From 3aacc652ba27d2dac418ff5aaa721842c1b6a1d0 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 22 Aug 2019 00:32:32 +0000 Subject: [PATCH 001/455] =?UTF-8?q?Bump=20version:=203.3.0=20=E2=86=92=203?= =?UTF-8?q?.4.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 189cc1466..a8038f476 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 3.3.0 +current_version = 3.4.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 6a157dcb2..f63100763 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '3.3.0' +__version__ = '3.4.0' diff --git a/setup.py b/setup.py index ecf71d6b2..ef4727eda 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ import os import sys -__version__ = '3.3.0' +__version__ = '3.4.0' if sys.argv[-1] == 'publish': # test server From 9f336d058de5b9d88759b4b2080d657915770276 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 17:42:18 -0400 Subject: [PATCH 002/455] feat(assistant): regenerate assistantv1 --- ibm_watson/assistant_v1.py | 3842 ++++++++++++++++++++++-------------- 1 file changed, 2307 insertions(+), 1535 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index f232c23a3..dafac2c9a 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,12 +19,12 @@ apps and your users. """ -from __future__ import absolute_import - import json from .common import get_sdk_headers +from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime +from ibm_cloud_sdk_core import get_authenticator_from_environment ############################################################################## # Service @@ -40,16 +40,8 @@ def __init__( self, version, url=default_url, - username=None, - password=None, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, + authenticator=None, + disable_ssl_verification=False, ): """ Construct a new client for the Assistant service. @@ -69,62 +61,21 @@ def __init__( "https://gateway.watsonplatform.net/assistant/api/assistant/api"). The base url may differ between IBM Cloud regions. - :param str username: The username used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str password: The password used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ + if not authenticator: + authenticator = get_authenticator_from_environment('Assistant') + BaseService.__init__( self, - vcap_services_name='conversation', url=url, - username=username, - password=password, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Assistant', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Assistant') self.version = version ######################### @@ -133,6 +84,7 @@ def __init__( def message(self, workspace_id, + *, input=None, intents=None, entities=None, @@ -152,22 +104,26 @@ def message(self, There is no rate limit for this operation. :param str workspace_id: Unique identifier of the workspace. - :param MessageInput input: An input object that includes the input text. - :param list[RuntimeIntent] intents: Intents to use when evaluating the user input. - Include intents from the previous response to continue using those intents rather - than trying to recognize intents in the new input. - :param list[RuntimeEntity] entities: Entities to use when evaluating the message. - Include entities from the previous response to continue using those entities - rather than detecting entities in the new input. - :param bool alternate_intents: Whether to return more than one intent. A value of - `true` indicates that all matching intents are returned. - :param Context context: State information for the conversation. To maintain state, - include the context from the previous response. - :param OutputData output: An output object that includes the response to the user, - the dialog nodes that were triggered, and messages from the log. - :param bool nodes_visited_details: Whether to include additional diagnostic - information about the dialog nodes that were visited during processing of the - message. + :param MessageInput input: (optional) An input object that includes the + input text. + :param list[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param list[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param bool alternate_intents: (optional) Whether to return more than one + intent. A value of `true` indicates that all matching intents are returned. + :param Context context: (optional) State information for the conversation. + To maintain state, include the context from the previous response. + :param OutputData output: (optional) An output object that includes the + response to the user, the dialog nodes that were triggered, and messages + from the log. + :param bool nodes_visited_details: (optional) Whether to include additional + diagnostic information about the dialog nodes that were visited during + processing of the message. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -208,13 +164,14 @@ def message(self, url = '/v1/workspaces/{0}/message'.format( *self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response ######################### @@ -222,8 +179,8 @@ def message(self, ######################### def list_workspaces(self, + *, page_limit=None, - include_count=None, sort=None, cursor=None, include_audit=None, @@ -235,14 +192,15 @@ def list_workspaces(self, This operation is limited to 500 requests per 30 minutes. For more information, see **Rate limiting**. - :param int page_limit: The number of records to return in each page of results. - :param bool include_count: Whether to include information about the number of - records returned. - :param str sort: The attribute by which returned workspaces will be sorted. To - reverse the sort order, prefix the value with a minus sign (`-`). - :param str cursor: A token identifying the page of results to retrieve. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param str sort: (optional) The attribute by which returned workspaces will + be sorted. To reverse the sort order, prefix the value with a minus sign + (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 @@ -257,22 +215,23 @@ def list_workspaces(self, params = { 'version': self.version, 'page_limit': page_limit, - 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit } url = '/v1/workspaces' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_workspace(self, + *, name=None, description=None, language=None, @@ -292,24 +251,26 @@ def create_workspace(self, This operation is limited to 30 requests per 30 minutes. For more information, see **Rate limiting**. - :param str name: The name of the workspace. This string cannot contain carriage - return, newline, or tab characters. - :param str description: The description of the workspace. This string cannot - contain carriage return, newline, or tab characters. - :param str language: The language of the workspace. - :param dict metadata: Any metadata related to the workspace. - :param bool learning_opt_out: Whether training data from the workspace (including - artifacts such as intents and entities) can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. - :param WorkspaceSystemSettings system_settings: Global settings for the workspace. - :param list[CreateIntent] intents: An array of objects defining the intents for - the workspace. - :param list[CreateEntity] entities: An array of objects describing the entities - for the workspace. - :param list[DialogNode] dialog_nodes: An array of objects describing the dialog - nodes in the workspace. - :param list[Counterexample] counterexamples: An array of objects defining input - examples that have been marked as irrelevant input. + :param str name: (optional) The name of the workspace. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the workspace. This + string cannot contain carriage return, newline, or tab characters. + :param str language: (optional) The language of the workspace. + :param dict metadata: (optional) Any metadata related to the workspace. + :param bool learning_opt_out: (optional) Whether training data from the + workspace (including artifacts such as intents and entities) can be used by + IBM for general service improvements. `true` indicates that workspace + training data is not to be used. + :param WorkspaceSystemSettings system_settings: (optional) Global settings + for the workspace. + :param list[CreateIntent] intents: (optional) An array of objects defining + the intents for the workspace. + :param list[CreateEntity] entities: (optional) An array of objects + describing the entities for the workspace. + :param list[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. + :param list[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -353,17 +314,19 @@ def create_workspace(self, } url = '/v1/workspaces' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_workspace(self, workspace_id, + *, export=None, include_audit=None, sort=None, @@ -377,15 +340,16 @@ def get_workspace(self, information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. - :param bool export: Whether to include all element content in the returned data. - If **export**=`false`, the returned data includes only information about the - element itself. If **export**=`true`, all content, including subelements, is - included. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. - :param str sort: Indicates how the returned workspace data will be sorted. This - parameter is valid only if **export**=`true`. Specify `sort=stable` to sort all - workspace objects by unique identifier, in ascending alphabetical order. + :param bool export: (optional) Whether to include all element content in + the returned data. If **export**=`false`, the returned data includes only + information about the element itself. If **export**=`true`, all content, + including subelements, is included. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param str sort: (optional) Indicates how the returned workspace data will + be sorted. This parameter is valid only if **export**=`true`. Specify + `sort=stable` to sort all workspace objects by unique identifier, in + ascending alphabetical order. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -408,16 +372,18 @@ def get_workspace(self, } url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_workspace(self, workspace_id, + *, name=None, description=None, language=None, @@ -439,33 +405,35 @@ def update_workspace(self, **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. - :param str name: The name of the workspace. This string cannot contain carriage - return, newline, or tab characters. - :param str description: The description of the workspace. This string cannot - contain carriage return, newline, or tab characters. - :param str language: The language of the workspace. - :param dict metadata: Any metadata related to the workspace. - :param bool learning_opt_out: Whether training data from the workspace (including - artifacts such as intents and entities) can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. - :param WorkspaceSystemSettings system_settings: Global settings for the workspace. - :param list[CreateIntent] intents: An array of objects defining the intents for - the workspace. - :param list[CreateEntity] entities: An array of objects describing the entities - for the workspace. - :param list[DialogNode] dialog_nodes: An array of objects describing the dialog - nodes in the workspace. - :param list[Counterexample] counterexamples: An array of objects defining input - examples that have been marked as irrelevant input. - :param bool append: 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. - 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 str name: (optional) The name of the workspace. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the workspace. This + string cannot contain carriage return, newline, or tab characters. + :param str language: (optional) The language of the workspace. + :param dict metadata: (optional) Any metadata related to the workspace. + :param bool learning_opt_out: (optional) Whether training data from the + workspace (including artifacts such as intents and entities) can be used by + IBM for general service improvements. `true` indicates that workspace + training data is not to be used. + :param WorkspaceSystemSettings system_settings: (optional) Global settings + for the workspace. + :param list[CreateIntent] intents: (optional) An array of objects defining + the intents for the workspace. + :param list[CreateEntity] entities: (optional) An array of objects + describing the entities for the workspace. + :param list[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. + :param list[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. + :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. + 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 dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -511,13 +479,14 @@ def update_workspace(self, } url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_workspace(self, workspace_id, **kwargs): @@ -546,12 +515,13 @@ def delete_workspace(self, workspace_id, **kwargs): params = {'version': self.version} url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -560,9 +530,9 @@ def delete_workspace(self, workspace_id, **kwargs): def list_intents(self, workspace_id, + *, export=None, page_limit=None, - include_count=None, sort=None, cursor=None, include_audit=None, @@ -576,18 +546,19 @@ def list_intents(self, more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. - :param bool export: Whether to include all element content in the returned data. - If **export**=`false`, the returned data includes only information about the - element itself. If **export**=`true`, all content, including subelements, is - included. - :param int page_limit: The number of records to return in each page of results. - :param bool include_count: Whether to include information about the number of - records returned. - :param str sort: The attribute by which returned intents will be sorted. To - reverse the sort order, prefix the value with a minus sign (`-`). - :param str cursor: A token identifying the page of results to retrieve. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param bool export: (optional) Whether to include all element content in + the returned data. If **export**=`false`, the returned data includes only + information about the element itself. If **export**=`true`, all content, + including subelements, is included. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param str sort: (optional) The attribute by which returned intents will be + sorted. To reverse the sort order, prefix the value with a minus sign + (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 @@ -606,7 +577,6 @@ def list_intents(self, 'version': self.version, 'export': export, 'page_limit': page_limit, - 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -614,17 +584,19 @@ def list_intents(self, url = '/v1/workspaces/{0}/intents'.format( *self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_intent(self, workspace_id, intent, + *, description=None, examples=None, **kwargs): @@ -639,13 +611,14 @@ def create_intent(self, :param str workspace_id: Unique identifier of the workspace. :param str intent: The name of the intent. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, underscore, hyphen, and dot - characters. - - It cannot begin with the reserved prefix `sys-`. - :param str description: The description of the intent. This string cannot contain - carriage return, newline, or tab characters. - :param list[Example] examples: An array of user input examples for the intent. + following restrictions: + - It can contain only Unicode alphanumeric, underscore, hyphen, and dot + characters. + - It cannot begin with the reserved prefix `sys-`. + :param str description: (optional) The description of the intent. This + string cannot contain carriage return, newline, or tab characters. + :param list[Example] examples: (optional) An array of user input examples + for the intent. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -674,18 +647,20 @@ def create_intent(self, url = '/v1/workspaces/{0}/intents'.format( *self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_intent(self, workspace_id, intent, + *, export=None, include_audit=None, **kwargs): @@ -699,12 +674,12 @@ def get_intent(self, :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. - :param bool export: Whether to include all element content in the returned data. - If **export**=`false`, the returned data includes only information about the - element itself. If **export**=`true`, all content, including subelements, is - included. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param bool export: (optional) Whether to include all element content in + the returned data. If **export**=`false`, the returned data includes only + information about the element itself. If **export**=`true`, all content, + including subelements, is included. + :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 @@ -729,17 +704,19 @@ def get_intent(self, url = '/v1/workspaces/{0}/intents/{1}'.format( *self._encode_path_vars(workspace_id, intent)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_intent(self, workspace_id, intent, + *, new_intent=None, new_description=None, new_examples=None, @@ -756,14 +733,15 @@ def update_intent(self, :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. - :param str new_intent: The name of the intent. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, underscore, hyphen, and dot - characters. - - It cannot begin with the reserved prefix `sys-`. - :param str new_description: The description of the intent. This string cannot - contain carriage return, newline, or tab characters. - :param list[Example] new_examples: An array of user input examples for the intent. + :param str new_intent: (optional) The name of the intent. This string must + conform to the following restrictions: + - It can contain only Unicode alphanumeric, underscore, hyphen, and dot + characters. + - It cannot begin with the reserved prefix `sys-`. + :param str new_description: (optional) The description of the intent. This + 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 dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -794,13 +772,14 @@ def update_intent(self, url = '/v1/workspaces/{0}/intents/{1}'.format( *self._encode_path_vars(workspace_id, intent)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_intent(self, workspace_id, intent, **kwargs): @@ -833,12 +812,13 @@ def delete_intent(self, workspace_id, intent, **kwargs): url = '/v1/workspaces/{0}/intents/{1}'.format( *self._encode_path_vars(workspace_id, intent)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -848,8 +828,8 @@ def delete_intent(self, workspace_id, intent, **kwargs): def list_examples(self, workspace_id, intent, + *, page_limit=None, - include_count=None, sort=None, cursor=None, include_audit=None, @@ -864,14 +844,15 @@ def list_examples(self, :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. - :param int page_limit: The number of records to return in each page of results. - :param bool include_count: Whether to include information about the number of - records returned. - :param str sort: The attribute by which returned examples will be sorted. To - reverse the sort order, prefix the value with a minus sign (`-`). - :param str cursor: A token identifying the page of results to retrieve. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param str sort: (optional) The attribute by which returned examples will + be sorted. To reverse the sort order, prefix the value with a minus sign + (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 @@ -891,7 +872,6 @@ def list_examples(self, params = { 'version': self.version, 'page_limit': page_limit, - 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -899,18 +879,20 @@ def list_examples(self, url = '/v1/workspaces/{0}/intents/{1}/examples'.format( *self._encode_path_vars(workspace_id, intent)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_example(self, workspace_id, intent, text, + *, mentions=None, **kwargs): """ @@ -924,11 +906,12 @@ def create_example(self, :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. - :param str text: The text of a user input example. 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 list[Mention] mentions: An array of contextual entity mentions. + :param str text: The text of a user input example. 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 list[Mention] mentions: (optional) An array of contextual entity + mentions. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -955,19 +938,21 @@ def create_example(self, url = '/v1/workspaces/{0}/intents/{1}/examples'.format( *self._encode_path_vars(workspace_id, intent)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_example(self, workspace_id, intent, text, + *, include_audit=None, **kwargs): """ @@ -980,8 +965,8 @@ def get_example(self, :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. :param str text: The text of the user input example. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :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 @@ -1004,18 +989,20 @@ def get_example(self, url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( *self._encode_path_vars(workspace_id, intent, text)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_example(self, workspace_id, intent, text, + *, new_text=None, new_mentions=None, **kwargs): @@ -1031,11 +1018,12 @@ def update_example(self, :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. :param str text: The text of the user input example. - :param str new_text: The text of the user input example. 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 list[Mention] new_mentions: An array of contextual entity mentions. + :param str new_text: (optional) The text of the user input example. 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 list[Mention] new_mentions: (optional) An array of contextual entity + mentions. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1064,13 +1052,14 @@ def update_example(self, url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( *self._encode_path_vars(workspace_id, intent, text)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_example(self, workspace_id, intent, text, **kwargs): @@ -1106,12 +1095,13 @@ def delete_example(self, workspace_id, intent, text, **kwargs): url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( *self._encode_path_vars(workspace_id, intent, text)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -1120,8 +1110,8 @@ def delete_example(self, workspace_id, intent, text, **kwargs): def list_counterexamples(self, workspace_id, + *, page_limit=None, - include_count=None, sort=None, cursor=None, include_audit=None, @@ -1135,14 +1125,15 @@ def list_counterexamples(self, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. - :param int page_limit: The number of records to return in each page of results. - :param bool include_count: Whether to include information about the number of - records returned. - :param str sort: The attribute by which returned counterexamples will be sorted. - To reverse the sort order, prefix the value with a minus sign (`-`). - :param str cursor: A token identifying the page of results to retrieve. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param str sort: (optional) The attribute by which returned counterexamples + will be sorted. To reverse the sort order, prefix the value with a minus + sign (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 @@ -1161,7 +1152,6 @@ def list_counterexamples(self, params = { 'version': self.version, 'page_limit': page_limit, - 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -1169,12 +1159,13 @@ def list_counterexamples(self, url = '/v1/workspaces/{0}/counterexamples'.format( *self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_counterexample(self, workspace_id, text, **kwargs): @@ -1189,10 +1180,10 @@ def create_counterexample(self, workspace_id, text, **kwargs): see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. - :param str text: The text of a user input marked as 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 str text: The text of a user input marked as 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 dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1216,18 +1207,20 @@ def create_counterexample(self, workspace_id, text, **kwargs): url = '/v1/workspaces/{0}/counterexamples'.format( *self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_counterexample(self, workspace_id, text, + *, include_audit=None, **kwargs): """ @@ -1239,10 +1232,10 @@ def get_counterexample(self, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. - :param str text: The text of a user input counterexample (for example, `What are - you wearing?`). - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param str text: The text of a user input counterexample (for example, + `What are you wearing?`). + :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 @@ -1264,15 +1257,20 @@ def get_counterexample(self, url = '/v1/workspaces/{0}/counterexamples/{1}'.format( *self._encode_path_vars(workspace_id, text)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response - def update_counterexample(self, workspace_id, text, new_text=None, + def update_counterexample(self, + workspace_id, + text, + *, + new_text=None, **kwargs): """ Update counterexample. @@ -1285,12 +1283,12 @@ def update_counterexample(self, workspace_id, text, new_text=None, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. - :param str text: The text of a user input counterexample (for example, `What are - you wearing?`). - :param str new_text: The text of a user input marked as 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 str text: The text of a user input counterexample (for example, + `What are you wearing?`). + :param str new_text: (optional) The text of a user input marked as + 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 dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1314,13 +1312,14 @@ def update_counterexample(self, workspace_id, text, new_text=None, url = '/v1/workspaces/{0}/counterexamples/{1}'.format( *self._encode_path_vars(workspace_id, text)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_counterexample(self, workspace_id, text, **kwargs): @@ -1333,8 +1332,8 @@ def delete_counterexample(self, workspace_id, text, **kwargs): see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. - :param str text: The text of a user input counterexample (for example, `What are - you wearing?`). + :param str text: The text of a user input counterexample (for example, + `What are you wearing?`). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1356,12 +1355,13 @@ def delete_counterexample(self, workspace_id, text, **kwargs): url = '/v1/workspaces/{0}/counterexamples/{1}'.format( *self._encode_path_vars(workspace_id, text)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -1370,9 +1370,9 @@ def delete_counterexample(self, workspace_id, text, **kwargs): def list_entities(self, workspace_id, + *, export=None, page_limit=None, - include_count=None, sort=None, cursor=None, include_audit=None, @@ -1386,18 +1386,19 @@ def list_entities(self, more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. - :param bool export: Whether to include all element content in the returned data. - If **export**=`false`, the returned data includes only information about the - element itself. If **export**=`true`, all content, including subelements, is - included. - :param int page_limit: The number of records to return in each page of results. - :param bool include_count: Whether to include information about the number of - records returned. - :param str sort: The attribute by which returned entities will be sorted. To - reverse the sort order, prefix the value with a minus sign (`-`). - :param str cursor: A token identifying the page of results to retrieve. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param bool export: (optional) Whether to include all element content in + the returned data. If **export**=`false`, the returned data includes only + information about the element itself. If **export**=`true`, all content, + including subelements, is included. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param str sort: (optional) The attribute by which returned entities will + be sorted. To reverse the sort order, prefix the value with a minus sign + (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 @@ -1416,7 +1417,6 @@ def list_entities(self, 'version': self.version, 'export': export, 'page_limit': page_limit, - 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -1424,17 +1424,19 @@ def list_entities(self, url = '/v1/workspaces/{0}/entities'.format( *self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_entity(self, workspace_id, entity, + *, description=None, metadata=None, fuzzy_match=None, @@ -1451,16 +1453,19 @@ def create_entity(self, :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - - If you specify an entity name beginning with the reserved prefix `sys-`, it must - be the name of a system entity that you want to enable. (Any entity content - specified with the request is ignored.). - :param str description: The description of the entity. This string cannot contain - carriage return, newline, or tab characters. - :param dict metadata: Any metadata related to the entity. - :param bool fuzzy_match: Whether to use fuzzy matching for the entity. - :param list[CreateValue] values: An array of objects describing the entity values. + following restrictions: + - It can contain only Unicode alphanumeric, underscore, and hyphen + characters. + - If you specify an entity name beginning with the reserved prefix `sys-`, + it must be the name of a system entity that you want to enable. (Any entity + content specified with the request is ignored.). + :param str description: (optional) The description of the entity. This + string cannot contain carriage return, newline, or tab characters. + :param dict metadata: (optional) Any metadata related to the entity. + :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the + entity. + :param list[CreateValue] values: (optional) An array of objects describing + the entity values. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1491,18 +1496,20 @@ def create_entity(self, url = '/v1/workspaces/{0}/entities'.format( *self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_entity(self, workspace_id, entity, + *, export=None, include_audit=None, **kwargs): @@ -1516,12 +1523,12 @@ def get_entity(self, :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. - :param bool export: Whether to include all element content in the returned data. - If **export**=`false`, the returned data includes only information about the - element itself. If **export**=`true`, all content, including subelements, is - included. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param bool export: (optional) Whether to include all element content in + the returned data. If **export**=`false`, the returned data includes only + information about the element itself. If **export**=`true`, all content, + including subelements, is included. + :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 @@ -1546,17 +1553,19 @@ def get_entity(self, url = '/v1/workspaces/{0}/entities/{1}'.format( *self._encode_path_vars(workspace_id, entity)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_entity(self, workspace_id, entity, + *, new_entity=None, new_description=None, new_metadata=None, @@ -1575,16 +1584,18 @@ def update_entity(self, :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. - :param str new_entity: The name of the entity. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - - It cannot begin with the reserved prefix `sys-`. - :param str new_description: The description of the entity. This string cannot - contain carriage return, newline, or tab characters. - :param dict new_metadata: Any metadata related to the entity. - :param bool new_fuzzy_match: Whether to use fuzzy matching for the entity. - :param list[CreateValue] new_values: An array of objects describing the entity - values. + :param str new_entity: (optional) The name of the entity. This string must + conform to the following restrictions: + - It can contain only Unicode alphanumeric, underscore, and hyphen + characters. + - It cannot begin with the reserved prefix `sys-`. + :param str new_description: (optional) The description of the entity. This + string cannot contain carriage return, newline, or tab characters. + :param dict new_metadata: (optional) Any metadata related to the entity. + :param bool new_fuzzy_match: (optional) Whether to use fuzzy matching for + the entity. + :param list[CreateValue] new_values: (optional) An array of objects + describing the entity values. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1617,13 +1628,14 @@ def update_entity(self, url = '/v1/workspaces/{0}/entities/{1}'.format( *self._encode_path_vars(workspace_id, entity)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_entity(self, workspace_id, entity, **kwargs): @@ -1656,12 +1668,13 @@ def delete_entity(self, workspace_id, entity, **kwargs): url = '/v1/workspaces/{0}/entities/{1}'.format( *self._encode_path_vars(workspace_id, entity)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -1671,6 +1684,7 @@ def delete_entity(self, workspace_id, entity, **kwargs): def list_mentions(self, workspace_id, entity, + *, export=None, include_audit=None, **kwargs): @@ -1684,12 +1698,12 @@ def list_mentions(self, :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. - :param bool export: Whether to include all element content in the returned data. - If **export**=`false`, the returned data includes only information about the - element itself. If **export**=`true`, all content, including subelements, is - included. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param bool export: (optional) Whether to include all element content in + the returned data. If **export**=`false`, the returned data includes only + information about the element itself. If **export**=`true`, all content, + including subelements, is included. + :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 @@ -1714,12 +1728,13 @@ def list_mentions(self, url = '/v1/workspaces/{0}/entities/{1}/mentions'.format( *self._encode_path_vars(workspace_id, entity)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -1729,9 +1744,9 @@ def list_mentions(self, def list_values(self, workspace_id, entity, + *, export=None, page_limit=None, - include_count=None, sort=None, cursor=None, include_audit=None, @@ -1745,18 +1760,19 @@ def list_values(self, :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. - :param bool export: Whether to include all element content in the returned data. - If **export**=`false`, the returned data includes only information about the - element itself. If **export**=`true`, all content, including subelements, is - included. - :param int page_limit: The number of records to return in each page of results. - :param bool include_count: Whether to include information about the number of - records returned. - :param str sort: The attribute by which returned entity values will be sorted. To - reverse the sort order, prefix the value with a minus sign (`-`). - :param str cursor: A token identifying the page of results to retrieve. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param bool export: (optional) Whether to include all element content in + the returned data. If **export**=`false`, the returned data includes only + information about the element itself. If **export**=`true`, all content, + including subelements, is included. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param str sort: (optional) The attribute by which returned entity values + will be sorted. To reverse the sort order, prefix the value with a minus + sign (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 @@ -1777,7 +1793,6 @@ def list_values(self, 'version': self.version, 'export': export, 'page_limit': page_limit, - 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -1785,20 +1800,22 @@ def list_values(self, url = '/v1/workspaces/{0}/entities/{1}/values'.format( *self._encode_path_vars(workspace_id, entity)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_value(self, workspace_id, entity, value, + *, metadata=None, - value_type=None, + type=None, synonyms=None, patterns=None, **kwargs): @@ -1813,22 +1830,23 @@ def create_value(self, :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. - :param str value: The text of the entity value. 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 dict metadata: Any metadata related to the entity value. - :param str value_type: Specifies the type of entity value. - :param list[str] synonyms: An array of synonyms for the entity value. A value can - specify either synonyms or patterns (depending on the value type), but not both. A - synonym must conform to the following resrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - :param list[str] patterns: An array of patterns for the 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). + :param str value: The text of the entity value. 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 dict metadata: (optional) Any metadata related to the entity value. + :param str type: (optional) Specifies the type of entity value. + :param list[str] synonyms: (optional) An array of synonyms for the entity + value. A value can specify either synonyms or patterns (depending on the + value type), but not both. A synonym must conform to the following + resrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + :param list[str] patterns: (optional) An array of patterns for the 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). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1852,26 +1870,28 @@ def create_value(self, data = { 'value': value, 'metadata': metadata, - 'type': value_type, + 'type': type, 'synonyms': synonyms, 'patterns': patterns } url = '/v1/workspaces/{0}/entities/{1}/values'.format( *self._encode_path_vars(workspace_id, entity)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_value(self, workspace_id, entity, value, + *, export=None, include_audit=None, **kwargs): @@ -1885,12 +1905,12 @@ def get_value(self, :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. :param str value: The text of the entity value. - :param bool export: Whether to include all element content in the returned data. - If **export**=`false`, the returned data includes only information about the - element itself. If **export**=`true`, all content, including subelements, is - included. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param bool export: (optional) Whether to include all element content in + the returned data. If **export**=`false`, the returned data includes only + information about the element itself. If **export**=`true`, all content, + including subelements, is included. + :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 @@ -1917,21 +1937,23 @@ def get_value(self, url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( *self._encode_path_vars(workspace_id, entity, value)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_value(self, workspace_id, entity, value, + *, new_value=None, new_metadata=None, - new_value_type=None, + new_type=None, new_synonyms=None, new_patterns=None, **kwargs): @@ -1948,22 +1970,24 @@ def update_value(self, :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. :param str value: The text of the entity value. - :param str new_value: The text of the entity value. 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 dict new_metadata: Any metadata related to the entity value. - :param str new_value_type: Specifies the type of entity value. - :param list[str] new_synonyms: An array of synonyms for the entity value. A value - can specify either synonyms or patterns (depending on the value type), but not - both. A synonym must conform to the following resrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - :param list[str] new_patterns: An array of patterns for the 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). + :param str new_value: (optional) The text of the entity value. 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 dict new_metadata: (optional) Any metadata related to the entity + value. + :param str new_type: (optional) Specifies the type of entity value. + :param list[str] new_synonyms: (optional) An array of synonyms for the + entity value. A value can specify either synonyms or patterns (depending on + the value type), but not both. A synonym must conform to the following + resrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + :param list[str] new_patterns: (optional) An array of patterns for the + 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). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1987,20 +2011,21 @@ def update_value(self, data = { 'value': new_value, 'metadata': new_metadata, - 'type': new_value_type, + 'type': new_type, 'synonyms': new_synonyms, 'patterns': new_patterns } url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( *self._encode_path_vars(workspace_id, entity, value)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_value(self, workspace_id, entity, value, **kwargs): @@ -2036,12 +2061,13 @@ def delete_value(self, workspace_id, entity, value, **kwargs): url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( *self._encode_path_vars(workspace_id, entity, value)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -2052,8 +2078,8 @@ def list_synonyms(self, workspace_id, entity, value, + *, page_limit=None, - include_count=None, sort=None, cursor=None, include_audit=None, @@ -2068,14 +2094,15 @@ def list_synonyms(self, :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. :param str value: The text of the entity value. - :param int page_limit: The number of records to return in each page of results. - :param bool include_count: Whether to include information about the number of - records returned. - :param str sort: The attribute by which returned entity value synonyms will be - sorted. To reverse the sort order, prefix the value with a minus sign (`-`). - :param str cursor: A token identifying the page of results to retrieve. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param str sort: (optional) The attribute by which returned entity value + synonyms will be sorted. To reverse the sort order, prefix the value with a + minus sign (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 @@ -2097,7 +2124,6 @@ def list_synonyms(self, params = { 'version': self.version, 'page_limit': page_limit, - 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -2105,12 +2131,13 @@ def list_synonyms(self, url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( *self._encode_path_vars(workspace_id, entity, value)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_synonym(self, workspace_id, entity, value, synonym, **kwargs): @@ -2127,10 +2154,10 @@ def create_synonym(self, workspace_id, entity, value, synonym, **kwargs): :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. :param str value: The text of the entity value. - :param str synonym: The text of the synonym. 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 str synonym: The text of the synonym. 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 dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2157,13 +2184,14 @@ def create_synonym(self, workspace_id, entity, value, synonym, **kwargs): url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( *self._encode_path_vars(workspace_id, entity, value)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_synonym(self, @@ -2171,6 +2199,7 @@ def get_synonym(self, entity, value, synonym, + *, include_audit=None, **kwargs): """ @@ -2184,8 +2213,8 @@ def get_synonym(self, :param str entity: The name of the entity. :param str value: The text of the entity value. :param str synonym: The text of the synonym. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :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 @@ -2210,12 +2239,13 @@ def get_synonym(self, url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( *self._encode_path_vars(workspace_id, entity, value, synonym)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_synonym(self, @@ -2223,6 +2253,7 @@ def update_synonym(self, entity, value, synonym, + *, new_synonym=None, **kwargs): """ @@ -2239,10 +2270,10 @@ def update_synonym(self, :param str entity: The name of the entity. :param str value: The text of the entity value. :param str synonym: The text of the synonym. - :param str new_synonym: The text of the synonym. 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 str new_synonym: (optional) The text of the synonym. 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 dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2269,13 +2300,14 @@ def update_synonym(self, url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( *self._encode_path_vars(workspace_id, entity, value, synonym)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): @@ -2314,12 +2346,13 @@ def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( *self._encode_path_vars(workspace_id, entity, value, synonym)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -2328,8 +2361,8 @@ def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): def list_dialog_nodes(self, workspace_id, + *, page_limit=None, - include_count=None, sort=None, cursor=None, include_audit=None, @@ -2342,14 +2375,15 @@ def list_dialog_nodes(self, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. - :param int page_limit: The number of records to return in each page of results. - :param bool include_count: Whether to include information about the number of - records returned. - :param str sort: The attribute by which returned dialog nodes will be sorted. To - reverse the sort order, prefix the value with a minus sign (`-`). - :param str cursor: A token identifying the page of results to retrieve. - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param str sort: (optional) The attribute by which returned dialog nodes + will be sorted. To reverse the sort order, prefix the value with a minus + sign (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 @@ -2367,7 +2401,6 @@ def list_dialog_nodes(self, params = { 'version': self.version, 'page_limit': page_limit, - 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -2375,17 +2408,19 @@ def list_dialog_nodes(self, url = '/v1/workspaces/{0}/dialog_nodes'.format( *self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_dialog_node(self, workspace_id, dialog_node, + *, description=None, conditions=None, parent=None, @@ -2395,7 +2430,7 @@ def create_dialog_node(self, metadata=None, next_step=None, title=None, - node_type=None, + type=None, event_name=None, variable=None, actions=None, @@ -2415,40 +2450,44 @@ def create_dialog_node(self, :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot - characters. - :param str description: The description of the dialog node. This string cannot - contain carriage return, newline, or tab characters. - :param str conditions: The condition that will trigger the dialog node. This - string cannot contain carriage return, newline, or tab characters. - :param str parent: The ID of the parent dialog node. This property is omitted if - the dialog node has no parent. - :param str previous_sibling: The ID of the previous sibling dialog node. This - property is omitted if the dialog node has no previous sibling. - :param DialogNodeOutput output: 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). - :param dict context: The context for the dialog node. - :param dict metadata: The metadata for the dialog node. - :param DialogNodeNextStep next_step: The next step to execute following this - dialog node. - :param str title: The alias used to identify the dialog node. This string must - conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot - characters. - :param str node_type: How the dialog node is processed. - :param str event_name: How an `event_handler` node is processed. - :param str variable: The location in the dialog context where output is stored. - :param list[DialogNodeAction] actions: An array of objects describing any actions - to be invoked by the dialog node. - :param str digress_in: Whether this top-level dialog node can be digressed into. - :param str digress_out: Whether this dialog node can be returned to after a - digression. - :param str digress_out_slots: Whether the user can digress to top-level nodes - while filling out slots. - :param str user_label: A label that can be displayed externally to describe the - purpose of the node to users. + following restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and + dot characters. + :param str description: (optional) The description of the dialog node. This + string cannot contain carriage return, newline, or tab characters. + :param str conditions: (optional) The condition that will trigger the + dialog node. This string cannot contain carriage return, newline, or tab + characters. + :param str parent: (optional) The ID of the parent dialog node. This + property is omitted if the dialog node has no parent. + :param str previous_sibling: (optional) The ID of the previous sibling + dialog node. This property is omitted if the dialog node has no previous + 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). + :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 + following this dialog node. + :param str title: (optional) The alias used to identify the dialog node. + This string must conform to the following restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and + dot characters. + :param str type: (optional) How the dialog node is processed. + :param str event_name: (optional) How an `event_handler` node is processed. + :param str variable: (optional) The location in the dialog context where + output is stored. + :param list[DialogNodeAction] actions: (optional) An array of objects + describing any actions to be invoked by the dialog node. + :param str digress_in: (optional) Whether this top-level dialog node can be + digressed into. + :param str digress_out: (optional) Whether this dialog node can be returned + to after a digression. + :param str digress_out_slots: (optional) Whether the user can digress to + top-level nodes while filling out slots. + :param str user_label: (optional) A label that can be displayed externally + to describe the purpose of the node to users. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2487,7 +2526,7 @@ def create_dialog_node(self, 'metadata': metadata, 'next_step': next_step, 'title': title, - 'type': node_type, + 'type': type, 'event_name': event_name, 'variable': variable, 'actions': actions, @@ -2499,18 +2538,20 @@ def create_dialog_node(self, url = '/v1/workspaces/{0}/dialog_nodes'.format( *self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_dialog_node(self, workspace_id, dialog_node, + *, include_audit=None, **kwargs): """ @@ -2522,8 +2563,8 @@ def get_dialog_node(self, :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID (for example, `get_order`). - :param bool include_audit: Whether to include the audit properties (`created` and - `updated` timestamps) in the response. + :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 @@ -2544,17 +2585,19 @@ def get_dialog_node(self, url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( *self._encode_path_vars(workspace_id, dialog_node)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_dialog_node(self, workspace_id, dialog_node, + *, new_dialog_node=None, new_description=None, new_conditions=None, @@ -2565,7 +2608,7 @@ def update_dialog_node(self, new_metadata=None, new_next_step=None, new_title=None, - new_node_type=None, + new_type=None, new_event_name=None, new_variable=None, new_actions=None, @@ -2585,43 +2628,46 @@ def update_dialog_node(self, :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID (for example, `get_order`). - :param str new_dialog_node: The dialog node ID. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot - characters. - :param str new_description: The description of the dialog node. This string cannot - contain carriage return, newline, or tab characters. - :param str new_conditions: The condition that will trigger the dialog node. This - string cannot contain carriage return, newline, or tab characters. - :param str new_parent: The ID of the parent dialog node. This property is omitted - if the dialog node has no parent. - :param str new_previous_sibling: The ID of the previous sibling dialog node. This - property is omitted if the dialog node has no previous sibling. - :param DialogNodeOutput new_output: 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). - :param dict new_context: The context for the dialog node. - :param dict new_metadata: The metadata for the dialog node. - :param DialogNodeNextStep new_next_step: The next step to execute following this - dialog node. - :param str new_title: The alias used to identify the dialog node. This string must - conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot - characters. - :param str new_node_type: How the dialog node is processed. - :param str new_event_name: How an `event_handler` node is processed. - :param str new_variable: The location in the dialog context where output is - stored. - :param list[DialogNodeAction] new_actions: An array of objects describing any - actions to be invoked by the dialog node. - :param str new_digress_in: Whether this top-level dialog node can be digressed - into. - :param str new_digress_out: Whether this dialog node can be returned to after a - digression. - :param str new_digress_out_slots: Whether the user can digress to top-level nodes - while filling out slots. - :param str new_user_label: A label that can be displayed externally to describe - the purpose of the node to users. + :param str new_dialog_node: (optional) The dialog node ID. This string must + conform to the following restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and + dot characters. + :param str new_description: (optional) The description of the dialog node. + This string cannot contain carriage return, newline, or tab characters. + :param str new_conditions: (optional) The condition that will trigger the + dialog node. This string cannot contain carriage return, newline, or tab + characters. + :param str new_parent: (optional) The ID of the parent dialog node. This + property is omitted if the dialog node has no parent. + :param str new_previous_sibling: (optional) The ID of the previous sibling + dialog node. This property is omitted if the dialog node has no previous + 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). + :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 + execute following this dialog node. + :param str new_title: (optional) The alias used to identify the dialog + node. This string must conform to the following restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and + dot characters. + :param str new_type: (optional) How the dialog node is processed. + :param str new_event_name: (optional) How an `event_handler` node is + processed. + :param str new_variable: (optional) The location in the dialog context + where output is stored. + :param list[DialogNodeAction] new_actions: (optional) An array of objects + describing any actions to be invoked by the dialog node. + :param str new_digress_in: (optional) Whether this top-level dialog node + can be digressed into. + :param str new_digress_out: (optional) Whether this dialog node can be + returned to after a digression. + :param str new_digress_out_slots: (optional) Whether the user can digress + to top-level nodes while filling out slots. + :param str new_user_label: (optional) A label that can be displayed + externally to describe the purpose of the node to users. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2661,7 +2707,7 @@ def update_dialog_node(self, 'metadata': new_metadata, 'next_step': new_next_step, 'title': new_title, - 'type': new_node_type, + 'type': new_type, 'event_name': new_event_name, 'variable': new_variable, 'actions': new_actions, @@ -2673,13 +2719,14 @@ def update_dialog_node(self, url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( *self._encode_path_vars(workspace_id, dialog_node)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): @@ -2713,12 +2760,13 @@ def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( *self._encode_path_vars(workspace_id, dialog_node)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -2727,6 +2775,7 @@ def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): def list_logs(self, workspace_id, + *, sort=None, filter=None, page_limit=None, @@ -2741,14 +2790,16 @@ def list_logs(self, more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. - :param str sort: 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 (`-`). - :param str filter: 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). - :param int page_limit: The number of records to return in each page of results. - :param str cursor: A token identifying the page of results to retrieve. + :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 (`-`). + :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). + :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 + retrieve. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2773,16 +2824,18 @@ def list_logs(self, url = '/v1/workspaces/{0}/logs'.format( *self._encode_path_vars(workspace_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def list_all_logs(self, filter, + *, sort=None, page_limit=None, cursor=None, @@ -2795,16 +2848,18 @@ def list_all_logs(self, minutes. If **cursor** is specified, the limit is 120 requests per minute. For more information, see **Rate limiting**. - :param str filter: A cacheable parameter that limits the results to those matching - the specified filter. You must specify a filter query that includes a value for - `language`, as well as a value for `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). - :param str sort: 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 (`-`). - :param int page_limit: The number of records to return in each page of results. - :param str cursor: A token identifying the page of results to retrieve. + :param str filter: A cacheable parameter that limits the results to those + matching the specified filter. You must specify a filter query that + includes a value for `language`, as well as a value for `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). + :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 (`-`). + :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 + retrieve. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2828,12 +2883,13 @@ def list_all_logs(self, } url = '/v1/logs' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -2851,7 +2907,8 @@ def delete_user_data(self, customer_id, **kwargs): customer IDs, see [Information security](https://cloud.ibm.com/docs/services/assistant?topic=assistant-information-security#information-security). - :param str customer_id: The customer ID for which all data is to be deleted. + :param str customer_id: The customer ID for which all data is to be + deleted. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2869,15 +2926,115 @@ def delete_user_data(self, customer_id, **kwargs): params = {'version': self.version, 'customer_id': customer_id} url = '/v1/user_data' - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response +class ListWorkspacesEnums(object): + + class Sort(Enum): + """ + The attribute by which returned workspaces will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + NAME = 'name' + UPDATED = 'updated' + + +class GetWorkspaceEnums(object): + + class Sort(Enum): + """ + Indicates how the returned workspace data will be sorted. This parameter is valid + only if **export**=`true`. Specify `sort=stable` to sort all workspace objects by + unique identifier, in ascending alphabetical order. + """ + STABLE = 'stable' + + +class ListIntentsEnums(object): + + class Sort(Enum): + """ + The attribute by which returned intents will be sorted. To reverse the sort order, + prefix the value with a minus sign (`-`). + """ + INTENT = 'intent' + UPDATED = 'updated' + + +class ListExamplesEnums(object): + + class Sort(Enum): + """ + The attribute by which returned examples will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + TEXT = 'text' + UPDATED = 'updated' + + +class ListCounterexamplesEnums(object): + + class Sort(Enum): + """ + The attribute by which returned counterexamples will be sorted. To reverse the + sort order, prefix the value with a minus sign (`-`). + """ + TEXT = 'text' + UPDATED = 'updated' + + +class ListEntitiesEnums(object): + + class Sort(Enum): + """ + The attribute by which returned entities will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + ENTITY = 'entity' + UPDATED = 'updated' + + +class ListValuesEnums(object): + + class Sort(Enum): + """ + The attribute by which returned entity values will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + VALUE = 'value' + UPDATED = 'updated' + + +class ListSynonymsEnums(object): + + class Sort(Enum): + """ + The attribute by which returned entity value synonyms will be sorted. To reverse + the sort order, prefix the value with a minus sign (`-`). + """ + SYNONYM = 'synonym' + UPDATED = 'updated' + + +class ListDialogNodesEnums(object): + + class Sort(Enum): + """ + The attribute by which returned dialog nodes will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + DIALOG_NODE = 'dialog_node' + UPDATED = 'updated' + + ############################################################################## # Models ############################################################################## @@ -2888,17 +3045,17 @@ class CaptureGroup(object): A recognized capture group for a pattern-based entity. :attr str group: A recognized capture group for the entity. - :attr list[int] location: (optional) Zero-based character offsets that indicate where - the entity value begins and ends in the input text. + :attr list[int] location: (optional) Zero-based character offsets that indicate + where the entity value begins and ends in the input text. """ - def __init__(self, group, location=None): + def __init__(self, group, *, location=None): """ Initialize a CaptureGroup object. :param str group: A recognized capture group for the entity. - :param list[int] location: (optional) Zero-based character offsets that indicate - where the entity value begins and ends in the input text. + :param list[int] location: (optional) Zero-based character offsets that + indicate where the entity value begins and ends in the input text. """ self.group = group self.location = location @@ -2953,10 +3110,12 @@ class Context(object): :attr str conversation_id: (optional) The unique identifier of the conversation. :attr SystemResponse system: (optional) For internal use only. - :attr MessageContextMetadata metadata: (optional) Metadata related to the message. + :attr MessageContextMetadata metadata: (optional) Metadata related to the + message. """ def __init__(self, + *, conversation_id=None, system=None, metadata=None, @@ -2964,10 +3123,11 @@ def __init__(self, """ Initialize a Context object. - :param str conversation_id: (optional) The unique identifier of the conversation. + :param str conversation_id: (optional) The unique identifier of the + conversation. :param SystemResponse system: (optional) For internal use only. :param MessageContextMetadata metadata: (optional) Metadata related to the - message. + message. :param **kwargs: (optional) Any additional properties. """ self.conversation_id = conversation_id @@ -3038,26 +3198,27 @@ class Counterexample(object): """ Counterexample. - :attr str text: The text of a user input marked as 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. + :attr str text: The text of a user input marked as 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. :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. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. """ - def __init__(self, text, created=None, updated=None): + def __init__(self, text, *, created=None, updated=None): """ Initialize a Counterexample object. - :param str text: The text of a user input marked as 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 datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. + :param str text: The text of a user input marked as 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 datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. """ self.text = text self.created = created @@ -3115,7 +3276,7 @@ class CounterexampleCollection(object): CounterexampleCollection. :attr list[Counterexample] counterexamples: An array of objects describing the - examples marked as irrelevant input. + examples marked as irrelevant input. :attr Pagination pagination: The pagination data for the returned objects. """ @@ -3123,8 +3284,8 @@ def __init__(self, counterexamples, pagination): """ Initialize a CounterexampleCollection object. - :param list[Counterexample] counterexamples: An array of objects describing the - examples marked as irrelevant input. + :param list[Counterexample] counterexamples: An array of objects describing + the examples marked as irrelevant input. :param Pagination pagination: The pagination data for the returned objects. """ self.counterexamples = counterexamples @@ -3188,25 +3349,26 @@ class CreateEntity(object): """ CreateEntity. - :attr str entity: The name of the entity. This string must conform to the following - restrictions: - - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - - If you specify an entity name beginning with the reserved prefix `sys-`, it must be - the name of a system entity that you want to enable. (Any entity content specified - with the request is ignored.). - :attr str description: (optional) The description of the entity. This string cannot - contain carriage return, newline, or tab characters. + :attr str entity: The name of the entity. This string must conform to the + following restrictions: + - It can contain only Unicode alphanumeric, underscore, and hyphen characters. + - If you specify an entity name beginning with the reserved prefix `sys-`, it + must be the name of a system entity that you want to enable. (Any entity content + specified with the request is ignored.). + :attr str description: (optional) The description of the entity. This string + cannot contain carriage return, newline, or tab characters. :attr dict metadata: (optional) Any metadata related to the entity. :attr bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. :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. - :attr list[CreateValue] values: (optional) An array of objects describing the entity - values. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. + :attr list[CreateValue] values: (optional) An array of objects describing the + entity values. """ def __init__(self, entity, + *, description=None, metadata=None, fuzzy_match=None, @@ -3217,20 +3379,23 @@ def __init__(self, Initialize a CreateEntity object. :param str entity: The name of the entity. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - - If you specify an entity name beginning with the reserved prefix `sys-`, it must - be the name of a system entity that you want to enable. (Any entity content - specified with the request is ignored.). - :param str description: (optional) The description of the entity. This string - cannot contain carriage return, newline, or tab characters. + following restrictions: + - It can contain only Unicode alphanumeric, underscore, and hyphen + characters. + - If you specify an entity name beginning with the reserved prefix `sys-`, + it must be the name of a system entity that you want to enable. (Any entity + content specified with the request is ignored.). + :param str description: (optional) The description of the entity. This + string cannot contain carriage return, newline, or tab characters. :param dict metadata: (optional) Any metadata related to the entity. - :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. - :param list[CreateValue] values: (optional) An array of objects describing the - entity values. + :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the + entity. + :param datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. + :param list[CreateValue] values: (optional) An array of objects describing + the entity values. """ self.entity = entity self.description = description @@ -3312,21 +3477,23 @@ class CreateIntent(object): """ CreateIntent. - :attr str intent: The name of the intent. This string must conform to the following - restrictions: - - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - - It cannot begin with the reserved prefix `sys-`. - :attr str description: (optional) The description of the intent. This string cannot - contain carriage return, newline, or tab characters. + :attr str intent: The name of the intent. This string must conform to the + following restrictions: + - It can contain only Unicode alphanumeric, underscore, hyphen, and dot + characters. + - It cannot begin with the reserved prefix `sys-`. + :attr str description: (optional) The description of the intent. This string + cannot contain carriage return, newline, or tab characters. :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. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. :attr list[Example] examples: (optional) An array of user input examples for the - intent. + intent. """ def __init__(self, intent, + *, description=None, created=None, updated=None, @@ -3335,17 +3502,18 @@ def __init__(self, Initialize a CreateIntent object. :param str intent: The name of the intent. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, underscore, hyphen, and dot - characters. - - It cannot begin with the reserved prefix `sys-`. - :param str description: (optional) The description of the intent. This string - cannot contain carriage return, newline, or tab characters. - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. - :param list[Example] examples: (optional) An array of user input examples for the - intent. + following restrictions: + - It can contain only Unicode alphanumeric, underscore, hyphen, and dot + characters. + - It cannot begin with the reserved prefix `sys-`. + :param str description: (optional) The description of the intent. This + string cannot contain carriage return, newline, or tab characters. + :param datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. + :param list[Example] examples: (optional) An array of user input examples + for the intent. """ self.intent = intent self.description = description @@ -3415,30 +3583,31 @@ class CreateValue(object): CreateValue. :attr str value: The text of the entity value. This string must conform to the - following restrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. + following restrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. :attr dict metadata: (optional) Any metadata related to the entity value. - :attr str value_type: (optional) Specifies the type of entity value. - :attr list[str] synonyms: (optional) An array of synonyms for the entity value. A - value can specify either synonyms or patterns (depending on the value type), but not - both. A synonym must conform to the following resrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - :attr list[str] patterns: (optional) An array of patterns for the 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). + :attr str type: (optional) Specifies the type of entity value. + :attr list[str] synonyms: (optional) An array of synonyms for the entity value. + A value can specify either synonyms or patterns (depending on the value type), + but not both. A synonym must conform to the following resrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + :attr list[str] patterns: (optional) An array of patterns for the 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). :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. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. """ def __init__(self, value, + *, metadata=None, - value_type=None, + type=None, synonyms=None, patterns=None, created=None, @@ -3446,29 +3615,31 @@ def __init__(self, """ Initialize a CreateValue object. - :param str value: The text of the entity value. 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 str value: The text of the entity value. 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 dict metadata: (optional) Any metadata related to the entity value. - :param str value_type: (optional) Specifies the type of entity value. - :param list[str] synonyms: (optional) An array of synonyms for the entity value. A - value can specify either synonyms or patterns (depending on the value type), but - not both. A synonym must conform to the following resrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - :param list[str] patterns: (optional) An array of patterns for the 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). - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. + :param str type: (optional) Specifies the type of entity value. + :param list[str] synonyms: (optional) An array of synonyms for the entity + value. A value can specify either synonyms or patterns (depending on the + value type), but not both. A synonym must conform to the following + resrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + :param list[str] patterns: (optional) An array of patterns for the 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). + :param datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. """ self.value = value self.metadata = metadata - self.value_type = value_type + self.type = type self.synonyms = synonyms self.patterns = patterns self.created = created @@ -3479,8 +3650,8 @@ def _from_dict(cls, _dict): """Initialize a CreateValue object from a json dictionary.""" args = {} validKeys = [ - 'value', 'metadata', 'value_type', 'type', 'synonyms', 'patterns', - 'created', 'updated' + 'value', 'metadata', 'type', 'synonyms', 'patterns', 'created', + 'updated' ] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: @@ -3494,8 +3665,8 @@ def _from_dict(cls, _dict): 'Required property \'value\' not present in CreateValue JSON') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') - if 'type' in _dict or 'value_type' in _dict: - args['value_type'] = _dict.get('type') or _dict.get('value_type') + if 'type' in _dict: + args['type'] = _dict.get('type') if 'synonyms' in _dict: args['synonyms'] = _dict.get('synonyms') if 'patterns' in _dict: @@ -3513,8 +3684,8 @@ def _to_dict(self): _dict['value'] = self.value if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata - if hasattr(self, 'value_type') and self.value_type is not None: - _dict['type'] = self.value_type + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type if hasattr(self, 'synonyms') and self.synonyms is not None: _dict['synonyms'] = self.synonyms if hasattr(self, 'patterns') and self.patterns is not None: @@ -3539,56 +3710,64 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + Specifies the type of entity value. + """ + SYNONYMS = "synonyms" + PATTERNS = "patterns" + class DialogNode(object): """ DialogNode. - :attr str dialog_node: The dialog node ID. This string must conform to the following - restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot - characters. - :attr str description: (optional) The description of the dialog node. This string - cannot contain carriage return, newline, or tab characters. - :attr str conditions: (optional) The condition that will trigger the dialog node. This - string cannot contain carriage return, newline, or tab characters. + :attr str dialog_node: The dialog node ID. This string must conform to the + following restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot + characters. + :attr str description: (optional) The description of the dialog node. This + string cannot contain carriage return, newline, or tab characters. + :attr str conditions: (optional) The condition that will trigger the dialog + node. This string cannot contain carriage return, newline, or tab characters. :attr str parent: (optional) The ID of the parent dialog node. This property is - omitted if the dialog node has no parent. - :attr str previous_sibling: (optional) The ID of the previous sibling dialog 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). + omitted if the dialog node has no parent. + :attr str previous_sibling: (optional) The ID of the previous sibling dialog + 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). :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 following this - dialog node. - :attr str title: (optional) The alias used to identify the dialog node. This string - must conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot - characters. - :attr str node_type: (optional) How the dialog node is processed. + :attr DialogNodeNextStep next_step: (optional) The next step to execute + following this dialog node. + :attr str title: (optional) The alias used to identify the dialog node. This + string must conform to the following restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot + characters. + :attr str type: (optional) How the dialog node is processed. :attr str event_name: (optional) How an `event_handler` node is processed. - :attr str variable: (optional) The location in the dialog context where output is - stored. - :attr list[DialogNodeAction] actions: (optional) An array of objects describing any - actions to be invoked by the dialog node. - :attr str digress_in: (optional) Whether this top-level dialog node can be digressed - into. - :attr str digress_out: (optional) Whether this dialog node can be returned to after a - digression. - :attr str digress_out_slots: (optional) Whether the user can digress to top-level - nodes while filling out slots. - :attr str user_label: (optional) A label that can be displayed externally to describe - the purpose of the node to users. + :attr str variable: (optional) The location in the dialog context where output + is stored. + :attr list[DialogNodeAction] actions: (optional) An array of objects describing + any actions to be invoked by the dialog node. + :attr str digress_in: (optional) Whether this top-level dialog node can be + digressed into. + :attr str digress_out: (optional) Whether this dialog node can be returned to + after a digression. + :attr str digress_out_slots: (optional) Whether the user can digress to + top-level nodes while filling out slots. + :attr str user_label: (optional) A label that can be displayed externally to + describe the purpose of the node to users. :attr bool disabled: (optional) For internal use only. :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. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. """ def __init__(self, dialog_node, + *, description=None, conditions=None, parent=None, @@ -3598,7 +3777,7 @@ def __init__(self, metadata=None, next_step=None, title=None, - node_type=None, + type=None, event_name=None, variable=None, actions=None, @@ -3613,46 +3792,49 @@ def __init__(self, Initialize a DialogNode object. :param str dialog_node: The dialog node ID. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot - characters. - :param str description: (optional) The description of the dialog node. This string - cannot contain carriage return, newline, or tab characters. - :param str conditions: (optional) The condition that will trigger the dialog node. - This string cannot contain carriage return, newline, or tab characters. - :param str parent: (optional) The ID of the parent dialog node. This property is - omitted if the dialog node has no parent. - :param str previous_sibling: (optional) The ID of the previous sibling dialog - node. This property is omitted if the dialog node has no previous 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). + following restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and + dot characters. + :param str description: (optional) The description of the dialog node. This + string cannot contain carriage return, newline, or tab characters. + :param str conditions: (optional) The condition that will trigger the + dialog node. This string cannot contain carriage return, newline, or tab + characters. + :param str parent: (optional) The ID of the parent dialog node. This + property is omitted if the dialog node has no parent. + :param str previous_sibling: (optional) The ID of the previous sibling + dialog node. This property is omitted if the dialog node has no previous + 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). :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 following - this dialog node. - :param str title: (optional) The alias used to identify the dialog node. This - string must conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot - characters. - :param str node_type: (optional) How the dialog node is processed. + :param DialogNodeNextStep next_step: (optional) The next step to execute + following this dialog node. + :param str title: (optional) The alias used to identify the dialog node. + This string must conform to the following restrictions: + - It can contain only Unicode alphanumeric, space, underscore, hyphen, and + dot characters. + :param str type: (optional) How the dialog node is processed. :param str event_name: (optional) How an `event_handler` node is processed. - :param str variable: (optional) The location in the dialog context where output is - stored. - :param list[DialogNodeAction] actions: (optional) An array of objects describing - any actions to be invoked by the dialog node. + :param str variable: (optional) The location in the dialog context where + output is stored. + :param list[DialogNodeAction] actions: (optional) An array of objects + describing any actions to be invoked by the dialog node. :param str digress_in: (optional) Whether this top-level dialog node can be - digressed into. - :param str digress_out: (optional) Whether this dialog node can be returned to - after a digression. - :param str digress_out_slots: (optional) Whether the user can digress to top-level - nodes while filling out slots. - :param str user_label: (optional) A label that can be displayed externally to - describe the purpose of the node to users. + digressed into. + :param str digress_out: (optional) Whether this dialog node can be returned + to after a digression. + :param str digress_out_slots: (optional) Whether the user can digress to + top-level nodes while filling out slots. + :param str user_label: (optional) A label that can be displayed externally + to describe the purpose of the node to users. :param bool disabled: (optional) For internal use only. - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. + :param datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. """ self.dialog_node = dialog_node self.description = description @@ -3664,7 +3846,7 @@ def __init__(self, self.metadata = metadata self.next_step = next_step self.title = title - self.node_type = node_type + self.type = type self.event_name = event_name self.variable = variable self.actions = actions @@ -3683,9 +3865,9 @@ def _from_dict(cls, _dict): validKeys = [ 'dialog_node', 'description', 'conditions', 'parent', 'previous_sibling', 'output', 'context', 'metadata', 'next_step', - 'title', 'node_type', 'type', 'event_name', 'variable', 'actions', - 'digress_in', 'digress_out', 'digress_out_slots', 'user_label', - 'disabled', 'created', 'updated' + 'title', 'type', 'event_name', 'variable', 'actions', 'digress_in', + 'digress_out', 'digress_out_slots', 'user_label', 'disabled', + 'created', 'updated' ] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: @@ -3717,8 +3899,8 @@ def _from_dict(cls, _dict): _dict.get('next_step')) if 'title' in _dict: args['title'] = _dict.get('title') - if 'type' in _dict or 'node_type' in _dict: - args['node_type'] = _dict.get('type') or _dict.get('node_type') + if 'type' in _dict: + args['type'] = _dict.get('type') if 'event_name' in _dict: args['event_name'] = _dict.get('event_name') if 'variable' in _dict: @@ -3767,8 +3949,8 @@ def _to_dict(self): _dict['next_step'] = self.next_step._to_dict() if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title - if hasattr(self, 'node_type') and self.node_type is not None: - _dict['type'] = self.node_type + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type if hasattr(self, 'event_name') and self.event_name is not None: _dict['event_name'] = self.event_name if hasattr(self, 'variable') and self.variable is not None: @@ -3806,41 +3988,91 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + How the dialog node is processed. + """ + STANDARD = "standard" + EVENT_HANDLER = "event_handler" + FRAME = "frame" + SLOT = "slot" + RESPONSE_CONDITION = "response_condition" + FOLDER = "folder" + + class EventNameEnum(Enum): + """ + How an `event_handler` node is processed. + """ + FOCUS = "focus" + INPUT = "input" + FILLED = "filled" + VALIDATE = "validate" + FILLED_MULTIPLE = "filled_multiple" + GENERIC = "generic" + NOMATCH = "nomatch" + NOMATCH_RESPONSES_DEPLETED = "nomatch_responses_depleted" + DIGRESSION_RETURN_PROMPT = "digression_return_prompt" + + class DigressInEnum(Enum): + """ + Whether this top-level dialog node can be digressed into. + """ + NOT_AVAILABLE = "not_available" + RETURNS = "returns" + DOES_NOT_RETURN = "does_not_return" + + class DigressOutEnum(Enum): + """ + Whether this dialog node can be returned to after a digression. + """ + ALLOW_RETURNING = "allow_returning" + ALLOW_ALL = "allow_all" + ALLOW_ALL_NEVER_RETURN = "allow_all_never_return" + + class DigressOutSlotsEnum(Enum): + """ + Whether the user can digress to top-level nodes while filling out slots. + """ + NOT_ALLOWED = "not_allowed" + ALLOW_RETURNING = "allow_returning" + ALLOW_ALL = "allow_all" + class DialogNodeAction(object): """ DialogNodeAction. :attr str name: The name of the action. - :attr str action_type: (optional) The type of action to invoke. + :attr str type: (optional) The type of action to invoke. :attr dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :attr str result_variable: The location in the dialog context where the result of the - action is stored. - :attr str credentials: (optional) The name of the context variable that the client - application will use to pass in credentials for the action. + action. + :attr str result_variable: The location in the dialog context where the result + of the action is stored. + :attr str credentials: (optional) The name of the context variable that the + client application will use to pass in credentials for the action. """ def __init__(self, name, result_variable, - action_type=None, + *, + type=None, parameters=None, credentials=None): """ Initialize a DialogNodeAction object. :param str name: The name of the action. - :param str result_variable: The location in the dialog context where the result of - the action is stored. - :param str action_type: (optional) The type of action to invoke. - :param dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :param str credentials: (optional) The name of the context variable that the - client application will use to pass in credentials for the action. + :param str result_variable: The location in the dialog context where the + result of the action is stored. + :param str type: (optional) The type of action to invoke. + :param dict parameters: (optional) A map of key/value pairs to be provided + to the action. + :param str credentials: (optional) The name of the context variable that + the client application will use to pass in credentials for the action. """ self.name = name - self.action_type = action_type + self.type = type self.parameters = parameters self.result_variable = result_variable self.credentials = credentials @@ -3850,8 +4082,7 @@ def _from_dict(cls, _dict): """Initialize a DialogNodeAction object from a json dictionary.""" args = {} validKeys = [ - 'name', 'action_type', 'type', 'parameters', 'result_variable', - 'credentials' + 'name', 'type', 'parameters', 'result_variable', 'credentials' ] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: @@ -3864,8 +4095,8 @@ def _from_dict(cls, _dict): raise ValueError( 'Required property \'name\' not present in DialogNodeAction JSON' ) - if 'type' in _dict or 'action_type' in _dict: - args['action_type'] = _dict.get('type') or _dict.get('action_type') + if 'type' in _dict: + args['type'] = _dict.get('type') if 'parameters' in _dict: args['parameters'] = _dict.get('parameters') if 'result_variable' in _dict: @@ -3883,8 +4114,8 @@ def _to_dict(self): _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name - if hasattr(self, 'action_type') and self.action_type is not None: - _dict['type'] = self.action_type + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type if hasattr(self, 'parameters') and self.parameters is not None: _dict['parameters'] = self.parameters if hasattr(self, @@ -3908,13 +4139,22 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The type of action to invoke. + """ + CLIENT = "client" + SERVER = "server" + CLOUD_FUNCTION = "cloud_function" + WEB_ACTION = "web_action" + class DialogNodeCollection(object): """ An array of dialog nodes. - :attr list[DialogNode] dialog_nodes: An array of objects describing the dialog nodes - defined for the workspace. + :attr list[DialogNode] dialog_nodes: An array of objects describing the dialog + nodes defined for the workspace. :attr Pagination pagination: The pagination data for the returned objects. """ @@ -3922,8 +4162,8 @@ def __init__(self, dialog_nodes, pagination): """ Initialize a DialogNodeCollection object. - :param list[DialogNode] dialog_nodes: An array of objects describing the dialog - nodes defined for the workspace. + :param list[DialogNode] dialog_nodes: An array of objects describing the + dialog nodes defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. """ self.dialog_nodes = dialog_nodes @@ -3983,60 +4223,61 @@ class DialogNodeNextStep(object): """ The next step to execute following this dialog node. - :attr str behavior: What happens after the dialog node completes. The valid values - depend on the node type: - - The following values are valid for any node: - - `get_user_input` - - `skip_user_input` - - `jump_to` - - If the node is of type `event_handler` and its parent node is of type `slot` or - `frame`, additional values are also valid: - - if **event_name**=`filled` and the type of the parent node is `slot`: - - `reprompt` - - `skip_all_slots` - - if **event_name**=`nomatch` and the type of the parent node is `slot`: - - `reprompt` - - `skip_slot` - - `skip_all_slots` - - if **event_name**=`generic` and the type of the parent node is `frame`: - - `reprompt` - - `skip_slot` - - `skip_all_slots` - If you specify `jump_to`, then you must also specify a value for the `dialog_node` - property. - :attr str dialog_node: (optional) The ID of the dialog node to process next. This - parameter is required if **behavior**=`jump_to`. + :attr str behavior: What happens after the dialog node completes. The valid + values depend on the node type: + - The following values are valid for any node: + - `get_user_input` + - `skip_user_input` + - `jump_to` + - If the node is of type `event_handler` and its parent node is of type `slot` + or `frame`, additional values are also valid: + - if **event_name**=`filled` and the type of the parent node is `slot`: + - `reprompt` + - `skip_all_slots` + - if **event_name**=`nomatch` and the type of the parent node is `slot`: + - `reprompt` + - `skip_slot` + - `skip_all_slots` + - if **event_name**=`generic` and the type of the parent node is `frame`: + - `reprompt` + - `skip_slot` + - `skip_all_slots` + If you specify `jump_to`, then you must also specify a value for the + `dialog_node` property. + :attr str dialog_node: (optional) The ID of the dialog node to process next. + This parameter is required if **behavior**=`jump_to`. :attr str selector: (optional) Which part of the dialog node to process next. """ - def __init__(self, behavior, dialog_node=None, selector=None): + def __init__(self, behavior, *, dialog_node=None, selector=None): """ Initialize a DialogNodeNextStep object. - :param str behavior: What happens after the dialog node completes. The valid - values depend on the node type: - - The following values are valid for any node: - - `get_user_input` - - `skip_user_input` - - `jump_to` - - If the node is of type `event_handler` and its parent node is of type `slot` or - `frame`, additional values are also valid: - - if **event_name**=`filled` and the type of the parent node is `slot`: - - `reprompt` - - `skip_all_slots` - - if **event_name**=`nomatch` and the type of the parent node is `slot`: - - `reprompt` - - `skip_slot` - - `skip_all_slots` - - if **event_name**=`generic` and the type of the parent node is `frame`: - - `reprompt` - - `skip_slot` - - `skip_all_slots` - If you specify `jump_to`, then you must also specify a value for the `dialog_node` - property. - :param str dialog_node: (optional) The ID of the dialog node to process next. This - parameter is required if **behavior**=`jump_to`. - :param str selector: (optional) Which part of the dialog node to process next. + :param str behavior: What happens after the dialog node completes. The + valid values depend on the node type: + - The following values are valid for any node: + - `get_user_input` + - `skip_user_input` + - `jump_to` + - If the node is of type `event_handler` and its parent node is of type + `slot` or `frame`, additional values are also valid: + - if **event_name**=`filled` and the type of the parent node is `slot`: + - `reprompt` + - `skip_all_slots` + - if **event_name**=`nomatch` and the type of the parent node is `slot`: + - `reprompt` + - `skip_slot` + - `skip_all_slots` + - if **event_name**=`generic` and the type of the parent node is `frame`: + - `reprompt` + - `skip_slot` + - `skip_all_slots` + If you specify `jump_to`, then you must also specify a value for the + `dialog_node` property. + :param str dialog_node: (optional) The ID of the dialog node to process + next. This parameter is required if **behavior**=`jump_to`. + :param str selector: (optional) Which part of the dialog node to process + next. """ self.behavior = behavior self.dialog_node = dialog_node @@ -4089,6 +4330,46 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class BehaviorEnum(Enum): + """ + What happens after the dialog node completes. The valid values depend on the node + type: + - The following values are valid for any node: + - `get_user_input` + - `skip_user_input` + - `jump_to` + - If the node is of type `event_handler` and its parent node is of type `slot` or + `frame`, additional values are also valid: + - if **event_name**=`filled` and the type of the parent node is `slot`: + - `reprompt` + - `skip_all_slots` + - if **event_name**=`nomatch` and the type of the parent node is `slot`: + - `reprompt` + - `skip_slot` + - `skip_all_slots` + - if **event_name**=`generic` and the type of the parent node is `frame`: + - `reprompt` + - `skip_slot` + - `skip_all_slots` + If you specify `jump_to`, then you must also specify a value for the + `dialog_node` property. + """ + GET_USER_INPUT = "get_user_input" + SKIP_USER_INPUT = "skip_user_input" + JUMP_TO = "jump_to" + REPROMPT = "reprompt" + SKIP_SLOT = "skip_slot" + SKIP_ALL_SLOTS = "skip_all_slots" + + class SelectorEnum(Enum): + """ + Which part of the dialog node to process next. + """ + CONDITION = "condition" + CLIENT = "client" + USER_INPUT = "user_input" + BODY = "body" + class DialogNodeOutput(object): """ @@ -4096,20 +4377,20 @@ class DialogNodeOutput(object): output, see the [documentation](https://cloud.ibm.com/docs/services/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. + :attr list[DialogNodeOutputGeneric] generic: (optional) An array of objects + describing the output defined for the dialog node. :attr DialogNodeOutputModifiers modifiers: (optional) Options that modify how - specified output is handled. + specified output is handled. """ - def __init__(self, generic=None, modifiers=None, **kwargs): + def __init__(self, *, generic=None, modifiers=None, **kwargs): """ Initialize a DialogNodeOutput object. - :param list[DialogNodeOutputGeneric] generic: (optional) An array of objects - describing the output defined for the dialog node. - :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how - specified output is handled. + :param list[DialogNodeOutputGeneric] generic: (optional) An array of + objects describing the output defined for the dialog node. + :param DialogNodeOutputModifiers modifiers: (optional) Options that modify + how specified output is handled. :param **kwargs: (optional) Any additional properties. """ self.generic = generic @@ -4178,36 +4459,54 @@ class DialogNodeOutputGeneric(object): DialogNodeOutputGeneric. :attr str response_type: The type of response returned by the dialog node. The - specified response type must be supported by the client application or channel. - :attr list[DialogNodeOutputTextValuesElement] values: (optional) A list of one or more - objects defining text responses. Required when **response_type**=`text`. - :attr str selection_policy: (optional) How a response is selected from the list, if - more than one response is specified. Valid only when **response_type**=`text`. - :attr str delimiter: (optional) The delimiter to use as a separator between responses - when `selection_policy`=`multiline`. - :attr int time: (optional) How long to pause, in milliseconds. The valid values are - from 0 to 10000. Valid only when **response_type**=`pause`. - :attr bool typing: (optional) Whether to send a "user is typing" event during the - pause. Ignored if the channel does not support this event. Valid only when - **response_type**=`pause`. + specified response type must be supported by the client application or channel. + **Note:** The **search_skill** response type is available only for Plus and + Premium users, and is used only by the v2 runtime API. + :attr list[DialogNodeOutputTextValuesElement] values: (optional) A list of one + or more objects defining text responses. Required when **response_type**=`text`. + :attr str selection_policy: (optional) How a response is selected from the list, + if more than one response is specified. Valid only when + **response_type**=`text`. + :attr str delimiter: (optional) The delimiter to use as a separator between + responses when `selection_policy`=`multiline`. + :attr int time: (optional) How long to pause, in milliseconds. The valid values + are from 0 to 10000. Valid only when **response_type**=`pause`. + :attr bool typing: (optional) Whether to send a "user is typing" event during + the pause. Ignored if the channel does not support this event. Valid only when + **response_type**=`pause`. :attr str source: (optional) The URL of the image. Required when - **response_type**=`image`. - :attr str title: (optional) An optional title to show before the response. Valid only - when **response_type**=`image` or `option`. - :attr str description: (optional) An optional description to show with the response. - Valid only when **response_type**=`image` or `option`. + **response_type**=`image`. + :attr str title: (optional) An optional title to show before the response. Valid + only when **response_type**=`image` or `option`. + :attr str description: (optional) An optional description to show with the + response. Valid only when **response_type**=`image` or `option`. :attr str preference: (optional) The preferred type of control to display, if - supported by the channel. Valid only when **response_type**=`option`. - :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of objects - describing the options from which the user can choose. You can include up to 20 - options. Required when **response_type**=`option`. - :attr str message_to_human_agent: (optional) An optional message to be sent to the - human agent who will be taking over the conversation. Valid only when - **reponse_type**=`connect_to_agent`. + supported by the channel. Valid only when **response_type**=`option`. + :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of + objects describing the options from which the user can choose. You can include + up to 20 options. Required when **response_type**=`option`. + :attr str message_to_human_agent: (optional) An optional message to be sent to + the human agent who will be taking over the conversation. Valid only when + **reponse_type**=`connect_to_agent`. + :attr str query: (optional) The text of the search query. This can be either a + natural-language query or a query that uses the Discovery query language syntax, + depending on the value of the **query_type** property. For more information, see + the [Discovery service + documentation](https://cloud.ibm.com/docs/services/discovery/query-operators.html#query-operators). + Required when **response_type**=`search_skill`. + :attr str query_type: (optional) The type of the search query. Required when + **response_type**=`search_skill`. + :attr str filter: (optional) An optional filter that narrows the set of + documents to be searched. For more information, see the [Discovery service + documentation]([Discovery service + documentation](https://cloud.ibm.com/docs/services/discovery/query-parameters.html#filter). + :attr str discovery_version: (optional) The version of the Discovery service API + to use for the query. """ def __init__(self, response_type, + *, values=None, selection_policy=None, delimiter=None, @@ -4218,37 +4517,60 @@ def __init__(self, description=None, preference=None, options=None, - message_to_human_agent=None): + message_to_human_agent=None, + query=None, + query_type=None, + filter=None, + discovery_version=None): """ Initialize a DialogNodeOutputGeneric object. - :param str response_type: The type of response returned by the dialog node. The - specified response type must be supported by the client application or channel. - :param list[DialogNodeOutputTextValuesElement] values: (optional) A list of one or - more objects defining text responses. Required when **response_type**=`text`. - :param str selection_policy: (optional) How a response is selected from the list, - if more than one response is specified. Valid only when **response_type**=`text`. - :param str delimiter: (optional) The delimiter to use as a separator between - responses when `selection_policy`=`multiline`. - :param int time: (optional) How long to pause, in milliseconds. The valid values - are from 0 to 10000. Valid only when **response_type**=`pause`. - :param bool typing: (optional) Whether to send a "user is typing" event during the - pause. Ignored if the channel does not support this event. Valid only when - **response_type**=`pause`. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + **Note:** The **search_skill** response type is available only for Plus and + Premium users, and is used only by the v2 runtime API. + :param list[DialogNodeOutputTextValuesElement] values: (optional) A list of + one or more objects defining text responses. Required when + **response_type**=`text`. + :param str selection_policy: (optional) How a response is selected from the + list, if more than one response is specified. Valid only when + **response_type**=`text`. + :param str delimiter: (optional) The delimiter to use as a separator + between responses when `selection_policy`=`multiline`. + :param int time: (optional) How long to pause, in milliseconds. The valid + values are from 0 to 10000. Valid only when **response_type**=`pause`. + :param bool typing: (optional) Whether to send a "user is typing" event + during the pause. Ignored if the channel does not support this event. Valid + only when **response_type**=`pause`. :param str source: (optional) The URL of the image. Required when - **response_type**=`image`. - :param str title: (optional) An optional title to show before the response. Valid - only when **response_type**=`image` or `option`. + **response_type**=`image`. + :param str title: (optional) An optional title to show before the response. + Valid only when **response_type**=`image` or `option`. :param str description: (optional) An optional description to show with the - response. Valid only when **response_type**=`image` or `option`. - :param str preference: (optional) The preferred type of control to display, if - supported by the channel. Valid only when **response_type**=`option`. + response. Valid only when **response_type**=`image` or `option`. + :param str preference: (optional) The preferred type of control to display, + if supported by the channel. Valid only when **response_type**=`option`. :param list[DialogNodeOutputOptionsElement] options: (optional) An array of - objects describing the options from which the user can choose. You can include up - to 20 options. Required when **response_type**=`option`. - :param str message_to_human_agent: (optional) An optional message to be sent to - the human agent who will be taking over the conversation. Valid only when - **reponse_type**=`connect_to_agent`. + objects describing the options from which the user can choose. You can + include up to 20 options. Required when **response_type**=`option`. + :param str message_to_human_agent: (optional) An optional message to be + sent to the human agent who will be taking over the conversation. Valid + only when **reponse_type**=`connect_to_agent`. + :param str query: (optional) The text of the search query. This can be + either a natural-language query or a query that uses the Discovery query + language syntax, depending on the value of the **query_type** property. For + more information, see the [Discovery service + documentation](https://cloud.ibm.com/docs/services/discovery/query-operators.html#query-operators). + Required when **response_type**=`search_skill`. + :param str query_type: (optional) The type of the search query. Required + when **response_type**=`search_skill`. + :param str filter: (optional) An optional filter that narrows the set of + documents to be searched. For more information, see the [Discovery service + documentation]([Discovery service + documentation](https://cloud.ibm.com/docs/services/discovery/query-parameters.html#filter). + :param str discovery_version: (optional) The version of the Discovery + service API to use for the query. """ self.response_type = response_type self.values = values @@ -4262,6 +4584,10 @@ def __init__(self, self.preference = preference self.options = options self.message_to_human_agent = message_to_human_agent + self.query = query + self.query_type = query_type + self.filter = filter + self.discovery_version = discovery_version @classmethod def _from_dict(cls, _dict): @@ -4270,7 +4596,8 @@ def _from_dict(cls, _dict): validKeys = [ 'response_type', 'values', 'selection_policy', 'delimiter', 'time', 'typing', 'source', 'title', 'description', 'preference', 'options', - 'message_to_human_agent' + 'message_to_human_agent', 'query', 'query_type', 'filter', + 'discovery_version' ] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: @@ -4311,6 +4638,14 @@ def _from_dict(cls, _dict): ] if 'message_to_human_agent' in _dict: args['message_to_human_agent'] = _dict.get('message_to_human_agent') + if 'query' in _dict: + args['query'] = _dict.get('query') + if 'query_type' in _dict: + args['query_type'] = _dict.get('query_type') + if 'filter' in _dict: + args['filter'] = _dict.get('filter') + if 'discovery_version' in _dict: + args['discovery_version'] = _dict.get('discovery_version') return cls(**args) def _to_dict(self): @@ -4342,6 +4677,15 @@ def _to_dict(self): if hasattr(self, 'message_to_human_agent' ) and self.message_to_human_agent is not None: _dict['message_to_human_agent'] = self.message_to_human_agent + if hasattr(self, 'query') and self.query is not None: + _dict['query'] = self.query + if hasattr(self, 'query_type') and self.query_type is not None: + _dict['query_type'] = self.query_type + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, + 'discovery_version') and self.discovery_version is not None: + _dict['discovery_version'] = self.discovery_version return _dict def __str__(self): @@ -4358,24 +4702,63 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + **Note:** The **search_skill** response type is available only for Plus and + Premium users, and is used only by the v2 runtime API. + """ + TEXT = "text" + PAUSE = "pause" + IMAGE = "image" + OPTION = "option" + CONNECT_TO_AGENT = "connect_to_agent" + SEARCH_SKILL = "search_skill" + + class SelectionPolicyEnum(Enum): + """ + How a response is selected from the list, if more than one response is specified. + Valid only when **response_type**=`text`. + """ + SEQUENTIAL = "sequential" + RANDOM = "random" + MULTILINE = "multiline" + + class PreferenceEnum(Enum): + """ + The preferred type of control to display, if supported by the channel. Valid only + when **response_type**=`option`. + """ + DROPDOWN = "dropdown" + BUTTON = "button" + + class QueryTypeEnum(Enum): + """ + The type of the search query. Required when **response_type**=`search_skill`. + """ + NATURAL_LANGUAGE = "natural_language" + DISCOVERY_QUERY_LANGUAGE = "discovery_query_language" + class DialogNodeOutputModifiers(object): """ Options that modify how specified output is handled. - :attr bool overwrite: (optional) Whether values in the output will overwrite output - values in an array specified by previously executed dialog nodes. If this option is - set to `false`, new values will be appended to previously specified values. + :attr bool overwrite: (optional) Whether values in the output will overwrite + output values in an array specified by previously executed dialog nodes. If this + option is set to `false`, new values will be appended to previously specified + values. """ - def __init__(self, overwrite=None): + def __init__(self, *, overwrite=None): """ Initialize a DialogNodeOutputModifiers object. - :param bool overwrite: (optional) Whether values in the output will overwrite - output values in an array specified by previously executed dialog nodes. If this - option is set to `false`, new values will be appended to previously specified - values. + :param bool overwrite: (optional) Whether values in the output will + overwrite output values in an array specified by previously executed dialog + nodes. If this option is set to `false`, new values will be appended to + previously specified values. """ self.overwrite = overwrite @@ -4420,9 +4803,9 @@ class DialogNodeOutputOptionsElement(object): DialogNodeOutputOptionsElement. :attr str label: The user-facing label for the option. - :attr DialogNodeOutputOptionsElementValue value: An object defining the message input - to be sent to the Watson Assistant service if the user selects the corresponding - option. + :attr DialogNodeOutputOptionsElementValue value: An object defining the message + input to be sent to the Watson Assistant service if the user selects the + corresponding option. """ def __init__(self, label, value): @@ -4430,9 +4813,9 @@ def __init__(self, label, value): Initialize a DialogNodeOutputOptionsElement object. :param str label: The user-facing label for the option. - :param DialogNodeOutputOptionsElementValue value: An object defining the message - input to be sent to the Watson Assistant service if the user selects the - corresponding option. + :param DialogNodeOutputOptionsElementValue value: An object defining the + message input to be sent to the Watson Assistant service if the user + selects the corresponding option. """ self.label = label self.value = value @@ -4491,31 +4874,32 @@ class DialogNodeOutputOptionsElementValue(object): An object defining the message input to be sent to the Watson Assistant service if the user selects the corresponding option. - :attr MessageInput input: (optional) An input object that includes the input text. - :attr list[RuntimeIntent] intents: (optional) An array of intents to be used while - processing the input. - **Note:** This property is supported for backward compatibility with applications that - use the v1 **Get response to user input** method. - :attr list[RuntimeEntity] entities: (optional) An array of entities to be used while - processing the user input. - **Note:** This property is supported for backward compatibility with applications that - use the v1 **Get response to user input** method. + :attr MessageInput input: (optional) An input object that includes the input + text. + :attr list[RuntimeIntent] intents: (optional) An array of intents to be used + while processing the input. + **Note:** This property is supported for backward compatibility with + applications that use the v1 **Get response to user input** method. + :attr list[RuntimeEntity] entities: (optional) An array of entities to be used + while processing the user input. + **Note:** This property is supported for backward compatibility with + applications that use the v1 **Get response to user input** method. """ - def __init__(self, input=None, intents=None, entities=None): + def __init__(self, *, input=None, intents=None, entities=None): """ Initialize a DialogNodeOutputOptionsElementValue object. - :param MessageInput input: (optional) An input object that includes the input - text. - :param list[RuntimeIntent] intents: (optional) An array of intents to be used - while processing the input. - **Note:** This property is supported for backward compatibility with applications - that use the v1 **Get response to user input** method. - :param list[RuntimeEntity] entities: (optional) An array of entities to be used - while processing the user input. - **Note:** This property is supported for backward compatibility with applications - that use the v1 **Get response to user input** method. + :param MessageInput input: (optional) An input object that includes the + input text. + :param list[RuntimeIntent] intents: (optional) An array of intents to be + used while processing the input. + **Note:** This property is supported for backward compatibility with + applications that use the v1 **Get response to user input** method. + :param list[RuntimeEntity] entities: (optional) An array of entities to be + used while processing the user input. + **Note:** This property is supported for backward compatibility with + applications that use the v1 **Get response to user input** method. """ self.input = input self.intents = intents @@ -4573,18 +4957,18 @@ class DialogNodeOutputTextValuesElement(object): """ DialogNodeOutputTextValuesElement. - :attr str text: (optional) The text of a response. This string can include newline - characters (`\\n`), Markdown tagging, or other special characters, if supported by the - channel. + :attr str text: (optional) The text of a response. This string can include + newline characters (`\n`), Markdown tagging, or other special characters, if + supported by the channel. """ - def __init__(self, text=None): + def __init__(self, *, text=None): """ Initialize a DialogNodeOutputTextValuesElement object. :param str text: (optional) The text of a response. This string can include - newline characters (`\\n`), Markdown tagging, or other special characters, if - supported by the channel. + newline characters (`\n`), Markdown tagging, or other special characters, + if supported by the channel. """ self.text = text @@ -4628,20 +5012,21 @@ class DialogNodeVisitedDetails(object): """ DialogNodeVisitedDetails. - :attr str dialog_node: (optional) A dialog node that was triggered during processing - of the input message. + :attr str dialog_node: (optional) A dialog node that was triggered during + processing of the input message. :attr str title: (optional) The title of the dialog node. :attr str conditions: (optional) The conditions that trigger the dialog node. """ - def __init__(self, dialog_node=None, title=None, conditions=None): + def __init__(self, *, dialog_node=None, title=None, conditions=None): """ Initialize a DialogNodeVisitedDetails object. :param str dialog_node: (optional) A dialog node that was triggered during - processing of the input message. + processing of the input message. :param str title: (optional) The title of the dialog node. - :param str conditions: (optional) The conditions that trigger the dialog node. + :param str conditions: (optional) The conditions that trigger the dialog + node. """ self.dialog_node = dialog_node self.title = title @@ -4691,182 +5076,89 @@ def __ne__(self, other): return not self == other -class DialogRuntimeResponseGeneric(object): +class DialogSuggestion(object): """ - DialogRuntimeResponseGeneric. + DialogSuggestion. - :attr str response_type: The type of response returned by the dialog node. The - specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation feature, - which is only available for Premium users. - :attr str text: (optional) The text of the response. - :attr int time: (optional) How long to pause, in milliseconds. - :attr bool typing: (optional) Whether to send a "user is typing" event during the - pause. - :attr str source: (optional) The URL of the image. - :attr str title: (optional) The title or introductory text to show before the - response. - :attr str description: (optional) The description to show with the the response. - :attr str preference: (optional) The preferred type of control to display. - :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of objects - describing the options from which the user can choose. - :attr str message_to_human_agent: (optional) A message to be sent to the human agent - who will be taking over the conversation. - :attr str topic: (optional) A label identifying the topic of the conversation, derived - from the **user_label** property of the relevant node. - :attr str dialog_node: (optional) The ID of the dialog node that the **topic** - property is taken from. The **topic** property is populated using the value of the - dialog node's **user_label** property. - :attr list[DialogSuggestion] suggestions: (optional) An array of objects describing - the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation feature, which is - only available for Premium users. + :attr str label: The user-facing label for the disambiguation option. This label + is taken from the **user_label** property of the corresponding dialog node. + :attr DialogSuggestionValue value: An object defining the message input, + intents, and entities to be sent to the Watson Assistant service if the user + selects the corresponding disambiguation option. + :attr DialogSuggestionOutput output: (optional) The dialog output that will be + returned from the Watson Assistant service if the user selects the corresponding + option. + :attr str dialog_node: (optional) The ID of the dialog node that the **label** + property is taken from. The **label** property is populated using the value of + the dialog node's **user_label** property. """ - def __init__(self, - response_type, - text=None, - time=None, - typing=None, - source=None, - title=None, - description=None, - preference=None, - options=None, - message_to_human_agent=None, - topic=None, - dialog_node=None, - suggestions=None): + def __init__(self, label, value, *, output=None, dialog_node=None): """ - Initialize a DialogRuntimeResponseGeneric object. + Initialize a DialogSuggestion object. - :param str response_type: The type of response returned by the dialog node. The - specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation feature, - which is only available for Premium users. - :param str text: (optional) The text of the response. - :param int time: (optional) How long to pause, in milliseconds. - :param bool typing: (optional) Whether to send a "user is typing" event during the - pause. - :param str source: (optional) The URL of the image. - :param str title: (optional) The title or introductory text to show before the - response. - :param str description: (optional) The description to show with the the response. - :param str preference: (optional) The preferred type of control to display. - :param list[DialogNodeOutputOptionsElement] options: (optional) An array of - objects describing the options from which the user can choose. - :param str message_to_human_agent: (optional) A message to be sent to the human - agent who will be taking over the conversation. - :param str topic: (optional) A label identifying the topic of the conversation, - derived from the **user_label** property of the relevant node. - :param str dialog_node: (optional) The ID of the dialog node that the **topic** - property is taken from. The **topic** property is populated using the value of the - dialog node's **user_label** property. - :param list[DialogSuggestion] suggestions: (optional) An array of objects - describing the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation feature, - which is only available for Premium users. + :param str label: The user-facing label for the disambiguation option. This + label is taken from the **user_label** property of the corresponding dialog + node. + :param DialogSuggestionValue value: An object defining the message input, + intents, and entities to be sent to the Watson Assistant service if the + user selects the corresponding disambiguation option. + :param DialogSuggestionOutput output: (optional) The dialog output that + will be returned from the Watson Assistant service if the user selects the + corresponding option. + :param str dialog_node: (optional) The ID of the dialog node that the + **label** property is taken from. The **label** property is populated using + the value of the dialog node's **user_label** property. """ - self.response_type = response_type - self.text = text - self.time = time - self.typing = typing - self.source = source - self.title = title - self.description = description - self.preference = preference - self.options = options - self.message_to_human_agent = message_to_human_agent - self.topic = topic + self.label = label + self.value = value + self.output = output self.dialog_node = dialog_node - self.suggestions = suggestions @classmethod def _from_dict(cls, _dict): - """Initialize a DialogRuntimeResponseGeneric object from a json dictionary.""" + """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - validKeys = [ - 'response_type', 'text', 'time', 'typing', 'source', 'title', - 'description', 'preference', 'options', 'message_to_human_agent', - 'topic', 'dialog_node', 'suggestions' - ] + validKeys = ['label', 'value', 'output', 'dialog_node'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogRuntimeResponseGeneric: ' + 'Unrecognized keys detected in dictionary for class DialogSuggestion: ' + ', '.join(badKeys)) - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if 'label' in _dict: + args['label'] = _dict.get('label') else: raise ValueError( - 'Required property \'response_type\' not present in DialogRuntimeResponseGeneric JSON' + 'Required property \'label\' not present in DialogSuggestion JSON' ) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'time' in _dict: - args['time'] = _dict.get('time') - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'source' in _dict: - args['source'] = _dict.get('source') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: - args['options'] = [ - DialogNodeOutputOptionsElement._from_dict(x) - for x in (_dict.get('options')) - ] - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'topic' in _dict: - args['topic'] = _dict.get('topic') + if 'value' in _dict: + args['value'] = DialogSuggestionValue._from_dict(_dict.get('value')) + else: + raise ValueError( + 'Required property \'value\' not present in DialogSuggestion JSON' + ) + if 'output' in _dict: + args['output'] = DialogSuggestionOutput._from_dict( + _dict.get('output')) if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') - if 'suggestions' in _dict: - args['suggestions'] = [ - DialogSuggestion._from_dict(x) - for x in (_dict.get('suggestions')) - ] return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'response_type') and self.response_type is not None: - _dict['response_type'] = self.response_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'time') and self.time is not None: - _dict['time'] = self.time - if hasattr(self, 'typing') and self.typing is not None: - _dict['typing'] = self.typing - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'preference') and self.preference is not None: - _dict['preference'] = self.preference - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x._to_dict() for x in self.options] - if hasattr(self, 'message_to_human_agent' - ) and self.message_to_human_agent is not None: - _dict['message_to_human_agent'] = self.message_to_human_agent - if hasattr(self, 'topic') and self.topic is not None: - _dict['topic'] = self.topic + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value._to_dict() + if hasattr(self, 'output') and self.output is not None: + _dict['output'] = self.output._to_dict() if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node - if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x._to_dict() for x in self.suggestions] return _dict def __str__(self): - """Return a `str` version of this DialogRuntimeResponseGeneric object.""" + """Return a `str` version of this DialogSuggestion object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): @@ -4880,66 +5172,264 @@ def __ne__(self, other): return not self == other -class DialogSuggestion(object): +class DialogSuggestionOutput(object): + """ + The dialog output that will be returned from the Watson Assistant service if the user + selects the corresponding option. + + :attr list[str] nodes_visited: (optional) An array of the nodes that were + triggered to create the response, in the order in which they were visited. This + information is useful for debugging and for tracing the path taken through the + node tree. + :attr list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array + of objects containing detailed diagnostic information about the nodes that were + triggered during processing of the input message. Included only if + **nodes_visited_details** is set to `true` in the message request. + :attr list[str] text: An array of responses to the user. + :attr list[DialogSuggestionResponseGeneric] generic: (optional) Output intended + for any channel. It is the responsibility of the client application to implement + the supported response types. """ - DialogSuggestion. - :attr str label: The user-facing label for the disambiguation option. This label is - taken from the **user_label** property of the corresponding dialog node. - :attr DialogSuggestionValue value: An object defining the message input, intents, and - entities to be sent to the Watson Assistant service if the user selects the - corresponding disambiguation option. - :attr dict output: (optional) The dialog output that will be returned from the Watson - Assistant service if the user selects the corresponding option. - :attr str dialog_node: (optional) The ID of the dialog node that the **label** - property is taken from. The **label** property is populated using the value of the - dialog node's **user_label** property. + def __init__(self, + text, + *, + nodes_visited=None, + nodes_visited_details=None, + generic=None, + **kwargs): + """ + Initialize a DialogSuggestionOutput object. + + :param list[str] text: An array of responses to the user. + :param list[str] nodes_visited: (optional) An array of the nodes that were + triggered to create the response, in the order in which they were visited. + This information is useful for debugging and for tracing the path taken + through the node tree. + :param list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An + array of objects containing detailed diagnostic information about the nodes + that were triggered during processing of the input message. Included only + if **nodes_visited_details** is set to `true` in the message request. + :param list[DialogSuggestionResponseGeneric] generic: (optional) Output + intended for any channel. It is the responsibility of the client + application to implement the supported response types. + :param **kwargs: (optional) Any additional properties. + """ + self.nodes_visited = nodes_visited + self.nodes_visited_details = nodes_visited_details + self.text = text + self.generic = generic + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestionOutput object from a json dictionary.""" + args = {} + xtra = _dict.copy() + if 'nodes_visited' in _dict: + args['nodes_visited'] = _dict.get('nodes_visited') + del xtra['nodes_visited'] + if 'nodes_visited_details' in _dict: + args['nodes_visited_details'] = [ + DialogNodeVisitedDetails._from_dict(x) + for x in (_dict.get('nodes_visited_details')) + ] + del xtra['nodes_visited_details'] + if 'text' in _dict: + args['text'] = _dict.get('text') + del xtra['text'] + else: + raise ValueError( + 'Required property \'text\' not present in DialogSuggestionOutput JSON' + ) + if 'generic' in _dict: + args['generic'] = [ + DialogSuggestionResponseGeneric._from_dict(x) + for x in (_dict.get('generic')) + ] + del xtra['generic'] + args.update(xtra) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: + _dict['nodes_visited'] = self.nodes_visited + if hasattr(self, 'nodes_visited_details' + ) and self.nodes_visited_details is not None: + _dict['nodes_visited_details'] = [ + x._to_dict() for x in self.nodes_visited_details + ] + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'generic') and self.generic is not None: + _dict['generic'] = [x._to_dict() for x in self.generic] + if hasattr(self, '_additionalProperties'): + for _key in self._additionalProperties: + _value = getattr(self, _key, None) + if _value is not None: + _dict[_key] = _value + return _dict + + def __setattr__(self, name, value): + properties = { + 'nodes_visited', 'nodes_visited_details', 'text', 'generic' + } + if not hasattr(self, '_additionalProperties'): + super(DialogSuggestionOutput, self).__setattr__( + '_additionalProperties', set()) + if name not in properties: + self._additionalProperties.add(name) + super(DialogSuggestionOutput, self).__setattr__(name, value) + + def __str__(self): + """Return a `str` version of this DialogSuggestionOutput object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DialogSuggestionResponseGeneric(object): """ + DialogSuggestionResponseGeneric. - def __init__(self, label, value, output=None, dialog_node=None): + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + **Note:** The **suggestion** response type is part of the disambiguation + feature, which is only available for Plus and Premium users. The + **search_skill** response type is available only for Plus and Premium users, and + is used only by the v2 runtime API. + :attr str text: (optional) The text of the response. + :attr int time: (optional) How long to pause, in milliseconds. + :attr bool typing: (optional) Whether to send a "user is typing" event during + the pause. + :attr str source: (optional) The URL of the image. + :attr str title: (optional) The title or introductory text to show before the + response. + :attr str description: (optional) The description to show with the the response. + :attr str preference: (optional) The preferred type of control to display. + :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of + objects describing the options from which the user can choose. + :attr str message_to_human_agent: (optional) A message to be sent to the human + agent who will be taking over the conversation. + :attr str topic: (optional) A label identifying the topic of the conversation, + derived from the **user_label** property of the relevant node. + :attr str dialog_node: (optional) The ID of the dialog node that the **topic** + property is taken from. The **topic** property is populated using the value of + the dialog node's **user_label** property. + """ + + def __init__(self, + response_type, + *, + text=None, + time=None, + typing=None, + source=None, + title=None, + description=None, + preference=None, + options=None, + message_to_human_agent=None, + topic=None, + dialog_node=None): """ - Initialize a DialogSuggestion object. + Initialize a DialogSuggestionResponseGeneric object. - :param str label: The user-facing label for the disambiguation option. This label - is taken from the **user_label** property of the corresponding dialog node. - :param DialogSuggestionValue value: An object defining the message input, intents, - and entities to be sent to the Watson Assistant service if the user selects the - corresponding disambiguation option. - :param dict output: (optional) The dialog output that will be returned from the - Watson Assistant service if the user selects the corresponding option. - :param str dialog_node: (optional) The ID of the dialog node that the **label** - property is taken from. The **label** property is populated using the value of the - dialog node's **user_label** property. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + **Note:** The **suggestion** response type is part of the disambiguation + feature, which is only available for Plus and Premium users. The + **search_skill** response type is available only for Plus and Premium + users, and is used only by the v2 runtime API. + :param str text: (optional) The text of the response. + :param int time: (optional) How long to pause, in milliseconds. + :param bool typing: (optional) Whether to send a "user is typing" event + during the pause. + :param str source: (optional) The URL of the image. + :param str title: (optional) The title or introductory text to show before + the response. + :param str description: (optional) The description to show with the the + response. + :param str preference: (optional) The preferred type of control to display. + :param list[DialogNodeOutputOptionsElement] options: (optional) An array of + objects describing the options from which the user can choose. + :param str message_to_human_agent: (optional) A message to be sent to the + human agent who will be taking over the conversation. + :param str topic: (optional) A label identifying the topic of the + conversation, derived from the **user_label** property of the relevant + node. + :param str dialog_node: (optional) The ID of the dialog node that the + **topic** property is taken from. The **topic** property is populated using + the value of the dialog node's **user_label** property. """ - self.label = label - self.value = value - self.output = output + self.response_type = response_type + self.text = text + self.time = time + self.typing = typing + self.source = source + self.title = title + self.description = description + self.preference = preference + self.options = options + self.message_to_human_agent = message_to_human_agent + self.topic = topic self.dialog_node = dialog_node @classmethod def _from_dict(cls, _dict): - """Initialize a DialogSuggestion object from a json dictionary.""" + """Initialize a DialogSuggestionResponseGeneric object from a json dictionary.""" args = {} - validKeys = ['label', 'value', 'output', 'dialog_node'] + validKeys = [ + 'response_type', 'text', 'time', 'typing', 'source', 'title', + 'description', 'preference', 'options', 'message_to_human_agent', + 'topic', 'dialog_node' + ] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogSuggestion: ' + 'Unrecognized keys detected in dictionary for class DialogSuggestionResponseGeneric: ' + ', '.join(badKeys)) - if 'label' in _dict: - args['label'] = _dict.get('label') - else: - raise ValueError( - 'Required property \'label\' not present in DialogSuggestion JSON' - ) - if 'value' in _dict: - args['value'] = DialogSuggestionValue._from_dict(_dict.get('value')) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') else: raise ValueError( - 'Required property \'value\' not present in DialogSuggestion JSON' + 'Required property \'response_type\' not present in DialogSuggestionResponseGeneric JSON' ) - if 'output' in _dict: - args['output'] = _dict.get('output') + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'time' in _dict: + args['time'] = _dict.get('time') + if 'typing' in _dict: + args['typing'] = _dict.get('typing') + if 'source' in _dict: + args['source'] = _dict.get('source') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'preference' in _dict: + args['preference'] = _dict.get('preference') + if 'options' in _dict: + args['options'] = [ + DialogNodeOutputOptionsElement._from_dict(x) + for x in (_dict.get('options')) + ] + if 'message_to_human_agent' in _dict: + args['message_to_human_agent'] = _dict.get('message_to_human_agent') + if 'topic' in _dict: + args['topic'] = _dict.get('topic') if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') return cls(**args) @@ -4947,18 +5437,35 @@ def _from_dict(cls, _dict): def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value._to_dict() - if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'time') and self.time is not None: + _dict['time'] = self.time + if hasattr(self, 'typing') and self.typing is not None: + _dict['typing'] = self.typing + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'preference') and self.preference is not None: + _dict['preference'] = self.preference + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = [x._to_dict() for x in self.options] + if hasattr(self, 'message_to_human_agent' + ) and self.message_to_human_agent is not None: + _dict['message_to_human_agent'] = self.message_to_human_agent + if hasattr(self, 'topic') and self.topic is not None: + _dict['topic'] = self.topic if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node return _dict def __str__(self): - """Return a `str` version of this DialogSuggestion object.""" + """Return a `str` version of this DialogSuggestionResponseGeneric object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): @@ -4971,29 +5478,53 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + **Note:** The **suggestion** response type is part of the disambiguation feature, + which is only available for Plus and Premium users. The **search_skill** response + type is available only for Plus and Premium users, and is used only by the v2 + runtime API. + """ + TEXT = "text" + PAUSE = "pause" + IMAGE = "image" + OPTION = "option" + CONNECT_TO_AGENT = "connect_to_agent" + SEARCH_SKILL = "search_skill" + + class PreferenceEnum(Enum): + """ + The preferred type of control to display. + """ + DROPDOWN = "dropdown" + BUTTON = "button" + class DialogSuggestionValue(object): """ An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. - :attr MessageInput input: (optional) An input object that includes the input text. - :attr list[RuntimeIntent] intents: (optional) An array of intents to be sent along - with the user input. - :attr list[RuntimeEntity] entities: (optional) An array of entities to be sent along - with the user input. + :attr MessageInput input: (optional) An input object that includes the input + text. + :attr list[RuntimeIntent] intents: (optional) An array of intents to be sent + along with the user input. + :attr list[RuntimeEntity] entities: (optional) An array of entities to be sent + along with the user input. """ - def __init__(self, input=None, intents=None, entities=None): + def __init__(self, *, input=None, intents=None, entities=None): """ Initialize a DialogSuggestionValue object. - :param MessageInput input: (optional) An input object that includes the input - text. - :param list[RuntimeIntent] intents: (optional) An array of intents to be sent - along with the user input. - :param list[RuntimeEntity] entities: (optional) An array of entities to be sent - along with the user input. + :param MessageInput input: (optional) An input object that includes the + input text. + :param list[RuntimeIntent] intents: (optional) An array of intents to be + sent along with the user input. + :param list[RuntimeEntity] entities: (optional) An array of entities to be + sent along with the user input. """ self.input = input self.intents = intents @@ -5051,24 +5582,26 @@ class Entity(object): """ Entity. - :attr str entity: The name of the entity. This string must conform to the following - restrictions: - - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - - If you specify an entity name beginning with the reserved prefix `sys-`, it must be - the name of a system entity that you want to enable. (Any entity content specified - with the request is ignored.). - :attr str description: (optional) The description of the entity. This string cannot - contain carriage return, newline, or tab characters. + :attr str entity: The name of the entity. This string must conform to the + following restrictions: + - It can contain only Unicode alphanumeric, underscore, and hyphen characters. + - If you specify an entity name beginning with the reserved prefix `sys-`, it + must be the name of a system entity that you want to enable. (Any entity content + specified with the request is ignored.). + :attr str description: (optional) The description of the entity. This string + cannot contain carriage return, newline, or tab characters. :attr dict metadata: (optional) Any metadata related to the entity. :attr bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. :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. - :attr list[Value] values: (optional) An array of objects describing the entity values. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. + :attr list[Value] values: (optional) An array of objects describing the entity + values. """ def __init__(self, entity, + *, description=None, metadata=None, fuzzy_match=None, @@ -5079,20 +5612,23 @@ def __init__(self, Initialize a Entity object. :param str entity: The name of the entity. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - - If you specify an entity name beginning with the reserved prefix `sys-`, it must - be the name of a system entity that you want to enable. (Any entity content - specified with the request is ignored.). - :param str description: (optional) The description of the entity. This string - cannot contain carriage return, newline, or tab characters. + following restrictions: + - It can contain only Unicode alphanumeric, underscore, and hyphen + characters. + - If you specify an entity name beginning with the reserved prefix `sys-`, + it must be the name of a system entity that you want to enable. (Any entity + content specified with the request is ignored.). + :param str description: (optional) The description of the entity. This + string cannot contain carriage return, newline, or tab characters. :param dict metadata: (optional) Any metadata related to the entity. - :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. - :param list[Value] values: (optional) An array of objects describing the entity - values. + :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the + entity. + :param datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. + :param list[Value] values: (optional) An array of objects describing the + entity values. """ self.entity = entity self.description = description @@ -5174,8 +5710,8 @@ class EntityCollection(object): """ An array of objects describing the entities for the workspace. - :attr list[Entity] entities: An array of objects describing the entities defined for - the workspace. + :attr list[Entity] entities: An array of objects describing the entities defined + for the workspace. :attr Pagination pagination: The pagination data for the returned objects. """ @@ -5183,8 +5719,8 @@ def __init__(self, entities, pagination): """ Initialize a EntityCollection object. - :param list[Entity] entities: An array of objects describing the entities defined - for the workspace. + :param list[Entity] entities: An array of objects describing the entities + defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. """ self.entities = entities @@ -5246,8 +5782,8 @@ class EntityMention(object): :attr str text: The text of the user input example. :attr str intent: The name of the intent. - :attr list[int] location: An array of zero-based character offsets that indicate where - the entity mentions begin and end in the input text. + :attr list[int] location: An array of zero-based character offsets that indicate + where the entity mentions begin and end in the input text. """ def __init__(self, text, intent, location): @@ -5256,8 +5792,8 @@ def __init__(self, text, intent, location): :param str text: The text of the user input example. :param str intent: The name of the intent. - :param list[int] location: An array of zero-based character offsets that indicate - where the entity mentions begin and end in the input text. + :param list[int] location: An array of zero-based character offsets that + indicate where the entity mentions begin and end in the input text. """ self.text = text self.intent = intent @@ -5322,8 +5858,8 @@ class EntityMentionCollection(object): """ EntityMentionCollection. - :attr list[EntityMention] examples: An array of objects describing the entity mentions - defined for an entity. + :attr list[EntityMention] examples: An array of objects describing the entity + mentions defined for an entity. :attr Pagination pagination: The pagination data for the returned objects. """ @@ -5331,8 +5867,8 @@ def __init__(self, examples, pagination): """ Initialize a EntityMentionCollection object. - :param list[EntityMention] examples: An array of objects describing the entity - mentions defined for an entity. + :param list[EntityMention] examples: An array of objects describing the + entity mentions defined for an entity. :param Pagination pagination: The pagination data for the returned objects. """ self.examples = examples @@ -5392,28 +5928,30 @@ class Example(object): """ Example. - :attr str text: The text of a user input example. This string must conform to the - following restrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. + :attr str text: The text of a user input example. This string must conform to + the following restrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. :attr list[Mention] mentions: (optional) An array of contextual entity mentions. :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. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. """ - def __init__(self, text, mentions=None, created=None, updated=None): + def __init__(self, text, *, mentions=None, created=None, updated=None): """ Initialize a Example object. - :param str text: The text of a user input example. 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 list[Mention] mentions: (optional) An array of contextual entity mentions. - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. + :param str text: The text of a user input example. 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 list[Mention] mentions: (optional) An array of contextual entity + mentions. + :param datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. """ self.text = text self.mentions = mentions @@ -5477,8 +6015,8 @@ class ExampleCollection(object): """ ExampleCollection. - :attr list[Example] examples: An array of objects describing the examples defined for - the intent. + :attr list[Example] examples: An array of objects describing the examples + defined for the intent. :attr Pagination pagination: The pagination data for the returned objects. """ @@ -5486,8 +6024,8 @@ def __init__(self, examples, pagination): """ Initialize a ExampleCollection object. - :param list[Example] examples: An array of objects describing the examples defined - for the intent. + :param list[Example] examples: An array of objects describing the examples + defined for the intent. :param Pagination pagination: The pagination data for the returned objects. """ self.examples = examples @@ -5547,21 +6085,23 @@ class Intent(object): """ Intent. - :attr str intent: The name of the intent. This string must conform to the following - restrictions: - - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - - It cannot begin with the reserved prefix `sys-`. - :attr str description: (optional) The description of the intent. This string cannot - contain carriage return, newline, or tab characters. + :attr str intent: The name of the intent. This string must conform to the + following restrictions: + - It can contain only Unicode alphanumeric, underscore, hyphen, and dot + characters. + - It cannot begin with the reserved prefix `sys-`. + :attr str description: (optional) The description of the intent. This string + cannot contain carriage return, newline, or tab characters. :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. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. :attr list[Example] examples: (optional) An array of user input examples for the - intent. + intent. """ def __init__(self, intent, + *, description=None, created=None, updated=None, @@ -5570,17 +6110,18 @@ def __init__(self, Initialize a Intent object. :param str intent: The name of the intent. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, underscore, hyphen, and dot - characters. - - It cannot begin with the reserved prefix `sys-`. - :param str description: (optional) The description of the intent. This string - cannot contain carriage return, newline, or tab characters. - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. - :param list[Example] examples: (optional) An array of user input examples for the - intent. + following restrictions: + - It can contain only Unicode alphanumeric, underscore, hyphen, and dot + characters. + - It cannot begin with the reserved prefix `sys-`. + :param str description: (optional) The description of the intent. This + string cannot contain carriage return, newline, or tab characters. + :param datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. + :param list[Example] examples: (optional) An array of user input examples + for the intent. """ self.intent = intent self.description = description @@ -5649,8 +6190,8 @@ class IntentCollection(object): """ IntentCollection. - :attr list[Intent] intents: An array of objects describing the intents defined for the - workspace. + :attr list[Intent] intents: An array of objects describing the intents defined + for the workspace. :attr Pagination pagination: The pagination data for the returned objects. """ @@ -5658,8 +6199,8 @@ def __init__(self, intents, pagination): """ Initialize a IntentCollection object. - :param list[Intent] intents: An array of objects describing the intents defined - for the workspace. + :param list[Intent] intents: An array of objects describing the intents + defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. """ self.intents = intents @@ -5719,16 +6260,18 @@ class Log(object): """ Log. - :attr MessageRequest request: A request sent to the workspace, including the user - input and context. - :attr MessageResponse response: The response sent by the workspace, including the - output text, detected intents and entities, and context. + :attr MessageRequest request: A request sent to the workspace, including the + user input and context. + :attr MessageResponse response: The response sent by the workspace, including + the output text, detected intents and entities, and context. :attr str log_id: A unique identifier for the logged event. :attr str request_timestamp: The timestamp for receipt of the message. - :attr str response_timestamp: The timestamp for the system response to the message. - :attr str workspace_id: The unique identifier of the workspace where the request was - made. - :attr str language: The language of the workspace where the message request was made. + :attr str response_timestamp: The timestamp for the system response to the + message. + :attr str workspace_id: The unique identifier of the workspace where the request + was made. + :attr str language: The language of the workspace where the message request was + made. """ def __init__(self, request, response, log_id, request_timestamp, @@ -5736,18 +6279,18 @@ def __init__(self, request, response, log_id, request_timestamp, """ Initialize a Log object. - :param MessageRequest request: A request sent to the workspace, including the user - input and context. - :param MessageResponse response: The response sent by the workspace, including the - output text, detected intents and entities, and context. + :param MessageRequest request: A request sent to the workspace, including + the user input and context. + :param MessageResponse response: The response sent by the workspace, + including the output text, detected intents and entities, and context. :param str log_id: A unique identifier for the logged event. :param str request_timestamp: The timestamp for receipt of the message. :param str response_timestamp: The timestamp for the system response to the - message. - :param str workspace_id: The unique identifier of the workspace where the request - was made. - :param str language: The language of the workspace where the message request was - made. + message. + :param str workspace_id: The unique identifier of the workspace where the + request was made. + :param str language: The language of the workspace where the message + request was made. """ self.request = request self.response = response @@ -5859,7 +6402,8 @@ def __init__(self, logs, pagination): Initialize a LogCollection object. :param list[Log] logs: An array of objects describing log events. - :param LogPagination pagination: The pagination data for the returned objects. + :param LogPagination pagination: The pagination data for the returned + objects. """ self.logs = logs self.pagination = pagination @@ -5920,37 +6464,36 @@ class LogMessage(object): :attr str msg: The text of the log message. """ - def __init__(self, level, msg, **kwargs): + def __init__(self, level, msg): """ Initialize a LogMessage object. :param str level: The severity of the log message. :param str msg: The text of the log message. - :param **kwargs: (optional) Any additional properties. """ self.level = level self.msg = msg - for _key, _value in kwargs.items(): - setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a LogMessage object from a json dictionary.""" args = {} - xtra = _dict.copy() + validKeys = ['level', 'msg'] + badKeys = set(_dict.keys()) - set(validKeys) + if badKeys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class LogMessage: ' + + ', '.join(badKeys)) if 'level' in _dict: args['level'] = _dict.get('level') - del xtra['level'] else: raise ValueError( 'Required property \'level\' not present in LogMessage JSON') if 'msg' in _dict: args['msg'] = _dict.get('msg') - del xtra['msg'] else: raise ValueError( 'Required property \'msg\' not present in LogMessage JSON') - args.update(xtra) return cls(**args) def _to_dict(self): @@ -5960,21 +6503,8 @@ def _to_dict(self): _dict['level'] = self.level if hasattr(self, 'msg') and self.msg is not None: _dict['msg'] = self.msg - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value return _dict - def __setattr__(self, name, value): - properties = {'level', 'msg'} - if not hasattr(self, '_additionalProperties'): - super(LogMessage, self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(LogMessage, self).__setattr__(name, value) - def __str__(self): """Return a `str` version of this LogMessage object.""" return json.dumps(self._to_dict(), indent=2) @@ -5989,25 +6519,34 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LevelEnum(Enum): + """ + The severity of the log message. + """ + INFO = "info" + ERROR = "error" + WARN = "warn" + class LogPagination(object): """ The pagination data for the returned objects. - :attr str next_url: (optional) The URL that will return the next page of results, if - any. + :attr str next_url: (optional) The URL that will return the next page of + results, if any. :attr int matched: (optional) Reserved for future use. :attr str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, next_url=None, matched=None, next_cursor=None): + def __init__(self, *, next_url=None, matched=None, next_cursor=None): """ Initialize a LogPagination object. - :param str next_url: (optional) The URL that will return the next page of results, - if any. + :param str next_url: (optional) The URL that will return the next page of + results, if any. :param int matched: (optional) Reserved for future use. - :param str next_cursor: (optional) A token identifying the next page of results. + :param str next_cursor: (optional) A token identifying the next page of + results. """ self.next_url = next_url self.matched = matched @@ -6062,8 +6601,8 @@ class Mention(object): A mention of a contextual entity. :attr str entity: The name of the entity. - :attr list[int] location: An array of zero-based character offsets that indicate where - the entity mentions begin and end in the input text. + :attr list[int] location: An array of zero-based character offsets that indicate + where the entity mentions begin and end in the input text. """ def __init__(self, entity, location): @@ -6071,8 +6610,8 @@ def __init__(self, entity, location): Initialize a Mention object. :param str entity: The name of the entity. - :param list[int] location: An array of zero-based character offsets that indicate - where the entity mentions begin and end in the input text. + :param list[int] location: An array of zero-based character offsets that + indicate where the entity mentions begin and end in the input text. """ self.entity = entity self.location = location @@ -6127,28 +6666,29 @@ class MessageContextMetadata(object): """ Metadata related to the message. - :attr str deployment: (optional) A label identifying the deployment environment, used - for filtering log data. This string cannot contain carriage return, newline, or tab - characters. + :attr str deployment: (optional) A label identifying the deployment environment, + used for filtering log data. This string cannot contain carriage return, + newline, or tab characters. :attr str user_id: (optional) A string value that identifies the user who is - interacting with the workspace. The client must provide a unique identifier for each - individual end user who accesses the application. For Plus and Premium plans, this - user ID is used to identify unique users for billing purposes. This string cannot - contain carriage return, newline, or tab characters. + interacting with the workspace. The client must provide a unique identifier for + each individual end user who accesses the application. For Plus and Premium + plans, this user ID is used to identify unique users for billing purposes. This + string cannot contain carriage return, newline, or tab characters. """ - def __init__(self, deployment=None, user_id=None): + def __init__(self, *, deployment=None, user_id=None): """ Initialize a MessageContextMetadata object. - :param str deployment: (optional) A label identifying the deployment environment, - used for filtering log data. This string cannot contain carriage return, newline, - or tab characters. - :param str user_id: (optional) A string value that identifies the user who is - interacting with the workspace. The client must provide a unique identifier for - each individual end user who accesses the application. For Plus and Premium plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. + :param str deployment: (optional) A label identifying the deployment + environment, used for filtering log data. This string cannot contain + carriage return, newline, or tab characters. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the workspace. The client must provide a unique + identifier for each individual end user who accesses the application. For + Plus and Premium plans, this user ID is used to identify unique users for + billing purposes. This string cannot contain carriage return, newline, or + tab characters. """ self.deployment = deployment self.user_id = user_id @@ -6197,16 +6737,16 @@ class MessageInput(object): """ An input object that includes the input text. - :attr str text: (optional) The text of the user input. This string cannot contain - carriage return, newline, or tab characters. + :attr str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. """ - def __init__(self, text=None, **kwargs): + def __init__(self, *, text=None, **kwargs): """ Initialize a MessageInput object. - :param str text: (optional) The text of the user input. This string cannot contain - carriage return, newline, or tab characters. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. :param **kwargs: (optional) Any additional properties. """ self.text = text @@ -6264,24 +6804,26 @@ class MessageRequest(object): """ A request sent to the workspace, including the user input and context. - :attr MessageInput input: (optional) An input object that includes the input text. - :attr list[RuntimeIntent] intents: (optional) Intents to use when evaluating the user - input. Include intents from the previous response to continue using those intents - rather than trying to recognize intents in the new input. - :attr list[RuntimeEntity] entities: (optional) Entities to use when evaluating the - message. Include entities from the previous response to continue using those entities - rather than detecting entities in the new input. - :attr bool alternate_intents: (optional) Whether to return more than one intent. A - value of `true` indicates that all matching intents are returned. - :attr Context context: (optional) State information for the conversation. To maintain - state, include the context from the previous response. - :attr OutputData output: (optional) An output object that includes the response to the - user, the dialog nodes that were triggered, and messages from the log. - :attr list[DialogNodeAction] actions: (optional) An array of objects describing any - actions requested by the dialog node. + :attr MessageInput input: (optional) An input object that includes the input + text. + :attr list[RuntimeIntent] intents: (optional) Intents to use when evaluating the + user input. Include intents from the previous response to continue using those + intents rather than trying to recognize intents in the new input. + :attr list[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :attr bool alternate_intents: (optional) Whether to return more than one intent. + A value of `true` indicates that all matching intents are returned. + :attr Context context: (optional) State information for the conversation. To + maintain state, include the context from the previous response. + :attr OutputData output: (optional) An output object that includes the response + to the user, the dialog nodes that were triggered, and messages from the log. + :attr list[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. """ def __init__(self, + *, input=None, intents=None, entities=None, @@ -6292,22 +6834,25 @@ def __init__(self, """ Initialize a MessageRequest object. - :param MessageInput input: (optional) An input object that includes the input - text. - :param list[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :param list[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :param bool alternate_intents: (optional) Whether to return more than one intent. - A value of `true` indicates that all matching intents are returned. - :param Context context: (optional) State information for the conversation. To - maintain state, include the context from the previous response. - :param OutputData output: (optional) An output object that includes the response - to the user, the dialog nodes that were triggered, and messages from the log. - :param list[DialogNodeAction] actions: (optional) An array of objects describing - any actions requested by the dialog node. + :param MessageInput input: (optional) An input object that includes the + input text. + :param list[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param list[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param bool alternate_intents: (optional) Whether to return more than one + intent. A value of `true` indicates that all matching intents are returned. + :param Context context: (optional) State information for the conversation. + To maintain state, include the context from the previous response. + :param OutputData output: (optional) An output object that includes the + response to the user, the dialog nodes that were triggered, and messages + from the log. + :param list[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. """ self.input = input self.intents = intents @@ -6393,17 +6938,18 @@ class MessageResponse(object): entities, and context. :attr MessageInput input: An input object that includes the input text. - :attr list[RuntimeIntent] intents: An array of intents recognized in the user input, - sorted in descending order of confidence. - :attr list[RuntimeEntity] entities: An array of entities identified in the user input. - :attr bool alternate_intents: (optional) Whether to return more than one intent. A - value of `true` indicates that all matching intents are returned. - :attr Context context: State information for the conversation. To maintain state, - include the context from the previous response. - :attr OutputData output: An output object that includes the response to the user, the - dialog nodes that were triggered, and messages from the log. - :attr list[DialogNodeAction] actions: (optional) An array of objects describing any - actions requested by the dialog node. + :attr list[RuntimeIntent] intents: An array of intents recognized in the user + input, sorted in descending order of confidence. + :attr list[RuntimeEntity] entities: An array of entities identified in the user + input. + :attr bool alternate_intents: (optional) Whether to return more than one intent. + A value of `true` indicates that all matching intents are returned. + :attr Context context: State information for the conversation. To maintain + state, include the context from the previous response. + :attr OutputData output: An output object that includes the response to the + user, the dialog nodes that were triggered, and messages from the log. + :attr list[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. """ def __init__(self, @@ -6412,24 +6958,25 @@ def __init__(self, entities, context, output, + *, alternate_intents=None, actions=None): """ Initialize a MessageResponse object. :param MessageInput input: An input object that includes the input text. - :param list[RuntimeIntent] intents: An array of intents recognized in the user - input, sorted in descending order of confidence. - :param list[RuntimeEntity] entities: An array of entities identified in the user - input. - :param Context context: State information for the conversation. To maintain state, - include the context from the previous response. - :param OutputData output: An output object that includes the response to the user, - the dialog nodes that were triggered, and messages from the log. - :param bool alternate_intents: (optional) Whether to return more than one intent. - A value of `true` indicates that all matching intents are returned. - :param list[DialogNodeAction] actions: (optional) An array of objects describing - any actions requested by the dialog node. + :param list[RuntimeIntent] intents: An array of intents recognized in the + user input, sorted in descending order of confidence. + :param list[RuntimeEntity] entities: An array of entities identified in the + user input. + :param Context context: State information for the conversation. To maintain + state, include the context from the previous response. + :param OutputData output: An output object that includes the response to + the user, the dialog nodes that were triggered, and messages from the log. + :param bool alternate_intents: (optional) Whether to return more than one + intent. A value of `true` indicates that all matching intents are returned. + :param list[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. """ self.input = input self.intents = intents @@ -6534,52 +7081,54 @@ class OutputData(object): An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr list[LogMessage] log_messages: An array of up to 50 messages logged with the - request. + :attr list[str] nodes_visited: (optional) An array of the nodes that were + triggered to create the response, in the order in which they were visited. This + information is useful for debugging and for tracing the path taken through the + node tree. + :attr list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array + of objects containing detailed diagnostic information about the nodes that were + triggered during processing of the input message. Included only if + **nodes_visited_details** is set to `true` in the message request. + :attr list[LogMessage] log_messages: An array of up to 50 messages logged with + the request. :attr list[str] text: An array of responses to the user. - :attr list[DialogRuntimeResponseGeneric] generic: (optional) Output intended for any - channel. It is the responsibility of the client application to implement the supported - response types. - :attr list[str] nodes_visited: (optional) An array of the nodes that were triggered to - create the response, in the order in which they were visited. This information is - useful for debugging and for tracing the path taken through the node tree. - :attr list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array of - objects containing detailed diagnostic information about the nodes that were triggered - during processing of the input message. Included only if **nodes_visited_details** is - set to `true` in the message request. + :attr list[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. """ def __init__(self, log_messages, text, - generic=None, + *, nodes_visited=None, nodes_visited_details=None, + generic=None, **kwargs): """ Initialize a OutputData object. - :param list[LogMessage] log_messages: An array of up to 50 messages logged with - the request. + :param list[LogMessage] log_messages: An array of up to 50 messages logged + with the request. :param list[str] text: An array of responses to the user. - :param list[DialogRuntimeResponseGeneric] generic: (optional) Output intended for - any channel. It is the responsibility of the client application to implement the - supported response types. :param list[str] nodes_visited: (optional) An array of the nodes that were - triggered to create the response, in the order in which they were visited. This - information is useful for debugging and for tracing the path taken through the - node tree. - :param list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array - of objects containing detailed diagnostic information about the nodes that were - triggered during processing of the input message. Included only if - **nodes_visited_details** is set to `true` in the message request. + triggered to create the response, in the order in which they were visited. + This information is useful for debugging and for tracing the path taken + through the node tree. + :param list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An + array of objects containing detailed diagnostic information about the nodes + that were triggered during processing of the input message. Included only + if **nodes_visited_details** is set to `true` in the message request. + :param list[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. :param **kwargs: (optional) Any additional properties. """ + self.nodes_visited = nodes_visited + self.nodes_visited_details = nodes_visited_details self.log_messages = log_messages self.text = text self.generic = generic - self.nodes_visited = nodes_visited - self.nodes_visited_details = nodes_visited_details for _key, _value in kwargs.items(): setattr(self, _key, _value) @@ -6588,6 +7137,15 @@ def _from_dict(cls, _dict): """Initialize a OutputData object from a json dictionary.""" args = {} xtra = _dict.copy() + if 'nodes_visited' in _dict: + args['nodes_visited'] = _dict.get('nodes_visited') + del xtra['nodes_visited'] + if 'nodes_visited_details' in _dict: + args['nodes_visited_details'] = [ + DialogNodeVisitedDetails._from_dict(x) + for x in (_dict.get('nodes_visited_details')) + ] + del xtra['nodes_visited_details'] if 'log_messages' in _dict: args['log_messages'] = [ LogMessage._from_dict(x) for x in (_dict.get('log_messages')) @@ -6605,31 +7163,16 @@ def _from_dict(cls, _dict): 'Required property \'text\' not present in OutputData JSON') if 'generic' in _dict: args['generic'] = [ - DialogRuntimeResponseGeneric._from_dict(x) + RuntimeResponseGeneric._from_dict(x) for x in (_dict.get('generic')) ] del xtra['generic'] - if 'nodes_visited' in _dict: - args['nodes_visited'] = _dict.get('nodes_visited') - del xtra['nodes_visited'] - if 'nodes_visited_details' in _dict: - args['nodes_visited_details'] = [ - DialogNodeVisitedDetails._from_dict(x) - for x in (_dict.get('nodes_visited_details')) - ] - del xtra['nodes_visited_details'] args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'log_messages') and self.log_messages is not None: - _dict['log_messages'] = [x._to_dict() for x in self.log_messages] - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x._to_dict() for x in self.generic] if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: _dict['nodes_visited'] = self.nodes_visited if hasattr(self, 'nodes_visited_details' @@ -6637,6 +7180,12 @@ def _to_dict(self): _dict['nodes_visited_details'] = [ x._to_dict() for x in self.nodes_visited_details ] + if hasattr(self, 'log_messages') and self.log_messages is not None: + _dict['log_messages'] = [x._to_dict() for x in self.log_messages] + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'generic') and self.generic is not None: + _dict['generic'] = [x._to_dict() for x in self.generic] if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) @@ -6646,8 +7195,8 @@ def _to_dict(self): def __setattr__(self, name, value): properties = { - 'log_messages', 'text', 'generic', 'nodes_visited', - 'nodes_visited_details' + 'nodes_visited', 'nodes_visited_details', 'log_messages', 'text', + 'generic' } if not hasattr(self, '_additionalProperties'): super(OutputData, self).__setattr__('_additionalProperties', set()) @@ -6675,15 +7224,18 @@ class Pagination(object): The pagination data for the returned objects. :attr str refresh_url: The URL that will return the same page of results. - :attr str next_url: (optional) The URL that will return the next page of results. + :attr str next_url: (optional) The URL that will return the next page of + results. :attr int total: (optional) Reserved for future use. :attr int matched: (optional) Reserved for future use. - :attr str refresh_cursor: (optional) A token identifying the current page of results. + :attr str refresh_cursor: (optional) A token identifying the current page of + results. :attr str next_cursor: (optional) A token identifying the next page of results. """ def __init__(self, refresh_url, + *, next_url=None, total=None, matched=None, @@ -6693,12 +7245,14 @@ def __init__(self, Initialize a Pagination object. :param str refresh_url: The URL that will return the same page of results. - :param str next_url: (optional) The URL that will return the next page of results. + :param str next_url: (optional) The URL that will return the next page of + results. :param int total: (optional) Reserved for future use. :param int matched: (optional) Reserved for future use. - :param str refresh_cursor: (optional) A token identifying the current page of - results. - :param str next_cursor: (optional) A token identifying the next page of results. + :param str refresh_cursor: (optional) A token identifying the current page + of results. + :param str next_cursor: (optional) A token identifying the next page of + results. """ self.refresh_url = refresh_url self.next_url = next_url @@ -6775,37 +7329,36 @@ class RuntimeEntity(object): A term from the request that was identified as an entity. :attr str entity: An entity detected in the input. - :attr list[int] location: An array of zero-based character offsets that indicate where - the detected entity values begin and end in the input text. + :attr list[int] location: An array of zero-based character offsets that indicate + where the detected entity values begin and end in the input text. :attr str value: 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. + confidence in the recognized entity. :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 list[CaptureGroup] groups: (optional) The recognized capture groups for + the entity, as defined by the entity pattern. """ def __init__(self, entity, location, value, + *, confidence=None, metadata=None, - groups=None, - **kwargs): + groups=None): """ Initialize a RuntimeEntity object. :param str entity: An entity detected in the input. - :param list[int] location: An array of zero-based character offsets that indicate - where the detected entity values begin and end in the input text. + :param list[int] location: An array of zero-based character offsets that + indicate where the detected entity values begin and end in the input text. :param str value: 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. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the recognized entity. :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 **kwargs: (optional) Any additional properties. + :param list[CaptureGroup] groups: (optional) The recognized capture groups + for the entity, as defined by the entity pattern. """ self.entity = entity self.location = location @@ -6813,46 +7366,44 @@ def __init__(self, self.confidence = confidence self.metadata = metadata self.groups = groups - for _key, _value in kwargs.items(): - setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a RuntimeEntity object from a json dictionary.""" args = {} - xtra = _dict.copy() + validKeys = [ + 'entity', 'location', 'value', 'confidence', 'metadata', 'groups' + ] + badKeys = set(_dict.keys()) - set(validKeys) + if badKeys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeEntity: ' + + ', '.join(badKeys)) if 'entity' in _dict: args['entity'] = _dict.get('entity') - del xtra['entity'] else: raise ValueError( 'Required property \'entity\' not present in RuntimeEntity JSON' ) if 'location' in _dict: args['location'] = _dict.get('location') - del xtra['location'] else: raise ValueError( 'Required property \'location\' not present in RuntimeEntity JSON' ) if 'value' in _dict: args['value'] = _dict.get('value') - del xtra['value'] else: raise ValueError( 'Required property \'value\' not present in RuntimeEntity JSON') if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') - del xtra['confidence'] if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') - del xtra['metadata'] if 'groups' in _dict: args['groups'] = [ CaptureGroup._from_dict(x) for x in (_dict.get('groups')) ] - del xtra['groups'] - args.update(xtra) return cls(**args) def _to_dict(self): @@ -6870,24 +7421,8 @@ def _to_dict(self): _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, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value return _dict - def __setattr__(self, name, value): - properties = { - 'entity', 'location', 'value', 'confidence', 'metadata', 'groups' - } - if not hasattr(self, '_additionalProperties'): - super(RuntimeEntity, self).__setattr__('_additionalProperties', - set()) - if name not in properties: - self._additionalProperties.add(name) - super(RuntimeEntity, self).__setattr__(name, value) - def __str__(self): """Return a `str` version of this RuntimeEntity object.""" return json.dumps(self._to_dict(), indent=2) @@ -6908,44 +7443,43 @@ class RuntimeIntent(object): An intent identified in the user input. :attr str intent: The name of the recognized intent. - :attr float confidence: A decimal percentage that represents Watson's confidence in - the intent. + :attr float confidence: A decimal percentage that represents Watson's confidence + in the intent. """ - def __init__(self, intent, confidence, **kwargs): + def __init__(self, intent, confidence): """ Initialize a RuntimeIntent object. :param str intent: The name of the recognized intent. - :param float confidence: A decimal percentage that represents Watson's confidence - in the intent. - :param **kwargs: (optional) Any additional properties. + :param float confidence: A decimal percentage that represents Watson's + confidence in the intent. """ self.intent = intent self.confidence = confidence - for _key, _value in kwargs.items(): - setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): """Initialize a RuntimeIntent object from a json dictionary.""" args = {} - xtra = _dict.copy() + validKeys = ['intent', 'confidence'] + badKeys = set(_dict.keys()) - set(validKeys) + if badKeys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeIntent: ' + + ', '.join(badKeys)) if 'intent' in _dict: args['intent'] = _dict.get('intent') - del xtra['intent'] else: raise ValueError( 'Required property \'intent\' not present in RuntimeIntent JSON' ) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') - del xtra['confidence'] else: raise ValueError( 'Required property \'confidence\' not present in RuntimeIntent JSON' ) - args.update(xtra) return cls(**args) def _to_dict(self): @@ -6955,22 +7489,8 @@ def _to_dict(self): _dict['intent'] = self.intent if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value return _dict - def __setattr__(self, name, value): - properties = {'intent', 'confidence'} - if not hasattr(self, '_additionalProperties'): - super(RuntimeIntent, self).__setattr__('_additionalProperties', - set()) - if name not in properties: - self._additionalProperties.add(name) - super(RuntimeIntent, self).__setattr__(name, value) - def __str__(self): """Return a `str` version of this RuntimeIntent object.""" return json.dumps(self._to_dict(), indent=2) @@ -6986,30 +7506,246 @@ def __ne__(self, other): return not self == other +class RuntimeResponseGeneric(object): + """ + RuntimeResponseGeneric. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + **Note:** The **suggestion** response type is part of the disambiguation + feature, which is only available for Plus and Premium users. + :attr str text: (optional) The text of the response. + :attr int time: (optional) How long to pause, in milliseconds. + :attr bool typing: (optional) Whether to send a "user is typing" event during + the pause. + :attr str source: (optional) The URL of the image. + :attr str title: (optional) The title or introductory text to show before the + response. + :attr str description: (optional) The description to show with the the response. + :attr str preference: (optional) The preferred type of control to display. + :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of + objects describing the options from which the user can choose. + :attr str message_to_human_agent: (optional) A message to be sent to the human + agent who will be taking over the conversation. + :attr str topic: (optional) A label identifying the topic of the conversation, + derived from the **user_label** property of the relevant node. + :attr str dialog_node: (optional) The ID of the dialog node that the **topic** + property is taken from. The **topic** property is populated using the value of + the dialog node's **user_label** property. + :attr list[DialogSuggestion] suggestions: (optional) An array of objects + describing the possible matching dialog nodes from which the user can choose. + **Note:** The **suggestions** property is part of the disambiguation feature, + which is only available for Premium users. + """ + + def __init__(self, + response_type, + *, + text=None, + time=None, + typing=None, + source=None, + title=None, + description=None, + preference=None, + options=None, + message_to_human_agent=None, + topic=None, + dialog_node=None, + suggestions=None): + """ + Initialize a RuntimeResponseGeneric object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + **Note:** The **suggestion** response type is part of the disambiguation + feature, which is only available for Plus and Premium users. + :param str text: (optional) The text of the response. + :param int time: (optional) How long to pause, in milliseconds. + :param bool typing: (optional) Whether to send a "user is typing" event + during the pause. + :param str source: (optional) The URL of the image. + :param str title: (optional) The title or introductory text to show before + the response. + :param str description: (optional) The description to show with the the + response. + :param str preference: (optional) The preferred type of control to display. + :param list[DialogNodeOutputOptionsElement] options: (optional) An array of + objects describing the options from which the user can choose. + :param str message_to_human_agent: (optional) A message to be sent to the + human agent who will be taking over the conversation. + :param str topic: (optional) A label identifying the topic of the + conversation, derived from the **user_label** property of the relevant + node. + :param str dialog_node: (optional) The ID of the dialog node that the + **topic** property is taken from. The **topic** property is populated using + the value of the dialog node's **user_label** property. + :param list[DialogSuggestion] suggestions: (optional) An array of objects + describing the possible matching dialog nodes from which the user can + choose. + **Note:** The **suggestions** property is part of the disambiguation + feature, which is only available for Premium users. + """ + self.response_type = response_type + self.text = text + self.time = time + self.typing = typing + self.source = source + self.title = title + self.description = description + self.preference = preference + self.options = options + self.message_to_human_agent = message_to_human_agent + self.topic = topic + self.dialog_node = dialog_node + self.suggestions = suggestions + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + args = {} + validKeys = [ + 'response_type', 'text', 'time', 'typing', 'source', 'title', + 'description', 'preference', 'options', 'message_to_human_agent', + 'topic', 'dialog_node', 'suggestions' + ] + badKeys = set(_dict.keys()) - set(validKeys) + if badKeys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeResponseGeneric: ' + + ', '.join(badKeys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGeneric JSON' + ) + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'time' in _dict: + args['time'] = _dict.get('time') + if 'typing' in _dict: + args['typing'] = _dict.get('typing') + if 'source' in _dict: + args['source'] = _dict.get('source') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'preference' in _dict: + args['preference'] = _dict.get('preference') + if 'options' in _dict: + args['options'] = [ + DialogNodeOutputOptionsElement._from_dict(x) + for x in (_dict.get('options')) + ] + if 'message_to_human_agent' in _dict: + args['message_to_human_agent'] = _dict.get('message_to_human_agent') + if 'topic' in _dict: + args['topic'] = _dict.get('topic') + if 'dialog_node' in _dict: + args['dialog_node'] = _dict.get('dialog_node') + if 'suggestions' in _dict: + args['suggestions'] = [ + DialogSuggestion._from_dict(x) + for x in (_dict.get('suggestions')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'time') and self.time is not None: + _dict['time'] = self.time + if hasattr(self, 'typing') and self.typing is not None: + _dict['typing'] = self.typing + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'preference') and self.preference is not None: + _dict['preference'] = self.preference + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = [x._to_dict() for x in self.options] + if hasattr(self, 'message_to_human_agent' + ) and self.message_to_human_agent is not None: + _dict['message_to_human_agent'] = self.message_to_human_agent + if hasattr(self, 'topic') and self.topic is not None: + _dict['topic'] = self.topic + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'suggestions') and self.suggestions is not None: + _dict['suggestions'] = [x._to_dict() for x in self.suggestions] + return _dict + + def __str__(self): + """Return a `str` version of this RuntimeResponseGeneric object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + **Note:** The **suggestion** response type is part of the disambiguation feature, + which is only available for Plus and Premium users. + """ + TEXT = "text" + PAUSE = "pause" + IMAGE = "image" + OPTION = "option" + CONNECT_TO_AGENT = "connect_to_agent" + SUGGESTION = "suggestion" + + class PreferenceEnum(Enum): + """ + The preferred type of control to display. + """ + DROPDOWN = "dropdown" + BUTTON = "button" + + class Synonym(object): """ Synonym. - :attr str synonym: The text of the synonym. This string must conform to the following - restrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. + :attr str synonym: The text of the synonym. This string must conform to the + following restrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. :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. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. """ - def __init__(self, synonym, created=None, updated=None): + def __init__(self, synonym, *, created=None, updated=None): """ Initialize a Synonym object. - :param str synonym: The text of the synonym. 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 datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. + :param str synonym: The text of the synonym. 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 datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. """ self.synonym = synonym self.created = created @@ -7192,29 +7928,30 @@ class Value(object): Value. :attr str value: The text of the entity value. This string must conform to the - following restrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. + following restrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. :attr dict metadata: (optional) Any metadata related to the entity value. - :attr str value_type: Specifies the type of entity value. - :attr list[str] synonyms: (optional) An array of synonyms for the entity value. A - value can specify either synonyms or patterns (depending on the value type), but not - both. A synonym must conform to the following resrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - :attr list[str] patterns: (optional) An array of patterns for the 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). + :attr str type: Specifies the type of entity value. + :attr list[str] synonyms: (optional) An array of synonyms for the entity value. + A value can specify either synonyms or patterns (depending on the value type), + but not both. A synonym must conform to the following resrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + :attr list[str] patterns: (optional) An array of patterns for the 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). :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. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. """ def __init__(self, value, - value_type, + type, + *, metadata=None, synonyms=None, patterns=None, @@ -7223,29 +7960,31 @@ def __init__(self, """ Initialize a Value object. - :param str value: The text of the entity value. 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 str value_type: Specifies the type of entity value. + :param str value: The text of the entity value. 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 str type: Specifies the type of entity value. :param dict metadata: (optional) Any metadata related to the entity value. - :param list[str] synonyms: (optional) An array of synonyms for the entity value. A - value can specify either synonyms or patterns (depending on the value type), but - not both. A synonym must conform to the following resrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - :param list[str] patterns: (optional) An array of patterns for the 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). - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. + :param list[str] synonyms: (optional) An array of synonyms for the entity + value. A value can specify either synonyms or patterns (depending on the + value type), but not both. A synonym must conform to the following + resrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + :param list[str] patterns: (optional) An array of patterns for the 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). + :param datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. """ self.value = value self.metadata = metadata - self.value_type = value_type + self.type = type self.synonyms = synonyms self.patterns = patterns self.created = created @@ -7256,8 +7995,8 @@ def _from_dict(cls, _dict): """Initialize a Value object from a json dictionary.""" args = {} validKeys = [ - 'value', 'metadata', 'value_type', 'type', 'synonyms', 'patterns', - 'created', 'updated' + 'value', 'metadata', 'type', 'synonyms', 'patterns', 'created', + 'updated' ] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: @@ -7271,8 +8010,8 @@ def _from_dict(cls, _dict): 'Required property \'value\' not present in Value JSON') if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') - if 'type' in _dict or 'value_type' in _dict: - args['value_type'] = _dict.get('type') or _dict.get('value_type') + if 'type' in _dict: + args['type'] = _dict.get('type') else: raise ValueError( 'Required property \'type\' not present in Value JSON') @@ -7293,8 +8032,8 @@ def _to_dict(self): _dict['value'] = self.value if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata - if hasattr(self, 'value_type') and self.value_type is not None: - _dict['type'] = self.value_type + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type if hasattr(self, 'synonyms') and self.synonyms is not None: _dict['synonyms'] = self.synonyms if hasattr(self, 'patterns') and self.patterns is not None: @@ -7319,6 +8058,13 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + Specifies the type of entity value. + """ + SYNONYMS = "synonyms" + PATTERNS = "patterns" + class ValueCollection(object): """ @@ -7392,28 +8138,29 @@ class Workspace(object): """ Workspace. - :attr str name: The name of the workspace. This string cannot contain carriage return, - newline, or tab characters. - :attr str description: (optional) The description of the workspace. This string cannot - contain carriage return, newline, or tab characters. + :attr str name: The name of the workspace. This string cannot contain carriage + return, newline, or tab characters. + :attr str description: (optional) The description of the workspace. This string + cannot contain carriage return, newline, or tab characters. :attr str language: The language of the workspace. :attr dict metadata: (optional) Any metadata related to the workspace. :attr bool learning_opt_out: Whether training data from the workspace (including - artifacts such as intents and entities) can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. - :attr WorkspaceSystemSettings system_settings: (optional) Global settings for the - workspace. + artifacts such as intents and entities) can be used by IBM for general service + improvements. `true` indicates that workspace training data is not to be used. + :attr WorkspaceSystemSettings system_settings: (optional) Global settings for + the workspace. :attr str workspace_id: The workspace ID of the workspace. :attr str status: (optional) The current status of the workspace. :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. + :attr datetime updated: (optional) The timestamp for the most recent update to + the object. :attr list[Intent] intents: (optional) An array of intents. - :attr list[Entity] entities: (optional) An array of objects describing the entities - for the workspace. - :attr list[DialogNode] dialog_nodes: (optional) An array of objects describing the - dialog nodes in the workspace. - :attr list[Counterexample] counterexamples: (optional) An array of counterexamples. + :attr list[Entity] entities: (optional) An array of objects describing the + entities for the workspace. + :attr list[DialogNode] dialog_nodes: (optional) An array of objects describing + the dialog nodes in the workspace. + :attr list[Counterexample] counterexamples: (optional) An array of + counterexamples. """ def __init__(self, @@ -7421,6 +8168,7 @@ def __init__(self, language, learning_opt_out, workspace_id, + *, description=None, metadata=None, system_settings=None, @@ -7434,29 +8182,31 @@ def __init__(self, """ Initialize a Workspace object. - :param str name: The name of the workspace. This string cannot contain carriage - return, newline, or tab characters. + :param str name: The name of the workspace. This string cannot contain + carriage return, newline, or tab characters. :param str language: The language of the workspace. - :param bool learning_opt_out: Whether training data from the workspace (including - artifacts such as intents and entities) can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. + :param bool learning_opt_out: Whether training data from the workspace + (including artifacts such as intents and entities) can be used by IBM for + general service improvements. `true` indicates that workspace training data + is not to be used. :param str workspace_id: The workspace ID of the workspace. - :param str description: (optional) The description of the workspace. This string - cannot contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the workspace. This + string cannot contain carriage return, newline, or tab characters. :param dict metadata: (optional) Any metadata related to the workspace. - :param WorkspaceSystemSettings system_settings: (optional) Global settings for the - workspace. + :param WorkspaceSystemSettings system_settings: (optional) Global settings + for the workspace. :param str status: (optional) The current status of the workspace. - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. + :param datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. :param list[Intent] intents: (optional) An array of intents. :param list[Entity] entities: (optional) An array of objects describing the - entities for the workspace. - :param list[DialogNode] dialog_nodes: (optional) An array of objects describing - the dialog nodes in the workspace. + entities for the workspace. + :param list[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. :param list[Counterexample] counterexamples: (optional) An array of - counterexamples. + counterexamples. """ self.name = name self.description = description @@ -7593,13 +8343,23 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The current status of the workspace. + """ + NON_EXISTENT = "Non Existent" + TRAINING = "Training" + FAILED = "Failed" + AVAILABLE = "Available" + UNAVAILABLE = "Unavailable" + class WorkspaceCollection(object): """ WorkspaceCollection. :attr list[Workspace] workspaces: An array of objects describing the workspaces - associated with the service instance. + associated with the service instance. :attr Pagination pagination: The pagination data for the returned objects. """ @@ -7607,8 +8367,8 @@ def __init__(self, workspaces, pagination): """ Initialize a WorkspaceCollection object. - :param list[Workspace] workspaces: An array of objects describing the workspaces - associated with the service instance. + :param list[Workspace] workspaces: An array of objects describing the + workspaces associated with the service instance. :param Pagination pagination: The pagination data for the returned objects. """ self.workspaces = workspaces @@ -7668,26 +8428,27 @@ class WorkspaceSystemSettings(object): """ Global settings for the workspace. - :attr WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings related to - the Watson Assistant user interface. + :attr WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings + related to the Watson Assistant user interface. :attr WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace - settings related to the disambiguation feature. - **Note:** This feature is available only to Premium users. + settings related to the disambiguation feature. + **Note:** This feature is available only to Premium users. :attr dict human_agent_assist: (optional) For internal use only. """ def __init__(self, + *, tooling=None, disambiguation=None, human_agent_assist=None): """ Initialize a WorkspaceSystemSettings object. - :param WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings - related to the Watson Assistant user interface. - :param WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace - settings related to the disambiguation feature. - **Note:** This feature is available only to Premium users. + :param WorkspaceSystemSettingsTooling tooling: (optional) Workspace + settings related to the Watson Assistant user interface. + :param WorkspaceSystemSettingsDisambiguation disambiguation: (optional) + Workspace settings related to the disambiguation feature. + **Note:** This feature is available only to Premium users. :param dict human_agent_assist: (optional) For internal use only. """ self.tooling = tooling @@ -7748,19 +8509,21 @@ class WorkspaceSystemSettingsDisambiguation(object): Workspace settings related to the disambiguation feature. **Note:** This feature is available only to Premium users. - :attr str prompt: (optional) The text of the introductory prompt that accompanies - disambiguation options presented to the user. - :attr str none_of_the_above_prompt: (optional) The user-facing label for the option - users can select if none of the suggested options is correct. If no value is specified - for this property, this option does not appear. - :attr bool enabled: (optional) Whether the disambiguation feature is enabled for the - workspace. - :attr str sensitivity: (optional) The sensitivity of the disambiguation feature to - intent detection conflicts. Set to **high** if you want the disambiguation feature to - be triggered more often. This can be useful for testing or demonstration purposes. + :attr str prompt: (optional) The text of the introductory prompt that + accompanies disambiguation options presented to the user. + :attr str none_of_the_above_prompt: (optional) The user-facing label for the + option users can select if none of the suggested options is correct. If no value + is specified for this property, this option does not appear. + :attr bool enabled: (optional) Whether the disambiguation feature is enabled for + the workspace. + :attr str sensitivity: (optional) The sensitivity of the disambiguation feature + to intent detection conflicts. Set to **high** if you want the disambiguation + feature to be triggered more often. This can be useful for testing or + demonstration purposes. """ def __init__(self, + *, prompt=None, none_of_the_above_prompt=None, enabled=None, @@ -7768,17 +8531,17 @@ def __init__(self, """ Initialize a WorkspaceSystemSettingsDisambiguation object. - :param str prompt: (optional) The text of the introductory prompt that accompanies - disambiguation options presented to the user. - :param str none_of_the_above_prompt: (optional) The user-facing label for the - option users can select if none of the suggested options is correct. If no value - is specified for this property, this option does not appear. - :param bool enabled: (optional) Whether the disambiguation feature is enabled for - the workspace. - :param str sensitivity: (optional) The sensitivity of the disambiguation feature - to intent detection conflicts. Set to **high** if you want the disambiguation - feature to be triggered more often. This can be useful for testing or - demonstration purposes. + :param str prompt: (optional) The text of the introductory prompt that + accompanies disambiguation options presented to the user. + :param str none_of_the_above_prompt: (optional) The user-facing label for + the option users can select if none of the suggested options is correct. If + no value is specified for this property, this option does not appear. + :param bool enabled: (optional) Whether the disambiguation feature is + enabled for the workspace. + :param str sensitivity: (optional) The sensitivity of the disambiguation + feature to intent detection conflicts. Set to **high** if you want the + disambiguation feature to be triggered more often. This can be useful for + testing or demonstration purposes. """ self.prompt = prompt self.none_of_the_above_prompt = none_of_the_above_prompt @@ -7836,21 +8599,30 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class SensitivityEnum(Enum): + """ + The sensitivity of the disambiguation feature to intent detection conflicts. Set + to **high** if you want the disambiguation feature to be triggered more often. + This can be useful for testing or demonstration purposes. + """ + AUTO = "auto" + HIGH = "high" + class WorkspaceSystemSettingsTooling(object): """ Workspace settings related to the Watson Assistant user interface. - :attr bool store_generic_responses: (optional) Whether the dialog JSON editor displays - text responses within the `output.generic` object. + :attr bool store_generic_responses: (optional) Whether the dialog JSON editor + displays text responses within the `output.generic` object. """ - def __init__(self, store_generic_responses=None): + def __init__(self, *, store_generic_responses=None): """ Initialize a WorkspaceSystemSettingsTooling object. - :param bool store_generic_responses: (optional) Whether the dialog JSON editor - displays text responses within the `output.generic` object. + :param bool store_generic_responses: (optional) Whether the dialog JSON + editor displays text responses within the `output.generic` object. """ self.store_generic_responses = store_generic_responses From fe6ef57c03ce74be78baed61980c777bdb73fd4d Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 17:42:35 -0400 Subject: [PATCH 003/455] chore(assistantv1): update assistantv1 examples --- examples/assistant_v1.py | 30 ++++++++++++------------------ 1 file changed, 12 insertions(+), 18 deletions(-) diff --git a/examples/assistant_v1.py b/examples/assistant_v1.py index 6bc766ae8..6de775b22 100644 --- a/examples/assistant_v1.py +++ b/examples/assistant_v1.py @@ -1,20 +1,14 @@ from __future__ import print_function import json from ibm_watson import AssistantV1 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -# If service instance provides API key authentication +authenticator = IAMAuthenticator('your api key') assistant = AssistantV1( version='2018-07-10', ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/assistant/api', - iam_apikey='YOUR APIKEY') - -# assistant = AssistantV1( -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD', -# ## url is optional, and defaults to the URL below. Use the correct URL for your region. -# # url='https://gateway.watsonplatform.net/assistant/api', -# version='2018-07-10') + authenticator=authenticator) ######################### # Workspaces @@ -22,7 +16,7 @@ create_workspace_data = { "name": - "test_workspace", + "test_workspace 3", "description": "integration tests", "language": @@ -196,18 +190,18 @@ 'values': [{ 'value': 'value0', 'patterns': ['\\d{6}\\w{1}\\d{7}'], - 'value_type': 'patterns' + 'type': 'patterns' }, { 'value': 'value1', 'patterns': ['[-9][0-9][0-9][0-9][0-9]~! [1-9][1-9][1-9][1-9][1-9][1-9]'], - 'value_type': + 'type': 'patterns' }, { 'value': 'value2', 'patterns': ['[a-z-9]{17}'], - 'value_type': 'patterns' + 'type': 'patterns' }, { 'value': 'value3', @@ -215,12 +209,12 @@ '\\d{3}(\\ |-)\\d{3}(\\ |-)\\d{4}', '\\(\\d{3}\\)(\\ |-)\\d{3}(\\ |-)\\d{4}' ], - 'value_type': + 'type': 'patterns' }, { 'value': 'value4', 'patterns': ['\\b\\d{5}\\b'], - 'value_type': 'patterns' + 'type': 'patterns' }] }] response = assistant.create_entity( @@ -266,7 +260,7 @@ print(json.dumps(response, indent=2)) response = assistant.update_synonym(workspace_id, 'beverage', 'orange juice', - 'oj', 'OJ').get_result() + 'oj', new_synonym='OJ').get_result() print(json.dumps(response, indent=2)) response = assistant.delete_synonym(workspace_id, 'beverage', 'orange juice', @@ -292,7 +286,7 @@ print(json.dumps(response, indent=2)) response = assistant.update_value(workspace_id, 'test_entity', 'test', - 'example').get_result() + new_value='example').get_result() print(json.dumps(response, indent=2)) response = assistant.delete_value(workspace_id, 'test_entity', @@ -320,7 +314,7 @@ response = assistant.create_dialog_node( workspace_id, create_dialog_node['dialog_node'], - create_dialog_node['description'], + description=create_dialog_node['description'], actions=create_dialog_node['actions']).get_result() print(json.dumps(response, indent=2)) From 385d1f07bac3af4ea977ee9d3a0c821b8a1ef65b Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 18:06:48 -0400 Subject: [PATCH 004/455] test(assistantv1): Update unit tests of assistantv1 --- test/unit/test_assistant_v1.py | 155 +++++++++++++++++++++------------ 1 file changed, 99 insertions(+), 56 deletions(-) diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index a44817100..bc5fd8a49 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -9,6 +9,7 @@ CounterexampleCollection, Entity, EntityCollection, Example, \ ExampleCollection, MessageInput, Intent, IntentCollection, Synonym, \ SynonymCollection, Value, ValueCollection, Workspace, WorkspaceCollection +from ibm_cloud_sdk_core.authenticators import BasicAuthenticator platform_url = 'https://gateway.watsonplatform.net' service_path = '/assistant/api' @@ -34,8 +35,8 @@ def test_create_counterexample(): body=json.dumps(response), status=201, content_type='application/json') - service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + authenticator = BasicAuthenticator('username', 'password') + service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) counterexample = service.create_counterexample( workspace_id='boguswid', text='I want financial advice today.').get_result() assert len(responses.calls) == 1 @@ -56,8 +57,8 @@ def test_rate_limit_exceeded(): body='Rate limit exceeded', status=429, content_type='application/json') - service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + authenticator = BasicAuthenticator('username', 'password') + service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) try: service.create_counterexample( workspace_id='boguswid', text='I want financial advice today.') @@ -77,8 +78,8 @@ def test_unknown_error(): url, status=407, content_type='application/json') - service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + authenticator = BasicAuthenticator('username', 'password') + service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) try: service.create_counterexample( workspace_id='boguswid', text='I want financial advice today.') @@ -98,8 +99,9 @@ def test_delete_counterexample(): body=response, status=204, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) counterexample = service.delete_counterexample( workspace_id='boguswid', text='I want financial advice today').get_result() assert len(responses.calls) == 1 @@ -123,8 +125,9 @@ def test_get_counterexample(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) counterexample = service.get_counterexample( workspace_id='boguswid', text='What are you wearing?').get_result() assert len(responses.calls) == 1 @@ -160,8 +163,9 @@ def test_list_counterexamples(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) counterexamples = service.list_counterexamples(workspace_id='boguswid').get_result() assert len(responses.calls) == 1 assert responses.calls[0].request.url.startswith(url) @@ -185,8 +189,9 @@ def test_update_counterexample(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) counterexample = service.update_counterexample( workspace_id='boguswid', text='What are you wearing?', @@ -221,8 +226,9 @@ def test_create_entity(): body=json.dumps(response), status=201, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) entity = service.create_entity( workspace_id='boguswid', entity='pizza_toppings', @@ -247,8 +253,9 @@ def test_delete_entity(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) entity = service.delete_entity(workspace_id='boguswid', entity='pizza_toppings').get_result() assert len(responses.calls) == 1 assert responses.calls[0].request.url.startswith(url) @@ -274,8 +281,9 @@ def test_get_entity(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) entity = service.get_entity(workspace_id='boguswid', entity='pizza_toppings', export=True).get_result() assert len(responses.calls) == 1 assert responses.calls[0].request.url.startswith(url) @@ -315,8 +323,9 @@ def test_list_entities(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) entities = service.list_entities( workspace_id='boguswid', export=True).get_result() @@ -346,8 +355,9 @@ def test_update_entity(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) entity = service.update_entity( workspace_id='boguswid', entity='pizza_toppings', @@ -380,8 +390,9 @@ def test_create_example(): body=json.dumps(response), status=201, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) example = service.create_example( workspace_id='boguswid', intent='pizza_order', @@ -406,8 +417,9 @@ def test_delete_example(): body=json.dumps(response), status=204, content_type='') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) example = service.delete_example( workspace_id='boguswid', intent='pizza_order', @@ -433,8 +445,8 @@ def test_get_example(): body=json.dumps(response), status=200, content_type='application/json') - service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + authenticator = BasicAuthenticator('username', 'password') + service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) example = service.get_example( workspace_id='boguswid', intent='pizza_order', @@ -474,8 +486,9 @@ def test_list_examples(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) examples = service.list_examples( workspace_id='boguswid', intent='pizza_order').get_result() assert len(responses.calls) == 1 @@ -501,8 +514,9 @@ def test_update_example(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) example = service.update_example( workspace_id='boguswid', intent='pizza_order', @@ -537,8 +551,9 @@ def test_create_intent(): body=json.dumps(response), status=201, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) intent = service.create_intent( workspace_id='boguswid', intent='pizza_order', @@ -562,8 +577,9 @@ def test_delete_intent(): body=json.dumps(response), status=204, content_type='') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) intent = service.delete_intent( workspace_id='boguswid', intent='pizza_order').get_result() assert len(responses.calls) == 1 @@ -588,8 +604,9 @@ def test_get_intent(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) intent = service.get_intent( workspace_id='boguswid', intent='pizza_order', export=False).get_result() assert len(responses.calls) == 1 @@ -622,8 +639,9 @@ def test_list_intents(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) intents = service.list_intents(workspace_id='boguswid', export=False).get_result() assert len(responses.calls) == 1 assert responses.calls[0].request.url.startswith(url) @@ -648,8 +666,9 @@ def test_update_intent(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) intent = service.update_intent( workspace_id='boguswid', intent='pizza_order', @@ -734,8 +753,9 @@ def test_list_logs(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) logs = service.list_logs( workspace_id='boguswid').get_result() assert len(responses.calls) == 1 @@ -805,8 +825,9 @@ def test_list_all_logs(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) logs = service.list_all_logs( 'language::en,request.context.metadata.deployment::deployment_1').get_result() assert len(responses.calls) == 1 @@ -822,13 +843,14 @@ def test_list_all_logs(): @responses.activate def test_message(): + authenticator = BasicAuthenticator('username', 'password') assistant = ibm_watson.AssistantV1( - username="username", password="password", version='2016-09-20') + version='2017-02-03', authenticator=authenticator) assistant.set_default_headers({'x-watson-learning-opt-out': "true"}) workspace_id = 'f8fdbc65-e0bd-4e43-b9f8-2975a366d4ec' message_url = '%s/v1/workspaces/%s/message' % (base_url, workspace_id) - url1_str = '%s/v1/workspaces/%s/message?version=2016-09-20' + url1_str = '%s/v1/workspaces/%s/message?version=2017-02-03' message_url1 = url1_str % (base_url, workspace_id) message_response = { "context": { @@ -897,14 +919,14 @@ def test_message(): @responses.activate def test_message_with_models(): - + authenticator = BasicAuthenticator('username', 'password') assistant = ibm_watson.AssistantV1( - username="username", password="password", version='2016-09-20') + version='2017-02-03', authenticator=authenticator) assistant.set_default_headers({'x-watson-learning-opt-out': "true"}) workspace_id = 'f8fdbc65-e0bd-4e43-b9f8-2975a366d4ec' message_url = '%s/v1/workspaces/%s/message' % (base_url, workspace_id) - url1_str = '%s/v1/workspaces/%s/message?version=2016-09-20' + url1_str = '%s/v1/workspaces/%s/message?version=2017-02-03' message_url1 = url1_str % (base_url, workspace_id) message_response = { "context": { @@ -984,8 +1006,9 @@ def test_create_synonym(): body=json.dumps(response), status=201, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) synonym = service.create_synonym( workspace_id='boguswid', entity='aeiou', value='vowel', synonym='a').get_result() assert len(responses.calls) == 1 @@ -1006,8 +1029,9 @@ def test_delete_synonym(): body=json.dumps(response), status=204, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) synonym = service.delete_synonym( workspace_id='boguswid', entity='aeiou', value='vowel', synonym='a').get_result() assert len(responses.calls) == 1 @@ -1031,8 +1055,9 @@ def test_get_synonym(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) synonym = service.get_synonym( workspace_id='boguswid', entity='grilling', value='bbq', synonym='barbecue').get_result() assert len(responses.calls) == 1 @@ -1074,8 +1099,9 @@ def test_list_synonyms(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) synonyms = service.list_synonyms( workspace_id='boguswid', entity='grilling', @@ -1103,8 +1129,9 @@ def test_update_synonym(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) synonym = service.update_synonym( workspace_id='boguswid', entity='grilling', value='bbq', synonym='barbecue', new_synonym='barbecue').get_result() assert len(responses.calls) == 1 @@ -1136,8 +1163,9 @@ def test_create_value(): body=json.dumps(response), status=201, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) value = service.create_value( workspace_id='boguswid', entity='grilling', @@ -1161,8 +1189,9 @@ def test_delete_value(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) value = service.delete_value( workspace_id='boguswid', entity='grilling', value='bbq').get_result() assert len(responses.calls) == 1 @@ -1190,8 +1219,9 @@ def test_get_value(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) value = service.get_value( workspace_id='boguswid', entity='grilling', value='bbq', export=True).get_result() assert len(responses.calls) == 1 @@ -1232,8 +1262,9 @@ def test_list_values(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) values = service.list_values( workspace_id='boguswid', entity='grilling', @@ -1265,8 +1296,9 @@ def test_update_value(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-04-21') + version='2017-02-03', authenticator=authenticator) value = service.update_value( workspace_id='boguswid', entity='grilling', @@ -1306,8 +1338,9 @@ def test_create_workspace(): body=json.dumps(response), status=201, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) workspace = service.create_workspace( name='Pizza app', description='Pizza app', language='en', metadata={}, system_settings={'tooling': {'store_generic_responses' : True}}).get_result() @@ -1328,8 +1361,9 @@ def test_delete_workspace(): body=json.dumps(response), status=204, content_type='') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) workspace = service.delete_workspace(workspace_id='boguswid').get_result() assert len(responses.calls) == 1 assert responses.calls[0].request.url.startswith(url) @@ -1357,8 +1391,9 @@ def test_get_workspace(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) workspace = service.get_workspace(workspace_id='boguswid', export=True, sort='stable').get_result() assert len(responses.calls) == 1 assert responses.calls[0].request.url.startswith(url) @@ -1395,8 +1430,9 @@ def test_list_workspaces(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) workspaces = service.list_workspaces().get_result() assert len(responses.calls) == 1 assert responses.calls[0].request.url.startswith(url) @@ -1425,8 +1461,9 @@ def test_update_workspace(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) workspace = service.update_workspace( workspace_id='pizza_app-e0f3', name='Pizza app', @@ -1452,26 +1489,28 @@ def test_dialog_nodes(): responses.add( responses.POST, - "{0}?version=2017-05-26".format(url), + "{0}?version=2017-02-03".format(url), body='{ "application/json": { "dialog_node": "location-done" }}', status=200, content_type='application/json') responses.add( responses.DELETE, - "{0}/location-done?version=2017-05-26".format(url), + "{0}/location-done?version=2017-02-03".format(url), body='{"description": "deleted successfully"}', status=200, content_type='application/json') responses.add( responses.GET, - "{0}/location-done?version=2017-05-26".format(url), + "{0}/location-done?version=2017-02-03".format(url), body='{ "application/json": { "dialog_node": "location-atm" }}', status=200, content_type='application/json') - assistant = ibm_watson.AssistantV1('2017-05-26', username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + assistant = ibm_watson.AssistantV1( + version='2017-02-03', authenticator=authenticator) assistant.create_dialog_node('id', 'location-done', user_label='xxx') assert responses.calls[0].response.json()['application/json']['dialog_node'] == 'location-done' @@ -1497,9 +1536,11 @@ def test_delete_user_data(): status=204, content_type='application_json') - assistant = ibm_watson.AssistantV1('2017-05-26', username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + service = ibm_watson.AssistantV1( + version='2017-02-03', authenticator=authenticator) - response = assistant.delete_user_data('id').get_result() + response = service.delete_user_data('id').get_result() assert response is None assert len(responses.calls) == 1 @@ -1513,8 +1554,10 @@ def test_list_mentions(): status=200, content_type='application_json') - assistant = ibm_watson.AssistantV1('2017-05-26', username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + service = ibm_watson.AssistantV1( + version='2017-02-03', authenticator=authenticator) - response = assistant.list_mentions('workspace_id', 'entity1').get_result() + response = service.list_mentions('workspace_id', 'entity1').get_result() assert response == [{"entity": "xxx"}] assert len(responses.calls) == 1 From 7099563b2a9b7e9beb4a3e2ecd8f99ec25e1dd09 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 18:07:45 -0400 Subject: [PATCH 005/455] feat(assistantv2): generate assistantv2 --- ibm_watson/assistant_v2.py | 1165 +++++++++++++++++++----------------- 1 file changed, 607 insertions(+), 558 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 78bfd0f4e..2e3989c8f 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,11 +19,11 @@ apps and your users. """ -from __future__ import absolute_import - import json 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 ############################################################################## # Service @@ -39,16 +39,8 @@ def __init__( self, version, url=default_url, - username=None, - password=None, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, + authenticator=None, + disable_ssl_verification=False, ): """ Construct a new client for the Assistant service. @@ -68,62 +60,21 @@ def __init__( "https://gateway.watsonplatform.net/assistant/api/assistant/api"). The base url may differ between IBM Cloud regions. - :param str username: The username used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str password: The password used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ + if not authenticator: + authenticator = get_authenticator_from_environment('Assistant') + BaseService.__init__( self, - vcap_services_name='conversation', url=url, - username=username, - password=password, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Assistant', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Assistant') self.version = version ######################### @@ -137,11 +88,12 @@ def create_session(self, assistant_id, **kwargs): Create a new session. A session is used to send user input to a skill and receive responses. It also maintains the state of the conversation. - :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). - **Note:** Currently, the v2 API does not support creating assistants. + :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). + **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. :rtype: DetailedResponse @@ -160,12 +112,13 @@ def create_session(self, assistant_id, **kwargs): url = '/v2/assistants/{0}/sessions'.format( *self._encode_path_vars(assistant_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def delete_session(self, assistant_id, session_id, **kwargs): @@ -174,11 +127,12 @@ def delete_session(self, assistant_id, session_id, **kwargs): Deletes a session explicitly before it times out. - :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). - **Note:** Currently, the v2 API does not support creating assistants. + :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). + **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 :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -200,12 +154,13 @@ def delete_session(self, assistant_id, session_id, **kwargs): url = '/v2/assistants/{0}/sessions/{1}'.format( *self._encode_path_vars(assistant_id, session_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -215,6 +170,7 @@ def delete_session(self, assistant_id, session_id, **kwargs): def message(self, assistant_id, session_id, + *, input=None, context=None, **kwargs): @@ -224,16 +180,19 @@ def message(self, Send user input to an assistant and receive a response. There is no rate limit for this operation. - :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). - **Note:** Currently, the v2 API does not support creating assistants. + :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). + **Note:** Currently, the v2 API does not support creating assistants. :param str session_id: Unique identifier of the session. - :param MessageInput input: An input object that includes the input text. - :param MessageContext context: State information for the conversation. The context - is stored by the assistant on a per-session basis. You can use this property to - set or modify context variables, which can also be accessed by dialog nodes. + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) State information for the + conversation. The context is stored by the assistant on a per-session + basis. You can use this property to set or modify context variables, which + can also be accessed by dialog nodes. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -260,13 +219,14 @@ def message(self, url = '/v2/assistants/{0}/sessions/{1}/message'.format( *self._encode_path_vars(assistant_id, session_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response @@ -280,17 +240,17 @@ class CaptureGroup(object): CaptureGroup. :attr str group: A recognized capture group for the entity. - :attr list[int] location: (optional) Zero-based character offsets that indicate where - the entity value begins and ends in the input text. + :attr list[int] location: (optional) Zero-based character offsets that indicate + where the entity value begins and ends in the input text. """ - def __init__(self, group, location=None): + def __init__(self, group, *, location=None): """ Initialize a CaptureGroup object. :param str group: A recognized capture group for the entity. - :param list[int] location: (optional) Zero-based character offsets that indicate - where the entity value begins and ends in the input text. + :param list[int] location: (optional) Zero-based character offsets that + indicate where the entity value begins and ends in the input text. """ self.group = group self.location = location @@ -403,41 +363,50 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LevelEnum(Enum): + """ + The severity of the log message. + """ + INFO = "info" + ERROR = "error" + WARN = "warn" + class DialogNodeAction(object): """ DialogNodeAction. :attr str name: The name of the action. - :attr str action_type: (optional) The type of action to invoke. + :attr str type: (optional) The type of action to invoke. :attr dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :attr str result_variable: The location in the dialog context where the result of the - action is stored. - :attr str credentials: (optional) The name of the context variable that the client - application will use to pass in credentials for the action. + action. + :attr str result_variable: The location in the dialog context where the result + of the action is stored. + :attr str credentials: (optional) The name of the context variable that the + client application will use to pass in credentials for the action. """ def __init__(self, name, result_variable, - action_type=None, + *, + type=None, parameters=None, credentials=None): """ Initialize a DialogNodeAction object. :param str name: The name of the action. - :param str result_variable: The location in the dialog context where the result of - the action is stored. - :param str action_type: (optional) The type of action to invoke. - :param dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :param str credentials: (optional) The name of the context variable that the - client application will use to pass in credentials for the action. + :param str result_variable: The location in the dialog context where the + result of the action is stored. + :param str type: (optional) The type of action to invoke. + :param dict parameters: (optional) A map of key/value pairs to be provided + to the action. + :param str credentials: (optional) The name of the context variable that + the client application will use to pass in credentials for the action. """ self.name = name - self.action_type = action_type + self.type = type self.parameters = parameters self.result_variable = result_variable self.credentials = credentials @@ -447,8 +416,7 @@ def _from_dict(cls, _dict): """Initialize a DialogNodeAction object from a json dictionary.""" args = {} validKeys = [ - 'name', 'action_type', 'type', 'parameters', 'result_variable', - 'credentials' + 'name', 'type', 'parameters', 'result_variable', 'credentials' ] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: @@ -461,8 +429,8 @@ def _from_dict(cls, _dict): raise ValueError( 'Required property \'name\' not present in DialogNodeAction JSON' ) - if 'type' in _dict or 'action_type' in _dict: - args['action_type'] = _dict.get('type') or _dict.get('action_type') + if 'type' in _dict: + args['type'] = _dict.get('type') if 'parameters' in _dict: args['parameters'] = _dict.get('parameters') if 'result_variable' in _dict: @@ -480,8 +448,8 @@ def _to_dict(self): _dict = {} if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name - if hasattr(self, 'action_type') and self.action_type is not None: - _dict['type'] = self.action_type + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type if hasattr(self, 'parameters') and self.parameters is not None: _dict['parameters'] = self.parameters if hasattr(self, @@ -505,14 +473,23 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The type of action to invoke. + """ + CLIENT = "client" + SERVER = "server" + WEB_ACTION = "web-action" + CLOUD_FUNCTION = "cloud-function" + class DialogNodeOutputOptionsElement(object): """ DialogNodeOutputOptionsElement. :attr str label: The user-facing label for the option. - :attr DialogNodeOutputOptionsElementValue value: An object defining the message input - to be sent to the assistant if the user selects the corresponding option. + :attr DialogNodeOutputOptionsElementValue value: An object defining the message + input to be sent to the assistant if the user selects the corresponding option. """ def __init__(self, label, value): @@ -520,8 +497,9 @@ def __init__(self, label, value): Initialize a DialogNodeOutputOptionsElement object. :param str label: The user-facing label for the option. - :param DialogNodeOutputOptionsElementValue value: An object defining the message - input to be sent to the assistant if the user selects the corresponding option. + :param DialogNodeOutputOptionsElementValue value: An object defining the + message input to be sent to the assistant if the user selects the + corresponding option. """ self.label = label self.value = value @@ -580,15 +558,16 @@ class DialogNodeOutputOptionsElementValue(object): An object defining the message input to be sent to the assistant if the user selects the corresponding option. - :attr MessageInput input: (optional) An input object that includes the input text. + :attr MessageInput input: (optional) An input object that includes the input + text. """ - def __init__(self, input=None): + def __init__(self, *, input=None): """ Initialize a DialogNodeOutputOptionsElementValue object. - :param MessageInput input: (optional) An input object that includes the input - text. + :param MessageInput input: (optional) An input object that includes the + input text. """ self.input = input @@ -632,20 +611,21 @@ class DialogNodesVisited(object): """ DialogNodesVisited. - :attr str dialog_node: (optional) A dialog node that was triggered during processing - of the input message. + :attr str dialog_node: (optional) A dialog node that was triggered during + processing of the input message. :attr str title: (optional) The title of the dialog node. :attr str conditions: (optional) The conditions that trigger the dialog node. """ - def __init__(self, dialog_node=None, title=None, conditions=None): + def __init__(self, *, dialog_node=None, title=None, conditions=None): """ Initialize a DialogNodesVisited object. :param str dialog_node: (optional) A dialog node that was triggered during - processing of the input message. + processing of the input message. :param str title: (optional) The title of the dialog node. - :param str conditions: (optional) The conditions that trigger the dialog node. + :param str conditions: (optional) The conditions that trigger the dialog + node. """ self.dialog_node = dialog_node self.title = title @@ -695,227 +675,31 @@ def __ne__(self, other): return not self == other -class DialogRuntimeResponseGeneric(object): - """ - DialogRuntimeResponseGeneric. - - :attr str response_type: The type of response returned by the dialog node. The - specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation feature, - which is only available for Premium users. - :attr str text: (optional) The text of the response. - :attr int time: (optional) How long to pause, in milliseconds. - :attr bool typing: (optional) Whether to send a "user is typing" event during the - pause. - :attr str source: (optional) The URL of the image. - :attr str title: (optional) The title or introductory text to show before the - response. - :attr str description: (optional) The description to show with the the response. - :attr str preference: (optional) The preferred type of control to display. - :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of objects - describing the options from which the user can choose. - :attr str message_to_human_agent: (optional) A message to be sent to the human agent - who will be taking over the conversation. - :attr str topic: (optional) A label identifying the topic of the conversation, derived - from the **user_label** property of the relevant node. - :attr list[DialogSuggestion] suggestions: (optional) An array of objects describing - the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation feature, which is - only available for Premium users. - :attr str header: (optional) The title or introductory text to show before the - response. This text is defined in the search skill configuration. - :attr list[SearchResult] results: (optional) An array of objects containing search - results. - """ - - def __init__(self, - response_type, - text=None, - time=None, - typing=None, - source=None, - title=None, - description=None, - preference=None, - options=None, - message_to_human_agent=None, - topic=None, - suggestions=None, - header=None, - results=None): - """ - Initialize a DialogRuntimeResponseGeneric object. - - :param str response_type: The type of response returned by the dialog node. The - specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation feature, - which is only available for Premium users. - :param str text: (optional) The text of the response. - :param int time: (optional) How long to pause, in milliseconds. - :param bool typing: (optional) Whether to send a "user is typing" event during the - pause. - :param str source: (optional) The URL of the image. - :param str title: (optional) The title or introductory text to show before the - response. - :param str description: (optional) The description to show with the the response. - :param str preference: (optional) The preferred type of control to display. - :param list[DialogNodeOutputOptionsElement] options: (optional) An array of - objects describing the options from which the user can choose. - :param str message_to_human_agent: (optional) A message to be sent to the human - agent who will be taking over the conversation. - :param str topic: (optional) A label identifying the topic of the conversation, - derived from the **user_label** property of the relevant node. - :param list[DialogSuggestion] suggestions: (optional) An array of objects - describing the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation feature, - which is only available for Premium users. - :param str header: (optional) The title or introductory text to show before the - response. This text is defined in the search skill configuration. - :param list[SearchResult] results: (optional) An array of objects containing - search results. - """ - self.response_type = response_type - self.text = text - self.time = time - self.typing = typing - self.source = source - self.title = title - self.description = description - self.preference = preference - self.options = options - self.message_to_human_agent = message_to_human_agent - self.topic = topic - self.suggestions = suggestions - self.header = header - self.results = results - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DialogRuntimeResponseGeneric object from a json dictionary.""" - args = {} - validKeys = [ - 'response_type', 'text', 'time', 'typing', 'source', 'title', - 'description', 'preference', 'options', 'message_to_human_agent', - 'topic', 'suggestions', 'header', 'results' - ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogRuntimeResponseGeneric: ' - + ', '.join(badKeys)) - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') - else: - raise ValueError( - 'Required property \'response_type\' not present in DialogRuntimeResponseGeneric JSON' - ) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'time' in _dict: - args['time'] = _dict.get('time') - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'source' in _dict: - args['source'] = _dict.get('source') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: - args['options'] = [ - DialogNodeOutputOptionsElement._from_dict(x) - for x in (_dict.get('options')) - ] - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'topic' in _dict: - args['topic'] = _dict.get('topic') - if 'suggestions' in _dict: - args['suggestions'] = [ - DialogSuggestion._from_dict(x) - for x in (_dict.get('suggestions')) - ] - if 'header' in _dict: - args['header'] = _dict.get('header') - if 'results' in _dict: - args['results'] = [ - SearchResult._from_dict(x) for x in (_dict.get('results')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'response_type') and self.response_type is not None: - _dict['response_type'] = self.response_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'time') and self.time is not None: - _dict['time'] = self.time - if hasattr(self, 'typing') and self.typing is not None: - _dict['typing'] = self.typing - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'preference') and self.preference is not None: - _dict['preference'] = self.preference - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x._to_dict() for x in self.options] - if hasattr(self, 'message_to_human_agent' - ) and self.message_to_human_agent is not None: - _dict['message_to_human_agent'] = self.message_to_human_agent - if hasattr(self, 'topic') and self.topic is not None: - _dict['topic'] = self.topic - if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x._to_dict() for x in self.suggestions] - if hasattr(self, 'header') and self.header is not None: - _dict['header'] = self.header - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] - return _dict - - def __str__(self): - """Return a `str` version of this DialogRuntimeResponseGeneric object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class DialogSuggestion(object): """ DialogSuggestion. - :attr str label: The user-facing label for the disambiguation option. This label is - taken from the **user_label** property of the corresponding dialog node. - :attr DialogSuggestionValue value: An object defining the message input to be sent to - the assistant if the user selects the corresponding disambiguation option. - :attr dict output: (optional) The dialog output that will be returned from the Watson - Assistant service if the user selects the corresponding option. + :attr str label: The user-facing label for the disambiguation option. This label + is taken from the **user_label** property of the corresponding dialog node. + :attr DialogSuggestionValue value: An object defining the message input to be + sent to the assistant if the user selects the corresponding disambiguation + option. + :attr dict output: (optional) The dialog output that will be returned from the + Watson Assistant service if the user selects the corresponding option. """ - def __init__(self, label, value, output=None): + def __init__(self, label, value, *, output=None): """ Initialize a DialogSuggestion object. - :param str label: The user-facing label for the disambiguation option. This label - is taken from the **user_label** property of the corresponding dialog node. - :param DialogSuggestionValue value: An object defining the message input to be - sent to the assistant if the user selects the corresponding disambiguation option. - :param dict output: (optional) The dialog output that will be returned from the - Watson Assistant service if the user selects the corresponding option. + :param str label: The user-facing label for the disambiguation option. This + label is taken from the **user_label** property of the corresponding dialog + node. + :param DialogSuggestionValue value: An object defining the message input to + be sent to the assistant if the user selects the corresponding + disambiguation option. + :param dict output: (optional) The dialog output that will be returned from + the Watson Assistant service if the user selects the corresponding option. """ self.label = label self.value = value @@ -978,15 +762,16 @@ class DialogSuggestionValue(object): An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. - :attr MessageInput input: (optional) An input object that includes the input text. + :attr MessageInput input: (optional) An input object that includes the input + text. """ - def __init__(self, input=None): + def __init__(self, *, input=None): """ Initialize a DialogSuggestionValue object. - :param MessageInput input: (optional) An input object that includes the input - text. + :param MessageInput input: (optional) An input object that includes the + input text. """ self.input = input @@ -1031,23 +816,25 @@ class MessageContext(object): MessageContext. :attr MessageContextGlobal global_: (optional) Information that is shared by all - skills used by the Assistant. + skills used by the Assistant. :attr MessageContextSkills skills: (optional) Information specific to particular - skills used by the Assistant. - **Note:** Currently, only a single property named `main skill` is supported. This - object contains variables that apply to the dialog skill used by the assistant. + skills used by the Assistant. + **Note:** Currently, only a single property named `main skill` is supported. + This object contains variables that apply to the dialog skill used by the + assistant. """ - def __init__(self, global_=None, skills=None): + def __init__(self, *, global_=None, skills=None): """ Initialize a MessageContext object. - :param MessageContextGlobal global_: (optional) Information that is shared by all - skills used by the Assistant. - :param MessageContextSkills skills: (optional) Information specific to particular - skills used by the Assistant. - **Note:** Currently, only a single property named `main skill` is supported. This - object contains variables that apply to the dialog skill used by the assistant. + :param MessageContextGlobal global_: (optional) Information that is shared + by all skills used by the Assistant. + :param MessageContextSkills skills: (optional) Information specific to + particular skills used by the Assistant. + **Note:** Currently, only a single property named `main skill` is + supported. This object contains variables that apply to the dialog skill + used by the assistant. """ self.global_ = global_ self.skills = skills @@ -1098,16 +885,16 @@ class MessageContextGlobal(object): """ Information that is shared by all skills used by the Assistant. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties that - apply to all skills used by the assistant. + :attr MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. """ - def __init__(self, system=None): + def __init__(self, *, system=None): """ Initialize a MessageContextGlobal object. - :param MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. """ self.system = system @@ -1152,34 +939,36 @@ class MessageContextGlobalSystem(object): """ Built-in system properties that apply to all skills used by the assistant. - :attr str timezone: (optional) The user time zone. The assistant uses the time zone to - correctly resolve relative time references. + :attr str timezone: (optional) The user time zone. The assistant uses the time + zone to correctly resolve relative time references. :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for each - individual end user who accesses the application. For Plus and Premium plans, this - user ID is used to identify unique users for billing purposes. This string cannot - contain carriage return, newline, or tab characters. - :attr int turn_count: (optional) A counter that is automatically incremented 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). + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For Plus and Premium + plans, this user ID is used to identify unique users for billing purposes. This + string cannot contain carriage return, newline, or tab characters. + :attr int turn_count: (optional) A counter that is automatically incremented + 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). """ - def __init__(self, timezone=None, user_id=None, turn_count=None): + def __init__(self, *, timezone=None, user_id=None, turn_count=None): """ Initialize a MessageContextGlobalSystem object. - :param str timezone: (optional) The user time zone. The assistant uses the time - zone to correctly resolve relative time references. - :param str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For Plus and Premium plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. - :param int turn_count: (optional) A counter that is automatically incremented 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). + :param str timezone: (optional) The user time zone. The assistant uses the + time zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + Plus and Premium plans, this user ID is used to identify unique users for + billing purposes. This string cannot contain carriage return, newline, or + tab characters. + :param int turn_count: (optional) A counter that is automatically + incremented 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). """ self.timezone = timezone self.user_id = user_id @@ -1233,16 +1022,16 @@ class MessageContextSkill(object): """ Contains information specific to a particular skill used by the Assistant. - :attr dict user_defined: (optional) Arbitrary variables that can be read and written - by a particular skill. + :attr dict user_defined: (optional) Arbitrary variables that can be read and + written by a particular skill. """ - def __init__(self, user_defined=None): + def __init__(self, *, user_defined=None): """ Initialize a MessageContextSkill object. - :param dict user_defined: (optional) Arbitrary variables that can be read and - written by a particular skill. + :param dict user_defined: (optional) Arbitrary variables that can be read + and written by a particular skill. """ self.user_defined = user_defined @@ -1345,22 +1134,23 @@ class MessageInput(object): """ An input object that includes the input text. - :attr str message_type: (optional) The type of user input. Currently, only text input - is supported. - :attr str text: (optional) The text of the user input. This string cannot contain - carriage return, newline, or tab characters. - :attr MessageInputOptions options: (optional) Optional properties that control how the - assistant responds. - :attr list[RuntimeIntent] intents: (optional) Intents to use when evaluating the user - input. Include intents from the previous response to continue using those intents - rather than trying to recognize intents in the new input. - :attr list[RuntimeEntity] entities: (optional) Entities to use when evaluating the - message. Include entities from the previous response to continue using those entities - rather than detecting entities in the new input. + :attr str message_type: (optional) The type of user input. Currently, only text + input is supported. + :attr str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :attr MessageInputOptions options: (optional) Optional properties that control + how the assistant responds. + :attr list[RuntimeIntent] intents: (optional) Intents to use when evaluating the + user input. Include intents from the previous response to continue using those + intents rather than trying to recognize intents in the new input. + :attr list[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. :attr str suggestion_id: (optional) For internal use only. """ def __init__(self, + *, message_type=None, text=None, options=None, @@ -1370,18 +1160,20 @@ def __init__(self, """ Initialize a MessageInput object. - :param str message_type: (optional) The type of user input. Currently, only text - input is supported. - :param str text: (optional) The text of the user input. This string cannot contain - carriage return, newline, or tab characters. - :param MessageInputOptions options: (optional) Optional properties that control - how the assistant responds. - :param list[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :param list[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. + :param str message_type: (optional) The type of user input. Currently, only + text input is supported. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param MessageInputOptions options: (optional) Optional properties that + control how the assistant responds. + :param list[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param list[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. :param str suggestion_id: (optional) For internal use only. """ self.message_type = message_type @@ -1454,23 +1246,32 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class MessageTypeEnum(Enum): + """ + The type of user input. Currently, only text input is supported. + """ + TEXT = "text" + class MessageInputOptions(object): """ Optional properties that control how the assistant responds. - :attr bool debug: (optional) Whether to return additional diagnostic information. Set - to `true` to return additional information under the `output.debug` key. - :attr bool restart: (optional) Whether to restart dialog processing at the root of the - dialog, regardless of any previously visited nodes. **Note:** This does not affect - `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. Set - to `true` to return all matching intents. + :attr bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information under the + `output.debug` key. + :attr bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :attr bool alternate_intents: (optional) Whether to return more than one intent. + Set to `true` to return all matching intents. :attr bool return_context: (optional) Whether to return session context with the - response. If you specify `true`, the response will include the `context` property. + response. If you specify `true`, the response will include the `context` + property. """ def __init__(self, + *, debug=None, restart=None, alternate_intents=None, @@ -1478,15 +1279,17 @@ def __init__(self, """ Initialize a MessageInputOptions object. - :param bool debug: (optional) Whether to return additional diagnostic information. - Set to `true` to return additional information under the `output.debug` key. - :param bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does not - affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :param bool return_context: (optional) Whether to return session context with the - response. If you specify `true`, the response will include the `context` property. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information under the + `output.debug` key. + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool return_context: (optional) Whether to return session context + with the response. If you specify `true`, the response will include the + `context` property. """ self.debug = debug self.restart = restart @@ -1546,23 +1349,24 @@ class MessageOutput(object): """ Assistant output to be rendered or processed by the client. - :attr list[DialogRuntimeResponseGeneric] generic: (optional) Output intended for any - channel. It is the responsibility of the client application to implement the supported - response types. - :attr list[RuntimeIntent] intents: (optional) An array of intents recognized in the - user input, sorted in descending order of confidence. - :attr list[RuntimeEntity] entities: (optional) An array of entities identified in the - user input. - :attr list[DialogNodeAction] actions: (optional) An array of objects describing any - actions requested by the dialog node. - :attr MessageOutputDebug debug: (optional) Additional detailed information about a - message response and how it was generated. + :attr list[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :attr list[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :attr list[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :attr list[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :attr MessageOutputDebug debug: (optional) Additional detailed information about + a message response and how it was generated. :attr dict user_defined: (optional) An object containing any custom properties - included in the response. This object includes any arbitrary properties defined in the - dialog JSON editor as part of the dialog node output. + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. """ def __init__(self, + *, generic=None, intents=None, entities=None, @@ -1572,20 +1376,21 @@ def __init__(self, """ Initialize a MessageOutput object. - :param list[DialogRuntimeResponseGeneric] generic: (optional) Output intended for - any channel. It is the responsibility of the client application to implement the - supported response types. - :param list[RuntimeIntent] intents: (optional) An array of intents recognized in - the user input, sorted in descending order of confidence. - :param list[RuntimeEntity] entities: (optional) An array of entities identified in - the user input. - :param list[DialogNodeAction] actions: (optional) An array of objects describing - any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information about - a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom properties - included in the response. This object includes any arbitrary properties defined in - the dialog JSON editor as part of the dialog node output. + :param list[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param list[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param list[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param list[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. """ self.generic = generic self.intents = intents @@ -1608,7 +1413,7 @@ def _from_dict(cls, _dict): + ', '.join(badKeys)) if 'generic' in _dict: args['generic'] = [ - DialogRuntimeResponseGeneric._from_dict(x) + RuntimeResponseGeneric._from_dict(x) for x in (_dict.get('generic')) ] if 'intents' in _dict: @@ -1666,18 +1471,19 @@ class MessageOutputDebug(object): Additional detailed information about a message response and how it was generated. :attr list[DialogNodesVisited] nodes_visited: (optional) An array of objects - containing detailed diagnostic information about the nodes that were triggered during - processing of the input message. - :attr list[DialogLogMessage] log_messages: (optional) An array of up to 50 messages - logged with the request. - :attr bool branch_exited: (optional) Assistant sets this to true when this message - response concludes or interrupts a dialog. - :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` by - the Assistant, the `branch_exited_reason` specifies whether the dialog completed by - itself or got interrupted. + containing detailed diagnostic information about the nodes that were triggered + during processing of the input message. + :attr list[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :attr bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` + by the Assistant, the `branch_exited_reason` specifies whether the dialog + completed by itself or got interrupted. """ def __init__(self, + *, nodes_visited=None, log_messages=None, branch_exited=None, @@ -1685,16 +1491,16 @@ def __init__(self, """ Initialize a MessageOutputDebug object. - :param list[DialogNodesVisited] nodes_visited: (optional) An array of objects - containing detailed diagnostic information about the nodes that were triggered - during processing of the input message. + :param list[DialogNodesVisited] nodes_visited: (optional) An array of + objects containing detailed diagnostic information about the nodes that + were triggered during processing of the input message. :param list[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. + messages logged with the request. :param bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :param str branch_exited_reason: (optional) When `branch_exited` is set to `true` - by the Assistant, the `branch_exited_reason` specifies whether the dialog - completed by itself or got interrupted. + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the Assistant, the `branch_exited_reason` specifies whether the + dialog completed by itself or got interrupted. """ self.nodes_visited = nodes_visited self.log_messages = log_messages @@ -1758,31 +1564,39 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class BranchExitedReasonEnum(Enum): + """ + When `branch_exited` is set to `true` by the Assistant, the `branch_exited_reason` + specifies whether the dialog completed by itself or got interrupted. + """ + COMPLETED = "completed" + FALLBACK = "fallback" + class MessageResponse(object): """ A response from the Watson Assistant service. :attr MessageOutput output: Assistant output to be rendered or processed by the - client. - :attr MessageContext context: (optional) State information for the conversation. The - context is stored by the assistant on a per-session basis. You can use this property - to access context variables. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. + client. + :attr MessageContext context: (optional) State information for the conversation. + The context is stored by the assistant on a per-session basis. You can use this + property to access context variables. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. """ - def __init__(self, output, context=None): + def __init__(self, output, *, context=None): """ Initialize a MessageResponse object. - :param MessageOutput output: Assistant output to be rendered or processed by the - client. - :param MessageContext context: (optional) State information for the conversation. - The context is stored by the assistant on a per-session basis. You can use this - property to access context variables. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param MessageContext context: (optional) State information for the + conversation. The context is stored by the assistant on a per-session + basis. You can use this property to access context variables. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. """ self.output = output self.context = context @@ -1836,20 +1650,22 @@ class RuntimeEntity(object): The entity value that was recognized in the user input. :attr str entity: An entity detected in the input. - :attr list[int] location: An array of zero-based character offsets that indicate where - the detected entity values begin and end in the input text. - :attr str value: The term in the input text that was recognized as an entity value. + :attr list[int] location: An array of zero-based character offsets that indicate + where the detected entity values begin and end in the input text. + :attr str value: The term in the input text that was recognized as an entity + value. :attr float confidence: (optional) A decimal percentage that represents Watson's - confidence in the recognized entity. + confidence in the recognized entity. :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 list[CaptureGroup] groups: (optional) The recognized capture groups for + the entity, as defined by the entity pattern. """ def __init__(self, entity, location, value, + *, confidence=None, metadata=None, groups=None): @@ -1857,15 +1673,15 @@ def __init__(self, Initialize a RuntimeEntity object. :param str entity: An entity detected in the input. - :param list[int] location: An array of zero-based character offsets that indicate - where the detected entity values begin and end in the input text. - :param str value: The term in the input text that was recognized as an entity - value. - :param float confidence: (optional) A decimal percentage that represents Watson's - confidence in the recognized entity. + :param list[int] location: An array of zero-based character offsets that + indicate where the detected entity values begin and end in the input text. + :param str value: The term in the input text that was recognized as an + entity value. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the recognized entity. :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 list[CaptureGroup] groups: (optional) The recognized capture groups + for the entity, as defined by the entity pattern. """ self.entity = entity self.location = location @@ -1950,8 +1766,8 @@ class RuntimeIntent(object): An intent identified in the user input. :attr str intent: The name of the recognized intent. - :attr float confidence: A decimal percentage that represents Watson's confidence in - the intent. + :attr float confidence: A decimal percentage that represents Watson's confidence + in the intent. """ def __init__(self, intent, confidence): @@ -1959,8 +1775,8 @@ def __init__(self, intent, confidence): Initialize a RuntimeIntent object. :param str intent: The name of the recognized intent. - :param float confidence: A decimal percentage that represents Watson's confidence - in the intent. + :param float confidence: A decimal percentage that represents Watson's + confidence in the intent. """ self.intent = intent self.confidence = confidence @@ -2013,31 +1829,259 @@ def __ne__(self, other): return not self == other +class RuntimeResponseGeneric(object): + """ + RuntimeResponseGeneric. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + **Note:** The **suggestion** response type is part of the disambiguation + feature, which is only available for Premium users. + :attr str text: (optional) The text of the response. + :attr int time: (optional) How long to pause, in milliseconds. + :attr bool typing: (optional) Whether to send a "user is typing" event during + the pause. + :attr str source: (optional) The URL of the image. + :attr str title: (optional) The title or introductory text to show before the + response. + :attr str description: (optional) The description to show with the the response. + :attr str preference: (optional) The preferred type of control to display. + :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of + objects describing the options from which the user can choose. + :attr str message_to_human_agent: (optional) A message to be sent to the human + agent who will be taking over the conversation. + :attr str topic: (optional) A label identifying the topic of the conversation, + derived from the **user_label** property of the relevant node. + :attr list[DialogSuggestion] suggestions: (optional) An array of objects + describing the possible matching dialog nodes from which the user can choose. + **Note:** The **suggestions** property is part of the disambiguation feature, + which is only available for Premium users. + :attr str header: (optional) The title or introductory text to show before the + response. This text is defined in the search skill configuration. + :attr list[SearchResult] results: (optional) An array of objects containing + search results. + """ + + def __init__(self, + response_type, + *, + text=None, + time=None, + typing=None, + source=None, + title=None, + description=None, + preference=None, + options=None, + message_to_human_agent=None, + topic=None, + suggestions=None, + header=None, + results=None): + """ + Initialize a RuntimeResponseGeneric object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + **Note:** The **suggestion** response type is part of the disambiguation + feature, which is only available for Premium users. + :param str text: (optional) The text of the response. + :param int time: (optional) How long to pause, in milliseconds. + :param bool typing: (optional) Whether to send a "user is typing" event + during the pause. + :param str source: (optional) The URL of the image. + :param str title: (optional) The title or introductory text to show before + the response. + :param str description: (optional) The description to show with the the + response. + :param str preference: (optional) The preferred type of control to display. + :param list[DialogNodeOutputOptionsElement] options: (optional) An array of + objects describing the options from which the user can choose. + :param str message_to_human_agent: (optional) A message to be sent to the + human agent who will be taking over the conversation. + :param str topic: (optional) A label identifying the topic of the + conversation, derived from the **user_label** property of the relevant + node. + :param list[DialogSuggestion] suggestions: (optional) An array of objects + describing the possible matching dialog nodes from which the user can + choose. + **Note:** The **suggestions** property is part of the disambiguation + feature, which is only available for Premium users. + :param str header: (optional) The title or introductory text to show before + the response. This text is defined in the search skill configuration. + :param list[SearchResult] results: (optional) An array of objects + containing search results. + """ + self.response_type = response_type + self.text = text + self.time = time + self.typing = typing + self.source = source + self.title = title + self.description = description + self.preference = preference + self.options = options + self.message_to_human_agent = message_to_human_agent + self.topic = topic + self.suggestions = suggestions + self.header = header + self.results = results + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + args = {} + validKeys = [ + 'response_type', 'text', 'time', 'typing', 'source', 'title', + 'description', 'preference', 'options', 'message_to_human_agent', + 'topic', 'suggestions', 'header', 'results' + ] + badKeys = set(_dict.keys()) - set(validKeys) + if badKeys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeResponseGeneric: ' + + ', '.join(badKeys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGeneric JSON' + ) + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'time' in _dict: + args['time'] = _dict.get('time') + if 'typing' in _dict: + args['typing'] = _dict.get('typing') + if 'source' in _dict: + args['source'] = _dict.get('source') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'preference' in _dict: + args['preference'] = _dict.get('preference') + if 'options' in _dict: + args['options'] = [ + DialogNodeOutputOptionsElement._from_dict(x) + for x in (_dict.get('options')) + ] + if 'message_to_human_agent' in _dict: + args['message_to_human_agent'] = _dict.get('message_to_human_agent') + if 'topic' in _dict: + args['topic'] = _dict.get('topic') + if 'suggestions' in _dict: + args['suggestions'] = [ + DialogSuggestion._from_dict(x) + for x in (_dict.get('suggestions')) + ] + if 'header' in _dict: + args['header'] = _dict.get('header') + if 'results' in _dict: + args['results'] = [ + SearchResult._from_dict(x) for x in (_dict.get('results')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'time') and self.time is not None: + _dict['time'] = self.time + if hasattr(self, 'typing') and self.typing is not None: + _dict['typing'] = self.typing + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'preference') and self.preference is not None: + _dict['preference'] = self.preference + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = [x._to_dict() for x in self.options] + if hasattr(self, 'message_to_human_agent' + ) and self.message_to_human_agent is not None: + _dict['message_to_human_agent'] = self.message_to_human_agent + if hasattr(self, 'topic') and self.topic is not None: + _dict['topic'] = self.topic + if hasattr(self, 'suggestions') and self.suggestions is not None: + _dict['suggestions'] = [x._to_dict() for x in self.suggestions] + if hasattr(self, 'header') and self.header is not None: + _dict['header'] = self.header + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + return _dict + + def __str__(self): + """Return a `str` version of this RuntimeResponseGeneric object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + **Note:** The **suggestion** response type is part of the disambiguation feature, + which is only available for Premium users. + """ + TEXT = "text" + PAUSE = "pause" + IMAGE = "image" + OPTION = "option" + CONNECT_TO_AGENT = "connect_to_agent" + SUGGESTION = "suggestion" + SEARCH = "search" + + class PreferenceEnum(Enum): + """ + The preferred type of control to display. + """ + DROPDOWN = "dropdown" + BUTTON = "button" + + class SearchResult(object): """ SearchResult. :attr str id: The unique identifier of the document in the Discovery service - collection. - This property is included in responses from search skills, which are a beta feature - available only to Plus or Premium plan users. + collection. + This property is included in responses from search skills, which are a beta + feature available only to Plus or Premium plan users. :attr SearchResultMetadata result_metadata: An object containing search result - metadata from the Discovery service. - :attr str body: (optional) A description of the search result. This is taken from an - abstract, summary, or highlight field in the Discovery service response, as specified - in the search skill configuration. - :attr str title: (optional) The title of the search result. This is taken from a title - or name field in the Discovery service response, as specified in the search skill - configuration. + metadata from the Discovery service. + :attr str body: (optional) A description of the search result. This is taken + from an abstract, summary, or highlight field in the Discovery service response, + as specified in the search skill configuration. + :attr str title: (optional) The title of the search result. This is taken from a + title or name field in the Discovery service response, as specified in the + search skill configuration. :attr str url: (optional) The URL of the original data object in its native data - source. - :attr SearchResultHighlight highlight: (optional) An object containing segments of - text from search results with query-matching text highlighted using HTML tags. + source. + :attr SearchResultHighlight highlight: (optional) An object containing segments + of text from search results with query-matching text highlighted using HTML + tags. """ def __init__(self, id, result_metadata, + *, body=None, title=None, url=None, @@ -2045,23 +2089,23 @@ def __init__(self, """ Initialize a SearchResult object. - :param str id: The unique identifier of the document in the Discovery service - collection. - This property is included in responses from search skills, which are a beta - feature available only to Plus or Premium plan users. - :param SearchResultMetadata result_metadata: An object containing search result - metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is taken from - an abstract, summary, or highlight field in the Discovery service response, as - specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken from a - title or name field in the Discovery service response, as specified in the search - skill configuration. - :param str url: (optional) The URL of the original data object in its native data - source. - :param SearchResultHighlight highlight: (optional) An object containing segments - of text from search results with query-matching text highlighted using HTML - tags. + :param str id: The unique identifier of the document in the Discovery + service collection. + This property is included in responses from search skills, which are a beta + feature available only to Plus or Premium plan users. + :param SearchResultMetadata result_metadata: An object containing search + result metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is + taken from an abstract, summary, or highlight field in the Discovery + service response, as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken + from a title or name field in the Discovery service response, as specified + in the search skill configuration. + :param str url: (optional) The URL of the original data object in its + native data source. + :param SearchResultHighlight highlight: (optional) An object containing + segments of text from search results with query-matching text highlighted + using HTML tags. """ self.id = id self.result_metadata = result_metadata @@ -2143,24 +2187,29 @@ class SearchResultHighlight(object): An object containing segments of text from search results with query-matching text highlighted using HTML tags. - :attr list[str] body: (optional) An array of strings containing segments taken from - body text in the search results, with query-matching substrings highlighted. - :attr list[str] title: (optional) An array of strings containing segments taken from - title text in the search results, with query-matching substrings highlighted. - :attr list[str] url: (optional) An array of strings containing segments taken from - URLs in the search results, with query-matching substrings highlighted. + :attr list[str] body: (optional) An array of strings containing segments taken + from body text in the search results, with query-matching substrings + highlighted. + :attr list[str] title: (optional) An array of strings containing segments taken + from title text in the search results, with query-matching substrings + highlighted. + :attr list[str] url: (optional) An array of strings containing segments taken + from URLs in the search results, with query-matching substrings highlighted. """ - def __init__(self, body=None, title=None, url=None, **kwargs): + def __init__(self, *, body=None, title=None, url=None, **kwargs): """ Initialize a SearchResultHighlight object. - :param list[str] body: (optional) An array of strings containing segments taken - from body text in the search results, with query-matching substrings highlighted. - :param list[str] title: (optional) An array of strings containing segments taken - from title text in the search results, with query-matching substrings highlighted. - :param list[str] url: (optional) An array of strings containing segments taken - from URLs in the search results, with query-matching substrings highlighted. + :param list[str] body: (optional) An array of strings containing segments + taken from body text in the search results, with query-matching substrings + highlighted. + :param list[str] title: (optional) An array of strings containing segments + taken from title text in the search results, with query-matching substrings + highlighted. + :param list[str] url: (optional) An array of strings containing segments + taken from URLs in the search results, with query-matching substrings + highlighted. :param **kwargs: (optional) Any additional properties. """ self.body = body @@ -2230,24 +2279,24 @@ class SearchResultMetadata(object): """ An object containing search result metadata from the Discovery service. - :attr float confidence: (optional) The confidence score for the given result. For more - information about how the confidence is calculated, see the Discovery service - [documentation](../discovery#query-your-collection). - :attr float score: (optional) An unbounded measure of the relevance of a particular - result, dependent on the query and matching document. A higher score indicates a - greater match to the query parameters. + :attr float confidence: (optional) The confidence score for the given result. + For more information about how the confidence is calculated, see the Discovery + service [documentation](../discovery#query-your-collection). + :attr float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher score + indicates a greater match to the query parameters. """ - def __init__(self, confidence=None, score=None): + def __init__(self, *, confidence=None, score=None): """ Initialize a SearchResultMetadata object. - :param float confidence: (optional) The confidence score for the given result. For - more information about how the confidence is calculated, see the Discovery service - [documentation](../discovery#query-your-collection). + :param float confidence: (optional) The confidence score for the given + result. For more information about how the confidence is calculated, see + the Discovery service [documentation](../discovery#query-your-collection). :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. + particular result, dependent on the query and matching document. A higher + score indicates a greater match to the query parameters. """ self.confidence = confidence self.score = score From 1e2d48fdff192643d5b895444f13c5537208e4c7 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 18:10:07 -0400 Subject: [PATCH 006/455] examples(assistantv2):Update assistantv2 examples --- examples/assistant_v1.py | 2 +- examples/assistant_v2.py | 12 +++--------- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/examples/assistant_v1.py b/examples/assistant_v1.py index 6de775b22..d06361a78 100644 --- a/examples/assistant_v1.py +++ b/examples/assistant_v1.py @@ -3,7 +3,7 @@ from ibm_watson import AssistantV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -authenticator = IAMAuthenticator('your api key') +authenticator = IAMAuthenticator('your apikey') assistant = AssistantV1( version='2018-07-10', ## url is optional, and defaults to the URL below. Use the correct URL for your region. diff --git a/examples/assistant_v2.py b/examples/assistant_v2.py index 90b9a2c43..5622fdc7b 100644 --- a/examples/assistant_v2.py +++ b/examples/assistant_v2.py @@ -1,20 +1,14 @@ from __future__ import print_function import json from ibm_watson import AssistantV2 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -# If service instance provides API key authentication +authenticator = IAMAuthenticator('your apikey') assistant = AssistantV2( version='2018-09-20', ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/assistant/api', - iam_apikey='YOUR APIKEY') - -# assistant = AssistantV2( -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD', -# ## url is optional, and defaults to the URL below. Use the correct URL for your region. -# url='https://gateway.watsonplatform.net/assistant/api', -# version='2018-09-20') + authenticator=authenticator) ######################### # Sessions From f94e5d5f4230a8da947e283510c2960cf8771d97 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 18:11:52 -0400 Subject: [PATCH 007/455] test(assistantv2): Update assistantv2 tests --- test/unit/test_assistant_v2.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 9931c0071..d2b3ad534 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -2,6 +2,7 @@ import json import responses import ibm_watson +from ibm_cloud_sdk_core.authenticators import BasicAuthenticator platform_url = 'https://gateway.watsonplatform.net' service_path = '/assistant/api' @@ -18,8 +19,9 @@ def test_create_session(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV2( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) session = service.create_session('bogus_id').get_result() assert len(responses.calls) == 1 assert responses.calls[0].request.url.startswith(url) @@ -38,8 +40,9 @@ def test_delete_session(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV2( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) delete_session = service.delete_session('bogus_id', 'session_id').get_result() assert len(responses.calls) == 1 @@ -73,8 +76,9 @@ def test_message(): body=json.dumps(response), status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV2( - username='username', password='password', version='2017-02-03') + version='2017-02-03', authenticator=authenticator) message = service.message( 'bogus_id', 'session_id', input={ 'text': 'What\'s the weather like?' From 158c451634b31ccb3c40fee0b43d86ad04a721e4 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 18:13:13 -0400 Subject: [PATCH 008/455] feat(compare comply): Generate compare and comply --- ibm_watson/compare_comply_v1.py | 2456 ++++++++++++++++++------------- 1 file changed, 1467 insertions(+), 989 deletions(-) diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 5813d48e1..1f7cd4cdc 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -18,12 +18,12 @@ critical aspects of the documents. """ -from __future__ import absolute_import - import json from .common import get_sdk_headers +from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime +from ibm_cloud_sdk_core import get_authenticator_from_environment from os.path import basename ############################################################################## @@ -40,16 +40,8 @@ def __init__( self, version, url=default_url, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, - username=None, - password=None, + authenticator=None, + disable_ssl_verification=False, ): """ Construct a new client for the Compare Comply service. @@ -69,62 +61,21 @@ def __init__( "https://gateway.watsonplatform.net/compare-comply/api/compare-comply/api"). The base url may differ between IBM Cloud regions. - :param str username: The username used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str password: The password used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ + if not authenticator: + authenticator = get_authenticator_from_environment('Compare Comply') + BaseService.__init__( self, - vcap_services_name='compare-comply', url=url, - username=username, - password=password, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Compare Comply', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Compare Comply') self.version = version ######################### @@ -133,7 +84,7 @@ def __init__( def convert_to_html(self, file, - filename=None, + *, file_content_type=None, model=None, **kwargs): @@ -143,13 +94,12 @@ def convert_to_html(self, Converts a document to HTML. :param file file: The document to convert. - :param str filename: The filename for file. - :param str file_content_type: The content type of file. - :param str model: The analysis model to be used by the service. For the **Element - classification** and **Compare two documents** methods, the default is - `contracts`. For the **Extract tables** method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in - batch-processing requests. + :param str file_content_type: (optional) The content type of file. + :param str model: (optional) The analysis model to be used by the service. + For the **Element classification** and **Compare two documents** methods, + the default is `contracts`. For the **Extract tables** method, the default + is `tables`. These defaults apply to the standalone methods as well as to + the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -167,21 +117,18 @@ def convert_to_html(self, params = {'version': self.version, 'model': model} form_data = {} - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data['file'] = (filename, file, file_content_type or + form_data['file'] = (None, file, file_content_type or 'application/octet-stream') url = '/v1/html_conversion' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response ######################### @@ -190,6 +137,7 @@ def convert_to_html(self, def classify_elements(self, file, + *, file_content_type=None, model=None, **kwargs): @@ -199,12 +147,12 @@ def classify_elements(self, Analyzes the structural and semantic elements of a document. :param file file: The document to classify. - :param str file_content_type: The content type of file. - :param str model: The analysis model to be used by the service. For the **Element - classification** and **Compare two documents** methods, the default is - `contracts`. For the **Extract tables** method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in - batch-processing requests. + :param str file_content_type: (optional) The content type of file. + :param str model: (optional) The analysis model to be used by the service. + For the **Element classification** and **Compare two documents** methods, + the default is `contracts`. For the **Extract tables** method, the default + is `tables`. These defaults apply to the standalone methods as well as to + the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -227,20 +175,25 @@ def classify_elements(self, 'application/octet-stream') url = '/v1/element_classification' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response ######################### # Tables ######################### - def extract_tables(self, file, file_content_type=None, model=None, + def extract_tables(self, + file, + *, + file_content_type=None, + model=None, **kwargs): """ Extract a document's tables. @@ -248,12 +201,12 @@ def extract_tables(self, file, file_content_type=None, model=None, Analyzes the tables in a document. :param file file: The document on which to run table extraction. - :param str file_content_type: The content type of file. - :param str model: The analysis model to be used by the service. For the **Element - classification** and **Compare two documents** methods, the default is - `contracts`. For the **Extract tables** method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in - batch-processing requests. + :param str file_content_type: (optional) The content type of file. + :param str model: (optional) The analysis model to be used by the service. + For the **Element classification** and **Compare two documents** methods, + the default is `contracts`. For the **Extract tables** method, the default + is `tables`. These defaults apply to the standalone methods as well as to + the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -275,13 +228,14 @@ def extract_tables(self, file, file_content_type=None, model=None, 'application/octet-stream') url = '/v1/tables' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response ######################### @@ -291,6 +245,7 @@ def extract_tables(self, file, file_content_type=None, model=None, def compare_documents(self, file_1, file_2, + *, file_1_content_type=None, file_2_content_type=None, file_1_label=None, @@ -304,15 +259,15 @@ def compare_documents(self, :param file file_1: The first document to compare. :param file file_2: The second document to compare. - :param str file_1_content_type: The content type of file_1. - :param str file_2_content_type: The content type of file_2. - :param str file_1_label: A text label for the first document. - :param str file_2_label: A text label for the second document. - :param str model: The analysis model to be used by the service. For the **Element - classification** and **Compare two documents** methods, the default is - `contracts`. For the **Extract tables** method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in - batch-processing requests. + :param str file_1_content_type: (optional) The content type of file_1. + :param str file_2_content_type: (optional) The content type of file_2. + :param str file_1_label: (optional) A text label for the first document. + :param str file_2_label: (optional) A text label for the second document. + :param str model: (optional) The analysis model to be used by the service. + For the **Element classification** and **Compare two documents** methods, + the default is `contracts`. For the **Extract tables** method, the default + is `tables`. These defaults apply to the standalone methods as well as to + the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -344,20 +299,26 @@ def compare_documents(self, 'application/octet-stream') url = '/v1/comparison' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response ######################### # Feedback ######################### - def add_feedback(self, feedback_data, user_id=None, comment=None, **kwargs): + def add_feedback(self, + feedback_data, + *, + user_id=None, + comment=None, + **kwargs): """ Add feedback. @@ -368,8 +329,9 @@ def add_feedback(self, feedback_data, user_id=None, comment=None, **kwargs): feedback is used to suggest future updates to the training model. :param FeedbackDataInput feedback_data: Feedback data for submission. - :param str user_id: An optional string identifying the user. - :param str comment: An optional comment on or description of the feedback. + :param str user_id: (optional) An optional string identifying the user. + :param str comment: (optional) An optional comment on or description of the + feedback. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -394,16 +356,18 @@ def add_feedback(self, feedback_data, user_id=None, comment=None, **kwargs): } url = '/v1/feedback' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def list_feedback(self, + *, feedback_type=None, before=None, after=None, @@ -426,50 +390,60 @@ def list_feedback(self, Lists the feedback in a document. - :param str feedback_type: An optional string that filters the output to include - only feedback with the specified feedback type. The only permitted value is - `element_classification`. - :param date before: An optional string in the format `YYYY-MM-DD` that filters the - output to include only feedback that was added before the specified date. - :param date after: An optional string in the format `YYYY-MM-DD` that filters the - output to include only feedback that was added after the specified date. - :param str document_title: An optional string that filters the output to include - only feedback from the document with the specified `document_title`. - :param str model_id: An optional string that filters the output to include only - feedback with the specified `model_id`. The only permitted value is `contracts`. - :param str model_version: An optional string that filters the output to include - only feedback with the specified `model_version`. - :param str category_removed: An optional string in the form of a comma-separated - list of categories. If it is specified, the service filters the output to include - only feedback that has at least one category from the list removed. - :param str category_added: An optional string in the form of a comma-separated - list of categories. If this is specified, the service filters the output to - include only feedback that has at least one category from the list added. - :param str category_not_changed: An optional string in the form of a - comma-separated list of categories. If this is specified, the service filters the - output to include only feedback that has at least one category from the list - unchanged. - :param str type_removed: An optional string of comma-separated `nature`:`party` - pairs. If this is specified, the service filters the output to include only - feedback that has at least one `nature`:`party` pair from the list removed. - :param str type_added: An optional string of comma-separated `nature`:`party` - pairs. If this is specified, the service filters the output to include only - feedback that has at least one `nature`:`party` pair from the list removed. - :param str type_not_changed: An optional string of comma-separated - `nature`:`party` pairs. If this is specified, the service filters the output to - include only feedback that has at least one `nature`:`party` pair from the list - unchanged. - :param int page_limit: An optional integer specifying the number of documents that - you want the service to return. - :param str cursor: An optional string that returns the set of documents after the - previous set. Use this parameter with the `page_limit` parameter. - :param str sort: An optional comma-separated list of fields in the document to - sort on. You can optionally specify the sort direction by prefixing the value of - the field with `-` for descending order or `+` for ascending order (the default). - Currently permitted sorting fields are `created`, `user_id`, and `document_title`. - :param bool include_total: An optional boolean value. If specified as `true`, the - `pagination` object in the output includes a value called `total` that gives the - total count of feedback created. + :param str feedback_type: (optional) An optional string that filters the + output to include only feedback with the specified feedback type. The only + permitted value is `element_classification`. + :param date before: (optional) An optional string in the format + `YYYY-MM-DD` that filters the output to include only feedback that was + added before the specified date. + :param date after: (optional) An optional string in the format `YYYY-MM-DD` + that filters the output to include only feedback that was added after the + specified date. + :param str document_title: (optional) An optional string that filters the + output to include only feedback from the document with the specified + `document_title`. + :param str model_id: (optional) An optional string that filters the output + to include only feedback with the specified `model_id`. The only permitted + value is `contracts`. + :param str model_version: (optional) An optional string that filters the + output to include only feedback with the specified `model_version`. + :param str category_removed: (optional) An optional string in the form of a + comma-separated list of categories. If it is specified, the service filters + the output to include only feedback that has at least one category from the + list removed. + :param str category_added: (optional) An optional string in the form of a + comma-separated list of categories. If this is specified, the service + filters the output to include only feedback that has at least one category + from the list added. + :param str category_not_changed: (optional) An optional string in the form + of a comma-separated list of categories. If this is specified, the service + filters the output to include only feedback that has at least one category + from the list unchanged. + :param str type_removed: (optional) An optional string of comma-separated + `nature`:`party` pairs. If this is specified, the service filters the + output to include only feedback that has at least one `nature`:`party` pair + from the list removed. + :param str type_added: (optional) An optional string of comma-separated + `nature`:`party` pairs. If this is specified, the service filters the + output to include only feedback that has at least one `nature`:`party` pair + from the list removed. + :param str type_not_changed: (optional) An optional string of + comma-separated `nature`:`party` pairs. If this is specified, the service + filters the output to include only feedback that has at least one + `nature`:`party` pair from the list unchanged. + :param int page_limit: (optional) An optional integer specifying the number + of documents that you want the service to return. + :param str cursor: (optional) An optional string that returns the set of + documents after the previous set. Use this parameter with the `page_limit` + parameter. + :param str sort: (optional) An optional comma-separated list of fields in + the document to sort on. You can optionally specify the sort direction by + prefixing the value of the field with `-` for descending order or `+` for + ascending order (the default). Currently permitted sorting fields are + `created`, `user_id`, and `document_title`. + :param bool include_total: (optional) An optional boolean value. If + specified as `true`, the `pagination` object in the output includes a value + called `total` that gives the total count of feedback created. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -502,27 +476,28 @@ def list_feedback(self, } url = '/v1/feedback' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response - def get_feedback(self, feedback_id, model=None, **kwargs): + def get_feedback(self, feedback_id, *, model=None, **kwargs): """ Get a specified feedback entry. Gets a feedback entry with a specified `feedback_id`. - :param str feedback_id: A string that specifies the feedback entry to be included - in the output. - :param str model: The analysis model to be used by the service. For the **Element - classification** and **Compare two documents** methods, the default is - `contracts`. For the **Extract tables** method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in - batch-processing requests. + :param str feedback_id: A string that specifies the feedback entry to be + included in the output. + :param str model: (optional) The analysis model to be used by the service. + For the **Element classification** and **Compare two documents** methods, + the default is `contracts`. For the **Extract tables** method, the default + is `tables`. These defaults apply to the standalone methods as well as to + the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -540,27 +515,28 @@ def get_feedback(self, feedback_id, model=None, **kwargs): params = {'version': self.version, 'model': model} url = '/v1/feedback/{0}'.format(*self._encode_path_vars(feedback_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response - def delete_feedback(self, feedback_id, model=None, **kwargs): + def delete_feedback(self, feedback_id, *, model=None, **kwargs): """ Delete a specified feedback entry. Deletes a feedback entry with a specified `feedback_id`. - :param str feedback_id: A string that specifies the feedback entry to be deleted - from the document. - :param str model: The analysis model to be used by the service. For the **Element - classification** and **Compare two documents** methods, the default is - `contracts`. For the **Extract tables** method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in - batch-processing requests. + :param str feedback_id: A string that specifies the feedback entry to be + deleted from the document. + :param str model: (optional) The analysis model to be used by the service. + For the **Element classification** and **Compare two documents** methods, + the default is `contracts`. For the **Extract tables** method, the default + is `tables`. These defaults apply to the standalone methods as well as to + the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -578,12 +554,13 @@ def delete_feedback(self, feedback_id, model=None, **kwargs): params = {'version': self.version, 'model': model} url = '/v1/feedback/{0}'.format(*self._encode_path_vars(feedback_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -598,6 +575,7 @@ def create_batch(self, output_credentials_file, output_bucket_location, output_bucket_name, + *, model=None, **kwargs): """ @@ -610,27 +588,32 @@ def create_batch(self, batch processing](https://cloud.ibm.com/docs/services/compare-comply?topic=compare-comply-batching#before-you-batch). - :param str function: The Compare and Comply method to run across the submitted - input documents. - :param file input_credentials_file: A JSON file containing the input Cloud Object - Storage credentials. At a minimum, the credentials must enable `READ` permissions - on the bucket defined by the `input_bucket_name` parameter. - :param str input_bucket_location: The geographical location of the Cloud Object - Storage input bucket as listed on the **Endpoint** tab of your Cloud Object - Storage instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. - :param str input_bucket_name: The name of the Cloud Object Storage input bucket. - :param file output_credentials_file: A JSON file that lists the Cloud Object - Storage output credentials. At a minimum, the credentials must enable `READ` and - `WRITE` permissions on the bucket defined by the `output_bucket_name` parameter. - :param str output_bucket_location: The geographical location of the Cloud Object - Storage output bucket as listed on the **Endpoint** tab of your Cloud Object - Storage instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. - :param str output_bucket_name: The name of the Cloud Object Storage output bucket. - :param str model: The analysis model to be used by the service. For the **Element - classification** and **Compare two documents** methods, the default is - `contracts`. For the **Extract tables** method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in - batch-processing requests. + :param str function: The Compare and Comply method to run across the + submitted input documents. + :param file input_credentials_file: A JSON file containing the input Cloud + Object Storage credentials. At a minimum, the credentials must enable + `READ` permissions on the bucket defined by the `input_bucket_name` + parameter. + :param str input_bucket_location: The geographical location of the Cloud + Object Storage input bucket as listed on the **Endpoint** tab of your Cloud + Object Storage instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. + :param str input_bucket_name: The name of the Cloud Object Storage input + bucket. + :param file output_credentials_file: A JSON file that lists the Cloud + Object Storage output credentials. At a minimum, the credentials must + enable `READ` and `WRITE` permissions on the bucket defined by the + `output_bucket_name` parameter. + :param str output_bucket_location: The geographical location of the Cloud + Object Storage output bucket as listed on the **Endpoint** tab of your + Cloud Object Storage instance; for example, `us-geo`, `eu-geo`, or + `ap-geo`. + :param str output_bucket_name: The name of the Cloud Object Storage output + bucket. + :param str model: (optional) The analysis model to be used by the service. + For the **Element classification** and **Compare two documents** methods, + the default is `contracts`. For the **Extract tables** method, the default + is `tables`. These defaults apply to the standalone methods as well as to + the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -673,13 +656,14 @@ def create_batch(self, 'text/plain') url = '/v1/batches' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response def list_batches(self, **kwargs): @@ -702,12 +686,13 @@ def list_batches(self, **kwargs): params = {'version': self.version} url = '/v1/batches' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_batch(self, batch_id, **kwargs): @@ -716,8 +701,8 @@ def get_batch(self, batch_id, **kwargs): Gets information about a batch-processing job with a specified ID. - :param str batch_id: The ID of the batch-processing job whose information you want - to retrieve. + :param str batch_id: The ID of the batch-processing job whose information + you want to retrieve. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -735,15 +720,16 @@ def get_batch(self, batch_id, **kwargs): params = {'version': self.version} url = '/v1/batches/{0}'.format(*self._encode_path_vars(batch_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response - def update_batch(self, batch_id, action, model=None, **kwargs): + def update_batch(self, batch_id, action, *, model=None, **kwargs): """ Update a pending or active batch-processing job. @@ -752,12 +738,12 @@ def update_batch(self, batch_id, action, model=None, **kwargs): :param str batch_id: The ID of the batch-processing job you want to update. :param str action: The action you want to perform on the specified - batch-processing job. - :param str model: The analysis model to be used by the service. For the **Element - classification** and **Compare two documents** methods, the default is - `contracts`. For the **Extract tables** method, the default is `tables`. These - defaults apply to the standalone methods as well as to the methods' use in - batch-processing requests. + batch-processing job. + :param str model: (optional) The analysis model to be used by the service. + For the **Element classification** and **Compare two documents** methods, + the default is `contracts`. For the **Extract tables** method, the default + is `tables`. These defaults apply to the standalone methods as well as to + the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -777,15 +763,204 @@ def update_batch(self, batch_id, action, model=None, **kwargs): params = {'version': self.version, 'action': action, 'model': model} url = '/v1/batches/{0}'.format(*self._encode_path_vars(batch_id)) - response = self.request( + request = self.prepare_request( method='PUT', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response +class ConvertToHtmlEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_PDF = 'application/pdf' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + IMAGE_BMP = 'image/bmp' + IMAGE_GIF = 'image/gif' + IMAGE_JPEG = 'image/jpeg' + IMAGE_PNG = 'image/png' + IMAGE_TIFF = 'image/tiff' + TEXT_PLAIN = 'text/plain' + + class Model(Enum): + """ + The analysis model to be used by the service. For the **Element classification** + and **Compare two documents** methods, the default is `contracts`. For the + **Extract tables** method, the default is `tables`. These defaults apply to the + standalone methods as well as to the methods' use in batch-processing requests. + """ + CONTRACTS = 'contracts' + TABLES = 'tables' + + +class ClassifyElementsEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_PDF = 'application/pdf' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + IMAGE_BMP = 'image/bmp' + IMAGE_GIF = 'image/gif' + IMAGE_JPEG = 'image/jpeg' + IMAGE_PNG = 'image/png' + IMAGE_TIFF = 'image/tiff' + + class Model(Enum): + """ + The analysis model to be used by the service. For the **Element classification** + and **Compare two documents** methods, the default is `contracts`. For the + **Extract tables** method, the default is `tables`. These defaults apply to the + standalone methods as well as to the methods' use in batch-processing requests. + """ + CONTRACTS = 'contracts' + TABLES = 'tables' + + +class ExtractTablesEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_PDF = 'application/pdf' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + IMAGE_BMP = 'image/bmp' + IMAGE_GIF = 'image/gif' + IMAGE_JPEG = 'image/jpeg' + IMAGE_PNG = 'image/png' + IMAGE_TIFF = 'image/tiff' + TEXT_PLAIN = 'text/plain' + + class Model(Enum): + """ + The analysis model to be used by the service. For the **Element classification** + and **Compare two documents** methods, the default is `contracts`. For the + **Extract tables** method, the default is `tables`. These defaults apply to the + standalone methods as well as to the methods' use in batch-processing requests. + """ + CONTRACTS = 'contracts' + TABLES = 'tables' + + +class CompareDocumentsEnums(object): + + class File1ContentType(Enum): + """ + The content type of file_1. + """ + APPLICATION_PDF = 'application/pdf' + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + IMAGE_BMP = 'image/bmp' + IMAGE_GIF = 'image/gif' + IMAGE_JPEG = 'image/jpeg' + IMAGE_PNG = 'image/png' + IMAGE_TIFF = 'image/tiff' + + class File2ContentType(Enum): + """ + The content type of file_2. + """ + APPLICATION_PDF = 'application/pdf' + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + IMAGE_BMP = 'image/bmp' + IMAGE_GIF = 'image/gif' + IMAGE_JPEG = 'image/jpeg' + IMAGE_PNG = 'image/png' + IMAGE_TIFF = 'image/tiff' + + class Model(Enum): + """ + The analysis model to be used by the service. For the **Element classification** + and **Compare two documents** methods, the default is `contracts`. For the + **Extract tables** method, the default is `tables`. These defaults apply to the + standalone methods as well as to the methods' use in batch-processing requests. + """ + CONTRACTS = 'contracts' + TABLES = 'tables' + + +class GetFeedbackEnums(object): + + class Model(Enum): + """ + The analysis model to be used by the service. For the **Element classification** + and **Compare two documents** methods, the default is `contracts`. For the + **Extract tables** method, the default is `tables`. These defaults apply to the + standalone methods as well as to the methods' use in batch-processing requests. + """ + CONTRACTS = 'contracts' + TABLES = 'tables' + + +class DeleteFeedbackEnums(object): + + class Model(Enum): + """ + The analysis model to be used by the service. For the **Element classification** + and **Compare two documents** methods, the default is `contracts`. For the + **Extract tables** method, the default is `tables`. These defaults apply to the + standalone methods as well as to the methods' use in batch-processing requests. + """ + CONTRACTS = 'contracts' + TABLES = 'tables' + + +class CreateBatchEnums(object): + + class Function(Enum): + """ + The Compare and Comply method to run across the submitted input documents. + """ + HTML_CONVERSION = 'html_conversion' + ELEMENT_CLASSIFICATION = 'element_classification' + TABLES = 'tables' + + class Model(Enum): + """ + The analysis model to be used by the service. For the **Element classification** + and **Compare two documents** methods, the default is `contracts`. For the + **Extract tables** method, the default is `tables`. These defaults apply to the + standalone methods as well as to the methods' use in batch-processing requests. + """ + CONTRACTS = 'contracts' + TABLES = 'tables' + + +class UpdateBatchEnums(object): + + class Action(Enum): + """ + The action you want to perform on the specified batch-processing job. + """ + RESCAN = 'rescan' + CANCEL = 'cancel' + + class Model(Enum): + """ + The analysis model to be used by the service. For the **Element classification** + and **Compare two documents** methods, the default is `contracts`. For the + **Extract tables** method, the default is `tables`. These defaults apply to the + standalone methods as well as to the methods' use in batch-processing requests. + """ + CONTRACTS = 'contracts' + TABLES = 'tables' + + ############################################################################## # Models ############################################################################## @@ -796,17 +971,19 @@ class Address(object): A party's address. :attr str text: (optional) A string listing the address. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ - def __init__(self, text=None, location=None): + def __init__(self, *, text=None, location=None): """ Initialize a Address object. :param str text: (optional) A string listing the address. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.text = text self.location = location @@ -856,18 +1033,19 @@ class AlignedElement(object): AlignedElement. :attr list[ElementPair] element_pair: (optional) Identifies two elements that - semantically align between the compared documents. + semantically align between the compared documents. :attr bool identical_text: (optional) Specifies whether the aligned element is - identical. Elements are considered identical despite minor differences such as leading - punctuation, end-of-sentence punctuation, whitespace, the presence or absence of - definite or indefinite articles, and others. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to IBM to - provide feedback or receive support. - :attr bool significant_elements: (optional) Indicates that the elements aligned are - contractual clauses of significance. + identical. Elements are considered identical despite minor differences such as + leading punctuation, end-of-sentence punctuation, whitespace, the presence or + absence of definite or indefinite articles, and others. + :attr list[str] provenance_ids: (optional) Hashed values that you can send to + IBM to provide feedback or receive support. + :attr bool significant_elements: (optional) Indicates that the elements aligned + are contractual clauses of significance. """ def __init__(self, + *, element_pair=None, identical_text=None, provenance_ids=None, @@ -875,16 +1053,17 @@ def __init__(self, """ Initialize a AlignedElement object. - :param list[ElementPair] element_pair: (optional) Identifies two elements that - semantically align between the compared documents. - :param bool identical_text: (optional) Specifies whether the aligned element is - identical. Elements are considered identical despite minor differences such as - leading punctuation, end-of-sentence punctuation, whitespace, the presence or - absence of definite or indefinite articles, and others. - :param list[str] provenance_ids: (optional) Hashed values that you can send to IBM - to provide feedback or receive support. - :param bool significant_elements: (optional) Indicates that the elements aligned - are contractual clauses of significance. + :param list[ElementPair] element_pair: (optional) Identifies two elements + that semantically align between the compared documents. + :param bool identical_text: (optional) Specifies whether the aligned + element is identical. Elements are considered identical despite minor + differences such as leading punctuation, end-of-sentence punctuation, + whitespace, the presence or absence of definite or indefinite articles, and + others. + :param list[str] provenance_ids: (optional) Hashed values that you can send + to IBM to provide feedback or receive support. + :param bool significant_elements: (optional) Indicates that the elements + aligned are contractual clauses of significance. """ self.element_pair = element_pair self.identical_text = identical_text @@ -951,18 +1130,20 @@ class Attribute(object): :attr str type: (optional) The type of attribute. :attr str text: (optional) The text associated with the attribute. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ - def __init__(self, type=None, text=None, location=None): + def __init__(self, *, type=None, text=None, location=None): """ Initialize a Attribute object. :param str type: (optional) The type of attribute. :param str text: (optional) The text associated with the attribute. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.type = type self.text = text @@ -1011,32 +1192,47 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The type of attribute. + """ + CURRENCY = "Currency" + DATETIME = "DateTime" + DEFINEDTERM = "DefinedTerm" + DURATION = "Duration" + LOCATION = "Location" + NUMBER = "Number" + ORGANIZATION = "Organization" + PERCENTAGE = "Percentage" + PERSON = "Person" + class BatchStatus(object): """ The batch-request status. - :attr str function: (optional) The method to be run against the documents. Possible - values are `html_conversion`, `element_classification`, and `tables`. - :attr str input_bucket_location: (optional) The geographical location of the Cloud - Object Storage input bucket as listed on the **Endpoint** tab of your COS instance; - for example, `us-geo`, `eu-geo`, or `ap-geo`. - :attr str input_bucket_name: (optional) The name of the Cloud Object Storage input - bucket. - :attr str output_bucket_location: (optional) The geographical location of the Cloud - Object Storage output bucket as listed on the **Endpoint** tab of your COS instance; - for example, `us-geo`, `eu-geo`, or `ap-geo`. - :attr str output_bucket_name: (optional) The name of the Cloud Object Storage output - bucket. + :attr str function: (optional) The method to be run against the documents. + Possible values are `html_conversion`, `element_classification`, and `tables`. + :attr str input_bucket_location: (optional) The geographical location of the + Cloud Object Storage input bucket as listed on the **Endpoint** tab of your COS + instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. + :attr str input_bucket_name: (optional) The name of the Cloud Object Storage + input bucket. + :attr str output_bucket_location: (optional) The geographical location of the + Cloud Object Storage output bucket as listed on the **Endpoint** tab of your COS + instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. + :attr str output_bucket_name: (optional) The name of the Cloud Object Storage + output bucket. :attr str batch_id: (optional) The unique identifier for the batch request. :attr DocCounts document_counts: (optional) Document counts. :attr str status: (optional) The status of the batch request. :attr datetime created: (optional) The creation time of the batch request. - :attr datetime updated: (optional) The time of the most recent update to the batch - request. + :attr datetime updated: (optional) The time of the most recent update to the + batch request. """ def __init__(self, + *, function=None, input_bucket_location=None, input_bucket_name=None, @@ -1051,23 +1247,25 @@ def __init__(self, Initialize a BatchStatus object. :param str function: (optional) The method to be run against the documents. - Possible values are `html_conversion`, `element_classification`, and `tables`. - :param str input_bucket_location: (optional) The geographical location of the - Cloud Object Storage input bucket as listed on the **Endpoint** tab of your COS - instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. - :param str input_bucket_name: (optional) The name of the Cloud Object Storage - input bucket. - :param str output_bucket_location: (optional) The geographical location of the - Cloud Object Storage output bucket as listed on the **Endpoint** tab of your COS - instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. - :param str output_bucket_name: (optional) The name of the Cloud Object Storage - output bucket. - :param str batch_id: (optional) The unique identifier for the batch request. + Possible values are `html_conversion`, `element_classification`, and + `tables`. + :param str input_bucket_location: (optional) The geographical location of + the Cloud Object Storage input bucket as listed on the **Endpoint** tab of + your COS instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. + :param str input_bucket_name: (optional) The name of the Cloud Object + Storage input bucket. + :param str output_bucket_location: (optional) The geographical location of + the Cloud Object Storage output bucket as listed on the **Endpoint** tab of + your COS instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. + :param str output_bucket_name: (optional) The name of the Cloud Object + Storage output bucket. + :param str batch_id: (optional) The unique identifier for the batch + request. :param DocCounts document_counts: (optional) Document counts. :param str status: (optional) The status of the batch request. :param datetime created: (optional) The creation time of the batch request. - :param datetime updated: (optional) The time of the most recent update to the - batch request. + :param datetime updated: (optional) The time of the most recent update to + the batch request. """ self.function = function self.input_bucket_location = input_bucket_location @@ -1162,21 +1360,30 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class FunctionEnum(Enum): + """ + The method to be run against the documents. Possible values are `html_conversion`, + `element_classification`, and `tables`. + """ + ELEMENT_CLASSIFICATION = "element_classification" + HTML_CONVERSION = "html_conversion" + TABLES = "tables" + class Batches(object): """ The results of a successful **List Batches** request. :attr list[BatchStatus] batches: (optional) A list of the status of all batch - requests. + requests. """ - def __init__(self, batches=None): + def __init__(self, *, batches=None): """ Initialize a Batches object. - :param list[BatchStatus] batches: (optional) A list of the status of all batch - requests. + :param list[BatchStatus] batches: (optional) A list of the status of all + batch requests. """ self.batches = batches @@ -1223,36 +1430,38 @@ class BodyCells(object): Cells that are not table header, column header, or row header cells. :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The textual contents of this cell from the input document - without associated markup content. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` location - in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` location in - the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's `column` - location in the current table. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. + :attr str text: (optional) The textual contents of this cell from the input + document without associated markup content. + :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + location in the current table. + :attr int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :attr int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. :attr int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. - :attr list[str] row_header_ids: (optional) An array that contains the `id` value of a - row header that is applicable to this body cell. - :attr list[str] row_header_texts: (optional) An array that contains the `text` value - of a row header that is applicable to this body cell. - :attr list[str] row_header_texts_normalized: (optional) If you provide customization - input, the normalized version of the row header texts according to the customization; - otherwise, the same value as `row_header_texts`. - :attr list[str] column_header_ids: (optional) An array that contains the `id` value of - a column header that is applicable to the current cell. - :attr list[str] column_header_texts: (optional) An array that contains the `text` - value of a column header that is applicable to the current cell. + location in the current table. + :attr list[str] row_header_ids: (optional) An array that contains the `id` value + of a row header that is applicable to this body cell. + :attr list[str] row_header_texts: (optional) An array that contains the `text` + value of a row header that is applicable to this body cell. + :attr list[str] row_header_texts_normalized: (optional) If you provide + customization input, the normalized version of the row header texts according to + the customization; otherwise, the same value as `row_header_texts`. + :attr list[str] column_header_ids: (optional) An array that contains the `id` + value of a column header that is applicable to the current cell. + :attr list[str] column_header_texts: (optional) An array that contains the + `text` value of a column header that is applicable to the current cell. :attr list[str] column_header_texts_normalized: (optional) If you provide - customization input, the normalized version of the column header texts according to - the customization; otherwise, the same value as `column_header_texts`. + customization input, the normalized version of the column header texts according + to the customization; otherwise, the same value as `column_header_texts`. :attr list[Attribute] attributes: (optional) """ def __init__(self, + *, cell_id=None, location=None, text=None, @@ -1270,33 +1479,37 @@ def __init__(self, """ Initialize a BodyCells object. - :param str cell_id: (optional) The unique ID of the cell in the current table. + :param str cell_id: (optional) The unique ID of the cell in the current + table. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. - :param str text: (optional) The textual contents of this cell from the input - document without associated markup content. - :param int row_index_begin: (optional) The `begin` index of this cell's `row` - location in the current table. - :param int row_index_end: (optional) The `end` index of this cell's `row` location - in the current table. + element in the document, represented with two integers labeled `begin` and + `end`. + :param str text: (optional) The textual contents of this cell from the + input document without associated markup content. + :param int row_index_begin: (optional) The `begin` index of this cell's + `row` location in the current table. + :param int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. :param int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :param int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. - :param list[str] row_header_ids: (optional) An array that contains the `id` value - of a row header that is applicable to this body cell. - :param list[str] row_header_texts: (optional) An array that contains the `text` - value of a row header that is applicable to this body cell. + `column` location in the current table. + :param int column_index_end: (optional) The `end` index of this cell's + `column` location in the current table. + :param list[str] row_header_ids: (optional) An array that contains the `id` + value of a row header that is applicable to this body cell. + :param list[str] row_header_texts: (optional) An array that contains the + `text` value of a row header that is applicable to this body cell. :param list[str] row_header_texts_normalized: (optional) If you provide - customization input, the normalized version of the row header texts according to - the customization; otherwise, the same value as `row_header_texts`. - :param list[str] column_header_ids: (optional) An array that contains the `id` - value of a column header that is applicable to the current cell. - :param list[str] column_header_texts: (optional) An array that contains the `text` - value of a column header that is applicable to the current cell. + customization input, the normalized version of the row header texts + according to the customization; otherwise, the same value as + `row_header_texts`. + :param list[str] column_header_ids: (optional) An array that contains the + `id` value of a column header that is applicable to the current cell. + :param list[str] column_header_texts: (optional) An array that contains the + `text` value of a column header that is applicable to the current cell. :param list[str] column_header_texts_normalized: (optional) If you provide - customization input, the normalized version of the column header texts according - to the customization; otherwise, the same value as `column_header_texts`. + customization input, the normalized version of the column header texts + according to the customization; otherwise, the same value as + `column_header_texts`. :param list[Attribute] attributes: (optional) """ self.cell_id = cell_id @@ -1429,17 +1642,17 @@ class Category(object): Information defining an element's subject matter. :attr str label: (optional) The category of the associated element. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to IBM to - provide feedback or receive support. + :attr list[str] provenance_ids: (optional) Hashed values that you can send to + IBM to provide feedback or receive support. """ - def __init__(self, label=None, provenance_ids=None): + def __init__(self, *, label=None, provenance_ids=None): """ Initialize a Category object. :param str label: (optional) The category of the associated element. - :param list[str] provenance_ids: (optional) Hashed values that you can send to IBM - to provide feedback or receive support. + :param list[str] provenance_ids: (optional) Hashed values that you can send + to IBM to provide feedback or receive support. """ self.label = label self.provenance_ids = provenance_ids @@ -1483,6 +1696,36 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LabelEnum(Enum): + """ + The category of the associated element. + """ + AMENDMENTS = "Amendments" + ASSET_USE = "Asset Use" + ASSIGNMENTS = "Assignments" + AUDITS = "Audits" + BUSINESS_CONTINUITY = "Business Continuity" + COMMUNICATION = "Communication" + CONFIDENTIALITY = "Confidentiality" + DELIVERABLES = "Deliverables" + DELIVERY = "Delivery" + DISPUTE_RESOLUTION = "Dispute Resolution" + FORCE_MAJEURE = "Force Majeure" + INDEMNIFICATION = "Indemnification" + INSURANCE = "Insurance" + INTELLECTUAL_PROPERTY = "Intellectual Property" + LIABILITY = "Liability" + ORDER_OF_PRECEDENCE = "Order of Precedence" + PAYMENT_TERMS_BILLING = "Payment Terms & Billing" + PRICING_TAXES = "Pricing & Taxes" + PRIVACY = "Privacy" + RESPONSIBILITIES = "Responsibilities" + SAFETY_AND_SECURITY = "Safety and Security" + SCOPE_OF_WORK = "Scope of Work" + SUBCONTRACTS = "Subcontracts" + TERM_TERMINATION = "Term & Termination" + WARRANTIES = "Warranties" + class CategoryComparison(object): """ @@ -1491,7 +1734,7 @@ class CategoryComparison(object): :attr str label: (optional) The category of the associated element. """ - def __init__(self, label=None): + def __init__(self, *, label=None): """ Initialize a CategoryComparison object. @@ -1534,45 +1777,78 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LabelEnum(Enum): + """ + The category of the associated element. + """ + AMENDMENTS = "Amendments" + ASSET_USE = "Asset Use" + ASSIGNMENTS = "Assignments" + AUDITS = "Audits" + BUSINESS_CONTINUITY = "Business Continuity" + COMMUNICATION = "Communication" + CONFIDENTIALITY = "Confidentiality" + DELIVERABLES = "Deliverables" + DELIVERY = "Delivery" + DISPUTE_RESOLUTION = "Dispute Resolution" + FORCE_MAJEURE = "Force Majeure" + INDEMNIFICATION = "Indemnification" + INSURANCE = "Insurance" + INTELLECTUAL_PROPERTY = "Intellectual Property" + LIABILITY = "Liability" + ORDER_OF_PRECEDENCE = "Order of Precedence" + PAYMENT_TERMS_BILLING = "Payment Terms & Billing" + PRICING_TAXES = "Pricing & Taxes" + PRIVACY = "Privacy" + RESPONSIBILITIES = "Responsibilities" + SAFETY_AND_SECURITY = "Safety and Security" + SCOPE_OF_WORK = "Scope of Work" + SUBCONTRACTS = "Subcontracts" + TERM_TERMINATION = "Term & Termination" + WARRANTIES = "Warranties" + class ClassifyReturn(object): """ The analysis of objects returned by the **Element classification** method. :attr Document document: (optional) Basic information about the input document. - :attr str model_id: (optional) The analysis model used to classify the input document. - For the **Element classification** method, the only valid value is `contracts`. - :attr str model_version: (optional) The version of the analysis model identified by - the value of the `model_id` key. - :attr list[Element] elements: (optional) Document elements identified by the service. - :attr list[EffectiveDates] effective_dates: (optional) The date or dates on which the - document becomes effective. + :attr str model_id: (optional) The analysis model used to classify the input + document. For the **Element classification** method, the only valid value is + `contracts`. + :attr str model_version: (optional) The version of the analysis model identified + by the value of the `model_id` key. + :attr list[Element] elements: (optional) Document elements identified by the + service. + :attr list[EffectiveDates] effective_dates: (optional) The date or dates on + which the document becomes effective. :attr list[ContractAmts] contract_amounts: (optional) The monetary amounts that - identify the total amount of the contract that needs to be paid from one party to - another. - :attr list[TerminationDates] termination_dates: (optional) The dates on which the - document is to be terminated. - :attr list[ContractTypes] contract_types: (optional) The contract type as declared in - the document. - :attr list[ContractTerms] contract_terms: (optional) The durations of the contract. - :attr list[PaymentTerms] payment_terms: (optional) The document's payment durations. - :attr list[ContractCurrencies] contract_currencies: (optional) The contract currencies - as declared in the document. - :attr list[Tables] tables: (optional) Definition of tables identified in the input - document. - :attr DocStructure document_structure: (optional) The structure of the input document. - :attr list[Parties] parties: (optional) Definitions of the parties identified in the - input document. + identify the total amount of the contract that needs to be paid from one party + to another. + :attr list[TerminationDates] termination_dates: (optional) The dates on which + the document is to be terminated. + :attr list[ContractTypes] contract_types: (optional) The contract type as + declared in the document. + :attr list[ContractTerms] contract_terms: (optional) The durations of the + contract. + :attr list[PaymentTerms] payment_terms: (optional) The document's payment + durations. + :attr list[ContractCurrencies] contract_currencies: (optional) The contract + currencies as declared in the document. + :attr list[Tables] tables: (optional) Definition of tables identified in the + input document. + :attr DocStructure document_structure: (optional) The structure of the input + document. + :attr list[Parties] parties: (optional) Definitions of the parties identified in + the input document. """ def __init__(self, + *, document=None, model_id=None, model_version=None, elements=None, - tables=None, - document_structure=None, - parties=None, effective_dates=None, contract_amounts=None, termination_dates=None, @@ -1580,39 +1856,42 @@ def __init__(self, contract_terms=None, payment_terms=None, contract_currencies=None, - ): + tables=None, + document_structure=None, + parties=None): """ Initialize a ClassifyReturn object. - :param Document document: (optional) Basic information about the input document. - :param str model_id: (optional) The analysis model used to classify the input - document. For the **Element classification** method, the only valid value is - `contracts`. - :param str model_version: (optional) The version of the analysis model identified - by the value of the `model_id` key. - :param list[Element] elements: (optional) Document elements identified by the - service. - :param list[EffectiveDates] effective_dates: (optional) The date or dates on which - the document becomes effective. - :param list[ContractAmts] contract_amounts: (optional) The monetary amounts that - identify the total amount of the contract that needs to be paid from one party to - another. - :param list[TerminationDates] termination_dates: (optional) The dates on which the - document is to be terminated. + :param Document document: (optional) Basic information about the input + document. + :param str model_id: (optional) The analysis model used to classify the + input document. For the **Element classification** method, the only valid + value is `contracts`. + :param str model_version: (optional) The version of the analysis model + identified by the value of the `model_id` key. + :param list[Element] elements: (optional) Document elements identified by + the service. + :param list[EffectiveDates] effective_dates: (optional) The date or dates + on which the document becomes effective. + :param list[ContractAmts] contract_amounts: (optional) The monetary amounts + that identify the total amount of the contract that needs to be paid from + one party to another. + :param list[TerminationDates] termination_dates: (optional) The dates on + which the document is to be terminated. :param list[ContractTypes] contract_types: (optional) The contract type as - declared in the document. + declared in the document. :param list[ContractTerms] contract_terms: (optional) The durations of the - contract. + contract. :param list[PaymentTerms] payment_terms: (optional) The document's payment - durations. - :param list[ContractCurrencies] contract_currencies: (optional) The contract - currencies as declared in the document. - :param list[Tables] tables: (optional) Definition of tables identified in the - input document. - :param DocStructure document_structure: (optional) The structure of the input - document. - :param list[Parties] parties: (optional) Definitions of the parties identified in - the input document. + durations. + :param list[ContractCurrencies] contract_currencies: (optional) The + contract currencies as declared in the document. + :param list[Tables] tables: (optional) Definition of tables identified in + the input document. + :param DocStructure document_structure: (optional) The structure of the + input document. + :param list[Parties] parties: (optional) Definitions of the parties + identified in the input document. """ self.document = document self.model_id = model_id @@ -1775,24 +2054,25 @@ class ColumnHeaders(object): :attr str cell_id: (optional) The unique ID of the cell in the current table. :attr object location: (optional) The location of the column header cell in the - current table as defined by its `begin` and `end` offsets, respectfully, in the input - document. - :attr str text: (optional) The textual contents of this cell from the input document - without associated markup content. + current table as defined by its `begin` and `end` offsets, respectfully, in the + input document. + :attr str text: (optional) The textual contents of this cell from the input + document without associated markup content. :attr str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, the - same value as `text`. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` location - in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` location in - the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's `column` - location in the current table. + normalized version of the cell text according to the customization; otherwise, + the same value as `text`. + :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + location in the current table. + :attr int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :attr int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. :attr int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. + location in the current table. """ def __init__(self, + *, cell_id=None, location=None, text=None, @@ -1804,23 +2084,24 @@ def __init__(self, """ Initialize a ColumnHeaders object. - :param str cell_id: (optional) The unique ID of the cell in the current table. - :param object location: (optional) The location of the column header cell in the - current table as defined by its `begin` and `end` offsets, respectfully, in the - input document. - :param str text: (optional) The textual contents of this cell from the input - document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, the - same value as `text`. - :param int row_index_begin: (optional) The `begin` index of this cell's `row` - location in the current table. - :param int row_index_end: (optional) The `end` index of this cell's `row` location - in the current table. + :param str cell_id: (optional) The unique ID of the cell in the current + table. + :param object location: (optional) The location of the column header cell + in the current table as defined by its `begin` and `end` offsets, + respectfully, in the input document. + :param str text: (optional) The textual contents of this cell from the + input document without associated markup content. + :param str text_normalized: (optional) If you provide customization input, + the normalized version of the cell text according to the customization; + otherwise, the same value as `text`. + :param int row_index_begin: (optional) The `begin` index of this cell's + `row` location in the current table. + :param int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. :param int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :param int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. + `column` location in the current table. + :param int column_index_end: (optional) The `end` index of this cell's + `column` location in the current table. """ self.cell_id = cell_id self.location = location @@ -1907,19 +2188,21 @@ class CompareReturn(object): """ The comparison of the two submitted documents. - :attr str model_id: (optional) The analysis model used to compare the input documents. - For the **Compare two documents** method, the only valid value is `contracts`. - :attr str model_version: (optional) The version of the analysis model identified by - the value of the `model_id` key. + :attr str model_id: (optional) The analysis model used to compare the input + documents. For the **Compare two documents** method, the only valid value is + `contracts`. + :attr str model_version: (optional) The version of the analysis model identified + by the value of the `model_id` key. :attr list[Document] documents: (optional) Information about the documents being - compared. - :attr list[AlignedElement] aligned_elements: (optional) A list of pairs of elements - that semantically align between the compared documents. - :attr list[UnalignedElement] unaligned_elements: (optional) A list of elements that do - not semantically align between the compared documents. + compared. + :attr list[AlignedElement] aligned_elements: (optional) A list of pairs of + elements that semantically align between the compared documents. + :attr list[UnalignedElement] unaligned_elements: (optional) A list of elements + that do not semantically align between the compared documents. """ def __init__(self, + *, model_id=None, model_version=None, documents=None, @@ -1928,17 +2211,17 @@ def __init__(self, """ Initialize a CompareReturn object. - :param str model_id: (optional) The analysis model used to compare the input - documents. For the **Compare two documents** method, the only valid value is - `contracts`. - :param str model_version: (optional) The version of the analysis model identified - by the value of the `model_id` key. - :param list[Document] documents: (optional) Information about the documents being - compared. + :param str model_id: (optional) The analysis model used to compare the + input documents. For the **Compare two documents** method, the only valid + value is `contracts`. + :param str model_version: (optional) The version of the analysis model + identified by the value of the `model_id` key. + :param list[Document] documents: (optional) Information about the documents + being compared. :param list[AlignedElement] aligned_elements: (optional) A list of pairs of - elements that semantically align between the compared documents. - :param list[UnalignedElement] unaligned_elements: (optional) A list of elements - that do not semantically align between the compared documents. + elements that semantically align between the compared documents. + :param list[UnalignedElement] unaligned_elements: (optional) A list of + elements that do not semantically align between the compared documents. """ self.model_id = model_id self.model_version = model_version @@ -2024,7 +2307,7 @@ class Contact(object): :attr str role: (optional) A string listing the role of the contact. """ - def __init__(self, name=None, role=None): + def __init__(self, *, name=None, role=None): """ Initialize a Contact object. @@ -2080,17 +2363,19 @@ class Contexts(object): current table. :attr str text: (optional) The related text. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ - def __init__(self, text=None, location=None): + def __init__(self, *, text=None, location=None): """ Initialize a Contexts object. :param str text: (optional) The related text. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.text = text self.location = location @@ -2139,43 +2424,47 @@ class ContractAmts(object): """ A monetary amount identified in the input document. - :attr str confidence_level: (optional) The confidence level in the identification of - the contract amount. + :attr str confidence_level: (optional) The confidence level in the + identification of the contract amount. :attr str text: (optional) The monetary amount. - :attr str text_normalized: (optional) The normalized form of the amount, which is - listed as a string. This element is optional; it is returned only if normalized text - exists. - :attr Interpretation interpretation: (optional) The details of the normalized text, if - applicable. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to IBM to - provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr str text_normalized: (optional) The normalized form of the amount, which + is listed as a string. This element is optional; it is returned only if + normalized text exists. + :attr Interpretation interpretation: (optional) The details of the normalized + text, if applicable. This element is optional; it is returned only if normalized + text exists. + :attr list[str] provenance_ids: (optional) Hashed values that you can send to + IBM to provide feedback or receive support. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ def __init__(self, - text=None, + *, confidence_level=None, - location=None, + text=None, text_normalized=None, interpretation=None, - provenance_ids=None): + provenance_ids=None, + location=None): """ Initialize a ContractAmts object. - :param str confidence_level: (optional) The confidence level in the identification - of the contract amount. + :param str confidence_level: (optional) The confidence level in the + identification of the contract amount. :param str text: (optional) The monetary amount. - :param str text_normalized: (optional) The normalized form of the amount, which is - listed as a string. This element is optional; it is returned only if normalized - text exists. - :param Interpretation interpretation: (optional) The details of the normalized - text, if applicable. This element is optional; it is returned only if normalized - text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send to IBM - to provide feedback or receive support. + :param str text_normalized: (optional) The normalized form of the amount, + which is listed as a string. This element is optional; it is returned only + if normalized text exists. + :param Interpretation interpretation: (optional) The details of the + normalized text, if applicable. This element is optional; it is returned + only if normalized text exists. + :param list[str] provenance_ids: (optional) Hashed values that you can send + to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.confidence_level = confidence_level self.text = text @@ -2245,25 +2534,35 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConfidenceLevelEnum(Enum): + """ + The confidence level in the identification of the contract amount. + """ + HIGH = "High" + MEDIUM = "Medium" + LOW = "Low" + class ContractCurrencies(object): """ The contract currencies that are declared in the document. - :attr str confidence_level: (optional) The confidence level in the identification of - the contract currency. + :attr str confidence_level: (optional) The confidence level in the + identification of the contract currency. :attr str text: (optional) The contract currency. - :attr str text_normalized: (optional) The normalized form of the contract currency, - which is listed as a string in - [ISO-4217](https://www.iso.org/iso-4217-currency-codes.html) format. This element is - optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to IBM to - provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr str text_normalized: (optional) The normalized form of the contract + currency, which is listed as a string in + [ISO-4217](https://www.iso.org/iso-4217-currency-codes.html) format. This + element is optional; it is returned only if normalized text exists. + :attr list[str] provenance_ids: (optional) Hashed values that you can send to + IBM to provide feedback or receive support. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ def __init__(self, + *, confidence_level=None, text=None, text_normalized=None, @@ -2272,17 +2571,18 @@ def __init__(self, """ Initialize a ContractCurrencies object. - :param str confidence_level: (optional) The confidence level in the identification - of the contract currency. + :param str confidence_level: (optional) The confidence level in the + identification of the contract currency. :param str text: (optional) The contract currency. :param str text_normalized: (optional) The normalized form of the contract - currency, which is listed as a string in - [ISO-4217](https://www.iso.org/iso-4217-currency-codes.html) format. This element - is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send to IBM - to provide feedback or receive support. + currency, which is listed as a string in + [ISO-4217](https://www.iso.org/iso-4217-currency-codes.html) format. This + element is optional; it is returned only if normalized text exists. + :param list[str] provenance_ids: (optional) Hashed values that you can send + to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.confidence_level = confidence_level self.text = text @@ -2346,26 +2646,37 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConfidenceLevelEnum(Enum): + """ + The confidence level in the identification of the contract currency. + """ + HIGH = "High" + MEDIUM = "Medium" + LOW = "Low" + class ContractTerms(object): """ The duration or durations of the contract. - :attr str confidence_level: (optional) The confidence level in the identification of - the contract term. + :attr str confidence_level: (optional) The confidence level in the + identification of the contract term. :attr str text: (optional) The contract term (duration). - :attr str text_normalized: (optional) The normalized form of the contract term, which - is listed as a string. This element is optional; it is returned only if normalized - text exists. - :attr Interpretation interpretation: (optional) The details of the normalized text, if - applicable. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to IBM to - provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr str text_normalized: (optional) The normalized form of the contract term, + which is listed as a string. This element is optional; it is returned only if + normalized text exists. + :attr Interpretation interpretation: (optional) The details of the normalized + text, if applicable. This element is optional; it is returned only if normalized + text exists. + :attr list[str] provenance_ids: (optional) Hashed values that you can send to + IBM to provide feedback or receive support. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ def __init__(self, + *, confidence_level=None, text=None, text_normalized=None, @@ -2375,19 +2686,20 @@ def __init__(self, """ Initialize a ContractTerms object. - :param str confidence_level: (optional) The confidence level in the identification - of the contract term. + :param str confidence_level: (optional) The confidence level in the + identification of the contract term. :param str text: (optional) The contract term (duration). - :param str text_normalized: (optional) The normalized form of the contract term, - which is listed as a string. This element is optional; it is returned only if - normalized text exists. - :param Interpretation interpretation: (optional) The details of the normalized - text, if applicable. This element is optional; it is returned only if normalized - text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send to IBM - to provide feedback or receive support. + :param str text_normalized: (optional) The normalized form of the contract + term, which is listed as a string. This element is optional; it is returned + only if normalized text exists. + :param Interpretation interpretation: (optional) The details of the + normalized text, if applicable. This element is optional; it is returned + only if normalized text exists. + :param list[str] provenance_ids: (optional) Hashed values that you can send + to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.confidence_level = confidence_level self.text = text @@ -2457,21 +2769,31 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConfidenceLevelEnum(Enum): + """ + The confidence level in the identification of the contract term. + """ + HIGH = "High" + MEDIUM = "Medium" + LOW = "Low" + class ContractTypes(object): """ The contract type identified in the input document. - :attr str confidence_level: (optional) The confidence level in the identification of - the contract type. + :attr str confidence_level: (optional) The confidence level in the + identification of the contract type. :attr str text: (optional) The contract type. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to IBM to - provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr list[str] provenance_ids: (optional) Hashed values that you can send to + IBM to provide feedback or receive support. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ def __init__(self, + *, confidence_level=None, text=None, provenance_ids=None, @@ -2479,13 +2801,14 @@ def __init__(self, """ Initialize a ContractTypes object. - :param str confidence_level: (optional) The confidence level in the identification - of the contract type. + :param str confidence_level: (optional) The confidence level in the + identification of the contract type. :param str text: (optional) The contract type. - :param list[str] provenance_ids: (optional) Hashed values that you can send to IBM - to provide feedback or receive support. + :param list[str] provenance_ids: (optional) Hashed values that you can send + to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.confidence_level = confidence_level self.text = text @@ -2540,6 +2863,14 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConfidenceLevelEnum(Enum): + """ + The confidence level in the identification of the contract type. + """ + HIGH = "High" + MEDIUM = "Medium" + LOW = "Low" + class DocCounts(object): """ @@ -2551,14 +2882,21 @@ class DocCounts(object): :attr int failed: (optional) Number of documents not successfully processed. """ - def __init__(self, total=None, pending=None, successful=None, failed=None): + def __init__(self, + *, + total=None, + pending=None, + successful=None, + failed=None): """ Initialize a DocCounts object. :param int total: (optional) Total number of documents. :param int pending: (optional) Number of pending documents. - :param int successful: (optional) Number of documents successfully processed. - :param int failed: (optional) Number of documents not successfully processed. + :param int successful: (optional) Number of documents successfully + processed. + :param int failed: (optional) Number of documents not successfully + processed. """ self.total = total self.pending = pending @@ -2618,18 +2956,19 @@ class DocInfo(object): Information about the parsed input document. :attr str html: (optional) The full text of the parsed document in HTML format. - :attr str title: (optional) The title of the parsed document. If the service did not - detect a title, the value of this element is `null`. + :attr str title: (optional) The title of the parsed document. If the service did + not detect a title, the value of this element is `null`. :attr str hash: (optional) The MD5 hash of the input document. """ - def __init__(self, html=None, title=None, hash=None): + def __init__(self, *, html=None, title=None, hash=None): """ Initialize a DocInfo object. - :param str html: (optional) The full text of the parsed document in HTML format. - :param str title: (optional) The title of the parsed document. If the service did - not detect a title, the value of this element is `null`. + :param str html: (optional) The full text of the parsed document in HTML + format. + :param str title: (optional) The title of the parsed document. If the + service did not detect a title, the value of this element is `null`. :param str hash: (optional) The MD5 hash of the input document. """ self.html = html @@ -2684,29 +3023,33 @@ class DocStructure(object): """ The structure of the input document. - :attr list[SectionTitles] section_titles: (optional) An array containing one object - per section or subsection identified in the input document. - :attr list[LeadingSentence] leading_sentences: (optional) An array containing one - object per section or subsection, in parallel with the `section_titles` array, that - details the leading sentences in the corresponding section or subsection. + :attr list[SectionTitles] section_titles: (optional) An array containing one + object per section or subsection identified in the input document. + :attr list[LeadingSentence] leading_sentences: (optional) An array containing + one object per section or subsection, in parallel with the `section_titles` + array, that details the leading sentences in the corresponding section or + subsection. :attr list[Paragraphs] paragraphs: (optional) An array containing one object per - paragraph, in parallel with the `section_titles` and `leading_sentences` arrays. + paragraph, in parallel with the `section_titles` and `leading_sentences` arrays. """ def __init__(self, + *, section_titles=None, leading_sentences=None, paragraphs=None): """ Initialize a DocStructure object. - :param list[SectionTitles] section_titles: (optional) An array containing one - object per section or subsection identified in the input document. - :param list[LeadingSentence] leading_sentences: (optional) An array containing one - object per section or subsection, in parallel with the `section_titles` array, - that details the leading sentences in the corresponding section or subsection. - :param list[Paragraphs] paragraphs: (optional) An array containing one object per - paragraph, in parallel with the `section_titles` and `leading_sentences` arrays. + :param list[SectionTitles] section_titles: (optional) An array containing + one object per section or subsection identified in the input document. + :param list[LeadingSentence] leading_sentences: (optional) An array + containing one object per section or subsection, in parallel with the + `section_titles` array, that details the leading sentences in the + corresponding section or subsection. + :param list[Paragraphs] paragraphs: (optional) An array containing one + object per paragraph, in parallel with the `section_titles` and + `leading_sentences` arrays. """ self.section_titles = section_titles self.leading_sentences = leading_sentences @@ -2776,21 +3119,21 @@ class Document(object): :attr str title: (optional) Document title, if detected. :attr str html: (optional) The input document converted into HTML format. :attr str hash: (optional) The MD5 hash value of the input document. - :attr str label: (optional) The label applied to the input document with the calling - method's `file_1_label` or `file_2_label` value. This field is specified only in the - output of the **Comparing two documents** method. + :attr str label: (optional) The label applied to the input document with the + calling method's `file_1_label` or `file_2_label` value. This field is specified + only in the output of the **Comparing two documents** method. """ - def __init__(self, title=None, html=None, hash=None, label=None): + def __init__(self, *, title=None, html=None, hash=None, label=None): """ Initialize a Document object. :param str title: (optional) Document title, if detected. :param str html: (optional) The input document converted into HTML format. :param str hash: (optional) The MD5 hash value of the input document. - :param str label: (optional) The label applied to the input document with the - calling method's `file_1_label` or `file_2_label` value. This field is specified - only in the output of the **Comparing two documents** method. + :param str label: (optional) The label applied to the input document with + the calling method's `file_1_label` or `file_2_label` value. This field is + specified only in the output of the **Comparing two documents** method. """ self.title = title self.html = html @@ -2849,19 +3192,21 @@ class EffectiveDates(object): """ An effective date. - :attr str confidence_level: (optional) The confidence level in the identification of - the effective date. + :attr str confidence_level: (optional) The confidence level in the + identification of the effective date. :attr str text: (optional) The effective date, listed as a string. - :attr str text_normalized: (optional) The normalized form of the effective date, which - is listed as a string. This element is optional; it is returned only if normalized - text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to IBM to - provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr str text_normalized: (optional) The normalized form of the effective date, + which is listed as a string. This element is optional; it is returned only if + normalized text exists. + :attr list[str] provenance_ids: (optional) Hashed values that you can send to + IBM to provide feedback or receive support. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ def __init__(self, + *, confidence_level=None, text=None, text_normalized=None, @@ -2870,16 +3215,17 @@ def __init__(self, """ Initialize a EffectiveDates object. - :param str confidence_level: (optional) The confidence level in the identification - of the effective date. + :param str confidence_level: (optional) The confidence level in the + identification of the effective date. :param str text: (optional) The effective date, listed as a string. - :param str text_normalized: (optional) The normalized form of the effective date, - which is listed as a string. This element is optional; it is returned only if - normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send to IBM - to provide feedback or receive support. + :param str text_normalized: (optional) The normalized form of the effective + date, which is listed as a string. This element is optional; it is returned + only if normalized text exists. + :param list[str] provenance_ids: (optional) Hashed values that you can send + to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.confidence_level = confidence_level self.text = text @@ -2943,22 +3289,32 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConfidenceLevelEnum(Enum): + """ + The confidence level in the identification of the effective date. + """ + HIGH = "High" + MEDIUM = "Medium" + LOW = "Low" + class Element(object): """ A component part of the document. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. :attr str text: (optional) The text of the element. - :attr list[TypeLabel] types: (optional) Description of the action specified by the - element and whom it affects. - :attr list[Category] categories: (optional) List of functional categories into which - the element falls; in other words, the subject matter of the element. + :attr list[TypeLabel] types: (optional) Description of the action specified by + the element and whom it affects. + :attr list[Category] categories: (optional) List of functional categories into + which the element falls; in other words, the subject matter of the element. :attr list[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, + *, location=None, text=None, types=None, @@ -2968,12 +3324,14 @@ def __init__(self, Initialize a Element object. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. :param str text: (optional) The text of the element. - :param list[TypeLabel] types: (optional) Description of the action specified by - the element and whom it affects. - :param list[Category] categories: (optional) List of functional categories into - which the element falls; in other words, the subject matter of the element. + :param list[TypeLabel] types: (optional) Description of the action + specified by the element and whom it affects. + :param list[Category] categories: (optional) List of functional categories + into which the element falls; in other words, the subject matter of the + element. :param list[Attribute] attributes: (optional) List of document attributes. """ self.location = location @@ -3045,20 +3403,20 @@ class ElementLocations(object): A list of `begin` and `end` indexes that indicate the locations of the elements in the input document. - :attr int begin: (optional) An integer that indicates the starting position of the - element in the input document. - :attr int end: (optional) An integer that indicates the ending position of the element - in the input document. + :attr int begin: (optional) An integer that indicates the starting position of + the element in the input document. + :attr int end: (optional) An integer that indicates the ending position of the + element in the input document. """ - def __init__(self, begin=None, end=None): + def __init__(self, *, begin=None, end=None): """ Initialize a ElementLocations object. - :param int begin: (optional) An integer that indicates the starting position of - the element in the input document. - :param int end: (optional) An integer that indicates the ending position of the - element in the input document. + :param int begin: (optional) An integer that indicates the starting + position of the element in the input document. + :param int end: (optional) An integer that indicates the ending position of + the element in the input document. """ self.begin = begin self.end = end @@ -3107,19 +3465,23 @@ class ElementPair(object): """ Details of semantically aligned elements. - :attr str document_label: (optional) The label of the document (that is, the value of - either the `file_1_label` or `file_2_label` parameters) in which the element occurs. + :attr str document_label: (optional) The label of the document (that is, the + value of either the `file_1_label` or `file_2_label` parameters) in which the + element occurs. :attr str text: (optional) The contents of the element. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. - :attr list[TypeLabelComparison] types: (optional) Description of the action specified - by the element and whom it affects. - :attr list[CategoryComparison] categories: (optional) List of functional categories - into which the element falls; in other words, the subject matter of the element. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. + :attr list[TypeLabelComparison] types: (optional) Description of the action + specified by the element and whom it affects. + :attr list[CategoryComparison] categories: (optional) List of functional + categories into which the element falls; in other words, the subject matter of + the element. :attr list[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, + *, document_label=None, text=None, location=None, @@ -3129,17 +3491,18 @@ def __init__(self, """ Initialize a ElementPair object. - :param str document_label: (optional) The label of the document (that is, the - value of either the `file_1_label` or `file_2_label` parameters) in which the - element occurs. + :param str document_label: (optional) The label of the document (that is, + the value of either the `file_1_label` or `file_2_label` parameters) in + which the element occurs. :param str text: (optional) The contents of the element. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. - :param list[TypeLabelComparison] types: (optional) Description of the action - specified by the element and whom it affects. + element in the document, represented with two integers labeled `begin` and + `end`. + :param list[TypeLabelComparison] types: (optional) Description of the + action specified by the element and whom it affects. :param list[CategoryComparison] categories: (optional) List of functional - categories into which the element falls; in other words, the subject matter of the - element. + categories into which the element falls; in other words, the subject matter + of the element. :param list[Attribute] attributes: (optional) List of document attributes. """ self.document_label = document_label @@ -3220,19 +3583,19 @@ class FeedbackDataInput(object): Feedback data for submission. :attr str feedback_type: The type of feedback. The only permitted value is - `element_classification`. + `element_classification`. :attr ShortDoc document: (optional) Brief information about the input document. - :attr str model_id: (optional) An optional string identifying the model ID. The only - permitted value is `contracts`. - :attr str model_version: (optional) An optional string identifying the version of the - model used. + :attr str model_id: (optional) An optional string identifying the model ID. The + only permitted value is `contracts`. + :attr str model_version: (optional) An optional string identifying the version + of the model used. :attr Location location: The numeric location of the identified element in the - document, represented with two integers labeled `begin` and `end`. + document, represented with two integers labeled `begin` and `end`. :attr str text: The text on which to submit feedback. - :attr OriginalLabelsIn original_labels: The original labeling from the input document, - without the submitted feedback. - :attr UpdatedLabelsIn updated_labels: The updated labeling from the input document, - accounting for the submitted feedback. + :attr OriginalLabelsIn original_labels: The original labeling from the input + document, without the submitted feedback. + :attr UpdatedLabelsIn updated_labels: The updated labeling from the input + document, accounting for the submitted feedback. """ def __init__(self, @@ -3241,6 +3604,7 @@ def __init__(self, text, original_labels, updated_labels, + *, document=None, model_id=None, model_version=None): @@ -3248,19 +3612,20 @@ def __init__(self, Initialize a FeedbackDataInput object. :param str feedback_type: The type of feedback. The only permitted value is - `element_classification`. - :param Location location: The numeric location of the identified element in the - document, represented with two integers labeled `begin` and `end`. + `element_classification`. + :param Location location: The numeric location of the identified element in + the document, represented with two integers labeled `begin` and `end`. :param str text: The text on which to submit feedback. - :param OriginalLabelsIn original_labels: The original labeling from the input - document, without the submitted feedback. + :param OriginalLabelsIn original_labels: The original labeling from the + input document, without the submitted feedback. :param UpdatedLabelsIn updated_labels: The updated labeling from the input - document, accounting for the submitted feedback. - :param ShortDoc document: (optional) Brief information about the input document. - :param str model_id: (optional) An optional string identifying the model ID. The - only permitted value is `contracts`. - :param str model_version: (optional) An optional string identifying the version of - the model used. + document, accounting for the submitted feedback. + :param ShortDoc document: (optional) Brief information about the input + document. + :param str model_id: (optional) An optional string identifying the model + ID. The only permitted value is `contracts`. + :param str model_version: (optional) An optional string identifying the + version of the model used. """ self.feedback_type = feedback_type self.document = document @@ -3365,25 +3730,27 @@ class FeedbackDataOutput(object): """ Information returned from the **Add Feedback** method. - :attr str feedback_type: (optional) A string identifying the user adding the feedback. - The only permitted value is `element_classification`. + :attr str feedback_type: (optional) A string identifying the user adding the + feedback. The only permitted value is `element_classification`. :attr ShortDoc document: (optional) Brief information about the input document. - :attr str model_id: (optional) An optional string identifying the model ID. The only - permitted value is `contracts`. - :attr str model_version: (optional) An optional string identifying the version of the - model used. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr str model_id: (optional) An optional string identifying the model ID. The + only permitted value is `contracts`. + :attr str model_version: (optional) An optional string identifying the version + of the model used. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. :attr str text: (optional) The text to which the feedback applies. - :attr OriginalLabelsOut original_labels: (optional) The original labeling from the - input document, without the submitted feedback. - :attr UpdatedLabelsOut updated_labels: (optional) The updated labeling from the input - document, accounting for the submitted feedback. - :attr Pagination pagination: (optional) Pagination details, if required by the length - of the output. + :attr OriginalLabelsOut original_labels: (optional) The original labeling from + the input document, without the submitted feedback. + :attr UpdatedLabelsOut updated_labels: (optional) The updated labeling from the + input document, accounting for the submitted feedback. + :attr Pagination pagination: (optional) Pagination details, if required by the + length of the output. """ def __init__(self, + *, feedback_type=None, document=None, model_id=None, @@ -3396,22 +3763,24 @@ def __init__(self, """ Initialize a FeedbackDataOutput object. - :param str feedback_type: (optional) A string identifying the user adding the - feedback. The only permitted value is `element_classification`. - :param ShortDoc document: (optional) Brief information about the input document. - :param str model_id: (optional) An optional string identifying the model ID. The - only permitted value is `contracts`. - :param str model_version: (optional) An optional string identifying the version of - the model used. + :param str feedback_type: (optional) A string identifying the user adding + the feedback. The only permitted value is `element_classification`. + :param ShortDoc document: (optional) Brief information about the input + document. + :param str model_id: (optional) An optional string identifying the model + ID. The only permitted value is `contracts`. + :param str model_version: (optional) An optional string identifying the + version of the model used. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. :param str text: (optional) The text to which the feedback applies. - :param OriginalLabelsOut original_labels: (optional) The original labeling from - the input document, without the submitted feedback. - :param UpdatedLabelsOut updated_labels: (optional) The updated labeling from the - input document, accounting for the submitted feedback. - :param Pagination pagination: (optional) Pagination details, if required by the - length of the output. + :param OriginalLabelsOut original_labels: (optional) The original labeling + from the input document, without the submitted feedback. + :param UpdatedLabelsOut updated_labels: (optional) The updated labeling + from the input document, accounting for the submitted feedback. + :param Pagination pagination: (optional) Pagination details, if required by + the length of the output. """ self.feedback_type = feedback_type self.document = document @@ -3506,7 +3875,7 @@ class FeedbackDeleted(object): :attr str message: (optional) Status message returned from the service. """ - def __init__(self, status=None, message=None): + def __init__(self, *, status=None, message=None): """ Initialize a FeedbackDeleted object. @@ -3560,15 +3929,16 @@ class FeedbackList(object): """ The results of a successful **List Feedback** request for all feedback. - :attr list[GetFeedback] feedback: (optional) A list of all feedback for the document. + :attr list[GetFeedback] feedback: (optional) A list of all feedback for the + document. """ - def __init__(self, feedback=None): + def __init__(self, *, feedback=None): """ Initialize a FeedbackList object. - :param list[GetFeedback] feedback: (optional) A list of all feedback for the - document. + :param list[GetFeedback] feedback: (optional) A list of all feedback for + the document. """ self.feedback = feedback @@ -3615,17 +3985,18 @@ class FeedbackReturn(object): Information about the document and the submitted feedback. :attr str feedback_id: (optional) The unique ID of the feedback object. - :attr str user_id: (optional) An optional string identifying the person submitting - feedback. + :attr str user_id: (optional) An optional string identifying the person + submitting feedback. :attr str comment: (optional) An optional comment from the person submitting the - feedback. - :attr datetime created: (optional) Timestamp listing the creation time of the feedback - submission. - :attr FeedbackDataOutput feedback_data: (optional) Information returned from the **Add - Feedback** method. + feedback. + :attr datetime created: (optional) Timestamp listing the creation time of the + feedback submission. + :attr FeedbackDataOutput feedback_data: (optional) Information returned from the + **Add Feedback** method. """ def __init__(self, + *, feedback_id=None, user_id=None, comment=None, @@ -3636,13 +4007,13 @@ def __init__(self, :param str feedback_id: (optional) The unique ID of the feedback object. :param str user_id: (optional) An optional string identifying the person - submitting feedback. - :param str comment: (optional) An optional comment from the person submitting the - feedback. - :param datetime created: (optional) Timestamp listing the creation time of the - feedback submission. - :param FeedbackDataOutput feedback_data: (optional) Information returned from the - **Add Feedback** method. + submitting feedback. + :param str comment: (optional) An optional comment from the person + submitting the feedback. + :param datetime created: (optional) Timestamp listing the creation time of + the feedback submission. + :param FeedbackDataOutput feedback_data: (optional) Information returned + from the **Add Feedback** method. """ self.feedback_id = feedback_id self.user_id = user_id @@ -3709,16 +4080,18 @@ class GetFeedback(object): """ The results of a successful **Get Feedback** request for a single feedback entry. - :attr str feedback_id: (optional) A string uniquely identifying the feedback entry. - :attr datetime created: (optional) A timestamp identifying the creation time of the - feedback entry. + :attr str feedback_id: (optional) A string uniquely identifying the feedback + entry. + :attr datetime created: (optional) A timestamp identifying the creation time of + the feedback entry. :attr str comment: (optional) A string containing the user's comment about the - feedback entry. - :attr FeedbackDataOutput feedback_data: (optional) Information returned from the **Add - Feedback** method. + feedback entry. + :attr FeedbackDataOutput feedback_data: (optional) Information returned from the + **Add Feedback** method. """ def __init__(self, + *, feedback_id=None, created=None, comment=None, @@ -3726,14 +4099,14 @@ def __init__(self, """ Initialize a GetFeedback object. - :param str feedback_id: (optional) A string uniquely identifying the feedback - entry. - :param datetime created: (optional) A timestamp identifying the creation time of - the feedback entry. - :param str comment: (optional) A string containing the user's comment about the - feedback entry. - :param FeedbackDataOutput feedback_data: (optional) Information returned from the - **Add Feedback** method. + :param str feedback_id: (optional) A string uniquely identifying the + feedback entry. + :param datetime created: (optional) A timestamp identifying the creation + time of the feedback entry. + :param str comment: (optional) A string containing the user's comment about + the feedback entry. + :param FeedbackDataOutput feedback_data: (optional) Information returned + from the **Add Feedback** method. """ self.feedback_id = feedback_id self.created = created @@ -3795,13 +4168,14 @@ class HTMLReturn(object): :attr str num_pages: (optional) The number of pages in the input document. :attr str author: (optional) The author of the input document, if identified. - :attr str publication_date: (optional) The publication date of the input document, if - identified. + :attr str publication_date: (optional) The publication date of the input + document, if identified. :attr str title: (optional) The title of the input document, if identified. :attr str html: (optional) The HTML version of the input document. """ def __init__(self, + *, num_pages=None, author=None, publication_date=None, @@ -3811,10 +4185,12 @@ def __init__(self, Initialize a HTMLReturn object. :param str num_pages: (optional) The number of pages in the input document. - :param str author: (optional) The author of the input document, if identified. + :param str author: (optional) The author of the input document, if + identified. :param str publication_date: (optional) The publication date of the input - document, if identified. - :param str title: (optional) The title of the input document, if identified. + document, if identified. + :param str title: (optional) The title of the input document, if + identified. :param str html: (optional) The HTML version of the input document. """ self.num_pages = num_pages @@ -3882,31 +4258,32 @@ class Interpretation(object): returned only if normalized text exists. :attr str value: (optional) The value that was located in the normalized text. - :attr float numeric_value: (optional) An integer or float expressing the numeric value - of the `value` key. - :attr str unit: (optional) A string listing the unit of the value that was found in - the normalized text. - **Note:** The value of `unit` is the [ISO-4217 currency - code](https://www.iso.org/iso-4217-currency-codes.html) identified for the currency - amount (for example, `USD` or `EUR`). If the service cannot disambiguate a currency - symbol (for example, `$` or `£`), the value of `unit` contains the ambiguous symbol - as-is. + :attr float numeric_value: (optional) An integer or float expressing the numeric + value of the `value` key. + :attr str unit: (optional) A string listing the unit of the value that was found + in the normalized text. + **Note:** The value of `unit` is the [ISO-4217 currency + code](https://www.iso.org/iso-4217-currency-codes.html) identified for the + currency amount (for example, `USD` or `EUR`). If the service cannot + disambiguate a currency symbol (for example, `$` or `£`), the value of `unit` + contains the ambiguous symbol as-is. """ - def __init__(self, value=None, numeric_value=None, unit=None): + def __init__(self, *, value=None, numeric_value=None, unit=None): """ Initialize a Interpretation object. - :param str value: (optional) The value that was located in the normalized text. - :param float numeric_value: (optional) An integer or float expressing the numeric - value of the `value` key. - :param str unit: (optional) A string listing the unit of the value that was found - in the normalized text. - **Note:** The value of `unit` is the [ISO-4217 currency - code](https://www.iso.org/iso-4217-currency-codes.html) identified for the - currency amount (for example, `USD` or `EUR`). If the service cannot disambiguate - a currency symbol (for example, `$` or `£`), the value of `unit` contains the - ambiguous symbol as-is. + :param str value: (optional) The value that was located in the normalized + text. + :param float numeric_value: (optional) An integer or float expressing the + numeric value of the `value` key. + :param str unit: (optional) A string listing the unit of the value that was + found in the normalized text. + **Note:** The value of `unit` is the [ISO-4217 currency + code](https://www.iso.org/iso-4217-currency-codes.html) identified for the + currency amount (for example, `USD` or `EUR`). If the service cannot + disambiguate a currency symbol (for example, `$` or `£`), the value of + `unit` contains the ambiguous symbol as-is. """ self.value = value self.numeric_value = numeric_value @@ -3961,20 +4338,23 @@ class Key(object): A key in a key-value pair. :attr str cell_id: (optional) The unique ID of the key in the table. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The text content of the table cell without HTML markup. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. + :attr str text: (optional) The text content of the table cell without HTML + markup. """ - def __init__(self, cell_id=None, location=None, text=None): + def __init__(self, *, cell_id=None, location=None, text=None): """ Initialize a Key object. :param str cell_id: (optional) The unique ID of the key in the table. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. :param str text: (optional) The text content of the table cell without HTML - markup. + markup. """ self.cell_id = cell_id self.location = location @@ -4032,7 +4412,7 @@ class KeyValuePair(object): :attr list[Value] value: (optional) A list of values in a key-value pair. """ - def __init__(self, key=None, value=None): + def __init__(self, *, key=None, value=None): """ Initialize a KeyValuePair object. @@ -4153,21 +4533,23 @@ class LeadingSentence(object): The leading sentences in a section or subsection of the input document. :attr str text: (optional) The text of the leading sentence. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. - :attr list[ElementLocations] element_locations: (optional) An array of `location` - objects that lists the locations of detected leading sentences. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. + :attr list[ElementLocations] element_locations: (optional) An array of + `location` objects that lists the locations of detected leading sentences. """ - def __init__(self, text=None, location=None, element_locations=None): + def __init__(self, *, text=None, location=None, element_locations=None): """ Initialize a LeadingSentence object. :param str text: (optional) The text of the leading sentence. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. - :param list[ElementLocations] element_locations: (optional) An array of `location` - objects that lists the locations of detected leading sentences. + element in the document, represented with two integers labeled `begin` and + `end`. + :param list[ElementLocations] element_locations: (optional) An array of + `location` objects that lists the locations of detected leading sentences. """ self.text = text self.location = location @@ -4293,17 +4675,19 @@ class Mention(object): A mention of a party. :attr str text: (optional) The name of the party. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ - def __init__(self, text=None, location=None): + def __init__(self, *, text=None, location=None): """ Initialize a Mention object. :param str text: (optional) The name of the party. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.text = text self.location = location @@ -4352,20 +4736,20 @@ class OriginalLabelsIn(object): """ The original labeling from the input document, without the submitted feedback. - :attr list[TypeLabel] types: Description of the action specified by the element and - whom it affects. - :attr list[Category] categories: List of functional categories into which the element - falls; in other words, the subject matter of the element. + :attr list[TypeLabel] types: Description of the action specified by the element + and whom it affects. + :attr list[Category] categories: List of functional categories into which the + element falls; in other words, the subject matter of the element. """ def __init__(self, types, categories): """ Initialize a OriginalLabelsIn object. - :param list[TypeLabel] types: Description of the action specified by the element - and whom it affects. - :param list[Category] categories: List of functional categories into which the - element falls; in other words, the subject matter of the element. + :param list[TypeLabel] types: Description of the action specified by the + element and whom it affects. + :param list[Category] categories: List of functional categories into which + the element falls; in other words, the subject matter of the element. """ self.types = types self.categories = categories @@ -4426,26 +4810,27 @@ class OriginalLabelsOut(object): """ The original labeling from the input document, without the submitted feedback. - :attr list[TypeLabel] types: (optional) Description of the action specified by the - element and whom it affects. - :attr list[Category] categories: (optional) List of functional categories into which - the element falls; in other words, the subject matter of the element. - :attr str modification: (optional) A string identifying the type of modification the - feedback entry in the `updated_labels` array. Possible values are `added`, - `not_changed`, and `removed`. + :attr list[TypeLabel] types: (optional) Description of the action specified by + the element and whom it affects. + :attr list[Category] categories: (optional) List of functional categories into + which the element falls; in other words, the subject matter of the element. + :attr str modification: (optional) A string identifying the type of modification + the feedback entry in the `updated_labels` array. Possible values are `added`, + `not_changed`, and `removed`. """ - def __init__(self, types=None, categories=None, modification=None): + def __init__(self, *, types=None, categories=None, modification=None): """ Initialize a OriginalLabelsOut object. - :param list[TypeLabel] types: (optional) Description of the action specified by - the element and whom it affects. - :param list[Category] categories: (optional) List of functional categories into - which the element falls; in other words, the subject matter of the element. - :param str modification: (optional) A string identifying the type of modification - the feedback entry in the `updated_labels` array. Possible values are `added`, - `not_changed`, and `removed`. + :param list[TypeLabel] types: (optional) Description of the action + specified by the element and whom it affects. + :param list[Category] categories: (optional) List of functional categories + into which the element falls; in other words, the subject matter of the + element. + :param str modification: (optional) A string identifying the type of + modification the feedback entry in the `updated_labels` array. Possible + values are `added`, `not_changed`, and `removed`. """ self.types = types self.categories = categories @@ -4498,19 +4883,31 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ModificationEnum(Enum): + """ + A string identifying the type of modification the feedback entry in the + `updated_labels` array. Possible values are `added`, `not_changed`, and `removed`. + """ + ADDED = "added" + NOT_CHANGED = "not_changed" + REMOVED = "removed" + class Pagination(object): """ Pagination details, if required by the length of the output. - :attr str refresh_cursor: (optional) A token identifying the current page of results. + :attr str refresh_cursor: (optional) A token identifying the current page of + results. :attr str next_cursor: (optional) A token identifying the next page of results. - :attr str refresh_url: (optional) The URL that returns the current page of results. + :attr str refresh_url: (optional) The URL that returns the current page of + results. :attr str next_url: (optional) The URL that returns the next page of results. :attr int total: (optional) Reserved for future use. """ def __init__(self, + *, refresh_cursor=None, next_cursor=None, refresh_url=None, @@ -4519,12 +4916,14 @@ def __init__(self, """ Initialize a Pagination object. - :param str refresh_cursor: (optional) A token identifying the current page of - results. - :param str next_cursor: (optional) A token identifying the next page of results. + :param str refresh_cursor: (optional) A token identifying the current page + of results. + :param str next_cursor: (optional) A token identifying the next page of + results. :param str refresh_url: (optional) The URL that returns the current page of - results. - :param str next_url: (optional) The URL that returns the next page of results. + results. + :param str next_url: (optional) The URL that returns the next page of + results. :param int total: (optional) Reserved for future use. """ self.refresh_cursor = refresh_cursor @@ -4591,16 +4990,18 @@ class Paragraphs(object): """ The locations of each paragraph in the input document. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ - def __init__(self, location=None): + def __init__(self, *, location=None): """ Initialize a Paragraphs object. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.location = location @@ -4647,18 +5048,21 @@ class Parties(object): :attr str party: (optional) The normalized form of the party's name. :attr str role: (optional) A string identifying the party's role. - :attr str importance: (optional) A string that identifies the importance of the party. - :attr list[Address] addresses: (optional) A list of the party's address or addresses. - :attr list[Contact] contacts: (optional) A list of the names and roles of contacts - identified in the input document. - :attr list[Mention] mentions: (optional) A list of the party's mentions in the input - document. + :attr str importance: (optional) A string that identifies the importance of the + party. + :attr list[Address] addresses: (optional) A list of the party's address or + addresses. + :attr list[Contact] contacts: (optional) A list of the names and roles of + contacts identified in the input document. + :attr list[Mention] mentions: (optional) A list of the party's mentions in the + input document. """ def __init__(self, + *, party=None, - importance=None, role=None, + importance=None, addresses=None, contacts=None, mentions=None): @@ -4667,14 +5071,14 @@ def __init__(self, :param str party: (optional) The normalized form of the party's name. :param str role: (optional) A string identifying the party's role. - :param str importance: (optional) A string that identifies the importance of the - party. + :param str importance: (optional) A string that identifies the importance + of the party. :param list[Address] addresses: (optional) A list of the party's address or - addresses. + addresses. :param list[Contact] contacts: (optional) A list of the names and roles of - contacts identified in the input document. - :param list[Mention] mentions: (optional) A list of the party's mentions in the - input document. + contacts identified in the input document. + :param list[Mention] mentions: (optional) A list of the party's mentions in + the input document. """ self.party = party self.role = role @@ -4746,26 +5150,36 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ImportanceEnum(Enum): + """ + A string that identifies the importance of the party. + """ + PRIMARY = "Primary" + UNKNOWN = "Unknown" + class PaymentTerms(object): """ The document's payment duration or durations. - :attr str confidence_level: (optional) The confidence level in the identification of - the payment term. + :attr str confidence_level: (optional) The confidence level in the + identification of the payment term. :attr str text: (optional) The payment term (duration). - :attr str text_normalized: (optional) The normalized form of the payment term, which - is listed as a string. This element is optional; it is returned only if normalized - text exists. - :attr Interpretation interpretation: (optional) The details of the normalized text, if - applicable. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to IBM to - provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr str text_normalized: (optional) The normalized form of the payment term, + which is listed as a string. This element is optional; it is returned only if + normalized text exists. + :attr Interpretation interpretation: (optional) The details of the normalized + text, if applicable. This element is optional; it is returned only if normalized + text exists. + :attr list[str] provenance_ids: (optional) Hashed values that you can send to + IBM to provide feedback or receive support. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ def __init__(self, + *, confidence_level=None, text=None, text_normalized=None, @@ -4775,19 +5189,20 @@ def __init__(self, """ Initialize a PaymentTerms object. - :param str confidence_level: (optional) The confidence level in the identification - of the payment term. + :param str confidence_level: (optional) The confidence level in the + identification of the payment term. :param str text: (optional) The payment term (duration). - :param str text_normalized: (optional) The normalized form of the payment term, - which is listed as a string. This element is optional; it is returned only if - normalized text exists. - :param Interpretation interpretation: (optional) The details of the normalized - text, if applicable. This element is optional; it is returned only if normalized - text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send to IBM - to provide feedback or receive support. + :param str text_normalized: (optional) The normalized form of the payment + term, which is listed as a string. This element is optional; it is returned + only if normalized text exists. + :param Interpretation interpretation: (optional) The details of the + normalized text, if applicable. This element is optional; it is returned + only if normalized text exists. + :param list[str] provenance_ids: (optional) Hashed values that you can send + to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.confidence_level = confidence_level self.text = text @@ -4857,6 +5272,14 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConfidenceLevelEnum(Enum): + """ + The confidence level in the identification of the payment term. + """ + HIGH = "High" + MEDIUM = "Medium" + LOW = "Low" + class RowHeaders(object): """ @@ -4864,24 +5287,26 @@ class RowHeaders(object): of the current table. :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The textual contents of this cell from the input document - without associated markup content. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. + :attr str text: (optional) The textual contents of this cell from the input + document without associated markup content. :attr str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, the - same value as `text`. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` location - in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` location in - the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's `column` - location in the current table. + normalized version of the cell text according to the customization; otherwise, + the same value as `text`. + :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + location in the current table. + :attr int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :attr int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. :attr int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. + location in the current table. """ def __init__(self, + *, cell_id=None, location=None, text=None, @@ -4893,22 +5318,24 @@ def __init__(self, """ Initialize a RowHeaders object. - :param str cell_id: (optional) The unique ID of the cell in the current table. + :param str cell_id: (optional) The unique ID of the cell in the current + table. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. - :param str text: (optional) The textual contents of this cell from the input - document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, the - same value as `text`. - :param int row_index_begin: (optional) The `begin` index of this cell's `row` - location in the current table. - :param int row_index_end: (optional) The `end` index of this cell's `row` location - in the current table. + element in the document, represented with two integers labeled `begin` and + `end`. + :param str text: (optional) The textual contents of this cell from the + input document without associated markup content. + :param str text_normalized: (optional) If you provide customization input, + the normalized version of the cell text according to the customization; + otherwise, the same value as `text`. + :param int row_index_begin: (optional) The `begin` index of this cell's + `row` location in the current table. + :param int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. :param int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :param int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. + `column` location in the current table. + :param int column_index_end: (optional) The `end` index of this cell's + `column` location in the current table. """ self.cell_id = cell_id self.location = location @@ -4996,17 +5423,19 @@ class SectionTitle(object): The table's section title, if identified. :attr str text: (optional) The text of the section title, if identified. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ - def __init__(self, text=None, location=None): + def __init__(self, *, text=None, location=None): """ Initialize a SectionTitle object. :param str text: (optional) The text of the section title, if identified. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.text = text self.location = location @@ -5059,16 +5488,18 @@ class SectionTitles(object): the `level` value of the section. :attr str text: (optional) The text of the section title, if identified. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. - :attr int level: (optional) An integer indicating the level at which the section is - located in the input document. For example, `1` represents a top-level section, `2` - represents a subsection within the level `1` section, and so forth. - :attr list[ElementLocations] element_locations: (optional) An array of `location` - objects that lists the locations of detected section titles. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. + :attr int level: (optional) An integer indicating the level at which the section + is located in the input document. For example, `1` represents a top-level + section, `2` represents a subsection within the level `1` section, and so forth. + :attr list[ElementLocations] element_locations: (optional) An array of + `location` objects that lists the locations of detected section titles. """ def __init__(self, + *, text=None, location=None, level=None, @@ -5078,12 +5509,14 @@ def __init__(self, :param str text: (optional) The text of the section title, if identified. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. - :param int level: (optional) An integer indicating the level at which the section - is located in the input document. For example, `1` represents a top-level section, - `2` represents a subsection within the level `1` section, and so forth. - :param list[ElementLocations] element_locations: (optional) An array of `location` - objects that lists the locations of detected section titles. + element in the document, represented with two integers labeled `begin` and + `end`. + :param int level: (optional) An integer indicating the level at which the + section is located in the input document. For example, `1` represents a + top-level section, `2` represents a subsection within the level `1` + section, and so forth. + :param list[ElementLocations] element_locations: (optional) An array of + `location` objects that lists the locations of detected section titles. """ self.text = text self.location = location @@ -5152,11 +5585,12 @@ class ShortDoc(object): :attr str hash: (optional) The MD5 hash of the input document. """ - def __init__(self, title=None, hash=None): + def __init__(self, *, title=None, hash=None): """ Initialize a ShortDoc object. - :param str title: (optional) The title of the input document, if identified. + :param str title: (optional) The title of the input document, if + identified. :param str hash: (optional) The MD5 hash of the input document. """ self.title = title @@ -5207,22 +5641,23 @@ class TableHeaders(object): The contents of the current table's header. :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr object location: (optional) The location of the table header cell in the current - table as defined by its `begin` and `end` offsets, respectfully, in the input - document. - :attr str text: (optional) The textual contents of the cell from the input document - without associated markup content. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` location - in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` location in - the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's `column` - location in the current table. + :attr object location: (optional) The location of the table header cell in the + current table as defined by its `begin` and `end` offsets, respectfully, in the + input document. + :attr str text: (optional) The textual contents of the cell from the input + document without associated markup content. + :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + location in the current table. + :attr int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :attr int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. :attr int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. + location in the current table. """ def __init__(self, + *, cell_id=None, location=None, text=None, @@ -5233,20 +5668,21 @@ def __init__(self, """ Initialize a TableHeaders object. - :param str cell_id: (optional) The unique ID of the cell in the current table. - :param object location: (optional) The location of the table header cell in the - current table as defined by its `begin` and `end` offsets, respectfully, in the - input document. + :param str cell_id: (optional) The unique ID of the cell in the current + table. + :param object location: (optional) The location of the table header cell in + the current table as defined by its `begin` and `end` offsets, + respectfully, in the input document. :param str text: (optional) The textual contents of the cell from the input - document without associated markup content. - :param int row_index_begin: (optional) The `begin` index of this cell's `row` - location in the current table. - :param int row_index_end: (optional) The `end` index of this cell's `row` location - in the current table. + document without associated markup content. + :param int row_index_begin: (optional) The `begin` index of this cell's + `row` location in the current table. + :param int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. :param int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :param int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. + `column` location in the current table. + :param int column_index_end: (optional) The `end` index of this cell's + `column` location in the current table. """ self.cell_id = cell_id self.location = location @@ -5328,14 +5764,15 @@ class TableReturn(object): The analysis of the document's tables. :attr DocInfo document: (optional) Information about the parsed input document. - :attr str model_id: (optional) The ID of the model used to extract the table contents. - The value for table extraction is `tables`. + :attr str model_id: (optional) The ID of the model used to extract the table + contents. The value for table extraction is `tables`. :attr str model_version: (optional) The version of the `tables` model ID. - :attr list[Tables] tables: (optional) Definitions of the tables identified in the - input document. + :attr list[Tables] tables: (optional) Definitions of the tables identified in + the input document. """ def __init__(self, + *, document=None, model_id=None, model_version=None, @@ -5343,12 +5780,13 @@ def __init__(self, """ Initialize a TableReturn object. - :param DocInfo document: (optional) Information about the parsed input document. - :param str model_id: (optional) The ID of the model used to extract the table - contents. The value for table extraction is `tables`. + :param DocInfo document: (optional) Information about the parsed input + document. + :param str model_id: (optional) The ID of the model used to extract the + table contents. The value for table extraction is `tables`. :param str model_version: (optional) The version of the `tables` model ID. - :param list[Tables] tables: (optional) Definitions of the tables identified in the - input document. + :param list[Tables] tables: (optional) Definitions of the tables identified + in the input document. """ self.document = document self.model_id = model_id @@ -5411,18 +5849,21 @@ class TableTitle(object): Empty when no title is identified. When exposed, the `title` is also excluded from the `contexts` array of the same table. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. :attr str text: (optional) The text of the identified table title or caption. """ - def __init__(self, location=None, text=None): + def __init__(self, *, location=None, text=None): """ Initialize a TableTitle object. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. - :param str text: (optional) The text of the identified table title or caption. + element in the document, represented with two integers labeled `begin` and + `end`. + :param str text: (optional) The text of the identified table title or + caption. """ self.location = location self.text = text @@ -5471,69 +5912,77 @@ class Tables(object): """ The contents of the tables extracted from a document. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The textual contents of the current table from the input - document without associated markup content. - :attr SectionTitle section_title: (optional) The table's section title, if identified. - :attr TableTitle title: (optional) If identified, the title or caption of the current - table of the form `Table x.: ...`. Empty when no title is identified. When exposed, - the `title` is also excluded from the `contexts` array of the same table. - :attr list[TableHeaders] table_headers: (optional) An array of table-level cells that - apply as headers to all the other cells in the current table. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. + :attr str text: (optional) The textual contents of the current table from the + input document without associated markup content. + :attr SectionTitle section_title: (optional) The table's section title, if + identified. + :attr TableTitle title: (optional) If identified, the title or caption of the + current table of the form `Table x.: ...`. Empty when no title is identified. + When exposed, the `title` is also excluded from the `contexts` array of the same + table. + :attr list[TableHeaders] table_headers: (optional) An array of table-level cells + that apply as headers to all the other cells in the current table. :attr list[RowHeaders] row_headers: (optional) An array of row-level cells, each - applicable as a header to other cells in the same row as itself, of the current table. - :attr list[ColumnHeaders] column_headers: (optional) An array of column-level cells, - each applicable as a header to other cells in the same column as itself, of the - current table. - :attr list[BodyCells] body_cells: (optional) An array of cells that are neither table - header nor column header nor row header cells, of the current table with corresponding - row and column header associations. - :attr list[Contexts] contexts: (optional) An array of objects that list text that is - related to the table contents and that precedes or follows the current table. + applicable as a header to other cells in the same row as itself, of the current + table. + :attr list[ColumnHeaders] column_headers: (optional) An array of column-level + cells, each applicable as a header to other cells in the same column as itself, + of the current table. + :attr list[BodyCells] body_cells: (optional) An array of cells that are neither + table header nor column header nor row header cells, of the current table with + corresponding row and column header associations. + :attr list[Contexts] contexts: (optional) An array of objects that list text + that is related to the table contents and that precedes or follows the current + table. :attr list[KeyValuePair] key_value_pairs: (optional) An array of key-value pairs - identified in the current table. + identified in the current table. """ - def __init__( - self, - location=None, - text=None, - section_title=None, - table_headers=None, - row_headers=None, - column_headers=None, - key_value_pairs=None, - body_cells=None, - contexts=None, - title=None): + def __init__(self, + *, + location=None, + text=None, + section_title=None, + title=None, + table_headers=None, + row_headers=None, + column_headers=None, + body_cells=None, + contexts=None, + key_value_pairs=None): """ Initialize a Tables object. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. - :param str text: (optional) The textual contents of the current table from the - input document without associated markup content. + element in the document, represented with two integers labeled `begin` and + `end`. + :param str text: (optional) The textual contents of the current table from + the input document without associated markup content. :param SectionTitle section_title: (optional) The table's section title, if - identified. - :param TableTitle title: (optional) If identified, the title or caption of the - current table of the form `Table x.: ...`. Empty when no title is identified. When - exposed, the `title` is also excluded from the `contexts` array of the same table. - :param list[TableHeaders] table_headers: (optional) An array of table-level cells - that apply as headers to all the other cells in the current table. - :param list[RowHeaders] row_headers: (optional) An array of row-level cells, each - applicable as a header to other cells in the same row as itself, of the current - table. - :param list[ColumnHeaders] column_headers: (optional) An array of column-level - cells, each applicable as a header to other cells in the same column as itself, of - the current table. - :param list[BodyCells] body_cells: (optional) An array of cells that are neither - table header nor column header nor row header cells, of the current table with - corresponding row and column header associations. - :param list[Contexts] contexts: (optional) An array of objects that list text that - is related to the table contents and that precedes or follows the current table. - :param list[KeyValuePair] key_value_pairs: (optional) An array of key-value pairs - identified in the current table. + identified. + :param TableTitle title: (optional) If identified, the title or caption of + the current table of the form `Table x.: ...`. Empty when no title is + identified. When exposed, the `title` is also excluded from the `contexts` + array of the same table. + :param list[TableHeaders] table_headers: (optional) An array of table-level + cells that apply as headers to all the other cells in the current table. + :param list[RowHeaders] row_headers: (optional) An array of row-level + cells, each applicable as a header to other cells in the same row as + itself, of the current table. + :param list[ColumnHeaders] column_headers: (optional) An array of + column-level cells, each applicable as a header to other cells in the same + column as itself, of the current table. + :param list[BodyCells] body_cells: (optional) An array of cells that are + neither table header nor column header nor row header cells, of the current + table with corresponding row and column header associations. + :param list[Contexts] contexts: (optional) An array of objects that list + text that is related to the table contents and that precedes or follows the + current table. + :param list[KeyValuePair] key_value_pairs: (optional) An array of key-value + pairs identified in the current table. """ self.location = location self.text = text @@ -5646,19 +6095,21 @@ class TerminationDates(object): """ Termination dates identified in the input document. - :attr str confidence_level: (optional) The confidence level in the identification of - the termination date. + :attr str confidence_level: (optional) The confidence level in the + identification of the termination date. :attr str text: (optional) The termination date. - :attr str text_normalized: (optional) The normalized form of the termination date, - which is listed as a string. This element is optional; it is returned only if - normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to IBM to - provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr str text_normalized: (optional) The normalized form of the termination + date, which is listed as a string. This element is optional; it is returned only + if normalized text exists. + :attr list[str] provenance_ids: (optional) Hashed values that you can send to + IBM to provide feedback or receive support. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. """ def __init__(self, + *, confidence_level=None, text=None, text_normalized=None, @@ -5667,16 +6118,17 @@ def __init__(self, """ Initialize a TerminationDates object. - :param str confidence_level: (optional) The confidence level in the identification - of the termination date. + :param str confidence_level: (optional) The confidence level in the + identification of the termination date. :param str text: (optional) The termination date. - :param str text_normalized: (optional) The normalized form of the termination - date, which is listed as a string. This element is optional; it is returned only - if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send to IBM - to provide feedback or receive support. + :param str text_normalized: (optional) The normalized form of the + termination date, which is listed as a string. This element is optional; it + is returned only if normalized text exists. + :param list[str] provenance_ids: (optional) Hashed values that you can send + to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. """ self.confidence_level = confidence_level self.text = text @@ -5740,27 +6192,35 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConfidenceLevelEnum(Enum): + """ + The confidence level in the identification of the termination date. + """ + HIGH = "High" + MEDIUM = "Medium" + LOW = "Low" + class TypeLabel(object): """ Identification of a specific type. - :attr Label label: (optional) A pair of `nature` and `party` objects. The `nature` - object identifies the effect of the element on the identified `party`, and the `party` - object identifies the affected party. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to IBM to - provide feedback or receive support. + :attr Label label: (optional) A pair of `nature` and `party` objects. The + `nature` object identifies the effect of the element on the identified `party`, + and the `party` object identifies the affected party. + :attr list[str] provenance_ids: (optional) Hashed values that you can send to + IBM to provide feedback or receive support. """ - def __init__(self, label=None, provenance_ids=None): + def __init__(self, *, label=None, provenance_ids=None): """ Initialize a TypeLabel object. :param Label label: (optional) A pair of `nature` and `party` objects. The - `nature` object identifies the effect of the element on the identified `party`, - and the `party` object identifies the affected party. - :param list[str] provenance_ids: (optional) Hashed values that you can send to IBM - to provide feedback or receive support. + `nature` object identifies the effect of the element on the identified + `party`, and the `party` object identifies the affected party. + :param list[str] provenance_ids: (optional) Hashed values that you can send + to IBM to provide feedback or receive support. """ self.label = label self.provenance_ids = provenance_ids @@ -5809,18 +6269,18 @@ class TypeLabelComparison(object): """ Identification of a specific type. - :attr Label label: (optional) A pair of `nature` and `party` objects. The `nature` - object identifies the effect of the element on the identified `party`, and the `party` - object identifies the affected party. + :attr Label label: (optional) A pair of `nature` and `party` objects. The + `nature` object identifies the effect of the element on the identified `party`, + and the `party` object identifies the affected party. """ - def __init__(self, label=None): + def __init__(self, *, label=None): """ Initialize a TypeLabelComparison object. :param Label label: (optional) A pair of `nature` and `party` objects. The - `nature` object identifies the effect of the element on the identified `party`, - and the `party` object identifies the affected party. + `nature` object identifies the effect of the element on the identified + `party`, and the `party` object identifies the affected party. """ self.label = label @@ -5864,20 +6324,23 @@ class UnalignedElement(object): """ Element that does not align semantically between two compared documents. - :attr str document_label: (optional) The label assigned to the document by the value - of the `file_1_label` or `file_2_label` parameters on the **Compare two documents** - method. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. + :attr str document_label: (optional) The label assigned to the document by the + value of the `file_1_label` or `file_2_label` parameters on the **Compare two + documents** method. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. :attr str text: (optional) The text of the element. - :attr list[TypeLabelComparison] types: (optional) Description of the action specified - by the element and whom it affects. - :attr list[CategoryComparison] categories: (optional) List of functional categories - into which the element falls; in other words, the subject matter of the element. + :attr list[TypeLabelComparison] types: (optional) Description of the action + specified by the element and whom it affects. + :attr list[CategoryComparison] categories: (optional) List of functional + categories into which the element falls; in other words, the subject matter of + the element. :attr list[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, + *, document_label=None, location=None, text=None, @@ -5887,17 +6350,18 @@ def __init__(self, """ Initialize a UnalignedElement object. - :param str document_label: (optional) The label assigned to the document by the - value of the `file_1_label` or `file_2_label` parameters on the **Compare two - documents** method. + :param str document_label: (optional) The label assigned to the document by + the value of the `file_1_label` or `file_2_label` parameters on the + **Compare two documents** method. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. :param str text: (optional) The text of the element. - :param list[TypeLabelComparison] types: (optional) Description of the action - specified by the element and whom it affects. + :param list[TypeLabelComparison] types: (optional) Description of the + action specified by the element and whom it affects. :param list[CategoryComparison] categories: (optional) List of functional - categories into which the element falls; in other words, the subject matter of the - element. + categories into which the element falls; in other words, the subject matter + of the element. :param list[Attribute] attributes: (optional) List of document attributes. """ self.document_label = document_label @@ -5977,20 +6441,20 @@ class UpdatedLabelsIn(object): """ The updated labeling from the input document, accounting for the submitted feedback. - :attr list[TypeLabel] types: Description of the action specified by the element and - whom it affects. - :attr list[Category] categories: List of functional categories into which the element - falls; in other words, the subject matter of the element. + :attr list[TypeLabel] types: Description of the action specified by the element + and whom it affects. + :attr list[Category] categories: List of functional categories into which the + element falls; in other words, the subject matter of the element. """ def __init__(self, types, categories): """ Initialize a UpdatedLabelsIn object. - :param list[TypeLabel] types: Description of the action specified by the element - and whom it affects. - :param list[Category] categories: List of functional categories into which the - element falls; in other words, the subject matter of the element. + :param list[TypeLabel] types: Description of the action specified by the + element and whom it affects. + :param list[Category] categories: List of functional categories into which + the element falls; in other words, the subject matter of the element. """ self.types = types self.categories = categories @@ -6051,25 +6515,27 @@ class UpdatedLabelsOut(object): """ The updated labeling from the input document, accounting for the submitted feedback. - :attr list[TypeLabel] types: (optional) Description of the action specified by the - element and whom it affects. - :attr list[Category] categories: (optional) List of functional categories into which - the element falls; in other words, the subject matter of the element. - :attr str modification: (optional) The type of modification the feedback entry in the - `updated_labels` array. Possible values are `added`, `not_changed`, and `removed`. + :attr list[TypeLabel] types: (optional) Description of the action specified by + the element and whom it affects. + :attr list[Category] categories: (optional) List of functional categories into + which the element falls; in other words, the subject matter of the element. + :attr str modification: (optional) The type of modification the feedback entry + in the `updated_labels` array. Possible values are `added`, `not_changed`, and + `removed`. """ - def __init__(self, types=None, categories=None, modification=None): + def __init__(self, *, types=None, categories=None, modification=None): """ Initialize a UpdatedLabelsOut object. - :param list[TypeLabel] types: (optional) Description of the action specified by - the element and whom it affects. - :param list[Category] categories: (optional) List of functional categories into - which the element falls; in other words, the subject matter of the element. - :param str modification: (optional) The type of modification the feedback entry in - the `updated_labels` array. Possible values are `added`, `not_changed`, and - `removed`. + :param list[TypeLabel] types: (optional) Description of the action + specified by the element and whom it affects. + :param list[Category] categories: (optional) List of functional categories + into which the element falls; in other words, the subject matter of the + element. + :param str modification: (optional) The type of modification the feedback + entry in the `updated_labels` array. Possible values are `added`, + `not_changed`, and `removed`. """ self.types = types self.categories = categories @@ -6122,26 +6588,38 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ModificationEnum(Enum): + """ + The type of modification the feedback entry in the `updated_labels` array. + Possible values are `added`, `not_changed`, and `removed`. + """ + ADDED = "added" + NOT_CHANGED = "not_changed" + REMOVED = "removed" + class Value(object): """ A value in a key-value pair. :attr str cell_id: (optional) The unique ID of the value in the table. - :attr Location location: (optional) The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The text content of the table cell without HTML markup. + :attr Location location: (optional) The numeric location of the identified + element in the document, represented with two integers labeled `begin` and + `end`. + :attr str text: (optional) The text content of the table cell without HTML + markup. """ - def __init__(self, cell_id=None, location=None, text=None): + def __init__(self, *, cell_id=None, location=None, text=None): """ Initialize a Value object. :param str cell_id: (optional) The unique ID of the value in the table. :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and `end`. + element in the document, represented with two integers labeled `begin` and + `end`. :param str text: (optional) The text content of the table cell without HTML - markup. + markup. """ self.cell_id = cell_id self.location = location From 2fc22dcdde989946250a4d40a83c1bb48c484a68 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 20:05:52 -0400 Subject: [PATCH 009/455] chore(compare complly): Hand edit compare complly --- ibm_watson/compare_comply_v1.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 1f7cd4cdc..35a63e185 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -24,7 +24,6 @@ from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime from ibm_cloud_sdk_core import get_authenticator_from_environment -from os.path import basename ############################################################################## # Service From c8b6be36843a1f915c84887ed7bcb178301cadd3 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 20:06:21 -0400 Subject: [PATCH 010/455] test(compare comply): Update compare comply integration tests --- test/integration/test_compare_comply_v1.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/integration/test_compare_comply_v1.py b/test/integration/test_compare_comply_v1.py index 4d00358a8..d74f5ec46 100644 --- a/test/integration/test_compare_comply_v1.py +++ b/test/integration/test_compare_comply_v1.py @@ -32,7 +32,7 @@ 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, '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): @@ -126,8 +126,8 @@ def test_feedback(self): add_feedback = self.compare_comply.add_feedback( feedback_data, - 'wonder woman', - 'test commment').get_result() + 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'] From 603a10205eb87deda106ff6e1a31a403a9420b0b Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 20:13:39 -0400 Subject: [PATCH 011/455] test(compare comply): Update compare comply unit tests --- test/unit/test_compare_comply_v1.py | 54 ++++++++++++++--------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 4ff715c1d..bdd543c05 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -5,8 +5,8 @@ import os import time import jwt - from unittest import TestCase +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator base_url = "https://gateway.watsonplatform.net/compare-comply/api" feedback = { @@ -152,8 +152,8 @@ def setUp(cls): @responses.activate def test_convert_to_html(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/html_conversion') @@ -184,8 +184,8 @@ def test_convert_to_html(self): @responses.activate def test_classify_elements(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/element_classification') @@ -226,8 +226,8 @@ def test_classify_elements(self): @responses.activate def test_extract_tables(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/tables') @@ -275,8 +275,8 @@ def test_extract_tables(self): @responses.activate def test_compare_documents(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/comparison') @@ -335,8 +335,8 @@ def test_compare_documents(self): @responses.activate def test_add_feedback(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/feedback') @@ -422,16 +422,16 @@ def test_add_feedback(self): result = service.add_feedback( feedback_data, - "wonder woman", - "test commment").get_result() + user_id="wonder woman", + comment="test commment").get_result() assert result["feedback_id"] == "lala" assert len(responses.calls) == 2 @responses.activate def test_get_feedback(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/feedback/xxx') @@ -449,8 +449,8 @@ def test_get_feedback(self): @responses.activate def test_list_feedback(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/feedback') @@ -468,8 +468,8 @@ def test_list_feedback(self): @responses.activate def test_delete_feedback(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/feedback/xxx') @@ -492,8 +492,8 @@ def test_delete_feedback(self): @responses.activate def test_create_batch(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/batches') @@ -522,8 +522,8 @@ def test_create_batch(self): @responses.activate def test_get_batch(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/batches/xxx') @@ -541,8 +541,8 @@ def test_get_batch(self): @responses.activate def test_list_batches(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/batches') @@ -560,8 +560,8 @@ def test_list_batches(self): @responses.activate def test_update_batch(self): - service = ibm_watson.CompareComplyV1( - '2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) url = "{0}{1}".format(base_url, '/v1/batches/xxx') From d31fa6e8089c7ca1d836aad1e8611d76f60c0e85 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 20:17:20 -0400 Subject: [PATCH 012/455] examples(compare comply): Update compare comply examples --- examples/compare_comply_v1.py | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/examples/compare_comply_v1.py b/examples/compare_comply_v1.py index e69770b2a..e41a70c38 100644 --- a/examples/compare_comply_v1.py +++ b/examples/compare_comply_v1.py @@ -3,20 +3,14 @@ import json import os from ibm_watson import CompareComplyV1 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -# If service instance provides API key authentication +authenticator = IAMAuthenticator('your apikey') compare_comply = CompareComplyV1( version='2018-03-23', ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/compare-comply/api', - iam_apikey='YOUR APIKEY') - -# compare_comply = CompareComplyV1( -# version='2018-03-23', -# ## url is optional, and defaults to the URL below. Use the correct URL for your region. -# # url='https://gateway.watsonplatform.net/compare-comply/api', -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD') + authenticator=authenticator) print('Convert to HTML') contract = os.path.abspath('resources/contract_A.pdf') @@ -27,7 +21,7 @@ print('Classify elements') contract = os.path.abspath('resources/contract_A.pdf') with open(contract, 'rb') as file: - result = compare_comply.classify_elements(file, 'application/pdf').get_result() + result = compare_comply.classify_elements(file, file_content_type='application/pdf').get_result() print(json.dumps(result, indent=2)) print('Extract tables') From bac470fe6673ea137d52e1169f6d8580e7ed298f Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 20:17:53 -0400 Subject: [PATCH 013/455] feat(discovery): Generate discovery --- ibm_watson/discovery_v1.py | 5136 ++++++++++++++++++++---------------- 1 file changed, 2933 insertions(+), 2203 deletions(-) diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index ac347b043..0688a537b 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,12 +21,12 @@ results. """ -from __future__ import absolute_import - import json from .common import get_sdk_headers +from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime +from ibm_cloud_sdk_core import get_authenticator_from_environment from os.path import basename ############################################################################## @@ -43,16 +43,8 @@ def __init__( self, version, url=default_url, - username=None, - password=None, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, + authenticator=None, + disable_ssl_verification=False, ): """ Construct a new client for the Discovery service. @@ -72,69 +64,29 @@ def __init__( "https://gateway.watsonplatform.net/discovery/api/discovery/api"). The base url may differ between IBM Cloud regions. - :param str username: The username used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str password: The password used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ + if not authenticator: + authenticator = get_authenticator_from_environment('Discovery') + BaseService.__init__( self, - vcap_services_name='discovery', url=url, - username=username, - password=password, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Discovery', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Discovery') self.version = version ######################### # Environments ######################### - def create_environment(self, name, description=None, size=None, **kwargs): + def create_environment(self, name, *, description=None, size=None, + **kwargs): """ Create an environment. @@ -144,9 +96,10 @@ def create_environment(self, name, description=None, size=None, **kwargs): instance. An attempt to create another environment results in an error. :param str name: Name that identifies the environment. - :param str description: Description of the environment. - :param str size: Size of the environment. In the Lite plan the default and only - accepted value is `LT`, in all other plans the default is `S`. + :param str description: (optional) Description of the environment. + :param str size: (optional) Size of the environment. In the Lite plan the + default and only accepted value is `LT`, in all other plans the default is + `S`. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -166,22 +119,23 @@ def create_environment(self, name, description=None, size=None, **kwargs): data = {'name': name, 'description': description, 'size': size} url = '/v1/environments' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response - def list_environments(self, name=None, **kwargs): + def list_environments(self, *, name=None, **kwargs): """ List environments. List existing environments for the service instance. - :param str name: Show only the environment with the given name. + :param str name: (optional) Show only the environment with the given name. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -196,12 +150,13 @@ def list_environments(self, name=None, **kwargs): params = {'version': self.version, 'name': name} url = '/v1/environments' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_environment(self, environment_id, **kwargs): @@ -227,16 +182,18 @@ def get_environment(self, environment_id, **kwargs): url = '/v1/environments/{0}'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_environment(self, environment_id, + *, name=None, description=None, size=None, @@ -248,11 +205,11 @@ def update_environment(self, can be changed. You must specify a **name** for the environment. :param str environment_id: The ID of the environment. - :param str name: Name that identifies the environment. - :param str description: Description of the environment. - :param str size: Size that the environment should be increased to. Environment - size cannot be modified when using a Lite plan. Environment size can only - increased and not decreased. + :param str name: (optional) Name that identifies the environment. + :param str description: (optional) Description of the environment. + :param str size: (optional) Size that the environment should be increased + to. Environment size cannot be modified when using a Lite plan. Environment + size can only increased and not decreased. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -273,13 +230,14 @@ def update_environment(self, url = '/v1/environments/{0}'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='PUT', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_environment(self, environment_id, **kwargs): @@ -305,12 +263,13 @@ def delete_environment(self, environment_id, **kwargs): url = '/v1/environments/{0}'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def list_fields(self, environment_id, collection_ids, **kwargs): @@ -321,8 +280,8 @@ def list_fields(self, environment_id, collection_ids, **kwargs): specified collections. :param str environment_id: The ID of the environment. - :param list[str] collection_ids: A comma-separated list of collection IDs to be - queried against. + :param list[str] collection_ids: A comma-separated list of collection IDs + to be queried against. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -346,12 +305,13 @@ def list_fields(self, environment_id, collection_ids, **kwargs): url = '/v1/environments/{0}/fields'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -361,6 +321,7 @@ def list_fields(self, environment_id, collection_ids, **kwargs): def create_configuration(self, environment_id, name, + *, description=None, conversions=None, enrichments=None, @@ -383,14 +344,17 @@ def create_configuration(self, :param str environment_id: The ID of the environment. :param str name: The name of the configuration. - :param str description: The description of the configuration, if available. - :param Conversions conversions: Document conversion settings. - :param list[Enrichment] enrichments: An array of document enrichment settings for - the configuration. - :param list[NormalizationOperation] normalizations: Defines operations that can be - used to transform the final output JSON into a normalized form. Operations are - executed in the order that they appear in the array. - :param Source source: Object containing source parameters for the configuration. + :param str description: (optional) The description of the configuration, if + available. + :param Conversions conversions: (optional) Document conversion settings. + :param list[Enrichment] enrichments: (optional) An array of document + enrichment settings for the configuration. + :param list[NormalizationOperation] normalizations: (optional) Defines + operations that can be used to transform the final output JSON into a + normalized form. Operations are executed in the order that they appear in + the array. + :param Source source: (optional) Object containing source parameters for + the configuration. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -433,23 +397,24 @@ def create_configuration(self, url = '/v1/environments/{0}/configurations'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response - def list_configurations(self, environment_id, name=None, **kwargs): + def list_configurations(self, environment_id, *, name=None, **kwargs): """ List configurations. Lists existing configurations for the service instance. :param str environment_id: The ID of the environment. - :param str name: Find configurations with the given name. + :param str name: (optional) Find configurations with the given name. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -468,12 +433,13 @@ def list_configurations(self, environment_id, name=None, **kwargs): url = '/v1/environments/{0}/configurations'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_configuration(self, environment_id, configuration_id, **kwargs): @@ -502,18 +468,20 @@ def get_configuration(self, environment_id, configuration_id, **kwargs): url = '/v1/environments/{0}/configurations/{1}'.format( *self._encode_path_vars(environment_id, configuration_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_configuration(self, environment_id, configuration_id, name, + *, description=None, conversions=None, enrichments=None, @@ -536,14 +504,17 @@ def update_configuration(self, :param str environment_id: The ID of the environment. :param str configuration_id: The ID of the configuration. :param str name: The name of the configuration. - :param str description: The description of the configuration, if available. - :param Conversions conversions: Document conversion settings. - :param list[Enrichment] enrichments: An array of document enrichment settings for - the configuration. - :param list[NormalizationOperation] normalizations: Defines operations that can be - used to transform the final output JSON into a normalized form. Operations are - executed in the order that they appear in the array. - :param Source source: Object containing source parameters for the configuration. + :param str description: (optional) The description of the configuration, if + available. + :param Conversions conversions: (optional) Document conversion settings. + :param list[Enrichment] enrichments: (optional) An array of document + enrichment settings for the configuration. + :param list[NormalizationOperation] normalizations: (optional) Defines + operations that can be used to transform the final output JSON into a + normalized form. Operations are executed in the order that they appear in + the array. + :param Source source: (optional) Object containing source parameters for + the configuration. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -588,13 +559,14 @@ def update_configuration(self, url = '/v1/environments/{0}/configurations/{1}'.format( *self._encode_path_vars(environment_id, configuration_id)) - response = self.request( + request = self.prepare_request( method='PUT', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_configuration(self, environment_id, configuration_id, **kwargs): @@ -630,12 +602,13 @@ def delete_configuration(self, environment_id, configuration_id, **kwargs): url = '/v1/environments/{0}/configurations/{1}'.format( *self._encode_path_vars(environment_id, configuration_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -644,6 +617,7 @@ def delete_configuration(self, environment_id, configuration_id, **kwargs): def test_configuration_in_environment(self, environment_id, + *, configuration=None, file=None, filename=None, @@ -662,31 +636,31 @@ def test_configuration_in_environment(self, processed. The document is not added to the index. :param str environment_id: The ID of the environment. - :param str configuration: The configuration to use to process the document. If - this part is provided, then the provided configuration is used to process the - document. If the **configuration_id** is also provided (both are present at the - same time), then request is rejected. The maximum supported configuration size is - 1 MB. Configuration parts larger than 1 MB are rejected. - See the `GET /configurations/{configuration_id}` operation for an example - configuration. - :param file file: The content of the document to ingest. The maximum supported - file size when adding a file to a collection is 50 megabytes, the maximum - supported file size when testing a confiruration is 1 megabyte. Files larger than - the supported size are rejected. - :param str filename: The filename for file. - :param str file_content_type: The content type of file. - :param str metadata: The maximum supported metadata file size is 1 MB. Metadata - parts larger than 1 MB are rejected. - Example: ``` { - \"Creator\": \"Johnny Appleseed\", - \"Subject\": \"Apples\" - } ```. - :param str step: Specify to only run the input document through the given step - instead of running the input document through the entire ingestion workflow. Valid - values are `convert`, `enrich`, and `normalize`. - :param str configuration_id: The ID of the configuration to use to process the - document. If the **configuration** form part is also provided (both are present at - the same time), then the request will be rejected. + :param str configuration: (optional) The configuration to use to process + the document. If this part is provided, then the provided configuration is + used to process the document. If the **configuration_id** is also provided + (both are present at the same time), then request is rejected. The maximum + supported configuration size is 1 MB. Configuration parts larger than 1 MB + are rejected. See the `GET /configurations/{configuration_id}` operation + for an example configuration. + :param file file: (optional) The content of the document to ingest. The + maximum supported file size when adding a file to a collection is 50 + megabytes, the maximum supported file size when testing a confiruration is + 1 megabyte. Files larger than the supported size are rejected. + :param str filename: (optional) The filename for file. + :param str file_content_type: (optional) The content type of file. + :param str metadata: (optional) The maximum supported metadata file size is + 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { + "Creator": "Johnny Appleseed", + "Subject": "Apples" + } ```. + :param str step: (optional) Specify to only run the input document through + the given step instead of running the input document through the entire + ingestion workflow. Valid values are `convert`, `enrich`, and `normalize`. + :param str configuration_id: (optional) The ID of the configuration to use + to process the document. If the **configuration** form part is also + provided (both are present at the same time), then the request will be + rejected. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -723,13 +697,14 @@ def test_configuration_in_environment(self, url = '/v1/environments/{0}/preview'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response ######################### @@ -739,6 +714,7 @@ def test_configuration_in_environment(self, def create_collection(self, environment_id, name, + *, description=None, configuration_id=None, language=None, @@ -748,11 +724,11 @@ def create_collection(self, :param str environment_id: The ID of the environment. :param str name: The name of the collection to be created. - :param str description: A description of the collection. - :param str configuration_id: The ID of the configuration in which the collection - is to be created. - :param str language: The language of the documents stored in the collection, in - the form of an ISO 639-1 language code. + :param str description: (optional) A description of the collection. + :param str configuration_id: (optional) The ID of the configuration in + which the collection is to be created. + :param str language: (optional) The language of the documents stored in the + collection, in the form of an ISO 639-1 language code. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -780,23 +756,24 @@ def create_collection(self, url = '/v1/environments/{0}/collections'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response - def list_collections(self, environment_id, name=None, **kwargs): + def list_collections(self, environment_id, *, name=None, **kwargs): """ List collections. Lists existing collections for the service instance. :param str environment_id: The ID of the environment. - :param str name: Find collections with the given name. + :param str name: (optional) Find collections with the given name. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -815,12 +792,13 @@ def list_collections(self, environment_id, name=None, **kwargs): url = '/v1/environments/{0}/collections'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_collection(self, environment_id, collection_id, **kwargs): @@ -849,18 +827,20 @@ def get_collection(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_collection(self, environment_id, collection_id, name, + *, description=None, configuration_id=None, **kwargs): @@ -870,9 +850,9 @@ def update_collection(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str name: The name of the collection. - :param str description: A description of the collection. - :param str configuration_id: The ID of the configuration in which the collection - is to be updated. + :param str description: (optional) A description of the collection. + :param str configuration_id: (optional) The ID of the configuration in + which the collection is to be updated. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -899,13 +879,14 @@ def update_collection(self, url = '/v1/environments/{0}/collections/{1}'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='PUT', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_collection(self, environment_id, collection_id, **kwargs): @@ -934,12 +915,13 @@ def delete_collection(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def list_collection_fields(self, environment_id, collection_id, **kwargs): @@ -971,12 +953,13 @@ def list_collection_fields(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/fields'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -1012,12 +995,13 @@ def list_expansions(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/expansions'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_expansions(self, environment_id, collection_id, expansions, @@ -1026,24 +1010,24 @@ def create_expansions(self, environment_id, collection_id, expansions, Create or update expansion list. Create or replace the Expansion list for this collection. The maximum number of - expanded terms per collection is `500`. - The current expansion list is replaced with the uploaded content. + expanded terms per collection is `500`. The current expansion list is replaced + with the uploaded content. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param list[Expansion] expansions: An array of query expansion definitions. - Each object in the **expansions** array represents a term or set of terms that - will be expanded into other terms. Each expansion object can be configured as - bidirectional or unidirectional. Bidirectional means that all terms are expanded - to all other terms in the object. Unidirectional means that a set list of terms - can be expanded into a second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. When - found in a query, all items in the **expanded_terms** array are then expanded to - the other items in the same array. - To create a uni-directional expansion, specify both an array of **input_terms** - and an array of **expanded_terms**. When items in the **input_terms** array are - present in a query, they are expanded using the items listed in the - **expanded_terms** array. + Each object in the **expansions** array represents a term or set of terms + that will be expanded into other terms. Each expansion object can be + configured as bidirectional or unidirectional. Bidirectional means that all + terms are expanded to all other terms in the object. Unidirectional means + that a set list of terms can be expanded into a second list of terms. + To create a bi-directional expansion specify an **expanded_terms** array. + When found in a query, all items in the **expanded_terms** array are then + expanded to the other items in the same array. + To create a uni-directional expansion, specify both an array of + **input_terms** and an array of **expanded_terms**. When items in the + **input_terms** array are present in a query, they are expanded using the + items listed in the **expanded_terms** array. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1069,13 +1053,14 @@ def create_expansions(self, environment_id, collection_id, expansions, url = '/v1/environments/{0}/collections/{1}/expansions'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_expansions(self, environment_id, collection_id, **kwargs): @@ -1107,12 +1092,13 @@ def delete_expansions(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/expansions'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response def get_tokenization_dictionary_status(self, environment_id, collection_id, @@ -1146,17 +1132,19 @@ def get_tokenization_dictionary_status(self, environment_id, collection_id, url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_tokenization_dictionary(self, environment_id, collection_id, + *, tokenization_rules=None, **kwargs): """ @@ -1166,9 +1154,10 @@ def create_tokenization_dictionary(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param list[TokenDictRule] tokenization_rules: An array of tokenization rules. - Each rule contains, the original `text` string, component `tokens`, any alternate - character set `readings`, and which `part_of_speech` the text is from. + :param list[TokenDictRule] tokenization_rules: (optional) An array of + tokenization rules. Each rule contains, the original `text` string, + component `tokens`, any alternate character set `readings`, and which + `part_of_speech` the text is from. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1197,13 +1186,14 @@ def create_tokenization_dictionary(self, url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_tokenization_dictionary(self, environment_id, collection_id, @@ -1236,12 +1226,13 @@ def delete_tokenization_dictionary(self, environment_id, collection_id, url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response def get_stopword_list_status(self, environment_id, collection_id, **kwargs): @@ -1273,18 +1264,20 @@ def get_stopword_list_status(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_stopword_list(self, environment_id, collection_id, stopword_file, + *, stopword_filename=None, **kwargs): """ @@ -1295,7 +1288,7 @@ def create_stopword_list(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param file stopword_file: The content of the stopword list to ingest. - :param str stopword_filename: The filename for stopword_file. + :param str stopword_filename: (optional) The filename for stopword_file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1326,13 +1319,14 @@ def create_stopword_list(self, url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response def delete_stopword_list(self, environment_id, collection_id, **kwargs): @@ -1364,12 +1358,13 @@ def delete_stopword_list(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response ######################### @@ -1379,6 +1374,7 @@ def delete_stopword_list(self, environment_id, collection_id, **kwargs): def add_document(self, environment_id, collection_id, + *, file=None, filename=None, file_content_type=None, @@ -1410,18 +1406,17 @@ def add_document(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param file file: The content of the document to ingest. The maximum supported - file size when adding a file to a collection is 50 megabytes, the maximum - supported file size when testing a confiruration is 1 megabyte. Files larger than - the supported size are rejected. - :param str filename: The filename for file. - :param str file_content_type: The content type of file. - :param str metadata: The maximum supported metadata file size is 1 MB. Metadata - parts larger than 1 MB are rejected. - Example: ``` { - \"Creator\": \"Johnny Appleseed\", - \"Subject\": \"Apples\" - } ```. + :param file file: (optional) The content of the document to ingest. The + maximum supported file size when adding a file to a collection is 50 + megabytes, the maximum supported file size when testing a confiruration is + 1 megabyte. Files larger than the supported size are rejected. + :param str filename: (optional) The filename for file. + :param str file_content_type: (optional) The content type of file. + :param str metadata: (optional) The maximum supported metadata file size is + 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { + "Creator": "Johnny Appleseed", + "Subject": "Apples" + } ```. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1453,13 +1448,14 @@ def add_document(self, url = '/v1/environments/{0}/collections/{1}/documents'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response def get_document_status(self, environment_id, collection_id, document_id, @@ -1497,18 +1493,20 @@ def get_document_status(self, environment_id, collection_id, document_id, url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( *self._encode_path_vars(environment_id, collection_id, document_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_document(self, environment_id, collection_id, document_id, + *, file=None, filename=None, file_content_type=None, @@ -1525,18 +1523,17 @@ def update_document(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param file file: The content of the document to ingest. The maximum supported - file size when adding a file to a collection is 50 megabytes, the maximum - supported file size when testing a confiruration is 1 megabyte. Files larger than - the supported size are rejected. - :param str filename: The filename for file. - :param str file_content_type: The content type of file. - :param str metadata: The maximum supported metadata file size is 1 MB. Metadata - parts larger than 1 MB are rejected. - Example: ``` { - \"Creator\": \"Johnny Appleseed\", - \"Subject\": \"Apples\" - } ```. + :param file file: (optional) The content of the document to ingest. The + maximum supported file size when adding a file to a collection is 50 + megabytes, the maximum supported file size when testing a confiruration is + 1 megabyte. Files larger than the supported size are rejected. + :param str filename: (optional) The filename for file. + :param str file_content_type: (optional) The content type of file. + :param str metadata: (optional) The maximum supported metadata file size is + 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { + "Creator": "Johnny Appleseed", + "Subject": "Apples" + } ```. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1570,13 +1567,14 @@ def update_document(self, url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( *self._encode_path_vars(environment_id, collection_id, document_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response def delete_document(self, environment_id, collection_id, document_id, @@ -1613,12 +1611,13 @@ def delete_document(self, environment_id, collection_id, document_id, url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( *self._encode_path_vars(environment_id, collection_id, document_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -1628,13 +1627,14 @@ def delete_document(self, environment_id, collection_id, document_id, def query(self, environment_id, collection_id, + *, filter=None, query=None, natural_language_query=None, passages=None, aggregation=None, count=None, - return_fields=None, + return_=None, offset=None, sort=None, highlight=None, @@ -1648,7 +1648,7 @@ def query(self, similar_document_ids=None, similar_fields=None, bias=None, - logging_opt_out=None, + x_watson_logging_opt_out=None, **kwargs): """ Query a collection. @@ -1659,72 +1659,77 @@ def query(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param str filter: A cacheable query that excludes documents that don't mention - the query content. Filter searches are better for metadata-type searches and for - assessing the concepts in the data set. - :param str query: A query search returns all documents in your data set with full - enrichments and full text, but with the most relevant documents listed first. Use - a query search when you want to find the most relevant search results. - :param str natural_language_query: A natural language query that returns relevant - documents by utilizing training data and natural language understanding. - :param bool passages: A passages query that returns the most relevant passages - from the results. - :param str aggregation: An aggregation search that returns an exact answer by - combining query search with filters. Useful for applications to build lists, - tables, and time series. For a full list of possible aggregations, see the Query - reference. - :param int count: Number of results to return. - :param str return_fields: A comma-separated list of the portion of the document - hierarchy to return. - :param int offset: The number of query results to skip at the beginning. For - example, if the total number of results that are returned is 10 and the offset is - 8, it returns the last two results. - :param str sort: A comma-separated list of fields in the document to sort on. You - can optionally specify a sort direction by prefixing the field with `-` for - descending or `+` for ascending. Ascending is the default sort direction if no - prefix is specified. This parameter cannot be used in the same query as the - **bias** parameter. - :param bool highlight: When true, a highlight field is returned for each result - which contains the fields which match the query with `` tags around the - matching query terms. - :param str passages_fields: A comma-separated list of fields that passages are - drawn from. If this parameter not specified, then all top-level fields are - included. - :param int passages_count: The maximum number of passages to return. The search - returns fewer passages if the requested total is not found. The default is `10`. - The maximum is `100`. - :param int passages_characters: The approximate number of characters that any one - passage will have. - :param bool deduplicate: When `true`, and used with a Watson Discovery News - collection, duplicate results (based on the contents of the **title** field) are - removed. Duplicate comparison is limited to the current query only; **offset** is - not considered. This parameter is currently Beta functionality. - :param str deduplicate_field: When specified, duplicate results based on the field - specified are removed from the returned results. Duplicate comparison is limited - to the current query only, **offset** is not considered. This parameter is - currently Beta functionality. - :param str collection_ids: A comma-separated list of collection IDs to be queried - against. Required when querying multiple collections, invalid when performing a - single collection query. - :param bool similar: When `true`, results are returned based on their similarity - to the document IDs specified in the **similar.document_ids** parameter. - :param str similar_document_ids: A comma-separated list of document IDs to find - similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the scope of - the document similarity search with the natural language query. Other query - parameters, such as **filter** and **query**, are subsequently applied and reduce - the scope. - :param str similar_fields: A comma-separated list of field names that are used as - a basis for comparison to identify similar documents. If not specified, the entire - document is used for comparison. - :param str bias: Field which the returned results will be biased against. The - specified field must be either a **date** or **number** format. When a **date** - type field is specified returned results are biased towards field values closer to - the current date. When a **number** type field is specified, returned results are - biased towards higher field values. This parameter cannot be used in the same - query as the **sort** parameter. - :param bool logging_opt_out: If `true`, queries are not stored in the Discovery - **Logs** endpoint. + :param str filter: (optional) A cacheable query that excludes documents + that don't mention the query content. Filter searches are better for + metadata-type searches and for assessing the concepts in the data set. + :param str query: (optional) A query search returns all documents in your + data set with full enrichments and full text, but with the most relevant + documents listed first. Use a query search when you want to find the most + relevant search results. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by utilizing training data and natural language + understanding. + :param bool passages: (optional) A passages query that returns the most + relevant passages from the results. + :param str aggregation: (optional) An aggregation search that returns an + exact answer by combining query search with filters. Useful for + applications to build lists, tables, and time series. For a full list of + possible aggregations, see the Query reference. + :param int count: (optional) Number of results to return. + :param str return_: (optional) A comma-separated list of the portion of the + document hierarchy to return. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. + :param str sort: (optional) A comma-separated list of fields in the + document to sort on. You can optionally specify a sort direction by + prefixing the field with `-` for descending or `+` for ascending. Ascending + is the default sort direction if no prefix is specified. This parameter + cannot be used in the same query as the **bias** parameter. + :param bool highlight: (optional) When true, a highlight field is returned + for each result which contains the fields which match the query with + `` tags around the matching query terms. + :param str passages_fields: (optional) A comma-separated list of fields + that passages are drawn from. If this parameter not specified, then all + top-level fields are included. + :param int passages_count: (optional) The maximum number of passages to + return. The search returns fewer passages if the requested total is not + found. The default is `10`. The maximum is `100`. + :param int passages_characters: (optional) The approximate number of + characters that any one passage will have. + :param bool deduplicate: (optional) When `true`, and used with a Watson + Discovery News collection, duplicate results (based on the contents of the + **title** field) are removed. Duplicate comparison is limited to the + current query only; **offset** is not considered. This parameter is + currently Beta functionality. + :param str deduplicate_field: (optional) When specified, duplicate results + based on the field specified are removed from the returned results. + Duplicate comparison is limited to the current query only, **offset** is + not considered. This parameter is currently Beta functionality. + :param str collection_ids: (optional) A comma-separated list of collection + IDs to be queried against. Required when querying multiple collections, + invalid when performing a single collection query. + :param bool similar: (optional) When `true`, results are returned based on + their similarity to the document IDs specified in the + **similar.document_ids** parameter. + :param str similar_document_ids: (optional) A comma-separated list of + document IDs to find similar documents. + **Tip:** Include the **natural_language_query** parameter to expand the + scope of the document similarity search with the natural language query. + Other query parameters, such as **filter** and **query**, are subsequently + applied and reduce the scope. + :param str similar_fields: (optional) A comma-separated list of field names + that are used as a basis for comparison to identify similar documents. If + not specified, the entire document is used for comparison. + :param str bias: (optional) Field which the returned results will be biased + against. The specified field must be either a **date** or **number** + format. When a **date** type field is specified returned results are biased + towards field values closer to the current date. When a **number** type + field is specified, returned results are biased towards higher field + values. This parameter cannot be used in the same query as the **sort** + parameter. + :param bool x_watson_logging_opt_out: (optional) If `true`, queries are not + stored in the Discovery **Logs** endpoint. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1735,7 +1740,7 @@ def query(self, if collection_id is None: raise ValueError('collection_id must be provided') - headers = {'X-Watson-Logging-Opt-Out': logging_opt_out} + headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} if 'headers' in kwargs: headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers('discovery', 'V1', 'query') @@ -1750,7 +1755,7 @@ def query(self, 'passages': passages, 'aggregation': aggregation, 'count': count, - 'return': return_fields, + 'return': return_, 'offset': offset, 'sort': sort, 'highlight': highlight, @@ -1768,25 +1773,27 @@ def query(self, url = '/v1/environments/{0}/collections/{1}/query'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def query_notices(self, environment_id, collection_id, + *, filter=None, query=None, natural_language_query=None, passages=None, aggregation=None, count=None, - return_fields=None, + return_=None, offset=None, sort=None, highlight=None, @@ -1809,56 +1816,60 @@ def query_notices(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param str filter: A cacheable query that excludes documents that don't mention - the query content. Filter searches are better for metadata-type searches and for - assessing the concepts in the data set. - :param str query: A query search returns all documents in your data set with full - enrichments and full text, but with the most relevant documents listed first. - :param str natural_language_query: A natural language query that returns relevant - documents by utilizing training data and natural language understanding. - :param bool passages: A passages query that returns the most relevant passages - from the results. - :param str aggregation: An aggregation search that returns an exact answer by - combining query search with filters. Useful for applications to build lists, - tables, and time series. For a full list of possible aggregations, see the Query - reference. - :param int count: Number of results to return. The maximum for the **count** and - **offset** values together in any one query is **10000**. - :param list[str] return_fields: A comma-separated list of the portion of the - document hierarchy to return. - :param int offset: The number of query results to skip at the beginning. For - example, if the total number of results that are returned is 10 and the offset is - 8, it returns the last two results. The maximum for the **count** and **offset** - values together in any one query is **10000**. - :param list[str] sort: A comma-separated list of fields in the document to sort - on. You can optionally specify a sort direction by prefixing the field with `-` - for descending or `+` for ascending. Ascending is the default sort direction if no - prefix is specified. - :param bool highlight: When true, a highlight field is returned for each result - which contains the fields which match the query with `` tags around the - matching query terms. - :param list[str] passages_fields: A comma-separated list of fields that passages - are drawn from. If this parameter not specified, then all top-level fields are - included. - :param int passages_count: The maximum number of passages to return. The search - returns fewer passages if the requested total is not found. - :param int passages_characters: The approximate number of characters that any one - passage will have. - :param str deduplicate_field: When specified, duplicate results based on the field - specified are removed from the returned results. Duplicate comparison is limited - to the current query only, **offset** is not considered. This parameter is - currently Beta functionality. - :param bool similar: When `true`, results are returned based on their similarity - to the document IDs specified in the **similar.document_ids** parameter. - :param list[str] similar_document_ids: A comma-separated list of document IDs to - find similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the scope of - the document similarity search with the natural language query. Other query - parameters, such as **filter** and **query**, are subsequently applied and reduce - the scope. - :param list[str] similar_fields: A comma-separated list of field names that are - used as a basis for comparison to identify similar documents. If not specified, - the entire document is used for comparison. + :param str filter: (optional) A cacheable query that excludes documents + that don't mention the query content. Filter searches are better for + metadata-type searches and for assessing the concepts in the data set. + :param str query: (optional) A query search returns all documents in your + data set with full enrichments and full text, but with the most relevant + documents listed first. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by utilizing training data and natural language + understanding. + :param bool passages: (optional) A passages query that returns the most + relevant passages from the results. + :param str aggregation: (optional) An aggregation search that returns an + exact answer by combining query search with filters. Useful for + applications to build lists, tables, and time series. For a full list of + possible aggregations, see the Query reference. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is **10000**. + :param list[str] return_: (optional) A comma-separated list of the portion + of the document hierarchy to return. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. The maximum for + the **count** and **offset** values together in any one query is **10000**. + :param list[str] sort: (optional) A comma-separated list of fields in the + document to sort on. You can optionally specify a sort direction by + prefixing the field with `-` for descending or `+` for ascending. Ascending + is the default sort direction if no prefix is specified. + :param bool highlight: (optional) When true, a highlight field is returned + for each result which contains the fields which match the query with + `` tags around the matching query terms. + :param list[str] passages_fields: (optional) A comma-separated list of + fields that passages are drawn from. If this parameter not specified, then + all top-level fields are included. + :param int passages_count: (optional) The maximum number of passages to + return. The search returns fewer passages if the requested total is not + found. + :param int passages_characters: (optional) The approximate number of + characters that any one passage will have. + :param str deduplicate_field: (optional) When specified, duplicate results + based on the field specified are removed from the returned results. + Duplicate comparison is limited to the current query only, **offset** is + not considered. This parameter is currently Beta functionality. + :param bool similar: (optional) When `true`, results are returned based on + their similarity to the document IDs specified in the + **similar.document_ids** parameter. + :param list[str] similar_document_ids: (optional) A comma-separated list of + document IDs to find similar documents. + **Tip:** Include the **natural_language_query** parameter to expand the + scope of the document similarity search with the natural language query. + Other query parameters, such as **filter** and **query**, are subsequently + applied and reduce the scope. + :param list[str] similar_fields: (optional) A comma-separated list of field + names that are used as a basis for comparison to identify similar + documents. If not specified, the entire document is used for comparison. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1883,7 +1894,7 @@ def query_notices(self, 'passages': passages, 'aggregation': aggregation, 'count': count, - 'return': self._convert_list(return_fields), + 'return': self._convert_list(return_), 'offset': offset, 'sort': self._convert_list(sort), 'highlight': highlight, @@ -1898,23 +1909,25 @@ def query_notices(self, url = '/v1/environments/{0}/collections/{1}/notices'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def federated_query(self, environment_id, + *, filter=None, query=None, natural_language_query=None, passages=None, aggregation=None, count=None, - return_fields=None, + return_=None, offset=None, sort=None, highlight=None, @@ -1928,7 +1941,7 @@ def federated_query(self, similar_document_ids=None, similar_fields=None, bias=None, - logging_opt_out=None, + x_watson_logging_opt_out=None, **kwargs): """ Query multiple collections. @@ -1938,72 +1951,77 @@ def federated_query(self, documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-query-concepts#query-concepts). :param str environment_id: The ID of the environment. - :param str filter: A cacheable query that excludes documents that don't mention - the query content. Filter searches are better for metadata-type searches and for - assessing the concepts in the data set. - :param str query: A query search returns all documents in your data set with full - enrichments and full text, but with the most relevant documents listed first. Use - a query search when you want to find the most relevant search results. - :param str natural_language_query: A natural language query that returns relevant - documents by utilizing training data and natural language understanding. - :param bool passages: A passages query that returns the most relevant passages - from the results. - :param str aggregation: An aggregation search that returns an exact answer by - combining query search with filters. Useful for applications to build lists, - tables, and time series. For a full list of possible aggregations, see the Query - reference. - :param int count: Number of results to return. - :param str return_fields: A comma-separated list of the portion of the document - hierarchy to return. - :param int offset: The number of query results to skip at the beginning. For - example, if the total number of results that are returned is 10 and the offset is - 8, it returns the last two results. - :param str sort: A comma-separated list of fields in the document to sort on. You - can optionally specify a sort direction by prefixing the field with `-` for - descending or `+` for ascending. Ascending is the default sort direction if no - prefix is specified. This parameter cannot be used in the same query as the - **bias** parameter. - :param bool highlight: When true, a highlight field is returned for each result - which contains the fields which match the query with `` tags around the - matching query terms. - :param str passages_fields: A comma-separated list of fields that passages are - drawn from. If this parameter not specified, then all top-level fields are - included. - :param int passages_count: The maximum number of passages to return. The search - returns fewer passages if the requested total is not found. The default is `10`. - The maximum is `100`. - :param int passages_characters: The approximate number of characters that any one - passage will have. - :param bool deduplicate: When `true`, and used with a Watson Discovery News - collection, duplicate results (based on the contents of the **title** field) are - removed. Duplicate comparison is limited to the current query only; **offset** is - not considered. This parameter is currently Beta functionality. - :param str deduplicate_field: When specified, duplicate results based on the field - specified are removed from the returned results. Duplicate comparison is limited - to the current query only, **offset** is not considered. This parameter is - currently Beta functionality. - :param str collection_ids: A comma-separated list of collection IDs to be queried - against. Required when querying multiple collections, invalid when performing a - single collection query. - :param bool similar: When `true`, results are returned based on their similarity - to the document IDs specified in the **similar.document_ids** parameter. - :param str similar_document_ids: A comma-separated list of document IDs to find - similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the scope of - the document similarity search with the natural language query. Other query - parameters, such as **filter** and **query**, are subsequently applied and reduce - the scope. - :param str similar_fields: A comma-separated list of field names that are used as - a basis for comparison to identify similar documents. If not specified, the entire - document is used for comparison. - :param str bias: Field which the returned results will be biased against. The - specified field must be either a **date** or **number** format. When a **date** - type field is specified returned results are biased towards field values closer to - the current date. When a **number** type field is specified, returned results are - biased towards higher field values. This parameter cannot be used in the same - query as the **sort** parameter. - :param bool logging_opt_out: If `true`, queries are not stored in the Discovery - **Logs** endpoint. + :param str filter: (optional) A cacheable query that excludes documents + that don't mention the query content. Filter searches are better for + metadata-type searches and for assessing the concepts in the data set. + :param str query: (optional) A query search returns all documents in your + data set with full enrichments and full text, but with the most relevant + documents listed first. Use a query search when you want to find the most + relevant search results. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by utilizing training data and natural language + understanding. + :param bool passages: (optional) A passages query that returns the most + relevant passages from the results. + :param str aggregation: (optional) An aggregation search that returns an + exact answer by combining query search with filters. Useful for + applications to build lists, tables, and time series. For a full list of + possible aggregations, see the Query reference. + :param int count: (optional) Number of results to return. + :param str return_: (optional) A comma-separated list of the portion of the + document hierarchy to return. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. + :param str sort: (optional) A comma-separated list of fields in the + document to sort on. You can optionally specify a sort direction by + prefixing the field with `-` for descending or `+` for ascending. Ascending + is the default sort direction if no prefix is specified. This parameter + cannot be used in the same query as the **bias** parameter. + :param bool highlight: (optional) When true, a highlight field is returned + for each result which contains the fields which match the query with + `` tags around the matching query terms. + :param str passages_fields: (optional) A comma-separated list of fields + that passages are drawn from. If this parameter not specified, then all + top-level fields are included. + :param int passages_count: (optional) The maximum number of passages to + return. The search returns fewer passages if the requested total is not + found. The default is `10`. The maximum is `100`. + :param int passages_characters: (optional) The approximate number of + characters that any one passage will have. + :param bool deduplicate: (optional) When `true`, and used with a Watson + Discovery News collection, duplicate results (based on the contents of the + **title** field) are removed. Duplicate comparison is limited to the + current query only; **offset** is not considered. This parameter is + currently Beta functionality. + :param str deduplicate_field: (optional) When specified, duplicate results + based on the field specified are removed from the returned results. + Duplicate comparison is limited to the current query only, **offset** is + not considered. This parameter is currently Beta functionality. + :param str collection_ids: (optional) A comma-separated list of collection + IDs to be queried against. Required when querying multiple collections, + invalid when performing a single collection query. + :param bool similar: (optional) When `true`, results are returned based on + their similarity to the document IDs specified in the + **similar.document_ids** parameter. + :param str similar_document_ids: (optional) A comma-separated list of + document IDs to find similar documents. + **Tip:** Include the **natural_language_query** parameter to expand the + scope of the document similarity search with the natural language query. + Other query parameters, such as **filter** and **query**, are subsequently + applied and reduce the scope. + :param str similar_fields: (optional) A comma-separated list of field names + that are used as a basis for comparison to identify similar documents. If + not specified, the entire document is used for comparison. + :param str bias: (optional) Field which the returned results will be biased + against. The specified field must be either a **date** or **number** + format. When a **date** type field is specified returned results are biased + towards field values closer to the current date. When a **number** type + field is specified, returned results are biased towards higher field + values. This parameter cannot be used in the same query as the **sort** + parameter. + :param bool x_watson_logging_opt_out: (optional) If `true`, queries are not + stored in the Discovery **Logs** endpoint. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2012,7 +2030,7 @@ def federated_query(self, if environment_id is None: raise ValueError('environment_id must be provided') - headers = {'X-Watson-Logging-Opt-Out': logging_opt_out} + headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} if 'headers' in kwargs: headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers('discovery', 'V1', 'federated_query') @@ -2027,7 +2045,7 @@ def federated_query(self, 'passages': passages, 'aggregation': aggregation, 'count': count, - 'return': return_fields, + 'return': return_, 'offset': offset, 'sort': sort, 'highlight': highlight, @@ -2045,24 +2063,26 @@ def federated_query(self, url = '/v1/environments/{0}/query'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def federated_query_notices(self, environment_id, collection_ids, + *, filter=None, query=None, natural_language_query=None, aggregation=None, count=None, - return_fields=None, + return_=None, offset=None, sort=None, highlight=None, @@ -2081,49 +2101,52 @@ def federated_query_notices(self, for more details on the query language. :param str environment_id: The ID of the environment. - :param list[str] collection_ids: A comma-separated list of collection IDs to be - queried against. - :param str filter: A cacheable query that excludes documents that don't mention - the query content. Filter searches are better for metadata-type searches and for - assessing the concepts in the data set. - :param str query: A query search returns all documents in your data set with full - enrichments and full text, but with the most relevant documents listed first. - :param str natural_language_query: A natural language query that returns relevant - documents by utilizing training data and natural language understanding. - :param str aggregation: An aggregation search that returns an exact answer by - combining query search with filters. Useful for applications to build lists, - tables, and time series. For a full list of possible aggregations, see the Query - reference. - :param int count: Number of results to return. The maximum for the **count** and - **offset** values together in any one query is **10000**. - :param list[str] return_fields: A comma-separated list of the portion of the - document hierarchy to return. - :param int offset: The number of query results to skip at the beginning. For - example, if the total number of results that are returned is 10 and the offset is - 8, it returns the last two results. The maximum for the **count** and **offset** - values together in any one query is **10000**. - :param list[str] sort: A comma-separated list of fields in the document to sort - on. You can optionally specify a sort direction by prefixing the field with `-` - for descending or `+` for ascending. Ascending is the default sort direction if no - prefix is specified. - :param bool highlight: When true, a highlight field is returned for each result - which contains the fields which match the query with `` tags around the - matching query terms. - :param str deduplicate_field: When specified, duplicate results based on the field - specified are removed from the returned results. Duplicate comparison is limited - to the current query only, **offset** is not considered. This parameter is - currently Beta functionality. - :param bool similar: When `true`, results are returned based on their similarity - to the document IDs specified in the **similar.document_ids** parameter. - :param list[str] similar_document_ids: A comma-separated list of document IDs to - find similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the scope of - the document similarity search with the natural language query. Other query - parameters, such as **filter** and **query**, are subsequently applied and reduce - the scope. - :param list[str] similar_fields: A comma-separated list of field names that are - used as a basis for comparison to identify similar documents. If not specified, - the entire document is used for comparison. + :param list[str] collection_ids: A comma-separated list of collection IDs + to be queried against. + :param str filter: (optional) A cacheable query that excludes documents + that don't mention the query content. Filter searches are better for + metadata-type searches and for assessing the concepts in the data set. + :param str query: (optional) A query search returns all documents in your + data set with full enrichments and full text, but with the most relevant + documents listed first. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by utilizing training data and natural language + understanding. + :param str aggregation: (optional) An aggregation search that returns an + exact answer by combining query search with filters. Useful for + applications to build lists, tables, and time series. For a full list of + possible aggregations, see the Query reference. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is **10000**. + :param list[str] return_: (optional) A comma-separated list of the portion + of the document hierarchy to return. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. The maximum for + the **count** and **offset** values together in any one query is **10000**. + :param list[str] sort: (optional) A comma-separated list of fields in the + document to sort on. You can optionally specify a sort direction by + prefixing the field with `-` for descending or `+` for ascending. Ascending + is the default sort direction if no prefix is specified. + :param bool highlight: (optional) When true, a highlight field is returned + for each result which contains the fields which match the query with + `` tags around the matching query terms. + :param str deduplicate_field: (optional) When specified, duplicate results + based on the field specified are removed from the returned results. + Duplicate comparison is limited to the current query only, **offset** is + not considered. This parameter is currently Beta functionality. + :param bool similar: (optional) When `true`, results are returned based on + their similarity to the document IDs specified in the + **similar.document_ids** parameter. + :param list[str] similar_document_ids: (optional) A comma-separated list of + document IDs to find similar documents. + **Tip:** Include the **natural_language_query** parameter to expand the + scope of the document similarity search with the natural language query. + Other query parameters, such as **filter** and **query**, are subsequently + applied and reduce the scope. + :param list[str] similar_fields: (optional) A comma-separated list of field + names that are used as a basis for comparison to identify similar + documents. If not specified, the entire document is used for comparison. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2149,7 +2172,7 @@ def federated_query_notices(self, 'natural_language_query': natural_language_query, 'aggregation': aggregation, 'count': count, - 'return': self._convert_list(return_fields), + 'return': self._convert_list(return_), 'offset': offset, 'sort': self._convert_list(sort), 'highlight': highlight, @@ -2161,17 +2184,19 @@ def federated_query_notices(self, url = '/v1/environments/{0}/notices'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def query_entities(self, environment_id, collection_id, + *, feature=None, entity=None, context=None, @@ -2187,18 +2212,19 @@ def query_entities(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param str feature: The entity query feature to perform. Supported features are - `disambiguate` and `similar_entities`. - :param QueryEntitiesEntity entity: A text string that appears within the entity - text field. - :param QueryEntitiesContext context: Entity text to provide context for the - queried entity and rank based on that association. For example, if you wanted to - query the city of London in England your query would look for `London` with the - context of `England`. - :param int count: The number of results to return. The default is `10`. The - maximum is `1000`. - :param int evidence_count: The number of evidence items to return for each result. - The default is `0`. The maximum number of evidence items per query is 10,000. + :param str feature: (optional) The entity query feature to perform. + Supported features are `disambiguate` and `similar_entities`. + :param QueryEntitiesEntity entity: (optional) A text string that appears + within the entity text field. + :param QueryEntitiesContext context: (optional) Entity text to provide + context for the queried entity and rank based on that association. For + example, if you wanted to query the city of London in England your query + would look for `London` with the context of `England`. + :param int count: (optional) The number of results to return. The default + is `10`. The maximum is `1000`. + :param int evidence_count: (optional) The number of evidence items to + return for each result. The default is `0`. The maximum number of evidence + items per query is 10,000. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2231,18 +2257,20 @@ def query_entities(self, url = '/v1/environments/{0}/collections/{1}/query_entities'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def query_relations(self, environment_id, collection_id, + *, entities=None, context=None, sort=None, @@ -2259,21 +2287,22 @@ def query_relations(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param list[QueryRelationsEntity] entities: An array of entities to find - relationships for. - :param QueryEntitiesContext context: Entity text to provide context for the - queried entity and rank based on that association. For example, if you wanted to - query the city of London in England your query would look for `London` with the - context of `England`. - :param str sort: The sorting method for the relationships, can be `score` or - `frequency`. `frequency` is the number of unique times each entity is identified. - The default is `score`. This parameter cannot be used in the same query as the - **bias** parameter. - :param QueryRelationsFilter filter: - :param int count: The number of results to return. The default is `10`. The - maximum is `1000`. - :param int evidence_count: The number of evidence items to return for each result. - The default is `0`. The maximum number of evidence items per query is 10,000. + :param list[QueryRelationsEntity] entities: (optional) An array of entities + to find relationships for. + :param QueryEntitiesContext context: (optional) Entity text to provide + context for the queried entity and rank based on that association. For + example, if you wanted to query the city of London in England your query + would look for `London` with the context of `England`. + :param str sort: (optional) The sorting method for the relationships, can + be `score` or `frequency`. `frequency` is the number of unique times each + entity is identified. The default is `score`. This parameter cannot be used + in the same query as the **bias** parameter. + :param QueryRelationsFilter filter: (optional) + :param int count: (optional) The number of results to return. The default + is `10`. The maximum is `1000`. + :param int evidence_count: (optional) The number of evidence items to + return for each result. The default is `0`. The maximum number of evidence + items per query is 10,000. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2311,13 +2340,14 @@ def query_relations(self, url = '/v1/environments/{0}/collections/{1}/query_relations'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response ######################### @@ -2352,17 +2382,19 @@ def list_training_data(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/training_data'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def add_training_data(self, environment_id, collection_id, + *, natural_language_query=None, filter=None, examples=None, @@ -2375,11 +2407,12 @@ def add_training_data(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param str natural_language_query: The natural text query for the new training - query. - :param str filter: The filter used on the collection before the - **natural_language_query** is applied. - :param list[TrainingExample] examples: Array of training examples. + :param str natural_language_query: (optional) The natural text query for + the new training query. + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. + :param list[TrainingExample] examples: (optional) Array of training + examples. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2410,13 +2443,14 @@ def add_training_data(self, url = '/v1/environments/{0}/collections/{1}/training_data'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_all_training_data(self, environment_id, collection_id, **kwargs): @@ -2448,12 +2482,13 @@ def delete_all_training_data(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/training_data'.format( *self._encode_path_vars(environment_id, collection_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response def get_training_data(self, environment_id, collection_id, query_id, @@ -2489,12 +2524,13 @@ def get_training_data(self, environment_id, collection_id, query_id, url = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def delete_training_data(self, environment_id, collection_id, query_id, @@ -2530,12 +2566,13 @@ def delete_training_data(self, environment_id, collection_id, query_id, url = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response def list_training_examples(self, environment_id, collection_id, query_id, @@ -2571,18 +2608,20 @@ def list_training_examples(self, environment_id, collection_id, query_id, url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_training_example(self, environment_id, collection_id, query_id, + *, document_id=None, cross_reference=None, relevance=None, @@ -2595,10 +2634,11 @@ def create_training_example(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str query_id: The ID of the query used for training. - :param str document_id: The document ID associated with this training example. - :param str cross_reference: The cross reference associated with this training - example. - :param int relevance: The relevance of the training example. + :param str document_id: (optional) The document ID associated with this + training example. + :param str cross_reference: (optional) The cross reference associated with + this training example. + :param int relevance: (optional) The relevance of the training example. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2628,13 +2668,14 @@ def create_training_example(self, url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_training_example(self, environment_id, collection_id, query_id, @@ -2674,12 +2715,13 @@ def delete_training_example(self, environment_id, collection_id, query_id, url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( *self._encode_path_vars(environment_id, collection_id, query_id, example_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response def update_training_example(self, @@ -2687,6 +2729,7 @@ def update_training_example(self, collection_id, query_id, example_id, + *, cross_reference=None, relevance=None, **kwargs): @@ -2699,8 +2742,8 @@ def update_training_example(self, :param str collection_id: The ID of the collection. :param str query_id: The ID of the query used for training. :param str example_id: The ID of the document as it is indexed. - :param str cross_reference: The example to add. - :param int relevance: The relevance value for this example. + :param str cross_reference: (optional) The example to add. + :param int relevance: (optional) The relevance value for this example. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2729,13 +2772,14 @@ def update_training_example(self, url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( *self._encode_path_vars(environment_id, collection_id, query_id, example_id)) - response = self.request( + request = self.prepare_request( method='PUT', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_training_example(self, environment_id, collection_id, query_id, @@ -2774,12 +2818,13 @@ def get_training_example(self, environment_id, collection_id, query_id, url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( *self._encode_path_vars(environment_id, collection_id, query_id, example_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -2797,7 +2842,8 @@ def delete_user_data(self, customer_id, **kwargs): customer IDs, see [Information security](https://cloud.ibm.com/docs/services/discovery?topic=discovery-information-security#information-security). - :param str customer_id: The customer ID for which all data is to be deleted. + :param str customer_id: The customer ID for which all data is to be + deleted. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2815,12 +2861,13 @@ def delete_user_data(self, customer_id, **kwargs): params = {'version': self.version, 'customer_id': customer_id} url = '/v1/user_data' - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response ######################### @@ -2833,7 +2880,7 @@ def create_event(self, type, data, **kwargs): The **Events** API can be used to create log entries that are associated with specific queries. For example, you can record which documents in the results set - were \"clicked\" by a user and when that click occured. + were "clicked" by a user and when that click occured. :param str type: The event type to be created. :param EventData data: Query event data object. @@ -2859,16 +2906,18 @@ def create_event(self, type, data, **kwargs): data = {'type': type, 'data': data} url = '/v1/events' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def query_log(self, + *, filter=None, query=None, count=None, @@ -2882,21 +2931,22 @@ def query_log(self, criteria. Searching the **logs** endpoint uses the standard Discovery query syntax for the parameters that are supported. - :param str filter: A cacheable query that excludes documents that don't mention - the query content. Filter searches are better for metadata-type searches and for - assessing the concepts in the data set. - :param str query: A query search returns all documents in your data set with full - enrichments and full text, but with the most relevant documents listed first. - :param int count: Number of results to return. The maximum for the **count** and - **offset** values together in any one query is **10000**. - :param int offset: The number of query results to skip at the beginning. For - example, if the total number of results that are returned is 10 and the offset is - 8, it returns the last two results. The maximum for the **count** and **offset** - values together in any one query is **10000**. - :param list[str] sort: A comma-separated list of fields in the document to sort - on. You can optionally specify a sort direction by prefixing the field with `-` - for descending or `+` for ascending. Ascending is the default sort direction if no - prefix is specified. + :param str filter: (optional) A cacheable query that excludes documents + that don't mention the query content. Filter searches are better for + metadata-type searches and for assessing the concepts in the data set. + :param str query: (optional) A query search returns all documents in your + data set with full enrichments and full text, but with the most relevant + documents listed first. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is **10000**. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. The maximum for + the **count** and **offset** values together in any one query is **10000**. + :param list[str] sort: (optional) A comma-separated list of fields in the + document to sort on. You can optionally specify a sort direction by + prefixing the field with `-` for descending or `+` for ascending. Ascending + is the default sort direction if no prefix is specified. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2918,15 +2968,17 @@ def query_log(self, } url = '/v1/logs' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_metrics_query(self, + *, start_time=None, end_time=None, result_type=None, @@ -2937,12 +2989,12 @@ def get_metrics_query(self, Total number of queries using the **natural_language_query** parameter over a specific time window. - :param datetime start_time: Metric is computed from data recorded after this - timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: Metric is computed from data recorded before this - timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: The type of result to consider when calculating the - metric. + :param datetime start_time: (optional) Metric is computed from data + recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. + :param datetime end_time: (optional) Metric is computed from data recorded + before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. + :param str result_type: (optional) The type of result to consider when + calculating the metric. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2962,15 +3014,17 @@ def get_metrics_query(self, } url = '/v1/metrics/number_of_queries' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_metrics_query_event(self, + *, start_time=None, end_time=None, result_type=None, @@ -2979,15 +3033,15 @@ def get_metrics_query_event(self, Number of queries with an event over time. Total number of queries using the **natural_language_query** parameter that have a - corresponding \"click\" event over a specified time window. This metric requires + corresponding "click" event over a specified time window. This metric requires having integrated event tracking in your application using the **Events** API. - :param datetime start_time: Metric is computed from data recorded after this - timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: Metric is computed from data recorded before this - timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: The type of result to consider when calculating the - metric. + :param datetime start_time: (optional) Metric is computed from data + recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. + :param datetime end_time: (optional) Metric is computed from data recorded + before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. + :param str result_type: (optional) The type of result to consider when + calculating the metric. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3008,15 +3062,17 @@ def get_metrics_query_event(self, } url = '/v1/metrics/number_of_queries_with_event' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_metrics_query_no_results(self, + *, start_time=None, end_time=None, result_type=None, @@ -3027,12 +3083,12 @@ def get_metrics_query_no_results(self, Total number of queries using the **natural_language_query** parameter that have no results returned over a specified time window. - :param datetime start_time: Metric is computed from data recorded after this - timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: Metric is computed from data recorded before this - timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: The type of result to consider when calculating the - metric. + :param datetime start_time: (optional) Metric is computed from data + recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. + :param datetime end_time: (optional) Metric is computed from data recorded + before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. + :param str result_type: (optional) The type of result to consider when + calculating the metric. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3053,15 +3109,17 @@ def get_metrics_query_no_results(self, } url = '/v1/metrics/number_of_queries_with_no_search_results' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_metrics_event_rate(self, + *, start_time=None, end_time=None, result_type=None, @@ -3070,16 +3128,15 @@ def get_metrics_event_rate(self, Percentage of queries with an associated event. The percentage of queries using the **natural_language_query** parameter that have - a corresponding \"click\" event over a specified time window. This metric - requires having integrated event tracking in your application using the **Events** - API. - - :param datetime start_time: Metric is computed from data recorded after this - timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: Metric is computed from data recorded before this - timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: The type of result to consider when calculating the - metric. + a corresponding "click" event over a specified time window. This metric requires + having integrated event tracking in your application using the **Events** API. + + :param datetime start_time: (optional) Metric is computed from data + recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. + :param datetime end_time: (optional) Metric is computed from data recorded + before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. + :param str result_type: (optional) The type of result to consider when + calculating the metric. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3100,25 +3157,26 @@ def get_metrics_event_rate(self, } url = '/v1/metrics/event_rate' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response - def get_metrics_query_token_event(self, count=None, **kwargs): + def get_metrics_query_token_event(self, *, count=None, **kwargs): """ Most frequent query tokens with an event. The most frequent query tokens parsed from the **natural_language_query** - parameter and their corresponding \"click\" event rate within the recording period + parameter and their corresponding "click" event rate within the recording period (queries and events are stored for 30 days). A query token is an individual word or unigram within the query string. - :param int count: Number of results to return. The maximum for the **count** and - **offset** values together in any one query is **10000**. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is **10000**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3134,12 +3192,13 @@ def get_metrics_query_token_event(self, count=None, **kwargs): params = {'version': self.version, 'count': count} url = '/v1/metrics/top_query_tokens_with_event_rate' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -3173,16 +3232,18 @@ def list_credentials(self, environment_id, **kwargs): url = '/v1/environments/{0}/credentials'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_credentials(self, environment_id, + *, source_type=None, credential_details=None, status=None, @@ -3196,23 +3257,25 @@ def create_credentials(self, rest. :param str environment_id: The ID of the environment. - :param str source_type: The source that this credentials object connects to. - - `box` indicates the credentials are used to connect an instance of Enterprise - Box. - - `salesforce` indicates the credentials are used to connect to Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to an IBM - Cloud Object Store. - :param CredentialDetails credential_details: Object containing details of the - stored credentials. - Obtain credentials for your source from the administrator of the source. - :param str status: The current status of this set of credentials. `connected` - indicates that the credentials are available to use with the source configuration - of a collection. `invalid` refers to the credentials (for example, the password - provided has expired) and must be corrected before they can be used with a - collection. + :param str source_type: (optional) The source that this credentials object + connects to. + - `box` indicates the credentials are used to connect an instance of + Enterprise Box. + - `salesforce` indicates the credentials are used to connect to + Salesforce. + - `sharepoint` indicates the credentials are used to connect to Microsoft + SharePoint Online. + - `web_crawl` indicates the credentials are used to perform a web crawl. + = `cloud_object_storage` indicates the credentials are used to connect to + an IBM Cloud Object Store. + :param CredentialDetails credential_details: (optional) Object containing + details of the stored credentials. + Obtain credentials for your source from the administrator of the source. + :param str status: (optional) The current status of this set of + credentials. `connected` indicates that the credentials are available to + use with the source configuration of a collection. `invalid` refers to the + credentials (for example, the password provided has expired) and must be + corrected before they can be used with a collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3240,13 +3303,14 @@ def create_credentials(self, url = '/v1/environments/{0}/credentials'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_credentials(self, environment_id, credential_id, **kwargs): @@ -3258,7 +3322,8 @@ def get_credentials(self, environment_id, credential_id, **kwargs): returned and must be obtained from the source system. :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source credentials. + :param str credential_id: The unique identifier for a set of source + credentials. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3279,17 +3344,19 @@ def get_credentials(self, environment_id, credential_id, **kwargs): url = '/v1/environments/{0}/credentials/{1}'.format( *self._encode_path_vars(environment_id, credential_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_credentials(self, environment_id, credential_id, + *, source_type=None, credential_details=None, status=None, @@ -3302,24 +3369,27 @@ def update_credentials(self, rest. :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source credentials. - :param str source_type: The source that this credentials object connects to. - - `box` indicates the credentials are used to connect an instance of Enterprise - Box. - - `salesforce` indicates the credentials are used to connect to Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to an IBM - Cloud Object Store. - :param CredentialDetails credential_details: Object containing details of the - stored credentials. - Obtain credentials for your source from the administrator of the source. - :param str status: The current status of this set of credentials. `connected` - indicates that the credentials are available to use with the source configuration - of a collection. `invalid` refers to the credentials (for example, the password - provided has expired) and must be corrected before they can be used with a - collection. + :param str credential_id: The unique identifier for a set of source + credentials. + :param str source_type: (optional) The source that this credentials object + connects to. + - `box` indicates the credentials are used to connect an instance of + Enterprise Box. + - `salesforce` indicates the credentials are used to connect to + Salesforce. + - `sharepoint` indicates the credentials are used to connect to Microsoft + SharePoint Online. + - `web_crawl` indicates the credentials are used to perform a web crawl. + = `cloud_object_storage` indicates the credentials are used to connect to + an IBM Cloud Object Store. + :param CredentialDetails credential_details: (optional) Object containing + details of the stored credentials. + Obtain credentials for your source from the administrator of the source. + :param str status: (optional) The current status of this set of + credentials. `connected` indicates that the credentials are available to + use with the source configuration of a collection. `invalid` refers to the + credentials (for example, the password provided has expired) and must be + corrected before they can be used with a collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3349,13 +3419,14 @@ def update_credentials(self, url = '/v1/environments/{0}/credentials/{1}'.format( *self._encode_path_vars(environment_id, credential_id)) - response = self.request( + request = self.prepare_request( method='PUT', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def delete_credentials(self, environment_id, credential_id, **kwargs): @@ -3365,7 +3436,8 @@ def delete_credentials(self, environment_id, credential_id, **kwargs): Deletes a set of stored credentials from your Discovery instance. :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source credentials. + :param str credential_id: The unique identifier for a set of source + credentials. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3386,12 +3458,13 @@ def delete_credentials(self, environment_id, credential_id, **kwargs): url = '/v1/environments/{0}/credentials/{1}'.format( *self._encode_path_vars(environment_id, credential_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -3423,22 +3496,23 @@ def list_gateways(self, environment_id, **kwargs): url = '/v1/environments/{0}/gateways'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response - def create_gateway(self, environment_id, name=None, **kwargs): + def create_gateway(self, environment_id, *, name=None, **kwargs): """ Create Gateway. Create a gateway configuration to use with a remotely installed gateway. :param str environment_id: The ID of the environment. - :param str name: User-defined name. + :param str name: (optional) User-defined name. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3459,13 +3533,14 @@ def create_gateway(self, environment_id, name=None, **kwargs): url = '/v1/environments/{0}/gateways'.format( *self._encode_path_vars(environment_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_gateway(self, environment_id, gateway_id, **kwargs): @@ -3496,12 +3571,13 @@ def get_gateway(self, environment_id, gateway_id, **kwargs): url = '/v1/environments/{0}/gateways/{1}'.format( *self._encode_path_vars(environment_id, gateway_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def delete_gateway(self, environment_id, gateway_id, **kwargs): @@ -3532,15 +3608,107 @@ def delete_gateway(self, environment_id, gateway_id, **kwargs): url = '/v1/environments/{0}/gateways/{1}'.format( *self._encode_path_vars(environment_id, gateway_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response +class TestConfigurationInEnvironmentEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + class Step(Enum): + """ + Specify to only run the input document through the given step instead of running + the input document through the entire ingestion workflow. Valid values are + `convert`, `enrich`, and `normalize`. + """ + HTML_INPUT = 'html_input' + HTML_OUTPUT = 'html_output' + JSON_OUTPUT = 'json_output' + JSON_NORMALIZATIONS_OUTPUT = 'json_normalizations_output' + ENRICHMENTS_OUTPUT = 'enrichments_output' + NORMALIZATIONS_OUTPUT = 'normalizations_output' + + +class AddDocumentEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +class UpdateDocumentEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +class GetMetricsQueryEnums(object): + + class ResultType(Enum): + """ + The type of result to consider when calculating the metric. + """ + DOCUMENT = 'document' + + +class GetMetricsQueryEventEnums(object): + + class ResultType(Enum): + """ + The type of result to consider when calculating the metric. + """ + DOCUMENT = 'document' + + +class GetMetricsQueryNoResultsEnums(object): + + class ResultType(Enum): + """ + The type of result to consider when calculating the metric. + """ + DOCUMENT = 'document' + + +class GetMetricsEventRateEnums(object): + + class ResultType(Enum): + """ + The type of result to consider when calculating the metric. + """ + DOCUMENT = 'document' + + ############################################################################## # Models ############################################################################## @@ -3552,18 +3720,18 @@ class AggregationResult(object): :attr str key: (optional) Key that matched the aggregation type. :attr int matching_results: (optional) Number of matching results. - :attr list[QueryAggregation] aggregations: (optional) Aggregations returned in the - case of chained aggregations. + :attr list[QueryAggregation] aggregations: (optional) Aggregations returned in + the case of chained aggregations. """ - def __init__(self, key=None, matching_results=None, aggregations=None): + def __init__(self, *, key=None, matching_results=None, aggregations=None): """ Initialize a AggregationResult object. :param str key: (optional) Key that matched the aggregation type. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations returned in - the case of chained aggregations. + :param list[QueryAggregation] aggregations: (optional) Aggregations + returned in the case of chained aggregations. """ self.key = key self.matching_results = matching_results @@ -3622,11 +3790,12 @@ class Calculation(object): Calculation. :attr str field: (optional) The field where the aggregation is located in the - document. + document. :attr float value: (optional) Value of the aggregation. """ def __init__(self, + *, type=None, results=None, matching_results=None, @@ -3636,14 +3805,15 @@ def __init__(self, """ Initialize a Calculation object. - :param str type: (optional) The type of aggregation command used. For example: - term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation results. + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param list[AggregationResult] results: (optional) Array of aggregation + results. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations returned by - Discovery. - :param str field: (optional) The field where the aggregation is located in the - document. + :param list[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. :param float value: (optional) Value of the aggregation. """ self.field = field @@ -3696,26 +3866,28 @@ class Collection(object): :attr str collection_id: (optional) The unique identifier of the collection. :attr str name: (optional) The name of the collection. :attr str description: (optional) The description of the collection. - :attr datetime created: (optional) The creation date of the collection in the format - yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. + :attr datetime created: (optional) The creation date of the collection in the + format yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. :attr datetime updated: (optional) The timestamp of when the collection was last - updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :attr str status: (optional) The status of the collection. :attr str configuration_id: (optional) The unique identifier of the collection's - configuration. - :attr str language: (optional) The language of the documents stored in the collection. - Permitted values include `en` (English), `de` (German), and `es` (Spanish). + configuration. + :attr str language: (optional) The language of the documents stored in the + collection. Permitted values include `en` (English), `de` (German), and `es` + (Spanish). :attr DocumentCounts document_counts: (optional) - :attr CollectionDiskUsage disk_usage: (optional) Summary of the disk usage statistics - for this collection. + :attr CollectionDiskUsage disk_usage: (optional) Summary of the disk usage + statistics for this collection. :attr TrainingStatus training_status: (optional) - :attr CollectionCrawlStatus crawl_status: (optional) Object containing information - about the crawl status of this collection. + :attr CollectionCrawlStatus crawl_status: (optional) Object containing + information about the crawl status of this collection. :attr SduStatus smart_document_understanding: (optional) Object containing smart - document understanding information for this collection. + document understanding information for this collection. """ def __init__(self, + *, collection_id=None, name=None, description=None, @@ -3732,27 +3904,28 @@ def __init__(self, """ Initialize a Collection object. - :param str collection_id: (optional) The unique identifier of the collection. + :param str collection_id: (optional) The unique identifier of the + collection. :param str name: (optional) The name of the collection. :param str description: (optional) The description of the collection. - :param datetime created: (optional) The creation date of the collection in the - format yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. - :param datetime updated: (optional) The timestamp of when the collection was last - updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :param datetime created: (optional) The creation date of the collection in + the format yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. + :param datetime updated: (optional) The timestamp of when the collection + was last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :param str status: (optional) The status of the collection. - :param str configuration_id: (optional) The unique identifier of the collection's - configuration. + :param str configuration_id: (optional) The unique identifier of the + collection's configuration. :param str language: (optional) The language of the documents stored in the - collection. Permitted values include `en` (English), `de` (German), and `es` - (Spanish). + collection. Permitted values include `en` (English), `de` (German), and + `es` (Spanish). :param DocumentCounts document_counts: (optional) :param CollectionDiskUsage disk_usage: (optional) Summary of the disk usage - statistics for this collection. + statistics for this collection. :param TrainingStatus training_status: (optional) :param CollectionCrawlStatus crawl_status: (optional) Object containing - information about the crawl status of this collection. - :param SduStatus smart_document_understanding: (optional) Object containing smart - document understanding information for this collection. + information about the crawl status of this collection. + :param SduStatus smart_document_understanding: (optional) Object containing + smart document understanding information for this collection. """ self.collection_id = collection_id self.name = name @@ -3867,21 +4040,29 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The status of the collection. + """ + ACTIVE = "active" + PENDING = "pending" + MAINTENANCE = "maintenance" + class CollectionCrawlStatus(object): """ Object containing information about the crawl status of this collection. - :attr SourceStatus source_crawl: (optional) Object containing source crawl status - information. + :attr SourceStatus source_crawl: (optional) Object containing source crawl + status information. """ - def __init__(self, source_crawl=None): + def __init__(self, *, source_crawl=None): """ Initialize a CollectionCrawlStatus object. - :param SourceStatus source_crawl: (optional) Object containing source crawl status - information. + :param SourceStatus source_crawl: (optional) Object containing source crawl + status information. """ self.source_crawl = source_crawl @@ -3929,7 +4110,7 @@ class CollectionDiskUsage(object): :attr int used_bytes: (optional) Number of bytes used by the collection. """ - def __init__(self, used_bytes=None): + def __init__(self, *, used_bytes=None): """ Initialize a CollectionDiskUsage object. @@ -3979,16 +4160,17 @@ class CollectionUsage(object): :attr int available: (optional) Number of active collections in the environment. :attr int maximum_allowed: (optional) Total number of collections allowed in the - environment. + environment. """ - def __init__(self, available=None, maximum_allowed=None): + def __init__(self, *, available=None, maximum_allowed=None): """ Initialize a CollectionUsage object. - :param int available: (optional) Number of active collections in the environment. - :param int maximum_allowed: (optional) Total number of collections allowed in the - environment. + :param int available: (optional) Number of active collections in the + environment. + :param int maximum_allowed: (optional) Total number of collections allowed + in the environment. """ self.available = available self.maximum_allowed = maximum_allowed @@ -4038,25 +4220,28 @@ class Configuration(object): """ A custom configuration for the environment. - :attr str configuration_id: (optional) The unique identifier of the configuration. + :attr str configuration_id: (optional) The unique identifier of the + configuration. :attr str name: The name of the configuration. :attr datetime created: (optional) The creation date of the configuration in the - format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr datetime updated: (optional) The timestamp of when the configuration was last - updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str description: (optional) The description of the configuration, if available. + format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :attr datetime updated: (optional) The timestamp of when the configuration was + last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :attr str description: (optional) The description of the configuration, if + available. :attr Conversions conversions: (optional) Document conversion settings. :attr list[Enrichment] enrichments: (optional) An array of document enrichment - settings for the configuration. - :attr list[NormalizationOperation] normalizations: (optional) Defines operations that - can be used to transform the final output JSON into a normalized form. Operations are - executed in the order that they appear in the array. + settings for the configuration. + :attr list[NormalizationOperation] normalizations: (optional) Defines operations + that can be used to transform the final output JSON into a normalized form. + Operations are executed in the order that they appear in the array. :attr Source source: (optional) Object containing source parameters for the - configuration. + configuration. """ def __init__(self, name, + *, configuration_id=None, created=None, updated=None, @@ -4070,21 +4255,22 @@ def __init__(self, :param str name: The name of the configuration. :param str configuration_id: (optional) The unique identifier of the - configuration. - :param datetime created: (optional) The creation date of the configuration in the - format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param datetime updated: (optional) The timestamp of when the configuration was - last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + configuration. + :param datetime created: (optional) The creation date of the configuration + in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :param datetime updated: (optional) The timestamp of when the configuration + was last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :param str description: (optional) The description of the configuration, if - available. + available. :param Conversions conversions: (optional) Document conversion settings. - :param list[Enrichment] enrichments: (optional) An array of document enrichment - settings for the configuration. - :param list[NormalizationOperation] normalizations: (optional) Defines operations - that can be used to transform the final output JSON into a normalized form. - Operations are executed in the order that they appear in the array. - :param Source source: (optional) Object containing source parameters for the - configuration. + :param list[Enrichment] enrichments: (optional) An array of document + enrichment settings for the configuration. + :param list[NormalizationOperation] normalizations: (optional) Defines + operations that can be used to transform the final output JSON into a + normalized form. Operations are executed in the order that they appear in + the array. + :param Source source: (optional) Object containing source parameters for + the configuration. """ self.configuration_id = configuration_id self.name = name @@ -4186,18 +4372,21 @@ class Conversions(object): :attr PdfSettings pdf: (optional) A list of PDF conversion settings. :attr WordSettings word: (optional) A list of Word conversion settings. :attr HtmlSettings html: (optional) A list of HTML conversion settings. - :attr SegmentSettings segment: (optional) A list of Document Segmentation settings. - :attr list[NormalizationOperation] json_normalizations: (optional) Defines operations - that can be used to transform the final output JSON into a normalized form. Operations - are executed in the order that they appear in the array. - :attr bool image_text_recognition: (optional) When `true`, automatic text extraction - from images (this includes images embedded in supported document formats, for example - PDF, and suppported image formats, for example TIFF) is performed on documents - uploaded to the collection. This field is supported on **Advanced** and higher plans - only. **Lite** plans do not support image text recognition. + :attr SegmentSettings segment: (optional) A list of Document Segmentation + settings. + :attr list[NormalizationOperation] json_normalizations: (optional) Defines + operations that can be used to transform the final output JSON into a normalized + form. Operations are executed in the order that they appear in the array. + :attr bool image_text_recognition: (optional) When `true`, automatic text + extraction from images (this includes images embedded in supported document + formats, for example PDF, and suppported image formats, for example TIFF) is + performed on documents uploaded to the collection. This field is supported on + **Advanced** and higher plans only. **Lite** plans do not support image text + recognition. """ def __init__(self, + *, pdf=None, word=None, html=None, @@ -4211,16 +4400,17 @@ def __init__(self, :param WordSettings word: (optional) A list of Word conversion settings. :param HtmlSettings html: (optional) A list of HTML conversion settings. :param SegmentSettings segment: (optional) A list of Document Segmentation - settings. + settings. :param list[NormalizationOperation] json_normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a normalized - form. Operations are executed in the order that they appear in the array. + operations that can be used to transform the final output JSON into a + normalized form. Operations are executed in the order that they appear in + the array. :param bool image_text_recognition: (optional) When `true`, automatic text - extraction from images (this includes images embedded in supported document - formats, for example PDF, and suppported image formats, for example TIFF) is - performed on documents uploaded to the collection. This field is supported on - **Advanced** and higher plans only. **Lite** plans do not support image text - recognition. + extraction from images (this includes images embedded in supported document + formats, for example PDF, and suppported image formats, for example TIFF) + is performed on documents uploaded to the collection. This field is + supported on **Advanced** and higher plans only. **Lite** plans do not + support image text recognition. """ self.pdf = pdf self.word = word @@ -4304,7 +4494,7 @@ class CreateEventResponse(object): :attr EventData data: (optional) Query event data object. """ - def __init__(self, type=None, data=None): + def __init__(self, *, type=None, data=None): """ Initialize a CreateEventResponse object. @@ -4353,86 +4543,98 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The event type that was created. + """ + CLICK = "click" + class CredentialDetails(object): """ Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. - :attr str credential_type: (optional) The authentication method for this credentials - definition. The **credential_type** specified must be supported by the - **source_type**. The following combinations are possible: - - `"source_type": "box"` - valid `credential_type`s: `oauth2` - - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with - **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. - :attr str client_id: (optional) The **client_id** of the source that these credentials - connect to. Only valid, and required, with a **credential_type** of `oauth2`. - :attr str enterprise_id: (optional) The **enterprise_id** of the Box site that these - credentials connect to. Only valid, and required, with a **source_type** of `box`. - :attr str url: (optional) The **url** of the source that these credentials connect to. - Only valid, and required, with a **credential_type** of `username_password`, `noauth`, - and `basic`. - :attr str username: (optional) The **username** of the source that these credentials - connect to. Only valid, and required, with a **credential_type** of `saml`, - `username_password`, `basic`, or `ntlm_v1`. - :attr str organization_url: (optional) The **organization_url** of the source that - these credentials connect to. Only valid, and required, with a **credential_type** of - `saml`. - :attr str site_collection_path: (optional) The **site_collection.path** of the source - that these credentials connect to. Only valid, and required, with a **source_type** of - `sharepoint`. - :attr str client_secret: (optional) The **client_secret** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or modifying - **credentials**. - :attr str public_key_id: (optional) The **public_key_id** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or modifying - **credentials**. + :attr str credential_type: (optional) The authentication method for this + credentials definition. The **credential_type** specified must be supported by + the **source_type**. The following combinations are possible: + - `"source_type": "box"` - valid `credential_type`s: `oauth2` + - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` + - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with + **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` + - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` + - "source_type": "cloud_object_storage"` - valid `credential_type`s: + `aws4_hmac`. + :attr str client_id: (optional) The **client_id** of the source that these + credentials connect to. Only valid, and required, with a **credential_type** of + `oauth2`. + :attr str enterprise_id: (optional) The **enterprise_id** of the Box site that + these credentials connect to. Only valid, and required, with a **source_type** + of `box`. + :attr str url: (optional) The **url** of the source that these credentials + connect to. Only valid, and required, with a **credential_type** of + `username_password`, `noauth`, and `basic`. + :attr str username: (optional) The **username** of the source that these + credentials connect to. Only valid, and required, with a **credential_type** of + `saml`, `username_password`, `basic`, or `ntlm_v1`. + :attr str organization_url: (optional) The **organization_url** of the source + that these credentials connect to. Only valid, and required, with a + **credential_type** of `saml`. + :attr str site_collection_path: (optional) The **site_collection.path** of the + source that these credentials connect to. Only valid, and required, with a + **source_type** of `sharepoint`. + :attr str client_secret: (optional) The **client_secret** of the source that + these credentials connect to. Only valid, and required, with a + **credential_type** of `oauth2`. This value is never returned and is only used + when creating or modifying **credentials**. + :attr str public_key_id: (optional) The **public_key_id** of the source that + these credentials connect to. Only valid, and required, with a + **credential_type** of `oauth2`. This value is never returned and is only used + when creating or modifying **credentials**. :attr str private_key: (optional) The **private_key** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or modifying - **credentials**. + credentials connect to. Only valid, and required, with a **credential_type** of + `oauth2`. This value is never returned and is only used when creating or + modifying **credentials**. :attr str passphrase: (optional) The **passphrase** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or modifying - **credentials**. - :attr str password: (optional) The **password** of the source that these credentials - connect to. Only valid, and required, with **credential_type**s of `saml`, - `username_password`, `basic`, or `ntlm_v1`. - **Note:** When used with a **source_type** of `salesforce`, the password consists of - the Salesforce password and a valid Salesforce security token concatenated. This value - is never returned and is only used when creating or modifying **credentials**. - :attr str gateway_id: (optional) The ID of the **gateway** to be connected through - (when connecting to intranet sites). Only valid with a **credential_type** of - `noauth`, `basic`, or `ntlm_v1`. Gateways are created using the - `/v1/environments/{environment_id}/gateways` methods. - :attr str source_version: (optional) The type of Sharepoint repository to connect to. - Only valid, and required, with a **source_type** of `sharepoint`. - :attr str web_application_url: (optional) SharePoint OnPrem WebApplication URL. Only - valid, and required, with a **source_version** of `2016`. If a port is not supplied, - the default to port `80` for http and port `443` for https connections are used. + credentials connect to. Only valid, and required, with a **credential_type** of + `oauth2`. This value is never returned and is only used when creating or + modifying **credentials**. + :attr str password: (optional) The **password** of the source that these + credentials connect to. Only valid, and required, with **credential_type**s of + `saml`, `username_password`, `basic`, or `ntlm_v1`. + **Note:** When used with a **source_type** of `salesforce`, the password + consists of the Salesforce password and a valid Salesforce security token + concatenated. This value is never returned and is only used when creating or + modifying **credentials**. + :attr str gateway_id: (optional) The ID of the **gateway** to be connected + through (when connecting to intranet sites). Only valid with a + **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are created + using the `/v1/environments/{environment_id}/gateways` methods. + :attr str source_version: (optional) The type of Sharepoint repository to + connect to. Only valid, and required, with a **source_type** of `sharepoint`. + :attr str web_application_url: (optional) SharePoint OnPrem WebApplication URL. + Only valid, and required, with a **source_version** of `2016`. If a port is not + supplied, the default to port `80` for http and port `443` for https connections + are used. :attr str domain: (optional) The domain used to log in to your OnPrem SharePoint - account. Only valid, and required, with a **source_version** of `2016`. - :attr str endpoint: (optional) The endpoint associated with the cloud object store - that your are connecting to. Only valid, and required, with a **credential_type** of - `aws4_hmac`. - :attr str access_key_id: (optional) The access key ID associated with the cloud object - store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value - is never returned and is only used when creating or modifying **credentials**. For - more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - :attr str secret_access_key: (optional) The secret access key associated with the - cloud object store. Only valid, and required, with a **credential_type** of - `aws4_hmac`. This value is never returned and is only used when creating or modifying - **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). + account. Only valid, and required, with a **source_version** of `2016`. + :attr str endpoint: (optional) The endpoint associated with the cloud object + store that your are connecting to. Only valid, and required, with a + **credential_type** of `aws4_hmac`. + :attr str access_key_id: (optional) The access key ID associated with the cloud + object store. Only valid, and required, with a **credential_type** of + `aws4_hmac`. This value is never returned and is only used when creating or + modifying **credentials**. For more infomation, see the [cloud object store + documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). + :attr str secret_access_key: (optional) The secret access key associated with + the cloud object store. Only valid, and required, with a **credential_type** of + `aws4_hmac`. This value is never returned and is only used when creating or + modifying **credentials**. For more infomation, see the [cloud object store + documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). """ def __init__(self, + *, credential_type=None, client_id=None, enterprise_id=None, @@ -4456,80 +4658,87 @@ def __init__(self, Initialize a CredentialDetails object. :param str credential_type: (optional) The authentication method for this - credentials definition. The **credential_type** specified must be supported by - the **source_type**. The following combinations are possible: - - `"source_type": "box"` - valid `credential_type`s: `oauth2` - - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with - **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. + credentials definition. The **credential_type** specified must be + supported by the **source_type**. The following combinations are possible: + - `"source_type": "box"` - valid `credential_type`s: `oauth2` + - `"source_type": "salesforce"` - valid `credential_type`s: + `username_password` + - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with + **source_version** of `online`, or `ntlm_v1` with **source_version** of + `2016` + - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or + `basic` + - "source_type": "cloud_object_storage"` - valid `credential_type`s: + `aws4_hmac`. :param str client_id: (optional) The **client_id** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. - :param str enterprise_id: (optional) The **enterprise_id** of the Box site that - these credentials connect to. Only valid, and required, with a **source_type** of - `box`. + credentials connect to. Only valid, and required, with a + **credential_type** of `oauth2`. + :param str enterprise_id: (optional) The **enterprise_id** of the Box site + that these credentials connect to. Only valid, and required, with a + **source_type** of `box`. :param str url: (optional) The **url** of the source that these credentials - connect to. Only valid, and required, with a **credential_type** of - `username_password`, `noauth`, and `basic`. + connect to. Only valid, and required, with a **credential_type** of + `username_password`, `noauth`, and `basic`. :param str username: (optional) The **username** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `saml`, `username_password`, `basic`, or `ntlm_v1`. - :param str organization_url: (optional) The **organization_url** of the source - that these credentials connect to. Only valid, and required, with a - **credential_type** of `saml`. - :param str site_collection_path: (optional) The **site_collection.path** of the - source that these credentials connect to. Only valid, and required, with a - **source_type** of `sharepoint`. - :param str client_secret: (optional) The **client_secret** of the source that - these credentials connect to. Only valid, and required, with a **credential_type** - of `oauth2`. This value is never returned and is only used when creating or - modifying **credentials**. - :param str public_key_id: (optional) The **public_key_id** of the source that - these credentials connect to. Only valid, and required, with a **credential_type** - of `oauth2`. This value is never returned and is only used when creating or - modifying **credentials**. - :param str private_key: (optional) The **private_key** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or modifying - **credentials**. - :param str passphrase: (optional) The **passphrase** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or modifying - **credentials**. + credentials connect to. Only valid, and required, with a + **credential_type** of `saml`, `username_password`, `basic`, or `ntlm_v1`. + :param str organization_url: (optional) The **organization_url** of the + source that these credentials connect to. Only valid, and required, with a + **credential_type** of `saml`. + :param str site_collection_path: (optional) The **site_collection.path** of + the source that these credentials connect to. Only valid, and required, + with a **source_type** of `sharepoint`. + :param str client_secret: (optional) The **client_secret** of the source + that these credentials connect to. Only valid, and required, with a + **credential_type** of `oauth2`. This value is never returned and is only + used when creating or modifying **credentials**. + :param str public_key_id: (optional) The **public_key_id** of the source + that these credentials connect to. Only valid, and required, with a + **credential_type** of `oauth2`. This value is never returned and is only + used when creating or modifying **credentials**. + :param str private_key: (optional) The **private_key** of the source that + these credentials connect to. Only valid, and required, with a + **credential_type** of `oauth2`. This value is never returned and is only + used when creating or modifying **credentials**. + :param str passphrase: (optional) The **passphrase** of the source that + these credentials connect to. Only valid, and required, with a + **credential_type** of `oauth2`. This value is never returned and is only + used when creating or modifying **credentials**. :param str password: (optional) The **password** of the source that these - credentials connect to. Only valid, and required, with **credential_type**s of - `saml`, `username_password`, `basic`, or `ntlm_v1`. - **Note:** When used with a **source_type** of `salesforce`, the password consists - of the Salesforce password and a valid Salesforce security token concatenated. - This value is never returned and is only used when creating or modifying - **credentials**. + credentials connect to. Only valid, and required, with **credential_type**s + of `saml`, `username_password`, `basic`, or `ntlm_v1`. + **Note:** When used with a **source_type** of `salesforce`, the password + consists of the Salesforce password and a valid Salesforce security token + concatenated. This value is never returned and is only used when creating + or modifying **credentials**. :param str gateway_id: (optional) The ID of the **gateway** to be connected - through (when connecting to intranet sites). Only valid with a **credential_type** - of `noauth`, `basic`, or `ntlm_v1`. Gateways are created using the - `/v1/environments/{environment_id}/gateways` methods. - :param str source_version: (optional) The type of Sharepoint repository to connect - to. Only valid, and required, with a **source_type** of `sharepoint`. - :param str web_application_url: (optional) SharePoint OnPrem WebApplication URL. - Only valid, and required, with a **source_version** of `2016`. If a port is not - supplied, the default to port `80` for http and port `443` for https connections - are used. - :param str domain: (optional) The domain used to log in to your OnPrem SharePoint - account. Only valid, and required, with a **source_version** of `2016`. - :param str endpoint: (optional) The endpoint associated with the cloud object - store that your are connecting to. Only valid, and required, with a - **credential_type** of `aws4_hmac`. - :param str access_key_id: (optional) The access key ID associated with the cloud - object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. - This value is never returned and is only used when creating or modifying - **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - :param str secret_access_key: (optional) The secret access key associated with the - cloud object store. Only valid, and required, with a **credential_type** of - `aws4_hmac`. This value is never returned and is only used when creating or - modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). + through (when connecting to intranet sites). Only valid with a + **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are + created using the `/v1/environments/{environment_id}/gateways` methods. + :param str source_version: (optional) The type of Sharepoint repository to + connect to. Only valid, and required, with a **source_type** of + `sharepoint`. + :param str web_application_url: (optional) SharePoint OnPrem WebApplication + URL. Only valid, and required, with a **source_version** of `2016`. If a + port is not supplied, the default to port `80` for http and port `443` for + https connections are used. + :param str domain: (optional) The domain used to log in to your OnPrem + SharePoint account. Only valid, and required, with a **source_version** of + `2016`. + :param str endpoint: (optional) The endpoint associated with the cloud + object store that your are connecting to. Only valid, and required, with a + **credential_type** of `aws4_hmac`. + :param str access_key_id: (optional) The access key ID associated with the + cloud object store. Only valid, and required, with a **credential_type** of + `aws4_hmac`. This value is never returned and is only used when creating or + modifying **credentials**. For more infomation, see the [cloud object store + documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). + :param str secret_access_key: (optional) The secret access key associated + with the cloud object store. Only valid, and required, with a + **credential_type** of `aws4_hmac`. This value is never returned and is + only used when creating or modifying **credentials**. For more infomation, + see the [cloud object store + documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). """ self.credential_type = credential_type self.client_id = client_id @@ -4670,31 +4879,62 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class CredentialTypeEnum(Enum): + """ + The authentication method for this credentials definition. The + **credential_type** specified must be supported by the **source_type**. The + following combinations are possible: + - `"source_type": "box"` - valid `credential_type`s: `oauth2` + - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` + - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with + **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` + - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` + - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. + """ + OAUTH2 = "oauth2" + SAML = "saml" + USERNAME_PASSWORD = "username_password" + NOAUTH = "noauth" + BASIC = "basic" + NTLM_V1 = "ntlm_v1" + AWS4_HMAC = "aws4_hmac" + + class SourceVersionEnum(Enum): + """ + The type of Sharepoint repository to connect to. Only valid, and required, with a + **source_type** of `sharepoint`. + """ + ONLINE = "online" + class Credentials(object): """ Object containing credential information. - :attr str credential_id: (optional) Unique identifier for this set of credentials. - :attr str source_type: (optional) The source that this credentials object connects to. - - `box` indicates the credentials are used to connect an instance of Enterprise Box. - - `salesforce` indicates the credentials are used to connect to Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft SharePoint - Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to an IBM - Cloud Object Store. - :attr CredentialDetails credential_details: (optional) Object containing details of - the stored credentials. - Obtain credentials for your source from the administrator of the source. + :attr str credential_id: (optional) Unique identifier for this set of + credentials. + :attr str source_type: (optional) The source that this credentials object + connects to. + - `box` indicates the credentials are used to connect an instance of Enterprise + Box. + - `salesforce` indicates the credentials are used to connect to Salesforce. + - `sharepoint` indicates the credentials are used to connect to Microsoft + SharePoint Online. + - `web_crawl` indicates the credentials are used to perform a web crawl. + = `cloud_object_storage` indicates the credentials are used to connect to an + IBM Cloud Object Store. + :attr CredentialDetails credential_details: (optional) Object containing details + of the stored credentials. + Obtain credentials for your source from the administrator of the source. :attr str status: (optional) The current status of this set of credentials. - `connected` indicates that the credentials are available to use with the source - configuration of a collection. `invalid` refers to the credentials (for example, the - password provided has expired) and must be corrected before they can be used with a - collection. + `connected` indicates that the credentials are available to use with the source + configuration of a collection. `invalid` refers to the credentials (for example, + the password provided has expired) and must be corrected before they can be used + with a collection. """ def __init__(self, + *, credential_id=None, source_type=None, credential_details=None, @@ -4703,25 +4943,26 @@ def __init__(self, Initialize a Credentials object. :param str credential_id: (optional) Unique identifier for this set of - credentials. + credentials. :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of Enterprise - Box. - - `salesforce` indicates the credentials are used to connect to Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to an IBM - Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing details - of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param str status: (optional) The current status of this set of credentials. - `connected` indicates that the credentials are available to use with the source - configuration of a collection. `invalid` refers to the credentials (for example, - the password provided has expired) and must be corrected before they can be used - with a collection. + connects to. + - `box` indicates the credentials are used to connect an instance of + Enterprise Box. + - `salesforce` indicates the credentials are used to connect to + Salesforce. + - `sharepoint` indicates the credentials are used to connect to Microsoft + SharePoint Online. + - `web_crawl` indicates the credentials are used to perform a web crawl. + = `cloud_object_storage` indicates the credentials are used to connect to + an IBM Cloud Object Store. + :param CredentialDetails credential_details: (optional) Object containing + details of the stored credentials. + Obtain credentials for your source from the administrator of the source. + :param str status: (optional) The current status of this set of + credentials. `connected` indicates that the credentials are available to + use with the source configuration of a collection. `invalid` refers to the + credentials (for example, the password provided has expired) and must be + corrected before they can be used with a collection. """ self.credential_id = credential_id self.source_type = source_type @@ -4780,21 +5021,49 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class SourceTypeEnum(Enum): + """ + The source that this credentials object connects to. + - `box` indicates the credentials are used to connect an instance of Enterprise + Box. + - `salesforce` indicates the credentials are used to connect to Salesforce. + - `sharepoint` indicates the credentials are used to connect to Microsoft + SharePoint Online. + - `web_crawl` indicates the credentials are used to perform a web crawl. + = `cloud_object_storage` indicates the credentials are used to connect to an IBM + Cloud Object Store. + """ + BOX = "box" + SALESFORCE = "salesforce" + SHAREPOINT = "sharepoint" + WEB_CRAWL = "web_crawl" + CLOUD_OBJECT_STORAGE = "cloud_object_storage" + + class StatusEnum(Enum): + """ + The current status of this set of credentials. `connected` indicates that the + credentials are available to use with the source configuration of a collection. + `invalid` refers to the credentials (for example, the password provided has + expired) and must be corrected before they can be used with a collection. + """ + CONNECTED = "connected" + INVALID = "invalid" + class CredentialsList(object): """ CredentialsList. - :attr list[Credentials] credentials: (optional) An array of credential definitions - that were created for this instance. + :attr list[Credentials] credentials: (optional) An array of credential + definitions that were created for this instance. """ - def __init__(self, credentials=None): + def __init__(self, *, credentials=None): """ Initialize a CredentialsList object. :param list[Credentials] credentials: (optional) An array of credential - definitions that were created for this instance. + definitions that were created for this instance. """ self.credentials = credentials @@ -4841,19 +5110,19 @@ class DeleteCollectionResponse(object): DeleteCollectionResponse. :attr str collection_id: The unique identifier of the collection that is being - deleted. - :attr str status: The status of the collection. The status of a successful deletion - operation is `deleted`. + deleted. + :attr str status: The status of the collection. The status of a successful + deletion operation is `deleted`. """ def __init__(self, collection_id, status): """ Initialize a DeleteCollectionResponse object. - :param str collection_id: The unique identifier of the collection that is being - deleted. + :param str collection_id: The unique identifier of the collection that is + being deleted. :param str status: The status of the collection. The status of a successful - deletion operation is `deleted`. + deletion operation is `deleted`. """ self.collection_id = collection_id self.status = status @@ -4905,25 +5174,33 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The status of the collection. The status of a successful deletion operation is + `deleted`. + """ + DELETED = "deleted" + class DeleteConfigurationResponse(object): """ DeleteConfigurationResponse. :attr str configuration_id: The unique identifier for the configuration. - :attr str status: Status of the configuration. A deleted configuration has the status - deleted. + :attr str status: Status of the configuration. A deleted configuration has the + status deleted. :attr list[Notice] notices: (optional) An array of notice messages, if any. """ - def __init__(self, configuration_id, status, notices=None): + def __init__(self, configuration_id, status, *, notices=None): """ Initialize a DeleteConfigurationResponse object. :param str configuration_id: The unique identifier for the configuration. - :param str status: Status of the configuration. A deleted configuration has the - status deleted. - :param list[Notice] notices: (optional) An array of notice messages, if any. + :param str status: Status of the configuration. A deleted configuration has + the status deleted. + :param list[Notice] notices: (optional) An array of notice messages, if + any. """ self.configuration_id = configuration_id self.status = status @@ -4983,22 +5260,28 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + Status of the configuration. A deleted configuration has the status deleted. + """ + DELETED = "deleted" + class DeleteCredentials(object): """ Object returned after credentials are deleted. - :attr str credential_id: (optional) The unique identifier of the credentials that have - been deleted. + :attr str credential_id: (optional) The unique identifier of the credentials + that have been deleted. :attr str status: (optional) The status of the deletion request. """ - def __init__(self, credential_id=None, status=None): + def __init__(self, *, credential_id=None, status=None): """ Initialize a DeleteCredentials object. - :param str credential_id: (optional) The unique identifier of the credentials that - have been deleted. + :param str credential_id: (optional) The unique identifier of the + credentials that have been deleted. :param str status: (optional) The status of the deletion request. """ self.credential_id = credential_id @@ -5043,23 +5326,29 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The status of the deletion request. + """ + DELETED = "deleted" + class DeleteDocumentResponse(object): """ DeleteDocumentResponse. :attr str document_id: (optional) The unique identifier of the document. - :attr str status: (optional) Status of the document. A deleted document has the status - deleted. + :attr str status: (optional) Status of the document. A deleted document has the + status deleted. """ - def __init__(self, document_id=None, status=None): + def __init__(self, *, document_id=None, status=None): """ Initialize a DeleteDocumentResponse object. :param str document_id: (optional) The unique identifier of the document. - :param str status: (optional) Status of the document. A deleted document has the - status deleted. + :param str status: (optional) Status of the document. A deleted document + has the status deleted. """ self.document_id = document_id self.status = status @@ -5103,6 +5392,12 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + Status of the document. A deleted document has the status deleted. + """ + DELETED = "deleted" + class DeleteEnvironmentResponse(object): """ @@ -5169,25 +5464,31 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + Status of the environment. + """ + DELETED = "deleted" + class DiskUsage(object): """ Summary of the disk usage statistics for the environment. :attr int used_bytes: (optional) Number of bytes within the environment's disk - capacity that are currently used to store data. - :attr int maximum_allowed_bytes: (optional) Total number of bytes available in the - environment's disk capacity. + capacity that are currently used to store data. + :attr int maximum_allowed_bytes: (optional) Total number of bytes available in + the environment's disk capacity. """ - def __init__(self, used_bytes=None, maximum_allowed_bytes=None): + def __init__(self, *, used_bytes=None, maximum_allowed_bytes=None): """ Initialize a DiskUsage object. - :param int used_bytes: (optional) Number of bytes within the environment's disk - capacity that are currently used to store data. - :param int maximum_allowed_bytes: (optional) Total number of bytes available in - the environment's disk capacity. + :param int used_bytes: (optional) Number of bytes within the environment's + disk capacity that are currently used to store data. + :param int maximum_allowed_bytes: (optional) Total number of bytes + available in the environment's disk capacity. """ self.used_bytes = used_bytes self.maximum_allowed_bytes = maximum_allowed_bytes @@ -5237,25 +5538,28 @@ class DocumentAccepted(object): """ DocumentAccepted. - :attr str document_id: (optional) The unique identifier of the ingested document. - :attr str status: (optional) Status of the document in the ingestion process. A status - of `processing` is returned for documents that are ingested with a *version* date - before `2019-01-01`. The `pending` status is returned for all others. + :attr str document_id: (optional) The unique identifier of the ingested + document. + :attr str status: (optional) Status of the document in the ingestion process. A + status of `processing` is returned for documents that are ingested with a + *version* date before `2019-01-01`. The `pending` status is returned for all + others. :attr list[Notice] notices: (optional) Array of notices produced by the - document-ingestion process. + document-ingestion process. """ - def __init__(self, document_id=None, status=None, notices=None): + def __init__(self, *, document_id=None, status=None, notices=None): """ Initialize a DocumentAccepted object. - :param str document_id: (optional) The unique identifier of the ingested document. - :param str status: (optional) Status of the document in the ingestion process. A - status of `processing` is returned for documents that are ingested with a - *version* date before `2019-01-01`. The `pending` status is returned for all - others. + :param str document_id: (optional) The unique identifier of the ingested + document. + :param str status: (optional) Status of the document in the ingestion + process. A status of `processing` is returned for documents that are + ingested with a *version* date before `2019-01-01`. The `pending` status is + returned for all others. :param list[Notice] notices: (optional) Array of notices produced by the - document-ingestion process. + document-ingestion process. """ self.document_id = document_id self.status = status @@ -5306,22 +5610,32 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + Status of the document in the ingestion process. A status of `processing` is + returned for documents that are ingested with a *version* date before + `2019-01-01`. The `pending` status is returned for all others. + """ + PROCESSING = "processing" + PENDING = "pending" + class DocumentCounts(object): """ DocumentCounts. :attr int available: (optional) The total number of available documents in the - collection. - :attr int processing: (optional) The number of documents in the collection that are - currently being processed. - :attr int failed: (optional) The number of documents in the collection that failed to - be ingested. - :attr int pending: (optional) The number of documents that have been uploaded to the - collection, but have not yet started processing. + collection. + :attr int processing: (optional) The number of documents in the collection that + are currently being processed. + :attr int failed: (optional) The number of documents in the collection that + failed to be ingested. + :attr int pending: (optional) The number of documents that have been uploaded to + the collection, but have not yet started processing. """ def __init__(self, + *, available=None, processing=None, failed=None, @@ -5329,14 +5643,14 @@ def __init__(self, """ Initialize a DocumentCounts object. - :param int available: (optional) The total number of available documents in the - collection. - :param int processing: (optional) The number of documents in the collection that - are currently being processed. - :param int failed: (optional) The number of documents in the collection that - failed to be ingested. - :param int pending: (optional) The number of documents that have been uploaded to - the collection, but have not yet started processing. + :param int available: (optional) The total number of available documents in + the collection. + :param int processing: (optional) The number of documents in the collection + that are currently being processed. + :param int failed: (optional) The number of documents in the collection + that failed to be ingested. + :param int pending: (optional) The number of documents that have been + uploaded to the collection, but have not yet started processing. """ self.available = available self.processing = processing @@ -5396,16 +5710,16 @@ class DocumentSnapshot(object): DocumentSnapshot. :attr str step: (optional) The step in the document conversion process that the - snapshot object represents. + snapshot object represents. :attr dict snapshot: (optional) Snapshot of the conversion. """ - def __init__(self, step=None, snapshot=None): + def __init__(self, *, step=None, snapshot=None): """ Initialize a DocumentSnapshot object. - :param str step: (optional) The step in the document conversion process that the - snapshot object represents. + :param str step: (optional) The step in the document conversion process + that the snapshot object represents. :param dict snapshot: (optional) Snapshot of the conversion. """ self.step = step @@ -5450,21 +5764,33 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StepEnum(Enum): + """ + The step in the document conversion process that the snapshot object represents. + """ + HTML_INPUT = "html_input" + HTML_OUTPUT = "html_output" + JSON_OUTPUT = "json_output" + JSON_NORMALIZATIONS_OUTPUT = "json_normalizations_output" + ENRICHMENTS_OUTPUT = "enrichments_output" + NORMALIZATIONS_OUTPUT = "normalizations_output" + class DocumentStatus(object): """ Status information about a submitted document. :attr str document_id: The unique identifier of the document. - :attr str configuration_id: (optional) The unique identifier for the configuration. + :attr str configuration_id: (optional) The unique identifier for the + configuration. :attr str status: Status of the document in the ingestion process. :attr str status_description: Description of the document status. :attr str filename: (optional) Name of the original source file (if available). :attr str file_type: (optional) The type of the original source file. - :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted as a - hexadecimal string). + :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted + as a hexadecimal string). :attr list[Notice] notices: Array of notices produced by the document-ingestion - process. + process. """ def __init__(self, @@ -5472,6 +5798,7 @@ def __init__(self, status, status_description, notices, + *, configuration_id=None, filename=None, file_type=None, @@ -5482,14 +5809,15 @@ def __init__(self, :param str document_id: The unique identifier of the document. :param str status: Status of the document in the ingestion process. :param str status_description: Description of the document status. - :param list[Notice] notices: Array of notices produced by the document-ingestion - process. + :param list[Notice] notices: Array of notices produced by the + document-ingestion process. :param str configuration_id: (optional) The unique identifier for the - configuration. - :param str filename: (optional) Name of the original source file (if available). + configuration. + :param str filename: (optional) Name of the original source file (if + available). :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file (formatted - as a hexadecimal string). + :param str sha1: (optional) The SHA-1 hash of the original source file + (formatted as a hexadecimal string). """ self.document_id = document_id self.configuration_id = configuration_id @@ -5587,40 +5915,61 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + Status of the document in the ingestion process. + """ + AVAILABLE = "available" + AVAILABLE_WITH_NOTICES = "available with notices" + FAILED = "failed" + PROCESSING = "processing" + PENDING = "pending" + + class FileTypeEnum(Enum): + """ + The type of the original source file. + """ + PDF = "pdf" + HTML = "html" + WORD = "word" + JSON = "json" + class Enrichment(object): """ Enrichment. :attr str description: (optional) Describes what the enrichment step does. - :attr str destination_field: Field where enrichments will be stored. This field must - already exist or be at most 1 level deeper than an existing field. For example, if - `text` is a top-level field with no sub-fields, `text.foo` is a valid destination but - `text.foo.bar` is not. + :attr str destination_field: Field where enrichments will be stored. This field + must already exist or be at most 1 level deeper than an existing field. For + example, if `text` is a top-level field with no sub-fields, `text.foo` is a + valid destination but `text.foo.bar` is not. :attr str source_field: Field to be enriched. - Arrays can be specified as the **source_field** if the **enrichment** service for this - enrichment is set to `natural_language_undstanding`. - :attr bool overwrite: (optional) Indicates that the enrichments will overwrite the - destination_field field if it already exists. - :attr str enrichment_name: Name of the enrichment service to call. Current options are - `natural_language_understanding` and `elements`. - When using `natual_language_understanding`, the **options** object must contain - Natural Language Understanding options. - When using `elements` the **options** object must contain Element Classification - options. Additionally, when using the `elements` enrichment the configuration - specified and files ingested must meet all the criteria specified in [the - documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-element-classification#element-classification). - :attr bool ignore_downstream_errors: (optional) If true, then most errors generated - during the enrichment process will be treated as warnings and will not cause the - document to fail processing. - :attr EnrichmentOptions options: (optional) Options which are specific to a particular - enrichment. + Arrays can be specified as the **source_field** if the **enrichment** service + for this enrichment is set to `natural_language_undstanding`. + :attr bool overwrite: (optional) Indicates that the enrichments will overwrite + the destination_field field if it already exists. + :attr str enrichment: Name of the enrichment service to call. Current options + are `natural_language_understanding` and `elements`. + When using `natual_language_understanding`, the **options** object must contain + Natural Language Understanding options. + When using `elements` the **options** object must contain Element + Classification options. Additionally, when using the `elements` enrichment the + configuration specified and files ingested must meet all the criteria specified + in [the + documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-element-classification#element-classification). + :attr bool ignore_downstream_errors: (optional) If true, then most errors + generated during the enrichment process will be treated as warnings and will not + cause the document to fail processing. + :attr EnrichmentOptions options: (optional) Options which are specific to a + particular enrichment. """ def __init__(self, destination_field, source_field, - enrichment_name, + enrichment, + *, description=None, overwrite=None, ignore_downstream_errors=None, @@ -5628,35 +5977,36 @@ def __init__(self, """ Initialize a Enrichment object. - :param str destination_field: Field where enrichments will be stored. This field - must already exist or be at most 1 level deeper than an existing field. For - example, if `text` is a top-level field with no sub-fields, `text.foo` is a valid - destination but `text.foo.bar` is not. + :param str destination_field: Field where enrichments will be stored. This + field must already exist or be at most 1 level deeper than an existing + field. For example, if `text` is a top-level field with no sub-fields, + `text.foo` is a valid destination but `text.foo.bar` is not. :param str source_field: Field to be enriched. - Arrays can be specified as the **source_field** if the **enrichment** service for - this enrichment is set to `natural_language_undstanding`. - :param str enrichment_name: Name of the enrichment service to call. Current - options are `natural_language_understanding` and `elements`. - When using `natual_language_understanding`, the **options** object must contain - Natural Language Understanding options. - When using `elements` the **options** object must contain Element Classification - options. Additionally, when using the `elements` enrichment the configuration - specified and files ingested must meet all the criteria specified in [the - documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-element-classification#element-classification). + Arrays can be specified as the **source_field** if the **enrichment** + service for this enrichment is set to `natural_language_undstanding`. + :param str enrichment: Name of the enrichment service to call. Current + options are `natural_language_understanding` and `elements`. + When using `natual_language_understanding`, the **options** object must + contain Natural Language Understanding options. + When using `elements` the **options** object must contain Element + Classification options. Additionally, when using the `elements` enrichment + the configuration specified and files ingested must meet all the criteria + specified in [the + documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-element-classification#element-classification). :param str description: (optional) Describes what the enrichment step does. - :param bool overwrite: (optional) Indicates that the enrichments will overwrite - the destination_field field if it already exists. + :param bool overwrite: (optional) Indicates that the enrichments will + overwrite the destination_field field if it already exists. :param bool ignore_downstream_errors: (optional) If true, then most errors - generated during the enrichment process will be treated as warnings and will not - cause the document to fail processing. - :param EnrichmentOptions options: (optional) Options which are specific to a - particular enrichment. + generated during the enrichment process will be treated as warnings and + will not cause the document to fail processing. + :param EnrichmentOptions options: (optional) Options which are specific to + a particular enrichment. """ self.description = description self.destination_field = destination_field self.source_field = source_field self.overwrite = overwrite - self.enrichment_name = enrichment_name + self.enrichment = enrichment self.ignore_downstream_errors = ignore_downstream_errors self.options = options @@ -5666,8 +6016,7 @@ def _from_dict(cls, _dict): args = {} validKeys = [ 'description', 'destination_field', 'source_field', 'overwrite', - 'enrichment_name', 'enrichment', 'ignore_downstream_errors', - 'options' + 'enrichment', 'ignore_downstream_errors', 'options' ] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: @@ -5690,9 +6039,8 @@ def _from_dict(cls, _dict): ) if 'overwrite' in _dict: args['overwrite'] = _dict.get('overwrite') - if 'enrichment' in _dict or 'enrichment_name' in _dict: - args['enrichment_name'] = _dict.get('enrichment') or _dict.get( - 'enrichment_name') + if 'enrichment' in _dict: + args['enrichment'] = _dict.get('enrichment') else: raise ValueError( 'Required property \'enrichment\' not present in Enrichment JSON' @@ -5716,9 +6064,8 @@ def _to_dict(self): _dict['source_field'] = self.source_field if hasattr(self, 'overwrite') and self.overwrite is not None: _dict['overwrite'] = self.overwrite - if hasattr(self, - 'enrichment_name') and self.enrichment_name is not None: - _dict['enrichment'] = self.enrichment_name + if hasattr(self, 'enrichment') and self.enrichment is not None: + _dict['enrichment'] = self.enrichment if hasattr(self, 'ignore_downstream_errors' ) and self.ignore_downstream_errors is not None: _dict['ignore_downstream_errors'] = self.ignore_downstream_errors @@ -5746,28 +6093,29 @@ class EnrichmentOptions(object): Options which are specific to a particular enrichment. :attr NluEnrichmentFeatures features: (optional) - :attr str language: (optional) ISO 639-1 code indicating the language to use for the - analysis. This code overrides the automatic language detection performed by the - service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` (German), - `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). - **Note:** Not all features support all languages, automatic detection is recommended. - :attr str model: (optional) *For use with `elements` enrichments only.* The element - extraction model to use. Models available are: `contract`. + :attr str language: (optional) ISO 639-1 code indicating the language to use for + the analysis. This code overrides the automatic language detection performed by + the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` + (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and + `sv` (Swedish). **Note:** Not all features support all languages, automatic + detection is recommended. + :attr str model: (optional) *For use with `elements` enrichments only.* The + element extraction model to use. Models available are: `contract`. """ - def __init__(self, features=None, language=None, model=None): + def __init__(self, *, features=None, language=None, model=None): """ Initialize a EnrichmentOptions object. :param NluEnrichmentFeatures features: (optional) - :param str language: (optional) ISO 639-1 code indicating the language to use for - the analysis. This code overrides the automatic language detection performed by - the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` - (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and - `sv` (Swedish). **Note:** Not all features support all languages, automatic - detection is recommended. - :param str model: (optional) *For use with `elements` enrichments only.* The - element extraction model to use. Models available are: `contract`. + :param str language: (optional) ISO 639-1 code indicating the language to + use for the analysis. This code overrides the automatic language detection + performed by the service. Valid codes are `ar` (Arabic), `en` (English), + `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` + (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features + support all languages, automatic detection is recommended. + :param str model: (optional) *For use with `elements` enrichments only.* + The element extraction model to use. Models available are: `contract`. """ self.features = features self.language = language @@ -5817,6 +6165,24 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LanguageEnum(Enum): + """ + ISO 639-1 code indicating the language to use for the analysis. This code + overrides the automatic language detection performed by the service. Valid codes + are `ar` (Arabic), `en` (English), `fr` (French), `de` (German), `it` (Italian), + `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** + Not all features support all languages, automatic detection is recommended. + """ + AR = "ar" + EN = "en" + FR = "fr" + DE = "de" + IT = "it" + PT = "pt" + RU = "ru" + ES = "es" + SV = "sv" + class Environment(object): """ @@ -5825,26 +6191,28 @@ class Environment(object): :attr str environment_id: (optional) Unique identifier for the environment. :attr str name: (optional) Name that identifies the environment. :attr str description: (optional) Description of the environment. - :attr datetime created: (optional) Creation date of the environment, in the format - `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :attr datetime updated: (optional) Date of most recent environment update, in the - format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. + :attr datetime created: (optional) Creation date of the environment, in the + format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. + :attr datetime updated: (optional) Date of most recent environment update, in + the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. :attr str status: (optional) Current status of the environment. `resizing` is - displayed when a request to increase the environment size has been made, but is still - in the process of being completed. + displayed when a request to increase the environment size has been made, but is + still in the process of being completed. :attr bool read_only: (optional) If `true`, the environment contains read-only - collections that are maintained by IBM. + collections that are maintained by IBM. :attr str size: (optional) Current size of the environment. - :attr str requested_size: (optional) The new size requested for this environment. Only - returned when the environment *status* is `resizing`. - *Note:* Querying and indexing can still be performed during an environment upsize. - :attr IndexCapacity index_capacity: (optional) Details about the resource usage and - capacity of the environment. + :attr str requested_size: (optional) The new size requested for this + environment. Only returned when the environment *status* is `resizing`. + *Note:* Querying and indexing can still be performed during an environment + upsize. + :attr IndexCapacity index_capacity: (optional) Details about the resource usage + and capacity of the environment. :attr SearchStatus search_status: (optional) Information about the Continuous - Relevancy Training for this environment. + Relevancy Training for this environment. """ def __init__(self, + *, environment_id=None, name=None, description=None, @@ -5859,26 +6227,28 @@ def __init__(self, """ Initialize a Environment object. - :param str environment_id: (optional) Unique identifier for the environment. + :param str environment_id: (optional) Unique identifier for the + environment. :param str name: (optional) Name that identifies the environment. :param str description: (optional) Description of the environment. - :param datetime created: (optional) Creation date of the environment, in the - format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :param datetime updated: (optional) Date of most recent environment update, in the - format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :param str status: (optional) Current status of the environment. `resizing` is - displayed when a request to increase the environment size has been made, but is - still in the process of being completed. - :param bool read_only: (optional) If `true`, the environment contains read-only - collections that are maintained by IBM. + :param datetime created: (optional) Creation date of the environment, in + the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. + :param datetime updated: (optional) Date of most recent environment update, + in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. + :param str status: (optional) Current status of the environment. `resizing` + is displayed when a request to increase the environment size has been made, + but is still in the process of being completed. + :param bool read_only: (optional) If `true`, the environment contains + read-only collections that are maintained by IBM. :param str size: (optional) Current size of the environment. - :param str requested_size: (optional) The new size requested for this environment. - Only returned when the environment *status* is `resizing`. - *Note:* Querying and indexing can still be performed during an environment upsize. - :param IndexCapacity index_capacity: (optional) Details about the resource usage - and capacity of the environment. - :param SearchStatus search_status: (optional) Information about the Continuous - Relevancy Training for this environment. + :param str requested_size: (optional) The new size requested for this + environment. Only returned when the environment *status* is `resizing`. + *Note:* Querying and indexing can still be performed during an environment + upsize. + :param IndexCapacity index_capacity: (optional) Details about the resource + usage and capacity of the environment. + :param SearchStatus search_status: (optional) Information about the + Continuous Relevancy Training for this environment. """ self.environment_id = environment_id self.name = name @@ -5973,6 +6343,32 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + Current status of the environment. `resizing` is displayed when a request to + increase the environment size has been made, but is still in the process of being + completed. + """ + ACTIVE = "active" + PENDING = "pending" + MAINTENANCE = "maintenance" + RESIZING = "resizing" + + class SizeEnum(Enum): + """ + Current size of the environment. + """ + LT = "LT" + XS = "XS" + S = "S" + MS = "MS" + M = "M" + ML = "ML" + L = "L" + XL = "XL" + XXL = "XXL" + XXXL = "XXXL" + class EnvironmentDocuments(object): """ @@ -5980,16 +6376,17 @@ class EnvironmentDocuments(object): :attr int indexed: (optional) Number of documents indexed for the environment. :attr int maximum_allowed: (optional) Total number of documents allowed in the - environment's capacity. + environment's capacity. """ - def __init__(self, indexed=None, maximum_allowed=None): + def __init__(self, *, indexed=None, maximum_allowed=None): """ Initialize a EnvironmentDocuments object. - :param int indexed: (optional) Number of documents indexed for the environment. - :param int maximum_allowed: (optional) Total number of documents allowed in the - environment's capacity. + :param int indexed: (optional) Number of documents indexed for the + environment. + :param int maximum_allowed: (optional) Total number of documents allowed in + the environment's capacity. """ self.indexed = indexed self.maximum_allowed = maximum_allowed @@ -6039,20 +6436,21 @@ class EventData(object): """ Query event data object. - :attr str environment_id: The **environment_id** associated with the query that the - event is associated with. - :attr str session_token: The session token that was returned as part of the query - results that this event is associated with. - :attr datetime client_timestamp: (optional) The optional timestamp for the event that - was created. If not provided, the time that the event was created in the log was used. - :attr int display_rank: (optional) The rank of the result item which the event is - associated with. - :attr str collection_id: The **collection_id** of the document that this event is - associated with. + :attr str environment_id: The **environment_id** associated with the query that + the event is associated with. + :attr str session_token: The session token that was returned as part of the + query results that this event is associated with. + :attr datetime client_timestamp: (optional) The optional timestamp for the event + that was created. If not provided, the time that the event was created in the + log was used. + :attr int display_rank: (optional) The rank of the result item which the event + is associated with. + :attr str collection_id: The **collection_id** of the document that this event + is associated with. :attr str document_id: The **document_id** of the document that this event is - associated with. - :attr str query_id: (optional) The query identifier stored in the log. The query and - any events associated with that query are stored with the same **query_id**. + associated with. + :attr str query_id: (optional) The query identifier stored in the log. The query + and any events associated with that query are stored with the same **query_id**. """ def __init__(self, @@ -6060,27 +6458,29 @@ def __init__(self, session_token, collection_id, document_id, + *, client_timestamp=None, display_rank=None, query_id=None): """ Initialize a EventData object. - :param str environment_id: The **environment_id** associated with the query that - the event is associated with. - :param str session_token: The session token that was returned as part of the query - results that this event is associated with. - :param str collection_id: The **collection_id** of the document that this event is - associated with. - :param str document_id: The **document_id** of the document that this event is - associated with. - :param datetime client_timestamp: (optional) The optional timestamp for the event - that was created. If not provided, the time that the event was created in the log - was used. - :param int display_rank: (optional) The rank of the result item which the event is - associated with. - :param str query_id: (optional) The query identifier stored in the log. The query - and any events associated with that query are stored with the same **query_id**. + :param str environment_id: The **environment_id** associated with the query + that the event is associated with. + :param str session_token: The session token that was returned as part of + the query results that this event is associated with. + :param str collection_id: The **collection_id** of the document that this + event is associated with. + :param str document_id: The **document_id** of the document that this event + is associated with. + :param datetime client_timestamp: (optional) The optional timestamp for the + event that was created. If not provided, the time that the event was + created in the log was used. + :param int display_rank: (optional) The rank of the result item which the + event is associated with. + :param str query_id: (optional) The query identifier stored in the log. The + query and any events associated with that query are stored with the same + **query_id**. """ self.environment_id = environment_id self.session_token = session_token @@ -6178,21 +6578,23 @@ class Expansion(object): example, you could have expansions for the word `hot` in one object, and expansions for the word `cold` in another. - :attr list[str] input_terms: (optional) A list of terms that will be expanded for this - expansion. If specified, only the items in this list are expanded. - :attr list[str] expanded_terms: A list of terms that this expansion will be expanded - to. If specified without **input_terms**, it also functions as the input term list. + :attr list[str] input_terms: (optional) A list of terms that will be expanded + for this expansion. If specified, only the items in this list are expanded. + :attr list[str] expanded_terms: A list of terms that this expansion will be + expanded to. If specified without **input_terms**, it also functions as the + input term list. """ - def __init__(self, expanded_terms, input_terms=None): + def __init__(self, expanded_terms, *, input_terms=None): """ Initialize a Expansion object. - :param list[str] expanded_terms: A list of terms that this expansion will be - expanded to. If specified without **input_terms**, it also functions as the input - term list. - :param list[str] input_terms: (optional) A list of terms that will be expanded for - this expansion. If specified, only the items in this list are expanded. + :param list[str] expanded_terms: A list of terms that this expansion will + be expanded to. If specified without **input_terms**, it also functions as + the input term list. + :param list[str] input_terms: (optional) A list of terms that will be + expanded for this expansion. If specified, only the items in this list are + expanded. """ self.input_terms = input_terms self.expanded_terms = expanded_terms @@ -6246,17 +6648,18 @@ class Expansions(object): The query expansion definitions for the specified collection. :attr list[Expansion] expansions: An array of query expansion definitions. - Each object in the **expansions** array represents a term or set of terms that will - be expanded into other terms. Each expansion object can be configured as bidirectional - or unidirectional. Bidirectional means that all terms are expanded to all other terms - in the object. Unidirectional means that a set list of terms can be expanded into a - second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. When found - in a query, all items in the **expanded_terms** array are then expanded to the other - items in the same array. - To create a uni-directional expansion, specify both an array of **input_terms** and - an array of **expanded_terms**. When items in the **input_terms** array are present in - a query, they are expanded using the items listed in the **expanded_terms** array. + Each object in the **expansions** array represents a term or set of terms that + will be expanded into other terms. Each expansion object can be configured as + bidirectional or unidirectional. Bidirectional means that all terms are expanded + to all other terms in the object. Unidirectional means that a set list of terms + can be expanded into a second list of terms. + To create a bi-directional expansion specify an **expanded_terms** array. When + found in a query, all items in the **expanded_terms** array are then expanded to + the other items in the same array. + To create a uni-directional expansion, specify both an array of **input_terms** + and an array of **expanded_terms**. When items in the **input_terms** array are + present in a query, they are expanded using the items listed in the + **expanded_terms** array. """ def __init__(self, expansions): @@ -6264,18 +6667,18 @@ def __init__(self, expansions): Initialize a Expansions object. :param list[Expansion] expansions: An array of query expansion definitions. - Each object in the **expansions** array represents a term or set of terms that - will be expanded into other terms. Each expansion object can be configured as - bidirectional or unidirectional. Bidirectional means that all terms are expanded - to all other terms in the object. Unidirectional means that a set list of terms - can be expanded into a second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. When - found in a query, all items in the **expanded_terms** array are then expanded to - the other items in the same array. - To create a uni-directional expansion, specify both an array of **input_terms** - and an array of **expanded_terms**. When items in the **input_terms** array are - present in a query, they are expanded using the items listed in the - **expanded_terms** array. + Each object in the **expansions** array represents a term or set of terms + that will be expanded into other terms. Each expansion object can be + configured as bidirectional or unidirectional. Bidirectional means that all + terms are expanded to all other terms in the object. Unidirectional means + that a set list of terms can be expanded into a second list of terms. + To create a bi-directional expansion specify an **expanded_terms** array. + When found in a query, all items in the **expanded_terms** array are then + expanded to the other items in the same array. + To create a uni-directional expansion, specify both an array of + **input_terms** and an array of **expanded_terms**. When items in the + **input_terms** array are present in a query, they are expanded using the + items listed in the **expanded_terms** array. """ self.expansions = expansions @@ -6325,43 +6728,43 @@ class Field(object): """ Field. - :attr str field_name: (optional) The name of the field. - :attr str field_type: (optional) The type of the field. + :attr str field: (optional) The name of the field. + :attr str type: (optional) The type of the field. """ - def __init__(self, field_name=None, field_type=None): + def __init__(self, *, field=None, type=None): """ Initialize a Field object. - :param str field_name: (optional) The name of the field. - :param str field_type: (optional) The type of the field. + :param str field: (optional) The name of the field. + :param str type: (optional) The type of the field. """ - self.field_name = field_name - self.field_type = field_type + self.field = field + self.type = type @classmethod def _from_dict(cls, _dict): """Initialize a Field object from a json dictionary.""" args = {} - validKeys = ['field_name', 'field', 'field_type', 'type'] + validKeys = ['field', 'type'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: raise ValueError( 'Unrecognized keys detected in dictionary for class Field: ' + ', '.join(badKeys)) - if 'field' in _dict or 'field_name' in _dict: - args['field_name'] = _dict.get('field') or _dict.get('field_name') - if 'type' in _dict or 'field_type' in _dict: - args['field_type'] = _dict.get('type') or _dict.get('field_type') + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'type' in _dict: + args['type'] = _dict.get('type') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'field_name') and self.field_name is not None: - _dict['field'] = self.field_name - if hasattr(self, 'field_type') and self.field_type is not None: - _dict['type'] = self.field_type + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def __str__(self): @@ -6378,6 +6781,22 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The type of the field. + """ + NESTED = "nested" + STRING = "string" + DATE = "date" + LONG = "long" + INTEGER = "integer" + SHORT = "short" + BYTE = "byte" + DOUBLE = "double" + FLOAT = "float" + BOOLEAN = "boolean" + BINARY = "binary" + class Filter(object): """ @@ -6387,6 +6806,7 @@ class Filter(object): """ def __init__(self, + *, type=None, results=None, matching_results=None, @@ -6395,12 +6815,13 @@ def __init__(self, """ Initialize a Filter object. - :param str type: (optional) The type of aggregation command used. For example: - term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation results. + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param list[AggregationResult] results: (optional) Array of aggregation + results. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations returned by - Discovery. + :param list[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. :param str match: (optional) The match the aggregated results queried for. """ self.match = match @@ -6445,8 +6866,8 @@ class FontSetting(object): """ FontSetting. - :attr int level: (optional) The HTML heading level that any content with the matching - font is converted to. + :attr int level: (optional) The HTML heading level that any content with the + matching font is converted to. :attr int min_size: (optional) The minimum size of the font to match. :attr int max_size: (optional) The maximum size of the font to match. :attr bool bold: (optional) When `true`, the font is matched if it is bold. @@ -6455,6 +6876,7 @@ class FontSetting(object): """ def __init__(self, + *, level=None, min_size=None, max_size=None, @@ -6464,12 +6886,14 @@ def __init__(self, """ Initialize a FontSetting object. - :param int level: (optional) The HTML heading level that any content with the - matching font is converted to. + :param int level: (optional) The HTML heading level that any content with + the matching font is converted to. :param int min_size: (optional) The minimum size of the font to match. :param int max_size: (optional) The maximum size of the font to match. - :param bool bold: (optional) When `true`, the font is matched if it is bold. - :param bool italic: (optional) When `true`, the font is matched if it is italic. + :param bool bold: (optional) When `true`, the font is matched if it is + bold. + :param bool italic: (optional) When `true`, the font is matched if it is + italic. :param str name: (optional) The name of the font. """ self.level = level @@ -6541,16 +6965,17 @@ class Gateway(object): :attr str gateway_id: (optional) The gateway ID of the gateway. :attr str name: (optional) The user defined name of the gateway. - :attr str status: (optional) The current status of the gateway. `connected` means the - gateway is connected to the remotly installed gateway. `idle` means this gateway is - not currently in use. - :attr str token: (optional) The generated **token** for this gateway. The value of - this field is used when configuring the remotly installed gateway. - :attr str token_id: (optional) The generated **token_id** for this gateway. The value - of this field is used when configuring the remotly installed gateway. + :attr str status: (optional) The current status of the gateway. `connected` + means the gateway is connected to the remotly installed gateway. `idle` means + this gateway is not currently in use. + :attr str token: (optional) The generated **token** for this gateway. The value + of this field is used when configuring the remotly installed gateway. + :attr str token_id: (optional) The generated **token_id** for this gateway. The + value of this field is used when configuring the remotly installed gateway. """ def __init__(self, + *, gateway_id=None, name=None, status=None, @@ -6561,13 +6986,14 @@ def __init__(self, :param str gateway_id: (optional) The gateway ID of the gateway. :param str name: (optional) The user defined name of the gateway. - :param str status: (optional) The current status of the gateway. `connected` means - the gateway is connected to the remotly installed gateway. `idle` means this - gateway is not currently in use. - :param str token: (optional) The generated **token** for this gateway. The value - of this field is used when configuring the remotly installed gateway. - :param str token_id: (optional) The generated **token_id** for this gateway. The - value of this field is used when configuring the remotly installed gateway. + :param str status: (optional) The current status of the gateway. + `connected` means the gateway is connected to the remotly installed + gateway. `idle` means this gateway is not currently in use. + :param str token: (optional) The generated **token** for this gateway. The + value of this field is used when configuring the remotly installed gateway. + :param str token_id: (optional) The generated **token_id** for this + gateway. The value of this field is used when configuring the remotly + installed gateway. """ self.gateway_id = gateway_id self.name = name @@ -6626,6 +7052,14 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The current status of the gateway. `connected` means the gateway is connected to + the remotly installed gateway. `idle` means this gateway is not currently in use. + """ + CONNECTED = "connected" + IDLE = "idle" + class GatewayDelete(object): """ @@ -6635,7 +7069,7 @@ class GatewayDelete(object): :attr str status: (optional) The status of the request. """ - def __init__(self, gateway_id=None, status=None): + def __init__(self, *, gateway_id=None, status=None): """ Initialize a GatewayDelete object. @@ -6689,14 +7123,16 @@ class GatewayList(object): """ Object containing gateways array. - :attr list[Gateway] gateways: (optional) Array of configured gateway connections. + :attr list[Gateway] gateways: (optional) Array of configured gateway + connections. """ - def __init__(self, gateways=None): + def __init__(self, *, gateways=None): """ Initialize a GatewayList object. - :param list[Gateway] gateways: (optional) Array of configured gateway connections. + :param list[Gateway] gateways: (optional) Array of configured gateway + connections. """ self.gateways = gateways @@ -6743,11 +7179,13 @@ class Histogram(object): Histogram. :attr str field: (optional) The field where the aggregation is located in the - document. - :attr int interval: (optional) Interval of the aggregation. (For 'histogram' type). + document. + :attr int interval: (optional) Interval of the aggregation. (For 'histogram' + type). """ def __init__(self, + *, type=None, results=None, matching_results=None, @@ -6757,16 +7195,17 @@ def __init__(self, """ Initialize a Histogram object. - :param str type: (optional) The type of aggregation command used. For example: - term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation results. + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param list[AggregationResult] results: (optional) Array of aggregation + results. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations returned by - Discovery. - :param str field: (optional) The field where the aggregation is located in the - document. - :param int interval: (optional) Interval of the aggregation. (For 'histogram' - type). + :param list[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. + :param int interval: (optional) Interval of the aggregation. (For + 'histogram' type). """ self.field = field self.interval = interval @@ -6816,18 +7255,19 @@ class HtmlSettings(object): A list of HTML conversion settings. :attr list[str] exclude_tags_completely: (optional) Array of HTML tags that are - excluded completely. - :attr list[str] exclude_tags_keep_content: (optional) Array of HTML tags which are - excluded but still retain content. + excluded completely. + :attr list[str] exclude_tags_keep_content: (optional) Array of HTML tags which + are excluded but still retain content. :attr XPathPatterns keep_content: (optional) :attr XPathPatterns exclude_content: (optional) - :attr list[str] keep_tag_attributes: (optional) An array of HTML tag attributes to - keep in the converted document. - :attr list[str] exclude_tag_attributes: (optional) Array of HTML tag attributes to - exclude. + :attr list[str] keep_tag_attributes: (optional) An array of HTML tag attributes + to keep in the converted document. + :attr list[str] exclude_tag_attributes: (optional) Array of HTML tag attributes + to exclude. """ def __init__(self, + *, exclude_tags_completely=None, exclude_tags_keep_content=None, keep_content=None, @@ -6837,16 +7277,16 @@ def __init__(self, """ Initialize a HtmlSettings object. - :param list[str] exclude_tags_completely: (optional) Array of HTML tags that are - excluded completely. - :param list[str] exclude_tags_keep_content: (optional) Array of HTML tags which - are excluded but still retain content. + :param list[str] exclude_tags_completely: (optional) Array of HTML tags + that are excluded completely. + :param list[str] exclude_tags_keep_content: (optional) Array of HTML tags + which are excluded but still retain content. :param XPathPatterns keep_content: (optional) :param XPathPatterns exclude_content: (optional) - :param list[str] keep_tag_attributes: (optional) An array of HTML tag attributes - to keep in the converted document. - :param list[str] exclude_tag_attributes: (optional) Array of HTML tag attributes - to exclude. + :param list[str] keep_tag_attributes: (optional) An array of HTML tag + attributes to keep in the converted document. + :param list[str] exclude_tag_attributes: (optional) Array of HTML tag + attributes to exclude. """ self.exclude_tags_completely = exclude_tags_completely self.exclude_tags_keep_content = exclude_tags_keep_content @@ -6930,23 +7370,23 @@ class IndexCapacity(object): Details about the resource usage and capacity of the environment. :attr EnvironmentDocuments documents: (optional) Summary of the document usage - statistics for the environment. - :attr DiskUsage disk_usage: (optional) Summary of the disk usage statistics for the - environment. - :attr CollectionUsage collections: (optional) Summary of the collection usage in the - environment. + statistics for the environment. + :attr DiskUsage disk_usage: (optional) Summary of the disk usage statistics for + the environment. + :attr CollectionUsage collections: (optional) Summary of the collection usage in + the environment. """ - def __init__(self, documents=None, disk_usage=None, collections=None): + def __init__(self, *, documents=None, disk_usage=None, collections=None): """ Initialize a IndexCapacity object. - :param EnvironmentDocuments documents: (optional) Summary of the document usage - statistics for the environment. - :param DiskUsage disk_usage: (optional) Summary of the disk usage statistics for - the environment. - :param CollectionUsage collections: (optional) Summary of the collection usage in - the environment. + :param EnvironmentDocuments documents: (optional) Summary of the document + usage statistics for the environment. + :param DiskUsage disk_usage: (optional) Summary of the disk usage + statistics for the environment. + :param CollectionUsage collections: (optional) Summary of the collection + usage in the environment. """ self.documents = documents self.disk_usage = disk_usage @@ -7011,16 +7451,16 @@ class ListCollectionFieldsResponse(object): `v{N}-fullnews-t3-{YEAR}.mappings` (for example, `v5-fullnews-t3-2016.mappings.text.properties.author`). - :attr list[Field] fields: (optional) An array containing information about each field - in the collections. + :attr list[Field] fields: (optional) An array containing information about each + field in the collections. """ - def __init__(self, fields=None): + def __init__(self, *, fields=None): """ Initialize a ListCollectionFieldsResponse object. - :param list[Field] fields: (optional) An array containing information about each - field in the collections. + :param list[Field] fields: (optional) An array containing information about + each field in the collections. """ self.fields = fields @@ -7066,16 +7506,16 @@ class ListCollectionsResponse(object): """ ListCollectionsResponse. - :attr list[Collection] collections: (optional) An array containing information about - each collection in the environment. + :attr list[Collection] collections: (optional) An array containing information + about each collection in the environment. """ - def __init__(self, collections=None): + def __init__(self, *, collections=None): """ Initialize a ListCollectionsResponse object. - :param list[Collection] collections: (optional) An array containing information - about each collection in the environment. + :param list[Collection] collections: (optional) An array containing + information about each collection in the environment. """ self.collections = collections @@ -7121,16 +7561,16 @@ class ListConfigurationsResponse(object): """ ListConfigurationsResponse. - :attr list[Configuration] configurations: (optional) An array of Configurations that - are available for the service instance. + :attr list[Configuration] configurations: (optional) An array of Configurations + that are available for the service instance. """ - def __init__(self, configurations=None): + def __init__(self, *, configurations=None): """ Initialize a ListConfigurationsResponse object. - :param list[Configuration] configurations: (optional) An array of Configurations - that are available for the service instance. + :param list[Configuration] configurations: (optional) An array of + Configurations that are available for the service instance. """ self.configurations = configurations @@ -7179,16 +7619,16 @@ class ListEnvironmentsResponse(object): """ ListEnvironmentsResponse. - :attr list[Environment] environments: (optional) An array of [environments] that are - available for the service instance. + :attr list[Environment] environments: (optional) An array of [environments] that + are available for the service instance. """ - def __init__(self, environments=None): + def __init__(self, *, environments=None): """ Initialize a ListEnvironmentsResponse object. - :param list[Environment] environments: (optional) An array of [environments] that - are available for the service instance. + :param list[Environment] environments: (optional) An array of + [environments] that are available for the service instance. """ self.environments = environments @@ -7235,17 +7675,17 @@ class LogQueryResponse(object): Object containing results that match the requested **logs** query. :attr int matching_results: (optional) Number of matching results. - :attr list[LogQueryResponseResult] results: (optional) Array of log query response - results. + :attr list[LogQueryResponseResult] results: (optional) Array of log query + response results. """ - def __init__(self, matching_results=None, results=None): + def __init__(self, *, matching_results=None, results=None): """ Initialize a LogQueryResponse object. :param int matching_results: (optional) Number of matching results. :param list[LogQueryResponseResult] results: (optional) Array of log query - response results. + response results. """ self.matching_results = matching_results self.results = results @@ -7299,56 +7739,59 @@ class LogQueryResponseResult(object): Individual result object for a **logs** query. Each object represents either a query to a Discovery collection or an event that is associated with a query. - :attr str environment_id: (optional) The environment ID that is associated with this - log entry. - :attr str customer_id: (optional) The **customer_id** label that was specified in the - header of the query or event API call that corresponds to this log entry. + :attr str environment_id: (optional) The environment ID that is associated with + this log entry. + :attr str customer_id: (optional) The **customer_id** label that was specified + in the header of the query or event API call that corresponds to this log entry. :attr str document_type: (optional) The type of log entry returned. - **query** indicates that the log represents the results of a call to the single - collection **query** method. - **event** indicates that the log represents a call to the **events** API. + **query** indicates that the log represents the results of a call to the single + collection **query** method. + **event** indicates that the log represents a call to the **events** API. :attr str natural_language_query: (optional) The value of the - **natural_language_query** query parameter that was used to create these results. Only - returned with logs of type **query**. - **Note:** Other query parameters (such as **filter** or **deduplicate**) might have - been used with this query, but are not recorded. - :attr LogQueryResponseResultDocuments document_results: (optional) Object containing - result information that was returned by the query used to create this log entry. Only - returned with logs of type `query`. - :attr datetime created_timestamp: (optional) Date that the log result was created. - Returned in `YYYY-MM-DDThh:mm:ssZ` format. - :attr datetime client_timestamp: (optional) Date specified by the user when recording - an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only returned with logs of type - **event**. + **natural_language_query** query parameter that was used to create these + results. Only returned with logs of type **query**. + **Note:** Other query parameters (such as **filter** or **deduplicate**) might + have been used with this query, but are not recorded. + :attr LogQueryResponseResultDocuments document_results: (optional) Object + containing result information that was returned by the query used to create this + log entry. Only returned with logs of type `query`. + :attr datetime created_timestamp: (optional) Date that the log result was + created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. + :attr datetime client_timestamp: (optional) Date specified by the user when + recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only returned + with logs of type **event**. :attr str query_id: (optional) Identifier that corresponds to the - **natural_language_query** string used in the original or associated query. All - **event** and **query** log entries that have the same original - **natural_language_query** string also have them same **query_id**. This field can be - used to recall all **event** and **query** log results that have the same original - query (**event** logs do not contain the original **natural_language_query** field). - :attr str session_token: (optional) Unique identifier (within a 24-hour period) that - identifies a single `query` log and any `event` logs that were created for it. - **Note:** If the exact same query is run at the exact same time on different days, the - **session_token** for those queries might be identical. However, the - **created_timestamp** differs. - **Note:** Session tokens are case sensitive. To avoid matching on session tokens that - are identical except for case, use the exact match operator (`::`) when you query for - a specific session token. - :attr str collection_id: (optional) The collection ID of the document associated with - this event. Only returned with logs of type `event`. + **natural_language_query** string used in the original or associated query. All + **event** and **query** log entries that have the same original + **natural_language_query** string also have them same **query_id**. This field + can be used to recall all **event** and **query** log results that have the same + original query (**event** logs do not contain the original + **natural_language_query** field). + :attr str session_token: (optional) Unique identifier (within a 24-hour period) + that identifies a single `query` log and any `event` logs that were created for + it. + **Note:** If the exact same query is run at the exact same time on different + days, the **session_token** for those queries might be identical. However, the + **created_timestamp** differs. + **Note:** Session tokens are case sensitive. To avoid matching on session tokens + that are identical except for case, use the exact match operator (`::`) when you + query for a specific session token. + :attr str collection_id: (optional) The collection ID of the document associated + with this event. Only returned with logs of type `event`. :attr int display_rank: (optional) The original display rank of the document - associated with this event. Only returned with logs of type `event`. - :attr str document_id: (optional) The document ID of the document associated with this - event. Only returned with logs of type `event`. + associated with this event. Only returned with logs of type `event`. + :attr str document_id: (optional) The document ID of the document associated + with this event. Only returned with logs of type `event`. :attr str event_type: (optional) The type of event that this object respresents. - Possible values are - - `query` the log of a query to a collection - - `click` the result of a call to the **events** endpoint. - :attr str result_type: (optional) The type of result that this **event** is associated - with. Only returned with logs of type `event`. + Possible values are + - `query` the log of a query to a collection + - `click` the result of a call to the **events** endpoint. + :attr str result_type: (optional) The type of result that this **event** is + associated with. Only returned with logs of type `event`. """ def __init__(self, + *, environment_id=None, customer_id=None, document_type=None, @@ -7366,55 +7809,57 @@ def __init__(self, """ Initialize a LogQueryResponseResult object. - :param str environment_id: (optional) The environment ID that is associated with - this log entry. - :param str customer_id: (optional) The **customer_id** label that was specified in - the header of the query or event API call that corresponds to this log entry. + :param str environment_id: (optional) The environment ID that is associated + with this log entry. + :param str customer_id: (optional) The **customer_id** label that was + specified in the header of the query or event API call that corresponds to + this log entry. :param str document_type: (optional) The type of log entry returned. - **query** indicates that the log represents the results of a call to the single - collection **query** method. - **event** indicates that the log represents a call to the **events** API. + **query** indicates that the log represents the results of a call to the + single collection **query** method. + **event** indicates that the log represents a call to the **events** API. :param str natural_language_query: (optional) The value of the - **natural_language_query** query parameter that was used to create these results. - Only returned with logs of type **query**. - **Note:** Other query parameters (such as **filter** or **deduplicate**) might - have been used with this query, but are not recorded. + **natural_language_query** query parameter that was used to create these + results. Only returned with logs of type **query**. + **Note:** Other query parameters (such as **filter** or **deduplicate**) + might have been used with this query, but are not recorded. :param LogQueryResponseResultDocuments document_results: (optional) Object - containing result information that was returned by the query used to create this - log entry. Only returned with logs of type `query`. + containing result information that was returned by the query used to create + this log entry. Only returned with logs of type `query`. :param datetime created_timestamp: (optional) Date that the log result was - created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime client_timestamp: (optional) Date specified by the user when - recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only returned with - logs of type **event**. + created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. + :param datetime client_timestamp: (optional) Date specified by the user + when recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only + returned with logs of type **event**. :param str query_id: (optional) Identifier that corresponds to the - **natural_language_query** string used in the original or associated query. All - **event** and **query** log entries that have the same original - **natural_language_query** string also have them same **query_id**. This field can - be used to recall all **event** and **query** log results that have the same - original query (**event** logs do not contain the original - **natural_language_query** field). - :param str session_token: (optional) Unique identifier (within a 24-hour period) - that identifies a single `query` log and any `event` logs that were created for - it. - **Note:** If the exact same query is run at the exact same time on different days, - the **session_token** for those queries might be identical. However, the - **created_timestamp** differs. - **Note:** Session tokens are case sensitive. To avoid matching on session tokens - that are identical except for case, use the exact match operator (`::`) when you - query for a specific session token. - :param str collection_id: (optional) The collection ID of the document associated - with this event. Only returned with logs of type `event`. - :param int display_rank: (optional) The original display rank of the document - associated with this event. Only returned with logs of type `event`. - :param str document_id: (optional) The document ID of the document associated with - this event. Only returned with logs of type `event`. - :param str event_type: (optional) The type of event that this object respresents. - Possible values are - - `query` the log of a query to a collection - - `click` the result of a call to the **events** endpoint. - :param str result_type: (optional) The type of result that this **event** is - associated with. Only returned with logs of type `event`. + **natural_language_query** string used in the original or associated query. + All **event** and **query** log entries that have the same original + **natural_language_query** string also have them same **query_id**. This + field can be used to recall all **event** and **query** log results that + have the same original query (**event** logs do not contain the original + **natural_language_query** field). + :param str session_token: (optional) Unique identifier (within a 24-hour + period) that identifies a single `query` log and any `event` logs that were + created for it. + **Note:** If the exact same query is run at the exact same time on + different days, the **session_token** for those queries might be identical. + However, the **created_timestamp** differs. + **Note:** Session tokens are case sensitive. To avoid matching on session + tokens that are identical except for case, use the exact match operator + (`::`) when you query for a specific session token. + :param str collection_id: (optional) The collection ID of the document + associated with this event. Only returned with logs of type `event`. + :param int display_rank: (optional) The original display rank of the + document associated with this event. Only returned with logs of type + `event`. + :param str document_id: (optional) The document ID of the document + associated with this event. Only returned with logs of type `event`. + :param str event_type: (optional) The type of event that this object + respresents. Possible values are + - `query` the log of a query to a collection + - `click` the result of a call to the **events** endpoint. + :param str result_type: (optional) The type of result that this **event** + is associated with. Only returned with logs of type `event`. """ self.environment_id = environment_id self.customer_id = customer_id @@ -7533,26 +7978,52 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class DocumentTypeEnum(Enum): + """ + The type of log entry returned. + **query** indicates that the log represents the results of a call to the single + collection **query** method. + **event** indicates that the log represents a call to the **events** API. + """ + QUERY = "query" + EVENT = "event" + + class EventTypeEnum(Enum): + """ + The type of event that this object respresents. Possible values are + - `query` the log of a query to a collection + - `click` the result of a call to the **events** endpoint. + """ + CLICK = "click" + QUERY = "query" + + class ResultTypeEnum(Enum): + """ + The type of result that this **event** is associated with. Only returned with logs + of type `event`. + """ + DOCUMENT = "document" + class LogQueryResponseResultDocuments(object): """ Object containing result information that was returned by the query used to create this log entry. Only returned with logs of type `query`. - :attr list[LogQueryResponseResultDocumentsResult] results: (optional) Array of log - query response results. - :attr int count: (optional) The number of results returned in the query associate with - this log. + :attr list[LogQueryResponseResultDocumentsResult] results: (optional) Array of + log query response results. + :attr int count: (optional) The number of results returned in the query + associate with this log. """ - def __init__(self, results=None, count=None): + def __init__(self, *, results=None, count=None): """ Initialize a LogQueryResponseResultDocuments object. - :param list[LogQueryResponseResultDocumentsResult] results: (optional) Array of - log query response results. - :param int count: (optional) The number of results returned in the query associate - with this log. + :param list[LogQueryResponseResultDocumentsResult] results: (optional) + Array of log query response results. + :param int count: (optional) The number of results returned in the query + associate with this log. """ self.results = results self.count = count @@ -7605,19 +8076,20 @@ class LogQueryResponseResultDocumentsResult(object): Each object in the **results** array corresponds to an individual document returned by the original query. - :attr int position: (optional) The result rank of this document. A position of `1` - indicates that it was the first returned result. - :attr str document_id: (optional) The **document_id** of the document that this result - represents. - :attr float score: (optional) The raw score of this result. A higher score indicates a - greater match to the query parameters. - :attr float confidence: (optional) The confidence score of the result's analysis. A - higher score indicating greater confidence. - :attr str collection_id: (optional) The **collection_id** of the document represented - by this result. + :attr int position: (optional) The result rank of this document. A position of + `1` indicates that it was the first returned result. + :attr str document_id: (optional) The **document_id** of the document that this + result represents. + :attr float score: (optional) The raw score of this result. A higher score + indicates a greater match to the query parameters. + :attr float confidence: (optional) The confidence score of the result's + analysis. A higher score indicating greater confidence. + :attr str collection_id: (optional) The **collection_id** of the document + represented by this result. """ def __init__(self, + *, position=None, document_id=None, score=None, @@ -7626,16 +8098,16 @@ def __init__(self, """ Initialize a LogQueryResponseResultDocumentsResult object. - :param int position: (optional) The result rank of this document. A position of - `1` indicates that it was the first returned result. - :param str document_id: (optional) The **document_id** of the document that this - result represents. + :param int position: (optional) The result rank of this document. A + position of `1` indicates that it was the first returned result. + :param str document_id: (optional) The **document_id** of the document that + this result represents. :param float score: (optional) The raw score of this result. A higher score - indicates a greater match to the query parameters. - :param float confidence: (optional) The confidence score of the result's analysis. - A higher score indicating greater confidence. + indicates a greater match to the query parameters. + :param float confidence: (optional) The confidence score of the result's + analysis. A higher score indicating greater confidence. :param str collection_id: (optional) The **collection_id** of the document - represented by this result. + represented by this result. """ self.position = position self.document_id = document_id @@ -7702,23 +8174,23 @@ class MetricAggregation(object): An aggregation analyzing log information for queries and events. :attr str interval: (optional) The measurement interval for this metric. Metric - intervals are always 1 day (`1d`). - :attr str event_type: (optional) The event type associated with this metric result. - This field, when present, will always be `click`. - :attr list[MetricAggregationResult] results: (optional) Array of metric aggregation - query results. + intervals are always 1 day (`1d`). + :attr str event_type: (optional) The event type associated with this metric + result. This field, when present, will always be `click`. + :attr list[MetricAggregationResult] results: (optional) Array of metric + aggregation query results. """ - def __init__(self, interval=None, event_type=None, results=None): + def __init__(self, *, interval=None, event_type=None, results=None): """ Initialize a MetricAggregation object. - :param str interval: (optional) The measurement interval for this metric. Metric - intervals are always 1 day (`1d`). - :param str event_type: (optional) The event type associated with this metric - result. This field, when present, will always be `click`. + :param str interval: (optional) The measurement interval for this metric. + Metric intervals are always 1 day (`1d`). + :param str event_type: (optional) The event type associated with this + metric result. This field, when present, will always be `click`. :param list[MetricAggregationResult] results: (optional) Array of metric - aggregation query results. + aggregation query results. """ self.interval = interval self.event_type = event_type @@ -7775,17 +8247,18 @@ class MetricAggregationResult(object): """ Aggregation result data for the requested metric. - :attr datetime key_as_string: (optional) Date in string form representing the start of - this interval. - :attr int key: (optional) Unix epoch time equivalent of the **key_as_string**, that - represents the start of this interval. + :attr datetime key_as_string: (optional) Date in string form representing the + start of this interval. + :attr int key: (optional) Unix epoch time equivalent of the **key_as_string**, + that represents the start of this interval. :attr int matching_results: (optional) Number of matching results. :attr float event_rate: (optional) The number of queries with associated events - divided by the total number of queries for the interval. Only returned with - **event_rate** metrics. + divided by the total number of queries for the interval. Only returned with + **event_rate** metrics. """ def __init__(self, + *, key_as_string=None, key=None, matching_results=None, @@ -7793,14 +8266,14 @@ def __init__(self, """ Initialize a MetricAggregationResult object. - :param datetime key_as_string: (optional) Date in string form representing the - start of this interval. - :param int key: (optional) Unix epoch time equivalent of the **key_as_string**, - that represents the start of this interval. + :param datetime key_as_string: (optional) Date in string form representing + the start of this interval. + :param int key: (optional) Unix epoch time equivalent of the + **key_as_string**, that represents the start of this interval. :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated events - divided by the total number of queries for the interval. Only returned with - **event_rate** metrics. + :param float event_rate: (optional) The number of queries with associated + events divided by the total number of queries for the interval. Only + returned with **event_rate** metrics. """ self.key_as_string = key_as_string self.key = key @@ -7861,15 +8334,16 @@ class MetricResponse(object): """ The response generated from a call to a **metrics** method. - :attr list[MetricAggregation] aggregations: (optional) Array of metric aggregations. + :attr list[MetricAggregation] aggregations: (optional) Array of metric + aggregations. """ - def __init__(self, aggregations=None): + def __init__(self, *, aggregations=None): """ Initialize a MetricResponse object. :param list[MetricAggregation] aggregations: (optional) Array of metric - aggregations. + aggregations. """ self.aggregations = aggregations @@ -7916,20 +8390,20 @@ class MetricTokenAggregation(object): """ An aggregation analyzing log information for queries and events. - :attr str event_type: (optional) The event type associated with this metric result. - This field, when present, will always be `click`. - :attr list[MetricTokenAggregationResult] results: (optional) Array of results for the - metric token aggregation. + :attr str event_type: (optional) The event type associated with this metric + result. This field, when present, will always be `click`. + :attr list[MetricTokenAggregationResult] results: (optional) Array of results + for the metric token aggregation. """ - def __init__(self, event_type=None, results=None): + def __init__(self, *, event_type=None, results=None): """ Initialize a MetricTokenAggregation object. - :param str event_type: (optional) The event type associated with this metric - result. This field, when present, will always be `click`. - :param list[MetricTokenAggregationResult] results: (optional) Array of results for - the metric token aggregation. + :param str event_type: (optional) The event type associated with this + metric result. This field, when present, will always be `click`. + :param list[MetricTokenAggregationResult] results: (optional) Array of + results for the metric token aggregation. """ self.event_type = event_type self.results = results @@ -7981,24 +8455,24 @@ class MetricTokenAggregationResult(object): """ Aggregation result data for the requested metric. - :attr str key: (optional) The content of the **natural_language_query** parameter used - in the query that this result represents. + :attr str key: (optional) The content of the **natural_language_query** + parameter used in the query that this result represents. :attr int matching_results: (optional) Number of matching results. :attr float event_rate: (optional) The number of queries with associated events - divided by the total number of queries currently stored (queries and events are stored - in the log for 30 days). + divided by the total number of queries currently stored (queries and events are + stored in the log for 30 days). """ - def __init__(self, key=None, matching_results=None, event_rate=None): + def __init__(self, *, key=None, matching_results=None, event_rate=None): """ Initialize a MetricTokenAggregationResult object. - :param str key: (optional) The content of the **natural_language_query** parameter - used in the query that this result represents. + :param str key: (optional) The content of the **natural_language_query** + parameter used in the query that this result represents. :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated events - divided by the total number of queries currently stored (queries and events are - stored in the log for 30 days). + :param float event_rate: (optional) The number of queries with associated + events divided by the total number of queries currently stored (queries and + events are stored in the log for 30 days). """ self.key = key self.matching_results = matching_results @@ -8053,16 +8527,16 @@ class MetricTokenResponse(object): """ The response generated from a call to a **metrics** method that evaluates tokens. - :attr list[MetricTokenAggregation] aggregations: (optional) Array of metric token - aggregations. + :attr list[MetricTokenAggregation] aggregations: (optional) Array of metric + token aggregations. """ - def __init__(self, aggregations=None): + def __init__(self, *, aggregations=None): """ Initialize a MetricTokenResponse object. - :param list[MetricTokenAggregation] aggregations: (optional) Array of metric token - aggregations. + :param list[MetricTokenAggregation] aggregations: (optional) Array of + metric token aggregations. """ self.aggregations = aggregations @@ -8109,10 +8583,12 @@ class Nested(object): """ Nested. - :attr str path: (optional) The area of the results the aggregation was restricted to. + :attr str path: (optional) The area of the results the aggregation was + restricted to. """ def __init__(self, + *, type=None, results=None, matching_results=None, @@ -8121,14 +8597,15 @@ def __init__(self, """ Initialize a Nested object. - :param str type: (optional) The type of aggregation command used. For example: - term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation results. + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param list[AggregationResult] results: (optional) Array of aggregation + results. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations returned by - Discovery. - :param str path: (optional) The area of the results the aggregation was restricted - to. + :param list[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str path: (optional) The area of the results the aggregation was + restricted to. """ self.path = path @@ -8230,16 +8707,16 @@ class NluEnrichmentConcepts(object): """ An object specifiying the concepts enrichment and related parameters. - :attr int limit: (optional) The maximum number of concepts enrichments to extact from - each instance of the specified field. + :attr int limit: (optional) The maximum number of concepts enrichments to extact + from each instance of the specified field. """ - def __init__(self, limit=None): + def __init__(self, *, limit=None): """ Initialize a NluEnrichmentConcepts object. - :param int limit: (optional) The maximum number of concepts enrichments to extact - from each instance of the specified field. + :param int limit: (optional) The maximum number of concepts enrichments to + extact from each instance of the specified field. """ self.limit = limit @@ -8283,20 +8760,20 @@ class NluEnrichmentEmotion(object): """ An object specifying the emotion detection enrichment and related parameters. - :attr bool document: (optional) When `true`, emotion detection is performed on the - entire field. - :attr list[str] targets: (optional) A comma-separated list of target strings that will - have any associated emotions detected. + :attr bool document: (optional) When `true`, emotion detection is performed on + the entire field. + :attr list[str] targets: (optional) A comma-separated list of target strings + that will have any associated emotions detected. """ - def __init__(self, document=None, targets=None): + def __init__(self, *, document=None, targets=None): """ Initialize a NluEnrichmentEmotion object. - :param bool document: (optional) When `true`, emotion detection is performed on - the entire field. - :param list[str] targets: (optional) A comma-separated list of target strings that - will have any associated emotions detected. + :param bool document: (optional) When `true`, emotion detection is + performed on the entire field. + :param list[str] targets: (optional) A comma-separated list of target + strings that will have any associated emotions detected. """ self.document = document self.targets = targets @@ -8345,24 +8822,26 @@ class NluEnrichmentEntities(object): """ An object speficying the Entities enrichment and related parameters. - :attr bool sentiment: (optional) When `true`, sentiment analysis of entities will be - performed on the specified field. - :attr bool emotion: (optional) When `true`, emotion detection of entities will be - performed on the specified field. + :attr bool sentiment: (optional) When `true`, sentiment analysis of entities + will be performed on the specified field. + :attr bool emotion: (optional) When `true`, emotion detection of entities will + be performed on the specified field. :attr int limit: (optional) The maximum number of entities to extract for each - instance of the specified field. - :attr bool mentions: (optional) When `true`, the number of mentions of each identified - entity is recorded. The default is `false`. + instance of the specified field. + :attr bool mentions: (optional) When `true`, the number of mentions of each + identified entity is recorded. The default is `false`. :attr bool mention_types: (optional) When `true`, the types of mentions for each - idetifieid entity is recorded. The default is `false`. - :attr bool sentence_locations: (optional) When `true`, a list of sentence locations - for each instance of each identified entity is recorded. The default is `false`. - :attr str model: (optional) The enrichement model to use with entity extraction. May - be a custom model provided by Watson Knowledge Studio, the public model for use with - Knowledge Graph `en-news`, or the default public model `alchemy`. + idetifieid entity is recorded. The default is `false`. + :attr bool sentence_locations: (optional) When `true`, a list of sentence + locations for each instance of each identified entity is recorded. The default + is `false`. + :attr str model: (optional) The enrichement model to use with entity extraction. + May be a custom model provided by Watson Knowledge Studio, the public model for + use with Knowledge Graph `en-news`, or the default public model `alchemy`. """ def __init__(self, + *, sentiment=None, emotion=None, limit=None, @@ -8373,22 +8852,23 @@ def __init__(self, """ Initialize a NluEnrichmentEntities object. - :param bool sentiment: (optional) When `true`, sentiment analysis of entities will - be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of entities will be - performed on the specified field. - :param int limit: (optional) The maximum number of entities to extract for each - instance of the specified field. - :param bool mentions: (optional) When `true`, the number of mentions of each - identified entity is recorded. The default is `false`. - :param bool mention_types: (optional) When `true`, the types of mentions for each - idetifieid entity is recorded. The default is `false`. + :param bool sentiment: (optional) When `true`, sentiment analysis of + entities will be performed on the specified field. + :param bool emotion: (optional) When `true`, emotion detection of entities + will be performed on the specified field. + :param int limit: (optional) The maximum number of entities to extract for + each instance of the specified field. + :param bool mentions: (optional) When `true`, the number of mentions of + each identified entity is recorded. The default is `false`. + :param bool mention_types: (optional) When `true`, the types of mentions + for each idetifieid entity is recorded. The default is `false`. :param bool sentence_locations: (optional) When `true`, a list of sentence - locations for each instance of each identified entity is recorded. The default is - `false`. - :param str model: (optional) The enrichement model to use with entity extraction. - May be a custom model provided by Watson Knowledge Studio, the public model for - use with Knowledge Graph `en-news`, or the default public model `alchemy`. + locations for each instance of each identified entity is recorded. The + default is `false`. + :param str model: (optional) The enrichement model to use with entity + extraction. May be a custom model provided by Watson Knowledge Studio, the + public model for use with Knowledge Graph `en-news`, or the default public + model `alchemy`. """ self.sentiment = sentiment self.emotion = emotion @@ -8467,25 +8947,26 @@ class NluEnrichmentFeatures(object): """ NluEnrichmentFeatures. - :attr NluEnrichmentKeywords keywords: (optional) An object specifying the Keyword - enrichment and related parameters. - :attr NluEnrichmentEntities entities: (optional) An object speficying the Entities - enrichment and related parameters. - :attr NluEnrichmentSentiment sentiment: (optional) An object specifying the sentiment - extraction enrichment and related parameters. + :attr NluEnrichmentKeywords keywords: (optional) An object specifying the + Keyword enrichment and related parameters. + :attr NluEnrichmentEntities entities: (optional) An object speficying the + Entities enrichment and related parameters. + :attr NluEnrichmentSentiment sentiment: (optional) An object specifying the + sentiment extraction enrichment and related parameters. :attr NluEnrichmentEmotion emotion: (optional) An object specifying the emotion - detection enrichment and related parameters. - :attr NluEnrichmentCategories categories: (optional) An object that indicates the - Categories enrichment will be applied to the specified field. - :attr NluEnrichmentSemanticRoles semantic_roles: (optional) An object specifiying the - semantic roles enrichment and related parameters. - :attr NluEnrichmentRelations relations: (optional) An object specifying the relations - enrichment and related parameters. - :attr NluEnrichmentConcepts concepts: (optional) An object specifiying the concepts - enrichment and related parameters. + detection enrichment and related parameters. + :attr NluEnrichmentCategories categories: (optional) An object that indicates + the Categories enrichment will be applied to the specified field. + :attr NluEnrichmentSemanticRoles semantic_roles: (optional) An object + specifiying the semantic roles enrichment and related parameters. + :attr NluEnrichmentRelations relations: (optional) An object specifying the + relations enrichment and related parameters. + :attr NluEnrichmentConcepts concepts: (optional) An object specifiying the + concepts enrichment and related parameters. """ def __init__(self, + *, keywords=None, entities=None, sentiment=None, @@ -8497,22 +8978,22 @@ def __init__(self, """ Initialize a NluEnrichmentFeatures object. - :param NluEnrichmentKeywords keywords: (optional) An object specifying the Keyword - enrichment and related parameters. + :param NluEnrichmentKeywords keywords: (optional) An object specifying the + Keyword enrichment and related parameters. :param NluEnrichmentEntities entities: (optional) An object speficying the - Entities enrichment and related parameters. - :param NluEnrichmentSentiment sentiment: (optional) An object specifying the - sentiment extraction enrichment and related parameters. - :param NluEnrichmentEmotion emotion: (optional) An object specifying the emotion - detection enrichment and related parameters. - :param NluEnrichmentCategories categories: (optional) An object that indicates the - Categories enrichment will be applied to the specified field. - :param NluEnrichmentSemanticRoles semantic_roles: (optional) An object specifiying - the semantic roles enrichment and related parameters. - :param NluEnrichmentRelations relations: (optional) An object specifying the - relations enrichment and related parameters. + Entities enrichment and related parameters. + :param NluEnrichmentSentiment sentiment: (optional) An object specifying + the sentiment extraction enrichment and related parameters. + :param NluEnrichmentEmotion emotion: (optional) An object specifying the + emotion detection enrichment and related parameters. + :param NluEnrichmentCategories categories: (optional) An object that + indicates the Categories enrichment will be applied to the specified field. + :param NluEnrichmentSemanticRoles semantic_roles: (optional) An object + specifiying the semantic roles enrichment and related parameters. + :param NluEnrichmentRelations relations: (optional) An object specifying + the relations enrichment and related parameters. :param NluEnrichmentConcepts concepts: (optional) An object specifiying the - concepts enrichment and related parameters. + concepts enrichment and related parameters. """ self.keywords = keywords self.entities = entities @@ -8602,24 +9083,24 @@ class NluEnrichmentKeywords(object): """ An object specifying the Keyword enrichment and related parameters. - :attr bool sentiment: (optional) When `true`, sentiment analysis of keywords will be - performed on the specified field. - :attr bool emotion: (optional) When `true`, emotion detection of keywords will be - performed on the specified field. + :attr bool sentiment: (optional) When `true`, sentiment analysis of keywords + will be performed on the specified field. + :attr bool emotion: (optional) When `true`, emotion detection of keywords will + be performed on the specified field. :attr int limit: (optional) The maximum number of keywords to extract for each - instance of the specified field. + instance of the specified field. """ - def __init__(self, sentiment=None, emotion=None, limit=None): + def __init__(self, *, sentiment=None, emotion=None, limit=None): """ Initialize a NluEnrichmentKeywords object. - :param bool sentiment: (optional) When `true`, sentiment analysis of keywords will - be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of keywords will be - performed on the specified field. - :param int limit: (optional) The maximum number of keywords to extract for each - instance of the specified field. + :param bool sentiment: (optional) When `true`, sentiment analysis of + keywords will be performed on the specified field. + :param bool emotion: (optional) When `true`, emotion detection of keywords + will be performed on the specified field. + :param int limit: (optional) The maximum number of keywords to extract for + each instance of the specified field. """ self.sentiment = sentiment self.emotion = emotion @@ -8673,20 +9154,21 @@ class NluEnrichmentRelations(object): """ An object specifying the relations enrichment and related parameters. - :attr str model: (optional) *For use with `natural_language_understanding` enrichments - only.* The enrichement model to use with relationship extraction. May be a custom - model provided by Watson Knowledge Studio, the public model for use with Knowledge - Graph `en-news`, the default is`en-news`. + :attr str model: (optional) *For use with `natural_language_understanding` + enrichments only.* The enrichement model to use with relationship extraction. + May be a custom model provided by Watson Knowledge Studio, the public model for + use with Knowledge Graph `en-news`, the default is`en-news`. """ - def __init__(self, model=None): + def __init__(self, *, model=None): """ Initialize a NluEnrichmentRelations object. :param str model: (optional) *For use with `natural_language_understanding` - enrichments only.* The enrichement model to use with relationship extraction. May - be a custom model provided by Watson Knowledge Studio, the public model for use - with Knowledge Graph `en-news`, the default is`en-news`. + enrichments only.* The enrichement model to use with relationship + extraction. May be a custom model provided by Watson Knowledge Studio, the + public model for use with Knowledge Graph `en-news`, the default + is`en-news`. """ self.model = model @@ -8731,23 +9213,23 @@ class NluEnrichmentSemanticRoles(object): An object specifiying the semantic roles enrichment and related parameters. :attr bool entities: (optional) When `true`, entities are extracted from the - identified sentence parts. + identified sentence parts. :attr bool keywords: (optional) When `true`, keywords are extracted from the - identified sentence parts. - :attr int limit: (optional) The maximum number of semantic roles enrichments to extact - from each instance of the specified field. + identified sentence parts. + :attr int limit: (optional) The maximum number of semantic roles enrichments to + extact from each instance of the specified field. """ - def __init__(self, entities=None, keywords=None, limit=None): + def __init__(self, *, entities=None, keywords=None, limit=None): """ Initialize a NluEnrichmentSemanticRoles object. - :param bool entities: (optional) When `true`, entities are extracted from the - identified sentence parts. - :param bool keywords: (optional) When `true`, keywords are extracted from the - identified sentence parts. - :param int limit: (optional) The maximum number of semantic roles enrichments to - extact from each instance of the specified field. + :param bool entities: (optional) When `true`, entities are extracted from + the identified sentence parts. + :param bool keywords: (optional) When `true`, keywords are extracted from + the identified sentence parts. + :param int limit: (optional) The maximum number of semantic roles + enrichments to extact from each instance of the specified field. """ self.entities = entities self.keywords = keywords @@ -8801,20 +9283,20 @@ class NluEnrichmentSentiment(object): """ An object specifying the sentiment extraction enrichment and related parameters. - :attr bool document: (optional) When `true`, sentiment analysis is performed on the - entire field. - :attr list[str] targets: (optional) A comma-separated list of target strings that will - have any associated sentiment analyzed. + :attr bool document: (optional) When `true`, sentiment analysis is performed on + the entire field. + :attr list[str] targets: (optional) A comma-separated list of target strings + that will have any associated sentiment analyzed. """ - def __init__(self, document=None, targets=None): + def __init__(self, *, document=None, targets=None): """ Initialize a NluEnrichmentSentiment object. - :param bool document: (optional) When `true`, sentiment analysis is performed on - the entire field. - :param list[str] targets: (optional) A comma-separated list of target strings that - will have any associated sentiment analyzed. + :param bool document: (optional) When `true`, sentiment analysis is + performed on the entire field. + :param list[str] targets: (optional) A comma-separated list of target + strings that will have any associated sentiment analyzed. """ self.document = document self.targets = targets @@ -8864,65 +9346,72 @@ class NormalizationOperation(object): NormalizationOperation. :attr str operation: (optional) Identifies what type of operation to perform. - **copy** - Copies the value of the **source_field** to the **destination_field** - field. If the **destination_field** already exists, then the value of the - **source_field** overwrites the original value of the **destination_field**. - **move** - Renames (moves) the **source_field** to the **destination_field**. If the - **destination_field** already exists, then the value of the **source_field** - overwrites the original value of the **destination_field**. Rename is identical to - copy, except that the **source_field** is removed after the value has been copied to - the **destination_field** (it is the same as a _copy_ followed by a _remove_). - **merge** - Merges the value of the **source_field** with the value of the - **destination_field**. The **destination_field** is converted into an array if it is - not already an array, and the value of the **source_field** is appended to the array. - This operation removes the **source_field** after the merge. If the **source_field** - does not exist in the current document, then the **destination_field** is still - converted into an array (if it is not an array already). This conversion ensures the - type for **destination_field** is consistent across all documents. - **remove** - Deletes the **source_field** field. The **destination_field** is ignored - for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the ingested - document. **source_field** and **destination_field** are ignored by this operation - because _remove_nulls_ operates on the entire ingested document. Typically, - **remove_nulls** is invoked as the last normalization operation (if it is invoked at - all, it can be time-expensive). + **copy** - Copies the value of the **source_field** to the **destination_field** + field. If the **destination_field** already exists, then the value of the + **source_field** overwrites the original value of the **destination_field**. + **move** - Renames (moves) the **source_field** to the **destination_field**. If + the **destination_field** already exists, then the value of the **source_field** + overwrites the original value of the **destination_field**. Rename is identical + to copy, except that the **source_field** is removed after the value has been + copied to the **destination_field** (it is the same as a _copy_ followed by a + _remove_). + **merge** - Merges the value of the **source_field** with the value of the + **destination_field**. The **destination_field** is converted into an array if + it is not already an array, and the value of the **source_field** is appended to + the array. This operation removes the **source_field** after the merge. If the + **source_field** does not exist in the current document, then the + **destination_field** is still converted into an array (if it is not an array + already). This conversion ensures the type for **destination_field** is + consistent across all documents. + **remove** - Deletes the **source_field** field. The **destination_field** is + ignored for this operation. + **remove_nulls** - Removes all nested null (blank) field values from the + ingested document. **source_field** and **destination_field** are ignored by + this operation because _remove_nulls_ operates on the entire ingested document. + Typically, **remove_nulls** is invoked as the last normalization operation (if + it is invoked at all, it can be time-expensive). :attr str source_field: (optional) The source field for the operation. :attr str destination_field: (optional) The destination field for the operation. """ def __init__(self, + *, operation=None, source_field=None, destination_field=None): """ Initialize a NormalizationOperation object. - :param str operation: (optional) Identifies what type of operation to perform. - **copy** - Copies the value of the **source_field** to the **destination_field** - field. If the **destination_field** already exists, then the value of the - **source_field** overwrites the original value of the **destination_field**. - **move** - Renames (moves) the **source_field** to the **destination_field**. If - the **destination_field** already exists, then the value of the **source_field** - overwrites the original value of the **destination_field**. Rename is identical to - copy, except that the **source_field** is removed after the value has been copied - to the **destination_field** (it is the same as a _copy_ followed by a _remove_). - **merge** - Merges the value of the **source_field** with the value of the - **destination_field**. The **destination_field** is converted into an array if it - is not already an array, and the value of the **source_field** is appended to the - array. This operation removes the **source_field** after the merge. If the - **source_field** does not exist in the current document, then the - **destination_field** is still converted into an array (if it is not an array - already). This conversion ensures the type for **destination_field** is consistent - across all documents. - **remove** - Deletes the **source_field** field. The **destination_field** is - ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the ingested - document. **source_field** and **destination_field** are ignored by this operation - because _remove_nulls_ operates on the entire ingested document. Typically, - **remove_nulls** is invoked as the last normalization operation (if it is invoked - at all, it can be time-expensive). + :param str operation: (optional) Identifies what type of operation to + perform. + **copy** - Copies the value of the **source_field** to the + **destination_field** field. If the **destination_field** already exists, + then the value of the **source_field** overwrites the original value of the + **destination_field**. + **move** - Renames (moves) the **source_field** to the + **destination_field**. If the **destination_field** already exists, then + the value of the **source_field** overwrites the original value of the + **destination_field**. Rename is identical to copy, except that the + **source_field** is removed after the value has been copied to the + **destination_field** (it is the same as a _copy_ followed by a _remove_). + **merge** - Merges the value of the **source_field** with the value of the + **destination_field**. The **destination_field** is converted into an array + if it is not already an array, and the value of the **source_field** is + appended to the array. This operation removes the **source_field** after + the merge. If the **source_field** does not exist in the current document, + then the **destination_field** is still converted into an array (if it is + not an array already). This conversion ensures the type for + **destination_field** is consistent across all documents. + **remove** - Deletes the **source_field** field. The **destination_field** + is ignored for this operation. + **remove_nulls** - Removes all nested null (blank) field values from the + ingested document. **source_field** and **destination_field** are ignored + by this operation because _remove_nulls_ operates on the entire ingested + document. Typically, **remove_nulls** is invoked as the last normalization + operation (if it is invoked at all, it can be time-expensive). :param str source_field: (optional) The source field for the operation. - :param str destination_field: (optional) The destination field for the operation. + :param str destination_field: (optional) The destination field for the + operation. """ self.operation = operation self.source_field = source_field @@ -8972,38 +9461,73 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class OperationEnum(Enum): + """ + Identifies what type of operation to perform. + **copy** - Copies the value of the **source_field** to the **destination_field** + field. If the **destination_field** already exists, then the value of the + **source_field** overwrites the original value of the **destination_field**. + **move** - Renames (moves) the **source_field** to the **destination_field**. If + the **destination_field** already exists, then the value of the **source_field** + overwrites the original value of the **destination_field**. Rename is identical to + copy, except that the **source_field** is removed after the value has been copied + to the **destination_field** (it is the same as a _copy_ followed by a _remove_). + **merge** - Merges the value of the **source_field** with the value of the + **destination_field**. The **destination_field** is converted into an array if it + is not already an array, and the value of the **source_field** is appended to the + array. This operation removes the **source_field** after the merge. If the + **source_field** does not exist in the current document, then the + **destination_field** is still converted into an array (if it is not an array + already). This conversion ensures the type for **destination_field** is consistent + across all documents. + **remove** - Deletes the **source_field** field. The **destination_field** is + ignored for this operation. + **remove_nulls** - Removes all nested null (blank) field values from the ingested + document. **source_field** and **destination_field** are ignored by this operation + because _remove_nulls_ operates on the entire ingested document. Typically, + **remove_nulls** is invoked as the last normalization operation (if it is invoked + at all, it can be time-expensive). + """ + COPY = "copy" + MOVE = "move" + MERGE = "merge" + REMOVE = "remove" + REMOVE_NULLS = "remove_nulls" + class Notice(object): """ A notice produced for the collection. - :attr str notice_id: (optional) Identifies the notice. Many notices might have the - same ID. This field exists so that user applications can programmatically identify a - notice and take automatic corrective action. Typical notice IDs include: - `index_failed`, `index_failed_too_many_requests`, `index_failed_incompatible_field`, - `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, - `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, - `smart_document_understanding_failed_incompatible_field`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_warning`, - `smart_document_understanding_page_error`, - `smart_document_understanding_page_warning`. **Note:** This is not a complete list, - other values might be returned. - :attr datetime created: (optional) The creation date of the collection in the format - yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :attr str notice_id: (optional) Identifies the notice. Many notices might have + the same ID. This field exists so that user applications can programmatically + identify a notice and take automatic corrective action. Typical notice IDs + include: `index_failed`, `index_failed_too_many_requests`, + `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, + `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, + `missing_model`, `unsupported_model`, + `smart_document_understanding_failed_incompatible_field`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_warning`, + `smart_document_understanding_page_error`, + `smart_document_understanding_page_warning`. **Note:** This is not a complete + list, other values might be returned. + :attr datetime created: (optional) The creation date of the collection in the + format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :attr str document_id: (optional) Unique identifier of the document. :attr str query_id: (optional) Unique identifier of the query used for relevance - training. + training. :attr str severity: (optional) Severity level of the notice. - :attr str step: (optional) Ingestion or training step in which the notice occurred. - Typical step values include: `classify_elements`, `smartDocumentUnderstanding`, - `ingestion`, `indexing`, `convert`. **Note:** This is not a complete list, other - values might be returned. + :attr str step: (optional) Ingestion or training step in which the notice + occurred. Typical step values include: `classify_elements`, + `smartDocumentUnderstanding`, `ingestion`, `indexing`, `convert`. **Note:** This + is not a complete list, other values might be returned. :attr str description: (optional) The description of the notice. """ def __init__(self, + *, notice_id=None, created=None, document_id=None, @@ -9014,30 +9538,30 @@ def __init__(self, """ Initialize a Notice object. - :param str notice_id: (optional) Identifies the notice. Many notices might have - the same ID. This field exists so that user applications can programmatically - identify a notice and take automatic corrective action. Typical notice IDs - include: `index_failed`, `index_failed_too_many_requests`, - `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, - `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, - `missing_model`, `unsupported_model`, - `smart_document_understanding_failed_incompatible_field`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_warning`, - `smart_document_understanding_page_error`, - `smart_document_understanding_page_warning`. **Note:** This is not a complete - list, other values might be returned. - :param datetime created: (optional) The creation date of the collection in the - format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :param str notice_id: (optional) Identifies the notice. Many notices might + have the same ID. This field exists so that user applications can + programmatically identify a notice and take automatic corrective action. + Typical notice IDs include: `index_failed`, + `index_failed_too_many_requests`, `index_failed_incompatible_field`, + `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, + `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, + `smart_document_understanding_failed_incompatible_field`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_warning`, + `smart_document_understanding_page_error`, + `smart_document_understanding_page_warning`. **Note:** This is not a + complete list, other values might be returned. + :param datetime created: (optional) The creation date of the collection in + the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :param str document_id: (optional) Unique identifier of the document. - :param str query_id: (optional) Unique identifier of the query used for relevance - training. + :param str query_id: (optional) Unique identifier of the query used for + relevance training. :param str severity: (optional) Severity level of the notice. :param str step: (optional) Ingestion or training step in which the notice - occurred. Typical step values include: `classify_elements`, - `smartDocumentUnderstanding`, `ingestion`, `indexing`, `convert`. **Note:** This - is not a complete list, other values might be returned. + occurred. Typical step values include: `classify_elements`, + `smartDocumentUnderstanding`, `ingestion`, `indexing`, `convert`. **Note:** + This is not a complete list, other values might be returned. :param str description: (optional) The description of the notice. """ self.notice_id = notice_id @@ -9110,6 +9634,13 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class SeverityEnum(Enum): + """ + Severity level of the notice. + """ + WARNING = "warning" + ERROR = "error" + class PdfHeadingDetection(object): """ @@ -9118,7 +9649,7 @@ class PdfHeadingDetection(object): :attr list[FontSetting] fonts: (optional) """ - def __init__(self, fonts=None): + def __init__(self, *, fonts=None): """ Initialize a PdfHeadingDetection object. @@ -9171,7 +9702,7 @@ class PdfSettings(object): :attr PdfHeadingDetection heading: (optional) """ - def __init__(self, heading=None): + def __init__(self, *, heading=None): """ Initialize a PdfSettings object. @@ -9220,15 +9751,16 @@ class QueryAggregation(object): """ An aggregation produced by Discovery to analyze the input provided. - :attr str type: (optional) The type of aggregation command used. For example: term, - filter, max, min, etc. + :attr str type: (optional) The type of aggregation command used. For example: + term, filter, max, min, etc. :attr list[AggregationResult] results: (optional) Array of aggregation results. :attr int matching_results: (optional) Number of matching results. :attr list[QueryAggregation] aggregations: (optional) Aggregations returned by - Discovery. + Discovery. """ def __init__(self, + *, type=None, results=None, matching_results=None, @@ -9236,12 +9768,13 @@ def __init__(self, """ Initialize a QueryAggregation object. - :param str type: (optional) The type of aggregation command used. For example: - term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation results. + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param list[AggregationResult] results: (optional) Array of aggregation + results. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations returned by - Discovery. + :param list[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. """ self.type = type self.results = results @@ -9308,19 +9841,20 @@ class QueryEntitiesContext(object): association. For example, if you wanted to query the city of London in England your query would look for `London` with the context of `England`. - :attr str text: (optional) Entity text to provide context for the queried entity and - rank based on that association. For example, if you wanted to query the city of London - in England your query would look for `London` with the context of `England`. + :attr str text: (optional) Entity text to provide context for the queried entity + and rank based on that association. For example, if you wanted to query the city + of London in England your query would look for `London` with the context of + `England`. """ - def __init__(self, text=None): + def __init__(self, *, text=None): """ Initialize a QueryEntitiesContext object. - :param str text: (optional) Entity text to provide context for the queried entity - and rank based on that association. For example, if you wanted to query the city - of London in England your query would look for `London` with the context of - `England`. + :param str text: (optional) Entity text to provide context for the queried + entity and rank based on that association. For example, if you wanted to + query the city of London in England your query would look for `London` with + the context of `England`. """ self.text = text @@ -9368,7 +9902,7 @@ class QueryEntitiesEntity(object): :attr str type: (optional) The type of the specified entity. """ - def __init__(self, text=None, type=None): + def __init__(self, *, text=None, type=None): """ Initialize a QueryEntitiesEntity object. @@ -9422,16 +9956,16 @@ class QueryEntitiesResponse(object): """ An object that contains an array of entities resulting from the query. - :attr list[QueryEntitiesResponseItem] entities: (optional) Array of entities that - results from the query. + :attr list[QueryEntitiesResponseItem] entities: (optional) Array of entities + that results from the query. """ - def __init__(self, entities=None): + def __init__(self, *, entities=None): """ Initialize a QueryEntitiesResponse object. - :param list[QueryEntitiesResponseItem] entities: (optional) Array of entities that - results from the query. + :param list[QueryEntitiesResponseItem] entities: (optional) Array of + entities that results from the query. """ self.entities = entities @@ -9480,18 +10014,18 @@ class QueryEntitiesResponseItem(object): :attr str text: (optional) Entity text content. :attr str type: (optional) The type of the result entity. - :attr list[QueryEvidence] evidence: (optional) List of different evidentiary items to - support the result. + :attr list[QueryEvidence] evidence: (optional) List of different evidentiary + items to support the result. """ - def __init__(self, text=None, type=None, evidence=None): + def __init__(self, *, text=None, type=None, evidence=None): """ Initialize a QueryEntitiesResponseItem object. :param str text: (optional) Entity text content. :param str type: (optional) The type of the result entity. - :param list[QueryEvidence] evidence: (optional) List of different evidentiary - items to support the result. + :param list[QueryEvidence] evidence: (optional) List of different + evidentiary items to support the result. """ self.text = text self.type = type @@ -9547,19 +10081,20 @@ class QueryEvidence(object): """ Description of evidence location supporting Knoweldge Graph query result. - :attr str document_id: (optional) The docuemnt ID (as indexed in Discovery) of the - evidence location. - :attr str field: (optional) The field of the document where the supporting evidence - was identified. + :attr str document_id: (optional) The docuemnt ID (as indexed in Discovery) of + the evidence location. + :attr str field: (optional) The field of the document where the supporting + evidence was identified. :attr int start_offset: (optional) The start location of the evidence in the - identified field. This value is inclusive. - :attr int end_offset: (optional) The end location of the evidence in the identified - field. This value is inclusive. - :attr list[QueryEvidenceEntity] entities: (optional) An array of entity objects that - show evidence of the result. + identified field. This value is inclusive. + :attr int end_offset: (optional) The end location of the evidence in the + identified field. This value is inclusive. + :attr list[QueryEvidenceEntity] entities: (optional) An array of entity objects + that show evidence of the result. """ def __init__(self, + *, document_id=None, field=None, start_offset=None, @@ -9568,16 +10103,16 @@ def __init__(self, """ Initialize a QueryEvidence object. - :param str document_id: (optional) The docuemnt ID (as indexed in Discovery) of - the evidence location. + :param str document_id: (optional) The docuemnt ID (as indexed in + Discovery) of the evidence location. :param str field: (optional) The field of the document where the supporting - evidence was identified. - :param int start_offset: (optional) The start location of the evidence in the - identified field. This value is inclusive. + evidence was identified. + :param int start_offset: (optional) The start location of the evidence in + the identified field. This value is inclusive. :param int end_offset: (optional) The end location of the evidence in the - identified field. This value is inclusive. - :param list[QueryEvidenceEntity] entities: (optional) An array of entity objects - that show evidence of the result. + identified field. This value is inclusive. + :param list[QueryEvidenceEntity] entities: (optional) An array of entity + objects that show evidence of the result. """ self.document_id = document_id self.field = field @@ -9646,29 +10181,33 @@ class QueryEvidenceEntity(object): """ Entity description and location within evidence field. - :attr str type: (optional) The entity type for this entity. Possible types vary based - on model used. - :attr str text: (optional) The original text of this entity as found in the evidence - field. + :attr str type: (optional) The entity type for this entity. Possible types vary + based on model used. + :attr str text: (optional) The original text of this entity as found in the + evidence field. :attr int start_offset: (optional) The start location of the entity text in the - identified field. This value is inclusive. - :attr int end_offset: (optional) The end location of the entity text in the identified - field. This value is exclusive. + identified field. This value is inclusive. + :attr int end_offset: (optional) The end location of the entity text in the + identified field. This value is exclusive. """ - def __init__(self, type=None, text=None, start_offset=None, + def __init__(self, + *, + type=None, + text=None, + start_offset=None, end_offset=None): """ Initialize a QueryEvidenceEntity object. - :param str type: (optional) The entity type for this entity. Possible types vary - based on model used. - :param str text: (optional) The original text of this entity as found in the - evidence field. - :param int start_offset: (optional) The start location of the entity text in the - identified field. This value is inclusive. - :param int end_offset: (optional) The end location of the entity text in the - identified field. This value is exclusive. + :param str type: (optional) The entity type for this entity. Possible types + vary based on model used. + :param str text: (optional) The original text of this entity as found in + the evidence field. + :param int start_offset: (optional) The start location of the entity text + in the identified field. This value is inclusive. + :param int end_offset: (optional) The end location of the entity text in + the identified field. This value is exclusive. """ self.type = type self.text = text @@ -9728,17 +10267,18 @@ class QueryFilterType(object): QueryFilterType. :attr list[str] exclude: (optional) A comma-separated list of types to exclude. - :attr list[str] include: (optional) A comma-separated list of types to include. All - other types are excluded. + :attr list[str] include: (optional) A comma-separated list of types to include. + All other types are excluded. """ - def __init__(self, exclude=None, include=None): + def __init__(self, *, exclude=None, include=None): """ Initialize a QueryFilterType object. - :param list[str] exclude: (optional) A comma-separated list of types to exclude. - :param list[str] include: (optional) A comma-separated list of types to include. - All other types are excluded. + :param list[str] exclude: (optional) A comma-separated list of types to + exclude. + :param list[str] include: (optional) A comma-separated list of types to + include. All other types are excluded. """ self.exclude = exclude self.include = include @@ -9788,17 +10328,18 @@ class QueryNoticesResponse(object): QueryNoticesResponse. :attr int matching_results: (optional) The number of matching results. - :attr list[QueryNoticesResult] results: (optional) Array of document results that - match the query. - :attr list[QueryAggregation] aggregations: (optional) Array of aggregation results - that match the query. - :attr list[QueryPassages] passages: (optional) Array of passage results that match the - query. - :attr int duplicates_removed: (optional) The number of duplicates removed from this - notices query. + :attr list[QueryNoticesResult] results: (optional) Array of document results + that match the query. + :attr list[QueryAggregation] aggregations: (optional) Array of aggregation + results that match the query. + :attr list[QueryPassages] passages: (optional) Array of passage results that + match the query. + :attr int duplicates_removed: (optional) The number of duplicates removed from + this notices query. """ def __init__(self, + *, matching_results=None, results=None, aggregations=None, @@ -9808,14 +10349,14 @@ def __init__(self, Initialize a QueryNoticesResponse object. :param int matching_results: (optional) The number of matching results. - :param list[QueryNoticesResult] results: (optional) Array of document results that - match the query. + :param list[QueryNoticesResult] results: (optional) Array of document + results that match the query. :param list[QueryAggregation] aggregations: (optional) Array of aggregation - results that match the query. - :param list[QueryPassages] passages: (optional) Array of passage results that - match the query. - :param int duplicates_removed: (optional) The number of duplicates removed from - this notices query. + results that match the query. + :param list[QueryPassages] passages: (optional) Array of passage results + that match the query. + :param int duplicates_removed: (optional) The number of duplicates removed + from this notices query. """ self.matching_results = matching_results self.results = results @@ -9894,20 +10435,22 @@ class QueryNoticesResult(object): :attr str id: (optional) The unique identifier of the document. :attr dict metadata: (optional) Metadata of the document. - :attr str collection_id: (optional) The collection ID of the collection containing the - document for this result. - :attr QueryResultMetadata result_metadata: (optional) Metadata of a query result. + :attr str collection_id: (optional) The collection ID of the collection + containing the document for this result. + :attr QueryResultMetadata result_metadata: (optional) Metadata of a query + result. :attr str title: (optional) Automatically extracted result title. :attr int code: (optional) The internal status code returned by the ingestion - subsystem indicating the overall result of ingesting the source document. + subsystem indicating the overall result of ingesting the source document. :attr str filename: (optional) Name of the original source file (if available). :attr str file_type: (optional) The type of the original source file. - :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted as a - hexadecimal string). + :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted + as a hexadecimal string). :attr list[Notice] notices: (optional) Array of notices for the document. """ def __init__(self, + *, id=None, metadata=None, collection_id=None, @@ -9925,15 +10468,18 @@ def __init__(self, :param str id: (optional) The unique identifier of the document. :param dict metadata: (optional) Metadata of the document. :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query result. + containing the document for this result. + :param QueryResultMetadata result_metadata: (optional) Metadata of a query + result. :param str title: (optional) Automatically extracted result title. - :param int code: (optional) The internal status code returned by the ingestion - subsystem indicating the overall result of ingesting the source document. - :param str filename: (optional) Name of the original source file (if available). + :param int code: (optional) The internal status code returned by the + ingestion subsystem indicating the overall result of ingesting the source + document. + :param str filename: (optional) Name of the original source file (if + available). :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file (formatted - as a hexadecimal string). + :param str sha1: (optional) The SHA-1 hash of the original source file + (formatted as a hexadecimal string). :param list[Notice] notices: (optional) Array of notices for the document. :param **kwargs: (optional) Any additional properties. """ @@ -10048,25 +10594,35 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class FileTypeEnum(Enum): + """ + The type of the original source file. + """ + PDF = "pdf" + HTML = "html" + WORD = "word" + JSON = "json" + class QueryPassages(object): """ QueryPassages. - :attr str document_id: (optional) The unique identifier of the document from which the - passage has been extracted. - :attr float passage_score: (optional) The confidence score of the passages's analysis. - A higher score indicates greater confidence. + :attr str document_id: (optional) The unique identifier of the document from + which the passage has been extracted. + :attr float passage_score: (optional) The confidence score of the passages's + analysis. A higher score indicates greater confidence. :attr str passage_text: (optional) The content of the extracted passage. :attr int start_offset: (optional) The position of the first character of the - extracted passage in the originating field. - :attr int end_offset: (optional) The position of the last character of the extracted - passage in the originating field. - :attr str field: (optional) The label of the field from which the passage has been - extracted. + extracted passage in the originating field. + :attr int end_offset: (optional) The position of the last character of the + extracted passage in the originating field. + :attr str field: (optional) The label of the field from which the passage has + been extracted. """ def __init__(self, + *, document_id=None, passage_score=None, passage_text=None, @@ -10076,17 +10632,17 @@ def __init__(self, """ Initialize a QueryPassages object. - :param str document_id: (optional) The unique identifier of the document from - which the passage has been extracted. - :param float passage_score: (optional) The confidence score of the passages's - analysis. A higher score indicates greater confidence. + :param str document_id: (optional) The unique identifier of the document + from which the passage has been extracted. + :param float passage_score: (optional) The confidence score of the + passages's analysis. A higher score indicates greater confidence. :param str passage_text: (optional) The content of the extracted passage. - :param int start_offset: (optional) The position of the first character of the - extracted passage in the originating field. + :param int start_offset: (optional) The position of the first character of + the extracted passage in the originating field. :param int end_offset: (optional) The position of the last character of the - extracted passage in the originating field. - :param str field: (optional) The label of the field from which the passage has - been extracted. + extracted passage in the originating field. + :param str field: (optional) The label of the field from which the passage + has been extracted. """ self.document_id = document_id self.passage_score = passage_score @@ -10161,11 +10717,12 @@ class QueryRelationsArgument(object): :attr list[QueryEntitiesEntity] entities: (optional) Array of query entities. """ - def __init__(self, entities=None): + def __init__(self, *, entities=None): """ Initialize a QueryRelationsArgument object. - :param list[QueryEntitiesEntity] entities: (optional) Array of query entities. + :param list[QueryEntitiesEntity] entities: (optional) Array of query + entities. """ self.entities = entities @@ -10214,18 +10771,18 @@ class QueryRelationsEntity(object): :attr str text: (optional) Entity text content. :attr str type: (optional) The type of the specified entity. - :attr bool exact: (optional) If false, implicit querying is performed. The default is - `false`. + :attr bool exact: (optional) If false, implicit querying is performed. The + default is `false`. """ - def __init__(self, text=None, type=None, exact=None): + def __init__(self, *, text=None, type=None, exact=None): """ Initialize a QueryRelationsEntity object. :param str text: (optional) Entity text content. :param str type: (optional) The type of the specified entity. :param bool exact: (optional) If false, implicit querying is performed. The - default is `false`. + default is `false`. """ self.text = text self.type = type @@ -10281,11 +10838,12 @@ class QueryRelationsFilter(object): :attr QueryFilterType relation_types: (optional) :attr QueryFilterType entity_types: (optional) - :attr list[str] document_ids: (optional) A comma-separated list of document IDs to - include in the query. + :attr list[str] document_ids: (optional) A comma-separated list of document IDs + to include in the query. """ def __init__(self, + *, relation_types=None, entity_types=None, document_ids=None): @@ -10294,8 +10852,8 @@ def __init__(self, :param QueryFilterType relation_types: (optional) :param QueryFilterType entity_types: (optional) - :param list[str] document_ids: (optional) A comma-separated list of document IDs - to include in the query. + :param list[str] document_ids: (optional) A comma-separated list of + document IDs to include in the query. """ self.relation_types = relation_types self.entity_types = entity_types @@ -10352,25 +10910,30 @@ class QueryRelationsRelationship(object): QueryRelationsRelationship. :attr str type: (optional) The identified relationship type. - :attr int frequency: (optional) The number of times the relationship is mentioned. + :attr int frequency: (optional) The number of times the relationship is + mentioned. :attr list[QueryRelationsArgument] arguments: (optional) Information about the - relationship. - :attr list[QueryEvidence] evidence: (optional) List of different evidentiary items to - support the result. + relationship. + :attr list[QueryEvidence] evidence: (optional) List of different evidentiary + items to support the result. """ - def __init__(self, type=None, frequency=None, arguments=None, + def __init__(self, + *, + type=None, + frequency=None, + arguments=None, evidence=None): """ Initialize a QueryRelationsRelationship object. :param str type: (optional) The identified relationship type. :param int frequency: (optional) The number of times the relationship is - mentioned. - :param list[QueryRelationsArgument] arguments: (optional) Information about the - relationship. - :param list[QueryEvidence] evidence: (optional) List of different evidentiary - items to support the result. + mentioned. + :param list[QueryRelationsArgument] arguments: (optional) Information about + the relationship. + :param list[QueryEvidence] evidence: (optional) List of different + evidentiary items to support the result. """ self.type = type self.frequency = frequency @@ -10434,16 +10997,16 @@ class QueryRelationsResponse(object): """ QueryRelationsResponse. - :attr list[QueryRelationsRelationship] relations: (optional) Array of relationships - for the relations query. + :attr list[QueryRelationsRelationship] relations: (optional) Array of + relationships for the relations query. """ - def __init__(self, relations=None): + def __init__(self, *, relations=None): """ Initialize a QueryRelationsResponse object. :param list[QueryRelationsRelationship] relations: (optional) Array of - relationships for the relations query. + relationships for the relations query. """ self.relations = relations @@ -10490,20 +11053,26 @@ class QueryResponse(object): """ A response containing the documents and aggregations for the query. - :attr int matching_results: (optional) The number of matching results for the query. - :attr list[QueryResult] results: (optional) Array of document results for the query. - :attr list[QueryAggregation] aggregations: (optional) Array of aggregation results for - the query. - :attr list[QueryPassages] passages: (optional) Array of passage results for the query. - :attr int duplicates_removed: (optional) The number of duplicate results removed. - :attr str session_token: (optional) The session token for this query. The session - token can be used to add events associated with this query to the query and event log. - **Important:** Session tokens are case sensitive. - :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval type - information. + :attr int matching_results: (optional) The number of matching results for the + query. + :attr list[QueryResult] results: (optional) Array of document results for the + query. + :attr list[QueryAggregation] aggregations: (optional) Array of aggregation + results for the query. + :attr list[QueryPassages] passages: (optional) Array of passage results for the + query. + :attr int duplicates_removed: (optional) The number of duplicate results + removed. + :attr str session_token: (optional) The session token for this query. The + session token can be used to add events associated with this query to the query + and event log. + **Important:** Session tokens are case sensitive. + :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval + type information. """ def __init__(self, + *, matching_results=None, results=None, aggregations=None, @@ -10514,21 +11083,22 @@ def __init__(self, """ Initialize a QueryResponse object. - :param int matching_results: (optional) The number of matching results for the - query. - :param list[QueryResult] results: (optional) Array of document results for the - query. + :param int matching_results: (optional) The number of matching results for + the query. + :param list[QueryResult] results: (optional) Array of document results for + the query. :param list[QueryAggregation] aggregations: (optional) Array of aggregation - results for the query. - :param list[QueryPassages] passages: (optional) Array of passage results for the - query. - :param int duplicates_removed: (optional) The number of duplicate results removed. - :param str session_token: (optional) The session token for this query. The session - token can be used to add events associated with this query to the query and event - log. - **Important:** Session tokens are case sensitive. - :param RetrievalDetails retrieval_details: (optional) An object contain retrieval - type information. + results for the query. + :param list[QueryPassages] passages: (optional) Array of passage results + for the query. + :param int duplicates_removed: (optional) The number of duplicate results + removed. + :param str session_token: (optional) The session token for this query. The + session token can be used to add events associated with this query to the + query and event log. + **Important:** Session tokens are case sensitive. + :param RetrievalDetails retrieval_details: (optional) An object contain + retrieval type information. """ self.matching_results = matching_results self.results = results @@ -10619,13 +11189,15 @@ class QueryResult(object): :attr str id: (optional) The unique identifier of the document. :attr dict metadata: (optional) Metadata of the document. - :attr str collection_id: (optional) The collection ID of the collection containing the - document for this result. - :attr QueryResultMetadata result_metadata: (optional) Metadata of a query result. + :attr str collection_id: (optional) The collection ID of the collection + containing the document for this result. + :attr QueryResultMetadata result_metadata: (optional) Metadata of a query + result. :attr str title: (optional) Automatically extracted result title. """ def __init__(self, + *, id=None, metadata=None, collection_id=None, @@ -10638,8 +11210,9 @@ def __init__(self, :param str id: (optional) The unique identifier of the document. :param dict metadata: (optional) Metadata of the document. :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query result. + containing the document for this result. + :param QueryResultMetadata result_metadata: (optional) Metadata of a query + result. :param str title: (optional) Automatically extracted result title. :param **kwargs: (optional) Any additional properties. """ @@ -10726,27 +11299,28 @@ class QueryResultMetadata(object): Metadata of a query result. :attr float score: An unbounded measure of the relevance of a particular result, - dependent on the query and matching document. A higher score indicates a greater match - to the query parameters. + dependent on the query and matching document. A higher score indicates a greater + match to the query parameters. :attr float confidence: (optional) The confidence score for the given result. - Calculated based on how relevant the result is estimated to be. confidence can range - from `0.0` to `1.0`. The higher the number, the more relevant the document. The - `confidence` value for a result was calculated using the model specified in the - `document_retrieval_strategy` field of the result set. + Calculated based on how relevant the result is estimated to be. confidence can + range from `0.0` to `1.0`. The higher the number, the more relevant the + document. The `confidence` value for a result was calculated using the model + specified in the `document_retrieval_strategy` field of the result set. """ - def __init__(self, score, confidence=None): + def __init__(self, score, *, confidence=None): """ Initialize a QueryResultMetadata object. - :param float score: An unbounded measure of the relevance of a particular result, - dependent on the query and matching document. A higher score indicates a greater - match to the query parameters. - :param float confidence: (optional) The confidence score for the given result. - Calculated based on how relevant the result is estimated to be. confidence can - range from `0.0` to `1.0`. The higher the number, the more relevant the document. - The `confidence` value for a result was calculated using the model specified in - the `document_retrieval_strategy` field of the result set. + :param float score: An unbounded measure of the relevance of a particular + result, dependent on the query and matching document. A higher score + indicates a greater match to the query parameters. + :param float confidence: (optional) The confidence score for the given + result. Calculated based on how relevant the result is estimated to be. + confidence can range from `0.0` to `1.0`. The higher the number, the more + relevant the document. The `confidence` value for a result was calculated + using the model specified in the `document_retrieval_strategy` field of the + result set. """ self.score = score self.confidence = confidence @@ -10799,30 +11373,31 @@ class RetrievalDetails(object): """ An object contain retrieval type information. - :attr str document_retrieval_strategy: (optional) Indentifies the document retrieval - strategy used for this query. `relevancy_training` indicates that the results were - returned using a relevancy trained model. `continuous_relevancy_training` indicates - that the results were returned using the continuous relevancy training model created - by result feedback analysis. `untrained` means the results were returned using the - standard untrained model. - **Note**: In the event of trained collections being queried, but the trained model is - not used to return results, the **document_retrieval_strategy** will be listed as - `untrained`. + :attr str document_retrieval_strategy: (optional) Indentifies the document + retrieval strategy used for this query. `relevancy_training` indicates that the + results were returned using a relevancy trained model. + `continuous_relevancy_training` indicates that the results were returned using + the continuous relevancy training model created by result feedback analysis. + `untrained` means the results were returned using the standard untrained model. + **Note**: In the event of trained collections being queried, but the trained + model is not used to return results, the **document_retrieval_strategy** will be + listed as `untrained`. """ - def __init__(self, document_retrieval_strategy=None): + def __init__(self, *, document_retrieval_strategy=None): """ Initialize a RetrievalDetails object. :param str document_retrieval_strategy: (optional) Indentifies the document - retrieval strategy used for this query. `relevancy_training` indicates that the - results were returned using a relevancy trained model. - `continuous_relevancy_training` indicates that the results were returned using the - continuous relevancy training model created by result feedback analysis. - `untrained` means the results were returned using the standard untrained model. - **Note**: In the event of trained collections being queried, but the trained - model is not used to return results, the **document_retrieval_strategy** will be - listed as `untrained`. + retrieval strategy used for this query. `relevancy_training` indicates that + the results were returned using a relevancy trained model. + `continuous_relevancy_training` indicates that the results were returned + using the continuous relevancy training model created by result feedback + analysis. `untrained` means the results were returned using the standard + untrained model. + **Note**: In the event of trained collections being queried, but the + trained model is not used to return results, the + **document_retrieval_strategy** will be listed as `untrained`. """ self.document_retrieval_strategy = document_retrieval_strategy @@ -10864,33 +11439,52 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class DocumentRetrievalStrategyEnum(Enum): + """ + Indentifies the document retrieval strategy used for this query. + `relevancy_training` indicates that the results were returned using a relevancy + trained model. `continuous_relevancy_training` indicates that the results were + returned using the continuous relevancy training model created by result feedback + analysis. `untrained` means the results were returned using the standard untrained + model. + **Note**: In the event of trained collections being queried, but the trained + model is not used to return results, the **document_retrieval_strategy** will be + listed as `untrained`. + """ + UNTRAINED = "untrained" + RELEVANCY_TRAINING = "relevancy_training" + CONTINUOUS_RELEVANCY_TRAINING = "continuous_relevancy_training" + class SduStatus(object): """ Object containing smart document understanding information for this collection. - :attr bool enabled: (optional) When `true`, smart document understanding conversion is - enabled for this collection. All collections created with a version date after - `2019-04-30` have smart document understanding enabled. If `false`, documents added to - the collection are converted using the **conversion** settings specified in the - configuration associated with the collection. - :attr int total_annotated_pages: (optional) The total number of pages annotated using - smart document understanding in this collection. - :attr int total_pages: (optional) The current number of pages that can be used for - training smart document understanding. The `total_pages` number is calculated as the - total number of pages identified from the documents listed in the **total_documents** - field. - :attr int total_documents: (optional) The total number of documents in this collection - that can be used to train smart document understanding. For **lite** plan collections, - the maximum is the first 20 uploaded documents (not including HTML or JSON documents). - For other plans, the maximum is the first 40 uploaded documents (not including HTML or - JSON documents). When the maximum is reached, additional documents uploaded to the - collection are not considered for training smart document understanding. - :attr SduStatusCustomFields custom_fields: (optional) Information about custom smart - document understanding fields that exist in this collection. + :attr bool enabled: (optional) When `true`, smart document understanding + conversion is enabled for this collection. All collections created with a + version date after `2019-04-30` have smart document understanding enabled. If + `false`, documents added to the collection are converted using the + **conversion** settings specified in the configuration associated with the + collection. + :attr int total_annotated_pages: (optional) The total number of pages annotated + using smart document understanding in this collection. + :attr int total_pages: (optional) The current number of pages that can be used + for training smart document understanding. The `total_pages` number is + calculated as the total number of pages identified from the documents listed in + the **total_documents** field. + :attr int total_documents: (optional) The total number of documents in this + collection that can be used to train smart document understanding. For **lite** + plan collections, the maximum is the first 20 uploaded documents (not including + HTML or JSON documents). For other plans, the maximum is the first 40 uploaded + documents (not including HTML or JSON documents). When the maximum is reached, + additional documents uploaded to the collection are not considered for training + smart document understanding. + :attr SduStatusCustomFields custom_fields: (optional) Information about custom + smart document understanding fields that exist in this collection. """ def __init__(self, + *, enabled=None, total_annotated_pages=None, total_pages=None, @@ -10900,25 +11494,26 @@ def __init__(self, Initialize a SduStatus object. :param bool enabled: (optional) When `true`, smart document understanding - conversion is enabled for this collection. All collections created with a version - date after `2019-04-30` have smart document understanding enabled. If `false`, - documents added to the collection are converted using the **conversion** settings - specified in the configuration associated with the collection. - :param int total_annotated_pages: (optional) The total number of pages annotated - using smart document understanding in this collection. - :param int total_pages: (optional) The current number of pages that can be used - for training smart document understanding. The `total_pages` number is calculated - as the total number of pages identified from the documents listed in the - **total_documents** field. - :param int total_documents: (optional) The total number of documents in this - collection that can be used to train smart document understanding. For **lite** - plan collections, the maximum is the first 20 uploaded documents (not including - HTML or JSON documents). For other plans, the maximum is the first 40 uploaded - documents (not including HTML or JSON documents). When the maximum is reached, - additional documents uploaded to the collection are not considered for training - smart document understanding. - :param SduStatusCustomFields custom_fields: (optional) Information about custom - smart document understanding fields that exist in this collection. + conversion is enabled for this collection. All collections created with a + version date after `2019-04-30` have smart document understanding enabled. + If `false`, documents added to the collection are converted using the + **conversion** settings specified in the configuration associated with the + collection. + :param int total_annotated_pages: (optional) The total number of pages + annotated using smart document understanding in this collection. + :param int total_pages: (optional) The current number of pages that can be + used for training smart document understanding. The `total_pages` number is + calculated as the total number of pages identified from the documents + listed in the **total_documents** field. + :param int total_documents: (optional) The total number of documents in + this collection that can be used to train smart document understanding. For + **lite** plan collections, the maximum is the first 20 uploaded documents + (not including HTML or JSON documents). For other plans, the maximum is the + first 40 uploaded documents (not including HTML or JSON documents). When + the maximum is reached, additional documents uploaded to the collection are + not considered for training smart document understanding. + :param SduStatusCustomFields custom_fields: (optional) Information about + custom smart document understanding fields that exist in this collection. """ self.enabled = enabled self.total_annotated_pages = total_annotated_pages @@ -10989,19 +11584,20 @@ class SduStatusCustomFields(object): Information about custom smart document understanding fields that exist in this collection. - :attr int defined: (optional) The number of custom fields defined for this collection. - :attr int maximum_allowed: (optional) The maximum number of custom fields that are - allowed in this collection. + :attr int defined: (optional) The number of custom fields defined for this + collection. + :attr int maximum_allowed: (optional) The maximum number of custom fields that + are allowed in this collection. """ - def __init__(self, defined=None, maximum_allowed=None): + def __init__(self, *, defined=None, maximum_allowed=None): """ Initialize a SduStatusCustomFields object. :param int defined: (optional) The number of custom fields defined for this - collection. - :param int maximum_allowed: (optional) The maximum number of custom fields that - are allowed in this collection. + collection. + :param int maximum_allowed: (optional) The maximum number of custom fields + that are allowed in this collection. """ self.defined = defined self.maximum_allowed = maximum_allowed @@ -11052,16 +11648,17 @@ class SearchStatus(object): Information about the Continuous Relevancy Training for this environment. :attr str scope: (optional) Current scope of the training. Always returned as - `environment`. - :attr str status: (optional) The current status of Continuous Relevancy Training for - this environment. - :attr str status_description: (optional) Long description of the current Continuous - Relevancy Training status. + `environment`. + :attr str status: (optional) The current status of Continuous Relevancy Training + for this environment. + :attr str status_description: (optional) Long description of the current + Continuous Relevancy Training status. :attr date last_trained: (optional) The date stamp of the most recent completed - training for this environment. + training for this environment. """ def __init__(self, + *, scope=None, status=None, status_description=None, @@ -11069,14 +11666,14 @@ def __init__(self, """ Initialize a SearchStatus object. - :param str scope: (optional) Current scope of the training. Always returned as - `environment`. - :param str status: (optional) The current status of Continuous Relevancy Training - for this environment. + :param str scope: (optional) Current scope of the training. Always returned + as `environment`. + :param str status: (optional) The current status of Continuous Relevancy + Training for this environment. :param str status_description: (optional) Long description of the current - Continuous Relevancy Training status. - :param date last_trained: (optional) The date stamp of the most recent completed - training for this environment. + Continuous Relevancy Training status. + :param date last_trained: (optional) The date stamp of the most recent + completed training for this environment. """ self.scope = scope self.status = status @@ -11132,49 +11729,67 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The current status of Continuous Relevancy Training for this environment. + """ + NO_DATA = "NO_DATA" + INSUFFICENT_DATA = "INSUFFICENT_DATA" + TRAINING = "TRAINING" + TRAINED = "TRAINED" + NOT_APPLICABLE = "NOT_APPLICABLE" + class SegmentSettings(object): """ A list of Document Segmentation settings. - :attr bool enabled: (optional) Enables/disables the Document Segmentation feature. - :attr list[str] selector_tags: (optional) Defines the heading level that splits into - document segments. Valid values are h1, h2, h3, h4, h5, h6. The content of the header - field that the segmentation splits at is used as the **title** field for that - segmented result. Only valid if used with a collection that has **enabled** set to - `false` in the **smart_document_understanding** object. - :attr list[str] annotated_fields: (optional) Defines the annotated smart document - understanding fields that the document is split on. The content of the annotated field - that the segmentation splits at is used as the **title** field for that segmented - result. For example, if the field `sub-title` is specified, when a document is - uploaded each time the smart documement understanding conversion encounters a field of - type `sub-title` the document is split at that point and the content of the field used - as the title of the remaining content. Thnis split is performed for all instances of - the listed fields in the uploaded document. Only valid if used with a collection that - has **enabled** set to `true` in the **smart_document_understanding** object. - """ - - def __init__(self, enabled=None, selector_tags=None, annotated_fields=None): + :attr bool enabled: (optional) Enables/disables the Document Segmentation + feature. + :attr list[str] selector_tags: (optional) Defines the heading level that splits + into document segments. Valid values are h1, h2, h3, h4, h5, h6. The content of + the header field that the segmentation splits at is used as the **title** field + for that segmented result. Only valid if used with a collection that has + **enabled** set to `false` in the **smart_document_understanding** object. + :attr list[str] annotated_fields: (optional) Defines the annotated smart + document understanding fields that the document is split on. The content of the + annotated field that the segmentation splits at is used as the **title** field + for that segmented result. For example, if the field `sub-title` is specified, + when a document is uploaded each time the smart documement understanding + conversion encounters a field of type `sub-title` the document is split at that + point and the content of the field used as the title of the remaining content. + Thnis split is performed for all instances of the listed fields in the uploaded + document. Only valid if used with a collection that has **enabled** set to + `true` in the **smart_document_understanding** object. + """ + + def __init__(self, + *, + enabled=None, + selector_tags=None, + annotated_fields=None): """ Initialize a SegmentSettings object. :param bool enabled: (optional) Enables/disables the Document Segmentation - feature. - :param list[str] selector_tags: (optional) Defines the heading level that splits - into document segments. Valid values are h1, h2, h3, h4, h5, h6. The content of - the header field that the segmentation splits at is used as the **title** field - for that segmented result. Only valid if used with a collection that has - **enabled** set to `false` in the **smart_document_understanding** object. - :param list[str] annotated_fields: (optional) Defines the annotated smart document - understanding fields that the document is split on. The content of the annotated - field that the segmentation splits at is used as the **title** field for that - segmented result. For example, if the field `sub-title` is specified, when a - document is uploaded each time the smart documement understanding conversion - encounters a field of type `sub-title` the document is split at that point and the - content of the field used as the title of the remaining content. Thnis split is - performed for all instances of the listed fields in the uploaded document. Only - valid if used with a collection that has **enabled** set to `true` in the - **smart_document_understanding** object. + feature. + :param list[str] selector_tags: (optional) Defines the heading level that + splits into document segments. Valid values are h1, h2, h3, h4, h5, h6. The + content of the header field that the segmentation splits at is used as the + **title** field for that segmented result. Only valid if used with a + collection that has **enabled** set to `false` in the + **smart_document_understanding** object. + :param list[str] annotated_fields: (optional) Defines the annotated smart + document understanding fields that the document is split on. The content of + the annotated field that the segmentation splits at is used as the + **title** field for that segmented result. For example, if the field + `sub-title` is specified, when a document is uploaded each time the smart + documement understanding conversion encounters a field of type `sub-title` + the document is split at that point and the content of the field used as + the title of the remaining content. Thnis split is performed for all + instances of the listed fields in the uploaded document. Only valid if used + with a collection that has **enabled** set to `true` in the + **smart_document_understanding** object. """ self.enabled = enabled self.selector_tags = selector_tags @@ -11230,24 +11845,26 @@ class Source(object): Object containing source parameters for the configuration. :attr str type: (optional) The type of source to connect to. - - `box` indicates the configuration is to connect an instance of Enterprise Box. - - `salesforce` indicates the configuration is to connect to Salesforce. - - `sharepoint` indicates the configuration is to connect to Microsoft SharePoint - Online. - - `web_crawl` indicates the configuration is to perform a web page crawl. - - `cloud_object_storage` indicates the configuration is to connect to a cloud object - store. - :attr str credential_id: (optional) The **credential_id** of the credentials to use to - connect to the source. Credentials are defined using the **credentials** method. The - **source_type** of the credentials used must match the **type** field specified in - this object. - :attr SourceSchedule schedule: (optional) Object containing the schedule information - for the source. - :attr SourceOptions options: (optional) The **options** object defines which items to - crawl from the source system. + - `box` indicates the configuration is to connect an instance of Enterprise + Box. + - `salesforce` indicates the configuration is to connect to Salesforce. + - `sharepoint` indicates the configuration is to connect to Microsoft + SharePoint Online. + - `web_crawl` indicates the configuration is to perform a web page crawl. + - `cloud_object_storage` indicates the configuration is to connect to a cloud + object store. + :attr str credential_id: (optional) The **credential_id** of the credentials to + use to connect to the source. Credentials are defined using the **credentials** + method. The **source_type** of the credentials used must match the **type** + field specified in this object. + :attr SourceSchedule schedule: (optional) Object containing the schedule + information for the source. + :attr SourceOptions options: (optional) The **options** object defines which + items to crawl from the source system. """ def __init__(self, + *, type=None, credential_id=None, schedule=None, @@ -11256,21 +11873,22 @@ def __init__(self, Initialize a Source object. :param str type: (optional) The type of source to connect to. - - `box` indicates the configuration is to connect an instance of Enterprise Box. - - `salesforce` indicates the configuration is to connect to Salesforce. - - `sharepoint` indicates the configuration is to connect to Microsoft SharePoint - Online. - - `web_crawl` indicates the configuration is to perform a web page crawl. - - `cloud_object_storage` indicates the configuration is to connect to a cloud - object store. - :param str credential_id: (optional) The **credential_id** of the credentials to - use to connect to the source. Credentials are defined using the **credentials** - method. The **source_type** of the credentials used must match the **type** field - specified in this object. + - `box` indicates the configuration is to connect an instance of + Enterprise Box. + - `salesforce` indicates the configuration is to connect to Salesforce. + - `sharepoint` indicates the configuration is to connect to Microsoft + SharePoint Online. + - `web_crawl` indicates the configuration is to perform a web page crawl. + - `cloud_object_storage` indicates the configuration is to connect to a + cloud object store. + :param str credential_id: (optional) The **credential_id** of the + credentials to use to connect to the source. Credentials are defined using + the **credentials** method. The **source_type** of the credentials used + must match the **type** field specified in this object. :param SourceSchedule schedule: (optional) Object containing the schedule - information for the source. - :param SourceOptions options: (optional) The **options** object defines which - items to crawl from the source system. + information for the source. + :param SourceOptions options: (optional) The **options** object defines + which items to crawl from the source system. """ self.type = type self.credential_id = credential_id @@ -11324,33 +11942,52 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The type of source to connect to. + - `box` indicates the configuration is to connect an instance of Enterprise Box. + - `salesforce` indicates the configuration is to connect to Salesforce. + - `sharepoint` indicates the configuration is to connect to Microsoft SharePoint + Online. + - `web_crawl` indicates the configuration is to perform a web page crawl. + - `cloud_object_storage` indicates the configuration is to connect to a cloud + object store. + """ + BOX = "box" + SALESFORCE = "salesforce" + SHAREPOINT = "sharepoint" + WEB_CRAWL = "web_crawl" + CLOUD_OBJECT_STORAGE = "cloud_object_storage" + class SourceOptions(object): """ The **options** object defines which items to crawl from the source system. - :attr list[SourceOptionsFolder] folders: (optional) Array of folders to crawl from the - Box source. Only valid, and required, when the **type** field of the **source** object - is set to `box`. + :attr list[SourceOptionsFolder] folders: (optional) Array of folders to crawl + from the Box source. Only valid, and required, when the **type** field of the + **source** object is set to `box`. :attr list[SourceOptionsObject] objects: (optional) Array of Salesforce document - object types to crawl from the Salesforce source. Only valid, and required, when the - **type** field of the **source** object is set to `salesforce`. - :attr list[SourceOptionsSiteColl] site_collections: (optional) Array of Microsoft - SharePointoint Online site collections to crawl from the SharePoint source. Only valid - and required when the **type** field of the **source** object is set to `sharepoint`. - :attr list[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to begin - crawling the web from. Only valid and required when the **type** field of the - **source** object is set to `web_crawl`. + object types to crawl from the Salesforce source. Only valid, and required, when + the **type** field of the **source** object is set to `salesforce`. + :attr list[SourceOptionsSiteColl] site_collections: (optional) Array of + Microsoft SharePointoint Online site collections to crawl from the SharePoint + source. Only valid and required when the **type** field of the **source** object + is set to `sharepoint`. + :attr list[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to + begin crawling the web from. Only valid and required when the **type** field of + the **source** object is set to `web_crawl`. :attr list[SourceOptionsBuckets] buckets: (optional) Array of cloud object store - buckets to begin crawling. Only valid and required when the **type** field of the - **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field - is `false` or not specified. - :attr bool crawl_all_buckets: (optional) When `true`, all buckets in the specified - cloud object store are crawled. If set to `true`, the **buckets** array must not be - specified. + buckets to begin crawling. Only valid and required when the **type** field of + the **source** object is set to `cloud_object_store`, and the + **crawl_all_buckets** field is `false` or not specified. + :attr bool crawl_all_buckets: (optional) When `true`, all buckets in the + specified cloud object store are crawled. If set to `true`, the **buckets** + array must not be specified. """ def __init__(self, + *, folders=None, objects=None, site_collections=None, @@ -11360,26 +11997,27 @@ def __init__(self, """ Initialize a SourceOptions object. - :param list[SourceOptionsFolder] folders: (optional) Array of folders to crawl - from the Box source. Only valid, and required, when the **type** field of the - **source** object is set to `box`. - :param list[SourceOptionsObject] objects: (optional) Array of Salesforce document - object types to crawl from the Salesforce source. Only valid, and required, when - the **type** field of the **source** object is set to `salesforce`. - :param list[SourceOptionsSiteColl] site_collections: (optional) Array of Microsoft - SharePointoint Online site collections to crawl from the SharePoint source. Only - valid and required when the **type** field of the **source** object is set to - `sharepoint`. - :param list[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to - begin crawling the web from. Only valid and required when the **type** field of - the **source** object is set to `web_crawl`. - :param list[SourceOptionsBuckets] buckets: (optional) Array of cloud object store - buckets to begin crawling. Only valid and required when the **type** field of the - **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** - field is `false` or not specified. + :param list[SourceOptionsFolder] folders: (optional) Array of folders to + crawl from the Box source. Only valid, and required, when the **type** + field of the **source** object is set to `box`. + :param list[SourceOptionsObject] objects: (optional) Array of Salesforce + document object types to crawl from the Salesforce source. Only valid, and + required, when the **type** field of the **source** object is set to + `salesforce`. + :param list[SourceOptionsSiteColl] site_collections: (optional) Array of + Microsoft SharePointoint Online site collections to crawl from the + SharePoint source. Only valid and required when the **type** field of the + **source** object is set to `sharepoint`. + :param list[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs + to begin crawling the web from. Only valid and required when the **type** + field of the **source** object is set to `web_crawl`. + :param list[SourceOptionsBuckets] buckets: (optional) Array of cloud object + store buckets to begin crawling. Only valid and required when the **type** + field of the **source** object is set to `cloud_object_store`, and the + **crawl_all_buckets** field is `false` or not specified. :param bool crawl_all_buckets: (optional) When `true`, all buckets in the - specified cloud object store are crawled. If set to `true`, the **buckets** array - must not be specified. + specified cloud object store are crawled. If set to `true`, the **buckets** + array must not be specified. """ self.folders = folders self.objects = objects @@ -11470,17 +12108,18 @@ class SourceOptionsBuckets(object): Object defining a cloud object store bucket to crawl. :attr str name: The name of the cloud object store bucket to crawl. - :attr int limit: (optional) The number of documents to crawl from this cloud object - store bucket. If not specified, all documents in the bucket are crawled. + :attr int limit: (optional) The number of documents to crawl from this cloud + object store bucket. If not specified, all documents in the bucket are crawled. """ - def __init__(self, name, limit=None): + def __init__(self, name, *, limit=None): """ Initialize a SourceOptionsBuckets object. :param str name: The name of the cloud object store bucket to crawl. - :param int limit: (optional) The number of documents to crawl from this cloud - object store bucket. If not specified, all documents in the bucket are crawled. + :param int limit: (optional) The number of documents to crawl from this + cloud object store bucket. If not specified, all documents in the bucket + are crawled. """ self.name = name self.limit = limit @@ -11533,21 +12172,22 @@ class SourceOptionsFolder(object): """ Object that defines a box folder to crawl with this configuration. - :attr str owner_user_id: The Box user ID of the user who owns the folder to crawl. + :attr str owner_user_id: The Box user ID of the user who owns the folder to + crawl. :attr str folder_id: The Box folder ID of the folder to crawl. - :attr int limit: (optional) The maximum number of documents to crawl for this folder. - By default, all documents in the folder are crawled. + :attr int limit: (optional) The maximum number of documents to crawl for this + folder. By default, all documents in the folder are crawled. """ - def __init__(self, owner_user_id, folder_id, limit=None): + def __init__(self, owner_user_id, folder_id, *, limit=None): """ Initialize a SourceOptionsFolder object. - :param str owner_user_id: The Box user ID of the user who owns the folder to - crawl. + :param str owner_user_id: The Box user ID of the user who owns the folder + to crawl. :param str folder_id: The Box folder ID of the folder to crawl. - :param int limit: (optional) The maximum number of documents to crawl for this - folder. By default, all documents in the folder are crawled. + :param int limit: (optional) The maximum number of documents to crawl for + this folder. By default, all documents in the folder are crawled. """ self.owner_user_id = owner_user_id self.folder_id = folder_id @@ -11609,20 +12249,21 @@ class SourceOptionsObject(object): """ Object that defines a Salesforce document object type crawl with this configuration. - :attr str name: The name of the Salesforce document object to crawl. For example, - `case`. - :attr int limit: (optional) The maximum number of documents to crawl for this document - object. By default, all documents in the document object are crawled. + :attr str name: The name of the Salesforce document object to crawl. For + example, `case`. + :attr int limit: (optional) The maximum number of documents to crawl for this + document object. By default, all documents in the document object are crawled. """ - def __init__(self, name, limit=None): + def __init__(self, name, *, limit=None): """ Initialize a SourceOptionsObject object. - :param str name: The name of the Salesforce document object to crawl. For example, - `case`. - :param int limit: (optional) The maximum number of documents to crawl for this - document object. By default, all documents in the document object are crawled. + :param str name: The name of the Salesforce document object to crawl. For + example, `case`. + :param int limit: (optional) The maximum number of documents to crawl for + this document object. By default, all documents in the document object are + crawled. """ self.name = name self.limit = limit @@ -11676,22 +12317,24 @@ class SourceOptionsSiteColl(object): Object that defines a Microsoft SharePoint site collection to crawl with this configuration. - :attr str site_collection_path: The Microsoft SharePoint Online site collection path - to crawl. The path must be be relative to the **organization_url** that was specified - in the credentials associated with this source configuration. - :attr int limit: (optional) The maximum number of documents to crawl for this site - collection. By default, all documents in the site collection are crawled. + :attr str site_collection_path: The Microsoft SharePoint Online site collection + path to crawl. The path must be be relative to the **organization_url** that was + specified in the credentials associated with this source configuration. + :attr int limit: (optional) The maximum number of documents to crawl for this + site collection. By default, all documents in the site collection are crawled. """ - def __init__(self, site_collection_path, limit=None): + def __init__(self, site_collection_path, *, limit=None): """ Initialize a SourceOptionsSiteColl object. - :param str site_collection_path: The Microsoft SharePoint Online site collection - path to crawl. The path must be be relative to the **organization_url** that was - specified in the credentials associated with this source configuration. - :param int limit: (optional) The maximum number of documents to crawl for this - site collection. By default, all documents in the site collection are crawled. + :param str site_collection_path: The Microsoft SharePoint Online site + collection path to crawl. The path must be be relative to the + **organization_url** that was specified in the credentials associated with + this source configuration. + :param int limit: (optional) The maximum number of documents to crawl for + this site collection. By default, all documents in the site collection are + crawled. """ self.site_collection_path = site_collection_path self.limit = limit @@ -11746,33 +12389,35 @@ class SourceOptionsWebCrawl(object): Object defining which URL to crawl and how to crawl it. :attr str url: The starting URL to crawl. - :attr bool limit_to_starting_hosts: (optional) When `true`, crawls of the specified - URL are limited to the host part of the **url** field. - :attr str crawl_speed: (optional) The number of concurrent URLs to fetch. `gentle` - means one URL is fetched at a time with a delay between each call. `normal` means as - many as two URLs are fectched concurrently with a short delay between fetch calls. - `aggressive` means that up to ten URLs are fetched concurrently with a short delay - between fetch calls. - :attr bool allow_untrusted_certificate: (optional) When `true`, allows the crawl to - interact with HTTPS sites with SSL certificates with untrusted signers. - :attr int maximum_hops: (optional) The maximum number of hops to make from the initial - URL. When a page is crawled each link on that page will also be crawled if it is - within the **maximum_hops** from the initial URL. The first page crawled is 0 hops, - each link crawled from the first page is 1 hop, each link crawled from those pages is - 2 hops, and so on. - :attr int request_timeout: (optional) The maximum milliseconds to wait for a response - from the web server. - :attr bool override_robots_txt: (optional) When `true`, the crawler will ignore any - `robots.txt` encountered by the crawler. This should only ever be done when crawling a - web site the user owns. This must be be set to `true` when a **gateway_id** is specied - in the **credentials**. - :attr list[str] blacklist: (optional) Array of URL's to be excluded while crawling. - The crawler will not follow links which contains this string. For example, listing - `https://ibm.com/watson` also excludes `https://ibm.com/watson/discovery`. + :attr bool limit_to_starting_hosts: (optional) When `true`, crawls of the + specified URL are limited to the host part of the **url** field. + :attr str crawl_speed: (optional) The number of concurrent URLs to fetch. + `gentle` means one URL is fetched at a time with a delay between each call. + `normal` means as many as two URLs are fectched concurrently with a short delay + between fetch calls. `aggressive` means that up to ten URLs are fetched + concurrently with a short delay between fetch calls. + :attr bool allow_untrusted_certificate: (optional) When `true`, allows the crawl + to interact with HTTPS sites with SSL certificates with untrusted signers. + :attr int maximum_hops: (optional) The maximum number of hops to make from the + initial URL. When a page is crawled each link on that page will also be crawled + if it is within the **maximum_hops** from the initial URL. The first page + crawled is 0 hops, each link crawled from the first page is 1 hop, each link + crawled from those pages is 2 hops, and so on. + :attr int request_timeout: (optional) The maximum milliseconds to wait for a + response from the web server. + :attr bool override_robots_txt: (optional) When `true`, the crawler will ignore + any `robots.txt` encountered by the crawler. This should only ever be done when + crawling a web site the user owns. This must be be set to `true` when a + **gateway_id** is specied in the **credentials**. + :attr list[str] blacklist: (optional) Array of URL's to be excluded while + crawling. The crawler will not follow links which contains this string. For + example, listing `https://ibm.com/watson` also excludes + `https://ibm.com/watson/discovery`. """ def __init__(self, url, + *, limit_to_starting_hosts=None, crawl_speed=None, allow_untrusted_certificate=None, @@ -11785,29 +12430,30 @@ def __init__(self, :param str url: The starting URL to crawl. :param bool limit_to_starting_hosts: (optional) When `true`, crawls of the - specified URL are limited to the host part of the **url** field. + specified URL are limited to the host part of the **url** field. :param str crawl_speed: (optional) The number of concurrent URLs to fetch. - `gentle` means one URL is fetched at a time with a delay between each call. - `normal` means as many as two URLs are fectched concurrently with a short delay - between fetch calls. `aggressive` means that up to ten URLs are fetched - concurrently with a short delay between fetch calls. - :param bool allow_untrusted_certificate: (optional) When `true`, allows the crawl - to interact with HTTPS sites with SSL certificates with untrusted signers. - :param int maximum_hops: (optional) The maximum number of hops to make from the - initial URL. When a page is crawled each link on that page will also be crawled if - it is within the **maximum_hops** from the initial URL. The first page crawled is - 0 hops, each link crawled from the first page is 1 hop, each link crawled from - those pages is 2 hops, and so on. - :param int request_timeout: (optional) The maximum milliseconds to wait for a - response from the web server. - :param bool override_robots_txt: (optional) When `true`, the crawler will ignore - any `robots.txt` encountered by the crawler. This should only ever be done when - crawling a web site the user owns. This must be be set to `true` when a - **gateway_id** is specied in the **credentials**. + `gentle` means one URL is fetched at a time with a delay between each call. + `normal` means as many as two URLs are fectched concurrently with a short + delay between fetch calls. `aggressive` means that up to ten URLs are + fetched concurrently with a short delay between fetch calls. + :param bool allow_untrusted_certificate: (optional) When `true`, allows the + crawl to interact with HTTPS sites with SSL certificates with untrusted + signers. + :param int maximum_hops: (optional) The maximum number of hops to make from + the initial URL. When a page is crawled each link on that page will also be + crawled if it is within the **maximum_hops** from the initial URL. The + first page crawled is 0 hops, each link crawled from the first page is 1 + hop, each link crawled from those pages is 2 hops, and so on. + :param int request_timeout: (optional) The maximum milliseconds to wait for + a response from the web server. + :param bool override_robots_txt: (optional) When `true`, the crawler will + ignore any `robots.txt` encountered by the crawler. This should only ever + be done when crawling a web site the user owns. This must be be set to + `true` when a **gateway_id** is specied in the **credentials**. :param list[str] blacklist: (optional) Array of URL's to be excluded while - crawling. The crawler will not follow links which contains this string. For - example, listing `https://ibm.com/watson` also excludes - `https://ibm.com/watson/discovery`. + crawling. The crawler will not follow links which contains this string. For + example, listing `https://ibm.com/watson` also excludes + `https://ibm.com/watson/discovery`. """ self.url = url self.limit_to_starting_hosts = limit_to_starting_hosts @@ -11897,41 +12543,59 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class CrawlSpeedEnum(Enum): + """ + The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a + time with a delay between each call. `normal` means as many as two URLs are + fectched concurrently with a short delay between fetch calls. `aggressive` means + that up to ten URLs are fetched concurrently with a short delay between fetch + calls. + """ + GENTLE = "gentle" + NORMAL = "normal" + AGGRESSIVE = "aggressive" + class SourceSchedule(object): """ Object containing the schedule information for the source. - :attr bool enabled: (optional) When `true`, the source is re-crawled based on the - **frequency** field in this object. When `false` the source is not re-crawled; When - `false` and connecting to Salesforce the source is crawled annually. - :attr str time_zone: (optional) The time zone to base source crawl times on. Possible - values correspond to the IANA (Internet Assigned Numbers Authority) time zones list. - :attr str frequency: (optional) The crawl schedule in the specified **time_zone**. - - `five_minutes`: Runs every five minutes. - - `hourly`: Runs every hour. - - `daily`: Runs every day between 00:00 and 06:00. - - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - - `monthly`: Runs the on the first Sunday of every month between 00:00 and 06:00. - """ - - def __init__(self, enabled=None, time_zone=None, frequency=None): + :attr bool enabled: (optional) When `true`, the source is re-crawled based on + the **frequency** field in this object. When `false` the source is not + re-crawled; When `false` and connecting to Salesforce the source is crawled + annually. + :attr str time_zone: (optional) The time zone to base source crawl times on. + Possible values correspond to the IANA (Internet Assigned Numbers Authority) + time zones list. + :attr str frequency: (optional) The crawl schedule in the specified + **time_zone**. + - `five_minutes`: Runs every five minutes. + - `hourly`: Runs every hour. + - `daily`: Runs every day between 00:00 and 06:00. + - `weekly`: Runs every week on Sunday between 00:00 and 06:00. + - `monthly`: Runs the on the first Sunday of every month between 00:00 and + 06:00. + """ + + def __init__(self, *, enabled=None, time_zone=None, frequency=None): """ Initialize a SourceSchedule object. - :param bool enabled: (optional) When `true`, the source is re-crawled based on the - **frequency** field in this object. When `false` the source is not re-crawled; - When `false` and connecting to Salesforce the source is crawled annually. - :param str time_zone: (optional) The time zone to base source crawl times on. - Possible values correspond to the IANA (Internet Assigned Numbers Authority) time - zones list. + :param bool enabled: (optional) When `true`, the source is re-crawled based + on the **frequency** field in this object. When `false` the source is not + re-crawled; When `false` and connecting to Salesforce the source is crawled + annually. + :param str time_zone: (optional) The time zone to base source crawl times + on. Possible values correspond to the IANA (Internet Assigned Numbers + Authority) time zones list. :param str frequency: (optional) The crawl schedule in the specified - **time_zone**. - - `five_minutes`: Runs every five minutes. - - `hourly`: Runs every hour. - - `daily`: Runs every day between 00:00 and 06:00. - - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - - `monthly`: Runs the on the first Sunday of every month between 00:00 and 06:00. + **time_zone**. + - `five_minutes`: Runs every five minutes. + - `hourly`: Runs every hour. + - `daily`: Runs every day between 00:00 and 06:00. + - `weekly`: Runs every week on Sunday between 00:00 and 06:00. + - `monthly`: Runs the on the first Sunday of every month between 00:00 and + 06:00. """ self.enabled = enabled self.time_zone = time_zone @@ -11980,37 +12644,53 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class FrequencyEnum(Enum): + """ + The crawl schedule in the specified **time_zone**. + - `five_minutes`: Runs every five minutes. + - `hourly`: Runs every hour. + - `daily`: Runs every day between 00:00 and 06:00. + - `weekly`: Runs every week on Sunday between 00:00 and 06:00. + - `monthly`: Runs the on the first Sunday of every month between 00:00 and 06:00. + """ + DAILY = "daily" + WEEKLY = "weekly" + MONTHLY = "monthly" + FIVE_MINUTES = "five_minutes" + HOURLY = "hourly" + class SourceStatus(object): """ Object containing source crawl status information. :attr str status: (optional) The current status of the source crawl for this - collection. This field returns `not_configured` if the default configuration for this - source does not have a **source** object defined. - - `running` indicates that a crawl to fetch more documents is in progress. - - `complete` indicates that the crawl has completed with no errors. - - `queued` indicates that the crawl has been paused by the system and will - automatically restart when possible. - - `unknown` indicates that an unidentified error has occured in the service. - :attr datetime next_crawl: (optional) Date in `RFC 3339` format indicating the time of - the next crawl attempt. + collection. This field returns `not_configured` if the default configuration for + this source does not have a **source** object defined. + - `running` indicates that a crawl to fetch more documents is in progress. + - `complete` indicates that the crawl has completed with no errors. + - `queued` indicates that the crawl has been paused by the system and will + automatically restart when possible. + - `unknown` indicates that an unidentified error has occured in the service. + :attr datetime next_crawl: (optional) Date in `RFC 3339` format indicating the + time of the next crawl attempt. """ - def __init__(self, status=None, next_crawl=None): + def __init__(self, *, status=None, next_crawl=None): """ Initialize a SourceStatus object. - :param str status: (optional) The current status of the source crawl for this - collection. This field returns `not_configured` if the default configuration for - this source does not have a **source** object defined. - - `running` indicates that a crawl to fetch more documents is in progress. - - `complete` indicates that the crawl has completed with no errors. - - `queued` indicates that the crawl has been paused by the system and will - automatically restart when possible. - - `unknown` indicates that an unidentified error has occured in the service. - :param datetime next_crawl: (optional) Date in `RFC 3339` format indicating the - time of the next crawl attempt. + :param str status: (optional) The current status of the source crawl for + this collection. This field returns `not_configured` if the default + configuration for this source does not have a **source** object defined. + - `running` indicates that a crawl to fetch more documents is in progress. + - `complete` indicates that the crawl has completed with no errors. + - `queued` indicates that the crawl has been paused by the system and will + automatically restart when possible. + - `unknown` indicates that an unidentified error has occured in the + service. + :param datetime next_crawl: (optional) Date in `RFC 3339` format indicating + the time of the next crawl attempt. """ self.status = status self.next_crawl = next_crawl @@ -12054,17 +12734,35 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The current status of the source crawl for this collection. This field returns + `not_configured` if the default configuration for this source does not have a + **source** object defined. + - `running` indicates that a crawl to fetch more documents is in progress. + - `complete` indicates that the crawl has completed with no errors. + - `queued` indicates that the crawl has been paused by the system and will + automatically restart when possible. + - `unknown` indicates that an unidentified error has occured in the service. + """ + RUNNING = "running" + COMPLETE = "complete" + NOT_CONFIGURED = "not_configured" + QUEUED = "queued" + UNKNOWN = "unknown" + class Term(object): """ Term. :attr str field: (optional) The field where the aggregation is located in the - document. + document. :attr int count: (optional) """ def __init__(self, + *, type=None, results=None, matching_results=None, @@ -12074,14 +12772,15 @@ def __init__(self, """ Initialize a Term object. - :param str type: (optional) The type of aggregation command used. For example: - term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation results. + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param list[AggregationResult] results: (optional) Array of aggregation + results. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations returned by - Discovery. - :param str field: (optional) The field where the aggregation is located in the - document. + :param list[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. :param int count: (optional) """ self.field = field @@ -12131,18 +12830,21 @@ class TestDocument(object): """ TestDocument. - :attr str configuration_id: (optional) The unique identifier for the configuration. + :attr str configuration_id: (optional) The unique identifier for the + configuration. :attr str status: (optional) Status of the preview operation. - :attr int enriched_field_units: (optional) The number of 10-kB chunks of field data - that were enriched. This can be used to estimate the cost of running a real ingestion. + :attr int enriched_field_units: (optional) The number of 10-kB chunks of field + data that were enriched. This can be used to estimate the cost of running a real + ingestion. :attr str original_media_type: (optional) Format of the test document. - :attr list[DocumentSnapshot] snapshots: (optional) An array of objects that describe - each step in the preview process. - :attr list[Notice] notices: (optional) An array of notice messages about the preview - operation. + :attr list[DocumentSnapshot] snapshots: (optional) An array of objects that + describe each step in the preview process. + :attr list[Notice] notices: (optional) An array of notice messages about the + preview operation. """ def __init__(self, + *, configuration_id=None, status=None, enriched_field_units=None, @@ -12153,16 +12855,16 @@ def __init__(self, Initialize a TestDocument object. :param str configuration_id: (optional) The unique identifier for the - configuration. + configuration. :param str status: (optional) Status of the preview operation. - :param int enriched_field_units: (optional) The number of 10-kB chunks of field - data that were enriched. This can be used to estimate the cost of running a real - ingestion. + :param int enriched_field_units: (optional) The number of 10-kB chunks of + field data that were enriched. This can be used to estimate the cost of + running a real ingestion. :param str original_media_type: (optional) Format of the test document. - :param list[DocumentSnapshot] snapshots: (optional) An array of objects that - describe each step in the preview process. - :param list[Notice] notices: (optional) An array of notice messages about the - preview operation. + :param list[DocumentSnapshot] snapshots: (optional) An array of objects + that describe each step in the preview process. + :param list[Notice] notices: (optional) An array of notice messages about + the preview operation. """ self.configuration_id = configuration_id self.status = status @@ -12243,16 +12945,17 @@ class Timeslice(object): Timeslice. :attr str field: (optional) The field where the aggregation is located in the - document. - :attr str interval: (optional) Interval of the aggregation. Valid date interval values - are second/seconds minute/minutes, hour/hours, day/days, week/weeks, month/months, and - year/years. + document. + :attr str interval: (optional) Interval of the aggregation. Valid date interval + values are second/seconds minute/minutes, hour/hours, day/days, week/weeks, + month/months, and year/years. :attr bool anomaly: (optional) Used to indicate that anomaly detection should be - performed. Anomaly detection is used to locate unusual datapoints within a time - series. + performed. Anomaly detection is used to locate unusual datapoints within a time + series. """ def __init__(self, + *, type=None, results=None, matching_results=None, @@ -12263,20 +12966,21 @@ def __init__(self, """ Initialize a Timeslice object. - :param str type: (optional) The type of aggregation command used. For example: - term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation results. + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param list[AggregationResult] results: (optional) Array of aggregation + results. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations returned by - Discovery. - :param str field: (optional) The field where the aggregation is located in the - document. - :param str interval: (optional) Interval of the aggregation. Valid date interval - values are second/seconds minute/minutes, hour/hours, day/days, week/weeks, - month/months, and year/years. - :param bool anomaly: (optional) Used to indicate that anomaly detection should be - performed. Anomaly detection is used to locate unusual datapoints within a time - series. + :param list[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. + :param str interval: (optional) Interval of the aggregation. Valid date + interval values are second/seconds minute/minutes, hour/hours, day/days, + week/weeks, month/months, and year/years. + :param bool anomaly: (optional) Used to indicate that anomaly detection + should be performed. Anomaly detection is used to locate unusual datapoints + within a time series. """ self.field = field self.interval = interval @@ -12332,24 +13036,24 @@ class TokenDictRule(object): :attr str text: The string to tokenize. :attr list[str] tokens: Array of tokens that the `text` field is split into when - found. - :attr list[str] readings: (optional) Array of tokens that represent the content of the - `text` field in an alternate character set. - :attr str part_of_speech: The part of speech that the `text` string belongs to. For - example `noun`. Custom parts of speech can be specified. + found. + :attr list[str] readings: (optional) Array of tokens that represent the content + of the `text` field in an alternate character set. + :attr str part_of_speech: The part of speech that the `text` string belongs to. + For example `noun`. Custom parts of speech can be specified. """ - def __init__(self, text, tokens, part_of_speech, readings=None): + def __init__(self, text, tokens, part_of_speech, *, readings=None): """ Initialize a TokenDictRule object. :param str text: The string to tokenize. - :param list[str] tokens: Array of tokens that the `text` field is split into when - found. - :param str part_of_speech: The part of speech that the `text` string belongs to. - For example `noun`. Custom parts of speech can be specified. - :param list[str] readings: (optional) Array of tokens that represent the content - of the `text` field in an alternate character set. + :param list[str] tokens: Array of tokens that the `text` field is split + into when found. + :param str part_of_speech: The part of speech that the `text` string + belongs to. For example `noun`. Custom parts of speech can be specified. + :param list[str] readings: (optional) Array of tokens that represent the + content of the `text` field in an alternate character set. """ self.text = text self.tokens = tokens @@ -12419,19 +13123,20 @@ class TokenDictStatusResponse(object): """ Object describing the current status of the wordlist. - :attr str status: (optional) Current wordlist status for the specified collection. + :attr str status: (optional) Current wordlist status for the specified + collection. :attr str type: (optional) The type for this wordlist. Can be - `tokenization_dictionary` or `stopwords`. + `tokenization_dictionary` or `stopwords`. """ - def __init__(self, status=None, type=None): + def __init__(self, *, status=None, type=None): """ Initialize a TokenDictStatusResponse object. :param str status: (optional) Current wordlist status for the specified - collection. + collection. :param str type: (optional) The type for this wordlist. Can be - `tokenization_dictionary` or `stopwords`. + `tokenization_dictionary` or `stopwords`. """ self.status = status self.type = type @@ -12475,6 +13180,14 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + Current wordlist status for the specified collection. + """ + ACTIVE = "active" + PENDING = "pending" + NOT_FOUND = "not found" + class TopHits(object): """ @@ -12485,6 +13198,7 @@ class TopHits(object): """ def __init__(self, + *, type=None, results=None, matching_results=None, @@ -12494,12 +13208,13 @@ def __init__(self, """ Initialize a TopHits object. - :param str type: (optional) The type of aggregation command used. For example: - term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation results. + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param list[AggregationResult] results: (optional) Array of aggregation + results. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations returned by - Discovery. + :param list[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. :param int size: (optional) Number of top hits returned by the aggregation. :param TopHitsResults hits: (optional) """ @@ -12551,15 +13266,17 @@ class TopHitsResults(object): TopHitsResults. :attr int matching_results: (optional) Number of matching results. - :attr list[QueryResult] hits: (optional) Top results returned by the aggregation. + :attr list[QueryResult] hits: (optional) Top results returned by the + aggregation. """ - def __init__(self, matching_results=None, hits=None): + def __init__(self, *, matching_results=None, hits=None): """ Initialize a TopHitsResults object. :param int matching_results: (optional) Number of matching results. - :param list[QueryResult] hits: (optional) Top results returned by the aggregation. + :param list[QueryResult] hits: (optional) Top results returned by the + aggregation. """ self.matching_results = matching_results self.hits = hits @@ -12611,21 +13328,22 @@ class TrainingDataSet(object): """ TrainingDataSet. - :attr str environment_id: (optional) The environment id associated with this training - data set. - :attr str collection_id: (optional) The collection id associated with this training - data set. + :attr str environment_id: (optional) The environment id associated with this + training data set. + :attr str collection_id: (optional) The collection id associated with this + training data set. :attr list[TrainingQuery] queries: (optional) Array of training queries. """ - def __init__(self, environment_id=None, collection_id=None, queries=None): + def __init__(self, *, environment_id=None, collection_id=None, + queries=None): """ Initialize a TrainingDataSet object. - :param str environment_id: (optional) The environment id associated with this - training data set. + :param str environment_id: (optional) The environment id associated with + this training data set. :param str collection_id: (optional) The collection id associated with this - training data set. + training data set. :param list[TrainingQuery] queries: (optional) Array of training queries. """ self.environment_id = environment_id @@ -12683,20 +13401,24 @@ class TrainingExample(object): TrainingExample. :attr str document_id: (optional) The document ID associated with this training - example. + example. :attr str cross_reference: (optional) The cross reference associated with this - training example. + training example. :attr int relevance: (optional) The relevance of the training example. """ - def __init__(self, document_id=None, cross_reference=None, relevance=None): + def __init__(self, + *, + document_id=None, + cross_reference=None, + relevance=None): """ Initialize a TrainingExample object. - :param str document_id: (optional) The document ID associated with this training - example. - :param str cross_reference: (optional) The cross reference associated with this - training example. + :param str document_id: (optional) The document ID associated with this + training example. + :param str cross_reference: (optional) The cross reference associated with + this training example. :param int relevance: (optional) The relevance of the training example. """ self.document_id = document_id @@ -12755,11 +13477,12 @@ class TrainingExampleList(object): :attr list[TrainingExample] examples: (optional) Array of training examples. """ - def __init__(self, examples=None): + def __init__(self, *, examples=None): """ Initialize a TrainingExampleList object. - :param list[TrainingExample] examples: (optional) Array of training examples. + :param list[TrainingExample] examples: (optional) Array of training + examples. """ self.examples = examples @@ -12806,14 +13529,15 @@ class TrainingQuery(object): TrainingQuery. :attr str query_id: (optional) The query ID associated with the training query. - :attr str natural_language_query: (optional) The natural text query for the training - query. + :attr str natural_language_query: (optional) The natural text query for the + training query. :attr str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + **natural_language_query** is applied. :attr list[TrainingExample] examples: (optional) Array of training examples. """ def __init__(self, + *, query_id=None, natural_language_query=None, filter=None, @@ -12821,12 +13545,14 @@ def __init__(self, """ Initialize a TrainingQuery object. - :param str query_id: (optional) The query ID associated with the training query. - :param str natural_language_query: (optional) The natural text query for the - training query. + :param str query_id: (optional) The query ID associated with the training + query. + :param str natural_language_query: (optional) The natural text query for + the training query. :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. - :param list[TrainingExample] examples: (optional) Array of training examples. + **natural_language_query** is applied. + :param list[TrainingExample] examples: (optional) Array of training + examples. """ self.query_id = query_id self.natural_language_query = natural_language_query @@ -12888,25 +13614,28 @@ class TrainingStatus(object): """ TrainingStatus. - :attr int total_examples: (optional) The total number of training examples uploaded to - this collection. - :attr bool available: (optional) When `true`, the collection has been successfully - trained. - :attr bool processing: (optional) When `true`, the collection is currently processing - training. + :attr int total_examples: (optional) The total number of training examples + uploaded to this collection. + :attr bool available: (optional) When `true`, the collection has been + successfully trained. + :attr bool processing: (optional) When `true`, the collection is currently + processing training. :attr bool minimum_queries_added: (optional) When `true`, the collection has a - sufficent amount of queries added for training to occur. + sufficent amount of queries added for training to occur. :attr bool minimum_examples_added: (optional) When `true`, the collection has a - sufficent amount of examples added for training to occur. - :attr bool sufficient_label_diversity: (optional) When `true`, the collection has a - sufficent amount of diversity in labeled results for training to occur. - :attr int notices: (optional) The number of notices associated with this data set. - :attr datetime successfully_trained: (optional) The timestamp of when the collection - was successfully trained. - :attr datetime data_updated: (optional) The timestamp of when the data was uploaded. + sufficent amount of examples added for training to occur. + :attr bool sufficient_label_diversity: (optional) When `true`, the collection + has a sufficent amount of diversity in labeled results for training to occur. + :attr int notices: (optional) The number of notices associated with this data + set. + :attr datetime successfully_trained: (optional) The timestamp of when the + collection was successfully trained. + :attr datetime data_updated: (optional) The timestamp of when the data was + uploaded. """ def __init__(self, + *, total_examples=None, available=None, processing=None, @@ -12920,23 +13649,24 @@ def __init__(self, Initialize a TrainingStatus object. :param int total_examples: (optional) The total number of training examples - uploaded to this collection. + uploaded to this collection. :param bool available: (optional) When `true`, the collection has been - successfully trained. + successfully trained. :param bool processing: (optional) When `true`, the collection is currently - processing training. - :param bool minimum_queries_added: (optional) When `true`, the collection has a - sufficent amount of queries added for training to occur. - :param bool minimum_examples_added: (optional) When `true`, the collection has a - sufficent amount of examples added for training to occur. - :param bool sufficient_label_diversity: (optional) When `true`, the collection has - a sufficent amount of diversity in labeled results for training to occur. - :param int notices: (optional) The number of notices associated with this data - set. + processing training. + :param bool minimum_queries_added: (optional) When `true`, the collection + has a sufficent amount of queries added for training to occur. + :param bool minimum_examples_added: (optional) When `true`, the collection + has a sufficent amount of examples added for training to occur. + :param bool sufficient_label_diversity: (optional) When `true`, the + collection has a sufficent amount of diversity in labeled results for + training to occur. + :param int notices: (optional) The number of notices associated with this + data set. :param datetime successfully_trained: (optional) The timestamp of when the - collection was successfully trained. + collection was successfully trained. :param datetime data_updated: (optional) The timestamp of when the data was - uploaded. + uploaded. """ self.total_examples = total_examples self.available = available @@ -13037,7 +13767,7 @@ class WordHeadingDetection(object): :attr list[WordStyle] styles: (optional) """ - def __init__(self, fonts=None, styles=None): + def __init__(self, *, fonts=None, styles=None): """ Initialize a WordHeadingDetection object. @@ -13098,7 +13828,7 @@ class WordSettings(object): :attr WordHeadingDetection heading: (optional) """ - def __init__(self, heading=None): + def __init__(self, *, heading=None): """ Initialize a WordSettings object. @@ -13147,17 +13877,17 @@ class WordStyle(object): """ WordStyle. - :attr int level: (optional) HTML head level that content matching this style is tagged - with. + :attr int level: (optional) HTML head level that content matching this style is + tagged with. :attr list[str] names: (optional) Array of word style names to convert. """ - def __init__(self, level=None, names=None): + def __init__(self, *, level=None, names=None): """ Initialize a WordStyle object. - :param int level: (optional) HTML head level that content matching this style is - tagged with. + :param int level: (optional) HTML head level that content matching this + style is tagged with. :param list[str] names: (optional) Array of word style names to convert. """ self.level = level @@ -13210,7 +13940,7 @@ class XPathPatterns(object): :attr list[str] xpaths: (optional) An array to XPaths. """ - def __init__(self, xpaths=None): + def __init__(self, *, xpaths=None): """ Initialize a XPathPatterns object. From aa31284ad832c5a46ec73090813dc87b520f11a3 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 20:20:20 -0400 Subject: [PATCH 014/455] test(discovery): Update discovery examples --- examples/discovery_v1.py | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/examples/discovery_v1.py b/examples/discovery_v1.py index 0d8d00893..9a7c4fc3f 100644 --- a/examples/discovery_v1.py +++ b/examples/discovery_v1.py @@ -1,21 +1,13 @@ -# coding: utf-8 -from __future__ import print_function import json from ibm_watson import DiscoveryV1 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -# If service instance provides API key authentication +authenticator = IAMAuthenticator('your_api_key') discovery = DiscoveryV1( version='2018-08-01', ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/discovery/api', - iam_apikey='YOUR APIKEY') - -# discovery = DiscoveryV1( -# version='2018-08-01', -# ## url is optional, and defaults to the URL below. Use the correct URL for your region. -# # url='https://gateway.watsonplatform.net/discovery/api', -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD') + authenticator=authenticator) environments = discovery.list_environments().get_result() print(json.dumps(environments, indent=2)) From 65607ace0b334fa74622feaaf198d9a1d4743cfe Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 20:43:06 -0400 Subject: [PATCH 015/455] test(discovery): Update discoevry unit tests --- test/unit/test_discovery_v1.py | 268 +++++++++++++++++---------------- 1 file changed, 141 insertions(+), 127 deletions(-) diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index f97f13bb0..529cc9563 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -8,11 +8,9 @@ from unittest import TestCase import ibm_watson from ibm_watson.discovery_v1 import TrainingDataSet, TrainingQuery, TrainingExample +from ibm_cloud_sdk_core.authenticators import BasicAuthenticator, IAMAuthenticator -try: - from urllib.parse import urlparse, urljoin -except ImportError: - from urlparse import urlparse, urljoin +from urllib.parse import urlparse, urljoin base_discovery_url = 'https://gateway.watsonplatform.net/discovery/api/v1/' @@ -94,12 +92,11 @@ def test_environments(cls): body=discovery_response_body, status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) discovery.list_environments() - url_str = "{0}?version=2016-11-07".format(discovery_url) + url_str = "{0}?version=2018-08-13".format(discovery_url) assert responses.calls[0].request.url == url_str assert responses.calls[0].response.text == discovery_response_body @@ -113,11 +110,11 @@ def test_get_environment(cls): body="{\"resulting_key\": true}", status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery.get_environment(environment_id='envid') - url_str = "{0}?version=2016-11-07".format(discovery_url) + url_str = "{0}?version=2018-08-13".format(discovery_url) assert responses.calls[0].request.url == url_str assert len(responses.calls) == 1 @@ -131,9 +128,8 @@ def test_create_environment(cls): body="{\"resulting_key\": true}", status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) discovery.create_environment(name="my name", description="my description") assert len(responses.calls) == 1 @@ -147,9 +143,9 @@ def test_update_environment(cls): body="{\"resulting_key\": true}", status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery.update_environment('envid', name="hello", description="new") assert len(responses.calls) == 1 @@ -162,9 +158,9 @@ def test_delete_environment(cls): body="{\"resulting_key\": true}", status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery.delete_environment('envid') assert len(responses.calls) == 1 @@ -179,9 +175,9 @@ def test_collections(cls): body="{\"body\": \"hello\"}", status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery.list_collections('envid') called_url = urlparse(responses.calls[0].request.url) @@ -227,9 +223,9 @@ def test_collection(cls): status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery.create_collection(environment_id='envid', name="name", description="", @@ -264,10 +260,11 @@ def test_federated_query(cls): responses.add(responses.POST, discovery_url, body="{\"body\": \"hello\"}", status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') - discovery.federated_query('envid', 'colls.sha1::9181d244*', collection_ids=['collid1', 'collid2']) + + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + + discovery.federated_query('envid', filter='colls.sha1::9181d244*', collection_ids=['collid1', 'collid2']) called_url = urlparse(responses.calls[0].request.url) test_url = urlparse(discovery_url) @@ -285,7 +282,10 @@ def test_federated_query_2(cls): responses.add(responses.POST, discovery_url, body="{\"body\": \"hello\"}", status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', username='username', password='password') + + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery.federated_query('envid', collection_ids="'collid1', 'collid2'", filter='colls.sha1::9181d244*', bias='1', @@ -307,7 +307,8 @@ def test_federated_query_notices(cls): responses.add(responses.GET, discovery_url, body="{\"body\": \"hello\"}", status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', username='username', password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) discovery.federated_query_notices('envid', collection_ids=['collid1', 'collid2'], filter='notices.sha1::9181d244*') called_url = urlparse(responses.calls[0].request.url) @@ -326,9 +327,8 @@ def test_query(cls): responses.add(responses.POST, discovery_url, body="{\"body\": \"hello\"}", status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) discovery.query('envid', 'collid', filter='extracted_metadata.sha1::9181d244*', count=1, @@ -353,9 +353,8 @@ def test_query_2(cls): responses.add(responses.POST, discovery_url, body="{\"body\": \"hello\"}", status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) discovery.query('envid', 'collid', filter='extracted_metadata.sha1::9181d244*', count=1, @@ -387,8 +386,8 @@ def test_query_relations(cls): status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1( - '2016-11-07', username='username', password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) discovery.query_relations('envid', 'collid', count=10) called_url = urlparse(responses.calls[0].request.url) @@ -412,10 +411,10 @@ def test_query_entities(cls): status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1( - '2016-11-07', username='username', password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) - discovery.query_entities('envid', 'collid', {'count': 10}) + discovery.query_entities('envid', 'collid', count={'count': 10}) called_url = urlparse(responses.calls[0].request.url) test_url = urlparse(discovery_url) assert called_url.netloc == test_url.netloc @@ -436,8 +435,8 @@ def test_query_notices(cls): status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1( - '2016-11-07', username='username', password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) discovery.query_notices('envid', 'collid', filter='notices.sha1::*') called_url = urlparse(responses.calls[0].request.url) @@ -479,9 +478,8 @@ def test_configs(cls): status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) discovery.list_configurations(environment_id='envid') discovery.get_configuration(environment_id='envid', @@ -523,9 +521,8 @@ def test_document(cls): status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) html_path = os.path.join(os.getcwd(), 'resources', 'simple.html') with open(html_path) as fileinfo: conf_id = discovery.test_configuration_in_environment(environment_id='envid', @@ -642,9 +639,11 @@ def test_delete_all_training_data(cls): url = '{0}{1}'.format(base_url, endpoint) responses.add(responses.DELETE, url, status=204) - service = ibm_watson.DiscoveryV1(version, username='username', password='password') - response = service.delete_all_training_data(environment_id=environment_id, - collection_id=collection_id).get_result() + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + + response = discovery.delete_all_training_data(environment_id=environment_id, + collection_id=collection_id).get_result() assert response is None @@ -679,11 +678,11 @@ def test_list_training_data(cls): status=200, content_type='application/json') - service = ibm_watson.DiscoveryV1(version, - username='username', - password='password') - response = service.list_training_data(environment_id=environment_id, - collection_id=collection_id).get_result() + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + + response = discovery.list_training_data(environment_id=environment_id, + collection_id=collection_id).get_result() assert response == mock_response # Verify that response can be converted to a TrainingDataSet @@ -727,10 +726,10 @@ def test_add_training_data(cls): status=200, content_type='application/json') - service = ibm_watson.DiscoveryV1(version, - username='username', - password='password') - response = service.add_training_data( + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + + response = discovery.add_training_data( environment_id=environment_id, collection_id=collection_id, natural_language_query=natural_language_query, @@ -752,12 +751,12 @@ def test_delete_training_data(cls): url = '{0}{1}'.format(base_url, endpoint) responses.add(responses.DELETE, url, status=204) - service = ibm_watson.DiscoveryV1(version, - username='username', - password='password') - response = service.delete_training_data(environment_id=environment_id, - collection_id=collection_id, - query_id=query_id).get_result() + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + + response = discovery.delete_training_data(environment_id=environment_id, + collection_id=collection_id, + query_id=query_id).get_result() assert response is None @@ -788,10 +787,11 @@ def test_get_training_data(cls): status=200, content_type='application/json') - service = ibm_watson.DiscoveryV1(version, username='username', password='password') - response = service.get_training_data(environment_id=environment_id, - collection_id=collection_id, - query_id=query_id).get_result() + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + response = discovery.get_training_data(environment_id=environment_id, + collection_id=collection_id, + query_id=query_id).get_result() assert response == mock_response # Verify that response can be converted to a TrainingQuery @@ -821,10 +821,10 @@ def test_create_training_example(cls): status=201, content_type='application/json') - service = ibm_watson.DiscoveryV1(version, - username='username', - password='password') - response = service.create_training_example( + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + + response = discovery.create_training_example( environment_id=environment_id, collection_id=collection_id, query_id=query_id, @@ -851,8 +851,9 @@ def test_delete_training_example(cls): url = '{0}{1}'.format(base_url, endpoint) responses.add(responses.DELETE, url, status=204) - service = ibm_watson.DiscoveryV1(version, username='username', password='password') - response = service.delete_training_example( + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + response = discovery.delete_training_example( environment_id=environment_id, collection_id=collection_id, query_id=query_id, @@ -884,8 +885,10 @@ def test_get_training_example(cls): status=200, content_type='application/json') - service = ibm_watson.DiscoveryV1(version, username='username', password='password') - response = service.get_training_example( + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + + response = discovery.get_training_example( environment_id=environment_id, collection_id=collection_id, query_id=query_id, @@ -921,10 +924,10 @@ def test_update_training_example(cls): status=200, content_type='application/json') - service = ibm_watson.DiscoveryV1(version, - username='username', - password='password') - response = service.update_training_example( + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + + response = discovery.update_training_example( environment_id=environment_id, collection_id=collection_id, query_id=query_id, @@ -959,7 +962,8 @@ def test_expansions(cls): status=200, content_type='application_json') - discovery = ibm_watson.DiscoveryV1('2017-11-07', username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) discovery.list_expansions('envid', 'colid') assert responses.calls[0].response.json() == {"expansions": "results"} @@ -983,7 +987,8 @@ def test_delete_user_data(cls): status=204, content_type='application_json') - discovery = ibm_watson.DiscoveryV1('2017-11-07', username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) response = discovery.delete_user_data('id').get_result() assert response is None @@ -1001,31 +1006,33 @@ def test_credentials(cls): 'credential_type': 'username_password', 'username':'user@email.com'} } - discovery = ibm_watson.DiscoveryV1('2016-11-07', iam_apikey='iam_apikey') - responses.add(responses.GET, "{0}/{1}?version=2016-11-07".format(discovery_credentials_url, 'credential_id'), + authenticator = IAMAuthenticator('iam_apikey') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + + responses.add(responses.GET, "{0}/{1}?version=2018-08-13".format(discovery_credentials_url, 'credential_id'), body=json.dumps(results), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2016-11-07".format(discovery_credentials_url), + responses.add(responses.GET, "{0}?version=2018-08-13".format(discovery_credentials_url), body=json.dumps([results]), status=200, content_type='application/json') - responses.add(responses.POST, "{0}?version=2016-11-07".format(discovery_credentials_url), + responses.add(responses.POST, "{0}?version=2018-08-13".format(discovery_credentials_url), body=json.dumps(results), status=200, content_type='application/json') results['source_type'] = 'ibm' - responses.add(responses.PUT, "{0}/{1}?version=2016-11-07".format(discovery_credentials_url, 'credential_id'), + responses.add(responses.PUT, "{0}/{1}?version=2018-08-13".format(discovery_credentials_url, 'credential_id'), body=json.dumps(results), status=200, content_type='application/json') - responses.add(responses.DELETE, "{0}/{1}?version=2016-11-07".format(discovery_credentials_url, 'credential_id'), + responses.add(responses.DELETE, "{0}/{1}?version=2018-08-13".format(discovery_credentials_url, 'credential_id'), body=json.dumps({'deleted': 'bogus -- ok'}), status=200, content_type='application/json') - discovery.create_credentials('envid', 'salesforce', { + discovery.create_credentials('envid', source_type='salesforce', credential_details={ 'url': 'https://login.salesforce.com', 'credential_type': 'username_password', 'username':'user@email.com' @@ -1135,65 +1142,68 @@ def test_events_and_feedback(cls): ] } - responses.add(responses.POST, "{0}?version=2016-11-07".format(discovery_event_url), + responses.add(responses.POST, "{0}?version=2018-08-13".format(discovery_event_url), body=json.dumps(create_event_response), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2016-11-07".format(discovery_metrics_event_rate_url), + responses.add(responses.GET, "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document".format(discovery_metrics_event_rate_url), body=json.dumps(metric_response), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2016-11-07".format(discovery_metrics_query_url), + responses.add(responses.GET, "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document".format(discovery_metrics_query_url), body=json.dumps(metric_response), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2016-11-07".format(discovery_metrics_query_event_url), + responses.add(responses.GET, "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document".format(discovery_metrics_query_event_url), body=json.dumps(metric_response), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2016-11-07".format(discovery_metrics_query_no_results_url), + responses.add(responses.GET, "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document".format(discovery_metrics_query_no_results_url), body=json.dumps(metric_response), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2016-11-07".format(discovery_metrics_query_token_event_url), + responses.add(responses.GET, "{0}?version=2018-08-13&count=2".format(discovery_metrics_query_token_event_url), body=json.dumps(metric_token_response), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2016-11-07".format(discovery_query_log_url), + responses.add(responses.GET, "{0}?version=2018-08-13".format(discovery_query_log_url), body=json.dumps(log_query_response), status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', iam_apikey='iam_apikey') + authenticator = IAMAuthenticator('iam_apikey') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) discovery.create_event('click', event_data) assert responses.calls[1].response.json()["data"] == event_data - discovery.get_metrics_event_rate('2018-08-13T14:39:59.309Z', - '2018-08-14T14:39:59.309Z', - 'document') + discovery.get_metrics_event_rate(start_time='2018-08-13T14:39:59.309Z', + end_time='2018-08-14T14:39:59.309Z', + result_type='document') assert responses.calls[3].response.json() == metric_response - discovery.get_metrics_query('2018-08-13T14:39:59.309Z', - '2018-08-14T14:39:59.309Z', - 'document') + discovery.get_metrics_query(start_time='2018-08-13T14:39:59.309Z', + end_time='2018-08-14T14:39:59.309Z', + result_type='document') assert responses.calls[5].response.json() == metric_response - discovery.get_metrics_query_event('2018-08-13T14:39:59.309Z', - '2018-08-14T14:39:59.309Z', - 'document') + discovery.get_metrics_query_event( + start_time='2018-08-13T14:39:59.309Z', + end_time='2018-08-14T14:39:59.309Z', + result_type='document') assert responses.calls[7].response.json() == metric_response - discovery.get_metrics_query_no_results('2018-08-13T14:39:59.309Z', - '2018-08-14T14:39:59.309Z', - 'document') + discovery.get_metrics_query_no_results( + start_time='2018-08-13T14:39:59.309Z', + end_time='2018-08-14T14:39:59.309Z', + result_type='document') assert responses.calls[9].response.json() == metric_response - discovery.get_metrics_query_token_event(2) + discovery.get_metrics_query_token_event(count=2) assert responses.calls[11].response.json() == metric_token_response discovery.query_log() @@ -1204,7 +1214,7 @@ def test_events_and_feedback(cls): @classmethod @responses.activate def test_tokenization_dictionary(cls): - url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/word_lists/tokenization_dictionary?version=2017-11-07' + url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/word_lists/tokenization_dictionary?version=2018-08-13' responses.add( responses.POST, url, @@ -1223,7 +1233,8 @@ def test_tokenization_dictionary(cls): status=200, content_type='application_json') - discovery = ibm_watson.DiscoveryV1('2017-11-07', username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) tokenization_rules = [ { @@ -1233,7 +1244,8 @@ def test_tokenization_dictionary(cls): 'part_of_speech': 'noun', } ] - discovery.create_tokenization_dictionary('envid', 'colid', tokenization_rules) + + discovery.create_tokenization_dictionary('envid', 'colid', tokenization_rules=tokenization_rules) assert responses.calls[0].response.json() == {"status": "pending"} discovery.get_tokenization_dictionary_status('envid', 'colid') @@ -1247,7 +1259,7 @@ def test_tokenization_dictionary(cls): @classmethod @responses.activate def test_stopword_operations(cls): - url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/word_lists/stopwords?version=2017-11-07' + url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/word_lists/stopwords?version=2018-08-13' responses.add( responses.POST, url, @@ -1265,7 +1277,8 @@ def test_stopword_operations(cls): status=200, content_type='application_json') - discovery = ibm_watson.DiscoveryV1('2017-11-07', username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) stopwords_file_path = os.path.join(os.getcwd(), 'resources', 'stopwords.txt') with open(stopwords_file_path) as file: @@ -1294,26 +1307,27 @@ def test_gateway_configuration(cls): "gateway_id": "gateway_id" } - responses.add(responses.GET, "{0}/{1}?version=2016-11-07".format(discovery_gateway_url, 'gateway_id'), + responses.add(responses.GET, "{0}/{1}?version=2018-08-13".format(discovery_gateway_url, 'gateway_id'), body=json.dumps(gateway_details), status=200, content_type='application/json') - responses.add(responses.POST, "{0}?version=2016-11-07".format(discovery_gateway_url), + responses.add(responses.POST, "{0}?version=2018-08-13".format(discovery_gateway_url), body=json.dumps(gateway_details), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2016-11-07".format(discovery_gateway_url), + responses.add(responses.GET, "{0}?version=2018-08-13".format(discovery_gateway_url), body=json.dumps({'gateways': [gateway_details]}), status=200, content_type='application/json') - responses.add(responses.DELETE, "{0}/{1}?version=2016-11-07".format(discovery_gateway_url, 'gateway_id'), + responses.add(responses.DELETE, "{0}/{1}?version=2018-08-13".format(discovery_gateway_url, 'gateway_id'), body=json.dumps({'gateway_id': 'gateway_id', 'status': 'deleted'}), status=200, content_type='application/json') - discovery = ibm_watson.DiscoveryV1('2016-11-07', iam_apikey='iam_apikey') + authenticator = IAMAuthenticator('iam_apikey') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) - discovery.create_gateway('envid', 'gateway_id') + discovery.create_gateway('envid', name='gateway_id') discovery.list_gateways('envid') discovery.get_gateway('envid', 'gateway_id') discovery.delete_gateway(environment_id='envid', gateway_id='gateway_id') From 68b762518079ec87355a80de40cca02485e72bec Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 20:53:34 -0400 Subject: [PATCH 016/455] test(discovery): Update discovery unit tests --- test/integration/test_discovery_v1.py | 39 ++++++++++++++------------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/test/integration/test_discovery_v1.py b/test/integration/test_discovery_v1.py index 1f3a19f70..f48ad353f 100644 --- a/test/integration/test_discovery_v1.py +++ b/test/integration/test_discovery_v1.py @@ -41,12 +41,15 @@ def test_environments(self): def test_configurations(self): configs = self.discovery.list_configurations(self.environment_id).get_result() + + self.discovery.delete_configuration(self.environment_id,'26506c92-31db-411c-87b3-68b987781f4a') + self.discovery.delete_configuration(self.environment_id,'bfb6230c-3b4c-4b9f-82bd-237fabb78124') assert configs is not None name = 'test' + random.choice('ABCDEFGHIJKLMNOPQ') new_configuration_id = self.discovery.create_configuration( self.environment_id, name, - 'creating new config for python sdk').get_result()['configuration_id'] + 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() @@ -128,8 +131,8 @@ def test_credentials(self): 'password': 'xxx' } credentials = self.discovery.create_credentials(self.environment_id, - 'salesforce', - credential_details).get_result() + source_type='salesforce', + credential_details=credential_details).get_result() assert credentials['credential_id'] is not None credential_id = credentials['credential_id'] @@ -145,7 +148,7 @@ def test_credentials(self): 'username': 'user@email.com', 'password': 'xxx' } - updated_credentials = self.discovery.update_credentials(self.environment_id, credential_id, 'salesforce', 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() @@ -193,27 +196,27 @@ def test_tokenization_dictionary(self): assert result['status'] is not None def test_feedback(self): - response = self.discovery.get_metrics_event_rate('2018-08-13T14:39:59.309Z', - '2018-08-14T14:39:59.309Z', - '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('2018-08-13T14:39:59.309Z', - '2018-08-14T14:39:59.309Z', - '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('2018-08-13T14:39:59.309Z', - '2018-08-14T14:39:59.309Z', - '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('2018-07-13T14:39:59.309Z', - '2018-08-14T14:39:59.309Z', - '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(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() @@ -238,7 +241,7 @@ def test_stopword_operations(self): def test_gateway_configuration(self): create_gateway_result = self.discovery.create_gateway( self.environment_id, - 'test-gateway-configuration-python' + name='test-gateway-configuration-python' ).get_result() assert create_gateway_result['gateway_id'] is not None From 9c1dac20675026d6b853b0d39e69b01c9d7e6973 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 20:54:32 -0400 Subject: [PATCH 017/455] feat(language translator): Generate language translator --- ibm_watson/language_translator_v3.py | 507 +++++++++++++++------------ 1 file changed, 289 insertions(+), 218 deletions(-) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 6b9fd8fce..b8c88cde8 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,12 +21,12 @@ language, and more. """ -from __future__ import absolute_import - import json from .common import get_sdk_headers +from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime +from ibm_cloud_sdk_core import get_authenticator_from_environment from os.path import basename ############################################################################## @@ -43,16 +43,8 @@ def __init__( self, version, url=default_url, - username=None, - password=None, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, + authenticator=None, + disable_ssl_verification=False, ): """ Construct a new client for the Language Translator service. @@ -72,81 +64,46 @@ def __init__( "https://gateway.watsonplatform.net/language-translator/api/language-translator/api"). The base url may differ between IBM Cloud regions. - :param str username: The username used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str password: The password used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ + if not authenticator: + authenticator = get_authenticator_from_environment( + 'Language Translator') + BaseService.__init__( self, - vcap_services_name='language_translator', url=url, - username=username, - password=password, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Language Translator', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Language Translator') self.version = version ######################### # Translation ######################### - def translate(self, text, model_id=None, source=None, target=None, + def translate(self, + text, + *, + model_id=None, + source=None, + target=None, **kwargs): """ Translate. Translates the input text from the source language to the target language. - :param list[str] text: Input text in UTF-8 encoding. Multiple entries will result - in multiple translations in the response. - :param str model_id: A globally unique string that identifies the underlying model - that is used for translation. - :param str source: Translation source language code. - :param str target: Translation target language code. + :param list[str] text: Input text in UTF-8 encoding. Multiple entries will + result in multiple translations in the response. + :param str model_id: (optional) A globally unique string that identifies + the underlying model that is used for translation. + :param str source: (optional) Translation source language code. + :param str target: (optional) Translation target language code. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -171,13 +128,14 @@ def translate(self, text, model_id=None, source=None, target=None, } url = '/v3/translate' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response ######################### @@ -206,12 +164,13 @@ def list_identifiable_languages(self, **kwargs): params = {'version': self.version} url = '/v3/identifiable_languages' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def identify(self, text, **kwargs): @@ -241,36 +200,35 @@ def identify(self, text, **kwargs): headers['content-type'] = 'text/plain' url = '/v3/identify' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=True) + response = self.send(request) return response ######################### # Models ######################### - def list_models(self, - source=None, - target=None, - default_models=None, - **kwargs): + def list_models(self, *, source=None, target=None, default=None, **kwargs): """ List models. Lists available translation models. - :param str source: Specify a language code to filter results by source language. - :param str target: Specify a language code to filter results by target language. - :param bool default_models: If the default parameter isn't specified, the service - will return all models (default and non-default) for each language pair. To return - only default models, set this to `true`. To return only non-default models, set - this to `false`. There is exactly one default model per language pair, the IBM - provided base model. + :param str source: (optional) Specify a language code to filter results by + source language. + :param str target: (optional) Specify a language code to filter results by + target language. + :param bool default: (optional) If the default parameter isn't specified, + the service will return all models (default and non-default) for each + language pair. To return only default models, set this to `true`. To return + only non-default models, set this to `false`. There is exactly one default + model per language pair, the IBM provided base model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -287,20 +245,22 @@ def list_models(self, 'version': self.version, 'source': source, 'target': target, - 'default': default_models + 'default': default } url = '/v3/models' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def create_model(self, base_model_id, + *, forced_glossary=None, parallel_corpus=None, name=None, @@ -323,22 +283,24 @@ def create_model(self, You can have a maximum of 10 custom models per language pair. :param str base_model_id: The model ID of the model to use as the base for - customization. To see available models, use the `List models` method. Usually all - IBM provided models are customizable. In addition, all your models that have been - created via parallel corpus customization, can be further customized with a forced - glossary. - :param file forced_glossary: A TMX file with your customizations. The - customizations in the file completely overwrite the domain translaton data, - including high frequency or high confidence phrase translations. You can upload - only one glossary with a file size less than 10 MB per call. A forced glossary - should contain single words or short phrases. - :param file parallel_corpus: A TMX file with parallel sentences for source and - target language. You can upload multiple parallel_corpus files in one request. All - uploaded parallel_corpus files combined, your parallel corpus must contain at - least 5,000 parallel sentences to train successfully. - :param str name: An optional model name that you can use to identify the model. - Valid characters are letters, numbers, dashes, underscores, spaces and - apostrophes. The maximum length is 32 characters. + customization. To see available models, use the `List models` method. + Usually all IBM provided models are customizable. In addition, all your + models that have been created via parallel corpus customization, can be + further customized with a forced glossary. + :param file forced_glossary: (optional) A TMX file with your + customizations. The customizations in the file completely overwrite the + domain translaton data, including high frequency or high confidence phrase + translations. You can upload only one glossary with a file size less than + 10 MB per call. A forced glossary should contain single words or short + phrases. + :param file parallel_corpus: (optional) A TMX file with parallel sentences + for source and target language. You can upload multiple parallel_corpus + files in one request. All uploaded parallel_corpus files combined, your + parallel corpus must contain at least 5,000 parallel sentences to train + successfully. + :param str name: (optional) An optional model name that you can use to + identify the model. Valid characters are letters, numbers, dashes, + underscores, spaces and apostrophes. The maximum length is 32 characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -369,13 +331,14 @@ def create_model(self, 'application/octet-stream') url = '/v3/models' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response def delete_model(self, model_id, **kwargs): @@ -403,12 +366,13 @@ def delete_model(self, model_id, **kwargs): params = {'version': self.version} url = '/v3/models/{0}'.format(*self._encode_path_vars(model_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_model(self, model_id, **kwargs): @@ -437,12 +401,13 @@ def get_model(self, model_id, **kwargs): params = {'version': self.version} url = '/v3/models/{0}'.format(*self._encode_path_vars(model_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -470,16 +435,18 @@ def list_documents(self, **kwargs): params = {'version': self.version} url = '/v3/documents' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def translate_document(self, file, + *, filename=None, file_content_type=None, model_id=None, @@ -495,19 +462,20 @@ def translate_document(self, ID. :param file file: The source file to translate. - [Supported file - types](https://cloud.ibm.com/docs/services/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats) - Maximum file size: **20 MB**. - :param str filename: The filename for file. - :param str file_content_type: The content type of file. - :param str model_id: The model to use for translation. `model_id` or both `source` - and `target` are required. - :param str source: Language code that specifies the language of the source - document. - :param str target: Language code that specifies the target language for - translation. - :param str document_id: To use a previously submitted document as the source for a - new translation, enter the `document_id` of the document. + [Supported file + types](https://cloud.ibm.com/docs/services/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats) + Maximum file size: **20 MB**. + :param str filename: (optional) The filename for file. + :param str file_content_type: (optional) The content type of file. + :param str model_id: (optional) The model to use for translation. + `model_id` or both `source` and `target` are required. + :param str source: (optional) Language code that specifies the language of + the source document. + :param str target: (optional) Language code that specifies the target + language for translation. + :param str document_id: (optional) To use a previously submitted document + as the source for a new translation, enter the `document_id` of the + document. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -542,13 +510,14 @@ def translate_document(self, form_data['document_id'] = (None, document_id, 'text/plain') url = '/v3/documents' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response def get_document_status(self, document_id, **kwargs): @@ -576,12 +545,13 @@ def get_document_status(self, document_id, **kwargs): params = {'version': self.version} url = '/v3/documents/{0}'.format(*self._encode_path_vars(document_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def delete_document(self, document_id, **kwargs): @@ -609,36 +579,37 @@ def delete_document(self, document_id, **kwargs): params = {'version': self.version} url = '/v3/documents/{0}'.format(*self._encode_path_vars(document_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response - def get_translated_document(self, document_id, accept=None, **kwargs): + def get_translated_document(self, document_id, *, accept=None, **kwargs): """ Get translated document. Gets the translated document associated with the given document ID. - :param str document_id: The document ID of the document that was submitted for - translation. - :param str accept: The type of the response: application/powerpoint, - application/mspowerpoint, application/x-rtf, application/json, application/xml, - application/vnd.ms-excel, - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, - application/vnd.ms-powerpoint, - application/vnd.openxmlformats-officedocument.presentationml.presentation, - application/msword, - application/vnd.openxmlformats-officedocument.wordprocessingml.document, - application/vnd.oasis.opendocument.spreadsheet, - application/vnd.oasis.opendocument.presentation, - application/vnd.oasis.opendocument.text, application/pdf, application/rtf, - text/html, text/json, text/plain, text/richtext, text/rtf, or text/xml. A - character encoding can be specified by including a `charset` parameter. For - example, 'text/html;charset=utf-8'. + :param str document_id: The document ID of the document that was submitted + for translation. + :param str accept: (optional) The type of the response: + application/powerpoint, application/mspowerpoint, application/x-rtf, + application/json, application/xml, application/vnd.ms-excel, + application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, + application/vnd.ms-powerpoint, + application/vnd.openxmlformats-officedocument.presentationml.presentation, + application/msword, + application/vnd.openxmlformats-officedocument.wordprocessingml.document, + application/vnd.oasis.opendocument.spreadsheet, + application/vnd.oasis.opendocument.presentation, + application/vnd.oasis.opendocument.text, application/pdf, application/rtf, + text/html, text/json, text/plain, text/richtext, text/rtf, or text/xml. A + character encoding can be specified by including a `charset` parameter. For + example, 'text/html;charset=utf-8'. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -658,15 +629,88 @@ def get_translated_document(self, document_id, accept=None, **kwargs): url = '/v3/documents/{0}/translated_document'.format( *self._encode_path_vars(document_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=(accept is None or accept == 'application/json')) + response = self.send(request) return response +class TranslateDocumentEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_POWERPOINT = 'application/powerpoint' + APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' + APPLICATION_X_RTF = 'application/x-rtf' + APPLICATION_JSON = 'application/json' + APPLICATION_XML = 'application/xml' + APPLICATION_VND_MS_EXCEL = 'application/vnd.ms-excel' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + APPLICATION_VND_MS_POWERPOINT = 'application/vnd.ms-powerpoint' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = 'application/vnd.openxmlformats-officedocument.presentationml.presentation' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' + APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' + APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' + APPLICATION_PDF = 'application/pdf' + APPLICATION_RTF = 'application/rtf' + TEXT_HTML = 'text/html' + TEXT_JSON = 'text/json' + TEXT_PLAIN = 'text/plain' + TEXT_RICHTEXT = 'text/richtext' + TEXT_RTF = 'text/rtf' + TEXT_XML = 'text/xml' + + +class GetTranslatedDocumentEnums(object): + + class Accept(Enum): + """ + The type of the response: application/powerpoint, application/mspowerpoint, + application/x-rtf, application/json, application/xml, application/vnd.ms-excel, + application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, + application/vnd.ms-powerpoint, + application/vnd.openxmlformats-officedocument.presentationml.presentation, + application/msword, + application/vnd.openxmlformats-officedocument.wordprocessingml.document, + application/vnd.oasis.opendocument.spreadsheet, + application/vnd.oasis.opendocument.presentation, + application/vnd.oasis.opendocument.text, application/pdf, application/rtf, + text/html, text/json, text/plain, text/richtext, text/rtf, or text/xml. A + character encoding can be specified by including a `charset` parameter. For + example, 'text/html;charset=utf-8'. + """ + APPLICATION_POWERPOINT = 'application/powerpoint' + APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' + APPLICATION_X_RTF = 'application/x-rtf' + APPLICATION_JSON = 'application/json' + APPLICATION_XML = 'application/xml' + APPLICATION_VND_MS_EXCEL = 'application/vnd.ms-excel' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + APPLICATION_VND_MS_POWERPOINT = 'application/vnd.ms-powerpoint' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = 'application/vnd.openxmlformats-officedocument.presentationml.presentation' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' + APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' + APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' + APPLICATION_PDF = 'application/pdf' + APPLICATION_RTF = 'application/rtf' + TEXT_HTML = 'text/html' + TEXT_JSON = 'text/json' + TEXT_PLAIN = 'text/plain' + TEXT_RICHTEXT = 'text/richtext' + TEXT_RTF = 'text/rtf' + TEXT_XML = 'text/xml' + + ############################################################################## # Models ############################################################################## @@ -731,7 +775,8 @@ class DocumentList(object): """ DocumentList. - :attr list[DocumentStatus] documents: An array of all previously submitted documents. + :attr list[DocumentStatus] documents: An array of all previously submitted + documents. """ def __init__(self, documents): @@ -739,7 +784,7 @@ def __init__(self, documents): Initialize a DocumentList object. :param list[DocumentStatus] documents: An array of all previously submitted - documents. + documents. """ self.documents = documents @@ -789,25 +834,25 @@ class DocumentStatus(object): """ Document information, including translation status. - :attr str document_id: System generated ID identifying a document being translated - using one specific translation model. + :attr str document_id: System generated ID identifying a document being + translated using one specific translation model. :attr str filename: filename from the submission (if it was missing in the - multipart-form, 'noname.' is used. + multipart-form, 'noname.' is used. :attr str status: The status of the translation job associated with a submitted - document. - :attr str model_id: A globally unique string that identifies the underlying model that - is used for translation. + document. + :attr str model_id: A globally unique string that identifies the underlying + model that is used for translation. :attr str base_model_id: (optional) Model ID of the base model that was used to - customize the model. If the model is not a custom model, this will be absent or an - empty string. + customize the model. If the model is not a custom model, this will be absent or + an empty string. :attr str source: Translation source language code. :attr str target: Translation target language code. :attr datetime created: The time when the document was submitted. :attr datetime completed: (optional) The time when the translation completed. - :attr int word_count: (optional) The number of words in the source document, present - only if status=available. - :attr int character_count: (optional) The number of characters in the source document, - present only if status=available. + :attr int word_count: (optional) The number of words in the source document, + present only if status=available. + :attr int character_count: (optional) The number of characters in the source + document, present only if status=available. """ def __init__(self, @@ -818,6 +863,7 @@ def __init__(self, source, target, created, + *, base_model_id=None, completed=None, word_count=None, @@ -826,24 +872,25 @@ def __init__(self, Initialize a DocumentStatus object. :param str document_id: System generated ID identifying a document being - translated using one specific translation model. + translated using one specific translation model. :param str filename: filename from the submission (if it was missing in the - multipart-form, 'noname.' is used. - :param str status: The status of the translation job associated with a submitted - document. - :param str model_id: A globally unique string that identifies the underlying model - that is used for translation. + multipart-form, 'noname.' is used. + :param str status: The status of the translation job associated with a + submitted document. + :param str model_id: A globally unique string that identifies the + underlying model that is used for translation. :param str source: Translation source language code. :param str target: Translation target language code. :param datetime created: The time when the document was submitted. - :param str base_model_id: (optional) Model ID of the base model that was used to - customize the model. If the model is not a custom model, this will be absent or an - empty string. - :param datetime completed: (optional) The time when the translation completed. - :param int word_count: (optional) The number of words in the source document, - present only if status=available. - :param int character_count: (optional) The number of characters in the source - document, present only if status=available. + :param str base_model_id: (optional) Model ID of the base model that was + used to customize the model. If the model is not a custom model, this will + be absent or an empty string. + :param datetime completed: (optional) The time when the translation + completed. + :param int word_count: (optional) The number of words in the source + document, present only if status=available. + :param int character_count: (optional) The number of characters in the + source document, present only if status=available. """ self.document_id = document_id self.filename = filename @@ -965,6 +1012,14 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The status of the translation job associated with a submitted document. + """ + PROCESSING = "processing" + AVAILABLE = "available" + FAILED = "failed" + class IdentifiableLanguage(object): """ @@ -1036,16 +1091,16 @@ class IdentifiableLanguages(object): """ IdentifiableLanguages. - :attr list[IdentifiableLanguage] languages: A list of all languages that the service - can identify. + :attr list[IdentifiableLanguage] languages: A list of all languages that the + service can identify. """ def __init__(self, languages): """ Initialize a IdentifiableLanguages object. - :param list[IdentifiableLanguage] languages: A list of all languages that the - service can identify. + :param list[IdentifiableLanguage] languages: A list of all languages that + the service can identify. """ self.languages = languages @@ -1163,15 +1218,15 @@ class IdentifiedLanguages(object): IdentifiedLanguages. :attr list[IdentifiedLanguage] languages: A ranking of identified languages with - confidence scores. + confidence scores. """ def __init__(self, languages): """ Initialize a IdentifiedLanguages object. - :param list[IdentifiedLanguage] languages: A ranking of identified languages with - confidence scores. + :param list[IdentifiedLanguage] languages: A ranking of identified + languages with confidence scores. """ self.languages = languages @@ -1222,30 +1277,29 @@ class Translation(object): """ Translation. - :attr str translation_output: Translation output in UTF-8. + :attr str translation: Translation output in UTF-8. """ - def __init__(self, translation_output): + def __init__(self, translation): """ Initialize a Translation object. - :param str translation_output: Translation output in UTF-8. + :param str translation: Translation output in UTF-8. """ - self.translation_output = translation_output + self.translation = translation @classmethod def _from_dict(cls, _dict): """Initialize a Translation object from a json dictionary.""" args = {} - validKeys = ['translation_output', 'translation'] + validKeys = ['translation'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: raise ValueError( 'Unrecognized keys detected in dictionary for class Translation: ' + ', '.join(badKeys)) - if 'translation' in _dict or 'translation_output' in _dict: - args['translation_output'] = _dict.get('translation') or _dict.get( - 'translation_output') + if 'translation' in _dict: + args['translation'] = _dict.get('translation') else: raise ValueError( 'Required property \'translation\' not present in Translation JSON' @@ -1255,10 +1309,8 @@ def _from_dict(cls, _dict): def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr( - self, - 'translation_output') and self.translation_output is not None: - _dict['translation'] = self.translation_output + if hasattr(self, 'translation') and self.translation is not None: + _dict['translation'] = self.translation return _dict def __str__(self): @@ -1280,28 +1332,30 @@ class TranslationModel(object): """ Response payload for models. - :attr str model_id: A globally unique string that identifies the underlying model that - is used for translation. + :attr str model_id: A globally unique string that identifies the underlying + model that is used for translation. :attr str name: (optional) Optional name that can be specified when the model is - created. + created. :attr str source: (optional) Translation source language code. :attr str target: (optional) Translation target language code. :attr str base_model_id: (optional) Model ID of the base model that was used to - customize the model. If the model is not a custom model, this will be an empty string. + customize the model. If the model is not a custom model, this will be an empty + string. :attr str domain: (optional) The domain of the translation model. :attr bool customizable: (optional) Whether this model can be used as a base for - customization. Customized models are not further customizable, and some base models - are not customizable. - :attr bool default_model: (optional) Whether or not the model is a default model. A - default model is the model for a given language pair that will be used when that - language pair is specified in the source and target parameters. - :attr str owner: (optional) Either an empty string, indicating the model is not a - custom model, or the ID of the service instance that created the model. + customization. Customized models are not further customizable, and some base + models are not customizable. + :attr bool default_model: (optional) Whether or not the model is a default + model. A default model is the model for a given language pair that will be used + when that language pair is specified in the source and target parameters. + :attr str owner: (optional) Either an empty string, indicating the model is not + a custom model, or the ID of the service instance that created the model. :attr str status: (optional) Availability of a model. """ def __init__(self, model_id, + *, name=None, source=None, target=None, @@ -1314,24 +1368,26 @@ def __init__(self, """ Initialize a TranslationModel object. - :param str model_id: A globally unique string that identifies the underlying model - that is used for translation. - :param str name: (optional) Optional name that can be specified when the model is - created. + :param str model_id: A globally unique string that identifies the + underlying model that is used for translation. + :param str name: (optional) Optional name that can be specified when the + model is created. :param str source: (optional) Translation source language code. :param str target: (optional) Translation target language code. - :param str base_model_id: (optional) Model ID of the base model that was used to - customize the model. If the model is not a custom model, this will be an empty - string. + :param str base_model_id: (optional) Model ID of the base model that was + used to customize the model. If the model is not a custom model, this will + be an empty string. :param str domain: (optional) The domain of the translation model. - :param bool customizable: (optional) Whether this model can be used as a base for - customization. Customized models are not further customizable, and some base - models are not customizable. - :param bool default_model: (optional) Whether or not the model is a default model. - A default model is the model for a given language pair that will be used when that - language pair is specified in the source and target parameters. - :param str owner: (optional) Either an empty string, indicating the model is not a - custom model, or the ID of the service instance that created the model. + :param bool customizable: (optional) Whether this model can be used as a + base for customization. Customized models are not further customizable, and + some base models are not customizable. + :param bool default_model: (optional) Whether or not the model is a default + model. A default model is the model for a given language pair that will be + used when that language pair is specified in the source and target + parameters. + :param str owner: (optional) Either an empty string, indicating the model + is not a custom model, or the ID of the service instance that created the + model. :param str status: (optional) Availability of a model. """ self.model_id = model_id @@ -1423,6 +1479,21 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + Availability of a model. + """ + UPLOADING = "uploading" + UPLOADED = "uploaded" + DISPATCHING = "dispatching" + QUEUED = "queued" + TRAINING = "training" + TRAINED = "trained" + PUBLISHING = "publishing" + AVAILABLE = "available" + DELETED = "deleted" + ERROR = "error" + class TranslationModels(object): """ @@ -1488,7 +1559,7 @@ class TranslationResult(object): :attr int word_count: Number of words in the input text. :attr int character_count: Number of characters in the input text. :attr list[Translation] translations: List of translation output in UTF-8, - corresponding to the input text entries. + corresponding to the input text entries. """ def __init__(self, word_count, character_count, translations): @@ -1498,7 +1569,7 @@ def __init__(self, word_count, character_count, translations): :param int word_count: Number of words in the input text. :param int character_count: Number of characters in the input text. :param list[Translation] translations: List of translation output in UTF-8, - corresponding to the input text entries. + corresponding to the input text entries. """ self.word_count = word_count self.character_count = character_count From 4a24a578435f4995b47b924e4819254689cbe88d Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 21:10:25 -0400 Subject: [PATCH 018/455] test( language translator): Update language translator unit tests --- test/unit/test_language_translator_v3.py | 54 ++++++++++-------------- 1 file changed, 23 insertions(+), 31 deletions(-) diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 6038d6bbb..a46144287 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -8,6 +8,7 @@ from os.path import join, dirname import ibm_watson from ibm_watson.language_translator_v3 import TranslationResult, TranslationModels, TranslationModel, IdentifiedLanguages, IdentifiableLanguages, DeleteModelResult +from ibm_cloud_sdk_core.authenticators import BasicAuthenticator, IAMAuthenticator platform_url = 'https://gateway.watsonplatform.net' service_path = '/language-translator/api' @@ -49,9 +50,8 @@ def setUp(cls): @classmethod @responses.activate def test_translate_source_target(cls): - service = ibm_watson.LanguageTranslatorV3( - version='2018-05-01', - iam_apikey='iam_apikey') + authenticator = IAMAuthenticator('apikey') + service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) endpoint = '/v3/translate' url = '{0}{1}'.format(base_url, endpoint) expected = { @@ -75,9 +75,8 @@ def test_translate_source_target(cls): @classmethod @responses.activate def test_translate_model_id(cls): - service = ibm_watson.LanguageTranslatorV3( - version='2018-05-01', - iam_apikey='iam_apikey') + authenticator = IAMAuthenticator('apikey') + service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) endpoint = '/v3/translate' url = '{0}{1}'.format(base_url, endpoint) expected = { @@ -106,9 +105,8 @@ def test_translate_model_id(cls): @classmethod @responses.activate def test_identify(cls): - service = ibm_watson.LanguageTranslatorV3( - version='2018-05-01', - iam_apikey='iam_apikey') + authenticator = IAMAuthenticator('apikey') + service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) endpoint = '/v3/identify' url = '{0}{1}'.format(base_url, endpoint) expected = { @@ -142,9 +140,8 @@ def test_identify(cls): @classmethod @responses.activate def test_list_identifiable_languages(cls): - service = ibm_watson.LanguageTranslatorV3( - version='2018-05-01', - iam_apikey='iam_apikey') + authenticator = IAMAuthenticator('apikey') + service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) endpoint = '/v3/identifiable_languages' url = '{0}{1}'.format(base_url, endpoint) expected = { @@ -190,11 +187,8 @@ def test_list_identifiable_languages(cls): @classmethod @responses.activate def test_create_model(cls): - service = ibm_watson.LanguageTranslatorV3( - version='2018-05-01', - username='xxx', - password='yyy' - ) + authenticator = BasicAuthenticator('xxx', 'yyy') + service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) endpoint = '/v3/models' url = '{0}{1}'.format(base_url, endpoint) expected = { @@ -227,9 +221,8 @@ def test_create_model(cls): @classmethod @responses.activate def test_delete_model(cls): - service = ibm_watson.LanguageTranslatorV3( - version='2018-05-01', - iam_apikey='iam_apikey') + authenticator = IAMAuthenticator('apikey') + service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) model_id = 'en-es-conversational' endpoint = '/v3/models/' + model_id url = '{0}{1}'.format(base_url, endpoint) @@ -251,9 +244,8 @@ def test_delete_model(cls): @classmethod @responses.activate def test_get_model(cls): - service = ibm_watson.LanguageTranslatorV3( - version='2018-05-01', - iam_apikey='iam_apikey') + authenticator = IAMAuthenticator('apikey') + service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) model_id = 'en-es-conversational' endpoint = '/v3/models/' + model_id url = '{0}{1}'.format(base_url, endpoint) @@ -284,9 +276,8 @@ def test_get_model(cls): @classmethod @responses.activate def test_list_models(cls): - service = ibm_watson.LanguageTranslatorV3( - version='2018-05-01', - iam_apikey='iam_apikey') + authenticator = IAMAuthenticator('apikey') + service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) endpoint = '/v3/models' url = '{0}{1}'.format(base_url, endpoint) expected = { @@ -360,16 +351,17 @@ def test_document_translation(cls): content_type='application_json') responses.add( responses.GET, - url + '/2a683723/translated_document?version=2017-11-07', + url + '/2a683723/translated_document?version=2018-05-01', body='binary response', status=200) responses.add( responses.GET, - url + '/2a683723?version=2017-11-07', + url + '/2a683723?version=2018-05-01', body=json.dumps(document_status), status=200, content_type='application_json') - language_translator = ibm_watson.LanguageTranslatorV3('2017-11-07', username="username", password="password") + authenticator = BasicAuthenticator('xxx', 'yyy') + language_translator = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) with open(join(dirname(__file__), '../../resources/hello_world.txt'), 'r') as fileinfo: translation = language_translator.translate_document( @@ -382,9 +374,9 @@ def test_document_translation(cls): assert status['documents'][0]['document_id'] == '2a683723' delete_result = language_translator.delete_document('2a683723').get_result() - assert delete_result.url == 'https://gateway.watsonplatform.net/language-translator/api/v3/documents/2a683723?version=2017-11-07' + assert delete_result is None - response = language_translator.get_translated_document('2a683723', 'text/plain').get_result() + response = language_translator.get_translated_document('2a683723', accept='text/plain').get_result() assert response.content is not None doc_status = language_translator.get_document_status('2a683723').get_result() From 7f8250d33bbdae0b3827262e33931c1fbe952a99 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 21:14:56 -0400 Subject: [PATCH 019/455] test( language translator): Update language translator examples --- examples/language_translator_v3.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/examples/language_translator_v3.py b/examples/language_translator_v3.py index bff612538..18d0cb49c 100644 --- a/examples/language_translator_v3.py +++ b/examples/language_translator_v3.py @@ -2,18 +2,14 @@ from __future__ import print_function import json from ibm_watson import LanguageTranslatorV3 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +authenticator = IAMAuthenticator('your_api_key') language_translator = LanguageTranslatorV3( version='2018-05-01', ### url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/language-translator/api', - iam_apikey='YOUR APIKEY') - -# Authenticate with username/password if your service instance doesn't provide an API key -# language_translator = LanguageTranslatorV3( -# version='2018-05-01', -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD') + authenticator=authenticator) ## Translate translation = language_translator.translate( From 96a33c61991e83b548ec055978fc497e69827c1b Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 21:16:06 -0400 Subject: [PATCH 020/455] feat(NLC): Generate natural language classifier --- ibm_watson/natural_language_classifier_v1.py | 205 ++++++++----------- 1 file changed, 91 insertions(+), 114 deletions(-) diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 5c5cae70d..25a4e480a 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -20,12 +20,12 @@ those classes to new inputs. """ -from __future__ import absolute_import - import json from .common import get_sdk_headers +from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime +from ibm_cloud_sdk_core import get_authenticator_from_environment ############################################################################## # Service @@ -40,16 +40,8 @@ class NaturalLanguageClassifierV1(BaseService): def __init__( self, url=default_url, - username=None, - password=None, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, + authenticator=None, + disable_ssl_verification=False, ): """ Construct a new client for the Natural Language Classifier service. @@ -58,62 +50,22 @@ def __init__( "https://gateway.watsonplatform.net/natural-language-classifier/api/natural-language-classifier/api"). The base url may differ between IBM Cloud regions. - :param str username: The username used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str password: The password used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ + if not authenticator: + authenticator = get_authenticator_from_environment( + 'Natural Language Classifier') + BaseService.__init__( self, - vcap_services_name='natural_language_classifier', url=url, - username=username, - password=password, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Natural Language Classifier', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Natural Language Classifier') ######################### # Classify text @@ -127,7 +79,8 @@ def classify(self, classifier_id, text, **kwargs): can use the classifier to classify text. :param str classifier_id: Classifier ID to use. - :param str text: The submitted phrase. The maximum length is 2048 characters. + :param str text: The submitted phrase. The maximum length is 2048 + characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -149,12 +102,13 @@ def classify(self, classifier_id, text, **kwargs): url = '/v1/classifiers/{0}/classify'.format( *self._encode_path_vars(classifier_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def classify_collection(self, classifier_id, collection, **kwargs): @@ -189,42 +143,44 @@ def classify_collection(self, classifier_id, collection, **kwargs): url = '/v1/classifiers/{0}/classify_collection'.format( *self._encode_path_vars(classifier_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, - json=data, + data=data, accept_json=True) + response = self.send(request) return response ######################### # Manage classifiers ######################### - def create_classifier(self, metadata, training_data, **kwargs): + def create_classifier(self, training_metadata, training_data, **kwargs): """ Create classifier. Sends data to create and train a classifier and returns information about the new classifier. - :param file metadata: Metadata in JSON format. The metadata identifies the - language of the data, and an optional name to identify the classifier. Specify the - language with the 2-letter primary language code as assigned in ISO standard 639. - Supported languages are English (`en`), Arabic (`ar`), French (`fr`), German, - (`de`), Italian (`it`), Japanese (`ja`), Korean (`ko`), Brazilian Portuguese - (`pt`), and Spanish (`es`). - :param file 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). + :param file training_metadata: Metadata in JSON format. The metadata + identifies the language of the data, and an optional name to identify the + classifier. Specify the language with the 2-letter primary language code as + assigned in ISO standard 639. + Supported languages are English (`en`), Arabic (`ar`), French (`fr`), + German, (`de`), Italian (`it`), Japanese (`ja`), Korean (`ko`), Brazilian + Portuguese (`pt`), and Spanish (`es`). + :param file 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). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse """ - if metadata is None: - raise ValueError('metadata must be provided') + if training_metadata is None: + raise ValueError('training_metadata must be provided') if training_data is None: raise ValueError('training_data must be provided') @@ -236,16 +192,18 @@ def create_classifier(self, metadata, training_data, **kwargs): headers.update(sdk_headers) form_data = {} - form_data['training_metadata'] = (None, metadata, 'application/json') + form_data['training_metadata'] = (None, training_metadata, + 'application/json') form_data['training_data'] = (None, training_data, 'text/csv') url = '/v1/classifiers' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, files=form_data, accept_json=True) + response = self.send(request) return response def list_classifiers(self, **kwargs): @@ -267,8 +225,9 @@ def list_classifiers(self, **kwargs): headers.update(sdk_headers) url = '/v1/classifiers' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def get_classifier(self, classifier_id, **kwargs): @@ -295,8 +254,9 @@ def get_classifier(self, classifier_id, **kwargs): url = '/v1/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def delete_classifier(self, classifier_id, **kwargs): @@ -321,8 +281,9 @@ def delete_classifier(self, classifier_id, **kwargs): url = '/v1/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, accept_json=True) + response = self.send(request) return response @@ -339,11 +300,12 @@ class Classification(object): :attr str url: (optional) Link to the classifier. :attr str text: (optional) The submitted phrase. :attr str top_class: (optional) The class with the highest confidence. - :attr list[ClassifiedClass] classes: (optional) An array of up to ten class-confidence - pairs sorted in descending order of confidence. + :attr list[ClassifiedClass] classes: (optional) An array of up to ten + class-confidence pairs sorted in descending order of confidence. """ def __init__(self, + *, classifier_id=None, url=None, text=None, @@ -357,7 +319,7 @@ def __init__(self, :param str text: (optional) The submitted phrase. :param str top_class: (optional) The class with the highest confidence. :param list[ClassifiedClass] classes: (optional) An array of up to ten - class-confidence pairs sorted in descending order of confidence. + class-confidence pairs sorted in descending order of confidence. """ self.classifier_id = classifier_id self.url = url @@ -425,18 +387,18 @@ class ClassificationCollection(object): :attr str classifier_id: (optional) Unique identifier for this classifier. :attr str url: (optional) Link to the classifier. - :attr list[CollectionItem] collection: (optional) An array of classifier responses for - each submitted phrase. + :attr list[CollectionItem] collection: (optional) An array of classifier + responses for each submitted phrase. """ - def __init__(self, classifier_id=None, url=None, collection=None): + def __init__(self, *, classifier_id=None, url=None, collection=None): """ Initialize a ClassificationCollection object. :param str classifier_id: (optional) Unique identifier for this classifier. :param str url: (optional) Link to the classifier. :param list[CollectionItem] collection: (optional) An array of classifier - responses for each submitted phrase. + responses for each submitted phrase. """ self.classifier_id = classifier_id self.url = url @@ -492,18 +454,19 @@ class ClassifiedClass(object): """ Class and confidence. - :attr float confidence: (optional) A decimal percentage that represents the confidence - that Watson has in this class. Higher values represent higher confidences. + :attr float confidence: (optional) A decimal percentage that represents the + confidence that Watson has in this class. Higher values represent higher + confidences. :attr str class_name: (optional) Class label. """ - def __init__(self, confidence=None, class_name=None): + def __init__(self, *, confidence=None, class_name=None): """ Initialize a ClassifiedClass object. - :param float confidence: (optional) A decimal percentage that represents the - confidence that Watson has in this class. Higher values represent higher - confidences. + :param float confidence: (optional) A decimal percentage that represents + the confidence that Watson has in this class. Higher values represent + higher confidences. :param str class_name: (optional) Class label. """ self.confidence = confidence @@ -557,7 +520,8 @@ class Classifier(object): :attr str url: Link to the classifier. :attr str status: (optional) The state of the classifier. :attr str classifier_id: Unique identifier for this classifier. - :attr datetime created: (optional) Date and time (UTC) the classifier was created. + :attr datetime created: (optional) Date and time (UTC) the classifier was + created. :attr str status_description: (optional) Additional detail about the status. :attr str language: (optional) The language used for the classifier. """ @@ -565,6 +529,7 @@ class Classifier(object): def __init__(self, url, classifier_id, + *, name=None, status=None, created=None, @@ -578,8 +543,9 @@ def __init__(self, :param str name: (optional) User-supplied name for the classifier. :param str status: (optional) The state of the classifier. :param datetime created: (optional) Date and time (UTC) the classifier was - created. - :param str status_description: (optional) Additional detail about the status. + created. + :param str status_description: (optional) Additional detail about the + status. :param str language: (optional) The language used for the classifier. """ self.name = name @@ -661,13 +627,23 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The state of the classifier. + """ + NON_EXISTENT = "Non Existent" + TRAINING = "Training" + FAILED = "Failed" + AVAILABLE = "Available" + UNAVAILABLE = "Unavailable" + class ClassifierList(object): """ List of available classifiers. - :attr list[Classifier] classifiers: The classifiers available to the user. Returns an - empty array if no classifiers are available. + :attr list[Classifier] classifiers: The classifiers available to the user. + Returns an empty array if no classifiers are available. """ def __init__(self, classifiers): @@ -675,7 +651,7 @@ def __init__(self, classifiers): Initialize a ClassifierList object. :param list[Classifier] classifiers: The classifiers available to the user. - Returns an empty array if no classifiers are available. + Returns an empty array if no classifiers are available. """ self.classifiers = classifiers @@ -732,7 +708,8 @@ def __init__(self, text): """ Initialize a ClassifyInput object. - :param str text: The submitted phrase. The maximum length is 2048 characters. + :param str text: The submitted phrase. The maximum length is 2048 + characters. """ self.text = text @@ -780,21 +757,21 @@ class CollectionItem(object): Response from the classifier for a phrase in a collection. :attr str text: (optional) The submitted phrase. The maximum length is 2048 - characters. + characters. :attr str top_class: (optional) The class with the highest confidence. - :attr list[ClassifiedClass] classes: (optional) An array of up to ten class-confidence - pairs sorted in descending order of confidence. + :attr list[ClassifiedClass] classes: (optional) An array of up to ten + class-confidence pairs sorted in descending order of confidence. """ - def __init__(self, text=None, top_class=None, classes=None): + def __init__(self, *, text=None, top_class=None, classes=None): """ Initialize a CollectionItem object. - :param str text: (optional) The submitted phrase. The maximum length is 2048 - characters. + :param str text: (optional) The submitted phrase. The maximum length is + 2048 characters. :param str top_class: (optional) The class with the highest confidence. :param list[ClassifiedClass] classes: (optional) An array of up to ten - class-confidence pairs sorted in descending order of confidence. + class-confidence pairs sorted in descending order of confidence. """ self.text = text self.top_class = top_class From cffd3f8c5b654a3b0b804af4ad772c33280c530b Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 23:12:36 -0400 Subject: [PATCH 021/455] test(nlc): Update natural language classifier unit tests --- test/unit/test_natural_language_classifier_v1.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index 8146d9c4d..5e923b18d 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -2,12 +2,13 @@ import os import responses import ibm_watson +from ibm_cloud_sdk_core.authenticators import BasicAuthenticator @responses.activate def test_success(): - natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1(username="username", - password="password") + authenticator = BasicAuthenticator('username', 'password') + natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1(authenticator=authenticator) list_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers' list_response = '{"classifiers": [{"url": "https://gateway.watsonplatform.net/natural-language-classifier-' \ @@ -64,7 +65,8 @@ def test_success(): content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../../resources/weather_data_train.csv'), 'rb') as training_data: natural_language_classifier.create_classifier( - training_data=training_data, metadata='{"language": "en"}') + training_metadata='{"language": "en"}', + training_data=training_data) assert responses.calls[3].request.url == create_url assert responses.calls[3].response.text == create_response @@ -85,8 +87,8 @@ def test_success(): @responses.activate def test_classify_collection(): - natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1(username="username", - password="password") + authenticator = BasicAuthenticator('username', 'password') + natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1(authenticator=authenticator) classify_collection_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/497EF2-nlc-00/classify_collection' classify_collection_response = '{ \ "classifier_id": "497EF2-nlc-00", \ From 8fdca7109d3b27d41f48804bb451d9f9971f3650 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 23:15:58 -0400 Subject: [PATCH 022/455] test(nlc): Update natural language classifier integration tests --- test/integration/test_natural_language_classifier_v1.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/integration/test_natural_language_classifier_v1.py b/test/integration/test_natural_language_classifier_v1.py index f9122be1f..a7506c45f 100644 --- a/test/integration/test_natural_language_classifier_v1.py +++ b/test/integration/test_natural_language_classifier_v1.py @@ -21,8 +21,8 @@ def setUp(self): 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( - metadata=metadata, - training_data=training_data + training_data=training_data, + training_metadata=metadata, ).get_result() self.classifier_id = classifier['classifier_id'] From 5732cb453903a8890d6e0026d95aa8010b2ab54a Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 23:23:32 -0400 Subject: [PATCH 023/455] test(nlc): Update natural language cllassifier examples --- examples/natural_language_classifier_v1.py | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/examples/natural_language_classifier_v1.py b/examples/natural_language_classifier_v1.py index 64183279d..5a8f1f6b1 100644 --- a/examples/natural_language_classifier_v1.py +++ b/examples/natural_language_classifier_v1.py @@ -1,21 +1,14 @@ -from __future__ import print_function import json import os -# from os.path import join, dirname from ibm_watson import NaturalLanguageClassifierV1 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -# If service instance provides API key authentication +authenticator = IAMAuthenticator('your_api_key') service = NaturalLanguageClassifierV1( ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/natural-language-classifier/api', - iam_apikey='YOUR APIKEY') - -# service = NaturalLanguageClassifierV1( -# ## url is optional, and defaults to the URL below. Use the correct URL for your region. -# # url='https://gateway.watsonplatform.net/natural-language-classifier/api', -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD') + authenticator=authenticator) classifiers = service.list_classifiers().get_result() print(json.dumps(classifiers, indent=2)) @@ -27,7 +20,7 @@ 'rb') as training_data: metadata = json.dumps({'name': 'my-classifier', 'language': 'en'}) classifier = service.create_classifier( - metadata=metadata, training_data=training_data).get_result() + training_metadata=metadata, training_data=training_data).get_result() classifier_id = classifier['classifier_id'] print(json.dumps(classifier, indent=2)) @@ -52,5 +45,5 @@ # example of raising a ValueError # print(json.dumps( -# service.create_classifier(training_data='', name='weather3', metadata='metadata'), +# service.create_classifier(training_data='', training_metadata='metadata'), # indent=2)) From 276ae93acafb0bef32b944f4691f60f71e013828 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 23:24:27 -0400 Subject: [PATCH 024/455] feat(NLU): Generate natural language understanding --- .../natural_language_understanding_v1.py | 1071 +++++++++-------- 1 file changed, 549 insertions(+), 522 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 71a91616c..f1e829101 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -24,12 +24,12 @@ Natural Language Understanding. """ -from __future__ import absolute_import - import json from .common import get_sdk_headers +from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime +from ibm_cloud_sdk_core import get_authenticator_from_environment ############################################################################## # Service @@ -45,16 +45,8 @@ def __init__( self, version, url=default_url, - username=None, - password=None, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, + authenticator=None, + disable_ssl_verification=False, ): """ Construct a new client for the Natural Language Understanding service. @@ -74,62 +66,22 @@ def __init__( "https://gateway.watsonplatform.net/natural-language-understanding/api/natural-language-understanding/api"). The base url may differ between IBM Cloud regions. - :param str username: The username used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str password: The password used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ + if not authenticator: + authenticator = get_authenticator_from_environment( + 'Natural Language Understanding') + BaseService.__init__( self, - vcap_services_name='natural-language-understanding', url=url, - username=username, - password=password, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Natural Language Understanding', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Natural Language Understanding') self.version = version ######################### @@ -138,6 +90,7 @@ def __init__( def analyze(self, features, + *, text=None, html=None, url=None, @@ -164,31 +117,33 @@ def analyze(self, - Syntax (Experimental). :param Features features: Specific features to analyze the document for. - :param str text: The plain text to analyze. One of the `text`, `html`, or `url` - parameters is required. - :param str html: The HTML file to analyze. One of the `text`, `html`, or `url` - parameters is required. - :param str url: The webpage to analyze. One of the `text`, `html`, or `url` - parameters is required. - :param bool clean: Set this to `false` to disable webpage cleaning. To learn more - about webpage cleaning, see the [Analyzing - webpages](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages) - documentation. - :param str xpath: An [XPath - query](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages#xpath) - to perform on `html` or `url` input. Results of the query will be appended to the - cleaned webpage text before it is analyzed. To analyze only the results of the - XPath query, set the `clean` parameter to `false`. - :param bool fallback_to_raw: Whether to use raw HTML content if text cleaning - fails. - :param bool return_analyzed_text: Whether or not to return the analyzed text. - :param str language: ISO 639-1 code that specifies the language of your text. This - overrides automatic language detection. Language support differs depending on the - features you include in your analysis. See [Language - support](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-language-support) - for more information. - :param int limit_text_characters: Sets the maximum number of characters that are - processed by the service. + :param str text: (optional) The plain text to analyze. One of the `text`, + `html`, or `url` parameters is required. + :param str html: (optional) The HTML file to analyze. One of the `text`, + `html`, or `url` parameters is required. + :param str url: (optional) The webpage to analyze. One of the `text`, + `html`, or `url` parameters is required. + :param bool clean: (optional) Set this to `false` to disable webpage + cleaning. To learn more about webpage cleaning, see the [Analyzing + webpages](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages) + documentation. + :param str xpath: (optional) An [XPath + query](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages#xpath) + to perform on `html` or `url` input. Results of the query will be appended + to the cleaned webpage text before it is analyzed. To analyze only the + results of the XPath query, set the `clean` parameter to `false`. + :param bool fallback_to_raw: (optional) Whether to use raw HTML content if + text cleaning fails. + :param bool return_analyzed_text: (optional) Whether or not to return the + analyzed text. + :param str language: (optional) ISO 639-1 code that specifies the language + of your text. This overrides automatic language detection. Language support + differs depending on the features you include in your analysis. See + [Language + support](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-language-support) + for more information. + :param int limit_text_characters: (optional) Sets the maximum number of + characters that are processed by the service. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -221,13 +176,14 @@ def analyze(self, } url = '/v1/analyze' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=True) + response = self.send(request) return response ######################### @@ -257,12 +213,13 @@ def list_models(self, **kwargs): params = {'version': self.version} url = '/v1/models' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def delete_model(self, model_id, **kwargs): @@ -290,12 +247,13 @@ def delete_model(self, model_id, **kwargs): params = {'version': self.version} url = '/v1/models/{0}'.format(*self._encode_path_vars(model_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response @@ -311,28 +269,31 @@ class AnalysisResults(object): :attr str language: (optional) Language used to analyze the text. :attr str analyzed_text: (optional) Text that was used in the analysis. :attr str retrieved_url: (optional) URL of the webpage that was analyzed. - :attr AnalysisResultsUsage usage: (optional) API usage information for the request. - :attr list[ConceptsResult] concepts: (optional) The general concepts referenced or - alluded to in the analyzed text. - :attr list[EntitiesResult] entities: (optional) The entities detected in the analyzed - text. - :attr list[KeywordsResult] keywords: (optional) The keywords from the analyzed text. - :attr list[CategoriesResult] categories: (optional) The categories that the service - assigned to the analyzed text. - :attr EmotionResult emotion: (optional) The anger, disgust, fear, joy, or sadness - conveyed by the content. + :attr AnalysisResultsUsage usage: (optional) API usage information for the + request. + :attr list[ConceptsResult] concepts: (optional) The general concepts referenced + or alluded to in the analyzed text. + :attr list[EntitiesResult] entities: (optional) The entities detected in the + analyzed text. + :attr list[KeywordsResult] keywords: (optional) The keywords from the analyzed + text. + :attr list[CategoriesResult] categories: (optional) The categories that the + service assigned to the analyzed text. + :attr EmotionResult emotion: (optional) The anger, disgust, fear, joy, or + sadness conveyed by the content. :attr AnalysisResultsMetadata metadata: (optional) Webpage metadata, such as the - author and the title of the page. - :attr list[RelationsResult] relations: (optional) The relationships between entities - in the content. + author and the title of the page. + :attr list[RelationsResult] relations: (optional) The relationships between + entities in the content. :attr list[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into - `subject`, `action`, and `object` form. + `subject`, `action`, and `object` form. :attr SentimentResult sentiment: (optional) The sentiment of the content. :attr SyntaxResult syntax: (optional) Tokens and sentences returned from syntax - analysis. + analysis. """ def __init__(self, + *, language=None, analyzed_text=None, retrieved_url=None, @@ -354,26 +315,26 @@ def __init__(self, :param str analyzed_text: (optional) Text that was used in the analysis. :param str retrieved_url: (optional) URL of the webpage that was analyzed. :param AnalysisResultsUsage usage: (optional) API usage information for the - request. - :param list[ConceptsResult] concepts: (optional) The general concepts referenced - or alluded to in the analyzed text. - :param list[EntitiesResult] entities: (optional) The entities detected in the - analyzed text. - :param list[KeywordsResult] keywords: (optional) The keywords from the analyzed - text. - :param list[CategoriesResult] categories: (optional) The categories that the - service assigned to the analyzed text. - :param EmotionResult emotion: (optional) The anger, disgust, fear, joy, or sadness - conveyed by the content. - :param AnalysisResultsMetadata metadata: (optional) Webpage metadata, such as the - author and the title of the page. - :param list[RelationsResult] relations: (optional) The relationships between - entities in the content. - :param list[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into - `subject`, `action`, and `object` form. + request. + :param list[ConceptsResult] concepts: (optional) The general concepts + referenced or alluded to in the analyzed text. + :param list[EntitiesResult] entities: (optional) The entities detected in + the analyzed text. + :param list[KeywordsResult] keywords: (optional) The keywords from the + analyzed text. + :param list[CategoriesResult] categories: (optional) The categories that + the service assigned to the analyzed text. + :param EmotionResult emotion: (optional) The anger, disgust, fear, joy, or + sadness conveyed by the content. + :param AnalysisResultsMetadata metadata: (optional) Webpage metadata, such + as the author and the title of the page. + :param list[RelationsResult] relations: (optional) The relationships + between entities in the content. + :param list[SemanticRolesResult] semantic_roles: (optional) Sentences + parsed into `subject`, `action`, and `object` form. :param SentimentResult sentiment: (optional) The sentiment of the content. - :param SyntaxResult syntax: (optional) Tokens and sentences returned from syntax - analysis. + :param SyntaxResult syntax: (optional) Tokens and sentences returned from + syntax analysis. """ self.language = language self.analyzed_text = analyzed_text @@ -505,13 +466,15 @@ class AnalysisResultsMetadata(object): Webpage metadata, such as the author and the title of the page. :attr list[Author] authors: (optional) The authors of the document. - :attr str publication_date: (optional) The publication date in the format ISO 8601. + :attr str publication_date: (optional) The publication date in the format ISO + 8601. :attr str title: (optional) The title of the document. :attr str image: (optional) URL of a prominent image on the webpage. :attr list[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. """ def __init__(self, + *, authors=None, publication_date=None, title=None, @@ -521,8 +484,8 @@ def __init__(self, Initialize a AnalysisResultsMetadata object. :param list[Author] authors: (optional) The authors of the document. - :param str publication_date: (optional) The publication date in the format ISO - 8601. + :param str publication_date: (optional) The publication date in the format + ISO 8601. :param str title: (optional) The title of the document. :param str image: (optional) URL of a prominent image on the webpage. :param list[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. @@ -597,13 +560,14 @@ class AnalysisResultsUsage(object): :attr int text_units: (optional) Number of 10,000-character units processed. """ - def __init__(self, features=None, text_characters=None, text_units=None): + def __init__(self, *, features=None, text_characters=None, text_units=None): """ Initialize a AnalysisResultsUsage object. :param int features: (optional) Number of features used in the API call. :param int text_characters: (optional) Number of text characters processed. - :param int text_units: (optional) Number of 10,000-character units processed. + :param int text_units: (optional) Number of 10,000-character units + processed. """ self.features = features self.text_characters = text_characters @@ -661,7 +625,7 @@ class Author(object): :attr str name: (optional) Name of the author. """ - def __init__(self, name=None): + def __init__(self, *, name=None): """ Initialize a Author object. @@ -711,24 +675,25 @@ class CategoriesOptions(object): Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr bool explanation: (optional) Set this to `true` to return explanations for each - categorization. **This is available only for English categories.**. + :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) 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. + model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the standard categories model. """ - def __init__(self, explanation=None, limit=None, model=None): + def __init__(self, *, explanation=None, limit=None, model=None): """ Initialize a CategoriesOptions object. - :param bool explanation: (optional) Set this to `true` to return explanations for - each categorization. **This is available only for English categories.**. + :param bool explanation: (optional) Set this to `true` to return + explanations for each categorization. **This is available only for English + categories.**. :param int limit: (optional) Maximum number of categories to return. :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. + model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the standard categories model. """ self.explanation = explanation self.limit = limit @@ -783,15 +748,15 @@ class CategoriesRelevantText(object): Relevant text that contributed to the categorization. :attr str text: (optional) Text from the analyzed source that supports the - categorization. + categorization. """ - def __init__(self, text=None): + def __init__(self, *, text=None): """ Initialize a CategoriesRelevantText object. :param str text: (optional) Text from the analyzed source that supports the - categorization. + categorization. """ self.text = text @@ -835,28 +800,29 @@ class CategoriesResult(object): """ A categorization of the analyzed text. - :attr str label: (optional) The path to the category through the 5-level taxonomy - hierarchy. For the complete list of categories, see the [Categories - hierarchy](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) - documentation. - :attr float score: (optional) Confidence score for the category classification. Higher - values indicate greater confidence. - :attr CategoriesResultExplanation explanation: (optional) Information that helps to - explain what contributed to the categories result. + :attr str label: (optional) The path to the category through the 5-level + taxonomy hierarchy. For the complete list of categories, see the [Categories + hierarchy](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) + documentation. + :attr float score: (optional) Confidence score for the category classification. + Higher values indicate greater confidence. + :attr CategoriesResultExplanation explanation: (optional) Information that helps + to explain what contributed to the categories result. """ - def __init__(self, label=None, score=None, explanation=None): + def __init__(self, *, label=None, score=None, explanation=None): """ Initialize a CategoriesResult object. - :param str label: (optional) The path to the category through the 5-level taxonomy - hierarchy. For the complete list of categories, see the [Categories - hierarchy](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) - documentation. - :param float score: (optional) Confidence score for the category classification. - Higher values indicate greater confidence. - :param CategoriesResultExplanation explanation: (optional) Information that helps - to explain what contributed to the categories result. + :param str label: (optional) The path to the category through the 5-level + taxonomy hierarchy. For the complete list of categories, see the + [Categories + hierarchy](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) + documentation. + :param float score: (optional) Confidence score for the category + classification. Higher values indicate greater confidence. + :param CategoriesResultExplanation explanation: (optional) Information that + helps to explain what contributed to the categories result. """ self.label = label self.score = score @@ -911,20 +877,20 @@ class CategoriesResultExplanation(object): """ Information that helps to explain what contributed to the categories result. - :attr list[CategoriesRelevantText] relevant_text: (optional) An array of relevant text - from the source that contributed to the categorization. The sorted array begins with - the phrase that contributed most significantly to the result, followed by phrases that - were less and less impactful. + :attr list[CategoriesRelevantText] relevant_text: (optional) An array of + relevant text from the source that contributed to the categorization. The sorted + array begins with the phrase that contributed most significantly to the result, + followed by phrases that were less and less impactful. """ - def __init__(self, relevant_text=None): + def __init__(self, *, relevant_text=None): """ Initialize a CategoriesResultExplanation object. - :param list[CategoriesRelevantText] relevant_text: (optional) An array of relevant - text from the source that contributed to the categorization. The sorted array - begins with the phrase that contributed most significantly to the result, followed - by phrases that were less and less impactful. + :param list[CategoriesRelevantText] relevant_text: (optional) An array of + relevant text from the source that contributed to the categorization. The + sorted array begins with the phrase that contributed most significantly to + the result, followed by phrases that were less and less impactful. """ self.relevant_text = relevant_text @@ -978,7 +944,7 @@ class ConceptsOptions(object): :attr int limit: (optional) Maximum number of concepts to return. """ - def __init__(self, limit=None): + def __init__(self, *, limit=None): """ Initialize a ConceptsOptions object. @@ -1028,19 +994,20 @@ class ConceptsResult(object): :attr str text: (optional) Name of the concept. :attr float relevance: (optional) Relevance score between 0 and 1. Higher scores - indicate greater relevance. - :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. + indicate greater relevance. + :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia + resource. """ - def __init__(self, text=None, relevance=None, dbpedia_resource=None): + def __init__(self, *, text=None, relevance=None, dbpedia_resource=None): """ Initialize a ConceptsResult object. :param str text: (optional) Name of the concept. - :param float relevance: (optional) Relevance score between 0 and 1. Higher scores - indicate greater relevance. + :param float relevance: (optional) Relevance score between 0 and 1. Higher + scores indicate greater relevance. :param str dbpedia_resource: (optional) Link to the corresponding DBpedia - resource. + resource. """ self.text = text self.relevance = relevance @@ -1098,7 +1065,7 @@ class DeleteModelResults(object): :attr str deleted: (optional) model_id of the deleted model. """ - def __init__(self, deleted=None): + def __init__(self, *, deleted=None): """ Initialize a DeleteModelResults object. @@ -1147,17 +1114,18 @@ class DisambiguationResult(object): Disambiguation information for the entity. :attr str name: (optional) Common entity name. - :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. + :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia + resource. :attr list[str] subtype: (optional) Entity subtype information. """ - def __init__(self, name=None, dbpedia_resource=None, subtype=None): + def __init__(self, *, name=None, dbpedia_resource=None, subtype=None): """ Initialize a DisambiguationResult object. :param str name: (optional) Common entity name. :param str dbpedia_resource: (optional) Link to the corresponding DBpedia - resource. + resource. :param list[str] subtype: (optional) Entity subtype information. """ self.name = name @@ -1213,15 +1181,16 @@ class DocumentEmotionResults(object): """ Emotion results for the document as a whole. - :attr EmotionScores emotion: (optional) Emotion results for the document as a whole. + :attr EmotionScores emotion: (optional) Emotion results for the document as a + whole. """ - def __init__(self, emotion=None): + def __init__(self, *, emotion=None): """ Initialize a DocumentEmotionResults object. - :param EmotionScores emotion: (optional) Emotion results for the document as a - whole. + :param EmotionScores emotion: (optional) Emotion results for the document + as a whole. """ self.emotion = emotion @@ -1265,18 +1234,20 @@ class DocumentSentimentResults(object): """ DocumentSentimentResults. - :attr str label: (optional) Indicates whether the sentiment is positive, neutral, or - negative. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 (positive). + :attr str label: (optional) Indicates whether the sentiment is positive, + neutral, or negative. + :attr float score: (optional) Sentiment score from -1 (negative) to 1 + (positive). """ - def __init__(self, label=None, score=None): + def __init__(self, *, label=None, score=None): """ Initialize a DocumentSentimentResults object. - :param str label: (optional) Indicates whether the sentiment is positive, neutral, - or negative. - :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). + :param str label: (optional) Indicates whether the sentiment is positive, + neutral, or negative. + :param float score: (optional) Sentiment score from -1 (negative) to 1 + (positive). """ self.label = label self.score = score @@ -1329,20 +1300,20 @@ class EmotionOptions(object): `keywords.emotion`. Supported languages: English. - :attr bool document: (optional) Set this to `false` to hide document-level emotion - results. - :attr list[str] targets: (optional) Emotion results will be returned for each target - string that is found in the document. + :attr bool document: (optional) Set this to `false` to hide document-level + emotion results. + :attr list[str] targets: (optional) Emotion results will be returned for each + target string that is found in the document. """ - def __init__(self, document=None, targets=None): + def __init__(self, *, document=None, targets=None): """ Initialize a EmotionOptions object. :param bool document: (optional) Set this to `false` to hide document-level - emotion results. - :param list[str] targets: (optional) Emotion results will be returned for each - target string that is found in the document. + emotion results. + :param list[str] targets: (optional) Emotion results will be returned for + each target string that is found in the document. """ self.document = document self.targets = targets @@ -1393,20 +1364,20 @@ class EmotionResult(object): Emotion information can be returned for detected entities, keywords, or user-specified target phrases found in the text. - :attr DocumentEmotionResults document: (optional) Emotion results for the document as - a whole. - :attr list[TargetedEmotionResults] targets: (optional) Emotion results for specified - targets. + :attr DocumentEmotionResults document: (optional) Emotion results for the + document as a whole. + :attr list[TargetedEmotionResults] targets: (optional) Emotion results for + specified targets. """ - def __init__(self, document=None, targets=None): + def __init__(self, *, document=None, targets=None): """ Initialize a EmotionResult object. :param DocumentEmotionResults document: (optional) Emotion results for the - document as a whole. + document as a whole. :param list[TargetedEmotionResults] targets: (optional) Emotion results for - specified targets. + specified targets. """ self.document = document self.targets = targets @@ -1459,19 +1430,20 @@ class EmotionScores(object): """ EmotionScores. - :attr float anger: (optional) Anger score from 0 to 1. A higher score means that the - text is more likely to convey anger. - :attr float disgust: (optional) Disgust score from 0 to 1. A higher score means that - the text is more likely to convey disgust. - :attr float fear: (optional) Fear score from 0 to 1. A higher score means that the - text is more likely to convey fear. - :attr float joy: (optional) Joy score from 0 to 1. A higher score means that the text - is more likely to convey joy. - :attr float sadness: (optional) Sadness score from 0 to 1. A higher score means that - the text is more likely to convey sadness. + :attr float anger: (optional) Anger score from 0 to 1. A higher score means that + the text is more likely to convey anger. + :attr float disgust: (optional) Disgust score from 0 to 1. A higher score means + that the text is more likely to convey disgust. + :attr float fear: (optional) Fear score from 0 to 1. A higher score means that + the text is more likely to convey fear. + :attr float joy: (optional) Joy score from 0 to 1. A higher score means that the + text is more likely to convey joy. + :attr float sadness: (optional) Sadness score from 0 to 1. A higher score means + that the text is more likely to convey sadness. """ def __init__(self, + *, anger=None, disgust=None, fear=None, @@ -1480,16 +1452,16 @@ def __init__(self, """ Initialize a EmotionScores object. - :param float anger: (optional) Anger score from 0 to 1. A higher score means that - the text is more likely to convey anger. - :param float disgust: (optional) Disgust score from 0 to 1. A higher score means - that the text is more likely to convey disgust. - :param float fear: (optional) Fear score from 0 to 1. A higher score means that - the text is more likely to convey fear. - :param float joy: (optional) Joy score from 0 to 1. A higher score means that the - text is more likely to convey joy. - :param float sadness: (optional) Sadness score from 0 to 1. A higher score means - that the text is more likely to convey sadness. + :param float anger: (optional) Anger score from 0 to 1. A higher score + means that the text is more likely to convey anger. + :param float disgust: (optional) Disgust score from 0 to 1. A higher score + means that the text is more likely to convey disgust. + :param float fear: (optional) Fear score from 0 to 1. A higher score means + that the text is more likely to convey fear. + :param float joy: (optional) Joy score from 0 to 1. A higher score means + that the text is more likely to convey joy. + :param float sadness: (optional) Sadness score from 0 to 1. A higher score + means that the text is more likely to convey sadness. """ self.anger = anger self.disgust = disgust @@ -1560,17 +1532,18 @@ class EntitiesOptions(object): :attr int limit: (optional) Maximum number of entities to return. :attr bool mentions: (optional) Set this to `true` to return locations of entity - mentions. + mentions. :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 entity detection model. - :attr bool sentiment: (optional) Set this to `true` to return sentiment information - for detected entities. - :attr bool emotion: (optional) Set this to `true` to analyze emotion for detected - keywords. + model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the standard entity detection model. + :attr bool sentiment: (optional) Set this to `true` to return sentiment + information for detected entities. + :attr bool emotion: (optional) Set this to `true` to analyze emotion for + detected keywords. """ def __init__(self, + *, limit=None, mentions=None, model=None, @@ -1580,15 +1553,15 @@ def __init__(self, Initialize a EntitiesOptions object. :param int limit: (optional) Maximum number of entities to return. - :param bool mentions: (optional) Set this to `true` to return locations of entity - mentions. + :param bool mentions: (optional) Set this to `true` to return locations of + entity mentions. :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 entity detection model. + model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the standard entity detection model. :param bool sentiment: (optional) Set this to `true` to return sentiment - information for detected entities. - :param bool emotion: (optional) Set this to `true` to analyze emotion for detected - keywords. + information for detected entities. + :param bool emotion: (optional) Set this to `true` to analyze emotion for + detected keywords. """ self.limit = limit self.mentions = mentions @@ -1655,23 +1628,24 @@ class EntitiesResult(object): :attr str type: (optional) Entity type. :attr str text: (optional) The name of the entity. - :attr float relevance: (optional) Relevance score from 0 to 1. Higher values indicate - greater relevance. - :attr float confidence: (optional) Confidence in the entity identification from 0 to - 1. Higher values indicate higher confidence. In standard entities requests, confidence - is returned only for English text. All entities requests that use custom models return - the confidence score. + :attr float relevance: (optional) Relevance score from 0 to 1. Higher values + indicate greater relevance. + :attr float confidence: (optional) Confidence in the entity identification from + 0 to 1. Higher values indicate higher confidence. In standard entities requests, + confidence is returned only for English text. All entities requests that use + custom models return the confidence score. :attr list[EntityMention] mentions: (optional) Entity mentions and locations. :attr int count: (optional) How many times the entity was mentioned in the text. :attr EmotionScores emotion: (optional) Emotion analysis results for the entity, - enabled with the `emotion` option. - :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the - entity, enabled with the `sentiment` option. - :attr DisambiguationResult disambiguation: (optional) Disambiguation information for - the entity. + enabled with the `emotion` option. + :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results + for the entity, enabled with the `sentiment` option. + :attr DisambiguationResult disambiguation: (optional) Disambiguation information + for the entity. """ def __init__(self, + *, type=None, text=None, relevance=None, @@ -1686,20 +1660,22 @@ def __init__(self, :param str type: (optional) Entity type. :param str text: (optional) The name of the entity. - :param float relevance: (optional) Relevance score from 0 to 1. Higher values - indicate greater relevance. - :param float confidence: (optional) Confidence in the entity identification from 0 - to 1. Higher values indicate higher confidence. In standard entities requests, - confidence is returned only for English text. All entities requests that use - custom models return the confidence score. - :param list[EntityMention] mentions: (optional) Entity mentions and locations. - :param int count: (optional) How many times the entity was mentioned in the text. - :param EmotionScores emotion: (optional) Emotion analysis results for the entity, - enabled with the `emotion` option. - :param FeatureSentimentResults sentiment: (optional) Sentiment analysis results - for the entity, enabled with the `sentiment` option. - :param DisambiguationResult disambiguation: (optional) Disambiguation information - for the entity. + :param float relevance: (optional) Relevance score from 0 to 1. Higher + values indicate greater relevance. + :param float confidence: (optional) Confidence in the entity identification + from 0 to 1. Higher values indicate higher confidence. In standard entities + requests, confidence is returned only for English text. All entities + requests that use custom models return the confidence score. + :param list[EntityMention] mentions: (optional) Entity mentions and + locations. + :param int count: (optional) How many times the entity was mentioned in the + text. + :param EmotionScores emotion: (optional) Emotion analysis results for the + entity, enabled with the `emotion` option. + :param FeatureSentimentResults sentiment: (optional) Sentiment analysis + results for the entity, enabled with the `sentiment` option. + :param DisambiguationResult disambiguation: (optional) Disambiguation + information for the entity. """ self.type = type self.text = text @@ -1791,25 +1767,25 @@ class EntityMention(object): EntityMention. :attr str text: (optional) Entity mention text. - :attr list[int] location: (optional) Character offsets indicating the beginning and - end of the mention in the analyzed text. - :attr float confidence: (optional) Confidence in the entity identification from 0 to - 1. Higher values indicate higher confidence. In standard entities requests, confidence - is returned only for English text. All entities requests that use custom models return - the confidence score. + :attr list[int] location: (optional) Character offsets indicating the beginning + and end of the mention in the analyzed text. + :attr float confidence: (optional) Confidence in the entity identification from + 0 to 1. Higher values indicate higher confidence. In standard entities requests, + confidence is returned only for English text. All entities requests that use + custom models return the confidence score. """ - def __init__(self, text=None, location=None, confidence=None): + def __init__(self, *, text=None, location=None, confidence=None): """ Initialize a EntityMention object. :param str text: (optional) Entity mention text. - :param list[int] location: (optional) Character offsets indicating the beginning - and end of the mention in the analyzed text. - :param float confidence: (optional) Confidence in the entity identification from 0 - to 1. Higher values indicate higher confidence. In standard entities requests, - confidence is returned only for English text. All entities requests that use - custom models return the confidence score. + :param list[int] location: (optional) Character offsets indicating the + beginning and end of the mention in the analyzed text. + :param float confidence: (optional) Confidence in the entity identification + from 0 to 1. Higher values indicate higher confidence. In standard entities + requests, confidence is returned only for English text. All entities + requests that use custom models return the confidence score. """ self.text = text self.location = location @@ -1863,14 +1839,16 @@ class FeatureSentimentResults(object): """ FeatureSentimentResults. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 (positive). + :attr float score: (optional) Sentiment score from -1 (negative) to 1 + (positive). """ - def __init__(self, score=None): + def __init__(self, *, score=None): """ Initialize a FeatureSentimentResults object. - :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). + :param float score: (optional) Sentiment score from -1 (negative) to 1 + (positive). """ self.score = score @@ -1914,52 +1892,56 @@ class Features(object): """ Analysis features and options. - :attr ConceptsOptions concepts: (optional) Returns high-level concepts in the content. - For example, a research paper about deep learning might return the concept, - "Artificial Intelligence" although the term is not mentioned. - Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, - Spanish. - :attr EmotionOptions emotion: (optional) Detects anger, disgust, fear, joy, or sadness - that is conveyed in the content or by the context around target phrases specified in - the targets parameter. You can analyze emotion for detected entities with - `entities.emotion` and for keywords with `keywords.emotion`. - Supported languages: English. - :attr EntitiesOptions entities: (optional) Identifies people, cities, organizations, - and other entities in the content. See [Entity types and - subtypes](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-entity-types). - Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, - Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through - custom models. - :attr KeywordsOptions keywords: (optional) Returns important keywords in the content. - Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, - Russian, Spanish, Swedish. - :attr MetadataOptions metadata: (optional) Returns information from the document, - including author name, title, RSS/ATOM feeds, prominent page image, and publication - date. Supports URL and HTML input types only. - :attr RelationsOptions relations: (optional) Recognizes when two entities are related - and identifies the type of relation. For example, an `awardedTo` relation might - connect the entities "Nobel Prize" and "Albert Einstein". See [Relation - types](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-relations). - Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, - Dutch, French, Italian, and Portuguese custom models are also supported. - :attr SemanticRolesOptions semantic_roles: (optional) Parses sentences into subject, - action, and object form. - Supported languages: English, German, Japanese, Korean, Spanish. - :attr SentimentOptions sentiment: (optional) Analyzes the general sentiment of your - content or the sentiment toward specific target phrases. You can analyze sentiment for - detected entities with `entities.sentiment` and for keywords with - `keywords.sentiment`. - Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, - Portuguese, Russian, Spanish. - :attr CategoriesOptions categories: (optional) Returns a five-level taxonomy of the - content. The top three categories are returned. - Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, - Portuguese, Spanish. - :attr SyntaxOptions syntax: (optional) Returns tokens and sentences from the input - text. + :attr ConceptsOptions concepts: (optional) Returns high-level concepts in the + content. For example, a research paper about deep learning might return the + concept, "Artificial Intelligence" although the term is not mentioned. + Supported languages: English, French, German, Italian, Japanese, Korean, + Portuguese, Spanish. + :attr EmotionOptions emotion: (optional) Detects anger, disgust, fear, joy, or + sadness that is conveyed in the content or by the context around target phrases + specified in the targets parameter. You can analyze emotion for detected + entities with `entities.emotion` and for keywords with `keywords.emotion`. + Supported languages: English. + :attr EntitiesOptions entities: (optional) Identifies people, cities, + organizations, and other entities in the content. See [Entity types and + subtypes](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-entity-types). + Supported languages: English, French, German, Italian, Japanese, Korean, + Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported + only through custom models. + :attr KeywordsOptions keywords: (optional) Returns important keywords in the + content. + Supported languages: English, French, German, Italian, Japanese, Korean, + Portuguese, Russian, Spanish, Swedish. + :attr MetadataOptions metadata: (optional) Returns information from the + document, including author name, title, RSS/ATOM feeds, prominent page image, + and publication date. Supports URL and HTML input types only. + :attr RelationsOptions relations: (optional) Recognizes when two entities are + related and identifies the type of relation. For example, an `awardedTo` + relation might connect the entities "Nobel Prize" and "Albert Einstein". See + [Relation + types](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-relations). + Supported languages: Arabic, English, German, Japanese, Korean, Spanish. + Chinese, Dutch, French, Italian, and Portuguese custom models are also + supported. + :attr SemanticRolesOptions semantic_roles: (optional) Parses sentences into + subject, action, and object form. + Supported languages: English, German, Japanese, Korean, Spanish. + :attr SentimentOptions sentiment: (optional) Analyzes the general sentiment of + your content or the sentiment toward specific target phrases. You can analyze + sentiment for detected entities with `entities.sentiment` and for keywords with + `keywords.sentiment`. + Supported languages: Arabic, English, French, German, Italian, Japanese, + Korean, Portuguese, Russian, Spanish. + :attr CategoriesOptions categories: (optional) Returns a five-level taxonomy of + the content. The top three categories are returned. + Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, + Portuguese, Spanish. + :attr SyntaxOptions syntax: (optional) Returns tokens and sentences from the + input text. """ def __init__(self, + *, concepts=None, emotion=None, entities=None, @@ -1973,50 +1955,53 @@ def __init__(self, """ Initialize a Features object. - :param ConceptsOptions concepts: (optional) Returns high-level concepts in the - content. For example, a research paper about deep learning might return the - concept, "Artificial Intelligence" although the term is not mentioned. - Supported languages: English, French, German, Italian, Japanese, Korean, - Portuguese, Spanish. - :param EmotionOptions emotion: (optional) Detects anger, disgust, fear, joy, or - sadness that is conveyed in the content or by the context around target phrases - specified in the targets parameter. You can analyze emotion for detected entities - with `entities.emotion` and for keywords with `keywords.emotion`. - Supported languages: English. + :param ConceptsOptions concepts: (optional) Returns high-level concepts in + the content. For example, a research paper about deep learning might return + the concept, "Artificial Intelligence" although the term is not mentioned. + Supported languages: English, French, German, Italian, Japanese, Korean, + Portuguese, Spanish. + :param EmotionOptions emotion: (optional) Detects anger, disgust, fear, + joy, or sadness that is conveyed in the content or by the context around + target phrases specified in the targets parameter. You can analyze emotion + for detected entities with `entities.emotion` and for keywords with + `keywords.emotion`. + Supported languages: English. :param EntitiesOptions entities: (optional) Identifies people, cities, - organizations, and other entities in the content. See [Entity types and - subtypes](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-entity-types). - Supported languages: English, French, German, Italian, Japanese, Korean, - Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported - only through custom models. - :param KeywordsOptions keywords: (optional) Returns important keywords in the - content. - Supported languages: English, French, German, Italian, Japanese, Korean, - Portuguese, Russian, Spanish, Swedish. - :param MetadataOptions metadata: (optional) Returns information from the document, - including author name, title, RSS/ATOM feeds, prominent page image, and - publication date. Supports URL and HTML input types only. - :param RelationsOptions relations: (optional) Recognizes when two entities are - related and identifies the type of relation. For example, an `awardedTo` relation - might connect the entities "Nobel Prize" and "Albert Einstein". See [Relation - types](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-relations). - Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, - Dutch, French, Italian, and Portuguese custom models are also supported. - :param SemanticRolesOptions semantic_roles: (optional) Parses sentences into - subject, action, and object form. - Supported languages: English, German, Japanese, Korean, Spanish. - :param SentimentOptions sentiment: (optional) Analyzes the general sentiment of - your content or the sentiment toward specific target phrases. You can analyze - sentiment for detected entities with `entities.sentiment` and for keywords with - `keywords.sentiment`. - Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, - Portuguese, Russian, Spanish. - :param CategoriesOptions categories: (optional) Returns a five-level taxonomy of - the content. The top three categories are returned. - Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, - Portuguese, Spanish. - :param SyntaxOptions syntax: (optional) Returns tokens and sentences from the - input text. + organizations, and other entities in the content. See [Entity types and + subtypes](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-entity-types). + Supported languages: English, French, German, Italian, Japanese, Korean, + Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are + supported only through custom models. + :param KeywordsOptions keywords: (optional) Returns important keywords in + the content. + Supported languages: English, French, German, Italian, Japanese, Korean, + Portuguese, Russian, Spanish, Swedish. + :param MetadataOptions metadata: (optional) Returns information from the + document, including author name, title, RSS/ATOM feeds, prominent page + image, and publication date. Supports URL and HTML input types only. + :param RelationsOptions relations: (optional) Recognizes when two entities + are related and identifies the type of relation. For example, an + `awardedTo` relation might connect the entities "Nobel Prize" and "Albert + Einstein". See [Relation + types](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-relations). + Supported languages: Arabic, English, German, Japanese, Korean, Spanish. + Chinese, Dutch, French, Italian, and Portuguese custom models are also + supported. + :param SemanticRolesOptions semantic_roles: (optional) Parses sentences + into subject, action, and object form. + Supported languages: English, German, Japanese, Korean, Spanish. + :param SentimentOptions sentiment: (optional) Analyzes the general + sentiment of your content or the sentiment toward specific target phrases. + You can analyze sentiment for detected entities with `entities.sentiment` + and for keywords with `keywords.sentiment`. + Supported languages: Arabic, English, French, German, Italian, Japanese, + Korean, Portuguese, Russian, Spanish. + :param CategoriesOptions categories: (optional) Returns a five-level + taxonomy of the content. The top three categories are returned. + Supported languages: Arabic, English, French, German, Italian, Japanese, + Korean, Portuguese, Spanish. + :param SyntaxOptions syntax: (optional) Returns tokens and sentences from + the input text. """ self.concepts = concepts self.emotion = emotion @@ -2115,7 +2100,7 @@ class Feed(object): :attr str link: (optional) URL of the RSS or ATOM feed. """ - def __init__(self, link=None): + def __init__(self, *, link=None): """ Initialize a Feed object. @@ -2166,21 +2151,21 @@ class KeywordsOptions(object): Russian, Spanish, Swedish. :attr int limit: (optional) Maximum number of keywords to return. - :attr bool sentiment: (optional) Set this to `true` to return sentiment information - for detected keywords. - :attr bool emotion: (optional) Set this to `true` to analyze emotion for detected - keywords. + :attr bool sentiment: (optional) Set this to `true` to return sentiment + information for detected keywords. + :attr bool emotion: (optional) Set this to `true` to analyze emotion for + detected keywords. """ - def __init__(self, limit=None, sentiment=None, emotion=None): + def __init__(self, *, limit=None, sentiment=None, emotion=None): """ Initialize a KeywordsOptions object. :param int limit: (optional) Maximum number of keywords to return. :param bool sentiment: (optional) Set this to `true` to return sentiment - information for detected keywords. - :param bool emotion: (optional) Set this to `true` to analyze emotion for detected - keywords. + information for detected keywords. + :param bool emotion: (optional) Set this to `true` to analyze emotion for + detected keywords. """ self.limit = limit self.sentiment = sentiment @@ -2234,17 +2219,19 @@ class KeywordsResult(object): """ The important keywords in the content, organized by relevance. - :attr int count: (optional) Number of times the keyword appears in the analyzed text. - :attr float relevance: (optional) Relevance score from 0 to 1. Higher values indicate - greater relevance. + :attr int count: (optional) Number of times the keyword appears in the analyzed + text. + :attr float relevance: (optional) Relevance score from 0 to 1. Higher values + indicate greater relevance. :attr str text: (optional) The keyword text. - :attr EmotionScores emotion: (optional) Emotion analysis results for the keyword, - enabled with the `emotion` option. - :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the - keyword, enabled with the `sentiment` option. + :attr EmotionScores emotion: (optional) Emotion analysis results for the + keyword, enabled with the `emotion` option. + :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results + for the keyword, enabled with the `sentiment` option. """ def __init__(self, + *, count=None, relevance=None, text=None, @@ -2253,15 +2240,15 @@ def __init__(self, """ Initialize a KeywordsResult object. - :param int count: (optional) Number of times the keyword appears in the analyzed - text. - :param float relevance: (optional) Relevance score from 0 to 1. Higher values - indicate greater relevance. + :param int count: (optional) Number of times the keyword appears in the + analyzed text. + :param float relevance: (optional) Relevance score from 0 to 1. Higher + values indicate greater relevance. :param str text: (optional) The keyword text. - :param EmotionScores emotion: (optional) Emotion analysis results for the keyword, - enabled with the `emotion` option. - :param FeatureSentimentResults sentiment: (optional) Sentiment analysis results - for the keyword, enabled with the `sentiment` option. + :param EmotionScores emotion: (optional) Emotion analysis results for the + keyword, enabled with the `emotion` option. + :param FeatureSentimentResults sentiment: (optional) Sentiment analysis + results for the keyword, enabled with the `sentiment` option. """ self.count = count self.relevance = relevance @@ -2329,7 +2316,7 @@ class ListModelsResults(object): :attr list[Model] models: (optional) An array of available models. """ - def __init__(self, models=None): + def __init__(self, *, models=None): """ Initialize a ListModelsResults object. @@ -2418,21 +2405,24 @@ class Model(object): """ Model. - :attr str status: (optional) When the status is `available`, the model is ready to - use. + :attr str status: (optional) When the status is `available`, the model is ready + to use. :attr str model_id: (optional) Unique model ID. - :attr str language: (optional) ISO 639-1 code indicating the language of the model. + :attr str language: (optional) ISO 639-1 code indicating the language of the + model. :attr str description: (optional) Model description. - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that - deployed this model to Natural Language Understanding. - :attr str version: (optional) The model version, if it was manually provided in Watson - Knowledge Studio. - :attr str version_description: (optional) The description of the version, if it was - manually provided in Watson Knowledge Studio. - :attr datetime created: (optional) A dateTime indicating when the model was created. + :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + that deployed this model to Natural Language Understanding. + :attr str version: (optional) The model version, if it was manually provided in + Watson Knowledge Studio. + :attr str version_description: (optional) The description of the version, if it + was manually provided in Watson Knowledge Studio. + :attr datetime created: (optional) A dateTime indicating when the model was + created. """ def __init__(self, + *, status=None, model_id=None, language=None, @@ -2444,20 +2434,20 @@ def __init__(self, """ Initialize a Model object. - :param str status: (optional) When the status is `available`, the model is ready - to use. + :param str status: (optional) When the status is `available`, the model is + ready to use. :param str model_id: (optional) Unique model ID. - :param str language: (optional) ISO 639-1 code indicating the language of the - model. + :param str language: (optional) ISO 639-1 code indicating the language of + the model. :param str description: (optional) Model description. - :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace - that deployed this model to Natural Language Understanding. - :param str version: (optional) The model version, if it was manually provided in - Watson Knowledge Studio. - :param str version_description: (optional) The description of the version, if it - was manually provided in Watson Knowledge Studio. - :param datetime created: (optional) A dateTime indicating when the model was - created. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio + workspace that deployed this model to Natural Language Understanding. + :param str version: (optional) The model version, if it was manually + provided in Watson Knowledge Studio. + :param str version_description: (optional) The description of the version, + if it was manually provided in Watson Knowledge Studio. + :param datetime created: (optional) A dateTime indicating when the model + was created. """ self.status = status self.model_id = model_id @@ -2542,18 +2532,19 @@ class RelationArgument(object): RelationArgument. :attr list[RelationEntity] entities: (optional) An array of extracted entities. - :attr list[int] location: (optional) Character offsets indicating the beginning and - end of the mention in the analyzed text. + :attr list[int] location: (optional) Character offsets indicating the beginning + and end of the mention in the analyzed text. :attr str text: (optional) Text that corresponds to the argument. """ - def __init__(self, entities=None, location=None, text=None): + def __init__(self, *, entities=None, location=None, text=None): """ Initialize a RelationArgument object. - :param list[RelationEntity] entities: (optional) An array of extracted entities. - :param list[int] location: (optional) Character offsets indicating the beginning - and end of the mention in the analyzed text. + :param list[RelationEntity] entities: (optional) An array of extracted + entities. + :param list[int] location: (optional) Character offsets indicating the + beginning and end of the mention in the analyzed text. :param str text: (optional) Text that corresponds to the argument. """ self.entities = entities @@ -2614,7 +2605,7 @@ class RelationEntity(object): :attr str type: (optional) Entity type. """ - def __init__(self, text=None, type=None): + def __init__(self, *, text=None, type=None): """ Initialize a RelationEntity object. @@ -2674,17 +2665,17 @@ class RelationsOptions(object): Dutch, French, Italian, and Portuguese custom models are also supported. :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 default model. + model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the default model. """ - def __init__(self, model=None): + def __init__(self, *, model=None): """ Initialize a RelationsOptions object. :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 default model. + model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the default model. """ self.model = model @@ -2729,23 +2720,23 @@ class RelationsResult(object): The relations between entities found in the content. :attr float score: (optional) Confidence score for the relation. Higher values - indicate greater confidence. + indicate greater confidence. :attr str sentence: (optional) The sentence that contains the relation. :attr str type: (optional) The type of the relation. - :attr list[RelationArgument] arguments: (optional) Entity mentions that are involved - in the relation. + :attr list[RelationArgument] arguments: (optional) Entity mentions that are + involved in the relation. """ - def __init__(self, score=None, sentence=None, type=None, arguments=None): + def __init__(self, *, score=None, sentence=None, type=None, arguments=None): """ Initialize a RelationsResult object. - :param float score: (optional) Confidence score for the relation. Higher values - indicate greater confidence. + :param float score: (optional) Confidence score for the relation. Higher + values indicate greater confidence. :param str sentence: (optional) The sentence that contains the relation. :param str type: (optional) The type of the relation. - :param list[RelationArgument] arguments: (optional) Entity mentions that are - involved in the relation. + :param list[RelationArgument] arguments: (optional) Entity mentions that + are involved in the relation. """ self.score = score self.sentence = sentence @@ -2810,7 +2801,7 @@ class SemanticRolesEntity(object): :attr str text: (optional) The entity text. """ - def __init__(self, type=None, text=None): + def __init__(self, *, type=None, text=None): """ Initialize a SemanticRolesEntity object. @@ -2867,7 +2858,7 @@ class SemanticRolesKeyword(object): :attr str text: (optional) The keyword text. """ - def __init__(self, text=None): + def __init__(self, *, text=None): """ Initialize a SemanticRolesKeyword object. @@ -2917,21 +2908,22 @@ class SemanticRolesOptions(object): Supported languages: English, German, Japanese, Korean, Spanish. :attr int limit: (optional) Maximum number of semantic_roles results to return. - :attr bool keywords: (optional) Set this to `true` to return keyword information for - subjects and objects. - :attr bool entities: (optional) Set this to `true` to return entity information for - subjects and objects. + :attr bool keywords: (optional) Set this to `true` to return keyword information + for subjects and objects. + :attr bool entities: (optional) Set this to `true` to return entity information + for subjects and objects. """ - def __init__(self, limit=None, keywords=None, entities=None): + def __init__(self, *, limit=None, keywords=None, entities=None): """ Initialize a SemanticRolesOptions object. - :param int limit: (optional) Maximum number of semantic_roles results to return. - :param bool keywords: (optional) Set this to `true` to return keyword information - for subjects and objects. - :param bool entities: (optional) Set this to `true` to return entity information - for subjects and objects. + :param int limit: (optional) Maximum number of semantic_roles results to + return. + :param bool keywords: (optional) Set this to `true` to return keyword + information for subjects and objects. + :param bool entities: (optional) Set this to `true` to return entity + information for subjects and objects. """ self.limit = limit self.keywords = keywords @@ -2985,28 +2977,29 @@ class SemanticRolesResult(object): """ The object containing the actions and the objects the actions act upon. - :attr str sentence: (optional) Sentence from the source that contains the subject, - action, and object. - :attr SemanticRolesResultSubject subject: (optional) The extracted subject from the - sentence. + :attr str sentence: (optional) Sentence from the source that contains the + subject, action, and object. + :attr SemanticRolesResultSubject subject: (optional) The extracted subject from + the sentence. :attr SemanticRolesResultAction action: (optional) The extracted action from the - sentence. + sentence. :attr SemanticRolesResultObject object: (optional) The extracted object from the - sentence. + sentence. """ - def __init__(self, sentence=None, subject=None, action=None, object=None): + def __init__(self, *, sentence=None, subject=None, action=None, + object=None): """ Initialize a SemanticRolesResult object. :param str sentence: (optional) Sentence from the source that contains the - subject, action, and object. - :param SemanticRolesResultSubject subject: (optional) The extracted subject from - the sentence. - :param SemanticRolesResultAction action: (optional) The extracted action from the - sentence. - :param SemanticRolesResultObject object: (optional) The extracted object from the - sentence. + subject, action, and object. + :param SemanticRolesResultSubject subject: (optional) The extracted subject + from the sentence. + :param SemanticRolesResultAction action: (optional) The extracted action + from the sentence. + :param SemanticRolesResultObject object: (optional) The extracted object + from the sentence. """ self.sentence = sentence self.subject = subject @@ -3073,7 +3066,7 @@ class SemanticRolesResultAction(object): :attr SemanticRolesVerb verb: (optional) """ - def __init__(self, text=None, normalized=None, verb=None): + def __init__(self, *, text=None, normalized=None, verb=None): """ Initialize a SemanticRolesResultAction object. @@ -3134,16 +3127,17 @@ class SemanticRolesResultObject(object): The extracted object from the sentence. :attr str text: (optional) Object text. - :attr list[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. + :attr list[SemanticRolesKeyword] keywords: (optional) An array of extracted + keywords. """ - def __init__(self, text=None, keywords=None): + def __init__(self, *, text=None, keywords=None): """ Initialize a SemanticRolesResultObject object. :param str text: (optional) Object text. - :param list[SemanticRolesKeyword] keywords: (optional) An array of extracted - keywords. + :param list[SemanticRolesKeyword] keywords: (optional) An array of + extracted keywords. """ self.text = text self.keywords = keywords @@ -3196,19 +3190,21 @@ class SemanticRolesResultSubject(object): The extracted subject from the sentence. :attr str text: (optional) Text that corresponds to the subject role. - :attr list[SemanticRolesEntity] entities: (optional) An array of extracted entities. - :attr list[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. + :attr list[SemanticRolesEntity] entities: (optional) An array of extracted + entities. + :attr list[SemanticRolesKeyword] keywords: (optional) An array of extracted + keywords. """ - def __init__(self, text=None, entities=None, keywords=None): + def __init__(self, *, text=None, entities=None, keywords=None): """ Initialize a SemanticRolesResultSubject object. :param str text: (optional) Text that corresponds to the subject role. :param list[SemanticRolesEntity] entities: (optional) An array of extracted - entities. - :param list[SemanticRolesKeyword] keywords: (optional) An array of extracted - keywords. + entities. + :param list[SemanticRolesKeyword] keywords: (optional) An array of + extracted keywords. """ self.text = text self.entities = entities @@ -3272,7 +3268,7 @@ class SemanticRolesVerb(object): :attr str tense: (optional) Verb tense. """ - def __init__(self, text=None, tense=None): + def __init__(self, *, text=None, tense=None): """ Initialize a SemanticRolesVerb object. @@ -3327,17 +3323,17 @@ class SentenceResult(object): SentenceResult. :attr str text: (optional) The sentence. - :attr list[int] location: (optional) Character offsets indicating the beginning and - end of the sentence in the analyzed text. + :attr list[int] location: (optional) Character offsets indicating the beginning + and end of the sentence in the analyzed text. """ - def __init__(self, text=None, location=None): + def __init__(self, *, text=None, location=None): """ Initialize a SentenceResult object. :param str text: (optional) The sentence. - :param list[int] location: (optional) Character offsets indicating the beginning - and end of the sentence in the analyzed text. + :param list[int] location: (optional) Character offsets indicating the + beginning and end of the sentence in the analyzed text. """ self.text = text self.location = location @@ -3390,20 +3386,20 @@ class SentimentOptions(object): Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :attr bool document: (optional) Set this to `false` to hide document-level sentiment - results. - :attr list[str] targets: (optional) Sentiment results will be returned for each target - string that is found in the document. + :attr bool document: (optional) Set this to `false` to hide document-level + sentiment results. + :attr list[str] targets: (optional) Sentiment results will be returned for each + target string that is found in the document. """ - def __init__(self, document=None, targets=None): + def __init__(self, *, document=None, targets=None): """ Initialize a SentimentOptions object. :param bool document: (optional) Set this to `false` to hide document-level - sentiment results. - :param list[str] targets: (optional) Sentiment results will be returned for each - target string that is found in the document. + sentiment results. + :param list[str] targets: (optional) Sentiment results will be returned for + each target string that is found in the document. """ self.document = document self.targets = targets @@ -3452,18 +3448,20 @@ class SentimentResult(object): """ The sentiment of the content. - :attr DocumentSentimentResults document: (optional) The document level sentiment. - :attr list[TargetedSentimentResults] targets: (optional) The targeted sentiment to - analyze. + :attr DocumentSentimentResults document: (optional) The document level + sentiment. + :attr list[TargetedSentimentResults] targets: (optional) The targeted sentiment + to analyze. """ - def __init__(self, document=None, targets=None): + def __init__(self, *, document=None, targets=None): """ Initialize a SentimentResult object. - :param DocumentSentimentResults document: (optional) The document level sentiment. - :param list[TargetedSentimentResults] targets: (optional) The targeted sentiment - to analyze. + :param DocumentSentimentResults document: (optional) The document level + sentiment. + :param list[TargetedSentimentResults] targets: (optional) The targeted + sentiment to analyze. """ self.document = document self.targets = targets @@ -3517,16 +3515,17 @@ class SyntaxOptions(object): Returns tokens and sentences from the input text. :attr SyntaxOptionsTokens tokens: (optional) Tokenization options. - :attr bool sentences: (optional) Set this to `true` to return sentence information. + :attr bool sentences: (optional) Set this to `true` to return sentence + information. """ - def __init__(self, tokens=None, sentences=None): + def __init__(self, *, tokens=None, sentences=None): """ Initialize a SyntaxOptions object. :param SyntaxOptionsTokens tokens: (optional) Tokenization options. :param bool sentences: (optional) Set this to `true` to return sentence - information. + information. """ self.tokens = tokens self.sentences = sentences @@ -3575,19 +3574,20 @@ class SyntaxOptionsTokens(object): """ Tokenization options. - :attr bool lemma: (optional) Set this to `true` to return the lemma for each token. - :attr bool part_of_speech: (optional) Set this to `true` to return the part of speech - for each token. + :attr bool lemma: (optional) Set this to `true` to return the lemma for each + token. + :attr bool part_of_speech: (optional) Set this to `true` to return the part of + speech for each token. """ - def __init__(self, lemma=None, part_of_speech=None): + def __init__(self, *, lemma=None, part_of_speech=None): """ Initialize a SyntaxOptionsTokens object. - :param bool lemma: (optional) Set this to `true` to return the lemma for each - token. - :param bool part_of_speech: (optional) Set this to `true` to return the part of - speech for each token. + :param bool lemma: (optional) Set this to `true` to return the lemma for + each token. + :param bool part_of_speech: (optional) Set this to `true` to return the + part of speech for each token. """ self.lemma = lemma self.part_of_speech = part_of_speech @@ -3640,7 +3640,7 @@ class SyntaxResult(object): :attr list[SentenceResult] sentences: (optional) """ - def __init__(self, tokens=None, sentences=None): + def __init__(self, *, tokens=None, sentences=None): """ Initialize a SyntaxResult object. @@ -3702,12 +3702,13 @@ class TargetedEmotionResults(object): :attr EmotionScores emotion: (optional) The emotion results for the target. """ - def __init__(self, text=None, emotion=None): + def __init__(self, *, text=None, emotion=None): """ Initialize a TargetedEmotionResults object. :param str text: (optional) Targeted text. - :param EmotionScores emotion: (optional) The emotion results for the target. + :param EmotionScores emotion: (optional) The emotion results for the + target. """ self.text = text self.emotion = emotion @@ -3757,15 +3758,17 @@ class TargetedSentimentResults(object): TargetedSentimentResults. :attr str text: (optional) Targeted text. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 (positive). + :attr float score: (optional) Sentiment score from -1 (negative) to 1 + (positive). """ - def __init__(self, text=None, score=None): + def __init__(self, *, text=None, score=None): """ Initialize a TargetedSentimentResults object. :param str text: (optional) Targeted text. - :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). + :param float score: (optional) Sentiment score from -1 (negative) to 1 + (positive). """ self.text = text self.score = score @@ -3815,16 +3818,17 @@ class TokenResult(object): TokenResult. :attr str text: (optional) The token as it appears in the analyzed text. - :attr str part_of_speech: (optional) The part of speech of the token. For descriptions - of the values, see [Universal Dependencies POS - tags](https://universaldependencies.org/u/pos/). - :attr list[int] location: (optional) Character offsets indicating the beginning and - end of the token in the analyzed text. + :attr str part_of_speech: (optional) The part of speech of the token. For + descriptions of the values, see [Universal Dependencies POS + tags](https://universaldependencies.org/u/pos/). + :attr list[int] location: (optional) Character offsets indicating the beginning + and end of the token in the analyzed text. :attr str lemma: (optional) The - [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. + [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. """ def __init__(self, + *, text=None, part_of_speech=None, location=None, @@ -3834,12 +3838,12 @@ def __init__(self, :param str text: (optional) The token as it appears in the analyzed text. :param str part_of_speech: (optional) The part of speech of the token. For - descriptions of the values, see [Universal Dependencies POS - tags](https://universaldependencies.org/u/pos/). - :param list[int] location: (optional) Character offsets indicating the beginning - and end of the token in the analyzed text. + descriptions of the values, see [Universal Dependencies POS + tags](https://universaldependencies.org/u/pos/). + :param list[int] location: (optional) Character offsets indicating the + beginning and end of the token in the analyzed text. :param str lemma: (optional) The - [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. + [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. """ self.text = text self.part_of_speech = part_of_speech @@ -3892,3 +3896,26 @@ def __eq__(self, other): def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + + class PartOfSpeechEnum(Enum): + """ + The part of speech of the token. For descriptions of the values, see [Universal + Dependencies POS tags](https://universaldependencies.org/u/pos/). + """ + ADJ = "ADJ" + ADP = "ADP" + ADV = "ADV" + AUX = "AUX" + CCONJ = "CCONJ" + DET = "DET" + INTJ = "INTJ" + NOUN = "NOUN" + NUM = "NUM" + PART = "PART" + PRON = "PRON" + PROPN = "PROPN" + PUNCT = "PUNCT" + SCONJ = "SCONJ" + SYM = "SYM" + VERB = "VERB" + X = "X" From 5495f121293df64be9f457a1f9d738b60edc26c3 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 23:27:35 -0400 Subject: [PATCH 025/455] test(nlu): Update natural language understanding examples --- examples/natural_language_understanding_v1.py | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/examples/natural_language_understanding_v1.py b/examples/natural_language_understanding_v1.py index 45d1ab768..82eec8c12 100644 --- a/examples/natural_language_understanding_v1.py +++ b/examples/natural_language_understanding_v1.py @@ -1,21 +1,14 @@ -from __future__ import print_function import json from ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -# If service instance provides API key authentication +authenticator = IAMAuthenticator('your_api_key') service = NaturalLanguageUnderstandingV1( version='2018-03-16', ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/natural-language-understanding/api', - iam_apikey='YOUR APIKEY') - -# service = NaturalLanguageUnderstandingV1( -# version='2018-03-16', -# ## url is optional, and defaults to the URL below. Use the correct URL for your region. -# # url='https://gateway.watsonplatform.net/natural-language-understanding/api', -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD') + authenticator=authenticator) response = service.analyze( text='Bruce Banner is the Hulk and Bruce Wayne is BATMAN! ' From 0fcebaa601ec7bea24d1869c341c6ea2f42af9ce Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 23:33:38 -0400 Subject: [PATCH 026/455] test(nlu): Update natural language understanding unit tests --- .../test_natural_language_understanding.py | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/test/unit/test_natural_language_understanding.py b/test/unit/test_natural_language_understanding.py index 4a18ad0a4..32c09ef56 100644 --- a/test/unit/test_natural_language_understanding.py +++ b/test/unit/test_natural_language_understanding.py @@ -5,6 +5,7 @@ Features, ConceptsOptions, EntitiesOptions, KeywordsOptions, CategoriesOptions, \ EmotionOptions, MetadataOptions, SemanticRolesOptions, RelationsOptions, \ SentimentOptions +from ibm_cloud_sdk_core.authenticators import BasicAuthenticator import os import pytest @@ -59,10 +60,10 @@ class TestNaturalLanguageUnderstanding(TestCase): def test_version_date(self): with pytest.raises(TypeError): NaturalLanguageUnderstandingV1() # pylint: disable=E1120 + authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', url='http://bogus.com', - username='username', - password='password') + authenticator=authenticator) assert nlu @pytest.mark.skipif(os.getenv('VCAP_SERVICES') is not None, @@ -71,14 +72,14 @@ def test_missing_credentials(self): with pytest.raises(ValueError): NaturalLanguageUnderstandingV1(version='2016-01-23') with pytest.raises(ValueError): - NaturalLanguageUnderstandingV1(version='2016-01-23', - url='https://bogus.com') + authenticator = BasicAuthenticator('username', 'password') + NaturalLanguageUnderstandingV1(version='2016-01-23', url='http://bogus.com') def test_analyze_throws(self): + authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', url='http://bogus.com', - username='username', - password='password') + authenticator=authenticator) with pytest.raises(ValueError): nlu.analyze(None, text="this will not work") @@ -88,10 +89,10 @@ def test_text_analyze(self): responses.add(responses.POST, nlu_url, body="{\"resulting_key\": true}", status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', url='http://bogus.com', - username='username', - password='password') + authenticator=authenticator) nlu.analyze(Features(sentiment=SentimentOptions()), text="hello this is a test") assert len(responses.calls) == 1 @@ -101,10 +102,10 @@ def test_html_analyze(self): responses.add(responses.POST, nlu_url, body="{\"resulting_key\": true}", status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', url='http://bogus.com', - username='username', - password='password') + authenticator=authenticator) nlu.analyze(Features(sentiment=SentimentOptions(), emotion=EmotionOptions(document=False)), html="hello this is a test") @@ -116,10 +117,10 @@ def test_url_analyze(self): responses.add(responses.POST, nlu_url, body="{\"resulting_key\": true}", status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', url='http://bogus.com', - username='username', - password='password') + authenticator=authenticator) nlu.analyze(Features(sentiment=SentimentOptions(), emotion=EmotionOptions(document=False)), url="http://cnn.com", @@ -132,10 +133,10 @@ def test_list_models(self): responses.add(responses.GET, nlu_url, status=200, body="{\"resulting_key\": true}", content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', url='http://bogus.com', - username='username', - password='password') + authenticator=authenticator) nlu.list_models() assert len(responses.calls) == 1 @@ -145,9 +146,9 @@ def test_delete_model(self): nlu_url = "http://bogus.com/v1/models/" + model_id responses.add(responses.DELETE, nlu_url, status=200, body="{}", content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', url='http://bogus.com', - username='username', - password='password') + authenticator=authenticator) nlu.delete_model(model_id) assert len(responses.calls) == 1 From 9f749f8c2d3595d33d662af884fdf28acf7a81d6 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 23:35:24 -0400 Subject: [PATCH 027/455] feat(STT): Generate speech to text --- ibm_watson/speech_to_text_v1.py | 4046 ++++++++++++++++++------------- 1 file changed, 2340 insertions(+), 1706 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 48cf45db9..db1623c6f 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -34,11 +34,11 @@ supported languages. """ -from __future__ import absolute_import - import json 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 ############################################################################## # Service @@ -53,16 +53,8 @@ class SpeechToTextV1(BaseService): def __init__( self, url=default_url, - username=None, - password=None, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, + authenticator=None, + disable_ssl_verification=False, ): """ Construct a new client for the Speech to Text service. @@ -71,62 +63,21 @@ def __init__( "https://stream.watsonplatform.net/speech-to-text/api/speech-to-text/api"). The base url may differ between IBM Cloud regions. - :param str username: The username used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str password: The password used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ + if not authenticator: + authenticator = get_authenticator_from_environment('Speech to Text') + BaseService.__init__( self, - vcap_services_name='speech_to_text', url=url, - username=username, - password=password, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Speech to Text', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Speech to Text') ######################### # Models @@ -154,8 +105,9 @@ def list_models(self, **kwargs): headers.update(sdk_headers) url = '/v1/models' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def get_model(self, model_id, **kwargs): @@ -168,8 +120,8 @@ def get_model(self, model_id, **kwargs): **See also:** [Languages and models](https://cloud.ibm.com/docs/services/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. + :param str model_id: The identifier of the model in the form of its name + from the output of the **Get a model** method. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -185,8 +137,9 @@ def get_model(self, model_id, **kwargs): headers.update(sdk_headers) url = '/v1/models/{0}'.format(*self._encode_path_vars(model_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response ######################### @@ -195,6 +148,8 @@ def get_model(self, model_id, **kwargs): def recognize(self, audio, + *, + content_type=None, model=None, language_customization_id=None, acoustic_customization_id=None, @@ -213,7 +168,6 @@ def recognize(self, customization_id=None, grammar_name=None, redaction=None, - content_type=None, audio_metrics=None, **kwargs): """ @@ -248,7 +202,7 @@ def recognize(self, * For all other formats, you can omit the `Content-Type` header or specify `application/octet-stream` with the header to have the service automatically detect the format of the audio. (With the `curl` command, you can specify either - `\"Content-Type:\"` or `\"Content-Type: application/octet-stream\"`.) + `"Content-Type:"` or `"Content-Type: application/octet-stream"`.) Where indicated, the format that you specify must include the sampling rate and can optionally include the number of channels and the endianness of the audio. * `audio/alaw` (**Required.** Specify the sampling rate (`rate`) of the audio.) @@ -290,137 +244,146 @@ def recognize(self, request](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-http#HTTP-multi). :param file audio: The audio to transcribe. - :param str model: 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). - :param str language_customization_id: 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). - **Note:** Use this parameter instead of the deprecated `customization_id` - parameter. - :param str acoustic_customization_id: The customization ID (GUID) of a custom - acoustic model that is to be used with the recognition request. The base model of - the specified custom acoustic 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 acoustic model is - used. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#custom-input). - :param str base_model_version: 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). - :param float customization_weight: 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 to words from the custom language model - compared to those from the base model for the current request. - Specify a value between 0.0 and 1.0. Unless a different customization weight was - specified for the custom model when it was trained, the default value is 0.3. A - customization weight that you specify overrides a weight that was specified when - the custom model was trained. - The default value yields the best performance in general. Assign a higher value if - your audio makes frequent use of OOV words from the custom model. Use caution when - setting the weight: a higher value can improve the 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). - :param int inactivity_timeout: 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). - :param list[str] keywords: 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). - :param float keywords_threshold: 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). - :param int max_alternatives: 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). - :param float word_alternatives_threshold: 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). - :param bool word_confidence: 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). - :param bool timestamps: 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). - :param bool profanity_filter: 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). - :param bool smart_formatting: 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 the final transcript of a - recognition request. For US English, the service also converts certain keyword - strings to punctuation symbols. By default, 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). - :param bool speaker_labels: 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. Setting `speaker_labels` to `true` - forces the `timestamps` parameter to be `true`, regardless of whether you specify - `false` for the parameter. - **Note:** Applies to US English, Japanese, and Spanish transcription only. To - determine whether a language model supports speaker labels, you can also 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). - :param str customization_id: **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 request. Do not specify both parameters with a - request. - :param str grammar_name: The name of a grammar that is to be used with the - recognition request. If you specify a grammar, you must also use the - `language_customization_id` parameter to specify the name of the 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). - :param bool redaction: 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` character. It is intended - to redact sensitive numeric data, such as credit card numbers. By default, the - service performs no redaction. - When you enable redaction, the service automatically enables smart formatting, - regardless of whether you explicitly disable that feature. To ensure maximum - security, the service also disables keyword spotting (ignores the `keywords` and - `keywords_threshold` parameters) and returns only a single final transcript - (forces the `max_alternatives` parameter to 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). - :param bool audio_metrics: 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. - :param str content_type: The format (MIME type) of the audio. For more information - about specifying an audio format, see **Audio formats (content types)** in the - method description. + :param str content_type: (optional) The format (MIME type) of the audio. + For more information about specifying an audio format, see **Audio formats + (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). + :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). + **Note:** Use this parameter instead of the deprecated `customization_id` + parameter. + :param str acoustic_customization_id: (optional) The customization ID + (GUID) of a custom acoustic model that is to be used with the recognition + request. The base model of the specified custom acoustic 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 acoustic model is used. See [Custom + models](https://cloud.ibm.com/docs/services/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). + :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 + to words from the custom language model compared to those from the base + model for the current request. + Specify a value between 0.0 and 1.0. Unless a different customization + weight was specified for the custom model when it was trained, the default + value is 0.3. A customization weight that you specify overrides a weight + that was specified when the custom model was trained. + The default value yields the best performance in general. Assign a higher + value if your audio makes frequent use of OOV words from the custom model. + Use caution when setting the weight: a higher value can improve the + 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). + :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). + :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). + :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). + :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). + :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). + :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). + :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). + :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). + :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 + the final transcript of a recognition request. For US English, the service + also converts certain keyword strings to punctuation symbols. By default, + 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). + :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. + Setting `speaker_labels` to `true` forces the `timestamps` parameter to be + `true`, regardless of whether you specify `false` for the parameter. + **Note:** Applies to US English, Japanese, and Spanish (both broadband and + narrowband models) and UK English (narrowband model) transcription only. To + determine whether a language model supports speaker labels, you can also + 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). + :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 + request. Do not specify both parameters with a request. + :param str grammar_name: (optional) The name of a grammar that is to be + used with the recognition request. If you specify a grammar, you must also + use the `language_customization_id` parameter to specify the name of the + 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). + :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` + character. It is intended to redact sensitive numeric data, such as credit + card numbers. By default, the service performs no redaction. + When you enable redaction, the service automatically enables smart + formatting, regardless of whether you explicitly disable that feature. To + ensure maximum security, the service also disables keyword spotting + (ignores the `keywords` and `keywords_threshold` parameters) and returns + only a single final transcript (forces the `max_alternatives` parameter to + 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). + :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. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -460,20 +423,21 @@ def recognize(self, data = audio url = '/v1/recognize' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=True) + response = self.send(request) return response ######################### # Asynchronous ######################### - def register_callback(self, callback_url, user_secret=None, **kwargs): + def register_callback(self, callback_url, *, user_secret=None, **kwargs): """ Register a callback. @@ -507,16 +471,17 @@ def register_callback(self, callback_url, user_secret=None, **kwargs): **See also:** [Registering a callback URL](https://cloud.ibm.com/docs/services/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 echo the challenge - string during URL verification. During verification, the client can also check the - signature that the service sends in the `X-Callback-Signature` header to verify - the origin of the request. - :param str user_secret: A user-specified string that the service uses to generate - the HMAC-SHA1 signature that it sends via the `X-Callback-Signature` header. The - service includes the header during URL verification and with every notification - sent to the callback URL. It calculates the signature over the payload of the - notification. If you omit the parameter, the service does not send the header. + :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 + echo the challenge string during URL verification. During verification, the + client can also check the signature that the service sends in the + `X-Callback-Signature` header to verify the origin of the request. + :param str user_secret: (optional) A user-specified string that the service + uses to generate the HMAC-SHA1 signature that it sends via the + `X-Callback-Signature` header. The service includes the header during URL + verification and with every notification sent to the callback URL. It + calculates the signature over the payload of the notification. If you omit + the parameter, the service does not send the header. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -535,12 +500,13 @@ def register_callback(self, callback_url, user_secret=None, **kwargs): params = {'callback_url': callback_url, 'user_secret': user_secret} url = '/v1/register_callback' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def unregister_callback(self, callback_url, **kwargs): @@ -572,16 +538,19 @@ def unregister_callback(self, callback_url, **kwargs): params = {'callback_url': callback_url} url = '/v1/unregister_callback' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response def create_job(self, audio, + *, + content_type=None, model=None, callback_url=None, events=None, @@ -604,7 +573,6 @@ def create_job(self, customization_id=None, grammar_name=None, redaction=None, - content_type=None, processing_metrics=None, processing_metrics_interval=None, audio_metrics=None, @@ -667,7 +635,7 @@ def create_job(self, * For all other formats, you can omit the `Content-Type` header or specify `application/octet-stream` with the header to have the service automatically detect the format of the audio. (With the `curl` command, you can specify either - `\"Content-Type:\"` or `\"Content-Type: application/octet-stream\"`.) + `"Content-Type:"` or `"Content-Type: application/octet-stream"`.) Where indicated, the format that you specify must include the sampling rate and can optionally include the number of channels and the endianness of the audio. * `audio/alaw` (**Required.** Specify the sampling rate (`rate`) of the audio.) @@ -696,183 +664,200 @@ def create_job(self, formats](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). :param file audio: The audio to transcribe. - :param str model: 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). - :param str callback_url: 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 with any number of job creation - requests. Omit the parameter to poll the service for job completion and results. - Use the `user_token` parameter to specify a unique user-specified string with each - job to differentiate the callback notifications for the jobs. - :param str events: If the job includes a callback URL, a comma-separated list of - notification events to which to subscribe. Valid events are - * `recognitions.started` generates a callback notification when the service begins - to process the job. - * `recognitions.completed` generates a callback notification when the job is - complete. You must use the **Check a job** method to retrieve the results before - they time out or are deleted. - * `recognitions.completed_with_results` generates a callback notification when the - job is complete. The notification includes the results of the request. - * `recognitions.failed` generates a callback notification if the service - experiences an error while processing the job. - The `recognitions.completed` and `recognitions.completed_with_results` events are - incompatible. You can specify only of the two events. - If the job includes a callback URL, omit the parameter to subscribe to the default - events: `recognitions.started`, `recognitions.completed`, and - `recognitions.failed`. If the job does not include a callback URL, omit the - parameter. - :param str user_token: If the job includes a callback URL, a user-specified string - that the service is to include with each callback notification for the job; the - token allows the user to maintain an internal mapping between jobs and - notification events. If the job does not include a callback URL, omit the - parameter. - :param int results_ttl: The number of minutes for which the results are to be - available after the job has finished. If not delivered via a callback, the results - must be retrieved within this time. Omit the parameter to use a time to live of - one week. The parameter is valid with or without a callback URL. - :param str language_customization_id: 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). - **Note:** Use this parameter instead of the deprecated `customization_id` - parameter. - :param str acoustic_customization_id: The customization ID (GUID) of a custom - acoustic model that is to be used with the recognition request. The base model of - the specified custom acoustic 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 acoustic model is - used. See [Custom - models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-input#custom-input). - :param str base_model_version: 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). - :param float customization_weight: 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 to words from the custom language model - compared to those from the base model for the current request. - Specify a value between 0.0 and 1.0. Unless a different customization weight was - specified for the custom model when it was trained, the default value is 0.3. A - customization weight that you specify overrides a weight that was specified when - the custom model was trained. - The default value yields the best performance in general. Assign a higher value if - your audio makes frequent use of OOV words from the custom model. Use caution when - setting the weight: a higher value can improve the 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). - :param int inactivity_timeout: 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). - :param list[str] keywords: 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). - :param float keywords_threshold: 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). - :param int max_alternatives: 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). - :param float word_alternatives_threshold: 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). - :param bool word_confidence: 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). - :param bool timestamps: 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). - :param bool profanity_filter: 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). - :param bool smart_formatting: 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 the final transcript of a - recognition request. For US English, the service also converts certain keyword - strings to punctuation symbols. By default, 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). - :param bool speaker_labels: 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. Setting `speaker_labels` to `true` - forces the `timestamps` parameter to be `true`, regardless of whether you specify - `false` for the parameter. - **Note:** Applies to US English, Japanese, and Spanish transcription only. To - determine whether a language model supports speaker labels, you can also 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). - :param str customization_id: **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 request. Do not specify both parameters with a - request. - :param str grammar_name: The name of a grammar that is to be used with the - recognition request. If you specify a grammar, you must also use the - `language_customization_id` parameter to specify the name of the 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). - :param bool redaction: 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` character. It is intended - to redact sensitive numeric data, such as credit card numbers. By default, the - service performs no redaction. - When you enable redaction, the service automatically enables smart formatting, - regardless of whether you explicitly disable that feature. To ensure maximum - security, the service also disables keyword spotting (ignores the `keywords` and - `keywords_threshold` parameters) and returns only a single final transcript - (forces the `max_alternatives` parameter to 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). - :param bool processing_metrics: 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 `processing_metrics_interval` parameter. It also - returns processing metrics for transcription events, for example, for final and - interim results. By default, the service returns no processing metrics. - :param float processing_metrics_interval: 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 is set to `true`. - The parameter accepts a minimum value of 0.1 seconds. The level of precision is - not restricted, so you can specify values such as 0.25 and 0.125. - The service does not impose a maximum value. If you want to receive processing - metrics only for transcription events instead of at periodic intervals, set the - value to a large number. If the value is larger than the duration of the audio, - the service returns processing metrics only for transcription events. - :param bool audio_metrics: 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. - :param str content_type: The format (MIME type) of the audio. For more information - about specifying an audio format, see **Audio formats (content types)** in the - method description. + :param str content_type: (optional) The format (MIME type) of the audio. + For more information about specifying an audio format, see **Audio formats + (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). + :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 + with any number of job creation requests. Omit the parameter to poll the + service for job completion and results. + Use the `user_token` parameter to specify a unique user-specified string + with each job to differentiate the callback notifications for the jobs. + :param str events: (optional) If the job includes a callback URL, a + comma-separated list of notification events to which to subscribe. Valid + events are + * `recognitions.started` generates a callback notification when the service + begins to process the job. + * `recognitions.completed` generates a callback notification when the job + is complete. You must use the **Check a job** method to retrieve the + results before they time out or are deleted. + * `recognitions.completed_with_results` generates a callback notification + when the job is complete. The notification includes the results of the + request. + * `recognitions.failed` generates a callback notification if the service + experiences an error while processing the job. + The `recognitions.completed` and `recognitions.completed_with_results` + events are incompatible. You can specify only of the two events. + If the job includes a callback URL, omit the parameter to subscribe to the + default events: `recognitions.started`, `recognitions.completed`, and + `recognitions.failed`. If the job does not include a callback URL, omit the + parameter. + :param str user_token: (optional) If the job includes a callback URL, a + user-specified string that the service is to include with each callback + notification for the job; the token allows the user to maintain an internal + mapping between jobs and notification events. If the job does not include a + callback URL, omit the parameter. + :param int results_ttl: (optional) The number of minutes for which the + results are to be available after the job has finished. If not delivered + via a callback, the results must be retrieved within this time. Omit the + parameter to use a time to live of one week. The parameter is valid with or + without a callback URL. + :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). + **Note:** Use this parameter instead of the deprecated `customization_id` + parameter. + :param str acoustic_customization_id: (optional) The customization ID + (GUID) of a custom acoustic model that is to be used with the recognition + request. The base model of the specified custom acoustic 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 acoustic model is used. See [Custom + models](https://cloud.ibm.com/docs/services/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). + :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 + to words from the custom language model compared to those from the base + model for the current request. + Specify a value between 0.0 and 1.0. Unless a different customization + weight was specified for the custom model when it was trained, the default + value is 0.3. A customization weight that you specify overrides a weight + that was specified when the custom model was trained. + The default value yields the best performance in general. Assign a higher + value if your audio makes frequent use of OOV words from the custom model. + Use caution when setting the weight: a higher value can improve the + 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). + :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). + :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). + :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). + :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). + :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). + :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). + :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). + :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). + :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 + the final transcript of a recognition request. For US English, the service + also converts certain keyword strings to punctuation symbols. By default, + 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). + :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. + Setting `speaker_labels` to `true` forces the `timestamps` parameter to be + `true`, regardless of whether you specify `false` for the parameter. + **Note:** Applies to US English, Japanese, and Spanish (both broadband and + narrowband models) and UK English (narrowband model) transcription only. To + determine whether a language model supports speaker labels, you can also + 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). + :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 + request. Do not specify both parameters with a request. + :param str grammar_name: (optional) The name of a grammar that is to be + used with the recognition request. If you specify a grammar, you must also + use the `language_customization_id` parameter to specify the name of the + 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). + :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` + character. It is intended to redact sensitive numeric data, such as credit + card numbers. By default, the service performs no redaction. + When you enable redaction, the service automatically enables smart + formatting, regardless of whether you explicitly disable that feature. To + ensure maximum security, the service also disables keyword spotting + (ignores the `keywords` and `keywords_threshold` parameters) and returns + only a single final transcript (forces the `max_alternatives` parameter to + 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). + :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 + `processing_metrics_interval` parameter. It also returns processing metrics + for transcription events, for example, for final and interim results. By + default, the service returns no 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 + is set to `true`. + The parameter accepts a minimum value of 0.1 seconds. The level of + precision is not restricted, so you can specify values such as 0.25 and + 0.125. + The service does not impose a maximum value. If you want to receive + processing metrics only for transcription events instead of at periodic + intervals, set the value to a large number. If the value is larger than the + duration of the audio, the service returns processing metrics only for + transcription events. + :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. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -918,13 +903,14 @@ def create_job(self, data = audio url = '/v1/recognitions' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=True) + response = self.send(request) return response def check_jobs(self, **kwargs): @@ -954,8 +940,9 @@ def check_jobs(self, **kwargs): headers.update(sdk_headers) url = '/v1/recognitions' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def check_job(self, id, **kwargs): @@ -975,9 +962,9 @@ def check_job(self, id, **kwargs): **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). - :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 instance of the - service that owns the 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 + instance of the service that owns the job. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -993,8 +980,9 @@ def check_job(self, id, **kwargs): headers.update(sdk_headers) url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def delete_job(self, id, **kwargs): @@ -1009,9 +997,9 @@ def delete_job(self, id, **kwargs): **See also:** [Deleting a job](https://cloud.ibm.com/docs/services/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 instance of the - service that owns the 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 + instance of the service that owns the job. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1027,8 +1015,9 @@ def delete_job(self, id, **kwargs): headers.update(sdk_headers) url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, accept_json=False) + response = self.send(request) return response ######################### @@ -1038,6 +1027,7 @@ def delete_job(self, id, **kwargs): def create_language_model(self, name, base_model_name, + *, dialect=None, description=None, **kwargs): @@ -1051,30 +1041,40 @@ def create_language_model(self, **See also:** [Create a custom language model](https://cloud.ibm.com/docs/services/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 localized name - that matches the language of the custom model. Use a name that describes the - domain of the custom model, such as `Medical custom model` or `Legal custom - model`. - :param str base_model_name: The name of the base language model that is to be - customized by the new custom language model. The new custom model can be used only - with the base model that it customizes. - To determine whether a base model supports language model customization, 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). - :param str dialect: The dialect of the specified language that is to be used with - the custom language model. The parameter is meaningful only for Spanish models, - for which the service creates a custom language model that is suited for speech in - one of the following dialects: - * `es-ES` for Castilian Spanish (the default) - * `es-LA` for Latin American Spanish - * `es-US` for North American (Mexican) Spanish - A specified dialect must be valid for the base model. By default, the dialect - matches the language of the base model; for example, `en-US` for either of the US - English language models. - :param str description: A description of the new custom language model. Use a - localized description that matches the language of the custom model. + :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 + localized name that matches the language of the custom model. Use a name + that describes the domain of the custom model, such as `Medical custom + model` or `Legal custom model`. + :param str base_model_name: The name of the base language model that is to + be customized by the new custom language model. The new custom model can be + used only with the base model that it customizes. + To determine whether a base model supports language model customization, + 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). + :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, + `en-US` is used for either of the US English language models. + For a Spanish language, the service creates a custom language model that is + suited for speech in one of the following dialects: + * `es-ES` for Castilian Spanish (`es-ES` models) + * `es-LA` for Latin American Spanish (`es-AR`, `es-CL`, `es-CO`, and + `es-PE` models) + * `es-US` for Mexican (North American) Spanish (`es-MX` models) + The parameter is meaningful only for Spanish models, for which you can + always safely omit the parameter to have the service create the correct + mapping. + If you specify the `dialect` parameter for non-Spanish language models, its + value must match the language of the base model. If you specify the + `dialect` for Spanish language models, its value must match one of the + defined mappings as indicated (`es-ES`, `es-LA`, or `es-MX`). All dialect + values are case-insensitive. + :param str description: (optional) A description of the new custom language + model. Use a localized description that matches the language of the custom + model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1100,15 +1100,16 @@ def create_language_model(self, } url = '/v1/customizations' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, - json=data, + data=data, accept_json=True) + response = self.send(request) return response - def list_language_models(self, language=None, **kwargs): + def list_language_models(self, *, language=None, **kwargs): """ List custom language models. @@ -1120,10 +1121,10 @@ def list_language_models(self, language=None, **kwargs): **See also:** [Listing custom language models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language). - :param str language: The identifier of the language for which custom language or - custom acoustic models are to be returned (for example, `en-US`). Omit the - parameter to see all custom language or custom acoustic models that are owned by - the requesting credentials. + :param str language: (optional) The identifier of the language for which + custom language or custom acoustic models are to be returned (for example, + `en-US`). Omit the parameter to see all custom language or custom acoustic + models that are owned by the requesting credentials. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1139,12 +1140,13 @@ def list_language_models(self, language=None, **kwargs): params = {'language': language} url = '/v1/customizations' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_language_model(self, customization_id, **kwargs): @@ -1156,9 +1158,10 @@ def get_language_model(self, customization_id, **kwargs): **See also:** [Listing custom language models](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. + :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 + request with credentials for the instance of the service that owns the + custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1176,8 +1179,9 @@ def get_language_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def delete_language_model(self, customization_id, **kwargs): @@ -1191,9 +1195,10 @@ def delete_language_model(self, customization_id, **kwargs): **See also:** [Deleting a custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. + :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 + request with credentials for the instance of the service that owns the + custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1211,12 +1216,14 @@ def delete_language_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def train_language_model(self, customization_id, + *, word_type_to_add=None, customization_weight=None, **kwargs): @@ -1253,29 +1260,31 @@ def train_language_model(self, invalid resources from the training. The model must contain at least one valid resource for training to succeed. - :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 request with - credentials for the instance of the service that owns the custom model. - :param str word_type_to_add: The type of words from the custom language model's - words resource on which to train the model: - * `all` (the default) trains the model on all new words, regardless of whether - they were extracted from corpora or grammars or were added or modified by the - user. - * `user` trains the model only on new words that were added or modified by the - user directly. The model is not trained on new words extracted from corpora or - grammars. - :param float customization_weight: Specifies a customization weight for the custom - language model. The customization weight tells the service how much weight to give - to words from the custom language model compared to those from the base model for - speech recognition. Specify a value between 0.0 and 1.0; the default is 0.3. - The default value yields the best performance in general. Assign a higher value if - your audio makes frequent use of OOV words from the custom model. Use caution when - setting the weight: a higher value can improve the accuracy of phrases from the - custom model's domain, but it can negatively affect performance on non-domain - phrases. - The value that you assign is used for all recognition requests that use the model. - You can override it for any recognition request by specifying a customization - weight for that request. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str word_type_to_add: (optional) The type of words from the custom + language model's words resource on which to train the model: + * `all` (the default) trains the model on all new words, regardless of + whether they were extracted from corpora or grammars or were added or + modified by the user. + * `user` trains the model only on new words that were added or modified by + the user directly. The model is not trained on new words extracted from + corpora or grammars. + :param float customization_weight: (optional) Specifies a customization + weight for the custom language model. The customization weight tells the + service how much weight to give to words from the custom language model + compared to those from the base model for speech recognition. Specify a + value between 0.0 and 1.0; the default is 0.3. + The default value yields the best performance in general. Assign a higher + value if your audio makes frequent use of OOV words from the custom model. + Use caution when setting the weight: a higher value can improve the + accuracy of phrases from the custom model's domain, but it can negatively + affect performance on non-domain phrases. + The value that you assign is used for all recognition requests that use the + model. You can override it for any recognition request by specifying a + customization weight for that request. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1298,12 +1307,13 @@ def train_language_model(self, url = '/v1/customizations/{0}/train'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def reset_language_model(self, customization_id, **kwargs): @@ -1319,9 +1329,10 @@ def reset_language_model(self, customization_id, **kwargs): **See also:** [Resetting a custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. + :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 + request with credentials for the instance of the service that owns the + custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1339,8 +1350,9 @@ def reset_language_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}/reset'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def upgrade_language_model(self, customization_id, **kwargs): @@ -1364,9 +1376,10 @@ def upgrade_language_model(self, customization_id, **kwargs): **See also:** [Upgrading a custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. + :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 + request with credentials for the instance of the service that owns the + custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1384,8 +1397,9 @@ def upgrade_language_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}/upgrade_model'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, accept_json=True) + response = self.send(request) return response ######################### @@ -1403,9 +1417,10 @@ def list_corpora(self, customization_id, **kwargs): **See also:** [Listing corpora for a custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. + :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 + request with credentials for the instance of the service that owns the + custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1422,14 +1437,16 @@ def list_corpora(self, customization_id, **kwargs): url = '/v1/customizations/{0}/corpora'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def add_corpus(self, customization_id, corpus_name, corpus_file, + *, allow_overwrite=None, **kwargs): """ @@ -1475,37 +1492,39 @@ def add_corpus(self, * [Add a corpus to the custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. - :param str corpus_name: The name of the new corpus for the custom language model. - Use a localized name that matches the language of the custom model and reflects - the contents of the corpus. - * Include a maximum of 128 characters in the name. - * Do not use characters that need to be URL-encoded. For example, do not use - spaces, slashes, backslashes, colons, ampersands, double quotes, plus signs, - equals signs, questions marks, and so on in the name. (The service does not - prevent the use of these characters. But because they must be URL-encoded wherever - used, their use is strongly discouraged.) - * Do not use the name of an existing corpus or grammar that is already defined for - the custom model. - * Do not use the name `user`, which is reserved by the service to denote custom - words that are added or modified by the user. - * Do not use the name `base_lm` or `default_lm`. Both names are reserved for - future use by the service. - :param file corpus_file: A plain text file that contains the training data for the - corpus. Encode the file in UTF-8 if it contains non-ASCII characters; the service - assumes UTF-8 encoding if it encounters non-ASCII characters. - 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). - With the `curl` command, use the `--data-binary` option to upload the file for the - request. - :param bool allow_overwrite: If `true`, the specified corpus overwrites an - existing corpus with the same name. If `false`, the request fails if a corpus with - the same name already exists. The parameter has no effect if a corpus with the - same name does not already exist. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str corpus_name: The name of the new corpus for the custom language + model. Use a localized name that matches the language of the custom model + and reflects the contents of the corpus. + * Include a maximum of 128 characters in the name. + * Do not use characters that need to be URL-encoded. For example, do not + use spaces, slashes, backslashes, colons, ampersands, double quotes, plus + signs, equals signs, questions marks, and so on in the name. (The service + does not prevent the use of these characters. But because they must be + URL-encoded wherever used, their use is strongly discouraged.) + * Do not use the name of an existing corpus or grammar that is already + defined for the custom model. + * Do not use the name `user`, which is reserved by the service to denote + custom words that are added or modified by the user. + * Do not use the name `base_lm` or `default_lm`. Both names are reserved + for future use by the service. + :param file corpus_file: A plain text file that contains the training data + for the corpus. Encode the file in UTF-8 if it contains non-ASCII + characters; the service assumes UTF-8 encoding if it encounters non-ASCII + characters. + 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). + 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 + overwrites an existing corpus with the same name. If `false`, the request + fails if a corpus with the same name already exists. The parameter has no + effect if a corpus with the same name does not already exist. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1531,13 +1550,14 @@ def add_corpus(self, url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response def get_corpus(self, customization_id, corpus_name, **kwargs): @@ -1551,10 +1571,12 @@ def get_corpus(self, customization_id, corpus_name, **kwargs): **See also:** [Listing corpora for a custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. - :param str corpus_name: The name of the corpus for the custom language model. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str corpus_name: The name of the corpus for the custom language + model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1573,8 +1595,9 @@ def get_corpus(self, customization_id, corpus_name, **kwargs): url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def delete_corpus(self, customization_id, corpus_name, **kwargs): @@ -1592,10 +1615,12 @@ def delete_corpus(self, customization_id, corpus_name, **kwargs): **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). - :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 request with - credentials for the instance of the service that owns the custom model. - :param str corpus_name: The name of the corpus for the custom language model. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str corpus_name: The name of the corpus for the custom language + model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1614,15 +1639,21 @@ def delete_corpus(self, customization_id, corpus_name, **kwargs): url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, accept_json=True) + response = self.send(request) return response ######################### # Custom words ######################### - def list_words(self, customization_id, word_type=None, sort=None, **kwargs): + def list_words(self, + customization_id, + *, + word_type=None, + sort=None, + **kwargs): """ List custom words. @@ -1636,23 +1667,25 @@ def list_words(self, customization_id, word_type=None, sort=None, **kwargs): **See also:** [Listing words from a custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. - :param str word_type: The type of words to be listed from the custom language - model's words resource: - * `all` (the default) shows all words. - * `user` shows only custom words that were added or modified by the user directly. - * `corpora` shows only OOV that were extracted from corpora. - * `grammars` shows only OOV words that are recognized by grammars. - :param str sort: Indicates the order in which the words are to be listed, - `alphabetical` or by `count`. You can prepend an optional `+` or `-` to an - argument to indicate whether the results are to be sorted in ascending or - descending order. By default, words are sorted in ascending alphabetical order. - For alphabetical ordering, the lexicographical precedence is numeric values, - uppercase letters, and lowercase letters. For count ordering, values with the same - count are ordered alphabetically. With the `curl` command, URL-encode the `+` - symbol as `%2B`. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str word_type: (optional) The type of words to be listed from the + custom language model's words resource: + * `all` (the default) shows all words. + * `user` shows only custom words that were added or modified by the user + directly. + * `corpora` shows only OOV that were extracted from corpora. + * `grammars` shows only OOV words that are recognized by grammars. + :param str sort: (optional) Indicates the order in which the words are to + be listed, `alphabetical` or by `count`. You can prepend an optional `+` or + `-` to an argument to indicate whether the results are to be sorted in + ascending or descending order. By default, words are sorted in ascending + alphabetical order. For alphabetical ordering, the lexicographical + precedence is numeric values, uppercase letters, and lowercase letters. For + count ordering, values with the same count are ordered alphabetically. With + the `curl` command, URL-encode the `+` symbol as `%2B`. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1671,12 +1704,13 @@ def list_words(self, customization_id, word_type=None, sort=None, **kwargs): url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def add_words(self, customization_id, words, **kwargs): @@ -1732,12 +1766,13 @@ def add_words(self, customization_id, words, **kwargs): * [Add words to the custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. - :param list[CustomWord] words: An array of `CustomWord` objects that provides - information about each custom word that is to be added to or updated in the custom - language model. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param list[CustomWord] words: An array of `CustomWord` objects that + provides information about each custom word that is to be added to or + updated in the custom language model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1759,17 +1794,19 @@ def add_words(self, customization_id, words, **kwargs): url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def add_word(self, customization_id, word_name, + *, word=None, sounds_like=None, display_as=None, @@ -1810,34 +1847,37 @@ def add_word(self, * [Add words to the custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. - :param str word_name: The custom word that is to be added to or updated in the - custom language model. Do not include spaces in the word. Use a `-` (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). - :param str word: 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 `_` (underscore) to connect the tokens of - compound words. - Omit this parameter for the **Add a custom word** method. - :param list[str] sounds_like: An array of sounds-like pronunciations for the - custom word. Specify how words that are difficult to pronounce, foreign words, - acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the parameter to - have the service automatically generate a sounds-like pronunciation for the word. - * For a word that is in the service's base vocabulary, use the parameter to - specify additional pronunciations for the word. You cannot override the default - pronunciation of a word; pronunciations you add augment the pronunciation from the - base vocabulary. - A word can have at most five sounds-like pronunciations. A pronunciation can - include at most 40 characters not including spaces. - :param str display_as: An alternative spelling for the custom word when it appears - in a transcript. Use the parameter when you want the word to have a spelling that - is different from its usual representation or from its spelling in corpora - training data. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str word_name: The custom word that is to be added to or updated in + the custom language model. Do not include spaces in the word. Use a `-` + (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). + :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 `_` + (underscore) to connect the tokens of compound words. + Omit this parameter for the **Add a custom word** method. + :param list[str] sounds_like: (optional) An array of sounds-like + pronunciations for the custom word. Specify how words that are difficult to + pronounce, foreign words, acronyms, and so on can be pronounced by users. + * For a word that is not in the service's base vocabulary, omit the + parameter to have the service automatically generate a sounds-like + pronunciation for the word. + * For a word that is in the service's base vocabulary, use the parameter to + specify additional pronunciations for the word. You cannot override the + default pronunciation of a word; pronunciations you add augment the + pronunciation from the base vocabulary. + A word can have at most five sounds-like pronunciations. A pronunciation + can include at most 40 characters not including spaces. + :param str display_as: (optional) An alternative spelling for the custom + word when it appears in a transcript. Use the parameter when you want the + word to have a spelling that is different from its usual representation or + from its spelling in corpora training data. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1862,8 +1902,9 @@ def add_word(self, url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) - response = self.request( - method='PUT', url=url, headers=headers, json=data, accept_json=True) + request = self.prepare_request( + method='PUT', url=url, headers=headers, data=data, accept_json=True) + response = self.send(request) return response def get_word(self, customization_id, word_name, **kwargs): @@ -1876,13 +1917,14 @@ def get_word(self, customization_id, word_name, **kwargs): **See also:** [Listing words from a custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. - :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). + :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 + request with credentials for the instance of the service that owns the + custom model. + :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). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1901,8 +1943,9 @@ def get_word(self, customization_id, word_name, **kwargs): url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def delete_word(self, customization_id, word_name, **kwargs): @@ -1919,13 +1962,14 @@ def delete_word(self, customization_id, word_name, **kwargs): **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). - :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 request with - credentials for the instance of the service that owns the custom model. + :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 + request with credentials for the instance of the service that owns the + custom model. :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). + 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). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1944,8 +1988,9 @@ def delete_word(self, customization_id, word_name, **kwargs): url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, accept_json=True) + response = self.send(request) return response ######################### @@ -1963,9 +2008,10 @@ def list_grammars(self, customization_id, **kwargs): **See also:** [Listing grammars from a custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. + :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 + request with credentials for the instance of the service that owns the + custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1982,8 +2028,9 @@ def list_grammars(self, customization_id, **kwargs): url = '/v1/customizations/{0}/grammars'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def add_grammar(self, @@ -1991,6 +2038,7 @@ def add_grammar(self, grammar_name, grammar_file, content_type, + *, allow_overwrite=None, **kwargs): """ @@ -2032,40 +2080,41 @@ def add_grammar(self, * [Add a grammar to the custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. - :param str grammar_name: The name of the new grammar for the custom language - model. Use a localized name that matches the language of the custom model and - reflects the contents of the grammar. - * Include a maximum of 128 characters in the name. - * Do not use characters that need to be URL-encoded. For example, do not use - spaces, slashes, backslashes, colons, ampersands, double quotes, plus signs, - equals signs, questions marks, and so on in the name. (The service does not - prevent the use of these characters. But because they must be URL-encoded wherever - used, their use is strongly discouraged.) - * Do not use the name of an existing grammar or corpus that is already defined for - the custom model. - * Do not use the name `user`, which is reserved by the service to denote custom - words that are added or modified by the user. - * Do not use the name `base_lm` or `default_lm`. Both names are reserved for - future use by the service. - :param str grammar_file: A plain text file that contains the grammar in the format - specified by the `Content-Type` header. Encode the file in UTF-8 (ASCII is a - subset of UTF-8). Using any other encoding can lead to issues when compiling the - grammar or to unexpected results in decoding. The service ignores an encoding that - is specified in the header of the grammar. - With the `curl` command, use the `--data-binary` option to upload the file for the - request. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str grammar_name: The name of the new grammar for the custom + language model. Use a localized name that matches the language of the + custom model and reflects the contents of the grammar. + * Include a maximum of 128 characters in the name. + * Do not use characters that need to be URL-encoded. For example, do not + use spaces, slashes, backslashes, colons, ampersands, double quotes, plus + signs, equals signs, questions marks, and so on in the name. (The service + does not prevent the use of these characters. But because they must be + URL-encoded wherever used, their use is strongly discouraged.) + * Do not use the name of an existing grammar or corpus that is already + defined for the custom model. + * Do not use the name `user`, which is reserved by the service to denote + custom words that are added or modified by the user. + * Do not use the name `base_lm` or `default_lm`. Both names are reserved + for future use by the service. + :param str grammar_file: A plain text file that contains the grammar in the + format specified by the `Content-Type` header. Encode the file in UTF-8 + (ASCII is a subset of UTF-8). Using any other encoding can lead to issues + when compiling the grammar or to unexpected results in decoding. The + service ignores an encoding that is specified in the header of the grammar. + With the `curl` command, use the `--data-binary` option to upload the file + for the request. :param str content_type: The format (MIME type) of the grammar file: - * `application/srgs` for Augmented Backus-Naur Form (ABNF), which uses a - plain-text representation that is similar to traditional BNF grammars. - * `application/srgs+xml` for XML Form, which uses XML elements to represent the - grammar. - :param bool allow_overwrite: If `true`, the specified grammar overwrites an - existing grammar with the same name. If `false`, the request fails if a grammar - with the same name already exists. The parameter has no effect if a grammar with - the same name does not already exist. + * `application/srgs` for Augmented Backus-Naur Form (ABNF), which uses a + plain-text representation that is similar to traditional BNF grammars. + * `application/srgs+xml` for XML Form, which uses XML elements to represent + the grammar. + :param bool allow_overwrite: (optional) If `true`, the specified grammar + overwrites an existing grammar with the same name. If `false`, the request + fails if a grammar with the same name already exists. The parameter has no + effect if a grammar with the same name does not already exist. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2092,13 +2141,14 @@ def add_grammar(self, url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=True) + response = self.send(request) return response def get_grammar(self, customization_id, grammar_name, **kwargs): @@ -2112,10 +2162,12 @@ def get_grammar(self, customization_id, grammar_name, **kwargs): **See also:** [Listing grammars from a custom language model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. - :param str grammar_name: The name of the grammar for the custom language model. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str grammar_name: The name of the grammar for the custom language + model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2134,8 +2186,9 @@ def get_grammar(self, customization_id, grammar_name, **kwargs): url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def delete_grammar(self, customization_id, grammar_name, **kwargs): @@ -2152,10 +2205,12 @@ def delete_grammar(self, customization_id, grammar_name, **kwargs): **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). - :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 request with - credentials for the instance of the service that owns the custom model. - :param str grammar_name: The name of the grammar for the custom language model. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str grammar_name: The name of the grammar for the custom language + model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2174,8 +2229,9 @@ def delete_grammar(self, customization_id, grammar_name, **kwargs): url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, accept_json=True) + response = self.send(request) return response ######################### @@ -2185,6 +2241,7 @@ def delete_grammar(self, customization_id, grammar_name, **kwargs): def create_acoustic_model(self, name, base_model_name, + *, description=None, **kwargs): """ @@ -2197,19 +2254,20 @@ def create_acoustic_model(self, **See also:** [Create a custom acoustic model](https://cloud.ibm.com/docs/services/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 localized name - that matches the language of the custom model. Use a name that describes the - acoustic environment of the custom model, such as `Mobile custom model` or `Noisy - car custom model`. - :param str base_model_name: The name of the base language model that is to be - customized by the new custom acoustic model. The new custom model can be 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). - :param str description: A description of the new custom acoustic model. Use a - localized description that matches the language of the custom model. + :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 + localized name that matches the language of the custom model. Use a name + that describes the acoustic environment of the custom model, such as + `Mobile custom model` or `Noisy car custom model`. + :param str base_model_name: The name of the base language model that is to + be customized by the new custom acoustic model. The new custom model can be + 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). + :param str description: (optional) A description of the new custom acoustic + model. Use a localized description that matches the language of the custom + model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2234,15 +2292,16 @@ def create_acoustic_model(self, } url = '/v1/acoustic_customizations' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, - json=data, + data=data, accept_json=True) + response = self.send(request) return response - def list_acoustic_models(self, language=None, **kwargs): + def list_acoustic_models(self, *, language=None, **kwargs): """ List custom acoustic models. @@ -2254,10 +2313,10 @@ def list_acoustic_models(self, language=None, **kwargs): **See also:** [Listing custom acoustic models](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). - :param str language: The identifier of the language for which custom language or - custom acoustic models are to be returned (for example, `en-US`). Omit the - parameter to see all custom language or custom acoustic models that are owned by - the requesting credentials. + :param str language: (optional) The identifier of the language for which + custom language or custom acoustic models are to be returned (for example, + `en-US`). Omit the parameter to see all custom language or custom acoustic + models that are owned by the requesting credentials. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2273,12 +2332,13 @@ def list_acoustic_models(self, language=None, **kwargs): params = {'language': language} url = '/v1/acoustic_customizations' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_acoustic_model(self, customization_id, **kwargs): @@ -2290,9 +2350,10 @@ def get_acoustic_model(self, customization_id, **kwargs): **See also:** [Listing custom acoustic models](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. + :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 + request with credentials for the instance of the service that owns the + custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2310,8 +2371,9 @@ def get_acoustic_model(self, customization_id, **kwargs): url = '/v1/acoustic_customizations/{0}'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def delete_acoustic_model(self, customization_id, **kwargs): @@ -2325,9 +2387,10 @@ def delete_acoustic_model(self, customization_id, **kwargs): **See also:** [Deleting a custom acoustic model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. + :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 + request with credentials for the instance of the service that owns the + custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2345,12 +2408,14 @@ def delete_acoustic_model(self, customization_id, **kwargs): url = '/v1/acoustic_customizations/{0}'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def train_acoustic_model(self, customization_id, + *, custom_language_model_id=None, **kwargs): """ @@ -2403,16 +2468,18 @@ def train_acoustic_model(self, the invalid resources from the training. The model must contain at least one valid resource for training to succeed. - :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 request with - credentials for the instance of the service that owns the custom model. - :param str custom_language_model_id: The customization ID (GUID) of a custom - language model that is to be used during training of the custom acoustic model. - Specify a custom language model that has been trained with verbatim transcriptions - of the audio resources or that contains words that are relevant to the contents of - the audio resources. The custom language model must be based on the same version - of the same base model as the custom acoustic model. The credentials specified - with the request must own both custom models. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str custom_language_model_id: (optional) The customization ID (GUID) + of a custom language model that is to be used during training of the custom + acoustic model. Specify a custom language model that has been trained with + verbatim transcriptions of the audio resources or that contains words that + are relevant to the contents of the audio resources. The custom language + model must be based on the same version of the same base model as the + custom acoustic model. The credentials specified with the request must own + both custom models. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2432,12 +2499,13 @@ def train_acoustic_model(self, url = '/v1/acoustic_customizations/{0}/train'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def reset_acoustic_model(self, customization_id, **kwargs): @@ -2455,9 +2523,10 @@ def reset_acoustic_model(self, customization_id, **kwargs): **See also:** [Resetting a custom acoustic model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. + :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 + request with credentials for the instance of the service that owns the + custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2475,12 +2544,14 @@ def reset_acoustic_model(self, customization_id, **kwargs): url = '/v1/acoustic_customizations/{0}/reset'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def upgrade_acoustic_model(self, customization_id, + *, custom_language_model_id=None, force=None, **kwargs): @@ -2512,21 +2583,22 @@ def upgrade_acoustic_model(self, **See also:** [Upgrading a custom acoustic model](https://cloud.ibm.com/docs/services/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 request with - credentials for the instance of the service that owns the custom model. - :param str custom_language_model_id: If the custom acoustic model was trained with - a custom language model, the customization ID (GUID) of that custom language - model. The custom language model must be upgraded before the custom acoustic model - can be upgraded. The credentials specified with the request must own both custom - models. - :param bool force: If `true`, forces the upgrade of a custom acoustic model for - which no input data has been modified since it was last trained. Use this - parameter only to force the upgrade of a custom acoustic 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). + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str custom_language_model_id: (optional) If the custom acoustic + model was trained with a custom language model, the customization ID (GUID) + of that custom language model. The custom language model must be upgraded + before the custom acoustic model can be upgraded. The credentials specified + with the request must own both custom models. + :param bool force: (optional) If `true`, forces the upgrade of a custom + acoustic model for which no input data has been modified since it was last + trained. Use this parameter only to force the upgrade of a custom acoustic + 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). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2549,12 +2621,13 @@ def upgrade_acoustic_model(self, url = '/v1/acoustic_customizations/{0}/upgrade_model'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -2574,9 +2647,10 @@ def list_audio(self, customization_id, **kwargs): **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). - :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 request with - credentials for the instance of the service that owns the custom model. + :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 + request with credentials for the instance of the service that owns the + custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2593,17 +2667,19 @@ def list_audio(self, customization_id, **kwargs): url = '/v1/acoustic_customizations/{0}/audio'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def add_audio(self, customization_id, audio_name, audio_resource, + *, + content_type=None, contained_content_type=None, allow_overwrite=None, - content_type=None, **kwargs): """ Add an audio resource. @@ -2694,46 +2770,49 @@ def add_audio(self, include a maximum of 128 characters. This includes the file extension and all elements of the name (for example, slashes). - :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 request with - credentials for the instance of the service that owns the custom model. - :param str audio_name: The name of the new audio resource for the custom acoustic - model. Use a localized name that matches the language of the custom model and - reflects the contents of the resource. - * Include a maximum of 128 characters in the name. - * Do not use characters that need to be URL-encoded. For example, do not use - spaces, slashes, backslashes, colons, ampersands, double quotes, plus signs, - equals signs, questions marks, and so on in the name. (The service does not - prevent the use of these characters. But because they must be URL-encoded wherever - used, their use is strongly discouraged.) - * Do not use the name of an audio resource that has already been added to the - custom model. - :param file audio_resource: The audio resource that is to be added to the custom - acoustic model, an individual audio file or an archive file. - With the `curl` command, use the `--data-binary` option to upload the file for the - request. - :param str contained_content_type: **For an archive-type resource,** specify the - format of the audio files that are contained in the archive file if they are of - type `audio/alaw`, `audio/basic`, `audio/l16`, or `audio/mulaw`. Include the - `rate`, `channels`, and `endianness` parameters where necessary. In this case, all - audio files that are contained in the archive file must be of the indicated type. - For all other audio formats, you can omit the header. In this case, the audio - files can be of multiple types as long as they are not of the types listed in the - previous paragraph. - The parameter accepts all of the audio formats that are supported for use with - speech recognition. For more information, see **Content types for audio-type - resources** in the method description. - **For an audio-type resource,** omit the header. - :param bool allow_overwrite: If `true`, the specified audio resource overwrites an - existing audio resource with the same name. If `false`, the request fails if an - audio resource with the same name already exists. The parameter has no effect if - an audio resource with the same name does not already exist. - :param str content_type: For an audio-type resource, the format (MIME type) of the - audio. For more information, see **Content types for audio-type resources** in the - method description. - For an archive-type resource, the media type of the archive file. For more - information, see **Content types for archive-type resources** in the method - description. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str audio_name: The name of the new audio resource for the custom + acoustic model. Use a localized name that matches the language of the + custom model and reflects the contents of the resource. + * Include a maximum of 128 characters in the name. + * Do not use characters that need to be URL-encoded. For example, do not + use spaces, slashes, backslashes, colons, ampersands, double quotes, plus + signs, equals signs, questions marks, and so on in the name. (The service + does not prevent the use of these characters. But because they must be + URL-encoded wherever used, their use is strongly discouraged.) + * Do not use the name of an audio resource that has already been added to + the custom model. + :param file audio_resource: The audio resource that is to be added to the + custom acoustic model, an individual audio file or an archive file. + With the `curl` command, use the `--data-binary` option to upload the file + for the request. + :param str content_type: (optional) For an audio-type resource, the format + (MIME type) of the audio. For more information, see **Content types for + audio-type resources** in the method description. + For an archive-type resource, the media type of the archive file. For more + information, see **Content types for archive-type resources** in the method + description. + :param str contained_content_type: (optional) **For an archive-type + resource,** specify the format of the audio files that are contained in the + archive file if they are of type `audio/alaw`, `audio/basic`, `audio/l16`, + or `audio/mulaw`. Include the `rate`, `channels`, and `endianness` + parameters where necessary. In this case, all audio files that are + contained in the archive file must be of the indicated type. + For all other audio formats, you can omit the header. In this case, the + audio files can be of multiple types as long as they are not of the types + listed in the previous paragraph. + The parameter accepts all of the audio formats that are supported for use + with speech recognition. For more information, see **Content types for + audio-type resources** in the method description. + **For an audio-type resource,** omit the header. + :param bool allow_overwrite: (optional) If `true`, the specified audio + resource overwrites an existing audio resource with the same name. If + `false`, the request fails if an audio resource with the same name already + exists. The parameter has no effect if an audio resource with the same name + does not already exist. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2747,8 +2826,8 @@ def add_audio(self, raise ValueError('audio_resource must be provided') headers = { - 'Contained-Content-Type': contained_content_type, - 'Content-Type': content_type + 'Content-Type': content_type, + 'Contained-Content-Type': contained_content_type } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2761,13 +2840,14 @@ def add_audio(self, url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=True) + response = self.send(request) return response def get_audio(self, customization_id, audio_name, **kwargs): @@ -2795,11 +2875,12 @@ def get_audio(self, customization_id, audio_name, **kwargs): **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). - :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 request with - credentials for the instance of the service that owns the custom model. - :param str audio_name: The name of the audio resource for the custom acoustic - model. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str audio_name: The name of the audio resource for the custom + acoustic model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2818,8 +2899,9 @@ def get_audio(self, customization_id, audio_name, **kwargs): url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def delete_audio(self, customization_id, audio_name, **kwargs): @@ -2837,11 +2919,12 @@ def delete_audio(self, customization_id, audio_name, **kwargs): **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). - :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 request with - credentials for the instance of the service that owns the custom model. - :param str audio_name: The name of the audio resource for the custom acoustic - model. + :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 + request with credentials for the instance of the service that owns the + custom model. + :param str audio_name: The name of the audio resource for the custom + acoustic model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2860,8 +2943,9 @@ def delete_audio(self, customization_id, audio_name, **kwargs): url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, accept_json=True) + response = self.send(request) return response ######################### @@ -2882,7 +2966,8 @@ def delete_user_data(self, customer_id, **kwargs): **See also:** [Information security](https://cloud.ibm.com/docs/services/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. + :param str customer_id: The customer ID for which all data is to be + deleted. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2901,15 +2986,325 @@ def delete_user_data(self, customer_id, **kwargs): params = {'customer_id': customer_id} url = '/v1/user_data' - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response +class GetModelEnums(object): + + class ModelId(Enum): + """ + The identifier of the model in the form of its name from the output of the **Get a + model** method. + """ + AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' + DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' + DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' + EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' + EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' + EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' + EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' + ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' + ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' + ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' + ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' + ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' + ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' + ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' + ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' + FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' + JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' + KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' + ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' + ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' + + +class RecognizeEnums(object): + + class ContentType(Enum): + """ + The format (MIME type) of the audio. For more information about specifying an + audio format, see **Audio formats (content types)** in the method description. + """ + APPLICATION_OCTET_STREAM = 'application/octet-stream' + AUDIO_ALAW = 'audio/alaw' + AUDIO_BASIC = 'audio/basic' + AUDIO_FLAC = 'audio/flac' + AUDIO_G729 = 'audio/g729' + AUDIO_L16 = 'audio/l16' + AUDIO_MP3 = 'audio/mp3' + AUDIO_MPEG = 'audio/mpeg' + AUDIO_MULAW = 'audio/mulaw' + AUDIO_OGG = 'audio/ogg' + AUDIO_OGG_CODECS_OPUS = 'audio/ogg;codecs=opus' + AUDIO_OGG_CODECS_VORBIS = 'audio/ogg;codecs=vorbis' + AUDIO_WAV = 'audio/wav' + AUDIO_WEBM = 'audio/webm' + AUDIO_WEBM_CODECS_OPUS = 'audio/webm;codecs=opus' + AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' + + 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). + """ + AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' + DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' + DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' + EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' + EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' + EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' + EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' + ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' + ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' + ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' + ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' + ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' + ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' + ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' + ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' + FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' + JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' + KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' + ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' + ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' + + +class CreateJobEnums(object): + + class ContentType(Enum): + """ + The format (MIME type) of the audio. For more information about specifying an + audio format, see **Audio formats (content types)** in the method description. + """ + APPLICATION_OCTET_STREAM = 'application/octet-stream' + AUDIO_ALAW = 'audio/alaw' + AUDIO_BASIC = 'audio/basic' + AUDIO_FLAC = 'audio/flac' + AUDIO_G729 = 'audio/g729' + AUDIO_L16 = 'audio/l16' + AUDIO_MP3 = 'audio/mp3' + AUDIO_MPEG = 'audio/mpeg' + AUDIO_MULAW = 'audio/mulaw' + AUDIO_OGG = 'audio/ogg' + AUDIO_OGG_CODECS_OPUS = 'audio/ogg;codecs=opus' + AUDIO_OGG_CODECS_VORBIS = 'audio/ogg;codecs=vorbis' + AUDIO_WAV = 'audio/wav' + AUDIO_WEBM = 'audio/webm' + AUDIO_WEBM_CODECS_OPUS = 'audio/webm;codecs=opus' + AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' + + 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). + """ + AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' + DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' + DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' + EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' + EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' + EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' + EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' + ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' + ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' + ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' + ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' + ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' + ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' + ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' + ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' + FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' + JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' + KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' + ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' + ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' + + class Events(Enum): + """ + If the job includes a callback URL, a comma-separated list of notification events + to which to subscribe. Valid events are + * `recognitions.started` generates a callback notification when the service begins + to process the job. + * `recognitions.completed` generates a callback notification when the job is + complete. You must use the **Check a job** method to retrieve the results before + they time out or are deleted. + * `recognitions.completed_with_results` generates a callback notification when the + job is complete. The notification includes the results of the request. + * `recognitions.failed` generates a callback notification if the service + experiences an error while processing the job. + The `recognitions.completed` and `recognitions.completed_with_results` events are + incompatible. You can specify only of the two events. + If the job includes a callback URL, omit the parameter to subscribe to the default + events: `recognitions.started`, `recognitions.completed`, and + `recognitions.failed`. If the job does not include a callback URL, omit the + parameter. + """ + RECOGNITIONS_STARTED = 'recognitions.started' + RECOGNITIONS_COMPLETED = 'recognitions.completed' + RECOGNITIONS_COMPLETED_WITH_RESULTS = 'recognitions.completed_with_results' + RECOGNITIONS_FAILED = 'recognitions.failed' + + +class TrainLanguageModelEnums(object): + + class WordTypeToAdd(Enum): + """ + The type of words from the custom language model's words resource on which to + train the model: + * `all` (the default) trains the model on all new words, regardless of whether + they were extracted from corpora or grammars or were added or modified by the + user. + * `user` trains the model only on new words that were added or modified by the + user directly. The model is not trained on new words extracted from corpora or + grammars. + """ + ALL = 'all' + USER = 'user' + + +class ListWordsEnums(object): + + class WordType(Enum): + """ + The type of words to be listed from the custom language model's words resource: + * `all` (the default) shows all words. + * `user` shows only custom words that were added or modified by the user directly. + * `corpora` shows only OOV that were extracted from corpora. + * `grammars` shows only OOV words that are recognized by grammars. + """ + ALL = 'all' + USER = 'user' + CORPORA = 'corpora' + GRAMMARS = 'grammars' + + class Sort(Enum): + """ + Indicates the order in which the words are to be listed, `alphabetical` or by + `count`. You can prepend an optional `+` or `-` to an argument to indicate whether + the results are to be sorted in ascending or descending order. By default, words + are sorted in ascending alphabetical order. For alphabetical ordering, the + lexicographical precedence is numeric values, uppercase letters, and lowercase + letters. For count ordering, values with the same count are ordered + alphabetically. With the `curl` command, URL-encode the `+` symbol as `%2B`. + """ + ALPHABETICAL = 'alphabetical' + COUNT = 'count' + + +class AddGrammarEnums(object): + + class ContentType(Enum): + """ + The format (MIME type) of the grammar file: + * `application/srgs` for Augmented Backus-Naur Form (ABNF), which uses a + plain-text representation that is similar to traditional BNF grammars. + * `application/srgs+xml` for XML Form, which uses XML elements to represent the + grammar. + """ + APPLICATION_SRGS = 'application/srgs' + APPLICATION_SRGS_XML = 'application/srgs+xml' + + +class AddAudioEnums(object): + + class ContentType(Enum): + """ + For an audio-type resource, the format (MIME type) of the audio. For more + information, see **Content types for audio-type resources** in the method + description. + For an archive-type resource, the media type of the archive file. For more + information, see **Content types for archive-type resources** in the method + description. + """ + APPLICATION_ZIP = 'application/zip' + APPLICATION_GZIP = 'application/gzip' + AUDIO_ALAW = 'audio/alaw' + AUDIO_BASIC = 'audio/basic' + AUDIO_FLAC = 'audio/flac' + AUDIO_G729 = 'audio/g729' + AUDIO_L16 = 'audio/l16' + AUDIO_MP3 = 'audio/mp3' + AUDIO_MPEG = 'audio/mpeg' + AUDIO_MULAW = 'audio/mulaw' + AUDIO_OGG = 'audio/ogg' + AUDIO_OGG_CODECS_OPUS = 'audio/ogg;codecs=opus' + AUDIO_OGG_CODECS_VORBIS = 'audio/ogg;codecs=vorbis' + AUDIO_WAV = 'audio/wav' + AUDIO_WEBM = 'audio/webm' + AUDIO_WEBM_CODECS_OPUS = 'audio/webm;codecs=opus' + AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' + + class ContainedContentType(Enum): + """ + **For an archive-type resource,** specify the format of the audio files that are + contained in the archive file if they are of type `audio/alaw`, `audio/basic`, + `audio/l16`, or `audio/mulaw`. Include the `rate`, `channels`, and `endianness` + parameters where necessary. In this case, all audio files that are contained in + the archive file must be of the indicated type. + For all other audio formats, you can omit the header. In this case, the audio + files can be of multiple types as long as they are not of the types listed in the + previous paragraph. + The parameter accepts all of the audio formats that are supported for use with + speech recognition. For more information, see **Content types for audio-type + resources** in the method description. + **For an audio-type resource,** omit the header. + """ + AUDIO_ALAW = 'audio/alaw' + AUDIO_BASIC = 'audio/basic' + AUDIO_FLAC = 'audio/flac' + AUDIO_G729 = 'audio/g729' + AUDIO_L16 = 'audio/l16' + AUDIO_MP3 = 'audio/mp3' + AUDIO_MPEG = 'audio/mpeg' + AUDIO_MULAW = 'audio/mulaw' + AUDIO_OGG = 'audio/ogg' + AUDIO_OGG_CODECS_OPUS = 'audio/ogg;codecs=opus' + AUDIO_OGG_CODECS_VORBIS = 'audio/ogg;codecs=vorbis' + AUDIO_WAV = 'audio/wav' + AUDIO_WEBM = 'audio/webm' + AUDIO_WEBM_CODECS_OPUS = 'audio/webm;codecs=opus' + AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' + + ############################################################################## # Models ############################################################################## @@ -2919,50 +3314,55 @@ class AcousticModel(object): """ Information about an existing custom acoustic model. - :attr str customization_id: The customization ID (GUID) of the custom acoustic model. - The **Create a custom acoustic model** method returns only this field of the object; - it does not return the other fields. - :attr str created: (optional) The date and time in Coordinated Universal Time (UTC) at - which the custom acoustic model was created. The value is provided in full ISO 8601 - format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time (UTC) at - which the custom acoustic model was last modified. The `created` and `updated` fields - are equal when an acoustic model is first added but has yet to be updated. The value - is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - :attr str language: (optional) The language identifier of the custom acoustic model - (for example, `en-US`). - :attr list[str] versions: (optional) A list of the available versions of the custom - acoustic model. Each element of the array indicates a version of the base model with - which the custom model can be used. Multiple versions exist only if the custom model - has been upgraded; otherwise, only a single version is shown. + :attr str customization_id: The customization ID (GUID) of the custom acoustic + model. The **Create a custom acoustic model** method returns only this field of + the object; it does not return the other fields. + :attr str created: (optional) The date and time in Coordinated Universal Time + (UTC) at which the custom acoustic model was created. The value is provided in + full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). + :attr str updated: (optional) The date and time in Coordinated Universal Time + (UTC) at which the custom acoustic model was last modified. The `created` and + `updated` fields are equal when an acoustic model is first added but has yet to + be updated. The value is provided in full ISO 8601 format + (YYYY-MM-DDThh:mm:ss.sTZD). + :attr str language: (optional) The language identifier of the custom acoustic + model (for example, `en-US`). + :attr list[str] versions: (optional) A list of the available versions of the + custom acoustic model. Each element of the array indicates a version of the base + model with which the custom model can be used. Multiple versions exist only if + the custom model has been upgraded; otherwise, only a single version is shown. :attr str owner: (optional) The GUID of the credentials for the instance of the - service that owns the custom acoustic model. + service that owns the custom acoustic model. :attr str name: (optional) The name of the custom acoustic model. :attr str description: (optional) The description of the custom acoustic model. - :attr str base_model_name: (optional) The name of the language model for which the - custom acoustic model was created. + :attr str base_model_name: (optional) The name of the language model for which + the custom acoustic model was created. :attr str status: (optional) The current status of the custom acoustic model: - * `pending`: The model was created but is waiting either for valid training data to be - added or for the service to finish analyzing added data. - * `ready`: The model contains valid data and is ready to be trained. If the model - contains a mix of valid and invalid resources, you need to set the `strict` parameter - to `false` for the training to proceed. - * `training`: The model is currently being trained. - * `available`: The model is trained and ready to use. - * `upgrading`: The model is currently being upgraded. - * `failed`: Training of the model failed. - :attr int progress: (optional) A percentage that indicates the progress of the custom - acoustic model's current training. A value of `100` means that the model is fully - trained. **Note:** The `progress` field does not currently reflect the progress of the - training. The field changes from `0` to `100` when training is complete. + * `pending`: The model was created but is waiting either for valid training data + to be added or for the service to finish analyzing added data. + * `ready`: The model contains valid data and is ready to be trained. If the + model contains a mix of valid and invalid resources, you need to set the + `strict` parameter to `false` for the training to proceed. + * `training`: The model is currently being trained. + * `available`: The model is trained and ready to use. + * `upgrading`: The model is currently being upgraded. + * `failed`: Training of the model failed. + :attr int progress: (optional) A percentage that indicates the progress of the + custom acoustic model's current training. A value of `100` means that the model + is fully trained. **Note:** The `progress` field does not currently reflect the + progress of the training. The field changes from `0` to `100` when training is + complete. :attr str warnings: (optional) If the request included unknown parameters, the - following message: `Unexpected query parameter(s) ['parameters'] detected`, where - `parameters` is a list that includes a quoted string for each unknown parameter. + following message: `Unexpected query parameter(s) ['parameters'] detected`, + where `parameters` is a list that includes a quoted string for each unknown + parameter. """ def __init__(self, customization_id, + *, created=None, + updated=None, language=None, versions=None, owner=None, @@ -2971,51 +3371,55 @@ def __init__(self, base_model_name=None, status=None, progress=None, - warnings=None, - updated=None): + warnings=None): """ Initialize a AcousticModel object. - :param str customization_id: The customization ID (GUID) of the custom acoustic - model. The **Create a custom acoustic model** method returns only this field of - the object; it does not return the other fields. - :param str created: (optional) The date and time in Coordinated Universal Time - (UTC) at which the custom acoustic model was created. The value is provided in - full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :param str updated: (optional) The date and time in Coordinated Universal Time - (UTC) at which the custom acoustic model was last modified. The `created` and - `updated` fields are equal when an acoustic model is first added but has yet to be - updated. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - :param str language: (optional) The language identifier of the custom acoustic - model (for example, `en-US`). - :param list[str] versions: (optional) A list of the available versions of the - custom acoustic model. Each element of the array indicates a version of the base - model with which the custom model can be used. Multiple versions exist only if the - custom model has been upgraded; otherwise, only a single version is shown. - :param str owner: (optional) The GUID of the credentials for the instance of the - service that owns the custom acoustic model. + :param str customization_id: The customization ID (GUID) of the custom + acoustic model. The **Create a custom acoustic model** method returns only + this field of the object; it does not return the other fields. + :param str created: (optional) The date and time in Coordinated Universal + Time (UTC) at which the custom acoustic model was created. The value is + provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). + :param str updated: (optional) The date and time in Coordinated Universal + Time (UTC) at which the custom acoustic model was last modified. The + `created` and `updated` fields are equal when an acoustic model is first + added but has yet to be updated. The value is provided in full ISO 8601 + format (YYYY-MM-DDThh:mm:ss.sTZD). + :param str language: (optional) The language identifier of the custom + acoustic model (for example, `en-US`). + :param list[str] versions: (optional) A list of the available versions of + the custom acoustic model. Each element of the array indicates a version of + the base model with which the custom model can be used. Multiple versions + exist only if the custom model has been upgraded; otherwise, only a single + version is shown. + :param str owner: (optional) The GUID of the credentials for the instance + of the service that owns the custom acoustic model. :param str name: (optional) The name of the custom acoustic model. - :param str description: (optional) The description of the custom acoustic model. - :param str base_model_name: (optional) The name of the language model for which - the custom acoustic model was created. - :param str status: (optional) The current status of the custom acoustic model: - * `pending`: The model was created but is waiting either for valid training data - to be added or for the service to finish analyzing added data. - * `ready`: The model contains valid data and is ready to be trained. If the model - contains a mix of valid and invalid resources, you need to set the `strict` - parameter to `false` for the training to proceed. - * `training`: The model is currently being trained. - * `available`: The model is trained and ready to use. - * `upgrading`: The model is currently being upgraded. - * `failed`: Training of the model failed. - :param int progress: (optional) A percentage that indicates the progress of the - custom acoustic model's current training. A value of `100` means that the model is - fully trained. **Note:** The `progress` field does not currently reflect the - progress of the training. The field changes from `0` to `100` when training is - complete. - :param str warnings: (optional) If the request included unknown parameters, the - following message: `Unexpected query parameter(s) ['parameters'] detected`, where - `parameters` is a list that includes a quoted string for each unknown parameter. + :param str description: (optional) The description of the custom acoustic + model. + :param str base_model_name: (optional) The name of the language model for + which the custom acoustic model was created. + :param str status: (optional) The current status of the custom acoustic + model: + * `pending`: The model was created but is waiting either for valid training + data to be added or for the service to finish analyzing added data. + * `ready`: The model contains valid data and is ready to be trained. If the + model contains a mix of valid and invalid resources, you need to set the + `strict` parameter to `false` for the training to proceed. + * `training`: The model is currently being trained. + * `available`: The model is trained and ready to use. + * `upgrading`: The model is currently being upgraded. + * `failed`: Training of the model failed. + :param int progress: (optional) A percentage that indicates the progress of + the custom acoustic model's current training. A value of `100` means that + the model is fully trained. **Note:** The `progress` field does not + currently reflect the progress of the training. The field changes from `0` + to `100` when training is complete. + :param str warnings: (optional) If the request included unknown parameters, + the following message: `Unexpected query parameter(s) ['parameters'] + detected`, where `parameters` is a list that includes a quoted string for + each unknown parameter. """ self.customization_id = customization_id self.created = created @@ -3119,25 +3523,47 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The current status of the custom acoustic model: + * `pending`: The model was created but is waiting either for valid training data + to be added or for the service to finish analyzing added data. + * `ready`: The model contains valid data and is ready to be trained. If the model + contains a mix of valid and invalid resources, you need to set the `strict` + parameter to `false` for the training to proceed. + * `training`: The model is currently being trained. + * `available`: The model is trained and ready to use. + * `upgrading`: The model is currently being upgraded. + * `failed`: Training of the model failed. + """ + PENDING = "pending" + READY = "ready" + TRAINING = "training" + AVAILABLE = "available" + UPGRADING = "upgrading" + FAILED = "failed" + class AcousticModels(object): """ Information about existing custom acoustic models. - :attr list[AcousticModel] customizations: An array of `AcousticModel` objects that - provides information about each available custom acoustic model. The array is empty if - the requesting credentials own no custom acoustic models (if no language is specified) - or own no custom acoustic models for the specified language. + :attr list[AcousticModel] customizations: An array of `AcousticModel` objects + that provides information about each available custom acoustic model. The array + is empty if the requesting credentials own no custom acoustic models (if no + language is specified) or own no custom acoustic models for the specified + language. """ def __init__(self, customizations): """ Initialize a AcousticModels object. - :param list[AcousticModel] customizations: An array of `AcousticModel` objects - that provides information about each available custom acoustic model. The array is - empty if the requesting credentials own no custom acoustic models (if no language - is specified) or own no custom acoustic models for the specified language. + :param list[AcousticModel] customizations: An array of `AcousticModel` + objects that provides information about each available custom acoustic + model. The array is empty if the requesting credentials own no custom + acoustic models (if no language is specified) or own no custom acoustic + models for the specified language. """ self.customizations = customizations @@ -3191,41 +3617,50 @@ class AudioDetails(object): Information about an audio resource from a custom acoustic model. :attr str type: (optional) The type of the audio resource: - * `audio` for an individual audio file - * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files - * `undetermined` for a resource that the service cannot validate (for example, if the - user mistakenly passes a file that does not contain audio, such as a JPEG file). - :attr str codec: (optional) **For an audio-type resource,** the codec in which the - audio is encoded. Omitted for an archive-type resource. - :attr int frequency: (optional) **For an audio-type resource,** the sampling rate of - the audio in Hertz (samples per second). Omitted for an archive-type resource. - :attr str compression: (optional) **For an archive-type resource,** the format of the - compressed archive: - * `zip` for a **.zip** file - * `gzip` for a **.tar.gz** file - Omitted for an audio-type resource. + * `audio` for an individual audio file + * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio + files + * `undetermined` for a resource that the service cannot validate (for example, + if the user mistakenly passes a file that does not contain audio, such as a JPEG + file). + :attr str codec: (optional) **For an audio-type resource,** the codec in which + the audio is encoded. Omitted for an archive-type resource. + :attr int frequency: (optional) **For an audio-type resource,** the sampling + rate of the audio in Hertz (samples per second). Omitted for an archive-type + resource. + :attr str compression: (optional) **For an archive-type resource,** the format + of the compressed archive: + * `zip` for a **.zip** file + * `gzip` for a **.tar.gz** file + Omitted for an audio-type resource. """ - def __init__(self, type=None, codec=None, frequency=None, compression=None): + def __init__(self, + *, + type=None, + codec=None, + frequency=None, + compression=None): """ Initialize a AudioDetails object. :param str type: (optional) The type of the audio resource: - * `audio` for an individual audio file - * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio - files - * `undetermined` for a resource that the service cannot validate (for example, if - the user mistakenly passes a file that does not contain audio, such as a JPEG - file). - :param str codec: (optional) **For an audio-type resource,** the codec in which - the audio is encoded. Omitted for an archive-type resource. - :param int frequency: (optional) **For an audio-type resource,** the sampling rate - of the audio in Hertz (samples per second). Omitted for an archive-type resource. - :param str compression: (optional) **For an archive-type resource,** the format of - the compressed archive: - * `zip` for a **.zip** file - * `gzip` for a **.tar.gz** file - Omitted for an audio-type resource. + * `audio` for an individual audio file + * `archive` for an archive (**.zip** or **.tar.gz**) file that contains + audio files + * `undetermined` for a resource that the service cannot validate (for + example, if the user mistakenly passes a file that does not contain audio, + such as a JPEG file). + :param str codec: (optional) **For an audio-type resource,** the codec in + which the audio is encoded. Omitted for an archive-type resource. + :param int frequency: (optional) **For an audio-type resource,** the + sampling rate of the audio in Hertz (samples per second). Omitted for an + archive-type resource. + :param str compression: (optional) **For an archive-type resource,** the + format of the compressed archive: + * `zip` for a **.zip** file + * `gzip` for a **.tar.gz** file + Omitted for an audio-type resource. """ self.type = type self.codec = codec @@ -3279,38 +3714,64 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The type of the audio resource: + * `audio` for an individual audio file + * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio + files + * `undetermined` for a resource that the service cannot validate (for example, if + the user mistakenly passes a file that does not contain audio, such as a JPEG + file). + """ + AUDIO = "audio" + ARCHIVE = "archive" + UNDETERMINED = "undetermined" + + class CompressionEnum(Enum): + """ + **For an archive-type resource,** the format of the compressed archive: + * `zip` for a **.zip** file + * `gzip` for a **.tar.gz** file + Omitted for an audio-type resource. + """ + ZIP = "zip" + GZIP = "gzip" + class AudioListing(object): """ Information about an audio resource from a custom acoustic model. - :attr int duration: (optional) **For an audio-type resource,** the total seconds of - audio in the resource. Omitted for an archive-type resource. - :attr str name: (optional) **For an audio-type resource,** the user-specified name of - the resource. Omitted for an archive-type resource. + :attr int duration: (optional) **For an audio-type resource,** the total + seconds of audio in the resource. Omitted for an archive-type resource. + :attr str name: (optional) **For an audio-type resource,** the user-specified + name of the resource. Omitted for an archive-type resource. :attr AudioDetails details: (optional) **For an audio-type resource,** an - `AudioDetails` object that provides detailed information about the resource. The - object is empty until the service finishes processing the audio. Omitted for an - archive-type resource. + `AudioDetails` object that provides detailed information about the resource. The + object is empty until the service finishes processing the audio. Omitted for an + archive-type resource. :attr str status: (optional) **For an audio-type resource,** the status of the - resource: - * `ok`: The service successfully analyzed the audio data. The data can be used to - train the custom model. - * `being_processed`: The service is still analyzing the audio data. The service cannot - accept requests to add new audio resources or to train the custom model until its - analysis is complete. - * `invalid`: The audio data is not valid for training the custom model (possibly - because it has the wrong format or sampling rate, or because it is corrupted). - Omitted for an archive-type resource. - :attr AudioResource container: (optional) **For an archive-type resource,** an object - of type `AudioResource` that provides information about the resource. Omitted for an - audio-type resource. - :attr list[AudioResource] audio: (optional) **For an archive-type resource,** an array - of `AudioResource` objects that provides information about the audio-type resources - that are contained in the resource. Omitted for an audio-type resource. + resource: + * `ok`: The service successfully analyzed the audio data. The data can be used + to train the custom model. + * `being_processed`: The service is still analyzing the audio data. The service + cannot accept requests to add new audio resources or to train the custom model + until its analysis is complete. + * `invalid`: The audio data is not valid for training the custom model (possibly + because it has the wrong format or sampling rate, or because it is corrupted). + Omitted for an archive-type resource. + :attr AudioResource container: (optional) **For an archive-type resource,** an + object of type `AudioResource` that provides information about the resource. + Omitted for an audio-type resource. + :attr list[AudioResource] audio: (optional) **For an archive-type resource,** an + array of `AudioResource` objects that provides information about the audio-type + resources that are contained in the resource. Omitted for an audio-type + resource. """ def __init__(self, + *, duration=None, name=None, details=None, @@ -3320,30 +3781,32 @@ def __init__(self, """ Initialize a AudioListing object. - :param int duration: (optional) **For an audio-type resource,** the total seconds - of audio in the resource. Omitted for an archive-type resource. - :param str name: (optional) **For an audio-type resource,** the user-specified - name of the resource. Omitted for an archive-type resource. + :param int duration: (optional) **For an audio-type resource,** the total + seconds of audio in the resource. Omitted for an archive-type resource. + :param str name: (optional) **For an audio-type resource,** the + user-specified name of the resource. Omitted for an archive-type resource. :param AudioDetails details: (optional) **For an audio-type resource,** an - `AudioDetails` object that provides detailed information about the resource. The - object is empty until the service finishes processing the audio. Omitted for an - archive-type resource. - :param str status: (optional) **For an audio-type resource,** the status of the - resource: - * `ok`: The service successfully analyzed the audio data. The data can be used to - train the custom model. - * `being_processed`: The service is still analyzing the audio data. The service - cannot accept requests to add new audio resources or to train the custom model - until its analysis is complete. - * `invalid`: The audio data is not valid for training the custom model (possibly - because it has the wrong format or sampling rate, or because it is corrupted). - Omitted for an archive-type resource. - :param AudioResource container: (optional) **For an archive-type resource,** an - object of type `AudioResource` that provides information about the resource. - Omitted for an audio-type resource. - :param list[AudioResource] audio: (optional) **For an archive-type resource,** an - array of `AudioResource` objects that provides information about the audio-type - resources that are contained in the resource. Omitted for an audio-type resource. + `AudioDetails` object that provides detailed information about the + resource. The object is empty until the service finishes processing the + audio. Omitted for an archive-type resource. + :param str status: (optional) **For an audio-type resource,** the status of + the resource: + * `ok`: The service successfully analyzed the audio data. The data can be + used to train the custom model. + * `being_processed`: The service is still analyzing the audio data. The + service cannot accept requests to add new audio resources or to train the + custom model until its analysis is complete. + * `invalid`: The audio data is not valid for training the custom model + (possibly because it has the wrong format or sampling rate, or because it + is corrupted). + Omitted for an archive-type resource. + :param AudioResource container: (optional) **For an archive-type + resource,** an object of type `AudioResource` that provides information + about the resource. Omitted for an audio-type resource. + :param list[AudioResource] audio: (optional) **For an archive-type + resource,** an array of `AudioResource` objects that provides information + about the audio-type resources that are contained in the resource. Omitted + for an audio-type resource. """ self.duration = duration self.name = name @@ -3411,32 +3874,48 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + **For an audio-type resource,** the status of the resource: + * `ok`: The service successfully analyzed the audio data. The data can be used to + train the custom model. + * `being_processed`: The service is still analyzing the audio data. The service + cannot accept requests to add new audio resources or to train the custom model + until its analysis is complete. + * `invalid`: The audio data is not valid for training the custom model (possibly + because it has the wrong format or sampling rate, or because it is corrupted). + Omitted for an archive-type resource. + """ + OK = "ok" + BEING_PROCESSED = "being_processed" + INVALID = "invalid" + class AudioMetrics(object): """ If audio metrics are requested, information about the signal characteristics of the input audio. - :attr float sampling_interval: The interval in seconds (typically 0.1 seconds) at - which the service calculated the audio metrics. In other words, how often the service - calculated the metrics. A single unit in each histogram (see the - `AudioMetricsHistogramBin` object) is calculated based on a `sampling_interval` length - of audio. + :attr float sampling_interval: The interval in seconds (typically 0.1 seconds) + at which the service calculated the audio metrics. In other words, how often the + service calculated the metrics. A single unit in each histogram (see the + `AudioMetricsHistogramBin` object) is calculated based on a `sampling_interval` + length of audio. :attr AudioMetricsDetails accumulated: Detailed information about the signal - characteristics of the input audio. + characteristics of the input audio. """ def __init__(self, sampling_interval, accumulated): """ Initialize a AudioMetrics object. - :param float sampling_interval: The interval in seconds (typically 0.1 seconds) at - which the service calculated the audio metrics. In other words, how often the - service calculated the metrics. A single unit in each histogram (see the - `AudioMetricsHistogramBin` object) is calculated based on a `sampling_interval` - length of audio. - :param AudioMetricsDetails accumulated: Detailed information about the signal - characteristics of the input audio. + :param float sampling_interval: The interval in seconds (typically 0.1 + seconds) at which the service calculated the audio metrics. In other words, + how often the service calculated the metrics. A single unit in each + histogram (see the `AudioMetricsHistogramBin` object) is calculated based + on a `sampling_interval` length of audio. + :param AudioMetricsDetails accumulated: Detailed information about the + signal characteristics of the input audio. """ self.sampling_interval = sampling_interval self.accumulated = accumulated @@ -3496,46 +3975,46 @@ class AudioMetricsDetails(object): Detailed information about the signal characteristics of the input audio. :attr bool final: If `true`, indicates the end of the audio stream, meaning that - transcription is complete. Currently, the field is always `true`. The service returns - metrics just once per audio stream. The results provide aggregated audio metrics that - pertain to the complete audio stream. + transcription is complete. Currently, the field is always `true`. The service + returns metrics just once per audio stream. The results provide aggregated audio + metrics that pertain to the complete audio stream. :attr float end_time: The end time in seconds of the block of audio to which the - metrics apply. - :attr float signal_to_noise_ratio: (optional) The signal-to-noise ratio (SNR) for the - audio signal. The value indicates the ratio of speech to noise in the audio. A valid - value lies in the range of 0 to 100 decibels (dB). The service omits the field if it - cannot compute the SNR for the audio. - :attr float speech_ratio: The ratio of speech to non-speech segments in the audio - signal. The value lies in the range of 0.0 to 1.0. - :attr float high_frequency_loss: The probability that the audio signal is missing the - upper half of its frequency content. - * A value close to 1.0 typically indicates artificially up-sampled audio, which - negatively impacts the accuracy of the transcription results. - * A value at or near 0.0 indicates that the audio signal is good and has a full - spectrum. - * A value around 0.5 means that detection of the frequency content is unreliable or - not available. + metrics apply. + :attr float signal_to_noise_ratio: (optional) The signal-to-noise ratio (SNR) + for the audio signal. The value indicates the ratio of speech to noise in the + audio. A valid value lies in the range of 0 to 100 decibels (dB). The service + omits the field if it cannot compute the SNR for the audio. + :attr float speech_ratio: The ratio of speech to non-speech segments in the + audio signal. The value lies in the range of 0.0 to 1.0. + :attr float high_frequency_loss: The probability that the audio signal is + missing the upper half of its frequency content. + * A value close to 1.0 typically indicates artificially up-sampled audio, which + negatively impacts the accuracy of the transcription results. + * A value at or near 0.0 indicates that the audio signal is good and has a full + spectrum. + * A value around 0.5 means that detection of the frequency content is unreliable + or not available. :attr list[AudioMetricsHistogramBin] direct_current_offset: An array of - `AudioMetricsHistogramBin` objects that defines a histogram of the cumulative direct - current (DC) component of the audio signal. + `AudioMetricsHistogramBin` objects that defines a histogram of the cumulative + direct current (DC) component of the audio signal. :attr list[AudioMetricsHistogramBin] clipping_rate: An array of - `AudioMetricsHistogramBin` objects that defines a histogram of the clipping rate for - the audio segments. The clipping rate is defined as the fraction of samples in the - segment that reach the maximum or minimum value that is offered by the audio - quantization range. The service auto-detects either a 16-bit Pulse-Code - Modulation(PCM) audio range (-32768 to +32767) or a unit range (-1.0 to +1.0). The - clipping rate is between 0.0 and 1.0, with higher values indicating possible - degradation of speech recognition. + `AudioMetricsHistogramBin` objects that defines a histogram of the clipping rate + for the audio segments. The clipping rate is defined as the fraction of samples + in the segment that reach the maximum or minimum value that is offered by the + audio quantization range. The service auto-detects either a 16-bit Pulse-Code + Modulation(PCM) audio range (-32768 to +32767) or a unit range (-1.0 to +1.0). + The clipping rate is between 0.0 and 1.0, with higher values indicating possible + degradation of speech recognition. :attr list[AudioMetricsHistogramBin] speech_level: An array of - `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in - segments of the audio that contain speech. The signal level is computed as the - Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range 0.0 - (minimum level) to 1.0 (maximum level). + `AudioMetricsHistogramBin` objects that defines a histogram of the signal level + in segments of the audio that contain speech. The signal level is computed as + the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range + 0.0 (minimum level) to 1.0 (maximum level). :attr list[AudioMetricsHistogramBin] non_speech_level: An array of - `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in - segments of the audio that do not contain speech. The signal level is computed as the - Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range 0.0 - (minimum level) to 1.0 (maximum level). + `AudioMetricsHistogramBin` objects that defines a histogram of the signal level + in segments of the audio that do not contain speech. The signal level is + computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized + to the range 0.0 (minimum level) to 1.0 (maximum level). """ def __init__(self, @@ -3547,51 +4026,53 @@ def __init__(self, clipping_rate, speech_level, non_speech_level, + *, signal_to_noise_ratio=None): """ Initialize a AudioMetricsDetails object. - :param bool final: If `true`, indicates the end of the audio stream, meaning that - transcription is complete. Currently, the field is always `true`. The service - returns metrics just once per audio stream. The results provide aggregated audio - metrics that pertain to the complete audio stream. - :param float end_time: The end time in seconds of the block of audio to which the - metrics apply. - :param float speech_ratio: The ratio of speech to non-speech segments in the audio - signal. The value lies in the range of 0.0 to 1.0. - :param float high_frequency_loss: The probability that the audio signal is missing - the upper half of its frequency content. - * A value close to 1.0 typically indicates artificially up-sampled audio, which - negatively impacts the accuracy of the transcription results. - * A value at or near 0.0 indicates that the audio signal is good and has a full - spectrum. - * A value around 0.5 means that detection of the frequency content is unreliable - or not available. + :param bool final: If `true`, indicates the end of the audio stream, + meaning that transcription is complete. Currently, the field is always + `true`. The service returns metrics just once per audio stream. The results + provide aggregated audio metrics that pertain to the complete audio stream. + :param float end_time: The end time in seconds of the block of audio to + which the metrics apply. + :param float speech_ratio: The ratio of speech to non-speech segments in + the audio signal. The value lies in the range of 0.0 to 1.0. + :param float high_frequency_loss: The probability that the audio signal is + missing the upper half of its frequency content. + * A value close to 1.0 typically indicates artificially up-sampled audio, + which negatively impacts the accuracy of the transcription results. + * A value at or near 0.0 indicates that the audio signal is good and has a + full spectrum. + * A value around 0.5 means that detection of the frequency content is + unreliable or not available. :param list[AudioMetricsHistogramBin] direct_current_offset: An array of - `AudioMetricsHistogramBin` objects that defines a histogram of the cumulative - direct current (DC) component of the audio signal. + `AudioMetricsHistogramBin` objects that defines a histogram of the + cumulative direct current (DC) component of the audio signal. :param list[AudioMetricsHistogramBin] clipping_rate: An array of - `AudioMetricsHistogramBin` objects that defines a histogram of the clipping rate - for the audio segments. The clipping rate is defined as the fraction of samples in - the segment that reach the maximum or minimum value that is offered by the audio - quantization range. The service auto-detects either a 16-bit Pulse-Code - Modulation(PCM) audio range (-32768 to +32767) or a unit range (-1.0 to +1.0). The - clipping rate is between 0.0 and 1.0, with higher values indicating possible - degradation of speech recognition. + `AudioMetricsHistogramBin` objects that defines a histogram of the clipping + rate for the audio segments. The clipping rate is defined as the fraction + of samples in the segment that reach the maximum or minimum value that is + offered by the audio quantization range. The service auto-detects either a + 16-bit Pulse-Code Modulation(PCM) audio range (-32768 to +32767) or a unit + range (-1.0 to +1.0). The clipping rate is between 0.0 and 1.0, with higher + values indicating possible degradation of speech recognition. :param list[AudioMetricsHistogramBin] speech_level: An array of - `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in - segments of the audio that contain speech. The signal level is computed as the - Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range 0.0 - (minimum level) to 1.0 (maximum level). + `AudioMetricsHistogramBin` objects that defines a histogram of the signal + level in segments of the audio that contain speech. The signal level is + computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale + normalized to the range 0.0 (minimum level) to 1.0 (maximum level). :param list[AudioMetricsHistogramBin] non_speech_level: An array of - `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in - segments of the audio that do not contain speech. The signal level is computed as - the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range - 0.0 (minimum level) to 1.0 (maximum level). - :param float signal_to_noise_ratio: (optional) The signal-to-noise ratio (SNR) for - the audio signal. The value indicates the ratio of speech to noise in the audio. A - valid value lies in the range of 0 to 100 decibels (dB). The service omits the - field if it cannot compute the SNR for the audio. + `AudioMetricsHistogramBin` objects that defines a histogram of the signal + level in segments of the audio that do not contain speech. The signal level + is computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale + normalized to the range 0.0 (minimum level) to 1.0 (maximum level). + :param float signal_to_noise_ratio: (optional) The signal-to-noise ratio + (SNR) for the audio signal. The value indicates the ratio of speech to + noise in the audio. A valid value lies in the range of 0 to 100 decibels + (dB). The service omits the field if it cannot compute the SNR for the + audio. """ self.final = final self.end_time = end_time @@ -3814,22 +4295,23 @@ class AudioResource(object): :attr int duration: The total seconds of audio in the audio resource. :attr str name: **For an archive-type resource,** the user-specified name of the - resource. - **For an audio-type resource,** the user-specified name of the resource or the name of - the audio file that the user added for the resource. The value depends on the method - that is called. + resource. + **For an audio-type resource,** the user-specified name of the resource or the + name of the audio file that the user added for the resource. The value depends + on the method that is called. :attr AudioDetails details: An `AudioDetails` object that provides detailed - information about the audio resource. The object is empty until the service finishes - processing the audio. + information about the audio resource. The object is empty until the service + finishes processing the audio. :attr str status: The status of the audio resource: - * `ok`: The service successfully analyzed the audio data. The data can be used to - train the custom model. - * `being_processed`: The service is still analyzing the audio data. The service cannot - accept requests to add new audio resources or to train the custom model until its - analysis is complete. - * `invalid`: The audio data is not valid for training the custom model (possibly - because it has the wrong format or sampling rate, or because it is corrupted). For an - archive file, the entire archive is invalid if any of its audio files are invalid. + * `ok`: The service successfully analyzed the audio data. The data can be used + to train the custom model. + * `being_processed`: The service is still analyzing the audio data. The service + cannot accept requests to add new audio resources or to train the custom model + until its analysis is complete. + * `invalid`: The audio data is not valid for training the custom model (possibly + because it has the wrong format or sampling rate, or because it is corrupted). + For an archive file, the entire archive is invalid if any of its audio files are + invalid. """ def __init__(self, duration, name, details, status): @@ -3837,24 +4319,24 @@ def __init__(self, duration, name, details, status): Initialize a AudioResource object. :param int duration: The total seconds of audio in the audio resource. - :param str name: **For an archive-type resource,** the user-specified name of the - resource. - **For an audio-type resource,** the user-specified name of the resource or the - name of the audio file that the user added for the resource. The value depends on - the method that is called. - :param AudioDetails details: An `AudioDetails` object that provides detailed - information about the audio resource. The object is empty until the service - finishes processing the audio. + :param str name: **For an archive-type resource,** the user-specified name + of the resource. + **For an audio-type resource,** the user-specified name of the resource or + the name of the audio file that the user added for the resource. The value + depends on the method that is called. + :param AudioDetails details: An `AudioDetails` object that provides + detailed information about the audio resource. The object is empty until + the service finishes processing the audio. :param str status: The status of the audio resource: - * `ok`: The service successfully analyzed the audio data. The data can be used to - train the custom model. - * `being_processed`: The service is still analyzing the audio data. The service - cannot accept requests to add new audio resources or to train the custom model - until its analysis is complete. - * `invalid`: The audio data is not valid for training the custom model (possibly - because it has the wrong format or sampling rate, or because it is corrupted). For - an archive file, the entire archive is invalid if any of its audio files are - invalid. + * `ok`: The service successfully analyzed the audio data. The data can be + used to train the custom model. + * `being_processed`: The service is still analyzing the audio data. The + service cannot accept requests to add new audio resources or to train the + custom model until its analysis is complete. + * `invalid`: The audio data is not valid for training the custom model + (possibly because it has the wrong format or sampling rate, or because it + is corrupted). For an archive file, the entire archive is invalid if any of + its audio files are invalid. """ self.duration = duration self.name = name @@ -3923,31 +4405,48 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The status of the audio resource: + * `ok`: The service successfully analyzed the audio data. The data can be used to + train the custom model. + * `being_processed`: The service is still analyzing the audio data. The service + cannot accept requests to add new audio resources or to train the custom model + until its analysis is complete. + * `invalid`: The audio data is not valid for training the custom model (possibly + because it has the wrong format or sampling rate, or because it is corrupted). For + an archive file, the entire archive is invalid if any of its audio files are + invalid. + """ + OK = "ok" + BEING_PROCESSED = "being_processed" + INVALID = "invalid" + class AudioResources(object): """ Information about the audio resources from a custom acoustic model. - :attr float total_minutes_of_audio: The total minutes of accumulated audio summed over - all of the valid audio resources for the custom acoustic model. You can use this value - to determine whether the custom model has too little or too much audio to begin - training. - :attr list[AudioResource] audio: An array of `AudioResource` objects that provides - information about the audio resources of the custom acoustic model. The array is empty - if the custom model has no audio resources. + :attr float total_minutes_of_audio: The total minutes of accumulated audio + summed over all of the valid audio resources for the custom acoustic model. You + can use this value to determine whether the custom model has too little or too + much audio to begin training. + :attr list[AudioResource] audio: An array of `AudioResource` objects that + provides information about the audio resources of the custom acoustic model. The + array is empty if the custom model has no audio resources. """ def __init__(self, total_minutes_of_audio, audio): """ Initialize a AudioResources object. - :param float total_minutes_of_audio: The total minutes of accumulated audio summed - over all of the valid audio resources for the custom acoustic model. You can use - this value to determine whether the custom model has too little or too much audio - to begin training. + :param float total_minutes_of_audio: The total minutes of accumulated audio + summed over all of the valid audio resources for the custom acoustic model. + You can use this value to determine whether the custom model has too little + or too much audio to begin training. :param list[AudioResource] audio: An array of `AudioResource` objects that - provides information about the audio resources of the custom acoustic model. The - array is empty if the custom model has no audio resources. + provides information about the audio resources of the custom acoustic + model. The array is empty if the custom model has no audio resources. """ self.total_minutes_of_audio = total_minutes_of_audio self.audio = audio @@ -4007,9 +4506,9 @@ class Corpora(object): """ Information about the corpora from a custom language model. - :attr list[Corpus] corpora: An array of `Corpus` objects that provides information - about the corpora for the custom model. The array is empty if the custom model has no - corpora. + :attr list[Corpus] corpora: An array of `Corpus` objects that provides + information about the corpora for the custom model. The array is empty if the + custom model has no corpora. """ def __init__(self, corpora): @@ -4017,8 +4516,8 @@ def __init__(self, corpora): Initialize a Corpora object. :param list[Corpus] corpora: An array of `Corpus` objects that provides - information about the corpora for the custom model. The array is empty if the - custom model has no corpora. + information about the corpora for the custom model. The array is empty if + the custom model has no corpora. """ self.corpora = corpora @@ -4068,20 +4567,20 @@ class Corpus(object): Information about a corpus from a custom language model. :attr str name: The name of the corpus. - :attr int total_words: The total number of words in the corpus. The value is `0` while - the corpus is being processed. - :attr int out_of_vocabulary_words: The number of OOV words in the corpus. The value is - `0` while the corpus is being processed. + :attr int total_words: The total number of words in the corpus. The value is `0` + while the corpus is being processed. + :attr int out_of_vocabulary_words: The number of OOV words in the corpus. The + value is `0` while the corpus is being processed. :attr str status: The status of the corpus: - * `analyzed`: The service successfully analyzed the corpus. The custom model can be - trained with data from the corpus. - * `being_processed`: The service is still analyzing the corpus. The service cannot - accept requests to add new resources or to train the custom model. - * `undetermined`: The service encountered an error while processing the corpus. The - `error` field describes the failure. + * `analyzed`: The service successfully analyzed the corpus. The custom model can + be trained with data from the corpus. + * `being_processed`: The service is still analyzing the corpus. The service + cannot accept requests to add new resources or to train the custom model. + * `undetermined`: The service encountered an error while processing the corpus. + The `error` field describes the failure. :attr str error: (optional) If the status of the corpus is `undetermined`, the - following message: `Analysis of corpus 'name' failed. Please try adding the corpus - again by setting the 'allow_overwrite' flag to 'true'`. + following message: `Analysis of corpus 'name' failed. Please try adding the + corpus again by setting the 'allow_overwrite' flag to 'true'`. """ def __init__(self, @@ -4089,25 +4588,26 @@ def __init__(self, total_words, out_of_vocabulary_words, status, + *, error=None): """ Initialize a Corpus object. :param str name: The name of the corpus. - :param int total_words: The total number of words in the corpus. The value is `0` - while the corpus is being processed. - :param int out_of_vocabulary_words: The number of OOV words in the corpus. The - value is `0` while the corpus is being processed. + :param int total_words: The total number of words in the corpus. The value + is `0` while the corpus is being processed. + :param int out_of_vocabulary_words: The number of OOV words in the corpus. + The value is `0` while the corpus is being processed. :param str status: The status of the corpus: - * `analyzed`: The service successfully analyzed the corpus. The custom model can - be trained with data from the corpus. - * `being_processed`: The service is still analyzing the corpus. The service cannot - accept requests to add new resources or to train the custom model. - * `undetermined`: The service encountered an error while processing the corpus. - The `error` field describes the failure. - :param str error: (optional) If the status of the corpus is `undetermined`, the - following message: `Analysis of corpus 'name' failed. Please try adding the corpus - again by setting the 'allow_overwrite' flag to 'true'`. + * `analyzed`: The service successfully analyzed the corpus. The custom + model can be trained with data from the corpus. + * `being_processed`: The service is still analyzing the corpus. The service + cannot accept requests to add new resources or to train the custom model. + * `undetermined`: The service encountered an error while processing the + corpus. The `error` field describes the failure. + :param str error: (optional) If the status of the corpus is `undetermined`, + the following message: `Analysis of corpus 'name' failed. Please try adding + the corpus again by setting the 'allow_overwrite' flag to 'true'`. """ self.name = name self.total_words = total_words @@ -4183,56 +4683,73 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The status of the corpus: + * `analyzed`: The service successfully analyzed the corpus. The custom model can + be trained with data from the corpus. + * `being_processed`: The service is still analyzing the corpus. The service cannot + accept requests to add new resources or to train the custom model. + * `undetermined`: The service encountered an error while processing the corpus. + The `error` field describes the failure. + """ + ANALYZED = "analyzed" + BEING_PROCESSED = "being_processed" + UNDETERMINED = "undetermined" + class CustomWord(object): """ Information about a word that is to be added to a custom language model. - :attr 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 `_` (underscore) to connect the tokens of - compound words. - Omit this parameter for the **Add a custom word** method. - :attr list[str] sounds_like: (optional) An array of sounds-like pronunciations for the - custom word. Specify how words that are difficult to pronounce, foreign words, - acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the parameter to have - the service automatically generate a sounds-like pronunciation for the word. - * For a word that is in the service's base vocabulary, use the parameter to specify - additional pronunciations for the word. You cannot override the default pronunciation - of a word; pronunciations you add augment the pronunciation from the base vocabulary. - A word can have at most five sounds-like pronunciations. A pronunciation can include - at most 40 characters not including spaces. - :attr str display_as: (optional) An alternative spelling for the custom word when it - appears in a transcript. Use the parameter when you want the word to have a spelling - that is different from its usual representation or from its spelling in corpora - training data. + :attr 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 `_` (underscore) to connect the + tokens of compound words. + Omit this parameter for the **Add a custom word** method. + :attr list[str] sounds_like: (optional) An array of sounds-like pronunciations + for the custom word. Specify how words that are difficult to pronounce, foreign + words, acronyms, and so on can be pronounced by users. + * For a word that is not in the service's base vocabulary, omit the parameter to + have the service automatically generate a sounds-like pronunciation for the + word. + * For a word that is in the service's base vocabulary, use the parameter to + specify additional pronunciations for the word. You cannot override the default + pronunciation of a word; pronunciations you add augment the pronunciation from + the base vocabulary. + A word can have at most five sounds-like pronunciations. A pronunciation can + include at most 40 characters not including spaces. + :attr str display_as: (optional) An alternative spelling for the custom word + when it appears in a transcript. Use the parameter when you want the word to + have a spelling that is different from its usual representation or from its + spelling in corpora training data. """ - def __init__(self, word=None, sounds_like=None, display_as=None): + def __init__(self, *, word=None, sounds_like=None, display_as=None): """ Initialize a CustomWord object. - :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 `_` (underscore) to connect the - tokens of compound words. - Omit this parameter for the **Add a custom word** method. - :param list[str] sounds_like: (optional) An array of sounds-like pronunciations - for the custom word. Specify how words that are difficult to pronounce, foreign - words, acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the parameter to - have the service automatically generate a sounds-like pronunciation for the word. - * For a word that is in the service's base vocabulary, use the parameter to - specify additional pronunciations for the word. You cannot override the default - pronunciation of a word; pronunciations you add augment the pronunciation from the - base vocabulary. - A word can have at most five sounds-like pronunciations. A pronunciation can - include at most 40 characters not including spaces. - :param str display_as: (optional) An alternative spelling for the custom word when - it appears in a transcript. Use the parameter when you want the word to have a - spelling that is different from its usual representation or from its spelling in - corpora training data. + :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 `_` + (underscore) to connect the tokens of compound words. + Omit this parameter for the **Add a custom word** method. + :param list[str] sounds_like: (optional) An array of sounds-like + pronunciations for the custom word. Specify how words that are difficult to + pronounce, foreign words, acronyms, and so on can be pronounced by users. + * For a word that is not in the service's base vocabulary, omit the + parameter to have the service automatically generate a sounds-like + pronunciation for the word. + * For a word that is in the service's base vocabulary, use the parameter to + specify additional pronunciations for the word. You cannot override the + default pronunciation of a word; pronunciations you add augment the + pronunciation from the base vocabulary. + A word can have at most five sounds-like pronunciations. A pronunciation + can include at most 40 characters not including spaces. + :param str display_as: (optional) An alternative spelling for the custom + word when it appears in a transcript. Use the parameter when you want the + word to have a spelling that is different from its usual representation or + from its spelling in corpora training data. """ self.word = word self.sounds_like = sounds_like @@ -4287,38 +4804,40 @@ class Grammar(object): Information about a grammar from a custom language model. :attr str name: The name of the grammar. - :attr int out_of_vocabulary_words: The number of OOV words in the grammar. The value - is `0` while the grammar is being processed. + :attr int out_of_vocabulary_words: The number of OOV words in the grammar. The + value is `0` while the grammar is being processed. :attr str status: The status of the grammar: - * `analyzed`: The service successfully analyzed the grammar. The custom model can be - trained with data from the grammar. - * `being_processed`: The service is still analyzing the grammar. The service cannot - accept requests to add new resources or to train the custom model. - * `undetermined`: The service encountered an error while processing the grammar. The - `error` field describes the failure. + * `analyzed`: The service successfully analyzed the grammar. The custom model + can be trained with data from the grammar. + * `being_processed`: The service is still analyzing the grammar. The service + cannot accept requests to add new resources or to train the custom model. + * `undetermined`: The service encountered an error while processing the grammar. + The `error` field describes the failure. :attr str error: (optional) If the status of the grammar is `undetermined`, the - following message: `Analysis of grammar '{grammar_name}' failed. Please try fixing the - error or adding the grammar again by setting the 'allow_overwrite' flag to 'true'.`. + following message: `Analysis of grammar '{grammar_name}' failed. Please try + fixing the error or adding the grammar again by setting the 'allow_overwrite' + flag to 'true'.`. """ - def __init__(self, name, out_of_vocabulary_words, status, error=None): + def __init__(self, name, out_of_vocabulary_words, status, *, error=None): """ Initialize a Grammar object. :param str name: The name of the grammar. - :param int out_of_vocabulary_words: The number of OOV words in the grammar. The - value is `0` while the grammar is being processed. + :param int out_of_vocabulary_words: The number of OOV words in the grammar. + The value is `0` while the grammar is being processed. :param str status: The status of the grammar: - * `analyzed`: The service successfully analyzed the grammar. The custom model can - be trained with data from the grammar. - * `being_processed`: The service is still analyzing the grammar. The service - cannot accept requests to add new resources or to train the custom model. - * `undetermined`: The service encountered an error while processing the grammar. - The `error` field describes the failure. - :param str error: (optional) If the status of the grammar is `undetermined`, the - following message: `Analysis of grammar '{grammar_name}' failed. Please try fixing - the error or adding the grammar again by setting the 'allow_overwrite' flag to - 'true'.`. + * `analyzed`: The service successfully analyzed the grammar. The custom + model can be trained with data from the grammar. + * `being_processed`: The service is still analyzing the grammar. The + service cannot accept requests to add new resources or to train the custom + model. + * `undetermined`: The service encountered an error while processing the + grammar. The `error` field describes the failure. + :param str error: (optional) If the status of the grammar is + `undetermined`, the following message: `Analysis of grammar + '{grammar_name}' failed. Please try fixing the error or adding the grammar + again by setting the 'allow_overwrite' flag to 'true'.`. """ self.name = name self.out_of_vocabulary_words = out_of_vocabulary_words @@ -4384,14 +4903,28 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The status of the grammar: + * `analyzed`: The service successfully analyzed the grammar. The custom model can + be trained with data from the grammar. + * `being_processed`: The service is still analyzing the grammar. The service + cannot accept requests to add new resources or to train the custom model. + * `undetermined`: The service encountered an error while processing the grammar. + The `error` field describes the failure. + """ + ANALYZED = "analyzed" + BEING_PROCESSED = "being_processed" + UNDETERMINED = "undetermined" + class Grammars(object): """ Information about the grammars from a custom language model. - :attr list[Grammar] grammars: An array of `Grammar` objects that provides information - about the grammars for the custom model. The array is empty if the custom model has no - grammars. + :attr list[Grammar] grammars: An array of `Grammar` objects that provides + information about the grammars for the custom model. The array is empty if the + custom model has no grammars. """ def __init__(self, grammars): @@ -4399,8 +4932,8 @@ def __init__(self, grammars): Initialize a Grammars object. :param list[Grammar] grammars: An array of `Grammar` objects that provides - information about the grammars for the custom model. The array is empty if the - custom model has no grammars. + information about the grammars for the custom model. The array is empty if + the custom model has no grammars. """ self.grammars = grammars @@ -4449,24 +4982,24 @@ class KeywordResult(object): """ Information about a match for a keyword from speech recognition results. - :attr str normalized_text: A specified keyword normalized to the spoken phrase that - matched in the audio input. + :attr str normalized_text: A specified keyword normalized to the spoken phrase + that matched in the audio input. :attr float start_time: The start time in seconds of the keyword match. :attr float end_time: The end time in seconds of the keyword match. - :attr float confidence: A confidence score for the keyword match in the range of 0.0 - to 1.0. + :attr float confidence: A confidence score for the keyword match in the range of + 0.0 to 1.0. """ def __init__(self, normalized_text, start_time, end_time, confidence): """ Initialize a KeywordResult object. - :param str normalized_text: A specified keyword normalized to the spoken phrase - that matched in the audio input. + :param str normalized_text: A specified keyword normalized to the spoken + phrase that matched in the audio input. :param float start_time: The start time in seconds of the keyword match. :param float end_time: The end time in seconds of the keyword match. - :param float confidence: A confidence score for the keyword match in the range of - 0.0 to 1.0. + :param float confidence: A confidence score for the keyword match in the + range of 0.0 to 1.0. """ self.normalized_text = normalized_text self.start_time = start_time @@ -4542,61 +5075,69 @@ class LanguageModel(object): """ Information about an existing custom language model. - :attr str customization_id: The customization ID (GUID) of the custom language model. - The **Create a custom language model** method returns only this field of the object; - it does not return the other fields. - :attr str created: (optional) The date and time in Coordinated Universal Time (UTC) at - which the custom language model was created. The value is provided in full ISO 8601 - format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time (UTC) at - which the custom language model was last modified. The `created` and `updated` fields - are equal when a language model is first added but has yet to be updated. The value is - provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - :attr str language: (optional) The language identifier of the custom language model - (for example, `en-US`). - :attr str dialect: (optional) The dialect of the language for the custom language - model. By default, the dialect matches the language of the base model; for example, - `en-US` for either of the US English language models. For Spanish models, the field - indicates the dialect for which the model was created: - * `es-ES` for Castilian Spanish (the default) - * `es-LA` for Latin American Spanish - * `es-US` for North American (Mexican) Spanish. - :attr list[str] versions: (optional) A list of the available versions of the custom - language model. Each element of the array indicates a version of the base model with - which the custom model can be used. Multiple versions exist only if the custom model - has been upgraded; otherwise, only a single version is shown. + :attr str customization_id: The customization ID (GUID) of the custom language + model. The **Create a custom language model** method returns only this field of + the object; it does not return the other fields. + :attr str created: (optional) The date and time in Coordinated Universal Time + (UTC) at which the custom language model was created. The value is provided in + full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). + :attr str updated: (optional) The date and time in Coordinated Universal Time + (UTC) at which the custom language model was last modified. The `created` and + `updated` fields are equal when a language model is first added but has yet to + be updated. The value is provided in full ISO 8601 format + (YYYY-MM-DDThh:mm:ss.sTZD). + :attr str language: (optional) The language identifier of the custom language + model (for example, `en-US`). + :attr str dialect: (optional) The dialect of the language for the custom + language model. For non-Spanish models, the field matches the language of the + base model; for example, `en-US` for either of the US English language models. + For Spanish models, the field indicates the dialect for which the model was + created: + * `es-ES` for Castilian Spanish (`es-ES` models) + * `es-LA` for Latin American Spanish (`es-AR`, `es-CL`, `es-CO`, and `es-PE` + models) + * `es-US` for Mexican (North American) Spanish (`es-MX` models) + Dialect values are case-insensitive. + :attr list[str] versions: (optional) A list of the available versions of the + custom language model. Each element of the array indicates a version of the base + model with which the custom model can be used. Multiple versions exist only if + the custom model has been upgraded; otherwise, only a single version is shown. :attr str owner: (optional) The GUID of the credentials for the instance of the - service that owns the custom language model. + service that owns the custom language model. :attr str name: (optional) The name of the custom language model. :attr str description: (optional) The description of the custom language model. - :attr str base_model_name: (optional) The name of the language model for which the - custom language model was created. + :attr str base_model_name: (optional) The name of the language model for which + the custom language model was created. :attr str status: (optional) The current status of the custom language model: - * `pending`: The model was created but is waiting either for valid training data to be - added or for the service to finish analyzing added data. - * `ready`: The model contains valid data and is ready to be trained. If the model - contains a mix of valid and invalid resources, you need to set the `strict` parameter - to `false` for the training to proceed. - * `training`: The model is currently being trained. - * `available`: The model is trained and ready to use. - * `upgrading`: The model is currently being upgraded. - * `failed`: Training of the model failed. - :attr int progress: (optional) A percentage that indicates the progress of the custom - language model's current training. A value of `100` means that the model is fully - trained. **Note:** The `progress` field does not currently reflect the progress of the - training. The field changes from `0` to `100` when training is complete. - :attr str error: (optional) If an error occurred while adding a grammar file to the - custom language model, a message that describes an `Internal Server Error` and - includes the string `Cannot compile grammar`. The status of the custom model is not - affected by the error, but the grammar cannot be used with the model. + * `pending`: The model was created but is waiting either for valid training data + to be added or for the service to finish analyzing added data. + * `ready`: The model contains valid data and is ready to be trained. If the + model contains a mix of valid and invalid resources, you need to set the + `strict` parameter to `false` for the training to proceed. + * `training`: The model is currently being trained. + * `available`: The model is trained and ready to use. + * `upgrading`: The model is currently being upgraded. + * `failed`: Training of the model failed. + :attr int progress: (optional) A percentage that indicates the progress of the + custom language model's current training. A value of `100` means that the model + is fully trained. **Note:** The `progress` field does not currently reflect the + progress of the training. The field changes from `0` to `100` when training is + complete. + :attr str error: (optional) If an error occurred while adding a grammar file to + the custom language model, a message that describes an `Internal Server Error` + and includes the string `Cannot compile grammar`. The status of the custom model + is not affected by the error, but the grammar cannot be used with the model. :attr str warnings: (optional) If the request included unknown parameters, the - following message: `Unexpected query parameter(s) ['parameters'] detected`, where - `parameters` is a list that includes a quoted string for each unknown parameter. + following message: `Unexpected query parameter(s) ['parameters'] detected`, + where `parameters` is a list that includes a quoted string for each unknown + parameter. """ def __init__(self, customization_id, + *, created=None, + updated=None, language=None, dialect=None, versions=None, @@ -4607,62 +5148,70 @@ def __init__(self, status=None, progress=None, error=None, - warnings=None, - updated=None): + warnings=None): """ Initialize a LanguageModel object. - :param str customization_id: The customization ID (GUID) of the custom language - model. The **Create a custom language model** method returns only this field of - the object; it does not return the other fields. - :param str created: (optional) The date and time in Coordinated Universal Time - (UTC) at which the custom language model was created. The value is provided in - full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :param str updated: (optional) The date and time in Coordinated Universal Time - (UTC) at which the custom language model was last modified. The `created` and - `updated` fields are equal when a language model is first added but has yet to be - updated. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - :param str language: (optional) The language identifier of the custom language - model (for example, `en-US`). - :param str dialect: (optional) The dialect of the language for the custom language - model. By default, the dialect matches the language of the base model; for - example, `en-US` for either of the US English language models. For Spanish models, - the field indicates the dialect for which the model was created: - * `es-ES` for Castilian Spanish (the default) - * `es-LA` for Latin American Spanish - * `es-US` for North American (Mexican) Spanish. - :param list[str] versions: (optional) A list of the available versions of the - custom language model. Each element of the array indicates a version of the base - model with which the custom model can be used. Multiple versions exist only if the - custom model has been upgraded; otherwise, only a single version is shown. - :param str owner: (optional) The GUID of the credentials for the instance of the - service that owns the custom language model. + :param str customization_id: The customization ID (GUID) of the custom + language model. The **Create a custom language model** method returns only + this field of the object; it does not return the other fields. + :param str created: (optional) The date and time in Coordinated Universal + Time (UTC) at which the custom language model was created. The value is + provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). + :param str updated: (optional) The date and time in Coordinated Universal + Time (UTC) at which the custom language model was last modified. The + `created` and `updated` fields are equal when a language model is first + added but has yet to be updated. The value is provided in full ISO 8601 + format (YYYY-MM-DDThh:mm:ss.sTZD). + :param str language: (optional) The language identifier of the custom + language model (for example, `en-US`). + :param str dialect: (optional) The dialect of the language for the custom + language model. For non-Spanish models, the field matches the language of + the base model; for example, `en-US` for either of the US English language + models. For Spanish models, the field indicates the dialect for which the + model was created: + * `es-ES` for Castilian Spanish (`es-ES` models) + * `es-LA` for Latin American Spanish (`es-AR`, `es-CL`, `es-CO`, and + `es-PE` models) + * `es-US` for Mexican (North American) Spanish (`es-MX` models) + Dialect values are case-insensitive. + :param list[str] versions: (optional) A list of the available versions of + the custom language model. Each element of the array indicates a version of + the base model with which the custom model can be used. Multiple versions + exist only if the custom model has been upgraded; otherwise, only a single + version is shown. + :param str owner: (optional) The GUID of the credentials for the instance + of the service that owns the custom language model. :param str name: (optional) The name of the custom language model. - :param str description: (optional) The description of the custom language model. - :param str base_model_name: (optional) The name of the language model for which - the custom language model was created. - :param str status: (optional) The current status of the custom language model: - * `pending`: The model was created but is waiting either for valid training data - to be added or for the service to finish analyzing added data. - * `ready`: The model contains valid data and is ready to be trained. If the model - contains a mix of valid and invalid resources, you need to set the `strict` - parameter to `false` for the training to proceed. - * `training`: The model is currently being trained. - * `available`: The model is trained and ready to use. - * `upgrading`: The model is currently being upgraded. - * `failed`: Training of the model failed. - :param int progress: (optional) A percentage that indicates the progress of the - custom language model's current training. A value of `100` means that the model is - fully trained. **Note:** The `progress` field does not currently reflect the - progress of the training. The field changes from `0` to `100` when training is - complete. - :param str error: (optional) If an error occurred while adding a grammar file to - the custom language model, a message that describes an `Internal Server Error` and - includes the string `Cannot compile grammar`. The status of the custom model is - not affected by the error, but the grammar cannot be used with the model. - :param str warnings: (optional) If the request included unknown parameters, the - following message: `Unexpected query parameter(s) ['parameters'] detected`, where - `parameters` is a list that includes a quoted string for each unknown parameter. + :param str description: (optional) The description of the custom language + model. + :param str base_model_name: (optional) The name of the language model for + which the custom language model was created. + :param str status: (optional) The current status of the custom language + model: + * `pending`: The model was created but is waiting either for valid training + data to be added or for the service to finish analyzing added data. + * `ready`: The model contains valid data and is ready to be trained. If the + model contains a mix of valid and invalid resources, you need to set the + `strict` parameter to `false` for the training to proceed. + * `training`: The model is currently being trained. + * `available`: The model is trained and ready to use. + * `upgrading`: The model is currently being upgraded. + * `failed`: Training of the model failed. + :param int progress: (optional) A percentage that indicates the progress of + the custom language model's current training. A value of `100` means that + the model is fully trained. **Note:** The `progress` field does not + currently reflect the progress of the training. The field changes from `0` + to `100` when training is complete. + :param str error: (optional) If an error occurred while adding a grammar + file to the custom language model, a message that describes an `Internal + Server Error` and includes the string `Cannot compile grammar`. The status + of the custom model is not affected by the error, but the grammar cannot be + used with the model. + :param str warnings: (optional) If the request included unknown parameters, + the following message: `Unexpected query parameter(s) ['parameters'] + detected`, where `parameters` is a list that includes a quoted string for + each unknown parameter. """ self.customization_id = customization_id self.created = created @@ -4776,25 +5325,47 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The current status of the custom language model: + * `pending`: The model was created but is waiting either for valid training data + to be added or for the service to finish analyzing added data. + * `ready`: The model contains valid data and is ready to be trained. If the model + contains a mix of valid and invalid resources, you need to set the `strict` + parameter to `false` for the training to proceed. + * `training`: The model is currently being trained. + * `available`: The model is trained and ready to use. + * `upgrading`: The model is currently being upgraded. + * `failed`: Training of the model failed. + """ + PENDING = "pending" + READY = "ready" + TRAINING = "training" + AVAILABLE = "available" + UPGRADING = "upgrading" + FAILED = "failed" + class LanguageModels(object): """ Information about existing custom language models. - :attr list[LanguageModel] customizations: An array of `LanguageModel` objects that - provides information about each available custom language model. The array is empty if - the requesting credentials own no custom language models (if no language is specified) - or own no custom language models for the specified language. + :attr list[LanguageModel] customizations: An array of `LanguageModel` objects + that provides information about each available custom language model. The array + is empty if the requesting credentials own no custom language models (if no + language is specified) or own no custom language models for the specified + language. """ def __init__(self, customizations): """ Initialize a LanguageModels object. - :param list[LanguageModel] customizations: An array of `LanguageModel` objects - that provides information about each available custom language model. The array is - empty if the requesting credentials own no custom language models (if no language - is specified) or own no custom language models for the specified language. + :param list[LanguageModel] customizations: An array of `LanguageModel` + objects that provides information about each available custom language + model. The array is empty if the requesting credentials own no custom + language models (if no language is specified) or own no custom language + models for the specified language. """ self.customizations = customizations @@ -4847,56 +5418,60 @@ class ProcessedAudio(object): """ Detailed timing information about the service's processing of the input audio. - :attr float received: The seconds of audio that the service has received as of this - response. The value of the field is greater than the values of the `transcription` and - `speaker_labels` fields during speech recognition processing, since the service first - has to receive the audio before it can begin to process it. The final value can also - be greater than the value of the `transcription` and `speaker_labels` fields by a - fractional number of seconds. - :attr float seen_by_engine: The seconds of audio that the service has passed to its - speech-processing engine as of this response. The value of the field is greater than - the values of the `transcription` and `speaker_labels` fields during speech - recognition processing. The `received` and `seen_by_engine` fields have identical - values when the service has finished processing all audio. This final value can be - greater than the value of the `transcription` and `speaker_labels` fields by a - fractional number of seconds. - :attr float transcription: The seconds of audio that the service has processed for - speech recognition as of this response. - :attr float speaker_labels: (optional) If speaker labels are requested, the seconds of - audio that the service has processed to determine speaker labels as of this response. - This value often trails the value of the `transcription` field during speech - recognition processing. The `transcription` and `speaker_labels` fields have identical - values when the service has finished processing all audio. + :attr float received: The seconds of audio that the service has received as of + this response. The value of the field is greater than the values of the + `transcription` and `speaker_labels` fields during speech recognition + processing, since the service first has to receive the audio before it can begin + to process it. The final value can also be greater than the value of the + `transcription` and `speaker_labels` fields by a fractional number of seconds. + :attr float seen_by_engine: The seconds of audio that the service has passed to + its speech-processing engine as of this response. The value of the field is + greater than the values of the `transcription` and `speaker_labels` fields + during speech recognition processing. The `received` and `seen_by_engine` fields + have identical values when the service has finished processing all audio. This + final value can be greater than the value of the `transcription` and + `speaker_labels` fields by a fractional number of seconds. + :attr float transcription: The seconds of audio that the service has processed + for speech recognition as of this response. + :attr float speaker_labels: (optional) If speaker labels are requested, the + seconds of audio that the service has processed to determine speaker labels as + of this response. This value often trails the value of the `transcription` field + during speech recognition processing. The `transcription` and `speaker_labels` + fields have identical values when the service has finished processing all audio. """ def __init__(self, received, seen_by_engine, transcription, + *, speaker_labels=None): """ Initialize a ProcessedAudio object. - :param float received: The seconds of audio that the service has received as of - this response. The value of the field is greater than the values of the - `transcription` and `speaker_labels` fields during speech recognition processing, - since the service first has to receive the audio before it can begin to process - it. The final value can also be greater than the value of the `transcription` and - `speaker_labels` fields by a fractional number of seconds. - :param float seen_by_engine: The seconds of audio that the service has passed to - its speech-processing engine as of this response. The value of the field is - greater than the values of the `transcription` and `speaker_labels` fields during - speech recognition processing. The `received` and `seen_by_engine` fields have - identical values when the service has finished processing all audio. This final - value can be greater than the value of the `transcription` and `speaker_labels` - fields by a fractional number of seconds. - :param float transcription: The seconds of audio that the service has processed - for speech recognition as of this response. - :param float speaker_labels: (optional) If speaker labels are requested, the - seconds of audio that the service has processed to determine speaker labels as of - this response. This value often trails the value of the `transcription` field - during speech recognition processing. The `transcription` and `speaker_labels` - fields have identical values when the service has finished processing all audio. + :param float received: The seconds of audio that the service has received + as of this response. The value of the field is greater than the values of + the `transcription` and `speaker_labels` fields during speech recognition + processing, since the service first has to receive the audio before it can + begin to process it. The final value can also be greater than the value of + the `transcription` and `speaker_labels` fields by a fractional number of + seconds. + :param float seen_by_engine: The seconds of audio that the service has + passed to its speech-processing engine as of this response. The value of + the field is greater than the values of the `transcription` and + `speaker_labels` fields during speech recognition processing. The + `received` and `seen_by_engine` fields have identical values when the + service has finished processing all audio. This final value can be greater + than the value of the `transcription` and `speaker_labels` fields by a + fractional number of seconds. + :param float transcription: The seconds of audio that the service has + processed for speech recognition as of this response. + :param float speaker_labels: (optional) If speaker labels are requested, + the seconds of audio that the service has processed to determine speaker + labels as of this response. This value often trails the value of the + `transcription` field during speech recognition processing. The + `transcription` and `speaker_labels` fields have identical values when the + service has finished processing all audio. """ self.received = received self.seen_by_engine = seen_by_engine @@ -4971,26 +5546,26 @@ class ProcessingMetrics(object): input audio. Processing metrics are not available with the synchronous **Recognize audio** method. - :attr ProcessedAudio processed_audio: Detailed timing information about the service's - processing of the input audio. - :attr float wall_clock_since_first_byte_received: The amount of real time in seconds - that has passed since the service received the first byte of input audio. Values in - this field are generally multiples of the specified metrics interval, with two - differences: - * Values might not reflect exact intervals (for instance, 0.25, 0.5, and so on). - Actual values might be 0.27, 0.52, and so on, depending on when the service receives - and processes audio. - * The service also returns values for transcription events if you set the - `interim_results` parameter to `true`. The service returns both processing metrics and - transcription results when such events occur. - :attr bool periodic: An indication of whether the metrics apply to a periodic interval - or a transcription event: - * `true` means that the response was triggered by a specified processing interval. The - information contains processing metrics only. - * `false` means that the response was triggered by a transcription event. The - information contains processing metrics plus transcription results. - Use the field to identify why the service generated the response and to filter - different results if necessary. + :attr ProcessedAudio processed_audio: Detailed timing information about the + service's processing of the input audio. + :attr float wall_clock_since_first_byte_received: The amount of real time in + seconds that has passed since the service received the first byte of input + audio. Values in this field are generally multiples of the specified metrics + interval, with two differences: + * Values might not reflect exact intervals (for instance, 0.25, 0.5, and so on). + Actual values might be 0.27, 0.52, and so on, depending on when the service + receives and processes audio. + * The service also returns values for transcription events if you set the + `interim_results` parameter to `true`. The service returns both processing + metrics and transcription results when such events occur. + :attr bool periodic: An indication of whether the metrics apply to a periodic + interval or a transcription event: + * `true` means that the response was triggered by a specified processing + interval. The information contains processing metrics only. + * `false` means that the response was triggered by a transcription event. The + information contains processing metrics plus transcription results. + Use the field to identify why the service generated the response and to filter + different results if necessary. """ def __init__(self, processed_audio, wall_clock_since_first_byte_received, @@ -4998,26 +5573,26 @@ def __init__(self, processed_audio, wall_clock_since_first_byte_received, """ Initialize a ProcessingMetrics object. - :param ProcessedAudio processed_audio: Detailed timing information about the - service's processing of the input audio. - :param float wall_clock_since_first_byte_received: The amount of real time in - seconds that has passed since the service received the first byte of input audio. - Values in this field are generally multiples of the specified metrics interval, - with two differences: - * Values might not reflect exact intervals (for instance, 0.25, 0.5, and so on). - Actual values might be 0.27, 0.52, and so on, depending on when the service - receives and processes audio. - * The service also returns values for transcription events if you set the - `interim_results` parameter to `true`. The service returns both processing metrics - and transcription results when such events occur. - :param bool periodic: An indication of whether the metrics apply to a periodic - interval or a transcription event: - * `true` means that the response was triggered by a specified processing interval. - The information contains processing metrics only. - * `false` means that the response was triggered by a transcription event. The - information contains processing metrics plus transcription results. - Use the field to identify why the service generated the response and to filter - different results if necessary. + :param ProcessedAudio processed_audio: Detailed timing information about + the service's processing of the input audio. + :param float wall_clock_since_first_byte_received: The amount of real time + in seconds that has passed since the service received the first byte of + input audio. Values in this field are generally multiples of the specified + metrics interval, with two differences: + * Values might not reflect exact intervals (for instance, 0.25, 0.5, and so + on). Actual values might be 0.27, 0.52, and so on, depending on when the + service receives and processes audio. + * The service also returns values for transcription events if you set the + `interim_results` parameter to `true`. The service returns both processing + metrics and transcription results when such events occur. + :param bool periodic: An indication of whether the metrics apply to a + periodic interval or a transcription event: + * `true` means that the response was triggered by a specified processing + interval. The information contains processing metrics only. + * `false` means that the response was triggered by a transcription event. + The information contains processing metrics plus transcription results. + Use the field to identify why the service generated the response and to + filter different results if necessary. """ self.processed_audio = processed_audio self.wall_clock_since_first_byte_received = wall_clock_since_first_byte_received @@ -5093,43 +5668,46 @@ class RecognitionJob(object): :attr str id: The ID of the asynchronous job. :attr str status: The current status of the job: - * `waiting`: The service is preparing the job for processing. The service returns this - status when the job is initially created or when it is waiting for capacity to process - the job. The job remains in this state until the service has the capacity to begin - processing it. - * `processing`: The service is actively processing the job. - * `completed`: The service has finished processing the job. If the job specified a - callback URL and the event `recognitions.completed_with_results`, the service sent the - results with the callback notification. Otherwise, you must retrieve the results by - checking the individual job. - * `failed`: The job failed. - :attr str created: The date and time in Coordinated Universal Time (UTC) at which the - job was created. The value is provided in full ISO 8601 format - (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time (UTC) at - which the job was last updated by the service. The value is provided in full ISO 8601 - format (`YYYY-MM-DDThh:mm:ss.sTZD`). This field is returned only by the **Check jobs** - and **Check a job** methods. - :attr str url: (optional) The URL to use to request information about the job with the - **Check a job** method. This field is returned only by the **Create a job** method. - :attr str user_token: (optional) The user token associated with a job that was created - with a callback URL and a user token. This field can be returned only by the **Check - jobs** method. - :attr list[SpeechRecognitionResults] results: (optional) If the status is `completed`, - the results of the recognition request as an array that includes a single instance of - a `SpeechRecognitionResults` object. This field is returned only by the **Check a - job** method. + * `waiting`: The service is preparing the job for processing. The service + returns this status when the job is initially created or when it is waiting for + capacity to process the job. The job remains in this state until the service has + the capacity to begin processing it. + * `processing`: The service is actively processing the job. + * `completed`: The service has finished processing the job. If the job specified + a callback URL and the event `recognitions.completed_with_results`, the service + sent the results with the callback notification. Otherwise, you must retrieve + the results by checking the individual job. + * `failed`: The job failed. + :attr str created: The date and time in Coordinated Universal Time (UTC) at + which the job was created. The value is provided in full ISO 8601 format + (`YYYY-MM-DDThh:mm:ss.sTZD`). + :attr str updated: (optional) The date and time in Coordinated Universal Time + (UTC) at which the job was last updated by the service. The value is provided in + full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). This field is returned only + by the **Check jobs** and **Check a job** methods. + :attr str url: (optional) The URL to use to request information about the job + with the **Check a job** method. This field is returned only by the **Create a + job** method. + :attr str user_token: (optional) The user token associated with a job that was + created with a callback URL and a user token. This field can be returned only by + the **Check jobs** method. + :attr list[SpeechRecognitionResults] results: (optional) If the status is + `completed`, the results of the recognition request as an array that includes a + single instance of a `SpeechRecognitionResults` object. This field is returned + only by the **Check a job** method. :attr list[str] warnings: (optional) An array of warning messages about invalid - parameters included with the request. Each warning includes a descriptive message and - a list of invalid argument strings, for example, `"unexpected query parameter - 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds - despite the warnings. This field can be returned only by the **Create a job** method. + parameters included with the request. Each warning includes a descriptive + message and a list of invalid argument strings, for example, `"unexpected query + parameter 'user_token', query parameter 'callback_url' was not specified"`. The + request succeeds despite the warnings. This field can be returned only by the + **Create a job** method. """ def __init__(self, id, status, created, + *, updated=None, url=None, user_token=None, @@ -5140,39 +5718,40 @@ def __init__(self, :param str id: The ID of the asynchronous job. :param str status: The current status of the job: - * `waiting`: The service is preparing the job for processing. The service returns - this status when the job is initially created or when it is waiting for capacity - to process the job. The job remains in this state until the service has the - capacity to begin processing it. - * `processing`: The service is actively processing the job. - * `completed`: The service has finished processing the job. If the job specified a - callback URL and the event `recognitions.completed_with_results`, the service sent - the results with the callback notification. Otherwise, you must retrieve the - results by checking the individual job. - * `failed`: The job failed. - :param str created: The date and time in Coordinated Universal Time (UTC) at which - the job was created. The value is provided in full ISO 8601 format - (`YYYY-MM-DDThh:mm:ss.sTZD`). - :param str updated: (optional) The date and time in Coordinated Universal Time - (UTC) at which the job was last updated by the service. The value is provided in - full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). This field is returned only by - the **Check jobs** and **Check a job** methods. - :param str url: (optional) The URL to use to request information about the job - with the **Check a job** method. This field is returned only by the **Create a - job** method. - :param str user_token: (optional) The user token associated with a job that was - created with a callback URL and a user token. This field can be returned only by - the **Check jobs** method. + * `waiting`: The service is preparing the job for processing. The service + returns this status when the job is initially created or when it is waiting + for capacity to process the job. The job remains in this state until the + service has the capacity to begin processing it. + * `processing`: The service is actively processing the job. + * `completed`: The service has finished processing the job. If the job + specified a callback URL and the event + `recognitions.completed_with_results`, the service sent the results with + the callback notification. Otherwise, you must retrieve the results by + checking the individual job. + * `failed`: The job failed. + :param str created: The date and time in Coordinated Universal Time (UTC) + at which the job was created. The value is provided in full ISO 8601 format + (`YYYY-MM-DDThh:mm:ss.sTZD`). + :param str updated: (optional) The date and time in Coordinated Universal + Time (UTC) at which the job was last updated by the service. The value is + provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). This field + is returned only by the **Check jobs** and **Check a job** methods. + :param str url: (optional) The URL to use to request information about the + job with the **Check a job** method. This field is returned only by the + **Create a job** method. + :param str user_token: (optional) The user token associated with a job that + was created with a callback URL and a user token. This field can be + returned only by the **Check jobs** method. :param list[SpeechRecognitionResults] results: (optional) If the status is - `completed`, the results of the recognition request as an array that includes a - single instance of a `SpeechRecognitionResults` object. This field is returned - only by the **Check a job** method. - :param list[str] warnings: (optional) An array of warning messages about invalid - parameters included with the request. Each warning includes a descriptive message - and a list of invalid argument strings, for example, `"unexpected query parameter - 'user_token', query parameter 'callback_url' was not specified"`. The request - succeeds despite the warnings. This field can be returned only by the **Create a - job** method. + `completed`, the results of the recognition request as an array that + includes a single instance of a `SpeechRecognitionResults` object. This + field is returned only by the **Check a job** method. + :param list[str] warnings: (optional) An array of warning messages about + invalid parameters included with the request. Each warning includes a + descriptive message and a list of invalid argument strings, for example, + `"unexpected query parameter 'user_token', query parameter 'callback_url' + was not specified"`. The request succeeds despite the warnings. This field + can be returned only by the **Create a job** method. """ self.id = id self.status = status @@ -5263,23 +5842,42 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The current status of the job: + * `waiting`: The service is preparing the job for processing. The service returns + this status when the job is initially created or when it is waiting for capacity + to process the job. The job remains in this state until the service has the + capacity to begin processing it. + * `processing`: The service is actively processing the job. + * `completed`: The service has finished processing the job. If the job specified a + callback URL and the event `recognitions.completed_with_results`, the service sent + the results with the callback notification. Otherwise, you must retrieve the + results by checking the individual job. + * `failed`: The job failed. + """ + WAITING = "waiting" + PROCESSING = "processing" + COMPLETED = "completed" + FAILED = "failed" + class RecognitionJobs(object): """ Information about current asynchronous speech recognition jobs. - :attr list[RecognitionJob] recognitions: An array of `RecognitionJob` objects that - provides the status for each of the user's current jobs. The array is empty if the - user has no current jobs. + :attr list[RecognitionJob] recognitions: An array of `RecognitionJob` objects + that provides the status for each of the user's current jobs. The array is empty + if the user has no current jobs. """ def __init__(self, recognitions): """ Initialize a RecognitionJobs object. - :param list[RecognitionJob] recognitions: An array of `RecognitionJob` objects - that provides the status for each of the user's current jobs. The array is empty - if the user has no current jobs. + :param list[RecognitionJob] recognitions: An array of `RecognitionJob` + objects that provides the status for each of the user's current jobs. The + array is empty if the user has no current jobs. """ self.recognitions = recognitions @@ -5332,9 +5930,9 @@ class RegisterStatus(object): recognition. :attr str status: The current status of the job: - * `created`: The service successfully white-listed the callback URL as a result of the - call. - * `already created`: The URL was already white-listed. + * `created`: The service successfully white-listed the callback URL as a result + of the call. + * `already created`: The URL was already white-listed. :attr str url: The callback URL that is successfully registered. """ @@ -5343,9 +5941,9 @@ def __init__(self, status, url): Initialize a RegisterStatus object. :param str status: The current status of the job: - * `created`: The service successfully white-listed the callback URL as a result of - the call. - * `already created`: The URL was already white-listed. + * `created`: The service successfully white-listed the callback URL as a + result of the call. + * `already created`: The URL was already white-listed. :param str url: The callback URL that is successfully registered. """ self.status = status @@ -5397,62 +5995,70 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + The current status of the job: + * `created`: The service successfully white-listed the callback URL as a result of + the call. + * `already created`: The URL was already white-listed. + """ + CREATED = "created" + ALREADY_CREATED = "already created" + class SpeakerLabelsResult(object): """ Information about the speakers from speech recognition results. - :attr float from_: The start time of a word from the transcript. The value matches the - start time of a word from the `timestamps` array. - :attr float to: The end time of a word from the transcript. The value matches the end - time of a word from the `timestamps` array. - :attr int speaker: The numeric identifier that the service assigns to a speaker from - the audio. Speaker IDs begin at `0` initially but can evolve and change across interim - results (if supported by the method) and between interim and final results as the - service processes the audio. They are not guaranteed to be sequential, contiguous, or - ordered. + :attr float from_: The start time of a word from the transcript. The value + matches the start time of a word from the `timestamps` array. + :attr float to: The end time of a word from the transcript. The value matches + the end time of a word from the `timestamps` array. + :attr int speaker: The numeric identifier that the service assigns to a speaker + from the audio. Speaker IDs begin at `0` initially but can evolve and change + across interim results (if supported by the method) and between interim and + final results as the service processes the audio. They are not guaranteed to be + sequential, contiguous, or ordered. :attr float confidence: A score that indicates the service's confidence in its - identification of the speaker in the range of 0.0 to 1.0. - :attr bool final_results: An indication of whether the service might further change - word and speaker-label results. A value of `true` means that the service guarantees - not to send any further updates for the current or any preceding results; `false` - means that the service might send further updates to the results. + identification of the speaker in the range of 0.0 to 1.0. + :attr bool final: An indication of whether the service might further change word + and speaker-label results. A value of `true` means that the service guarantees + not to send any further updates for the current or any preceding results; + `false` means that the service might send further updates to the results. """ - def __init__(self, from_, to, speaker, confidence, final_results): + def __init__(self, from_, to, speaker, confidence, final): """ Initialize a SpeakerLabelsResult object. :param float from_: The start time of a word from the transcript. The value - matches the start time of a word from the `timestamps` array. - :param float to: The end time of a word from the transcript. The value matches the - end time of a word from the `timestamps` array. - :param int speaker: The numeric identifier that the service assigns to a speaker - from the audio. Speaker IDs begin at `0` initially but can evolve and change - across interim results (if supported by the method) and between interim and final - results as the service processes the audio. They are not guaranteed to be - sequential, contiguous, or ordered. - :param float confidence: A score that indicates the service's confidence in its - identification of the speaker in the range of 0.0 to 1.0. - :param bool final_results: An indication of whether the service might further - change word and speaker-label results. A value of `true` means that the service - guarantees not to send any further updates for the current or any preceding - results; `false` means that the service might send further updates to the results. + matches the start time of a word from the `timestamps` array. + :param float to: The end time of a word from the transcript. The value + matches the end time of a word from the `timestamps` array. + :param int speaker: The numeric identifier that the service assigns to a + speaker from the audio. Speaker IDs begin at `0` initially but can evolve + and change across interim results (if supported by the method) and between + interim and final results as the service processes the audio. They are not + guaranteed to be sequential, contiguous, or ordered. + :param float confidence: A score that indicates the service's confidence in + its identification of the speaker in the range of 0.0 to 1.0. + :param bool final: An indication of whether the service might further + change word and speaker-label results. A value of `true` means that the + service guarantees not to send any further updates for the current or any + preceding results; `false` means that the service might send further + updates to the results. """ self.from_ = from_ self.to = to self.speaker = speaker self.confidence = confidence - self.final_results = final_results + self.final = final @classmethod def _from_dict(cls, _dict): """Initialize a SpeakerLabelsResult object from a json dictionary.""" args = {} - validKeys = [ - 'from_', 'from', 'to', 'speaker', 'confidence', 'final_results', - 'final' - ] + validKeys = ['from_', 'from', 'to', 'speaker', 'confidence', 'final'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: raise ValueError( @@ -5482,9 +6088,8 @@ def _from_dict(cls, _dict): raise ValueError( 'Required property \'confidence\' not present in SpeakerLabelsResult JSON' ) - if 'final' in _dict or 'final_results' in _dict: - args['final_results'] = _dict.get('final') or _dict.get( - 'final_results') + if 'final' in _dict: + args['final'] = _dict.get('final') else: raise ValueError( 'Required property \'final\' not present in SpeakerLabelsResult JSON' @@ -5502,8 +6107,8 @@ def _to_dict(self): _dict['speaker'] = self.speaker if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence - if hasattr(self, 'final_results') and self.final_results is not None: - _dict['final'] = self.final_results + if hasattr(self, 'final') and self.final is not None: + _dict['final'] = self.final return _dict def __str__(self): @@ -5525,14 +6130,14 @@ class SpeechModel(object): """ Information about an available language model. - :attr str name: The name of the model for use as an identifier in calls to the service - (for example, `en-US_BroadbandModel`). + :attr str name: The name of the model for use as an identifier in calls to the + service (for example, `en-US_BroadbandModel`). :attr str language: The language identifier of the model (for example, `en-US`). - :attr int rate: The sampling rate (minimum acceptable rate for audio) used by the - model in Hertz. + :attr int rate: The sampling rate (minimum acceptable rate for audio) used by + the model in Hertz. :attr str url: The URI for the model. :attr SupportedFeatures supported_features: Additional service features that are - supported with the model. + supported with the model. :attr str description: A brief description of the model. """ @@ -5541,14 +6146,15 @@ def __init__(self, name, language, rate, url, supported_features, """ Initialize a SpeechModel object. - :param str name: The name of the model for use as an identifier in calls to the - service (for example, `en-US_BroadbandModel`). - :param str language: The language identifier of the model (for example, `en-US`). - :param int rate: The sampling rate (minimum acceptable rate for audio) used by the - model in Hertz. + :param str name: The name of the model for use as an identifier in calls to + the service (for example, `en-US_BroadbandModel`). + :param str language: The language identifier of the model (for example, + `en-US`). + :param int rate: The sampling rate (minimum acceptable rate for audio) used + by the model in Hertz. :param str url: The URI for the model. - :param SupportedFeatures supported_features: Additional service features that are - supported with the model. + :param SupportedFeatures supported_features: Additional service features + that are supported with the model. :param str description: A brief description of the model. """ self.name = name @@ -5646,15 +6252,15 @@ class SpeechModels(object): Information about the available language models. :attr list[SpeechModel] models: An array of `SpeechModel` objects that provides - information about each available model. + information about each available model. """ def __init__(self, models): """ Initialize a SpeechModels object. - :param list[SpeechModel] models: An array of `SpeechModel` objects that provides - information about each available model. + :param list[SpeechModel] models: An array of `SpeechModel` objects that + provides information about each available model. """ self.models = models @@ -5704,23 +6310,24 @@ class SpeechRecognitionAlternative(object): An alternative transcript from speech recognition results. :attr str transcript: A transcription of the audio. - :attr float confidence: (optional) A score that indicates the service's confidence in - the transcript in the range of 0.0 to 1.0. A confidence score is returned only for the - best alternative and only with results marked as final. + :attr float confidence: (optional) A score that indicates the service's + confidence in the transcript in the range of 0.0 to 1.0. A confidence score is + returned only for the best alternative and only with results marked as final. :attr list[str] timestamps: (optional) Time alignments for each word from the - transcript as a list of lists. Each inner list consists of three elements: the word - followed by its start and end time in seconds, for example: - `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best - alternative. - :attr list[str] word_confidence: (optional) A confidence score for each word of the - transcript as a list of lists. Each inner list consists of two elements: the word and - its confidence score in the range of 0.0 to 1.0, for example: - `[["hello",0.95],["world",0.866]]`. Confidence scores are returned only for the best - alternative and only with results marked as final. + transcript as a list of lists. Each inner list consists of three elements: the + word followed by its start and end time in seconds, for example: + `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the + best alternative. + :attr list[str] word_confidence: (optional) A confidence score for each word of + the transcript as a list of lists. Each inner list consists of two elements: the + word and its confidence score in the range of 0.0 to 1.0, for example: + `[["hello",0.95],["world",0.866]]`. Confidence scores are returned only for the + best alternative and only with results marked as final. """ def __init__(self, transcript, + *, confidence=None, timestamps=None, word_confidence=None): @@ -5729,18 +6336,19 @@ def __init__(self, :param str transcript: A transcription of the audio. :param float confidence: (optional) A score that indicates the service's - confidence in the transcript in the range of 0.0 to 1.0. A confidence score is - returned only for the best alternative and only with results marked as final. - :param list[str] timestamps: (optional) Time alignments for each word from the - transcript as a list of lists. Each inner list consists of three elements: the - word followed by its start and end time in seconds, for example: - `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best - alternative. - :param list[str] word_confidence: (optional) A confidence score for each word of - the transcript as a list of lists. Each inner list consists of two elements: the - word and its confidence score in the range of 0.0 to 1.0, for example: - `[["hello",0.95],["world",0.866]]`. Confidence scores are returned only for the - best alternative and only with results marked as final. + confidence in the transcript in the range of 0.0 to 1.0. A confidence score + is returned only for the best alternative and only with results marked as + final. + :param list[str] timestamps: (optional) Time alignments for each word from + the transcript as a list of lists. Each inner list consists of three + elements: the word followed by its start and end time in seconds, for + example: `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned + only for the best alternative. + :param list[str] word_confidence: (optional) A confidence score for each + word of the transcript as a list of lists. Each inner list consists of two + elements: the word and its confidence score in the range of 0.0 to 1.0, for + example: `[["hello",0.95],["world",0.866]]`. Confidence scores are returned + only for the best alternative and only with results marked as final. """ self.transcript = transcript self.confidence = confidence @@ -5806,51 +6414,52 @@ class SpeechRecognitionResult(object): """ Component results for a speech recognition request. - :attr bool final_results: An indication of whether the transcription results are - final. If `true`, the results for this utterance are not updated further; no - additional results are sent for a `result_index` once its results are indicated as - final. + :attr bool final: An indication of whether the transcription results are final. + If `true`, the results for this utterance are not updated further; no additional + results are sent for a `result_index` once its results are indicated as final. :attr list[SpeechRecognitionAlternative] alternatives: An array of alternative - transcripts. The `alternatives` array can include additional requested output such as - word confidence or timestamps. - :attr dict keywords_result: (optional) A dictionary (or associative array) whose keys - are the strings specified for `keywords` if both that parameter and - `keywords_threshold` are specified. The value for each key is an array of matches - spotted in the audio for that keyword. Each match is described by a `KeywordResult` - object. A keyword for which no matches are found is omitted from the dictionary. The - dictionary is omitted entirely if no matches are found for any keywords. + transcripts. The `alternatives` array can include additional requested output + such as word confidence or timestamps. + :attr dict keywords_result: (optional) A dictionary (or associative array) whose + keys are the strings specified for `keywords` if both that parameter and + `keywords_threshold` are specified. The value for each key is an array of + matches spotted in the audio for that keyword. Each match is described by a + `KeywordResult` object. A keyword for which no matches are found is omitted from + the dictionary. The dictionary is omitted entirely if no matches are found for + any keywords. :attr list[WordAlternativeResults] word_alternatives: (optional) An array of - alternative hypotheses found for words of the input audio if a - `word_alternatives_threshold` is specified. + alternative hypotheses found for words of the input audio if a + `word_alternatives_threshold` is specified. """ def __init__(self, - final_results, + final, alternatives, + *, keywords_result=None, word_alternatives=None): """ Initialize a SpeechRecognitionResult object. - :param bool final_results: An indication of whether the transcription results are - final. If `true`, the results for this utterance are not updated further; no - additional results are sent for a `result_index` once its results are indicated as - final. - :param list[SpeechRecognitionAlternative] alternatives: An array of alternative - transcripts. The `alternatives` array can include additional requested output such - as word confidence or timestamps. - :param dict keywords_result: (optional) A dictionary (or associative array) whose - keys are the strings specified for `keywords` if both that parameter and - `keywords_threshold` are specified. The value for each key is an array of matches - spotted in the audio for that keyword. Each match is described by a - `KeywordResult` object. A keyword for which no matches are found is omitted from - the dictionary. The dictionary is omitted entirely if no matches are found for any - keywords. - :param list[WordAlternativeResults] word_alternatives: (optional) An array of - alternative hypotheses found for words of the input audio if a - `word_alternatives_threshold` is specified. - """ - self.final_results = final_results + :param bool final: An indication of whether the transcription results are + final. If `true`, the results for this utterance are not updated further; + no additional results are sent for a `result_index` once its results are + indicated as final. + :param list[SpeechRecognitionAlternative] alternatives: An array of + alternative transcripts. The `alternatives` array can include additional + requested output such as word confidence or timestamps. + :param dict keywords_result: (optional) A dictionary (or associative array) + whose keys are the strings specified for `keywords` if both that parameter + and `keywords_threshold` are specified. The value for each key is an array + of matches spotted in the audio for that keyword. Each match is described + by a `KeywordResult` object. A keyword for which no matches are found is + omitted from the dictionary. The dictionary is omitted entirely if no + matches are found for any keywords. + :param list[WordAlternativeResults] word_alternatives: (optional) An array + of alternative hypotheses found for words of the input audio if a + `word_alternatives_threshold` is specified. + """ + self.final = final self.alternatives = alternatives self.keywords_result = keywords_result self.word_alternatives = word_alternatives @@ -5860,17 +6469,15 @@ def _from_dict(cls, _dict): """Initialize a SpeechRecognitionResult object from a json dictionary.""" args = {} validKeys = [ - 'final_results', 'final', 'alternatives', 'keywords_result', - 'word_alternatives' + 'final', 'alternatives', 'keywords_result', 'word_alternatives' ] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: raise ValueError( 'Unrecognized keys detected in dictionary for class SpeechRecognitionResult: ' + ', '.join(badKeys)) - if 'final' in _dict or 'final_results' in _dict: - args['final_results'] = _dict.get('final') or _dict.get( - 'final_results') + if 'final' in _dict: + args['final'] = _dict.get('final') else: raise ValueError( 'Required property \'final\' not present in SpeechRecognitionResult JSON' @@ -5896,8 +6503,8 @@ def _from_dict(cls, _dict): def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'final_results') and self.final_results is not None: - _dict['final'] = self.final_results + if hasattr(self, 'final') and self.final is not None: + _dict['final'] = self.final if hasattr(self, 'alternatives') and self.alternatives is not None: _dict['alternatives'] = [x._to_dict() for x in self.alternatives] if hasattr(self, @@ -5930,87 +6537,92 @@ class SpeechRecognitionResults(object): The complete results for a speech recognition request. :attr list[SpeechRecognitionResult] results: (optional) An array of - `SpeechRecognitionResult` objects that can include interim and final results (interim - results are returned only if supported by the method). Final results are guaranteed - not to change; interim results might be replaced by further interim results and final - results. The service periodically sends updates to the results list; the - `result_index` is set to the lowest index in the array that has changed; it is - incremented for new results. + `SpeechRecognitionResult` objects that can include interim and final results + (interim results are returned only if supported by the method). Final results + are guaranteed not to change; interim results might be replaced by further + interim results and final results. The service periodically sends updates to the + results list; the `result_index` is set to the lowest index in the array that + has changed; it is incremented for new results. :attr int result_index: (optional) An index that indicates a change point in the - `results` array. The service increments the index only for additional results that it - sends for new audio for the same request. + `results` array. The service increments the index only for additional results + that it sends for new audio for the same request. :attr list[SpeakerLabelsResult] speaker_labels: (optional) An array of - `SpeakerLabelsResult` objects that identifies which words were spoken by which - speakers in a multi-person exchange. The array is returned only if the - `speaker_labels` parameter is `true`. When interim results are also requested for - methods that support them, it is possible for a `SpeechRecognitionResults` object to - include only the `speaker_labels` field. + `SpeakerLabelsResult` objects that identifies which words were spoken by which + speakers in a multi-person exchange. The array is returned only if the + `speaker_labels` parameter is `true`. When interim results are also requested + for methods that support them, it is possible for a `SpeechRecognitionResults` + object to include only the `speaker_labels` field. :attr ProcessingMetrics processing_metrics: (optional) If processing metrics are - requested, information about the service's processing of the input audio. Processing - metrics are not available with the synchronous **Recognize audio** method. + requested, information about the service's processing of the input audio. + Processing metrics are not available with the synchronous **Recognize audio** + method. :attr AudioMetrics audio_metrics: (optional) If audio metrics are requested, - information about the signal characteristics of the input audio. - :attr list[str] warnings: (optional) An array of warning messages associated with the - request: - * Warnings for invalid parameters or fields can include a descriptive message and a - list of invalid argument strings, for example, `"Unknown arguments:"` or `"Unknown url - query arguments:"` followed by a list of the form `"{invalid_arg_1}, - {invalid_arg_2}."` - * The following warning is returned if the request passes a custom model that is based - on an older version of a base model for which an updated version is available: `"Using - previous version of base model, because your custom model has been built with it. - Please note that this version will be supported only for a limited time. Consider - updating your custom model to the new base model. If you do not do that you will be - automatically switched to base model when you used the non-updated custom model."` - In both cases, the request succeeds despite the warnings. + information about the signal characteristics of the input audio. + :attr list[str] warnings: (optional) An array of warning messages associated + with the request: + * Warnings for invalid parameters or fields can include a descriptive message + and a list of invalid argument strings, for example, `"Unknown arguments:"` or + `"Unknown url query arguments:"` followed by a list of the form + `"{invalid_arg_1}, {invalid_arg_2}."` + * The following warning is returned if the request passes a custom model that is + based on an older version of a base model for which an updated version is + available: `"Using previous version of base model, because your custom model has + been built with it. Please note that this version will be supported only for a + limited time. Consider updating your custom model to the new base model. If you + do not do that you will be automatically switched to base model when you used + the non-updated custom model."` + In both cases, the request succeeds despite the warnings. """ def __init__(self, + *, results=None, result_index=None, speaker_labels=None, + processing_metrics=None, audio_metrics=None, - warnings=None, - processing_metrics=None): + warnings=None): """ Initialize a SpeechRecognitionResults object. :param list[SpeechRecognitionResult] results: (optional) An array of - `SpeechRecognitionResult` objects that can include interim and final results - (interim results are returned only if supported by the method). Final results are - guaranteed not to change; interim results might be replaced by further interim - results and final results. The service periodically sends updates to the results - list; the `result_index` is set to the lowest index in the array that has changed; - it is incremented for new results. - :param int result_index: (optional) An index that indicates a change point in the - `results` array. The service increments the index only for additional results that - it sends for new audio for the same request. + `SpeechRecognitionResult` objects that can include interim and final + results (interim results are returned only if supported by the method). + Final results are guaranteed not to change; interim results might be + replaced by further interim results and final results. The service + periodically sends updates to the results list; the `result_index` is set + to the lowest index in the array that has changed; it is incremented for + new results. + :param int result_index: (optional) An index that indicates a change point + in the `results` array. The service increments the index only for + additional results that it sends for new audio for the same request. :param list[SpeakerLabelsResult] speaker_labels: (optional) An array of - `SpeakerLabelsResult` objects that identifies which words were spoken by which - speakers in a multi-person exchange. The array is returned only if the - `speaker_labels` parameter is `true`. When interim results are also requested for - methods that support them, it is possible for a `SpeechRecognitionResults` object - to include only the `speaker_labels` field. - :param ProcessingMetrics processing_metrics: (optional) If processing metrics are - requested, information about the service's processing of the input audio. - Processing metrics are not available with the synchronous **Recognize audio** - method. - :param AudioMetrics audio_metrics: (optional) If audio metrics are requested, - information about the signal characteristics of the input audio. - :param list[str] warnings: (optional) An array of warning messages associated with - the request: - * Warnings for invalid parameters or fields can include a descriptive message and - a list of invalid argument strings, for example, `"Unknown arguments:"` or - `"Unknown url query arguments:"` followed by a list of the form `"{invalid_arg_1}, - {invalid_arg_2}."` - * The following warning is returned if the request passes a custom model that is - based on an older version of a base model for which an updated version is - available: `"Using previous version of base model, because your custom model has - been built with it. Please note that this version will be supported only for a - limited time. Consider updating your custom model to the new base model. If you do - not do that you will be automatically switched to base model when you used the - non-updated custom model."` - In both cases, the request succeeds despite the warnings. + `SpeakerLabelsResult` objects that identifies which words were spoken by + which speakers in a multi-person exchange. The array is returned only if + the `speaker_labels` parameter is `true`. When interim results are also + requested for methods that support them, it is possible for a + `SpeechRecognitionResults` object to include only the `speaker_labels` + field. + :param ProcessingMetrics processing_metrics: (optional) If processing + metrics are requested, information about the service's processing of the + input audio. Processing metrics are not available with the synchronous + **Recognize audio** method. + :param AudioMetrics audio_metrics: (optional) If audio metrics are + requested, information about the signal characteristics of the input audio. + :param list[str] warnings: (optional) An array of warning messages + associated with the request: + * Warnings for invalid parameters or fields can include a descriptive + message and a list of invalid argument strings, for example, `"Unknown + arguments:"` or `"Unknown url query arguments:"` followed by a list of the + form `"{invalid_arg_1}, {invalid_arg_2}."` + * The following warning is returned if the request passes a custom model + that is based on an older version of a base model for which an updated + version is available: `"Using previous version of base model, because your + custom model has been built with it. Please note that this version will be + supported only for a limited time. Consider updating your custom model to + the new base model. If you do not do that you will be automatically + switched to base model when you used the non-updated custom model."` + In both cases, the request succeeds despite the warnings. """ self.results = results self.result_index = result_index @@ -6094,20 +6706,21 @@ class SupportedFeatures(object): """ Additional service features that are supported with the model. - :attr bool custom_language_model: Indicates whether the customization interface can be - used to create a custom language model based on the language model. - :attr bool speaker_labels: Indicates whether the `speaker_labels` parameter can be - used with the language model. + :attr bool custom_language_model: Indicates whether the customization interface + can be used to create a custom language model based on the language model. + :attr bool speaker_labels: Indicates whether the `speaker_labels` parameter can + be used with the language model. """ def __init__(self, custom_language_model, speaker_labels): """ Initialize a SupportedFeatures object. - :param bool custom_language_model: Indicates whether the customization interface - can be used to create a custom language model based on the language model. - :param bool speaker_labels: Indicates whether the `speaker_labels` parameter can - be used with the language model. + :param bool custom_language_model: Indicates whether the customization + interface can be used to create a custom language model based on the + language model. + :param bool speaker_labels: Indicates whether the `speaker_labels` + parameter can be used with the language model. """ self.custom_language_model = custom_language_model self.speaker_labels = speaker_labels @@ -6165,20 +6778,22 @@ class TrainingResponse(object): """ The response from training of a custom language or custom acoustic model. - :attr list[TrainingWarning] warnings: (optional) An array of `TrainingWarning` objects - that lists any invalid resources contained in the custom model. For custom language - models, invalid resources are grouped and identified by type of resource. The method - can return warnings only if the `strict` parameter is set to `false`. + :attr list[TrainingWarning] warnings: (optional) An array of `TrainingWarning` + objects that lists any invalid resources contained in the custom model. For + custom language models, invalid resources are grouped and identified by type of + resource. The method can return warnings only if the `strict` parameter is set + to `false`. """ - def __init__(self, warnings=None): + def __init__(self, *, warnings=None): """ Initialize a TrainingResponse object. - :param list[TrainingWarning] warnings: (optional) An array of `TrainingWarning` - objects that lists any invalid resources contained in the custom model. For custom - language models, invalid resources are grouped and identified by type of resource. - The method can return warnings only if the `strict` parameter is set to `false`. + :param list[TrainingWarning] warnings: (optional) An array of + `TrainingWarning` objects that lists any invalid resources contained in the + custom model. For custom language models, invalid resources are grouped and + identified by type of resource. The method can return warnings only if the + `strict` parameter is set to `false`. """ self.warnings = warnings @@ -6225,24 +6840,25 @@ class TrainingWarning(object): A warning from training of a custom language or custom acoustic model. :attr str code: An identifier for the type of invalid resources listed in the - `description` field. + `description` field. :attr str message: A warning message that lists the invalid resources that are - excluded from the custom model's training. The message has the following format: - `Analysis of the following {resource_type} has not completed successfully: - [{resource_names}]. They will be excluded from custom {model_type} model training.`. + excluded from the custom model's training. The message has the following format: + `Analysis of the following {resource_type} has not completed successfully: + [{resource_names}]. They will be excluded from custom {model_type} model + training.`. """ def __init__(self, code, message): """ Initialize a TrainingWarning object. - :param str code: An identifier for the type of invalid resources listed in the - `description` field. - :param str message: A warning message that lists the invalid resources that are - excluded from the custom model's training. The message has the following format: - `Analysis of the following {resource_type} has not completed successfully: - [{resource_names}]. They will be excluded from custom {model_type} model - training.`. + :param str code: An identifier for the type of invalid resources listed in + the `description` field. + :param str message: A warning message that lists the invalid resources that + are excluded from the custom model's training. The message has the + following format: `Analysis of the following {resource_type} has not + completed successfully: [{resource_names}]. They will be excluded from + custom {model_type} model training.`. """ self.code = code self.message = message @@ -6294,64 +6910,81 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class CodeEnum(Enum): + """ + An identifier for the type of invalid resources listed in the `description` field. + """ + INVALID_AUDIO_FILES = "invalid_audio_files" + INVALID_CORPUS_FILES = "invalid_corpus_files" + INVALID_GRAMMAR_FILES = "invalid_grammar_files" + INVALID_WORDS = "invalid_words" + class Word(object): """ Information about a word from a custom language model. - :attr str word: A word from the custom model's words resource. The spelling of the - word is used to train the model. - :attr list[str] sounds_like: An array of pronunciations for the word. The array can - include the sounds-like pronunciation automatically generated by the service if none - is provided for the word; the service adds this pronunciation when it finishes - processing the word. - :attr str display_as: The spelling of the word that the service uses to display the - word in a transcript. The field contains an empty string if no display-as value is - provided for the word, in which case the word is displayed as it is spelled. - :attr int count: A sum of the number of times the word is found across all corpora. - For example, if the word occurs five times in one corpus and seven times in another, - its count is `12`. If you add a custom word to a model before it is added by any - corpora, the count begins at `1`; if the word is added from a corpus first and later - modified, the count reflects only the number of times it is found in corpora. - :attr list[str] source: An array of sources that describes how the word was added to - the custom model's words resource. For OOV words added from a corpus, includes the - name of the corpus; if the word was added by multiple corpora, the names of all - corpora are listed. If the word was modified or added by the user directly, the field - includes the string `user`. - :attr list[WordError] error: (optional) If the service discovered one or more problems - that you need to correct for the word's definition, an array that describes each of - the errors. + :attr str word: A word from the custom model's words resource. The spelling of + the word is used to train the model. + :attr list[str] sounds_like: An array of pronunciations for the word. The array + can include the sounds-like pronunciation automatically generated by the service + if none is provided for the word; the service adds this pronunciation when it + finishes processing the word. + :attr str display_as: The spelling of the word that the service uses to display + the word in a transcript. The field contains an empty string if no display-as + value is provided for the word, in which case the word is displayed as it is + spelled. + :attr int count: A sum of the number of times the word is found across all + corpora. For example, if the word occurs five times in one corpus and seven + times in another, its count is `12`. If you add a custom word to a model before + it is added by any corpora, the count begins at `1`; if the word is added from a + corpus first and later modified, the count reflects only the number of times it + is found in corpora. + :attr list[str] source: An array of sources that describes how the word was + added to the custom model's words resource. For OOV words added from a corpus, + includes the name of the corpus; if the word was added by multiple corpora, the + names of all corpora are listed. If the word was modified or added by the user + directly, the field includes the string `user`. + :attr list[WordError] error: (optional) If the service discovered one or more + problems that you need to correct for the word's definition, an array that + describes each of the errors. """ - def __init__(self, word, sounds_like, display_as, count, source, + def __init__(self, + word, + sounds_like, + display_as, + count, + source, + *, error=None): """ Initialize a Word object. - :param str word: A word from the custom model's words resource. The spelling of - the word is used to train the model. - :param list[str] sounds_like: An array of pronunciations for the word. The array - can include the sounds-like pronunciation automatically generated by the service - if none is provided for the word; the service adds this pronunciation when it - finishes processing the word. - :param str display_as: The spelling of the word that the service uses to display - the word in a transcript. The field contains an empty string if no display-as - value is provided for the word, in which case the word is displayed as it is - spelled. + :param str word: A word from the custom model's words resource. The + spelling of the word is used to train the model. + :param list[str] sounds_like: An array of pronunciations for the word. The + array can include the sounds-like pronunciation automatically generated by + the service if none is provided for the word; the service adds this + pronunciation when it finishes processing the word. + :param str display_as: The spelling of the word that the service uses to + display the word in a transcript. The field contains an empty string if no + display-as value is provided for the word, in which case the word is + displayed as it is spelled. :param int count: A sum of the number of times the word is found across all - corpora. For example, if the word occurs five times in one corpus and seven times - in another, its count is `12`. If you add a custom word to a model before it is - added by any corpora, the count begins at `1`; if the word is added from a corpus - first and later modified, the count reflects only the number of times it is found - in corpora. - :param list[str] source: An array of sources that describes how the word was added - to the custom model's words resource. For OOV words added from a corpus, includes - the name of the corpus; if the word was added by multiple corpora, the names of - all corpora are listed. If the word was modified or added by the user directly, - the field includes the string `user`. - :param list[WordError] error: (optional) If the service discovered one or more - problems that you need to correct for the word's definition, an array that - describes each of the errors. + corpora. For example, if the word occurs five times in one corpus and seven + times in another, its count is `12`. If you add a custom word to a model + before it is added by any corpora, the count begins at `1`; if the word is + added from a corpus first and later modified, the count reflects only the + number of times it is found in corpora. + :param list[str] source: An array of sources that describes how the word + was added to the custom model's words resource. For OOV words added from a + corpus, includes the name of the corpus; if the word was added by multiple + corpora, the names of all corpora are listed. If the word was modified or + added by the user directly, the field includes the string `user`. + :param list[WordError] error: (optional) If the service discovered one or + more problems that you need to correct for the word's definition, an array + that describes each of the errors. """ self.word = word self.sounds_like = sounds_like @@ -6439,8 +7072,8 @@ class WordAlternativeResult(object): """ An alternative hypothesis for a word from speech recognition results. - :attr float confidence: A confidence score for the word alternative hypothesis in the - range of 0.0 to 1.0. + :attr float confidence: A confidence score for the word alternative hypothesis + in the range of 0.0 to 1.0. :attr str word: An alternative hypothesis for a word from the input audio. """ @@ -6448,8 +7081,8 @@ def __init__(self, confidence, word): """ Initialize a WordAlternativeResult object. - :param float confidence: A confidence score for the word alternative hypothesis in - the range of 0.0 to 1.0. + :param float confidence: A confidence score for the word alternative + hypothesis in the range of 0.0 to 1.0. :param str word: An alternative hypothesis for a word from the input audio. """ self.confidence = confidence @@ -6507,24 +7140,24 @@ class WordAlternativeResults(object): """ Information about alternative hypotheses for words from speech recognition results. - :attr float start_time: The start time in seconds of the word from the input audio - that corresponds to the word alternatives. - :attr float end_time: The end time in seconds of the word from the input audio that - corresponds to the word alternatives. - :attr list[WordAlternativeResult] alternatives: An array of alternative hypotheses for - a word from the input audio. + :attr float start_time: The start time in seconds of the word from the input + audio that corresponds to the word alternatives. + :attr float end_time: The end time in seconds of the word from the input audio + that corresponds to the word alternatives. + :attr list[WordAlternativeResult] alternatives: An array of alternative + hypotheses for a word from the input audio. """ def __init__(self, start_time, end_time, alternatives): """ Initialize a WordAlternativeResults object. - :param float start_time: The start time in seconds of the word from the input - audio that corresponds to the word alternatives. - :param float end_time: The end time in seconds of the word from the input audio - that corresponds to the word alternatives. + :param float start_time: The start time in seconds of the word from the + input audio that corresponds to the word alternatives. + :param float end_time: The end time in seconds of the word from the input + audio that corresponds to the word alternatives. :param list[WordAlternativeResult] alternatives: An array of alternative - hypotheses for a word from the input audio. + hypotheses for a word from the input audio. """ self.start_time = start_time self.end_time = end_time @@ -6594,24 +7227,25 @@ class WordError(object): An error associated with a word from a custom language model. :attr str element: A key-value pair that describes an error associated with the - definition of a word in the words resource. The pair has the format `"element": - "message"`, where `element` is the aspect of the definition that caused the problem - and `message` describes the problem. The following example describes a problem with - one of the word's sounds-like definitions: `"{sounds_like_string}": "Numbers are not - allowed in sounds-like. You can try for example '{suggested_string}'."`. + definition of a word in the words resource. The pair has the format `"element": + "message"`, where `element` is the aspect of the definition that caused the + problem and `message` describes the problem. The following example describes a + problem with one of the word's sounds-like definitions: `"{sounds_like_string}": + "Numbers are not allowed in sounds-like. You can try for example + '{suggested_string}'."`. """ def __init__(self, element): """ Initialize a WordError object. - :param str element: A key-value pair that describes an error associated with the - definition of a word in the words resource. The pair has the format `"element": - "message"`, where `element` is the aspect of the definition that caused the - problem and `message` describes the problem. The following example describes a - problem with one of the word's sounds-like definitions: `"{sounds_like_string}": - "Numbers are not allowed in sounds-like. You can try for example - '{suggested_string}'."`. + :param str element: A key-value pair that describes an error associated + with the definition of a word in the words resource. The pair has the + format `"element": "message"`, where `element` is the aspect of the + definition that caused the problem and `message` describes the problem. The + following example describes a problem with one of the word's sounds-like + definitions: `"{sounds_like_string}": "Numbers are not allowed in + sounds-like. You can try for example '{suggested_string}'."`. """ self.element = element @@ -6658,18 +7292,18 @@ class Words(object): """ Information about the words from a custom language model. - :attr list[Word] words: An array of `Word` objects that provides information about - each word in the custom model's words resource. The array is empty if the custom model - has no words. + :attr list[Word] words: An array of `Word` objects that provides information + about each word in the custom model's words resource. The array is empty if the + custom model has no words. """ def __init__(self, words): """ Initialize a Words object. - :param list[Word] words: An array of `Word` objects that provides information - about each word in the custom model's words resource. The array is empty if the - custom model has no words. + :param list[Word] words: An array of `Word` objects that provides + information about each word in the custom model's words resource. The array + is empty if the custom model has no words. """ self.words = words From 55e9ae5efa70a590786035b7e44b2460bc74cff5 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 23:39:06 -0400 Subject: [PATCH 028/455] test(stt): Update speech to text unit tests --- test/unit/test_speech_to_text_v1.py | 50 +++++++++++++++-------------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 87a5514c9..dd02220d8 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -4,6 +4,7 @@ import responses import ibm_watson from ibm_watson.speech_to_text_v1 import CustomWord +from ibm_cloud_sdk_core.authenticators import BasicAuthenticator @responses.activate @@ -20,8 +21,8 @@ def test_success(): status=200, content_type='application/json') - speech_to_text = ibm_watson.SpeechToTextV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) speech_to_text.list_models() assert responses.calls[0].request.url == models_url @@ -63,8 +64,8 @@ def test_get_model(): body='{"bogus_response": "yep"}', status=200, content_type='application/json') - speech_to_text = ibm_watson.SpeechToTextV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) speech_to_text.get_model(model_id='modelid') assert len(responses.calls) == 1 @@ -108,8 +109,8 @@ def test_recognitions(): status=200, content_type='application/json') - speech_to_text = ibm_watson.SpeechToTextV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) speech_to_text.check_jobs() assert responses.calls[0].response.json()['recognitions'][0][ @@ -147,8 +148,8 @@ def test_callbacks(): status=200, content_type='application/json') - speech_to_text = ibm_watson.SpeechToTextV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) speech_to_text.register_callback("monitorcalls.com") assert responses.calls[0].response.json() == { "status": "created", @@ -203,8 +204,8 @@ def test_custom_model(): status=200, content_type='application/json') - speech_to_text = ibm_watson.SpeechToTextV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) speech_to_text.list_language_models() @@ -270,8 +271,8 @@ def test_acoustic_model(): status=200, content_type='application/json') - speech_to_text = ibm_watson.SpeechToTextV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) speech_to_text.list_acoustic_models() @@ -309,12 +310,12 @@ def test_upgrade_acoustic_model(): status=200, content_type='application/json') - speech_to_text = ibm_watson.SpeechToTextV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) speech_to_text.upgrade_acoustic_model( 'customid', - 'model_x', + custom_language_model_id='model_x', force=True) assert responses.calls[0].response.json() == {"bogus_response": "yep"} @@ -356,8 +357,8 @@ def test_custom_corpora(): status=200, content_type='application/json') - speech_to_text = ibm_watson.SpeechToTextV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) speech_to_text.list_corpora(customization_id='customid') @@ -437,8 +438,8 @@ def test_custom_words(): status=200, content_type='application/json') - speech_to_text = ibm_watson.SpeechToTextV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) custom_word = CustomWord( word="IEEE", sounds_like=["i triple e"], display_as="IEEE") @@ -502,8 +503,8 @@ def test_custom_audio_resources(): status=200, content_type='application/json') - speech_to_text = ibm_watson.SpeechToTextV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: speech_to_text.add_audio( @@ -532,7 +533,8 @@ def test_delete_user_data(): status=204, content_type='application_json') - speech_to_text = ibm_watson.SpeechToTextV1(username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) response = speech_to_text.delete_user_data('id').get_result() assert response is None assert len(responses.calls) == 1 @@ -568,8 +570,8 @@ def test_custom_grammars(): status=200, content_type='application/json') - speech_to_text = ibm_watson.SpeechToTextV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) with open(os.path.join(os.path.dirname(__file__), '../../resources/confirm-grammar.xml'), 'rb') as grammar_file: speech_to_text.add_grammar( From 1b0c1ab571620383d9142ce13178d0e91a426e6d Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 23:51:11 -0400 Subject: [PATCH 029/455] fix(recognize): Update websocket request --- ibm_watson/speech_to_text_v1_adapter.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 6448829e3..bf597ddd8 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -207,21 +207,20 @@ def recognize_using_websocket(self, raise Exception( 'Callback is not a derived class of RecognizeCallback') + request = {} + headers = {} if self.default_headers is not None: headers = self.default_headers.copy() if 'headers' in kwargs: headers.update(kwargs.get('headers')) + request['headers'] = headers - if self.token_manager: - access_token = self.token_manager.get_token() - headers['Authorization'] = '{0} {1}'.format(BEARER, access_token) - else: - authstring = "{0}:{1}".format(self.username, self.password) - base64_authorization = base64.b64encode(authstring.encode('utf-8')).decode('utf-8') - headers['Authorization'] = 'Basic {0}'.format(base64_authorization) + if self.authenticator: + self.authenticator.authenticate(request) url = self.url.replace('https:', 'wss:') + params = { 'model': model, 'customization_id': customization_id, @@ -232,6 +231,7 @@ def recognize_using_websocket(self, } params = dict([(k, v) for k, v in params.items() if v is not None]) url += '/v1/recognize?{0}'.format(urlencode(params)) + request['url'] = url options = { 'content_type': content_type, @@ -253,12 +253,13 @@ def recognize_using_websocket(self, 'audio_metrics': audio_metrics } options = dict([(k, v) for k, v in options.items() if v is not None]) + request['options'] = options RecognizeListener(audio, - options, + request.get('options'), recognize_callback, - url, - headers, + request.get('url'), + request.get('headers'), http_proxy_host, http_proxy_port, - self.verify) + self.disable_ssl_verification) From f3404d536c2823afd35125cb8cf4647e30e6d155 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 28 Aug 2019 23:56:43 -0400 Subject: [PATCH 030/455] examples(stt): Update speech to text examples --- examples/speech_to_text_v1.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/examples/speech_to_text_v1.py b/examples/speech_to_text_v1.py index b2a267c7d..77ef35614 100644 --- a/examples/speech_to_text_v1.py +++ b/examples/speech_to_text_v1.py @@ -1,20 +1,15 @@ -from __future__ import print_function import json from os.path import join, dirname from ibm_watson import SpeechToTextV1 from ibm_watson.websocket import RecognizeCallback, AudioSource import threading +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -# If service instance provides API key authentication +authenticator = IAMAuthenticator('your_api_key') service = SpeechToTextV1( ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://stream.watsonplatform.net/speech-to-text/api', - iam_apikey='YOUR APIKEY') - -# service = SpeechToTextV1( -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD', -# url='https://stream.watsonplatform.net/speech-to-text/api') + authenticator=authenticator) models = service.list_models().get_result() print(json.dumps(models, indent=2)) From 2783bcdcdc27327cf538982517d359d7c013f2cd Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 00:05:26 -0400 Subject: [PATCH 031/455] fix(synthesize): Update websocket tts synthesize request --- ibm_watson/speech_to_text_v1_adapter.py | 6 +----- ibm_watson/text_to_speech_adapter_v1.py | 28 +++++++++++-------------- 2 files changed, 13 insertions(+), 21 deletions(-) diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index bf597ddd8..c0678e430 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -16,11 +16,7 @@ from ibm_watson.websocket import RecognizeCallback, RecognizeListener, AudioSource from .speech_to_text_v1 import SpeechToTextV1 -import base64 -try: - from urllib.parse import urlencode -except ImportError: - from urllib import urlencode +from urllib.parse import urlencode BEARER = 'Bearer' diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index 06fe03eb7..fdd4e7c3c 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -16,12 +16,8 @@ # limitations under the License. from ibm_watson.websocket import SynthesizeCallback, SynthesizeListener -import base64 from .text_to_speech_v1 import TextToSpeechV1 -try: - from urllib.parse import urlencode -except ImportError: - from urllib import urlencode +from urllib.parse import urlencode BEARER = 'Bearer' @@ -77,19 +73,17 @@ def synthesize_using_websocket(self, raise Exception( 'Callback is not a derived class of SynthesizeCallback') + request = {} + headers = {} if self.default_headers is not None: headers = self.default_headers.copy() if 'headers' in kwargs: headers.update(kwargs.get('headers')) + request['headers'] = headers - if self.token_manager: - access_token = self.token_manager.get_token() - headers['Authorization'] = '{0} {1}'.format(BEARER, access_token) - else: - authstring = "{0}:{1}".format(self.username, self.password) - base64_authorization = base64.b64encode(authstring.encode('utf-8')).decode('utf-8') - headers['Authorization'] = 'Basic {0}'.format(base64_authorization) + if self.authenticator: + self.authenticator.authenticate(request) url = self.url.replace('https:', 'wss:') params = { @@ -98,6 +92,7 @@ def synthesize_using_websocket(self, } params = dict([(k, v) for k, v in params.items() if v is not None]) url += '/v1/synthesize?{0}'.format(urlencode(params)) + request['url'] = url options = { 'text': text, @@ -105,11 +100,12 @@ def synthesize_using_websocket(self, 'timings': timings } options = dict([(k, v) for k, v in options.items() if v is not None]) + request['options'] = options - SynthesizeListener(options, + SynthesizeListener(request.get('options'), synthesize_callback, - url, - headers, + request.get('url'), + request.get('headers'), http_proxy_host, http_proxy_port, - self.verify) + self.disable_ssl_verification) From 082d8ae09261a1e0e53692414b6d32aa34e76134 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 00:05:47 -0400 Subject: [PATCH 032/455] feat(TTS): Generate text to speech --- ibm_watson/text_to_speech_v1.py | 855 ++++++++++++++++++++------------ 1 file changed, 532 insertions(+), 323 deletions(-) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 3eae5a650..f0aac9eaf 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -30,11 +30,11 @@ Symbolic Phonetic Representation (SPR). """ -from __future__ import absolute_import - import json 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 os.path import basename ############################################################################## @@ -50,16 +50,8 @@ class TextToSpeechV1(BaseService): def __init__( self, url=default_url, - username=None, - password=None, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, + authenticator=None, + disable_ssl_verification=False, ): """ Construct a new client for the Text to Speech service. @@ -68,62 +60,21 @@ def __init__( "https://stream.watsonplatform.net/text-to-speech/api/text-to-speech/api"). The base url may differ between IBM Cloud regions. - :param str username: The username used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str password: The password used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ + if not authenticator: + authenticator = get_authenticator_from_environment('Text to Speech') + BaseService.__init__( self, - vcap_services_name='text_to_speech', url=url, - username=username, - password=password, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Text to Speech', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Text to Speech') ######################### # Voices @@ -151,11 +102,12 @@ def list_voices(self, **kwargs): headers.update(sdk_headers) url = '/v1/voices' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response - def get_voice(self, voice, customization_id=None, **kwargs): + def get_voice(self, voice, *, customization_id=None, **kwargs): """ Get a voice. @@ -168,10 +120,11 @@ def get_voice(self, voice, customization_id=None, **kwargs): voice](https://cloud.ibm.com/docs/services/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: The customization ID (GUID) of a custom voice model - for which information is to be returned. You must make the request with - credentials for the instance of the service that owns the custom model. Omit the - parameter to see information about the specified voice with no customization. + :param str customization_id: (optional) The customization ID (GUID) of a + custom voice model for which information is to be returned. You must make + the request with credentials for the instance of the service that owns the + custom model. Omit the parameter to see information about the specified + voice with no customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -189,12 +142,13 @@ def get_voice(self, voice, customization_id=None, **kwargs): params = {'customization_id': customization_id} url = '/v1/voices/{0}'.format(*self._encode_path_vars(voice)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -203,9 +157,10 @@ def get_voice(self, voice, customization_id=None, **kwargs): def synthesize(self, text, + *, + accept=None, voice=None, customization_id=None, - accept=None, **kwargs): """ Synthesize audio. @@ -273,21 +228,22 @@ def synthesize(self, If a request includes invalid query parameters, the service returns a `Warnings` response header that provides messages about the invalid parameters. The warning includes a descriptive message and a list of invalid argument strings. For - example, a message such as `\"Unknown arguments:\"` or `\"Unknown url query - arguments:\"` followed by a list of the form `\"{invalid_arg_1}, - {invalid_arg_2}.\"` The request succeeds despite the warnings. + example, a message such as `"Unknown arguments:"` or `"Unknown url query + arguments:"` followed by a list of the form `"{invalid_arg_1}, {invalid_arg_2}."` + The request succeeds despite the warnings. :param str text: The text to synthesize. - :param str voice: The voice to use for synthesis. - :param str customization_id: The customization ID (GUID) of a custom voice model - to use for the synthesis. If a custom voice model is specified, it is guaranteed - to work only if it matches the language of the indicated voice. You must make the - request with credentials for the instance of the service that owns the custom - model. Omit the parameter to use the specified voice with no customization. - :param str accept: The requested format (MIME type) of the audio. You can use the - `Accept` header or the `accept` parameter to specify the audio format. For more - information about specifying an audio format, see **Audio formats (accept types)** - in the method description. + :param str accept: (optional) The requested format (MIME type) of the + audio. You can use the `Accept` header or the `accept` parameter to specify + the audio format. For more information about specifying an audio format, + see **Audio formats (accept types)** in the method description. + :param str voice: (optional) The voice to use for synthesis. + :param str customization_id: (optional) The customization ID (GUID) of a + custom voice model to use for the synthesis. If a custom voice model is + specified, it is guaranteed to work only if it matches the language of the + indicated voice. You must make the request with credentials for the + instance of the service that owns the custom model. Omit the parameter to + use the specified voice with no customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -307,13 +263,14 @@ def synthesize(self, data = {'text': text} url = '/v1/synthesize' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, - json=data, + data=data, accept_json=False) + response = self.send(request) return response ######################### @@ -322,6 +279,7 @@ def synthesize(self, def get_pronunciation(self, text, + *, voice=None, format=None, customization_id=None, @@ -338,18 +296,20 @@ def get_pronunciation(self, language](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). :param str text: The word for which the pronunciation is requested. - :param str voice: A voice that specifies the language in which the pronunciation - is to be returned. All voices for the same language (for example, `en-US`) return - the same translation. - :param str format: The phoneme format in which to return the pronunciation. Omit - the parameter to obtain the pronunciation in the default format. - :param str customization_id: The customization ID (GUID) of a custom voice model - for which the pronunciation is to be returned. The language of a specified custom - model must match the language of the specified voice. If the word is not defined - in the specified custom model, the service returns the default translation for the - custom model's language. You must make the request with credentials for the - instance of the service that owns the custom model. Omit the parameter to see the - translation for the specified voice with no customization. + :param str voice: (optional) A voice that specifies the language in which + the pronunciation is to be returned. All voices for the same language (for + example, `en-US`) return the same translation. + :param str format: (optional) The phoneme format in which to return the + pronunciation. Omit the parameter to obtain the pronunciation in the + default format. + :param str customization_id: (optional) The customization ID (GUID) of a + custom voice model for which the pronunciation is to be returned. The + language of a specified custom model must match the language of the + specified voice. If the word is not defined in the specified custom model, + the service returns the default translation for the custom model's + language. You must make the request with credentials for the instance of + the service that owns the custom model. Omit the parameter to see the + translation for the specified voice with no customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -373,12 +333,13 @@ def get_pronunciation(self, } url = '/v1/pronunciation' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -387,6 +348,7 @@ def get_pronunciation(self, def create_voice_model(self, name, + *, language=None, description=None, **kwargs): @@ -402,10 +364,10 @@ def create_voice_model(self, model](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). :param str name: The name of the new custom voice model. - :param str language: The language of the new custom voice model. Omit the - parameter to use the the default language, `en-US`. - :param str description: A description of the new custom voice model. Specifying a - description is recommended. + :param str language: (optional) The language of the new custom voice model. + Omit the parameter to use the the default language, `en-US`. + :param str description: (optional) A description of the new custom voice + model. Specifying a description is recommended. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -424,15 +386,16 @@ def create_voice_model(self, data = {'name': name, 'language': language, 'description': description} url = '/v1/customizations' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, - json=data, + data=data, accept_json=True) + response = self.send(request) return response - def list_voice_models(self, language=None, **kwargs): + def list_voice_models(self, *, language=None, **kwargs): """ List custom models. @@ -446,9 +409,9 @@ def list_voice_models(self, language=None, **kwargs): **See also:** [Querying all custom models](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customModels#cuModelsQueryAll). - :param str language: The language for which custom voice models that are owned by - the requesting credentials are to be returned. Omit the parameter to see all - custom voice models that are owned by the requester. + :param str language: (optional) The language for which custom voice models + that are owned by the requesting credentials are to be returned. Omit the + parameter to see all custom voice models that are owned by the requester. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -464,16 +427,18 @@ def list_voice_models(self, language=None, **kwargs): params = {'language': language} url = '/v1/customizations' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_voice_model(self, customization_id, + *, name=None, description=None, words=None, @@ -492,11 +457,11 @@ def update_voice_model(self, word. Phonetic translations are based on the SSML phoneme format for representing a word. You can specify them in standard International Phonetic Alphabet (IPA) representation - <phoneme alphabet=\"ipa\" - ph=\"təmˈɑto\"></phoneme> + <phoneme alphabet="ipa" + ph="təmˈɑto"></phoneme> or in the proprietary IBM Symbolic Phonetic Representation (SPR) - <phoneme alphabet=\"ibm\" - ph=\"1gAstroEntxrYFXs\"></phoneme> + <phoneme alphabet="ibm" + ph="1gAstroEntxrYFXs"></phoneme> **Note:** This method is currently a beta release. **See also:** * [Updating a custom @@ -506,14 +471,16 @@ def update_voice_model(self, * [Understanding customization](https://cloud.ibm.com/docs/services/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 the service - that owns the custom model. - :param str name: A new name for the custom voice model. - :param str description: A new description for the custom voice model. - :param list[Word] words: An array of `Word` objects that provides the words and - their translations that are to be added or updated for the custom voice model. - Pass an empty array to make no additions or updates. + :param str customization_id: The customization ID (GUID) of the custom + voice model. You must make the request with credentials for the instance of + the service that owns the custom model. + :param str name: (optional) A new name for the custom voice model. + :param str description: (optional) A new description for the custom voice + model. + :param list[Word] words: (optional) An array of `Word` objects that + provides the words and their translations that are to be added or updated + for the custom voice model. Pass an empty array to make no additions or + updates. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -535,12 +502,13 @@ def update_voice_model(self, url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def get_voice_model(self, customization_id, **kwargs): @@ -555,9 +523,9 @@ def get_voice_model(self, customization_id, **kwargs): **See also:** [Querying a custom model](https://cloud.ibm.com/docs/services/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 the service - that owns the custom model. + :param str customization_id: The customization ID (GUID) of the custom + voice model. You must make the request with credentials for the instance of + the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -574,8 +542,9 @@ def get_voice_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def delete_voice_model(self, customization_id, **kwargs): @@ -588,9 +557,9 @@ def delete_voice_model(self, customization_id, **kwargs): **See also:** [Deleting a custom model](https://cloud.ibm.com/docs/services/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 the service - that owns the custom model. + :param str customization_id: The customization ID (GUID) of the custom + voice model. You must make the request with credentials for the instance of + the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -608,8 +577,9 @@ def delete_voice_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, accept_json=False) + response = self.send(request) return response ######################### @@ -630,11 +600,11 @@ def add_words(self, customization_id, words, **kwargs): word. Phonetic translations are based on the SSML phoneme format for representing a word. You can specify them in standard International Phonetic Alphabet (IPA) representation - <phoneme alphabet=\"ipa\" - ph=\"təmˈɑto\"></phoneme> + <phoneme alphabet="ipa" + ph="təmˈɑto"></phoneme> or in the proprietary IBM Symbolic Phonetic Representation (SPR) - <phoneme alphabet=\"ibm\" - ph=\"1gAstroEntxrYFXs\"></phoneme> + <phoneme alphabet="ibm" + ph="1gAstroEntxrYFXs"></phoneme> **Note:** This method is currently a beta release. **See also:** * [Adding multiple words to a custom @@ -644,16 +614,17 @@ def add_words(self, customization_id, words, **kwargs): * [Understanding customization](https://cloud.ibm.com/docs/services/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 the service - that owns the custom model. - :param list[Word] words: The **Add custom words** method accepts an array of - `Word` objects. Each object provides a word that is to be added or updated for the - custom voice model and the word's translation. - The **List custom words** method returns an array of `Word` objects. Each object - shows a word and its translation from the custom voice model. The words are listed - in alphabetical order, with uppercase letters listed before lowercase letters. The - array is empty if the custom model contains no words. + :param str customization_id: The customization ID (GUID) of the custom + voice model. You must make the request with credentials for the instance of + the service that owns the custom model. + :param list[Word] words: The **Add custom words** method accepts an array + of `Word` objects. Each object provides a word that is to be added or + updated for the custom voice model and the word's translation. + The **List custom words** method returns an array of `Word` objects. Each + object shows a word and its translation from the custom voice model. The + words are listed in alphabetical order, with uppercase letters listed + before lowercase letters. The array is empty if the custom model contains + no words. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -675,12 +646,13 @@ def add_words(self, customization_id, words, **kwargs): url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, - json=data, + data=data, accept_json=True) + response = self.send(request) return response def list_words(self, customization_id, **kwargs): @@ -695,9 +667,9 @@ def list_words(self, customization_id, **kwargs): **See also:** [Querying all words from a custom model](https://cloud.ibm.com/docs/services/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 the service - that owns the custom model. + :param str customization_id: The customization ID (GUID) of the custom + voice model. You must make the request with credentials for the instance of + the service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -714,14 +686,16 @@ def list_words(self, customization_id, **kwargs): url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def add_word(self, customization_id, word, translation, + *, part_of_speech=None, **kwargs): """ @@ -737,11 +711,11 @@ def add_word(self, word. Phonetic translations are based on the SSML phoneme format for representing a word. You can specify them in standard International Phonetic Alphabet (IPA) representation - <phoneme alphabet=\"ipa\" - ph=\"təmˈɑto\"></phoneme> + <phoneme alphabet="ipa" + ph="təmˈɑto"></phoneme> or in the proprietary IBM Symbolic Phonetic Representation (SPR) - <phoneme alphabet=\"ibm\" - ph=\"1gAstroEntxrYFXs\"></phoneme> + <phoneme alphabet="ibm" + ph="1gAstroEntxrYFXs"></phoneme> **Note:** This method is currently a beta release. **See also:** * [Adding a single word to a custom @@ -751,21 +725,23 @@ def add_word(self, * [Understanding customization](https://cloud.ibm.com/docs/services/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 the service - that owns the custom model. - :param str word: The word that is to be added or updated for the custom voice - model. - :param str translation: The phonetic or sounds-like translation for the word. A - phonetic translation is based on the SSML format for representing the phonetic - string of a word either as an IPA translation or as an IBM SPR translation. A - sounds-like is one or more words that, when combined, sound like the word. - :param str part_of_speech: **Japanese only.** The part of speech for the word. The - service uses the value to produce the correct intonation for the 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). + :param str customization_id: The customization ID (GUID) of the custom + voice model. You must make the request with credentials for the instance of + the service that owns the custom model. + :param str word: The word that is to be added or updated for the custom + voice model. + :param str translation: The phonetic or sounds-like translation for the + word. A phonetic translation is based on the SSML format for representing + the phonetic string of a word either as an IPA translation or as an IBM SPR + translation. A sounds-like is one or more words that, when combined, sound + like the word. + :param str part_of_speech: (optional) **Japanese only.** The part of speech + for the word. The service uses the value to produce the correct intonation + for the 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). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -788,12 +764,13 @@ def add_word(self, url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) - response = self.request( + request = self.prepare_request( method='PUT', url=url, headers=headers, - json=data, + data=data, accept_json=False) + response = self.send(request) return response def get_word(self, customization_id, word, **kwargs): @@ -807,10 +784,11 @@ def get_word(self, customization_id, word, **kwargs): **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). - :param str customization_id: The customization ID (GUID) of the custom voice - model. You must make the request with credentials for the instance of the service - that owns the custom model. - :param str word: The word that is to be queried from the custom voice model. + :param str customization_id: The customization ID (GUID) of the custom + voice model. You must make the request with credentials for the instance of + the service that owns the custom model. + :param str word: The word that is to be queried from the custom voice + model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -829,8 +807,9 @@ def get_word(self, customization_id, word, **kwargs): url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, accept_json=True) + response = self.send(request) return response def delete_word(self, customization_id, word, **kwargs): @@ -843,10 +822,11 @@ def delete_word(self, customization_id, word, **kwargs): **See also:** [Deleting a word from a custom model](https://cloud.ibm.com/docs/services/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 the service - that owns the custom model. - :param str word: The word that is to be deleted from the custom voice model. + :param str customization_id: The customization ID (GUID) of the custom + voice model. You must make the request with credentials for the instance of + the service that owns the custom model. + :param str word: The word that is to be deleted from the custom voice + model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -865,8 +845,9 @@ def delete_word(self, customization_id, word, **kwargs): url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, accept_json=False) + response = self.send(request) return response ######################### @@ -887,7 +868,8 @@ def delete_user_data(self, customer_id, **kwargs): **See also:** [Information security](https://cloud.ibm.com/docs/services/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. + :param str customer_id: The customer ID for which all data is to be + deleted. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -906,15 +888,175 @@ def delete_user_data(self, customer_id, **kwargs): params = {'customer_id': customer_id} url = '/v1/user_data' - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response +class GetVoiceEnums(object): + + class Voice(Enum): + """ + The voice for which information is to be returned. + """ + DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' + DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' + DE_DE_DIETERVOICE = 'de-DE_DieterVoice' + DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' + EN_GB_KATEVOICE = 'en-GB_KateVoice' + EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' + EN_US_ALLISONVOICE = 'en-US_AllisonVoice' + EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_LISAVOICE = 'en-US_LisaVoice' + EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' + EN_US_MICHAELVOICE = 'en-US_MichaelVoice' + EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' + ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' + ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' + ES_ES_LAURAVOICE = 'es-ES_LauraVoice' + ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' + ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' + ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' + ES_US_SOFIAVOICE = 'es-US_SofiaVoice' + ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' + FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' + IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' + IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' + JA_JP_EMIVOICE = 'ja-JP_EmiVoice' + JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' + PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' + PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + + +class SynthesizeEnums(object): + + class Accept(Enum): + """ + The requested format (MIME type) of the audio. You can use the `Accept` header or + the `accept` parameter to specify the audio format. For more information about + specifying an audio format, see **Audio formats (accept types)** in the method + description. + """ + AUDIO_BASIC = 'audio/basic' + AUDIO_FLAC = 'audio/flac' + AUDIO_L16 = 'audio/l16' + AUDIO_OGG = 'audio/ogg' + AUDIO_OGG_CODECS_OPUS = 'audio/ogg;codecs=opus' + AUDIO_OGG_CODECS_VORBIS = 'audio/ogg;codecs=vorbis' + AUDIO_MP3 = 'audio/mp3' + AUDIO_MPEG = 'audio/mpeg' + AUDIO_MULAW = 'audio/mulaw' + AUDIO_WAV = 'audio/wav' + AUDIO_WEBM = 'audio/webm' + AUDIO_WEBM_CODECS_OPUS = 'audio/webm;codecs=opus' + AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' + + class Voice(Enum): + """ + The voice to use for synthesis. + """ + DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' + DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' + DE_DE_DIETERVOICE = 'de-DE_DieterVoice' + DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' + EN_GB_KATEVOICE = 'en-GB_KateVoice' + EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' + EN_US_ALLISONVOICE = 'en-US_AllisonVoice' + EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_LISAVOICE = 'en-US_LisaVoice' + EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' + EN_US_MICHAELVOICE = 'en-US_MichaelVoice' + EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' + ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' + ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' + ES_ES_LAURAVOICE = 'es-ES_LauraVoice' + ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' + ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' + ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' + ES_US_SOFIAVOICE = 'es-US_SofiaVoice' + ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' + FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' + IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' + IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' + JA_JP_EMIVOICE = 'ja-JP_EmiVoice' + JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' + PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' + PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + + +class GetPronunciationEnums(object): + + class Voice(Enum): + """ + A voice that specifies the language in which the pronunciation is to be returned. + All voices for the same language (for example, `en-US`) return the same + translation. + """ + DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' + DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' + DE_DE_DIETERVOICE = 'de-DE_DieterVoice' + DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' + EN_GB_KATEVOICE = 'en-GB_KateVoice' + EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' + EN_US_ALLISONVOICE = 'en-US_AllisonVoice' + EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_LISAVOICE = 'en-US_LisaVoice' + EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' + EN_US_MICHAELVOICE = 'en-US_MichaelVoice' + EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' + ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' + ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' + ES_ES_LAURAVOICE = 'es-ES_LauraVoice' + ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' + ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' + ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' + ES_US_SOFIAVOICE = 'es-US_SofiaVoice' + ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' + FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' + IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' + IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' + JA_JP_EMIVOICE = 'ja-JP_EmiVoice' + JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' + PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' + PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + + class Format(Enum): + """ + The phoneme format in which to return the pronunciation. Omit the parameter to + obtain the pronunciation in the default format. + """ + IBM = 'ibm' + IPA = 'ipa' + + +class ListVoiceModelsEnums(object): + + class Language(Enum): + """ + The language for which custom voice models that are owned by the requesting + credentials are to be returned. Omit the parameter to see all custom voice models + that are owned by the requester. + """ + DE_DE = 'de-DE' + EN_GB = 'en-GB' + EN_US = 'en-US' + ES_ES = 'es-ES' + ES_LA = 'es-LA' + ES_US = 'es-US' + FR_FR = 'fr-FR' + IT_IT = 'it-IT' + JA_JP = 'ja-JP' + PT_BR = 'pt-BR' + + ############################################################################## # Models ############################################################################## @@ -924,18 +1066,18 @@ class Pronunciation(object): """ The pronunciation of the specified text. - :attr str pronunciation: The pronunciation of the specified text in the requested - voice and format. If a custom voice model is specified, the pronunciation also - reflects that custom voice. + :attr str pronunciation: The pronunciation of the specified text in the + requested voice and format. If a custom voice model is specified, the + pronunciation also reflects that custom voice. """ def __init__(self, pronunciation): """ Initialize a Pronunciation object. - :param str pronunciation: The pronunciation of the specified text in the requested - voice and format. If a custom voice model is specified, the pronunciation also - reflects that custom voice. + :param str pronunciation: The pronunciation of the specified text in the + requested voice and format. If a custom voice model is specified, the + pronunciation also reflects that custom voice. """ self.pronunciation = pronunciation @@ -983,22 +1125,22 @@ class SupportedFeatures(object): """ Additional service features that are supported with the voice. - :attr bool custom_pronunciation: If `true`, the voice can be customized; if `false`, - the voice cannot be customized. (Same as `customizable`.). - :attr bool voice_transformation: If `true`, the voice can be transformed by using the - SSML <voice-transformation> element; if `false`, the voice cannot be - transformed. + :attr bool custom_pronunciation: If `true`, the voice can be customized; if + `false`, the voice cannot be customized. (Same as `customizable`.). + :attr bool voice_transformation: If `true`, the voice can be transformed by + using the SSML <voice-transformation> element; if `false`, the voice + cannot be transformed. """ def __init__(self, custom_pronunciation, voice_transformation): """ Initialize a SupportedFeatures object. - :param bool custom_pronunciation: If `true`, the voice can be customized; if - `false`, the voice cannot be customized. (Same as `customizable`.). - :param bool voice_transformation: If `true`, the voice can be transformed by using - the SSML <voice-transformation> element; if `false`, the voice cannot be - transformed. + :param bool custom_pronunciation: If `true`, the voice can be customized; + if `false`, the voice cannot be customized. (Same as `customizable`.). + :param bool voice_transformation: If `true`, the voice can be transformed + by using the SSML <voice-transformation> element; if `false`, the + voice cannot be transformed. """ self.custom_pronunciation = custom_pronunciation self.voice_transformation = voice_transformation @@ -1058,31 +1200,33 @@ class Translation(object): Information about the translation for the specified text. :attr str translation: The phonetic or sounds-like translation for the word. A - phonetic translation is based on the SSML format for representing the phonetic string - of a word either as an IPA translation or as an IBM SPR translation. A sounds-like is - one or more words that, when combined, sound like the word. - :attr str part_of_speech: (optional) **Japanese only.** The part of speech for the - word. The service uses the value to produce the correct intonation for the 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). + phonetic translation is based on the SSML format for representing the phonetic + string of a word either as an IPA translation or as an IBM SPR translation. A + sounds-like is one or more words that, when combined, sound like the word. + :attr str part_of_speech: (optional) **Japanese only.** The part of speech for + the word. The service uses the value to produce the correct intonation for the + 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). """ - def __init__(self, translation, part_of_speech=None): + def __init__(self, translation, *, part_of_speech=None): """ Initialize a Translation object. - :param str translation: The phonetic or sounds-like translation for the word. A - phonetic translation is based on the SSML format for representing the phonetic - string of a word either as an IPA translation or as an IBM SPR translation. A - sounds-like is one or more words that, when combined, sound like the word. - :param str part_of_speech: (optional) **Japanese only.** The part of speech for - the word. The service uses the value to produce the correct intonation for the - 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). + :param str translation: The phonetic or sounds-like translation for the + word. A phonetic translation is based on the SSML format for representing + the phonetic string of a word either as an IPA translation or as an IBM SPR + translation. A sounds-like is one or more words that, when combined, sound + like the word. + :param str part_of_speech: (optional) **Japanese only.** The part of speech + for the word. The service uses the value to produce the correct intonation + for the 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). """ self.translation = translation self.part_of_speech = part_of_speech @@ -1130,6 +1274,33 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class PartOfSpeechEnum(Enum): + """ + **Japanese only.** The part of speech for the word. The service uses the value to + produce the correct intonation for the 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). + """ + DOSI = "Dosi" + FUKU = "Fuku" + GOBI = "Gobi" + HOKA = "Hoka" + JODO = "Jodo" + JOSI = "Josi" + KATO = "Kato" + KEDO = "Kedo" + KEYO = "Keyo" + KIGO = "Kigo" + KOYU = "Koyu" + MESI = "Mesi" + RETA = "Reta" + STBI = "Stbi" + STTO = "Stto" + STZO = "Stzo" + SUJI = "Suji" + class Voice(object): """ @@ -1138,17 +1309,17 @@ class Voice(object): :attr str url: The URI of the voice. :attr str gender: The gender of the voice: `male` or `female`. :attr str name: The name of the voice. Use this as the voice identifier in all - requests. + requests. :attr str language: The language and region of the voice (for example, `en-US`). :attr str description: A textual description of the voice. - :attr bool customizable: If `true`, the voice can be customized; if `false`, the voice - cannot be customized. (Same as `custom_pronunciation`; maintained for backward - compatibility.). + :attr bool customizable: If `true`, the voice can be customized; if `false`, the + voice cannot be customized. (Same as `custom_pronunciation`; maintained for + backward compatibility.). :attr SupportedFeatures supported_features: Additional service features that are - supported with the voice. + supported with the voice. :attr VoiceModel customization: (optional) Returns information about a specified - custom voice model. This field is returned only by the **Get a voice** method and only - when you specify the customization ID of a custom voice model. + custom voice model. This field is returned only by the **Get a voice** method + and only when you specify the customization ID of a custom voice model. """ def __init__(self, @@ -1159,24 +1330,27 @@ def __init__(self, description, customizable, supported_features, + *, customization=None): """ Initialize a Voice object. :param str url: The URI of the voice. :param str gender: The gender of the voice: `male` or `female`. - :param str name: The name of the voice. Use this as the voice identifier in all - requests. - :param str language: The language and region of the voice (for example, `en-US`). + :param str name: The name of the voice. Use this as the voice identifier in + all requests. + :param str language: The language and region of the voice (for example, + `en-US`). :param str description: A textual description of the voice. - :param bool customizable: If `true`, the voice can be customized; if `false`, the - voice cannot be customized. (Same as `custom_pronunciation`; maintained for - backward compatibility.). - :param SupportedFeatures supported_features: Additional service features that are - supported with the voice. - :param VoiceModel customization: (optional) Returns information about a specified - custom voice model. This field is returned only by the **Get a voice** method and - only when you specify the customization ID of a custom voice model. + :param bool customizable: If `true`, the voice can be customized; if + `false`, the voice cannot be customized. (Same as `custom_pronunciation`; + maintained for backward compatibility.). + :param SupportedFeatures supported_features: Additional service features + that are supported with the voice. + :param VoiceModel customization: (optional) Returns information about a + specified custom voice model. This field is returned only by the **Get a + voice** method and only when you specify the customization ID of a custom + voice model. """ self.url = url self.gender = gender @@ -1284,31 +1458,34 @@ class VoiceModel(object): """ Information about an existing custom voice model. - :attr str customization_id: The customization ID (GUID) of the custom voice model. The - **Create a custom model** method returns only this field. It does not not return the - other fields of this object. + :attr str customization_id: The customization ID (GUID) of the custom voice + model. The **Create a custom model** method returns only this field. It does not + not return the other fields of this object. :attr str name: (optional) The name of the custom voice model. - :attr str language: (optional) The language identifier of the custom voice model (for - example, `en-US`). + :attr str language: (optional) The language identifier of the custom voice model + (for example, `en-US`). :attr str owner: (optional) The GUID of the credentials for the instance of the - service that owns the custom voice model. - :attr str created: (optional) The date and time in Coordinated Universal Time (UTC) at - which the custom voice model was created. The value is provided in full ISO 8601 - format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str last_modified: (optional) The date and time in Coordinated Universal Time - (UTC) at which the custom voice model was last modified. The `created` and `updated` - fields are equal when a voice model is first added but has yet to be updated. The - value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). + service that owns the custom voice model. + :attr str created: (optional) The date and time in Coordinated Universal Time + (UTC) at which the custom voice model was created. The value is provided in full + ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). + :attr str last_modified: (optional) The date and time in Coordinated Universal + Time (UTC) at which the custom voice model was last modified. The `created` and + `updated` fields are equal when a voice model is first added but has yet to be + updated. The value is provided in full ISO 8601 format + (`YYYY-MM-DDThh:mm:ss.sTZD`). :attr str description: (optional) The description of the custom voice model. - :attr list[Word] words: (optional) An array of `Word` objects that lists the words and - their translations from the custom voice model. The words are listed in alphabetical - order, with uppercase letters listed before lowercase letters. The array is empty if - the custom model contains no words. This field is returned only by the **Get a voice** - method and only when you specify the customization ID of a custom voice model. + :attr list[Word] words: (optional) An array of `Word` objects that lists the + words and their translations from the custom voice model. The words are listed + in alphabetical order, with uppercase letters listed before lowercase letters. + The array is empty if the custom model contains no words. This field is returned + only by the **Get a voice** method and only when you specify the customization + ID of a custom voice model. """ def __init__(self, customization_id, + *, name=None, language=None, owner=None, @@ -1319,29 +1496,30 @@ def __init__(self, """ Initialize a VoiceModel object. - :param str customization_id: The customization ID (GUID) of the custom voice - model. The **Create a custom model** method returns only this field. It does not - not return the other fields of this object. + :param str customization_id: The customization ID (GUID) of the custom + voice model. The **Create a custom model** method returns only this field. + It does not not return the other fields of this object. :param str name: (optional) The name of the custom voice model. - :param str language: (optional) The language identifier of the custom voice model - (for example, `en-US`). - :param str owner: (optional) The GUID of the credentials for the instance of the - service that owns the custom voice model. - :param str created: (optional) The date and time in Coordinated Universal Time - (UTC) at which the custom voice model was created. The value is provided in full - ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :param str last_modified: (optional) The date and time in Coordinated Universal - Time (UTC) at which the custom voice model was last modified. The `created` and - `updated` fields are equal when a voice model is first added but has yet to be - updated. The value is provided in full ISO 8601 format - (`YYYY-MM-DDThh:mm:ss.sTZD`). - :param str description: (optional) The description of the custom voice model. - :param list[Word] words: (optional) An array of `Word` objects that lists the - words and their translations from the custom voice model. The words are listed in - alphabetical order, with uppercase letters listed before lowercase letters. The - array is empty if the custom model contains no words. This field is returned only - by the **Get a voice** method and only when you specify the customization ID of a - custom voice model. + :param str language: (optional) The language identifier of the custom voice + model (for example, `en-US`). + :param str owner: (optional) The GUID of the credentials for the instance + of the service that owns the custom voice model. + :param str created: (optional) The date and time in Coordinated Universal + Time (UTC) at which the custom voice model was created. The value is + provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). + :param str last_modified: (optional) The date and time in Coordinated + Universal Time (UTC) at which the custom voice model was last modified. The + `created` and `updated` fields are equal when a voice model is first added + but has yet to be updated. The value is provided in full ISO 8601 format + (`YYYY-MM-DDThh:mm:ss.sTZD`). + :param str description: (optional) The description of the custom voice + model. + :param list[Word] words: (optional) An array of `Word` objects that lists + the words and their translations from the custom voice model. The words are + listed in alphabetical order, with uppercase letters listed before + lowercase letters. The array is empty if the custom model contains no + words. This field is returned only by the **Get a voice** method and only + when you specify the customization ID of a custom voice model. """ self.customization_id = customization_id self.name = name @@ -1428,20 +1606,21 @@ class VoiceModels(object): """ Information about existing custom voice models. - :attr list[VoiceModel] customizations: An array of `VoiceModel` objects that provides - information about each available custom voice model. The array is empty if the - requesting credentials own no custom voice models (if no language is specified) or own - no custom voice models for the specified language. + :attr list[VoiceModel] customizations: An array of `VoiceModel` objects that + provides information about each available custom voice model. The array is empty + if the requesting credentials own no custom voice models (if no language is + specified) or own no custom voice models for the specified language. """ def __init__(self, customizations): """ Initialize a VoiceModels object. - :param list[VoiceModel] customizations: An array of `VoiceModel` objects that - provides information about each available custom voice model. The array is empty - if the requesting credentials own no custom voice models (if no language is - specified) or own no custom voice models for the specified language. + :param list[VoiceModel] customizations: An array of `VoiceModel` objects + that provides information about each available custom voice model. The + array is empty if the requesting credentials own no custom voice models (if + no language is specified) or own no custom voice models for the specified + language. """ self.customizations = customizations @@ -1551,33 +1730,35 @@ class Word(object): :attr str word: The word for the custom voice model. :attr str translation: The phonetic or sounds-like translation for the word. A - phonetic translation is based on the SSML format for representing the phonetic string - of a word either as an IPA or IBM SPR translation. A sounds-like translation consists - of one or more words that, when combined, sound like the word. - :attr str part_of_speech: (optional) **Japanese only.** The part of speech for the - word. The service uses the value to produce the correct intonation for the 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). + phonetic translation is based on the SSML format for representing the phonetic + string of a word either as an IPA or IBM SPR translation. A sounds-like + translation consists of one or more words that, when combined, sound like the + word. + :attr str part_of_speech: (optional) **Japanese only.** The part of speech for + the word. The service uses the value to produce the correct intonation for the + 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). """ - def __init__(self, word, translation, part_of_speech=None): + def __init__(self, word, translation, *, part_of_speech=None): """ Initialize a Word object. :param str word: The word for the custom voice model. - :param str translation: The phonetic or sounds-like translation for the word. A - phonetic translation is based on the SSML format for representing the phonetic - string of a word either as an IPA or IBM SPR translation. A sounds-like - translation consists of one or more words that, when combined, sound like the - word. - :param str part_of_speech: (optional) **Japanese only.** The part of speech for - the word. The service uses the value to produce the correct intonation for the - 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). + :param str translation: The phonetic or sounds-like translation for the + word. A phonetic translation is based on the SSML format for representing + the phonetic string of a word either as an IPA or IBM SPR translation. A + sounds-like translation consists of one or more words that, when combined, + sound like the word. + :param str part_of_speech: (optional) **Japanese only.** The part of speech + for the word. The service uses the value to produce the correct intonation + for the 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). """ self.word = word self.translation = translation @@ -1632,6 +1813,33 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class PartOfSpeechEnum(Enum): + """ + **Japanese only.** The part of speech for the word. The service uses the value to + produce the correct intonation for the 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). + """ + DOSI = "Dosi" + FUKU = "Fuku" + GOBI = "Gobi" + HOKA = "Hoka" + JODO = "Jodo" + JOSI = "Josi" + KATO = "Kato" + KEDO = "Kedo" + KEYO = "Keyo" + KIGO = "Kigo" + KOYU = "Koyu" + MESI = "Mesi" + RETA = "Reta" + STBI = "Stbi" + STTO = "Stto" + STZO = "Stzo" + SUJI = "Suji" + class Words(object): """ @@ -1640,26 +1848,27 @@ class Words(object): For the **List custom words** method, the words and their translations from the custom voice model. - :attr list[Word] words: The **Add custom words** method accepts an array of `Word` - objects. Each object provides a word that is to be added or updated for the custom - voice model and the word's translation. - The **List custom words** method returns an array of `Word` objects. Each object shows - a word and its translation from the custom voice model. The words are listed in - alphabetical order, with uppercase letters listed before lowercase letters. The array - is empty if the custom model contains no words. + :attr list[Word] words: The **Add custom words** method accepts an array of + `Word` objects. Each object provides a word that is to be added or updated for + the custom voice model and the word's translation. + The **List custom words** method returns an array of `Word` objects. Each object + shows a word and its translation from the custom voice model. The words are + listed in alphabetical order, with uppercase letters listed before lowercase + letters. The array is empty if the custom model contains no words. """ def __init__(self, words): """ Initialize a Words object. - :param list[Word] words: The **Add custom words** method accepts an array of - `Word` objects. Each object provides a word that is to be added or updated for the - custom voice model and the word's translation. - The **List custom words** method returns an array of `Word` objects. Each object - shows a word and its translation from the custom voice model. The words are listed - in alphabetical order, with uppercase letters listed before lowercase letters. The - array is empty if the custom model contains no words. + :param list[Word] words: The **Add custom words** method accepts an array + of `Word` objects. Each object provides a word that is to be added or + updated for the custom voice model and the word's translation. + The **List custom words** method returns an array of `Word` objects. Each + object shows a word and its translation from the custom voice model. The + words are listed in alphabetical order, with uppercase letters listed + before lowercase letters. The array is empty if the custom model contains + no words. """ self.words = words From 0c07e530839c3a894810f62c5491028e783b07fd Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 00:06:16 -0400 Subject: [PATCH 033/455] examples(tts): Update text to speech examples --- examples/text_to_speech_v1.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/examples/text_to_speech_v1.py b/examples/text_to_speech_v1.py index bca6882e7..86ffc0dd8 100644 --- a/examples/text_to_speech_v1.py +++ b/examples/text_to_speech_v1.py @@ -4,18 +4,13 @@ from os.path import join, dirname from ibm_watson import TextToSpeechV1 from ibm_watson.websocket import SynthesizeCallback +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -# If service instance provides API key authentication +authenticator = IAMAuthenticator('your_api_key') service = TextToSpeechV1( ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://stream.watsonplatform.net/text-to-speech/api', - iam_apikey='YOUR APIKEY') - -# service = TextToSpeechV1( -# ## url is optional, and defaults to the URL below. Use the correct URL for your region. -# # url='https://stream.watsonplatform.net/text-to-speech/api, -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD') + authenticator=authenticator) voices = service.list_voices().get_result() print(json.dumps(voices, indent=2)) From a4c0a1d51dd97e94eb66f994250b13c238f700ce Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 00:09:14 -0400 Subject: [PATCH 034/455] test(tts): Update text to speech unit tests --- test/unit/test_text_to_speech_v1.py | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index c18f5e629..454ce955c 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -2,7 +2,7 @@ import responses import ibm_watson import json - +from ibm_cloud_sdk_core.authenticators import BasicAuthenticator @responses.activate def test_success(): @@ -88,8 +88,8 @@ def test_success(): content_type='application/json', match_querystring=True) - text_to_speech = ibm_watson.TextToSpeechV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) text_to_speech.list_voices() assert responses.calls[0].request.url == voices_url @@ -116,8 +116,8 @@ def test_get_pronunciation(): status=200, content_type='application_json') - text_to_speech = ibm_watson.TextToSpeechV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) text_to_speech.get_pronunciation(text="this is some text") text_to_speech.get_pronunciation(text="yo", voice="VoiceEnUsLisa") @@ -160,8 +160,9 @@ def test_custom_voice_models(): status=200, content_type='application_json') - text_to_speech = ibm_watson.TextToSpeechV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) + text_to_speech.list_voice_models() text_to_speech.list_voice_models(language="en-US") assert len(responses.calls) == 2 @@ -215,8 +216,8 @@ def test_custom_words(): status=200, content_type='application_json') - text_to_speech = ibm_watson.TextToSpeechV1( - username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) text_to_speech.list_words(customization_id="custid") text_to_speech.add_words( @@ -239,7 +240,9 @@ def test_delete_user_data(): status=204, content_type='application_json') - text_to_speech = ibm_watson.TextToSpeechV1(username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) + response = text_to_speech.delete_user_data('id').get_result() assert response is None assert len(responses.calls) == 1 From bb6249228ed2097880a86aed36a47152bc4d068c Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 00:19:21 -0400 Subject: [PATCH 035/455] feat(PI): Generate personality insight --- ibm_watson/personality_insights_v3.py | 737 +++++++++++++++----------- 1 file changed, 418 insertions(+), 319 deletions(-) diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index fba01291e..fb60bbf3f 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -33,11 +33,11 @@ or retain data from requests and responses. """ -from __future__ import absolute_import - import json 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 ############################################################################## # Service @@ -53,16 +53,8 @@ def __init__( self, version, url=default_url, - username=None, - password=None, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, + authenticator=None, + disable_ssl_verification=False, ): """ Construct a new client for the Personality Insights service. @@ -82,62 +74,22 @@ def __init__( "https://gateway.watsonplatform.net/personality-insights/api/personality-insights/api"). The base url may differ between IBM Cloud regions. - :param str username: The username used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str password: The password used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ + if not authenticator: + authenticator = get_authenticator_from_environment( + 'Personality Insights') + BaseService.__init__( self, - vcap_services_name='personality_insights', url=url, - username=username, - password=password, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Personality Insights', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Personality Insights') self.version = version ######################### @@ -147,12 +99,13 @@ def __init__( def profile(self, content, accept, + *, + content_type=None, content_language=None, accept_language=None, raw_scores=None, csv_headers=None, consumption_preferences=None, - content_type=None, **kwargs): """ Get profile. @@ -190,37 +143,42 @@ def profile(self, * [Understanding a CSV profile](https://cloud.ibm.com/docs/services/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). - 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. - :param str content_language: The language of the input text for the request: - Arabic, English, Japanese, Korean, or Spanish. Regional variants are treated as - their parent language; for example, `en-US` is interpreted as `en`. - The effect of the **Content-Language** parameter depends on the **Content-Type** - parameter. When **Content-Type** is `text/plain` or `text/html`, - **Content-Language** is the only way to specify the language. When - **Content-Type** is `application/json`, **Content-Language** overrides a language - specified with the `language` parameter of a `ContentItem` object, and content - items that specify a different language are ignored; omit this parameter to base - the language on the specification of the content items. You can specify any - combination of languages for **Content-Language** and **Accept-Language**. - :param str accept_language: The desired language of the response. For - two-character arguments, regional variants are treated as their parent language; - for example, `en-US` is interpreted as `en`. You can specify any combination of - languages for the input and response content. - :param bool raw_scores: Indicates whether a raw score in addition to a normalized - percentile is returned for each characteristic; raw scores are not compared with a - sample population. By default, only normalized percentiles are returned. - :param bool csv_headers: Indicates whether column labels are returned with a CSV - response. By default, no column labels are returned. Applies only when the - response type is CSV (`text/csv`). - :param bool consumption_preferences: Indicates whether consumption preferences are - returned with the results. By default, no consumption preferences are returned. - :param str content_type: The type of the input. For more information, see - **Content types** in the method description. + :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). + 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. + :param str content_type: (optional) The type of the input. For more + information, see **Content types** in the method description. + :param str content_language: (optional) The language of the input text for + the request: Arabic, English, Japanese, Korean, or Spanish. Regional + variants are treated as their parent language; for example, `en-US` is + interpreted as `en`. + The effect of the **Content-Language** parameter depends on the + **Content-Type** parameter. When **Content-Type** is `text/plain` or + `text/html`, **Content-Language** is the only way to specify the language. + When **Content-Type** is `application/json`, **Content-Language** overrides + a language specified with the `language` parameter of a `ContentItem` + object, and content items that specify a different language are ignored; + omit this parameter to base the language on the specification of the + content items. You can specify any combination of languages for + **Content-Language** and **Accept-Language**. + :param str accept_language: (optional) The desired language of the + response. For two-character arguments, regional variants are treated as + their parent language; for example, `en-US` is interpreted as `en`. You can + specify any combination of languages for the input and response content. + :param bool raw_scores: (optional) Indicates whether a raw score in + addition to a normalized percentile is returned for each characteristic; + raw scores are not compared with a sample population. By default, only + normalized percentiles are returned. + :param bool csv_headers: (optional) Indicates whether column labels are + returned with a CSV response. By default, no column labels are returned. + Applies only when the response type is CSV (`text/csv`). + :param bool consumption_preferences: (optional) Indicates whether + consumption preferences are returned with the results. By default, no + consumption preferences are returned. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -235,9 +193,9 @@ def profile(self, headers = { 'Accept': accept, + 'Content-Type': content_type, 'Content-Language': content_language, - 'Accept-Language': accept_language, - 'Content-Type': content_type + 'Accept-Language': accept_language } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -257,16 +215,76 @@ def profile(self, data = content url = '/v3/profile' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, data=data, accept_json=(accept is None or accept == 'application/json')) + response = self.send(request) return response +class ProfileEnums(object): + + class Accept(Enum): + """ + The type of the response. For more information, see **Accept types** in the method + description. + """ + APPLICATION_JSON = 'application/json' + TEXT_CSV = 'text/csv' + + class ContentType(Enum): + """ + The type of the input. For more information, see **Content types** in the method + description. + """ + APPLICATION_JSON = 'application/json' + TEXT_HTML = 'text/html' + TEXT_PLAIN = 'text/plain' + + class ContentLanguage(Enum): + """ + The language of the input text for the request: Arabic, English, Japanese, Korean, + or Spanish. Regional variants are treated as their parent language; for example, + `en-US` is interpreted as `en`. + The effect of the **Content-Language** parameter depends on the **Content-Type** + parameter. When **Content-Type** is `text/plain` or `text/html`, + **Content-Language** is the only way to specify the language. When + **Content-Type** is `application/json`, **Content-Language** overrides a language + specified with the `language` parameter of a `ContentItem` object, and content + items that specify a different language are ignored; omit this parameter to base + the language on the specification of the content items. You can specify any + combination of languages for **Content-Language** and **Accept-Language**. + """ + AR = 'ar' + EN = 'en' + ES = 'es' + JA = 'ja' + KO = 'ko' + + class AcceptLanguage(Enum): + """ + The desired language of the response. For two-character arguments, regional + variants are treated as their parent language; for example, `en-US` is interpreted + as `en`. You can specify any combination of languages for the input and response + content. + """ + AR = 'ar' + DE = 'de' + EN = 'en' + ES = 'es' + FR = 'fr' + IT = 'it' + JA = 'ja' + KO = 'ko' + PT_BR = 'pt-br' + ZH_CN = 'zh-cn' + ZH_TW = 'zh-tw' + + ############################################################################## # Models ############################################################################## @@ -276,27 +294,29 @@ class Behavior(object): """ The temporal behavior for the input content. - :attr str trait_id: The unique, non-localized identifier of the characteristic to - which the results pertain. IDs have the form `behavior_{value}`. + :attr str trait_id: The unique, non-localized identifier of the characteristic + to which the results pertain. IDs have the form `behavior_{value}`. :attr str name: The user-visible, localized name of the characteristic. - :attr str category: The category of the characteristic: `behavior` for temporal data. + :attr str category: The category of the characteristic: `behavior` for temporal + data. :attr float percentage: For JSON content that is timestamped, the percentage of - timestamped input data that occurred during that day of the week or hour of the day. - The range is 0 to 1. + timestamped input data that occurred during that day of the week or hour of the + day. The range is 0 to 1. """ def __init__(self, trait_id, name, category, percentage): """ Initialize a Behavior object. - :param str trait_id: The unique, non-localized identifier of the characteristic to - which the results pertain. IDs have the form `behavior_{value}`. + :param str trait_id: The unique, non-localized identifier of the + characteristic to which the results pertain. IDs have the form + `behavior_{value}`. :param str name: The user-visible, localized name of the characteristic. - :param str category: The category of the characteristic: `behavior` for temporal - data. - :param float percentage: For JSON content that is timestamped, the percentage of - timestamped input data that occurred during that day of the week or hour of the - day. The range is 0 to 1. + :param str category: The category of the characteristic: `behavior` for + temporal data. + :param float percentage: For JSON content that is timestamped, the + percentage of timestamped input data that occurred during that day of the + week or hour of the day. The range is 0 to 1. """ self.trait_id = trait_id self.name = name @@ -368,33 +388,34 @@ class ConsumptionPreferences(object): A consumption preference that the service inferred from the input content. :attr str consumption_preference_id: The unique, non-localized identifier of the - consumption preference to which the results pertain. IDs have the form - `consumption_preferences_{preference}`. + consumption preference to which the results pertain. IDs have the form + `consumption_preferences_{preference}`. :attr str name: The user-visible, localized name of the consumption preference. :attr float score: The score for the consumption preference: - * `0.0`: Unlikely - * `0.5`: Neutral - * `1.0`: Likely - The scores for some preferences are binary and do not allow a neutral value. The score - is an indication of preference based on the results inferred from the input text, not - a normalized percentile. + * `0.0`: Unlikely + * `0.5`: Neutral + * `1.0`: Likely + The scores for some preferences are binary and do not allow a neutral value. The + score is an indication of preference based on the results inferred from the + input text, not a normalized percentile. """ def __init__(self, consumption_preference_id, name, score): """ Initialize a ConsumptionPreferences object. - :param str consumption_preference_id: The unique, non-localized identifier of the - consumption preference to which the results pertain. IDs have the form - `consumption_preferences_{preference}`. - :param str name: The user-visible, localized name of the consumption preference. + :param str consumption_preference_id: The unique, non-localized identifier + of the consumption preference to which the results pertain. IDs have the + form `consumption_preferences_{preference}`. + :param str name: The user-visible, localized name of the consumption + preference. :param float score: The score for the consumption preference: - * `0.0`: Unlikely - * `0.5`: Neutral - * `1.0`: Likely - The scores for some preferences are binary and do not allow a neutral value. The - score is an indication of preference based on the results inferred from the input - text, not a normalized percentile. + * `0.0`: Unlikely + * `0.5`: Neutral + * `1.0`: Likely + The scores for some preferences are binary and do not allow a neutral + value. The score is an indication of preference based on the results + inferred from the input text, not a normalized percentile. """ self.consumption_preference_id = consumption_preference_id self.name = name @@ -462,12 +483,12 @@ class ConsumptionPreferencesCategory(object): """ The consumption preferences that the service inferred from the input content. - :attr str consumption_preference_category_id: The unique, non-localized identifier of - the consumption preferences category to which the results pertain. IDs have the form - `consumption_preferences_{category}`. + :attr str consumption_preference_category_id: The unique, non-localized + identifier of the consumption preferences category to which the results pertain. + IDs have the form `consumption_preferences_{category}`. :attr str name: The user-visible name of the consumption preferences category. - :attr list[ConsumptionPreferences] consumption_preferences: Detailed results inferred - from the input text for the individual preferences of the category. + :attr list[ConsumptionPreferences] consumption_preferences: Detailed results + inferred from the input text for the individual preferences of the category. """ def __init__(self, consumption_preference_category_id, name, @@ -476,11 +497,13 @@ def __init__(self, consumption_preference_category_id, name, Initialize a ConsumptionPreferencesCategory object. :param str consumption_preference_category_id: The unique, non-localized - identifier of the consumption preferences category to which the results pertain. - IDs have the form `consumption_preferences_{category}`. - :param str name: The user-visible name of the consumption preferences category. - :param list[ConsumptionPreferences] consumption_preferences: Detailed results - inferred from the input text for the individual preferences of the category. + identifier of the consumption preferences category to which the results + pertain. IDs have the form `consumption_preferences_{category}`. + :param str name: The user-visible name of the consumption preferences + category. + :param list[ConsumptionPreferences] consumption_preferences: Detailed + results inferred from the input text for the individual preferences of the + category. """ self.consumption_preference_category_id = consumption_preference_category_id self.name = name @@ -558,16 +581,16 @@ class Content(object): """ The full input content that the service is to analyze. - :attr list[ContentItem] content_items: An array of `ContentItem` objects that provides - the text that is to be analyzed. + :attr list[ContentItem] content_items: An array of `ContentItem` objects that + provides the text that is to be analyzed. """ def __init__(self, content_items): """ Initialize a Content object. - :param list[ContentItem] content_items: An array of `ContentItem` objects that - provides the text that is to be analyzed. + :param list[ContentItem] content_items: An array of `ContentItem` objects + that provides the text that is to be analyzed. """ self.content_items = content_items @@ -617,38 +640,40 @@ class ContentItem(object): """ An input content item that the service is to analyze. - :attr str content: The content that is to be analyzed. The service supports up to 20 - MB of content for all `ContentItem` objects combined. + :attr str content: The content that is to be analyzed. The service supports up + to 20 MB of content for all `ContentItem` objects combined. :attr str id: (optional) A unique identifier for this content item. :attr int created: (optional) A timestamp that identifies when this content was - created. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, at - 0:00 UTC). Required only for results that include temporal behavior data. - :attr int updated: (optional) A timestamp that identifies when this content was last - updated. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, at - 0:00 UTC). Required only for results that include temporal behavior data. - :attr str contenttype: (optional) The MIME type of the content. The default is plain - text. The tags are stripped from HTML content before it is analyzed; plain text is - processed as submitted. + created. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, + at 0:00 UTC). Required only for results that include temporal behavior data. + :attr int updated: (optional) A timestamp that identifies when this content was + last updated. Specify a value in milliseconds since the UNIX Epoch (January 1, + 1970, at 0:00 UTC). Required only for results that include temporal behavior + data. + :attr str contenttype: (optional) The MIME type of the content. The default is + plain text. The tags are stripped from HTML content before it is analyzed; plain + text is processed as submitted. :attr str language: (optional) The language identifier (two-letter ISO 639-1 - identifier) for the language of the content item. The default is `en` (English). - Regional variants are treated as their parent language; for example, `en-US` is - interpreted as `en`. A language specified with the **Content-Type** parameter - overrides the value of this parameter; any content items that specify a different - language are ignored. Omit the **Content-Type** parameter to base the language on the - most prevalent specification among the content items; again, content items that - specify a different language are ignored. You can specify any combination of languages - for the input and response content. - :attr str parentid: (optional) The unique ID of the parent content item for this item. - Used to identify hierarchical relationships between posts/replies, messages/replies, - and so on. - :attr bool reply: (optional) Indicates whether this content item is a reply to another - content item. + identifier) for the language of the content item. The default is `en` (English). + Regional variants are treated as their parent language; for example, `en-US` is + interpreted as `en`. A language specified with the **Content-Type** parameter + overrides the value of this parameter; any content items that specify a + different language are ignored. Omit the **Content-Type** parameter to base the + language on the most prevalent specification among the content items; again, + content items that specify a different language are ignored. You can specify any + combination of languages for the input and response content. + :attr str parentid: (optional) The unique ID of the parent content item for this + item. Used to identify hierarchical relationships between posts/replies, + messages/replies, and so on. + :attr bool reply: (optional) Indicates whether this content item is a reply to + another content item. :attr bool forward: (optional) Indicates whether this content item is a - forwarded/copied version of another content item. + forwarded/copied version of another content item. """ def __init__(self, content, + *, id=None, created=None, updated=None, @@ -660,34 +685,37 @@ def __init__(self, """ Initialize a ContentItem object. - :param str content: The content that is to be analyzed. The service supports up to - 20 MB of content for all `ContentItem` objects combined. + :param str content: The content that is to be analyzed. The service + supports up to 20 MB of content for all `ContentItem` objects combined. :param str id: (optional) A unique identifier for this content item. - :param int created: (optional) A timestamp that identifies when this content was - created. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, at - 0:00 UTC). Required only for results that include temporal behavior data. - :param int updated: (optional) A timestamp that identifies when this content was - last updated. Specify a value in milliseconds since the UNIX Epoch (January 1, - 1970, at 0:00 UTC). Required only for results that include temporal behavior data. - :param str contenttype: (optional) The MIME type of the content. The default is - plain text. The tags are stripped from HTML content before it is analyzed; plain - text is processed as submitted. - :param str language: (optional) The language identifier (two-letter ISO 639-1 - identifier) for the language of the content item. The default is `en` (English). - Regional variants are treated as their parent language; for example, `en-US` is - interpreted as `en`. A language specified with the **Content-Type** parameter - overrides the value of this parameter; any content items that specify a different - language are ignored. Omit the **Content-Type** parameter to base the language on - the most prevalent specification among the content items; again, content items - that specify a different language are ignored. You can specify any combination of - languages for the input and response content. - :param str parentid: (optional) The unique ID of the parent content item for this - item. Used to identify hierarchical relationships between posts/replies, - messages/replies, and so on. - :param bool reply: (optional) Indicates whether this content item is a reply to - another content item. + :param int created: (optional) A timestamp that identifies when this + content was created. Specify a value in milliseconds since the UNIX Epoch + (January 1, 1970, at 0:00 UTC). Required only for results that include + temporal behavior data. + :param int updated: (optional) A timestamp that identifies when this + content was last updated. Specify a value in milliseconds since the UNIX + Epoch (January 1, 1970, at 0:00 UTC). Required only for results that + include temporal behavior data. + :param str contenttype: (optional) The MIME type of the content. The + default is plain text. The tags are stripped from HTML content before it is + analyzed; plain text is processed as submitted. + :param str language: (optional) The language identifier (two-letter ISO + 639-1 identifier) for the language of the content item. The default is `en` + (English). Regional variants are treated as their parent language; for + example, `en-US` is interpreted as `en`. A language specified with the + **Content-Type** parameter overrides the value of this parameter; any + content items that specify a different language are ignored. Omit the + **Content-Type** parameter to base the language on the most prevalent + specification among the content items; again, content items that specify a + different language are ignored. You can specify any combination of + languages for the input and response content. + :param str parentid: (optional) The unique ID of the parent content item + for this item. Used to identify hierarchical relationships between + posts/replies, messages/replies, and so on. + :param bool reply: (optional) Indicates whether this content item is a + reply to another content item. :param bool forward: (optional) Indicates whether this content item is a - forwarded/copied version of another content item. + forwarded/copied version of another content item. """ self.content = content self.id = id @@ -772,34 +800,63 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ContenttypeEnum(Enum): + """ + The MIME type of the content. The default is plain text. The tags are stripped + from HTML content before it is analyzed; plain text is processed as submitted. + """ + TEXT_PLAIN = "text/plain" + TEXT_HTML = "text/html" + + class LanguageEnum(Enum): + """ + The language identifier (two-letter ISO 639-1 identifier) for the language of the + content item. The default is `en` (English). Regional variants are treated as + their parent language; for example, `en-US` is interpreted as `en`. A language + specified with the **Content-Type** parameter overrides the value of this + parameter; any content items that specify a different language are ignored. Omit + the **Content-Type** parameter to base the language on the most prevalent + specification among the content items; again, content items that specify a + different language are ignored. You can specify any combination of languages for + the input and response content. + """ + AR = "ar" + EN = "en" + ES = "es" + JA = "ja" + KO = "ko" + class Profile(object): """ The personality profile that the service generated for the input content. - :attr str processed_language: The language model that was used to process the input. - :attr int word_count: The number of words from the input that were used to produce the - profile. - :attr str word_count_message: (optional) When guidance is appropriate, a string that - provides a message that indicates the number of words found and where that value falls - in the range of required or suggested number of words. - :attr list[Trait] personality: A recursive array of `Trait` objects that provides - detailed results for the Big Five personality characteristics (dimensions and facets) - inferred from the input text. - :attr list[Trait] needs: Detailed results for the Needs characteristics inferred from - the input text. - :attr list[Trait] values: Detailed results for the Values characteristics inferred - from the input text. + :attr str processed_language: The language model that was used to process the + input. + :attr int word_count: The number of words from the input that were used to + produce the profile. + :attr str word_count_message: (optional) When guidance is appropriate, a string + that provides a message that indicates the number of words found and where that + value falls in the range of required or suggested number of words. + :attr list[Trait] personality: A recursive array of `Trait` objects that + provides detailed results for the Big Five personality characteristics + (dimensions and facets) inferred from the input text. + :attr list[Trait] needs: Detailed results for the Needs characteristics inferred + from the input text. + :attr list[Trait] values: Detailed results for the Values characteristics + inferred from the input text. :attr list[Behavior] behavior: (optional) For JSON content that is timestamped, - detailed results about the social behavior disclosed by the input in terms of temporal - characteristics. The results include information about the distribution of the content - over the days of the week and the hours of the day. - :attr list[ConsumptionPreferencesCategory] consumption_preferences: (optional) If the - **consumption_preferences** parameter is `true`, detailed results for each category of - consumption preferences. Each element of the array provides information inferred from - the input text for the individual preferences of that category. - :attr list[Warning] warnings: An array of warning messages that are associated with - the input text for the request. The array is empty if the input generated no warnings. + detailed results about the social behavior disclosed by the input in terms of + temporal characteristics. The results include information about the distribution + of the content over the days of the week and the hours of the day. + :attr list[ConsumptionPreferencesCategory] consumption_preferences: (optional) + If the **consumption_preferences** parameter is `true`, detailed results for + each category of consumption preferences. Each element of the array provides + information inferred from the input text for the individual preferences of that + category. + :attr list[Warning] warnings: An array of warning messages that are associated + with the input text for the request. The array is empty if the input generated + no warnings. """ def __init__(self, @@ -809,38 +866,41 @@ def __init__(self, needs, values, warnings, + *, word_count_message=None, behavior=None, consumption_preferences=None): """ Initialize a Profile object. - :param str processed_language: The language model that was used to process the - input. + :param str processed_language: The language model that was used to process + the input. :param int word_count: The number of words from the input that were used to - produce the profile. - :param list[Trait] personality: A recursive array of `Trait` objects that provides - detailed results for the Big Five personality characteristics (dimensions and - facets) inferred from the input text. - :param list[Trait] needs: Detailed results for the Needs characteristics inferred - from the input text. + produce the profile. + :param list[Trait] personality: A recursive array of `Trait` objects that + provides detailed results for the Big Five personality characteristics + (dimensions and facets) inferred from the input text. + :param list[Trait] needs: Detailed results for the Needs characteristics + inferred from the input text. :param list[Trait] values: Detailed results for the Values characteristics - inferred from the input text. - :param list[Warning] warnings: An array of warning messages that are associated - with the input text for the request. The array is empty if the input generated no - warnings. - :param str word_count_message: (optional) When guidance is appropriate, a string - that provides a message that indicates the number of words found and where that - value falls in the range of required or suggested number of words. - :param list[Behavior] behavior: (optional) For JSON content that is timestamped, - detailed results about the social behavior disclosed by the input in terms of - temporal characteristics. The results include information about the distribution - of the content over the days of the week and the hours of the day. - :param list[ConsumptionPreferencesCategory] consumption_preferences: (optional) If - the **consumption_preferences** parameter is `true`, detailed results for each - category of consumption preferences. Each element of the array provides - information inferred from the input text for the individual preferences of that - category. + inferred from the input text. + :param list[Warning] warnings: An array of warning messages that are + associated with the input text for the request. The array is empty if the + input generated no warnings. + :param str word_count_message: (optional) When guidance is appropriate, a + string that provides a message that indicates the number of words found and + where that value falls in the range of required or suggested number of + words. + :param list[Behavior] behavior: (optional) For JSON content that is + timestamped, detailed results about the social behavior disclosed by the + input in terms of temporal characteristics. The results include information + about the distribution of the content over the days of the week and the + hours of the day. + :param list[ConsumptionPreferencesCategory] consumption_preferences: + (optional) If the **consumption_preferences** parameter is `true`, detailed + results for each category of consumption preferences. Each element of the + array provides information inferred from the input text for the individual + preferences of that category. """ self.processed_language = processed_language self.word_count = word_count @@ -960,40 +1020,53 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ProcessedLanguageEnum(Enum): + """ + The language model that was used to process the input. + """ + AR = "ar" + EN = "en" + ES = "es" + JA = "ja" + KO = "ko" + class Trait(object): """ The characteristics that the service inferred from the input content. - :attr str trait_id: The unique, non-localized identifier of the characteristic to - which the results pertain. IDs have the form - * `big5_{characteristic}` for Big Five personality dimensions - * `facet_{characteristic}` for Big Five personality facets - * `need_{characteristic}` for Needs - *`value_{characteristic}` for Values. + :attr str trait_id: The unique, non-localized identifier of the characteristic + to which the results pertain. IDs have the form + * `big5_{characteristic}` for Big Five personality dimensions + * `facet_{characteristic}` for Big Five personality facets + * `need_{characteristic}` for Needs + *`value_{characteristic}` for Values. :attr str name: The user-visible, localized name of the characteristic. - :attr str category: The category of the characteristic: `personality` for Big Five - personality characteristics, `needs` for Needs, and `values` for Values. - :attr float percentile: The normalized percentile score for the characteristic. The - range is 0 to 1. For example, if the percentage for Openness is 0.60, the author - scored in the 60th percentile; the author is more open than 59 percent of the - population and less open than 39 percent of the population. - :attr float raw_score: (optional) The raw score for the characteristic. The range is 0 - to 1. A higher score generally indicates a greater likelihood that the author has that - characteristic, but raw scores must be considered in aggregate: The range of values in - practice might be much smaller than 0 to 1, so an individual score must be considered - in the context of the overall scores and their range. - The raw score is computed based on the input and the service model; it is not - normalized or compared with a sample population. The raw score enables comparison of - the results against a different sampling population and with a custom normalization - approach. + :attr str category: The category of the characteristic: `personality` for Big + Five personality characteristics, `needs` for Needs, and `values` for Values. + :attr float percentile: The normalized percentile score for the characteristic. + The range is 0 to 1. For example, if the percentage for Openness is 0.60, the + author scored in the 60th percentile; the author is more open than 59 percent of + the population and less open than 39 percent of the population. + :attr float raw_score: (optional) The raw score for the characteristic. The + range is 0 to 1. A higher score generally indicates a greater likelihood that + the author has that characteristic, but raw scores must be considered in + aggregate: The range of values in practice might be much smaller than 0 to 1, so + an individual score must be considered in the context of the overall scores and + their range. + The raw score is computed based on the input and the service model; it is not + normalized or compared with a sample population. The raw score enables + comparison of the results against a different sampling population and with a + custom normalization approach. :attr bool significant: (optional) **`2017-10-13`**: Indicates whether the - characteristic is meaningful for the input language. The field is always `true` for - all characteristics of English, Spanish, and Japanese input. The field is `false` for - the subset of characteristics of Arabic and Korean input for which the service's - models are unable to generate meaningful results. **`2016-10-19`**: Not returned. - :attr list[Trait] children: (optional) For `personality` (Big Five) dimensions, more - detailed results for the facets of each dimension as inferred from the input text. + characteristic is meaningful for the input language. The field is always `true` + for all characteristics of English, Spanish, and Japanese input. The field is + `false` for the subset of characteristics of Arabic and Korean input for which + the service's models are unable to generate meaningful results. + **`2016-10-19`**: Not returned. + :attr list[Trait] children: (optional) For `personality` (Big Five) dimensions, + more detailed results for the facets of each dimension as inferred from the + input text. """ def __init__(self, @@ -1001,43 +1074,47 @@ def __init__(self, name, category, percentile, + *, raw_score=None, significant=None, children=None): """ Initialize a Trait object. - :param str trait_id: The unique, non-localized identifier of the characteristic to - which the results pertain. IDs have the form - * `big5_{characteristic}` for Big Five personality dimensions - * `facet_{characteristic}` for Big Five personality facets - * `need_{characteristic}` for Needs - *`value_{characteristic}` for Values. + :param str trait_id: The unique, non-localized identifier of the + characteristic to which the results pertain. IDs have the form + * `big5_{characteristic}` for Big Five personality dimensions + * `facet_{characteristic}` for Big Five personality facets + * `need_{characteristic}` for Needs + *`value_{characteristic}` for Values. :param str name: The user-visible, localized name of the characteristic. - :param str category: The category of the characteristic: `personality` for Big - Five personality characteristics, `needs` for Needs, and `values` for Values. - :param float percentile: The normalized percentile score for the characteristic. - The range is 0 to 1. For example, if the percentage for Openness is 0.60, the - author scored in the 60th percentile; the author is more open than 59 percent of - the population and less open than 39 percent of the population. - :param float raw_score: (optional) The raw score for the characteristic. The range - is 0 to 1. A higher score generally indicates a greater likelihood that the author - has that characteristic, but raw scores must be considered in aggregate: The range - of values in practice might be much smaller than 0 to 1, so an individual score - must be considered in the context of the overall scores and their range. - The raw score is computed based on the input and the service model; it is not - normalized or compared with a sample population. The raw score enables comparison - of the results against a different sampling population and with a custom - normalization approach. + :param str category: The category of the characteristic: `personality` for + Big Five personality characteristics, `needs` for Needs, and `values` for + Values. + :param float percentile: The normalized percentile score for the + characteristic. The range is 0 to 1. For example, if the percentage for + Openness is 0.60, the author scored in the 60th percentile; the author is + more open than 59 percent of the population and less open than 39 percent + of the population. + :param float raw_score: (optional) The raw score for the characteristic. + The range is 0 to 1. A higher score generally indicates a greater + likelihood that the author has that characteristic, but raw scores must be + considered in aggregate: The range of values in practice might be much + smaller than 0 to 1, so an individual score must be considered in the + context of the overall scores and their range. + The raw score is computed based on the input and the service model; it is + not normalized or compared with a sample population. The raw score enables + comparison of the results against a different sampling population and with + a custom normalization approach. :param bool significant: (optional) **`2017-10-13`**: Indicates whether the - characteristic is meaningful for the input language. The field is always `true` - for all characteristics of English, Spanish, and Japanese input. The field is - `false` for the subset of characteristics of Arabic and Korean input for which the - service's models are unable to generate meaningful results. **`2016-10-19`**: Not - returned. - :param list[Trait] children: (optional) For `personality` (Big Five) dimensions, - more detailed results for the facets of each dimension as inferred from the input - text. + characteristic is meaningful for the input language. The field is always + `true` for all characteristics of English, Spanish, and Japanese input. The + field is `false` for the subset of characteristics of Arabic and Korean + input for which the service's models are unable to generate meaningful + results. **`2016-10-19`**: Not returned. + :param list[Trait] children: (optional) For `personality` (Big Five) + dimensions, more detailed results for the facets of each dimension as + inferred from the input text. """ self.trait_id = trait_id self.name = name @@ -1123,6 +1200,15 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class CategoryEnum(Enum): + """ + The category of the characteristic: `personality` for Big Five personality + characteristics, `needs` for Needs, and `values` for Values. + """ + PERSONALITY = "personality" + NEEDS = "needs" + VALUES = "values" + class Warning(object): """ @@ -1130,17 +1216,20 @@ class Warning(object): :attr str warning_id: The identifier of the warning message. :attr str message: The message associated with the `warning_id`: - * `WORD_COUNT_MESSAGE`: "There were {number} words in the input. We need a minimum of - 600, preferably 1,200 or more, to compute statistically significant estimates." - * `JSON_AS_TEXT`: "Request input was processed as text/plain as indicated, however - detected a JSON input. Did you mean application/json?" - * `CONTENT_TRUNCATED`: "For maximum accuracy while also optimizing processing time, - only the first 250KB of input text (excluding markup) was analyzed. Accuracy levels - off at approximately 3,000 words so this did not affect the accuracy of the profile." - * `PARTIAL_TEXT_USED`, "The text provided to compute the profile was trimmed for - performance reasons. This action does not affect the accuracy of the output, as not - all of the input text was required." Applies only when Arabic input text exceeds a - threshold at which additional words do not contribute to the accuracy of the profile. + * `WORD_COUNT_MESSAGE`: "There were {number} words in the input. We need a + minimum of 600, preferably 1,200 or more, to compute statistically significant + estimates." + * `JSON_AS_TEXT`: "Request input was processed as text/plain as indicated, + however detected a JSON input. Did you mean application/json?" + * `CONTENT_TRUNCATED`: "For maximum accuracy while also optimizing processing + time, only the first 250KB of input text (excluding markup) was analyzed. + Accuracy levels off at approximately 3,000 words so this did not affect the + accuracy of the profile." + * `PARTIAL_TEXT_USED`, "The text provided to compute the profile was trimmed for + performance reasons. This action does not affect the accuracy of the output, as + not all of the input text was required." Applies only when Arabic input text + exceeds a threshold at which additional words do not contribute to the accuracy + of the profile. """ def __init__(self, warning_id, message): @@ -1149,19 +1238,20 @@ def __init__(self, warning_id, message): :param str warning_id: The identifier of the warning message. :param str message: The message associated with the `warning_id`: - * `WORD_COUNT_MESSAGE`: "There were {number} words in the input. We need a minimum - of 600, preferably 1,200 or more, to compute statistically significant estimates." - * `JSON_AS_TEXT`: "Request input was processed as text/plain as indicated, however - detected a JSON input. Did you mean application/json?" - * `CONTENT_TRUNCATED`: "For maximum accuracy while also optimizing processing - time, only the first 250KB of input text (excluding markup) was analyzed. Accuracy - levels off at approximately 3,000 words so this did not affect the accuracy of the - profile." - * `PARTIAL_TEXT_USED`, "The text provided to compute the profile was trimmed for - performance reasons. This action does not affect the accuracy of the output, as - not all of the input text was required." Applies only when Arabic input text - exceeds a threshold at which additional words do not contribute to the accuracy of - the profile. + * `WORD_COUNT_MESSAGE`: "There were {number} words in the input. We need a + minimum of 600, preferably 1,200 or more, to compute statistically + significant estimates." + * `JSON_AS_TEXT`: "Request input was processed as text/plain as indicated, + however detected a JSON input. Did you mean application/json?" + * `CONTENT_TRUNCATED`: "For maximum accuracy while also optimizing + processing time, only the first 250KB of input text (excluding markup) was + analyzed. Accuracy levels off at approximately 3,000 words so this did not + affect the accuracy of the profile." + * `PARTIAL_TEXT_USED`, "The text provided to compute the profile was + trimmed for performance reasons. This action does not affect the accuracy + of the output, as not all of the input text was required." Applies only + when Arabic input text exceeds a threshold at which additional words do not + contribute to the accuracy of the profile. """ self.warning_id = warning_id self.message = message @@ -1210,3 +1300,12 @@ def __eq__(self, other): def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + + class WarningIdEnum(Enum): + """ + The identifier of the warning message. + """ + WORD_COUNT_MESSAGE = "WORD_COUNT_MESSAGE" + JSON_AS_TEXT = "JSON_AS_TEXT" + CONTENT_TRUNCATED = "CONTENT_TRUNCATED" + PARTIAL_TEXT_USED = "PARTIAL_TEXT_USED" From 8529ff0cf2f13703e1f66baad42edddaa190e39e Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 00:19:53 -0400 Subject: [PATCH 036/455] test(PI): Update personality insights unit tests --- test/unit/test_personality_insights_v3.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index 548e06486..a1c58572e 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -4,14 +4,14 @@ import os import codecs from ibm_watson.personality_insights_v3 import Profile +from ibm_cloud_sdk_core.authenticators import BasicAuthenticator profile_url = 'https://gateway.watsonplatform.net/personality-insights/api/v3/profile' @responses.activate def test_plain_to_json(): - - personality_insights = ibm_watson.PersonalityInsightsV3( - '2016-10-20', username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect1.txt')) as expect_file: profile_response = expect_file.read() @@ -33,8 +33,8 @@ def test_plain_to_json(): @responses.activate def test_json_to_json(): - personality_insights = ibm_watson.PersonalityInsightsV3( - '2016-10-20', username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect2.txt')) as expect_file: profile_response = expect_file.read() @@ -61,8 +61,8 @@ def test_json_to_json(): @responses.activate def test_json_to_csv(): - personality_insights = ibm_watson.PersonalityInsightsV3( - '2016-10-20', username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect3.txt')) as expect_file: profile_response = expect_file.read() @@ -91,8 +91,8 @@ def test_json_to_csv(): @responses.activate def test_plain_to_json_es(): - personality_insights = ibm_watson.PersonalityInsightsV3( - '2016-10-20', username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) with codecs.open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect4.txt'), \ encoding='utf-8') as expect_file: From f88d15e138b0393ccb4ff19f293307b66897836a Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 00:30:10 -0400 Subject: [PATCH 037/455] examples(pi): Update personality insights examples --- examples/personality_insights_v3.py | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/examples/personality_insights_v3.py b/examples/personality_insights_v3.py index d10d6ae47..b513ddfd5 100755 --- a/examples/personality_insights_v3.py +++ b/examples/personality_insights_v3.py @@ -2,25 +2,18 @@ The example returns a JSON response whose content is the same as that in ../resources/personality-v3-expect2.txt """ -from __future__ import print_function import json from os.path import join, dirname from ibm_watson import PersonalityInsightsV3 import csv +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -# If service instance provides API key authentication +authenticator = IAMAuthenticator('your_api_key') service = PersonalityInsightsV3( version='2017-10-13', ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/personality-insights/api', - iam_apikey='YOUR APIKEY') - -# service = PersonalityInsightsV3( -# version='2017-10-13', -# ## url is optional, and defaults to the URL below. Use the correct URL for your region. -# # url='https://gateway.watsonplatform.net/personality-insights/api', -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD') + authenticator=authenticator) ############################ # Profile with JSON output # @@ -40,7 +33,7 @@ # Profile with CSV output # ########################### -with open(join(dirname(__file__), '../resources/personality-v3.json')) as \ +with open(join(dirname(__file__), '../resources/personality-v3.json'), 'r') as \ profile_json: response = service.profile( profile_json.read(), @@ -48,7 +41,7 @@ csv_headers=True).get_result() profile = response.content -cr = csv.reader(profile.splitlines()) +cr = csv.reader(profile.decode('utf-8').splitlines()) my_list = list(cr) for row in my_list: print(row) From 565649827a01313f882620e30a769fa0053297b8 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 10:01:23 -0400 Subject: [PATCH 038/455] feat(TA): Generate tone analyzer --- ibm_watson/tone_analyzer_v3.py | 859 ++++++++++++++++----------------- 1 file changed, 422 insertions(+), 437 deletions(-) diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 8fdf7f9b1..1f8324272 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + """ The IBM Watson™ Tone Analyzer service uses linguistic analysis to detect emotional and language tones in written text. The service can analyze tone at both the document and @@ -25,37 +26,27 @@ data from requests and responses. """ -from __future__ import absolute_import - import json 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 ############################################################################## # Service ############################################################################## - class ToneAnalyzerV3(BaseService): """The Tone Analyzer V3 service.""" default_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' - def __init__( - self, - version, - url=default_url, - username=None, - password=None, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, - ): + def __init__(self, + version, + url=default_url, + authenticator=None, + disable_ssl_verification=False, + ): """ Construct a new client for the Tone Analyzer service. @@ -74,76 +65,29 @@ def __init__( "https://gateway.watsonplatform.net/tone-analyzer/api/tone-analyzer/api"). The base url may differ between IBM Cloud regions. - :param str username: The username used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str password: The password used to authenticate with the service. - Username and password credentials are only required to run your - application locally or outside of IBM Cloud. When running on - IBM Cloud, the credentials will be automatically loaded from the - `VCAP_SERVICES` environment variable. - - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ - BaseService.__init__( - self, - vcap_services_name='tone_analyzer', + if not authenticator: + authenticator = get_authenticator_from_environment('Tone Analyzer') + + BaseService.__init__(self, url=url, - username=username, - password=password, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Tone Analyzer', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Tone Analyzer') self.version = version ######################### # Methods ######################### - def tone(self, - tone_input, - sentences=None, - tones=None, - content_language=None, - accept_language=None, - content_type=None, - **kwargs): + + + def tone(self, tone_input, *, content_type=None, sentences=None, tones=None, content_language=None, accept_language=None, **kwargs): """ Analyze general tone. @@ -165,32 +109,36 @@ def tone(self, **See also:** [Using the general-purpose endpoint](https://cloud.ibm.com/docs/services/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 `ToneInput`. - :param bool sentences: Indicates whether the service is to return an analysis of - each individual sentence in addition to its analysis of the full document. If - `true` (the default), the service returns results for each sentence. - :param list[str] tones: **`2017-09-21`:** Deprecated. The service continues to - accept the parameter for backward-compatibility, but the parameter no longer - affects the response. - **`2016-05-19`:** A comma-separated list of tones for which the service is to - return its analysis of the input; the indicated tones apply both to the full - document and to individual sentences of the document. You can specify one or more - of the valid values. Omit the parameter to request results for all three tones. - :param str content_language: The language of the input text for the request: - English or French. Regional variants are treated as their parent language; for - example, `en-US` is interpreted as `en`. The input content must match the - specified language. Do not submit content that contains both languages. You can - use different languages for **Content-Language** and **Accept-Language**. - * **`2017-09-21`:** Accepts `en` or `fr`. - * **`2016-05-19`:** Accepts only `en`. - :param str accept_language: The desired language of the response. For - two-character arguments, regional variants are treated as their parent language; - for example, `en-US` is interpreted as `en`. You can use different languages for - **Content-Language** and **Accept-Language**. - :param str content_type: The type of the input. A character encoding can be - specified by including a `charset` parameter. For example, - 'text/plain;charset=utf-8'. + :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 + `ToneInput`. + :param str content_type: (optional) The type of the input. A character + encoding can be specified by including a `charset` parameter. For example, + 'text/plain;charset=utf-8'. + :param bool sentences: (optional) Indicates whether the service is to + return an analysis of each individual sentence in addition to its analysis + of the full document. If `true` (the default), the service returns results + for each sentence. + :param list[str] tones: (optional) **`2017-09-21`:** Deprecated. The + service continues to accept the parameter for backward-compatibility, but + the parameter no longer affects the response. + **`2016-05-19`:** A comma-separated list of tones for which the service is + to return its analysis of the input; the indicated tones apply both to the + full document and to individual sentences of the document. You can specify + one or more of the valid values. Omit the parameter to request results for + all three tones. + :param str content_language: (optional) The language of the input text for + the request: English or French. Regional variants are treated as their + parent language; for example, `en-US` is interpreted as `en`. The input + content must match the specified language. Do not submit content that + contains both languages. You can use different languages for + **Content-Language** and **Accept-Language**. + * **`2017-09-21`:** Accepts `en` or `fr`. + * **`2016-05-19`:** Accepts only `en`. + :param str accept_language: (optional) The desired language of the + response. For two-character arguments, regional variants are treated as + their parent language; for example, `en-US` is interpreted as `en`. You can + use different languages for **Content-Language** and **Accept-Language**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -202,9 +150,9 @@ def tone(self, tone_input = self._convert_model(tone_input, ToneInput) headers = { + 'Content-Type': content_type, 'Content-Language': content_language, - 'Accept-Language': accept_language, - 'Content-Type': content_type + 'Accept-Language': accept_language } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -223,20 +171,17 @@ def tone(self, data = tone_input url = '/v3/tone' - response = self.request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) + response = self.send(request) return response - def tone_chat(self, - utterances, - content_language=None, - accept_language=None, - **kwargs): + + def tone_chat(self, utterances, *, content_language=None, accept_language=None, **kwargs): """ Analyze customer-engagement tone. @@ -253,19 +198,20 @@ def tone_chat(self, **See also:** [Using the customer-engagement endpoint](https://cloud.ibm.com/docs/services/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. - :param str content_language: The language of the input text for the request: - English or French. Regional variants are treated as their parent language; for - example, `en-US` is interpreted as `en`. The input content must match the - specified language. Do not submit content that contains both languages. You can - use different languages for **Content-Language** and **Accept-Language**. - * **`2017-09-21`:** Accepts `en` or `fr`. - * **`2016-05-19`:** Accepts only `en`. - :param str accept_language: The desired language of the response. For - two-character arguments, regional variants are treated as their parent language; - for example, `en-US` is interpreted as `en`. You can use different languages for - **Content-Language** and **Accept-Language**. + :param list[Utterance] utterances: An array of `Utterance` objects that + provides the input content that the service is to analyze. + :param str content_language: (optional) The language of the input text for + the request: English or French. Regional variants are treated as their + parent language; for example, `en-US` is interpreted as `en`. The input + content must match the specified language. Do not submit content that + contains both languages. You can use different languages for + **Content-Language** and **Accept-Language**. + * **`2017-09-21`:** Accepts `en` or `fr`. + * **`2016-05-19`:** Accepts only `en`. + :param str accept_language: (optional) The desired language of the + response. For two-character arguments, regional variants are treated as + their parent language; for example, `en-US` is interpreted as `en`. You can + use different languages for **Content-Language** and **Accept-Language**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -273,7 +219,7 @@ def tone_chat(self, if utterances is None: raise ValueError('utterances must be provided') - utterances = [self._convert_model(x, Utterance) for x in utterances] + utterances = [ self._convert_model(x, Utterance) for x in utterances ] headers = { 'Content-Language': content_language, @@ -284,21 +230,111 @@ def tone_chat(self, sdk_headers = get_sdk_headers('tone_analyzer', 'V3', 'tone_chat') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version + } - data = {'utterances': utterances} + data = { + 'utterances': utterances + } url = '/v3/tone_chat' - response = self.request( - method='POST', - url=url, - headers=headers, - params=params, - json=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) + response = self.send(request) return response +class ToneEnums(object): + class ContentType(Enum): + """ + The type of the input. A character encoding can be specified by including a + `charset` parameter. For example, 'text/plain;charset=utf-8'. + """ + APPLICATION_JSON = 'application/json' + TEXT_PLAIN = 'text/plain' + TEXT_HTML = 'text/html' + class Tones(Enum): + """ + **`2017-09-21`:** Deprecated. The service continues to accept the parameter for + backward-compatibility, but the parameter no longer affects the response. + **`2016-05-19`:** A comma-separated list of tones for which the service is to + return its analysis of the input; the indicated tones apply both to the full + document and to individual sentences of the document. You can specify one or more + of the valid values. Omit the parameter to request results for all three tones. + """ + EMOTION = 'emotion' + LANGUAGE = 'language' + SOCIAL = 'social' + class ContentLanguage(Enum): + """ + The language of the input text for the request: English or French. Regional + variants are treated as their parent language; for example, `en-US` is interpreted + as `en`. The input content must match the specified language. Do not submit + content that contains both languages. You can use different languages for + **Content-Language** and **Accept-Language**. + * **`2017-09-21`:** Accepts `en` or `fr`. + * **`2016-05-19`:** Accepts only `en`. + """ + EN = 'en' + FR = 'fr' + class AcceptLanguage(Enum): + """ + The desired language of the response. For two-character arguments, regional + variants are treated as their parent language; for example, `en-US` is interpreted + as `en`. You can use different languages for **Content-Language** and + **Accept-Language**. + """ + AR = 'ar' + DE = 'de' + EN = 'en' + ES = 'es' + FR = 'fr' + IT = 'it' + JA = 'ja' + KO = 'ko' + PT_BR = 'pt-br' + ZH_CN = 'zh-cn' + ZH_TW = 'zh-tw' + + +class ToneChatEnums(object): + class ContentLanguage(Enum): + """ + The language of the input text for the request: English or French. Regional + variants are treated as their parent language; for example, `en-US` is interpreted + as `en`. The input content must match the specified language. Do not submit + content that contains both languages. You can use different languages for + **Content-Language** and **Accept-Language**. + * **`2017-09-21`:** Accepts `en` or `fr`. + * **`2016-05-19`:** Accepts only `en`. + """ + EN = 'en' + FR = 'fr' + class AcceptLanguage(Enum): + """ + The desired language of the response. For two-character arguments, regional + variants are treated as their parent language; for example, `en-US` is interpreted + as `en`. You can use different languages for **Content-Language** and + **Accept-Language**. + """ + AR = 'ar' + DE = 'de' + EN = 'en' + ES = 'es' + FR = 'fr' + IT = 'it' + JA = 'ja' + KO = 'ko' + PT_BR = 'pt-br' + ZH_CN = 'zh-cn' + ZH_TW = 'zh-tw' + + ############################################################################## # Models ############################################################################## @@ -308,39 +344,41 @@ class DocumentAnalysis(object): """ The results of the analysis for the full input content. - :attr list[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` - objects that provides the results of the analysis for each qualifying tone of the - document. The array includes results for any tone whose score is at least 0.5. The - array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not - returned. - :attr list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. - **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the - tone analysis for the full document of the input content. The service returns results - only for the tones specified with the `tones` parameter of the request. + :attr list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + `ToneScore` objects that provides the results of the analysis for each + qualifying tone of the document. The array includes results for any tone whose + score is at least 0.5. The array is empty if no tone has a score that meets this + threshold. **`2016-05-19`:** Not returned. + :attr list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not + returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the + results of the tone analysis for the full document of the input content. The + service returns results only for the tones specified with the `tones` parameter + of the request. :attr str warning: (optional) **`2017-09-21`:** A warning message if the overall - content exceeds 128 KB or contains more than 1000 sentences. The service analyzes only - the first 1000 sentences for document-level analysis and the first 100 sentences for - sentence-level analysis. **`2016-05-19`:** Not returned. + content exceeds 128 KB or contains more than 1000 sentences. The service + analyzes only the first 1000 sentences for document-level analysis and the first + 100 sentences for sentence-level analysis. **`2016-05-19`:** Not returned. """ - def __init__(self, tones=None, tone_categories=None, warning=None): + def __init__(self, *, tones=None, tone_categories=None, warning=None): """ Initialize a DocumentAnalysis object. - :param list[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` - objects that provides the results of the analysis for each qualifying tone of the - document. The array includes results for any tone whose score is at least 0.5. The - array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** - Not returned. + :param list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + `ToneScore` objects that provides the results of the analysis for each + qualifying tone of the document. The array includes results for any tone + whose score is at least 0.5. The array is empty if no tone has a score that + meets this threshold. **`2016-05-19`:** Not returned. :param list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not - returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the - results of the tone analysis for the full document of the input content. The - service returns results only for the tones specified with the `tones` parameter of - the request. - :param str warning: (optional) **`2017-09-21`:** A warning message if the overall - content exceeds 128 KB or contains more than 1000 sentences. The service analyzes - only the first 1000 sentences for document-level analysis and the first 100 - sentences for sentence-level analysis. **`2016-05-19`:** Not returned. + returned. **`2016-05-19`:** An array of `ToneCategory` objects that + provides the results of the tone analysis for the full document of the + input content. The service returns results only for the tones specified + with the `tones` parameter of the request. + :param str warning: (optional) **`2017-09-21`:** A warning message if the + overall content exceeds 128 KB or contains more than 1000 sentences. The + service analyzes only the first 1000 sentences for document-level analysis + and the first 100 sentences for sentence-level analysis. **`2016-05-19`:** + Not returned. """ self.tones = tones self.tone_categories = tone_categories @@ -353,18 +391,11 @@ def _from_dict(cls, _dict): validKeys = ['tones', 'tone_categories', 'warning'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentAnalysis: ' - + ', '.join(badKeys)) + raise ValueError('Unrecognized keys detected in dictionary for class DocumentAnalysis: ' + ', '.join(badKeys)) if 'tones' in _dict: - args['tones'] = [ - ToneScore._from_dict(x) for x in (_dict.get('tones')) - ] + args['tones'] = [ToneScore._from_dict(x) for x in (_dict.get('tones') )] if 'tone_categories' in _dict: - args['tone_categories'] = [ - ToneCategory._from_dict(x) - for x in (_dict.get('tone_categories')) - ] + args['tone_categories'] = [ToneCategory._from_dict(x) for x in (_dict.get('tone_categories') )] if 'warning' in _dict: args['warning'] = _dict.get('warning') return cls(**args) @@ -374,11 +405,8 @@ def _to_dict(self): _dict = {} if hasattr(self, 'tones') and self.tones is not None: _dict['tones'] = [x._to_dict() for x in self.tones] - if hasattr(self, - 'tone_categories') and self.tone_categories is not None: - _dict['tone_categories'] = [ - x._to_dict() for x in self.tone_categories - ] + if hasattr(self, 'tone_categories') and self.tone_categories is not None: + _dict['tone_categories'] = [x._to_dict() for x in self.tone_categories] if hasattr(self, 'warning') and self.warning is not None: _dict['warning'] = self.warning return _dict @@ -398,56 +426,55 @@ def __ne__(self, other): return not self == other + class SentenceAnalysis(object): """ The results of the analysis for the individual sentences of the input content. - :attr int sentence_id: The unique identifier of a sentence of the input content. The - first sentence has ID 0, and the ID of each subsequent sentence is incremented by one. + :attr int sentence_id: The unique identifier of a sentence of the input content. + The first sentence has ID 0, and the ID of each subsequent sentence is + incremented by one. :attr str text: The text of the input sentence. - :attr list[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` - objects that provides the results of the analysis for each qualifying tone of the - sentence. The array includes results for any tone whose score is at least 0.5. The - array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not - returned. - :attr list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. - **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the - tone analysis for the sentence. The service returns results only for the tones - specified with the `tones` parameter of the request. - :attr int input_from: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** The - offset of the first character of the sentence in the overall input content. - :attr int input_to: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** The - offset of the last character of the sentence in the overall input content. + :attr list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + `ToneScore` objects that provides the results of the analysis for each + qualifying tone of the sentence. The array includes results for any tone whose + score is at least 0.5. The array is empty if no tone has a score that meets this + threshold. **`2016-05-19`:** Not returned. + :attr list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not + returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the + results of the tone analysis for the sentence. The service returns results only + for the tones specified with the `tones` parameter of the request. + :attr int input_from: (optional) **`2017-09-21`:** Not returned. + **`2016-05-19`:** The offset of the first character of the sentence in the + overall input content. + :attr int input_to: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** + The offset of the last character of the sentence in the overall input content. """ - def __init__(self, - sentence_id, - text, - tones=None, - tone_categories=None, - input_from=None, - input_to=None): + def __init__(self, sentence_id, text, *, tones=None, tone_categories=None, input_from=None, input_to=None): """ Initialize a SentenceAnalysis object. - :param int sentence_id: The unique identifier of a sentence of the input content. - The first sentence has ID 0, and the ID of each subsequent sentence is incremented - by one. + :param int sentence_id: The unique identifier of a sentence of the input + content. The first sentence has ID 0, and the ID of each subsequent + sentence is incremented by one. :param str text: The text of the input sentence. - :param list[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` - objects that provides the results of the analysis for each qualifying tone of the - sentence. The array includes results for any tone whose score is at least 0.5. The - array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** - Not returned. + :param list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + `ToneScore` objects that provides the results of the analysis for each + qualifying tone of the sentence. The array includes results for any tone + whose score is at least 0.5. The array is empty if no tone has a score that + meets this threshold. **`2016-05-19`:** Not returned. :param list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not - returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the - results of the tone analysis for the sentence. The service returns results only - for the tones specified with the `tones` parameter of the request. + returned. **`2016-05-19`:** An array of `ToneCategory` objects that + provides the results of the tone analysis for the sentence. The service + returns results only for the tones specified with the `tones` parameter of + the request. :param int input_from: (optional) **`2017-09-21`:** Not returned. - **`2016-05-19`:** The offset of the first character of the sentence in the overall - input content. - :param int input_to: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** - The offset of the last character of the sentence in the overall input content. + **`2016-05-19`:** The offset of the first character of the sentence in the + overall input content. + :param int input_to: (optional) **`2017-09-21`:** Not returned. + **`2016-05-19`:** The offset of the last character of the sentence in the + overall input content. """ self.sentence_id = sentence_id self.text = text @@ -460,36 +487,22 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SentenceAnalysis object from a json dictionary.""" args = {} - validKeys = [ - 'sentence_id', 'text', 'tones', 'tone_categories', 'input_from', - 'input_to' - ] + validKeys = ['sentence_id', 'text', 'tones', 'tone_categories', 'input_from', 'input_to'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SentenceAnalysis: ' - + ', '.join(badKeys)) + raise ValueError('Unrecognized keys detected in dictionary for class SentenceAnalysis: ' + ', '.join(badKeys)) if 'sentence_id' in _dict: args['sentence_id'] = _dict.get('sentence_id') else: - raise ValueError( - 'Required property \'sentence_id\' not present in SentenceAnalysis JSON' - ) + raise ValueError('Required property \'sentence_id\' not present in SentenceAnalysis JSON') if 'text' in _dict: args['text'] = _dict.get('text') else: - raise ValueError( - 'Required property \'text\' not present in SentenceAnalysis JSON' - ) + raise ValueError('Required property \'text\' not present in SentenceAnalysis JSON') if 'tones' in _dict: - args['tones'] = [ - ToneScore._from_dict(x) for x in (_dict.get('tones')) - ] + args['tones'] = [ToneScore._from_dict(x) for x in (_dict.get('tones') )] if 'tone_categories' in _dict: - args['tone_categories'] = [ - ToneCategory._from_dict(x) - for x in (_dict.get('tone_categories')) - ] + args['tone_categories'] = [ToneCategory._from_dict(x) for x in (_dict.get('tone_categories') )] if 'input_from' in _dict: args['input_from'] = _dict.get('input_from') if 'input_to' in _dict: @@ -505,11 +518,8 @@ def _to_dict(self): _dict['text'] = self.text if hasattr(self, 'tones') and self.tones is not None: _dict['tones'] = [x._to_dict() for x in self.tones] - if hasattr(self, - 'tone_categories') and self.tone_categories is not None: - _dict['tone_categories'] = [ - x._to_dict() for x in self.tone_categories - ] + if hasattr(self, 'tone_categories') and self.tone_categories is not None: + _dict['tone_categories'] = [x._to_dict() for x in self.tone_categories] if hasattr(self, 'input_from') and self.input_from is not None: _dict['input_from'] = self.input_from if hasattr(self, 'input_to') and self.input_to is not None: @@ -531,30 +541,31 @@ def __ne__(self, other): return not self == other + class ToneAnalysis(object): """ The tone analysis results for the input from the general-purpose endpoint. - :attr DocumentAnalysis document_tone: The results of the analysis for the full input - content. - :attr list[SentenceAnalysis] sentences_tone: (optional) An array of `SentenceAnalysis` - objects that provides the results of the analysis for the individual sentences of the - input content. The service returns results only for the first 100 sentences of the - input. The field is omitted if the `sentences` parameter of the request is set to - `false`. + :attr DocumentAnalysis document_tone: The results of the analysis for the full + input content. + :attr list[SentenceAnalysis] sentences_tone: (optional) An array of + `SentenceAnalysis` objects that provides the results of the analysis for the + individual sentences of the input content. The service returns results only for + the first 100 sentences of the input. The field is omitted if the `sentences` + parameter of the request is set to `false`. """ - def __init__(self, document_tone, sentences_tone=None): + def __init__(self, document_tone, *, sentences_tone=None): """ Initialize a ToneAnalysis object. - :param DocumentAnalysis document_tone: The results of the analysis for the full - input content. + :param DocumentAnalysis document_tone: The results of the analysis for the + full input content. :param list[SentenceAnalysis] sentences_tone: (optional) An array of - `SentenceAnalysis` objects that provides the results of the analysis for the - individual sentences of the input content. The service returns results only for - the first 100 sentences of the input. The field is omitted if the `sentences` - parameter of the request is set to `false`. + `SentenceAnalysis` objects that provides the results of the analysis for + the individual sentences of the input content. The service returns results + only for the first 100 sentences of the input. The field is omitted if the + `sentences` parameter of the request is set to `false`. """ self.document_tone = document_tone self.sentences_tone = sentences_tone @@ -566,21 +577,13 @@ def _from_dict(cls, _dict): validKeys = ['document_tone', 'sentences_tone'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ToneAnalysis: ' - + ', '.join(badKeys)) + raise ValueError('Unrecognized keys detected in dictionary for class ToneAnalysis: ' + ', '.join(badKeys)) if 'document_tone' in _dict: - args['document_tone'] = DocumentAnalysis._from_dict( - _dict.get('document_tone')) + args['document_tone'] = DocumentAnalysis._from_dict(_dict.get('document_tone')) else: - raise ValueError( - 'Required property \'document_tone\' not present in ToneAnalysis JSON' - ) + raise ValueError('Required property \'document_tone\' not present in ToneAnalysis JSON') if 'sentences_tone' in _dict: - args['sentences_tone'] = [ - SentenceAnalysis._from_dict(x) - for x in (_dict.get('sentences_tone')) - ] + args['sentences_tone'] = [SentenceAnalysis._from_dict(x) for x in (_dict.get('sentences_tone') )] return cls(**args) def _to_dict(self): @@ -589,9 +592,7 @@ def _to_dict(self): if hasattr(self, 'document_tone') and self.document_tone is not None: _dict['document_tone'] = self.document_tone._to_dict() if hasattr(self, 'sentences_tone') and self.sentences_tone is not None: - _dict['sentences_tone'] = [ - x._to_dict() for x in self.sentences_tone - ] + _dict['sentences_tone'] = [x._to_dict() for x in self.sentences_tone] return _dict def __str__(self): @@ -609,15 +610,16 @@ def __ne__(self, other): return not self == other + class ToneCategory(object): """ The category for a tone from the input content. - :attr list[ToneScore] tones: An array of `ToneScore` objects that provides the results - for the tones of the category. - :attr str category_id: The unique, non-localized identifier of the category for the - results. The service can return results for the following category IDs: - `emotion_tone`, `language_tone`, and `social_tone`. + :attr list[ToneScore] tones: An array of `ToneScore` objects that provides the + results for the tones of the category. + :attr str category_id: The unique, non-localized identifier of the category for + the results. The service can return results for the following category IDs: + `emotion_tone`, `language_tone`, and `social_tone`. :attr str category_name: The user-visible, localized name of the category. """ @@ -625,11 +627,11 @@ def __init__(self, tones, category_id, category_name): """ Initialize a ToneCategory object. - :param list[ToneScore] tones: An array of `ToneScore` objects that provides the - results for the tones of the category. - :param str category_id: The unique, non-localized identifier of the category for - the results. The service can return results for the following category IDs: - `emotion_tone`, `language_tone`, and `social_tone`. + :param list[ToneScore] tones: An array of `ToneScore` objects that provides + the results for the tones of the category. + :param str category_id: The unique, non-localized identifier of the + category for the results. The service can return results for the following + category IDs: `emotion_tone`, `language_tone`, and `social_tone`. :param str category_name: The user-visible, localized name of the category. """ self.tones = tones @@ -643,28 +645,19 @@ def _from_dict(cls, _dict): validKeys = ['tones', 'category_id', 'category_name'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ToneCategory: ' - + ', '.join(badKeys)) + raise ValueError('Unrecognized keys detected in dictionary for class ToneCategory: ' + ', '.join(badKeys)) if 'tones' in _dict: - args['tones'] = [ - ToneScore._from_dict(x) for x in (_dict.get('tones')) - ] + args['tones'] = [ToneScore._from_dict(x) for x in (_dict.get('tones') )] else: - raise ValueError( - 'Required property \'tones\' not present in ToneCategory JSON') + raise ValueError('Required property \'tones\' not present in ToneCategory JSON') if 'category_id' in _dict: args['category_id'] = _dict.get('category_id') else: - raise ValueError( - 'Required property \'category_id\' not present in ToneCategory JSON' - ) + raise ValueError('Required property \'category_id\' not present in ToneCategory JSON') if 'category_name' in _dict: args['category_name'] = _dict.get('category_name') else: - raise ValueError( - 'Required property \'category_name\' not present in ToneCategory JSON' - ) + raise ValueError('Required property \'category_name\' not present in ToneCategory JSON') return cls(**args) def _to_dict(self): @@ -693,15 +686,17 @@ def __ne__(self, other): return not self == other + class ToneChatScore(object): """ The score for an utterance from the input content. - :attr float score: The score for the tone in the range of 0.5 to 1. A score greater - than 0.75 indicates a high likelihood that the tone is perceived in the utterance. - :attr str tone_id: The unique, non-localized identifier of the tone for the results. - The service returns results only for tones whose scores meet a minimum threshold of - 0.5. + :attr float score: The score for the tone in the range of 0.5 to 1. A score + greater than 0.75 indicates a high likelihood that the tone is perceived in the + utterance. + :attr str tone_id: The unique, non-localized identifier of the tone for the + results. The service returns results only for tones whose scores meet a minimum + threshold of 0.5. :attr str tone_name: The user-visible, localized name of the tone. """ @@ -709,12 +704,12 @@ def __init__(self, score, tone_id, tone_name): """ Initialize a ToneChatScore object. - :param float score: The score for the tone in the range of 0.5 to 1. A score - greater than 0.75 indicates a high likelihood that the tone is perceived in the - utterance. - :param str tone_id: The unique, non-localized identifier of the tone for the - results. The service returns results only for tones whose scores meet a minimum - threshold of 0.5. + :param float score: The score for the tone in the range of 0.5 to 1. A + score greater than 0.75 indicates a high likelihood that the tone is + perceived in the utterance. + :param str tone_id: The unique, non-localized identifier of the tone for + the results. The service returns results only for tones whose scores meet a + minimum threshold of 0.5. :param str tone_name: The user-visible, localized name of the tone. """ self.score = score @@ -728,26 +723,19 @@ def _from_dict(cls, _dict): validKeys = ['score', 'tone_id', 'tone_name'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ToneChatScore: ' - + ', '.join(badKeys)) + raise ValueError('Unrecognized keys detected in dictionary for class ToneChatScore: ' + ', '.join(badKeys)) if 'score' in _dict: args['score'] = _dict.get('score') else: - raise ValueError( - 'Required property \'score\' not present in ToneChatScore JSON') + raise ValueError('Required property \'score\' not present in ToneChatScore JSON') if 'tone_id' in _dict: args['tone_id'] = _dict.get('tone_id') else: - raise ValueError( - 'Required property \'tone_id\' not present in ToneChatScore JSON' - ) + raise ValueError('Required property \'tone_id\' not present in ToneChatScore JSON') if 'tone_name' in _dict: args['tone_name'] = _dict.get('tone_name') else: - raise ValueError( - 'Required property \'tone_name\' not present in ToneChatScore JSON' - ) + raise ValueError('Required property \'tone_name\' not present in ToneChatScore JSON') return cls(**args) def _to_dict(self): @@ -776,6 +764,21 @@ def __ne__(self, other): return not self == other + class ToneIdEnum(Enum): + """ + The unique, non-localized identifier of the tone for the results. The service + returns results only for tones whose scores meet a minimum threshold of 0.5. + """ + EXCITED = "excited" + FRUSTRATED = "frustrated" + IMPOLITE = "impolite" + POLITE = "polite" + SAD = "sad" + SATISFIED = "satisfied" + SYMPATHETIC = "sympathetic" + + + class ToneInput(object): """ Input for the general-purpose endpoint. @@ -798,14 +801,11 @@ def _from_dict(cls, _dict): validKeys = ['text'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ToneInput: ' - + ', '.join(badKeys)) + raise ValueError('Unrecognized keys detected in dictionary for class ToneInput: ' + ', '.join(badKeys)) if 'text' in _dict: args['text'] = _dict.get('text') else: - raise ValueError( - 'Required property \'text\' not present in ToneInput JSON') + raise ValueError('Required property \'text\' not present in ToneInput JSON') return cls(**args) def _to_dict(self): @@ -830,28 +830,31 @@ def __ne__(self, other): return not self == other + class ToneScore(object): """ The score for a tone from the input content. :attr float score: The score for the tone. - * **`2017-09-21`:** The score that is returned lies in the range of 0.5 to 1. A score - greater than 0.75 indicates a high likelihood that the tone is perceived in the - content. - * **`2016-05-19`:** The score that is returned lies in the range of 0 to 1. A score - less than 0.5 indicates that the tone is unlikely to be perceived in the content; a - score greater than 0.75 indicates a high likelihood that the tone is perceived. + * **`2017-09-21`:** The score that is returned lies in the range of 0.5 to 1. A + score greater than 0.75 indicates a high likelihood that the tone is perceived + in the content. + * **`2016-05-19`:** The score that is returned lies in the range of 0 to 1. A + score less than 0.5 indicates that the tone is unlikely to be perceived in the + content; a score greater than 0.75 indicates a high likelihood that the tone is + perceived. :attr str tone_id: The unique, non-localized identifier of the tone. - * **`2017-09-21`:** The service can return results for the following tone IDs: - `anger`, `fear`, `joy`, and `sadness` (emotional tones); `analytical`, `confident`, - and `tentative` (language tones). The service returns results only for tones whose - scores meet a minimum threshold of 0.5. - * **`2016-05-19`:** The service can return results for the following tone IDs of the - different categories: for the `emotion` category: `anger`, `disgust`, `fear`, `joy`, - and `sadness`; for the `language` category: `analytical`, `confident`, and - `tentative`; for the `social` category: `openness_big5`, `conscientiousness_big5`, - `extraversion_big5`, `agreeableness_big5`, and `emotional_range_big5`. The service - returns scores for all tones of a category, regardless of their values. + * **`2017-09-21`:** The service can return results for the following tone IDs: + `anger`, `fear`, `joy`, and `sadness` (emotional tones); `analytical`, + `confident`, and `tentative` (language tones). The service returns results only + for tones whose scores meet a minimum threshold of 0.5. + * **`2016-05-19`:** The service can return results for the following tone IDs of + the different categories: for the `emotion` category: `anger`, `disgust`, + `fear`, `joy`, and `sadness`; for the `language` category: `analytical`, + `confident`, and `tentative`; for the `social` category: `openness_big5`, + `conscientiousness_big5`, `extraversion_big5`, `agreeableness_big5`, and + `emotional_range_big5`. The service returns scores for all tones of a category, + regardless of their values. :attr str tone_name: The user-visible, localized name of the tone. """ @@ -860,24 +863,25 @@ def __init__(self, score, tone_id, tone_name): Initialize a ToneScore object. :param float score: The score for the tone. - * **`2017-09-21`:** The score that is returned lies in the range of 0.5 to 1. A - score greater than 0.75 indicates a high likelihood that the tone is perceived in - the content. - * **`2016-05-19`:** The score that is returned lies in the range of 0 to 1. A - score less than 0.5 indicates that the tone is unlikely to be perceived in the - content; a score greater than 0.75 indicates a high likelihood that the tone is - perceived. + * **`2017-09-21`:** The score that is returned lies in the range of 0.5 to + 1. A score greater than 0.75 indicates a high likelihood that the tone is + perceived in the content. + * **`2016-05-19`:** The score that is returned lies in the range of 0 to 1. + A score less than 0.5 indicates that the tone is unlikely to be perceived + in the content; a score greater than 0.75 indicates a high likelihood that + the tone is perceived. :param str tone_id: The unique, non-localized identifier of the tone. - * **`2017-09-21`:** The service can return results for the following tone IDs: - `anger`, `fear`, `joy`, and `sadness` (emotional tones); `analytical`, - `confident`, and `tentative` (language tones). The service returns results only - for tones whose scores meet a minimum threshold of 0.5. - * **`2016-05-19`:** The service can return results for the following tone IDs of - the different categories: for the `emotion` category: `anger`, `disgust`, `fear`, - `joy`, and `sadness`; for the `language` category: `analytical`, `confident`, and - `tentative`; for the `social` category: `openness_big5`, `conscientiousness_big5`, - `extraversion_big5`, `agreeableness_big5`, and `emotional_range_big5`. The service - returns scores for all tones of a category, regardless of their values. + * **`2017-09-21`:** The service can return results for the following tone + IDs: `anger`, `fear`, `joy`, and `sadness` (emotional tones); `analytical`, + `confident`, and `tentative` (language tones). The service returns results + only for tones whose scores meet a minimum threshold of 0.5. + * **`2016-05-19`:** The service can return results for the following tone + IDs of the different categories: for the `emotion` category: `anger`, + `disgust`, `fear`, `joy`, and `sadness`; for the `language` category: + `analytical`, `confident`, and `tentative`; for the `social` category: + `openness_big5`, `conscientiousness_big5`, `extraversion_big5`, + `agreeableness_big5`, and `emotional_range_big5`. The service returns + scores for all tones of a category, regardless of their values. :param str tone_name: The user-visible, localized name of the tone. """ self.score = score @@ -891,24 +895,19 @@ def _from_dict(cls, _dict): validKeys = ['score', 'tone_id', 'tone_name'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ToneScore: ' - + ', '.join(badKeys)) + raise ValueError('Unrecognized keys detected in dictionary for class ToneScore: ' + ', '.join(badKeys)) if 'score' in _dict: args['score'] = _dict.get('score') else: - raise ValueError( - 'Required property \'score\' not present in ToneScore JSON') + raise ValueError('Required property \'score\' not present in ToneScore JSON') if 'tone_id' in _dict: args['tone_id'] = _dict.get('tone_id') else: - raise ValueError( - 'Required property \'tone_id\' not present in ToneScore JSON') + raise ValueError('Required property \'tone_id\' not present in ToneScore JSON') if 'tone_name' in _dict: args['tone_name'] = _dict.get('tone_name') else: - raise ValueError( - 'Required property \'tone_name\' not present in ToneScore JSON') + raise ValueError('Required property \'tone_name\' not present in ToneScore JSON') return cls(**args) def _to_dict(self): @@ -937,24 +936,25 @@ def __ne__(self, other): return not self == other + class Utterance(object): """ An utterance for the input of the general-purpose endpoint. - :attr str text: An utterance contributed by a user in the conversation that is to be - analyzed. The utterance can contain multiple sentences. + :attr str text: An utterance contributed by a user in the conversation that is + to be analyzed. The utterance can contain multiple sentences. :attr str user: (optional) A string that identifies the user who contributed the - utterance specified by the `text` parameter. + utterance specified by the `text` parameter. """ - def __init__(self, text, user=None): + def __init__(self, text, *, user=None): """ Initialize a Utterance object. - :param str text: An utterance contributed by a user in the conversation that is to - be analyzed. The utterance can contain multiple sentences. - :param str user: (optional) A string that identifies the user who contributed the - utterance specified by the `text` parameter. + :param str text: An utterance contributed by a user in the conversation + that is to be analyzed. The utterance can contain multiple sentences. + :param str user: (optional) A string that identifies the user who + contributed the utterance specified by the `text` parameter. """ self.text = text self.user = user @@ -966,14 +966,11 @@ def _from_dict(cls, _dict): validKeys = ['text', 'user'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Utterance: ' - + ', '.join(badKeys)) + raise ValueError('Unrecognized keys detected in dictionary for class Utterance: ' + ', '.join(badKeys)) if 'text' in _dict: args['text'] = _dict.get('text') else: - raise ValueError( - 'Required property \'text\' not present in Utterance JSON') + raise ValueError('Required property \'text\' not present in Utterance JSON') if 'user' in _dict: args['user'] = _dict.get('user') return cls(**args) @@ -1002,26 +999,28 @@ def __ne__(self, other): return not self == other + class UtteranceAnalyses(object): """ The results of the analysis for the utterances of the input content. - :attr list[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` objects - that provides the results for each utterance of the input. + :attr list[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` + objects that provides the results for each utterance of the input. :attr str warning: (optional) **`2017-09-21`:** A warning message if the content - contains more than 50 utterances. The service analyzes only the first 50 utterances. - **`2016-05-19`:** Not returned. + contains more than 50 utterances. The service analyzes only the first 50 + utterances. **`2016-05-19`:** Not returned. """ - def __init__(self, utterances_tone, warning=None): + def __init__(self, utterances_tone, *, warning=None): """ Initialize a UtteranceAnalyses object. - :param list[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` - objects that provides the results for each utterance of the input. - :param str warning: (optional) **`2017-09-21`:** A warning message if the content - contains more than 50 utterances. The service analyzes only the first 50 - utterances. **`2016-05-19`:** Not returned. + :param list[UtteranceAnalysis] utterances_tone: An array of + `UtteranceAnalysis` objects that provides the results for each utterance of + the input. + :param str warning: (optional) **`2017-09-21`:** A warning message if the + content contains more than 50 utterances. The service analyzes only the + first 50 utterances. **`2016-05-19`:** Not returned. """ self.utterances_tone = utterances_tone self.warning = warning @@ -1033,18 +1032,11 @@ def _from_dict(cls, _dict): validKeys = ['utterances_tone', 'warning'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class UtteranceAnalyses: ' - + ', '.join(badKeys)) + raise ValueError('Unrecognized keys detected in dictionary for class UtteranceAnalyses: ' + ', '.join(badKeys)) if 'utterances_tone' in _dict: - args['utterances_tone'] = [ - UtteranceAnalysis._from_dict(x) - for x in (_dict.get('utterances_tone')) - ] + args['utterances_tone'] = [UtteranceAnalysis._from_dict(x) for x in (_dict.get('utterances_tone') )] else: - raise ValueError( - 'Required property \'utterances_tone\' not present in UtteranceAnalyses JSON' - ) + raise ValueError('Required property \'utterances_tone\' not present in UtteranceAnalyses JSON') if 'warning' in _dict: args['warning'] = _dict.get('warning') return cls(**args) @@ -1052,11 +1044,8 @@ def _from_dict(cls, _dict): def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, - 'utterances_tone') and self.utterances_tone is not None: - _dict['utterances_tone'] = [ - x._to_dict() for x in self.utterances_tone - ] + if hasattr(self, 'utterances_tone') and self.utterances_tone is not None: + _dict['utterances_tone'] = [x._to_dict() for x in self.utterances_tone] if hasattr(self, 'warning') and self.warning is not None: _dict['warning'] = self.warning return _dict @@ -1076,36 +1065,39 @@ def __ne__(self, other): return not self == other + class UtteranceAnalysis(object): """ The results of the analysis for an utterance of the input content. - :attr int utterance_id: The unique identifier of the utterance. The first utterance - has ID 0, and the ID of each subsequent utterance is incremented by one. + :attr int utterance_id: The unique identifier of the utterance. The first + utterance has ID 0, and the ID of each subsequent utterance is incremented by + one. :attr str utterance_text: The text of the utterance. - :attr list[ToneChatScore] tones: An array of `ToneChatScore` objects that provides - results for the most prevalent tones of the utterance. The array includes results for - any tone whose score is at least 0.5. The array is empty if no tone has a score that - meets this threshold. + :attr list[ToneChatScore] tones: An array of `ToneChatScore` objects that + provides results for the most prevalent tones of the utterance. The array + includes results for any tone whose score is at least 0.5. The array is empty if + no tone has a score that meets this threshold. :attr str error: (optional) **`2017-09-21`:** An error message if the utterance - contains more than 500 characters. The service does not analyze the utterance. - **`2016-05-19`:** Not returned. + contains more than 500 characters. The service does not analyze the utterance. + **`2016-05-19`:** Not returned. """ - def __init__(self, utterance_id, utterance_text, tones, error=None): + def __init__(self, utterance_id, utterance_text, tones, *, error=None): """ Initialize a UtteranceAnalysis object. :param int utterance_id: The unique identifier of the utterance. The first - utterance has ID 0, and the ID of each subsequent utterance is incremented by one. + utterance has ID 0, and the ID of each subsequent utterance is incremented + by one. :param str utterance_text: The text of the utterance. :param list[ToneChatScore] tones: An array of `ToneChatScore` objects that - provides results for the most prevalent tones of the utterance. The array includes - results for any tone whose score is at least 0.5. The array is empty if no tone - has a score that meets this threshold. - :param str error: (optional) **`2017-09-21`:** An error message if the utterance - contains more than 500 characters. The service does not analyze the utterance. - **`2016-05-19`:** Not returned. + provides results for the most prevalent tones of the utterance. The array + includes results for any tone whose score is at least 0.5. The array is + empty if no tone has a score that meets this threshold. + :param str error: (optional) **`2017-09-21`:** An error message if the + utterance contains more than 500 characters. The service does not analyze + the utterance. **`2016-05-19`:** Not returned. """ self.utterance_id = utterance_id self.utterance_text = utterance_text @@ -1119,29 +1111,19 @@ def _from_dict(cls, _dict): validKeys = ['utterance_id', 'utterance_text', 'tones', 'error'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class UtteranceAnalysis: ' - + ', '.join(badKeys)) + raise ValueError('Unrecognized keys detected in dictionary for class UtteranceAnalysis: ' + ', '.join(badKeys)) if 'utterance_id' in _dict: args['utterance_id'] = _dict.get('utterance_id') else: - raise ValueError( - 'Required property \'utterance_id\' not present in UtteranceAnalysis JSON' - ) + raise ValueError('Required property \'utterance_id\' not present in UtteranceAnalysis JSON') if 'utterance_text' in _dict: args['utterance_text'] = _dict.get('utterance_text') else: - raise ValueError( - 'Required property \'utterance_text\' not present in UtteranceAnalysis JSON' - ) + raise ValueError('Required property \'utterance_text\' not present in UtteranceAnalysis JSON') if 'tones' in _dict: - args['tones'] = [ - ToneChatScore._from_dict(x) for x in (_dict.get('tones')) - ] + args['tones'] = [ToneChatScore._from_dict(x) for x in (_dict.get('tones') )] else: - raise ValueError( - 'Required property \'tones\' not present in UtteranceAnalysis JSON' - ) + raise ValueError('Required property \'tones\' not present in UtteranceAnalysis JSON') if 'error' in _dict: args['error'] = _dict.get('error') return cls(**args) @@ -1172,3 +1154,6 @@ def __eq__(self, other): def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + + + From d36b6d11d6264ec3d362907af2015640cc19d891 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 10:05:27 -0400 Subject: [PATCH 039/455] test(TA): Update tone analyzer unit tests --- test/unit/test_tone_analyzer_v3.py | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index d0ae45ff2..94e7af5e3 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -4,6 +4,7 @@ from ibm_watson import ApiException import os import json +from ibm_cloud_sdk_core.authenticators import BasicAuthenticator @responses.activate @@ -19,10 +20,10 @@ def test_tone(): body=tone_response, status=200, content_type='application/json') + authenticator = BasicAuthenticator('username', 'password') + tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) + with open(os.path.join(os.path.dirname(__file__), '../../resources/personality.txt')) as tone_text: - tone_analyzer = ibm_watson.ToneAnalyzerV3("2016-05-19", - username="username", - password="password") tone_analyzer.tone(tone_text.read(), content_type='application/json') assert responses.calls[0].request.url == tone_url + tone_args @@ -45,7 +46,8 @@ def test_tone_with_args(): content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../../resources/personality.txt')) as tone_text: - tone_analyzer = ibm_watson.ToneAnalyzerV3("2016-05-19", username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) tone_analyzer.tone(tone_text.read(), content_type='application/json', sentences=False) assert responses.calls[0].request.url.split('?')[0] == tone_url @@ -72,7 +74,8 @@ def test_tone_with_positional_args(): content_type='application/json') with open(os.path.join(os.path.dirname(__file__), '../../resources/personality.txt')) as tone_text: - tone_analyzer = ibm_watson.ToneAnalyzerV3("2016-05-19", username="username", password="password") + authenticator = BasicAuthenticator('username', 'password') + tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) tone_analyzer.tone(tone_text.read(), content_type='application/json', sentences=False) assert responses.calls[0].request.url.split('?')[0] == tone_url @@ -98,9 +101,8 @@ def test_tone_chat(): body=tone_response, status=200, content_type='application/json') - tone_analyzer = ibm_watson.ToneAnalyzerV3("2016-05-19", - username="username", - password="password") + authenticator = BasicAuthenticator('username', 'password') + tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) utterances = [{'text': 'I am very happy', 'user': 'glenn'}] tone_analyzer.tone_chat(utterances) @@ -130,12 +132,12 @@ def test_error(): status=error_code, content_type='application/json') - tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', - username='username', - password='password') + authenticator = BasicAuthenticator('username', 'password') + tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) + text = 'Team, I know that times are tough!' try: - tone_analyzer.tone(text, 'application/json') + tone_analyzer.tone(text, content_type='application/json') except ApiException as ex: assert len(responses.calls) == 1 assert isinstance(ex, ApiException) From 155eb2f8dafece72063a428982653eb0866e18c9 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 10:08:49 -0400 Subject: [PATCH 040/455] examples(ta): Update tone analyzer examples --- examples/tone_analyzer_v3.py | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/examples/tone_analyzer_v3.py b/examples/tone_analyzer_v3.py index 17a56e085..993223a34 100755 --- a/examples/tone_analyzer_v3.py +++ b/examples/tone_analyzer_v3.py @@ -3,20 +3,14 @@ from os.path import join, dirname from ibm_watson import ToneAnalyzerV3 from ibm_watson.tone_analyzer_v3 import ToneInput +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -# If service instance provides API key authentication +authenticator = IAMAuthenticator('your_api_key') service = ToneAnalyzerV3( ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/tone-analyzer/api', version='2017-09-21', - iam_apikey='YOU APIKEY') - -# service = ToneAnalyzerV3( -# ## url is optional, and defaults to the URL below. Use the correct URL for your region. -# # url='https://gateway.watsonplatform.net/tone-analyzer/api', -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD', -# version='2017-09-21') + authenticator=authenticator) print("\ntone_chat() example 1:\n") utterances = [{ From 74a3fe6f6d746e44c6e0f29291c93b4842a4347c Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 10:23:49 -0400 Subject: [PATCH 041/455] feat(VR): Generate visuall recognition --- ibm_watson/visual_recognition_v3.py | 653 +++++++++++++++------------- 1 file changed, 358 insertions(+), 295 deletions(-) diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 453f5a53c..e0b788cdf 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,12 +19,12 @@ a custom classifier to identify subjects that suit your needs. """ -from __future__ import absolute_import - import json from .common import get_sdk_headers +from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import datetime_to_string, string_to_datetime +from ibm_cloud_sdk_core import get_authenticator_from_environment from os.path import basename ############################################################################## @@ -41,14 +41,8 @@ def __init__( self, version, url=default_url, - iam_apikey=None, - iam_access_token=None, - iam_url=None, - iam_client_id=None, - iam_client_secret=None, - icp4d_access_token=None, - icp4d_url=None, - authentication_type=None, + authenticator=None, + disable_ssl_verification=False, ): """ Construct a new client for the Visual Recognition service. @@ -68,48 +62,22 @@ def __init__( "https://gateway.watsonplatform.net/visual-recognition/api/visual-recognition/api"). The base url may differ between IBM Cloud regions. - :param str iam_apikey: An API key that can be used to request IAM tokens. If - this API key is provided, the SDK will manage the token and handle the - refreshing. - - :param str iam_access_token: An IAM access token is fully managed by the application. - Responsibility falls on the application to refresh the token, either before - it expires or reactively upon receiving a 401 from the service as any requests - made with an expired token will fail. - - :param str iam_url: An optional URL for the IAM service API. Defaults to - 'https://iam.cloud.ibm.com/identity/token'. - - :param str iam_client_id: An optional client_id value to use when interacting with the IAM service. - - :param str iam_client_secret: An optional client_secret value to use when interacting with the IAM service. - - :param str icp4d_access_token: A ICP4D(IBM Cloud Pak for Data) access token is - fully managed by the application. Responsibility falls on the application to - refresh the token, either before it expires or reactively upon receiving a 401 - from the service as any requests made with an expired token will fail. - - :param str icp4d_url: In order to use an SDK-managed token with ICP4D authentication, this - URL must be passed in. - - :param str authentication_type: Specifies the authentication pattern to use. Values that it - takes are basic, iam or icp4d. + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + :param bool disable_ssl_verification: If True, disables ssl verification """ + if not authenticator: + authenticator = get_authenticator_from_environment( + 'Visual Recognition') + BaseService.__init__( self, - vcap_services_name='watson_vision_combined', url=url, - iam_apikey=iam_apikey, - iam_access_token=iam_access_token, - iam_url=iam_url, - iam_client_id=iam_client_id, - iam_client_secret=iam_client_secret, - use_vcap_services=True, - display_name='Visual Recognition', - icp4d_access_token=icp4d_access_token, - icp4d_url=icp4d_url, - authentication_type=authentication_type) + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Visual Recognition') self.version = version ######################### @@ -117,6 +85,7 @@ def __init__( ######################### def classify(self, + *, images_file=None, images_filename=None, images_file_content_type=None, @@ -131,40 +100,44 @@ def classify(self, Classify images with built-in or custom classifiers. - :param file images_file: An image file (.gif, .jpg, .png, .tif) or .zip file with - images. Maximum image size is 10 MB. Include no more than 20 images and limit the - .zip file to 100 MB. Encode the image and .zip file names in UTF-8 if they contain - non-ASCII characters. The service assumes UTF-8 encoding if it encounters - non-ASCII characters. - You can also include an image with the **url** parameter. - :param str images_filename: The filename for images_file. - :param str images_file_content_type: The content type of images_file. - :param str url: The URL of an image (.gif, .jpg, .png, .tif) to analyze. The - minimum recommended pixel density is 32X32 pixels, but the service tends to - perform better with images that are at least 224 x 224 pixels. The maximum image - size is 10 MB. - You can also include images with the **images_file** parameter. - :param float threshold: The minimum score a class must have to be displayed in the - response. Set the threshold to `0.0` to return all identified classes. - :param list[str] owners: The categories of classifiers to apply. The - **classifier_ids** parameter overrides **owners**, so make sure that - **classifier_ids** is empty. - - Use `IBM` to classify against the `default` general classifier. You get the same - result if both **classifier_ids** and **owners** parameters are empty. - - Use `me` to classify against all your custom classifiers. However, for better - performance use **classifier_ids** to specify the specific custom classifiers to - apply. - - Use both `IBM` and `me` to analyze the image against both classifier categories. - :param list[str] classifier_ids: Which classifiers to apply. Overrides the - **owners** parameter. You can specify both custom and built-in classifier IDs. The - built-in `default` classifier is used if both **classifier_ids** and **owners** - parameters are empty. - The following built-in classifier IDs require no training: - - `default`: Returns classes from thousands of general tags. - - `food`: Enhances specificity and accuracy for images of food items. - - `explicit`: Evaluates whether the image might be pornographic. - :param str accept_language: The desired language of parts of the response. See the - response for details. + :param file images_file: (optional) An image file (.gif, .jpg, .png, .tif) + or .zip file with images. Maximum image size is 10 MB. Include no more than + 20 images and limit the .zip file to 100 MB. Encode the image and .zip file + names in UTF-8 if they contain non-ASCII characters. The service assumes + UTF-8 encoding if it encounters non-ASCII characters. + You can also include an image with the **url** parameter. + :param str images_filename: (optional) The filename for images_file. + :param str images_file_content_type: (optional) The content type of + images_file. + :param str url: (optional) The URL of an image (.gif, .jpg, .png, .tif) to + analyze. The minimum recommended pixel density is 32X32 pixels, but the + service tends to perform better with images that are at least 224 x 224 + pixels. The maximum image size is 10 MB. + You can also include images with the **images_file** parameter. + :param float threshold: (optional) The minimum score a class must have to + be displayed in the response. Set the threshold to `0.0` to return all + identified classes. + :param list[str] owners: (optional) The categories of classifiers to apply. + The **classifier_ids** parameter overrides **owners**, so make sure that + **classifier_ids** is empty. + - Use `IBM` to classify against the `default` general classifier. You get + the same result if both **classifier_ids** and **owners** parameters are + empty. + - Use `me` to classify against all your custom classifiers. However, for + better performance use **classifier_ids** to specify the specific custom + classifiers to apply. + - Use both `IBM` and `me` to analyze the image against both classifier + categories. + :param list[str] classifier_ids: (optional) Which classifiers to apply. + Overrides the **owners** parameter. You can specify both custom and + built-in classifier IDs. The built-in `default` classifier is used if both + **classifier_ids** and **owners** parameters are empty. + The following built-in classifier IDs require no training: + - `default`: Returns classes from thousands of general tags. + - `food`: Enhances specificity and accuracy for images of food items. + - `explicit`: Evaluates whether the image might be pornographic. + :param str accept_language: (optional) The desired language of parts of the + response. See the response for details. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -201,13 +174,14 @@ def classify(self, 'application/json') url = '/v3/classify' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response ######################### @@ -215,6 +189,7 @@ def classify(self, ######################### def detect_faces(self, + *, images_file=None, images_filename=None, images_file_content_type=None, @@ -236,23 +211,24 @@ def detect_faces(self, is 10 MB. The minimum recommended pixel density is 32X32 pixels, but the service tends to perform better with images that are at least 224 x 224 pixels. - :param file images_file: An image file (gif, .jpg, .png, .tif.) or .zip file with - images. Limit the .zip file to 100 MB. You can include a maximum of 15 images in a - request. - Encode the image and .zip file names in UTF-8 if they contain non-ASCII - characters. The service assumes UTF-8 encoding if it encounters non-ASCII - characters. - You can also include an image with the **url** parameter. - :param str images_filename: The filename for images_file. - :param str images_file_content_type: The content type of images_file. - :param str url: The URL of an image to analyze. Must be in .gif, .jpg, .png, or - .tif format. The minimum recommended pixel density is 32X32 pixels, but the - service tends to perform better with images that are at least 224 x 224 pixels. - The maximum image size is 10 MB. Redirects are followed, so you can use a - shortened URL. - You can also include images with the **images_file** parameter. - :param str accept_language: The desired language of parts of the response. See the - response for details. + :param file images_file: (optional) An image file (gif, .jpg, .png, .tif.) + or .zip file with images. Limit the .zip file to 100 MB. You can include a + maximum of 15 images in a request. + Encode the image and .zip file names in UTF-8 if they contain non-ASCII + characters. The service assumes UTF-8 encoding if it encounters non-ASCII + characters. + You can also include an image with the **url** parameter. + :param str images_filename: (optional) The filename for images_file. + :param str images_file_content_type: (optional) The content type of + images_file. + :param str url: (optional) The URL of an image to analyze. Must be in .gif, + .jpg, .png, or .tif format. The minimum recommended pixel density is 32X32 + pixels, but the service tends to perform better with images that are at + least 224 x 224 pixels. The maximum image size is 10 MB. Redirects are + followed, so you can use a shortened URL. + You can also include images with the **images_file** parameter. + :param str accept_language: (optional) The desired language of parts of the + response. See the response for details. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -280,13 +256,14 @@ def detect_faces(self, form_data['url'] = (None, url, 'text/plain') url = '/v3/detect_faces' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response ######################### @@ -296,6 +273,7 @@ def detect_faces(self, def create_classifier(self, name, positive_examples, + *, negative_examples=None, negative_examples_filename=None, **kwargs): @@ -303,31 +281,37 @@ def create_classifier(self, Create a classifier. Train a new multi-faceted classifier on the uploaded image data. Create your - custom classifier with positive or negative examples. Include at least two sets of - examples, either two positive example files or one positive and one negative file. - You can upload a maximum of 256 MB per call. - Encode all names in UTF-8 if they contain non-ASCII characters (.zip and image + custom classifier with positive or negative example training images. Include at + least two sets of examples, either two positive example files or one positive and + one negative file. You can upload a maximum of 256 MB per call. + **Tips when creating:** + - If you set the **X-Watson-Learning-Opt-Out** header parameter to `true` when you + create a classifier, the example training images are not stored. Save your + training images locally. For more information, see [Data + collection](#data-collection). + - 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. - :param str name: The name of the new classifier. Encode special characters in - UTF-8. - :param dict positive_examples: A dictionary that contains the value for each - classname. The value is a .zip file of images that depict the visual subject of a - class in the new classifier. You can include more than one positive example file - in a call. - Specify the parameter name by appending `_positive_examples` to the class name. - For example, `goldenretriever_positive_examples` creates the class - **goldenretriever**. - Include at least 10 images in .jpg or .png format. The minimum recommended image - resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 - MB per .zip file. - Encode special characters in the file name in UTF-8. - :param file negative_examples: A .zip file of images that do not depict the visual - subject of any of the classes of the new classifier. Must contain a minimum of 10 - images. - Encode special characters in the file name in UTF-8. - :param str negative_examples_filename: The filename for negative_examples. + :param str name: The name of the new classifier. Encode special characters + in UTF-8. + :param dict positive_examples: A dictionary that contains the value for + each classname. The value is a .zip file of images that depict the visual + subject of a class in the new classifier. You can include more than one + positive example file in a call. + Specify the parameter name by appending `_positive_examples` to the class + name. For example, `goldenretriever_positive_examples` creates the class + **goldenretriever**. + Include at least 10 images in .jpg or .png format. The minimum recommended + image resolution is 32X32 pixels. The maximum number of images is 10,000 + images or 100 MB per .zip file. + Encode special characters in the file name in UTF-8. + :param file negative_examples: (optional) A .zip file of images that do not + depict the visual subject of any of the classes of the new classifier. Must + contain a minimum of 10 images. + Encode special characters in the file name in UTF-8. + :param str negative_examples_filename: (optional) The filename for + negative_examples. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -366,21 +350,22 @@ class in the new classifier. You can include more than one positive example file 'application/octet-stream') url = '/v3/classifiers' - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response - def list_classifiers(self, verbose=None, **kwargs): + def list_classifiers(self, *, verbose=None, **kwargs): """ Retrieve a list of classifiers. - :param bool verbose: Specify `true` to return details about the classifiers. Omit - this parameter to return a brief list of classifiers. + :param bool verbose: (optional) Specify `true` to return details about the + classifiers. Omit this parameter to return a brief list of classifiers. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -396,12 +381,13 @@ def list_classifiers(self, verbose=None, **kwargs): params = {'version': self.version, 'verbose': verbose} url = '/v3/classifiers' - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def get_classifier(self, classifier_id, **kwargs): @@ -430,16 +416,18 @@ def get_classifier(self, classifier_id, **kwargs): url = '/v3/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response def update_classifier(self, classifier_id, + *, positive_examples={}, negative_examples=None, negative_examples_filename=None, @@ -454,28 +442,35 @@ def update_classifier(self, 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. - **Tip:** Don't make retraining calls on a classifier until the status is ready. - When you submit retraining requests in parallel, the last request overwrites the - previous requests. The retrained property shows the last time the classifier - retraining finished. + **Tips about retraining:** + - You can't update the classifier if the **X-Watson-Learning-Opt-Out** header + parameter was set to `true` when the classifier was created. Training images are + not stored in that case. Instead, create another classifier. For more information, + see [Data collection](#data-collection). + - Don't make retraining calls on a classifier until the status is ready. When you + submit retraining requests in parallel, the last request overwrites the previous + requests. The `retrained` property shows the last time the classifier retraining + finished. :param str classifier_id: The ID of the classifier. - :param dict positive_examples: A dictionary that contains the value for each - classname. The value is a .zip file of images that depict the visual subject of a - class in the classifier. The positive examples create or update classes in the - classifier. You can include more than one positive example file in a call. - Specify the parameter name by appending `_positive_examples` to the class name. - For example, `goldenretriever_positive_examples` creates the class - `goldenretriever`. - Include at least 10 images in .jpg or .png format. The minimum recommended image - resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 - MB per .zip file. - Encode special characters in the file name in UTF-8. - :param file negative_examples: A .zip file of images that do not depict the visual - subject of any of the classes of the new classifier. Must contain a minimum of 10 - images. - Encode special characters in the file name in UTF-8. - :param str negative_examples_filename: The filename for negative_examples. + :param dict positive_examples: (optional) A dictionary that contains the + value for each classname. The value is a .zip file of images that depict + the visual subject of a class in the classifier. The positive examples + create or update classes in the classifier. You can include more than one + positive example file in a call. + Specify the parameter name by appending `_positive_examples` to the class + name. For example, `goldenretriever_positive_examples` creates the class + `goldenretriever`. + Include at least 10 images in .jpg or .png format. The minimum recommended + image resolution is 32X32 pixels. The maximum number of images is 10,000 + images or 100 MB per .zip file. + Encode special characters in the file name in UTF-8. + :param file negative_examples: (optional) A .zip file of images that do not + depict the visual subject of any of the classes of the new classifier. Must + contain a minimum of 10 images. + Encode special characters in the file name in UTF-8. + :param str negative_examples_filename: (optional) The filename for + negative_examples. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -512,13 +507,14 @@ class in the classifier. The positive examples create or update classes in the url = '/v3/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - response = self.request( + request = self.prepare_request( method='POST', url=url, headers=headers, params=params, files=form_data, accept_json=True) + response = self.send(request) return response def delete_classifier(self, classifier_id, **kwargs): @@ -545,12 +541,13 @@ def delete_classifier(self, classifier_id, **kwargs): url = '/v3/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response ######################### @@ -562,7 +559,7 @@ def get_core_ml_model(self, classifier_id, **kwargs): Retrieve a Core ML model of a classifier. Download a Core ML model file (.mlmodel) of a custom classifier that returns - \"core_ml_enabled\": true in the classifier details. + "core_ml_enabled": true in the classifier details. :param str classifier_id: The ID of the classifier. :param dict headers: A `dict` containing the request headers @@ -584,12 +581,13 @@ def get_core_ml_model(self, classifier_id, **kwargs): url = '/v3/classifiers/{0}/core_ml_model'.format( *self._encode_path_vars(classifier_id)) - response = self.request( + request = self.prepare_request( method='GET', url=url, headers=headers, params=params, accept_json=False) + response = self.send(request) return response ######################### @@ -607,7 +605,8 @@ def delete_user_data(self, customer_id, **kwargs): customer IDs, see [Information security](https://cloud.ibm.com/docs/services/visual-recognition?topic=visual-recognition-information-security). - :param str customer_id: The customer ID for which all data is to be deleted. + :param str customer_id: The customer ID for which all data is to be + deleted. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -626,15 +625,54 @@ def delete_user_data(self, customer_id, **kwargs): params = {'version': self.version, 'customer_id': customer_id} url = '/v3/user_data' - response = self.request( + request = self.prepare_request( method='DELETE', url=url, headers=headers, params=params, accept_json=True) + response = self.send(request) return response +class ClassifyEnums(object): + + class AcceptLanguage(Enum): + """ + The desired language of parts of the response. See the response for details. + """ + EN = 'en' + AR = 'ar' + DE = 'de' + ES = 'es' + FR = 'fr' + IT = 'it' + JA = 'ja' + KO = 'ko' + PT_BR = 'pt-br' + ZH_CN = 'zh-cn' + ZH_TW = 'zh-tw' + + +class DetectFacesEnums(object): + + class AcceptLanguage(Enum): + """ + The desired language of parts of the response. See the response for details. + """ + EN = 'en' + AR = 'ar' + DE = 'de' + ES = 'es' + FR = 'fr' + IT = 'it' + JA = 'ja' + KO = 'ko' + PT_BR = 'pt-br' + ZH_CN = 'zh-cn' + ZH_TW = 'zh-tw' + + ############################################################################## # Models ############################################################################## @@ -644,29 +682,29 @@ class Class(object): """ A category within a classifier. - :attr str class_name: The name of the class. + :attr str class_: The name of the class. """ - def __init__(self, class_name): + def __init__(self, class_): """ Initialize a Class object. - :param str class_name: The name of the class. + :param str class_: The name of the class. """ - self.class_name = class_name + self.class_ = class_ @classmethod def _from_dict(cls, _dict): """Initialize a Class object from a json dictionary.""" args = {} - validKeys = ['class_name', 'class'] + validKeys = ['class_', 'class'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: raise ValueError( 'Unrecognized keys detected in dictionary for class Class: ' + ', '.join(badKeys)) - if 'class' in _dict or 'class_name' in _dict: - args['class_name'] = _dict.get('class') or _dict.get('class_name') + if 'class' in _dict: + args['class_'] = _dict.get('class') else: raise ValueError( 'Required property \'class\' not present in Class JSON') @@ -675,8 +713,8 @@ def _from_dict(cls, _dict): def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'class_name') and self.class_name is not None: - _dict['class'] = self.class_name + if hasattr(self, 'class_') and self.class_ is not None: + _dict['class'] = self.class_ return _dict def __str__(self): @@ -698,37 +736,40 @@ class ClassResult(object): """ Result of a class within a classifier. - :attr str class_name: Name of the class. - Class names are translated in the language defined by the **Accept-Language** request - header for the build-in classifier IDs (`default`, `food`, and `explicit`). Class - names of custom classifiers are not translated. The response might not be in the - specified language when the requested language is not supported or when there is no - translation for the class name. - :attr float score: Confidence score for the property in the range of 0 to 1. A higher - score indicates greater likelihood that the class is depicted in the image. The - default threshold for returning scores from a classifier is 0.5. - :attr str type_hierarchy: (optional) Knowledge graph of the property. For example, - `/fruit/pome/apple/eating apple/Granny Smith`. Included only if identified. + :attr str class_: Name of the class. + Class names are translated in the language defined by the **Accept-Language** + request header for the build-in classifier IDs (`default`, `food`, and + `explicit`). Class names of custom classifiers are not translated. The response + might not be in the specified language when the requested language is not + supported or when there is no translation for the class name. + :attr float score: Confidence score for the property in the range of 0 to 1. A + higher score indicates greater likelihood that the class is depicted in the + image. The default threshold for returning scores from a classifier is 0.5. + :attr str type_hierarchy: (optional) Knowledge graph of the property. For + example, `/fruit/pome/apple/eating apple/Granny Smith`. Included only if + identified. """ - def __init__(self, class_name, score, type_hierarchy=None): + def __init__(self, class_, score, *, type_hierarchy=None): """ Initialize a ClassResult object. - :param str class_name: Name of the class. - Class names are translated in the language defined by the **Accept-Language** - request header for the build-in classifier IDs (`default`, `food`, and - `explicit`). Class names of custom classifiers are not translated. The response - might not be in the specified language when the requested language is not - supported or when there is no translation for the class name. - :param float score: Confidence score for the property in the range of 0 to 1. A - higher score indicates greater likelihood that the class is depicted in the image. - The default threshold for returning scores from a classifier is 0.5. + :param str class_: Name of the class. + Class names are translated in the language defined by the + **Accept-Language** request header for the build-in classifier IDs + (`default`, `food`, and `explicit`). Class names of custom classifiers are + not translated. The response might not be in the specified language when + the requested language is not supported or when there is no translation for + the class name. + :param float score: Confidence score for the property in the range of 0 to + 1. A higher score indicates greater likelihood that the class is depicted + in the image. The default threshold for returning scores from a classifier + is 0.5. :param str type_hierarchy: (optional) Knowledge graph of the property. For - example, `/fruit/pome/apple/eating apple/Granny Smith`. Included only if - identified. + example, `/fruit/pome/apple/eating apple/Granny Smith`. Included only if + identified. """ - self.class_name = class_name + self.class_ = class_ self.score = score self.type_hierarchy = type_hierarchy @@ -736,14 +777,14 @@ def __init__(self, class_name, score, type_hierarchy=None): def _from_dict(cls, _dict): """Initialize a ClassResult object from a json dictionary.""" args = {} - validKeys = ['class_name', 'class', 'score', 'type_hierarchy'] + validKeys = ['class_', 'class', 'score', 'type_hierarchy'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: raise ValueError( 'Unrecognized keys detected in dictionary for class ClassResult: ' + ', '.join(badKeys)) - if 'class' in _dict or 'class_name' in _dict: - args['class_name'] = _dict.get('class') or _dict.get('class_name') + if 'class' in _dict: + args['class_'] = _dict.get('class') else: raise ValueError( 'Required property \'class\' not present in ClassResult JSON') @@ -759,8 +800,8 @@ def _from_dict(cls, _dict): def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'class_name') and self.class_name is not None: - _dict['class'] = self.class_name + if hasattr(self, 'class_') and self.class_ is not None: + _dict['class'] = self.class_ if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'type_hierarchy') and self.type_hierarchy is not None: @@ -787,18 +828,20 @@ class ClassifiedImage(object): Results for one image. :attr str source_url: (optional) Source of the image before any redirects. Not - returned when the image is uploaded. - :attr str resolved_url: (optional) Fully resolved URL of the image after redirects are - followed. Not returned when the image is uploaded. - :attr str image: (optional) Relative path of the image file if uploaded directly. Not - returned when the image is passed by URL. - :attr ErrorInfo error: (optional) Information about what might have caused a failure, - such as an image that is too large. Not returned when there is no error. + returned when the image is uploaded. + :attr str resolved_url: (optional) Fully resolved URL of the image after + redirects are followed. Not returned when the image is uploaded. + :attr str image: (optional) Relative path of the image file if uploaded + directly. Not returned when the image is passed by URL. + :attr ErrorInfo error: (optional) Information about what might have caused a + failure, such as an image that is too large. Not returned when there is no + error. :attr list[ClassifierResult] classifiers: The classifiers. """ def __init__(self, classifiers, + *, source_url=None, resolved_url=None, image=None, @@ -807,14 +850,15 @@ def __init__(self, Initialize a ClassifiedImage object. :param list[ClassifierResult] classifiers: The classifiers. - :param str source_url: (optional) Source of the image before any redirects. Not - returned when the image is uploaded. + :param str source_url: (optional) Source of the image before any redirects. + Not returned when the image is uploaded. :param str resolved_url: (optional) Fully resolved URL of the image after - redirects are followed. Not returned when the image is uploaded. - :param str image: (optional) Relative path of the image file if uploaded directly. - Not returned when the image is passed by URL. - :param ErrorInfo error: (optional) Information about what might have caused a - failure, such as an image that is too large. Not returned when there is no error. + redirects are followed. Not returned when the image is uploaded. + :param str image: (optional) Relative path of the image file if uploaded + directly. Not returned when the image is passed by URL. + :param ErrorInfo error: (optional) Information about what might have caused + a failure, such as an image that is too large. Not returned when there is + no error. """ self.source_url = source_url self.resolved_url = resolved_url @@ -888,17 +932,19 @@ class ClassifiedImages(object): Results for all images. :attr int custom_classes: (optional) Number of custom classes identified in the - images. - :attr int images_processed: (optional) Number of images processed for the API call. + images. + :attr int images_processed: (optional) Number of images processed for the API + call. :attr list[ClassifiedImage] images: Classified images. - :attr list[WarningInfo] warnings: (optional) Information about what might cause less - than optimal output. For example, a request sent with a corrupt .zip file and a list - of image URLs will still complete, but does not return the expected output. Not - returned when there is no warning. + :attr list[WarningInfo] warnings: (optional) Information about what might cause + less than optimal output. For example, a request sent with a corrupt .zip file + and a list of image URLs will still complete, but does not return the expected + output. Not returned when there is no warning. """ def __init__(self, images, + *, custom_classes=None, images_processed=None, warnings=None): @@ -906,14 +952,14 @@ def __init__(self, Initialize a ClassifiedImages object. :param list[ClassifiedImage] images: Classified images. - :param int custom_classes: (optional) Number of custom classes identified in the - images. - :param int images_processed: (optional) Number of images processed for the API - call. - :param list[WarningInfo] warnings: (optional) Information about what might cause - less than optimal output. For example, a request sent with a corrupt .zip file and - a list of image URLs will still complete, but does not return the expected output. - Not returned when there is no warning. + :param int custom_classes: (optional) Number of custom classes identified + in the images. + :param int images_processed: (optional) Number of images processed for the + API call. + :param list[WarningInfo] warnings: (optional) Information about what might + cause less than optimal output. For example, a request sent with a corrupt + .zip file and a list of image URLs will still complete, but does not return + the expected output. Not returned when there is no warning. """ self.custom_classes = custom_classes self.images_processed = images_processed @@ -983,27 +1029,28 @@ class Classifier(object): :attr str classifier_id: ID of a classifier identified in the image. :attr str name: Name of the classifier. - :attr str owner: (optional) Unique ID of the account who owns the classifier. Might - not be returned by some requests. + :attr str owner: (optional) Unique ID of the account who owns the classifier. + Might not be returned by some requests. :attr str status: (optional) Training status of classifier. - :attr bool core_ml_enabled: (optional) Whether the classifier can be downloaded as a - Core ML model after the training status is `ready`. - :attr str explanation: (optional) If classifier training has failed, this field might - explain why. - :attr datetime created: (optional) Date and time in Coordinated Universal Time (UTC) - that the classifier was created. + :attr bool core_ml_enabled: (optional) Whether the classifier can be downloaded + as a Core ML model after the training status is `ready`. + :attr str explanation: (optional) If classifier training has failed, this field + might explain why. + :attr datetime created: (optional) Date and time in Coordinated Universal Time + (UTC) that the classifier was created. :attr list[Class] classes: (optional) Classes that define a classifier. - :attr datetime retrained: (optional) Date and time in Coordinated Universal Time (UTC) - that the classifier was updated. Might not be returned by some requests. Identical to - `updated` and retained for backward compatibility. - :attr datetime updated: (optional) Date and time in Coordinated Universal Time (UTC) - that the classifier was most recently updated. The field matches either `retrained` or - `created`. Might not be returned by some requests. + :attr datetime retrained: (optional) Date and time in Coordinated Universal Time + (UTC) that the classifier was updated. Might not be returned by some requests. + Identical to `updated` and retained for backward compatibility. + :attr datetime updated: (optional) Date and time in Coordinated Universal Time + (UTC) that the classifier was most recently updated. The field matches either + `retrained` or `created`. Might not be returned by some requests. """ def __init__(self, classifier_id, name, + *, owner=None, status=None, core_ml_enabled=None, @@ -1017,22 +1064,23 @@ def __init__(self, :param str classifier_id: ID of a classifier identified in the image. :param str name: Name of the classifier. - :param str owner: (optional) Unique ID of the account who owns the classifier. - Might not be returned by some requests. + :param str owner: (optional) Unique ID of the account who owns the + classifier. Might not be returned by some requests. :param str status: (optional) Training status of classifier. - :param bool core_ml_enabled: (optional) Whether the classifier can be downloaded - as a Core ML model after the training status is `ready`. - :param str explanation: (optional) If classifier training has failed, this field - might explain why. - :param datetime created: (optional) Date and time in Coordinated Universal Time - (UTC) that the classifier was created. + :param bool core_ml_enabled: (optional) Whether the classifier can be + downloaded as a Core ML model after the training status is `ready`. + :param str explanation: (optional) If classifier training has failed, this + field might explain why. + :param datetime created: (optional) Date and time in Coordinated Universal + Time (UTC) that the classifier was created. :param list[Class] classes: (optional) Classes that define a classifier. - :param datetime retrained: (optional) Date and time in Coordinated Universal Time - (UTC) that the classifier was updated. Might not be returned by some requests. - Identical to `updated` and retained for backward compatibility. - :param datetime updated: (optional) Date and time in Coordinated Universal Time - (UTC) that the classifier was most recently updated. The field matches either - `retrained` or `created`. Might not be returned by some requests. + :param datetime retrained: (optional) Date and time in Coordinated + Universal Time (UTC) that the classifier was updated. Might not be returned + by some requests. Identical to `updated` and retained for backward + compatibility. + :param datetime updated: (optional) Date and time in Coordinated Universal + Time (UTC) that the classifier was most recently updated. The field matches + either `retrained` or `created`. Might not be returned by some requests. """ self.classifier_id = classifier_id self.name = name @@ -1129,6 +1177,15 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + Training status of classifier. + """ + READY = "ready" + TRAINING = "training" + RETRAINING = "retraining" + FAILED = "failed" + class ClassifierResult(object): """ @@ -1272,22 +1329,22 @@ class DetectedFaces(object): :attr int images_processed: Number of images processed for the API call. :attr list[ImageWithFaces] images: The images. - :attr list[WarningInfo] warnings: (optional) Information about what might cause less - than optimal output. For example, a request sent with a corrupt .zip file and a list - of image URLs will still complete, but does not return the expected output. Not - returned when there is no warning. + :attr list[WarningInfo] warnings: (optional) Information about what might cause + less than optimal output. For example, a request sent with a corrupt .zip file + and a list of image URLs will still complete, but does not return the expected + output. Not returned when there is no warning. """ - def __init__(self, images_processed, images, warnings=None): + def __init__(self, images_processed, images, *, warnings=None): """ Initialize a DetectedFaces object. :param int images_processed: Number of images processed for the API call. :param list[ImageWithFaces] images: The images. - :param list[WarningInfo] warnings: (optional) Information about what might cause - less than optimal output. For example, a request sent with a corrupt .zip file and - a list of image URLs will still complete, but does not return the expected output. - Not returned when there is no warning. + :param list[WarningInfo] warnings: (optional) Information about what might + cause less than optimal output. For example, a request sent with a corrupt + .zip file and a list of image URLs will still complete, but does not return + the expected output. Not returned when there is no warning. """ self.images_processed = images_processed self.images = images @@ -1356,8 +1413,8 @@ class ErrorInfo(object): large. Not returned when there is no error. :attr int code: HTTP status code. - :attr str description: Human-readable error description. For example, `File size limit - exceeded`. + :attr str description: Human-readable error description. For example, `File size + limit exceeded`. :attr str error_id: Codified error string. For example, `limit_exceeded`. """ @@ -1366,8 +1423,8 @@ def __init__(self, code, description, error_id): Initialize a ErrorInfo object. :param int code: HTTP status code. - :param str description: Human-readable error description. For example, `File size - limit exceeded`. + :param str description: Human-readable error description. For example, + `File size limit exceeded`. :param str error_id: Codified error string. For example, `limit_exceeded`. """ self.code = code @@ -1434,18 +1491,19 @@ class Face(object): :attr FaceAge age: (optional) Age information about a face. :attr FaceGender gender: (optional) Information about the gender of the face. - :attr FaceLocation face_location: (optional) The location of the bounding box around - the face. + :attr FaceLocation face_location: (optional) The location of the bounding box + around the face. """ - def __init__(self, age=None, gender=None, face_location=None): + def __init__(self, *, age=None, gender=None, face_location=None): """ Initialize a Face object. :param FaceAge age: (optional) Age information about a face. - :param FaceGender gender: (optional) Information about the gender of the face. - :param FaceLocation face_location: (optional) The location of the bounding box - around the face. + :param FaceGender gender: (optional) Information about the gender of the + face. + :param FaceLocation face_location: (optional) The location of the bounding + box around the face. """ self.age = age self.gender = gender @@ -1502,16 +1560,16 @@ class FaceAge(object): :attr int min: (optional) Estimated minimum age. :attr int max: (optional) Estimated maximum age. - :attr float score: Confidence score in the range of 0 to 1. A higher score indicates - greater confidence in the estimated value for the property. + :attr float score: Confidence score in the range of 0 to 1. A higher score + indicates greater confidence in the estimated value for the property. """ - def __init__(self, score, min=None, max=None): + def __init__(self, score, *, min=None, max=None): """ Initialize a FaceAge object. :param float score: Confidence score in the range of 0 to 1. A higher score - indicates greater confidence in the estimated value for the property. + indicates greater confidence in the estimated value for the property. :param int min: (optional) Estimated minimum age. :param int max: (optional) Estimated maximum age. """ @@ -1570,22 +1628,24 @@ class FaceGender(object): """ Information about the gender of the face. - :attr str gender: Gender identified by the face. For example, `MALE` or `FEMALE`. - :attr str gender_label: The word for "male" or "female" in the language defined by the - **Accept-Language** request header. - :attr float score: Confidence score in the range of 0 to 1. A higher score indicates - greater confidence in the estimated value for the property. + :attr str gender: Gender identified by the face. For example, `MALE` or + `FEMALE`. + :attr str gender_label: The word for "male" or "female" in the language defined + by the **Accept-Language** request header. + :attr float score: Confidence score in the range of 0 to 1. A higher score + indicates greater confidence in the estimated value for the property. """ def __init__(self, gender, gender_label, score): """ Initialize a FaceGender object. - :param str gender: Gender identified by the face. For example, `MALE` or `FEMALE`. - :param str gender_label: The word for "male" or "female" in the language defined - by the **Accept-Language** request header. + :param str gender: Gender identified by the face. For example, `MALE` or + `FEMALE`. + :param str gender_label: The word for "male" or "female" in the language + defined by the **Accept-Language** request header. :param float score: Confidence score in the range of 0 to 1. A higher score - indicates greater confidence in the estimated value for the property. + indicates greater confidence in the estimated value for the property. """ self.gender = gender self.gender_label = gender_label @@ -1734,18 +1794,20 @@ class ImageWithFaces(object): Information about faces in the image. :attr list[Face] faces: Faces detected in the images. - :attr str image: (optional) Relative path of the image file if uploaded directly. Not - returned when the image is passed by URL. + :attr str image: (optional) Relative path of the image file if uploaded + directly. Not returned when the image is passed by URL. :attr str source_url: (optional) Source of the image before any redirects. Not - returned when the image is uploaded. - :attr str resolved_url: (optional) Fully resolved URL of the image after redirects are - followed. Not returned when the image is uploaded. - :attr ErrorInfo error: (optional) Information about what might have caused a failure, - such as an image that is too large. Not returned when there is no error. + returned when the image is uploaded. + :attr str resolved_url: (optional) Fully resolved URL of the image after + redirects are followed. Not returned when the image is uploaded. + :attr ErrorInfo error: (optional) Information about what might have caused a + failure, such as an image that is too large. Not returned when there is no + error. """ def __init__(self, faces, + *, image=None, source_url=None, resolved_url=None, @@ -1754,14 +1816,15 @@ def __init__(self, Initialize a ImageWithFaces object. :param list[Face] faces: Faces detected in the images. - :param str image: (optional) Relative path of the image file if uploaded directly. - Not returned when the image is passed by URL. - :param str source_url: (optional) Source of the image before any redirects. Not - returned when the image is uploaded. + :param str image: (optional) Relative path of the image file if uploaded + directly. Not returned when the image is passed by URL. + :param str source_url: (optional) Source of the image before any redirects. + Not returned when the image is uploaded. :param str resolved_url: (optional) Fully resolved URL of the image after - redirects are followed. Not returned when the image is uploaded. - :param ErrorInfo error: (optional) Information about what might have caused a - failure, such as an image that is too large. Not returned when there is no error. + redirects are followed. Not returned when the image is uploaded. + :param ErrorInfo error: (optional) Information about what might have caused + a failure, such as an image that is too large. Not returned when there is + no error. """ self.faces = faces self.image = image From 0b34fa0063f7301f874345d2bb2a0a4cf5652c10 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 10:34:15 -0400 Subject: [PATCH 042/455] test(VR): Update visuall recognition unit tests --- test/unit/test_visual_recognition_v3.py | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index 5452c3717..d56a94b67 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -7,6 +7,7 @@ import time from unittest import TestCase +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator base_url = "https://gateway.watsonplatform.net/visual-recognition/api/" @@ -44,7 +45,8 @@ def setUp(cls): @responses.activate def test_get_classifier(self): - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) gc_url = "{0}{1}".format(base_url, 'v3/classifiers/bogusnumber') @@ -68,7 +70,8 @@ def test_get_classifier(self): @responses.activate def test_delete_classifier(self): - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) gc_url = "{0}{1}".format(base_url, 'v3/classifiers/bogusnumber') @@ -83,7 +86,8 @@ def test_delete_classifier(self): @responses.activate def test_list_classifiers(self): - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) gc_url = "{0}{1}".format(base_url, 'v3/classifiers') @@ -111,7 +115,8 @@ def test_list_classifiers(self): @responses.activate def test_create_classifier(self): - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) gc_url = "{0}{1}".format(base_url, 'v3/classifiers') @@ -138,7 +143,8 @@ def test_create_classifier(self): @responses.activate def test_update_classifier(self): - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) gc_url = "{0}{1}".format(base_url, 'v3/classifiers/bogusid') @@ -166,7 +172,8 @@ def test_update_classifier(self): @responses.activate def test_classify(self): - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) gc_url = "{0}{1}".format(base_url, 'v3/classify') @@ -212,7 +219,8 @@ def test_classify(self): @responses.activate def test_detect_faces(self): - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) gc_url = "{0}{1}".format(base_url, 'v3/detect_faces') @@ -277,7 +285,8 @@ def test_delete_user_data(self): status=204, content_type='application_json') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', iam_apikey='bogusapikey') + authenticator = IAMAuthenticator('bogusapikey') + vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) response = vr_service.delete_user_data('id').get_result() assert response is None assert len(responses.calls) == 2 From 9ce08fd17c6d72791c08fb18f87755a4a702764a Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 11:27:31 -0400 Subject: [PATCH 043/455] examples(vr): Update visual recognition examples --- examples/visual_recognition_v3.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/examples/visual_recognition_v3.py b/examples/visual_recognition_v3.py index f33ea577a..99500ceb7 100644 --- a/examples/visual_recognition_v3.py +++ b/examples/visual_recognition_v3.py @@ -2,7 +2,9 @@ import json from os.path import abspath from ibm_watson import VisualRecognitionV3, ApiException +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +authenticator = IAMAuthenticator('your_apikey') test_url = 'https://www.ibm.com/ibm/ginni/images' \ '/ginni_bio_780x981_v4_03162016.jpg' @@ -11,7 +13,7 @@ '2018-03-19', ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/visual-recognition/api', - iam_apikey='YOUR APIKEY') + authenticator=authenticator) # with open(abspath('resources/cars.zip'), 'rb') as cars, \ # open(abspath('resources/trucks.zip'), 'rb') as trucks: From 77649cb19b829dfb657122327719fed0c294f2d5 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 12:36:43 -0400 Subject: [PATCH 044/455] chore(print): remove future import statements --- .../tone_assistant_integration.v1.py | 1 - examples/assistant_v1.py | 1 - examples/assistant_v2.py | 1 - examples/compare_comply_v1.py | 1 - examples/language_translator_v3.py | 1 - examples/microphone-speech-to-text.py | 1 - examples/speaker_text_to_speech.py | 1 - examples/text_to_speech_v1.py | 1 - examples/tone_analyzer_v3.py | 1 - examples/visual_recognition_v3.py | 1 - setup.py | 1 - test/integration/__init__.py | 1 - test/integration/test_examples.py | 1 - test/integration/test_speech_to_text_v1.py | 1 - test/unit/__init__.py | 1 - 15 files changed, 15 deletions(-) diff --git a/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py b/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py index b708da4e1..16baa6781 100644 --- a/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py +++ b/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py @@ -1,4 +1,3 @@ -from __future__ import print_function import json import os from dotenv import load_dotenv, find_dotenv diff --git a/examples/assistant_v1.py b/examples/assistant_v1.py index d06361a78..0aec96ccd 100644 --- a/examples/assistant_v1.py +++ b/examples/assistant_v1.py @@ -1,4 +1,3 @@ -from __future__ import print_function import json from ibm_watson import AssistantV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator diff --git a/examples/assistant_v2.py b/examples/assistant_v2.py index 5622fdc7b..92bd4aea2 100644 --- a/examples/assistant_v2.py +++ b/examples/assistant_v2.py @@ -1,4 +1,3 @@ -from __future__ import print_function import json from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator diff --git a/examples/compare_comply_v1.py b/examples/compare_comply_v1.py index e41a70c38..f932ac34c 100644 --- a/examples/compare_comply_v1.py +++ b/examples/compare_comply_v1.py @@ -1,5 +1,4 @@ # coding: utf-8 -from __future__ import print_function import json import os from ibm_watson import CompareComplyV1 diff --git a/examples/language_translator_v3.py b/examples/language_translator_v3.py index 18d0cb49c..fa392ce37 100644 --- a/examples/language_translator_v3.py +++ b/examples/language_translator_v3.py @@ -1,5 +1,4 @@ # coding=utf-8 -from __future__ import print_function import json from ibm_watson import LanguageTranslatorV3 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator diff --git a/examples/microphone-speech-to-text.py b/examples/microphone-speech-to-text.py index 7acc7468a..bab7157f4 100644 --- a/examples/microphone-speech-to-text.py +++ b/examples/microphone-speech-to-text.py @@ -6,7 +6,6 @@ # recordings to the queue, and the websocket client would be sending the # recordings to the speech to text service -from __future__ import print_function import pyaudio from ibm_watson import SpeechToTextV1 from ibm_watson.websocket import RecognizeCallback, AudioSource diff --git a/examples/speaker_text_to_speech.py b/examples/speaker_text_to_speech.py index 0b55c4512..039a260c6 100644 --- a/examples/speaker_text_to_speech.py +++ b/examples/speaker_text_to_speech.py @@ -5,7 +5,6 @@ # passed in the request. When the service responds with the synthesized # audio, the pyaudio would play it in a blocking mode -from __future__ import print_function from ibm_watson import TextToSpeechV1 from ibm_watson.websocket import SynthesizeCallback import pyaudio diff --git a/examples/text_to_speech_v1.py b/examples/text_to_speech_v1.py index 86ffc0dd8..4c3c6cc1e 100644 --- a/examples/text_to_speech_v1.py +++ b/examples/text_to_speech_v1.py @@ -1,5 +1,4 @@ # coding=utf-8 -from __future__ import print_function import json from os.path import join, dirname from ibm_watson import TextToSpeechV1 diff --git a/examples/tone_analyzer_v3.py b/examples/tone_analyzer_v3.py index 993223a34..c7d36ed6f 100755 --- a/examples/tone_analyzer_v3.py +++ b/examples/tone_analyzer_v3.py @@ -1,4 +1,3 @@ -from __future__ import print_function import json from os.path import join, dirname from ibm_watson import ToneAnalyzerV3 diff --git a/examples/visual_recognition_v3.py b/examples/visual_recognition_v3.py index 99500ceb7..f0efc1677 100644 --- a/examples/visual_recognition_v3.py +++ b/examples/visual_recognition_v3.py @@ -1,4 +1,3 @@ -from __future__ import print_function import json from os.path import abspath from ibm_watson import VisualRecognitionV3, ApiException diff --git a/setup.py b/setup.py index ef4727eda..1a74cc3d8 100644 --- a/setup.py +++ b/setup.py @@ -13,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -from __future__ import print_function from setuptools import setup from setuptools.command.test import test as TestCommand import os diff --git a/test/integration/__init__.py b/test/integration/__init__.py index 161119efe..949039f3b 100644 --- a/test/integration/__init__.py +++ b/test/integration/__init__.py @@ -1,5 +1,4 @@ # coding: utf-8 -from __future__ import print_function from dotenv import load_dotenv, find_dotenv # load the .env file containing your environment variables for the required diff --git a/test/integration/test_examples.py b/test/integration/test_examples.py index 9e5e7d634..5d087ca06 100644 --- a/test/integration/test_examples.py +++ b/test/integration/test_examples.py @@ -1,6 +1,5 @@ # coding=utf-8 -from __future__ import print_function import re import traceback import pytest diff --git a/test/integration/test_speech_to_text_v1.py b/test/integration/test_speech_to_text_v1.py index 5dd4e5dfc..cfd4f5298 100644 --- a/test/integration/test_speech_to_text_v1.py +++ b/test/integration/test_speech_to_text_v1.py @@ -1,4 +1,3 @@ -from __future__ import print_function from unittest import TestCase import os from ibm_watson.websocket import RecognizeCallback, AudioSource diff --git a/test/unit/__init__.py b/test/unit/__init__.py index 161119efe..949039f3b 100644 --- a/test/unit/__init__.py +++ b/test/unit/__init__.py @@ -1,5 +1,4 @@ # coding: utf-8 -from __future__ import print_function from dotenv import load_dotenv, find_dotenv # load the .env file containing your environment variables for the required From ca6a1d51fca88b99ee4d406785201aecb4d5a760 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 12:45:54 -0400 Subject: [PATCH 045/455] examples(Assistant/TA): Update assistant and TA examples --- .../tone_assistant_integration.v1.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py b/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py index 16baa6781..1e4695c40 100644 --- a/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py +++ b/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py @@ -4,6 +4,7 @@ from ibm_watson import AssistantV1 from ibm_watson import ToneAnalyzerV3 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator # import tone detection import tone_detection @@ -13,14 +14,16 @@ load_dotenv(find_dotenv()) # replace with your own assistant credentials or put them in a .env file +assistant_authenticator = IAMAuthenticator(os.environ.get('ASSISTANT_APIKEY') or 'YOUR ASSISTANT APIKEY') assistant = AssistantV1( - iam_apikey=os.environ.get('ASSISTANT_APIKEY') or 'YOUR ASSISTANT APIKEY', - version='2018-07-10') + version='2018-07-10', + authenticator=assistant_authenticator) # replace with your own tone analyzer credentials +tone_analyzer_authenticator = IAMAuthenticator(os.environ.get('TONE_ANALYZER_APIKEY') or 'YOUR TONE ANALYZER APIKEY') tone_analyzer = ToneAnalyzerV3( - iam_apikey=os.environ.get('TONE_ANALYZER_APIKEY') or 'YOUR TONE ANALYZER APIKEY', - version='2016-05-19') + version='2016-05-19', + authenticator=tone_analyzer_authenticator) # replace with your own workspace_id workspace_id = os.environ.get('WORKSPACE_ID') or 'YOUR WORKSPACE ID' From c716a87e6470415b4d4392fd188ab38b8d887573 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 12:58:24 -0400 Subject: [PATCH 046/455] examples(notebook): update python notebooks --- examples/notebooks/assistant_v1.ipynb | 37 ++++++++++++------- .../natural_language_understanding_v1.ipynb | 29 +++++++++------ 2 files changed, 42 insertions(+), 24 deletions(-) diff --git a/examples/notebooks/assistant_v1.ipynb b/examples/notebooks/assistant_v1.ipynb index 8497e6787..54a1b22e7 100644 --- a/examples/notebooks/assistant_v1.ipynb +++ b/examples/notebooks/assistant_v1.ipynb @@ -10,20 +10,25 @@ { "cell_type": "code", "execution_count": 5, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "import json\n", "import sys\n", "import os\n", "sys.path.append(os.path.join(os.getcwd(),'..','..'))\n", - "import ibm_watson" + "import ibm_watson\n", + "from ibm_cloud_sdk_core.authenticators import IAMAuthenticator" ] }, { "cell_type": "code", "execution_count": 6, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "API_KEY = os.environ.get('ASSISTANT_APIKEY','')" @@ -32,11 +37,13 @@ { "cell_type": "code", "execution_count": 7, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ - "assistant = ibm_watson.AssistantV1(iam_apikey=API_KEY,\n", - " version='2018-07-10')" + "authenticator = IAMAuthenticator(API_KEY)\n", + "assistant = ibm_watson.AssistantV1(version='2018-07-10', authenticator=authenticator)" ] }, { @@ -1026,7 +1033,9 @@ { "cell_type": "code", "execution_count": 37, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "values = [{\"value\": \"juice\"}]" @@ -1767,28 +1776,30 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { - "display_name": "Python 2", + "display_name": "Python 3", "language": "python", - "name": "python2" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.10" + "pygments_lexer": "ipython3", + "version": "3.6.3" } }, "nbformat": 4, diff --git a/examples/notebooks/natural_language_understanding_v1.ipynb b/examples/notebooks/natural_language_understanding_v1.ipynb index 5a4ce07ac..98d4445fa 100644 --- a/examples/notebooks/natural_language_understanding_v1.ipynb +++ b/examples/notebooks/natural_language_understanding_v1.ipynb @@ -3,24 +3,29 @@ { "cell_type": "code", "execution_count": 1, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ "import sys\n", "import os\n", "sys.path.append(os.path.join(os.getcwd(),'..'))\n", "import ibm_watson\n", - "from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions" + "from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions\n", + "from ibm_cloud_sdk_core.authenticators import IAMAuthenticator" ] }, { "cell_type": "code", "execution_count": 2, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [ - "nlu = ibm_watson.NaturalLanguageUnderstandingV1(version='2018-03-16',\n", - " iam_apikey='YOUR API KEY')" + "authenticator = IAMAuthenticator('YOUR API KEY')\n", + "nlu = ibm_watson.NaturalLanguageUnderstandingV1(version='2018-03-16', authenticator=authenticator)" ] }, { @@ -75,28 +80,30 @@ { "cell_type": "code", "execution_count": null, - "metadata": {}, + "metadata": { + "collapsed": true + }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { - "display_name": "Python with Pixiedust (Spark 2.2)", + "display_name": "Python 3", "language": "python", - "name": "pythonwithpixiedustspark22" + "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", - "version": 2 + "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", - "pygments_lexer": "ipython2", - "version": "2.7.10" + "pygments_lexer": "ipython3", + "version": "3.6.3" } }, "nbformat": 4, From 013c5875d0b4a31cc3c9b31c1ae265a0e94a37b2 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 12:59:55 -0400 Subject: [PATCH 047/455] test(travis): remove python2.7 from travis --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d3235e10b..0110dc95c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: python matrix: include: - - python: 2.7 - python: 3.5 - python: 3.6 - python: 3.7 From 8f2ee0079141d6e6bd7d66f730981b85aba45e03 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 14:51:44 -0400 Subject: [PATCH 048/455] example(stt): Update microphone example --- examples/microphone-speech-to-text.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/microphone-speech-to-text.py b/examples/microphone-speech-to-text.py index bab7157f4..2a9a72601 100644 --- a/examples/microphone-speech-to-text.py +++ b/examples/microphone-speech-to-text.py @@ -10,6 +10,7 @@ from ibm_watson import SpeechToTextV1 from ibm_watson.websocket import RecognizeCallback, AudioSource from threading import Thread +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator try: from Queue import Queue, Full @@ -34,9 +35,10 @@ ############################################### # initialize speech to text service +authenticator = IAMAuthenticator('your_api_key') speech_to_text = SpeechToTextV1( - iam_apikey='{YOUR_IAM_API_KEY}', - url='{YOUR_GATEWAY_URL}') + url='{YOUR_GATEWAY_URL}', + authenticator=authenticator) # define callback for the speech to text service class MyRecognizeCallback(RecognizeCallback): From 5136c07cdbef128bbc65ccdc2a70885eeedc0fb5 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 14:51:58 -0400 Subject: [PATCH 049/455] test(discovery): Update discovery test --- test/integration/test_discovery_v1.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/test/integration/test_discovery_v1.py b/test/integration/test_discovery_v1.py index f48ad353f..e234e815a 100644 --- a/test/integration/test_discovery_v1.py +++ b/test/integration/test_discovery_v1.py @@ -41,9 +41,6 @@ def test_environments(self): def test_configurations(self): configs = self.discovery.list_configurations(self.environment_id).get_result() - - self.discovery.delete_configuration(self.environment_id,'26506c92-31db-411c-87b3-68b987781f4a') - self.discovery.delete_configuration(self.environment_id,'bfb6230c-3b4c-4b9f-82bd-237fabb78124') assert configs is not None name = 'test' + random.choice('ABCDEFGHIJKLMNOPQ') From e584db314c2de7cd5dab6621b9c85875beaa2159 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 14:54:00 -0400 Subject: [PATCH 050/455] doc(readme): Update readme with new auth changes --- README.md | 169 ++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 108 insertions(+), 61 deletions(-) diff --git a/README.md b/README.md index 9b47efff2..335905c9a 100755 --- a/README.md +++ b/README.md @@ -18,10 +18,12 @@ Python client library to quickly get started with the various [Watson APIs][wdc] * [Getting credentials](#getting-credentials) * [IAM](#iam) * [Username and password](#username-and-password) + * [No Authentication](#no-authentication) * [Python version](#python-version) * [Changes for v1.0](#changes-for-v10) * [Changes for v2.0](#changes-for-v20) * [Changes for v3.0](#changes-for-v30) + * [Changes for v4.0](#changes-for-v40) * [Migration](#migration) * [Configuring the http client](#configuring-the-http-client-supported-from-v110) * [Disable SSL certificate verification](#disable-ssl-certificate-verification) @@ -103,9 +105,9 @@ On this page, you should be able to see your credentials for accessing your serv ### Supplying credentials -There are two ways to supply the credentials you found above to the SDK for authentication. +There are three ways to supply the credentials you found above to the SDK for authentication. -#### Credential file (easier!) +#### Credential file With a credential file, you just need to put the file in the right place and the SDK will do the work of parsing and authenticating. You can get this file by clicking the **Download** button for the credentials in the **Manage** tab of your service instance. @@ -132,6 +134,21 @@ export IBM_CREDENTIALS_FILE="" where `` is something like `/home/user/Downloads/.env`. +#### Environment Variables +Simply set the environment variables using _ syntax. For example, using your favourite terminal, you can set environment variables for Assistant service instance: + +```bash +export assistant_apikey="" +export assistant_auth_type="iam" +``` + +The credentials will be loaded from the environment automatically + +```python +assistant = AssistantV1(version='2018-08-01') +``` + + #### Manually If you'd prefer to set authentication values manually in your code, the SDK supports that as well. The way you'll do this depends on what type of credentials your service instance gives you. @@ -139,65 +156,67 @@ If you'd prefer to set authentication values manually in your code, the SDK supp IBM Cloud has migrated to token-based Identity and Access Management (IAM) authentication. IAM authentication uses a service API key to get an access token that is passed with the call. Access tokens are valid for approximately one hour and must be regenerated. -You supply either an IAM service **API key** or an **access token**: +You supply either an IAM service **API key** or a **bearer token**: - Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary. - Use the access token if you want to manage the lifecycle yourself. For details, see [Authenticating with IAM tokens](https://cloud.ibm.com/docs/services/watson?topic=watson-iam). - Use a server-side to generate access tokens using your IAM API key for untrusted environments like client-side scripts. The generated access tokens will be valid for one hour and can be refreshed. -### Generating access tokens using IAM API key +#### Supplying the API key ```python -# In your API endpoint use this to generate new access tokens -iam_token_manager = IAMTokenManager(iam_apikey='') -token = iam_token_manager.get_token() -``` - -#### Supplying the IAM API key +from ibm_watson import DiscoveryV1 +import from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -```python -# In the constructor, letting the SDK manage the IAM token +# In the constructor, letting the SDK manage the token +authenticator = IAMAuthenticator('apikey', + url='') # optional - the default value is https://iam.cloud.ibm.com/identity/token discovery = DiscoveryV1(version='2018-08-01', url='', - apikey='', - iam_url='') # optional - the default value is https://iam.cloud.ibm.com/identity/token + authenticator=authenticator) ``` +#### Generating access tokens using API key ```python -# after instantiation, letting the SDK manage the IAM token -discovery = DiscoveryV1(version='2018-08-01', url='') -discovery.set_apikey('') +from ibm_watson import IAMTokenManager + +# In your API endpoint use this to generate new access tokens +iam_token_manager = IAMTokenManager(apikey='') +token = iam_token_manager.get_token() ``` -#### Supplying the access token +##### Supplying the bearer token ```python -# in the constructor, assuming control of managing IAM token +from ibm_watson import DiscoveryV1 +from ibm_cloud_sdk_core.authenticators import BearerAuthenticator + +# in the constructor, assuming control of managing the token +authenticator = BearerAuthenticator('your bearer token') discovery = DiscoveryV1(version='2018-08-01', url='', - iam_access_token='') -``` - -```python -# after instantiation, assuming control of managing IAM token -discovery = DiscoveryV1(version='2018-08-01', url='') -discovery.set_iam_access_token('') + authenticator=authenticator) ``` ### Username and password ```python from ibm_watson import DiscoveryV1 -# In the constructor -discovery = DiscoveryV1(version='2018-08-01', url='', username='', password='') +from ibm_cloud_sdk_core.authenticators import BasicAuthenticator + +authenticator = BasicAuthenticator('username', 'password') +discovery = DiscoveryV1(version='2018-08-01', url='', authenticator=authenticator) ``` +### No Authentication ```python -# After instantiation -discovery = DiscoveryV1(version='2018-08-01', url='') -discovery.set_username_and_password('', '') +from ibm_watson import DiscoveryV1 +from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator + +authenticator = NoAuthAuthenticator() +discovery = DiscoveryV1(version='2018-08-01', url='', authenticator=authenticator) ``` ## Python version -Tested on Python 2.7, 3.5, 3.6, and 3.7. +Tested on Python 3.5, 3.6, and 3.7. ## Changes for v1.0 Version 1.0 focuses on the move to programmatically-generated code for many of the services. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. @@ -225,6 +244,21 @@ The SDK is generated using OpenAPI Specification(OAS3). Changes are basic reorde The package is renamed to ibm_watson. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. +## Changes for v4.0 +Authenticator variable indicates the type of authentication to be used. + +```python +from ibm_watson import AssistantV1 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator + +authenticator = IAMAuthenticator('your apikey') +assistant = AssistantV1( + version='2018-07-10', + ## url is optional, and defaults to the URL below. Use the correct URL for your region. + url='https://gateway.watsonplatform.net/assistant/api', + authenticator=authenticator) +``` + ## Migration This version includes many breaking changes as a result of standardizing behavior across the new generated services. Full details on migration from previous versions can be found [here](https://github.com/watson-developer-cloud/python-sdk/wiki/Migration). @@ -233,12 +267,14 @@ To set client configs like timeout use the `with_http_config()` function and pas ```python from ibm_watson import AssistantV1 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +authenticator = IAMAuthenticator('your apikey') assistant = AssistantV1( - username='xxx', - password='yyy', - url='', - version='2018-07-10') + version='2018-07-10', + ## url is optional, and defaults to the URL below. Use the correct URL for your region. + url='https://gateway.watsonplatform.net/assistant/api', + authenticator=authenticator) assistant.set_http_config({'timeout': 100}) response = assistant.message(workspace_id=workspace_id, input={ @@ -250,7 +286,7 @@ print(json.dumps(response, indent=2)) For ICP(IBM Cloud Private), you can disable the SSL certificate verification by: ```python -service.disable_SSL_verification() +service.set_disable_ssl_verification() ``` ## Sending request headers @@ -264,12 +300,14 @@ For example, to send a header called `Custom-Header` to a call in Watson Assista the headers parameter as: ```python from ibm_watson import AssistantV1 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +authenticator = IAMAuthenticator('your apikey') assistant = AssistantV1( - username='xxx', - password='yyy', - url='', - version='2018-07-10') + version='2018-07-10', + ## url is optional, and defaults to the URL below. Use the correct URL for your region. + url='https://gateway.watsonplatform.net/assistant/api', + authenticator=authenticator) response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() ``` @@ -278,12 +316,14 @@ response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}). If you would like access to some HTTP response information along with the response model, you can set the `set_detailed_response()` to `True`. Since Python SDK `v2.0`, it is set to `True` ```python from ibm_watson import AssistantV1 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +authenticator = IAMAuthenticator('your apikey') assistant = AssistantV1( - username='xxx', - password='yyy', - url='', - version='2018-07-10') + version='2018-07-10', + ## url is optional, and defaults to the URL below. Use the correct URL for your region. + url='https://gateway.watsonplatform.net/assistant/api', + authenticator=authenticator) assistant.set_detailed_response(True) response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() @@ -324,31 +364,38 @@ service.synthesize_using_websocket('I like to pet dogs', ) ``` -## IBM Cloud Pak for Data(ICP4D) -If your service instance is of ICP4D, below are two ways of initializing the assistant service. +## Cloud Pak for Data(CP4D) +If your service instance is of CP4D, below are two ways of initializing the assistant service. -### 1) Supplying the username, password, icp4d_url and authentication_type +### 1) Supplying the username, password and authentication url The SDK will manage the token for the user ```python +from ibm_watson import AssistantV1 +from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator + +authenticator = CloudPakForDataAuthenticator( + '', + '', + '') # should be of the form https://{icp_cluster_host}{instance-id}/api + assistant = AssistantV1( - version='', + url='service url', # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api + authenticator=authenticator, + disable_ssl_verification=True) # MAKE SURE SSL VERIFICATION IS DISABLED ``` ## Dependencies @@ -358,7 +405,7 @@ assistant.disable_SSL_verification() # MAKE SURE SSL VERIFICATION IS DISABLED * [responses] for testing * Following for web sockets support in speech to text * `websocket-client` 0.48.0 -* `ibm_cloud_sdk_core` >=0.5.1 +* `ibm_cloud_sdk_core` >=0.6.0 ## Contributing From 8a7294d119a498dce08e56d953433969bcb3329e Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 29 Aug 2019 14:57:42 -0400 Subject: [PATCH 051/455] test(travis): Update travis file --- .env.enc | Bin 2752 -> 2736 bytes .travis.yml | 10 +++++----- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.env.enc b/.env.enc index ad9be380f175bbb9b1346d0a304f292801583896..9611625769cd74d646ce711f952807cb53a003a1 100644 GIT binary patch literal 2736 zcmV;h3QzSo-W(gK^u@L65L6-;^Hk#{ZU%t(zAoP>LwrLU^=6r2dX=g836j3J3J~tG zB$)^75(;ji_5QI&xx#TF^w^>Y8^7fAVi!7N01pz(wrq4>&U@!s5Je@lV~ov>qDR@t z!brqXn?J+7|GboE4rCTcFNhBmRADBpx@P$~xCqml>wge+pC)m1nhp!@N4SQh6f@r< zv01Qb^M3%WfHLp+rJLusL_29b7%L{YkFOO~F0Dn=d!(;@qJb8#CUua4m3nX~JuPKP zB9b$CLbSzB7{E9D^oe#?yrjxYMWjA!_mcYJ21hj6p#*EQNg+R%fx(O)l6Cx1j^`AX zT!jktS~4)CJ~>2E(2}wqye4hlOu{|5Ax@NvOt)l!(DX$Y^20ppk&_PDMyv5(#Omya z@${7$tc?CP(hiU!QWk@j5EaQz@=`;ZnEN5?p2`N&O`W8|((g(+vG?f^OT#R24NCyEb~8aU2CAk1*42eGgA1QX00h=4eu zSZ$}{0m{aiqU>pjRV@3t8op1!Q{uuTLyq}9z73ZN2F2G(?9VKKy-#5|5rM^C1>S%j zGAv%ddAHXw8CrqhH^7tWU@mH~Kp&j7wQ^th7I6+FkCj?h%$67+lYCe;a|_=R1w0?6 zo93@2Tu%FG^@1COnAdTLctu?JIt*r;;$fj{9Zyu-h8dfg&=VjhnNA<2n9)s@Vt9UP=~kw zaEz)T`aVLN{+o%S;{>_QsMrRAI>#PaSZwE+wZn@im&O!5KZ~s~nATaV^H%N^n*u6m zbyZA5U)~fIOBBY1Cm7G21c7E7zEw_hy)oUXF5}MA;PHqM;6=m!oGMy&%Vi0y@pJt)0YWKn=71k=3on`-C2S#x65LGh$uPyM-qOQmT(2dL#}rZa0@ z7ERI*x(>|1)GMB?)#R(=^Wjk7bBp`X0!4f|~NX&+@wZhq-l zknj7AjmJ#MRf`c~tlfO#N?_oP%kO2jQ2kw>%%}WBeAAjCe(0aNn`IGX{iojMrw_onv#h{gZ26#ufvhxl-N_;8LQu1!4NTE6ITFiv+X3> zNwD4C4W1p*o)u`zj!1<<`?j4fABR-n#nuz5RM`lQIhT4N#JJH{Og3?0fLH&}(1>>Q zJW4F=-hs34tL*QjmzDpaf1&f5=W&s94OfviO)R0~yadmZbRLVaQYXL&5OpWmrQ94l zF}#6}Ul41)nest@f=wmfk9;)re^d;e^DJK z^iVB)82L;jBPE9}A?9fQF{2V>Q&+QdxFnL;K9w{>0ba#&z~Q!Eg%H>KRqM)^n2){zg>)jDIWp*fJ$l zcp*|)gRRjzW_|M2)xkvDqC$$m_5fS&Hi#jq1rB$dDhd>ywJU`^k0Thk?GsK>v%tYs ze&fL;G`$l0IWwrZ9A1xETy9Phvj^mDAgm8ovx%o_YJMdt2+2?Ma?LWi^ox$V5H>UV zbEsEKA}Jxz0p6;1-_rCV16{jT_xBPbSwV$)wBR0p?Hc642sa|#@KWBZ1fJ9lEFE-Z z`So&!2e!vVfK4L<)1p4xwiiS4_^&J;T-nkBk#(D1yvaXCJANfm7qDM$HLc&=SOL~- z?diLI3t44R(j_Ht@9J}+297_5${=X9I?O9m3j9g%D5tb%A%hW}5x=W?H)`(HNxxIq z1zQMGk?-Kkg%dLBnJ0>G$n_+C6?1lNsOL^s#PzQz3S~FK7O+;P`&!E2 zA6r<$WSCTs7<6={mm z_Sm;`J=^1ivUrPU7VmZ4x5)P5MTI(aav|qbe64d$Agf#0(x|ZjNw6|%OlCAx;1({S z=H0oanAuV_Hp~o3SV1ni=mEG#=>t;PzJ5+JaGlKnvcgY50_~d_L3jYJIo<{5jBB)7 zhXH#I)Xr8XUkK4FTfs$-eCI?jpMCj>h?5@+>eKvk3V4*8NsbE|D%LOH1MUZRW5;6! zm?lRDOI#p!(#;m)0+Tt*_Sd?fwG~E^y>^0 z@1fU(P!yh2Hkx;I`Z=`6R2c55u%;FGN_p19SZGr6`- z+@e>gxD;nND!jF%jR+xY^skstSF}%)=qw3uGH9E;wA@`w_=^?v*Yur9kL>EZtU}N_ z&R#|W=eM07CT*#i2Y%e7G|R=7u=TP(%q+!f(o3z2ArcDAbemfC^}}pTbHoUE1yxB^ zhT&oL5(j^>h^U_izMJ$KYsVUCAXKXwgqhTev+zXq+<2YPw^^PAyJV;w)B&2o4oYod zB*tAl{`xoAe(N)-%SYl#Xk4otii~tiGwJBns4(mN^E9DL9m&tdEo@_qOS@;6KRxn! zJYlDHgrMiqu~#l)@Th)*>wN{J3odWXeV`%uq|LC#7@$HR1o?kPb+~BEjP)lu7qhDXE;f?Pign(yM#0|wwLL+O-N_a#pS-kY?C#fZaQ}0m z*e4d*xvq9D9|{&_=ut0#%22wo_jJpogKq=lix>DYe#XAJ&b%OqK06}g*=`I~H~^L{ z9`du@C2P9aNIQX9INaBEGu3CVT>aDuHYRf*dN{m0L1HKsaA1w0gaSwTY_q__R>N*> zA~V2{<<5b;VsB9!oAmYwRsKc0C)lVJ-@)-Ki%t+6D`gghIf(6>7|#OmT?X`qa|+mK zlLYt^$6vdfptf=Db4J=VF(n(`AG?ADe2TEdC;DlYHeVCAGB)Z`c^x=*SJoUkKd-C( zP-xJoLWt$d$62|I+DaGpM|OZX+e`N;9sz$M1_K?)cA_ zY3!WLEK#k4#*M~WBl{5216b**Xlm)Be7Kikqk6XJvjLdWHcJLA1$Co{sQss;`MYGT zmHtoRU&P_9xRPS9#Z68X$E;)}Ut>x2a{`&Qn7!}iYUT|1V=l8&d@KX84Qm~`Dv(Wd zFDnJGSSFgmlZyn9^(OW_`>rEmhW^8i7ez(io3Nu_g2w*BS%SSyJz^cDk^q-5@5#tk z!bV^UP~6LWepCr6Ic_^zs*lT#BP;W~(oSMCP%&9V5?!$eC%TYm=Ol{mCA|ELX|jsY zS8UXVOXT@F?{v)ar{!|#y6@~kK0KG(+gNlvvuvA&uKN*tR96r4-E(z+8tXm7=JiH- z-y;~YSp~LDo?slg`uUmTfdva(n*FHdBC1cam%s(KbgBZXE>I;3J{c{70{ZpqeGp%t z>&?cuQ@wxTYq4NIjMneTH1OKi0t2Y^v7-gH(6(Gz6nLRD6FdXyZfQ4em{B2u&^2+B zv2+(6r3%fIc(3bcoLc>?SezC(gJbix3bpH!T)<`8v!PSwp$kG?---kl)hYjGgKhWO z$?6b?4SK30%ihO7>()oaODq|PN7&nI<=!eyOh<|YXNYrF8GXv z$H=g>Y_3kKi{~7uiwI1DX7fkM{_!4b7urN1SvEih#5X5|kXr(0CI;1nWy1+sp}?;qR z(GDey)4q>1gA7AoR`X;DtuZ^$;z6mTk5e7x)#wS<6*mYX{9Xb3d@(ZpAIfALG%3iI z8IAT&od=Gd<|1s8`W1cl(_l)Kuwz>0c9nN!z|`$J#RP$A{hU^cl&gSO-W9C}%fj~I zaPa#T=M>es7zq`}U^N%w1XB_vgQAM0CxXbyHNqbvy`{ePKbM>`jRQ89w+L14cN;qFt+CNiDRGEU)V`S-xVLp3;%-bPrQcax_IW8K%dqYXMI(L+m5UMg(s>L@ zKFkQx{9+*GH_-M^wJ!ysbHoc77CnT4eW53u1PT)mNdBxwad5U`6fOD{g%T(#J>AN3#)WXgBk8s4MSIf zZ6v}*|9MKQ-2heNwpFjcdnrFd(b92sys$5jZ|N&JR!gGR2u5xRrpDUeRey#qVjcIB z-{X`rRe$x?Wu@JSKv&Fz^HupmfB(A8v)imP2b78EW|s^dXL+vocyW+R`2(hrE=s~@ zeJ|A7?HN19fW2?4i2dQ8^%5A@Zd9c(bo~PTQ|d%kC>A6Bxrk8dgX&RzQNo6I$;Gw2CV5rv2n}-hbbzC{Q;h{2Ib%lGZA}a z*g7T!r*-8-c;0c;koe!75IBrFcU@j!`l+yT)XI_D-EA`&b$=?Z4#2nTJ)`?p4QH#<|i}5n8@d)U*{`n5-#@y8Zkv7LAmJP*=<>w(0A+GKAq>La?;Reo4du_&N+n*~KV^&a%L&ux?N9 zm&oWG>>G;`H&39kQb%XuMpfjggF25=laNK>UurXIH*pCQ7wUYVJ*}VL4IQ?ZEJXpy zx#(P`0M5a5FG_`u=v{9HC1{FIgDAq=p6&0d_C|CPL=OI72Dd?AHFPYgWnYgO&5D3zIHKwA#^M6D85M^hIx0(kGCE#_$8ACut4 zU{X1?vkjsVVyg#h9b>F-kKC{T8IUGI3PU4*{M7W(g4)4=84A=o4-=$0c?=-47fUmQ9C^6$?NakYryZRQyMYDy8U}bcrZ*h4 z4-;GSe0+Ez%l4k0l*q88lyfK?y}B>Lt`enOH*I$Gcq@0?>ZDHkX;zSPKoF;1AChV; zY%&!zm(RkzE#avQ#W2-8FE=kF1Av7?p5yHGBQw-De+IIwRd<{tzfW4AlhxnxeK99@EPyIW^vywRMO#9&FGSY4Yu(1*sk}EJvP*Wqy7s6AN9QN(%k1QEIALj8gu*Lq_~D_@d*ey`iUukbDn`FD$1#?^bK}ANajQq&T3>Vm zkZ)+U5czj`IMk;vm$gQ)jj%?h-tVp zWsr(L*zLO^g@$#+5%?nOswv`Y7-=Gx9ht5ab?1&;s%x}??oa-!rc4H_TUV;7)Z1+X zf#1YNc$A{mLc4PfG;Q#t?HOILcL{`Bc#h*gjb{lb+66 zP6M?>py6=tt0TSCR3TMq!jVtXence)Ph?6!0Wa0-n9o=r3zBj3ZlRL Date: Fri, 30 Aug 2019 10:45:11 -0400 Subject: [PATCH 052/455] fix(core): Update core to use pre-release --- requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 7f218b427..ce4adcf96 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 -ibm_cloud_sdk_core>=0.5.1 \ No newline at end of file +ibm_cloud_sdk_core==1.0.0rc1 \ No newline at end of file From da8a3e16d351514cf46e0b51ddc386b292e26130 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 30 Aug 2019 10:51:28 -0400 Subject: [PATCH 053/455] fix(core): Update core versions --- requirements-dev.txt | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index ec79977bd..9a301299e 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ python_dotenv>=0.1.5;python_version!='3.2' pylint>=1.4.4 tox>=2.9.1 pytest-rerunfailures>=3.1 -ibm_cloud_sdk_core>=0.5.1 +ibm_cloud_sdk_core==1.0.0rc1 # code coverage coverage<5 diff --git a/setup.py b/setup.py index 1a74cc3d8..c955a6b57 100644 --- a/setup.py +++ b/setup.py @@ -63,7 +63,7 @@ def run_tests(self): version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core>=0.5.1'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.0.0rc1'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='IBM Watson', From 7931c02cc19f1a81ea9b946fc91ea7131a1c73c7 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 30 Aug 2019 11:13:17 -0400 Subject: [PATCH 054/455] chore(authorization): remove authorization --- examples/authorization_v1.py | 10 ----- ibm_watson/__init__.py | 1 - ibm_watson/authorization_v1.py | 63 ------------------------------ test/integration/test_examples.py | 2 +- test/unit/test_authorization_v1.py | 16 -------- 5 files changed, 1 insertion(+), 91 deletions(-) delete mode 100644 examples/authorization_v1.py delete mode 100644 ibm_watson/authorization_v1.py delete mode 100644 test/unit/test_authorization_v1.py diff --git a/examples/authorization_v1.py b/examples/authorization_v1.py deleted file mode 100644 index 8cef2af3c..000000000 --- a/examples/authorization_v1.py +++ /dev/null @@ -1,10 +0,0 @@ -import json -from ibm_watson import AuthorizationV1 -from ibm_watson import SpeechToTextV1 - -authorization = AuthorizationV1( - username='YOUR SERVICE USERNAME', password='YOUR SERVICE PASSWORD') - -print( - json.dumps( - authorization.get_token(url=SpeechToTextV1.default_url), indent=2)) diff --git a/ibm_watson/__init__.py b/ibm_watson/__init__.py index 10dff2368..56d7b7d29 100755 --- a/ibm_watson/__init__.py +++ b/ibm_watson/__init__.py @@ -15,7 +15,6 @@ from ibm_cloud_sdk_core import IAMTokenManager, DetailedResponse, BaseService, ApiException -from .authorization_v1 import AuthorizationV1 from .assistant_v1 import AssistantV1 from .assistant_v2 import AssistantV2 from .language_translator_v3 import LanguageTranslatorV3 diff --git a/ibm_watson/authorization_v1.py b/ibm_watson/authorization_v1.py deleted file mode 100644 index ea119dbf8..000000000 --- a/ibm_watson/authorization_v1.py +++ /dev/null @@ -1,63 +0,0 @@ -# coding: utf-8 -# Copyright 2016 IBM All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" -The v1 Authorization "service" that enables developers to -retrieve a temporary access token -""" - -from ibm_cloud_sdk_core import BaseService - -try: - import urllib.parse as urlparse # Python 3 -except ImportError: - import urlparse # Python 2 - - -class AuthorizationV1(BaseService): - """ - Generates tokens, which can be used client-side to avoid exposing the - service credentials. - Tokens are valid for 1 hour and are sent using the - `X-Watson-Authorization-Token` header. - """ - default_url = "https://stream.watsonplatform.net/authorization/api" - - def __init__(self, - url=default_url, - username=None, - password=None, - use_vcap_services=True): - BaseService.__init__( - self, - 'authorization', - url, - username, - password, - use_vcap_services, - display_name='authorization') - - def get_token(self, url): - """ - Retrieves a temporary access token - """ - # A hack to avoid url-encoding the url, since the authorization service - # doesn't work with correctly encoded urls - - parsed_url = urlparse.urlsplit(url) - parsed_url = parsed_url._replace(path='/authorization/api') - self.url = urlparse.urlunsplit(parsed_url) - - response = self.request(method='GET', url='/v1/token?url=' + url) - return response.result.text diff --git a/test/integration/test_examples.py b/test/integration/test_examples.py index 5d087ca06..1ee6c1369 100644 --- a/test/integration/test_examples.py +++ b/test/integration/test_examples.py @@ -9,7 +9,7 @@ from glob import glob # tests to exclude -excludes = ['authorization_v1.py', 'discovery_v1.ipynb', '__init__.py', 'microphone-speech-to-text.py'] +excludes = ['discovery_v1.ipynb', '__init__.py', 'microphone-speech-to-text.py'] # examples path. /examples examples_path = join(dirname(__file__), '../', 'examples', '*.py') diff --git a/test/unit/test_authorization_v1.py b/test/unit/test_authorization_v1.py deleted file mode 100644 index 0b2125c84..000000000 --- a/test/unit/test_authorization_v1.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding: utf-8 -import responses -import ibm_watson - - -@responses.activate -def test_request_token(): - url = 'https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api' - responses.add(responses.GET, - url=url, - body=b'mocked token', - status=200) - authorization = ibm_watson.AuthorizationV1(username='xxx', password='yyy') - authorization.get_token(url=ibm_watson.SpeechToTextV1.default_url) - assert responses.calls[0].request.url == url - assert responses.calls[0].response.content.decode('utf-8') == 'mocked token' From 5f725ebbd905e4eba15dcd64af94e9b7068a6091 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 30 Aug 2019 11:38:42 -0400 Subject: [PATCH 055/455] fix(core): Update to rc2 core --- requirements-dev.txt | 2 +- requirements.txt | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 9a301299e..902036a5e 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ python_dotenv>=0.1.5;python_version!='3.2' pylint>=1.4.4 tox>=2.9.1 pytest-rerunfailures>=3.1 -ibm_cloud_sdk_core==1.0.0rc1 +ibm_cloud_sdk_core==1.0.0rc2 # code coverage coverage<5 diff --git a/requirements.txt b/requirements.txt index ce4adcf96..ad45287d6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 -ibm_cloud_sdk_core==1.0.0rc1 \ No newline at end of file +ibm_cloud_sdk_core==1.0.0rc2 \ No newline at end of file diff --git a/setup.py b/setup.py index c955a6b57..d5ab8e6f7 100644 --- a/setup.py +++ b/setup.py @@ -63,7 +63,7 @@ def run_tests(self): version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.0.0rc1'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.0.0rc2'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='IBM Watson', From 0439a981fa67b028f62cfc9867ae1dc51f6894df Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 30 Aug 2019 12:45:07 -0400 Subject: [PATCH 056/455] chore(core): Update to rc4 core version --- requirements-dev.txt | 2 +- requirements.txt | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 902036a5e..d4f8e56f5 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ python_dotenv>=0.1.5;python_version!='3.2' pylint>=1.4.4 tox>=2.9.1 pytest-rerunfailures>=3.1 -ibm_cloud_sdk_core==1.0.0rc2 +ibm_cloud_sdk_core==1.0.0rc4 # code coverage coverage<5 diff --git a/requirements.txt b/requirements.txt index ad45287d6..3704aa416 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 -ibm_cloud_sdk_core==1.0.0rc2 \ No newline at end of file +ibm_cloud_sdk_core==1.0.0rc4 \ No newline at end of file diff --git a/setup.py b/setup.py index d5ab8e6f7..980427d60 100644 --- a/setup.py +++ b/setup.py @@ -63,7 +63,7 @@ def run_tests(self): version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.0.0rc2'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.0.0rc4'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='IBM Watson', From 62adbe66913403f4da28dc19c802077906d343c9 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 30 Aug 2019 12:50:35 -0400 Subject: [PATCH 057/455] chore(appveyor): remove appveyor 2.7 --- appveyor.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/appveyor.yml b/appveyor.yml index 7d324ea93..17727297f 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -3,7 +3,6 @@ environment: matrix: - PYTHON: "C:\\Python35" - - PYTHON: "C:\\Python27-x64" - PYTHON: "C:\\Python36-x64" install: From 91769c254a13e3d8983f1a19bf717db63749308e Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 30 Aug 2019 13:14:47 -0400 Subject: [PATCH 058/455] test(vr): temporary disable some vr test as they are time consuming --- test/integration/test_visual_recognition.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/integration/test_visual_recognition.py b/test/integration/test_visual_recognition.py index 152ec9d24..59b3b3890 100644 --- a/test/integration/test_visual_recognition.py +++ b/test/integration/test_visual_recognition.py @@ -31,6 +31,7 @@ def test_classify(self): classifier_ids=['default']).get_result() assert dog_results is not None + @pytest.mark.skip(reason="temporray disable") def test_detect_faces(self): output = self.visual_recognition.detect_faces( url='https://www.ibm.com/ibm/ginni/images/ginni_bio_780x981_v4_03162016.jpg').get_result() @@ -54,6 +55,7 @@ def test_custom_classifier(self): output = self.visual_recognition.delete_classifier(classifier_id).get_result() + @pytest.mark.skip(reason="temporray disable") def test_core_ml_model(self): core_ml_model = self.visual_recognition.get_core_ml_model(self.classifier_id).get_result() assert core_ml_model.ok From 8c770116ba06bc61e2bc3d2edcadc65b61f31166 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 30 Aug 2019 14:40:41 -0400 Subject: [PATCH 059/455] chore(review): Update as per review comments --- README.md | 2 +- examples/assistant_v1.py | 2 +- test/integration/test_visual_recognition.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 335905c9a..62a17f90e 100755 --- a/README.md +++ b/README.md @@ -405,7 +405,7 @@ assistant = AssistantV1(version='', * [responses] for testing * Following for web sockets support in speech to text * `websocket-client` 0.48.0 -* `ibm_cloud_sdk_core` >=0.6.0 +* `ibm_cloud_sdk_core` >= 1.0.0rc4 ## Contributing diff --git a/examples/assistant_v1.py b/examples/assistant_v1.py index 0aec96ccd..71d9b610c 100644 --- a/examples/assistant_v1.py +++ b/examples/assistant_v1.py @@ -15,7 +15,7 @@ create_workspace_data = { "name": - "test_workspace 3", + "test_workspace", "description": "integration tests", "language": diff --git a/test/integration/test_visual_recognition.py b/test/integration/test_visual_recognition.py index 59b3b3890..f08baa85c 100644 --- a/test/integration/test_visual_recognition.py +++ b/test/integration/test_visual_recognition.py @@ -31,7 +31,7 @@ def test_classify(self): classifier_ids=['default']).get_result() assert dog_results is not None - @pytest.mark.skip(reason="temporray disable") + @pytest.mark.skip(reason="temporay disable") def test_detect_faces(self): output = self.visual_recognition.detect_faces( url='https://www.ibm.com/ibm/ginni/images/ginni_bio_780x981_v4_03162016.jpg').get_result() @@ -55,7 +55,7 @@ def test_custom_classifier(self): output = self.visual_recognition.delete_classifier(classifier_id).get_result() - @pytest.mark.skip(reason="temporray disable") + @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() assert core_ml_model.ok From 47aa6a98066946013fc981806c2555b1a2ad6180 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 30 Aug 2019 15:09:55 -0400 Subject: [PATCH 060/455] update version --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index a8038f476..b01f0886d 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 3.4.0 +current_version = 4.0.0rc1 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index f63100763..5d65240c3 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '3.4.0' +__version__ = '4.0.0rc1' diff --git a/setup.py b/setup.py index 980427d60..c028b7480 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '3.4.0' +__version__ = '4.0.0rc1' if sys.argv[-1] == 'publish': # test server From 148b5a78d4c516ca33aa80113a95cd39d2ce3ca1 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 4 Sep 2019 16:53:19 -0700 Subject: [PATCH 061/455] feat(logging): Add logging to ws functions --- ibm_watson/websocket/recognize_listener.py | 9 +++++++-- ibm_watson/websocket/synthesize_listener.py | 9 +++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index e1471c0cb..7151688c2 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -18,6 +18,8 @@ import json import time import ssl +import logging +import sys try: import thread except ImportError: @@ -40,7 +42,8 @@ def __init__(self, headers, http_proxy_host=None, http_proxy_port=None, - verify=None): + verify=None, + debug=False): self.audio_source = audio_source self.options = options self.callback = callback @@ -51,7 +54,9 @@ def __init__(self, self.isListening = False self.verify = verify - # websocket.enableTrace(True) + if debug: + logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) + websocket.enableTrace(True) self.ws_client = websocket.WebSocketApp( self.url, diff --git a/ibm_watson/websocket/synthesize_listener.py b/ibm_watson/websocket/synthesize_listener.py index 905e02ba3..c07b3b83d 100644 --- a/ibm_watson/websocket/synthesize_listener.py +++ b/ibm_watson/websocket/synthesize_listener.py @@ -18,6 +18,8 @@ import json import ssl import time +import logging +import sys try: import thread except ImportError: @@ -34,7 +36,8 @@ def __init__(self, headers, http_proxy_host=None, http_proxy_port=None, - verify=None): + verify=None, + debug=False): self.options = options self.callback = callback self.url = url @@ -43,7 +46,9 @@ def __init__(self, self.http_proxy_port = http_proxy_port self.verify = verify - # websocket.enableTrace(True) + if debug: + logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) + websocket.enableTrace(True) self.ws_client = websocket.WebSocketApp( self.url, From f367c4ff8f3a21949719f927a37adbe07bdf1950 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 4 Sep 2019 16:53:36 -0700 Subject: [PATCH 062/455] doc(readme): Update readme with examples --- README.md | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 65 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 62a17f90e..b50ecadcd 100755 --- a/README.md +++ b/README.md @@ -30,7 +30,8 @@ Python client library to quickly get started with the various [Watson APIs][wdc] * [Sending request headers](#sending-request-headers) * [Parsing HTTP response info](#parsing-http-response-info) * [Using Websockets](#using-websockets) - * [IBM Cloud Pak for Data(ICP4D)](#ibm-cloud-pak-for-data(icp4d)) + * [Cloud Pak for Data(CP4D)](#cloud-pak-for-data) + * [Debugging/Logging](#debugging-and-logging) * [Dependencies](#dependencies) * [License](#license) * [Contributing](#contributing) @@ -364,7 +365,7 @@ service.synthesize_using_websocket('I like to pet dogs', ) ``` -## Cloud Pak for Data(CP4D) +## Cloud Pak for Data If your service instance is of CP4D, below are two ways of initializing the assistant service. ### 1) Supplying the username, password and authentication url @@ -398,6 +399,67 @@ assistant = AssistantV1(version='', disable_ssl_verification=True) # MAKE SURE SSL VERIFICATION IS DISABLED ``` +## Debugging and Logging + +### Enable Debugging +To take advantage of the underlying http request printed to stdout, simply enable debugging +```python +my_service.enable_debugging() +``` + +### Enable Debugging +To disable debugging printed to stdout, simply disable debugging +```python +my_service.disable_debugging() +``` + +### Enable logging +We support python's logging capabilities by passing in a config file. As an example, consider the following `logging.conf` file + +``` +[loggers] +keys=root + +[handlers] +keys=fileHandler + +[formatters] +keys=Formatter + +[logger_root] +level=DEBUG +handlers=fileHandler +qualname=main + +[handler_fileHandler] +class=FileHandler +level=DEBUG +formatter=Formatter +args=('app.log', 'w', 'utf8') + +[formatter_Formatter] +format=%(asctime)s - %(levelname)s - %(message)s +datefmt="%Y-%m-%d %H:%M:%S" +``` + +Using this file, enable logging: + +```python +from os import path +log_file_path = path.join(path.dirname(path.abspath(__file__)), 'logging.conf') +my_service.enable_logging(log_file_path) +``` + +### Get logger +Using the logger, configure it as per your needs. As an example: + +```python +logger = my_service.get_logger() +ch = logging.StreamHandler() +ch.setLevel(logging.DEBUG) +logger.addHandler(ch) +``` + ## Dependencies * [requests] @@ -405,7 +467,7 @@ assistant = AssistantV1(version='', * [responses] for testing * Following for web sockets support in speech to text * `websocket-client` 0.48.0 -* `ibm_cloud_sdk_core` >= 1.0.0rc4 +* `ibm_cloud_sdk_core` >= 1.0.0rc5 ## Contributing From 5f40ac229e6214b0b98c528fec0ffa2a504eb42b Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 4 Sep 2019 16:54:45 -0700 Subject: [PATCH 063/455] feat(model): _convert_model doesnt need classname anymore --- ibm_watson/assistant_v1.py | 75 +++++++------------ ibm_watson/assistant_v2.py | 4 +- ibm_watson/compare_comply_v1.py | 2 +- ibm_watson/discovery_v1.py | 55 +++++--------- ibm_watson/natural_language_classifier_v1.py | 2 +- .../natural_language_understanding_v1.py | 2 +- ibm_watson/personality_insights_v3.py | 2 +- ibm_watson/speech_to_text_v1.py | 2 +- ibm_watson/text_to_speech_v1.py | 4 +- ibm_watson/tone_analyzer_v3.py | 32 +++----- 10 files changed, 66 insertions(+), 114 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index dafac2c9a..3fe5fc74a 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -132,15 +132,15 @@ def message(self, if workspace_id is None: raise ValueError('workspace_id must be provided') if input is not None: - input = self._convert_model(input, MessageInput) + input = self._convert_model(input) if intents is not None: - intents = [self._convert_model(x, RuntimeIntent) for x in intents] + intents = [self._convert_model(x) for x in intents] if entities is not None: - entities = [self._convert_model(x, RuntimeEntity) for x in entities] + entities = [self._convert_model(x) for x in entities] if context is not None: - context = self._convert_model(context, Context) + context = self._convert_model(context) if output is not None: - output = self._convert_model(output, OutputData) + output = self._convert_model(output) headers = {} if 'headers' in kwargs: @@ -277,20 +277,15 @@ def create_workspace(self, """ if system_settings is not None: - system_settings = self._convert_model(system_settings, - WorkspaceSystemSettings) + system_settings = self._convert_model(system_settings) if intents is not None: - intents = [self._convert_model(x, CreateIntent) for x in intents] + intents = [self._convert_model(x) for x in intents] if entities is not None: - entities = [self._convert_model(x, CreateEntity) for x in entities] + entities = [self._convert_model(x) for x in entities] if dialog_nodes is not None: - dialog_nodes = [ - self._convert_model(x, DialogNode) for x in dialog_nodes - ] + dialog_nodes = [self._convert_model(x) for x in dialog_nodes] if counterexamples is not None: - counterexamples = [ - self._convert_model(x, Counterexample) for x in counterexamples - ] + counterexamples = [self._convert_model(x) for x in counterexamples] headers = {} if 'headers' in kwargs: @@ -442,20 +437,15 @@ def update_workspace(self, if workspace_id is None: raise ValueError('workspace_id must be provided') if system_settings is not None: - system_settings = self._convert_model(system_settings, - WorkspaceSystemSettings) + system_settings = self._convert_model(system_settings) if intents is not None: - intents = [self._convert_model(x, CreateIntent) for x in intents] + intents = [self._convert_model(x) for x in intents] if entities is not None: - entities = [self._convert_model(x, CreateEntity) for x in entities] + entities = [self._convert_model(x) for x in entities] if dialog_nodes is not None: - dialog_nodes = [ - self._convert_model(x, DialogNode) for x in dialog_nodes - ] + dialog_nodes = [self._convert_model(x) for x in dialog_nodes] if counterexamples is not None: - counterexamples = [ - self._convert_model(x, Counterexample) for x in counterexamples - ] + counterexamples = [self._convert_model(x) for x in counterexamples] headers = {} if 'headers' in kwargs: @@ -629,7 +619,7 @@ def create_intent(self, if intent is None: raise ValueError('intent must be provided') if examples is not None: - examples = [self._convert_model(x, Example) for x in examples] + examples = [self._convert_model(x) for x in examples] headers = {} if 'headers' in kwargs: @@ -752,9 +742,7 @@ def update_intent(self, if intent is None: raise ValueError('intent must be provided') if new_examples is not None: - new_examples = [ - self._convert_model(x, Example) for x in new_examples - ] + new_examples = [self._convert_model(x) for x in new_examples] headers = {} if 'headers' in kwargs: @@ -924,7 +912,7 @@ def create_example(self, if text is None: raise ValueError('text must be provided') if mentions is not None: - mentions = [self._convert_model(x, Mention) for x in mentions] + mentions = [self._convert_model(x) for x in mentions] headers = {} if 'headers' in kwargs: @@ -1036,9 +1024,7 @@ def update_example(self, if text is None: raise ValueError('text must be provided') if new_mentions is not None: - new_mentions = [ - self._convert_model(x, Mention) for x in new_mentions - ] + new_mentions = [self._convert_model(x) for x in new_mentions] headers = {} if 'headers' in kwargs: @@ -1476,7 +1462,7 @@ def create_entity(self, if entity is None: raise ValueError('entity must be provided') if values is not None: - values = [self._convert_model(x, CreateValue) for x in values] + values = [self._convert_model(x) for x in values] headers = {} if 'headers' in kwargs: @@ -1606,9 +1592,7 @@ def update_entity(self, if entity is None: raise ValueError('entity must be provided') if new_values is not None: - new_values = [ - self._convert_model(x, CreateValue) for x in new_values - ] + new_values = [self._convert_model(x) for x in new_values] headers = {} if 'headers' in kwargs: @@ -2498,13 +2482,11 @@ def create_dialog_node(self, if dialog_node is None: raise ValueError('dialog_node must be provided') if output is not None: - output = self._convert_model(output, DialogNodeOutput) + output = self._convert_model(output) if next_step is not None: - next_step = self._convert_model(next_step, DialogNodeNextStep) + next_step = self._convert_model(next_step) if actions is not None: - actions = [ - self._convert_model(x, DialogNodeAction) for x in actions - ] + actions = [self._convert_model(x) for x in actions] headers = {} if 'headers' in kwargs: @@ -2678,14 +2660,11 @@ def update_dialog_node(self, if dialog_node is None: raise ValueError('dialog_node must be provided') if new_output is not None: - new_output = self._convert_model(new_output, DialogNodeOutput) + new_output = self._convert_model(new_output) if new_next_step is not None: - new_next_step = self._convert_model(new_next_step, - DialogNodeNextStep) + new_next_step = self._convert_model(new_next_step) if new_actions is not None: - new_actions = [ - self._convert_model(x, DialogNodeAction) for x in new_actions - ] + new_actions = [self._convert_model(x) for x in new_actions] headers = {} if 'headers' in kwargs: diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 2e3989c8f..54644c79b 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -203,9 +203,9 @@ def message(self, if session_id is None: raise ValueError('session_id must be provided') if input is not None: - input = self._convert_model(input, MessageInput) + input = self._convert_model(input) if context is not None: - context = self._convert_model(context, MessageContext) + context = self._convert_model(context) headers = {} if 'headers' in kwargs: diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 35a63e185..599f1ce62 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -338,7 +338,7 @@ def add_feedback(self, if feedback_data is None: raise ValueError('feedback_data must be provided') - feedback_data = self._convert_model(feedback_data, FeedbackDataInput) + feedback_data = self._convert_model(feedback_data) headers = {} if 'headers' in kwargs: diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 0688a537b..4977372e4 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -365,18 +365,13 @@ def create_configuration(self, if name is None: raise ValueError('name must be provided') if conversions is not None: - conversions = self._convert_model(conversions, Conversions) + conversions = self._convert_model(conversions) if enrichments is not None: - enrichments = [ - self._convert_model(x, Enrichment) for x in enrichments - ] + enrichments = [self._convert_model(x) for x in enrichments] if normalizations is not None: - normalizations = [ - self._convert_model(x, NormalizationOperation) - for x in normalizations - ] + normalizations = [self._convert_model(x) for x in normalizations] if source is not None: - source = self._convert_model(source, Source) + source = self._convert_model(source) headers = {} if 'headers' in kwargs: @@ -527,18 +522,13 @@ def update_configuration(self, if name is None: raise ValueError('name must be provided') if conversions is not None: - conversions = self._convert_model(conversions, Conversions) + conversions = self._convert_model(conversions) if enrichments is not None: - enrichments = [ - self._convert_model(x, Enrichment) for x in enrichments - ] + enrichments = [self._convert_model(x) for x in enrichments] if normalizations is not None: - normalizations = [ - self._convert_model(x, NormalizationOperation) - for x in normalizations - ] + normalizations = [self._convert_model(x) for x in normalizations] if source is not None: - source = self._convert_model(source, Source) + source = self._convert_model(source) headers = {} if 'headers' in kwargs: @@ -1039,7 +1029,7 @@ def create_expansions(self, environment_id, collection_id, expansions, raise ValueError('collection_id must be provided') if expansions is None: raise ValueError('expansions must be provided') - expansions = [self._convert_model(x, Expansion) for x in expansions] + expansions = [self._convert_model(x) for x in expansions] headers = {} if 'headers' in kwargs: @@ -1169,8 +1159,7 @@ def create_tokenization_dictionary(self, raise ValueError('collection_id must be provided') if tokenization_rules is not None: tokenization_rules = [ - self._convert_model(x, TokenDictRule) - for x in tokenization_rules + self._convert_model(x) for x in tokenization_rules ] headers = {} @@ -2235,9 +2224,9 @@ def query_entities(self, if collection_id is None: raise ValueError('collection_id must be provided') if entity is not None: - entity = self._convert_model(entity, QueryEntitiesEntity) + entity = self._convert_model(entity) if context is not None: - context = self._convert_model(context, QueryEntitiesContext) + context = self._convert_model(context) headers = {} if 'headers' in kwargs: @@ -2313,13 +2302,11 @@ def query_relations(self, if collection_id is None: raise ValueError('collection_id must be provided') if entities is not None: - entities = [ - self._convert_model(x, QueryRelationsEntity) for x in entities - ] + entities = [self._convert_model(x) for x in entities] if context is not None: - context = self._convert_model(context, QueryEntitiesContext) + context = self._convert_model(context) if filter is not None: - filter = self._convert_model(filter, QueryRelationsFilter) + filter = self._convert_model(filter) headers = {} if 'headers' in kwargs: @@ -2423,9 +2410,7 @@ def add_training_data(self, if collection_id is None: raise ValueError('collection_id must be provided') if examples is not None: - examples = [ - self._convert_model(x, TrainingExample) for x in examples - ] + examples = [self._convert_model(x) for x in examples] headers = {} if 'headers' in kwargs: @@ -2893,7 +2878,7 @@ def create_event(self, type, data, **kwargs): raise ValueError('type must be provided') if data is None: raise ValueError('data must be provided') - data = self._convert_model(data, EventData) + data = self._convert_model(data) headers = {} if 'headers' in kwargs: @@ -3284,8 +3269,7 @@ def create_credentials(self, if environment_id is None: raise ValueError('environment_id must be provided') if credential_details is not None: - credential_details = self._convert_model(credential_details, - CredentialDetails) + credential_details = self._convert_model(credential_details) headers = {} if 'headers' in kwargs: @@ -3400,8 +3384,7 @@ def update_credentials(self, if credential_id is None: raise ValueError('credential_id must be provided') if credential_details is not None: - credential_details = self._convert_model(credential_details, - CredentialDetails) + credential_details = self._convert_model(credential_details) headers = {} if 'headers' in kwargs: diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 25a4e480a..0d445cade 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -130,7 +130,7 @@ def classify_collection(self, classifier_id, collection, **kwargs): raise ValueError('classifier_id must be provided') if collection is None: raise ValueError('collection must be provided') - collection = [self._convert_model(x, ClassifyInput) for x in collection] + collection = [self._convert_model(x) for x in collection] headers = {} if 'headers' in kwargs: diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index f1e829101..f896bfd31 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -151,7 +151,7 @@ def analyze(self, if features is None: raise ValueError('features must be provided') - features = self._convert_model(features, Features) + features = self._convert_model(features) headers = {} if 'headers' in kwargs: diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index fb60bbf3f..a7f4b9081 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -189,7 +189,7 @@ def profile(self, if accept is None: raise ValueError('accept must be provided') if isinstance(content, Content): - content = self._convert_model(content, Content) + content = self._convert_model(content) headers = { 'Accept': accept, diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index db1623c6f..1efe4b2dc 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1782,7 +1782,7 @@ def add_words(self, customization_id, words, **kwargs): raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') - words = [self._convert_model(x, CustomWord) for x in words] + words = [self._convert_model(x) for x in words] headers = {} if 'headers' in kwargs: diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index f0aac9eaf..217648801 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -489,7 +489,7 @@ def update_voice_model(self, if customization_id is None: raise ValueError('customization_id must be provided') if words is not None: - words = [self._convert_model(x, Word) for x in words] + words = [self._convert_model(x) for x in words] headers = {} if 'headers' in kwargs: @@ -634,7 +634,7 @@ def add_words(self, customization_id, words, **kwargs): raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') - words = [self._convert_model(x, Word) for x in words] + words = [self._convert_model(x) for x in words] headers = {} if 'headers' in kwargs: diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 1f8324272..cc08f27b9 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -147,7 +147,7 @@ def tone(self, tone_input, *, content_type=None, sentences=None, tones=None, con if tone_input is None: raise ValueError('tone_input must be provided') if isinstance(tone_input, ToneInput): - tone_input = self._convert_model(tone_input, ToneInput) + tone_input = self._convert_model(tone_input) headers = { 'Content-Type': content_type, @@ -219,7 +219,7 @@ def tone_chat(self, utterances, *, content_language=None, accept_language=None, if utterances is None: raise ValueError('utterances must be provided') - utterances = [ self._convert_model(x, Utterance) for x in utterances ] + utterances = [ self._convert_model(x) for x in utterances ] headers = { 'Content-Language': content_language, @@ -426,7 +426,6 @@ def __ne__(self, other): return not self == other - class SentenceAnalysis(object): """ The results of the analysis for the individual sentences of the input content. @@ -541,7 +540,6 @@ def __ne__(self, other): return not self == other - class ToneAnalysis(object): """ The tone analysis results for the input from the general-purpose endpoint. @@ -610,7 +608,6 @@ def __ne__(self, other): return not self == other - class ToneCategory(object): """ The category for a tone from the input content. @@ -686,7 +683,6 @@ def __ne__(self, other): return not self == other - class ToneChatScore(object): """ The score for an utterance from the input content. @@ -763,20 +759,19 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other - + class ToneIdEnum(Enum): - """ + """ The unique, non-localized identifier of the tone for the results. The service returns results only for tones whose scores meet a minimum threshold of 0.5. """ - EXCITED = "excited" - FRUSTRATED = "frustrated" - IMPOLITE = "impolite" - POLITE = "polite" - SAD = "sad" - SATISFIED = "satisfied" - SYMPATHETIC = "sympathetic" - + EXCITED = "excited" + FRUSTRATED = "frustrated" + IMPOLITE = "impolite" + POLITE = "polite" + SAD = "sad" + SATISFIED = "satisfied" + SYMPATHETIC = "sympathetic" class ToneInput(object): @@ -830,7 +825,6 @@ def __ne__(self, other): return not self == other - class ToneScore(object): """ The score for a tone from the input content. @@ -936,7 +930,6 @@ def __ne__(self, other): return not self == other - class Utterance(object): """ An utterance for the input of the general-purpose endpoint. @@ -999,7 +992,6 @@ def __ne__(self, other): return not self == other - class UtteranceAnalyses(object): """ The results of the analysis for the utterances of the input content. @@ -1065,7 +1057,6 @@ def __ne__(self, other): return not self == other - class UtteranceAnalysis(object): """ The results of the analysis for an utterance of the input content. @@ -1156,4 +1147,3 @@ def __ne__(self, other): return not self == other - From db8a07a8728344d06b554c02aa8fa667418f3dbc Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 4 Sep 2019 16:55:11 -0700 Subject: [PATCH 064/455] chore(adapters): Pass in debug to adapters --- ibm_watson/speech_to_text_v1_adapter.py | 3 ++- ibm_watson/text_to_speech_adapter_v1.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index c0678e430..80de6fb33 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -258,4 +258,5 @@ def recognize_using_websocket(self, request.get('headers'), http_proxy_host, http_proxy_port, - self.disable_ssl_verification) + self.disable_ssl_verification, + self.debug) diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index fdd4e7c3c..de53f20c8 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -108,4 +108,5 @@ def synthesize_using_websocket(self, request.get('headers'), http_proxy_host, http_proxy_port, - self.disable_ssl_verification) + self.disable_ssl_verification, + self.debug) From 6efdec33172b88ab89a0c799e2e8a1daab01031b Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 4 Sep 2019 16:55:25 -0700 Subject: [PATCH 065/455] chore(core): udpate core version --- requirements-dev.txt | 2 +- requirements.txt | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index d4f8e56f5..615708de5 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ python_dotenv>=0.1.5;python_version!='3.2' pylint>=1.4.4 tox>=2.9.1 pytest-rerunfailures>=3.1 -ibm_cloud_sdk_core==1.0.0rc4 +ibm_cloud_sdk_core==1.0.0rc5 # code coverage coverage<5 diff --git a/requirements.txt b/requirements.txt index 3704aa416..85af66e0f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 -ibm_cloud_sdk_core==1.0.0rc4 \ No newline at end of file +ibm_cloud_sdk_core==1.0.0rc5 \ No newline at end of file diff --git a/setup.py b/setup.py index c028b7480..aace9b7c2 100644 --- a/setup.py +++ b/setup.py @@ -63,7 +63,7 @@ def run_tests(self): version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.0.0rc4'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.0.0rc5'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='IBM Watson', From 751aa5ddcb3203e0e4bc102615edc74af0f473d6 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 5 Sep 2019 10:18:45 -0700 Subject: [PATCH 066/455] feat(logging): enable logging in websocket --- ibm_watson/speech_to_text_v1_adapter.py | 3 +-- ibm_watson/text_to_speech_adapter_v1.py | 3 +-- ibm_watson/websocket/recognize_listener.py | 7 ++----- ibm_watson/websocket/synthesize_listener.py | 7 ++----- 4 files changed, 6 insertions(+), 14 deletions(-) diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 80de6fb33..c0678e430 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -258,5 +258,4 @@ def recognize_using_websocket(self, request.get('headers'), http_proxy_host, http_proxy_port, - self.disable_ssl_verification, - self.debug) + self.disable_ssl_verification) diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index de53f20c8..fdd4e7c3c 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -108,5 +108,4 @@ def synthesize_using_websocket(self, request.get('headers'), http_proxy_host, http_proxy_port, - self.disable_ssl_verification, - self.debug) + self.disable_ssl_verification) diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index 7151688c2..6973a746b 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -42,8 +42,7 @@ def __init__(self, headers, http_proxy_host=None, http_proxy_port=None, - verify=None, - debug=False): + verify=None): self.audio_source = audio_source self.options = options self.callback = callback @@ -54,9 +53,7 @@ def __init__(self, self.isListening = False self.verify = verify - if debug: - logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) - websocket.enableTrace(True) + websocket.enableTrace(True) self.ws_client = websocket.WebSocketApp( self.url, diff --git a/ibm_watson/websocket/synthesize_listener.py b/ibm_watson/websocket/synthesize_listener.py index c07b3b83d..c067a2f18 100644 --- a/ibm_watson/websocket/synthesize_listener.py +++ b/ibm_watson/websocket/synthesize_listener.py @@ -36,8 +36,7 @@ def __init__(self, headers, http_proxy_host=None, http_proxy_port=None, - verify=None, - debug=False): + verify=None): self.options = options self.callback = callback self.url = url @@ -46,9 +45,7 @@ def __init__(self, self.http_proxy_port = http_proxy_port self.verify = verify - if debug: - logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) - websocket.enableTrace(True) + websocket.enableTrace(True) self.ws_client = websocket.WebSocketApp( self.url, From 92e424a50f9e9386fc1ce6b45115be7499bfba9b Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 5 Sep 2019 10:19:20 -0700 Subject: [PATCH 067/455] doc(logging): Update doc with logging information --- README.md | 68 +++++++++++++++---------------------------------------- 1 file changed, 18 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index b50ecadcd..a4712e4f3 100755 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Python client library to quickly get started with the various [Watson APIs][wdc] * [Parsing HTTP response info](#parsing-http-response-info) * [Using Websockets](#using-websockets) * [Cloud Pak for Data(CP4D)](#cloud-pak-for-data) - * [Debugging/Logging](#debugging-and-logging) + * [Logging](#logging) * [Dependencies](#dependencies) * [License](#license) * [Contributing](#contributing) @@ -399,65 +399,33 @@ assistant = AssistantV1(version='', disable_ssl_verification=True) # MAKE SURE SSL VERIFICATION IS DISABLED ``` -## Debugging and Logging - -### Enable Debugging -To take advantage of the underlying http request printed to stdout, simply enable debugging -```python -my_service.enable_debugging() -``` - -### Enable Debugging -To disable debugging printed to stdout, simply disable debugging -```python -my_service.disable_debugging() -``` +## Logging ### Enable logging -We support python's logging capabilities by passing in a config file. As an example, consider the following `logging.conf` file +```python +import logging +logging.basicConfig(level=logging.DEBUG) ``` -[loggers] -keys=root -[handlers] -keys=fileHandler - -[formatters] -keys=Formatter - -[logger_root] -level=DEBUG -handlers=fileHandler -qualname=main - -[handler_fileHandler] -class=FileHandler -level=DEBUG -formatter=Formatter -args=('app.log', 'w', 'utf8') - -[formatter_Formatter] -format=%(asctime)s - %(levelname)s - %(message)s -datefmt="%Y-%m-%d %H:%M:%S" +This would show output of the form: ``` - -Using this file, enable logging: - -```python -from os import path -log_file_path = path.join(path.dirname(path.abspath(__file__)), 'logging.conf') -my_service.enable_logging(log_file_path) +DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): iam.cloud.ibm.com:443 +DEBUG:urllib3.connectionpool:https://iam.cloud.ibm.com:443 "POST /identity/token HTTP/1.1" 200 1809 +DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443 +DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "POST /assistant/api/v1/workspaces?version=2018-07-10 HTTP/1.1" 201 None +DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443 +DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "GET /assistant/api/v1/workspaces/883a2a44-eb5f-4b1a-96b0-32a90b475ea8?version=2018-07-10&export=true HTTP/1.1" 200 None +DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): gateway.watsonplatform.net:443 +DEBUG:urllib3.connectionpool:https://gateway.watsonplatform.net:443 "DELETE /assistant/api/v1/workspaces/883a2a44-eb5f-4b1a-96b0-32a90b475ea8?version=2018-07-10 HTTP/1.1" 200 28 ``` -### Get logger -Using the logger, configure it as per your needs. As an example: +### Low level request and response dump +To get low level information of the requests/ responses: ```python -logger = my_service.get_logger() -ch = logging.StreamHandler() -ch.setLevel(logging.DEBUG) -logger.addHandler(ch) +from http.client import HTTPConnection +HTTPConnection.debuglevel = 1 ``` ## Dependencies From 4532e7435bf5a2f603001a500e1fd34da39b4686 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 5 Sep 2019 10:24:20 -0700 Subject: [PATCH 068/455] chore(imports): remove unused imports --- ibm_watson/websocket/recognize_listener.py | 2 -- ibm_watson/websocket/synthesize_listener.py | 2 -- 2 files changed, 4 deletions(-) diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index 6973a746b..a37e6792e 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -18,8 +18,6 @@ import json import time import ssl -import logging -import sys try: import thread except ImportError: diff --git a/ibm_watson/websocket/synthesize_listener.py b/ibm_watson/websocket/synthesize_listener.py index c067a2f18..fe21fcc1d 100644 --- a/ibm_watson/websocket/synthesize_listener.py +++ b/ibm_watson/websocket/synthesize_listener.py @@ -18,8 +18,6 @@ import json import ssl import time -import logging -import sys try: import thread except ImportError: From 3427e79b264394275520205c94c057a77628c9ee Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 12 Sep 2019 13:53:54 -0700 Subject: [PATCH 069/455] doc(service_url): Update readme to show setting of service url --- README.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index a4712e4f3..cc22fe81b 100755 --- a/README.md +++ b/README.md @@ -287,7 +287,20 @@ print(json.dumps(response, indent=2)) For ICP(IBM Cloud Private), you can disable the SSL certificate verification by: ```python -service.set_disable_ssl_verification() +service.set_disable_ssl_verification(True) +``` + +## Setting the service url +To set the base service to be used when contacting the service + +```python +service.set_service_url('my_new_service_url') +``` + +Or can set it in the environment variable + +``` +export service_service_url="" ``` ## Sending request headers From 1e51bff346eb6a5258726f58a8018a275c1a1ae4 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 12 Sep 2019 13:55:44 -0700 Subject: [PATCH 070/455] doc(readme): Update table of contents --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index cc22fe81b..cedc11bbe 100755 --- a/README.md +++ b/README.md @@ -27,6 +27,7 @@ Python client library to quickly get started with the various [Watson APIs][wdc] * [Migration](#migration) * [Configuring the http client](#configuring-the-http-client-supported-from-v110) * [Disable SSL certificate verification](#disable-ssl-certificate-verification) + * [Setting the service url](#setting-the-service-url) * [Sending request headers](#sending-request-headers) * [Parsing HTTP response info](#parsing-http-response-info) * [Using Websockets](#using-websockets) From efc4bb620f745dfc3dad95d056a241f256a4ab57 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 12 Sep 2019 14:25:21 -0700 Subject: [PATCH 071/455] doc(readme): Update doc for url --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cedc11bbe..9c7f54f20 100755 --- a/README.md +++ b/README.md @@ -298,10 +298,10 @@ To set the base service to be used when contacting the service service.set_service_url('my_new_service_url') ``` -Or can set it in the environment variable +Or can set it in the environment variable. ``` -export service_service_url="" +export _url="" ``` ## Sending request headers From 9ddd85b1d068bb1c7958b3e67315dc0bf54dc687 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Mon, 16 Sep 2019 14:54:11 -0700 Subject: [PATCH 072/455] chore(pylint): new dict comprehension syntax --- ibm_watson/speech_to_text_v1_adapter.py | 4 ++-- ibm_watson/text_to_speech_adapter_v1.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index c0678e430..166b67f93 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -225,7 +225,7 @@ def recognize_using_websocket(self, 'base_model_version': base_model_version, 'language_customization_id': language_customization_id } - params = dict([(k, v) for k, v in params.items() if v is not None]) + params = {k: v for k, v in params.items() if v is not None} url += '/v1/recognize?{0}'.format(urlencode(params)) request['url'] = url @@ -248,7 +248,7 @@ def recognize_using_websocket(self, 'processing_metrics_interval': processing_metrics_interval, 'audio_metrics': audio_metrics } - options = dict([(k, v) for k, v in options.items() if v is not None]) + options = {k: v for k, v in options.items() if v is not None} request['options'] = options RecognizeListener(audio, diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index fdd4e7c3c..31485f482 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -90,7 +90,7 @@ def synthesize_using_websocket(self, 'voice': voice, 'customization_id': customization_id, } - params = dict([(k, v) for k, v in params.items() if v is not None]) + params = {k: v for k, v in params.items() if v is not None} url += '/v1/synthesize?{0}'.format(urlencode(params)) request['url'] = url @@ -99,7 +99,7 @@ def synthesize_using_websocket(self, 'accept': accept, 'timings': timings } - options = dict([(k, v) for k, v in options.items() if v is not None]) + options = {k: v for k, v in options.items() if v is not None} request['options'] = options SynthesizeListener(request.get('options'), From 2dc2827bdab1e21df7e4a294590c982a287003ad Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Mon, 16 Sep 2019 14:54:48 -0700 Subject: [PATCH 073/455] chore(pylint): proper indentation --- examples/natural_language_classifier_v1.py | 6 +- ibm_watson/tone_analyzer_v3.py | 265 ++++++++++++++------- test/unit/test_compare_comply_v1.py | 4 +- 3 files changed, 188 insertions(+), 87 deletions(-) diff --git a/examples/natural_language_classifier_v1.py b/examples/natural_language_classifier_v1.py index 5a8f1f6b1..8e4688124 100644 --- a/examples/natural_language_classifier_v1.py +++ b/examples/natural_language_classifier_v1.py @@ -15,9 +15,9 @@ # create a classifier with open( - os.path.join( - os.path.dirname(__file__), '../resources/weather_data_train.csv'), - 'rb') as training_data: + 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 = service.create_classifier( training_metadata=metadata, training_data=training_data).get_result() diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index cc08f27b9..5e6a7b4de 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -13,7 +13,6 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - """ The IBM Watson™ Tone Analyzer service uses linguistic analysis to detect emotional and language tones in written text. The service can analyze tone at both the document and @@ -36,17 +35,19 @@ # Service ############################################################################## + class ToneAnalyzerV3(BaseService): """The Tone Analyzer V3 service.""" default_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' - def __init__(self, - version, - url=default_url, - authenticator=None, - disable_ssl_verification=False, - ): + def __init__( + self, + version, + url=default_url, + authenticator=None, + disable_ssl_verification=False, + ): """ Construct a new client for the Tone Analyzer service. @@ -75,19 +76,25 @@ def __init__(self, authenticator = get_authenticator_from_environment('Tone Analyzer') BaseService.__init__(self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Tone Analyzer') + url=url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification, + display_name='Tone Analyzer') self.version = version ######################### # Methods ######################### - - - def tone(self, tone_input, *, content_type=None, sentences=None, tones=None, content_language=None, accept_language=None, **kwargs): + def tone(self, + tone_input, + *, + content_type=None, + sentences=None, + tones=None, + content_language=None, + accept_language=None, + **kwargs): """ Analyze general tone. @@ -172,16 +179,20 @@ def tone(self, tone_input, *, content_type=None, sentences=None, tones=None, con url = '/v3/tone' request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response - - def tone_chat(self, utterances, *, content_language=None, accept_language=None, **kwargs): + def tone_chat(self, + utterances, + *, + content_language=None, + accept_language=None, + **kwargs): """ Analyze customer-engagement tone. @@ -219,7 +230,7 @@ def tone_chat(self, utterances, *, content_language=None, accept_language=None, if utterances is None: raise ValueError('utterances must be provided') - utterances = [ self._convert_model(x) for x in utterances ] + utterances = [self._convert_model(x) for x in utterances] headers = { 'Content-Language': content_language, @@ -230,26 +241,23 @@ def tone_chat(self, utterances, *, content_language=None, accept_language=None, sdk_headers = get_sdk_headers('tone_analyzer', 'V3', 'tone_chat') headers.update(sdk_headers) - params = { - 'version': self.version - } + params = {'version': self.version} - data = { - 'utterances': utterances - } + data = {'utterances': utterances} url = '/v3/tone_chat' request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response class ToneEnums(object): + class ContentType(Enum): """ The type of the input. A character encoding can be specified by including a @@ -258,6 +266,7 @@ class ContentType(Enum): APPLICATION_JSON = 'application/json' TEXT_PLAIN = 'text/plain' TEXT_HTML = 'text/html' + class Tones(Enum): """ **`2017-09-21`:** Deprecated. The service continues to accept the parameter for @@ -270,6 +279,7 @@ class Tones(Enum): EMOTION = 'emotion' LANGUAGE = 'language' SOCIAL = 'social' + class ContentLanguage(Enum): """ The language of the input text for the request: English or French. Regional @@ -282,6 +292,7 @@ class ContentLanguage(Enum): """ EN = 'en' FR = 'fr' + class AcceptLanguage(Enum): """ The desired language of the response. For two-character arguments, regional @@ -303,6 +314,7 @@ class AcceptLanguage(Enum): class ToneChatEnums(object): + class ContentLanguage(Enum): """ The language of the input text for the request: English or French. Regional @@ -315,6 +327,7 @@ class ContentLanguage(Enum): """ EN = 'en' FR = 'fr' + class AcceptLanguage(Enum): """ The desired language of the response. For two-character arguments, regional @@ -391,11 +404,18 @@ def _from_dict(cls, _dict): validKeys = ['tones', 'tone_categories', 'warning'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError('Unrecognized keys detected in dictionary for class DocumentAnalysis: ' + ', '.join(badKeys)) + raise ValueError( + 'Unrecognized keys detected in dictionary for class DocumentAnalysis: ' + + ', '.join(badKeys)) if 'tones' in _dict: - args['tones'] = [ToneScore._from_dict(x) for x in (_dict.get('tones') )] + args['tones'] = [ + ToneScore._from_dict(x) for x in (_dict.get('tones')) + ] if 'tone_categories' in _dict: - args['tone_categories'] = [ToneCategory._from_dict(x) for x in (_dict.get('tone_categories') )] + args['tone_categories'] = [ + ToneCategory._from_dict(x) + for x in (_dict.get('tone_categories')) + ] if 'warning' in _dict: args['warning'] = _dict.get('warning') return cls(**args) @@ -405,8 +425,11 @@ def _to_dict(self): _dict = {} if hasattr(self, 'tones') and self.tones is not None: _dict['tones'] = [x._to_dict() for x in self.tones] - if hasattr(self, 'tone_categories') and self.tone_categories is not None: - _dict['tone_categories'] = [x._to_dict() for x in self.tone_categories] + if hasattr(self, + 'tone_categories') and self.tone_categories is not None: + _dict['tone_categories'] = [ + x._to_dict() for x in self.tone_categories + ] if hasattr(self, 'warning') and self.warning is not None: _dict['warning'] = self.warning return _dict @@ -450,7 +473,14 @@ class SentenceAnalysis(object): The offset of the last character of the sentence in the overall input content. """ - def __init__(self, sentence_id, text, *, tones=None, tone_categories=None, input_from=None, input_to=None): + def __init__(self, + sentence_id, + text, + *, + tones=None, + tone_categories=None, + input_from=None, + input_to=None): """ Initialize a SentenceAnalysis object. @@ -486,22 +516,36 @@ def __init__(self, sentence_id, text, *, tones=None, tone_categories=None, input def _from_dict(cls, _dict): """Initialize a SentenceAnalysis object from a json dictionary.""" args = {} - validKeys = ['sentence_id', 'text', 'tones', 'tone_categories', 'input_from', 'input_to'] + validKeys = [ + 'sentence_id', 'text', 'tones', 'tone_categories', 'input_from', + 'input_to' + ] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError('Unrecognized keys detected in dictionary for class SentenceAnalysis: ' + ', '.join(badKeys)) + raise ValueError( + 'Unrecognized keys detected in dictionary for class SentenceAnalysis: ' + + ', '.join(badKeys)) if 'sentence_id' in _dict: args['sentence_id'] = _dict.get('sentence_id') else: - raise ValueError('Required property \'sentence_id\' not present in SentenceAnalysis JSON') + raise ValueError( + 'Required property \'sentence_id\' not present in SentenceAnalysis JSON' + ) if 'text' in _dict: args['text'] = _dict.get('text') else: - raise ValueError('Required property \'text\' not present in SentenceAnalysis JSON') + raise ValueError( + 'Required property \'text\' not present in SentenceAnalysis JSON' + ) if 'tones' in _dict: - args['tones'] = [ToneScore._from_dict(x) for x in (_dict.get('tones') )] + args['tones'] = [ + ToneScore._from_dict(x) for x in (_dict.get('tones')) + ] if 'tone_categories' in _dict: - args['tone_categories'] = [ToneCategory._from_dict(x) for x in (_dict.get('tone_categories') )] + args['tone_categories'] = [ + ToneCategory._from_dict(x) + for x in (_dict.get('tone_categories')) + ] if 'input_from' in _dict: args['input_from'] = _dict.get('input_from') if 'input_to' in _dict: @@ -517,8 +561,11 @@ def _to_dict(self): _dict['text'] = self.text if hasattr(self, 'tones') and self.tones is not None: _dict['tones'] = [x._to_dict() for x in self.tones] - if hasattr(self, 'tone_categories') and self.tone_categories is not None: - _dict['tone_categories'] = [x._to_dict() for x in self.tone_categories] + if hasattr(self, + 'tone_categories') and self.tone_categories is not None: + _dict['tone_categories'] = [ + x._to_dict() for x in self.tone_categories + ] if hasattr(self, 'input_from') and self.input_from is not None: _dict['input_from'] = self.input_from if hasattr(self, 'input_to') and self.input_to is not None: @@ -575,13 +622,21 @@ def _from_dict(cls, _dict): validKeys = ['document_tone', 'sentences_tone'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError('Unrecognized keys detected in dictionary for class ToneAnalysis: ' + ', '.join(badKeys)) + raise ValueError( + 'Unrecognized keys detected in dictionary for class ToneAnalysis: ' + + ', '.join(badKeys)) if 'document_tone' in _dict: - args['document_tone'] = DocumentAnalysis._from_dict(_dict.get('document_tone')) + args['document_tone'] = DocumentAnalysis._from_dict( + _dict.get('document_tone')) else: - raise ValueError('Required property \'document_tone\' not present in ToneAnalysis JSON') + raise ValueError( + 'Required property \'document_tone\' not present in ToneAnalysis JSON' + ) if 'sentences_tone' in _dict: - args['sentences_tone'] = [SentenceAnalysis._from_dict(x) for x in (_dict.get('sentences_tone') )] + args['sentences_tone'] = [ + SentenceAnalysis._from_dict(x) + for x in (_dict.get('sentences_tone')) + ] return cls(**args) def _to_dict(self): @@ -590,7 +645,9 @@ def _to_dict(self): if hasattr(self, 'document_tone') and self.document_tone is not None: _dict['document_tone'] = self.document_tone._to_dict() if hasattr(self, 'sentences_tone') and self.sentences_tone is not None: - _dict['sentences_tone'] = [x._to_dict() for x in self.sentences_tone] + _dict['sentences_tone'] = [ + x._to_dict() for x in self.sentences_tone + ] return _dict def __str__(self): @@ -642,19 +699,28 @@ def _from_dict(cls, _dict): validKeys = ['tones', 'category_id', 'category_name'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError('Unrecognized keys detected in dictionary for class ToneCategory: ' + ', '.join(badKeys)) + raise ValueError( + 'Unrecognized keys detected in dictionary for class ToneCategory: ' + + ', '.join(badKeys)) if 'tones' in _dict: - args['tones'] = [ToneScore._from_dict(x) for x in (_dict.get('tones') )] + args['tones'] = [ + ToneScore._from_dict(x) for x in (_dict.get('tones')) + ] else: - raise ValueError('Required property \'tones\' not present in ToneCategory JSON') + raise ValueError( + 'Required property \'tones\' not present in ToneCategory JSON') if 'category_id' in _dict: args['category_id'] = _dict.get('category_id') else: - raise ValueError('Required property \'category_id\' not present in ToneCategory JSON') + raise ValueError( + 'Required property \'category_id\' not present in ToneCategory JSON' + ) if 'category_name' in _dict: args['category_name'] = _dict.get('category_name') else: - raise ValueError('Required property \'category_name\' not present in ToneCategory JSON') + raise ValueError( + 'Required property \'category_name\' not present in ToneCategory JSON' + ) return cls(**args) def _to_dict(self): @@ -719,19 +785,26 @@ def _from_dict(cls, _dict): validKeys = ['score', 'tone_id', 'tone_name'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError('Unrecognized keys detected in dictionary for class ToneChatScore: ' + ', '.join(badKeys)) + raise ValueError( + 'Unrecognized keys detected in dictionary for class ToneChatScore: ' + + ', '.join(badKeys)) if 'score' in _dict: args['score'] = _dict.get('score') else: - raise ValueError('Required property \'score\' not present in ToneChatScore JSON') + raise ValueError( + 'Required property \'score\' not present in ToneChatScore JSON') if 'tone_id' in _dict: args['tone_id'] = _dict.get('tone_id') else: - raise ValueError('Required property \'tone_id\' not present in ToneChatScore JSON') + raise ValueError( + 'Required property \'tone_id\' not present in ToneChatScore JSON' + ) if 'tone_name' in _dict: args['tone_name'] = _dict.get('tone_name') else: - raise ValueError('Required property \'tone_name\' not present in ToneChatScore JSON') + raise ValueError( + 'Required property \'tone_name\' not present in ToneChatScore JSON' + ) return cls(**args) def _to_dict(self): @@ -759,7 +832,6 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ToneIdEnum(Enum): """ The unique, non-localized identifier of the tone for the results. The service @@ -796,11 +868,14 @@ def _from_dict(cls, _dict): validKeys = ['text'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError('Unrecognized keys detected in dictionary for class ToneInput: ' + ', '.join(badKeys)) + raise ValueError( + 'Unrecognized keys detected in dictionary for class ToneInput: ' + + ', '.join(badKeys)) if 'text' in _dict: args['text'] = _dict.get('text') else: - raise ValueError('Required property \'text\' not present in ToneInput JSON') + raise ValueError( + 'Required property \'text\' not present in ToneInput JSON') return cls(**args) def _to_dict(self): @@ -889,19 +964,24 @@ def _from_dict(cls, _dict): validKeys = ['score', 'tone_id', 'tone_name'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError('Unrecognized keys detected in dictionary for class ToneScore: ' + ', '.join(badKeys)) + raise ValueError( + 'Unrecognized keys detected in dictionary for class ToneScore: ' + + ', '.join(badKeys)) if 'score' in _dict: args['score'] = _dict.get('score') else: - raise ValueError('Required property \'score\' not present in ToneScore JSON') + raise ValueError( + 'Required property \'score\' not present in ToneScore JSON') if 'tone_id' in _dict: args['tone_id'] = _dict.get('tone_id') else: - raise ValueError('Required property \'tone_id\' not present in ToneScore JSON') + raise ValueError( + 'Required property \'tone_id\' not present in ToneScore JSON') if 'tone_name' in _dict: args['tone_name'] = _dict.get('tone_name') else: - raise ValueError('Required property \'tone_name\' not present in ToneScore JSON') + raise ValueError( + 'Required property \'tone_name\' not present in ToneScore JSON') return cls(**args) def _to_dict(self): @@ -959,11 +1039,14 @@ def _from_dict(cls, _dict): validKeys = ['text', 'user'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError('Unrecognized keys detected in dictionary for class Utterance: ' + ', '.join(badKeys)) + raise ValueError( + 'Unrecognized keys detected in dictionary for class Utterance: ' + + ', '.join(badKeys)) if 'text' in _dict: args['text'] = _dict.get('text') else: - raise ValueError('Required property \'text\' not present in Utterance JSON') + raise ValueError( + 'Required property \'text\' not present in Utterance JSON') if 'user' in _dict: args['user'] = _dict.get('user') return cls(**args) @@ -1024,11 +1107,18 @@ def _from_dict(cls, _dict): validKeys = ['utterances_tone', 'warning'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError('Unrecognized keys detected in dictionary for class UtteranceAnalyses: ' + ', '.join(badKeys)) + raise ValueError( + 'Unrecognized keys detected in dictionary for class UtteranceAnalyses: ' + + ', '.join(badKeys)) if 'utterances_tone' in _dict: - args['utterances_tone'] = [UtteranceAnalysis._from_dict(x) for x in (_dict.get('utterances_tone') )] + args['utterances_tone'] = [ + UtteranceAnalysis._from_dict(x) + for x in (_dict.get('utterances_tone')) + ] else: - raise ValueError('Required property \'utterances_tone\' not present in UtteranceAnalyses JSON') + raise ValueError( + 'Required property \'utterances_tone\' not present in UtteranceAnalyses JSON' + ) if 'warning' in _dict: args['warning'] = _dict.get('warning') return cls(**args) @@ -1036,8 +1126,11 @@ def _from_dict(cls, _dict): def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'utterances_tone') and self.utterances_tone is not None: - _dict['utterances_tone'] = [x._to_dict() for x in self.utterances_tone] + if hasattr(self, + 'utterances_tone') and self.utterances_tone is not None: + _dict['utterances_tone'] = [ + x._to_dict() for x in self.utterances_tone + ] if hasattr(self, 'warning') and self.warning is not None: _dict['warning'] = self.warning return _dict @@ -1102,19 +1195,29 @@ def _from_dict(cls, _dict): validKeys = ['utterance_id', 'utterance_text', 'tones', 'error'] badKeys = set(_dict.keys()) - set(validKeys) if badKeys: - raise ValueError('Unrecognized keys detected in dictionary for class UtteranceAnalysis: ' + ', '.join(badKeys)) + raise ValueError( + 'Unrecognized keys detected in dictionary for class UtteranceAnalysis: ' + + ', '.join(badKeys)) if 'utterance_id' in _dict: args['utterance_id'] = _dict.get('utterance_id') else: - raise ValueError('Required property \'utterance_id\' not present in UtteranceAnalysis JSON') + raise ValueError( + 'Required property \'utterance_id\' not present in UtteranceAnalysis JSON' + ) if 'utterance_text' in _dict: args['utterance_text'] = _dict.get('utterance_text') else: - raise ValueError('Required property \'utterance_text\' not present in UtteranceAnalysis JSON') + raise ValueError( + 'Required property \'utterance_text\' not present in UtteranceAnalysis JSON' + ) if 'tones' in _dict: - args['tones'] = [ToneChatScore._from_dict(x) for x in (_dict.get('tones') )] + args['tones'] = [ + ToneChatScore._from_dict(x) for x in (_dict.get('tones')) + ] else: - raise ValueError('Required property \'tones\' not present in UtteranceAnalysis JSON') + raise ValueError( + 'Required property \'tones\' not present in UtteranceAnalysis JSON' + ) if 'error' in _dict: args['error'] = _dict.get('error') return cls(**args) @@ -1145,5 +1248,3 @@ def __eq__(self, other): def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other - - diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index bdd543c05..640573678 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -173,8 +173,8 @@ def test_convert_to_html(self): content_type='application/json') with open( - os.path.join(os.path.dirname(__file__), - '../../resources/contract_A.pdf'), 'rb') as file: + os.path.join(os.path.dirname(__file__), + '../../resources/contract_A.pdf'), 'rb') as file: service.convert_to_html( file, model_id="contracts", From 614391d75d395842f9ecd842024695d84ef5c478 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Mon, 16 Sep 2019 14:55:12 -0700 Subject: [PATCH 074/455] chore(pyllint): Unused imports --- ibm_watson/text_to_speech_v1.py | 1 - test/unit/test_natural_language_understanding.py | 1 - 2 files changed, 2 deletions(-) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 217648801..40a0b5b10 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -35,7 +35,6 @@ from enum import Enum from ibm_cloud_sdk_core import BaseService from ibm_cloud_sdk_core import get_authenticator_from_environment -from os.path import basename ############################################################################## # Service diff --git a/test/unit/test_natural_language_understanding.py b/test/unit/test_natural_language_understanding.py index 32c09ef56..485b402bd 100644 --- a/test/unit/test_natural_language_understanding.py +++ b/test/unit/test_natural_language_understanding.py @@ -72,7 +72,6 @@ def test_missing_credentials(self): with pytest.raises(ValueError): NaturalLanguageUnderstandingV1(version='2016-01-23') with pytest.raises(ValueError): - authenticator = BasicAuthenticator('username', 'password') NaturalLanguageUnderstandingV1(version='2016-01-23', url='http://bogus.com') def test_analyze_throws(self): From a01129943c2f334a45c8229fa44ccb7fdb0013fe Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Mon, 16 Sep 2019 14:57:57 -0700 Subject: [PATCH 075/455] chore(pylint): pass not needed when docsstring is present --- .../websocket/recognize_abstract_callback.py | 40 ++++++++----------- ibm_watson/websocket/synthesize_callback.py | 36 +++++++---------- 2 files changed, 30 insertions(+), 46 deletions(-) diff --git a/ibm_watson/websocket/recognize_abstract_callback.py b/ibm_watson/websocket/recognize_abstract_callback.py index ffbb4bfeb..ed77ce253 100644 --- a/ibm_watson/websocket/recognize_abstract_callback.py +++ b/ibm_watson/websocket/recognize_abstract_callback.py @@ -21,48 +21,40 @@ def __init__(self): def on_transcription(self, transcript): """ - Called after the service returns the final result for the transcription. - """ - pass + Called after the service returns the final result for the transcription. + """ def on_connected(self): """ - Called when a Websocket connection was made - """ - pass + Called when a Websocket connection was made + """ def on_error(self, error): """ - Called when there is an error in the Websocket connection. - """ - pass + Called when there is an error in the Websocket connection. + """ def on_inactivity_timeout(self, error): """ - Called when there is an inactivity timeout. - """ - pass + Called when there is an inactivity timeout. + """ def on_listening(self): """ - Called when the service is listening for audio. - """ - pass + Called when the service is listening for audio. + """ def on_hypothesis(self, hypothesis): """ - Called when an interim result is received. - """ - pass + Called when an interim result is received. + """ def on_data(self, data): """ - Called when the service returns results. The data is returned unparsed. - """ - pass + Called when the service returns results. The data is returned unparsed. + """ def on_close(self): """ - Called when the Websocket connection is closed - """ - pass + Called when the Websocket connection is closed + """ diff --git a/ibm_watson/websocket/synthesize_callback.py b/ibm_watson/websocket/synthesize_callback.py index 70c7a6075..e153b66b2 100644 --- a/ibm_watson/websocket/synthesize_callback.py +++ b/ibm_watson/websocket/synthesize_callback.py @@ -21,43 +21,35 @@ def __init__(self): def on_connected(self): """ - Called when a Websocket connection was made - """ - pass + Called when a Websocket connection was made + """ def on_error(self, error): """ - Called when there is an error in the Websocket connection. - """ - pass - + Called when there is an error in the Websocket connection. + """ def on_content_type(self, content_type): """ - Called when the service responds with the format of the audio response - """ - pass + Called when the service responds with the format of the audio response + """ def on_timing_information(self, timing_information): """ - Called when the service returns timing information - """ - pass + Called when the service returns timing information + """ def on_audio_stream(self, audio_stream): """ - Called when the service sends the synthesized audio as a binary stream of data in the indicated format. - """ - pass + Called when the service sends the synthesized audio as a binary stream of data in the indicated format. + """ def on_data(self, data): """ - Called when the service returns results. The data is returned unparsed. - """ - pass + Called when the service returns results. The data is returned unparsed. + """ def on_close(self): """ - Called when the Websocket connection is closed - """ - pass + Called when the Websocket connection is closed + """ From 18ca8901720a27f163ff558c934510e01cedcb9f Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Mon, 16 Sep 2019 14:58:34 -0700 Subject: [PATCH 076/455] chore(pylinyt): Handle x is unsubscriptable and len-as-condition --- test/integration/test_speech_to_text_v1.py | 10 +++++----- test/integration/test_text_to_speech_v1.py | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/test/integration/test_speech_to_text_v1.py b/test/integration/test_speech_to_text_v1.py index cfd4f5298..6f53da5b7 100644 --- a/test/integration/test_speech_to_text_v1.py +++ b/test/integration/test_speech_to_text_v1.py @@ -26,12 +26,12 @@ def setup_class(cls): cls.create_custom_model = cls.speech_to_text.create_language_model( name="integration_test_model", base_model_name="en-US_BroadbandModel").get_result() - cls.customization_id = cls.create_custom_model['customization_id'] + cls.customization_id = cls.create_custom_model.get('customization_id') @classmethod def teardown_class(cls): cls.speech_to_text.delete_language_model( - customization_id=cls.create_custom_model['customization_id']) + customization_id=cls.create_custom_model.get('customization_id')) def test_models(self): output = self.speech_to_text.list_models().get_result() @@ -46,7 +46,7 @@ def test_models(self): def test_create_custom_model(self): current_custom_models = self.speech_to_text.list_language_models().get_result() assert len(current_custom_models['customizations']) - len( - self.custom_models['customizations']) >= 1 + self.custom_models.get('customizations')) >= 1 def test_recognize(self): with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: @@ -61,7 +61,7 @@ def test_recognitions(self): def test_custom_corpora(self): output = self.speech_to_text.list_corpora(self.customization_id).get_result() - assert len(output['corpora']) == 0 # pylint: disable=len-as-condition + assert not output['corpora'] def test_acoustic_model(self): list_models = self.speech_to_text.list_acoustic_models().get_result() @@ -107,7 +107,7 @@ def on_transcription(self, transcript): def test_custom_grammars(self): customization_id = None - for custom_model in self.custom_models['customizations']: + for custom_model in self.custom_models.get('customizations'): if custom_model['name'] == 'integration_test_model_for_grammar': customization_id = custom_model['customization_id'] break diff --git a/test/integration/test_text_to_speech_v1.py b/test/integration/test_text_to_speech_v1.py index 6da05df7a..01806447a 100644 --- a/test/integration/test_text_to_speech_v1.py +++ b/test/integration/test_text_to_speech_v1.py @@ -28,7 +28,7 @@ def setup_class(cls): @classmethod def teardown_class(cls): - custid = cls.created_customization['customization_id'] + custid = cls.created_customization.get('customization_id') cls.text_to_speech.delete_voice_model(customization_id=custid) def test_voices(self): @@ -49,15 +49,15 @@ def test_pronunciation(self): assert output['pronunciation'] is not None def test_customizations(self): - old_length = len(self.original_customizations['customizations']) + old_length = len(self.original_customizations.get('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['customization_id'] + customization_id = self.created_customization.get('customization_id') words = self.text_to_speech.list_words(customization_id).get_result()['words'] - assert len(words) == 0 # pylint: disable=len-as-condition + assert not words self.text_to_speech.add_word( customization_id, word="ACLs", translation="ackles") From 351d24ecf2891161892f31f0465785ada3bca696 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Mon, 16 Sep 2019 14:58:59 -0700 Subject: [PATCH 077/455] chore(pylint): Update pylint to run on python 3.7 --- pylint.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pylint.sh b/pylint.sh index 906f3921b..ad71867fb 100644 --- a/pylint.sh +++ b/pylint.sh @@ -1,8 +1,8 @@ #!/bin/bash -# Runs pylint only for Python 2.7.X +# Runs pylint only for Python 3.7 PYTHON_VERSION=$(python -c 'import sys; print(".".join(map(str, sys.version_info[:2])))') echo "Python version: $PYTHON_VERSION" -if [ $PYTHON_VERSION = '2.7' ]; then +if [ $PYTHON_VERSION = '3.7' ]; then pylint ibm_watson test examples fi From 415233c556c19046a79ec4ec41866e15e38c2b17 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Mon, 16 Sep 2019 14:59:17 -0700 Subject: [PATCH 078/455] chore(python): remove unsupported python versions --- CONTRIBUTING.md | 2 +- tox.ini | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 60a21455b..3ac3a86ae 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -21,7 +21,7 @@ If you want to contribute to the repository, here's a quick guide: * Only use spaces for indentation. * Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change. * Check for unnecessary whitespace with `git diff --check` before committing. - * Make sure your code supports Python 2.7, 3.4, 3.5 and 3.6. You can use `pyenv` and `tox` for this + * Make sure your code supports Python 3.5, 3.6 and 3.7. You can use `pyenv` and `tox` for this 1. Make the test pass 1. Commit your changes * Commits should follow the [Angular commit message guidelines](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-commit-message-guidelines). This is because our release tool uses this format for determining release versions and generating changelogs. To make this easier, we recommend using the [Commitizen CLI](https://github.com/commitizen/cz-cli) with the `cz-conventional-changelog` adapter. diff --git a/tox.ini b/tox.ini index 1f0396717..f8e4d5efd 100644 --- a/tox.ini +++ b/tox.ini @@ -1,5 +1,5 @@ [tox] -envlist = lint, py27, py35, py36, py37 +envlist = lint, py35, py36, py37 [testenv:lint] basepython = python3.7 From c7f7ff136424d399054f6d087f7b7ab4c1f49eca Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 25 Sep 2019 11:09:39 -0700 Subject: [PATCH 079/455] test(vr3): remove detect faces --- test/integration/test_visual_recognition.py | 6 --- test/unit/test_visual_recognition_v3.py | 59 --------------------- 2 files changed, 65 deletions(-) diff --git a/test/integration/test_visual_recognition.py b/test/integration/test_visual_recognition.py index f08baa85c..b29ea31c1 100644 --- a/test/integration/test_visual_recognition.py +++ b/test/integration/test_visual_recognition.py @@ -31,12 +31,6 @@ def test_classify(self): classifier_ids=['default']).get_result() assert dog_results is not None - @pytest.mark.skip(reason="temporay disable") - def test_detect_faces(self): - output = self.visual_recognition.detect_faces( - url='https://www.ibm.com/ibm/ginni/images/ginni_bio_780x981_v4_03162016.jpg').get_result() - assert output is not None - @pytest.mark.skip(reason="Time consuming") def test_custom_classifier(self): with open(abspath('resources/cars.zip'), 'rb') as cars, \ diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index d56a94b67..d1e879ef5 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -47,7 +47,6 @@ def setUp(cls): def test_get_classifier(self): authenticator = IAMAuthenticator('bogusapikey') vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - gc_url = "{0}{1}".format(base_url, 'v3/classifiers/bogusnumber') response = { @@ -217,64 +216,6 @@ def test_classify(self): vr_service.classify(images_file=image_file) assert len(responses.calls) == 8 - @responses.activate - def test_detect_faces(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - - gc_url = "{0}{1}".format(base_url, 'v3/detect_faces') - - response = { - "images": [ - { - "faces": [ - { - "age": { - "max": 44, - "min": 35, - "score": 0.446989 - }, - "face_location": { - "height": 159, - "left": 256, - "top": 64, - "width": 92 - }, - "gender": { - "gender": "MALE", - "score": 0.99593 - }, - "identity": { - "name": "Barack Obama", - "score": 0.970688, - "type_hierarchy": "/people/politicians/democrats/barack obama" - } - } - ], - "resolved_url": "https://watson-developer-cloud.github.io/doc-tutorial-downloads/visual-recognition/prez.jpg", - "source_url": "https://watson-developer-cloud.github.io/doc-tutorial-downloads/visual-recognition/prez.jpg" - } - ], - "images_processed": 1 - } - - responses.add(responses.GET, - gc_url, - body=json.dumps(response), - status=200, - content_type='application/json') - - responses.add(responses.POST, - gc_url, - body=json.dumps(response), - status=200, - content_type='application/json') - - vr_service.detect_faces(parameters='{"url": "http://google.com"}') - with open(os.path.join(os.path.dirname(__file__), '../../resources/test.jpg'), 'rb') as image_file: - vr_service.detect_faces(images_file=image_file) - assert len(responses.calls) == 4 - @responses.activate def test_delete_user_data(self): url = "{0}{1}".format(base_url, 'v3/user_data') From 307b885d7a27c5c17d8a716548a943a05e25281c Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 25 Sep 2019 11:10:32 -0700 Subject: [PATCH 080/455] feat(visual recognition3): Regenerate vr3 --- ibm_watson/visual_recognition_v3.py | 809 ++++------------------------ 1 file changed, 108 insertions(+), 701 deletions(-) diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index e0b788cdf..ff8d0349e 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -15,8 +15,8 @@ # limitations under the License. """ The IBM Watson™ Visual Recognition service uses deep learning algorithms to identify -scenes, objects, and faces in images you upload to the service. You can create and train -a custom classifier to identify subjects that suit your needs. +scenes and objects in images that you upload to the service. You can create and train a +custom classifier to identify subjects that suit your needs. """ import json @@ -25,6 +25,7 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources from os.path import basename ############################################################################## @@ -35,14 +36,12 @@ class VisualRecognitionV3(BaseService): """The Visual Recognition V3 service.""" - default_url = 'https://gateway.watsonplatform.net/visual-recognition/api' + default_service_url = 'https://gateway.watsonplatform.net/visual-recognition/api' def __init__( self, version, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Visual Recognition service. @@ -58,26 +57,28 @@ def __init__( application, and don't change it until your application is ready for a later version. - :param str url: The base url to use when contacting the service (e.g. - "https://gateway.watsonplatform.net/visual-recognition/api/visual-recognition/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('visual_recognition') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: authenticator = get_authenticator_from_environment( - 'Visual Recognition') + 'visual_recognition') - BaseService.__init__( - self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Visual Recognition') + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) self.version = version ######################### @@ -174,95 +175,12 @@ def classify(self, 'application/json') url = '/v3/classify' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) - response = self.send(request) - return response - - ######################### - # Face - ######################### - - def detect_faces(self, - *, - images_file=None, - images_filename=None, - images_file_content_type=None, - url=None, - accept_language=None, - **kwargs): - """ - Detect faces in images. - - **Important:** On April 2, 2018, the identity information in the response to calls - to the Face model was removed. The identity information refers to the `name` of - the person, `score`, and `type_hierarchy` knowledge graph. For details about the - enhanced Face model, see the [Release - notes](https://cloud.ibm.com/docs/services/visual-recognition?topic=visual-recognition-release-notes#2april2018). - Analyze and get data about faces in images. Responses can include estimated age - and gender. This feature uses a built-in model, so no training is necessary. The - **Detect faces** method does not support general biometric facial recognition. - Supported image formats include .gif, .jpg, .png, and .tif. The maximum image size - is 10 MB. The minimum recommended pixel density is 32X32 pixels, but the service - tends to perform better with images that are at least 224 x 224 pixels. - - :param file images_file: (optional) An image file (gif, .jpg, .png, .tif.) - or .zip file with images. Limit the .zip file to 100 MB. You can include a - maximum of 15 images in a request. - Encode the image and .zip file names in UTF-8 if they contain non-ASCII - characters. The service assumes UTF-8 encoding if it encounters non-ASCII - characters. - You can also include an image with the **url** parameter. - :param str images_filename: (optional) The filename for images_file. - :param str images_file_content_type: (optional) The content type of - images_file. - :param str url: (optional) The URL of an image to analyze. Must be in .gif, - .jpg, .png, or .tif format. The minimum recommended pixel density is 32X32 - pixels, but the service tends to perform better with images that are at - least 224 x 224 pixels. The maximum image size is 10 MB. Redirects are - followed, so you can use a shortened URL. - You can also include images with the **images_file** parameter. - :param str accept_language: (optional) The desired language of parts of the - response. See the response for details. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - headers = {'Accept-Language': accept_language} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'detect_faces') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = {} - if images_file: - if not images_filename and hasattr(images_file, 'name'): - images_filename = basename(images_file.name) - if not images_filename: - raise ValueError('images_filename must be provided') - form_data['images_file'] = (images_filename, images_file, - images_file_content_type or - 'application/octet-stream') - if url: - form_data['url'] = (None, url, 'text/plain') - - url = '/v3/detect_faces' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -350,13 +268,12 @@ def create_classifier(self, 'application/octet-stream') url = '/v3/classifiers' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -381,12 +298,11 @@ def list_classifiers(self, *, verbose=None, **kwargs): params = {'version': self.version, 'verbose': verbose} url = '/v3/classifiers' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -416,12 +332,11 @@ def get_classifier(self, classifier_id, **kwargs): url = '/v3/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -507,13 +422,12 @@ def update_classifier(self, url = '/v3/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -541,12 +455,11 @@ def delete_classifier(self, classifier_id, **kwargs): url = '/v3/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -581,12 +494,11 @@ def get_core_ml_model(self, classifier_id, **kwargs): url = '/v3/classifiers/{0}/core_ml_model'.format( *self._encode_path_vars(classifier_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -625,12 +537,11 @@ def delete_user_data(self, customer_id, **kwargs): params = {'version': self.version, 'customer_id': customer_id} url = '/v3/user_data' - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -654,31 +565,12 @@ class AcceptLanguage(Enum): ZH_TW = 'zh-tw' -class DetectFacesEnums(object): - - class AcceptLanguage(Enum): - """ - The desired language of parts of the response. See the response for details. - """ - EN = 'en' - AR = 'ar' - DE = 'de' - ES = 'es' - FR = 'fr' - IT = 'it' - JA = 'ja' - KO = 'ko' - PT_BR = 'pt-br' - ZH_CN = 'zh-cn' - ZH_TW = 'zh-tw' - - ############################################################################## # Models ############################################################################## -class Class(object): +class Class(): """ A category within a classifier. @@ -697,12 +589,12 @@ def __init__(self, class_): def _from_dict(cls, _dict): """Initialize a Class object from a json dictionary.""" args = {} - validKeys = ['class_', 'class'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['class_', 'class'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Class: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'class' in _dict: args['class_'] = _dict.get('class') else: @@ -732,7 +624,7 @@ def __ne__(self, other): return not self == other -class ClassResult(object): +class ClassResult(): """ Result of a class within a classifier. @@ -777,12 +669,12 @@ def __init__(self, class_, score, *, type_hierarchy=None): def _from_dict(cls, _dict): """Initialize a ClassResult object from a json dictionary.""" args = {} - validKeys = ['class_', 'class', 'score', 'type_hierarchy'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['class_', 'class', 'score', 'type_hierarchy'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ClassResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'class' in _dict: args['class_'] = _dict.get('class') else: @@ -823,7 +715,7 @@ def __ne__(self, other): return not self == other -class ClassifiedImage(object): +class ClassifiedImage(): """ Results for one image. @@ -870,14 +762,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a ClassifiedImage object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'source_url', 'resolved_url', 'image', 'error', 'classifiers' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ClassifiedImage: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'source_url' in _dict: args['source_url'] = _dict.get('source_url') if 'resolved_url' in _dict: @@ -927,7 +819,7 @@ def __ne__(self, other): return not self == other -class ClassifiedImages(object): +class ClassifiedImages(): """ Results for all images. @@ -970,12 +862,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a ClassifiedImages object from a json dictionary.""" args = {} - validKeys = ['custom_classes', 'images_processed', 'images', 'warnings'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = [ + 'custom_classes', 'images_processed', 'images', 'warnings' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ClassifiedImages: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'custom_classes' in _dict: args['custom_classes'] = _dict.get('custom_classes') if 'images_processed' in _dict: @@ -1023,7 +917,7 @@ def __ne__(self, other): return not self == other -class Classifier(object): +class Classifier(): """ Information about a classifier. @@ -1097,15 +991,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Classifier object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'classifier_id', 'name', 'owner', 'status', 'core_ml_enabled', 'explanation', 'created', 'classes', 'retrained', 'updated' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Classifier: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') else: @@ -1187,7 +1081,7 @@ class StatusEnum(Enum): FAILED = "failed" -class ClassifierResult(object): +class ClassifierResult(): """ Classifier and score combination. @@ -1212,12 +1106,12 @@ def __init__(self, name, classifier_id, classes): def _from_dict(cls, _dict): """Initialize a ClassifierResult object from a json dictionary.""" args = {} - validKeys = ['name', 'classifier_id', 'classes'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['name', 'classifier_id', 'classes'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ClassifierResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -1266,7 +1160,7 @@ def __ne__(self, other): return not self == other -class Classifiers(object): +class Classifiers(): """ A container for the list of classifiers. @@ -1285,12 +1179,12 @@ def __init__(self, classifiers): def _from_dict(cls, _dict): """Initialize a Classifiers object from a json dictionary.""" args = {} - validKeys = ['classifiers'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['classifiers'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Classifiers: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'classifiers' in _dict: args['classifiers'] = [ Classifier._from_dict(x) for x in (_dict.get('classifiers')) @@ -1323,91 +1217,7 @@ def __ne__(self, other): return not self == other -class DetectedFaces(object): - """ - Results for all faces. - - :attr int images_processed: Number of images processed for the API call. - :attr list[ImageWithFaces] images: The images. - :attr list[WarningInfo] warnings: (optional) Information about what might cause - less than optimal output. For example, a request sent with a corrupt .zip file - and a list of image URLs will still complete, but does not return the expected - output. Not returned when there is no warning. - """ - - def __init__(self, images_processed, images, *, warnings=None): - """ - Initialize a DetectedFaces object. - - :param int images_processed: Number of images processed for the API call. - :param list[ImageWithFaces] images: The images. - :param list[WarningInfo] warnings: (optional) Information about what might - cause less than optimal output. For example, a request sent with a corrupt - .zip file and a list of image URLs will still complete, but does not return - the expected output. Not returned when there is no warning. - """ - self.images_processed = images_processed - self.images = images - self.warnings = warnings - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DetectedFaces object from a json dictionary.""" - args = {} - validKeys = ['images_processed', 'images', 'warnings'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DetectedFaces: ' - + ', '.join(badKeys)) - if 'images_processed' in _dict: - args['images_processed'] = _dict.get('images_processed') - else: - raise ValueError( - 'Required property \'images_processed\' not present in DetectedFaces JSON' - ) - if 'images' in _dict: - args['images'] = [ - ImageWithFaces._from_dict(x) for x in (_dict.get('images')) - ] - else: - raise ValueError( - 'Required property \'images\' not present in DetectedFaces JSON' - ) - if 'warnings' in _dict: - args['warnings'] = [ - WarningInfo._from_dict(x) for x in (_dict.get('warnings')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, - 'images_processed') and self.images_processed is not None: - _dict['images_processed'] = self.images_processed - if hasattr(self, 'images') and self.images is not None: - _dict['images'] = [x._to_dict() for x in self.images] - if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x._to_dict() for x in self.warnings] - return _dict - - def __str__(self): - """Return a `str` version of this DetectedFaces object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ErrorInfo(object): +class ErrorInfo(): """ Information about what might have caused a failure, such as an image that is too large. Not returned when there is no error. @@ -1435,12 +1245,12 @@ def __init__(self, code, description, error_id): def _from_dict(cls, _dict): """Initialize a ErrorInfo object from a json dictionary.""" args = {} - validKeys = ['code', 'description', 'error_id'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['code', 'description', 'error_id'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ErrorInfo: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'code' in _dict: args['code'] = _dict.get('code') else: @@ -1485,410 +1295,7 @@ def __ne__(self, other): return not self == other -class Face(object): - """ - Information about the face. - - :attr FaceAge age: (optional) Age information about a face. - :attr FaceGender gender: (optional) Information about the gender of the face. - :attr FaceLocation face_location: (optional) The location of the bounding box - around the face. - """ - - def __init__(self, *, age=None, gender=None, face_location=None): - """ - Initialize a Face object. - - :param FaceAge age: (optional) Age information about a face. - :param FaceGender gender: (optional) Information about the gender of the - face. - :param FaceLocation face_location: (optional) The location of the bounding - box around the face. - """ - self.age = age - self.gender = gender - self.face_location = face_location - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Face object from a json dictionary.""" - args = {} - validKeys = ['age', 'gender', 'face_location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Face: ' + - ', '.join(badKeys)) - if 'age' in _dict: - args['age'] = FaceAge._from_dict(_dict.get('age')) - if 'gender' in _dict: - args['gender'] = FaceGender._from_dict(_dict.get('gender')) - if 'face_location' in _dict: - args['face_location'] = FaceLocation._from_dict( - _dict.get('face_location')) - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'age') and self.age is not None: - _dict['age'] = self.age._to_dict() - if hasattr(self, 'gender') and self.gender is not None: - _dict['gender'] = self.gender._to_dict() - if hasattr(self, 'face_location') and self.face_location is not None: - _dict['face_location'] = self.face_location._to_dict() - return _dict - - def __str__(self): - """Return a `str` version of this Face object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class FaceAge(object): - """ - Age information about a face. - - :attr int min: (optional) Estimated minimum age. - :attr int max: (optional) Estimated maximum age. - :attr float score: Confidence score in the range of 0 to 1. A higher score - indicates greater confidence in the estimated value for the property. - """ - - def __init__(self, score, *, min=None, max=None): - """ - Initialize a FaceAge object. - - :param float score: Confidence score in the range of 0 to 1. A higher score - indicates greater confidence in the estimated value for the property. - :param int min: (optional) Estimated minimum age. - :param int max: (optional) Estimated maximum age. - """ - self.min = min - self.max = max - self.score = score - - @classmethod - def _from_dict(cls, _dict): - """Initialize a FaceAge object from a json dictionary.""" - args = {} - validKeys = ['min', 'max', 'score'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class FaceAge: ' + - ', '.join(badKeys)) - if 'min' in _dict: - args['min'] = _dict.get('min') - if 'max' in _dict: - args['max'] = _dict.get('max') - if 'score' in _dict: - args['score'] = _dict.get('score') - else: - raise ValueError( - 'Required property \'score\' not present in FaceAge JSON') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'min') and self.min is not None: - _dict['min'] = self.min - if hasattr(self, 'max') and self.max is not None: - _dict['max'] = self.max - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score - return _dict - - def __str__(self): - """Return a `str` version of this FaceAge object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class FaceGender(object): - """ - Information about the gender of the face. - - :attr str gender: Gender identified by the face. For example, `MALE` or - `FEMALE`. - :attr str gender_label: The word for "male" or "female" in the language defined - by the **Accept-Language** request header. - :attr float score: Confidence score in the range of 0 to 1. A higher score - indicates greater confidence in the estimated value for the property. - """ - - def __init__(self, gender, gender_label, score): - """ - Initialize a FaceGender object. - - :param str gender: Gender identified by the face. For example, `MALE` or - `FEMALE`. - :param str gender_label: The word for "male" or "female" in the language - defined by the **Accept-Language** request header. - :param float score: Confidence score in the range of 0 to 1. A higher score - indicates greater confidence in the estimated value for the property. - """ - self.gender = gender - self.gender_label = gender_label - self.score = score - - @classmethod - def _from_dict(cls, _dict): - """Initialize a FaceGender object from a json dictionary.""" - args = {} - validKeys = ['gender', 'gender_label', 'score'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class FaceGender: ' - + ', '.join(badKeys)) - if 'gender' in _dict: - args['gender'] = _dict.get('gender') - else: - raise ValueError( - 'Required property \'gender\' not present in FaceGender JSON') - if 'gender_label' in _dict: - args['gender_label'] = _dict.get('gender_label') - else: - raise ValueError( - 'Required property \'gender_label\' not present in FaceGender JSON' - ) - if 'score' in _dict: - args['score'] = _dict.get('score') - else: - raise ValueError( - 'Required property \'score\' not present in FaceGender JSON') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'gender') and self.gender is not None: - _dict['gender'] = self.gender - if hasattr(self, 'gender_label') and self.gender_label is not None: - _dict['gender_label'] = self.gender_label - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score - return _dict - - def __str__(self): - """Return a `str` version of this FaceGender object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class FaceLocation(object): - """ - The location of the bounding box around the face. - - :attr float width: Width in pixels of face region. - :attr float height: Height in pixels of face region. - :attr float left: X-position of top-left pixel of face region. - :attr float top: Y-position of top-left pixel of face region. - """ - - def __init__(self, width, height, left, top): - """ - Initialize a FaceLocation object. - - :param float width: Width in pixels of face region. - :param float height: Height in pixels of face region. - :param float left: X-position of top-left pixel of face region. - :param float top: Y-position of top-left pixel of face region. - """ - self.width = width - self.height = height - self.left = left - self.top = top - - @classmethod - def _from_dict(cls, _dict): - """Initialize a FaceLocation object from a json dictionary.""" - args = {} - validKeys = ['width', 'height', 'left', 'top'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class FaceLocation: ' - + ', '.join(badKeys)) - if 'width' in _dict: - args['width'] = _dict.get('width') - else: - raise ValueError( - 'Required property \'width\' not present in FaceLocation JSON') - if 'height' in _dict: - args['height'] = _dict.get('height') - else: - raise ValueError( - 'Required property \'height\' not present in FaceLocation JSON') - if 'left' in _dict: - args['left'] = _dict.get('left') - else: - raise ValueError( - 'Required property \'left\' not present in FaceLocation JSON') - if 'top' in _dict: - args['top'] = _dict.get('top') - else: - raise ValueError( - 'Required property \'top\' not present in FaceLocation JSON') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'width') and self.width is not None: - _dict['width'] = self.width - if hasattr(self, 'height') and self.height is not None: - _dict['height'] = self.height - if hasattr(self, 'left') and self.left is not None: - _dict['left'] = self.left - if hasattr(self, 'top') and self.top is not None: - _dict['top'] = self.top - return _dict - - def __str__(self): - """Return a `str` version of this FaceLocation object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ImageWithFaces(object): - """ - Information about faces in the image. - - :attr list[Face] faces: Faces detected in the images. - :attr str image: (optional) Relative path of the image file if uploaded - directly. Not returned when the image is passed by URL. - :attr str source_url: (optional) Source of the image before any redirects. Not - returned when the image is uploaded. - :attr str resolved_url: (optional) Fully resolved URL of the image after - redirects are followed. Not returned when the image is uploaded. - :attr ErrorInfo error: (optional) Information about what might have caused a - failure, such as an image that is too large. Not returned when there is no - error. - """ - - def __init__(self, - faces, - *, - image=None, - source_url=None, - resolved_url=None, - error=None): - """ - Initialize a ImageWithFaces object. - - :param list[Face] faces: Faces detected in the images. - :param str image: (optional) Relative path of the image file if uploaded - directly. Not returned when the image is passed by URL. - :param str source_url: (optional) Source of the image before any redirects. - Not returned when the image is uploaded. - :param str resolved_url: (optional) Fully resolved URL of the image after - redirects are followed. Not returned when the image is uploaded. - :param ErrorInfo error: (optional) Information about what might have caused - a failure, such as an image that is too large. Not returned when there is - no error. - """ - self.faces = faces - self.image = image - self.source_url = source_url - self.resolved_url = resolved_url - self.error = error - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ImageWithFaces object from a json dictionary.""" - args = {} - validKeys = ['faces', 'image', 'source_url', 'resolved_url', 'error'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ImageWithFaces: ' - + ', '.join(badKeys)) - if 'faces' in _dict: - args['faces'] = [Face._from_dict(x) for x in (_dict.get('faces'))] - else: - raise ValueError( - 'Required property \'faces\' not present in ImageWithFaces JSON' - ) - if 'image' in _dict: - args['image'] = _dict.get('image') - if 'source_url' in _dict: - args['source_url'] = _dict.get('source_url') - if 'resolved_url' in _dict: - args['resolved_url'] = _dict.get('resolved_url') - if 'error' in _dict: - args['error'] = ErrorInfo._from_dict(_dict.get('error')) - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'faces') and self.faces is not None: - _dict['faces'] = [x._to_dict() for x in self.faces] - if hasattr(self, 'image') and self.image is not None: - _dict['image'] = self.image - if hasattr(self, 'source_url') and self.source_url is not None: - _dict['source_url'] = self.source_url - if hasattr(self, 'resolved_url') and self.resolved_url is not None: - _dict['resolved_url'] = self.resolved_url - if hasattr(self, 'error') and self.error is not None: - _dict['error'] = self.error._to_dict() - return _dict - - def __str__(self): - """Return a `str` version of this ImageWithFaces object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class WarningInfo(object): +class WarningInfo(): """ Information about something that went wrong. @@ -1910,12 +1317,12 @@ def __init__(self, warning_id, description): def _from_dict(cls, _dict): """Initialize a WarningInfo object from a json dictionary.""" args = {} - validKeys = ['warning_id', 'description'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['warning_id', 'description'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class WarningInfo: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'warning_id' in _dict: args['warning_id'] = _dict.get('warning_id') else: From 05c711702cac15bfce863276b00e6576e419fd04 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 27 Sep 2019 13:10:28 -0700 Subject: [PATCH 081/455] fix(ws): Move customization_weight as part of message --- ibm_watson/speech_to_text_v1_adapter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 6448829e3..b7660743b 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -226,7 +226,6 @@ def recognize_using_websocket(self, 'model': model, 'customization_id': customization_id, 'acoustic_customization_id': acoustic_customization_id, - 'customization_weight': customization_weight, 'base_model_version': base_model_version, 'language_customization_id': language_customization_id } @@ -234,6 +233,7 @@ def recognize_using_websocket(self, url += '/v1/recognize?{0}'.format(urlencode(params)) options = { + 'customization_weight': customization_weight, 'content_type': content_type, 'inactivity_timeout': inactivity_timeout, 'interim_results': interim_results, From 6a607c6a1c2e92ee7bcb6135c2fe05d2b2b3f2aa Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 27 Sep 2019 21:03:51 +0000 Subject: [PATCH 082/455] =?UTF-8?q?Bump=20version:=203.4.0=20=E2=86=92=203?= =?UTF-8?q?.4.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index a8038f476..24b4b4b92 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 3.4.0 +current_version = 3.4.1 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index f63100763..da4564dd6 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '3.4.0' +__version__ = '3.4.1' diff --git a/setup.py b/setup.py index ef4727eda..84a25409b 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ import os import sys -__version__ = '3.4.0' +__version__ = '3.4.1' if sys.argv[-1] == 'publish': # test server From c087917d55280e81f66f1350d9583204b522ff1b Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 1 Oct 2019 10:10:34 -0700 Subject: [PATCH 083/455] feat(visual recongition): New version v4 in visual recognition --- examples/visual_recognition_v4.py | 41 + ibm_watson/__init__.py | 1 + ibm_watson/visual_recognition_v4.py | 2693 +++++++++++++++++ .../integration/test_visual_recognition_v4.py | 126 + test/unit/test_visual_recognition_v4.py | 853 ++++++ 5 files changed, 3714 insertions(+) create mode 100644 examples/visual_recognition_v4.py create mode 100644 ibm_watson/visual_recognition_v4.py create mode 100644 test/integration/test_visual_recognition_v4.py create mode 100644 test/unit/test_visual_recognition_v4.py diff --git a/examples/visual_recognition_v4.py b/examples/visual_recognition_v4.py new file mode 100644 index 000000000..116e7b932 --- /dev/null +++ b/examples/visual_recognition_v4.py @@ -0,0 +1,41 @@ +import json +import os +from ibm_watson import VisualRecognitionV4 +from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata, BaseObject, Location +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator + +authenticator = IAMAuthenticator('') +service = VisualRecognitionV4( + '2018-03-19', + authenticator=authenticator) +service.set_service_url('https://gateway.watsonplatform.net/visual-recognition/api') + +# create a classifier +my_collection = service.create_collection( + name='', + description='tetsing for python' +).get_result() +collection_id = my_collection.get('collection_id') + +# add images +with open(os.path.join(os.path.dirname(__file__), '../resources/South_Africa_Luca_Galuzzi_2004.jpg'), 'rb') as giraffe_info: + add_images_result = service.add_images( + collection_id, + images_file=[FileWithMetadata(giraffe_info)], + ).get_result() +print(json.dumps(add_images_result, indent=2)) +image_id = add_images_result.get('images')[0].get('image_id') + +# add image training data +training_data = service.add_image_training_data( + collection_id, + image_id, + objects=[ + BaseObject(object='giraffe training data', location=Location(64, 270, 755, 784)) + ]).get_result() + +# train collection +train_result = service.train(collection_id).get_result() + +# delete collection +service.delete_collection(collection_id) \ No newline at end of file diff --git a/ibm_watson/__init__.py b/ibm_watson/__init__.py index 56d7b7d29..8b757e30e 100755 --- a/ibm_watson/__init__.py +++ b/ibm_watson/__init__.py @@ -30,3 +30,4 @@ from .common import get_sdk_headers from .speech_to_text_v1_adapter import SpeechToTextV1Adapter as SpeechToTextV1 from .text_to_speech_adapter_v1 import TextToSpeechV1Adapter as TextToSpeechV1 +from .visual_recognition_v4 import VisualRecognitionV4 diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py new file mode 100644 index 000000000..18ea1507b --- /dev/null +++ b/ibm_watson/visual_recognition_v4.py @@ -0,0 +1,2693 @@ +# coding: utf-8 + +# (C) Copyright IBM Corp. 2019. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Provide images to the IBM Watson™ Visual Recognition service for analysis. The +service detects objects based on a set of images with training data. +**Beta:** The Visual Recognition v4 API and Object Detection model are beta features. For +more information about beta features, see the [Release +notes](https://cloud.ibm.com/docs/services/visual-recognition?topic=visual-recognition-release-notes#beta). +{: important} +""" + +import json +from .common import get_sdk_headers +from enum import Enum +from ibm_cloud_sdk_core import BaseService +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 import read_external_sources +from os.path import basename + +############################################################################## +# Service +############################################################################## + + +class VisualRecognitionV4(BaseService): + """The Visual Recognition V4 service.""" + + default_service_url = 'https://gateway.watsonplatform.net/visual-recognition/api' + + def __init__( + self, + version, + authenticator=None, + ): + """ + Construct a new client for the Visual Recognition service. + + :param str version: The API version date to use with the service, in + "YYYY-MM-DD" format. Whenever the API is changed in a backwards + incompatible way, a new minor version of the API is released. + The service uses the API version for the date you specify, or + the most recent version before that date. Note that you should + not programmatically specify the current date at runtime, in + case the API has been updated since your application's release. + Instead, specify a version date that is compatible with your + application, and don't change it until your application is + ready for a later version. + + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + """ + + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('visual_recognition') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + + if not authenticator: + authenticator = get_authenticator_from_environment( + 'visual_recognition') + + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) + self.version = version + + ######################### + # Analysis + ######################### + + def analyze(self, + collection_ids, + features, + *, + images_file=None, + image_url=None, + threshold=None, + **kwargs): + """ + Analyze images. + + Analyze images by URL, by file, or both against your own collection. Make sure + that **training_status.objects.ready** is `true` for the feature before you use a + collection to analyze images. + Encode the image and .zip file names in UTF-8 if they contain non-ASCII + characters. The service assumes UTF-8 encoding if it encounters non-ASCII + characters. + + :param str collection_ids: The IDs of the collections to analyze. Separate + multiple values with commas. + :param str features: The features to analyze. Separate multiple values with + commas. + :param list[FileWithMetadata] images_file: (optional) An image file (.jpg + or .png) or .zip file with images. + - Include a maximum of 20 images in a request. + - Limit the .zip file to 100 MB. + - You can provide multiple separate image files by including this form + field multiple times. + - Limit each image file to 10 MB. + You can also include an image with the **image_url** parameter. + :param list[str] image_url: (optional) The URL of an image (.jpg or .png). + - You can provide multiple separate image URLs by including this form field + multiple times. Include a maximum of 20 images in a request. + - Limit each image file to 10 MB. + - Minimum width and height is 30 pixels, but the service tends to perform + better with images that are at least 300 x 300 pixels. Maximum is 5400 + pixels for either height or width. + You can also include images with the **images_url** parameter. + :param float threshold: (optional) The minimum score a feature must have to + be returned. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if collection_ids is None: + raise ValueError('collection_ids must be provided') + if features is None: + raise ValueError('features must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', 'analyze') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + form_data.append( + ('collection_ids', (None, collection_ids, 'text/plain'))) + form_data.append(('features', (None, features, 'text/plain'))) + if images_file: + for item in images_file: + form_data.append(('images_file', (item.filename, item.data, + item.content_type or + 'application/octet-stream'))) + if image_url: + for item in image_url: + form_data.append(('image_url', (None, item, 'text/plain'))) + if threshold: + form_data.append( + ('threshold', (None, threshold, 'application/json'))) + + url = '/v4/analyze' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) + response = self.send(request) + return response + + ######################### + # Collections + ######################### + + def create_collection(self, + *, + name=None, + description=None, + training_status=None, + **kwargs): + """ + Create a collection. + + Create a collection that can be used to store images. + To create a collection without specifying a name and description, include an empty + JSON object in the request body. + Encode the name and description in UTF-8 if they contain non-ASCII characters. The + service assumes UTF-8 encoding if it encounters non-ASCII characters. + + :param str name: (optional) The name of the collection. The name can + contain alphanumeric, underscore, hyphen, and dot characters. It cannot + begin with the reserved prefix `sys-`. + :param str description: (optional) The description of the collection. + :param BaseCollectionTrainingStatus training_status: (optional) Training + status information for 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 training_status is not None: + training_status = self._convert_model(training_status) + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', + 'create_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'name': name, + 'description': description, + 'training_status': training_status + } + + url = '/v4/collections' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) + response = self.send(request) + return response + + def list_collections(self, **kwargs): + """ + List collections. + + Retrieves a list of collections for the service instance. + + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', + 'list_collections') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v4/collections' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + def get_collection(self, collection_id, **kwargs): + """ + Get collection details. + + Get details of one 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('watson_vision_combined', 'V4', + 'get_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v4/collections/{0}'.format( + *self._encode_path_vars(collection_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + def update_collection(self, + collection_id, + *, + name=None, + description=None, + training_status=None, + **kwargs): + """ + Update a collection. + + Update the name or description of a collection. + Encode the name and description in UTF-8 if they contain non-ASCII characters. The + service assumes UTF-8 encoding if it encounters non-ASCII characters. + + :param str collection_id: The identifier of the collection. + :param str name: (optional) The name of the collection. The name can + contain alphanumeric, underscore, hyphen, and dot characters. It cannot + begin with the reserved prefix `sys-`. + :param str description: (optional) The description of the collection. + :param BaseCollectionTrainingStatus training_status: (optional) Training + status information for 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') + if training_status is not None: + training_status = self._convert_model(training_status) + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', + 'update_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'name': name, + 'description': description, + 'training_status': training_status + } + + url = '/v4/collections/{0}'.format( + *self._encode_path_vars(collection_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) + response = self.send(request) + return response + + def delete_collection(self, collection_id, **kwargs): + """ + Delete a collection. + + Delete a collection from the service instance. + + :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('watson_vision_combined', 'V4', + 'delete_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v4/collections/{0}'.format( + *self._encode_path_vars(collection_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + ######################### + # Images + ######################### + + def add_images(self, + collection_id, + *, + images_file=None, + image_url=None, + training_data=None, + **kwargs): + """ + Add images. + + Add images to a collection by URL, by file, or both. + Encode the image and .zip file names in UTF-8 if they contain non-ASCII + characters. The service assumes UTF-8 encoding if it encounters non-ASCII + characters. + + :param str collection_id: The identifier of the collection. + :param list[FileWithMetadata] images_file: (optional) An image file (.jpg + or .png) or .zip file with images. + - You can provide multiple separate image files by including this form + field multiple times. + - Limit each image file to 10 MB. + - Include a maximum of 100 images in a request. + - Limit the .zip file to 100 MB. + -Minimum width and height is 30 pixels, but the service tends to perform + better with images that are at least 300 x 300 pixels. Maximum is 5400 + pixels for either height or width. + You can also include an image with the **image_url** parameter. + :param list[str] image_url: (optional) The URL of an image (.jpg or .png). + - You can provide multiple separate image URLs by including this form field + multiple times. Include a maximum of 20 images in a request. + - Limit each image file to 10 MB. + - Minimum width and height is 30 pixels, but the service tends to perform + better with images that are at least 300 x 300 pixels. Maximum is 5400 + pixels for either height or width. + You can also include images with the **images_url** parameter. + :param str training_data: (optional) Training data for a single image. + Include training data only if you add one image with the request. + The `object` property can contain alphanumeric, underscore, hyphen, space, + and dot characters. It cannot begin with the reserved prefix `sys-` and + must be no longer than 32 characters. + :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('watson_vision_combined', 'V4', + 'add_images') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + if images_file: + for item in images_file: + form_data.append(('images_file', (item.filename, item.data, + item.content_type or + 'application/octet-stream'))) + if image_url: + for item in image_url: + form_data.append(('image_url', (None, item, 'text/plain'))) + if training_data: + form_data.append( + ('training_data', (None, training_data, 'text/plain'))) + + url = '/v4/collections/{0}/images'.format( + *self._encode_path_vars(collection_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) + response = self.send(request) + return response + + def list_images(self, collection_id, **kwargs): + """ + List images. + + Retrieves a list of images 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('watson_vision_combined', 'V4', + 'list_images') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v4/collections/{0}/images'.format( + *self._encode_path_vars(collection_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + def get_image_details(self, collection_id, image_id, **kwargs): + """ + Get image details. + + Get the details of an image in a collection. + + :param str collection_id: The identifier of the collection. + :param str image_id: The identifier of the image. + :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 image_id is None: + raise ValueError('image_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', + 'get_image_details') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v4/collections/{0}/images/{1}'.format( + *self._encode_path_vars(collection_id, image_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + def delete_image(self, collection_id, image_id, **kwargs): + """ + Delete an image. + + Delete one image from a collection. + + :param str collection_id: The identifier of the collection. + :param str image_id: The identifier of the image. + :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 image_id is None: + raise ValueError('image_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', + 'delete_image') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v4/collections/{0}/images/{1}'.format( + *self._encode_path_vars(collection_id, image_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + def get_jpeg_image(self, collection_id, image_id, *, size=None, **kwargs): + """ + Get a JPEG file of an image. + + Download a JPEG representation of an image. + + :param str collection_id: The identifier of the collection. + :param str image_id: The identifier of the image. + :param str size: (optional) Specify the image size. + :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 image_id is None: + raise ValueError('image_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', + 'get_jpeg_image') + headers.update(sdk_headers) + + params = {'version': self.version, 'size': size} + + url = '/v4/collections/{0}/images/{1}/jpeg'.format( + *self._encode_path_vars(collection_id, image_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=False) + response = self.send(request) + return response + + ######################### + # Training + ######################### + + def train(self, collection_id, **kwargs): + """ + Train a collection. + + Start training on images in a collection. The collection must have enough training + data and untrained data (the **training_status.objects.data_changed** is `true`). + If training is in progress, the request queues the next training job. + + :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('watson_vision_combined', 'V4', 'train') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v4/collections/{0}/train'.format( + *self._encode_path_vars(collection_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + def add_image_training_data(self, + collection_id, + image_id, + *, + objects=None, + **kwargs): + """ + Add training data to an image. + + Add, update, or delete training data for an image. Encode the object name in UTF-8 + if it contains non-ASCII characters. The service assumes UTF-8 encoding if it + encounters non-ASCII characters. + Elements in the request replace the existing elements. + - To update the training data, provide both the unchanged and the new or changed + values. + - To delete the training data, provide an empty value for the training data. + + :param str collection_id: The identifier of the collection. + :param str image_id: The identifier of the image. + :param list[BaseObject] objects: (optional) Training data for specific + objects. + :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 image_id is None: + raise ValueError('image_id must be provided') + if objects is not None: + objects = [self._convert_model(x) for x in objects] + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', + 'add_image_training_data') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'objects': objects} + + url = '/v4/collections/{0}/images/{1}/training_data'.format( + *self._encode_path_vars(collection_id, image_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) + response = self.send(request) + return response + + ######################### + # User data + ######################### + + def delete_user_data(self, customer_id, **kwargs): + """ + Delete labeled data. + + Deletes all data associated with a specified customer ID. The method has no effect + if no data is associated with the customer ID. + 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). + + :param str customer_id: The customer ID for which all data is to be + deleted. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if customer_id is None: + raise ValueError('customer_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', + 'delete_user_data') + headers.update(sdk_headers) + + params = {'version': self.version, 'customer_id': customer_id} + + url = '/v4/user_data' + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + +class AnalyzeEnums(object): + + class Features(Enum): + """ + The features to analyze. Separate multiple values with commas. + """ + OBJECTS = 'objects' + + +class GetJpegImageEnums(object): + + class Size(Enum): + """ + Specify the image size. + """ + FULL = 'full' + + +############################################################################## +# Models +############################################################################## + + +class AnalyzeResponse(): + """ + Results for all images. + + :attr list[Image] images: Analyzed images. + :attr list[BaseError] warnings: (optional) Information about what might cause + less than optimal output. + :attr str trace: (optional) A unique identifier of the request. Included only + when an error or warning is returned. + """ + + def __init__(self, images, *, warnings=None, trace=None): + """ + Initialize a AnalyzeResponse object. + + :param list[Image] images: Analyzed images. + :param list[BaseError] warnings: (optional) Information about what might + cause less than optimal output. + :param str trace: (optional) A unique identifier of the request. Included + only when an error or warning is returned. + """ + self.images = images + self.warnings = warnings + self.trace = trace + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalyzeResponse object from a json dictionary.""" + args = {} + valid_keys = ['images', 'warnings', 'trace'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class AnalyzeResponse: ' + + ', '.join(bad_keys)) + if 'images' in _dict: + args['images'] = [ + Image._from_dict(x) for x in (_dict.get('images')) + ] + else: + raise ValueError( + 'Required property \'images\' not present in AnalyzeResponse JSON' + ) + if 'warnings' in _dict: + args['warnings'] = [ + BaseError._from_dict(x) for x in (_dict.get('warnings')) + ] + if 'trace' in _dict: + args['trace'] = _dict.get('trace') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'images') and self.images is not None: + _dict['images'] = [x._to_dict() for x in self.images] + if hasattr(self, 'warnings') and self.warnings is not None: + _dict['warnings'] = [x._to_dict() for x in self.warnings] + if hasattr(self, 'trace') and self.trace is not None: + _dict['trace'] = self.trace + return _dict + + def __str__(self): + """Return a `str` version of this AnalyzeResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class BaseCollection(): + """ + Base details about a collection. + + :attr str collection_id: (optional) The identifier of the collection. + :attr str name: (optional) The name of the collection. The name can contain + alphanumeric, underscore, hyphen, and dot characters. It cannot begin with the + reserved prefix `sys-`. + :attr str description: (optional) The description of the collection. + :attr datetime created: (optional) Date and time in Coordinated Universal Time + (UTC) that the collection was created. + :attr datetime updated: (optional) Date and time in Coordinated Universal Time + (UTC) that the collection was most recently updated. + :attr int image_count: (optional) Number of images in the collection. + :attr BaseCollectionTrainingStatus training_status: (optional) Training status + information for the collection. + """ + + def __init__(self, + *, + collection_id=None, + name=None, + description=None, + created=None, + updated=None, + image_count=None, + training_status=None): + """ + Initialize a BaseCollection object. + + :param str collection_id: (optional) The identifier of the collection. + :param str name: (optional) The name of the collection. The name can + contain alphanumeric, underscore, hyphen, and dot characters. It cannot + begin with the reserved prefix `sys-`. + :param str description: (optional) The description of the collection. + :param datetime created: (optional) Date and time in Coordinated Universal + Time (UTC) that the collection was created. + :param datetime updated: (optional) Date and time in Coordinated Universal + Time (UTC) that the collection was most recently updated. + :param int image_count: (optional) Number of images in the collection. + :param BaseCollectionTrainingStatus training_status: (optional) Training + status information for the collection. + """ + self.collection_id = collection_id + self.name = name + self.description = description + self.created = created + self.updated = updated + self.image_count = image_count + self.training_status = training_status + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BaseCollection object from a json dictionary.""" + args = {} + valid_keys = [ + 'collection_id', 'name', 'description', 'created', 'updated', + 'image_count', 'training_status' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class BaseCollection: ' + + ', '.join(bad_keys)) + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + if 'image_count' in _dict: + args['image_count'] = _dict.get('image_count') + if 'training_status' in _dict: + args['training_status'] = BaseCollectionTrainingStatus._from_dict( + _dict.get('training_status')) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'updated') and self.updated is not None: + _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'image_count') and self.image_count is not None: + _dict['image_count'] = self.image_count + if hasattr(self, + 'training_status') and self.training_status is not None: + _dict['training_status'] = self.training_status._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this BaseCollection object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class BaseCollectionTrainingStatus(): + """ + Training status information for the collection. + + :attr ObjectTrainingStatus objects: Training status for the objects in the + collection. + """ + + def __init__(self, objects): + """ + Initialize a BaseCollectionTrainingStatus object. + + :param ObjectTrainingStatus objects: Training status for the objects in the + collection. + """ + self.objects = objects + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BaseCollectionTrainingStatus object from a json dictionary.""" + args = {} + valid_keys = ['objects'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class BaseCollectionTrainingStatus: ' + + ', '.join(bad_keys)) + if 'objects' in _dict: + args['objects'] = ObjectTrainingStatus._from_dict( + _dict.get('objects')) + else: + raise ValueError( + 'Required property \'objects\' not present in BaseCollectionTrainingStatus JSON' + ) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'objects') and self.objects is not None: + _dict['objects'] = self.objects._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this BaseCollectionTrainingStatus object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class BaseError(): + """ + Details about a problem. + + :attr str code: Identifier of the problem. + :attr str message: An explanation of the problem with possible solutions. + :attr str more_info: (optional) A URL for more information about the solution. + """ + + def __init__(self, code, message, *, more_info=None): + """ + Initialize a BaseError object. + + :param str code: Identifier of the problem. + :param str message: An explanation of the problem with possible solutions. + :param str more_info: (optional) A URL for more information about the + solution. + """ + self.code = code + self.message = message + self.more_info = more_info + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BaseError object from a json dictionary.""" + args = {} + valid_keys = ['code', 'message', 'more_info'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class BaseError: ' + + ', '.join(bad_keys)) + if 'code' in _dict: + args['code'] = _dict.get('code') + else: + raise ValueError( + 'Required property \'code\' not present in BaseError JSON') + if 'message' in _dict: + args['message'] = _dict.get('message') + else: + raise ValueError( + 'Required property \'message\' not present in BaseError JSON') + if 'more_info' in _dict: + args['more_info'] = _dict.get('more_info') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + if hasattr(self, 'more_info') and self.more_info is not None: + _dict['more_info'] = self.more_info + return _dict + + def __str__(self): + """Return a `str` version of this BaseError object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class CodeEnum(Enum): + """ + Identifier of the problem. + """ + INVALID_FIELD = "invalid_field" + INVALID_HEADER = "invalid_header" + INVALID_METHOD = "invalid_method" + MISSING_FIELD = "missing_field" + SERVER_ERROR = "server_error" + + +class BaseObject(): + """ + Details about an object and its location. + + :attr str object: (optional) The name of the object. The name can contain + alphanumeric, underscore, hyphen, space, and dot characters. It cannot begin + with the reserved prefix `sys-`. + :attr Location location: (optional) Defines the location of the bounding box + around the object. + """ + + def __init__(self, *, object=None, location=None): + """ + Initialize a BaseObject object. + + :param str object: (optional) The name of the object. The name can contain + alphanumeric, underscore, hyphen, space, and dot characters. It cannot + begin with the reserved prefix `sys-`. + :param Location location: (optional) Defines the location of the bounding + box around the object. + """ + self.object = object + self.location = location + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BaseObject object from a json dictionary.""" + args = {} + valid_keys = ['object', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class BaseObject: ' + + ', '.join(bad_keys)) + if 'object' in _dict: + args['object'] = _dict.get('object') + if 'location' in _dict: + args['location'] = Location._from_dict(_dict.get('location')) + return cls(**args) + + def _to_dict(self): + """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, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this BaseObject object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Collection(): + """ + Details about a collection. + + :attr str collection_id: The identifier of the collection. + :attr str name: The name of the collection. + :attr str description: The descripion of the collection. + :attr datetime created: Date and time in Coordinated Universal Time (UTC) that + the collection was created. + :attr datetime updated: Date and time in Coordinated Universal Time (UTC) that + the collection was most recently updated. + :attr int image_count: Number of images in the collection. + :attr BaseCollectionTrainingStatus training_status: Training status information + for the collection. + """ + + def __init__(self, collection_id, name, description, created, updated, + image_count, training_status): + """ + Initialize a Collection object. + + :param str collection_id: The identifier of the collection. + :param str name: The name of the collection. + :param str description: The descripion of the collection. + :param datetime created: Date and time in Coordinated Universal Time (UTC) + that the collection was created. + :param datetime updated: Date and time in Coordinated Universal Time (UTC) + that the collection was most recently updated. + :param int image_count: Number of images in the collection. + :param BaseCollectionTrainingStatus training_status: Training status + information for the collection. + """ + self.collection_id = collection_id + self.name = name + self.description = description + self.created = created + self.updated = updated + self.image_count = image_count + self.training_status = training_status + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection object from a json dictionary.""" + args = {} + valid_keys = [ + 'collection_id', 'name', 'description', 'created', 'updated', + 'image_count', 'training_status' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Collection: ' + + ', '.join(bad_keys)) + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + else: + raise ValueError( + 'Required property \'collection_id\' not present in Collection JSON' + ) + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in Collection JSON') + if 'description' in _dict: + args['description'] = _dict.get('description') + else: + raise ValueError( + 'Required property \'description\' not present in Collection JSON' + ) + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + else: + raise ValueError( + 'Required property \'created\' not present in Collection JSON') + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + else: + raise ValueError( + 'Required property \'updated\' not present in Collection JSON') + if 'image_count' in _dict: + args['image_count'] = _dict.get('image_count') + else: + raise ValueError( + 'Required property \'image_count\' not present in Collection JSON' + ) + if 'training_status' in _dict: + args['training_status'] = BaseCollectionTrainingStatus._from_dict( + _dict.get('training_status')) + else: + raise ValueError( + 'Required property \'training_status\' not present in Collection JSON' + ) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'updated') and self.updated is not None: + _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'image_count') and self.image_count is not None: + _dict['image_count'] = self.image_count + if hasattr(self, + 'training_status') and self.training_status is not None: + _dict['training_status'] = self.training_status._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this Collection object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionObjects(): + """ + The objects in a collection that are detected in an image. + + :attr str collection_id: The identifier of the collection. + :attr list[ObjectDetail] objects: The identified objects in a collection. + """ + + def __init__(self, collection_id, objects): + """ + Initialize a CollectionObjects object. + + :param str collection_id: The identifier of the collection. + :param list[ObjectDetail] objects: The identified objects in a collection. + """ + self.collection_id = collection_id + self.objects = objects + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionObjects object from a json dictionary.""" + args = {} + valid_keys = ['collection_id', 'objects'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class CollectionObjects: ' + + ', '.join(bad_keys)) + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + else: + raise ValueError( + 'Required property \'collection_id\' not present in CollectionObjects JSON' + ) + if 'objects' in _dict: + args['objects'] = [ + ObjectDetail._from_dict(x) for x in (_dict.get('objects')) + ] + else: + raise ValueError( + 'Required property \'objects\' not present in CollectionObjects JSON' + ) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'objects') and self.objects is not None: + _dict['objects'] = [x._to_dict() for x in self.objects] + return _dict + + def __str__(self): + """Return a `str` version of this CollectionObjects object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionsList(): + """ + A container for the list of collections. + + :attr list[BaseCollection] collections: The collections in this service + instance. + """ + + def __init__(self, collections): + """ + Initialize a CollectionsList object. + + :param list[BaseCollection] collections: The collections in this service + instance. + """ + self.collections = collections + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionsList object from a json dictionary.""" + args = {} + valid_keys = ['collections'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class CollectionsList: ' + + ', '.join(bad_keys)) + if 'collections' in _dict: + args['collections'] = [ + BaseCollection._from_dict(x) for x in (_dict.get('collections')) + ] + else: + raise ValueError( + 'Required property \'collections\' not present in CollectionsList JSON' + ) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collections') and self.collections is not None: + _dict['collections'] = [x._to_dict() for x in self.collections] + return _dict + + def __str__(self): + """Return a `str` version of this CollectionsList object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DetectedObjects(): + """ + Container for the list of collections that have objects detected in an image. + + :attr list[CollectionObjects] collections: (optional) The collections with + identified objects. + """ + + def __init__(self, *, collections=None): + """ + Initialize a DetectedObjects object. + + :param list[CollectionObjects] collections: (optional) The collections with + identified objects. + """ + self.collections = collections + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DetectedObjects object from a json dictionary.""" + args = {} + valid_keys = ['collections'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DetectedObjects: ' + + ', '.join(bad_keys)) + if 'collections' in _dict: + args['collections'] = [ + CollectionObjects._from_dict(x) + for x in (_dict.get('collections')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collections') and self.collections is not None: + _dict['collections'] = [x._to_dict() for x in self.collections] + return _dict + + def __str__(self): + """Return a `str` version of this DetectedObjects object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Error(): + """ + Details about an error. + + :attr str code: Identifier of the problem. + :attr str message: An explanation of the problem with possible solutions. + :attr str more_info: (optional) A URL for more information about the solution. + :attr ErrorTarget target: (optional) Details about the specfic area of the + problem. + """ + + def __init__(self, code, message, *, more_info=None, target=None): + """ + Initialize a Error object. + + :param str code: Identifier of the problem. + :param str message: An explanation of the problem with possible solutions. + :param str more_info: (optional) A URL for more information about the + solution. + :param ErrorTarget target: (optional) Details about the specfic area of the + problem. + """ + self.code = code + self.message = message + self.more_info = more_info + self.target = target + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Error object from a json dictionary.""" + args = {} + valid_keys = ['code', 'message', 'more_info', 'target'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Error: ' + + ', '.join(bad_keys)) + if 'code' in _dict: + args['code'] = _dict.get('code') + else: + raise ValueError( + 'Required property \'code\' not present in Error JSON') + if 'message' in _dict: + args['message'] = _dict.get('message') + else: + raise ValueError( + 'Required property \'message\' not present in Error JSON') + if 'more_info' in _dict: + args['more_info'] = _dict.get('more_info') + if 'target' in _dict: + args['target'] = ErrorTarget._from_dict(_dict.get('target')) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + if hasattr(self, 'more_info') and self.more_info is not None: + _dict['more_info'] = self.more_info + if hasattr(self, 'target') and self.target is not None: + _dict['target'] = self.target._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this Error object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class CodeEnum(Enum): + """ + Identifier of the problem. + """ + INVALID_FIELD = "invalid_field" + INVALID_HEADER = "invalid_header" + INVALID_METHOD = "invalid_method" + MISSING_FIELD = "missing_field" + SERVER_ERROR = "server_error" + + +class ErrorTarget(): + """ + Details about the specfic area of the problem. + + :attr str type: The parameter or property that is the focus of the problem. + :attr str name: The property that is identified with the problem. + """ + + def __init__(self, type, name): + """ + Initialize a ErrorTarget object. + + :param str type: The parameter or property that is the focus of the + problem. + :param str name: The property that is identified with the problem. + """ + self.type = type + self.name = name + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ErrorTarget object from a json dictionary.""" + args = {} + valid_keys = ['type', 'name'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ErrorTarget: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in ErrorTarget JSON') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in ErrorTarget JSON') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + return _dict + + def __str__(self): + """Return a `str` version of this ErrorTarget object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(Enum): + """ + The parameter or property that is the focus of the problem. + """ + FIELD = "field" + PARAMETER = "parameter" + HEADER = "header" + + +class Image(): + """ + Details about an image. + + :attr ImageSource source: The source type of the image. + :attr ImageDimensions dimensions: Height and width of an image. + :attr DetectedObjects objects: Container for the list of collections that have + objects detected in an image. + :attr Error errors: (optional) Details about an error. + """ + + def __init__(self, source, dimensions, objects, *, errors=None): + """ + Initialize a Image object. + + :param ImageSource source: The source type of the image. + :param ImageDimensions dimensions: Height and width of an image. + :param DetectedObjects objects: Container for the list of collections that + have objects detected in an image. + :param Error errors: (optional) Details about an error. + """ + self.source = source + self.dimensions = dimensions + self.objects = objects + self.errors = errors + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Image object from a json dictionary.""" + args = {} + valid_keys = ['source', 'dimensions', 'objects', 'errors'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Image: ' + + ', '.join(bad_keys)) + if 'source' in _dict: + args['source'] = ImageSource._from_dict(_dict.get('source')) + else: + raise ValueError( + 'Required property \'source\' not present in Image JSON') + if 'dimensions' in _dict: + args['dimensions'] = ImageDimensions._from_dict( + _dict.get('dimensions')) + else: + raise ValueError( + 'Required property \'dimensions\' not present in Image JSON') + if 'objects' in _dict: + args['objects'] = DetectedObjects._from_dict(_dict.get('objects')) + else: + raise ValueError( + 'Required property \'objects\' not present in Image JSON') + if 'errors' in _dict: + args['errors'] = Error._from_dict(_dict.get('errors')) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source._to_dict() + if hasattr(self, 'dimensions') and self.dimensions is not None: + _dict['dimensions'] = self.dimensions._to_dict() + if hasattr(self, 'objects') and self.objects is not None: + _dict['objects'] = self.objects._to_dict() + if hasattr(self, 'errors') and self.errors is not None: + _dict['errors'] = self.errors._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this Image object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ImageDetails(): + """ + Details about an image. + + :attr str image_id: The identifier of the image. + :attr datetime updated: Date and time in Coordinated Universal Time (UTC) that + the image was most recently updated. + :attr datetime created: Date and time in Coordinated Universal Time (UTC) that + the image was created. + :attr ImageSource source: The source type of the image. + :attr ImageDimensions dimensions: Height and width of an image. + :attr Error errors: (optional) Details about an error. + :attr TrainingDataObjects training_data: Training data for all objects. + """ + + def __init__(self, + image_id, + updated, + created, + source, + dimensions, + training_data, + *, + errors=None): + """ + Initialize a ImageDetails object. + + :param str image_id: The identifier of the image. + :param datetime updated: Date and time in Coordinated Universal Time (UTC) + that the image was most recently updated. + :param datetime created: Date and time in Coordinated Universal Time (UTC) + that the image was created. + :param ImageSource source: The source type of the image. + :param ImageDimensions dimensions: Height and width of an image. + :param TrainingDataObjects training_data: Training data for all objects. + :param Error errors: (optional) Details about an error. + """ + self.image_id = image_id + self.updated = updated + self.created = created + self.source = source + self.dimensions = dimensions + self.errors = errors + self.training_data = training_data + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageDetails object from a json dictionary.""" + args = {} + valid_keys = [ + 'image_id', 'updated', 'created', 'source', 'dimensions', 'errors', + 'training_data' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ImageDetails: ' + + ', '.join(bad_keys)) + if 'image_id' in _dict: + args['image_id'] = _dict.get('image_id') + else: + raise ValueError( + 'Required property \'image_id\' not present in ImageDetails JSON' + ) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + else: + raise ValueError( + 'Required property \'updated\' not present in ImageDetails JSON' + ) + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + else: + raise ValueError( + 'Required property \'created\' not present in ImageDetails JSON' + ) + if 'source' in _dict: + args['source'] = ImageSource._from_dict(_dict.get('source')) + else: + raise ValueError( + 'Required property \'source\' not present in ImageDetails JSON') + if 'dimensions' in _dict: + args['dimensions'] = ImageDimensions._from_dict( + _dict.get('dimensions')) + else: + raise ValueError( + 'Required property \'dimensions\' not present in ImageDetails JSON' + ) + if 'errors' in _dict: + args['errors'] = Error._from_dict(_dict.get('errors')) + if 'training_data' in _dict: + args['training_data'] = TrainingDataObjects._from_dict( + _dict.get('training_data')) + else: + raise ValueError( + 'Required property \'training_data\' not present in ImageDetails JSON' + ) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'image_id') and self.image_id is not None: + _dict['image_id'] = self.image_id + if hasattr(self, 'updated') and self.updated is not None: + _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source._to_dict() + if hasattr(self, 'dimensions') and self.dimensions is not None: + _dict['dimensions'] = self.dimensions._to_dict() + if hasattr(self, 'errors') and self.errors is not None: + _dict['errors'] = self.errors._to_dict() + if hasattr(self, 'training_data') and self.training_data is not None: + _dict['training_data'] = self.training_data._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this ImageDetails object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ImageDetailsList(): + """ + List of information about the images. + + :attr list[ImageDetails] images: (optional) The images in the collection. + :attr list[BaseError] warnings: (optional) Information about what might cause + less than optimal output. + :attr str trace: (optional) A unique identifier of the request. Included only + when an error or warning is returned. + """ + + def __init__(self, *, images=None, warnings=None, trace=None): + """ + Initialize a ImageDetailsList object. + + :param list[ImageDetails] images: (optional) The images in the collection. + :param list[BaseError] warnings: (optional) Information about what might + cause less than optimal output. + :param str trace: (optional) A unique identifier of the request. Included + only when an error or warning is returned. + """ + self.images = images + self.warnings = warnings + self.trace = trace + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageDetailsList object from a json dictionary.""" + args = {} + valid_keys = ['images', 'warnings', 'trace'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ImageDetailsList: ' + + ', '.join(bad_keys)) + if 'images' in _dict: + args['images'] = [ + ImageDetails._from_dict(x) for x in (_dict.get('images')) + ] + if 'warnings' in _dict: + args['warnings'] = [ + BaseError._from_dict(x) for x in (_dict.get('warnings')) + ] + if 'trace' in _dict: + args['trace'] = _dict.get('trace') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'images') and self.images is not None: + _dict['images'] = [x._to_dict() for x in self.images] + if hasattr(self, 'warnings') and self.warnings is not None: + _dict['warnings'] = [x._to_dict() for x in self.warnings] + if hasattr(self, 'trace') and self.trace is not None: + _dict['trace'] = self.trace + return _dict + + def __str__(self): + """Return a `str` version of this ImageDetailsList object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ImageDimensions(): + """ + Height and width of an image. + + :attr int height: Height in pixels of the image. + :attr int width: Width in pixels of the image. + """ + + def __init__(self, height, width): + """ + Initialize a ImageDimensions object. + + :param int height: Height in pixels of the image. + :param int width: Width in pixels of the image. + """ + self.height = height + self.width = width + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageDimensions object from a json dictionary.""" + args = {} + valid_keys = ['height', 'width'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ImageDimensions: ' + + ', '.join(bad_keys)) + if 'height' in _dict: + args['height'] = _dict.get('height') + else: + raise ValueError( + 'Required property \'height\' not present in ImageDimensions JSON' + ) + if 'width' in _dict: + args['width'] = _dict.get('width') + else: + raise ValueError( + 'Required property \'width\' not present in ImageDimensions JSON' + ) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'height') and self.height is not None: + _dict['height'] = self.height + if hasattr(self, 'width') and self.width is not None: + _dict['width'] = self.width + return _dict + + def __str__(self): + """Return a `str` version of this ImageDimensions object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ImageSource(): + """ + The source type of the image. + + :attr str type: The source type of the image. + :attr str filename: (optional) Name of the image file if uploaded. Not returned + when the image is passed by URL. + :attr str archive_filename: (optional) Name of the .zip file of images if + uploaded. Not returned when the image is passed directly or by URL. + :attr str source_url: (optional) Source of the image before any redirects. Not + returned when the image is uploaded. + :attr str resolved_url: (optional) Fully resolved URL of the image after + redirects are followed. Not returned when the image is uploaded. + """ + + def __init__(self, + type, + *, + filename=None, + archive_filename=None, + source_url=None, + resolved_url=None): + """ + Initialize a ImageSource object. + + :param str type: The source type of the image. + :param str filename: (optional) Name of the image file if uploaded. Not + returned when the image is passed by URL. + :param str archive_filename: (optional) Name of the .zip file of images if + uploaded. Not returned when the image is passed directly or by URL. + :param str source_url: (optional) Source of the image before any redirects. + Not returned when the image is uploaded. + :param str resolved_url: (optional) Fully resolved URL of the image after + redirects are followed. Not returned when the image is uploaded. + """ + self.type = type + self.filename = filename + self.archive_filename = archive_filename + self.source_url = source_url + self.resolved_url = resolved_url + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageSource object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'filename', 'archive_filename', 'source_url', 'resolved_url' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ImageSource: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in ImageSource JSON') + if 'filename' in _dict: + args['filename'] = _dict.get('filename') + if 'archive_filename' in _dict: + args['archive_filename'] = _dict.get('archive_filename') + if 'source_url' in _dict: + args['source_url'] = _dict.get('source_url') + if 'resolved_url' in _dict: + args['resolved_url'] = _dict.get('resolved_url') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'filename') and self.filename is not None: + _dict['filename'] = self.filename + if hasattr(self, + 'archive_filename') and self.archive_filename is not None: + _dict['archive_filename'] = self.archive_filename + if hasattr(self, 'source_url') and self.source_url is not None: + _dict['source_url'] = self.source_url + if hasattr(self, 'resolved_url') and self.resolved_url is not None: + _dict['resolved_url'] = self.resolved_url + return _dict + + def __str__(self): + """Return a `str` version of this ImageSource object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(Enum): + """ + The source type of the image. + """ + FILE = "file" + URL = "url" + + +class ImageSummary(): + """ + Basic information about an image. + + :attr str image_id: (optional) The identifier of the image. + :attr datetime updated: (optional) Date and time in Coordinated Universal Time + (UTC) that the image was most recently updated. + """ + + def __init__(self, *, image_id=None, updated=None): + """ + Initialize a ImageSummary object. + + :param str image_id: (optional) The identifier of the image. + :param datetime updated: (optional) Date and time in Coordinated Universal + Time (UTC) that the image was most recently updated. + """ + self.image_id = image_id + self.updated = updated + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageSummary object from a json dictionary.""" + args = {} + valid_keys = ['image_id', 'updated'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ImageSummary: ' + + ', '.join(bad_keys)) + if 'image_id' in _dict: + args['image_id'] = _dict.get('image_id') + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'image_id') and self.image_id is not None: + _dict['image_id'] = self.image_id + if hasattr(self, 'updated') and self.updated is not None: + _dict['updated'] = datetime_to_string(self.updated) + return _dict + + def __str__(self): + """Return a `str` version of this ImageSummary object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ImageSummaryList(): + """ + List of images. + + :attr list[ImageSummary] images: The images in the collection. + """ + + def __init__(self, images): + """ + Initialize a ImageSummaryList object. + + :param list[ImageSummary] images: The images in the collection. + """ + self.images = images + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageSummaryList object from a json dictionary.""" + args = {} + valid_keys = ['images'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ImageSummaryList: ' + + ', '.join(bad_keys)) + if 'images' in _dict: + args['images'] = [ + ImageSummary._from_dict(x) for x in (_dict.get('images')) + ] + else: + raise ValueError( + 'Required property \'images\' not present in ImageSummaryList JSON' + ) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'images') and self.images is not None: + _dict['images'] = [x._to_dict() for x in self.images] + return _dict + + def __str__(self): + """Return a `str` version of this ImageSummaryList object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Location(): + """ + Defines the location of the bounding box around the object. + + :attr int top: Y-position of top-left pixel of the bounding box. + :attr int left: X-position of top-left pixel of the bounding box. + :attr int width: Width in pixels of of the bounding box. + :attr int height: Height in pixels of the bounding box. + """ + + def __init__(self, top, left, width, height): + """ + Initialize a Location object. + + :param int top: Y-position of top-left pixel of the bounding box. + :param int left: X-position of top-left pixel of the bounding box. + :param int width: Width in pixels of of the bounding box. + :param int height: Height in pixels of the bounding box. + """ + self.top = top + self.left = left + self.width = width + self.height = height + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Location object from a json dictionary.""" + args = {} + valid_keys = ['top', 'left', 'width', 'height'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Location: ' + + ', '.join(bad_keys)) + if 'top' in _dict: + args['top'] = _dict.get('top') + else: + raise ValueError( + 'Required property \'top\' not present in Location JSON') + if 'left' in _dict: + args['left'] = _dict.get('left') + else: + raise ValueError( + 'Required property \'left\' not present in Location JSON') + if 'width' in _dict: + args['width'] = _dict.get('width') + else: + raise ValueError( + 'Required property \'width\' not present in Location JSON') + if 'height' in _dict: + args['height'] = _dict.get('height') + else: + raise ValueError( + 'Required property \'height\' not present in Location JSON') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'top') and self.top is not None: + _dict['top'] = self.top + if hasattr(self, 'left') and self.left is not None: + _dict['left'] = self.left + if hasattr(self, 'width') and self.width is not None: + _dict['width'] = self.width + if hasattr(self, 'height') and self.height is not None: + _dict['height'] = self.height + return _dict + + def __str__(self): + """Return a `str` version of this Location object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ObjectDetail(): + """ + Details about an object in the collection. + + :attr str object: The label for the object. + :attr Location location: Defines the location of the bounding box around the + object. + :attr float score: Confidence score for the object in the range of 0 to 1. A + higher score indicates greater likelihood that the object is depicted at this + location in the image. + """ + + def __init__(self, object, location, score): + """ + Initialize a ObjectDetail object. + + :param str object: The label for the object. + :param Location location: Defines the location of the bounding box around + the object. + :param float score: Confidence score for the object in the range of 0 to 1. + A higher score indicates greater likelihood that the object is depicted at + this location in the image. + """ + self.object = object + self.location = location + self.score = score + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ObjectDetail object from a json dictionary.""" + args = {} + valid_keys = ['object', 'location', 'score'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ObjectDetail: ' + + ', '.join(bad_keys)) + if 'object' in _dict: + args['object'] = _dict.get('object') + else: + raise ValueError( + 'Required property \'object\' not present in ObjectDetail JSON') + if 'location' in _dict: + args['location'] = Location._from_dict(_dict.get('location')) + else: + raise ValueError( + 'Required property \'location\' not present in ObjectDetail JSON' + ) + if 'score' in _dict: + args['score'] = _dict.get('score') + else: + raise ValueError( + 'Required property \'score\' not present in ObjectDetail JSON') + return cls(**args) + + def _to_dict(self): + """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, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score + return _dict + + def __str__(self): + """Return a `str` version of this ObjectDetail object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """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. + + :attr bool ready: Whether you can analyze images in the collection with the + **objects** feature. + :attr bool in_progress: Whether training is in progress. + :attr bool data_changed: Whether there are changes to the training data since + the most recent training. + :attr bool latest_failed: Whether the most recent training failed. + :attr str description: Details about the training. If training is in progress, + includes information about the status. If training is not in progress, includes + a success message or information about why training failed. + """ + + def __init__(self, ready, in_progress, data_changed, latest_failed, + description): + """ + Initialize a ObjectTrainingStatus object. + + :param bool ready: Whether you can analyze images in the collection with + the **objects** feature. + :param bool in_progress: Whether training is in progress. + :param bool data_changed: Whether there are changes to the training data + since the most recent training. + :param bool latest_failed: Whether the most recent training failed. + :param str description: Details about the training. If training is in + progress, includes information about the status. If training is not in + progress, includes a success message or information about why training + failed. + """ + self.ready = ready + self.in_progress = in_progress + self.data_changed = data_changed + self.latest_failed = latest_failed + self.description = description + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ObjectTrainingStatus object from a json dictionary.""" + args = {} + valid_keys = [ + 'ready', 'in_progress', 'data_changed', 'latest_failed', + 'description' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ObjectTrainingStatus: ' + + ', '.join(bad_keys)) + if 'ready' in _dict: + args['ready'] = _dict.get('ready') + else: + raise ValueError( + 'Required property \'ready\' not present in ObjectTrainingStatus JSON' + ) + if 'in_progress' in _dict: + args['in_progress'] = _dict.get('in_progress') + else: + raise ValueError( + 'Required property \'in_progress\' not present in ObjectTrainingStatus JSON' + ) + if 'data_changed' in _dict: + args['data_changed'] = _dict.get('data_changed') + else: + raise ValueError( + 'Required property \'data_changed\' not present in ObjectTrainingStatus JSON' + ) + if 'latest_failed' in _dict: + args['latest_failed'] = _dict.get('latest_failed') + else: + raise ValueError( + 'Required property \'latest_failed\' not present in ObjectTrainingStatus JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + else: + raise ValueError( + 'Required property \'description\' not present in ObjectTrainingStatus JSON' + ) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'ready') and self.ready is not None: + _dict['ready'] = self.ready + if hasattr(self, 'in_progress') and self.in_progress is not None: + _dict['in_progress'] = self.in_progress + if hasattr(self, 'data_changed') and self.data_changed is not None: + _dict['data_changed'] = self.data_changed + if hasattr(self, 'latest_failed') and self.latest_failed is not None: + _dict['latest_failed'] = self.latest_failed + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + return _dict + + def __str__(self): + """Return a `str` version of this ObjectTrainingStatus object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TrainingDataObject(): + """ + Details about the training data. + + :attr str object: (optional) The name of the object. + :attr Location location: (optional) Defines the location of the bounding box + around the object. + """ + + def __init__(self, *, object=None, location=None): + """ + Initialize a TrainingDataObject object. + + :param str object: (optional) The name of the object. + :param Location location: (optional) Defines the location of the bounding + box around the object. + """ + self.object = object + self.location = location + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingDataObject object from a json dictionary.""" + args = {} + valid_keys = ['object', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TrainingDataObject: ' + + ', '.join(bad_keys)) + if 'object' in _dict: + args['object'] = _dict.get('object') + if 'location' in _dict: + args['location'] = Location._from_dict(_dict.get('location')) + return cls(**args) + + def _to_dict(self): + """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, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this TrainingDataObject object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TrainingDataObjects(): + """ + Training data for all objects. + + :attr list[TrainingDataObject] objects: Training data for specific objects. + """ + + def __init__(self, objects): + """ + Initialize a TrainingDataObjects object. + + :param list[TrainingDataObject] objects: Training data for specific + objects. + """ + self.objects = objects + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingDataObjects object from a json dictionary.""" + args = {} + valid_keys = ['objects'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TrainingDataObjects: ' + + ', '.join(bad_keys)) + if 'objects' in _dict: + args['objects'] = [ + TrainingDataObject._from_dict(x) for x in (_dict.get('objects')) + ] + else: + raise ValueError( + 'Required property \'objects\' not present in TrainingDataObjects JSON' + ) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'objects') and self.objects is not None: + _dict['objects'] = [x._to_dict() for x in self.objects] + return _dict + + def __str__(self): + """Return a `str` version of this TrainingDataObjects object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class FileWithMetadata(): + """ + A file with its associated metadata. + + :attr file data: The data / content for the file. + :attr str filename: (optional) The filename of the file. + :attr str content_type: (optional) The content type of the file. + """ + + def __init__(self, data, *, filename=None, content_type=None): + """ + Initialize a FileWithMetadata object. + + :param file data: The data / content for the file. + :param str filename: (optional) The filename of the file. + :param str content_type: (optional) The content type of the file. + """ + self.data = data + self.filename = filename + self.content_type = content_type + + @classmethod + def _from_dict(cls, _dict): + """Initialize a FileWithMetadata object from a json dictionary.""" + args = {} + valid_keys = ['data', 'filename', 'content_type'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class FileWithMetadata: ' + + ', '.join(bad_keys)) + if 'data' in _dict: + args['data'] = file._from_dict(_dict.get('data')) + else: + raise ValueError( + 'Required property \'data\' not present in FileWithMetadata JSON' + ) + if 'filename' in _dict: + args['filename'] = _dict.get('filename') + if 'content_type' in _dict: + args['content_type'] = _dict.get('content_type') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'data') and self.data is not None: + _dict['data'] = self.data._to_dict() + if hasattr(self, 'filename') and self.filename is not None: + _dict['filename'] = self.filename + if hasattr(self, 'content_type') and self.content_type is not None: + _dict['content_type'] = self.content_type + return _dict + + def __str__(self): + """Return a `str` version of this FileWithMetadata object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py new file mode 100644 index 000000000..c00074931 --- /dev/null +++ b/test/integration/test_visual_recognition_v4.py @@ -0,0 +1,126 @@ +# coding: utf-8 +import pytest +import ibm_watson +import os +from os.path import abspath +import json +from unittest import TestCase +from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata, BaseObject, Location + +@pytest.mark.skipif( + os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') +class IntegrationTestVisualRecognitionV3(TestCase): + visual_recognition = None + + @classmethod + 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' + }) + + def test_01_colllections(self): + collection = self.visual_recognition.create_collection( + 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() + assert my_collection is not None + assert my_collection.get('name') == 'my_collection' + + updated_collection = self.visual_recognition.update_collection( + collection_id=collection_id, + description='new description').get_result() + assert updated_collection is not None + + collections = self.visual_recognition.list_collections().get_result().get('collections') + print(json.dumps(collections, indent=2)) + 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() + 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"], + ).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() + assert list_images is not None + + 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() + 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 = abspath( + '/Users/erikadsouza/workspace/public/python-sdk/resources/dog.jpg') + giraffe_path = abspath( + '/Users/erikadsouza/workspace/public/python-sdk/resources/my-giraffe.jpeg' + ) + with open(dog_path, 'rb') as dog_file, open(giraffe_path, 'rb') as giraffe_files: + analyze_images = self.visual_recognition.analyze( + collection_ids='d31d6534-3458-40c4-b6de-2185a5f3cbe4', + features=AnalyzeEnums.Features.OBJECTS.value, + images_file=[ + 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() + assert analyze_images is not None + print(json.dumps(analyze_images, indent=2)) + + def test_04_training(self): + # create a classifier + my_collection = self.visual_recognition.create_collection( + name='my_test_collection', + description='tetsing 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.jpg'), 'rb') as giraffe_info: + add_images_result = self.visual_recognition.add_images( + collection_id, + images_file=[FileWithMetadata(giraffe_info)], + ).get_result() + assert add_images_result is not None + image_id = add_images_result.get('images')[0].get('image_id') + assert image_id is not None + + # add image training data + training_data = self.visual_recognition.add_image_training_data( + collection_id, + image_id, + objects=[ + BaseObject(object='giraffe training data', location=Location(64, 270, 755, 784)) + ]).get_result() + assert training_data is not None + + # 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 + + # delete collection + self.visual_recognition.delete_collection(collection_id) diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py new file mode 100644 index 000000000..0215a52b8 --- /dev/null +++ b/test/unit/test_visual_recognition_v4.py @@ -0,0 +1,853 @@ +# (C) Copyright IBM Corp. 2019. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +import responses +import ibm_watson +import responses +import ibm_watson +import json +import os +import jwt +import time +import pytest +from unittest import TestCase +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata, BaseObject, Location + +platform_url = 'https://gateway.watsonplatform.net' +service_path = '/visual-recognition/api' +base_url = '{0}{1}'.format(platform_url, service_path) + + +def get_access_token(): + access_token_layout = { + "username": "dummy", + "role": "Admin", + "permissions": ["administrator", "manage_catalog"], + "sub": "admin", + "iss": "sss", + "aud": "sss", + "uid": "sss", + "iat": 3600, + "exp": int(time.time()) + } + + access_token = jwt.encode( + access_token_layout, + 'secret', + algorithm='HS256', + headers={'kid': '230498151c214b788dd97f22b85410a5'}) + return access_token.decode('utf-8') + + +class TestVisualRecognitionV4(TestCase): + + @classmethod + def setUp(cls): + iam_url = "https://iam.cloud.ibm.com/identity/token" + iam_token_response = { + "access_token": get_access_token(), + "token_type": "Bearer", + "expires_in": 3600, + "expiration": 1524167011, + "refresh_token": "jy4gl91BQ" + } + responses.add(responses.POST, + url=iam_url, + body=json.dumps(iam_token_response), + status=200) + + ######################### + # analysis + ######################### + + @responses.activate + def test_analyze(self): + endpoint = '/v4/analyze' + url = '{0}{1}'.format(base_url, endpoint) + response = { + "images": [{ + "objects": { + "collections": [{ + "collection_id": + "collection_id", + "objects": [{ + "score": 7.0614014, + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }, { + "score": 7.0614014, + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }] + }, { + "collection_id": + "collection_id", + "objects": [{ + "score": 7.0614014, + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }, { + "score": 7.0614014, + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }] + }] + }, + "source": { + "archive_filename": "archive_filename", + "filename": "filename", + "type": "file", + "resolved_url": "resolved_url", + "source_url": "source_url" + }, + "errors": { + "code": + "invalid_field", + "message": + "The date provided for `version` is not valid. Specify dates in `YYYY-MM-DD` format.", + "more_info": + "https://cloud.ibm.com/apidocs/visual-recognition-v4#versioning", + "target": { + "type": "parameter", + "name": "version" + } + }, + "dimensions": { + "width": 6, + "height": 0 + } + }, { + "objects": { + "collections": [{ + "collection_id": + "collection_id", + "objects": [{ + "score": 7.0614014, + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }, { + "score": 7.0614014, + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }] + }, { + "collection_id": + "collection_id", + "objects": [{ + "score": 7.0614014, + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }, { + "score": 7.0614014, + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }] + }] + }, + "source": { + "archive_filename": "archive_filename", + "filename": "filename", + "type": "file", + "resolved_url": "resolved_url", + "source_url": "source_url" + }, + "errors": { + "code": + "invalid_field", + "message": + "The date provided for `version` is not valid. Specify dates in `YYYY-MM-DD` format.", + "more_info": + "https://cloud.ibm.com/apidocs/visual-recognition-v4#versioning", + "target": { + "type": "parameter", + "name": "version" + } + }, + "dimensions": { + "width": 6, + "height": 0 + } + }], + "trace": + "trace", + "warnings": [{ + "code": "invalid_field", + "more_info": "more_info", + "message": "message" + }, { + "code": "invalid_field", + "more_info": "more_info", + "message": "message" + }] + } + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + with open( + os.path.join(os.path.dirname(__file__), + '../../resources/cars.zip'), 'rb') as cars: + detailed_response = service.analyze( + collection_ids='collection_id1, collection_id2', + features=AnalyzeEnums.Features.OBJECTS.value, + images_file=[FileWithMetadata(cars)], + image_url=[ + 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/American_Eskimo_Dog.jpg/1280px-American_Eskimo_Dog.jpg' + ], + threshold='0.2') + result = detailed_response.get_result() + assert result is not None + assert len(responses.calls) == 2 + + ######################### + # collections + ######################### + + @responses.activate + def test_create_collection(self): + endpoint = '/v4/collections' + url = '{0}{1}'.format(base_url, endpoint) + response = { + "collection_id": "collection_id", + "training_status": { + "objects": { + "in_progress": "true", + "data_changed": "true", + "ready": "true", + "latest_failed": "true", + "description": "description" + } + }, + "created": "2000-01-23T04:56:07.000+00:00", + "name": "name", + "description": "description", + "image_count": 0, + "updated": "2000-01-23T04:56:07.000+00:00" + } + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + detailed_response = service.create_collection(name='name', + description='description') + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + @responses.activate + def test_list_collections(self): + endpoint = '/v4/collections' + url = '{0}{1}'.format(base_url, endpoint) + response = { + "collections": [{ + "collection_id": "collection_id", + "training_status": { + "objects": { + "in_progress": "true", + "data_changed": "true", + "ready": "true", + "latest_failed": "true", + "description": "description" + } + }, + "created": "2000-01-23T04:56:07.000+00:00", + "name": "name", + "description": "description", + "image_count": 0, + "updated": "2000-01-23T04:56:07.000+00:00" + }, { + "collection_id": "collection_id", + "training_status": { + "objects": { + "in_progress": "true", + "data_changed": "true", + "ready": "true", + "latest_failed": "true", + "description": "description" + } + }, + "created": "2000-01-23T04:56:07.000+00:00", + "name": "name", + "description": "description", + "image_count": 0, + "updated": "2000-01-23T04:56:07.000+00:00" + }] + } + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.list_collections() + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + @responses.activate + def test_get_collection(self): + endpoint = '/v4/collections/{0}'.format('collection_id') + url = '{0}{1}'.format(base_url, endpoint) + response = { + "collection_id": "collection_id", + "training_status": { + "objects": { + "in_progress": "true", + "data_changed": "true", + "ready": "true", + "latest_failed": "true", + "description": "description" + } + }, + "created": "2000-01-23T04:56:07.000+00:00", + "name": "name", + "description": "description", + "image_count": 0, + "updated": "2000-01-23T04:56:07.000+00:00" + } + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.get_collection( + collection_id='collection_id') + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + @responses.activate + def test_update_collection(self): + endpoint = '/v4/collections/{0}'.format('collection_id') + url = '{0}{1}'.format(base_url, endpoint) + response = { + "collection_id": "collection_id", + "training_status": { + "objects": { + "in_progress": "true", + "data_changed": "true", + "ready": "true", + "latest_failed": "true", + "description": "description" + } + }, + "created": "2000-01-23T04:56:07.000+00:00", + "name": "name", + "description": "description", + "image_count": 0, + "updated": "2000-01-23T04:56:07.000+00:00" + } + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.update_collection( + collection_id='collection_id', + name='name', + description='description') + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + @responses.activate + def test_delete_collection(self): + endpoint = '/v4/collections/{0}'.format('collection_id') + url = '{0}{1}'.format(base_url, endpoint) + response = {} + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.delete_collection( + collection_id='collection_id') + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + with pytest.raises(TypeError): + service.delete_collection() + + # ######################### + # # images + # ######################### + + @responses.activate + def test_add_images(self): + endpoint = '/v4/collections/{0}/images'.format('collection_id') + url = '{0}{1}'.format(base_url, endpoint) + response = { + "images": [{ + "training_data": { + "objects": [{ + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }, { + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }] + }, + "created": "2000-01-23T04:56:07.000+00:00", + "source": { + "archive_filename": "archive_filename", + "filename": "filename", + "type": "file", + "resolved_url": "resolved_url", + "source_url": "source_url" + }, + "image_id": "image_id", + "updated": "2000-01-23T04:56:07.000+00:00", + "errors": { + "code": + "invalid_field", + "message": + "The date provided for `version` is not valid. Specify dates in `YYYY-MM-DD` format.", + "more_info": + "https://cloud.ibm.com/apidocs/visual-recognition-v4#versioning", + "target": { + "type": "parameter", + "name": "version" + } + }, + "dimensions": { + "width": 6, + "height": 0 + } + }, { + "training_data": { + "objects": [{ + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }, { + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }] + }, + "created": "2000-01-23T04:56:07.000+00:00", + "source": { + "archive_filename": "archive_filename", + "filename": "filename", + "type": "file", + "resolved_url": "resolved_url", + "source_url": "source_url" + }, + "image_id": "image_id", + "updated": "2000-01-23T04:56:07.000+00:00", + "errors": { + "code": + "invalid_field", + "message": + "The date provided for `version` is not valid. Specify dates in `YYYY-MM-DD` format.", + "more_info": + "https://cloud.ibm.com/apidocs/visual-recognition-v4#versioning", + "target": { + "type": "parameter", + "name": "version" + } + }, + "dimensions": { + "width": 6, + "height": 0 + } + }], + "trace": + "trace", + "warnings": [{ + "code": "invalid_field", + "more_info": "more_info", + "message": "message" + }, { + "code": "invalid_field", + "more_info": "more_info", + "message": "message" + }] + } + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.add_images(collection_id='collection_id', + image_url='image_url', + training_data='training_data') + + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + with pytest.raises(TypeError): + service.add_images() + + @responses.activate + def test_list_images(self): + endpoint = '/v4/collections/{0}/images'.format('collection_id') + url = '{0}{1}'.format(base_url, endpoint) + response = { + "images": [{ + "image_id": "image_id", + "updated": "2000-01-23T04:56:07.000+00:00" + }, { + "image_id": "image_id", + "updated": "2000-01-23T04:56:07.000+00:00" + }] + } + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.list_images(collection_id='collection_id') + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + with pytest.raises(TypeError): + service.list_images() + + @responses.activate + def test_get_image_details(self): + endpoint = '/v4/collections/{0}/images/{1}'.format( + 'collection_id', 'image_id').format('image_id') + url = '{0}{1}'.format(base_url, endpoint) + response = { + "training_data": { + "objects": [{ + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }, { + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }] + }, + "created": "2000-01-23T04:56:07.000+00:00", + "source": { + "archive_filename": "archive_filename", + "filename": "filename", + "type": "file", + "resolved_url": "resolved_url", + "source_url": "source_url" + }, + "image_id": "image_id", + "updated": "2000-01-23T04:56:07.000+00:00", + "errors": { + "code": + "invalid_field", + "message": + "The date provided for `version` is not valid. Specify dates in `YYYY-MM-DD` format.", + "more_info": + "https://cloud.ibm.com/apidocs/visual-recognition-v4#versioning", + "target": { + "type": "parameter", + "name": "version" + } + }, + "dimensions": { + "width": 6, + "height": 0 + } + } + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.get_image_details( + collection_id='collection_id', image_id='image_id') + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + with pytest.raises(TypeError): + service.get_image_details() + + @responses.activate + def test_delete_image(self): + endpoint = '/v4/collections/{0}/images/{1}'.format( + 'collection_id', 'image_id').format('image_id') + url = '{0}{1}'.format(base_url, endpoint) + response = {} + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.delete_image(collection_id='collection_id', + image_id='image_id') + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + with pytest.raises(TypeError): + service.delete_image() + + @responses.activate + def test_get_jpeg_image(self): + endpoint = '/v4/collections/{0}/images/{1}/jpeg'.format( + 'collection_id', 'image_id').format('image_id') + url = '{0}{1}'.format(base_url, endpoint) + response = {} + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.get_jpeg_image( + collection_id='collection_id', image_id='image_id', size='size') + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + with pytest.raises(TypeError): + service.get_jpeg_image() + + ######################### + # training + ######################### + + @responses.activate + def test_train(self): + endpoint = '/v4/collections/{0}/train'.format('collection_id') + url = '{0}{1}'.format(base_url, endpoint) + response = { + "collection_id": "collection_id", + "training_status": { + "objects": { + "in_progress": "true", + "data_changed": "true", + "ready": "true", + "latest_failed": "true", + "description": "description" + } + }, + "created": "2000-01-23T04:56:07.000+00:00", + "name": "name", + "description": "description", + "image_count": 0, + "updated": "2000-01-23T04:56:07.000+00:00" + } + responses.add(responses.POST, + url, + body=json.dumps(response), + status=202, + content_type='application/json') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.train(collection_id='collection_id') + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + with pytest.raises(TypeError): + service.train() + + @responses.activate + def test_add_image_training_data(self): + endpoint = '/v4/collections/{0}/images/{1}/training_data'.format( + 'collection_id', 'image_id') + url = '{0}{1}'.format(base_url, endpoint) + response = { + "objects": [{ + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }, { + "location": { + "top": 1, + "left": 5, + "width": 5, + "height": 2 + }, + "object": "object" + }] + } + responses.add(responses.POST, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.add_image_training_data( + collection_id='collection_id', image_id='image_id') + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + with pytest.raises(TypeError): + service.add_image_training_data() + + ######################### + # userData + ######################### + + @responses.activate + def test_delete_user_data(self): + endpoint = '/v4/user_data' + url = '{0}{1}'.format(base_url, endpoint) + response = {} + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=202, + content_type='') + + authenticator = IAMAuthenticator('bogusapikey') + service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', + authenticator=authenticator) + service.set_service_url(base_url) + + detailed_response = service.delete_user_data(customer_id='customer_id') + result = detailed_response.get_result() + assert len(responses.calls) == 2 + + with pytest.raises(TypeError): + service.delete_user_data() From 8d06d3c37079fd547e782fcf956967ff663c0b80 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 1 Oct 2019 10:11:54 -0700 Subject: [PATCH 084/455] chore(package): Update core and responses version --- requirements-dev.txt | 4 ++-- requirements.txt | 2 +- setup.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 615708de5..66ba484f8 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,11 +1,11 @@ # test dependencies pytest>=2.8.2 -responses==0.9.0 +responses>=0.10.6 python_dotenv>=0.1.5;python_version!='3.2' pylint>=1.4.4 tox>=2.9.1 pytest-rerunfailures>=3.1 -ibm_cloud_sdk_core==1.0.0rc5 +ibm_cloud_sdk_core==1.0.0rc9 # code coverage coverage<5 diff --git a/requirements.txt b/requirements.txt index 85af66e0f..a214f221f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 -ibm_cloud_sdk_core==1.0.0rc5 \ No newline at end of file +ibm_cloud_sdk_core==1.0.0rc9 \ No newline at end of file diff --git a/setup.py b/setup.py index aace9b7c2..e6124e95b 100644 --- a/setup.py +++ b/setup.py @@ -63,7 +63,7 @@ def run_tests(self): version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.0.0rc5'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.0.0rc9'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='IBM Watson', From a7d10f0dea2a60ccae69d0d5029fba3698f3d40a Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 1 Oct 2019 10:20:41 -0700 Subject: [PATCH 085/455] test(service): Update tests of all services --- resources/South_Africa_Luca_Galuzzi_2004.JPG | Bin 0 -> 289418 bytes resources/my-giraffe.jpeg | Bin 0 -> 33499 bytes test/unit/test_assistant_v1.py | 1 + test/unit/test_discovery_v1.py | 76 ++---------------- .../test_natural_language_understanding.py | 19 ++--- test/unit/test_personality_insights_v3.py | 17 ++-- 6 files changed, 23 insertions(+), 90 deletions(-) create mode 100755 resources/South_Africa_Luca_Galuzzi_2004.JPG create mode 100644 resources/my-giraffe.jpeg diff --git a/resources/South_Africa_Luca_Galuzzi_2004.JPG b/resources/South_Africa_Luca_Galuzzi_2004.JPG new file mode 100755 index 0000000000000000000000000000000000000000..67375877102ea055b7c66385cf0fd83593b1a5df GIT binary patch literal 289418 zcmb@uc|25o_&@wPGsYkp*^_08GAWg!>;`2^Owy*JLbi}4YZy`8$sQGnktHfgmMD@+ zQnyS@6e5&0NsWDbuG9T}y}rNK^Uw1uD#duh&^02PZA6i=W>at<9SqygWR-JbgC>xVpP~I61nW*yQEo zycvJB89!ai#MS4-sZ&n&W_~UwPM@&fZEI=2&+Dw8i@m`qA6JJH_7-R1hslZ4XM=-X z?YC~(qPEGLVY1Xqpqm*P*)y!IjLj@|!6*q zA|m?xb;7~-i~)mTfxqzd@^t#|-T(9FWGjLzA=ILRU+e$;&HsyI0f#d_esJDA{M+j2 z*NbMqX!vd|aJf{HUs$nwnGtN3WAk)O|s|eoh{~R5MQp zFP}4BJ}3N~9O2ym#)p3jt@!Ume8p(+L5=l)-~Ipb2fh#gUGC4`zw3)h{QJM}{qKz& z&ieTO&nt|u4Wa+1*Z+HsbSZ?aauMR0|KIo2Vi96(M2M2|zwfP6MM!uvLeJ8dI*<|K zWThLRxmMy!0vs83_sMMykR(rS;0| zSIVnwQK4;FOIuIFFM^TDWC1<_Q2_x_nzV#8?f>)F(sQ(ekGP+Nh}a55Sb-5&U`wwM zY%E5?o$G(UFc>YFNZ^CtnhPTWMkEq=@GlaPfGx)eM8va#B(hr7fLCVPDk5Y)_Dp{0VL@83kn#xeX!XRRhN9#~cA<8rw zYedeK{Y(apr)iX~f`p!NFuEAVRYQ6lMa?X1tevTuwR&M8pB}nxf+eK?hc26srs~a+ zW`ER07gAF$=>lRL3WrN&a0zU3Fh-eT33dPAU@r8`u{2cQ6?KKK)Xv=EW-7oW=JI0; zG`c_nFO#y6Pt+^L=(5u+c>kFu3#&unwn&|-S7n2A$E}HTY?8t11zi_zD>~VlE0`QEC7l_4enX=gH(^;A9*qzck%iIa%`tK=I?ED3ENrrusXfOa4^6QI zM8pW8K`bFI!C#E(+fl|Z8OMQ@g`x85hQX4p)97VVMqsOM71KALOT+XFQFW6!MkCc1 zjnL%_QNRxuVm=F_%fY!aaLHiQ2aAcS2YE*6@@{CDMyya0Bg``R;1hNn1jEtxXA#Hf z#AYT~ibEl~)2@sK$-C`s<%MVUZl(ZE#C$h)$jxr%O$!VfEGM7A#>4mnB4B~DlFrO6Tn1D#!fHPvF1*}imMrXH8TNEnc@5!RfQ zPBLWL577zC<#aH(@Ze>{CcDyyvY|tcB>so8S~kq4eeF>sI>imswux}r!_3DP@(Ijs zQ@PBEdUMQ$$YqJb0(zE8sG##qy<3CCVwS)m0W28&W{j@%$&ZD#<}8b5%7fVxm}sb( ziMX)JN+a~mxhQiCOm!JuX^{r@CZsQyYb@ZdXvO~K;QcotJxlCm_OA=o*8 zmQWWL91Dz{x?ZZ0en!cNpTNBIxMsrCl5 zu&1&xY}F=PVR>^AaYU1{Nf2B2N{wn?Xt2iSioh}f^z|%D48|Fp#4|S9&ZL=!x@@FO z09Y}>a?AJygk=V5?!a&neyz=3Q~08Th$qPQQ!1iHYsW%G%xOe=E)Yb{hgbX5JG3b2}kMcWvrjyD8M@6GFw@^y6cZyeknMv zx*G$}Ws?g59oy6qI8zFhMw(zzs^PBoMI#JC4&N?RwJ^w|$HBT-LMCPWqIb*_Hh06a zi6gQ@a}+O)1Y;*RM_qD5vj98tBZh>i3y4ADqk!*@(v^Y{7gpB_)~XP$dDNFKmyE(V zSoeYpcn5gH!XQzKB~)XJzJi-(RI!&WxWJs?N(}NOi-Ln#AspJl?coq$0DeJ&MIdNR zvc!V9EaA|*$cDL?jI}eh*(AE4H(i{n>xKX~t5HB5er~2MT2Q9j2-9FK6g3N|+BPC` z9I81M@|B&?my43A_GSD+^KAZ(Xv7j)^jkN%P*aCX|T^TF;Q9uE?a9b>J;7&VpIr8pe>gOT{SuGAzAq^uThn017nZ8Iv z`Vz85;#6(MvhFmdk}U#T5W}Luz~B@m*oP1Xd9Igf)dh|Xj%$nULa?xc5Fh|(a`8Zs zpve-t$Ryj*h?$iv$!c_|nW?Lf?*+e5e-wFcguY4hIZJd1wicrk@o9F!W{}|;jAaWn z9vpuIhVY+Zr2u*zfL$0^zWw7NKqvsZQ7|Q~P&c~27#2rEbBtv%985K?6axeSD_=sI za1Mms5C$*!qjne<(TF2}BMiVo-8lwg2{44B7$iJ^{s7aV5y5d5Xr#ZUH^CxKz^CU< zGWDw1445X|8)>l_$ykd9#2D&&$4hOwNN!>cle0zap%{Td{tF*8;$uY^uC%a{RdWsr z<@j=JL=7nphQxFZb9BtmMVU`1g=)bd%TKbfT9zPS57;>t%;pOjPb0q9)k|lCDa=YE z+0a4KC3@I*)Vh6^Qi~LxE{xC_F;P@f{gBZ3r z%O<-4D2fprs!^2#xGH?h&eS#{0X%+q&oUAw#|(MuA$DN&O)jPmW$0G;xFLZFjv!jb z2M8PvkXeY}VoCr7;H&`ofIUZHNd%bGA!`x~8+I`T)?+{jt#8la1s0-4h{hlW(5A#7 ze#qFM0xT{lpCCjd0dy=3l13n;LR^Q5<&(xdmvf~+o$2WJhcuyet%%>Z;<2$B#3k_iCQfZdcLF#reE^KcRgg+v412u)CR zRTtb46RuiHI2lC-untZliSt|@jZPxg7|>+|M0lg{YuTHliGC)G!|)J;$q;zT|%al~*ZSmtZ+E`bDbq*|{#NGwBO0o`I?)ACli zFrZeL1I(N<5AkX(&?nee;3bTNETr#-nRJif_6x6I>SBM=M8q)8f->onx+2-LmzBUR zpyJ^K;mgm>=hOR0{p%G=;2OfnmtjtvVx0gJ>5Agj$XeZ=!<=1E23kl$c}#P_swNyg zfS$_g>P;Yh^90^3ChUG064C_F0Wf8WmH}d`Aj;Gzj)bsjEXjp&IAkpAWb+2HC|yj0 zwnBhr7&1T=7#$!10chan7BygdWhfb&fPMFL0Sm^_Spd_`CtSlFb^%8L92M}{g${zt z3OfTu@cR4t9eYSR-sJR}CAZ%R}@QQ>4@kF-$`tBS6D$sHPft*A_hF zZHs2A5CssRh8n~Uq{GGrU|oc2fR{ca;jmDz4;N-c_)cW4VMMqP%Uw(v5!w)+wAoC6 zf-;;K07rumR;s9VHVb@KHx?{u03r-fZKRXwh6cmkz?xY7u;jVu)*e*zfM)8SMF;_} z@&`If_GOs*6%c^a0CmMWAPs;}0U-wP13d4qqq$+KjVLr9td;_of?z8goPSg zOzIRXQGm^>HEu}Kb>V3=6`Xg0}w1aa8v~FkB4As zv@ncne8Cl-Rlo*-KhMEhgu87)i+?i=GVnB(pfl`92v|xe;6JR=TyGQ-Q`G)LmwL`+ z5mfPXh(^kS2ozR|0TsdhCuZU+d)cfbJ5gf@GAyqnC0<=p_Ux}x}j7$Fyu4x9hA8zN{+ zCx9^`6ENo#9+Ih0Cj*0&V+5!^c;z=oHZ}r&Q-*?1M*S0hM+`G0>m_f54_H5!VL+ZE zfU>X!2rD(SKn_gLE}=$J#0dT65FG+2j*?SZ+t>1mMT-z;=WNhz1et{v2Mt-%OBHEg z!~XezjDUP|X-qJ1@`$x5*uGSgIr^c^!7*%f3}zUh23RZkFl%)qpXe+M2WLsDvm8L2 zdSLuOx1uq~!bS}ZA<6)V$&abw>}(W5g%?l{5g0pz32Ed2Z`38PVDy)$>Lp{{Wq5)P z9|!swjL`rLCiAgQPQrS?hFkeSc^%-SjIuQ^tNAEXjVRbg1ZHG&^|_I1#OtKzu{!UB*-u> zrf1cty5NBc5Wb=ywXc_jYZt=mAaN=UP2f}yz$ck7nNK*Gv#h0=1uuafdjsnYhJA*F z6qq}L7^~F_v`!`xh^O9*9I`o6zR;A24+0k=aQ12m!VKoZBR`ggg>k{ZhyIEO`upf& zR4p43`D#-PLT6|`&lr6@4trpMk8v)u)>Mo;wjTv^BDC4mAG$EEi2@YDCRg_6pnT*) zlwmMOBMpsY*u0Q2LP9GAkVfBZ$t5_%&v7DxGu?!hVCP5Zaw$l)iJPscm4;-MO+_al zpXZMTfrY@ddk&e$FB(aHiY2N}Rb`mkB*<3a0Veow0FB0$L*@v}Fi?m?IBu(W{0j&C z5x}$rP(6o@0r17J6DI%0c4@>C&2u3xz{&}eVTl1H#1z3==(661Jawj$nR5(YN;8YU zTbydkR02{U1-5N*Hfwcv%pW>YYGlNatm|?J#-*EY3j9gX4|qC*Ibvue4-1IKAYie9 zxzLE`X&V`P_(h_Y#idB_h*Pyr!3T)ov%0|38|eb5AI$PNrJ7%834sWJQzBd`(1j@B zn;s3DSO!4^43LB(A;4fk;AS9A=nj&&jhJ}v9{;A7t!MTG%b7hmTJPZ@M|}U>>7S-u zdmB6>M{LqL3JqL4VPC)K%JK5shHq5VI7ZFesxME>JkrlSQ)6FkGNmn<6JP24Yq8R+ za2GZ9+|7#pc88W-e321%=gC04L+g`=&T&reB{#QAUjC6%7{lZw0Dk}+qzkEn;?~6? z+vkG&=3|-7*8r9>l2M3F#2y2Je*u95T9%wPAS#c1GmG4Ub0e(dVFC8jg;=AGNJNS` zDgaVUTDXhCs~G&ls?liBjm|g}GR69F)CR%HZ*DMOvHsBLO3^oMPF;Aoq6NSICqXEH;wp z>^b=MKz*CyKvzYmMS8AP?Z+$TAFLjYOJtw6xtS^_^E*B=^Uj^t%A=xM62?cuh0g8n zUA}L8nNiup3R6#|RF8nuJbaV^o`4wxy{ZGB^vv$6Hf>_~hg#I_7GeHSikbB<+WAd~ zlK@scF$55!(F7LHfvCzL6<|XQ9+p5dA%{Pjxe2rYhN(kq6yPe%0RIL?C5A1bXv_-O z0D)`1U5}TW8~Zx`SyNZ!tko_-PlL%$o3 zV4`#EW!$VaSUR{h1w?@GV5aO{Is^6%@Rfmvwb=iOnJh{$rp|_j-W#D5n4D!CXpdmxzAQ;V>s7s#Vh3FLAj0|E31vF%>0UcmwG7ERjB$&Fe z2w>EdGP+Rd!$M?uI%G9h`60TvDn zki<`HE8_!Z->pVq14*x}Ljj;LFCkFLaX}nHS`cpPu;fG0@cVfN2^&^FcveKibY@fi zjE&&cNtAZpD*Bwq19{QF$A?<0N~EeQgIc%x>@}OQS>PoF%{b<+`_LwC9=AO>^dr}) zs^p*S=g(i8*f&?^UQ=z+Qi!%5{J4a;Us${4uawDJ_af`J4T*{hdPkcRSj0t-4CnSI zp^Dece2yt(a%yW8n^=n<2W28M(%BK9ghEk3Wg{Me(>ajIfu^rISwQH!V~(lT(IGg4 zAXB4;;qoAaG%>=$Hi%q|gvDekfIZF#@oX9LRMrVxW6}n32PfsgCsC*}J<2~{45ui6 zEv_EYY@mGg+Npc#iY4jF5eXF z-U6Lp*;I&&0ddpMHKPVkWMPXb$PmyEB>lJ)$aJLv%Bbd$NNYk)GEA45S}a8_c)}?K zf+H+ey&D#MlBt@82Gj_0RctbBHQ))>vXUk2-Ok)M1lFzx{sXC5E1Vu8jcH}>gGJ9g z>J8T#qHp%5uO8F{{Q~IL99!rqBN0-0NZ%K^7@f+J>=Xr4ql?OLV7ovEX0GLz97z+# z;}RcBY$2a#bTVsAU-~Q~LYbajXoMF~X4$+h#E0O6upM8Q5O8G!7!Ighko^NLBCdWb zQ{U|`4!|y#5A`7SWLbo2%KUE|6&tx0zo9EH1RBG5s8$sthA+5H=^=eJVTPUPY>aPwayy+0( zJ$+Gr3sFb<&w|Bu^%>bu4z4!?zE*kasNel}{KDZfbho?zcdtO;+@#jv^*o+YUpT_-uw8-pKh76L7YX2u>)+SvyHWq{{IREi1BP$ zLchK)++%Zt95!68ANE$OTxH+r4Hik8sc_BRiI>1HIy&U@JY z*j99Z%WvNw$F44+=kAof%9r{*F78l}{8g5-+uu_ZJ0Q9B)xSc`WT~;pQM*lMpGOSE zuH1<#lx}<3T=iiOPc!XM8w7V6%-l2-QVJjy@J*fo4vgo)coi&z1Gz1v+yJlOgys;PLFk28%Eelv zBKm-Cfr1oX0;Wn|iya=fk2t5_Tckd5%ViVmkL6I*<2P&9n1*{l8{zzVXoIu|)gZMw!GFv{*eS zeJ$bOi1{z~-o2B&{CTL)&2jRIT9`~5_lu`|uZioKNB`cf(B@zLOIP6PR6h4}r_XE0 z?=N!6^1egp!;|diy@wPTB(Z7 z!>z^`^Z>DqN?v7rtf3(TgSK2V2s0#uHS*PbViN_B7z}&YNwEs3%2Gnl7CAfr32ih3 z0Yr8Wq-hYSx*(@=P?!`)memy_)<8V1p9io65|n@&sAfX8&7$C?Iw<)7V5-jApvf`3 z^fadis|*YRsOa8kpmDZH|FIkPksmU@IlKS>MMkSax>)ES&ls-t3E~0;sQ%yvZs1-} zKMgm>f~EhWCX{hk!nJi>NO%DY%A?>3EoDgF7XPg-Y_&3!iUuKB!?9v{nU9nsI59B;H5S2XGc!&{NuNt#&|5sY4&gI!|s$L^cz zMxT5dy7}%BYD-F6%xq{H*41hfqAbSxT5*1q@$+oIzM`ylrNocnwfY7bVV!Nw$0q`- zO_osXSVzOx0dD1)F!dtesvQ!4y5F53y%Onu^|b4wBCn&pb>zX~AuJxeGO&v@`!KY0|eg&Zs*_djd{+@q~4Ct)g| z`u7ufe1$#v8{+Wg6=8xZtOxB1W&%veFL7zd4W}YFZ}A^7wCEncTASc5?KF1zc$(>i z?$##nDC7IrS15RT)aM`1`TFO1o$o+hgO6HWVr^UHpR$rAbjf|=N$-_1cUDRr=Obr^ zmGz%GpT0gLW4*e?hq7g+-Fv31{&ApfJxX)**&48-L+9sMi}<%C^v)!!y~J={s;&J9 z`PUbC?R`r6h=h`!qpsbSP{ys7i`OQLvOv+9y^y4{s(q27&~~DCam`3WP8%zz2a}IhK(80EGIyNGvpb4lfN#K3yMf{ z4s(ow{OkBdSp_?nwYA|@uiIG1_Za;;E-q%S_Je;2|^#KdKX#C;-L;~i(bS2Sh*!gHQ_Sv7@az$ zjsiH|)~3=4IKtV07#-&VwRfoR17GG~jX2zakPAS+F!+})Hi^Nd1@z4^eT!b!GHaeu zJmX+2n`DVV+lL@{;vj(~pj%mh%|$bzP{tbw4$oTFX@e<0S4K%%yTp z_tW%G=g2N;IsP9kc!Cy{#>HmN#qGDUi;_7jC71HOX?$;Y{9Z-%5OVdn8W!`&aFZV8 zSxY5~_tJUrO+Wa;p0TiHWm)GotM{jza1dX3V&xGMpq_tg_QhxAqR2KyIZCdD>;ChU zae)Sf(lYnd@cB9FA?J$6bn%b;YmQ}SZY!Rfe30&Q#`VVc_Vw4N)_J{Jr5zd^GWWR^ z6SGqPvoTSkVdtN1l{SuF9Vd!R`o4ettyCH`CZT7pvWk33$6og0Q}Ttf&z{zMz4%M3 zs#A8GJykdz%PH0nuwqX>=r$V8O*vpvaaroJ5rM=A9YHoC;@iXG0`nlDs~31O>Dvqq_q*JZ{V@) z*tm}>Oik)p_3xEAO_s`u#nZYst$*c6T2>s(`+RQXgqG^wKZJKNj@HdVmS50i*81z}lGRHWJZVKKpJPI0x_dtyyE1;y#`UlwyVU!=6{xu7gKwb8$sXneLxYNCN~Pbm0M_ z15FuCYJ_m8p+UqoB;-IdSvT;N=9~n5%UyKQxFuA`N9n}7s^kk1lzbSxP_CD)1EEC> z>wsh^L5_>UtLXsXLXaQMdJoc`2XoM@4O4fRexn!XL>*}t$@>*AAe$sH0!LUDSLbX{ zBj{jt=&XJda8|)V_LB zZPc35*oVUR55?V3OqUDltt|L*OCX2wo)z+>@Psd()6MX1RE2l<|R9!ZT-s1M% zsl=?g@1pMS@p(hp#NDL5=MAW5-wRQW9+df>9cUmOb~P{j(lF_ytM!`Sj>dic&)@jz z{=>uZ_W1Ep%U0WUhqPtpo#n=h-@lbtq&KeId-Q5f`%o5)a0`Zhlrmf6|7 z=ke~JZ<^%XwjX#VUv|~B@`P8Q^uXyXqfL$~FEW^_LmWz>UGoFI@CM^A+P`enzO4B@ zG4SNi+H0=G>QCyZouiyM1Nr0yv%-CQ+Ew%Ropa9VEUU{X^77EyGr*H%sPiU%&;2_E z-xAMjD2RW&v}Uh&nB}>Lk6oTlH>#ZNxH8?m{@)DQvS{s_lTxnPev2oyR?y@P(*1H2 z$49q1iR*4Pu^68y&$yN_ydz^P=bLK$`tQ^B%5;rQRrBu>&K%L*&{jX(GQTI|T(t_< zZeG8)TK~{d+LN-Y38dcJpdI8y4_^#y%FYPOV01hF@ZGgZryx5aa|s#ul*}GzjgfXQ zxf6^-5p>N&k@!WJc7LVHP&c~t-**)?Ce#tIhfzbq1*R{kICQMhlr;wW8Vza+e;FOv z(ORMaQ`U_kaNdY3u1FHblOG1%hRG5wcRc|$uw1wx zfN_5KE6=R&zk`0?K0RNtcuM9^M2zpd;SwFU?CxKFv**k`zkfI?srC2*OEN>Y?R!h< zf|XZh#mw{Fi(b8+tBWHl!B>qw5oW zX9DDyK4+9Gw^cs9`sl;!Y<3UTv8*QfcFMVvre=<@Rt)bJy@@N=AE}wLYXqwn_)Hwm z?B|a3?~v#>{&a6Ux#1^YZC`Vx?#|?4tCD*H_lz&~9+P!+58;$MKaD!qV;O+-js~9{ z4&885QQB>HN#I+q^}Ip0Vk^OP*>Qq#_sy$Ka@lzy9HX6kY-uW|U;8Ae~~a+xuG-#@{IT9$LLH{L?niaOdl*`gKN%+akZO7PxOk9autQkuJ?Y zI&?&PceSbLN&ns@-S{X|-8){FOxQm$nrUQjGNfzXB)^1G{c9?FW@{{dy>07pN)9XI z`1ljcq=XqvkW(gx42^&d(q(XkSN;UFnc%%h5PhJgmCy%usWLv?@$(507Z4P++3*`Y zHG_^o9w?4va6y0>$xyW>5m=DI?Sn2Un@?~WG&hMu9_|o9U%fywhjP_W*EIr*S93Hv zK?;adW;MU4+)JpFF3xhcXv-Ixt?}=Vy27mkk%?dR32UIA1XwilKBIurk);T)ddJ<$hJX&hc;Sz@!0on>!0AeGC z#F(!fwBTzwW(cvQF4_!g*yz&w_#-EBNYjVkMQ4Tx8M^ z9GB%?=>8`Ut`u3{L`>*!yDGi=J@nZe*2e&pQ*Y%71gT-Er zy{`+Y(~BLFE?q}HG?pzJxy&OM(z)H|efL}K%#$IR!H=a{QpC%TR`KV&3)!5sC7Oi< zlHRIvW`%CKU)|M1GeU5ktHweOOAXDXhRP0g&xP+=F2o_bog%T?^n-SYBEse$jc`q$;M+38H> zR8{Y*_Qel0f5#?=YQGH5yVonV=JB=f_s=zs`gk0Ax%&N&?9AlEdWE8Om(6W=9oc>Q z^G2?=J;lIhW5DoLcgZ|g+o4Fc#4SpmAw7p8GTmAkj1f<($t9%U`F88TblL8yE$&UV zv9>LTD_d0Z%(x0_dGCkv1lTdof>jAQ=^=?3%1)_Y)Mpp%cGHx~rcOB*1^UeGKW@l+fWiW#RL&KLN(?iwZrMb zn!ms9JF?wgaJs{?^;faVD~}~K>cFROU9Ude`)^+SwoPPS+XWD^KRs8)8||`KltD0D zs1}%(QZ4793z1DO5F_-Jfl$mZszwFbB5O4+IA%eX4LLua3PUO7ukZw&eEg!g1Ojl2 z7yUu_pb?nH$5}}x_O^%DAFk8e{*&F5d#JiO!Q9g+_DH#bQeNmT-`yV_EU#)Q4COAN zHQD#~^tm2?Qo4lZ?CICNme74Wx8llOP1cty{;<7UEA5Mt{F?3WYT4)1+pCm2{8^M} zQ0cJJkDsTEiqvtzgkxQnby_sk_P9x1DxMOccc`UJgU82;} z@+7(6LC;5t8ee0$y$`J!Z9hFKy(Sela`Q@}S2Y~3zW8Oo*|q*pW}dMbDDYia&H-!l z2OFC=bUvQee*N5hl3`nH3$seNhb z=8osnkJ?||&93sw9=?3#`V!)=>J%^h*&$%5pJW*o?95v|Z&xC*|Blt?jCEGKuFIQ$ zaIWpBI9~9RPhmowS^s8L{#Qv`s1ZDz#2GE)+20EH1 zXgan~0}{|$LQpy9P_?0S4~|2@I1JMB3 zmH^y^=ow(B8o?VEdPg$N5lhx4iTuokm{owF-Y&yn<}2#mSWq@4cEX@Q)#IR%)*R^e zwPEHH09kK6<)AU>gU~wrSAY;l+H5FSQtZm0YQ0YHMs7sNT=Vnfhw{)t2h}SZk#L! zV=+Iye5&ibgR6#D^geaA&#PiUK|6DMe@|$M-5ww3+gr<=h4|m>lwoO3 zHroEdT>#aXb=I@n%Psn2%F`X0XwbXE)j!r-q(R%T#G+@GjFQMok@Y%Z z(|vC%wVe+rnKqBArKrAnX4_El^WSq`REckYn#6a-*Jd|-D+=sXOlm(=tMDpGdt=h3 zk6RTYU;l8Fxu)ZD#vsq!Cd%{v*`8(ldd8L=dYLtt)KjKbzW(eV)yoaMC&?#$xnDDs z_az-jDQ|PM_Q;zL-1JO=^JCYuA`e&T>ej0s%BT1K$r8>f9+evOVPV_{RmoR(zX-3( zzABQEH(xg2vURLZU&JNYxi{M6Zs)OOhf6PPRewr0yYa^6oAdW|s%r*{#+R?XsHxc9 z-Jv2FCv19&vxHXNsphDC+IWBTv|63F;DZ~dI^OIjOYP!$U@C(}92x)RLrGb&_VHwqO}Vs7T;x9B)e-x7+yXX5R-(d(RM z!A9%P$6h^+x!kmU8Zf+}oY!V$Ax(`s5bwMeew} z`&h^Gl! z<$uN)^DBSt>fGC5(RS_6>!-VqbO%}Xaq_=rmf1=bzdTseGM8%Udu_zN;CFc6!3(7| z0@FXo%-Ob+M_l&qo;MSb>im813{mI!oU`n`dt#$fZ?!*j0~S-yE_)Nc{B+BKYs)+| z`@J11C*Pv^SB}5=J58R29Ml;#n_KldSG@3pc5l3(tM#-~nLcT-oWEBhVK>i^XYtLX z-yUa^nZ#@%)_8a1A;+Y^k4F~gir#cfd%u~{l_=a{{`f;-)}u$46%OU>&e3>V-@k2r zJ=Y6{?_Sd>@S#{a0B5tpO@ZFVR`|1@sDPa>~I|bW+((VY` zKkwe&{5+kc_bvX;i1oK8j)kIW%RfBw-E>v+G4Ud^Sb6%ViB3psMX064X3#$t_!^>D z?%!ko+a*n|NTTqxdA#yZb>6^jGrpa{Mckrn?z23(Jeln7G&(4BpfU5!n=E2c z*`WkAMZIbldUgC!Mxs_C^m-CjWRxN@JPqLh-FySBObQ#CDY!`2`#(w44W8+6A*vDj z^6>^MeRJmezZ%3-U{*F5-o7aZ4f6|W7zI?)2*^#(?-W<$)%IpUa|;&~V(7v&`U$ZS zv<;gGZ5zU^>6AXdU!mt;o^-hSN^<>^FH)XI9Q79lAVCtC(&5VVWO7UdJ*Ij>r+3sw zd=EDo;7i)|#n-P{yJ5AfW5C*6-v);a-|n>Wt>1#yzBMV3%D-!9SEuNIq_a}w>jjy< zbb{{Phod61RD~z*9&eVA>Omfv*|Q7oC9&y0cU^fY{XW$-zh32!_LD8DB7D1)^1Zx* zbBc>s-rGJZG4g8(?Tgd&)Uo1C33oF)a!c=bV2n#}zR=A>j*mx6x`j|UfLjWt%I!`@%^>;@6{Ubwg>4f zxK-qFCMTwLemkG6R(?Ro>)!Mg`c0FMXH(alF&Wc!9(7W`9X7a}dQwTM-IycM#MAuGp6kn{fA(30Un+Op9w0(Z zd;5Jy$G@*4{;VGintyj*Tl%f*{+ot-TsT#0?@tHUPBaO+t9F@XS!pXCSv*rz)pL26 zcl)0PDc-8ohV|Qnw>-%)3B30*V3EXOJ!$@#d#$$i_k-~DJP|iKuu(&!cBaM~ z7Pbgoe$dGip#ja&cyF?;hzdN1!w1cK;AbOr8SraqL@aUx*$3T;+A`qJpENUAE_&4<#92 zOyq4#pOzQ$J+`@W{lcc7rLh99Rm_K9&-NU8bM@uvUy=sYPDevap(8P8yr19iemlCk z=2@)1q~kmHhlgEv1nBMV3|iG|TJpz~r(*A{Tv$rxrWGFdihdu7Oir?`881;D|M~dt z(3a&mJRX1L=UG{E%5vMh+f-)=wKWi!|X^uu_q_oMHDObz<&Q$U^eZGQI zlwlM>e?%gW-fQ3D;R2)vCt_w|r@k z&KdFAa$*3xzEVLq476!)E6E)`&PRQ`ha~nm*RrLk5^c@*G840Jkh|{0slHKnAxizN| zsXh@dp?9aPasoH;_q|QPbEKyL-2onu+>_lA`I>ZqIJYPUo`}3OMrf-zYpWVV_OS@M95X@EkXy$=OS9B3J7wGWmG#Z26EbCQ1qu7 z=~(R~^ooT)D+Tpk5_%-3Sdul+%r_LBAd5f8)*=rr)yEg$!OzBxKp%qI7$^=RWaznuHlH~Nl;kiM;zF9pg$4Wp zAU-I;i-;*|%`(K7ko5HJju%gC|6M%V9{c=+lUx0tha(EX#?=c}gh!2O8V+xbE4EZU zDk3*+dzN*ttMiMUl}g?BS1(*2ND+=bag1Oi)i~zygH2BFe>c1}DVCx=P_@-LJni$l z|AeoaQBTCi2c|R6x#Bk)3MCj$No~6xS6bAqGCy(Pk2%eUwO#=tVtiMgZc5VaNTu`Y zl~Je5_nlut8{I}8YYY^OMy986B}~)fS3Ud3>({CwXO~fxoaFp(g3fVwhBB0gO&e>| zJ-D%kAp<2B-v({se0`C>o0#q=Z>yR6be(G0>px$^YXgtB)U`gPxhL$fk~;Bdi)Ov0 zm6TFfrSpy*T&>m8W93^f&bBO}w|bd5yRhxTM^g?_c`b@jorJ-Av6$k~md6_JD?UGI zx!urr%(&;=-X0I>R@1L7ud`(4UWFX)4(jR%K7Q>qg}&VP%MiCF)7P)!-lm5~Y^Rq{ z?c&B?bt&1dwV#g66!$d*P0d8VTS5&%lS-|nFB8|Ri#er9TUyLqGKA^wd?LwzruA`o zlIdEK5!xU9=%GU5YrY~QE0^AYZ<+Bg(w^01FQEzfOMaSnnmr%bsg*wR+U}xA+$gd6 zUkCl|s_DlgJGLKQlPUSxM6!MLsM?ixN3wa^E$=?I4F9ek^X!D)jSlPIwXS6ghA|n< zJK|py)y^nf)EAj=2QPHAz_^zPTTVRpUs$k5x8g> zh&?{O-J9baeX%HKPyXH07k-tO^ziG@J=NB4Qc zZECn;{bBF;_Vn3J+4+ZVJb&nV;Lz87OGrg#ytpQLvi{uuK0QvfSIrp|7j{+cwpH`V4)appA6m1Q6IvJi>G%3VxdTVf$?q%= z9Whc>ZGz`$WuWnEc9EmV>)VnBQVIDqTfl{$3XSvdq*N{nr9ev{@eW>@NA>WG23mw;y^l^q_uEmx4+ei_#1_%tSf27lw$FI?S|>SLq3Pv z{(ZZAD)xaQR6Z%C(H|(M95#_ZRNUKaSyi$!7{nwoBe(01ZBy$3R$uK)P8=ft?@ zXY|e6g=5skeBb+A?NAC|UL#VqdpbOLtYhmSs(UaObu!>2cFFjbJe@AHbA zL!e??J=gc8shc)AugKdyckcPAyA@xq1=u*-QhN0YeZvXE2d#8FA6*LlHuK1I ztEBu}UbENaaNB`~_(}yAtJ(thwDiSQEgRpZ<~^xw-??wQWzWnbY(j@ppv2sewEMi4 zsI_yZ$lznG(Fa%Vev0%=JNwG8pF4ba*jA-3c`iGl zGv^}pu0U+8@{TjU7wtVY3dPOJei~gdZ?bj1FtJC;K5p`h%IQhl3qhwJ8QUNuh2x_d z?++$~x&`f7@mfVf#rb)d`1t#@v%BAISh;x}+MX>jeeBnkfP$Z@F)|D8`}Ou#l#t_N z?wVG+1k1(u#ENVPUq1BV$PwN>#q}R5NvSuSm7eW!Y2Tgnd6(?C^YY`zR_@RClW{&B z!*I06jeK^*Znpw=t`9pY#l2& z?X`Vfvg6h*eDl9Ge`;rXPAFG00!&tp0dZgc@xg1qeU-L!(px!#Xp3&`#DgVdHY|VV z)`QIOeOEa>hqLOgFJE=AxV2Ea&ocR;wZx%xk0gmDw4rEf(0$1J+eOpgk)`JrEqq=N zn}#pk?LR@6jWt^h4-9riU7l@z163C&*+BhyC-mg~)jZZ*;~CkFO@d=AEXOO~S@3WJ z)OPU4W~}fBXQ9gh8cg9K0r;x{z>M`ce;@V#+x-v-%89Ui89)4?f_ZPc6g&)Hh<@gf zgA?ST)lUkZ{s&?Uf5!x#Ooh7C=5rh*19TVIE;nAq-0f%9IhG~WxR;u?_l*Z@#k-$g6Suhj4e*XUyLyqks9b?+P6pX zY3RYc^37h){%+Y*Tv_u`Nn%o>IQ7BW*ZwT7Y=Z_0P-G+*e)tpGdMBtCVDgyzY=kQR zo8Q?7nqGFSU#(!*DfBES$$g+YpkO+6!wcP_-Iro^+hvN!Muqu)|Nam4WkOwgx??6? z?{-y#dHMUnxT&u#PNU)!khmbk1hi$CUNto=zM7?%^TxPxF_Dug?he8un>0cF3gr z4XjIg{J}*r5&PO`Wl-UMD`Zd9P?|@&Po2t0{pCKR>)XnkeU8168bDwD?+*`5IW@@% zeq7sDI=Y#W^#1ct6|bbP3Oy31=mvaNtDkw2?|z%QpCuV$xBLBp(jz+hy$f3JjwHSA zS1aY%ddBiw`~r3|(9%)ul2%=q?ACUQJbmw!T8(&Md8_O_8QZ9*`>y`36e2I7n&_Wb zW?cHN`@8EAK0G+Lp-02>s_^4fXTn$c40=q7<0SRycFJ9cvNJxuK50{P3#pvjx0Ayz zPW6C$xvvUJeaY`25@*&^xfpfO#<{6F{r@8AEW@Jgx;8wNNC<);HS|bIccU~&NH>zw z4bmNgbV>~%EhXKh!VuCO(%oGG&$oHMKOTpQE%&|mTGw@+;|RoYf^OM|*+!I&nHl0< zdXk4p0n^juF8V*e4(^N!_olDB=-SL)zg+%2?$jTF8Ok&Z2~LdjOWu?=!k?IATfWfu z5R2dceW$Zrt}Hzfn$p4eEIC`AtpwX(M5ub$;j`pW&cx3_76lN&KTVmQwOA7FgZOVOTSl6MY9L3989krmGV6^-Uz%~ za~C=r*(`0yHpKxJ$|l6*O&s=E^vPt9-uSqoT?*XJ1ott)+Ths$4xE>frcGH0x=l0#S*w+WuMf zt!4wxmt}LOTjUR8k1U<`g0I=* zga}y1oZ!UVPBLC&l?n$ukAT6GNp7x4cq9_`jx}8yo!TrezGcSQs%m}bnz>dgJ+{-!6SLmgr-nSkm@;}GB3yJqTwC^z@^_m{cHI@#Mb&W@ZC zv(L*D=?#bPsdB=|w4o9LNd!Ncs-*O1*P~3x#!ZfljggSgl*7dFK6-kigl0d z3SxL?J=rPH;Vs0><1)?`4jdEi)nhMy62h47bB8oZx4ol&Q|~N(_(3hwEe%%4{1(=sLyMgDak>6E+*(7(E8B zzrSCG(3N()^EiG3-;j^a_;1OQp~)%-*v2?x#j$e-N@gI=7pWK!N#d^XqD|kbQ}HMOEucnNxOYJsg~X=G-VE~!yDc3FNr>cWMFKB1Ff{yz+ z3>|P609*=e2tn!#cK&yDGpu2#!2LzmT0ZjyKCjd9# zXc{atbYDLA1)q3ShHYRF{8pvy45aMcK@k`Y2M|TD;DRF<7x%kzMD>=aN7;8H0mC30 z3wqfgjW`iN{=^#myhuj??F34xJK+4R9_W203G!r*Bp&dd-vO&YqrDv!6qI^Uo%`np zXfMIy=0(Ap!(QGwJx`H#yk<)C2wMP%-v~X#xa5*ASg}eIl6X zKga~`X9_u%J1#3Ky!mSVT?q6A*T?=?v2#XN-@h(njlLF!%t2>&{xy~35)bdnxA`>d zH8ro_&f2xeXsGbh9~lWH$nRf*DTWB|q=Uo$V8KGeX*|Wb`U<-oRpN}Z$B}mN{CJHP zlT^=6s%ERH=ZnAd-Q1RMrG1+IWN?N7OIjzf>qC>phy#SEhAKe(Td8 zf*oDnwG%brtkkzUN%Bx~?Q64YAaC>aPUoZ3CTFhVN_3e36}7wlH9|>|rQ&Nsdw1(d znhzyi;$;8a80nrY3IRT;!Gkp$3Mku^XFs+aHb6Uq;wRxA15 zeRkz>csg9-M}JLmr12STI%&ahzIki2hS)TC)Ibye&7p2xNJeDc($aBMe#%}~jmMTk zbn7#JJ1eN=<*}j@1d7XVN_<;GIaR{&3e&*07PfG3Q+a6K%ojm7?zZDv>iLIjUJ9kH zw0?<)bdm1oLlbC0X%wckXLq@dvo#w<83(PReM(WlipRHj_d1@-o$Bl~0e!5v`ow!@ z^kZy72SbS;%#VV#yhOCL@Bo+kJ?!;0b|-eN-F)D9J12+E5KnD1HLI>|)sD&nYoKj< zUg=_au1q{-1advnu>OO7`cO7yMl*M_*A-_a!oz;6E@*dgP<5<-)6zVvu#ZkWgD`wv z;3!ig=Y}_(Iq|*HA243OQf|)v&07%_H8n)%3=OQ4?Y+%hyC~FpS*u3sZs<>V{&~I1 zzV^FnoqYQ>N-wH3I3u`5>(Nz^qR>_$)u@m0vlpWGi(>EB$#)B+2 zBMJYZM~OpB;;6RJzW*vEdUuKTTw!YQTz$c7yN#!x@s>iD57chV(7&J4#kr146_82O zm+0zS&ShYQ+IUX(kP3&Y3I>VTO#DhVGhz$=0`q9Ln7p>Sj>nRs$Szx`RYfDij=>Dv z*UL10$UCpN6aCh%1J$_~1Fv?I=qX99wM#gCLcvz) zay17X#0$>EDgBtlvz0(a38(!6HQ;jREm|LFvgXnNuGG%`ASAEoe=8XX<#h>_z&Tj0 z-l`{1Dp@|p_#HqIRSi5&76X*MAb_;<$Z3G7EDHLHEwA++AeM$%J>G zGA%QRy_M~&kh|@b=$eilRnil+KatK|#o9}4Y6)8Fk zsfll!X}Fi+W|jo!fi`88P_rR+H-EJ&zq$>M~FC z4fYyTeMHLM4>CmEyst`l19b}Tk$WvC!cQ2|_O8I^nQ0)?x{Zy)a<9XB_%As5SOW8> zQ{g`9Go7Gbl{HV;`tso+a|Yc<*XWf{jhexsI&XiN=5u`sC%c!Xc)F5Q(F<^bWa!1M z7FQqLUd=c5_dBGxD`H`XwOJGz6Ek-jzh1z^xB5|vM2p168qQ}jwFc+ehvNkmx{Oco z6rcRm8zD}Or;#0|z0PL-DAJN$pa+(Ou&t}=#--mre&@zwvG3dJj;=Qle}2BPm5)*P z>FYc=qvO&FvRCv3|Kpei<=($N-v8-6kJXqTmq-H-nu6vy|= z&En=Wx-2<_`WMVsd$*c$&R?X<$KUNOA7L$6HRlV)Hzv%Dl83~Hcg6ct-FO$9JU!^T z_`VigCmPR{Q1l{tsy=-ke-TyWv17RduDTp`meCWn1K#;D7Ma=$FZ&&%^6!ZWsbUa>P%U2^<%&P! z-4w(rQ*!zEZ|o~b6j(pRCOAIfjPx8LBln=IN)epR|LDavG|z=UlG|wWwwtLcbX9vu7=~+&+pQ+G3WmsS3^)ipFf}7JQmREkZ%Hrj zDNC;VO59_aCqG;}BIxXzKFGea{JtA%2Kfj=(2M7JA+#dQ--vIL=#}9RL2>a7lV> zD_mv5KH=)U74k-IjL=Tva4!ZQCG>scjC3od5Z z`IGJ{o1W0&QOosArOEO$I5kjVU-Dm+Ufwd*Mh>qQ#h8)0!*6L@1}J~`G`y$A5tY)! zT-q>E6T#?~%o|Yt)>phgZg(es8y-w&V46lj%)%=Aju5V{>FhL;Ln8KWf|2h@_Qt*J zYSOq-TJ-f$j|2YhF-vCsWjk%{ILoRIwMmH(opXZyT@mpwS8`nF#7`}G!(MrwQN9%e z-{{r(>mvE|0j;nlM|`@Ge=K|$=%y)}>+14&`_f9$yex0%uO~yXe==r9IqG2yjZO=n zi#*gN9^{!X_tvrf)D`TE3Z#%- zc14Zjy0|J1THnj%>()WKc3TtRu{yFnS_}HrDB}S>2VQ@r{AG@UPUW;SJXQHx?AfSB zYO1;PPc{0_RmQ09TB~nMNqm?%_&ZsCE^i6&czKl*bQs&&SGty#$-)h~Td)a8=61cd z8U${q6lwb3RV#lg^q4~%=P91U8h@(opdKdrft<3?X-_j`0hYcm$N1esqtfzf5!%e# zaFWI%_eVA0?GMDJ+I{InnCyn`{+d$?efyV&K!3a=S2nt(A-;6&ISP6bSIYAwayY#vl?SQ>okZ z)d}vT0%r3nakOx-x|=7U;-{EEngQ!d$fsfGh|0%t0s{Jx5iGzF13*Tw7;kld43J{VbhoUAJ|ciGaH7uJ0MnM;p5M}QJVl#R>O!E#{`u_`tQG0@E`K|-{kSsuql3-L z1>X|7N5^lq@Gkw037>ZDS4vuAxl8Z=auRt{-MI*pvc{HqIRBI_stqiYSZL}?vD}Q0 z(D!Gc$|ZNvr9VDo_O~sf(4f;g2)(;X6lOI|S;>?}qCO>a7db;1wlT9b*z`G{TubEj zmGE@0|9Yu;7WyaLGCobN2QnW@bt;+^CaT(jthU--n3{Y2{nZJIo^-cu*v4BTQPXER z?fwJ9gl_3Y=QP^(Wc$_E{ex~sILg>VCuM;@ZI{DlbOa90OfSk^5UUb?exqTGj_|0W z6I?|_Q(3rPLkt|&f%;k0KePK%9_C^>gVgUgtGh9CW-sTS=Nt)ch%0>Sztm4%+K zFN*UQJ9|qRUe7l|K2a7~w{^A2R+1DnX04n+Rja%5^oCvRabJKlJ=IF{*-`vdQTAus z7z&F4)cT(aCT9{TvU|;vJuYxu-O+MAX{&v6mwYLfh*04X-UGZa6pGf&38#^b77ioI zJ>B8Ji;b`o`~1;L!YD3b>kYvT5fYam^?PYXf?MN0(a8TGVU^(#7Z{Qwuf9LgAo?+| z@pcR^`J+;#@>{K_<@l*mVZWZZtX!UKOyNP6!F(oD%_s(FIHz!i3VY8}4NVab+NmGb z$>|#LGQV^SlLZ%lroKrYqN_KBMxy&Y9l|B=f=*HxqD}D*P-L$vTu#}s@d&Uu(1nK9 zHgJAJ2nMlZt({TGK3j0oLhNSJRkNWgpnfF6a2=Eg4nmrfmX_wPERRZB&2P=-;pdm@ zx(q?#F#+625DUHsbG%2oBVgNFBXR8jUbis7BtZ}~j}+NBu;qtTHb z2Y9(pgs4yWkHjh3Yf)Hi)PkkP?CY2t^V69fTRwdDIqUuNl0WtD*Fg9$`Z~${yq8O| zUlECU8%8g8iTtQ1?RgZvRu!_|{LN(~jb$QK3xpa*7SS$M!ZusWW*0U-=Eagm<_jKg zM!@sFefz71|%1_=J{EG^JI;WJE!;JHv#1`tYIT zJdK($mg&BhiF!mB9rxeOr-8yWTW1s@RcpdHXbw;tB_n^ocLjVCO6@ew;U8>N_D_)W zh=1|QU@Kv6WkRRQr=@7p0z6u}Qy<7rgj4uRg;R$4e(U&XZYw7ZCo2x#1fa%vQCc(9 z2U~G=w(~10zmM#GQ_aeWAu4M@l`PPQ&N5CsWL^Em>ve%7Jatu(Z>V0Ujv@MwNAf=0 z38hDNJ%VhbcdxdR|Ela7fG6HAg!A3PV^^8it)^CYSNcMw8ds48u(bhX%WuInGJlPv z#hZnM|GQ*&cPKooNIEqY>mzE#o6pT5j#>~tf7@ecX(?U)2@O{n-o>cW--ayy&jyN( ztVlhxrQ0)YJ0f}U1_*w5szDqfKHqOqYMmCFjmdO5GE0AqT_|{GV<~bXaMI#Y~Y(}m{MfrZ)dT+e%JSw|5Hs#IWiV=}V@Idp3Fq`kQW(fk!=IH+44<@X{ z#mT{V@F)BSdcVeonmJQTB2Ag?g!I~v4WcU|Rx)mmxIGVHlXnY&KdOJkTJ;>h{~Fl1 zMyR!uKVPj?9JyWPQF(%{bOKGcOJaWg(qhc_t$!xERw`L?Jp`xMgo>ibqvBIU@wB%f zZM+WK%Dlp$)^EP|3#c)Nlq`!DKg(=h)m|}hO<*$+mwiP4bhVN0%;SGtY=2NYU?63h zIg??@-q*lziEtl>@1FXFm9^5JKRk7)Z|~@n{4s6o!?ng-{^WL7dqqb9AzVi6gvm@j zEYax9FJePMNNdil%PFF?xH_%VT9--Fidz+Su)A#LQ`Fc+SuTcIC^287a3@fe_NrsT zxGNHkA>+wACCtpqaa4-@VEyX(4%0#`^}7`CcV_+Tw+(@+KeB71Bb|2FM{(!Q!)>v# z!mHDNiJI-Ee6gMB^?~IQE=4dR_AZ(}vXmLJ1a(fgAzXWb{Az_h*|o)3Ke6K$qoMS$ z4Af|$ih<7!KL3Uxfg{T}PEyINeI7@aDUHW#)^i4>yKHEMRZlTsWk`Iq4!znjTg1a6 z0(%kZ!)v?O`5gLp{n^Xt>TMKVnAUflfpaE>11*U_fYP|N>9w>}`^n-AK?WZwJ{ zBbiZ7EY_^Ti`WNKbb-xElG+1|H$3n9TP3bNKNT7EH1qTuVyMVLtvls{cY-9?@^JDh zm`B4)71c+3j`=&1Vvo0?+&VCJ_3So1j%U*6j6+RusbUYAYoO^j-(1$^b>q*)0z2@y z9S9{q*Svz~_!)&JcP{vEn?^4w)oq&&lk8l2-iQe2*|{2I=|D@FX}$1*Z#B0Bw%P^V zi(z8mi3!+nmMGv!X7UJR273|)$kpIe0L=k_LJ(MbWVi+e@Pph^1BgGhCxH}G5)uNS z(7_Gu;yj1chUmn~y-)`hYPKD@B^290(^O-zT0+jx?(F_Y?>7Za`y}hvK1Y*S5tBC) zFQR_j)UQoU$ELo{02A1?D9w1ig|Yten%8M03m7KKwl0~|1my=AG!k;=M8~?)8uUKQ zva-hbR|hw-w3UP$hM0Yc$cF~aw)b zNO`?=&^7*thAj!1#pcz~1^I3%lR1asGe zy|a)>Im6m+Z>$(YqlYNgs}WeVj%hs;ssd&v>zFh_wju7sRQ&fEMgzDH*|q=6aIx#q zE{WGQb^SjD85SvtFHjol)F^P+GCMfWhOK^zx$C<1rYmx(L_bJIV9y61^o+!?d;2NX zm3`Z(oWAy->F1P}H}ZSe=VN3;*M^h6XGfRn@>=tVEQ(osv8PLV<;JIpFwX2lS)^cq z6}tMg5nwU|okq%M`~US%+`6|PQ)m+%mym)};v-6GpAi&ge4bwqy@Dbm2k;>U2~-sS zoYR;cV7#2Q{Bg&60#9}#oGi>MA`4OwwsP&;Xn6OcVRKD{x!_iyjaX(8r_GBAY!?3Ez|rdL}6QGnC4R*>nljY3DuvU|lYT6zh%z0?T3=Y9(H@f!>gb zlBbZkutgCCG-k|bfR;|136%DXoAqbstAD&OXpTX~4U6{m+GygLjQtNn8UMfnJ-etf z3NdvmyZ)vZCF5H#JHzY~r`Js#pE|l>0>-f+n2UyCZtoK~4J*hSmzJtF6=jSTu(d8x zC?693&TQ>v!tbp+!0rxg4fntJAN~T1igG`i9nz(!^9&JDg##wkAT`G1mH4ljrYPj- z^gQO<7A=-}7fvTHh)&Rh-IlN`<3F*~4Mq@^q(}jqO)j zd4+Z4>_(u$OL((jcAGF4g?5^mp11HV2ZpaFO&#X#M|4RaTCdyH`UO)_BJIsu1I z4uI2Bp+8tY&&%#8fPC%BMP3W+#y|q;EwOjtw*hupwXk;|ZdD-L{5d(h{11R0pNljD zN@!yN9B-wzD*euXpjTEfh<{xx0+{^Awi)E>E(3$wJTjPQ33M}{i-E|AKO?CB#I(0x zz`~XHQ~)I52*ku7DV^(ZcA*jCqBW(W5^FH`bWe7D*)#YqM~0PXP}4kNQ*8u|D&MrE zi?&i&w21eb4NSv>8=ml{vbpe%aM$mevN2PpB=2bc%AA&RgCsC@Z_ruM^P}W5wV(Au_96Hdl3kv3sCHIj8J73XzFdKW z()@Q551{-xo;qMz&F%7+77G^1knFU{Z@$107_ zjn)Uh=`>*9RBGFAQj5r&ZO{X19sLm}nJ0NLQNNqlr=h(8|1E5oM20Mua$}gBX}iew zXPp?vPOR&@PZXHdSw<|DK5{G#sS|gjy?GF4M|RJOkaFT7^>ZcNYZq|?LH>(uq6dn( z*DRZF?T!@BztV5Ypa$)F9wFZA2rJLuut2{Yrk?7ai(&1Qohn%A6ELih6$l{RjDtd58$65c?S;XO{HO zw1h5Q6}!5B-E|;+;?MCCm(PC?E>jXyz?qbm(}_=)eudjFM^DI$`B1RDgthDR`N&70 zpgJtRD+~$6-fa%S7zMvuM@H(lIC*REt>4*zvuL#vb+BlltrtZ^B~}X&lu!NWt>zZqXr}8mQ}%d~NIvJ~ zq0DeN3gRVK3aVHg9mZ^Mk7oPt5-EBc7}pI*#v2+)o27+hvx4j-CGjpNr_0hV6E(qn z_2AA6KlJ)>AG-ppX)Qahr8gEI(vrJO@TyxIQi10S~((qj39L3IbS2AMy%_4o1=Gz2)c^yC4?c&lXw%)fy9)y{T$ZjsL zO%1;25{vvaC$Fb#t-5gcl>b*%nz+aaA1y^j)s6vwjWStjt!XMM{oL$1PJHp)?iAxE zW5lm>vdu`dla=of&007hB>Q+ultC`Ut?OcHC9TK+M<<4NOKTN-6_ouamW zEB-E@rh8`bXZ_9)uLQ2_I#166p?MM8_mR3%bi1ooH0m$pVAk#}H5ksmH-NlsR`1rG zTV4A;&iKz&%r6t-pb(NS)0m(dIhKk(=Sz`a(0zLrQ|H{wcN;x_K47ok;`m#K0cK|8 zd%mK-GB#wtY+iW2mur;QenQ;UyVmfIqNm!9^-G@Ov1pVlU-c9Zb4cJJE2@J1GRoQW zU&3zGE(nx1J*Wo{FX;Kf6i=0&#-A)^d$L4#-@Plfvu|XWMU#tLY2$!z{a8&iIZ6$E zkQRV7-f)Tt4}OS$yVqEvpCI^LiCq-Dc?PXgcpZKTgKi-!d1pkfAH&xBNoBtr_+#hy2NEw^MBkb(UvK7aQs$Ljv zSL^?R_WlX%TW=(nc*0M9`J>c0w#S-dSK;V3H|>r&sYUsc;q01HcEY&oKgcczU8Rea zb&4FbkRD?MaW$iC@81S~)XZh<>GCh5KQZCMeDo!mf6HG62J~y-=@3ZgQ}q`wGl+;^ zRx~Tfh?zX*G{jkbL6#p0S2VjoF%k)Z5_q6s5?oRYVE}O_h9~LKNu<$Hm!INq>c=al z_18qhMXKI2l(2Gc(~Z}f!s+f{t#Jd#x{(T~@`ij#lzg=OMoJs$cE4hwgjOtBgdcdWc^BrDC9M96urt zQ4R#nH8ON7ksiTQX3F>A^Hk>((YtZn$`la=%Nk2Bv#H+drB+4vem>$in2p;+!tsY* z)5`hhrQ>h9J=rfrb8jQ)?p{cgyAfku4F0cs2j0j@$d6!AKqo8)P$7{0q&x!eS8%I% z%#7X0bL9*oN;kp<}6}21EW(~PPZL1i9Q_-KyMU?ygd)(1K|}-&R8Rp1Ub#Wp8lN~9 z8Al2OfU*O&iukVpWI0Fz3iK}gAcG+OV(+b#z;GouMDQdXvh5uS0iwe59)_n!_|_-a z{=d>IY8a7hS>WbG7_`unf=qh}b;^&yar|P408OPDYS!o=z_;e+)YiB1$B6Od$?vuL)&(ECq3*feTXFyn-Z_51^Q`2_h#_xZ`dAg zhC5sB({~E~EmYkir)B!_qwkT35vb6Zw9-nch)>nAljgpH_c%7ol~|rZaz0|_uFGi8 zJjNE5aRNMJ97RgCmk|{4nbku^5ec`3Sw%ajS+wuQUAIJZhx!@5{s%eL7(UWvC>WJK zsv7Tul{d?HlEvuMsETKa*20vYJbQ|b+XfO+py%T>qzK72Dt`)q!yr7!C>D_&Uf<4B zceXz#go`Kjhe#gz)i1N>HP5-SWp**PXbT0L82861w4Qlzv7oC9hKI4Wa)5;I%AmRE zviaSK!V5yTzq=Y40(&vchyiqTnUWa&Q=HvEg8;>spqjRM_m81`@eVE;`uosOV zAK+foLczV4b|jA52LQ3Re&oQKS*0fhwG4ztJ$WCTIE^m$Kn3Y|^ z+X1NFoXT%#4VyUf;nq@aamaTDMV-{y0nx-_*qpKX^Y!TH+HAYoT^9rU!ismBy6#?+ ztaOvCq^A~1LkQOn2Gxa6C>`YAUld7pWSHy(=`rHvnk__?l@UD0d2`5dFsKGApS3KE zW}49Us8l$+;Ez8vji1tr)P%Y%$3!Zd2u5k@FX&Vf!o=y~js3Ybr%00v?p*NE%6m@> zqqYJ9?g~1rx1+M$%~mTSl_Ohe{qql-WDSL6(8*#vhGj_jMgNL07ZDXJZ=_mq^^Dib z`9b}ttl?x$Pk#!vv9nTuGDA@_-z&fHjaw~O=T5Bjf;Rg`u z*q?yYM##@*Tt6Hcz79X}1-d`IH zbJ=9aVo<-S_5`W2gIi4{^^(+8y$&27==4>+ZuvEqb)rKc^jQO%OBXCYFe<&C|J17e zbK+`y5hbxl;Dw@>La+;8mo_2q=VD#~F-F@M1i3HdyLmR>r+g!*$9En!^j+rfbFzt^ z%DhW-CIgvfSvfJ8Q`bd(YMcWULIxz+F|{4XO&^)QV=7XG5_ZjTKIK0YKveDMi12>7 zj5obQ8$XnsD<63C+UVDF<^+;=Ex~xh^-EKAof)6bIs11ReHH4~RdwZ{W347D+5?pR z?!7;iGh#O=GcGE!6?ZYzO$Z4se%8|JNcWQ#vuC%Se71Ltuf$L z!64qa1sGyLD;MQ5Z2jCkJ9_a+w$Aw032ykve~>TpRNe!w(1qXG_mda#;#+t9T$7$# z!=VbBrw(73WBX0vq;0{5V-DOI+mozfTl4+VwM6rE!Psl)kdvkKGkS_=++NR9VVe6n z=}YQ*o_Ld2Nl4PN_P_m>tZT2x=tMH6mk-7Vauw`6t%N$ydW*Y}WUwKw!|#GHsLq1B zD(PQa%j8BZ$h`Lu?GY;ZSSM#OX1Dcu-zV$?85@PS-BIQia??$Vo!gbgf|j9z@BQ5D zjB@o#HoeR>d`ahyuW(VXINi6HGE3mqLJMF;l0o#A-SD8N&n8CL^AM81#8x%sr0+vtLxkoBFO9Td~27Q=z-yl53)U8Q><=zMqxUx zzD)DV4QAR0S5&jFEf2bFYK_*79Ri!kul(`ECa-|lmRAAvfjvy8HpzHI-_0q1 z!%02rz7&^JUz01*i~W+Q7vO+viEwft%H3CoE=UfbHHi6GGym{9?^3yh#ZOJOX=F?% zO`*Xt;f~whUZhhBU$&w@^Sx5#wj(?7*BF<4Z-eFVUE*g-;^o+$W)?6Fo1dUd=O%a>Lkvf>PP^c;FC=%PZ}oK zYc5D~c$N}DO-y-$-<)&>Wf!Ov6Dv-bq)071KR&3T0>S2u6zLYYT5vTF{sE@Y@)P>( za!-L8MR<})s)T|-cXnCB&C(r)Y-bMzDz3Tiac|GTtCxG%%2|k%o+SHa% z@ts-nclEXX(5J7wX(zUQPR;xcH?hgW(C0ast_b7=$Cv{hj;QQt{0GjKFYk^m3TS9$ z@V=NKv*eifzOQv%gRK#IHh;<2WZq;Kkv_D-OQ6#TRp}{yN}062MLE`#UZ;>}G01j2 ztP?KlVG`e|kgA!~nw^A9%uaqgv6lKPbu=Z@vnSs7BrN2CnsLUpb0W=~1Q!qAg zL!|x(U3^qTB|S0=0|ZF{=#U=V_KConCJ7nX3?CbF^N~oN^pQwHkZ4hOHAMhtatq{ClzGvIMT1Iq0AzPLag`*#d%%sMxmGSPx)y@C4Vt zoP-8oJO$POw991?Xqo|Ff?_d?34$}j4UqwRATP+#Bi63!Rs}1&f=iqL0 z3jwA+N~LzdzXhgL=wn@=mI`>!K;a(j&9kjRQcz+k5{3KDb%f3B=t<5GIlAWBX1$Px zHwoJs$v=eZ+5G}8=t|RB9j!=LQc3ipU!;BZJ6nE5C7akiNSN|yo*k>d!A5@*j3A=ZJ%%YE6 z+ZnuhlQ=}v-LS|uQp{awS`*652oi&4^iR=gV{M%by_M4Dz8q$icYRw@{4%pqlj=4{ zh!fM@gzg~j0jUJwjSusAH3UhDG{4lVCSSMyPAAFH!YPXm5PT6NNST4^>&u+r^dBTD zrm@dGl5KUdqJe@sUUF<0`+1IK21;LAlWm;iEb-2Gyq*-J$fdb}lN_NUmO;z-kx65{ z>87Og_St_BcI*wm@Z4g@Z&mQY+FC8aPg$?6P0X-O8b80p?8FZj0bKI~9rx%RY*tF; zrwuehXs6;HXEZ(=ksH?sy=q6nDr2P;?f*f>3Ha)#Y6o={{&|zc{he!sA>E8*5|P|p z(~>zY7IfE{%@RF`7{6=~2_1RqOeg25Z|B^mB^=-QVYL)$cNpQKAm#A8ok7p{Ek>>P zO=6!*3tqAuM>GJ4d^L^EcZ&6zdhUl^#GN)Z|9eiUg$c2W#h__W#3$SRURoKw@n9*| zx+YfhZMxZEWnN)vLC`6){?o`Vc5@4t?13KVqFWdBs5uq}M$0m*MY4$xZ5orV7nb@f z)e;d&{!DgThXTM4Tb?;Ln-F%%K6QsHvRiHSxkq-Qmo@=k)=*Am=@0rpLR-Jw?wJ&3 zT}D636P&8$a@!43dR5`xf~bwuN*@ZFDFpYluG^EibuC`g zN_20Ij^~o22Jb8a@%o69x5!c_of0@=r&==)vudV$YPG&4SiVtD`bH=BVTLKMMA-GJ zf{>9n)IncH>dL9!_QUfRz1ro?O^w>CH>sGO zdl6)DpD0xXQFNsK)*2Mak=XToyW&(#WW6Djcy|!y4vkyC7#0yi(#cQ%Hh3gC6E$*}IYbND&q zL`O-&uI3T+l;MeEHt!P&i1^>G+vhG9WoE4}DR;8*M8BEFuxpw@nBtV&*W=-hpjg7Y zWWXisZsR9BVgLHP)R%iIt$1uG^BJb6_9WcJG6Mq-e6E{vqQTc@RydbI78I<6fm7NN z8PLE%2Le1RK*Jd*UH+#n0$+VhVx!vv>OVf9vx6^$PR8iMrWeH!@xEao5dRMXw2AZJdf)~8j!B?BjjlBF zKVnwwohuN*fm=>+AQ-fXc;vj;12Qv_V#vMUInolCoGpSCSme?Q8e!kzFddhKdBC&_)Sj@j2jQh$sJ{Wf7 z9xjGysk~JzKRa1rF0ePrX3L3*Be&D9tLR+I3XYBkbQ0!OEOi27Hb``Y6LyUtCA1B> zq8D3UnO3%kU1DfQC$zs#cWD&gPR+@%yxc3)G$_t_R#Do;4_VK)-U^v8sPXKswV2Wz zBXsQKKq1pA8S?rxsH^&Jh{GzwzPd*LTK7{Ly@6fonltx?&;d`e1g%dOFAd$_R;e=e;lK6Hq&p25#$qE5m4x zHoT>XA98k;ttUV6EHKr-C16NFqTuj2sN-40eS>O~fXu8_GEP zo=o&L{VMhPt$p}fi$W7yZaiBqQpzUp;y>9H18L5tLs8>H{!+y269chB$tncXY?iel z&SWbOe@ji%l36G5;WyioUJ-BTS=TOel~>)Xv&v(aJ9MmX-d))dx9y?yUAxavFF%W) zX1OPmU&0YHQCfy#@A;WyM#Gd9v9rI_I3EvxajksbN!q_sa`!dvwh0aeKAvkv^5I`RVsu|Zr=e3LsE zJymZ2s1S4& zwHaKA4HD6qqh^gVsK+fZrobf&uh4C$@z}PH0=nNuViVOT!Qk^oIC4xqjNv1b0V|=Z z?2>063VjNh@5xxHa?lsHBHlmsyHh+;s4}V8+dtJ}m9kpm)0w_8TtQEtR=+YSPx3*Q zrFO(14{vBAn+&%3F;>ANhKhxOZA3hkGLRr2;=6F##u3!!wOQmtYOpP$$anGZ`))c57tVYR-7BCNj;C+NRyx{H3W z`;GRQefdRz@(+ZUCVxBQ!F|4ti}juF{-?Ea8giw}p`~lM+2H11`TU@iz0UVD_y~xv zvh`l~4#3TGF+5bB3OIkf=FjXX+T=$P$Be`yK+}Mtq2v&r@4!kZh3D;OFykooN6^9S z1dMTrLE#nY5ikKBM~{sczX@dU9Q@xS>VHcI0`PJ~<$jbz1Nm$|dIw05gSr`*w@d_p z!3&5ZT>g(bNO6t?Y%kpqs7Zh_z^ws9MI|?&t;r)P7eF!rj*xhp0R@at9{rb8U>!Gz zK@j^M*sT~)L8#mxn5-^yQF8CWe1XF2OcmlX6#&eOMDw@mAQ*uGitXnF$XfuL-U0qY z0dv|d3&(I(phG0441-!MNwmIIS4nHu+ zZK}sunul#NY}TjqMp~MY$l-;N$ezcIYZY}Ym6TJvf;{G)FPBZ;@B z2u~vJBvL%{@HT$n*)22MTS?F>eantgj8rfNKm}-n7Yl|;zBRtSJGE` zyO*b}Ov5;5QTE0OFvNyw7g?-CFW_So5xw-{NchNxw=)&EX;Vx+>#>slo@T{NUC8WN zOvhKenZT*s28z3T@OP&=XBP8y-i{{hbX$?{=cZMI3#&THu!(>16`_LWen&9RWGhm+ z1Yy}18^XC48=--x>M@ZsC<#JS9fSynzC?uY3kr-ehuS`#%7`FYy7~wd85%-I1+!;} zAP%@^?{~QdJCA?&SkkPpjtDkx9oGyS19u%s7xK}Y4?>dC()%%QAW^rgg=FOs=jKNR zielaVVX%fb>|+P9n|LQ-vvgRjsO>aa=dZGf}dU(2HivZ>ncy;ac|BFb$HWVpllx^6sDY_}Y}iVl3ze z*Zcp39CHQtiG(p=M5C*=9dFz&y~WqlAa+Dp((;1_!ds?jMn8*q9|gk(U#C3o=8DJ> z#ezjDIh1E7hdl@7B&eoKQJNf)%~JCu`rBTVUxK39b+xUDNgCi18%+or0e*p_+K0OQ zkFV`l`x|?_7;nRZE3Ym7`DixaeO3Ni8m8JPmgdq&S?*?f@f==IXfEumCqL?c%(lAr zIfS%K^=}f23r0ZdLMSK?*o=f1!(W{-%Mjd)3RkS|q!)&-J;T+FH?C>JaP{OJk52Fl z55DA?|1u%Lw({|%vO*%o+;r0iVJKekwluR#rVwcWV~=My#G9fP*|!P6)Pcfu4cMO_ z+Ru?K@}XOBGLJdE2z&;_tE>RT!X!Npp=~SG<_-yc?45gJLzmSj@y6B!o;u@b( zDdS9UV)sRMN7YqTFNNo0S@;IX9@L=BWVng;>~Ho(TFx|_PkUw4#;KdViw|g-hG}z* zUK{ruK6!c}wreABnx}nf^}xbm1t%RpFN~2wR^~9m>{?X{S-*hArz^=b${a~{JKIaU zk%#vfl$SBRWYk+%f2*{=*6{`?I>KsH4Ln$WkKEy1`)HC>@H9p>$nLDq`rlGv2=EIx zK-Tz4%1xhK{Ud35pW`FHquHD_`i!0 z+#)Tob2`D$#Pd6pNpT?0t}S~wt6p{(Ka-YElk)#)`U5}dg6eOfUK)R7q8YM)!yHmOm7#jJ#clLkYbMUyk;_w~L^4#Zsa#LLYdRcB~ zip;UjZ@FaPq<=f~pKrvjVEa6vt6fBKK%#AE9k31*EWJ`TF~hW zsOJ0VN?x#l1Kk7<80a9D2r7&MtF!P3mOrQzyjI2g;Sbi@;~jN~iRyh0YX}}^49Ex~ zEdom^*wTR+(GAq7-yBP@F+rly#$+t9hHTQ9@ueU|=V5)QiVsxm7IZ_(v{+*jVVsLf zL8uk~T4MwWoP&;3Q1SdGADk>gR9D5&5ht%~ynjj%4^ZF*fD#`NbPL*?j(`P0xdwWJ z4cQhR0cBezPo06`!yZcd%({+Ns;sPKazXRBItV=T4jY2p%{1q~*68P&chn!(t$| z<-XQbd%tzcdLDinw%$;pL2L4#8vwf+rWBdZgaMmjAo=}^j+YkdYH4$ zn57D59ilk z7rH9z;IRr*Kw}t~2P@5_n<`!_v-@ubrBuycExCaMZ zfes7_LePh80Am}+v(Cu%HV_F$!*jFqT(Jx!Ga8MTH$LY;(7a7=VEo(WR&$~0c&9~+&l46AIODT3giLdA708E}lww>VqpKWPbL0-B3h({mdr+z%Y zj^xsvHCzD6`TeS2Wi2t+pZ$4pv>>c_%G7O{VX{r(4D>G6^%0y7F46= z44JVIEBeiLmu);whhB-cdzBim@N4oq$Gf$cmCVI9^l$G^S>CBO{^~Z=VuZ8RUfhyI zHJnQ??`9JIEeO$Ne&4KAchdE>N?x{ipr}wrkgBLaui=Grd7OH}&r!`O@kfSmR^}Gl)pl)Ru zPBl#aZuwwkt8GS_Cft%8OQcIo_Q8g`F~&GErPFn;mN@s2y;|`vU*dH@V)X#uuv^}z zj>L}vTHSe6uG3^^m3IGwknaQ_TX?QTT5n^DS6hgDp9dP(qTnB?0mms0LKB(5pnD*} zCUlWa*bI3Sq#?m*2zYeRFD?%O9Tk)xKveNRFs{K)tqKIY+c42>7!L@g(FfzZ6Fn%2 zFaVAEpO`oal;ss;r~)fF+Oj2tE;p56L{~C{zet6`06h}cnBC~GaF-eo+?rpych)vy`BZsl>LeymL&=niE7})IekE(NBoxcEP=*1|v%SS4eR&RKrBzoEp4f z%vg{BIKr;M%Ygm77LuhV!30t!$I}DLAkys`6EcbrKcBioa!N5KvWdCd6V^%KjZYWqf`U85B$LL$la~|a zPwvXgWEex+^OZ_5In8YzCVO-60nfDHdn~0G%jVu#yqMV(hZ(HbdCc~5G zG&Peoujr$K0xV!5(Oz`vS`CbKI$!9{4nP{CQYNMP?9zo&;#KTY*E$EnfjwFkwf>Jq zO3J+6`k1ejb>g8z$+IS?fjtoMedO|fdQ-d=()sf9{~%RQQ8GqeE}M>A4tO^{MVrwo z;740ycsXs-JYpj0e-L^@ifz+B%f!1&PbR-_4w`wA&(hKKHK5!CF@2-$>cpA1KBU+N zvPs%MdA(ZQM$7)u!9K4(_P#=-hiP|1uf`ds)wqa`G`sOp)HF)4>Ke-vE*(;E874FN z2H&(~wm&X5SCs-Kz&nqx7VXa+5s-!SdmMs$B}?}m5ivIaIR(sF$@&PQLZOUp^y3K} z@N3U*qLcJQNg}w!DR-}L`u_gZjZ|*{%Wq?xLG-Kuxmf1p=2m)T^(5-}6Zwr$$Db7C zJW2~%Rf@)i2eeI1B^Oq1y2o$ip7-@WmyG=w%(pZo2e)2>eCXZNbG9*H7$4(p#kTQ? z*PUN(!r*Cq-@`!nIJ=8ueSJL&FD1WzS+a5=ajIrpzU#trv5bJXV}~~6^xjS*tWPtprOi z-!k&w7x-N{=#=}iGM)gWDrcKz+L6sUr0s0C+SXrm|2|QA8-tgB-c!h<5qpB0pG`?- z9``c}tP8f!rci3g4PzWL?eWU*v@sEe9F{iI{d02Lv%5uhC;)QK%h$p2r45V>#1Ji6dSYpvKDZJn4 z+G2o!fVqDCA5Khot$LpcmZcA9PVmWK&HwKM;3N`gRSq$YIJ%b|sHxP^?dD)`f~0G7 z!uMIhJ6nMFsAD8zt^xG;3?j-biybUUEf3iSO_!iG)v+1UDjy_-Dggr-77g?)V3~IZ zVpI>oY%#h|$pl1=0eSYAgEc}Tep69)$*xI2I& z1_r9`gxugn5Ksav{BIjiNBjJu&XeTx)bZl%!qaG9Z)t7Gy^x(x#56Mn3@TFRpH{B1iD1FL6P zf88#!(4EmbXYU7bSDg5er$JbUt4UCM$Z#REAbqYt3-Cf=EXbLb;xlti)vKjg+|I*H zQy$%%A%bOW^YfcXgDqmZu0==#5C%P&(m%&(aj`3OvHEdBheh$cQ9NCjJ0xlA7QJu( z<|+N|GN-&*Y+nQ3l=_0#H+G4F3V(*;3xy~+&B)0lw&Y$cNYU9An< z9fRtT#XHdtm)bytNC~SILA}_LTfg{pznoFl{E;5#jZeo zvl#ca@BDc@F8V8nVwTGri(N0yDx!I!o{zX6NbCmSRi{aY7s_eTi};n@=N><~=q`T) z)ChCT1Pe8iA-&iVtn;jGYb{*P2FSQipZd6OH)&@KgZJXwGhKu=7YXFO9CcgA4&MZ8 zT2*IJx#x#4_4&lMj#JtuydR&FGn|MK$2nQLuD2=xw_uDFAr@B={o6|u^ z`hZrrz1q5-)Mde-iDOa5X^hkDA(C~(0eRBocCe#U!uL^A>atR@=2$=|QB14jQEc>i z&!f>^QRjZQt(XD>61`W}`78N-opoO#<#Hk<6J@%S4NKQib6GF(Sfm6+QyX%z6<7|Q ztP#`=mg$(6e+w4H60dbD3%{dR9Fi-~z4%kvQM$-QMzZS%>7!cOeNt zGY>cdO!6!1w43Z3DXdC}WqphEzLez2(tOxV)%zW)jsZ>fONb?MUpHSXx6Ga2<`ei9 z&l09h=TKgE#K!hz_T%$^f@befU;E@La~YUgz0`M4E)3t5A6nWViv7MltQCE+cTx$T zCJx zqEw05l&iNWoQ>^Gl@=FC;s@3H4-B2p5&w3hkHWuNHl;OZM!l(P?pw;neEuj2p8nYP z-j%dqxnUyD4Y!)>-1brN{Px|m+U1W&>O7~k^xvTNxC6dhaPn&{^Sp$>z!J_4Typjp zKYI6q7j~3M)v^%>H1X`|)d)m=V4`!UWyKSV0*zbb>kt%6|0kcJUjC~w#Kvbb!;@K* zajSkz*N*4KEmj4E5n`6Ch*KlA%i)LB$z9rYs-*MYa5MY=i1A}y`#7qctZ zw@1iJ-$3!byk#;05uIEo=>H&KE`qJ~A{#F+8+EM;1r-O%H4qsP;x@h$0rV&l5HuUv z9FPcIj(~C|0FDzq_pt#S4%S@ISO?}eJwz2sgpmbQEzpDm^kheuk#wS?p1?|s5hRF4 zfdG!99}8-S0U888Fwt4-!p{GVeS8od4Y8I@#K^iBl*OCC2q?^k^T5jRZNaB61KXiK zWD9%^Rtdt^3TsgB{{G=Ox_65Qst!X?1OMI~3UC1bw(o&jyviL38Zrbh0WJYqCqR&z zz;S}^dT@=t%q9dJXFv)lV+ZFBcsYhD6MhO%6a)<;A-p?u3{Oz`Xb<`0+mi4z)BX*;*iMRMuxHI!L z;!54@9Su1Rimu2>WLRrwLEp|Af37VR7v6;zmN$75xP!XW!Uw`@A;=A z{v;FA+wbc=*&exly2eyn`kI;SwxsFT<^zma4NMMoFVkf^yu66D{_wVA8D)_OqXbv4 zW$9Xmv6a|jNw&iIOUYnq7@oAS`J-Vqy)M?Y#tz3n%a7-kN)(d`$%!>vmY+q^-rvxT z>$W$)`0C`e9ITmG6DrgiqQ1LoP)=)Z;Gx0N$sPYFGC+$a;I-L!!7HB{m4`@_<3j`e zemmCro{Mk7q_S%7>7)4$w!QYceah18e|#e3cMj7-CW~`f$T$sn1m{(rUAq_gN92aA z6{b2KypIp7()G;$!pFB3qzUdJ?_%nC%L2Kd5k0K>6?o6Uxrb$MnK^KocNDYKN*L+p zqE}S=iZRLQ3!-?jOWJuR^L?7Ia&P2c&xY~*@!7}Mv{VvR?X>)TeOz4m?x=G*;xF-1 z4aw9GtdrC7l<50Ya;oQ$l4gzVh~NdcAyUd=gcc*iCsPVW_rZtq)#DXx!LKZs1!?kJ zQg_R^oZw`y7qm#9?e%i0MO1~Y;ZwgTl_4TIXLDFh7&s-ny>;RUxEl0aL&YC%uVsCW z9Fr24{9*S`UwMoxBPjE(vAk;a4`!U~`ug^_9igPd&n^cz<;hTU!wqEH5V>!Rv!S|N zIYpNe=|+~~vES^^y5zY_nd$)kDi@AE=?C38!^ANRHI5|&j50splNl2?hrlgbVx!qtbZ8w5!WbqRlZ8JuFzpDvb-&7JSVPv7TB4X&nbrQ#XdIY>rIy+ z7`NuamoV;l5-+e~Rj%g~&ZsD&bVWa}K4JgHpU+4~o$ok^zya!eTKl5s-|q4grO8q3 z2Lz{vQgk7X^fjsE10Rc3L@&;+wTx!z{&Df)z`A-q1TEuXGY!*!rWBRs)hr9k8SLzk z7M^EeP08RNrlaY7_^A}tvn}esYmh(2GP~KupmeAI9zyEg)AI|pm9?Yi*yfdcc4>p- znYPy#!Z1hoEM6@m;|22O-Bd2omc{xmePD-{5ttgN$ z+_pxl`S-xgn@CtMzKPr{=WA4$`RX7=46wkxa>ug#X?|%W zo|uyy6e4KU+cfG>fJ zydny0@gQLo^L#T1Ks6AbClK)h2sPkqfoU9kHzWj%=L~E~xMy}rMve3g*?LW4Ep!9l z2tVpMP#?2ReO5bq%D9^K=U_OPZSdgp7wvQ!G3HY04)gmXkc;}gHEcO)K z%4{Seiw*M-)zI|xlLy1Z`9DTAKM6}EPj~#laIVWq;{S|^G0Jq^C z1MOiwrW|h(7ZBcy1&)H9QvaSvHR1L_j&g7++ z$`NB5{VH)T#xSOImTS=IjcNUv?@!<+hI6Cyf|CkR!~IPb78Oy~(2j(M`6281SY5p; zKGK2s)x>8ZAq|<{WdB?Z%NH}4dBj?4Y7_d#Oj{yYO4bI{5WOLbvW#TwQClKfxy7Lp z{K4+R-1Gx3dJ9r8E004Ytfl>0>u9Ek)I)5d$>8r3$6pm$IPWga&F8*u-G&r*Icr7y zHL6Mw?U=^rNv(TNcxA|G;!m16S@qRYTWCBt(=vj_Jf-)f<1VfgSau? zi0_k>PL1pATk`XtX1oPmjt66Nn!>t>wYS{S0^Q1X0^$Mvy}D~{nItXK&_*3o8^Q$P z#MKwmZxVX!%@3(^BNKC97R*-pN%B4UP#(P?=ax%G1NUbBDkmWFXgo{5C3oy%TL-!P zUHew@Z_V7qaetA1Sv6U3lW89b9pc)=wOb=?7-_Wd$U;dos=Cud`v*OsjlKEtAK;uO zcAcAWN$lrkUt5;#_?22b$!Yyy2Hc5H>#9z*w%ns&-N?0=rIM~iLQ6sDKQUj=YU?zoXKj({;zT{hO_QyRuC}s*nh%3J)}<9AcJvmmUG- zP$}t@B^5bN3!;aFwJ=L~{#qGuaGkd{Evf?lA( zpP;8N5hQR1{08Q-=NzCR)nP?1B-jAr5SB1K2YOgwsuD#}BM`ABAbSBsrwQ0OLGlFv zHs*pT%KHegEzniQB(Cm=EI=y>#T-6{EnSf23?-b;1xumhM3(wjOeGHt5y( zr_0d(%&BiOIdbo(w1&N+T*=1;ePn;VFB1-}$eAF_X7^>R9X%$*VmA)-IQNNPzL#yOYFCj z4cscG`4#=v%T#83p8S3{R`v3SZ9Bw_bdmgDJ=M63jL%mOS0ZCRQ}+mApK-RKohfp? z`_bh%!>@`5Uoh2p@#}n+o^YsGd#Oc%KaP{pcI{qaf7yc67veO(bWvR7UDP||2@D_o zlf1d4Ls+wY`3PZ=7`H2-dhxa;-$7oJ*o2vRqmgtkE zO^Bp#`Z@On$;BoL7m4lby@+XJI#s{7_h=R_rmAvYz1V9*#B%vNYdrIMYCn4alU11% zZu@-7`iVkz`1ezcjsv=qo}--*U4!@<+azl{*A?%s!n*V9NXFQlq!Uk>8p>POUV4A7 zqB>?T`5iZ+JZ;hMwIjEb2p8j}7koKfDeJF4a~6&TyqLjR*-B4KOe8t)TGp4032QPn zD;~tTFfHrFz-MjotA^yo3Jl%T7Gy1ACGk2_FyE}s-$`p?Id*Py;cQ4&M>q&an6FiU z`Y@wT+1!Mf;L6n)LaE%@@)}4*HREw&-OFELkVdk(Wu{-0--nyc&!+mdFGeL^KU&Uk zS|0Y8=C0mQ4BJ%ud9E&u$3jxz_hmLWE9U-q&Yr6AtWCeG^H0@G2DWVHi6|GZwW4D3 z@;sigmUC@Y+r2!#-{m7)z>g7D}N+HV={>jZ?k*9-jBYN- zc&mOcNEr*PWO(AXu?W0c2q&;pQrd#D7m*P-m^OeXM2jO9KuB55e<~12HeoHmbfMw^ zOa`+MsQQ3yCIVdZ_s}{Ia2W>!iwGKx&MiX^II!}8L^CuahyI|4Jb{jY+#o6x1Y|kV zqJV%8b6Wz8RvMt3qx3Jnw;2S-2vP(x4btc!5Er}tCI~!_xIUP3U;qNV8t)d|@ok}? z+3o*|t5nJ*VAE-_@Vhg}Yv39LqZGd!;$tNO9?f4M8$Un*y)gqsfe9w!_HSD@5qg$` zBbEpREC8)I0K6l}z`q%RUUV_R4w=CEI}K6?{@IuSar4N%7of8E{~{8A2AWdE77E1Q zWT?9uc&hrd?6ij;%^K=5xe+5h{K#T2=Jp2hi((tG&S~jKt1%CDUx(Ja?9M$=De+SK z_?S-Cb2fN6S>@Wr%ZbAW@#NHBCBHc{tmurlP@Pv)n`N)ps*aGLDp}%2p=iK~OH`n{ zzQB8!l*H4uI=;50)GPR`<4JI^_Wnr%yVhfTV<$5IZlBTC_;+Pq(t46o=vzI{VIa6`GU{1C2Cf$bXs{!vG?#pTQ(cB4I+{X*V@A5SUe-=}G zlO?C*-Wya`kUsXTQ9EpU@paZNfvpu`LH#Anq6FYJy1w%w?Fdbmah=k=#yF3J)hiS4)Il1WBxQy6LFHZhOb^6v+vvs#j z+9Cp(%<{22^+a9(6Ayo?ax}|IddBTsTk4cxrNz6L9YxNxn*Tmrfrztk1@E+HZ+Nb_ z|H3_6_hgvIxpF#dYx=R9vV#Y-G?|hpgKnEY zzD;-X|Juj%@%u)*HwVwXH+H4Lq>ma|ttjx`^as50>h~CemiEaDN%_+Ii9W3|btO?e z&W5(Kzs&w{vD0?gabAX84w3!J?jsYi(lYU(>UZ)OO=7mzfN7$eu{VOsdsyJ>Vil_R zHKmjf)onmjj4Nv@iKx>9%ICB!2Sh?GU3bIV|$cgfoSca3bj7qH)WgMU6eEhO7i6L$u zJ`yEvJ6dq4Io9;3oG63Jq@3oLCJwZV8-)^?Qqmq1qGMCAY`bH%VG9@CIBNgMs`*po zy%`-MVZ@!%-_EO+x0;*{{}lzrjonHXoFi5KHY`(Te#U2d{MrKR#Y>#4WsM;Xmy~VX zc4jX8mx6A$T+uQeY(TiGmtP@Z-|+|Gd@>>`bTarxlos{?Q^CGUg)w!hmD+?c_J zrMMcTaRcgI8^A^g41r@o!q;g~aeZi@EmTwpC>$!63V@yg9uWEwRL#zez`qTN7GvHx zOCVhTZ%zT?3`mpFss^-waBT@a)Rw`#LyN}1#3L9%{{vbSafgC`c9&Y%C-zr@abwNx>du4!JrI_rmS;(0Lmg>E&>_EhmB+^1h(0gzFP(58V-s zC26Qu{Rnd(s4H~|^YH8Wi>D)EQVKg;E${6dRpzTR%Ve%jP?@r-OTwA{r;`iDm z$5-pYJ+`!t7emslfog`Xq(U*(KRU|mU-x;n{=89Y^1$3jiN35=x|r)wFB-SC%(Gs> zXKIsJ#VC&!tsh)|1a;T}86l1FxgbS}#ez+xyBqMw@It2?Q1pYHY-iHYElv-q#6!n7ibwC) zH4ctXK&|$q0nHBX!1t83c#FlWWE&3oLduh&IMbSrJy#h-tC4zD!F%Rl^FcsY)>ASnT}>BV;KM#S4zYZs@S+h?+d z_5L+lo#}~m;AU-;|D4%4KMXnRRBX}pYbK=Zw|v2n$~!Qy4s`qhhD?5^S&GiR zWr<}!-%)r&LU#>ZW+h(6HJGQHRjLGzm8Ef8`xk+<-$Sp&dup3c1uV(0RQ9IwXs0c5 zaxc~tj9#n$4amr|VR7V$OV*y9gcoz4JZn>0(*Ve9umw9^8O2cKg6lA6sy}u-6kXikiK@rPT z-b=HI-=!{jv#>4;Do5{)Bat03xK&X#YMJr!-5G;XANGRrea<*GTRVn@#jqFDJTN(* z`rMpXbc_q6S?lXT#|t?RB;X|_(5wL9WSc;1arY!(cWbo}s%8+pt#Yf11*Zf?3GcJE zow4^=z9^8a2%Kf0fXv?-6Id-KMjj4}wSvAr5zTjkfc>5(g3jf`UrzDeVDDor0M|`09C*NGR30kIDe;Ud7@&|hU}ijlf)x=LqKeC_P+wJJGe(lm z_&jo&vgd1`pf+3mho($eG=Iq-mvP$OL-ma){}b zTjjwM{zvbicT3>(rUVrw00YP?lm?5Z@L4v2J0Sf372l(3RsmvS;L0ST5%LAmQsC`_ z^vhb*2?cgq z`~aXO3j_`n@Jn2t0OWn>KW5|sS8y8r$Mnx10%EHeDhc}s1P`kBc0eZi*!xf*i3nl` zlo%lCV8Ee%EWtPpzPT@^g77uKsKe%twDHBg&xNT@vRS^R^yBe(+QwwUCx=! zjTPPuUu5TmW=nPnUIaSwMvbyO4=R?!x}#Z)3l#|#d+SAa_SGNPwh#4k{Pz!Tnd0GN zj=8W1M)QYUbnY6xJ-eLa<7rLa%2MVNTGe>RpB7u1zw&nez;cbvuXyMmxJh5D%h3Kq`uP3pwOa2*MZ)fgYFGc@PZX=I(ouI&L}o_kV5kNco}W@N1IH^ zD^1A(GAd;}8M;E5Iw|j2EN&J~$Kn zE$;$vpN?-dO&F^ezX=xox=!%(_ybL5z9+0!i(%bJDE!T>{5W}K`C%+i_9p$E^#s!} zY~-%lCcaV6I)IQjSvdR%Q~5xM^iffK{>lo9u3=^ENNeMDctq9C%4^)+Cmuz|p5K~q z?F$~Y^*6mIJ{1a3^+`}zJiC)Ce-f2uuKvsZt&V@**OgY-h9%>L=+~3rK)StKJt_7p zAZyyL^!lkdUNcYJP+OB|JSe#EHK=gGie4I`_U^1~Gmo<3=;-=MTc2{1TC(9BeS0sm zv~k_i>`9dU8WP82-G8^#KX!CjN~?OD{mkI}^B)IN&&0?$;dl%NVUjn3q7dFfveVPt zct2TOyY95i9IX0=NBQr`mSnj?Uo0BbiLzLPPR@SmUyYRcvsv!!Nfc*XZD^CjS>=Qy z?|f&up)B;K>N9@QT{QATd*;uNnESF}7nV8vHD35=$Zj3J|JR3il=mOPjl@s5)6>+jk zD)x;FGg_iWT2kfI_eW5aYP^vQ4H0}%WuaVA-tfwsi=N6?Bo?2oPpeJ6GPtDcIB}fg zfSWk1@_vx`vVJUsz#t?)IIvs_0t@NlREGen4ut=Rr~=s%jPfJ6$9rT$ME@JvFtEu6 z1cCwH3Bma%mP8{UULb*QIPzec2ipDmMl%~sK|tY)UuNTj;SU&ez}-+^qG$I1gQ{0R9Cp6fA$O`e^JD{Pnq@4Nv~|`I=0F-srC($bU>&zBl1#b^=|=NA|~tc}m0+ z77v+3D#cnR2X{G@-8)A|Ly$Cg78b_W3eAKaRlC|Qy~Vo2OcA=QjRfot{nJN=F;s?Z z(+L%V&K6qiunZqcyxmP8GSjZJo~fe2Og!ZrA@Dh`NM+gIil~SzPsP9*RV{k~joPA# zQ7JAz?i^vnBqH`J?Usx-69zh}~(z#gsIo&iAS60-G z(g_YGe#Am^$ADR18@2Y~;$`tRt)csH05fRg6wD?>8(Of|fan7A7pfTItbPv|CvAhM z$HBM%em=G>#8V^yMI#L2mT{ao05V~VKD=sxz9A6;xM@C#fy z(5WTHH4wB92Mxo(fSrAB3{4yo%Smg$)S6g-G~qh|dwwf%%j@mlaI3LWYMr2^Si6); zhE;D|NwCutGe|9c(A%~-9Fpedwldgx+ZC8Qw{u-ExHdod_q?9}F-`rm?>UV3@L%^) zz~Du6wO);;N^`TjYiY@&Zet?64t5BBdNJB##P`qrT+%c5^yJrqBxpiLqNeE_D4)?a zcd$5Gf7gX>bk{w_i90;$a;1QHJvD%B%ZjY=R7icvVZGJE)>Cr#Ca(+oA7qsMm`EHG zvS4EF{4*AhOX~GXBfq4d7S(`fcMD77ROOtUCYCNi1Q!=v5$H&KjI+jz?NMtogk4FIjacF7oZu9 z6ql+HI%IMPa7n{mXVx`azifQo4EwVXNXyuM_oR00=uF|`8U;h@02KO~i34+O`KgnP z1m{u-mP6~dzWSJKVu*en6|!z@HN3F-O}{Yn1}%KcWM;2dEpt{ZDc|C>xS+L8C#-LN zJAK@;E{)UGxo$&?JS|JpN@>cUs_))mqn`f@6)(6jsb=rhH z&`sF6o|bfBp5t_~>z#f*UO39b!ou{vdS33p;?e^O6O@!f>H}W+)rt!uG&U8hC z>4a)bxrCNQm!6&s<(PF(-al}+<;a)a)l*R=73YA%v%3*fkKb-@hfaP^&iiBIFm~^y>h<$$FdlzJ7|5(7^>g8d2jY5^nF)jq&~7#00abm_1>|Gc z{+DQS4ei{(gw;vOLV$F)Nfi!`GT2y0x}+8<8Cen z!sTyh5aLm&3__LaRj@}L>^jg{0iHMbT-9}cEXb_bR!lM65tGZ%un{B%!5bMPItPuO zlsS~LWYQ!#IK-b@>kr)|*_5vv)@R$hqk7A@*NrmBOy7PyAXKZLvS)W-j9k4p+A*@6 z?NuNuV0wk0bGF&|xir#GIcz8YGtJ+Ya`$XGl8~=+3+;A|$@8k2M#pR7&)@$0l5W*X zR#B!B>=$hxxvC*~6neBasiOtLvwJdF+4S)<#qfmw`VZPUCyyp3L_Di9qIgZ-G$+aV zA?8xPK$cv*9~5;?Cw!r8OI!6xd2?!7LWwGud&_>1KTX4G<>UEsw6!O?=-%rEv->~( z>}tfvG!C%dpq-y9a2!x9T;`P&Aq>6cF4Hm?a-6LE?pX#AH@g^2l!0+ z5udORPU2VY|Cyk*zP&2nS|F$Jz^+2kO;z-HQ?&bf+c+Yp%Mnwf!A4tKtYY+$;w8_<=G7h*{n;!N92n7Mc(cYBfy>&OLBFs$lv*di5HhbUTA+hQVx} z2Q5ZKa{$0g3V<*laB>2Dp!I(w?SHHTF2oZE+!w8ZsfS4d^rjSmF9D!FU>w5Q)_(}B zOW>NC2$YFfcoRslOMwFH9SN(z2=UNkubeNsBih1_kBhh%{vdpU4$1zKyp~zv5Ad$= zYakjtwse{f;TUalbgq2nSJVEeMn;;%++K?hB$FPtE6VnU#p$neFGZf zWW*^h>-)Gr@oOaS_G!H5ERN~J#QzNL&+EHVo$~IPxVpelo$atS= z$KPuD0t@>}N~y_wE0q;O{<}MB+QULd@k{cw-rA(G2cNRu18l8UF@uGHdDd)fGjrq< zw{DQhy5zVM{F}YcG@FiHypVGzE0?7mQ(j{n>gKzZ6A{NtPnIYb;CAFn4=~O~RRp{q zKgzRsvb{fQB==asHk?24f%`{Tql)uFN%yNBx)42~6YH|{$o_}{DWPF!Z_>o$`5*6| zOP=;SNpuMu;u9OW^^-W>-*za0727iKe~;Jj#(Jy&jOc_PVd`HUQP4;N?g4xH3EC5L zl1p_gDcSEDu=7Tpqx}OWaZmPg%XxFAL);B~Ddp+dc1Q!`|9(B-lI}2dUA8m1tJTwv z{5A8mA$?ASKBqSIA&)(Tg%B21?FmcR87nYSAHRct*$=NeCJDF0an)Bmsar;NVw$Ah z$Fh3<>#>mM*;#Q^?vLAW=Y)L=&&wFWTB$M9h==c`xPBt?pI3NdwXFm<2o8(lzU%{8 z7g=Exo~^C)Pix87n?tSFA3TkEy2$uC<`|erCj39)NVe6%EiI%Ka?0-+V~{e#GFxo13@Queji* zL1jY^x~ESOYemfl)cr305B&Nf9Yb#A(;}BtJhbQB2fo7m%Ca%!h9~fDCsunspV{@2 zKh00>6(_LO{t>VjRka}TN$9>qgGMYxT<<>jIB!jU?p^6kDpMn~KQ*`4o)!pmoTP6U z_=(qf--fsk$BnV|luF1lkI37jZzFk!*rpa9OFK-bV4WA3u=%*y$LYbENZMYMA|kb0 zezKxw_RC62k^q-vw~G*}o!xJ;fWqLBea*~*js9Yvj5|&psY`55w$X9&Fp>%3qk|la zsP>vj^%=VrHnlcQzL$XvPu4(U-Z`lloIuFD*udOdM{0&`V}5@W%Yt-Z7<){4HG zH0HmyPclQNN;kQHwM8l@1h=BOlz8m*S#Ny`6Kwn+T`?-nP)0k+ z%uJ7&_EojXQHy4gwtx9}QO{fQ5l_fjg0dUz;2@YBn}(`e97yMUCZNI|CD3KSkm^IR zdd^Xu5~TlwP%=wormNnEh=U=9$V98>^r7Gy2BN0Wv8}_-60G1z8}auCNgolhlu{CS zh52wFC@!QBy?kRsc9}5Ifhbo0(y-Ce4j`!WM<05DK*)#nX)?dzgI~`6$|}lpm-8TEGpyu&7B!=0Gf(`wZaICl zm%1+UF`Y}kXGQ*P`X}vBk{)DhgMVN3yBgx1sHwNlKC4?R$w+;hU@Ztef66QuGOX(V z;;X`VmulEkOx9IQxGPNB!PwIb~&6wq{L} zhF|5EO5?IkS&GvZdNd6UT=~^}Q{k6%bQ2-H2y@L>$-OzmUKMonyy;1<(sECHUSi;Za}E>)+t%`-$1(t=(N| zhAKhL8ta~zU#BZj7%I;VEvk3<`g$g%vBw(9^aabnr*ldz9PdOEgHNuX2DVkujf(sa z67$1Iy_eill|MWYuORSCGz(w;+8M8l{OgxN7w4qHJZrv0Q|uqyKVflN<+Q=*(yi*1 zC)XPkW>A`Whq|}y6-tFR<@YisG=|A7_*|l0(g`RU=`c0h#SG=kK1Wh1kJjSPwS2t# z+kMk1iHI@JH>_GJwh|vLX?hy#C0iW!TK79fI4RR7d;0~G` z&xQd`d{2TASbAXy^Z}|0_fx%x1p>-mN&r3Q$UQ9VARnVS0v zB@*`gbkV4jp>eRG{v^jcYLtny9_}tQ6Bh;wfzq zT9W@yp|KO#4rtXyuest)gZw0I&f6?He6<2nsYS<=k;%kWUD%lhe@H7-84WK zwpP5Now6aV_tclWKP83p)16YY9GT#thqQc+t3ZM=*@*e%+X7v`l+~aI$WuHh z`qWRJ?&#UJR!4a&Bfg(V`@;;kMnX&0mz7nb`VM zF7B^KnQc&=C1(FI?i!6xj+FUOYgdWGS{LV{@>>R37E@3DqA_Nf248*$b@zQuUJQrZ zM|XXGe<~?iGFnnNFHT$1{!AMZ10vlYxJJaE_}#AjVI*DA|E>yjGK_Dz(T+-bNCWT} zH38F&6EJv!o!{RU5Jiw1AV*w|Q-_TsvcPEhe{e=?;5q z=}tvDmXeT=Zt0Q|VF>|g>2B%H?{oP*GyKKQE)4VG-glhyI=+w<_go}6rTCLF67zj9 z4%q1Qfte@}Ekf4Cc92H_E7zU!NeoHPDi20vAjTD}Vh9ipeSuuv7nR9$5@>ut+UyG^ z&_Klf1^%L^{WT>Zi!oJS^EiNuE_J%l<#;ns>aFBu~F}o zZ%(#nJ91#?`!=%WhTd1$b5fydru=Yc{c8#2-l`f=z3+dQmJK*I_iqwuEni-0O;QPa z4a+_Dz1?Z*>YK2%YKpe5pCmEc#V7Y_AvzLu6xSU=zoH0(o6c5th{Rj7P4t;?Utt}T z|1wr2l*4L1uWF#5%8J7hw({$%GgPyDAHGXBscyYw)k7#ABTOhJR8c#^JV8L2@Q8i_ z36spma`tiNBK)yTE8Q|h;QtrSVE<(<+0!nacZ#$sscLTCyGeFHqL_BzwZ2YED^Av<*IgUqa@uMeW9Qgto*3tCoo8>eQ9uy1UCtBr z+BY`%Fz6C0@-jun)rxW3OBQc(P(?_}=~+1lHT%v!(h885Gl zfN}lLP3eS4KPeC&;z14Xmu97i0;I+{nV6?r#=wFrxSJy0877C~_e@ppxu7B0#t*eH$GoeqM_-Gc%ow zz7+hwCk|Y3pk{mWQ~=ZwWPduCl^sI~Ec^u53eYA901Qc=C>IRN4M8ba3>eT5yLS?W zpr{iI0{ti$SO7=EQO5uFqlVzlz5Sm;1aLun0WJCu@IHXo!Mq>v@wC9IGBAY*m-ERSXMST?=ZPu6Bp^zSX;h6_=_0RsET(leViJA%@Au?$GNY;B83)QTll8vK^{W{%VL7*)n*2?*AIMqdHOlo2|^k3P)`VA+OQLLo2w=(Lq>_GgQ1&w729FGla zK3+6?D!-T2>+0%ID}zIi?922ILKgS1t!FjgU4Qafv*OO@dALV5QH@ijWbPk*>kAU} zlHB;x<&XDkBS$TF{YYc3UMH6JjHGNJkvtV6mEsjrwWCL&ZK&pAOaj{*(%+K((&oXM z5U>Wl@2r&eEG3eix(-}}_gtPV$V7W9!>kt@4?LM%PyT~6zw@Lm}s2y!kw~=Ej7}NgGc&aXYxLp%@64eeX(j$ z{~ztETu4umfJKgdqu%&~{O8p7JGy=~=&Y$nXHJ*~vOK%}d>MhhC~-^OP6ywbBbt86 zou->JB%j3oi0ev(8&4gkBuSGiA$YiButie(V6GsA#ccnHU(i)3p0(%0!u~5|VOLPY z;Zv59YH9JCpLy}@Pk$GV2WrE*M)5-Dr$?Eiw21#85*Isjy@J%EV%9g4Kb0afA5_L&orS!b9u)&j|+K{_&alBxx zQCuWzrz4m?VrpxJS?l`ngu2R``r=5LWO?g0Y zC!*E5E&yr21NUPOOL~8-6l=?wHs(gopq~p>N;fGq<*Tc4zWh**-~D3H=}zxQ%gDzxw96z71%VqjClctH@I&6-Y8={hO5q2!ciKl z2`g&tTBU2zz1RI$EUrJP$NmR|!DEL_98|L0{sKF z8pW-;x;q%Ml_0eYL%xszpaX)>c6L4e8z4}iUi$b6lGDg68PHq`VMTxbg4*yoK1CEv zQnSkqWU~Wl9EfCMMs@4{(4@py5bR8&fPZd&uw&oQ_O`f;+}=wMox2yMt^UixvrVIU z-d1#jHz#@#RZNpr92FVz42|mZ`X4H@UZ{D{fIj%_!8DMXBl~kf?*PB1(Y=wz^cq=s zI>$yi`I`=d?s#Z7&11?CvCz4DYrNHr!m(3N59{6r+{cl>yTz?l6w_kCBKu;30;@c6 zRCGZ2ZB}c0Ncg(sJ zR8lcq{30v0z(5)A7?!wHQ-5b&syohT-O*gv2qVV8d{mbv-FVqA(s?rMR><7HIG~_G z2QAo}$*}Y?BOu~p2hQN<=l>pm=_&R~^u;j1SWYZhJVZ){^XC>ut)8cvb1Jb|(>QTF zN{4_^NQvvfiZ&^Jkd@*f z4hiX8`E%1vxGxnvzxQu^fEun2knR-83nq5ZOp3~_ezpE9f2zWcn@;mVVoNUJdCgIG zIXeu_YUSN$KTsm-=HgbMX2qZ7Y?aE$g?z0QHlWo;O0py4-2T?sUY5IutzO3|f6`h- zmP4$`u99_RS`XuAHAUVwT6X@Cz7n?~ul};*Ezf1O{u#L5|b`50x6^D)vI2#0rU9dli^x)PbrI z*aXEudH6Is@eQm;h!cAvIEkMF`Q-mp=%79Q-jJb-SoC=@~`e97mUmOR*+% zVfsw`;|u$ETAB6Oj(%oQs8a=PEViwY2IPls8atu$$rQn5kQBgmnvtjG&$f2MPuxFD z`0Ev2_ege3IEO|q(GeuptZX;>y>MXI6Ee1%ZF=k^D#U*^W!c;u`qQYHKHEXQFR3J4 zW%k+gZXxkKPyD^$86uxPqtmz_8V+*q$A`s5bMvF+1za|~+p1@ljx`nu9q+G5Nk->d zC@SX!G_FW{%~4Xa1az6%s~yKaO&X=k{4)Pu(R1UL*w8|79b27gc~TV_%hYolJN&1u zIoy5jH`oSn_Y+EWGqv7kf2&DqG@xbbi^D7m-iO^TOpOQ)sjXoT5%h^Xv$cIO$ z@q{b9A*ALM+C$|T^)+}aT>HE%PyfaTjb+m9Ph4@9j@3ck96>x?<+5$J8Beb70Vyxs2Mv~sj(Pi#>AH9%fA;=(yBmsP&F9 zRfuiY>;XsosM@}E^*f2$^bTQ}FuRztm0bGV{fSO7`*kdUa8- zZytOXE46{W*^03D^UKMP_@L_L$@J0CN3`tclU4pQjK$?9^O3u{|A z9{9M`$V$;2nPwTX;f@TrSO}^jjlV0nVI3Fjf3%|^! zojAN8k7eD`xuG0`zI?raD0CCjC#x!_>cI7xxsYir5b7NDIr0Y^Lx!4%4W2?V=KvCK zNV;3!Gs=+l9Q$P|>-5ni;$*E9GV)ML10PaWx10u#Q_aX&jgm(y_D%%1EhXrNPt-Sh z^GzZ;Sb#o6uv&t)Sk77?zxY3hj)8)!Q?bHJDs$~G!GyAbnu7trnxhPDl9tZ35h^Rob(;#5P2?wwoX6S!y8NEzSa z^QGGWJcbN%%QG@!li7cFe$`dW_U0c?>{17qEq9WdP3(iP4EFShOUb3tVe;_)9;DLk zoTfq-29}BFSIuuGWbMlJ9ehpmiAqc7L~~IRNa$C}t7Ii_XE<%i*S=z(2S_d$@~DDF z&W}_A+o)O_KFSHg^#(BEq$Mr#@vf79a& zdJ*{^X279wAQ~Z;13?Mt9}3dQ7LHdu(-pv)T{?B0dbUIzuJfb4VTwLWiX?GdQ>pB( zS{+MA)#>xIUXz%$X~wp(3Dx>(%L$nJaV_c~T^xcl`g32K22b+=zSDu7ts#>3LMvAZ z0*6ORrC2KO#IQIfHT~hgj~7@5+X-wpz;O4B=wub`0V9WF@aT5f#7CY}d?v z2u#`D{8TQyo)kI2r&QE=mT_O2VE*>w0aD5KTt4RYd4JmQtfQ0NMYNv+m-EZ0LsDH- zQiMm>7Z1MGgj480CNvV|2;(^AcdtM4eyQFz<6K%hHDij1V8D|YeF;}fUSBHxs$yy9 z{#ucXtYdH|LSHP)SGFvUlK~yV&3V4qH!fH0w&Orz#%f)sSRa5YVSg*#P2dhhWQ7nv zkkkHPPlDf|0HC}WySp0iz&J)9NfRka5-r|7m;fXtfikmmJXjpa%Yfnt+{jPDC#0jx zT;hZO?_i(eWC0BT1p>Akk2l~3=LInpLSnYeKp6n8VGQ6l;{mt(LkYNsu@_5_@=5^o z(acvL|H;oa0rba@tdgF&IPH?a$K|;d1N6n9EP7wtk|+cM#@nl?E3ukkQKUJA1}=mGzfd_t(oKxJ95{YE$+#n?c1 zvhu*O8g{3g;<%cz3Pt+v!ZDglaqRaXG9!9ww27||*B&A&H>cY*3@k0|_7#=$^?2=B!!Jp!!{)6yyS12JWrt0ogX8+PC>cp8a z`(onAbuP$$;Ov2OeA#|2Y4EN+`9AfaJ36G_B=_M|I3v#F0fqD`(j&k~letNt!|z$m zJ^Qx#A(Ae=&%g-2Fa1zN^RJn2F#)I&5(NapLsO_x>u^hrWXchtMMPX9sDYdV}h zg}{~XmsL~Z^j7Mz;N6W^myNF}HKoZ+KR1UO$Zi|Z$53YlO%npkMzmLz$@1{l)kS`( zM|IwOuPIUU$t8R2JIoijH!?Yfl zp&I6#`>_JO=c&N(CYs=4NI%Wt<-mC*?J`kopoG~%B*TFCpF724-4xqMasxRZnuNjM zBRX054O(KTXw|5R-GpVG9bx@#pVe1nhj=ZQn#_iWF_4QkB)v>a4018Y+ z@qBmx7kNAD;-bo>+vzK3&Re-~Q3((6(k&lX`4hpHQZ$WHG&Y^pb9o$7j@4xIf*=E% z=@*9+W6sJ0tM`IkS)ILO7P<{Jj3=&*cuV|fl(s!bE%J?oz~^^g++;w!6Da z22qT)N^xrBU!0tS!!NwPylr`hJ|M`H<#}Mt)5F|E;3>^(MPL!g*$H+8Q&ribA5-7- zQ*74E^Udz&eyi9T;MA;}`B)$6fu;H^woSfm=6BD*jobd6)}&?OHz+)bj|rHI~d4teoVei9dH_@hW>ZyR|}cqw$zcCEYk0D5Qb$ ze_ITU;a+H&M5_%kuCmw5_;Dp&?z9~_sNUP31%t-Ue2$fnujP-HA1`VWzJih>?v<~4 zFfYB~3)GLF#it-@(_nH5#^%BxYVIl*7$Dvt@gjOX*3+YjxAZ>44vTM)f8jw5vb~*c zk=Kh!z*&8<{WQW{24I9<2-O4Vv%o--Sw0J2k`kP`U_S`@F(fd*v;eNQYF?VE>+by8 ziLH(l=UH`3f9_P~*_8yLUaQ0t-Qk*p@t5ag1#=VxDr&dX^zvNxUu)Fe&DzkU1AhK6h7Zkeb zBVn^ixh#S2p0uY9WI&n48OMyICM_ZltBh16%c)72dEhmKsg~cai_8eJQfj#`Pquza z@nSfGp!T<#7?`IBM{_kEz4>n!Q@Id1&eJ;a-p?aY>17=>A9HhyAcYMSG3MUXo~ddS z2%T_ldCpWBnC=hhugREH_IWneTXHy zBw=bQh8nIb#qzK;4USFpV4v&~b&{oC@yCQ5kND`APbt7vxdA>L^CWRTTw^yO&G!*j zOOH3ZFpo&WvhWN^f<^FhWvx6O!#2`VDX#+di#>Jy15r)?bCtgH+m-DJEZvWG<2*_A zGP7LQGZ7s8%Ou-&WTO3lSpgDln{Rq!oIA#8f_{!|UL@1bYnP{o;*(-`1N!rzFE+)# z5zWH~xb&+Vw=>m>7xBEp*)j^W@$HZ-i$X|yzz%W=jUfc&1hhP{^q)W$RLM`a#(Q-% z^KoFH`S}rjR}yTbXKw#Imw0OapX`aHPfkR!9i-e#;O{Jy;wM1Rvc!0J!i_3H0&^PV z5oW+gqZLYGdV<=8VlqU+KA4aO>f-@JQa!{LslyhjS`k6K9`Ui$5aIQ%Bw8V) zxb%Pi^#({fFs{o$a5}*v3P`KLF9WPo=Lm4OsNj^?Bj>fc8rY%MJxQNIaK9-u>AXzU zJ(D+FTvI;R{!z??`w*jr*3Nx8{ebHoMf;DxS1aW)wU?sthHGghr*YT59^19CUPY1} zbZ*6J`$!!6g{v~)ww zujoSGgzgw|OtkD9h*pXOJUsjd3Ed;kOZ)VL!Okjo$$>0Jx2xAXB4P2nr#n`Q{Oly| zh%dk3T1~2|iMwr{npKFXbYVxPz5Bj}6MgB%5bqA^l!2EsYcbXPuf=GjvhP@bI5`{z z4RYKhcj9@&06sj*XnU4!WWt|&dnnqw`?+ut_NI6~VKHS3fvb)*7UH2?3wDxx%m^bF zd5ZfxZB(?QVch_+2(gUIuYQ=RWAkdrwMIUym0~{$mKOT1Nzp{326;@xV+~KEsMnA& z?A&X*i{V85E! z#B^ksW3mv}AX|szbm-lSayT-c1XR04VczPzK57!LzNv(68Lzwrhg5JrY$on{oA7NT zd#g8_h6%ah??MJ*+@=h=9^sIX7=)NZ2~F1BV?Tx}#n@D~WP~5-uTC0gwFHfm{^Xc8 zObvFnjI1Aa(pIj=<19F!1+*xWmY$E zReMuDLoUp!-HiCvl-S=hqi)a4Sb696w~{T|a^Znr_XjSx9+?V5e1rq(O;s2x3BRPM zG_-=6g6_ANlz2Oe92RQtRz2jzFyTj(Fq7&}k^yf@0Z8 z9if8I%Ikv*%Kao>EtRh%nXOzok*!)Lf9sdU@p;@4FRan7>#sy9}`e+-FzFrz5T;(A9XYV;KR#9v4YtNFC{{T%yP5kq%PVHt) z5*-DZmrN#{f0QEisuK@0mgLjgI|LCwpggV8R_(CfOR_0if(LO877 zr3rF@+9oD$u$smkSiZ15^vpUQ{XdAAg?(LX=;eZ%9qj;a*Gf$3xnOl}Zw6`pAkG67 z(Nq3|?LRRYM{A@UfCrHSmXs#9D1i5$n0V^nM6@B>AO!0WIxG)%u^>GC8n`RBNp}Iu z4d{e{Z`2&{J#mT;G*R|r0v`4tA8&K!3Q&Nn9Gt<$z+|}#AR<@80C`joPJO&!jeSYd zr*_dA)D*ym|HQBZFQKK=>nCPQHxR=>6c%l&kh-X9RY&gl4vgp5w3AQ1ae<~1W)U~i zPoG;|AUpW>Cn-#Y^j{OVUEOZl7+=q_<4s~(v&NrWOTG9#F$v`6oy!ltaVoRKYj=KM zxGFduDXjz)XtG`NKQQIO7uNE63phmR>Nz}vuy<;@&0XjtMRP~#BiqD(Jq+7n#5dg2q2|~? z-1-y#yf@)~Ue$Lc(9FJre<@0(yiWEwEkd>Q{Y=gZOvN=<#x=1Sn*=*hm*(&Sv7Lgi zYjxPaWcXg8XelU4jdGqpi=I)Q_^jYNzuzf0HVV|nOvFZ(>GT_?NVL;)uZBtX_0*RQ zc?kl{AGiZv$yw~M5l#wx@FG?cC+xw~GGT^TGP(-ITH_wuO$v zWiJn4UXA)BLeECNw~A{cid)hBlTiFjKZO@Mc;g}RrJ@QG`X%zTa5nUpr_co9EGBjptTzbo zM2+SKT=*urENn!X*tQa+llI}#+R1Z<3^G3AWw##H`Jz%#z>GCa09)NZAUs(G0uqKK z(Lm5@6e?v2OF+ zq*z(JwsRsM?Q}TFM8mOheha5kty6drj!NVe`0;{-_DrD}-DW%!1+3q&;95m5R3<7z z;*G?S=(b$*VtcNf@&i$BhrD-5@4w7= z8aYsGcB9?&$ti0)CD{?`L3v9U2Xru6+*0QRnJD`pch5glCR&Bb&Nw@!J!0Lb;_?Ps zdb1V~9by7Wn@m~PqfkQKMNre5mQoVrKlT8WIY*pygHZpODM(al!3)>1Gs$GAl}7x#PVvxOYIpwo@0nCf>XKaQN;$CAgvk4mkhAxE%BB~Cq?NeDNvBl`+O|1Z@s^xA4!SIy zk*GDYCX0KIZt-U5?HV(_X3ZIAL?lQ%5%}0`1$+~=sS0TK)3Y>8_MwB>^%)zS=&gZ4 z&&Ek-EEiWEL&Zx*HW?)99<;NdQ_+W4Y~$zGj}%UqqY|Pw?e480(gGy4zWMnkhxYr3 zgXdV3T)Rq`#MX_R)V}UJ`Dh#5JR`CWqj~pGn}bf z!nE&)gicHL63$P(`}Y=;qAGrr1>}-RgXnScsv=(fynWZSb;bn(6ZHyJRz|k8)-S`i z%#xXzO5vTi+DZa2A`$Dz{A)aNu{Ug`4A+_Rg|e>{1$^?6=r(uHEaOCUxd(>aT`26t zhv-{Vlky~|XRb7nJ?Nf_;2sMR9xU`K*xeEw_hX|taRe~j^ z2K?=PjaNihjl*8n?=!c&|D>^2?I*>hYwSL-^tBP$P_a((eL2in)`%ZK3Hydvfr^bf zP3d=46~S=mW|>r5ytz>LvK|#ufoXW$22WV<$EaQFX!u} z;)xo#@nyyOo+)}M*BzfXk*(lRzDMI1?HjL8u4+15) z_)V7^Akc*vAop{>1W*P*-2rGXk*9+Zgt-yrm*Ot6-%DWAl&Gq7-LLVWwmNJ|2=;vYeGTza@ z_GlX#UT_zb(ZfjTUjH!Yzfl#s7}i^x`?jEI6aTr_6yjHV$#@pRB2Tb@1>cw70==N?=5 zI!KLX!)3m4|Jmblz};8yz~rg;a#KJvl_@WHGD+iE6Mu)*nmmLY{1h4r7PJn(yUF8A#+_EXY>rr~Q23iye+%IQ z>|U(I+kLN_FPUZvttVkcu>@%$v9bRe$?j`S`ZJyL?5uUwKXfI6>85=)`lViqyX4%G ziipYLH{wqtWQ;qDbq8{%tyat{b^g53)G74u66qZaz7{tRYc*JojbCmJhqjjIAEAxt zu!U2e?CUj+6Bry^eB%GM*ZZ<|G6{p>XX*Th*OS%n1Df}ZYv*StNNrnE^!3|n)K3vu8BID4NDy|5YdE5kY;SJ| z;Zi=iI5U;<5E1QHKsiU!pNj*1gH(u!X;ZC;M{QaUs#mNh!rxz=c^t}V&w~7EMf_?u71%hLUfbt~h1Gwc$AVRQ3 z1`Ikh8f`I@S`6c9^YA^BmsNBPKeA^x8&c*sx!F*dd;WvK1e)1J^q5NeQ*)FL&;MrL zw8!vY_YxME5flDg{4O_9xi%z!H`~-5e;Q8d>vd$RoW>z=bs?rynHrD3ppd^H6;L+U zzIi_VB}5ZNAEqj9Kn?rlA$kH5GTIsq+DT(Olk2KX;;0$INt)qj*y%?{Mnx6d^ymA9 z8P7NvLI`K0d53SlW(vOd7JX+ysBlLnIpvStx0&COZk{oBjNDvvmO1S8oO|)rN1Svu z>39uetspV6;`O83{3@1{hT=n^dzt3AWo`0ppHv4A;(h|^?dQXB|11{7e^z?{P6RjJ zj9DVgLAQdFNt=VY>E>f_4EF}sgKw>qtHf|?tCPkkLoGU|>Ff}z?2R<89tGqEIlkDi zp5L0UsYNFRxjN!1PE6Kk|KNdnrTm*?&8`3jPY;4+6ob138>i=b$OXwZRdbbso#Pz# zxdZ0dZmYxVME@LC0|9yda=hF)f)B0;cT>D+7kvLl{iR*`NH;q|kP%fTo~E>ZzF!MkI{bDX_?0{|`c#eGfBq7qsr|sE_({zk14~amte*kCrX8 zINHbxQ`2@J-dK3S`Dt}_=^g>Az2KDs5eA!+CV%$B$$78CHO)dt+T(MHYz3~;NQYCI z0M9ccDO;+QG>?zw77Wc@JH)}S#CY^~FN`=JA_x=;T70amUxl4v8`-VXY;1QPsV^QR zqz(*yt;G;%f6;>=hYLqcYH$^zD+azEyBW^N`#4{fK{?iF*w!2a^CvSDX}5aIQ-om+ z1)rT{V|Of~ZOs>%v>n!ee)r$w`88FcV(CbYZpJTfnZcqOH^hAc|kfVTSh$;-yP zWPSiDRxqf97--e!mUvldRz5^rr1c*}k6eaL=TBdH#jq2Ba!i%}OVXdXEvmlQA~t-r zzfWan)jodPrBl7<;_g|U#Vp$r_;R2pIViR9N{GS|caJTar=|4~yMpzb`0;4?M)-0lB672)7=0=4+-^&Usks|y2+CC@qvrTTn=Lk0`l0U-|RE73@hBccS^*>FE zT38eqFB#P1urzrXm&|5wIFBN2ks@WY$*(8zq{`s)PK!!IE0xIi@c!Y#H~UJ0-v;|4 zOfU(7n|XE3oIOstrLrPT9IeJG*>Knef1p(X(|*tOb=*H!;RiOxCfSbXm@xTTiWkHo z4Q&A^PK37GPT!Pdr?P3`K61=mDWVC!=err7<7RC)rbqN{%UaU&-zy*}m8{$*F6T@~ z?nngF67;P zUJDvh;&M$@z*1a>PA%=+QFmI6l5-iyI^Iohk*;h~6{^&Iz95{kbvjnXc36dTG;^3Hb`@-KPjDhR?S@pj1sNR>Q5Mc{o z4e;7whS*$)?L6`Jc?r;Vfnhku9)b!M)nNdMIsx=xIDpmP=~4)cPEUtA_^fNt)iFP- z#x*n9olacPpTAe43uD*c=*^bD)iGk=f~FR)V^IyM5x?0a`F=yow8eDad{MEa-O3+F zG}jR`%onTni|k>LgfY$`uN~J6m(Ub-Q)2jW*eAVM6jm;VsUFTN)H-cx;Qp0Ir51;C zZRYtlR4Xi@V_U4uB8n#-&s2}pmC>UUebGDqP24m?!>4yiEKumcoKKgSTlQj0ncSFV zl>I6Y61N!OUL|!43EQ71jJ#dQ0z)upu&^1j-maXdvGFFQ zl}1z#vu@@^E!pRWa@NIp-XyalBN&@U1o zhK=Te92|E7#I;~$n@UIrK)it6#38ff5BI#6K)VPS@$&df!KPpv0$65}1TQ~Zdc}e~_=*o0ER)w_&D1B^SII za(TNC9QCtNj||sw&-ln$)?gxErQWk)a;0KnaN#ftL8^XZw~+1{v$Wig<~N*t9&BUF zCj0^WdFz7bAi&dBi%Ue{-0bQT8`Pg`xdH7WRA|R1J~XRbt(`tk&uz<~j*ODcVyJ_? z;67AGBZY*jRjW=7k2R*l7Jn+c3S?Ai)WOMH@Bf}ZrZlm=O16a-8gCwxb0iEZ-2e8u z!)|9`I#gC^J1$b7pP=qn*B7pHqRC=S=qjZv%L;zB12s;)X*CNv_henIB@MRmU%Y{R9&k1}K7e3kVLn}VUy*?uX9(~?uDCcsxDV0MGE ziS14Ivvc|u#jih_-t+;pW!;tz_IjWyh#)qD(vHk<*ujnCRGIPGnmzxe<$GvLe91ae z2dj45=07z&5uJ%Sw74b4(?_e=8K_oBg3-do?b^2=23VBmLoWQA6oyq^mVMfIs*)sd z5+RDXt%|v}+{E%74T;Y`u()UOnr2Eg(O9{&Rucaa;NeuU$uF_1Y8;%~NIa(F1<;~c zL=CUTU)%4+vLSAt9%JB%jflN+Ku)$JZ?ZyNhm&P4j5=9y8}+iSyIXJ!jB<>c+1G1l zrzJ7b=2Y%6+NFFAJ6QM?7VegXrxqAwKP~usTZHP`>(_^QyDQnpo6mzpf}Wqc$ z$DwZv4x6kd?L-XwaB-~;^B5AH*}szA`RE8^K{X(_?@IWfAcXcfmBU0;@6gLFyDeWA zH?*26#8Dx6O6at~)}XL}MuAhhoi*)r>N&)qBuD4xVrA~$$n7&qSd%dSW`4jJug&+? zW0;QmnZTj?z1cd7Uxd||O^d=uT9!gI`~F}=g5rSUmRmhpQLiF%(T-l!!-H)X4z({h zBgR%OV!kuR&=Xl~UD2_B&U_*tqo!$3aofm)S8%feP;6j|%=KEnvWrE#rwg{F&R6l@ zOYnX~pA8B-_ESI;;m&TxsZ0O%s!fc7H`o@s!w|2w0dZ z&~4Y$QjG3@oxn>_TU^&p-PgX_rkv=7TTNBbwN79S|AOVL`NUyQG{yLN+>#Y=3x2b~ z@D=fPQ>r`u+FN*8=eMzdNJ`sHL#-=%GGFXlQLr@-s{Svb@!q_(ZW6K)?V7fdOhOI6F;QQouCd|Mqql&+AA(0;DIT~G*RR* z*1LCNl}50e9cZSIM7BA{WK3wSi~LHECgz1h$re74iyDIb3ktAd0Z9?z!N#sEAUO>g zNvKyIVS;2W7nN0#svcpq9TBG;9ly9(@kJMay(cj3XF$aKv>|sHAki)Ee_R4JFs&(p zoJfLOh8hfT&N7g)VDuXGuvgkh^x2S-?=t$v@KT2$V(Wc&q8eUPcgJU(@(h7fvKPwj zJ}gV(VQL*y74Fv@+j5hZFON8k>=wiq(JIXa;VGFvHLGs9E48#UuykP0w!^m=nP>g^ zR|2ikn(S8wI63mGM5Lnw9QC>Ft=`;luPIv@Z&%?gRiocXJt)P9i!?P)9Hw9J$GjES z4}Sh^KBr0m3a{pKc}OpUu^iXb!>JIagW&aQArn6$sOC0~+B~-{8dnC3vo;d5QzkGY ztH1ozU%W5$ga5JhMT`8cU|Y#Tn!Z?bFFh7aUFl|(B0oV1WiI!;-CUg5Q@mnx?)?@| zx2bG#i=dNrWt|vH#Uw#s?kDoWG2dyt>~!gKyvupTW+DgPw*eE~!-Z##Y5wBx?7sBL z>uC+*iFx;lSZ5vJ_oW+7H3(&FEX^y>DsZkckqBOuTbOQI&2Fns7KaU{`mLRWlSVX2 zXzch-jyzY&EmUr~_S}LSOlhf3d4zwTa9XvaPqlknvh6k0Co$-AMWNgL`r3+#i#c)P zqODRup(T0QU|;vA#j_6~Ut|TfLWM1w+TWf+&E;Tp=Lc`hqMDn$ou)C;?4pD>EwKLh zu0U^R*tZtH3jVq4nWHDx%_vT*B`^2?_kNijAQ)IEUq3eJ>xfvx;%n(DMEOvPvNNJ{ z8(ZFZ+BRkeK<8Jj%rF2y>xwR4)+y#TCI%aq*wc2^L7 zjUc64h6at#!z)|KfVvEXz~(z`1Qd3Ri(Yp0QN;wV!Y7;$7r^(QsUv*{1`^=uTnYwY zDW0cTDHN(n2s6^bFaT>H{rwXHY8yj5!14gg%$PqI*#J+%efxxD`|lFWTpWf#9)d13BLW4D0Hh1swwa(K(`GT+M|W&_(xGMsHa22j-=jf zFNJ=*oqUeH1qPJ9&qJiLfy#Tl0Jn9ik}A!Pu4;hO8xM5M=j3Wlt!L36Cw$W=x*vZCc6TO+Z-Xq0g9!~uf>YR3`h4#V;vJPWNDkBw(t6#* zeia^|y7}Wqe^|8Q#&f&nV!P0Zxp-_ePyx%v0Cwx(ot)g%5FzK-`54FTsv!0^31%OM zG8qZ>J;QeH0W!{3tO-2)2VGc;0j{pxi{e>&oZ1s(9sK21^S>Ucq7CXlYmIZ7>f_A} z+b%r&85afF$%iCOoZe2eobWp&X2}!}oGO1e{_-^_e2b^%@39b^v0}S2S>1a3TG~OZ z=!**zw-m*AMS=poRKiJ(F>ap}6J7Ip1%9ck%TfNfD&99s-bTO3mdb@pXyp&AQ)Oh? zHA(cH```OKR}K87iQY-QlHPFiC=Y}v&+R=Aowg>bU$Fm966r}%rr|i_QWp~SK;m_C zFw-R9Fl4;vxc0%$w>lAyUY3azt*nuyv%EoIR~Xpw_0{ffVSB5{Dje|DBi7<)AWo)r zI%WG%{c4P-t5q-@<;!-wOOS7CJgiDlLYm`*I{K&~Esk_!9(!%xqMuw%(8bvARyPq| zZmpS9<8aS8U44I(m&QFij|}~=fnZ;3Y^_|Ua)&HTS30x9V?ot{u79CRco=W}yb!Ql8m2k84z`wP{j zNao)-+>&M~FY;65H4BmTjL|KIcxp zG5dacrxxe%w}+moA1aKws@!}de?dpueO?aum?kb4tVP#1OPy~DnO66>x7IbDk9Tm> zLK0*ZC__Y{2m1G@ZE4n>qyhyzQ$Hjgu@DPjnIE$S@RZ1)nsT(}p14m(R*lFT!J ze+X_xk7{}sM*1f;y z|C9Z58c@0flvugDPg8N_+P2<_sbcx0+YD5rc?yoRWs6Q)kzE$(dRkfk{l?!#1K|nj zW~_`8ZRHtYOebAA@Z=!Zv~Wk1V?JGGLLjC&>>s7jo%pphmSvr0!$tO2$-;l8@g%vn z)rFf@OiumvOv!`&b%rk+UmIKM@$dg2!ic@CVSPBod==Y-MVgts)IG661(O+@I-e7C z6yp>){${N}gpQ02OzQISDw8B4^<Rz41T?z8*##6h zg(mOb`di1p4t(i=m-E@G@pap_`RC0Mv`(bX{e4|;JUvT)-65_|7wJcD$Uh=(QsgAi zKKsLIgjOvz(+SZNUD}x=e@j(Yy)?wvHEx;WM6pUHKgm;V92OIjb&@TzRsS)WcUIwF zvGL;Gn}71g6~VzI*m_Y1F;f&(A}`GBlaOQfh*3E|Ay=RQ9|B{!ZOS=ED{6euyF^p| z0`@E`N=t+kDXJDY-++)ztNiXq!+9zPvedA^y{4_3rPtpF(7VL1#nh-3BV>wgRTXxk z(|R&wj?t8--%|@xnT$uw5>MXd*w3nJ@T?PWB%M@#{No*@60N4NRUeU){>%zF7-79# ziy((nxkINQ@!dW9$#Nvt_^xmp`49<|1hz$#xFVL^|LmQJe|L@P=f}Ig)Qa`MC?TT& z9*xhva|DrW?e`kbBJn70qCP@L781nztA3a^QK_Ck-e;wY5y^`=rhjj3oU8z$$sSIA zwn2B(;}wxt-79w#dYa2}Y^uUG&KLCPIn|dSFbw36q1=H^Js1FW3?X;g!H-W-?E6_y zyENvf#P$o|2znwIAfpvN!}0&4ZZWA1qn`eVD#r3Y>^38qQmvBxncMP_5?W+Y9Lb!5 zF)J6l!mjKN{i_MSN(s#~l)^y~*?CgmcatnkV>YOb16*eIH5yfU1Xo1k(heV{n=p$9 zGi{wJfi!Jb!(BmlN=s+D%4*zl>cIW0B7>|qR_hSq&uomm|0C%vgW77lE*uI)3WehC z?k>UI-Cc@nakoNCkzm1!yAx<3xRv5w+}(=1mhyb3?>Cc~rEYYSj2;>n$vXB0$8)%?)P5904BoDscC@SeDXpp^PR#W$=}Y^$iM0`fjju>#hJ9zUKDlLHg#meY<~R4{`#;vRG7P zZO6`lVYUQ75}~?>5Bb6x+LrDs{g=+O+z&NF&tsx zR5yb|z|6xXDWezraMa$X>=B}j%WTy{jwLo(QA>DaHY4Dl5y6$w#6qVFX<;(+e|r+* zWLnBVOF>uD+-A1dLFhNppypB{KfjAW+AP`o+={<|I=!ScvK~E9pR_d2x~SqVWI)Or zzC`shkkp&pNj&1no^#5vIptbslcE@PL=@d*v>z=5!NCG_5aE*IW$lH0@Ciq`yQnF- z!d3t2CAPbjC6yQ)rG>rKAnZfkoUCS?hn-Q?7N=0A>4MqKh;zk6jXd_d1v(DBKNtwZ z2g!f3z6`SH$He#icHYLqH2(b*!y4jlw4-2)O2qPQ63O@6^a{d}3>`$PK3T~|uUH;e3~8h2|+;J@zUuhNEPdx&=1XIkK;v66c`W-{VV)1HXMLa9sSQaJRJ_Ovay2y4T=f=L5;cdff+L( z&q4be0vx>sG&>?*k|?nt3Si>KNerlZfI%K0@Bz>r0HFiGSpD-50f>)AkTt-j0X)RB z|1w>GL@3~F|E$KRl4O4YKT-iMV6=l%No*+NFq)@Qv4DKW(J+HF!%w9ZC5RuOy+7OV z$8T>6RQA3#e+&q)86=_zPf|KH+8rur8t1n53jF<}!*9pAI(iqb7#TTzGv&)L zJQ<N0_esy14`6=VnUlc;@`$-iVr&RCs3Eil;1UkF$r9`wGDt63X% zYT3Jg)SuJsnp=MZl^hm{5mER0INg%9R@a&95xB&(E;d!z+!WPgpBBF{k`j)`as4b0 zK3qlk``Ugmb}CeqB0;Jh4?42X6Qp1vd`kR#pji4VQSe}nYkTB{Tx{Pxnas{n z_-GnjBW~$GNv$rB-^FULlNjiH{`AOWfHFVBA`vTr50t~%Y6xyfvGiQ67?qQIh}W1K z%4HhmVPUgff=kz-m9JzyNRwjS#WbGur*y{{B-vVWzPm7i*C1Gdhgwr{wsF1YR9ORe zLIZm<^RCx@(FGIbQ5b_z?jdp>mQ0#dUt=7{?B>rUYR*3udY56B?p6ulTH1_4|Xor6CD2i5oSdY>+)OE0~ z6L;S0vB~!u6z|MDqKGV0hDo`2`S(~+BsNt1&Xz7U>-xTsL=MVN8m>>tLx3T?8Nni_ zL(Rc=%BVi8V=}8pi=9J^CXpLGN*Rm+3Q@Da*etzdyc-pTdTimO1#Pp!OiX9j9hR(` zGq!ftTiytSPrtsW@;Wq9_RLw!8hC@PYu&{^YtuffLORd_kC$pjdqg2iPQb*J54>P` z*ijs%gQd1-f1x`I=5p<6NXgsHI)Vg$^`yIXET0SJEpJC?n=oj?IN_>5eo-(#xUH6A z5{nU$Gh(L~~9>6`QTQb z71F-0?z3*00RDGwI;3qQ5Flub5UT zAL_{xOd(b0A`*1*m}&IbP5c=s5V==o&bRT#!E60>#P%lMV;P!f3E(QKXg*Ky7`NPA zs)DG5#@Ji7>E|`^u-$RvlnjpY1u0<&BxcWmCn@H#%T8aq!(8TAj9CaNUd?TU^!GK5 zO~80FOTFL(I~8CdF%|99!&HIb=MR8R3w{P-V;VK+LzPW8aqXTbl-K-Llp-ko4AUJKUsy_TZkJ3uug zhuuG2>ZVS!6SZ>?zB79Gpt@#DEvQ{S+M1w12JPg+l(TZ}%pTp7F~c1wbEII`#`Uvi_b=#5T`KT6fdF~Q|6YWj=}RE=)t6JG3zwSP@~La z6mMslK9@p(=}2o(Qy%Nkm^jY?09Rp|2Lb^R5#bt*02Hzx1UO#Aa~(iapu@>dCF~hl*ZMzP?~43rAy=SiltRh7@G<)cKlR}1P|`vB)+0T z+*HZl2z~5}oFTomtpxLA+GE#TF*om9W3P(Q7ZOfUB^!lHLDj0(xSaar^MuEpQd{Ph zEP2t`jo7+dhnp28K5oAnqpR$FNG5ENEVu^TBf7c&{Q(N)*V3|;UNQQJr{;C(xz@Vu z#+^>lO76*;NLL;xY&|vcVv-ouCOI`!{@M@n;h-u%@H2;c9DiYFf6kM6F8<9#v&6eD z6J~mwPdPjMzPZGOuH_L6QnAcSbXHWpbiqSB0sP#y%babP-CM(1MsBC2nK4?#CN6@A zh>V@i19#fXQ>5FOXPnO(n3WFGalofH^=Obq^UJ5;SKOv6)dLp9d&~Af7 zhV^)fZ8u-N)!$8exJfMh#8x6TayIatQ{Bw7cpF#TLwDH2TgBh2zd4Y5R#XH-NmNi_RLN}t^OLubm;ysvVOqZy4d z)jV~!qdsfoR@!Ru8M0&9o=P0#eM=6+AlA`2fA4_`X3RJeu)5+eub~h9Fj{>cYS}ZS zRK2ay)y=1K+MnL$X_@6b<2;Efbx(Ki!8REp6gU^%pjKD{gxx&u70w@c=#eC`D;m{-DZ3aMxy%q+;FnUqqq0YcFJze=SwGt zX5m+>>~LR_giQjZVZ;yQAy^hLiy5$IH*&zN(4ouIuTVfMrU?g7F+k}@xn3Av_zDP+ z4gnIA0m0!v4fxGI;6vEq19CX9J_G{p1|Ww1AC6{lI$RhCQ2qy+VS3#U3|axF7{Fox z=;IO_PC!Ko5M=(@+5b^e@qkEX@qe-}O%yjcaL)gA8#VvE0M>fRYe|e>sDUK!@TmcO zdC@S|eb&FoY0Oz9PKc;R*@KKCNkZ-Okh1X#Badl!0p%X$*x<*R%2(CQOx5hDSKh%3 z+nnUXRZckLETR#zw)87r(7_~3u40K1iN*k4NXerFV>JP^gfsfa^;V?2J) zU*?(*d(G_{G!7Ql=aX*}KHc3?8qf2jX~`!fIZjX1U0geo3&*J8DK8>xf$9xm&RX=p^5l@!r{t~A<%`~ z_bHF{3rnfJx?rF{3{C7bUst-KK1yWZstSc62O1Ubqu1edgLjqMF%X`_eu(GyEcsBq z`yj)S@ga)z7aD4?yW#+*hRb~L?i!3hnOSFX!Qv8W0r_C(>o_9n4pgk0Ck+LoE0R4) z#IDG%nPzyphz0#TLJM(Z^8@<`R6|uz)aLA<8{c@RnlYI@pqklXOMZopNjZ4OO91S; z_LLtyJItuE$gJggG2cP`P0IHgFB%(zIukDt)a{iIGsmeN8D{p`-EJFb5GX{Q0e&<_ zC9WIPa&Jh}Ce1-)KHv&S*_wi{Y%v}zC)jyg(Z}pPCnj6Xz)~p3t>khXZE!WQ#6Chj z!qfcYnUX?JI==y@#A4Ayc|Ur2_k(}5`l(BqQrxMKEp0P+C3ajvcEqQcdETvlBB>sA z2SK`+0?#AA^`&tkmaxf7U53e}yerR6@_Tf#y(7pDMfCI26|x5Y^d1o`Z3UQ`ftLFz zKbJ?CD9J`KLfmZs1I46$q*pvbVd0%`xf)GvrS)ggmG&p?Ijy!hpQCj+c^^`*$Rj$h z1?}1)b0cTT0F(KIq_i4YmD{@rFxM zXRh9>eYy^Oet6{=3Gx~;;^4C&Qz)psBKTM zWgQ9L=B8zWnR1PDG$+_=&ByIsnP*}Fy z`ghFu64@pJ%|fFzsKjU^BKa8XW0C<8B62J1%K39H;hBz47{yw5ba`u(zKXjvdqen8 zHxtTCCFpj-L*LzXNh8LXOkwB#>sTAaoxVl;m9bm|PXN;Q$F9X=o&Mx;91?<#w(*;9 zhK}0;dIp*+o)iAd_&@;UPL5sG-(-h&ec6Xmtz^+-5jCy-2*2Ky{-o@Wi2ID!!M%%? zZ{*5L`bJ25n20kyO^Wg}7T+mMx8ay$`rQ(l{=AR-$ip`X?ggQUbsiV-_p!ISSwQ_10CW56WfW@>*9j6Aj$ic|f!Q^}Fdjpp?NvMyhmX~MF ziJisOTDn6Yx5jbxW9??nRVFsl(1uo(=#t^@#Dw+paTF&%*+_M7-EPeaV37KVTaS(5 zz3!Pr=>&!o^+&O6Y`JZ1Gtb-(^XFcdwWTW36Mpz-{zC>kv)(n^IZFZjZ;gmKiVKeg zy3~e(oSQ~iJ0O<>fx8%&dATe{9O4+OJ2c{9ui;nUr_W&=AFbhR;X>pwh@Fm?l{(B9 zD~Ad2PRwf+D-VyFUaLG$8}{yQ_3fhBCb*G8!q;t+b4>9{gkERdgGi^Y^pI=tx7ske@)Ph& z;~KFsn9OBH^zB1R)uAuCm2-7m1oz&`v6F2~NV*(#Y7pXG^?#rfn}J)n)|0=Q&dCgX zvfq_9SkpgiR@AqY30k+0FOreYgk-=wJblfU@pMGwE<) zCQ_2M2tT;fb5Sf5@`U-BsG4 z0kz(KE4@BKZ?yGhI^Yuog_8OHw{t0jXHy&XdE=VB!ki6BWVDQcQE(j(gT^)Tu}*ze zbX@u+R_yudxeNPF`_xF(n;L6c44JoUkCSA&LX1nc0&(=Q4;79$hAY443D}n8S{)mD zUfy#L4;~w6#>$zlFpodTRpn|gXoUnabKp0teH|P>&Ku-U{9#~M%}e|2xW!DU>E9*x z{@O5i)CL>7Q(maXHj2fxVjgS~PbO+x=(IpV@I|+N!D@ETtZAkct`c9|P9f|u!Lp}8kE0(`7Z!h%^{rPlpL_kPz{h6z8 zlP&s(ZMe3ubvMk%8miflPvbg8&bU4Pn0|VC!j74@8T}$@LJQLdPoIbyOc`6?JNX3y zk)?R@r1RI%rNwYk%It*4{nov#wPM3>PL*LV ztmUI(8^F`;n{39{{9Q3an}Ad{b2Z%O&s3Y)Cs;;2XYag$fw+1x{iRY7h2Br{6{QKH zI-jAQn_934S>F%pUOkeQ9)bAeuSHU*y>u}j`Sa-yk&jz*$Y;G2fZ1{8UYmtCAi#KBau)m@y z!KznMbI^sbFTxa&mBGl(FzUpuypZf6*AX7jPWQRls)lXb;-z+r2XuZNbbY_DlLG2_SGDAuCsL6#RItwhNn%Si2_l%_AvvUZ8CWw~ZR zyC0YBS7a(~O@3P9p7p7j&|%IDJS2@eM*~M8QAPA|jdHCzO^!U2^SORr8-4G6_ho8;Ga#9 zFzXJHG3;*X>P(i-w0B7=xG3<}JGe?<&C>Sto%q^M+x+L;-3Cs=#)~FL%xlYi z9^H4n&h{e1M7ue2p|8D%9=fGnYh6S&n+fzsYHXmQ9UkfL7YFXh)q(Eyv7kq>oHjk2 z@{MDgY8d6VQgMt5RCEyh#=T1i;rWk(+kSmc&dq2){glte2E@R4HeaKm-tfeAb`&GI zZk!7Pj~C%*xRBnN6u2g{shwAXbWzTEJ6D>hfYl8eQK2rIImCfgxO;c1uMXMkOf%eB z5$+Np=@a2uC9l z4dnX4pPEuFKO(cnbGS+j!%Dr1Bu=`e6wr)3Qe5=Dos^eLGoq4-04jiyjOqRb)IAEhoXvulwNcAu zocEHG{N5<5zDOE%Mdy>Y>*Y}fl3_{?P=v&bTI)6TNr6p z)k6Lf1j;r+K?>v9Oi9#An9JzfUNz>|I?}fhAkgq~=CcZZwD~E$nL8!?T|`0X@#Ca; z8h539M_S?POib`-laVowuXd-v-ZOHj~WGACZczmd*B(LGl7lZ*Qyl zWj*Omo+a1GXR_A&!!I%GP*w1Af|IB}0F$_+yOkkxFre*#2+i~Dadvm#Swq!b<+z)^ zl#do3mTmhVWNWt#x35sAmHA+d0GWcl{5j<=oy29uejdTw`)B&;_Ien7AQ1XsGezE< z|5Ti>GcdQr6HkbRX~dsOh{c1&S~8-(F6;u{-3?P7&{-d+ zC6TMX__<`8^|IxLnCkIPPbaAp;|tmKgm~JhL>i0WKuzb-a#!Zo1M#AaXa%8*^E(_4 zVekMK=|1s2z8Yg`SYa6HRP4isS>Ds8;taf)o(iEQ1|3H?gm)GKe8t>BUu|+BqTtG0 z@kd5(wtk7UE95|%yslfYN0~lux!uB+N(+BqeT$*7P@fv_b5*}C4yKq$;N?oGW$`uL zGdW?kyxLC7*$bz3`k#sGjs?syJY*^lcmkKau!r$e&~8mH%M6pTi|T>}($9i&=$I7Qnx^o58TO^1A=sy2t|6?D>@I zvIaYiVaB)!kq=|!kJE(|*=$>STA`NqHMTN=kkvC5#X+&_`F1O0XhUWL4BoHvikERj z>Fr>-5a7vWaLE6%FeS%oJZkU!tyqJt&n>f_3v@#UtP=|y@)`E>>=|OtiYoAj<4o%4 z*9p9QSNO49WMmu&q~C&We!tc-Iho4T?{vQ>eIH#B&s9)2nuEg|`5!22fvkf_6*6^G z=vM)2b3vzd#o$4tc)a-`y4^So&9J4$R9%6$XngTTAYJSAvC%v+@&(a_hBx_>r9@81 zJEx=s2_MR7C4^Eb0cBX+szw0$5Cm*U_RYue`s%ao4#*dO?F$JkCxE>E&4BZFZiiiO zI`?`%c&!XFo1 zIp1%+TJl$BPCi@E>UNiEYNk`55Hs{SzTGLc+!>owiKRKKgOh9fW@t|H3+;#2;s16C z+N?V@?sqq4+OrP3AXRCleCE|#_p_1lK`;E%7SSEbVy;*sJ+L>$U+nloJ-zS$er5~0 zzWH`06P=cG_3wAX*8Ud)XQE->pn13$J1_mpu!E5wk-=*evQJ1h*UM$Z#&gM{&h=eS z_FuvswO_XN?cP-A(q0aVM>Ge}*%c)@3lHQwziWs>3~<5>i$1UiQn0`kgDAcX=Q8=P zj{R_)(8>?*I1$y-v20Gs;{F3^9^?eg?t2cjGS)BdjP3>TG0usGl$5-h>2s}QxO&}q zTH@JC0onEV5424&2T<3pyo?=6{vr#0e@T1Dty%s|!FkuPH#Jen9TWrY!m-qaf$=4P>q0;~mi#oi5F5u3P5~|`bW(ixGDpRm=f53( zDN-eUG6s;73nS^KPV0gted1KmbhhbJ(aJCk-jqX$yibpulNnh>IAisV{{vyw_=w2m ztr*N~N0IVa!;=kj7k}8@uPq$w-#oMk+5|#6ri*s=>b}~bc3Fc;FNY~IYg3X2BnUb} zLdqWE`Ct@8Zm}QtsY#>7J_68D2%LPW%%6n0@WM9*zyEtvGA%edX9wzanlm?Kvo2u_ z#p2Lqsf5eCO>AvBgkZk)w8@}XP^DEL>oT&B*gG>m z^1ns0w6Gr`S2_}FSm5u6s=t{LeqY1kgVNf~s1xM?VYCU=LaO+ILficz@E~15&|K|3 z^dxZ>uEzH)+vVZM&GrrMU@|6Z8tRuBZVQ!=8(e{+ZCZkP3#oeUpY#nUxO9;K7`#_?BlrmF-TBt^fn+RK-fl`jAwC)2 zRTrk^>`)7Hq+K+5q%PFNcC9};n5_;IU@d2>)K#T|om`fz^!b>WNviF`I)Yv|K*@{Q zJV9byO8k9gGmq+Ncz=W%`vmT#x37#i_mUT7Yf6{7uu#M=gh03o>Ko|{%jQ!bQ8+R8OtVa#k1^>gJbR?fm!hVEv0lV z$XZdO;HTm_c&GH$gf)Mk=hjQKwS%ncML&_5tJ9h0Q*4p6jmE{7}Q5Z(R@uL5$9e|-e(xc|Vo|H@e^ zz~%zf%4EQm^Z&O{KpKGeFHRDuX@Qe{p$v=w&4v&BJ3{>5Q|SL+Ay5{6i>IyX+fO>w zn*zs8tSgmdS*N?4_*_UD{dU#hDV51&6GpF3mB4j{QROu#`bXbul*rc^Lp$?}|DQ|3 zzNfux1+vpJ$EyQ@bWAr>DIQ zZ4s{V+!-fFX@H^Vq{u{#Jf?~p_-;TVaDwGdEhFrwNmJ~$iErvjn#@qP-v@+xblgW> zZ^SNV<~F;eWy(+%$7_WU$H2S0DH%39ral*?k)~~Rc`;#oh@R_$G24_9blFk~J6uaI zS6#PohwOe5c(a{BH1XJx4?@vO`?O^5N}kuAo`Ur9p>RWzDaMG6@jg#Q&o1NO^6$ix z`vCmUxU3|(l+5K!G^K@@Fe*M-V~ht=3T3AGm%f_Ll=pbuMYY-I6N#U?>KSMUOi|kM zhN+IIC&l}W3t4bdjW}HWn&@ZasjVQ5OW1<57qdfszR)ArJIfcn=iNU$c!7`k&>+1N z>xHJG09u|((8sIYSBevXH?%2{`r5^eI4hf+$W0XzefDVVIbH!4m}sjfT%Lo^T}#7N zU;%TX1((^nMinfy<3RqeO^I%$;)knmyNpx5n}9rd6LPt=oNz33ly@_M|0GW_E&EqQ zc`quS)X7n1xw`S?F9qoDf-ZHKOcp{VG|r@282ph*mpm7(@?k<*n3$+6877;wmjRoMw4Y^Eu!l7W*dWYRV=vUD(yL`6$jI+ z@CHEtf$pr|aOV{@4W;H~Y|IW|HjO4k*7R?K-DsK(Oq@d?wS%O)Nx>r}SIB}CLH5(F zSq{I|cqsc{Nb6_#)}+sVDN(gr&@AIa0yITJt@9Sq7P>ri(5e?bru2TnXn~112@xGoD62$v^WqIE=yfo#Ut_JB#B0E ztAraX0Rx!v%(juaE|fhSb>f8kDQ~-N&(SE^b?WqnH9Ahsi;olH63^qYT4#<@SgWu; zj!!6o{B_8C#wCq#0zjUq9HkknGq&9C7_%KJ$H2Yb#E%w5uOXyPU41RjahO^;|L%-#bN8IU; z2*~|B=r(5eMj7SAd-XbJ>OOrl#ec7kK$@DcgOU)!+8n!6jCAMF_0Cz%v5Qh~hCOwl zbb6cVO~r(NNcl{;^5!W0wD9+V1=$Qp?LbC}jH5M;NsJ*&jc5Fne5)v@R!V|D-K>BQ3H**a-0+C2Y!x?LPe8}1eCNW%D;Kg2+4-$6OlvvGb{kwgc>)hI`+0dh)Kz1Om|y)=6^~-NR%i0sZ|(D041R?vN7wFjAPi z*8r;?KP@40EU>sovIg4^e7cPRBjJ}piU2}}Xf|C~0q{t#Vv z@=*4Xm@K_+ZOG;1J9v-dpZJ?7jQQyn_I;WsC%A}ZLa;U08lA3W*H!A8vfz(?{4`UF z%S+LCH>B|o~LS*iAsc;Haz#w%`N`HZptui8@Az;_9Y>NGnDr~(0H?-{x?x8 z8%R>Qulfn)xfxN2u(O@#=m)v-pP}rHbFQ@Th4QTR0J_x-_s1e z8MPYb`9^_2uv~k1jxCwH6lErnuVrAQg?dRzYKH3La8J)=20*D%GR6WjrJZmXS8faN zBJ)-Qf1v@h+-_sU>}Jt96Sm~R3F4Yol8RiddW34ZB_kHGgKqvJTO>R5#{`7i(j)`A z+1>WpT2~ipFCGSMIXA&4N@Lhr+@+q)aDyOra^O$t(TL*DlVLD5hw|j6&jpLWfz%O& zYf1(sv-*j!f)dN(DW2@~Os0@=(~49?`)~D7M?2`mQdtJ+E;qAvVz6CN_yNVz0Lpa9 zYXp=U2QMd=m2=>mM}6o0^fW7gvz9vfZgJUPMD1Z|ANOdwIRz=)mF_zz-_tqWa8@su zD?3}U0I-kG-@x?A-}?mcJ<=|7;LDaG&^`Cg&}}XdxOjRrG>}2P{p;u7&-$oHh-f72 zuMEbF$KLZD(^hE`dFfHyzM>v!;2((j*ErDE~3P;mVy@~5OlqSEx6qTFJ`fsLDK3=yZhlIASFR z)>_jrBIYcqRI3GwKJV>sW#gyx-y5Ui?B7M1DDF0N#VjVYBzr1^HjYEpvjjfj|4tG9 zka`#Ro!JxG`g!Ura$Evth={&sT*jE$the_xy&9OPFa6U>1JC1VyI;lq;C*e5=hhTt zflm5i`dmBO)XBGL%4Eq*^aE1{GML;G5n*vF{Lh;un*+|V!9?snfs4cRL$TandDHIA z&|n%+L2^X9hQ@8pUuiAxcy2RtzSi2(PF{zR41$aJY5B0IMOsMW9c$YCji80h@8p@~ zuAIkBpTsd+K>b^2m?5Hh17sx0Vt2L|Dkzbp95S*AjehlU%wZ~iu#wh z1B6E5AxKMq`u6}IB*vnI1t`#|m|hi7Rnjp5jNMn^%J10G-hc`bq-BqU3J`m?3&KS) zJ9MEq^)iT)qRCQjkzV6`aU@K)Y<(aWROKh0bAlKChag2qb~vid!uiK#axeS}F$uwg zuoo)CV)P|6P2fT#5AadRT{C!F2NtFHm%15&RtwVB6-+T~UgqEwuuNrOc!afO z#2=Ir;)8c+?b78kVX)_pIy9+{LieO^m-EUu|hkbLJu*5YI`nkIgmHS27zr~?6d_B z@9(sWfkuwBs=+`cDA%K{1uwGf4hxoBWWI8-X&kdw0*&2L44sXQD1u8XrR z>XnOB{PlvPR7)MjgyG8G7QEE+`X{FWq8N+N^m^CdIK~f(eRcdIG28GI%@#pq^e`$M ztT*{7Vi%s6feFq6sg-|1icE@SpP3g9vStrcOa~~?X!2F1kzZso(AP2|d#a`2(7#$Z z2HnSxgmW_-1@m<`$D@vAQ$BP`R_Tm1LiR|zWF9w@1+Y|-lsE(8FcqGCV6oY@n2#NM z!AYOE-=VOz{T%T)fx5mbfUi*S^ZMLSlr!y5z@L|>V;ZLnTjzekyOUFf>?>Iv5ow!h zR&R=83OIbd4Rd|z)9;ftn#yA=ulH6Ay>VkO_4@#(|E=fveVx7`fzUVqzk_~a$UlwM8!BNeY{*b`-}}&QpoD@IZP4K>HZ{~z z4W3@|yU>pe3#s^-<=W@5Cf((`?-pC~s`on;*-od2O$KnK$5b8j4wji1J9@1u1%z;3 z=8Fpd=zv3zrI{IB_22o}?vAX-RIk)l;&;>$=8~My6LtL(6i^rQtnxb4e;zT?xRi_R zuN>NYh2A8H&B7Hx*8>)%%wQCyREGQB>B}+d8_~MF)=U1Tu5{2Gc+#upa*$!IVny4X zK1?CW-uOlJI(elVzh+r^$Sj?l2W?qaw^?ab5zHdVA~7Zc*}1PZ;&X@x2B#n19LD+* zQoNVq6BzNr<)Y6<5v7!wZ*?3#%vISlVQMy~&y#pJT)EOvGRYkLO&ehV8H9+k4kPnx zUdqn@wrr+$R)?vWyXTWyi^j3$sjwg>HW`>{b%##NKiTVQb?dC)DyMHmAVqM_7&Wx{ zeFAN=T!@_YEwhd=u4jDaeGHt?%w7}T9N|TV0}rEPj|kty0S$^M4ORaP#t$NzAZwCa ze9+Kr)yrA|q>fD#s{X3sNULIf+`U|!MxH1=di4Pi|OY`=Jx3jcs;y!6oe)j5mcTqD6izKjItvPhi&UZPWDhb8a#)jD{S;t*|K2ky<5r)S92 z649kxqFS6{`rJ;viiv$ge~Q&BJ{wmH_J)N#v8VY!=ObtMP{;?_i?yh_w*z&qE}Ul3 z2CeS}H$f&TQM4?;{$#c~5|*rNLJPORda&CtjQ9^E-`@Bi=v^4^@F!DNPSy#+iXW4I z_G6lNvlJ^{X#ACLZ==tw1e+6mP2RHwWrd zgE1WQV?(}i{@pR0ss|rbLyik=KFDKH;xLSws`02q*T7dCVYYPG0)C1jZr}s_Qcn|> zQkfWj3Cs-@GU%e|;WhQPio)yA@|V>)e|SZ`WBOlDGvP1{-WXSO<-%>~rjYBR(8|Z$ z#gh={EQ#2Jm{44fRvGs_tM{9myIw$C49r*V@?^)cNw6V7$j)^_xB0h(F?@qh)qLFV z2gysmD+WO`Va70RxTbpHj?9uZYx?oxrMa8K{M1IQZ^g8CM)OP~^CEKs>jH)KK!L)( zH>SdS4dVO#_WyuQclnmhgJ)pI$%Mr7m-2^}$9~ta*Iy$_qKK$atyC!+&^*57X? z#IyfFqeTJ1CO62VUy2!nqm(-OWiE9I{%*;JzV&w8#!0-{r2xN1D|Ioebk&!{b$oS9 zUr4i+c2Pf3-q!hNV6T7r#HiLswf>Y!BPkJMuyBG{zZct#*N%efx1U^lLG0i9$xyZN z3}T-V z2{}Z1dYQ;=m#G>fJ0eK`3=iO}$7OtC4;Cr)w>3Yb6UT}jr0-~>Yw9i+6;JZweZR_PQzm-$9JV>vrKmYw`UJc7 zqoqTU5eSqhNJ~5^>Ay>9yfdCQ(V38AnChBi(3k8;LFw8e06`fN?*3pdp&Tvd08bw< z2&JFlU}qoy(c)i7UC`Lb+5sjRi zr$q=P9B{RFgh=s?d%kB+@lwF?M7J+fD8H|&tx>60QE8n!g`1Fqts_*3a++o(`t{xm z4QkA{mdAsQ;GW_v^ywQqaq2U6iONlDf%=Ne%#sFL;r=IqH^Vgf*sPy@&H6jDVIgQ+ zfESMN?>5lAp8nU;=Dq))P6Ko(N$K=Ig)#Eqa)4@vE=g5kX$*R4q*4y&bOODk z0r%|xEAzwg5bg>PXJ^9!y$3z08zzOIt@y89jsl3Afei!F(=UVqyjO-S5r!8a;&Dj= zZ)e-LK21xCjJ)3Q8JN%KxE#v7P;fYxfYzS@uL6y@fYQ_wf8C| zrtj#0w5bV)|Ei~ z(z+mMIh#Rc|4B%Nx(lLyk2*9cljAXn?{8Zw#~9zl_2HGX`$&We^{X6ayEK6)Mg*_? z;AG=qo3Soj#$et;r2>mw8FMHTTY)AbR(=rf)!mS}h?k*F20N{TLZVGv?^b+}zLhgx z$~t*HEuTxpNHM80;tw*9JV|^7=6=U41xP0QL&1k_V3}Q=@aDdH{KkcC+5nQj;%e*cl>SwtYqZny!5vYStyS9lS<4e5zTUWiM&~v9-Fsd!cgF^45UT!+xQP3dm*x^X zBo`^er4-`U{7MRatbL9SHS{FV_m6$2hkAzH_me05o1WT-_h&dKzgGKfAYI!;SA-54 zU#}rvlY!&GBk@mm&gG$$PS;28Oor|5oWV={eKm#eBCsTtZnmq{kBc1HQ|8Uz%<

M^V@&7c?q)N)tpD3QI`2(Mnf zt`4QL7_Ly|i%2&4vYZ?}`1J=y@Y3+A#?}3+YK9HjDmDtd%TM3eY7EXX_V@J+$2^kI zUGyd}xuNQ3OPhMMf`nmVp?j;k$=NS7D<+3|OtZ8z76J~(L_gC^KVBmop;)h%$2KMB zWY5@Z{QPUO`7CGaA?h(oW+W80he8WJLH5e)O2e%Xxnrap_h>jozt_NXM1Z%)knp-o zT9WXGbVMC|vpraD&U%=7q)Y*2@(IHvVXqY`E%_dm9~GNvpa4DVOO!{+uM8iE5AMmFM_iq(NjSXP4$TG^d0tzs1& zmQDO0XfLtRgk^=OS=KkhZhTibl`}%YwYPb?V-?ySE3zH;I$H(9?QoB*ntIe$@&^1H zJh|MOqr)nh(pPtfEwPK)fQsv46xmgAK}1`S~)o?iPsPyfYqcD(E(`>JyP zEGi!PaBkn%#a97H2!CQHa*|7@a{a&b2PPDMz%VFV=f*{m!IQ!aprX*I9GtHyZV=>Y zbPNH?E*akE(_bDp2aQHMQ+hmGMGy7c6Fy4inKgI;@wftaEFy&xsn^Ge%H_Rxd`4p9 z^0UhiDZSGw?3K11+E;Qsr>nweLPBKM$@f)%8kfp1G&`&|9co}!?K3;*A1D@gqjAn^ zG}x4mcqEAq%3+L*__qEGH>RT41?69ADE4nY)5}7eGXSCvf{3Sl0J%n?P-S8}L!~ws z0Ca!&cpHYjzW(@GCZAfgUNgY@3W8Op9<<-i)!&dp*Ti!{Q2e&3oxbmEz(AVT>S*e(??m*JGeZBBN4npu{`rxUjGMiJ*Vf!}ON@-H^7 z)EMqO0RzI#D0TRQBC*8|)i#NVwP&uffhJ2OOds7uCxwWWz(bZoqB#kj@$Vapjd+E- zB#lyS$aXVmMSXjIOo|09sPm$coo;1JvP`9XbA6k0neUdy>qvuRxAEY!wbIEmAu`|k z#;q8L4dglDenlKGcyK&uW$G%T>pK8ln$fyk&v&kDjLz+-#hCfIL>|CM)+CHU=A}h6 z{32&slt}U+(L3gI-!*JZCH}`ym9achaJ1A9A=)}iC;z*}{e0Q|m1hw%{LY*>!jZ#u;oa1$M1lR~HcxMdz!6 zeeO@*Uv9|l^a}Ime+m|%AEN3-Iz!sKYhA-$REeG*YSPHOXsC zz7HMhdCYO6xs8u1&ABu>zjEPZ*S;-Auh+=1&VTZ{_9Sh+@5j|BZ!kFD8~`*gaFah` zR=czICWYSZMVW-7*W3$lutreILmNvd3GImSZ*&X3aSyD&PnQfhPY9Z?yjV(q0kEpW@ zYO8D8Hk1OTxLeTRTHM{;-HW@swNNM;2<{YjcZVXu-Jv)HFYfLArq6sc-%S4H@6OJ; z)^(o8VW%K$c`1(!$Tyr9*wn%I^R-L5f_!sjHE{uU6X=2Q?OL&h)%xmMnHdjUZQ6Gs zPQ6cAM}a0d4@L~%pHe>aCKjWeLinA+XD!KY4VZdro_W#@Y5OqV43MMGZCjmBDpr}E z=lX7C{cspB;h)vY$Xo7B6ZnRP>Y9VLtB0>{3{TP~Ut`V$;GjKl?paurk1&`HUnHAWE~;?CjcG0(%&0;8J`m5QRWXhfHHxYuVy82jHezI1ju=gZ zX;^k$Ho5HhVH>k#ZP*cBs8ueFX|C7PD%VoR=hQhd~Q*QVw^8^gN#9H3KZAGhg&f=2qO;omabJp%u<8%HZ4%`Ja3 z?45^=f&buC9cop)fOxNLS+0A+f|2Ro7*$N`Bh(*3C^P^!&oi*Lf7L+cuuULElnXV; z?{jKqoqq981&D#&tlds}}>_J%_$P5=QKCo_$ zeQO)G(N75+Tc3HMqmrIE?`4RGk?Bk^cT*Klb5c`mHBQ_Xv`wH&i`ii!{Yy7T@SYhO z*G97)D`3R;{-dgALXSp(-9c*O{LHW>w~;GqrNMxwPwR^38k{6#-U`aJ-9Y}GXNf`$ zgfTb8a%=bHP1*!U|9t#p1$>I^I7s=K9B>0W>6BgQxhvUCDKv2`+b+7YD+@0Dn!8E3 z`js8<&Tj@_duE_$dIXl9{&H;}AhK0>yP;BUIDSPM_?^m#K2j^c;w3;UOFoaaQA;BY zs(f|lqk_ig`3s(n)yzE(L&>&P#hqWPsYP)K%SSLT8F9Gf?%`Gr58RjmvQmfr6C%te zhOU7@()|xkJaszh%pK?=!Tp7-_~0F~y4+T6kMPQ*rh(;BG6~(+%2QFC zm0fV*9JEnRrlmECd0gG<4F)AtGdzzF0W^guCG6h%nMq%5>RXjwE(VdS+?gw|EsMc7qZ+&ROCRIa8zf9u=w_&GpUSn;T zTy*#^joe5QYd~ariQNlN_UWUh8EIewO&p>>g;=JCoVfperI-SUE_QL+koWEH(v~~A z&0-C8f(D)WMH%Gim+Y6OkrE|@wq9|5h_SXlK#E!gXABid4nExLlxwB{T7s))M}8_E z_Qk9O?%OQt){hTzEpRQc6~jNrHO$Wg(@y@5f%`#trVgVzt0OEIqyCHVz`D)<8+Y_! z-+zS7Jpc5>FyOw>?7!K?0q$Q|9Ts?Jct1+?gWw3 zw(Tk+TY3u5=k{51yg$AQn8s=Tiikgvyg1ewCg}d+S2v=0Z{51U%}CX~)Z`l?JXWj8 z+n#mEm8#7mAuXanPxFeVi=ES`xHYw@4b))v>0Hh%Lw=+wmWqp(Z-t~)n?X=}k@d5UWs;HG zDLmSTS_4rv**Wc+^gpf;Lziz8_Ql-3PL@m+Xy2{7e#3nSF2P{$fMw1gy>W-Or|6A8 z0n;1ON%!nHVjLv9)Y;U$OrOSk#?BHvwdftC%YPT7M|KBWRJ?EM)mymyJPskd);Ox@ zA9WwK*cM&-sH5;ir=ha``X8K3Ei0 z@qEv}wB32Unh!w5KL)KhJ28}`plxeR8oSk$@f~h78h#2bUwv|L6`f>gvr(NRKm?2Q zS|)FlD5lD^3sGmMPg*u8pYSULL9*eMzw$Omi80r?y?K+Tc<9-IqUG5MP(CO7r^+rs zSu)Whrv zKEE|YMwq-sv}iTXEb8U^)nA#$t3|EpM?^Zzz*e(yY*MSQa^^a1uTUO-k~jgenHRy( zrbaF{&ywemI>$$CrPBsT8SM~faUs$z&{ty=NMr#Lr>b`}V2|81GlC%~`4tWnm5#Nz za}m_q7W;;3Y|{?)0)7IVWn7-f9&&E{XXd-auKy;nnc?5>9Nur0D!7?61|m++O>p!- z()BcripspH`L!gBVB#qeqr>&3D!jkJIv*8t*t_T2bvhp)C0|=re7KfXT^+oL`zFBO zj|wVYNf6E!VHlLD`YDS3l)cM(h3v8>P1V$F^<`4%rWpIK`uRy_S>*iosjQr3J^P5@akW%|{LVCS5>}Jfb+ktA08z0|2ytGu_7d9% zuGi?u{k@d`!4V*+bw@R4vNYl#XK*aIK7W6YJ%U`LEBI^>*q4d&R8T%+{oc@v4~KeF z+B$Xd;JW`k^o##{@@}2{J^9#Yr{`qjc6+vBnlR#NJtEPT)14TNrkUimmBDM2duDzm z1i%6{95Rb928ULvU53b7o1f#5Pq;z8N{%$KH6x(h=QrioX3uF=zhlRVti4~k;MC*8 zr{sc?gU@>l)?Mo~jh)m8P>gorgiII+_-?NmLQ|um95d9LR3%4Acc_$BOtiF zc61DIXKxlE==;+?>{Tmmd-uqLM4(;URL5pUQp)z^%(%CpLdk@TD7Lj^=L{3uU_+#! zvANS1zV@9f8^>%S#BD}Rt;AFIgvMnlHCOHGRhP3c>f(`$M$~jS6-`xD;A1yN!0ls| zXNuSI_#5}b_fE6jfwn*{e=kj;h{R1LmsM={o7(;7p3(kt&-tyek-D&dnW4; zCWw>wM(wBv<9NI)7vs$1M*v{#^APiw4L@G4*?Blz=r#U5lB*b`;p5D(`51HlQ>7R~ z;aUEy{l%+lz+o<@S=MNK#@6$@*QZSzk>fHi<^dZxOG*!cm!(bI*ehL5`!qEigguIn zCqJjDFRY09Br#@az+pW%`c}zj+G+_QsAFa_90h69yOue^Xf<(HAAp;%QXk8VUB*Ib z8t?5_ckWPb=Vohttc{L+o|Gk^vC}3GsgY10=7_KsVhSx#O6d7ZsXU;9Xe|%!HKxh% zIo9h=XJ@&a)tYRorwoke25I`MFd0MowLPxSuz<0UYxpJbOi-E6(B!2jNp@Zyv@3@k z2^V+&SQx5FQ$zIDb#WscR7OA(e0`PvURdA6re50jtG<;EAhP9+xn4F0eW&+}Y}J}hX}N4~10s95s)h`EC*x8ek` z9FKSTrt~u zqaD$tTlaFQvRT{KH0DED7#4FO?vcW(}f!jh06|SLa+;d+yR=ByG=n71SVXx#(jt z`*N**&;&kiNtb~GjKO4h1hFu~(855;AIJ3!dZn#l^}escD)Ue}ANEl%9nsBc%; zm{6c6cGOhWhYLj0RcJk4t{}BZz({-4(9gACuPu2eP$b5H-gaotT*zThq_CFn_kyk_ zzH+WhoMpgEHdhTl0Jp>O0wsUqF<_>$o4KrQ!NgH3KlPBn0LpL{mM)F#pdhq~m3U5z zG!ZIk9Y zwCWJ7BvRrK>Mf>MjAiUoW3ZgRLo^+;$0)=67|pCi@b5BP3_tMWW^ zFYJ~-#p(qz@bP&JJuK_WH?<=X>JS@9oMIO2=(5v3I1*87=`S3$w?>rAl^AVEPwx67 z=W)I2aoY}D>1T?X6SLt^3JT|ER#e9O!@GDK0G{fQ3tvld^x&59zk0 z1(4-l)Hg#C-QY}pL!PP27RJ~{X9#z!+4mBn4d=l1zT=13n!rDPmNP^+-#*ucy~ z)iw3V*ps)jW6c(OCUDTUd6YNzYhMP^CG*sjFgTP+1Pu#9>pT~9wMar%xTQFShPyF> z=COfcD%yd5D&~-{c51vm8GTQl#}PlA+~C(5dS(0M2VKg83z~>S{Q3HI8-KI0Y;NdU zj9x@eERLF}ZS+iBSi*t(|&plA%9hK&bu$ z`>`WSU0O0bzRZf;Q!u+)L*(SfChhP*q}0cAo1D12X;d__UxGF*BkhnT0bIKiN+fy( zye0;Q{xCUp%oYb3^2!gGEwGJHIjkvM0cQs*`C{C`3BGFoukA}FngTBlOMltDg8^;+ zhhG%>-;M}2cKx%pzyEXmzvx)s>@12n`~TD;p)gbqY%;^Ffj{Nn(pw`TaKin1a&~cF zj;IK|Mi>O2x|Zs1iB^CLjzFTNyF+{0Wd1WD^#0p~M255Fj+N@C{0NQNKh)vRxtU8dQM(N-S@TBv zJi&@`dhOl4HW^41EqKMdXa=(=}BlvX*5>oTO_g6|PjCc%GS(enV~w%yy&E zGpVc$X_Nm@y<78PX%ylo>SnDb|DzS?Do*EH%nBc}6-yQ6JV!~`IoH0Iv z!sa4P;Ff7^?&JD!0AAH@lcrf?EmxlF?+k9rEb_rv$T@Pl>U-73aua&2zMR4-{G@Qe zNkCsJ4glrk!SJP}_MwqkRV}N{?fx{)Aa)KNkR-3{EF2UKg;<~#Fjvx4g;(wW)Dcq0 zn`@q~8%@^fZ*TDqe2AlJlJPY;!L)gplpeT595&LVFcC-owac=CJd<)o%M0XjzmtGI zxW~G@g3gUW=%pz~uB%RDtssoB>N}08xIYFibp?G?vYvo+rUa1ZQ+#js36o!@&I<2z zwFXAS9ay>%jUfw+I5N~(8rT!1?%L!}Y`VdHMj?KG0DY{J{g|5LoZzHOx$hN&EvM;* zys=&ZHc7@kHXG>qJaRL9_q4-E`_1AYw}c&KNPcdpV>B=V*(m$W_f z(yidOz&Qh@01rH0y}F-bgme^J56_N~D~|Rd_$lrWkub9FHd;ftJ%8a)*;5V)Qb-zskd_(7+lRtN?Y+$!5vR|cD&YqTdo|0)kqqK4w z)ba-TzQ=)&$YhSn?h5WQbZ@Yr4mWD7ilUNGT8vQc>rN6!12$|5rWnuQ{~bOov)HPn zH;1>p))<(PSctU#H2y5tAQH9nx=54NNK%kf;BuF}*lwVToYm-~(o)K7bfc3tGw=t) zM9U~H+lIjBaO-bSVgsc965$>R)Q(AvZia^P|+xa!?uvcRjya|_Tr=@qL14`#Iw{jj8=}}OA zs$0hZl)4kocwVjTFHGw@7s1d*TU_^itmHSTJ11-9|B+Jj(qqznO!TNX0YJddz>XX) z&;jE&;+*~!p&q~0&aojA-78mDO5{woGGOunZn|RwN1% z@vgDYE@p~-lmGgR)$#n0C!vWXE2J%BI-B0`#W7u?1TJyd$lZKRc;DBwWiE!~Q_6!~ zUqn`WgiH0TyaI=6fwA>hL`*Vy0L9&z{(-8{jdM&E>Nf6N5$t@`o?dA&JBM{*avy+F)O1MBJQ>O(7bscgww|S$ z>J|YKc{)li4%8#YU#Y<7X!wLqk^Yic;~0Sa#(vBEJ&PQrcl zy4ME#n3q7?_375;+FD6QbEIdcjqhm*gsBHvIOoM(C)?iD?7@_km+MW(fUdpSi0+nj z!joEx2vIvs!UuvN(C8z3TTEm6hP~_0c5l^&&Y~QB6itLv`86_N=OAZ)rOpAG z-0DiSJT(9KGMC|50`DohJQ86Ia8z?#@y#0FN-)_(RZR8)@rvbfacJxTl}r z_y+C{nJ3~kwC~Po|5D>k4!t$s{dTmFazHscf{hT_4MLLy2L-j)eEuz~sjc>x=v342 zl;B~7gUR0a;&2Kfhb3n1J$78)FEs&tJvOd2t6E?Jwx6mBPeGF1L=_jJFC2QMXOoBo z>W1iArJ^cXn#PgPY!Hy)8rMGE$RgH0^AXEeuEmW5Jm>;J=AS81>NQ4*DH-h!p|YzJ zix4GLjWoa!upE~>U>f<7Fs>$%5Txn09COpw1noL%kMR+pk|&!1wkb9Ttfh2u&%8I8 zvfUkEYhx{Gjhr6)IE~s}*G8)j|Li{ltf=HZ3nm?|joboW#e-^W*~)g;!c)x+5qI&N ziPbr7@+5`@u8qMMD97<;gJ(}A%vi0t)D}I4vMSHSlI5;^@3hw)HPyrItt6@4~r-*6bQp*SUbm(&`i$4)hJ2|IGMeZXQhKv|9wYulX@a_uc$Ow|qDj5|Z+cqOV5&od`$1;X7oVmIas6+}h?R z>qQ(oyJ%x#H-6%m{g^6e_8;0druQBR3b7d*aP&pB}&oyv^h zRxRfyh-(d-JNJpM+{_- zyCzgIX@zpM(TMEAMPd|85q5Se7qzuvEGYNXoylbeL+fE*2uJk^Q;FM zk%{w=+^D_*T6&P>vIidxw%x&1VMDMQwIg8Su*g`&L)RjNGHFF;@nS_O zO_KH_8Nd?#EM{+*AZ@y1%%sq4mwQT-xSIPy^O8&>8ExDXHUDwD#fz1Q?^4l^{JvUHzjzxdi7(%_Dr zjX1ExunMN-2Xd3B{0A5JyLz{+MI}w)z2f8~rUFJV$9&`TQI>)s?;w$ohnM)-ilI&w zPfxe*HlfEe(l(P80_B&0(13w~xjKd?VyV4gRcCU0O(lKm@W1}HbP5>a2d~R!FK=x& z`D7*1HW5e_6%v70>DDY(?czVBB5cOiw|<@4;$=niUsTb(sbJI<5>l^H;yIM5L z9lzq3Rv=R|Yq7sF=C*2L^zog|A6)*S^uDg_DeR{#lOY9%6*;Kmfc%3>)8iWRrN%cW$_|w^r$0|;VSA9|3tL!w+L53>Up&0WgURz#Ta2%a7 z0^);|J3Ho9Zj69RR?p*f(&LPd)?~fet-ub`VeYooHp1KDBks}lc|_9I#Ly%7X)ds# z6!fgH&LnAn&~U1nU_q+-$^COg;+ntP<_Dd%M&2(Q`WzyPInebMeVa#Oyo2sEbZY1j zP@ACh;+rfn{%B_#N5%jg7H668&8Kn9<>uJY63z8ThO+^oKWCo{#3`g;%RaG^e^EtD zhc7T76--1H%!B*z*6o$X=w#R78y7u({3@yy8Oa{I>sqFjh2M;^3VC#O4mwS*D^ydIz>Sk z;iRcget^r4f!$K`5Lfl0L-Ie4Sq8>wFfN}$O1n30OB=^<(i%mIh5JcD=r;ZYzo(%2 zrjnB=^P>42uKF_VEif_M)~b&(F%sx6mhJGi3L$=3BEa{G6|SvGA$C#uThuomLj{CR z#LJs@Kq_j#-xTGsC-Vq}4vLs?TeSxYZ0Q>lTa3&%q@vX#`G#`PSjM5})lr;!3J*E{#_JkDGFxCYZL|rj1QZ140Dam*|BGKc&bkum z%|It=ojOlx0_DiTo1swsu=4`D&m`xz*_l|`Ee#JQsNu^c-FP31X3dYL|Ms1H2w^ts zXo80oXzXqWy4ESV*sAjMrR^Cts*0w-{i)q#g)#Wv3kGuQu?0jEq>vul3G)RydNpjW z|3We0gXK+~pF~iMZNuXd44a#n3km4rZLh|}`hyq)D~ut6qNY28G#K)XsR#&VvVYw5 z1!yj(iU_qef^>Kr>da`?YppxoEWP!WE%@I%6ODv81uV)sTr@E773<>u^cCh#Y<8yp zoxmIy#)(N^09etyH=#4Xl8*_d^GoAHBRiybKo~=K)y*eh#oL*4ypox^%&uB9HmDLA z;$%;WPUpmNkMEn>j@g}jbU#1-+0Atliv9E%GTdpjF+Knk_1=}Rwq?^AaL#uL6K!N6$tXa%Vxk7bKjG%(;xAxXHIdv@{Eb{irGknBv#O_%@^AE}j zE^}{t3^i^1e{f+a>$RbblmO@)$n)6IZdf$V>bO3H%+Y7vv>?>ii`?-fMm7q#HD5u~ zi{XYspO|TNN&Ti>PA{;7-if==PHMZJd#xwMb*Z;@J#c`3Ym5>2OqK$ zcOy`xc3{Yi=xWncReq(nYn&EFz_qQ!)6E(dSC23U3qbV4U_UK74g{~MX=zZU;ZV)4 z9TO%M-Aj*Y@an4MZ%^iT!i&0FU&x27?#~_O!jkvTb;eVZ#lB}{pY`%CwkUY!ho@4; zQEK49>J^V-J&q^&L(_4=GIFTgW{NM7L8n}y5D`V!D^v>fHQSkGlaelLb2MFbtZ4-i zgiogd&sM(GTnFmmP8(=|L;1%Ym3JFzZHd)t*P7oH=Aw0lNXP#vOmK3>b7;H0CO5Hn07g`P}E?Y4VglCdbkR1L;pXlJ5-uNeMCVA`l%NNt6`n)G0aRL0$im-GT@Li;9Ly^ZDCC62RqlRYGu zzcw9_-U*To0!RI&vp2<_ueEM=bnK{|OU>2Yu_XJ5y8v7vJBcsvQ~~o;*@%T!%5LHJ zEnHZ{eE6IaVr-+_PMPzF020Bh2_PzbX5>ns-(`N`2NzpQ`)n3tVQ@XxaB1p}j-2Pu zFCUQwD)=HG>1fP`nC`T}f!1pM-Q8`fl)L>l43$WGsIk%>-39#{BPAPywi)FT>QDV1 zfXfXap*3Gl&%pdXJ57#E;S$g)Ad`t_Rm0f5c39U#SC!c{ATb_aDDe4YpMv}kb zqUlGm5l?|%so+0TEvAlKu0ljaPN}$maZ4A@HI zjN0kflCs%g9I*z&(+5IAc^i2I4hf7~;sMeOUxZrZg&I#Q1+F5}CY9@MjV(V(p$szg zh@q%UOmYj)2$(_TY&KtUVx*HhIHNDBfa{m)UsFO#26a5|{+|yT^KIYCe=1qlq3LI@ z?P1Jfa_Y#YNm9v2yB|@p>p5?dPy4G&%Tdaa|G4v4I`2?g z3^%nua>AI0_XPZdn1k~^KfZyPa(UAi(r<06`pRy;xQQhSr+jG8*10o-Vb6u* z-XC_$FDk`ZUT(hxe?ch5X`Be`2|?OuF3^0#B?bCr{u-7#{kmrK9N-ZJ`kcqn zYP?@J%3ZZtRNkx}GeavJEbBbQhzBzEyOLe9?p1B4=PEm-G?QY5n?k{Da|8OT$6NuNA|A73df3HdPu*j|lJ;=3A zjdat1*tShx?67o(O^%;mSAZ%JAu;f%YUB=3ez>zu7_X(SMCN5Q1%TKm$=^=TmKVs8 zg$6VinMA22zFw0DPBAffoiRtWG;!n%yt^iXVyy{Zcl2Sc zJV8F>NFS6`^QJFbD0P^sbH+wxGj#pNeW7aSjm~tWz@qeS*^^mzSPreA6MF6_sQD%& z+XCsq48`F=CsYe`<}zruFGxY4t~=5>t`^<7UT!_rIk%>-Y2^ATxG755rVlE^{}1jP zi3N$`0m@yQXTSAt0$3V1z5J4S{m!(m+VcT!q!57Nns@smflpoKBLt(w2cp_#FL)LvFzplb8EPS=j2*31xTL|?F+^~oBTmsll@NDG-5?G z_fHidn`eZ-t#QGX<&w6cRi{ga1uQRt80={pI6*JUaJo;*Kw)Pm{F%5g!4T!}H#Pm>g?jDJd&(Z- z!nU)YtLWt$b<4dgkNKS4NH*mTRiAXwzk=g%H*%Kt&o%x^Uxp+8%@5>_4G|?<_)BY` zs)uldylM4uhIK?C>$5M3z|)NW;+sUBz5}1T9CL;K6411$H+afu&y(vZNPY&-;W41L z0&#P>6fYKAR{XhM$hJ>0Z%i>>>MG+z>r_jDF4xN=jMrcny;T+T;~oYY2e?^V3(yv+ z&Q;fV#o9Z2+ckO#oWyb@IGcot4_>_9(Yq5MnZ{ zlT_%mVj3+~uXX~NQ-jsyOkCE7>D%HjHs4har8s?UPV`GY(gM%7=xZ;JcWC%rnKl(Z zc`7ckc~^W%U1fQQ$7Ojn2tDxku-K-|!A=#1(J;dxHl99o@%v<4@^jqs&g|wrNn2wD zexPH6O#&*cv1YnqI1bStA3J9d-DUhl$Ie1YqD=>^u4bZ&2s7cA@lw#x!gx7;CC_5G zPnqrY!EW%R%rxg*Kjm?r0FFCG=%R*TSmbCZexZ-{*;eT&rYRF#%DcykdRS=nT`{s@ zER5L<7XsV3{#&jZ!oz~Frgw1vc+TQfKM3n!LK1{Hbrf+{7`XX=*;kk+5=LtN=fG1( zgg+%(Hz432F#sWoi(0-pU3d8<8@9$OcaD57YYO6YIochOGREHI<*oYz++1NZPJ1e< zBNx=QUDpjScj#yjLnIg;wKtWCCq$r!8NSJ0ba9eo=i={_4D1Z`7i%t#mMA+j#-(JO zN{ZG6-rfSCF-6I&x^h#FS6l7G&62dwM4D|U*qm*Hb!teYe4Q}7=vpZxJTR&*UK9nM~p=YFW{5R-LpvY*$ zKCLsaGYxC4N{Uz?p$m$91A5x$C%@+}zU(UOpst*}*?F>6hzX4Kuk}_)rxhN0_i1|q z3^6mC?*cl{P0)Y|ck{8$Hq53%9zAF#4VKyfKugm8d*c3=1#Uh09Otw^SAf~-C5k(c zf<_icW{(9s?$ZE0=@;Zu$4ra4z9E6lCx}^Rd;uT0a!1x@2>vt1CWY?ECTK^eeU8xj z(nRhJL9wa3-9og+uex8c0FOaLGCY-tOz72?=UZEo^mJNZG)L4PX7OYr83cQiL6_FU zJy9GA031A4pB27=1?-=`JG!%I)I_W~7R%#B;}cHV!C?BMvChbLHQ%{S_fVG{dQ zLI>9)BDw>DdnPfDN*{w0D3#x`-2!h&D6;nX^zG`tJl8NA2&9b+3 zn473w5ApX~ash;xW!ACBSK>B2!PYnZ`O9UZdvul!Nz08-$_f$h&t;GiUlP^G)bLGN z{Z<~X3{*w;FX(^58gk7F-ajVT(mhEo?5y1eR5#15=~E%zqJ@>|tn_N9q)Hxo&xDvr zPij(EHPw2+G0vdMtoXSPzF1PuB3QWX0sDCIKHH~CE#-yaeKk@Old}qZaHq+~`CSqq zHg@Kuttan}pxcMDvnlJ;aT725_eJ~GO(P_%WwG3j!KwnaI#ltsnzZ>I_)Mr)mbVz< zz$8c8+gkZC`)eC6wxsMWqaqqNrf2`pe*OFWXIWE4S!~a^-EZ}0@7U8VB)0y}Y1{`*u4)hwhNY)uH-8dn!+SD}37-^~WZ))DY zO*7+Ezq-)D;h2_(NaUb-#uNi<&fe0-IBRcFPb}jYXz{9o)->_%#vb@$A{+G zX`7aQw6}T1$Xnx7frjNNZ|^8d=<><1$>;9s;@GIk;d4up%t5#lNE%e;tNk=?8xoWc z6ov<5PrP0OL68~4vP@UMQWVxb*5=#}>-RSTkTXL|jkj^7M#zrk(dqT*@V6;ZzA``q zk-FMvwcq+j!6X*vbA14|+-{|^V-5d8QYCLDz&%SD`lUETJnw&}MqQB$Ay$bfVp;6clfJq`6#&ck&z>y0ep{7%F}%axdG3{BL= zV|4h-+T8#>Xs_-+xCFJml4qiqCD=XAOL{}|L3b>k1FCSG8@BkEKP)uf{>GXv-C8x)#fhrbul{dP2eLf%$7{PW|hwd0UreiXO= zJu~TRkc5ZgTkS5G^Aj*JcSC{rxhcm@#?2$J*+(zMwlig6j7m@FA!#RhMi|R|<@br9 zlquT5v?;|B8+VV#h!rJ~wJtvb5pqs&lVN$OR5r9%N{nP8-%CXt)43g;mN5rfpO6RD?bp2oBbK`2rONd}@D)zJ z_>aF^6ZQmg80Tnh2rks%U_U`s;_Gm5c?PB35h`77+o8yy%-_o~Dki==xtyyB7M1q% zh+ww!lDHqb?}590jDVbXNL8G#Z zH^ye#dEnbB6A>@G){INvnaPv&xZ<>Or>?Z0hb!C8<+1#T8Z5|GbhT!zX7in_<{RO% zVU&Uk5cBB5>b+bfl+x`~Ru+Cd*|;G@HB!6VqMYWXkWzdCPCC*rJ59%IeEWzp2VsT0 zWg*_!%W9($`eafkQ@U-ifz*SgmSG)jDL05apzc5Ip7hE6MUULOt*HpDP8PgBgO08w z`}E3KM2IA^k{Ns$cHlAwJwzys0~?@Z))vDU zeqX=OPX?zo?XYGTWNGU98dCgOb>k1=jTU7L#7sRDVZ8#xrc!FC7CFVPxr82>8?ww%-A3X?)eZjg$}tNXj5`QOHWbh) zS%(=t-!f$T_ST9QT@8u1_%B@$=LgZ^%3HnqSDHR%Q+TBD*VHI?KCoQnXMi1bzUfgIs*2Q)JJ0T0C#8rC@EDZHSWjkVPV! z+h$I_JBZmpb}w62Bb7^aN&Bg5K#dN3%?Q9SC~PM!PAM07?y>|Dzv!x6bzV6Qde#k64o5oNX%|?LH?K|X4&d|KPBf8xV{>#p*vUujlUX5Z>m9|_=i#%r zYRd2%uR7O7!g0wGt9p_GnJX>&6%>`mn+7~RL-N)w7zDd`IJ=m)43~1o0XE-vr@AQifDVccd1P&f6uS|zKI2H+H*YCMs>DpS!4ZvX>V+h3jkoGE?q&eM- zJQraBf48gjmCOB4y?1uAI3gYU_>QJSdW!{q%MZV$dre5yuJMN_7oL+R9A;(1le-pf z4g&70J$eX7YBHcvE=8T~Np{VdHMI#`NuT&Y#R0)psZE7djb!X?#?Q6Fv*k!MCl8g} zMqsWou3`B0RN8o-XE2agyVRdDVDa3L2NT^v6tIAvyPWQdxb#|k?eRM;7ML>dqT67P z=W-{w#KVrcxe4W9 z>InnTLh=o(vW`=+yF~%@399+(i)^~uvT$-(!nbjjuUSRh(S-ih=)9*K#f`&p z4O5m^`#z4-CRo?0OFZ=U*g7Qw&OKauITiSEtaFxgK|I%wIQHl1xKlKNMI3;L0Wqgn zT@B|Z117nuK1`D*kF}UCp2^tOBc!H?rrEs`z+8t4*Bb+L5S|9=4)Wu03 zwg+l2Vk49|%sUvCltz~*rnR>5eeCtBL~!Gu@G(AWjbznGY22W5?!&l0xtFW&aHYD) zsF(EY`3j}j5OJ6WXkq6zhU^cncQ?HW^R4(K|JbG!qvlXHcQy7ROE`;x4x~$HC=Z@+3zF7hu*JA8V61fdbdUdp9+Q|evo7oYySBDvGpHsKQOvKkw4cSS8-S;_lE%e zUG9#qR$By%qb8Tz7{9vd#2le4@yP(u4pr6nYrJITr{!n=gM*~2USmeN7+CYlZmacV zDj@E(=X3PY?1Z8LIYC7^faPhUHA#0-RQ36wF1{EQK^TaOZ^YZ-7z9!d(0VE|}A%Ouk2S5q?h4I6= z8*`TDHatglY#j+0GDp+C4+5dul0*J5mNjl_@a+V`0%?STaj#lx3kx$HsWT`ec<^tN z3UKUVKVW47ZFbul%c1Dz4Lfz7i1xRc)LSbTk4ZT)wdDf2%?709^WkF4!93ywNwxPc zP^6jw;0^c8pxFnbE#b$Pno}dYw69iKy8Q6rY})yUrvd}xEgn`uQ$>Yy)ghEB<)`j) zr4nR4-#m-sU7KCn&7W7t1sU(4KSY-xBB!7XL6+?pUV<&ks}z#_!OX+2-x9~GQ6Z@H zx@dY;?>zkeYJpPirg}hP*P=n!WDPCkieuf0B^el>@Kwd$lm{K_rrC~@t}bI~ z(yqJ5E!$YY$_E$-X~-uFWG_0jX@_+lbCK1~mIx-NVKllHl!-&~>|F;eUqIdDeTKZ{ zS!)4TrjhA?sTx;nmo>g+PlQehX8IIT7+c}U|2Dn}ipR6teMz6!AHr|F6nxHT*e2V5&V@4Tev@b%jV4fe0RDnt*JOxjRuFskaX8e+L@$Qamn+xkE}icBQzCS&ln9bxk4 zne9F(^R_OAyTR6%1(Taa`<-HgIVm8aPT01-=4uRxR+&j^j`Zh{?>)pR!j$Ru%*OqE zT@3E7%IKHN%|oCSvrAO{sQhNc1|aUPAKFIUQH0O<`}e7rhkLl)@27-4D<6V|KRg(F06x$1#s^=Np9O}%GL@67wdiaqr86f;O}acrsv~1+10p8zwv{IN6p4X zcHqgVI;wflHkdU_&fx?PG2bbPkYyP5m~jyQIbA&*IL~BLk`o*1VJ#r|ygtqE^mzb@ zmR28Hrk4JH03Si%zNp8qIi^VQX;y?^CEm=7#8&AYtZdLZc>?DHf_HK-2M2&L?^6wI zi4OcQ!oqKemDCkdsWMMR+tT@59%*y^Pp65M9buCFPbCL6Bt6 zLUK+z=K`%ID@l3#*(-}q`!sJ2*xqQ~6N1iY;<=t3>4;9k!Hz)%vNQ7ldmPloN-?S- zwJB+zJb1rE)b!0t<4(CDypy-g!9;B54amqHKqsy~l}Nr1i!CJNtran9^GJcC-t2G& zFgYAn>S?_gIGhEm#c{YWG3Nvk!T$igSK!w#W{>s-3x;&jvGnU7pU4a51Yp&vZP1_lQM1K8C$w1{!GTfYso32*hQWk{M; zGa;N1r^}CaS;svv2ZE@tvZC27boyX->R%LJ-)Z~7( z(UvZGbiXqkZ9^A*XvaSi^|>`)#0_FmDQKXbY~ap*RE=?w_a`4xYfPI~QaaJ5_&VnD zAHi*E;utqiWiskEYVq>P8>2`;URaDjU+GclXUBfcHT_A?4oxT1O@D*O(PlYKOviN0akX4`CEg? z5Dqt$Zl#Fh1YjO(o~bqO`+L#Up4ZT{Y5qNhwK=@l%4z6K$Ri-iM?i&-%6exb*n8Fa z)VkO2`4r-s`j>AE-JMp!?(P*t(@gHsGwuq6U;sTa`kb269nCi`@9lm?GA=DBke({= zx?~Knvf+kUDiNNiIRJt{0;?=)JA%nD>eF19@|B(L|xj2?oK_t{0ww zVDsr#jFMDDpxIp4G+7}0JMk2c8U->yQ!9u0Upe|5_2_=p(dno2Bbz)bEXg$K8XLqQ zkTZfajMt%&Tv|C{r)BEY;9I|x3<6MPZ~!o=!iVFa&r#Dg!xW|2(8fM0o$rOBx+6&p zC8g-4*tbweUI4A&>$5lAkh*ommUAE|G8^S?{d%wcsg??9?7UrV8@GeC+kJCGn?#@D zBtA*sGbwK^Gs6G~Cmk?3;2QH(f8x%*cC8uaqh%$>n{_hz@&w6alxYS&T#R~P`tmD9 zI(sPMTfYtbF7j%25?$GD(vW0HC?Of}F^21c2h%+Ws=0hdS}TgO^WqN~!KG@CX3@&~ zT?v#hB}oS$gU;>-eR69lH)e{wj&$!F+AzMJ{4JK70w%*WyQFqvcvW5s@OeEd>9zS0 z#XT;|d{>IPdf%IA3~GUy3T%;vLmjGcGIuTk{{SsHE#?@~9dY`$Lo zr6F`?R0s%W$0vevGoCTVDw30wx!3S%2=R{_AYcN+Wx|6c)T8B+Me-s=Z2nhM{G?|k zyB@V)!oJe`{Y!VD$A{vQ`tC%QCf=%MJBAfb#wy{t8@DC_`c`p|C)d~Z)BTMbrDlT_ zhxn(5rMJ{%o?kdDjUip1Gb%7DJL8{ho|V-YyqKzQzwn-pSxbgXkKI`jtZG_zjcV3c zI~C2bE9I#TDaHpQp(oevP~2j;lDSFpF#R*dGiaV86H6?ULm)9+e-M_EG6*|~`TV1@!xiUyUyW$d3~3 zlVJ$scOV~7dsN4Av|Xx&F}Ab#fp@2CSF>8qlG(7tYa}EU1OAiHlxGs1E^DZC_JVbC()V@9F#(sJU5vwOQWEJAGp6+u|G)A|}R29DsAn4D*V* zPPpW1{{H}S9Vc)`KjN(sbX{KJ%HHLsyV|c4p(0RQo`cwZDtJy8uvMXM(ifGc! z5UICdz!V{}{QC00p{~5y6ju`nLAPb2@c#fvzqG!OGGAK}A>VH5e4Ci|kIG5mhaXXl zcdlPLI#Q*w!{Q$nY5G*A!uHwb0EXCdgKKp=kKgvAm;73?KDK8bC1@nKXSTWXB@O06 z8bwhWXMh0Uk{h0TWY<*Z$s}_|JZ+pTF0Urol0N}qn^+H~40_7*K;bzsi%PS=ABn3hPmvt)*NE}>hSRt*G%lpyry1y7*|f-C7EH8`n9 zrhNS1;U^h(k7v@XRBduHO;SbTF=&Bo)sT*p7s1hqA9KmMQ-CI(*=sEPHUv4Phf)XS> zg$XF$JfBC>?weVb%HHz!D7=|Ia2-^hxII85XC9;0vdEQNF9%OXN8{ahP1ST;b+WdS z%I-7e+>OA1x%o%AC-xQ0)PLe_ZT2sGp^gLPv1y|DO5;PS28W(h!dVEgm^YLbs0%O_+FtPxz?Ng}nxR>bcLqZsdw zDv6ftyJ=RdX{KJ@+iQrfBipj*46^r8pG=z3t3^r!20%z%zcFR>Vd}M+VGZ5QyfVcT z6}FV&hg|;v-i)%Lq&ETXgUo@qADaXERP;M1w0lU#q=J7XZHr~3E&RXQu*q&ZHHBWu z>z!IH4^!LWyYmF8Dl|?3bdgv9z~}t9&%SDKT6V@-Yek~NMQg26eM)0*j=BQ3L@Ho8P4v(0~REv3})HT|W@ds(fa#7^6G;Q9hO9CfZNxvlUz zVTmPvNo_Xm?cN2BrYIe2BiA)vB~;&Cie+?Q4xP{_>d z_2U&B*SIbID!I1P^h;LLF{s?!FiH2u%OoHV%btvcaaNnhDE1R}SL}>%T-)xvdkg6q zSzT_opj>`@fw*J1HHQ?ozo|A^TG~AyQ*&*uLv5%e{{SuipXQ+R4nAUXq$3V80Uo_; zrY^jdqDM-;v$OFn^_BjgX4izdhH}!BPnhoV)(};Gf04$G04w1bU(_&0|U4N99L{peX|!wdyNys@yCrf#zBi@mAW;?^UyiM6}vE-ngx7B#k2DC3WoML1#KB|-XB#Yr!jkjXx^asq${ z?LZ{}xS#{lfG7jE6aj%kL#+r362Q=a mk{U`!}Kdk_F^`Hs>p(rRoPz3;S^%Mc# zfCsezPz4FF_QePRKp#o~{?q}``%nio0n&gyK9m99wE^ZwjwofC;$(u}7}{B;kl|uQ z8D?YX0L?=O$A5}mEB^rN4;$)wt-e;pK(@0Cp;$nlDremC$K0Cc$u3OZDv<@E-Op)p z8MH6vZ&nJq$sq7C-nsH^9azz!>mCb&YninP@9nhRDHM5zBEf zXxEH2OQwe5rB{%uzvUvW=?v2J8O-sdZJmN4C;zZzPFlosshac6MSE^(aAJfQ3Gl(EYuP z^y&MR?-S}Vt&DcIF?kjd{E5!?BR@8H=OmMk#GF+lxf3T!h@B2c^FWBtjDq_J+!TSp z9RUovt4~Ub$Fp1T28|qRHmx|Y0j*?)7BiJFx()6@C*?dYIX(R`SV5y^jFVNGXAgBe z!g(elNt`hx$mc9Ze>WNZYiK3OqbU&<7Oc|5sK?EakgQko=b_0ptmSB`?7w(&3u~qc zGRY)Ovn8;lzFZBbJoMtYCr#|?$MiSf0ba?e_-ZMbGP;v)S!NDPE_(Bjaey<|t}tnZ zxkL8soQ)|TJ^mnB$#1FN#`aBU7E*k$`_%zC#(2&~4sppnhAQ}<(u!u=AoQyS5ytRE zApwH_01W)YjGd$Tk3a703!=n}P9m@IAw9-o~v;5^7CEfN9=3|m@LH5ooEPpod@AEXt zqMK@x$#c3iW=6?!4l|s9KY!Y`@XmGFp!jKi8d&9U&2eucNXVoqIKlkiVf5=*xYPQZ z#pv4Mp4-H_TyxEDi(Awo;YT3EbAWn!j-tAgSyi>C`yBM~y8CC(J}=Vdu+>gHo8sVy|e3BZSWTT=I8F zcq5YMx4IwXd{FP6SQ= z0O8h$G?x?kFB3}Hl@zxjTbv$Bf_Nu`P~qFMRMXWFS09F+ABt;%$f zFCUnnQhFR!DaGCW{q$Q>@LKHQg(PcvBaT4mo?witDyTh9?BEPz?NGGo{r>=7gWk~{ zt$rTqx`SNJ1e06J@)?+*R{6@Q$^zJ*>xU(#f z`m-FEo;fDAkDs*91ZvvHiFHk}gq}O1^Gx3&Dzgo&yz|#M9jh5h%jJo;1f8?#4G&JY z(6p;-R3qVS(Q_IX!viw~Tl%za}$(5$O4s{{T}q$4;NZI&H9L((Uagdnrq9 zSB<6lS3attRF6O_)WMUMB%8YaJRW{nR#yH00G}i`f^IHu($>#TxbozX7x75TkNp{Gp2rRCw zV{^bNNXS2+AmG)z?5|xASK3XMq8;xot!_z?cSs@0b>{<&5sc><<37~4?oB7)dEwnY z(@40MJ4cma8I#K)h(LcaQciGqBzDIY4^Hf#1#j^}B^srXxs-^FyOfDZ`95%dR?l!p zzCCD_OJqsfGg}#AI?DM_{#~Vu9FQ2}BDH;TT^Yx+&*CrfZ8KYrJCI!#IEplUa7PCn zK{cIp%^PQ38fiS#X7h*u7AJsI94{Y3kF`T4FJ`CUy+&Jk<4EU?e92=CAYi#da(4zf z$8nBE4QCls)Alry;A0-u zz9`;BMj0h=+49-b{L8{(kx`aFTY1J5_xlmecDJT;MA3XPq{)BbU0V1mn;~aA79Mj;E+4hNCiD5TwU9IsCl=9Zq{1>2Tv4FpIW1)I1$~ zX!|ZLnskwOLp8Z9n}OuFa0outm&M|{HQ--A39K({Z|^Urx4VrYw{_U-^6yi)D{+-P zaDDyjo0U68$!lfGFAeC2PuOik2b53eETvh%OoY#;d=CErO3kE~-}E$3XHON(d@tdr zlSr~*bvRh>U;e~O)VMQ zEPfYw?k{a4c;Zs>pap?qH!#5q(2xNf@rsGXGWg!lpzrUN+d{gM=@L@pN3v|;j&i31 zCnwNIAs$myQZ8)fX-v5C;IfWMH?jHH70y*p)wvnYI#)W2@7U?J*SRg> z{Wi^=?EIA9DuO0>hz%YH7%Y131mKKvdez|-_*dHh0J5@fxff`(%^OM3ZZ!v-31PNq z-{%53NhLy+>5|QW2XpURaD-sz_D}q4odmNLF{p$Y!E;Ypwxw~dJ<2`oA zS(aH6-EGW_8AZCUl&2sbzcBqe(${Z9KVj9%Ph(3&q z{{RsCMRjjxvU0J;=)3|*C(x2P>ro|IB|0vC4xdp=`)j*vC%T>&EEEE8t@*m}G7n!` z#avy*bZ)9jr292Hy&4@>YbmuD9^cB#DyxJc@!f|})Yj@QO-ZUUt0o+x%uH(^JCfz>F^GfjK+J)j< z!@5Q}&fba#ziNodHdlk}*Sr_uNi6&@EOm>RE-a^&Wbz2c3F82qXD1o@aat(4`JRQ> zOK6|h?L0T&{R>CC)HK!jbiV!?#Gf~qRFF4)M?>jWlp&5PO=&wSrzuIK$gdCFCZnOY ztsR&?d6s9lNdaK0&4namjxaOpSw%YK*|fEyBf*-w-D|#PpBu%eYCdAzTS#{_7igQ6 z$6>icA@$m)sIOoD02!Zu55w#8{{Uy1{{WD}oPH;j{C}eH>0Z&}oFo}1`qd;|9JXYf zRSS+$cBmK?sxxOR?>FIQ_;*yCE>OQhed%;UAoM>HjcWGUEMW7k+8o@t%C)?`FhS}M zKWZ+86FQEeX{Osf#r)|E3CU(W3RpAUPw^MQw>P3&u_U)Te(9~4p#k4JO8V!Y?^JV3 zR#`>8oivXc=~HSEUtVaj+T4(Qxue52-h`2ij=!hUrAa*|99f}S+(mT)O$34BZiIHL zl{*2NtC1-j?hCEFrX^;OAu1QCIO7ydG-JLZ@QmIfNHo}*;pCms=AKXf%VQ*Q*bdz@ zgURU=T!eH}t^WWAJVJa$1(eNh_C$$Z?76{A^1u7AI(yb@7naRAu8l*)qfXPV?eyzQ zWU{c+K?ZQ4oi_~OPhdKeS1EfjZy0!z?^3>4bql|b(`}`1C@}oWc;NT%`qwr`x;BJZ zo*6b#%W-dUb?|XrMB)~4xdZn8)ticL%kpTFYp8W?Ba#4-sgSP1enZgxDUSD|XG)3B3u$*pMT1eb)D`5HD#_%Q2&>qW zz&@3RY`-@e=-U=Lk1uj|_Vx5n565{NUUj2pCBDcKg55%n*e5^IvV@$aQ8k*SY^*+^ zHiNbcN#>H$@OkqRgl}QcXSntCtt*o6*yfWR+s68|5yv9E<=ZRE)RX{ogX(DsHPa~4 z@T?OLTND{RZ5{+)Lf^_(+FZEH2dOMql!xqUd#^{A$u z5?C*F8?8Ac)7<$IWD^`Kvv?yTEINw9b(ie#mSYnj14534&Iobz9$l&u@ zl}9VBPFA?{Z3OLhp?+Z7mE$~ooMRn*`qk80s}^~**4o!oRn#IV(B)F%DSVbdz>YZ^ zm#zn|TGA@fR&9TST7CSwU6uK{jOgklmI5LIMvNf&KpXM2XB|&rS)`J(>6e7mZhSGR=$;w35t-p=jpHB^mYPGBT$~IbWf<&p=~SF= zqRII#mtHRL(U$W~)FdpD39N3MM$Fg*1jLKR+>OVQ0OVFpH0Zsq%T}SP*!VxdmPbIb zi~cqjip?bDVpiKDv+g^YPgTjtBpxwTl&UxGUNLf({22bZ8^;9i1otOIbG^gn=36Eh zVIh2fE2@LQY!lQPV3OtSe}AED%S9G8Yi&?Va+?j(3!}BZU!Uh(A3>g;)zz9U#O8yu zNbpC9?zFkr%2hB)AW4!C5V*(+H+JOU6Vo-pZaYUx*>e1Aw$$51v%Hqm$@AnxexbMd zW+K4|#~mix$D#Rst47^hRQ~?}$rXBD42My$cVtk*AObe@1e~bk_v`vn>6NQ2z5wuT z_O*2scCf#cfH|H)^2S3Ew0q}*J*u;mrs_SHf=O~_+S)~qm#3zK0w9J@IT)}T%yLE& zNeICs=WWFF9QxFCQG5RYqE`NIzRVNE`W%*;liD)wkssk#`Ep}jp~8;L26NMqQl#uo zK1c?I?Z^s{`GA&CPImFfu>1Sf`5Ez{&9Bx4E*aLnB|e54jVh!xKojPF!#{%BC!@w3BeYpL4aTie@1 zYjV!4OYOgjhgCLjLJ5Zf+svIXXa-ljDk7_9kbgN zTwgon{{6)63yM1UqsEs|YO&hs^P*Uds}zXa#NfL8+ej)v+Ia3Vd(~x@N=ZTM`PwfW zaj%(d&OB5jzgd0>)uxTpfDlN+P7TGW!r?YL%8Llxkh_a2|q6;~eH9LvYy$B6#`!*!_Uy_xWQdI{CPCo<3@$!zX=^nQG(}5w~A@+no~TlE)f7#2yl1{fyOx}KDDM;w$qQB zBNUQVJy65KzlL&K5q;tU)^gjpc%y<)SdiO;FV@Hi4UYc+7%xOo z$E755HQm&a-Zz#us;cl+f#I@OIQo-X=aoA0%Hme9$3_9DGbD`hjpJ|Sell~63?4tV zQZ;)kD?{H1_^wSSR)+Ae@$IBCg)CRh`AUVz&jTRy=~_5(e3ry#s%4aTlTo`{2<6m= zmlL%3mp?p=H*?Nk@~G#IwaVdYucLK6*#7{DU+-|QTcclr>C;=71+{Z`H;0W}#!momzCPaq$aLG6yGia7kPKK}sb!pXG# zjWfWWHiG78Q^Xpl{{Wott|NvdSTM0D0|b%5+;BZ<7r&YBM7_u5Ltn-#>)k(6w%>5_ zY4}9&Qj<0nI z<$~^TE#*Xs;fv*uo=6$s;QI5$b2ll!ndsGVk4UI^jzi*a0^aBo?UPZ`W^3&_UD-It z@gW|}K5jpm2d#E`ERPre06BDXdYF7qop=5W+rqcf#pT4YDGu3Fz{$os=dE@6h$eGm zm42tu-Vtf;zYk)tyz)e|TA0zLZm8KPTO8w&p7p?$CXSohW=-N-JBvx@^AIiEEw(~{ zkVmgQvB*8@VW+YtjvfHKX7Mhc1ahQPNhgylV<4f<;5~YbXTLSHqoX*>W8W6|zUEI5 z-os;d=$>(nRxHQ3AuG7!x%KZ*;r{?4T;D~L@W|@M=6joqhZZRlNiO!^=I5p{>5fMg zlZ%e}Mv;}4pTrFfu5<|Gi_Dr!HTiJBp+HnI$?JedG54rylJZ*Y$I{s&)@Io}1R`w@ z8>@rN6qjc4tD%O8 z;Yp>v5W{XGxiOMNiGaILt~dan_tK#^C&$TVqZNJ)GfnV>HmwYkT=}~Su~P!!y+>bs zXRUOsKJ3C--BMqGNUL6NIOOVBex#aylT#AT@1A?RxLhs7ZAPM3;yn03Cv72_9blT4V-Zqdr73#PE`huded+gHa%&Mc{4V2d! z*NUK?Smd~Z+I{y0&nuspZt0vc9FNkuqw~!-*9o2_~tsl^=sHw4W8(x+6^$yteOkEJF&e%-92WP%(`5tmK?! zOXyxHJ(@u9wwYRP6@lSsA?Y`e^?N@NqXpHg~f=~~MiakneA{z@#e$rT!> ze}B-&{7G~EAFo{an?$>cZ8A%wJ8kltU$A62$2lPM>sjHOjQ%7Ud9G38BUiDyivGsl z@(v@N1A*5Excd-m>R~lFsV^ta&JP^iAAws2t0zUGj{uB}{*_xV#Ow`fnT&>a_m)ux zg6ifNnZd%y+jCM@(U#m=YF-XYtGz25dxr%pbors$Lmy0m!nJY zh5RsTQAen15wW*r+Rln{4`O-bbo5cIjZTJldZhocGjBGXTve?!RkAM+O3LllC)bSWf#TvaJ|)UHC_hn(kl#dWQF#(aijQ1X!B{4N$~r;o7j%T+~jgc^KtsEfA$; zZ&TAl=o9LTa=vxDtX@b$M2g*Tdt<-WrxI07m6Gy^=;6LLQQX01ZQJJ{(jNs8Jl3I?nq9}sW${A#ZBl)>GXRMYf z)wElZ@N$RDd^64P%6Lq-%tz9wm(*GA=SsV|xEFEU`QBMl>l~PnFJb}U{WDrFngVM! z*D}hDYw-e50eBg(Jv08Ip(M1>BCKJ#ww4$k(Hcc1*tlm&Vmy+>9snS6Ij)KEy_HC_ zXj)7c(p!%)E}~#Tww)d0hjHQ5sSFpsF`uC|lG~-(FGi0Jk>U>t=-QpduZH|O+F5}_ zazz-pkT5Hj5})Gb!8lgP0P%|IYIx&xQGCvkrs12Lgq5WDaJ~W573^Y+*X!U^|^PVZe8!4s!uJB zxE<&~0uJB^Bpe(Z;QCa7XibPH1)vguS^(`p6ahdK0YD$E0DjZ~KrdrJAH4uj2U-Cr z1)%{z9q0gbpb8QcAUeCECv*N8sQo7W&8_Uc2n&R^AMwV$`tH{SJ$M0N?+qQHqX%`Q} zZ$4|=iBeRG(@nIJ<@fTe!}90q#D0Rgvgqo@v_xGgp6E#Jxyv+eIj^SjIF5x}TMNmB#InSu5PS~m`DRnH`tk-uA^GoI#T1V>4NhIgglUk*u zRlOdx^?Qr8alP>rnJ8gUU;+cn?tvjcvAWnSz?)`EF?uN6gj~v zcHm>!X1L^>vC=vs)Mc_uNc<$f{{Rln)b?%hQ99gNpFxw2{*qineK=h+5Lxc!C`Y7$i%X)nbU2P>gOP z@`AQ<0;|UfJoE;&o8J_^>-{3JUoS7ceX)ez9MJq(X=A8HzXLVZw0q;gz@6I?DI{=H zVNg8>twiFa^vfwY_OJXAJ~Q!p==KLe@Z3;9@ty50sS5VeZY86_=Q$b9PDeFaJ#j*- z=4CfR@qOGLAhgsc)F!!Dhmu698_a@0%Oc~rJ&&-e*A1fFxoPxjo;A`S@h^u(^_Rg3 zEttq|E+X9FBaEm+CUMY?I%R!oTe$K>#Z%(U)?W{#T5R&Xk!3f>8M3$z#SR8`s-8LZ z=~*nMj~9w7T8@cv2BErWQs&v%s>nH3+QTGtKdoxACAMVowbCT?J6SF6Avc<9GNPX_ zN?QaHGUTsp9-TVY6G?bAf@t~*T{6qXdM}6OzQxZYAFd$*}*50R-8Ox;%MOnGjLQF+%wp01#{?4Z5oOz zc68OW*=LGL{vCtDF*yK$8;-}I+*tmCrtGBSXp6D4Ve{ZJeozAbVf@8Me@bcWszv_* z!`>LVy}I%=*tgwA36M#&Bul{#bH^NU?O923bso)CM{L?IwF?gmcz)6=`+^lM9|4#b{9rJn@gfDV05PhcxAnLU@1O=!<=?EV>@_qd#rSTV;v zD`-!ZCSxej??$3#B}+MOUA0gk!|pl%(}gk*~Pjb8=kamLZeR2~@|Z5RWu&5TvEN0unb6N*)mP(FLql4iRw z#N|%x;IJbqa(Vv#wUl+)XLd~9X&QpbZ>d^skuFGhq+F;ijm9yacMKi?#ZA-XiQ?Hu z)Ggw&)>7gyB7#>8RC9-6$j4xLIP67s$1lW%R@d-yN*rZo63$8{W?agXno_o6}4R7d9b7wvH5f3{%BsA2l>!04guqn-l9$2qROh7 zgH1R1eys}W&I_c9Oq+3mp5wUhpGxV9O0T_nmT@niB!_PG1Sljndf3;ZX|9 z42|vu}ayxeiQso`@1mh zC90q+9LtdwTRT(?@z;;qvd4Vd@NYWfeoZ&-TwfS zou}+W>YgimaNi3Ej#%Fe?7_DV)8Jb~38BBVp$Q z=yUqj{WO(veU$YPcgb`=@lAl1+Dnv(Gi?GuI_D!8{{VffOwdhoqdYUOm9yus#!nAw zH$Dl~wJn>iY?VoE#I6j=r<2Bc=qkREKZ==uR@VlPoE8FHgPt%+^v!y%N1sU3KMe%2 zMI>o*_U_xnQ$*aa83WT9>O1DSax0O%UX0@I-J+gRoPhiiHs?L@T`8(DA8B_?B?{pQ zURRDmJup7CmRPE^YX`Gz@V=xc($dO3vn;S(EW2Uy_Q=3(U;z2KZgI{#aa>V48#4>- zHhY_x{ta1}E<(kUF`hul?N)@;bjafT8jplUzlAJJ`n2&S+=!wpNaQaeUBQWE9Cg6S z!3265=a!YTSh`ebTdlRNG!}jDBn~4ERb^1XgU4gQ>F7T0*VMJqT)dw}@WrLIv49DT zY<$MV&RnYH3op&Jk05je8d9P;Y?JUuizB8thWDE_%IQ8jO#SRd2Yj5xRla_qsqMnfgpNMuzs^y}bSg{^lgOaL2 z&&Wmh$88BWsb4gq3)M>(tGlbW`K;-dRA ztwY5co}*`f6~oAulR1>Y03Z(IJz03oV;MY=Y4pt;R9=?Qwq7pOV$zb%DM~>b#);*p zK3HPMpKx$}1z!GMKXgX9a%IzA)bC{QmYIIHA|X3}#Q7&~Lxwm`INQ@5c=xR(%212G z`~Lt%B9fa#CWGQz#DTwxvqV$nj$DwS^yjvE)=`^^G;vZanoZ5?iKNvaHnGVd3ZUa~ zDh}XJY>(|%#^v1AB9l?-F4+sHT+FWQtkNhYLq2c@f0T5rB--C*=^`M>Jc$al4z7bG z)?(rdGh5~kDWhp_M$hrB%=-BxJixGZIeyBN*} z2nqq`2cbVotHTIuBP|?`PyYa#EqC`?RoB0 zC-gIqD8)`6U)ZnslShL@xm&>_lRujpMdaWp2O|eKVxo> z-R82@?XJ*0uB8Ju#!Lf(M}D~nn!lpjlJO*G>posGU8Y(5L2lE28C}?!3&^atg}}~0 zm=C5l{?*Yn{{Z;4=da)V9P$4E{iOUo{>BBXX%hbc^-Q)AIb%8oV#~M(1eGiYY>MTA z;&n@Ao8gCF@R=h*e}QuHOjD*W| z>7KnY&0)oxDIz<>x<;Q4m|SWXQr#?hb(*?oWZ8E7HPm&8FALj%9oPwr zNH&lT4oUj|07~h`=^05H_13&Zr6RYMZJbLY3?jFtO<|eSI&j9-oo;pLEHr8FZpe*c zUCyp~$M-(ft_EYDOr~A_Ea{forR+Zu1h(c6HquD`V9(tSJN;{+x<@ir%=g8bUhY6wL{@Wr{P<1{iOl?ewe`ZbttA3XYbRUKG}Ktr+Rf(Oq0czT}p|hXa;j+nzB^ zKFH{k{9JX?w3{TihSq$@AxZG2RmUS3@0yvVS|TmkM)5|AueHvbt80-P$Zug^E>ghZ zM*)7{-m+<$#jcL_T3wua75ug`M)Rxec-`<+GMo(kfA3sUl)2M8BBRALcZ*XNJ{{8G z)NK~k;FB@WALlB1pXpiCl$%A{N+}U$`93CZHSQ-uHze7?VyA!)Z>=0_Z02$x^#!@q zb#LNNG}lZJ2_%zuJ%;b5E3+NAnDkD|tlrpb(2aY}xxTlL%2&By!4!@^_kC)U#`x4t zp_6vW8_iX&t!K5fvx5F9(M-}q@~{E2208}o&syeDlJ892&3GSpk5GMCz8>Nxf)$Mo zy}Z+B2zU+01o76oG0CXYFv#uL*GkZIeKS&l^^1m*#&tX1Ikrg~4^xAXf7z|z?d-|6 zF2AODT77yr{249E+A@hGymw>dWM^nS&j;SLmlVwRhgr5dee8#Gl=!I^3UF{p zC#b5pUdd9TbK+mZ+O5`|sEd747a5jl$zV|MO8)?qjNppq$%$Q~YxPHR9mTBEKX_Fd79_HHO-^*Wza*~`TPHT9+Mh#KZ!`HU9TAR-` zsk@hM6+q!z)~6(7;*dkhGdkX0+%a2^%!&SAwPExp>O?NA8rVimiSu$*xIb#>_$?LW zO=!BNn``qKB%a{Le=sVlaqFIIKZMh=c_PYTH;)jMQ7QTJ|~V7nW1%3vjx_Xx8@|R$F^pLp+h~UBu#wYaofO)gm)C~m_N8w^)=G0L_Ny<+`bRH>r> z0144<)Aeh6{Yvh_6_svnp;_Hne-sP?L)i& z0QP%UIVGwzg7RSP11X4bOMt^3=CE#!V;g4E;I9f@w}CF9S4%1NNm2LCb_Rht13mI{ z#~np*WS=9y98Wg>2!u?(6Rv5ohm&e-ecQ+LVD`o<56zl!I{qoaIMRGSWn*n3>F`9* z#vschPVQT1^=yArTElc!OGaAOt!H$w&O=GhnuntO>!wdeU6&sSMP+e&5=&0;9X>8vVZJ$x!`F;-YR?Qf#u!1&<*>1N^cb422<;W~gsmG;KPvOSn z_x%kc9&)Gq6+a06B5Lv8G*ezZ;PYN)7cZ1#AoL+iE(jO{j=T!z$Dbr$cD}!MYd=qp zYO22@C-DZAeQn||5bA=$;yW9SM(#L4D<;d3-fqG=9LB|lcwllmSA6bKOyx?X<7Th; zJ!-J&Q{8-ALK$D-o)w749B;eK^9dw|Uzh=mW1nim30=4J`Wi{}tLkT-I=H@ zA1_ccg>Z~^d7v*(^5hNNjvFL!D>$bA02hDU)^xh)XQ6na<4c-J(`3#VNp}>j<_VZQ z#ffYXcwx>vo<&+q%Iu}yi$CI?hPN_WYPxLb-yEqC5$#YVRNjm_a_V|#JCxM5bkPdh zre->H9$msM)J8N=$jpjH(UaFB)bsVIa!*Vo&!PVS3M?dt!WP2%34$`b(!Ji%5s8;O zfzQmRXeT`}?^MMe_5KYqI-+vlRq(8^%_NfOsfLa#gS>6Q#xaa>+astHQiDzF#ggNZ zYS_g*8{w^0=4~qP61jIK-uEhuK-x@r`9=Xeb;Ux2W%wWO{Rw$ypUl4h05SEqg#0I@ zc?ofG65c?GF*4qrtf~R|l<~2)l6w+F-=Ie7@Kci2=et0^#8!T|z$635TH20!wpnzo5X*5Lw$@V7 zS^*v~$|W-LPqy6Rw3gzTDN%U3&?7o9hHbH#rpRNG!Cwv6`H0@#cm!0%I@wt?ioTiP z>-W`UuuDy>GG18;Sd~HHivh==$9i#g;*ncPS+HrbX+9Lut;OW1o?#KR%!C=F0FqDr zAZH&>deQL3ADF7=mRc*{j47#HXqK0Dw{aaDENoB!WfL}b6P|EYh6lZ6>J-{iPvtbi z;;mNCpEV6eI~&094WM*qExsQ&=*y_Qd!qeA>v(Wbf6ZS@;?$%@3ha>g5wi~^SW2J7qvGezo4 z!8oM93-kB<7+;7i;l&PC-4fRmUn5jghvxb=SjQXUqj*^2t=-62NkL zE(h*wXk=SvTo}mdmklhEI0qnxW?nEz8O2Y=L~v(wqqV)!07mGFp+b!3JoWy*n5xez z>dP!_zjy<|+ODaqDrr-!DQs3rF5WY>aC5+6$;iMS-j&MV#Fa$pidfev8}_N7S$Kxd zJ55QXl0+`i%%m&E?6}|Z`~AJEZVM;NC%?bg&zr|`iZBD=ORWp>6He0g05d_%z6i4= z$=ZCgygIllNcO?cx7xCUlx4z8*?&^)Mf}lvHZ-uE{{RIN*5w#nTEJsvI3=1nF@x=q z`d0gXpKGu3XV<9w{{X>R+4MJzWOEuf5Z<7;>t^_0wfNmMI#3djP1`(!}Y6Ul}RVj z8DYvTuLVo++r`?Az2&nhmTOsNQ8Y1}7RfjSo=zBo58AskLxX7I$19_1@vX~gejC(o z7t37#0K(7bNYSy}HiD%AB;??Ff;kn7)4%F$x1;B%H1PVi<{_Rba9s1TwPiF6ZG6u`= z=!^SUVV>ODHM7ju3_d|2auy&nlZD4Tcl4~>WZFsi{Vck1+oMm?^y?o8=@&Cw`SL^N zdG1+;^MI>d`8c%P`0!5;-6fpQl{ZubWAZiywtGDPw4(N#u@f63kcU zz!=Jd^~O8Y!c_Y!D5kco*e!4^)6H$^f%AdafywvpUX*IKd9uD*F|Ykhc#S0dGuAZg zLATB^2^ixnt1=!jz~p`D4A+%LJrgW0INYV#@g?f01#*8zzv4S_5CVbQC?PRe}$42y`LsRtq%5` z56v5708V(r1B`VWYbQyYFTz3oCrbYS<1QnH83S98Oebj)5(sh!LxGHQR*iW@W>-8h zt*l#{bBT(k#V%DhbCO%Ga0eds88Oi?l^WN8yi@S5%jT`Yc{fQJ8xg=ecW0iN0|yymNpOpirl?o$5%4>Wsg_^$O`Qa~*1R39(pCQ>j$ z{KJ(ej2>$)3a$7wO|Fa0*NqW;OKLRG&!xp~u^6FI5;TlD^Uf3;5Irig%Tl${G=@7| zUu~BiZ^O{)8f?mKmP^D^uqqL>Fys<_GmognZ7h1%W=kgf(N&M|-teO{IwX#wPcP0b z^A1SIa(W)sRf}@y|wIM+^f8}Y~@MLeQ-v4dzy(xv85%jo#bvM zLr#`eo+MZVC!<2YHqtpKrzwtm)hy8>adqqHBobWDIgPOHBpddUPb=yE@lno8Y@P}9 zIbCfGk-V%{J>+xO9-iD)o=V#a7ouk8#4-FL{63!vVsW}<$mzy0(;RoB%&SPM#P4i} zv%bB%XwqR9nY;LGh$A3_)G+DSy<^UAPqSqhqd|(^`Ykn&4SZ1l0MC>D|_$p<7=o-=3EItXI97!yP}-%GI#>Gaza|_Bpxzx{p+{?0AWWgll#>i@x^de_q#>+#JXIbB=F6& zT6M>tBy+_wJcDPN6cr~uM&bUIY_a&*s~f$i_xYJ(m%+(%)}PdrwbQ@)f5V1Ldr>|7 zcFdwU*eGTso(bvKueEK%;bP>K%8aF#-f>( zQS5@y?qiz&09o>mP|7z9Z2{1j+XK+?_XfRB{9NA|$LetZ0OVu1NOLQadiSo`?Bs@o zgCCiWP4Wt-h48%cj~#=OM{Jxh>PV z@6IY7$6X&k{v@`sHmL>9vfEQo2g;1$6%|P11Fi|`eGPMD`WnFJrTBbYYnB$ax}0cP zqU9(T|CxULYIPY~EpYYqeS&%Kna6)2aAYqpJRUQg zS1w0v?Z%Z4Y_wemQx=yK+_lZbO}66N_Cxb>GnFS98S7mbRYd0X4&_9qp`_SZ-e}g> zI&G|0kzNS6P#wWi0ps&^>MM7&&TfdED@L=_EVW%Q-`XYRl;v$rzyRzZ6&t(b7~?%F zH;r~^vOgssQ1I>DuDrKbHqbqc*exZY;W;@Z=dT^{*R@xRvdT(`e;!%smb&$&zKg0& zJ)X?sX$$#HpL53*S+$vgRnc#?g$E+~l4Q%?9n^J2v8!A3&;77bMIG{OA$>D^m&E9hxHYXKP${C*)7){F`p_*U}v1&-y^TiY-aiGUGE+5CX#lffKk-n7Gy=C)Q+(S7_v&@`*B2|*T_r^Dvj z%8t;&z_Q?Sr1$jt6J6X>XESWeylrV|;k`)?izS({zqd(k;&u~AaxltARmN~L>0Fs& z`Doq_(A&dzHrMtIr^RM&B8Yz!yY2G&jE3!x?OYR!i`qJ(`6?KAlGU>^G9=oE25C4I$}gX zHi6SQBi6Xm-6LltUt;k6o{8cpblqpd`W=>}(VL4qxNccd6CrnH*sPfJIL2$WCbZ06 z%2$tkQDdv>cax=+)S6YXb+fs(gvSzGt_m^EK_8eA#&|siCG-fY*y`UMcX2Jm@yBs- zJ6%mFjBb(JB*s9-2c`!YL0HY`^$hz`A~~q8|`Vsm(lzhkHw@8POxh%p5{Dlg?F_KK0d$6mr9Cq^8piC44ui z_MPs%XTt`sonTaL#S5so@(=sU83tLl>9+AXYdv=O>0`D}rf zGKGTd0O3PtoOL5L&hj;<(RwAk9j9BzB8__F>2o|yvg2xn-c*SACm)z{Pd{pyB`I&9 z`Xsa`)O5{y%Tm@Bdl4m~ELSS-kjlk|42*=a3OfOjk-+O)^wTLSXw_`==x!y9-hLu# z7xLT8rQ(L_*4YHO!1+d4djfgtYq@;gvz@ZhXJ)o*A}sgQ?`_4eE}C`+7~r0R*l}8- z4*XPsde8|#7@!a7Kn8#)0)Sq^fJy;q1G(maC)s_fQ{MR=M zGqB@7FFgMMTI9r z(<0YxWLS$lS5d?jC5(*xxrc7vq&5Y0V#xR;*NXn@`8l#;T-=l2-Ii?uf5ATtu3?zj z>J4$_rH2%>vL;z!X(Dt1OQ0xZM3L~wPg7~3yf}3pab&y z9My74GEs2+C9y%q)VncjyU!*sCMY6`OLgW#!GS_KP{07(gMdK5`c(Wq2ReE=OX3OP zmSv7*h|Wtn-M4CBCnQw72AOK8(?=P)n7(%`d&(|-GlG5it?DW0#@kyYejpfUl@7*K zeX?Zm*vJRyf2pgtqKL@+XX0D!QsHL4D+EAe$%;m3w-{Jj-C$j zeYK<$=~|_{cX~z14Kh!X%g4-Af1fxYo&X&xu=zCA#r^*PQqSkwbkUvo_Q`Fp55uIA zhYHb5CRe~b;E~@QM_l#vt?<(PMtN53j?g8!wz-bx+2*#oNfnZ4nC=gsl#Enme#Aqw z>p>s?08scu!17!)ceWV#sUtBv7F-fjs2N=QgI3(3UF))c4DajFQ(wZRj_m&c`ND67 z^LDea21U13&UWMGZRZ|L3CcmS1{mx8T9AhX;Z*}>lM{P4%w($pq^{LV#w)X9H1mY98wj(4r z{^Q3UwRmM&G0Ig*U-8+T;PGUNPj0`SkDl+Nir(gUuq0HGq9l*Z89^*as)r~xc^G9)A6P!QX)U(h zMPk{wNZXl8FeN|$`s9wi`L8X@-0n-*iMi4AO-wE1b~=1Btohv=fRecc6+3w7LHdfc zT6^e;HjH2K8%e#e)~;ukHuC4d!6?LS1vyd3;11n|b>nTMj%=D`Q%$&)m`CRMfPA@8 z$;Th2IQ=TwVzxwH&GYcHOuAcnFE0G%wUA;4G6Nr%mSW+0uRQk8HNd0uZ0t^z8drw3 zOKYo}xM7wXgBz@Jh5WI$G6vzs2t7w}){vIilyziBiHC_}TctXjk?F`tNn?yhAC^HM zH*zt-?0&ecrt&V{jiRx>mj3{9tzn?PrE<~E+oao+OsNT;-M4h(Jo0KHxjGL@&i7U- znvcUofi@5WAjS_)q;tpHy-V(b>e+Mf^@X+D!*Ot^M7RwisV6zkeT``prM71|G^rX^ zn-R3K^5SzaKw2_JGCJVmyYZ(8>t~&n^Oe0AC;p)Q7spn`Tk<-?zDQK09iH6wQ>hK7I0L&DHE6{HrD>e(5oC07ali}4YbEqFXw4P} zTf$*?EC^ho&f)9FTD9Jc%~$Zk_G>+AD|eS{b7ffu+{n8L1OhtpI6Zq-YE4NiHmi#w zd}{^1rQ%nP$)aRch8wnpaU63fDo1WeAd}eV(xXd3#j>|?r>&zP_(>#55cLBrazG;- zalsr^+9Qn??+V*NbqaZaZ;i~8s@#mW?1g0r2@DF6&vGjasXf2s-x2g?g)Dj|onU8l z-6OP(frO1zZhQbvFr)5Ct?@sCqxt>*#yMBTa$d{t_c0#}*#z*%f~31&_|01GeMO}Y z^XF?YByo|s)bZ_8JbyO(Z}`$CGgRxs{&rVC5w&L5JY{gP3x$dX@(~$H>G_X-{eN1{ zO5_%i<5t$Cn#R{b(}E?An#|7JGfgS#W6`{tr*w7eIJ-IpH(crRABzO$Q9w}?d( zZ!2(jtE&QV6?=2o^&F1Xi-T=zUtWz=lI@z0igg#$^y^q`Oz=*{W{uE%s*Ay1z0NrF zHMUuCN-JJ}r{DA`iaeWgrn)M#_{UJauxMUbl5MJ45EN{$U`I@!^sL@lNmZJBD8<<~ zpk5toL%q{(9%Q=-^GfZKz?=dbqaW#7Lgg0+*__ghl+h7qrrT-$CYIX#87Bd_(W(oo3bBU^KaD3W@vhi_#ZqG*!i&fH6N1B`A1--GSeuPkak?9F6y>qTQt zw}M?+Bf`vp+A21)ueFA{MBYt&lPdKmfNdQJ+sGeF@cy7y;L_C=K%Xx zRH4aIbaAP)?n=rH$Kl>DW10!!mIx${Xv>eCm=TfaI%c_Frjmav){dp>V%N;Kvbp08 z7U%x}%5~!+I>UV+mLMPVk};lr!S)i86Xb%z^=bhnpj|~zwmP4#SGGS*ZDo`*B))%(Sqh?I&YV$h$4I}xs8xQ{Boxu zuseZUPH9S2x~5|YzA?WxzuBBr|$m% zeVvLCSNSj4vi=}=vRxz{F5W4B;%%kba9e95jw5gX01!Pp3fDGAd>3DIVT&EEeoW)= zu6d-k)*9whBbQbTTk{rnEI{qedLQ`xDKnqe?}=|_89l{!Gm#GMQzo^9Os6jcQ$Z>iZH^Urytg;^ozw_iG4ptZPGZ|^OX6v z;AbYdUQ3l8g2z!9c%tpDnpo^K7rnVJ@b2-bO{0Pvc0Ok5#dhQ9;LF*ac%xPE4w$-K zmZ=2qXK5*x2_z@X*`83I}@U7 z;6?yu&r;r}iq35sLM(;7wuUQc1PIM>x6Cb`quf?pk#wExd!^}f{{V-_shO4u8et4d z{lV&as!mBGNR~}n>dx20aB1;QXS{QTW%*VxKi8#kK{qS#Zv^#& zFv7%R++Uuc_O9+o{*8;P0SE5$R!IBs*rjFj` zXs%asNVBLUocF4>>d8`}#0l`4d>31xGC;&KpP5Mddh=D~;ReOg?(Z2Dp|`{(i9!z0 zPhYpzjn;@QmKt`s1;6;{mhM<(%x>24`H}|4N|*ElxUJy{Ridq;uXp2ZZ&sZxAd(v! zc)mzNE)f9Fe^Zl_?^|2!&Fr!0ABtD{MxS$Sb8TmFIDw&pZgz~GPBG4X>i+;4rA2rm zpp#t5@mh%ZR+d*2?h3iw4o?{Ej-KYTa_!F=%8Np6IK#1KVQ#@&JZOQIVfWtQXPF_VGv=hCC*MYLJ0^tkl4 zOQtUbz?mU|u9Zu{v|A?bPU|8 zBu;`!bF>U?80Ci**19tyHMkPnOumOmxzu#)IIa|2*j+Ofw`brDr-H|6`Nt#=N~N{g zbIygQ#dqKhjV!+#au3{ zZKsW%ZOYmC(J7GPJQX>^HgEvVQNcB3tl9Mc0K@zJHp<1JZ5Hn4-g6|--`g3)yo?y+ zz+@nQD|fDpI4u;MsI#VlVSROREV^yZmvFLw8aSj4Z#g506FE|SzyuO=>s_h~$}n3jOQH*C3!yPuSlrx^!rqRpaF^i?LY^u0Ke~=0PoOH1ppcV z??4m*`cwd^0Z;`L06nMzqz6g>&nBP=-hf`z0(PJmr2uxI4)p*(dI0)R1ps>DfS`Un z>Ss*+E7cJhmVHKOY$My(1-!@mZI2)Pss6xc>G9EKo!=Op(v$mMM8f}$f!5_#uwEO^dF2tB`Q$1_H; z?6_!p6t}_WxN~Qv#2MwhWcgG9(SOW+s|6d`r$yVr*LHf}#_3vZp@T1Q>wN%qA2X*;otPF=?B10MPZX{F{{WKp z@f9;c@zs`}sQ6REJ}dCz&2MX`$K=iMu0vbI_;{QTM3DlK>V2!FMlTy{wDw}$l=#oi z*Y`PiT1$<8!@91YVRvuwSArXxNNxz*G8WqLgMt*SzF!Blh&$DyoZ!-Xe}9pb+Jw`6 z8Ah|Z>M5FXOpr;nqEq~vu)z8d+-KjtQZH7^OpLL&iS5vc=H0pDlOz6OmB7coHv{w@ zm8zFb8PT-<5oz*iI(_D%UDo8 z>7pj!5RVJ62m_ClCU_w*Gv76YE+LNT14lWwK+*x{uu$1d z9#`f9x)xZr<9|=g##p4O*Vpp=%I}P|tBYH!%Ovw-QxXXs26yix<_ER{(jRfr+VZ^Lq$Q>SY~8F zC}0lagaA%>&vE|%YL!JvY1&Oj&7m>Ec1DfOk!h!q(rXRGHLXRi9ggqgu??0S1pK|dDqJMU=DZUcPvQo>Bg7X}kde7nrB!juZq5kC?!Pyt z0IcP4@?J7e!Mc7JYZB`^CDTuG_lXay18v>l&8{v7Ihrm`CD{_+NeCX_D4!`v}q z14uFaH2`EN=bW0`)ADk+EpPL0>+FpELV}GY{;S*FvbXpkuLXyWqmu9jOV&?`Q@Ktf ze7N-)=iiFAr&SqmdjA0aiu#vxj=t>}Zliu$S>{OzMjl~1ak%Xpu->PxJ7&4yu8m~f zvQxvtRd$$dauI;qHwI7$KQDGYeQJ6_8!lJ+jmL(30j}yR3PW){y6HCY%6!H%$k=~x zmLTn)*R^fvp!vBqTCdc{*3O`p-`$@-UTLDn>2BkVqq3dwi}`|clDX@^>Fr*mpCoy) zbU)U7T|TF29kPW;;Vekb)pjTIW79l=&IvxXm;Smo_^g-wF7X+()}ge!kI%N1(jmRJ zqLyF@^!EByGh$KMcx1apzwuv4xu4-RKQOfLBS9c5$ir?2c5>X6!1O(9JZ-Hq(^gb` z8R4hZJVWpZ(!+9CxGabGcv9FS{;jz5;H`Do`Dyo>4GE{^c*sAyZz+>xK<4fj~`|@ix z{#1+JgR5C;S~N4=+*_n>%%T}cIpwewEncmI_ z#L=rpt~n^&=dN&h9`&NeqS}vTUP(&16x|}u8;=m%hl9*9hTQ1H6ig7q8S9hZpGxP( zu4z|B^K}a@ejc}u!Z|$o0gRF}AjSrGB=pWZd)HPdsI9Y`B%Hb?S5~%$*3Rizyi>{| zLY>%yfse7RJ|c=z_cD0gn~$<6{{W75;OLeLu%k!*DdvVF^0$#7rdt99B0OhpBj0(^sVeY- zPC9aW`qxxtOu|T}uK3-y?j-O>sIHr|Qi~6VCNbSY>;k&DeD~ZtFgXMo=E`XYvwqX> zzAHl#MvEca88JwLPdPJzy#d0UoM#;eBDn17qOGI&F6U9ayfZ-+jDVRuwvd(OfMvq` z+zg+3jopex{^4vq9jDsF*qS@JuVu|Jdm0r$l}0w(z!XNuRv7IMV}%1LkW zO4ki;6pW_<_V7mH2e&z>e=^s<+a~C)c$32ymN0_wA=5nV{%FcG=L0RbBmt766-n}k zYel0{(qxx|v>TZ9J7^+w2`NU7P@+$e=l)xa5DN7KcEQ1{_a>4xPl|GW3Gc@}e(y{0 z=A-bYcw&!E!bra==3ue&w~)hg0h|sirYoL!!@{GP{J3Q=B|BQzA%^F{dST%#v~)ot zXXR;vsKVoh8wG15=^4gbe^KU_q-nD2@+H)U9ZELKFq9uTnHv&-eeiHQk?C1dOwlpl zhddQ)pz2ZT8qM{yqBdeuN^Z#`a}su(9&z5WQRBHACcG9w$zijNt{OOYqk*zE zmp%E9+by~$Tn_qy{*oA=g{J`f>|TJ%FVn|wb$}g zwT(7ZxM*Z_62$vh78@7=xPMXitYyhMeVfLbv^cWTuAzH->w9?~-5U}jfCvD9z>cJI zo;l*CpW;hIHopUVEq1z1ytL(*~ZRb7bVVBgM~%t*mt+X)J6&I|Hb|=t=tm zF^{c7<#3k0VQNMk+ZddGy?<+3krBq5ne3K^S>XPjdL?OC?6VC4Hn(s=XI>Hh#? zE5iON)b3}7))=C@c97-eW1YF^8=*aV)_AkzwH32WzMmaAJtE_Iqv_WgtT*=nd_}y7 z;md`{0fK@*U(?#VWr_|;Pr=6=vy2=g=Ey(99}iw@GTKQLk0eEwAq-1{7$+sO-`=qG zSSOLDwzc{i`dqMur?2ii(=6J<#GWVAWD0FEVT?22VIo!|*bEVx=!Q4(az77W(HP{& zz7{p-zuftQ@OI|+P-mJsi~?)Yo^xfECUP4-yb@}jrym*X*?)siPdkmhpG9llA4~0L zNxhw-Ltx>hP`~quA1*R@0P~Lds?HZU%h;GnD7Ej=p7?i8{{RQS*CUJ(8%Tf>LCDJy z_Z6YBBk2^ICs z=@qFA7&jR>;|8Ro(eqxlc(->`&a&L!M|d7sUf(Fu5PG-m^{giLZv~>eZyfQ%GfZ7P zvNz=NGu(f^Ya>G4;GJ(z@a^xM@W**?AoAoAa=;&NulwS)iJK}K)}d<_y>i-7e}RtS zngwIgPf_~SSVY(O-Q9+z1?9WV1TzfC20(T00rjgXFw!s0qT9g*rn_wzxY94M)7y|U z6raq%bO7LS){=VJY-*m1t-YR`G=k>N^WoRN)*U?v`d2()n>wX7lRIAc*2luyJf9hL z4a#rC3m-4I@&O;-yHZI}=gGFpZnt)xFTZ>JQ&NUK4$j}tj!oz0euX*Xa3l^m$*ReS zr{v16bqkqqB!bCAwy7x)xm>Vba7i4K&1H6LLv13#Zm*b2Hr0o__vZ$v<;7bxj5%n! zTiWUNI&_ek?hXCKg%S5+Ft`{5V;xOnJke;{7}_JeUkd3~*6`ig5p^tM7YaaD1Hb*N zJZ(v6oT{BNwQ%h+L>^{%(Qt~Vf2U7|wP z^y${{%{(%_#hQiM>;f{MUgTBY$^@6mswCGDX4ymJNG=MZH`50=^r|nB(+$|l>&kW$ zTt)_@%Z=m`B=u&`f2BmFarzY`Ah5L57S10kR=G!JWLFB30tPZqOk$xrTI>;8w6aLP zRkKTKv2nIeH~j~CykeuaMVBuE__FUzm2Kz0n$ab1E=WrGkxGZvdV}sct)Y{Syb$AK z?;YvdSBG@T?R2|)TbQn6^Bz$r&NI*D1a10rSCo?Ig%d2ln(AmRi!Hv@P`Ql&ILGsQ z)onh=sw3{_45*OfVhrRC^>n?+Y?ko+tg|CY9@GHxz3UvS*s^2W{{RqJ#T?LBTej&z z63FM*r~~`eVTsj;BEP9g5Zac`O0WgF<085utFo<;^>PnLKwwyIUgJ2;0p3=Dgnn9- zIr)j_6&nVld0;JcyR9~P;8_-2z}B|OF_D4E3noSv+!3B@iW1@5H*vI3+QW3xTp7#~ zt-z0DVVYifE*Fde^&M-jGUQ~{774B=@kRSs{{V*D9ZD2clHn(pHzF{8cWE7fJdQyF zuoXWPXjz7Dvy)8me9M$GCryOl+q#L+Z&J(MsCaDa}idBDax)gzHzC2ZAUZE};O zNBH|j@n)r|J>Ii>rrS=gu^m3j;K*PlTPx*^?_h+MWh5%{PipOOl%2Dl(&&Lt!+Vyy zYX#MGxo;5>yv3Q;7|R7=8|FXE+r~NI=Q!(C_;MqXE&c`YQ(s)q9nO<+3dYYKp>O7} zc((kfXu;o-4=M=c3diA3ms%~&8YYe4{{Rc57Zz4l^H|(O66AS~uek|6T%a7O1Y{k! zAdDKB<4HQ~z8PGVmu(ppG`n!UNXb33{*}L_Pln2Rs`!l|=hLlpoZ&ze04M{~wE!9c zXaax-T+jwM?@?el>p&GC4FGrh)B$?*pcA*P0A_$H0JR`WkQD%4{L}!T58k8)-k=Bj z#Q;zTekcRdfG7fh!hiKas636J=@7OI7V_#cf&T#Q8_QAu0O5^~-m=Q|M!46L3ca`h z{5)y|Y4YTE>HYKi)(q7;X2ETy=~|YFqiI*|@VcR}FAFgP%VKh)Zh6iRTH%*_J7U!w zd@tb>ZY0$;_?p{KwFTb|^GLvDR3Ag@?^siPnpd%3@h-o2tz9$8w%*lAFSDWCa)`WZ)ci9dnA#aHX?I%VxRwqir4SmYd=mYm0NI-Xg4CYstED z5S4!|hScBy2;}FQ=FGa0zCN6NjIK@6GN@lLU=?*aQSH~)u4@OSvfY;d00LUd`kI33 zvxLqhWkRY3c+UiO``0|}JF}}2_cmV$X*Q6{b*9|JPLHgKfJOO2nFsM>7~l+$>PJtS zxAfCXD&^F*{=ZE%`4#m^{5IpkI&_d<%N*A>x6|6oG)h%*vNe?n z>I(#hP)`|Bb6qVs+NxIm{{X?r__mt%{(kA5d`;mkC&ckw>e^qxCB@vb%`CF9j1~+S zvEYP|gY&KcA<62rljrlN-{0TnBl4~iUd0OU!J4+4af4*@%M|gUNEj(#st$JdIeY>= z4;VF8pRp>Q(=Ph`-M58&8F8lAHNC{QN|3;~V9bPq&H)`kVx)SSnI#ysyp>y*FJmXX zx-v}ZB%Pdw+)n(bE4$QjMM6xAvVq!AEr9^8<;F%vc`L`Ts=MqW)1~RpH1I}{#_Xzb zGDhHzexshed(|IQjgl{38nlB|ziW1i7>~p@9LP!nK?C+8Qd;fAWuMgFk$*l!)zJbTFdFnDz*NhDU3IV?#pARw;YzrF`v)y|Qx zBSP?H@Rw4uw~S&fz_?WThS8IsTwr6`s=pFN?$a*+0Elr&y7D_hsS!ajnT`Ndjo9@) zj!)XUeL`;{RoxhRX1*Q!A1eMEBDC?#B6)?Mb1698gU(N9q*&3q)_9s zmEF#m8RgToJD-KW zOFOh}sV9~l$o^#kxHt!|I2kp*NlFoXWl!?^{{Tif(wvp6N6r2$(&4wVlHx0bxP%gl zKwYhd9H|GNQ^j**id#ncN)&dn%IwIj&RYl%A2tt9dh6uqnMYS-jtcmwvyZ17nHFM49veN&l|bNA8u<{ zC5sKcf0xmmuP$CIYx{XVYw^U_H#*5_<&p00AI+9$<%EQM{0@L)f!JcPhTXrvb6lFz z=!ej))>qo-$1)NL01SHaeF3PQJrM+M-W^~5o%|-&wZigzUBpvc!@6zRk(cqjK!grlmW^9vtR4(K%!6NX9+K ztszm0y3)KA)M|ZzF+d-W3f3kD-)jILRl6)Ex+KS{yJ;$>YgMTUY7XM^mcvQK*YCF zozk58C?N-@%qzbi7^+8|o0Of)?u`EDRJFL$CeyAgGLr$eL~d1wA&1k_x>V9s&U!OD zm}IoOXk{NdA5IUwY?_j^SIrs+;eLw_sd^;3vo8X2H(VIjLOI3)oR4n(E0fee2VN9t zUM18|{{Wx#8*9lLJ8LN(Pc1`7k&Fd$GJaeP5HNB$#dE!<(m)-rjFAM7kP( zkg`V@9&{o?GIP|72K5|NO|oOro@(}UL*tE3-ucpF1g|8I9Ayb$z+|ZCFnU&UUnzCD z8|J61j}G`QEk1eRT~V~uHtTH}3m`4Av4P0jl6&Wx!cyZNK5OsxHc?Jj;WIghQMh(< zXXZRs>dAwQjxZQ@;{(^VVAXVLn`WE%X*`9mA)4-4C*g!{r*r4|m#`z8`te#|)SPUl zW%8#*hU>&yb(Or&Z}81{`;n47BMB7nAC8BfeQRf$30!K~n#CzPeH8xy5bLR|-dYPL z5*ZjGC}Xur_4|Setg=mHc4-K4Ec3%U_+Il#n{!=hw^o-ixZ#-$s&o1l=i0Y_{wYEB znt!>HYvRUhr)%~){x{n*{vAtq00vtNguLauZDek}crC|XE2A=h4OhSNnmO>g$nV?y zGX=A9#aHGaFd5Br!0DGq4NC4COI4bA0;6U41eO`c`quGhJds$|H8~@&^X;}Y5}k}m z&coDm>x$AX_%o43f-Uz9(wr+Cu^ixkb6pNfidTYT;2O^I5++2Bc=yLE$;Lm*djp?Z z&U;jgMAbhHHb` z!Q}*Dle^_09;6>ys=Kw(Hi$nNc&+tmW12$-<&9$U<70rsCveEfBpylY#T*}!IR&1r z@C9NLtWjKuXEFiZavd0sc=QBtMMR;Z@s%1^g}gwT!%1x^g;=WNmc_#W0g$OU1LYa- zoE%jzbju~HMXKXhi$R7e^nl z_%*9)FiMf#vfD8N@ zYWEr~#B#DpG6DQ}i{Q6W$777}YLJtJxf@Cx*Ar1)KFe2{4M8_~av=pcQs<{WgmcYx zaE?Z%j#oKiP6P&{;;k!Be}vPLO|iBVkIKY1%rl(&^Hi2t$5BPrIZJb7uZQ&kt6Rvj z#veIZAs;f3azXkZPQKNAa_6ZO%MKexbK_$*t^A82c)-d9WyV1{QhuVjr)cSgK8pw8 z{IOeUmv>3|)mW*{a6lOPbNwq^GD$XPmOQBvJ`NL4tF+3%g3M)R7-vzz$EnT^D?d+e zT)(NOsig`W_@BeAb*n@zcq8vNZl$XhfR^DC8m~lGBb50Fq!>SpS^m1nhF?|9G;?FvRAS^ zF0F5CbsTq0VGLa zw=F9)5S$3|Fam+==~#Bn(xh1Rdjn^z*j-szD(JHLWs>E0A>kH}W=dp1hnl-xVBmM zji*KM_k}!N;plDb9io<0Wib#Lp>F4noZ_@ec_`0TT1KVeeKJiE?=AI6WF`wm7~c`< zcOL8Co|T?iQZ~aLO!o$hV+JO=NbZ(A4=lI*-}8Ul>0GdyOzfOp6)zR(urG`BnQruZ zYb_?`WC4``4svsza5(j@wAsMYS}J}#i%!4SuVC<^@3OTAdqpWRIUPy^*T2ocJ-tjx z*$8i@toj|GH#SBqnF`!lT*!VwgYyDAoOU%!qfXh^1pRGjNB*^-FGeia@1%zzJBLz>VK9$1Ymd?n|(GB9O9a`=Wi@sp7rr44^ z=gUF{)%xQVt{KMY$1EhDCRH6}iZUc;3ama%V!BR$CBj>U}GkOJtK;<+g^l z(8(UDeRFn66GX7=LI}ti=Lgh&^{qlGircY@Xcsp&PzbD%1e={vqy?FO%t^*QI^v^- zvkF z#3?a}gic6TJOhdVghrF%;Te=<6;pyw)_{Fwbsdb29JbKNta3|@+bWV*(JMxcF1F7c zb`!MCVIW*9T#cq#K4T$Jy-ytAax2ew(bLHb4c41_*74uz&{!@uw52!5I~*uD1pfe< zs^?llDPGTh8`EqxN$y(DOlh=|k~5;;q%+DR04g&OPXuo$qj4BL1$JYL*CH}bKkzo+ z2FrJCrNg96;q*4b-XksC7jR6M2*&~V05}93jFLSoy8@`y9CK~5$*9;vs3}XPcZkIC zY#j#W+qh>qAauq(^U}8{b&lEy^z^Y?dv&u!*da(&6BxlEQ~)#2Pgp%ymdH_D>_n-;@^`HuneB1c>CjS7%Ym0eF5k8%1 z8lOzW5A`SYu6({e{F~$I%$C~U&cA_MEF_SFo-zTfnRVG^ZB6fdNG|^XIkzgPPCz?< zpf$&z<%!h;Mez*x8i#~!E_}_A8OV6|gN&{eA6}g+ne8Tyl7W1lRj6*QGZBwLj%xV& zvneVo63XuiM!c*!A%cO%dY`$j)V!FsS-%gwH>voaR=2Rzq1@9kKgmVlMQfO1&)A+zsU7f=54L>k%U0BwH4pcjO#WqPh`$V_-DuZ7L)`o=$CDMowPt1JIlAm^rx?z8=Cf^fyc#Ip zi%yN;?OGTG<>ibP_GLz1=6@?WBMb=S5;2j1P}IK{@>)DoqUEIcI(Tj5HnynI%F)DS zx1CgMAOc2mz=B6T@toB-O0cWEfjfSXj)>1IT#(`+vPiP zz}x)24{oNms_5rs@9@YOFBaj5Qg=eQ&QQ9Xo_II|89npuS-10F-pwQUO*iq^RF2>9 ze^b7UlXUxSVJb#L$lhNk*-1QCsTiz^FWLS700*DR<8oh5zvTJT@V3$7mf7G|^BQN4 zJ-Enizyp)$1zRTFm50>dyhxH*Xb{71F^w8hk}(5ovjTZNczQC!EOhp906js% zzC6W0iaUCZdZ;ue4~O}94-Qp*N=Z%W7D#eWOj#Z4aM*? zx$WzNKQjgN$zBJgTi`(q@R6^yx|Y=ecfVd=7|_;~wPZuNiz)yb%yZymu^-i_t40~rUW@BM3BGxrT_ zn(+6CL<}l-S zcp&FF^-)~XTwOM7zGOiD8EP_V{v@-uxspGJEwC)|6;&8Km0(u{fs?`MR?3rHkb|d0 z?~kI3OYz0YjhZoXg5XLHcNsa`l{^5zewnU$Cex#2>65yip>yKRMFp4^)(}M$IP*bB z_KbYKqjpL9n&-&|`so|Nnl6>$&kblXqidR#oR<;}!q(3W%y`BKB!lZz;~4I5^hMO9 z^^QNQEdC#xOlf9q15cH0R1NdF3%S3_yzV>`&jW#1#W*+r0M0u1DUvd!&5U(ubS*OU z-0GTb>PK|^y2qI07#~wGzQF{?{lBCv%U0TD#aq5~a=Z6^ETtj-W%^aX% zl1%am;~?{l^ffJG*Td7Wz9szT$EfLRbuse@-8H9>#d!R!xPMyj$&UN-tNJs89$qQG zXMfaz{81)P18Vk>#2w~C0Kw!FC|-Z~xjCx(hfryK@BNqb>gJ!{U+BU-VQmJVtIs4U zh?!9C#~Z?6;QQk>&wnx3TC+RxEz-Irs-4>-k$a zFrfS9w&@x6L_UIHmSH5H!Q+s)Klb|6+eA@d&?Z>#EbW6tBuNL9vH&y39XlLjo-@ru zC3ai9KdRUZ`K;h1M>{)8RaC~f;dcT!U^9|BjCHJ?S*K-3ThZR#r7_7gTb*Mn%p*i% z2rAygxfM%MC$p+}O7&&4TZ>579f56ygpOMW zVNtU^vByw2rKYTkG+)EG?mXxN$Vd_cx2m#{$=rH%&JSL^)(t*J@p@&i#&EQ-MJh*f zf+F_bVq!&eoZth{4Q z*G8D$&F@x*9~SsN%I?x>J|^59(a3-hNcoh3-=PDc&2dX{*MqJ-oc{n0tY)*%W? z&4wu+Iao$j3Sg_}J$(r4n$8k@tuBpPTw1e4vhbz2N&JbVhT1n)w;2pDd0-RPRUDRSF`s)hlF%3HYOu5ppyHOlqb)VI;4{vFAP?$#*E21N4#Vo7nF6&+94 z6|N52Uu>p+lYeMunQ39VNB4y|+-z8r;ZT z)EtQzc0WQh_Nn0s#{5}TIpdSo>-r2VyftHMtHY>TnG#ftsZjhlJ-5j}|R+OZ4|L@BK>a_ix~@ z4(X2Qt*lDZ&k~&ch~@G2I|tNPZU-sUpSSYPJke2;iue8zn*I^#(%pE8WrEkvTWOI_ zTVVeH@pj;v%hqnRZRvco=&u<;WfqM0mv+FVoGm|=SO!&G5Hry74Rd8mu8xdvZF`iv zRSBVKhEfp8ZjzAPa{mB6KmF?U;T{;{7wmB4mn@QN+;4MiX11O&95Ur{Qa~9_Ip;r0 zlvS9_7gupUn|pCR%4v5l&n>OGGp;ffP6u{5IN%&&v-q#1Ps3hIr-U`vlfc@xgCujw zaU60Tw-K^3MsisWcpq=2b>o|H*~yj)^k;qyvC=fnXH37=t^!6UFR%a=anPT>J-Mk* zWnV_ycXMwg?Vh1>(511HFbr_&0l~*!dvJ5!woJ*5yi;(x&LV;i1BVt7E^9M_R~=&Vsla1(GG@znMDR(QV^m&*Q9mE->a#1`=owzIZ^Yi&O{mE|Mm2aT$r ze2d3kN%ier=<``%xbQu_rOuD3NEacTP zA5k#N7zN~esRru`5U`QZ{^!qNY^o_S^h;lHaTCnrCH-lg*H7)88vp2 z^JFaL1di`1!j7F!Q^jQ~j*BhqnA5a$mN-N=4R-h~u}%QM&M-Us)nx?Gv!VvmcNk=i z(*dNn&klP7>w#F+640{hvR>Gu%+8Ran7pKZc5cXCc>^cC{{X+9PaGP&WTdEq0$oLcNG7z|Fh4ZRULblW+jN(RXhuE@q zLQhrS+zs>UV*Qm~G&XY~)8=}kM?E>=hTZ{ch;ce|;P$rrbW{nq+11Kec zVllt@eJe=gjJhM08upFh2!1C*)RNmsWU`6ibr#u6n41PRjltld-JRJak_qO$9B@u3 z=ajZtv`sB^medj^3u|$5ZX$(1RERfKQR$l6F;VEFc1eEqas{X$N&qXoZQNHpWOkt_ zi14&>Tj_5N%${Y>#7gY=#^o)=a{73<%4c7yl9G!=#dMruk6Hl@NEUzx)}RGQ5`bS? zfE_3U`uflX0J!J90F(hh6avr%0DjZ~KokOYpcmGFC<1^e1DXK#pbpdlKokHfLGzFP zqa$zs04cT%7l|~Rb|)Qyb;c1utW5_#8N*EO z-7}xRYUR#!V>MkGcGWaXs{&NArudft3<3{cz3Y*0M^RO~(`LN5NUh+KcMuYas(xo< z!jG)>a$AdL}9i;p}@GY{&s=grB zVv<3Le5bXDsZ@0%somK3HH`lN{f!~)R{TG$n;ZLU#bf72hhq{{l0h4{4nfI0=D24H z?CFg5eF6AQ;~hi9EB+0w+C_J6*7B1xCK#&re4H}jfEWW99eUMp0y8gyAuSIKrPpd4*DCm@V)eGO~>0H=kzas3RRtjwcoU#Tk$)>pcC zo*Czg-X?grLzVK%9jAc=BW9n@MY4D@ILZ$CHCew@-d=W=r_K6~7PKTcEQ( zm30)NL69EaVqs&E+xUye{WZtw=R8)?reP*SO>}0AMDi0DL%-(gGsy(~jb164S)zUyYIjpy zrIp3o+s>jzg!x0tkU0$7*mKF~JALXK-B~EVN#iX}EofTl)`}wp#dfk4{v3<>h-Ek< z2RZ6^tln8E()~?VG~;Zn>OMGzeSRRu9ZJm@tZ~c|>0hc&D z@-fz;S#m3W{{VU=Vurqkk>E{I<5L8&iN|*IA{{R|C3|gJ~-P;Cad5J)qP%hvBQ@|Xu`xBbv$m(wXr))PBUqdj~ zH0zsU*4Gib-F(jL<|!a|1m~_n$nC}|&N8Zfndz5*!$)8tRsIx=#Q9(nI6^m%ziyo7 zt8bA%@j8F%KVMnwG%pOG8I6C$t`$H7Bo&B$rbG4>>tVMVYopG}s!jWqPr?=Q<N@nuu88_*!*X{20H^A{rc(71o}#IL zZ>ck^e~Ek?r$)E2yOH8-CFF%SG3YoLWyW|o$@Hxx=iDj&e|sqo3I71}ZCA1L2D=5t zg~i>o+C8M<0<=t^g**nsXBg{_NFevF6&keB*Ei)A%Y!tNy4|Ze1d}3T4pec^PMP{~ zTgSU+JGOe!?Aj>{Gsv|o-dY47ju%xcLXYnhSvCz-JC$RMV0G2Ccz0t33HA{)*n&RPZJebHy zBzIsURRsK~#DUL68Khfj^L_99et{)xitAs0Qsv^ELThghE$W+BGKhrD81o|}A=@5L zRNsDYR07soUxw~a`JcqZ8q@OrH&ByCbx+~bq2zJdf?@~7w2oFk@+aULJkz6B0`3P4G zRQLK-py}upJyc4!07`ksZk5}PsHB~ATKqAqYF0iE)L^#0L2Y!xCbpGwybwbVL)Y}I zvOzg)))I6z&~DsnQA`*ki9Eo2XCo?oGmLXsHX3Li+_-aPrdBFpwKfPf$X0eMc+J1v2tCGfG zsR~Z+;DFJ)ZQMs=o->?REULHHf1%SDn^vB&Xx+nU+w0GZD^DV}Z{ixnmhL$)OopND$Qz-C!2)mkme0VP>n^W60Uy0KzTEp&6_ok=5P@Xn^%&Y5AU#xZL$ z1_Q4Q2Q}zola)#IdD){F+*fRh@zNPIW=o=kCG1LD9E2nj&$t--)ibY_rS55gu2&x@ z&2=jnr11Wxvcna?xrRGbL(n{@V3AL%l1M()%@;|_@;aoiN6ua)v6jnL)S;01?`?AM z0uSdZai7|{qe&%a9M;JX5U;}cY71ELlY&6%2;`o9&24=YLtP_O7qZ6*EH}Ub{{Y^n zx2F{2;EN%zZ)UaBe7m+`osT(6Y$S2THB z&$o(21!Zu@zo^gaiqWd0G)-Gr3)T4h6b5T`V=mmj@CY3+c^Mr$aahjWbZZXHr@@d} zX*wy^Vw_EHG-)iRUJPmm2*U7A;CaS-V~XRY7s(xWX+@JU`1?9S|UdYC>N(e5H-dppTCNZ_2S706NFuHp3pshQjtvoyr2 za!<5NcyjMi8eF%Rvn9o>((Q+HpD?I9PIKEny!WZb69kBEjw^ zw^%K%9d7U%c$audGl99kD)a*Y_NwMv((mu`Err^r;Os>H9ngaCZf@EC0EjZiBpBSF zuOv2epRG&0ar(d6dj!@=eHZRP#ee=H4xc=YwQ>XQKg3*~Mth2+UHq+=lHHcY8VN=wBLlUBL6@U%0)WlNuol~9qKp&v0nQb*95vYU=1*LME^e#*RRd76Dv z{=Pq9_kpc%Ztv#RH8CSdtK`N@0tOEtdJpSY^qAb|@h86qUbiH1eXvUg9`?d8>P zwAr^L&`M)QAmTtrQhRq5(T_Y_<&E~4&6Cr~LOEm8SNRUEbeJU4n@@lUp?#ajQ-DT( z=M}5N9vl}&OFX_O#FpOAm4EdWsV1TLt94--fgX`*4YI2KQ0@$_N59U1{VSm^KYxB~ z$vfL6{{RAm+3GXGmgZHsi{eVR&R;fw!0QB-)BkrU|b;E?Fj`{r>>Ij_O#`YwtrXaB4RfvH7RUw~dxH3cwWzFa|sH z0=?lMy_6}f% zAtBy{NAmh{-nWY~lB2G@_^;qO`g%BhM`e84+#f0K zAZ14$R85_ru;de;b6sa6MS=WJtZF_Vw$kq;MvBeq>}EuqW4{6|WCtK1N|@;p>Zr)L}r2EudwV8FIgH2c~;gZYGhH zqhCG)vWvmCLrb$pxp)>uofwZYLD!MW{{X%zJWccz=+1RmKf`qhVUh%CV*%RTW%Cfq zcrCjm_edbK z%!;ayxrW`??hjgvD9*N8O^hvb@i*4$M%RKp!0sdSgZ4ZT>59IZ*#}=NE6H_!>m9q# z{2>u5li1_ar9ys75!%;>rPA)=ySuo|GM_ih;PvVN&U5vv^KDfWaiU2r?QeuO_Onkp zcjPa~gWZp%X8wiZtl%*q)?OsrlJZMfCN{~E|NCzwqb6Tj|xU!A=o3DbjJFNpwxU{>t zNrO((g17Jy0tXaayc z^`H)dfIFVl0i2FI&;XzhN&z|cpca5Vd7ugb4FJ990)WDQ^*W7dcj3GE)Mnz=Yd1cg zT%pJ9EoYT!Gi+PYj=?%giDzyUG|&>yo_CSR{e^S3YIV{g_;i6JTuC5l93G*1FZZr& z^+!fB`Qc`3d-x>`Fse&uki*ma{i~5J+0o$Ps`$}u^;DHnj8Ms#*$5lX4%Q&?$Lm{0 z-$rehO%KI(J}hIVTv*EUSZ3-8M1Epmp++x`6Y~ywW~;T?Ka(?`AHCCfqUYkIvUiOH zL|RH@Ko^duq2rO*)X08Bm*LNbF1$^td@Z7&F`#)2jv_={<0SMwdUwThWs8&Ijd9Z3 z=-Rc97g+c_Hi6)%A!ZAUjYd@7^2v^N51=DGIpfx`o<)st#oxKSVa=&!{SklsDPZ0d zxW9P(n~CLSmhxt2X?Bmy!14m}Fb*-utNJvfj#BCQef9788T!`ck}>UjetzGXAE9`a zt$bl}WlM1l?A}bwgzP7@i;{Rb$?eImEIy^;^$u++lc(+Zqqje$S$#T+yNb2%`4j## z(XI8p6IHObXyJRid35`Qb;v^Ch}@4wa;G)uNk%f~4%4Q;hy6|*QlB0s8Y}F-qqeS#%I;0ln?SI3>w$TL&M2(V+G5p@2U!_{r+A?T!r?j!WQ49x&?Nv;b zl?F&<$5EcX)p;!ti_eE4fpr(X%bS0Y$0DO6oB^LvfJ<<3oK_R0?C6KGHxI*`d2H?P zG~tXU*ixMmYG86{=T81haCJ^S&G&5Fq+_RS<(ybWtB zylPu)SR0fQHjv2NW01cqk7|^y?2Dvio-o(j#6B(6b&c-O$u1#g>LEk1N9Z&6uUiy& z!6VGeE>dOJ@X98WQHs|%5m|&>HVE8udUM~cME9c6)f?hz0#6Q&i{{L!gb|&CBxI9= z&tBbYnt1Lujp34|OpNg7frO1C>XB@T+^CN~Ho!CbWFJFVWAv_DpG?~)sZsnLoqS8< z*sQ;WqQMl=hX71KDdn%`U7c`o!4(;OO)AE<{l6iP(|O4M0PKzb0PD59(tJjS8Ex(+ za%{|UD?B+vf>@u*3icdsBC~nhjMH89_wD=|EEOm;`tRyI{5kQPY9ijxRh3`NFk8bT z0(XHMA^!m6Sy!H)HAkoQ4b*aZrTaDex*nqfNzWgPf4%gZmm$9BdRm!86zkl=oOy1wXm#eHjqiJ4qBr%yhyzEmT zU7Jou4qKdYoc89qmp3jvd@tUs`8qyMJg-~*zv%0!_+_lL$uAnu&5}7;UPY0g$&?f3 zMh8p~bCNm%jh0{7rv0l%`$R84|SLEQ4STgP+Ts_w_Z5oLt1$hYl|(mk80jig^_>aTphv$InLvpp11&$QyB8w>+eM+Cmk;S z_H)*5?z}^DHnpl2HZe>r?QMq;W3)T30`r^ixsN8|W8*;!h>B%QSXx zKg3+hhjE?M@q>;>LBw=5yZ~ymfyrIlmepI(9%Lh_+PxI#Oi|$-cFZ$Q z^in0cGCXUum_GR;JBaFbp1-FRt|{(_XFF3AI#GrE_m<%X)eHbu4Uk8#%b&Te zCGK4pPs7i{9b;c}HO;j4)^fmJDYpb!azMatp1(|UT$%E^9F@gy`8CHRok+E7n$50{YZ<$e2h?P?jeZvanSmWWHijqktuo|LTid0t zzZO#-H#bX4-v0cPntj%tsZV>R#UwW-5Wa9hn4FM0c0B(8O4cqjlf~cg%w^6Ij$Xf% zEw-VfPj>n&NEEDvOdeJcus$QkLARGPPF zv`v3aw!E9dI+cX;Ln~ZE70fKf)v}DHPJ5Lrk@c)Av}^3jo|Ap4X;%=-=E({E9EL?d zCnNw*Odf#s?OFA*=C!BZNvv7iO>u1rX3pTKcZOe3c+Wq*T|P;bYmbr-S=YpIM%F9= zGPF!z1dKN$ZyD$T9eJ#0CjS5lqFdQCo+N!Az_*(H+7>o&yG6SJjK#4C1OEVf0gpu{ zwZxpL%Py9WmT#?}myz08Pck{=mM0~?=O(+FIYzg08(X_+0pSlL+r3?EB3r@w)S5=F z?;Ivjq@BGn>-zLHj!0_FApOmsQ4g(n7+h(MZ*K*>@ z>Ae}Yn}2Z5WR0Dp<#^;F&r*K)BC6v^Mn<(4iG%(fM+~u}#@dW=M$Ewu2;5uSBzCTO zzy5ANQ?5UaOXyfNUl80KFHN`6JkKu2Yc#A^{vzb#Nx{s8Bk=K`Z7pA@0v_hJ$G zq~+)MCS})Ui(73ffAINjt}>8GX>iQSH(^>(>NcLd0^Y{A$u${pPSgF2qaI1gs%Sh# zre02CxK+EHKzUM z8NgCF0hc{^J?jVRA1jYu%-TMhJb1}(-4@+jPF+P-2?p3#bc1La-Htxl&TFeCFNyN_ zIPqope>b1(MeEuU%i+i^;>h?x=7ouHUC##}Oy;u7i~j(UUfcamuxDQxx94A=<_oL4 z4+pK&M6z8&5}W{jbOa2r9SB}e(xpyt^!$?A{ywE=2xRpYaa0ey7DACe$R=d|~1}UJ)d%d#Ft$ z2nI`K%EX`!q=2}txV>NMWf=HI)8MTVT@%HZdMJ$f+HRevK`Sc|RzU{$0FPI4e)Ykg z{w02=ej509^$kx*eLq~#bjb@zJ?@~_Qx+tsh9oj$^#k>)dMtODC;6B4GptRo$byQ( zeNV)9Qr<%2Yln{6CL;h7hLH3?atH^WIvVy`y`E+9TPi<@vRpw7Hc~_*{ux4r@=gy` z#{~y&bI&6+%RWidM$x9UPW}Z+ZxUQ2a88p*xDv4W4m&CDT{tvjofZv$NV(GW4NG2> z{8S4UoQSG72T_1M^ON)$t=Y_sD_GWUqPn@Ud_|}{ih@{MAqZe0|lt5rgI+V*7y~ z%1Pp^G4WXAbu?uJcl zqw97O&8sX@D?us((yWWL#y!VsoDgxlGRo|&O@BF&i?E*9IVgkj@-d&T1#a1bNssJd zc@)cf4T^vg2O5Q7GE?PG|drrH#gG7^45n9b6h+~q~fMjfLNf(Sa92)CU_Bo`<`@aHNUhCF6 z>*4RCflC4M@0V}q>4Be0aU$6(;9F^}JUI&8$K_qTj`N`(mGjM7t3)Sd3&y{OQ~0yQ z6Y91)hr*G~lSm3rvIX|slh-}1s zac^g)T-<669Iq}#xVBq$*t>8D9-MRQ&2!|$o3il9N{asgi1Zo!H>ul8Z!;?DG5O7B zyFV!z+HupbLtObWB#onyvKo8qSS{XIt>ubDVkAjO8O{Lv*C)YmNVAe8E#3+A*qR4{ zBv$iwxeWcgW2d!M#*iNC5Z!zf&9$s;q$7EF#t%+gh3LU7nABGy-dxneBHK zN0G1z^#YQPts&Vlaio~yXzXtlb|@kcxGux<9sK~tPcOEF$l*{>_I$ys=dz@ih{1l^@ka9RJ zj&VpfuGtLTmt0YE1UFXCWi0S{rWYmrm&W3y#~9nrI3uNcamcAz%;U1Fsd)2DeMZ`7 zeDwG^m(93>K+7x)aCWEWVh%bCilp<#=(2+%t$a$u#y3{iH+LE&cejk<K$bM~Wjt&)>{3lK$#5;qR0p#yH+ zoD6b(Y7}4cb#tQ`IU$4Ym!cp)kVl!G1a9mcVrEuc3S1i&WJ>}yh~@HO*~HV z%`74r5D|`BpVVTqS~fF{b&w+t2`&14D_l!vFS6bEec~&R33yjo)L@BzGWJNVZFiH0 zP{G}C>5l%mt4=AEPh`jA6_jw@>H7AO6w~PXq+)k`21uuJcc35*ppY02oSMcfnl*n? za?iyv_)Ec`;5rC0UEM|h0Ou>f+q}0szkm-+fW&992N|rVX=uDFwpV;Csd0H3k(rzj z75@M`u^qBbGmmb$pD) z^JWp6{{Y%kU0>*8_w&hXa}&6e006;yu^yh);pATDxfkUcUXQCZw>n0naL(4Z%4}{k z*b#+n_89`Yab`;-GRge1`Cs-qvthh*#}4E3FXfppAZG2D*!A zl#n`ZO^xnzUZ!kLFlwLWoV>! zRw6CDBjl5SMtLJW>ooYaD4M^WahFD;@iv;*hXwrBf5S-K&@^PIAQdHhkU{H?#MfGq z$qsHkU)nhMym>e&cVBG7<UpYFDB<>ys|z4VbpIuK3rva^{xdkba%M#ME|Py`?JkkHSY;&lGy0?*VkxcmgPW%vW5T*4xZrGG~df-L>A3oNb#h0+C7wP z&PXcKvjC-#e4s9S@%FA|nZ+b)@KbG%H7#dQz0hs-eHLjggflmuBYf@20eX*{gY@M3 zQc{$lrw3cvF@$3$3GU2u#Wzo!zm}bKBOq+Vdr|s_UX3PSu%$ z+oH6Akb=qi!vIQ$2aUM^pQpW9V_gx9R^quL&*te^0#}ey0>7 zlUi;5cl~-U+HR=^rD(SrZRMo4<>{${cWc<2?FS@yMpGEm!Ju&l7{G#oy?Ayt0Dk z+GsA3j1w|6sEdvJae%?O$I1u3DrE%IQt8##``C=+nv{E2SN*F*4~+FB&^#q`~C6661$kz;BOq`$QeD|Pf^XtASjTA!>guJrc%%sBt#&XU< z<%!^d?kkrZc{*QzQ>sp_vTEWr@jJt5Z#mPvC!|B>Nq066mV=2UU_UgE#~pHTGtFxi z@gEiVSKa=mGWj<9e{@qkcRX5-uWe${Ev}nk3N5vxF#ZH*<_gCkG>!S)k8%e=S~;gx zqP54q%Mam2gg5>t(k?AvM_6KXzNETzUSUc{gNr95wo zh^*}7{H5ZwAo@1hZcovd%TImn*jG|ZB->prer)7-jtO~x!Smjyad8!@d2T{v93Dyc z&21Q~Fl=vaF6ei^Ol0%kr;QYSo}szI6h_N8zol1>g^%>-kZoDp2ddR1snKM0zP`AY z;us-jSh#;;N4-yqVD&QzZ}yeS$h#$9QI5Y_s?#Kem7h#8Dv(`V?I)-J*HZa{ELwKE zsp;AtbnQwwt8YtDe_X_zoy6L{3WW~%L^T?ACqH5qTECz3Wq0)y$xmj3|bP}M#j?9wm(e?u?v7Ik?p3^EmK zmsl;y;}L=|Gw;P_-TtMTq(k`cRCGyTPxzZlD{t_-YnCOv$+Mf8LGPEsk7cgN=~71| z{Fzpfs7nT-vA7{*kRuFq1o~G~hZShcvR78oAh@1cVVPrgY$~zpe!tqQ8MG>gwh%Ri zsEOT~j!y@GYOh4Co(+Zd*||1tF+x9xB6E)uy{bWH^b66J5FTw`i3<%v!XGIuk50Ir-dt(^H?x-*C_1c{Elv+G- z)~4%Z-3uX%YH`Udax@I8$7c))9FTswqpBu78+YOTo5iMI+gfUAKA&>|ShpRFtiX&q z@(}#OxMfM{=;~WWe{%uTH5Sp%C6OGNlaZ7BhaS65IN;)w{2D5|K7jl_(roU0F=Cpg zo|8tGX6_`FalMsxsbGCRZ?Ag73*C9Mrf;f#4DU)~Z{w*R!bqaMGwx05B!klc_Zh*fdU?C!Us38Hnz5IQ?qG|}j?u(Y5DTnp%z4gOk5kVz zX;acE8(o#32J3QZ`pvw7BncjOZ~k!H5XaNFtf2Tb*Mn;Kk#S|lZ9Yi6PvqN$nI&;7 z0fs;g@AS<~qSW}U-(RU{O?*C5)pz<9zZL427Hb;m^O&SmEg{-IP)-I;I`!hW^%-1s z2T$+G$?34hR_3h^JSndxr>DC-a)!2y8D)M%hX*VO`WnBd&&oSpFY0CLy*~+B^7ZsO zMR#f9I~`8ODK;Y$5)?RQOar?IoKa3bqBDZmh53F$Smo)Z43gi!=j=1ouGhm+>AGH# z6fW|+J1e$ZANN1fsX6}u>v6@8&)@D}96$D)vgFl${={$M$B8EJ=Yg)Z5XKv^Z77XV zvPAMHmk`ghK7Q5LZOSSBr!6X%=zRD80H^I2{8#Y@Pco=BdNd~e_YSOsWJBw{gMaX@ zhVSp#s#08m5N$h zfUO7uRU-t+j#&EVs3)keTO6u9UYb12ir*#EB6Zy+4SvFFX9%-@_N6P68)vWfsFgC% z`AO{(-EDOEA=s#6O`~WWag5{lt3{QPvbW+N6ifaNw(hoVadNTSEGB$3j?IT9age8; zLCD2tk0j;UIWfjP8DELKJ0_vw=hdaPlGj&lU&x(G;1rQ@!Sq)Eee0u%&t{9@H2(k; z@Ku6Z$tA_z+evSH)345jPCld#-&)d&Sv+)P@c#gZ+^eD$*(L85&9AjY5>eV?M{Pz6i}`*6h+OVQZjk@IiU7&tnk{m_zPDqpnYS zt4@o?thD%3RGKK`jwUhRu^-2moE&<3WAv_GTcfUs{d-Qey%!Tjs4d2$B*rIpCAS>) zC%MO`de^~=yBlgA4!vvW;EPU%DX=7sUL(dc+j(8Qa#)`QWd30&CTdQcI zxq|Z6N8cDxoDz7?86CdnxiZ6#%x#VGbV%!VTE*0#4|KOs!xWnYESpkBBmCc&pS@(h zWoWdb;^~}kbt`=`(p@)FwP-a3A{EP!As^-*wR+VwP-l0lIzw)tAu7M~2*GkkbK0?Y zM3M9A^2-<-wjzuKjAK5zsHR1XH9KMD{7ghDo*7%H{{XdV2X2UDN5@SYh{=p9{J?=- zORW?*28w1-qswkdU^>*jB2geL+xTD;5n-L}!26oY%MQF2u(yfr#l*}&ljV_5Tz!42 zo~Hg8(dns3)tqWK8a32r{(CJ>=@!lBnka)baYn8bF>vU(P{CC}+&SE8amiN9T4fhT zn^wBH7dMc^?x4bEW96Nh#6F~YI4n`S;uuej~m^y812q;m0$pA0pn`ck&={yREPOhUQFuFw)eJ|MTMoz6O|bvH_irn{VK_)(4oLN$6ja#Gs2SU_7aX> zGINgII{uZ-nWoZbRwUG0L)G96bgq+?ih9t2Xaayer~-gH&Ax{u+PiQsJJ zJ5P#2I){nX$Lt9Enu#k-7K^5Qt)oE%y3}ZkgoxwUf-*mU>s%A)?T*W4l`2asG{`qb zODXova>?1%6+^4-L`;bUh@l*j&(n&c?6cA+I?PQK^if=7M&xCelZ^5}^{$+1jAZDt z{wCjPAn7`HhSie7(Pfq}!MB4U83%X%-2LieoqWYs-J7uo$E%IH?3}^ql#uyP{$i&v*2~dLOzGuxboB0=;_6MrL*a)`7P``7v(a`cW#zy zBXnJ?*dQz8`EiwO*3#n)6;`OrA1UYLwD0YIV=L4lnn@TD6uw?EnS)ws9~pn9 zTCysMCIEnVCqFZOfPS^dwMRl$bo@ruEv#Zo8(EB!M|$$ip-J2a3IX&3_pLEQl4xa` zRFL!V*IJEkC$hYN+*#g6Vq#A!LLLS=P*fae`Gs4L9T}-vF|KLR!E|DTh~bG)Au+KL zU~W}xjtTjWc?4A+o{f7&MmS#HX$oZQRT*?7ZESSv0S6;J4Nq23xab;vzNaXJJaAkQ zv3EukxaW>Y`{SG*^_zR6WQ$~e1=cN6-Jecd{o8je5Byk(A2NwD4h}QV<>XXL6zP1o z`G23f3nUe;RBJvH)9&=!61UUbODmO83%Nd78R~m(1OtvZ714$g#-AtpefymG@<${2 ze0lr!8*3gT&@|a2k5w?p@wWmPr6rPv89c3l>T4F0bqR ze}g6e0Mu`fEp9wBX{1_tgU-}U`-uf+iX5CSKkH;X;<~Wp=O(M844D2JPWI7~{t;Ns z;-ADDSkfT&)~oSy4Do@$2ldW7;1XAaMz^=%>vtmKGDBP}P$9ZO(2I2>>=NA#|F zRFS+i%(z8(x2*#Jk<6+>jtX|#di3CCxM{X^>a5cIALVL38oAO2qx@+X%Vr}2Fmcch zy#`OIt+D*kc<*e^cNr}CH; zb}#4qoO)K4zX?Nk@V2DdKjDSUw=*ie{lgI;ANHWAVM&yL7hHFK(`xRLJRY%CdpnsldP^(0wZ;rMX+bJ1@#N zNgBW5wa&S$MHQs8PX(o`8LlUq+{$i49o|@#jz=dwI#⋘$(allI_=jOEL974-)3p zx1_GC>qXa9vD5XdJDomPmDlBxLvG}3?u4G4j@8vD!y<6M>H8e9obk0k=l7zQt$1D( zw|y5vv1w$#WtRR~7#3w$0a4qso=L~1D+h~QAg#XN_WBzvw)xHV(M#20hgi0^({xyY z(5+r27J z-MeKb?@%fK01Btgw?l<3)E{GAk&UA%N{>)9Gg`>9%40an@to9EXpg8Zyh|6F7^y@0 z(QRxTr@4|)N;7WkX;$_?vFg&KXpPBEhZJ~`9FCf0%+uY3FN~h1t0*P1$=TmnkIq(b z+nyEq@$P!nqUgFTn)-_^2f~)|DgbQ$C7C)gXK$FE$AB^FE1r99&Ee6b{uFqM-aj`^ z)b#l81^Y)CK3?_!Ht)&&!#Ft{=Dhr`Zq?b@is@|IjqDaa7}O<6Kf}-mU_kkzbHE`$ z$veAaHAf_%-O;Lxl+x_P+S2b(y3W^j-k|kT%sC(t>V10iT=ANtcLv$Cej33&u9=jzMtle77S2IQ(O9)2ZZ$-U0TT7HQ)G*(Jsq}kpL285ZF`O zsN`2~rpX+Ok1K1oaQeJ*$MaPu(ei)zMc;yd5j9;F2Y9XRu8h{lmfvpq3Hoq7h&61o z=A%D7Kg|dy7su|Ita!^?6KJ}1suLZ>@O3h-aFM71{$t$aFY0S4JBnWBv0H4W>i720 zTFLN{M$Cz}Ih}w3v4U6BDCVbKB4u^6I`IrQ@aYiAro6D*Mww6vUBI4Ldgr;WtSxf6 z9GMj&pKqvNLn28s`NKc`)yY2j>s``HNu22<$&F17^@#HG8xj~R9)5_V_wuQhds(r8BwU9bw=R2BMj9QOAA&Ary0^xmKbXKb zmnRqm;OF+P9J`U%i=z2=aT4jv6s;Q{E#GNS%ESz-4DdPJ57cI+D@0F2JtxH)W%aeZ zaKM(*LYXaZk1cR;4$wb_bC7YzQ&;^AuVjyk^_%@4NV{2>qC`B!xDVzls^FcZ50$b& zsi|KPYqJ8?bt|tBT-@L4Z~p)jaVGaWKmY-N20aHA)fAGXVBPGDx0*f1IAS42M&rd; zQ#jsSG;gtRc&8f)7jMI>Xmy90!em({Hs=c5F;#8ZQ`xXhW0Fa2nn7NRHIIoOz}Hjh z7wKkVky&EAw~bgf3ERKbl$;QG!5y(!B&44o2DituuyrZy{9$dXTuXy>D!G>Kc1WbnAEp>_m_WUo~QqKd2Ka1EB*oIAgj*WtOd#Kf`G?Is8&J3mwfjn83)( zg^*`EWb2Se_NdEg{DT!g#C-#&-f4O~Q=2sMcM|M?Gm(svJ+M!2YOEeOejOS~PJf8Y zym7C?s_RR2X_b78?mcn9@AcxU_Uu(?w)j^|x4zS$mR1VoHttcu^dmohDtM_amQrzL z_QK%=wsxSYWcg!e_8kYkSw5mwuH;E;R`-x5nrpofFS~|&a&GNMT4n2V+eT`>zr^_v-EiJ)wlC6*tf0Ak$kCqulFrYr&>M8 z)FuGTWD@zVK*j+Izd>EU3JzZp``N|uW~1=eRbS-8KlL@@MYuW^foRI%v#MQ;bBFCsWt3cKlI_@m(n~HF0XU~-0N&7RV#wF$&nED-IjhkFr#JOseRl3 z07Om9_ji6F@h+L+_J`ti4Qk=8?&QIS$|XgN40UN3$DOOr2RN=gv*#whzqOrsqs9?$ zsyujiPa11#aTyXl8)J?YCEF|& zh$n%7Pux_?B1w?3w$V`6&YcXJE~u6hYI0hZS5^GQR0NC+@Gway{-!mjr-D&NKB8^S zk=`q`@qW9kE}d^-Hk+r(Y_|-rhdY^rRF3xEtwpzR=rR$MgPj6#&1+Ax= zCb^O+GE9szM$^x)UJp@PD)MIjg@eV@*=V{I&F-_P+>02n*Z^+b+ipAO7^!bW8MlD7 zfAOpRV_1UPITK>Wpg36(0VJ0s_2iOy>r}K}nkPIZ{{Yk8AiujY-nm&| zbCQ4ifN`FK+M-OfQ(HNBvKgOHhC540kWC}R&Jb|BbJNtE{*}uv&ZzW4_-jf!DYk}K z4c4J3X%%ohu)u&>pQ5P9$EoQ^r_mDX%`(~>%|lbuuI_EE)otHtbeD586(Nf+@`1(& zIqO|%Gm*96scF6wZFb|uamyt3P_Ct$QyXkQ^1$7Z*ykX2t8t>XS!U5~biWN-Nvb)! zyS9=d_fNygh98@;;CHMuwHVpc=~d)ksU1DN-PhtRo%M_?khCT{iQ@UAT=R_jf^nLN z#p#*KlW4F*;hRYG?N-gQ>8L9#rN5gs(MDEz@P>zR;p=H^&D3*P1N;Qrhe7Uo8n%j- z40==m?T%_mJVz2ltRhgkJBat7A@yx;&dyJSzDZI?A1T4we&Vv8MIACyvkLKLh49qn zxw(zj862<}V56VRM@r+!neYMzP72kx!PYJMcRFI#w!8Jr}Dj zFnH@sI?u)HR$t>6Q7A|vb_F6i<%*sQ9u9HEb*$+b@hqCAx#5j-Nxr$gCL6n$QZa6^ z{{YAFxQxhJ z;g9^n0YVR@YZjkn8f0b0sc>x?+2$?}4Uzk1w2n1)ky|5zHr?Zq{VQSzx;CHwA#@|& z%AjSKE^%4pp9D%)S@qpI*4sq2Huv(&b`I8zoZx$oz_fe&_EN z4rg6{`#DnZBtuLioX;8xk3=is*E zOVMC!opVY7q?myxo(?-9C4n$rmc0^6=ZwsRxx;&;cTz19_ASYS8#^;mmnYXuQ%1@QJSWDUY0zd z(>>exn@D6b$*Ef`GHrN^NHP_erV5TnBfdI{?Z=)INv3)8$0)jF%yJ~L2_kiLZiF1x z$=^n2u9O1zpaDP>0o&GqC;(6gUw>*6LPY}V{wJPkN=;>@ZGs5M42^KhmU2B+PCc_& zwB?eYOZhr4hBaNXQp)Zd*xpN4-vYZuymV$$h6B_NnH*-djFh@Dlw5l~UQR7+u5MX( zED=1+GmM1=kKX{)zKDvpkd`vZJ%yz6LiX}a3QEyG=8td$Dfa-1t~qmxku#4OIQt#y z#RQ-hfIhSWF$x%x00ShGiUZ6tEYQa+Y#KQiadcLoT_a-b(DR zVHNDrfN;5J(Fs35#~*r2$L3l#lO(E9RvDoIKokK$6(A}A43aU{fMKUEKv$oWM|2(0XVD8Z_+UVg9Q$Nf50kANFGD5FD&UQexa4{a z(jSOT=#B8^rEhVpS?tD2kH{KAn5)k^8lusiN6hzWXAdhn%It3>^In8rUQETdJ z6w62Ajgo)$JXeu4KL>wn9n?p8V!)`+(1NTu{{ShhChwzEiO&T-gDiSoxVU{cQVy2) zer$1w83U^5h?0col|TGHYh|+>&&SzDad`1Htbc7qDtK*2>@U1RefYA&3L> zI)Vu27#_l|-0&ui{(r$ov6A7LMxbPCg28r3dS|Zg=Dglg{{Ww7 zs~YfYz6rL93t28#AwFf^4;UEh{l131PeBB)CxgiU0Lf%>Yag8%7vr{~gTm0KoJ_YG z;Q2K@1`C57& zNFU7q08f9VOMmhy9T{hfEa$t_C%KTHHe8uDp5vYcbYpx>a$9yY(q3zJSsb0Nzc9%x z7uWv)H8P@+(Y3{J(&#YUThD}N3?-BT%O5+CHZ#Kl0MAFqO3C%3XuXYP@V(scDjQk0 z<;hdH5(viKy@)$bbJ*sn)R%(lnQrjEh8y6W^?9?j4DVf@X5Ij8-G~KpPq-CTjmdod z7U#$ClDfByZ0u|#gGN{$1RGF2Gz+NPh?_PUdLV0|P zg=oxjzU5Jav~D=TIN*;=QxoGVlhYX@oOHH`AH+LLy)xmNP_a+q3I?*nF)w;uRd>0hTrSx35A+sU2}y zB}&a3w?-S|D?5gga|sBx&T;_dpQ$+O(C3d@-(KB^svX%ZTH{yGR;p$mH?||0gRzmdADvV+4c0t>59kVqW=I1_(X=W;$VC?rs;7r z{AIRMWk(_~0ouPP;O9BW}BBkO!_k21Rz{arF3`~8e$ z<%!jpPviHCA-c1*@Xn1XO)xO?B;E5&$&rDN>Vr$Om5^@)k`f(o(|q@Va`RUZ+l@J*2ZMSPZ9iw`Gr~&Y&2HdBsUm23DlEa9Gz&+iyfAdEU#vQ zKn#c%obm|)hwN*fc^fX3XyK>LoeZ8FQU!n$<&mA;c5nm3mWEORBo zlq;Swo(4Jp42*<8{tIx`uu8zo5 zXw&DvZ70Lg-)l_`oUPLeEj_q44e9mR$#5k6+cUt+cljSix*d-4r11CjbC@4tYKL zRKq7cjuGiD$dnWyr7qh#jW=XB_S#!p*)-u{kK3p&>KAid z+Z2R+@+Q@Aqtu7w5BiOCHAlh=P0{7xGAbe zd9CR;+J37(ovA}4GS3Q0ZX`I)I(<4GwdrA!loXM}k}fi)NNC#9CA2p3TFn*XF!LsI z3~!EsQwQenyEV<565B^cInl3vDe4-wrT9|XrR|zo6@>%}lL=Z_OpvRyk<)Q1agHi5 z$CTq_=6qt>D?f)`D7Uh*(fs()mgVG9sf8-zqa5H9laG34i;J&fF*ItB>sI>ph16ye zE#n|=EIwdV=ci6RE1RD?v!{<5qdvE>x0_p&C`=ZtNk9u^bpt(ls7+ma6Gn;Q4N84V z;RLa)cIc#R0DSx%rH^8IaokkGPEB7#xTO}?XSj7)th`qfUNPAWqvQhwC>=jT*0WP_ z$eZxZc&TG?UQu%JM!u6tC56M4d1aDler$rI=U^XlYi~`NC&FItzroGwur|IVd?kP6 zoze7&ba*bshnQuSJ*&B~wEV<==C;L&VNZv2bLP(TIH~lX_$e2<6xv>;Z)ag6t-P_M zQ*c0)k2v?q$jPrhcwRXuN3M@b8J0-7%f+(Y;ypU%`DPMdEv=MDzL>}#JCo?6cOCIw zj%-q#zZE6+&o>rW!ChN_X!&+~TaUz##ZM*x@us(Rget%CY*1|n?F#4r0CRiSWMz7Z zf>rZN#{T~RGwRzL>r3+$zKqed5X^1S5Md)&n`0B~tffHi!_XS7@^v4z@BTf*j}>$K zZ|{D_9pT$Mi(8^CA;qj0R~Ip}{PHr%bs~(P=3#-!uP-e5pYWco zi-=@&1jrZV>HhOs#M#ix{4&;IbZ%stC57EnW>C3B5`2y8lY`rujvhmqIpN<7BgJVh zpt7S|I!#d*uwOJ@|&#Lv59i5(=s zJqId%Ipd{T5#y1i`IMBoV^`o?I~29Lxt2YIO@dC`Fax0aR`y^-ej?jXdEjkc-qD~* z-V?CS7iS#z;2t{msFJh{U%-Edz9M}&u5FqaV84&yZeudxf->iS=xa3tPDr=-6Y#cQ z3uMOblcsQ~)i8C6BS%ATAxE*TdN1?`e0ChZd_n;xK zWIC3!{uWW<7KB|HRmluN00WMkGkmApwR1{e6DJR2t`Ycn{wKbPi+Iu%D;U6L+}PtM zxvr#fp8nJzKi()ve@X!dImfL4zwhZlGSxKbbr=j+C4zPNdV}j#oD{UdmU#aF!aAM! zFzMG$u-bnbcetD7Ve9oD-nr!u28o#+yf@a@SC*FdNjy@1R|kRDk?maain>VAGo73T zE~K}bSfpirrezpAhicALnPhgF?(D-Yv}-JB)zti=UwVZvVAr_fCcV?_V_EIk0^(yb zxX#g@2klyJh#~JU?=AHfStE)OD;WZk8Mc$gO-ty7*=N!%qPViVk-Vn6j0Xx-0C9ng zR!JHQ;%!RG?#?@g)2!?zjkXtxGrfnd4NcyWM$GE<9qt^gOsF}@^z}8;w2B_>XSG<2 zPiN*z$A>awA8MCnPhZliv9z>JkNhPijQY*J*tAP{km1-r%`eew9QLD4oj#qU?26O1OQWXF(#0&Q zvM7z$aA>;Z1JEe+_pLHwUJNagFxXhl1-05ZlH`?Oj~OwR92IUb0nY~<;smcS;^Bzb9bSI@s%9PxfvMklXM9=(x z;(4yFA+d^BWw^VAqK@j#9U|0W&&#wiI|}o>5IGqK99Dj#FD3Gfajwof2BC3re+;*? z32&iKAfQtwz&%`a!2V;`-?y7LChyqq!j;o5`Ui(&u+=VQ*X->zOF77r*6K@io8iw> zzm5UU20F_0bheM?9O8 zwlwiPuLp*;SBL&_w`k-40N(!qD*ohDWOWAqg|Ms1AIz4xK^*RirBzPQr?xv(VoESe z=vHmHHqRfWT%b?~+JFTBs=-@xAaqb!lz_pM43UG^fM`k}ycCf~;fpl17UINjHojA{ zW+rmWxSlhH0}H^$J6AuZlag=2)9Rv>{-fP^Drj20$;S9J`;w&g+?YSmR?_@P${S4* zQw_4Ro(SXCtc=;>garT&lmS9UTD9DkcJ}WIM(;J;HsK#Uhiowz>Ojf+8qX}8W3J6H zMM>}2e8ZFVtqg^YL%JzE5(P*gd?|4EaOxK?bkqD*+uSO7dsZCaV?D{*51{Q_*cxt4 zd!0U_EpboSoHfvMhW`LBG88YjEwpuSVNrfU?D+><(~XCVb$ddswQdWmo|z=>Ao^|x z2imwjL)qPpXtHS0t1*>+T=Ea7JRjb?_V#thp@y|)9z2 zoQF2&8R^%Y*JK@|mPoXI9{8EGofA`Am6CWD2(h66hGcDrC!h=$ka4ST-@ma!TXb)fS&b#;@U<4=-4^ll~Ow z&lL9aqY$lOG2F47pX6uS2=q0a)wlHi4I=KZ&+<6%&w{PBdkANaWrj~I$K~832T79z z#=|&e!Ql1E`_?nZ@j7OapAONdLwTb3TSU`z`CXa`WZGtmBg3#Hv#8}k0DV9;bu50K z3J;==GtDHD`Y%vg6 zTV~~%a8_G_C3E!=h`&=dSjuU( zt~LQ0^mZQoe@diw)Bc6z=^4npxVw&4y8=g$la={SbD!I{wQUyJ&c^ylhD+FCR~)e+ zT#=vi4F3NBYL!o-EWc`c-1=IinnbZA5TYqn0$(-~a>~KD9S$i>wViwu;w$ToWl?S~ zCUQ)uE!;1eo^W^igO9h~vy@y_qVbiwW{u)}Ja8|UD1~G5H>$Q&vg8xgV1HWAD(KT2 zqcPMH>M7@FJo%#uxA>4Mvvk1(aB{c@t}|6c%d&sK^GLeFiJ~z`q!w_+igBIz!31>n z#U@;d(j)L)4r()5dMHo*dFxAv@;1%X*0hk^49XZ?mm=d5205VTp0p7X2O`Bk7`#;1Q?S`AC z+cm`bitS_D!2yGuZuZ7=?Ogu=5hT8*stvdFD6ZC;q`q3*d6woh%!=7$a?S@nyd31z zQjv7rNBRecwCxEYztwNVEg4B-2`1d*k~sX_a6sUU)*lKnspNfa8+=(!af0l$e~0M0 z^kVtdHcmpB1MD(j>{IQN(2jT&e}|7R&+qzuKj@;#lMl+g4bscP+6Abd;^Nw7gtA6m z)!U87YAF70)kTlf;#S?Y_phmUlhkE=Ql$R?PwLrH)xQz6%`h_9XmN>}P3h+xDLYOM zJ05?nVDlyTA@}(k{271FZ}c-~k45}O)@S*l)3v`aBmgls^BiN#Qb)+y&t5Z%rOE52 z{{W-^00rBPZ)tyD%(i|I_;P;__}V)SYTiiY2*%vDM%U^X4u_#0m0S(KQy64a{{X*+ zGb;4*o;Pdzc}4H>qHBn>>lmPf%XMPdbWBKNqWZG_&AI$mukoUpmyYaiDoq4&~X) z@aMt$rOL#YQMuEnxbx&jW=U??awKv7LU>T!ve?EeoyX!-R?|8yL2_oL;``aO-4QM9 z+E^Otc9up`(Zswvrf>l{0DAT9PgR@YK~}H$@;yF3i#GeC<=@4?w!S0M>}QBWcD8GA zaD$>VpOA6J;)<-qa7$MHn-?5BpKRsznG~{dUJ9`$NL(tm2Tpp|LC7;(a|@PHoS)|O zt0uwb-aYz+xhSPqJpTY{vQ|e!sP7|*N0{Uj&>EwIK{Jb7o8fSfA#JEjXQ-)+T6Rxl z6S$e8Q4m7;lRw18)h&d;Ic$;x z0y|=>4G>7^J|nc#1-v&Z+mh(-48I|T$2|2N!5?~L#V66cCXsD#9$aa&O{dz#6<|=7 z<)tNY+D)Wz3X#*e?Oa(fv~|ZX(AIPvN)H)$bVqX}@g>R_pUD1JADAAw=m_u9xt{eS zqA&hP&-_LBf8r?TBS=q;k0nsUJY=#1+-}G|qa0LY#@A~?d+C>p2&T~NG(QR3KHW!F zkWZ+*Io^>2jhW}rlUYeVD;n-kf8+a_!LD52QS1A^>{+~P;tP!?_Q=>d5y*hJDvU|V z83gl^4_{nW{YF{BQE_E(&FgqPsWaXlH$0o%7%w(w-@%d_mVNQcTnL@4${F- zJmabTE2d9QNgTSdHJu${)%7?uk2YItS!ZQtZ=1=Dh}=&c;~%YF628pkt4QYtq~#Hw zAoodt8ILYK{c5v^hB-B%U>}ck~X#v7_ApY8zU4nYIY7Y zz^ze_Np8Ld6q)eKE)DM`6EkkfMXRxg6&mDkvN#Ec?+oDfzu> z$yV4*z5X2d!TcsJui>;aOZj5CE0F;`NX>I)#ctPT*z!{1$s6m-jc)J!QtCrJ%et_3 z%eG12gPi8L)0A1gCW{A-d@miW8h)*BZ*^;O*M3~7JY`5$PnS91ar*k!xhB$W`64j3 zABnN0zu;ztEsMlVx6N%ok{gt4$%pN@GJb?ry&8*Y`&nO7rPt(DyglK2>%Rxs&uWrS z@bk+ok*Wg9xEa9CP6!-z>&0I@xi-;UQKV}Y5y1Zdhv_^JG)U@v*&$p8b;!>@r>9X| zI&id(@A**+;QeMReQkyQ(#%SiW#E7h1XM;;_B+w8*l6~!-${LIx8bLYX^b9(j(UGC zF@ahrE9AO=f6%WtTwiAmS4@H9o_N)oex|GC9u-77Xi;pRRD%|6ot7LVl!JZk{)e)Nn@cyQM_|vc6>Ancm_sk)SQ%gn#_?;K(v3S$F+gRK-rQ%+ zol~JZkx_DSxB`AqYS5nxZ?~oQ?rA)H_2F&*0Ay_6hnfzTqiMitx-42$w+9nW2k%~F zrTCfYsO>Mk9_|!dSiu1Q0PRGh?~I?{HSgl6V~l-~;$`{rN?%f^sZHfgf;xPnJ zJ0(7~xrxH|+B@4xZRb^ZN=yk~NKsg$jp_qdR{1#TY}~O@OzM z_1H2%>x@+<(oDQny&3+M6z`}d$Cjp9pDG)ogWvS8K0A@=zm_HINwaG$-g6|y{$nzN z4t+3tS9UCXEc5c@StyV-p^y@*8?&;aDwbwrfT{*bC(sPjuE7bRp}x7)b)=ZbWpeIe zd;kjID3QKgoMQv^HN}akN?8|^zcO%yaX!%-;J*^yYYeg9MP?>&WLWK`&zBbBJjW-g zByCht&}5NYV9MvFW9l%dB++gitDxl%>p&R*9G*RB4k+mzz=6n3`6DN(syR_)tYtpA zVF0)?%IW0F(GciWiBL0udiCq~tp5P^BApj_q>^L`c-qacRvG1v(OZ=BxZXWSAJ(X| zw&;!qapP|k4-)Ek7LeSxz@r$XNWYk5V<))pk4mOV+>1s!Gfx>?&7|u|Z()BW)KQ>y znPb`k{{Sx@l@2JBII-01{{Z@eE18)YOhbCay<420tx`}-vUEr;pxU}lCT3MYP~`x? z?b5mB@@Ua)gS|7uWg1VqO_K7?Ps}?Eeul3cid__GjVz)Q>H~T_(+o3YWUBuFsH^OP z%$mWG?go`|ckJ@kcZ_aT>wrGJ>nTf%El3w=yn-m$rwR=^Vt`3Kw9v{@CDqT8zI zUKP6V>b;~lwtB}VLowVl>OkYa0CXK{XX^1Fv9h6O;n@~Mis9316Y~L_5nTB_Rc$So zP#nIMrs=mJ>Q8fZ0(D3Z4t~F-PAu+nsuGPNy?BvBGj0sZ?UfAqDm}>WU1_(`kzw#z z`2PSC*&yBJ#CUC>V!6FVs9D$PmCl*Y!p$t;m*a$zTE`%AnBqv>e6A0u!RMTF?^c|x z=)#HHMBQl}qO8(e+05$%aWZAm*b*4yuK_|#$-~F`we8T5{4`oIy7C$;tEY}rKFp6G0Qrs7 zlE5!4NzMSRGRetVc&<9KuOEnRrq|`T*01gF3dCZ&xmlo`xCB1T+$&&=oCN@G&2jUR zl`>jYqfPNdz6f0gO-_3qH{q@$@_s(f)naHm96QD`t(;+7^AUi1*Q3uIqiDe?CSnKi z3jWtZ)qE=?a9-J8N~g>*JW?@N$amUFJAfZAIId{MlTqoKUA>WdTo)Hnok~Ooc96=< z@iR9a7Bie}9sM(0xmw&&tWl}>ELzCVd8g^xnX-|5iLP$h2GYlp>lx*Ez$`j_>BUoV zM@Bg&>Go@OkS3jD7!HdL6c$c%>Bp^gdPK3NW$LdZOmiH_?X!GhZGuLNcr2jwBzjk( zot}Hq(u4&7Pz3;eC<1`;vPNZ+Fu=TE7XasOeSQ7C>pzOQ@J7E0@aFm=?yn)5_T%BL zq`AD&x1GTW5l-j=pgjwfVaH%|RLMQjra02K|&TrYP}(UqZPh%58`$=-{^CmGw(nH{o;fL2?_zD$^QW7xR6RW zMPnqsS97{W0sg^A_4$ouCb=d0n#Mo;+ZY$^k&mendjo8 zTTyh39xa|=BalTyl8UxWVC3l#-VGbHaLPb|Wp#-G{Gc92dx4yOzLm}CSIXbi>Ggk! zM4l$P&O$R?3nhzrm$w#h!pS_31~)ao@dpo~M?q@5Yl_Beb$s7mw!S1RqX$t|W9t9WY>+(+Q3uI*)l_U$2t=rTp-0yBUa zSb{!W20e1WddHlj2GusUYM~iPC#1>`i8YN%@*uY?<73F+NH&#LVnXrRNjr0r2N}hA z`7%m+e}D9MMhZO-d-aMXwVRz@^>41O8cBc% zyzq!RARUDiXwAy|9Bqzil5L?}3?A95cd#_n?Tjpw+3v!f+du~%wJlcB2YD_H#h`JL zyKuuCh4%V?da`y1I2+-w14k^@%%FKwBYs~@Z7bEIAC8k7>lr)fznl9g?)69?p6^f~!J9dnFQFyzp4(TRAUS-SBir+27oQpVTU zEEs@zMFR?h*;E1g`qy+-Dmf(Vr)n0SQ}LXiQP#GMyfZmOT?*{lU&omqG-h17Hr7H8 zRfBdQ_p4-$trUZ)A5MNEc&+dJAK|TD8_Z2Lys@yn2;13$#`}UF&4wi77&tf?uQD-| zp3e6qqe!awGsHJm+QyS$lK_%Nig#qI5c$prQ~tGi!-7;omnQ7E{v>Ksd9Y4|CA@I5 zTgs|2$i^6+xX*5Yistnxwwcj}s*A7TrT&?B;JrG}Q}S*;E_Sqga5pkB%P#T!xxrvZ z86u+>4jd=DbwetfmpE#bm7f~;1+-XhZzI+%B82V{MEUbwdgB=24^zfRyYoXz@ivX1>i0*>zO!dt>M~tH+CeARAJ^8qJv@K*VUH}GN-eL>jz3dB z{aIwhmBvXw%E{eY-qCePbzMZDg2ocjmLHMH!C~)?KK0#_G5D)2`b+mXu})7D#SY~E z0AmU9uZVB_U9QX!NiL9${{RVZB9)KjpaQsZW_h2}!QYPx!mH1c^Wm)r zOtVKfU|vfatFU}*1St96fH(H}vy5;BUNDdRxA*7jQd5_W7aO_cjvI@S4BMI~F~EZ| z&O&7M$I37O9Ax8>n%%zNzwiE$gjY-3_WuB9DRk!5w53>#*#x$G zWL8tc^GEpp4RPmKCEw@$PmezoFAk~rf#Of#10dAi&e=f8#2A4G+()0ic4{$D_Bfr% z-$9MLuzvPM4L>eQ;pX|B&u+^J;qSz|IE=jh(qqKY8x<9My~uNZ0; zR^}(!FAo!CKxGY&ws1#m8oU+7F_9%EkmpF!uQf{to+y^$7ztu{1%9Wu(zJ23Wn&i> zmiK$qICtUHbQOzCx@3-!mNM#=ipZ$#ItG>cD9Gm(jNKaJrzCjs_KpSZ#oRv`CCkqv zNYiyIxa~OX2;>h+=*Kn1B9l*>vNubTJLLFzi}cuA?Zr~5l93H`tk6R#&rOY%&KQ5< zwh?{_4INz-Q+ki2ocipuVLfs7UH z*yg;1>EGYvcc|28rTD)^)hzWHFX4)7Xl^Hv$0=~dxz0&mm7H3S<618zChjJbx|4W+ zMDUKg;yY%%*RGgZLn@uJ>~qz+Zr}r-de+@@{NL!mp7c+53nlzb;5(gTT8mh)zk(%2 z2_?MB!Aob2q_3(VN`1fkFel+T~s-VMZ9i^&d3@!=d*124pmd?1UN0yfA+f{<<-yqu%#j}99;AH#es+;9uvZ>=c z`&~m(OG`^-QEZ|)E&=7rj^2ZfRHE9wgn~>B!5K(#kA1)oy<-;CmHU>fPx2|6Nl%E_{{WjjpK9u!wsYN+ zD{B&Ju}H6l#|xgOxu*VBnWjF?5(u|x>KR4?j@8HCXK_>W7C#fs@bDp)BZ&@ndqBy!pA52Z&zyFG}R*b|+qLl=MOJ$|&WBw6kJt*F3xj!(Dbnn=SKV{otYa?IJh ztZwH>BDR19jwwEP+~)wC5bSYp~0;&P5eg^ znPYKHnb+XfseU|6$qShhQeIfx5}+u^Vb26(sQ2qz`l#_rkxU!2d%M+i%|6*It_s?_ z$XYNHDf1q^#xhSh?_3SWKPx(^y_63T*<(?X;@kM4q~E-dKpy`9)~Pj5MWeG=(r}XSZ)M@aqc}URr2GaU(J%no*eNQTb-BNOlkpU>$kOI9GpK9tnu>vCXDm> zT64_=GfF}bf&v4#9f|K#|_S=8VV25^0GUcMY_6k2DG>N333O&DMPp(Jfr#~vHe zVRxNPyIwZY!igJXW7~vtpZcou(!0C@JcYB$ z?Tv^(s1?yB<8odT{thIRmlx%)F&~-(3@D(Sk%U2?Y~a_K7`tuxqt3eh?Sd;$%YW2P@k2T`iSJhQ5fkM>{PT(IsIkTUfk`uRDRYBLr?@c)Qssw zMG~{fz$iHZa!A;$_uM-;v0z8Sof|QYYdEv))M6vBx5MJ$;J3P8nIKuI2~AI z9!7dqT#;@ie_4@*z1fje$}SUN4V~x@2lQqHdsjAD+-T{=3TcgWn=o|%;BR0s54W(Y zV~*_GB)(cFZuJQ5E^T0Z6Fcnu+^@bpE2+sNi;H8mVBeI2GmL}MteFiBb;a{EOZY&` zPYJdF^d?V}^yJkt$*4AqVTzVWr_kDcFHOAg>RHVcl30Z=8%V`uQa2ToAdC=xYR(wq zv7~F4EajESy`JL({Emx4~W zImGS3$n~H+%8MjyjhqpVC=BDrI=#-Ah6q)zWP=S5R>AiT=rNP;(!BowQ8t|;d`i(? zUlKO2sKIo}8_vNdxLs2m&#?a~j4oae56|DW%CgntMZb zP{QDVRQ%ZV&1WaF%c2?Ky|uG(V)2z$-Shrz8rgA{<=4=w(B-D{EYr;@83yu(J`cI| ztYaEN_~R$-J5505Y6p1Dqd9 zuc@CbX5N*5^h2FJ8ZkA^gT|sG=KMIysXY9u4o)yh8TF}hZd) z2PEf?)Rfv)-auN~MvT5=c{cLLXc_eljBsmsE(pv^3XmhnB8}x`EU|*yNAr3QxxlK*Nh@We9!`dOY;xLZ`);F# zD}q{CL`|H#9Fk53lv4-k)yv?*qFaxK&iV-GW#!$qWb$ zk~sqhwmIW2Db23Vmbo<>{{Ta+K6ZUeRe~|T*4|ZsN>4IKh=YOb3uOA5>5k`THcdu} z3fRC#QtHU0ZeUe&>P83eLRV)iE7)}#I45>$Z^4%Tr)VqXSf!C5bBey1_GK5zqx)^y)xUVQQ z$9Z(#>Ja|$Bwa~Q4kzP2JSfV)EV^1-Psr10&t&Jp^T&>DOTahDp zV%Wd%AIn!|#&&{9+I@K9vC7iK?VI9@_=<@QE-@CJZli7r1_1^X1J54a{`IG){{Zo$ zA5s4ROEy;fAIB`ix?tM<;Nr9AB+Nd3zPD$NXcMFBb$@8 z(ci&Aaq?Eb671gYDCS_Fz#-!UhTGAyJ*$`0w$1%KRT=675jp9ebLm_sPZ}ZarYWe# zryQSOYT5|SY^3T}4R5NKLRiMc{NK?1tFs!>$u^FjR&871PSl=Q&m$mY^!pmOk`b!@ z8F;EaCgAvgP0|?3+#8wLnPfYah}xqJryOUXJe*e+Xw&ArojB!ciFfeFhBXU2WWUrJ z+Vm`GJRyUF^99_w$W;-zZVo=)4l#+{`KW~td^ZZ0BmQu_4 zfM9W0G^^&?f8VoMwz}+b;~f$k1cy-*%O#wR<&T>JCnF#L+(0A0XFMtQ{`Jl3A;PA* z{u$Nj@^krG+9&@24{ZYYZ&|jm+%Lpxxfoo=Pb3gJ@JH!a^s&5oBM-$(`V{ptTV>sbujScejr_LuBScvNz>^iVt$ck=C>HxVdIoCDeEN`29^iUPQ3)k8=Jz z{>RThjovsjc-vX9w6a2$w{lv`GmMvb+ixF2E7^yqYEP3qndRh?k49@}a$0T4D(@$i zVS;|&=~kXPF}f$MZ;4&9Wk~8j(AFlFIrz6Yz{;M!)Urf*RxnvI2RxzmskDe=J?K<4 zVOSo9q=Sd}poT<3WKf*04ho;8N==|!w5@AR)Z@0azH69na#=29y2NVd`INBvK|NIQ z?^WYu@+_xaniS> z`ZDb89OC9P6sj}W^uYtmhTlEf!n6IeiGZ)2_zZ*4@fB59Q;p_pF+}%@d*{YFG0<%_9X9sz;?ghi2<;gbSqtGK!9SHx&Cv0VO?76%q@0@CUtWwb z=5cBX{H^^vK3~-!lIr#d;)t;G6drIKj-YXo!RuU+dZVUF*|7c@_+HpvGuugTeWw*` zd%dT3lwC=J0Pw9O$TO|G*HK*G8)mk<=E?~E_Ff`u?u2$AJ0~;NI zR6gAP_2~0TE;n8;*}j?Ota6mO)%pDwXo=ILdAu`s9qVH1#z`%lWSp?aBRxsTKYGgr zye(wzEwAJGIx|#rrw*i(D;gY2Zf^eo!z`t^)NVjBd@&BuCp#nDaELmbmKizV;8bJP z@mAlr?7f%u86DRrOYik%yG+xfv9^Xwu^F7;!)pr`P~M|InEISxR`809Q5pPD}IK@9FgYJdAbYOUKvi{tAY> z_={@374c4~qswk4(XAzTjO@}Zk^%A@3=D4|bw1TkOX?S>n^9F>_V4TM{Fn6}nc#)X zckQbBd;b6j$C^Bsb}MtQYIo2J`5o5DZd;kBeqLfRjj9>BZVM1O!N+1zo20)pn%q8b zBs{vDlgT{#n@M#&%a@jNa?IYQugAfgcI=eVbop-eTML&FO>U&S#kdAUQI>9a$Q=Eu zB(zK&O2zSlN3CnJ&uY=zTcRk6C50mk$2kfBEKW&o`Kv*wt}T(0T%_c+WHP>|VQNjR z%@lddDxL}Tt0}IG+Bv|jGspymWybHDxvIUAiywq+9&K{jCr6$87 ziX-(4c^2mO0;kMLi7GkgBpiL~WhAP?Ox6DY3be@L(jG$?Gt4mRPDb9iBOmV-<$9TO zlRYd7qF!!wCW68lZ1&46l6fpy{{Sz`pPL^~+PNLIXz5+-l<=;(Y2sZyMAnGvm=eU_ zKO;Qg_5T2U>0G{6f_1bw@fEUbTGxiBSmicWo8-W3F69|j$MTbp(xOk3kF);(veD9h z<3AMYI=ntC`1og*4Y4RlZKrLHKbeR;G08om#)Kpc;ybF-;*Mp)|43A|YhYo^=2mF@RoOq@IVlj)lDVsXo{El0u26zGCPk8?7g<`_8@dcMlC zd+_W0LiX!XfXc?o?%GJE5vsUZJhm}2A^u!~p}GP_NaC~07{)2D48AvQ$LPvjmJ`8w zBr7CRO&QwF45CHPvo1q@K_lGPM5LEzGDGb$!u$L}7Ik72=a%hQWt?1EU7BP3Mz>_H z)))i-0JaCyit~>^&o#?S%|A}PxbH5aQdjOa46o{3{*~Q|q>_FPS=!mbuBX*}D>~gu z&n!>;G3(R*^>rA+c8GT4Oo)9wVbg6c<~fSxq(F0mu7qWA^eS`jTV1^vNi@kn4B4CO zd(xjj!CSS)_8dnZKsi5F8275T?piBHL2LxUc9sEumG=Yop(hEgcDbJ5;xs$Lo;mg% z=o_NX;3w4eJsZSPXtCTyEEe%im;$>NS9}5q2Wj8S4i}PmtmjdbZ^>kwqa=!co|iun zKk*dHle~t=ZhC?^BivNv-$rD-!6SI)U@|^dBd|W*$F*dQBJ_B)*XPo8m?m=43w9n} z{{Wli_V(n|d@fr?s#IS*C#q?dAL6>D{O0=6B517;jqNdzW9J-Tfu8+q2akiZURH*B zRF?h|*5$Z`lv`Z6mfA%C?oFgG9D4mK*&Aw^5Yw{V7Nfgvl&1t-Q>^c~TUs z5<2$%d9Fz-+0wLd@Xo6j!owStFS};e86@)YOs4h>Dqmyy@O#@2SZM6w5V?*Ud8wFJ$u0ZN~ zU;=AsW>Rf*j(OpfY4*y!)|!vw;GS=r678SNK3%$o~Muc%AaSGlP-+>(O#a@%kQOi>^q*ZuGhJPao=M%aUu4BHKl^D<;yr zAP;dMCx92s+mqeBYYATnL3j7}`khcoIZj<0RkU$vuvl3_(A(QZ0E#PHQcP-~bO4@s z!QIsLu9-=}tABrfPGpu#b?3L=-_YmcsU#i~@fV)1qx?SMKw>e<5Dy)C)p9nWHvOOQ zL{f5(A9QC^+!@NIenr}$anoSOO67yOufC5$N|Pb4qYAknml+tY#I$nW%I({Sx!BoK zFg>d__FXL#mT(QWuE%hJnqo*Dlz<1^kJ7s_?IV_YY@a6L7_VlGNh4ZW$rK3`d6Uf9 zk{6GgmQV*h4Rl9aIpwuqQb0MlG1yA0Hk@>ktP`%FA`zYg{YsTc_`l4@)6qj~(y1uzs;ud!1 z>gqY-j#!nz$`Z<3CxMN*BhYb0H58(sLBY+rKO^N~jk|<|aLl6vAmHQf4Q!;Ik%Nm} zkk4=s%*r{IW^>Qb5B~s$xhIp!+YEjNvX@hHG-Gf^Qa2H|aqEwMzSYS&y|iwj(imze zZV)8%JW;4D^4qZma8F*{FmgTWpB7I<{4%$w>XO^uL8xA*oAB}N^Azw#NgsZdD=e)x zR!~W3>)~(23pr(j@FF^;%M*M+B+xnVxK;Au{Z@H z2RZwZfPKwvl1n2|j>aXyIm`4DU$r;dEc$h|+F8#&*kWPHP#A6jatQ@D1L>UA=HlbQ zc2WuQ=K4gCNaIzC-2`w(yJJDoPz(>+wN({Ha&Aqx+2TO$5fQe>Ve+x(2CPu1*y~ri zMzMQguNy>+fh;n_NHVWNNbE;^QL+}hCgj#)lJ+<(6>c{|(s|fp7{dX^IbqkH2M3zQ zS!!HOqmJU_Wxt4xr%dwQTWh}^aSLJ4vg`!)R7Kzq*WA}Wbe`8_y#4TZH!R%$Zm_FQ==&e~! z3&2AOB!QV^m`+%(3XTJJ>s5_4vR=<~UE95e){SCy{Enn&6met@?R6zE`EMrJ(Rf8) z`JI5OMQdc(Oc`PF;I{?j;h6Owr?pq;NX>N1TRVq{OPO4janvu?w0RpzFo`V&Fqi7r zkwJB3&j)}$p0!r=UNTFwo~`iqjUcvwHM=%85y18zt!EcR1WYr8~(wgM67vA8V>XCp@ zjPZ^$+kx9Aq2;X+#IZqd6`jsuvWn&#=nxcuf+Hc0SYe4h0nZ;w$0V&5irJ}a`c?g= zooS-$IuMmCrHolz!U9IiATPfp?PeheB!WO4Gm0p>Nuusv#Xjj_)^4=B4I(%oSA#7Y zfM%9gVylo24tN;)k_A~!cX?a~>ei^$X@c}zoU?*)fe>(c;d z9je&yr#?vDSt<%FxWlPj+`D8D8c6N`Mkj~)}%=hfr6Ed+5v3*jVH+Goimu^f!_Qhh&(U8v#!17%#5R^X6&d;Pl5p0-B#dPaRFB$i(~Yhw1Y$$$xw9EJw~ z1CBWW4tTC#OBqEqCwn@5RFtHgQ6*hRC{PKIc?5kypck3|X$(swi`F!022ME&NayWB zQnry1;j>|5;d?ohi)}bYZdl;$MPs>$9dVLR@6x&bI^&Mt=5%L#^6T;;waIU9^lb|I zeIE8Zq}2SuC5!Hw#4L^@l$;RJvVLVf*kZHIFNuk?YlSR%IKRl6@b$fpkKwCFc8=cN zEtcZy;#cI7GV(bmxjhF1I2EP}jwrv>!!^$=hBDsGd!%V?Aj;}U^Rg_SQB>Nc0DR?o zjQ2d&8FDuiueNnz#-k@H=%2Rp%qrJY$2`ZQ#xT1F2nW$X$@M0>Jvvc^BbU@Wn`d6e zwlF+Q?2t_H#$|Mkonr?D$OMH4)Z-s|Jt9)KN0gK;m&73XyrVOg<8uWkpVJujtg$Ce z$k!z~QX(uhR{sF#$JQi|EFzjy12A7NYqAtA$l!y|eAQtlvGSMH(s7H;#wQ!EjQ;@X z=bsjMo0oAJcUpO00W@v0Ku$qLBa<4rl%_)q<~yr>Zv?}N1q9|ZalRM z!VjiKO<_06Oz48Bqbt?ZV3sENSQ3ZW*Bgn@-iU7)Czo@iYA~r-Z|z~ZI2EXYs?YhCDUl%>+suK$2WZa08)|LjM4nPZ$Fy zisjCljA0+l=*I2JUy-2x9r(jZyU`)F)kvJIcq~vzCdXz^P%+O#jMEROf?P7M?|+&j zE(y2G3;xymnkJEFr?u*8I!i23$_SPfA1itscES5|UAS@MbNINmeWQy$T&o+!nO$_q z-xXiSr`+1Z99W5G7qhnSnaZ4z`UCoVRXs$MWT6%2-_+aFLF9y|C*qgU9~t``n>8@RVW_cXBKK}rl71I{mxh)3`Op9Q_4 z$u7lf*rZZz=ZYr(04wzUYRV2Ia*OhFd%4^NQ3S3z1v$X_Rnzw-ljwJ8YpL9_q#9M+ ztl+XFR_xgTWRb^D=~Zs}WbkNs-VfJr{MikY+s6z|DK}E2cu+EMI+OGsl`2X-vMIj< zcswwJ!_sQg-$S%#WC}ob9F5%e$j444mB4c$A$&6>E?JOe>r3kUBvCeh9kqv>kTy!kP=}5iCC& zd}NQ~6PY7i4Z%l1+5T?BisenkTJ4>BdVPKU(SH0A@dTQU#;v4Y-hB5X%|a$EF6L4n zYZ2IOJ$UC8KA+{2h4w~w$|`ly3$1t$RI|D&)>6oknOPnoxHM{UxSqqO70r?pj+*NK z0HQi!IAq#>-?^%IA4j*)H2a40BY18ES0d;p(on~eqz*8rk@Ypx>7cQu^-i7rEBkmk zJxtz4qPteB>wnzEKM;QuTT|5J_#38!OfZP!L;nEW+QHS|(1sZp>~UQAIr@u9Yp=i5 z=*HuNOTPaAv8USjsvUpBRywuDt*7Z4ZR~E+8d3KSkg9{>7Xk>Aqyw6Sc+jE+x7ke4q42zP^e+r26Uq0OD=Q+`aw2iF^G& zsfzyq>q#n)h41xm+wB$49NI~Fqm-W7ZPPCJt=Y08QH-?sN_0=Y=>2L4%G5-J&Yg72AP>wkirMo9jO_H)w78Nxh{J~&jr~5NuJmWwA);xK9X|EpGAyd6EQ~`cF$h=x0G8}xvy`27 zT_c9G6n6Fz`8f^HhCeVLdW7v2V>!I*Jt$mB6UlDp9%eWP)Ay}ZUu8=1mUf@b0H2$I zT2f?mUc3)$s=f8B%WHAv$WJT=!-XdYoQ&3aAe3y^3w)Ik*R$NNq%79XTV;L4QI9Ll zN5S?erS3S>8b$Fgn`tB=W-^cA&W8`4FbE@_bDWH0IpV1-ZYkNOHk^=}^vQAJi;0Ah z?rCLbDW;%HIq#wjqhc@!;*=tWLWZ(;~Xy1MtzS4xaYRcynPayRtLn{ zToR8fsX1Sma6vfecs0(Xqw=$KgG=x(t80HE>DK{Z4pnY^!VrdBjt4ySIPPjDKD7CAhG*Q>olrF4PRe1gQ1=#G0#eg8AAms$C(rqh}J|N2oNOW>pF(OaeNBbII#b zC@x&fDLUdy*y+~#l%Ek1_<2=J?m@;u>;9sy@kb-%w8}h=8hbH6#-|_tT0BhOl~zk) z_#AKeXty8My)4hB&o32t7$lo)jGM9)6I^fTcB7P|rCJ+yMj{!Q^khzo{^bvY;+4?L3x=cYLD_jAxGi z^|d)!k|!*+m=Yy<9A`KK9qS23S4HCXUUd7Zg{a%H_~BUX2k+bKTz9j%bXUA#r@;48 z3wxi4mmyX2kc2TZ5snUWqdtPVaLS`b8CKC1XJsl_Ie>YRnE=4!cTrYzv_w(I#5U7f z_{E^Be`Pw~(dy;wzMsZz)pRnOPJ}$K_ z7TPUE9$U!6+(_YowHZ0zk;Vt>+OD!HWVpVI4}f%t?_kxepp*x`vM`&V*bu0YGZq7q zq%Yf#dZgVn--cTnZAp8bY&;iq^M|vL$XrMuMqCzDAQm|221g#GRg^8!St?dd=)Z^h z_0bPKzm$=j@&V31ztXk;0M{}2gg1`7HF@D%s3dDecx6#6USeb^{$$TXj=xI5>P>qc zD`_&XrD}noxR(AAI!3{QE&wF(GCTIDoHnSkv`+ZCad)M7cJX|e;V?WdP;nC$;1%iz zQS_>%dM)I$cp~Yq{28g~%ZpbdEs}u^|au0FZ zu2R9=Ymjz3KTcRkh%>_%6>; zvej-;;bR&Nl1b(rm^_99y-pa;GkWNzc|uTI{EOjjp`90VugnyW%yH^{tG4?%E5TLN zB9_-$k6+fBD_b=F3d3)fE=VKhC)+(e>z{;{Pm7aFsz&^y@ZKzL-_*=>J!-;jeBDQI z(#L>6PR!F7m?Q_2w8&VO zIRmi9YVmHGOwLhCn?-}iw-TQTUi_$1Qxsu9KQfsUC-lu*)JeQg^!`dy8e74Yv0MP+0C8~^iDjcXVUPc27ZoPPV^g_~`&ykKi6dV!RhsGcE2`mCul)gIJPvY4sH?p4jGLpK<4q(sPZ7Z{ zi5Qz11aQH=DdTWVkvgB5fdgm-dY(bgYR~@wa$K&9{{ZX!qdP-!Jer4yrkP^$WsJOV zkf+LtyvJDvc;Uka9Q}=B2})_?XG^Sg4|BeOeRE}?UtY@%s=el;Jl4@~AhD8C+etad z$0>|)*P7^tZ-)mXpEMMu7_S2fwNTSD!r$=ZZr;j5{LDxh?${$W#XnHrM|3eHhu1gJ z!3DgKtZ1^G&E^sTRT%pcK&0nUv_gY!ju%r1ZJTj#pZT+#FB}@eISrgB&pc7HRRY4z zo6QpEYVe?U7_HM!M=n%#wS!H4CRVq$TWwMpjDBNEs!@Rla8uOa8r@1RKU14_Tf8%^ z+JPcLbGk>4HGTOqD<~&DFccmF*0?22$qdfok?%s(lK%k3l3rO_+b*KYVV3F9pKmzA zo{NxjPf`}N!rZc1oSKe0MZ3iI&2yl=n1oy#+ly;CK`p{dGNZOfI0{d&@fcfPEphYJq3IQju!8LUx_Ep8*6d%OxGg$F1p0VlLJ=|sq zGM7?K98oClNhfoY)1XoB)~P39N8H1&^_^o*p6=AmEHNoq?qG&oEa7^M;Pmz$wSzP` zM|*9mN-ieevaVHaB2gS@oyP9x>sim(v`*I+mp3 z`z}b?>91)dHxu8*Cz>(>_BD=3sIthh>biD=bEd%d*Hb+55UQ*;;P*f8)~P-cg3s2mnPhN~2=gJpW&w=KuP0=)ml!1u?0eM95B!3V=GOIXbv7~?K2*u`#xv+eW$>*cc~IJ2dUpm} zeW-|e3;WgArS~h$Nqki+#>&eZxBXmZrFuck>atwx7R?})14cRl!1`2hSmk8hlDb{e zS!mK)NfVi5Z_SOqhpk~b^0Z1k%QnTsurJgCcpl(Z2|v)AJzd;g$7c<=bdo8u2ddVjKg5>Nx$YN$naWTJ9}; z*zDF>;g%(lVv&HtZ6lIM<%r1oVzF8_Q6aA&foz%^>D6Us0s$ZKl~gteBn|*0fuCH~ zi@UNojql_|xRyIuz7E~wF7d|YmDjLV><2#l)||YQlA;#oH?`H)JI(7G$TDRi=xq|=sMoBr+jU`vu%4}3}P`2+q|V2aLBPH z30!~%><$4L12ueiDDS~7?6+tMBWW7erK z=*IN*(VJgU--rBG_gcmMrJRiLEyu)pgp8{3!6V#l=dbHrS+X@J#PmHqO;hk$ZEl+9 z#V+=6FdK@+7U>=}n5hpdV}w;gM?98c>0KV1D{RNq<4BS5Mbwd5Tttyf*8czlJKRc( zox8CdY7R%uy@|(grn|FAsGRd?&N2d~GJh(1F~BDv^r~QT zQsO;Ai(HW>^gMf4Va5~yc;=uGI*j+TU0l7fHrDntq-H=sY4D|;N$h~*KBVHfy+ofa zK95Jz!6@&^2dYU7dK7lLRhq2&oy2Nfz|7Oaj8&L{oDIQLb_zi~Yb7o?bhgcS-cC*F z5?A&zO{?nGkcqAIi0om8Mz@n;i^?0yCw@8Sz-be-0VpkP?7b?BN-I*sl~L)`nr;gkt3?!J(MxB!tBxqL@R<)O@zjz zci!J9$8s~luB@396|1XOGE|(H){B6B`f`qF#EZ9$+vR2~eaja81y>Sr<@uM*B_^8oL(Vb%D?=m0u`(pm zt0~u4DSb7chOQP>meFGqLvB3MQCU2(AyLNXK*S7y00%ka&YpInqR&bg5`2+m7nU+= zX5(~)?V@0>Dl~*D<;fgi9D|lT{J5>5n;hn%{20p?NWs^W*M~1xQPU&2jvt1B(l>_K zuq_l$p_g_$wn^r<^tlw1M>nd+!bp%=m98a)Pw^vFcJ|$ze@f`&xp6u8zC4avrO&}> zmzPSxUKoo;NZpw_AOpEAj1Kh3>J5xa=8?`=Z(b=OX81_g5ilsSPU=Vu=L9NeCyX3t zn&(bjXy|G@tcBF=r@xLZ5!yRAXP)W&sR%DLNiigVKQQ^mI%8-jip8lvl<172zIxf< ziRabiyNc|5GLBSk~^t_O_1l0Fe$^q)>k|83qTk`d1!zDZ7E)>C%GZBY?e@UnTCP zc<%K8h7=z%DwXUzan1?Pddm}hZN0Nhu~$iH5x4RspOBV?<5^{9lm*<(3E+D56q};Z zO|6;N;sv5x>r#l$Bb63)$GE}$!K`N;m%E7ra*HqF<&E#eF`ma&n#jS9Jcq;Y2iivf z{{Ze4wkL6;43}nqsOnNha`D6z1a2GJwo$Vd=#IQE9qgQd+p-A#s?(Swr#!|)uPjy$HRJr>~B>AZg2?RBS5Rm z5xn_hoa5%_8Lk|ToinNgz2oQ>J|bIR7+UHR+c^dsgEs4TZMoXYerVly@&UzRkwPx# zZ0L_BzDgdi;ntZfl3w^LP%oDfJ*UJ302Ax<&sxVO2bEqaU+ifN-wpo&^i*kH4bkS) zh`ZIOt?hxd)t}&png9@6 z2OF3F0CPB8`US>1iqcwxXsjPRn=4<5-Wij^o+(=>ZOz7)a{g_rZOHGGKI-4G6-ndZ z$W!Eso~x$nwss;`(`16qRVF!JCIOW7$N9PLI&oDTC$nIL!2woWWg2!{XUB8$BGwoEK=9#2zW0X-|mFyx*i;HbMTiM>~ zGF@Fvs;*IBV5t6C#sj!JRD8YgK&oVtNwjH>4Z3A7#j|T449#PxPSA}y19X<`H!8Hg zQbwJAVn$9ovwByarMpLD~C+pFK4S^VZJdrlFl_P@iINgiB(AC0-yjpb5>a{ zRET)~TV)%@5ourGch|Z!l6ezfd>m$D^RlL0@;eN&FeA4eM?E-{xo`71GgFPO`YV1E zmg?746GLd%cK%x}%o)Iv78qbpZaN;s1KPHfc`7;6r)G<7rHhNhZjSdmS!9jXbG>i~ zI6Vm+ed~iX9W%Qg*{o~+47}7dJsLXzC!WsLgph>%>d(moI3#W)s5v+$xbj9yE02S+ z5{#SV=$z3%4lJ~7YT`@D=X+=tCV`Z+QpF%VvFuZ>I`D95EGfyUbcv2yis9QWH(oWj z{{ZSse-GJtm%4=JH9JS}@Ww?Xt1NlI1N?-StgB#Zc?|JdndY zkj*WdTF)RG(J(}q;|r1x)DcHDk;*<(X)E^W{RCqyTx6Ye{{XLpCe{A{2`*x@ySu-h z1~$-_cY*WgK2=ph;1nH6&UgbA&nQn6WiJcsf4767Jb5J)yJeff`h0pbc{;3`PM>XS z=3EQQwGVR;pJo!>2rK#Ga>RmjfCpOJ1k_^G-x{yae&3aQ7s8w7R!#zyAQGd;W$C9lkD`_F7B- z0P1AMi(xmE9!L_^6#oDY*`zW^$NbYjc0G2E2XaqKVZ|r5tLfYS0Q;Z6np*d=nexSH zJNJDr{{Xdnc)#gHw1VDNmKWIn04OpcvG-r zp65rf5v9GTi6(S(1Ww?{*-|$gt0y3U4;<92OX4|K{rN8}lK4t3{{Yv66VV~Lx0_@@ z&pf26gc&XL{{VffNk1k@TP+?c(+-uWL22e0)u4`1akFYn?73}&sa4=-)Edc6v|4cC zE+l51Wp{9r!x43B>EpB#A`&tPkeu|$!kkj+TP+B=XnW%;JDL1Zc`899(2^u~a1+Zo z0IBPeG0E;p#cPFfRx>U#qnv;L0E^2CNgS(lD?-qf!*m5m&#(5au8fp96TSu0yeDaM z1p3|dR+k8*JXa^n0fzt`!x=q#*0|laXOcWy#SDc2Ro z)!I9fA-rs=BGE0jF7aX}m~-;;%$mr&?R3&*BA?$s0lCUB)Ak1`;lZlm-1wN5pj9ktis%iw2+kCIp@V;Y_ zCs4s6lXEK&H!}{*PdKiOYCIL`nB{jO-Qi`i)AaVayGCY6%Z!fLI5_&}^sF1FXHGPf zN{`|-j->a(Nehb@k~3>=Sf7=nR^F@bIVao-?DX@DV@%}BZhw(y)%1a?ejVtx+IHu- z(5$17+nCC>XWb;MIXlZU!~pH)K*Q=qS>Lvrs-OrhAwPur1GBe7I=}Q4iVRa!}+nE2**s< zE!RfrS<6rG?Zu7trQV&o3u~BCJCWvsV|7qv2iu{@^#-!ZZ=+Z$C45afyb4qe?!#~g zI5_6H@;w^Fd*SlZI>vLHbAz5LAF00H>!BXtz$B&!2baebaxYYGUeM0o&-eLp_?UxJc zM`MhAs(mt?pC{1uJR=npwpafE5X73sxo4-`%R1YC5?_TzQ6!Q6Q_0~~uvc;H#}t*% zBEGkxuu3qs*-O#%ds(%lmPCVdMyVB|Oj05<+1~NGw)hQ`Ue}Abh@n3(zyJ)xi zd^TwmPzyK_gllgq1!M#OIUF!Oh$l7K3B@X^IPyYo&Hn(e;IIBG+-=jXpbdc6u%HSs z2Uh<8`fDFl^q18edNsTH6pJEKHa%OVU(!dmU(`uy5VyArEyQJ%s~yCv40k-A{{RhI zeUTD2Hc4hJxD_XH$4cgx;x=6t9Sx&vX=2z6a<%hE=SkWy5lYvBbrg=Q6n`kgw$s6tV?+o7V1gk4g(vIhxn*ajz>MY zQ;s>!ZRd8=q@@zc5hab7X?e>}$`-Hxsc% zIKLS09h(>&^M%h9N0Oh>8z?4@Me}JDl!3&|6qR02%Z#e~RU++Cqh3+tRthzJ z=VXZz>_i80DH!ZK^ZQk@G~E?~t&KHpP2)*+2@#6n^Vc}6s-2dUh+9}KA!{#)ONp*! zA*O~l+DenfZ;d5h=Qc)*KB=JidG#$=B|M1YZPIz(TJGA%qJm2wemYlHP8^z# zMi5sW_E&}68cu9HM{#!!o4Nd^wNNFSo^Wx~I6r!vPjw?as)-*9c(X;*uW#;Sn)W+C zDHhExuoy~L_=MxA=m*r-UM8bwJnf>%;?ES=Po~&f$8~Y>EpZIyOLZkkQ}e3<$y^>l z=Yxv2d8tN;^znS`v-nmBBhl?=gi9l|W;B}V#IpHd^aST>ll-IZO>2j6M0$twvbE!4 zSxQ7Z(xDZvl~zMy53&?o*NTf}nGqq~Hpou5(Mhe*v%laetYd_?N zIG#(?w^`)@WDv$MiZDk`IL}(cBWaq&=#jM3tu+Ww_-u-{=v1g>CHeVD1JHFfjH&3= zM)q*K(i+M*%lzze#%RgM{@hj)O0-0x;zWxzyqKlxK0^kKF9(`JRP<)ZTg^5^yJ+z& z5agA4PIp&aC2M6F<|*WepkSmT?0f;<-he8Dk3;C3t+T-#8c&FKyTy^XhwwwXsNy zyJ=QfV3lFaOi!AT9Gvr(Bd%&&@Mh4u&9Yo7%_2t>jf7}mQX7H*1fI+?GCCTvm2ApL zONcF=;h|TSREUy4iSsOE3@OK^7<1H`H{}&)G}I=C;#W+yX$kzTJSQ;Z9FdLz!0Xnf zMK1a&XB$mY;^9_%nOYlBwh#zt)V9_maR;1k+w0D2M+)hYW4%t_Q$$4ngq`_E3=>I5!4ofv?DX5sPHWvm&64kA@tbz@6-FU@PIn-Urk(LRhqFe1Q7UI_0L~Z_LNaT)jxpE2g&2~mft2tVxcLyYn zaxvH5r;@rNomkIWSzkreQVCian%UJPQIdp=1|H)%sGs3w@vEA$FT_^Kai-eYnVvKR zNw>}0=gbh8k;&wfCnwYco-2xJN-23e@i!S*&ebn9d&@hBZ_T!mr^5sf&5oK#mSbhxb|u~AwVkBb6U!WN zMC=`l05=yS^)1FI@preqjpk<4w|q!3Z;#8_jx@P!hw(PC4xMSTMP?TTp>m`jDHs*pMsu_hp}jYb)z9j3s6nqR>h!o= zrlsK(-wi_*w7Qn7aca|CO(IIa2>a6s7~7m=wg7H&26Kw@aV_$aJsiJ-A!$E6b~5-=19eNGcQJNp>u$Ft(?E(DfI{#2RJ30$0E7dR*NHPHV65zei~ zhzsPny4NhDx`tAcPw{JR%a4bGA(dh=ozH`wq-PvvxpKYKyq$R0%W?2X-NfQ60jG_Y z!gQA5BgxIYd3M|1EJ6eS08US8+0%`q7^lja2d-)lrg*30C30btO`1DRkeLLYS_$Pj z8N%VC8Q>iE0=cI)rO6#w@$!cezk%*%x@&EoafT#6A`B!=Al%H^>cn7io~E$$&gQ;` zzNb)Wk{%_N={1`Rdv{MF_9upPe#$w>`y74iZ(Am~@iO#KO-lR>ucn^v17mLzm|hTJ z3^p##hiL~n#&({ZoYx$4N>>ziyit$L$guLQ&4Z_z1Su-V86+L3xzA4fiOHl}i(U|t zO*A`67F)w|q!5TBTps-7kJh*3o3j?FQAPYmcAQ$=Hq*ny*PI66pT26d*(p*P{u)}1 zXGQTIj@H56b}%bQ#Zi3qRZ`gKM3F|o$i_8`|x zeU4cxIL^Lu!7786U9Exq%l`muRJKGDG{3`mqSLIk*{(v!mb*l;Gleq4AS%IgkC>8} zJwpZcHN~0k&b({EGvi+j&26Y1QDovLoS+cLMv z89~YHPjOxTsm3euY~%F2r25hG_x_+Yq?I&%3e~cqj-zk^>(wI9+{oDW2CwL&+{pE^ z>Lxm|9p^s0=DSWK#msR8Eh_*QjAxTZkS^bYo(zk{o-J)hRE?z3G_(v*9DGFQK3rh* z;Ng#600*sYg>os9Rij_i0le_vhG*9%xm&bJFQgDUzT1UY-GQ`%?9SO7g3NK!uL|OX zljQx!H}2OF%O8j!gI3Wajb7~hI;GW|j&Y5sc1p^B$Q8jO0jkd`lcK8=T@aD}9{5{O z(d}iqw7R&K@((fun*L@;*^m;-p|CIpPwDAM!W?ZPyriblF`@W&!$8#Z=q)s>8)+qu zX&LOIK3aK7paRZI7d~Jh@P1aP_)SSkmiURm#SXPZX`{WlG0i3H7m+TWv8!N6nAkRw z6oT$|5^zV-sg>6z{5=|DT_xoWX4EbuveLB^3N^*GqF!7~q(~uY2ooweI4_)WjBN*+ zjJYJC@{@-gT&eZZ0jQ)B$*S7gvO#BRZSAh^LW3-ZJmMk&?v^C$7Rr7_K=_m9w!&jal>;;ZC^TBGayBParIE z2%}YEN*$n*!~UX8a>2PanY5BgQ3t7b;(c?$ekz_gz7pcqBeigk=OBt_D#wwLj&ge( zRx!yek&}OEn>=a_CHBhq;C7U^o+UcW!Z(Xg=V2LQ?g&D@gaCQ#%~u}he#Fc0HSeM( z*IK*MzZ11)+YHwpe9=6P#l%X_^E!I4Ugy8kv666ZUzxIepA>G&H2eD-bi22=^5uL( z6xqw|Kbc1dk;u(ySmzbVDt;gK{L0+nC&j%FwEa5WwU}>h?P2oavS?#20+>q6oQLGD zLvxO}u8dJ!?kh=tRZsjs2QFzoJY@FY=X(A2iw%vmP$-d`%$bQIMi?qR5PvBB{cEcn zR8{%+{{SA}$;py(ldm6r`<p$R*Bu98USj2s)MWR6-S_?vS*T?6`2Dp10H=fF+Z)Ne zOXBP6`{@H4nI*oM%5&=2B=+bl-B{EjlJI!WT(|C6JTUrhgDu_GwQV)s%;ebFTEJC^ z+&_yk2ZEz0fMjmV42&AaaB@_g8e)=zwydb#t<|oleXty)j2WIkES`IyBq{dE0<>x_ zjOm&!g_Yf}g!H*!xi5CHUEE6?XXc2?S|yNrVG}v^VOhAVHG}z5BqN^CS_thWXOyII zh%OVN0ggY*(OMX55QDm>%8QC)2Hkq)}oy%S0-?boozS*sU=9(d3Ntx|bF~>K+I1{5K-@ z&f4DD?p9lUw(@LNW{rTr2j%t1rdqF&efFD{p zx#WuQOk$&oO?GE@x|{f~#1q_JKanF_nBa)BI1H=8f_+H+O?Ew;k$(N;?xGv0@k3 z^Lo`Tod*rsDdOwRTSxH@m35`v?OC8z4H(=Vfd>S3JoN8Z)Kiz5L??PL-XrlNS>8co zEw1vgqsccQF(aLzdz^Dwi+FR^-K2qC)?dP|t`qlAdw&=Z_ZZF}LDZi=zMyy2a9t{0R#G0R1)S4~O3_R44x(=LtBl|{>qanVR zG_rZCD;z48867JB0FY~C-qQN#P1JP8u(+BSbvIXd5%4zofk&8sn|IFHKHinjII6Qq zN!mrq%S!UK9VSTT-=jp|6Dd^yO*T)NCOeW86=f@v`1sc#}?&@=-jO zFhgvwA?2hlLzX}P05RL2YThxdYxOy@Tb&Z}#Vw3cXtS#&&6~(2h{_vl=NSqIa0gOz z*NWwS$3snMsrZ?VuBy<0JjRg8k)M^b)Ap@nrTHAwdmq^9Np%Fa_l)W$A}z>-fLX!M z>`hVA0OLR$zi!TmO5!%q;+tLZ#*qn$k?!tefT{jeIUr>J0Maw}t(B!`J#v`$z_(Id zL#{3wJ9pFWW=BFs)E+>TT96-<$>n_+iod*Y2fB!NQp%R;7m*_v@f$xG z!9DO7kO!`6kc67HGRY@M;hGsZBNN%B`@B77B2p zL5#2-;1ANdT$_=!P@05yH?teWhDC*l3`xdM{pzh-zXgpa!@4YytPc2rjCkABV~qXz z6&1QVV(D3O((J9Fx{mC-2938U$N+JS^ZL}N#`!WOCf5{5Yq~wX)R%YHjsE}(97?`X z1%r?>GDkd~)X9xD=Prt4$kI?mxa-{La7R@Up1lH+Q}&J#YQkOB9s@nn=; zzrUeuxZ^cNmg`CQofhL$ySCk|UPdl1T~8o&5qlya3y)l$_0`47JfClW>-uQs3!ek*;Vj{g{Nzpjoq@e%plGTE>xk;M*I)Fr zB7#gIlQAo)B=&Bbxz0Lfyy?QFYjk%f$ync1NXCz8sio;u-E;@Qz5t#;j)0aN<#U{1 zk(^Y{3K74|&y#M6A#vvDv&rX}wM)7Dp#ps23INZshZxS`l6f3=u6&ESdph7H<;8?| zsT6lgu%TkorWAk| zwOO1y2@Hhx+%jrwTQHpKq9;pR=`IpmwOLE9;~NG6fao_b*jCCr(ahUr!&qBw zFT)OJuw6dl)QgLTX$we9rwF;m0RbBdI}%N3<7$%GWv#NSuWEL>u8kwJTe`$iJok|9 zPyi##1HT5gg86CoWs%z|?*4N^B-9oUAhfZ_@sgYl2iK03qzsv0v+;7kwo}aowac=X zA~nE`nM$0F_|NpIo1$X)ntz8s5;V!J3^&@U*@#sYN0YR=kL4KSrxmUlq^inf`JIto zHSxX4{{RxZ@cqQr##tkVDURQoEu5eO(42$lNI9;2)2X>Hp|oHB05uYusC-7Prmy&f z_ZKDb#U4Ynk@V~gV;#KW# zZsNln z4zF)#dsGHxDtX#Q2&%;r*%ZyZ7I){aJ!<3<`X-c@2=6H%uS_5Jn&-=v-9);HEF@WT zZu|Ey%Yskzt~Q!hSbeCf+39K#V^(fPInSj;RkdM|mh;@qcKoLun02k*IIfD@I^9hy zF)6!MSYIuH)cbo>s5hhtfqNT7(UvH=;1QEuD;q>vZ}7H|&j6M?i2UWl7=Sq$>&f8p z)K?xy&DuNS_E;o>IG6YlM<(s2Arlb9ws_n2Keb~h`x>Tl)DdFHL{^XylECAU`FZdD zl@I0UlY-mJ5=Q9Tx1rszkU!r+O7=3Ajw1HXLn*$M;+2>J6owm@ryt5PGyQW`O_??^ zxq|v}Yh=?$8{;wrjhaBDmKXqYo=^3yBgfC^XD948f=ii1GK69y4E|iNu}C-@_Ku{C z4!!Ds4WfeGT3Ews%^YsBxf>_kN#C^PcqfeDaf8V8t0_02I)Y1!iz{_EH&CYUhRooR z7BRfIz&sLqV}XO3HB2Jc_;otV55vh6yPE1q;k}3EMwcO!;C@ko$J|#obdx)MGc?_I z#7(AnJ*2q+GouaRQIrFmuEybqU(i(gdDB*H>KDq{lEvaUBD1v8^j%)|CTUEic=DMF zf}pE#PT|M{1F^2J2c2X!u#z`v-a&D0tk7(NC3oA-7@fecKg-Af)^g&3uXtMGTRlg^ z_cxltY8H~qcu!Rjo0qf5zMy3{VLv`Ayp zQsF^)J}N|yiP&d*<$xm~bWT{FwN;W)kISP@3R1ZfR#p(%>62eUr?>dE{Gt=)PEG+o z^1#UoL~DYeWOpR-Tj7mEm2I5)XUbe}NSeEyu6$i@5>4=aRCC%s+;2W|$0+2C1W^`q z&KQm>dCUI*q+-lt3dZENG}7-c^&bX_?52)=N62}jm4E|q-s;3~Sg^rm{{X0t*s4n- zaCNgtV}a8$Aa*Pe3cLlFJ%6lwK+A9XvRb-FSG%a&D~cW=WX&B4Nt!13R(#wqWD!nzt)WqBw0PLFzXQ-Xgn# zL2}XGTT5wbVnWe5R~wzN(5cAD`EWB$7E+2_yCn6w zwApPnIHP-b1)>CLG6KR8(SkAdUVgRFmN9FOvN`cNr*F$8?e6U2vYKlxt#0>C6bTq4 zNhTKnV?Qo1bJ%3o{+*=_O9^u2t-12eqj=rX{%(>*_?7x#-UnV>E zWR{_HmI3bNmOE=pYjg93Bu2oEy*mX?IO=O@Qbtfsy7I_KMWW4pEwBx0(8!i@DJ29F zK3X+BI+9fX0F{FO04^)cpQv1$k6(6ral-heBi@Y!FkESla9xskOUoY8&-s^O@A87b z(zf)eD5i`(Q*v%B=d4c*y4|!=ADTGZ3)GN*F!t&D)qPBqrxg4b^wDvHYskytpo9RZ z1W1ag2suEbj&qUzm4qUav~)^M>5%%HJbqkQk&8a_1xQt`XUd@{wBcm6VcrJ6E}w0duD;Qn)-ecYydG<-?Pn^+=~HCT^&&{s>-!;x821 zIUq}<`H{aTW2DFx`0l&&_O0>MQ*7jw%1I)ha0ToaCKTy64E zL}ZHM;xbOp z#F2$WRT*!Yl<+-pG0ks0iAf`#80Afs{d}18OUp;NHu{C!5?sd^l*s6j5X!1L4nWK8SP(pz1ZgKtc%>)KMjj@n(t*2`0MB;st565s!ER0#|hKT{+jaM1!jsiY(Je6$S_tmAcMPdf_Oe!p4Ad>rc6?y zhL`w#rNOC>iJjFFStpZGxdrkQEsz1{r~d#W?On3T{{YU;H3X+a?S9ftQ%2P-<-VHj z?d{g`6Cm9yD3b_eIsC>lSdPG`tRLZ{YHitY{3I~9gRX4st__x;;ig-l19aq^1Gr&9 z>({kl;FYB5vhkI)+O$M!Yo=+Q3)iDbr@4J)Rb#vXcHES5+i}%Y@K4m&G+M@<-u(Wj zT-Po84m2MY!{Cn&X_koxoqu@|l6}FK$|VYd207c2$9z?}a9T5J`!lO+w6xdnB)%SA z=NnL|P}w~*&jj#&s~N-PO1;e^Kbp%gi#%N={0(-OlX>D&%PO+~q<{clPMy07&Bx+T zdu93YkIHFZfZj5?)HO4u>TTxr{UqFSaeKS|tNxBZRUTNm zFB<&~H^w)*lvYJ-(UUnW(J7F!(v4?=sKcCSV+ z;$~C#OZxP1&3rr#9@qUo*@M_lKo*B~=t&V{>BYYP&QG=Eb~gRtcUWd1W>p=bA{yeIW^aYUm`hj#^lMC(DiF8 zJsIBORV8CB6KYYD}z)TmGR(Ha^%AbQY`IE#JW6ts%O%$CtWymYfq2u+f<&utN3piT| z^vzQ8!bn~@(sHs45wxojk8W{X`QyqwnbVJ2H9ZpQ`D|^P-bq?PDUapklec#jT(poO7L%IM^h=bJVzTj}_D?_m=aS7&?>F zfXaGv{*+4l?5cjnzR|R8W_e5eG}kGJNqI z6}`3f{I(Z23u`>lfoUt`$L9tIW8i1zUBG|T7uKRu;+rNBvwYpo;=Bhl)6xi}wWMk%UTz*nip~pXz*A}U^cGJ2;Zxd;k2gWuI zEv)VyI9XOq60C(^4E*3P1g<&CXT46=I=;eRJ+A?*8RhcUIL*!AA&llMM<9^~|o<)Ye1KjsC%82;6G zqLYm>S3=Y5W6|za8ffn!Ljs6Y>^a%VU^;G453-uP>X|sxMBV~91YS_+ zT~rOE=RI%_)7rI*&E#&cu*$h#zU8+C~OJ_O9s1?&Gd1o{sz9@w8OTlw_X0|r6U1b!J z6ggf;R_vgVdGxEsNkt`5ih7br?u2b@jJwh_xHRoL_eC!a z#niVOS9?5c>ATDk=Q)fGhdJbuYgE2fCR3*3XS!YKw$ybda~r&v7_c^5=ZL+1{>qvY(d#W^0 zT*u~anOn-waqpgeF;vI$Hd=o&NVQz+(#;MmZF2jSlui6GgVc9DGuzWRt)5%_D9vI^ za%CIF7lz{cB}Hh!B=g2jKW-}wj@i+PQYbpr)b`g5$+1XLDFo+pjud|RH8GP>B1+iS zD~6UZ3rJ+kIm?m>>A>{sQsfd1K0TM<+#Sl%1yx1cjyC|szo#`m zsi%^P`c&33KT>6uV?E`VjytldA-2Su7#D5sj7D-n`ANn(IlvW^H!b-zo|cB1Ew!b_ zpQy`e@kM7;v__UtzC^)Ul4Mbp$MAXpI^!hdR{2#`7{hmDU7n?PV>?Fnjc>X}mL=HH zsB#Ddll-6@@!q(Wp3$YWGu3q#l2u7=1dA9d(<<#b&r_bJr6tvroSW?Tr`_8%gmIgv zWE)Ezgfn9}=kHo7=(Xss__FmD;tPAViMEpA)i6lF;xSk;}%j9~_UFC3FyDI<h zJA=Ew1aVfnWe!%6HIxpp+X+IQrbHh(KSC=BK1>g!glbj^9Pu&3jGeeDD=u=5(5n_8 z*7pJ{Qqnj-@=RomP>BqPF_k-y5_q*fNd_p z#7d|Hj7QCr{JHl2^|WJZ$mQVi;mvT`vqEp~(lr~%-;nL;^sMs5v`l43Ul3}`H5IO=X)6)Wv^pl=6pLg6MFT>`^9PSxH6Yx3+rWyG)aTaD>i)G z@sCffZ5eq*8Y0}ZQ!$SyM*{}6TSN&Ia$L$4erG8&MVw%jvhx_C{M}1~yBO)|Tp5y2XKZB2*!;_xp)CtqG_sE=8H8&YKa_?z!t^}% zHH+E0I>9@{phEIHyN7%+V&@zJFmum(t+dH2+JKkh(kUd9I|Hk$VOO3>9+fG3vXbm? z6Gj`%-4u|sfUhd;`MVb5j%w9UMhzUbn|6ZZ&9T#EwU*u{X1R^z0$hSgY?ICj9AIL% zjkQe8h||Y;JerD4C9oFZB!wamumDFnU;)DM-1ef6hCtfH+S|(Zw|BEcV2_ZVSjfl? zyx`|Kzz6s3R%yMi$R5XW4a9c0l4?xSe-Y*oaVkbRIaA!{JG0d0sqotHO`=!9)9O)c zUVfBk@-DZ|SMo&87lK#cKfPm>wz$60(SbX)(bw@mQ+f5x66CWOWrWJAPUyir;167p zQ-&8AKghSKlWh?9H?4N@i@P~5LN?-=5smwPY;?{KLDIB~r?zwUSiA>mVz-h7xwVK~ zEb_@`JYHb7LVi_=i66wkKQ=%Ij%v9kr0o+0MyYGBXvtxw$rhg_#h#sg=BxZZ#+gw{ ziGVoY`I`V_;}{0ES)j3~qUkp#&fXo>q|~+RhPc0;Ws);uVUktHX9G9~wkyb&&2l@D$5XxWmC%|w?bG0G zOcF>~`7$$OYO-fL0}tf@gN&SJww&%X{1FUuZ{;-~2gf?c3|BW&%xwc4N~m_Ly92bS zA2BNAvB~=y?exl0q~Asv>OFZOJXLvm_IhL%cEbBmiv6b!a#eG<$+&;|GNlysUY+nM zl1@wNX^JU+N2_fT-$_r0SC-m+N*0Zp+5EE{q_f7OAeLA8K~M$?`bC$Y2 zS(|+q!dH4th0NC%Qt3W*vy!axZ$ODJ%hzM>-M1xF4Exsp68bV+ej`uVm~$V8{5u7W ztgu{O>H2%z13Q1r@|SdyG5o-iTL->s*`EZIdt_i-N-+n%|e~i49Se=kINqHr;)E^No&YtNj$uMocX_WCCdHKFo z87xOrj@8Y|qUh>zPD#GWJw6CyhfRfUOdy1fBSHz3JcY{O^MD5=bj4|oOGbGXnb%jG zUr&E5EinH84z`fRBppoh42DlqJg`6cReem9=l=loujG1oxJUDUu?2Z*_e~b3su+W) zxrjjk%EG=*#02D$pyUyO>rosoZ8;Z~WgCo13(q;P2I*y~K*lv`O8HzWI2_)b2 zjR&q+Q`GA%FDQ>sPa3|HXFXM|C-Bkf%+c8Jm$6qb+|Y-E9vkc8v+R7OE_X?v>NU)#%>ti1IWJk?`oOK9U5 zZ!}2E4=MoeJA<5kYo|Zqq;ueO+dJ6k=UUM&tgl=NuC3-W#>1a6;&hB3WymA1BBumC zTV-=(sc8Az@Xr27yi*^QxJ@pfc?@73zs2$#uJ3Ki4>Zda#o3-0^Tm>Xj&RD_=9PCO zY?8^Q!db{8%=wsa=iiU8sPwnPWxY@0O%!tlgH}6&i z6;|Nj5~l|THRj}Tj-+=&+O%n(hu2;jwbfuvI@0ZCkQIvJ?Y4!;;X;BzEHQ$5bgVGs zz_Kb%-DY4=HX_ID6TZ*>z9G&3njkLnHxuKv-$(@$ePav4RA+i+WNEC-0^VgAFxt-69PP{Rw@@Bu``CigEWWAEu zM$z)oFbXps^O2sw6$81g{VqR-`5F3|b6ilu?PrqySakb~YiaPUDw}p^5lH@PBDdwn z!T~*q80%3Eo%#L?NiWSW^CEL$T93ZO``UABS=lOs87kF|5< zQgt7v>`oj`2{|0BE)JLCxK?Kp%O#Xn=#UNTza^%W0+M%`wP8)5)H zYkvWAj^G#R^{%{9i;6iiL8(7tzpcc};tzwjx|)0TlEoY340idxSyaaWY+_GypIYV2 zmn9bZIM4D=ihNiR_tr1nc~qqXk06q<64zH|WuF%|?I0myG$b?2^eR*db}gEtCRj(!n_ z9Y)=*nFGYG&LRU3C{TCv&?n{V-Gx&$(`$*Q2zO<7!cfcMZ^d@DfV8PBQzRhgZ0b;z z0ds;+L6cXSaj(AyX)9~NqQ&6|HP{{WsGdtm^01~s2ngO6cR;{!bKi>dr;W<^F2C&W zQ;Pop@;#GYGw@{Eo!*l)3*<*(Y2{@6N8gRZOeuHZnJd^|6T7I=KQ4Fy=tc8glSc!ui^x?1w>MKkw{AkKuD}SXsGtCw7 zWW2imQMb!9HL<9`=32{x=EzJTV#dW z{5goMhyjiIV;;Y?c^2EIxAi?)*N%o?i2f$Fz3>i+;cEf`vPrLRW|gz%G-F`dj>Y6- z+k~%M)5SboQt0yiMe}a^MNh-JC9STFt=`|<1P^l!t(<7P%#yOVI5+?Z+0K9J6{?fe zQHp{}*!RXdjirnc*!WgwmhDJz5SbVz2zG1_m3isLab3`l82wIZ&y>E0Z8O4}mZ5QT zDoe2@f&ylZ@=iALM_nXT5~EKw`%Rgp;_H$O7uV2(N(x&Y({ASj%mArU!-7=c(r=bEdnP)YE&3eR>1P=+ z#S=8_RTF~P?hmzj^V>V&(PcWl)Ou?=+e;)d=W-*B!yWK>{VJQH+9+NL)nZQ*-Fb0r zYm>Q7>}@&D0qORuG~$yoi?>Cl;@p4rOqRBim6GO7;5%*3dBEf4InF(6o^bivi#j6p zvi|@Z1E<_+cDoGm!~-B~mC5JZv8^lRmN@p2AM#UXA7^Xvmp7LzK4~syVhH4BMkh7X z@i+JEj&1_#wlYDX>hmYck;?*~L(3ET59?ZDlX7J;MwOHq&+!>to_ZSeEZ}{U+6}Iq zZ#I>yM>W{Jw`RDS)TkH=2w9?XaO=2d9YF+i!K|`6Oy3kzsSUhJBEFIChN8E#-o`w@ z#f*r{8n4Vq>5+vQ&IMlzsG~ftk1$)-1aaK_~bVIyIz9x>}S0yZ>m4P7e zz@O=g&B-@RRWjn%>vCkc)0{_aU*uF@m?7#Hw(JhQhEH0*C*ZXz+2cc&Np*`k=YYX% zipJ?6WBf$jfB+nxO8cH_vXgyuCAIK@>> z*A?{*Chegl)D~NxhJ?gnjm%L(yL`e|ADu9cNY=6Lw%>ENk_jjpu}K_syF$voSS<#1zCRx{9H zyuxxY2TrxDC-o_kH?!K9Akr^}n36A)jQeC${504cbm^VI=Zp?&o}(#mPmT6TTda{; zTFD#|M|UL2F^sStSZMc6+m*^G#~ICV^4*ZWsezAW6&PV zTItikk>X}((p(&|7|wIwn&-<&n&Tv3jzg(Pta#nQ_QrEuj`=jr(WZEPNYeHcADEMl zJ5oJSvmbj=b^KwCNS?nU1xoi@i}xkOX9xBc^>T2Xbdj zbf~P{=1ZN-c{x35Vng>E*uui^F2RQ2GwoCqN!nYtm=YpTu~4jgIbs1h;}|qer=l7s zt|NIDSpNVDwL>$*3~aYZB=fdP6U${kloceB2LKK;TB*0=*o3;jsLM>clFI7c;F)eE zk)n+R00w9YVyVTKC1!Nz#zwZQ2%XPI7z=`{V+uE3$O}T!4N4hLo~*+Njg<<&pDg2!m~MJg6!^~mr87q3Lag`0!eMfUqqOB%1krfO1Xz3a#18^lr9G*IT zDp3zerD{>!U1~mKg^)Pfo>|BP>0NMXMJ3tB_RD3h#J9f=*Ot-3@r6Zo{vJp?VDuk) z$;#QHMWXdJ`v@aVH(F!o+ZSkE)nx{B#p8q#KMS=R4Sjjdz1g4#IIIP(DH(MNVwvM%CJB0Y%;jlkslR?%14 z7ByYF)naZso!nL3zQA2w$vT8QBKE0KNT`s;yI9D1{!vihv1EsDWp^IMK)}cgDI9V2 zs&k6lEyc3Irf73%wgXbSU>S(nw31Zy=k%^zxw$$<$_^3RiQC6smE2I)A^!jlvepdNH;kp*e2VI!_Z7)v z6ac`UgBTu_=Q%d*or;%3Io5m2xtey^I4mTSbFdr?h2T~)SLD?(y3X(dv7s_C~acR5%0KFMN9XakjJwO zejd;-8AN~cqmoG@BL~dJ20oqYFe~{?y-$Wh!>ua3G06k@X(s3ypKjy)ypG>W)=|;S znPOY3iDCG%Sa}h+Cf!xaslnrLzyqc_@@oes*<|QlQtn$zT^{n@>-cLNh*D|u<*L5} zZ}Ni7NGGN$R^poegxS|j)O8)d8)&i3a9u7Q^4)~YvMQgQOJz}u5tbva0L5t@QGF41 zTyz_T)bCbL66iNNgskT}gzFo{zyY05k&}=MFa&4PqH>dWC-?jvIH60TLhr-&x3R;j zYp^p>@6M_})e0Xbass$Q+Lr;56xkNgaF_tut|D7N!7o=k6nx?Re# z6=RSWD2v~KPd!XZQIbg(g5uqmO&9=<>+gv=Y1+JrbC02w2v8uD}LUKAPu5sA6N-4D24hvsGKgTzdB)Sf#1a~)C zvbnjqLfaZ0@((6iK+ee1J$ddpB-CYTq~DWFN!v(p(Zg@y7fS|9iS+#{Xrfq1iwh_G z&O0{z0N#juHBt|pU(mNwPu-H5YYX2?~@!5m;_x-rgJ)Y`QaMx|CfN`zlUVW2sDgWlZS?IT*G!qAWLNWAU&yV4v=FB|dE*%s$v5#P-JNm& z0OgJ(zl(rZuvENjOEGx@N(7yd;3|$z2H~G_I-V+hRH-P#qCGTj+?LJ|Mw*6;r^POx z2B9piJd;{Z+kDv>+^LcCfH182IqAU7R}_=RqRY-LO}@Gu>2{XWT}yLkX=4?-T=`JE z39w5Vs+W8Z%b7Q09YXV67-JUPk~yb6r~>vlJWHPcxj`L426o8jX?q%i*g zGM>Fp>sZex2IBfQjyEM4uE&~<#L+F4yg?pmH{7!^Bn1O=4X3Zl#ACKW?M#xaJMu9` z^0(|#vPK9A*G_4u#h7A?aw7EHKA{5nWu!%OxF5{e$^9#m z6WTf_9WmX+w?^~pE)r900I13xI~ZmR@&UQ;d*?&V6*@nnxX?Cww~5R5(ia9mn*j&xzDdrRmB$=@qP>CYE3j|a_P)1ObGcZ z`^J68O47`H*)jNZ4Znz#UPmFfSY%lj8Nw0s5Dy0(ao(`?8;u)c)Qwj|@wNQAwc|}~ z4ymR~aVdmLf)&Z&f^t-l0mg7^%*`hk@ANyd#{PzlY2sV8YYjQ{n_Fv}n8cBY;4bP5 z07y)Hr;PQiURflg#Vh(93leuOP0=%P1k&72nq)IUr@kU#FwBh0%aS`BoE@NmGt`RC87>XWPpbR=r$n%>Nk!Ub!KEdfjS}AZujWNP+z?1W1~|qN zJPx5y4m+C96O5(GU!ULTZ##;plha%+j*hDof(2NLL$r*?h|FM~$L4JPtFz)LLfOag z-0~G2Lf-D)18oJ=_YZpvHZsYT41sObd4nWu!BSn01_wPWj(H_5eur!!6|wv+XSYw0 zSuU*azsR*F;%MeEKfUEkNMk?>~`~Lu9PD=W?zA=a4z8LTSp`6Nk%4mDeL%*{$uS#CLg-w80dc5PQIcR>3>@s+pF@$!&2!1OE&iuMq_lChhVE^Bk`n;3pUarG2=ZcHe3r%u za_Wn;WDpKL2%a++Cu8jI)LQ6BS?7a**FKVBy_HMP3+O5n^{Y9=0RZ-TuRO5MvA|h zO^kfAj=3NXJ!qw{*0xJ&)}u-`8cmG8YRWzy{^9};3Y(b}9>LgWxhgoo=4m|ysaVs+ zIvaVP;<1BmC6JQ&+&)}H#{qHcm0b4u&N^1pYU5U~O2L{z8NPthgsN74Y%NUEl5W{{TOc8p$}cs)@hDn6F^)-zma=%(B05*-)BJ}cB${yo}QAcz8{IhoZsCs zEbnL3A|iW~WGttnNR#f}5{CJZpk-!!^#>$-lf`2^yq#IJVZ?W(TPf6HOTRsBu4mtH z1F`es3>X3r3)isD4lA1@@!;Ak*piafB(b_%g$pF9vvUlPNX7~MxT(XEn{pYU$!Mrr z=@VPs!J|g7Gb{~1mXd5!zHk-P;NgLcfB20?Nn5{iAsW$L{8ni1HT^d3)NQsfNox_o zUEWlHk^$!#bA#Mg(w)No`Z96i$Ceu}G<0T9;sz*6{{WbCpRYKsHk6Uo7po*ZF|9{s zaU@rap(G)Z4NyRP22$0dhPy(hTQ2`jSw z7KD=clEYD({$voea=LIB^ipx}-|0r1n!nfk8d_0jT{g^F_?uC`b=;-@06F<`FbU(h zJt~-^S!FgR{zQyh!}kTP-Hvk7GlA+$XCJ+6-r0;<)5lLNdQG|^3kA~$k#p3kIR5~C z)wVA5Q$OJ-F~ZkkKoGHw8d3*cqw^8;9Q~`%wAC}ur)9sxx`b9*6pyKVIrwQL(;~G8 z;r!*AGV&Q)1mJB0BLtSmeAam_y&V|cMwtn%=~HQ%@r{-=wrG+_V@bT zaVP%(Z|hga()p$JD>T~U9T4+c+*?{$CfJtcpo}hL-hcsu-Ev6eZR^SRtQu;IY1sL! z?CkX&Qdo}5rG_YAY;FvP_uC(o`W-e3*+pJCaEIkx?mM-_VsG1Z+0XX$vmJn1npmkj;Qtbv|YWD|k{dnz6XjZtryar!3HtA)KQ&*rlC|4te=^41zJ7=Z=*& z$l|<@d`Wq1liwIw1XE4rnUT5jPz7Zuyt6RRUIKyEv&k;@X%tB6(k-T*R(NEX{A@`x zWD=X0xQwS8xbm0VJ*tgeufNFC&7DoUF}<|4f=D#@E+v!BXCpTZssgThDwe<>=H1u| z=y9b>ukK`??5}vfICTpvnYDSE?o{5kjJOL5g=36#1C=Mf;A)C*%OX%sX<<&_|_P zTf>=ryPe4<4p=hseuRvQ)6_e5{me17;Jw7C&aND*gUM4|jU7n1*y;r|_@n@szyaKM zY*L?Qx8Rl2HCXifT(a1^^_1$j3eT z_o~01(F^6-95uMkyi3NjBvJw8yA|9N;0%o8IP|2J?3l^)jd=KyDRfl2xrJ?RBrcF3 zm`NHo2wX4&91L;+=DLvF8w;3QeJv$!tSYIYuT_Q`y z+NkJO61-6JS1nH$Prp5jTAvY}v9oQ(Zyk=JIek+5I1 z%`Cv+w<89oypv?Uk^FgLT>S1pAU97_S+eM|!6USeB82WTED=l&1R(HO`<#L7GgZ5E zA67yMVph4fx>-ueYd^z}I0y3!#=9hA)pAbKGI<1}jYEANXp zbKJ08NU}#N#0N|O5i&<|MQs^UbWD}WA*HpQri%rNMQrzajPgqBbXzSEj@%7}k58G$ z0OyfdJx0;Co`%QZhMj5v{9~%?BgBW zMbtXvq8DO#`&Dfcn9o`qDe_plfWxoF`ccHc-bXChGdG(q@HPEc_R`;1LWs+Fh_rSMW)L< zHMUlzwGqhi2^wq?p|%l{I`LN3=%*2Yg6=j|XdinIl;@!L^sTt5D>G`DWAMG;)-D>- z?&QW05ek#Q@BKw`=fzZShM!}rtGRBqdy6zG-w*PuH-B2m!P1i^ZrRx_W_wwcznFZu z9Fyr)i_u0#NpW(JtWnssYZv^|{4uRkNp@u2jii|nyz7^WMZrR9>rRT0a$G|jjD{q3 z^sc2A`Y6ViR~~x}tF&~*X&BdKPZsdBrSbfuCZ^>&8UZ6dN`Cz!kg)N}h*X<99GJ(6aywYJjc zkssnu1ayxlzolit%Gxiv`qv)0Y`=lIj(DwG%!Emj zcuwN1sX9b7RWAxP%XvVB^gXM-JsC3R0V4MG94(xd#4M4OGVb~LUT{VT$FJ77Clr;l zp%QNE9MQ!CO%x8mI+?yvo~nPStXnpVJ)3uy@rXpi5xhr{vyXF{qq{apleU9nJ-ak) zk*)&`*<6oN=sjw$x+aG<){P@GT-#kdWGcLtcHU_uDGH#H3h;4}+~>7k4`p0zr|VjM z$+Ek!guI3;ghmf+%OPFABINYI9V@OA;_aN%h|f%0T{)ti#M=?hgrfDQTTSoTD zG8H_0!MFsRW50T=qM0$36CNA57B?2!gfq<)wo@o{P(wnyhqf@sfCPzNORuDRDp;7F3S)9#Vra|5=T^0mIkVH+ zF==%c){^FP0!J!&hS?PvqX^%Za|Rh45CUO%65H-)3ml7D9tWU8~2}RsV>=>V@&1~~2t@dXed|%Ly z8s?p=NvFu(S@ML9acQJu{9v*L1R`)O;hB7~1)~vZZj7 z#J778gC^#ZVmOTF3(igs0N__7lcTCM^dlq&>w2sC1gpr0lIj?6NAqOo?Nx-5m6npV zM}2yDZtnJZax`q z(p)5OWe#3R1;|~^wNQY+Aaa1`)DHE^rlWRsP7YL&WVCBtD@caOl!>84wpje##K_Tr zagSWFKYHr)`4ki7^f`0E&Ps;br^U8`cK2%w&nxXfN6PM_bC3^Z$OGtW9L>CPm%B8@ zN@^>><50bCh=pJXWR)fa%$Xsbg5v<=b|E?KkF7?0zx?3^^(O{8l%)QHK?!IcXqxBZ z{PNNW{{S}BiLgF}o27Hc-{=00hfDIW?j%yA9vIUDODVY$kYbKZ78{*oi06ROjtG_$=j<_y zxMeE%`BThNNj*At>w{f59Cv0JxoU>`9lY_w7>Y-_c2m9*#Ow_koCZ7%uFcoE#wsB+ znG=np=l=l2%aIr2o&D@XsVqp)qH9(#j~*Hs+1R$M<0 zFPBi%qO$WXZFLY@NM)Hb9HVbBw|+)(?~3Qo7gmjM%XDm(m)c*4gjU)#7E#_z8SJVt~$8%VGXO2&g zZ^^W=tcfSm@M`)N{{ZmWB)qjTKKWeXv%fhcj{OC7;cdmas_*qU^Dmu757?8sy^hx1 zKp;v~BB?zI9Z#^$Z9J+G`j|ruvP%4S_xX^XI@M*(a9I z6OzZqFMr9mrG#EiQjUy!!?qC1e;iO4nWVXyZ)QRKYl35lu1<5a48RX|?_7|LB@6fd z$8_b}W9PWD)O8iRNReW<7Zb)7P0bQ05tGLN?`0)(gMprv(4|WJZT|pcIYss4^{70; z>r{&BRrsrU1YvMpRk=~+@$(Ur{{Xc0HKe5{$ul@cDw-o~ZoW5G(yuRVc0z4lL6T%p zcO+`;&4IXl-zgmK@0!9AO{qy5xU`&8J6n@Bvu$k?O9_>x7URiW#S1A6%m=PA3CC3f zrfO98q9qzzJS~{A@L^bPB75Dx;tO!Un=0v(^xe60p5B#eOA>y2BHPJcIy$x7pW_iV zxRl!1!Ma(&Vo~;N^1_eHz2B00EJqwQZn8!{p_7A`>JTzm>Wwbq_fH|6A#PPxIQA=% z#!1=;2lA3@6!^;DW|CZ$csLlO)UCb>Z#4{eQpy$FsYxZ5C9=JdMt-24r;OzJHlMk4 zxT{}uF|xWp;>Y5w=-l8{Z^#1<uT1;{@V|XyO+-E@-pM{ zt23_y3(Yg}2TitXksR>c%VQ%I+zR0G2dfMaed|1tzKDaSUi?+zTdjA+nw{mHwawHm zD~Ox{w4N1}pU@28`(v$hO8z9ARqW`6aE~WiB>X4fD-R6oa$M@~9pO-~7I}>jk%=&I zmR>XIoYspPPv-0If2Wf*Dqkmmf5_AE7sdWhiWcWexsG^Xwp5W-%Aj!}bPG|Ijt6Rx*kUuXTu!u}lE?)86{mHmur z#@A21xsj4lHNCXk{Mh1cq$-J60DX~0Jy>() z@3IO)cLtR*?K(lKrN4# z_2DFkPxgo!39!3Nm#xO85?yOEb{i~x2gr%UK<4v7WP?e#$vt3Q=4;Eu|RJyp_rw;xNA|o}_?sM;*uBsa3f$>*!e_@eI0c-klY~FtWT| zhESZ~^Nsj{Y#amJK4>a;zkg(H$iG${3t}gBi_P$^5PP zAtkholTfu?BU!(R9bPYqGp0Hi*;gcE{G`85xUS66ik%~x4c5p%7R~2Iu{M8#mJQX!Uq;jhZEmGc{M9l%1lKKQOC^mimZn^1d2j`b~?C0MpX@TbhN zIUgWjc>`yTf~e%vv|TGy#=2d)z@BuGz0RdIs}?)VWu$g2`xqW~515nusxUdCf7Fs& zQp}q5rk`hM78HUY=pW@!znQW*&p6K=&0ix;sKm|*rEINQS!!No^s&tZlBANEWGw4% zZeMN{G0Wf_o_dk!X*qnnd?5(aZ_6HCO9;Ny1-wrnl34u9sbgYUfH~TEz&pk=c?p4B z@|N8jDEVaGsuFgdS+OLohENU)uVo&G0Dnr(eKyO-RCa+?tc+e_F=X7}W3Mf=f0?j@ zj{MZ3MjCtx9h@=%%o&mQZs({Ww{AV^(~{#>RxzfX4z)%W8kCQ##}LxuwJuv} zX%6wUudz8i`_!khTC`bv)F%HK~#kI61-Q- z*Y9qKmg8*9gB@IeGD!3sRb#0+64j%gh2eQGC*2GU46-Xp{AX;i&rmx7P@~IKH5Y8W zYxXhNcxK8wW0^K7Vym6l&*}dFdc5MJ2&6=0+BHsznC~Mo%?Ovv6PIM<5;BURvA`UR=REzY zs`?D!rd&Xu;wvb)+?KI2<%1w7+_pf^%EfYV{$H(KDptySBZY>V>8V>sBsX&;meK9= zSC1q~Axxg+43qb$ZuBCzXRBMCLG>u(w$kDFCZ6izNiH(Gqm`8h2cQBq#sTS*-l4Us zMU-9a?c!Utwz6w$+nXC%TGU4zkf!fE=c&(3ZX^Eyh^wdWW0pxGi+g)-rfKD-xM`wTj+5k`zG~ArEh<<0tD@lz6riv)dVNCJ46R z_3Ck1N#3ZkLoIG8e25j09mJMWcmPuCvLu2lXd*!Ff;VoPc^K>}_wH39Cs}_dDH#BV z!DG({(ya)l=+1qTnm(m1qzOFcJD5l@BvPhSdyH~9@9k34TP6~sOMac=D4~k({jKD& z3X#OF2IGvm+)o)e0DDw6(lv{WyJX+R+gj+%zZG!vD+^Nb<8TC%kjJM(%|seT)26gh z7gbALMj37AbSlgc0hSr)ed}o7Xy$H+4N0EkR**sQ2$QjI;_#919n0Ct# zg*-oQmn$pDAe~}nC`V6m>s;A0w&>}{jU{A;hok25d2TX}WHK;4dFV4-{JD4F(}Fwd z_j1{*h#V;cf$8s3yD-SBq7EyI>66a5gt}msW*?h1cI%^A5SF7(j~g04YsLa@OfS}dc9E24Q2+sJMsRvU4jUe%1< zveD4y&slpL_~)}mgzdmPLl3Q1QM7Ft(=L7&ywffV4RbcnCRj9nwiH<|Tm)c&fCT1GsKuFi0Yv>1H`0bMli^ za9&YmA>N;^PXev1>?4Ii$;Mdr#%iwu?G8jNtdctfP`@$8JJ#z(3tHVGT|^wp_ZtbC z;zWdZ1W=qGbYi102nNN2h-NDYuy{fl(xD-8j~Dh zXN>I;Mc5Jm4e7^PqkiVmI>9uCUC~G)NWcYHe{!LDJR$$Rvzqhs*cL2M^wX+;-hmd<`wkxUwOeP6^*CUigo_HKLvtt? zAxJqThf~{;$*tB@zY6~VXE(z4W`&@5cGFd{vzF;5m9S03Epa4Dh>Mb{i-K70827GK zk@R-M6nJb)9XH`;z0)j%O*D#y=a7a`I=;e$W0W}ugTVxzDsRHobnyZl7tgx%MK-f(+!SaETZ<=X!MJsWAJ z(Bk$qlG9EuP{|$alMgQuVT&@i%6?p9jD7o67fE~n0Fu&U4~_o-5Y?|HyD=nQT!{ii z%r-VeP~;qBoy3BD4`Euvdohz8NfMj;w~Xz&x3hmLXJy#L?vMbu!7H4exE-n++o3~U zF4E%HOj+*dwwie|E}$`kDoW0*eo^SBgVW~p6%E$eqK>vj-r1MAOIwh*_=6PJgmD}1 zMVu}_kVlm~a>V;qi&~MLUePtCTrBZlvr4x2v$TlAX%4Zng2+Mi^3{O{8?*GR`8)25 z){jzJgwy3lxMUOGBy&j_%K(80T=xsWKKZR;`4xI+nXlpyn62U*fhN~KE4vJU2e2Ql zZ7C$EtW&X!k}9OifsW|T$7B4#IM4q8D(Alj^d*#w8p7%%DQ_IJ#S;=n@IWMv=Op#2 z-Bb4246#{U+d#Th7ZI6aSq0>=k_mU+GRCByo~O6UD(X~{f1mPE#k>B4ySXIPE-fUo zibZn>k~8IwBvXYe?l*k}YVuoDipL!%Y-{2))9!pRt6JTp^1~D@wh}=qkisLv@-!+qy=G?xfyc3F1 z`hO%RgYEtgPqs_QM&TfH6f9VyZa6}E91zS;r`E88-@eX_gVSu6_Y+-P#<9s}T6m|D zGR?TDXOJBIfjs~?t1EX}ue&p}sXrs2@sx{9x0+^1V04rCj#Z^9A929O6DKYkoZ}d& zmPX>Sr=&z+l)1IH{0=T9K5|=$!f}TwwJYq_?y$ zw;wWsIM4k>xD^Sg?mida>RHE<;{3AN;H`H1Q@w??NnAIasOrnLL$NEg52k*&tNL8h zoYyz!`O%-L!x%yEUO(ACsG~ltVIE;(xdn1aZ%^MfY>M)6BNIyxF9jdP)7!gAqv`7^ z+1S6Ebu2&v(i4uP4av1g zN0!f!tU`dGo})aUQU|4F88qqmqU~DIGOUtHCy`@WVt~X8p(Oz;`F8X2fX5v{Bc9c) zUa6Tlv7WPIZ*iht$zeCc$rX^B&m>?(Wb;mQ(J*Al?|>^#Je5SPwAU}c1FbU9X*QRF z-KUwBWV&c3loKRw(-LIpT0<7jGv9&5SC+krPJ6* z_}o)}AmDM%I6W``Uqv zpPI6Euix+On<{iQ-?G9BaU^id9Eq|?@EHd8e=)lM05f#;$J##v8~P|{_?#Sr9i%DZE>2d!<1G?RT9`$vso)S$S&kOMR26pldJ$8qdA10DFNU9Lg(ql#R#a8K~wTyqj*GL75U zjF33TsXtnny68QPZ0>x!wFh!^V(i~B&U=pB^!nAJ_8QRc#k{23AW(@QxVe6C0;$J6 zixR7!txqcN^D5Pq9ciP{HLW95K|FT%N&WhXsA;;#mrOmeD`tZF_q zx$xGIkhPRPWXNTL<~j2Y2nPUTJo4B$>siWDf~x(?MlqAN%>Mwy{wSNoJ|B+ib|OnT zcQ`|XBu?1I-r-0bpK8fm<8m(AUxa6*XxBa~k|-iFG_r&uSvU#->7Vj@^s7lW=`FDu zru-UzhdeW7;f)q)H7i(+)u!vHr;Ycsg_lo7Yc1BTe>xRyUU|X(%EWwS3qUtdI~oXLn&!j#o)}Cn8GQ@F*`W)!omZDk93Ir}6-Mhl}MP6({7} zatZI84l5~1sXKjtZ|rLnxUC$cYrP~V!`cvw0;ib4W>oVtBe4YKScX%M3CXKNl4%ht zen*j+CW%lZ8+X|WXi)ilsW?!189uqjFff;Q2VnZZBkA~IOhNoa(jVQj`YcqFJ%R^cTn63gp58~Rdxe$ImYHO zufNO1YvWAK-$f@}w70s_?)6PZ+Gygoo;^+2uJx79NL-KRc9lUK0fXFNut~Q5rE;Z7 z4RmcfXsm7ZOP1c3h%QWybMySj;ODqupQBYJU6T%p1=OInm67*G%%pEs&p6=w8p*44 zUe0T&N2+i|grj{w366lH=o`Hg_e_rG-*i zV*ykGpUMv0V0PoKYSK$2ntnc>KO*YjtZg>0735mv8jv|rBU-DW1xgMuI{}ZbYba$> zl$8GfG+I!kxc;Vn<9#0L($i14*&BRC!YGx&Oidu%1Ymw)joD`7(>3TqZX zU5nxb@18@PF!To>+NFLgGM7bjO_ED3a?nSe?|YXap}!&{H)VV{K8I&YqSwrguIemrWunV<;=79&(c^1%A|En6xj;9eVd_Hz zpL&T&QbZ`VC-f~^D1zt1_l4z<-280zY|)RA)H=JC>>@2sNCHuh@F@+RD?9!Twh zz`*IW3aj7fNc9XN)Lu_K>2QqRNl8jGgC;=F1TFe9|hY#J+herK1;-6L{i z86|gPsT^dEq*2>chJ@53c_9)+vPLe*Wh}WeI2%-+fGUMh4mtU%TXI%9V;cmLJwU)q zzR5&R+0JlC&(L$vwP#f5wdj`9j4uqs&3MCNRhCSzA4Z;<+S6_51LfXd7VX=%Z+p`G@L5&b$1LwYSa5`rd z34FEpqO#i?&ff#2X)p^xak@uoXPLsGD#_-ygD|>r;tJxre2tFWx4Q6elCp>UZ zPi)qy)Z1S|ja+EUe-UA2@g|?F!s^d)=387mYQP(aa9Oznvw{Br$GvX{c-nprJgTOd zEvLI&G+tO%+{qXtsUT#Z+OlhAuq`Hd<1sWrSzC{D$A3<1Ce4x7>sOZA$`fxGOSNVa zIXyOxFg^3yt0zj=WUkLT4D(n|0lBntWEl+j&KQi5_321lbkTOL7CVh(!G43`!mK0! z6?h}l+OFqP=&FW^8y!>pRz|hj3j^jIi;OQg8T!?uE?+Aud9TYyF1* z0CCQv;hidIuBW$#OWV6GJhDYIlNe%fhdss#Zaa!ElSWx$rM6~cMV89$L8?I=>p1|y z=Hn~V9CY^2U$L#ZQ&e*-OUXT^=yrBWvRXndrck5^oX8Y+$vkfDQ7nzSeVa!TT@vr1 zfQC~c5^>l0t0_*+Ry0Rzma%*^D&sGmo4?J9vUk~>;*kSpvE9vZoFr&)uKe&ioP9ki z@u_IWhgR{r-9;9L~FQwyL$W9(N?x)(I*y#b1lU8 zV)6)7N9L-lVP72-A6~UrG~>mh(d@KIeQ)ru4A7^YDGV?$xG9W&nHlTJtSuc)=&zkB z%TO{p+To&JnLM9tR*}gi_)H{M?yT-xSA{N2hsjkd5kHZA1$0L*$wn)(&!=jw8_67V z?(&ojk@GR`N%qZQGp`(xBOSuoTW`+!TO@~U zw*&L#dLOMDQC7&I-koDAe2eo;r*`h352ay~B5u)Sk9yKi8!Ow)#z#}RK=0{Oj!|yd zdMj74PLdOe1_lmmvmBz;8Meo>>oQBCt)6f}%O78AEOjd-v9+9yeI>P=pDaM&m0nF+ zZ9#Go`H4o*u5%>ug!pJr$&-wX^)-*hQd%zKL)(juIi-bUg&I%*C3<};HOj8Y(Z*d8 z>M13-wTd>4)a}8^AEjD3bdxIJRc4K%a<7fu`OS7CFpC~y?l>9dq4Y}Z)2uGu+B>O| zJ+sNYD#VMh249#JZn+-DyuJ30ghJe0+cnEe2G)5ZLM?-kyNK!t1E3#j(}gYcT{2Hg znpTBlL<;HiyLH^h*FN8^bL9FP<0rKEip>a;GC=vj$o+nuD-&W&lCjAVBmvIdp}{2c z^{BFFgS~<)aDi;f;)7CTp%!BA`v0yA27}V z>NDQ9PN>1ei@5ORnvaNCW119gjOTy=9P-#0u6y3MUVXK* zx(cA1B6K9X(zIyhnglHqrQ~o#00Kl{q8;5!G6sF4sRVJ&S}%9{{{Y!`yc}*?D=kvS z8KyH^h@pMk!WlfsnU#SVC*_x^A4)wmpU|V1lcVZ)8fLE?mrxmEzYQWpvZ4*D1V%E) z0Z`zOdnq}|HEM0|@BI{%lvx_L*HJvTUKF>7SDlq&Y2x!93oW1^R$Oj4QH|KZ$-z0P zSgG6niaf2ake8or{{V)`k>Eol<1A(&%%#hi*CV0H&T))Zd~JR9YUOd+12(A)YPw;! z)OE=gRhr@S=nS|ikX2X>qyYHGI3Q-Vjwe+A0FxIlZJzukbTwPaL^+D_bom-69G%l< zJR_5UI0GF205@8rjd%B=*reRHObA}u{w!OpQTZkA0AkEAna1P8fgw?z`8nWLO~pNX z9Z5E*>Ed;{(zQshCABffZ>S=y<;;ovWsRg@z3|c@&Q5XCw&~jOzwS|O9PS~G!$}g| zNhFsxa-mt*F44JHAppnCoy4DA-qoA5zNDl|PVqr&9@v$^{{V{EM?mLk$n{;gHMAs= zn~jy5Yh`)nX2UYD+D>uQ_o}&aG>W0&S9tB*FPP5zKnJ16B>Hv5R?8f%g6xhom6$>s zBOG#AWcvaDs7-Z!5I)hqCIet@lt}X5ZTso}|()nhjbd^=Xfj8c8HD zq~1>G@L8q-i7GqcoO94&Ppw{4<=%>&p$dgs%QDg`F)V^5%`X^B9NTNAi*! zCOsd%YS{cHN1H5OE@7g0V)&UJ<5sxQ*5Tx45*hBECL6LaenelFvV~Fr@4P2@6lTo0 zz755DjC?Dl+-Z6pl3KsdECHjsyMdU9=TYW7o4PRsBMU6Sc(FtAAWDZ{!td6~&5S7-<+}hbaf(MMI1dN&4o}dKa)bnzaLC1_&^*U;dt1Za@ zM+!$236K;jhTMAh;Ys>uy)sL0*g;ZOKwJQ3W-O<9F56qUAM0H5-)4)W-Mf6zfyo4) zQBYYUp04QDGchd$GRm?6*pPp0e@aQ|vQi!CI*fLf_frdSOR$uTeqf`5eTNmMIo8oh z#>zgY6nB?5Q_X_XHrFG+$^k!qYTTc>l%ujE@lRNi_B|Y{ZkJB65KQboW-R3LJ%CaB z*JcZ8oSFTM-$|D`qGhq>t|Z-8vyE2lAwOBi|cjenuXLAGa0F zo>dcEQMnsNkF8tjQ%2KGkt&(kl`fzGzyWy!wrk2#;O+T6SuR>H8ZN1#*m!C?$l@?X zsoh2+RmS%*@<~3N57w#iVF+^ff59IPa++Sr{`xL<;@s)+%N?9iB)2O%tY|nXD(xrt z=hnK@TrEbe-}GvZX(>6=mC~>3o&Nw~JYRPfg{A6x%x5=HM8Z7tnF+$KJCemlD%lc) zc^73cw~;Jz=*Ijz6U`b=szRY4nJ0M_{$>Gk<@bL%Zmc?oz^*ivCf8k^@^8nJy~u4U z&ry3EXsxR>$$J!)cnRN4SdSEz!jBK2yrrNmJ{&iO*nH8LOvP;gox8*z%GC z;q6QaCl{LH+$=C4+^VY!EGzos_wCnwb4gs6;{FV!7TT`^g`QizI$LYF1Kh`KH3Am562$C0)JRq^ z&dbRPrBq{#?jxl+)|ceJLR@xp)MS$DP(yMic_T-L6BN5+jZqO9j{tzrAUNoDj@38Y z{XfYG38*Ez-Zinf5m}3P=XjzZv*K;QF+3=3%-{jW+;kL@O}*>={{XuQ>*{xHPFsyW z+&=F)h?V0+A1T^?Pjs+y&ZjJsQgI4@H@HBRl z81LK7wTLt;5Cj<&hC^pOa5`tLZ5%%l)cP}?Plq3qvb*@7;%2*3WfQDW%2$MtsFiuj zfz%D5diU*E<&&4qfqxvM3^=J#K3_9FRdef`;Ex0W+&5=$I*tddRVG)hXq zOowWKak;QC4@~8bYKhyvyZsA2Do0qMH`5LvbRb2Tp>NH09$Kkb)6ZmfEL31pZm$Jr| z>-lCzMKJ=WkL3fN0`uCEpEaewzw$(5#ciE+tMaovNp90!Dx0|^iB1**On4;p92|E$ zN4;ZB?!Qw-qn3}UK-R%7nlQz@tPB#w@IPuNOJ#`}E(NvKxRUJaHnchRk&E{qLfaQVWT#^$Ux6qmE*rv;%NlsO-m_R*G&bS}d`ynRNU<)SFY1Y|DK-fRv2R z71i;;V#AQ!WahEQK2oi}-5O+78za1BB$n5x?nc%fmhik|rAykk!Bjwa&vh06# zD?%eIM2ie~ot2A9@qdw3Midepl6rl`UrWFCLEB46MvZ9mCc<*jtFT2@3KYHv{aH99 z^PjC%eiYdrXz^nwpYgHXT-q26zDa1<$uhz++fF(bVsH?BdR3Kl-`{_^KcVkSgUO#s zhU#mG-Xz*t3n+DxP^p8-0|EFx#~7$dB^34l0A%jn9_=T&gGi9w80MZkdxVj8E+lR8 z0RI4WQcfxx;+pTVR?Yz2OYksWdA~GIG6YPqiZw+q^7SVtf!K4&HF&1#%Dr6;eDh&* zW{R)6Mw%&PiEv>k%34R=kO>6xeSLtbOV79Y7C6<#wWgZuJR#%SBO6|L;+yKwhu=-XUXx`5^T35vCEVhR`^4#%` zDjKloilekw48BHU^Q37WNa5N^l0%J)@6c!3sq9#` zhPWC;jddEyHMhe~W7=EF07^Chy%>@P2Xz^&q^0NS{mmC=t7Tie>t~eAEjG?=+>B9CcmFilJMy%G-GeUTW*b7GDGbOSnvaI3G2Z0rmyzscpu)_ zMXAoZN;2IUmPkV`SNQ4ya)9zes^p%8kSbQ)E&l+J>8*_Bg6~EM`d+Vc))Cr6Jl4{~ z<_9ct0ulLeNCTd^sf^c;p`6urQ8oVn5sg6>STALgIF;g#DO5AWHx?`EMo(X_t#0DX zIU>VpegK9Gh^Mn@KZ=mbn^eYdS847uo=s;Xc(QFK5~O9YbDGKRnxt1eOLCBLBxUe^ zVn=NDts>Ge%E%oy-u5WX)bfZeW&~QJ09tj=BaY**HM5TtnS$Bs>fNpwF2Y7S3Z;`M z*$scCDoiJp%Ht$4@9kPgBUM zdS~DCth`aLgPpzkf_9AVJ;?T=i=!sasdH~W>yaZFNdxEUx6oDTuKP3cH`8riTib`) z1GZ#h4+H_gqkO4*8{^VCYDPh3#zXuvI(t+`+>prrQWfmsmJP+-mLZe_p0(Dd_H!~m z<|~AiUOC7mK2eUI)ud$d6vm|jC+>DdG0}?a;0Gi7hw(Oa`6~vHv%1VVfFY8907-OecFmu$3SGGQAlS%0oNRhL$g8CT~$?|7tNsi$VM-+_2aO?bs zsN;;Daar77=4y~=sVs7(y~J__N8ucPRvk+Yy{n%l-7|O=h@?h*pb8f|fLvuej(S!y zH%D8UE#tLEk(p73&TkaD@tKKy+vrV&rRj(LxKF)Z@`0Ey}vlo6$tnG37N$PmdnTqx8He3Gy3Xv_md1EZ{uIsNcWr{ZhA=-McP!GLhpK(W5 zr++#$EhoY@_8LyDCERNy(q&<2)Q5>Y;)?m{xR${741Ft&Nz?oDR(Jd)nBv9cN7S_F zA-jztg*?Xvb1%#DhB(Px#c(r$v}B%@3Du-uiqj!3Z=#1;k~@omzAaGQo!JTxl$&;r zHvmI{=)YRgcruZL3x8Lqp;m%94 zQZEczSm}#-Jn{gD9%(IaOn(%koE(y%j1ULqZrC-7ntJ>H0JC`D5nw~R?{uv)AXC^kvD^J8^{_qlja>b zWnsAn2VC=>wO1$jQ!5;Cj>+3-;1{w%G_j-+%MZk?g;8UP9OYY%2PZWYoU8Kvi|s2o zYPRtC+NH0=MKUaMGr;{=so0od&KxpvjAxpOQgT<<_UroSyj#`%`;mI%ix}+fBEOzE z;gZ_g6q@0Qw|9;;Wf>h-K-`mz00#oJl5bbNdHQeq6;74Ez3cWmUqX;+cg(Uhaavzn zpWwFO$7_N!*ZEh2)~e|z^rAa!^&>8$adOJjZdnz~n>h?g&t9MTsj7Qqt&JuHAz0&4 zxVFXr0H*`yKT3x6pg)QHh=2-rmfE2+lgCg!YS%-to|`7yidU0;I3Jl0Db%V z)_+gGA(Jz^T+GwjLlxhfI|MHyM1T-L3_v)+APf$DvsSd_elPF$EV>^m`TB#)bqXvg z<=dp2vlDF$aC682vvvOfDaSQ2cQ3js)~K%Qmg3(^wS!>-{^~g$S&#g=CX!8zr?~>( z+ywx2u7xFkp`9__yE090a}1W!wahkBJ6e}uHheBbZgNOsOMIa4KDek=%h)GM(Dy=X z&;FH5T~_u>jauNmcLvyQC{r6iQTdfNAZ%xjdQ~#CH{od%)s$Y6%e}=o0 zPrkH$w${^Iy|FUMx>*Lo8)zH_80vGLxEQUWCm7f0XC$1E*G>rH@8dBw!@>p1?NYl? zVZKw>gl;j;Y836a=g;Z?07a!5>!LdT7~#{>P_tWnOn?|+oq_;(0H+`jpmW}*{x|MX z_eh9`cwkpKD}Zsp@7}W{eQRd3GDj)S@JVFhjxop6JXE!1lcDCP94QJ(a1~=DUI&D5wPXhFmD3X(qUxE<98-n4{w_wG`1GlO*_+mh@zN*UOm z+2sEKTGEluf>E=JBXVSH0u!mg@Dd{48wZWO>vm$U zi_eEq?CfqeYY63-6(q!@pP2U})0*@1w&h1|74q3_(yfe|qus|8)4~~GjR-7G(5l0Z zpdNa6t{l4A*N)phjI+=qwioA0tUg9tg++}c+LsN zf6ZD+a`~U1^h{lRtH8ljU*Fpu<8&HaOce5K93~2Y zTk`zDNgU)1`cyq@?_a?U`64w*(rGSiksT$uBHMc^ff{Eeh#4f{FaUp=r8Om9`VDk= zww;XA$OABWPVid>Pn)Jd^rgMDO=y(2b!o2}=;7MjDsKF-DItKzI2h@UxvH+)e#H2r zoz%ZHSCYub%$0ndqvlh};~Bz`zzlX3Yr2=;u?=__UaQS4RSrW(*Ie z{n!Jz6=fdSHJb1l8JM;tZ2dSte@aEB$$cD5LfvyIERmAP1M#`WIX~~UQPNv3 zi#5a+*qR%dJlLaVjdw9$D-mto$I3tw9Q)O;i~Nc;Xrz7@4~Ou_i8P5ei>T4!DtQh^ zEA%Ai3_g|7nc9>0M=mu|Uzx3FlR@FX1zJxvrR0)28I7z^?qcu3$i^2LInEDC=TcbU zn>rj^=Sa)-k00xo7flR)b-S5ED2g(y+eSGDj>Ccds;=c5vb&6_BgVULad&k05TF34 zA%O&rGC=O#X%8eDAHtc zQ_YgoMuK*THw`3&NIb$vP)6(yfRpJ|%l`o6ZocfaH57*Wwf_LbSYEZJWEN2bk^cbY z?89V$o}BIkl74J^RX1Ay03WeFPS-0OcA8z`NnxH@1-yz_g7C|L3vKPc%j@e_{7F$B zb~w4ylTy?5U`j^UlT8>71Zs+|0By&j00%wrMOFE0$tm??zYerIhPimwqzg;CokBTp z9|{Wjdsr%v2_=C8t^fzxuPdCZ-}s`pO8uzir%x`SaeFLKIt#ZKD-*B}Zvv=Ph#u|1 zCAsVGRJ7aTzW)C9S*lBuI>9tWJju8GGY4ec+jkCB5_+8A^H+@N6>8bi*UGiiZx-pq zFtxK5XFMkG5CQc$d{RWKJ-wb-T5cJRBHzs+1h($CHy|LHk>DSh+ z7|AsszKENw*+I!fN1jxnY0RCni zDEkh6_0fhGrgG(#XombMfiHYr1UEaxGb@}BNZdIX^{u^9N+}WP{{R_k@tlpOc-qHO zk=i-#E&)i;?To~Xsu(Eb2E%;El5$6C&l_$wTP<=WJSU{V1@!uQO2XFl+Q<$04oKd+ zGv8}tj=8GMm&Xzd@XqdCE5$mcmBBH?8liF!{OFE$?Hxfm9ldJV>En!%Ur%wHiKoc1 z*jlagvTqSB*6F2YBWDqYU_N7#+%F`Nj&WR3(@g7ov^2KUidpHR?p0?N&lHiM41lYh zq-1oCH|4-t+|FrF93vfjyS+T#QTy+`{J$1Q5Cux zL2KpN+rzXfD&TRS{M1<~646`6CARZb)JZPM8Ab>mR!#}^!TMsO%D=q=E=jK;lG@(U zL}u!EC7$DU#7I1uWZ2|)$PMU7t7BS!m6V&>EEX}P$G}H#%xh{)Zps@hRIxpO=?6Z8 z-m1JM?f3i>b!0)*BE8eDZ0xV$-4S`oiX$1_lCB;>)R0a&$lN;ANwpsSrK@DIj$y5x zUDOA%fuTrSAxyqvf~7`I6rlk1=RGRYlTEto`S$#RitF6+%C`DkKL{0F<86;74|fxW8`7J=$lT zVmM`rXC6eN8)>1ALKG6xM$8V}^2*yzPb87X1xkDRFYX=D4XLHX+A1Ur%`C1^896y& zu$DbKa0OnS6n&MUBM4ID8T{AI!RGMiILQaCUN6a;9e6@{W1cp3NL37ub_0fHV4UaZ zarCLZ2<*CD%));x;IBY4SxM~KBh8$JwGK%fkTKQ0suyLbvgz7gv{2lxqQyM18>1CF zeqqVT_swYtC2C(oIZf%rfbkT5YTb(>8cbyleLGY&ZP7QPwc#ts;qf}leQNg#NM#`K zht&5UTCFR#h*x?vTb8>XIJLXeqCR9Ok2cU)i1`irsWmOhW>Sx2q@E_F(9`iQ>rZLu_!05pua@46zdMYZO)u+t}& z$_WsQJ9JgIW+phqrGo-bUCub_G6AYL;TL^b&f5NS6|5I4@fSDNvD~UlCf%FEnFEhb zPJ8qKQc9h6RWsI{_L_Q^SCOslB#}}ah}S4U!SoxLob}`DROQEh#rr0-9WHBYi7u?J zCTp8^n!*&CMFLBS3nB=?8@MErPki>NQEJ?LT3?@mDJrM={)2e`0E=U3Ztc9jml*&r zmS&Nr%EnlKD(uNUNX1n&l2_yVha0_lAvIkyOI->Z0|mUZ#T4>0stl>f<(sJ|vVuUX z#(yeJ`<0Yev0j|r$$AakvCPPeZ@oTXktYg(p4FtCvo#tl7OsZf0XPGYeXBNZSNuq0 zlpisG2ex{O(g`)Qmnj2cs+XQAF)QAXYe^X7ehR#eX{XN4*D^Dnk)YsLbW@r~ zJ7cKIrK8+Q{7fnG)SMGligpN}@d*&Qhxl@20ugdR_pXH!gSa3sZe^1UnY=JbV%k~Xs@DiBxQy_ z<}l>@*E*D-?G{+u8{BBq=^AeIn|#w9s-E3{rF3)V(~_YmIHEq<=H|v&#p*JkKbJTa zE)kdEGaOwsH+JEsj|xx9>(GCxs7=HV^oT{JliRD8f%!XAJpTZ^RVR_kR$4kEbv-WP z(&AZRMO1D=u>7L6$CF7(6=Jd2f*U|Vw%MloHmeAbNmE*fUFr?!zLo5(ERB3S29 zmIpZ_@6x%PB&F7lh|O`KmEFCK)Yh{=&ALyTQbr44_NY^F(N@K`g~jF7#Bs)uhC5%-kC*gCi=q3mX&z zkaBwtxa(Za`8SFkC-J3t?~e2Us>;7StLO*$zK8XwyVEsDl+#4EGZgcpB(ChMkgh+J zgMvxx#ZsJnnysB>nn+cja=2rVSwrvolhUDRmWT~dyAyS^qO+BLaOzLDdb(foF=bm( zMwm!bmns!h9lMA<>wI&nvl$}M_?f9K-OAf(*3OXKN_9JkP7!yw7$@n1Kl55)i*DG? z*A)~}^o>ZvbbQu3-b^HJK1Brl+lb_hcCB(jIOyfNC2eK+`}vNS2bpY8NhO@}fS|5$ zRlR*Nj=a`#N)f4OcFSLabepXYP)Xj(@kA2a$#f=%a!2McRb`c1Z#g&wXCR8@^%7YY zot>Va9HA>{w)po{OK%Wf>6TX}JD8j`+L0nB!yTtAz~Hv_+C7@F_&lQJ`hVHJY>v`L zoi9Y+v`%F?bqMxUaR#Q+Cgz| zG!`+%9Fj?Y1XDX@!mbOmH-D6c$JA%NS~2kcg(&ihlH)LzXXn8WocqPB~o`CmLimJO#{{H^}g3hXlpAguYv}@Tdm(6>4-dj-2 z*q8(auH57jhCCkZ1!)wzy?y@xVkLF;JWFtO7nW;rA&%%lwKjB}qREqPaI6)Ik9vuI zCtsKA?oum2`yWw~Byff}$&cIx#xeQ|n_Q@#ki^C2UrJt8OIt&lWHhxtikpOwc1p64FC40}>Lpf}UfCKqzZ-!k00v*(czRrvt-Zh!dI6HNw*-wj6` zCf!3Mspt8D#z;8E)Al^$+L-lJOtx{*Zef>4_*r5zHPz#>jJQ5*YZ!?`{{WRw=08)8 zO-x->SKsIUM6U1ev)-y!=Ex&UD#Vu$a(0j6BE|C~jQVUi_pM^>QvU#DD`N{QFE>f} zksa2fcl=i{f(6aMlVNvf#@2Jj)dTrR@0zlFyCSI)KZM$XMQoS4&y+R2RvWWo(8R%Q zkCu$&lhEQoJpsaulUnhLn{oQ9`k8#vicje4=rz>Tu8U)DaXqYd)4Scu*DfOS-BnyF zmsW>Fy)C{;ElM+>64DN ze68B#ykF}`&m3w$UcaMfc;=cp;k-wV)-|?m@sYf|r7#x+fsDHP=RK;9(^BjFmZi|z zSz3J;PqwsJ2gD?D62z!O6}m6x#~9B)YR*pLlJotNE~z%(kM74lE7ha7msPcs9}&4C zg;Z{EvPQYej)0ROB=$Y3`F>{p{D0Y=Jy9Jp+bY}KhE!|&!#s~Gz9x`^5ySV3$r#{tNbdeRd&K4-&6>k(Lb7Te2 z7#{xBRpAOGEt$k_8QB;&{MB4-3yf_Xj=iXvY9nuNSX<2%z*!pv6O3*+>yF3iQQFy@ zofKaiUR+$@(d~*&5K*|R z5_rY{AaTH~X5*-@KlW^{n|=E7>oR{B`&*FBFZQ-=Dv}qCxdtnjS31$icw2RZP`b^i(s_1ggVD<+xwIxZzlK=+Q6<|3K2$OW4<;2t zxoE=F4(+o$Zmf4VQ=L@f+Z268!NDn~*AJ4nY+2Pd{gP3aKHJLo){8<=#@ zEJpL&I_C;iS7MMr=%j)NuhymN>*@FXM0Zc~JkB0_jgYBnEG`Y<5w{WrSq}rCz$9*~ zDQ>;La;T5XNj3md9Aid851u*$9*>)RF67jd(fBB@bm z*SvJPMxhs;kL0A_OommFUOk0(2KH1*B%hJNzvz9h{dXc6^pAWD(&yF z6?x=xcqXYQw%?M;bdM0riw$-;?bQTV4Qsre+tpMmg#Q4gah(4E)JJNGKb6@lv`I&& zCH0lE+)N%#zbB`d0U+ayfK(rSwLPU|NsaApMyICe(#nLxEw9E+9G~-9w|u5f#4+4) z&}XGY*3y^iLh{D8cCcwHEu>cv`4RYnd&`*#=!KUlxbw*cc>12Euab7xFBSU{2vT+T zWP)EoX?7AgWH-=7JhDQ-f`O$HfJopBNM7>+r$D+>a_0NWxq`Hpk^sQ~?Z)|k_hZT?@aQ!3p`m*#NP z%(r(su_+vKZ8u92kN`(=xdZ&)E(>R)06NjzZL-NyNabWFiUN8H-zo}Q#ub`TxS467J6;wo3&V$RAUWwP6}tS~Xil=AUD2r`_ND3r7dU2%9`6CC&%X zWA9aJuAi}@>uB|PqRpt?YZrF&8+BNM$ih>SNXvjv10#%%nf0ouw>eENzS(O@B*(rR zw1I3Vnl&M9t%^e#>={lv_wQDOwaf2iWV{edr$rJ05~-Eq-VQqkKk7evMYZW& zZ9Bx#gp@j5M7KMX@w@V{`!bsKeH?8w&h;;hthIh0{1vR)baQW8`)gRPm)2L1?sfJ7 z2>ojhQ%h!^pV)@{OnZwxYWck1iJlk;Hxj<~EiwLILb2gM=%9L<*VEHUKP59Sn04dX zrH|mDUC>7%j`12Jw1zhE0krnoK{=}9?#P>@hrSx!uXvKjTf9i_=AV6y(LXCoHZrmm z9nSBY*Cf?*I)zcL9ll7>V45gr5X8G-8{v%`k^C~GupHnh#yw62adhj)`2PS0Ut-%~ zHF(jNa`|DJRN#5CeCiH546!)>0H6$xY7?m?_iyj^C$*!+r^DNiDI#aTA&$~OJ#tAM z003tm=AzVBTP)S@z+Gv=JyuKWDF>fv3~I6unN^Aqt_QC!K=u_M^0njd{gGGSk-J+v zTE+2C9FzGm`Q{Ob!);T$jC8>a25%1ANBk=% zf;pJ4UBl;KIu3_u`WlI?SHIi;07a9wP2EnS`K{%RNCw{O`sogG2+QP;^RO$ALGM(0 zdtS}I=lYjjYwJfVsQwwPpp{Iovf@g}QpYLj_3^BCl~+wwGtAD58b zGm6o#pXfq=Es@uUZQMw#$s9|$;ynQv9Q{iQF3}AYV$yl`hGBsUjxml|jxqMBQg)m0 zWnKv#KF7|~11zC@*&!L~6aq^V_c^29i^W#U43gXOVmpGJsK==ur{1XO)g!H%o&I#5{6xZI1l=ae`g ze$`cX@{{1KYx1^<<9XN52%$u$ARZh0=Qycx`K--KnRe54c@C>|VPexoVuX$yMf2d1`Eta5 z)NQ2O`>l|gvfZsm9*tq*OPxYt<(q>Fqp)X|Z=NJ@}U(NUTU&(mM zI-|#nt~9G{V%#kM00$(m=6prWWJpwiVgnjE%MS_c>yp?EGI#}zR(9IgYx_~8X(##L z?_@5yaTMCs#IrW&fibG#LWNRB(0gIC)2J1G-H@#!zjwAcWO#Cf7;S7ggYS{sX}y_sg2%BBZS z26|UVgwAGViG5cM6!UNhE_&n0ZHYr22&!?BI-7+^=U2a4&%nYB#HQ5arFZ~hpVXG_)T zgOQ5phkrvRL&N+cfbJpretOo;*#v@1BHQjqU9NvGagOzyfonZkYB8IVvLgm7v~B7Q zN5X4pay{H!Ni2$?$u`S{-PVpi33CEHvf_W4KTg84@V%Qz@xCLWfb$X%*ePk-(Be5Go5E zzwZ?Q;iyS-2B9Uyu>6vpsEP(L^&ZtKpXLdT2FCF(B%EKNO~8eW=3#(#tM=e^29u># zqoONhte!&Ms#?5FfhU*)lBWxj+wsu!1KzpydNx`X1SGMK%ZCK*SjPcRr4_R1^=_)s zO&Y!?jl+i-{Jk*W_NrB?PiCIn&f8CiogY92sxyS@F61x%9cmRIhec;;3pHjh)4 zVfCuEqU_F5ISn~&WJ|k+1_dm`>NZmX|L#YHFIU^bB1~@e{%}VH^#@Rn<;JIxQ*m)tf zFD1>o>FnRfRU3(C1df>ij&eF2Rx|Y+^#1_Ky7byLo2cg2?W{EUZ{n0&#T?huTLnd$ zSm6iF&mfEtfk4LX>^UO1rqr~*U+MP0so9Pcwn=!_TZy$vEv}jwGmxgH3 zxCtz?lexR?Si<0OlGx~`wDPZ8ztz2d#&4(h;EUF@xd2OLj7xJqqaCZA%nXXf{K@2D z&m$mbpvbCmPfzdu%d71Y7dB!Ry_uufJm&KEOP!!H?O(nJ?N;5l^(A;Y=<{#*8N9if z=8(Agu%vUGkLJ$Fgt=aQIV8hNn!{C(-_7*Dlgb2?skS4VkQY5J<>7xSLMkZ5^_2Y zN7|t!&|wAOS!ase0@6D)V4j`2)sx#uXm*OiSoSDc1fFK>0Col0&wQL`?ka2B@4)Y~ zx0WJHiJuJ2tr-9l@@!|SX$*7`)2@rYI!h4X(C;nc)jq!H&5N=kgvJ`qnCVlh{x z4bQ)C+@~iets}ObrdsL$0O6M5HtIJKyIkEnnI@7Vssb~%dXlODz#FrUD;FlzQ`hC~ z>}^%GvR}oKSTy=jy|Rg~CeovMXO1%rvdXFyg^_UB$Xt?0z^l1+e&4@EA^2T;zv*^Y zFQvPSM%12I<-L)uXPzMJzGNW2#C3i=%gfVT$j1$KL6$$w)NLWSYE0x9+78`rxpy%H|r6Nl!ek4SI#Vcnn z4EDIx;g0J*Zs6iE*?;OiiQ|vfx?-snPeaF1+*ccPt6MvwypKN!1o~yxud3>kG_u74h*ggu9FlR{ zI0CU!QGDNoYT)F!`hr+FzL5F(*q+pIXOAvuG-?KdynKoPm{-5 zdh%2M01`FnHCtbYw4ci`#}u!#`g^~kLpZhcDB1|QK6N=o@ioLCAVyJ+PNpw<;WenQRzRavYPTZy&p5}#Bn16 zR1P-o!2P+Y@@R%O@xPHHy5*S+V`=J0DlzUiW}zocu{URM_S0q%KZh7x959k2z-*3l zxntwg>sPvZ`(JcLSkF~-i%{^*fR#lSB^^HqHs#m2 z@5D^^D+^4^Ztz;|xM^6g%jO9N(g6%aats5G^_!}v_vF$G&(!1Mk1of=`nB3h1a@x< zp>ewo%z%W!;DQvX^#|6p-#InfGgRP))=`9qTTQS=VsQ*pLyfz3qsR*MtDP703{gC?ThKAMw&TpFUpYk+6Y#8F`q@=y>XsBDvk12@BZ1M@A5dLu!Afw z5nuwvG?6h?Rz?g)Facb39SA(;te=0mR(RFnc<$2T3DRVplWn>-^ zj`VsEdaQh; z8z%I0S*~G7?q;=XYjWatP!&K%+zA~(1mOK?k8LFSU*tamzmvU=T<3tJJ-O+|*GZiDQ#g2<*6MvVVtETo5|21JLJ_)=mE+uEv2o(d zUnuCT&7{pHmbZ{WB+#n?EQJXRo|z-Ic+Fi(HD+!t^k_eZ-WayHv$(s|k=3opLmByT z+_&4;wP4_++h;^RRK3eb;y$}+K7lryXjHUO;TMI!aF_LHhx-1uWmlVMv%GtK#w zZHpdI=eNnZ!0XSwR&l3K>-<;jOkM2juZzoX4K&wD65m`OKI})FjJaa>v~(p%VTK`v%w(9Kg5MvJ*0Xa+4m#TwVV`p;r{?*D9e}Vbh5Q& z)ODz=qm{J}HW;m%Nj9Wv%yJWqY*Hl7JLen<$tSfQ{{Y#qh3rOX?pMTDD9{IvJN92O zP%$qfysa2sg8|^(>5O{S<+m2R{r=>3hnGsbZ_I==(@jhmVT*hiNheo**4vCmP(AnEU|f6**!W2Ql64Xf?EmUq0JjGB$ZNcltM zp?r`tv`TnT063|Xwx7HFzWkBZuc7Mh${8Bg>Uot>;+0Dk0Lreheq3^Kv}2$Ilis0i zZ>CMt(8kMN7k772S|Df=Faj|7*Z>J6{Q~jRinEonE6L+U)HMs=7NxzMaoj{jn!ji#y!GaROc5Ds75Il1UvtQu{*^7p?&S zW7t(9^~g0^F|P{dJucMVO38B|m(0iI4)Txz_W=h!mDQJzCtVmq>*nm4)owKtra&Sw z#~kRYRxk)e1B`kD*Z%-DjFqkVF201duIszKBGwC(h0@(n?gW__XFqYqGw)et@Rx*b z3oW--15MJ>)_syqbBk#lAywP7v$s>oTrNj*>MF10TzvKZOLp(VA9xSo;u_*u#Ikwv z8Dor$V6yE2a(ZRIO13JwQvAQMT%97I*COKjIPBDwXk-QPl?f0Cpd55By!-J=_9E}H z1IE4=Um9E5i(OLME5*8dI2PmhQ3oilBLws=Rq@ynj`i8;GPpf-&TmnTNo?_==$Dor zF0#}v0og2O+CAU>khwso-z%TJMDp^bLKvKOd(?EeT4^%>0K-=En8-IPBC#!j?#c#F zqT;CsOXy6aWq-tu&!A%dIZmN&lE)jj@+%ckaol7O54CNId)bay=syZ=-Z`%CeAZie zy@L$t-h$jC)qQO~nwZlV@9BDr0kgq7}Q3 z_>)Y^0_|oaIOs4wTvk_iFD0I-csK->?h_5X?QLlHkiosaRT0G(%rbc-<-c00T$L`a zzoIR4?fvYLyKyH35Q!TCx#xk$9k>Fu?59YnEVIpE*FJLmj$g|IqURXTbB=1N+<6A~ zM|&HEj#-h)DHD7$yrf_*(nrvH{++4U@CQ1z{I>oU)UK@(<9(`#!$b3Yq4(uS2c`+< zpyvjy1PVhYR5Jto#kPPCu`J}{x7w`QNx#3lA*W?aREWIa5Azj7 zUUAj9@B36Y{{Ry=**Rp8+gaiu?5KI#+ycXB{-pl^@vA11(RlQ9os~qg0x};1pIU}p z9xqkQCF3smQMFX<`HKJuKGc$>V3mcgE?`yEE}C7A@? z_07C@PjPiCnXKYs;HfObVJ8Q^bI3lmM%OET4PdS`PV1>0+CRi?S!ZWO-kHmipf>}I zfyR3Afm0V-6OHK4Y|)nNfIlhNa&wGvkGD^*YW_@-+VEoKOoT9vvK0PYd(ysTWtm;q z9NS&R1dFs7$DNkPE_XN3l`1P(>3vKj_G}hH-37Jgp>H@_J1O-wc}RIM$eT+qKn~JW zb->9y*F2MMm*@Tt*#7{cPX04-;``a8wu

E+q<&0A(=-*tyRK<;!IEIip|w93;|-CfTuluSG7b^{{V{Y$24_pCcB#BLyjA% zEt5r)_=$4?Q|0G{UNB1ojQRj+B>ePJGF>y(-l=V)rk`V{TtzgC7*$o;?4enSc5&)6 z^5cRadv1b50}pmxwT4>N_?)Fn_75B$oV^yCQC4d1kSKWm#VB#A>^- z@{UP3=so?ac=cp4+?G*7lASeCELu!6u`FBx%CG%7 zDwySLvNM~6eiHMUb{)Zi^ z5>{4hr%N1v8#skYBFteZ4E2EU%+jt1e4! zHB^bEa-m@4o;vbJw*Xc=tm#lq5D`xbUd;uVW3h@WKl6M409w^Y!YJa1y;pp<1WAbo zFcv--ed=zVGnQSH?Mq0yjPDSbm7L%c(z@ZEJu?YM*yh#?r%V3;5avl4ayE_uHL}Zn zB9%u^59uv^aXZT(5hocvDw%UAQb?5>4NpUw)hD@#ZbUiXy9T2dsZ(k!hZ@-*Vzc>? z-FYi26OFC>#PbmMQ04X)NQL%TYL$jGd* z6qjT@>bhLUwy%hXbL;f3xHz=z&Dqk{?n8MK-C_Ev&p;|NMKtJ?PR?wtz?K<|&gXZR zj-G@2S0jsMiCrgMx{7hO)I1I`jQaQb(Yi#YJ85mj=av`BSKx*n{{Y#nTc@oOalf~Y zJ4sO6I7A0yDg54*G1KUVQqt1tE;As`dBJYg+}di9LdS09qF7{wNyk<{@0#U(?H3_* z>8)Df1T8d^67o&)65=ifcN`v1UcQyrkvcR@wp{Ig4YauAStFHh2b(0%+>yj%J(mQN z(>xB9$tA~3+AqpGTSpm+5@Y`Wn41E|dX7%wPXJ?_nxad|svX3T#}AWW3pA)>-bXCz zcVv^$ardaCl|;H8+vxXmLM}t0h_H;6I0!M4Pp^I|tybBhRyLl>M7Mc_Pw?j;C|HuO!xki$dH^f?&|vKyMl>$|f1gmD+L-2O#s2kEC}ZgS+Uol#xq>nyY@QaD^$FV%E=Y%FCw{^ z%%DlP19Ywn?fzZ>JaT@On@xB3X0PZ@c+DN`w20$7XLKCncmyup$F|Xy8T6}4+DUdH z_$Q zb{A#IIR}lo&N0`}RXjO2_RD$VhFbNc*M2x#w2kL3^4vz5%EVJ@s{q^<2XOZ7)~?&+ z()0a_QsS)lG>~8GFtxPD$c9i7ZTNRkq&aU`^1()MO9R+cw69zKex$2QXANp$73`5l z>lc{LKQ7>12_Z6g&O+q}|2? z>h`ea#?atJC`09U+A)mtfydwLRc%M*UgfLH94z2TlEkxy!Bf?TL+(3bp`bp7Xnq%c z(cIEB+e!S`ByG+;G6n~&D_1Y68*fKj=wX&yKbK%@RvXl?W0>)PILh#UdX|%G^8Ug; ze=(MsVHfeFgrSK^F@v0i103VmAFWm@?Us5Z+QZJciqyNeoiI=ba&x!$=M`@??nTnF zwK0O?=@H`taWPv27>$@U~Idv+{B#~P|+4E^(;`lyvZ*j<%>5ZpZa zBz89L6wjyHq>Ro(M-c&8&mCCE5CO-2ifdeJi|6fM)TGs_UsBy=X=mY!Z8{G=aiq1J z@hOpTj);oDxENsB5^Xu^!~u$jE>7Q)Vz|bafph}*R|4*PX?&<-+=4(ArFJR;f&8or zfZu#qJap~&{raNv-jLr@mhRJ3w78y84ZJZ3OEC=B8?xCaJPqr&)Z(;;slWUCWIgmX zv$mE<JfP&T0-^r1puPSQVj-M3L1}^3ni09;HkZuRIag6#@-L$>TTB0vjzG)uh z+rAcAPDai*1}XxN{h?{yvo_8a*CHm%Nc-`HV#6Tgr%IY8G9(i9oyHC^z~dOBHcXeY zxKk6BH~~lip1<$=(IU;2FBx2`>DIedOTtxHkFNm#07}yu_c`;jnG9j2AwMW=f_cqt z`5Z-yO|c7ZtjwWH42nPPxl zW-GO9$eVIdw@uvj?^7&^7g*ah55uR^G=pR{3sZM>EJT;sSb?17N2g9Z=D8fB7j$(- z5^{Uf4+k^iA z;;ds^`{=Z#TN-$N@vLp$Nv1PDlF_C=l#`Nv-k#NHYi4qqAT?JKzzl8Am~sK=6+)=~ zr2T4m+WY+ue2iq5l3;{lIx!=)N;9*x7uzHp?qEUZ>s58pWhRR%>J4z95tb)|-l@Kh zsARLWjU(GER@;_VVGxuI1t&ab+ZoLp)gyK8K1tHT+iu2dS9W>M0oxj@Dz-`E@}>v2 zYfDjILLJDDv4VEgEEeD@q=<1GvGi0{9Irs7ILF?qyeH(J$e7Zt&GPEDH`ggOz4iU9 z%1rx@!kvJpBb}H~4{%qxH7%)9UTXgUul*9fUH)TTa%pbvVpmBPdz+`#CuLpF=0zb9 zF9U&su17#4$9kC0w|jT}{{XRW6p~&k5w;CFSZYGy-^{tYYoM(dL{*tYyOa*h2?2S) zP-@bAmA|Lo>QkmVv@Lx$z%wJTf6a}fIXOO+TD=o=IEvycyXmAqI>Q+exeNlv6t6+a zInTXQl9aF5RUnKXETy~wmK%Q}7F78l!36G8#(Bsmk%88sH(!6avA(rwXFY}Nvs=2v zV{)Z4<{y=L`kZv{SESvIjjfvE&dLFD$ggb~EU1KGh{g#%gQulMwZCFe`K8$mCP3x9 zoviG*3P>FR`hih;K<5Mx9-%x|^DqJ*Dn&*GLooS94<`W`vO4CbN&Xc6{`N}uAL}>b z7!SiVSV;V(+Az+fgCX}P0YIp4+wa`1c^FO>+rxU9xQINH+uX?De9QBIyL0NGD9QJ$ z!P`~Yocd(9;Xa3^_>)M9AidKijxmXBq1_br*%&c8F*#nONIK@aGGTLRr`e2i#wpq& zFLkXK!g@W{hG6r}y~9B67;HOELC$_*>*-w7_Zqftm6V?TL#&Mpk*#Lb_QOAt9Eq|dITIA0&DocJI&7%m# z=bl*diUAuoDej{zc|A>1O<&9Tu^lavb0*uX*JTWo+(u!IWFyXC03?CV#S7P|>F-yU zZv4G{`!C#u(qDh}MCvO5)n0v3W0>69o7X!B@z=`Oqa&a%BODB8uYA(`bK39r{_K4t z`3?L*bjhX1e|p~!6fNZftAm9{U8p-QK>LwaR_VPJ($XUQGi@EbARaC-3n^d-Eze)L z6*W=%mqnR_vt3VZZlw&3DSQ+05wPP6+bX?JVN`bQrT)<#$&tQ1)xX1_v$fOhJ~nMi zcwmCuFa_C_wg6B60JPbkOjhv5vP!&mXDRVl`I*m$pn~e|*5cyey~DYR<~2M@cNUei z(B+#P4mwtuA1A+aICfhu2bVnN=VN?c78r7&QAYr7>;M3I@mW8wlT=P=lUX~#aU?FX zqcM!2x72OLhl&>Cg;TkY78ZlfEdZcv{*?B#K6t zYb~r%fDZ)ZvlHvdJXLKvpgz~^lgySEf1e0j^Jlr^88nlp^(_@@$9nF9_gA;pu)K_3TRSr@ z>}*2L+d=P*yT~2bRj>X(S~F|OSMlV7Q-)Y{#4-uWS*F3sPc__N`Va@}>0KD5#kOOW zavf+IYQtf3VQS4Fu#PJT*>FFKT*)(M-H93WRTW=RCz8e}@h*{EJkj~Vyr9y@D9G~} zHf|-e{LH8KYUY0H@BWUYCAGB6eJ!oIju`D>jS#YKf8oZfo!uDWxjwlRcgmK((k*(i zjPT=5wbNJvSVwnwT}bm2Bu5eNfy=k4$GubV!;0_8D{``XSi#lhFA_)Q&hq(dgS2^n z!}h=&pQx#t0QEo$zxnp7f7?PIhwt?nU0p12PEZpptm>)=7zZDGbu~XyAF&e!zTH2` zh=2C@Vl$9V8NRs~{b>}GXot6FjV{_qrHnadkytZ^d?+DE&rVM~d(tbWLnpLiFKq9v zT21jr!)muoV`ez@-TwgY=B67>A{i6m`zE)B-I8mVV}dB;f;M5fyr{ge?g!;LAc3B_ zJk+^zZeOq8_7zHr8Ks`vM3^GGWR!?TyQEUlmOwl5dVT7twHhs3JU*IP{s2fM5ZXoY zi0jG$yL4&?1n($#?UBxNPAUAKPv}k7{-b1?NoKY>eY}1`*(|d$To|O}fKGAGm`icS z0HrVZ`2PT8KQ>8epdX2v+%rAJ&A-gexm##;!usTrJ8(Fn{{Z=Y(LHuJzDVw7fi3PH zRgU4juP>Y?WRSV_2yvQ}t*U;1%l(LMkzBJ#f{p(cArAH~Ejqrg00N~=I zvgfN{j?Nu+@y9-uWL2Ckr;=S}-rfNi0PSYk)G)ehYxRTCa0c4PD2oH^wc@-gY16Dkb7>eXzcBANr@9~9}<4{rmt#L>hZ ziB$5BcK-m{z5T0r%Vrg9yh&-STUhHF!&^mrX?qmW?h|5vEQ1_Oh)+O@rw14WRxPKq zsV0@b%#hOcweby&_NNP6TSl(ZOCz!QSdN4b%s?FUs>wFkQu%C%)jUZisTQEpUO9rw z*l#c~hs}()3RH4QWBF=f2Pezh^f{-O!+Ieuth9TLHr8z@y}QL3NtKV7f-UZ? zQfnvqppPo8-?lUQ)~YMF;L38RquY3b^5XK=Cd_tlL=_@d1Oz;uoln-HNhvBKGGsQp z;%nNig3isI$EP)H^0^TOW!1Fs$@0&# zMNxnjx%pYY5(;YtGjDat&*ta#sk0s=m9(-f2*J0isSq!&jz;slRv9u1~QC$^Xlpb5%#P0>VrqnH$3cT*BNnd26zP}rPhtCtJ ze2u}QJQ4kmwIG~km}=0=!#2@Ch?k6@07`+$2DHhMIdUqOf>%zqw1&pz1b-piL!Y7N z>)Nu6+^)^>tq_;ile;A9vH40cGt(Sakdm#LOR^q$4b{<(HVx(VIK_0om0Kb)DeV@ zVdciy+z&ssM-@cbchNj0tR}4`_K_8g&u+qdc;jS|FD6fzs0>sD+6x?y$~gSPIV_Qv z%O~_YqmEsjKgIN`tI2O9xSHb6Pn1q>q>W+@WN$F4An&-c?E`Mnp7d~OqSs>vywr7l zINn>>-%Sh5>jY_Uxn*E??sioeLVaM8q~yHOsuW5Abs)&6AzQhUWQ)O}N109Pw4RefD0E%U{v7t&tBmcA)H_7+Zb^ zVn?v!-l4eldnn_62G+W3J)X~phtK&`$j2MN1Y>W1UY)AyTKbTn#uwUAg7R1$gpr8? z8Bmo*Y;ZDoKD^bNT@{opma)|T0K@$0E)!%aGRGl+1a@`}hr=8{LU4A0fsWNyuHWDL zA$+ByLA$e>@tQpFJO1@j6>DQhrswr>p{>`q|hc|a(_R2e7J?Dl$ zk~LKa_-X+woOdAeP`a-l*&1m(7|&=UdwFBH$H3Z48!U3~DI|}AoM09zxgOX!#Y42K z*o#e*x^Qc2V)Md{XDruOVkdTW2o+-kvDyL_1OB5{d#!6_7n*z0EA6N=O{q#&;Lj^H zq$=n`gOP!>@CkMRfAP&#DLZAQR*}%f2A6!F5VpiiZe$`I+t+IBR8|0i=t=59J?ieF z$lF65R#XY4$24X+Ac8Ps=NUZY=eZ}G^)*$hL*9>9_Q@Tk(@G&*g(0T63!E>@gkEp} zCmF{lK9v(y7XJWp(N@VT`zvc}bdK3!5s1)&2Q0@qB=sYK`g_%$v=;V6{HAspJS!jX zRCQ#IrIssQT`ml4@-$4UjK}9Ck-7?08~k|_1e)fUgx$%H=2F4akz#lRWO8)Fzw_IQaS7IP|~#((kFD;B@OsQ znp-TJfT|Gfz(V*fASbWN_#UKzQweRg_w_3!;gk|)Zx?ChOi62FWpN{&*>q`GppS26 zAq!(10)4Ax^27E0wo*;GB1%B;M3$g=dsm#0tl0&!Pi{#+rDwJBms{A%MNfh-CP^-m zF)9Wd7*U?y^i@Z{=Yuy#1LdGv89UP!_aKAHtKyY*Qz{j>~YJlPh zjJkA<8zkA4;+6r=m>Ee^gZV+p=rVYyUxv#^x*2I!{(Zf+p>;Y4o)}o=3BpFJ6e*l= z11q;Z3uM)&JEh?eqDn@K4aShOFt|3P%v18lBzAIsQa)fesT~Ic7|mAcpw^h~4MnYN zZLK8pQsU`O*)X8K-dyD6hy{l|a!0La^Kt&<>AM;DjibA|Eq4rWI$FnP3P9wT2;j=V zf(wxD2s~j)6rM0=bg+jU;%ZM4y)Qx3 z6^ka3^xWOOBF5F7)*Bz7cV{`GjR9P%SKpEM{vF;V1%O2)-v@6AOUAtt^47Qn=I z&!t&tqmc!u?z;?;1Lc+nKHyc>%xAq3N~Q-R@`2kOD&1(tnkTf_-^rHdNt8nt3l=!% zuoVeD>;&=J-hqS%ah+n zTr^x?MYhvLmDQcNo#Ry^C!cXuA240LzV$LyQcBHY?_Cj+!TumGN<0?Yi|w4e%_Fp7 z{{WOEcwPp1`f*uWn{D^spX_T~X?XoVxg~8Y+W1+PE0ZsncD$~;1E>VyG6(Zun!Fui z)4#t3Cm)|{qJgW$J=|AMEON%>{Iy)*Z3J$}`i{P)s*`E|07EIQ5MiBTRNUA@!1{mU zv|Ulo$or|h=|)LihlQzhXCu527fwm%+v`zuLPMCW<4DKK3xArcX%j@1p=gIK*N!T* zZ;cXyjyT3D zR8?CgyLvcB6q0LO*_AAy(^;gAxoKIyC|n$c0N|YCClzX4KFB*<6c<*4V#y?cM1yeH zGJyQ34gvEKKAhDg>rc<$@>zWaxz<%Qd0>HGHDkQuk0UBhNQZQ*}ZGeINn}&Z< z*ckMvWZB(F#IY+pl1?4nIQdaH$FVu-?OFDynG9|91&m2%h-8-XRy)8W54YvW>^S|Z z6QtLXI{oVOha!T$j9 z9@Ray_w_B{ZEy_NKsMY)21@iK^Sj&a=~Z`R_&fNeptJDit8eA)2Es-lDLV+;wCAQd zCmy&Q^sTW+=Sb(u{#MQ(fLg3@UfpT)=+Vr8HqAyBiaC`?3}KWp23Ya|8*;>OXn3EtO6({AEvCX}>uHugeT@!vSft{Aw%+*KV?Zdw<^-WAn!y+LF* zKMJbi9v_f#z$3pH{c8C#a{4OT*oAgNpN|?F(fbjIQejUb*X7nqIYABUsL}8gf|R= z-DOs03b`twNKAqM08#1m^rWq;>+eLTv&@%~!kT5AG6p{f8DdwRx1i5N!57!(J#9sQ_ueZ6OQqS5ug#ozFtc>$jfp604YZ&)~~kte^0+;HC6Zj z0AyE*FA*=|v75_`n;@H}Q@J-`oN>n-1;;0hRc5tcK)uNS01?e)b0m;7$v2aK9G+Nq zRtl;jja-hImBVqIgsqb8)!9zyV;-F&U*E00%Cf9mL&kCo0f2MqyC0=zC2gcx6LLx< zi{YcWxDLBgc>%+fR>%j?V09g^DfCb653L2wtaqnQ)C^)TfxL?9DOE7!#T%S+(N0wR zkSj$x+FwGFN$Hf$D$XlAxn*@oqqKHdQ4{kon6hJ@x$`>z0MdObWj`#eVN8*eLz`5- zj@9K5TEja?iyME;EXQtt=^anM)~j!(Xp$c`nWWqJkp%MH8=X>nYXph{cSx%E*hl#r zA2I9~9qP(l+lSw=No(dNw6SM)_twx6FTv07$rwNV?S~`$pnSc%lUO*@roS)O{*5iw zklF;_;d;I9VrH3Q^9*Yt#!16+d(>moY_yiBknq9?@8eV}m&kS}KgvMB_Nm6UR!55~ zb0_$mHyiE*sUph@zR;+V+Z7U$+wuO(rCJ|&p5{@fw9bKUqIX0D;Ze$z!N;nH&N;{xHt%}-{{R+NyDC~` zqC=;{%#gzzksE`bn&E}N%B$Z4JOS6eZl|Lc5#5ptCV}RHH*ODBNxJINVQR>Gi3;$}#VT1hK+mmMKa|b1C2Q{MkJ{a0fq1img#A zq0E!dKA5se2#e!eY)3yfKa~1qv)8a*)kf|+U6Pi`WkF}7>Cwmr~Kr;^hf+qnth|ne6@rn zlf@f5{&ZNwlEWX&$6(3h1c69K_2K^jk|f4ASNc@*On|d$cQ;6}!)QmG9h_{z{Hh5f zla7bATjBDzRP3)R(d@$GRlU?RBS_hT-2~Z6>eN6J`*P*3%#y|#-}p|yhfT4tQm zxi<+X%ehV!JiZ%_r#K79@99*E();`R6CyHc0KRZA>&PT@V~#&ee$_|WQgzPM^ZrpB zQK(V=Vn7^VKx#b1mvDcKDA_tvz?2+9FQ<_2N=MlNMh;Gxwv}!CLVgASioS+0d3f9_27MK9C{@(x#BA)FeEn4fmH-5LHSD)fOFUb zkZP@^rcGGl`rZpjEbNtCQr$L1BmQ|)Cl14~B)J3A6?}mWD0sjCJw?EColhETM10L0Q_%e|hGBU+E=s;q9{VMCTIdoI!zPQpf)2P`^ zBo~q~wTeja8BhXTsp=2Rsy_A8hAH-8DK*i(>DG!r4|HK7G>n#OAcPPJb^&nYewgeB zHOG=af5F=scq!V}muR-p$!%qS9`MnaERHvjFkQP~oROUIQ3kw~oLlIm>i!+o-%4Ah zirsA?bR@aiBjlV0$5Ib^>4c-%$2<}mcw*(W`{}Orcul-=u>iI}kPe$c9Mz=OxQuI$ zWQ$uXT*Gl`&9tDC=%>^ARxh;Cx`{0ubAV$~6$yc)+NkGj)(b})?Keq%CRwj$R-9n8Bw>IjpzY7C zPCSp_WMqlsPPUF6QhcDbjSeG@5yo-A&(oaMr6$|5uvA<0Ng|rs;x}L7Z7j`@4$;MB zcFoaRy0eyFF`)#a{HM3gf^a_7Wh+`UaoEoI`8sk4)aPgGZ2|UP@Nz(lnhR^!8lI<_){hsr`uUT+>v}ylRlwRk(=V zOlNQ5h1<_enygxHW#!RUztpYm&|4xZ-Np;7@tpDKYoZafdHE*F^_A$kx!rp<(nuhV zKU&^+(ppAQm$_-yTEcG*h~p(CBsS$8aqH}VwP6pHqe*ROtjl%f`F=!OJh7fS6I!U* zld|98eKGItCOYa7ywR<2B70UXjrSNsOM`W}7SxA!m$m zp!?RTobp5tgQacMT10T@=NnJ2y>FK*oKm9rRXZ$~c8vDhJhn10DypMDdgoGZj)t^A z+*|6FwyU-!k}icn$*t6)^xH=qkk(rzi6NC`^4+*_#1apB`s!Ph)2SnWT15T1MQPWDEZQDf!M*CpqKIUxv=s z{0$@U{JPbR!N0W9&4-dDGC^q?jH%H(z>N{5LiH`s26;c>qmDJ& zBgh|{l6~>-nygmqwp*dLlxEZPviF7wAh?whId+EfMgYz@8SS3Ns^!Ku`u+=6=#Y4A z$+tHXT~4#cM1FGu<})tQy8sLp&H(5$Q6#m#{{YBM_!?d(m3MHFMH-}E!BmL?;lau0 z+pbMj{H?EH*y7&VZ0#qK?o~G-$`B6W7$>0hIM3@+wRXwxq6&L;<~t~u&4 zj9?z*`(mc_IPB}G>Ch#(W=5H!i*OjpL%0CI9u7Ai4{X(?Dj`K4wAdo}^EH&NhhQ5= z=R9>JdY*!-+^sUyqKgKdU7%H!>?zs!X8zN1Fc)JvypK3hv5xoh$WHo0;;AmNFOohpywIu z#aTYtRxoHJxx8;H3or!lJu!ntwl0pVAePM9K$$V|=RXDVF~&O_H$K&F*AlIc^m~N~ zZ6?7x#>kHda~|NVPb@h&87JIhB9VGe*jXsC+AoK6Xs#Ll9y>Rg5Dl@p$y8=j*!56( zVlrterF~QT`|Oo={{S*4QNFlKiEb^USs3KJ@}>elFrbd70~`<9t9!B^u+?C>g6iGw zFJ_$E#U=!bBl1CDcmq4I$)B4&iS1Xekrpv6b#Z+b_m)JGb2Bhqg5VXvVn=MRBcUTS z-+~mGH+Q8?J>y#|AQwd1tA_bTMq3|H2>Pu{PX7Qh>#HH2^h)>l2yn7Y!B0XFM$kU| z)4OBX#9pRs$*<8Kr87aztLIev+#(kUYeI8)yZFdHN6Z6@RNa+=e#5$tHRZ z)n3Vt$%M+na(L;`*#-H6*$~|H+?-T6qA)vx>Sqjfou2$CLXgXWjO5^tUEj4!sYWezXl+TS*_djQ%RZN(AD;(>Y{92)xHG6^jgZ@BQiC%)2eN+G3;! zB&aA{6WvYG}eo7BNjb?7d&L$Dkj*M6|5Z$*&N!_bYQ}YR@Ib{Bfa`@?i-3tcD*r0_c{+@G>QQH+MyV@a?-C_x( zwJ;);X%CbD0}SkV80w;y%<+r;N%aA*Ja&SHCKFhXO^~<4eJ9%u|dDwaoJCCnwwP?a}rhC!ncJrn! zBCyWY&Q}Cu^{3QD*!^RWvVf!<9D;BFJfG5t+-~KWF}UEN2kD>p`qUO4$ulLgp+${K zl7)B}9FkAaW9h|9=#$Nik1z3AfD#cQ8-0J4s=dn*J|~4+M%M1Ux02zbirr;9w#JVj zBo5iafsT5yt^GgaXFh+z9u3lBz3~2%a4c=_oL)^V;zrvbS3;^|=OuwbfH~yXOy-@V zni1)fUJlZ%^gj+*KA=Ntk_DCIkQ}B-B{><~KLqu7)JbEt}tP@r9ec7vC#~TYRGsPMr+)n=h5pxg|10scJzHBHB`(Rd|HGN9y zo~5#b<1Lmc3N7n=FXhGn1d@HmIQr(JxB2Lvj{X`+qnAj6bd6(nX&AJd{MTHmVlk2l zRL8b`YN=C-@Js2malF)2-^C~BpX5V4F1 zc5ct}g*f%;nzd5sSlasSPMvaOEG7761&b0(=lzdvYIx|22=18bO(QN^MlPTLe6fxX z?fcZpc?h2q%DQxE0BDu2q?Pc+vOKg3$FR;bk9y7BYuvKzl(tBfA&y5YFguYP<7oWM z%zw%<27QfEmc7Zk*&(Ih+T2`fw@U94#VE21BJA8Z24GX!BVtZ7&j*fWx^2I;{{Tsl z(^S6x_C?ERw;Jz<(Iyhk@I;w*7(o`)O{ckLEHXLc&{V^GRr?7#OiNo>lw4fPwdI=m z?&Hc0o1=%wTmjSgtY03y)!t1d`ToCbqK?RmOUYx^E^Yj^30>S`{mP}<7lP#5;(e5z0qeNbbksqgGDRBfVS zU35lauRz{hQO5$Kd8D5+%_pcm008ma`&HwqFQAh7M;b1b2AkpaHtctKa^7|2B_x#t zK7$MHOLJMJtNnjp^jpmkdS=xGa)^~q?Svd|BzO9IR*KilUP%dGT(T_$0RV(=mx6pzcm7#`hCJ&7RhBc2Oqlgi$Q zgY#he3Wq9ID$72DWNq~KXwV53HAA_wLy|c?eSb=tt0C5o?Wf1GA2#M0*(FAfC`S;L z>CZsK4B&M3sNt^f@(N!=mB;bfAir!f1rF*l<$!mwC%+`o?^65n67q(ZI_{n&x!T4V z?xiFmaT+D+Y8KIu2vXS%yFQAlIOKim^2pR_bV7o=FKKTCO1AOI z7?2EXWyTZ$%%eR%UVh`&v!uRXzq&QDA6k&!Tv=MR%gG^CLbmE0us<)BfOp9Q*CwI2 zDoy_YLLDV#e^!a%nS!#AT&olLgJT#!ZgM)D)>$odLfJ0665q;Qu3HkjZYMo}$F>D* zl`2KN*~F=oV4N;FsYIOPV5+aQfS~-j=t5;yz4yP0b@J_{=ReU5Mj1jQ)$6VBRw5*k`$9^!eI(3cQj8xkau1|7H1^rD@QSBDK zh$y6Mi=;cS6ct}ZP`gxphJRYOk_pIXcq7}@4Q_eu``_=DOR;-BCG}!F5cXrgO0~37lOV2bEp;tI zH@S@8Nf`N*$iS)RsXTSTtEp_Gg^OWmsb=xCVF7*Ndi|=mqRKQ$+r#F3%Ag?mNCX3% zdR3OmA@58Q-P^}3Y|xoiT|>F z^!3GH?`+c=q29V0_dwMx4qR-9@*7t#(Cbqf( z#_^N9k)PWYFjaq2ve}>BSjf<*4h%)k8w6(+y6;CkkrFidY)XOY6 z`Gk2H{`C=lS)`(xGv5|Nr^R|=(PEfJ4j8{sKK0v)+Ox{f8kH4mr1B|NXK{d?dOwlu~{k$4gta64PWZZ;v#yHI*ax6>#0E_uLDflKN zl>n&Vf7_|7oOiRUm&-_^3wxW1!^pdfbU45j-EoSjo_kv_8aIeo&0}oLme%%aM%Bqz zIRJj0YYdI~Ix&|GFk0%5cQuqL9m0aePaFf(3gmol*JoT3t(3h|ArK-RvdHa^&B&_7 zBo#wGaCN@F+PH|o3*m|)pkossM|-UNbWW>e+>D2H`b{Jnl*1k z9+z;5Y)aiZC5S5hG4-oBKL<6A_3Irb_S9bK*NoFbnUNTMJN?M_;l&jKg0z5q}N6)u5XKBq7m)Q&C5&?QArLFM{4MK zII1IwJ*TbH-X-n9jLN_yaqZ3r(z)_vy&}<#8e*9y)zzbQw}Qq~Ik_veI+ZNVkV$T* z1Ev7aB-fu?q;&Z_-0E*}EK0VQFs~k5A$B#aIQ*;!21f^TdSrUjB_~MM443d^?DpEc z)~I5-0vj7vRNhuu+^Ha+%2i3p?bfRZ_Sfb8OXHQwnKx-~cWv?QcM3xU)~M?gcL!$m zlq-)@yJk7;IH>UT_x|YV?v9t2f-4lYREWl#7zos|u`Eag9tjv3KdnP_sGldNjLmGQ z@XFD^*73(9a6v9usQ&<@jQjNUsB2qYP+#Qq>*UKcuP703^BLVnAxFa<-n}-1)SfD@ zzr9&2XG^(~czl(RAZf(tpoYjLj!zv(=bnI3?N`*FsMb-s_1P2zP!$woo_hQGRQBw6 zJYPz?oDly2^8WycdjLoPeR@&KnJD9HZ*(ElH48BuQ`k)$W+U?lW>z>S)CE4&SGKg# zNj0eZkGw5(*B%(TyYre`#xl=v9DvF56;)z?F9Z^M1^21CO|HUr)sAF}$_+V(nO$nnla_I`Yyv$eLCtl7{^3p{11jVVSz} z1x>nd?^|Lu%kT0S+LVh=eLfkkAX|9Ct;W^goPu_S$j?3V)`_LBV%_ZT1b#)tl0$Nj ze6sm!^S_$PU7eF4fzf_$gXTHM6*1Ga_Er0MBJ{h7-%=`2#zH8SF}rIJ2`$ego=EjI zFuqhvS{iA~C9M8UtdheUGlZ3tyY1*kduOFj(F!JIR2Ei|s(gfbiX434AIqOp*Y&FE zk|lXK*rFxSY4Tx55=qDMu1WpyDvhPKA6hI49I(rEbjs%7sYv+&Km_t}*k>QDTWPk) z`VpV;EiokvbMukM9@Sm4?vd8sX1LZC2*eF&B3W)H&nWwhN(VgWdwn)%rCUw+_t8$4 z{``&ZGr$Cf&_}!si&{)bUqe zQnDiE{uvW)A)g?T#{;k4r5UlB&h6&BM`{C*2ON`u_27Q>Z^+HNCUodyf+_EAfM%7E zVTU6niwtCXXCI|0D{Pef3#qV_X;$+p$t$WES(}w*EXUW6n2)KdPiZDzK2Ea6v0O=a zBLe3v75NAOCESDGJ?eUHMED~mm7dyZI8>G?88g?P$~}GR*51lUh8H(bU3r__6t@}K z`Bd!$0o#qnl>B=XvdyPmyjMvvLL-hgmK9t0IWmfq`y`uxmW1p$y z(mEzgt;sgdSd;1P=~^7Jk>kuVO}MYhyn14dTe7LyFKD@Cz&$FBoe(7!CNYr11Ja<{ zhfsu#cm!v?K?7Yz?PGz6{3+TPDm=d|jWIfO%|X z+)w2z(~nxWDrmYyg}t@4j))<+k)9=t%BY}%%o}r-$2i~*y;Z$aIwI*4J^@=;qGJn% zX5T!Z1Gj;WGwN99?NN@IHe0+aa~x7#EKIwbX8CY3sCN^eu={7;k(FH+YRZlMgAa#c zJk1FYJF>pqlH`DK)2&m5C9>0&*xK_~xwD=KzGg@pdm(J8f77>mv%MI%LtRf&^6a68 zGL0G`K4|0S86k1$`*T+6jO8Mzj_(mN62+GUd(k~xFl=|GTePF7Gr#8GmB z;eUjZppA38Y3x2+4trEzxzL>)Z*ErV=X+uII3Q$@amGz9*<|lTUHCxlu%25d=}{v@ zcCkq1lWdK)6-IdpSCPB^*qUUH_dUMjD$+e)G zA0$b2bkWyWhLac+I`5DMB$YR1UX&AlmpZN zIUe*$w9%tiv86R>n>ws!oP0=XlV*s0l^`TLmcNE*E8GK=4_KsWy-@& zZ9dA~Wpz;1cLy?bqtZA>yuhg?6wF&+U;u=t~y7W$JmvdMW3>~@MIc@=HE!~Xy*0mCUhh8wLy`K?FJhg8_+E6bhw zJT1g#=1CsmBG{OLHsOfLc{!7~&I44o={N8EFZ&C(_u0noD4WI;vaGiD+J2hQTQLNH z(gbK&;Bov%w(2gZ6#hmzW)GXEndo0Gu_{^-%P$+%!bw!c>e$( zRs^@ENzOe0&w8|-t0pVKIcqtB`HCqf|L&>TqQY_V>w!LvIvw2p?07&qI zJY(K`V|!btLjn z1CD~Gou&Gay~w=^-SmkyE4GkEzD!Y!w(_#bdJlZCKWag7Pw!$)ba>LQW1qx#mNuyx z0@4|7rT|H~lm*+*7#Jk=Iqh0Q>HSQbvIoL*ywlxX?0D^%szn#`TrCiL5KY$Fb;@Qkwpa6lQ!KHPrPYQ>S4 zM&kbfQ9lE{E!2U#Kc7F_1B%Y=>qY+nGG5x+JAFdf+@IjZD#+O#K*e2BYRbNy4y~js z0tkVQGb6qTg-#ofp|ODk?>KD=WU5sx&J_a(a7-r;Og+IjC4W;2G77%$Fw$L91bKp%ffvXZAM zZpupfMP}9*-u&C$Br3DW$#E)K<$ z_OLth2;>~(@s3HVuJ%>w72goKhUO_DZPBg^64?&>KqudxIjT)*G*-z-Wl;jFb1R+1 z01gm$C$K#Jm8#KeJ)$T>gPhc&Y>$|in8vv0Bxj(h4DqSlF8Jh`3uaF(+4kh zKd0WJeF(&kHY;xbZ+tVI`h_MzYWyC9nt_o|2jB zGTXi|!#tI%cO4XclQt@;43W%`Bkws__%SXrp#4v!VAVFh(W25T8m0ZTm&&Pc9I64Ix0FdDDFst+Js4w--D^aQ+p;Ps-6Fka zF|m03vRw8jB#+XjH?~ocv&NC#qcoeCfOyCNcI#D^n%FFQ7BmYvCf?%Sn3eCnk+w2 zjN_WD)gwqcE*=`Xdwpi^XO&pb1cxek;D20JEpKO3UXBxuK2aRW45)T|*v{47qy2~;X;wuYiY%{e>@hNP z*MW+{YnNoCcf7D)f|egL;&hSl5qLPyLr}g=qUjv}0KuY>v2P0`igvNy3jK{)&AlU4 z1U$CW5Zw!lcFV>vROkEsYE$+rD5O|y=F=e4ZLQ2UmsiusC4Gbqq~(G(c*bzp=y0PP z*D6&-(jGy3ePGgBYEiUo^T~I)Fz)iJ1!Wts9PS_xJ$R)_Y5xFH$)s7Kw~I-gO~8^_ zAh;0f5(L_fcA=Hn9&(r^LBRZgb*kj3wS6zYy&B_wNk)k!u~v-+I2VoyV&ChNA6prLXkn5Y{M{?K^$%_5py zJooyPl2^<0JzBt{RyPt`hqt65er)ZlT( zYX1N>1^HU>W^7*bE~$Gut7dn$BE3#!j^ACVuHHb>tJ!2Pf* zB=2uUzKD5cX7grE>N+!$c8(50oO6uepQTMUOLRGz-s<5#br9fyGr?V?mp}D!^r&v% z(3FxxTa+vR013D&OA!+@9Bo#?$EJ4RduFDe;rAu`o^*vvaU_rc$p%#CfMjpV2=BBn z_Nb1!@%Q@`mGnkSD%t9{cm8Pe;t^Y}L2bA~z;(icPIq_4DtS2k-rwL==#ic{wD_*A zpmbY^U`T_Z3{h|aUt&j6Ir>z!#?tl)-o|SCei>sb5mb;py-q#NSK5j9Iml$15|WUM zD~>bQ-}d5)+Sw07JN92KkYt2sEuVA8HFez?vK*1{a)G!u><3;jYW@tYkg>QQ;ufkw zDmJDMIUwY*&wfo+_heZnvn$S8W-29Oxl#aBB%F-)JHNd zo=*aXa?xJB-z45&m`3giBY-njYV>kWR>_S9HS?U@IapK$RZuxq$miERe)MRn5?h}& zOpbtIxjuyT{i=;#%Qr$xt2q*Ui;|m2C;57h+){}6jFHgqZ>8Lj6;Tq%>^ATfRYu%; zvpFX}pz0|uiSq^y}ekzOKebEd^5glLH*jGN>*a=9uA^*IF9tyQ9|hPtuxA!WH@uI#0O z7z#K)y-STPn9HM(w_hMgqYCao;~D<|d8dmoC2U|oBVREi0e~BZLCfODC6zUY9x!Y7C9UtC$4(c5i#uMRhtXfjs;I<;>RIP(Xk2$+HvWclbTYd zNLgGiQU3rpBfc^{Xo8iFY;_}L0|^utL}HFlMs~?Q{{Z%>hK+fUnyuf&1cC|V+Rj;z zY@SPfPc?L(NOBt9PJ+QB48vf_1J}3qty1t(Pex~~Ni3JZBNLW6B=t4X8mDIzmdjU$ zEFGZU`DQiCI=ectLXkInrSFA+P)m38s%X{0(bvN|7+Z#Lr-wZH3agcfV%eeEz$1u_ z%HovXaf$0CK2Ld~^Q*iUe}CkIcLC zcBojLb|W_mHk=He!yM<=)}=k!dhj@&G>%4D5yHBu{tye(x6tuW$wN;RLpGy#p<2YH zqDig`DZ?trV+0oUV4?koJ?o|uYonheY~X@BYflX6aZ7h|V`(tCnXPuFe6?ViBp&<8 z9Zr3!WhC_c{pig^b$_j`EB> zdj`f401*R$jI*;b{{Y%5Dwh8JiM{BK)nT@_mg7qjPPZ*GDK_85a(0cwC#l?d`hi+B zqw;#Q5Sq6G=N&c9tq*bypi_ber&T)h5jB;wk9WG;5 zO}hu18w-uVUvghdS#c;ntOKt0O^k=(gax~jx|k@oMuPMaC)AD>}sw2oqK-el_%Nf;odE3_U74x z>ChpCL~n&x+kl8am<;XDT!T|Jw%1>M6;DY%$MG~5mzOsZzGF!ul_NawRb8NCr&I?A zjt8|-HEsSwq>!36pBb`C*+6@bF9PaC`Sz0EFZ=6J3vsqxz0y20$fab7N;|gLS^9Iv z@1{@fin4FD`V#1^c#lnM*y4*#lXNL?!Ap=GWI#l@_6^7*voEb{#U;n@>SMRIPueR- zpnOK4H(Xq*Mu3n@7Ga4v<8BeKKDA%Z$v3@tD;IGr5&3bIc%f$zj`DMWeuJ8arTG!r zE2Y8kx`o}zCBsF)+nkOG!0Xo|C(@!$n~^DaC$zYyf*bde{zQs6B$6`>Vm4V>mNB`x zC#w;Yjty2V#Xb1_?umPAR&=|@m7}U#qN^mN5fMp{l9vJ?plv< z#vU0w#Tn0*GI5NI6QAC!y4ehh#4x?a#+cqsC(GrIRv6SK1#g39sUrE$k<|^Hxbt36tdt4tM|! z-+Wcl)4y`FWIctjwZE{`NI;TLE$p~ZF%vQ(?(TTczZGRJoBKs8w0g6*md4Se^IQo0 zuPe-5jQ9pta-?uKI`P|TiitW}R9P!y^pHl23<_CT>`r;-<<33*ed@hw8n3C|WoaP1 zdy%%_m>}v8mb=Mi&#n}YrhO_^@0WTaPpTkhxi2FHE%|u*ROq20cW@4!99BmXTp(6` z*x08T{+%kaR;oTrN4=8vsF23eoHqQp9;cw=u;2=ct(H4L%-4ue6a2eWXK~w;{b?V? zqOt%3LHxd262>7VgFV#m98yU$sgLF(Kb1%6jP~ZD3gfrkkte+kVUBs`x0Wc@D|3|C zoUjDoXYG&F(I(n{2`6oC*j;>zi)n6hiNAt#fb0Ot91;Nk0KHvG<@8^6RjqwUEmHD% zN_9b_|#yZ3w6Xa>=6%3E%qJhBYc2A%H zaf*lk0P4Q{lD*j_soGuX>j6IQOh1X^atD;tddlpf}QN`r;Nt#GCaU@?^j(HL-OE66r6EFP~Hdy&D3bS z9!Z;GDIk8i?L@7T`W?Y(@mi&roxq4rXXJ7K;BnKj^{9Jl!s|n;=YNU6xOY^NIX{Hm zaH>HZeQL6MY?Qi3y;AWW>PV#WBL!oTAwYgb+@(nM&VNdo_d*NUcYcxK*+TDP%qm%A zMrqd~=SaA@K3HWqVEw)7klM1cb)vNI=1S@t&2amj$iT_ZPWa;$p+Z94Jm&r`c8|(E zy(wj=^$wkFZ#JPlyJ5VIkx1u+e1Oge-ydqS@>9wrBSKaU$P7}-tblYx9X_P>`_&%m z%@DV7`RqdhjpwI087CjDJd(69NQ03i$X93?81I_5du1ebo)3qL=J91zxRKQZy6_Nx zE_(`BZ547MH641)$84mXm@>%gxPV*ot~+1>$>O8BL~G20&aDWg47`*Xg5U_!YPfX1CS1X zY}Ib%PqNjkBQE?sr_FkP0`5q!MqWjo!jbcI1F8GflE1=XD62czMI!D~ju`Y)f$m3Y zG|ghPNl68z%pytEe0Q!>=H)#&IE^%{{YIgTSikL2r-b7 zIcEeYK_DxRxIap|RoQ{&7;bK_Ar|qO9G($ZIs12|JJBaQ*OKb>jo+GOQMJ&nHlIvX z%jSC_B455Q4o zRgxXZ?8G+<=qtH8?BisPiv!9gcm4>4a?C;f>l~?ciHU9Su|}|W+sO=x@3>?B^~*I* zncI)>q4)eO#h_Fw**`GtTOZ=qUB&3PU5%NKyQ3jY8$Y9$oj zjbev3_b4o9XolGqL^vL~BR{yTm*I41nEu|}#i7r5vlWp}agJO4kOf)^q$IRX#Dwaa zg~AI~m*+=jwM&S_ynL6Bcq4hhAok!^QOQlwq@(U|)MoO;GQua+r_v%Dd&T2cu@ z6d+y+_U4~f2X_*ow~|@%h{dIu(Yg%ek8BUnnuoQrNlWFLJzDbK$H^=%QqtV1z-gS0 zLG%n*40>eM=X{!vx=ZsYn&O-M$=y0Q6H*bwF_YpHgiv<|11O9SafEUJ>DQ^LRm)Gm z`u@Z=>few1DR*}=+gV*nY^7YYF4Y;_6~Iz?#&<49Zrs%_qiD5k=dU@6=t2b7QCP;1 z1dUIa357|FhZs|g z)N6G9@1p+A{pjm)7NsLgZ47N4w55_MCC(NgSnlKe#NcOu6n$zMlXOOw%HFXh)@<$) zb(t;8%_afMFk`nLP^&Pby7 zfk_tX^T>WcPdf$8tX|@5wA08;hpt=6X<`Kqj3GA)3YIFYTWdQGHxR6G?e9_4e*XY*+avWUPLFASsF4-S>l%C|yO7HF z8+m3u)dOcA<{(wzlwT=*{{YwWR!;PUzj)=jj#-BJk}y<()xVqW3H`luNh^Eol*ZFA zMPj@tU7&j4)k(3qxZXoHH?9X-lvS~d%*@Q2j${D+g;^QNj9J*0KuA(Sho2GV)QpWcV;lJgmdETWQHDlV?jr$#3g;)5^s5|l?C6=NmhT8Orjh7rpqarZg@0DnrW)gvn& zE~Dh(!)fBiZiDP()Sp2~{hf{yw#35+f=+T-}Cn6p)Ng)${}0 z)TkG+m&e5uZ7c|0nC)69vUyP2?*19qU}nkdin7;bT&!ndp)LH6apj*bJQ7d7f3W@P z9Oy$IBHdwQ@X-_03@VR*O2$skl&F!neb);ZRU;Ta+|^s~PKySO0>x@TP^wtt1Ftnh zWu!WuL?p3bFpGut>;C|M(xT9Ai0O72C5Z6l%xc-r-a+g1U*4s!1yRW-9#zRKRV17; z5KiK}W9`3oFB?AO8-L;n?uydcMYP#AC_Z7>%%(5m7j~*92j(Gl^1xD?# zbhJno;^uv>$qR&zZMbO*kDTOtU}KJ^uLP59&R0mQXjf4kO8VHqsu@6q420t+2PAWo zj)S#dtr?^{MYp%Kv%0*FDI_yAafKw1pks{w)s69rZ?jJ&hfPSNzLxg(NLmOcNW+B! zIGlXMfzEITe&($gQf<92=!5E!5q8(pU9H80OO=94oJqiGc`C;pNq5dYx#?O)UP{U= z^`hKdSosU9-aO#M%qL(6n>R*fQO3|1p!QSiNliEOB}Y}{ZFMtSrNo|dE3|>bhTP{W z0bKS21Dc}xlFGr6*`<-f<^F7L*q`sJd+yOF?~T z!Zs+aB#6<-*i7fxVBiyX1JA<5{lA30OOII5Ix7eOLUTdnO@zUEaHsZYFndpeM;e`jI(Vh zh~%m$ACw5=UccN_$*Et9{?-!jc3{Yu){*Go6ovBI~Sgi9g<;@sPWE44O*ydKIwbLwc9*JL5WT1RNn6ph&mYF5hBQVP>vD-~^ z8%U>uv5wf_{NU%<4|=4ZJxiv=P`ZnxXf7`dYZ{?dW$BQ4EDz9qmZ5+9NG|B(b!L)k z@iE-Wf40j)l3IaQP13IVb-BcWSD)*>XNqUxK)|kVI|_ zVlC~Gs^m5a^!ZQpt1rUS?5w-7rGcJpYI&9<7VokJg)ls)iAs-~xnc_sPqk@jy)U$8 z*0#~8s_8By%WPw+K@2enq#r%Nc*}3kSqb5J$IQc?xE_@{s(*VZd5xM`uUVbi z&NXQN0Eps3?g;2e>5x4$fk{2TVq%Wc$G2c#kd#p19Fx%h0Hs4TI_fM1y97CvpDfuq zVn#EMToN-&HtF})^X=a)!T6hN06R!kd0?Jn&{ix*Awcx8tsh%f^ zpWy?8&}Vl~Zic41DQ7}_tv)E@VX#bNWh!zBg=dE{j09@whO{{Ynzz1Z7XjzOv|vjkg4#I5DA3Ke+S&sv$S*McKeXS<7M zy`IuYp^;-`C>~FgY#%d^ZaUPvlT;Ry97iVjCv-+zK>}ej^5BexC$>rHP~E2dQ8Y5w zuC5c|qy|>*R{I_FM0mLzc#`Z%BFQDZL1$$LX_c}{udv{Kv)-afrtiU(g`}Zvu$+>MpJP@} zS}cc9jm+h;NE}oeBuiWAsP`)Dv9xf+OM}1}2RS~KWUbi^=z@b$k^D=kUt7intT}=L zc-*V<y~!uFl1Tu`EEnY-!1So>lDDY&R`Xv*j1QZ&qfOWY1oQQ+B8+6n zYg4sMK<;)$l(&9K{{TZ)=@N?upYkMxHWaDJ&!tqb+*OEKs;#wp&(ApA!(g7i)qqvVoTpy`e~ z`qlhdjEFn;o?8aE8o8D#i^ z%IP5>?8rFIJ$lr&;k}D0>3Fx-axS+hp7sYT4Z%EZ^lT59Rh3Ip?7)$o#OH8-u7YciEkgkq2j*p7fM%+YY-1M7i5=t^UBfCOPZ4iIrv8BXpsInF~VU8Qpw^no6Mgp(>b&m8rwv8rZS9h899+gVe4O_R4B1$I`pU?stf`D+{PWgM|R>G}{~yfiGL z(U?f$Omf8c`CI$fotF8!JqTCBD3dxR)5mJLKzQ$6={BvLO&zDz?{3k7N-Rag>CfH!G!H{(v_Nc=Tnx)a6ZnRU9 z?)4d%%_s~oa(jI%zlJ`NIicC6cups|vmF{x09TOvbgwc?XQhv#$7?*gOiLLly^rM_ zlb+Rtk}TO?@jBdH>$0-D!ibq>2Lm|iTR}dKO#c9ggwiFrz0_V62g`)+k%v-0r{1*T zq{?I4C$+1cC16N2yu~HL5h&fzBE$QVCRd)9BOB@ZqpnRNKm zGAlcRRR<^iioNL;o3v=N0$|8~f0Nrlndh^rTsSB6P`#K)J zR3??>$qmGiLQ>*O#1auU5>Tn~mKetTF49Nl@69D`BvVO`^-IWLzY^TZ0F>Q0c0swr z73EZuouD=k9C}pgKh&+NAVtExoNm#g9FhQCqZuG^>HF1JOGVMmmK8%ID*^1}G-san3<#el3WwIZ$ip}_K#KvwM-l1r@!v|f77Ck{r*Jca$ByUXDT2_{KZRk zIbY$91_14XKBUptB+~r9BHQCb9ZOA-wX3+>3Z~-{xIZjWhVwRoj5BS|9l7LHT5eDI z`gi;eUn*xSn~QC;%WZD)$EaLla(-Vi_K;P-n*%33k0PzfO4?oh{ri)~zeAg91}`es z@WUWMvN@ zl2;pQn(_52p8FqOMwZWT$M~LfX%fb+OGx0I+z!N?eK0B;<8ApRY-xX|qRg<*EONAQ z$O^)x!Ug$?fH>u`*U)vVq?4w|Zq<+$>o7&U^5jHh0GSEM>67h~lSRLnr_hYKySNfy zs9fh6KD2l2LuVN7Nrjz55`UO`Q8d+yIebuQ02#_D8LK9Wv$ebq>Z~{i(yW#?BcGS?_P9rN|YLtaayKfk&VrOQG}$vb}$l;Z;&)qlC7bTGTsL4{*~ETy;xGmfN;b5^C- zv02Q57i{xnImkb~Rd!;S_U`IG_*nx5kd`fh*N;lq%4O_j8^t3#OyKVMa7Ur3iuV>V zjxE=W@chZqa(Dn$c<#|wa@A)sM0YMpI3Cq{D*7X=WDh1}VpR9^G^ON-?U#)WRv-fs z*aIEvl2xO(5~Mx9yYke!0(&s3c`rFqDq5`Va=d*i)Y-)+Y>Arip~QfezyR_w=~^o( zW4Nx_Vg-&nlhUrVwrH6Xsm|x-zyXf}tsRjjbML8a&VD0e?qBM}5h)-Pe)A}0M&6kTgMJS6* z0bNYSQm7AA0DQ-eoZ_nuBTpl5F^fjvkf45GPZ;Z0S`28jJf327+Q*J~#Z|kqq~@t} z9C}OGsud;GPSLfC9$AOm3Oy+%lHylyWHz@khVmwk+}h6De}YNMw}(ZVKd($X-b1D%a(2AG5-Ldj+pte_Nvz^ zEVMefj1+GtXkq*;=f6@9`}C;qqEXg7LuBD{hGbBVgn}8El2?QC05U!4bgYWDJJTVK z&rXg(=J}@#&cg;n<`q<5us*zVS?Vg+{re9zGVy8&FK%pX@a+LjV|ij1V$< zbRFqyX?Fhrxe-rCeaQ~BZ5v7)Z3an-kPgzo06hmETC|-{@4;yFI%feIOaxW{9)6sC zYM)a|@G;aDOk6syNV!r2F9m_!&)0!heLu{r>}jgQ2+-eT(>3EH^2`+*_(otsVlmW? z0AE6Cd|L0n>+Vx`^gYTmWR(eg5X{!V*<`Bqm*c;oY`X9ANN|!~_*yb&y?v&)`pZE5wB3TtMo_WJ8 zYydy4QQKq^F`KW53j(j4SOD1R%~?5Kic<16g%UX07^ILZ%)#G3nfvoqNpzWXKeQ~i z^AcN?3)FSS0Q%&LE}IPZCzLX-?8+W8$zbUy5<}lndo^o40*z~J+ zC-h&*Jul6Q)~0)_$m5YDCh=t?a=FRapme|-(W`A=mHvoNN&N`TR12#uK0XDtwfv=J z{$aBmLdh+FN7Hhd9 zmL$BBdY1XVV-8e${Mc{Ok7>42T07}5l+(kw8{|EGs3qDw}CFuB1eg1u_S=@Syj z)|RUiU|dRqVh=mL7a#AvOVXm9vWuxrB=^wi!ZlV&Lo=pHc5KK&Bd!z-RHbT+n|z5F zujbSBC$^3@NpD1L@{oMcINnceWS`ciO01Z&%CR`qW{?ChtX@kxjNySDKVR0el6QU$ zV#o3ah$PYQ6a@f|zSUl~iy7{+WEay-aIA6(1N@+Jb6P>twq()HHTY}D5Gt^i6@AC3 zBoY_tS8AF_giP2cnZM-QfzEpxty?rY-AyT9gttwa4Ze|D@_6Acop}lQ zGI`_Hr^#;z8QJo&q=YEW4mx|&=u~HO1ZyIapA+)oq>~|c5(&WSO-+8K8N&Ick{Oau znhyI12zaA<-$YR8OYoNvqJ=TRZz69ixGIvlE$j)aI!=i2b8B-3uFR6|hm|q_aO^st z-l4CUn3A#0FU~}J(0~ACiuE;X7*Z!sg1R1SF({$q{@Bdtna!LkojxR^Xc_}PSP zjhU5#k3dEbtzO+3QQixY<#4-3GJdr*Sn&4@Q~7Ybfl#6t%-={AkbI%fEKdiw_x-9$ zvx`gr03E`Gj1B^lNAFg@n5pEnTcwgxO(nM6>+;bWzI3hSHUqPW|^Xi zaBxWHBZKv!chLi^%F=~9O0WQBf15R=Uz3+1TYDK8%+L@~P6q_w_pOyPos4xmXdqd@ zo8k){k&>l)e>M$tL8Z}@h$9>@sLP)>Ipd{tC&?LfEz(-DtdPt@k(X8(=i02VqNKFb zGx%mNC4f8CTrXT;*E)hzc66t4NfvLzdmA6{txEe)L}IE$d%JPh=s7ixe2<+YXhkTu zBA9I+?rCn(L~t{bo4Cl&0=itdsyUMKTr@=ZVVn%8831?disGMkcEh8-xoLY1x=(v- z{{Rap`EY&u)gfu@rf!PzX^SP|`Doif1-sVIE2=Pzc3UkKtnH(cCOgAtXJK6L-08NE z-pf+By48pv%E(I}Z%VHp`7svkd9Nky&BKEUHo>xA91l)@#->-YnN_jIgQN=!Ync%q zWtnnF=m*qO;y2k4REQL^FR4o+EKV5VSLw(4)xL|sPRHwS9P!QNFdOn&IVC%(CqPRB(Mb{i>}u(0vkGLt8izY7okw4*viY%Nr2L*a|SK z%Vmp@FmNi>YNWouf2mHLla>M-iQ>FjLKJ)%Wy-oJ=K(wLJv}O#e=__13-qX#zKU1z z^pG>R!NY9VAv~}bd5rK0KQX{1jyUO)(zJ2^0O_~x{{Ui_@@wy9KgBoFzlX=cy9>9t z^AV(6x0mIB2+ufEy}9aNCZS5AUB_?oBP=7D#wj4UxSCl!^kwsuZ#%lVKAap?bAh!2}VQRz-VQ?PGOJ5M6wfR0NLM z-Sy_8lwZ?d!msX1m7<*lrDB%c5>5+x6^62j^z!tX!(5=nfrDG$flB6^J31$F$15tW++x`(p+V=kE zs~Cmd!x*yOW3v)ErvCuU`TqbnB>QpeM7ceA{{5A1hZ0=Fr>~m>Wv$s&9!1DU!Sc=r z=Euy$booctiKxAJ`(NB`_C*_(yt9+d^F$;JLWgGZ!*a35ZiIo*8Yx+O%$m!P7V&f`t;<0FljY>tCJ zn2+A3FJ#goBeemXjzKuZk346Zgo;Rl zmVMH*73hCcR!HTNJiyF%9(g#$N=9uBwIoo0u+O)>OH{T+5i-otuH`>!s%4X+7WVMX zaq|O^E2;THnbVCEM{=%BP}vP2UHi)(r-AEI zfNC}?Eu*$RVBTKS{c6Qzv{5b*?dIBgb~S1^%&ATq)SRlUI5PSpM1{Hc$!5jw<6Y*ei(WvS-S zCBPyu%FoX&=sx6BUzgBmb1ktJGF%xNYpaWfVE# z?nspK#Eb$@^Btf8?!?hMT)ITRVVV`lamE^{VGzXzN53A ztgSVqw)Ufa{n`adW|#8!W4F)@W88|fb@{Ti$98sSO|`a5vn9b+Rx(0%i6tjH3myOm zf<;5EH}=P8d8A`3vBw;5asgFP4#Z+NW8b$Y)}g)9?07s`+Dj^YH1iO$Vh=GBAmei7 zMtM0n82*(+uTA|4Z7q@-t2l_=+zkcU^r*kFq#l zwY99XvWAb(Wiv~VG4cbjo~NkbcQt6zSMT>kCfOTvB&jx#(_y40L@DT{au4oD+LB*} z{-%-hN4al9k1P8vPZ-5Zwy29q*xOr?-fPP{Lb5?? z9@mmK!m}t)xj$ar@N?F$F5F||`xJ`OZ^^>b&9%{X!L}w_W@cl-W!wl+?pTsXUVZ8| zq56IPtX24MO$q(j~Tz!^?wu{Oh>n zj&tez^`sJMr|e5@J3Bo1g$6&0>Ptl#Y1w z0LfA9{{Vbbu8f)QPMA+1*x>x%Hy+&41kN|`7~+6}p$v?~ckfh^(lktS3xjJT1k8C> z$>Sd9`qZtWud#*o+RHSL8tqNkD~@>lqx9s}tgUz>;E=ANHNH5OHIaSJK{XvVfpE7C zZ5#l|P|QdfKb1h~Q`HjoH@>xp%Z_Q_677+KvB4|27UMsreX6c0ZI!d!Vi+MvmDI6W>Y9Vc zAHiCHkhb6+Qd|OXexwRUT5|A;y|j)d8QV&+^P~R&g^uh=GVTF}{og4*;C1$^#xIKY zvKv;rtQMOZLY7T!)@ilBH$-amvi;$!Ocg9?QEYU4yOxT*iS5*4A9(&@)&%9 z5O)5a{8nwgE&D&U*ae#53y@V#PHM>2x;@<7$#Zm)5(IN8 zG4cm|1wHxzKJ;z3`ISjk5c=Ml_PXt~xP~a?j0bSvD?4pm{{Z+w9=YvTUJ5;t&?E<0 zmi9(0@gz|~p|S`E=03w2=}RJuC5-PjqdW`@kV`RjC^mt)GCxccS+%yAq!~Fa*-!|K zN@H)8PeYD5s-{`=XPzMjIbbX@g@_~6_2l>MS4hc>mQy9+Ge*cz0H+)<99EBSVKT|3 zI?Etj@s371)mfxR*D7s{azYfmXK)PMG0t)ORbIL!jIQNZk=PJjI3G&4)S%heo1`v7 zFv~E;1_x?+2b+j^jGeiWumBh%9=}}F(NoQ&=`42;5JNfnko4n>R3~MAqC{d#`?%g_ z5i})+PbNL!74^*%+d=F?0G10?e8+BtpxvE?pBQg_s6Sel?d(iRBw!*ya7jOzjQuLqQeBZVMqb$-c*?doUaj}5F1BXIb4pQ;o;IJ5>6h_mnT|H7c=0{&ocO9(OkU*kWJNGZkfsxH`2fAhwAhif( zdxlwp?VNq8 zpB*VvF0nSOobcX-YkQ?lI<$_XA1NL4kLg_5vdurp>&1yU>^w<#7LTXf>6Xp4CQxSE z*B|eSoG^JGCR03=K2%liwKDP~aHtmXoFdm>!`9AqJ<)H_LA$q-MU!bP2~+)R&&wBQ zY&s-wXT7_M+6m>~1S&wRTXjrLTRrItsVD(Ihn(^|`_Vf>F&|&DY;P>{jl>^JRJtzE zo*cW=;)?2bR5AtOdzvjGs!0uX3)_p2CKfK1GJ;uGBZ0sf`&2hd%%!$jbb~CKRFGLs z6e%i|U!N>~l@;t+bZ2)K7rJJp@S&T{+}XkCGh4Yut7TMQMaxFf&8~xYD?Tn5mL&G$ zBl=cS?COF^5W0q^CaAJUCDNs(s_sPt8E(1%0DiTqif1-Vt(s-5L*f=ViZZbXSP**u z04Y7st#ChM)mlWoyvku)Xr(s}E*pC!Ta_VBxdel^wtlr`{{ZTp@Ae{I<4rbHYm1*U z^(JYSG7YNkz)X>x;1hs8QPVw5RyBS1T@=~JUATq|cr7k>TSp=Drg;WdR%Xdk0UTqs zS-MrwlOE|YJa(5Wr~Dj4$x;f&5E$IxDD)WT1B~LOTes)@mDY%;te-AT$zdZM++=+{ z{=U^z%hA#sASandOTa&fHiPpL1`p60Id;8?qtu#gWJob4MgS?tLD%{Zy;bZDB6W?P zFEHrr0o(4a_C8)Okqi5V{-CvlOVpaUU5JoT+Lrcp_@$5*X%-YZwr%<)F@ zF^A16VYx4if;!~n4F3S7Or=hj`Y*=T$9Irj+}nvGd7(u92GtneR1=bW1qbh%qTNw7 zS}GRC;oR-v9Fkc_Lsyk}Dp>6yEg&oa$N&O*RSjZTtTsbyE4Bl=`C~nSZcpec6QtWE z?Dwcbu}!2{O9R7ocW!0#F`T(V+gNr1O8w~L_+wjWt=+#CH7OOHtnvAd>l_AFNaQH4 z9o)n&=2%u-STCF6~;=BI+URn4)33IOv@J%0ZH-lnusqs5-+$li0;nvJ3la?Bb+J7by>L|;plBiE;T zo1{`hMzbDJWaE**J*w-YIYk~M1}O6X0GraSXvv~3Ssr;oJfP`W-Lon<-dpB8punqs zMAnFdXcBgBl;gc@o1+G{c7ynM$8*}E+AR|0q70}c4h3O0bz>$cLeb#;Du#m_b=x3j zJOhkX(I|U&bs1Jy#$<3$euMtPuX`d-MKe=TE!o(+vQB>0FX(eiv&uk_f>_|=7^C`> zqp7-RV#1tp&U;jNBFJmI$>orMatW)aYh_z(l+tV@os>T12a;E?{?%S3lx*dwz+%St zjlFW9Jp=tYx}k=mSF=!D0y+%(PdoNnqxLvHBkfnl-Quw{tIsA%htL~gZmWDKe^ z+Z73H$1Ad|@Vn3Xj?wATx+2n4b8)i4rfH#VN!ya&F({mewpkWv{um(7PT#Fk(bL3c@d>06g2!`m zDy><=Fb+7WB`O-+?Tvz=91>XL_Mni?bedyt9BY9o+%P-({?#|qGogpV zx@AYoRAhtH^WX1KN{t?^r!02K)lW}eeJWG;G(?4#GN7D+OD>7P(TGT8R%XG+)1T}8 zY2b!-S%cZyiP%FDP3K66IN8^3KlqA^(!C-pZ0F&?R%=VC5fKKy@LHs54xv6i^? zo^e*HVRU=9wGdp&_Y<&b7idNxG0#A!_2_=IN}IM-@1vcR&o$Du^GfLotZ}XfmZx_+ zSE(cbGf@|9Ux3vu9ifJGxpOIrmML7ai41J)PeGjL1cCOcik0u`L!-5v?$#6A+cQCN z6mba7MosqW2B$BLu8go^+7D5OejL2UO6M**EOPdD`l5Q6pm>w z3p=VK9;cucT5XoH*gVT?@g&3k939Au)SZWDIQmqy)UEVawMdUfNp;nYU6RZxdDCXl zIrQ9A>9a$6XfaoYZcd!X!}N z#8MATJ}?O)uk|yp1SA(LWgY7(86%B@9j7B3dBOC~DzVj;?uh$4lW_uOJTU!6d;XM9 zMbSS6qQ`7xnCwlvhp+xBQu4@h_A0(0yI5g22ah^HPI{>9F;gAv%1)0S62CI#+4k~A zYAZr6$?N--B1pyxDuAaQbJYH|S$Rf?Znr3H8U|t%V>umL9DbBtQ4H;;#wV3Vzz_qD zah5&)v_a^PzGzch(&rfvtnCzx-jx=cOj9hHh=Sr6BYDdCHtgUI4oU1jn532W;SqFu zy^qhfiZlhbNEOC#O6|^nTnfCEq>5h1va`cwG5K+qEMk5C9&-<*X#%mTLk^=H=ss5r)|cZ!OSgAYkasDE-@zE@PdTfDo@Tjd)jnb7vpbgL zfVungimu%iXMtnzaiMrlZdsenh=a6)+#X0i-RY#iG6dJ9jyZIazb)Y0&I;g#JSabY ze@d42y~tK86&kLfhZ~f|9~j5VgP*QR%}kXyWuiHfZ-;=p0K{?yR*Scy5`95_C1mp3 z0RVMlo_Xo^trDXbBZEw4fRe|1l6Gf>sqidkK1_@o(-kBhQ3`@bZuAFxa(u;1;aii% zN6?eJl5Aj%#~C;Wr3H|eP3K&`0on-9Jaz9=^fG6JLlm+Q59TzgvSLcuLeowa$iemX z6$`zWqn52{J-wZ@_V8~&7?(l9l1B!w7W^1wTPvErqCi;Bk_s=D3LM~PJl3|~M>NLL zq<1q;NL|HMdgPuu)rvlf)Snk>-wNOxc5T2vO6yWmjhM7vJUep?{uaEnV$B!?e4`n_ z>H3gsizmw`XLcoUJ9swTbXzOyolDHOwLz4~>)apjRh+&glSZ+B4lT1Y*6*89)aSZ6 z!?(x}W$j+39Dfc9CzX^k*J$fkWF%d@IP7g&aF~c?cs&nn*O}@SNwd+# z(QnZ-L#x@ekVI8tQe~c5aHRSH?Oe$wx;5jgWDHj&C3J=|BTT4f$jQ$YFG$Tubw9*h z!tttRQ_zl>qU7|^XVDiWy~4-kJSw6y*CUhlts7}klP4}>H`)wQM$FtO4E!>k$MxXT z!CuMjF4ZlpBaA#nB2n|6yT9?Dy;fbCN1?0id(dNz9$uT?R9^vJ-$scG1j&w73J#q_rj$WrBHkrbnYxT^E{v(7Ql)g`y?N+%LDp61v^ zh>@9@@%+j-LxYv+H(RkDkP|~enOxsmTd96cH##oJmRI&@9*3FkVD-u z_=%BHBtS;ijq;=(ocdIGp=2JTJXZG)6`;bo8=f@*PI~0^{9G`GFmQ=daqV zmlbT9vVU1gF08CH`EN~=-C1oC&w&#r_4y6r%X{U2t%;S+_5c=qX2tn-m-40 zK0KF&-T5c{MzkxB z5rXdgs=G-f`u_mlkygZ+8+ms3z9_c~GsSNrj7)MEUt;) zM+4>H6VsDY-zUr8@AxQ}AD7r?x5*PUE4h-@ql(=C+Jgir`VHTDmwRj5q4YU2+?cMB z&^*yc7Uy-&@=|CQ@>wL9AsTFY|32Rnj@cl0?ZTt}t*r z)W2{ubuu9h`MVEVuYHs|L8lNE_6`Rpy-kWIbnBR6NrQ|yjD;iA)TU^(Mrx1dL`WIO z>rVw|vIw1|KGJB6Xyzt3A&y75=~hIetR=*ME_V0LM6QV*ga#ZoPaUckTOf+Kj69`B zZusj~Pme^UWX_EU+yMo+{VO~2b>fLsF1Nxd!%- zZrQlx=aGuN`7=nf+5SKVLif#4?A{@HGWnr-IO$7BGrpZ_w|5(e2M4EWiAad6Wsb{A z+w&2D+uxea$(=BQM47S>Mpy+nTn>59aaHSPr&~K9hs_`_Z>?6nib^Lz2FdSs~Ehw5pO$Fg?HDN`e|BB3-CAjnXRwBe$R* zwFsh8$)Y#!gc~Me0_Ptpf=})Mt1ZYrh|7&mCzeSSm6!s+DEU-isXTNUJ$V5RW1Mn?T^sawLpuQhJsWqOlyTx*qq=G zzpYDpXe3!;f;&q)*rZ_SQ6wQgZNqLz{lKcXN!eseM6lbuGq7${LfPtY0Ux|?9Qo_tZEK2@w`7d_bEF%>Sfmx3ZlTQG-DnPO5T zmOX%v*ZWjArd!C~7+K(oNe>MW81$^-ttS1AFTnOUbZ2!{REY145#Kz1^?PgdD9+I+ zg`%}>q1SYULCIamfKPLQnu@B49qcczB8oRfj7aiGq>u9B`LR~D(F}y1Qw7|z$vd%N zxd(*}kLys=w(PQcJq=t-V>Dwdh*a)=#Cm#C-BA^?MI^Rq;J9~IwzrXF4Ce!6V6o@j z$RBE(ji=#%3;mH!hI+#^QY;a~7L{%zf??)YPTu5cIH#Y%U7#2WJ zDmdv^<9jP;eJ$JS5Zx?Lc@fG=;~e3Rar+91HtvZ_-1h`NU-Dzr4#0M**`g*cBtBSa z2=X20e^#ZJ9%CCxSjm4llbG?hG{{Sc$1NN&$S)7PZ3=ssIeGgH_4NY1R(K9vX z`AVPzw@+@hSJ|RxyLU3UR_MJ(c&MULIRtxTiJc6JqkAM>cFkib&WriC zso(%X>yNEpg^-yGb#T+pvcn{@JP2bYQ}Z$E0X=HkvV;8{E)roC%#M=W!o@^?F&X~= z#aGQgBD6G}A&&J%qdwbDB}<~@v+itQ0pE|@)I~1jM6baeeH>D1YLgzJ1J+V1V9-wOWe~^;`2j%#%h0 z-b`r=5T_nm00un>Amiy%d(o9~(HZf73-K1N6bWV=NZRhc&sJ6 ze*Xa2-Yj1bNQV6*g@Lz3!ybA0v-aspEsG(qZY5-qRy^bd2aetU07|=)16iZR!pqbZ z5+7iDezh;VC_9bXD`ACTUQXQO9e&kWGEpS2=RB@QaezLREV}3x81@+n0rv$9?ewbs zN0Fu6xVQ+RvO1pJ(!)7{Exo+Vjmr~)yyA^Cik+`!b7dKjfYCZi2p^eLjt8exNiA6j z@8SkavUY+{M<7rJOF0-(^vzmSz{xNrmmx%s#zx!IB#xh@ACh8sx?J17;s_%+^`SE8 zuPkISeu~6^tUG_d?OG?~#iPnbkuK6kSKgwilzRN`PB|2^L}kQT9r?{jIzYo|h)PKuVnG3!oS|F* zRQmeWT_tS0bVq9XjAr_43y9?|2s=krI2bQu+(_or=frR-oOJ{;qRHoN285sx5KHl+G^>o3t3y0B1ed0%;03V^{!mDHTEhdxTAi~PvZ45Zzdz!SNOJyRhoi)8)Ip=E|33f*eg-I=) z$GINWM;1BwM9zls@0z-eQ!6%A*u$v3($2Cu_@szUKGHTKv1ULp zSFe5CpK7%yrf1}7Jf>NO^-!P*0{03BAMf6wyJe`D(XG)85}szbWs2ffIK**|NA1Vfw2t&ve}(>q zLt4F_c8+^((MKak8mVlJql8uLa6V#vYe~1-Ir=X?7)4z|=#<+G$8#W;auSP;*f_^; zT#;B`DN(*P#5Jj|FXE6|q~2pOjIK8-N8dg8sO8Ass7S7)ODizw;KodDv94JE0F_7e zqwvamoK3sUD~VNbBzG&Ga&grDl|Pv$D;R`Qy9Ed3X22fRL|qpD01qg8vXV9xpxSn} z(iCCXra{7G*)P1ouL+1;eY#0Aq9(ia1Bxy)O)I5OD0v@{Kj&~vudP`qS7e@Ht>Oh z-~*E1QZtWwI&%6D`q}EvW}8r0t<{*#@?&m3RT%npAAD4;y?HBI*zPix(rOZ0KKMjy zwYuelfKRzNHB{7GoO&#+)tz1yotao=U>R%WG`}`O?dd5`D1_b2^|^mwW{TP+$qamG-R44DTt%a)O@KFtF_a*^cV7U!Qz<8NnlIv&b@ zGd~Bmd(>HGakpGf3uhH{w`Oc>aVVZeKtDD~$6hF%vnddF5V_viIL_L-*^^X7NX%tW zy))X4+bVa7153X-!0%Gl>=QPTp+;#6s9wX9QjuaZ{D@hZ3Ci_8zSUN|qOFaDrd)62 z5Gu=LSdvDB5->+NZ|IlQthIJao$&pHk=QlaLamL& zf0STk)f?58glLU9v_s8p1vu=g7e?IuDqcScL4nR7Y zq$0*+W!;aIW9|A?r2HacCh)L1AbJWS);2e*7{DM8QC7MQSmA;=DC##bBXb_O89${} zr1Z?_j?`Gm1d?vU&bu@IP=A})oOGghzj9FmQxB2A00H_?x(1Z0=huNyNnz715$1`R zNdOjXbs<-A{=%j^XiKBOxG`P`SvD3vVeSF^%m>`jI&{i3dyyUQptYC~vZS*WL!GD& z2IKG83Yu-C%HFJ7NFYUNEuv5u1ObK>K<9zn@l{pYCvUTsqi(kvlLK%iG40#({J8@p zShdGw=uvMPu>$&20GMv&zhkS=)o57MUh zRqRx84WgMH(F2ll6b?55o_&Y*sr-u;8wkAU^vIMUSm9xHk&W9csw3Q2^&{MA zJaQ$x2Y4l*MtlyW<*)~?4Ohbaiy@A+tizzd;wainsfZ}5GmP_}+xD#zu8PT=t?Z>( z(o5$4Gp6H{ow?_yuQ{qU?pYQ)c#vDBK$1afS%Y*NvN8G!R{sD($=S*am5Lapl;IHu zIO;&E#i~u0k~`a74}p2ug*&)7&N0yc0D8BJDEpzMgpD&P2<%^TDCl99YK<)Y?EHm@OYm;*g>OkxVRbwxiXKTPP{W=%89${=rD?VGA}XmI zWV)Vv5~4hph$@l6+*czXQ<|ikaqF_wkjGM*C{o_op>&Ep%@9xF?#5WQe=*3%r&^Us zDEogxkKBW}m7Z%?m7C@)M?RE&rpQE;ObSAT923hQT-5yyD3Z0^@sLLvvj<)WeCP9i zl-rU>t!Rgm5G`UM%Wh&7@yiUJfA3UXBFCxjEfHfV<+8$EzWC&t(^@K%J6a;jVOV1% zGXhx^&(U!Iu?D4%cR&l|?1M(2Lg2LrWa z-McQ84jd#Zm`G7BX=AeboHozG<}M_GC#!^C0f?nHU1*P zcMwTGnEwEC`&O!3Mr{?1BHmC50|1lPwL*Fc5?0V{5;GD>{ZF+)qC~xwvYn);`F?CS zPrX%>MEr2>_-`Z)==oAt13ht3S5!y6mHz+`T>*6|XIUdIL1yET!TV&^i(QmB=&ECe zHk^edjo=OdC%3L@I;$$lSejdlresZ$GI>a=!#E9+e?UJ{Yi+!0+`XsfO4$mrh$|P2S*LdqAE(cC9Iv=em z=|5nZTAJnLk)H4I)S_UMHF(7VngT33G)Vi93Nl!mj$H zVC8I!M4I8HiuNK*GRPBe0Kf-aj;A=zeMMQT?1akY-HeH-wcJ+{PqZwhi05M{>Gl9q z>t%S+E2X20b(8pP$&fN~NvLX(q)8d!H#1uct*E~&sTesf6yrGb!9S%{t?aryUc?eN z91spk1Fkq9TC)$Kjhqi8S7tyIkf0OJ03@2K-H>)Amuo0J)N_xmN&|?<7UK*uaz#mG zacSg7+8G%~AD5bf8#u{6=L#@SAZ8u#xgCe4M7js7 z%a0)(sAgaas|DzBl4@l5k!M&f#8D>W%Eq9abDVSarBc~+gqP<8W8@j&ng&H(U`Dbp z92^R|GLXgs+pyej=k400gh<=Mtt)}k98`HOk>%qaUNU&@Dl9RqYE(+cxy4FlS>8L3 zF2%P#(oTAHBh%8QbVDIbQmm#;>$f9;MxSOw>morVxWMT{L~zumBG!G(c9F>I^dg9^ zN20Eu6g5j(WLJ_YuuQHx9)y0Cy(b$uypxvqT79h1L+7bk=Gio?xiNw5>+MjYmXUF_ ztkGO*cQ+Hu8pk+c6F4Xad*kRSR>9`?TGJ8;!-<$jA=*ZEpP=@sSliM?d9I0j#Fp2? zYWr9lry)Y{dB#4~n^um7oKfD{Y;UV$(iKHAwk;07ksdk+asv~baH>O1c z4>DVelD=ayNE$T@oQA8ZzO2c?6)TSpMQveic_ZZBPEsW4uyx7%S4zt!jMPzZ@N6j> z+$*pFh5;Pl^sY>uotT!19aT_i_i?PO$OhfWJ%wgW`YKv|gm%&|lvU18B~RD-)#o=h zV;GKg;sV60(MH^lr$5%A_DdqQxTm?h)2t%_$yL~=xhDd;VNp$)Nn4{qo$S0J;Zb0! zvR&LOH1Cjb8-jl40DBL5=eId*)=febjMG!uZV@F&8|K`hNmez}1ll;fll~hL&1~Qw z;xuH9$DqzD7QSYV*guqzg8AaT^4?Xrd@tqxP#E?8m77GF)s(jjcJf_peFR zQohaveIoB2gMWuw5|A&+D>2K>E;lhggC`Z>$))nHk8%n2#ngn8h?~yCMvRES@VR0} ze{OxNO@^$3wTf>fKGB%uXptCvzGR?DZ~Y})x>O8*`@OVMe>LQ@yB0$ew1yp z^gFuMA)4gM5iPz=ktTA{sNf9r9<`-gvZ+z#DCBFK8%Af6N#l2r1~?eW4V?A@v+|?v z8_^MYrxw&S&B-bz!6%fe%8t1sA+v%`54r7{x>`mpTP5_{aTTja8+mS3qK7I*&`tqA zL(l&J6IHs=qCmEb6w51Q!x$09qmlp|6X}pM^)ybuB3Tw8@}-Z-+%P0Zlmw4OkPgD9;lPbv@WekL59!U4={{V`HT@G!n zcS*OX2-}G5$NlQRLhR`&^6vbXZjq3Kk-H!U$JZ3C(=%*yd42x?6$Fv0vq0b|PemM` z(}DWcoVJ=Oqo#;tyB3HTfKFM{lgT3)ZsgTt@|J4OS2qS5c+@CsyM-Q7jz|RUWB0}f z-jexO)ON{>GQLq*3$&g~6(D15nE7&ky!|RKw7%ICIntwrotAY(1~M3rQS)c+YO(eu z{SR_PUPqCGD!UvhJaTxz{VLbwk{eP|(>fpIsGQX%^NdRRy?r~EUeVp@^5VC5!%K}c}#al)Wc6+zEGcW{( z$sI*B%*!o=Dj=Rx!0m*bp7|kh`_)mjO8%t+Op2vQ22cp=oO4>hOwM&%Qx)8@MfpQF zUvpj9=gCt!CD`vkn3+{}lKcVbSbBv@%`x_C{vNe5+X4VBk&*3#TrJx@2rUn8Ekpc( zbjK&wqRY_XtQI);Duc%(u^Vsn1$g3sK|>ZO36R){%m`F zYPP{1F36ai44+Ck`6WG)`eeJfCj|3Zd848Xv0Jl82M4FM4ur;%$_%>+KQYJJse7Xt zc37;LRxz}2dYsk2BWz>jm`E_AC3^~n&C?od03=`{5RZY^oRiH~PeoZ^hfs!X8N_Oc zU4jU}>WT>r-+pmddsakV$os8I6@-K#Mbv$e(OSjc$^%V!;c#aSY}h-jsfTaZS4w4-)PY_mjh0NL`D zLx4xGT+|~(N8My>OyN{6Ip7+ED2<(hMimz!OAL>5Q_>{}<0^pkW&qKWSW@9F67ksX z2?>iMxi}5`3N2Yz;DXcPeM0$OS7PZRxhvOUIKUp~tvKJ`g0@(1B%bQ{M;u}mNc^TN z#|eO-dz_j{w<<&=sB!W@t7{@gSSfTpfzKKGRH|PoKT)uNHl|*Gm^uW0dV+pz{f0jE zAM)8gG)C&4cu8(w_-G^tJ;7xl@$|v_Qr~Q^(2KRT5?Hk462@GCyYmh}{edUzR*JaU zUnjjT`{JW{llVw~fP{bd4?B<39A=}H?6nrHHARMk)3X^fIA_TGpo|gjDzD^LJ9Kco zVQplVf@m0e-c0u8HmJt=Q-iUoXe%Ow!LWDHKX@6Yu)eMY^(SSzx+PI^~8l z843`8m;sKzKslp)m`ah(ORP#8p^;ny+~5<(?fq$cvQff$!$!8zMj7xJ`h6+ZiN7P8 zJ9b+%ic$b97=zzDkx^QrFLph*`4otV4giCj&vwV@s<`w{Q05}|aoKjnHVIlR@J1w%u=X1Li66nz~M#SNw zCmYo~&6(+ejw#l`&s2qN?h@7k{{RmZYN*fDf(Jj>^rQJ*E|5;uvNB63Bl3>)SCL$j z{S=OI^)+I)JG8vFwzaUD_57m{CAS=f03HDDa%iWiWfKoqZiIk z+N(`%mqff9L@e#sY2JY z9hi^iJ$Cz!gWQ^z^3p5W5v|}|GRG>+BSnQ6o^ZV5JQcVSH?p~J8(xQ&>49C{eK&W<*A-{c1p7z)bS)W6H4F2p{K^-11M9_C&(MM0t>B99 zRK1=Dx3;mgkKt8EGD>=2ckWNpr8{n36$)u3?sK%hS*6opzJTwF<==8QQo|~^_9Ho{ zjeM#5{{SSr-4XY8uUK= zhQ=$4ojy&78fl(XC5t?PdS$u*Ndp+C1!SUmD4+k z>JER>w2sW#;wLv3CDeSXGoN58TfKxjwQao*QH<45qCLnC2=D1aMpq;F8wX69j|Ex6 z`bF6kZWXqtBiz;PbY&tk?Y2k+M{1GC9<+Msp)03Gs|jZ1h#Vf34@}lQ394Fo(CtuF z+!3{p1a@y~C+<@sv_sozw;F3g(&`HYGATY|seB%p0=JB}^f{bpCGg~T7m&0XgffTu zr3n_&2Xo1(bQEk&Urvq@HJmcXa}fjnVZqP8wOMPTvqU|P*>0hN=GZ|TV+B;?Fb5+a zrA*poajlZxCe)|D)pYwiCc#prS05rSM_ zhd-x1XyWAW*rSyWwY_ISveEBstuKBiMuYjl8IiHMR~?2a3=_1HD=e|CGKr~7e9b&; zbVLILzCq@?;~$ljPi4Quw_aJ06Tw_!xSHA1321z`3@@g)Kumc!4aYT4`B7)F)K47t z{Dg^6V4c4)Be1A@3q*dY9#YskSqK&v@msOxyPl3}$HZV}12 z?JB>N;N$B{rDC>1Tj>aze4b-5k|JLLeqf+=1Du?mm1xgJTG;1PSmD#H?k+{gkS$_S z8i3C%Y=eM1nx!b%glH?Y0Y8;@ZdqH&VC+4l$0L(Yx|e z4#^vsAxk84{6$EJCwJyz4{rPtKIW+UwrNCtqzElwELHArBDlM98UihpbfZe41hn&ob~HbcI}ELr-`C+%rHz~;P5IW=(-n4xsJm6 zX)g$CXG6OKJnd|KiK<8CcFC_}t&Q!~{gTMh6|uLt*@AZEp9g3?xWKD9w;r@EnP9Vx zU~7o(%EcV3BxWd|d}Wh`Vo1p&`A=%Jbob`W+P;XN58rvZPMUcT+ir=DagY_W$8c~z zK~W2FkJJ5^bgXX+u(pk*1iHe%o1QQ_e@d0s%Rb17t_sQKF5C$Ye!jJ9D#tc=MOdzJ zmd_Pd%c8++DwyB4b~We<4_~cg;@Up6_=6+Lfwbk`qay`P;012Z6SsTQ3T*S z!h?cNzy?RBT9>4f?2he_@);dnL}|U`SkPqUduQvxH5(?$9Tp@PUmRLFWsH3ie?G?O#c8bG2G^~k4FwyvbA9% zNg-@?;8LmV#S-ytjP7y)&N$+&M515f*{zur@IcQT5Gs^vh>OW&iTV7ioO>VjsZO?5 zL@mXMxI=&f=CxC$qaHRm@cxoT$YP@a);V%HBW!TlrfL5Gz=ZR`7zZ6|3-Wd)NOUF{ zR=^qP4O%-aEZ1ypBvd@NKq~eb2X$)mZk4ikHZTVR6i>;Fqh)^n*juBA<3BM6in=*w znq*nIMFbK7?T+N>I&zMYUf1}HwZ=I6UxzM!sxQwB$8?qNJ(%6YLKr+C4nbCyMLjoKg8KS1-+4BmPQeV_-+cQ&#p64-F}3m zag9_2at_itk3CNvPe3X@p^@776GZ|)Pv<3%%ydsI3np`>DU-3<$yEkwGdCJaw${KLoFFj-z(p z6&<3&ti&vg!0-+*Ijc9|FLFlLK2pUS4WZ*Cu)$y$;15imGwGVLTBI+?`Mj39WsDD& zFbT)yEx|w5mbq*0!{~s$-z&>LczwlGbOQhn)B#TRPtb3w$`P$Ta0|!0kTIUXVx~&y zi#lHFO&zM3&=qWg!>{|mq?IBQ+3!ue+^X_|(J&y6nd6V%p;9c}kk^+9{w87@TMd_E z`FZ1ywHI_$oYJI(T+9$`Nq;%dIqW|{R+ScsF>!1s6FU$C4ha3KtzDCKp}aRRtTv`K zXry&b**=G#wL*GS8uuDr%OlMyZY3S^*y!E*dS<1BMnuIXSi`JPo!Q91UwVYMLHnNW zE~D~eNhBz-r*rN|>GjSkZ``d5riGQQUP8mkG6K)g_Za(AzWf8RB59D0+0K2b=E8pd{G^KDU_4EOI-F2d-JlG&~xMxQGhZj_9%{*zk_PAt9+tHLOnp_((M=W zNA1(@DAAD|LDpR*?ty0j(Nz`5`w3nTJb#{@X zzySXMmp+)OgrCaF%gFZCJ|Y>Od_@#1&rq%I#o-N8se?Z^|iXp@XaEplFPv4XEmZ%O3Y>1R=2tG z??sK`Pc6bqu#~s_!WiEqr=t=(;2OG(syXELO=;SUmsf2#7YP%(x+BPW3-YKSanSR} zb5&Ap*`nx(@pbHWR<0r&t|gnvb}Ny9GI9E2?^?ljXOYnvqp?_&M8w8<1Ex9YMyXL~ z77=o>D@VU1e!0hQek&$ynZR8&LSWp1^TaM4q(y6gU8U$L~SvToo({tYU3E}GAd)>s~1jCkjlkQF^{pSWuiNc2qOS+Y73*J zgARUzppm4h&)n3I&o@yZf+6zxj7zZY02mc+jM)!7Upec=8#8E;umz$Eo~(c0?^Js) z7CP0n7;QA@NBjeNEu#8$C)8NF?|03de&Idri>Js zE2>?khLdXquInYsd5qY>LH_uvC^=~(OQOeSEwnEWU269TCAv1}$qmQ{xAy&O9BH{E zjb%`cludT&UqsV`s1mU(?gl@XrFP+pQgm}T308KOx)d z@=pTzi!?a1uM~@|%!zY1k!X#*NZ#1(*pvJI zm6O|}awV@}^R6Oy+>w$Ml#&S@2kTk2;gQIdWJ~L9K30)(vKYi$PC)CrqE6|WMOi&J zhAj0BKIX^D22sm0e9fJi108$RDam!(CBiJP>K7IoEVkNxy^*}Uh06J^Hw55k^fjy< zt8Bw7Nzx*9*^A94=Xn}dURklT)DJ=WRhg35>qIWra->^)*q9Y6cMfWX@VXu77js%! zTt*$kKH_u8=rR53k(P}TbUVG%o=qBAl@ZDicDGFb0JB;rWil-qHR&yJYa4APQNuEf zf=h$f>zd(xq<2K)Bn(2NL~mjMEHmHIkJ%SP(H7|zJPek36gfH0cJ4p^9+fG0E7BnE z?k>&Uy|k$up!~}xMgykS?0M#rzL_+Mg;}JAP|~6zs-m`VOE=8e2ZMq7deOJChYt{G z;AzT`yZLcEcB`Gh%7F}O+3UA0oZ#mjDqFAM&Pw!0={8MaYOu;87Xf^iFs{Htk`5@u zBSV?o%H}xB5Q;(!-~vY^{{T;=L+*_RvZRYNa!3>fjbVpz01y$7<+yVdvun5Ql9^$W#sWZBfq|>T0`6n4!d0#akz+=B1ZIvpI-He<;uEN)|ZypmD)1$prrZT9%5iSk`$K z;zg24k+2_jFnWKl6s6lBkG~BRaDb$_lY-610OyS7sTEtGNceKj;$1EsIo9LPoy*GZ zIgsI1Kt1Y>IW8;79c=gFIiA*eZ7n48VTsXEh8r)p5@7ll{eY`ZqP|}rZ}$f)4XBk%WP9ecjZw*wSqEckB6e(n&U*1h zx3iz4w9ZHYuziI@rS46VT5~ywuNfl%Vu_nU1h&QUrF6;v<{qg zry{BwB=m~~Rwr&(lUcWH>4a!`bvae+G18)}v(U!#P-v8{dE3V|qK=9=Q0qgy-!e3Z zpxw#NM_P46##T+j(I`BEp+g@`nyOS?l@Ax(B1j7JmFPS1+}4rk;?3EgOLG2Z-J}nC z=u64TXEQO`miV;uFWQDcL^!a{J__o?MtVvg3z$~n&+s*-j}M{TEeKnLEa*<_0zh`X5> z;~?~`DD1?GNN+MTlkJL=riiJcCgXNE98~>EQ0X@dY$i7!zf)4)g_4?FUQ}w?#~nJ= zO(HGD@~c0ZR4T9}o_k`YAl`^QS~Dyv(2c5iAN3PSD_S|^j~4J8s46nNbKan>GU;SI zt3=)TjZo-@jvBkCm6B8w#|Etu(s~)_K$%(Dcp%{VQ^64|uHW#RK?R(s9kGvEq`Edj zI|)p45J#A~=eh4uY3#B&#JieiDUpJs9S6VeY9r-_GPuLs2(z{@eqw%4 znX|ZvaSJx~0wc%rjFxY1yj4>{r{v=IE~>yOb0FTpfCoHt+|(w?p{&A3hBoX0+&#|~ zH0Y8d?oo59K>-;E4oG3f2S2S@Zd6h9H@%&rwrC_IJ22xtOAbFzN|`-T2z0U{F~-zI z9$(o;rfAnCeMWQpQSDc`E3zL|m^3m1N6I#?!HfVfIQmtV!_q3K zvfNz>0~|yEQco2>nVT%HWB&jH5SflqG6#0zk7%+XuWyzOkVJ6joKe?AHbtd{?4f3m zIwKwqGoSV5iECn;Egm1VFa~oxtk;@*#>Hf7==q5*DnhXJw z-`=A1340`Uun8MBT$OF!`0Y^csShNTmA(saC5Pn%jxSWpte@s*-dL`)(H3&9XJW)uop;E2CzD-M7qOJKL?)6h|BZy>_ z=PCgJ3}YO6Rnk^bIug@fhGj)5k1HrLI}wV9UI|XiBoic)+eDHAN(CE<&fFe8SHL6xANi7maU9|#y@fmRleFDMs}8-PMc?M2Mut+WOfCaLayWeMOr;1ypbY0 zOEDzq%@Y$WftceMOynQX3YP4x4t49MgGZd(MYSEUqdcGY){}3GqCAoMgbHl!E##Il z{{Ru^NO90G9DNQCG-*;yi`!%#zbLrYBAKF&AQ4DdeF^zg`})?2+p?nR&AwN6Ic$;7 zw-s3zfo9X>!vWX5X4$$P-0l#$LzX=N{=dCJB~!&SJ+;P}a*j?S2o!KbBNgZDMQslZ z!f#{*UR~a|BS~<^DG-Ec$INrd`Mp7{A7)i$z6g>Vconc8a`T^?)1Tg`{-%hnc&0M) z5aSUmmpgg`)2Gw=){xS(3HEc*?aWqaGBBzS9{m2bSuV7YM8sDa}#GIZU*87JG1y+>Exvc;w!*H1qnwI#ROG5vQvenxoYh$;SyAGN8CgkYJx8&tB}7S#^iBr$%M!$#{+Otb zR#fF7GEWKQ<~HJ`G6_93H(Bj&RN&(t^%h+SiUg<7o_#7WWsi4J;$xB68lNPLCR~*0 z0V0+`=g8d5%nnXRTAM1+%H|xF} zb@lb4Z3hwKXtv-a*2s{@Z!QUT-oSsdc&l=46r_s3ifkg*wIc0$_XtA7k>eQq4{~c* zHny3RqL{|VK#i`~Ow;XRG8up84?uB~{*`G>w@j>Y+tF9?+@c>5y_s<$qbkUKIqCiW z_0@_kr!yHkkmto(pPyrGYP>@!UOVj{G5-Mie@f33De_(sc}+-&*H+$bHr&TH3c2}D zBl3^EZRyiec4L>M$XKJhbsk%XMc^rZKSNzdJzqn1if=b##^wJ2%SS|{*<$eI1|>IA z5}{5GM|$MXv$Gna*`wY!nLL9ymx9Bv9qW^JZk~qHv_BOpTX|@bZd8%^+v>o2o^erW zGL}#25y=*ssPH}{J#p5p zmTLOZ7~oj+`*}3!2k>V#=h9@yGOA(#>jtC8!DDyY|q4<@vb zi^!x5%1KS5{r9WI*Jm`Hnw{$Go&+Ds7g6=ia<$RuBsqx{e5NWGvnuD%dsL;deT`ze zd9{0d0D>sQU=DMaZh7xjgSjCsM2yoXXV&L)%fi@F-1^kZTPxXZn%pOx%CM0o#8#g? zdx(gIW?bjKXyaG;rTS=(WJl|c(dy}Py)CT-qCU;XPj0l5so%0HmBg>hyUa%?lDp3y zy$9Nin2s#aJ=MwR$`2#he_whf^D@t*MruTx;~J6{JOPuF`qKABNr<6S7nOiA22Zcd z1sc0Wk>25p#Ql^$+f?sG5L3N z_2R6R63Hb&6}&1iL2}0h{GqOW7L?F9Sq57wqD zZ|K80X`({6LP<-9nTu{2$t0SLYV5l>`C&^kGzKJ95VpJgYIL&DmR!EJwkg3Po zx+1L1_W=!sBil6%Y$MgfVn8w8lu6#+X2?8dvy?$29J|#?9cvjDM|A~*H!IG8G^A9|TB5Tx#lRiHO(Zme)-mtj42 zjCTEN7q>@DA7`t18d5jlkt46$IR4cUe7iTJs&N}C@tpHkS|Ro@iG)m&72PD63V+Fr zay|K|TG)QW;=Wvwx*Ru|f!`goR=Odt1YGkOF3fH+oiR|IvM7<#mN^8@>6O^PE_!tD zQ{9!8k=Y!y`^OuX7#%7+*>3_|&dF?De=r1R*9N44j8_s)jkuBAKn#jsU5BrU`hXSzl`bu@Jrh#!nS$y$+8TS!8g> zCp~&~6`Z;V?p)hg&he6DXjOL}*#n>6tIZ*ncFU!rm2YMy z*D&r##~gJ30C}a+omqXph859P6p!*o0y8lsKqrCq%|xHdT0MhWta20#NL9{HQgAxe zn%xUM-NvnMBs{Pru6tsVj;vjkses))fk0=N4m)Fy?^Ukf!Zc zRc+A?9TWKR+lKybYU^|eyOa`nYT5aDUu>}-+NmXFiJduO_}P%gO0MT4JRB&%{mn{B z%D#u_+w5Z?D*1NN36XQZVO*2gRHRjqx4M+GD#pWy_vwt9(lJkFa*(=ID}8!`enxjUzkjt$(FzNnH2tRFsiHuKCWsd&|Qwa*Om#MMkY_ok;VbfPq4*ZZ8peiv^Tdcc|GZo zun~$V9e^M9sO`HARS~+P$#o+EF38|!RZL`O9Zf{p6mpofw=QI2$!!`HPRApkrCsgY z@Mg$A60#<@^2P(sgXRbFjN_-SJJsHbqm)0wl!4Hk;-YGeB3P~1!zv&-EV<9rpY*Iv zqDcHf^ETjNqvTYjvRPf%R5Uqk@7%##{JE}-NXH=sp$y$x^TIR6qa0%uE2A`7w6-$q zR>a_L!ynxL0BWs##h*n}TDzN3)@HSK2?#A13OfuR?^jP$VD~B|>|)9VE%G0iZaQFA zZ*1s_JINBi4%RCdxQz_yr@`eBS^*?Ht}delE8Gp+hCg6Yx7#&QVGazLs{ zY0yV2H{1d+1xhdP$M>m^u`FwHgUt5niq<7Yl3`_0fr3R#(;#^nA2%FqK=F24;MZ#v+NAOIYM%ydG`x8zpkqHV zKYUcKi5gps+$a4ie{oMClG=O!0K%^Wx7w;*9HKwP$Nf}DvK-DgyOZlmC83rE@x?(0 zNq`722LluXcw$$$i~ak&*sZ0Nl+(vAGV zkM+3z9>#GS9LUP#{XjiGPtuK2Wg8&jw^h_&c+S&o+tgqX#0>I2)wFcXnzBDt)UI?L z7g5!%oHgysxZRDSJdij8>sw-nH&4l)Sv+xV86>wab$J`j^Gxyr&Uq)A^my@$qmPri zEV{e_^;iR(q*m*-M;wuy)(Pv6xusUfO>Q8TvGPvY2>pd?fX^>PGD{?9_-@PeIIe>W zqSN55C3SgjUU^7pmmuRg;F{$1GjXJjuTLIJWTw9acG|+}&@R}ZgkCxKhQc_A@KK zSAVC*ns#zze=#$mYIhe6X%*86gwQ)S{{T_Yk4ncQFAnIkT|&0=q^t8gMCT{iaahSK pv#J8xa}%K8?NVF0$jPduqefP)ELZ$RSh*_FXK!k<(?=^u|Jf~A6(j%v literal 0 HcmV?d00001 diff --git a/resources/my-giraffe.jpeg b/resources/my-giraffe.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..ebed77d357145d3920b92857a6e6c0b5c78b37d2 GIT binary patch literal 33499 zcmd43cUV*1*ESexq)YEbL5lPyy~#rtk*-vwNE49WLQ$kQ0RgE2Lq~{6@10OYItWNd zkWQ!p0?dg%@B4ednd_TtX8xK$*lq27&Q8|ad*5r_hnpWaOQ74Dsv4>wEG!TR3-|%u zT!Unk^;DD$bo8Xz>}>cQU)$QTc?$~&v2lBOIJnrcX=tjkX+BX=WAlC>!o$br=Jn#0 zgQp*x9GjF7;msUK8H9t4jrj#$xWF&oEj&D2Ts%TB82=VAAu%x#ArTP?DaCCPQgTuv zqT4jL$tkI*si}#{Xz6IE=qRYDsW5|J;Q)Pb@d)tn2&hPiNT~i_zi!$=e^}W;tv7nWA!_CRmVl6kmX4m`9w!$!&wVlR2NIG} z(#rp+sH&-JXzCjn8W}%*W@2q)`_j(d!O_Fh%iG7-&p-5CSa?KaRCH4Ehm_Q`kLeko zVEF}wMa3nhU#qHXYU}D78aunXdwLOl{R3m;6O&WZKW1i^S60`4t#AC^+(I569iN<@ zq0TQb^TGn*{GAr?_wU61PxB%N=7o)mi-QZs%nJ+K2YBO<B#-~uy1;22kyesnN z7S+SVyvhy&c2T_pYAg3qLK+US<$FlX)c(xu|JlUe{(qX;e^2Z`^O^+_<6r?_9u7H3 z0d%Dcqq5OWR3wUiq?@Q}59*;S7_Q+|0nx#jMlofCm{shNDyB?j^D=e>D_U4pg`Nsj zpWg!-O;p6^hTV;g1_`Tj57Fo1P}S!T*8q)H(V{?47}ZNmlUBTg2=}lU$SRF0ovI-h zw}%cU_A-Q6H(G>y2s7&6LA5d-jbM*irHQ2j-D7n#L@_ty2Gk;fYxK~=fc`+O2sh^b zhB$%S1o|atg3LxWw9cPksX6i}+y|NP@YsVsB}IeGj#QX8F%{hTxp*+K57i*u3?6PQ zZTe41AvDoC1F0dzBii@)K~%aLibN{+SW`g!%$qy`BUq{qJoZ>Tz#q^Mm98Ql{ikRU zcRuVe7w=O%cP=P{`%?&^45p8UmI{a}y@RW|C@wqH2RT; zDmRv!Di82!{r@PL1(~s$JYqGGf@Ofr82&56Y9g#L#597vx)96o*nT~P7A*ErzS<*0 zDi;So4L=!3@jCK5PGEmBC;!R8SdOzshd=^k<(zWA*W>L$9R(dH`Rk#;*uYf+M*kg? z)dVvrF{_DLz?g>`FerE`jpaC9ta$|c`Ni1M1yCsls+X_+h`9i!@$V%OEp%tFjK{#J zCou3-{J%r|9gLRc`1yZ#18x;Fz}bJ@7^Y)Ba67=~F1Lx9De&gb#mSHYzF{CMssdsf z9isBd#mNGuBr~cAmajP-7ux~Dg%#gSk%Wm{*)z0|V^^6(tYG#>_k=k!ey%~$%lI((-NPPnA zdx&Wiu-)~v3}vPNd_I7sGL3$>hqZv1#*Q>F?eT&3pF&6j?biYA-4N)HvmHdi+QN|b7T4CW26Boz?y-t#|N+`lSc`fBHUOW8X0B@nm`_~VG%j* zK8)3-Q`z`G!OF4cqoVM|X%MsVH~t=69nr(Drj4{nUX~MYE;CK(nQv#iwdSJx*dO^8 z-15Sr6b61!;rZm#_K=bca|8k!Ib48J4OHkdK23I-CcW#N%q#wxgZVIVn2i_|0ChaS zyERm!KxgjoAo(FP`%%R@ZmOS_v&`b$b1cQ*ydwfN{4OM%y{rFl%H)-_WS=a*OQ!Oh zSr;6v3%eJ-BBF>R^;tW(bGD_RwV=$xvIDkl(%Sg-N2%tK>gnxbD`?XrRqqXN|E!~7 zR>5e!UJZ@%Hu$%TEG_|30iLZJ5WMfuGK`hn7NvEmr^FfM<`!7k?;xJCe#blhm(RCL z-#%T&-bDr0c7@2$6W5qF2Ug~1zA-vY2dzKOseSN2iYVLw|}AMyT!#H)l9!4O!bTN zE&Xi@!rKIh>3X;wVM~^w%nu||&yaJ=WMj+{FW4SV1aTSvByBzTqTFhASDJq%(c{(g zL<;kt)>!$mc0c1w+x_F6j)uE)WHOf#y}M4`P_nyKp=N37TG>VeTg=EoBAqlZ#5|v_ z&xJF1s`V#I2dSWjYFH{$xNUz#K;9m`&R<|c(D@emKH#nYAsH^iPLc7VXW`W^6nxtw zx|~tT=ZeWjUBmx_gKwyceR-#7YCa{$M+h8}F zCOc;1ueSyW0eP`>mJbb7AZVBXuoD5gHAD})n|wEfR!k4G@!DUW2qN<24~BrMwEK4V!ipYuXM6b;=I+wAWk*z>!SUNX+K+6}Eu>1?%i%Iy8@ zcu&A3a=b@sJvSic8imLXFzckR*LS!!Xrv0Y zahe`+N!dAFvNRm=MT^5fys|_h?Q}%=%(#Tv8xEmx8}Z2@MOiu@B)2yjB`>we_dSbb z{MP6_FE&?s6prBgnLJli;9DQTr&S$9jXKX+XH6qu99#*0v)Xnr8iadL(elaHVpdSX zL?oA0AqCf+);&?SJme|8=`D}99u}2I-WBJzux5c>_>gs8)I{k5qWEFY)A$eyHv}^o z9rX%pHQA2tvQC1Fm+9{sOERbE%onLcqqSc+_Jr5M`=!`J6DNGmH`*1x1V(h-fap5{ zRuw39R(NvLzE#yE;lHKgO+DfqlmHR0hRCcp@;rGG4%g2pck!EN-`7@NQ42>)9l*5f z+Zt*!F7>ODZsmDC&HvbB{ap68gh;$}lAP1pymilPOQ?3BQy~$T0$-v~;*@~MExB7# zC-kSE1sN7MPfhAVQ*S^kV#dZ9#CpDI2DLTs2GWf7Ie$#i?nEN&nXmO@R~qL9duE-# z`6!UAR@OJPjMebU;5MWmo(X-=e3uWBWO}n(TNQLX)x@CUuBH-@B@xy9w5y}%m&OwE zag(hNUdsfZvS|A!uh=(NOPQ|~TH?c7$WEW3ju#2UO#@$^1W2RInAYf8_<7nHhv zK%^hR>j=Y>`@F6z!Ch^5zK_ji%%^L3*h1TlyPniny;1JlzyB`&fkj9BLW|#;7rg}o z%5+(W;EMlHz3im z!Fire&#j_C!R=pTh)tH1(ix`=ua;}57xk}{PJ%l*VB+|qJY26bGvhAH%Kh#@{bgwU zUMnN&?J`ug)tWP%BTSgMMH9Q_qq`iUC2*+6|A(xB+lLgDHp7{m2QpwjYCG+%I-N$! zXp9Z;)*p4R#Pj&VqCtbFV(*P38As0x<&F7V@o%wsdmEe-|_@t^5 zmcmLnj;W7ydfHYcgJO;_6hd(Gj=|5)gY9{~eWI=l%UuW%^5jLOw?L6LG zJ)MZ{32FN`^`Ac4w zlN)1W%1;foG19IE;|lW4Ki+Fz{jrZyeu@;MrOBbGZow0y;^CiDr*>iWwz)?pLzSHy zz*^u(+j#?udJsh1CNwMl>({StzCkCK^tU`rS)uWu?~fmgZjTsBp@Wg^nmNC!%L2IB z8az%vRw!%pEhYErV}Uk8$X3m^XU5K^_5-zl?Q&h#eVtSOiS|S4jVpa=K(eG@Ypf4U zRheHE4g46$%`P<#QQC%XTY&A5?t+nxWYLAl&pONd*gK}epU;=y9f`*FzGJhl$0oC= zFJ~kR3#LH_tZF$+=p3AcA-ek3wBW}vqFf(;sV-SO#7F<~$Vu64Wx9IHhkoJY+eRg* zP+h%U8`k#4^D;ekft-Bces(*Tes*Y^$!u2XWNOsh!42r`3vtyCUjEk#2V}9Ht`Q3a zQ>{E(*IYNCci+d&4yGgd(*F5UTNRZTKpnSo2Y=_7oOq2mZP@=puv1>-;LQ}@i4(un zLp2{)8^N_mmxiaRSVmjz+|S9TsZXe&Us*ff9dw)AgT5>GMDdTNPWckiJAb?ZF^Ezg z*=1!NO*K8A#?$xKgvEhjb*q@1wNYi zZ5X<+owv-wUpdiw-?wdL@=Lf=_>@?QP56wIcPc^N58>?;NTAdA8<0(A%pwuQXuNv6 z%#S~7Azzyq<^Y27Pn7JxRh7Fc+YM%P45C2c8;z@eiQm?pC^&*!__-sy8{`6PHgJ$q zLw>ce%O}2%d{cW@#yh;HX_2irpjyrL{`cwwUo7{|&cs&@vU%OVTO97dr#4!Y44uDc z$<6pUcvi-&Xx|SEP@B-3Iw|)WCNb~7oh+F)U@UKnjlYMz%9hYHY;vi8>W(S`_b5cr zNNBrrP4ay(S@ch*3fxEC-ax`Ly;#G2>MS^GkkIf|;}LOR+3n(&ANgXFZL<}DdF`@! z^leA?pjb=h(fFv-+Q!&&nurRk(aJlAACfO?*%B;7e>*|(OrFYWu8)a~UdJvns?zO< zKJoeBWsV*_+v9Ol7gDwF37k2=UWwJSihY6=ZKh`h;67c9egA=+!m0pn0PtuJ-G36y zQUEmmkpbjmb^mKw_+M6s9*_VAq5UV3f>C|^1faT)09G)O%I|>ThtR~^cjN=0C_@SZ zDsYyAnUsp=QBc#CNik++lSxm6cPjIP?^;oY$~Jqq^4~yR0*qr-mWJbks|BO^mqs9z zB`BS)ht6eQWu}b2wM=gh>4ly?znZ{>T1;MK-Nsg@<0?5RSZ`){rdPOsKkgdbq%Zzq z5{BDG+1*MR)YpoQdQtdBAS;J$iYxNodR}qG4M?i7mi@A{;X9baKjTD>z5SYb1UpVb zY5bM&$ef89{S{4Z0}Q|A-*`>g6l0fuht1gwnOvu#S!TWWCA$har=K)n|={^OV zZHu-`K8Z*#IDtm+3ehbl_C%**DpvcfJ?FKHr7Fn023I+R_1?BLqj&%`?|wxNvlVlO z!?R%1tm$2;dwWsK%wV1ImzQ|WG-cGiP~2Er7m%LZ!(DlFf(g=G=1D8Es7piHtjURm z^*x)+vlvCcxcconyx=AFDJW9EXBHkM>sA`GFHbK&)$wZPR+3OYw|Q$W7NSP^V6of# znjV>dY7$nLiMLI}TO3LEWX;)%U;}sKsDf~Rw!fvq|EaIE*rz%t%OeFP1v}QLO0+)8 zFyHazi+fj%L|P-Fi6S7z;$d0V-WG)n^bP0=+H89RA{1QhUSOV3JGF=^Z-{J8q9jYd z0rAaMU~wg&r~|J_71b>MF-`#*r$59k1N!=UbU zK=1$U_qPcE=NKscS7JRjLwmv{7Y{Iqd5uQQFn|0!z-aTT_E>(WFrc{s11Vu%oLhe` z4Y+}1Emw=$<7ig|qaoreWozBD51T1VW9gS&)2Y5lFKd;J~%XB{vn|v)~kmYU+-Zl_h zjLacGjS7v{43nu8I;BMnn5${Wd@iWJr^a@Cf^PIRWR^~bH2Oo;BE0O!VlrA|oTmrT z@yaF{I&=`uG4U$zBu9Ulz>MX+d%Qfe9*j`;`i*!GOTX*yi&LG}bI4XLWlSJ42Z*kZi|TLP+{ztkB9rIRy~RdL&eN5am|ULAEKMt1N}+Zj zq^L!oWx2=RH6t|}1lawz4WIR2&DpVeWKo8G=PeQ}J@CyhJkCkzKbG_$)J43otTO2` zTyKQ>XN`F5YBZ*K1umbXJXEzg?dKJVlGVgq@_}@S9-|I^xj39@fI7UyC=}o-#BvWT zUQY(pfmY0B4DbhHA7Q!yULzrkbBK=))grHL=WM zj1D8AWnh54~B|Bkp*sMquSm;VSJJuU?eUrbxcL8*@| zoYtXp$q!S5u{Wi^u|X?;YB;m8B&lk$UhauoUOHHK%kz(VL{CY>#s=3~8jB?C2UUGp zcPS560&x%`D5!>)vtT#TdeFwYDukr{VoyPW*@snAXJ&B8aG_=;CYXHw1_aymHfC|6 zAhosqT^jh2c)B=fsLcV{*2Or)+wHw_+B@Z`juSpV(>Gk%u{v=vm4;AY{sDP#;Pjh; z@3pC!IX-EnbkX};#2Oa)b%#TcjCXn$-K{JOfh_`oKD8ymrAh&pmV<5O3D7qC{o6#Y zF=Gpx(?j=Qx4QL}1<)eJUew|j_W9A+x$08Xd^8Q;yXV%j#CEyp0OKa#GLy82C}Ei6MPN_)+Jm~JudkKxuspoYEYf(IBFHx>qM8UUJ-U0tw(h5 z8*jx(VKk@VViZ~)pcc-#|5ra)vq7AHyaj-6{>iXr3;fkGv6pFLpmdnnA6*-wKmGKl z2#kJsR|A6zXUq`bXOUWn(VJ5>*W>@i>7gn1CK#>H=*F(tk5%SAQ=s zB;Wv4nQ+69x!6f*fNPnQhsR9?bdR6z4Dg+C@2jmU;xPs2s(@HisDi|vV3`efL-A)& zfa{Q>guuv%G(R9**Zcu@&!bO8w6sv_s|{r42G!xbfG8 zlcZMH?>!}zBY=l~xc``1|M&Fr+{h*Baoqh6966iwXD+jC`fJ0H{wH&Dn~6=Le!B0l z($lG8y*W-1OdASmaEL;(J}T}&t-F;LEOF{q@T*zr-2TnaJ`h+o9$bRmJlCE>(u!=0 zh}nzVf8OSF6nJy1|;nG`4bKp}~RZZ!}HdLsE<=lrDN zm7Ij`;?B0W&&pQs2LodSOluwDwrojY?mMhB(aa;}9@yF^H<_FmFM5RdF8m`lV0!Wf z^kuqt)5SCIV6gjZwf{ouXR)&s#iJ$tGklrc&8;?NEs02o!iy#6;GS0S=*EP=oHX@r1Ny=atMdq87mw*6^^QRJb!6uzrV8XXI9g8Y zc~)m&Yn1e@L^C#xzqWPr29$Wwq~g1{(|@UEzgVsCmg4$nd1{M2u1RXf#zxeI3rq2j zK7|Nfi~i^<>}>VP=q%=O1*tMk&zGA+&vMblFeHpR@BN3C-#yH~v3Trzs6e`yGcT1c z;GzAL&>IZ`G)J-LIwSyn#?D@Mtz$RT3I+y}gvsq>u6-ly?!xJ7B~ zc&kUty`LUdxYa7`v~U|0MVjt?MmuUb&tJZ#C+z)ww<#j9Jt^?Qc)^n9_@lT2_Et~; zT@u~5a9gvF2;ln;x!OmOKspY#m+&%CwR0woQ+)dtQjn|K;fTZt<@j4`HrL|FhHw_Q zo)Z0S_&L-mb)`g>1NO|h2yQ)fcU)F@XOMR!a3(KBN-(^2quWH>A){dm^#N*-0E8eh) zQZb>-h@i>t8m?Q<8mI2am`VkeYsbhEJCqP{R`T>e*P?p zmv1bbOHX|7q?nh%CQ9+(M! zFefKk!kVz5OuPY2!*#EckHf!?c_mP}D&ao)@&kpV;F}e%MiiedZMdBhcHSw~fW{;4+`G8zTo&y|;9 z$Wpt5l7ro!7oQ5}PutJUNKM)45UUn4%Qv9-Ala)_`8zYHU@dzAh=lm>G~KHDhgLs+ zin3d~zZY_s?8CvYXGoI;R$f`XI7KIA6H+Mp%&1$UMGR|2`KfK&$lDj*6bq9qQJEKA;v&#bj-AY)rLxX=q#N%T`F|U~ z``^U&0A2pS1pLVVYW;&TtGGf;JOmS`BDL=k6w3m_D|A3CL=5zNG*nH@LlF#|pQV6^ z6A*&}!Y_X_`0+qUCWM#)IE%;IV-sD{)$lTA%Dg+`-($DWe;9Q5rGqsQKFqJTzP(h} z%M5i$T^5@Qdj{*J%X*F+0qfTX$OT1vSTG~2mU5C;+Gu|G#_uu?2uHfCnqjeXU3?Af zyQlND+&8^~!LWp;S4If0t~kZbJdN0l5VP?vS+`ztJZxdN$N=>a+Om;=W|R zejXjSymRtqYgii|eHp(UsJx_ZcTRU%5(dG$B^xdZWtI>W78+*>K8lB|((!6v6yjH|70 z%IU=RsW-_Ne!5^)PzYw@yA$a5ZAr7Ne?9$BIwR;k%eyn$SYS!!BN&`%l)8CcM7w-B zfl@eluwhwKeFRbaJbbE7`0LvXKi3b3fU8VLHz&Ly1!evjZG3Q+#+l|P`%)pz@Q_M9 zR_&oeBykq`cE$zkO3lVw2>DVR#g;kmrRKbBfA!^)wSRgdU)s6&{&uq<{|q?eBx0Af zwv}1Ja(`&8k=@Ic*4ql+_I^7-=^9!@}Q>FpheTI%6aR0Eot#sG9he% z8wuX=SheS;SulkYYlXGd(i5dhk``SKxJ_4(d06Jl6C+zAR<9`JOuH_!7|KJF-Uj&m zlpxK$U^rJ;NvRDhLDP@y*A!|LHpSj)Qt#Yd+7)I?@IbR9f!bT z&w(iMPJnQ*hbqbcG#sl~1`Or|j3W&b2L?=J1Be5II$&U`W*};;h))6pa+!cg zJ|+c%mZ4fhTtKu@m8|^FDA7Fj00V(FPQZQ`2nfYdH2|T=kDpS3vzdpA0MLXG(_07d zhprYtKp=?b@le|UlA_NJ+ocY5G~ciUid+IDtj{NZj%pO#dnq>Sqqd>YOSEhHbXuIK z$Vfs+edH@CGyPL|DwPjikH11^9G&mWWyWcWd-1>fhKQsn zM80&nvM!IcQqXDW^*pASR)bd{7AATh7LroNr#cRf2a=`B6Po?lG&ZSL0+9e1kGpDYWLJF^kdV#704%VsnM)+_?eQS0Y#t5XNuC0Lp-$n<~nrhZ_8 z4NBND-+%@ubHYrrzUmjkd3M??|M66)9u7Z=3?lpCAT6FX`%W6-$dxKrO0D}~kGCIP zf3e=G($G9n10~qZVAw3NC4rsC8)Wrul(@`P#B{P&Lt~q{WERE0CE!hbdY0EJZ=WWK z6SUgIwZ*%cK$3ukYEz3q=sIj#y{eOk*--MVud-QhDbbw{d41QS1tE+%%Q@oG*?q2rl6 z^*EXzFD2}AoGW`jROq(46nhve)S^ahMWXu#MCH5Mi!`6L&~Os3{x(8&^&^`4m*#3w zut&z0STHe4>ohlK;Yc^-nBPOEWAbji5Pos=W1IGlpSPrBPd1-vt2PIw+;g2S>YF7r zxVKwLx*aIESG#|-8x$e2JheoP>rpqop?^9=s>toUp!^!EM@2*-C@ z1(mS;!)plp#I<@Rd-d4|@*{TY7ooqE;6pc{7$~hLoXKL&-hwvdsY5NnFD2f@aC)5A zx>>KmU^zLbksHv9MM`tD7!q$cwbGA2EzIlX99a%oBJ+%kyme=2-^G_9=hPJo(z;5Q zgXBx-In#L|(e?-VFDa!e&hx?932iC>35WVjZKKmF+6<`z0*-zH7{tPjcJKhuJa@sT z5K1a5j8*9-_+t=Hfjeiy$Kn}CojThUsK0RUuZtI+RRgR!0!#zI|^ zrlurn(+Ej0+fsasFH^=9)(`{+4;q%XiwKf6M-}qm)kJ=9%>Oo{Zp@euVhMF`IHf;@ z=M23*$_&#CShPHnPvGg+kC2mYdNzlKH_Z69JvnfV@Y+tG+*98v4PEG=dF9|cMT5zgO2?oQZNwkFjKS;+{uVZdA zMnUYrOAmgA}jZWx4YhU9EA|0 z;_o(P95QN2QgCZQ62Sr-Y^*NzpW!og9X`?taml?VvB^*EGag=5uD|Tu2b~?u=Y*W~ zc>8>r=8O zjb1%Nr|%gKPX`pvo$Dky>>R)jlDKwR)88#=Zb0^d);)~{*@Xq&}hwxDe3$X^!-}q3#x`D#mCyi`CiXK zm%4=NIk7>S+1m%K&I~%jaG4etf7x5 zf1>JE(_&=F4oo{|vv&?2w3POZ^L=eE8mM~$M3-G$8ji&~eOKFa=&wquji+SqjyME~ zgp1zWOPaGbh0VWTBi?8@Sx-?R;39Ng@LmjXwcYs1qv@zwZo5}_V(MWr9hl~Vs1E9f zR{xVDGHR+aSr8BtC_Vqkzonz=6%*cvocfOQtA-PJ5r0K)OI>_`pPnzrlYYKe^iNsd zkxv-6TkxWSS6RbuK(~%r@lkeNXU1t~Q5>^1>rlo=^kGo>*1|>g{0W8$7cll5h%^fT%bXB*`$;Yyz$#l$#*QTfq(&3` z9}$nf!C>BfjW?=zAOX4G2%w{zB2j|B@ZTD4L<=V#9l)JDgL7ZydvR9_M)*kN)ml8> zw5A)r=<&uIM;f|ziEsTh9%!qzjDeY(Dves#+dUZ7@Z)dR?(;s^jXVK8ko$Nso&9lm zX89#LL5II!*X>C{_VsGYRcVFTwjjaGHea;3)5la1WP^>(-22=dA^Ld94bIkk2M;0w zR?WTb%Ri;As3yNt;j27~eGdj9PgYCB&%6*_YpDGLtw*6xCN{?9dyVuVNT#5j+bA$& znghF>WQAHsj@SWLdqKlkGx$@%$*A>)lf)i_X|AGFA7~fM1OhV=XPnK??l%`E;qkCB$ZmuF^JcfhT zpwRaX;GA6JB-CnGT1HxrgRJaGVOsEM7~_Lvro4~NHtkE~eF(=fef=W3ag=x9_eJqGi5wT`aUM{KpZ1sn9FQ+W>`(g$**y7)Q^|FuH z={iUm;FR@(KP>$mDroJfdaIw_*y?rg#bn+kuW$IZE9;<-%!hcimX{y@Ad}i{y>I!R zr~RvvEA@-4j;#`?GbGDybpYewHe1kghW%-eFJ&?kX6API;nDyjl4f#O{v!5=qh{el!I{JQm3g?Kob>fPt(?>%C% zUrTOqW&D;W-)1-|>KvxnR-lCcYCU*a<~UVaCxNf=D-#ztlp{r!C6^Ry*BsG9hJ`YI zcrg7A;)-O^sM&q_eaLevR43hpC@n6%wz;TKMA>;usWgZKc@};x2oXG(N^mPMeP+2Z z58auUCTJaEP-+__Wd*y)zxY8B@#D#IKfn3sl(c@=YjY(-L!Nw?=i1)2^XBx%s9%oK zrQ8pQ==3#DPmzN(S)`GJk&1@v-jpv+h`L>rweFkvwKtpQdvGM#D!8kSqBW*q4wXT7 zx88m!RWdJQ)-@CKDdu&Uj&85t`q!G_utmzk)a?!n@=?~VMhdfPol_2;(=eku7EY-h z$&y^fOj%fuCYu9nFGV&fHvKIc1f!Z?ysxVoW^YMJ2jg>(BsLs%xZZ%Cd>l@3@>;JB zigCID89(@7t!H9lY)Le|epYv4y(kdu1Upz%uK9`#8>+}#30Z8b`l5KKs?fwaMos5~ zqo8@bPjo#dPd(+?!mw|Ud5L#ou=pxX`+b)r(-Qd!JIl#=zuTpz@Ak9zgDz7qpV{*;3L_sbUDK4!{`L>94K!YYcY-S>1?dLbHO)bVVeq+nPlIVh|DD5AMKT1X!AQ@ z85_9lJk@^NCO4#MfLqAjB;q*Pe3UEaSWR*Tr>_0sE zu1YZL?$*ZzX4zvDDKfDb2-;~QOP05$Oqqm{IqNJ$1eHy)^rL`fS2DjH4je-NFnlqL zJ2$mejc6fmtY8LVRXi@bKdbaveme|1geIXkId&9Sz%fhnzbi37BTh~*F(U*$A{64r zkOiWJFjOIsBn%tF7Wl7Zh^l@)nF<6f{{m6~^PP?gaE=0`zdt@xI;!Uw7byKT+hm&3 zsH+zabM!T21(X9NV!Buq>G>n#1P49LO$rl(^UU8?!Yu|LD!|-nhqQS zzT0BFYK$;-1);>Yrk)V(o@qOi`Wf+N4(RwDM??{QAC@BjFGG zyPZx%{PLuCqP&-lnTPc}5=L;App_++e$7j`}Gg-yAPJJz;Vd0p6uQxE}AWeJz%Ar&8yunMs)L`Wab{4C^{C zLf6CMusOB0tYly6K1H*6?oJD<@0B9DIJ`CSxFYHHyS|^hYj0KjVb}c`s0YzgBUeyv8=F@jaCx|x zAB(6hIgQll%vg|kbhR>9O`R~Bs*XcWNV2;&oComT7Tsj0AKfw1p3OwZJEj!#S`^%X zD0>yGBV~2UeRHM`%o}fErEaNNf9aLpN0=qIpTG@KZ&noEm8{6@YHlmlPkCYgS`_sY zDq(u=d~G;U*LBGnZb{gz#u|P?6tLd#URiF%d4TI7jJ|*42E=j-k9R3&u_QOwC~Hpq zLG9bS-f=`ml=u_d@3g`{+F&eytm&+#N~52wxRc68^6e?M)LnSQHObZ@!!`d_j_B0D zQ8BL^`Vd6UN2UOOV^gH^>5C>*(@NO1n7OOQgqUjFKm1Is2Hus$orR;L zhKfuc2yxl3S%H1?K@YAV7lBjaUOeL|MKW@WPA8@gXGN|O9zDmd@z)YayKYJGxxtwV z+v<7>B_@}Dp2RQf?-e5k$D#hfXPN-5`gH^9hEh3X?8O!6@cFMPI40pHIE24An~Z8_ zI!cZ`G8qZ(tUwVI^hNOn2~ENDs7=IaqOV)zUDT}nz1N#=K;eL2;AA*9hz!}R?Z;el zN$q_kB zfb;ArbzObbMVO7Gb=K>$AD$-%Z4?f(p-ygnG3(u30>UBcl89B!10)Be z+0n6ngwu&X7^HBwGMsw(fqD4ITTX`O$}eJ zzmHe2I?p=2`ZD{I?6i3WYgkSSZi4C)6U5zo5X3Q>XD;uojV0kP0}hv>3jdk^0Lw`C zZT+T&U@4jlY1}h^f5V{Cr=_7X`d)pt27MuU=`L|@)|b^RAGkh>{QzOwbii4@3}t-! za~9>)=lt;dq2fR9A4NEUT3)M3vZI0-O5IKq&kUQqjYP}uJvJLp8uyx9Yzx{}-eR3; zI!&$vn3F^NvKl_lEMH&JXnQe|Bx@wRufGAMKE8UhR0qn6y~61UdWx2HB|#bYT;KVp zJ|~!T$W~16*`o);Y;?~3@kNB{Yvi-7Q&(w0QVxq0V(j@O_FL1bT9GdsJIyt2BL+pz zy!sdsB-0g6+h6GRU!_R3=tO@z+3esM_`u`R^`S}WgLX;I{+X7xG{mJY5r#l@NB?;hz?v*0N)J5$?5o)u!DK-1@kBc z;0Ogez#5DL{ES3vALjEMORhjeRY^dQf^vxB!LR8U!B(p6`>EaR2yCNnz|b zZ%G3^wk_p-rlHW9Jb~u`Cajt*{S@h@|pp$vKU$A z1z;8wtb->16h^5ptyAT7PHu zVUbaX_bLbVcKpKRaZadf={3NC#Hum3)W7=P=69DW!7rFgl8`ahhNSyscgRn$cX5u( zAZ|6Gi|kZR{Jnb8YzRl%GvR4J>#3h zUrs(-GG2dgye{ytU+$KsbO8jvK|afjh~Y?>D@pwVR%p4 z*~ytTfMubLT2|sx_S}Nu>!m=+3WdUogD7z^{i}b#wU2e`>JbiJ$jpvwhJ!~7(ypXG zOy@NLXJfKs*t1na<^#|gRyB)s&dHHl_u{*Z#pqVCZK2<_H=x<5Vl%apn7F0_1Gkh% zOU_tkHUVUsC6`tMvIH=cV8-ob;6&CFH=6H2Ps2e8#N}(jJFS!1`Ve*(nfWAGq^N) zQJKgZclVB&(L5)e>f=2kgSW=E3GX=6LbewA*bo{AB73@c+-K>-X6 zJON3Xht5G{=r-)TODXCS_GQ<+MZ-whqn;ZONljTWjpGF$vhq-nUbu=+U2^HdZNzx2 z4X;^>wxjLVJgTmnad$;MXO>asW295W3+RW$v)5z_7W3Y+!Iy>(((*O0#j*iB=_3Po zf#GXBTyhs8W3z@AxI<~s+9i-zD0-TTWZaxCU3-DMb#!_aAuwy^*8L5$XoEb?WqCVh zqg0E!ZRhU|(kFRzlSKmsHYZKTby_VX)Tq$|M0c`TAgtrPjHZ@rty{}iWy<%o;MZF+ zL5AayCzC-;C^EItLkr)@}_u2cB) z=XK90q~57_`G?=j?*C4T5o@i&boH_d&8U^oR;atV!%(TG+y;pd{$q3PMm-c z|7BUd*b__(5l2Cbw!9fWLc6Bly!;aKermka0Ia6lMSQWg6l@JPzq5aZRlvw%y~Lp)4H;? z{Cm`~KytsJuH~Za24o~z=8B`xt7RHYg%bHL-u`{TyEWyuMVjN* zcxTRm@pY5GGg}JIOuBVC)5#w?KbP)Kup1L&B6|)b19sPdMe8Azw&gE6{@OLQjd68 zLT^9^k6dHFnm^rIz?qXCdjQz_v!(qPi4@qUU>QOVn0*Sf(_zBeSKR0lckaGiTy!zI zxUb-ErUVl;5Iu$+0@S~4s>))h=v-1-wlWfBgA;6gQ!+W9nfO&a*}vMJeQ){MA(0r+t6{(Uxeb6F)CQ-G?N* zZT-Prfr$6ptX1n(C1~M;2YH{Aspkt}uD=|0tRGm%)&26RlmwA9aJ?DwM|766K15NM z%*ow=;&NM?h{C^)?{*_AXxH@x6v6OE@p9V)uG2ugsq&}rZ|A$p&H=T1L}tBoBIvdV zoCN=Kh*Od&Dq~jSX!iC;Yp1q~E z&XPx{3$LobSBmZIyNvPFwSd+l<@GlP+iLQZc?Q+Kjc?AmS+|vz?C4I#4^m;5!YEje zf49VlNplQw-Xu8@<=b1=hFk7M;=CrCqJ8fQ=p;QXhRW=NBGGpn)4DA2#hJBC-_CUl zD-kN=m$M0SH=UNE zx=PTZNWn13y`_&_(splO&?SN9Oq9cXhzscE+; z?ZP4tdym#->ZjO2>2gl%`?od^e)_6uqgtn4|8C`;^n8}O@*^%mwjEC`){}66Do1A8 z?UL8&z3&aEU3&4Yc-hBy#yf{9UU&Mna$I(!6D?AS|(ewvxo<2FP!iuiofa*%vzh>eikqP%5JWOMdS+V zxzB*WFJJas36QC3M)0CbwnK-5a*yFL$K8|VUMJxLoNu{pyJ1-@P@fz%@DaSy3r=AH zkwlTeWF<)OPL8f}n^jVpTbr3kgO<>~1)6oWv3XHv9}M@aOv>e7K8;nFETUfyoaS7d)5v^=v^71GPOI)YYT|Qyjnx;6B{tzLL z>DOBU7&A&JYo>{jjWchn_nc1R^cMoi;xRTG_u8U9s)0a`5q6#v+*< zY8Hqe?I+6^X5^92MHfl+>Nrk$!svKR7kn(j9jiAU!1u~ze5SAIdVsH{T(mReG;<}6 z)}rPa`_%E^CVx?~O~=DQs^5sBed@K@faG}e_2-RE%SaaD>L%o5LU)u{lLlMe^>a`Ui8J{(}vPC(N80~VGBlpdO4gVD9K^H+VXB#_aSM?!lIpNvp*eNrqz=nQpxfu~C zdXKgINmo%DmvD2R+GeN7wneZtv>D3eh*>>(ROss-=(G0vkyyMsI%t~}`I)~5UYiCm zAK(24NwdK(=w<53X5Cm>_(Q{L9@CeDqm^t4$A*bX@ zT4vYyI~lqTw~>9hdFhR!G_ju%OoOKO(Liup*{=d=uBD!>Q~NrBI|}JL`%E`eK1+t) zUUusC_kNy4;EU3RQaJ{bj88dcidRIAa))TgDlt4{kp$xw^A*Xiy&iUa*8= z%Ply3jFrUyTAP;4q{i^TJBo68eVs~ZvEP2On9%@dTe0B7jji$7Na)4lgK6bEmjoV~ z>9ADFdOkx1cNcAjgWX^M zXhBMC8V?t0=sS3x#zxCIzTldHZA(KZT-$@hcd9xy16B4c+;h1P$`2o5${0$lY^M{E z#JmjB8#)axLH)sH++!WkcWyp~T6Pjf{49Hu?c<(L36^By($5)AqAV|1YGZTY?1Vl; zS~W>pOutc90UL7b_D0JWj!(N=7G@)h=g&BiFK~`9)147?AoC;p_`cmf6@SmrYYu-P zp0R7bEMwvepTh&Vi?ft>`2sXDyx1c$S#~5chuUmx<9@HQiN=d@==ySQeX|IZ-XJ)U zMJKl+!h)`0*kJDY>-P-m{Nt^{Xvsszcsz(Er8;F7ssrC=6ydr4PLR@{<7r8#;)7^*MX`|CneU$L z6Wg6L?88Mv`qk#%4^kDIY=*7(UJxw0aB|Ffo$-quHuNv|2VLiRx3Q73fm3p3otOJY zx67tf^NI&fsvpdj_}h{kYIhTJt(Ch0b34g|EX|wc&?II*I-ZWlso+w}qaS>MiW^Qn z(T-ogFFJQ^HU#JT_4#<;Wg8GQsJ9Au}8R6*o%VtTRLAP4S8l zYHLDNNIl{8*!YJ2Kpce#9Zj5z=tupEUsJmnZP7{-7^S~{CF*C#;)$R;E2|gq zcU6c^Qo5#CUK%!}6UY5X^!_UskE+bvU8iOo5k~N|If(mpxoO1HQd>$&{}8J5tC?V( z5nh6p9&&h5%%m|k0yfGx5846)qbSjFv~XF&=16znFXpqb-V8 zS&jL1JC`&4$Y7}9-l^#H+BNp8w>QhvA_TJiM+lmsa&n7tQ*@+_N!ToO0RUkMh0U;! zG8=^49eQGvtgG4boum0uAGP~fu{#KE`~zuq4Q;$WC@#-9`*_4o$oXa|?I&b)XcxkL zEWfGPCC8z#dwSsWx#{I~X@i%rrmqg32aVw$0s^rpv@AQ@T9t|F>+*(|>phpvEgbm< zFODo4_tDanXH2ox5Z0kF^9!x)6n7eAhP28X2R85gDt}wf!IS(v?*7IrFAlLTxOAsH ziQ5UXl@*GvY(lJA@HB`aQn`kTu3pjfyy5v#J@!@5rmB2Pk!48b49#dGTYym`#x~(= z@UvgVc_Y=L%eFNh!Y{s)5J6=~Q7lvndKS?cs_N6fGG9DQH2&qGs*}=einIO$2@MVm zg#UI^w)teXCSu8;>td&BJl=^MA_L}agQvxK^Ey^}?)U!D6^Hda(66JlzRa)l+{8g-u+|2aO0C}f$pg8b(OXJ)ruNMS5>_?r5!njQ0c<59(u9{l)V^1U zR+rEg0I!Y!t{t`&sc}MBj#W?VKE#Ey<1$K&eouasJv;85iMAZSUOgZ2)7e*56m^q zohL&%4e3QD$!Sbl>BNv{lxK=`Jg*hRP=&daHWBx`9wg+ZC3^Jr`vo7IxcB;Y);X8> zAlo0YT^@0Mu9aB(Img4FR_o*8-fn!5t~M=THj3dGB%#9Ke#$FKliJX$&2wY#Zyyg?t86+?|HzYpk^({=8Myp)*X|&(sPEb>xqy6Z_ z=a`b;ew1QnKfgFiCXFVTo2!2u|H-EU`AxuGeI#CbU~{WGp85FONH+Y!o~GfV|90pB zigLzDbZTZihTSrWlceA9Iycvo6`Zo}&Ur|o58+a=`1p;Q{w?k?2b`2PS+V<;G+66) z3w{hV6h0cDiY^Q+UM^Mgps_LU6Z!ezfRoGJB1EXg^;-9f-5BW)O*<7+HcEdWjRjm- z%XwC+wKeuDs-Jkm@1#9`?y^n$wl@0voS-84FDXuGY0?_Up+ce3!95dSd4JXqP6jdC zT(b#dy$;jtV)pEn78wf-7FwL`GYo@U0TS#-FAHdT>+Qpr9vsL^FH{!`O_Z>jTGsE( z)W979k3y@^mvI%(NsfT5vahe|G_pQ;#AXepvtJA9GSo0-1C#!O*hT;j&O+Oi?zRl>hO9U7ps z^Jz$}>eTWurWlt8uMKTOE`^+2%Jn=rc?3hokUhl0cGB9|Zhg0w$mTdl)hfD&MaMH_ zJt8}PBsf~0v#l&Jt5soPE*E3XXf8E;baQ61Hc~uk5V_l`CI8UuQ`6QvuFC25m6yUYp6pqL*nx5=ESUWHLA7=K%z|=9 z?PR>MukW!avH z9D-q*D}JV%cGR0dMe-HWfpgk8#Jnm5rzsg)e{G>K3Pn9R{mW!EvcN{>DWhsC5xoVD zW$eyQXW-Me))Vf;rEiA5DaCDwo=7(WE0n++)k^-sT#Q1X6BZp*A%C&2R0J-6KgnUN#pazHGG0J zLiT3zJagHXb(4rFdnboyH>4V*V6PgRLW2t2Nc?=Co4!ccRZUFQP}s1ZZW_XM;Ouh& z`^=Oa;Czz;TYn=${&qnF*g>#T2dReBrh{-kp#_y&fTan<@aaEI#sd+W-8| z#>(I;N`F0=BOZ1jg3=J#Q~_vYi1kFYzaAcF0CN=C#6x*V zF@QTET4uw8M6l5jMV+2!LG}t$Rpc)(4u~>@9heaYmOA}rb83Y?=Qn=d$TaDbsBd4P zb>&c6KxnhmbH z-56CBdd#5G{kl(&jkeN}^od96t}BxTj(^9lJ@Bqt!o%8;;w_4^kF@m5cag7QX^?$X zzTbf}a~m7q4o_RLVF3SEfzb-7kcZ(aPs`G5yv{cCzClH=X1qPrm6k41omXB&qVG2f zHw-%Cp!1JxoH}D$ENpq(oe3Y1@SL`@_>YCiI8IegntPqXvO`rC7iSJl96)!_ER!Lr z@@*uDH9%)%BWLf9lNRq@3xAboF9Xh+urUzpfuR>-!3s)0mg`P)xKv)f^p1?6DK8Lu z%Ck1%3X{7tPiB7S`DTR_t(obqseFYeE^cBOE2+mJXuB43C$w!@!K7ub8=s{nZDb#d z7Q1cp>W|+}j_;4Gc#8oFL5%!``f&8oBV6qFLw+qHEz@t5xj#N~vCN$tTFxbAj76V| zVChCOyIN-reDf-^u0$opit*7wTOT6pCg}?2AG@qHikM6{e9-HBoPqA)R$LJn+PO0x z)GZ;=D1_~xYO*U}j$-9kuYPCR9?B_6i780v$3?eczT}f^TGLGx^bOnaG{C;QYsUJ4 zYBDyIC47^g0;xbTbk5;pae8-nAf{r_+K)y2xwMhNcu247vw>bbI+v0E^TTIoZr(ca zpqD;-XttO+7#-HGC3QC9&TP4S`)-RsL#h4DEj3X^Q^f4uHNQfdF~~^pyV9AU!A8oO zosOlM3>yrER$bDzM(I`7y>XgasII2qsM)R&@d4snqm<8+3@)cb6Bd(^v#5ypoBBO5 zt;uE{M=z-436Lho-go=!Wzi^DlBQ&c7c={n-?fry4uQliIdyMM-xu6eoiP))3eP4s zYFXetvuFbAf76Gnd#Y1t5q4wvX3$`h^U3kASp&<%V64NuE42^bC8GHcsa}Vv!iT!E zJ)eDYIj$6<7#M$`^g5l=v3aKkRjsJ2-ROvVF$cT6iJyyU>dE{!-nfA-WR{E469K`# zZ@dm@w4gCK=6PwH`KO{!{>9K`|8+vKU9D^8@U3mjWQb?4-%8AW7S=KAtxRxid7+OL z=5rXK<#^G(fN1I;<0wv71l;e*Tza~%75rFYY^Y<|!uE>=09b`f4E|e%TuvN7CTy0BEW-4>4 zjj2yE$t=8{%FI!>SYFAK>^v=LO-`jfh^#JNRq7gC!$tE+AyZ|3`5v4X1yZA(R1;3` z9!h@-J3L5PP?1x~#udV>Uc(%JgtsN7(nl>g-?OX@(}8LvjV^0SQuA}x!fO34pGqH< zFt_{FIZ7l;l-8M=-IZ(M(rkmcy&&UQkmnbhBh5hn_L^ldUX$rLi5XfoNE^39y^p)d z$+LWp4Xj4yl&tMV7f5wHf1#Jh`%ph&23Z-@b>wYv`|MKyH@e#<-N(CCMs~)Um@LuC z*rBVTF&Ce@Z2{M3su&P#F0rsxnK2(@ycw?a={UZ&%TK4 zW@J(fSW9YSm;R`eS`j~a&VFzi=4hsuprYkRmP-3E55z(c03$130M?Em5Ac@PL<~60 zXz@lFpRD7p?ZsY}0f2s|=w%tSo{5B5fN%*g|JYOSWse~%h6n*#o@ftc2!MPI#M*;6 zy@6glVxHD+G$B<4_}Bol>}j+=0AqSI(F8D)wX+khH?q`ls1}&0Lp*R)sz3ff44sRy zM#=!UBA%OSqg-9V-G7{=vJ;BlsR}s=zPxs?RY7>@xuE!K&hMLXJBHfSU2RAH&D*KV zK^(@|$#a^fD}bfujC7Q=T6xH&WL}5An{mqca`P2o#p8D!t~e8HAa#e9YkMYSd3?GVJCjxPF?k zypaCwF>cgXzBQjPRD5c`J$}N?ottL#a&Vftw#uXQ47Q~(lxHR~JU2XL@-?M6d-rL8 z+5&GigN3jZEB^{2#sn4(+}+AP`Kk@oqQ7M}cFi5)%_xyqKeoU2W{WiCRjociz?+_> zu`;ZlgdT?SPdPm88yp=qXcmEMb_z?QxK76|o@$()H(KI+gi)xo;{*hO6ktr_sT`?YVa`< zpM}weszbig;LTtr3)5d6);aH<8))Ar@*sW8rs6V}Q2OK#x>_6v87x(c_ig?enLJC zW+-O&5rCw1HtV2Z-&?$XIX>FM;&=}YY7>atS0o^gJZ3+P+Zl_v?d8DSG9#cxq3^6E z#1p04b=Num@}Bd1s)r;~MiUP_?;LdUcb`kz-(8l!YUsgd@_34_R=C|}nmMM-PG7UWOob&8akM?k4Oh)a1TZS|lSe@gHVD}V=c7qpbDOTbAhfT@hiv%lr`?HzpRI>DA$d|pj6tIqLC z`XC49C5kAc78TpYJchr|XnaD9SQcEni)lZ8TItV30&z!Goeu5v#>4p)` z0wqF^kv*H@njCI{KX2AqDY&RNY`o}74avAu@dxr_Z3Rog{%%yZK}hc!zidFyMa3qA zkho3LMliiX2Zv|gOd=b$%6i-wvk*BdEXlVyHFx^NKd8cGx!VNmv6K8bvvX-__}RE& z&g}=9eL7X6jW$@ObMCQ51qawmL7vJ`yK93QJ`a;5?~T=PyKgx;_P>2H7?Y;rxuWl~ zu)$C=iN9IbI3slNYc}Sg!z1tGM7poBk&|+hG;V z{Kn4C=&*+o*=1ZvmRDEiuBdmKfHl*&9oiXjj9?X)*jbkGxB53L8XpwKV3+T*zz)?> z^Zet%c2J6Lv<~siq#4VU`WH>k*tR7zs>Ts8kGpc|D5CN9tc5X3Ty(X{X2qAb$o08< z#kDfGaD|lOmGf;9?wZSgAin7dlZb<=|KMk{`TajQ3s`%7ur$?xrW;4;o+t&EPeWD?J?wKt+#Vq{C z_o~UMEi;eP>f?o3@h{4J-%1O6yV7f5D)0t8xr{vjm|UEP@=ZVyqe$u~`?3Di*P6`1 zhL4#M*#H%{n}}(%UYXR?VKnvOv?xo^FK@zd#Pp`b>ONz%ZeyEvx487h(UMMFhhW@n zZH8+I$6oMw4aQRD*z>?hxbcG7W$()`q&ED<5V#jRoy9xLtVR!a#ej#Z!MPjuCv z82~bf*VUPsZ>rDyn@y58FV4{o)|(DH!JGhW*&1Oqz|MvEgAK%=pUNwDSOYZ z%$_rxk{iH;Dqb!nYaTy2Roq{*J=Tqbtvvq&hMmahfE)weEsb%WlJ2D$%fQG zj>CI$7g=!AP7^^lu;y}i@_qPCD!A zb}Nlp7-8tc9oSOnOMYBXe36&v=cc|wR^i3eun#Oyt%DSrAg+DW(4Q;x852q zm#+?#Hb=v(%*DBCQWM7V6PxnCW%yJuR2Rz}&z_hbNl~~mVAI+ToxHrQ4^NAAbVD?U z_J2xUkp)iN!wz5ArZ*-C+Y09#MvUI^B@;zY` zsD+CGbn_ISo@&XgrrLB87JV7mLOsonr+#kR#2@VRu~?wVLBLyez&3KLbH;cfra0F@ zWiSWTGgU^2f%k+c}B=l^2q z>+bXQVa=e8bI#M$htrGduv$y@TU+h1paCP=QDK&4O;LBS#apfj!J-NZ=PP^d?|a0~ zBX9pw=;f(U5qiTCw04x`+~pJMy1?_ zfk$$=e?#xuC45CR55H_1J8TOmxcHL(ZO&7rs=F`MD_*ZpW_JcU71qA7 z-{!FwynnI!e1n6ND_*D3G4oq?NujvWRgq?;L`KUG5*zGK6>){_o>NnaRkPbu2Xuxc z*8(d~D{o@mB(P?bAtI@k!m%o6Q)f;qg)!=$@`A+G_rx}D@k>f`C4^-9r=C!tqa%32 z?Z%b#yoDJ~#`+q$Y#PSwC>V?vIn1W1lKspgH{47Q<#f_QWN98I{qyJd?M80EI@WGz^ z!wem7|IOKx{*y`cqa2%}0Jh+YR;|#XJLO@w!D*K(Pm zxVV4D9X~P8+Y=fcvBXyvrce~KFHLune=55^25>whk_3=DJG<7QEUhCn< zO$3%a=hK!DInDVqRUOPq^oGTe(opeC*ZCia4rKb5X&qq|1p_i=@rNeuRx!tqADlxm zKAq*JqibX5jjAv{QO_mjiM~UH*EC<#dGpW=fJ;>tv$lu(n zTlgk-LS5!*E+fGHpz3>-63b-{wSG@>8FC!UP8O_@^St9+xSy)Ltv#69h0^1f`Rd?B zXV+rm zW?sOlD3LbE=q)|p``VqtSq<8M2SZ87#|HzcCSa(2F+s%v@NIzH|Fr$=GY|u)vIbU@ z0Js(oXrf8x6Qcj}KVyK`4mj#q^g8W<8xOJ|{sh1EiV`5U@cRJT70U}4*YP{}T#LW% zJYino)RW4l@>`y}wKwniOwM((jy?26(5;d5)pe$+_cl{pFW1_3&JCT~Wt>N&6tWL} zMH+2lF3Kvoo;Ui?A)UsIR5hv`0xGI+(<_zFvFt@+IQ90Vem>63y0N6Mnu`-IKa~vG zjF{`@`W{5m2UX-pDu`fTY_|moO6sXV%PL5xY2P)uqh<}T=`ia}i!=1Pa%q40shh;H z8wV%rj@Zd^4I-*m#_^o${r4n^Ayp}&@r6GS+cW;k20_1D0t2B;^%X9Mb|@x2i5CUY za<4N|#-t`udgr7K$T|6EYyK;FN4Egk7Ybnf)&FO}_$akT;)9Bn}**{;Kf|wAFuI zqIg6be#!2&r4-H`OLwh3E5gsB?8|KN=j7bGRHJ&Qowm2BbXWq~b`kJu#2xH*t|r1q zX~Qac19g3-Y=!ypg(o$eb#bYC-*)t~XPtHK5$O$;6m14l)1Sc=NF8SBo$KZ4a|#8* zqCSU-{fMOa8OosOF-3%32r*M_`E|~0KSR|7NE3>4hs!mkpJl4M!sj1jDcxU>L82qq zi*bQg7_!!?#tS0?Cf)kGiAQJ0pgf_qYo+j(t8y9I55Y zksi!>t!L#0#F!L!Nb%>Ni3i#+aHTuS-l;myEZjlN2Ns8S6kDp9`sCMVY3_BKh`5uz z9~Y5?khZs-A9uJzDUOTO)2B1nVb(u+0qW()at?ui;NYaN^k(83_1 zN(58+Z7P|xit9g4Y}rtYtu*l#Vwrl*%IkUP>+*koZeh{;r6cUW5%cP9cHIlMu~k7?L`3JMgb^<+-_ z*gww5;tjVFs)MY^BXBfZ{&lVtPT5ldsIT2tzE0&t?>2MnpFy`my;#pZGT$^H6|pL= zK_obe!EMGlukV?%iQWX66lv<<&V>33tv6!R;5?QmDxlwB{aLoa*&)C@*$jA>G2 zlQ29Ou!C;h@J99ouCK0EeG0Nn%73jtnppn_B2PWQ_P52=q2&IyI4L|V@^8H%#KYwA z)n{Fm7Vl_xS0O9LH(((41EPc>47q>`3-2EnNd?ivc&3oQZg&=-{)2bF|KkFJblkj! zcL0g}CspD7>ljk`o7*wwY+V;Gm8)VS>roEkD*=rW;k>NNgDpl@d1?!%-U1iz<(ESZalf(640JII z;?rm?)9AS88&HC*Ra3K3%gDs6Hl}Kd>NNFIYLC*f9HG$kxM_At$E(j{XKWsltBZ=U zsSY;A?R3qdgiDhj=XZ!)8(iT17?@8?)4~AQ!cQ#Q$P}0d)m9JHn)V6I z7+hmjT{!0=@*>TEJIcc%qWR`6_rI>KND)o^!b0Ri(5+SX^&nQ*gUnl8m5m=wyD%)` ziiMZwPK8Z2YKl-a*8};ULhO`klo%I1O9Jluu4*W#4BPzF7gczO>C1PTEB4kNd>Xqf zZJtD5BUeV$=`q%1HueF9rU=7G9=c?>2Xh~6o?dwW-Y^B$B{oc%<#$xq;L^40kkeRJ z8@9{aeK%S7_?w#_e1XgE+oGRg@UNQB7-%fQrXgBn@c#G0&|^($^6HaIv+od*vFwxD z;zI)sa&=ix3u|eY^e6HVSx>=wVixH%jvs3Ucc?mCxBe39T1nJrGv#elxAN`8C@#P^ zOLzEA_ruFk-Dw3k%3`M#pSArUT}B2F9gmIAaFst6OyQcBXn&PSE2*u6J{b#jlp#Ku z-6TSm!q~@P)x? zO1;UqP7XJYEiPU?GtJphA{vjSQo2#Ujn-*d++p2HD7^oZE&EX4bnU5ltC?6+Ix}nJ zkKKidd%yX|rNv)8c|v}oN<57s(8_y~*8#kVj|uSNRDb`a2l{(}&kYDa)erOmb*k%s ztN6cvB?*|egQ!4A`O92svuP*dv4IPwxI(Iu6?$Uml zXx{XysLnn@7`Z zf>x!+fygaHTEM+8y$+wI%RZfbyl(S+Zl?y+_9NKq+WbRQ%O42Y^iiPbWpA&pF9uod zMrq;kUMA)+m3ouhv@LIO@B$i6jXwM4fLEZp1RNdz{${)N_87q@R;$*F|ymS(=nxn{CW=&`+2*_ zJsP*9g!^C=^)_Z5!R0p|VG^=ur&%oZR`up|J0UdD*CiGNT(fLGi#u{DPl4Z6*n+SI zvyV1d8b+%_Rv6@C`TL$*OEfWTBtL1dEW>s9QBjFujRNnV6`xv5Cb`%g8o|2Gl;=l^G4DgOI%NQeiH2afv*QpL7aSMcn{fCfoL zrvZ@CGQ#BsPz}WWKrN}4_4mrmE6RZ^KT%*?DF;+nKV4R?`PLCxkCD$oiRfjyE4GAJ~0{`#B$~7TcE9Yb-;l)?#Ifi}Jxcx&u#LsrN3p znT1{*IGH-1qqZK~@AcOoyuAmnmAh)OGd?OO;OlbwW?E(7IMO#dE*du2pmXS1ZZ3o- z4bLa^uwF5()b_m!-M>-FVNX&=Hi1E2RioYKsiL!+qmCTXO>UPF;ZS#W6Vy{ZGP4Sw zQ^XH#kZ|6%EAWxRp!@WHh@f&%rk1a}sjs2*~aP*J^O$O(0c({EFLcRM?h z+UVPQMNg;|AqX)-guZM4zKF~4e1poYAl7%0km|yG{lp>(wkbQ~_}Grw+fD2$TjFZ6 z>d~dRRSUb~>cR6HJ}=PC7sl9hxj^&@BLp{5=ZJGZP~{fL`;F3ri|h4zrMD=FGXcI} zG5n9ie^l)M{m;Qt2qPS~4|L8BvWZ|CP;xW9V_m`^_F@)4{dr(<0DSyEd9*+_X+Am- z2p8?cVH#$EfaQRP?SnfA;Q|&3Yz5I)0}Dosfq?3?|b8BbOC=&r7t8-jv9l z;ylO*$C&sn;|lpJ)WWL7QT&&uFOmee z2UVmIh5uN$3GTW&gl-Sa92;!>9y=_oA)|TimVQTX?pJKOHgnZJy(PrQl3T} zv}S1>KcLKe*YUa5X;&fZnzqz)&L(r}ue45Spfk@**^SJ=b$D~atnEUM+z$E&Y43npU8eTA*?U*!eKUHqzK?B)>DT8 z@3!m!Rxj2Mv;l^dJO=zBUT_^+JuJ8|FPt_j6e7T$K|9#u*H2U!gIWBn&JkmKaS7Lc zS@r-m$Dd!{6gxOZh5uWF+rI!^5}}Ji>>PiO7DHdHE{%!XAQf-VDo?% zpSh=;(_tjG%mzK_AnuN6C`@x;IeVADujX?f`B_wbzTw&-2bMI8ypb*Iiep?2Mkhkg z#l^(3ftWZcR#^6GM(bt4G(+4-e19oJoh2;-C5|&I9fYhj#IKJ9zh8bYJF zs^zhKi0_e{Ea1eZd+MQ*pKt~u@IFGwN*FRE(9 zlGf8hhbM{jrjM@?Ik9O}$q^tQEM$sUlvv-A3F;z0!o@8wVIm7QZ8zdlyaVlz4#!F! z&0nt$i-{tYHJ)=1fmu498J&HQv;K_DpCb$58u|qyiDNtM!^Bv=eR)LuvX3Z`!Dv}= zM{IRM+$1JfxZ6=f8P&ujx0Yn3r_BrFgM6H*g7N!+ec_QP&sYDVz2Fe ziVg%z#vlP&o>pr~>w;VX{B~~gPR_Bk3FEf)-NqQLDZio#k1zH;Puf@BtFvN;=-MI+ z7?f{$$=ECX{Ovvi9l4B!sa_QRMW6GWGVsThTjya7z}iO003b zKYC6O2Gs*d*O9T0IJP)+&9Jl1G>z&_S?Uxd_S|rFWK6|uf5`TZb+^PD&?H=*(Y^$- zHN2k^*i8VDJRs>Nu>TaINCH{|7(jf4?}CH)#dgrBvWa%!K&z3I7to`!p6U|B+9L;J z_k%#F6KI*r!1^-)dk>03PC!cnh!$N45;Ce#TtJ~VzQRy!_uJ_s=1yTRQRsd)b>=x2 z&O@d-iIx8N?W3wo%)XYsi}!v&H$q^DC9{$Yi~?$&G+7}nP~7iPH7!Y;)l=Jzmk6_i zxvNO&Vxf1IWX}&|*P{}@(M)M*A3yCX3sgHXig(H)@ai6=u$dRI)SQfoq2Q-$K@ms8 zzTDaSSVZz%S@k9=_)=7kN@{E`oAm;1IU6*?WabA-PGG6+y2=azN~Og@hQ+HHF#!Fw zj;xwdz-pn-j0_^sjY;&eiYwfQvK#?NQ?!x`mdseEL*Z{2(t=B^Ch7Msr?jeVkTur(kb4vdtsO)mQ}>xXAfHKM zZz%3lc8xDgG&Ww9mSFovU5c!A_61DsvsVh6w# zJY92Fq&w(dEFD@DbTgwh^P6u}$NpTP$yW8{bM&otU%H>qx1JDvx`5-Ks<&R?9x-qF zJ}s18WgFT<$#4<+js=W30=6;mR;Hvn^zi{{Rh41LQTPgX>j5XjKHY9gjHR9cwn`{@&<)3Tg)p}5=Cdoou$TOsrRg^39QZsroo9;nL@HP{b~nmZuVcth%w;#O z+*j~e=1a%aL10T3MDwudK7wzf<0g)J8ovkHgLH{lO9CS|<^9JR1GL|o*^gr5^akA) zdrZadkMbCuP{i&a%WDWYBr<~v+F5)N(- z&smypis2Bqo(NH$=PzBl#x|Vs1*eQhmj!_ltS-S!B#@~kmH*NK26~ZDK3-tw;Cp#1 zgRx-j29*&x_$3?YRN9;*O!JrD_sfrD4s zO%U#mWw(G5AT*TaM3+q78~su6ViytCkaWlJoAmD3Zb=h9TJn{2nkBhu^RI_QJH>UT z+^-;{d^7R|!GKf?s2vBBOYh@VpHBw&R#kNJAUq2D-rJg}Ja9q6r?9@{9XOy_j5Vlm z>S+|1SyOHGD`GM$CfP3)Rlad>*N4mhb-Gc$T3vG9i$<;ih3Tu5cH*hE_71;32i)7K z0xT|A^+K^}F-v1tD{tF&{vW}OVtuOXuc$Q+dyNjmupaXQf?HkuSnle~SN0 z7jmk6F3(<5jAg4{LEY9nnamzheu~yv!rPt#$|cU8lTMGb!s8j}7{fe%65Xt?ev&S( zKh(eP_;kTw#(iw~caxp@&6B|+{oxYvKahGUtsXX|KJ-sBFg)ip)|dgQPrv8N$6uw>ouwwa09^BUM~Q3ki!O!To)&E3;srsKW2 znXGvM{o{J|dE-%}e*NpKr-C;apCgG2+|*wFVC0OILYW+`3*WcCvyRSQ9n^C~rdeos zu_V;kg8w&5XEZjD|4Xw@AASc+G$8+O{ij--)BaQIjzI;%SH+Jf1CeH@e>Pe3Ng|72klAz)6z^uNm?EB>BFf@cd5huFsc ze$;9{V~i`TZx&A@fjo6crG5E?L|4RA zFI!K$8AzT3)`Gu+=<|_yooRnCs>MHyUREBMx8oIK^-?baMj$Ak82+b1aKCY@yyB21 z&>*>K|BnP8*|ws(q7DMyEWyi60L!WWQ;KIr5opu_6Oao+nJxPg_CPOBaoiuwq(KD& zpFw-q_$Sc@OC+FJlb?ocKf&?fx#tIf#rb;`pab%^oGier4#GNtj5_`%@%Xsuzo$cR ztHCn&Kv3O^`tiWO$=@eQ*n>9^{@1;u&m5pA6Dct61|oZ}$TeQx0xBUuiVu1GS6{?T zm(Uweg7gQ1F9LXwAfJ-iR{$vzL{Ag2CS6npZep+r+lzbf4kpm!I-HQa5(^I+SehvV#%0Rde+zIFb66z1mgKw}7gFlxR%xJ+0giL^@ znisHBg9o{Zzbnfh$Uy-(gIo4LPxJSI@uh&Y$^Z3<-T!A&{h!ITGOY)G81;XDW`Hga zUYqCt_krVQBKVmK{-cDSn*dk3Jpmpn3<#lcUp6Pejq%RHPk%`-z|J-pec{c1Rw9US zJO}PXpr;LdWqh+RWuAMELLCF4hI|0cZuTr?7N6}xam s9_TmJ|2Y$=2k8=M{=Fc6un6VT>5AkfaQOF${y7V{1U|ij{`vL40Gn583;+NC literal 0 HcmV?d00001 diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index bc5fd8a49..dad8ed580 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -37,6 +37,7 @@ def test_create_counterexample(): content_type='application/json') authenticator = BasicAuthenticator('username', 'password') service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) + service.set_service_url(base_url) counterexample = service.create_counterexample( workspace_id='boguswid', text='I want financial advice today.').get_result() assert len(responses.calls) == 1 diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 529cc9563..0182bf8f5 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -372,55 +372,6 @@ def test_query_2(cls): assert called_url.path == test_url.path assert len(responses.calls) == 1 - @classmethod - @responses.activate - def test_query_relations(cls): - discovery_url = urljoin( - base_discovery_url, - 'environments/envid/collections/collid/query_relations') - - responses.add( - responses.POST, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) - - discovery.query_relations('envid', 'collid', count=10) - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path - assert len(responses.calls) == 1 - - - @classmethod - @responses.activate - def test_query_entities(cls): - discovery_url = urljoin( - base_discovery_url, - 'environments/envid/collections/collid/query_entities') - - responses.add( - responses.POST, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) - - discovery.query_entities('envid', 'collid', count={'count': 10}) - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path - assert len(responses.calls) == 1 - @classmethod @responses.activate def test_query_notices(cls): @@ -523,17 +474,6 @@ def test_document(cls): authenticator = BasicAuthenticator('username', 'password') discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) - html_path = os.path.join(os.getcwd(), 'resources', 'simple.html') - with open(html_path) as fileinfo: - conf_id = discovery.test_configuration_in_environment(environment_id='envid', - configuration_id='bogus', - file=fileinfo) - assert conf_id is not None - conf_id = discovery.test_configuration_in_environment(environment_id='envid', - file=fileinfo) - assert conf_id is not None - - assert len(responses.calls) == 2 add_doc_url = urljoin(base_discovery_url, 'environments/envid/collections/collid/documents') @@ -580,38 +520,38 @@ def test_document(cls): file=fileinfo) assert conf_id is not None - assert len(responses.calls) == 3 + assert len(responses.calls) == 1 discovery.get_document_status(environment_id='envid', collection_id='collid', document_id='docid') - assert len(responses.calls) == 4 + assert len(responses.calls) == 2 discovery.update_document(environment_id='envid', collection_id='collid', document_id='docid') - assert len(responses.calls) == 5 + assert len(responses.calls) == 3 discovery.update_document(environment_id='envid', collection_id='collid', document_id='docid') - assert len(responses.calls) == 6 + assert len(responses.calls) == 4 discovery.delete_document(environment_id='envid', collection_id='collid', document_id='docid') - assert len(responses.calls) == 7 + assert len(responses.calls) == 5 conf_id = discovery.add_document(environment_id='envid', collection_id='collid', file=io.StringIO(u'my string of file'), filename='file.txt') - assert len(responses.calls) == 8 + assert len(responses.calls) == 6 conf_id = discovery.add_document(environment_id='envid', collection_id='collid', @@ -619,7 +559,7 @@ def test_document(cls): filename='file.html', file_content_type='application/html') - assert len(responses.calls) == 9 + assert len(responses.calls) == 7 conf_id = discovery.add_document(environment_id='envid', collection_id='collid', @@ -628,7 +568,7 @@ def test_document(cls): file_content_type='application/html', metadata=io.StringIO(u'{"stuff": "woot!"}')) - assert len(responses.calls) == 10 + assert len(responses.calls) == 8 @classmethod diff --git a/test/unit/test_natural_language_understanding.py b/test/unit/test_natural_language_understanding.py index 485b402bd..d5b01db4c 100644 --- a/test/unit/test_natural_language_understanding.py +++ b/test/unit/test_natural_language_understanding.py @@ -62,7 +62,6 @@ def test_version_date(self): NaturalLanguageUnderstandingV1() # pylint: disable=E1120 authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - url='http://bogus.com', authenticator=authenticator) assert nlu @@ -72,38 +71,35 @@ def test_missing_credentials(self): with pytest.raises(ValueError): NaturalLanguageUnderstandingV1(version='2016-01-23') with pytest.raises(ValueError): - NaturalLanguageUnderstandingV1(version='2016-01-23', url='http://bogus.com') + NaturalLanguageUnderstandingV1(version='2016-01-23') def test_analyze_throws(self): authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - url='http://bogus.com', authenticator=authenticator) with pytest.raises(ValueError): nlu.analyze(None, text="this will not work") @responses.activate def test_text_analyze(self): - nlu_url = "http://bogus.com/v1/analyze" + nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze" responses.add(responses.POST, nlu_url, body="{\"resulting_key\": true}", status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - url='http://bogus.com', authenticator=authenticator) nlu.analyze(Features(sentiment=SentimentOptions()), text="hello this is a test") assert len(responses.calls) == 1 @responses.activate def test_html_analyze(self): - nlu_url = "http://bogus.com/v1/analyze" + nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze" responses.add(responses.POST, nlu_url, body="{\"resulting_key\": true}", status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - url='http://bogus.com', authenticator=authenticator) nlu.analyze(Features(sentiment=SentimentOptions(), emotion=EmotionOptions(document=False)), @@ -112,13 +108,12 @@ def test_html_analyze(self): @responses.activate def test_url_analyze(self): - nlu_url = "http://bogus.com/v1/analyze" + nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze" responses.add(responses.POST, nlu_url, body="{\"resulting_key\": true}", status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - url='http://bogus.com', authenticator=authenticator) nlu.analyze(Features(sentiment=SentimentOptions(), emotion=EmotionOptions(document=False)), @@ -128,13 +123,12 @@ def test_url_analyze(self): @responses.activate def test_list_models(self): - nlu_url = "http://bogus.com/v1/models" + nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models" responses.add(responses.GET, nlu_url, status=200, body="{\"resulting_key\": true}", content_type='application/json') authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - url='http://bogus.com', authenticator=authenticator) nlu.list_models() assert len(responses.calls) == 1 @@ -142,12 +136,11 @@ def test_list_models(self): @responses.activate def test_delete_model(self): model_id = "invalid_model_id" - nlu_url = "http://bogus.com/v1/models/" + model_id + nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models/" + model_id responses.add(responses.DELETE, nlu_url, status=200, body="{}", content_type='application/json') authenticator = BasicAuthenticator('username', 'password') nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - url='http://bogus.com', authenticator=authenticator) nlu.delete_model(model_id) assert len(responses.calls) == 1 diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index a1c58572e..269346959 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -13,14 +13,14 @@ def test_plain_to_json(): authenticator = BasicAuthenticator('username', 'password') personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect1.txt')) as expect_file: + with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect1.txt'), 'r') as expect_file: profile_response = expect_file.read() responses.add(responses.POST, profile_url, body=profile_response, status=200, content_type='application/json') - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.txt')) as personality_text: + with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.txt'), 'rb') as personality_text: response = personality_insights.profile( personality_text, 'application/json', content_type='text/plain;charset=utf-8').get_result() @@ -36,14 +36,14 @@ def test_json_to_json(): authenticator = BasicAuthenticator('username', 'password') personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect2.txt')) as expect_file: + with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect2.txt'), 'r') as expect_file: profile_response = expect_file.read() responses.add(responses.POST, profile_url, body=profile_response, status=200, content_type='application/json') - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.json')) as personality_text: + with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.json'), 'rb') as personality_text: response = personality_insights.profile( personality_text, accept='application/json', content_type='application/json', @@ -64,14 +64,14 @@ def test_json_to_csv(): authenticator = BasicAuthenticator('username', 'password') personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect3.txt')) as expect_file: + with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect3.txt'), 'r') as expect_file: profile_response = expect_file.read() responses.add(responses.POST, profile_url, body=profile_response, status=200, content_type='text/csv') - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.json')) as personality_text: + with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.json'), 'rb') as personality_text: personality_insights.profile( personality_text, 'text/csv', @@ -94,15 +94,14 @@ def test_plain_to_json_es(): authenticator = BasicAuthenticator('username', 'password') personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - with codecs.open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect4.txt'), \ - encoding='utf-8') as expect_file: + with codecs.open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect4.txt'), 'r') as expect_file: profile_response = expect_file.read() responses.add(responses.POST, profile_url, body=profile_response, status=200, content_type='application/json') - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-es.txt')) as personality_text: + with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-es.txt'), 'rb') as personality_text: response = personality_insights.profile( personality_text, 'application/json', From 975d39ecee6f4b9929eb06445adce7d68e3be9aa Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 1 Oct 2019 10:21:25 -0700 Subject: [PATCH 086/455] chore(exmaples): Update setting url in examples --- examples/assistant_v1.py | 3 +-- examples/assistant_v2.py | 3 +-- examples/compare_comply_v1.py | 3 +-- examples/discovery_v1.py | 3 +-- examples/language_translator_v3.py | 3 +-- examples/microphone-speech-to-text.py | 4 +--- examples/natural_language_classifier_v1.py | 6 ++---- examples/natural_language_understanding_v1.py | 3 +-- examples/personality_insights_v3.py | 3 +-- examples/speaker_text_to_speech.py | 14 +++----------- examples/speech_to_text_v1.py | 6 ++---- examples/text_to_speech_v1.py | 6 ++---- examples/tone_analyzer_v3.py | 3 +-- examples/visual_recognition_v3.py | 11 +---------- 14 files changed, 19 insertions(+), 52 deletions(-) diff --git a/examples/assistant_v1.py b/examples/assistant_v1.py index 71d9b610c..c4faa537e 100644 --- a/examples/assistant_v1.py +++ b/examples/assistant_v1.py @@ -5,9 +5,8 @@ authenticator = IAMAuthenticator('your apikey') assistant = AssistantV1( version='2018-07-10', - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/assistant/api', authenticator=authenticator) +assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') ######################### # Workspaces diff --git a/examples/assistant_v2.py b/examples/assistant_v2.py index 92bd4aea2..bf81d13ab 100644 --- a/examples/assistant_v2.py +++ b/examples/assistant_v2.py @@ -5,9 +5,8 @@ authenticator = IAMAuthenticator('your apikey') assistant = AssistantV2( version='2018-09-20', - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/assistant/api', authenticator=authenticator) +assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') ######################### # Sessions diff --git a/examples/compare_comply_v1.py b/examples/compare_comply_v1.py index f932ac34c..81867d0c0 100644 --- a/examples/compare_comply_v1.py +++ b/examples/compare_comply_v1.py @@ -7,9 +7,8 @@ authenticator = IAMAuthenticator('your apikey') compare_comply = CompareComplyV1( version='2018-03-23', - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/compare-comply/api', authenticator=authenticator) +compare_comply.set_service_url('https://gateway.watsonplatform.net/compare-comply/api') print('Convert to HTML') contract = os.path.abspath('resources/contract_A.pdf') diff --git a/examples/discovery_v1.py b/examples/discovery_v1.py index 9a7c4fc3f..1bf1dad4d 100644 --- a/examples/discovery_v1.py +++ b/examples/discovery_v1.py @@ -5,9 +5,8 @@ authenticator = IAMAuthenticator('your_api_key') discovery = DiscoveryV1( version='2018-08-01', - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/discovery/api', authenticator=authenticator) +discovery.set_service_url('https://gateway.watsonplatform.net/discovery/api') environments = discovery.list_environments().get_result() print(json.dumps(environments, indent=2)) diff --git a/examples/language_translator_v3.py b/examples/language_translator_v3.py index fa392ce37..2cced01c4 100644 --- a/examples/language_translator_v3.py +++ b/examples/language_translator_v3.py @@ -6,9 +6,8 @@ authenticator = IAMAuthenticator('your_api_key') language_translator = LanguageTranslatorV3( version='2018-05-01', - ### url is optional, and defaults to the URL below. Use the correct URL for your region. - # url='https://gateway.watsonplatform.net/language-translator/api', authenticator=authenticator) +language_translator.set_service_url('https://gateway.watsonplatform.net/language-translator/api') ## Translate translation = language_translator.translate( diff --git a/examples/microphone-speech-to-text.py b/examples/microphone-speech-to-text.py index 2a9a72601..9174de74f 100644 --- a/examples/microphone-speech-to-text.py +++ b/examples/microphone-speech-to-text.py @@ -36,9 +36,7 @@ # initialize speech to text service authenticator = IAMAuthenticator('your_api_key') -speech_to_text = SpeechToTextV1( - url='{YOUR_GATEWAY_URL}', - authenticator=authenticator) +speech_to_text = SpeechToTextV1(authenticator=authenticator) # define callback for the speech to text service class MyRecognizeCallback(RecognizeCallback): diff --git a/examples/natural_language_classifier_v1.py b/examples/natural_language_classifier_v1.py index 8e4688124..3cf93c1f4 100644 --- a/examples/natural_language_classifier_v1.py +++ b/examples/natural_language_classifier_v1.py @@ -5,10 +5,8 @@ from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your_api_key') -service = NaturalLanguageClassifierV1( - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/natural-language-classifier/api', - authenticator=authenticator) +service = NaturalLanguageClassifierV1(authenticator=authenticator) +service.set_service_url('https://gateway.watsonplatform.net/natural-language-classifier/api') classifiers = service.list_classifiers().get_result() print(json.dumps(classifiers, indent=2)) diff --git a/examples/natural_language_understanding_v1.py b/examples/natural_language_understanding_v1.py index 82eec8c12..9ed28204a 100644 --- a/examples/natural_language_understanding_v1.py +++ b/examples/natural_language_understanding_v1.py @@ -6,9 +6,8 @@ authenticator = IAMAuthenticator('your_api_key') service = NaturalLanguageUnderstandingV1( version='2018-03-16', - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/natural-language-understanding/api', authenticator=authenticator) +service.set_service_url('https://gateway.watsonplatform.net/natural-language-understanding/api') response = service.analyze( text='Bruce Banner is the Hulk and Bruce Wayne is BATMAN! ' diff --git a/examples/personality_insights_v3.py b/examples/personality_insights_v3.py index b513ddfd5..68fe1f2cd 100755 --- a/examples/personality_insights_v3.py +++ b/examples/personality_insights_v3.py @@ -11,9 +11,8 @@ authenticator = IAMAuthenticator('your_api_key') service = PersonalityInsightsV3( version='2017-10-13', - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/personality-insights/api', authenticator=authenticator) +service.set_service_url('https://gateway.watsonplatform.net/personality-insights/api') ############################ # Profile with JSON output # diff --git a/examples/speaker_text_to_speech.py b/examples/speaker_text_to_speech.py index 039a260c6..78b8c6ab5 100644 --- a/examples/speaker_text_to_speech.py +++ b/examples/speaker_text_to_speech.py @@ -9,17 +9,9 @@ from ibm_watson.websocket import SynthesizeCallback import pyaudio -# If service instance provides API key authentication -service = TextToSpeechV1( - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://stream.watsonplatform.net/text-to-speech/api', - iam_apikey='your_apikey') - -# service = TextToSpeechV1( -# ## url is optional, and defaults to the URL below. Use the correct URL for your region. -# # url='https://stream.watsonplatform.net/text-to-speech/api, -# username='YOUR SERVICE USERNAME', -# password='YOUR SERVICE PASSWORD') +authenticator = IAMAuthenticator('your_api_key') +service = SpeechToTextV1(authenticator=authenticator) +service.set_service_url('https://stream.watsonplatform.net/speech-to-text/api') class Play(object): """ diff --git a/examples/speech_to_text_v1.py b/examples/speech_to_text_v1.py index 77ef35614..083e7d961 100644 --- a/examples/speech_to_text_v1.py +++ b/examples/speech_to_text_v1.py @@ -6,10 +6,8 @@ from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your_api_key') -service = SpeechToTextV1( - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://stream.watsonplatform.net/speech-to-text/api', - authenticator=authenticator) +service = SpeechToTextV1(authenticator=authenticator) +service.set_service_url('https://stream.watsonplatform.net/speech-to-text/api') models = service.list_models().get_result() print(json.dumps(models, indent=2)) diff --git a/examples/text_to_speech_v1.py b/examples/text_to_speech_v1.py index 4c3c6cc1e..3f60b9cbf 100644 --- a/examples/text_to_speech_v1.py +++ b/examples/text_to_speech_v1.py @@ -6,10 +6,8 @@ from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your_api_key') -service = TextToSpeechV1( - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://stream.watsonplatform.net/text-to-speech/api', - authenticator=authenticator) +service = TextToSpeechV1(authenticator=authenticator) +service.set_service_url('https://stream.watsonplatform.net/text-to-speech/api') voices = service.list_voices().get_result() print(json.dumps(voices, indent=2)) diff --git a/examples/tone_analyzer_v3.py b/examples/tone_analyzer_v3.py index c7d36ed6f..921336fa6 100755 --- a/examples/tone_analyzer_v3.py +++ b/examples/tone_analyzer_v3.py @@ -6,10 +6,9 @@ authenticator = IAMAuthenticator('your_api_key') service = ToneAnalyzerV3( - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/tone-analyzer/api', version='2017-09-21', authenticator=authenticator) +service.set_service_url('https://gateway.watsonplatform.net/tone-analyzer/api') print("\ntone_chat() example 1:\n") utterances = [{ diff --git a/examples/visual_recognition_v3.py b/examples/visual_recognition_v3.py index f0efc1677..775edba73 100644 --- a/examples/visual_recognition_v3.py +++ b/examples/visual_recognition_v3.py @@ -10,9 +10,8 @@ # If service instance provides IAM API key authentication service = VisualRecognitionV3( '2018-03-19', - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/visual-recognition/api', authenticator=authenticator) +service.set_service_url('https://gateway.watsonplatform.net/visual-recognition/api') # with open(abspath('resources/cars.zip'), 'rb') as cars, \ # open(abspath('resources/trucks.zip'), 'rb') as trucks: @@ -40,20 +39,12 @@ # positive_examples={'cars_positive_examples': image_file}).get_result() # print(json.dumps(classifier, indent=2)) -# faces_result = service.detect_faces(url=test_url).get_result() -# print(json.dumps(faces_result, indent=2)) - # response = service.delete_classifier(classifier_id='YOUR CLASSIFIER ID').get_result() # print(json.dumps(response, indent=2)) classifiers = service.list_classifiers().get_result() print(json.dumps(classifiers, indent=2)) -face_path = abspath('resources/face.jpg') -with open(face_path, 'rb') as image_file: - face_result = service.detect_faces(images_file=image_file).get_result() - print(json.dumps(face_result, indent=2)) - #Core ml model example # model_name = '{0}.mlmodel'.format(classifier_id) # core_ml_model = service.get_core_ml_model(classifier_id).get_result() From 5f2a44f0b7c4ae3522a1233d085da62ef92cbca1 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 1 Oct 2019 10:37:30 -0700 Subject: [PATCH 087/455] chore(services): regenerate all the services --- ibm_watson/assistant_v1.py | 1056 +++-- ibm_watson/assistant_v2.py | 308 +- ibm_watson/compare_comply_v1.py | 830 ++-- ibm_watson/discovery_v1.py | 3745 ++++++----------- ibm_watson/language_translator_v3.py | 294 +- ibm_watson/natural_language_classifier_v1.py | 160 +- .../natural_language_understanding_v1.py | 548 ++- ibm_watson/personality_insights_v3.py | 111 +- ibm_watson/speech_to_text_v1.py | 737 ++-- ibm_watson/speech_to_text_v1_adapter.py | 2 +- ibm_watson/text_to_speech_adapter_v1.py | 2 +- ibm_watson/text_to_speech_v1.py | 258 +- ibm_watson/tone_analyzer_v3.py | 126 +- ibm_watson/visual_recognition_v3.py | 43 +- ibm_watson/visual_recognition_v4.py | 1 - 15 files changed, 3431 insertions(+), 4790 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 3fe5fc74a..a24f38826 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -25,6 +25,7 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources ############################################################################## # Service @@ -34,14 +35,12 @@ class AssistantV1(BaseService): """The Assistant V1 service.""" - default_url = 'https://gateway.watsonplatform.net/assistant/api' + default_service_url = 'https://gateway.watsonplatform.net/assistant/api' def __init__( self, version, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Assistant service. @@ -57,25 +56,27 @@ def __init__( application, and don't change it until your application is ready for a later version. - :param str url: The base url to use when contacting the service (e.g. - "https://gateway.watsonplatform.net/assistant/api/assistant/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('assistant') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: - authenticator = get_authenticator_from_environment('Assistant') + authenticator = get_authenticator_from_environment('assistant') - BaseService.__init__( - self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Assistant') + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) self.version = version ######################### @@ -164,13 +165,12 @@ def message(self, url = '/v1/workspaces/{0}/message'.format( *self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -221,12 +221,11 @@ def list_workspaces(self, } url = '/v1/workspaces' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -309,13 +308,12 @@ def create_workspace(self, } url = '/v1/workspaces' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -367,12 +365,11 @@ def get_workspace(self, } url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -469,13 +466,12 @@ def update_workspace(self, } url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -505,12 +501,11 @@ def delete_workspace(self, workspace_id, **kwargs): params = {'version': self.version} url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -574,12 +569,11 @@ def list_intents(self, url = '/v1/workspaces/{0}/intents'.format( *self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -637,13 +631,12 @@ def create_intent(self, url = '/v1/workspaces/{0}/intents'.format( *self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -694,12 +687,11 @@ def get_intent(self, url = '/v1/workspaces/{0}/intents/{1}'.format( *self._encode_path_vars(workspace_id, intent)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -760,13 +752,12 @@ def update_intent(self, url = '/v1/workspaces/{0}/intents/{1}'.format( *self._encode_path_vars(workspace_id, intent)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -800,12 +791,11 @@ def delete_intent(self, workspace_id, intent, **kwargs): url = '/v1/workspaces/{0}/intents/{1}'.format( *self._encode_path_vars(workspace_id, intent)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -867,12 +857,11 @@ def list_examples(self, url = '/v1/workspaces/{0}/intents/{1}/examples'.format( *self._encode_path_vars(workspace_id, intent)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -926,13 +915,12 @@ def create_example(self, url = '/v1/workspaces/{0}/intents/{1}/examples'.format( *self._encode_path_vars(workspace_id, intent)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -977,12 +965,11 @@ def get_example(self, url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( *self._encode_path_vars(workspace_id, intent, text)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1038,13 +1025,12 @@ def update_example(self, url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( *self._encode_path_vars(workspace_id, intent, text)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -1081,12 +1067,11 @@ def delete_example(self, workspace_id, intent, text, **kwargs): url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( *self._encode_path_vars(workspace_id, intent, text)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1145,12 +1130,11 @@ def list_counterexamples(self, url = '/v1/workspaces/{0}/counterexamples'.format( *self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1193,13 +1177,12 @@ def create_counterexample(self, workspace_id, text, **kwargs): url = '/v1/workspaces/{0}/counterexamples'.format( *self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -1243,12 +1226,11 @@ def get_counterexample(self, url = '/v1/workspaces/{0}/counterexamples/{1}'.format( *self._encode_path_vars(workspace_id, text)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1298,13 +1280,12 @@ def update_counterexample(self, url = '/v1/workspaces/{0}/counterexamples/{1}'.format( *self._encode_path_vars(workspace_id, text)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -1341,12 +1322,11 @@ def delete_counterexample(self, workspace_id, text, **kwargs): url = '/v1/workspaces/{0}/counterexamples/{1}'.format( *self._encode_path_vars(workspace_id, text)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1410,12 +1390,11 @@ def list_entities(self, url = '/v1/workspaces/{0}/entities'.format( *self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1482,13 +1461,12 @@ def create_entity(self, url = '/v1/workspaces/{0}/entities'.format( *self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -1539,12 +1517,11 @@ def get_entity(self, url = '/v1/workspaces/{0}/entities/{1}'.format( *self._encode_path_vars(workspace_id, entity)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1612,13 +1589,12 @@ def update_entity(self, url = '/v1/workspaces/{0}/entities/{1}'.format( *self._encode_path_vars(workspace_id, entity)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -1652,12 +1628,11 @@ def delete_entity(self, workspace_id, entity, **kwargs): url = '/v1/workspaces/{0}/entities/{1}'.format( *self._encode_path_vars(workspace_id, entity)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1712,12 +1687,11 @@ def list_mentions(self, url = '/v1/workspaces/{0}/entities/{1}/mentions'.format( *self._encode_path_vars(workspace_id, entity)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1784,12 +1758,11 @@ def list_values(self, url = '/v1/workspaces/{0}/entities/{1}/values'.format( *self._encode_path_vars(workspace_id, entity)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1861,13 +1834,12 @@ def create_value(self, url = '/v1/workspaces/{0}/entities/{1}/values'.format( *self._encode_path_vars(workspace_id, entity)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -1921,12 +1893,11 @@ def get_value(self, url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( *self._encode_path_vars(workspace_id, entity, value)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2002,13 +1973,12 @@ def update_value(self, url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( *self._encode_path_vars(workspace_id, entity, value)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2045,12 +2015,11 @@ def delete_value(self, workspace_id, entity, value, **kwargs): url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( *self._encode_path_vars(workspace_id, entity, value)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2115,12 +2084,11 @@ def list_synonyms(self, url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( *self._encode_path_vars(workspace_id, entity, value)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2168,13 +2136,12 @@ def create_synonym(self, workspace_id, entity, value, synonym, **kwargs): url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( *self._encode_path_vars(workspace_id, entity, value)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2223,12 +2190,11 @@ def get_synonym(self, url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( *self._encode_path_vars(workspace_id, entity, value, synonym)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2284,13 +2250,12 @@ def update_synonym(self, url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( *self._encode_path_vars(workspace_id, entity, value, synonym)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2330,12 +2295,11 @@ def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( *self._encode_path_vars(workspace_id, entity, value, synonym)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2392,12 +2356,11 @@ def list_dialog_nodes(self, url = '/v1/workspaces/{0}/dialog_nodes'.format( *self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2520,13 +2483,12 @@ def create_dialog_node(self, url = '/v1/workspaces/{0}/dialog_nodes'.format( *self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2567,12 +2529,11 @@ def get_dialog_node(self, url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( *self._encode_path_vars(workspace_id, dialog_node)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2698,13 +2659,12 @@ def update_dialog_node(self, url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( *self._encode_path_vars(workspace_id, dialog_node)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2739,12 +2699,11 @@ def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( *self._encode_path_vars(workspace_id, dialog_node)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2803,12 +2762,11 @@ def list_logs(self, url = '/v1/workspaces/{0}/logs'.format( *self._encode_path_vars(workspace_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2862,12 +2820,11 @@ def list_all_logs(self, } url = '/v1/logs' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2905,12 +2862,11 @@ def delete_user_data(self, customer_id, **kwargs): params = {'version': self.version, 'customer_id': customer_id} url = '/v1/user_data' - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -3019,7 +2975,7 @@ class Sort(Enum): ############################################################################## -class CaptureGroup(object): +class CaptureGroup(): """ A recognized capture group for a pattern-based entity. @@ -3043,12 +2999,12 @@ def __init__(self, group, *, location=None): def _from_dict(cls, _dict): """Initialize a CaptureGroup object from a json dictionary.""" args = {} - validKeys = ['group', 'location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['group', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CaptureGroup: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'group' in _dict: args['group'] = _dict.get('group') else: @@ -3082,7 +3038,7 @@ def __ne__(self, other): return not self == other -class Context(object): +class Context(): """ State information for the conversation. To maintain state, include the context from the previous response. @@ -3173,7 +3129,7 @@ def __ne__(self, other): return not self == other -class Counterexample(object): +class Counterexample(): """ Counterexample. @@ -3207,12 +3163,12 @@ def __init__(self, text, *, created=None, updated=None): def _from_dict(cls, _dict): """Initialize a Counterexample object from a json dictionary.""" args = {} - validKeys = ['text', 'created', 'updated'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'created', 'updated'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Counterexample: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -3250,7 +3206,7 @@ def __ne__(self, other): return not self == other -class CounterexampleCollection(object): +class CounterexampleCollection(): """ CounterexampleCollection. @@ -3274,12 +3230,12 @@ def __init__(self, counterexamples, pagination): def _from_dict(cls, _dict): """Initialize a CounterexampleCollection object from a json dictionary.""" args = {} - validKeys = ['counterexamples', 'pagination'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['counterexamples', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CounterexampleCollection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'counterexamples' in _dict: args['counterexamples'] = [ Counterexample._from_dict(x) @@ -3324,7 +3280,7 @@ def __ne__(self, other): return not self == other -class CreateEntity(object): +class CreateEntity(): """ CreateEntity. @@ -3388,15 +3344,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a CreateEntity object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'entity', 'description', 'metadata', 'fuzzy_match', 'created', 'updated', 'values' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CreateEntity: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'entity' in _dict: args['entity'] = _dict.get('entity') else: @@ -3452,7 +3408,7 @@ def __ne__(self, other): return not self == other -class CreateIntent(object): +class CreateIntent(): """ CreateIntent. @@ -3504,12 +3460,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a CreateIntent object from a json dictionary.""" args = {} - validKeys = ['intent', 'description', 'created', 'updated', 'examples'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['intent', 'description', 'created', 'updated', 'examples'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CreateIntent: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'intent' in _dict: args['intent'] = _dict.get('intent') else: @@ -3557,7 +3513,7 @@ def __ne__(self, other): return not self == other -class CreateValue(object): +class CreateValue(): """ CreateValue. @@ -3628,15 +3584,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a CreateValue object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'value', 'metadata', 'type', 'synonyms', 'patterns', 'created', 'updated' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CreateValue: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'value' in _dict: args['value'] = _dict.get('value') else: @@ -3697,7 +3653,7 @@ class TypeEnum(Enum): PATTERNS = "patterns" -class DialogNode(object): +class DialogNode(): """ DialogNode. @@ -3841,18 +3797,18 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a DialogNode object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'dialog_node', 'description', 'conditions', 'parent', 'previous_sibling', 'output', 'context', 'metadata', 'next_step', 'title', 'type', 'event_name', 'variable', 'actions', 'digress_in', 'digress_out', 'digress_out_slots', 'user_label', 'disabled', 'created', 'updated' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNode: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') else: @@ -4017,7 +3973,7 @@ class DigressOutSlotsEnum(Enum): ALLOW_ALL = "allow_all" -class DialogNodeAction(object): +class DialogNodeAction(): """ DialogNodeAction. @@ -4060,14 +4016,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a DialogNodeAction object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'name', 'type', 'parameters', 'result_variable', 'credentials' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeAction: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -4128,7 +4084,7 @@ class TypeEnum(Enum): WEB_ACTION = "web_action" -class DialogNodeCollection(object): +class DialogNodeCollection(): """ An array of dialog nodes. @@ -4152,12 +4108,12 @@ def __init__(self, dialog_nodes, pagination): def _from_dict(cls, _dict): """Initialize a DialogNodeCollection object from a json dictionary.""" args = {} - validKeys = ['dialog_nodes', 'pagination'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['dialog_nodes', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeCollection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'dialog_nodes' in _dict: args['dialog_nodes'] = [ DialogNode._from_dict(x) for x in (_dict.get('dialog_nodes')) @@ -4198,7 +4154,7 @@ def __ne__(self, other): return not self == other -class DialogNodeNextStep(object): +class DialogNodeNextStep(): """ The next step to execute following this dialog node. @@ -4266,12 +4222,12 @@ def __init__(self, behavior, *, dialog_node=None, selector=None): def _from_dict(cls, _dict): """Initialize a DialogNodeNextStep object from a json dictionary.""" args = {} - validKeys = ['behavior', 'dialog_node', 'selector'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['behavior', 'dialog_node', 'selector'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeNextStep: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'behavior' in _dict: args['behavior'] = _dict.get('behavior') else: @@ -4350,7 +4306,7 @@ class SelectorEnum(Enum): BODY = "body" -class DialogNodeOutput(object): +class DialogNodeOutput(): """ The output of the dialog node. For more information about how to specify dialog node output, see the @@ -4433,7 +4389,7 @@ def __ne__(self, other): return not self == other -class DialogNodeOutputGeneric(object): +class DialogNodeOutputGeneric(): """ DialogNodeOutputGeneric. @@ -4572,17 +4528,17 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a DialogNodeOutputGeneric object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'response_type', 'values', 'selection_policy', 'delimiter', 'time', 'typing', 'source', 'title', 'description', 'preference', 'options', 'message_to_human_agent', 'query', 'query_type', 'filter', 'discovery_version' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeOutputGeneric: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -4720,7 +4676,7 @@ class QueryTypeEnum(Enum): DISCOVERY_QUERY_LANGUAGE = "discovery_query_language" -class DialogNodeOutputModifiers(object): +class DialogNodeOutputModifiers(): """ Options that modify how specified output is handled. @@ -4745,12 +4701,12 @@ def __init__(self, *, overwrite=None): def _from_dict(cls, _dict): """Initialize a DialogNodeOutputModifiers object from a json dictionary.""" args = {} - validKeys = ['overwrite'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['overwrite'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeOutputModifiers: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'overwrite' in _dict: args['overwrite'] = _dict.get('overwrite') return cls(**args) @@ -4777,7 +4733,7 @@ def __ne__(self, other): return not self == other -class DialogNodeOutputOptionsElement(object): +class DialogNodeOutputOptionsElement(): """ DialogNodeOutputOptionsElement. @@ -4803,12 +4759,12 @@ def __init__(self, label, value): def _from_dict(cls, _dict): """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} - validKeys = ['label', 'value'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['label', 'value'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeOutputOptionsElement: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') else: @@ -4848,7 +4804,7 @@ def __ne__(self, other): return not self == other -class DialogNodeOutputOptionsElementValue(object): +class DialogNodeOutputOptionsElementValue(): """ An object defining the message input to be sent to the Watson Assistant service if the user selects the corresponding option. @@ -4888,12 +4844,12 @@ def __init__(self, *, input=None, intents=None, entities=None): def _from_dict(cls, _dict): """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} - validKeys = ['input', 'intents', 'entities'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['input', 'intents', 'entities'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeOutputOptionsElementValue: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) if 'intents' in _dict: @@ -4932,7 +4888,7 @@ def __ne__(self, other): return not self == other -class DialogNodeOutputTextValuesElement(object): +class DialogNodeOutputTextValuesElement(): """ DialogNodeOutputTextValuesElement. @@ -4955,12 +4911,12 @@ def __init__(self, *, text=None): def _from_dict(cls, _dict): """Initialize a DialogNodeOutputTextValuesElement object from a json dictionary.""" args = {} - validKeys = ['text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeOutputTextValuesElement: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -4987,7 +4943,7 @@ def __ne__(self, other): return not self == other -class DialogNodeVisitedDetails(object): +class DialogNodeVisitedDetails(): """ DialogNodeVisitedDetails. @@ -5015,12 +4971,12 @@ def __init__(self, *, dialog_node=None, title=None, conditions=None): def _from_dict(cls, _dict): """Initialize a DialogNodeVisitedDetails object from a json dictionary.""" args = {} - validKeys = ['dialog_node', 'title', 'conditions'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['dialog_node', 'title', 'conditions'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeVisitedDetails: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') if 'title' in _dict: @@ -5055,7 +5011,7 @@ def __ne__(self, other): return not self == other -class DialogSuggestion(object): +class DialogSuggestion(): """ DialogSuggestion. @@ -5098,12 +5054,12 @@ def __init__(self, label, value, *, output=None, dialog_node=None): def _from_dict(cls, _dict): """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - validKeys = ['label', 'value', 'output', 'dialog_node'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['label', 'value', 'output', 'dialog_node'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogSuggestion: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') else: @@ -5151,7 +5107,7 @@ def __ne__(self, other): return not self == other -class DialogSuggestionOutput(object): +class DialogSuggestionOutput(): """ The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. @@ -5257,8 +5213,8 @@ def __setattr__(self, name, value): 'nodes_visited', 'nodes_visited_details', 'text', 'generic' } if not hasattr(self, '_additionalProperties'): - super(DialogSuggestionOutput, self).__setattr__( - '_additionalProperties', set()) + super(DialogSuggestionOutput, + self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(DialogSuggestionOutput, self).__setattr__(name, value) @@ -5278,7 +5234,7 @@ def __ne__(self, other): return not self == other -class DialogSuggestionResponseGeneric(object): +class DialogSuggestionResponseGeneric(): """ DialogSuggestionResponseGeneric. @@ -5370,16 +5326,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a DialogSuggestionResponseGeneric object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'response_type', 'text', 'time', 'typing', 'source', 'title', 'description', 'preference', 'options', 'message_to_human_agent', 'topic', 'dialog_node' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogSuggestionResponseGeneric: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -5481,7 +5437,7 @@ class PreferenceEnum(Enum): BUTTON = "button" -class DialogSuggestionValue(object): +class DialogSuggestionValue(): """ An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. @@ -5513,12 +5469,12 @@ def __init__(self, *, input=None, intents=None, entities=None): def _from_dict(cls, _dict): """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - validKeys = ['input', 'intents', 'entities'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['input', 'intents', 'entities'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogSuggestionValue: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) if 'intents' in _dict: @@ -5557,7 +5513,7 @@ def __ne__(self, other): return not self == other -class Entity(object): +class Entity(): """ Entity. @@ -5621,15 +5577,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Entity object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'entity', 'description', 'metadata', 'fuzzy_match', 'created', 'updated', 'values' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Entity: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'entity' in _dict: args['entity'] = _dict.get('entity') else: @@ -5685,7 +5641,7 @@ def __ne__(self, other): return not self == other -class EntityCollection(object): +class EntityCollection(): """ An array of objects describing the entities for the workspace. @@ -5709,12 +5665,12 @@ def __init__(self, entities, pagination): def _from_dict(cls, _dict): """Initialize a EntityCollection object from a json dictionary.""" args = {} - validKeys = ['entities', 'pagination'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['entities', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EntityCollection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'entities' in _dict: args['entities'] = [ Entity._from_dict(x) for x in (_dict.get('entities')) @@ -5755,7 +5711,7 @@ def __ne__(self, other): return not self == other -class EntityMention(object): +class EntityMention(): """ An object describing a contextual entity mention. @@ -5782,12 +5738,12 @@ def __init__(self, text, intent, location): def _from_dict(cls, _dict): """Initialize a EntityMention object from a json dictionary.""" args = {} - validKeys = ['text', 'intent', 'location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'intent', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EntityMention: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -5833,7 +5789,7 @@ def __ne__(self, other): return not self == other -class EntityMentionCollection(object): +class EntityMentionCollection(): """ EntityMentionCollection. @@ -5857,12 +5813,12 @@ def __init__(self, examples, pagination): def _from_dict(cls, _dict): """Initialize a EntityMentionCollection object from a json dictionary.""" args = {} - validKeys = ['examples', 'pagination'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['examples', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EntityMentionCollection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'examples' in _dict: args['examples'] = [ EntityMention._from_dict(x) for x in (_dict.get('examples')) @@ -5903,7 +5859,7 @@ def __ne__(self, other): return not self == other -class Example(object): +class Example(): """ Example. @@ -5941,12 +5897,12 @@ def __init__(self, text, *, mentions=None, created=None, updated=None): def _from_dict(cls, _dict): """Initialize a Example object from a json dictionary.""" args = {} - validKeys = ['text', 'mentions', 'created', 'updated'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'mentions', 'created', 'updated'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Example: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -5990,7 +5946,7 @@ def __ne__(self, other): return not self == other -class ExampleCollection(object): +class ExampleCollection(): """ ExampleCollection. @@ -6014,12 +5970,12 @@ def __init__(self, examples, pagination): def _from_dict(cls, _dict): """Initialize a ExampleCollection object from a json dictionary.""" args = {} - validKeys = ['examples', 'pagination'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['examples', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ExampleCollection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'examples' in _dict: args['examples'] = [ Example._from_dict(x) for x in (_dict.get('examples')) @@ -6060,7 +6016,7 @@ def __ne__(self, other): return not self == other -class Intent(object): +class Intent(): """ Intent. @@ -6112,12 +6068,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Intent object from a json dictionary.""" args = {} - validKeys = ['intent', 'description', 'created', 'updated', 'examples'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['intent', 'description', 'created', 'updated', 'examples'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Intent: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'intent' in _dict: args['intent'] = _dict.get('intent') else: @@ -6165,7 +6121,7 @@ def __ne__(self, other): return not self == other -class IntentCollection(object): +class IntentCollection(): """ IntentCollection. @@ -6189,12 +6145,12 @@ def __init__(self, intents, pagination): def _from_dict(cls, _dict): """Initialize a IntentCollection object from a json dictionary.""" args = {} - validKeys = ['intents', 'pagination'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['intents', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class IntentCollection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'intents' in _dict: args['intents'] = [ Intent._from_dict(x) for x in (_dict.get('intents')) @@ -6235,7 +6191,7 @@ def __ne__(self, other): return not self == other -class Log(object): +class Log(): """ Log. @@ -6283,15 +6239,15 @@ def __init__(self, request, response, log_id, request_timestamp, def _from_dict(cls, _dict): """Initialize a Log object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'request', 'response', 'log_id', 'request_timestamp', 'response_timestamp', 'workspace_id', 'language' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Log: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'request' in _dict: args['request'] = MessageRequest._from_dict(_dict.get('request')) else: @@ -6368,7 +6324,7 @@ def __ne__(self, other): return not self == other -class LogCollection(object): +class LogCollection(): """ LogCollection. @@ -6391,12 +6347,12 @@ def __init__(self, logs, pagination): def _from_dict(cls, _dict): """Initialize a LogCollection object from a json dictionary.""" args = {} - validKeys = ['logs', 'pagination'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['logs', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class LogCollection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'logs' in _dict: args['logs'] = [Log._from_dict(x) for x in (_dict.get('logs'))] else: @@ -6435,7 +6391,7 @@ def __ne__(self, other): return not self == other -class LogMessage(object): +class LogMessage(): """ Log message details. @@ -6457,12 +6413,12 @@ def __init__(self, level, msg): def _from_dict(cls, _dict): """Initialize a LogMessage object from a json dictionary.""" args = {} - validKeys = ['level', 'msg'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['level', 'msg'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class LogMessage: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'level' in _dict: args['level'] = _dict.get('level') else: @@ -6507,7 +6463,7 @@ class LevelEnum(Enum): WARN = "warn" -class LogPagination(object): +class LogPagination(): """ The pagination data for the returned objects. @@ -6535,12 +6491,12 @@ def __init__(self, *, next_url=None, matched=None, next_cursor=None): def _from_dict(cls, _dict): """Initialize a LogPagination object from a json dictionary.""" args = {} - validKeys = ['next_url', 'matched', 'next_cursor'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['next_url', 'matched', 'next_cursor'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class LogPagination: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'next_url' in _dict: args['next_url'] = _dict.get('next_url') if 'matched' in _dict: @@ -6575,7 +6531,7 @@ def __ne__(self, other): return not self == other -class Mention(object): +class Mention(): """ A mention of a contextual entity. @@ -6599,12 +6555,12 @@ def __init__(self, entity, location): def _from_dict(cls, _dict): """Initialize a Mention object from a json dictionary.""" args = {} - validKeys = ['entity', 'location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['entity', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Mention: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'entity' in _dict: args['entity'] = _dict.get('entity') else: @@ -6641,7 +6597,7 @@ def __ne__(self, other): return not self == other -class MessageContextMetadata(object): +class MessageContextMetadata(): """ Metadata related to the message. @@ -6676,12 +6632,12 @@ def __init__(self, *, deployment=None, user_id=None): def _from_dict(cls, _dict): """Initialize a MessageContextMetadata object from a json dictionary.""" args = {} - validKeys = ['deployment', 'user_id'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['deployment', 'user_id'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageContextMetadata: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'deployment' in _dict: args['deployment'] = _dict.get('deployment') if 'user_id' in _dict: @@ -6712,7 +6668,7 @@ def __ne__(self, other): return not self == other -class MessageInput(object): +class MessageInput(): """ An input object that includes the input text. @@ -6779,7 +6735,7 @@ def __ne__(self, other): return not self == other -class MessageRequest(object): +class MessageRequest(): """ A request sent to the workspace, including the user input and context. @@ -6845,15 +6801,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a MessageRequest object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'input', 'intents', 'entities', 'alternate_intents', 'context', 'output', 'actions' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageRequest: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) if 'intents' in _dict: @@ -6911,7 +6867,7 @@ def __ne__(self, other): return not self == other -class MessageResponse(object): +class MessageResponse(): """ The response sent by the workspace, including the output text, detected intents and entities, and context. @@ -6969,15 +6925,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a MessageResponse object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'input', 'intents', 'entities', 'alternate_intents', 'context', 'output', 'actions' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) else: @@ -7055,7 +7011,7 @@ def __ne__(self, other): return not self == other -class OutputData(object): +class OutputData(): """ An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. @@ -7198,7 +7154,7 @@ def __ne__(self, other): return not self == other -class Pagination(object): +class Pagination(): """ The pagination data for the returned objects. @@ -7244,15 +7200,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Pagination object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'refresh_url', 'next_url', 'total', 'matched', 'refresh_cursor', 'next_cursor' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Pagination: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'refresh_url' in _dict: args['refresh_url'] = _dict.get('refresh_url') else: @@ -7303,7 +7259,7 @@ def __ne__(self, other): return not self == other -class RuntimeEntity(object): +class RuntimeEntity(): """ A term from the request that was identified as an entity. @@ -7350,14 +7306,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a RuntimeEntity object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'entity', 'location', 'value', 'confidence', 'metadata', 'groups' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RuntimeEntity: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'entity' in _dict: args['entity'] = _dict.get('entity') else: @@ -7417,7 +7373,7 @@ def __ne__(self, other): return not self == other -class RuntimeIntent(object): +class RuntimeIntent(): """ An intent identified in the user input. @@ -7441,12 +7397,12 @@ def __init__(self, intent, confidence): def _from_dict(cls, _dict): """Initialize a RuntimeIntent object from a json dictionary.""" args = {} - validKeys = ['intent', 'confidence'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['intent', 'confidence'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RuntimeIntent: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'intent' in _dict: args['intent'] = _dict.get('intent') else: @@ -7485,7 +7441,7 @@ def __ne__(self, other): return not self == other -class RuntimeResponseGeneric(object): +class RuntimeResponseGeneric(): """ RuntimeResponseGeneric. @@ -7584,16 +7540,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a RuntimeResponseGeneric object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'response_type', 'text', 'time', 'typing', 'source', 'title', 'description', 'preference', 'options', 'message_to_human_agent', 'topic', 'dialog_node', 'suggestions' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RuntimeResponseGeneric: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -7700,7 +7656,7 @@ class PreferenceEnum(Enum): BUTTON = "button" -class Synonym(object): +class Synonym(): """ Synonym. @@ -7734,12 +7690,12 @@ def __init__(self, synonym, *, created=None, updated=None): def _from_dict(cls, _dict): """Initialize a Synonym object from a json dictionary.""" args = {} - validKeys = ['synonym', 'created', 'updated'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['synonym', 'created', 'updated'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Synonym: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'synonym' in _dict: args['synonym'] = _dict.get('synonym') else: @@ -7777,7 +7733,7 @@ def __ne__(self, other): return not self == other -class SynonymCollection(object): +class SynonymCollection(): """ SynonymCollection. @@ -7799,12 +7755,12 @@ def __init__(self, synonyms, pagination): def _from_dict(cls, _dict): """Initialize a SynonymCollection object from a json dictionary.""" args = {} - validKeys = ['synonyms', 'pagination'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['synonyms', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SynonymCollection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'synonyms' in _dict: args['synonyms'] = [ Synonym._from_dict(x) for x in (_dict.get('synonyms')) @@ -7845,7 +7801,7 @@ def __ne__(self, other): return not self == other -class SystemResponse(object): +class SystemResponse(): """ For internal use only. @@ -7902,7 +7858,7 @@ def __ne__(self, other): return not self == other -class Value(object): +class Value(): """ Value. @@ -7973,15 +7929,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Value object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'value', 'metadata', 'type', 'synonyms', 'patterns', 'created', 'updated' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Value: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'value' in _dict: args['value'] = _dict.get('value') else: @@ -8045,7 +8001,7 @@ class TypeEnum(Enum): PATTERNS = "patterns" -class ValueCollection(object): +class ValueCollection(): """ ValueCollection. @@ -8067,12 +8023,12 @@ def __init__(self, values, pagination): def _from_dict(cls, _dict): """Initialize a ValueCollection object from a json dictionary.""" args = {} - validKeys = ['values', 'pagination'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['values', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ValueCollection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'values' in _dict: args['values'] = [ Value._from_dict(x) for x in (_dict.get('values')) @@ -8113,7 +8069,7 @@ def __ne__(self, other): return not self == other -class Workspace(object): +class Workspace(): """ Workspace. @@ -8206,16 +8162,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Workspace object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'name', 'description', 'language', 'metadata', 'learning_opt_out', 'system_settings', 'workspace_id', 'status', 'created', 'updated', 'intents', 'entities', 'dialog_nodes', 'counterexamples' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Workspace: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -8333,7 +8289,7 @@ class StatusEnum(Enum): UNAVAILABLE = "Unavailable" -class WorkspaceCollection(object): +class WorkspaceCollection(): """ WorkspaceCollection. @@ -8357,12 +8313,12 @@ def __init__(self, workspaces, pagination): def _from_dict(cls, _dict): """Initialize a WorkspaceCollection object from a json dictionary.""" args = {} - validKeys = ['workspaces', 'pagination'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['workspaces', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class WorkspaceCollection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'workspaces' in _dict: args['workspaces'] = [ Workspace._from_dict(x) for x in (_dict.get('workspaces')) @@ -8403,7 +8359,7 @@ def __ne__(self, other): return not self == other -class WorkspaceSystemSettings(object): +class WorkspaceSystemSettings(): """ Global settings for the workspace. @@ -8438,12 +8394,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a WorkspaceSystemSettings object from a json dictionary.""" args = {} - validKeys = ['tooling', 'disambiguation', 'human_agent_assist'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['tooling', 'disambiguation', 'human_agent_assist'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettings: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'tooling' in _dict: args['tooling'] = WorkspaceSystemSettingsTooling._from_dict( _dict.get('tooling')) @@ -8483,7 +8439,7 @@ def __ne__(self, other): return not self == other -class WorkspaceSystemSettingsDisambiguation(object): +class WorkspaceSystemSettingsDisambiguation(): """ Workspace settings related to the disambiguation feature. **Note:** This feature is available only to Premium users. @@ -8531,14 +8487,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'prompt', 'none_of_the_above_prompt', 'enabled', 'sensitivity' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsDisambiguation: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'prompt' in _dict: args['prompt'] = _dict.get('prompt') if 'none_of_the_above_prompt' in _dict: @@ -8588,7 +8544,7 @@ class SensitivityEnum(Enum): HIGH = "high" -class WorkspaceSystemSettingsTooling(object): +class WorkspaceSystemSettingsTooling(): """ Workspace settings related to the Watson Assistant user interface. @@ -8609,12 +8565,12 @@ def __init__(self, *, store_generic_responses=None): def _from_dict(cls, _dict): """Initialize a WorkspaceSystemSettingsTooling object from a json dictionary.""" args = {} - validKeys = ['store_generic_responses'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['store_generic_responses'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsTooling: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'store_generic_responses' in _dict: args['store_generic_responses'] = _dict.get( 'store_generic_responses') diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 54644c79b..4bc1ea9f7 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -24,6 +24,7 @@ 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 read_external_sources ############################################################################## # Service @@ -33,14 +34,12 @@ class AssistantV2(BaseService): """The Assistant V2 service.""" - default_url = 'https://gateway.watsonplatform.net/assistant/api' + default_service_url = 'https://gateway.watsonplatform.net/assistant/api' def __init__( self, version, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Assistant service. @@ -56,25 +55,27 @@ def __init__( application, and don't change it until your application is ready for a later version. - :param str url: The base url to use when contacting the service (e.g. - "https://gateway.watsonplatform.net/assistant/api/assistant/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('assistant') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: - authenticator = get_authenticator_from_environment('Assistant') + authenticator = get_authenticator_from_environment('assistant') - BaseService.__init__( - self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Assistant') + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) self.version = version ######################### @@ -112,12 +113,11 @@ def create_session(self, assistant_id, **kwargs): url = '/v2/assistants/{0}/sessions'.format( *self._encode_path_vars(assistant_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -154,12 +154,11 @@ def delete_session(self, assistant_id, session_id, **kwargs): url = '/v2/assistants/{0}/sessions/{1}'.format( *self._encode_path_vars(assistant_id, session_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -219,13 +218,12 @@ def message(self, url = '/v2/assistants/{0}/sessions/{1}/message'.format( *self._encode_path_vars(assistant_id, session_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -235,7 +233,7 @@ def message(self, ############################################################################## -class CaptureGroup(object): +class CaptureGroup(): """ CaptureGroup. @@ -259,12 +257,12 @@ def __init__(self, group, *, location=None): def _from_dict(cls, _dict): """Initialize a CaptureGroup object from a json dictionary.""" args = {} - validKeys = ['group', 'location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['group', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CaptureGroup: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'group' in _dict: args['group'] = _dict.get('group') else: @@ -298,7 +296,7 @@ def __ne__(self, other): return not self == other -class DialogLogMessage(object): +class DialogLogMessage(): """ Dialog log message details. @@ -320,12 +318,12 @@ def __init__(self, level, message): def _from_dict(cls, _dict): """Initialize a DialogLogMessage object from a json dictionary.""" args = {} - validKeys = ['level', 'message'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['level', 'message'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogLogMessage: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'level' in _dict: args['level'] = _dict.get('level') else: @@ -372,7 +370,7 @@ class LevelEnum(Enum): WARN = "warn" -class DialogNodeAction(object): +class DialogNodeAction(): """ DialogNodeAction. @@ -415,14 +413,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a DialogNodeAction object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'name', 'type', 'parameters', 'result_variable', 'credentials' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeAction: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -483,7 +481,7 @@ class TypeEnum(Enum): CLOUD_FUNCTION = "cloud-function" -class DialogNodeOutputOptionsElement(object): +class DialogNodeOutputOptionsElement(): """ DialogNodeOutputOptionsElement. @@ -508,12 +506,12 @@ def __init__(self, label, value): def _from_dict(cls, _dict): """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} - validKeys = ['label', 'value'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['label', 'value'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeOutputOptionsElement: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') else: @@ -553,7 +551,7 @@ def __ne__(self, other): return not self == other -class DialogNodeOutputOptionsElementValue(object): +class DialogNodeOutputOptionsElementValue(): """ An object defining the message input to be sent to the assistant if the user selects the corresponding option. @@ -575,12 +573,12 @@ def __init__(self, *, input=None): def _from_dict(cls, _dict): """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} - validKeys = ['input'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['input'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodeOutputOptionsElementValue: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) return cls(**args) @@ -607,7 +605,7 @@ def __ne__(self, other): return not self == other -class DialogNodesVisited(object): +class DialogNodesVisited(): """ DialogNodesVisited. @@ -635,12 +633,12 @@ def __init__(self, *, dialog_node=None, title=None, conditions=None): def _from_dict(cls, _dict): """Initialize a DialogNodesVisited object from a json dictionary.""" args = {} - validKeys = ['dialog_node', 'title', 'conditions'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['dialog_node', 'title', 'conditions'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogNodesVisited: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') if 'title' in _dict: @@ -675,7 +673,7 @@ def __ne__(self, other): return not self == other -class DialogSuggestion(object): +class DialogSuggestion(): """ DialogSuggestion. @@ -709,12 +707,12 @@ def __init__(self, label, value, *, output=None): def _from_dict(cls, _dict): """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - validKeys = ['label', 'value', 'output'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['label', 'value', 'output'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogSuggestion: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') else: @@ -757,7 +755,7 @@ def __ne__(self, other): return not self == other -class DialogSuggestionValue(object): +class DialogSuggestionValue(): """ An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. @@ -779,12 +777,12 @@ def __init__(self, *, input=None): def _from_dict(cls, _dict): """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - validKeys = ['input'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['input'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DialogSuggestionValue: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'input' in _dict: args['input'] = MessageInput._from_dict(_dict.get('input')) return cls(**args) @@ -811,7 +809,7 @@ def __ne__(self, other): return not self == other -class MessageContext(object): +class MessageContext(): """ MessageContext. @@ -843,12 +841,12 @@ def __init__(self, *, global_=None, skills=None): def _from_dict(cls, _dict): """Initialize a MessageContext object from a json dictionary.""" args = {} - validKeys = ['global_', 'global', 'skills'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['global_', 'global', 'skills'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageContext: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'global' in _dict: args['global_'] = MessageContextGlobal._from_dict( _dict.get('global')) @@ -881,7 +879,7 @@ def __ne__(self, other): return not self == other -class MessageContextGlobal(object): +class MessageContextGlobal(): """ Information that is shared by all skills used by the Assistant. @@ -902,12 +900,12 @@ def __init__(self, *, system=None): def _from_dict(cls, _dict): """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} - validKeys = ['system'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['system'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageContextGlobal: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'system' in _dict: args['system'] = MessageContextGlobalSystem._from_dict( _dict.get('system')) @@ -935,7 +933,7 @@ def __ne__(self, other): return not self == other -class MessageContextGlobalSystem(object): +class MessageContextGlobalSystem(): """ Built-in system properties that apply to all skills used by the assistant. @@ -978,12 +976,12 @@ def __init__(self, *, timezone=None, user_id=None, turn_count=None): def _from_dict(cls, _dict): """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} - validKeys = ['timezone', 'user_id', 'turn_count'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['timezone', 'user_id', 'turn_count'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageContextGlobalSystem: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'timezone' in _dict: args['timezone'] = _dict.get('timezone') if 'user_id' in _dict: @@ -1018,7 +1016,7 @@ def __ne__(self, other): return not self == other -class MessageContextSkill(object): +class MessageContextSkill(): """ Contains information specific to a particular skill used by the Assistant. @@ -1039,12 +1037,12 @@ def __init__(self, *, user_defined=None): def _from_dict(cls, _dict): """Initialize a MessageContextSkill object from a json dictionary.""" args = {} - validKeys = ['user_defined'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['user_defined'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageContextSkill: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') return cls(**args) @@ -1071,7 +1069,7 @@ def __ne__(self, other): return not self == other -class MessageContextSkills(object): +class MessageContextSkills(): """ Information specific to particular skills used by the Assistant. **Note:** Currently, only a single property named `main skill` is supported. This @@ -1109,8 +1107,8 @@ def _to_dict(self): def __setattr__(self, name, value): properties = {} if not hasattr(self, '_additionalProperties'): - super(MessageContextSkills, self).__setattr__( - '_additionalProperties', set()) + super(MessageContextSkills, + self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(MessageContextSkills, self).__setattr__(name, value) @@ -1130,7 +1128,7 @@ def __ne__(self, other): return not self == other -class MessageInput(object): +class MessageInput(): """ An input object that includes the input text. @@ -1187,15 +1185,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a MessageInput object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'message_type', 'text', 'options', 'intents', 'entities', 'suggestion_id' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageInput: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'message_type' in _dict: args['message_type'] = _dict.get('message_type') if 'text' in _dict: @@ -1253,7 +1251,7 @@ class MessageTypeEnum(Enum): TEXT = "text" -class MessageInputOptions(object): +class MessageInputOptions(): """ Optional properties that control how the assistant responds. @@ -1300,12 +1298,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a MessageInputOptions object from a json dictionary.""" args = {} - validKeys = ['debug', 'restart', 'alternate_intents', 'return_context'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['debug', 'restart', 'alternate_intents', 'return_context'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageInputOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'debug' in _dict: args['debug'] = _dict.get('debug') if 'restart' in _dict: @@ -1345,7 +1343,7 @@ def __ne__(self, other): return not self == other -class MessageOutput(object): +class MessageOutput(): """ Assistant output to be rendered or processed by the client. @@ -1403,14 +1401,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a MessageOutput object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'generic', 'intents', 'entities', 'actions', 'debug', 'user_defined' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageOutput: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'generic' in _dict: args['generic'] = [ RuntimeResponseGeneric._from_dict(x) @@ -1466,7 +1464,7 @@ def __ne__(self, other): return not self == other -class MessageOutputDebug(object): +class MessageOutputDebug(): """ Additional detailed information about a message response and how it was generated. @@ -1511,15 +1509,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a MessageOutputDebug object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'nodes_visited', 'log_messages', 'branch_exited', 'branch_exited_reason' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageOutputDebug: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'nodes_visited' in _dict: args['nodes_visited'] = [ DialogNodesVisited._from_dict(x) @@ -1573,7 +1571,7 @@ class BranchExitedReasonEnum(Enum): FALLBACK = "fallback" -class MessageResponse(object): +class MessageResponse(): """ A response from the Watson Assistant service. @@ -1605,12 +1603,12 @@ def __init__(self, output, *, context=None): def _from_dict(cls, _dict): """Initialize a MessageResponse object from a json dictionary.""" args = {} - validKeys = ['output', 'context'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['output', 'context'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'output' in _dict: args['output'] = MessageOutput._from_dict(_dict.get('output')) else: @@ -1645,7 +1643,7 @@ def __ne__(self, other): return not self == other -class RuntimeEntity(object): +class RuntimeEntity(): """ The entity value that was recognized in the user input. @@ -1694,14 +1692,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a RuntimeEntity object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'entity', 'location', 'value', 'confidence', 'metadata', 'groups' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RuntimeEntity: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'entity' in _dict: args['entity'] = _dict.get('entity') else: @@ -1761,7 +1759,7 @@ def __ne__(self, other): return not self == other -class RuntimeIntent(object): +class RuntimeIntent(): """ An intent identified in the user input. @@ -1785,12 +1783,12 @@ def __init__(self, intent, confidence): def _from_dict(cls, _dict): """Initialize a RuntimeIntent object from a json dictionary.""" args = {} - validKeys = ['intent', 'confidence'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['intent', 'confidence'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RuntimeIntent: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'intent' in _dict: args['intent'] = _dict.get('intent') else: @@ -1829,7 +1827,7 @@ def __ne__(self, other): return not self == other -class RuntimeResponseGeneric(object): +class RuntimeResponseGeneric(): """ RuntimeResponseGeneric. @@ -1932,16 +1930,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a RuntimeResponseGeneric object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'response_type', 'text', 'time', 'typing', 'source', 'title', 'description', 'preference', 'options', 'message_to_human_agent', 'topic', 'suggestions', 'header', 'results' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RuntimeResponseGeneric: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -2055,7 +2053,7 @@ class PreferenceEnum(Enum): BUTTON = "button" -class SearchResult(object): +class SearchResult(): """ SearchResult. @@ -2118,14 +2116,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SearchResult object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'id', 'result_metadata', 'body', 'title', 'url', 'highlight' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SearchResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'id' in _dict: args['id'] = _dict.get('id') else: @@ -2182,7 +2180,7 @@ def __ne__(self, other): return not self == other -class SearchResultHighlight(object): +class SearchResultHighlight(): """ An object containing segments of text from search results with query-matching text highlighted using HTML tags. @@ -2254,8 +2252,8 @@ def _to_dict(self): def __setattr__(self, name, value): properties = {'body', 'title', 'url'} if not hasattr(self, '_additionalProperties'): - super(SearchResultHighlight, self).__setattr__( - '_additionalProperties', set()) + super(SearchResultHighlight, + self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(SearchResultHighlight, self).__setattr__(name, value) @@ -2275,7 +2273,7 @@ def __ne__(self, other): return not self == other -class SearchResultMetadata(object): +class SearchResultMetadata(): """ An object containing search result metadata from the Discovery service. @@ -2305,12 +2303,12 @@ def __init__(self, *, confidence=None, score=None): def _from_dict(cls, _dict): """Initialize a SearchResultMetadata object from a json dictionary.""" args = {} - validKeys = ['confidence', 'score'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['confidence', 'score'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SearchResultMetadata: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') if 'score' in _dict: @@ -2341,7 +2339,7 @@ def __ne__(self, other): return not self == other -class SessionResponse(object): +class SessionResponse(): """ SessionResponse. @@ -2360,12 +2358,12 @@ def __init__(self, session_id): def _from_dict(cls, _dict): """Initialize a SessionResponse object from a json dictionary.""" args = {} - validKeys = ['session_id'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['session_id'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SessionResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'session_id' in _dict: args['session_id'] = _dict.get('session_id') else: diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 599f1ce62..9b45d0840 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -24,6 +24,7 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources ############################################################################## # Service @@ -33,14 +34,12 @@ class CompareComplyV1(BaseService): """The Compare Comply V1 service.""" - default_url = 'https://gateway.watsonplatform.net/compare-comply/api' + default_service_url = 'https://gateway.watsonplatform.net/compare-comply/api' def __init__( self, version, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Compare Comply service. @@ -56,25 +55,27 @@ def __init__( application, and don't change it until your application is ready for a later version. - :param str url: The base url to use when contacting the service (e.g. - "https://gateway.watsonplatform.net/compare-comply/api/compare-comply/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('compare_comply') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: - authenticator = get_authenticator_from_environment('Compare Comply') + authenticator = get_authenticator_from_environment('compare_comply') - BaseService.__init__( - self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Compare Comply') + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) self.version = version ######################### @@ -115,18 +116,17 @@ def convert_to_html(self, params = {'version': self.version, 'model': model} - form_data = {} - form_data['file'] = (None, file, file_content_type or - 'application/octet-stream') + form_data = [] + form_data.append(('file', (None, file, file_content_type or + 'application/octet-stream'))) url = '/v1/html_conversion' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -169,18 +169,17 @@ def classify_elements(self, params = {'version': self.version, 'model': model} - form_data = {} - form_data['file'] = (None, file, file_content_type or - 'application/octet-stream') + form_data = [] + form_data.append(('file', (None, file, file_content_type or + 'application/octet-stream'))) url = '/v1/element_classification' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -222,18 +221,17 @@ def extract_tables(self, params = {'version': self.version, 'model': model} - form_data = {} - form_data['file'] = (None, file, file_content_type or - 'application/octet-stream') + form_data = [] + form_data.append(('file', (None, file, file_content_type or + 'application/octet-stream'))) url = '/v1/tables' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -291,20 +289,19 @@ def compare_documents(self, 'model': model } - form_data = {} - form_data['file_1'] = (None, file_1, file_1_content_type or - 'application/octet-stream') - form_data['file_2'] = (None, file_2, file_2_content_type or - 'application/octet-stream') + form_data = [] + form_data.append(('file_1', (None, file_1, file_1_content_type or + 'application/octet-stream'))) + form_data.append(('file_2', (None, file_2, file_2_content_type or + 'application/octet-stream'))) url = '/v1/comparison' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -355,13 +352,12 @@ def add_feedback(self, } url = '/v1/feedback' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -475,12 +471,11 @@ def list_feedback(self, } url = '/v1/feedback' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -514,12 +509,11 @@ def get_feedback(self, feedback_id, *, model=None, **kwargs): params = {'version': self.version, 'model': model} url = '/v1/feedback/{0}'.format(*self._encode_path_vars(feedback_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -553,12 +547,11 @@ def delete_feedback(self, feedback_id, *, model=None, **kwargs): params = {'version': self.version, 'model': model} url = '/v1/feedback/{0}'.format(*self._encode_path_vars(feedback_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -641,27 +634,27 @@ def create_batch(self, params = {'version': self.version, 'function': function, 'model': model} - form_data = {} - form_data['input_credentials_file'] = (None, input_credentials_file, - 'application/json') - form_data['input_bucket_location'] = (None, input_bucket_location, - 'text/plain') - form_data['input_bucket_name'] = (None, input_bucket_name, 'text/plain') - form_data['output_credentials_file'] = (None, output_credentials_file, - 'application/json') - form_data['output_bucket_location'] = (None, output_bucket_location, - 'text/plain') - form_data['output_bucket_name'] = (None, output_bucket_name, - 'text/plain') + form_data = [] + form_data.append(('input_credentials_file', + (None, input_credentials_file, 'application/json'))) + form_data.append(('input_bucket_location', (None, input_bucket_location, + 'text/plain'))) + form_data.append( + ('input_bucket_name', (None, input_bucket_name, 'text/plain'))) + form_data.append(('output_credentials_file', + (None, output_credentials_file, 'application/json'))) + form_data.append(('output_bucket_location', + (None, output_bucket_location, 'text/plain'))) + form_data.append( + ('output_bucket_name', (None, output_bucket_name, 'text/plain'))) url = '/v1/batches' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -685,12 +678,11 @@ def list_batches(self, **kwargs): params = {'version': self.version} url = '/v1/batches' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -719,12 +711,11 @@ def get_batch(self, batch_id, **kwargs): params = {'version': self.version} url = '/v1/batches/{0}'.format(*self._encode_path_vars(batch_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -762,12 +753,11 @@ def update_batch(self, batch_id, action, *, model=None, **kwargs): params = {'version': self.version, 'action': action, 'model': model} url = '/v1/batches/{0}'.format(*self._encode_path_vars(batch_id)) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -965,7 +955,7 @@ class Model(Enum): ############################################################################## -class Address(object): +class Address(): """ A party's address. @@ -991,12 +981,12 @@ def __init__(self, *, text=None, location=None): def _from_dict(cls, _dict): """Initialize a Address object from a json dictionary.""" args = {} - validKeys = ['text', 'location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Address: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: @@ -1027,7 +1017,7 @@ def __ne__(self, other): return not self == other -class AlignedElement(object): +class AlignedElement(): """ AlignedElement. @@ -1073,15 +1063,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a AlignedElement object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'element_pair', 'identical_text', 'provenance_ids', 'significant_elements' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AlignedElement: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'element_pair' in _dict: args['element_pair'] = [ ElementPair._from_dict(x) for x in (_dict.get('element_pair')) @@ -1123,7 +1113,7 @@ def __ne__(self, other): return not self == other -class Attribute(object): +class Attribute(): """ List of document attributes. @@ -1152,12 +1142,12 @@ def __init__(self, *, type=None, text=None, location=None): def _from_dict(cls, _dict): """Initialize a Attribute object from a json dictionary.""" args = {} - validKeys = ['type', 'text', 'location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['type', 'text', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Attribute: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'text' in _dict: @@ -1206,7 +1196,7 @@ class TypeEnum(Enum): PERSON = "Person" -class BatchStatus(object): +class BatchStatus(): """ The batch-request status. @@ -1281,16 +1271,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a BatchStatus object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'function', 'input_bucket_location', 'input_bucket_name', 'output_bucket_location', 'output_bucket_name', 'batch_id', 'document_counts', 'status', 'created', 'updated' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class BatchStatus: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'function' in _dict: args['function'] = _dict.get('function') if 'input_bucket_location' in _dict: @@ -1369,7 +1359,7 @@ class FunctionEnum(Enum): TABLES = "tables" -class Batches(object): +class Batches(): """ The results of a successful **List Batches** request. @@ -1390,12 +1380,12 @@ def __init__(self, *, batches=None): def _from_dict(cls, _dict): """Initialize a Batches object from a json dictionary.""" args = {} - validKeys = ['batches'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['batches'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Batches: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'batches' in _dict: args['batches'] = [ BatchStatus._from_dict(x) for x in (_dict.get('batches')) @@ -1424,7 +1414,7 @@ def __ne__(self, other): return not self == other -class BodyCells(object): +class BodyCells(): """ Cells that are not table header, column header, or row header cells. @@ -1530,18 +1520,18 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a BodyCells object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'cell_id', 'location', 'text', 'row_index_begin', 'row_index_end', 'column_index_begin', 'column_index_end', 'row_header_ids', 'row_header_texts', 'row_header_texts_normalized', 'column_header_ids', 'column_header_texts', 'column_header_texts_normalized', 'attributes' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class BodyCells: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: @@ -1636,7 +1626,7 @@ def __ne__(self, other): return not self == other -class Category(object): +class Category(): """ Information defining an element's subject matter. @@ -1660,12 +1650,12 @@ def __init__(self, *, label=None, provenance_ids=None): def _from_dict(cls, _dict): """Initialize a Category object from a json dictionary.""" args = {} - validKeys = ['label', 'provenance_ids'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['label', 'provenance_ids'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Category: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') if 'provenance_ids' in _dict: @@ -1726,7 +1716,7 @@ class LabelEnum(Enum): WARRANTIES = "Warranties" -class CategoryComparison(object): +class CategoryComparison(): """ Information defining an element's subject matter. @@ -1745,12 +1735,12 @@ def __init__(self, *, label=None): def _from_dict(cls, _dict): """Initialize a CategoryComparison object from a json dictionary.""" args = {} - validKeys = ['label'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['label'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CategoryComparison: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') return cls(**args) @@ -1807,7 +1797,7 @@ class LabelEnum(Enum): WARRANTIES = "Warranties" -class ClassifyReturn(object): +class ClassifyReturn(): """ The analysis of objects returned by the **Element classification** method. @@ -1911,17 +1901,17 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a ClassifyReturn object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'document', 'model_id', 'model_version', 'elements', 'effective_dates', 'contract_amounts', 'termination_dates', 'contract_types', 'contract_terms', 'payment_terms', 'contract_currencies', 'tables', 'document_structure', 'parties' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ClassifyReturn: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = Document._from_dict(_dict.get('document')) if 'model_id' in _dict: @@ -2046,7 +2036,7 @@ def __ne__(self, other): return not self == other -class ColumnHeaders(object): +class ColumnHeaders(): """ Column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. @@ -2115,15 +2105,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a ColumnHeaders object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'cell_id', 'location', 'text', 'text_normalized', 'row_index_begin', 'row_index_end', 'column_index_begin', 'column_index_end' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ColumnHeaders: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: @@ -2183,7 +2173,7 @@ def __ne__(self, other): return not self == other -class CompareReturn(object): +class CompareReturn(): """ The comparison of the two submitted documents. @@ -2232,15 +2222,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a CompareReturn object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'model_id', 'model_version', 'documents', 'aligned_elements', 'unaligned_elements' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CompareReturn: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: @@ -2298,7 +2288,7 @@ def __ne__(self, other): return not self == other -class Contact(object): +class Contact(): """ A contact. @@ -2320,12 +2310,12 @@ def __init__(self, *, name=None, role=None): def _from_dict(cls, _dict): """Initialize a Contact object from a json dictionary.""" args = {} - validKeys = ['name', 'role'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['name', 'role'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Contact: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') if 'role' in _dict: @@ -2356,7 +2346,7 @@ def __ne__(self, other): return not self == other -class Contexts(object): +class Contexts(): """ Text that is related to the contents of the table and that precedes or follows the current table. @@ -2383,12 +2373,12 @@ def __init__(self, *, text=None, location=None): def _from_dict(cls, _dict): """Initialize a Contexts object from a json dictionary.""" args = {} - validKeys = ['text', 'location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Contexts: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: @@ -2419,7 +2409,7 @@ def __ne__(self, other): return not self == other -class ContractAmts(object): +class ContractAmts(): """ A monetary amount identified in the input document. @@ -2476,15 +2466,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a ContractAmts object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'confidence_level', 'text', 'text_normalized', 'interpretation', 'provenance_ids', 'location' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ContractAmts: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -2542,7 +2532,7 @@ class ConfidenceLevelEnum(Enum): LOW = "Low" -class ContractCurrencies(object): +class ContractCurrencies(): """ The contract currencies that are declared in the document. @@ -2593,15 +2583,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a ContractCurrencies object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'confidence_level', 'text', 'text_normalized', 'provenance_ids', 'location' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ContractCurrencies: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -2654,7 +2644,7 @@ class ConfidenceLevelEnum(Enum): LOW = "Low" -class ContractTerms(object): +class ContractTerms(): """ The duration or durations of the contract. @@ -2711,15 +2701,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a ContractTerms object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'confidence_level', 'text', 'text_normalized', 'interpretation', 'provenance_ids', 'location' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ContractTerms: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -2777,7 +2767,7 @@ class ConfidenceLevelEnum(Enum): LOW = "Low" -class ContractTypes(object): +class ContractTypes(): """ The contract type identified in the input document. @@ -2818,12 +2808,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a ContractTypes object from a json dictionary.""" args = {} - validKeys = ['confidence_level', 'text', 'provenance_ids', 'location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['confidence_level', 'text', 'provenance_ids', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ContractTypes: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -2871,7 +2861,7 @@ class ConfidenceLevelEnum(Enum): LOW = "Low" -class DocCounts(object): +class DocCounts(): """ Document counts. @@ -2906,12 +2896,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a DocCounts object from a json dictionary.""" args = {} - validKeys = ['total', 'pending', 'successful', 'failed'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['total', 'pending', 'successful', 'failed'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DocCounts: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'total' in _dict: args['total'] = _dict.get('total') if 'pending' in _dict: @@ -2950,7 +2940,7 @@ def __ne__(self, other): return not self == other -class DocInfo(object): +class DocInfo(): """ Information about the parsed input document. @@ -2978,12 +2968,12 @@ def __init__(self, *, html=None, title=None, hash=None): def _from_dict(cls, _dict): """Initialize a DocInfo object from a json dictionary.""" args = {} - validKeys = ['html', 'title', 'hash'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['html', 'title', 'hash'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DocInfo: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'html' in _dict: args['html'] = _dict.get('html') if 'title' in _dict: @@ -3018,7 +3008,7 @@ def __ne__(self, other): return not self == other -class DocStructure(object): +class DocStructure(): """ The structure of the input document. @@ -3058,12 +3048,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a DocStructure object from a json dictionary.""" args = {} - validKeys = ['section_titles', 'leading_sentences', 'paragraphs'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['section_titles', 'leading_sentences', 'paragraphs'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DocStructure: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'section_titles' in _dict: args['section_titles'] = [ SectionTitles._from_dict(x) @@ -3111,7 +3101,7 @@ def __ne__(self, other): return not self == other -class Document(object): +class Document(): """ Basic information about the input document. @@ -3143,12 +3133,12 @@ def __init__(self, *, title=None, html=None, hash=None, label=None): def _from_dict(cls, _dict): """Initialize a Document object from a json dictionary.""" args = {} - validKeys = ['title', 'html', 'hash', 'label'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['title', 'html', 'hash', 'label'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Document: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'title' in _dict: args['title'] = _dict.get('title') if 'html' in _dict: @@ -3187,7 +3177,7 @@ def __ne__(self, other): return not self == other -class EffectiveDates(object): +class EffectiveDates(): """ An effective date. @@ -3236,15 +3226,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a EffectiveDates object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'confidence_level', 'text', 'text_normalized', 'provenance_ids', 'location' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EffectiveDates: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -3297,7 +3287,7 @@ class ConfidenceLevelEnum(Enum): LOW = "Low" -class Element(object): +class Element(): """ A component part of the document. @@ -3343,12 +3333,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Element object from a json dictionary.""" args = {} - validKeys = ['location', 'text', 'types', 'categories', 'attributes'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['location', 'text', 'types', 'categories', 'attributes'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Element: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: @@ -3397,7 +3387,7 @@ def __ne__(self, other): return not self == other -class ElementLocations(object): +class ElementLocations(): """ A list of `begin` and `end` indexes that indicate the locations of the elements in the input document. @@ -3424,12 +3414,12 @@ def __init__(self, *, begin=None, end=None): def _from_dict(cls, _dict): """Initialize a ElementLocations object from a json dictionary.""" args = {} - validKeys = ['begin', 'end'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['begin', 'end'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ElementLocations: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'begin' in _dict: args['begin'] = _dict.get('begin') if 'end' in _dict: @@ -3460,7 +3450,7 @@ def __ne__(self, other): return not self == other -class ElementPair(object): +class ElementPair(): """ Details of semantically aligned elements. @@ -3515,15 +3505,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a ElementPair object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'document_label', 'text', 'location', 'types', 'categories', 'attributes' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ElementPair: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document_label' in _dict: args['document_label'] = _dict.get('document_label') if 'text' in _dict: @@ -3577,7 +3567,7 @@ def __ne__(self, other): return not self == other -class FeedbackDataInput(object): +class FeedbackDataInput(): """ Feedback data for submission. @@ -3639,15 +3629,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a FeedbackDataInput object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'feedback_type', 'document', 'model_id', 'model_version', 'location', 'text', 'original_labels', 'updated_labels' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class FeedbackDataInput: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'feedback_type' in _dict: args['feedback_type'] = _dict.get('feedback_type') else: @@ -3725,7 +3715,7 @@ def __ne__(self, other): return not self == other -class FeedbackDataOutput(object): +class FeedbackDataOutput(): """ Information returned from the **Add Feedback** method. @@ -3795,16 +3785,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a FeedbackDataOutput object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'feedback_type', 'document', 'model_id', 'model_version', 'location', 'text', 'original_labels', 'updated_labels', 'pagination' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class FeedbackDataOutput: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'feedback_type' in _dict: args['feedback_type'] = _dict.get('feedback_type') if 'document' in _dict: @@ -3866,7 +3856,7 @@ def __ne__(self, other): return not self == other -class FeedbackDeleted(object): +class FeedbackDeleted(): """ The status and message of the deletion request. @@ -3888,12 +3878,12 @@ def __init__(self, *, status=None, message=None): def _from_dict(cls, _dict): """Initialize a FeedbackDeleted object from a json dictionary.""" args = {} - validKeys = ['status', 'message'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['status', 'message'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class FeedbackDeleted: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') if 'message' in _dict: @@ -3924,7 +3914,7 @@ def __ne__(self, other): return not self == other -class FeedbackList(object): +class FeedbackList(): """ The results of a successful **List Feedback** request for all feedback. @@ -3945,12 +3935,12 @@ def __init__(self, *, feedback=None): def _from_dict(cls, _dict): """Initialize a FeedbackList object from a json dictionary.""" args = {} - validKeys = ['feedback'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['feedback'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class FeedbackList: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'feedback' in _dict: args['feedback'] = [ GetFeedback._from_dict(x) for x in (_dict.get('feedback')) @@ -3979,7 +3969,7 @@ def __ne__(self, other): return not self == other -class FeedbackReturn(object): +class FeedbackReturn(): """ Information about the document and the submitted feedback. @@ -4024,14 +4014,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a FeedbackReturn object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'feedback_id', 'user_id', 'comment', 'created', 'feedback_data' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class FeedbackReturn: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'feedback_id' in _dict: args['feedback_id'] = _dict.get('feedback_id') if 'user_id' in _dict: @@ -4075,7 +4065,7 @@ def __ne__(self, other): return not self == other -class GetFeedback(object): +class GetFeedback(): """ The results of a successful **Get Feedback** request for a single feedback entry. @@ -4116,12 +4106,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a GetFeedback object from a json dictionary.""" args = {} - validKeys = ['feedback_id', 'created', 'comment', 'feedback_data'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['feedback_id', 'created', 'comment', 'feedback_data'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class GetFeedback: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'feedback_id' in _dict: args['feedback_id'] = _dict.get('feedback_id') if 'created' in _dict: @@ -4161,7 +4151,7 @@ def __ne__(self, other): return not self == other -class HTMLReturn(object): +class HTMLReturn(): """ The HTML converted from an input document. @@ -4202,12 +4192,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a HTMLReturn object from a json dictionary.""" args = {} - validKeys = ['num_pages', 'author', 'publication_date', 'title', 'html'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = [ + 'num_pages', 'author', 'publication_date', 'title', 'html' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class HTMLReturn: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'num_pages' in _dict: args['num_pages'] = _dict.get('num_pages') if 'author' in _dict: @@ -4251,7 +4243,7 @@ def __ne__(self, other): return not self == other -class Interpretation(object): +class Interpretation(): """ The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. @@ -4292,12 +4284,12 @@ def __init__(self, *, value=None, numeric_value=None, unit=None): def _from_dict(cls, _dict): """Initialize a Interpretation object from a json dictionary.""" args = {} - validKeys = ['value', 'numeric_value', 'unit'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['value', 'numeric_value', 'unit'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Interpretation: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'value' in _dict: args['value'] = _dict.get('value') if 'numeric_value' in _dict: @@ -4332,7 +4324,7 @@ def __ne__(self, other): return not self == other -class Key(object): +class Key(): """ A key in a key-value pair. @@ -4363,12 +4355,12 @@ def __init__(self, *, cell_id=None, location=None, text=None): def _from_dict(cls, _dict): """Initialize a Key object from a json dictionary.""" args = {} - validKeys = ['cell_id', 'location', 'text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['cell_id', 'location', 'text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Key: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: @@ -4403,7 +4395,7 @@ def __ne__(self, other): return not self == other -class KeyValuePair(object): +class KeyValuePair(): """ Key-value pairs detected across cell boundaries. @@ -4425,12 +4417,12 @@ def __init__(self, *, key=None, value=None): def _from_dict(cls, _dict): """Initialize a KeyValuePair object from a json dictionary.""" args = {} - validKeys = ['key', 'value'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['key', 'value'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class KeyValuePair: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'key' in _dict: args['key'] = Key._from_dict(_dict.get('key')) if 'value' in _dict: @@ -4461,7 +4453,7 @@ def __ne__(self, other): return not self == other -class Label(object): +class Label(): """ A pair of `nature` and `party` objects. The `nature` object identifies the effect of the element on the identified `party`, and the `party` object identifies the affected @@ -4485,12 +4477,12 @@ def __init__(self, nature, party): def _from_dict(cls, _dict): """Initialize a Label object from a json dictionary.""" args = {} - validKeys = ['nature', 'party'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['nature', 'party'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Label: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'nature' in _dict: args['nature'] = _dict.get('nature') else: @@ -4527,7 +4519,7 @@ def __ne__(self, other): return not self == other -class LeadingSentence(object): +class LeadingSentence(): """ The leading sentences in a section or subsection of the input document. @@ -4558,12 +4550,12 @@ def __init__(self, *, text=None, location=None, element_locations=None): def _from_dict(cls, _dict): """Initialize a LeadingSentence object from a json dictionary.""" args = {} - validKeys = ['text', 'location', 'element_locations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'location', 'element_locations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class LeadingSentence: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: @@ -4604,7 +4596,7 @@ def __ne__(self, other): return not self == other -class Location(object): +class Location(): """ The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. @@ -4627,12 +4619,12 @@ def __init__(self, begin, end): def _from_dict(cls, _dict): """Initialize a Location object from a json dictionary.""" args = {} - validKeys = ['begin', 'end'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['begin', 'end'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Location: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'begin' in _dict: args['begin'] = _dict.get('begin') else: @@ -4669,7 +4661,7 @@ def __ne__(self, other): return not self == other -class Mention(object): +class Mention(): """ A mention of a party. @@ -4695,12 +4687,12 @@ def __init__(self, *, text=None, location=None): def _from_dict(cls, _dict): """Initialize a Mention object from a json dictionary.""" args = {} - validKeys = ['text', 'location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Mention: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: @@ -4731,7 +4723,7 @@ def __ne__(self, other): return not self == other -class OriginalLabelsIn(object): +class OriginalLabelsIn(): """ The original labeling from the input document, without the submitted feedback. @@ -4757,12 +4749,12 @@ def __init__(self, types, categories): def _from_dict(cls, _dict): """Initialize a OriginalLabelsIn object from a json dictionary.""" args = {} - validKeys = ['types', 'categories'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['types', 'categories'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class OriginalLabelsIn: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'types' in _dict: args['types'] = [ TypeLabel._from_dict(x) for x in (_dict.get('types')) @@ -4805,7 +4797,7 @@ def __ne__(self, other): return not self == other -class OriginalLabelsOut(object): +class OriginalLabelsOut(): """ The original labeling from the input document, without the submitted feedback. @@ -4839,12 +4831,12 @@ def __init__(self, *, types=None, categories=None, modification=None): def _from_dict(cls, _dict): """Initialize a OriginalLabelsOut object from a json dictionary.""" args = {} - validKeys = ['types', 'categories', 'modification'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['types', 'categories', 'modification'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class OriginalLabelsOut: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'types' in _dict: args['types'] = [ TypeLabel._from_dict(x) for x in (_dict.get('types')) @@ -4892,7 +4884,7 @@ class ModificationEnum(Enum): REMOVED = "removed" -class Pagination(object): +class Pagination(): """ Pagination details, if required by the length of the output. @@ -4935,14 +4927,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Pagination object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'refresh_cursor', 'next_cursor', 'refresh_url', 'next_url', 'total' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Pagination: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'refresh_cursor' in _dict: args['refresh_cursor'] = _dict.get('refresh_cursor') if 'next_cursor' in _dict: @@ -4985,7 +4977,7 @@ def __ne__(self, other): return not self == other -class Paragraphs(object): +class Paragraphs(): """ The locations of each paragraph in the input document. @@ -5008,12 +5000,12 @@ def __init__(self, *, location=None): def _from_dict(cls, _dict): """Initialize a Paragraphs object from a json dictionary.""" args = {} - validKeys = ['location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Paragraphs: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) @@ -5040,7 +5032,7 @@ def __ne__(self, other): return not self == other -class Parties(object): +class Parties(): """ A party and its corresponding role, including address and contact information if identified. @@ -5090,14 +5082,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Parties object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'party', 'role', 'importance', 'addresses', 'contacts', 'mentions' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Parties: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'party' in _dict: args['party'] = _dict.get('party') if 'role' in _dict: @@ -5157,7 +5149,7 @@ class ImportanceEnum(Enum): UNKNOWN = "Unknown" -class PaymentTerms(object): +class PaymentTerms(): """ The document's payment duration or durations. @@ -5214,15 +5206,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a PaymentTerms object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'confidence_level', 'text', 'text_normalized', 'interpretation', 'provenance_ids', 'location' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class PaymentTerms: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -5280,7 +5272,7 @@ class ConfidenceLevelEnum(Enum): LOW = "Low" -class RowHeaders(object): +class RowHeaders(): """ Row-level cells, each applicable as a header to other cells in the same row as itself, of the current table. @@ -5349,15 +5341,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a RowHeaders object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'cell_id', 'location', 'text', 'text_normalized', 'row_index_begin', 'row_index_end', 'column_index_begin', 'column_index_end' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RowHeaders: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: @@ -5417,7 +5409,7 @@ def __ne__(self, other): return not self == other -class SectionTitle(object): +class SectionTitle(): """ The table's section title, if identified. @@ -5443,12 +5435,12 @@ def __init__(self, *, text=None, location=None): def _from_dict(cls, _dict): """Initialize a SectionTitle object from a json dictionary.""" args = {} - validKeys = ['text', 'location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SectionTitle: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: @@ -5479,7 +5471,7 @@ def __ne__(self, other): return not self == other -class SectionTitles(object): +class SectionTitles(): """ An array containing one object per section or subsection detected in the input document. Sections and subsections are not nested; instead, they are flattened out and @@ -5526,12 +5518,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SectionTitles object from a json dictionary.""" args = {} - validKeys = ['text', 'location', 'level', 'element_locations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'location', 'level', 'element_locations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SectionTitles: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: @@ -5576,7 +5568,7 @@ def __ne__(self, other): return not self == other -class ShortDoc(object): +class ShortDoc(): """ Brief information about the input document. @@ -5599,12 +5591,12 @@ def __init__(self, *, title=None, hash=None): def _from_dict(cls, _dict): """Initialize a ShortDoc object from a json dictionary.""" args = {} - validKeys = ['title', 'hash'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['title', 'hash'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ShortDoc: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'title' in _dict: args['title'] = _dict.get('title') if 'hash' in _dict: @@ -5635,7 +5627,7 @@ def __ne__(self, other): return not self == other -class TableHeaders(object): +class TableHeaders(): """ The contents of the current table's header. @@ -5695,15 +5687,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a TableHeaders object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'cell_id', 'location', 'text', 'row_index_begin', 'row_index_end', 'column_index_begin', 'column_index_end' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TableHeaders: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: @@ -5758,7 +5750,7 @@ def __ne__(self, other): return not self == other -class TableReturn(object): +class TableReturn(): """ The analysis of the document's tables. @@ -5796,12 +5788,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a TableReturn object from a json dictionary.""" args = {} - validKeys = ['document', 'model_id', 'model_version', 'tables'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document', 'model_id', 'model_version', 'tables'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TableReturn: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = DocInfo._from_dict(_dict.get('document')) if 'model_id' in _dict: @@ -5842,7 +5834,7 @@ def __ne__(self, other): return not self == other -class TableTitle(object): +class TableTitle(): """ If identified, the title or caption of the current table of the form `Table x.: ...`. Empty when no title is identified. When exposed, the `title` is also excluded from the @@ -5871,12 +5863,12 @@ def __init__(self, *, location=None, text=None): def _from_dict(cls, _dict): """Initialize a TableTitle object from a json dictionary.""" args = {} - validKeys = ['location', 'text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['location', 'text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TableTitle: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: @@ -5907,7 +5899,7 @@ def __ne__(self, other): return not self == other -class Tables(object): +class Tables(): """ The contents of the tables extracted from a document. @@ -5998,16 +5990,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Tables object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'location', 'text', 'section_title', 'title', 'table_headers', 'row_headers', 'column_headers', 'body_cells', 'contexts', 'key_value_pairs' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Tables: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'location' in _dict: args['location'] = Location._from_dict(_dict.get('location')) if 'text' in _dict: @@ -6090,7 +6082,7 @@ def __ne__(self, other): return not self == other -class TerminationDates(object): +class TerminationDates(): """ Termination dates identified in the input document. @@ -6139,15 +6131,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a TerminationDates object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'confidence_level', 'text', 'text_normalized', 'provenance_ids', 'location' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TerminationDates: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -6200,7 +6192,7 @@ class ConfidenceLevelEnum(Enum): LOW = "Low" -class TypeLabel(object): +class TypeLabel(): """ Identification of a specific type. @@ -6228,12 +6220,12 @@ def __init__(self, *, label=None, provenance_ids=None): def _from_dict(cls, _dict): """Initialize a TypeLabel object from a json dictionary.""" args = {} - validKeys = ['label', 'provenance_ids'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['label', 'provenance_ids'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TypeLabel: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = Label._from_dict(_dict.get('label')) if 'provenance_ids' in _dict: @@ -6264,7 +6256,7 @@ def __ne__(self, other): return not self == other -class TypeLabelComparison(object): +class TypeLabelComparison(): """ Identification of a specific type. @@ -6287,12 +6279,12 @@ def __init__(self, *, label=None): def _from_dict(cls, _dict): """Initialize a TypeLabelComparison object from a json dictionary.""" args = {} - validKeys = ['label'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['label'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TypeLabelComparison: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = Label._from_dict(_dict.get('label')) return cls(**args) @@ -6319,7 +6311,7 @@ def __ne__(self, other): return not self == other -class UnalignedElement(object): +class UnalignedElement(): """ Element that does not align semantically between two compared documents. @@ -6374,15 +6366,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a UnalignedElement object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'document_label', 'location', 'text', 'types', 'categories', 'attributes' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class UnalignedElement: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document_label' in _dict: args['document_label'] = _dict.get('document_label') if 'location' in _dict: @@ -6436,7 +6428,7 @@ def __ne__(self, other): return not self == other -class UpdatedLabelsIn(object): +class UpdatedLabelsIn(): """ The updated labeling from the input document, accounting for the submitted feedback. @@ -6462,12 +6454,12 @@ def __init__(self, types, categories): def _from_dict(cls, _dict): """Initialize a UpdatedLabelsIn object from a json dictionary.""" args = {} - validKeys = ['types', 'categories'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['types', 'categories'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class UpdatedLabelsIn: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'types' in _dict: args['types'] = [ TypeLabel._from_dict(x) for x in (_dict.get('types')) @@ -6510,7 +6502,7 @@ def __ne__(self, other): return not self == other -class UpdatedLabelsOut(object): +class UpdatedLabelsOut(): """ The updated labeling from the input document, accounting for the submitted feedback. @@ -6544,12 +6536,12 @@ def __init__(self, *, types=None, categories=None, modification=None): def _from_dict(cls, _dict): """Initialize a UpdatedLabelsOut object from a json dictionary.""" args = {} - validKeys = ['types', 'categories', 'modification'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['types', 'categories', 'modification'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class UpdatedLabelsOut: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'types' in _dict: args['types'] = [ TypeLabel._from_dict(x) for x in (_dict.get('types')) @@ -6597,7 +6589,7 @@ class ModificationEnum(Enum): REMOVED = "removed" -class Value(object): +class Value(): """ A value in a key-value pair. @@ -6628,12 +6620,12 @@ def __init__(self, *, cell_id=None, location=None, text=None): def _from_dict(cls, _dict): """Initialize a Value object from a json dictionary.""" args = {} - validKeys = ['cell_id', 'location', 'text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['cell_id', 'location', 'text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Value: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 4977372e4..eda9262d0 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -27,6 +27,7 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources from os.path import basename ############################################################################## @@ -37,14 +38,12 @@ class DiscoveryV1(BaseService): """The Discovery V1 service.""" - default_url = 'https://gateway.watsonplatform.net/discovery/api' + default_service_url = 'https://gateway.watsonplatform.net/discovery/api' def __init__( self, version, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Discovery service. @@ -60,25 +59,27 @@ def __init__( application, and don't change it until your application is ready for a later version. - :param str url: The base url to use when contacting the service (e.g. - "https://gateway.watsonplatform.net/discovery/api/discovery/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('discovery') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: - authenticator = get_authenticator_from_environment('Discovery') + authenticator = get_authenticator_from_environment('discovery') - BaseService.__init__( - self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Discovery') + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) self.version = version ######################### @@ -119,13 +120,12 @@ def create_environment(self, name, *, description=None, size=None, data = {'name': name, 'description': description, 'size': size} url = '/v1/environments' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -150,12 +150,11 @@ def list_environments(self, *, name=None, **kwargs): params = {'version': self.version, 'name': name} url = '/v1/environments' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -182,12 +181,11 @@ def get_environment(self, environment_id, **kwargs): url = '/v1/environments/{0}'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -230,13 +228,12 @@ def update_environment(self, url = '/v1/environments/{0}'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -263,12 +260,11 @@ def delete_environment(self, environment_id, **kwargs): url = '/v1/environments/{0}'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -305,12 +301,11 @@ def list_fields(self, environment_id, collection_ids, **kwargs): url = '/v1/environments/{0}/fields'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -392,13 +387,12 @@ def create_configuration(self, url = '/v1/environments/{0}/configurations'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -428,12 +422,11 @@ def list_configurations(self, environment_id, *, name=None, **kwargs): url = '/v1/environments/{0}/configurations'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -463,12 +456,11 @@ def get_configuration(self, environment_id, configuration_id, **kwargs): url = '/v1/environments/{0}/configurations/{1}'.format( *self._encode_path_vars(environment_id, configuration_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -549,13 +541,12 @@ def update_configuration(self, url = '/v1/environments/{0}/configurations/{1}'.format( *self._encode_path_vars(environment_id, configuration_id)) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -592,108 +583,11 @@ def delete_configuration(self, environment_id, configuration_id, **kwargs): url = '/v1/environments/{0}/configurations/{1}'.format( *self._encode_path_vars(environment_id, configuration_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) - response = self.send(request) - return response - - ######################### - # Test your configuration on a document - ######################### - - def test_configuration_in_environment(self, - environment_id, - *, - configuration=None, - file=None, - filename=None, - file_content_type=None, - metadata=None, - step=None, - configuration_id=None, - **kwargs): - """ - Test configuration. - - **Deprecated** This method is no longer supported and is scheduled to be removed - from service on July 31st 2019. - Runs a sample document through the default or your configuration and returns - diagnostic information designed to help you understand how the document was - processed. The document is not added to the index. - - :param str environment_id: The ID of the environment. - :param str configuration: (optional) The configuration to use to process - the document. If this part is provided, then the provided configuration is - used to process the document. If the **configuration_id** is also provided - (both are present at the same time), then request is rejected. The maximum - supported configuration size is 1 MB. Configuration parts larger than 1 MB - are rejected. See the `GET /configurations/{configuration_id}` operation - for an example configuration. - :param file file: (optional) The content of the document to ingest. The - maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a confiruration is - 1 megabyte. Files larger than the supported size are rejected. - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. - :param str step: (optional) Specify to only run the input document through - the given step instead of running the input document through the entire - ingestion workflow. Valid values are `convert`, `enrich`, and `normalize`. - :param str configuration_id: (optional) The ID of the configuration to use - to process the document. If the **configuration** form part is also - provided (both are present at the same time), then the request will be - rejected. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - - headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'test_configuration_in_environment') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'step': step, - 'configuration_id': configuration_id - } - - form_data = {} - if configuration: - form_data['configuration'] = (None, configuration, 'text/plain') - if file: - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data['file'] = (filename, file, file_content_type or - 'application/octet-stream') - if metadata: - form_data['metadata'] = (None, metadata, 'text/plain') - - url = '/v1/environments/{0}/preview'.format( - *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -746,13 +640,12 @@ def create_collection(self, url = '/v1/environments/{0}/collections'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -782,12 +675,11 @@ def list_collections(self, environment_id, *, name=None, **kwargs): url = '/v1/environments/{0}/collections'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -817,12 +709,11 @@ def get_collection(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -869,13 +760,12 @@ def update_collection(self, url = '/v1/environments/{0}/collections/{1}'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -905,12 +795,11 @@ def delete_collection(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -943,12 +832,11 @@ def list_collection_fields(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/fields'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -985,12 +873,11 @@ def list_expansions(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/expansions'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1043,13 +930,12 @@ def create_expansions(self, environment_id, collection_id, expansions, url = '/v1/environments/{0}/collections/{1}/expansions'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -1082,12 +968,11 @@ def delete_expansions(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/expansions'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -1122,12 +1007,11 @@ def get_tokenization_dictionary_status(self, environment_id, collection_id, url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1175,13 +1059,12 @@ def create_tokenization_dictionary(self, url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -1215,12 +1098,11 @@ def delete_tokenization_dictionary(self, environment_id, collection_id, url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -1253,12 +1135,11 @@ def get_stopword_list_status(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1298,23 +1179,22 @@ def create_stopword_list(self, params = {'version': self.version} - form_data = {} + form_data = [] if not stopword_filename and hasattr(stopword_file, 'name'): stopword_filename = basename(stopword_file.name) if not stopword_filename: raise ValueError('stopword_filename must be provided') - form_data['stopword_file'] = (stopword_filename, stopword_file, - 'application/octet-stream') + form_data.append(('stopword_file', (stopword_filename, stopword_file, + 'application/octet-stream'))) url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -1347,12 +1227,11 @@ def delete_stopword_list(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -1424,26 +1303,25 @@ def add_document(self, params = {'version': self.version} - form_data = {} + form_data = [] if file: if not filename and hasattr(file, 'name'): filename = basename(file.name) if not filename: raise ValueError('filename must be provided') - form_data['file'] = (filename, file, file_content_type or - 'application/octet-stream') + form_data.append(('file', (filename, file, file_content_type or + 'application/octet-stream'))) if metadata: - form_data['metadata'] = (None, metadata, 'text/plain') + form_data.append(('metadata', (None, metadata, 'text/plain'))) url = '/v1/environments/{0}/collections/{1}/documents'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -1482,12 +1360,11 @@ def get_document_status(self, environment_id, collection_id, document_id, url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( *self._encode_path_vars(environment_id, collection_id, document_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1543,26 +1420,25 @@ def update_document(self, params = {'version': self.version} - form_data = {} + form_data = [] if file: if not filename and hasattr(file, 'name'): filename = basename(file.name) if not filename: raise ValueError('filename must be provided') - form_data['file'] = (filename, file, file_content_type or - 'application/octet-stream') + form_data.append(('file', (filename, file, file_content_type or + 'application/octet-stream'))) if metadata: - form_data['metadata'] = (None, metadata, 'text/plain') + form_data.append(('metadata', (None, metadata, 'text/plain'))) url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( *self._encode_path_vars(environment_id, collection_id, document_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -1600,12 +1476,11 @@ def delete_document(self, environment_id, collection_id, document_id, url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( *self._encode_path_vars(environment_id, collection_id, document_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1632,7 +1507,6 @@ def query(self, passages_characters=None, deduplicate=None, deduplicate_field=None, - collection_ids=None, similar=None, similar_document_ids=None, similar_fields=None, @@ -1695,9 +1569,6 @@ def query(self, based on the field specified are removed from the returned results. Duplicate comparison is limited to the current query only, **offset** is not considered. This parameter is currently Beta functionality. - :param str collection_ids: (optional) A comma-separated list of collection - IDs to be queried against. Required when querying multiple collections, - invalid when performing a single collection query. :param bool similar: (optional) When `true`, results are returned based on their similarity to the document IDs specified in the **similar.document_ids** parameter. @@ -1753,7 +1624,6 @@ def query(self, 'passages.characters': passages_characters, 'deduplicate': deduplicate, 'deduplicate.field': deduplicate_field, - 'collection_ids': collection_ids, 'similar': similar, 'similar.document_ids': similar_document_ids, 'similar.fields': similar_fields, @@ -1762,13 +1632,12 @@ def query(self, url = '/v1/environments/{0}/collections/{1}/query'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -1898,17 +1767,17 @@ def query_notices(self, url = '/v1/environments/{0}/collections/{1}/notices'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response def federated_query(self, environment_id, + collection_ids, *, filter=None, query=None, @@ -1925,7 +1794,6 @@ def federated_query(self, passages_characters=None, deduplicate=None, deduplicate_field=None, - collection_ids=None, similar=None, similar_document_ids=None, similar_fields=None, @@ -1940,6 +1808,8 @@ def federated_query(self, documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-query-concepts#query-concepts). :param str environment_id: The ID of the environment. + :param str collection_ids: A comma-separated list of collection IDs to be + queried against. :param str filter: (optional) A cacheable query that excludes documents that don't mention the query content. Filter searches are better for metadata-type searches and for assessing the concepts in the data set. @@ -1987,9 +1857,6 @@ def federated_query(self, based on the field specified are removed from the returned results. Duplicate comparison is limited to the current query only, **offset** is not considered. This parameter is currently Beta functionality. - :param str collection_ids: (optional) A comma-separated list of collection - IDs to be queried against. Required when querying multiple collections, - invalid when performing a single collection query. :param bool similar: (optional) When `true`, results are returned based on their similarity to the document IDs specified in the **similar.document_ids** parameter. @@ -2028,6 +1895,7 @@ def federated_query(self, params = {'version': self.version} data = { + 'collection_ids': collection_ids, 'filter': filter, 'query': query, 'natural_language_query': natural_language_query, @@ -2043,7 +1911,6 @@ def federated_query(self, 'passages.characters': passages_characters, 'deduplicate': deduplicate, 'deduplicate.field': deduplicate_field, - 'collection_ids': collection_ids, 'similar': similar, 'similar.document_ids': similar_document_ids, 'similar.fields': similar_fields, @@ -2052,13 +1919,12 @@ def federated_query(self, url = '/v1/environments/{0}/query'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2173,167 +2039,11 @@ def federated_query_notices(self, url = '/v1/environments/{0}/notices'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) - response = self.send(request) - return response - - def query_entities(self, - environment_id, - collection_id, - *, - feature=None, - entity=None, - context=None, - count=None, - evidence_count=None, - **kwargs): - """ - Knowledge Graph entity query. - - See the [Knowledge Graph - documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-kg#kg) - for more details. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str feature: (optional) The entity query feature to perform. - Supported features are `disambiguate` and `similar_entities`. - :param QueryEntitiesEntity entity: (optional) A text string that appears - within the entity text field. - :param QueryEntitiesContext context: (optional) Entity text to provide - context for the queried entity and rank based on that association. For - example, if you wanted to query the city of London in England your query - would look for `London` with the context of `England`. - :param int count: (optional) The number of results to return. The default - is `10`. The maximum is `1000`. - :param int evidence_count: (optional) The number of evidence items to - return for each result. The default is `0`. The maximum number of evidence - items per query is 10,000. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if entity is not None: - entity = self._convert_model(entity) - if context is not None: - context = self._convert_model(context) - - headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'query_entities') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'feature': feature, - 'entity': entity, - 'context': context, - 'count': count, - 'evidence_count': evidence_count - } - - url = '/v1/environments/{0}/collections/{1}/query_entities'.format( - *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) - response = self.send(request) - return response - - def query_relations(self, - environment_id, - collection_id, - *, - entities=None, - context=None, - sort=None, - filter=None, - count=None, - evidence_count=None, - **kwargs): - """ - Knowledge Graph relationship query. - - See the [Knowledge Graph - documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-kg#kg) - for more details. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param list[QueryRelationsEntity] entities: (optional) An array of entities - to find relationships for. - :param QueryEntitiesContext context: (optional) Entity text to provide - context for the queried entity and rank based on that association. For - example, if you wanted to query the city of London in England your query - would look for `London` with the context of `England`. - :param str sort: (optional) The sorting method for the relationships, can - be `score` or `frequency`. `frequency` is the number of unique times each - entity is identified. The default is `score`. This parameter cannot be used - in the same query as the **bias** parameter. - :param QueryRelationsFilter filter: (optional) - :param int count: (optional) The number of results to return. The default - is `10`. The maximum is `1000`. - :param int evidence_count: (optional) The number of evidence items to - return for each result. The default is `0`. The maximum number of evidence - items per query is 10,000. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if environment_id is None: - raise ValueError('environment_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if entities is not None: - entities = [self._convert_model(x) for x in entities] - if context is not None: - context = self._convert_model(context) - if filter is not None: - filter = self._convert_model(filter) - - headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'query_relations') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'entities': entities, - 'context': context, - 'sort': sort, - 'filter': filter, - 'count': count, - 'evidence_count': evidence_count - } - - url = '/v1/environments/{0}/collections/{1}/query_relations'.format( - *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2369,12 +2079,11 @@ def list_training_data(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/training_data'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2428,13 +2137,12 @@ def add_training_data(self, url = '/v1/environments/{0}/collections/{1}/training_data'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2467,12 +2175,11 @@ def delete_all_training_data(self, environment_id, collection_id, **kwargs): url = '/v1/environments/{0}/collections/{1}/training_data'.format( *self._encode_path_vars(environment_id, collection_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -2509,12 +2216,11 @@ def get_training_data(self, environment_id, collection_id, query_id, url = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2551,12 +2257,11 @@ def delete_training_data(self, environment_id, collection_id, query_id, url = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -2593,12 +2298,11 @@ def list_training_examples(self, environment_id, collection_id, query_id, url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2653,13 +2357,12 @@ def create_training_example(self, url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( *self._encode_path_vars(environment_id, collection_id, query_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2700,12 +2403,11 @@ def delete_training_example(self, environment_id, collection_id, query_id, url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( *self._encode_path_vars(environment_id, collection_id, query_id, example_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -2757,13 +2459,12 @@ def update_training_example(self, url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( *self._encode_path_vars(environment_id, collection_id, query_id, example_id)) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2803,12 +2504,11 @@ def get_training_example(self, environment_id, collection_id, query_id, url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( *self._encode_path_vars(environment_id, collection_id, query_id, example_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2846,12 +2546,11 @@ def delete_user_data(self, customer_id, **kwargs): params = {'version': self.version, 'customer_id': customer_id} url = '/v1/user_data' - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -2891,13 +2590,12 @@ def create_event(self, type, data, **kwargs): data = {'type': type, 'data': data} url = '/v1/events' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2953,12 +2651,11 @@ def query_log(self, } url = '/v1/logs' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2999,12 +2696,11 @@ def get_metrics_query(self, } url = '/v1/metrics/number_of_queries' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -3047,12 +2743,11 @@ def get_metrics_query_event(self, } url = '/v1/metrics/number_of_queries_with_event' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -3094,12 +2789,11 @@ def get_metrics_query_no_results(self, } url = '/v1/metrics/number_of_queries_with_no_search_results' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -3142,12 +2836,11 @@ def get_metrics_event_rate(self, } url = '/v1/metrics/event_rate' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -3177,12 +2870,11 @@ def get_metrics_query_token_event(self, *, count=None, **kwargs): params = {'version': self.version, 'count': count} url = '/v1/metrics/top_query_tokens_with_event_rate' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -3217,12 +2909,11 @@ def list_credentials(self, environment_id, **kwargs): url = '/v1/environments/{0}/credentials'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -3287,13 +2978,12 @@ def create_credentials(self, url = '/v1/environments/{0}/credentials'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -3328,12 +3018,11 @@ def get_credentials(self, environment_id, credential_id, **kwargs): url = '/v1/environments/{0}/credentials/{1}'.format( *self._encode_path_vars(environment_id, credential_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -3402,13 +3091,12 @@ def update_credentials(self, url = '/v1/environments/{0}/credentials/{1}'.format( *self._encode_path_vars(environment_id, credential_id)) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -3441,12 +3129,11 @@ def delete_credentials(self, environment_id, credential_id, **kwargs): url = '/v1/environments/{0}/credentials/{1}'.format( *self._encode_path_vars(environment_id, credential_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -3479,12 +3166,11 @@ def list_gateways(self, environment_id, **kwargs): url = '/v1/environments/{0}/gateways'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -3516,13 +3202,12 @@ def create_gateway(self, environment_id, *, name=None, **kwargs): url = '/v1/environments/{0}/gateways'.format( *self._encode_path_vars(environment_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -3554,12 +3239,11 @@ def get_gateway(self, environment_id, gateway_id, **kwargs): url = '/v1/environments/{0}/gateways/{1}'.format( *self._encode_path_vars(environment_id, gateway_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -3591,43 +3275,15 @@ def delete_gateway(self, environment_id, gateway_id, **kwargs): url = '/v1/environments/{0}/gateways/{1}'.format( *self._encode_path_vars(environment_id, gateway_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response -class TestConfigurationInEnvironmentEnums(object): - - class FileContentType(Enum): - """ - The content type of file. - """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' - - class Step(Enum): - """ - Specify to only run the input document through the given step instead of running - the input document through the entire ingestion workflow. Valid values are - `convert`, `enrich`, and `normalize`. - """ - HTML_INPUT = 'html_input' - HTML_OUTPUT = 'html_output' - JSON_OUTPUT = 'json_output' - JSON_NORMALIZATIONS_OUTPUT = 'json_normalizations_output' - ENRICHMENTS_OUTPUT = 'enrichments_output' - NORMALIZATIONS_OUTPUT = 'normalizations_output' - - class AddDocumentEnums(object): class FileContentType(Enum): @@ -3697,9 +3353,9 @@ class ResultType(Enum): ############################################################################## -class AggregationResult(object): +class AggregationResult(): """ - AggregationResult. + Aggregation results for the specified query. :attr str key: (optional) Key that matched the aggregation type. :attr int matching_results: (optional) Number of matching results. @@ -3724,12 +3380,12 @@ def __init__(self, *, key=None, matching_results=None, aggregations=None): def _from_dict(cls, _dict): """Initialize a AggregationResult object from a json dictionary.""" args = {} - validKeys = ['key', 'matching_results', 'aggregations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['key', 'matching_results', 'aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AggregationResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'key' in _dict: args['key'] = _dict.get('key') if 'matching_results' in _dict: @@ -3768,7 +3424,7 @@ def __ne__(self, other): return not self == other -class Calculation(object): +class Calculation(): """ Calculation. @@ -3806,12 +3462,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Calculation object from a json dictionary.""" args = {} - validKeys = ['field', 'value'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['field', 'value'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Calculation: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'field' in _dict: args['field'] = _dict.get('field') if 'value' in _dict: @@ -3842,7 +3498,7 @@ def __ne__(self, other): return not self == other -class Collection(object): +class Collection(): """ A collection for storing documents. @@ -3859,10 +3515,11 @@ class Collection(object): :attr str language: (optional) The language of the documents stored in the collection. Permitted values include `en` (English), `de` (German), and `es` (Spanish). - :attr DocumentCounts document_counts: (optional) + :attr DocumentCounts document_counts: (optional) Object containing collection + document count information. :attr CollectionDiskUsage disk_usage: (optional) Summary of the disk usage statistics for this collection. - :attr TrainingStatus training_status: (optional) + :attr TrainingStatus training_status: (optional) Training status details. :attr CollectionCrawlStatus crawl_status: (optional) Object containing information about the crawl status of this collection. :attr SduStatus smart_document_understanding: (optional) Object containing smart @@ -3901,10 +3558,11 @@ def __init__(self, :param str language: (optional) The language of the documents stored in the collection. Permitted values include `en` (English), `de` (German), and `es` (Spanish). - :param DocumentCounts document_counts: (optional) + :param DocumentCounts document_counts: (optional) Object containing + collection document count information. :param CollectionDiskUsage disk_usage: (optional) Summary of the disk usage statistics for this collection. - :param TrainingStatus training_status: (optional) + :param TrainingStatus training_status: (optional) Training status details. :param CollectionCrawlStatus crawl_status: (optional) Object containing information about the crawl status of this collection. :param SduStatus smart_document_understanding: (optional) Object containing @@ -3928,17 +3586,17 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Collection object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'collection_id', 'name', 'description', 'created', 'updated', 'status', 'configuration_id', 'language', 'document_counts', 'disk_usage', 'training_status', 'crawl_status', 'smart_document_understanding' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Collection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') if 'name' in _dict: @@ -4032,7 +3690,7 @@ class StatusEnum(Enum): MAINTENANCE = "maintenance" -class CollectionCrawlStatus(object): +class CollectionCrawlStatus(): """ Object containing information about the crawl status of this collection. @@ -4053,12 +3711,12 @@ def __init__(self, *, source_crawl=None): def _from_dict(cls, _dict): """Initialize a CollectionCrawlStatus object from a json dictionary.""" args = {} - validKeys = ['source_crawl'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['source_crawl'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CollectionCrawlStatus: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'source_crawl' in _dict: args['source_crawl'] = SourceStatus._from_dict( _dict.get('source_crawl')) @@ -4086,7 +3744,7 @@ def __ne__(self, other): return not self == other -class CollectionDiskUsage(object): +class CollectionDiskUsage(): """ Summary of the disk usage statistics for this collection. @@ -4105,12 +3763,12 @@ def __init__(self, *, used_bytes=None): def _from_dict(cls, _dict): """Initialize a CollectionDiskUsage object from a json dictionary.""" args = {} - validKeys = ['used_bytes'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['used_bytes'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CollectionDiskUsage: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'used_bytes' in _dict: args['used_bytes'] = _dict.get('used_bytes') return cls(**args) @@ -4137,7 +3795,7 @@ def __ne__(self, other): return not self == other -class CollectionUsage(object): +class CollectionUsage(): """ Summary of the collection usage in the environment. @@ -4162,12 +3820,12 @@ def __init__(self, *, available=None, maximum_allowed=None): def _from_dict(cls, _dict): """Initialize a CollectionUsage object from a json dictionary.""" args = {} - validKeys = ['available', 'maximum_allowed'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['available', 'maximum_allowed'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CollectionUsage: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'available' in _dict: args['available'] = _dict.get('available') if 'maximum_allowed' in _dict: @@ -4199,7 +3857,7 @@ def __ne__(self, other): return not self == other -class Configuration(object): +class Configuration(): """ A custom configuration for the environment. @@ -4269,15 +3927,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Configuration object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'configuration_id', 'name', 'created', 'updated', 'description', 'conversions', 'enrichments', 'normalizations', 'source' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Configuration: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'configuration_id' in _dict: args['configuration_id'] = _dict.get('configuration_id') if 'name' in _dict: @@ -4348,7 +4006,7 @@ def __ne__(self, other): return not self == other -class Conversions(object): +class Conversions(): """ Document conversion settings. @@ -4406,15 +4064,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Conversions object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'pdf', 'word', 'html', 'segment', 'json_normalizations', 'image_text_recognition' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Conversions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'pdf' in _dict: args['pdf'] = PdfSettings._from_dict(_dict.get('pdf')) if 'word' in _dict: @@ -4469,7 +4127,7 @@ def __ne__(self, other): return not self == other -class CreateEventResponse(object): +class CreateEventResponse(): """ An object defining the event being created. @@ -4491,12 +4149,12 @@ def __init__(self, *, type=None, data=None): def _from_dict(cls, _dict): """Initialize a CreateEventResponse object from a json dictionary.""" args = {} - validKeys = ['type', 'data'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['type', 'data'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CreateEventResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'data' in _dict: @@ -4533,7 +4191,7 @@ class TypeEnum(Enum): CLICK = "click" -class CredentialDetails(object): +class CredentialDetails(): """ Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. @@ -4747,18 +4405,18 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a CredentialDetails object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'credential_type', 'client_id', 'enterprise_id', 'url', 'username', 'organization_url', 'site_collection_path', 'site_collection.path', 'client_secret', 'public_key_id', 'private_key', 'passphrase', 'password', 'gateway_id', 'source_version', 'web_application_url', 'domain', 'endpoint', 'access_key_id', 'secret_access_key' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CredentialDetails: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'credential_type' in _dict: args['credential_type'] = _dict.get('credential_type') if 'client_id' in _dict: @@ -4890,7 +4548,7 @@ class SourceVersionEnum(Enum): ONLINE = "online" -class Credentials(object): +class Credentials(): """ Object containing credential information. @@ -4956,14 +4614,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Credentials object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'credential_id', 'source_type', 'credential_details', 'status' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Credentials: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'credential_id' in _dict: args['credential_id'] = _dict.get('credential_id') if 'source_type' in _dict: @@ -5033,9 +4691,9 @@ class StatusEnum(Enum): INVALID = "invalid" -class CredentialsList(object): +class CredentialsList(): """ - CredentialsList. + Object containing array of credential definitions. :attr list[Credentials] credentials: (optional) An array of credential definitions that were created for this instance. @@ -5054,12 +4712,12 @@ def __init__(self, *, credentials=None): def _from_dict(cls, _dict): """Initialize a CredentialsList object from a json dictionary.""" args = {} - validKeys = ['credentials'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['credentials'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CredentialsList: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'credentials' in _dict: args['credentials'] = [ Credentials._from_dict(x) for x in (_dict.get('credentials')) @@ -5088,9 +4746,9 @@ def __ne__(self, other): return not self == other -class DeleteCollectionResponse(object): +class DeleteCollectionResponse(): """ - DeleteCollectionResponse. + Response object returned when deleting a colleciton. :attr str collection_id: The unique identifier of the collection that is being deleted. @@ -5114,12 +4772,12 @@ def __init__(self, collection_id, status): def _from_dict(cls, _dict): """Initialize a DeleteCollectionResponse object from a json dictionary.""" args = {} - validKeys = ['collection_id', 'status'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['collection_id', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DeleteCollectionResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') else: @@ -5165,9 +4823,9 @@ class StatusEnum(Enum): DELETED = "deleted" -class DeleteConfigurationResponse(object): +class DeleteConfigurationResponse(): """ - DeleteConfigurationResponse. + Information returned when a configuration is deleted. :attr str configuration_id: The unique identifier for the configuration. :attr str status: Status of the configuration. A deleted configuration has the @@ -5193,12 +4851,12 @@ def __init__(self, configuration_id, status, *, notices=None): def _from_dict(cls, _dict): """Initialize a DeleteConfigurationResponse object from a json dictionary.""" args = {} - validKeys = ['configuration_id', 'status', 'notices'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['configuration_id', 'status', 'notices'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DeleteConfigurationResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'configuration_id' in _dict: args['configuration_id'] = _dict.get('configuration_id') else: @@ -5250,7 +4908,7 @@ class StatusEnum(Enum): DELETED = "deleted" -class DeleteCredentials(object): +class DeleteCredentials(): """ Object returned after credentials are deleted. @@ -5274,12 +4932,12 @@ def __init__(self, *, credential_id=None, status=None): def _from_dict(cls, _dict): """Initialize a DeleteCredentials object from a json dictionary.""" args = {} - validKeys = ['credential_id', 'status'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['credential_id', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DeleteCredentials: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'credential_id' in _dict: args['credential_id'] = _dict.get('credential_id') if 'status' in _dict: @@ -5316,9 +4974,9 @@ class StatusEnum(Enum): DELETED = "deleted" -class DeleteDocumentResponse(object): +class DeleteDocumentResponse(): """ - DeleteDocumentResponse. + Information returned when a document is deleted. :attr str document_id: (optional) The unique identifier of the document. :attr str status: (optional) Status of the document. A deleted document has the @@ -5340,12 +4998,12 @@ def __init__(self, *, document_id=None, status=None): def _from_dict(cls, _dict): """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} - validKeys = ['document_id', 'status'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document_id', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DeleteDocumentResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'status' in _dict: @@ -5382,9 +5040,9 @@ class StatusEnum(Enum): DELETED = "deleted" -class DeleteEnvironmentResponse(object): +class DeleteEnvironmentResponse(): """ - DeleteEnvironmentResponse. + Response object returned when deleting an environment. :attr str environment_id: The unique identifier for the environment. :attr str status: Status of the environment. @@ -5404,12 +5062,12 @@ def __init__(self, environment_id, status): def _from_dict(cls, _dict): """Initialize a DeleteEnvironmentResponse object from a json dictionary.""" args = {} - validKeys = ['environment_id', 'status'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['environment_id', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DeleteEnvironmentResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') else: @@ -5454,7 +5112,7 @@ class StatusEnum(Enum): DELETED = "deleted" -class DiskUsage(object): +class DiskUsage(): """ Summary of the disk usage statistics for the environment. @@ -5480,12 +5138,12 @@ def __init__(self, *, used_bytes=None, maximum_allowed_bytes=None): def _from_dict(cls, _dict): """Initialize a DiskUsage object from a json dictionary.""" args = {} - validKeys = ['used_bytes', 'maximum_allowed_bytes'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['used_bytes', 'maximum_allowed_bytes'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DiskUsage: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'used_bytes' in _dict: args['used_bytes'] = _dict.get('used_bytes') if 'maximum_allowed_bytes' in _dict: @@ -5517,9 +5175,9 @@ def __ne__(self, other): return not self == other -class DocumentAccepted(object): +class DocumentAccepted(): """ - DocumentAccepted. + Information returned after an uploaded document is accepted. :attr str document_id: (optional) The unique identifier of the ingested document. @@ -5552,12 +5210,12 @@ def __init__(self, *, document_id=None, status=None, notices=None): def _from_dict(cls, _dict): """Initialize a DocumentAccepted object from a json dictionary.""" args = {} - validKeys = ['document_id', 'status', 'notices'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document_id', 'status', 'notices'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DocumentAccepted: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'status' in _dict: @@ -5603,9 +5261,9 @@ class StatusEnum(Enum): PENDING = "pending" -class DocumentCounts(object): +class DocumentCounts(): """ - DocumentCounts. + Object containing collection document count information. :attr int available: (optional) The total number of available documents in the collection. @@ -5644,12 +5302,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a DocumentCounts object from a json dictionary.""" args = {} - validKeys = ['available', 'processing', 'failed', 'pending'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['available', 'processing', 'failed', 'pending'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DocumentCounts: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'available' in _dict: args['available'] = _dict.get('available') if 'processing' in _dict: @@ -5688,78 +5346,7 @@ def __ne__(self, other): return not self == other -class DocumentSnapshot(object): - """ - DocumentSnapshot. - - :attr str step: (optional) The step in the document conversion process that the - snapshot object represents. - :attr dict snapshot: (optional) Snapshot of the conversion. - """ - - def __init__(self, *, step=None, snapshot=None): - """ - Initialize a DocumentSnapshot object. - - :param str step: (optional) The step in the document conversion process - that the snapshot object represents. - :param dict snapshot: (optional) Snapshot of the conversion. - """ - self.step = step - self.snapshot = snapshot - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentSnapshot object from a json dictionary.""" - args = {} - validKeys = ['step', 'snapshot'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentSnapshot: ' - + ', '.join(badKeys)) - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot - return _dict - - def __str__(self): - """Return a `str` version of this DocumentSnapshot object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StepEnum(Enum): - """ - The step in the document conversion process that the snapshot object represents. - """ - HTML_INPUT = "html_input" - HTML_OUTPUT = "html_output" - JSON_OUTPUT = "json_output" - JSON_NORMALIZATIONS_OUTPUT = "json_normalizations_output" - ENRICHMENTS_OUTPUT = "enrichments_output" - NORMALIZATIONS_OUTPUT = "normalizations_output" - - -class DocumentStatus(object): +class DocumentStatus(): """ Status information about a submitted document. @@ -5815,15 +5402,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a DocumentStatus object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'document_id', 'configuration_id', 'status', 'status_description', 'filename', 'file_type', 'sha1', 'notices' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DocumentStatus: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') else: @@ -5918,9 +5505,10 @@ class FileTypeEnum(Enum): JSON = "json" -class Enrichment(object): +class Enrichment(): """ - Enrichment. + Enrichment step to perform on the document. Each enrichment is performed on the + specified field in the order that they are listed in the configuration. :attr str description: (optional) Describes what the enrichment step does. :attr str destination_field: Field where enrichments will be stored. This field @@ -5997,15 +5585,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Enrichment object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'description', 'destination_field', 'source_field', 'overwrite', 'enrichment', 'ignore_downstream_errors', 'options' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Enrichment: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'description' in _dict: args['description'] = _dict.get('description') if 'destination_field' in _dict: @@ -6071,11 +5659,12 @@ def __ne__(self, other): return not self == other -class EnrichmentOptions(object): +class EnrichmentOptions(): """ Options which are specific to a particular enrichment. - :attr NluEnrichmentFeatures features: (optional) + :attr NluEnrichmentFeatures features: (optional) Object containing Natural + Language Understanding features to be used. :attr str language: (optional) ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` @@ -6090,7 +5679,8 @@ def __init__(self, *, features=None, language=None, model=None): """ Initialize a EnrichmentOptions object. - :param NluEnrichmentFeatures features: (optional) + :param NluEnrichmentFeatures features: (optional) Object containing Natural + Language Understanding features to be used. :param str language: (optional) ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes are `ar` (Arabic), `en` (English), @@ -6108,12 +5698,12 @@ def __init__(self, *, features=None, language=None, model=None): def _from_dict(cls, _dict): """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} - validKeys = ['features', 'language', 'model'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['features', 'language', 'model'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EnrichmentOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'features' in _dict: args['features'] = NluEnrichmentFeatures._from_dict( _dict.get('features')) @@ -6167,7 +5757,7 @@ class LanguageEnum(Enum): SV = "sv" -class Environment(object): +class Environment(): """ Details about an environment. @@ -6249,16 +5839,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Environment object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'environment_id', 'name', 'description', 'created', 'updated', 'status', 'read_only', 'size', 'requested_size', 'index_capacity', 'search_status' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Environment: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') if 'name' in _dict: @@ -6353,7 +5943,7 @@ class SizeEnum(Enum): XXXL = "XXXL" -class EnvironmentDocuments(object): +class EnvironmentDocuments(): """ Summary of the document usage statistics for the environment. @@ -6378,12 +5968,12 @@ def __init__(self, *, indexed=None, maximum_allowed=None): def _from_dict(cls, _dict): """Initialize a EnvironmentDocuments object from a json dictionary.""" args = {} - validKeys = ['indexed', 'maximum_allowed'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['indexed', 'maximum_allowed'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EnvironmentDocuments: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'indexed' in _dict: args['indexed'] = _dict.get('indexed') if 'maximum_allowed' in _dict: @@ -6415,7 +6005,7 @@ def __ne__(self, other): return not self == other -class EventData(object): +class EventData(): """ Query event data object. @@ -6477,15 +6067,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a EventData object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'environment_id', 'session_token', 'client_timestamp', 'display_rank', 'collection_id', 'document_id', 'query_id' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EventData: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') else: @@ -6555,7 +6145,7 @@ def __ne__(self, other): return not self == other -class Expansion(object): +class Expansion(): """ An expansion definition. Each object respresents one set of expandable strings. For example, you could have expansions for the word `hot` in one object, and expansions @@ -6586,12 +6176,12 @@ def __init__(self, expanded_terms, *, input_terms=None): def _from_dict(cls, _dict): """Initialize a Expansion object from a json dictionary.""" args = {} - validKeys = ['input_terms', 'expanded_terms'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['input_terms', 'expanded_terms'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Expansion: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'input_terms' in _dict: args['input_terms'] = _dict.get('input_terms') if 'expanded_terms' in _dict: @@ -6626,7 +6216,7 @@ def __ne__(self, other): return not self == other -class Expansions(object): +class Expansions(): """ The query expansion definitions for the specified collection. @@ -6669,12 +6259,12 @@ def __init__(self, expansions): def _from_dict(cls, _dict): """Initialize a Expansions object from a json dictionary.""" args = {} - validKeys = ['expansions'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['expansions'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Expansions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'expansions' in _dict: args['expansions'] = [ Expansion._from_dict(x) for x in (_dict.get('expansions')) @@ -6707,9 +6297,9 @@ def __ne__(self, other): return not self == other -class Field(object): +class Field(): """ - Field. + Object containing field details. :attr str field: (optional) The name of the field. :attr str type: (optional) The type of the field. @@ -6729,12 +6319,12 @@ def __init__(self, *, field=None, type=None): def _from_dict(cls, _dict): """Initialize a Field object from a json dictionary.""" args = {} - validKeys = ['field', 'type'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['field', 'type'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Field: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'field' in _dict: args['field'] = _dict.get('field') if 'type' in _dict: @@ -6781,7 +6371,7 @@ class TypeEnum(Enum): BINARY = "binary" -class Filter(object): +class Filter(): """ Filter. @@ -6813,12 +6403,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Filter object from a json dictionary.""" args = {} - validKeys = ['match'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['match'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Filter: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'match' in _dict: args['match'] = _dict.get('match') return cls(**args) @@ -6845,9 +6435,9 @@ def __ne__(self, other): return not self == other -class FontSetting(object): +class FontSetting(): """ - FontSetting. + Font matching configuration. :attr int level: (optional) The HTML heading level that any content with the matching font is converted to. @@ -6890,12 +6480,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a FontSetting object from a json dictionary.""" args = {} - validKeys = ['level', 'min_size', 'max_size', 'bold', 'italic', 'name'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['level', 'min_size', 'max_size', 'bold', 'italic', 'name'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class FontSetting: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'level' in _dict: args['level'] = _dict.get('level') if 'min_size' in _dict: @@ -6942,7 +6532,7 @@ def __ne__(self, other): return not self == other -class Gateway(object): +class Gateway(): """ Object describing a specific gateway. @@ -6988,12 +6578,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Gateway object from a json dictionary.""" args = {} - validKeys = ['gateway_id', 'name', 'status', 'token', 'token_id'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['gateway_id', 'name', 'status', 'token', 'token_id'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Gateway: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'gateway_id' in _dict: args['gateway_id'] = _dict.get('gateway_id') if 'name' in _dict: @@ -7044,7 +6634,7 @@ class StatusEnum(Enum): IDLE = "idle" -class GatewayDelete(object): +class GatewayDelete(): """ Gatway deletion confirmation. @@ -7066,12 +6656,12 @@ def __init__(self, *, gateway_id=None, status=None): def _from_dict(cls, _dict): """Initialize a GatewayDelete object from a json dictionary.""" args = {} - validKeys = ['gateway_id', 'status'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['gateway_id', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class GatewayDelete: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'gateway_id' in _dict: args['gateway_id'] = _dict.get('gateway_id') if 'status' in _dict: @@ -7102,7 +6692,7 @@ def __ne__(self, other): return not self == other -class GatewayList(object): +class GatewayList(): """ Object containing gateways array. @@ -7123,12 +6713,12 @@ def __init__(self, *, gateways=None): def _from_dict(cls, _dict): """Initialize a GatewayList object from a json dictionary.""" args = {} - validKeys = ['gateways'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['gateways'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class GatewayList: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'gateways' in _dict: args['gateways'] = [ Gateway._from_dict(x) for x in (_dict.get('gateways')) @@ -7157,7 +6747,7 @@ def __ne__(self, other): return not self == other -class Histogram(object): +class Histogram(): """ Histogram. @@ -7197,12 +6787,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Histogram object from a json dictionary.""" args = {} - validKeys = ['field', 'interval'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['field', 'interval'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Histogram: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'field' in _dict: args['field'] = _dict.get('field') if 'interval' in _dict: @@ -7233,7 +6823,7 @@ def __ne__(self, other): return not self == other -class HtmlSettings(object): +class HtmlSettings(): """ A list of HTML conversion settings. @@ -7241,8 +6831,10 @@ class HtmlSettings(object): excluded completely. :attr list[str] exclude_tags_keep_content: (optional) Array of HTML tags which are excluded but still retain content. - :attr XPathPatterns keep_content: (optional) - :attr XPathPatterns exclude_content: (optional) + :attr XPathPatterns keep_content: (optional) Object containing an array of + XPaths. + :attr XPathPatterns exclude_content: (optional) Object containing an array of + XPaths. :attr list[str] keep_tag_attributes: (optional) An array of HTML tag attributes to keep in the converted document. :attr list[str] exclude_tag_attributes: (optional) Array of HTML tag attributes @@ -7264,8 +6856,10 @@ def __init__(self, that are excluded completely. :param list[str] exclude_tags_keep_content: (optional) Array of HTML tags which are excluded but still retain content. - :param XPathPatterns keep_content: (optional) - :param XPathPatterns exclude_content: (optional) + :param XPathPatterns keep_content: (optional) Object containing an array of + XPaths. + :param XPathPatterns exclude_content: (optional) Object containing an array + of XPaths. :param list[str] keep_tag_attributes: (optional) An array of HTML tag attributes to keep in the converted document. :param list[str] exclude_tag_attributes: (optional) Array of HTML tag @@ -7282,16 +6876,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a HtmlSettings object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'exclude_tags_completely', 'exclude_tags_keep_content', 'keep_content', 'exclude_content', 'keep_tag_attributes', 'exclude_tag_attributes' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class HtmlSettings: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'exclude_tags_completely' in _dict: args['exclude_tags_completely'] = _dict.get( 'exclude_tags_completely') @@ -7348,7 +6942,7 @@ def __ne__(self, other): return not self == other -class IndexCapacity(object): +class IndexCapacity(): """ Details about the resource usage and capacity of the environment. @@ -7379,12 +6973,12 @@ def __init__(self, *, documents=None, disk_usage=None, collections=None): def _from_dict(cls, _dict): """Initialize a IndexCapacity object from a json dictionary.""" args = {} - validKeys = ['documents', 'disk_usage', 'collections'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['documents', 'disk_usage', 'collections'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class IndexCapacity: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'documents' in _dict: args['documents'] = EnvironmentDocuments._from_dict( _dict.get('documents')) @@ -7421,7 +7015,7 @@ def __ne__(self, other): return not self == other -class ListCollectionFieldsResponse(object): +class ListCollectionFieldsResponse(): """ The list of fetched fields. The fields are returned using a fully qualified name format, however, the format @@ -7451,12 +7045,12 @@ def __init__(self, *, fields=None): def _from_dict(cls, _dict): """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" args = {} - validKeys = ['fields'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['fields'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ListCollectionFieldsResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'fields' in _dict: args['fields'] = [ Field._from_dict(x) for x in (_dict.get('fields')) @@ -7485,9 +7079,9 @@ def __ne__(self, other): return not self == other -class ListCollectionsResponse(object): +class ListCollectionsResponse(): """ - ListCollectionsResponse. + Response object containing an array of collection details. :attr list[Collection] collections: (optional) An array containing information about each collection in the environment. @@ -7506,12 +7100,12 @@ def __init__(self, *, collections=None): def _from_dict(cls, _dict): """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} - validKeys = ['collections'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['collections'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ListCollectionsResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'collections' in _dict: args['collections'] = [ Collection._from_dict(x) for x in (_dict.get('collections')) @@ -7540,11 +7134,11 @@ def __ne__(self, other): return not self == other -class ListConfigurationsResponse(object): +class ListConfigurationsResponse(): """ - ListConfigurationsResponse. + Object containing an array of available configurations. - :attr list[Configuration] configurations: (optional) An array of Configurations + :attr list[Configuration] configurations: (optional) An array of configurations that are available for the service instance. """ @@ -7553,7 +7147,7 @@ def __init__(self, *, configurations=None): Initialize a ListConfigurationsResponse object. :param list[Configuration] configurations: (optional) An array of - Configurations that are available for the service instance. + configurations that are available for the service instance. """ self.configurations = configurations @@ -7561,12 +7155,12 @@ def __init__(self, *, configurations=None): def _from_dict(cls, _dict): """Initialize a ListConfigurationsResponse object from a json dictionary.""" args = {} - validKeys = ['configurations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['configurations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ListConfigurationsResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'configurations' in _dict: args['configurations'] = [ Configuration._from_dict(x) @@ -7598,9 +7192,9 @@ def __ne__(self, other): return not self == other -class ListEnvironmentsResponse(object): +class ListEnvironmentsResponse(): """ - ListEnvironmentsResponse. + Response object containing an array of configured environments. :attr list[Environment] environments: (optional) An array of [environments] that are available for the service instance. @@ -7619,12 +7213,12 @@ def __init__(self, *, environments=None): def _from_dict(cls, _dict): """Initialize a ListEnvironmentsResponse object from a json dictionary.""" args = {} - validKeys = ['environments'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['environments'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ListEnvironmentsResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'environments' in _dict: args['environments'] = [ Environment._from_dict(x) for x in (_dict.get('environments')) @@ -7653,7 +7247,7 @@ def __ne__(self, other): return not self == other -class LogQueryResponse(object): +class LogQueryResponse(): """ Object containing results that match the requested **logs** query. @@ -7677,12 +7271,12 @@ def __init__(self, *, matching_results=None, results=None): def _from_dict(cls, _dict): """Initialize a LogQueryResponse object from a json dictionary.""" args = {} - validKeys = ['matching_results', 'results'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['matching_results', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class LogQueryResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: @@ -7717,7 +7311,7 @@ def __ne__(self, other): return not self == other -class LogQueryResponseResult(object): +class LogQueryResponseResult(): """ Individual result object for a **logs** query. Each object represents either a query to a Discovery collection or an event that is associated with a query. @@ -7863,17 +7457,17 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a LogQueryResponseResult object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'environment_id', 'customer_id', 'document_type', 'natural_language_query', 'document_results', 'created_timestamp', 'client_timestamp', 'query_id', 'session_token', 'collection_id', 'display_rank', 'document_id', 'event_type', 'result_type' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class LogQueryResponseResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') if 'customer_id' in _dict: @@ -7988,7 +7582,7 @@ class ResultTypeEnum(Enum): DOCUMENT = "document" -class LogQueryResponseResultDocuments(object): +class LogQueryResponseResultDocuments(): """ Object containing result information that was returned by the query used to create this log entry. Only returned with logs of type `query`. @@ -8015,12 +7609,12 @@ def __init__(self, *, results=None, count=None): def _from_dict(cls, _dict): """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" args = {} - validKeys = ['results', 'count'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['results', 'count'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class LogQueryResponseResultDocuments: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'results' in _dict: args['results'] = [ LogQueryResponseResultDocumentsResult._from_dict(x) @@ -8054,7 +7648,7 @@ def __ne__(self, other): return not self == other -class LogQueryResponseResultDocumentsResult(object): +class LogQueryResponseResultDocumentsResult(): """ Each object in the **results** array corresponds to an individual document returned by the original query. @@ -8102,14 +7696,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a LogQueryResponseResultDocumentsResult object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'position', 'document_id', 'score', 'confidence', 'collection_id' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class LogQueryResponseResultDocumentsResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'position' in _dict: args['position'] = _dict.get('position') if 'document_id' in _dict: @@ -8152,7 +7746,7 @@ def __ne__(self, other): return not self == other -class MetricAggregation(object): +class MetricAggregation(): """ An aggregation analyzing log information for queries and events. @@ -8183,12 +7777,12 @@ def __init__(self, *, interval=None, event_type=None, results=None): def _from_dict(cls, _dict): """Initialize a MetricAggregation object from a json dictionary.""" args = {} - validKeys = ['interval', 'event_type', 'results'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['interval', 'event_type', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MetricAggregation: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'interval' in _dict: args['interval'] = _dict.get('interval') if 'event_type' in _dict: @@ -8226,7 +7820,7 @@ def __ne__(self, other): return not self == other -class MetricAggregationResult(object): +class MetricAggregationResult(): """ Aggregation result data for the requested metric. @@ -8267,12 +7861,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a MetricAggregationResult object from a json dictionary.""" args = {} - validKeys = ['key_as_string', 'key', 'matching_results', 'event_rate'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['key_as_string', 'key', 'matching_results', 'event_rate'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MetricAggregationResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'key_as_string' in _dict: args['key_as_string'] = string_to_datetime( _dict.get('key_as_string')) @@ -8313,7 +7907,7 @@ def __ne__(self, other): return not self == other -class MetricResponse(object): +class MetricResponse(): """ The response generated from a call to a **metrics** method. @@ -8334,12 +7928,12 @@ def __init__(self, *, aggregations=None): def _from_dict(cls, _dict): """Initialize a MetricResponse object from a json dictionary.""" args = {} - validKeys = ['aggregations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MetricResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'aggregations' in _dict: args['aggregations'] = [ MetricAggregation._from_dict(x) @@ -8369,7 +7963,7 @@ def __ne__(self, other): return not self == other -class MetricTokenAggregation(object): +class MetricTokenAggregation(): """ An aggregation analyzing log information for queries and events. @@ -8395,12 +7989,12 @@ def __init__(self, *, event_type=None, results=None): def _from_dict(cls, _dict): """Initialize a MetricTokenAggregation object from a json dictionary.""" args = {} - validKeys = ['event_type', 'results'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['event_type', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MetricTokenAggregation: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'event_type' in _dict: args['event_type'] = _dict.get('event_type') if 'results' in _dict: @@ -8434,7 +8028,7 @@ def __ne__(self, other): return not self == other -class MetricTokenAggregationResult(object): +class MetricTokenAggregationResult(): """ Aggregation result data for the requested metric. @@ -8465,12 +8059,12 @@ def __init__(self, *, key=None, matching_results=None, event_rate=None): def _from_dict(cls, _dict): """Initialize a MetricTokenAggregationResult object from a json dictionary.""" args = {} - validKeys = ['key', 'matching_results', 'event_rate'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['key', 'matching_results', 'event_rate'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MetricTokenAggregationResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'key' in _dict: args['key'] = _dict.get('key') if 'matching_results' in _dict: @@ -8506,7 +8100,7 @@ def __ne__(self, other): return not self == other -class MetricTokenResponse(object): +class MetricTokenResponse(): """ The response generated from a call to a **metrics** method that evaluates tokens. @@ -8527,12 +8121,12 @@ def __init__(self, *, aggregations=None): def _from_dict(cls, _dict): """Initialize a MetricTokenResponse object from a json dictionary.""" args = {} - validKeys = ['aggregations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MetricTokenResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'aggregations' in _dict: args['aggregations'] = [ MetricTokenAggregation._from_dict(x) @@ -8562,7 +8156,7 @@ def __ne__(self, other): return not self == other -class Nested(object): +class Nested(): """ Nested. @@ -8596,12 +8190,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Nested object from a json dictionary.""" args = {} - validKeys = ['path'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['path'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Nested: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'path' in _dict: args['path'] = _dict.get('path') return cls(**args) @@ -8628,7 +8222,7 @@ def __ne__(self, other): return not self == other -class NluEnrichmentCategories(object): +class NluEnrichmentCategories(): """ An object that indicates the Categories enrichment will be applied to the specified field. @@ -8665,8 +8259,8 @@ def _to_dict(self): def __setattr__(self, name, value): properties = {} if not hasattr(self, '_additionalProperties'): - super(NluEnrichmentCategories, self).__setattr__( - '_additionalProperties', set()) + super(NluEnrichmentCategories, + self).__setattr__('_additionalProperties', set()) if name not in properties: self._additionalProperties.add(name) super(NluEnrichmentCategories, self).__setattr__(name, value) @@ -8686,7 +8280,7 @@ def __ne__(self, other): return not self == other -class NluEnrichmentConcepts(object): +class NluEnrichmentConcepts(): """ An object specifiying the concepts enrichment and related parameters. @@ -8707,12 +8301,12 @@ def __init__(self, *, limit=None): def _from_dict(cls, _dict): """Initialize a NluEnrichmentConcepts object from a json dictionary.""" args = {} - validKeys = ['limit'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['limit'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class NluEnrichmentConcepts: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) @@ -8739,7 +8333,7 @@ def __ne__(self, other): return not self == other -class NluEnrichmentEmotion(object): +class NluEnrichmentEmotion(): """ An object specifying the emotion detection enrichment and related parameters. @@ -8765,12 +8359,12 @@ def __init__(self, *, document=None, targets=None): def _from_dict(cls, _dict): """Initialize a NluEnrichmentEmotion object from a json dictionary.""" args = {} - validKeys = ['document', 'targets'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document', 'targets'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class NluEnrichmentEmotion: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: @@ -8801,7 +8395,7 @@ def __ne__(self, other): return not self == other -class NluEnrichmentEntities(object): +class NluEnrichmentEntities(): """ An object speficying the Entities enrichment and related parameters. @@ -8819,8 +8413,8 @@ class NluEnrichmentEntities(object): locations for each instance of each identified entity is recorded. The default is `false`. :attr str model: (optional) The enrichement model to use with entity extraction. - May be a custom model provided by Watson Knowledge Studio, the public model for - use with Knowledge Graph `en-news`, or the default public model `alchemy`. + May be a custom model provided by Watson Knowledge Studio, or the default public + model `alchemy`. """ def __init__(self, @@ -8849,9 +8443,8 @@ def __init__(self, locations for each instance of each identified entity is recorded. The default is `false`. :param str model: (optional) The enrichement model to use with entity - extraction. May be a custom model provided by Watson Knowledge Studio, the - public model for use with Knowledge Graph `en-news`, or the default public - model `alchemy`. + extraction. May be a custom model provided by Watson Knowledge Studio, or + the default public model `alchemy`. """ self.sentiment = sentiment self.emotion = emotion @@ -8865,15 +8458,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a NluEnrichmentEntities object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'sentiment', 'emotion', 'limit', 'mentions', 'mention_types', 'sentence_locations', 'model' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class NluEnrichmentEntities: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'sentiment' in _dict: args['sentiment'] = _dict.get('sentiment') if 'emotion' in _dict: @@ -8926,9 +8519,9 @@ def __ne__(self, other): return not self == other -class NluEnrichmentFeatures(object): +class NluEnrichmentFeatures(): """ - NluEnrichmentFeatures. + Object containing Natural Language Understanding features to be used. :attr NluEnrichmentKeywords keywords: (optional) An object specifying the Keyword enrichment and related parameters. @@ -8991,15 +8584,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a NluEnrichmentFeatures object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'keywords', 'entities', 'sentiment', 'emotion', 'categories', 'semantic_roles', 'relations', 'concepts' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class NluEnrichmentFeatures: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'keywords' in _dict: args['keywords'] = NluEnrichmentKeywords._from_dict( _dict.get('keywords')) @@ -9062,7 +8655,7 @@ def __ne__(self, other): return not self == other -class NluEnrichmentKeywords(object): +class NluEnrichmentKeywords(): """ An object specifying the Keyword enrichment and related parameters. @@ -9093,12 +8686,12 @@ def __init__(self, *, sentiment=None, emotion=None, limit=None): def _from_dict(cls, _dict): """Initialize a NluEnrichmentKeywords object from a json dictionary.""" args = {} - validKeys = ['sentiment', 'emotion', 'limit'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['sentiment', 'emotion', 'limit'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class NluEnrichmentKeywords: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'sentiment' in _dict: args['sentiment'] = _dict.get('sentiment') if 'emotion' in _dict: @@ -9133,14 +8726,14 @@ def __ne__(self, other): return not self == other -class NluEnrichmentRelations(object): +class NluEnrichmentRelations(): """ An object specifying the relations enrichment and related parameters. :attr str model: (optional) *For use with `natural_language_understanding` enrichments only.* The enrichement model to use with relationship extraction. - May be a custom model provided by Watson Knowledge Studio, the public model for - use with Knowledge Graph `en-news`, the default is`en-news`. + May be a custom model provided by Watson Knowledge Studio, the default public + model is`en-news`. """ def __init__(self, *, model=None): @@ -9150,8 +8743,7 @@ def __init__(self, *, model=None): :param str model: (optional) *For use with `natural_language_understanding` enrichments only.* The enrichement model to use with relationship extraction. May be a custom model provided by Watson Knowledge Studio, the - public model for use with Knowledge Graph `en-news`, the default - is`en-news`. + default public model is`en-news`. """ self.model = model @@ -9159,12 +8751,12 @@ def __init__(self, *, model=None): def _from_dict(cls, _dict): """Initialize a NluEnrichmentRelations object from a json dictionary.""" args = {} - validKeys = ['model'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['model'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class NluEnrichmentRelations: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'model' in _dict: args['model'] = _dict.get('model') return cls(**args) @@ -9191,7 +8783,7 @@ def __ne__(self, other): return not self == other -class NluEnrichmentSemanticRoles(object): +class NluEnrichmentSemanticRoles(): """ An object specifiying the semantic roles enrichment and related parameters. @@ -9222,12 +8814,12 @@ def __init__(self, *, entities=None, keywords=None, limit=None): def _from_dict(cls, _dict): """Initialize a NluEnrichmentSemanticRoles object from a json dictionary.""" args = {} - validKeys = ['entities', 'keywords', 'limit'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['entities', 'keywords', 'limit'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class NluEnrichmentSemanticRoles: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'entities' in _dict: args['entities'] = _dict.get('entities') if 'keywords' in _dict: @@ -9262,7 +8854,7 @@ def __ne__(self, other): return not self == other -class NluEnrichmentSentiment(object): +class NluEnrichmentSentiment(): """ An object specifying the sentiment extraction enrichment and related parameters. @@ -9288,12 +8880,12 @@ def __init__(self, *, document=None, targets=None): def _from_dict(cls, _dict): """Initialize a NluEnrichmentSentiment object from a json dictionary.""" args = {} - validKeys = ['document', 'targets'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document', 'targets'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class NluEnrichmentSentiment: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: @@ -9324,9 +8916,9 @@ def __ne__(self, other): return not self == other -class NormalizationOperation(object): +class NormalizationOperation(): """ - NormalizationOperation. + Object containing normalization operations. :attr str operation: (optional) Identifies what type of operation to perform. **copy** - Copies the value of the **source_field** to the **destination_field** @@ -9404,12 +8996,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a NormalizationOperation object from a json dictionary.""" args = {} - validKeys = ['operation', 'source_field', 'destination_field'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['operation', 'source_field', 'destination_field'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class NormalizationOperation: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'operation' in _dict: args['operation'] = _dict.get('operation') if 'source_field' in _dict: @@ -9478,7 +9070,7 @@ class OperationEnum(Enum): REMOVE_NULLS = "remove_nulls" -class Notice(object): +class Notice(): """ A notice produced for the collection. @@ -9559,15 +9151,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Notice object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'notice_id', 'created', 'document_id', 'query_id', 'severity', 'step', 'description' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Notice: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'notice_id' in _dict: args['notice_id'] = _dict.get('notice_id') if 'created' in _dict: @@ -9625,18 +9217,19 @@ class SeverityEnum(Enum): ERROR = "error" -class PdfHeadingDetection(object): +class PdfHeadingDetection(): """ - PdfHeadingDetection. + Object containing heading detection conversion settings for PDF documents. - :attr list[FontSetting] fonts: (optional) + :attr list[FontSetting] fonts: (optional) Array of font matching configurations. """ def __init__(self, *, fonts=None): """ Initialize a PdfHeadingDetection object. - :param list[FontSetting] fonts: (optional) + :param list[FontSetting] fonts: (optional) Array of font matching + configurations. """ self.fonts = fonts @@ -9644,12 +9237,12 @@ def __init__(self, *, fonts=None): def _from_dict(cls, _dict): """Initialize a PdfHeadingDetection object from a json dictionary.""" args = {} - validKeys = ['fonts'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['fonts'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class PdfHeadingDetection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'fonts' in _dict: args['fonts'] = [ FontSetting._from_dict(x) for x in (_dict.get('fonts')) @@ -9678,18 +9271,20 @@ def __ne__(self, other): return not self == other -class PdfSettings(object): +class PdfSettings(): """ A list of PDF conversion settings. - :attr PdfHeadingDetection heading: (optional) + :attr PdfHeadingDetection heading: (optional) Object containing heading + detection conversion settings for PDF documents. """ def __init__(self, *, heading=None): """ Initialize a PdfSettings object. - :param PdfHeadingDetection heading: (optional) + :param PdfHeadingDetection heading: (optional) Object containing heading + detection conversion settings for PDF documents. """ self.heading = heading @@ -9697,12 +9292,12 @@ def __init__(self, *, heading=None): def _from_dict(cls, _dict): """Initialize a PdfSettings object from a json dictionary.""" args = {} - validKeys = ['heading'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['heading'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class PdfSettings: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'heading' in _dict: args['heading'] = PdfHeadingDetection._from_dict( _dict.get('heading')) @@ -9730,7 +9325,7 @@ def __ne__(self, other): return not self == other -class QueryAggregation(object): +class QueryAggregation(): """ An aggregation produced by Discovery to analyze the input provided. @@ -9768,12 +9363,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a QueryAggregation object from a json dictionary.""" args = {} - validKeys = ['type', 'results', 'matching_results', 'aggregations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['type', 'results', 'matching_results', 'aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class QueryAggregation: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'results' in _dict: @@ -9818,52 +9413,99 @@ def __ne__(self, other): return not self == other -class QueryEntitiesContext(object): +class QueryNoticesResponse(): """ - Entity text to provide context for the queried entity and rank based on that - association. For example, if you wanted to query the city of London in England your - query would look for `London` with the context of `England`. + Object containing notice query results. - :attr str text: (optional) Entity text to provide context for the queried entity - and rank based on that association. For example, if you wanted to query the city - of London in England your query would look for `London` with the context of - `England`. + :attr int matching_results: (optional) The number of matching results. + :attr list[QueryNoticesResult] results: (optional) Array of document results + that match the query. + :attr list[QueryAggregation] aggregations: (optional) Array of aggregation + results that match the query. + :attr list[QueryPassages] passages: (optional) Array of passage results that + match the query. + :attr int duplicates_removed: (optional) The number of duplicates removed from + this notices query. """ - def __init__(self, *, text=None): + def __init__(self, + *, + matching_results=None, + results=None, + aggregations=None, + passages=None, + duplicates_removed=None): """ - Initialize a QueryEntitiesContext object. + Initialize a QueryNoticesResponse object. - :param str text: (optional) Entity text to provide context for the queried - entity and rank based on that association. For example, if you wanted to - query the city of London in England your query would look for `London` with - the context of `England`. + :param int matching_results: (optional) The number of matching results. + :param list[QueryNoticesResult] results: (optional) Array of document + results that match the query. + :param list[QueryAggregation] aggregations: (optional) Array of aggregation + results that match the query. + :param list[QueryPassages] passages: (optional) Array of passage results + that match the query. + :param int duplicates_removed: (optional) The number of duplicates removed + from this notices query. """ - self.text = text + self.matching_results = matching_results + self.results = results + self.aggregations = aggregations + self.passages = passages + self.duplicates_removed = duplicates_removed @classmethod def _from_dict(cls, _dict): - """Initialize a QueryEntitiesContext object from a json dictionary.""" + """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} - validKeys = ['text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = [ + 'matching_results', 'results', 'aggregations', 'passages', + 'duplicates_removed' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryEntitiesContext: ' - + ', '.join(badKeys)) - if 'text' in _dict: - args['text'] = _dict.get('text') + 'Unrecognized keys detected in dictionary for class QueryNoticesResponse: ' + + ', '.join(bad_keys)) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'results' in _dict: + args['results'] = [ + QueryNoticesResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'passages' in _dict: + args['passages'] = [ + QueryPassages._from_dict(x) for x in (_dict.get('passages')) + ] + if 'duplicates_removed' in _dict: + args['duplicates_removed'] = _dict.get('duplicates_removed') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'passages') and self.passages is not None: + _dict['passages'] = [x._to_dict() for x in self.passages] + if hasattr( + self, + 'duplicates_removed') and self.duplicates_removed is not None: + _dict['duplicates_removed'] = self.duplicates_removed return _dict def __str__(self): - """Return a `str` version of this QueryEntitiesContext object.""" + """Return a `str` version of this QueryNoticesResponse object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): @@ -9877,1092 +9519,159 @@ def __ne__(self, other): return not self == other -class QueryEntitiesEntity(object): +class QueryNoticesResult(): """ - A text string that appears within the entity text field. - - :attr str text: (optional) Entity text content. - :attr str type: (optional) The type of the specified entity. - """ - - def __init__(self, *, text=None, type=None): - """ - Initialize a QueryEntitiesEntity object. + Query result object. - :param str text: (optional) Entity text content. - :param str type: (optional) The type of the specified entity. - """ - self.text = text - self.type = type - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryEntitiesEntity object from a json dictionary.""" - args = {} - validKeys = ['text', 'type'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryEntitiesEntity: ' - + ', '.join(badKeys)) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'type' in _dict: - args['type'] = _dict.get('type') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - return _dict - - def __str__(self): - """Return a `str` version of this QueryEntitiesEntity object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryEntitiesResponse(object): - """ - An object that contains an array of entities resulting from the query. - - :attr list[QueryEntitiesResponseItem] entities: (optional) Array of entities - that results from the query. - """ - - def __init__(self, *, entities=None): - """ - Initialize a QueryEntitiesResponse object. - - :param list[QueryEntitiesResponseItem] entities: (optional) Array of - entities that results from the query. - """ - self.entities = entities - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryEntitiesResponse object from a json dictionary.""" - args = {} - validKeys = ['entities'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryEntitiesResponse: ' - + ', '.join(badKeys)) - if 'entities' in _dict: - args['entities'] = [ - QueryEntitiesResponseItem._from_dict(x) - for x in (_dict.get('entities')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] - return _dict - - def __str__(self): - """Return a `str` version of this QueryEntitiesResponse object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryEntitiesResponseItem(object): - """ - Object containing Entity query response information. - - :attr str text: (optional) Entity text content. - :attr str type: (optional) The type of the result entity. - :attr list[QueryEvidence] evidence: (optional) List of different evidentiary - items to support the result. - """ - - def __init__(self, *, text=None, type=None, evidence=None): - """ - Initialize a QueryEntitiesResponseItem object. - - :param str text: (optional) Entity text content. - :param str type: (optional) The type of the result entity. - :param list[QueryEvidence] evidence: (optional) List of different - evidentiary items to support the result. - """ - self.text = text - self.type = type - self.evidence = evidence - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryEntitiesResponseItem object from a json dictionary.""" - args = {} - validKeys = ['text', 'type', 'evidence'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryEntitiesResponseItem: ' - + ', '.join(badKeys)) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'evidence' in _dict: - args['evidence'] = [ - QueryEvidence._from_dict(x) for x in (_dict.get('evidence')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'evidence') and self.evidence is not None: - _dict['evidence'] = [x._to_dict() for x in self.evidence] - return _dict - - def __str__(self): - """Return a `str` version of this QueryEntitiesResponseItem object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryEvidence(object): - """ - Description of evidence location supporting Knoweldge Graph query result. - - :attr str document_id: (optional) The docuemnt ID (as indexed in Discovery) of - the evidence location. - :attr str field: (optional) The field of the document where the supporting - evidence was identified. - :attr int start_offset: (optional) The start location of the evidence in the - identified field. This value is inclusive. - :attr int end_offset: (optional) The end location of the evidence in the - identified field. This value is inclusive. - :attr list[QueryEvidenceEntity] entities: (optional) An array of entity objects - that show evidence of the result. - """ - - def __init__(self, - *, - document_id=None, - field=None, - start_offset=None, - end_offset=None, - entities=None): - """ - Initialize a QueryEvidence object. - - :param str document_id: (optional) The docuemnt ID (as indexed in - Discovery) of the evidence location. - :param str field: (optional) The field of the document where the supporting - evidence was identified. - :param int start_offset: (optional) The start location of the evidence in - the identified field. This value is inclusive. - :param int end_offset: (optional) The end location of the evidence in the - identified field. This value is inclusive. - :param list[QueryEvidenceEntity] entities: (optional) An array of entity - objects that show evidence of the result. - """ - self.document_id = document_id - self.field = field - self.start_offset = start_offset - self.end_offset = end_offset - self.entities = entities - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryEvidence object from a json dictionary.""" - args = {} - validKeys = [ - 'document_id', 'field', 'start_offset', 'end_offset', 'entities' - ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryEvidence: ' - + ', '.join(badKeys)) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'entities' in _dict: - args['entities'] = [ - QueryEvidenceEntity._from_dict(x) - for x in (_dict.get('entities')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'start_offset') and self.start_offset is not None: - _dict['start_offset'] = self.start_offset - if hasattr(self, 'end_offset') and self.end_offset is not None: - _dict['end_offset'] = self.end_offset - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] - return _dict - - def __str__(self): - """Return a `str` version of this QueryEvidence object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryEvidenceEntity(object): - """ - Entity description and location within evidence field. - - :attr str type: (optional) The entity type for this entity. Possible types vary - based on model used. - :attr str text: (optional) The original text of this entity as found in the - evidence field. - :attr int start_offset: (optional) The start location of the entity text in the - identified field. This value is inclusive. - :attr int end_offset: (optional) The end location of the entity text in the - identified field. This value is exclusive. - """ - - def __init__(self, - *, - type=None, - text=None, - start_offset=None, - end_offset=None): - """ - Initialize a QueryEvidenceEntity object. - - :param str type: (optional) The entity type for this entity. Possible types - vary based on model used. - :param str text: (optional) The original text of this entity as found in - the evidence field. - :param int start_offset: (optional) The start location of the entity text - in the identified field. This value is inclusive. - :param int end_offset: (optional) The end location of the entity text in - the identified field. This value is exclusive. - """ - self.type = type - self.text = text - self.start_offset = start_offset - self.end_offset = end_offset - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryEvidenceEntity object from a json dictionary.""" - args = {} - validKeys = ['type', 'text', 'start_offset', 'end_offset'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryEvidenceEntity: ' - + ', '.join(badKeys)) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'start_offset') and self.start_offset is not None: - _dict['start_offset'] = self.start_offset - if hasattr(self, 'end_offset') and self.end_offset is not None: - _dict['end_offset'] = self.end_offset - return _dict - - def __str__(self): - """Return a `str` version of this QueryEvidenceEntity object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryFilterType(object): - """ - QueryFilterType. - - :attr list[str] exclude: (optional) A comma-separated list of types to exclude. - :attr list[str] include: (optional) A comma-separated list of types to include. - All other types are excluded. - """ - - def __init__(self, *, exclude=None, include=None): - """ - Initialize a QueryFilterType object. - - :param list[str] exclude: (optional) A comma-separated list of types to - exclude. - :param list[str] include: (optional) A comma-separated list of types to - include. All other types are excluded. - """ - self.exclude = exclude - self.include = include - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryFilterType object from a json dictionary.""" - args = {} - validKeys = ['exclude', 'include'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryFilterType: ' - + ', '.join(badKeys)) - if 'exclude' in _dict: - args['exclude'] = _dict.get('exclude') - if 'include' in _dict: - args['include'] = _dict.get('include') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'exclude') and self.exclude is not None: - _dict['exclude'] = self.exclude - if hasattr(self, 'include') and self.include is not None: - _dict['include'] = self.include - return _dict - - def __str__(self): - """Return a `str` version of this QueryFilterType object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNoticesResponse(object): - """ - QueryNoticesResponse. - - :attr int matching_results: (optional) The number of matching results. - :attr list[QueryNoticesResult] results: (optional) Array of document results - that match the query. - :attr list[QueryAggregation] aggregations: (optional) Array of aggregation - results that match the query. - :attr list[QueryPassages] passages: (optional) Array of passage results that - match the query. - :attr int duplicates_removed: (optional) The number of duplicates removed from - this notices query. - """ - - def __init__(self, - *, - matching_results=None, - results=None, - aggregations=None, - passages=None, - duplicates_removed=None): - """ - Initialize a QueryNoticesResponse object. - - :param int matching_results: (optional) The number of matching results. - :param list[QueryNoticesResult] results: (optional) Array of document - results that match the query. - :param list[QueryAggregation] aggregations: (optional) Array of aggregation - results that match the query. - :param list[QueryPassages] passages: (optional) Array of passage results - that match the query. - :param int duplicates_removed: (optional) The number of duplicates removed - from this notices query. - """ - self.matching_results = matching_results - self.results = results - self.aggregations = aggregations - self.passages = passages - self.duplicates_removed = duplicates_removed - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryNoticesResponse object from a json dictionary.""" - args = {} - validKeys = [ - 'matching_results', 'results', 'aggregations', 'passages', - 'duplicates_removed' - ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryNoticesResponse: ' - + ', '.join(badKeys)) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: - args['results'] = [ - QueryNoticesResult._from_dict(x) for x in (_dict.get('results')) - ] - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) - ] - if 'passages' in _dict: - args['passages'] = [ - QueryPassages._from_dict(x) for x in (_dict.get('passages')) - ] - if 'duplicates_removed' in _dict: - args['duplicates_removed'] = _dict.get('duplicates_removed') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] - if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x._to_dict() for x in self.passages] - if hasattr( - self, - 'duplicates_removed') and self.duplicates_removed is not None: - _dict['duplicates_removed'] = self.duplicates_removed - return _dict - - def __str__(self): - """Return a `str` version of this QueryNoticesResponse object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNoticesResult(object): - """ - QueryNoticesResult. - - :attr str id: (optional) The unique identifier of the document. - :attr dict metadata: (optional) Metadata of the document. - :attr str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :attr QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - :attr str title: (optional) Automatically extracted result title. - :attr int code: (optional) The internal status code returned by the ingestion - subsystem indicating the overall result of ingesting the source document. - :attr str filename: (optional) Name of the original source file (if available). - :attr str file_type: (optional) The type of the original source file. - :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted - as a hexadecimal string). - :attr list[Notice] notices: (optional) Array of notices for the document. - """ - - def __init__(self, - *, - id=None, - metadata=None, - collection_id=None, - result_metadata=None, - title=None, - code=None, - filename=None, - file_type=None, - sha1=None, - notices=None, - **kwargs): - """ - Initialize a QueryNoticesResult object. - - :param str id: (optional) The unique identifier of the document. - :param dict metadata: (optional) Metadata of the document. - :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - :param str title: (optional) Automatically extracted result title. - :param int code: (optional) The internal status code returned by the - ingestion subsystem indicating the overall result of ingesting the source - document. - :param str filename: (optional) Name of the original source file (if - available). - :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file - (formatted as a hexadecimal string). - :param list[Notice] notices: (optional) Array of notices for the document. - :param **kwargs: (optional) Any additional properties. - """ - self.id = id - self.metadata = metadata - self.collection_id = collection_id - self.result_metadata = result_metadata - self.title = title - self.code = code - self.filename = filename - self.file_type = file_type - self.sha1 = sha1 - self.notices = notices - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryNoticesResult object from a json dictionary.""" - args = {} - xtra = _dict.copy() - if 'id' in _dict: - args['id'] = _dict.get('id') - del xtra['id'] - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - del xtra['metadata'] - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - del xtra['collection_id'] - if 'result_metadata' in _dict: - args['result_metadata'] = QueryResultMetadata._from_dict( - _dict.get('result_metadata')) - del xtra['result_metadata'] - if 'title' in _dict: - args['title'] = _dict.get('title') - del xtra['title'] - if 'code' in _dict: - args['code'] = _dict.get('code') - del xtra['code'] - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - del xtra['filename'] - if 'file_type' in _dict: - args['file_type'] = _dict.get('file_type') - del xtra['file_type'] - if 'sha1' in _dict: - args['sha1'] = _dict.get('sha1') - del xtra['sha1'] - if 'notices' in _dict: - args['notices'] = [ - Notice._from_dict(x) for x in (_dict.get('notices')) - ] - del xtra['notices'] - args.update(xtra) - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata._to_dict() - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, 'file_type') and self.file_type is not None: - _dict['file_type'] = self.file_type - if hasattr(self, 'sha1') and self.sha1 is not None: - _dict['sha1'] = self.sha1 - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x._to_dict() for x in self.notices] - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value - return _dict - - def __setattr__(self, name, value): - properties = { - 'id', 'metadata', 'collection_id', 'result_metadata', 'title', - 'code', 'filename', 'file_type', 'sha1', 'notices' - } - if not hasattr(self, '_additionalProperties'): - super(QueryNoticesResult, self).__setattr__('_additionalProperties', - set()) - if name not in properties: - self._additionalProperties.add(name) - super(QueryNoticesResult, self).__setattr__(name, value) - - def __str__(self): - """Return a `str` version of this QueryNoticesResult object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class FileTypeEnum(Enum): - """ - The type of the original source file. - """ - PDF = "pdf" - HTML = "html" - WORD = "word" - JSON = "json" - - -class QueryPassages(object): - """ - QueryPassages. - - :attr str document_id: (optional) The unique identifier of the document from - which the passage has been extracted. - :attr float passage_score: (optional) The confidence score of the passages's - analysis. A higher score indicates greater confidence. - :attr str passage_text: (optional) The content of the extracted passage. - :attr int start_offset: (optional) The position of the first character of the - extracted passage in the originating field. - :attr int end_offset: (optional) The position of the last character of the - extracted passage in the originating field. - :attr str field: (optional) The label of the field from which the passage has - been extracted. - """ - - def __init__(self, - *, - document_id=None, - passage_score=None, - passage_text=None, - start_offset=None, - end_offset=None, - field=None): - """ - Initialize a QueryPassages object. - - :param str document_id: (optional) The unique identifier of the document - from which the passage has been extracted. - :param float passage_score: (optional) The confidence score of the - passages's analysis. A higher score indicates greater confidence. - :param str passage_text: (optional) The content of the extracted passage. - :param int start_offset: (optional) The position of the first character of - the extracted passage in the originating field. - :param int end_offset: (optional) The position of the last character of the - extracted passage in the originating field. - :param str field: (optional) The label of the field from which the passage - has been extracted. - """ - self.document_id = document_id - self.passage_score = passage_score - self.passage_text = passage_text - self.start_offset = start_offset - self.end_offset = end_offset - self.field = field - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryPassages object from a json dictionary.""" - args = {} - validKeys = [ - 'document_id', 'passage_score', 'passage_text', 'start_offset', - 'end_offset', 'field' - ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryPassages: ' - + ', '.join(badKeys)) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'passage_score' in _dict: - args['passage_score'] = _dict.get('passage_score') - if 'passage_text' in _dict: - args['passage_text'] = _dict.get('passage_text') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'field' in _dict: - args['field'] = _dict.get('field') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'passage_score') and self.passage_score is not None: - _dict['passage_score'] = self.passage_score - if hasattr(self, 'passage_text') and self.passage_text is not None: - _dict['passage_text'] = self.passage_text - if hasattr(self, 'start_offset') and self.start_offset is not None: - _dict['start_offset'] = self.start_offset - if hasattr(self, 'end_offset') and self.end_offset is not None: - _dict['end_offset'] = self.end_offset - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - return _dict - - def __str__(self): - """Return a `str` version of this QueryPassages object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryRelationsArgument(object): - """ - QueryRelationsArgument. - - :attr list[QueryEntitiesEntity] entities: (optional) Array of query entities. - """ - - def __init__(self, *, entities=None): - """ - Initialize a QueryRelationsArgument object. - - :param list[QueryEntitiesEntity] entities: (optional) Array of query - entities. - """ - self.entities = entities - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryRelationsArgument object from a json dictionary.""" - args = {} - validKeys = ['entities'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryRelationsArgument: ' - + ', '.join(badKeys)) - if 'entities' in _dict: - args['entities'] = [ - QueryEntitiesEntity._from_dict(x) - for x in (_dict.get('entities')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] - return _dict - - def __str__(self): - """Return a `str` version of this QueryRelationsArgument object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryRelationsEntity(object): - """ - QueryRelationsEntity. - - :attr str text: (optional) Entity text content. - :attr str type: (optional) The type of the specified entity. - :attr bool exact: (optional) If false, implicit querying is performed. The - default is `false`. - """ - - def __init__(self, *, text=None, type=None, exact=None): - """ - Initialize a QueryRelationsEntity object. - - :param str text: (optional) Entity text content. - :param str type: (optional) The type of the specified entity. - :param bool exact: (optional) If false, implicit querying is performed. The - default is `false`. - """ - self.text = text - self.type = type - self.exact = exact - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryRelationsEntity object from a json dictionary.""" - args = {} - validKeys = ['text', 'type', 'exact'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryRelationsEntity: ' - + ', '.join(badKeys)) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'exact' in _dict: - args['exact'] = _dict.get('exact') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'exact') and self.exact is not None: - _dict['exact'] = self.exact - return _dict - - def __str__(self): - """Return a `str` version of this QueryRelationsEntity object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryRelationsFilter(object): - """ - QueryRelationsFilter. - - :attr QueryFilterType relation_types: (optional) - :attr QueryFilterType entity_types: (optional) - :attr list[str] document_ids: (optional) A comma-separated list of document IDs - to include in the query. - """ - - def __init__(self, - *, - relation_types=None, - entity_types=None, - document_ids=None): - """ - Initialize a QueryRelationsFilter object. - - :param QueryFilterType relation_types: (optional) - :param QueryFilterType entity_types: (optional) - :param list[str] document_ids: (optional) A comma-separated list of - document IDs to include in the query. - """ - self.relation_types = relation_types - self.entity_types = entity_types - self.document_ids = document_ids - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryRelationsFilter object from a json dictionary.""" - args = {} - validKeys = ['relation_types', 'entity_types', 'document_ids'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryRelationsFilter: ' - + ', '.join(badKeys)) - if 'relation_types' in _dict: - args['relation_types'] = QueryFilterType._from_dict( - _dict.get('relation_types')) - if 'entity_types' in _dict: - args['entity_types'] = QueryFilterType._from_dict( - _dict.get('entity_types')) - if 'document_ids' in _dict: - args['document_ids'] = _dict.get('document_ids') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'relation_types') and self.relation_types is not None: - _dict['relation_types'] = self.relation_types._to_dict() - if hasattr(self, 'entity_types') and self.entity_types is not None: - _dict['entity_types'] = self.entity_types._to_dict() - if hasattr(self, 'document_ids') and self.document_ids is not None: - _dict['document_ids'] = self.document_ids - return _dict - - def __str__(self): - """Return a `str` version of this QueryRelationsFilter object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryRelationsRelationship(object): - """ - QueryRelationsRelationship. - - :attr str type: (optional) The identified relationship type. - :attr int frequency: (optional) The number of times the relationship is - mentioned. - :attr list[QueryRelationsArgument] arguments: (optional) Information about the - relationship. - :attr list[QueryEvidence] evidence: (optional) List of different evidentiary - items to support the result. + :attr str id: (optional) The unique identifier of the document. + :attr dict metadata: (optional) Metadata of the document. + :attr str collection_id: (optional) The collection ID of the collection + containing the document for this result. + :attr QueryResultMetadata result_metadata: (optional) Metadata of a query + result. + :attr str title: (optional) Automatically extracted result title. + :attr int code: (optional) The internal status code returned by the ingestion + subsystem indicating the overall result of ingesting the source document. + :attr str filename: (optional) Name of the original source file (if available). + :attr str file_type: (optional) The type of the original source file. + :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted + as a hexadecimal string). + :attr list[Notice] notices: (optional) Array of notices for the document. """ def __init__(self, *, - type=None, - frequency=None, - arguments=None, - evidence=None): + id=None, + metadata=None, + collection_id=None, + result_metadata=None, + title=None, + code=None, + filename=None, + file_type=None, + sha1=None, + notices=None, + **kwargs): """ - Initialize a QueryRelationsRelationship object. + Initialize a QueryNoticesResult object. - :param str type: (optional) The identified relationship type. - :param int frequency: (optional) The number of times the relationship is - mentioned. - :param list[QueryRelationsArgument] arguments: (optional) Information about - the relationship. - :param list[QueryEvidence] evidence: (optional) List of different - evidentiary items to support the result. + :param str id: (optional) The unique identifier of the document. + :param dict metadata: (optional) Metadata of the document. + :param str collection_id: (optional) The collection ID of the collection + containing the document for this result. + :param QueryResultMetadata result_metadata: (optional) Metadata of a query + result. + :param str title: (optional) Automatically extracted result title. + :param int code: (optional) The internal status code returned by the + ingestion subsystem indicating the overall result of ingesting the source + document. + :param str filename: (optional) Name of the original source file (if + available). + :param str file_type: (optional) The type of the original source file. + :param str sha1: (optional) The SHA-1 hash of the original source file + (formatted as a hexadecimal string). + :param list[Notice] notices: (optional) Array of notices for the document. + :param **kwargs: (optional) Any additional properties. """ - self.type = type - self.frequency = frequency - self.arguments = arguments - self.evidence = evidence + self.id = id + self.metadata = metadata + self.collection_id = collection_id + self.result_metadata = result_metadata + self.title = title + self.code = code + self.filename = filename + self.file_type = file_type + self.sha1 = sha1 + self.notices = notices + for _key, _value in kwargs.items(): + setattr(self, _key, _value) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryRelationsRelationship object from a json dictionary.""" + """Initialize a QueryNoticesResult object from a json dictionary.""" args = {} - validKeys = ['type', 'frequency', 'arguments', 'evidence'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryRelationsRelationship: ' - + ', '.join(badKeys)) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'frequency' in _dict: - args['frequency'] = _dict.get('frequency') - if 'arguments' in _dict: - args['arguments'] = [ - QueryRelationsArgument._from_dict(x) - for x in (_dict.get('arguments')) - ] - if 'evidence' in _dict: - args['evidence'] = [ - QueryEvidence._from_dict(x) for x in (_dict.get('evidence')) + xtra = _dict.copy() + if 'id' in _dict: + args['id'] = _dict.get('id') + del xtra['id'] + if 'metadata' in _dict: + args['metadata'] = _dict.get('metadata') + del xtra['metadata'] + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + del xtra['collection_id'] + if 'result_metadata' in _dict: + args['result_metadata'] = QueryResultMetadata._from_dict( + _dict.get('result_metadata')) + del xtra['result_metadata'] + if 'title' in _dict: + args['title'] = _dict.get('title') + del xtra['title'] + if 'code' in _dict: + args['code'] = _dict.get('code') + del xtra['code'] + if 'filename' in _dict: + args['filename'] = _dict.get('filename') + del xtra['filename'] + if 'file_type' in _dict: + args['file_type'] = _dict.get('file_type') + del xtra['file_type'] + if 'sha1' in _dict: + args['sha1'] = _dict.get('sha1') + del xtra['sha1'] + if 'notices' in _dict: + args['notices'] = [ + Notice._from_dict(x) for x in (_dict.get('notices')) ] + del xtra['notices'] + args.update(xtra) return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'frequency') and self.frequency is not None: - _dict['frequency'] = self.frequency - if hasattr(self, 'arguments') and self.arguments is not None: - _dict['arguments'] = [x._to_dict() for x in self.arguments] - if hasattr(self, 'evidence') and self.evidence is not None: - _dict['evidence'] = [x._to_dict() for x in self.evidence] + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, + 'result_metadata') and self.result_metadata is not None: + _dict['result_metadata'] = self.result_metadata._to_dict() + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'filename') and self.filename is not None: + _dict['filename'] = self.filename + if hasattr(self, 'file_type') and self.file_type is not None: + _dict['file_type'] = self.file_type + if hasattr(self, 'sha1') and self.sha1 is not None: + _dict['sha1'] = self.sha1 + if hasattr(self, 'notices') and self.notices is not None: + _dict['notices'] = [x._to_dict() for x in self.notices] + if hasattr(self, '_additionalProperties'): + for _key in self._additionalProperties: + _value = getattr(self, _key, None) + if _value is not None: + _dict[_key] = _value return _dict + def __setattr__(self, name, value): + properties = { + 'id', 'metadata', 'collection_id', 'result_metadata', 'title', + 'code', 'filename', 'file_type', 'sha1', 'notices' + } + if not hasattr(self, '_additionalProperties'): + super(QueryNoticesResult, self).__setattr__('_additionalProperties', + set()) + if name not in properties: + self._additionalProperties.add(name) + super(QueryNoticesResult, self).__setattr__(name, value) + def __str__(self): - """Return a `str` version of this QueryRelationsRelationship object.""" + """Return a `str` version of this QueryNoticesResult object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): @@ -10975,50 +9684,109 @@ def __ne__(self, other): """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class FileTypeEnum(Enum): + """ + The type of the original source file. + """ + PDF = "pdf" + HTML = "html" + WORD = "word" + JSON = "json" -class QueryRelationsResponse(object): + +class QueryPassages(): """ - QueryRelationsResponse. + A passage query result. - :attr list[QueryRelationsRelationship] relations: (optional) Array of - relationships for the relations query. + :attr str document_id: (optional) The unique identifier of the document from + which the passage has been extracted. + :attr float passage_score: (optional) The confidence score of the passages's + analysis. A higher score indicates greater confidence. + :attr str passage_text: (optional) The content of the extracted passage. + :attr int start_offset: (optional) The position of the first character of the + extracted passage in the originating field. + :attr int end_offset: (optional) The position of the last character of the + extracted passage in the originating field. + :attr str field: (optional) The label of the field from which the passage has + been extracted. """ - def __init__(self, *, relations=None): + def __init__(self, + *, + document_id=None, + passage_score=None, + passage_text=None, + start_offset=None, + end_offset=None, + field=None): """ - Initialize a QueryRelationsResponse object. + Initialize a QueryPassages object. - :param list[QueryRelationsRelationship] relations: (optional) Array of - relationships for the relations query. + :param str document_id: (optional) The unique identifier of the document + from which the passage has been extracted. + :param float passage_score: (optional) The confidence score of the + passages's analysis. A higher score indicates greater confidence. + :param str passage_text: (optional) The content of the extracted passage. + :param int start_offset: (optional) The position of the first character of + the extracted passage in the originating field. + :param int end_offset: (optional) The position of the last character of the + extracted passage in the originating field. + :param str field: (optional) The label of the field from which the passage + has been extracted. """ - self.relations = relations + self.document_id = document_id + self.passage_score = passage_score + self.passage_text = passage_text + self.start_offset = start_offset + self.end_offset = end_offset + self.field = field @classmethod def _from_dict(cls, _dict): - """Initialize a QueryRelationsResponse object from a json dictionary.""" + """Initialize a QueryPassages object from a json dictionary.""" args = {} - validKeys = ['relations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = [ + 'document_id', 'passage_score', 'passage_text', 'start_offset', + 'end_offset', 'field' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryRelationsResponse: ' - + ', '.join(badKeys)) - if 'relations' in _dict: - args['relations'] = [ - QueryRelationsRelationship._from_dict(x) - for x in (_dict.get('relations')) - ] + 'Unrecognized keys detected in dictionary for class QueryPassages: ' + + ', '.join(bad_keys)) + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'passage_score' in _dict: + args['passage_score'] = _dict.get('passage_score') + if 'passage_text' in _dict: + args['passage_text'] = _dict.get('passage_text') + if 'start_offset' in _dict: + args['start_offset'] = _dict.get('start_offset') + if 'end_offset' in _dict: + args['end_offset'] = _dict.get('end_offset') + if 'field' in _dict: + args['field'] = _dict.get('field') return cls(**args) def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = [x._to_dict() for x in self.relations] + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'passage_score') and self.passage_score is not None: + _dict['passage_score'] = self.passage_score + if hasattr(self, 'passage_text') and self.passage_text is not None: + _dict['passage_text'] = self.passage_text + if hasattr(self, 'start_offset') and self.start_offset is not None: + _dict['start_offset'] = self.start_offset + if hasattr(self, 'end_offset') and self.end_offset is not None: + _dict['end_offset'] = self.end_offset + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field return _dict def __str__(self): - """Return a `str` version of this QueryRelationsResponse object.""" + """Return a `str` version of this QueryPassages object.""" return json.dumps(self._to_dict(), indent=2) def __eq__(self, other): @@ -11032,7 +9800,7 @@ def __ne__(self, other): return not self == other -class QueryResponse(object): +class QueryResponse(): """ A response containing the documents and aggregations for the query. @@ -11095,15 +9863,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a QueryResponse object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'matching_results', 'results', 'aggregations', 'passages', 'duplicates_removed', 'session_token', 'retrieval_details' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class QueryResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: @@ -11166,9 +9934,9 @@ def __ne__(self, other): return not self == other -class QueryResult(object): +class QueryResult(): """ - QueryResult. + Query result object. :attr str id: (optional) The unique identifier of the document. :attr dict metadata: (optional) Metadata of the document. @@ -11277,7 +10045,7 @@ def __ne__(self, other): return not self == other -class QueryResultMetadata(object): +class QueryResultMetadata(): """ Metadata of a query result. @@ -11312,12 +10080,12 @@ def __init__(self, score, *, confidence=None): def _from_dict(cls, _dict): """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} - validKeys = ['score', 'confidence'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['score', 'confidence'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class QueryResultMetadata: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'score' in _dict: args['score'] = _dict.get('score') else: @@ -11352,7 +10120,7 @@ def __ne__(self, other): return not self == other -class RetrievalDetails(object): +class RetrievalDetails(): """ An object contain retrieval type information. @@ -11388,12 +10156,12 @@ def __init__(self, *, document_retrieval_strategy=None): def _from_dict(cls, _dict): """Initialize a RetrievalDetails object from a json dictionary.""" args = {} - validKeys = ['document_retrieval_strategy'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document_retrieval_strategy'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RetrievalDetails: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document_retrieval_strategy' in _dict: args['document_retrieval_strategy'] = _dict.get( 'document_retrieval_strategy') @@ -11439,7 +10207,7 @@ class DocumentRetrievalStrategyEnum(Enum): CONTINUOUS_RELEVANCY_TRAINING = "continuous_relevancy_training" -class SduStatus(object): +class SduStatus(): """ Object containing smart document understanding information for this collection. @@ -11508,15 +10276,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SduStatus object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'enabled', 'total_annotated_pages', 'total_pages', 'total_documents', 'custom_fields' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SduStatus: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'total_annotated_pages' in _dict: @@ -11562,7 +10330,7 @@ def __ne__(self, other): return not self == other -class SduStatusCustomFields(object): +class SduStatusCustomFields(): """ Information about custom smart document understanding fields that exist in this collection. @@ -11589,12 +10357,12 @@ def __init__(self, *, defined=None, maximum_allowed=None): def _from_dict(cls, _dict): """Initialize a SduStatusCustomFields object from a json dictionary.""" args = {} - validKeys = ['defined', 'maximum_allowed'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['defined', 'maximum_allowed'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SduStatusCustomFields: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'defined' in _dict: args['defined'] = _dict.get('defined') if 'maximum_allowed' in _dict: @@ -11626,7 +10394,7 @@ def __ne__(self, other): return not self == other -class SearchStatus(object): +class SearchStatus(): """ Information about the Continuous Relevancy Training for this environment. @@ -11667,12 +10435,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SearchStatus object from a json dictionary.""" args = {} - validKeys = ['scope', 'status', 'status_description', 'last_trained'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['scope', 'status', 'status_description', 'last_trained'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SearchStatus: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'scope' in _dict: args['scope'] = _dict.get('scope') if 'status' in _dict: @@ -11723,7 +10491,7 @@ class StatusEnum(Enum): NOT_APPLICABLE = "NOT_APPLICABLE" -class SegmentSettings(object): +class SegmentSettings(): """ A list of Document Segmentation settings. @@ -11782,12 +10550,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SegmentSettings object from a json dictionary.""" args = {} - validKeys = ['enabled', 'selector_tags', 'annotated_fields'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['enabled', 'selector_tags', 'annotated_fields'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SegmentSettings: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'selector_tags' in _dict: @@ -11823,7 +10591,7 @@ def __ne__(self, other): return not self == other -class Source(object): +class Source(): """ Object containing source parameters for the configuration. @@ -11882,12 +10650,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Source object from a json dictionary.""" args = {} - validKeys = ['type', 'credential_id', 'schedule', 'options'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['type', 'credential_id', 'schedule', 'options'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Source: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'credential_id' in _dict: @@ -11943,7 +10711,7 @@ class TypeEnum(Enum): CLOUD_OBJECT_STORAGE = "cloud_object_storage" -class SourceOptions(object): +class SourceOptions(): """ The **options** object defines which items to crawl from the source system. @@ -12013,15 +10781,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SourceOptions object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'folders', 'objects', 'site_collections', 'urls', 'buckets', 'crawl_all_buckets' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SourceOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'folders' in _dict: args['folders'] = [ SourceOptionsFolder._from_dict(x) @@ -12086,7 +10854,7 @@ def __ne__(self, other): return not self == other -class SourceOptionsBuckets(object): +class SourceOptionsBuckets(): """ Object defining a cloud object store bucket to crawl. @@ -12111,12 +10879,12 @@ def __init__(self, name, *, limit=None): def _from_dict(cls, _dict): """Initialize a SourceOptionsBuckets object from a json dictionary.""" args = {} - validKeys = ['name', 'limit'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['name', 'limit'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SourceOptionsBuckets: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -12151,7 +10919,7 @@ def __ne__(self, other): return not self == other -class SourceOptionsFolder(object): +class SourceOptionsFolder(): """ Object that defines a box folder to crawl with this configuration. @@ -12180,12 +10948,12 @@ def __init__(self, owner_user_id, folder_id, *, limit=None): def _from_dict(cls, _dict): """Initialize a SourceOptionsFolder object from a json dictionary.""" args = {} - validKeys = ['owner_user_id', 'folder_id', 'limit'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['owner_user_id', 'folder_id', 'limit'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SourceOptionsFolder: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'owner_user_id' in _dict: args['owner_user_id'] = _dict.get('owner_user_id') else: @@ -12228,7 +10996,7 @@ def __ne__(self, other): return not self == other -class SourceOptionsObject(object): +class SourceOptionsObject(): """ Object that defines a Salesforce document object type crawl with this configuration. @@ -12255,12 +11023,12 @@ def __init__(self, name, *, limit=None): def _from_dict(cls, _dict): """Initialize a SourceOptionsObject object from a json dictionary.""" args = {} - validKeys = ['name', 'limit'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['name', 'limit'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SourceOptionsObject: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -12295,7 +11063,7 @@ def __ne__(self, other): return not self == other -class SourceOptionsSiteColl(object): +class SourceOptionsSiteColl(): """ Object that defines a Microsoft SharePoint site collection to crawl with this configuration. @@ -12326,12 +11094,12 @@ def __init__(self, site_collection_path, *, limit=None): def _from_dict(cls, _dict): """Initialize a SourceOptionsSiteColl object from a json dictionary.""" args = {} - validKeys = ['site_collection_path', 'limit'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['site_collection_path', 'limit'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SourceOptionsSiteColl: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'site_collection_path' in _dict: args['site_collection_path'] = _dict.get('site_collection_path') else: @@ -12367,7 +11135,7 @@ def __ne__(self, other): return not self == other -class SourceOptionsWebCrawl(object): +class SourceOptionsWebCrawl(): """ Object defining which URL to crawl and how to crawl it. @@ -12451,16 +11219,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SourceOptionsWebCrawl object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'url', 'limit_to_starting_hosts', 'crawl_speed', 'allow_untrusted_certificate', 'maximum_hops', 'request_timeout', 'override_robots_txt', 'blacklist' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SourceOptionsWebCrawl: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'url' in _dict: args['url'] = _dict.get('url') else: @@ -12539,7 +11307,7 @@ class CrawlSpeedEnum(Enum): AGGRESSIVE = "aggressive" -class SourceSchedule(object): +class SourceSchedule(): """ Object containing the schedule information for the source. @@ -12588,12 +11356,12 @@ def __init__(self, *, enabled=None, time_zone=None, frequency=None): def _from_dict(cls, _dict): """Initialize a SourceSchedule object from a json dictionary.""" args = {} - validKeys = ['enabled', 'time_zone', 'frequency'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['enabled', 'time_zone', 'frequency'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SourceSchedule: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'time_zone' in _dict: @@ -12643,7 +11411,7 @@ class FrequencyEnum(Enum): HOURLY = "hourly" -class SourceStatus(object): +class SourceStatus(): """ Object containing source crawl status information. @@ -12682,12 +11450,12 @@ def __init__(self, *, status=None, next_crawl=None): def _from_dict(cls, _dict): """Initialize a SourceStatus object from a json dictionary.""" args = {} - validKeys = ['status', 'next_crawl'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['status', 'next_crawl'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SourceStatus: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') if 'next_crawl' in _dict: @@ -12735,13 +11503,13 @@ class StatusEnum(Enum): UNKNOWN = "unknown" -class Term(object): +class Term(): """ Term. :attr str field: (optional) The field where the aggregation is located in the document. - :attr int count: (optional) + :attr int count: (optional) The number of terms identified. """ def __init__(self, @@ -12764,7 +11532,7 @@ def __init__(self, returned by Discovery. :param str field: (optional) The field where the aggregation is located in the document. - :param int count: (optional) + :param int count: (optional) The number of terms identified. """ self.field = field self.count = count @@ -12773,12 +11541,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Term object from a json dictionary.""" args = {} - validKeys = ['field', 'count'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['field', 'count'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Term: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'field' in _dict: args['field'] = _dict.get('field') if 'count' in _dict: @@ -12809,121 +11577,7 @@ def __ne__(self, other): return not self == other -class TestDocument(object): - """ - TestDocument. - - :attr str configuration_id: (optional) The unique identifier for the - configuration. - :attr str status: (optional) Status of the preview operation. - :attr int enriched_field_units: (optional) The number of 10-kB chunks of field - data that were enriched. This can be used to estimate the cost of running a real - ingestion. - :attr str original_media_type: (optional) Format of the test document. - :attr list[DocumentSnapshot] snapshots: (optional) An array of objects that - describe each step in the preview process. - :attr list[Notice] notices: (optional) An array of notice messages about the - preview operation. - """ - - def __init__(self, - *, - configuration_id=None, - status=None, - enriched_field_units=None, - original_media_type=None, - snapshots=None, - notices=None): - """ - Initialize a TestDocument object. - - :param str configuration_id: (optional) The unique identifier for the - configuration. - :param str status: (optional) Status of the preview operation. - :param int enriched_field_units: (optional) The number of 10-kB chunks of - field data that were enriched. This can be used to estimate the cost of - running a real ingestion. - :param str original_media_type: (optional) Format of the test document. - :param list[DocumentSnapshot] snapshots: (optional) An array of objects - that describe each step in the preview process. - :param list[Notice] notices: (optional) An array of notice messages about - the preview operation. - """ - self.configuration_id = configuration_id - self.status = status - self.enriched_field_units = enriched_field_units - self.original_media_type = original_media_type - self.snapshots = snapshots - self.notices = notices - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TestDocument object from a json dictionary.""" - args = {} - validKeys = [ - 'configuration_id', 'status', 'enriched_field_units', - 'original_media_type', 'snapshots', 'notices' - ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TestDocument: ' - + ', '.join(badKeys)) - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'enriched_field_units' in _dict: - args['enriched_field_units'] = _dict.get('enriched_field_units') - if 'original_media_type' in _dict: - args['original_media_type'] = _dict.get('original_media_type') - if 'snapshots' in _dict: - args['snapshots'] = [ - DocumentSnapshot._from_dict(x) for x in (_dict.get('snapshots')) - ] - if 'notices' in _dict: - args['notices'] = [ - Notice._from_dict(x) for x in (_dict.get('notices')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, - 'configuration_id') and self.configuration_id is not None: - _dict['configuration_id'] = self.configuration_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'enriched_field_units' - ) and self.enriched_field_units is not None: - _dict['enriched_field_units'] = self.enriched_field_units - if hasattr( - self, - 'original_media_type') and self.original_media_type is not None: - _dict['original_media_type'] = self.original_media_type - if hasattr(self, 'snapshots') and self.snapshots is not None: - _dict['snapshots'] = [x._to_dict() for x in self.snapshots] - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x._to_dict() for x in self.notices] - return _dict - - def __str__(self): - """Return a `str` version of this TestDocument object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Timeslice(object): +class Timeslice(): """ Timeslice. @@ -12973,12 +11627,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Timeslice object from a json dictionary.""" args = {} - validKeys = ['field', 'interval', 'anomaly'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['field', 'interval', 'anomaly'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Timeslice: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'field' in _dict: args['field'] = _dict.get('field') if 'interval' in _dict: @@ -13013,7 +11667,7 @@ def __ne__(self, other): return not self == other -class TokenDictRule(object): +class TokenDictRule(): """ An object defining a single tokenizaion rule. @@ -13047,12 +11701,12 @@ def __init__(self, text, tokens, part_of_speech, *, readings=None): def _from_dict(cls, _dict): """Initialize a TokenDictRule object from a json dictionary.""" args = {} - validKeys = ['text', 'tokens', 'readings', 'part_of_speech'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'tokens', 'readings', 'part_of_speech'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TokenDictRule: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -13102,7 +11756,7 @@ def __ne__(self, other): return not self == other -class TokenDictStatusResponse(object): +class TokenDictStatusResponse(): """ Object describing the current status of the wordlist. @@ -13128,12 +11782,12 @@ def __init__(self, *, status=None, type=None): def _from_dict(cls, _dict): """Initialize a TokenDictStatusResponse object from a json dictionary.""" args = {} - validKeys = ['status', 'type'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['status', 'type'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TokenDictStatusResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') if 'type' in _dict: @@ -13172,7 +11826,7 @@ class StatusEnum(Enum): NOT_FOUND = "not found" -class TopHits(object): +class TopHits(): """ TopHits. @@ -13208,12 +11862,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a TopHits object from a json dictionary.""" args = {} - validKeys = ['size', 'hits'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['size', 'hits'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TopHits: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'size' in _dict: args['size'] = _dict.get('size') if 'hits' in _dict: @@ -13244,9 +11898,9 @@ def __ne__(self, other): return not self == other -class TopHitsResults(object): +class TopHitsResults(): """ - TopHitsResults. + Top hit information for this query. :attr int matching_results: (optional) Number of matching results. :attr list[QueryResult] hits: (optional) Top results returned by the @@ -13268,12 +11922,12 @@ def __init__(self, *, matching_results=None, hits=None): def _from_dict(cls, _dict): """Initialize a TopHitsResults object from a json dictionary.""" args = {} - validKeys = ['matching_results', 'hits'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['matching_results', 'hits'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TopHitsResults: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'hits' in _dict: @@ -13307,9 +11961,9 @@ def __ne__(self, other): return not self == other -class TrainingDataSet(object): +class TrainingDataSet(): """ - TrainingDataSet. + Training information for a specific collection. :attr str environment_id: (optional) The environment id associated with this training data set. @@ -13337,12 +11991,12 @@ def __init__(self, *, environment_id=None, collection_id=None, def _from_dict(cls, _dict): """Initialize a TrainingDataSet object from a json dictionary.""" args = {} - validKeys = ['environment_id', 'collection_id', 'queries'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['environment_id', 'collection_id', 'queries'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TrainingDataSet: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') if 'collection_id' in _dict: @@ -13379,9 +12033,9 @@ def __ne__(self, other): return not self == other -class TrainingExample(object): +class TrainingExample(): """ - TrainingExample. + Training example details. :attr str document_id: (optional) The document ID associated with this training example. @@ -13412,12 +12066,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a TrainingExample object from a json dictionary.""" args = {} - validKeys = ['document_id', 'cross_reference', 'relevance'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document_id', 'cross_reference', 'relevance'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TrainingExample: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'cross_reference' in _dict: @@ -13453,9 +12107,9 @@ def __ne__(self, other): return not self == other -class TrainingExampleList(object): +class TrainingExampleList(): """ - TrainingExampleList. + Object containing an array of training examples. :attr list[TrainingExample] examples: (optional) Array of training examples. """ @@ -13473,12 +12127,12 @@ def __init__(self, *, examples=None): def _from_dict(cls, _dict): """Initialize a TrainingExampleList object from a json dictionary.""" args = {} - validKeys = ['examples'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['examples'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TrainingExampleList: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'examples' in _dict: args['examples'] = [ TrainingExample._from_dict(x) for x in (_dict.get('examples')) @@ -13507,9 +12161,9 @@ def __ne__(self, other): return not self == other -class TrainingQuery(object): +class TrainingQuery(): """ - TrainingQuery. + Training query details. :attr str query_id: (optional) The query ID associated with the training query. :attr str natural_language_query: (optional) The natural text query for the @@ -13546,12 +12200,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a TrainingQuery object from a json dictionary.""" args = {} - validKeys = ['query_id', 'natural_language_query', 'filter', 'examples'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = [ + 'query_id', 'natural_language_query', 'filter', 'examples' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TrainingQuery: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'query_id' in _dict: args['query_id'] = _dict.get('query_id') if 'natural_language_query' in _dict: @@ -13593,9 +12249,9 @@ def __ne__(self, other): return not self == other -class TrainingStatus(object): +class TrainingStatus(): """ - TrainingStatus. + Training status details. :attr int total_examples: (optional) The total number of training examples uploaded to this collection. @@ -13665,17 +12321,17 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a TrainingStatus object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'total_examples', 'available', 'processing', 'minimum_queries_added', 'minimum_examples_added', 'sufficient_label_diversity', 'notices', 'successfully_trained', 'data_updated' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TrainingStatus: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'total_examples' in _dict: args['total_examples'] = _dict.get('total_examples') if 'available' in _dict: @@ -13742,20 +12398,23 @@ def __ne__(self, other): return not self == other -class WordHeadingDetection(object): +class WordHeadingDetection(): """ - WordHeadingDetection. + Object containing heading detection conversion settings for Microsoft Word documents. - :attr list[FontSetting] fonts: (optional) - :attr list[WordStyle] styles: (optional) + :attr list[FontSetting] fonts: (optional) Array of font matching configurations. + :attr list[WordStyle] styles: (optional) Array of Microsoft Word styles to + convert. """ def __init__(self, *, fonts=None, styles=None): """ Initialize a WordHeadingDetection object. - :param list[FontSetting] fonts: (optional) - :param list[WordStyle] styles: (optional) + :param list[FontSetting] fonts: (optional) Array of font matching + configurations. + :param list[WordStyle] styles: (optional) Array of Microsoft Word styles to + convert. """ self.fonts = fonts self.styles = styles @@ -13764,12 +12423,12 @@ def __init__(self, *, fonts=None, styles=None): def _from_dict(cls, _dict): """Initialize a WordHeadingDetection object from a json dictionary.""" args = {} - validKeys = ['fonts', 'styles'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['fonts', 'styles'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class WordHeadingDetection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'fonts' in _dict: args['fonts'] = [ FontSetting._from_dict(x) for x in (_dict.get('fonts')) @@ -13804,18 +12463,20 @@ def __ne__(self, other): return not self == other -class WordSettings(object): +class WordSettings(): """ A list of Word conversion settings. - :attr WordHeadingDetection heading: (optional) + :attr WordHeadingDetection heading: (optional) Object containing heading + detection conversion settings for Microsoft Word documents. """ def __init__(self, *, heading=None): """ Initialize a WordSettings object. - :param WordHeadingDetection heading: (optional) + :param WordHeadingDetection heading: (optional) Object containing heading + detection conversion settings for Microsoft Word documents. """ self.heading = heading @@ -13823,12 +12484,12 @@ def __init__(self, *, heading=None): def _from_dict(cls, _dict): """Initialize a WordSettings object from a json dictionary.""" args = {} - validKeys = ['heading'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['heading'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class WordSettings: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'heading' in _dict: args['heading'] = WordHeadingDetection._from_dict( _dict.get('heading')) @@ -13856,9 +12517,9 @@ def __ne__(self, other): return not self == other -class WordStyle(object): +class WordStyle(): """ - WordStyle. + Microsoft Word styles to convert into a specified HTML head level. :attr int level: (optional) HTML head level that content matching this style is tagged with. @@ -13880,12 +12541,12 @@ def __init__(self, *, level=None, names=None): def _from_dict(cls, _dict): """Initialize a WordStyle object from a json dictionary.""" args = {} - validKeys = ['level', 'names'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['level', 'names'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class WordStyle: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'level' in _dict: args['level'] = _dict.get('level') if 'names' in _dict: @@ -13916,9 +12577,9 @@ def __ne__(self, other): return not self == other -class XPathPatterns(object): +class XPathPatterns(): """ - XPathPatterns. + Object containing an array of XPaths. :attr list[str] xpaths: (optional) An array to XPaths. """ @@ -13935,12 +12596,12 @@ def __init__(self, *, xpaths=None): def _from_dict(cls, _dict): """Initialize a XPathPatterns object from a json dictionary.""" args = {} - validKeys = ['xpaths'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['xpaths'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class XPathPatterns: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'xpaths' in _dict: args['xpaths'] = _dict.get('xpaths') return cls(**args) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index b8c88cde8..9b0612b73 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -27,6 +27,7 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources from os.path import basename ############################################################################## @@ -37,14 +38,12 @@ class LanguageTranslatorV3(BaseService): """The Language Translator V3 service.""" - default_url = 'https://gateway.watsonplatform.net/language-translator/api' + default_service_url = 'https://gateway.watsonplatform.net/language-translator/api' def __init__( self, version, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Language Translator service. @@ -60,26 +59,28 @@ def __init__( application, and don't change it until your application is ready for a later version. - :param str url: The base url to use when contacting the service (e.g. - "https://gateway.watsonplatform.net/language-translator/api/language-translator/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('language_translator') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: authenticator = get_authenticator_from_environment( - 'Language Translator') + 'language_translator') - BaseService.__init__( - self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Language Translator') + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) self.version = version ######################### @@ -128,13 +129,12 @@ def translate(self, } url = '/v3/translate' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -164,12 +164,11 @@ def list_identifiable_languages(self, **kwargs): params = {'version': self.version} url = '/v3/identifiable_languages' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -200,13 +199,12 @@ def identify(self, text, **kwargs): headers['content-type'] = 'text/plain' url = '/v3/identify' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -249,12 +247,11 @@ def list_models(self, *, source=None, target=None, default=None, **kwargs): } url = '/v3/models' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -322,22 +319,21 @@ def create_model(self, 'name': name } - form_data = {} + form_data = [] if forced_glossary: - form_data['forced_glossary'] = (None, forced_glossary, - 'application/octet-stream') + form_data.append(('forced_glossary', (None, forced_glossary, + 'application/octet-stream'))) if parallel_corpus: - form_data['parallel_corpus'] = (None, parallel_corpus, - 'application/octet-stream') + form_data.append(('parallel_corpus', (None, parallel_corpus, + 'application/octet-stream'))) url = '/v3/models' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -366,12 +362,11 @@ def delete_model(self, model_id, **kwargs): params = {'version': self.version} url = '/v3/models/{0}'.format(*self._encode_path_vars(model_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -401,12 +396,11 @@ def get_model(self, model_id, **kwargs): params = {'version': self.version} url = '/v3/models/{0}'.format(*self._encode_path_vars(model_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -435,12 +429,11 @@ def list_documents(self, **kwargs): params = {'version': self.version} url = '/v3/documents' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -493,30 +486,29 @@ def translate_document(self, params = {'version': self.version} - form_data = {} + form_data = [] if not filename and hasattr(file, 'name'): filename = basename(file.name) if not filename: raise ValueError('filename must be provided') - form_data['file'] = (filename, file, file_content_type or - 'application/octet-stream') + form_data.append(('file', (filename, file, file_content_type or + 'application/octet-stream'))) if model_id: - form_data['model_id'] = (None, model_id, 'text/plain') + form_data.append(('model_id', (None, model_id, 'text/plain'))) if source: - form_data['source'] = (None, source, 'text/plain') + form_data.append(('source', (None, source, 'text/plain'))) if target: - form_data['target'] = (None, target, 'text/plain') + form_data.append(('target', (None, target, 'text/plain'))) if document_id: - form_data['document_id'] = (None, document_id, 'text/plain') + form_data.append(('document_id', (None, document_id, 'text/plain'))) url = '/v3/documents' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -545,12 +537,11 @@ def get_document_status(self, document_id, **kwargs): params = {'version': self.version} url = '/v3/documents/{0}'.format(*self._encode_path_vars(document_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -579,12 +570,11 @@ def delete_document(self, document_id, **kwargs): params = {'version': self.version} url = '/v3/documents/{0}'.format(*self._encode_path_vars(document_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -716,7 +706,7 @@ class Accept(Enum): ############################################################################## -class DeleteModelResult(object): +class DeleteModelResult(): """ DeleteModelResult. @@ -735,12 +725,12 @@ def __init__(self, status): def _from_dict(cls, _dict): """Initialize a DeleteModelResult object from a json dictionary.""" args = {} - validKeys = ['status'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DeleteModelResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') else: @@ -771,7 +761,7 @@ def __ne__(self, other): return not self == other -class DocumentList(object): +class DocumentList(): """ DocumentList. @@ -792,12 +782,12 @@ def __init__(self, documents): def _from_dict(cls, _dict): """Initialize a DocumentList object from a json dictionary.""" args = {} - validKeys = ['documents'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['documents'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DocumentList: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'documents' in _dict: args['documents'] = [ DocumentStatus._from_dict(x) for x in (_dict.get('documents')) @@ -830,7 +820,7 @@ def __ne__(self, other): return not self == other -class DocumentStatus(object): +class DocumentStatus(): """ Document information, including translation status. @@ -908,16 +898,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a DocumentStatus object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'document_id', 'filename', 'status', 'model_id', 'base_model_id', 'source', 'target', 'created', 'completed', 'word_count', 'character_count' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DocumentStatus: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') else: @@ -1021,7 +1011,7 @@ class StatusEnum(Enum): FAILED = "failed" -class IdentifiableLanguage(object): +class IdentifiableLanguage(): """ IdentifiableLanguage. @@ -1043,12 +1033,12 @@ def __init__(self, language, name): def _from_dict(cls, _dict): """Initialize a IdentifiableLanguage object from a json dictionary.""" args = {} - validKeys = ['language', 'name'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['language', 'name'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class IdentifiableLanguage: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'language' in _dict: args['language'] = _dict.get('language') else: @@ -1087,7 +1077,7 @@ def __ne__(self, other): return not self == other -class IdentifiableLanguages(object): +class IdentifiableLanguages(): """ IdentifiableLanguages. @@ -1108,12 +1098,12 @@ def __init__(self, languages): def _from_dict(cls, _dict): """Initialize a IdentifiableLanguages object from a json dictionary.""" args = {} - validKeys = ['languages'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['languages'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class IdentifiableLanguages: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'languages' in _dict: args['languages'] = [ IdentifiableLanguage._from_dict(x) @@ -1147,7 +1137,7 @@ def __ne__(self, other): return not self == other -class IdentifiedLanguage(object): +class IdentifiedLanguage(): """ IdentifiedLanguage. @@ -1169,12 +1159,12 @@ def __init__(self, language, confidence): def _from_dict(cls, _dict): """Initialize a IdentifiedLanguage object from a json dictionary.""" args = {} - validKeys = ['language', 'confidence'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['language', 'confidence'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class IdentifiedLanguage: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'language' in _dict: args['language'] = _dict.get('language') else: @@ -1213,7 +1203,7 @@ def __ne__(self, other): return not self == other -class IdentifiedLanguages(object): +class IdentifiedLanguages(): """ IdentifiedLanguages. @@ -1234,12 +1224,12 @@ def __init__(self, languages): def _from_dict(cls, _dict): """Initialize a IdentifiedLanguages object from a json dictionary.""" args = {} - validKeys = ['languages'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['languages'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class IdentifiedLanguages: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'languages' in _dict: args['languages'] = [ IdentifiedLanguage._from_dict(x) @@ -1273,7 +1263,7 @@ def __ne__(self, other): return not self == other -class Translation(object): +class Translation(): """ Translation. @@ -1292,12 +1282,12 @@ def __init__(self, translation): def _from_dict(cls, _dict): """Initialize a Translation object from a json dictionary.""" args = {} - validKeys = ['translation'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['translation'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Translation: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'translation' in _dict: args['translation'] = _dict.get('translation') else: @@ -1328,7 +1318,7 @@ def __ne__(self, other): return not self == other -class TranslationModel(object): +class TranslationModel(): """ Response payload for models. @@ -1405,15 +1395,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a TranslationModel object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'model_id', 'name', 'source', 'target', 'base_model_id', 'domain', 'customizable', 'default_model', 'owner', 'status' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TranslationModel: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') else: @@ -1495,7 +1485,7 @@ class StatusEnum(Enum): ERROR = "error" -class TranslationModels(object): +class TranslationModels(): """ The response type for listing existing translation models. @@ -1514,12 +1504,12 @@ def __init__(self, models): def _from_dict(cls, _dict): """Initialize a TranslationModels object from a json dictionary.""" args = {} - validKeys = ['models'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['models'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TranslationModels: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'models' in _dict: args['models'] = [ TranslationModel._from_dict(x) for x in (_dict.get('models')) @@ -1552,7 +1542,7 @@ def __ne__(self, other): return not self == other -class TranslationResult(object): +class TranslationResult(): """ TranslationResult. @@ -1579,12 +1569,12 @@ def __init__(self, word_count, character_count, translations): def _from_dict(cls, _dict): """Initialize a TranslationResult object from a json dictionary.""" args = {} - validKeys = ['word_count', 'character_count', 'translations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['word_count', 'character_count', 'translations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TranslationResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'word_count' in _dict: args['word_count'] = _dict.get('word_count') else: diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 0d445cade..2f7a00d05 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -26,6 +26,7 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources ############################################################################## # Service @@ -35,37 +36,37 @@ class NaturalLanguageClassifierV1(BaseService): """The Natural Language Classifier V1 service.""" - default_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api' + default_service_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api' def __init__( self, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Natural Language Classifier service. - :param str url: The base url to use when contacting the service (e.g. - "https://gateway.watsonplatform.net/natural-language-classifier/api/natural-language-classifier/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('natural_language_classifier') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: authenticator = get_authenticator_from_environment( - 'Natural Language Classifier') + 'natural_language_classifier') - BaseService.__init__( - self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Natural Language Classifier') + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) ######################### # Classify text @@ -102,12 +103,11 @@ def classify(self, classifier_id, text, **kwargs): url = '/v1/classifiers/{0}/classify'.format( *self._encode_path_vars(classifier_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + data=data, + accept_json=True) response = self.send(request) return response @@ -143,12 +143,11 @@ def classify_collection(self, classifier_id, collection, **kwargs): url = '/v1/classifiers/{0}/classify_collection'.format( *self._encode_path_vars(classifier_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + data=data, + accept_json=True) response = self.send(request) return response @@ -191,18 +190,17 @@ def create_classifier(self, training_metadata, training_data, **kwargs): 'create_classifier') headers.update(sdk_headers) - form_data = {} - form_data['training_metadata'] = (None, training_metadata, - 'application/json') - form_data['training_data'] = (None, training_data, 'text/csv') + form_data = [] + form_data.append(('training_metadata', (None, training_metadata, + 'application/json'))) + form_data.append(('training_data', (None, training_data, 'text/csv'))) url = '/v1/classifiers' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -225,8 +223,10 @@ def list_classifiers(self, **kwargs): headers.update(sdk_headers) url = '/v1/classifiers' - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -254,8 +254,10 @@ def get_classifier(self, classifier_id, **kwargs): url = '/v1/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -281,8 +283,10 @@ def delete_classifier(self, classifier_id, **kwargs): url = '/v1/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - request = self.prepare_request( - method='DELETE', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -292,7 +296,7 @@ def delete_classifier(self, classifier_id, **kwargs): ############################################################################## -class Classification(object): +class Classification(): """ Response from the classifier for a phrase. @@ -331,12 +335,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Classification object from a json dictionary.""" args = {} - validKeys = ['classifier_id', 'url', 'text', 'top_class', 'classes'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['classifier_id', 'url', 'text', 'top_class', 'classes'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Classification: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') if 'url' in _dict: @@ -381,7 +385,7 @@ def __ne__(self, other): return not self == other -class ClassificationCollection(object): +class ClassificationCollection(): """ Response from the classifier for multiple phrases. @@ -408,12 +412,12 @@ def __init__(self, *, classifier_id=None, url=None, collection=None): def _from_dict(cls, _dict): """Initialize a ClassificationCollection object from a json dictionary.""" args = {} - validKeys = ['classifier_id', 'url', 'collection'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['classifier_id', 'url', 'collection'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ClassificationCollection: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') if 'url' in _dict: @@ -450,7 +454,7 @@ def __ne__(self, other): return not self == other -class ClassifiedClass(object): +class ClassifiedClass(): """ Class and confidence. @@ -476,12 +480,12 @@ def __init__(self, *, confidence=None, class_name=None): def _from_dict(cls, _dict): """Initialize a ClassifiedClass object from a json dictionary.""" args = {} - validKeys = ['confidence', 'class_name'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['confidence', 'class_name'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ClassifiedClass: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') if 'class_name' in _dict: @@ -512,7 +516,7 @@ def __ne__(self, other): return not self == other -class Classifier(object): +class Classifier(): """ A classifier for natural language phrases. @@ -560,15 +564,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Classifier object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'name', 'url', 'status', 'classifier_id', 'created', 'status_description', 'language' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Classifier: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') if 'url' in _dict: @@ -638,7 +642,7 @@ class StatusEnum(Enum): UNAVAILABLE = "Unavailable" -class ClassifierList(object): +class ClassifierList(): """ List of available classifiers. @@ -659,12 +663,12 @@ def __init__(self, classifiers): def _from_dict(cls, _dict): """Initialize a ClassifierList object from a json dictionary.""" args = {} - validKeys = ['classifiers'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['classifiers'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ClassifierList: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'classifiers' in _dict: args['classifiers'] = [ Classifier._from_dict(x) for x in (_dict.get('classifiers')) @@ -697,7 +701,7 @@ def __ne__(self, other): return not self == other -class ClassifyInput(object): +class ClassifyInput(): """ Request payload to classify. @@ -717,12 +721,12 @@ def __init__(self, text): def _from_dict(cls, _dict): """Initialize a ClassifyInput object from a json dictionary.""" args = {} - validKeys = ['text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ClassifyInput: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -752,7 +756,7 @@ def __ne__(self, other): return not self == other -class CollectionItem(object): +class CollectionItem(): """ Response from the classifier for a phrase in a collection. @@ -781,12 +785,12 @@ def __init__(self, *, text=None, top_class=None, classes=None): def _from_dict(cls, _dict): """Initialize a CollectionItem object from a json dictionary.""" args = {} - validKeys = ['text', 'top_class', 'classes'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'top_class', 'classes'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CollectionItem: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'top_class' in _dict: diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index f896bfd31..89c5dc027 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -30,6 +30,7 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources ############################################################################## # Service @@ -39,14 +40,12 @@ class NaturalLanguageUnderstandingV1(BaseService): """The Natural Language Understanding V1 service.""" - default_url = 'https://gateway.watsonplatform.net/natural-language-understanding/api' + default_service_url = 'https://gateway.watsonplatform.net/natural-language-understanding/api' def __init__( self, version, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Natural Language Understanding service. @@ -62,26 +61,28 @@ def __init__( application, and don't change it until your application is ready for a later version. - :param str url: The base url to use when contacting the service (e.g. - "https://gateway.watsonplatform.net/natural-language-understanding/api/natural-language-understanding/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('natural_language_understanding') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: authenticator = get_authenticator_from_environment( - 'Natural Language Understanding') + 'natural_language_understanding') - BaseService.__init__( - self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Natural Language Understanding') + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) self.version = version ######################### @@ -176,13 +177,12 @@ def analyze(self, } url = '/v1/analyze' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -213,12 +213,11 @@ def list_models(self, **kwargs): params = {'version': self.version} url = '/v1/models' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -247,12 +246,11 @@ def delete_model(self, model_id, **kwargs): params = {'version': self.version} url = '/v1/models/{0}'.format(*self._encode_path_vars(model_id)) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -262,7 +260,7 @@ def delete_model(self, model_id, **kwargs): ############################################################################## -class AnalysisResults(object): +class AnalysisResults(): """ Results of the analysis, organized by feature. @@ -355,16 +353,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a AnalysisResults object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'language', 'analyzed_text', 'retrieved_url', 'usage', 'concepts', 'entities', 'keywords', 'categories', 'emotion', 'metadata', 'relations', 'semantic_roles', 'sentiment', 'syntax' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AnalysisResults: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'language' in _dict: args['language'] = _dict.get('language') if 'analyzed_text' in _dict: @@ -461,7 +459,7 @@ def __ne__(self, other): return not self == other -class AnalysisResultsMetadata(object): +class AnalysisResultsMetadata(): """ Webpage metadata, such as the author and the title of the page. @@ -500,12 +498,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a AnalysisResultsMetadata object from a json dictionary.""" args = {} - validKeys = ['authors', 'publication_date', 'title', 'image', 'feeds'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['authors', 'publication_date', 'title', 'image', 'feeds'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AnalysisResultsMetadata: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'authors' in _dict: args['authors'] = [ Author._from_dict(x) for x in (_dict.get('authors')) @@ -551,7 +549,7 @@ def __ne__(self, other): return not self == other -class AnalysisResultsUsage(object): +class AnalysisResultsUsage(): """ API usage information for the request. @@ -577,12 +575,12 @@ def __init__(self, *, features=None, text_characters=None, text_units=None): def _from_dict(cls, _dict): """Initialize a AnalysisResultsUsage object from a json dictionary.""" args = {} - validKeys = ['features', 'text_characters', 'text_units'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['features', 'text_characters', 'text_units'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AnalysisResultsUsage: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'features' in _dict: args['features'] = _dict.get('features') if 'text_characters' in _dict: @@ -618,7 +616,7 @@ def __ne__(self, other): return not self == other -class Author(object): +class Author(): """ The author of the analyzed content. @@ -637,12 +635,12 @@ def __init__(self, *, name=None): def _from_dict(cls, _dict): """Initialize a Author object from a json dictionary.""" args = {} - validKeys = ['name'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['name'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Author: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') return cls(**args) @@ -669,7 +667,7 @@ def __ne__(self, other): return not self == other -class CategoriesOptions(object): +class CategoriesOptions(): """ Returns a five-level taxonomy of the content. The top three categories are returned. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, @@ -703,12 +701,12 @@ def __init__(self, *, explanation=None, limit=None, model=None): def _from_dict(cls, _dict): """Initialize a CategoriesOptions object from a json dictionary.""" args = {} - validKeys = ['explanation', 'limit', 'model'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['explanation', 'limit', 'model'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CategoriesOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'explanation' in _dict: args['explanation'] = _dict.get('explanation') if 'limit' in _dict: @@ -743,7 +741,7 @@ def __ne__(self, other): return not self == other -class CategoriesRelevantText(object): +class CategoriesRelevantText(): """ Relevant text that contributed to the categorization. @@ -764,12 +762,12 @@ def __init__(self, *, text=None): def _from_dict(cls, _dict): """Initialize a CategoriesRelevantText object from a json dictionary.""" args = {} - validKeys = ['text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CategoriesRelevantText: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -796,7 +794,7 @@ def __ne__(self, other): return not self == other -class CategoriesResult(object): +class CategoriesResult(): """ A categorization of the analyzed text. @@ -832,12 +830,12 @@ def __init__(self, *, label=None, score=None, explanation=None): def _from_dict(cls, _dict): """Initialize a CategoriesResult object from a json dictionary.""" args = {} - validKeys = ['label', 'score', 'explanation'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['label', 'score', 'explanation'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CategoriesResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') if 'score' in _dict: @@ -873,7 +871,7 @@ def __ne__(self, other): return not self == other -class CategoriesResultExplanation(object): +class CategoriesResultExplanation(): """ Information that helps to explain what contributed to the categories result. @@ -898,12 +896,12 @@ def __init__(self, *, relevant_text=None): def _from_dict(cls, _dict): """Initialize a CategoriesResultExplanation object from a json dictionary.""" args = {} - validKeys = ['relevant_text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['relevant_text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CategoriesResultExplanation: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'relevant_text' in _dict: args['relevant_text'] = [ CategoriesRelevantText._from_dict(x) @@ -933,7 +931,7 @@ def __ne__(self, other): return not self == other -class ConceptsOptions(object): +class ConceptsOptions(): """ Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not @@ -956,12 +954,12 @@ def __init__(self, *, limit=None): def _from_dict(cls, _dict): """Initialize a ConceptsOptions object from a json dictionary.""" args = {} - validKeys = ['limit'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['limit'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ConceptsOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) @@ -988,7 +986,7 @@ def __ne__(self, other): return not self == other -class ConceptsResult(object): +class ConceptsResult(): """ The general concepts referenced or alluded to in the analyzed text. @@ -1017,12 +1015,12 @@ def __init__(self, *, text=None, relevance=None, dbpedia_resource=None): def _from_dict(cls, _dict): """Initialize a ConceptsResult object from a json dictionary.""" args = {} - validKeys = ['text', 'relevance', 'dbpedia_resource'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'relevance', 'dbpedia_resource'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ConceptsResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'relevance' in _dict: @@ -1058,7 +1056,7 @@ def __ne__(self, other): return not self == other -class DeleteModelResults(object): +class DeleteModelResults(): """ Delete model results. @@ -1077,12 +1075,12 @@ def __init__(self, *, deleted=None): def _from_dict(cls, _dict): """Initialize a DeleteModelResults object from a json dictionary.""" args = {} - validKeys = ['deleted'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['deleted'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DeleteModelResults: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'deleted' in _dict: args['deleted'] = _dict.get('deleted') return cls(**args) @@ -1109,7 +1107,7 @@ def __ne__(self, other): return not self == other -class DisambiguationResult(object): +class DisambiguationResult(): """ Disambiguation information for the entity. @@ -1136,12 +1134,12 @@ def __init__(self, *, name=None, dbpedia_resource=None, subtype=None): def _from_dict(cls, _dict): """Initialize a DisambiguationResult object from a json dictionary.""" args = {} - validKeys = ['name', 'dbpedia_resource', 'subtype'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['name', 'dbpedia_resource', 'subtype'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DisambiguationResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') if 'dbpedia_resource' in _dict: @@ -1177,7 +1175,7 @@ def __ne__(self, other): return not self == other -class DocumentEmotionResults(object): +class DocumentEmotionResults(): """ Emotion results for the document as a whole. @@ -1198,12 +1196,12 @@ def __init__(self, *, emotion=None): def _from_dict(cls, _dict): """Initialize a DocumentEmotionResults object from a json dictionary.""" args = {} - validKeys = ['emotion'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['emotion'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DocumentEmotionResults: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'emotion' in _dict: args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) return cls(**args) @@ -1230,7 +1228,7 @@ def __ne__(self, other): return not self == other -class DocumentSentimentResults(object): +class DocumentSentimentResults(): """ DocumentSentimentResults. @@ -1256,12 +1254,12 @@ def __init__(self, *, label=None, score=None): def _from_dict(cls, _dict): """Initialize a DocumentSentimentResults object from a json dictionary.""" args = {} - validKeys = ['label', 'score'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['label', 'score'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DocumentSentimentResults: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') if 'score' in _dict: @@ -1292,7 +1290,7 @@ def __ne__(self, other): return not self == other -class EmotionOptions(object): +class EmotionOptions(): """ Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze @@ -1322,12 +1320,12 @@ def __init__(self, *, document=None, targets=None): def _from_dict(cls, _dict): """Initialize a EmotionOptions object from a json dictionary.""" args = {} - validKeys = ['document', 'targets'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document', 'targets'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EmotionOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: @@ -1358,7 +1356,7 @@ def __ne__(self, other): return not self == other -class EmotionResult(object): +class EmotionResult(): """ The detected anger, disgust, fear, joy, or sadness that is conveyed by the content. Emotion information can be returned for detected entities, keywords, or user-specified @@ -1386,12 +1384,12 @@ def __init__(self, *, document=None, targets=None): def _from_dict(cls, _dict): """Initialize a EmotionResult object from a json dictionary.""" args = {} - validKeys = ['document', 'targets'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document', 'targets'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EmotionResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = DocumentEmotionResults._from_dict( _dict.get('document')) @@ -1426,7 +1424,7 @@ def __ne__(self, other): return not self == other -class EmotionScores(object): +class EmotionScores(): """ EmotionScores. @@ -1473,12 +1471,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a EmotionScores object from a json dictionary.""" args = {} - validKeys = ['anger', 'disgust', 'fear', 'joy', 'sadness'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['anger', 'disgust', 'fear', 'joy', 'sadness'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EmotionScores: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'anger' in _dict: args['anger'] = _dict.get('anger') if 'disgust' in _dict: @@ -1521,7 +1519,7 @@ def __ne__(self, other): return not self == other -class EntitiesOptions(object): +class EntitiesOptions(): """ Identifies people, cities, organizations, and other entities in the content. See [Entity types and @@ -1573,12 +1571,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a EntitiesOptions object from a json dictionary.""" args = {} - validKeys = ['limit', 'mentions', 'model', 'sentiment', 'emotion'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['limit', 'mentions', 'model', 'sentiment', 'emotion'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EntitiesOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'limit' in _dict: args['limit'] = _dict.get('limit') if 'mentions' in _dict: @@ -1621,7 +1619,7 @@ def __ne__(self, other): return not self == other -class EntitiesResult(object): +class EntitiesResult(): """ The important people, places, geopolitical entities and other types of entities in your content. @@ -1691,15 +1689,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a EntitiesResult object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'type', 'text', 'relevance', 'confidence', 'mentions', 'count', 'emotion', 'sentiment', 'disambiguation' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EntitiesResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'text' in _dict: @@ -1762,7 +1760,7 @@ def __ne__(self, other): return not self == other -class EntityMention(object): +class EntityMention(): """ EntityMention. @@ -1795,12 +1793,12 @@ def __init__(self, *, text=None, location=None, confidence=None): def _from_dict(cls, _dict): """Initialize a EntityMention object from a json dictionary.""" args = {} - validKeys = ['text', 'location', 'confidence'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'location', 'confidence'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EntityMention: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: @@ -1835,7 +1833,7 @@ def __ne__(self, other): return not self == other -class FeatureSentimentResults(object): +class FeatureSentimentResults(): """ FeatureSentimentResults. @@ -1856,12 +1854,12 @@ def __init__(self, *, score=None): def _from_dict(cls, _dict): """Initialize a FeatureSentimentResults object from a json dictionary.""" args = {} - validKeys = ['score'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['score'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class FeatureSentimentResults: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'score' in _dict: args['score'] = _dict.get('score') return cls(**args) @@ -1888,7 +1886,7 @@ def __ne__(self, other): return not self == other -class Features(object): +class Features(): """ Analysis features and options. @@ -2018,15 +2016,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Features object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'concepts', 'emotion', 'entities', 'keywords', 'metadata', 'relations', 'semantic_roles', 'sentiment', 'categories', 'syntax' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Features: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'concepts' in _dict: args['concepts'] = ConceptsOptions._from_dict(_dict.get('concepts')) if 'emotion' in _dict: @@ -2093,7 +2091,7 @@ def __ne__(self, other): return not self == other -class Feed(object): +class Feed(): """ RSS or ATOM feed found on the webpage. @@ -2112,12 +2110,12 @@ def __init__(self, *, link=None): def _from_dict(cls, _dict): """Initialize a Feed object from a json dictionary.""" args = {} - validKeys = ['link'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['link'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Feed: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'link' in _dict: args['link'] = _dict.get('link') return cls(**args) @@ -2144,7 +2142,7 @@ def __ne__(self, other): return not self == other -class KeywordsOptions(object): +class KeywordsOptions(): """ Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, @@ -2175,12 +2173,12 @@ def __init__(self, *, limit=None, sentiment=None, emotion=None): def _from_dict(cls, _dict): """Initialize a KeywordsOptions object from a json dictionary.""" args = {} - validKeys = ['limit', 'sentiment', 'emotion'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['limit', 'sentiment', 'emotion'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class KeywordsOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'limit' in _dict: args['limit'] = _dict.get('limit') if 'sentiment' in _dict: @@ -2215,7 +2213,7 @@ def __ne__(self, other): return not self == other -class KeywordsResult(object): +class KeywordsResult(): """ The important keywords in the content, organized by relevance. @@ -2260,12 +2258,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a KeywordsResult object from a json dictionary.""" args = {} - validKeys = ['count', 'relevance', 'text', 'emotion', 'sentiment'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['count', 'relevance', 'text', 'emotion', 'sentiment'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class KeywordsResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'count' in _dict: args['count'] = _dict.get('count') if 'relevance' in _dict: @@ -2309,7 +2307,7 @@ def __ne__(self, other): return not self == other -class ListModelsResults(object): +class ListModelsResults(): """ Custom models that are available for entities and relations. @@ -2328,12 +2326,12 @@ def __init__(self, *, models=None): def _from_dict(cls, _dict): """Initialize a ListModelsResults object from a json dictionary.""" args = {} - validKeys = ['models'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['models'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ListModelsResults: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'models' in _dict: args['models'] = [ Model._from_dict(x) for x in (_dict.get('models')) @@ -2362,7 +2360,7 @@ def __ne__(self, other): return not self == other -class MetadataOptions(object): +class MetadataOptions(): """ Returns information from the document, including author name, title, RSS/ATOM feeds, prominent page image, and publication date. Supports URL and HTML input types only. @@ -2401,7 +2399,7 @@ def __ne__(self, other): return not self == other -class Model(object): +class Model(): """ Model. @@ -2462,15 +2460,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Model object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'status', 'model_id', 'language', 'description', 'workspace_id', 'version', 'version_description', 'created' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Model: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') if 'model_id' in _dict: @@ -2527,7 +2525,7 @@ def __ne__(self, other): return not self == other -class RelationArgument(object): +class RelationArgument(): """ RelationArgument. @@ -2555,12 +2553,12 @@ def __init__(self, *, entities=None, location=None, text=None): def _from_dict(cls, _dict): """Initialize a RelationArgument object from a json dictionary.""" args = {} - validKeys = ['entities', 'location', 'text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['entities', 'location', 'text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RelationArgument: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'entities' in _dict: args['entities'] = [ RelationEntity._from_dict(x) for x in (_dict.get('entities')) @@ -2597,7 +2595,7 @@ def __ne__(self, other): return not self == other -class RelationEntity(object): +class RelationEntity(): """ An entity that corresponds with an argument in a relation. @@ -2619,12 +2617,12 @@ def __init__(self, *, text=None, type=None): def _from_dict(cls, _dict): """Initialize a RelationEntity object from a json dictionary.""" args = {} - validKeys = ['text', 'type'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'type'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RelationEntity: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'type' in _dict: @@ -2655,7 +2653,7 @@ def __ne__(self, other): return not self == other -class RelationsOptions(object): +class RelationsOptions(): """ Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert @@ -2683,12 +2681,12 @@ def __init__(self, *, model=None): def _from_dict(cls, _dict): """Initialize a RelationsOptions object from a json dictionary.""" args = {} - validKeys = ['model'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['model'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RelationsOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'model' in _dict: args['model'] = _dict.get('model') return cls(**args) @@ -2715,7 +2713,7 @@ def __ne__(self, other): return not self == other -class RelationsResult(object): +class RelationsResult(): """ The relations between entities found in the content. @@ -2747,12 +2745,12 @@ def __init__(self, *, score=None, sentence=None, type=None, arguments=None): def _from_dict(cls, _dict): """Initialize a RelationsResult object from a json dictionary.""" args = {} - validKeys = ['score', 'sentence', 'type', 'arguments'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['score', 'sentence', 'type', 'arguments'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RelationsResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'score' in _dict: args['score'] = _dict.get('score') if 'sentence' in _dict: @@ -2793,7 +2791,7 @@ def __ne__(self, other): return not self == other -class SemanticRolesEntity(object): +class SemanticRolesEntity(): """ SemanticRolesEntity. @@ -2815,12 +2813,12 @@ def __init__(self, *, type=None, text=None): def _from_dict(cls, _dict): """Initialize a SemanticRolesEntity object from a json dictionary.""" args = {} - validKeys = ['type', 'text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['type', 'text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SemanticRolesEntity: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'text' in _dict: @@ -2851,7 +2849,7 @@ def __ne__(self, other): return not self == other -class SemanticRolesKeyword(object): +class SemanticRolesKeyword(): """ SemanticRolesKeyword. @@ -2870,12 +2868,12 @@ def __init__(self, *, text=None): def _from_dict(cls, _dict): """Initialize a SemanticRolesKeyword object from a json dictionary.""" args = {} - validKeys = ['text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SemanticRolesKeyword: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -2902,7 +2900,7 @@ def __ne__(self, other): return not self == other -class SemanticRolesOptions(object): +class SemanticRolesOptions(): """ Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. @@ -2933,12 +2931,12 @@ def __init__(self, *, limit=None, keywords=None, entities=None): def _from_dict(cls, _dict): """Initialize a SemanticRolesOptions object from a json dictionary.""" args = {} - validKeys = ['limit', 'keywords', 'entities'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['limit', 'keywords', 'entities'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SemanticRolesOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'limit' in _dict: args['limit'] = _dict.get('limit') if 'keywords' in _dict: @@ -2973,7 +2971,7 @@ def __ne__(self, other): return not self == other -class SemanticRolesResult(object): +class SemanticRolesResult(): """ The object containing the actions and the objects the actions act upon. @@ -3010,12 +3008,12 @@ def __init__(self, *, sentence=None, subject=None, action=None, def _from_dict(cls, _dict): """Initialize a SemanticRolesResult object from a json dictionary.""" args = {} - validKeys = ['sentence', 'subject', 'action', 'object'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['sentence', 'subject', 'action', 'object'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SemanticRolesResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'sentence' in _dict: args['sentence'] = _dict.get('sentence') if 'subject' in _dict: @@ -3057,7 +3055,7 @@ def __ne__(self, other): return not self == other -class SemanticRolesResultAction(object): +class SemanticRolesResultAction(): """ The extracted action from the sentence. @@ -3082,12 +3080,12 @@ def __init__(self, *, text=None, normalized=None, verb=None): def _from_dict(cls, _dict): """Initialize a SemanticRolesResultAction object from a json dictionary.""" args = {} - validKeys = ['text', 'normalized', 'verb'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'normalized', 'verb'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SemanticRolesResultAction: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'normalized' in _dict: @@ -3122,7 +3120,7 @@ def __ne__(self, other): return not self == other -class SemanticRolesResultObject(object): +class SemanticRolesResultObject(): """ The extracted object from the sentence. @@ -3146,12 +3144,12 @@ def __init__(self, *, text=None, keywords=None): def _from_dict(cls, _dict): """Initialize a SemanticRolesResultObject object from a json dictionary.""" args = {} - validKeys = ['text', 'keywords'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'keywords'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SemanticRolesResultObject: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'keywords' in _dict: @@ -3185,7 +3183,7 @@ def __ne__(self, other): return not self == other -class SemanticRolesResultSubject(object): +class SemanticRolesResultSubject(): """ The extracted subject from the sentence. @@ -3214,12 +3212,12 @@ def __init__(self, *, text=None, entities=None, keywords=None): def _from_dict(cls, _dict): """Initialize a SemanticRolesResultSubject object from a json dictionary.""" args = {} - validKeys = ['text', 'entities', 'keywords'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'entities', 'keywords'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SemanticRolesResultSubject: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'entities' in _dict: @@ -3260,7 +3258,7 @@ def __ne__(self, other): return not self == other -class SemanticRolesVerb(object): +class SemanticRolesVerb(): """ SemanticRolesVerb. @@ -3282,12 +3280,12 @@ def __init__(self, *, text=None, tense=None): def _from_dict(cls, _dict): """Initialize a SemanticRolesVerb object from a json dictionary.""" args = {} - validKeys = ['text', 'tense'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'tense'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SemanticRolesVerb: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'tense' in _dict: @@ -3318,7 +3316,7 @@ def __ne__(self, other): return not self == other -class SentenceResult(object): +class SentenceResult(): """ SentenceResult. @@ -3342,12 +3340,12 @@ def __init__(self, *, text=None, location=None): def _from_dict(cls, _dict): """Initialize a SentenceResult object from a json dictionary.""" args = {} - validKeys = ['text', 'location'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SentenceResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: @@ -3378,7 +3376,7 @@ def __ne__(self, other): return not self == other -class SentimentOptions(object): +class SentimentOptions(): """ Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and @@ -3408,12 +3406,12 @@ def __init__(self, *, document=None, targets=None): def _from_dict(cls, _dict): """Initialize a SentimentOptions object from a json dictionary.""" args = {} - validKeys = ['document', 'targets'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document', 'targets'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SentimentOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: @@ -3444,7 +3442,7 @@ def __ne__(self, other): return not self == other -class SentimentResult(object): +class SentimentResult(): """ The sentiment of the content. @@ -3470,12 +3468,12 @@ def __init__(self, *, document=None, targets=None): def _from_dict(cls, _dict): """Initialize a SentimentResult object from a json dictionary.""" args = {} - validKeys = ['document', 'targets'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document', 'targets'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SentimentResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = DocumentSentimentResults._from_dict( _dict.get('document')) @@ -3510,7 +3508,7 @@ def __ne__(self, other): return not self == other -class SyntaxOptions(object): +class SyntaxOptions(): """ Returns tokens and sentences from the input text. @@ -3534,12 +3532,12 @@ def __init__(self, *, tokens=None, sentences=None): def _from_dict(cls, _dict): """Initialize a SyntaxOptions object from a json dictionary.""" args = {} - validKeys = ['tokens', 'sentences'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['tokens', 'sentences'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SyntaxOptions: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'tokens' in _dict: args['tokens'] = SyntaxOptionsTokens._from_dict(_dict.get('tokens')) if 'sentences' in _dict: @@ -3570,7 +3568,7 @@ def __ne__(self, other): return not self == other -class SyntaxOptionsTokens(object): +class SyntaxOptionsTokens(): """ Tokenization options. @@ -3596,12 +3594,12 @@ def __init__(self, *, lemma=None, part_of_speech=None): def _from_dict(cls, _dict): """Initialize a SyntaxOptionsTokens object from a json dictionary.""" args = {} - validKeys = ['lemma', 'part_of_speech'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['lemma', 'part_of_speech'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SyntaxOptionsTokens: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'lemma' in _dict: args['lemma'] = _dict.get('lemma') if 'part_of_speech' in _dict: @@ -3632,7 +3630,7 @@ def __ne__(self, other): return not self == other -class SyntaxResult(object): +class SyntaxResult(): """ Tokens and sentences returned from syntax analysis. @@ -3654,12 +3652,12 @@ def __init__(self, *, tokens=None, sentences=None): def _from_dict(cls, _dict): """Initialize a SyntaxResult object from a json dictionary.""" args = {} - validKeys = ['tokens', 'sentences'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['tokens', 'sentences'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SyntaxResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'tokens' in _dict: args['tokens'] = [ TokenResult._from_dict(x) for x in (_dict.get('tokens')) @@ -3694,7 +3692,7 @@ def __ne__(self, other): return not self == other -class TargetedEmotionResults(object): +class TargetedEmotionResults(): """ Emotion results for a specified target. @@ -3717,12 +3715,12 @@ def __init__(self, *, text=None, emotion=None): def _from_dict(cls, _dict): """Initialize a TargetedEmotionResults object from a json dictionary.""" args = {} - validKeys = ['text', 'emotion'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'emotion'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TargetedEmotionResults: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'emotion' in _dict: @@ -3753,7 +3751,7 @@ def __ne__(self, other): return not self == other -class TargetedSentimentResults(object): +class TargetedSentimentResults(): """ TargetedSentimentResults. @@ -3777,12 +3775,12 @@ def __init__(self, *, text=None, score=None): def _from_dict(cls, _dict): """Initialize a TargetedSentimentResults object from a json dictionary.""" args = {} - validKeys = ['text', 'score'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'score'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TargetedSentimentResults: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'score' in _dict: @@ -3813,7 +3811,7 @@ def __ne__(self, other): return not self == other -class TokenResult(object): +class TokenResult(): """ TokenResult. @@ -3854,12 +3852,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a TokenResult object from a json dictionary.""" args = {} - validKeys = ['text', 'part_of_speech', 'location', 'lemma'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'part_of_speech', 'location', 'lemma'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TokenResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'part_of_speech' in _dict: diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index a7f4b9081..2bdd20062 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -38,6 +38,7 @@ 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 read_external_sources ############################################################################## # Service @@ -47,14 +48,12 @@ class PersonalityInsightsV3(BaseService): """The Personality Insights V3 service.""" - default_url = 'https://gateway.watsonplatform.net/personality-insights/api' + default_service_url = 'https://gateway.watsonplatform.net/personality-insights/api' def __init__( self, version, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Personality Insights service. @@ -70,26 +69,28 @@ def __init__( application, and don't change it until your application is ready for a later version. - :param str url: The base url to use when contacting the service (e.g. - "https://gateway.watsonplatform.net/personality-insights/api/personality-insights/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('personality_insights') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: authenticator = get_authenticator_from_environment( - 'Personality Insights') + 'personality_insights') - BaseService.__init__( - self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Personality Insights') + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) self.version = version ######################### @@ -290,7 +291,7 @@ class AcceptLanguage(Enum): ############################################################################## -class Behavior(object): +class Behavior(): """ The temporal behavior for the input content. @@ -327,12 +328,12 @@ def __init__(self, trait_id, name, category, percentage): def _from_dict(cls, _dict): """Initialize a Behavior object from a json dictionary.""" args = {} - validKeys = ['trait_id', 'name', 'category', 'percentage'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['trait_id', 'name', 'category', 'percentage'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Behavior: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'trait_id' in _dict: args['trait_id'] = _dict.get('trait_id') else: @@ -383,7 +384,7 @@ def __ne__(self, other): return not self == other -class ConsumptionPreferences(object): +class ConsumptionPreferences(): """ A consumption preference that the service inferred from the input content. @@ -425,12 +426,12 @@ def __init__(self, consumption_preference_id, name, score): def _from_dict(cls, _dict): """Initialize a ConsumptionPreferences object from a json dictionary.""" args = {} - validKeys = ['consumption_preference_id', 'name', 'score'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['consumption_preference_id', 'name', 'score'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ConsumptionPreferences: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'consumption_preference_id' in _dict: args['consumption_preference_id'] = _dict.get( 'consumption_preference_id') @@ -479,7 +480,7 @@ def __ne__(self, other): return not self == other -class ConsumptionPreferencesCategory(object): +class ConsumptionPreferencesCategory(): """ The consumption preferences that the service inferred from the input content. @@ -513,15 +514,15 @@ def __init__(self, consumption_preference_category_id, name, def _from_dict(cls, _dict): """Initialize a ConsumptionPreferencesCategory object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'consumption_preference_category_id', 'name', 'consumption_preferences' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ConsumptionPreferencesCategory: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'consumption_preference_category_id' in _dict: args['consumption_preference_category_id'] = _dict.get( 'consumption_preference_category_id') @@ -577,7 +578,7 @@ def __ne__(self, other): return not self == other -class Content(object): +class Content(): """ The full input content that the service is to analyze. @@ -598,12 +599,12 @@ def __init__(self, content_items): def _from_dict(cls, _dict): """Initialize a Content object from a json dictionary.""" args = {} - validKeys = ['content_items', 'contentItems'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['content_items', 'contentItems'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Content: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'contentItems' in _dict: args['content_items'] = [ ContentItem._from_dict(x) for x in (_dict.get('contentItems')) @@ -636,7 +637,7 @@ def __ne__(self, other): return not self == other -class ContentItem(object): +class ContentItem(): """ An input content item that the service is to analyze. @@ -731,15 +732,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a ContentItem object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'content', 'id', 'created', 'updated', 'contenttype', 'language', 'parentid', 'reply', 'forward' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ContentItem: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'content' in _dict: args['content'] = _dict.get('content') else: @@ -827,7 +828,7 @@ class LanguageEnum(Enum): KO = "ko" -class Profile(object): +class Profile(): """ The personality profile that the service generated for the input content. @@ -916,16 +917,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Profile object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'processed_language', 'word_count', 'word_count_message', 'personality', 'needs', 'values', 'behavior', 'consumption_preferences', 'warnings' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Profile: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'processed_language' in _dict: args['processed_language'] = _dict.get('processed_language') else: @@ -1031,7 +1032,7 @@ class ProcessedLanguageEnum(Enum): KO = "ko" -class Trait(object): +class Trait(): """ The characteristics that the service inferred from the input content. @@ -1128,15 +1129,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Trait object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'trait_id', 'name', 'category', 'percentile', 'raw_score', 'significant', 'children' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Trait: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'trait_id' in _dict: args['trait_id'] = _dict.get('trait_id') else: @@ -1210,7 +1211,7 @@ class CategoryEnum(Enum): VALUES = "values" -class Warning(object): +class Warning(): """ A warning message that is associated with the input content. @@ -1260,12 +1261,12 @@ def __init__(self, warning_id, message): def _from_dict(cls, _dict): """Initialize a Warning object from a json dictionary.""" args = {} - validKeys = ['warning_id', 'message'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['warning_id', 'message'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Warning: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'warning_id' in _dict: args['warning_id'] = _dict.get('warning_id') else: diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 1efe4b2dc..9865543c4 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -39,6 +39,7 @@ 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 read_external_sources ############################################################################## # Service @@ -48,36 +49,36 @@ class SpeechToTextV1(BaseService): """The Speech to Text V1 service.""" - default_url = 'https://stream.watsonplatform.net/speech-to-text/api' + default_service_url = 'https://stream.watsonplatform.net/speech-to-text/api' def __init__( self, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Speech to Text service. - :param str url: The base url to use when contacting the service (e.g. - "https://stream.watsonplatform.net/speech-to-text/api/speech-to-text/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('speech_to_text') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: - authenticator = get_authenticator_from_environment('Speech to Text') + authenticator = get_authenticator_from_environment('speech_to_text') - BaseService.__init__( - self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Speech to Text') + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) ######################### # Models @@ -105,8 +106,10 @@ def list_models(self, **kwargs): headers.update(sdk_headers) url = '/v1/models' - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -137,8 +140,10 @@ def get_model(self, model_id, **kwargs): headers.update(sdk_headers) url = '/v1/models/{0}'.format(*self._encode_path_vars(model_id)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -423,13 +428,12 @@ def recognize(self, data = audio url = '/v1/recognize' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -500,12 +504,11 @@ def register_callback(self, callback_url, *, user_secret=None, **kwargs): params = {'callback_url': callback_url, 'user_secret': user_secret} url = '/v1/register_callback' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -538,12 +541,11 @@ def unregister_callback(self, callback_url, **kwargs): params = {'callback_url': callback_url} url = '/v1/unregister_callback' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -903,13 +905,12 @@ def create_job(self, data = audio url = '/v1/recognitions' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -940,8 +941,10 @@ def check_jobs(self, **kwargs): headers.update(sdk_headers) url = '/v1/recognitions' - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -980,8 +983,10 @@ def check_job(self, id, **kwargs): headers.update(sdk_headers) url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -1015,8 +1020,10 @@ def delete_job(self, id, **kwargs): headers.update(sdk_headers) url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) - request = self.prepare_request( - method='DELETE', url=url, headers=headers, accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + accept_json=False) response = self.send(request) return response @@ -1100,12 +1107,11 @@ def create_language_model(self, } url = '/v1/customizations' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + data=data, + accept_json=True) response = self.send(request) return response @@ -1140,12 +1146,11 @@ def list_language_models(self, *, language=None, **kwargs): params = {'language': language} url = '/v1/customizations' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1179,8 +1184,10 @@ def get_language_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -1216,8 +1223,10 @@ def delete_language_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='DELETE', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -1307,12 +1316,11 @@ def train_language_model(self, url = '/v1/customizations/{0}/train'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1350,8 +1358,10 @@ def reset_language_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}/reset'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='POST', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -1397,8 +1407,10 @@ def upgrade_language_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}/upgrade_model'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='POST', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -1437,8 +1449,10 @@ def list_corpora(self, customization_id, **kwargs): url = '/v1/customizations/{0}/corpora'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -1545,18 +1559,17 @@ def add_corpus(self, params = {'allow_overwrite': allow_overwrite} - form_data = {} - form_data['corpus_file'] = (None, corpus_file, 'text/plain') + form_data = [] + form_data.append(('corpus_file', (None, corpus_file, 'text/plain'))) url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) response = self.send(request) return response @@ -1595,8 +1608,10 @@ def get_corpus(self, customization_id, corpus_name, **kwargs): url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -1639,8 +1654,10 @@ def delete_corpus(self, customization_id, corpus_name, **kwargs): url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) - request = self.prepare_request( - method='DELETE', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -1704,12 +1721,11 @@ def list_words(self, url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -1794,12 +1810,11 @@ def add_words(self, customization_id, words, **kwargs): url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + data=data, + accept_json=True) response = self.send(request) return response @@ -1902,8 +1917,11 @@ def add_word(self, url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) - request = self.prepare_request( - method='PUT', url=url, headers=headers, data=data, accept_json=True) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + data=data, + accept_json=True) response = self.send(request) return response @@ -1943,8 +1961,10 @@ def get_word(self, customization_id, word_name, **kwargs): url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -1988,8 +2008,10 @@ def delete_word(self, customization_id, word_name, **kwargs): url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) - request = self.prepare_request( - method='DELETE', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -2028,8 +2050,10 @@ def list_grammars(self, customization_id, **kwargs): url = '/v1/customizations/{0}/grammars'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -2141,13 +2165,12 @@ def add_grammar(self, url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2186,8 +2209,10 @@ def get_grammar(self, customization_id, grammar_name, **kwargs): url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -2229,8 +2254,10 @@ def delete_grammar(self, customization_id, grammar_name, **kwargs): url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) - request = self.prepare_request( - method='DELETE', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -2292,12 +2319,11 @@ def create_acoustic_model(self, } url = '/v1/acoustic_customizations' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + data=data, + accept_json=True) response = self.send(request) return response @@ -2332,12 +2358,11 @@ def list_acoustic_models(self, *, language=None, **kwargs): params = {'language': language} url = '/v1/acoustic_customizations' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2371,8 +2396,10 @@ def get_acoustic_model(self, customization_id, **kwargs): url = '/v1/acoustic_customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -2408,8 +2435,10 @@ def delete_acoustic_model(self, customization_id, **kwargs): url = '/v1/acoustic_customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='DELETE', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -2499,12 +2528,11 @@ def train_acoustic_model(self, url = '/v1/acoustic_customizations/{0}/train'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2544,8 +2572,10 @@ def reset_acoustic_model(self, customization_id, **kwargs): url = '/v1/acoustic_customizations/{0}/reset'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='POST', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -2621,12 +2651,11 @@ def upgrade_acoustic_model(self, url = '/v1/acoustic_customizations/{0}/upgrade_model'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -2667,8 +2696,10 @@ def list_audio(self, customization_id, **kwargs): url = '/v1/acoustic_customizations/{0}/audio'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -2840,13 +2871,12 @@ def add_audio(self, url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) response = self.send(request) return response @@ -2899,8 +2929,10 @@ def get_audio(self, customization_id, audio_name, **kwargs): url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -2943,8 +2975,10 @@ def delete_audio(self, customization_id, audio_name, **kwargs): url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) - request = self.prepare_request( - method='DELETE', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -2986,12 +3020,11 @@ def delete_user_data(self, customer_id, **kwargs): params = {'customer_id': customer_id} url = '/v1/user_data' - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -3310,7 +3343,7 @@ class ContainedContentType(Enum): ############################################################################## -class AcousticModel(object): +class AcousticModel(): """ Information about an existing custom acoustic model. @@ -3438,16 +3471,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a AcousticModel object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'customization_id', 'created', 'updated', 'language', 'versions', 'owner', 'name', 'description', 'base_model_name', 'status', 'progress', 'warnings' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AcousticModel: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'customization_id' in _dict: args['customization_id'] = _dict.get('customization_id') else: @@ -3544,7 +3577,7 @@ class StatusEnum(Enum): FAILED = "failed" -class AcousticModels(object): +class AcousticModels(): """ Information about existing custom acoustic models. @@ -3571,12 +3604,12 @@ def __init__(self, customizations): def _from_dict(cls, _dict): """Initialize a AcousticModels object from a json dictionary.""" args = {} - validKeys = ['customizations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['customizations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AcousticModels: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'customizations' in _dict: args['customizations'] = [ AcousticModel._from_dict(x) @@ -3612,7 +3645,7 @@ def __ne__(self, other): return not self == other -class AudioDetails(object): +class AudioDetails(): """ Information about an audio resource from a custom acoustic model. @@ -3671,12 +3704,12 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a AudioDetails object from a json dictionary.""" args = {} - validKeys = ['type', 'codec', 'frequency', 'compression'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['type', 'codec', 'frequency', 'compression'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AudioDetails: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'codec' in _dict: @@ -3739,7 +3772,7 @@ class CompressionEnum(Enum): GZIP = "gzip" -class AudioListing(object): +class AudioListing(): """ Information about an audio resource from a custom acoustic model. @@ -3819,14 +3852,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a AudioListing object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'duration', 'name', 'details', 'status', 'container', 'audio' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AudioListing: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'duration' in _dict: args['duration'] = _dict.get('duration') if 'name' in _dict: @@ -3891,7 +3924,7 @@ class StatusEnum(Enum): INVALID = "invalid" -class AudioMetrics(object): +class AudioMetrics(): """ If audio metrics are requested, information about the signal characteristics of the input audio. @@ -3924,12 +3957,12 @@ def __init__(self, sampling_interval, accumulated): def _from_dict(cls, _dict): """Initialize a AudioMetrics object from a json dictionary.""" args = {} - validKeys = ['sampling_interval', 'accumulated'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['sampling_interval', 'accumulated'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AudioMetrics: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'sampling_interval' in _dict: args['sampling_interval'] = _dict.get('sampling_interval') else: @@ -3970,7 +4003,7 @@ def __ne__(self, other): return not self == other -class AudioMetricsDetails(object): +class AudioMetricsDetails(): """ Detailed information about the signal characteristics of the input audio. @@ -4088,16 +4121,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a AudioMetricsDetails object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'final', 'end_time', 'signal_to_noise_ratio', 'speech_ratio', 'high_frequency_loss', 'direct_current_offset', 'clipping_rate', 'speech_level', 'non_speech_level' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AudioMetricsDetails: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'final' in _dict: args['final'] = _dict.get('final') else: @@ -4209,7 +4242,7 @@ def __ne__(self, other): return not self == other -class AudioMetricsHistogramBin(object): +class AudioMetricsHistogramBin(): """ A bin with defined boundaries that indicates the number of values in a range of signal characteristics for a histogram. The first and last bins of a histogram are the @@ -4237,12 +4270,12 @@ def __init__(self, begin, end, count): def _from_dict(cls, _dict): """Initialize a AudioMetricsHistogramBin object from a json dictionary.""" args = {} - validKeys = ['begin', 'end', 'count'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['begin', 'end', 'count'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AudioMetricsHistogramBin: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'begin' in _dict: args['begin'] = _dict.get('begin') else: @@ -4289,7 +4322,7 @@ def __ne__(self, other): return not self == other -class AudioResource(object): +class AudioResource(): """ Information about an audio resource from a custom acoustic model. @@ -4347,12 +4380,12 @@ def __init__(self, duration, name, details, status): def _from_dict(cls, _dict): """Initialize a AudioResource object from a json dictionary.""" args = {} - validKeys = ['duration', 'name', 'details', 'status'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['duration', 'name', 'details', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AudioResource: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'duration' in _dict: args['duration'] = _dict.get('duration') else: @@ -4423,7 +4456,7 @@ class StatusEnum(Enum): INVALID = "invalid" -class AudioResources(object): +class AudioResources(): """ Information about the audio resources from a custom acoustic model. @@ -4455,12 +4488,12 @@ def __init__(self, total_minutes_of_audio, audio): def _from_dict(cls, _dict): """Initialize a AudioResources object from a json dictionary.""" args = {} - validKeys = ['total_minutes_of_audio', 'audio'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['total_minutes_of_audio', 'audio'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class AudioResources: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'total_minutes_of_audio' in _dict: args['total_minutes_of_audio'] = _dict.get('total_minutes_of_audio') else: @@ -4502,7 +4535,7 @@ def __ne__(self, other): return not self == other -class Corpora(object): +class Corpora(): """ Information about the corpora from a custom language model. @@ -4525,12 +4558,12 @@ def __init__(self, corpora): def _from_dict(cls, _dict): """Initialize a Corpora object from a json dictionary.""" args = {} - validKeys = ['corpora'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['corpora'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Corpora: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'corpora' in _dict: args['corpora'] = [ Corpus._from_dict(x) for x in (_dict.get('corpora')) @@ -4562,7 +4595,7 @@ def __ne__(self, other): return not self == other -class Corpus(object): +class Corpus(): """ Information about a corpus from a custom language model. @@ -4619,14 +4652,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Corpus object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'name', 'total_words', 'out_of_vocabulary_words', 'status', 'error' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Corpus: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -4698,7 +4731,7 @@ class StatusEnum(Enum): UNDETERMINED = "undetermined" -class CustomWord(object): +class CustomWord(): """ Information about a word that is to be added to a custom language model. @@ -4759,12 +4792,12 @@ def __init__(self, *, word=None, sounds_like=None, display_as=None): def _from_dict(cls, _dict): """Initialize a CustomWord object from a json dictionary.""" args = {} - validKeys = ['word', 'sounds_like', 'display_as'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['word', 'sounds_like', 'display_as'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class CustomWord: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'word' in _dict: args['word'] = _dict.get('word') if 'sounds_like' in _dict: @@ -4799,7 +4832,7 @@ def __ne__(self, other): return not self == other -class Grammar(object): +class Grammar(): """ Information about a grammar from a custom language model. @@ -4848,12 +4881,12 @@ def __init__(self, name, out_of_vocabulary_words, status, *, error=None): def _from_dict(cls, _dict): """Initialize a Grammar object from a json dictionary.""" args = {} - validKeys = ['name', 'out_of_vocabulary_words', 'status', 'error'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['name', 'out_of_vocabulary_words', 'status', 'error'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Grammar: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -4918,7 +4951,7 @@ class StatusEnum(Enum): UNDETERMINED = "undetermined" -class Grammars(object): +class Grammars(): """ Information about the grammars from a custom language model. @@ -4941,12 +4974,12 @@ def __init__(self, grammars): def _from_dict(cls, _dict): """Initialize a Grammars object from a json dictionary.""" args = {} - validKeys = ['grammars'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['grammars'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Grammars: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'grammars' in _dict: args['grammars'] = [ Grammar._from_dict(x) for x in (_dict.get('grammars')) @@ -4978,7 +5011,7 @@ def __ne__(self, other): return not self == other -class KeywordResult(object): +class KeywordResult(): """ Information about a match for a keyword from speech recognition results. @@ -5010,12 +5043,12 @@ def __init__(self, normalized_text, start_time, end_time, confidence): def _from_dict(cls, _dict): """Initialize a KeywordResult object from a json dictionary.""" args = {} - validKeys = ['normalized_text', 'start_time', 'end_time', 'confidence'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['normalized_text', 'start_time', 'end_time', 'confidence'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class KeywordResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'normalized_text' in _dict: args['normalized_text'] = _dict.get('normalized_text') else: @@ -5071,7 +5104,7 @@ def __ne__(self, other): return not self == other -class LanguageModel(object): +class LanguageModel(): """ Information about an existing custom language model. @@ -5232,16 +5265,16 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a LanguageModel object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'customization_id', 'created', 'updated', 'language', 'dialect', 'versions', 'owner', 'name', 'description', 'base_model_name', 'status', 'progress', 'error', 'warnings' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class LanguageModel: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'customization_id' in _dict: args['customization_id'] = _dict.get('customization_id') else: @@ -5346,7 +5379,7 @@ class StatusEnum(Enum): FAILED = "failed" -class LanguageModels(object): +class LanguageModels(): """ Information about existing custom language models. @@ -5373,12 +5406,12 @@ def __init__(self, customizations): def _from_dict(cls, _dict): """Initialize a LanguageModels object from a json dictionary.""" args = {} - validKeys = ['customizations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['customizations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class LanguageModels: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'customizations' in _dict: args['customizations'] = [ LanguageModel._from_dict(x) @@ -5414,7 +5447,7 @@ def __ne__(self, other): return not self == other -class ProcessedAudio(object): +class ProcessedAudio(): """ Detailed timing information about the service's processing of the input audio. @@ -5482,14 +5515,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a ProcessedAudio object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'received', 'seen_by_engine', 'transcription', 'speaker_labels' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ProcessedAudio: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'received' in _dict: args['received'] = _dict.get('received') else: @@ -5540,7 +5573,7 @@ def __ne__(self, other): return not self == other -class ProcessingMetrics(object): +class ProcessingMetrics(): """ If processing metrics are requested, information about the service's processing of the input audio. Processing metrics are not available with the synchronous **Recognize @@ -5602,15 +5635,15 @@ def __init__(self, processed_audio, wall_clock_since_first_byte_received, def _from_dict(cls, _dict): """Initialize a ProcessingMetrics object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'processed_audio', 'wall_clock_since_first_byte_received', 'periodic' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ProcessingMetrics: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'processed_audio' in _dict: args['processed_audio'] = ProcessedAudio._from_dict( _dict.get('processed_audio')) @@ -5662,7 +5695,7 @@ def __ne__(self, other): return not self == other -class RecognitionJob(object): +class RecognitionJob(): """ Information about a current asynchronous speech recognition job. @@ -5766,15 +5799,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a RecognitionJob object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'id', 'status', 'created', 'updated', 'url', 'user_token', 'results', 'warnings' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RecognitionJob: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'id' in _dict: args['id'] = _dict.get('id') else: @@ -5862,7 +5895,7 @@ class StatusEnum(Enum): FAILED = "failed" -class RecognitionJobs(object): +class RecognitionJobs(): """ Information about current asynchronous speech recognition jobs. @@ -5885,12 +5918,12 @@ def __init__(self, recognitions): def _from_dict(cls, _dict): """Initialize a RecognitionJobs object from a json dictionary.""" args = {} - validKeys = ['recognitions'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['recognitions'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RecognitionJobs: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'recognitions' in _dict: args['recognitions'] = [ RecognitionJob._from_dict(x) @@ -5924,7 +5957,7 @@ def __ne__(self, other): return not self == other -class RegisterStatus(object): +class RegisterStatus(): """ Information about a request to register a callback for asynchronous speech recognition. @@ -5953,12 +5986,12 @@ def __init__(self, status, url): def _from_dict(cls, _dict): """Initialize a RegisterStatus object from a json dictionary.""" args = {} - validKeys = ['status', 'url'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['status', 'url'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class RegisterStatus: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') else: @@ -6006,7 +6039,7 @@ class StatusEnum(Enum): ALREADY_CREATED = "already created" -class SpeakerLabelsResult(object): +class SpeakerLabelsResult(): """ Information about the speakers from speech recognition results. @@ -6058,12 +6091,12 @@ def __init__(self, from_, to, speaker, confidence, final): def _from_dict(cls, _dict): """Initialize a SpeakerLabelsResult object from a json dictionary.""" args = {} - validKeys = ['from_', 'from', 'to', 'speaker', 'confidence', 'final'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['from_', 'from', 'to', 'speaker', 'confidence', 'final'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SpeakerLabelsResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'from' in _dict: args['from_'] = _dict.get('from') else: @@ -6126,7 +6159,7 @@ def __ne__(self, other): return not self == other -class SpeechModel(object): +class SpeechModel(): """ Information about an available language model. @@ -6168,15 +6201,15 @@ def __init__(self, name, language, rate, url, supported_features, def _from_dict(cls, _dict): """Initialize a SpeechModel object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'name', 'language', 'rate', 'url', 'supported_features', 'description' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SpeechModel: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -6247,7 +6280,7 @@ def __ne__(self, other): return not self == other -class SpeechModels(object): +class SpeechModels(): """ Information about the available language models. @@ -6268,12 +6301,12 @@ def __init__(self, models): def _from_dict(cls, _dict): """Initialize a SpeechModels object from a json dictionary.""" args = {} - validKeys = ['models'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['models'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SpeechModels: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'models' in _dict: args['models'] = [ SpeechModel._from_dict(x) for x in (_dict.get('models')) @@ -6305,7 +6338,7 @@ def __ne__(self, other): return not self == other -class SpeechRecognitionAlternative(object): +class SpeechRecognitionAlternative(): """ An alternative transcript from speech recognition results. @@ -6359,14 +6392,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SpeechRecognitionAlternative object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'transcript', 'confidence', 'timestamps', 'word_confidence' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SpeechRecognitionAlternative: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'transcript' in _dict: args['transcript'] = _dict.get('transcript') else: @@ -6410,7 +6443,7 @@ def __ne__(self, other): return not self == other -class SpeechRecognitionResult(object): +class SpeechRecognitionResult(): """ Component results for a speech recognition request. @@ -6468,14 +6501,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SpeechRecognitionResult object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'final', 'alternatives', 'keywords_result', 'word_alternatives' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SpeechRecognitionResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'final' in _dict: args['final'] = _dict.get('final') else: @@ -6532,7 +6565,7 @@ def __ne__(self, other): return not self == other -class SpeechRecognitionResults(object): +class SpeechRecognitionResults(): """ The complete results for a speech recognition request. @@ -6635,15 +6668,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SpeechRecognitionResults object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'results', 'result_index', 'speaker_labels', 'processing_metrics', 'audio_metrics', 'warnings' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SpeechRecognitionResults: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'results' in _dict: args['results'] = [ SpeechRecognitionResult._from_dict(x) @@ -6702,7 +6735,7 @@ def __ne__(self, other): return not self == other -class SupportedFeatures(object): +class SupportedFeatures(): """ Additional service features that are supported with the model. @@ -6729,12 +6762,12 @@ def __init__(self, custom_language_model, speaker_labels): def _from_dict(cls, _dict): """Initialize a SupportedFeatures object from a json dictionary.""" args = {} - validKeys = ['custom_language_model', 'speaker_labels'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['custom_language_model', 'speaker_labels'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SupportedFeatures: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'custom_language_model' in _dict: args['custom_language_model'] = _dict.get('custom_language_model') else: @@ -6774,7 +6807,7 @@ def __ne__(self, other): return not self == other -class TrainingResponse(object): +class TrainingResponse(): """ The response from training of a custom language or custom acoustic model. @@ -6801,12 +6834,12 @@ def __init__(self, *, warnings=None): def _from_dict(cls, _dict): """Initialize a TrainingResponse object from a json dictionary.""" args = {} - validKeys = ['warnings'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['warnings'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TrainingResponse: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'warnings' in _dict: args['warnings'] = [ TrainingWarning._from_dict(x) for x in (_dict.get('warnings')) @@ -6835,7 +6868,7 @@ def __ne__(self, other): return not self == other -class TrainingWarning(object): +class TrainingWarning(): """ A warning from training of a custom language or custom acoustic model. @@ -6867,12 +6900,12 @@ def __init__(self, code, message): def _from_dict(cls, _dict): """Initialize a TrainingWarning object from a json dictionary.""" args = {} - validKeys = ['code', 'message'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['code', 'message'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class TrainingWarning: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'code' in _dict: args['code'] = _dict.get('code') else: @@ -6920,7 +6953,7 @@ class CodeEnum(Enum): INVALID_WORDS = "invalid_words" -class Word(object): +class Word(): """ Information about a word from a custom language model. @@ -6997,14 +7030,14 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Word object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'word', 'sounds_like', 'display_as', 'count', 'source', 'error' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Word: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'word' in _dict: args['word'] = _dict.get('word') else: @@ -7068,7 +7101,7 @@ def __ne__(self, other): return not self == other -class WordAlternativeResult(object): +class WordAlternativeResult(): """ An alternative hypothesis for a word from speech recognition results. @@ -7092,12 +7125,12 @@ def __init__(self, confidence, word): def _from_dict(cls, _dict): """Initialize a WordAlternativeResult object from a json dictionary.""" args = {} - validKeys = ['confidence', 'word'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['confidence', 'word'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class WordAlternativeResult: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') else: @@ -7136,7 +7169,7 @@ def __ne__(self, other): return not self == other -class WordAlternativeResults(object): +class WordAlternativeResults(): """ Information about alternative hypotheses for words from speech recognition results. @@ -7167,12 +7200,12 @@ def __init__(self, start_time, end_time, alternatives): def _from_dict(cls, _dict): """Initialize a WordAlternativeResults object from a json dictionary.""" args = {} - validKeys = ['start_time', 'end_time', 'alternatives'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['start_time', 'end_time', 'alternatives'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class WordAlternativeResults: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'start_time' in _dict: args['start_time'] = _dict.get('start_time') else: @@ -7222,7 +7255,7 @@ def __ne__(self, other): return not self == other -class WordError(object): +class WordError(): """ An error associated with a word from a custom language model. @@ -7253,12 +7286,12 @@ def __init__(self, element): def _from_dict(cls, _dict): """Initialize a WordError object from a json dictionary.""" args = {} - validKeys = ['element'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['element'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class WordError: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'element' in _dict: args['element'] = _dict.get('element') else: @@ -7288,7 +7321,7 @@ def __ne__(self, other): return not self == other -class Words(object): +class Words(): """ Information about the words from a custom language model. @@ -7311,12 +7344,12 @@ def __init__(self, words): def _from_dict(cls, _dict): """Initialize a Words object from a json dictionary.""" args = {} - validKeys = ['words'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['words'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Words: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'words' in _dict: args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] else: diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 166b67f93..c8503868c 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -215,7 +215,7 @@ def recognize_using_websocket(self, if self.authenticator: self.authenticator.authenticate(request) - url = self.url.replace('https:', 'wss:') + url = self.service_url.replace('https:', 'wss:') params = { 'model': model, diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index 31485f482..16f71e68b 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -85,7 +85,7 @@ def synthesize_using_websocket(self, if self.authenticator: self.authenticator.authenticate(request) - url = self.url.replace('https:', 'wss:') + url = self.service_url.replace('https:', 'wss:') params = { 'voice': voice, 'customization_id': customization_id, diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 40a0b5b10..50fc538cf 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -35,6 +35,7 @@ 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 read_external_sources ############################################################################## # Service @@ -44,36 +45,36 @@ class TextToSpeechV1(BaseService): """The Text to Speech V1 service.""" - default_url = 'https://stream.watsonplatform.net/text-to-speech/api' + default_service_url = 'https://stream.watsonplatform.net/text-to-speech/api' def __init__( self, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Text to Speech service. - :param str url: The base url to use when contacting the service (e.g. - "https://stream.watsonplatform.net/text-to-speech/api/text-to-speech/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('text_to_speech') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: - authenticator = get_authenticator_from_environment('Text to Speech') + authenticator = get_authenticator_from_environment('text_to_speech') - BaseService.__init__( - self, - url=url, - authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Text to Speech') + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) ######################### # Voices @@ -101,8 +102,10 @@ def list_voices(self, **kwargs): headers.update(sdk_headers) url = '/v1/voices' - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -141,12 +144,11 @@ def get_voice(self, voice, *, customization_id=None, **kwargs): params = {'customization_id': customization_id} url = '/v1/voices/{0}'.format(*self._encode_path_vars(voice)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -262,13 +264,12 @@ def synthesize(self, data = {'text': text} url = '/v1/synthesize' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=False) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=False) response = self.send(request) return response @@ -332,12 +333,11 @@ def get_pronunciation(self, } url = '/v1/pronunciation' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -385,12 +385,11 @@ def create_voice_model(self, data = {'name': name, 'language': language, 'description': description} url = '/v1/customizations' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + data=data, + accept_json=True) response = self.send(request) return response @@ -426,12 +425,11 @@ def list_voice_models(self, *, language=None, **kwargs): params = {'language': language} url = '/v1/customizations' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) response = self.send(request) return response @@ -501,12 +499,11 @@ def update_voice_model(self, url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + data=data, + accept_json=True) response = self.send(request) return response @@ -541,8 +538,10 @@ def get_voice_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -576,8 +575,10 @@ def delete_voice_model(self, customization_id, **kwargs): url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='DELETE', url=url, headers=headers, accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + accept_json=False) response = self.send(request) return response @@ -645,12 +646,11 @@ def add_words(self, customization_id, words, **kwargs): url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - data=data, - accept_json=True) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + data=data, + accept_json=True) response = self.send(request) return response @@ -685,8 +685,10 @@ def list_words(self, customization_id, **kwargs): url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -763,12 +765,11 @@ def add_word(self, url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - data=data, - accept_json=False) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + data=data, + accept_json=False) response = self.send(request) return response @@ -806,8 +807,10 @@ def get_word(self, customization_id, word, **kwargs): url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) - request = self.prepare_request( - method='GET', url=url, headers=headers, accept_json=True) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + accept_json=True) response = self.send(request) return response @@ -844,8 +847,10 @@ def delete_word(self, customization_id, word, **kwargs): url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) - request = self.prepare_request( - method='DELETE', url=url, headers=headers, accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + accept_json=False) response = self.send(request) return response @@ -887,12 +892,11 @@ def delete_user_data(self, customer_id, **kwargs): params = {'customer_id': customer_id} url = '/v1/user_data' - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - accept_json=False) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=False) response = self.send(request) return response @@ -1061,7 +1065,7 @@ class Language(Enum): ############################################################################## -class Pronunciation(object): +class Pronunciation(): """ The pronunciation of the specified text. @@ -1084,12 +1088,12 @@ def __init__(self, pronunciation): def _from_dict(cls, _dict): """Initialize a Pronunciation object from a json dictionary.""" args = {} - validKeys = ['pronunciation'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['pronunciation'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Pronunciation: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'pronunciation' in _dict: args['pronunciation'] = _dict.get('pronunciation') else: @@ -1120,7 +1124,7 @@ def __ne__(self, other): return not self == other -class SupportedFeatures(object): +class SupportedFeatures(): """ Additional service features that are supported with the voice. @@ -1148,12 +1152,12 @@ def __init__(self, custom_pronunciation, voice_transformation): def _from_dict(cls, _dict): """Initialize a SupportedFeatures object from a json dictionary.""" args = {} - validKeys = ['custom_pronunciation', 'voice_transformation'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['custom_pronunciation', 'voice_transformation'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SupportedFeatures: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'custom_pronunciation' in _dict: args['custom_pronunciation'] = _dict.get('custom_pronunciation') else: @@ -1194,7 +1198,7 @@ def __ne__(self, other): return not self == other -class Translation(object): +class Translation(): """ Information about the translation for the specified text. @@ -1234,12 +1238,12 @@ def __init__(self, translation, *, part_of_speech=None): def _from_dict(cls, _dict): """Initialize a Translation object from a json dictionary.""" args = {} - validKeys = ['translation', 'part_of_speech'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['translation', 'part_of_speech'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Translation: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'translation' in _dict: args['translation'] = _dict.get('translation') else: @@ -1301,7 +1305,7 @@ class PartOfSpeechEnum(Enum): SUJI = "Suji" -class Voice(object): +class Voice(): """ Information about an available voice model. @@ -1364,15 +1368,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a Voice object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'url', 'gender', 'name', 'language', 'description', 'customizable', 'supported_features', 'customization' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Voice: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'url' in _dict: args['url'] = _dict.get('url') else: @@ -1453,7 +1457,7 @@ def __ne__(self, other): return not self == other -class VoiceModel(object): +class VoiceModel(): """ Information about an existing custom voice model. @@ -1533,15 +1537,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a VoiceModel object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'customization_id', 'name', 'language', 'owner', 'created', 'last_modified', 'description', 'words' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class VoiceModel: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'customization_id' in _dict: args['customization_id'] = _dict.get('customization_id') else: @@ -1601,7 +1605,7 @@ def __ne__(self, other): return not self == other -class VoiceModels(object): +class VoiceModels(): """ Information about existing custom voice models. @@ -1627,12 +1631,12 @@ def __init__(self, customizations): def _from_dict(cls, _dict): """Initialize a VoiceModels object from a json dictionary.""" args = {} - validKeys = ['customizations'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['customizations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class VoiceModels: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'customizations' in _dict: args['customizations'] = [ VoiceModel._from_dict(x) for x in (_dict.get('customizations')) @@ -1667,7 +1671,7 @@ def __ne__(self, other): return not self == other -class Voices(object): +class Voices(): """ Information about all available voice models. @@ -1686,12 +1690,12 @@ def __init__(self, voices): def _from_dict(cls, _dict): """Initialize a Voices object from a json dictionary.""" args = {} - validKeys = ['voices'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['voices'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Voices: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'voices' in _dict: args['voices'] = [ Voice._from_dict(x) for x in (_dict.get('voices')) @@ -1723,7 +1727,7 @@ def __ne__(self, other): return not self == other -class Word(object): +class Word(): """ Information about a word for the custom voice model. @@ -1767,12 +1771,12 @@ def __init__(self, word, translation, *, part_of_speech=None): def _from_dict(cls, _dict): """Initialize a Word object from a json dictionary.""" args = {} - validKeys = ['word', 'translation', 'part_of_speech'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['word', 'translation', 'part_of_speech'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Word: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'word' in _dict: args['word'] = _dict.get('word') else: @@ -1840,7 +1844,7 @@ class PartOfSpeechEnum(Enum): SUJI = "Suji" -class Words(object): +class Words(): """ For the **Add custom words** method, one or more words that are to be added or updated for the custom voice model and the translation for each specified word. @@ -1875,12 +1879,12 @@ def __init__(self, words): def _from_dict(cls, _dict): """Initialize a Words object from a json dictionary.""" args = {} - validKeys = ['words'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['words'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Words: ' + - ', '.join(badKeys)) + ', '.join(bad_keys)) if 'words' in _dict: args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] else: diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 5e6a7b4de..c36c9523e 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -30,6 +30,7 @@ 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 read_external_sources ############################################################################## # Service @@ -39,14 +40,12 @@ class ToneAnalyzerV3(BaseService): """The Tone Analyzer V3 service.""" - default_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' + default_service_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' def __init__( self, version, - url=default_url, authenticator=None, - disable_ssl_verification=False, ): """ Construct a new client for the Tone Analyzer service. @@ -62,24 +61,27 @@ def __init__( application, and don't change it until your application is ready for a later version. - :param str url: The base url to use when contacting the service (e.g. - "https://gateway.watsonplatform.net/tone-analyzer/api/tone-analyzer/api"). - The base url may differ between IBM Cloud regions. - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - :param bool disable_ssl_verification: If True, disables ssl verification """ + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('tone_analyzer') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + if not authenticator: - authenticator = get_authenticator_from_environment('Tone Analyzer') + authenticator = get_authenticator_from_environment('tone_analyzer') BaseService.__init__(self, - url=url, + service_url=service_url, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification, - display_name='Tone Analyzer') + disable_ssl_verification=disable_ssl_verification) self.version = version ######################### @@ -353,7 +355,7 @@ class AcceptLanguage(Enum): ############################################################################## -class DocumentAnalysis(object): +class DocumentAnalysis(): """ The results of the analysis for the full input content. @@ -401,12 +403,12 @@ def __init__(self, *, tones=None, tone_categories=None, warning=None): def _from_dict(cls, _dict): """Initialize a DocumentAnalysis object from a json dictionary.""" args = {} - validKeys = ['tones', 'tone_categories', 'warning'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['tones', 'tone_categories', 'warning'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class DocumentAnalysis: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'tones' in _dict: args['tones'] = [ ToneScore._from_dict(x) for x in (_dict.get('tones')) @@ -449,7 +451,7 @@ def __ne__(self, other): return not self == other -class SentenceAnalysis(object): +class SentenceAnalysis(): """ The results of the analysis for the individual sentences of the input content. @@ -516,15 +518,15 @@ def __init__(self, def _from_dict(cls, _dict): """Initialize a SentenceAnalysis object from a json dictionary.""" args = {} - validKeys = [ + valid_keys = [ 'sentence_id', 'text', 'tones', 'tone_categories', 'input_from', 'input_to' ] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class SentenceAnalysis: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'sentence_id' in _dict: args['sentence_id'] = _dict.get('sentence_id') else: @@ -587,7 +589,7 @@ def __ne__(self, other): return not self == other -class ToneAnalysis(object): +class ToneAnalysis(): """ The tone analysis results for the input from the general-purpose endpoint. @@ -619,12 +621,12 @@ def __init__(self, document_tone, *, sentences_tone=None): def _from_dict(cls, _dict): """Initialize a ToneAnalysis object from a json dictionary.""" args = {} - validKeys = ['document_tone', 'sentences_tone'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['document_tone', 'sentences_tone'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ToneAnalysis: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'document_tone' in _dict: args['document_tone'] = DocumentAnalysis._from_dict( _dict.get('document_tone')) @@ -665,7 +667,7 @@ def __ne__(self, other): return not self == other -class ToneCategory(object): +class ToneCategory(): """ The category for a tone from the input content. @@ -696,12 +698,12 @@ def __init__(self, tones, category_id, category_name): def _from_dict(cls, _dict): """Initialize a ToneCategory object from a json dictionary.""" args = {} - validKeys = ['tones', 'category_id', 'category_name'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['tones', 'category_id', 'category_name'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ToneCategory: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'tones' in _dict: args['tones'] = [ ToneScore._from_dict(x) for x in (_dict.get('tones')) @@ -749,7 +751,7 @@ def __ne__(self, other): return not self == other -class ToneChatScore(object): +class ToneChatScore(): """ The score for an utterance from the input content. @@ -782,12 +784,12 @@ def __init__(self, score, tone_id, tone_name): def _from_dict(cls, _dict): """Initialize a ToneChatScore object from a json dictionary.""" args = {} - validKeys = ['score', 'tone_id', 'tone_name'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['score', 'tone_id', 'tone_name'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ToneChatScore: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'score' in _dict: args['score'] = _dict.get('score') else: @@ -846,7 +848,7 @@ class ToneIdEnum(Enum): SYMPATHETIC = "sympathetic" -class ToneInput(object): +class ToneInput(): """ Input for the general-purpose endpoint. @@ -865,12 +867,12 @@ def __init__(self, text): def _from_dict(cls, _dict): """Initialize a ToneInput object from a json dictionary.""" args = {} - validKeys = ['text'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ToneInput: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -900,7 +902,7 @@ def __ne__(self, other): return not self == other -class ToneScore(object): +class ToneScore(): """ The score for a tone from the input content. @@ -961,12 +963,12 @@ def __init__(self, score, tone_id, tone_name): def _from_dict(cls, _dict): """Initialize a ToneScore object from a json dictionary.""" args = {} - validKeys = ['score', 'tone_id', 'tone_name'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['score', 'tone_id', 'tone_name'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class ToneScore: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'score' in _dict: args['score'] = _dict.get('score') else: @@ -1010,7 +1012,7 @@ def __ne__(self, other): return not self == other -class Utterance(object): +class Utterance(): """ An utterance for the input of the general-purpose endpoint. @@ -1036,12 +1038,12 @@ def __init__(self, text, *, user=None): def _from_dict(cls, _dict): """Initialize a Utterance object from a json dictionary.""" args = {} - validKeys = ['text', 'user'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['text', 'user'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class Utterance: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -1075,7 +1077,7 @@ def __ne__(self, other): return not self == other -class UtteranceAnalyses(object): +class UtteranceAnalyses(): """ The results of the analysis for the utterances of the input content. @@ -1104,12 +1106,12 @@ def __init__(self, utterances_tone, *, warning=None): def _from_dict(cls, _dict): """Initialize a UtteranceAnalyses object from a json dictionary.""" args = {} - validKeys = ['utterances_tone', 'warning'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['utterances_tone', 'warning'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class UtteranceAnalyses: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'utterances_tone' in _dict: args['utterances_tone'] = [ UtteranceAnalysis._from_dict(x) @@ -1150,7 +1152,7 @@ def __ne__(self, other): return not self == other -class UtteranceAnalysis(object): +class UtteranceAnalysis(): """ The results of the analysis for an utterance of the input content. @@ -1192,12 +1194,12 @@ def __init__(self, utterance_id, utterance_text, tones, *, error=None): def _from_dict(cls, _dict): """Initialize a UtteranceAnalysis object from a json dictionary.""" args = {} - validKeys = ['utterance_id', 'utterance_text', 'tones', 'error'] - badKeys = set(_dict.keys()) - set(validKeys) - if badKeys: + valid_keys = ['utterance_id', 'utterance_text', 'tones', 'error'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class UtteranceAnalysis: ' - + ', '.join(badKeys)) + + ', '.join(bad_keys)) if 'utterance_id' in _dict: args['utterance_id'] = _dict.get('utterance_id') else: diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index ff8d0349e..476f32ba9 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -153,26 +153,27 @@ def classify(self, params = {'version': self.version} - form_data = {} + form_data = [] if images_file: if not images_filename and hasattr(images_file, 'name'): images_filename = basename(images_file.name) if not images_filename: raise ValueError('images_filename must be provided') - form_data['images_file'] = (images_filename, images_file, - images_file_content_type or - 'application/octet-stream') + form_data.append(('images_file', (images_filename, images_file, + images_file_content_type or + 'application/octet-stream'))) if url: - form_data['url'] = (None, url, 'text/plain') + form_data.append(('url', (None, url, 'text/plain'))) if threshold: - form_data['threshold'] = (None, threshold, 'application/json') + form_data.append( + ('threshold', (None, threshold, 'application/json'))) if owners: owners = self._convert_list(owners) - form_data['owners'] = (None, owners, 'application/json') + form_data.append(('owners', (None, owners, 'application/json'))) if classifier_ids: classifier_ids = self._convert_list(classifier_ids) - form_data['classifier_ids'] = (None, classifier_ids, - 'application/json') + form_data.append( + ('classifier_ids', (None, classifier_ids, 'application/json'))) url = '/v3/classify' request = self.prepare_request(method='POST', @@ -249,23 +250,24 @@ def create_classifier(self, params = {'version': self.version} - form_data = {} - form_data['name'] = (None, name, 'text/plain') + form_data = [] + form_data.append(('name', (None, name, 'text/plain'))) for key in positive_examples.keys(): part_name = '%s_positive_examples' % (key) value = positive_examples[key] if hasattr(value, 'name'): filename = basename(value.name) - form_data[part_name] = (filename, value, 'application/octet-stream') + form_data.append( + (part_name, (filename, value, 'application/octet-stream'))) if negative_examples: if not negative_examples_filename and hasattr( negative_examples, 'name'): negative_examples_filename = basename(negative_examples.name) if not negative_examples_filename: raise ValueError('negative_examples_filename must be provided') - form_data['negative_examples'] = (negative_examples_filename, - negative_examples, - 'application/octet-stream') + form_data.append(('negative_examples', + (negative_examples_filename, negative_examples, + 'application/octet-stream'))) url = '/v3/classifiers' request = self.prepare_request(method='POST', @@ -403,22 +405,23 @@ def update_classifier(self, params = {'version': self.version} - form_data = {} + form_data = [] for key in positive_examples.keys(): part_name = '%s_positive_examples' % (key) value = positive_examples[key] if hasattr(value, 'name'): filename = basename(value.name) - form_data[part_name] = (filename, value, 'application/octet-stream') + form_data.append( + (part_name, (filename, value, 'application/octet-stream'))) if negative_examples: if not negative_examples_filename and hasattr( negative_examples, 'name'): negative_examples_filename = basename(negative_examples.name) if not negative_examples_filename: raise ValueError('negative_examples_filename must be provided') - form_data['negative_examples'] = (negative_examples_filename, - negative_examples, - 'application/octet-stream') + form_data.append(('negative_examples', + (negative_examples_filename, negative_examples, + 'application/octet-stream'))) url = '/v3/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 18ea1507b..d59b06eef 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -29,7 +29,6 @@ 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 import read_external_sources -from os.path import basename ############################################################################## # Service From a425f8ba1f51f875f5f33d87098a37702a617279 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 1 Oct 2019 10:37:48 -0700 Subject: [PATCH 088/455] chore(example): remove unused import --- examples/visual_recognition_v4.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/visual_recognition_v4.py b/examples/visual_recognition_v4.py index 116e7b932..c244fe1ab 100644 --- a/examples/visual_recognition_v4.py +++ b/examples/visual_recognition_v4.py @@ -1,7 +1,7 @@ import json import os from ibm_watson import VisualRecognitionV4 -from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata, BaseObject, Location +from ibm_watson.visual_recognition_v4 import FileWithMetadata, BaseObject, Location from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('') @@ -38,4 +38,4 @@ train_result = service.train(collection_id).get_result() # delete collection -service.delete_collection(collection_id) \ No newline at end of file +service.delete_collection(collection_id) From abefd714a81c5a8110106e00993304cc5742b7eb Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 1 Oct 2019 10:38:18 -0700 Subject: [PATCH 089/455] doc(readme): Update readme with setting url --- README.md | 39 ++++++++++++++++++--------------------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 9c7f54f20..e764ce6c6 100755 --- a/README.md +++ b/README.md @@ -173,8 +173,8 @@ import from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('apikey', url='') # optional - the default value is https://iam.cloud.ibm.com/identity/token discovery = DiscoveryV1(version='2018-08-01', - url='', authenticator=authenticator) +discovery.set_service_url('') ``` #### Generating access tokens using API key @@ -194,8 +194,8 @@ from ibm_cloud_sdk_core.authenticators import BearerAuthenticator # in the constructor, assuming control of managing the token authenticator = BearerAuthenticator('your bearer token') discovery = DiscoveryV1(version='2018-08-01', - url='', authenticator=authenticator) +discovery.set_service_url('') ``` ### Username and password @@ -204,7 +204,8 @@ from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators import BasicAuthenticator authenticator = BasicAuthenticator('username', 'password') -discovery = DiscoveryV1(version='2018-08-01', url='', authenticator=authenticator) +discovery = DiscoveryV1(version='2018-08-01', authenticator=authenticator) +discovery.set_service_url('') ``` ### No Authentication @@ -213,7 +214,8 @@ from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator authenticator = NoAuthAuthenticator() -discovery = DiscoveryV1(version='2018-08-01', url='', authenticator=authenticator) +discovery = DiscoveryV1(version='2018-08-01', authenticator=authenticator) +discovery.set_service_url('') ``` ## Python version @@ -256,9 +258,8 @@ from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') assistant = AssistantV1( version='2018-07-10', - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/assistant/api', authenticator=authenticator) +assistant.set_service_url('') ``` ## Migration @@ -274,9 +275,8 @@ from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') assistant = AssistantV1( version='2018-07-10', - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/assistant/api', authenticator=authenticator) +assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') assistant.set_http_config({'timeout': 100}) response = assistant.message(workspace_id=workspace_id, input={ @@ -301,7 +301,7 @@ service.set_service_url('my_new_service_url') Or can set it in the environment variable. ``` -export _url="" +export _URL="" ``` ## Sending request headers @@ -320,9 +320,8 @@ from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') assistant = AssistantV1( version='2018-07-10', - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/assistant/api', authenticator=authenticator) +assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() ``` @@ -336,9 +335,8 @@ from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') assistant = AssistantV1( version='2018-07-10', - ## url is optional, and defaults to the URL below. Use the correct URL for your region. - url='https://gateway.watsonplatform.net/assistant/api', authenticator=authenticator) +assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') assistant.set_detailed_response(True) response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() @@ -395,10 +393,9 @@ authenticator = CloudPakForDataAuthenticator( assistant = AssistantV1( version='', - url='', # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api - authenticator=authenticator, - disable_ssl_verification=True # MAKE SURE SSL VERIFICATION IS DISABLED - ) + authenticator=authenticator) +assistant.set_service_url('') # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api +assistant.set_disable_ssl_verification(True) # MAKE SURE SSL VERIFICATION IS DISABLED ``` ### 2) Supplying the access token @@ -408,9 +405,9 @@ from ibm_cloud_sdk_core.authenticators import BearerAuthenticator authenticator = BearerAuthenticator('your managed access token') assistant = AssistantV1(version='', - url='service url', # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api - authenticator=authenticator, - disable_ssl_verification=True) # MAKE SURE SSL VERIFICATION IS DISABLED + authenticator=authenticator) +assistant.set_service_url('') # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api +assistant.set_disable_ssl_verification(True) # MAKE SURE SSL VERIFICATION IS DISABLED ``` ## Logging @@ -449,7 +446,7 @@ HTTPConnection.debuglevel = 1 * [responses] for testing * Following for web sockets support in speech to text * `websocket-client` 0.48.0 -* `ibm_cloud_sdk_core` >= 1.0.0rc5 +* `ibm_cloud_sdk_core` >= 1.0.0rc9 ## Contributing From 4fef32cf23382f9da9d90831e85bd6c4b70aec9f Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 1 Oct 2019 12:04:37 -0700 Subject: [PATCH 090/455] chore(env): update env file --- .env.enc | Bin 2736 -> 2736 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/.env.enc b/.env.enc index 9611625769cd74d646ce711f952807cb53a003a1..78b26c9d65f2369cef9bf281440e83732dc1a2d7 100644 GIT binary patch literal 2736 zcmV;h3QzUS-GLZw@Th>3K}N28mP#-@o$L+M>NnMRZSHGyq z?`zF1p^PKgt=$Q;a9pAcscY?DsJ;+~YL$ufO$h4Rek2mcRzp|Gp((`oz+d#oRa%-O z`Jvy=2Cpt9^-B`l(>rvJ6?lEG2I74sFL*m<&b48YoTD9SM zFOd83b&hV&PEXGr_VwM1bNV=8nI2d>99ry@PI$nWXVUww6sZfS#Pmhy?sbjxP7R)& zGFCM#C*3g~toI5(Qcs%pEpB+s%mWSM&pGftf^mHzDggvT6-Q_veKXYYTX)`&%;;aa zm&^bDlL7MsmB?crZ-2M(2ooZe+bA+Ey5b#UMc(=yK0mBUnBYgbeKJvrg$WdH7l!bi zicS^jfAXj&LdM%nIJJr)R2dn;RhX5k3>I_j^r$;_PA3&@G!9c5;*}`MuABCE0vVLY z4tE)9n6RgV$b~VlNm3{A-W@+mx>a&+Xd7HD89X<6SBWFup>qF`uHYi-W|4pf{7V<< z7j-_UOaq)5yu{t=O&@|sv=#F97xseO4B`A#Idn1}wZI#o8gsVR>S;M6C64W3wKFwN za-gKCVQ$qNk6&J_P#H4j?ke8!KdZ>xrgU{hV0lJkk?fgdN_T-M$xsbf?=1u14{j+P z$#niPit3Q21Y}-5dkK7NSbXHoKqn(W%}I?9cMc1*1{%tHtdPT5zCaqgwE2R5r}DL!gDg4CYywzZAwD zL5HFmoX&Y_#Sw$Os~vtBjHgT`Nl6Zrp}z2k)mRCT8W6wtkWak(E*a`T$Qm0EiF-I_ zK?JLkJOSnt(>Ax~nOSq;{e>;W&M5?=8Y>fi*~($ve$ti-M1rVIqmYRCT#qf*S z1%KcMXRbTW4+DMJaqb6Uc{RAZU%&)&52cC5{X4h(qz)g%)DXTI%vX7FB$1dK6S{K* zpG=})eKTsQ5dGS6A?{d?$4bOw)z=kG^4Jds5Hc4j=Q!xPfIJs{yX6tm3RVG??)ocB zKAC8)G)WyID)id^#7v#miK!;9u0~{Tq3S#BGvN?EoQf#U?EFi!b{2M=Sq zO?+OqYb@Y{QK$+VqAL3eAGq@O0N zh9ru@bV5~Z>t=Epjy_lp3D6UKsJN0=w`4;be-AnH5xQhsk?5P$F&?inz{SroK7ThG z=3>MbcWqeiwe3%!hS2I;ivE78)%avMN6zcHO3yH4K`#jes>H|4L_DXEhPUDn+N|$g zy4QMSbfzQf*;IuTPA;vKL5IIyWq;e!idCU!AJcY{nf&G{hD}!6=sS%Q7u0^wZ8JFFpM!-q3Gx<2rsoY< zWQmZUjECNOCbqLzfSWPmHS>R%t-iP_yUWKAKS{-G?5NYq|YT^2fLtqTvNk@gemQDHg6|R;nMSMWTgFKL?(VmBO7U zDl8PKM&mtt*7`FkIxysCuG_LY<|R_}--{gKz!~vLlG|2ewrIo3xsl|Y_B4wNwkUBHU7W+6M1ZHW}J{=zuEBWZ8SenN~nzHAKJ{=gfK z{D3zNhM4ktO%a5CwZ=)#vTsq)?l;p*!sK@uyM{LANFnMpcoyFd}A)h zpKQfmups5*NXx=F4H5Y-uv(+RR+{{Lg74yC>{*l1+T)_ze0r#)+)JkFi(hO_;Flet zW&~;(yaypFXoVb-DUfeAH`LmpUVs0inyD&53D!TuGSS!gv*ce55;@Hv=Do<`y5L8! zm>m#L^(QPa#6jWi&JMz{*nz)AUa2VYl_zRwd~GlWNR5o_01gV?;e)G0{FoS?lq)ND zeC>-ZbK4~`A3SkFC_Zi`;iP+49kxxv)bR*%c$COdr+7pYlVae`D-#t#(3S^tsE<`J zg8|IRB0w9w-{LB~#%7in1Iu9RD*<*+Kkn+|<`PX=)MQ(SCyrR(MapM4&dtxFShxrw z31eok3a5EnP`-6np!&#fMW6W=rAdV~k-%kc53Xd^`n;u!eqjfEajhFQn+E!YKR zzvgwqerP%b@}Wi{2Qng9?YQ(j3-$qaHDhl%x9m1tm|>a|>AL(d`DASm=c|f86y+7y z8!&VbO(EXG^^l-E-q(I8soUfi3aK?|_-|91!w|tKIA=l%^CJ`69q-;@F8vDrcyUj& ztXSI&^c1tGQZ{$*3Q~<9#Qp1#9km#naY^n_tqG08 literal 2736 zcmV;h3QzSo-W(gK^u@L65L6-;^Hk#{ZU%t(zAoP>LwrLU^=6r2dX=g836j3J3J~tG zB$)^75(;ji_5QI&xx#TF^w^>Y8^7fAVi!7N01pz(wrq4>&U@!s5Je@lV~ov>qDR@t z!brqXn?J+7|GboE4rCTcFNhBmRADBpx@P$~xCqml>wge+pC)m1nhp!@N4SQh6f@r< zv01Qb^M3%WfHLp+rJLusL_29b7%L{YkFOO~F0Dn=d!(;@qJb8#CUua4m3nX~JuPKP zB9b$CLbSzB7{E9D^oe#?yrjxYMWjA!_mcYJ21hj6p#*EQNg+R%fx(O)l6Cx1j^`AX zT!jktS~4)CJ~>2E(2}wqye4hlOu{|5Ax@NvOt)l!(DX$Y^20ppk&_PDMyv5(#Omya z@${7$tc?CP(hiU!QWk@j5EaQz@=`;ZnEN5?p2`N&O`W8|((g(+vG?f^OT#R24NCyEb~8aU2CAk1*42eGgA1QX00h=4eu zSZ$}{0m{aiqU>pjRV@3t8op1!Q{uuTLyq}9z73ZN2F2G(?9VKKy-#5|5rM^C1>S%j zGAv%ddAHXw8CrqhH^7tWU@mH~Kp&j7wQ^th7I6+FkCj?h%$67+lYCe;a|_=R1w0?6 zo93@2Tu%FG^@1COnAdTLctu?JIt*r;;$fj{9Zyu-h8dfg&=VjhnNA<2n9)s@Vt9UP=~kw zaEz)T`aVLN{+o%S;{>_QsMrRAI>#PaSZwE+wZn@im&O!5KZ~s~nATaV^H%N^n*u6m zbyZA5U)~fIOBBY1Cm7G21c7E7zEw_hy)oUXF5}MA;PHqM;6=m!oGMy&%Vi0y@pJt)0YWKn=71k=3on`-C2S#x65LGh$uPyM-qOQmT(2dL#}rZa0@ z7ERI*x(>|1)GMB?)#R(=^Wjk7bBp`X0!4f|~NX&+@wZhq-l zknj7AjmJ#MRf`c~tlfO#N?_oP%kO2jQ2kw>%%}WBeAAjCe(0aNn`IGX{iojMrw_onv#h{gZ26#ufvhxl-N_;8LQu1!4NTE6ITFiv+X3> zNwD4C4W1p*o)u`zj!1<<`?j4fABR-n#nuz5RM`lQIhT4N#JJH{Og3?0fLH&}(1>>Q zJW4F=-hs34tL*QjmzDpaf1&f5=W&s94OfviO)R0~yadmZbRLVaQYXL&5OpWmrQ94l zF}#6}Ul41)nest@f=wmfk9;)re^d;e^DJK z^iVB)82L;jBPE9}A?9fQF{2V>Q&+QdxFnL;K9w{>0ba#&z~Q!Eg%H>KRqM)^n2){zg>)jDIWp*fJ$l zcp*|)gRRjzW_|M2)xkvDqC$$m_5fS&Hi#jq1rB$dDhd>ywJU`^k0Thk?GsK>v%tYs ze&fL;G`$l0IWwrZ9A1xETy9Phvj^mDAgm8ovx%o_YJMdt2+2?Ma?LWi^ox$V5H>UV zbEsEKA}Jxz0p6;1-_rCV16{jT_xBPbSwV$)wBR0p?Hc642sa|#@KWBZ1fJ9lEFE-Z z`So&!2e!vVfK4L<)1p4xwiiS4_^&J;T-nkBk#(D1yvaXCJANfm7qDM$HLc&=SOL~- z?diLI3t44R(j_Ht@9J}+297_5${=X9I?O9m3j9g%D5tb%A%hW}5x=W?H)`(HNxxIq z1zQMGk?-Kkg%dLBnJ0>G$n_+C6?1lNsOL^s#PzQz3S~FK7O+;P`&!E2 zA6r<$WSCTs7<6={mm z_Sm;`J=^1ivUrPU7VmZ4x5)P5MTI(aav|qbe64d$Agf#0(x|ZjNw6|%OlCAx;1({S z=H0oanAuV_Hp~o3SV1ni=mEG#=>t;PzJ5+JaGlKnvcgY50_~d_L3jYJIo<{5jBB)7 zhXH#I)Xr8XUkK4FTfs$-eCI?jpMCj>h?5@+>eKvk3V4*8NsbE|D%LOH1MUZRW5;6! zm?lRDOI#p!(#;m)0+Tt*_Sd?fwG~E^y>^0 z@1fU(P!yh2Hkx;I`Z=`6R2c55u%;FGN_p19SZGr6`- z+@e>gxD;nND!jF%jR+xY^skstSF}%)=qw3uGH9E;wA@`w_=^?v*Yur9kL>EZtU}N_ z&R#|W=eM07CT*#i2Y%e7G|R=7u=TP(%q+!f(o3z2ArcDAbemfC^}}pTbHoUE1yxB^ zhT&oL5(j^>h^U_izMJ$KYsVUCAXKXwgqhTev+zXq+<2YPw^^PAyJV;w)B&2o4oYod zB*tAl{`xoAe(N)-%SYl#Xk4otii~tiGwJBns4(mN^E9DL9m&tdEo@_qOS@;6KRxn! zJYlDHgrMiqu~#l)@Th)*>wN{J3odWXeV`%uq|LC#7@$HR1o?kPb+~BE Date: Tue, 1 Oct 2019 12:27:36 -0700 Subject: [PATCH 091/455] test(path): Update file paths --- test/integration/test_visual_recognition_v4.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index c00074931..3939e0662 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -72,11 +72,9 @@ def test_02_images(self): self.visual_recognition.delete_collection(collection_id) def test_03_analyze(self): - dog_path = abspath( - '/Users/erikadsouza/workspace/public/python-sdk/resources/dog.jpg') - giraffe_path = abspath( - '/Users/erikadsouza/workspace/public/python-sdk/resources/my-giraffe.jpeg' - ) + 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: analyze_images = self.visual_recognition.analyze( collection_ids='d31d6534-3458-40c4-b6de-2185a5f3cbe4', From 1043f084cab212ad4faf6fc9779c84c54fb9dcc9 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 1 Oct 2019 12:40:58 -0700 Subject: [PATCH 092/455] chore(test): Update file path --- examples/visual_recognition_v4.py | 2 +- resources/South_Africa_Luca_Galuzzi_2004.jpeg | Bin 0 -> 289418 bytes test/integration/test_visual_recognition_v4.py | 3 +-- 3 files changed, 2 insertions(+), 3 deletions(-) create mode 100755 resources/South_Africa_Luca_Galuzzi_2004.jpeg diff --git a/examples/visual_recognition_v4.py b/examples/visual_recognition_v4.py index c244fe1ab..a9ddca0b8 100644 --- a/examples/visual_recognition_v4.py +++ b/examples/visual_recognition_v4.py @@ -18,7 +18,7 @@ collection_id = my_collection.get('collection_id') # add images -with open(os.path.join(os.path.dirname(__file__), '../resources/South_Africa_Luca_Galuzzi_2004.jpg'), '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 = service.add_images( collection_id, images_file=[FileWithMetadata(giraffe_info)], diff --git a/resources/South_Africa_Luca_Galuzzi_2004.jpeg b/resources/South_Africa_Luca_Galuzzi_2004.jpeg new file mode 100755 index 0000000000000000000000000000000000000000..67375877102ea055b7c66385cf0fd83593b1a5df GIT binary patch literal 289418 zcmb@uc|25o_&@wPGsYkp*^_08GAWg!>;`2^Owy*JLbi}4YZy`8$sQGnktHfgmMD@+ zQnyS@6e5&0NsWDbuG9T}y}rNK^Uw1uD#duh&^02PZA6i=W>at<9SqygWR-JbgC>xVpP~I61nW*yQEo zycvJB89!ai#MS4-sZ&n&W_~UwPM@&fZEI=2&+Dw8i@m`qA6JJH_7-R1hslZ4XM=-X z?YC~(qPEGLVY1Xqpqm*P*)y!IjLj@|!6*q zA|m?xb;7~-i~)mTfxqzd@^t#|-T(9FWGjLzA=ILRU+e$;&HsyI0f#d_esJDA{M+j2 z*NbMqX!vd|aJf{HUs$nwnGtN3WAk)O|s|eoh{~R5MQp zFP}4BJ}3N~9O2ym#)p3jt@!Ume8p(+L5=l)-~Ipb2fh#gUGC4`zw3)h{QJM}{qKz& z&ieTO&nt|u4Wa+1*Z+HsbSZ?aauMR0|KIo2Vi96(M2M2|zwfP6MM!uvLeJ8dI*<|K zWThLRxmMy!0vs83_sMMykR(rS;0| zSIVnwQK4;FOIuIFFM^TDWC1<_Q2_x_nzV#8?f>)F(sQ(ekGP+Nh}a55Sb-5&U`wwM zY%E5?o$G(UFc>YFNZ^CtnhPTWMkEq=@GlaPfGx)eM8va#B(hr7fLCVPDk5Y)_Dp{0VL@83kn#xeX!XRRhN9#~cA<8rw zYedeK{Y(apr)iX~f`p!NFuEAVRYQ6lMa?X1tevTuwR&M8pB}nxf+eK?hc26srs~a+ zW`ER07gAF$=>lRL3WrN&a0zU3Fh-eT33dPAU@r8`u{2cQ6?KKK)Xv=EW-7oW=JI0; zG`c_nFO#y6Pt+^L=(5u+c>kFu3#&unwn&|-S7n2A$E}HTY?8t11zi_zD>~VlE0`QEC7l_4enX=gH(^;A9*qzck%iIa%`tK=I?ED3ENrrusXfOa4^6QI zM8pW8K`bFI!C#E(+fl|Z8OMQ@g`x85hQX4p)97VVMqsOM71KALOT+XFQFW6!MkCc1 zjnL%_QNRxuVm=F_%fY!aaLHiQ2aAcS2YE*6@@{CDMyya0Bg``R;1hNn1jEtxXA#Hf z#AYT~ibEl~)2@sK$-C`s<%MVUZl(ZE#C$h)$jxr%O$!VfEGM7A#>4mnB4B~DlFrO6Tn1D#!fHPvF1*}imMrXH8TNEnc@5!RfQ zPBLWL577zC<#aH(@Ze>{CcDyyvY|tcB>so8S~kq4eeF>sI>imswux}r!_3DP@(Ijs zQ@PBEdUMQ$$YqJb0(zE8sG##qy<3CCVwS)m0W28&W{j@%$&ZD#<}8b5%7fVxm}sb( ziMX)JN+a~mxhQiCOm!JuX^{r@CZsQyYb@ZdXvO~K;QcotJxlCm_OA=o*8 zmQWWL91Dz{x?ZZ0en!cNpTNBIxMsrCl5 zu&1&xY}F=PVR>^AaYU1{Nf2B2N{wn?Xt2iSioh}f^z|%D48|Fp#4|S9&ZL=!x@@FO z09Y}>a?AJygk=V5?!a&neyz=3Q~08Th$qPQQ!1iHYsW%G%xOe=E)Yb{hgbX5JG3b2}kMcWvrjyD8M@6GFw@^y6cZyeknMv zx*G$}Ws?g59oy6qI8zFhMw(zzs^PBoMI#JC4&N?RwJ^w|$HBT-LMCPWqIb*_Hh06a zi6gQ@a}+O)1Y;*RM_qD5vj98tBZh>i3y4ADqk!*@(v^Y{7gpB_)~XP$dDNFKmyE(V zSoeYpcn5gH!XQzKB~)XJzJi-(RI!&WxWJs?N(}NOi-Ln#AspJl?coq$0DeJ&MIdNR zvc!V9EaA|*$cDL?jI}eh*(AE4H(i{n>xKX~t5HB5er~2MT2Q9j2-9FK6g3N|+BPC` z9I81M@|B&?my43A_GSD+^KAZ(Xv7j)^jkN%P*aCX|T^TF;Q9uE?a9b>J;7&VpIr8pe>gOT{SuGAzAq^uThn017nZ8Iv z`Vz85;#6(MvhFmdk}U#T5W}Luz~B@m*oP1Xd9Igf)dh|Xj%$nULa?xc5Fh|(a`8Zs zpve-t$Ryj*h?$iv$!c_|nW?Lf?*+e5e-wFcguY4hIZJd1wicrk@o9F!W{}|;jAaWn z9vpuIhVY+Zr2u*zfL$0^zWw7NKqvsZQ7|Q~P&c~27#2rEbBtv%985K?6axeSD_=sI za1Mms5C$*!qjne<(TF2}BMiVo-8lwg2{44B7$iJ^{s7aV5y5d5Xr#ZUH^CxKz^CU< zGWDw1445X|8)>l_$ykd9#2D&&$4hOwNN!>cle0zap%{Td{tF*8;$uY^uC%a{RdWsr z<@j=JL=7nphQxFZb9BtmMVU`1g=)bd%TKbfT9zPS57;>t%;pOjPb0q9)k|lCDa=YE z+0a4KC3@I*)Vh6^Qi~LxE{xC_F;P@f{gBZ3r z%O<-4D2fprs!^2#xGH?h&eS#{0X%+q&oUAw#|(MuA$DN&O)jPmW$0G;xFLZFjv!jb z2M8PvkXeY}VoCr7;H&`ofIUZHNd%bGA!`x~8+I`T)?+{jt#8la1s0-4h{hlW(5A#7 ze#qFM0xT{lpCCjd0dy=3l13n;LR^Q5<&(xdmvf~+o$2WJhcuyet%%>Z;<2$B#3k_iCQfZdcLF#reE^KcRgg+v412u)CR zRTtb46RuiHI2lC-untZliSt|@jZPxg7|>+|M0lg{YuTHliGC)G!|)J;$q;zT|%al~*ZSmtZ+E`bDbq*|{#NGwBO0o`I?)ACli zFrZeL1I(N<5AkX(&?nee;3bTNETr#-nRJif_6x6I>SBM=M8q)8f->onx+2-LmzBUR zpyJ^K;mgm>=hOR0{p%G=;2OfnmtjtvVx0gJ>5Agj$XeZ=!<=1E23kl$c}#P_swNyg zfS$_g>P;Yh^90^3ChUG064C_F0Wf8WmH}d`Aj;Gzj)bsjEXjp&IAkpAWb+2HC|yj0 zwnBhr7&1T=7#$!10chan7BygdWhfb&fPMFL0Sm^_Spd_`CtSlFb^%8L92M}{g${zt z3OfTu@cR4t9eYSR-sJR}CAZ%R}@QQ>4@kF-$`tBS6D$sHPft*A_hF zZHs2A5CssRh8n~Uq{GGrU|oc2fR{ca;jmDz4;N-c_)cW4VMMqP%Uw(v5!w)+wAoC6 zf-;;K07rumR;s9VHVb@KHx?{u03r-fZKRXwh6cmkz?xY7u;jVu)*e*zfM)8SMF;_} z@&`If_GOs*6%c^a0CmMWAPs;}0U-wP13d4qqq$+KjVLr9td;_of?z8goPSg zOzIRXQGm^>HEu}Kb>V3=6`Xg0}w1aa8v~FkB4As zv@ncne8Cl-Rlo*-KhMEhgu87)i+?i=GVnB(pfl`92v|xe;6JR=TyGQ-Q`G)LmwL`+ z5mfPXh(^kS2ozR|0TsdhCuZU+d)cfbJ5gf@GAyqnC0<=p_Ux}x}j7$Fyu4x9hA8zN{+ zCx9^`6ENo#9+Ih0Cj*0&V+5!^c;z=oHZ}r&Q-*?1M*S0hM+`G0>m_f54_H5!VL+ZE zfU>X!2rD(SKn_gLE}=$J#0dT65FG+2j*?SZ+t>1mMT-z;=WNhz1et{v2Mt-%OBHEg z!~XezjDUP|X-qJ1@`$x5*uGSgIr^c^!7*%f3}zUh23RZkFl%)qpXe+M2WLsDvm8L2 zdSLuOx1uq~!bS}ZA<6)V$&abw>}(W5g%?l{5g0pz32Ed2Z`38PVDy)$>Lp{{Wq5)P z9|!swjL`rLCiAgQPQrS?hFkeSc^%-SjIuQ^tNAEXjVRbg1ZHG&^|_I1#OtKzu{!UB*-u> zrf1cty5NBc5Wb=ywXc_jYZt=mAaN=UP2f}yz$ck7nNK*Gv#h0=1uuafdjsnYhJA*F z6qq}L7^~F_v`!`xh^O9*9I`o6zR;A24+0k=aQ12m!VKoZBR`ggg>k{ZhyIEO`upf& zR4p43`D#-PLT6|`&lr6@4trpMk8v)u)>Mo;wjTv^BDC4mAG$EEi2@YDCRg_6pnT*) zlwmMOBMpsY*u0Q2LP9GAkVfBZ$t5_%&v7DxGu?!hVCP5Zaw$l)iJPscm4;-MO+_al zpXZMTfrY@ddk&e$FB(aHiY2N}Rb`mkB*<3a0Veow0FB0$L*@v}Fi?m?IBu(W{0j&C z5x}$rP(6o@0r17J6DI%0c4@>C&2u3xz{&}eVTl1H#1z3==(661Jawj$nR5(YN;8YU zTbydkR02{U1-5N*Hfwcv%pW>YYGlNatm|?J#-*EY3j9gX4|qC*Ibvue4-1IKAYie9 zxzLE`X&V`P_(h_Y#idB_h*Pyr!3T)ov%0|38|eb5AI$PNrJ7%834sWJQzBd`(1j@B zn;s3DSO!4^43LB(A;4fk;AS9A=nj&&jhJ}v9{;A7t!MTG%b7hmTJPZ@M|}U>>7S-u zdmB6>M{LqL3JqL4VPC)K%JK5shHq5VI7ZFesxME>JkrlSQ)6FkGNmn<6JP24Yq8R+ za2GZ9+|7#pc88W-e321%=gC04L+g`=&T&reB{#QAUjC6%7{lZw0Dk}+qzkEn;?~6? z+vkG&=3|-7*8r9>l2M3F#2y2Je*u95T9%wPAS#c1GmG4Ub0e(dVFC8jg;=AGNJNS` zDgaVUTDXhCs~G&ls?liBjm|g}GR69F)CR%HZ*DMOvHsBLO3^oMPF;Aoq6NSICqXEH;wp z>^b=MKz*CyKvzYmMS8AP?Z+$TAFLjYOJtw6xtS^_^E*B=^Uj^t%A=xM62?cuh0g8n zUA}L8nNiup3R6#|RF8nuJbaV^o`4wxy{ZGB^vv$6Hf>_~hg#I_7GeHSikbB<+WAd~ zlK@scF$55!(F7LHfvCzL6<|XQ9+p5dA%{Pjxe2rYhN(kq6yPe%0RIL?C5A1bXv_-O z0D)`1U5}TW8~Zx`SyNZ!tko_-PlL%$o3 zV4`#EW!$VaSUR{h1w?@GV5aO{Is^6%@Rfmvwb=iOnJh{$rp|_j-W#D5n4D!CXpdmxzAQ;V>s7s#Vh3FLAj0|E31vF%>0UcmwG7ERjB$&Fe z2w>EdGP+Rd!$M?uI%G9h`60TvDn zki<`HE8_!Z->pVq14*x}Ljj;LFCkFLaX}nHS`cpPu;fG0@cVfN2^&^FcveKibY@fi zjE&&cNtAZpD*Bwq19{QF$A?<0N~EeQgIc%x>@}OQS>PoF%{b<+`_LwC9=AO>^dr}) zs^p*S=g(i8*f&?^UQ=z+Qi!%5{J4a;Us${4uawDJ_af`J4T*{hdPkcRSj0t-4CnSI zp^Dece2yt(a%yW8n^=n<2W28M(%BK9ghEk3Wg{Me(>ajIfu^rISwQH!V~(lT(IGg4 zAXB4;;qoAaG%>=$Hi%q|gvDekfIZF#@oX9LRMrVxW6}n32PfsgCsC*}J<2~{45ui6 zEv_EYY@mGg+Npc#iY4jF5eXF z-U6Lp*;I&&0ddpMHKPVkWMPXb$PmyEB>lJ)$aJLv%Bbd$NNYk)GEA45S}a8_c)}?K zf+H+ey&D#MlBt@82Gj_0RctbBHQ))>vXUk2-Ok)M1lFzx{sXC5E1Vu8jcH}>gGJ9g z>J8T#qHp%5uO8F{{Q~IL99!rqBN0-0NZ%K^7@f+J>=Xr4ql?OLV7ovEX0GLz97z+# z;}RcBY$2a#bTVsAU-~Q~LYbajXoMF~X4$+h#E0O6upM8Q5O8G!7!Ighko^NLBCdWb zQ{U|`4!|y#5A`7SWLbo2%KUE|6&tx0zo9EH1RBG5s8$sthA+5H=^=eJVTPUPY>aPwayy+0( zJ$+Gr3sFb<&w|Bu^%>bu4z4!?zE*kasNel}{KDZfbho?zcdtO;+@#jv^*o+YUpT_-uw8-pKh76L7YX2u>)+SvyHWq{{IREi1BP$ zLchK)++%Zt95!68ANE$OTxH+r4Hik8sc_BRiI>1HIy&U@JY z*j99Z%WvNw$F44+=kAof%9r{*F78l}{8g5-+uu_ZJ0Q9B)xSc`WT~;pQM*lMpGOSE zuH1<#lx}<3T=iiOPc!XM8w7V6%-l2-QVJjy@J*fo4vgo)coi&z1Gz1v+yJlOgys;PLFk28%Eelv zBKm-Cfr1oX0;Wn|iya=fk2t5_Tckd5%ViVmkL6I*<2P&9n1*{l8{zzVXoIu|)gZMw!GFv{*eS zeJ$bOi1{z~-o2B&{CTL)&2jRIT9`~5_lu`|uZioKNB`cf(B@zLOIP6PR6h4}r_XE0 z?=N!6^1egp!;|diy@wPTB(Z7 z!>z^`^Z>DqN?v7rtf3(TgSK2V2s0#uHS*PbViN_B7z}&YNwEs3%2Gnl7CAfr32ih3 z0Yr8Wq-hYSx*(@=P?!`)memy_)<8V1p9io65|n@&sAfX8&7$C?Iw<)7V5-jApvf`3 z^fadis|*YRsOa8kpmDZH|FIkPksmU@IlKS>MMkSax>)ES&ls-t3E~0;sQ%yvZs1-} zKMgm>f~EhWCX{hk!nJi>NO%DY%A?>3EoDgF7XPg-Y_&3!iUuKB!?9v{nU9nsI59B;H5S2XGc!&{NuNt#&|5sY4&gI!|s$L^cz zMxT5dy7}%BYD-F6%xq{H*41hfqAbSxT5*1q@$+oIzM`ylrNocnwfY7bVV!Nw$0q`- zO_osXSVzOx0dD1)F!dtesvQ!4y5F53y%Onu^|b4wBCn&pb>zX~AuJxeGO&v@`!KY0|eg&Zs*_djd{+@q~4Ct)g| z`u7ufe1$#v8{+Wg6=8xZtOxB1W&%veFL7zd4W}YFZ}A^7wCEncTASc5?KF1zc$(>i z?$##nDC7IrS15RT)aM`1`TFO1o$o+hgO6HWVr^UHpR$rAbjf|=N$-_1cUDRr=Obr^ zmGz%GpT0gLW4*e?hq7g+-Fv31{&ApfJxX)**&48-L+9sMi}<%C^v)!!y~J={s;&J9 z`PUbC?R`r6h=h`!qpsbSP{ys7i`OQLvOv+9y^y4{s(q27&~~DCam`3WP8%zz2a}IhK(80EGIyNGvpb4lfN#K3yMf{ z4s(ow{OkBdSp_?nwYA|@uiIG1_Za;;E-q%S_Je;2|^#KdKX#C;-L;~i(bS2Sh*!gHQ_Sv7@az$ zjsiH|)~3=4IKtV07#-&VwRfoR17GG~jX2zakPAS+F!+})Hi^Nd1@z4^eT!b!GHaeu zJmX+2n`DVV+lL@{;vj(~pj%mh%|$bzP{tbw4$oTFX@e<0S4K%%yTp z_tW%G=g2N;IsP9kc!Cy{#>HmN#qGDUi;_7jC71HOX?$;Y{9Z-%5OVdn8W!`&aFZV8 zSxY5~_tJUrO+Wa;p0TiHWm)GotM{jza1dX3V&xGMpq_tg_QhxAqR2KyIZCdD>;ChU zae)Sf(lYnd@cB9FA?J$6bn%b;YmQ}SZY!Rfe30&Q#`VVc_Vw4N)_J{Jr5zd^GWWR^ z6SGqPvoTSkVdtN1l{SuF9Vd!R`o4ettyCH`CZT7pvWk33$6og0Q}Ttf&z{zMz4%M3 zs#A8GJykdz%PH0nuwqX>=r$V8O*vpvaaroJ5rM=A9YHoC;@iXG0`nlDs~31O>Dvqq_q*JZ{V@) z*tm}>Oik)p_3xEAO_s`u#nZYst$*c6T2>s(`+RQXgqG^wKZJKNj@HdVmS50i*81z}lGRHWJZVKKpJPI0x_dtyyE1;y#`UlwyVU!=6{xu7gKwb8$sXneLxYNCN~Pbm0M_ z15FuCYJ_m8p+UqoB;-IdSvT;N=9~n5%UyKQxFuA`N9n}7s^kk1lzbSxP_CD)1EEC> z>wsh^L5_>UtLXsXLXaQMdJoc`2XoM@4O4fRexn!XL>*}t$@>*AAe$sH0!LUDSLbX{ zBj{jt=&XJda8|)V_LB zZPc35*oVUR55?V3OqUDltt|L*OCX2wo)z+>@Psd()6MX1RE2l<|R9!ZT-s1M% zsl=?g@1pMS@p(hp#NDL5=MAW5-wRQW9+df>9cUmOb~P{j(lF_ytM!`Sj>dic&)@jz z{=>uZ_W1Ep%U0WUhqPtpo#n=h-@lbtq&KeId-Q5f`%o5)a0`Zhlrmf6|7 z=ke~JZ<^%XwjX#VUv|~B@`P8Q^uXyXqfL$~FEW^_LmWz>UGoFI@CM^A+P`enzO4B@ zG4SNi+H0=G>QCyZouiyM1Nr0yv%-CQ+Ew%Ropa9VEUU{X^77EyGr*H%sPiU%&;2_E z-xAMjD2RW&v}Uh&nB}>Lk6oTlH>#ZNxH8?m{@)DQvS{s_lTxnPev2oyR?y@P(*1H2 z$49q1iR*4Pu^68y&$yN_ydz^P=bLK$`tQ^B%5;rQRrBu>&K%L*&{jX(GQTI|T(t_< zZeG8)TK~{d+LN-Y38dcJpdI8y4_^#y%FYPOV01hF@ZGgZryx5aa|s#ul*}GzjgfXQ zxf6^-5p>N&k@!WJc7LVHP&c~t-**)?Ce#tIhfzbq1*R{kICQMhlr;wW8Vza+e;FOv z(ORMaQ`U_kaNdY3u1FHblOG1%hRG5wcRc|$uw1wx zfN_5KE6=R&zk`0?K0RNtcuM9^M2zpd;SwFU?CxKFv**k`zkfI?srC2*OEN>Y?R!h< zf|XZh#mw{Fi(b8+tBWHl!B>qw5oW zX9DDyK4+9Gw^cs9`sl;!Y<3UTv8*QfcFMVvre=<@Rt)bJy@@N=AE}wLYXqwn_)Hwm z?B|a3?~v#>{&a6Ux#1^YZC`Vx?#|?4tCD*H_lz&~9+P!+58;$MKaD!qV;O+-js~9{ z4&885QQB>HN#I+q^}Ip0Vk^OP*>Qq#_sy$Ka@lzy9HX6kY-uW|U;8Ae~~a+xuG-#@{IT9$LLH{L?niaOdl*`gKN%+akZO7PxOk9autQkuJ?Y zI&?&PceSbLN&ns@-S{X|-8){FOxQm$nrUQjGNfzXB)^1G{c9?FW@{{dy>07pN)9XI z`1ljcq=XqvkW(gx42^&d(q(XkSN;UFnc%%h5PhJgmCy%usWLv?@$(507Z4P++3*`Y zHG_^o9w?4va6y0>$xyW>5m=DI?Sn2Un@?~WG&hMu9_|o9U%fywhjP_W*EIr*S93Hv zK?;adW;MU4+)JpFF3xhcXv-Ixt?}=Vy27mkk%?dR32UIA1XwilKBIurk);T)ddJ<$hJX&hc;Sz@!0on>!0AeGC z#F(!fwBTzwW(cvQF4_!g*yz&w_#-EBNYjVkMQ4Tx8M^ z9GB%?=>8`Ut`u3{L`>*!yDGi=J@nZe*2e&pQ*Y%71gT-Er zy{`+Y(~BLFE?q}HG?pzJxy&OM(z)H|efL}K%#$IR!H=a{QpC%TR`KV&3)!5sC7Oi< zlHRIvW`%CKU)|M1GeU5ktHweOOAXDXhRP0g&xP+=F2o_bog%T?^n-SYBEse$jc`q$;M+38H> zR8{Y*_Qel0f5#?=YQGH5yVonV=JB=f_s=zs`gk0Ax%&N&?9AlEdWE8Om(6W=9oc>Q z^G2?=J;lIhW5DoLcgZ|g+o4Fc#4SpmAw7p8GTmAkj1f<($t9%U`F88TblL8yE$&UV zv9>LTD_d0Z%(x0_dGCkv1lTdof>jAQ=^=?3%1)_Y)Mpp%cGHx~rcOB*1^UeGKW@l+fWiW#RL&KLN(?iwZrMb zn!ms9JF?wgaJs{?^;faVD~}~K>cFROU9Ude`)^+SwoPPS+XWD^KRs8)8||`KltD0D zs1}%(QZ4793z1DO5F_-Jfl$mZszwFbB5O4+IA%eX4LLua3PUO7ukZw&eEg!g1Ojl2 z7yUu_pb?nH$5}}x_O^%DAFk8e{*&F5d#JiO!Q9g+_DH#bQeNmT-`yV_EU#)Q4COAN zHQD#~^tm2?Qo4lZ?CICNme74Wx8llOP1cty{;<7UEA5Mt{F?3WYT4)1+pCm2{8^M} zQ0cJJkDsTEiqvtzgkxQnby_sk_P9x1DxMOccc`UJgU82;} z@+7(6LC;5t8ee0$y$`J!Z9hFKy(Sela`Q@}S2Y~3zW8Oo*|q*pW}dMbDDYia&H-!l z2OFC=bUvQee*N5hl3`nH3$seNhb z=8osnkJ?||&93sw9=?3#`V!)=>J%^h*&$%5pJW*o?95v|Z&xC*|Blt?jCEGKuFIQ$ zaIWpBI9~9RPhmowS^s8L{#Qv`s1ZDz#2GE)+20EH1 zXgan~0}{|$LQpy9P_?0S4~|2@I1JMB3 zmH^y^=ow(B8o?VEdPg$N5lhx4iTuokm{owF-Y&yn<}2#mSWq@4cEX@Q)#IR%)*R^e zwPEHH09kK6<)AU>gU~wrSAY;l+H5FSQtZm0YQ0YHMs7sNT=Vnfhw{)t2h}SZk#L! zV=+Iye5&ibgR6#D^geaA&#PiUK|6DMe@|$M-5ww3+gr<=h4|m>lwoO3 zHroEdT>#aXb=I@n%Psn2%F`X0XwbXE)j!r-q(R%T#G+@GjFQMok@Y%Z z(|vC%wVe+rnKqBArKrAnX4_El^WSq`REckYn#6a-*Jd|-D+=sXOlm(=tMDpGdt=h3 zk6RTYU;l8Fxu)ZD#vsq!Cd%{v*`8(ldd8L=dYLtt)KjKbzW(eV)yoaMC&?#$xnDDs z_az-jDQ|PM_Q;zL-1JO=^JCYuA`e&T>ej0s%BT1K$r8>f9+evOVPV_{RmoR(zX-3( zzABQEH(xg2vURLZU&JNYxi{M6Zs)OOhf6PPRewr0yYa^6oAdW|s%r*{#+R?XsHxc9 z-Jv2FCv19&vxHXNsphDC+IWBTv|63F;DZ~dI^OIjOYP!$U@C(}92x)RLrGb&_VHwqO}Vs7T;x9B)e-x7+yXX5R-(d(RM z!A9%P$6h^+x!kmU8Zf+}oY!V$Ax(`s5bwMeew} z`&h^Gl! z<$uN)^DBSt>fGC5(RS_6>!-VqbO%}Xaq_=rmf1=bzdTseGM8%Udu_zN;CFc6!3(7| z0@FXo%-Ob+M_l&qo;MSb>im813{mI!oU`n`dt#$fZ?!*j0~S-yE_)Nc{B+BKYs)+| z`@J11C*Pv^SB}5=J58R29Ml;#n_KldSG@3pc5l3(tM#-~nLcT-oWEBhVK>i^XYtLX z-yUa^nZ#@%)_8a1A;+Y^k4F~gir#cfd%u~{l_=a{{`f;-)}u$46%OU>&e3>V-@k2r zJ=Y6{?_Sd>@S#{a0B5tpO@ZFVR`|1@sDPa>~I|bW+((VY` zKkwe&{5+kc_bvX;i1oK8j)kIW%RfBw-E>v+G4Ud^Sb6%ViB3psMX064X3#$t_!^>D z?%!ko+a*n|NTTqxdA#yZb>6^jGrpa{Mckrn?z23(Jeln7G&(4BpfU5!n=E2c z*`WkAMZIbldUgC!Mxs_C^m-CjWRxN@JPqLh-FySBObQ#CDY!`2`#(w44W8+6A*vDj z^6>^MeRJmezZ%3-U{*F5-o7aZ4f6|W7zI?)2*^#(?-W<$)%IpUa|;&~V(7v&`U$ZS zv<;gGZ5zU^>6AXdU!mt;o^-hSN^<>^FH)XI9Q79lAVCtC(&5VVWO7UdJ*Ij>r+3sw zd=EDo;7i)|#n-P{yJ5AfW5C*6-v);a-|n>Wt>1#yzBMV3%D-!9SEuNIq_a}w>jjy< zbb{{Phod61RD~z*9&eVA>Omfv*|Q7oC9&y0cU^fY{XW$-zh32!_LD8DB7D1)^1Zx* zbBc>s-rGJZG4g8(?Tgd&)Uo1C33oF)a!c=bV2n#}zR=A>j*mx6x`j|UfLjWt%I!`@%^>;@6{Ubwg>4f zxK-qFCMTwLemkG6R(?Ro>)!Mg`c0FMXH(alF&Wc!9(7W`9X7a}dQwTM-IycM#MAuGp6kn{fA(30Un+Op9w0(Z zd;5Jy$G@*4{;VGintyj*Tl%f*{+ot-TsT#0?@tHUPBaO+t9F@XS!pXCSv*rz)pL26 zcl)0PDc-8ohV|Qnw>-%)3B30*V3EXOJ!$@#d#$$i_k-~DJP|iKuu(&!cBaM~ z7Pbgoe$dGip#ja&cyF?;hzdN1!w1cK;AbOr8SraqL@aUx*$3T;+A`qJpENUAE_&4<#92 zOyq4#pOzQ$J+`@W{lcc7rLh99Rm_K9&-NU8bM@uvUy=sYPDevap(8P8yr19iemlCk z=2@)1q~kmHhlgEv1nBMV3|iG|TJpz~r(*A{Tv$rxrWGFdihdu7Oir?`881;D|M~dt z(3a&mJRX1L=UG{E%5vMh+f-)=wKWi!|X^uu_q_oMHDObz<&Q$U^eZGQI zlwlM>e?%gW-fQ3D;R2)vCt_w|r@k z&KdFAa$*3xzEVLq476!)E6E)`&PRQ`ha~nm*RrLk5^c@*G840Jkh|{0slHKnAxizN| zsXh@dp?9aPasoH;_q|QPbEKyL-2onu+>_lA`I>ZqIJYPUo`}3OMrf-zYpWVV_OS@M95X@EkXy$=OS9B3J7wGWmG#Z26EbCQ1qu7 z=~(R~^ooT)D+Tpk5_%-3Sdul+%r_LBAd5f8)*=rr)yEg$!OzBxKp%qI7$^=RWaznuHlH~Nl;kiM;zF9pg$4Wp zAU-I;i-;*|%`(K7ko5HJju%gC|6M%V9{c=+lUx0tha(EX#?=c}gh!2O8V+xbE4EZU zDk3*+dzN*ttMiMUl}g?BS1(*2ND+=bag1Oi)i~zygH2BFe>c1}DVCx=P_@-LJni$l z|AeoaQBTCi2c|R6x#Bk)3MCj$No~6xS6bAqGCy(Pk2%eUwO#=tVtiMgZc5VaNTu`Y zl~Je5_nlut8{I}8YYY^OMy986B}~)fS3Ud3>({CwXO~fxoaFp(g3fVwhBB0gO&e>| zJ-D%kAp<2B-v({se0`C>o0#q=Z>yR6be(G0>px$^YXgtB)U`gPxhL$fk~;Bdi)Ov0 zm6TFfrSpy*T&>m8W93^f&bBO}w|bd5yRhxTM^g?_c`b@jorJ-Av6$k~md6_JD?UGI zx!urr%(&;=-X0I>R@1L7ud`(4UWFX)4(jR%K7Q>qg}&VP%MiCF)7P)!-lm5~Y^Rq{ z?c&B?bt&1dwV#g66!$d*P0d8VTS5&%lS-|nFB8|Ri#er9TUyLqGKA^wd?LwzruA`o zlIdEK5!xU9=%GU5YrY~QE0^AYZ<+Bg(w^01FQEzfOMaSnnmr%bsg*wR+U}xA+$gd6 zUkCl|s_DlgJGLKQlPUSxM6!MLsM?ixN3wa^E$=?I4F9ek^X!D)jSlPIwXS6ghA|n< zJK|py)y^nf)EAj=2QPHAz_^zPTTVRpUs$k5x8g> zh&?{O-J9baeX%HKPyXH07k-tO^ziG@J=NB4Qc zZECn;{bBF;_Vn3J+4+ZVJb&nV;Lz87OGrg#ytpQLvi{uuK0QvfSIrp|7j{+cwpH`V4)appA6m1Q6IvJi>G%3VxdTVf$?q%= z9Whc>ZGz`$WuWnEc9EmV>)VnBQVIDqTfl{$3XSvdq*N{nr9ev{@eW>@NA>WG23mw;y^l^q_uEmx4+ei_#1_%tSf27lw$FI?S|>SLq3Pv z{(ZZAD)xaQR6Z%C(H|(M95#_ZRNUKaSyi$!7{nwoBe(01ZBy$3R$uK)P8=ft?@ zXY|e6g=5skeBb+A?NAC|UL#VqdpbOLtYhmSs(UaObu!>2cFFjbJe@AHbA zL!e??J=gc8shc)AugKdyckcPAyA@xq1=u*-QhN0YeZvXE2d#8FA6*LlHuK1I ztEBu}UbENaaNB`~_(}yAtJ(thwDiSQEgRpZ<~^xw-??wQWzWnbY(j@ppv2sewEMi4 zsI_yZ$lznG(Fa%Vev0%=JNwG8pF4ba*jA-3c`iGl zGv^}pu0U+8@{TjU7wtVY3dPOJei~gdZ?bj1FtJC;K5p`h%IQhl3qhwJ8QUNuh2x_d z?++$~x&`f7@mfVf#rb)d`1t#@v%BAISh;x}+MX>jeeBnkfP$Z@F)|D8`}Ou#l#t_N z?wVG+1k1(u#ENVPUq1BV$PwN>#q}R5NvSuSm7eW!Y2Tgnd6(?C^YY`zR_@RClW{&B z!*I06jeK^*Znpw=t`9pY#l2& z?X`Vfvg6h*eDl9Ge`;rXPAFG00!&tp0dZgc@xg1qeU-L!(px!#Xp3&`#DgVdHY|VV z)`QIOeOEa>hqLOgFJE=AxV2Ea&ocR;wZx%xk0gmDw4rEf(0$1J+eOpgk)`JrEqq=N zn}#pk?LR@6jWt^h4-9riU7l@z163C&*+BhyC-mg~)jZZ*;~CkFO@d=AEXOO~S@3WJ z)OPU4W~}fBXQ9gh8cg9K0r;x{z>M`ce;@V#+x-v-%89Ui89)4?f_ZPc6g&)Hh<@gf zgA?ST)lUkZ{s&?Uf5!x#Ooh7C=5rh*19TVIE;nAq-0f%9IhG~WxR;u?_l*Z@#k-$g6Suhj4e*XUyLyqks9b?+P6pX zY3RYc^37h){%+Y*Tv_u`Nn%o>IQ7BW*ZwT7Y=Z_0P-G+*e)tpGdMBtCVDgyzY=kQR zo8Q?7nqGFSU#(!*DfBES$$g+YpkO+6!wcP_-Iro^+hvN!Muqu)|Nam4WkOwgx??6? z?{-y#dHMUnxT&u#PNU)!khmbk1hi$CUNto=zM7?%^TxPxF_Dug?he8un>0cF3gr z4XjIg{J}*r5&PO`Wl-UMD`Zd9P?|@&Po2t0{pCKR>)XnkeU8168bDwD?+*`5IW@@% zeq7sDI=Y#W^#1ct6|bbP3Oy31=mvaNtDkw2?|z%QpCuV$xBLBp(jz+hy$f3JjwHSA zS1aY%ddBiw`~r3|(9%)ul2%=q?ACUQJbmw!T8(&Md8_O_8QZ9*`>y`36e2I7n&_Wb zW?cHN`@8EAK0G+Lp-02>s_^4fXTn$c40=q7<0SRycFJ9cvNJxuK50{P3#pvjx0Ayz zPW6C$xvvUJeaY`25@*&^xfpfO#<{6F{r@8AEW@Jgx;8wNNC<);HS|bIccU~&NH>zw z4bmNgbV>~%EhXKh!VuCO(%oGG&$oHMKOTpQE%&|mTGw@+;|RoYf^OM|*+!I&nHl0< zdXk4p0n^juF8V*e4(^N!_olDB=-SL)zg+%2?$jTF8Ok&Z2~LdjOWu?=!k?IATfWfu z5R2dceW$Zrt}Hzfn$p4eEIC`AtpwX(M5ub$;j`pW&cx3_76lN&KTVmQwOA7FgZOVOTSl6MY9L3989krmGV6^-Uz%~ za~C=r*(`0yHpKxJ$|l6*O&s=E^vPt9-uSqoT?*XJ1ott)+Ths$4xE>frcGH0x=l0#S*w+WuMf zt!4wxmt}LOTjUR8k1U<`g0I=* zga}y1oZ!UVPBLC&l?n$ukAT6GNp7x4cq9_`jx}8yo!TrezGcSQs%m}bnz>dgJ+{-!6SLmgr-nSkm@;}GB3yJqTwC^z@^_m{cHI@#Mb&W@ZC zv(L*D=?#bPsdB=|w4o9LNd!Ncs-*O1*P~3x#!ZfljggSgl*7dFK6-kigl0d z3SxL?J=rPH;Vs0><1)?`4jdEi)nhMy62h47bB8oZx4ol&Q|~N(_(3hwEe%%4{1(=sLyMgDak>6E+*(7(E8B zzrSCG(3N()^EiG3-;j^a_;1OQp~)%-*v2?x#j$e-N@gI=7pWK!N#d^XqD|kbQ}HMOEucnNxOYJsg~X=G-VE~!yDc3FNr>cWMFKB1Ff{yz+ z3>|P609*=e2tn!#cK&yDGpu2#!2LzmT0ZjyKCjd9# zXc{atbYDLA1)q3ShHYRF{8pvy45aMcK@k`Y2M|TD;DRF<7x%kzMD>=aN7;8H0mC30 z3wqfgjW`iN{=^#myhuj??F34xJK+4R9_W203G!r*Bp&dd-vO&YqrDv!6qI^Uo%`np zXfMIy=0(Ap!(QGwJx`H#yk<)C2wMP%-v~X#xa5*ASg}eIl6X zKga~`X9_u%J1#3Ky!mSVT?q6A*T?=?v2#XN-@h(njlLF!%t2>&{xy~35)bdnxA`>d zH8ro_&f2xeXsGbh9~lWH$nRf*DTWB|q=Uo$V8KGeX*|Wb`U<-oRpN}Z$B}mN{CJHP zlT^=6s%ERH=ZnAd-Q1RMrG1+IWN?N7OIjzf>qC>phy#SEhAKe(Td8 zf*oDnwG%brtkkzUN%Bx~?Q64YAaC>aPUoZ3CTFhVN_3e36}7wlH9|>|rQ&Nsdw1(d znhzyi;$;8a80nrY3IRT;!Gkp$3Mku^XFs+aHb6Uq;wRxA15 zeRkz>csg9-M}JLmr12STI%&ahzIki2hS)TC)Ibye&7p2xNJeDc($aBMe#%}~jmMTk zbn7#JJ1eN=<*}j@1d7XVN_<;GIaR{&3e&*07PfG3Q+a6K%ojm7?zZDv>iLIjUJ9kH zw0?<)bdm1oLlbC0X%wckXLq@dvo#w<83(PReM(WlipRHj_d1@-o$Bl~0e!5v`ow!@ z^kZy72SbS;%#VV#yhOCL@Bo+kJ?!;0b|-eN-F)D9J12+E5KnD1HLI>|)sD&nYoKj< zUg=_au1q{-1advnu>OO7`cO7yMl*M_*A-_a!oz;6E@*dgP<5<-)6zVvu#ZkWgD`wv z;3!ig=Y}_(Iq|*HA243OQf|)v&07%_H8n)%3=OQ4?Y+%hyC~FpS*u3sZs<>V{&~I1 zzV^FnoqYQ>N-wH3I3u`5>(Nz^qR>_$)u@m0vlpWGi(>EB$#)B+2 zBMJYZM~OpB;;6RJzW*vEdUuKTTw!YQTz$c7yN#!x@s>iD57chV(7&J4#kr146_82O zm+0zS&ShYQ+IUX(kP3&Y3I>VTO#DhVGhz$=0`q9Ln7p>Sj>nRs$Szx`RYfDij=>Dv z*UL10$UCpN6aCh%1J$_~1Fv?I=qX99wM#gCLcvz) zay17X#0$>EDgBtlvz0(a38(!6HQ;jREm|LFvgXnNuGG%`ASAEoe=8XX<#h>_z&Tj0 z-l`{1Dp@|p_#HqIRSi5&76X*MAb_;<$Z3G7EDHLHEwA++AeM$%J>G zGA%QRy_M~&kh|@b=$eilRnil+KatK|#o9}4Y6)8Fk zsfll!X}Fi+W|jo!fi`88P_rR+H-EJ&zq$>M~FC z4fYyTeMHLM4>CmEyst`l19b}Tk$WvC!cQ2|_O8I^nQ0)?x{Zy)a<9XB_%As5SOW8> zQ{g`9Go7Gbl{HV;`tso+a|Yc<*XWf{jhexsI&XiN=5u`sC%c!Xc)F5Q(F<^bWa!1M z7FQqLUd=c5_dBGxD`H`XwOJGz6Ek-jzh1z^xB5|vM2p168qQ}jwFc+ehvNkmx{Oco z6rcRm8zD}Or;#0|z0PL-DAJN$pa+(Ou&t}=#--mre&@zwvG3dJj;=Qle}2BPm5)*P z>FYc=qvO&FvRCv3|Kpei<=($N-v8-6kJXqTmq-H-nu6vy|= z&En=Wx-2<_`WMVsd$*c$&R?X<$KUNOA7L$6HRlV)Hzv%Dl83~Hcg6ct-FO$9JU!^T z_`VigCmPR{Q1l{tsy=-ke-TyWv17RduDTp`meCWn1K#;D7Ma=$FZ&&%^6!ZWsbUa>P%U2^<%&P! z-4w(rQ*!zEZ|o~b6j(pRCOAIfjPx8LBln=IN)epR|LDavG|z=UlG|wWwwtLcbX9vu7=~+&+pQ+G3WmsS3^)ipFf}7JQmREkZ%Hrj zDNC;VO59_aCqG;}BIxXzKFGea{JtA%2Kfj=(2M7JA+#dQ--vIL=#}9RL2>a7lV> zD_mv5KH=)U74k-IjL=Tva4!ZQCG>scjC3od5Z z`IGJ{o1W0&QOosArOEO$I5kjVU-Dm+Ufwd*Mh>qQ#h8)0!*6L@1}J~`G`y$A5tY)! zT-q>E6T#?~%o|Yt)>phgZg(es8y-w&V46lj%)%=Aju5V{>FhL;Ln8KWf|2h@_Qt*J zYSOq-TJ-f$j|2YhF-vCsWjk%{ILoRIwMmH(opXZyT@mpwS8`nF#7`}G!(MrwQN9%e z-{{r(>mvE|0j;nlM|`@Ge=K|$=%y)}>+14&`_f9$yex0%uO~yXe==r9IqG2yjZO=n zi#*gN9^{!X_tvrf)D`TE3Z#%- zc14Zjy0|J1THnj%>()WKc3TtRu{yFnS_}HrDB}S>2VQ@r{AG@UPUW;SJXQHx?AfSB zYO1;PPc{0_RmQ09TB~nMNqm?%_&ZsCE^i6&czKl*bQs&&SGty#$-)h~Td)a8=61cd z8U${q6lwb3RV#lg^q4~%=P91U8h@(opdKdrft<3?X-_j`0hYcm$N1esqtfzf5!%e# zaFWI%_eVA0?GMDJ+I{InnCyn`{+d$?efyV&K!3a=S2nt(A-;6&ISP6bSIYAwayY#vl?SQ>okZ z)d}vT0%r3nakOx-x|=7U;-{EEngQ!d$fsfGh|0%t0s{Jx5iGzF13*Tw7;kld43J{VbhoUAJ|ciGaH7uJ0MnM;p5M}QJVl#R>O!E#{`u_`tQG0@E`K|-{kSsuql3-L z1>X|7N5^lq@Gkw037>ZDS4vuAxl8Z=auRt{-MI*pvc{HqIRBI_stqiYSZL}?vD}Q0 z(D!Gc$|ZNvr9VDo_O~sf(4f;g2)(;X6lOI|S;>?}qCO>a7db;1wlT9b*z`G{TubEj zmGE@0|9Yu;7WyaLGCobN2QnW@bt;+^CaT(jthU--n3{Y2{nZJIo^-cu*v4BTQPXER z?fwJ9gl_3Y=QP^(Wc$_E{ex~sILg>VCuM;@ZI{DlbOa90OfSk^5UUb?exqTGj_|0W z6I?|_Q(3rPLkt|&f%;k0KePK%9_C^>gVgUgtGh9CW-sTS=Nt)ch%0>Sztm4%+K zFN*UQJ9|qRUe7l|K2a7~w{^A2R+1DnX04n+Rja%5^oCvRabJKlJ=IF{*-`vdQTAus z7z&F4)cT(aCT9{TvU|;vJuYxu-O+MAX{&v6mwYLfh*04X-UGZa6pGf&38#^b77ioI zJ>B8Ji;b`o`~1;L!YD3b>kYvT5fYam^?PYXf?MN0(a8TGVU^(#7Z{Qwuf9LgAo?+| z@pcR^`J+;#@>{K_<@l*mVZWZZtX!UKOyNP6!F(oD%_s(FIHz!i3VY8}4NVab+NmGb z$>|#LGQV^SlLZ%lroKrYqN_KBMxy&Y9l|B=f=*HxqD}D*P-L$vTu#}s@d&Uu(1nK9 zHgJAJ2nMlZt({TGK3j0oLhNSJRkNWgpnfF6a2=Eg4nmrfmX_wPERRZB&2P=-;pdm@ zx(q?#F#+625DUHsbG%2oBVgNFBXR8jUbis7BtZ}~j}+NBu;qtTHb z2Y9(pgs4yWkHjh3Yf)Hi)PkkP?CY2t^V69fTRwdDIqUuNl0WtD*Fg9$`Z~${yq8O| zUlECU8%8g8iTtQ1?RgZvRu!_|{LN(~jb$QK3xpa*7SS$M!ZusWW*0U-=Eagm<_jKg zM!@sFefz71|%1_=J{EG^JI;WJE!;JHv#1`tYIT zJdK($mg&BhiF!mB9rxeOr-8yWTW1s@RcpdHXbw;tB_n^ocLjVCO6@ew;U8>N_D_)W zh=1|QU@Kv6WkRRQr=@7p0z6u}Qy<7rgj4uRg;R$4e(U&XZYw7ZCo2x#1fa%vQCc(9 z2U~G=w(~10zmM#GQ_aeWAu4M@l`PPQ&N5CsWL^Em>ve%7Jatu(Z>V0Ujv@MwNAf=0 z38hDNJ%VhbcdxdR|Ela7fG6HAg!A3PV^^8it)^CYSNcMw8ds48u(bhX%WuInGJlPv z#hZnM|GQ*&cPKooNIEqY>mzE#o6pT5j#>~tf7@ecX(?U)2@O{n-o>cW--ayy&jyN( ztVlhxrQ0)YJ0f}U1_*w5szDqfKHqOqYMmCFjmdO5GE0AqT_|{GV<~bXaMI#Y~Y(}m{MfrZ)dT+e%JSw|5Hs#IWiV=}V@Idp3Fq`kQW(fk!=IH+44<@X{ z#mT{V@F)BSdcVeonmJQTB2Ag?g!I~v4WcU|Rx)mmxIGVHlXnY&KdOJkTJ;>h{~Fl1 zMyR!uKVPj?9JyWPQF(%{bOKGcOJaWg(qhc_t$!xERw`L?Jp`xMgo>ibqvBIU@wB%f zZM+WK%Dlp$)^EP|3#c)Nlq`!DKg(=h)m|}hO<*$+mwiP4bhVN0%;SGtY=2NYU?63h zIg??@-q*lziEtl>@1FXFm9^5JKRk7)Z|~@n{4s6o!?ng-{^WL7dqqb9AzVi6gvm@j zEYax9FJePMNNdil%PFF?xH_%VT9--Fidz+Su)A#LQ`Fc+SuTcIC^287a3@fe_NrsT zxGNHkA>+wACCtpqaa4-@VEyX(4%0#`^}7`CcV_+Tw+(@+KeB71Bb|2FM{(!Q!)>v# z!mHDNiJI-Ee6gMB^?~IQE=4dR_AZ(}vXmLJ1a(fgAzXWb{Az_h*|o)3Ke6K$qoMS$ z4Af|$ih<7!KL3Uxfg{T}PEyINeI7@aDUHW#)^i4>yKHEMRZlTsWk`Iq4!znjTg1a6 z0(%kZ!)v?O`5gLp{n^Xt>TMKVnAUflfpaE>11*U_fYP|N>9w>}`^n-AK?WZwJ{ zBbiZ7EY_^Ti`WNKbb-xElG+1|H$3n9TP3bNKNT7EH1qTuVyMVLtvls{cY-9?@^JDh zm`B4)71c+3j`=&1Vvo0?+&VCJ_3So1j%U*6j6+RusbUYAYoO^j-(1$^b>q*)0z2@y z9S9{q*Svz~_!)&JcP{vEn?^4w)oq&&lk8l2-iQe2*|{2I=|D@FX}$1*Z#B0Bw%P^V zi(z8mi3!+nmMGv!X7UJR273|)$kpIe0L=k_LJ(MbWVi+e@Pph^1BgGhCxH}G5)uNS z(7_Gu;yj1chUmn~y-)`hYPKD@B^290(^O-zT0+jx?(F_Y?>7Za`y}hvK1Y*S5tBC) zFQR_j)UQoU$ELo{02A1?D9w1ig|Yten%8M03m7KKwl0~|1my=AG!k;=M8~?)8uUKQ zva-hbR|hw-w3UP$hM0Yc$cF~aw)b zNO`?=&^7*thAj!1#pcz~1^I3%lR1asGe zy|a)>Im6m+Z>$(YqlYNgs}WeVj%hs;ssd&v>zFh_wju7sRQ&fEMgzDH*|q=6aIx#q zE{WGQb^SjD85SvtFHjol)F^P+GCMfWhOK^zx$C<1rYmx(L_bJIV9y61^o+!?d;2NX zm3`Z(oWAy->F1P}H}ZSe=VN3;*M^h6XGfRn@>=tVEQ(osv8PLV<;JIpFwX2lS)^cq z6}tMg5nwU|okq%M`~US%+`6|PQ)m+%mym)};v-6GpAi&ge4bwqy@Dbm2k;>U2~-sS zoYR;cV7#2Q{Bg&60#9}#oGi>MA`4OwwsP&;Xn6OcVRKD{x!_iyjaX(8r_GBAY!?3Ez|rdL}6QGnC4R*>nljY3DuvU|lYT6zh%z0?T3=Y9(H@f!>gb zlBbZkutgCCG-k|bfR;|136%DXoAqbstAD&OXpTX~4U6{m+GygLjQtNn8UMfnJ-etf z3NdvmyZ)vZCF5H#JHzY~r`Js#pE|l>0>-f+n2UyCZtoK~4J*hSmzJtF6=jSTu(d8x zC?693&TQ>v!tbp+!0rxg4fntJAN~T1igG`i9nz(!^9&JDg##wkAT`G1mH4ljrYPj- z^gQO<7A=-}7fvTHh)&Rh-IlN`<3F*~4Mq@^q(}jqO)j zd4+Z4>_(u$OL((jcAGF4g?5^mp11HV2ZpaFO&#X#M|4RaTCdyH`UO)_BJIsu1I z4uI2Bp+8tY&&%#8fPC%BMP3W+#y|q;EwOjtw*hupwXk;|ZdD-L{5d(h{11R0pNljD zN@!yN9B-wzD*euXpjTEfh<{xx0+{^Awi)E>E(3$wJTjPQ33M}{i-E|AKO?CB#I(0x zz`~XHQ~)I52*ku7DV^(ZcA*jCqBW(W5^FH`bWe7D*)#YqM~0PXP}4kNQ*8u|D&MrE zi?&i&w21eb4NSv>8=ml{vbpe%aM$mevN2PpB=2bc%AA&RgCsC@Z_ruM^P}W5wV(Au_96Hdl3kv3sCHIj8J73XzFdKW z()@Q551{-xo;qMz&F%7+77G^1knFU{Z@$107_ zjn)Uh=`>*9RBGFAQj5r&ZO{X19sLm}nJ0NLQNNqlr=h(8|1E5oM20Mua$}gBX}iew zXPp?vPOR&@PZXHdSw<|DK5{G#sS|gjy?GF4M|RJOkaFT7^>ZcNYZq|?LH>(uq6dn( z*DRZF?T!@BztV5Ypa$)F9wFZA2rJLuut2{Yrk?7ai(&1Qohn%A6ELih6$l{RjDtd58$65c?S;XO{HO zw1h5Q6}!5B-E|;+;?MCCm(PC?E>jXyz?qbm(}_=)eudjFM^DI$`B1RDgthDR`N&70 zpgJtRD+~$6-fa%S7zMvuM@H(lIC*REt>4*zvuL#vb+BlltrtZ^B~}X&lu!NWt>zZqXr}8mQ}%d~NIvJ~ zq0DeN3gRVK3aVHg9mZ^Mk7oPt5-EBc7}pI*#v2+)o27+hvx4j-CGjpNr_0hV6E(qn z_2AA6KlJ)>AG-ppX)Qahr8gEI(vrJO@TyxIQi10S~((qj39L3IbS2AMy%_4o1=Gz2)c^yC4?c&lXw%)fy9)y{T$ZjsL zO%1;25{vvaC$Fb#t-5gcl>b*%nz+aaA1y^j)s6vwjWStjt!XMM{oL$1PJHp)?iAxE zW5lm>vdu`dla=of&007hB>Q+ultC`Ut?OcHC9TK+M<<4NOKTN-6_ouamW zEB-E@rh8`bXZ_9)uLQ2_I#166p?MM8_mR3%bi1ooH0m$pVAk#}H5ksmH-NlsR`1rG zTV4A;&iKz&%r6t-pb(NS)0m(dIhKk(=Sz`a(0zLrQ|H{wcN;x_K47ok;`m#K0cK|8 zd%mK-GB#wtY+iW2mur;QenQ;UyVmfIqNm!9^-G@Ov1pVlU-c9Zb4cJJE2@J1GRoQW zU&3zGE(nx1J*Wo{FX;Kf6i=0&#-A)^d$L4#-@Plfvu|XWMU#tLY2$!z{a8&iIZ6$E zkQRV7-f)Tt4}OS$yVqEvpCI^LiCq-Dc?PXgcpZKTgKi-!d1pkfAH&xBNoBtr_+#hy2NEw^MBkb(UvK7aQs$Ljv zSL^?R_WlX%TW=(nc*0M9`J>c0w#S-dSK;V3H|>r&sYUsc;q01HcEY&oKgcczU8Rea zb&4FbkRD?MaW$iC@81S~)XZh<>GCh5KQZCMeDo!mf6HG62J~y-=@3ZgQ}q`wGl+;^ zRx~Tfh?zX*G{jkbL6#p0S2VjoF%k)Z5_q6s5?oRYVE}O_h9~LKNu<$Hm!INq>c=al z_18qhMXKI2l(2Gc(~Z}f!s+f{t#Jd#x{(T~@`ij#lzg=OMoJs$cE4hwgjOtBgdcdWc^BrDC9M96urt zQ4R#nH8ON7ksiTQX3F>A^Hk>((YtZn$`la=%Nk2Bv#H+drB+4vem>$in2p;+!tsY* z)5`hhrQ>h9J=rfrb8jQ)?p{cgyAfku4F0cs2j0j@$d6!AKqo8)P$7{0q&x!eS8%I% z%#7X0bL9*oN;kp<}6}21EW(~PPZL1i9Q_-KyMU?ygd)(1K|}-&R8Rp1Ub#Wp8lN~9 z8Al2OfU*O&iukVpWI0Fz3iK}gAcG+OV(+b#z;GouMDQdXvh5uS0iwe59)_n!_|_-a z{=d>IY8a7hS>WbG7_`unf=qh}b;^&yar|P408OPDYS!o=z_;e+)YiB1$B6Od$?vuL)&(ECq3*feTXFyn-Z_51^Q`2_h#_xZ`dAg zhC5sB({~E~EmYkir)B!_qwkT35vb6Zw9-nch)>nAljgpH_c%7ol~|rZaz0|_uFGi8 zJjNE5aRNMJ97RgCmk|{4nbku^5ec`3Sw%ajS+wuQUAIJZhx!@5{s%eL7(UWvC>WJK zsv7Tul{d?HlEvuMsETKa*20vYJbQ|b+XfO+py%T>qzK72Dt`)q!yr7!C>D_&Uf<4B zceXz#go`Kjhe#gz)i1N>HP5-SWp**PXbT0L82861w4Qlzv7oC9hKI4Wa)5;I%AmRE zviaSK!V5yTzq=Y40(&vchyiqTnUWa&Q=HvEg8;>spqjRM_m81`@eVE;`uosOV zAK+foLczV4b|jA52LQ3Re&oQKS*0fhwG4ztJ$WCTIE^m$Kn3Y|^ z+X1NFoXT%#4VyUf;nq@aamaTDMV-{y0nx-_*qpKX^Y!TH+HAYoT^9rU!ismBy6#?+ ztaOvCq^A~1LkQOn2Gxa6C>`YAUld7pWSHy(=`rHvnk__?l@UD0d2`5dFsKGApS3KE zW}49Us8l$+;Ez8vji1tr)P%Y%$3!Zd2u5k@FX&Vf!o=y~js3Ybr%00v?p*NE%6m@> zqqYJ9?g~1rx1+M$%~mTSl_Ohe{qql-WDSL6(8*#vhGj_jMgNL07ZDXJZ=_mq^^Dib z`9b}ttl?x$Pk#!vv9nTuGDA@_-z&fHjaw~O=T5Bjf;Rg`u z*q?yYM##@*Tt6Hcz79X}1-d`IH zbJ=9aVo<-S_5`W2gIi4{^^(+8y$&27==4>+ZuvEqb)rKc^jQO%OBXCYFe<&C|J17e zbK+`y5hbxl;Dw@>La+;8mo_2q=VD#~F-F@M1i3HdyLmR>r+g!*$9En!^j+rfbFzt^ z%DhW-CIgvfSvfJ8Q`bd(YMcWULIxz+F|{4XO&^)QV=7XG5_ZjTKIK0YKveDMi12>7 zj5obQ8$XnsD<63C+UVDF<^+;=Ex~xh^-EKAof)6bIs11ReHH4~RdwZ{W347D+5?pR z?!7;iGh#O=GcGE!6?ZYzO$Z4se%8|JNcWQ#vuC%Se71Ltuf$L z!64qa1sGyLD;MQ5Z2jCkJ9_a+w$Aw032ykve~>TpRNe!w(1qXG_mda#;#+t9T$7$# z!=VbBrw(73WBX0vq;0{5V-DOI+mozfTl4+VwM6rE!Psl)kdvkKGkS_=++NR9VVe6n z=}YQ*o_Ld2Nl4PN_P_m>tZT2x=tMH6mk-7Vauw`6t%N$ydW*Y}WUwKw!|#GHsLq1B zD(PQa%j8BZ$h`Lu?GY;ZSSM#OX1Dcu-zV$?85@PS-BIQia??$Vo!gbgf|j9z@BQ5D zjB@o#HoeR>d`ahyuW(VXINi6HGE3mqLJMF;l0o#A-SD8N&n8CL^AM81#8x%sr0+vtLxkoBFO9Td~27Q=z-yl53)U8Q><=zMqxUx zzD)DV4QAR0S5&jFEf2bFYK_*79Ri!kul(`ECa-|lmRAAvfjvy8HpzHI-_0q1 z!%02rz7&^JUz01*i~W+Q7vO+viEwft%H3CoE=UfbHHi6GGym{9?^3yh#ZOJOX=F?% zO`*Xt;f~whUZhhBU$&w@^Sx5#wj(?7*BF<4Z-eFVUE*g-;^o+$W)?6Fo1dUd=O%a>Lkvf>PP^c;FC=%PZ}oK zYc5D~c$N}DO-y-$-<)&>Wf!Ov6Dv-bq)071KR&3T0>S2u6zLYYT5vTF{sE@Y@)P>( za!-L8MR<})s)T|-cXnCB&C(r)Y-bMzDz3Tiac|GTtCxG%%2|k%o+SHa% z@ts-nclEXX(5J7wX(zUQPR;xcH?hgW(C0ast_b7=$Cv{hj;QQt{0GjKFYk^m3TS9$ z@V=NKv*eifzOQv%gRK#IHh;<2WZq;Kkv_D-OQ6#TRp}{yN}062MLE`#UZ;>}G01j2 ztP?KlVG`e|kgA!~nw^A9%uaqgv6lKPbu=Z@vnSs7BrN2CnsLUpb0W=~1Q!qAg zL!|x(U3^qTB|S0=0|ZF{=#U=V_KConCJ7nX3?CbF^N~oN^pQwHkZ4hOHAMhtatq{ClzGvIMT1Iq0AzPLag`*#d%%sMxmGSPx)y@C4Vt zoP-8oJO$POw991?Xqo|Ff?_d?34$}j4UqwRATP+#Bi63!Rs}1&f=iqL0 z3jwA+N~LzdzXhgL=wn@=mI`>!K;a(j&9kjRQcz+k5{3KDb%f3B=t<5GIlAWBX1$Px zHwoJs$v=eZ+5G}8=t|RB9j!=LQc3ipU!;BZJ6nE5C7akiNSN|yo*k>d!A5@*j3A=ZJ%%YE6 z+ZnuhlQ=}v-LS|uQp{awS`*652oi&4^iR=gV{M%by_M4Dz8q$icYRw@{4%pqlj=4{ zh!fM@gzg~j0jUJwjSusAH3UhDG{4lVCSSMyPAAFH!YPXm5PT6NNST4^>&u+r^dBTD zrm@dGl5KUdqJe@sUUF<0`+1IK21;LAlWm;iEb-2Gyq*-J$fdb}lN_NUmO;z-kx65{ z>87Og_St_BcI*wm@Z4g@Z&mQY+FC8aPg$?6P0X-O8b80p?8FZj0bKI~9rx%RY*tF; zrwuehXs6;HXEZ(=ksH?sy=q6nDr2P;?f*f>3Ha)#Y6o={{&|zc{he!sA>E8*5|P|p z(~>zY7IfE{%@RF`7{6=~2_1RqOeg25Z|B^mB^=-QVYL)$cNpQKAm#A8ok7p{Ek>>P zO=6!*3tqAuM>GJ4d^L^EcZ&6zdhUl^#GN)Z|9eiUg$c2W#h__W#3$SRURoKw@n9*| zx+YfhZMxZEWnN)vLC`6){?o`Vc5@4t?13KVqFWdBs5uq}M$0m*MY4$xZ5orV7nb@f z)e;d&{!DgThXTM4Tb?;Ln-F%%K6QsHvRiHSxkq-Qmo@=k)=*Am=@0rpLR-Jw?wJ&3 zT}D636P&8$a@!43dR5`xf~bwuN*@ZFDFpYluG^EibuC`g zN_20Ij^~o22Jb8a@%o69x5!c_of0@=r&==)vudV$YPG&4SiVtD`bH=BVTLKMMA-GJ zf{>9n)IncH>dL9!_QUfRz1ro?O^w>CH>sGO zdl6)DpD0xXQFNsK)*2Mak=XToyW&(#WW6Djcy|!y4vkyC7#0yi(#cQ%Hh3gC6E$*}IYbND&q zL`O-&uI3T+l;MeEHt!P&i1^>G+vhG9WoE4}DR;8*M8BEFuxpw@nBtV&*W=-hpjg7Y zWWXisZsR9BVgLHP)R%iIt$1uG^BJb6_9WcJG6Mq-e6E{vqQTc@RydbI78I<6fm7NN z8PLE%2Le1RK*Jd*UH+#n0$+VhVx!vv>OVf9vx6^$PR8iMrWeH!@xEao5dRMXw2AZJdf)~8j!B?BjjlBF zKVnwwohuN*fm=>+AQ-fXc;vj;12Qv_V#vMUInolCoGpSCSme?Q8e!kzFddhKdBC&_)Sj@j2jQh$sJ{Wf7 z9xjGysk~JzKRa1rF0ePrX3L3*Be&D9tLR+I3XYBkbQ0!OEOi27Hb``Y6LyUtCA1B> zq8D3UnO3%kU1DfQC$zs#cWD&gPR+@%yxc3)G$_t_R#Do;4_VK)-U^v8sPXKswV2Wz zBXsQKKq1pA8S?rxsH^&Jh{GzwzPd*LTK7{Ly@6fonltx?&;d`e1g%dOFAd$_R;e=e;lK6Hq&p25#$qE5m4x zHoT>XA98k;ttUV6EHKr-C16NFqTuj2sN-40eS>O~fXu8_GEP zo=o&L{VMhPt$p}fi$W7yZaiBqQpzUp;y>9H18L5tLs8>H{!+y269chB$tncXY?iel z&SWbOe@ji%l36G5;WyioUJ-BTS=TOel~>)Xv&v(aJ9MmX-d))dx9y?yUAxavFF%W) zX1OPmU&0YHQCfy#@A;WyM#Gd9v9rI_I3EvxajksbN!q_sa`!dvwh0aeKAvkv^5I`RVsu|Zr=e3LsE zJymZ2s1S4& zwHaKA4HD6qqh^gVsK+fZrobf&uh4C$@z}PH0=nNuViVOT!Qk^oIC4xqjNv1b0V|=Z z?2>063VjNh@5xxHa?lsHBHlmsyHh+;s4}V8+dtJ}m9kpm)0w_8TtQEtR=+YSPx3*Q zrFO(14{vBAn+&%3F;>ANhKhxOZA3hkGLRr2;=6F##u3!!wOQmtYOpP$$anGZ`))c57tVYR-7BCNj;C+NRyx{H3W z`;GRQefdRz@(+ZUCVxBQ!F|4ti}juF{-?Ea8giw}p`~lM+2H11`TU@iz0UVD_y~xv zvh`l~4#3TGF+5bB3OIkf=FjXX+T=$P$Be`yK+}Mtq2v&r@4!kZh3D;OFykooN6^9S z1dMTrLE#nY5ikKBM~{sczX@dU9Q@xS>VHcI0`PJ~<$jbz1Nm$|dIw05gSr`*w@d_p z!3&5ZT>g(bNO6t?Y%kpqs7Zh_z^ws9MI|?&t;r)P7eF!rj*xhp0R@at9{rb8U>!Gz zK@j^M*sT~)L8#mxn5-^yQF8CWe1XF2OcmlX6#&eOMDw@mAQ*uGitXnF$XfuL-U0qY z0dv|d3&(I(phG0441-!MNwmIIS4nHu+ zZK}sunul#NY}TjqMp~MY$l-;N$ezcIYZY}Ym6TJvf;{G)FPBZ;@B z2u~vJBvL%{@HT$n*)22MTS?F>eantgj8rfNKm}-n7Yl|;zBRtSJGE` zyO*b}Ov5;5QTE0OFvNyw7g?-CFW_So5xw-{NchNxw=)&EX;Vx+>#>slo@T{NUC8WN zOvhKenZT*s28z3T@OP&=XBP8y-i{{hbX$?{=cZMI3#&THu!(>16`_LWen&9RWGhm+ z1Yy}18^XC48=--x>M@ZsC<#JS9fSynzC?uY3kr-ehuS`#%7`FYy7~wd85%-I1+!;} zAP%@^?{~QdJCA?&SkkPpjtDkx9oGyS19u%s7xK}Y4?>dC()%%QAW^rgg=FOs=jKNR zielaVVX%fb>|+P9n|LQ-vvgRjsO>aa=dZGf}dU(2HivZ>ncy;ac|BFb$HWVpllx^6sDY_}Y}iVl3ze z*Zcp39CHQtiG(p=M5C*=9dFz&y~WqlAa+Dp((;1_!ds?jMn8*q9|gk(U#C3o=8DJ> z#ezjDIh1E7hdl@7B&eoKQJNf)%~JCu`rBTVUxK39b+xUDNgCi18%+or0e*p_+K0OQ zkFV`l`x|?_7;nRZE3Ym7`DixaeO3Ni8m8JPmgdq&S?*?f@f==IXfEumCqL?c%(lAr zIfS%K^=}f23r0ZdLMSK?*o=f1!(W{-%Mjd)3RkS|q!)&-J;T+FH?C>JaP{OJk52Fl z55DA?|1u%Lw({|%vO*%o+;r0iVJKekwluR#rVwcWV~=My#G9fP*|!P6)Pcfu4cMO_ z+Ru?K@}XOBGLJdE2z&;_tE>RT!X!Npp=~SG<_-yc?45gJLzmSj@y6B!o;u@b( zDdS9UV)sRMN7YqTFNNo0S@;IX9@L=BWVng;>~Ho(TFx|_PkUw4#;KdViw|g-hG}z* zUK{ruK6!c}wreABnx}nf^}xbm1t%RpFN~2wR^~9m>{?X{S-*hArz^=b${a~{JKIaU zk%#vfl$SBRWYk+%f2*{=*6{`?I>KsH4Ln$WkKEy1`)HC>@H9p>$nLDq`rlGv2=EIx zK-Tz4%1xhK{Ud35pW`FHquHD_`i!0 z+#)Tob2`D$#Pd6pNpT?0t}S~wt6p{(Ka-YElk)#)`U5}dg6eOfUK)R7q8YM)!yHmOm7#jJ#clLkYbMUyk;_w~L^4#Zsa#LLYdRcB~ zip;UjZ@FaPq<=f~pKrvjVEa6vt6fBKK%#AE9k31*EWJ`TF~hW zsOJ0VN?x#l1Kk7<80a9D2r7&MtF!P3mOrQzyjI2g;Sbi@;~jN~iRyh0YX}}^49Ex~ zEdom^*wTR+(GAq7-yBP@F+rly#$+t9hHTQ9@ueU|=V5)QiVsxm7IZ_(v{+*jVVsLf zL8uk~T4MwWoP&;3Q1SdGADk>gR9D5&5ht%~ynjj%4^ZF*fD#`NbPL*?j(`P0xdwWJ z4cQhR0cBezPo06`!yZcd%({+Ns;sPKazXRBItV=T4jY2p%{1q~*68P&chn!(t$| z<-XQbd%tzcdLDinw%$;pL2L4#8vwf+rWBdZgaMmjAo=}^j+YkdYH4$ zn57D59ilk z7rH9z;IRr*Kw}t~2P@5_n<`!_v-@ubrBuycExCaMZ zfes7_LePh80Am}+v(Cu%HV_F$!*jFqT(Jx!Ga8MTH$LY;(7a7=VEo(WR&$~0c&9~+&l46AIODT3giLdA708E}lww>VqpKWPbL0-B3h({mdr+z%Y zj^xsvHCzD6`TeS2Wi2t+pZ$4pv>>c_%G7O{VX{r(4D>G6^%0y7F46= z44JVIEBeiLmu);whhB-cdzBim@N4oq$Gf$cmCVI9^l$G^S>CBO{^~Z=VuZ8RUfhyI zHJnQ??`9JIEeO$Ne&4KAchdE>N?x{ipr}wrkgBLaui=Grd7OH}&r!`O@kfSmR^}Gl)pl)Ru zPBl#aZuwwkt8GS_Cft%8OQcIo_Q8g`F~&GErPFn;mN@s2y;|`vU*dH@V)X#uuv^}z zj>L}vTHSe6uG3^^m3IGwknaQ_TX?QTT5n^DS6hgDp9dP(qTnB?0mms0LKB(5pnD*} zCUlWa*bI3Sq#?m*2zYeRFD?%O9Tk)xKveNRFs{K)tqKIY+c42>7!L@g(FfzZ6Fn%2 zFaVAEpO`oal;ss;r~)fF+Oj2tE;p56L{~C{zet6`06h}cnBC~GaF-eo+?rpych)vy`BZsl>LeymL&=niE7})IekE(NBoxcEP=*1|v%SS4eR&RKrBzoEp4f z%vg{BIKr;M%Ygm77LuhV!30t!$I}DLAkys`6EcbrKcBioa!N5KvWdCd6V^%KjZYWqf`U85B$LL$la~|a zPwvXgWEex+^OZ_5In8YzCVO-60nfDHdn~0G%jVu#yqMV(hZ(HbdCc~5G zG&Peoujr$K0xV!5(Oz`vS`CbKI$!9{4nP{CQYNMP?9zo&;#KTY*E$EnfjwFkwf>Jq zO3J+6`k1ejb>g8z$+IS?fjtoMedO|fdQ-d=()sf9{~%RQQ8GqeE}M>A4tO^{MVrwo z;740ycsXs-JYpj0e-L^@ifz+B%f!1&PbR-_4w`wA&(hKKHK5!CF@2-$>cpA1KBU+N zvPs%MdA(ZQM$7)u!9K4(_P#=-hiP|1uf`ds)wqa`G`sOp)HF)4>Ke-vE*(;E874FN z2H&(~wm&X5SCs-Kz&nqx7VXa+5s-!SdmMs$B}?}m5ivIaIR(sF$@&PQLZOUp^y3K} z@N3U*qLcJQNg}w!DR-}L`u_gZjZ|*{%Wq?xLG-Kuxmf1p=2m)T^(5-}6Zwr$$Db7C zJW2~%Rf@)i2eeI1B^Oq1y2o$ip7-@WmyG=w%(pZo2e)2>eCXZNbG9*H7$4(p#kTQ? z*PUN(!r*Cq-@`!nIJ=8ueSJL&FD1WzS+a5=ajIrpzU#trv5bJXV}~~6^xjS*tWPtprOi z-!k&w7x-N{=#=}iGM)gWDrcKz+L6sUr0s0C+SXrm|2|QA8-tgB-c!h<5qpB0pG`?- z9``c}tP8f!rci3g4PzWL?eWU*v@sEe9F{iI{d02Lv%5uhC;)QK%h$p2r45V>#1Ji6dSYpvKDZJn4 z+G2o!fVqDCA5Khot$LpcmZcA9PVmWK&HwKM;3N`gRSq$YIJ%b|sHxP^?dD)`f~0G7 z!uMIhJ6nMFsAD8zt^xG;3?j-biybUUEf3iSO_!iG)v+1UDjy_-Dggr-77g?)V3~IZ zVpI>oY%#h|$pl1=0eSYAgEc}Tep69)$*xI2I& z1_r9`gxugn5Ksav{BIjiNBjJu&XeTx)bZl%!qaG9Z)t7Gy^x(x#56Mn3@TFRpH{B1iD1FL6P zf88#!(4EmbXYU7bSDg5er$JbUt4UCM$Z#REAbqYt3-Cf=EXbLb;xlti)vKjg+|I*H zQy$%%A%bOW^YfcXgDqmZu0==#5C%P&(m%&(aj`3OvHEdBheh$cQ9NCjJ0xlA7QJu( z<|+N|GN-&*Y+nQ3l=_0#H+G4F3V(*;3xy~+&B)0lw&Y$cNYU9An< z9fRtT#XHdtm)bytNC~SILA}_LTfg{pznoFl{E;5#jZeo zvl#ca@BDc@F8V8nVwTGri(N0yDx!I!o{zX6NbCmSRi{aY7s_eTi};n@=N><~=q`T) z)ChCT1Pe8iA-&iVtn;jGYb{*P2FSQipZd6OH)&@KgZJXwGhKu=7YXFO9CcgA4&MZ8 zT2*IJx#x#4_4&lMj#JtuydR&FGn|MK$2nQLuD2=xw_uDFAr@B={o6|u^ z`hZrrz1q5-)Mde-iDOa5X^hkDA(C~(0eRBocCe#U!uL^A>atR@=2$=|QB14jQEc>i z&!f>^QRjZQt(XD>61`W}`78N-opoO#<#Hk<6J@%S4NKQib6GF(Sfm6+QyX%z6<7|Q ztP#`=mg$(6e+w4H60dbD3%{dR9Fi-~z4%kvQM$-QMzZS%>7!cOeNt zGY>cdO!6!1w43Z3DXdC}WqphEzLez2(tOxV)%zW)jsZ>fONb?MUpHSXx6Ga2<`ei9 z&l09h=TKgE#K!hz_T%$^f@befU;E@La~YUgz0`M4E)3t5A6nWViv7MltQCE+cTx$T zCJx zqEw05l&iNWoQ>^Gl@=FC;s@3H4-B2p5&w3hkHWuNHl;OZM!l(P?pw;neEuj2p8nYP z-j%dqxnUyD4Y!)>-1brN{Px|m+U1W&>O7~k^xvTNxC6dhaPn&{^Sp$>z!J_4Typjp zKYI6q7j~3M)v^%>H1X`|)d)m=V4`!UWyKSV0*zbb>kt%6|0kcJUjC~w#Kvbb!;@K* zajSkz*N*4KEmj4E5n`6Ch*KlA%i)LB$z9rYs-*MYa5MY=i1A}y`#7qctZ zw@1iJ-$3!byk#;05uIEo=>H&KE`qJ~A{#F+8+EM;1r-O%H4qsP;x@h$0rV&l5HuUv z9FPcIj(~C|0FDzq_pt#S4%S@ISO?}eJwz2sgpmbQEzpDm^kheuk#wS?p1?|s5hRF4 zfdG!99}8-S0U888Fwt4-!p{GVeS8od4Y8I@#K^iBl*OCC2q?^k^T5jRZNaB61KXiK zWD9%^Rtdt^3TsgB{{G=Ox_65Qst!X?1OMI~3UC1bw(o&jyviL38Zrbh0WJYqCqR&z zz;S}^dT@=t%q9dJXFv)lV+ZFBcsYhD6MhO%6a)<;A-p?u3{Oz`Xb<`0+mi4z)BX*;*iMRMuxHI!L z;!54@9Su1Rimu2>WLRrwLEp|Af37VR7v6;zmN$75xP!XW!Uw`@A;=A z{v;FA+wbc=*&exly2eyn`kI;SwxsFT<^zma4NMMoFVkf^yu66D{_wVA8D)_OqXbv4 zW$9Xmv6a|jNw&iIOUYnq7@oAS`J-Vqy)M?Y#tz3n%a7-kN)(d`$%!>vmY+q^-rvxT z>$W$)`0C`e9ITmG6DrgiqQ1LoP)=)Z;Gx0N$sPYFGC+$a;I-L!!7HB{m4`@_<3j`e zemmCro{Mk7q_S%7>7)4$w!QYceah18e|#e3cMj7-CW~`f$T$sn1m{(rUAq_gN92aA z6{b2KypIp7()G;$!pFB3qzUdJ?_%nC%L2Kd5k0K>6?o6Uxrb$MnK^KocNDYKN*L+p zqE}S=iZRLQ3!-?jOWJuR^L?7Ia&P2c&xY~*@!7}Mv{VvR?X>)TeOz4m?x=G*;xF-1 z4aw9GtdrC7l<50Ya;oQ$l4gzVh~NdcAyUd=gcc*iCsPVW_rZtq)#DXx!LKZs1!?kJ zQg_R^oZw`y7qm#9?e%i0MO1~Y;ZwgTl_4TIXLDFh7&s-ny>;RUxEl0aL&YC%uVsCW z9Fr24{9*S`UwMoxBPjE(vAk;a4`!U~`ug^_9igPd&n^cz<;hTU!wqEH5V>!Rv!S|N zIYpNe=|+~~vES^^y5zY_nd$)kDi@AE=?C38!^ANRHI5|&j50splNl2?hrlgbVx!qtbZ8w5!WbqRlZ8JuFzpDvb-&7JSVPv7TB4X&nbrQ#XdIY>rIy+ z7`NuamoV;l5-+e~Rj%g~&ZsD&bVWa}K4JgHpU+4~o$ok^zya!eTKl5s-|q4grO8q3 z2Lz{vQgk7X^fjsE10Rc3L@&;+wTx!z{&Df)z`A-q1TEuXGY!*!rWBRs)hr9k8SLzk z7M^EeP08RNrlaY7_^A}tvn}esYmh(2GP~KupmeAI9zyEg)AI|pm9?Yi*yfdcc4>p- znYPy#!Z1hoEM6@m;|22O-Bd2omc{xmePD-{5ttgN$ z+_pxl`S-xgn@CtMzKPr{=WA4$`RX7=46wkxa>ug#X?|%W zo|uyy6e4KU+cfG>fJ zydny0@gQLo^L#T1Ks6AbClK)h2sPkqfoU9kHzWj%=L~E~xMy}rMve3g*?LW4Ep!9l z2tVpMP#?2ReO5bq%D9^K=U_OPZSdgp7wvQ!G3HY04)gmXkc;}gHEcO)K z%4{Seiw*M-)zI|xlLy1Z`9DTAKM6}EPj~#laIVWq;{S|^G0Jq^C z1MOiwrW|h(7ZBcy1&)H9QvaSvHR1L_j&g7++ z$`NB5{VH)T#xSOImTS=IjcNUv?@!<+hI6Cyf|CkR!~IPb78Oy~(2j(M`6281SY5p; zKGK2s)x>8ZAq|<{WdB?Z%NH}4dBj?4Y7_d#Oj{yYO4bI{5WOLbvW#TwQClKfxy7Lp z{K4+R-1Gx3dJ9r8E004Ytfl>0>u9Ek)I)5d$>8r3$6pm$IPWga&F8*u-G&r*Icr7y zHL6Mw?U=^rNv(TNcxA|G;!m16S@qRYTWCBt(=vj_Jf-)f<1VfgSau? zi0_k>PL1pATk`XtX1oPmjt66Nn!>t>wYS{S0^Q1X0^$Mvy}D~{nItXK&_*3o8^Q$P z#MKwmZxVX!%@3(^BNKC97R*-pN%B4UP#(P?=ax%G1NUbBDkmWFXgo{5C3oy%TL-!P zUHew@Z_V7qaetA1Sv6U3lW89b9pc)=wOb=?7-_Wd$U;dos=Cud`v*OsjlKEtAK;uO zcAcAWN$lrkUt5;#_?22b$!Yyy2Hc5H>#9z*w%ns&-N?0=rIM~iLQ6sDKQUj=YU?zoXKj({;zT{hO_QyRuC}s*nh%3J)}<9AcJvmmUG- zP$}t@B^5bN3!;aFwJ=L~{#qGuaGkd{Evf?lA( zpP;8N5hQR1{08Q-=NzCR)nP?1B-jAr5SB1K2YOgwsuD#}BM`ABAbSBsrwQ0OLGlFv zHs*pT%KHegEzniQB(Cm=EI=y>#T-6{EnSf23?-b;1xumhM3(wjOeGHt5y( zr_0d(%&BiOIdbo(w1&N+T*=1;ePn;VFB1-}$eAF_X7^>R9X%$*VmA)-IQNNPzL#yOYFCj z4cscG`4#=v%T#83p8S3{R`v3SZ9Bw_bdmgDJ=M63jL%mOS0ZCRQ}+mApK-RKohfp? z`_bh%!>@`5Uoh2p@#}n+o^YsGd#Oc%KaP{pcI{qaf7yc67veO(bWvR7UDP||2@D_o zlf1d4Ls+wY`3PZ=7`H2-dhxa;-$7oJ*o2vRqmgtkE zO^Bp#`Z@On$;BoL7m4lby@+XJI#s{7_h=R_rmAvYz1V9*#B%vNYdrIMYCn4alU11% zZu@-7`iVkz`1ezcjsv=qo}--*U4!@<+azl{*A?%s!n*V9NXFQlq!Uk>8p>POUV4A7 zqB>?T`5iZ+JZ;hMwIjEb2p8j}7koKfDeJF4a~6&TyqLjR*-B4KOe8t)TGp4032QPn zD;~tTFfHrFz-MjotA^yo3Jl%T7Gy1ACGk2_FyE}s-$`p?Id*Py;cQ4&M>q&an6FiU z`Y@wT+1!Mf;L6n)LaE%@@)}4*HREw&-OFELkVdk(Wu{-0--nyc&!+mdFGeL^KU&Uk zS|0Y8=C0mQ4BJ%ud9E&u$3jxz_hmLWE9U-q&Yr6AtWCeG^H0@G2DWVHi6|GZwW4D3 z@;sigmUC@Y+r2!#-{m7)z>g7D}N+HV={>jZ?k*9-jBYN- zc&mOcNEr*PWO(AXu?W0c2q&;pQrd#D7m*P-m^OeXM2jO9KuB55e<~12HeoHmbfMw^ zOa`+MsQQ3yCIVdZ_s}{Ia2W>!iwGKx&MiX^II!}8L^CuahyI|4Jb{jY+#o6x1Y|kV zqJV%8b6Wz8RvMt3qx3Jnw;2S-2vP(x4btc!5Er}tCI~!_xIUP3U;qNV8t)d|@ok}? z+3o*|t5nJ*VAE-_@Vhg}Yv39LqZGd!;$tNO9?f4M8$Un*y)gqsfe9w!_HSD@5qg$` zBbEpREC8)I0K6l}z`q%RUUV_R4w=CEI}K6?{@IuSar4N%7of8E{~{8A2AWdE77E1Q zWT?9uc&hrd?6ij;%^K=5xe+5h{K#T2=Jp2hi((tG&S~jKt1%CDUx(Ja?9M$=De+SK z_?S-Cb2fN6S>@Wr%ZbAW@#NHBCBHc{tmurlP@Pv)n`N)ps*aGLDp}%2p=iK~OH`n{ zzQB8!l*H4uI=;50)GPR`<4JI^_Wnr%yVhfTV<$5IZlBTC_;+Pq(t46o=vzI{VIa6`GU{1C2Cf$bXs{!vG?#pTQ(cB4I+{X*V@A5SUe-=}G zlO?C*-Wya`kUsXTQ9EpU@paZNfvpu`LH#Anq6FYJy1w%w?Fdbmah=k=#yF3J)hiS4)Il1WBxQy6LFHZhOb^6v+vvs#j z+9Cp(%<{22^+a9(6Ayo?ax}|IddBTsTk4cxrNz6L9YxNxn*Tmrfrztk1@E+HZ+Nb_ z|H3_6_hgvIxpF#dYx=R9vV#Y-G?|hpgKnEY zzD;-X|Juj%@%u)*HwVwXH+H4Lq>ma|ttjx`^as50>h~CemiEaDN%_+Ii9W3|btO?e z&W5(Kzs&w{vD0?gabAX84w3!J?jsYi(lYU(>UZ)OO=7mzfN7$eu{VOsdsyJ>Vil_R zHKmjf)onmjj4Nv@iKx>9%ICB!2Sh?GU3bIV|$cgfoSca3bj7qH)WgMU6eEhO7i6L$u zJ`yEvJ6dq4Io9;3oG63Jq@3oLCJwZV8-)^?Qqmq1qGMCAY`bH%VG9@CIBNgMs`*po zy%`-MVZ@!%-_EO+x0;*{{}lzrjonHXoFi5KHY`(Te#U2d{MrKR#Y>#4WsM;Xmy~VX zc4jX8mx6A$T+uQeY(TiGmtP@Z-|+|Gd@>>`bTarxlos{?Q^CGUg)w!hmD+?c_J zrMMcTaRcgI8^A^g41r@o!q;g~aeZi@EmTwpC>$!63V@yg9uWEwRL#zez`qTN7GvHx zOCVhTZ%zT?3`mpFss^-waBT@a)Rw`#LyN}1#3L9%{{vbSafgC`c9&Y%C-zr@abwNx>du4!JrI_rmS;(0Lmg>E&>_EhmB+^1h(0gzFP(58V-s zC26Qu{Rnd(s4H~|^YH8Wi>D)EQVKg;E${6dRpzTR%Ve%jP?@r-OTwA{r;`iDm z$5-pYJ+`!t7emslfog`Xq(U*(KRU|mU-x;n{=89Y^1$3jiN35=x|r)wFB-SC%(Gs> zXKIsJ#VC&!tsh)|1a;T}86l1FxgbS}#ez+xyBqMw@It2?Q1pYHY-iHYElv-q#6!n7ibwC) zH4ctXK&|$q0nHBX!1t83c#FlWWE&3oLduh&IMbSrJy#h-tC4zD!F%Rl^FcsY)>ASnT}>BV;KM#S4zYZs@S+h?+d z_5L+lo#}~m;AU-;|D4%4KMXnRRBX}pYbK=Zw|v2n$~!Qy4s`qhhD?5^S&GiR zWr<}!-%)r&LU#>ZW+h(6HJGQHRjLGzm8Ef8`xk+<-$Sp&dup3c1uV(0RQ9IwXs0c5 zaxc~tj9#n$4amr|VR7V$OV*y9gcoz4JZn>0(*Ve9umw9^8O2cKg6lA6sy}u-6kXikiK@rPT z-b=HI-=!{jv#>4;Do5{)Bat03xK&X#YMJr!-5G;XANGRrea<*GTRVn@#jqFDJTN(* z`rMpXbc_q6S?lXT#|t?RB;X|_(5wL9WSc;1arY!(cWbo}s%8+pt#Yf11*Zf?3GcJE zow4^=z9^8a2%Kf0fXv?-6Id-KMjj4}wSvAr5zTjkfc>5(g3jf`UrzDeVDDor0M|`09C*NGR30kIDe;Ud7@&|hU}ijlf)x=LqKeC_P+wJJGe(lm z_&jo&vgd1`pf+3mho($eG=Iq-mvP$OL-ma){}b zTjjwM{zvbicT3>(rUVrw00YP?lm?5Z@L4v2J0Sf372l(3RsmvS;L0ST5%LAmQsC`_ z^vhb*2?cgq z`~aXO3j_`n@Jn2t0OWn>KW5|sS8y8r$Mnx10%EHeDhc}s1P`kBc0eZi*!xf*i3nl` zlo%lCV8Ee%EWtPpzPT@^g77uKsKe%twDHBg&xNT@vRS^R^yBe(+QwwUCx=! zjTPPuUu5TmW=nPnUIaSwMvbyO4=R?!x}#Z)3l#|#d+SAa_SGNPwh#4k{Pz!Tnd0GN zj=8W1M)QYUbnY6xJ-eLa<7rLa%2MVNTGe>RpB7u1zw&nez;cbvuXyMmxJh5D%h3Kq`uP3pwOa2*MZ)fgYFGc@PZX=I(ouI&L}o_kV5kNco}W@N1IH^ zD^1A(GAd;}8M;E5Iw|j2EN&J~$Kn zE$;$vpN?-dO&F^ezX=xox=!%(_ybL5z9+0!i(%bJDE!T>{5W}K`C%+i_9p$E^#s!} zY~-%lCcaV6I)IQjSvdR%Q~5xM^iffK{>lo9u3=^ENNeMDctq9C%4^)+Cmuz|p5K~q z?F$~Y^*6mIJ{1a3^+`}zJiC)Ce-f2uuKvsZt&V@**OgY-h9%>L=+~3rK)StKJt_7p zAZyyL^!lkdUNcYJP+OB|JSe#EHK=gGie4I`_U^1~Gmo<3=;-=MTc2{1TC(9BeS0sm zv~k_i>`9dU8WP82-G8^#KX!CjN~?OD{mkI}^B)IN&&0?$;dl%NVUjn3q7dFfveVPt zct2TOyY95i9IX0=NBQr`mSnj?Uo0BbiLzLPPR@SmUyYRcvsv!!Nfc*XZD^CjS>=Qy z?|f&up)B;K>N9@QT{QATd*;uNnESF}7nV8vHD35=$Zj3J|JR3il=mOPjl@s5)6>+jk zD)x;FGg_iWT2kfI_eW5aYP^vQ4H0}%WuaVA-tfwsi=N6?Bo?2oPpeJ6GPtDcIB}fg zfSWk1@_vx`vVJUsz#t?)IIvs_0t@NlREGen4ut=Rr~=s%jPfJ6$9rT$ME@JvFtEu6 z1cCwH3Bma%mP8{UULb*QIPzec2ipDmMl%~sK|tY)UuNTj;SU&ez}-+^qG$I1gQ{0R9Cp6fA$O`e^JD{Pnq@4Nv~|`I=0F-srC($bU>&zBl1#b^=|=NA|~tc}m0+ z77v+3D#cnR2X{G@-8)A|Ly$Cg78b_W3eAKaRlC|Qy~Vo2OcA=QjRfot{nJN=F;s?Z z(+L%V&K6qiunZqcyxmP8GSjZJo~fe2Og!ZrA@Dh`NM+gIil~SzPsP9*RV{k~joPA# zQ7JAz?i^vnBqH`J?Usx-69zh}~(z#gsIo&iAS60-G z(g_YGe#Am^$ADR18@2Y~;$`tRt)csH05fRg6wD?>8(Of|fan7A7pfTItbPv|CvAhM z$HBM%em=G>#8V^yMI#L2mT{ao05V~VKD=sxz9A6;xM@C#fy z(5WTHH4wB92Mxo(fSrAB3{4yo%Smg$)S6g-G~qh|dwwf%%j@mlaI3LWYMr2^Si6); zhE;D|NwCutGe|9c(A%~-9Fpedwldgx+ZC8Qw{u-ExHdod_q?9}F-`rm?>UV3@L%^) zz~Du6wO);;N^`TjYiY@&Zet?64t5BBdNJB##P`qrT+%c5^yJrqBxpiLqNeE_D4)?a zcd$5Gf7gX>bk{w_i90;$a;1QHJvD%B%ZjY=R7icvVZGJE)>Cr#Ca(+oA7qsMm`EHG zvS4EF{4*AhOX~GXBfq4d7S(`fcMD77ROOtUCYCNi1Q!=v5$H&KjI+jz?NMtogk4FIjacF7oZu9 z6ql+HI%IMPa7n{mXVx`azifQo4EwVXNXyuM_oR00=uF|`8U;h@02KO~i34+O`KgnP z1m{u-mP6~dzWSJKVu*en6|!z@HN3F-O}{Yn1}%KcWM;2dEpt{ZDc|C>xS+L8C#-LN zJAK@;E{)UGxo$&?JS|JpN@>cUs_))mqn`f@6)(6jsb=rhH z&`sF6o|bfBp5t_~>z#f*UO39b!ou{vdS33p;?e^O6O@!f>H}W+)rt!uG&U8hC z>4a)bxrCNQm!6&s<(PF(-al}+<;a)a)l*R=73YA%v%3*fkKb-@hfaP^&iiBIFm~^y>h<$$FdlzJ7|5(7^>g8d2jY5^nF)jq&~7#00abm_1>|Gc z{+DQS4ei{(gw;vOLV$F)Nfi!`GT2y0x}+8<8Cen z!sTyh5aLm&3__LaRj@}L>^jg{0iHMbT-9}cEXb_bR!lM65tGZ%un{B%!5bMPItPuO zlsS~LWYQ!#IK-b@>kr)|*_5vv)@R$hqk7A@*NrmBOy7PyAXKZLvS)W-j9k4p+A*@6 z?NuNuV0wk0bGF&|xir#GIcz8YGtJ+Ya`$XGl8~=+3+;A|$@8k2M#pR7&)@$0l5W*X zR#B!B>=$hxxvC*~6neBasiOtLvwJdF+4S)<#qfmw`VZPUCyyp3L_Di9qIgZ-G$+aV zA?8xPK$cv*9~5;?Cw!r8OI!6xd2?!7LWwGud&_>1KTX4G<>UEsw6!O?=-%rEv->~( z>}tfvG!C%dpq-y9a2!x9T;`P&Aq>6cF4Hm?a-6LE?pX#AH@g^2l!0+ z5udORPU2VY|Cyk*zP&2nS|F$Jz^+2kO;z-HQ?&bf+c+Yp%Mnwf!A4tKtYY+$;w8_<=G7h*{n;!N92n7Mc(cYBfy>&OLBFs$lv*di5HhbUTA+hQVx} z2Q5ZKa{$0g3V<*laB>2Dp!I(w?SHHTF2oZE+!w8ZsfS4d^rjSmF9D!FU>w5Q)_(}B zOW>NC2$YFfcoRslOMwFH9SN(z2=UNkubeNsBih1_kBhh%{vdpU4$1zKyp~zv5Ad$= zYakjtwse{f;TUalbgq2nSJVEeMn;;%++K?hB$FPtE6VnU#p$neFGZf zWW*^h>-)Gr@oOaS_G!H5ERN~J#QzNL&+EHVo$~IPxVpelo$atS= z$KPuD0t@>}N~y_wE0q;O{<}MB+QULd@k{cw-rA(G2cNRu18l8UF@uGHdDd)fGjrq< zw{DQhy5zVM{F}YcG@FiHypVGzE0?7mQ(j{n>gKzZ6A{NtPnIYb;CAFn4=~O~RRp{q zKgzRsvb{fQB==asHk?24f%`{Tql)uFN%yNBx)42~6YH|{$o_}{DWPF!Z_>o$`5*6| zOP=;SNpuMu;u9OW^^-W>-*za0727iKe~;Jj#(Jy&jOc_PVd`HUQP4;N?g4xH3EC5L zl1p_gDcSEDu=7Tpqx}OWaZmPg%XxFAL);B~Ddp+dc1Q!`|9(B-lI}2dUA8m1tJTwv z{5A8mA$?ASKBqSIA&)(Tg%B21?FmcR87nYSAHRct*$=NeCJDF0an)Bmsar;NVw$Ah z$Fh3<>#>mM*;#Q^?vLAW=Y)L=&&wFWTB$M9h==c`xPBt?pI3NdwXFm<2o8(lzU%{8 z7g=Exo~^C)Pix87n?tSFA3TkEy2$uC<`|erCj39)NVe6%EiI%Ka?0-+V~{e#GFxo13@Queji* zL1jY^x~ESOYemfl)cr305B&Nf9Yb#A(;}BtJhbQB2fo7m%Ca%!h9~fDCsunspV{@2 zKh00>6(_LO{t>VjRka}TN$9>qgGMYxT<<>jIB!jU?p^6kDpMn~KQ*`4o)!pmoTP6U z_=(qf--fsk$BnV|luF1lkI37jZzFk!*rpa9OFK-bV4WA3u=%*y$LYbENZMYMA|kb0 zezKxw_RC62k^q-vw~G*}o!xJ;fWqLBea*~*js9Yvj5|&psY`55w$X9&Fp>%3qk|la zsP>vj^%=VrHnlcQzL$XvPu4(U-Z`lloIuFD*udOdM{0&`V}5@W%Yt-Z7<){4HG zH0HmyPclQNN;kQHwM8l@1h=BOlz8m*S#Ny`6Kwn+T`?-nP)0k+ z%uJ7&_EojXQHy4gwtx9}QO{fQ5l_fjg0dUz;2@YBn}(`e97yMUCZNI|CD3KSkm^IR zdd^Xu5~TlwP%=wormNnEh=U=9$V98>^r7Gy2BN0Wv8}_-60G1z8}auCNgolhlu{CS zh52wFC@!QBy?kRsc9}5Ifhbo0(y-Ce4j`!WM<05DK*)#nX)?dzgI~`6$|}lpm-8TEGpyu&7B!=0Gf(`wZaICl zm%1+UF`Y}kXGQ*P`X}vBk{)DhgMVN3yBgx1sHwNlKC4?R$w+;hU@Ztef66QuGOX(V z;;X`VmulEkOx9IQxGPNB!PwIb~&6wq{L} zhF|5EO5?IkS&GvZdNd6UT=~^}Q{k6%bQ2-H2y@L>$-OzmUKMonyy;1<(sECHUSi;Za}E>)+t%`-$1(t=(N| zhAKhL8ta~zU#BZj7%I;VEvk3<`g$g%vBw(9^aabnr*ldz9PdOEgHNuX2DVkujf(sa z67$1Iy_eill|MWYuORSCGz(w;+8M8l{OgxN7w4qHJZrv0Q|uqyKVflN<+Q=*(yi*1 zC)XPkW>A`Whq|}y6-tFR<@YisG=|A7_*|l0(g`RU=`c0h#SG=kK1Wh1kJjSPwS2t# z+kMk1iHI@JH>_GJwh|vLX?hy#C0iW!TK79fI4RR7d;0~G` z&xQd`d{2TASbAXy^Z}|0_fx%x1p>-mN&r3Q$UQ9VARnVS0v zB@*`gbkV4jp>eRG{v^jcYLtny9_}tQ6Bh;wfzq zT9W@yp|KO#4rtXyuest)gZw0I&f6?He6<2nsYS<=k;%kWUD%lhe@H7-84WK zwpP5Now6aV_tclWKP83p)16YY9GT#thqQc+t3ZM=*@*e%+X7v`l+~aI$WuHh z`qWRJ?&#UJR!4a&Bfg(V`@;;kMnX&0mz7nb`VM zF7B^KnQc&=C1(FI?i!6xj+FUOYgdWGS{LV{@>>R37E@3DqA_Nf248*$b@zQuUJQrZ zM|XXGe<~?iGFnnNFHT$1{!AMZ10vlYxJJaE_}#AjVI*DA|E>yjGK_Dz(T+-bNCWT} zH38F&6EJv!o!{RU5Jiw1AV*w|Q-_TsvcPEhe{e=?;5q z=}tvDmXeT=Zt0Q|VF>|g>2B%H?{oP*GyKKQE)4VG-glhyI=+w<_go}6rTCLF67zj9 z4%q1Qfte@}Ekf4Cc92H_E7zU!NeoHPDi20vAjTD}Vh9ipeSuuv7nR9$5@>ut+UyG^ z&_Klf1^%L^{WT>Zi!oJS^EiNuE_J%l<#;ns>aFBu~F}o zZ%(#nJ91#?`!=%WhTd1$b5fydru=Yc{c8#2-l`f=z3+dQmJK*I_iqwuEni-0O;QPa z4a+_Dz1?Z*>YK2%YKpe5pCmEc#V7Y_AvzLu6xSU=zoH0(o6c5th{Rj7P4t;?Utt}T z|1wr2l*4L1uWF#5%8J7hw({$%GgPyDAHGXBscyYw)k7#ABTOhJR8c#^JV8L2@Q8i_ z36spma`tiNBK)yTE8Q|h;QtrSVE<(<+0!nacZ#$sscLTCyGeFHqL_BzwZ2YED^Av<*IgUqa@uMeW9Qgto*3tCoo8>eQ9uy1UCtBr z+BY`%Fz6C0@-jun)rxW3OBQc(P(?_}=~+1lHT%v!(h885Gl zfN}lLP3eS4KPeC&;z14Xmu97i0;I+{nV6?r#=wFrxSJy0877C~_e@ppxu7B0#t*eH$GoeqM_-Gc%ow zz7+hwCk|Y3pk{mWQ~=ZwWPduCl^sI~Ec^u53eYA901Qc=C>IRN4M8ba3>eT5yLS?W zpr{iI0{ti$SO7=EQO5uFqlVzlz5Sm;1aLun0WJCu@IHXo!Mq>v@wC9IGBAY*m-ERSXMST?=ZPu6Bp^zSX;h6_=_0RsET(leViJA%@Au?$GNY;B83)QTll8vK^{W{%VL7*)n*2?*AIMqdHOlo2|^k3P)`VA+OQLLo2w=(Lq>_GgQ1&w729FGla zK3+6?D!-T2>+0%ID}zIi?922ILKgS1t!FjgU4Qafv*OO@dALV5QH@ijWbPk*>kAU} zlHB;x<&XDkBS$TF{YYc3UMH6JjHGNJkvtV6mEsjrwWCL&ZK&pAOaj{*(%+K((&oXM z5U>Wl@2r&eEG3eix(-}}_gtPV$V7W9!>kt@4?LM%PyT~6zw@Lm}s2y!kw~=Ej7}NgGc&aXYxLp%@64eeX(j$ z{~ztETu4umfJKgdqu%&~{O8p7JGy=~=&Y$nXHJ*~vOK%}d>MhhC~-^OP6ywbBbt86 zou->JB%j3oi0ev(8&4gkBuSGiA$YiButie(V6GsA#ccnHU(i)3p0(%0!u~5|VOLPY z;Zv59YH9JCpLy}@Pk$GV2WrE*M)5-Dr$?Eiw21#85*Isjy@J%EV%9g4Kb0afA5_L&orS!b9u)&j|+K{_&alBxx zQCuWzrz4m?VrpxJS?l`ngu2R``r=5LWO?g0Y zC!*E5E&yr21NUPOOL~8-6l=?wHs(gopq~p>N;fGq<*Tc4zWh**-~D3H=}zxQ%gDzxw96z71%VqjClctH@I&6-Y8={hO5q2!ciKl z2`g&tTBU2zz1RI$EUrJP$NmR|!DEL_98|L0{sKF z8pW-;x;q%Ml_0eYL%xszpaX)>c6L4e8z4}iUi$b6lGDg68PHq`VMTxbg4*yoK1CEv zQnSkqWU~Wl9EfCMMs@4{(4@py5bR8&fPZd&uw&oQ_O`f;+}=wMox2yMt^UixvrVIU z-d1#jHz#@#RZNpr92FVz42|mZ`X4H@UZ{D{fIj%_!8DMXBl~kf?*PB1(Y=wz^cq=s zI>$yi`I`=d?s#Z7&11?CvCz4DYrNHr!m(3N59{6r+{cl>yTz?l6w_kCBKu;30;@c6 zRCGZ2ZB}c0Ncg(sJ zR8lcq{30v0z(5)A7?!wHQ-5b&syohT-O*gv2qVV8d{mbv-FVqA(s?rMR><7HIG~_G z2QAo}$*}Y?BOu~p2hQN<=l>pm=_&R~^u;j1SWYZhJVZ){^XC>ut)8cvb1Jb|(>QTF zN{4_^NQvvfiZ&^Jkd@*f z4hiX8`E%1vxGxnvzxQu^fEun2knR-83nq5ZOp3~_ezpE9f2zWcn@;mVVoNUJdCgIG zIXeu_YUSN$KTsm-=HgbMX2qZ7Y?aE$g?z0QHlWo;O0py4-2T?sUY5IutzO3|f6`h- zmP4$`u99_RS`XuAHAUVwT6X@Cz7n?~ul};*Ezf1O{u#L5|b`50x6^D)vI2#0rU9dli^x)PbrI z*aXEudH6Is@eQm;h!cAvIEkMF`Q-mp=%79Q-jJb-SoC=@~`e97mUmOR*+% zVfsw`;|u$ETAB6Oj(%oQs8a=PEViwY2IPls8atu$$rQn5kQBgmnvtjG&$f2MPuxFD z`0Ev2_ege3IEO|q(GeuptZX;>y>MXI6Ee1%ZF=k^D#U*^W!c;u`qQYHKHEXQFR3J4 zW%k+gZXxkKPyD^$86uxPqtmz_8V+*q$A`s5bMvF+1za|~+p1@ljx`nu9q+G5Nk->d zC@SX!G_FW{%~4Xa1az6%s~yKaO&X=k{4)Pu(R1UL*w8|79b27gc~TV_%hYolJN&1u zIoy5jH`oSn_Y+EWGqv7kf2&DqG@xbbi^D7m-iO^TOpOQ)sjXoT5%h^Xv$cIO$ z@q{b9A*ALM+C$|T^)+}aT>HE%PyfaTjb+m9Ph4@9j@3ck96>x?<+5$J8Beb70Vyxs2Mv~sj(Pi#>AH9%fA;=(yBmsP&F9 zRfuiY>;XsosM@}E^*f2$^bTQ}FuRztm0bGV{fSO7`*kdUa8- zZytOXE46{W*^03D^UKMP_@L_L$@J0CN3`tclU4pQjK$?9^O3u{|A z9{9M`$V$;2nPwTX;f@TrSO}^jjlV0nVI3Fjf3%|^! zojAN8k7eD`xuG0`zI?raD0CCjC#x!_>cI7xxsYir5b7NDIr0Y^Lx!4%4W2?V=KvCK zNV;3!Gs=+l9Q$P|>-5ni;$*E9GV)ML10PaWx10u#Q_aX&jgm(y_D%%1EhXrNPt-Sh z^GzZ;Sb#o6uv&t)Sk77?zxY3hj)8)!Q?bHJDs$~G!GyAbnu7trnxhPDl9tZ35h^Rob(;#5P2?wwoX6S!y8NEzSa z^QGGWJcbN%%QG@!li7cFe$`dW_U0c?>{17qEq9WdP3(iP4EFShOUb3tVe;_)9;DLk zoTfq-29}BFSIuuGWbMlJ9ehpmiAqc7L~~IRNa$C}t7Ii_XE<%i*S=z(2S_d$@~DDF z&W}_A+o)O_KFSHg^#(BEq$Mr#@vf79a& zdJ*{^X279wAQ~Z;13?Mt9}3dQ7LHdu(-pv)T{?B0dbUIzuJfb4VTwLWiX?GdQ>pB( zS{+MA)#>xIUXz%$X~wp(3Dx>(%L$nJaV_c~T^xcl`g32K22b+=zSDu7ts#>3LMvAZ z0*6ORrC2KO#IQIfHT~hgj~7@5+X-wpz;O4B=wub`0V9WF@aT5f#7CY}d?v z2u#`D{8TQyo)kI2r&QE=mT_O2VE*>w0aD5KTt4RYd4JmQtfQ0NMYNv+m-EZ0LsDH- zQiMm>7Z1MGgj480CNvV|2;(^AcdtM4eyQFz<6K%hHDij1V8D|YeF;}fUSBHxs$yy9 z{#ucXtYdH|LSHP)SGFvUlK~yV&3V4qH!fH0w&Orz#%f)sSRa5YVSg*#P2dhhWQ7nv zkkkHPPlDf|0HC}WySp0iz&J)9NfRka5-r|7m;fXtfikmmJXjpa%Yfnt+{jPDC#0jx zT;hZO?_i(eWC0BT1p>Akk2l~3=LInpLSnYeKp6n8VGQ6l;{mt(LkYNsu@_5_@=5^o z(acvL|H;oa0rba@tdgF&IPH?a$K|;d1N6n9EP7wtk|+cM#@nl?E3ukkQKUJA1}=mGzfd_t(oKxJ95{YE$+#n?c1 zvhu*O8g{3g;<%cz3Pt+v!ZDglaqRaXG9!9ww27||*B&A&H>cY*3@k0|_7#=$^?2=B!!Jp!!{)6yyS12JWrt0ogX8+PC>cp8a z`(onAbuP$$;Ov2OeA#|2Y4EN+`9AfaJ36G_B=_M|I3v#F0fqD`(j&k~letNt!|z$m zJ^Qx#A(Ae=&%g-2Fa1zN^RJn2F#)I&5(NapLsO_x>u^hrWXchtMMPX9sDYdV}h zg}{~XmsL~Z^j7Mz;N6W^myNF}HKoZ+KR1UO$Zi|Z$53YlO%npkMzmLz$@1{l)kS`( zM|IwOuPIUU$t8R2JIoijH!?Yfl zp&I6#`>_JO=c&N(CYs=4NI%Wt<-mC*?J`kopoG~%B*TFCpF724-4xqMasxRZnuNjM zBRX054O(KTXw|5R-GpVG9bx@#pVe1nhj=ZQn#_iWF_4QkB)v>a4018Y+ z@qBmx7kNAD;-bo>+vzK3&Re-~Q3((6(k&lX`4hpHQZ$WHG&Y^pb9o$7j@4xIf*=E% z=@*9+W6sJ0tM`IkS)ILO7P<{Jj3=&*cuV|fl(s!bE%J?oz~^^g++;w!6Da z22qT)N^xrBU!0tS!!NwPylr`hJ|M`H<#}Mt)5F|E;3>^(MPL!g*$H+8Q&ribA5-7- zQ*74E^Udz&eyi9T;MA;}`B)$6fu;H^woSfm=6BD*jobd6)}&?OHz+)bj|rHI~d4teoVei9dH_@hW>ZyR|}cqw$zcCEYk0D5Qb$ ze_ITU;a+H&M5_%kuCmw5_;Dp&?z9~_sNUP31%t-Ue2$fnujP-HA1`VWzJih>?v<~4 zFfYB~3)GLF#it-@(_nH5#^%BxYVIl*7$Dvt@gjOX*3+YjxAZ>44vTM)f8jw5vb~*c zk=Kh!z*&8<{WQW{24I9<2-O4Vv%o--Sw0J2k`kP`U_S`@F(fd*v;eNQYF?VE>+by8 ziLH(l=UH`3f9_P~*_8yLUaQ0t-Qk*p@t5ag1#=VxDr&dX^zvNxUu)Fe&DzkU1AhK6h7Zkeb zBVn^ixh#S2p0uY9WI&n48OMyICM_ZltBh16%c)72dEhmKsg~cai_8eJQfj#`Pquza z@nSfGp!T<#7?`IBM{_kEz4>n!Q@Id1&eJ;a-p?aY>17=>A9HhyAcYMSG3MUXo~ddS z2%T_ldCpWBnC=hhugREH_IWneTXHy zBw=bQh8nIb#qzK;4USFpV4v&~b&{oC@yCQ5kND`APbt7vxdA>L^CWRTTw^yO&G!*j zOOH3ZFpo&WvhWN^f<^FhWvx6O!#2`VDX#+di#>Jy15r)?bCtgH+m-DJEZvWG<2*_A zGP7LQGZ7s8%Ou-&WTO3lSpgDln{Rq!oIA#8f_{!|UL@1bYnP{o;*(-`1N!rzFE+)# z5zWH~xb&+Vw=>m>7xBEp*)j^W@$HZ-i$X|yzz%W=jUfc&1hhP{^q)W$RLM`a#(Q-% z^KoFH`S}rjR}yTbXKw#Imw0OapX`aHPfkR!9i-e#;O{Jy;wM1Rvc!0J!i_3H0&^PV z5oW+gqZLYGdV<=8VlqU+KA4aO>f-@JQa!{LslyhjS`k6K9`Ui$5aIQ%Bw8V) zxb%Pi^#({fFs{o$a5}*v3P`KLF9WPo=Lm4OsNj^?Bj>fc8rY%MJxQNIaK9-u>AXzU zJ(D+FTvI;R{!z??`w*jr*3Nx8{ebHoMf;DxS1aW)wU?sthHGghr*YT59^19CUPY1} zbZ*6J`$!!6g{v~)ww zujoSGgzgw|OtkD9h*pXOJUsjd3Ed;kOZ)VL!Okjo$$>0Jx2xAXB4P2nr#n`Q{Oly| zh%dk3T1~2|iMwr{npKFXbYVxPz5Bj}6MgB%5bqA^l!2EsYcbXPuf=GjvhP@bI5`{z z4RYKhcj9@&06sj*XnU4!WWt|&dnnqw`?+ut_NI6~VKHS3fvb)*7UH2?3wDxx%m^bF zd5ZfxZB(?QVch_+2(gUIuYQ=RWAkdrwMIUym0~{$mKOT1Nzp{326;@xV+~KEsMnA& z?A&X*i{V85E! z#B^ksW3mv}AX|szbm-lSayT-c1XR04VczPzK57!LzNv(68Lzwrhg5JrY$on{oA7NT zd#g8_h6%ah??MJ*+@=h=9^sIX7=)NZ2~F1BV?Tx}#n@D~WP~5-uTC0gwFHfm{^Xc8 zObvFnjI1Aa(pIj=<19F!1+*xWmY$E zReMuDLoUp!-HiCvl-S=hqi)a4Sb696w~{T|a^Znr_XjSx9+?V5e1rq(O;s2x3BRPM zG_-=6g6_ANlz2Oe92RQtRz2jzFyTj(Fq7&}k^yf@0Z8 z9if8I%Ikv*%Kao>EtRh%nXOzok*!)Lf9sdU@p;@4FRan7>#sy9}`e+-FzFrz5T;(A9XYV;KR#9v4YtNFC{{T%yP5kq%PVHt) z5*-DZmrN#{f0QEisuK@0mgLjgI|LCwpggV8R_(CfOR_0if(LO877 zr3rF@+9oD$u$smkSiZ15^vpUQ{XdAAg?(LX=;eZ%9qj;a*Gf$3xnOl}Zw6`pAkG67 z(Nq3|?LRRYM{A@UfCrHSmXs#9D1i5$n0V^nM6@B>AO!0WIxG)%u^>GC8n`RBNp}Iu z4d{e{Z`2&{J#mT;G*R|r0v`4tA8&K!3Q&Nn9Gt<$z+|}#AR<@80C`joPJO&!jeSYd zr*_dA)D*ym|HQBZFQKK=>nCPQHxR=>6c%l&kh-X9RY&gl4vgp5w3AQ1ae<~1W)U~i zPoG;|AUpW>Cn-#Y^j{OVUEOZl7+=q_<4s~(v&NrWOTG9#F$v`6oy!ltaVoRKYj=KM zxGFduDXjz)XtG`NKQQIO7uNE63phmR>Nz}vuy<;@&0XjtMRP~#BiqD(Jq+7n#5dg2q2|~? z-1-y#yf@)~Ue$Lc(9FJre<@0(yiWEwEkd>Q{Y=gZOvN=<#x=1Sn*=*hm*(&Sv7Lgi zYjxPaWcXg8XelU4jdGqpi=I)Q_^jYNzuzf0HVV|nOvFZ(>GT_?NVL;)uZBtX_0*RQ zc?kl{AGiZv$yw~M5l#wx@FG?cC+xw~GGT^TGP(-ITH_wuO$v zWiJn4UXA)BLeECNw~A{cid)hBlTiFjKZO@Mc;g}RrJ@QG`X%zTa5nUpr_co9EGBjptTzbo zM2+SKT=*urENn!X*tQa+llI}#+R1Z<3^G3AWw##H`Jz%#z>GCa09)NZAUs(G0uqKK z(Lm5@6e?v2OF+ zq*z(JwsRsM?Q}TFM8mOheha5kty6drj!NVe`0;{-_DrD}-DW%!1+3q&;95m5R3<7z z;*G?S=(b$*VtcNf@&i$BhrD-5@4w7= z8aYsGcB9?&$ti0)CD{?`L3v9U2Xru6+*0QRnJD`pch5glCR&Bb&Nw@!J!0Lb;_?Ps zdb1V~9by7Wn@m~PqfkQKMNre5mQoVrKlT8WIY*pygHZpODM(al!3)>1Gs$GAl}7x#PVvxOYIpwo@0nCf>XKaQN;$CAgvk4mkhAxE%BB~Cq?NeDNvBl`+O|1Z@s^xA4!SIy zk*GDYCX0KIZt-U5?HV(_X3ZIAL?lQ%5%}0`1$+~=sS0TK)3Y>8_MwB>^%)zS=&gZ4 z&&Ek-EEiWEL&Zx*HW?)99<;NdQ_+W4Y~$zGj}%UqqY|Pw?e480(gGy4zWMnkhxYr3 zgXdV3T)Rq`#MX_R)V}UJ`Dh#5JR`CWqj~pGn}bf z!nE&)gicHL63$P(`}Y=;qAGrr1>}-RgXnScsv=(fynWZSb;bn(6ZHyJRz|k8)-S`i z%#xXzO5vTi+DZa2A`$Dz{A)aNu{Ug`4A+_Rg|e>{1$^?6=r(uHEaOCUxd(>aT`26t zhv-{Vlky~|XRb7nJ?Nf_;2sMR9xU`K*xeEw_hX|taRe~j^ z2K?=PjaNihjl*8n?=!c&|D>^2?I*>hYwSL-^tBP$P_a((eL2in)`%ZK3Hydvfr^bf zP3d=46~S=mW|>r5ytz>LvK|#ufoXW$22WV<$EaQFX!u} z;)xo#@nyyOo+)}M*BzfXk*(lRzDMI1?HjL8u4+15) z_)V7^Akc*vAop{>1W*P*-2rGXk*9+Zgt-yrm*Ot6-%DWAl&Gq7-LLVWwmNJ|2=;vYeGTza@ z_GlX#UT_zb(ZfjTUjH!Yzfl#s7}i^x`?jEI6aTr_6yjHV$#@pRB2Tb@1>cw70==N?=5 zI!KLX!)3m4|Jmblz};8yz~rg;a#KJvl_@WHGD+iE6Mu)*nmmLY{1h4r7PJn(yUF8A#+_EXY>rr~Q23iye+%IQ z>|U(I+kLN_FPUZvttVkcu>@%$v9bRe$?j`S`ZJyL?5uUwKXfI6>85=)`lViqyX4%G ziipYLH{wqtWQ;qDbq8{%tyat{b^g53)G74u66qZaz7{tRYc*JojbCmJhqjjIAEAxt zu!U2e?CUj+6Bry^eB%GM*ZZ<|G6{p>XX*Th*OS%n1Df}ZYv*StNNrnE^!3|n)K3vu8BID4NDy|5YdE5kY;SJ| z;Zi=iI5U;<5E1QHKsiU!pNj*1gH(u!X;ZC;M{QaUs#mNh!rxz=c^t}V&w~7EMf_?u71%hLUfbt~h1Gwc$AVRQ3 z1`Ikh8f`I@S`6c9^YA^BmsNBPKeA^x8&c*sx!F*dd;WvK1e)1J^q5NeQ*)FL&;MrL zw8!vY_YxME5flDg{4O_9xi%z!H`~-5e;Q8d>vd$RoW>z=bs?rynHrD3ppd^H6;L+U zzIi_VB}5ZNAEqj9Kn?rlA$kH5GTIsq+DT(Olk2KX;;0$INt)qj*y%?{Mnx6d^ymA9 z8P7NvLI`K0d53SlW(vOd7JX+ysBlLnIpvStx0&COZk{oBjNDvvmO1S8oO|)rN1Svu z>39uetspV6;`O83{3@1{hT=n^dzt3AWo`0ppHv4A;(h|^?dQXB|11{7e^z?{P6RjJ zj9DVgLAQdFNt=VY>E>f_4EF}sgKw>qtHf|?tCPkkLoGU|>Ff}z?2R<89tGqEIlkDi zp5L0UsYNFRxjN!1PE6Kk|KNdnrTm*?&8`3jPY;4+6ob138>i=b$OXwZRdbbso#Pz# zxdZ0dZmYxVME@LC0|9yda=hF)f)B0;cT>D+7kvLl{iR*`NH;q|kP%fTo~E>ZzF!MkI{bDX_?0{|`c#eGfBq7qsr|sE_({zk14~amte*kCrX8 zINHbxQ`2@J-dK3S`Dt}_=^g>Az2KDs5eA!+CV%$B$$78CHO)dt+T(MHYz3~;NQYCI z0M9ccDO;+QG>?zw77Wc@JH)}S#CY^~FN`=JA_x=;T70amUxl4v8`-VXY;1QPsV^QR zqz(*yt;G;%f6;>=hYLqcYH$^zD+azEyBW^N`#4{fK{?iF*w!2a^CvSDX}5aIQ-om+ z1)rT{V|Of~ZOs>%v>n!ee)r$w`88FcV(CbYZpJTfnZcqOH^hAc|kfVTSh$;-yP zWPSiDRxqf97--e!mUvldRz5^rr1c*}k6eaL=TBdH#jq2Ba!i%}OVXdXEvmlQA~t-r zzfWan)jodPrBl7<;_g|U#Vp$r_;R2pIViR9N{GS|caJTar=|4~yMpzb`0;4?M)-0lB672)7=0=4+-^&Usks|y2+CC@qvrTTn=Lk0`l0U-|RE73@hBccS^*>FE zT38eqFB#P1urzrXm&|5wIFBN2ks@WY$*(8zq{`s)PK!!IE0xIi@c!Y#H~UJ0-v;|4 zOfU(7n|XE3oIOstrLrPT9IeJG*>Knef1p(X(|*tOb=*H!;RiOxCfSbXm@xTTiWkHo z4Q&A^PK37GPT!Pdr?P3`K61=mDWVC!=err7<7RC)rbqN{%UaU&-zy*}m8{$*F6T@~ z?nngF67;P zUJDvh;&M$@z*1a>PA%=+QFmI6l5-iyI^Iohk*;h~6{^&Iz95{kbvjnXc36dTG;^3Hb`@-KPjDhR?S@pj1sNR>Q5Mc{o z4e;7whS*$)?L6`Jc?r;Vfnhku9)b!M)nNdMIsx=xIDpmP=~4)cPEUtA_^fNt)iFP- z#x*n9olacPpTAe43uD*c=*^bD)iGk=f~FR)V^IyM5x?0a`F=yow8eDad{MEa-O3+F zG}jR`%onTni|k>LgfY$`uN~J6m(Ub-Q)2jW*eAVM6jm;VsUFTN)H-cx;Qp0Ir51;C zZRYtlR4Xi@V_U4uB8n#-&s2}pmC>UUebGDqP24m?!>4yiEKumcoKKgSTlQj0ncSFV zl>I6Y61N!OUL|!43EQ71jJ#dQ0z)upu&^1j-maXdvGFFQ zl}1z#vu@@^E!pRWa@NIp-XyalBN&@U1o zhK=Te92|E7#I;~$n@UIrK)it6#38ff5BI#6K)VPS@$&df!KPpv0$65}1TQ~Zdc}e~_=*o0ER)w_&D1B^SII za(TNC9QCtNj||sw&-ln$)?gxErQWk)a;0KnaN#ftL8^XZw~+1{v$Wig<~N*t9&BUF zCj0^WdFz7bAi&dBi%Ue{-0bQT8`Pg`xdH7WRA|R1J~XRbt(`tk&uz<~j*ODcVyJ_? z;67AGBZY*jRjW=7k2R*l7Jn+c3S?Ai)WOMH@Bf}ZrZlm=O16a-8gCwxb0iEZ-2e8u z!)|9`I#gC^J1$b7pP=qn*B7pHqRC=S=qjZv%L;zB12s;)X*CNv_henIB@MRmU%Y{R9&k1}K7e3kVLn}VUy*?uX9(~?uDCcsxDV0MGE ziS14Ivvc|u#jih_-t+;pW!;tz_IjWyh#)qD(vHk<*ujnCRGIPGnmzxe<$GvLe91ae z2dj45=07z&5uJ%Sw74b4(?_e=8K_oBg3-do?b^2=23VBmLoWQA6oyq^mVMfIs*)sd z5+RDXt%|v}+{E%74T;Y`u()UOnr2Eg(O9{&Rucaa;NeuU$uF_1Y8;%~NIa(F1<;~c zL=CUTU)%4+vLSAt9%JB%jflN+Ku)$JZ?ZyNhm&P4j5=9y8}+iSyIXJ!jB<>c+1G1l zrzJ7b=2Y%6+NFFAJ6QM?7VegXrxqAwKP~usTZHP`>(_^QyDQnpo6mzpf}Wqc$ z$DwZv4x6kd?L-XwaB-~;^B5AH*}szA`RE8^K{X(_?@IWfAcXcfmBU0;@6gLFyDeWA zH?*26#8Dx6O6at~)}XL}MuAhhoi*)r>N&)qBuD4xVrA~$$n7&qSd%dSW`4jJug&+? zW0;QmnZTj?z1cd7Uxd||O^d=uT9!gI`~F}=g5rSUmRmhpQLiF%(T-l!!-H)X4z({h zBgR%OV!kuR&=Xl~UD2_B&U_*tqo!$3aofm)S8%feP;6j|%=KEnvWrE#rwg{F&R6l@ zOYnX~pA8B-_ESI;;m&TxsZ0O%s!fc7H`o@s!w|2w0dZ z&~4Y$QjG3@oxn>_TU^&p-PgX_rkv=7TTNBbwN79S|AOVL`NUyQG{yLN+>#Y=3x2b~ z@D=fPQ>r`u+FN*8=eMzdNJ`sHL#-=%GGFXlQLr@-s{Svb@!q_(ZW6K)?V7fdOhOI6F;QQouCd|Mqql&+AA(0;DIT~G*RR* z*1LCNl}50e9cZSIM7BA{WK3wSi~LHECgz1h$re74iyDIb3ktAd0Z9?z!N#sEAUO>g zNvKyIVS;2W7nN0#svcpq9TBG;9ly9(@kJMay(cj3XF$aKv>|sHAki)Ee_R4JFs&(p zoJfLOh8hfT&N7g)VDuXGuvgkh^x2S-?=t$v@KT2$V(Wc&q8eUPcgJU(@(h7fvKPwj zJ}gV(VQL*y74Fv@+j5hZFON8k>=wiq(JIXa;VGFvHLGs9E48#UuykP0w!^m=nP>g^ zR|2ikn(S8wI63mGM5Lnw9QC>Ft=`;luPIv@Z&%?gRiocXJt)P9i!?P)9Hw9J$GjES z4}Sh^KBr0m3a{pKc}OpUu^iXb!>JIagW&aQArn6$sOC0~+B~-{8dnC3vo;d5QzkGY ztH1ozU%W5$ga5JhMT`8cU|Y#Tn!Z?bFFh7aUFl|(B0oV1WiI!;-CUg5Q@mnx?)?@| zx2bG#i=dNrWt|vH#Uw#s?kDoWG2dyt>~!gKyvupTW+DgPw*eE~!-Z##Y5wBx?7sBL z>uC+*iFx;lSZ5vJ_oW+7H3(&FEX^y>DsZkckqBOuTbOQI&2Fns7KaU{`mLRWlSVX2 zXzch-jyzY&EmUr~_S}LSOlhf3d4zwTa9XvaPqlknvh6k0Co$-AMWNgL`r3+#i#c)P zqODRup(T0QU|;vA#j_6~Ut|TfLWM1w+TWf+&E;Tp=Lc`hqMDn$ou)C;?4pD>EwKLh zu0U^R*tZtH3jVq4nWHDx%_vT*B`^2?_kNijAQ)IEUq3eJ>xfvx;%n(DMEOvPvNNJ{ z8(ZFZ+BRkeK<8Jj%rF2y>xwR4)+y#TCI%aq*wc2^L7 zjUc64h6at#!z)|KfVvEXz~(z`1Qd3Ri(Yp0QN;wV!Y7;$7r^(QsUv*{1`^=uTnYwY zDW0cTDHN(n2s6^bFaT>H{rwXHY8yj5!14gg%$PqI*#J+%efxxD`|lFWTpWf#9)d13BLW4D0Hh1swwa(K(`GT+M|W&_(xGMsHa22j-=jf zFNJ=*oqUeH1qPJ9&qJiLfy#Tl0Jn9ik}A!Pu4;hO8xM5M=j3Wlt!L36Cw$W=x*vZCc6TO+Z-Xq0g9!~uf>YR3`h4#V;vJPWNDkBw(t6#* zeia^|y7}Wqe^|8Q#&f&nV!P0Zxp-_ePyx%v0Cwx(ot)g%5FzK-`54FTsv!0^31%OM zG8qZ>J;QeH0W!{3tO-2)2VGc;0j{pxi{e>&oZ1s(9sK21^S>Ucq7CXlYmIZ7>f_A} z+b%r&85afF$%iCOoZe2eobWp&X2}!}oGO1e{_-^_e2b^%@39b^v0}S2S>1a3TG~OZ z=!**zw-m*AMS=poRKiJ(F>ap}6J7Ip1%9ck%TfNfD&99s-bTO3mdb@pXyp&AQ)Oh? zHA(cH```OKR}K87iQY-QlHPFiC=Y}v&+R=Aowg>bU$Fm966r}%rr|i_QWp~SK;m_C zFw-R9Fl4;vxc0%$w>lAyUY3azt*nuyv%EoIR~Xpw_0{ffVSB5{Dje|DBi7<)AWo)r zI%WG%{c4P-t5q-@<;!-wOOS7CJgiDlLYm`*I{K&~Esk_!9(!%xqMuw%(8bvARyPq| zZmpS9<8aS8U44I(m&QFij|}~=fnZ;3Y^_|Ua)&HTS30x9V?ot{u79CRco=W}yb!Ql8m2k84z`wP{j zNao)-+>&M~FY;65H4BmTjL|KIcxp zG5dacrxxe%w}+moA1aKws@!}de?dpueO?aum?kb4tVP#1OPy~DnO66>x7IbDk9Tm> zLK0*ZC__Y{2m1G@ZE4n>qyhyzQ$Hjgu@DPjnIE$S@RZ1)nsT(}p14m(R*lFT!J ze+X_xk7{}sM*1f;y z|C9Z58c@0flvugDPg8N_+P2<_sbcx0+YD5rc?yoRWs6Q)kzE$(dRkfk{l?!#1K|nj zW~_`8ZRHtYOebAA@Z=!Zv~Wk1V?JGGLLjC&>>s7jo%pphmSvr0!$tO2$-;l8@g%vn z)rFf@OiumvOv!`&b%rk+UmIKM@$dg2!ic@CVSPBod==Y-MVgts)IG661(O+@I-e7C z6yp>){${N}gpQ02OzQISDw8B4^<Rz41T?z8*##6h zg(mOb`di1p4t(i=m-E@G@pap_`RC0Mv`(bX{e4|;JUvT)-65_|7wJcD$Uh=(QsgAi zKKsLIgjOvz(+SZNUD}x=e@j(Yy)?wvHEx;WM6pUHKgm;V92OIjb&@TzRsS)WcUIwF zvGL;Gn}71g6~VzI*m_Y1F;f&(A}`GBlaOQfh*3E|Ay=RQ9|B{!ZOS=ED{6euyF^p| z0`@E`N=t+kDXJDY-++)ztNiXq!+9zPvedA^y{4_3rPtpF(7VL1#nh-3BV>wgRTXxk z(|R&wj?t8--%|@xnT$uw5>MXd*w3nJ@T?PWB%M@#{No*@60N4NRUeU){>%zF7-79# ziy((nxkINQ@!dW9$#Nvt_^xmp`49<|1hz$#xFVL^|LmQJe|L@P=f}Ig)Qa`MC?TT& z9*xhva|DrW?e`kbBJn70qCP@L781nztA3a^QK_Ck-e;wY5y^`=rhjj3oU8z$$sSIA zwn2B(;}wxt-79w#dYa2}Y^uUG&KLCPIn|dSFbw36q1=H^Js1FW3?X;g!H-W-?E6_y zyENvf#P$o|2znwIAfpvN!}0&4ZZWA1qn`eVD#r3Y>^38qQmvBxncMP_5?W+Y9Lb!5 zF)J6l!mjKN{i_MSN(s#~l)^y~*?CgmcatnkV>YOb16*eIH5yfU1Xo1k(heV{n=p$9 zGi{wJfi!Jb!(BmlN=s+D%4*zl>cIW0B7>|qR_hSq&uomm|0C%vgW77lE*uI)3WehC z?k>UI-Cc@nakoNCkzm1!yAx<3xRv5w+}(=1mhyb3?>Cc~rEYYSj2;>n$vXB0$8)%?)P5904BoDscC@SeDXpp^PR#W$=}Y^$iM0`fjju>#hJ9zUKDlLHg#meY<~R4{`#;vRG7P zZO6`lVYUQ75}~?>5Bb6x+LrDs{g=+O+z&NF&tsx zR5yb|z|6xXDWezraMa$X>=B}j%WTy{jwLo(QA>DaHY4Dl5y6$w#6qVFX<;(+e|r+* zWLnBVOF>uD+-A1dLFhNppypB{KfjAW+AP`o+={<|I=!ScvK~E9pR_d2x~SqVWI)Or zzC`shkkp&pNj&1no^#5vIptbslcE@PL=@d*v>z=5!NCG_5aE*IW$lH0@Ciq`yQnF- z!d3t2CAPbjC6yQ)rG>rKAnZfkoUCS?hn-Q?7N=0A>4MqKh;zk6jXd_d1v(DBKNtwZ z2g!f3z6`SH$He#icHYLqH2(b*!y4jlw4-2)O2qPQ63O@6^a{d}3>`$PK3T~|uUH;e3~8h2|+;J@zUuhNEPdx&=1XIkK;v66c`W-{VV)1HXMLa9sSQaJRJ_Ovay2y4T=f=L5;cdff+L( z&q4be0vx>sG&>?*k|?nt3Si>KNerlZfI%K0@Bz>r0HFiGSpD-50f>)AkTt-j0X)RB z|1w>GL@3~F|E$KRl4O4YKT-iMV6=l%No*+NFq)@Qv4DKW(J+HF!%w9ZC5RuOy+7OV z$8T>6RQA3#e+&q)86=_zPf|KH+8rur8t1n53jF<}!*9pAI(iqb7#TTzGv&)L zJQ<N0_esy14`6=VnUlc;@`$-iVr&RCs3Eil;1UkF$r9`wGDt63X% zYT3Jg)SuJsnp=MZl^hm{5mER0INg%9R@a&95xB&(E;d!z+!WPgpBBF{k`j)`as4b0 zK3qlk``Ugmb}CeqB0;Jh4?42X6Qp1vd`kR#pji4VQSe}nYkTB{Tx{Pxnas{n z_-GnjBW~$GNv$rB-^FULlNjiH{`AOWfHFVBA`vTr50t~%Y6xyfvGiQ67?qQIh}W1K z%4HhmVPUgff=kz-m9JzyNRwjS#WbGur*y{{B-vVWzPm7i*C1Gdhgwr{wsF1YR9ORe zLIZm<^RCx@(FGIbQ5b_z?jdp>mQ0#dUt=7{?B>rUYR*3udY56B?p6ulTH1_4|Xor6CD2i5oSdY>+)OE0~ z6L;S0vB~!u6z|MDqKGV0hDo`2`S(~+BsNt1&Xz7U>-xTsL=MVN8m>>tLx3T?8Nni_ zL(Rc=%BVi8V=}8pi=9J^CXpLGN*Rm+3Q@Da*etzdyc-pTdTimO1#Pp!OiX9j9hR(` zGq!ftTiytSPrtsW@;Wq9_RLw!8hC@PYu&{^YtuffLORd_kC$pjdqg2iPQb*J54>P` z*ijs%gQd1-f1x`I=5p<6NXgsHI)Vg$^`yIXET0SJEpJC?n=oj?IN_>5eo-(#xUH6A z5{nU$Gh(L~~9>6`QTQb z71F-0?z3*00RDGwI;3qQ5Flub5UT zAL_{xOd(b0A`*1*m}&IbP5c=s5V==o&bRT#!E60>#P%lMV;P!f3E(QKXg*Ky7`NPA zs)DG5#@Ji7>E|`^u-$RvlnjpY1u0<&BxcWmCn@H#%T8aq!(8TAj9CaNUd?TU^!GK5 zO~80FOTFL(I~8CdF%|99!&HIb=MR8R3w{P-V;VK+LzPW8aqXTbl-K-Llp-ko4AUJKUsy_TZkJ3uug zhuuG2>ZVS!6SZ>?zB79Gpt@#DEvQ{S+M1w12JPg+l(TZ}%pTp7F~c1wbEII`#`Uvi_b=#5T`KT6fdF~Q|6YWj=}RE=)t6JG3zwSP@~La z6mMslK9@p(=}2o(Qy%Nkm^jY?09Rp|2Lb^R5#bt*02Hzx1UO#Aa~(iapu@>dCF~hl*ZMzP?~43rAy=SiltRh7@G<)cKlR}1P|`vB)+0T z+*HZl2z~5}oFTomtpxLA+GE#TF*om9W3P(Q7ZOfUB^!lHLDj0(xSaar^MuEpQd{Ph zEP2t`jo7+dhnp28K5oAnqpR$FNG5ENEVu^TBf7c&{Q(N)*V3|;UNQQJr{;C(xz@Vu z#+^>lO76*;NLL;xY&|vcVv-ouCOI`!{@M@n;h-u%@H2;c9DiYFf6kM6F8<9#v&6eD z6J~mwPdPjMzPZGOuH_L6QnAcSbXHWpbiqSB0sP#y%babP-CM(1MsBC2nK4?#CN6@A zh>V@i19#fXQ>5FOXPnO(n3WFGalofH^=Obq^UJ5;SKOv6)dLp9d&~Af7 zhV^)fZ8u-N)!$8exJfMh#8x6TayIatQ{Bw7cpF#TLwDH2TgBh2zd4Y5R#XH-NmNi_RLN}t^OLubm;ysvVOqZy4d z)jV~!qdsfoR@!Ru8M0&9o=P0#eM=6+AlA`2fA4_`X3RJeu)5+eub~h9Fj{>cYS}ZS zRK2ay)y=1K+MnL$X_@6b<2;Efbx(Ki!8REp6gU^%pjKD{gxx&u70w@c=#eC`D;m{-DZ3aMxy%q+;FnUqqq0YcFJze=SwGt zX5m+>>~LR_giQjZVZ;yQAy^hLiy5$IH*&zN(4ouIuTVfMrU?g7F+k}@xn3Av_zDP+ z4gnIA0m0!v4fxGI;6vEq19CX9J_G{p1|Ww1AC6{lI$RhCQ2qy+VS3#U3|axF7{Fox z=;IO_PC!Ko5M=(@+5b^e@qkEX@qe-}O%yjcaL)gA8#VvE0M>fRYe|e>sDUK!@TmcO zdC@S|eb&FoY0Oz9PKc;R*@KKCNkZ-Okh1X#Badl!0p%X$*x<*R%2(CQOx5hDSKh%3 z+nnUXRZckLETR#zw)87r(7_~3u40K1iN*k4NXerFV>JP^gfsfa^;V?2J) zU*?(*d(G_{G!7Ql=aX*}KHc3?8qf2jX~`!fIZjX1U0geo3&*J8DK8>xf$9xm&RX=p^5l@!r{t~A<%`~ z_bHF{3rnfJx?rF{3{C7bUst-KK1yWZstSc62O1Ubqu1edgLjqMF%X`_eu(GyEcsBq z`yj)S@ga)z7aD4?yW#+*hRb~L?i!3hnOSFX!Qv8W0r_C(>o_9n4pgk0Ck+LoE0R4) z#IDG%nPzyphz0#TLJM(Z^8@<`R6|uz)aLA<8{c@RnlYI@pqklXOMZopNjZ4OO91S; z_LLtyJItuE$gJggG2cP`P0IHgFB%(zIukDt)a{iIGsmeN8D{p`-EJFb5GX{Q0e&<_ zC9WIPa&Jh}Ce1-)KHv&S*_wi{Y%v}zC)jyg(Z}pPCnj6Xz)~p3t>khXZE!WQ#6Chj z!qfcYnUX?JI==y@#A4Ayc|Ur2_k(}5`l(BqQrxMKEp0P+C3ajvcEqQcdETvlBB>sA z2SK`+0?#AA^`&tkmaxf7U53e}yerR6@_Tf#y(7pDMfCI26|x5Y^d1o`Z3UQ`ftLFz zKbJ?CD9J`KLfmZs1I46$q*pvbVd0%`xf)GvrS)ggmG&p?Ijy!hpQCj+c^^`*$Rj$h z1?}1)b0cTT0F(KIq_i4YmD{@rFxM zXRh9>eYy^Oet6{=3Gx~;;^4C&Qz)psBKTM zWgQ9L=B8zWnR1PDG$+_=&ByIsnP*}Fy z`ghFu64@pJ%|fFzsKjU^BKa8XW0C<8B62J1%K39H;hBz47{yw5ba`u(zKXjvdqen8 zHxtTCCFpj-L*LzXNh8LXOkwB#>sTAaoxVl;m9bm|PXN;Q$F9X=o&Mx;91?<#w(*;9 zhK}0;dIp*+o)iAd_&@;UPL5sG-(-h&ec6Xmtz^+-5jCy-2*2Ky{-o@Wi2ID!!M%%? zZ{*5L`bJ25n20kyO^Wg}7T+mMx8ay$`rQ(l{=AR-$ip`X?ggQUbsiV-_p!ISSwQ_10CW56WfW@>*9j6Aj$ic|f!Q^}Fdjpp?NvMyhmX~MF ziJisOTDn6Yx5jbxW9??nRVFsl(1uo(=#t^@#Dw+paTF&%*+_M7-EPeaV37KVTaS(5 zz3!Pr=>&!o^+&O6Y`JZ1Gtb-(^XFcdwWTW36Mpz-{zC>kv)(n^IZFZjZ;gmKiVKeg zy3~e(oSQ~iJ0O<>fx8%&dATe{9O4+OJ2c{9ui;nUr_W&=AFbhR;X>pwh@Fm?l{(B9 zD~Ad2PRwf+D-VyFUaLG$8}{yQ_3fhBCb*G8!q;t+b4>9{gkERdgGi^Y^pI=tx7ske@)Ph& z;~KFsn9OBH^zB1R)uAuCm2-7m1oz&`v6F2~NV*(#Y7pXG^?#rfn}J)n)|0=Q&dCgX zvfq_9SkpgiR@AqY30k+0FOreYgk-=wJblfU@pMGwE<) zCQ_2M2tT;fb5Sf5@`U-BsG4 z0kz(KE4@BKZ?yGhI^Yuog_8OHw{t0jXHy&XdE=VB!ki6BWVDQcQE(j(gT^)Tu}*ze zbX@u+R_yudxeNPF`_xF(n;L6c44JoUkCSA&LX1nc0&(=Q4;79$hAY443D}n8S{)mD zUfy#L4;~w6#>$zlFpodTRpn|gXoUnabKp0teH|P>&Ku-U{9#~M%}e|2xW!DU>E9*x z{@O5i)CL>7Q(maXHj2fxVjgS~PbO+x=(IpV@I|+N!D@ETtZAkct`c9|P9f|u!Lp}8kE0(`7Z!h%^{rPlpL_kPz{h6z8 zlP&s(ZMe3ubvMk%8miflPvbg8&bU4Pn0|VC!j74@8T}$@LJQLdPoIbyOc`6?JNX3y zk)?R@r1RI%rNwYk%It*4{nov#wPM3>PL*LV ztmUI(8^F`;n{39{{9Q3an}Ad{b2Z%O&s3Y)Cs;;2XYag$fw+1x{iRY7h2Br{6{QKH zI-jAQn_934S>F%pUOkeQ9)bAeuSHU*y>u}j`Sa-yk&jz*$Y;G2fZ1{8UYmtCAi#KBau)m@y z!KznMbI^sbFTxa&mBGl(FzUpuypZf6*AX7jPWQRls)lXb;-z+r2XuZNbbY_DlLG2_SGDAuCsL6#RItwhNn%Si2_l%_AvvUZ8CWw~ZR zyC0YBS7a(~O@3P9p7p7j&|%IDJS2@eM*~M8QAPA|jdHCzO^!U2^SORr8-4G6_ho8;Ga#9 zFzXJHG3;*X>P(i-w0B7=xG3<}JGe?<&C>Sto%q^M+x+L;-3Cs=#)~FL%xlYi z9^H4n&h{e1M7ue2p|8D%9=fGnYh6S&n+fzsYHXmQ9UkfL7YFXh)q(Eyv7kq>oHjk2 z@{MDgY8d6VQgMt5RCEyh#=T1i;rWk(+kSmc&dq2){glte2E@R4HeaKm-tfeAb`&GI zZk!7Pj~C%*xRBnN6u2g{shwAXbWzTEJ6D>hfYl8eQK2rIImCfgxO;c1uMXMkOf%eB z5$+Np=@a2uC9l z4dnX4pPEuFKO(cnbGS+j!%Dr1Bu=`e6wr)3Qe5=Dos^eLGoq4-04jiyjOqRb)IAEhoXvulwNcAu zocEHG{N5<5zDOE%Mdy>Y>*Y}fl3_{?P=v&bTI)6TNr6p z)k6Lf1j;r+K?>v9Oi9#An9JzfUNz>|I?}fhAkgq~=CcZZwD~E$nL8!?T|`0X@#Ca; z8h539M_S?POib`-laVowuXd-v-ZOHj~WGACZczmd*B(LGl7lZ*Qyl zWj*Omo+a1GXR_A&!!I%GP*w1Af|IB}0F$_+yOkkxFre*#2+i~Dadvm#Swq!b<+z)^ zl#do3mTmhVWNWt#x35sAmHA+d0GWcl{5j<=oy29uejdTw`)B&;_Ien7AQ1XsGezE< z|5Ti>GcdQr6HkbRX~dsOh{c1&S~8-(F6;u{-3?P7&{-d+ zC6TMX__<`8^|IxLnCkIPPbaAp;|tmKgm~JhL>i0WKuzb-a#!Zo1M#AaXa%8*^E(_4 zVekMK=|1s2z8Yg`SYa6HRP4isS>Ds8;taf)o(iEQ1|3H?gm)GKe8t>BUu|+BqTtG0 z@kd5(wtk7UE95|%yslfYN0~lux!uB+N(+BqeT$*7P@fv_b5*}C4yKq$;N?oGW$`uL zGdW?kyxLC7*$bz3`k#sGjs?syJY*^lcmkKau!r$e&~8mH%M6pTi|T>}($9i&=$I7Qnx^o58TO^1A=sy2t|6?D>@I zvIaYiVaB)!kq=|!kJE(|*=$>STA`NqHMTN=kkvC5#X+&_`F1O0XhUWL4BoHvikERj z>Fr>-5a7vWaLE6%FeS%oJZkU!tyqJt&n>f_3v@#UtP=|y@)`E>>=|OtiYoAj<4o%4 z*9p9QSNO49WMmu&q~C&We!tc-Iho4T?{vQ>eIH#B&s9)2nuEg|`5!22fvkf_6*6^G z=vM)2b3vzd#o$4tc)a-`y4^So&9J4$R9%6$XngTTAYJSAvC%v+@&(a_hBx_>r9@81 zJEx=s2_MR7C4^Eb0cBX+szw0$5Cm*U_RYue`s%ao4#*dO?F$JkCxE>E&4BZFZiiiO zI`?`%c&!XFo1 zIp1%+TJl$BPCi@E>UNiEYNk`55Hs{SzTGLc+!>owiKRKKgOh9fW@t|H3+;#2;s16C z+N?V@?sqq4+OrP3AXRCleCE|#_p_1lK`;E%7SSEbVy;*sJ+L>$U+nloJ-zS$er5~0 zzWH`06P=cG_3wAX*8Ud)XQE->pn13$J1_mpu!E5wk-=*evQJ1h*UM$Z#&gM{&h=eS z_FuvswO_XN?cP-A(q0aVM>Ge}*%c)@3lHQwziWs>3~<5>i$1UiQn0`kgDAcX=Q8=P zj{R_)(8>?*I1$y-v20Gs;{F3^9^?eg?t2cjGS)BdjP3>TG0usGl$5-h>2s}QxO&}q zTH@JC0onEV5424&2T<3pyo?=6{vr#0e@T1Dty%s|!FkuPH#Jen9TWrY!m-qaf$=4P>q0;~mi#oi5F5u3P5~|`bW(ixGDpRm=f53( zDN-eUG6s;73nS^KPV0gted1KmbhhbJ(aJCk-jqX$yibpulNnh>IAisV{{vyw_=w2m ztr*N~N0IVa!;=kj7k}8@uPq$w-#oMk+5|#6ri*s=>b}~bc3Fc;FNY~IYg3X2BnUb} zLdqWE`Ct@8Zm}QtsY#>7J_68D2%LPW%%6n0@WM9*zyEtvGA%edX9wzanlm?Kvo2u_ z#p2Lqsf5eCO>AvBgkZk)w8@}XP^DEL>oT&B*gG>m z^1ns0w6Gr`S2_}FSm5u6s=t{LeqY1kgVNf~s1xM?VYCU=LaO+ILficz@E~15&|K|3 z^dxZ>uEzH)+vVZM&GrrMU@|6Z8tRuBZVQ!=8(e{+ZCZkP3#oeUpY#nUxO9;K7`#_?BlrmF-TBt^fn+RK-fl`jAwC)2 zRTrk^>`)7Hq+K+5q%PFNcC9};n5_;IU@d2>)K#T|om`fz^!b>WNviF`I)Yv|K*@{Q zJV9byO8k9gGmq+Ncz=W%`vmT#x37#i_mUT7Yf6{7uu#M=gh03o>Ko|{%jQ!bQ8+R8OtVa#k1^>gJbR?fm!hVEv0lV z$XZdO;HTm_c&GH$gf)Mk=hjQKwS%ncML&_5tJ9h0Q*4p6jmE{7}Q5Z(R@uL5$9e|-e(xc|Vo|H@e^ zz~%zf%4EQm^Z&O{KpKGeFHRDuX@Qe{p$v=w&4v&BJ3{>5Q|SL+Ay5{6i>IyX+fO>w zn*zs8tSgmdS*N?4_*_UD{dU#hDV51&6GpF3mB4j{QROu#`bXbul*rc^Lp$?}|DQ|3 zzNfux1+vpJ$EyQ@bWAr>DIQ zZ4s{V+!-fFX@H^Vq{u{#Jf?~p_-;TVaDwGdEhFrwNmJ~$iErvjn#@qP-v@+xblgW> zZ^SNV<~F;eWy(+%$7_WU$H2S0DH%39ral*?k)~~Rc`;#oh@R_$G24_9blFk~J6uaI zS6#PohwOe5c(a{BH1XJx4?@vO`?O^5N}kuAo`Ur9p>RWzDaMG6@jg#Q&o1NO^6$ix z`vCmUxU3|(l+5K!G^K@@Fe*M-V~ht=3T3AGm%f_Ll=pbuMYY-I6N#U?>KSMUOi|kM zhN+IIC&l}W3t4bdjW}HWn&@ZasjVQ5OW1<57qdfszR)ArJIfcn=iNU$c!7`k&>+1N z>xHJG09u|((8sIYSBevXH?%2{`r5^eI4hf+$W0XzefDVVIbH!4m}sjfT%Lo^T}#7N zU;%TX1((^nMinfy<3RqeO^I%$;)knmyNpx5n}9rd6LPt=oNz33ly@_M|0GW_E&EqQ zc`quS)X7n1xw`S?F9qoDf-ZHKOcp{VG|r@282ph*mpm7(@?k<*n3$+6877;wmjRoMw4Y^Eu!l7W*dWYRV=vUD(yL`6$jI+ z@CHEtf$pr|aOV{@4W;H~Y|IW|HjO4k*7R?K-DsK(Oq@d?wS%O)Nx>r}SIB}CLH5(F zSq{I|cqsc{Nb6_#)}+sVDN(gr&@AIa0yITJt@9Sq7P>ri(5e?bru2TnXn~112@xGoD62$v^WqIE=yfo#Ut_JB#B0E ztAraX0Rx!v%(juaE|fhSb>f8kDQ~-N&(SE^b?WqnH9Ahsi;olH63^qYT4#<@SgWu; zj!!6o{B_8C#wCq#0zjUq9HkknGq&9C7_%KJ$H2Yb#E%w5uOXyPU41RjahO^;|L%-#bN8IU; z2*~|B=r(5eMj7SAd-XbJ>OOrl#ec7kK$@DcgOU)!+8n!6jCAMF_0Cz%v5Qh~hCOwl zbb6cVO~r(NNcl{;^5!W0wD9+V1=$Qp?LbC}jH5M;NsJ*&jc5Fne5)v@R!V|D-K>BQ3H**a-0+C2Y!x?LPe8}1eCNW%D;Kg2+4-$6OlvvGb{kwgc>)hI`+0dh)Kz1Om|y)=6^~-NR%i0sZ|(D041R?vN7wFjAPi z*8r;?KP@40EU>sovIg4^e7cPRBjJ}piU2}}Xf|C~0q{t#Vv z@=*4Xm@K_+ZOG;1J9v-dpZJ?7jQQyn_I;WsC%A}ZLa;U08lA3W*H!A8vfz(?{4`UF z%S+LCH>B|o~LS*iAsc;Haz#w%`N`HZptui8@Az;_9Y>NGnDr~(0H?-{x?x8 z8%R>Qulfn)xfxN2u(O@#=m)v-pP}rHbFQ@Th4QTR0J_x-_s1e z8MPYb`9^_2uv~k1jxCwH6lErnuVrAQg?dRzYKH3La8J)=20*D%GR6WjrJZmXS8faN zBJ)-Qf1v@h+-_sU>}Jt96Sm~R3F4Yol8RiddW34ZB_kHGgKqvJTO>R5#{`7i(j)`A z+1>WpT2~ipFCGSMIXA&4N@Lhr+@+q)aDyOra^O$t(TL*DlVLD5hw|j6&jpLWfz%O& zYf1(sv-*j!f)dN(DW2@~Os0@=(~49?`)~D7M?2`mQdtJ+E;qAvVz6CN_yNVz0Lpa9 zYXp=U2QMd=m2=>mM}6o0^fW7gvz9vfZgJUPMD1Z|ANOdwIRz=)mF_zz-_tqWa8@su zD?3}U0I-kG-@x?A-}?mcJ<=|7;LDaG&^`Cg&}}XdxOjRrG>}2P{p;u7&-$oHh-f72 zuMEbF$KLZD(^hE`dFfHyzM>v!;2((j*ErDE~3P;mVy@~5OlqSEx6qTFJ`fsLDK3=yZhlIASFR z)>_jrBIYcqRI3GwKJV>sW#gyx-y5Ui?B7M1DDF0N#VjVYBzr1^HjYEpvjjfj|4tG9 zka`#Ro!JxG`g!Ura$Evth={&sT*jE$the_xy&9OPFa6U>1JC1VyI;lq;C*e5=hhTt zflm5i`dmBO)XBGL%4Eq*^aE1{GML;G5n*vF{Lh;un*+|V!9?snfs4cRL$TandDHIA z&|n%+L2^X9hQ@8pUuiAxcy2RtzSi2(PF{zR41$aJY5B0IMOsMW9c$YCji80h@8p@~ zuAIkBpTsd+K>b^2m?5Hh17sx0Vt2L|Dkzbp95S*AjehlU%wZ~iu#wh z1B6E5AxKMq`u6}IB*vnI1t`#|m|hi7Rnjp5jNMn^%J10G-hc`bq-BqU3J`m?3&KS) zJ9MEq^)iT)qRCQjkzV6`aU@K)Y<(aWROKh0bAlKChag2qb~vid!uiK#axeS}F$uwg zuoo)CV)P|6P2fT#5AadRT{C!F2NtFHm%15&RtwVB6-+T~UgqEwuuNrOc!afO z#2=Ir;)8c+?b78kVX)_pIy9+{LieO^m-EUu|hkbLJu*5YI`nkIgmHS27zr~?6d_B z@9(sWfkuwBs=+`cDA%K{1uwGf4hxoBWWI8-X&kdw0*&2L44sXQD1u8XrR z>XnOB{PlvPR7)MjgyG8G7QEE+`X{FWq8N+N^m^CdIK~f(eRcdIG28GI%@#pq^e`$M ztT*{7Vi%s6feFq6sg-|1icE@SpP3g9vStrcOa~~?X!2F1kzZso(AP2|d#a`2(7#$Z z2HnSxgmW_-1@m<`$D@vAQ$BP`R_Tm1LiR|zWF9w@1+Y|-lsE(8FcqGCV6oY@n2#NM z!AYOE-=VOz{T%T)fx5mbfUi*S^ZMLSlr!y5z@L|>V;ZLnTjzekyOUFf>?>Iv5ow!h zR&R=83OIbd4Rd|z)9;ftn#yA=ulH6Ay>VkO_4@#(|E=fveVx7`fzUVqzk_~a$UlwM8!BNeY{*b`-}}&QpoD@IZP4K>HZ{~z z4W3@|yU>pe3#s^-<=W@5Cf((`?-pC~s`on;*-od2O$KnK$5b8j4wji1J9@1u1%z;3 z=8Fpd=zv3zrI{IB_22o}?vAX-RIk)l;&;>$=8~My6LtL(6i^rQtnxb4e;zT?xRi_R zuN>NYh2A8H&B7Hx*8>)%%wQCyREGQB>B}+d8_~MF)=U1Tu5{2Gc+#upa*$!IVny4X zK1?CW-uOlJI(elVzh+r^$Sj?l2W?qaw^?ab5zHdVA~7Zc*}1PZ;&X@x2B#n19LD+* zQoNVq6BzNr<)Y6<5v7!wZ*?3#%vISlVQMy~&y#pJT)EOvGRYkLO&ehV8H9+k4kPnx zUdqn@wrr+$R)?vWyXTWyi^j3$sjwg>HW`>{b%##NKiTVQb?dC)DyMHmAVqM_7&Wx{ zeFAN=T!@_YEwhd=u4jDaeGHt?%w7}T9N|TV0}rEPj|kty0S$^M4ORaP#t$NzAZwCa ze9+Kr)yrA|q>fD#s{X3sNULIf+`U|!MxH1=di4Pi|OY`=Jx3jcs;y!6oe)j5mcTqD6izKjItvPhi&UZPWDhb8a#)jD{S;t*|K2ky<5r)S92 z649kxqFS6{`rJ;viiv$ge~Q&BJ{wmH_J)N#v8VY!=ObtMP{;?_i?yh_w*z&qE}Ul3 z2CeS}H$f&TQM4?;{$#c~5|*rNLJPORda&CtjQ9^E-`@Bi=v^4^@F!DNPSy#+iXW4I z_G6lNvlJ^{X#ACLZ==tw1e+6mP2RHwWrd zgE1WQV?(}i{@pR0ss|rbLyik=KFDKH;xLSws`02q*T7dCVYYPG0)C1jZr}s_Qcn|> zQkfWj3Cs-@GU%e|;WhQPio)yA@|V>)e|SZ`WBOlDGvP1{-WXSO<-%>~rjYBR(8|Z$ z#gh={EQ#2Jm{44fRvGs_tM{9myIw$C49r*V@?^)cNw6V7$j)^_xB0h(F?@qh)qLFV z2gysmD+WO`Va70RxTbpHj?9uZYx?oxrMa8K{M1IQZ^g8CM)OP~^CEKs>jH)KK!L)( zH>SdS4dVO#_WyuQclnmhgJ)pI$%Mr7m-2^}$9~ta*Iy$_qKK$atyC!+&^*57X? z#IyfFqeTJ1CO62VUy2!nqm(-OWiE9I{%*;JzV&w8#!0-{r2xN1D|Ioebk&!{b$oS9 zUr4i+c2Pf3-q!hNV6T7r#HiLswf>Y!BPkJMuyBG{zZct#*N%efx1U^lLG0i9$xyZN z3}T-V z2{}Z1dYQ;=m#G>fJ0eK`3=iO}$7OtC4;Cr)w>3Yb6UT}jr0-~>Yw9i+6;JZweZR_PQzm-$9JV>vrKmYw`UJc7 zqoqTU5eSqhNJ~5^>Ay>9yfdCQ(V38AnChBi(3k8;LFw8e06`fN?*3pdp&Tvd08bw< z2&JFlU}qoy(c)i7UC`Lb+5sjRi zr$q=P9B{RFgh=s?d%kB+@lwF?M7J+fD8H|&tx>60QE8n!g`1Fqts_*3a++o(`t{xm z4QkA{mdAsQ;GW_v^ywQqaq2U6iONlDf%=Ne%#sFL;r=IqH^Vgf*sPy@&H6jDVIgQ+ zfESMN?>5lAp8nU;=Dq))P6Ko(N$K=Ig)#Eqa)4@vE=g5kX$*R4q*4y&bOODk z0r%|xEAzwg5bg>PXJ^9!y$3z08zzOIt@y89jsl3Afei!F(=UVqyjO-S5r!8a;&Dj= zZ)e-LK21xCjJ)3Q8JN%KxE#v7P;fYxfYzS@uL6y@fYQ_wf8C| zrtj#0w5bV)|Ei~ z(z+mMIh#Rc|4B%Nx(lLyk2*9cljAXn?{8Zw#~9zl_2HGX`$&We^{X6ayEK6)Mg*_? z;AG=qo3Soj#$et;r2>mw8FMHTTY)AbR(=rf)!mS}h?k*F20N{TLZVGv?^b+}zLhgx z$~t*HEuTxpNHM80;tw*9JV|^7=6=U41xP0QL&1k_V3}Q=@aDdH{KkcC+5nQj;%e*cl>SwtYqZny!5vYStyS9lS<4e5zTUWiM&~v9-Fsd!cgF^45UT!+xQP3dm*x^X zBo`^er4-`U{7MRatbL9SHS{FV_m6$2hkAzH_me05o1WT-_h&dKzgGKfAYI!;SA-54 zU#}rvlY!&GBk@mm&gG$$PS;28Oor|5oWV={eKm#eBCsTtZnmq{kBc1HQ|8Uz%<

M^V@&7c?q)N)tpD3QI`2(Mnf zt`4QL7_Ly|i%2&4vYZ?}`1J=y@Y3+A#?}3+YK9HjDmDtd%TM3eY7EXX_V@J+$2^kI zUGyd}xuNQ3OPhMMf`nmVp?j;k$=NS7D<+3|OtZ8z76J~(L_gC^KVBmop;)h%$2KMB zWY5@Z{QPUO`7CGaA?h(oW+W80he8WJLH5e)O2e%Xxnrap_h>jozt_NXM1Z%)knp-o zT9WXGbVMC|vpraD&U%=7q)Y*2@(IHvVXqY`E%_dm9~GNvpa4DVOO!{+uM8iE5AMmFM_iq(NjSXP4$TG^d0tzs1& zmQDO0XfLtRgk^=OS=KkhZhTibl`}%YwYPb?V-?ySE3zH;I$H(9?QoB*ntIe$@&^1H zJh|MOqr)nh(pPtfEwPK)fQsv46xmgAK}1`S~)o?iPsPyfYqcD(E(`>JyP zEGi!PaBkn%#a97H2!CQHa*|7@a{a&b2PPDMz%VFV=f*{m!IQ!aprX*I9GtHyZV=>Y zbPNH?E*akE(_bDp2aQHMQ+hmGMGy7c6Fy4inKgI;@wftaEFy&xsn^Ge%H_Rxd`4p9 z^0UhiDZSGw?3K11+E;Qsr>nweLPBKM$@f)%8kfp1G&`&|9co}!?K3;*A1D@gqjAn^ zG}x4mcqEAq%3+L*__qEGH>RT41?69ADE4nY)5}7eGXSCvf{3Sl0J%n?P-S8}L!~ws z0Ca!&cpHYjzW(@GCZAfgUNgY@3W8Op9<<-i)!&dp*Ti!{Q2e&3oxbmEz(AVT>S*e(??m*JGeZBBN4npu{`rxUjGMiJ*Vf!}ON@-H^7 z)EMqO0RzI#D0TRQBC*8|)i#NVwP&uffhJ2OOds7uCxwWWz(bZoqB#kj@$Vapjd+E- zB#lyS$aXVmMSXjIOo|09sPm$coo;1JvP`9XbA6k0neUdy>qvuRxAEY!wbIEmAu`|k z#;q8L4dglDenlKGcyK&uW$G%T>pK8ln$fyk&v&kDjLz+-#hCfIL>|CM)+CHU=A}h6 z{32&slt}U+(L3gI-!*JZCH}`ym9achaJ1A9A=)}iC;z*}{e0Q|m1hw%{LY*>!jZ#u;oa1$M1lR~HcxMdz!6 zeeO@*Uv9|l^a}Ime+m|%AEN3-Iz!sKYhA-$REeG*YSPHOXsC zz7HMhdCYO6xs8u1&ABu>zjEPZ*S;-Auh+=1&VTZ{_9Sh+@5j|BZ!kFD8~`*gaFah` zR=czICWYSZMVW-7*W3$lutreILmNvd3GImSZ*&X3aSyD&PnQfhPY9Z?yjV(q0kEpW@ zYO8D8Hk1OTxLeTRTHM{;-HW@swNNM;2<{YjcZVXu-Jv)HFYfLArq6sc-%S4H@6OJ; z)^(o8VW%K$c`1(!$Tyr9*wn%I^R-L5f_!sjHE{uU6X=2Q?OL&h)%xmMnHdjUZQ6Gs zPQ6cAM}a0d4@L~%pHe>aCKjWeLinA+XD!KY4VZdro_W#@Y5OqV43MMGZCjmBDpr}E z=lX7C{cspB;h)vY$Xo7B6ZnRP>Y9VLtB0>{3{TP~Ut`V$;GjKl?paurk1&`HUnHAWE~;?CjcG0(%&0;8J`m5QRWXhfHHxYuVy82jHezI1ju=gZ zX;^k$Ho5HhVH>k#ZP*cBs8ueFX|C7PD%VoR=hQhd~Q*QVw^8^gN#9H3KZAGhg&f=2qO;omabJp%u<8%HZ4%`Ja3 z?45^=f&buC9cop)fOxNLS+0A+f|2Ro7*$N`Bh(*3C^P^!&oi*Lf7L+cuuULElnXV; z?{jKqoqq981&D#&tlds}}>_J%_$P5=QKCo_$ zeQO)G(N75+Tc3HMqmrIE?`4RGk?Bk^cT*Klb5c`mHBQ_Xv`wH&i`ii!{Yy7T@SYhO z*G97)D`3R;{-dgALXSp(-9c*O{LHW>w~;GqrNMxwPwR^38k{6#-U`aJ-9Y}GXNf`$ zgfTb8a%=bHP1*!U|9t#p1$>I^I7s=K9B>0W>6BgQxhvUCDKv2`+b+7YD+@0Dn!8E3 z`js8<&Tj@_duE_$dIXl9{&H;}AhK0>yP;BUIDSPM_?^m#K2j^c;w3;UOFoaaQA;BY zs(f|lqk_ig`3s(n)yzE(L&>&P#hqWPsYP)K%SSLT8F9Gf?%`Gr58RjmvQmfr6C%te zhOU7@()|xkJaszh%pK?=!Tp7-_~0F~y4+T6kMPQ*rh(;BG6~(+%2QFC zm0fV*9JEnRrlmECd0gG<4F)AtGdzzF0W^guCG6h%nMq%5>RXjwE(VdS+?gw|EsMc7qZ+&ROCRIa8zf9u=w_&GpUSn;T zTy*#^joe5QYd~ariQNlN_UWUh8EIewO&p>>g;=JCoVfperI-SUE_QL+koWEH(v~~A z&0-C8f(D)WMH%Gim+Y6OkrE|@wq9|5h_SXlK#E!gXABid4nExLlxwB{T7s))M}8_E z_Qk9O?%OQt){hTzEpRQc6~jNrHO$Wg(@y@5f%`#trVgVzt0OEIqyCHVz`D)<8+Y_! z-+zS7Jpc5>FyOw>?7!K?0q$Q|9Ts?Jct1+?gWw3 zw(Tk+TY3u5=k{51yg$AQn8s=Tiikgvyg1ewCg}d+S2v=0Z{51U%}CX~)Z`l?JXWj8 z+n#mEm8#7mAuXanPxFeVi=ES`xHYw@4b))v>0Hh%Lw=+wmWqp(Z-t~)n?X=}k@d5UWs;HG zDLmSTS_4rv**Wc+^gpf;Lziz8_Ql-3PL@m+Xy2{7e#3nSF2P{$fMw1gy>W-Or|6A8 z0n;1ON%!nHVjLv9)Y;U$OrOSk#?BHvwdftC%YPT7M|KBWRJ?EM)mymyJPskd);Ox@ zA9WwK*cM&-sH5;ir=ha``X8K3Ei0 z@qEv}wB32Unh!w5KL)KhJ28}`plxeR8oSk$@f~h78h#2bUwv|L6`f>gvr(NRKm?2Q zS|)FlD5lD^3sGmMPg*u8pYSULL9*eMzw$Omi80r?y?K+Tc<9-IqUG5MP(CO7r^+rs zSu)Whrv zKEE|YMwq-sv}iTXEb8U^)nA#$t3|EpM?^Zzz*e(yY*MSQa^^a1uTUO-k~jgenHRy( zrbaF{&ywemI>$$CrPBsT8SM~faUs$z&{ty=NMr#Lr>b`}V2|81GlC%~`4tWnm5#Nz za}m_q7W;;3Y|{?)0)7IVWn7-f9&&E{XXd-auKy;nnc?5>9Nur0D!7?61|m++O>p!- z()BcripspH`L!gBVB#qeqr>&3D!jkJIv*8t*t_T2bvhp)C0|=re7KfXT^+oL`zFBO zj|wVYNf6E!VHlLD`YDS3l)cM(h3v8>P1V$F^<`4%rWpIK`uRy_S>*iosjQr3J^P5@akW%|{LVCS5>}Jfb+ktA08z0|2ytGu_7d9% zuGi?u{k@d`!4V*+bw@R4vNYl#XK*aIK7W6YJ%U`LEBI^>*q4d&R8T%+{oc@v4~KeF z+B$Xd;JW`k^o##{@@}2{J^9#Yr{`qjc6+vBnlR#NJtEPT)14TNrkUimmBDM2duDzm z1i%6{95Rb928ULvU53b7o1f#5Pq;z8N{%$KH6x(h=QrioX3uF=zhlRVti4~k;MC*8 zr{sc?gU@>l)?Mo~jh)m8P>gorgiII+_-?NmLQ|um95d9LR3%4Acc_$BOtiF zc61DIXKxlE==;+?>{Tmmd-uqLM4(;URL5pUQp)z^%(%CpLdk@TD7Lj^=L{3uU_+#! zvANS1zV@9f8^>%S#BD}Rt;AFIgvMnlHCOHGRhP3c>f(`$M$~jS6-`xD;A1yN!0ls| zXNuSI_#5}b_fE6jfwn*{e=kj;h{R1LmsM={o7(;7p3(kt&-tyek-D&dnW4; zCWw>wM(wBv<9NI)7vs$1M*v{#^APiw4L@G4*?Blz=r#U5lB*b`;p5D(`51HlQ>7R~ z;aUEy{l%+lz+o<@S=MNK#@6$@*QZSzk>fHi<^dZxOG*!cm!(bI*ehL5`!qEigguIn zCqJjDFRY09Br#@az+pW%`c}zj+G+_QsAFa_90h69yOue^Xf<(HAAp;%QXk8VUB*Ib z8t?5_ckWPb=Vohttc{L+o|Gk^vC}3GsgY10=7_KsVhSx#O6d7ZsXU;9Xe|%!HKxh% zIo9h=XJ@&a)tYRorwoke25I`MFd0MowLPxSuz<0UYxpJbOi-E6(B!2jNp@Zyv@3@k z2^V+&SQx5FQ$zIDb#WscR7OA(e0`PvURdA6re50jtG<;EAhP9+xn4F0eW&+}Y}J}hX}N4~10s95s)h`EC*x8ek` z9FKSTrt~u zqaD$tTlaFQvRT{KH0DED7#4FO?vcW(}f!jh06|SLa+;d+yR=ByG=n71SVXx#(jt z`*N**&;&kiNtb~GjKO4h1hFu~(855;AIJ3!dZn#l^}escD)Ue}ANEl%9nsBc%; zm{6c6cGOhWhYLj0RcJk4t{}BZz({-4(9gACuPu2eP$b5H-gaotT*zThq_CFn_kyk_ zzH+WhoMpgEHdhTl0Jp>O0wsUqF<_>$o4KrQ!NgH3KlPBn0LpL{mM)F#pdhq~m3U5z zG!ZIk9Y zwCWJ7BvRrK>Mf>MjAiUoW3ZgRLo^+;$0)=67|pCi@b5BP3_tMWW^ zFYJ~-#p(qz@bP&JJuK_WH?<=X>JS@9oMIO2=(5v3I1*87=`S3$w?>rAl^AVEPwx67 z=W)I2aoY}D>1T?X6SLt^3JT|ER#e9O!@GDK0G{fQ3tvld^x&59zk0 z1(4-l)Hg#C-QY}pL!PP27RJ~{X9#z!+4mBn4d=l1zT=13n!rDPmNP^+-#*ucy~ z)iw3V*ps)jW6c(OCUDTUd6YNzYhMP^CG*sjFgTP+1Pu#9>pT~9wMar%xTQFShPyF> z=COfcD%yd5D&~-{c51vm8GTQl#}PlA+~C(5dS(0M2VKg83z~>S{Q3HI8-KI0Y;NdU zj9x@eERLF}ZS+iBSi*t(|&plA%9hK&bu$ z`>`WSU0O0bzRZf;Q!u+)L*(SfChhP*q}0cAo1D12X;d__UxGF*BkhnT0bIKiN+fy( zye0;Q{xCUp%oYb3^2!gGEwGJHIjkvM0cQs*`C{C`3BGFoukA}FngTBlOMltDg8^;+ zhhG%>-;M}2cKx%pzyEXmzvx)s>@12n`~TD;p)gbqY%;^Ffj{Nn(pw`TaKin1a&~cF zj;IK|Mi>O2x|Zs1iB^CLjzFTNyF+{0Wd1WD^#0p~M255Fj+N@C{0NQNKh)vRxtU8dQM(N-S@TBv zJi&@`dhOl4HW^41EqKMdXa=(=}BlvX*5>oTO_g6|PjCc%GS(enV~w%yy&E zGpVc$X_Nm@y<78PX%ylo>SnDb|DzS?Do*EH%nBc}6-yQ6JV!~`IoH0Iv z!sa4P;Ff7^?&JD!0AAH@lcrf?EmxlF?+k9rEb_rv$T@Pl>U-73aua&2zMR4-{G@Qe zNkCsJ4glrk!SJP}_MwqkRV}N{?fx{)Aa)KNkR-3{EF2UKg;<~#Fjvx4g;(wW)Dcq0 zn`@q~8%@^fZ*TDqe2AlJlJPY;!L)gplpeT595&LVFcC-owac=CJd<)o%M0XjzmtGI zxW~G@g3gUW=%pz~uB%RDtssoB>N}08xIYFibp?G?vYvo+rUa1ZQ+#js36o!@&I<2z zwFXAS9ay>%jUfw+I5N~(8rT!1?%L!}Y`VdHMj?KG0DY{J{g|5LoZzHOx$hN&EvM;* zys=&ZHc7@kHXG>qJaRL9_q4-E`_1AYw}c&KNPcdpV>B=V*(m$W_f z(yidOz&Qh@01rH0y}F-bgme^J56_N~D~|Rd_$lrWkub9FHd;ftJ%8a)*;5V)Qb-zskd_(7+lRtN?Y+$!5vR|cD&YqTdo|0)kqqK4w z)ba-TzQ=)&$YhSn?h5WQbZ@Yr4mWD7ilUNGT8vQc>rN6!12$|5rWnuQ{~bOov)HPn zH;1>p))<(PSctU#H2y5tAQH9nx=54NNK%kf;BuF}*lwVToYm-~(o)K7bfc3tGw=t) zM9U~H+lIjBaO-bSVgsc965$>R)Q(AvZia^P|+xa!?uvcRjya|_Tr=@qL14`#Iw{jj8=}}OA zs$0hZl)4kocwVjTFHGw@7s1d*TU_^itmHSTJ11-9|B+Jj(qqznO!TNX0YJddz>XX) z&;jE&;+*~!p&q~0&aojA-78mDO5{woGGOunZn|RwN1% z@vgDYE@p~-lmGgR)$#n0C!vWXE2J%BI-B0`#W7u?1TJyd$lZKRc;DBwWiE!~Q_6!~ zUqn`WgiH0TyaI=6fwA>hL`*Vy0L9&z{(-8{jdM&E>Nf6N5$t@`o?dA&JBM{*avy+F)O1MBJQ>O(7bscgww|S$ z>J|YKc{)li4%8#YU#Y<7X!wLqk^Yic;~0Sa#(vBEJ&PQrcl zy4ME#n3q7?_375;+FD6QbEIdcjqhm*gsBHvIOoM(C)?iD?7@_km+MW(fUdpSi0+nj z!joEx2vIvs!UuvN(C8z3TTEm6hP~_0c5l^&&Y~QB6itLv`86_N=OAZ)rOpAG z-0DiSJT(9KGMC|50`DohJQ86Ia8z?#@y#0FN-)_(RZR8)@rvbfacJxTl}r z_y+C{nJ3~kwC~Po|5D>k4!t$s{dTmFazHscf{hT_4MLLy2L-j)eEuz~sjc>x=v342 zl;B~7gUR0a;&2Kfhb3n1J$78)FEs&tJvOd2t6E?Jwx6mBPeGF1L=_jJFC2QMXOoBo z>W1iArJ^cXn#PgPY!Hy)8rMGE$RgH0^AXEeuEmW5Jm>;J=AS81>NQ4*DH-h!p|YzJ zix4GLjWoa!upE~>U>f<7Fs>$%5Txn09COpw1noL%kMR+pk|&!1wkb9Ttfh2u&%8I8 zvfUkEYhx{Gjhr6)IE~s}*G8)j|Li{ltf=HZ3nm?|joboW#e-^W*~)g;!c)x+5qI&N ziPbr7@+5`@u8qMMD97<;gJ(}A%vi0t)D}I4vMSHSlI5;^@3hw)HPyrItt6@4~r-*6bQp*SUbm(&`i$4)hJ2|IGMeZXQhKv|9wYulX@a_uc$Ow|qDj5|Z+cqOV5&od`$1;X7oVmIas6+}h?R z>qQ(oyJ%x#H-6%m{g^6e_8;0druQBR3b7d*aP&pB}&oyv^h zRxRfyh-(d-JNJpM+{_- zyCzgIX@zpM(TMEAMPd|85q5Se7qzuvEGYNXoylbeL+fE*2uJk^Q;FM zk%{w=+^D_*T6&P>vIidxw%x&1VMDMQwIg8Su*g`&L)RjNGHFF;@nS_O zO_KH_8Nd?#EM{+*AZ@y1%%sq4mwQT-xSIPy^O8&>8ExDXHUDwD#fz1Q?^4l^{JvUHzjzxdi7(%_Dr zjX1ExunMN-2Xd3B{0A5JyLz{+MI}w)z2f8~rUFJV$9&`TQI>)s?;w$ohnM)-ilI&w zPfxe*HlfEe(l(P80_B&0(13w~xjKd?VyV4gRcCU0O(lKm@W1}HbP5>a2d~R!FK=x& z`D7*1HW5e_6%v70>DDY(?czVBB5cOiw|<@4;$=niUsTb(sbJI<5>l^H;yIM5L z9lzq3Rv=R|Yq7sF=C*2L^zog|A6)*S^uDg_DeR{#lOY9%6*;Kmfc%3>)8iWRrN%cW$_|w^r$0|;VSA9|3tL!w+L53>Up&0WgURz#Ta2%a7 z0^);|J3Ho9Zj69RR?p*f(&LPd)?~fet-ub`VeYooHp1KDBks}lc|_9I#Ly%7X)ds# z6!fgH&LnAn&~U1nU_q+-$^COg;+ntP<_Dd%M&2(Q`WzyPInebMeVa#Oyo2sEbZY1j zP@ACh;+rfn{%B_#N5%jg7H668&8Kn9<>uJY63z8ThO+^oKWCo{#3`g;%RaG^e^EtD zhc7T76--1H%!B*z*6o$X=w#R78y7u({3@yy8Oa{I>sqFjh2M;^3VC#O4mwS*D^ydIz>Sk z;iRcget^r4f!$K`5Lfl0L-Ie4Sq8>wFfN}$O1n30OB=^<(i%mIh5JcD=r;ZYzo(%2 zrjnB=^P>42uKF_VEif_M)~b&(F%sx6mhJGi3L$=3BEa{G6|SvGA$C#uThuomLj{CR z#LJs@Kq_j#-xTGsC-Vq}4vLs?TeSxYZ0Q>lTa3&%q@vX#`G#`PSjM5})lr;!3J*E{#_JkDGFxCYZL|rj1QZ140Dam*|BGKc&bkum z%|It=ojOlx0_DiTo1swsu=4`D&m`xz*_l|`Ee#JQsNu^c-FP31X3dYL|Ms1H2w^ts zXo80oXzXqWy4ESV*sAjMrR^Cts*0w-{i)q#g)#Wv3kGuQu?0jEq>vul3G)RydNpjW z|3We0gXK+~pF~iMZNuXd44a#n3km4rZLh|}`hyq)D~ut6qNY28G#K)XsR#&VvVYw5 z1!yj(iU_qef^>Kr>da`?YppxoEWP!WE%@I%6ODv81uV)sTr@E773<>u^cCh#Y<8yp zoxmIy#)(N^09etyH=#4Xl8*_d^GoAHBRiybKo~=K)y*eh#oL*4ypox^%&uB9HmDLA z;$%;WPUpmNkMEn>j@g}jbU#1-+0Atliv9E%GTdpjF+Knk_1=}Rwq?^AaL#uL6K!N6$tXa%Vxk7bKjG%(;xAxXHIdv@{Eb{irGknBv#O_%@^AE}j zE^}{t3^i^1e{f+a>$RbblmO@)$n)6IZdf$V>bO3H%+Y7vv>?>ii`?-fMm7q#HD5u~ zi{XYspO|TNN&Ti>PA{;7-if==PHMZJd#xwMb*Z;@J#c`3Ym5>2OqK$ zcOy`xc3{Yi=xWncReq(nYn&EFz_qQ!)6E(dSC23U3qbV4U_UK74g{~MX=zZU;ZV)4 z9TO%M-Aj*Y@an4MZ%^iT!i&0FU&x27?#~_O!jkvTb;eVZ#lB}{pY`%CwkUY!ho@4; zQEK49>J^V-J&q^&L(_4=GIFTgW{NM7L8n}y5D`V!D^v>fHQSkGlaelLb2MFbtZ4-i zgiogd&sM(GTnFmmP8(=|L;1%Ym3JFzZHd)t*P7oH=Aw0lNXP#vOmK3>b7;H0CO5Hn07g`P}E?Y4VglCdbkR1L;pXlJ5-uNeMCVA`l%NNt6`n)G0aRL0$im-GT@Li;9Ly^ZDCC62RqlRYGu zzcw9_-U*To0!RI&vp2<_ueEM=bnK{|OU>2Yu_XJ5y8v7vJBcsvQ~~o;*@%T!%5LHJ zEnHZ{eE6IaVr-+_PMPzF020Bh2_PzbX5>ns-(`N`2NzpQ`)n3tVQ@XxaB1p}j-2Pu zFCUQwD)=HG>1fP`nC`T}f!1pM-Q8`fl)L>l43$WGsIk%>-39#{BPAPywi)FT>QDV1 zfXfXap*3Gl&%pdXJ57#E;S$g)Ad`t_Rm0f5c39U#SC!c{ATb_aDDe4YpMv}kb zqUlGm5l?|%so+0TEvAlKu0ljaPN}$maZ4A@HI zjN0kflCs%g9I*z&(+5IAc^i2I4hf7~;sMeOUxZrZg&I#Q1+F5}CY9@MjV(V(p$szg zh@q%UOmYj)2$(_TY&KtUVx*HhIHNDBfa{m)UsFO#26a5|{+|yT^KIYCe=1qlq3LI@ z?P1Jfa_Y#YNm9v2yB|@p>p5?dPy4G&%Tdaa|G4v4I`2?g z3^%nua>AI0_XPZdn1k~^KfZyPa(UAi(r<06`pRy;xQQhSr+jG8*10o-Vb6u* z-XC_$FDk`ZUT(hxe?ch5X`Be`2|?OuF3^0#B?bCr{u-7#{kmrK9N-ZJ`kcqn zYP?@J%3ZZtRNkx}GeavJEbBbQhzBzEyOLe9?p1B4=PEm-G?QY5n?k{Da|8OT$6NuNA|A73df3HdPu*j|lJ;=3A zjdat1*tShx?67o(O^%;mSAZ%JAu;f%YUB=3ez>zu7_X(SMCN5Q1%TKm$=^=TmKVs8 zg$6VinMA22zFw0DPBAffoiRtWG;!n%yt^iXVyy{Zcl2Sc zJV8F>NFS6`^QJFbD0P^sbH+wxGj#pNeW7aSjm~tWz@qeS*^^mzSPreA6MF6_sQD%& z+XCsq48`F=CsYe`<}zruFGxY4t~=5>t`^<7UT!_rIk%>-Y2^ATxG755rVlE^{}1jP zi3N$`0m@yQXTSAt0$3V1z5J4S{m!(m+VcT!q!57Nns@smflpoKBLt(w2cp_#FL)LvFzplb8EPS=j2*31xTL|?F+^~oBTmsll@NDG-5?G z_fHidn`eZ-t#QGX<&w6cRi{ga1uQRt80={pI6*JUaJo;*Kw)Pm{F%5g!4T!}H#Pm>g?jDJd&(Z- z!nU)YtLWt$b<4dgkNKS4NH*mTRiAXwzk=g%H*%Kt&o%x^Uxp+8%@5>_4G|?<_)BY` zs)uldylM4uhIK?C>$5M3z|)NW;+sUBz5}1T9CL;K6411$H+afu&y(vZNPY&-;W41L z0&#P>6fYKAR{XhM$hJ>0Z%i>>>MG+z>r_jDF4xN=jMrcny;T+T;~oYY2e?^V3(yv+ z&Q;fV#o9Z2+ckO#oWyb@IGcot4_>_9(Yq5MnZ{ zlT_%mVj3+~uXX~NQ-jsyOkCE7>D%HjHs4har8s?UPV`GY(gM%7=xZ;JcWC%rnKl(Z zc`7ckc~^W%U1fQQ$7Ojn2tDxku-K-|!A=#1(J;dxHl99o@%v<4@^jqs&g|wrNn2wD zexPH6O#&*cv1YnqI1bStA3J9d-DUhl$Ie1YqD=>^u4bZ&2s7cA@lw#x!gx7;CC_5G zPnqrY!EW%R%rxg*Kjm?r0FFCG=%R*TSmbCZexZ-{*;eT&rYRF#%DcykdRS=nT`{s@ zER5L<7XsV3{#&jZ!oz~Frgw1vc+TQfKM3n!LK1{Hbrf+{7`XX=*;kk+5=LtN=fG1( zgg+%(Hz432F#sWoi(0-pU3d8<8@9$OcaD57YYO6YIochOGREHI<*oYz++1NZPJ1e< zBNx=QUDpjScj#yjLnIg;wKtWCCq$r!8NSJ0ba9eo=i={_4D1Z`7i%t#mMA+j#-(JO zN{ZG6-rfSCF-6I&x^h#FS6l7G&62dwM4D|U*qm*Hb!teYe4Q}7=vpZxJTR&*UK9nM~p=YFW{5R-LpvY*$ zKCLsaGYxC4N{Uz?p$m$91A5x$C%@+}zU(UOpst*}*?F>6hzX4Kuk}_)rxhN0_i1|q z3^6mC?*cl{P0)Y|ck{8$Hq53%9zAF#4VKyfKugm8d*c3=1#Uh09Otw^SAf~-C5k(c zf<_icW{(9s?$ZE0=@;Zu$4ra4z9E6lCx}^Rd;uT0a!1x@2>vt1CWY?ECTK^eeU8xj z(nRhJL9wa3-9og+uex8c0FOaLGCY-tOz72?=UZEo^mJNZG)L4PX7OYr83cQiL6_FU zJy9GA031A4pB27=1?-=`JG!%I)I_W~7R%#B;}cHV!C?BMvChbLHQ%{S_fVG{dQ zLI>9)BDw>DdnPfDN*{w0D3#x`-2!h&D6;nX^zG`tJl8NA2&9b+3 zn473w5ApX~ash;xW!ACBSK>B2!PYnZ`O9UZdvul!Nz08-$_f$h&t;GiUlP^G)bLGN z{Z<~X3{*w;FX(^58gk7F-ajVT(mhEo?5y1eR5#15=~E%zqJ@>|tn_N9q)Hxo&xDvr zPij(EHPw2+G0vdMtoXSPzF1PuB3QWX0sDCIKHH~CE#-yaeKk@Old}qZaHq+~`CSqq zHg@Kuttan}pxcMDvnlJ;aT725_eJ~GO(P_%WwG3j!KwnaI#ltsnzZ>I_)Mr)mbVz< zz$8c8+gkZC`)eC6wxsMWqaqqNrf2`pe*OFWXIWE4S!~a^-EZ}0@7U8VB)0y}Y1{`*u4)hwhNY)uH-8dn!+SD}37-^~WZ))DY zO*7+Ezq-)D;h2_(NaUb-#uNi<&fe0-IBRcFPb}jYXz{9o)->_%#vb@$A{+G zX`7aQw6}T1$Xnx7frjNNZ|^8d=<><1$>;9s;@GIk;d4up%t5#lNE%e;tNk=?8xoWc z6ov<5PrP0OL68~4vP@UMQWVxb*5=#}>-RSTkTXL|jkj^7M#zrk(dqT*@V6;ZzA``q zk-FMvwcq+j!6X*vbA14|+-{|^V-5d8QYCLDz&%SD`lUETJnw&}MqQB$Ay$bfVp;6clfJq`6#&ck&z>y0ep{7%F}%axdG3{BL= zV|4h-+T8#>Xs_-+xCFJml4qiqCD=XAOL{}|L3b>k1FCSG8@BkEKP)uf{>GXv-C8x)#fhrbul{dP2eLf%$7{PW|hwd0UreiXO= zJu~TRkc5ZgTkS5G^Aj*JcSC{rxhcm@#?2$J*+(zMwlig6j7m@FA!#RhMi|R|<@br9 zlquT5v?;|B8+VV#h!rJ~wJtvb5pqs&lVN$OR5r9%N{nP8-%CXt)43g;mN5rfpO6RD?bp2oBbK`2rONd}@D)zJ z_>aF^6ZQmg80Tnh2rks%U_U`s;_Gm5c?PB35h`77+o8yy%-_o~Dki==xtyyB7M1q% zh+ww!lDHqb?}590jDVbXNL8G#Z zH^ye#dEnbB6A>@G){INvnaPv&xZ<>Or>?Z0hb!C8<+1#T8Z5|GbhT!zX7in_<{RO% zVU&Uk5cBB5>b+bfl+x`~Ru+Cd*|;G@HB!6VqMYWXkWzdCPCC*rJ59%IeEWzp2VsT0 zWg*_!%W9($`eafkQ@U-ifz*SgmSG)jDL05apzc5Ip7hE6MUULOt*HpDP8PgBgO08w z`}E3KM2IA^k{Ns$cHlAwJwzys0~?@Z))vDU zeqX=OPX?zo?XYGTWNGU98dCgOb>k1=jTU7L#7sRDVZ8#xrc!FC7CFVPxr82>8?ww%-A3X?)eZjg$}tNXj5`QOHWbh) zS%(=t-!f$T_ST9QT@8u1_%B@$=LgZ^%3HnqSDHR%Q+TBD*VHI?KCoQnXMi1bzUfgIs*2Q)JJ0T0C#8rC@EDZHSWjkVPV! z+h$I_JBZmpb}w62Bb7^aN&Bg5K#dN3%?Q9SC~PM!PAM07?y>|Dzv!x6bzV6Qde#k64o5oNX%|?LH?K|X4&d|KPBf8xV{>#p*vUujlUX5Z>m9|_=i#%r zYRd2%uR7O7!g0wGt9p_GnJX>&6%>`mn+7~RL-N)w7zDd`IJ=m)43~1o0XE-vr@AQifDVccd1P&f6uS|zKI2H+H*YCMs>DpS!4ZvX>V+h3jkoGE?q&eM- zJQraBf48gjmCOB4y?1uAI3gYU_>QJSdW!{q%MZV$dre5yuJMN_7oL+R9A;(1le-pf z4g&70J$eX7YBHcvE=8T~Np{VdHMI#`NuT&Y#R0)psZE7djb!X?#?Q6Fv*k!MCl8g} zMqsWou3`B0RN8o-XE2agyVRdDVDa3L2NT^v6tIAvyPWQdxb#|k?eRM;7ML>dqT67P z=W-{w#KVrcxe4W9 z>InnTLh=o(vW`=+yF~%@399+(i)^~uvT$-(!nbjjuUSRh(S-ih=)9*K#f`&p z4O5m^`#z4-CRo?0OFZ=U*g7Qw&OKauITiSEtaFxgK|I%wIQHl1xKlKNMI3;L0Wqgn zT@B|Z117nuK1`D*kF}UCp2^tOBc!H?rrEs`z+8t4*Bb+L5S|9=4)Wu03 zwg+l2Vk49|%sUvCltz~*rnR>5eeCtBL~!Gu@G(AWjbznGY22W5?!&l0xtFW&aHYD) zsF(EY`3j}j5OJ6WXkq6zhU^cncQ?HW^R4(K|JbG!qvlXHcQy7ROE`;x4x~$HC=Z@+3zF7hu*JA8V61fdbdUdp9+Q|evo7oYySBDvGpHsKQOvKkw4cSS8-S;_lE%e zUG9#qR$By%qb8Tz7{9vd#2le4@yP(u4pr6nYrJITr{!n=gM*~2USmeN7+CYlZmacV zDj@E(=X3PY?1Z8LIYC7^faPhUHA#0-RQ36wF1{EQK^TaOZ^YZ-7z9!d(0VE|}A%Ouk2S5q?h4I6= z8*`TDHatglY#j+0GDp+C4+5dul0*J5mNjl_@a+V`0%?STaj#lx3kx$HsWT`ec<^tN z3UKUVKVW47ZFbul%c1Dz4Lfz7i1xRc)LSbTk4ZT)wdDf2%?709^WkF4!93ywNwxPc zP^6jw;0^c8pxFnbE#b$Pno}dYw69iKy8Q6rY})yUrvd}xEgn`uQ$>Yy)ghEB<)`j) zr4nR4-#m-sU7KCn&7W7t1sU(4KSY-xBB!7XL6+?pUV<&ks}z#_!OX+2-x9~GQ6Z@H zx@dY;?>zkeYJpPirg}hP*P=n!WDPCkieuf0B^el>@Kwd$lm{K_rrC~@t}bI~ z(yqJ5E!$YY$_E$-X~-uFWG_0jX@_+lbCK1~mIx-NVKllHl!-&~>|F;eUqIdDeTKZ{ zS!)4TrjhA?sTx;nmo>g+PlQehX8IIT7+c}U|2Dn}ipR6teMz6!AHr|F6nxHT*e2V5&V@4Tev@b%jV4fe0RDnt*JOxjRuFskaX8e+L@$Qamn+xkE}icBQzCS&ln9bxk4 zne9F(^R_OAyTR6%1(Taa`<-HgIVm8aPT01-=4uRxR+&j^j`Zh{?>)pR!j$Ru%*OqE zT@3E7%IKHN%|oCSvrAO{sQhNc1|aUPAKFIUQH0O<`}e7rhkLl)@27-4D<6V|KRg(F06x$1#s^=Np9O}%GL@67wdiaqr86f;O}acrsv~1+10p8zwv{IN6p4X zcHqgVI;wflHkdU_&fx?PG2bbPkYyP5m~jyQIbA&*IL~BLk`o*1VJ#r|ygtqE^mzb@ zmR28Hrk4JH03Si%zNp8qIi^VQX;y?^CEm=7#8&AYtZdLZc>?DHf_HK-2M2&L?^6wI zi4OcQ!oqKemDCkdsWMMR+tT@59%*y^Pp65M9buCFPbCL6Bt6 zLUK+z=K`%ID@l3#*(-}q`!sJ2*xqQ~6N1iY;<=t3>4;9k!Hz)%vNQ7ldmPloN-?S- zwJB+zJb1rE)b!0t<4(CDypy-g!9;B54amqHKqsy~l}Nr1i!CJNtran9^GJcC-t2G& zFgYAn>S?_gIGhEm#c{YWG3Nvk!T$igSK!w#W{>s-3x;&jvGnU7pU4a51Yp&vZP1_lQM1K8C$w1{!GTfYso32*hQWk{M; zGa;N1r^}CaS;svv2ZE@tvZC27boyX->R%LJ-)Z~7( z(UvZGbiXqkZ9^A*XvaSi^|>`)#0_FmDQKXbY~ap*RE=?w_a`4xYfPI~QaaJ5_&VnD zAHi*E;utqiWiskEYVq>P8>2`;URaDjU+GclXUBfcHT_A?4oxT1O@D*O(PlYKOviN0akX4`CEg? z5Dqt$Zl#Fh1YjO(o~bqO`+L#Up4ZT{Y5qNhwK=@l%4z6K$Ri-iM?i&-%6exb*n8Fa z)VkO2`4r-s`j>AE-JMp!?(P*t(@gHsGwuq6U;sTa`kb269nCi`@9lm?GA=DBke({= zx?~Knvf+kUDiNNiIRJt{0;?=)JA%nD>eF19@|B(L|xj2?oK_t{0ww zVDsr#jFMDDpxIp4G+7}0JMk2c8U->yQ!9u0Upe|5_2_=p(dno2Bbz)bEXg$K8XLqQ zkTZfajMt%&Tv|C{r)BEY;9I|x3<6MPZ~!o=!iVFa&r#Dg!xW|2(8fM0o$rOBx+6&p zC8g-4*tbweUI4A&>$5lAkh*ommUAE|G8^S?{d%wcsg??9?7UrV8@GeC+kJCGn?#@D zBtA*sGbwK^Gs6G~Cmk?3;2QH(f8x%*cC8uaqh%$>n{_hz@&w6alxYS&T#R~P`tmD9 zI(sPMTfYtbF7j%25?$GD(vW0HC?Of}F^21c2h%+Ws=0hdS}TgO^WqN~!KG@CX3@&~ zT?v#hB}oS$gU;>-eR69lH)e{wj&$!F+AzMJ{4JK70w%*WyQFqvcvW5s@OeEd>9zS0 z#XT;|d{>IPdf%IA3~GUy3T%;vLmjGcGIuTk{{SsHE#?@~9dY`$Lo zr6F`?R0s%W$0vevGoCTVDw30wx!3S%2=R{_AYcN+Wx|6c)T8B+Me-s=Z2nhM{G?|k zyB@V)!oJe`{Y!VD$A{vQ`tC%QCf=%MJBAfb#wy{t8@DC_`c`p|C)d~Z)BTMbrDlT_ zhxn(5rMJ{%o?kdDjUip1Gb%7DJL8{ho|V-YyqKzQzwn-pSxbgXkKI`jtZG_zjcV3c zI~C2bE9I#TDaHpQp(oevP~2j;lDSFpF#R*dGiaV86H6?ULm)9+e-M_EG6*|~`TV1@!xiUyUyW$d3~3 zlVJ$scOV~7dsN4Av|Xx&F}Ab#fp@2CSF>8qlG(7tYa}EU1OAiHlxGs1E^DZC_JVbC()V@9F#(sJU5vwOQWEJAGp6+u|G)A|}R29DsAn4D*V* zPPpW1{{H}S9Vc)`KjN(sbX{KJ%HHLsyV|c4p(0RQo`cwZDtJy8uvMXM(ifGc! z5UICdz!V{}{QC00p{~5y6ju`nLAPb2@c#fvzqG!OGGAK}A>VH5e4Ci|kIG5mhaXXl zcdlPLI#Q*w!{Q$nY5G*A!uHwb0EXCdgKKp=kKgvAm;73?KDK8bC1@nKXSTWXB@O06 z8bwhWXMh0Uk{h0TWY<*Z$s}_|JZ+pTF0Urol0N}qn^+H~40_7*K;bzsi%PS=ABn3hPmvt)*NE}>hSRt*G%lpyry1y7*|f-C7EH8`n9 zrhNS1;U^h(k7v@XRBduHO;SbTF=&Bo)sT*p7s1hqA9KmMQ-CI(*=sEPHUv4Phf)XS> zg$XF$JfBC>?weVb%HHz!D7=|Ia2-^hxII85XC9;0vdEQNF9%OXN8{ahP1ST;b+WdS z%I-7e+>OA1x%o%AC-xQ0)PLe_ZT2sGp^gLPv1y|DO5;PS28W(h!dVEgm^YLbs0%O_+FtPxz?Ng}nxR>bcLqZsdw zDv6ftyJ=RdX{KJ@+iQrfBipj*46^r8pG=z3t3^r!20%z%zcFR>Vd}M+VGZ5QyfVcT z6}FV&hg|;v-i)%Lq&ETXgUo@qADaXERP;M1w0lU#q=J7XZHr~3E&RXQu*q&ZHHBWu z>z!IH4^!LWyYmF8Dl|?3bdgv9z~}t9&%SDKT6V@-Yek~NMQg26eM)0*j=BQ3L@Ho8P4v(0~REv3})HT|W@ds(fa#7^6G;Q9hO9CfZNxvlUz zVTmPvNo_Xm?cN2BrYIe2BiA)vB~;&Cie+?Q4xP{_>d z_2U&B*SIbID!I1P^h;LLF{s?!FiH2u%OoHV%btvcaaNnhDE1R}SL}>%T-)xvdkg6q zSzT_opj>`@fw*J1HHQ?ozo|A^TG~AyQ*&*uLv5%e{{SuipXQ+R4nAUXq$3V80Uo_; zrY^jdqDM-;v$OFn^_BjgX4izdhH}!BPnhoV)(};Gf04$G04w1bU(_&0|U4N99L{peX|!wdyNys@yCrf#zBi@mAW;?^UyiM6}vE-ngx7B#k2DC3WoML1#KB|-XB#Yr!jkjXx^asq${ z?LZ{}xS#{lfG7jE6aj%kL#+r362Q=a mk{U`!}Kdk_F^`Hs>p(rRoPz3;S^%Mc# zfCsezPz4FF_QePRKp#o~{?q}``%nio0n&gyK9m99wE^ZwjwofC;$(u}7}{B;kl|uQ z8D?YX0L?=O$A5}mEB^rN4;$)wt-e;pK(@0Cp;$nlDremC$K0Cc$u3OZDv<@E-Op)p z8MH6vZ&nJq$sq7C-nsH^9azz!>mCb&YninP@9nhRDHM5zBEf zXxEH2OQwe5rB{%uzvUvW=?v2J8O-sdZJmN4C;zZzPFlosshac6MSE^(aAJfQ3Gl(EYuP z^y&MR?-S}Vt&DcIF?kjd{E5!?BR@8H=OmMk#GF+lxf3T!h@B2c^FWBtjDq_J+!TSp z9RUovt4~Ub$Fp1T28|qRHmx|Y0j*?)7BiJFx()6@C*?dYIX(R`SV5y^jFVNGXAgBe z!g(elNt`hx$mc9Ze>WNZYiK3OqbU&<7Oc|5sK?EakgQko=b_0ptmSB`?7w(&3u~qc zGRY)Ovn8;lzFZBbJoMtYCr#|?$MiSf0ba?e_-ZMbGP;v)S!NDPE_(Bjaey<|t}tnZ zxkL8soQ)|TJ^mnB$#1FN#`aBU7E*k$`_%zC#(2&~4sppnhAQ}<(u!u=AoQyS5ytRE zApwH_01W)YjGd$Tk3a703!=n}P9m@IAw9-o~v;5^7CEfN9=3|m@LH5ooEPpod@AEXt zqMK@x$#c3iW=6?!4l|s9KY!Y`@XmGFp!jKi8d&9U&2eucNXVoqIKlkiVf5=*xYPQZ z#pv4Mp4-H_TyxEDi(Awo;YT3EbAWn!j-tAgSyi>C`yBM~y8CC(J}=Vdu+>gHo8sVy|e3BZSWTT=I8F zcq5YMx4IwXd{FP6SQ= z0O8h$G?x?kFB3}Hl@zxjTbv$Bf_Nu`P~qFMRMXWFS09F+ABt;%$f zFCUnnQhFR!DaGCW{q$Q>@LKHQg(PcvBaT4mo?witDyTh9?BEPz?NGGo{r>=7gWk~{ zt$rTqx`SNJ1e06J@)?+*R{6@Q$^zJ*>xU(#f z`m-FEo;fDAkDs*91ZvvHiFHk}gq}O1^Gx3&Dzgo&yz|#M9jh5h%jJo;1f8?#4G&JY z(6p;-R3qVS(Q_IX!viw~Tl%za}$(5$O4s{{T}q$4;NZI&H9L((Uagdnrq9 zSB<6lS3attRF6O_)WMUMB%8YaJRW{nR#yH00G}i`f^IHu($>#TxbozX7x75TkNp{Gp2rRCw zV{^bNNXS2+AmG)z?5|xASK3XMq8;xot!_z?cSs@0b>{<&5sc><<37~4?oB7)dEwnY z(@40MJ4cma8I#K)h(LcaQciGqBzDIY4^Hf#1#j^}B^srXxs-^FyOfDZ`95%dR?l!p zzCCD_OJqsfGg}#AI?DM_{#~Vu9FQ2}BDH;TT^Yx+&*CrfZ8KYrJCI!#IEplUa7PCn zK{cIp%^PQ38fiS#X7h*u7AJsI94{Y3kF`T4FJ`CUy+&Jk<4EU?e92=CAYi#da(4zf z$8nBE4QCls)Alry;A0-u zz9`;BMj0h=+49-b{L8{(kx`aFTY1J5_xlmecDJT;MA3XPq{)BbU0V1mn;~aA79Mj;E+4hNCiD5TwU9IsCl=9Zq{1>2Tv4FpIW1)I1$~ zX!|ZLnskwOLp8Z9n}OuFa0outm&M|{HQ--A39K({Z|^Urx4VrYw{_U-^6yi)D{+-P zaDDyjo0U68$!lfGFAeC2PuOik2b53eETvh%OoY#;d=CErO3kE~-}E$3XHON(d@tdr zlSr~*bvRh>U;e~O)VMQ zEPfYw?k{a4c;Zs>pap?qH!#5q(2xNf@rsGXGWg!lpzrUN+d{gM=@L@pN3v|;j&i31 zCnwNIAs$myQZ8)fX-v5C;IfWMH?jHH70y*p)wvnYI#)W2@7U?J*SRg> z{Wi^=?EIA9DuO0>hz%YH7%Y131mKKvdez|-_*dHh0J5@fxff`(%^OM3ZZ!v-31PNq z-{%53NhLy+>5|QW2XpURaD-sz_D}q4odmNLF{p$Y!E;Ypwxw~dJ<2`oA zS(aH6-EGW_8AZCUl&2sbzcBqe(${Z9KVj9%Ph(3&q z{{RsCMRjjxvU0J;=)3|*C(x2P>ro|IB|0vC4xdp=`)j*vC%T>&EEEE8t@*m}G7n!` z#avy*bZ)9jr292Hy&4@>YbmuD9^cB#DyxJc@!f|})Yj@QO-ZUUt0o+x%uH(^JCfz>F^GfjK+J)j< z!@5Q}&fba#ziNodHdlk}*Sr_uNi6&@EOm>RE-a^&Wbz2c3F82qXD1o@aat(4`JRQ> zOK6|h?L0T&{R>CC)HK!jbiV!?#Gf~qRFF4)M?>jWlp&5PO=&wSrzuIK$gdCFCZnOY ztsR&?d6s9lNdaK0&4namjxaOpSw%YK*|fEyBf*-w-D|#PpBu%eYCdAzTS#{_7igQ6 z$6>icA@$m)sIOoD02!Zu55w#8{{Uy1{{WD}oPH;j{C}eH>0Z&}oFo}1`qd;|9JXYf zRSS+$cBmK?sxxOR?>FIQ_;*yCE>OQhed%;UAoM>HjcWGUEMW7k+8o@t%C)?`FhS}M zKWZ+86FQEeX{Osf#r)|E3CU(W3RpAUPw^MQw>P3&u_U)Te(9~4p#k4JO8V!Y?^JV3 zR#`>8oivXc=~HSEUtVaj+T4(Qxue52-h`2ij=!hUrAa*|99f}S+(mT)O$34BZiIHL zl{*2NtC1-j?hCEFrX^;OAu1QCIO7ydG-JLZ@QmIfNHo}*;pCms=AKXf%VQ*Q*bdz@ zgURU=T!eH}t^WWAJVJa$1(eNh_C$$Z?76{A^1u7AI(yb@7naRAu8l*)qfXPV?eyzQ zWU{c+K?ZQ4oi_~OPhdKeS1EfjZy0!z?^3>4bql|b(`}`1C@}oWc;NT%`qwr`x;BJZ zo*6b#%W-dUb?|XrMB)~4xdZn8)ticL%kpTFYp8W?Ba#4-sgSP1enZgxDUSD|XG)3B3u$*pMT1eb)D`5HD#_%Q2&>qW zz&@3RY`-@e=-U=Lk1uj|_Vx5n565{NUUj2pCBDcKg55%n*e5^IvV@$aQ8k*SY^*+^ zHiNbcN#>H$@OkqRgl}QcXSntCtt*o6*yfWR+s68|5yv9E<=ZRE)RX{ogX(DsHPa~4 z@T?OLTND{RZ5{+)Lf^_(+FZEH2dOMql!xqUd#^{A$u z5?C*F8?8Ac)7<$IWD^`Kvv?yTEINw9b(ie#mSYnj14534&Iobz9$l&u@ zl}9VBPFA?{Z3OLhp?+Z7mE$~ooMRn*`qk80s}^~**4o!oRn#IV(B)F%DSVbdz>YZ^ zm#zn|TGA@fR&9TST7CSwU6uK{jOgklmI5LIMvNf&KpXM2XB|&rS)`J(>6e7mZhSGR=$;w35t-p=jpHB^mYPGBT$~IbWf<&p=~SF= zqRII#mtHRL(U$W~)FdpD39N3MM$Fg*1jLKR+>OVQ0OVFpH0Zsq%T}SP*!VxdmPbIb zi~cqjip?bDVpiKDv+g^YPgTjtBpxwTl&UxGUNLf({22bZ8^;9i1otOIbG^gn=36Eh zVIh2fE2@LQY!lQPV3OtSe}AED%S9G8Yi&?Va+?j(3!}BZU!Uh(A3>g;)zz9U#O8yu zNbpC9?zFkr%2hB)AW4!C5V*(+H+JOU6Vo-pZaYUx*>e1Aw$$51v%Hqm$@AnxexbMd zW+K4|#~mix$D#Rst47^hRQ~?}$rXBD42My$cVtk*AObe@1e~bk_v`vn>6NQ2z5wuT z_O*2scCf#cfH|H)^2S3Ew0q}*J*u;mrs_SHf=O~_+S)~qm#3zK0w9J@IT)}T%yLE& zNeICs=WWFF9QxFCQG5RYqE`NIzRVNE`W%*;liD)wkssk#`Ep}jp~8;L26NMqQl#uo zK1c?I?Z^s{`GA&CPImFfu>1Sf`5Ez{&9Bx4E*aLnB|e54jVh!xKojPF!#{%BC!@w3BeYpL4aTie@1 zYjV!4OYOgjhgCLjLJ5Zf+svIXXa-ljDk7_9kbgN zTwgon{{6)63yM1UqsEs|YO&hs^P*Uds}zXa#NfL8+ej)v+Ia3Vd(~x@N=ZTM`PwfW zaj%(d&OB5jzgd0>)uxTpfDlN+P7TGW!r?YL%8Llxkh_a2|q6;~eH9LvYy$B6#`!*!_Uy_xWQdI{CPCo<3@$!zX=^nQG(}5w~A@+no~TlE)f7#2yl1{fyOx}KDDM;w$qQB zBNUQVJy65KzlL&K5q;tU)^gjpc%y<)SdiO;FV@Hi4UYc+7%xOo z$E755HQm&a-Zz#us;cl+f#I@OIQo-X=aoA0%Hme9$3_9DGbD`hjpJ|Sell~63?4tV zQZ;)kD?{H1_^wSSR)+Ae@$IBCg)CRh`AUVz&jTRy=~_5(e3ry#s%4aTlTo`{2<6m= zmlL%3mp?p=H*?Nk@~G#IwaVdYucLK6*#7{DU+-|QTcclr>C;=71+{Z`H;0W}#!momzCPaq$aLG6yGia7kPKK}sb!pXG# zjWfWWHiG78Q^Xpl{{Wott|NvdSTM0D0|b%5+;BZ<7r&YBM7_u5Ltn-#>)k(6w%>5_ zY4}9&Qj<0nI z<$~^TE#*Xs;fv*uo=6$s;QI5$b2ll!ndsGVk4UI^jzi*a0^aBo?UPZ`W^3&_UD-It z@gW|}K5jpm2d#E`ERPre06BDXdYF7qop=5W+rqcf#pT4YDGu3Fz{$os=dE@6h$eGm zm42tu-Vtf;zYk)tyz)e|TA0zLZm8KPTO8w&p7p?$CXSohW=-N-JBvx@^AIiEEw(~{ zkVmgQvB*8@VW+YtjvfHKX7Mhc1ahQPNhgylV<4f<;5~YbXTLSHqoX*>W8W6|zUEI5 z-os;d=$>(nRxHQ3AuG7!x%KZ*;r{?4T;D~L@W|@M=6joqhZZRlNiO!^=I5p{>5fMg zlZ%e}Mv;}4pTrFfu5<|Gi_Dr!HTiJBp+HnI$?JedG54rylJZ*Y$I{s&)@Io}1R`w@ z8>@rN6qjc4tD%O8 z;Yp>v5W{XGxiOMNiGaILt~dan_tK#^C&$TVqZNJ)GfnV>HmwYkT=}~Su~P!!y+>bs zXRUOsKJ3C--BMqGNUL6NIOOVBex#aylT#AT@1A?RxLhs7ZAPM3;yn03Cv72_9blT4V-Zqdr73#PE`huded+gHa%&Mc{4V2d! z*NUK?Smd~Z+I{y0&nuspZt0vc9FNkuqw~!-*9o2_~tsl^=sHw4W8(x+6^$yteOkEJF&e%-92WP%(`5tmK?! zOXyxHJ(@u9wwYRP6@lSsA?Y`e^?N@NqXpHg~f=~~MiakneA{z@#e$rT!> ze}B-&{7G~EAFo{an?$>cZ8A%wJ8kltU$A62$2lPM>sjHOjQ%7Ud9G38BUiDyivGsl z@(v@N1A*5Excd-m>R~lFsV^ta&JP^iAAws2t0zUGj{uB}{*_xV#Ow`fnT&>a_m)ux zg6ifNnZd%y+jCM@(U#m=YF-XYtGz25dxr%pbors$Lmy0m!nJY zh5RsTQAen15wW*r+Rln{4`O-bbo5cIjZTJldZhocGjBGXTve?!RkAM+O3LllC)bSWf#TvaJ|)UHC_hn(kl#dWQF#(aijQ1X!B{4N$~r;o7j%T+~jgc^KtsEfA$; zZ&TAl=o9LTa=vxDtX@b$M2g*Tdt<-WrxI07m6Gy^=;6LLQQX01ZQJJ{(jNs8Jl3I?nq9}sW${A#ZBl)>GXRMYf z)wElZ@N$RDd^64P%6Lq-%tz9wm(*GA=SsV|xEFEU`QBMl>l~PnFJb}U{WDrFngVM! z*D}hDYw-e50eBg(Jv08Ip(M1>BCKJ#ww4$k(Hcc1*tlm&Vmy+>9snS6Ij)KEy_HC_ zXj)7c(p!%)E}~#Tww)d0hjHQ5sSFpsF`uC|lG~-(FGi0Jk>U>t=-QpduZH|O+F5}_ zazz-pkT5Hj5})Gb!8lgP0P%|IYIx&xQGCvkrs12Lgq5WDaJ~W573^Y+*X!U^|^PVZe8!4s!uJB zxE<&~0uJB^Bpe(Z;QCa7XibPH1)vguS^(`p6ahdK0YD$E0DjZ~KrdrJAH4uj2U-Cr z1)%{z9q0gbpb8QcAUeCECv*N8sQo7W&8_Uc2n&R^AMwV$`tH{SJ$M0N?+qQHqX%`Q} zZ$4|=iBeRG(@nIJ<@fTe!}90q#D0Rgvgqo@v_xGgp6E#Jxyv+eIj^SjIF5x}TMNmB#InSu5PS~m`DRnH`tk-uA^GoI#T1V>4NhIgglUk*u zRlOdx^?Qr8alP>rnJ8gUU;+cn?tvjcvAWnSz?)`EF?uN6gj~v zcHm>!X1L^>vC=vs)Mc_uNc<$f{{Rln)b?%hQ99gNpFxw2{*qineK=h+5Lxc!C`Y7$i%X)nbU2P>gOP z@`AQ<0;|UfJoE;&o8J_^>-{3JUoS7ceX)ez9MJq(X=A8HzXLVZw0q;gz@6I?DI{=H zVNg8>twiFa^vfwY_OJXAJ~Q!p==KLe@Z3;9@ty50sS5VeZY86_=Q$b9PDeFaJ#j*- z=4CfR@qOGLAhgsc)F!!Dhmu698_a@0%Oc~rJ&&-e*A1fFxoPxjo;A`S@h^u(^_Rg3 zEttq|E+X9FBaEm+CUMY?I%R!oTe$K>#Z%(U)?W{#T5R&Xk!3f>8M3$z#SR8`s-8LZ z=~*nMj~9w7T8@cv2BErWQs&v%s>nH3+QTGtKdoxACAMVowbCT?J6SF6Avc<9GNPX_ zN?QaHGUTsp9-TVY6G?bAf@t~*T{6qXdM}6OzQxZYAFd$*}*50R-8Ox;%MOnGjLQF+%wp01#{?4Z5oOz zc68OW*=LGL{vCtDF*yK$8;-}I+*tmCrtGBSXp6D4Ve{ZJeozAbVf@8Me@bcWszv_* z!`>LVy}I%=*tgwA36M#&Bul{#bH^NU?O923bso)CM{L?IwF?gmcz)6=`+^lM9|4#b{9rJn@gfDV05PhcxAnLU@1O=!<=?EV>@_qd#rSTV;v zD`-!ZCSxej??$3#B}+MOUA0gk!|pl%(}gk*~Pjb8=kamLZeR2~@|Z5RWu&5TvEN0unb6N*)mP(FLql4iRw z#N|%x;IJbqa(Vv#wUl+)XLd~9X&QpbZ>d^skuFGhq+F;ijm9yacMKi?#ZA-XiQ?Hu z)Ggw&)>7gyB7#>8RC9-6$j4xLIP67s$1lW%R@d-yN*rZo63$8{W?agXno_o6}4R7d9b7wvH5f3{%BsA2l>!04guqn-l9$2qROh7 zgH1R1eys}W&I_c9Oq+3mp5wUhpGxV9O0T_nmT@niB!_PG1Sljndf3;ZX|9 z42|vu}ayxeiQso`@1mh zC90q+9LtdwTRT(?@z;;qvd4Vd@NYWfeoZ&-TwfS zou}+W>YgimaNi3Ej#%Fe?7_DV)8Jb~38BBVp$Q z=yUqj{WO(veU$YPcgb`=@lAl1+Dnv(Gi?GuI_D!8{{VffOwdhoqdYUOm9yus#!nAw zH$Dl~wJn>iY?VoE#I6j=r<2Bc=qkREKZ==uR@VlPoE8FHgPt%+^v!y%N1sU3KMe%2 zMI>o*_U_xnQ$*aa83WT9>O1DSax0O%UX0@I-J+gRoPhiiHs?L@T`8(DA8B_?B?{pQ zURRDmJup7CmRPE^YX`Gz@V=xc($dO3vn;S(EW2Uy_Q=3(U;z2KZgI{#aa>V48#4>- zHhY_x{ta1}E<(kUF`hul?N)@;bjafT8jplUzlAJJ`n2&S+=!wpNaQaeUBQWE9Cg6S z!3265=a!YTSh`ebTdlRNG!}jDBn~4ERb^1XgU4gQ>F7T0*VMJqT)dw}@WrLIv49DT zY<$MV&RnYH3op&Jk05je8d9P;Y?JUuizB8thWDE_%IQ8jO#SRd2Yj5xRla_qsqMnfgpNMuzs^y}bSg{^lgOaL2 z&&Wmh$88BWsb4gq3)M>(tGlbW`K;-dRA ztwY5co}*`f6~oAulR1>Y03Z(IJz03oV;MY=Y4pt;R9=?Qwq7pOV$zb%DM~>b#);*p zK3HPMpKx$}1z!GMKXgX9a%IzA)bC{QmYIIHA|X3}#Q7&~Lxwm`INQ@5c=xR(%212G z`~Lt%B9fa#CWGQz#DTwxvqV$nj$DwS^yjvE)=`^^G;vZanoZ5?iKNvaHnGVd3ZUa~ zDh}XJY>(|%#^v1AB9l?-F4+sHT+FWQtkNhYLq2c@f0T5rB--C*=^`M>Jc$al4z7bG z)?(rdGh5~kDWhp_M$hrB%=-BxJixGZIeyBN*} z2nqq`2cbVotHTIuBP|?`PyYa#EqC`?RoB0 zC-gIqD8)`6U)ZnslShL@xm&>_lRujpMdaWp2O|eKVxo> z-R82@?XJ*0uB8Ju#!Lf(M}D~nn!lpjlJO*G>posGU8Y(5L2lE28C}?!3&^atg}}~0 zm=C5l{?*Yn{{Z;4=da)V9P$4E{iOUo{>BBXX%hbc^-Q)AIb%8oV#~M(1eGiYY>MTA z;&n@Ao8gCF@R=h*e}QuHOjD*W| z>7KnY&0)oxDIz<>x<;Q4m|SWXQr#?hb(*?oWZ8E7HPm&8FALj%9oPwr zNH&lT4oUj|07~h`=^05H_13&Zr6RYMZJbLY3?jFtO<|eSI&j9-oo;pLEHr8FZpe*c zUCyp~$M-(ft_EYDOr~A_Ea{forR+Zu1h(c6HquD`V9(tSJN;{+x<@ir%=g8bUhY6wL{@Wr{P<1{iOl?ewe`ZbttA3XYbRUKG}Ktr+Rf(Oq0czT}p|hXa;j+nzB^ zKFH{k{9JX?w3{TihSq$@AxZG2RmUS3@0yvVS|TmkM)5|AueHvbt80-P$Zug^E>ghZ zM*)7{-m+<$#jcL_T3wua75ug`M)Rxec-`<+GMo(kfA3sUl)2M8BBRALcZ*XNJ{{8G z)NK~k;FB@WALlB1pXpiCl$%A{N+}U$`93CZHSQ-uHze7?VyA!)Z>=0_Z02$x^#!@q zb#LNNG}lZJ2_%zuJ%;b5E3+NAnDkD|tlrpb(2aY}xxTlL%2&By!4!@^_kC)U#`x4t zp_6vW8_iX&t!K5fvx5F9(M-}q@~{E2208}o&syeDlJ892&3GSpk5GMCz8>Nxf)$Mo zy}Z+B2zU+01o76oG0CXYFv#uL*GkZIeKS&l^^1m*#&tX1Ikrg~4^xAXf7z|z?d-|6 zF2AODT77yr{249E+A@hGymw>dWM^nS&j;SLmlVwRhgr5dee8#Gl=!I^3UF{p zC#b5pUdd9TbK+mZ+O5`|sEd747a5jl$zV|MO8)?qjNppq$%$Q~YxPHR9mTBEKX_Fd79_HHO-^*Wza*~`TPHT9+Mh#KZ!`HU9TAR-` zsk@hM6+q!z)~6(7;*dkhGdkX0+%a2^%!&SAwPExp>O?NA8rVimiSu$*xIb#>_$?LW zO=!BNn``qKB%a{Le=sVlaqFIIKZMh=c_PYTH;)jMQ7QTJ|~V7nW1%3vjx_Xx8@|R$F^pLp+h~UBu#wYaofO)gm)C~m_N8w^)=G0L_Ny<+`bRH>r> z0144<)Aeh6{Yvh_6_svnp;_Hne-sP?L)i& z0QP%UIVGwzg7RSP11X4bOMt^3=CE#!V;g4E;I9f@w}CF9S4%1NNm2LCb_Rht13mI{ z#~np*WS=9y98Wg>2!u?(6Rv5ohm&e-ecQ+LVD`o<56zl!I{qoaIMRGSWn*n3>F`9* z#vschPVQT1^=yArTElc!OGaAOt!H$w&O=GhnuntO>!wdeU6&sSMP+e&5=&0;9X>8vVZJ$x!`F;-YR?Qf#u!1&<*>1N^cb422<;W~gsmG;KPvOSn z_x%kc9&)Gq6+a06B5Lv8G*ezZ;PYN)7cZ1#AoL+iE(jO{j=T!z$Dbr$cD}!MYd=qp zYO22@C-DZAeQn||5bA=$;yW9SM(#L4D<;d3-fqG=9LB|lcwllmSA6bKOyx?X<7Th; zJ!-J&Q{8-ALK$D-o)w749B;eK^9dw|Uzh=mW1nim30=4J`Wi{}tLkT-I=H@ zA1_ccg>Z~^d7v*(^5hNNjvFL!D>$bA02hDU)^xh)XQ6na<4c-J(`3#VNp}>j<_VZQ z#ffYXcwx>vo<&+q%Iu}yi$CI?hPN_WYPxLb-yEqC5$#YVRNjm_a_V|#JCxM5bkPdh zre->H9$msM)J8N=$jpjH(UaFB)bsVIa!*Vo&!PVS3M?dt!WP2%34$`b(!Ji%5s8;O zfzQmRXeT`}?^MMe_5KYqI-+vlRq(8^%_NfOsfLa#gS>6Q#xaa>+astHQiDzF#ggNZ zYS_g*8{w^0=4~qP61jIK-uEhuK-x@r`9=Xeb;Ux2W%wWO{Rw$ypUl4h05SEqg#0I@ zc?ofG65c?GF*4qrtf~R|l<~2)l6w+F-=Ie7@Kci2=et0^#8!T|z$635TH20!wpnzo5X*5Lw$@V7 zS^*v~$|W-LPqy6Rw3gzTDN%U3&?7o9hHbH#rpRNG!Cwv6`H0@#cm!0%I@wt?ioTiP z>-W`UuuDy>GG18;Sd~HHivh==$9i#g;*ncPS+HrbX+9Lut;OW1o?#KR%!C=F0FqDr zAZH&>deQL3ADF7=mRc*{j47#HXqK0Dw{aaDENoB!WfL}b6P|EYh6lZ6>J-{iPvtbi z;;mNCpEV6eI~&094WM*qExsQ&=*y_Qd!qeA>v(Wbf6ZS@;?$%@3ha>g5wi~^SW2J7qvGezo4 z!8oM93-kB<7+;7i;l&PC-4fRmUn5jghvxb=SjQXUqj*^2t=-62NkL zE(h*wXk=SvTo}mdmklhEI0qnxW?nEz8O2Y=L~v(wqqV)!07mGFp+b!3JoWy*n5xez z>dP!_zjy<|+ODaqDrr-!DQs3rF5WY>aC5+6$;iMS-j&MV#Fa$pidfev8}_N7S$Kxd zJ55QXl0+`i%%m&E?6}|Z`~AJEZVM;NC%?bg&zr|`iZBD=ORWp>6He0g05d_%z6i4= z$=ZCgygIllNcO?cx7xCUlx4z8*?&^)Mf}lvHZ-uE{{RIN*5w#nTEJsvI3=1nF@x=q z`d0gXpKGu3XV<9w{{X>R+4MJzWOEuf5Z<7;>t^_0wfNmMI#3djP1`(!}Y6Ul}RVj z8DYvTuLVo++r`?Az2&nhmTOsNQ8Y1}7RfjSo=zBo58AskLxX7I$19_1@vX~gejC(o z7t37#0K(7bNYSy}HiD%AB;??Ff;kn7)4%F$x1;B%H1PVi<{_Rba9s1TwPiF6ZG6u`= z=!^SUVV>ODHM7ju3_d|2auy&nlZD4Tcl4~>WZFsi{Vck1+oMm?^y?o8=@&Cw`SL^N zdG1+;^MI>d`8c%P`0!5;-6fpQl{ZubWAZiywtGDPw4(N#u@f63kcU zz!=Jd^~O8Y!c_Y!D5kco*e!4^)6H$^f%AdafywvpUX*IKd9uD*F|Ykhc#S0dGuAZg zLATB^2^ixnt1=!jz~p`D4A+%LJrgW0INYV#@g?f01#*8zzv4S_5CVbQC?PRe}$42y`LsRtq%5` z56v5708V(r1B`VWYbQyYFTz3oCrbYS<1QnH83S98Oebj)5(sh!LxGHQR*iW@W>-8h zt*l#{bBT(k#V%DhbCO%Ga0eds88Oi?l^WN8yi@S5%jT`Yc{fQJ8xg=ecW0iN0|yymNpOpirl?o$5%4>Wsg_^$O`Qa~*1R39(pCQ>j$ z{KJ(ej2>$)3a$7wO|Fa0*NqW;OKLRG&!xp~u^6FI5;TlD^Uf3;5Irig%Tl${G=@7| zUu~BiZ^O{)8f?mKmP^D^uqqL>Fys<_GmognZ7h1%W=kgf(N&M|-teO{IwX#wPcP0b z^A1SIa(W)sRf}@y|wIM+^f8}Y~@MLeQ-v4dzy(xv85%jo#bvM zLr#`eo+MZVC!<2YHqtpKrzwtm)hy8>adqqHBobWDIgPOHBpddUPb=yE@lno8Y@P}9 zIbCfGk-V%{J>+xO9-iD)o=V#a7ouk8#4-FL{63!vVsW}<$mzy0(;RoB%&SPM#P4i} zv%bB%XwqR9nY;LGh$A3_)G+DSy<^UAPqSqhqd|(^`Ykn&4SZ1l0MC>D|_$p<7=o-=3EItXI97!yP}-%GI#>Gaza|_Bpxzx{p+{?0AWWgll#>i@x^de_q#>+#JXIbB=F6& zT6M>tBy+_wJcDPN6cr~uM&bUIY_a&*s~f$i_xYJ(m%+(%)}PdrwbQ@)f5V1Ldr>|7 zcFdwU*eGTso(bvKueEK%;bP>K%8aF#-f>( zQS5@y?qiz&09o>mP|7z9Z2{1j+XK+?_XfRB{9NA|$LetZ0OVu1NOLQadiSo`?Bs@o zgCCiWP4Wt-h48%cj~#=OM{Jxh>PV z@6IY7$6X&k{v@`sHmL>9vfEQo2g;1$6%|P11Fi|`eGPMD`WnFJrTBbYYnB$ax}0cP zqU9(T|CxULYIPY~EpYYqeS&%Kna6)2aAYqpJRUQg zS1w0v?Z%Z4Y_wemQx=yK+_lZbO}66N_Cxb>GnFS98S7mbRYd0X4&_9qp`_SZ-e}g> zI&G|0kzNS6P#wWi0ps&^>MM7&&TfdED@L=_EVW%Q-`XYRl;v$rzyRzZ6&t(b7~?%F zH;r~^vOgssQ1I>DuDrKbHqbqc*exZY;W;@Z=dT^{*R@xRvdT(`e;!%smb&$&zKg0& zJ)X?sX$$#HpL53*S+$vgRnc#?g$E+~l4Q%?9n^J2v8!A3&;77bMIG{OA$>D^m&E9hxHYXKP${C*)7){F`p_*U}v1&-y^TiY-aiGUGE+5CX#lffKk-n7Gy=C)Q+(S7_v&@`*B2|*T_r^Dvj z%8t;&z_Q?Sr1$jt6J6X>XESWeylrV|;k`)?izS({zqd(k;&u~AaxltARmN~L>0Fs& z`Doq_(A&dzHrMtIr^RM&B8Yz!yY2G&jE3!x?OYR!i`qJ(`6?KAlGU>^G9=oE25C4I$}gX zHi6SQBi6Xm-6LltUt;k6o{8cpblqpd`W=>}(VL4qxNccd6CrnH*sPfJIL2$WCbZ06 z%2$tkQDdv>cax=+)S6YXb+fs(gvSzGt_m^EK_8eA#&|siCG-fY*y`UMcX2Jm@yBs- zJ6%mFjBb(JB*s9-2c`!YL0HY`^$hz`A~~q8|`Vsm(lzhkHw@8POxh%p5{Dlg?F_KK0d$6mr9Cq^8piC44ui z_MPs%XTt`sonTaL#S5so@(=sU83tLl>9+AXYdv=O>0`D}rf zGKGTd0O3PtoOL5L&hj;<(RwAk9j9BzB8__F>2o|yvg2xn-c*SACm)z{Pd{pyB`I&9 z`Xsa`)O5{y%Tm@Bdl4m~ELSS-kjlk|42*=a3OfOjk-+O)^wTLSXw_`==x!y9-hLu# z7xLT8rQ(L_*4YHO!1+d4djfgtYq@;gvz@ZhXJ)o*A}sgQ?`_4eE}C`+7~r0R*l}8- z4*XPsde8|#7@!a7Kn8#)0)Sq^fJy;q1G(maC)s_fQ{MR=M zGqB@7FFgMMTI9r z(<0YxWLS$lS5d?jC5(*xxrc7vq&5Y0V#xR;*NXn@`8l#;T-=l2-Ii?uf5ATtu3?zj z>J4$_rH2%>vL;z!X(Dt1OQ0xZM3L~wPg7~3yf}3pab&y z9My74GEs2+C9y%q)VncjyU!*sCMY6`OLgW#!GS_KP{07(gMdK5`c(Wq2ReE=OX3OP zmSv7*h|Wtn-M4CBCnQw72AOK8(?=P)n7(%`d&(|-GlG5it?DW0#@kyYejpfUl@7*K zeX?Zm*vJRyf2pgtqKL@+XX0D!QsHL4D+EAe$%;m3w-{Jj-C$j zeYK<$=~|_{cX~z14Kh!X%g4-Af1fxYo&X&xu=zCA#r^*PQqSkwbkUvo_Q`Fp55uIA zhYHb5CRe~b;E~@QM_l#vt?<(PMtN53j?g8!wz-bx+2*#oNfnZ4nC=gsl#Enme#Aqw z>p>s?08scu!17!)ceWV#sUtBv7F-fjs2N=QgI3(3UF))c4DajFQ(wZRj_m&c`ND67 z^LDea21U13&UWMGZRZ|L3CcmS1{mx8T9AhX;Z*}>lM{P4%w($pq^{LV#w)X9H1mY98wj(4r z{^Q3UwRmM&G0Ig*U-8+T;PGUNPj0`SkDl+Nir(gUuq0HGq9l*Z89^*as)r~xc^G9)A6P!QX)U(h zMPk{wNZXl8FeN|$`s9wi`L8X@-0n-*iMi4AO-wE1b~=1Btohv=fRecc6+3w7LHdfc zT6^e;HjH2K8%e#e)~;ukHuC4d!6?LS1vyd3;11n|b>nTMj%=D`Q%$&)m`CRMfPA@8 z$;Th2IQ=TwVzxwH&GYcHOuAcnFE0G%wUA;4G6Nr%mSW+0uRQk8HNd0uZ0t^z8drw3 zOKYo}xM7wXgBz@Jh5WI$G6vzs2t7w}){vIilyziBiHC_}TctXjk?F`tNn?yhAC^HM zH*zt-?0&ecrt&V{jiRx>mj3{9tzn?PrE<~E+oao+OsNT;-M4h(Jo0KHxjGL@&i7U- znvcUofi@5WAjS_)q;tpHy-V(b>e+Mf^@X+D!*Ot^M7RwisV6zkeT``prM71|G^rX^ zn-R3K^5SzaKw2_JGCJVmyYZ(8>t~&n^Oe0AC;p)Q7spn`Tk<-?zDQK09iH6wQ>hK7I0L&DHE6{HrD>e(5oC07ali}4YbEqFXw4P} zTf$*?EC^ho&f)9FTD9Jc%~$Zk_G>+AD|eS{b7ffu+{n8L1OhtpI6Zq-YE4NiHmi#w zd}{^1rQ%nP$)aRch8wnpaU63fDo1WeAd}eV(xXd3#j>|?r>&zP_(>#55cLBrazG;- zalsr^+9Qn??+V*NbqaZaZ;i~8s@#mW?1g0r2@DF6&vGjasXf2s-x2g?g)Dj|onU8l z-6OP(frO1zZhQbvFr)5Ct?@sCqxt>*#yMBTa$d{t_c0#}*#z*%f~31&_|01GeMO}Y z^XF?YByo|s)bZ_8JbyO(Z}`$CGgRxs{&rVC5w&L5JY{gP3x$dX@(~$H>G_X-{eN1{ zO5_%i<5t$Cn#R{b(}E?An#|7JGfgS#W6`{tr*w7eIJ-IpH(crRABzO$Q9w}?d( zZ!2(jtE&QV6?=2o^&F1Xi-T=zUtWz=lI@z0igg#$^y^q`Oz=*{W{uE%s*Ay1z0NrF zHMUuCN-JJ}r{DA`iaeWgrn)M#_{UJauxMUbl5MJ45EN{$U`I@!^sL@lNmZJBD8<<~ zpk5toL%q{(9%Q=-^GfZKz?=dbqaW#7Lgg0+*__ghl+h7qrrT-$CYIX#87Bd_(W(oo3bBU^KaD3W@vhi_#ZqG*!i&fH6N1B`A1--GSeuPkak?9F6y>qTQt zw}M?+Bf`vp+A21)ueFA{MBYt&lPdKmfNdQJ+sGeF@cy7y;L_C=K%Xx zRH4aIbaAP)?n=rH$Kl>DW10!!mIx${Xv>eCm=TfaI%c_Frjmav){dp>V%N;Kvbp08 z7U%x}%5~!+I>UV+mLMPVk};lr!S)i86Xb%z^=bhnpj|~zwmP4#SGGS*ZDo`*B))%(Sqh?I&YV$h$4I}xs8xQ{Boxu zuseZUPH9S2x~5|YzA?WxzuBBr|$m% zeVvLCSNSj4vi=}=vRxz{F5W4B;%%kba9e95jw5gX01!Pp3fDGAd>3DIVT&EEeoW)= zu6d-k)*9whBbQbTTk{rnEI{qedLQ`xDKnqe?}=|_89l{!Gm#GMQzo^9Os6jcQ$Z>iZH^Urytg;^ozw_iG4ptZPGZ|^OX6v z;AbYdUQ3l8g2z!9c%tpDnpo^K7rnVJ@b2-bO{0Pvc0Ok5#dhQ9;LF*ac%xPE4w$-K zmZ=2qXK5*x2_z@X*`83I}@U7 z;6?yu&r;r}iq35sLM(;7wuUQc1PIM>x6Cb`quf?pk#wExd!^}f{{V-_shO4u8et4d z{lV&as!mBGNR~}n>dx20aB1;QXS{QTW%*VxKi8#kK{qS#Zv^#& zFv7%R++Uuc_O9+o{*8;P0SE5$R!IBs*rjFj` zXs%asNVBLUocF4>>d8`}#0l`4d>31xGC;&KpP5Mddh=D~;ReOg?(Z2Dp|`{(i9!z0 zPhYpzjn;@QmKt`s1;6;{mhM<(%x>24`H}|4N|*ElxUJy{Ridq;uXp2ZZ&sZxAd(v! zc)mzNE)f9Fe^Zl_?^|2!&Fr!0ABtD{MxS$Sb8TmFIDw&pZgz~GPBG4X>i+;4rA2rm zpp#t5@mh%ZR+d*2?h3iw4o?{Ej-KYTa_!F=%8Np6IK#1KVQ#@&JZOQIVfWtQXPF_VGv=hCC*MYLJ0^tkl4 zOQtUbz?mU|u9Zu{v|A?bPU|8 zBu;`!bF>U?80Ci**19tyHMkPnOumOmxzu#)IIa|2*j+Ofw`brDr-H|6`Nt#=N~N{g zbIygQ#dqKhjV!+#au3{ zZKsW%ZOYmC(J7GPJQX>^HgEvVQNcB3tl9Mc0K@zJHp<1JZ5Hn4-g6|--`g3)yo?y+ zz+@nQD|fDpI4u;MsI#VlVSROREV^yZmvFLw8aSj4Z#g506FE|SzyuO=>s_h~$}n3jOQH*C3!yPuSlrx^!rqRpaF^i?LY^u0Ke~=0PoOH1ppcV z??4m*`cwd^0Z;`L06nMzqz6g>&nBP=-hf`z0(PJmr2uxI4)p*(dI0)R1ps>DfS`Un z>Ss*+E7cJhmVHKOY$My(1-!@mZI2)Pss6xc>G9EKo!=Op(v$mMM8f}$f!5_#uwEO^dF2tB`Q$1_H; z?6_!p6t}_WxN~Qv#2MwhWcgG9(SOW+s|6d`r$yVr*LHf}#_3vZp@T1Q>wN%qA2X*;otPF=?B10MPZX{F{{WKp z@f9;c@zs`}sQ6REJ}dCz&2MX`$K=iMu0vbI_;{QTM3DlK>V2!FMlTy{wDw}$l=#oi z*Y`PiT1$<8!@91YVRvuwSArXxNNxz*G8WqLgMt*SzF!Blh&$DyoZ!-Xe}9pb+Jw`6 z8Ah|Z>M5FXOpr;nqEq~vu)z8d+-KjtQZH7^OpLL&iS5vc=H0pDlOz6OmB7coHv{w@ zm8zFb8PT-<5oz*iI(_D%UDo8 z>7pj!5RVJ62m_ClCU_w*Gv76YE+LNT14lWwK+*x{uu$1d z9#`f9x)xZr<9|=g##p4O*Vpp=%I}P|tBYH!%Ovw-QxXXs26yix<_ER{(jRfr+VZ^Lq$Q>SY~8F zC}0lagaA%>&vE|%YL!JvY1&Oj&7m>Ec1DfOk!h!q(rXRGHLXRi9ggqgu??0S1pK|dDqJMU=DZUcPvQo>Bg7X}kde7nrB!juZq5kC?!Pyt z0IcP4@?J7e!Mc7JYZB`^CDTuG_lXay18v>l&8{v7Ihrm`CD{_+NeCX_D4!`v}q z14uFaH2`EN=bW0`)ADk+EpPL0>+FpELV}GY{;S*FvbXpkuLXyWqmu9jOV&?`Q@Ktf ze7N-)=iiFAr&SqmdjA0aiu#vxj=t>}Zliu$S>{OzMjl~1ak%Xpu->PxJ7&4yu8m~f zvQxvtRd$$dauI;qHwI7$KQDGYeQJ6_8!lJ+jmL(30j}yR3PW){y6HCY%6!H%$k=~x zmLTn)*R^fvp!vBqTCdc{*3O`p-`$@-UTLDn>2BkVqq3dwi}`|clDX@^>Fr*mpCoy) zbU)U7T|TF29kPW;;Vekb)pjTIW79l=&IvxXm;Smo_^g-wF7X+()}ge!kI%N1(jmRJ zqLyF@^!EByGh$KMcx1apzwuv4xu4-RKQOfLBS9c5$ir?2c5>X6!1O(9JZ-Hq(^gb` z8R4hZJVWpZ(!+9CxGabGcv9FS{;jz5;H`Do`Dyo>4GE{^c*sAyZz+>xK<4fj~`|@ix z{#1+JgR5C;S~N4=+*_n>%%T}cIpwewEncmI_ z#L=rpt~n^&=dN&h9`&NeqS}vTUP(&16x|}u8;=m%hl9*9hTQ1H6ig7q8S9hZpGxP( zu4z|B^K}a@ejc}u!Z|$o0gRF}AjSrGB=pWZd)HPdsI9Y`B%Hb?S5~%$*3Rizyi>{| zLY>%yfse7RJ|c=z_cD0gn~$<6{{W75;OLeLu%k!*DdvVF^0$#7rdt99B0OhpBj0(^sVeY- zPC9aW`qxxtOu|T}uK3-y?j-O>sIHr|Qi~6VCNbSY>;k&DeD~ZtFgXMo=E`XYvwqX> zzAHl#MvEca88JwLPdPJzy#d0UoM#;eBDn17qOGI&F6U9ayfZ-+jDVRuwvd(OfMvq` z+zg+3jopex{^4vq9jDsF*qS@JuVu|Jdm0r$l}0w(z!XNuRv7IMV}%1LkW zO4ki;6pW_<_V7mH2e&z>e=^s<+a~C)c$32ymN0_wA=5nV{%FcG=L0RbBmt766-n}k zYel0{(qxx|v>TZ9J7^+w2`NU7P@+$e=l)xa5DN7KcEQ1{_a>4xPl|GW3Gc@}e(y{0 z=A-bYcw&!E!bra==3ue&w~)hg0h|sirYoL!!@{GP{J3Q=B|BQzA%^F{dST%#v~)ot zXXR;vsKVoh8wG15=^4gbe^KU_q-nD2@+H)U9ZELKFq9uTnHv&-eeiHQk?C1dOwlpl zhddQ)pz2ZT8qM{yqBdeuN^Z#`a}su(9&z5WQRBHACcG9w$zijNt{OOYqk*zE zmp%E9+by~$Tn_qy{*oA=g{J`f>|TJ%FVn|wb$}g zwT(7ZxM*Z_62$vh78@7=xPMXitYyhMeVfLbv^cWTuAzH->w9?~-5U}jfCvD9z>cJI zo;l*CpW;hIHopUVEq1z1ytL(*~ZRb7bVVBgM~%t*mt+X)J6&I|Hb|=t=tm zF^{c7<#3k0VQNMk+ZddGy?<+3krBq5ne3K^S>XPjdL?OC?6VC4Hn(s=XI>Hh#? zE5iON)b3}7))=C@c97-eW1YF^8=*aV)_AkzwH32WzMmaAJtE_Iqv_WgtT*=nd_}y7 z;md`{0fK@*U(?#VWr_|;Pr=6=vy2=g=Ey(99}iw@GTKQLk0eEwAq-1{7$+sO-`=qG zSSOLDwzc{i`dqMur?2ii(=6J<#GWVAWD0FEVT?22VIo!|*bEVx=!Q4(az77W(HP{& zz7{p-zuftQ@OI|+P-mJsi~?)Yo^xfECUP4-yb@}jrym*X*?)siPdkmhpG9llA4~0L zNxhw-Ltx>hP`~quA1*R@0P~Lds?HZU%h;GnD7Ej=p7?i8{{RQS*CUJ(8%Tf>LCDJy z_Z6YBBk2^ICs z=@qFA7&jR>;|8Ro(eqxlc(->`&a&L!M|d7sUf(Fu5PG-m^{giLZv~>eZyfQ%GfZ7P zvNz=NGu(f^Ya>G4;GJ(z@a^xM@W**?AoAoAa=;&NulwS)iJK}K)}d<_y>i-7e}RtS zngwIgPf_~SSVY(O-Q9+z1?9WV1TzfC20(T00rjgXFw!s0qT9g*rn_wzxY94M)7y|U z6raq%bO7LS){=VJY-*m1t-YR`G=k>N^WoRN)*U?v`d2()n>wX7lRIAc*2luyJf9hL z4a#rC3m-4I@&O;-yHZI}=gGFpZnt)xFTZ>JQ&NUK4$j}tj!oz0euX*Xa3l^m$*ReS zr{v16bqkqqB!bCAwy7x)xm>Vba7i4K&1H6LLv13#Zm*b2Hr0o__vZ$v<;7bxj5%n! zTiWUNI&_ek?hXCKg%S5+Ft`{5V;xOnJke;{7}_JeUkd3~*6`ig5p^tM7YaaD1Hb*N zJZ(v6oT{BNwQ%h+L>^{%(Qt~Vf2U7|wP z^y${{%{(%_#hQiM>;f{MUgTBY$^@6mswCGDX4ymJNG=MZH`50=^r|nB(+$|l>&kW$ zTt)_@%Z=m`B=u&`f2BmFarzY`Ah5L57S10kR=G!JWLFB30tPZqOk$xrTI>;8w6aLP zRkKTKv2nIeH~j~CykeuaMVBuE__FUzm2Kz0n$ab1E=WrGkxGZvdV}sct)Y{Syb$AK z?;YvdSBG@T?R2|)TbQn6^Bz$r&NI*D1a10rSCo?Ig%d2ln(AmRi!Hv@P`Ql&ILGsQ z)onh=sw3{_45*OfVhrRC^>n?+Y?ko+tg|CY9@GHxz3UvS*s^2W{{RqJ#T?LBTej&z z63FM*r~~`eVTsj;BEP9g5Zac`O0WgF<085utFo<;^>PnLKwwyIUgJ2;0p3=Dgnn9- zIr)j_6&nVld0;JcyR9~P;8_-2z}B|OF_D4E3noSv+!3B@iW1@5H*vI3+QW3xTp7#~ zt-z0DVVYifE*Fde^&M-jGUQ~{774B=@kRSs{{V*D9ZD2clHn(pHzF{8cWE7fJdQyF zuoXWPXjz7Dvy)8me9M$GCryOl+q#L+Z&J(MsCaDa}idBDax)gzHzC2ZAUZE};O zNBH|j@n)r|J>Ii>rrS=gu^m3j;K*PlTPx*^?_h+MWh5%{PipOOl%2Dl(&&Lt!+Vyy zYX#MGxo;5>yv3Q;7|R7=8|FXE+r~NI=Q!(C_;MqXE&c`YQ(s)q9nO<+3dYYKp>O7} zc((kfXu;o-4=M=c3diA3ms%~&8YYe4{{Rc57Zz4l^H|(O66AS~uek|6T%a7O1Y{k! zAdDKB<4HQ~z8PGVmu(ppG`n!UNXb33{*}L_Pln2Rs`!l|=hLlpoZ&ze04M{~wE!9c zXaax-T+jwM?@?el>p&GC4FGrh)B$?*pcA*P0A_$H0JR`WkQD%4{L}!T58k8)-k=Bj z#Q;zTekcRdfG7fh!hiKas636J=@7OI7V_#cf&T#Q8_QAu0O5^~-m=Q|M!46L3ca`h z{5)y|Y4YTE>HYKi)(q7;X2ETy=~|YFqiI*|@VcR}FAFgP%VKh)Zh6iRTH%*_J7U!w zd@tb>ZY0$;_?p{KwFTb|^GLvDR3Ag@?^siPnpd%3@h-o2tz9$8w%*lAFSDWCa)`WZ)ci9dnA#aHX?I%VxRwqir4SmYd=mYm0NI-Xg4CYstED z5S4!|hScBy2;}FQ=FGa0zCN6NjIK@6GN@lLU=?*aQSH~)u4@OSvfY;d00LUd`kI33 zvxLqhWkRY3c+UiO``0|}JF}}2_cmV$X*Q6{b*9|JPLHgKfJOO2nFsM>7~l+$>PJtS zxAfCXD&^F*{=ZE%`4#m^{5IpkI&_d<%N*A>x6|6oG)h%*vNe?n z>I(#hP)`|Bb6qVs+NxIm{{X?r__mt%{(kA5d`;mkC&ckw>e^qxCB@vb%`CF9j1~+S zvEYP|gY&KcA<62rljrlN-{0TnBl4~iUd0OU!J4+4af4*@%M|gUNEj(#st$JdIeY>= z4;VF8pRp>Q(=Ph`-M58&8F8lAHNC{QN|3;~V9bPq&H)`kVx)SSnI#ysyp>y*FJmXX zx-v}ZB%Pdw+)n(bE4$QjMM6xAvVq!AEr9^8<;F%vc`L`Ts=MqW)1~RpH1I}{#_Xzb zGDhHzexshed(|IQjgl{38nlB|ziW1i7>~p@9LP!nK?C+8Qd;fAWuMgFk$*l!)zJbTFdFnDz*NhDU3IV?#pARw;YzrF`v)y|Qx zBSP?H@Rw4uw~S&fz_?WThS8IsTwr6`s=pFN?$a*+0Elr&y7D_hsS!ajnT`Ndjo9@) zj!)XUeL`;{RoxhRX1*Q!A1eMEBDC?#B6)?Mb1698gU(N9q*&3q)_9s zmEF#m8RgToJD-KW zOFOh}sV9~l$o^#kxHt!|I2kp*NlFoXWl!?^{{Tif(wvp6N6r2$(&4wVlHx0bxP%gl zKwYhd9H|GNQ^j**id#ncN)&dn%IwIj&RYl%A2tt9dh6uqnMYS-jtcmwvyZ17nHFM49veN&l|bNA8u<{ zC5sKcf0xmmuP$CIYx{XVYw^U_H#*5_<&p00AI+9$<%EQM{0@L)f!JcPhTXrvb6lFz z=!ej))>qo-$1)NL01SHaeF3PQJrM+M-W^~5o%|-&wZigzUBpvc!@6zRk(cqjK!grlmW^9vtR4(K%!6NX9+K ztszm0y3)KA)M|ZzF+d-W3f3kD-)jILRl6)Ex+KS{yJ;$>YgMTUY7XM^mcvQK*YCF zozk58C?N-@%qzbi7^+8|o0Of)?u`EDRJFL$CeyAgGLr$eL~d1wA&1k_x>V9s&U!OD zm}IoOXk{NdA5IUwY?_j^SIrs+;eLw_sd^;3vo8X2H(VIjLOI3)oR4n(E0fee2VN9t zUM18|{{Wx#8*9lLJ8LN(Pc1`7k&Fd$GJaeP5HNB$#dE!<(m)-rjFAM7kP( zkg`V@9&{o?GIP|72K5|NO|oOro@(}UL*tE3-ucpF1g|8I9Ayb$z+|ZCFnU&UUnzCD z8|J61j}G`QEk1eRT~V~uHtTH}3m`4Av4P0jl6&Wx!cyZNK5OsxHc?Jj;WIghQMh(< zXXZRs>dAwQjxZQ@;{(^VVAXVLn`WE%X*`9mA)4-4C*g!{r*r4|m#`z8`te#|)SPUl zW%8#*hU>&yb(Or&Z}81{`;n47BMB7nAC8BfeQRf$30!K~n#CzPeH8xy5bLR|-dYPL z5*ZjGC}Xur_4|Setg=mHc4-K4Ec3%U_+Il#n{!=hw^o-ixZ#-$s&o1l=i0Y_{wYEB znt!>HYvRUhr)%~){x{n*{vAtq00vtNguLauZDek}crC|XE2A=h4OhSNnmO>g$nV?y zGX=A9#aHGaFd5Br!0DGq4NC4COI4bA0;6U41eO`c`quGhJds$|H8~@&^X;}Y5}k}m z&coDm>x$AX_%o43f-Uz9(wr+Cu^ixkb6pNfidTYT;2O^I5++2Bc=yLE$;Lm*djp?Z z&U;jgMAbhHHb` z!Q}*Dle^_09;6>ys=Kw(Hi$nNc&+tmW12$-<&9$U<70rsCveEfBpylY#T*}!IR&1r z@C9NLtWjKuXEFiZavd0sc=QBtMMR;Z@s%1^g}gwT!%1x^g;=WNmc_#W0g$OU1LYa- zoE%jzbju~HMXKXhi$R7e^nl z_%*9)FiMf#vfD8N@ zYWEr~#B#DpG6DQ}i{Q6W$777}YLJtJxf@Cx*Ar1)KFe2{4M8_~av=pcQs<{WgmcYx zaE?Z%j#oKiP6P&{;;k!Be}vPLO|iBVkIKY1%rl(&^Hi2t$5BPrIZJb7uZQ&kt6Rvj z#veIZAs;f3azXkZPQKNAa_6ZO%MKexbK_$*t^A82c)-d9WyV1{QhuVjr)cSgK8pw8 z{IOeUmv>3|)mW*{a6lOPbNwq^GD$XPmOQBvJ`NL4tF+3%g3M)R7-vzz$EnT^D?d+e zT)(NOsig`W_@BeAb*n@zcq8vNZl$XhfR^DC8m~lGBb50Fq!>SpS^m1nhF?|9G;?FvRAS^ zF0F5CbsTq0VGLa zw=F9)5S$3|Fam+==~#Bn(xh1Rdjn^z*j-szD(JHLWs>E0A>kH}W=dp1hnl-xVBmM zji*KM_k}!N;plDb9io<0Wib#Lp>F4noZ_@ec_`0TT1KVeeKJiE?=AI6WF`wm7~c`< zcOL8Co|T?iQZ~aLO!o$hV+JO=NbZ(A4=lI*-}8Ul>0GdyOzfOp6)zR(urG`BnQruZ zYb_?`WC4``4svsza5(j@wAsMYS}J}#i%!4SuVC<^@3OTAdqpWRIUPy^*T2ocJ-tjx z*$8i@toj|GH#SBqnF`!lT*!VwgYyDAoOU%!qfXh^1pRGjNB*^-FGeia@1%zzJBLz>VK9$1Ymd?n|(GB9O9a`=Wi@sp7rr44^ z=gUF{)%xQVt{KMY$1EhDCRH6}iZUc;3ama%V!BR$CBj>U}GkOJtK;<+g^l z(8(UDeRFn66GX7=LI}ti=Lgh&^{qlGircY@Xcsp&PzbD%1e={vqy?FO%t^*QI^v^- zvkF z#3?a}gic6TJOhdVghrF%;Te=<6;pyw)_{Fwbsdb29JbKNta3|@+bWV*(JMxcF1F7c zb`!MCVIW*9T#cq#K4T$Jy-ytAax2ew(bLHb4c41_*74uz&{!@uw52!5I~*uD1pfe< zs^?llDPGTh8`EqxN$y(DOlh=|k~5;;q%+DR04g&OPXuo$qj4BL1$JYL*CH}bKkzo+ z2FrJCrNg96;q*4b-XksC7jR6M2*&~V05}93jFLSoy8@`y9CK~5$*9;vs3}XPcZkIC zY#j#W+qh>qAauq(^U}8{b&lEy^z^Y?dv&u!*da(&6BxlEQ~)#2Pgp%ymdH_D>_n-;@^`HuneB1c>CjS7%Ym0eF5k8%1 z8lOzW5A`SYu6({e{F~$I%$C~U&cA_MEF_SFo-zTfnRVG^ZB6fdNG|^XIkzgPPCz?< zpf$&z<%!h;Mez*x8i#~!E_}_A8OV6|gN&{eA6}g+ne8Tyl7W1lRj6*QGZBwLj%xV& zvneVo63XuiM!c*!A%cO%dY`$j)V!FsS-%gwH>voaR=2Rzq1@9kKgmVlMQfO1&)A+zsU7f=54L>k%U0BwH4pcjO#WqPh`$V_-DuZ7L)`o=$CDMowPt1JIlAm^rx?z8=Cf^fyc#Ip zi%yN;?OGTG<>ibP_GLz1=6@?WBMb=S5;2j1P}IK{@>)DoqUEIcI(Tj5HnynI%F)DS zx1CgMAOc2mz=B6T@toB-O0cWEfjfSXj)>1IT#(`+vPiP zz}x)24{oNms_5rs@9@YOFBaj5Qg=eQ&QQ9Xo_II|89npuS-10F-pwQUO*iq^RF2>9 ze^b7UlXUxSVJb#L$lhNk*-1QCsTiz^FWLS700*DR<8oh5zvTJT@V3$7mf7G|^BQN4 zJ-Enizyp)$1zRTFm50>dyhxH*Xb{71F^w8hk}(5ovjTZNczQC!EOhp906js% zzC6W0iaUCZdZ;ue4~O}94-Qp*N=Z%W7D#eWOj#Z4aM*? zx$WzNKQjgN$zBJgTi`(q@R6^yx|Y=ecfVd=7|_;~wPZuNiz)yb%yZymu^-i_t40~rUW@BM3BGxrT_ zn(+6CL<}l-S zcp&FF^-)~XTwOM7zGOiD8EP_V{v@-uxspGJEwC)|6;&8Km0(u{fs?`MR?3rHkb|d0 z?~kI3OYz0YjhZoXg5XLHcNsa`l{^5zewnU$Cex#2>65yip>yKRMFp4^)(}M$IP*bB z_KbYKqjpL9n&-&|`so|Nnl6>$&kblXqidR#oR<;}!q(3W%y`BKB!lZz;~4I5^hMO9 z^^QNQEdC#xOlf9q15cH0R1NdF3%S3_yzV>`&jW#1#W*+r0M0u1DUvd!&5U(ubS*OU z-0GTb>PK|^y2qI07#~wGzQF{?{lBCv%U0TD#aq5~a=Z6^ETtj-W%^aX% zl1%am;~?{l^ffJG*Td7Wz9szT$EfLRbuse@-8H9>#d!R!xPMyj$&UN-tNJs89$qQG zXMfaz{81)P18Vk>#2w~C0Kw!FC|-Z~xjCx(hfryK@BNqb>gJ!{U+BU-VQmJVtIs4U zh?!9C#~Z?6;QQk>&wnx3TC+RxEz-Irs-4>-k$a zFrfS9w&@x6L_UIHmSH5H!Q+s)Klb|6+eA@d&?Z>#EbW6tBuNL9vH&y39XlLjo-@ru zC3ai9KdRUZ`K;h1M>{)8RaC~f;dcT!U^9|BjCHJ?S*K-3ThZR#r7_7gTb*Mn%p*i% z2rAygxfM%MC$p+}O7&&4TZ>579f56ygpOMW zVNtU^vByw2rKYTkG+)EG?mXxN$Vd_cx2m#{$=rH%&JSL^)(t*J@p@&i#&EQ-MJh*f zf+F_bVq!&eoZth{4Q z*G8D$&F@x*9~SsN%I?x>J|^59(a3-hNcoh3-=PDc&2dX{*MqJ-oc{n0tY)*%W? z&4wu+Iao$j3Sg_}J$(r4n$8k@tuBpPTw1e4vhbz2N&JbVhT1n)w;2pDd0-RPRUDRSF`s)hlF%3HYOu5ppyHOlqb)VI;4{vFAP?$#*E21N4#Vo7nF6&+94 z6|N52Uu>p+lYeMunQ39VNB4y|+-z8r;ZT z)EtQzc0WQh_Nn0s#{5}TIpdSo>-r2VyftHMtHY>TnG#ftsZjhlJ-5j}|R+OZ4|L@BK>a_ix~@ z4(X2Qt*lDZ&k~&ch~@G2I|tNPZU-sUpSSYPJke2;iue8zn*I^#(%pE8WrEkvTWOI_ zTVVeH@pj;v%hqnRZRvco=&u<;WfqM0mv+FVoGm|=SO!&G5Hry74Rd8mu8xdvZF`iv zRSBVKhEfp8ZjzAPa{mB6KmF?U;T{;{7wmB4mn@QN+;4MiX11O&95Ur{Qa~9_Ip;r0 zlvS9_7gupUn|pCR%4v5l&n>OGGp;ffP6u{5IN%&&v-q#1Ps3hIr-U`vlfc@xgCujw zaU60Tw-K^3MsisWcpq=2b>o|H*~yj)^k;qyvC=fnXH37=t^!6UFR%a=anPT>J-Mk* zWnV_ycXMwg?Vh1>(511HFbr_&0l~*!dvJ5!woJ*5yi;(x&LV;i1BVt7E^9M_R~=&Vsla1(GG@znMDR(QV^m&*Q9mE->a#1`=owzIZ^Yi&O{mE|Mm2aT$r ze2d3kN%ier=<``%xbQu_rOuD3NEacTP zA5k#N7zN~esRru`5U`QZ{^!qNY^o_S^h;lHaTCnrCH-lg*H7)88vp2 z^JFaL1di`1!j7F!Q^jQ~j*BhqnA5a$mN-N=4R-h~u}%QM&M-Us)nx?Gv!VvmcNk=i z(*dNn&klP7>w#F+640{hvR>Gu%+8Ran7pKZc5cXCc>^cC{{X+9PaGP&WTdEq0$oLcNG7z|Fh4ZRULblW+jN(RXhuE@q zLQhrS+zs>UV*Qm~G&XY~)8=}kM?E>=hTZ{ch;ce|;P$rrbW{nq+11Kec zVllt@eJe=gjJhM08upFh2!1C*)RNmsWU`6ibr#u6n41PRjltld-JRJak_qO$9B@u3 z=ajZtv`sB^medj^3u|$5ZX$(1RERfKQR$l6F;VEFc1eEqas{X$N&qXoZQNHpWOkt_ zi14&>Tj_5N%${Y>#7gY=#^o)=a{73<%4c7yl9G!=#dMruk6Hl@NEUzx)}RGQ5`bS? zfE_3U`uflX0J!J90F(hh6avr%0DjZ~KokOYpcmGFC<1^e1DXK#pbpdlKokHfLGzFP zqa$zs04cT%7l|~Rb|)Qyb;c1utW5_#8N*EO z-7}xRYUR#!V>MkGcGWaXs{&NArudft3<3{cz3Y*0M^RO~(`LN5NUh+KcMuYas(xo< z!jG)>a$AdL}9i;p}@GY{&s=grB zVv<3Le5bXDsZ@0%somK3HH`lN{f!~)R{TG$n;ZLU#bf72hhq{{l0h4{4nfI0=D24H z?CFg5eF6AQ;~hi9EB+0w+C_J6*7B1xCK#&re4H}jfEWW99eUMp0y8gyAuSIKrPpd4*DCm@V)eGO~>0H=kzas3RRtjwcoU#Tk$)>pcC zo*Czg-X?grLzVK%9jAc=BW9n@MY4D@ILZ$CHCew@-d=W=r_K6~7PKTcEQ( zm30)NL69EaVqs&E+xUye{WZtw=R8)?reP*SO>}0AMDi0DL%-(gGsy(~jb164S)zUyYIjpy zrIp3o+s>jzg!x0tkU0$7*mKF~JALXK-B~EVN#iX}EofTl)`}wp#dfk4{v3<>h-Ek< z2RZ6^tln8E()~?VG~;Zn>OMGzeSRRu9ZJm@tZ~c|>0hc&D z@-fz;S#m3W{{VU=Vurqkk>E{I<5L8&iN|*IA{{R|C3|gJ~-P;Cad5J)qP%hvBQ@|Xu`xBbv$m(wXr))PBUqdj~ zH0zsU*4Gib-F(jL<|!a|1m~_n$nC}|&N8Zfndz5*!$)8tRsIx=#Q9(nI6^m%ziyo7 zt8bA%@j8F%KVMnwG%pOG8I6C$t`$H7Bo&B$rbG4>>tVMVYopG}s!jWqPr?=Q<N@nuu88_*!*X{20H^A{rc(71o}#IL zZ>ck^e~Ek?r$)E2yOH8-CFF%SG3YoLWyW|o$@Hxx=iDj&e|sqo3I71}ZCA1L2D=5t zg~i>o+C8M<0<=t^g**nsXBg{_NFevF6&keB*Ei)A%Y!tNy4|Ze1d}3T4pec^PMP{~ zTgSU+JGOe!?Aj>{Gsv|o-dY47ju%xcLXYnhSvCz-JC$RMV0G2Ccz0t33HA{)*n&RPZJebHy zBzIsURRsK~#DUL68Khfj^L_99et{)xitAs0Qsv^ELThghE$W+BGKhrD81o|}A=@5L zRNsDYR07soUxw~a`JcqZ8q@OrH&ByCbx+~bq2zJdf?@~7w2oFk@+aULJkz6B0`3P4G zRQLK-py}upJyc4!07`ksZk5}PsHB~ATKqAqYF0iE)L^#0L2Y!xCbpGwybwbVL)Y}I zvOzg)))I6z&~DsnQA`*ki9Eo2XCo?oGmLXsHX3Li+_-aPrdBFpwKfPf$X0eMc+J1v2tCGfG zsR~Z+;DFJ)ZQMs=o->?REULHHf1%SDn^vB&Xx+nU+w0GZD^DV}Z{ixnmhL$)OopND$Qz-C!2)mkme0VP>n^W60Uy0KzTEp&6_ok=5P@Xn^%&Y5AU#xZL$ z1_Q4Q2Q}zola)#IdD){F+*fRh@zNPIW=o=kCG1LD9E2nj&$t--)ibY_rS55gu2&x@ z&2=jnr11Wxvcna?xrRGbL(n{@V3AL%l1M()%@;|_@;aoiN6ua)v6jnL)S;01?`?AM z0uSdZai7|{qe&%a9M;JX5U;}cY71ELlY&6%2;`o9&24=YLtP_O7qZ6*EH}Ub{{Y^n zx2F{2;EN%zZ)UaBe7m+`osT(6Y$S2THB z&$o(21!Zu@zo^gaiqWd0G)-Gr3)T4h6b5T`V=mmj@CY3+c^Mr$aahjWbZZXHr@@d} zX*wy^Vw_EHG-)iRUJPmm2*U7A;CaS-V~XRY7s(xWX+@JU`1?9S|UdYC>N(e5H-dppTCNZ_2S706NFuHp3pshQjtvoyr2 za!<5NcyjMi8eF%Rvn9o>((Q+HpD?I9PIKEny!WZb69kBEjw^ zw^%K%9d7U%c$audGl99kD)a*Y_NwMv((mu`Err^r;Os>H9ngaCZf@EC0EjZiBpBSF zuOv2epRG&0ar(d6dj!@=eHZRP#ee=H4xc=YwQ>XQKg3*~Mth2+UHq+=lHHcY8VN=wBLlUBL6@U%0)WlNuol~9qKp&v0nQb*95vYU=1*LME^e#*RRd76Dv z{=Pq9_kpc%Ztv#RH8CSdtK`N@0tOEtdJpSY^qAb|@h86qUbiH1eXvUg9`?d8>P zwAr^L&`M)QAmTtrQhRq5(T_Y_<&E~4&6Cr~LOEm8SNRUEbeJU4n@@lUp?#ajQ-DT( z=M}5N9vl}&OFX_O#FpOAm4EdWsV1TLt94--fgX`*4YI2KQ0@$_N59U1{VSm^KYxB~ z$vfL6{{RAm+3GXGmgZHsi{eVR&R;fw!0QB-)BkrU|b;E?Fj`{r>>Ij_O#`YwtrXaB4RfvH7RUw~dxH3cwWzFa|sH z0=?lMy_6}f% zAtBy{NAmh{-nWY~lB2G@_^;qO`g%BhM`e84+#f0K zAZ14$R85_ru;de;b6sa6MS=WJtZF_Vw$kq;MvBeq>}EuqW4{6|WCtK1N|@;p>Zr)L}r2EudwV8FIgH2c~;gZYGhH zqhCG)vWvmCLrb$pxp)>uofwZYLD!MW{{X%zJWccz=+1RmKf`qhVUh%CV*%RTW%Cfq zcrCjm_edbK z%!;ayxrW`??hjgvD9*N8O^hvb@i*4$M%RKp!0sdSgZ4ZT>59IZ*#}=NE6H_!>m9q# z{2>u5li1_ar9ys75!%;>rPA)=ySuo|GM_ih;PvVN&U5vv^KDfWaiU2r?QeuO_Onkp zcjPa~gWZp%X8wiZtl%*q)?OsrlJZMfCN{~E|NCzwqb6Tj|xU!A=o3DbjJFNpwxU{>t zNrO((g17Jy0tXaayc z^`H)dfIFVl0i2FI&;XzhN&z|cpca5Vd7ugb4FJ990)WDQ^*W7dcj3GE)Mnz=Yd1cg zT%pJ9EoYT!Gi+PYj=?%giDzyUG|&>yo_CSR{e^S3YIV{g_;i6JTuC5l93G*1FZZr& z^+!fB`Qc`3d-x>`Fse&uki*ma{i~5J+0o$Ps`$}u^;DHnj8Ms#*$5lX4%Q&?$Lm{0 z-$rehO%KI(J}hIVTv*EUSZ3-8M1Epmp++x`6Y~ywW~;T?Ka(?`AHCCfqUYkIvUiOH zL|RH@Ko^duq2rO*)X08Bm*LNbF1$^td@Z7&F`#)2jv_={<0SMwdUwThWs8&Ijd9Z3 z=-Rc97g+c_Hi6)%A!ZAUjYd@7^2v^N51=DGIpfx`o<)st#oxKSVa=&!{SklsDPZ0d zxW9P(n~CLSmhxt2X?Bmy!14m}Fb*-utNJvfj#BCQef9788T!`ck}>UjetzGXAE9`a zt$bl}WlM1l?A}bwgzP7@i;{Rb$?eImEIy^;^$u++lc(+Zqqje$S$#T+yNb2%`4j## z(XI8p6IHObXyJRid35`Qb;v^Ch}@4wa;G)uNk%f~4%4Q;hy6|*QlB0s8Y}F-qqeS#%I;0ln?SI3>w$TL&M2(V+G5p@2U!_{r+A?T!r?j!WQ49x&?Nv;b zl?F&<$5EcX)p;!ti_eE4fpr(X%bS0Y$0DO6oB^LvfJ<<3oK_R0?C6KGHxI*`d2H?P zG~tXU*ixMmYG86{=T81haCJ^S&G&5Fq+_RS<(ybWtB zylPu)SR0fQHjv2NW01cqk7|^y?2Dvio-o(j#6B(6b&c-O$u1#g>LEk1N9Z&6uUiy& z!6VGeE>dOJ@X98WQHs|%5m|&>HVE8udUM~cME9c6)f?hz0#6Q&i{{L!gb|&CBxI9= z&tBbYnt1Lujp34|OpNg7frO1C>XB@T+^CN~Ho!CbWFJFVWAv_DpG?~)sZsnLoqS8< z*sQ;WqQMl=hX71KDdn%`U7c`o!4(;OO)AE<{l6iP(|O4M0PKzb0PD59(tJjS8Ex(+ za%{|UD?B+vf>@u*3icdsBC~nhjMH89_wD=|EEOm;`tRyI{5kQPY9ijxRh3`NFk8bT z0(XHMA^!m6Sy!H)HAkoQ4b*aZrTaDex*nqfNzWgPf4%gZmm$9BdRm!86zkl=oOy1wXm#eHjqiJ4qBr%yhyzEmT zU7Jou4qKdYoc89qmp3jvd@tUs`8qyMJg-~*zv%0!_+_lL$uAnu&5}7;UPY0g$&?f3 zMh8p~bCNm%jh0{7rv0l%`$R84|SLEQ4STgP+Ts_w_Z5oLt1$hYl|(mk80jig^_>aTphv$InLvpp11&$QyB8w>+eM+Cmk;S z_H)*5?z}^DHnpl2HZe>r?QMq;W3)T30`r^ixsN8|W8*;!h>B%QSXx zKg3+hhjE?M@q>;>LBw=5yZ~ymfyrIlmepI(9%Lh_+PxI#Oi|$-cFZ$Q z^in0cGCXUum_GR;JBaFbp1-FRt|{(_XFF3AI#GrE_m<%X)eHbu4Uk8#%b&Te zCGK4pPs7i{9b;c}HO;j4)^fmJDYpb!azMatp1(|UT$%E^9F@gy`8CHRok+E7n$50{YZ<$e2h?P?jeZvanSmWWHijqktuo|LTid0t zzZO#-H#bX4-v0cPntj%tsZV>R#UwW-5Wa9hn4FM0c0B(8O4cqjlf~cg%w^6Ij$Xf% zEw-VfPj>n&NEEDvOdeJcus$QkLARGPPF zv`v3aw!E9dI+cX;Ln~ZE70fKf)v}DHPJ5Lrk@c)Av}^3jo|Ap4X;%=-=E({E9EL?d zCnNw*Odf#s?OFA*=C!BZNvv7iO>u1rX3pTKcZOe3c+Wq*T|P;bYmbr-S=YpIM%F9= zGPF!z1dKN$ZyD$T9eJ#0CjS5lqFdQCo+N!Az_*(H+7>o&yG6SJjK#4C1OEVf0gpu{ zwZxpL%Py9WmT#?}myz08Pck{=mM0~?=O(+FIYzg08(X_+0pSlL+r3?EB3r@w)S5=F z?;Ivjq@BGn>-zLHj!0_FApOmsQ4g(n7+h(MZ*K*>@ z>Ae}Yn}2Z5WR0Dp<#^;F&r*K)BC6v^Mn<(4iG%(fM+~u}#@dW=M$Ewu2;5uSBzCTO zzy5ANQ?5UaOXyfNUl80KFHN`6JkKu2Yc#A^{vzb#Nx{s8Bk=K`Z7pA@0v_hJ$G zq~+)MCS})Ui(73ffAINjt}>8GX>iQSH(^>(>NcLd0^Y{A$u${pPSgF2qaI1gs%Sh# zre02CxK+EHKzUM z8NgCF0hc{^J?jVRA1jYu%-TMhJb1}(-4@+jPF+P-2?p3#bc1La-Htxl&TFeCFNyN_ zIPqope>b1(MeEuU%i+i^;>h?x=7ouHUC##}Oy;u7i~j(UUfcamuxDQxx94A=<_oL4 z4+pK&M6z8&5}W{jbOa2r9SB}e(xpyt^!$?A{ywE=2xRpYaa0ey7DACe$R=d|~1}UJ)d%d#Ft$ z2nI`K%EX`!q=2}txV>NMWf=HI)8MTVT@%HZdMJ$f+HRevK`Sc|RzU{$0FPI4e)Ykg z{w02=ej509^$kx*eLq~#bjb@zJ?@~_Qx+tsh9oj$^#k>)dMtODC;6B4GptRo$byQ( zeNV)9Qr<%2Yln{6CL;h7hLH3?atH^WIvVy`y`E+9TPi<@vRpw7Hc~_*{ux4r@=gy` z#{~y&bI&6+%RWidM$x9UPW}Z+ZxUQ2a88p*xDv4W4m&CDT{tvjofZv$NV(GW4NG2> z{8S4UoQSG72T_1M^ON)$t=Y_sD_GWUqPn@Ud_|}{ih@{MAqZe0|lt5rgI+V*7y~ z%1Pp^G4WXAbu?uJcl zqw97O&8sX@D?us((yWWL#y!VsoDgxlGRo|&O@BF&i?E*9IVgkj@-d&T1#a1bNssJd zc@)cf4T^vg2O5Q7GE?PG|drrH#gG7^45n9b6h+~q~fMjfLNf(Sa92)CU_Bo`<`@aHNUhCF6 z>*4RCflC4M@0V}q>4Be0aU$6(;9F^}JUI&8$K_qTj`N`(mGjM7t3)Sd3&y{OQ~0yQ z6Y91)hr*G~lSm3rvIX|slh-}1s zac^g)T-<669Iq}#xVBq$*t>8D9-MRQ&2!|$o3il9N{asgi1Zo!H>ul8Z!;?DG5O7B zyFV!z+HupbLtObWB#onyvKo8qSS{XIt>ubDVkAjO8O{Lv*C)YmNVAe8E#3+A*qR4{ zBv$iwxeWcgW2d!M#*iNC5Z!zf&9$s;q$7EF#t%+gh3LU7nABGy-dxneBHK zN0G1z^#YQPts&Vlaio~yXzXtlb|@kcxGux<9sK~tPcOEF$l*{>_I$ys=dz@ih{1l^@ka9RJ zj&VpfuGtLTmt0YE1UFXCWi0S{rWYmrm&W3y#~9nrI3uNcamcAz%;U1Fsd)2DeMZ`7 zeDwG^m(93>K+7x)aCWEWVh%bCilp<#=(2+%t$a$u#y3{iH+LE&cejk<K$bM~Wjt&)>{3lK$#5;qR0p#yH+ zoD6b(Y7}4cb#tQ`IU$4Ym!cp)kVl!G1a9mcVrEuc3S1i&WJ>}yh~@HO*~HV z%`74r5D|`BpVVTqS~fF{b&w+t2`&14D_l!vFS6bEec~&R33yjo)L@BzGWJNVZFiH0 zP{G}C>5l%mt4=AEPh`jA6_jw@>H7AO6w~PXq+)k`21uuJcc35*ppY02oSMcfnl*n? za?iyv_)Ec`;5rC0UEM|h0Ou>f+q}0szkm-+fW&992N|rVX=uDFwpV;Csd0H3k(rzj z75@M`u^qBbGmmb$pD) z^JWp6{{Y%kU0>*8_w&hXa}&6e006;yu^yh);pATDxfkUcUXQCZw>n0naL(4Z%4}{k z*b#+n_89`Yab`;-GRge1`Cs-qvthh*#}4E3FXfppAZG2D*!A zl#n`ZO^xnzUZ!kLFlwLWoV>! zRw6CDBjl5SMtLJW>ooYaD4M^WahFD;@iv;*hXwrBf5S-K&@^PIAQdHhkU{H?#MfGq z$qsHkU)nhMym>e&cVBG7<UpYFDB<>ys|z4VbpIuK3rva^{xdkba%M#ME|Py`?JkkHSY;&lGy0?*VkxcmgPW%vW5T*4xZrGG~df-L>A3oNb#h0+C7wP z&PXcKvjC-#e4s9S@%FA|nZ+b)@KbG%H7#dQz0hs-eHLjggflmuBYf@20eX*{gY@M3 zQc{$lrw3cvF@$3$3GU2u#Wzo!zm}bKBOq+Vdr|s_UX3PSu%$ z+oH6Akb=qi!vIQ$2aUM^pQpW9V_gx9R^quL&*te^0#}ey0>7 zlUi;5cl~-U+HR=^rD(SrZRMo4<>{${cWc<2?FS@yMpGEm!Ju&l7{G#oy?Ayt0Dk z+GsA3j1w|6sEdvJae%?O$I1u3DrE%IQt8##``C=+nv{E2SN*F*4~+FB&^#q`~C6661$kz;BOq`$QeD|Pf^XtASjTA!>guJrc%%sBt#&XU< z<%!^d?kkrZc{*QzQ>sp_vTEWr@jJt5Z#mPvC!|B>Nq066mV=2UU_UgE#~pHTGtFxi z@gEiVSKa=mGWj<9e{@qkcRX5-uWe${Ev}nk3N5vxF#ZH*<_gCkG>!S)k8%e=S~;gx zqP54q%Mam2gg5>t(k?AvM_6KXzNETzUSUc{gNr95wo zh^*}7{H5ZwAo@1hZcovd%TImn*jG|ZB->prer)7-jtO~x!Smjyad8!@d2T{v93Dyc z&21Q~Fl=vaF6ei^Ol0%kr;QYSo}szI6h_N8zol1>g^%>-kZoDp2ddR1snKM0zP`AY z;us-jSh#;;N4-yqVD&QzZ}yeS$h#$9QI5Y_s?#Kem7h#8Dv(`V?I)-J*HZa{ELwKE zsp;AtbnQwwt8YtDe_X_zoy6L{3WW~%L^T?ACqH5qTECz3Wq0)y$xmj3|bP}M#j?9wm(e?u?v7Ik?p3^EmK zmsl;y;}L=|Gw;P_-TtMTq(k`cRCGyTPxzZlD{t_-YnCOv$+Mf8LGPEsk7cgN=~71| z{Fzpfs7nT-vA7{*kRuFq1o~G~hZShcvR78oAh@1cVVPrgY$~zpe!tqQ8MG>gwh%Ri zsEOT~j!y@GYOh4Co(+Zd*||1tF+x9xB6E)uy{bWH^b66J5FTw`i3<%v!XGIuk50Ir-dt(^H?x-*C_1c{Elv+G- z)~4%Z-3uX%YH`Udax@I8$7c))9FTswqpBu78+YOTo5iMI+gfUAKA&>|ShpRFtiX&q z@(}#OxMfM{=;~WWe{%uTH5Sp%C6OGNlaZ7BhaS65IN;)w{2D5|K7jl_(roU0F=Cpg zo|8tGX6_`FalMsxsbGCRZ?Ag73*C9Mrf;f#4DU)~Z{w*R!bqaMGwx05B!klc_Zh*fdU?C!Us38Hnz5IQ?qG|}j?u(Y5DTnp%z4gOk5kVz zX;acE8(o#32J3QZ`pvw7BncjOZ~k!H5XaNFtf2Tb*Mn;Kk#S|lZ9Yi6PvqN$nI&;7 z0fs;g@AS<~qSW}U-(RU{O?*C5)pz<9zZL427Hb;m^O&SmEg{-IP)-I;I`!hW^%-1s z2T$+G$?34hR_3h^JSndxr>DC-a)!2y8D)M%hX*VO`WnBd&&oSpFY0CLy*~+B^7ZsO zMR#f9I~`8ODK;Y$5)?RQOar?IoKa3bqBDZmh53F$Smo)Z43gi!=j=1ouGhm+>AGH# z6fW|+J1e$ZANN1fsX6}u>v6@8&)@D}96$D)vgFl${={$M$B8EJ=Yg)Z5XKv^Z77XV zvPAMHmk`ghK7Q5LZOSSBr!6X%=zRD80H^I2{8#Y@Pco=BdNd~e_YSOsWJBw{gMaX@ zhVSp#s#08m5N$h zfUO7uRU-t+j#&EVs3)keTO6u9UYb12ir*#EB6Zy+4SvFFX9%-@_N6P68)vWfsFgC% z`AO{(-EDOEA=s#6O`~WWag5{lt3{QPvbW+N6ifaNw(hoVadNTSEGB$3j?IT9age8; zLCD2tk0j;UIWfjP8DELKJ0_vw=hdaPlGj&lU&x(G;1rQ@!Sq)Eee0u%&t{9@H2(k; z@Ku6Z$tA_z+evSH)345jPCld#-&)d&Sv+)P@c#gZ+^eD$*(L85&9AjY5>eV?M{Pz6i}`*6h+OVQZjk@IiU7&tnk{m_zPDqpnYS zt4@o?thD%3RGKK`jwUhRu^-2moE&<3WAv_GTcfUs{d-Qey%!Tjs4d2$B*rIpCAS>) zC%MO`de^~=yBlgA4!vvW;EPU%DX=7sUL(dc+j(8Qa#)`QWd30&CTdQcI zxq|Z6N8cDxoDz7?86CdnxiZ6#%x#VGbV%!VTE*0#4|KOs!xWnYESpkBBmCc&pS@(h zWoWdb;^~}kbt`=`(p@)FwP-a3A{EP!As^-*wR+VwP-l0lIzw)tAu7M~2*GkkbK0?Y zM3M9A^2-<-wjzuKjAK5zsHR1XH9KMD{7ghDo*7%H{{XdV2X2UDN5@SYh{=p9{J?=- zORW?*28w1-qswkdU^>*jB2geL+xTD;5n-L}!26oY%MQF2u(yfr#l*}&ljV_5Tz!42 zo~Hg8(dns3)tqWK8a32r{(CJ>=@!lBnka)baYn8bF>vU(P{CC}+&SE8amiN9T4fhT zn^wBH7dMc^?x4bEW96Nh#6F~YI4n`S;uuej~m^y812q;m0$pA0pn`ck&={yREPOhUQFuFw)eJ|MTMoz6O|bvH_irn{VK_)(4oLN$6ja#Gs2SU_7aX> zGINgII{uZ-nWoZbRwUG0L)G96bgq+?ih9t2Xaayer~-gH&Ax{u+PiQsJJ zJ5P#2I){nX$Lt9Enu#k-7K^5Qt)oE%y3}ZkgoxwUf-*mU>s%A)?T*W4l`2asG{`qb zODXova>?1%6+^4-L`;bUh@l*j&(n&c?6cA+I?PQK^if=7M&xCelZ^5}^{$+1jAZDt z{wCjPAn7`HhSie7(Pfq}!MB4U83%X%-2LieoqWYs-J7uo$E%IH?3}^ql#uyP{$i&v*2~dLOzGuxboB0=;_6MrL*a)`7P``7v(a`cW#zy zBXnJ?*dQz8`EiwO*3#n)6;`OrA1UYLwD0YIV=L4lnn@TD6uw?EnS)ws9~pn9 zTCysMCIEnVCqFZOfPS^dwMRl$bo@ruEv#Zo8(EB!M|$$ip-J2a3IX&3_pLEQl4xa` zRFL!V*IJEkC$hYN+*#g6Vq#A!LLLS=P*fae`Gs4L9T}-vF|KLR!E|DTh~bG)Au+KL zU~W}xjtTjWc?4A+o{f7&MmS#HX$oZQRT*?7ZESSv0S6;J4Nq23xab;vzNaXJJaAkQ zv3EukxaW>Y`{SG*^_zR6WQ$~e1=cN6-Jecd{o8je5Byk(A2NwD4h}QV<>XXL6zP1o z`G23f3nUe;RBJvH)9&=!61UUbODmO83%Nd78R~m(1OtvZ714$g#-AtpefymG@<${2 ze0lr!8*3gT&@|a2k5w?p@wWmPr6rPv89c3l>T4F0bqR ze}g6e0Mu`fEp9wBX{1_tgU-}U`-uf+iX5CSKkH;X;<~Wp=O(M844D2JPWI7~{t;Ns z;-ADDSkfT&)~oSy4Do@$2ldW7;1XAaMz^=%>vtmKGDBP}P$9ZO(2I2>>=NA#|F zRFS+i%(z8(x2*#Jk<6+>jtX|#di3CCxM{X^>a5cIALVL38oAO2qx@+X%Vr}2Fmcch zy#`OIt+D*kc<*e^cNr}CH; zb}#4qoO)K4zX?Nk@V2DdKjDSUw=*ie{lgI;ANHWAVM&yL7hHFK(`xRLJRY%CdpnsldP^(0wZ;rMX+bJ1@#N zNgBW5wa&S$MHQs8PX(o`8LlUq+{$i49o|@#jz=dwI#⋘$(allI_=jOEL974-)3p zx1_GC>qXa9vD5XdJDomPmDlBxLvG}3?u4G4j@8vD!y<6M>H8e9obk0k=l7zQt$1D( zw|y5vv1w$#WtRR~7#3w$0a4qso=L~1D+h~QAg#XN_WBzvw)xHV(M#20hgi0^({xyY z(5+r27J z-MeKb?@%fK01Btgw?l<3)E{GAk&UA%N{>)9Gg`>9%40an@to9EXpg8Zyh|6F7^y@0 z(QRxTr@4|)N;7WkX;$_?vFg&KXpPBEhZJ~`9FCf0%+uY3FN~h1t0*P1$=TmnkIq(b z+nyEq@$P!nqUgFTn)-_^2f~)|DgbQ$C7C)gXK$FE$AB^FE1r99&Ee6b{uFqM-aj`^ z)b#l81^Y)CK3?_!Ht)&&!#Ft{=Dhr`Zq?b@is@|IjqDaa7}O<6Kf}-mU_kkzbHE`$ z$veAaHAf_%-O;Lxl+x_P+S2b(y3W^j-k|kT%sC(t>V10iT=ANtcLv$Cej33&u9=jzMtle77S2IQ(O9)2ZZ$-U0TT7HQ)G*(Jsq}kpL285ZF`O zsN`2~rpX+Ok1K1oaQeJ*$MaPu(ei)zMc;yd5j9;F2Y9XRu8h{lmfvpq3Hoq7h&61o z=A%D7Kg|dy7su|Ita!^?6KJ}1suLZ>@O3h-aFM71{$t$aFY0S4JBnWBv0H4W>i720 zTFLN{M$Cz}Ih}w3v4U6BDCVbKB4u^6I`IrQ@aYiAro6D*Mww6vUBI4Ldgr;WtSxf6 z9GMj&pKqvNLn28s`NKc`)yY2j>s``HNu22<$&F17^@#HG8xj~R9)5_V_wuQhds(r8BwU9bw=R2BMj9QOAA&Ary0^xmKbXKb zmnRqm;OF+P9J`U%i=z2=aT4jv6s;Q{E#GNS%ESz-4DdPJ57cI+D@0F2JtxH)W%aeZ zaKM(*LYXaZk1cR;4$wb_bC7YzQ&;^AuVjyk^_%@4NV{2>qC`B!xDVzls^FcZ50$b& zsi|KPYqJ8?bt|tBT-@L4Z~p)jaVGaWKmY-N20aHA)fAGXVBPGDx0*f1IAS42M&rd; zQ#jsSG;gtRc&8f)7jMI>Xmy90!em({Hs=c5F;#8ZQ`xXhW0Fa2nn7NRHIIoOz}Hjh z7wKkVky&EAw~bgf3ERKbl$;QG!5y(!B&44o2DituuyrZy{9$dXTuXy>D!G>Kc1WbnAEp>_m_WUo~QqKd2Ka1EB*oIAgj*WtOd#Kf`G?Is8&J3mwfjn83)( zg^*`EWb2Se_NdEg{DT!g#C-#&-f4O~Q=2sMcM|M?Gm(svJ+M!2YOEeOejOS~PJf8Y zym7C?s_RR2X_b78?mcn9@AcxU_Uu(?w)j^|x4zS$mR1VoHttcu^dmohDtM_amQrzL z_QK%=wsxSYWcg!e_8kYkSw5mwuH;E;R`-x5nrpofFS~|&a&GNMT4n2V+eT`>zr^_v-EiJ)wlC6*tf0Ak$kCqulFrYr&>M8 z)FuGTWD@zVK*j+Izd>EU3JzZp``N|uW~1=eRbS-8KlL@@MYuW^foRI%v#MQ;bBFCsWt3cKlI_@m(n~HF0XU~-0N&7RV#wF$&nED-IjhkFr#JOseRl3 z07Om9_ji6F@h+L+_J`ti4Qk=8?&QIS$|XgN40UN3$DOOr2RN=gv*#whzqOrsqs9?$ zsyujiPa11#aTyXl8)J?YCEF|& zh$n%7Pux_?B1w?3w$V`6&YcXJE~u6hYI0hZS5^GQR0NC+@Gway{-!mjr-D&NKB8^S zk=`q`@qW9kE}d^-Hk+r(Y_|-rhdY^rRF3xEtwpzR=rR$MgPj6#&1+Ax= zCb^O+GE9szM$^x)UJp@PD)MIjg@eV@*=V{I&F-_P+>02n*Z^+b+ipAO7^!bW8MlD7 zfAOpRV_1UPITK>Wpg36(0VJ0s_2iOy>r}K}nkPIZ{{Yk8AiujY-nm&| zbCQ4ifN`FK+M-OfQ(HNBvKgOHhC540kWC}R&Jb|BbJNtE{*}uv&ZzW4_-jf!DYk}K z4c4J3X%%ohu)u&>pQ5P9$EoQ^r_mDX%`(~>%|lbuuI_EE)otHtbeD586(Nf+@`1(& zIqO|%Gm*96scF6wZFb|uamyt3P_Ct$QyXkQ^1$7Z*ykX2t8t>XS!U5~biWN-Nvb)! zyS9=d_fNygh98@;;CHMuwHVpc=~d)ksU1DN-PhtRo%M_?khCT{iQ@UAT=R_jf^nLN z#p#*KlW4F*;hRYG?N-gQ>8L9#rN5gs(MDEz@P>zR;p=H^&D3*P1N;Qrhe7Uo8n%j- z40==m?T%_mJVz2ltRhgkJBat7A@yx;&dyJSzDZI?A1T4we&Vv8MIACyvkLKLh49qn zxw(zj862<}V56VRM@r+!neYMzP72kx!PYJMcRFI#w!8Jr}Dj zFnH@sI?u)HR$t>6Q7A|vb_F6i<%*sQ9u9HEb*$+b@hqCAx#5j-Nxr$gCL6n$QZa6^ z{{YAFxQxhJ z;g9^n0YVR@YZjkn8f0b0sc>x?+2$?}4Uzk1w2n1)ky|5zHr?Zq{VQSzx;CHwA#@|& z%AjSKE^%4pp9D%)S@qpI*4sq2Huv(&b`I8zoZx$oz_fe&_EN z4rg6{`#DnZBtuLioX;8xk3=is*E zOVMC!opVY7q?myxo(?-9C4n$rmc0^6=ZwsRxx;&;cTz19_ASYS8#^;mmnYXuQ%1@QJSWDUY0zd z(>>exn@D6b$*Ef`GHrN^NHP_erV5TnBfdI{?Z=)INv3)8$0)jF%yJ~L2_kiLZiF1x z$=^n2u9O1zpaDP>0o&GqC;(6gUw>*6LPY}V{wJPkN=;>@ZGs5M42^KhmU2B+PCc_& zwB?eYOZhr4hBaNXQp)Zd*xpN4-vYZuymV$$h6B_NnH*-djFh@Dlw5l~UQR7+u5MX( zED=1+GmM1=kKX{)zKDvpkd`vZJ%yz6LiX}a3QEyG=8td$Dfa-1t~qmxku#4OIQt#y z#RQ-hfIhSWF$x%x00ShGiUZ6tEYQa+Y#KQiadcLoT_a-b(DR zVHNDrfN;5J(Fs35#~*r2$L3l#lO(E9RvDoIKokK$6(A}A43aU{fMKUEKv$oWM|2(0XVD8Z_+UVg9Q$Nf50kANFGD5FD&UQexa4{a z(jSOT=#B8^rEhVpS?tD2kH{KAn5)k^8lusiN6hzWXAdhn%It3>^In8rUQETdJ z6w62Ajgo)$JXeu4KL>wn9n?p8V!)`+(1NTu{{ShhChwzEiO&T-gDiSoxVU{cQVy2) zer$1w83U^5h?0col|TGHYh|+>&&SzDad`1Htbc7qDtK*2>@U1RefYA&3L> zI)Vu27#_l|-0&ui{(r$ov6A7LMxbPCg28r3dS|Zg=Dglg{{Ww7 zs~YfYz6rL93t28#AwFf^4;UEh{l131PeBB)CxgiU0Lf%>Yag8%7vr{~gTm0KoJ_YG z;Q2K@1`C57& zNFU7q08f9VOMmhy9T{hfEa$t_C%KTHHe8uDp5vYcbYpx>a$9yY(q3zJSsb0Nzc9%x z7uWv)H8P@+(Y3{J(&#YUThD}N3?-BT%O5+CHZ#Kl0MAFqO3C%3XuXYP@V(scDjQk0 z<;hdH5(viKy@)$bbJ*sn)R%(lnQrjEh8y6W^?9?j4DVf@X5Ij8-G~KpPq-CTjmdod z7U#$ClDfByZ0u|#gGN{$1RGF2Gz+NPh?_PUdLV0|P zg=oxjzU5Jav~D=TIN*;=QxoGVlhYX@oOHH`AH+LLy)xmNP_a+q3I?*nF)w;uRd>0hTrSx35A+sU2}y zB}&a3w?-S|D?5gga|sBx&T;_dpQ$+O(C3d@-(KB^svX%ZTH{yGR;p$mH?||0gRzmdADvV+4c0t>59kVqW=I1_(X=W;$VC?rs;7r z{AIRMWk(_~0ouPP;O9BW}BBkO!_k21Rz{arF3`~8e$ z<%!jpPviHCA-c1*@Xn1XO)xO?B;E5&$&rDN>Vr$Om5^@)k`f(o(|q@Va`RUZ+l@J*2ZMSPZ9iw`Gr~&Y&2HdBsUm23DlEa9Gz&+iyfAdEU#vQ zKn#c%obm|)hwN*fc^fX3XyK>LoeZ8FQU!n$<&mA;c5nm3mWEORBo zlq;Swo(4Jp42*<8{tIx`uu8zo5 zXw&DvZ70Lg-)l_`oUPLeEj_q44e9mR$#5k6+cUt+cljSix*d-4r11CjbC@4tYKL zRKq7cjuGiD$dnWyr7qh#jW=XB_S#!p*)-u{kK3p&>KAid z+Z2R+@+Q@Aqtu7w5BiOCHAlh=P0{7xGAbe zd9CR;+J37(ovA}4GS3Q0ZX`I)I(<4GwdrA!loXM}k}fi)NNC#9CA2p3TFn*XF!LsI z3~!EsQwQenyEV<565B^cInl3vDe4-wrT9|XrR|zo6@>%}lL=Z_OpvRyk<)Q1agHi5 z$CTq_=6qt>D?f)`D7Uh*(fs()mgVG9sf8-zqa5H9laG34i;J&fF*ItB>sI>ph16ye zE#n|=EIwdV=ci6RE1RD?v!{<5qdvE>x0_p&C`=ZtNk9u^bpt(ls7+ma6Gn;Q4N84V z;RLa)cIc#R0DSx%rH^8IaokkGPEB7#xTO}?XSj7)th`qfUNPAWqvQhwC>=jT*0WP_ z$eZxZc&TG?UQu%JM!u6tC56M4d1aDler$rI=U^XlYi~`NC&FItzroGwur|IVd?kP6 zoze7&ba*bshnQuSJ*&B~wEV<==C;L&VNZv2bLP(TIH~lX_$e2<6xv>;Z)ag6t-P_M zQ*c0)k2v?q$jPrhcwRXuN3M@b8J0-7%f+(Y;ypU%`DPMdEv=MDzL>}#JCo?6cOCIw zj%-q#zZE6+&o>rW!ChN_X!&+~TaUz##ZM*x@us(Rget%CY*1|n?F#4r0CRiSWMz7Z zf>rZN#{T~RGwRzL>r3+$zKqed5X^1S5Md)&n`0B~tffHi!_XS7@^v4z@BTf*j}>$K zZ|{D_9pT$Mi(8^CA;qj0R~Ip}{PHr%bs~(P=3#-!uP-e5pYWco zi-=@&1jrZV>HhOs#M#ix{4&;IbZ%stC57EnW>C3B5`2y8lY`rujvhmqIpN<7BgJVh zpt7S|I!#d*uwOJ@|&#Lv59i5(=s zJqId%Ipd{T5#y1i`IMBoV^`o?I~29Lxt2YIO@dC`Fax0aR`y^-ej?jXdEjkc-qD~* z-V?CS7iS#z;2t{msFJh{U%-Edz9M}&u5FqaV84&yZeudxf->iS=xa3tPDr=-6Y#cQ z3uMOblcsQ~)i8C6BS%ATAxE*TdN1?`e0ChZd_n;xK zWIC3!{uWW<7KB|HRmluN00WMkGkmApwR1{e6DJR2t`Ycn{wKbPi+Iu%D;U6L+}PtM zxvr#fp8nJzKi()ve@X!dImfL4zwhZlGSxKbbr=j+C4zPNdV}j#oD{UdmU#aF!aAM! zFzMG$u-bnbcetD7Ve9oD-nr!u28o#+yf@a@SC*FdNjy@1R|kRDk?maain>VAGo73T zE~K}bSfpirrezpAhicALnPhgF?(D-Yv}-JB)zti=UwVZvVAr_fCcV?_V_EIk0^(yb zxX#g@2klyJh#~JU?=AHfStE)OD;WZk8Mc$gO-ty7*=N!%qPViVk-Vn6j0Xx-0C9ng zR!JHQ;%!RG?#?@g)2!?zjkXtxGrfnd4NcyWM$GE<9qt^gOsF}@^z}8;w2B_>XSG<2 zPiN*z$A>awA8MCnPhZliv9z>JkNhPijQY*J*tAP{km1-r%`eew9QLD4oj#qU?26O1OQWXF(#0&Q zvM7z$aA>;Z1JEe+_pLHwUJNagFxXhl1-05ZlH`?Oj~OwR92IUb0nY~<;smcS;^Bzb9bSI@s%9PxfvMklXM9=(x z;(4yFA+d^BWw^VAqK@j#9U|0W&&#wiI|}o>5IGqK99Dj#FD3Gfajwof2BC3re+;*? z32&iKAfQtwz&%`a!2V;`-?y7LChyqq!j;o5`Ui(&u+=VQ*X->zOF77r*6K@io8iw> zzm5UU20F_0bheM?9O8 zwlwiPuLp*;SBL&_w`k-40N(!qD*ohDWOWAqg|Ms1AIz4xK^*RirBzPQr?xv(VoESe z=vHmHHqRfWT%b?~+JFTBs=-@xAaqb!lz_pM43UG^fM`k}ycCf~;fpl17UINjHojA{ zW+rmWxSlhH0}H^$J6AuZlag=2)9Rv>{-fP^Drj20$;S9J`;w&g+?YSmR?_@P${S4* zQw_4Ro(SXCtc=;>garT&lmS9UTD9DkcJ}WIM(;J;HsK#Uhiowz>Ojf+8qX}8W3J6H zMM>}2e8ZFVtqg^YL%JzE5(P*gd?|4EaOxK?bkqD*+uSO7dsZCaV?D{*51{Q_*cxt4 zd!0U_EpboSoHfvMhW`LBG88YjEwpuSVNrfU?D+><(~XCVb$ddswQdWmo|z=>Ao^|x z2imwjL)qPpXtHS0t1*>+T=Ea7JRjb?_V#thp@y|)9z2 zoQF2&8R^%Y*JK@|mPoXI9{8EGofA`Am6CWD2(h66hGcDrC!h=$ka4ST-@ma!TXb)fS&b#;@U<4=-4^ll~Ow z&lL9aqY$lOG2F47pX6uS2=q0a)wlHi4I=KZ&+<6%&w{PBdkANaWrj~I$K~832T79z z#=|&e!Ql1E`_?nZ@j7OapAONdLwTb3TSU`z`CXa`WZGtmBg3#Hv#8}k0DV9;bu50K z3J;==GtDHD`Y%vg6 zTV~~%a8_G_C3E!=h`&=dSjuU( zt~LQ0^mZQoe@diw)Bc6z=^4npxVw&4y8=g$la={SbD!I{wQUyJ&c^ylhD+FCR~)e+ zT#=vi4F3NBYL!o-EWc`c-1=IinnbZA5TYqn0$(-~a>~KD9S$i>wViwu;w$ToWl?S~ zCUQ)uE!;1eo^W^igO9h~vy@y_qVbiwW{u)}Ja8|UD1~G5H>$Q&vg8xgV1HWAD(KT2 zqcPMH>M7@FJo%#uxA>4Mvvk1(aB{c@t}|6c%d&sK^GLeFiJ~z`q!w_+igBIz!31>n z#U@;d(j)L)4r()5dMHo*dFxAv@;1%X*0hk^49XZ?mm=d5205VTp0p7X2O`Bk7`#;1Q?S`AC z+cm`bitS_D!2yGuZuZ7=?Ogu=5hT8*stvdFD6ZC;q`q3*d6woh%!=7$a?S@nyd31z zQjv7rNBRecwCxEYztwNVEg4B-2`1d*k~sX_a6sUU)*lKnspNfa8+=(!af0l$e~0M0 z^kVtdHcmpB1MD(j>{IQN(2jT&e}|7R&+qzuKj@;#lMl+g4bscP+6Abd;^Nw7gtA6m z)!U87YAF70)kTlf;#S?Y_phmUlhkE=Ql$R?PwLrH)xQz6%`h_9XmN>}P3h+xDLYOM zJ05?nVDlyTA@}(k{271FZ}c-~k45}O)@S*l)3v`aBmgls^BiN#Qb)+y&t5Z%rOE52 z{{W-^00rBPZ)tyD%(i|I_;P;__}V)SYTiiY2*%vDM%U^X4u_#0m0S(KQy64a{{X*+ zGb;4*o;Pdzc}4H>qHBn>>lmPf%XMPdbWBKNqWZG_&AI$mukoUpmyYaiDoq4&~X) z@aMt$rOL#YQMuEnxbx&jW=U??awKv7LU>T!ve?EeoyX!-R?|8yL2_oL;``aO-4QM9 z+E^Otc9up`(Zswvrf>l{0DAT9PgR@YK~}H$@;yF3i#GeC<=@4?w!S0M>}QBWcD8GA zaD$>VpOA6J;)<-qa7$MHn-?5BpKRsznG~{dUJ9`$NL(tm2Tpp|LC7;(a|@PHoS)|O zt0uwb-aYz+xhSPqJpTY{vQ|e!sP7|*N0{Uj&>EwIK{Jb7o8fSfA#JEjXQ-)+T6Rxl z6S$e8Q4m7;lRw18)h&d;Ic$;x z0y|=>4G>7^J|nc#1-v&Z+mh(-48I|T$2|2N!5?~L#V66cCXsD#9$aa&O{dz#6<|=7 z<)tNY+D)Wz3X#*e?Oa(fv~|ZX(AIPvN)H)$bVqX}@g>R_pUD1JADAAw=m_u9xt{eS zqA&hP&-_LBf8r?TBS=q;k0nsUJY=#1+-}G|qa0LY#@A~?d+C>p2&T~NG(QR3KHW!F zkWZ+*Io^>2jhW}rlUYeVD;n-kf8+a_!LD52QS1A^>{+~P;tP!?_Q=>d5y*hJDvU|V z83gl^4_{nW{YF{BQE_E(&FgqPsWaXlH$0o%7%w(w-@%d_mVNQcTnL@4${F- zJmabTE2d9QNgTSdHJu${)%7?uk2YItS!ZQtZ=1=Dh}=&c;~%YF628pkt4QYtq~#Hw zAoodt8ILYK{c5v^hB-B%U>}ck~X#v7_ApY8zU4nYIY7Y zz^ze_Np8Ld6q)eKE)DM`6EkkfMXRxg6&mDkvN#Ec?+oDfzu> z$yV4*z5X2d!TcsJui>;aOZj5CE0F;`NX>I)#ctPT*z!{1$s6m-jc)J!QtCrJ%et_3 z%eG12gPi8L)0A1gCW{A-d@miW8h)*BZ*^;O*M3~7JY`5$PnS91ar*k!xhB$W`64j3 zABnN0zu;ztEsMlVx6N%ok{gt4$%pN@GJb?ry&8*Y`&nO7rPt(DyglK2>%Rxs&uWrS z@bk+ok*Wg9xEa9CP6!-z>&0I@xi-;UQKV}Y5y1Zdhv_^JG)U@v*&$p8b;!>@r>9X| zI&id(@A**+;QeMReQkyQ(#%SiW#E7h1XM;;_B+w8*l6~!-${LIx8bLYX^b9(j(UGC zF@ahrE9AO=f6%WtTwiAmS4@H9o_N)oex|GC9u-77Xi;pRRD%|6ot7LVl!JZk{)e)Nn@cyQM_|vc6>Ancm_sk)SQ%gn#_?;K(v3S$F+gRK-rQ%+ zol~JZkx_DSxB`AqYS5nxZ?~oQ?rA)H_2F&*0Ay_6hnfzTqiMitx-42$w+9nW2k%~F zrTCfYsO>Mk9_|!dSiu1Q0PRGh?~I?{HSgl6V~l-~;$`{rN?%f^sZHfgf;xPnJ zJ0(7~xrxH|+B@4xZRb^ZN=yk~NKsg$jp_qdR{1#TY}~O@OzM z_1H2%>x@+<(oDQny&3+M6z`}d$Cjp9pDG)ogWvS8K0A@=zm_HINwaG$-g6|y{$nzN z4t+3tS9UCXEc5c@StyV-p^y@*8?&;aDwbwrfT{*bC(sPjuE7bRp}x7)b)=ZbWpeIe zd;kjID3QKgoMQv^HN}akN?8|^zcO%yaX!%-;J*^yYYeg9MP?>&WLWK`&zBbBJjW-g zByCht&}5NYV9MvFW9l%dB++gitDxl%>p&R*9G*RB4k+mzz=6n3`6DN(syR_)tYtpA zVF0)?%IW0F(GciWiBL0udiCq~tp5P^BApj_q>^L`c-qacRvG1v(OZ=BxZXWSAJ(X| zw&;!qapP|k4-)Ek7LeSxz@r$XNWYk5V<))pk4mOV+>1s!Gfx>?&7|u|Z()BW)KQ>y znPb`k{{Sx@l@2JBII-01{{Z@eE18)YOhbCay<420tx`}-vUEr;pxU}lCT3MYP~`x? z?b5mB@@Ua)gS|7uWg1VqO_K7?Ps}?Eeul3cid__GjVz)Q>H~T_(+o3YWUBuFsH^OP z%$mWG?go`|ckJ@kcZ_aT>wrGJ>nTf%El3w=yn-m$rwR=^Vt`3Kw9v{@CDqT8zI zUKP6V>b;~lwtB}VLowVl>OkYa0CXK{XX^1Fv9h6O;n@~Mis9316Y~L_5nTB_Rc$So zP#nIMrs=mJ>Q8fZ0(D3Z4t~F-PAu+nsuGPNy?BvBGj0sZ?UfAqDm}>WU1_(`kzw#z z`2PSC*&yBJ#CUC>V!6FVs9D$PmCl*Y!p$t;m*a$zTE`%AnBqv>e6A0u!RMTF?^c|x z=)#HHMBQl}qO8(e+05$%aWZAm*b*4yuK_|#$-~F`we8T5{4`oIy7C$;tEY}rKFp6G0Qrs7 zlE5!4NzMSRGRetVc&<9KuOEnRrq|`T*01gF3dCZ&xmlo`xCB1T+$&&=oCN@G&2jUR zl`>jYqfPNdz6f0gO-_3qH{q@$@_s(f)naHm96QD`t(;+7^AUi1*Q3uIqiDe?CSnKi z3jWtZ)qE=?a9-J8N~g>*JW?@N$amUFJAfZAIId{MlTqoKUA>WdTo)Hnok~Ooc96=< z@iR9a7Bie}9sM(0xmw&&tWl}>ELzCVd8g^xnX-|5iLP$h2GYlp>lx*Ez$`j_>BUoV zM@Bg&>Go@OkS3jD7!HdL6c$c%>Bp^gdPK3NW$LdZOmiH_?X!GhZGuLNcr2jwBzjk( zot}Hq(u4&7Pz3;eC<1`;vPNZ+Fu=TE7XasOeSQ7C>pzOQ@J7E0@aFm=?yn)5_T%BL zq`AD&x1GTW5l-j=pgjwfVaH%|RLMQjra02K|&TrYP}(UqZPh%58`$=-{^CmGw(nH{o;fL2?_zD$^QW7xR6RW zMPnqsS97{W0sg^A_4$ouCb=d0n#Mo;+ZY$^k&mendjo8 zTTyh39xa|=BalTyl8UxWVC3l#-VGbHaLPb|Wp#-G{Gc92dx4yOzLm}CSIXbi>Ggk! zM4l$P&O$R?3nhzrm$w#h!pS_31~)ao@dpo~M?q@5Yl_Beb$s7mw!S1RqX$t|W9t9WY>+(+Q3uI*)l_U$2t=rTp-0yBUa zSb{!W20e1WddHlj2GusUYM~iPC#1>`i8YN%@*uY?<73F+NH&#LVnXrRNjr0r2N}hA z`7%m+e}D9MMhZO-d-aMXwVRz@^>41O8cBc% zyzq!RARUDiXwAy|9Bqzil5L?}3?A95cd#_n?Tjpw+3v!f+du~%wJlcB2YD_H#h`JL zyKuuCh4%V?da`y1I2+-w14k^@%%FKwBYs~@Z7bEIAC8k7>lr)fznl9g?)69?p6^f~!J9dnFQFyzp4(TRAUS-SBir+27oQpVTU zEEs@zMFR?h*;E1g`qy+-Dmf(Vr)n0SQ}LXiQP#GMyfZmOT?*{lU&omqG-h17Hr7H8 zRfBdQ_p4-$trUZ)A5MNEc&+dJAK|TD8_Z2Lys@yn2;13$#`}UF&4wi77&tf?uQD-| zp3e6qqe!awGsHJm+QyS$lK_%Nig#qI5c$prQ~tGi!-7;omnQ7E{v>Ksd9Y4|CA@I5 zTgs|2$i^6+xX*5Yistnxwwcj}s*A7TrT&?B;JrG}Q}S*;E_Sqga5pkB%P#T!xxrvZ z86u+>4jd=DbwetfmpE#bm7f~;1+-XhZzI+%B82V{MEUbwdgB=24^zfRyYoXz@ivX1>i0*>zO!dt>M~tH+CeARAJ^8qJv@K*VUH}GN-eL>jz3dB z{aIwhmBvXw%E{eY-qCePbzMZDg2ocjmLHMH!C~)?KK0#_G5D)2`b+mXu})7D#SY~E z0AmU9uZVB_U9QX!NiL9${{RVZB9)KjpaQsZW_h2}!QYPx!mH1c^Wm)r zOtVKfU|vfatFU}*1St96fH(H}vy5;BUNDdRxA*7jQd5_W7aO_cjvI@S4BMI~F~EZ| z&O&7M$I37O9Ax8>n%%zNzwiE$gjY-3_WuB9DRk!5w53>#*#x$G zWL8tc^GEpp4RPmKCEw@$PmezoFAk~rf#Of#10dAi&e=f8#2A4G+()0ic4{$D_Bfr% z-$9MLuzvPM4L>eQ;pX|B&u+^J;qSz|IE=jh(qqKY8x<9My~uNZ0; zR^}(!FAo!CKxGY&ws1#m8oU+7F_9%EkmpF!uQf{to+y^$7ztu{1%9Wu(zJ23Wn&i> zmiK$qICtUHbQOzCx@3-!mNM#=ipZ$#ItG>cD9Gm(jNKaJrzCjs_KpSZ#oRv`CCkqv zNYiyIxa~OX2;>h+=*Kn1B9l*>vNubTJLLFzi}cuA?Zr~5l93H`tk6R#&rOY%&KQ5< zwh?{_4INz-Q+ki2ocipuVLfs7UH z*yg;1>EGYvcc|28rTD)^)hzWHFX4)7Xl^Hv$0=~dxz0&mm7H3S<618zChjJbx|4W+ zMDUKg;yY%%*RGgZLn@uJ>~qz+Zr}r-de+@@{NL!mp7c+53nlzb;5(gTT8mh)zk(%2 z2_?MB!Aob2q_3(VN`1fkFel+T~s-VMZ9i^&d3@!=d*124pmd?1UN0yfA+f{<<-yqu%#j}99;AH#es+;9uvZ>=c z`&~m(OG`^-QEZ|)E&=7rj^2ZfRHE9wgn~>B!5K(#kA1)oy<-;CmHU>fPx2|6Nl%E_{{WjjpK9u!wsYN+ zD{B&Ju}H6l#|xgOxu*VBnWjF?5(u|x>KR4?j@8HCXK_>W7C#fs@bDp)BZ&@ndqBy!pA52Z&zyFG}R*b|+qLl=MOJ$|&WBw6kJt*F3xj!(Dbnn=SKV{otYa?IJh ztZwH>BDR19jwwEP+~)wC5bSYp~0;&P5eg^ znPYKHnb+XfseU|6$qShhQeIfx5}+u^Vb26(sQ2qz`l#_rkxU!2d%M+i%|6*It_s?_ z$XYNHDf1q^#xhSh?_3SWKPx(^y_63T*<(?X;@kM4q~E-dKpy`9)~Pj5MWeG=(r}XSZ)M@aqc}URr2GaU(J%no*eNQTb-BNOlkpU>$kOI9GpK9tnu>vCXDm> zT64_=GfF}bf&v4#9f|K#|_S=8VV25^0GUcMY_6k2DG>N333O&DMPp(Jfr#~vHe zVRxNPyIwZY!igJXW7~vtpZcou(!0C@JcYB$ z?Tv^(s1?yB<8odT{thIRmlx%)F&~-(3@D(Sk%U2?Y~a_K7`tuxqt3eh?Sd;$%YW2P@k2T`iSJhQ5fkM>{PT(IsIkTUfk`uRDRYBLr?@c)Qssw zMG~{fz$iHZa!A;$_uM-;v0z8Sof|QYYdEv))M6vBx5MJ$;J3P8nIKuI2~AI z9!7dqT#;@ie_4@*z1fje$}SUN4V~x@2lQqHdsjAD+-T{=3TcgWn=o|%;BR0s54W(Y zV~*_GB)(cFZuJQ5E^T0Z6Fcnu+^@bpE2+sNi;H8mVBeI2GmL}MteFiBb;a{EOZY&` zPYJdF^d?V}^yJkt$*4AqVTzVWr_kDcFHOAg>RHVcl30Z=8%V`uQa2ToAdC=xYR(wq zv7~F4EajESy`JL({Emx4~W zImGS3$n~H+%8MjyjhqpVC=BDrI=#-Ah6q)zWP=S5R>AiT=rNP;(!BowQ8t|;d`i(? zUlKO2sKIo}8_vNdxLs2m&#?a~j4oae56|DW%CgntMZb zP{QDVRQ%ZV&1WaF%c2?Ky|uG(V)2z$-Shrz8rgA{<=4=w(B-D{EYr;@83yu(J`cI| ztYaEN_~R$-J5505Y6p1Dqd9 zuc@CbX5N*5^h2FJ8ZkA^gT|sG=KMIysXY9u4o)yh8TF}hZd) z2PEf?)Rfv)-auN~MvT5=c{cLLXc_eljBsmsE(pv^3XmhnB8}x`EU|*yNAr3QxxlK*Nh@We9!`dOY;xLZ`);F# zD}q{CL`|H#9Fk53lv4-k)yv?*qFaxK&iV-GW#!$qWb$ zk~sqhwmIW2Db23Vmbo<>{{Ta+K6ZUeRe~|T*4|ZsN>4IKh=YOb3uOA5>5k`THcdu} z3fRC#QtHU0ZeUe&>P83eLRV)iE7)}#I45>$Z^4%Tr)VqXSf!C5bBey1_GK5zqx)^y)xUVQQ z$9Z(#>Ja|$Bwa~Q4kzP2JSfV)EV^1-Psr10&t&Jp^T&>DOTahDp zV%Wd%AIn!|#&&{9+I@K9vC7iK?VI9@_=<@QE-@CJZli7r1_1^X1J54a{`IG){{Zo$ zA5s4ROEy;fAIB`ix?tM<;Nr9AB+Nd3zPD$NXcMFBb$@8 z(ci&Aaq?Eb671gYDCS_Fz#-!UhTGAyJ*$`0w$1%KRT=675jp9ebLm_sPZ}ZarYWe# zryQSOYT5|SY^3T}4R5NKLRiMc{NK?1tFs!>$u^FjR&871PSl=Q&m$mY^!pmOk`b!@ z8F;EaCgAvgP0|?3+#8wLnPfYah}xqJryOUXJe*e+Xw&ArojB!ciFfeFhBXU2WWUrJ z+Vm`GJRyUF^99_w$W;-zZVo=)4l#+{`KW~td^ZZ0BmQu_4 zfM9W0G^^&?f8VoMwz}+b;~f$k1cy-*%O#wR<&T>JCnF#L+(0A0XFMtQ{`Jl3A;PA* z{u$Nj@^krG+9&@24{ZYYZ&|jm+%Lpxxfoo=Pb3gJ@JH!a^s&5oBM-$(`V{ptTV>sbujScejr_LuBScvNz>^iVt$ck=C>HxVdIoCDeEN`29^iUPQ3)k8=Jz z{>RThjovsjc-vX9w6a2$w{lv`GmMvb+ixF2E7^yqYEP3qndRh?k49@}a$0T4D(@$i zVS;|&=~kXPF}f$MZ;4&9Wk~8j(AFlFIrz6Yz{;M!)Urf*RxnvI2RxzmskDe=J?K<4 zVOSo9q=Sd}poT<3WKf*04ho;8N==|!w5@AR)Z@0azH69na#=29y2NVd`INBvK|NIQ z?^WYu@+_xaniS> z`ZDb89OC9P6sj}W^uYtmhTlEf!n6IeiGZ)2_zZ*4@fB59Q;p_pF+}%@d*{YFG0<%_9X9sz;?ghi2<;gbSqtGK!9SHx&Cv0VO?76%q@0@CUtWwb z=5cBX{H^^vK3~-!lIr#d;)t;G6drIKj-YXo!RuU+dZVUF*|7c@_+HpvGuugTeWw*` zd%dT3lwC=J0Pw9O$TO|G*HK*G8)mk<=E?~E_Ff`u?u2$AJ0~;NI zR6gAP_2~0TE;n8;*}j?Ota6mO)%pDwXo=ILdAu`s9qVH1#z`%lWSp?aBRxsTKYGgr zye(wzEwAJGIx|#rrw*i(D;gY2Zf^eo!z`t^)NVjBd@&BuCp#nDaELmbmKizV;8bJP z@mAlr?7f%u86DRrOYik%yG+xfv9^Xwu^F7;!)pr`P~M|InEISxR`809Q5pPD}IK@9FgYJdAbYOUKvi{tAY> z_={@374c4~qswk4(XAzTjO@}Zk^%A@3=D4|bw1TkOX?S>n^9F>_V4TM{Fn6}nc#)X zckQbBd;b6j$C^Bsb}MtQYIo2J`5o5DZd;kBeqLfRjj9>BZVM1O!N+1zo20)pn%q8b zBs{vDlgT{#n@M#&%a@jNa?IYQugAfgcI=eVbop-eTML&FO>U&S#kdAUQI>9a$Q=Eu zB(zK&O2zSlN3CnJ&uY=zTcRk6C50mk$2kfBEKW&o`Kv*wt}T(0T%_c+WHP>|VQNjR z%@lddDxL}Tt0}IG+Bv|jGspymWybHDxvIUAiywq+9&K{jCr6$87 ziX-(4c^2mO0;kMLi7GkgBpiL~WhAP?Ox6DY3be@L(jG$?Gt4mRPDb9iBOmV-<$9TO zlRYd7qF!!wCW68lZ1&46l6fpy{{Sz`pPL^~+PNLIXz5+-l<=;(Y2sZyMAnGvm=eU_ zKO;Qg_5T2U>0G{6f_1bw@fEUbTGxiBSmicWo8-W3F69|j$MTbp(xOk3kF);(veD9h z<3AMYI=ntC`1og*4Y4RlZKrLHKbeR;G08om#)Kpc;ybF-;*Mp)|43A|YhYo^=2mF@RoOq@IVlj)lDVsXo{El0u26zGCPk8?7g<`_8@dcMlC zd+_W0LiX!XfXc?o?%GJE5vsUZJhm}2A^u!~p}GP_NaC~07{)2D48AvQ$LPvjmJ`8w zBr7CRO&QwF45CHPvo1q@K_lGPM5LEzGDGb$!u$L}7Ik72=a%hQWt?1EU7BP3Mz>_H z)))i-0JaCyit~>^&o#?S%|A}PxbH5aQdjOa46o{3{*~Q|q>_FPS=!mbuBX*}D>~gu z&n!>;G3(R*^>rA+c8GT4Oo)9wVbg6c<~fSxq(F0mu7qWA^eS`jTV1^vNi@kn4B4CO zd(xjj!CSS)_8dnZKsi5F8275T?piBHL2LxUc9sEumG=Yop(hEgcDbJ5;xs$Lo;mg% z=o_NX;3w4eJsZSPXtCTyEEe%im;$>NS9}5q2Wj8S4i}PmtmjdbZ^>kwqa=!co|iun zKk*dHle~t=ZhC?^BivNv-$rD-!6SI)U@|^dBd|W*$F*dQBJ_B)*XPo8m?m=43w9n} z{{Wli_V(n|d@fr?s#IS*C#q?dAL6>D{O0=6B517;jqNdzW9J-Tfu8+q2akiZURH*B zRF?h|*5$Z`lv`Z6mfA%C?oFgG9D4mK*&Aw^5Yw{V7Nfgvl&1t-Q>^c~TUs z5<2$%d9Fz-+0wLd@Xo6j!owStFS};e86@)YOs4h>Dqmyy@O#@2SZM6w5V?*Ud8wFJ$u0ZN~ zU;=AsW>Rf*j(OpfY4*y!)|!vw;GS=r678SNK3%$o~Muc%AaSGlP-+>(O#a@%kQOi>^q*ZuGhJPao=M%aUu4BHKl^D<;yr zAP;dMCx92s+mqeBYYATnL3j7}`khcoIZj<0RkU$vuvl3_(A(QZ0E#PHQcP-~bO4@s z!QIsLu9-=}tABrfPGpu#b?3L=-_YmcsU#i~@fV)1qx?SMKw>e<5Dy)C)p9nWHvOOQ zL{f5(A9QC^+!@NIenr}$anoSOO67yOufC5$N|Pb4qYAknml+tY#I$nW%I({Sx!BoK zFg>d__FXL#mT(QWuE%hJnqo*Dlz<1^kJ7s_?IV_YY@a6L7_VlGNh4ZW$rK3`d6Uf9 zk{6GgmQV*h4Rl9aIpwuqQb0MlG1yA0Hk@>ktP`%FA`zYg{YsTc_`l4@)6qj~(y1uzs;ud!1 z>gqY-j#!nz$`Z<3CxMN*BhYb0H58(sLBY+rKO^N~jk|<|aLl6vAmHQf4Q!;Ik%Nm} zkk4=s%*r{IW^>Qb5B~s$xhIp!+YEjNvX@hHG-Gf^Qa2H|aqEwMzSYS&y|iwj(imze zZV)8%JW;4D^4qZma8F*{FmgTWpB7I<{4%$w>XO^uL8xA*oAB}N^Azw#NgsZdD=e)x zR!~W3>)~(23pr(j@FF^;%M*M+B+xnVxK;Au{Z@H z2RZwZfPKwvl1n2|j>aXyIm`4DU$r;dEc$h|+F8#&*kWPHP#A6jatQ@D1L>UA=HlbQ zc2WuQ=K4gCNaIzC-2`w(yJJDoPz(>+wN({Ha&Aqx+2TO$5fQe>Ve+x(2CPu1*y~ri zMzMQguNy>+fh;n_NHVWNNbE;^QL+}hCgj#)lJ+<(6>c{|(s|fp7{dX^IbqkH2M3zQ zS!!HOqmJU_Wxt4xr%dwQTWh}^aSLJ4vg`!)R7Kzq*WA}Wbe`8_y#4TZH!R%$Zm_FQ==&e~! z3&2AOB!QV^m`+%(3XTJJ>s5_4vR=<~UE95e){SCy{Enn&6met@?R6zE`EMrJ(Rf8) z`JI5OMQdc(Oc`PF;I{?j;h6Owr?pq;NX>N1TRVq{OPO4janvu?w0RpzFo`V&Fqi7r zkwJB3&j)}$p0!r=UNTFwo~`iqjUcvwHM=%85y18zt!EcR1WYr8~(wgM67vA8V>XCp@ zjPZ^$+kx9Aq2;X+#IZqd6`jsuvWn&#=nxcuf+Hc0SYe4h0nZ;w$0V&5irJ}a`c?g= zooS-$IuMmCrHolz!U9IiATPfp?PeheB!WO4Gm0p>Nuusv#Xjj_)^4=B4I(%oSA#7Y zfM%9gVylo24tN;)k_A~!cX?a~>ei^$X@c}zoU?*)fe>(c;d z9je&yr#?vDSt<%FxWlPj+`D8D8c6N`Mkj~)}%=hfr6Ed+5v3*jVH+Goimu^f!_Qhh&(U8v#!17%#5R^X6&d;Pl5p0-B#dPaRFB$i(~Yhw1Y$$$xw9EJw~ z1CBWW4tTC#OBqEqCwn@5RFtHgQ6*hRC{PKIc?5kypck3|X$(swi`F!022ME&NayWB zQnry1;j>|5;d?ohi)}bYZdl;$MPs>$9dVLR@6x&bI^&Mt=5%L#^6T;;waIU9^lb|I zeIE8Zq}2SuC5!Hw#4L^@l$;RJvVLVf*kZHIFNuk?YlSR%IKRl6@b$fpkKwCFc8=cN zEtcZy;#cI7GV(bmxjhF1I2EP}jwrv>!!^$=hBDsGd!%V?Aj;}U^Rg_SQB>Nc0DR?o zjQ2d&8FDuiueNnz#-k@H=%2Rp%qrJY$2`ZQ#xT1F2nW$X$@M0>Jvvc^BbU@Wn`d6e zwlF+Q?2t_H#$|Mkonr?D$OMH4)Z-s|Jt9)KN0gK;m&73XyrVOg<8uWkpVJujtg$Ce z$k!z~QX(uhR{sF#$JQi|EFzjy12A7NYqAtA$l!y|eAQtlvGSMH(s7H;#wQ!EjQ;@X z=bsjMo0oAJcUpO00W@v0Ku$qLBa<4rl%_)q<~yr>Zv?}N1q9|ZalRM z!VjiKO<_06Oz48Bqbt?ZV3sENSQ3ZW*Bgn@-iU7)Czo@iYA~r-Z|z~ZI2EXYs?YhCDUl%>+suK$2WZa08)|LjM4nPZ$Fy zisjCljA0+l=*I2JUy-2x9r(jZyU`)F)kvJIcq~vzCdXz^P%+O#jMEROf?P7M?|+&j zE(y2G3;xymnkJEFr?u*8I!i23$_SPfA1itscES5|UAS@MbNINmeWQy$T&o+!nO$_q z-xXiSr`+1Z99W5G7qhnSnaZ4z`UCoVRXs$MWT6%2-_+aFLF9y|C*qgU9~t``n>8@RVW_cXBKK}rl71I{mxh)3`Op9Q_4 z$u7lf*rZZz=ZYr(04wzUYRV2Ia*OhFd%4^NQ3S3z1v$X_Rnzw-ljwJ8YpL9_q#9M+ ztl+XFR_xgTWRb^D=~Zs}WbkNs-VfJr{MikY+s6z|DK}E2cu+EMI+OGsl`2X-vMIj< zcswwJ!_sQg-$S%#WC}ob9F5%e$j444mB4c$A$&6>E?JOe>r3kUBvCeh9kqv>kTy!kP=}5iCC& zd}NQ~6PY7i4Z%l1+5T?BisenkTJ4>BdVPKU(SH0A@dTQU#;v4Y-hB5X%|a$EF6L4n zYZ2IOJ$UC8KA+{2h4w~w$|`ly3$1t$RI|D&)>6oknOPnoxHM{UxSqqO70r?pj+*NK z0HQi!IAq#>-?^%IA4j*)H2a40BY18ES0d;p(on~eqz*8rk@Ypx>7cQu^-i7rEBkmk zJxtz4qPteB>wnzEKM;QuTT|5J_#38!OfZP!L;nEW+QHS|(1sZp>~UQAIr@u9Yp=i5 z=*HuNOTPaAv8USjsvUpBRywuDt*7Z4ZR~E+8d3KSkg9{>7Xk>Aqyw6Sc+jE+x7ke4q42zP^e+r26Uq0OD=Q+`aw2iF^G& zsfzyq>q#n)h41xm+wB$49NI~Fqm-W7ZPPCJt=Y08QH-?sN_0=Y=>2L4%G5-J&Yg72AP>wkirMo9jO_H)w78Nxh{J~&jr~5NuJmWwA);xK9X|EpGAyd6EQ~`cF$h=x0G8}xvy`27 zT_c9G6n6Fz`8f^HhCeVLdW7v2V>!I*Jt$mB6UlDp9%eWP)Ay}ZUu8=1mUf@b0H2$I zT2f?mUc3)$s=f8B%WHAv$WJT=!-XdYoQ&3aAe3y^3w)Ik*R$NNq%79XTV;L4QI9Ll zN5S?erS3S>8b$Fgn`tB=W-^cA&W8`4FbE@_bDWH0IpV1-ZYkNOHk^=}^vQAJi;0Ah z?rCLbDW;%HIq#wjqhc@!;*=tWLWZ(;~Xy1MtzS4xaYRcynPayRtLn{ zToR8fsX1Sma6vfecs0(Xqw=$KgG=x(t80HE>DK{Z4pnY^!VrdBjt4ySIPPjDKD7CAhG*Q>olrF4PRe1gQ1=#G0#eg8AAms$C(rqh}J|N2oNOW>pF(OaeNBbII#b zC@x&fDLUdy*y+~#l%Ek1_<2=J?m@;u>;9sy@kb-%w8}h=8hbH6#-|_tT0BhOl~zk) z_#AKeXty8My)4hB&o32t7$lo)jGM9)6I^fTcB7P|rCJ+yMj{!Q^khzo{^bvY;+4?L3x=cYLD_jAxGi z^|d)!k|!*+m=Yy<9A`KK9qS23S4HCXUUd7Zg{a%H_~BUX2k+bKTz9j%bXUA#r@;48 z3wxi4mmyX2kc2TZ5snUWqdtPVaLS`b8CKC1XJsl_Ie>YRnE=4!cTrYzv_w(I#5U7f z_{E^Be`Pw~(dy;wzMsZz)pRnOPJ}$K_ z7TPUE9$U!6+(_YowHZ0zk;Vt>+OD!HWVpVI4}f%t?_kxepp*x`vM`&V*bu0YGZq7q zq%Yf#dZgVn--cTnZAp8bY&;iq^M|vL$XrMuMqCzDAQm|221g#GRg^8!St?dd=)Z^h z_0bPKzm$=j@&V31ztXk;0M{}2gg1`7HF@D%s3dDecx6#6USeb^{$$TXj=xI5>P>qc zD`_&XrD}noxR(AAI!3{QE&wF(GCTIDoHnSkv`+ZCad)M7cJX|e;V?WdP;nC$;1%iz zQS_>%dM)I$cp~Yq{28g~%ZpbdEs}u^|au0FZ zu2R9=Ymjz3KTcRkh%>_%6>; zvej-;;bR&Nl1b(rm^_99y-pa;GkWNzc|uTI{EOjjp`90VugnyW%yH^{tG4?%E5TLN zB9_-$k6+fBD_b=F3d3)fE=VKhC)+(e>z{;{Pm7aFsz&^y@ZKzL-_*=>J!-;jeBDQI z(#L>6PR!F7m?Q_2w8&VO zIRmi9YVmHGOwLhCn?-}iw-TQTUi_$1Qxsu9KQfsUC-lu*)JeQg^!`dy8e74Yv0MP+0C8~^iDjcXVUPc27ZoPPV^g_~`&ykKi6dV!RhsGcE2`mCul)gIJPvY4sH?p4jGLpK<4q(sPZ7Z{ zi5Qz11aQH=DdTWVkvgB5fdgm-dY(bgYR~@wa$K&9{{ZX!qdP-!Jer4yrkP^$WsJOV zkf+LtyvJDvc;Uka9Q}=B2})_?XG^Sg4|BeOeRE}?UtY@%s=el;Jl4@~AhD8C+etad z$0>|)*P7^tZ-)mXpEMMu7_S2fwNTSD!r$=ZZr;j5{LDxh?${$W#XnHrM|3eHhu1gJ z!3DgKtZ1^G&E^sTRT%pcK&0nUv_gY!ju%r1ZJTj#pZT+#FB}@eISrgB&pc7HRRY4z zo6QpEYVe?U7_HM!M=n%#wS!H4CRVq$TWwMpjDBNEs!@Rla8uOa8r@1RKU14_Tf8%^ z+JPcLbGk>4HGTOqD<~&DFccmF*0?22$qdfok?%s(lK%k3l3rO_+b*KYVV3F9pKmzA zo{NxjPf`}N!rZc1oSKe0MZ3iI&2yl=n1oy#+ly;CK`p{dGNZOfI0{d&@fcfPEphYJq3IQju!8LUx_Ep8*6d%OxGg$F1p0VlLJ=|sq zGM7?K98oClNhfoY)1XoB)~P39N8H1&^_^o*p6=AmEHNoq?qG&oEa7^M;Pmz$wSzP` zM|*9mN-ieevaVHaB2gS@oyP9x>sim(v`*I+mp3 z`z}b?>91)dHxu8*Cz>(>_BD=3sIthh>biD=bEd%d*Hb+55UQ*;;P*f8)~P-cg3s2mnPhN~2=gJpW&w=KuP0=)ml!1u?0eM95B!3V=GOIXbv7~?K2*u`#xv+eW$>*cc~IJ2dUpm} zeW-|e3;WgArS~h$Nqki+#>&eZxBXmZrFuck>atwx7R?})14cRl!1`2hSmk8hlDb{e zS!mK)NfVi5Z_SOqhpk~b^0Z1k%QnTsurJgCcpl(Z2|v)AJzd;g$7c<=bdo8u2ddVjKg5>Nx$YN$naWTJ9}; z*zDF>;g%(lVv&HtZ6lIM<%r1oVzF8_Q6aA&foz%^>D6Us0s$ZKl~gteBn|*0fuCH~ zi@UNojql_|xRyIuz7E~wF7d|YmDjLV><2#l)||YQlA;#oH?`H)JI(7G$TDRi=xq|=sMoBr+jU`vu%4}3}P`2+q|V2aLBPH z30!~%><$4L12ueiDDS~7?6+tMBWW7erK z=*IN*(VJgU--rBG_gcmMrJRiLEyu)pgp8{3!6V#l=dbHrS+X@J#PmHqO;hk$ZEl+9 z#V+=6FdK@+7U>=}n5hpdV}w;gM?98c>0KV1D{RNq<4BS5Mbwd5Tttyf*8czlJKRc( zox8CdY7R%uy@|(grn|FAsGRd?&N2d~GJh(1F~BDv^r~QT zQsO;Ai(HW>^gMf4Va5~yc;=uGI*j+TU0l7fHrDntq-H=sY4D|;N$h~*KBVHfy+ofa zK95Jz!6@&^2dYU7dK7lLRhq2&oy2Nfz|7Oaj8&L{oDIQLb_zi~Yb7o?bhgcS-cC*F z5?A&zO{?nGkcqAIi0om8Mz@n;i^?0yCw@8Sz-be-0VpkP?7b?BN-I*sl~L)`nr;gkt3?!J(MxB!tBxqL@R<)O@zjz zci!J9$8s~luB@396|1XOGE|(H){B6B`f`qF#EZ9$+vR2~eaja81y>Sr<@uM*B_^8oL(Vb%D?=m0u`(pm zt0~u4DSb7chOQP>meFGqLvB3MQCU2(AyLNXK*S7y00%ka&YpInqR&bg5`2+m7nU+= zX5(~)?V@0>Dl~*D<;fgi9D|lT{J5>5n;hn%{20p?NWs^W*M~1xQPU&2jvt1B(l>_K zuq_l$p_g_$wn^r<^tlw1M>nd+!bp%=m98a)Pw^vFcJ|$ze@f`&xp6u8zC4avrO&}> zmzPSxUKoo;NZpw_AOpEAj1Kh3>J5xa=8?`=Z(b=OX81_g5ilsSPU=Vu=L9NeCyX3t zn&(bjXy|G@tcBF=r@xLZ5!yRAXP)W&sR%DLNiigVKQQ^mI%8-jip8lvl<172zIxf< ziRabiyNc|5GLBSk~^t_O_1l0Fe$^q)>k|83qTk`d1!zDZ7E)>C%GZBY?e@UnTCP zc<%K8h7=z%DwXUzan1?Pddm}hZN0Nhu~$iH5x4RspOBV?<5^{9lm*<(3E+D56q};Z zO|6;N;sv5x>r#l$Bb63)$GE}$!K`N;m%E7ra*HqF<&E#eF`ma&n#jS9Jcq;Y2iivf z{{Ze4wkL6;43}nqsOnNha`D6z1a2GJwo$Vd=#IQE9qgQd+p-A#s?(Swr#!|)uPjy$HRJr>~B>AZg2?RBS5Rm z5xn_hoa5%_8Lk|ToinNgz2oQ>J|bIR7+UHR+c^dsgEs4TZMoXYerVly@&UzRkwPx# zZ0L_BzDgdi;ntZfl3w^LP%oDfJ*UJ302Ax<&sxVO2bEqaU+ifN-wpo&^i*kH4bkS) zh`ZIOt?hxd)t}&png9@6 z2OF3F0CPB8`US>1iqcwxXsjPRn=4<5-Wij^o+(=>ZOz7)a{g_rZOHGGKI-4G6-ndZ z$W!Eso~x$nwss;`(`16qRVF!JCIOW7$N9PLI&oDTC$nIL!2woWWg2!{XUB8$BGwoEK=9#2zW0X-|mFyx*i;HbMTiM>~ zGF@Fvs;*IBV5t6C#sj!JRD8YgK&oVtNwjH>4Z3A7#j|T449#PxPSA}y19X<`H!8Hg zQbwJAVn$9ovwByarMpLD~C+pFK4S^VZJdrlFl_P@iINgiB(AC0-yjpb5>a{ zRET)~TV)%@5ourGch|Z!l6ezfd>m$D^RlL0@;eN&FeA4eM?E-{xo`71GgFPO`YV1E zmg?746GLd%cK%x}%o)Iv78qbpZaN;s1KPHfc`7;6r)G<7rHhNhZjSdmS!9jXbG>i~ zI6Vm+ed~iX9W%Qg*{o~+47}7dJsLXzC!WsLgph>%>d(moI3#W)s5v+$xbj9yE02S+ z5{#SV=$z3%4lJ~7YT`@D=X+=tCV`Z+QpF%VvFuZ>I`D95EGfyUbcv2yis9QWH(oWj z{{ZSse-GJtm%4=JH9JS}@Ww?Xt1NlI1N?-StgB#Zc?|JdndY zkj*WdTF)RG(J(}q;|r1x)DcHDk;*<(X)E^W{RCqyTx6Ye{{XLpCe{A{2`*x@ySu-h z1~$-_cY*WgK2=ph;1nH6&UgbA&nQn6WiJcsf4767Jb5J)yJeff`h0pbc{;3`PM>XS z=3EQQwGVR;pJo!>2rK#Ga>RmjfCpOJ1k_^G-x{yae&3aQ7s8w7R!#zyAQGd;W$C9lkD`_F7B- z0P1AMi(xmE9!L_^6#oDY*`zW^$NbYjc0G2E2XaqKVZ|r5tLfYS0Q;Z6np*d=nexSH zJNJDr{{Xdnc)#gHw1VDNmKWIn04OpcvG-r zp65rf5v9GTi6(S(1Ww?{*-|$gt0y3U4;<92OX4|K{rN8}lK4t3{{Yv66VV~Lx0_@@ z&pf26gc&XL{{VffNk1k@TP+?c(+-uWL22e0)u4`1akFYn?73}&sa4=-)Edc6v|4cC zE+l51Wp{9r!x43B>EpB#A`&tPkeu|$!kkj+TP+B=XnW%;JDL1Zc`899(2^u~a1+Zo z0IBPeG0E;p#cPFfRx>U#qnv;L0E^2CNgS(lD?-qf!*m5m&#(5au8fp96TSu0yeDaM z1p3|dR+k8*JXa^n0fzt`!x=q#*0|laXOcWy#SDc2Ro z)!I9fA-rs=BGE0jF7aX}m~-;;%$mr&?R3&*BA?$s0lCUB)Ak1`;lZlm-1wN5pj9ktis%iw2+kCIp@V;Y_ zCs4s6lXEK&H!}{*PdKiOYCIL`nB{jO-Qi`i)AaVayGCY6%Z!fLI5_&}^sF1FXHGPf zN{`|-j->a(Nehb@k~3>=Sf7=nR^F@bIVao-?DX@DV@%}BZhw(y)%1a?ejVtx+IHu- z(5$17+nCC>XWb;MIXlZU!~pH)K*Q=qS>Lvrs-OrhAwPur1GBe7I=}Q4iVRa!}+nE2**s< zE!RfrS<6rG?Zu7trQV&o3u~BCJCWvsV|7qv2iu{@^#-!ZZ=+Z$C45afyb4qe?!#~g zI5_6H@;w^Fd*SlZI>vLHbAz5LAF00H>!BXtz$B&!2baebaxYYGUeM0o&-eLp_?UxJc zM`MhAs(mt?pC{1uJR=npwpafE5X73sxo4-`%R1YC5?_TzQ6!Q6Q_0~~uvc;H#}t*% zBEGkxuu3qs*-O#%ds(%lmPCVdMyVB|Oj05<+1~NGw)hQ`Ue}Abh@n3(zyJ)xi zd^TwmPzyK_gllgq1!M#OIUF!Oh$l7K3B@X^IPyYo&Hn(e;IIBG+-=jXpbdc6u%HSs z2Uh<8`fDFl^q18edNsTH6pJEKHa%OVU(!dmU(`uy5VyArEyQJ%s~yCv40k-A{{RhI zeUTD2Hc4hJxD_XH$4cgx;x=6t9Sx&vX=2z6a<%hE=SkWy5lYvBbrg=Q6n`kgw$s6tV?+o7V1gk4g(vIhxn*ajz>MY zQ;s>!ZRd8=q@@zc5hab7X?e>}$`-Hxsc% zIKLS09h(>&^M%h9N0Oh>8z?4@Me}JDl!3&|6qR02%Z#e~RU++Cqh3+tRthzJ z=VXZz>_i80DH!ZK^ZQk@G~E?~t&KHpP2)*+2@#6n^Vc}6s-2dUh+9}KA!{#)ONp*! zA*O~l+DenfZ;d5h=Qc)*KB=JidG#$=B|M1YZPIz(TJGA%qJm2wemYlHP8^z# zMi5sW_E&}68cu9HM{#!!o4Nd^wNNFSo^Wx~I6r!vPjw?as)-*9c(X;*uW#;Sn)W+C zDHhExuoy~L_=MxA=m*r-UM8bwJnf>%;?ES=Po~&f$8~Y>EpZIyOLZkkQ}e3<$y^>l z=Yxv2d8tN;^znS`v-nmBBhl?=gi9l|W;B}V#IpHd^aST>ll-IZO>2j6M0$twvbE!4 zSxQ7Z(xDZvl~zMy53&?o*NTf}nGqq~Hpou5(Mhe*v%laetYd_?N zIG#(?w^`)@WDv$MiZDk`IL}(cBWaq&=#jM3tu+Ww_-u-{=v1g>CHeVD1JHFfjH&3= zM)q*K(i+M*%lzze#%RgM{@hj)O0-0x;zWxzyqKlxK0^kKF9(`JRP<)ZTg^5^yJ+z& z5agA4PIp&aC2M6F<|*WepkSmT?0f;<-he8Dk3;C3t+T-#8c&FKyTy^XhwwwXsNy zyJ=QfV3lFaOi!AT9Gvr(Bd%&&@Mh4u&9Yo7%_2t>jf7}mQX7H*1fI+?GCCTvm2ApL zONcF=;h|TSREUy4iSsOE3@OK^7<1H`H{}&)G}I=C;#W+yX$kzTJSQ;Z9FdLz!0Xnf zMK1a&XB$mY;^9_%nOYlBwh#zt)V9_maR;1k+w0D2M+)hYW4%t_Q$$4ngq`_E3=>I5!4ofv?DX5sPHWvm&64kA@tbz@6-FU@PIn-Urk(LRhqFe1Q7UI_0L~Z_LNaT)jxpE2g&2~mft2tVxcLyYn zaxvH5r;@rNomkIWSzkreQVCian%UJPQIdp=1|H)%sGs3w@vEA$FT_^Kai-eYnVvKR zNw>}0=gbh8k;&wfCnwYco-2xJN-23e@i!S*&ebn9d&@hBZ_T!mr^5sf&5oK#mSbhxb|u~AwVkBb6U!WN zMC=`l05=yS^)1FI@preqjpk<4w|q!3Z;#8_jx@P!hw(PC4xMSTMP?TTp>m`jDHs*pMsu_hp}jYb)z9j3s6nqR>h!o= zrlsK(-wi_*w7Qn7aca|CO(IIa2>a6s7~7m=wg7H&26Kw@aV_$aJsiJ-A!$E6b~5-=19eNGcQJNp>u$Ft(?E(DfI{#2RJ30$0E7dR*NHPHV65zei~ zhzsPny4NhDx`tAcPw{JR%a4bGA(dh=ozH`wq-PvvxpKYKyq$R0%W?2X-NfQ60jG_Y z!gQA5BgxIYd3M|1EJ6eS08US8+0%`q7^lja2d-)lrg*30C30btO`1DRkeLLYS_$Pj z8N%VC8Q>iE0=cI)rO6#w@$!cezk%*%x@&EoafT#6A`B!=Al%H^>cn7io~E$$&gQ;` zzNb)Wk{%_N={1`Rdv{MF_9upPe#$w>`y74iZ(Am~@iO#KO-lR>ucn^v17mLzm|hTJ z3^p##hiL~n#&({ZoYx$4N>>ziyit$L$guLQ&4Z_z1Su-V86+L3xzA4fiOHl}i(U|t zO*A`67F)w|q!5TBTps-7kJh*3o3j?FQAPYmcAQ$=Hq*ny*PI66pT26d*(p*P{u)}1 zXGQTIj@H56b}%bQ#Zi3qRZ`gKM3F|o$i_8`|x zeU4cxIL^Lu!7786U9Exq%l`muRJKGDG{3`mqSLIk*{(v!mb*l;Gleq4AS%IgkC>8} zJwpZcHN~0k&b({EGvi+j&26Y1QDovLoS+cLMv z89~YHPjOxTsm3euY~%F2r25hG_x_+Yq?I&%3e~cqj-zk^>(wI9+{oDW2CwL&+{pE^ z>Lxm|9p^s0=DSWK#msR8Eh_*QjAxTZkS^bYo(zk{o-J)hRE?z3G_(v*9DGFQK3rh* z;Ng#600*sYg>os9Rij_i0le_vhG*9%xm&bJFQgDUzT1UY-GQ`%?9SO7g3NK!uL|OX zljQx!H}2OF%O8j!gI3Wajb7~hI;GW|j&Y5sc1p^B$Q8jO0jkd`lcK8=T@aD}9{5{O z(d}iqw7R&K@((fun*L@;*^m;-p|CIpPwDAM!W?ZPyriblF`@W&!$8#Z=q)s>8)+qu zX&LOIK3aK7paRZI7d~Jh@P1aP_)SSkmiURm#SXPZX`{WlG0i3H7m+TWv8!N6nAkRw z6oT$|5^zV-sg>6z{5=|DT_xoWX4EbuveLB^3N^*GqF!7~q(~uY2ooweI4_)WjBN*+ zjJYJC@{@-gT&eZZ0jQ)B$*S7gvO#BRZSAh^LW3-ZJmMk&?v^C$7Rr7_K=_m9w!&jal>;;ZC^TBGayBParIE z2%}YEN*$n*!~UX8a>2PanY5BgQ3t7b;(c?$ekz_gz7pcqBeigk=OBt_D#wwLj&ge( zRx!yek&}OEn>=a_CHBhq;C7U^o+UcW!Z(Xg=V2LQ?g&D@gaCQ#%~u}he#Fc0HSeM( z*IK*MzZ11)+YHwpe9=6P#l%X_^E!I4Ugy8kv666ZUzxIepA>G&H2eD-bi22=^5uL( z6xqw|Kbc1dk;u(ySmzbVDt;gK{L0+nC&j%FwEa5WwU}>h?P2oavS?#20+>q6oQLGD zLvxO}u8dJ!?kh=tRZsjs2QFzoJY@FY=X(A2iw%vmP$-d`%$bQIMi?qR5PvBB{cEcn zR8{%+{{SA}$;py(ldm6r`<p$R*Bu98USj2s)MWR6-S_?vS*T?6`2Dp10H=fF+Z)Ne zOXBP6`{@H4nI*oM%5&=2B=+bl-B{EjlJI!WT(|C6JTUrhgDu_GwQV)s%;ebFTEJC^ z+&_yk2ZEz0fMjmV42&AaaB@_g8e)=zwydb#t<|oleXty)j2WIkES`IyBq{dE0<>x_ zjOm&!g_Yf}g!H*!xi5CHUEE6?XXc2?S|yNrVG}v^VOhAVHG}z5BqN^CS_thWXOyII zh%OVN0ggY*(OMX55QDm>%8QC)2Hkq)}oy%S0-?boozS*sU=9(d3Ntx|bF~>K+I1{5K-@ z&f4DD?p9lUw(@LNW{rTr2j%t1rdqF&efFD{p zx#WuQOk$&oO?GE@x|{f~#1q_JKanF_nBa)BI1H=8f_+H+O?Ew;k$(N;?xGv0@k3 z^Lo`Tod*rsDdOwRTSxH@m35`v?OC8z4H(=Vfd>S3JoN8Z)Kiz5L??PL-XrlNS>8co zEw1vgqsccQF(aLzdz^Dwi+FR^-K2qC)?dP|t`qlAdw&=Z_ZZF}LDZi=zMyy2a9t{0R#G0R1)S4~O3_R44x(=LtBl|{>qanVR zG_rZCD;z48867JB0FY~C-qQN#P1JP8u(+BSbvIXd5%4zofk&8sn|IFHKHinjII6Qq zN!mrq%S!UK9VSTT-=jp|6Dd^yO*T)NCOeW86=f@v`1sc#}?&@=-jO zFhgvwA?2hlLzX}P05RL2YThxdYxOy@Tb&Z}#Vw3cXtS#&&6~(2h{_vl=NSqIa0gOz z*NWwS$3snMsrZ?VuBy<0JjRg8k)M^b)Ap@nrTHAwdmq^9Np%Fa_l)W$A}z>-fLX!M z>`hVA0OLR$zi!TmO5!%q;+tLZ#*qn$k?!tefT{jeIUr>J0Maw}t(B!`J#v`$z_(Id zL#{3wJ9pFWW=BFs)E+>TT96-<$>n_+iod*Y2fB!NQp%R;7m*_v@f$xG z!9DO7kO!`6kc67HGRY@M;hGsZBNN%B`@B77B2p zL5#2-;1ANdT$_=!P@05yH?teWhDC*l3`xdM{pzh-zXgpa!@4YytPc2rjCkABV~qXz z6&1QVV(D3O((J9Fx{mC-2938U$N+JS^ZL}N#`!WOCf5{5Yq~wX)R%YHjsE}(97?`X z1%r?>GDkd~)X9xD=Prt4$kI?mxa-{La7R@Up1lH+Q}&J#YQkOB9s@nn=; zzrUeuxZ^cNmg`CQofhL$ySCk|UPdl1T~8o&5qlya3y)l$_0`47JfClW>-uQs3!ek*;Vj{g{Nzpjoq@e%plGTE>xk;M*I)Fr zB7#gIlQAo)B=&Bbxz0Lfyy?QFYjk%f$ync1NXCz8sio;u-E;@Qz5t#;j)0aN<#U{1 zk(^Y{3K74|&y#M6A#vvDv&rX}wM)7Dp#ps23INZshZxS`l6f3=u6&ESdph7H<;8?| zsT6lgu%TkorWAk| zwOO1y2@Hhx+%jrwTQHpKq9;pR=`IpmwOLE9;~NG6fao_b*jCCr(ahUr!&qBw zFT)OJuw6dl)QgLTX$we9rwF;m0RbBdI}%N3<7$%GWv#NSuWEL>u8kwJTe`$iJok|9 zPyi##1HT5gg86CoWs%z|?*4N^B-9oUAhfZ_@sgYl2iK03qzsv0v+;7kwo}aowac=X zA~nE`nM$0F_|NpIo1$X)ntz8s5;V!J3^&@U*@#sYN0YR=kL4KSrxmUlq^inf`JIto zHSxX4{{RxZ@cqQr##tkVDURQoEu5eO(42$lNI9;2)2X>Hp|oHB05uYusC-7Prmy&f z_ZKDb#U4Ynk@V~gV;#KW# zZsNln z4zF)#dsGHxDtX#Q2&%;r*%ZyZ7I){aJ!<3<`X-c@2=6H%uS_5Jn&-=v-9);HEF@WT zZu|Ey%Yskzt~Q!hSbeCf+39K#V^(fPInSj;RkdM|mh;@qcKoLun02k*IIfD@I^9hy zF)6!MSYIuH)cbo>s5hhtfqNT7(UvH=;1QEuD;q>vZ}7H|&j6M?i2UWl7=Sq$>&f8p z)K?xy&DuNS_E;o>IG6YlM<(s2Arlb9ws_n2Keb~h`x>Tl)DdFHL{^XylECAU`FZdD zl@I0UlY-mJ5=Q9Tx1rszkU!r+O7=3Ajw1HXLn*$M;+2>J6owm@ryt5PGyQW`O_??^ zxq|v}Yh=?$8{;wrjhaBDmKXqYo=^3yBgfC^XD948f=ii1GK69y4E|iNu}C-@_Ku{C z4!!Ds4WfeGT3Ews%^YsBxf>_kN#C^PcqfeDaf8V8t0_02I)Y1!iz{_EH&CYUhRooR z7BRfIz&sLqV}XO3HB2Jc_;otV55vh6yPE1q;k}3EMwcO!;C@ko$J|#obdx)MGc?_I z#7(AnJ*2q+GouaRQIrFmuEybqU(i(gdDB*H>KDq{lEvaUBD1v8^j%)|CTUEic=DMF zf}pE#PT|M{1F^2J2c2X!u#z`v-a&D0tk7(NC3oA-7@fecKg-Af)^g&3uXtMGTRlg^ z_cxltY8H~qcu!Rjo0qf5zMy3{VLv`Ayp zQsF^)J}N|yiP&d*<$xm~bWT{FwN;W)kISP@3R1ZfR#p(%>62eUr?>dE{Gt=)PEG+o z^1#UoL~DYeWOpR-Tj7mEm2I5)XUbe}NSeEyu6$i@5>4=aRCC%s+;2W|$0+2C1W^`q z&KQm>dCUI*q+-lt3dZENG}7-c^&bX_?52)=N62}jm4E|q-s;3~Sg^rm{{X0t*s4n- zaCNgtV}a8$Aa*Pe3cLlFJ%6lwK+A9XvRb-FSG%a&D~cW=WX&B4Nt!13R(#wqWD!nzt)WqBw0PLFzXQ-Xgn# zL2}XGTT5wbVnWe5R~wzN(5cAD`EWB$7E+2_yCn6w zwApPnIHP-b1)>CLG6KR8(SkAdUVgRFmN9FOvN`cNr*F$8?e6U2vYKlxt#0>C6bTq4 zNhTKnV?Qo1bJ%3o{+*=_O9^u2t-12eqj=rX{%(>*_?7x#-UnV>E zWR{_HmI3bNmOE=pYjg93Bu2oEy*mX?IO=O@Qbtfsy7I_KMWW4pEwBx0(8!i@DJ29F zK3X+BI+9fX0F{FO04^)cpQv1$k6(6ral-heBi@Y!FkESla9xskOUoY8&-s^O@A87b z(zf)eD5i`(Q*v%B=d4c*y4|!=ADTGZ3)GN*F!t&D)qPBqrxg4b^wDvHYskytpo9RZ z1W1ag2suEbj&qUzm4qUav~)^M>5%%HJbqkQk&8a_1xQt`XUd@{wBcm6VcrJ6E}w0duD;Qn)-ecYydG<-?Pn^+=~HCT^&&{s>-!;x821 zIUq}<`H{aTW2DFx`0l&&_O0>MQ*7jw%1I)ha0ToaCKTy64E zL}ZHM;xbOp z#F2$WRT*!Yl<+-pG0ks0iAf`#80Afs{d}18OUp;NHu{C!5?sd^l*s6j5X!1L4nWK8SP(pz1ZgKtc%>)KMjj@n(t*2`0MB;st565s!ER0#|hKT{+jaM1!jsiY(Je6$S_tmAcMPdf_Oe!p4Ad>rc6?y zhL`w#rNOC>iJjFFStpZGxdrkQEsz1{r~d#W?On3T{{YU;H3X+a?S9ftQ%2P-<-VHj z?d{g`6Cm9yD3b_eIsC>lSdPG`tRLZ{YHitY{3I~9gRX4st__x;;ig-l19aq^1Gr&9 z>({kl;FYB5vhkI)+O$M!Yo=+Q3)iDbr@4J)Rb#vXcHES5+i}%Y@K4m&G+M@<-u(Wj zT-Po84m2MY!{Cn&X_koxoqu@|l6}FK$|VYd207c2$9z?}a9T5J`!lO+w6xdnB)%SA z=NnL|P}w~*&jj#&s~N-PO1;e^Kbp%gi#%N={0(-OlX>D&%PO+~q<{clPMy07&Bx+T zdu93YkIHFZfZj5?)HO4u>TTxr{UqFSaeKS|tNxBZRUTNm zFB<&~H^w)*lvYJ-(UUnW(J7F!(v4?=sKcCSV+ z;$~C#OZxP1&3rr#9@qUo*@M_lKo*B~=t&V{>BYYP&QG=Eb~gRtcUWd1W>p=bA{yeIW^aYUm`hj#^lMC(DiF8 zJsIBORV8CB6KYYD}z)TmGR(Ha^%AbQY`IE#JW6ts%O%$CtWymYfq2u+f<&utN3piT| z^vzQ8!bn~@(sHs45wxojk8W{X`QyqwnbVJ2H9ZpQ`D|^P-bq?PDUapklec#jT(poO7L%IM^h=bJVzTj}_D?_m=aS7&?>F zfXaGv{*+4l?5cjnzR|R8W_e5eG}kGJNqI z6}`3f{I(Z23u`>lfoUt`$L9tIW8i1zUBG|T7uKRu;+rNBvwYpo;=Bhl)6xi}wWMk%UTz*nip~pXz*A}U^cGJ2;Zxd;k2gWuI zEv)VyI9XOq60C(^4E*3P1g<&CXT46=I=;eRJ+A?*8RhcUIL*!AA&llMM<9^~|o<)Ye1KjsC%82;6G zqLYm>S3=Y5W6|za8ffn!Ljs6Y>^a%VU^;G453-uP>X|sxMBV~91YS_+ zT~rOE=RI%_)7rI*&E#&cu*$h#zU8+C~OJ_O9s1?&Gd1o{sz9@w8OTlw_X0|r6U1b!J z6ggf;R_vgVdGxEsNkt`5ih7br?u2b@jJwh_xHRoL_eC!a z#niVOS9?5c>ATDk=Q)fGhdJbuYgE2fCR3*3XS!YKw$ybda~r&v7_c^5=ZL+1{>qvY(d#W^0 zT*u~anOn-waqpgeF;vI$Hd=o&NVQz+(#;MmZF2jSlui6GgVc9DGuzWRt)5%_D9vI^ za%CIF7lz{cB}Hh!B=g2jKW-}wj@i+PQYbpr)b`g5$+1XLDFo+pjud|RH8GP>B1+iS zD~6UZ3rJ+kIm?m>>A>{sQsfd1K0TM<+#Sl%1yx1cjyC|szo#`m zsi%^P`c&33KT>6uV?E`VjytldA-2Su7#D5sj7D-n`ANn(IlvW^H!b-zo|cB1Ew!b_ zpQy`e@kM7;v__UtzC^)Ul4Mbp$MAXpI^!hdR{2#`7{hmDU7n?PV>?Fnjc>X}mL=HH zsB#Ddll-6@@!q(Wp3$YWGu3q#l2u7=1dA9d(<<#b&r_bJr6tvroSW?Tr`_8%gmIgv zWE)Ezgfn9}=kHo7=(Xss__FmD;tPAViMEpA)i6lF;xSk;}%j9~_UFC3FyDI<h zJA=Ew1aVfnWe!%6HIxpp+X+IQrbHh(KSC=BK1>g!glbj^9Pu&3jGeeDD=u=5(5n_8 z*7pJ{Qqnj-@=RomP>BqPF_k-y5_q*fNd_p z#7d|Hj7QCr{JHl2^|WJZ$mQVi;mvT`vqEp~(lr~%-;nL;^sMs5v`l43Ul3}`H5IO=X)6)Wv^pl=6pLg6MFT>`^9PSxH6Yx3+rWyG)aTaD>i)G z@sCffZ5eq*8Y0}ZQ!$SyM*{}6TSN&Ia$L$4erG8&MVw%jvhx_C{M}1~yBO)|Tp5y2XKZB2*!;_xp)CtqG_sE=8H8&YKa_?z!t^}% zHH+E0I>9@{phEIHyN7%+V&@zJFmum(t+dH2+JKkh(kUd9I|Hk$VOO3>9+fG3vXbm? z6Gj`%-4u|sfUhd;`MVb5j%w9UMhzUbn|6ZZ&9T#EwU*u{X1R^z0$hSgY?ICj9AIL% zjkQe8h||Y;JerD4C9oFZB!wamumDFnU;)DM-1ef6hCtfH+S|(Zw|BEcV2_ZVSjfl? zyx`|Kzz6s3R%yMi$R5XW4a9c0l4?xSe-Y*oaVkbRIaA!{JG0d0sqotHO`=!9)9O)c zUVfBk@-DZ|SMo&87lK#cKfPm>wz$60(SbX)(bw@mQ+f5x66CWOWrWJAPUyir;167p zQ-&8AKghSKlWh?9H?4N@i@P~5LN?-=5smwPY;?{KLDIB~r?zwUSiA>mVz-h7xwVK~ zEb_@`JYHb7LVi_=i66wkKQ=%Ij%v9kr0o+0MyYGBXvtxw$rhg_#h#sg=BxZZ#+gw{ ziGVoY`I`V_;}{0ES)j3~qUkp#&fXo>q|~+RhPc0;Ws);uVUktHX9G9~wkyb&&2l@D$5XxWmC%|w?bG0G zOcF>~`7$$OYO-fL0}tf@gN&SJww&%X{1FUuZ{;-~2gf?c3|BW&%xwc4N~m_Ly92bS zA2BNAvB~=y?exl0q~Asv>OFZOJXLvm_IhL%cEbBmiv6b!a#eG<$+&;|GNlysUY+nM zl1@wNX^JU+N2_fT-$_r0SC-m+N*0Zp+5EE{q_f7OAeLA8K~M$?`bC$Y2 zS(|+q!dH4th0NC%Qt3W*vy!axZ$ODJ%hzM>-M1xF4Exsp68bV+ej`uVm~$V8{5u7W ztgu{O>H2%z13Q1r@|SdyG5o-iTL->s*`EZIdt_i-N-+n%|e~i49Se=kINqHr;)E^No&YtNj$uMocX_WCCdHKFo z87xOrj@8Y|qUh>zPD#GWJw6CyhfRfUOdy1fBSHz3JcY{O^MD5=bj4|oOGbGXnb%jG zUr&E5EinH84z`fRBppoh42DlqJg`6cReem9=l=loujG1oxJUDUu?2Z*_e~b3su+W) zxrjjk%EG=*#02D$pyUyO>rosoZ8;Z~WgCo13(q;P2I*y~K*lv`O8HzWI2_)b2 zjR&q+Q`GA%FDQ>sPa3|HXFXM|C-Bkf%+c8Jm$6qb+|Y-E9vkc8v+R7OE_X?v>NU)#%>ti1IWJk?`oOK9U5 zZ!}2E4=MoeJA<5kYo|Zqq;ueO+dJ6k=UUM&tgl=NuC3-W#>1a6;&hB3WymA1BBumC zTV-=(sc8Az@Xr27yi*^QxJ@pfc?@73zs2$#uJ3Ki4>Zda#o3-0^Tm>Xj&RD_=9PCO zY?8^Q!db{8%=wsa=iiU8sPwnPWxY@0O%!tlgH}6&i z6;|Nj5~l|THRj}Tj-+=&+O%n(hu2;jwbfuvI@0ZCkQIvJ?Y4!;;X;BzEHQ$5bgVGs zz_Kb%-DY4=HX_ID6TZ*>z9G&3njkLnHxuKv-$(@$ePav4RA+i+WNEC-0^VgAFxt-69PP{Rw@@Bu``CigEWWAEu zM$z)oFbXps^O2sw6$81g{VqR-`5F3|b6ilu?PrqySakb~YiaPUDw}p^5lH@PBDdwn z!T~*q80%3Eo%#L?NiWSW^CEL$T93ZO``UABS=lOs87kF|5< zQgt7v>`oj`2{|0BE)JLCxK?Kp%O#Xn=#UNTza^%W0+M%`wP8)5)H zYkvWAj^G#R^{%{9i;6iiL8(7tzpcc};tzwjx|)0TlEoY340idxSyaaWY+_GypIYV2 zmn9bZIM4D=ihNiR_tr1nc~qqXk06q<64zH|WuF%|?I0myG$b?2^eR*db}gEtCRj(!n_ z9Y)=*nFGYG&LRU3C{TCv&?n{V-Gx&$(`$*Q2zO<7!cfcMZ^d@DfV8PBQzRhgZ0b;z z0ds;+L6cXSaj(AyX)9~NqQ&6|HP{{WsGdtm^01~s2ngO6cR;{!bKi>dr;W<^F2C&W zQ;Pop@;#GYGw@{Eo!*l)3*<*(Y2{@6N8gRZOeuHZnJd^|6T7I=KQ4Fy=tc8glSc!ui^x?1w>MKkw{AkKuD}SXsGtCw7 zWW2imQMb!9HL<9`=32{x=EzJTV#dW z{5goMhyjiIV;;Y?c^2EIxAi?)*N%o?i2f$Fz3>i+;cEf`vPrLRW|gz%G-F`dj>Y6- z+k~%M)5SboQt0yiMe}a^MNh-JC9STFt=`|<1P^l!t(<7P%#yOVI5+?Z+0K9J6{?fe zQHp{}*!RXdjirnc*!WgwmhDJz5SbVz2zG1_m3isLab3`l82wIZ&y>E0Z8O4}mZ5QT zDoe2@f&ylZ@=iALM_nXT5~EKw`%Rgp;_H$O7uV2(N(x&Y({ASj%mArU!-7=c(r=bEdnP)YE&3eR>1P=+ z#S=8_RTF~P?hmzj^V>V&(PcWl)Ou?=+e;)d=W-*B!yWK>{VJQH+9+NL)nZQ*-Fb0r zYm>Q7>}@&D0qORuG~$yoi?>Cl;@p4rOqRBim6GO7;5%*3dBEf4InF(6o^bivi#j6p zvi|@Z1E<_+cDoGm!~-B~mC5JZv8^lRmN@p2AM#UXA7^Xvmp7LzK4~syVhH4BMkh7X z@i+JEj&1_#wlYDX>hmYck;?*~L(3ET59?ZDlX7J;MwOHq&+!>to_ZSeEZ}{U+6}Iq zZ#I>yM>W{Jw`RDS)TkH=2w9?XaO=2d9YF+i!K|`6Oy3kzsSUhJBEFIChN8E#-o`w@ z#f*r{8n4Vq>5+vQ&IMlzsG~ftk1$)-1aaK_~bVIyIz9x>}S0yZ>m4P7e zz@O=g&B-@RRWjn%>vCkc)0{_aU*uF@m?7#Hw(JhQhEH0*C*ZXz+2cc&Np*`k=YYX% zipJ?6WBf$jfB+nxO8cH_vXgyuCAIK@>> z*A?{*Chegl)D~NxhJ?gnjm%L(yL`e|ADu9cNY=6Lw%>ENk_jjpu}K_syF$voSS<#1zCRx{9H zyuxxY2TrxDC-o_kH?!K9Akr^}n36A)jQeC${504cbm^VI=Zp?&o}(#mPmT6TTda{; zTFD#|M|UL2F^sStSZMc6+m*^G#~ICV^4*ZWsezAW6&PV zTItikk>X}((p(&|7|wIwn&-<&n&Tv3jzg(Pta#nQ_QrEuj`=jr(WZEPNYeHcADEMl zJ5oJSvmbj=b^KwCNS?nU1xoi@i}xkOX9xBc^>T2Xbdj zbf~P{=1ZN-c{x35Vng>E*uui^F2RQ2GwoCqN!nYtm=YpTu~4jgIbs1h;}|qer=l7s zt|NIDSpNVDwL>$*3~aYZB=fdP6U${kloceB2LKK;TB*0=*o3;jsLM>clFI7c;F)eE zk)n+R00w9YVyVTKC1!Nz#zwZQ2%XPI7z=`{V+uE3$O}T!4N4hLo~*+Njg<<&pDg2!m~MJg6!^~mr87q3Lag`0!eMfUqqOB%1krfO1Xz3a#18^lr9G*IT zDp3zerD{>!U1~mKg^)Pfo>|BP>0NMXMJ3tB_RD3h#J9f=*Ot-3@r6Zo{vJp?VDuk) z$;#QHMWXdJ`v@aVH(F!o+ZSkE)nx{B#p8q#KMS=R4Sjjdz1g4#IIIP(DH(MNVwvM%CJB0Y%;jlkslR?%14 z7ByYF)naZso!nL3zQA2w$vT8QBKE0KNT`s;yI9D1{!vihv1EsDWp^IMK)}cgDI9V2 zs&k6lEyc3Irf73%wgXbSU>S(nw31Zy=k%^zxw$$<$_^3RiQC6smE2I)A^!jlvepdNH;kp*e2VI!_Z7)v z6ac`UgBTu_=Q%d*or;%3Io5m2xtey^I4mTSbFdr?h2T~)SLD?(y3X(dv7s_C~acR5%0KFMN9XakjJwO zejd;-8AN~cqmoG@BL~dJ20oqYFe~{?y-$Wh!>ua3G06k@X(s3ypKjy)ypG>W)=|;S znPOY3iDCG%Sa}h+Cf!xaslnrLzyqc_@@oes*<|QlQtn$zT^{n@>-cLNh*D|u<*L5} zZ}Ni7NGGN$R^poegxS|j)O8)d8)&i3a9u7Q^4)~YvMQgQOJz}u5tbva0L5t@QGF41 zTyz_T)bCbL66iNNgskT}gzFo{zyY05k&}=MFa&4PqH>dWC-?jvIH60TLhr-&x3R;j zYp^p>@6M_})e0Xbass$Q+Lr;56xkNgaF_tut|D7N!7o=k6nx?Re# z6=RSWD2v~KPd!XZQIbg(g5uqmO&9=<>+gv=Y1+JrbC02w2v8uD}LUKAPu5sA6N-4D24hvsGKgTzdB)Sf#1a~)C zvbnjqLfaZ0@((6iK+ee1J$ddpB-CYTq~DWFN!v(p(Zg@y7fS|9iS+#{Xrfq1iwh_G z&O0{z0N#juHBt|pU(mNwPu-H5YYX2?~@!5m;_x-rgJ)Y`QaMx|CfN`zlUVW2sDgWlZS?IT*G!qAWLNWAU&yV4v=FB|dE*%s$v5#P-JNm& z0OgJ(zl(rZuvENjOEGx@N(7yd;3|$z2H~G_I-V+hRH-P#qCGTj+?LJ|Mw*6;r^POx z2B9piJd;{Z+kDv>+^LcCfH182IqAU7R}_=RqRY-LO}@Gu>2{XWT}yLkX=4?-T=`JE z39w5Vs+W8Z%b7Q09YXV67-JUPk~yb6r~>vlJWHPcxj`L426o8jX?q%i*g zGM>Fp>sZex2IBfQjyEM4uE&~<#L+F4yg?pmH{7!^Bn1O=4X3Zl#ACKW?M#xaJMu9` z^0(|#vPK9A*G_4u#h7A?aw7EHKA{5nWu!%OxF5{e$^9#m z6WTf_9WmX+w?^~pE)r900I13xI~ZmR@&UQ;d*?&V6*@nnxX?Cww~5R5(ia9mn*j&xzDdrRmB$=@qP>CYE3j|a_P)1ObGcZ z`^J68O47`H*)jNZ4Znz#UPmFfSY%lj8Nw0s5Dy0(ao(`?8;u)c)Qwj|@wNQAwc|}~ z4ymR~aVdmLf)&Z&f^t-l0mg7^%*`hk@ANyd#{PzlY2sV8YYjQ{n_Fv}n8cBY;4bP5 z07y)Hr;PQiURflg#Vh(93leuOP0=%P1k&72nq)IUr@kU#FwBh0%aS`BoE@NmGt`RC87>XWPpbR=r$n%>Nk!Ub!KEdfjS}AZujWNP+z?1W1~|qN zJPx5y4m+C96O5(GU!ULTZ##;plha%+j*hDof(2NLL$r*?h|FM~$L4JPtFz)LLfOag z-0~G2Lf-D)18oJ=_YZpvHZsYT41sObd4nWu!BSn01_wPWj(H_5eur!!6|wv+XSYw0 zSuU*azsR*F;%MeEKfUEkNMk?>~`~Lu9PD=W?zA=a4z8LTSp`6Nk%4mDeL%*{$uS#CLg-w80dc5PQIcR>3>@s+pF@$!&2!1OE&iuMq_lChhVE^Bk`n;3pUarG2=ZcHe3r%u za_Wn;WDpKL2%a++Cu8jI)LQ6BS?7a**FKVBy_HMP3+O5n^{Y9=0RZ-TuRO5MvA|h zO^kfAj=3NXJ!qw{*0xJ&)}u-`8cmG8YRWzy{^9};3Y(b}9>LgWxhgoo=4m|ysaVs+ zIvaVP;<1BmC6JQ&+&)}H#{qHcm0b4u&N^1pYU5U~O2L{z8NPthgsN74Y%NUEl5W{{TOc8p$}cs)@hDn6F^)-zma=%(B05*-)BJ}cB${yo}QAcz8{IhoZsCs zEbnL3A|iW~WGttnNR#f}5{CJZpk-!!^#>$-lf`2^yq#IJVZ?W(TPf6HOTRsBu4mtH z1F`es3>X3r3)isD4lA1@@!;Ak*piafB(b_%g$pF9vvUlPNX7~MxT(XEn{pYU$!Mrr z=@VPs!J|g7Gb{~1mXd5!zHk-P;NgLcfB20?Nn5{iAsW$L{8ni1HT^d3)NQsfNox_o zUEWlHk^$!#bA#Mg(w)No`Z96i$Ceu}G<0T9;sz*6{{WbCpRYKsHk6Uo7po*ZF|9{s zaU@rap(G)Z4NyRP22$0dhPy(hTQ2`jSw z7KD=clEYD({$voea=LIB^ipx}-|0r1n!nfk8d_0jT{g^F_?uC`b=;-@06F<`FbU(h zJt~-^S!FgR{zQyh!}kTP-Hvk7GlA+$XCJ+6-r0;<)5lLNdQG|^3kA~$k#p3kIR5~C z)wVA5Q$OJ-F~ZkkKoGHw8d3*cqw^8;9Q~`%wAC}ur)9sxx`b9*6pyKVIrwQL(;~G8 z;r!*AGV&Q)1mJB0BLtSmeAam_y&V|cMwtn%=~HQ%@r{-=wrG+_V@bT zaVP%(Z|hga()p$JD>T~U9T4+c+*?{$CfJtcpo}hL-hcsu-Ev6eZR^SRtQu;IY1sL! z?CkX&Qdo}5rG_YAY;FvP_uC(o`W-e3*+pJCaEIkx?mM-_VsG1Z+0XX$vmJn1npmkj;Qtbv|YWD|k{dnz6XjZtryar!3HtA)KQ&*rlC|4te=^41zJ7=Z=*& z$l|<@d`Wq1liwIw1XE4rnUT5jPz7Zuyt6RRUIKyEv&k;@X%tB6(k-T*R(NEX{A@`x zWD=X0xQwS8xbm0VJ*tgeufNFC&7DoUF}<|4f=D#@E+v!BXCpTZssgThDwe<>=H1u| z=y9b>ukK`??5}vfICTpvnYDSE?o{5kjJOL5g=36#1C=Mf;A)C*%OX%sX<<&_|_P zTf>=ryPe4<4p=hseuRvQ)6_e5{me17;Jw7C&aND*gUM4|jU7n1*y;r|_@n@szyaKM zY*L?Qx8Rl2HCXifT(a1^^_1$j3eT z_o~01(F^6-95uMkyi3NjBvJw8yA|9N;0%o8IP|2J?3l^)jd=KyDRfl2xrJ?RBrcF3 zm`NHo2wX4&91L;+=DLvF8w;3QeJv$!tSYIYuT_Q`y z+NkJO61-6JS1nH$Prp5jTAvY}v9oQ(Zyk=JIek+5I1 z%`Cv+w<89oypv?Uk^FgLT>S1pAU97_S+eM|!6USeB82WTED=l&1R(HO`<#L7GgZ5E zA67yMVph4fx>-ueYd^z}I0y3!#=9hA)pAbKGI<1}jYEANXp zbKJ08NU}#N#0N|O5i&<|MQs^UbWD}WA*HpQri%rNMQrzajPgqBbXzSEj@%7}k58G$ z0OyfdJx0;Co`%QZhMj5v{9~%?BgBW zMbtXvq8DO#`&Dfcn9o`qDe_plfWxoF`ccHc-bXChGdG(q@HPEc_R`;1LWs+Fh_rSMW)L< zHMUlzwGqhi2^wq?p|%l{I`LN3=%*2Yg6=j|XdinIl;@!L^sTt5D>G`DWAMG;)-D>- z?&QW05ek#Q@BKw`=fzZShM!}rtGRBqdy6zG-w*PuH-B2m!P1i^ZrRx_W_wwcznFZu z9Fyr)i_u0#NpW(JtWnssYZv^|{4uRkNp@u2jii|nyz7^WMZrR9>rRT0a$G|jjD{q3 z^sc2A`Y6ViR~~x}tF&~*X&BdKPZsdBrSbfuCZ^>&8UZ6dN`Cz!kg)N}h*X<99GJ(6aywYJjc zkssnu1ayxlzolit%Gxiv`qv)0Y`=lIj(DwG%!Emj zcuwN1sX9b7RWAxP%XvVB^gXM-JsC3R0V4MG94(xd#4M4OGVb~LUT{VT$FJ77Clr;l zp%QNE9MQ!CO%x8mI+?yvo~nPStXnpVJ)3uy@rXpi5xhr{vyXF{qq{apleU9nJ-ak) zk*)&`*<6oN=sjw$x+aG<){P@GT-#kdWGcLtcHU_uDGH#H3h;4}+~>7k4`p0zr|VjM z$+Ek!guI3;ghmf+%OPFABINYI9V@OA;_aN%h|f%0T{)ti#M=?hgrfDQTTSoTD zG8H_0!MFsRW50T=qM0$36CNA57B?2!gfq<)wo@o{P(wnyhqf@sfCPzNORuDRDp;7F3S)9#Vra|5=T^0mIkVH+ zF==%c){^FP0!J!&hS?PvqX^%Za|Rh45CUO%65H-)3ml7D9tWU8~2}RsV>=>V@&1~~2t@dXed|%Ly z8s?p=NvFu(S@ML9acQJu{9v*L1R`)O;hB7~1)~vZZj7 z#J778gC^#ZVmOTF3(igs0N__7lcTCM^dlq&>w2sC1gpr0lIj?6NAqOo?Nx-5m6npV zM}2yDZtnJZax`q z(p)5OWe#3R1;|~^wNQY+Aaa1`)DHE^rlWRsP7YL&WVCBtD@caOl!>84wpje##K_Tr zagSWFKYHr)`4ki7^f`0E&Ps;br^U8`cK2%w&nxXfN6PM_bC3^Z$OGtW9L>CPm%B8@ zN@^>><50bCh=pJXWR)fa%$Xsbg5v<=b|E?KkF7?0zx?3^^(O{8l%)QHK?!IcXqxBZ z{PNNW{{S}BiLgF}o27Hc-{=00hfDIW?j%yA9vIUDODVY$kYbKZ78{*oi06ROjtG_$=j<_y zxMeE%`BThNNj*At>w{f59Cv0JxoU>`9lY_w7>Y-_c2m9*#Ow_koCZ7%uFcoE#wsB+ znG=np=l=l2%aIr2o&D@XsVqp)qH9(#j~*Hs+1R$M<0 zFPBi%qO$WXZFLY@NM)Hb9HVbBw|+)(?~3Qo7gmjM%XDm(m)c*4gjU)#7E#_z8SJVt~$8%VGXO2&g zZ^^W=tcfSm@M`)N{{ZmWB)qjTKKWeXv%fhcj{OC7;cdmas_*qU^Dmu757?8sy^hx1 zKp;v~BB?zI9Z#^$Z9J+G`j|ruvP%4S_xX^XI@M*(a9I z6OzZqFMr9mrG#EiQjUy!!?qC1e;iO4nWVXyZ)QRKYl35lu1<5a48RX|?_7|LB@6fd z$8_b}W9PWD)O8iRNReW<7Zb)7P0bQ05tGLN?`0)(gMprv(4|WJZT|pcIYss4^{70; z>r{&BRrsrU1YvMpRk=~+@$(Ur{{Xc0HKe5{$ul@cDw-o~ZoW5G(yuRVc0z4lL6T%p zcO+`;&4IXl-zgmK@0!9AO{qy5xU`&8J6n@Bvu$k?O9_>x7URiW#S1A6%m=PA3CC3f zrfO98q9qzzJS~{A@L^bPB75Dx;tO!Un=0v(^xe60p5B#eOA>y2BHPJcIy$x7pW_iV zxRl!1!Ma(&Vo~;N^1_eHz2B00EJqwQZn8!{p_7A`>JTzm>Wwbq_fH|6A#PPxIQA=% z#!1=;2lA3@6!^;DW|CZ$csLlO)UCb>Z#4{eQpy$FsYxZ5C9=JdMt-24r;OzJHlMk4 zxT{}uF|xWp;>Y5w=-l8{Z^#1<uT1;{@V|XyO+-E@-pM{ zt23_y3(Yg}2TitXksR>c%VQ%I+zR0G2dfMaed|1tzKDaSUi?+zTdjA+nw{mHwawHm zD~Ox{w4N1}pU@28`(v$hO8z9ARqW`6aE~WiB>X4fD-R6oa$M@~9pO-~7I}>jk%=&I zmR>XIoYspPPv-0If2Wf*Dqkmmf5_AE7sdWhiWcWexsG^Xwp5W-%Aj!}bPG|Ijt6Rx*kUuXTu!u}lE?)86{mHmur z#@A21xsj4lHNCXk{Mh1cq$-J60DX~0Jy>() z@3IO)cLtR*?K(lKrN4# z_2DFkPxgo!39!3Nm#xO85?yOEb{i~x2gr%UK<4v7WP?e#$vt3Q=4;Eu|RJyp_rw;xNA|o}_?sM;*uBsa3f$>*!e_@eI0c-klY~FtWT| zhESZ~^Nsj{Y#amJK4>a;zkg(H$iG${3t}gBi_P$^5PP zAtkholTfu?BU!(R9bPYqGp0Hi*;gcE{G`85xUS66ik%~x4c5p%7R~2Iu{M8#mJQX!Uq;jhZEmGc{M9l%1lKKQOC^mimZn^1d2j`b~?C0MpX@TbhN zIUgWjc>`yTf~e%vv|TGy#=2d)z@BuGz0RdIs}?)VWu$g2`xqW~515nusxUdCf7Fs& zQp}q5rk`hM78HUY=pW@!znQW*&p6K=&0ix;sKm|*rEINQS!!No^s&tZlBANEWGw4% zZeMN{G0Wf_o_dk!X*qnnd?5(aZ_6HCO9;Ny1-wrnl34u9sbgYUfH~TEz&pk=c?p4B z@|N8jDEVaGsuFgdS+OLohENU)uVo&G0Dnr(eKyO-RCa+?tc+e_F=X7}W3Mf=f0?j@ zj{MZ3MjCtx9h@=%%o&mQZs({Ww{AV^(~{#>RxzfX4z)%W8kCQ##}LxuwJuv} zX%6wUudz8i`_!khTC`bv)F%HK~#kI61-Q- z*Y9qKmg8*9gB@IeGD!3sRb#0+64j%gh2eQGC*2GU46-Xp{AX;i&rmx7P@~IKH5Y8W zYxXhNcxK8wW0^K7Vym6l&*}dFdc5MJ2&6=0+BHsznC~Mo%?Ovv6PIM<5;BURvA`UR=REzY zs`?D!rd&Xu;wvb)+?KI2<%1w7+_pf^%EfYV{$H(KDptySBZY>V>8V>sBsX&;meK9= zSC1q~Axxg+43qb$ZuBCzXRBMCLG>u(w$kDFCZ6izNiH(Gqm`8h2cQBq#sTS*-l4Us zMU-9a?c!Utwz6w$+nXC%TGU4zkf!fE=c&(3ZX^Eyh^wdWW0pxGi+g)-rfKD-xM`wTj+5k`zG~ArEh<<0tD@lz6riv)dVNCJ46R z_3Ck1N#3ZkLoIG8e25j09mJMWcmPuCvLu2lXd*!Ff;VoPc^K>}_wH39Cs}_dDH#BV z!DG({(ya)l=+1qTnm(m1qzOFcJD5l@BvPhSdyH~9@9k34TP6~sOMac=D4~k({jKD& z3X#OF2IGvm+)o)e0DDw6(lv{WyJX+R+gj+%zZG!vD+^Nb<8TC%kjJM(%|seT)26gh z7gbALMj37AbSlgc0hSr)ed}o7Xy$H+4N0EkR**sQ2$QjI;_#919n0Ct# zg*-oQmn$pDAe~}nC`V6m>s;A0w&>}{jU{A;hok25d2TX}WHK;4dFV4-{JD4F(}Fwd z_j1{*h#V;cf$8s3yD-SBq7EyI>66a5gt}msW*?h1cI%^A5SF7(j~g04YsLa@OfS}dc9E24Q2+sJMsRvU4jUe%1< zveD4y&slpL_~)}mgzdmPLl3Q1QM7Ft(=L7&ywffV4RbcnCRj9nwiH<|Tm)c&fCT1GsKuFi0Yv>1H`0bMli^ za9&YmA>N;^PXev1>?4Ii$;Mdr#%iwu?G8jNtdctfP`@$8JJ#z(3tHVGT|^wp_ZtbC z;zWdZ1W=qGbYi102nNN2h-NDYuy{fl(xD-8j~Dh zXN>I;Mc5Jm4e7^PqkiVmI>9uCUC~G)NWcYHe{!LDJR$$Rvzqhs*cL2M^wX+;-hmd<`wkxUwOeP6^*CUigo_HKLvtt? zAxJqThf~{;$*tB@zY6~VXE(z4W`&@5cGFd{vzF;5m9S03Epa4Dh>Mb{i-K70827GK zk@R-M6nJb)9XH`;z0)j%O*D#y=a7a`I=;e$W0W}ugTVxzDsRHobnyZl7tgx%MK-f(+!SaETZ<=X!MJsWAJ z(Bk$qlG9EuP{|$alMgQuVT&@i%6?p9jD7o67fE~n0Fu&U4~_o-5Y?|HyD=nQT!{ii z%r-VeP~;qBoy3BD4`Euvdohz8NfMj;w~Xz&x3hmLXJy#L?vMbu!7H4exE-n++o3~U zF4E%HOj+*dwwie|E}$`kDoW0*eo^SBgVW~p6%E$eqK>vj-r1MAOIwh*_=6PJgmD}1 zMVu}_kVlm~a>V;qi&~MLUePtCTrBZlvr4x2v$TlAX%4Zng2+Mi^3{O{8?*GR`8)25 z){jzJgwy3lxMUOGBy&j_%K(80T=xsWKKZR;`4xI+nXlpyn62U*fhN~KE4vJU2e2Ql zZ7C$EtW&X!k}9OifsW|T$7B4#IM4q8D(Alj^d*#w8p7%%DQ_IJ#S;=n@IWMv=Op#2 z-Bb4246#{U+d#Th7ZI6aSq0>=k_mU+GRCByo~O6UD(X~{f1mPE#k>B4ySXIPE-fUo zibZn>k~8IwBvXYe?l*k}YVuoDipL!%Y-{2))9!pRt6JTp^1~D@wh}=qkisLv@-!+qy=G?xfyc3F1 z`hO%RgYEtgPqs_QM&TfH6f9VyZa6}E91zS;r`E88-@eX_gVSu6_Y+-P#<9s}T6m|D zGR?TDXOJBIfjs~?t1EX}ue&p}sXrs2@sx{9x0+^1V04rCj#Z^9A929O6DKYkoZ}d& zmPX>Sr=&z+l)1IH{0=T9K5|=$!f}TwwJYq_?y$ zw;wWsIM4k>xD^Sg?mida>RHE<;{3AN;H`H1Q@w??NnAIasOrnLL$NEg52k*&tNL8h zoYyz!`O%-L!x%yEUO(ACsG~ltVIE;(xdn1aZ%^MfY>M)6BNIyxF9jdP)7!gAqv`7^ z+1S6Ebu2&v(i4uP4av1g zN0!f!tU`dGo})aUQU|4F88qqmqU~DIGOUtHCy`@WVt~X8p(Oz;`F8X2fX5v{Bc9c) zUa6Tlv7WPIZ*iht$zeCc$rX^B&m>?(Wb;mQ(J*Al?|>^#Je5SPwAU}c1FbU9X*QRF z-KUwBWV&c3loKRw(-LIpT0<7jGv9&5SC+krPJ6* z_}o)}AmDM%I6W``Uqv zpPI6Euix+On<{iQ-?G9BaU^id9Eq|?@EHd8e=)lM05f#;$J##v8~P|{_?#Sr9i%DZE>2d!<1G?RT9`$vso)S$S&kOMR26pldJ$8qdA10DFNU9Lg(ql#R#a8K~wTyqj*GL75U zjF33TsXtnny68QPZ0>x!wFh!^V(i~B&U=pB^!nAJ_8QRc#k{23AW(@QxVe6C0;$J6 zixR7!txqcN^D5Pq9ciP{HLW95K|FT%N&WhXsA;;#mrOmeD`tZF_q zx$xGIkhPRPWXNTL<~j2Y2nPUTJo4B$>siWDf~x(?MlqAN%>Mwy{wSNoJ|B+ib|OnT zcQ`|XBu?1I-r-0bpK8fm<8m(AUxa6*XxBa~k|-iFG_r&uSvU#->7Vj@^s7lW=`FDu zru-UzhdeW7;f)q)H7i(+)u!vHr;Ycsg_lo7Yc1BTe>xRyUU|X(%EWwS3qUtdI~oXLn&!j#o)}Cn8GQ@F*`W)!omZDk93Ir}6-Mhl}MP6({7} zatZI84l5~1sXKjtZ|rLnxUC$cYrP~V!`cvw0;ib4W>oVtBe4YKScX%M3CXKNl4%ht zen*j+CW%lZ8+X|WXi)ilsW?!189uqjFff;Q2VnZZBkA~IOhNoa(jVQj`YcqFJ%R^cTn63gp58~Rdxe$ImYHO zufNO1YvWAK-$f@}w70s_?)6PZ+Gygoo;^+2uJx79NL-KRc9lUK0fXFNut~Q5rE;Z7 z4RmcfXsm7ZOP1c3h%QWybMySj;ODqupQBYJU6T%p1=OInm67*G%%pEs&p6=w8p*44 zUe0T&N2+i|grj{w366lH=o`Hg_e_rG-*i zV*ykGpUMv0V0PoKYSK$2ntnc>KO*YjtZg>0735mv8jv|rBU-DW1xgMuI{}ZbYba$> zl$8GfG+I!kxc;Vn<9#0L($i14*&BRC!YGx&Oidu%1Ymw)joD`7(>3TqZX zU5nxb@18@PF!To>+NFLgGM7bjO_ED3a?nSe?|YXap}!&{H)VV{K8I&YqSwrguIemrWunV<;=79&(c^1%A|En6xj;9eVd_Hz zpL&T&QbZ`VC-f~^D1zt1_l4z<-280zY|)RA)H=JC>>@2sNCHuh@F@+RD?9!Twh zz`*IW3aj7fNc9XN)Lu_K>2QqRNl8jGgC;=F1TFe9|hY#J+herK1;-6L{i z86|gPsT^dEq*2>chJ@53c_9)+vPLe*Wh}WeI2%-+fGUMh4mtU%TXI%9V;cmLJwU)q zzR5&R+0JlC&(L$vwP#f5wdj`9j4uqs&3MCNRhCSzA4Z;<+S6_51LfXd7VX=%Z+p`G@L5&b$1LwYSa5`rd z34FEpqO#i?&ff#2X)p^xak@uoXPLsGD#_-ygD|>r;tJxre2tFWx4Q6elCp>UZ zPi)qy)Z1S|ja+EUe-UA2@g|?F!s^d)=387mYQP(aa9Oznvw{Br$GvX{c-nprJgTOd zEvLI&G+tO%+{qXtsUT#Z+OlhAuq`Hd<1sWrSzC{D$A3<1Ce4x7>sOZA$`fxGOSNVa zIXyOxFg^3yt0zj=WUkLT4D(n|0lBntWEl+j&KQi5_321lbkTOL7CVh(!G43`!mK0! z6?h}l+OFqP=&FW^8y!>pRz|hj3j^jIi;OQg8T!?uE?+Aud9TYyF1* z0CCQv;hidIuBW$#OWV6GJhDYIlNe%fhdss#Zaa!ElSWx$rM6~cMV89$L8?I=>p1|y z=Hn~V9CY^2U$L#ZQ&e*-OUXT^=yrBWvRXndrck5^oX8Y+$vkfDQ7nzSeVa!TT@vr1 zfQC~c5^>l0t0_*+Ry0Rzma%*^D&sGmo4?J9vUk~>;*kSpvE9vZoFr&)uKe&ioP9ki z@u_IWhgR{r-9;9L~FQwyL$W9(N?x)(I*y#b1lU8 zV)6)7N9L-lVP72-A6~UrG~>mh(d@KIeQ)ru4A7^YDGV?$xG9W&nHlTJtSuc)=&zkB z%TO{p+To&JnLM9tR*}gi_)H{M?yT-xSA{N2hsjkd5kHZA1$0L*$wn)(&!=jw8_67V z?(&ojk@GR`N%qZQGp`(xBOSuoTW`+!TO@~U zw*&L#dLOMDQC7&I-koDAe2eo;r*`h352ay~B5u)Sk9yKi8!Ow)#z#}RK=0{Oj!|yd zdMj74PLdOe1_lmmvmBz;8Meo>>oQBCt)6f}%O78AEOjd-v9+9yeI>P=pDaM&m0nF+ zZ9#Go`H4o*u5%>ug!pJr$&-wX^)-*hQd%zKL)(juIi-bUg&I%*C3<};HOj8Y(Z*d8 z>M13-wTd>4)a}8^AEjD3bdxIJRc4K%a<7fu`OS7CFpC~y?l>9dq4Y}Z)2uGu+B>O| zJ+sNYD#VMh249#JZn+-DyuJ30ghJe0+cnEe2G)5ZLM?-kyNK!t1E3#j(}gYcT{2Hg znpTBlL<;HiyLH^h*FN8^bL9FP<0rKEip>a;GC=vj$o+nuD-&W&lCjAVBmvIdp}{2c z^{BFFgS~<)aDi;f;)7CTp%!BA`v0yA27}V z>NDQ9PN>1ei@5ORnvaNCW119gjOTy=9P-#0u6y3MUVXK* zx(cA1B6K9X(zIyhnglHqrQ~o#00Kl{q8;5!G6sF4sRVJ&S}%9{{{Y!`yc}*?D=kvS z8KyH^h@pMk!WlfsnU#SVC*_x^A4)wmpU|V1lcVZ)8fLE?mrxmEzYQWpvZ4*D1V%E) z0Z`zOdnq}|HEM0|@BI{%lvx_L*HJvTUKF>7SDlq&Y2x!93oW1^R$Oj4QH|KZ$-z0P zSgG6niaf2ake8or{{V)`k>Eol<1A(&%%#hi*CV0H&T))Zd~JR9YUOd+12(A)YPw;! z)OE=gRhr@S=nS|ikX2X>qyYHGI3Q-Vjwe+A0FxIlZJzukbTwPaL^+D_bom-69G%l< zJR_5UI0GF205@8rjd%B=*reRHObA}u{w!OpQTZkA0AkEAna1P8fgw?z`8nWLO~pNX z9Z5E*>Ed;{(zQshCABffZ>S=y<;;ovWsRg@z3|c@&Q5XCw&~jOzwS|O9PS~G!$}g| zNhFsxa-mt*F44JHAppnCoy4DA-qoA5zNDl|PVqr&9@v$^{{V{EM?mLk$n{;gHMAs= zn~jy5Yh`)nX2UYD+D>uQ_o}&aG>W0&S9tB*FPP5zKnJ16B>Hv5R?8f%g6xhom6$>s zBOG#AWcvaDs7-Z!5I)hqCIet@lt}X5ZTso}|()nhjbd^=Xfj8c8HD zq~1>G@L8q-i7GqcoO94&Ppw{4<=%>&p$dgs%QDg`F)V^5%`X^B9NTNAi*! zCOsd%YS{cHN1H5OE@7g0V)&UJ<5sxQ*5Tx45*hBECL6LaenelFvV~Fr@4P2@6lTo0 zz755DjC?Dl+-Z6pl3KsdECHjsyMdU9=TYW7o4PRsBMU6Sc(FtAAWDZ{!td6~&5S7-<+}hbaf(MMI1dN&4o}dKa)bnzaLC1_&^*U;dt1Za@ zM+!$236K;jhTMAh;Ys>uy)sL0*g;ZOKwJQ3W-O<9F56qUAM0H5-)4)W-Mf6zfyo4) zQBYYUp04QDGchd$GRm?6*pPp0e@aQ|vQi!CI*fLf_frdSOR$uTeqf`5eTNmMIo8oh z#>zgY6nB?5Q_X_XHrFG+$^k!qYTTc>l%ujE@lRNi_B|Y{ZkJB65KQboW-R3LJ%CaB z*JcZ8oSFTM-$|D`qGhq>t|Z-8vyE2lAwOBi|cjenuXLAGa0F zo>dcEQMnsNkF8tjQ%2KGkt&(kl`fzGzyWy!wrk2#;O+T6SuR>H8ZN1#*m!C?$l@?X zsoh2+RmS%*@<~3N57w#iVF+^ff59IPa++Sr{`xL<;@s)+%N?9iB)2O%tY|nXD(xrt z=hnK@TrEbe-}GvZX(>6=mC~>3o&Nw~JYRPfg{A6x%x5=HM8Z7tnF+$KJCemlD%lc) zc^73cw~;Jz=*Ijz6U`b=szRY4nJ0M_{$>Gk<@bL%Zmc?oz^*ivCf8k^@^8nJy~u4U z&ry3EXsxR>$$J!)cnRN4SdSEz!jBK2yrrNmJ{&iO*nH8LOvP;gox8*z%GC z;q6QaCl{LH+$=C4+^VY!EGzos_wCnwb4gs6;{FV!7TT`^g`QizI$LYF1Kh`KH3Am562$C0)JRq^ z&dbRPrBq{#?jxl+)|ceJLR@xp)MS$DP(yMic_T-L6BN5+jZqO9j{tzrAUNoDj@38Y z{XfYG38*Ez-Zinf5m}3P=XjzZv*K;QF+3=3%-{jW+;kL@O}*>={{XuQ>*{xHPFsyW z+&=F)h?V0+A1T^?Pjs+y&ZjJsQgI4@H@HBRl z81LK7wTLt;5Cj<&hC^pOa5`tLZ5%%l)cP}?Plq3qvb*@7;%2*3WfQDW%2$MtsFiuj zfz%D5diU*E<&&4qfqxvM3^=J#K3_9FRdef`;Ex0W+&5=$I*tddRVG)hXq zOowWKak;QC4@~8bYKhyvyZsA2Do0qMH`5LvbRb2Tp>NH09$Kkb)6ZmfEL31pZm$Jr| z>-lCzMKJ=WkL3fN0`uCEpEaewzw$(5#ciE+tMaovNp90!Dx0|^iB1**On4;p92|E$ zN4;ZB?!Qw-qn3}UK-R%7nlQz@tPB#w@IPuNOJ#`}E(NvKxRUJaHnchRk&E{qLfaQVWT#^$Ux6qmE*rv;%NlsO-m_R*G&bS}d`ynRNU<)SFY1Y|DK-fRv2R z71i;;V#AQ!WahEQK2oi}-5O+78za1BB$n5x?nc%fmhik|rAykk!Bjwa&vh06# zD?%eIM2ie~ot2A9@qdw3Midepl6rl`UrWFCLEB46MvZ9mCc<*jtFT2@3KYHv{aH99 z^PjC%eiYdrXz^nwpYgHXT-q26zDa1<$uhz++fF(bVsH?BdR3Kl-`{_^KcVkSgUO#s zhU#mG-Xz*t3n+DxP^p8-0|EFx#~7$dB^34l0A%jn9_=T&gGi9w80MZkdxVj8E+lR8 z0RI4WQcfxx;+pTVR?Yz2OYksWdA~GIG6YPqiZw+q^7SVtf!K4&HF&1#%Dr6;eDh&* zW{R)6Mw%&PiEv>k%34R=kO>6xeSLtbOV79Y7C6<#wWgZuJR#%SBO6|L;+yKwhu=-XUXx`5^T35vCEVhR`^4#%` zDjKloilekw48BHU^Q37WNa5N^l0%J)@6c!3sq9#` zhPWC;jddEyHMhe~W7=EF07^Chy%>@P2Xz^&q^0NS{mmC=t7Tie>t~eAEjG?=+>B9CcmFilJMy%G-GeUTW*b7GDGbOSnvaI3G2Z0rmyzscpu)_ zMXAoZN;2IUmPkV`SNQ4ya)9zes^p%8kSbQ)E&l+J>8*_Bg6~EM`d+Vc))Cr6Jl4{~ z<_9ct0ulLeNCTd^sf^c;p`6urQ8oVn5sg6>STALgIF;g#DO5AWHx?`EMo(X_t#0DX zIU>VpegK9Gh^Mn@KZ=mbn^eYdS847uo=s;Xc(QFK5~O9YbDGKRnxt1eOLCBLBxUe^ zVn=NDts>Ge%E%oy-u5WX)bfZeW&~QJ09tj=BaY**HM5TtnS$Bs>fNpwF2Y7S3Z;`M z*$scCDoiJp%Ht$4@9kPgBUM zdS~DCth`aLgPpzkf_9AVJ;?T=i=!sasdH~W>yaZFNdxEUx6oDTuKP3cH`8riTib`) z1GZ#h4+H_gqkO4*8{^VCYDPh3#zXuvI(t+`+>prrQWfmsmJP+-mLZe_p0(Dd_H!~m z<|~AiUOC7mK2eUI)ud$d6vm|jC+>DdG0}?a;0Gi7hw(Oa`6~vHv%1VVfFY8907-OecFmu$3SGGQAlS%0oNRhL$g8CT~$?|7tNsi$VM-+_2aO?bs zsN;;Daar77=4y~=sVs7(y~J__N8ucPRvk+Yy{n%l-7|O=h@?h*pb8f|fLvuej(S!y zH%D8UE#tLEk(p73&TkaD@tKKy+vrV&rRj(LxKF)Z@`0Ey}vlo6$tnG37N$PmdnTqx8He3Gy3Xv_md1EZ{uIsNcWr{ZhA=-McP!GLhpK(W5 zr++#$EhoY@_8LyDCERNy(q&<2)Q5>Y;)?m{xR${741Ft&Nz?oDR(Jd)nBv9cN7S_F zA-jztg*?Xvb1%#DhB(Px#c(r$v}B%@3Du-uiqj!3Z=#1;k~@omzAaGQo!JTxl$&;r zHvmI{=)YRgcruZL3x8Lqp;m%94 zQZEczSm}#-Jn{gD9%(IaOn(%koE(y%j1ULqZrC-7ntJ>H0JC`D5nw~R?{uv)AXC^kvD^J8^{_qlja>b zWnsAn2VC=>wO1$jQ!5;Cj>+3-;1{w%G_j-+%MZk?g;8UP9OYY%2PZWYoU8Kvi|s2o zYPRtC+NH0=MKUaMGr;{=so0od&KxpvjAxpOQgT<<_UroSyj#`%`;mI%ix}+fBEOzE z;gZ_g6q@0Qw|9;;Wf>h-K-`mz00#oJl5bbNdHQeq6;74Ez3cWmUqX;+cg(Uhaavzn zpWwFO$7_N!*ZEh2)~e|z^rAa!^&>8$adOJjZdnz~n>h?g&t9MTsj7Qqt&JuHAz0&4 zxVFXr0H*`yKT3x6pg)QHh=2-rmfE2+lgCg!YS%-to|`7yidU0;I3Jl0Db%V z)_+gGA(Jz^T+GwjLlxhfI|MHyM1T-L3_v)+APf$DvsSd_elPF$EV>^m`TB#)bqXvg z<=dp2vlDF$aC682vvvOfDaSQ2cQ3js)~K%Qmg3(^wS!>-{^~g$S&#g=CX!8zr?~>( z+ywx2u7xFkp`9__yE090a}1W!wahkBJ6e}uHheBbZgNOsOMIa4KDek=%h)GM(Dy=X z&;FH5T~_u>jauNmcLvyQC{r6iQTdfNAZ%xjdQ~#CH{od%)s$Y6%e}=o0 zPrkH$w${^Iy|FUMx>*Lo8)zH_80vGLxEQUWCm7f0XC$1E*G>rH@8dBw!@>p1?NYl? zVZKw>gl;j;Y836a=g;Z?07a!5>!LdT7~#{>P_tWnOn?|+oq_;(0H+`jpmW}*{x|MX z_eh9`cwkpKD}Zsp@7}W{eQRd3GDj)S@JVFhjxop6JXE!1lcDCP94QJ(a1~=DUI&D5wPXhFmD3X(qUxE<98-n4{w_wG`1GlO*_+mh@zN*UOm z+2sEKTGEluf>E=JBXVSH0u!mg@Dd{48wZWO>vm$U zi_eEq?CfqeYY63-6(q!@pP2U})0*@1w&h1|74q3_(yfe|qus|8)4~~GjR-7G(5l0Z zpdNa6t{l4A*N)phjI+=qwioA0tUg9tg++}c+LsN zf6ZD+a`~U1^h{lRtH8ljU*Fpu<8&HaOce5K93~2Y zTk`zDNgU)1`cyq@?_a?U`64w*(rGSiksT$uBHMc^ff{Eeh#4f{FaUp=r8Om9`VDk= zww;XA$OABWPVid>Pn)Jd^rgMDO=y(2b!o2}=;7MjDsKF-DItKzI2h@UxvH+)e#H2r zoz%ZHSCYub%$0ndqvlh};~Bz`zzlX3Yr2=;u?=__UaQS4RSrW(*Ie z{n!Jz6=fdSHJb1l8JM;tZ2dSte@aEB$$cD5LfvyIERmAP1M#`WIX~~UQPNv3 zi#5a+*qR%dJlLaVjdw9$D-mto$I3tw9Q)O;i~Nc;Xrz7@4~Ou_i8P5ei>T4!DtQh^ zEA%Ai3_g|7nc9>0M=mu|Uzx3FlR@FX1zJxvrR0)28I7z^?qcu3$i^2LInEDC=TcbU zn>rj^=Sa)-k00xo7flR)b-S5ED2g(y+eSGDj>Ccds;=c5vb&6_BgVULad&k05TF34 zA%O&rGC=O#X%8eDAHtc zQ_YgoMuK*THw`3&NIb$vP)6(yfRpJ|%l`o6ZocfaH57*Wwf_LbSYEZJWEN2bk^cbY z?89V$o}BIkl74J^RX1Ay03WeFPS-0OcA8z`NnxH@1-yz_g7C|L3vKPc%j@e_{7F$B zb~w4ylTy?5U`j^UlT8>71Zs+|0By&j00%wrMOFE0$tm??zYerIhPimwqzg;CokBTp z9|{Wjdsr%v2_=C8t^fzxuPdCZ-}s`pO8uzir%x`SaeFLKIt#ZKD-*B}Zvv=Ph#u|1 zCAsVGRJ7aTzW)C9S*lBuI>9tWJju8GGY4ec+jkCB5_+8A^H+@N6>8bi*UGiiZx-pq zFtxK5XFMkG5CQc$d{RWKJ-wb-T5cJRBHzs+1h($CHy|LHk>DSh+ z7|AsszKENw*+I!fN1jxnY0RCni zDEkh6_0fhGrgG(#XombMfiHYr1UEaxGb@}BNZdIX^{u^9N+}WP{{R_k@tlpOc-qHO zk=i-#E&)i;?To~Xsu(Eb2E%;El5$6C&l_$wTP<=WJSU{V1@!uQO2XFl+Q<$04oKd+ zGv8}tj=8GMm&Xzd@XqdCE5$mcmBBH?8liF!{OFE$?Hxfm9ldJV>En!%Ur%wHiKoc1 z*jlagvTqSB*6F2YBWDqYU_N7#+%F`Nj&WR3(@g7ov^2KUidpHR?p0?N&lHiM41lYh zq-1oCH|4-t+|FrF93vfjyS+T#QTy+`{J$1Q5Cux zL2KpN+rzXfD&TRS{M1<~646`6CARZb)JZPM8Ab>mR!#}^!TMsO%D=q=E=jK;lG@(U zL}u!EC7$DU#7I1uWZ2|)$PMU7t7BS!m6V&>EEX}P$G}H#%xh{)Zps@hRIxpO=?6Z8 z-m1JM?f3i>b!0)*BE8eDZ0xV$-4S`oiX$1_lCB;>)R0a&$lN;ANwpsSrK@DIj$y5x zUDOA%fuTrSAxyqvf~7`I6rlk1=RGRYlTEto`S$#RitF6+%C`DkKL{0F<86;74|fxW8`7J=$lT zVmM`rXC6eN8)>1ALKG6xM$8V}^2*yzPb87X1xkDRFYX=D4XLHX+A1Ur%`C1^896y& zu$DbKa0OnS6n&MUBM4ID8T{AI!RGMiILQaCUN6a;9e6@{W1cp3NL37ub_0fHV4UaZ zarCLZ2<*CD%));x;IBY4SxM~KBh8$JwGK%fkTKQ0suyLbvgz7gv{2lxqQyM18>1CF zeqqVT_swYtC2C(oIZf%rfbkT5YTb(>8cbyleLGY&ZP7QPwc#ts;qf}leQNg#NM#`K zht&5UTCFR#h*x?vTb8>XIJLXeqCR9Ok2cU)i1`irsWmOhW>Sx2q@E_F(9`iQ>rZLu_!05pua@46zdMYZO)u+t}& z$_WsQJ9JgIW+phqrGo-bUCub_G6AYL;TL^b&f5NS6|5I4@fSDNvD~UlCf%FEnFEhb zPJ8qKQc9h6RWsI{_L_Q^SCOslB#}}ah}S4U!SoxLob}`DROQEh#rr0-9WHBYi7u?J zCTp8^n!*&CMFLBS3nB=?8@MErPki>NQEJ?LT3?@mDJrM={)2e`0E=U3Ztc9jml*&r zmS&Nr%EnlKD(uNUNX1n&l2_yVha0_lAvIkyOI->Z0|mUZ#T4>0stl>f<(sJ|vVuUX z#(yeJ`<0Yev0j|r$$AakvCPPeZ@oTXktYg(p4FtCvo#tl7OsZf0XPGYeXBNZSNuq0 zlpisG2ex{O(g`)Qmnj2cs+XQAF)QAXYe^X7ehR#eX{XN4*D^Dnk)YsLbW@r~ zJ7cKIrK8+Q{7fnG)SMGligpN}@d*&Qhxl@20ugdR_pXH!gSa3sZe^1UnY=JbV%k~Xs@DiBxQy_ z<}l>@*E*D-?G{+u8{BBq=^AeIn|#w9s-E3{rF3)V(~_YmIHEq<=H|v&#p*JkKbJTa zE)kdEGaOwsH+JEsj|xx9>(GCxs7=HV^oT{JliRD8f%!XAJpTZ^RVR_kR$4kEbv-WP z(&AZRMO1D=u>7L6$CF7(6=Jd2f*U|Vw%MloHmeAbNmE*fUFr?!zLo5(ERB3S29 zmIpZ_@6x%PB&F7lh|O`KmEFCK)Yh{=&ALyTQbr44_NY^F(N@K`g~jF7#Bs)uhC5%-kC*gCi=q3mX&z zkaBwtxa(Za`8SFkC-J3t?~e2Us>;7StLO*$zK8XwyVEsDl+#4EGZgcpB(ChMkgh+J zgMvxx#ZsJnnysB>nn+cja=2rVSwrvolhUDRmWT~dyAyS^qO+BLaOzLDdb(foF=bm( zMwm!bmns!h9lMA<>wI&nvl$}M_?f9K-OAf(*3OXKN_9JkP7!yw7$@n1Kl55)i*DG? z*A)~}^o>ZvbbQu3-b^HJK1Brl+lb_hcCB(jIOyfNC2eK+`}vNS2bpY8NhO@}fS|5$ zRlR*Nj=a`#N)f4OcFSLabepXYP)Xj(@kA2a$#f=%a!2McRb`c1Z#g&wXCR8@^%7YY zot>Va9HA>{w)po{OK%Wf>6TX}JD8j`+L0nB!yTtAz~Hv_+C7@F_&lQJ`hVHJY>v`L zoi9Y+v`%F?bqMxUaR#Q+Cgz| zG!`+%9Fj?Y1XDX@!mbOmH-D6c$JA%NS~2kcg(&ihlH)LzXXn8WocqPB~o`CmLimJO#{{H^}g3hXlpAguYv}@Tdm(6>4-dj-2 z*q8(auH57jhCCkZ1!)wzy?y@xVkLF;JWFtO7nW;rA&%%lwKjB}qREqPaI6)Ik9vuI zCtsKA?oum2`yWw~Byff}$&cIx#xeQ|n_Q@#ki^C2UrJt8OIt&lWHhxtikpOwc1p64FC40}>Lpf}UfCKqzZ-!k00v*(czRrvt-Zh!dI6HNw*-wj6` zCf!3Mspt8D#z;8E)Al^$+L-lJOtx{*Zef>4_*r5zHPz#>jJQ5*YZ!?`{{WRw=08)8 zO-x->SKsIUM6U1ev)-y!=Ex&UD#Vu$a(0j6BE|C~jQVUi_pM^>QvU#DD`N{QFE>f} zksa2fcl=i{f(6aMlVNvf#@2Jj)dTrR@0zlFyCSI)KZM$XMQoS4&y+R2RvWWo(8R%Q zkCu$&lhEQoJpsaulUnhLn{oQ9`k8#vicje4=rz>Tu8U)DaXqYd)4Scu*DfOS-BnyF zmsW>Fy)C{;ElM+>64DN ze68B#ykF}`&m3w$UcaMfc;=cp;k-wV)-|?m@sYf|r7#x+fsDHP=RK;9(^BjFmZi|z zSz3J;PqwsJ2gD?D62z!O6}m6x#~9B)YR*pLlJotNE~z%(kM74lE7ha7msPcs9}&4C zg;Z{EvPQYej)0ROB=$Y3`F>{p{D0Y=Jy9Jp+bY}KhE!|&!#s~Gz9x`^5ySV3$r#{tNbdeRd&K4-&6>k(Lb7Te2 z7#{xBRpAOGEt$k_8QB;&{MB4-3yf_Xj=iXvY9nuNSX<2%z*!pv6O3*+>yF3iQQFy@ zofKaiUR+$@(d~*&5K*|R z5_rY{AaTH~X5*-@KlW^{n|=E7>oR{B`&*FBFZQ-=Dv}qCxdtnjS31$icw2RZP`b^i(s_1ggVD<+xwIxZzlK=+Q6<|3K2$OW4<;2t zxoE=F4(+o$Zmf4VQ=L@f+Z268!NDn~*AJ4nY+2Pd{gP3aKHJLo){8<=#@ zEJpL&I_C;iS7MMr=%j)NuhymN>*@FXM0Zc~JkB0_jgYBnEG`Y<5w{WrSq}rCz$9*~ zDQ>;La;T5XNj3md9Aid851u*$9*>)RF67jd(fBB@bm z*SvJPMxhs;kL0A_OommFUOk0(2KH1*B%hJNzvz9h{dXc6^pAWD(&yF z6?x=xcqXYQw%?M;bdM0riw$-;?bQTV4Qsre+tpMmg#Q4gah(4E)JJNGKb6@lv`I&& zCH0lE+)N%#zbB`d0U+ayfK(rSwLPU|NsaApMyICe(#nLxEw9E+9G~-9w|u5f#4+4) z&}XGY*3y^iLh{D8cCcwHEu>cv`4RYnd&`*#=!KUlxbw*cc>12Euab7xFBSU{2vT+T zWP)EoX?7AgWH-=7JhDQ-f`O$HfJopBNM7>+r$D+>a_0NWxq`Hpk^sQ~?Z)|k_hZT?@aQ!3p`m*#NP z%(r(su_+vKZ8u92kN`(=xdZ&)E(>R)06NjzZL-NyNabWFiUN8H-zo}Q#ub`TxS467J6;wo3&V$RAUWwP6}tS~Xil=AUD2r`_ND3r7dU2%9`6CC&%X zWA9aJuAi}@>uB|PqRpt?YZrF&8+BNM$ih>SNXvjv10#%%nf0ouw>eENzS(O@B*(rR zw1I3Vnl&M9t%^e#>={lv_wQDOwaf2iWV{edr$rJ05~-Eq-VQqkKk7evMYZW& zZ9Bx#gp@j5M7KMX@w@V{`!bsKeH?8w&h;;hthIh0{1vR)baQW8`)gRPm)2L1?sfJ7 z2>ojhQ%h!^pV)@{OnZwxYWck1iJlk;Hxj<~EiwLILb2gM=%9L<*VEHUKP59Sn04dX zrH|mDUC>7%j`12Jw1zhE0krnoK{=}9?#P>@hrSx!uXvKjTf9i_=AV6y(LXCoHZrmm z9nSBY*Cf?*I)zcL9ll7>V45gr5X8G-8{v%`k^C~GupHnh#yw62adhj)`2PS0Ut-%~ zHF(jNa`|DJRN#5CeCiH546!)>0H6$xY7?m?_iyj^C$*!+r^DNiDI#aTA&$~OJ#tAM z003tm=AzVBTP)S@z+Gv=JyuKWDF>fv3~I6unN^Aqt_QC!K=u_M^0njd{gGGSk-J+v zTE+2C9FzGm`Q{Ob!);T$jC8>a25%1ANBk=% zf;pJ4UBl;KIu3_u`WlI?SHIi;07a9wP2EnS`K{%RNCw{O`sogG2+QP;^RO$ALGM(0 zdtS}I=lYjjYwJfVsQwwPpp{Iovf@g}QpYLj_3^BCl~+wwGtAD58b zGm6o#pXfq=Es@uUZQMw#$s9|$;ynQv9Q{iQF3}AYV$yl`hGBsUjxml|jxqMBQg)m0 zWnKv#KF7|~11zC@*&!L~6aq^V_c^29i^W#U43gXOVmpGJsK==ur{1XO)g!H%o&I#5{6xZI1l=ae`g ze$`cX@{{1KYx1^<<9XN52%$u$ARZh0=Qycx`K--KnRe54c@C>|VPexoVuX$yMf2d1`Eta5 z)NQ2O`>l|gvfZsm9*tq*OPxYt<(q>Fqp)X|Z=NJ@}U(NUTU&(mM zI-|#nt~9G{V%#kM00$(m=6prWWJpwiVgnjE%MS_c>yp?EGI#}zR(9IgYx_~8X(##L z?_@5yaTMCs#IrW&fibG#LWNRB(0gIC)2J1G-H@#!zjwAcWO#Cf7;S7ggYS{sX}y_sg2%BBZS z26|UVgwAGViG5cM6!UNhE_&n0ZHYr22&!?BI-7+^=U2a4&%nYB#HQ5arFZ~hpVXG_)T zgOQ5phkrvRL&N+cfbJpretOo;*#v@1BHQjqU9NvGagOzyfonZkYB8IVvLgm7v~B7Q zN5X4pay{H!Ni2$?$u`S{-PVpi33CEHvf_W4KTg84@V%Qz@xCLWfb$X%*ePk-(Be5Go5E zzwZ?Q;iyS-2B9Uyu>6vpsEP(L^&ZtKpXLdT2FCF(B%EKNO~8eW=3#(#tM=e^29u># zqoONhte!&Ms#?5FfhU*)lBWxj+wsu!1KzpydNx`X1SGMK%ZCK*SjPcRr4_R1^=_)s zO&Y!?jl+i-{Jk*W_NrB?PiCIn&f8CiogY92sxyS@F61x%9cmRIhec;;3pHjh)4 zVfCuEqU_F5ISn~&WJ|k+1_dm`>NZmX|L#YHFIU^bB1~@e{%}VH^#@Rn<;JIxQ*m)tf zFD1>o>FnRfRU3(C1df>ij&eF2Rx|Y+^#1_Ky7byLo2cg2?W{EUZ{n0&#T?huTLnd$ zSm6iF&mfEtfk4LX>^UO1rqr~*U+MP0so9Pcwn=!_TZy$vEv}jwGmxgH3 zxCtz?lexR?Si<0OlGx~`wDPZ8ztz2d#&4(h;EUF@xd2OLj7xJqqaCZA%nXXf{K@2D z&m$mbpvbCmPfzdu%d71Y7dB!Ry_uufJm&KEOP!!H?O(nJ?N;5l^(A;Y=<{#*8N9if z=8(Agu%vUGkLJ$Fgt=aQIV8hNn!{C(-_7*Dlgb2?skS4VkQY5J<>7xSLMkZ5^_2Y zN7|t!&|wAOS!ase0@6D)V4j`2)sx#uXm*OiSoSDc1fFK>0Col0&wQL`?ka2B@4)Y~ zx0WJHiJuJ2tr-9l@@!|SX$*7`)2@rYI!h4X(C;nc)jq!H&5N=kgvJ`qnCVlh{x z4bQ)C+@~iets}ObrdsL$0O6M5HtIJKyIkEnnI@7Vssb~%dXlODz#FrUD;FlzQ`hC~ z>}^%GvR}oKSTy=jy|Rg~CeovMXO1%rvdXFyg^_UB$Xt?0z^l1+e&4@EA^2T;zv*^Y zFQvPSM%12I<-L)uXPzMJzGNW2#C3i=%gfVT$j1$KL6$$w)NLWSYE0x9+78`rxpy%H|r6Nl!ek4SI#Vcnn z4EDIx;g0J*Zs6iE*?;OiiQ|vfx?-snPeaF1+*ccPt6MvwypKN!1o~yxud3>kG_u74h*ggu9FlR{ zI0CU!QGDNoYT)F!`hr+FzL5F(*q+pIXOAvuG-?KdynKoPm{-5 zdh%2M01`FnHCtbYw4ci`#}u!#`g^~kLpZhcDB1|QK6N=o@ioLCAVyJ+PNpw<;WenQRzRavYPTZy&p5}#Bn16 zR1P-o!2P+Y@@R%O@xPHHy5*S+V`=J0DlzUiW}zocu{URM_S0q%KZh7x959k2z-*3l zxntwg>sPvZ`(JcLSkF~-i%{^*fR#lSB^^HqHs#m2 z@5D^^D+^4^Ztz;|xM^6g%jO9N(g6%aats5G^_!}v_vF$G&(!1Mk1of=`nB3h1a@x< zp>ewo%z%W!;DQvX^#|6p-#InfGgRP))=`9qTTQS=VsQ*pLyfz3qsR*MtDP703{gC?ThKAMw&TpFUpYk+6Y#8F`q@=y>XsBDvk12@BZ1M@A5dLu!Afw z5nuwvG?6h?Rz?g)Facb39SA(;te=0mR(RFnc<$2T3DRVplWn>-^ zj`VsEdaQh; z8z%I0S*~G7?q;=XYjWatP!&K%+zA~(1mOK?k8LFSU*tamzmvU=T<3tJJ-O+|*GZiDQ#g2<*6MvVVtETo5|21JLJ_)=mE+uEv2o(d zUnuCT&7{pHmbZ{WB+#n?EQJXRo|z-Ic+Fi(HD+!t^k_eZ-WayHv$(s|k=3opLmByT z+_&4;wP4_++h;^RRK3eb;y$}+K7lryXjHUO;TMI!aF_LHhx-1uWmlVMv%GtK#w zZHpdI=eNnZ!0XSwR&l3K>-<;jOkM2juZzoX4K&wD65m`OKI})FjJaa>v~(p%VTK`v%w(9Kg5MvJ*0Xa+4m#TwVV`p;r{?*D9e}Vbh5Q& z)ODz=qm{J}HW;m%Nj9Wv%yJWqY*Hl7JLen<$tSfQ{{Y#qh3rOX?pMTDD9{IvJN92O zP%$qfysa2sg8|^(>5O{S<+m2R{r=>3hnGsbZ_I==(@jhmVT*hiNheo**4vCmP(AnEU|f6**!W2Ql64Xf?EmUq0JjGB$ZNcltM zp?r`tv`TnT063|Xwx7HFzWkBZuc7Mh${8Bg>Uot>;+0Dk0Lreheq3^Kv}2$Ilis0i zZ>CMt(8kMN7k772S|Df=Faj|7*Z>J6{Q~jRinEonE6L+U)HMs=7NxzMaoj{jn!ji#y!GaROc5Ds75Il1UvtQu{*^7p?&S zW7t(9^~g0^F|P{dJucMVO38B|m(0iI4)Txz_W=h!mDQJzCtVmq>*nm4)owKtra&Sw z#~kRYRxk)e1B`kD*Z%-DjFqkVF201duIszKBGwC(h0@(n?gW__XFqYqGw)et@Rx*b z3oW--15MJ>)_syqbBk#lAywP7v$s>oTrNj*>MF10TzvKZOLp(VA9xSo;u_*u#Ikwv z8Dor$V6yE2a(ZRIO13JwQvAQMT%97I*COKjIPBDwXk-QPl?f0Cpd55By!-J=_9E}H z1IE4=Um9E5i(OLME5*8dI2PmhQ3oilBLws=Rq@ynj`i8;GPpf-&TmnTNo?_==$Dor zF0#}v0og2O+CAU>khwso-z%TJMDp^bLKvKOd(?EeT4^%>0K-=En8-IPBC#!j?#c#F zqT;CsOXy6aWq-tu&!A%dIZmN&lE)jj@+%ckaol7O54CNId)bay=syZ=-Z`%CeAZie zy@L$t-h$jC)qQO~nwZlV@9BDr0kgq7}Q3 z_>)Y^0_|oaIOs4wTvk_iFD0I-csK->?h_5X?QLlHkiosaRT0G(%rbc-<-c00T$L`a zzoIR4?fvYLyKyH35Q!TCx#xk$9k>Fu?59YnEVIpE*FJLmj$g|IqURXTbB=1N+<6A~ zM|&HEj#-h)DHD7$yrf_*(nrvH{++4U@CQ1z{I>oU)UK@(<9(`#!$b3Yq4(uS2c`+< zpyvjy1PVhYR5Jto#kPPCu`J}{x7w`QNx#3lA*W?aREWIa5Azj7 zUUAj9@B36Y{{Ry=**Rp8+gaiu?5KI#+ycXB{-pl^@vA11(RlQ9os~qg0x};1pIU}p z9xqkQCF3smQMFX<`HKJuKGc$>V3mcgE?`yEE}C7A@? z_07C@PjPiCnXKYs;HfObVJ8Q^bI3lmM%OET4PdS`PV1>0+CRi?S!ZWO-kHmipf>}I zfyR3Afm0V-6OHK4Y|)nNfIlhNa&wGvkGD^*YW_@-+VEoKOoT9vvK0PYd(ysTWtm;q z9NS&R1dFs7$DNkPE_XN3l`1P(>3vKj_G}hH-37Jgp>H@_J1O-wc}RIM$eT+qKn~JW zb->9y*F2MMm*@Tt*#7{cPX04-;``a8wu

my string of file

'), - filename='file.html', - file_content_type='application/html') + conf_id = discovery.add_document( + environment_id='envid', + collection_id='collid', + file=io.StringIO(u'

my string of file

'), + filename='file.html', + file_content_type='application/html') assert len(responses.calls) == 7 - conf_id = discovery.add_document(environment_id='envid', - collection_id='collid', - file=io.StringIO(u'

my string of file

'), - filename='file.html', - file_content_type='application/html', - metadata=io.StringIO(u'{"stuff": "woot!"}')) + conf_id = discovery.add_document( + environment_id='envid', + collection_id='collid', + file=io.StringIO(u'

my string of file

'), + filename='file.html', + file_content_type='application/html', + metadata=io.StringIO(u'{"stuff": "woot!"}')) assert len(responses.calls) == 8 - @classmethod @responses.activate def test_delete_all_training_data(cls): @@ -580,14 +660,15 @@ def test_delete_all_training_data(cls): responses.add(responses.DELETE, url, status=204) authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) - response = discovery.delete_all_training_data(environment_id=environment_id, - collection_id=collection_id).get_result() + response = discovery.delete_all_training_data( + environment_id=environment_id, + collection_id=collection_id).get_result() assert response is None - @classmethod @responses.activate def test_list_training_data(cls): @@ -595,22 +676,23 @@ def test_list_training_data(cls): endpoint = training_endpoint.format(environment_id, collection_id) url = '{0}{1}'.format(base_url, endpoint) mock_response = { - "environment_id": "string", - "collection_id": "string", - "queries": [ - { - "query_id": "string", - "natural_language_query": "string", - "filter": "string", - "examples": [ - { - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - } - ] - } - ] + "environment_id": + "string", + "collection_id": + "string", + "queries": [{ + "query_id": + "string", + "natural_language_query": + "string", + "filter": + "string", + "examples": [{ + "document_id": "string", + "cross_reference": "string", + "relevance": 0 + }] + }] } responses.add(responses.GET, url, @@ -619,16 +701,17 @@ def test_list_training_data(cls): content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) - response = discovery.list_training_data(environment_id=environment_id, - collection_id=collection_id).get_result() + response = discovery.list_training_data( + environment_id=environment_id, + collection_id=collection_id).get_result() assert response == mock_response # Verify that response can be converted to a TrainingDataSet TrainingDataSet._from_dict(response) - @classmethod @responses.activate def test_add_training_data(cls): @@ -637,28 +720,26 @@ def test_add_training_data(cls): url = '{0}{1}'.format(base_url, endpoint) natural_language_query = "why is the sky blue" filter = "text:meteorology" - examples = [ - { - "document_id": "54f95ac0-3e4f-4756-bea6-7a67b2713c81", - "relevance": 1 - }, - { - "document_id": "01bcca32-7300-4c9f-8d32-33ed7ea643da", - "cross_reference": "my_id_field:1463", - "relevance": 5 - } - ] + examples = [{ + "document_id": "54f95ac0-3e4f-4756-bea6-7a67b2713c81", + "relevance": 1 + }, { + "document_id": "01bcca32-7300-4c9f-8d32-33ed7ea643da", + "cross_reference": "my_id_field:1463", + "relevance": 5 + }] mock_response = { - "query_id": "string", - "natural_language_query": "string", - "filter": "string", - "examples": [ - { - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - } - ] + "query_id": + "string", + "natural_language_query": + "string", + "filter": + "string", + "examples": [{ + "document_id": "string", + "cross_reference": "string", + "relevance": 0 + }] } responses.add(responses.POST, url, @@ -667,7 +748,8 @@ def test_add_training_data(cls): content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) response = discovery.add_training_data( environment_id=environment_id, @@ -680,46 +762,47 @@ def test_add_training_data(cls): # Verify that response can be converted to a TrainingQuery TrainingQuery._from_dict(response) - @classmethod @responses.activate def test_delete_training_data(cls): training_endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}' query_id = 'queryid' - endpoint = training_endpoint.format( - environment_id, collection_id, query_id) + endpoint = training_endpoint.format(environment_id, collection_id, + query_id) url = '{0}{1}'.format(base_url, endpoint) responses.add(responses.DELETE, url, status=204) authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) - response = discovery.delete_training_data(environment_id=environment_id, - collection_id=collection_id, - query_id=query_id).get_result() + response = discovery.delete_training_data( + environment_id=environment_id, + collection_id=collection_id, + query_id=query_id).get_result() assert response is None - @classmethod @responses.activate def test_get_training_data(cls): training_endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}' query_id = 'queryid' - endpoint = training_endpoint.format( - environment_id, collection_id, query_id) + endpoint = training_endpoint.format(environment_id, collection_id, + query_id) url = '{0}{1}'.format(base_url, endpoint) mock_response = { - "query_id": "string", - "natural_language_query": "string", - "filter": "string", - "examples": [ - { - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - } - ] + "query_id": + "string", + "natural_language_query": + "string", + "filter": + "string", + "examples": [{ + "document_id": "string", + "cross_reference": "string", + "relevance": 0 + }] } responses.add(responses.GET, url, @@ -728,7 +811,8 @@ def test_get_training_data(cls): content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) response = discovery.get_training_data(environment_id=environment_id, collection_id=collection_id, query_id=query_id).get_result() @@ -737,15 +821,14 @@ def test_get_training_data(cls): # Verify that response can be converted to a TrainingQuery TrainingQuery._from_dict(response) - @classmethod @responses.activate def test_create_training_example(cls): examples_endpoint = '/v1/environments/{0}/collections/{1}/training_data' + \ '/{2}/examples' query_id = 'queryid' - endpoint = examples_endpoint.format( - environment_id, collection_id, query_id) + endpoint = examples_endpoint.format(environment_id, collection_id, + query_id) url = '{0}{1}'.format(base_url, endpoint) document_id = "string" relevance = 0 @@ -762,7 +845,8 @@ def test_create_training_example(cls): content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) response = discovery.create_training_example( environment_id=environment_id, @@ -776,7 +860,6 @@ def test_create_training_example(cls): # Verify that response can be converted to a TrainingExample TrainingExample._from_dict(response) - @classmethod @responses.activate def test_delete_training_example(cls): @@ -784,15 +867,14 @@ def test_delete_training_example(cls): '/{2}/examples/{3}' query_id = 'queryid' example_id = 'exampleid' - endpoint = examples_endpoint.format(environment_id, - collection_id, - query_id, - example_id) + endpoint = examples_endpoint.format(environment_id, collection_id, + query_id, example_id) url = '{0}{1}'.format(base_url, endpoint) responses.add(responses.DELETE, url, status=204) authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) response = discovery.delete_training_example( environment_id=environment_id, collection_id=collection_id, @@ -801,7 +883,6 @@ def test_delete_training_example(cls): assert response is None - @classmethod @responses.activate def test_get_training_example(cls): @@ -809,10 +890,8 @@ def test_get_training_example(cls): '/{2}/examples/{3}' query_id = 'queryid' example_id = 'exampleid' - endpoint = examples_endpoint.format(environment_id, - collection_id, - query_id, - example_id) + endpoint = examples_endpoint.format(environment_id, collection_id, + query_id, example_id) url = '{0}{1}'.format(base_url, endpoint) mock_response = { "document_id": "string", @@ -826,7 +905,8 @@ def test_get_training_example(cls): content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) response = discovery.get_training_example( environment_id=environment_id, @@ -838,7 +918,6 @@ def test_get_training_example(cls): # Verify that response can be converted to a TrainingExample TrainingExample._from_dict(response) - @classmethod @responses.activate def test_update_training_example(cls): @@ -846,10 +925,8 @@ def test_update_training_example(cls): '/{2}/examples/{3}' query_id = 'queryid' example_id = 'exampleid' - endpoint = examples_endpoint.format(environment_id, - collection_id, - query_id, - example_id) + endpoint = examples_endpoint.format(environment_id, collection_id, + query_id, example_id) url = '{0}{1}'.format(base_url, endpoint) relevance = 0 cross_reference = "string" @@ -865,7 +942,8 @@ def test_update_training_example(cls): content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) response = discovery.update_training_example( environment_id=environment_id, @@ -883,32 +961,33 @@ def test_update_training_example(cls): @responses.activate def test_expansions(cls): url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/expansions' - responses.add( - responses.GET, - url, - body='{"expansions": "results"}', - status=200, - content_type='application_json') - responses.add( - responses.DELETE, - url, - body='{"description": "success" }', - status=200, - content_type='application_json') - responses.add( - responses.POST, - url, - body='{"expansions": "success" }', - status=200, - content_type='application_json') + responses.add(responses.GET, + url, + body='{"expansions": "results"}', + status=200, + content_type='application_json') + responses.add(responses.DELETE, + url, + body='{"description": "success" }', + status=200, + content_type='application_json') + responses.add(responses.POST, + url, + body='{"expansions": "success" }', + status=200, + content_type='application_json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) discovery.list_expansions('envid', 'colid') assert responses.calls[0].response.json() == {"expansions": "results"} - discovery.create_expansions('envid', 'colid', [{"input_terms": "dumb", "expanded_terms": "dumb2"}]) + discovery.create_expansions('envid', 'colid', [{ + "input_terms": "dumb", + "expanded_terms": "dumb2" + }]) assert responses.calls[1].response.json() == {"expansions": "success"} discovery.delete_expansions('envid', 'colid') @@ -920,15 +999,15 @@ def test_expansions(cls): @responses.activate def test_delete_user_data(cls): url = 'https://gateway.watsonplatform.net/discovery/api/v1/user_data' - responses.add( - responses.DELETE, - url, - body='{"description": "success" }', - status=204, - content_type='application_json') + responses.add(responses.DELETE, + url, + body='{"description": "success" }', + status=204, + content_type='application_json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) response = discovery.delete_user_data('id').get_result() assert response is None @@ -937,66 +1016,90 @@ def test_delete_user_data(cls): @classmethod @responses.activate def test_credentials(cls): - discovery_credentials_url = urljoin(base_discovery_url, 'environments/envid/credentials') - - results = {'credential_id': 'e68305ce-29f3-48ea-b829-06653ca0fdef', - 'source_type': 'salesforce', - 'credential_details': { - 'url': 'https://login.salesforce.com', - 'credential_type': 'username_password', - 'username':'user@email.com'} - } + discovery_credentials_url = urljoin(base_discovery_url, + 'environments/envid/credentials') + + results = { + 'credential_id': 'e68305ce-29f3-48ea-b829-06653ca0fdef', + 'source_type': 'salesforce', + 'credential_details': { + 'url': 'https://login.salesforce.com', + 'credential_type': 'username_password', + 'username': 'user@email.com' + } + } authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) - responses.add(responses.GET, "{0}/{1}?version=2018-08-13".format(discovery_credentials_url, 'credential_id'), + responses.add(responses.GET, + "{0}/{1}?version=2018-08-13".format( + discovery_credentials_url, 'credential_id'), body=json.dumps(results), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2018-08-13".format(discovery_credentials_url), - body=json.dumps([results]), - status=200, - content_type='application/json') + responses.add( + responses.GET, + "{0}?version=2018-08-13".format(discovery_credentials_url), + body=json.dumps([results]), + status=200, + content_type='application/json') - responses.add(responses.POST, "{0}?version=2018-08-13".format(discovery_credentials_url), - body=json.dumps(results), - status=200, - content_type='application/json') + responses.add( + responses.POST, + "{0}?version=2018-08-13".format(discovery_credentials_url), + body=json.dumps(results), + status=200, + content_type='application/json') results['source_type'] = 'ibm' - responses.add(responses.PUT, "{0}/{1}?version=2018-08-13".format(discovery_credentials_url, 'credential_id'), + responses.add(responses.PUT, + "{0}/{1}?version=2018-08-13".format( + discovery_credentials_url, 'credential_id'), body=json.dumps(results), status=200, content_type='application/json') - responses.add(responses.DELETE, "{0}/{1}?version=2018-08-13".format(discovery_credentials_url, 'credential_id'), + responses.add(responses.DELETE, + "{0}/{1}?version=2018-08-13".format( + discovery_credentials_url, 'credential_id'), body=json.dumps({'deleted': 'bogus -- ok'}), status=200, content_type='application/json') - discovery.create_credentials('envid', source_type='salesforce', credential_details={ - 'url': 'https://login.salesforce.com', - 'credential_type': 'username_password', - 'username':'user@email.com' - }) + discovery.create_credentials('envid', + source_type='salesforce', + credential_details={ + 'url': 'https://login.salesforce.com', + 'credential_type': 'username_password', + 'username': 'user@email.com' + }) discovery.get_credentials('envid', 'credential_id') - discovery.update_credentials(environment_id='envid', - credential_id='credential_id', - source_type='salesforce', - credential_details=results['credential_details']) + discovery.update_credentials( + environment_id='envid', + credential_id='credential_id', + source_type='salesforce', + credential_details=results['credential_details']) discovery.list_credentials('envid') - discovery.delete_credentials(environment_id='envid', credential_id='credential_id') + discovery.delete_credentials(environment_id='envid', + credential_id='credential_id') assert len(responses.calls) == 10 @classmethod @responses.activate def test_events_and_feedback(cls): discovery_event_url = urljoin(base_discovery_url, 'events') - discovery_metrics_event_rate_url = urljoin(base_discovery_url, 'metrics/event_rate') - discovery_metrics_query_url = urljoin(base_discovery_url, 'metrics/number_of_queries') - discovery_metrics_query_event_url = urljoin(base_discovery_url, 'metrics/number_of_queries_with_event') - discovery_metrics_query_no_results_url = urljoin(base_discovery_url, 'metrics/number_of_queries_with_no_search_results') - discovery_metrics_query_token_event_url = urljoin(base_discovery_url, 'metrics/top_query_tokens_with_event_rate') + discovery_metrics_event_rate_url = urljoin(base_discovery_url, + 'metrics/event_rate') + discovery_metrics_query_url = urljoin(base_discovery_url, + 'metrics/number_of_queries') + discovery_metrics_query_event_url = urljoin( + base_discovery_url, 'metrics/number_of_queries_with_event') + discovery_metrics_query_no_results_url = urljoin( + base_discovery_url, + 'metrics/number_of_queries_with_no_search_results') + discovery_metrics_query_token_event_url = urljoin( + base_discovery_url, 'metrics/top_query_tokens_with_event_rate') discovery_query_log_url = urljoin(base_discovery_url, 'logs') event_data = { @@ -1009,114 +1112,118 @@ def test_events_and_feedback(cls): "query_id": "cde" } - create_event_response = { - "type": "click", - "data": event_data - } + create_event_response = {"type": "click", "data": event_data} metric_response = { - "aggregations": [ - { - "interval": "1d", - "event_type": "click", - "results": [ - { - "key_as_string": "2018-08-14T14:39:59.309Z", - "key": 1533513600000, - "matching_results": 2, - "event_rate": 0.0 - } - ] - } - ] + "aggregations": [{ + "interval": + "1d", + "event_type": + "click", + "results": [{ + "key_as_string": "2018-08-14T14:39:59.309Z", + "key": 1533513600000, + "matching_results": 2, + "event_rate": 0.0 + }] + }] } metric_token_response = { - "aggregations": [ - { - "event_type": "click", - "results": [ - { - "key": "content", - "matching_results": 5, - "event_rate": 0.6 - }, - { - "key": "first", - "matching_results": 5, - "event_rate": 0.6 - }, - { - "key": "of", - "matching_results": 5, - "event_rate": 0.6 - } - ] - } - ] + "aggregations": [{ + "event_type": + "click", + "results": [{ + "key": "content", + "matching_results": 5, + "event_rate": 0.6 + }, { + "key": "first", + "matching_results": 5, + "event_rate": 0.6 + }, { + "key": "of", + "matching_results": 5, + "event_rate": 0.6 + }] + }] } log_query_response = { - "matching_results": 20, - "results": [ - { - "customer_id": "", - "environment_id": "xxx", - "natural_language_query": "The content of the first chapter", - "query_id": "1ICUdh3Pab", - "document_results": { - "count": 1, - "results": [ - { - "collection_id": "b67a82f3-6507-4c25-9757-3485ff4f2a32", - "score": 0.025773458, - "position": 10, - "document_id": "af0be20e-e130-4712-9a2e-37d9c8b9c52f" - } - ] - }, - "event_type": "query", - "session_token": "1_nbEfQtKVcg9qx3t41ICUdh3Pab", - "created_timestamp": "2018-08-14T18:20:30.460Z" - } - ] + "matching_results": + 20, + "results": [{ + "customer_id": "", + "environment_id": "xxx", + "natural_language_query": "The content of the first chapter", + "query_id": "1ICUdh3Pab", + "document_results": { + "count": + 1, + "results": [{ + "collection_id": "b67a82f3-6507-4c25-9757-3485ff4f2a32", + "score": 0.025773458, + "position": 10, + "document_id": "af0be20e-e130-4712-9a2e-37d9c8b9c52f" + }] + }, + "event_type": "query", + "session_token": "1_nbEfQtKVcg9qx3t41ICUdh3Pab", + "created_timestamp": "2018-08-14T18:20:30.460Z" + }] } - responses.add(responses.POST, "{0}?version=2018-08-13".format(discovery_event_url), + responses.add(responses.POST, + "{0}?version=2018-08-13".format(discovery_event_url), body=json.dumps(create_event_response), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document".format(discovery_metrics_event_rate_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') + responses.add( + responses.GET, + "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" + .format(discovery_metrics_event_rate_url), + body=json.dumps(metric_response), + status=200, + content_type='application/json') - responses.add(responses.GET, "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document".format(discovery_metrics_query_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') + responses.add( + responses.GET, + "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" + .format(discovery_metrics_query_url), + body=json.dumps(metric_response), + status=200, + content_type='application/json') - responses.add(responses.GET, "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document".format(discovery_metrics_query_event_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') - responses.add(responses.GET, "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document".format(discovery_metrics_query_no_results_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') - responses.add(responses.GET, "{0}?version=2018-08-13&count=2".format(discovery_metrics_query_token_event_url), + responses.add( + responses.GET, + "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" + .format(discovery_metrics_query_event_url), + body=json.dumps(metric_response), + status=200, + content_type='application/json') + responses.add( + responses.GET, + "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" + .format(discovery_metrics_query_no_results_url), + body=json.dumps(metric_response), + status=200, + content_type='application/json') + responses.add(responses.GET, + "{0}?version=2018-08-13&count=2".format( + discovery_metrics_query_token_event_url), body=json.dumps(metric_token_response), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2018-08-13".format(discovery_query_log_url), + responses.add(responses.GET, + "{0}?version=2018-08-13".format(discovery_query_log_url), body=json.dumps(log_query_response), status=200, content_type='application/json') - authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) discovery.create_event('click', event_data) assert responses.calls[1].response.json()["data"] == event_data @@ -1131,10 +1238,9 @@ def test_events_and_feedback(cls): result_type='document') assert responses.calls[5].response.json() == metric_response - discovery.get_metrics_query_event( - start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document') + discovery.get_metrics_query_event(start_time='2018-08-13T14:39:59.309Z', + end_time='2018-08-14T14:39:59.309Z', + result_type='document') assert responses.calls[7].response.json() == metric_response discovery.get_metrics_query_no_results( @@ -1155,17 +1261,15 @@ def test_events_and_feedback(cls): @responses.activate def test_tokenization_dictionary(cls): url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/word_lists/tokenization_dictionary?version=2018-08-13' - responses.add( - responses.POST, - url, - body='{"status": "pending"}', - status=200, - content_type='application_json') - responses.add( - responses.DELETE, - url, - body='{"status": "pending"}', - status=200) + responses.add(responses.POST, + url, + body='{"status": "pending"}', + status=200, + content_type='application_json') + responses.add(responses.DELETE, + url, + body='{"status": "pending"}', + status=200) responses.add( responses.GET, url, @@ -1174,22 +1278,25 @@ def test_tokenization_dictionary(cls): content_type='application_json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) - - tokenization_rules = [ - { - 'text': 'token', - 'tokens': ['token 1', 'token 2'], - 'readings': ['reading 1', 'reading 2'], - 'part_of_speech': 'noun', - } - ] - - discovery.create_tokenization_dictionary('envid', 'colid', tokenization_rules=tokenization_rules) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) + + tokenization_rules = [{ + 'text': 'token', + 'tokens': ['token 1', 'token 2'], + 'readings': ['reading 1', 'reading 2'], + 'part_of_speech': 'noun', + }] + + discovery.create_tokenization_dictionary( + 'envid', 'colid', tokenization_rules=tokenization_rules) assert responses.calls[0].response.json() == {"status": "pending"} discovery.get_tokenization_dictionary_status('envid', 'colid') - assert responses.calls[1].response.json() == {"status": "pending", "type":"tokenization_dictionary"} + assert responses.calls[1].response.json() == { + "status": "pending", + "type": "tokenization_dictionary" + } discovery.delete_tokenization_dictionary('envid', 'colid') assert responses.calls[2].response.status_code == 200 @@ -1200,44 +1307,47 @@ def test_tokenization_dictionary(cls): @responses.activate def test_stopword_operations(cls): url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/word_lists/stopwords?version=2018-08-13' - responses.add( - responses.POST, - url, - body='{"status": "pending", "type": "stopwords"}', - status=200, - content_type='application_json') - responses.add( - responses.DELETE, - url, - status=200) - responses.add( - responses.GET, - url, - body='{"status": "ready", "type": "stopwords"}', - status=200, - content_type='application_json') + responses.add(responses.POST, + url, + body='{"status": "pending", "type": "stopwords"}', + status=200, + content_type='application_json') + responses.add(responses.DELETE, url, status=200) + responses.add(responses.GET, + url, + body='{"status": "ready", "type": "stopwords"}', + status=200, + content_type='application_json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) - stopwords_file_path = os.path.join(os.getcwd(), 'resources', 'stopwords.txt') + stopwords_file_path = os.path.join(os.getcwd(), 'resources', + 'stopwords.txt') with open(stopwords_file_path) as file: discovery.create_stopword_list('envid', 'colid', file) - assert responses.calls[0].response.json() == {"status": "pending", "type": "stopwords"} + assert responses.calls[0].response.json() == { + "status": "pending", + "type": "stopwords" + } discovery.get_stopword_list_status('envid', 'colid') - assert responses.calls[1].response.json() == {"status": "ready", "type": "stopwords"} + assert responses.calls[1].response.json() == { + "status": "ready", + "type": "stopwords" + } discovery.delete_stopword_list('envid', 'colid') assert responses.calls[2].response.status_code == 200 assert len(responses.calls) == 3 - @classmethod @responses.activate def test_gateway_configuration(cls): - discovery_gateway_url = urljoin(base_discovery_url, 'environments/envid/gateways') + discovery_gateway_url = urljoin(base_discovery_url, + 'environments/envid/gateways') gateway_details = { "status": "idle", @@ -1247,55 +1357,67 @@ def test_gateway_configuration(cls): "gateway_id": "gateway_id" } - responses.add(responses.GET, "{0}/{1}?version=2018-08-13".format(discovery_gateway_url, 'gateway_id'), + responses.add(responses.GET, + "{0}/{1}?version=2018-08-13".format( + discovery_gateway_url, 'gateway_id'), body=json.dumps(gateway_details), status=200, content_type='application/json') - responses.add(responses.POST, "{0}?version=2018-08-13".format(discovery_gateway_url), + responses.add(responses.POST, + "{0}?version=2018-08-13".format(discovery_gateway_url), body=json.dumps(gateway_details), status=200, content_type='application/json') - responses.add(responses.GET, "{0}?version=2018-08-13".format(discovery_gateway_url), + responses.add(responses.GET, + "{0}?version=2018-08-13".format(discovery_gateway_url), body=json.dumps({'gateways': [gateway_details]}), status=200, content_type='application/json') - responses.add(responses.DELETE, "{0}/{1}?version=2018-08-13".format(discovery_gateway_url, 'gateway_id'), - body=json.dumps({'gateway_id': 'gateway_id', 'status': 'deleted'}), + responses.add(responses.DELETE, + "{0}/{1}?version=2018-08-13".format( + discovery_gateway_url, 'gateway_id'), + body=json.dumps({ + 'gateway_id': 'gateway_id', + 'status': 'deleted' + }), status=200, content_type='application/json') authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) discovery.create_gateway('envid', name='gateway_id') discovery.list_gateways('envid') discovery.get_gateway('envid', 'gateway_id') - discovery.delete_gateway(environment_id='envid', gateway_id='gateway_id') + discovery.delete_gateway(environment_id='envid', + gateway_id='gateway_id') assert len(responses.calls) == 8 - @responses.activate def test_get_autocompletion(self): - endpoint = 'environments/{0}/collections/{1}/autocompletion?version=2018-08-13&field=field&prefix=prefix&count=count'.format('environment_id', 'collection_id').format('collection_id') + endpoint = 'environments/{0}/collections/{1}/autocompletion?version=2018-08-13&field=field&prefix=prefix&count=count'.format( + 'environment_id', 'collection_id').format('collection_id') url = '{0}{1}'.format(base_discovery_url, endpoint) print('hello') print(url) - response = { - "completions" : [ "completions", "completions" ] - } + response = {"completions": ["completions", "completions"]} responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) - detailed_response = discovery.get_autocompletion(environment_id='environment_id', + detailed_response = discovery.get_autocompletion( + environment_id='environment_id', collection_id='collection_id', field='field', prefix='prefix', count='count') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index a670c9db6..ffc1d4f01 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -14,15 +14,13 @@ import json import ibm_watson +from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata import responses -import json import os import jwt import time -import pytest from unittest import TestCase from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata platform_url = 'https://gateway.watsonplatform.net' service_path = '/visual-recognition/api' @@ -294,6 +292,7 @@ def test_create_collection(self): detailed_response = service.create_collection(name='name', description='description') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 @responses.activate @@ -348,6 +347,7 @@ def test_list_collections(self): detailed_response = service.list_collections() result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 @responses.activate @@ -385,6 +385,7 @@ def test_get_collection(self): detailed_response = service.get_collection( collection_id='collection_id') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 @responses.activate @@ -424,6 +425,7 @@ def test_update_collection(self): name='name', description='description') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 @responses.activate @@ -445,11 +447,9 @@ def test_delete_collection(self): detailed_response = service.delete_collection( collection_id='collection_id') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 - with pytest.raises(TypeError): - service.delete_collection() - # ######################### # # images # ######################### @@ -580,11 +580,9 @@ def test_add_images(self): training_data='training_data') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 - with pytest.raises(TypeError): - service.add_images() - @responses.activate def test_list_images(self): endpoint = '/v4/collections/{0}/images'.format('collection_id') @@ -611,11 +609,9 @@ def test_list_images(self): detailed_response = service.list_images(collection_id='collection_id') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 - with pytest.raises(TypeError): - service.list_images() - @responses.activate def test_get_image_details(self): endpoint = '/v4/collections/{0}/images/{1}'.format( @@ -682,11 +678,9 @@ def test_get_image_details(self): detailed_response = service.get_image_details( collection_id='collection_id', image_id='image_id') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 - with pytest.raises(TypeError): - service.get_image_details() - @responses.activate def test_delete_image(self): endpoint = '/v4/collections/{0}/images/{1}'.format( @@ -707,11 +701,9 @@ def test_delete_image(self): detailed_response = service.delete_image(collection_id='collection_id', image_id='image_id') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 - with pytest.raises(TypeError): - service.delete_image() - @responses.activate def test_get_jpeg_image(self): endpoint = '/v4/collections/{0}/images/{1}/jpeg'.format( @@ -732,11 +724,9 @@ def test_get_jpeg_image(self): detailed_response = service.get_jpeg_image( collection_id='collection_id', image_id='image_id', size='size') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 - with pytest.raises(TypeError): - service.get_jpeg_image() - ######################### # training ######################### @@ -775,11 +765,9 @@ def test_train(self): detailed_response = service.train(collection_id='collection_id') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 - with pytest.raises(TypeError): - service.train() - @responses.activate def test_add_image_training_data(self): endpoint = '/v4/collections/{0}/images/{1}/training_data'.format( @@ -818,11 +806,9 @@ def test_add_image_training_data(self): detailed_response = service.add_image_training_data( collection_id='collection_id', image_id='image_id') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 - with pytest.raises(TypeError): - service.add_image_training_data() - ######################### # userData ######################### @@ -845,7 +831,5 @@ def test_delete_user_data(self): detailed_response = service.delete_user_data(customer_id='customer_id') result = detailed_response.get_result() + assert result is not None assert len(responses.calls) == 2 - - with pytest.raises(TypeError): - service.delete_user_data() From a331df05aa0a9114ab4b980ebf3e7e8a6d667d5f Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 3 Oct 2019 18:01:35 -0700 Subject: [PATCH 112/455] refactor(stt): Add customization_id back to recognize_using_websocket --- MIGRATION-V4.md | 1 - ibm_watson/speech_to_text_v1_adapter.py | 6 ++++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/MIGRATION-V4.md b/MIGRATION-V4.md index 2a3828ef9..52fc40182 100644 --- a/MIGRATION-V4.md +++ b/MIGRATION-V4.md @@ -203,7 +203,6 @@ The SDK no longer supports Pyhton versions 2.7 and <=3.4. #### Speech to Text V1 * `final_results` was renamed to `final` in the SpeakerLabelsResult model * `final_results` was renamed to `final` in the SpeechRecognitionResult model -* `customization_id` no longer a param in `recognize_using_websocket()` method #### Visual Recognition V3 * `detect_faces()` method was removed diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 32b95dc7f..d9eded45c 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -43,6 +43,7 @@ def recognize_using_websocket(self, speaker_labels=None, http_proxy_host=None, http_proxy_port=None, + customization_id=None, grammar_name=None, redaction=None, processing_metrics=None, @@ -144,6 +145,10 @@ def recognize_using_websocket(self, labels](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#speaker_labels). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. + :param str customization_id: **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 request. Do not specify both parameters with a + request. :param str grammar_name: The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language @@ -214,6 +219,7 @@ def recognize_using_websocket(self, params = { 'model': model, + 'customization_id': customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, 'language_customization_id': language_customization_id From c6df9c4d91c6e56dc5048c2afee6099713c09b43 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 3 Oct 2019 18:01:53 -0700 Subject: [PATCH 113/455] doc(url): Update migration doc link --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 509fb6804..e6d756757 100755 --- a/README.md +++ b/README.md @@ -259,10 +259,10 @@ assistant = AssistantV1( authenticator=authenticator) assistant.set_service_url('') ``` -For more information, follow the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/MIGRATION-V4.md) +For more information, follow the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md) ## Migration -To move from v3.x to v4.0, refer to the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/MIGRATION-V4.md). +To move from v3.x to v4.0, refer to the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md). ## Configuring the http client (Supported from v1.1.0) To set client configs like timeout use the `with_http_config()` function and pass it a dictionary of configs. For example for a Assistant service instance From 04b90555264efee515eda98d224222733c567d79 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 3 Oct 2019 18:04:39 -0700 Subject: [PATCH 114/455] chore(discoveryv1): prefix in get_autocompletion and suggested_query in QueryResponse --- ibm_watson/discovery_v1.py | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 625678099..e5e5145a4 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -2058,9 +2058,9 @@ def federated_query_notices(self, def get_autocompletion(self, environment_id, collection_id, + prefix, *, field=None, - prefix=None, count=None, **kwargs): """ @@ -2072,11 +2072,11 @@ def get_autocompletion(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. + :param str prefix: The prefix to use for autocompletion. For example, the + prefix `Ho` could autocomplete to `Hot`, `Housing`, or `How do I upgrade`. + Possible completions are. :param str field: (optional) The field in the result documents that autocompletion suggestions are identified from. - :param str prefix: (optional) The prefix to use for autocompletion. For - example, the prefix `Ho` could autocomplete to `Hot`, `Housing`, or `How do - I upgrade`. Possible completions are. :param int count: (optional) The number of autocompletion suggestions to return. :param dict headers: A `dict` containing the request headers @@ -2088,6 +2088,8 @@ def get_autocompletion(self, raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') + if prefix is None: + raise ValueError('prefix must be provided') headers = {} if 'headers' in kwargs: @@ -2097,8 +2099,8 @@ def get_autocompletion(self, params = { 'version': self.version, - 'field': field, 'prefix': prefix, + 'field': field, 'count': count } @@ -9938,6 +9940,8 @@ class QueryResponse(): **Important:** Session tokens are case sensitive. :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval type information. + :attr str suggested_query: (optional) The suggestions for a misspelled natural + language query. """ def __init__(self, @@ -9948,7 +9952,8 @@ def __init__(self, passages=None, duplicates_removed=None, session_token=None, - retrieval_details=None): + retrieval_details=None, + suggested_query=None): """ Initialize a QueryResponse object. @@ -9968,6 +9973,8 @@ def __init__(self, **Important:** Session tokens are case sensitive. :param RetrievalDetails retrieval_details: (optional) An object contain retrieval type information. + :param str suggested_query: (optional) The suggestions for a misspelled + natural language query. """ self.matching_results = matching_results self.results = results @@ -9976,6 +9983,7 @@ def __init__(self, self.duplicates_removed = duplicates_removed self.session_token = session_token self.retrieval_details = retrieval_details + self.suggested_query = suggested_query @classmethod def _from_dict(cls, _dict): @@ -9983,7 +9991,8 @@ def _from_dict(cls, _dict): args = {} valid_keys = [ 'matching_results', 'results', 'aggregations', 'passages', - 'duplicates_removed', 'session_token', 'retrieval_details' + 'duplicates_removed', 'session_token', 'retrieval_details', + 'suggested_query' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -10012,6 +10021,8 @@ def _from_dict(cls, _dict): if 'retrieval_details' in _dict: args['retrieval_details'] = RetrievalDetails._from_dict( _dict.get('retrieval_details')) + if 'suggested_query' in _dict: + args['suggested_query'] = _dict.get('suggested_query') return cls(**args) def _to_dict(self): @@ -10035,6 +10046,9 @@ def _to_dict(self): if hasattr(self, 'retrieval_details') and self.retrieval_details is not None: _dict['retrieval_details'] = self.retrieval_details._to_dict() + if hasattr(self, + 'suggested_query') and self.suggested_query is not None: + _dict['suggested_query'] = self.suggested_query return _dict def __str__(self): From 63e2d0d6aeb5e3909d811f8a5023064ef691dc59 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 4 Oct 2019 15:38:56 +0000 Subject: [PATCH 115/455] =?UTF-8?q?Bump=20version:=203.4.2=20=E2=86=92=204?= =?UTF-8?q?.0.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index c259b7b89..dc9167ad6 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 3.4.2 +current_version = 4.0.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index daee014fe..d6497a814 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '3.4.2' +__version__ = '4.0.0' diff --git a/setup.py b/setup.py index 30c5c38e8..56d5589c1 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '3.4.2' +__version__ = '4.0.0' if sys.argv[-1] == 'publish': From 2d6f6d0a5cf653c06b815cae0291f58496fef97a Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 4 Oct 2019 10:09:50 -0700 Subject: [PATCH 116/455] fix(FileWithMetadata): Hand edit for FileWithMetadata _to_dict() --- ibm_watson/visual_recognition_v4.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 28f1e275b..a70ca9b7e 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -2457,7 +2457,7 @@ def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'data') and self.data is not None: - _dict['data'] = self.data._to_dict() + _dict['data'] = self.data.__str__() if hasattr(self, 'filename') and self.filename is not None: _dict['filename'] = self.filename if hasattr(self, 'content_type') and self.content_type is not None: From 89fcf8881a250fb158f811570eabd8188923bce5 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 4 Oct 2019 17:51:12 +0000 Subject: [PATCH 117/455] =?UTF-8?q?Bump=20version:=204.0.0=20=E2=86=92=204?= =?UTF-8?q?.0.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index dc9167ad6..663cccb49 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.0.0 +current_version = 4.0.1 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index d6497a814..1a3bef532 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.0.0' +__version__ = '4.0.1' diff --git a/setup.py b/setup.py index 56d5589c1..94951f1b2 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.0.0' +__version__ = '4.0.1' if sys.argv[-1] == 'publish': From 79d89a629a1dc02e564c55e7c24267971d1effab Mon Sep 17 00:00:00 2001 From: Christian Compton Date: Mon, 14 Oct 2019 16:07:22 -0500 Subject: [PATCH 118/455] docs: BearerToken fix --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e6d756757..7aeffb6b9 100755 --- a/README.md +++ b/README.md @@ -187,10 +187,10 @@ token = iam_token_manager.get_token() ##### Supplying the bearer token ```python from ibm_watson import DiscoveryV1 -from ibm_cloud_sdk_core.authenticators import BearerAuthenticator +from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator # in the constructor, assuming control of managing the token -authenticator = BearerAuthenticator('your bearer token') +authenticator = BearerTokenAuthenticator('your bearer token') discovery = DiscoveryV1(version='2018-08-01', authenticator=authenticator) discovery.set_service_url('') @@ -247,7 +247,7 @@ The SDK is generated using OpenAPI Specification(OAS3). Changes are basic reorde The package is renamed to ibm_watson. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. ## Changes for v4.0 -Authenticator variable indicates the type of authentication to be used. +Authenticator variable indicates the type of authentication to be used. ```python from ibm_watson import AssistantV1 @@ -406,9 +406,9 @@ assistant.set_disable_ssl_verification(True) # MAKE SURE SSL VERIFICATION IS DIS ### 2) Supplying the access token ```python from ibm_watson import AssistantV1 -from ibm_cloud_sdk_core.authenticators import BearerAuthenticator +from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator -authenticator = BearerAuthenticator('your managed access token') +authenticator = BearerTokenAuthenticator('your managed access token') assistant = AssistantV1(version='', authenticator=authenticator) assistant.set_service_url('') # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api From 1fd9a3444e3d03035adfad8a8884beb34b254ccb Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 23 Oct 2019 04:16:02 +0200 Subject: [PATCH 119/455] Travis CI: Add Python 3.8 to the testing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Also, Xenial is now Travis’ default distro. --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 800863ac6..40f4f7388 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,7 +4,7 @@ matrix: - python: 3.5 - python: 3.6 - python: 3.7 - dist: xenial + - python: 3.8 cache: pip before_install: - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && openssl aes-256-cbc -K $encrypted_cebf25e6c525_key From 3a6375bb4da5cc8f47486c2954865ba5f54fd93f Mon Sep 17 00:00:00 2001 From: Siddhant Naik Date: Thu, 7 Nov 2019 19:11:45 +0530 Subject: [PATCH 120/455] Import the correct class in speaker_text_to_speech example --- examples/speaker_text_to_speech.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/speaker_text_to_speech.py b/examples/speaker_text_to_speech.py index eb2646df7..9faf6fb98 100644 --- a/examples/speaker_text_to_speech.py +++ b/examples/speaker_text_to_speech.py @@ -5,13 +5,13 @@ # passed in the request. When the service responds with the synthesized # audio, the pyaudio would play it in a blocking mode -from ibm_watson import SpeechToTextV1 +from ibm_watson import TextToSpeechV1 from ibm_watson.websocket import SynthesizeCallback import pyaudio from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your_api_key') -service = SpeechToTextV1(authenticator=authenticator) +service = TextToSpeechV1(authenticator=authenticator) service.set_service_url('https://stream.watsonplatform.net/speech-to-text/api') class Play(object): From 625fe9da9923619d27c6beeda3f118123cb5a2e1 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 8 Nov 2019 11:12:15 -0800 Subject: [PATCH 121/455] test(services): rename and refactor integration tests --- test/integration/test_discovery_v1.py | 65 ++++++++++--------- ...ition.py => test_visual_recognition_v3.py} | 0 .../integration/test_visual_recognition_v4.py | 3 +- 3 files changed, 36 insertions(+), 32 deletions(-) rename test/integration/{test_visual_recognition.py => test_visual_recognition_v3.py} (100%) diff --git a/test/integration/test_discovery_v1.py b/test/integration/test_discovery_v1.py index e234e815a..566ccdb1d 100644 --- a/test/integration/test_discovery_v1.py +++ b/test/integration/test_discovery_v1.py @@ -8,26 +8,39 @@ @pytest.mark.skipif( os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') class Discoveryv1(TestCase): - def setUp(self): - self.discovery = ibm_watson.DiscoveryV1( - version='2018-08-01') - self.discovery.set_default_headers({ + discovery = None + environment_id = '62b0dd87-eefa-40bf-81d6-cf9bc82692ab' # This environment is created for integration testing + collection_id = None + collection_name = 'FOR-PYTHON-DELETE-ME' + + @classmethod + def setup_class(cls): + cls.discovery = ibm_watson.DiscoveryV1(version='2018-08-01') + cls.discovery.set_default_headers({ 'X-Watson-Learning-Opt-Out': '1', 'X-Watson-Test': '1' }) - self.environment_id = 'e15f6424-f887-4f50-b4ea-68267c36fc9c' # This environment is created for integration testing - collections = self.discovery.list_collections(self.environment_id).get_result()['collections'] - self.collection_id = collections[0]['collection_id'] + collections = cls.discovery.list_collections(cls.environment_id).get_result()['collections'] for collection in collections: - if collection['name'] == 'DO-NOT-DELETE-JAPANESE-COLLECTION': - self.collection_id_JP = collection['collection_id'] - - def tearDown(self): - collections = self.discovery.list_collections(self.environment_id).get_result()['collections'] + if collection['name'] == cls.collection_name: + cls.collection_id = collection['collection_id'] + + if cls.collection_id is None: + print("Creating a new temporary collection") + cls.collection_id = cls.discovery.create_collection( + cls.environment_id, + cls.collection_name, + 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'] for collection in collections: - if not collection['name'].startswith('DO-NOT-DELETE'): - self.discovery.delete_collection(self.environment_id, collection['collection_id']) + if collection['name'] == cls.collection_name: + print('Deleting the temporary collection') + cls.discovery.delete_collection(cls.environment_id, cls.collection_id) + break def test_environments(self): envs = self.discovery.list_environments().get_result() @@ -60,32 +73,21 @@ def test_configurations(self): assert deleted_config['status'] == 'deleted' def test_collections_and_expansions(self): - name = 'Example collection for python' + random.choice('ABCDEFGHIJKLMNOPQ') - new_collection_id = self.discovery.create_collection( - self.environment_id, - name, - description="Integration test for python sdk").get_result()['collection_id'] - assert new_collection_id is not None - - self.discovery.get_collection(self.environment_id, new_collection_id) + self.discovery.get_collection(self.environment_id, self.collection_id) updated_collection = self.discovery.update_collection( - self.environment_id, new_collection_id, 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, - new_collection_id, [{ + self.collection_id, [{ 'input_terms': ['a'], 'expanded_terms': ['aa'] }]).get_result() expansions = self.discovery.list_expansions(self.environment_id, - new_collection_id).get_result() + self.collection_id).get_result() assert expansions['expansions'] self.discovery.delete_expansions(self.environment_id, - new_collection_id) - - deleted_collection = self.discovery.delete_collection( - self.environment_id, new_collection_id).get_result() - assert deleted_collection['status'] == 'deleted' + self.collection_id) def test_documents(self): with open(os.path.join(os.path.dirname(__file__), '../../resources/simple.html'), 'r') as fileinfo: @@ -185,10 +187,11 @@ def test_create_event(self): 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_JP + self.collection_id ).get_result() assert result['status'] is not None diff --git a/test/integration/test_visual_recognition.py b/test/integration/test_visual_recognition_v3.py similarity index 100% rename from test/integration/test_visual_recognition.py rename to test/integration/test_visual_recognition_v3.py diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index 5677b6815..8ed3aa073 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -73,9 +73,10 @@ def test_03_analyze(self): 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: analyze_images = self.visual_recognition.analyze( - collection_ids=['d31d6534-3458-40c4-b6de-2185a5f3cbe4'], + collection_ids=['684777e5-1f2d-40e3-987f-72d36557ef46'], features=[AnalyzeEnums.Features.OBJECTS.value], images_file=[ FileWithMetadata(dog_file), From 02fb28a99bbbe46b4a7d178afb8a803d0f2ada89 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 8 Nov 2019 11:12:42 -0800 Subject: [PATCH 122/455] test(examples): Include examples in integration tests which are not already in integration test --- examples/assistant_v1.py | 17 ++++++++++---- examples/natural_language_understanding_v1.py | 12 +++++++--- examples/personality_insights_v3.py | 13 +++++++---- examples/tone_analyzer_v3.py | 23 +++++++++++-------- examples/visual_recognition_v4.py | 2 +- test/integration/test_examples.py | 13 ++++------- 6 files changed, 50 insertions(+), 30 deletions(-) diff --git a/examples/assistant_v1.py b/examples/assistant_v1.py index c4faa537e..77d49191e 100644 --- a/examples/assistant_v1.py +++ b/examples/assistant_v1.py @@ -1,11 +1,18 @@ import json from ibm_watson import AssistantV1 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +# from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2018-07-10', - authenticator=authenticator) + +# Authentication via IAM +# authenticator = IAMAuthenticator('your apikey') +# assistant = AssistantV1( +# version='2018-07-10', +# authenticator=authenticator) +# assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') + + +# Authentication via external config like VCAP_SERVICES +assistant = AssistantV1(version='2018-07-10') assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') ######################### diff --git a/examples/natural_language_understanding_v1.py b/examples/natural_language_understanding_v1.py index 9ed28204a..86485e796 100644 --- a/examples/natural_language_understanding_v1.py +++ b/examples/natural_language_understanding_v1.py @@ -3,10 +3,16 @@ from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -authenticator = IAMAuthenticator('your_api_key') +# Authentication via IAM +# authenticator = IAMAuthenticator('your_api_key') +# service = NaturalLanguageUnderstandingV1( +# version='2018-03-16', +# authenticator=authenticator) +# service.set_service_url('https://gateway.watsonplatform.net/natural-language-understanding/api') + +# Authentication via external config like VCAP_SERVICES service = NaturalLanguageUnderstandingV1( - version='2018-03-16', - authenticator=authenticator) + version='2018-03-16') service.set_service_url('https://gateway.watsonplatform.net/natural-language-understanding/api') response = service.analyze( diff --git a/examples/personality_insights_v3.py b/examples/personality_insights_v3.py index 68fe1f2cd..c9b6394c7 100755 --- a/examples/personality_insights_v3.py +++ b/examples/personality_insights_v3.py @@ -8,10 +8,15 @@ import csv from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -authenticator = IAMAuthenticator('your_api_key') -service = PersonalityInsightsV3( - version='2017-10-13', - authenticator=authenticator) +# Authentication via IAM +# authenticator = IAMAuthenticator('your_api_key') +# service = PersonalityInsightsV3( +# version='2017-10-13', +# authenticator=authenticator) +# service.set_service_url('https://gateway.watsonplatform.net/personality-insights/api') + +# Authentication via external config like VCAP_SERVICES +service = PersonalityInsightsV3(version='2017-10-13') service.set_service_url('https://gateway.watsonplatform.net/personality-insights/api') ############################ diff --git a/examples/tone_analyzer_v3.py b/examples/tone_analyzer_v3.py index 921336fa6..896a26b73 100755 --- a/examples/tone_analyzer_v3.py +++ b/examples/tone_analyzer_v3.py @@ -4,10 +4,15 @@ from ibm_watson.tone_analyzer_v3 import ToneInput from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -authenticator = IAMAuthenticator('your_api_key') -service = ToneAnalyzerV3( - version='2017-09-21', - authenticator=authenticator) +# Authentication via IAM +# authenticator = IAMAuthenticator('your_api_key') +# service = ToneAnalyzerV3( +# version='2017-09-21', +# authenticator=authenticator) +# service.set_service_url('https://gateway.watsonplatform.net/tone-analyzer/api') + +# Authentication via external config like VCAP_SERVICES +service = ToneAnalyzerV3(version='2017-09-21') service.set_service_url('https://gateway.watsonplatform.net/tone-analyzer/api') print("\ntone_chat() example 1:\n") @@ -31,13 +36,13 @@ print("\ntone() example 2:\n") with open(join(dirname(__file__), - '../resources/tone-example.json')) as tone_json: + '../../resources/tone-example.json')) as tone_json: tone = service.tone(json.load(tone_json)['text'], content_type="text/plain").get_result() print(json.dumps(tone, indent=2)) print("\ntone() example 3:\n") with open(join(dirname(__file__), - '../resources/tone-example.json')) as tone_json: + '../../resources/tone-example.json')) as tone_json: tone = service.tone( tone_input=json.load(tone_json)['text'], content_type='text/plain', @@ -46,7 +51,7 @@ print("\ntone() example 4:\n") with open(join(dirname(__file__), - '../resources/tone-example.json')) as tone_json: + '../../resources/tone-example.json')) as tone_json: tone = service.tone( tone_input=json.load(tone_json), content_type='application/json').get_result() @@ -54,7 +59,7 @@ print("\ntone() example 5:\n") with open(join(dirname(__file__), - '../resources/tone-example-html.json')) as tone_html: + '../../resources/tone-example-html.json')) as tone_html: tone = service.tone( json.load(tone_html)['text'], content_type='text/html').get_result() @@ -62,7 +67,7 @@ print("\ntone() example 6 with GDPR support:\n") with open(join(dirname(__file__), - '../resources/tone-example-html.json')) as tone_html: + '../../resources/tone-example-html.json')) as tone_html: tone = service.tone( json.load(tone_html)['text'], content_type='text/html', diff --git a/examples/visual_recognition_v4.py b/examples/visual_recognition_v4.py index ae51c5b7d..6ea4eb7b0 100644 --- a/examples/visual_recognition_v4.py +++ b/examples/visual_recognition_v4.py @@ -14,7 +14,7 @@ # create a classifier my_collection = service.create_collection( name='', - description='tetsing for python' + description='testing for python' ).get_result() collection_id = my_collection.get('collection_id') diff --git a/test/integration/test_examples.py b/test/integration/test_examples.py index 1ee6c1369..861fb27e5 100644 --- a/test/integration/test_examples.py +++ b/test/integration/test_examples.py @@ -8,11 +8,11 @@ from os.path import join, dirname from glob import glob -# tests to exclude -excludes = ['discovery_v1.ipynb', '__init__.py', 'microphone-speech-to-text.py'] +# tests to include +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') +examples_path = join(dirname(__file__), '../../', 'examples', '*.py') @pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') @@ -22,13 +22,10 @@ def test_examples(): for example in examples: name = example.split('/')[-1] - # exclude some tests cases like authorization - if name in excludes: + if not name in includes: continue - # exclude tests if there are no credentials for that service - service_name = name[:-6] if not name.startswith('visual_recognition')\ - else 'watson_vision_combined' + service_name = name[:-6] if service_name not in vcap_services: print('%s does not have credentials in VCAP_SERVICES', From c20828a69c46370f61dd2fca614eb342a40e25e6 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 8 Nov 2019 11:36:05 -0800 Subject: [PATCH 123/455] refactor(test): Update test paths --- examples/personality_insights_v3.py | 4 ++-- examples/tone_analyzer_v3.py | 20 ++++++++++---------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/examples/personality_insights_v3.py b/examples/personality_insights_v3.py index c9b6394c7..82753f321 100755 --- a/examples/personality_insights_v3.py +++ b/examples/personality_insights_v3.py @@ -23,7 +23,7 @@ # Profile with JSON output # ############################ -with open(join(dirname(__file__), '../resources/personality-v3.json')) as \ +with open(join(os.getcwd(), 'resources/personality-v3.json')) as \ profile_json: profile = service.profile( profile_json.read(), @@ -37,7 +37,7 @@ # Profile with CSV output # ########################### -with open(join(dirname(__file__), '../resources/personality-v3.json'), 'r') as \ +with open(jjoin(os.getcwd(), 'resources/personality-v3.json'), 'r') as \ profile_json: response = service.profile( profile_json.read(), diff --git a/examples/tone_analyzer_v3.py b/examples/tone_analyzer_v3.py index 896a26b73..a8bb4e30f 100755 --- a/examples/tone_analyzer_v3.py +++ b/examples/tone_analyzer_v3.py @@ -35,14 +35,14 @@ indent=2)) print("\ntone() example 2:\n") -with open(join(dirname(__file__), - '../../resources/tone-example.json')) as tone_json: +with open(join(os.getcwd(), + 'resources/tone-example.json')) as tone_json: tone = service.tone(json.load(tone_json)['text'], content_type="text/plain").get_result() print(json.dumps(tone, indent=2)) print("\ntone() example 3:\n") -with open(join(dirname(__file__), - '../../resources/tone-example.json')) as tone_json: +with open(join(os.getcwd(), + 'resources/tone-example.json')) as tone_json: tone = service.tone( tone_input=json.load(tone_json)['text'], content_type='text/plain', @@ -50,24 +50,24 @@ print(json.dumps(tone, indent=2)) print("\ntone() example 4:\n") -with open(join(dirname(__file__), - '../../resources/tone-example.json')) as tone_json: +with open(join(os.getcwd(), + 'resources/tone-example.json')) as tone_json: tone = service.tone( tone_input=json.load(tone_json), content_type='application/json').get_result() print(json.dumps(tone, indent=2)) print("\ntone() example 5:\n") -with open(join(dirname(__file__), - '../../resources/tone-example-html.json')) as tone_html: +with open(join(os.getcwd(), + 'resources/tone-example-html.json')) as tone_html: tone = service.tone( json.load(tone_html)['text'], content_type='text/html').get_result() print(json.dumps(tone, indent=2)) print("\ntone() example 6 with GDPR support:\n") -with open(join(dirname(__file__), - '../../resources/tone-example-html.json')) as tone_html: +with open(join(os.getcwd(), + 'resources/tone-example-html.json')) as tone_html: tone = service.tone( json.load(tone_html)['text'], content_type='text/html', From f0eaafa2731b12847c9941687f0f91d73c43d94f Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 8 Nov 2019 11:43:48 -0800 Subject: [PATCH 124/455] fix(semantic): Fix semantic release stale commit --- .releaserc | 7 +++++-- .travis.yml | 21 +++++++++++++-------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/.releaserc b/.releaserc index 69775b042..7bca89531 100644 --- a/.releaserc +++ b/.releaserc @@ -1,7 +1,10 @@ { "branch": "master", - "verifyConditions": [], + "verifyConditions": ["@semantic-release/changelog", "@semantic-release/github"], + "debug": true, "prepare": [ + "@semantic-release/changelog", + "@semantic-release/git", { "path": "@semantic-release/exec", "cmd": "bumpversion --current-version ${lastRelease.version} --new-version ${nextRelease.version} patch" @@ -9,7 +12,7 @@ ], "publish": [ { - "path": "@semantic-release/github", + "path": "@semantic-release/github" } ] } \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 40f4f7388..62e0621b9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,18 +12,23 @@ before_install: - npm install npm@latest -g install: - pip install tox-travis -- pip install bumpversion -- npm install @semantic-release/exec -script: -- pip install -U python-dotenv -- tox -before_deploy: +before_script: - sudo apt-get update -- pip install -r requirements.txt -- pip install -r requirements-dev.txt - pip install pypandoc - sudo apt-get install pandoc +- pip install -r requirements.txt +- pip install -r requirements-dev.txt - pip install --editable . +script: +- pip install -U python-dotenv +- tox +before_deploy: +- pip install bumpversion +- nvm install 12 +- npm install @semantic-release/changelog +- npm install @semantic-release/exec +- npm install @semantic-release/git +- npm install @semantic-release/github deploy: - provider: script script: docs/publish.sh From fa24ca943a47664f79276e6e88fb3b453b8ff5de Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 8 Nov 2019 11:44:53 -0800 Subject: [PATCH 125/455] chore(travis): Update env file --- .env.enc | Bin 2736 -> 1792 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/.env.enc b/.env.enc index 78b26c9d65f2369cef9bf281440e83732dc1a2d7..314487b935a79d4c97b851c97835575d10fd900b 100644 GIT binary patch literal 1792 zcmV+b2mkofCg_VMQQ-b2GupQ4;73}wQ=Z1`5iUqv)8<{whT{GvuJ7TtG!dRJz(Pi$ z#RF$f7H~>ZLaqh zMbzR&zFcCMUvGVJ~VcU=d0NkSPhB_Zb(nQcjEvMdr(xAo4#5aNyyJx+(^8z_D)d~5n0 zozTG@-py9nZ^B!glYX7=0-0I{1E+#Yo*DdUzPG|6F?tm+ttJi_O0)OT(32~znGN>= zc1<6?$u>rIh!O4gc7R+NRu% z!{=PBRgvV~T`LNFN*3^M38lI384JDxt;jKGPJUvvTt`WHcv_MwCj@V1IcVFpe z*u(Nm<^#Sbafs%RQTk0?^xPLYGWc{l+_x5Jq=?Pc0ZPdx?+ zUW+TTzb-1h3kC)L{k@vNhEaH`TsqGs6O(H;o~>gOoMuaJSx6K8C_=yif2JNg-^hC+ z-&*%p)4N!CnE~Y`qX&}=$8JiLb*Gq}SRerD{gN<=xeY>Ekwl*owPA6bn~@XU(L~!2 z1%K)BV>g0LvNb%j=RuvJA2P1hkV8JhZE=B-q*_4#HR4R)j_o1>9Un!;Q-cT87(>B5 zVg7tG?l_9jgu=5Tu~$(L`6?nKe4CN;zWCGJAh3)9s~B7 z=lnv-t&PI;>G|XeGj<-}-c+tF)1ef~xG!&@rPz5<^U8^uQ?|%6!9O@*=2zS^GK@#s z-`4RFeP5#Wiwv@p9pl-D@~6ULFf^kD#qvCfxD6l)&}HSKz)hX&IE$pqGd4zRbcX^> zWZtF4z{xYk0J=1y`ZGu#K49^HGAGZTfBSFc7BNj)AYKn2rAo1v1ZlCh7(|4nFbXNWdci32ERulOZ`<)LK&tWikaaKZUm&}91(l> z_^O2YxIQ0?j?eM!lGSx&3Sv>&taT`X=UZg}vkzzGkeRW6Yb3DZhF z;u0;8{OGR$4m#0KDNfm_Y&rBd#96^4xQc_(4EgRD6h{-7LUX5PX90Tl>-CO&B%@~J z@tAHEy#Qn_y)#}fzi5Ea2ThY6oH%mEVW5r$+5?889$+52O-p#IsYTn=DG!7rp_M0h z#F*I>7C783^g_a9@=Zd!j&K;OF0mWseWr}guf*Lws&&?XKv+XG_I~ya>H3eg!u!%Q z+^~+^4n;Z2^pQ{A8){eh+)4Im7)5_Z0jDTamTKsN8qx2^(xI2chN8||Mo*GLCg)t4 iDd=ohlcEt-zm3{#0D5ai*Twu1StE2IF^TgT0OyHb#C(SU literal 2736 zcmV;h3QzUS-GLZw@Th>3K}N28mP#-@o$L+M>NnMRZSHGyq z?`zF1p^PKgt=$Q;a9pAcscY?DsJ;+~YL$ufO$h4Rek2mcRzp|Gp((`oz+d#oRa%-O z`Jvy=2Cpt9^-B`l(>rvJ6?lEG2I74sFL*m<&b48YoTD9SM zFOd83b&hV&PEXGr_VwM1bNV=8nI2d>99ry@PI$nWXVUww6sZfS#Pmhy?sbjxP7R)& zGFCM#C*3g~toI5(Qcs%pEpB+s%mWSM&pGftf^mHzDggvT6-Q_veKXYYTX)`&%;;aa zm&^bDlL7MsmB?crZ-2M(2ooZe+bA+Ey5b#UMc(=yK0mBUnBYgbeKJvrg$WdH7l!bi zicS^jfAXj&LdM%nIJJr)R2dn;RhX5k3>I_j^r$;_PA3&@G!9c5;*}`MuABCE0vVLY z4tE)9n6RgV$b~VlNm3{A-W@+mx>a&+Xd7HD89X<6SBWFup>qF`uHYi-W|4pf{7V<< z7j-_UOaq)5yu{t=O&@|sv=#F97xseO4B`A#Idn1}wZI#o8gsVR>S;M6C64W3wKFwN za-gKCVQ$qNk6&J_P#H4j?ke8!KdZ>xrgU{hV0lJkk?fgdN_T-M$xsbf?=1u14{j+P z$#niPit3Q21Y}-5dkK7NSbXHoKqn(W%}I?9cMc1*1{%tHtdPT5zCaqgwE2R5r}DL!gDg4CYywzZAwD zL5HFmoX&Y_#Sw$Os~vtBjHgT`Nl6Zrp}z2k)mRCT8W6wtkWak(E*a`T$Qm0EiF-I_ zK?JLkJOSnt(>Ax~nOSq;{e>;W&M5?=8Y>fi*~($ve$ti-M1rVIqmYRCT#qf*S z1%KcMXRbTW4+DMJaqb6Uc{RAZU%&)&52cC5{X4h(qz)g%)DXTI%vX7FB$1dK6S{K* zpG=})eKTsQ5dGS6A?{d?$4bOw)z=kG^4Jds5Hc4j=Q!xPfIJs{yX6tm3RVG??)ocB zKAC8)G)WyID)id^#7v#miK!;9u0~{Tq3S#BGvN?EoQf#U?EFi!b{2M=Sq zO?+OqYb@Y{QK$+VqAL3eAGq@O0N zh9ru@bV5~Z>t=Epjy_lp3D6UKsJN0=w`4;be-AnH5xQhsk?5P$F&?inz{SroK7ThG z=3>MbcWqeiwe3%!hS2I;ivE78)%avMN6zcHO3yH4K`#jes>H|4L_DXEhPUDn+N|$g zy4QMSbfzQf*;IuTPA;vKL5IIyWq;e!idCU!AJcY{nf&G{hD}!6=sS%Q7u0^wZ8JFFpM!-q3Gx<2rsoY< zWQmZUjECNOCbqLzfSWPmHS>R%t-iP_yUWKAKS{-G?5NYq|YT^2fLtqTvNk@gemQDHg6|R;nMSMWTgFKL?(VmBO7U zDl8PKM&mtt*7`FkIxysCuG_LY<|R_}--{gKz!~vLlG|2ewrIo3xsl|Y_B4wNwkUBHU7W+6M1ZHW}J{=zuEBWZ8SenN~nzHAKJ{=gfK z{D3zNhM4ktO%a5CwZ=)#vTsq)?l;p*!sK@uyM{LANFnMpcoyFd}A)h zpKQfmups5*NXx=F4H5Y-uv(+RR+{{Lg74yC>{*l1+T)_ze0r#)+)JkFi(hO_;Flet zW&~;(yaypFXoVb-DUfeAH`LmpUVs0inyD&53D!TuGSS!gv*ce55;@Hv=Do<`y5L8! zm>m#L^(QPa#6jWi&JMz{*nz)AUa2VYl_zRwd~GlWNR5o_01gV?;e)G0{FoS?lq)ND zeC>-ZbK4~`A3SkFC_Zi`;iP+49kxxv)bR*%c$COdr+7pYlVae`D-#t#(3S^tsE<`J zg8|IRB0w9w-{LB~#%7in1Iu9RD*<*+Kkn+|<`PX=)MQ(SCyrR(MapM4&dtxFShxrw z31eok3a5EnP`-6np!&#fMW6W=rAdV~k
-%kc53Xd^`n;u!eqjfEajhFQn+E!YKR zzvgwqerP%b@}Wi{2Qng9?YQ(j3-$qaHDhl%x9m1tm|>a|>AL(d`DASm=c|f86y+7y z8!&VbO(EXG^^l-E-q(I8soUfi3aK?|_-|91!w|tKIA=l%^CJ`69q-;@F8vDrcyUj& ztXSI&^c1tGQZ{$*3Q~<9#Qp1#9km#naY^n_tqG08 From d53bcc9397cbd276f1dc73ecd74ba3e5973df705 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 8 Nov 2019 12:01:17 -0800 Subject: [PATCH 126/455] chore(pi): correct typo --- examples/personality_insights_v3.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/personality_insights_v3.py b/examples/personality_insights_v3.py index 82753f321..2ba587d79 100755 --- a/examples/personality_insights_v3.py +++ b/examples/personality_insights_v3.py @@ -37,7 +37,7 @@ # Profile with CSV output # ########################### -with open(jjoin(os.getcwd(), 'resources/personality-v3.json'), 'r') as \ +with open(join(os.getcwd(), 'resources/personality-v3.json'), 'r') as \ profile_json: response = service.profile( profile_json.read(), From 5242d9778a173079dd789971da85c0003276d6f5 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 8 Nov 2019 12:51:22 -0800 Subject: [PATCH 127/455] refactor(test): Update minor details --- examples/natural_language_understanding_v1.py | 2 +- examples/tone_analyzer_v3.py | 5 +++-- test/integration/test_examples.py | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/examples/natural_language_understanding_v1.py b/examples/natural_language_understanding_v1.py index 86485e796..87449a6d2 100644 --- a/examples/natural_language_understanding_v1.py +++ b/examples/natural_language_understanding_v1.py @@ -1,7 +1,7 @@ import json from ibm_watson import NaturalLanguageUnderstandingV1 from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +# from ibm_cloud_sdk_core.authenticators import IAMAuthenticator # Authentication via IAM # authenticator = IAMAuthenticator('your_api_key') diff --git a/examples/tone_analyzer_v3.py b/examples/tone_analyzer_v3.py index a8bb4e30f..bcd32adfd 100755 --- a/examples/tone_analyzer_v3.py +++ b/examples/tone_analyzer_v3.py @@ -1,8 +1,9 @@ import json -from os.path import join, dirname +import os +from os.path import join from ibm_watson import ToneAnalyzerV3 from ibm_watson.tone_analyzer_v3 import ToneInput -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +# from ibm_cloud_sdk_core.authenticators import IAMAuthenticator # Authentication via IAM # authenticator = IAMAuthenticator('your_api_key') diff --git a/test/integration/test_examples.py b/test/integration/test_examples.py index 861fb27e5..ed6e5f9a1 100644 --- a/test/integration/test_examples.py +++ b/test/integration/test_examples.py @@ -22,7 +22,7 @@ def test_examples(): for example in examples: name = example.split('/')[-1] - if not name in includes: + if name not in includes: continue service_name = name[:-6] From 63f19e244d4449fef8a02815e063629e790fa116 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Mon, 11 Nov 2019 10:09:51 -0800 Subject: [PATCH 128/455] refactor(release.rc): Update release rc file with prepare steps order --- .releaserc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.releaserc b/.releaserc index 7bca89531..5402290f7 100644 --- a/.releaserc +++ b/.releaserc @@ -3,12 +3,12 @@ "verifyConditions": ["@semantic-release/changelog", "@semantic-release/github"], "debug": true, "prepare": [ - "@semantic-release/changelog", - "@semantic-release/git", { "path": "@semantic-release/exec", "cmd": "bumpversion --current-version ${lastRelease.version} --new-version ${nextRelease.version} patch" - } + }, + "@semantic-release/changelog", + "@semantic-release/git" ], "publish": [ { From 0811d62eb5090b7d508134d960cc622d5f375f0b Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Mon, 11 Nov 2019 22:14:06 +0000 Subject: [PATCH 129/455] =?UTF-8?q?Bump=20version:=204.0.1=20=E2=86=92=204?= =?UTF-8?q?.0.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 663cccb49..ef2253944 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.0.1 +current_version = 4.0.2 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 1a3bef532..439176402 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.0.1' +__version__ = '4.0.2' diff --git a/setup.py b/setup.py index 94951f1b2..b86aec84f 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.0.1' +__version__ = '4.0.2' if sys.argv[-1] == 'publish': From e84551db9cebd8f330c09412667a1ebed9d6fb74 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Mon, 11 Nov 2019 22:14:06 +0000 Subject: [PATCH 130/455] chore(release): 4.0.2 [skip ci] ## [4.0.2](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.1...v4.0.2) (2019-11-11) ### Bug Fixes * **semantic:** Fix semantic release stale commit ([f0eaafa](https://github.com/watson-developer-cloud/python-sdk/commit/f0eaafa2731b12847c9941687f0f91d73c43d94f)) --- CHANGELOG.md | 7 + package-lock.json | 1050 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1057 insertions(+) create mode 100644 package-lock.json diff --git a/CHANGELOG.md b/CHANGELOG.md index f7e2525c2..b39dec37a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1 +1,8 @@ +## [4.0.2](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.1...v4.0.2) (2019-11-11) + + +### Bug Fixes + +* **semantic:** Fix semantic release stale commit ([f0eaafa](https://github.com/watson-developer-cloud/python-sdk/commit/f0eaafa2731b12847c9941687f0f91d73c43d94f)) + Moved to [https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..34dfb8d2b --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1050 @@ +{ + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@babel/code-frame": { + "version": "7.5.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.5.5.tgz", + "integrity": "sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw==", + "requires": { + "@babel/highlight": "^7.0.0" + } + }, + "@babel/highlight": { + "version": "7.5.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.5.0.tgz", + "integrity": "sha512-7dV4eu9gBxoM0dAnj/BCFDW9LFU0zvTrkq0ugM7pnHEgguOEeOz1so2ZghEdzviYzQEED0r4EAgpsBChKy1TRQ==", + "requires": { + "chalk": "^2.0.0", + "esutils": "^2.0.2", + "js-tokens": "^4.0.0" + } + }, + "@nodelib/fs.scandir": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.3.tgz", + "integrity": "sha512-eGmwYQn3gxo4r7jdQnkrrN6bY478C3P+a/y72IJukF8LjB6ZHeB3c+Ehacj3sYeSmUXGlnA67/PmbM9CVwL7Dw==", + "requires": { + "@nodelib/fs.stat": "2.0.3", + "run-parallel": "^1.1.9" + } + }, + "@nodelib/fs.stat": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.3.tgz", + "integrity": "sha512-bQBFruR2TAwoevBEd/NWMoAAtNGzTRgdrqnYCc7dhzfoNvqPzLyqlEQnzZ3kVnNrSp25iyxE00/3h2fqGAGArA==" + }, + "@nodelib/fs.walk": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.4.tgz", + "integrity": "sha512-1V9XOY4rDW0rehzbrcqAmHnz8e7SKvX27gh8Gt2WgB0+pdzdiLV83p72kZPU+jvMbS1qU5mauP2iOvO8rhmurQ==", + "requires": { + "@nodelib/fs.scandir": "2.1.3", + "fastq": "^1.6.0" + } + }, + "@octokit/endpoint": { + "version": "5.5.1", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-5.5.1.tgz", + "integrity": "sha512-nBFhRUb5YzVTCX/iAK1MgQ4uWo89Gu0TH00qQHoYRCsE12dWcG1OiLd7v2EIo2+tpUKPMOQ62QFy9hy9Vg2ULg==", + "requires": { + "@octokit/types": "^2.0.0", + "is-plain-object": "^3.0.0", + "universal-user-agent": "^4.0.0" + } + }, + "@octokit/request": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.3.1.tgz", + "integrity": "sha512-5/X0AL1ZgoU32fAepTfEoggFinO3rxsMLtzhlUX+RctLrusn/CApJuGFCd0v7GMFhF+8UiCsTTfsu7Fh1HnEJg==", + "requires": { + "@octokit/endpoint": "^5.5.0", + "@octokit/request-error": "^1.0.1", + "@octokit/types": "^2.0.0", + "deprecation": "^2.0.0", + "is-plain-object": "^3.0.0", + "node-fetch": "^2.3.0", + "once": "^1.4.0", + "universal-user-agent": "^4.0.0" + } + }, + "@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==", + "requires": { + "@octokit/types": "^2.0.0", + "deprecation": "^2.0.0", + "once": "^1.4.0" + } + }, + "@octokit/rest": { + "version": "16.35.0", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.35.0.tgz", + "integrity": "sha512-9ShFqYWo0CLoGYhA1FdtdykJuMzS/9H6vSbbQWDX4pWr4p9v+15MsH/wpd/3fIU+tSxylaNO48+PIHqOkBRx3w==", + "requires": { + "@octokit/request": "^5.2.0", + "@octokit/request-error": "^1.0.2", + "atob-lite": "^2.0.0", + "before-after-hook": "^2.0.0", + "btoa-lite": "^1.0.0", + "deprecation": "^2.0.0", + "lodash.get": "^4.4.2", + "lodash.set": "^4.3.2", + "lodash.uniq": "^4.5.0", + "octokit-pagination-methods": "^1.1.0", + "once": "^1.4.0", + "universal-user-agent": "^4.0.0" + } + }, + "@octokit/types": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-2.0.1.tgz", + "integrity": "sha512-YDYgV6nCzdGdOm7wy43Ce8SQ3M5DMKegB8E5sTB/1xrxOdo2yS/KgUgML2N2ZGD621mkbdrAglwTyA4NDOlFFA==", + "requires": { + "@types/node": ">= 8" + } + }, + "@semantic-release/changelog": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@semantic-release/changelog/-/changelog-3.0.5.tgz", + "integrity": "sha512-/U44eK5qL2olevbEi+GrJxq1lNGUABChqK58A3SkiDsZS6AoGO8CJHQ7OG0zx+spxwkY4TevZ85Whz/hYyO+5w==", + "requires": { + "@semantic-release/error": "^2.1.0", + "aggregate-error": "^3.0.0", + "fs-extra": "^8.0.0", + "lodash": "^4.17.4" + } + }, + "@semantic-release/error": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@semantic-release/error/-/error-2.2.0.tgz", + "integrity": "sha512-9Tj/qn+y2j+sjCI3Jd+qseGtHjOAeg7dU2/lVcqIQ9TV3QDaDXDYXcoOHU+7o2Hwh8L8ymL4gfuO7KxDs3q2zg==" + }, + "@semantic-release/exec": { + "version": "3.3.8", + "resolved": "https://registry.npmjs.org/@semantic-release/exec/-/exec-3.3.8.tgz", + "integrity": "sha512-GH1v5BwXRIUAnvrXjil+R+9DjI+ELgk2NMdQUAnp2/qZ6YItZt6KI8HrY3zAFDrG0YGaOwC9XxuUNKeldsOK7A==", + "requires": { + "@semantic-release/error": "^2.1.0", + "aggregate-error": "^3.0.0", + "debug": "^4.0.0", + "execa": "^3.2.0", + "lodash": "^4.17.4", + "parse-json": "^5.0.0" + } + }, + "@semantic-release/git": { + "version": "7.0.18", + "resolved": "https://registry.npmjs.org/@semantic-release/git/-/git-7.0.18.tgz", + "integrity": "sha512-VwnsGUXpNdvPcsq05BQyLBZxGUlEiJCMKNi8ttLvZZAhjI1mAp9dwypOeyxSJ5eFQ+iGMBLdoKF1LL0pmA/d0A==", + "requires": { + "@semantic-release/error": "^2.1.0", + "aggregate-error": "^3.0.0", + "debug": "^4.0.0", + "dir-glob": "^3.0.0", + "execa": "^3.2.0", + "fs-extra": "^8.0.0", + "globby": "^10.0.0", + "lodash": "^4.17.4", + "micromatch": "^4.0.0", + "p-reduce": "^2.0.0" + } + }, + "@semantic-release/github": { + "version": "5.5.5", + "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-5.5.5.tgz", + "integrity": "sha512-Wo9OIULMRydbq+HpFh9yiLvra1XyEULPro9Tp4T5MQJ0WZyAQ3YQm74IdT8Pe/UmVDq2nfpT1oHrWkwOc4loHg==", + "requires": { + "@octokit/rest": "^16.27.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": "^2.1.0", + "https-proxy-agent": "^3.0.0", + "issue-parser": "^5.0.0", + "lodash": "^4.17.4", + "mime": "^2.4.3", + "p-filter": "^2.0.0", + "p-retry": "^4.0.0", + "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==" + }, + "@types/node": { + "version": "12.12.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.7.tgz", + "integrity": "sha512-E6Zn0rffhgd130zbCbAr/JdXfXkoOUFAKNs/rF8qnafSJ8KYaA/j3oz7dcwal+lYjLA7xvdd5J4wdYpCTlP8+w==" + }, + "@types/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==" + }, + "agent-base": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-4.3.0.tgz", + "integrity": "sha512-salcGninV0nPrwpGNn4VTXBb1SOuXQBiqbrNXoeizJsHrsL6ERFM2Ne3JUSBWRE6aeNJI2ROP/WEEIDUiDe3cg==", + "requires": { + "es6-promisify": "^5.0.0" + } + }, + "aggregate-error": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.0.1.tgz", + "integrity": "sha512-quoaXsZ9/BLNae5yiNoUz+Nhkwz83GhWwtYFglcjEQB2NDHCIpApbqXxIFnm4Pq/Nvhrsq5sYJFyohrrxnTGAA==", + "requires": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + } + }, + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "array-union": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", + "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==" + }, + "atob-lite": { + "version": "2.0.0", + "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", + "integrity": "sha512-IWIbu7pMqyw3EAJHzzHbWa85b6oud/yfKYg5rqB5hNE8CeMi3nX+2C2sj0HswfblST86hpVEOAb9x34NZd6P7A==" + }, + "bottleneck": { + "version": "2.19.5", + "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", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "requires": { + "fill-range": "^7.0.1" + } + }, + "btoa-lite": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/btoa-lite/-/btoa-lite-1.0.0.tgz", + "integrity": "sha1-M3dm2hWAEhD92VbCLpxokaudAzc=" + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "clean-stack": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", + "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==" + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "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", + "integrity": "sha512-u7v4o84SwFpD32Z8IIcPZ6z1/ie24O6RU3RbtL5Y316l3KuHVPx9ItBgWQ6VlfAFnRnTtMUrsQ9MUUTuEZjogg==", + "requires": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + } + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "requires": { + "ms": "^2.1.1" + } + }, + "deprecation": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/deprecation/-/deprecation-2.3.1.tgz", + "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==" + }, + "dir-glob": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/dir-glob/-/dir-glob-3.0.1.tgz", + "integrity": "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==", + "requires": { + "path-type": "^4.0.0" + } + }, + "end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "requires": { + "once": "^1.4.0" + } + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "es6-promise": { + "version": "4.2.8", + "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz", + "integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==" + }, + "es6-promisify": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/es6-promisify/-/es6-promisify-5.0.0.tgz", + "integrity": "sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM=", + "requires": { + "es6-promise": "^4.0.3" + } + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" + }, + "esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==" + }, + "execa": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-3.2.0.tgz", + "integrity": "sha512-kJJfVbI/lZE1PZYDI5VPxp8zXPO9rtxOkhpZ0jMKha56AI9y2gGVC6bkukStQf0ka5Rh15BA5m7cCCH4jmHqkw==", + "requires": { + "cross-spawn": "^7.0.0", + "get-stream": "^5.0.0", + "human-signals": "^1.1.1", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.0", + "onetime": "^5.1.0", + "p-finally": "^2.0.0", + "signal-exit": "^3.0.2", + "strip-final-newline": "^2.0.0" + } + }, + "fast-glob": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.1.0.tgz", + "integrity": "sha512-TrUz3THiq2Vy3bjfQUB2wNyPdGBeGmdjbzzBLhfHN4YFurYptCKwGq/TfiRavbGywFRzY6U2CdmQ1zmsY5yYaw==", + "requires": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.0", + "merge2": "^1.3.0", + "micromatch": "^4.0.2" + } + }, + "fastq": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.6.0.tgz", + "integrity": "sha512-jmxqQ3Z/nXoeyDmWAzF9kH1aGZSis6e/SbfPmJpUnyZ0ogr6iscHQaml4wsEepEWSdtmpy+eVXmCRIMpxaXqOA==", + "requires": { + "reusify": "^1.0.0" + } + }, + "fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "requires": { + "to-regex-range": "^5.0.1" + } + }, + "fs-extra": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", + "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", + "requires": { + "graceful-fs": "^4.2.0", + "jsonfile": "^4.0.0", + "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", + "integrity": "sha512-EXr1FOzrzTfGeL0gQdeFEvOMm2mzMOglyiOXSTpPC+iAjAKftbr3jpCMWynogwYnM+eSj9sHGc6wjIcDvYiygw==", + "requires": { + "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", + "integrity": "sha512-qjtRgnIVmOfnKUE3NJAQEdk+lKrxfw8t5ke7SXtfMTHcjsBfOfWXCQfdb30zfDoZQ2IRSIiidmjtbHZPZ++Ihw==", + "requires": { + "is-glob": "^4.0.1" + } + }, + "globby": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/globby/-/globby-10.0.1.tgz", + "integrity": "sha512-sSs4inE1FB2YQiymcmTv6NWENryABjUNPeWhOvmn4SjtKybglsyPZxFB3U1/+L1bYi0rNZDqCLlHyLYDl1Pq5A==", + "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", + "slash": "^3.0.0" + } + }, + "graceful-fs": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz", + "integrity": "sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ==" + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" + }, + "http-proxy-agent": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-2.1.0.tgz", + "integrity": "sha512-qwHbBLV7WviBl0rQsOzH6o5lwyOIvwp/BdFnvVxXORldu5TmjFfjzBcWUWS5kWAZhmv+JtiDhSuQCp4sBfbIgg==", + "requires": { + "agent-base": "4", + "debug": "3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "requires": { + "ms": "2.0.0" + } + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + } + } + }, + "https-proxy-agent": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-3.0.1.tgz", + "integrity": "sha512-+ML2Rbh6DAuee7d07tYGEKOEi2voWPUGan+ExdPbPW6Z3svq+JCqr0v8WmKPOkz1vOVykPCBSuobe7G8GJUtVg==", + "requires": { + "agent-base": "^4.3.0", + "debug": "^3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", + "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", + "requires": { + "ms": "^2.1.1" + } + } + } + }, + "human-signals": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-1.1.1.tgz", + "integrity": "sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==" + }, + "ignore": { + "version": "5.1.4", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.4.tgz", + "integrity": "sha512-MzbUSahkTW1u7JpKKjY7LCARd1fU5W2rLdxlM4kdkayuCwZImjkpluF9CM1aLewYJguPDqewLam18Y6AU69A8A==" + }, + "indent-string": { + "version": "4.0.0", + "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", + "integrity": "sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=" + }, + "is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha1-qIwCU1eR8C7TfHahueqXc8gz+MI=" + }, + "is-glob": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.1.tgz", + "integrity": "sha512-5G0tKtBTFImOqDnLB2hG6Bp2qcKEFduo4tZu9MT/H6NQv/ghhy30o55ufafxJ/LdH79LLs2Kfrn85TLKyA7BUg==", + "requires": { + "is-extglob": "^2.1.1" + } + }, + "is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" + }, + "is-plain-object": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-3.0.0.tgz", + "integrity": "sha512-tZIpofR+P05k8Aocp7UI/2UTa9lTJSebCXpFFoR9aibpokDj/uXBsJ8luUu0tTVYKkMU6URDUuOfJZ7koewXvg==", + "requires": { + "isobject": "^4.0.0" + } + }, + "is-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", + "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==" + }, + "isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" + }, + "isobject": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/isobject/-/isobject-4.0.0.tgz", + "integrity": "sha512-S/2fF5wH8SJA/kmwr6HYhK/RI/OkhD84k8ntalo0iJjZikgq1XFvR5M8NPT1x5F7fBwCG3qHfnzeP/Vh/ZxCUA==" + }, + "issue-parser": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/issue-parser/-/issue-parser-5.0.0.tgz", + "integrity": "sha512-q/16W7EPHRL0FKVz9NU++TUsoygXGj6JOi88oulyAcQG+IEZ0T6teVdE+VLbe19OfL/tbV8Wi3Dfo0HedeHW0Q==", + "requires": { + "lodash.capitalize": "^4.2.1", + "lodash.escaperegexp": "^4.1.2", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.uniqby": "^4.7.0" + } + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "json-parse-better-errors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", + "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==" + }, + "jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "requires": { + "graceful-fs": "^4.1.6" + } + }, + "lines-and-columns": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.1.6.tgz", + "integrity": "sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA=" + }, + "lodash": { + "version": "4.17.15", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", + "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==" + }, + "lodash.capitalize": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/lodash.capitalize/-/lodash.capitalize-4.2.1.tgz", + "integrity": "sha1-+CbJtOKoUR2E46yinbBeGk87cqk=" + }, + "lodash.escaperegexp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz", + "integrity": "sha1-ZHYsSGGAglGKw99Mz11YhtriA0c=" + }, + "lodash.get": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", + "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=" + }, + "lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=" + }, + "lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" + }, + "lodash.set": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/lodash.set/-/lodash.set-4.3.2.tgz", + "integrity": "sha1-2HV7HagH3eJIFrDWqEvqGnYjCyM=" + }, + "lodash.uniq": { + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", + "integrity": "sha1-0CJTc662Uq3BvILklFM5qEJ1R3M=" + }, + "lodash.uniqby": { + "version": "4.7.0", + "resolved": "https://registry.npmjs.org/lodash.uniqby/-/lodash.uniqby-4.7.0.tgz", + "integrity": "sha1-2ZwHpmnp5tJOE2Lf4mbGdhavEwI=" + }, + "macos-release": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/macos-release/-/macos-release-2.3.0.tgz", + "integrity": "sha512-OHhSbtcviqMPt7yfw5ef5aghS2jzFVKEFyCJndQt2YpSQ9qRVSEv2axSJI1paVThEu+FFGs584h/1YhxjVqajA==" + }, + "merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==" + }, + "merge2": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.3.0.tgz", + "integrity": "sha512-2j4DAdlBOkiSZIsaXk4mTE3sRS02yBHAtfy127xRV3bQUFqXkjHCHLW6Scv7DwNRbIWNHH8zpnz9zMaKXIdvYw==" + }, + "micromatch": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz", + "integrity": "sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==", + "requires": { + "braces": "^3.0.1", + "picomatch": "^2.0.5" + } + }, + "mime": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.4.tgz", + "integrity": "sha512-LRxmNwziLPT828z+4YkNzloCFC2YM4wrB99k+AV5ZbEyfGNWfG8SO1FUXLmLDBSo89NrJZ4DIWeLjy1CHGhMGA==" + }, + "mimic-fn": { + "version": "2.1.0", + "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", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "nice-try": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", + "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==" + }, + "node-fetch": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz", + "integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==" + }, + "npm-run-path": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.0.tgz", + "integrity": "sha512-8eyAOAH+bYXFPSnNnKr3J+yoybe8O87Is5rtAQ8qRczJz1ajcsjg8l2oZqP+Ppx15Ii3S1vUTjQN2h4YO2tWWQ==", + "requires": { + "path-key": "^3.0.0" + } + }, + "octokit-pagination-methods": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/octokit-pagination-methods/-/octokit-pagination-methods-1.1.0.tgz", + "integrity": "sha512-fZ4qZdQ2nxJvtcasX7Ghl+WlWS/d9IgnBIwFZXVNNZUmzpno91SX5bc5vuxiuKoCtK78XxGGNuSCrDC7xYB3OQ==" + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "requires": { + "wrappy": "1" + } + }, + "onetime": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.0.tgz", + "integrity": "sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q==", + "requires": { + "mimic-fn": "^2.1.0" + } + }, + "os-name": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/os-name/-/os-name-3.1.0.tgz", + "integrity": "sha512-h8L+8aNjNcMpo/mAIBPn5PXCM16iyPGjHNWo6U1YO8sJTMHtEtyczI6QJnLoplswm6goopQkqc7OAnjhWcugVg==", + "requires": { + "macos-release": "^2.2.0", + "windows-release": "^3.1.0" + } + }, + "p-filter": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/p-filter/-/p-filter-2.1.0.tgz", + "integrity": "sha512-ZBxxZ5sL2HghephhpGAQdoskxplTwr7ICaehZwLIlfL6acuVgZPm8yBNuRAFBGEqtD/hmUeq9eqLg2ys9Xr/yw==", + "requires": { + "p-map": "^2.0.0" + } + }, + "p-finally": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-2.0.1.tgz", + "integrity": "sha512-vpm09aKwq6H9phqRQzecoDpD8TmVyGw70qmWlyq5onxY7tqyTTFVvxMykxQSQKILBSFlbXpypIw2T1Ml7+DDtw==" + }, + "p-map": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/p-map/-/p-map-2.1.0.tgz", + "integrity": "sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw==" + }, + "p-reduce": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/p-reduce/-/p-reduce-2.1.0.tgz", + "integrity": "sha512-2USApvnsutq8uoxZBGbbWM0JIYLiEMJ9RlaN7fAzVNb9OZN0SHjjTTfIcb667XynS5Y1VhwDJVDa72TnPzAYWw==" + }, + "p-retry": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.2.0.tgz", + "integrity": "sha512-jPH38/MRh263KKcq0wBNOGFJbm+U6784RilTmHjB/HM9kH9V8WlCpVUcdOmip9cjXOh6MxZ5yk1z2SjDUJfWmA==", + "requires": { + "@types/retry": "^0.12.0", + "retry": "^0.12.0" + } + }, + "parse-json": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.0.0.tgz", + "integrity": "sha512-OOY5b7PAEFV0E2Fir1KOkxchnZNCdowAJgQ5NuxjpBKTRP3pQhwkrkxqQjeoKJ+fO7bCpmIZaogI4eZGDMEGOw==", + "requires": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1", + "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.0", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.0.tgz", + "integrity": "sha512-8cChqz0RP6SHJkMt48FW0A7+qUOn+OsnOsVtzI59tZ8m+5bCSk7hzwET0pulwOM2YMn9J1efb07KB9l9f30SGg==" + }, + "path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==" + }, + "picomatch": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.1.1.tgz", + "integrity": "sha512-OYMyqkKzK7blWO/+XZYP6w8hH0LDvkBvdvKukti+7kqYFCiEAk+gI3DWnryapc0Dau05ugGTy0foQ6mqn4AHYA==" + }, + "pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha1-G0KmJmoh8HQh0bC1S33BZ7AcATs=" + }, + "reusify": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz", + "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==" + }, + "run-parallel": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.1.9.tgz", + "integrity": "sha512-DEqnSRTDw/Tc3FXf49zedI638Z9onwUotBMiUFKmrO2sdFKIbXamXGQ3Axd4qgphxKB4kw/qP1w5kTxnfU1B9Q==" + }, + "semver": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", + "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + }, + "shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "requires": { + "shebang-regex": "^3.0.0" + } + }, + "shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" + }, + "signal-exit": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", + "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=" + }, + "slash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", + "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==" + }, + "strip-eof": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=" + }, + "strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==" + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + }, + "to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "requires": { + "is-number": "^7.0.0" + } + }, + "universal-user-agent": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-4.0.0.tgz", + "integrity": "sha512-eM8knLpev67iBDizr/YtqkJsF3GK8gzDc6st/WKzrTuPtcsOKW/0IdL4cnMBsU69pOx0otavLWBDGTwg+dB0aA==", + "requires": { + "os-name": "^3.1.0" + } + }, + "universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==" + }, + "url-join": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.1.tgz", + "integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==" + }, + "which": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.1.tgz", + "integrity": "sha512-N7GBZOTswtB9lkQBZA4+zAXrjEIWAUOB93AvzUiudRzRxhUdLURQ7D/gAIMY1gatT/LTbmbcv8SiYazy3eYB7w==", + "requires": { + "isexe": "^2.0.0" + } + }, + "windows-release": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/windows-release/-/windows-release-3.2.0.tgz", + "integrity": "sha512-QTlz2hKLrdqukrsapKsINzqMgOUpQW268eJ0OaOpJN32h272waxR9fkB9VoWRtK7uKHG5EHJcTXQBD8XZVJkFA==", + "requires": { + "execa": "^1.0.0" + }, + "dependencies": { + "cross-spawn": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", + "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", + "requires": { + "nice-try": "^1.0.4", + "path-key": "^2.0.1", + "semver": "^5.5.0", + "shebang-command": "^1.2.0", + "which": "^1.2.9" + } + }, + "execa": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", + "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", + "requires": { + "cross-spawn": "^6.0.0", + "get-stream": "^4.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" + } + }, + "get-stream": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", + "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", + "requires": { + "pump": "^3.0.0" + } + }, + "is-stream": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", + "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=" + }, + "npm-run-path": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", + "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", + "requires": { + "path-key": "^2.0.0" + } + }, + "p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" + }, + "path-key": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", + "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" + }, + "shebang-command": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", + "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", + "requires": { + "shebang-regex": "^1.0.0" + } + }, + "shebang-regex": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", + "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" + }, + "which": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", + "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", + "requires": { + "isexe": "^2.0.0" + } + } + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" + } + } +} From 7f66fbe1f20e440105620823bb13a78e3c5e22a1 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 19 Nov 2019 08:04:15 -0800 Subject: [PATCH 131/455] doc(cp4d): Disable ssl verification for CP4D authenticator --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7aeffb6b9..154ba9c2a 100755 --- a/README.md +++ b/README.md @@ -394,7 +394,8 @@ from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator authenticator = CloudPakForDataAuthenticator( '', '', - '') # should be of the form https://{icp_cluster_host}{instance-id}/api + '', # should be of the form https://{icp_cluster_host}{instance-id}/api + disable_ssl_verification=True) # Disable ssl verification for authenticator assistant = AssistantV1( version='', From 237aef9855fdddf49a2293686042726166144113 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 19 Nov 2019 09:20:23 -0800 Subject: [PATCH 132/455] chore(format): run yapf cmd on non generated files --- ibm_watson/common.py | 17 +++++++++++++---- ibm_watson/speech_to_text_v1_adapter.py | 15 +++++++-------- ibm_watson/text_to_speech_adapter_v1.py | 18 ++++++------------ ibm_watson/websocket/audio_source.py | 1 + .../websocket/recognize_abstract_callback.py | 1 + ibm_watson/websocket/recognize_listener.py | 15 +++++++++++---- ibm_watson/websocket/synthesize_callback.py | 1 + ibm_watson/websocket/synthesize_listener.py | 10 +++++++--- 8 files changed, 47 insertions(+), 31 deletions(-) diff --git a/ibm_watson/common.py b/ibm_watson/common.py index 5929c6b57..81ecc7ec0 100644 --- a/ibm_watson/common.py +++ b/ibm_watson/common.py @@ -21,21 +21,30 @@ USER_AGENT_HEADER = 'User-Agent' SDK_NAME = 'watson-apis-python-sdk' + def get_system_info(): - return '{0} {1} {2}'.format(platform.system(), # OS - platform.release(), # OS version - platform.python_version()) # Python version + return '{0} {1} {2}'.format( + platform.system(), # OS + platform.release(), # OS version + platform.python_version()) # Python version + + def get_user_agent(): return user_agent + def get_sdk_analytics(service_name, service_version, operation_id): return 'service_name={0};service_version={1};operation_id={2}'.format( service_name, service_version, operation_id) + user_agent = '{0}-{1} {2}'.format(SDK_NAME, __version__, get_system_info()) + def get_sdk_headers(service_name, service_version, operation_id): headers = {} - headers[SDK_ANALYTICS_HEADER] = get_sdk_analytics(service_name, service_version, operation_id) + headers[SDK_ANALYTICS_HEADER] = get_sdk_analytics(service_name, + service_version, + operation_id) headers[USER_AGENT_HEADER] = get_user_agent() return headers diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index d9eded45c..9f59e4721 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -20,7 +20,9 @@ BEARER = 'Bearer' + class SpeechToTextV1Adapter(SpeechToTextV1): + def recognize_using_websocket(self, audio, content_type, @@ -194,7 +196,8 @@ def recognize_using_websocket(self, raise ValueError('audio must be provided') if not isinstance(audio, AudioSource): raise Exception( - 'audio is not of type AudioSource. Import the class from ibm_watson.websocket') + 'audio is not of type AudioSource. Import the class from ibm_watson.websocket' + ) if content_type is None: raise ValueError('content_type must be provided') if recognize_callback is None: @@ -251,11 +254,7 @@ def recognize_using_websocket(self, options = {k: v for k, v in options.items() if v is not None} request['options'] = options - RecognizeListener(audio, - request.get('options'), - recognize_callback, - request.get('url'), - request.get('headers'), - http_proxy_host, - http_proxy_port, + RecognizeListener(audio, request.get('options'), recognize_callback, + request.get('url'), request.get('headers'), + http_proxy_host, http_proxy_port, self.disable_ssl_verification) diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index 16f71e68b..0c2f92229 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -1,4 +1,3 @@ - # coding: utf-8 # Copyright 2018 IBM All Rights Reserved. @@ -21,7 +20,9 @@ BEARER = 'Bearer' + class TextToSpeechV1Adapter(TextToSpeechV1): + def synthesize_using_websocket(self, text, synthesize_callback, @@ -94,18 +95,11 @@ def synthesize_using_websocket(self, url += '/v1/synthesize?{0}'.format(urlencode(params)) request['url'] = url - options = { - 'text': text, - 'accept': accept, - 'timings': timings - } + options = {'text': text, 'accept': accept, 'timings': timings} options = {k: v for k, v in options.items() if v is not None} request['options'] = options - SynthesizeListener(request.get('options'), - synthesize_callback, - request.get('url'), - request.get('headers'), - http_proxy_host, - http_proxy_port, + SynthesizeListener(request.get('options'), synthesize_callback, + request.get('url'), request.get('headers'), + http_proxy_host, http_proxy_port, self.disable_ssl_verification) diff --git a/ibm_watson/websocket/audio_source.py b/ibm_watson/websocket/audio_source.py index b33930578..dfeb44b8e 100644 --- a/ibm_watson/websocket/audio_source.py +++ b/ibm_watson/websocket/audio_source.py @@ -14,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. + class AudioSource(object): """"Audio source for the speech to text recognize using websocket""" diff --git a/ibm_watson/websocket/recognize_abstract_callback.py b/ibm_watson/websocket/recognize_abstract_callback.py index ed77ce253..1c8ab5220 100644 --- a/ibm_watson/websocket/recognize_abstract_callback.py +++ b/ibm_watson/websocket/recognize_abstract_callback.py @@ -16,6 +16,7 @@ class RecognizeCallback(object): + def __init__(self): pass diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index a37e6792e..09f2f1276 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -31,7 +31,9 @@ START = "start" STOP = "stop" + class RecognizeListener(object): + def __init__(self, audio_source, options, @@ -64,7 +66,8 @@ def __init__(self, self.ws_client.run_forever(http_proxy_host=self.http_proxy_host, http_proxy_port=self.http_proxy_port, - sslopt={"cert_reqs": ssl.CERT_NONE} if self.verify is not None else None) + sslopt={"cert_reqs": ssl.CERT_NONE} + if self.verify is not None else None) @classmethod def build_start_message(cls, options): @@ -102,6 +105,7 @@ def send_audio(self, ws): :param ws: Websocket client """ + def run(*args): """Background process to stream the data""" if not self.audio_source.is_buffer: @@ -118,7 +122,8 @@ def run(*args): try: if not self.audio_source.input.empty(): chunk = self.audio_source.input.get() - self.ws_client.send(chunk, websocket.ABNF.OPCODE_BINARY) + self.ws_client.send(chunk, + websocket.ABNF.OPCODE_BINARY) time.sleep(TEN_MILLISECONDS) if self.audio_source.input.empty(): if self.audio_source.is_recording: @@ -132,7 +137,8 @@ def run(*args): break time.sleep(TEN_MILLISECONDS) - self.ws_client.send(self.build_closing_message(), websocket.ABNF.OPCODE_TEXT) + self.ws_client.send(self.build_closing_message(), + websocket.ABNF.OPCODE_TEXT) thread.start_new_thread(run, ()) @@ -147,7 +153,8 @@ def on_open(self, ws): # Send initialization message init_data = self.build_start_message(self.options) - self.ws_client.send(json.dumps(init_data).encode('utf8'), websocket.ABNF.OPCODE_TEXT) + self.ws_client.send( + json.dumps(init_data).encode('utf8'), websocket.ABNF.OPCODE_TEXT) def on_data(self, ws, message, message_type, fin): """ diff --git a/ibm_watson/websocket/synthesize_callback.py b/ibm_watson/websocket/synthesize_callback.py index e153b66b2..c8ee34c3c 100644 --- a/ibm_watson/websocket/synthesize_callback.py +++ b/ibm_watson/websocket/synthesize_callback.py @@ -16,6 +16,7 @@ class SynthesizeCallback(object): + def __init__(self): pass diff --git a/ibm_watson/websocket/synthesize_listener.py b/ibm_watson/websocket/synthesize_listener.py index fe21fcc1d..9c110daea 100644 --- a/ibm_watson/websocket/synthesize_listener.py +++ b/ibm_watson/websocket/synthesize_listener.py @@ -23,10 +23,11 @@ except ImportError: import _thread as thread - TEN_MILLISECONDS = 0.01 + class SynthesizeListener(object): + def __init__(self, options, callback, @@ -56,13 +57,15 @@ def __init__(self, self.ws_client.run_forever(http_proxy_host=self.http_proxy_host, http_proxy_port=self.http_proxy_port, - sslopt={'cert_reqs': ssl.CERT_NONE} if self.verify is not None else None) + sslopt={'cert_reqs': ssl.CERT_NONE} + if self.verify is not None else None) def send_text(self): """ Sends the text message Note: The service handles one request per connection """ + def run(*args): """Background process to send the text""" self.ws_client.send(json.dumps(self.options).encode('utf8')) @@ -94,7 +97,8 @@ def on_data(self, ws, message, message_type, fin): if message_type == websocket.ABNF.OPCODE_TEXT: json_object = json.loads(message) if 'binary_streams' in json_object: - self.callback.on_content_type(json_object['binary_streams'][0]['content_type']) + self.callback.on_content_type( + json_object['binary_streams'][0]['content_type']) elif 'error' in json_object: self.on_error(ws, json_object.get('error')) return From 595a59837df231b1db786833b54ec0a7453dcdfb Mon Sep 17 00:00:00 2001 From: Dustin Popp Date: Tue, 19 Nov 2019 14:09:14 -0600 Subject: [PATCH 133/455] docs: document correct service method for http configuration (#708) The function `with_http_config` is defined and used in the unit tests in the core but is not a method on the service client. It should not be documented - the correct method is `set_http_config` --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 154ba9c2a..0f148b3d4 100755 --- a/README.md +++ b/README.md @@ -265,7 +265,7 @@ For more information, follow the [MIGRATION-V4](https://github.com/watson-develo To move from v3.x to v4.0, refer to the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md). ## Configuring the http client (Supported from v1.1.0) -To set client configs like timeout use the `with_http_config()` function and pass it a dictionary of configs. For example for a Assistant service instance +To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. For example for a Assistant service instance ```python from ibm_watson import AssistantV1 From fd38d7395daf3d28e8dd085b0a1c8e9d4358a1b5 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 13:13:47 -0800 Subject: [PATCH 134/455] fix(bumpversion): Skip for bumpversion --- .bumpversion.cfg | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index ef2253944..2a60e5e6a 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,6 +1,8 @@ [bumpversion] current_version = 4.0.2 commit = True +message = [skip ci] Bump version: {current_version} -> {new_version} + [bumpversion:file:ibm_watson/version.py] search = __version__ = '{current_version}' From 73df7e4a53ef83ad1271b71215ab357f7a538177 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 13:25:23 -0800 Subject: [PATCH 135/455] feat(discoveryv2): New discovery v2 available on CP4D --- ibm_watson/__init__.py | 1 + ibm_watson/discovery_v2.py | 5603 ++++++++++++++++++++++++++++++++ test/unit/test_discovery_v2.py | 1214 +++++++ 3 files changed, 6818 insertions(+) create mode 100644 ibm_watson/discovery_v2.py create mode 100644 test/unit/test_discovery_v2.py diff --git a/ibm_watson/__init__.py b/ibm_watson/__init__.py index 8b757e30e..4f8afd62c 100755 --- a/ibm_watson/__init__.py +++ b/ibm_watson/__init__.py @@ -24,6 +24,7 @@ from .text_to_speech_v1 import TextToSpeechV1 from .tone_analyzer_v3 import ToneAnalyzerV3 from .discovery_v1 import DiscoveryV1 +from .discovery_v2 import DiscoveryV2 from .compare_comply_v1 import CompareComplyV1 from .visual_recognition_v3 import VisualRecognitionV3 from .version import __version__ diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py new file mode 100644 index 000000000..9f77823c1 --- /dev/null +++ b/ibm_watson/discovery_v2.py @@ -0,0 +1,5603 @@ +# coding: utf-8 + +# (C) Copyright IBM Corp. 2019. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +IBM Watson™ Discovery for IBM Cloud Pak for Data is a cognitive search and content +analytics engine that you can add to applications to identify patterns, trends and +actionable insights to drive better decision-making. Securely unify structured and +unstructured data with pre-enriched content, and use a simplified query language to +eliminate the need for manual filtering of results. +""" + +import json +from .common import get_sdk_headers +from enum import Enum +from ibm_cloud_sdk_core import BaseService +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 import read_external_sources +from os.path import basename + +############################################################################## +# Service +############################################################################## + + +class DiscoveryV2(BaseService): + """The Discovery V2 service.""" + + default_service_url = None + + def __init__( + self, + version, + authenticator=None, + ): + """ + Construct a new client for the Discovery service. + + :param str version: The API version date to use with the service, in + "YYYY-MM-DD" format. Whenever the API is changed in a backwards + incompatible way, a new minor version of the API is released. + The service uses the API version for the date you specify, or + the most recent version before that date. Note that you should + not programmatically specify the current date at runtime, in + case the API has been updated since your application's release. + Instead, specify a version date that is compatible with your + application, and don't change it until your application is + ready for a later version. + + :param Authenticator authenticator: The authenticator specifies the authentication mechanism. + Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + about initializing the authenticator of your choice. + """ + + service_url = self.default_service_url + disable_ssl_verification = False + + config = read_external_sources('discovery') + if config.get('URL'): + service_url = config.get('URL') + if config.get('DISABLE_SSL'): + disable_ssl_verification = config.get('DISABLE_SSL') + + if not authenticator: + authenticator = get_authenticator_from_environment('discovery') + + BaseService.__init__(self, + service_url=service_url, + authenticator=authenticator, + disable_ssl_verification=disable_ssl_verification) + self.version = version + + ######################### + # Collections + ######################### + + def list_collections(self, project_id, **kwargs): + """ + List collections. + + Lists existing collections for the specified project. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', 'list_collections') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/collections'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + ######################### + # Queries + ######################### + + def query(self, + project_id, + *, + collection_ids=None, + filter=None, + query=None, + natural_language_query=None, + aggregation=None, + count=None, + return_=None, + offset=None, + sort=None, + highlight=None, + spelling_suggestions=None, + table_results=None, + suggested_refinements=None, + passages=None, + **kwargs): + """ + Query a project. + + By using this method, you can construct queries. For details, see the [Discovery + documentation](https://cloud.ibm.com/docs/services/discovery-data?topic=discovery-data-query-concepts). + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param list[str] collection_ids: (optional) A comma-separated list of + collection IDs to be queried against. + :param str filter: (optional) A cacheable query that excludes documents + that don't mention the query content. Filter searches are better for + metadata-type searches and for assessing the concepts in the data set. + :param str query: (optional) A query search returns all documents in your + data set with full enrichments and full text, but with the most relevant + documents listed first. Use a query search when you want to find the most + relevant search results. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by utilizing training data and natural language + understanding. + :param str aggregation: (optional) An aggregation search that returns an + exact answer by combining query search with filters. Useful for + applications to build lists, tables, and time series. For a full list of + possible aggregations, see the Query reference. + :param int count: (optional) Number of results to return. + :param list[str] return_: (optional) A list of the fields in the document + hierarchy to return. If this parameter not specified, then all top-level + fields are returned. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. + :param str sort: (optional) A comma-separated list of fields in the + document to sort on. You can optionally specify a sort direction by + prefixing the field with `-` for descending or `+` for ascending. Ascending + is the default sort direction if no prefix is specified. This parameter + cannot be used in the same query as the **bias** parameter. + :param bool highlight: (optional) When `true`, a highlight field is + returned for each result which contains the fields which match the query + with `` tags around the matching query terms. + :param bool spelling_suggestions: (optional) When `true` and the + **natural_language_query** parameter is used, the + **natural_language_query** parameter is spell checked. The most likely + correction is returned in the **suggested_query** field of the response (if + one exists). + :param QueryLargeTableResults table_results: (optional) Configuration for + table retrieval. + :param QueryLargeSuggestedRefinements suggested_refinements: (optional) + Configuration for suggested refinements. + :param QueryLargePassages passages: (optional) Configuration for passage + retrieval. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if table_results is not None: + table_results = self._convert_model(table_results) + if suggested_refinements is not None: + suggested_refinements = self._convert_model(suggested_refinements) + if passages is not None: + passages = self._convert_model(passages) + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', 'query') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'collection_ids': collection_ids, + 'filter': filter, + 'query': query, + 'natural_language_query': natural_language_query, + 'aggregation': aggregation, + 'count': count, + 'return': return_, + 'offset': offset, + 'sort': sort, + 'highlight': highlight, + 'spelling_suggestions': spelling_suggestions, + 'table_results': table_results, + 'suggested_refinements': suggested_refinements, + 'passages': passages + } + + url = '/v2/projects/{0}/query'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) + response = self.send(request) + return response + + def get_autocompletion(self, + project_id, + prefix, + *, + collection_ids=None, + field=None, + count=None, + **kwargs): + """ + Get Autocomplete Suggestions. + + Returns completion query suggestions for the specified prefix. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str prefix: The prefix to use for autocompletion. For example, the + prefix `Ho` could autocomplete to `Hot`, `Housing`, or `How do I upgrade`. + Possible completions are. + :param list[str] collection_ids: (optional) Comma separated list of the + collection IDs. If this parameter is not specified, all collections in the + project are used. + :param str field: (optional) The field in the result documents that + autocompletion suggestions are identified from. + :param int count: (optional) The number of autocompletion suggestions to + return. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if prefix is None: + raise ValueError('prefix must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', 'get_autocompletion') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'prefix': prefix, + 'collection_ids': self._convert_list(collection_ids), + 'field': field, + 'count': count + } + + url = '/v2/projects/{0}/autocompletion'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + def query_notices(self, + project_id, + *, + filter=None, + query=None, + natural_language_query=None, + count=None, + offset=None, + **kwargs): + """ + Query system notices. + + Queries for notices (errors or warnings) that might have been generated by the + system. Notices are generated when ingesting documents and performing relevance + training. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str filter: (optional) A cacheable query that excludes documents + that don't mention the query content. Filter searches are better for + metadata-type searches and for assessing the concepts in the data set. + :param str query: (optional) A query search returns all documents in your + data set with full enrichments and full text, but with the most relevant + documents listed first. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by utilizing training data and natural language + understanding. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is **10000**. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. The maximum for + the **count** and **offset** values together in any one query is **10000**. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', 'query_notices') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'filter': filter, + 'query': query, + 'natural_language_query': natural_language_query, + 'count': count, + 'offset': offset + } + + url = '/v2/projects/{0}/notices'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + def list_fields(self, project_id, *, collection_ids=None, **kwargs): + """ + List fields. + + Gets a list of the unique fields (and their types) stored in the the specified + collections. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param list[str] collection_ids: (optional) Comma separated list of the + collection IDs. If this parameter is not specified, all collections in the + project are used. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', 'list_fields') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'collection_ids': self._convert_list(collection_ids) + } + + url = '/v2/projects/{0}/fields'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + ######################### + # Component settings + ######################### + + def get_component_settings(self, project_id, **kwargs): + """ + Configuration settings for components. + + Returns default configuration settings for components. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', + 'get_component_settings') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/component_settings'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + ######################### + # Documents + ######################### + + def add_document(self, + project_id, + collection_id, + *, + file=None, + filename=None, + file_content_type=None, + metadata=None, + x_watson_discovery_force=None, + **kwargs): + """ + Add a document. + + Add a document to a collection with optional metadata. + Returns immediately after the system has accepted the document for processing. + * The user must provide document content, metadata, or both. If the request is + missing both document content and metadata, it is rejected. + * The user can set the **Content-Type** parameter on the **file** part to + indicate the media type of the document. If the **Content-Type** parameter is + missing or is one of the generic media types (for example, + `application/octet-stream`), then the service attempts to automatically detect the + document's media type. + * The following field names are reserved and will be filtered out if present + after normalization: `id`, `score`, `highlight`, and any field with the prefix of: + `_`, `+`, or `-` + * Fields with empty name values after normalization are filtered out before + indexing. + * Fields containing the following characters after normalization are filtered + out before indexing: `#` and `,` + If the document is uploaded to a collection that has it's data shared with + another collection, the **X-Watson-Discovery-Force** header must be set to `true`. + **Note:** Documents can be added with a specific **document_id** by using the + **_/v2/projects/{project_id}/collections/{collection_id}/documents** method. + **Note:** This operation only works on collections created to accept direct file + uploads. It cannot be used to modify a collection that conects to an external + source such as Microsoft SharePoint. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str collection_id: The ID of the collection. + :param file file: (optional) The content of the document to ingest. The + maximum supported file size when adding a file to a collection is 50 + megabytes, the maximum supported file size when testing a confiruration is + 1 megabyte. Files larger than the supported size are rejected. + :param str filename: (optional) The filename for file. + :param str file_content_type: (optional) The content type of file. + :param str metadata: (optional) The maximum supported metadata file size is + 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { + "Creator": "Johnny Appleseed", + "Subject": "Apples" + } ```. + :param bool x_watson_discovery_force: (optional) When `true`, the uploaded + document is added to the collection even if the data for that collection is + shared with other collections. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + + headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', 'add_document') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + if file: + if not filename and hasattr(file, 'name'): + filename = basename(file.name) + if not filename: + raise ValueError('filename must be provided') + form_data.append(('file', (filename, file, file_content_type or + 'application/octet-stream'))) + if metadata: + form_data.append(('metadata', (None, metadata, 'text/plain'))) + + url = '/v2/projects/{0}/collections/{1}/documents'.format( + *self._encode_path_vars(project_id, collection_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) + response = self.send(request) + return response + + def update_document(self, + project_id, + collection_id, + document_id, + *, + file=None, + filename=None, + file_content_type=None, + metadata=None, + x_watson_discovery_force=None, + **kwargs): + """ + Update a document. + + Replace an existing document or add a document with a specified **document_id**. + Starts ingesting a document with optional metadata. + If the document is uploaded to a collection that has it's data shared with another + collection, the **X-Watson-Discovery-Force** header must be set to `true`. + **Note:** When uploading a new document with this method it automatically replaces + any document stored with the same **document_id** if it exists. + **Note:** This operation only works on collections created to accept direct file + uploads. It cannot be used to modify a collection that conects to an external + source such as Microsoft SharePoint. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str collection_id: The ID of the collection. + :param str document_id: The ID of the document. + :param file file: (optional) The content of the document to ingest. The + maximum supported file size when adding a file to a collection is 50 + megabytes, the maximum supported file size when testing a confiruration is + 1 megabyte. Files larger than the supported size are rejected. + :param str filename: (optional) The filename for file. + :param str file_content_type: (optional) The content type of file. + :param str metadata: (optional) The maximum supported metadata file size is + 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { + "Creator": "Johnny Appleseed", + "Subject": "Apples" + } ```. + :param bool x_watson_discovery_force: (optional) When `true`, the uploaded + document is added to the collection even if the data for that collection is + shared with other collections. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + if document_id is None: + raise ValueError('document_id must be provided') + + headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', 'update_document') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + if file: + if not filename and hasattr(file, 'name'): + filename = basename(file.name) + if not filename: + raise ValueError('filename must be provided') + form_data.append(('file', (filename, file, file_content_type or + 'application/octet-stream'))) + if metadata: + form_data.append(('metadata', (None, metadata, 'text/plain'))) + + url = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( + *self._encode_path_vars(project_id, collection_id, document_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + accept_json=True) + response = self.send(request) + return response + + def delete_document(self, + project_id, + collection_id, + document_id, + *, + x_watson_discovery_force=None, + **kwargs): + """ + Delete a document. + + If the given document ID is invalid, or if the document is not found, then the a + success response is returned (HTTP status code `200`) with the status set to + 'deleted'. + **Note:** This operation only works on collections created to accept direct file + uploads. It cannot be used to modify a collection that conects to an external + source such as Microsoft SharePoint. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str collection_id: The ID of the collection. + :param str document_id: The ID of the document. + :param bool x_watson_discovery_force: (optional) When `true`, the uploaded + document is added to the collection even if the data for that collection is + shared with other collections. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + if document_id is None: + raise ValueError('document_id must be provided') + + headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', 'delete_document') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( + *self._encode_path_vars(project_id, collection_id, document_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + ######################### + # Training data + ######################### + + def list_training_queries(self, project_id, **kwargs): + """ + List training queries. + + List the training queries for the specified project. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', + 'list_training_queries') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/training_data/queries'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + def delete_training_queries(self, project_id, **kwargs): + """ + Delete training queries. + + Removes all training queries for the specified project. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', + 'delete_training_queries') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/training_data/queries'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params, + accept_json=False) + response = self.send(request) + return response + + def create_training_query(self, + project_id, + *, + natural_language_query=None, + filter=None, + examples=None, + **kwargs): + """ + Create training query. + + Add a query to the training data for this project. The query can contain a filter + and natural language query. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str natural_language_query: (optional) The natural text query for + the training query. + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. + :param list[TrainingExample] examples: (optional) Array of training + examples. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if examples is not None: + examples = [self._convert_model(x) for x in examples] + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', + 'create_training_query') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'natural_language_query': natural_language_query, + 'filter': filter, + 'examples': examples + } + + url = '/v2/projects/{0}/training_data/queries'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) + response = self.send(request) + return response + + def get_training_query(self, project_id, query_id, **kwargs): + """ + Get a training data query. + + Get details for a specific training data query, including the query string and all + examples. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str query_id: The ID of the query used for training. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if query_id is None: + raise ValueError('query_id must be provided') + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', 'get_training_query') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/training_data/queries/{1}'.format( + *self._encode_path_vars(project_id, query_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + + def update_training_query(self, + project_id, + query_id, + *, + natural_language_query=None, + filter=None, + examples=None, + **kwargs): + """ + Update a training query. + + Updates an existing training query and it's examples. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str query_id: The ID of the query used for training. + :param str natural_language_query: (optional) The natural text query for + the training query. + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. + :param list[TrainingExample] examples: (optional) Array of training + examples. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if query_id is None: + raise ValueError('query_id must be provided') + if examples is not None: + examples = [self._convert_model(x) for x in examples] + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('discovery', 'V2', + 'update_training_query') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'natural_language_query': natural_language_query, + 'filter': filter, + 'examples': examples + } + + url = '/v2/projects/{0}/training_data/queries/{1}'.format( + *self._encode_path_vars(project_id, query_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data, + accept_json=True) + response = self.send(request) + return response + + +class AddDocumentEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +class UpdateDocumentEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +############################################################################## +# Models +############################################################################## + + +class Collection(): + """ + A collection for storing documents. + + :attr str collection_id: (optional) The unique identifier of the collection. + :attr str name: (optional) The name of the collection. + """ + + def __init__(self, *, collection_id=None, name=None): + """ + Initialize a Collection object. + + :param str collection_id: (optional) The unique identifier of the + collection. + :param str name: (optional) The name of the collection. + """ + self.collection_id = collection_id + self.name = name + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection object from a json dictionary.""" + args = {} + valid_keys = ['collection_id', 'name'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Collection: ' + + ', '.join(bad_keys)) + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + return _dict + + def __str__(self): + """Return a `str` version of this Collection object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Completions(): + """ + An object containing an array of autocompletion suggestions. + + :attr list[str] completions: (optional) Array of autcomplete suggestion based on + the provided prefix. + """ + + def __init__(self, *, completions=None): + """ + Initialize a Completions object. + + :param list[str] completions: (optional) Array of autcomplete suggestion + based on the provided prefix. + """ + self.completions = completions + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Completions object from a json dictionary.""" + args = {} + valid_keys = ['completions'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Completions: ' + + ', '.join(bad_keys)) + if 'completions' in _dict: + args['completions'] = _dict.get('completions') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'completions') and self.completions is not None: + _dict['completions'] = self.completions + return _dict + + def __str__(self): + """Return a `str` version of this Completions object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsAggregation(): + """ + Display settings for aggregations. + + :attr str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :attr str label: (optional) User-friendly alias for the aggregation. + :attr bool multiple_selections_allowed: (optional) Whether users is allowed to + select more than one of the aggregation terms. + :attr str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + + def __init__(self, + *, + name=None, + label=None, + multiple_selections_allowed=None, + visualization_type=None): + """ + Initialize a ComponentSettingsAggregation object. + + :param str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :param str label: (optional) User-friendly alias for the aggregation. + :param bool multiple_selections_allowed: (optional) Whether users is + allowed to select more than one of the aggregation terms. + :param str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + self.name = name + self.label = label + self.multiple_selections_allowed = multiple_selections_allowed + self.visualization_type = visualization_type + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + args = {} + valid_keys = [ + 'name', 'label', 'multiple_selections_allowed', 'visualization_type' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsAggregation: ' + + ', '.join(bad_keys)) + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'label' in _dict: + args['label'] = _dict.get('label') + if 'multiple_selections_allowed' in _dict: + args['multiple_selections_allowed'] = _dict.get( + 'multiple_selections_allowed') + if 'visualization_type' in _dict: + args['visualization_type'] = _dict.get('visualization_type') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'multiple_selections_allowed' + ) and self.multiple_selections_allowed is not None: + _dict[ + 'multiple_selections_allowed'] = self.multiple_selections_allowed + if hasattr( + self, + 'visualization_type') and self.visualization_type is not None: + _dict['visualization_type'] = self.visualization_type + return _dict + + def __str__(self): + """Return a `str` version of this ComponentSettingsAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class VisualizationTypeEnum(Enum): + """ + Type of visualization to use when rendering the aggregation. + """ + AUTO = "auto" + FACET_TABLE = "facet_table" + WORD_CLOUD = "word_cloud" + MAP = "map" + + +class ComponentSettingsFieldsShown(): + """ + Fields shown in the results section of the UI. + + :attr ComponentSettingsFieldsShownBody body: (optional) Body label. + :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + """ + + def __init__(self, *, body=None, title=None): + """ + Initialize a ComponentSettingsFieldsShown object. + + :param ComponentSettingsFieldsShownBody body: (optional) Body label. + :param ComponentSettingsFieldsShownTitle title: (optional) Title label. + """ + self.body = body + self.title = title + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + args = {} + valid_keys = ['body', 'title'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShown: ' + + ', '.join(bad_keys)) + if 'body' in _dict: + args['body'] = ComponentSettingsFieldsShownBody._from_dict( + _dict.get('body')) + if 'title' in _dict: + args['title'] = ComponentSettingsFieldsShownTitle._from_dict( + _dict.get('title')) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body._to_dict() + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this ComponentSettingsFieldsShown object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsFieldsShownBody(): + """ + Body label. + + :attr bool use_passage: (optional) Use the whole passage as the body. + :attr str field: (optional) Use a specific field as the title. + """ + + def __init__(self, *, use_passage=None, field=None): + """ + Initialize a ComponentSettingsFieldsShownBody object. + + :param bool use_passage: (optional) Use the whole passage as the body. + :param str field: (optional) Use a specific field as the title. + """ + self.use_passage = use_passage + self.field = field + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + args = {} + valid_keys = ['use_passage', 'field'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownBody: ' + + ', '.join(bad_keys)) + if 'use_passage' in _dict: + args['use_passage'] = _dict.get('use_passage') + if 'field' in _dict: + args['field'] = _dict.get('field') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'use_passage') and self.use_passage is not None: + _dict['use_passage'] = self.use_passage + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + return _dict + + def __str__(self): + """Return a `str` version of this ComponentSettingsFieldsShownBody object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsFieldsShownTitle(): + """ + Title label. + + :attr str field: (optional) Use a specific field as the title. + """ + + def __init__(self, *, field=None): + """ + Initialize a ComponentSettingsFieldsShownTitle object. + + :param str field: (optional) Use a specific field as the title. + """ + self.field = field + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + args = {} + valid_keys = ['field'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownTitle: ' + + ', '.join(bad_keys)) + if 'field' in _dict: + args['field'] = _dict.get('field') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + return _dict + + def __str__(self): + """Return a `str` version of this ComponentSettingsFieldsShownTitle object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsResponse(): + """ + A response containing the default component settings. + + :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the + results section of the UI. + :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. + :attr bool structured_search: (optional) Whether or not structured search is + enabled. + :attr int results_per_page: (optional) Number or results shown per page. + :attr list[ComponentSettingsAggregation] aggregations: (optional) a list of + component setting aggregations. + """ + + def __init__(self, + *, + fields_shown=None, + autocomplete=None, + structured_search=None, + results_per_page=None, + aggregations=None): + """ + Initialize a ComponentSettingsResponse object. + + :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown + in the results section of the UI. + :param bool autocomplete: (optional) Whether or not autocomplete is + enabled. + :param bool structured_search: (optional) Whether or not structured search + is enabled. + :param int results_per_page: (optional) Number or results shown per page. + :param list[ComponentSettingsAggregation] aggregations: (optional) a list + of component setting aggregations. + """ + self.fields_shown = fields_shown + self.autocomplete = autocomplete + self.structured_search = structured_search + self.results_per_page = results_per_page + self.aggregations = aggregations + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsResponse object from a json dictionary.""" + args = {} + valid_keys = [ + 'fields_shown', 'autocomplete', 'structured_search', + 'results_per_page', 'aggregations' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsResponse: ' + + ', '.join(bad_keys)) + if 'fields_shown' in _dict: + args['fields_shown'] = ComponentSettingsFieldsShown._from_dict( + _dict.get('fields_shown')) + if 'autocomplete' in _dict: + args['autocomplete'] = _dict.get('autocomplete') + if 'structured_search' in _dict: + args['structured_search'] = _dict.get('structured_search') + if 'results_per_page' in _dict: + args['results_per_page'] = _dict.get('results_per_page') + if 'aggregations' in _dict: + args['aggregations'] = [ + ComponentSettingsAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'fields_shown') and self.fields_shown is not None: + _dict['fields_shown'] = self.fields_shown._to_dict() + if hasattr(self, 'autocomplete') and self.autocomplete is not None: + _dict['autocomplete'] = self.autocomplete + if hasattr(self, + 'structured_search') and self.structured_search is not None: + _dict['structured_search'] = self.structured_search + if hasattr(self, + 'results_per_page') and self.results_per_page is not None: + _dict['results_per_page'] = self.results_per_page + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + return _dict + + def __str__(self): + """Return a `str` version of this ComponentSettingsResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DeleteDocumentResponse(): + """ + Information returned when a document is deleted. + + :attr str document_id: (optional) The unique identifier of the document. + :attr str status: (optional) Status of the document. A deleted document has the + status deleted. + """ + + def __init__(self, *, document_id=None, status=None): + """ + Initialize a DeleteDocumentResponse object. + + :param str document_id: (optional) The unique identifier of the document. + :param str status: (optional) Status of the document. A deleted document + has the status deleted. + """ + self.document_id = document_id + self.status = status + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteDocumentResponse object from a json dictionary.""" + args = {} + valid_keys = ['document_id', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DeleteDocumentResponse: ' + + ', '.join(bad_keys)) + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + return _dict + + def __str__(self): + """Return a `str` version of this DeleteDocumentResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(Enum): + """ + Status of the document. A deleted document has the status deleted. + """ + DELETED = "deleted" + + +class DocumentAccepted(): + """ + Information returned after an uploaded document is accepted. + + :attr str document_id: (optional) The unique identifier of the ingested + document. + :attr str status: (optional) Status of the document in the ingestion process. A + status of `processing` is returned for documents that are ingested with a + *version* date before `2019-01-01`. The `pending` status is returned for all + others. + """ + + def __init__(self, *, document_id=None, status=None): + """ + Initialize a DocumentAccepted object. + + :param str document_id: (optional) The unique identifier of the ingested + document. + :param str status: (optional) Status of the document in the ingestion + process. A status of `processing` is returned for documents that are + ingested with a *version* date before `2019-01-01`. The `pending` status is + returned for all others. + """ + self.document_id = document_id + self.status = status + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAccepted object from a json dictionary.""" + args = {} + valid_keys = ['document_id', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DocumentAccepted: ' + + ', '.join(bad_keys)) + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + return _dict + + def __str__(self): + """Return a `str` version of this DocumentAccepted object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(Enum): + """ + Status of the document in the ingestion process. A status of `processing` is + returned for documents that are ingested with a *version* date before + `2019-01-01`. The `pending` status is returned for all others. + """ + PROCESSING = "processing" + PENDING = "pending" + + +class DocumentAttribute(): + """ + List of document attributes. + + :attr str type: (optional) The type of attribute. + :attr str text: (optional) The text associated with the attribute. + :attr TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + """ + + def __init__(self, *, type=None, text=None, location=None): + """ + Initialize a DocumentAttribute object. + + :param str type: (optional) The type of attribute. + :param str text: (optional) The text associated with the attribute. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. + """ + self.type = type + self.text = text + self.location = location + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAttribute object from a json dictionary.""" + args = {} + valid_keys = ['type', 'text', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DocumentAttribute: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'location' in _dict: + args['location'] = TableElementLocation._from_dict( + _dict.get('location')) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this DocumentAttribute object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Field(): + """ + Object containing field details. + + :attr str field: (optional) The name of the field. + :attr str type: (optional) The type of the field. + :attr str collection_id: (optional) The collection Id of the collection where + the field was found. + """ + + def __init__(self, *, field=None, type=None, collection_id=None): + """ + Initialize a Field object. + + :param str field: (optional) The name of the field. + :param str type: (optional) The type of the field. + :param str collection_id: (optional) The collection Id of the collection + where the field was found. + """ + self.field = field + self.type = type + self.collection_id = collection_id + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Field object from a json dictionary.""" + args = {} + valid_keys = ['field', 'type', 'collection_id'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Field: ' + + ', '.join(bad_keys)) + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + return _dict + + def __str__(self): + """Return a `str` version of this Field object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(Enum): + """ + The type of the field. + """ + NESTED = "nested" + STRING = "string" + DATE = "date" + LONG = "long" + INTEGER = "integer" + SHORT = "short" + BYTE = "byte" + DOUBLE = "double" + FLOAT = "float" + BOOLEAN = "boolean" + BINARY = "binary" + + +class ListCollectionsResponse(): + """ + Response object containing an array of collection details. + + :attr list[Collection] collections: (optional) An array containing information + about each collection in the project. + """ + + def __init__(self, *, collections=None): + """ + Initialize a ListCollectionsResponse object. + + :param list[Collection] collections: (optional) An array containing + information about each collection in the project. + """ + self.collections = collections + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListCollectionsResponse object from a json dictionary.""" + args = {} + valid_keys = ['collections'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ListCollectionsResponse: ' + + ', '.join(bad_keys)) + if 'collections' in _dict: + args['collections'] = [ + Collection._from_dict(x) for x in (_dict.get('collections')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'collections') and self.collections is not None: + _dict['collections'] = [x._to_dict() for x in self.collections] + return _dict + + def __str__(self): + """Return a `str` version of this ListCollectionsResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ListFieldsResponse(): + """ + The list of fetched fields. + The fields are returned using a fully qualified name format, however, the format + differs slightly from that used by the query operations. + * Fields which contain nested objects are assigned a type of "nested". + * Fields which belong to a nested object are prefixed with `.properties` (for + example, `warnings.properties.severity` means that the `warnings` object has a + property called `severity`). + + :attr list[Field] fields: (optional) An array containing information about each + field in the collections. + """ + + def __init__(self, *, fields=None): + """ + Initialize a ListFieldsResponse object. + + :param list[Field] fields: (optional) An array containing information about + each field in the collections. + """ + self.fields = fields + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListFieldsResponse object from a json dictionary.""" + args = {} + valid_keys = ['fields'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ListFieldsResponse: ' + + ', '.join(bad_keys)) + if 'fields' in _dict: + args['fields'] = [ + Field._from_dict(x) for x in (_dict.get('fields')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = [x._to_dict() for x in self.fields] + return _dict + + def __str__(self): + """Return a `str` version of this ListFieldsResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Notice(): + """ + A notice produced for the collection. + + :attr str notice_id: (optional) Identifies the notice. Many notices might have + the same ID. This field exists so that user applications can programmatically + identify a notice and take automatic corrective action. Typical notice IDs + include: `index_failed`, `index_failed_too_many_requests`, + `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, + `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, + `missing_model`, `unsupported_model`, + `smart_document_understanding_failed_incompatible_field`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_warning`, + `smart_document_understanding_page_error`, + `smart_document_understanding_page_warning`. **Note:** This is not a complete + list, other values might be returned. + :attr datetime created: (optional) The creation date of the collection in the + format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :attr str document_id: (optional) Unique identifier of the document. + :attr str collection_id: (optional) Unique identifier of the collection. + :attr str query_id: (optional) Unique identifier of the query used for relevance + training. + :attr str severity: (optional) Severity level of the notice. + :attr str step: (optional) Ingestion or training step in which the notice + occurred. + :attr str description: (optional) The description of the notice. + """ + + def __init__(self, + *, + notice_id=None, + created=None, + document_id=None, + collection_id=None, + query_id=None, + severity=None, + step=None, + description=None): + """ + Initialize a Notice object. + + :param str notice_id: (optional) Identifies the notice. Many notices might + have the same ID. This field exists so that user applications can + programmatically identify a notice and take automatic corrective action. + Typical notice IDs include: `index_failed`, + `index_failed_too_many_requests`, `index_failed_incompatible_field`, + `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, + `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, + `smart_document_understanding_failed_incompatible_field`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_warning`, + `smart_document_understanding_page_error`, + `smart_document_understanding_page_warning`. **Note:** This is not a + complete list, other values might be returned. + :param datetime created: (optional) The creation date of the collection in + the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :param str document_id: (optional) Unique identifier of the document. + :param str collection_id: (optional) Unique identifier of the collection. + :param str query_id: (optional) Unique identifier of the query used for + relevance training. + :param str severity: (optional) Severity level of the notice. + :param str step: (optional) Ingestion or training step in which the notice + occurred. + :param str description: (optional) The description of the notice. + """ + self.notice_id = notice_id + self.created = created + self.document_id = document_id + self.collection_id = collection_id + self.query_id = query_id + self.severity = severity + self.step = step + self.description = description + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Notice object from a json dictionary.""" + args = {} + valid_keys = [ + 'notice_id', 'created', 'document_id', 'collection_id', 'query_id', + 'severity', 'step', 'description' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Notice: ' + + ', '.join(bad_keys)) + if 'notice_id' in _dict: + args['notice_id'] = _dict.get('notice_id') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'query_id' in _dict: + args['query_id'] = _dict.get('query_id') + if 'severity' in _dict: + args['severity'] = _dict.get('severity') + if 'step' in _dict: + args['step'] = _dict.get('step') + if 'description' in _dict: + args['description'] = _dict.get('description') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'notice_id') and self.notice_id is not None: + _dict['notice_id'] = self.notice_id + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'query_id') and self.query_id is not None: + _dict['query_id'] = self.query_id + if hasattr(self, 'severity') and self.severity is not None: + _dict['severity'] = self.severity + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + return _dict + + def __str__(self): + """Return a `str` version of this Notice object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class SeverityEnum(Enum): + """ + Severity level of the notice. + """ + WARNING = "warning" + ERROR = "error" + + +class QueryAggregation(): + """ + An abstract aggregation type produced by Discovery to analyze the input provided. + + :attr str type: The type of aggregation command used. Options include: term, + histogram, timeslice, nested, filter, min, max, sum, average, unique_count, and + top_hits. + """ + + def __init__(self, type): + """ + Initialize a QueryAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + """ + self.type = type + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregation 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 QueryAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryAggregation JSON' + ) + return cls(**args) + + def _to_dict(self): + """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 __str__(self): + """Return a `str` version of this QueryAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryCalculationAggregation(): + """ + Returns a scalar calculation across all documents for the field specified. Possible + calculations include min, max, sum, average, and unique_count. + + :attr str field: The field to perform the calculation on. + :attr float value: (optional) The value of the calculation. + """ + + def __init__(self, type, field, *, value=None): + """ + Initialize a QueryCalculationAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str field: The field to perform the calculation on. + :param float value: (optional) The value of the calculation. + """ + self.field = field + self.value = value + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryCalculationAggregation object from a json dictionary.""" + args = {} + valid_keys = ['field', 'value'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryCalculationAggregation: ' + + ', '.join(bad_keys)) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryCalculationAggregation JSON' + ) + if 'value' in _dict: + args['value'] = _dict.get('value') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + return _dict + + def __str__(self): + """Return a `str` version of this QueryCalculationAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryFilterAggregation(): + """ + A modifier that will narrow down the document set of the sub aggregations it precedes. + + :attr str match: The filter written in Discovery Query Language syntax applied + to the documents before sub aggregations are run. + :attr int matching_results: Number of documents matching the filter. + :attr list[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + + def __init__(self, type, match, matching_results, *, aggregations=None): + """ + Initialize a QueryFilterAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str match: The filter written in Discovery Query Language syntax + applied to the documents before sub aggregations are run. + :param int matching_results: Number of documents matching the filter. + :param list[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + self.match = match + self.matching_results = matching_results + self.aggregations = aggregations + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryFilterAggregation object from a json dictionary.""" + args = {} + valid_keys = ['match', 'matching_results', 'aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryFilterAggregation: ' + + ', '.join(bad_keys)) + if 'match' in _dict: + args['match'] = _dict.get('match') + else: + raise ValueError( + 'Required property \'match\' not present in QueryFilterAggregation JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'match') and self.match is not None: + _dict['match'] = self.match + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + return _dict + + def __str__(self): + """Return a `str` version of this QueryFilterAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryHistogramAggregation(): + """ + Numeric interval segments to categorize documents by using field values from a single + numeric field to describe the category. + + :attr str field: The numeric field name used to create the histogram. + :attr int interval: The size of the sections the results are split into. + :attr list[QueryHistogramAggregationResult] results: (optional) Array of numeric + intervals. + """ + + def __init__(self, type, field, interval, *, results=None): + """ + Initialize a QueryHistogramAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str field: The numeric field name used to create the histogram. + :param int interval: The size of the sections the results are split into. + :param list[QueryHistogramAggregationResult] results: (optional) Array of + numeric intervals. + """ + self.field = field + self.interval = interval + self.results = results + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryHistogramAggregation object from a json dictionary.""" + args = {} + valid_keys = ['field', 'interval', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryHistogramAggregation: ' + + ', '.join(bad_keys)) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryHistogramAggregation JSON' + ) + if 'interval' in _dict: + args['interval'] = _dict.get('interval') + else: + raise ValueError( + 'Required property \'interval\' not present in QueryHistogramAggregation JSON' + ) + if 'results' in _dict: + args['results'] = [ + QueryHistogramAggregationResult._from_dict(x) + for x in (_dict.get('results')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'interval') and self.interval is not None: + _dict['interval'] = self.interval + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + return _dict + + def __str__(self): + """Return a `str` version of this QueryHistogramAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryHistogramAggregationResult(): + """ + Histogram numeric interval result. + + :attr int key: The value of the upper bound for the numeric segment. + :attr int matching_results: Number of documents with the specified key as the + upper bound. + :attr list[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + + def __init__(self, key, matching_results, *, aggregations=None): + """ + Initialize a QueryHistogramAggregationResult object. + + :param int key: The value of the upper bound for the numeric segment. + :param int matching_results: Number of documents with the specified key as + the upper bound. + :param list[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + self.key = key + self.matching_results = matching_results + self.aggregations = aggregations + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" + args = {} + valid_keys = ['key', 'matching_results', 'aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryHistogramAggregationResult: ' + + ', '.join(bad_keys)) + if 'key' in _dict: + args['key'] = _dict.get('key') + else: + raise ValueError( + 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'key') and self.key is not None: + _dict['key'] = self.key + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + return _dict + + def __str__(self): + """Return a `str` version of this QueryHistogramAggregationResult object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryLargePassages(): + """ + Configuration for passage retrieval. + + :attr bool enabled: (optional) A passages query that returns the most relevant + passages from the results. + :attr bool per_document: (optional) When `true`, passages will be returned + whithin their respective result. + :attr int max_per_document: (optional) Maximum number of passages to return per + result. + :attr list[str] fields: (optional) A list of fields that passages are drawn + from. If this parameter not specified, then all top-level fields are included. + :attr int count: (optional) The maximum number of passages to return. The search + returns fewer passages if the requested total is not found. The default is `10`. + The maximum is `100`. + :attr int characters: (optional) The approximate number of characters that any + one passage will have. + """ + + def __init__(self, + *, + enabled=None, + per_document=None, + max_per_document=None, + fields=None, + count=None, + characters=None): + """ + Initialize a QueryLargePassages object. + + :param bool enabled: (optional) A passages query that returns the most + relevant passages from the results. + :param bool per_document: (optional) When `true`, passages will be returned + whithin their respective result. + :param int max_per_document: (optional) Maximum number of passages to + return per result. + :param list[str] fields: (optional) A list of fields that passages are + drawn from. If this parameter not specified, then all top-level fields are + included. + :param int count: (optional) The maximum number of passages to return. The + search returns fewer passages if the requested total is not found. The + default is `10`. The maximum is `100`. + :param int characters: (optional) The approximate number of characters that + any one passage will have. + """ + self.enabled = enabled + self.per_document = per_document + self.max_per_document = max_per_document + self.fields = fields + self.count = count + self.characters = characters + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargePassages object from a json dictionary.""" + args = {} + valid_keys = [ + 'enabled', 'per_document', 'max_per_document', 'fields', 'count', + 'characters' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryLargePassages: ' + + ', '.join(bad_keys)) + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'per_document' in _dict: + args['per_document'] = _dict.get('per_document') + if 'max_per_document' in _dict: + args['max_per_document'] = _dict.get('max_per_document') + if 'fields' in _dict: + args['fields'] = _dict.get('fields') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'characters' in _dict: + args['characters'] = _dict.get('characters') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document + if hasattr(self, + 'max_per_document') and self.max_per_document is not None: + _dict['max_per_document'] = self.max_per_document + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'characters') and self.characters is not None: + _dict['characters'] = self.characters + return _dict + + def __str__(self): + """Return a `str` version of this QueryLargePassages object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryLargeSuggestedRefinements(): + """ + Configuration for suggested refinements. + + :attr bool enabled: (optional) Whether to perform suggested refinements. + :attr int count: (optional) Maximum number of suggested refinements texts to be + returned. The default is `10`. The maximum is `100`. + """ + + def __init__(self, *, enabled=None, count=None): + """ + Initialize a QueryLargeSuggestedRefinements object. + + :param bool enabled: (optional) Whether to perform suggested refinements. + :param int count: (optional) Maximum number of suggested refinements texts + to be returned. The default is `10`. The maximum is `100`. + """ + self.enabled = enabled + self.count = count + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargeSuggestedRefinements object from a json dictionary.""" + args = {} + valid_keys = ['enabled', 'count'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryLargeSuggestedRefinements: ' + + ', '.join(bad_keys)) + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + return _dict + + def __str__(self): + """Return a `str` version of this QueryLargeSuggestedRefinements object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryLargeTableResults(): + """ + Configuration for table retrieval. + + :attr bool enabled: (optional) Whether to enable table retrieval. + :attr int count: (optional) Maximum number of tables to return. + """ + + def __init__(self, *, enabled=None, count=None): + """ + Initialize a QueryLargeTableResults object. + + :param bool enabled: (optional) Whether to enable table retrieval. + :param int count: (optional) Maximum number of tables to return. + """ + self.enabled = enabled + self.count = count + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargeTableResults object from a json dictionary.""" + args = {} + valid_keys = ['enabled', 'count'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryLargeTableResults: ' + + ', '.join(bad_keys)) + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + return _dict + + def __str__(self): + """Return a `str` version of this QueryLargeTableResults object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryNestedAggregation(): + """ + A restriction that alter the document set used for sub aggregations it precedes to + nested documents found in the field specified. + + :attr str path: The path to the document field to scope sub aggregations to. + :attr int matching_results: Number of nested documents found in the specified + field. + :attr list[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + + def __init__(self, type, path, matching_results, *, aggregations=None): + """ + Initialize a QueryNestedAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str path: The path to the document field to scope sub aggregations + to. + :param int matching_results: Number of nested documents found in the + specified field. + :param list[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + self.path = path + self.matching_results = matching_results + self.aggregations = aggregations + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryNestedAggregation object from a json dictionary.""" + args = {} + valid_keys = ['path', 'matching_results', 'aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryNestedAggregation: ' + + ', '.join(bad_keys)) + if 'path' in _dict: + args['path'] = _dict.get('path') + else: + raise ValueError( + 'Required property \'path\' not present in QueryNestedAggregation JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + return _dict + + def __str__(self): + """Return a `str` version of this QueryNestedAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryNoticesResponse(): + """ + Object containing notice query results. + + :attr int matching_results: (optional) The number of matching results. + :attr list[Notice] notices: (optional) Array of document results that match the + query. + """ + + def __init__(self, *, matching_results=None, notices=None): + """ + Initialize a QueryNoticesResponse object. + + :param int matching_results: (optional) The number of matching results. + :param list[Notice] notices: (optional) Array of document results that + match the query. + """ + self.matching_results = matching_results + self.notices = notices + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryNoticesResponse object from a json dictionary.""" + args = {} + valid_keys = ['matching_results', 'notices'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryNoticesResponse: ' + + ', '.join(bad_keys)) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'notices' in _dict: + args['notices'] = [ + Notice._from_dict(x) for x in (_dict.get('notices')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'notices') and self.notices is not None: + _dict['notices'] = [x._to_dict() for x in self.notices] + return _dict + + def __str__(self): + """Return a `str` version of this QueryNoticesResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryResponse(): + """ + A response containing the documents and aggregations for the query. + + :attr int matching_results: (optional) The number of matching results for the + query. + :attr list[QueryResult] results: (optional) Array of document results for the + query. + :attr list[QueryAggregation] aggregations: (optional) Array of aggregations for + the query. + :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval + type information. + :attr str suggested_query: (optional) Suggested correction to the submitted + **natural_language_query** value. + :attr list[QuerySuggestedRefinement] suggested_refinements: (optional) Array of + suggested refinments. + :attr list[QueryTableResult] table_results: (optional) Array of table results. + """ + + def __init__(self, + *, + matching_results=None, + results=None, + aggregations=None, + retrieval_details=None, + suggested_query=None, + suggested_refinements=None, + table_results=None): + """ + Initialize a QueryResponse object. + + :param int matching_results: (optional) The number of matching results for + the query. + :param list[QueryResult] results: (optional) Array of document results for + the query. + :param list[QueryAggregation] aggregations: (optional) Array of + aggregations for the query. + :param RetrievalDetails retrieval_details: (optional) An object contain + retrieval type information. + :param str suggested_query: (optional) Suggested correction to the + submitted **natural_language_query** value. + :param list[QuerySuggestedRefinement] suggested_refinements: (optional) + Array of suggested refinments. + :param list[QueryTableResult] table_results: (optional) Array of table + results. + """ + self.matching_results = matching_results + self.results = results + self.aggregations = aggregations + self.retrieval_details = retrieval_details + self.suggested_query = suggested_query + self.suggested_refinements = suggested_refinements + self.table_results = table_results + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResponse object from a json dictionary.""" + args = {} + valid_keys = [ + 'matching_results', 'results', 'aggregations', 'retrieval_details', + 'suggested_query', 'suggested_refinements', 'table_results' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryResponse: ' + + ', '.join(bad_keys)) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'results' in _dict: + args['results'] = [ + QueryResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'retrieval_details' in _dict: + args['retrieval_details'] = RetrievalDetails._from_dict( + _dict.get('retrieval_details')) + if 'suggested_query' in _dict: + args['suggested_query'] = _dict.get('suggested_query') + if 'suggested_refinements' in _dict: + args['suggested_refinements'] = [ + QuerySuggestedRefinement._from_dict(x) + for x in (_dict.get('suggested_refinements')) + ] + if 'table_results' in _dict: + args['table_results'] = [ + QueryTableResult._from_dict(x) + for x in (_dict.get('table_results')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, + 'retrieval_details') and self.retrieval_details is not None: + _dict['retrieval_details'] = self.retrieval_details._to_dict() + if hasattr(self, + 'suggested_query') and self.suggested_query is not None: + _dict['suggested_query'] = self.suggested_query + if hasattr(self, 'suggested_refinements' + ) and self.suggested_refinements is not None: + _dict['suggested_refinements'] = [ + x._to_dict() for x in self.suggested_refinements + ] + if hasattr(self, 'table_results') and self.table_results is not None: + _dict['table_results'] = [x._to_dict() for x in self.table_results] + return _dict + + def __str__(self): + """Return a `str` version of this QueryResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryResult(): + """ + Result document for the specified query. + + :attr str document_id: The unique identifier of the document. + :attr dict metadata: (optional) Metadata of the document. + :attr QueryResultMetadata result_metadata: Metadata of a query result. + :attr list[QueryResultPassage] document_passages: (optional) Passages returned + by Discovery. + """ + + def __init__(self, + document_id, + result_metadata, + *, + metadata=None, + document_passages=None, + **kwargs): + """ + Initialize a QueryResult object. + + :param str document_id: The unique identifier of the document. + :param QueryResultMetadata result_metadata: Metadata of a query result. + :param dict metadata: (optional) Metadata of the document. + :param list[QueryResultPassage] document_passages: (optional) Passages + returned by Discovery. + :param **kwargs: (optional) Any additional properties. + """ + self.document_id = document_id + self.metadata = metadata + self.result_metadata = result_metadata + self.document_passages = document_passages + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResult object from a json dictionary.""" + args = {} + xtra = _dict.copy() + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + del xtra['document_id'] + else: + raise ValueError( + 'Required property \'document_id\' not present in QueryResult JSON' + ) + if 'metadata' in _dict: + args['metadata'] = _dict.get('metadata') + del xtra['metadata'] + if 'result_metadata' in _dict: + args['result_metadata'] = QueryResultMetadata._from_dict( + _dict.get('result_metadata')) + del xtra['result_metadata'] + else: + raise ValueError( + 'Required property \'result_metadata\' not present in QueryResult JSON' + ) + if 'document_passages' in _dict: + args['document_passages'] = [ + QueryResultPassage._from_dict(x) + for x in (_dict.get('document_passages')) + ] + del xtra['document_passages'] + args.update(xtra) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + if hasattr(self, + 'result_metadata') and self.result_metadata is not None: + _dict['result_metadata'] = self.result_metadata._to_dict() + if hasattr(self, + 'document_passages') and self.document_passages is not None: + _dict['document_passages'] = [ + x._to_dict() for x in self.document_passages + ] + if hasattr(self, '_additionalProperties'): + for _key in self._additionalProperties: + _value = getattr(self, _key, None) + if _value is not None: + _dict[_key] = _value + return _dict + + def __setattr__(self, name, value): + properties = { + 'document_id', 'metadata', 'result_metadata', 'document_passages' + } + if not hasattr(self, '_additionalProperties'): + super(QueryResult, self).__setattr__('_additionalProperties', set()) + if name not in properties: + self._additionalProperties.add(name) + super(QueryResult, self).__setattr__(name, value) + + def __str__(self): + """Return a `str` version of this QueryResult object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryResultMetadata(): + """ + Metadata of a query result. + + :attr str document_retrieval_source: (optional) The document retrieval source + that produced this search result. + :attr str collection_id: The collection id associated with this training data + set. + :attr float confidence: (optional) The confidence score for the given result. + Calculated based on how relevant the result is estimated to be. confidence can + range from `0.0` to `1.0`. The higher the number, the more relevant the + document. The `confidence` value for a result was calculated using the model + specified in the `document_retrieval_strategy` field of the result set. This + field is only returned if the **natural_language_query** parameter is specified + in the query. + """ + + def __init__(self, + collection_id, + *, + document_retrieval_source=None, + confidence=None): + """ + Initialize a QueryResultMetadata object. + + :param str collection_id: The collection id associated with this training + data set. + :param str document_retrieval_source: (optional) The document retrieval + source that produced this search result. + :param float confidence: (optional) The confidence score for the given + result. Calculated based on how relevant the result is estimated to be. + confidence can range from `0.0` to `1.0`. The higher the number, the more + relevant the document. The `confidence` value for a result was calculated + using the model specified in the `document_retrieval_strategy` field of the + result set. This field is only returned if the **natural_language_query** + parameter is specified in the query. + """ + self.document_retrieval_source = document_retrieval_source + self.collection_id = collection_id + self.confidence = confidence + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResultMetadata object from a json dictionary.""" + args = {} + valid_keys = [ + 'document_retrieval_source', 'collection_id', 'confidence' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryResultMetadata: ' + + ', '.join(bad_keys)) + if 'document_retrieval_source' in _dict: + args['document_retrieval_source'] = _dict.get( + 'document_retrieval_source') + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + else: + raise ValueError( + 'Required property \'collection_id\' not present in QueryResultMetadata JSON' + ) + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'document_retrieval_source' + ) and self.document_retrieval_source is not None: + _dict['document_retrieval_source'] = self.document_retrieval_source + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + return _dict + + def __str__(self): + """Return a `str` version of this QueryResultMetadata object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class DocumentRetrievalSourceEnum(Enum): + """ + The document retrieval source that produced this search result. + """ + SEARCH = "search" + CURATION = "curation" + + +class QueryResultPassage(): + """ + A passage query result. + + :attr str passage_text: (optional) The content of the extracted passage. + :attr int start_offset: (optional) The position of the first character of the + extracted passage in the originating field. + :attr int end_offset: (optional) The position of the last character of the + extracted passage in the originating field. + :attr str field: (optional) The label of the field from which the passage has + been extracted. + """ + + def __init__(self, + *, + passage_text=None, + start_offset=None, + end_offset=None, + field=None): + """ + Initialize a QueryResultPassage object. + + :param str passage_text: (optional) The content of the extracted passage. + :param int start_offset: (optional) The position of the first character of + the extracted passage in the originating field. + :param int end_offset: (optional) The position of the last character of the + extracted passage in the originating field. + :param str field: (optional) The label of the field from which the passage + has been extracted. + """ + self.passage_text = passage_text + self.start_offset = start_offset + self.end_offset = end_offset + self.field = field + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResultPassage object from a json dictionary.""" + args = {} + valid_keys = ['passage_text', 'start_offset', 'end_offset', 'field'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryResultPassage: ' + + ', '.join(bad_keys)) + if 'passage_text' in _dict: + args['passage_text'] = _dict.get('passage_text') + if 'start_offset' in _dict: + args['start_offset'] = _dict.get('start_offset') + if 'end_offset' in _dict: + args['end_offset'] = _dict.get('end_offset') + if 'field' in _dict: + args['field'] = _dict.get('field') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'passage_text') and self.passage_text is not None: + _dict['passage_text'] = self.passage_text + if hasattr(self, 'start_offset') and self.start_offset is not None: + _dict['start_offset'] = self.start_offset + if hasattr(self, 'end_offset') and self.end_offset is not None: + _dict['end_offset'] = self.end_offset + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + return _dict + + def __str__(self): + """Return a `str` version of this QueryResultPassage object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QuerySuggestedRefinement(): + """ + A suggested additional query term or terms user to filter results. + + :attr str text: (optional) The text used to filter. + """ + + def __init__(self, *, text=None): + """ + Initialize a QuerySuggestedRefinement object. + + :param str text: (optional) The text used to filter. + """ + self.text = text + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QuerySuggestedRefinement object from a json dictionary.""" + args = {} + valid_keys = ['text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QuerySuggestedRefinement: ' + + ', '.join(bad_keys)) + if 'text' in _dict: + args['text'] = _dict.get('text') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + return _dict + + def __str__(self): + """Return a `str` version of this QuerySuggestedRefinement object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTableResult(): + """ + A tables whose content or context match a search query. + + :attr str table_id: (optional) The identifier for the retrieved table. + :attr str source_document_id: (optional) The identifier of the document the + table was retrieved from. + :attr str collection_id: (optional) The identifier of the collection the table + was retrieved from. + :attr str table_html: (optional) HTML snippet of the table info. + :attr int table_html_offset: (optional) The offset of the table html snippet in + the original document html. + :attr TableResultTable table: (optional) Full table object retrieved from Table + Understanding Enrichment. + """ + + def __init__(self, + *, + table_id=None, + source_document_id=None, + collection_id=None, + table_html=None, + table_html_offset=None, + table=None): + """ + Initialize a QueryTableResult object. + + :param str table_id: (optional) The identifier for the retrieved table. + :param str source_document_id: (optional) The identifier of the document + the table was retrieved from. + :param str collection_id: (optional) The identifier of the collection the + table was retrieved from. + :param str table_html: (optional) HTML snippet of the table info. + :param int table_html_offset: (optional) The offset of the table html + snippet in the original document html. + :param TableResultTable table: (optional) Full table object retrieved from + Table Understanding Enrichment. + """ + self.table_id = table_id + self.source_document_id = source_document_id + self.collection_id = collection_id + self.table_html = table_html + self.table_html_offset = table_html_offset + self.table = table + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTableResult object from a json dictionary.""" + args = {} + valid_keys = [ + 'table_id', 'source_document_id', 'collection_id', 'table_html', + 'table_html_offset', 'table' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTableResult: ' + + ', '.join(bad_keys)) + if 'table_id' in _dict: + args['table_id'] = _dict.get('table_id') + if 'source_document_id' in _dict: + args['source_document_id'] = _dict.get('source_document_id') + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'table_html' in _dict: + args['table_html'] = _dict.get('table_html') + if 'table_html_offset' in _dict: + args['table_html_offset'] = _dict.get('table_html_offset') + if 'table' in _dict: + args['table'] = TableResultTable._from_dict(_dict.get('table')) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'table_id') and self.table_id is not None: + _dict['table_id'] = self.table_id + if hasattr( + self, + 'source_document_id') and self.source_document_id is not None: + _dict['source_document_id'] = self.source_document_id + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'table_html') and self.table_html is not None: + _dict['table_html'] = self.table_html + if hasattr(self, + 'table_html_offset') and self.table_html_offset is not None: + _dict['table_html_offset'] = self.table_html_offset + if hasattr(self, 'table') and self.table is not None: + _dict['table'] = self.table._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this QueryTableResult object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTermAggregation(): + """ + Returns the top values for the field specified. + + :attr str field: The field in the document used to generate top values from. + :attr int count: (optional) The number of top values returned. + :attr list[QueryTermAggregationResult] results: (optional) Array of top values + for the field. + """ + + def __init__(self, type, field, *, count=None, results=None): + """ + Initialize a QueryTermAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str field: The field in the document used to generate top values + from. + :param int count: (optional) The number of top values returned. + :param list[QueryTermAggregationResult] results: (optional) Array of top + values for the field. + """ + self.field = field + self.count = count + self.results = results + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTermAggregation object from a json dictionary.""" + args = {} + valid_keys = ['field', 'count', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTermAggregation: ' + + ', '.join(bad_keys)) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryTermAggregation JSON' + ) + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'results' in _dict: + args['results'] = [ + QueryTermAggregationResult._from_dict(x) + for x in (_dict.get('results')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + return _dict + + def __str__(self): + """Return a `str` version of this QueryTermAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTermAggregationResult(): + """ + Top value result for the term aggregation. + + :attr str key: Value of the field with a non-zero frequency in the document set. + :attr int matching_results: Number of documents containing the 'key'. + :attr list[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + + def __init__(self, key, matching_results, *, aggregations=None): + """ + Initialize a QueryTermAggregationResult object. + + :param str key: Value of the field with a non-zero frequency in the + document set. + :param int matching_results: Number of documents containing the 'key'. + :param list[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + self.key = key + self.matching_results = matching_results + self.aggregations = aggregations + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTermAggregationResult object from a json dictionary.""" + args = {} + valid_keys = ['key', 'matching_results', 'aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTermAggregationResult: ' + + ', '.join(bad_keys)) + if 'key' in _dict: + args['key'] = _dict.get('key') + else: + raise ValueError( + 'Required property \'key\' not present in QueryTermAggregationResult JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'key') and self.key is not None: + _dict['key'] = self.key + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + return _dict + + def __str__(self): + """Return a `str` version of this QueryTermAggregationResult object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTimesliceAggregation(): + """ + A specialized histogram aggregation that uses dates to create interval segments. + + :attr str field: The date field name used to create the timeslice. + :attr str interval: The date interval value. Valid values are seconds, minutes, + hours, days, weeks, and years. + :attr list[QueryTimesliceAggregationResult] results: (optional) Array of + aggregation results. + """ + + def __init__(self, type, field, interval, *, results=None): + """ + Initialize a QueryTimesliceAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str field: The date field name used to create the timeslice. + :param str interval: The date interval value. Valid values are seconds, + minutes, hours, days, weeks, and years. + :param list[QueryTimesliceAggregationResult] results: (optional) Array of + aggregation results. + """ + self.field = field + self.interval = interval + self.results = results + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTimesliceAggregation object from a json dictionary.""" + args = {} + valid_keys = ['field', 'interval', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTimesliceAggregation: ' + + ', '.join(bad_keys)) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryTimesliceAggregation JSON' + ) + if 'interval' in _dict: + args['interval'] = _dict.get('interval') + else: + raise ValueError( + 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' + ) + if 'results' in _dict: + args['results'] = [ + QueryTimesliceAggregationResult._from_dict(x) + for x in (_dict.get('results')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'interval') and self.interval is not None: + _dict['interval'] = self.interval + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + return _dict + + def __str__(self): + """Return a `str` version of this QueryTimesliceAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTimesliceAggregationResult(): + """ + A timeslice interval segment. + + :attr str key_as_string: String date value of the upper bound for the timeslice + interval in ISO-8601 format. + :attr int key: Numeric date value of the upper bound for the timeslice interval + in UNIX miliseconds since epoch. + :attr int matching_results: Number of documents with the specified key as the + upper bound. + :attr list[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + + def __init__(self, + key_as_string, + key, + matching_results, + *, + aggregations=None): + """ + Initialize a QueryTimesliceAggregationResult object. + + :param str key_as_string: String date value of the upper bound for the + timeslice interval in ISO-8601 format. + :param int key: Numeric date value of the upper bound for the timeslice + interval in UNIX miliseconds since epoch. + :param int matching_results: Number of documents with the specified key as + the upper bound. + :param list[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + self.key_as_string = key_as_string + self.key = key + self.matching_results = matching_results + self.aggregations = aggregations + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" + args = {} + valid_keys = [ + 'key_as_string', 'key', 'matching_results', 'aggregations' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTimesliceAggregationResult: ' + + ', '.join(bad_keys)) + if 'key_as_string' in _dict: + args['key_as_string'] = _dict.get('key_as_string') + else: + raise ValueError( + 'Required property \'key_as_string\' not present in QueryTimesliceAggregationResult JSON' + ) + if 'key' in _dict: + args['key'] = _dict.get('key') + else: + raise ValueError( + 'Required property \'key\' not present in QueryTimesliceAggregationResult JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'key_as_string') and self.key_as_string is not None: + _dict['key_as_string'] = self.key_as_string + if hasattr(self, 'key') and self.key is not None: + _dict['key'] = self.key + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + return _dict + + def __str__(self): + """Return a `str` version of this QueryTimesliceAggregationResult object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTopHitsAggregation(): + """ + Returns the top documents ranked by the score of the query. + + :attr int size: The number of documents to return. + :attr QueryTopHitsAggregationResult hits: (optional) + """ + + def __init__(self, type, size, *, hits=None): + """ + Initialize a QueryTopHitsAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param int size: The number of documents to return. + :param QueryTopHitsAggregationResult hits: (optional) + """ + self.size = size + self.hits = hits + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTopHitsAggregation object from a json dictionary.""" + args = {} + valid_keys = ['size', 'hits'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTopHitsAggregation: ' + + ', '.join(bad_keys)) + if 'size' in _dict: + args['size'] = _dict.get('size') + else: + raise ValueError( + 'Required property \'size\' not present in QueryTopHitsAggregation JSON' + ) + if 'hits' in _dict: + args['hits'] = QueryTopHitsAggregationResult._from_dict( + _dict.get('hits')) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'size') and self.size is not None: + _dict['size'] = self.size + if hasattr(self, 'hits') and self.hits is not None: + _dict['hits'] = self.hits._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this QueryTopHitsAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTopHitsAggregationResult(): + """ + A query response containing the matching documents for the preceding aggregations. + + :attr int matching_results: Number of matching results. + :attr list[dict] hits: (optional) An array of the document results. + """ + + def __init__(self, matching_results, *, hits=None): + """ + Initialize a QueryTopHitsAggregationResult object. + + :param int matching_results: Number of matching results. + :param list[dict] hits: (optional) An array of the document results. + """ + self.matching_results = matching_results + self.hits = hits + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" + args = {} + valid_keys = ['matching_results', 'hits'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTopHitsAggregationResult: ' + + ', '.join(bad_keys)) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryTopHitsAggregationResult JSON' + ) + if 'hits' in _dict: + args['hits'] = _dict.get('hits') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'hits') and self.hits is not None: + _dict['hits'] = self.hits + return _dict + + def __str__(self): + """Return a `str` version of this QueryTopHitsAggregationResult object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RetrievalDetails(): + """ + An object contain retrieval type information. + + :attr str document_retrieval_strategy: (optional) Indentifies the document + retrieval strategy used for this query. `relevancy_training` indicates that the + results were returned using a relevancy trained model. + **Note**: In the event of trained collections being queried, but the trained + model is not used to return results, the **document_retrieval_strategy** will be + listed as `untrained`. + """ + + def __init__(self, *, document_retrieval_strategy=None): + """ + Initialize a RetrievalDetails object. + + :param str document_retrieval_strategy: (optional) Indentifies the document + retrieval strategy used for this query. `relevancy_training` indicates that + the results were returned using a relevancy trained model. + **Note**: In the event of trained collections being queried, but the + trained model is not used to return results, the + **document_retrieval_strategy** will be listed as `untrained`. + """ + self.document_retrieval_strategy = document_retrieval_strategy + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RetrievalDetails object from a json dictionary.""" + args = {} + valid_keys = ['document_retrieval_strategy'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RetrievalDetails: ' + + ', '.join(bad_keys)) + if 'document_retrieval_strategy' in _dict: + args['document_retrieval_strategy'] = _dict.get( + 'document_retrieval_strategy') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'document_retrieval_strategy' + ) and self.document_retrieval_strategy is not None: + _dict[ + 'document_retrieval_strategy'] = self.document_retrieval_strategy + return _dict + + def __str__(self): + """Return a `str` version of this RetrievalDetails object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class DocumentRetrievalStrategyEnum(Enum): + """ + Indentifies the document retrieval strategy used for this query. + `relevancy_training` indicates that the results were returned using a relevancy + trained model. + **Note**: In the event of trained collections being queried, but the trained + model is not used to return results, the **document_retrieval_strategy** will be + listed as `untrained`. + """ + UNTRAINED = "untrained" + RELEVANCY_TRAINING = "relevancy_training" + + +class TableBodyCells(): + """ + Cells that are not table header, column header, or row header cells. + + :attr str cell_id: (optional) The unique ID of the cell in the current table. + :attr TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + :attr str text: (optional) The textual contents of this cell from the input + document without associated markup content. + :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + location in the current table. + :attr int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :attr int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. + :attr int column_index_end: (optional) The `end` index of this cell's `column` + location in the current table. + :attr list[TableRowHeaderIds] row_header_ids: (optional) A list of table row + header ids. + :attr list[TableRowHeaderTexts] row_header_texts: (optional) A list of table row + header texts. + :attr list[TableRowHeaderTextsNormalized] row_header_texts_normalized: + (optional) A list of table row header texts normalized. + :attr list[TableColumnHeaderIds] column_header_ids: (optional) A list of table + column header ids. + :attr list[TableColumnHeaderTexts] column_header_texts: (optional) A list of + table column header texts. + :attr list[TableColumnHeaderTextsNormalized] column_header_texts_normalized: + (optional) A list of table column header texts normalized. + :attr list[DocumentAttribute] attributes: (optional) A list of document + attributes. + """ + + def __init__(self, + *, + cell_id=None, + location=None, + text=None, + row_index_begin=None, + row_index_end=None, + column_index_begin=None, + column_index_end=None, + row_header_ids=None, + row_header_texts=None, + row_header_texts_normalized=None, + column_header_ids=None, + column_header_texts=None, + column_header_texts_normalized=None, + attributes=None): + """ + Initialize a TableBodyCells object. + + :param str cell_id: (optional) The unique ID of the cell in the current + table. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. + :param str text: (optional) The textual contents of this cell from the + input document without associated markup content. + :param int row_index_begin: (optional) The `begin` index of this cell's + `row` location in the current table. + :param int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :param int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. + :param int column_index_end: (optional) The `end` index of this cell's + `column` location in the current table. + :param list[TableRowHeaderIds] row_header_ids: (optional) A list of table + row header ids. + :param list[TableRowHeaderTexts] row_header_texts: (optional) A list of + table row header texts. + :param list[TableRowHeaderTextsNormalized] row_header_texts_normalized: + (optional) A list of table row header texts normalized. + :param list[TableColumnHeaderIds] column_header_ids: (optional) A list of + table column header ids. + :param list[TableColumnHeaderTexts] column_header_texts: (optional) A list + of table column header texts. + :param list[TableColumnHeaderTextsNormalized] + column_header_texts_normalized: (optional) A list of table column header + texts normalized. + :param list[DocumentAttribute] attributes: (optional) A list of document + attributes. + """ + self.cell_id = cell_id + self.location = location + self.text = text + self.row_index_begin = row_index_begin + self.row_index_end = row_index_end + self.column_index_begin = column_index_begin + self.column_index_end = column_index_end + self.row_header_ids = row_header_ids + self.row_header_texts = row_header_texts + self.row_header_texts_normalized = row_header_texts_normalized + self.column_header_ids = column_header_ids + self.column_header_texts = column_header_texts + self.column_header_texts_normalized = column_header_texts_normalized + self.attributes = attributes + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableBodyCells object from a json dictionary.""" + args = {} + valid_keys = [ + 'cell_id', 'location', 'text', 'row_index_begin', 'row_index_end', + 'column_index_begin', 'column_index_end', 'row_header_ids', + 'row_header_texts', 'row_header_texts_normalized', + 'column_header_ids', 'column_header_texts', + 'column_header_texts_normalized', 'attributes' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableBodyCells: ' + + ', '.join(bad_keys)) + if 'cell_id' in _dict: + args['cell_id'] = _dict.get('cell_id') + if 'location' in _dict: + args['location'] = TableElementLocation._from_dict( + _dict.get('location')) + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'row_index_begin' in _dict: + args['row_index_begin'] = _dict.get('row_index_begin') + if 'row_index_end' in _dict: + args['row_index_end'] = _dict.get('row_index_end') + if 'column_index_begin' in _dict: + args['column_index_begin'] = _dict.get('column_index_begin') + if 'column_index_end' in _dict: + args['column_index_end'] = _dict.get('column_index_end') + if 'row_header_ids' in _dict: + args['row_header_ids'] = [ + TableRowHeaderIds._from_dict(x) + for x in (_dict.get('row_header_ids')) + ] + if 'row_header_texts' in _dict: + args['row_header_texts'] = [ + TableRowHeaderTexts._from_dict(x) + for x in (_dict.get('row_header_texts')) + ] + if 'row_header_texts_normalized' in _dict: + args['row_header_texts_normalized'] = [ + TableRowHeaderTextsNormalized._from_dict(x) + for x in (_dict.get('row_header_texts_normalized')) + ] + if 'column_header_ids' in _dict: + args['column_header_ids'] = [ + TableColumnHeaderIds._from_dict(x) + for x in (_dict.get('column_header_ids')) + ] + if 'column_header_texts' in _dict: + args['column_header_texts'] = [ + TableColumnHeaderTexts._from_dict(x) + for x in (_dict.get('column_header_texts')) + ] + if 'column_header_texts_normalized' in _dict: + args['column_header_texts_normalized'] = [ + TableColumnHeaderTextsNormalized._from_dict(x) + for x in (_dict.get('column_header_texts_normalized')) + ] + if 'attributes' in _dict: + args['attributes'] = [ + DocumentAttribute._from_dict(x) + for x in (_dict.get('attributes')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'cell_id') and self.cell_id is not None: + _dict['cell_id'] = self.cell_id + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, + 'row_index_begin') and self.row_index_begin is not None: + _dict['row_index_begin'] = self.row_index_begin + if hasattr(self, 'row_index_end') and self.row_index_end is not None: + _dict['row_index_end'] = self.row_index_end + if hasattr( + self, + 'column_index_begin') and self.column_index_begin is not None: + _dict['column_index_begin'] = self.column_index_begin + if hasattr(self, + 'column_index_end') and self.column_index_end is not None: + _dict['column_index_end'] = self.column_index_end + if hasattr(self, 'row_header_ids') and self.row_header_ids is not None: + _dict['row_header_ids'] = [ + x._to_dict() for x in self.row_header_ids + ] + if hasattr(self, + 'row_header_texts') and self.row_header_texts is not None: + _dict['row_header_texts'] = [ + x._to_dict() for x in self.row_header_texts + ] + if hasattr(self, 'row_header_texts_normalized' + ) and self.row_header_texts_normalized is not None: + _dict['row_header_texts_normalized'] = [ + x._to_dict() for x in self.row_header_texts_normalized + ] + if hasattr(self, + 'column_header_ids') and self.column_header_ids is not None: + _dict['column_header_ids'] = [ + x._to_dict() for x in self.column_header_ids + ] + if hasattr( + self, + 'column_header_texts') and self.column_header_texts is not None: + _dict['column_header_texts'] = [ + x._to_dict() for x in self.column_header_texts + ] + if hasattr(self, 'column_header_texts_normalized' + ) and self.column_header_texts_normalized is not None: + _dict['column_header_texts_normalized'] = [ + x._to_dict() for x in self.column_header_texts_normalized + ] + if hasattr(self, 'attributes') and self.attributes is not None: + _dict['attributes'] = [x._to_dict() for x in self.attributes] + return _dict + + def __str__(self): + """Return a `str` version of this TableBodyCells object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableCellKey(): + """ + A key in a key-value pair. + + :attr str cell_id: (optional) The unique ID of the key in the table. + :attr TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + :attr str text: (optional) The text content of the table cell without HTML + markup. + """ + + def __init__(self, *, cell_id=None, location=None, text=None): + """ + Initialize a TableCellKey object. + + :param str cell_id: (optional) The unique ID of the key in the table. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. + :param str text: (optional) The text content of the table cell without HTML + markup. + """ + self.cell_id = cell_id + self.location = location + self.text = text + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableCellKey object from a json dictionary.""" + args = {} + valid_keys = ['cell_id', 'location', 'text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableCellKey: ' + + ', '.join(bad_keys)) + if 'cell_id' in _dict: + args['cell_id'] = _dict.get('cell_id') + if 'location' in _dict: + args['location'] = TableElementLocation._from_dict( + _dict.get('location')) + if 'text' in _dict: + args['text'] = _dict.get('text') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'cell_id') and self.cell_id is not None: + _dict['cell_id'] = self.cell_id + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + return _dict + + def __str__(self): + """Return a `str` version of this TableCellKey object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableCellValues(): + """ + A value in a key-value pair. + + :attr str cell_id: (optional) The unique ID of the value in the table. + :attr TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + :attr str text: (optional) The text content of the table cell without HTML + markup. + """ + + def __init__(self, *, cell_id=None, location=None, text=None): + """ + Initialize a TableCellValues object. + + :param str cell_id: (optional) The unique ID of the value in the table. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. + :param str text: (optional) The text content of the table cell without HTML + markup. + """ + self.cell_id = cell_id + self.location = location + self.text = text + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableCellValues object from a json dictionary.""" + args = {} + valid_keys = ['cell_id', 'location', 'text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableCellValues: ' + + ', '.join(bad_keys)) + if 'cell_id' in _dict: + args['cell_id'] = _dict.get('cell_id') + if 'location' in _dict: + args['location'] = TableElementLocation._from_dict( + _dict.get('location')) + if 'text' in _dict: + args['text'] = _dict.get('text') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'cell_id') and self.cell_id is not None: + _dict['cell_id'] = self.cell_id + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + return _dict + + def __str__(self): + """Return a `str` version of this TableCellValues object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableColumnHeaderIds(): + """ + An array of values, each being the `id` value of a column header that is applicable to + the current cell. + + :attr str id: (optional) The `id` value of a column header. + """ + + def __init__(self, *, id=None): + """ + Initialize a TableColumnHeaderIds object. + + :param str id: (optional) The `id` value of a column header. + """ + self.id = id + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableColumnHeaderIds object from a json dictionary.""" + args = {} + valid_keys = ['id'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableColumnHeaderIds: ' + + ', '.join(bad_keys)) + if 'id' in _dict: + args['id'] = _dict.get('id') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id + return _dict + + def __str__(self): + """Return a `str` version of this TableColumnHeaderIds object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableColumnHeaderTexts(): + """ + An array of values, each being the `text` value of a column header that is applicable + to the current cell. + + :attr str text: (optional) The `text` value of a column header. + """ + + def __init__(self, *, text=None): + """ + Initialize a TableColumnHeaderTexts object. + + :param str text: (optional) The `text` value of a column header. + """ + self.text = text + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableColumnHeaderTexts object from a json dictionary.""" + args = {} + valid_keys = ['text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableColumnHeaderTexts: ' + + ', '.join(bad_keys)) + if 'text' in _dict: + args['text'] = _dict.get('text') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + return _dict + + def __str__(self): + """Return a `str` version of this TableColumnHeaderTexts object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableColumnHeaderTextsNormalized(): + """ + If you provide customization input, the normalized version of the column header texts + according to the customization; otherwise, the same value as `column_header_texts`. + + :attr str text_normalized: (optional) The normalized version of a column header + text. + """ + + def __init__(self, *, text_normalized=None): + """ + Initialize a TableColumnHeaderTextsNormalized object. + + :param str text_normalized: (optional) The normalized version of a column + header text. + """ + self.text_normalized = text_normalized + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableColumnHeaderTextsNormalized object from a json dictionary.""" + args = {} + valid_keys = ['text_normalized'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableColumnHeaderTextsNormalized: ' + + ', '.join(bad_keys)) + if 'text_normalized' in _dict: + args['text_normalized'] = _dict.get('text_normalized') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'text_normalized') and self.text_normalized is not None: + _dict['text_normalized'] = self.text_normalized + return _dict + + def __str__(self): + """Return a `str` version of this TableColumnHeaderTextsNormalized object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableColumnHeaders(): + """ + Column-level cells, each applicable as a header to other cells in the same column as + itself, of the current table. + + :attr str cell_id: (optional) The unique ID of the cell in the current table. + :attr object location: (optional) The location of the column header cell in the + current table as defined by its `begin` and `end` offsets, respectfully, in the + input document. + :attr str text: (optional) The textual contents of this cell from the input + document without associated markup content. + :attr str text_normalized: (optional) If you provide customization input, the + normalized version of the cell text according to the customization; otherwise, + the same value as `text`. + :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + location in the current table. + :attr int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :attr int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. + :attr int column_index_end: (optional) The `end` index of this cell's `column` + location in the current table. + """ + + def __init__(self, + *, + cell_id=None, + location=None, + text=None, + text_normalized=None, + row_index_begin=None, + row_index_end=None, + column_index_begin=None, + column_index_end=None): + """ + Initialize a TableColumnHeaders object. + + :param str cell_id: (optional) The unique ID of the cell in the current + table. + :param object location: (optional) The location of the column header cell + in the current table as defined by its `begin` and `end` offsets, + respectfully, in the input document. + :param str text: (optional) The textual contents of this cell from the + input document without associated markup content. + :param str text_normalized: (optional) If you provide customization input, + the normalized version of the cell text according to the customization; + otherwise, the same value as `text`. + :param int row_index_begin: (optional) The `begin` index of this cell's + `row` location in the current table. + :param int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :param int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. + :param int column_index_end: (optional) The `end` index of this cell's + `column` location in the current table. + """ + self.cell_id = cell_id + self.location = location + self.text = text + self.text_normalized = text_normalized + self.row_index_begin = row_index_begin + self.row_index_end = row_index_end + self.column_index_begin = column_index_begin + self.column_index_end = column_index_end + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableColumnHeaders object from a json dictionary.""" + args = {} + valid_keys = [ + 'cell_id', 'location', 'text', 'text_normalized', 'row_index_begin', + 'row_index_end', 'column_index_begin', 'column_index_end' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableColumnHeaders: ' + + ', '.join(bad_keys)) + if 'cell_id' in _dict: + args['cell_id'] = _dict.get('cell_id') + if 'location' in _dict: + args['location'] = _dict.get('location') + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'text_normalized' in _dict: + args['text_normalized'] = _dict.get('text_normalized') + if 'row_index_begin' in _dict: + args['row_index_begin'] = _dict.get('row_index_begin') + if 'row_index_end' in _dict: + args['row_index_end'] = _dict.get('row_index_end') + if 'column_index_begin' in _dict: + args['column_index_begin'] = _dict.get('column_index_begin') + if 'column_index_end' in _dict: + args['column_index_end'] = _dict.get('column_index_end') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'cell_id') and self.cell_id is not None: + _dict['cell_id'] = self.cell_id + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, + 'text_normalized') and self.text_normalized is not None: + _dict['text_normalized'] = self.text_normalized + if hasattr(self, + 'row_index_begin') and self.row_index_begin is not None: + _dict['row_index_begin'] = self.row_index_begin + if hasattr(self, 'row_index_end') and self.row_index_end is not None: + _dict['row_index_end'] = self.row_index_end + if hasattr( + self, + 'column_index_begin') and self.column_index_begin is not None: + _dict['column_index_begin'] = self.column_index_begin + if hasattr(self, + 'column_index_end') and self.column_index_end is not None: + _dict['column_index_end'] = self.column_index_end + return _dict + + def __str__(self): + """Return a `str` version of this TableColumnHeaders object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableElementLocation(): + """ + The numeric location of the identified element in the document, represented with two + integers labeled `begin` and `end`. + + :attr int begin: The element's `begin` index. + :attr int end: The element's `end` index. + """ + + def __init__(self, begin, end): + """ + Initialize a TableElementLocation object. + + :param int begin: The element's `begin` index. + :param int end: The element's `end` index. + """ + self.begin = begin + self.end = end + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableElementLocation object from a json dictionary.""" + args = {} + valid_keys = ['begin', 'end'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableElementLocation: ' + + ', '.join(bad_keys)) + if 'begin' in _dict: + args['begin'] = _dict.get('begin') + else: + raise ValueError( + 'Required property \'begin\' not present in TableElementLocation JSON' + ) + if 'end' in _dict: + args['end'] = _dict.get('end') + else: + raise ValueError( + 'Required property \'end\' not present in TableElementLocation JSON' + ) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'begin') and self.begin is not None: + _dict['begin'] = self.begin + if hasattr(self, 'end') and self.end is not None: + _dict['end'] = self.end + return _dict + + def __str__(self): + """Return a `str` version of this TableElementLocation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableHeaders(): + """ + The contents of the current table's header. + + :attr str cell_id: (optional) The unique ID of the cell in the current table. + :attr object location: (optional) The location of the table header cell in the + current table as defined by its `begin` and `end` offsets, respectfully, in the + input document. + :attr str text: (optional) The textual contents of the cell from the input + document without associated markup content. + :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + location in the current table. + :attr int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :attr int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. + :attr int column_index_end: (optional) The `end` index of this cell's `column` + location in the current table. + """ + + def __init__(self, + *, + cell_id=None, + location=None, + text=None, + row_index_begin=None, + row_index_end=None, + column_index_begin=None, + column_index_end=None): + """ + Initialize a TableHeaders object. + + :param str cell_id: (optional) The unique ID of the cell in the current + table. + :param object location: (optional) The location of the table header cell in + the current table as defined by its `begin` and `end` offsets, + respectfully, in the input document. + :param str text: (optional) The textual contents of the cell from the input + document without associated markup content. + :param int row_index_begin: (optional) The `begin` index of this cell's + `row` location in the current table. + :param int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :param int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. + :param int column_index_end: (optional) The `end` index of this cell's + `column` location in the current table. + """ + self.cell_id = cell_id + self.location = location + self.text = text + self.row_index_begin = row_index_begin + self.row_index_end = row_index_end + self.column_index_begin = column_index_begin + self.column_index_end = column_index_end + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableHeaders object from a json dictionary.""" + args = {} + valid_keys = [ + 'cell_id', 'location', 'text', 'row_index_begin', 'row_index_end', + 'column_index_begin', 'column_index_end' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableHeaders: ' + + ', '.join(bad_keys)) + if 'cell_id' in _dict: + args['cell_id'] = _dict.get('cell_id') + if 'location' in _dict: + args['location'] = _dict.get('location') + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'row_index_begin' in _dict: + args['row_index_begin'] = _dict.get('row_index_begin') + if 'row_index_end' in _dict: + args['row_index_end'] = _dict.get('row_index_end') + if 'column_index_begin' in _dict: + args['column_index_begin'] = _dict.get('column_index_begin') + if 'column_index_end' in _dict: + args['column_index_end'] = _dict.get('column_index_end') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'cell_id') and self.cell_id is not None: + _dict['cell_id'] = self.cell_id + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, + 'row_index_begin') and self.row_index_begin is not None: + _dict['row_index_begin'] = self.row_index_begin + if hasattr(self, 'row_index_end') and self.row_index_end is not None: + _dict['row_index_end'] = self.row_index_end + if hasattr( + self, + 'column_index_begin') and self.column_index_begin is not None: + _dict['column_index_begin'] = self.column_index_begin + if hasattr(self, + 'column_index_end') and self.column_index_end is not None: + _dict['column_index_end'] = self.column_index_end + return _dict + + def __str__(self): + """Return a `str` version of this TableHeaders object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableKeyValuePairs(): + """ + Key-value pairs detected across cell boundaries. + + :attr TableCellKey key: (optional) A key in a key-value pair. + :attr list[TableCellValues] value: (optional) A list of values in a key-value + pair. + """ + + def __init__(self, *, key=None, value=None): + """ + Initialize a TableKeyValuePairs object. + + :param TableCellKey key: (optional) A key in a key-value pair. + :param list[TableCellValues] value: (optional) A list of values in a + key-value pair. + """ + self.key = key + self.value = value + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableKeyValuePairs object from a json dictionary.""" + args = {} + valid_keys = ['key', 'value'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableKeyValuePairs: ' + + ', '.join(bad_keys)) + if 'key' in _dict: + args['key'] = TableCellKey._from_dict(_dict.get('key')) + if 'value' in _dict: + args['value'] = [ + TableCellValues._from_dict(x) for x in (_dict.get('value')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'key') and self.key is not None: + _dict['key'] = self.key._to_dict() + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = [x._to_dict() for x in self.value] + return _dict + + def __str__(self): + """Return a `str` version of this TableKeyValuePairs object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableResultTable(): + """ + Full table object retrieved from Table Understanding Enrichment. + + :attr TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + :attr str text: (optional) The textual contents of the current table from the + input document without associated markup content. + :attr TableTextLocation section_title: (optional) Text and associated location + within a table. + :attr TableTextLocation title: (optional) Text and associated location within a + table. + :attr list[TableHeaders] table_headers: (optional) An array of table-level cells + that apply as headers to all the other cells in the current table. + :attr list[TableRowHeaders] row_headers: (optional) An array of row-level cells, + each applicable as a header to other cells in the same row as itself, of the + current table. + :attr list[TableColumnHeaders] column_headers: (optional) An array of + column-level cells, each applicable as a header to other cells in the same + column as itself, of the current table. + :attr list[TableKeyValuePairs] key_value_pairs: (optional) An array of key-value + pairs identified in the current table. + :attr list[TableBodyCells] body_cells: (optional) An array of cells that are + neither table header nor column header nor row header cells, of the current + table with corresponding row and column header associations. + :attr list[TableTextLocation] contexts: (optional) An array of lists of textual + entries across the document related to the current table being parsed. + """ + + def __init__(self, + *, + location=None, + text=None, + section_title=None, + title=None, + table_headers=None, + row_headers=None, + column_headers=None, + key_value_pairs=None, + body_cells=None, + contexts=None): + """ + Initialize a TableResultTable object. + + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. + :param str text: (optional) The textual contents of the current table from + the input document without associated markup content. + :param TableTextLocation section_title: (optional) Text and associated + location within a table. + :param TableTextLocation title: (optional) Text and associated location + within a table. + :param list[TableHeaders] table_headers: (optional) An array of table-level + cells that apply as headers to all the other cells in the current table. + :param list[TableRowHeaders] row_headers: (optional) An array of row-level + cells, each applicable as a header to other cells in the same row as + itself, of the current table. + :param list[TableColumnHeaders] column_headers: (optional) An array of + column-level cells, each applicable as a header to other cells in the same + column as itself, of the current table. + :param list[TableKeyValuePairs] key_value_pairs: (optional) An array of + key-value pairs identified in the current table. + :param list[TableBodyCells] body_cells: (optional) An array of cells that + are neither table header nor column header nor row header cells, of the + current table with corresponding row and column header associations. + :param list[TableTextLocation] contexts: (optional) An array of lists of + textual entries across the document related to the current table being + parsed. + """ + self.location = location + self.text = text + self.section_title = section_title + self.title = title + self.table_headers = table_headers + self.row_headers = row_headers + self.column_headers = column_headers + self.key_value_pairs = key_value_pairs + self.body_cells = body_cells + self.contexts = contexts + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableResultTable object from a json dictionary.""" + args = {} + valid_keys = [ + 'location', 'text', 'section_title', 'title', 'table_headers', + 'row_headers', 'column_headers', 'key_value_pairs', 'body_cells', + 'contexts' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableResultTable: ' + + ', '.join(bad_keys)) + if 'location' in _dict: + args['location'] = TableElementLocation._from_dict( + _dict.get('location')) + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'section_title' in _dict: + args['section_title'] = TableTextLocation._from_dict( + _dict.get('section_title')) + if 'title' in _dict: + args['title'] = TableTextLocation._from_dict(_dict.get('title')) + if 'table_headers' in _dict: + args['table_headers'] = [ + TableHeaders._from_dict(x) for x in (_dict.get('table_headers')) + ] + if 'row_headers' in _dict: + args['row_headers'] = [ + TableRowHeaders._from_dict(x) + for x in (_dict.get('row_headers')) + ] + if 'column_headers' in _dict: + args['column_headers'] = [ + TableColumnHeaders._from_dict(x) + for x in (_dict.get('column_headers')) + ] + if 'key_value_pairs' in _dict: + args['key_value_pairs'] = [ + TableKeyValuePairs._from_dict(x) + for x in (_dict.get('key_value_pairs')) + ] + if 'body_cells' in _dict: + args['body_cells'] = [ + TableBodyCells._from_dict(x) for x in (_dict.get('body_cells')) + ] + if 'contexts' in _dict: + args['contexts'] = [ + TableTextLocation._from_dict(x) for x in (_dict.get('contexts')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'section_title') and self.section_title is not None: + _dict['section_title'] = self.section_title._to_dict() + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title._to_dict() + if hasattr(self, 'table_headers') and self.table_headers is not None: + _dict['table_headers'] = [x._to_dict() for x in self.table_headers] + if hasattr(self, 'row_headers') and self.row_headers is not None: + _dict['row_headers'] = [x._to_dict() for x in self.row_headers] + if hasattr(self, 'column_headers') and self.column_headers is not None: + _dict['column_headers'] = [ + x._to_dict() for x in self.column_headers + ] + if hasattr(self, + 'key_value_pairs') and self.key_value_pairs is not None: + _dict['key_value_pairs'] = [ + x._to_dict() for x in self.key_value_pairs + ] + if hasattr(self, 'body_cells') and self.body_cells is not None: + _dict['body_cells'] = [x._to_dict() for x in self.body_cells] + if hasattr(self, 'contexts') and self.contexts is not None: + _dict['contexts'] = [x._to_dict() for x in self.contexts] + return _dict + + def __str__(self): + """Return a `str` version of this TableResultTable object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableRowHeaderIds(): + """ + An array of values, each being the `id` value of a row header that is applicable to + this body cell. + + :attr str id: (optional) The `id` values of a row header. + """ + + def __init__(self, *, id=None): + """ + Initialize a TableRowHeaderIds object. + + :param str id: (optional) The `id` values of a row header. + """ + self.id = id + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableRowHeaderIds object from a json dictionary.""" + args = {} + valid_keys = ['id'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableRowHeaderIds: ' + + ', '.join(bad_keys)) + if 'id' in _dict: + args['id'] = _dict.get('id') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id + return _dict + + def __str__(self): + """Return a `str` version of this TableRowHeaderIds object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableRowHeaderTexts(): + """ + An array of values, each being the `text` value of a row header that is applicable to + this body cell. + + :attr str text: (optional) The `text` value of a row header. + """ + + def __init__(self, *, text=None): + """ + Initialize a TableRowHeaderTexts object. + + :param str text: (optional) The `text` value of a row header. + """ + self.text = text + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableRowHeaderTexts object from a json dictionary.""" + args = {} + valid_keys = ['text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableRowHeaderTexts: ' + + ', '.join(bad_keys)) + if 'text' in _dict: + args['text'] = _dict.get('text') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + return _dict + + def __str__(self): + """Return a `str` version of this TableRowHeaderTexts object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableRowHeaderTextsNormalized(): + """ + If you provide customization input, the normalized version of the row header texts + according to the customization; otherwise, the same value as `row_header_texts`. + + :attr str text_normalized: (optional) The normalized version of a row header + text. + """ + + def __init__(self, *, text_normalized=None): + """ + Initialize a TableRowHeaderTextsNormalized object. + + :param str text_normalized: (optional) The normalized version of a row + header text. + """ + self.text_normalized = text_normalized + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableRowHeaderTextsNormalized object from a json dictionary.""" + args = {} + valid_keys = ['text_normalized'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableRowHeaderTextsNormalized: ' + + ', '.join(bad_keys)) + if 'text_normalized' in _dict: + args['text_normalized'] = _dict.get('text_normalized') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, + 'text_normalized') and self.text_normalized is not None: + _dict['text_normalized'] = self.text_normalized + return _dict + + def __str__(self): + """Return a `str` version of this TableRowHeaderTextsNormalized object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableRowHeaders(): + """ + Row-level cells, each applicable as a header to other cells in the same row as itself, + of the current table. + + :attr str cell_id: (optional) The unique ID of the cell in the current table. + :attr TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + :attr str text: (optional) The textual contents of this cell from the input + document without associated markup content. + :attr str text_normalized: (optional) If you provide customization input, the + normalized version of the cell text according to the customization; otherwise, + the same value as `text`. + :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + location in the current table. + :attr int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :attr int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. + :attr int column_index_end: (optional) The `end` index of this cell's `column` + location in the current table. + """ + + def __init__(self, + *, + cell_id=None, + location=None, + text=None, + text_normalized=None, + row_index_begin=None, + row_index_end=None, + column_index_begin=None, + column_index_end=None): + """ + Initialize a TableRowHeaders object. + + :param str cell_id: (optional) The unique ID of the cell in the current + table. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. + :param str text: (optional) The textual contents of this cell from the + input document without associated markup content. + :param str text_normalized: (optional) If you provide customization input, + the normalized version of the cell text according to the customization; + otherwise, the same value as `text`. + :param int row_index_begin: (optional) The `begin` index of this cell's + `row` location in the current table. + :param int row_index_end: (optional) The `end` index of this cell's `row` + location in the current table. + :param int column_index_begin: (optional) The `begin` index of this cell's + `column` location in the current table. + :param int column_index_end: (optional) The `end` index of this cell's + `column` location in the current table. + """ + self.cell_id = cell_id + self.location = location + self.text = text + self.text_normalized = text_normalized + self.row_index_begin = row_index_begin + self.row_index_end = row_index_end + self.column_index_begin = column_index_begin + self.column_index_end = column_index_end + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableRowHeaders object from a json dictionary.""" + args = {} + valid_keys = [ + 'cell_id', 'location', 'text', 'text_normalized', 'row_index_begin', + 'row_index_end', 'column_index_begin', 'column_index_end' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableRowHeaders: ' + + ', '.join(bad_keys)) + if 'cell_id' in _dict: + args['cell_id'] = _dict.get('cell_id') + if 'location' in _dict: + args['location'] = TableElementLocation._from_dict( + _dict.get('location')) + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'text_normalized' in _dict: + args['text_normalized'] = _dict.get('text_normalized') + if 'row_index_begin' in _dict: + args['row_index_begin'] = _dict.get('row_index_begin') + if 'row_index_end' in _dict: + args['row_index_end'] = _dict.get('row_index_end') + if 'column_index_begin' in _dict: + args['column_index_begin'] = _dict.get('column_index_begin') + if 'column_index_end' in _dict: + args['column_index_end'] = _dict.get('column_index_end') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'cell_id') and self.cell_id is not None: + _dict['cell_id'] = self.cell_id + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, + 'text_normalized') and self.text_normalized is not None: + _dict['text_normalized'] = self.text_normalized + if hasattr(self, + 'row_index_begin') and self.row_index_begin is not None: + _dict['row_index_begin'] = self.row_index_begin + if hasattr(self, 'row_index_end') and self.row_index_end is not None: + _dict['row_index_end'] = self.row_index_end + if hasattr( + self, + 'column_index_begin') and self.column_index_begin is not None: + _dict['column_index_begin'] = self.column_index_begin + if hasattr(self, + 'column_index_end') and self.column_index_end is not None: + _dict['column_index_end'] = self.column_index_end + return _dict + + def __str__(self): + """Return a `str` version of this TableRowHeaders object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TableTextLocation(): + """ + Text and associated location within a table. + + :attr str text: (optional) The text retrieved. + :attr TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. + """ + + def __init__(self, *, text=None, location=None): + """ + Initialize a TableTextLocation object. + + :param str text: (optional) The text retrieved. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. + """ + self.text = text + self.location = location + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableTextLocation object from a json dictionary.""" + args = {} + valid_keys = ['text', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TableTextLocation: ' + + ', '.join(bad_keys)) + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'location' in _dict: + args['location'] = TableElementLocation._from_dict( + _dict.get('location')) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this TableTextLocation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TrainingExample(): + """ + Object containing example response details for a training query. + + :attr str document_id: The document ID associated with this training example. + :attr str collection_id: The collection ID associated with this training + example. + :attr int relevance: (optional) The relevance of the training example. + :attr date created: (optional) The date and time the example was created. + :attr date updated: (optional) The date and time the example was updated. + """ + + def __init__(self, + document_id, + collection_id, + *, + relevance=None, + created=None, + updated=None): + """ + Initialize a TrainingExample object. + + :param str document_id: The document ID associated with this training + example. + :param str collection_id: The collection ID associated with this training + example. + :param int relevance: (optional) The relevance of the training example. + :param date created: (optional) The date and time the example was created. + :param date updated: (optional) The date and time the example was updated. + """ + self.document_id = document_id + self.collection_id = collection_id + self.relevance = relevance + self.created = created + self.updated = updated + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingExample object from a json dictionary.""" + args = {} + valid_keys = [ + 'document_id', 'collection_id', 'relevance', 'created', 'updated' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TrainingExample: ' + + ', '.join(bad_keys)) + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + else: + raise ValueError( + 'Required property \'document_id\' not present in TrainingExample JSON' + ) + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + else: + raise ValueError( + 'Required property \'collection_id\' not present in TrainingExample JSON' + ) + if 'relevance' in _dict: + args['relevance'] = _dict.get('relevance') + if 'created' in _dict: + args['created'] = _dict.get('created') + if 'updated' in _dict: + args['updated'] = _dict.get('updated') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'relevance') and self.relevance is not None: + _dict['relevance'] = self.relevance + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = self.created + if hasattr(self, 'updated') and self.updated is not None: + _dict['updated'] = self.updated + return _dict + + def __str__(self): + """Return a `str` version of this TrainingExample object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TrainingQuery(): + """ + Object containing training query details. + + :attr str query_id: (optional) The query ID associated with the training query. + :attr str natural_language_query: (optional) The natural text query for the + training query. + :attr str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. + :attr date created: (optional) The date and time the query was created. + :attr date updated: (optional) The date and time the query was updated. + :attr list[TrainingExample] examples: (optional) Array of training examples. + """ + + def __init__(self, + *, + query_id=None, + natural_language_query=None, + filter=None, + created=None, + updated=None, + examples=None): + """ + Initialize a TrainingQuery object. + + :param str query_id: (optional) The query ID associated with the training + query. + :param str natural_language_query: (optional) The natural text query for + the training query. + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. + :param date created: (optional) The date and time the query was created. + :param date updated: (optional) The date and time the query was updated. + :param list[TrainingExample] examples: (optional) Array of training + examples. + """ + self.query_id = query_id + self.natural_language_query = natural_language_query + self.filter = filter + self.created = created + self.updated = updated + self.examples = examples + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingQuery object from a json dictionary.""" + args = {} + valid_keys = [ + 'query_id', 'natural_language_query', 'filter', 'created', + 'updated', 'examples' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TrainingQuery: ' + + ', '.join(bad_keys)) + if 'query_id' in _dict: + args['query_id'] = _dict.get('query_id') + if 'natural_language_query' in _dict: + args['natural_language_query'] = _dict.get('natural_language_query') + if 'filter' in _dict: + args['filter'] = _dict.get('filter') + if 'created' in _dict: + args['created'] = _dict.get('created') + if 'updated' in _dict: + args['updated'] = _dict.get('updated') + if 'examples' in _dict: + args['examples'] = [ + TrainingExample._from_dict(x) for x in (_dict.get('examples')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'query_id') and self.query_id is not None: + _dict['query_id'] = self.query_id + if hasattr(self, 'natural_language_query' + ) and self.natural_language_query is not None: + _dict['natural_language_query'] = self.natural_language_query + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = self.created + if hasattr(self, 'updated') and self.updated is not None: + _dict['updated'] = self.updated + if hasattr(self, 'examples') and self.examples is not None: + _dict['examples'] = [x._to_dict() for x in self.examples] + return _dict + + def __str__(self): + """Return a `str` version of this TrainingQuery object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TrainingQuerySet(): + """ + Object specifying the training queries contained in the identified training set. + + :attr list[TrainingQuery] queries: (optional) Array of training queries. + """ + + def __init__(self, *, queries=None): + """ + Initialize a TrainingQuerySet object. + + :param list[TrainingQuery] queries: (optional) Array of training queries. + """ + self.queries = queries + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingQuerySet object from a json dictionary.""" + args = {} + valid_keys = ['queries'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TrainingQuerySet: ' + + ', '.join(bad_keys)) + if 'queries' in _dict: + args['queries'] = [ + TrainingQuery._from_dict(x) for x in (_dict.get('queries')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'queries') and self.queries is not None: + _dict['queries'] = [x._to_dict() for x in self.queries] + return _dict + + def __str__(self): + """Return a `str` version of this TrainingQuerySet object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py new file mode 100644 index 000000000..cfc96854f --- /dev/null +++ b/test/unit/test_discovery_v2.py @@ -0,0 +1,1214 @@ +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2019. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ibm_cloud_sdk_core.authenticators.bearer_token_authenticator import BearerTokenAuthenticator +import json +import responses +import tempfile +from ibm_watson.discovery_v2 import * + +base_url = 'https://fake' + +############################################################################## +# Start of Service: Collections +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_collections +#----------------------------------------------------------------------------- +class TestListCollections(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collections_response(self): + body = self.construct_full_body() + response = fake_response_ListCollectionsResponse_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_collections_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListCollectionsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collections_empty(self): + check_empty_required_params(self, + fake_response_ListCollectionsResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections'.format(body['project_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 = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.list_collections(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Collections +############################################################################## + +############################################################################## +# Start of Service: Queries +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for query +#----------------------------------------------------------------------------- +class TestQuery(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_response(self): + body = self.construct_full_body() + response = fake_response_QueryResponse_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_query_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_QueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_empty(self): + check_empty_required_params(self, fake_response_QueryResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/query'.format(body['project_id']) + 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 = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.query(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body.update({ + "collection_ids": [], + "filter": + "string1", + "query": + "string1", + "natural_language_query": + "string1", + "aggregation": + "string1", + "count": + 12345, + "return_": {}, + "offset": + 12345, + "sort": + "string1", + "highlight": + True, + "spelling_suggestions": + True, + "table_results": + QueryLargeTableResults._from_dict( + json.loads("""{"enabled": false, "count": 5}""")), + "suggested_refinements": + QueryLargeSuggestedRefinements._from_dict( + json.loads("""{"enabled": false, "count": 5}""")), + "passages": + QueryLargePassages._from_dict( + json.loads( + """{"enabled": false, "per_document": true, "fields": [], "count": 5, "characters": 10}""" + )), + }) + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_autocompletion +#----------------------------------------------------------------------------- +class TestGetAutocompletion(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_autocompletion_response(self): + body = self.construct_full_body() + response = fake_response_Completions_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_autocompletion_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Completions_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_autocompletion_empty(self): + check_empty_required_params(self, fake_response_Completions_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/autocompletion'.format(body['project_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 = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.get_autocompletion(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_ids'] = {"collection_ids": {"mock": "data"}} + body['field'] = "string1" + body['prefix'] = "string1" + body['count'] = 12345 + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['prefix'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for query_notices +#----------------------------------------------------------------------------- +class TestQueryNotices(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_notices_response(self): + body = self.construct_full_body() + response = fake_response_QueryNoticesResponse_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_query_notices_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_QueryNoticesResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_notices_empty(self): + check_empty_required_params(self, + fake_response_QueryNoticesResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/notices'.format(body['project_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 = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.query_notices(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['filter'] = "string1" + body['query'] = "string1" + body['natural_language_query'] = "string1" + body['aggregation'] = "string1" + body['count'] = 12345 + body['return_'] = {"return_": {"mock": "data"}} + body['offset'] = 12345 + body['sort'] = {"sort": {"mock": "data"}} + body['highlight'] = True + body['spelling_suggestions'] = True + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_fields +#----------------------------------------------------------------------------- +class TestListFields(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_fields_response(self): + body = self.construct_full_body() + response = fake_response_ListFieldsResponse_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_fields_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListFieldsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_fields_empty(self): + check_empty_required_params(self, fake_response_ListFieldsResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/fields'.format(body['project_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 = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.list_fields(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_ids'] = {"collection_ids": {"mock": "data"}} + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Queries +############################################################################## + +############################################################################## +# Start of Service: ComponentSettings +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for get_component_settings +#----------------------------------------------------------------------------- +class TestGetComponentSettings(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_component_settings_response(self): + body = self.construct_full_body() + response = fake_response_ComponentSettingsResponse_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_component_settings_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ComponentSettingsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_component_settings_empty(self): + check_empty_required_params( + self, fake_response_ComponentSettingsResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/component_settings'.format( + body['project_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 = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.get_component_settings(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: ComponentSettings +############################################################################## + +############################################################################## +# Start of Service: Documents +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for add_document +#----------------------------------------------------------------------------- +class TestAddDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_document_response(self): + body = self.construct_full_body() + response = fake_response_DocumentAccepted_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_add_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentAccepted_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_document_empty(self): + check_empty_required_params(self, fake_response_DocumentAccepted_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections/{1}/documents'.format( + body['project_id'], body['collection_id']) + 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=202, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.add_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + body['file'] = tempfile.NamedTemporaryFile() + body['filename'] = "string1" + body['file_content_type'] = "string1" + body['metadata'] = "string1" + body['x_watson_discovery_force'] = True + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_document +#----------------------------------------------------------------------------- +class TestUpdateDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_document_response(self): + body = self.construct_full_body() + response = fake_response_DocumentAccepted_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_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentAccepted_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_document_empty(self): + check_empty_required_params(self, fake_response_DocumentAccepted_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( + body['project_id'], body['collection_id'], body['document_id']) + 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=202, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.update_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + body['file'] = tempfile.NamedTemporaryFile() + body['filename'] = "string1" + body['file_content_type'] = "string1" + body['metadata'] = "string1" + body['x_watson_discovery_force'] = True + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_document +#----------------------------------------------------------------------------- +class TestDeleteDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_response(self): + body = self.construct_full_body() + response = fake_response_DeleteDocumentResponse_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_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteDocumentResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_empty(self): + check_empty_required_params(self, + fake_response_DeleteDocumentResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( + body['project_id'], body['collection_id'], body['document_id']) + 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='application/json') + + def call_service(self, body): + service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.delete_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + body['x_watson_discovery_force'] = True + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Documents +############################################################################## + +############################################################################## +# Start of Service: TrainingData +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_training_queries +#----------------------------------------------------------------------------- +class TestListTrainingQueries(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_training_queries_response(self): + body = self.construct_full_body() + response = fake_response_TrainingQuerySet_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_training_queries_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingQuerySet_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_training_queries_empty(self): + check_empty_required_params(self, fake_response_TrainingQuerySet_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/training_data/queries'.format( + body['project_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 = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.list_training_queries(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_training_queries +#----------------------------------------------------------------------------- +class TestDeleteTrainingQueries(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_training_queries_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_training_queries_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_training_queries_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 = '/v2/projects/{0}/training_data/queries'.format( + body['project_id']) + 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=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.delete_training_queries(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_training_query +#----------------------------------------------------------------------------- +class TestCreateTrainingQuery(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_training_query_response(self): + body = self.construct_full_body() + response = fake_response_TrainingQuery_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_create_training_query_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingQuery_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_training_query_empty(self): + check_empty_required_params(self, fake_response_TrainingQuery_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/training_data/queries'.format( + body['project_id']) + 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=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.create_training_query(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body.update({ + "natural_language_query": "string1", + "filter": "string1", + "examples": [] + }) + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_training_query +#----------------------------------------------------------------------------- +class TestGetTrainingQuery(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_query_response(self): + body = self.construct_full_body() + response = fake_response_TrainingQuery_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_training_query_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingQuery_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_query_empty(self): + check_empty_required_params(self, fake_response_TrainingQuery_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( + body['project_id'], body['query_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 = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.get_training_query(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['query_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['query_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_training_query +#----------------------------------------------------------------------------- +class TestUpdateTrainingQuery(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_training_query_response(self): + body = self.construct_full_body() + response = fake_response_TrainingExample_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_training_query_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingExample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_training_query_empty(self): + check_empty_required_params(self, fake_response_TrainingExample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( + body['project_id'], body['query_id']) + 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=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + version='2019-11-22') + service.set_service_url('https://fake') + output = service.update_training_query(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['query_id'] = "string1" + body.update({ + "natural_language_query": "string1", + "filter": "string1", + "examples": [] + }) + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['query_id'] = "string1" + body.update({ + "natural_language_query": "string1", + "filter": "string1", + "examples": [] + }) + return body + + +# endregion +############################################################################## +# End of Service: TrainingData +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_ListCollectionsResponse_json = """{"collections": []}""" +fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query", "suggested_refinements": [], "table_results": []}""" +fake_response_Completions_json = """{"completions": []}""" +fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "results": [], "aggregations": []}""" +fake_response_ListFieldsResponse_json = """{"fields": []}""" +fake_response_ComponentSettingsResponse_json = """{"fields_shown": {"body": {"use_passage": false, "field": "fake_field"}, "title": {"field": "fake_field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": []}""" +fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" +fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" +fake_response_DeleteDocumentResponse_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" +fake_response_TrainingQuerySet_json = """{"queries": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" +fake_response_TrainingExample_json = """{"document_id": "fake_document_id", "cross_reference": "fake_cross_reference", "relevance": 9}""" From 1a13a0c0bf8522b8ea10146d4daf9059f2595c35 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 13:58:17 -0800 Subject: [PATCH 136/455] fix(semrelease): Reorder semantic release steps --- .bumpversion.cfg | 2 ++ .releaserc | 6 +++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 2a60e5e6a..0928b875e 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,6 +1,8 @@ [bumpversion] current_version = 4.0.2 commit = True +tag = True +tag_name = v{new_version} message = [skip ci] Bump version: {current_version} -> {new_version} diff --git a/.releaserc b/.releaserc index 5402290f7..7bca89531 100644 --- a/.releaserc +++ b/.releaserc @@ -3,12 +3,12 @@ "verifyConditions": ["@semantic-release/changelog", "@semantic-release/github"], "debug": true, "prepare": [ + "@semantic-release/changelog", + "@semantic-release/git", { "path": "@semantic-release/exec", "cmd": "bumpversion --current-version ${lastRelease.version} --new-version ${nextRelease.version} patch" - }, - "@semantic-release/changelog", - "@semantic-release/git" + } ], "publish": [ { From 9ccaf0da8a632c751aae47c5c69b7d199c64b789 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Wed, 20 Nov 2019 22:35:01 +0000 Subject: [PATCH 137/455] chore(release): 4.0.3 [skip ci] ## [4.0.3](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.2...v4.0.3) (2019-11-20) ### Bug Fixes * **bumpversion:** Skip for bumpversion ([fd38d73](https://github.com/watson-developer-cloud/python-sdk/commit/fd38d7395daf3d28e8dd085b0a1c8e9d4358a1b5)) * **semrelease:** Reorder semantic release steps ([1a13a0c](https://github.com/watson-developer-cloud/python-sdk/commit/1a13a0c0bf8522b8ea10146d4daf9059f2595c35)) --- CHANGELOG.md | 8 ++++++++ package-lock.json | 24 ++++++++++++------------ 2 files changed, 20 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b39dec37a..80e6e2e1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +## [4.0.3](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.2...v4.0.3) (2019-11-20) + + +### Bug Fixes + +* **bumpversion:** Skip for bumpversion ([fd38d73](https://github.com/watson-developer-cloud/python-sdk/commit/fd38d7395daf3d28e8dd085b0a1c8e9d4358a1b5)) +* **semrelease:** Reorder semantic release steps ([1a13a0c](https://github.com/watson-developer-cloud/python-sdk/commit/1a13a0c0bf8522b8ea10146d4daf9059f2595c35)) + ## [4.0.2](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.1...v4.0.2) (2019-11-11) diff --git a/package-lock.json b/package-lock.json index 34dfb8d2b..4d4aaf41e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -98,9 +98,9 @@ } }, "@octokit/types": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-2.0.1.tgz", - "integrity": "sha512-YDYgV6nCzdGdOm7wy43Ce8SQ3M5DMKegB8E5sTB/1xrxOdo2yS/KgUgML2N2ZGD621mkbdrAglwTyA4NDOlFFA==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-2.0.2.tgz", + "integrity": "sha512-StASIL2lgT3TRjxv17z9pAqbnI7HGu9DrJlg3sEBFfCLaMEqp+O3IQPUF6EZtQ4xkAu2ml6kMBBCtGxjvmtmuQ==", "requires": { "@types/node": ">= 8" } @@ -195,9 +195,9 @@ "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==" }, "@types/node": { - "version": "12.12.7", - "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.7.tgz", - "integrity": "sha512-E6Zn0rffhgd130zbCbAr/JdXfXkoOUFAKNs/rF8qnafSJ8KYaA/j3oz7dcwal+lYjLA7xvdd5J4wdYpCTlP8+w==" + "version": "12.12.11", + "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.11.tgz", + "integrity": "sha512-O+x6uIpa6oMNTkPuHDa9MhMMehlxLAd5QcOvKRjAFsBVpeFWTOPnXbDvILvFgFFZfQ1xh1EZi1FbXxUix+zpsQ==" }, "@types/retry": { "version": "0.12.0", @@ -380,9 +380,9 @@ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==" }, "execa": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-3.2.0.tgz", - "integrity": "sha512-kJJfVbI/lZE1PZYDI5VPxp8zXPO9rtxOkhpZ0jMKha56AI9y2gGVC6bkukStQf0ka5Rh15BA5m7cCCH4jmHqkw==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-3.3.0.tgz", + "integrity": "sha512-j5Vit5WZR/cbHlqU97+qcnw9WHRCIL4V1SVe75VcHcD1JRBdt8fv0zw89b7CQHQdUHTt2VjuhcF5ibAgVOxqpg==", "requires": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", @@ -946,9 +946,9 @@ "integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==" }, "which": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.1.tgz", - "integrity": "sha512-N7GBZOTswtB9lkQBZA4+zAXrjEIWAUOB93AvzUiudRzRxhUdLURQ7D/gAIMY1gatT/LTbmbcv8SiYazy3eYB7w==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "requires": { "isexe": "^2.0.0" } From bb1a6a93fcbc8ac13df45d78fc2b97b071267699 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 14:41:06 -0800 Subject: [PATCH 138/455] fix(semantic): remove tag in bumpversion --- .bumpversion.cfg | 2 -- 1 file changed, 2 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 0928b875e..2a60e5e6a 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,8 +1,6 @@ [bumpversion] current_version = 4.0.2 commit = True -tag = True -tag_name = v{new_version} message = [skip ci] Bump version: {current_version} -> {new_version} From 0134b6981c09fc7132297aeb161eb75029bbd54d Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 15:06:31 -0800 Subject: [PATCH 139/455] feat(assistantv1): New param `webhooks` in `create_workspace()` and `update_workspace()` --- ibm_watson/assistant_v1.py | 174 ++++++++++++++++++++++++++++++++- test/unit/test_assistant_v1.py | 8 +- 2 files changed, 175 insertions(+), 7 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index c47cd91d7..5ef2e986a 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -243,6 +243,7 @@ def create_workspace(self, entities=None, dialog_nodes=None, counterexamples=None, + webhooks=None, **kwargs): """ Create workspace. @@ -272,6 +273,7 @@ def create_workspace(self, describing the dialog nodes in the workspace. :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 dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -287,6 +289,8 @@ def create_workspace(self, dialog_nodes = [self._convert_model(x) for x in dialog_nodes] if counterexamples is not None: counterexamples = [self._convert_model(x) for x in counterexamples] + if webhooks is not None: + webhooks = [self._convert_model(x) for x in webhooks] headers = {} if 'headers' in kwargs: @@ -306,7 +310,8 @@ def create_workspace(self, 'intents': intents, 'entities': entities, 'dialog_nodes': dialog_nodes, - 'counterexamples': counterexamples + 'counterexamples': counterexamples, + 'webhooks': webhooks } url = '/v1/workspaces' @@ -388,6 +393,7 @@ def update_workspace(self, entities=None, dialog_nodes=None, counterexamples=None, + webhooks=None, append=None, **kwargs): """ @@ -419,6 +425,7 @@ def update_workspace(self, describing the dialog nodes in the workspace. :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 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 @@ -445,6 +452,8 @@ def update_workspace(self, dialog_nodes = [self._convert_model(x) for x in dialog_nodes] if counterexamples is not None: counterexamples = [self._convert_model(x) for x in counterexamples] + if webhooks is not None: + webhooks = [self._convert_model(x) for x in webhooks] headers = {} if 'headers' in kwargs: @@ -464,7 +473,8 @@ def update_workspace(self, 'intents': intents, 'entities': entities, 'dialog_nodes': dialog_nodes, - 'counterexamples': counterexamples + 'counterexamples': counterexamples, + 'webhooks': webhooks } url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) @@ -4084,6 +4094,7 @@ class TypeEnum(Enum): SERVER = "server" CLOUD_FUNCTION = "cloud_function" WEB_ACTION = "web_action" + WEBHOOK = "webhook" class DialogNodeCollection(): @@ -8071,6 +8082,151 @@ def __ne__(self, other): return not self == other +class Webhook(): + """ + A webhook that can be used by dialog nodes to make programmatic calls to an external + function. + **Note:** Currently, only a single webhook named `main_webhook` is supported. + + :attr str url: The URL for the external service or application to which you want + to send HTTP POST requests. + :attr str name: The name of the webhook. Currently, `main_webhook` is the only + supported value. + :attr list[WebhookHeader] headers: (optional) An optional array of HTTP headers + to pass with the HTTP request. + """ + + def __init__(self, url, name, *, headers=None): + """ + Initialize a Webhook object. + + :param str url: The URL for the external service or application to which + you want to send HTTP POST requests. + :param str name: The name of the webhook. Currently, `main_webhook` is the + only supported value. + :param list[WebhookHeader] headers: (optional) An optional array of HTTP + headers to pass with the HTTP request. + """ + self.url = url + self.name = name + self.headers = headers + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Webhook object from a json dictionary.""" + args = {} + valid_keys = ['url', 'name', 'headers'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Webhook: ' + + ', '.join(bad_keys)) + if 'url' in _dict: + args['url'] = _dict.get('url') + else: + raise ValueError( + 'Required property \'url\' not present in Webhook JSON') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in Webhook JSON') + if 'headers' in _dict: + args['headers'] = [ + WebhookHeader._from_dict(x) for x in (_dict.get('headers')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'headers') and self.headers is not None: + _dict['headers'] = [x._to_dict() for x in self.headers] + return _dict + + def __str__(self): + """Return a `str` version of this Webhook object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class WebhookHeader(): + """ + A key/value pair defining an HTTP header and a value. + + :attr str name: The name of an HTTP header (for example, `Authorization`). + :attr str value: The value of an HTTP header. + """ + + def __init__(self, name, value): + """ + Initialize a WebhookHeader object. + + :param str name: The name of an HTTP header (for example, `Authorization`). + :param str value: The value of an HTTP header. + """ + self.name = name + self.value = value + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WebhookHeader object from a json dictionary.""" + args = {} + valid_keys = ['name', 'value'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class WebhookHeader: ' + + ', '.join(bad_keys)) + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in WebhookHeader JSON') + if 'value' in _dict: + args['value'] = _dict.get('value') + else: + raise ValueError( + 'Required property \'value\' not present in WebhookHeader JSON') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + return _dict + + def __str__(self): + """Return a `str` version of this WebhookHeader object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Workspace(): """ Workspace. @@ -8098,6 +8254,7 @@ class Workspace(): the dialog nodes in the workspace. :attr list[Counterexample] counterexamples: (optional) An array of counterexamples. + :attr list[Webhook] webhooks: (optional) """ def __init__(self, @@ -8115,7 +8272,8 @@ def __init__(self, intents=None, entities=None, dialog_nodes=None, - counterexamples=None): + counterexamples=None, + webhooks=None): """ Initialize a Workspace object. @@ -8144,6 +8302,7 @@ def __init__(self, describing the dialog nodes in the workspace. :param list[Counterexample] counterexamples: (optional) An array of counterexamples. + :param list[Webhook] webhooks: (optional) """ self.name = name self.description = description @@ -8159,6 +8318,7 @@ def __init__(self, self.entities = entities self.dialog_nodes = dialog_nodes self.counterexamples = counterexamples + self.webhooks = webhooks @classmethod def _from_dict(cls, _dict): @@ -8167,7 +8327,7 @@ def _from_dict(cls, _dict): valid_keys = [ 'name', 'description', 'language', 'metadata', 'learning_opt_out', 'system_settings', 'workspace_id', 'status', 'created', 'updated', - 'intents', 'entities', 'dialog_nodes', 'counterexamples' + 'intents', 'entities', 'dialog_nodes', 'counterexamples', 'webhooks' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -8226,6 +8386,10 @@ def _from_dict(cls, _dict): Counterexample._from_dict(x) for x in (_dict.get('counterexamples')) ] + if 'webhooks' in _dict: + args['webhooks'] = [ + Webhook._from_dict(x) for x in (_dict.get('webhooks')) + ] return cls(**args) def _to_dict(self): @@ -8264,6 +8428,8 @@ def _to_dict(self): _dict['counterexamples'] = [ x._to_dict() for x in self.counterexamples ] + if hasattr(self, 'webhooks') and self.webhooks is not None: + _dict['webhooks'] = [x._to_dict() for x in self.webhooks] return _dict def __str__(self): diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index dad8ed580..504b361d5 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -8,7 +8,7 @@ from ibm_watson.assistant_v1 import Context, Counterexample, \ CounterexampleCollection, Entity, EntityCollection, Example, \ ExampleCollection, MessageInput, Intent, IntentCollection, Synonym, \ - SynonymCollection, Value, ValueCollection, Workspace, WorkspaceCollection + SynonymCollection, Value, ValueCollection, Workspace, WorkspaceCollection, Webhook, WebhookHeader from ibm_cloud_sdk_core.authenticators import BasicAuthenticator platform_url = 'https://gateway.watsonplatform.net' @@ -1344,7 +1344,8 @@ def test_create_workspace(): version='2017-02-03', authenticator=authenticator) workspace = service.create_workspace( name='Pizza app', description='Pizza app', language='en', metadata={}, - system_settings={'tooling': {'store_generic_responses' : True}}).get_result() + system_settings={'tooling': {'store_generic_responses' : True}}, + webhooks=[Webhook(url='fake-jenkins-url', name='jenkins', headers=[WebhookHeader('fake', 'header')])]).get_result() assert len(responses.calls) == 1 assert responses.calls[0].request.url.startswith(url) assert workspace == response @@ -1471,7 +1472,8 @@ def test_update_workspace(): description='Pizza app', language='en', metadata={}, - system_settings={'tooling': {'store_generic_responses' : True}}).get_result() + system_settings={'tooling': {'store_generic_responses' : True}}, + webhooks=[Webhook(url='fake-jenkins-url', name='jenkins', headers=[WebhookHeader('fake', 'header')])]).get_result() assert len(responses.calls) == 1 assert responses.calls[0].request.url.startswith(url) assert workspace == response From 5a5b84076ff4b0d87355ed71cf7a2cbb9612c866 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 15:15:45 -0800 Subject: [PATCH 140/455] feat(assistantv1): New param `new_disambiguation_opt_out ` in `create_dialog_node` --- ibm_watson/assistant_v1.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 5ef2e986a..8b7435a0b 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -2397,6 +2397,7 @@ def create_dialog_node(self, digress_out=None, digress_out_slots=None, user_label=None, + disambiguation_opt_out=None, **kwargs): """ Create dialog node. @@ -2447,6 +2448,8 @@ def create_dialog_node(self, top-level nodes while filling out slots. :param str user_label: (optional) A label that can be displayed externally 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 dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2490,7 +2493,8 @@ def create_dialog_node(self, 'digress_in': digress_in, 'digress_out': digress_out, 'digress_out_slots': digress_out_slots, - 'user_label': user_label + 'user_label': user_label, + 'disambiguation_opt_out': disambiguation_opt_out } url = '/v1/workspaces/{0}/dialog_nodes'.format( From e21caff9a6093fc5b74456776b6ccfc80976c13d Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 15:17:09 -0800 Subject: [PATCH 141/455] test(assistantv1): test new param disambiguation_opt_out --- test/unit/test_assistant_v1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 504b361d5..936c38a1f 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1515,7 +1515,7 @@ def test_dialog_nodes(): assistant = ibm_watson.AssistantV1( version='2017-02-03', authenticator=authenticator) - assistant.create_dialog_node('id', 'location-done', user_label='xxx') + assistant.create_dialog_node('id', 'location-done', user_label='xxx', disambiguation_opt_out=False) assert responses.calls[0].response.json()['application/json']['dialog_node'] == 'location-done' assistant.delete_dialog_node('id', 'location-done') From 6e52e07b3e3ab0a9bc2687406b8a98c5e5826e33 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 15:27:03 -0800 Subject: [PATCH 142/455] feat(assistantv1): New param `new_disambiguation_opt_out ` in `update_dialog_node() ` --- ibm_watson/assistant_v1.py | 21 ++++++++++++++++++--- test/unit/test_assistant_v1.py | 18 ++++++++++++++---- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 8b7435a0b..f940e0cb7 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -2575,6 +2575,7 @@ def update_dialog_node(self, new_digress_out=None, new_digress_out_slots=None, new_user_label=None, + new_disambiguation_opt_out=None, **kwargs): """ Update dialog node. @@ -2627,6 +2628,8 @@ def update_dialog_node(self, to top-level nodes while filling out slots. :param str new_user_label: (optional) A label that can be displayed 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 dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2670,7 +2673,8 @@ def update_dialog_node(self, 'digress_in': new_digress_in, 'digress_out': new_digress_out, 'digress_out_slots': new_digress_out_slots, - 'user_label': new_user_label + 'user_label': new_user_label, + 'disambiguation_opt_out': new_disambiguation_opt_out } url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( @@ -3710,6 +3714,8 @@ class DialogNode(): top-level nodes while filling out slots. :attr str user_label: (optional) A label that can be displayed externally to describe the purpose of the node to users. + :attr bool disambiguation_opt_out: (optional) Whether the dialog node should be + excluded from disambiguation suggestions. :attr bool disabled: (optional) For internal use only. :attr datetime created: (optional) The timestamp for creation of the object. :attr datetime updated: (optional) The timestamp for the most recent update to @@ -3736,6 +3742,7 @@ def __init__(self, digress_out=None, digress_out_slots=None, user_label=None, + disambiguation_opt_out=None, disabled=None, created=None, updated=None): @@ -3781,6 +3788,8 @@ def __init__(self, top-level nodes while filling out slots. :param str user_label: (optional) A label that can be displayed externally 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 disabled: (optional) For internal use only. :param datetime created: (optional) The timestamp for creation of the object. @@ -3805,6 +3814,7 @@ def __init__(self, self.digress_out = digress_out self.digress_out_slots = digress_out_slots self.user_label = user_label + self.disambiguation_opt_out = disambiguation_opt_out self.disabled = disabled self.created = created self.updated = updated @@ -3817,8 +3827,8 @@ def _from_dict(cls, _dict): 'dialog_node', 'description', 'conditions', 'parent', 'previous_sibling', 'output', 'context', 'metadata', 'next_step', 'title', 'type', 'event_name', 'variable', 'actions', 'digress_in', - 'digress_out', 'digress_out_slots', 'user_label', 'disabled', - 'created', 'updated' + 'digress_out', 'digress_out_slots', 'user_label', + 'disambiguation_opt_out', 'disabled', 'created', 'updated' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -3868,6 +3878,8 @@ def _from_dict(cls, _dict): args['digress_out_slots'] = _dict.get('digress_out_slots') if 'user_label' in _dict: args['user_label'] = _dict.get('user_label') + if 'disambiguation_opt_out' in _dict: + args['disambiguation_opt_out'] = _dict.get('disambiguation_opt_out') if 'disabled' in _dict: args['disabled'] = _dict.get('disabled') if 'created' in _dict: @@ -3917,6 +3929,9 @@ def _to_dict(self): _dict['digress_out_slots'] = self.digress_out_slots if hasattr(self, 'user_label') and self.user_label is not None: _dict['user_label'] = self.user_label + if hasattr(self, 'disambiguation_opt_out' + ) and self.disambiguation_opt_out is not None: + _dict['disambiguation_opt_out'] = self.disambiguation_opt_out if hasattr(self, 'disabled') and self.disabled is not None: _dict['disabled'] = self.disabled if hasattr(self, 'created') and self.created is not None: diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 936c38a1f..8ef258a87 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1490,6 +1490,13 @@ def test_dialog_nodes(): status=200, content_type='application/json') + responses.add( + responses.POST, + "{0}/location-done?version=2017-02-03".format(url), + body='{ "application/json": { "dialog_node": "location-done" }}', + status=200, + content_type='application/json') + responses.add( responses.POST, "{0}?version=2017-02-03".format(url), @@ -1518,16 +1525,19 @@ def test_dialog_nodes(): assistant.create_dialog_node('id', 'location-done', user_label='xxx', disambiguation_opt_out=False) assert responses.calls[0].response.json()['application/json']['dialog_node'] == 'location-done' + assistant.update_dialog_node('id', 'location-done', user_label='xxx', new_disambiguation_opt_out=False) + assert responses.calls[1].response.json()['application/json']['dialog_node'] == 'location-done' + assistant.delete_dialog_node('id', 'location-done') - assert responses.calls[1].response.json() == {"description": "deleted successfully"} + assert responses.calls[2].response.json() == {"description": "deleted successfully"} assistant.get_dialog_node('id', 'location-done') - assert responses.calls[2].response.json() == {"application/json": {"dialog_node": "location-atm"}} + assert responses.calls[3].response.json() == {"application/json": {"dialog_node": "location-atm"}} assistant.list_dialog_nodes('id') - assert responses.calls[3].response.json() == {"application/json": {"dialog_node": "location-atm"}} + assert responses.calls[4].response.json() == {"application/json": {"dialog_node": "location-atm"}} - assert len(responses.calls) == 4 + assert len(responses.calls) == 5 @responses.activate def test_delete_user_data(): From aeaa29a2cd0b8bff63e3314cac8a9b0bfe06394c Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Wed, 20 Nov 2019 23:33:15 +0000 Subject: [PATCH 143/455] chore(release): 4.0.3 [skip ci] ## [4.0.3](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.2...v4.0.3) (2019-11-20) ### Bug Fixes * **bumpversion:** Skip for bumpversion ([fd38d73](https://github.com/watson-developer-cloud/python-sdk/commit/fd38d7395daf3d28e8dd085b0a1c8e9d4358a1b5)) * **semantic:** remove tag in bumpversion ([bb1a6a9](https://github.com/watson-developer-cloud/python-sdk/commit/bb1a6a93fcbc8ac13df45d78fc2b97b071267699)) * **semrelease:** Reorder semantic release steps ([1a13a0c](https://github.com/watson-developer-cloud/python-sdk/commit/1a13a0c0bf8522b8ea10146d4daf9059f2595c35)) --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 80e6e2e1a..245c04e83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,15 @@ ## [4.0.3](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.2...v4.0.3) (2019-11-20) +### Bug Fixes + +* **bumpversion:** Skip for bumpversion ([fd38d73](https://github.com/watson-developer-cloud/python-sdk/commit/fd38d7395daf3d28e8dd085b0a1c8e9d4358a1b5)) +* **semantic:** remove tag in bumpversion ([bb1a6a9](https://github.com/watson-developer-cloud/python-sdk/commit/bb1a6a93fcbc8ac13df45d78fc2b97b071267699)) +* **semrelease:** Reorder semantic release steps ([1a13a0c](https://github.com/watson-developer-cloud/python-sdk/commit/1a13a0c0bf8522b8ea10146d4daf9059f2595c35)) + +## [4.0.3](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.2...v4.0.3) (2019-11-20) + + ### Bug Fixes * **bumpversion:** Skip for bumpversion ([fd38d73](https://github.com/watson-developer-cloud/python-sdk/commit/fd38d7395daf3d28e8dd085b0a1c8e9d4358a1b5)) From d40bea2c1907648d1bde117f967f0b0ef7c2c8f2 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Wed, 20 Nov 2019 23:33:19 +0000 Subject: [PATCH 144/455] [skip ci] Bump version: 4.0.2 -> 4.0.3 --- .bumpversion.cfg | 3 +-- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 2a60e5e6a..b55bcb966 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,9 +1,8 @@ [bumpversion] -current_version = 4.0.2 +current_version = 4.0.3 commit = True message = [skip ci] Bump version: {current_version} -> {new_version} - [bumpversion:file:ibm_watson/version.py] search = __version__ = '{current_version}' replace = __version__ = '{new_version}' diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 439176402..4efd83ead 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.0.2' +__version__ = '4.0.3' diff --git a/setup.py b/setup.py index b86aec84f..dbd2f072d 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.0.2' +__version__ = '4.0.3' if sys.argv[-1] == 'publish': From 5f93c552828b539b846c9a44df4f69ed888d27b4 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 15:36:17 -0800 Subject: [PATCH 145/455] feat(assistantv1): New property `off_topic` in `WorkspaceSystemSettings` --- ibm_watson/assistant_v1.py | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index f940e0cb7..b74483b56 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -8554,15 +8554,18 @@ class WorkspaceSystemSettings(): related to the Watson Assistant user interface. :attr WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace settings related to the disambiguation feature. - **Note:** This feature is available only to Premium users. + **Note:** This feature is available only to Plus and Premium users. :attr dict human_agent_assist: (optional) For internal use only. + :attr WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings + related to detection of irrelevant input. """ def __init__(self, *, tooling=None, disambiguation=None, - human_agent_assist=None): + human_agent_assist=None, + off_topic=None): """ Initialize a WorkspaceSystemSettings object. @@ -8570,18 +8573,23 @@ def __init__(self, settings related to the Watson Assistant user interface. :param WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace settings related to the disambiguation feature. - **Note:** This feature is available only to Premium users. + **Note:** This feature is available only to Plus and Premium users. :param dict human_agent_assist: (optional) For internal use only. + :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.off_topic = off_topic @classmethod def _from_dict(cls, _dict): """Initialize a WorkspaceSystemSettings object from a json dictionary.""" args = {} - valid_keys = ['tooling', 'disambiguation', 'human_agent_assist'] + valid_keys = [ + 'tooling', 'disambiguation', 'human_agent_assist', 'off_topic' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -8596,6 +8604,9 @@ def _from_dict(cls, _dict): _dict.get('disambiguation')) if 'human_agent_assist' in _dict: args['human_agent_assist'] = _dict.get('human_agent_assist') + if 'off_topic' in _dict: + args['off_topic'] = WorkspaceSystemSettingsOffTopic._from_dict( + _dict.get('off_topic')) return cls(**args) def _to_dict(self): @@ -8609,6 +8620,8 @@ def _to_dict(self): self, 'human_agent_assist') and self.human_agent_assist is not None: _dict['human_agent_assist'] = self.human_agent_assist + if hasattr(self, 'off_topic') and self.off_topic is not None: + _dict['off_topic'] = self.off_topic._to_dict() return _dict def __str__(self): From 27a8cd7173a48fb6aaf909598fc3eb34e1320fe4 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 15:39:30 -0800 Subject: [PATCH 146/455] feat(assistantv1): New properties `randomize` and `max_ssuggestions` in `WorkspaceSystemSettingsDisambiguation` --- ibm_watson/assistant_v1.py | 37 +++++++++++++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index b74483b56..f784223f3 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -8655,6 +8655,12 @@ class WorkspaceSystemSettingsDisambiguation(): to intent detection conflicts. Set to **high** if you want the disambiguation feature to be triggered more often. This can be useful for testing or demonstration purposes. + :attr bool randomize: (optional) Whether the order in which disambiguation + suggestions are presented should be randomized (but still influenced by relative + confidence). + :attr int max_suggestions: (optional) The maximum number of disambigation + suggestions that can be included in a `suggestion` response. + :attr str suggestion_text_policy: (optional) For internal use only. """ def __init__(self, @@ -8662,7 +8668,10 @@ def __init__(self, prompt=None, none_of_the_above_prompt=None, enabled=None, - sensitivity=None): + sensitivity=None, + randomize=None, + max_suggestions=None, + suggestion_text_policy=None): """ Initialize a WorkspaceSystemSettingsDisambiguation object. @@ -8677,18 +8686,28 @@ def __init__(self, feature to intent detection conflicts. Set to **high** if you want the disambiguation feature to be triggered more often. This can be useful for testing or demonstration purposes. + :param bool randomize: (optional) Whether the order in which disambiguation + suggestions are presented should be randomized (but still influenced by + relative confidence). + :param int max_suggestions: (optional) The maximum number of disambigation + suggestions that can be included in a `suggestion` response. + :param str suggestion_text_policy: (optional) For internal use only. """ self.prompt = prompt self.none_of_the_above_prompt = none_of_the_above_prompt self.enabled = enabled self.sensitivity = sensitivity + self.randomize = randomize + self.max_suggestions = max_suggestions + self.suggestion_text_policy = suggestion_text_policy @classmethod def _from_dict(cls, _dict): """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" args = {} valid_keys = [ - 'prompt', 'none_of_the_above_prompt', 'enabled', 'sensitivity' + 'prompt', 'none_of_the_above_prompt', 'enabled', 'sensitivity', + 'randomize', 'max_suggestions', 'suggestion_text_policy' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -8704,6 +8723,12 @@ def _from_dict(cls, _dict): args['enabled'] = _dict.get('enabled') if 'sensitivity' in _dict: args['sensitivity'] = _dict.get('sensitivity') + if 'randomize' in _dict: + args['randomize'] = _dict.get('randomize') + if 'max_suggestions' in _dict: + args['max_suggestions'] = _dict.get('max_suggestions') + if 'suggestion_text_policy' in _dict: + args['suggestion_text_policy'] = _dict.get('suggestion_text_policy') return cls(**args) def _to_dict(self): @@ -8718,6 +8743,14 @@ def _to_dict(self): _dict['enabled'] = self.enabled if hasattr(self, 'sensitivity') and self.sensitivity is not None: _dict['sensitivity'] = self.sensitivity + if hasattr(self, 'randomize') and self.randomize is not None: + _dict['randomize'] = self.randomize + if hasattr(self, + 'max_suggestions') and self.max_suggestions is not None: + _dict['max_suggestions'] = self.max_suggestions + if hasattr(self, 'suggestion_text_policy' + ) and self.suggestion_text_policy is not None: + _dict['suggestion_text_policy'] = self.suggestion_text_policy return _dict def __str__(self): From 3f0ae545c8109a9f252a438d9610feceae921fda Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 15:39:56 -0800 Subject: [PATCH 147/455] chore(asssistantv1): description changes --- ibm_watson/assistant_v1.py | 69 ++++++++++++++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 7 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index f784223f3..c93fc3ada 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -2807,7 +2807,8 @@ def list_all_logs(self, :param str filter: A cacheable parameter that limits the results to those matching the specified filter. You must specify a filter query that - includes a value for `language`, as well as a value for `workspace_id` or + 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). :param str sort: (optional) How to sort the returned log events. You can @@ -5048,7 +5049,8 @@ class DialogSuggestion(): DialogSuggestion. :attr str label: The user-facing label for the disambiguation option. This label - is taken from the **user_label** property of the corresponding dialog node. + is taken from the **title** or **user_label** property of the corresponding + dialog node, depending on the disambiguation options. :attr DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. @@ -5065,8 +5067,8 @@ def __init__(self, label, value, *, output=None, dialog_node=None): Initialize a DialogSuggestion object. :param str label: The user-facing label for the disambiguation option. This - label is taken from the **user_label** property of the corresponding dialog - node. + label is taken from the **title** or **user_label** property of the + corresponding dialog node, depending on the disambiguation options. :param DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. @@ -7502,7 +7504,7 @@ class RuntimeResponseGeneric(): :attr list[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, - which is only available for Premium users. + which is only available for Plus and Premium users. """ def __init__(self, @@ -7552,7 +7554,7 @@ def __init__(self, describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation - feature, which is only available for Premium users. + feature, which is only available for Plus and Premium users. """ self.response_type = response_type self.text = text @@ -8642,7 +8644,7 @@ def __ne__(self, other): class WorkspaceSystemSettingsDisambiguation(): """ Workspace settings related to the disambiguation feature. - **Note:** This feature is available only to Premium users. + **Note:** This feature is available only to Plus and Premium users. :attr str prompt: (optional) The text of the introductory prompt that accompanies disambiguation options presented to the user. @@ -8777,6 +8779,59 @@ class SensitivityEnum(Enum): HIGH = "high" +class WorkspaceSystemSettingsOffTopic(): + """ + Workspace settings related to detection of irrelevant input. + + :attr bool enabled: (optional) Whether enhanced irrelevance detection is enabled + for the workspace. + """ + + def __init__(self, *, enabled=None): + """ + Initialize a WorkspaceSystemSettingsOffTopic object. + + :param bool enabled: (optional) Whether enhanced irrelevance detection is + enabled for the workspace. + """ + self.enabled = enabled + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettingsOffTopic 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 WorkspaceSystemSettingsOffTopic: ' + + ', '.join(bad_keys)) + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + return cls(**args) + + def _to_dict(self): + """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 __str__(self): + """Return a `str` version of this WorkspaceSystemSettingsOffTopic object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """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. From 81895eb3279e9b2776f032d547cd72e1484beaf0 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 20 Nov 2019 15:40:15 -0800 Subject: [PATCH 148/455] doc(assistantv2): description changes --- ibm_watson/assistant_v2.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 8f36be0bc..6489bfab1 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -89,7 +89,10 @@ def create_session(self, assistant_id, **kwargs): Create a session. Create a new session. A session is used to send user input to a skill and receive - responses. It also maintains the state of the conversation. + 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). :param str assistant_id: Unique identifier of the assistant. To find the assistant ID in the Watson Assistant user interface, open the assistant @@ -127,7 +130,9 @@ def delete_session(self, assistant_id, session_id, **kwargs): """ Delete session. - Deletes a session explicitly before it times out. + 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)). :param str assistant_id: Unique identifier of the assistant. To find the assistant ID in the Watson Assistant user interface, open the assistant @@ -680,7 +685,8 @@ class DialogSuggestion(): DialogSuggestion. :attr str label: The user-facing label for the disambiguation option. This label - is taken from the **user_label** property of the corresponding dialog node. + is taken from the **title** or **user_label** property of the corresponding + dialog node, depending on the disambiguation options. :attr DialogSuggestionValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. @@ -693,8 +699,8 @@ def __init__(self, label, value, *, output=None): Initialize a DialogSuggestion object. :param str label: The user-facing label for the disambiguation option. This - label is taken from the **user_label** property of the corresponding dialog - node. + label is taken from the **title** or **user_label** property of the + corresponding dialog node, depending on the disambiguation options. :param DialogSuggestionValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. From 2ce0ad33c91714eb6d9b2adb7ac44ff70ad378e9 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 21 Nov 2019 11:39:08 -0800 Subject: [PATCH 149/455] feat(discoveryv1): `title` property not part of `QueryNoticesResult` and `QueryResult` --- ibm_watson/discovery_v1.py | 30 +++++------------------------- 1 file changed, 5 insertions(+), 25 deletions(-) diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index e5e5145a4..eac3e348e 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1276,7 +1276,7 @@ def add_document(self, :param str collection_id: The ID of the collection. :param file file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a confiruration is + megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -1391,7 +1391,7 @@ def update_document(self, :param str document_id: The ID of the document. :param file file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a confiruration is + megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -9649,7 +9649,6 @@ class QueryNoticesResult(): containing the document for this result. :attr QueryResultMetadata result_metadata: (optional) Metadata of a query result. - :attr str title: (optional) Automatically extracted result title. :attr int code: (optional) The internal status code returned by the ingestion subsystem indicating the overall result of ingesting the source document. :attr str filename: (optional) Name of the original source file (if available). @@ -9665,7 +9664,6 @@ def __init__(self, metadata=None, collection_id=None, result_metadata=None, - title=None, code=None, filename=None, file_type=None, @@ -9681,7 +9679,6 @@ def __init__(self, containing the document for this result. :param QueryResultMetadata result_metadata: (optional) Metadata of a query result. - :param str title: (optional) Automatically extracted result title. :param int code: (optional) The internal status code returned by the ingestion subsystem indicating the overall result of ingesting the source document. @@ -9697,7 +9694,6 @@ def __init__(self, self.metadata = metadata self.collection_id = collection_id self.result_metadata = result_metadata - self.title = title self.code = code self.filename = filename self.file_type = file_type @@ -9724,9 +9720,6 @@ def _from_dict(cls, _dict): args['result_metadata'] = QueryResultMetadata._from_dict( _dict.get('result_metadata')) del xtra['result_metadata'] - if 'title' in _dict: - args['title'] = _dict.get('title') - del xtra['title'] if 'code' in _dict: args['code'] = _dict.get('code') del xtra['code'] @@ -9759,8 +9752,6 @@ def _to_dict(self): if hasattr(self, 'result_metadata') and self.result_metadata is not None: _dict['result_metadata'] = self.result_metadata._to_dict() - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title if hasattr(self, 'code') and self.code is not None: _dict['code'] = self.code if hasattr(self, 'filename') and self.filename is not None: @@ -9780,8 +9771,8 @@ def _to_dict(self): def __setattr__(self, name, value): properties = { - 'id', 'metadata', 'collection_id', 'result_metadata', 'title', - 'code', 'filename', 'file_type', 'sha1', 'notices' + 'id', 'metadata', 'collection_id', 'result_metadata', 'code', + 'filename', 'file_type', 'sha1', 'notices' } if not hasattr(self, '_additionalProperties'): super(QueryNoticesResult, self).__setattr__('_additionalProperties', @@ -10076,7 +10067,6 @@ class QueryResult(): containing the document for this result. :attr QueryResultMetadata result_metadata: (optional) Metadata of a query result. - :attr str title: (optional) Automatically extracted result title. """ def __init__(self, @@ -10085,7 +10075,6 @@ def __init__(self, metadata=None, collection_id=None, result_metadata=None, - title=None, **kwargs): """ Initialize a QueryResult object. @@ -10096,14 +10085,12 @@ def __init__(self, containing the document for this result. :param QueryResultMetadata result_metadata: (optional) Metadata of a query result. - :param str title: (optional) Automatically extracted result title. :param **kwargs: (optional) Any additional properties. """ self.id = id self.metadata = metadata self.collection_id = collection_id self.result_metadata = result_metadata - self.title = title for _key, _value in kwargs.items(): setattr(self, _key, _value) @@ -10125,9 +10112,6 @@ def _from_dict(cls, _dict): args['result_metadata'] = QueryResultMetadata._from_dict( _dict.get('result_metadata')) del xtra['result_metadata'] - if 'title' in _dict: - args['title'] = _dict.get('title') - del xtra['title'] args.update(xtra) return cls(**args) @@ -10143,8 +10127,6 @@ def _to_dict(self): if hasattr(self, 'result_metadata') and self.result_metadata is not None: _dict['result_metadata'] = self.result_metadata._to_dict() - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) @@ -10153,9 +10135,7 @@ def _to_dict(self): return _dict def __setattr__(self, name, value): - properties = { - 'id', 'metadata', 'collection_id', 'result_metadata', 'title' - } + properties = {'id', 'metadata', 'collection_id', 'result_metadata'} if not hasattr(self, '_additionalProperties'): super(QueryResult, self).__setattr__('_additionalProperties', set()) if name not in properties: From 2b54527725438d229e4acd80dc31d0869bdaa464 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 21 Nov 2019 12:30:02 -0800 Subject: [PATCH 150/455] feat(discoveryv2): Add examples for discoveryv2 --- examples/discovery_v2.py | 83 ++++++++++++++++++++++++++++++ ibm_watson/discovery_v2.py | 76 +++++++++++++++------------ test/unit/test_discovery_v2.py | 94 +++++++++++++++++----------------- 3 files changed, 173 insertions(+), 80 deletions(-) create mode 100644 examples/discovery_v2.py diff --git a/examples/discovery_v2.py b/examples/discovery_v2.py new file mode 100644 index 000000000..dfcd2f917 --- /dev/null +++ b/examples/discovery_v2.py @@ -0,0 +1,83 @@ +import json +import os +from ibm_watson import DiscoveryV2 +from ibm_watson.discovery_v2 import TrainingExample +from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator, BearerTokenAuthenticator + + +## Authentication ## +## Option 1: username/password +authenticator = CloudPakForDataAuthenticator('', + '', + '', + disable_ssl_verification=True) + +## Option 2: bearer token +authenticator = BearerTokenAuthenticator('your bearer token') + +## Initialize discovery instance ## +discovery = DiscoveryV2(version='2019-11-22', authenticator=authenticator) +discovery.set_service_url( + 'https://zen-gm-cpd-zen-gm.apps.big-smoke-lb-1.fyre.ibm.com/discovery/deweyan-poet/instances/1574286017227/api' +) +discovery.set_disable_ssl_verification(True) + +PROJECT_ID = 'your project id' +## List Collections ## +collections = discovery.list_collections(project_id=PROJECT_ID).get_result() +print(json.dumps(collections, indent=2)) + +## Component settings ## +settings_result = discovery.get_component_settings( + project_id=PROJECT_ID).get_result() +print(json.dumps(settings_result, indent=2)) + +## Add Document ## +COLLECTION_ID = 'your collection id' +with open(os.path.join(os.getcwd(), '..', 'resources', + 'simple.html')) as fileinfo: + add_document_result = discovery.add_document(project_id=PROJECT_ID, + collection_id=COLLECTION_ID, + file=fileinfo).get_result() +print(json.dumps(add_document_result, indent=2)) +document_id = add_document_result.get('document_id') + +## Create Training Data ## +training_example = TrainingExample(document_id=document_id, + collection_id=COLLECTION_ID, + relevance=1) +create_query = discovery.create_training_query( + project_id=PROJECT_ID, + natural_language_query='How is the weather today?', + examples=[training_example]).get_result() +print(json.dumps(create_query, indent=2)) + +training_queries = discovery.list_training_queries( + project_id=PROJECT_ID).get_result() +print(json.dumps(training_queries, indent=2)) + +## Queries ## +query_result = discovery.query( + project_id=PROJECT_ID, + collection_ids=[COLLECTION_ID], + natural_language_query='How is the weather today?').get_result() +print(json.dumps(query_result, indent=2)) + +autocomplete_result = discovery.get_autocompletion( + project_id=PROJECT_ID, prefix="The content").get_result() +print(json.dumps(autocomplete_result, indent=2)) + +query_notices_result = discovery.query_notices( + project_id=PROJECT_ID, natural_language_query='warning').get_result() +print(json.dumps(query_notices_result, indent=2)) + +list_fields = discovery.list_fields(project_id=PROJECT_ID).get_result() +print(json.dumps(list_fields, indent=2)) + +## Cleanup ## +discovery.delete_training_queries(project_id=PROJECT_ID).get_result() + +delete_document_result = discovery.delete_document( + project_id=PROJECT_ID, collection_id=COLLECTION_ID, + document_id=document_id).get_result() +print(json.dumps(delete_document_result, indent=2)) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 9f77823c1..ef9dc5b8f 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -759,10 +759,10 @@ def delete_training_queries(self, project_id, **kwargs): def create_training_query(self, project_id, + natural_language_query, + examples, *, - natural_language_query=None, filter=None, - examples=None, **kwargs): """ Create training query. @@ -772,12 +772,11 @@ def create_training_query(self, :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. - :param str natural_language_query: (optional) The natural text query for - the training query. + :param str natural_language_query: The natural text query for the training + query. + :param list[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :param list[TrainingExample] examples: (optional) Array of training - examples. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -785,8 +784,7 @@ def create_training_query(self, if project_id is None: raise ValueError('project_id must be provided') - if examples is not None: - examples = [self._convert_model(x) for x in examples] + examples = [self._convert_model(x) for x in examples] headers = {} if 'headers' in kwargs: @@ -799,8 +797,8 @@ def create_training_query(self, data = { 'natural_language_query': natural_language_query, - 'filter': filter, - 'examples': examples + 'examples': examples, + 'filter': filter } url = '/v2/projects/{0}/training_data/queries'.format( @@ -855,10 +853,10 @@ def get_training_query(self, project_id, query_id, **kwargs): def update_training_query(self, project_id, query_id, + natural_language_query, + examples, *, - natural_language_query=None, filter=None, - examples=None, **kwargs): """ Update a training query. @@ -868,12 +866,11 @@ def update_training_query(self, :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. :param str query_id: The ID of the query used for training. - :param str natural_language_query: (optional) The natural text query for - the training query. + :param str natural_language_query: The natural text query for the training + query. + :param list[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :param list[TrainingExample] examples: (optional) Array of training - examples. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -883,8 +880,11 @@ def update_training_query(self, raise ValueError('project_id must be provided') if query_id is None: raise ValueError('query_id must be provided') - if examples is not None: - examples = [self._convert_model(x) for x in examples] + if natural_language_query is None: + raise ValueError('natural_language_query must be provided') + if examples is None: + raise ValueError('examples must be provided') + examples = [self._convert_model(x) for x in examples] headers = {} if 'headers' in kwargs: @@ -897,8 +897,8 @@ def update_training_query(self, data = { 'natural_language_query': natural_language_query, - 'filter': filter, - 'examples': examples + 'examples': examples, + 'filter': filter } url = '/v2/projects/{0}/training_data/queries/{1}'.format( @@ -5354,7 +5354,7 @@ class TrainingExample(): :attr str document_id: The document ID associated with this training example. :attr str collection_id: The collection ID associated with this training example. - :attr int relevance: (optional) The relevance of the training example. + :attr int relevance: The relevance of the training example. :attr date created: (optional) The date and time the example was created. :attr date updated: (optional) The date and time the example was updated. """ @@ -5362,8 +5362,8 @@ class TrainingExample(): def __init__(self, document_id, collection_id, + relevance, *, - relevance=None, created=None, updated=None): """ @@ -5373,7 +5373,7 @@ def __init__(self, example. :param str collection_id: The collection ID associated with this training example. - :param int relevance: (optional) The relevance of the training example. + :param int relevance: The relevance of the training example. :param date created: (optional) The date and time the example was created. :param date updated: (optional) The date and time the example was updated. """ @@ -5409,6 +5409,10 @@ def _from_dict(cls, _dict): ) if 'relevance' in _dict: args['relevance'] = _dict.get('relevance') + else: + raise ValueError( + 'Required property \'relevance\' not present in TrainingExample JSON' + ) if 'created' in _dict: args['created'] = _dict.get('created') if 'updated' in _dict: @@ -5450,36 +5454,34 @@ class TrainingQuery(): Object containing training query details. :attr str query_id: (optional) The query ID associated with the training query. - :attr str natural_language_query: (optional) The natural text query for the - training query. + :attr str natural_language_query: The natural text query for the training query. :attr str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. :attr date created: (optional) The date and time the query was created. :attr date updated: (optional) The date and time the query was updated. - :attr list[TrainingExample] examples: (optional) Array of training examples. + :attr list[TrainingExample] examples: Array of training examples. """ def __init__(self, + natural_language_query, + examples, *, query_id=None, - natural_language_query=None, filter=None, created=None, - updated=None, - examples=None): + updated=None): """ Initialize a TrainingQuery object. + :param str natural_language_query: The natural text query for the training + query. + :param list[TrainingExample] examples: Array of training examples. :param str query_id: (optional) The query ID associated with the training query. - :param str natural_language_query: (optional) The natural text query for - the training query. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. :param date created: (optional) The date and time the query was created. :param date updated: (optional) The date and time the query was updated. - :param list[TrainingExample] examples: (optional) Array of training - examples. """ self.query_id = query_id self.natural_language_query = natural_language_query @@ -5505,6 +5507,10 @@ def _from_dict(cls, _dict): args['query_id'] = _dict.get('query_id') if 'natural_language_query' in _dict: args['natural_language_query'] = _dict.get('natural_language_query') + else: + raise ValueError( + 'Required property \'natural_language_query\' not present in TrainingQuery JSON' + ) if 'filter' in _dict: args['filter'] = _dict.get('filter') if 'created' in _dict: @@ -5515,6 +5521,10 @@ def _from_dict(cls, _dict): args['examples'] = [ TrainingExample._from_dict(x) for x in (_dict.get('examples')) ] + else: + raise ValueError( + 'Required property \'examples\' not present in TrainingQuery JSON' + ) return cls(**args) def _to_dict(self): diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index cfc96854f..cbfc342df 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -13,10 +13,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -from ibm_cloud_sdk_core.authenticators.bearer_token_authenticator import BearerTokenAuthenticator +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import json import responses import tempfile +import ibm_watson.discovery_v2 from ibm_watson.discovery_v2 import * base_url = 'https://fake' @@ -79,9 +80,9 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.list_collections(**body) return output @@ -158,9 +159,9 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.query(**body) return output @@ -179,7 +180,7 @@ def construct_full_body(self): "string1", "count": 12345, - "return_": {}, + "return_": [], "offset": 12345, "sort": @@ -197,7 +198,7 @@ def construct_full_body(self): "passages": QueryLargePassages._from_dict( json.loads( - """{"enabled": false, "per_document": true, "fields": [], "count": 5, "characters": 10}""" + """{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""" )), }) return body @@ -259,18 +260,18 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.get_autocompletion(**body) return output def construct_full_body(self): body = dict() body['project_id'] = "string1" - body['collection_ids'] = {"collection_ids": {"mock": "data"}} - body['field'] = "string1" body['prefix'] = "string1" + body['collection_ids'] = [] + body['field'] = "string1" body['count'] = 12345 return body @@ -333,9 +334,9 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.query_notices(**body) return output @@ -345,13 +346,8 @@ def construct_full_body(self): body['filter'] = "string1" body['query'] = "string1" body['natural_language_query'] = "string1" - body['aggregation'] = "string1" body['count'] = 12345 - body['return_'] = {"return_": {"mock": "data"}} body['offset'] = 12345 - body['sort'] = {"sort": {"mock": "data"}} - body['highlight'] = True - body['spelling_suggestions'] = True return body def construct_required_body(self): @@ -411,16 +407,16 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.list_fields(**body) return output def construct_full_body(self): body = dict() body['project_id'] = "string1" - body['collection_ids'] = {"collection_ids": {"mock": "data"}} + body['collection_ids'] = [] return body def construct_required_body(self): @@ -493,9 +489,9 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.get_component_settings(**body) return output @@ -573,9 +569,9 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.add_document(**body) return output @@ -649,9 +645,9 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.update_document(**body) return output @@ -728,9 +724,9 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -813,9 +809,9 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.list_training_queries(**body) return output @@ -882,9 +878,9 @@ def add_mock_response(self, url, response): content_type='') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.delete_training_queries(**body) return output @@ -951,9 +947,9 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.create_training_query(**body) return output @@ -962,14 +958,18 @@ def construct_full_body(self): body['project_id'] = "string1" body.update({ "natural_language_query": "string1", + "examples": [], "filter": "string1", - "examples": [] }) return body def construct_required_body(self): body = dict() body['project_id'] = "string1" + body.update({ + "natural_language_query": "string1", + "examples": [], + }) return body @@ -1025,9 +1025,9 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.get_training_query(**body) return output @@ -1055,7 +1055,7 @@ class TestUpdateTrainingQuery(): @responses.activate def test_update_training_query_response(self): body = self.construct_full_body() - response = fake_response_TrainingExample_json + response = fake_response_TrainingQuery_json send_request(self, body, response) assert len(responses.calls) == 1 @@ -1066,7 +1066,7 @@ def test_update_training_query_response(self): def test_update_training_query_required_response(self): # Check response with required params body = self.construct_required_body() - response = fake_response_TrainingExample_json + response = fake_response_TrainingQuery_json send_request(self, body, response) assert len(responses.calls) == 1 @@ -1075,7 +1075,7 @@ def test_update_training_query_required_response(self): #-------------------------------------------------------- @responses.activate def test_update_training_query_empty(self): - check_empty_required_params(self, fake_response_TrainingExample_json) + check_empty_required_params(self, fake_response_TrainingQuery_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1096,9 +1096,9 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = DiscoveryV2(authenticator=BearerTokenAuthenticator('token'), + service = DiscoveryV2(authenticator=NoAuthAuthenticator(), version='2019-11-22') - service.set_service_url('https://fake') + service.set_service_url(base_url) output = service.update_training_query(**body) return output @@ -1108,8 +1108,8 @@ def construct_full_body(self): body['query_id'] = "string1" body.update({ "natural_language_query": "string1", + "examples": [], "filter": "string1", - "examples": [] }) return body @@ -1119,8 +1119,8 @@ def construct_required_body(self): body['query_id'] = "string1" body.update({ "natural_language_query": "string1", + "examples": [], "filter": "string1", - "examples": [] }) return body @@ -1202,7 +1202,7 @@ def send_request(obj, body, response, url=None): fake_response_ListCollectionsResponse_json = """{"collections": []}""" fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query", "suggested_refinements": [], "table_results": []}""" fake_response_Completions_json = """{"completions": []}""" -fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "results": [], "aggregations": []}""" +fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "notices": []}""" fake_response_ListFieldsResponse_json = """{"fields": []}""" fake_response_ComponentSettingsResponse_json = """{"fields_shown": {"body": {"use_passage": false, "field": "fake_field"}, "title": {"field": "fake_field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": []}""" fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" @@ -1211,4 +1211,4 @@ def send_request(obj, body, response, url=None): fake_response_TrainingQuerySet_json = """{"queries": []}""" fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" -fake_response_TrainingExample_json = """{"document_id": "fake_document_id", "cross_reference": "fake_cross_reference", "relevance": 9}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" From 8f3d7d7789dfa15a0e5a2673ff31af91a48aa1d5 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 21 Nov 2019 12:46:00 -0800 Subject: [PATCH 151/455] doc(speech to text v1): doc updates --- ibm_watson/speech_to_text_v1.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 9865543c4..2697d164e 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1045,6 +1045,10 @@ def create_language_model(self, language model can be used only with the base model for which it is created. The model is owned by the instance of the service whose credentials are used to create it. + You can create a maximum of 1024 custom language models, per credential. The + service returns an error if you attempt to create more than 1024 models. You 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). @@ -2278,6 +2282,10 @@ def create_acoustic_model(self, acoustic model can be used only with the base model for which it is created. The model is owned by the instance of the service whose credentials are used to create it. + You can create a maximum of 1024 custom acoustic models, per credential. The + service returns an error if you attempt to create more than 1024 models. You 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). From a5bec467005db9340f6983654c293c94587258d9 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 21 Nov 2019 14:17:42 -0800 Subject: [PATCH 152/455] feat(VisualRecognitionv4): New method `get_training_usage` --- examples/visual_recognition_v4.py | 8 +- ibm_watson/visual_recognition_v4.py | 374 ++++++++++++++---- .../integration/test_visual_recognition_v4.py | 4 + 3 files changed, 316 insertions(+), 70 deletions(-) diff --git a/examples/visual_recognition_v4.py b/examples/visual_recognition_v4.py index 6ea4eb7b0..bb690deee 100644 --- a/examples/visual_recognition_v4.py +++ b/examples/visual_recognition_v4.py @@ -35,9 +35,15 @@ TrainingDataObject(object='giraffe training data', location=Location(64, 270, 755, 784)) ]).get_result() +print(json.dumps(training_data, indent=2)) # train collection train_result = service.train(collection_id).get_result() +print(json.dumps(train_result, indent=2)) + +# training usage +training_usage = service.get_training_usage() +print(json.dumps(training_usage, indent=2)) # analyze dog_path = os.path.join(os.path.dirname(__file__), '../resources/dog.jpg') @@ -51,7 +57,7 @@ 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() - assert analyze_images is not None + print(json.dumps(analyze_images, indent=2)) # delete collection service.delete_collection(collection_id) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index a70ca9b7e..b20d2a14f 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -16,10 +16,6 @@ """ Provide images to the IBM Watson™ Visual Recognition service for analysis. The service detects objects based on a set of images with training data. -**Beta:** The Visual Recognition v4 API and Object Detection model are beta features. For -more information about beta features, see the [Release -notes](https://cloud.ibm.com/docs/services/visual-recognition?topic=visual-recognition-release-notes#beta). -{: important} """ import json @@ -555,7 +551,10 @@ def get_jpeg_image(self, collection_id, image_id, *, size=None, **kwargs): :param str collection_id: The identifier of the collection. :param str image_id: The identifier of the image. - :param str size: (optional) Specify the image size. + :param str size: (optional) The image size. Specify `thumbnail` to return a + version that maintains the original aspect ratio but is no larger than 200 + pixels in the larger dimension. For example, an original 800 x 1000 image + is resized to 160 x 200 pixels. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -679,6 +678,47 @@ def add_image_training_data(self, response = self.send(request) return response + def get_training_usage(self, *, start_time=None, end_time=None, **kwargs): + """ + Get training usage. + + Information about the completed training events. You can use this information to + determine how close you are to the training limits for the month. + + :param str start_time: (optional) The earliest day to include training + events. Specify dates in YYYY-MM-DD format. If empty or not specified, the + earliest training event is included. + :param str end_time: (optional) The most recent day to include training + events. Specify dates in YYYY-MM-DD format. All events for the day are + included. If empty or not specified, the current day is used. Specify the + same value as `start_time` to request events for a single day. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', + 'get_training_usage') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'start_time': start_time, + 'end_time': end_time + } + + url = '/v4/training_usage' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + ######################### # User data ######################### @@ -736,9 +776,12 @@ class GetJpegImageEnums(object): class Size(Enum): """ - Specify the image size. + The image size. Specify `thumbnail` to return a version that maintains the + original aspect ratio but is no larger than 200 pixels in the larger dimension. + For example, an original 800 x 1000 image is resized to 160 x 200 pixels. """ FULL = 'full' + THUMBNAIL = 'thumbnail' ############################################################################## @@ -1307,7 +1350,8 @@ class Image(): :attr ImageDimensions dimensions: Height and width of an image. :attr DetectedObjects objects: Container for the list of collections that have objects detected in an image. - :attr Error errors: (optional) Details about an error. + :attr list[Error] errors: (optional) A container for the problems in the + request. """ def __init__(self, source, dimensions, objects, *, errors=None): @@ -1318,7 +1362,8 @@ def __init__(self, source, dimensions, objects, *, errors=None): :param ImageDimensions dimensions: Height and width of an image. :param DetectedObjects objects: Container for the list of collections that have objects detected in an image. - :param Error errors: (optional) Details about an error. + :param list[Error] errors: (optional) A container for the problems in the + request. """ self.source = source self.dimensions = dimensions @@ -1352,7 +1397,9 @@ def _from_dict(cls, _dict): raise ValueError( 'Required property \'objects\' not present in Image JSON') if 'errors' in _dict: - args['errors'] = Error._from_dict(_dict.get('errors')) + args['errors'] = [ + Error._from_dict(x) for x in (_dict.get('errors')) + ] return cls(**args) def _to_dict(self): @@ -1365,7 +1412,7 @@ def _to_dict(self): if hasattr(self, 'objects') and self.objects is not None: _dict['objects'] = self.objects._to_dict() if hasattr(self, 'errors') and self.errors is not None: - _dict['errors'] = self.errors._to_dict() + _dict['errors'] = [x._to_dict() for x in self.errors] return _dict def __str__(self): @@ -1387,38 +1434,40 @@ class ImageDetails(): """ Details about an image. - :attr str image_id: The identifier of the image. - :attr datetime updated: Date and time in Coordinated Universal Time (UTC) that - the image was most recently updated. - :attr datetime created: Date and time in Coordinated Universal Time (UTC) that - the image was created. + :attr str image_id: (optional) The identifier of the image. + :attr datetime updated: (optional) Date and time in Coordinated Universal Time + (UTC) that the image was most recently updated. + :attr datetime created: (optional) Date and time in Coordinated Universal Time + (UTC) that the image was created. :attr ImageSource source: The source type of the image. - :attr ImageDimensions dimensions: Height and width of an image. - :attr Error errors: (optional) Details about an error. - :attr TrainingDataObjects training_data: Training data for all objects. + :attr ImageDimensions dimensions: (optional) Height and width of an image. + :attr list[Error] errors: (optional) + :attr TrainingDataObjects training_data: (optional) Training data for all + objects. """ def __init__(self, - image_id, - updated, - created, source, - dimensions, - training_data, *, - errors=None): + image_id=None, + updated=None, + created=None, + dimensions=None, + errors=None, + training_data=None): """ Initialize a ImageDetails object. - :param str image_id: The identifier of the image. - :param datetime updated: Date and time in Coordinated Universal Time (UTC) - that the image was most recently updated. - :param datetime created: Date and time in Coordinated Universal Time (UTC) - that the image was created. :param ImageSource source: The source type of the image. - :param ImageDimensions dimensions: Height and width of an image. - :param TrainingDataObjects training_data: Training data for all objects. - :param Error errors: (optional) Details about an error. + :param str image_id: (optional) The identifier of the image. + :param datetime updated: (optional) Date and time in Coordinated Universal + Time (UTC) that the image was most recently updated. + :param datetime created: (optional) Date and time in Coordinated Universal + Time (UTC) that the image was created. + :param ImageDimensions dimensions: (optional) Height and width of an image. + :param list[Error] errors: (optional) + :param TrainingDataObjects training_data: (optional) Training data for all + objects. """ self.image_id = image_id self.updated = updated @@ -1443,22 +1492,10 @@ def _from_dict(cls, _dict): + ', '.join(bad_keys)) if 'image_id' in _dict: args['image_id'] = _dict.get('image_id') - else: - raise ValueError( - 'Required property \'image_id\' not present in ImageDetails JSON' - ) if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) - else: - raise ValueError( - 'Required property \'updated\' not present in ImageDetails JSON' - ) if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) - else: - raise ValueError( - 'Required property \'created\' not present in ImageDetails JSON' - ) if 'source' in _dict: args['source'] = ImageSource._from_dict(_dict.get('source')) else: @@ -1467,19 +1504,13 @@ def _from_dict(cls, _dict): if 'dimensions' in _dict: args['dimensions'] = ImageDimensions._from_dict( _dict.get('dimensions')) - else: - raise ValueError( - 'Required property \'dimensions\' not present in ImageDetails JSON' - ) if 'errors' in _dict: - args['errors'] = Error._from_dict(_dict.get('errors')) + args['errors'] = [ + Error._from_dict(x) for x in (_dict.get('errors')) + ] if 'training_data' in _dict: args['training_data'] = TrainingDataObjects._from_dict( _dict.get('training_data')) - else: - raise ValueError( - 'Required property \'training_data\' not present in ImageDetails JSON' - ) return cls(**args) def _to_dict(self): @@ -1496,7 +1527,7 @@ def _to_dict(self): if hasattr(self, 'dimensions') and self.dimensions is not None: _dict['dimensions'] = self.dimensions._to_dict() if hasattr(self, 'errors') and self.errors is not None: - _dict['errors'] = self.errors._to_dict() + _dict['errors'] = [x._to_dict() for x in self.errors] if hasattr(self, 'training_data') and self.training_data is not None: _dict['training_data'] = self.training_data._to_dict() return _dict @@ -1593,16 +1624,16 @@ class ImageDimensions(): """ Height and width of an image. - :attr int height: Height in pixels of the image. - :attr int width: Width in pixels of the image. + :attr int height: (optional) Height in pixels of the image. + :attr int width: (optional) Width in pixels of the image. """ - def __init__(self, height, width): + def __init__(self, *, height=None, width=None): """ Initialize a ImageDimensions object. - :param int height: Height in pixels of the image. - :param int width: Width in pixels of the image. + :param int height: (optional) Height in pixels of the image. + :param int width: (optional) Width in pixels of the image. """ self.height = height self.width = width @@ -1619,16 +1650,8 @@ def _from_dict(cls, _dict): + ', '.join(bad_keys)) if 'height' in _dict: args['height'] = _dict.get('height') - else: - raise ValueError( - 'Required property \'height\' not present in ImageDimensions JSON' - ) if 'width' in _dict: args['width'] = _dict.get('width') - else: - raise ValueError( - 'Required property \'width\' not present in ImageDimensions JSON' - ) return cls(**args) def _to_dict(self): @@ -2270,6 +2293,219 @@ def __ne__(self, other): return not self == other +class TrainingEvent(): + """ + Details about the training event. + + :attr str type: (optional) Trained object type. Only `objects` is currently + supported. + :attr str collection_id: (optional) Identifier of the trained collection. + :attr datetime completion_time: (optional) Date and time in Coordinated + Universal Time (UTC) that training on the collection finished. + :attr str status: (optional) Training status of the training event. + :attr int image_count: (optional) The total number of images that were used in + training for this training event. + """ + + def __init__(self, + *, + type=None, + collection_id=None, + completion_time=None, + status=None, + image_count=None): + """ + Initialize a TrainingEvent object. + + :param str type: (optional) Trained object type. Only `objects` is + currently supported. + :param str collection_id: (optional) Identifier of the trained collection. + :param datetime completion_time: (optional) Date and time in Coordinated + Universal Time (UTC) that training on the collection finished. + :param str status: (optional) Training status of the training event. + :param int image_count: (optional) The total number of images that were + used in training for this training event. + """ + self.type = type + self.collection_id = collection_id + self.completion_time = completion_time + self.status = status + self.image_count = image_count + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingEvent object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'collection_id', 'completion_time', 'status', 'image_count' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TrainingEvent: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'completion_time' in _dict: + args['completion_time'] = string_to_datetime( + _dict.get('completion_time')) + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'image_count' in _dict: + args['image_count'] = _dict.get('image_count') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, + 'completion_time') and self.completion_time is not None: + _dict['completion_time'] = datetime_to_string(self.completion_time) + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + if hasattr(self, 'image_count') and self.image_count is not None: + _dict['image_count'] = self.image_count + return _dict + + def __str__(self): + """Return a `str` version of this TrainingEvent object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(Enum): + """ + Trained object type. Only `objects` is currently supported. + """ + OBJECTS = "objects" + + class StatusEnum(Enum): + """ + Training status of the training event. + """ + FAILED = "failed" + SUCCEEDED = "succeeded" + + +class TrainingEvents(): + """ + Details about the training events. + + :attr datetime start_time: (optional) The starting day for the returned training + events in Coordinated Universal Time (UTC). If not specified in the request, it + identifies the earliest training event. + :attr datetime end_time: (optional) The ending day for the returned training + events in Coordinated Universal Time (UTC). If not specified in the request, it + lists the current time. + :attr int completed_events: (optional) The total number of training events in + the response for the start and end times. + :attr int trained_images: (optional) The total number of images that were used + in training for the start and end times. + :attr list[TrainingEvent] events: (optional) The completed training events for + the start and end time. + """ + + def __init__(self, + *, + start_time=None, + end_time=None, + completed_events=None, + trained_images=None, + events=None): + """ + Initialize a TrainingEvents object. + + :param datetime start_time: (optional) The starting day for the returned + training events in Coordinated Universal Time (UTC). If not specified in + the request, it identifies the earliest training event. + :param datetime end_time: (optional) The ending day for the returned + training events in Coordinated Universal Time (UTC). If not specified in + the request, it lists the current time. + :param int completed_events: (optional) The total number of training events + in the response for the start and end times. + :param int trained_images: (optional) The total number of images that were + used in training for the start and end times. + :param list[TrainingEvent] events: (optional) The completed training events + for the start and end time. + """ + self.start_time = start_time + self.end_time = end_time + self.completed_events = completed_events + self.trained_images = trained_images + self.events = events + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingEvents object from a json dictionary.""" + args = {} + valid_keys = [ + 'start_time', 'end_time', 'completed_events', 'trained_images', + 'events' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TrainingEvents: ' + + ', '.join(bad_keys)) + if 'start_time' in _dict: + args['start_time'] = string_to_datetime(_dict.get('start_time')) + if 'end_time' in _dict: + args['end_time'] = string_to_datetime(_dict.get('end_time')) + if 'completed_events' in _dict: + args['completed_events'] = _dict.get('completed_events') + if 'trained_images' in _dict: + args['trained_images'] = _dict.get('trained_images') + if 'events' in _dict: + args['events'] = [ + TrainingEvent._from_dict(x) for x in (_dict.get('events')) + ] + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'start_time') and self.start_time is not None: + _dict['start_time'] = datetime_to_string(self.start_time) + if hasattr(self, 'end_time') and self.end_time is not None: + _dict['end_time'] = datetime_to_string(self.end_time) + if hasattr(self, + 'completed_events') and self.completed_events is not None: + _dict['completed_events'] = self.completed_events + if hasattr(self, 'trained_images') and self.trained_images is not None: + _dict['trained_images'] = self.trained_images + if hasattr(self, 'events') and self.events is not None: + _dict['events'] = [x._to_dict() for x in self.events] + return _dict + + def __str__(self): + """Return a `str` version of this TrainingEvents object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TrainingStatus(): """ Training status information for the collection. @@ -2442,7 +2678,7 @@ def _from_dict(cls, _dict): 'Unrecognized keys detected in dictionary for class FileWithMetadata: ' + ', '.join(bad_keys)) if 'data' in _dict: - args['data'] = _dict.get('data') + args['data'] = file._from_dict(_dict.get('data')) else: raise ValueError( 'Required property \'data\' not present in FileWithMetadata JSON' @@ -2457,7 +2693,7 @@ def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'data') and self.data is not None: - _dict['data'] = self.data.__str__() + _dict['data'] = self.data._to_dict() if hasattr(self, 'filename') and self.filename is not None: _dict['filename'] = self.filename if hasattr(self, 'content_type') and self.content_type is not None: diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index 8ed3aa073..abfb07854 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -120,5 +120,9 @@ def test_04_training(self): 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').get_result() + assert training_usage is not None + # delete collection self.visual_recognition.delete_collection(collection_id) From 55760599c03d1dcd5f7e8f3d49dd20ec5bdb335e Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 21 Nov 2019 14:30:29 -0800 Subject: [PATCH 153/455] chore(visual recognition v3): Apply manual changes for threshold --- ibm_watson/visual_recognition_v3.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 24cfb08d1..bfa038545 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -166,7 +166,7 @@ def classify(self, form_data.append(('url', (None, url, 'text/plain'))) if threshold: form_data.append( - ('threshold', (None, threshold, 'application/json'))) + ('threshold', (None, str(threshold), 'application/json'))) if owners: owners = self._convert_list(owners) form_data.append(('owners', (None, owners, 'text/plain'))) From 1e3d594efc20c93b0c81f5777c760ad1b9c956d6 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 21 Nov 2019 14:30:47 -0800 Subject: [PATCH 154/455] chore(visual recognition v4): Apply manual changes for threshold --- ibm_watson/visual_recognition_v4.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index b20d2a14f..a1218ce84 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -154,7 +154,7 @@ def analyze(self, form_data.append(('image_url', (None, item, 'text/plain'))) if threshold: form_data.append( - ('threshold', (None, threshold, 'application/json'))) + ('threshold', (None, str(threshold), 'application/json'))) url = '/v4/analyze' request = self.prepare_request(method='POST', From 9259b89441785c1c856ef5cf711c596f81f39abc Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 21 Nov 2019 14:38:09 -0800 Subject: [PATCH 155/455] chore(visual recognition v4): Apply manual changes to FileWithMetadata --- ibm_watson/visual_recognition_v4.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index a1218ce84..7ccad5166 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -2693,7 +2693,7 @@ def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'data') and self.data is not None: - _dict['data'] = self.data._to_dict() + _dict['data'] = self.data if hasattr(self, 'filename') and self.filename is not None: _dict['filename'] = self.filename if hasattr(self, 'content_type') and self.content_type is not None: From f42de897bd4cceffaaff59d03a4cb0f5d538cf62 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 21 Nov 2019 14:39:54 -0800 Subject: [PATCH 156/455] test(vr4): Update vr4 with generated tests --- test/unit/test_visual_recognition_v4.py | 1691 ++++++++++++++--------- 1 file changed, 1034 insertions(+), 657 deletions(-) diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index ffc1d4f01..7ac33bf40 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1,3 +1,4 @@ +# -*- coding: utf-8 -*- # (C) Copyright IBM Corp. 2019. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -12,824 +13,1200 @@ # See the License for the specific language governing permissions and # limitations under the License. -import json -import ibm_watson -from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import responses -import os -import jwt -import time -from unittest import TestCase -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -platform_url = 'https://gateway.watsonplatform.net' -service_path = '/visual-recognition/api' -base_url = '{0}{1}'.format(platform_url, service_path) - - -def get_access_token(): - access_token_layout = { - "username": "dummy", - "role": "Admin", - "permissions": ["administrator", "manage_catalog"], - "sub": "admin", - "iss": "sss", - "aud": "sss", - "uid": "sss", - "iat": 3600, - "exp": int(time.time()) - } - - access_token = jwt.encode( - access_token_layout, - 'secret', - algorithm='HS256', - headers={'kid': '230498151c214b788dd97f22b85410a5'}) - return access_token.decode('utf-8') - - -class TestVisualRecognitionV4(TestCase): - - @classmethod - def setUp(cls): - iam_url = "https://iam.cloud.ibm.com/identity/token" - iam_token_response = { - "access_token": get_access_token(), - "token_type": "Bearer", - "expires_in": 3600, - "expiration": 1524167011, - "refresh_token": "jy4gl91BQ" - } - responses.add(responses.POST, - url=iam_url, - body=json.dumps(iam_token_response), - status=200) +import tempfile +import ibm_watson.visual_recognition_v4 +from ibm_watson.visual_recognition_v4 import * + +base_url = 'https://gateway.watsonplatform.net/visual-recognition/api' + +############################################################################## +# Start of Service: Analysis +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for analyze +#----------------------------------------------------------------------------- +class TestAnalyze(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_analyze_response(self): + body = self.construct_full_body() + response = fake_response_AnalyzeResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - ######################### - # analysis - ######################### + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_analyze_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AnalyzeResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_analyze(self): + def test_analyze_empty(self): + check_empty_required_params(self, fake_response_AnalyzeResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v4/analyze' url = '{0}{1}'.format(base_url, endpoint) - response = { - "images": [{ - "objects": { - "collections": [{ - "collection_id": - "collection_id", - "objects": [{ - "score": 7.0614014, - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }, { - "score": 7.0614014, - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }] - }, { - "collection_id": - "collection_id", - "objects": [{ - "score": 7.0614014, - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }, { - "score": 7.0614014, - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }] - }] - }, - "source": { - "archive_filename": "archive_filename", - "filename": "filename", - "type": "file", - "resolved_url": "resolved_url", - "source_url": "source_url" - }, - "errors": { - "code": - "invalid_field", - "message": - "The date provided for `version` is not valid. Specify dates in `YYYY-MM-DD` format.", - "more_info": - "https://cloud.ibm.com/apidocs/visual-recognition-v4#versioning", - "target": { - "type": "parameter", - "name": "version" - } - }, - "dimensions": { - "width": 6, - "height": 0 - } - }, { - "objects": { - "collections": [{ - "collection_id": - "collection_id", - "objects": [{ - "score": 7.0614014, - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }, { - "score": 7.0614014, - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }] - }, { - "collection_id": - "collection_id", - "objects": [{ - "score": 7.0614014, - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }, { - "score": 7.0614014, - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }] - }] - }, - "source": { - "archive_filename": "archive_filename", - "filename": "filename", - "type": "file", - "resolved_url": "resolved_url", - "source_url": "source_url" - }, - "errors": { - "code": - "invalid_field", - "message": - "The date provided for `version` is not valid. Specify dates in `YYYY-MM-DD` format.", - "more_info": - "https://cloud.ibm.com/apidocs/visual-recognition-v4#versioning", - "target": { - "type": "parameter", - "name": "version" - } - }, - "dimensions": { - "width": 6, - "height": 0 - } - }], - "trace": - "trace", - "warnings": [{ - "code": "invalid_field", - "more_info": "more_info", - "message": "message" - }, { - "code": "invalid_field", - "more_info": "more_info", - "message": "message" - }] - } + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, url, body=json.dumps(response), status=200, content_type='application/json') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.analyze(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_ids'] = ['collection_id1, collection_id2'] + body['features'] = ['test'] + body['image_url'] = ['https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/American_Eskimo_Dog.jpg/1280px-American_Eskimo_Dog.jpg'] + body['threshold'] = 12345.0 + body['images_file'] = [FileWithMetadata(tempfile.NamedTemporaryFile())] + return body + + def construct_required_body(self): + body = dict() + body['collection_ids'] = ['fake'] + body['features'] = [AnalyzeEnums.Features.OBJECTS.value] + return body + + +# endregion +############################################################################## +# End of Service: Analysis +############################################################################## + +############################################################################## +# Start of Service: Collections +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for create_collection +#----------------------------------------------------------------------------- +class TestCreateCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_collection_response(self): + body = self.construct_full_body() + response = fake_response_Collection_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_create_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_collection_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 - with open( - os.path.join(os.path.dirname(__file__), - '../../resources/cars.zip'), 'rb') as cars: - detailed_response = service.analyze( - collection_ids=['collection_id1, collection_id2'], - features=[AnalyzeEnums.Features.OBJECTS.value], - images_file=[FileWithMetadata(cars)], - image_url=[ - 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/American_Eskimo_Dog.jpg/1280px-American_Eskimo_Dog.jpg' - ], - threshold='0.2') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 - - ######################### - # collections - ######################### - - @responses.activate - def test_create_collection(self): + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v4/collections' url = '{0}{1}'.format(base_url, endpoint) - response = { - "collection_id": "collection_id", - "training_status": { - "objects": { - "in_progress": "true", - "data_changed": "true", - "ready": "true", - "latest_failed": "true", - "description": "description" - } - }, - "created": "2000-01-23T04:56:07.000+00:00", - "name": "name", - "description": "description", - "image_count": 0, - "updated": "2000-01-23T04:56:07.000+00:00" - } + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, url, body=json.dumps(response), status=200, content_type='application/json') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) - detailed_response = service.create_collection(name='name', - description='description') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 + output = service.create_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "name": "string1", + "description": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body.update({ + "name": "string1", + "description": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_collections +#----------------------------------------------------------------------------- +class TestListCollections(): + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_list_collections(self): + def test_list_collections_response(self): + body = self.construct_full_body() + response = fake_response_CollectionsList_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_collections_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CollectionsList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collections_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v4/collections' url = '{0}{1}'.format(base_url, endpoint) - response = { - "collections": [{ - "collection_id": "collection_id", - "training_status": { - "objects": { - "in_progress": "true", - "data_changed": "true", - "ready": "true", - "latest_failed": "true", - "description": "description" - } - }, - "created": "2000-01-23T04:56:07.000+00:00", - "name": "name", - "description": "description", - "image_count": 0, - "updated": "2000-01-23T04:56:07.000+00:00" - }, { - "collection_id": "collection_id", - "training_status": { - "objects": { - "in_progress": "true", - "data_changed": "true", - "ready": "true", - "latest_failed": "true", - "description": "description" - } - }, - "created": "2000-01-23T04:56:07.000+00:00", - "name": "name", - "description": "description", - "image_count": 0, - "updated": "2000-01-23T04:56:07.000+00:00" - }] - } + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, url, body=json.dumps(response), status=200, content_type='application/json') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.list_collections(**body) + return output - detailed_response = service.list_collections() - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 + def construct_full_body(self): + body = dict() + return body + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_collection +#----------------------------------------------------------------------------- +class TestGetCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_get_collection(self): - endpoint = '/v4/collections/{0}'.format('collection_id') + def test_get_collection_response(self): + body = self.construct_full_body() + response = fake_response_Collection_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_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_collection_empty(self): + check_empty_required_params(self, fake_response_Collection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v4/collections/{0}'.format(body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) - response = { - "collection_id": "collection_id", - "training_status": { - "objects": { - "in_progress": "true", - "data_changed": "true", - "ready": "true", - "latest_failed": "true", - "description": "description" - } - }, - "created": "2000-01-23T04:56:07.000+00:00", - "name": "name", - "description": "description", - "image_count": 0, - "updated": "2000-01-23T04:56:07.000+00:00" - } + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, url, body=json.dumps(response), status=200, content_type='application/json') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.get_collection(**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 - detailed_response = service.get_collection( - collection_id='collection_id') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 +#----------------------------------------------------------------------------- +# Test Class for update_collection +#----------------------------------------------------------------------------- +class TestUpdateCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_response(self): + body = self.construct_full_body() + response = fake_response_Collection_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_collection(self): - endpoint = '/v4/collections/{0}'.format('collection_id') + def test_update_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_empty(self): + check_empty_required_params(self, fake_response_Collection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v4/collections/{0}'.format(body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) - response = { - "collection_id": "collection_id", - "training_status": { - "objects": { - "in_progress": "true", - "data_changed": "true", - "ready": "true", - "latest_failed": "true", - "description": "description" - } - }, - "created": "2000-01-23T04:56:07.000+00:00", - "name": "name", - "description": "description", - "image_count": 0, - "updated": "2000-01-23T04:56:07.000+00:00" - } + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, url, body=json.dumps(response), status=200, content_type='application/json') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.update_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_id'] = "string1" + body.update({ + "name": "string1", + "description": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body['collection_id'] = "string1" + return body - detailed_response = service.update_collection( - collection_id='collection_id', - name='name', - description='description') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 +#----------------------------------------------------------------------------- +# Test Class for delete_collection +#----------------------------------------------------------------------------- +class TestDeleteCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_collection_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_collection(self): - endpoint = '/v4/collections/{0}'.format('collection_id') + def test_delete_collection_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_collection_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}'.format(body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) - response = {} + return url + + def add_mock_response(self, url, response): responses.add(responses.DELETE, url, body=json.dumps(response), status=200, content_type='') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.delete_collection(**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 - detailed_response = service.delete_collection( - collection_id='collection_id') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 - # ######################### - # # images - # ######################### +# endregion +############################################################################## +# End of Service: Collections +############################################################################## + +############################################################################## +# Start of Service: Images +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for add_images +#----------------------------------------------------------------------------- +class TestAddImages(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_images_response(self): + body = self.construct_full_body() + response = fake_response_ImageDetailsList_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_add_images(self): - endpoint = '/v4/collections/{0}/images'.format('collection_id') + def test_add_images_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ImageDetailsList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_images_empty(self): + check_empty_required_params(self, fake_response_ImageDetailsList_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v4/collections/{0}/images'.format(body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) - response = { - "images": [{ - "training_data": { - "objects": [{ - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }, { - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }] - }, - "created": "2000-01-23T04:56:07.000+00:00", - "source": { - "archive_filename": "archive_filename", - "filename": "filename", - "type": "file", - "resolved_url": "resolved_url", - "source_url": "source_url" - }, - "image_id": "image_id", - "updated": "2000-01-23T04:56:07.000+00:00", - "errors": { - "code": - "invalid_field", - "message": - "The date provided for `version` is not valid. Specify dates in `YYYY-MM-DD` format.", - "more_info": - "https://cloud.ibm.com/apidocs/visual-recognition-v4#versioning", - "target": { - "type": "parameter", - "name": "version" - } - }, - "dimensions": { - "width": 6, - "height": 0 - } - }, { - "training_data": { - "objects": [{ - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }, { - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }] - }, - "created": "2000-01-23T04:56:07.000+00:00", - "source": { - "archive_filename": "archive_filename", - "filename": "filename", - "type": "file", - "resolved_url": "resolved_url", - "source_url": "source_url" - }, - "image_id": "image_id", - "updated": "2000-01-23T04:56:07.000+00:00", - "errors": { - "code": - "invalid_field", - "message": - "The date provided for `version` is not valid. Specify dates in `YYYY-MM-DD` format.", - "more_info": - "https://cloud.ibm.com/apidocs/visual-recognition-v4#versioning", - "target": { - "type": "parameter", - "name": "version" - } - }, - "dimensions": { - "width": 6, - "height": 0 - } - }], - "trace": - "trace", - "warnings": [{ - "code": "invalid_field", - "more_info": "more_info", - "message": "message" - }, { - "code": "invalid_field", - "more_info": "more_info", - "message": "message" - }] - } + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, url, body=json.dumps(response), status=200, content_type='application/json') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.add_images(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_id'] = "string1" + body['images_file'] = [] + body['image_url'] = [] + body['training_data'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['collection_id'] = "string1" + return body - detailed_response = service.add_images(collection_id='collection_id', - image_url='image_url', - training_data='training_data') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 +#----------------------------------------------------------------------------- +# Test Class for list_images +#----------------------------------------------------------------------------- +class TestListImages(): + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_list_images(self): - endpoint = '/v4/collections/{0}/images'.format('collection_id') + def test_list_images_response(self): + body = self.construct_full_body() + response = fake_response_ImageSummaryList_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_images_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ImageSummaryList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_images_empty(self): + check_empty_required_params(self, fake_response_ImageSummaryList_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v4/collections/{0}/images'.format(body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) - response = { - "images": [{ - "image_id": "image_id", - "updated": "2000-01-23T04:56:07.000+00:00" - }, { - "image_id": "image_id", - "updated": "2000-01-23T04:56:07.000+00:00" - }] - } + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, url, body=json.dumps(response), status=200, content_type='application/json') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.list_images(**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 - detailed_response = service.list_images(collection_id='collection_id') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 +#----------------------------------------------------------------------------- +# Test Class for get_image_details +#----------------------------------------------------------------------------- +class TestGetImageDetails(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_image_details_response(self): + body = self.construct_full_body() + response = fake_response_ImageDetails_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_image_details(self): + def test_get_image_details_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ImageDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_image_details_empty(self): + check_empty_required_params(self, fake_response_ImageDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v4/collections/{0}/images/{1}'.format( - 'collection_id', 'image_id').format('image_id') + body['collection_id'], body['image_id']) url = '{0}{1}'.format(base_url, endpoint) - response = { - "training_data": { - "objects": [{ - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }, { - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }] - }, - "created": "2000-01-23T04:56:07.000+00:00", - "source": { - "archive_filename": "archive_filename", - "filename": "filename", - "type": "file", - "resolved_url": "resolved_url", - "source_url": "source_url" - }, - "image_id": "image_id", - "updated": "2000-01-23T04:56:07.000+00:00", - "errors": { - "code": - "invalid_field", - "message": - "The date provided for `version` is not valid. Specify dates in `YYYY-MM-DD` format.", - "more_info": - "https://cloud.ibm.com/apidocs/visual-recognition-v4#versioning", - "target": { - "type": "parameter", - "name": "version" - } - }, - "dimensions": { - "width": 6, - "height": 0 - } - } + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, url, body=json.dumps(response), status=200, content_type='application/json') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.get_image_details(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_id'] = "string1" + body['image_id'] = "string1" + return body - detailed_response = service.get_image_details( - collection_id='collection_id', image_id='image_id') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 + def construct_required_body(self): + body = dict() + body['collection_id'] = "string1" + body['image_id'] = "string1" + return body + +#----------------------------------------------------------------------------- +# Test Class for delete_image +#----------------------------------------------------------------------------- +class TestDeleteImage(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_image_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_image_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_image(self): + def test_delete_image_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}/images/{1}'.format( - 'collection_id', 'image_id').format('image_id') + body['collection_id'], body['image_id']) url = '{0}{1}'.format(base_url, endpoint) - response = {} + return url + + def add_mock_response(self, url, response): responses.add(responses.DELETE, url, body=json.dumps(response), status=200, content_type='') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.delete_image(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_id'] = "string1" + body['image_id'] = "string1" + return body - detailed_response = service.delete_image(collection_id='collection_id', - image_id='image_id') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 + def construct_required_body(self): + body = dict() + body['collection_id'] = "string1" + body['image_id'] = "string1" + return body + +#----------------------------------------------------------------------------- +# Test Class for get_jpeg_image +#----------------------------------------------------------------------------- +class TestGetJpegImage(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_get_jpeg_image(self): + def test_get_jpeg_image_response(self): + body = self.construct_full_body() + response = fake_response_BinaryIO_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_jpeg_image_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BinaryIO_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_jpeg_image_empty(self): + check_empty_required_params(self, fake_response_BinaryIO_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v4/collections/{0}/images/{1}/jpeg'.format( - 'collection_id', 'image_id').format('image_id') + body['collection_id'], body['image_id']) url = '{0}{1}'.format(base_url, endpoint) - response = {} + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, url, body=json.dumps(response), status=200, content_type='') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.get_jpeg_image(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_id'] = "string1" + body['image_id'] = "string1" + body['size'] = "string1" + return body - detailed_response = service.get_jpeg_image( - collection_id='collection_id', image_id='image_id', size='size') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 + def construct_required_body(self): + body = dict() + body['collection_id'] = "string1" + body['image_id'] = "string1" + return body - ######################### - # training - ######################### +# endregion +############################################################################## +# End of Service: Images +############################################################################## + +############################################################################## +# Start of Service: Training +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for train +#----------------------------------------------------------------------------- +class TestTrain(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_train(self): - endpoint = '/v4/collections/{0}/train'.format('collection_id') + def test_train_response(self): + body = self.construct_full_body() + response = fake_response_Collection_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_train_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_train_empty(self): + check_empty_required_params(self, fake_response_Collection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v4/collections/{0}/train'.format(body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) - response = { - "collection_id": "collection_id", - "training_status": { - "objects": { - "in_progress": "true", - "data_changed": "true", - "ready": "true", - "latest_failed": "true", - "description": "description" - } - }, - "created": "2000-01-23T04:56:07.000+00:00", - "name": "name", - "description": "description", - "image_count": 0, - "updated": "2000-01-23T04:56:07.000+00:00" - } + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, url, body=json.dumps(response), status=202, content_type='application/json') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.train(**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 add_image_training_data +#----------------------------------------------------------------------------- +class TestAddImageTrainingData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_image_training_data_response(self): + body = self.construct_full_body() + response = fake_response_TrainingDataObjects_json + send_request(self, body, response) + assert len(responses.calls) == 1 - detailed_response = service.train(collection_id='collection_id') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_image_training_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingDataObjects_json + send_request(self, body, response) + assert len(responses.calls) == 1 + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_add_image_training_data(self): + def test_add_image_training_data_empty(self): + check_empty_required_params(self, + fake_response_TrainingDataObjects_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v4/collections/{0}/images/{1}/training_data'.format( - 'collection_id', 'image_id') + body['collection_id'], body['image_id']) url = '{0}{1}'.format(base_url, endpoint) - response = { - "objects": [{ - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }, { - "location": { - "top": 1, - "left": 5, - "width": 5, - "height": 2 - }, - "object": "object" - }] - } + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, url, body=json.dumps(response), status=200, content_type='application/json') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') + service.set_service_url(base_url) + output = service.add_image_training_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_id'] = "string1" + body['image_id'] = "string1" + body.update({ + "objects": [], + }) + return body + + def construct_required_body(self): + body = dict() + body['collection_id'] = "string1" + body['image_id'] = "string1" + body.update({ + "objects": [], + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_training_usage +#----------------------------------------------------------------------------- +class TestGetTrainingUsage(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_usage_response(self): + body = self.construct_full_body() + response = fake_response_TrainingEvents_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_training_usage_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingEvents_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_usage_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v4/training_usage' + 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_training_usage(**body) + return output - detailed_response = service.add_image_training_data( - collection_id='collection_id', image_id='image_id') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 + def construct_full_body(self): + body = dict() + body['start_time'] = "string1" + body['end_time'] = "string1" + return body - ######################### - # userData - ######################### + def construct_required_body(self): + body = dict() + return body + +# endregion +############################################################################## +# End of Service: Training +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_delete_user_data(self): + def test_delete_user_data_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_user_data_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_user_data_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/user_data' url = '{0}{1}'.format(base_url, endpoint) - response = {} + return url + + def add_mock_response(self, url, response): responses.add(responses.DELETE, url, body=json.dumps(response), status=202, content_type='') - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.VisualRecognitionV4('YYYY-MM-DD', - authenticator=authenticator) + def call_service(self, body): + service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), + version='2019-02-11') service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### - detailed_response = service.delete_user_data(customer_id='customer_id') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 +fake_response__json = None +fake_response_AnalyzeResponse_json = """{"images": [], "warnings": [], "trace": "fake_trace"}""" +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_CollectionsList_json = """{"collections": []}""" +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_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_ImageDetailsList_json = """{"images": [], "warnings": [], "trace": "fake_trace"}""" +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_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": []}""" From d70b41e324cbbfa66dcf1f1b12446029bf8c5578 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 21 Nov 2019 14:45:48 -0800 Subject: [PATCH 157/455] doc(discovery v2): Update documentation for discovery v2 --- README.md | 4 ++++ examples/discovery_v2.py | 1 + 2 files changed, 5 insertions(+) diff --git a/README.md b/README.md index 7aeffb6b9..53828a843 100755 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Python client library to quickly get started with the various [Watson APIs][wdc] * [Before you begin](#before-you-begin) * [Installation](#installation) * [Examples](#examples) + * [Discovery v2 only on CP4D](#discovery-v2-only-on-cp4d) * [Running in IBM Cloud](#running-in-ibm-cloud) * [Authentication](#authentication) * [Getting credentials](#getting-credentials) @@ -83,6 +84,9 @@ For more details see [#405](https://github.com/watson-developer-cloud/python-sdk The [examples][examples] folder has basic and advanced examples. The examples within each service assume that you already have [service credentials](#getting-credentials). +## Discovery v2 only on CP4D +Discovery v2 is only available on Cloud Pak for Data. + ## Running in IBM Cloud If you run your app in IBM Cloud, the SDK gets credentials from the [`VCAP_SERVICES`][vcap_services] environment variable. diff --git a/examples/discovery_v2.py b/examples/discovery_v2.py index dfcd2f917..f148e4d67 100644 --- a/examples/discovery_v2.py +++ b/examples/discovery_v2.py @@ -4,6 +4,7 @@ from ibm_watson.discovery_v2 import TrainingExample from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator, BearerTokenAuthenticator +## Important: Discovery v2 is only available on Cloud Pak for Data. ## ## Authentication ## ## Option 1: username/password From 88e2c0806882693d175c5b8aedb1bf187223db79 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 21 Nov 2019 14:57:37 -0800 Subject: [PATCH 158/455] fix(semrelease): Provide proper git message for semantic release --- .bumpversion.cfg | 1 - .releaserc | 31 +++++++++++++++++-------------- .travis.yml | 28 ++++++++++++++++++---------- 3 files changed, 35 insertions(+), 25 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index b55bcb966..9daceebe7 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,7 +1,6 @@ [bumpversion] current_version = 4.0.3 commit = True -message = [skip ci] Bump version: {current_version} -> {new_version} [bumpversion:file:ibm_watson/version.py] search = __version__ = '{current_version}' diff --git a/.releaserc b/.releaserc index 7bca89531..4ee525055 100644 --- a/.releaserc +++ b/.releaserc @@ -1,18 +1,21 @@ { - "branch": "master", - "verifyConditions": ["@semantic-release/changelog", "@semantic-release/github"], "debug": true, - "prepare": [ + "plugins": [ + "@semantic-release/commit-analyzer", + "@semantic-release/release-notes-generator", "@semantic-release/changelog", - "@semantic-release/git", - { - "path": "@semantic-release/exec", - "cmd": "bumpversion --current-version ${lastRelease.version} --new-version ${nextRelease.version} patch" - } - ], - "publish": [ - { - "path": "@semantic-release/github" - } + [ + "@semantic-release/exec", + { + "prepareCmd": "bumpversion --allow-dirty --current-version ${lastRelease.version} --new-version ${nextRelease.version} patch" + } + ], + [ + "@semantic-release/git", + { + "message": "chore(release): ${nextRelease.version} release notes\n\n${nextRelease.notes}" + } + ], + "@semantic-release/github" ] -} \ No newline at end of file +} diff --git a/.travis.yml b/.travis.yml index 62e0621b9..b32f1e8e7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,34 +1,42 @@ language: python + matrix: include: - python: 3.5 - python: 3.6 - python: 3.7 - python: 3.8 -cache: pip + +cache: pip3 + before_install: - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && openssl aes-256-cbc -K $encrypted_cebf25e6c525_key -iv $encrypted_cebf25e6c525_iv -in .env.enc -out .env -d || true' - npm install npm@latest -g + install: -- pip install tox-travis +- pip3 install tox-travis + before_script: -- sudo apt-get update -- pip install pypandoc -- sudo apt-get install pandoc -- pip install -r requirements.txt -- pip install -r requirements-dev.txt -- pip install --editable . +- pip3 install -r requirements.txt +- pip3 install -r requirements-dev.txt +- pip3 install --editable . + script: -- pip install -U python-dotenv +- pip3 install -U python-dotenv - tox + before_deploy: -- pip install bumpversion +- sudo apt-get update +- pip3 install pypandoc +- sudo apt-get install pandoc +- pip3 install bumpversion - nvm install 12 - npm install @semantic-release/changelog - npm install @semantic-release/exec - npm install @semantic-release/git - npm install @semantic-release/github + deploy: - provider: script script: docs/publish.sh From fdfb07db94586f206b3819a34f237e774b1ba84f Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 21 Nov 2019 17:28:52 -0800 Subject: [PATCH 159/455] doc(example): Update url for service --- examples/discovery_v2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/discovery_v2.py b/examples/discovery_v2.py index f148e4d67..07bbfdd59 100644 --- a/examples/discovery_v2.py +++ b/examples/discovery_v2.py @@ -19,7 +19,7 @@ ## Initialize discovery instance ## discovery = DiscoveryV2(version='2019-11-22', authenticator=authenticator) discovery.set_service_url( - 'https://zen-gm-cpd-zen-gm.apps.big-smoke-lb-1.fyre.ibm.com/discovery/deweyan-poet/instances/1574286017227/api' + '' ) discovery.set_disable_ssl_verification(True) From 7f61abbb861748c6c47bf765971b5847e7605ec8 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 22 Nov 2019 11:34:16 -0800 Subject: [PATCH 160/455] test(stt): refactor tests when operation is locked --- test/integration/test_speech_to_text_v1.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/test/integration/test_speech_to_text_v1.py b/test/integration/test_speech_to_text_v1.py index 6f53da5b7..28a755661 100644 --- a/test/integration/test_speech_to_text_v1.py +++ b/test/integration/test_speech_to_text_v1.py @@ -142,11 +142,13 @@ def test_custom_grammars(self): assert get_grammar_result is not None else: print('Deleting grammar') - delete_grammar_result = self.speech_to_text.delete_grammar( - customization_id, - 'test-add-grammar-python' - ).get_result() - assert delete_grammar_result is not None + try: + delete_grammar_result = self.speech_to_text.delete_grammar( + customization_id, + 'test-add-grammar-python' + ).get_result() + except ibm_watson.ApiException as ex: + print('Could not delete grammar: {0}'.format(ex.message)) try: self.speech_to_text.delete_language_model(customization_id) From d17593d88417943ad91be40e01a98e8a43eae1ae Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 22 Nov 2019 11:47:21 -0800 Subject: [PATCH 161/455] test(stt): remove unused variable --- test/integration/test_speech_to_text_v1.py | 69 +++++++++++++--------- 1 file changed, 40 insertions(+), 29 deletions(-) diff --git a/test/integration/test_speech_to_text_v1.py b/test/integration/test_speech_to_text_v1.py index 28a755661..3b58aa854 100644 --- a/test/integration/test_speech_to_text_v1.py +++ b/test/integration/test_speech_to_text_v1.py @@ -5,8 +5,9 @@ import pytest import threading -@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 TestSpeechToTextV1(TestCase): text_to_speech = None custom_models = None @@ -17,12 +18,11 @@ class TestSpeechToTextV1(TestCase): def setup_class(cls): cls.speech_to_text = ibm_watson.SpeechToTextV1() cls.speech_to_text.set_default_headers({ - 'X-Watson-Learning-Opt-Out': - '1', - 'X-Watson-Test': - '1' + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' }) - cls.custom_models = cls.speech_to_text.list_language_models().get_result() + cls.custom_models = cls.speech_to_text.list_language_models( + ).get_result() cls.create_custom_model = cls.speech_to_text.create_language_model( name="integration_test_model", base_model_name="en-US_BroadbandModel").get_result() @@ -36,7 +36,8 @@ def teardown_class(cls): def test_models(self): output = self.speech_to_text.list_models().get_result() assert output is not None - model = self.speech_to_text.get_model('ko-KR_BroadbandModel').get_result() + model = self.speech_to_text.get_model( + 'ko-KR_BroadbandModel').get_result() assert model is not None try: self.speech_to_text.get_model('bogus') @@ -44,14 +45,18 @@ def test_models(self): assert 'X-global-transaction-id:' in str(e) def test_create_custom_model(self): - current_custom_models = self.speech_to_text.list_language_models().get_result() + current_custom_models = self.speech_to_text.list_language_models( + ).get_result() assert len(current_custom_models['customizations']) - len( self.custom_models.get('customizations')) >= 1 def test_recognize(self): - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: + with open( + os.path.join(os.path.dirname(__file__), + '../../resources/speech.wav'), 'rb') as audio_file: output = self.speech_to_text.recognize( - audio=audio_file, content_type='audio/l16; rate=44100').get_result() + audio=audio_file, + content_type='audio/l16; rate=44100').get_result() assert output['results'][0]['alternatives'][0][ 'transcript'] == 'thunderstorms could produce large hail isolated tornadoes and heavy rain ' @@ -60,7 +65,8 @@ def test_recognitions(self): assert output is not None def test_custom_corpora(self): - output = self.speech_to_text.list_corpora(self.customization_id).get_result() + output = self.speech_to_text.list_corpora( + self.customization_id).get_result() assert not output['corpora'] def test_acoustic_model(self): @@ -83,7 +89,9 @@ def test_acoustic_model(self): get_acoustic_model['customization_id']).get_result() def test_recognize_using_websocket(self): + class MyRecognizeCallback(RecognizeCallback): + def __init__(self): RecognizeCallback.__init__(self) self.error = None @@ -96,14 +104,19 @@ def on_transcription(self, transcript): self.transcript = transcript test_callback = MyRecognizeCallback() - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: + with open( + os.path.join(os.path.dirname(__file__), + '../../resources/speech.wav'), 'rb') as audio_file: audio_source = AudioSource(audio_file, False) - t = threading.Thread(target=self.speech_to_text.recognize_using_websocket, args=(audio_source, "audio/l16; rate=44100", test_callback)) + t = threading.Thread( + target=self.speech_to_text.recognize_using_websocket, + args=(audio_source, "audio/l16; rate=44100", test_callback)) t.start() t.join() assert test_callback.error is None assert test_callback.transcript is not None - assert test_callback.transcript[0]['transcript'] == 'thunderstorms could produce large hail isolated tornadoes and heavy rain ' + assert test_callback.transcript[0][ + 'transcript'] == 'thunderstorms could produce large hail isolated tornadoes and heavy rain ' def test_custom_grammars(self): customization_id = None @@ -116,37 +129,35 @@ def test_custom_grammars(self): print('Creating a new custom model') create_custom_model_for_grammar = self.speech_to_text.create_language_model( name="integration_test_model_for_grammar", - base_model_name="en-US_BroadbandModel" - ).get_result() - customization_id = create_custom_model_for_grammar['customization_id'] + base_model_name="en-US_BroadbandModel").get_result() + customization_id = create_custom_model_for_grammar[ + 'customization_id'] grammars = self.speech_to_text.list_grammars( - customization_id - ).get_result()['grammars'] + customization_id).get_result()['grammars'] if not grammars: - with open(os.path.join(os.path.dirname(__file__), '../../resources/confirm-grammar.xml'), 'rb') as grammar_file: + with open( + os.path.join(os.path.dirname(__file__), + '../../resources/confirm-grammar.xml'), + 'rb') as grammar_file: add_grammar_result = self.speech_to_text.add_grammar( customization_id, grammar_name='test-add-grammar-python', grammar_file=grammar_file, content_type='application/srgs+xml', - allow_overwrite=True - ).get_result() + allow_overwrite=True).get_result() assert add_grammar_result is not None get_grammar_result = self.speech_to_text.get_grammar( customization_id, - grammar_name='test-add-grammar-python' - ).get_result() + grammar_name='test-add-grammar-python').get_result() assert get_grammar_result is not None else: print('Deleting grammar') try: - delete_grammar_result = self.speech_to_text.delete_grammar( - customization_id, - 'test-add-grammar-python' - ).get_result() + self.speech_to_text.delete_grammar( + customization_id, 'test-add-grammar-python').get_result() except ibm_watson.ApiException as ex: print('Could not delete grammar: {0}'.format(ex.message)) From 39eedd41dfb11cc27db4fb972344df86b0308405 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 22 Nov 2019 20:26:52 +0000 Subject: [PATCH 162/455] =?UTF-8?q?Bump=20version:=204.0.3=20=E2=86=92=204?= =?UTF-8?q?.0.4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 9daceebe7..a1a5402f1 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.0.3 +current_version = 4.0.4 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 4efd83ead..d5f9f2a7b 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.0.3' +__version__ = '4.0.4' diff --git a/setup.py b/setup.py index dbd2f072d..36f6bf589 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.0.3' +__version__ = '4.0.4' if sys.argv[-1] == 'publish': From 8950135a7c85801691157274778088d75bcbd475 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 22 Nov 2019 20:26:52 +0000 Subject: [PATCH 163/455] chore(release): 4.0.4 release notes ## [4.0.4](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.3...v4.0.4) (2019-11-22) ### Bug Fixes * **semrelease:** Provide proper git message for semantic release ([88e2c08](https://github.com/watson-developer-cloud/python-sdk/commit/88e2c0806882693d175c5b8aedb1bf187223db79)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 12 ++++++------ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 245c04e83..6fae472a4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [4.0.4](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.3...v4.0.4) (2019-11-22) + + +### Bug Fixes + +* **semrelease:** Provide proper git message for semantic release ([88e2c08](https://github.com/watson-developer-cloud/python-sdk/commit/88e2c0806882693d175c5b8aedb1bf187223db79)) + ## [4.0.3](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.2...v4.0.3) (2019-11-20) diff --git a/package-lock.json b/package-lock.json index 4d4aaf41e..df88bc2c5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -106,9 +106,9 @@ } }, "@semantic-release/changelog": { - "version": "3.0.5", - "resolved": "https://registry.npmjs.org/@semantic-release/changelog/-/changelog-3.0.5.tgz", - "integrity": "sha512-/U44eK5qL2olevbEi+GrJxq1lNGUABChqK58A3SkiDsZS6AoGO8CJHQ7OG0zx+spxwkY4TevZ85Whz/hYyO+5w==", + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@semantic-release/changelog/-/changelog-3.0.6.tgz", + "integrity": "sha512-9TqPL/VarLLj6WkUqbIqFiY3nwPmLuKFHy9fe/LamAW5s4MEW/ig9zW9vzYGOUVtWdErGJ1J62E3Edkamh3xaQ==", "requires": { "@semantic-release/error": "^2.1.0", "aggregate-error": "^3.0.0", @@ -835,9 +835,9 @@ "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, "path-key": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.0.tgz", - "integrity": "sha512-8cChqz0RP6SHJkMt48FW0A7+qUOn+OsnOsVtzI59tZ8m+5bCSk7hzwET0pulwOM2YMn9J1efb07KB9l9f30SGg==" + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==" }, "path-type": { "version": "4.0.0", From c43567f000618283256d6cdc1ce2987c55a0fb06 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Sat, 23 Nov 2019 16:01:53 -0800 Subject: [PATCH 164/455] chore(test): remove unused imports --- test/unit/test_discovery_v2.py | 1 - test/unit/test_visual_recognition_v4.py | 1 - 2 files changed, 2 deletions(-) diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index cbfc342df..da2d2caad 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -17,7 +17,6 @@ import json import responses import tempfile -import ibm_watson.discovery_v2 from ibm_watson.discovery_v2 import * base_url = 'https://fake' diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 7ac33bf40..0c408ad30 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -16,7 +16,6 @@ from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import responses import tempfile -import ibm_watson.visual_recognition_v4 from ibm_watson.visual_recognition_v4 import * base_url = 'https://gateway.watsonplatform.net/visual-recognition/api' From 4bbe258968543b5409868ea6a21e541f806df0eb Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Sat, 23 Nov 2019 16:15:04 -0800 Subject: [PATCH 165/455] doc(github): Add code of conduct --- .github/CODE_OF_CONDUCT.md | 46 ++++++++++++++++++++++++++++++++++++++ .github/issue_template.md | 12 ---------- 2 files changed, 46 insertions(+), 12 deletions(-) create mode 100644 .github/CODE_OF_CONDUCT.md delete mode 100644 .github/issue_template.md diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 000000000..c046c47f5 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at ehdsouza27@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ \ No newline at end of file diff --git a/.github/issue_template.md b/.github/issue_template.md deleted file mode 100644 index c789fbb17..000000000 --- a/.github/issue_template.md +++ /dev/null @@ -1,12 +0,0 @@ -#### Expected behavior - -#### Actual behavior - -#### Steps to reproduce the problem - -#### Code snippet (Note: Do not paste your credentials) - -#### python sdk version - -#### python version - From 6e8e10077d894126fb10f5717da1d7063f93f9e2 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Sun, 24 Nov 2019 04:22:25 +0100 Subject: [PATCH 166/455] Travis CI: Python cache is pip, not pip3 --- .travis.yml | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/.travis.yml b/.travis.yml index b32f1e8e7..f9b57df0a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,13 +1,12 @@ language: python -matrix: - include: - - python: 3.5 - - python: 3.6 - - python: 3.7 - - python: 3.8 +python: + - 3.5 + - 3.6 + - 3.7 + - 3.8 -cache: pip3 +cache: pip before_install: - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && openssl aes-256-cbc -K $encrypted_cebf25e6c525_key @@ -27,10 +26,9 @@ script: - tox before_deploy: +- pip3 install bumpversion pypandoc - sudo apt-get update -- pip3 install pypandoc - sudo apt-get install pandoc -- pip3 install bumpversion - nvm install 12 - npm install @semantic-release/changelog - npm install @semantic-release/exec @@ -42,13 +40,13 @@ deploy: script: docs/publish.sh skip_cleanup: true on: - python: '3.5' + python: 3.8 tags: true - provider: script script: npx semantic-release skip_cleanup: true on: - python: '3.5' + python: 3.8 branch: master - provider: pypi user: watson-devex @@ -56,5 +54,5 @@ deploy: repository: https://upload.pypi.org/legacy skip_cleanup: true on: - python: '3.5' + python: 3.8 tags: true From 5bbcc5bd7f2a5741edfbc2553056c9ca88fb01e8 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 26 Nov 2019 11:25:44 -0800 Subject: [PATCH 167/455] test(vr4): Add end time to get_training_usage --- test/integration/test_visual_recognition_v4.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index abfb07854..036e3510e 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -121,7 +121,7 @@ def test_04_training(self): assert train_result.get('training_status') is not None # training usage - training_usage = self.visual_recognition.get_training_usage(start_time='2019-11-01').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 collection From c202d84bafc0fab4a83d7438bf70b1f52ff7ce4b Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Wed, 27 Nov 2019 16:19:42 +0000 Subject: [PATCH 168/455] =?UTF-8?q?Bump=20version:=204.0.4=20=E2=86=92=204?= =?UTF-8?q?.1.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index a1a5402f1..0951758da 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.0.4 +current_version = 4.1.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index d5f9f2a7b..fa721b497 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.0.4' +__version__ = '4.1.0' diff --git a/setup.py b/setup.py index 36f6bf589..fb53120b9 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.0.4' +__version__ = '4.1.0' if sys.argv[-1] == 'publish': From f09b1ea74b3b43d6b3d41aec2670740d1c659bc7 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Wed, 27 Nov 2019 16:19:42 +0000 Subject: [PATCH 169/455] chore(release): 4.1.0 release notes # [4.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.4...v4.1.0) (2019-11-27) ### Features * **assistantv1:** New param `new_disambiguation_opt_out ` in `create_dialog_node` ([5a5b840](https://github.com/watson-developer-cloud/python-sdk/commit/5a5b84076ff4b0d87355ed71cf7a2cbb9612c866)) * **assistantv1:** New param `new_disambiguation_opt_out ` in `update_dialog_node() ` ([6e52e07](https://github.com/watson-developer-cloud/python-sdk/commit/6e52e07b3e3ab0a9bc2687406b8a98c5e5826e33)) * **assistantv1:** New param `webhooks` in `create_workspace()` and `update_workspace()` ([0134b69](https://github.com/watson-developer-cloud/python-sdk/commit/0134b6981c09fc7132297aeb161eb75029bbd54d)) * **assistantv1:** New properties `randomize` and `max_ssuggestions` in `WorkspaceSystemSettingsDisambiguation` ([27a8cd7](https://github.com/watson-developer-cloud/python-sdk/commit/27a8cd7173a48fb6aaf909598fc3eb34e1320fe4)) * **assistantv1:** New property `off_topic` in `WorkspaceSystemSettings` ([5f93c55](https://github.com/watson-developer-cloud/python-sdk/commit/5f93c552828b539b846c9a44df4f69ed888d27b4)) * **discoveryv1:** `title` property not part of `QueryNoticesResult` and `QueryResult` ([2ce0ad3](https://github.com/watson-developer-cloud/python-sdk/commit/2ce0ad33c91714eb6d9b2adb7ac44ff70ad378e9)) * **discoveryv2:** Add examples for discoveryv2 ([2b54527](https://github.com/watson-developer-cloud/python-sdk/commit/2b54527725438d229e4acd80dc31d0869bdaa464)) * **discoveryv2:** New discovery v2 available on CP4D ([73df7e4](https://github.com/watson-developer-cloud/python-sdk/commit/73df7e4a53ef83ad1271b71215ab357f7a538177)) * **VisualRecognitionv4:** New method `get_training_usage` ([a5bec46](https://github.com/watson-developer-cloud/python-sdk/commit/a5bec467005db9340f6983654c293c94587258d9)) --- CHANGELOG.md | 15 +++++++++++++++ package-lock.json | 12 ++++++------ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fae472a4..1c425f246 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,18 @@ +# [4.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.4...v4.1.0) (2019-11-27) + + +### Features + +* **assistantv1:** New param `new_disambiguation_opt_out ` in `create_dialog_node` ([5a5b840](https://github.com/watson-developer-cloud/python-sdk/commit/5a5b84076ff4b0d87355ed71cf7a2cbb9612c866)) +* **assistantv1:** New param `new_disambiguation_opt_out ` in `update_dialog_node() ` ([6e52e07](https://github.com/watson-developer-cloud/python-sdk/commit/6e52e07b3e3ab0a9bc2687406b8a98c5e5826e33)) +* **assistantv1:** New param `webhooks` in `create_workspace()` and `update_workspace()` ([0134b69](https://github.com/watson-developer-cloud/python-sdk/commit/0134b6981c09fc7132297aeb161eb75029bbd54d)) +* **assistantv1:** New properties `randomize` and `max_ssuggestions` in `WorkspaceSystemSettingsDisambiguation` ([27a8cd7](https://github.com/watson-developer-cloud/python-sdk/commit/27a8cd7173a48fb6aaf909598fc3eb34e1320fe4)) +* **assistantv1:** New property `off_topic` in `WorkspaceSystemSettings` ([5f93c55](https://github.com/watson-developer-cloud/python-sdk/commit/5f93c552828b539b846c9a44df4f69ed888d27b4)) +* **discoveryv1:** `title` property not part of `QueryNoticesResult` and `QueryResult` ([2ce0ad3](https://github.com/watson-developer-cloud/python-sdk/commit/2ce0ad33c91714eb6d9b2adb7ac44ff70ad378e9)) +* **discoveryv2:** Add examples for discoveryv2 ([2b54527](https://github.com/watson-developer-cloud/python-sdk/commit/2b54527725438d229e4acd80dc31d0869bdaa464)) +* **discoveryv2:** New discovery v2 available on CP4D ([73df7e4](https://github.com/watson-developer-cloud/python-sdk/commit/73df7e4a53ef83ad1271b71215ab357f7a538177)) +* **VisualRecognitionv4:** New method `get_training_usage` ([a5bec46](https://github.com/watson-developer-cloud/python-sdk/commit/a5bec467005db9340f6983654c293c94587258d9)) + ## [4.0.4](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.3...v4.0.4) (2019-11-22) diff --git a/package-lock.json b/package-lock.json index df88bc2c5..3603f0197 100644 --- a/package-lock.json +++ b/package-lock.json @@ -195,9 +195,9 @@ "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==" }, "@types/node": { - "version": "12.12.11", - "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.11.tgz", - "integrity": "sha512-O+x6uIpa6oMNTkPuHDa9MhMMehlxLAd5QcOvKRjAFsBVpeFWTOPnXbDvILvFgFFZfQ1xh1EZi1FbXxUix+zpsQ==" + "version": "12.12.14", + "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.14.tgz", + "integrity": "sha512-u/SJDyXwuihpwjXy7hOOghagLEV1KdAST6syfnOk6QZAMzZuWZqXy5aYYZbh8Jdpd4escVFP0MvftHNDb9pruA==" }, "@types/retry": { "version": "0.12.0", @@ -380,9 +380,9 @@ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==" }, "execa": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-3.3.0.tgz", - "integrity": "sha512-j5Vit5WZR/cbHlqU97+qcnw9WHRCIL4V1SVe75VcHcD1JRBdt8fv0zw89b7CQHQdUHTt2VjuhcF5ibAgVOxqpg==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-3.4.0.tgz", + "integrity": "sha512-r9vdGQk4bmCuK1yKQu1KTwcT2zwfWdbdaXfCtAh+5nU/4fSX+JAb7vZGvI5naJrQlvONrEB20jeruESI69530g==", "requires": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", From ffa787178210f5ef2959d34ff6107175a27616b1 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 19 Dec 2019 02:57:47 -0500 Subject: [PATCH 170/455] doc(ltv3): Add examples for document translation methods --- examples/language_translator_v3.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/examples/language_translator_v3.py b/examples/language_translator_v3.py index 2cced01c4..12feb0b1d 100644 --- a/examples/language_translator_v3.py +++ b/examples/language_translator_v3.py @@ -43,3 +43,32 @@ # # Get model details # model = language_translator.get_model(model_id='').get_result() # print(json.dumps(model, indent=2)) + +#### Document Translation #### +# List Documents +result = language_translator.list_documents().get_result() +print(json.dumps(result, indent=2)) + +# Translate Document +with open('en.pdf', 'rb') as file: + result = language_translator.translate_document( + file=file, + file_content_type='application/pdf', + filename='en.pdf', + model_id='en-fr').get_result() + print(json.dumps(result, indent=2)) + +# Document Status +result = language_translator.get_document_status( + document_id='{document id}').get_result() +print(json.dumps(result, indent=2)) + +# Translated Document +with open('translated.pdf', 'wb') as f: + result = language_translator.get_translated_document( + document_id='{document id}', + accept='application/pdf').get_result() + f.write(result.content) + +# Delete Document +language_translator.delete_document(document_id='{document id}') From 97286d33b362928ca67e50f6af71891ce3d983e3 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 13:31:36 -0500 Subject: [PATCH 171/455] refactor(assssistantv1): Regenerate assistantv1 --- ibm_watson/assistant_v1.py | 2791 ++++++++++------- test/unit/test_assistant_v1.py | 5131 ++++++++++++++++++++++---------- 2 files changed, 5286 insertions(+), 2636 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index c93fc3ada..393be33e2 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,12 +22,17 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService 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 import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from typing import Dict +from typing import List ############################################################################## # Service @@ -37,13 +42,15 @@ class AssistantV1(BaseService): """The Assistant V1 service.""" - default_service_url = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_NAME = 'conversation' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Assistant service. @@ -62,40 +69,30 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('assistant') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('assistant') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Message ######################### def message(self, - workspace_id, + workspace_id: str, *, - input=None, - intents=None, - entities=None, - alternate_intents=None, - context=None, - output=None, - nodes_visited_details=None, - **kwargs): + input: 'MessageInput' = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + alternate_intents: bool = None, + context: 'Context' = None, + output: 'OutputData' = None, + nodes_visited_details: bool = None, + **kwargs) -> 'DetailedResponse': """ Get response to user input. @@ -109,11 +106,11 @@ def message(self, :param str workspace_id: Unique identifier of the workspace. :param MessageInput input: (optional) An input object that includes the input text. - :param list[RuntimeIntent] intents: (optional) Intents to use when + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. - :param list[RuntimeEntity] entities: (optional) Entities to use when + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. @@ -148,7 +145,9 @@ def message(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'message') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='message') headers.update(sdk_headers) params = { @@ -171,8 +170,8 @@ def message(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -182,11 +181,11 @@ def message(self, def list_workspaces(self, *, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List workspaces. @@ -211,7 +210,9 @@ def list_workspaces(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'list_workspaces') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_workspaces') headers.update(sdk_headers) params = { @@ -226,25 +227,25 @@ def list_workspaces(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_workspace(self, *, - name=None, - description=None, - language=None, - metadata=None, - learning_opt_out=None, - system_settings=None, - intents=None, - entities=None, - dialog_nodes=None, - counterexamples=None, - webhooks=None, - **kwargs): + name: str = None, + description: str = None, + language: str = None, + metadata: dict = None, + learning_opt_out: bool = None, + system_settings: 'WorkspaceSystemSettings' = None, + intents: List['CreateIntent'] = None, + entities: List['CreateEntity'] = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, + webhooks: List['Webhook'] = None, + **kwargs) -> 'DetailedResponse': """ Create workspace. @@ -265,15 +266,15 @@ def create_workspace(self, training data is not to be used. :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. - :param list[CreateIntent] intents: (optional) An array of objects defining + :param List[CreateIntent] intents: (optional) An array of objects defining the intents for the workspace. - :param list[CreateEntity] entities: (optional) An array of objects + :param List[CreateEntity] entities: (optional) An array of objects describing the entities for the workspace. - :param list[DialogNode] dialog_nodes: (optional) An array of objects + :param List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. - :param list[Counterexample] counterexamples: (optional) An array of objects + :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 List[Webhook] webhooks: (optional) :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -295,7 +296,9 @@ def create_workspace(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'create_workspace') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_workspace') headers.update(sdk_headers) params = {'version': self.version} @@ -319,18 +322,18 @@ def create_workspace(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_workspace(self, - workspace_id, + workspace_id: str, *, - export=None, - include_audit=None, - sort=None, - **kwargs): + export: bool = None, + include_audit: bool = None, + sort: str = None, + **kwargs) -> 'DetailedResponse': """ Get information about a workspace. @@ -361,7 +364,9 @@ def get_workspace(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'get_workspace') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_workspace') headers.update(sdk_headers) params = { @@ -375,27 +380,27 @@ def get_workspace(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_workspace(self, - workspace_id, + workspace_id: str, *, - name=None, - description=None, - language=None, - metadata=None, - learning_opt_out=None, - system_settings=None, - intents=None, - entities=None, - dialog_nodes=None, - counterexamples=None, - webhooks=None, - append=None, - **kwargs): + name: str = None, + description: str = None, + language: str = None, + metadata: dict = None, + learning_opt_out: bool = None, + system_settings: 'WorkspaceSystemSettings' = None, + intents: List['CreateIntent'] = None, + entities: List['CreateEntity'] = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, + webhooks: List['Webhook'] = None, + append: bool = None, + **kwargs) -> 'DetailedResponse': """ Update workspace. @@ -417,15 +422,15 @@ def update_workspace(self, training data is not to be used. :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. - :param list[CreateIntent] intents: (optional) An array of objects defining + :param List[CreateIntent] intents: (optional) An array of objects defining the intents for the workspace. - :param list[CreateEntity] entities: (optional) An array of objects + :param List[CreateEntity] entities: (optional) An array of objects describing the entities for the workspace. - :param list[DialogNode] dialog_nodes: (optional) An array of objects + :param List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. - :param list[Counterexample] counterexamples: (optional) An array of objects + :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 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 @@ -458,7 +463,9 @@ def update_workspace(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'update_workspace') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_workspace') headers.update(sdk_headers) params = {'version': self.version, 'append': append} @@ -482,12 +489,13 @@ def update_workspace(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_workspace(self, workspace_id, **kwargs): + def delete_workspace(self, workspace_id: str, + **kwargs) -> 'DetailedResponse': """ Delete workspace. @@ -507,7 +515,9 @@ def delete_workspace(self, workspace_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'delete_workspace') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_workspace') headers.update(sdk_headers) params = {'version': self.version} @@ -516,8 +526,8 @@ def delete_workspace(self, workspace_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -526,14 +536,14 @@ def delete_workspace(self, workspace_id, **kwargs): ######################### def list_intents(self, - workspace_id, + workspace_id: str, *, - export=None, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + export: bool = None, + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List intents. @@ -567,7 +577,9 @@ def list_intents(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'list_intents') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_intents') headers.update(sdk_headers) params = { @@ -584,18 +596,18 @@ def list_intents(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_intent(self, - workspace_id, - intent, + workspace_id: str, + intent: str, *, - description=None, - examples=None, - **kwargs): + description: str = None, + examples: List['Example'] = None, + **kwargs) -> 'DetailedResponse': """ Create intent. @@ -613,7 +625,7 @@ def create_intent(self, - It cannot begin with the reserved prefix `sys-`. :param str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :param list[Example] examples: (optional) An array of user input examples + :param List[Example] examples: (optional) An array of user input examples for the intent. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -630,7 +642,9 @@ def create_intent(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'create_intent') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_intent') headers.update(sdk_headers) params = {'version': self.version} @@ -647,18 +661,18 @@ def create_intent(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_intent(self, - workspace_id, - intent, + workspace_id: str, + intent: str, *, - export=None, - include_audit=None, - **kwargs): + export: bool = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get intent. @@ -688,7 +702,9 @@ def get_intent(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'get_intent') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_intent') headers.update(sdk_headers) params = { @@ -702,19 +718,19 @@ def get_intent(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_intent(self, - workspace_id, - intent, + workspace_id: str, + intent: str, *, - new_intent=None, - new_description=None, - new_examples=None, - **kwargs): + new_intent: str = None, + new_description: str = None, + new_examples: List['Example'] = None, + **kwargs) -> 'DetailedResponse': """ Update intent. @@ -734,7 +750,7 @@ def update_intent(self, - It cannot begin with the reserved prefix `sys-`. :param str new_description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :param list[Example] new_examples: (optional) An array of user input + :param List[Example] new_examples: (optional) An array of user input examples for the intent. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -751,7 +767,9 @@ def update_intent(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'update_intent') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_intent') headers.update(sdk_headers) params = {'version': self.version} @@ -768,12 +786,13 @@ def update_intent(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_intent(self, workspace_id, intent, **kwargs): + def delete_intent(self, workspace_id: str, intent: str, + **kwargs) -> 'DetailedResponse': """ Delete intent. @@ -796,7 +815,9 @@ def delete_intent(self, workspace_id, intent, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'delete_intent') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_intent') headers.update(sdk_headers) params = {'version': self.version} @@ -806,8 +827,8 @@ def delete_intent(self, workspace_id, intent, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -816,14 +837,14 @@ def delete_intent(self, workspace_id, intent, **kwargs): ######################### def list_examples(self, - workspace_id, - intent, + workspace_id: str, + intent: str, *, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List user input examples. @@ -856,7 +877,9 @@ def list_examples(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'list_examples') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_examples') headers.update(sdk_headers) params = { @@ -872,18 +895,18 @@ def list_examples(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_example(self, - workspace_id, - intent, - text, + workspace_id: str, + intent: str, + text: str, *, - mentions=None, - **kwargs): + mentions: List['Mention'] = None, + **kwargs) -> 'DetailedResponse': """ Create user input example. @@ -899,7 +922,7 @@ def create_example(self, to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param list[Mention] mentions: (optional) An array of contextual entity + :param List[Mention] mentions: (optional) An array of contextual entity mentions. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -918,7 +941,9 @@ def create_example(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'create_example') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_example') headers.update(sdk_headers) params = {'version': self.version} @@ -931,18 +956,18 @@ def create_example(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_example(self, - workspace_id, - intent, - text, + workspace_id: str, + intent: str, + text: str, *, - include_audit=None, - **kwargs): + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get user input example. @@ -970,7 +995,9 @@ def get_example(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'get_example') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_example') headers.update(sdk_headers) params = {'version': self.version, 'include_audit': include_audit} @@ -980,19 +1007,19 @@ def get_example(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_example(self, - workspace_id, - intent, - text, + workspace_id: str, + intent: str, + text: str, *, - new_text=None, - new_mentions=None, - **kwargs): + new_text: str = None, + new_mentions: List['Mention'] = None, + **kwargs) -> 'DetailedResponse': """ Update user input example. @@ -1009,7 +1036,7 @@ def update_example(self, string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param list[Mention] new_mentions: (optional) An array of contextual entity + :param List[Mention] new_mentions: (optional) An array of contextual entity mentions. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1028,7 +1055,9 @@ def update_example(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'update_example') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_example') headers.update(sdk_headers) params = {'version': self.version} @@ -1041,12 +1070,13 @@ def update_example(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_example(self, workspace_id, intent, text, **kwargs): + def delete_example(self, workspace_id: str, intent: str, text: str, + **kwargs) -> 'DetailedResponse': """ Delete user input example. @@ -1072,7 +1102,9 @@ def delete_example(self, workspace_id, intent, text, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'delete_example') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_example') headers.update(sdk_headers) params = {'version': self.version} @@ -1082,8 +1114,8 @@ def delete_example(self, workspace_id, intent, text, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -1092,13 +1124,13 @@ def delete_example(self, workspace_id, intent, text, **kwargs): ######################### def list_counterexamples(self, - workspace_id, + workspace_id: str, *, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List counterexamples. @@ -1128,8 +1160,9 @@ def list_counterexamples(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - 'list_counterexamples') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_counterexamples') headers.update(sdk_headers) params = { @@ -1145,12 +1178,13 @@ def list_counterexamples(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def create_counterexample(self, workspace_id, text, **kwargs): + def create_counterexample(self, workspace_id: str, text: str, + **kwargs) -> 'DetailedResponse': """ Create counterexample. @@ -1179,8 +1213,9 @@ def create_counterexample(self, workspace_id, text, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - 'create_counterexample') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_counterexample') headers.update(sdk_headers) params = {'version': self.version} @@ -1193,17 +1228,17 @@ def create_counterexample(self, workspace_id, text, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_counterexample(self, - workspace_id, - text, + workspace_id: str, + text: str, *, - include_audit=None, - **kwargs): + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get counterexample. @@ -1230,8 +1265,9 @@ def get_counterexample(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - 'get_counterexample') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_counterexample') headers.update(sdk_headers) params = {'version': self.version, 'include_audit': include_audit} @@ -1241,17 +1277,17 @@ def get_counterexample(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_counterexample(self, - workspace_id, - text, + workspace_id: str, + text: str, *, - new_text=None, - **kwargs): + new_text: str = None, + **kwargs) -> 'DetailedResponse': """ Update counterexample. @@ -1282,8 +1318,9 @@ def update_counterexample(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - 'update_counterexample') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_counterexample') headers.update(sdk_headers) params = {'version': self.version} @@ -1296,12 +1333,13 @@ def update_counterexample(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_counterexample(self, workspace_id, text, **kwargs): + def delete_counterexample(self, workspace_id: str, text: str, + **kwargs) -> 'DetailedResponse': """ Delete counterexample. @@ -1326,8 +1364,9 @@ def delete_counterexample(self, workspace_id, text, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - 'delete_counterexample') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_counterexample') headers.update(sdk_headers) params = {'version': self.version} @@ -1337,8 +1376,8 @@ def delete_counterexample(self, workspace_id, text, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -1347,14 +1386,14 @@ def delete_counterexample(self, workspace_id, text, **kwargs): ######################### def list_entities(self, - workspace_id, + workspace_id: str, *, - export=None, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + export: bool = None, + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List entities. @@ -1388,7 +1427,9 @@ def list_entities(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'list_entities') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_entities') headers.update(sdk_headers) params = { @@ -1405,20 +1446,20 @@ def list_entities(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_entity(self, - workspace_id, - entity, + workspace_id: str, + entity: str, *, - description=None, - metadata=None, - fuzzy_match=None, - values=None, - **kwargs): + description: str = None, + metadata: dict = None, + fuzzy_match: bool = None, + values: List['CreateValue'] = None, + **kwargs) -> 'DetailedResponse': """ Create entity. @@ -1441,7 +1482,7 @@ def create_entity(self, :param dict metadata: (optional) Any metadata related to the entity. :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :param list[CreateValue] values: (optional) An array of objects describing + :param List[CreateValue] values: (optional) An array of objects describing the entity values. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1458,7 +1499,9 @@ def create_entity(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'create_entity') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_entity') headers.update(sdk_headers) params = {'version': self.version} @@ -1477,18 +1520,18 @@ def create_entity(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_entity(self, - workspace_id, - entity, + workspace_id: str, + entity: str, *, - export=None, - include_audit=None, - **kwargs): + export: bool = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get entity. @@ -1518,7 +1561,9 @@ def get_entity(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'get_entity') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_entity') headers.update(sdk_headers) params = { @@ -1532,21 +1577,21 @@ def get_entity(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_entity(self, - workspace_id, - entity, + workspace_id: str, + entity: str, *, - new_entity=None, - new_description=None, - new_metadata=None, - new_fuzzy_match=None, - new_values=None, - **kwargs): + new_entity: str = None, + new_description: str = None, + new_metadata: dict = None, + new_fuzzy_match: bool = None, + new_values: List['CreateValue'] = None, + **kwargs) -> 'DetailedResponse': """ Update entity. @@ -1569,7 +1614,7 @@ def update_entity(self, :param dict new_metadata: (optional) Any metadata related to the entity. :param bool new_fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :param list[CreateValue] new_values: (optional) An array of objects + :param List[CreateValue] new_values: (optional) An array of objects describing the entity values. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1586,7 +1631,9 @@ def update_entity(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'update_entity') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_entity') headers.update(sdk_headers) params = {'version': self.version} @@ -1605,12 +1652,13 @@ def update_entity(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_entity(self, workspace_id, entity, **kwargs): + def delete_entity(self, workspace_id: str, entity: str, + **kwargs) -> 'DetailedResponse': """ Delete entity. @@ -1633,7 +1681,9 @@ def delete_entity(self, workspace_id, entity, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'delete_entity') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_entity') headers.update(sdk_headers) params = {'version': self.version} @@ -1643,8 +1693,8 @@ def delete_entity(self, workspace_id, entity, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -1653,12 +1703,12 @@ def delete_entity(self, workspace_id, entity, **kwargs): ######################### def list_mentions(self, - workspace_id, - entity, + workspace_id: str, + entity: str, *, - export=None, - include_audit=None, - **kwargs): + export: bool = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List entity mentions. @@ -1688,7 +1738,9 @@ def list_mentions(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'list_mentions') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_mentions') headers.update(sdk_headers) params = { @@ -1702,8 +1754,8 @@ def list_mentions(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -1712,15 +1764,15 @@ def list_mentions(self, ######################### def list_values(self, - workspace_id, - entity, + workspace_id: str, + entity: str, *, - export=None, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + export: bool = None, + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List entity values. @@ -1756,7 +1808,9 @@ def list_values(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'list_values') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_values') headers.update(sdk_headers) params = { @@ -1773,21 +1827,21 @@ def list_values(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_value(self, - workspace_id, - entity, - value, + workspace_id: str, + entity: str, + value: str, *, - metadata=None, - type=None, - synonyms=None, - patterns=None, - **kwargs): + metadata: dict = None, + type: str = None, + synonyms: List[str] = None, + patterns: List[str] = None, + **kwargs) -> 'DetailedResponse': """ Create entity value. @@ -1805,13 +1859,13 @@ def create_value(self, - It cannot consist of only whitespace characters. :param dict metadata: (optional) Any metadata related to the entity value. :param str type: (optional) Specifies the type of entity value. - :param list[str] synonyms: (optional) An array of synonyms for the entity + :param List[str] synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param list[str] patterns: (optional) An array of patterns for the entity + :param List[str] patterns: (optional) An array of patterns for the 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 @@ -1831,7 +1885,9 @@ def create_value(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'create_value') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_value') headers.update(sdk_headers) params = {'version': self.version} @@ -1850,19 +1906,19 @@ def create_value(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_value(self, - workspace_id, - entity, - value, + workspace_id: str, + entity: str, + value: str, *, - export=None, - include_audit=None, - **kwargs): + export: bool = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get entity value. @@ -1894,7 +1950,9 @@ def get_value(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'get_value') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_value') headers.update(sdk_headers) params = { @@ -1908,22 +1966,22 @@ def get_value(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_value(self, - workspace_id, - entity, - value, + workspace_id: str, + entity: str, + value: str, *, - new_value=None, - new_metadata=None, - new_type=None, - new_synonyms=None, - new_patterns=None, - **kwargs): + new_value: str = None, + new_metadata: dict = None, + new_type: str = None, + new_synonyms: List[str] = None, + new_patterns: List[str] = None, + **kwargs) -> 'DetailedResponse': """ Update entity value. @@ -1944,13 +2002,13 @@ def update_value(self, :param dict new_metadata: (optional) Any metadata related to the entity value. :param str new_type: (optional) Specifies the type of entity value. - :param list[str] new_synonyms: (optional) An array of synonyms for the + :param List[str] new_synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param list[str] new_patterns: (optional) An array of patterns for the + :param List[str] new_patterns: (optional) An array of patterns for the 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 @@ -1970,7 +2028,9 @@ def update_value(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'update_value') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_value') headers.update(sdk_headers) params = {'version': self.version} @@ -1989,12 +2049,13 @@ def update_value(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_value(self, workspace_id, entity, value, **kwargs): + def delete_value(self, workspace_id: str, entity: str, value: str, + **kwargs) -> 'DetailedResponse': """ Delete entity value. @@ -2020,7 +2081,9 @@ def delete_value(self, workspace_id, entity, value, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'delete_value') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_value') headers.update(sdk_headers) params = {'version': self.version} @@ -2030,8 +2093,8 @@ def delete_value(self, workspace_id, entity, value, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2040,15 +2103,15 @@ def delete_value(self, workspace_id, entity, value, **kwargs): ######################### def list_synonyms(self, - workspace_id, - entity, - value, + workspace_id: str, + entity: str, + value: str, *, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List entity value synonyms. @@ -2083,7 +2146,9 @@ def list_synonyms(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'list_synonyms') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_synonyms') headers.update(sdk_headers) params = { @@ -2099,12 +2164,13 @@ def list_synonyms(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def create_synonym(self, workspace_id, entity, value, synonym, **kwargs): + def create_synonym(self, workspace_id: str, entity: str, value: str, + synonym: str, **kwargs) -> 'DetailedResponse': """ Create entity value synonym. @@ -2139,7 +2205,9 @@ def create_synonym(self, workspace_id, entity, value, synonym, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'create_synonym') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_synonym') headers.update(sdk_headers) params = {'version': self.version} @@ -2152,19 +2220,19 @@ def create_synonym(self, workspace_id, entity, value, synonym, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_synonym(self, - workspace_id, - entity, - value, - synonym, + workspace_id: str, + entity: str, + value: str, + synonym: str, *, - include_audit=None, - **kwargs): + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get entity value synonym. @@ -2195,7 +2263,9 @@ def get_synonym(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'get_synonym') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_synonym') headers.update(sdk_headers) params = {'version': self.version, 'include_audit': include_audit} @@ -2205,19 +2275,19 @@ def get_synonym(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_synonym(self, - workspace_id, - entity, - value, - synonym, + workspace_id: str, + entity: str, + value: str, + synonym: str, *, - new_synonym=None, - **kwargs): + new_synonym: str = None, + **kwargs) -> 'DetailedResponse': """ Update entity value synonym. @@ -2253,7 +2323,9 @@ def update_synonym(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'update_synonym') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_synonym') headers.update(sdk_headers) params = {'version': self.version} @@ -2266,12 +2338,13 @@ def update_synonym(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): + def delete_synonym(self, workspace_id: str, entity: str, value: str, + synonym: str, **kwargs) -> 'DetailedResponse': """ Delete entity value synonym. @@ -2300,7 +2373,9 @@ def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'delete_synonym') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_synonym') headers.update(sdk_headers) params = {'version': self.version} @@ -2310,8 +2385,8 @@ def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2320,13 +2395,13 @@ def delete_synonym(self, workspace_id, entity, value, synonym, **kwargs): ######################### def list_dialog_nodes(self, - workspace_id, + workspace_id: str, *, - page_limit=None, - sort=None, - cursor=None, - include_audit=None, - **kwargs): + page_limit: int = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ List dialog nodes. @@ -2355,7 +2430,9 @@ def list_dialog_nodes(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'list_dialog_nodes') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_dialog_nodes') headers.update(sdk_headers) params = { @@ -2371,34 +2448,34 @@ def list_dialog_nodes(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_dialog_node(self, - workspace_id, - dialog_node, + workspace_id: str, + dialog_node: str, *, - description=None, - conditions=None, - parent=None, - previous_sibling=None, - output=None, - context=None, - metadata=None, - next_step=None, - title=None, - type=None, - event_name=None, - variable=None, - actions=None, - digress_in=None, - digress_out=None, - digress_out_slots=None, - user_label=None, - disambiguation_opt_out=None, - **kwargs): + description: str = None, + conditions: str = None, + parent: str = None, + previous_sibling: str = None, + output: 'DialogNodeOutput' = None, + context: dict = None, + metadata: dict = None, + next_step: 'DialogNodeNextStep' = None, + title: str = None, + type: str = None, + event_name: str = None, + variable: str = None, + actions: List['DialogNodeAction'] = None, + digress_in: str = None, + digress_out: str = None, + digress_out_slots: str = None, + user_label: str = None, + disambiguation_opt_out: bool = None, + **kwargs) -> 'DetailedResponse': """ Create dialog node. @@ -2438,7 +2515,7 @@ def create_dialog_node(self, :param str event_name: (optional) How an `event_handler` node is processed. :param str variable: (optional) The location in the dialog context where output is stored. - :param list[DialogNodeAction] actions: (optional) An array of objects + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions to be invoked by the dialog node. :param str digress_in: (optional) Whether this top-level dialog node can be digressed into. @@ -2469,8 +2546,9 @@ def create_dialog_node(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - 'create_dialog_node') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_dialog_node') headers.update(sdk_headers) params = {'version': self.version} @@ -2503,17 +2581,17 @@ def create_dialog_node(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_dialog_node(self, - workspace_id, - dialog_node, + workspace_id: str, + dialog_node: str, *, - include_audit=None, - **kwargs): + include_audit: bool = None, + **kwargs) -> 'DetailedResponse': """ Get dialog node. @@ -2538,7 +2616,9 @@ def get_dialog_node(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'get_dialog_node') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_dialog_node') headers.update(sdk_headers) params = {'version': self.version, 'include_audit': include_audit} @@ -2548,35 +2628,35 @@ def get_dialog_node(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_dialog_node(self, - workspace_id, - dialog_node, + workspace_id: str, + dialog_node: str, *, - new_dialog_node=None, - new_description=None, - new_conditions=None, - new_parent=None, - new_previous_sibling=None, - new_output=None, - new_context=None, - new_metadata=None, - new_next_step=None, - new_title=None, - new_type=None, - new_event_name=None, - new_variable=None, - new_actions=None, - new_digress_in=None, - new_digress_out=None, - new_digress_out_slots=None, - new_user_label=None, - new_disambiguation_opt_out=None, - **kwargs): + new_dialog_node: str = None, + new_description: str = None, + new_conditions: str = None, + new_parent: str = None, + new_previous_sibling: str = None, + new_output: 'DialogNodeOutput' = None, + new_context: dict = None, + new_metadata: dict = None, + new_next_step: 'DialogNodeNextStep' = None, + new_title: str = None, + new_type: str = None, + new_event_name: str = None, + new_variable: str = None, + new_actions: List['DialogNodeAction'] = None, + new_digress_in: str = None, + new_digress_out: str = None, + new_digress_out_slots: str = None, + new_user_label: str = None, + new_disambiguation_opt_out: bool = None, + **kwargs) -> 'DetailedResponse': """ Update dialog node. @@ -2618,7 +2698,7 @@ def update_dialog_node(self, processed. :param str new_variable: (optional) The location in the dialog context where output is stored. - :param list[DialogNodeAction] new_actions: (optional) An array of objects + :param List[DialogNodeAction] new_actions: (optional) An array of objects describing any actions to be invoked by the dialog node. :param str new_digress_in: (optional) Whether this top-level dialog node can be digressed into. @@ -2649,8 +2729,9 @@ def update_dialog_node(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - 'update_dialog_node') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_dialog_node') headers.update(sdk_headers) params = {'version': self.version} @@ -2683,12 +2764,13 @@ def update_dialog_node(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): + def delete_dialog_node(self, workspace_id: str, dialog_node: str, + **kwargs) -> 'DetailedResponse': """ Delete dialog node. @@ -2711,8 +2793,9 @@ def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', - 'delete_dialog_node') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_dialog_node') headers.update(sdk_headers) params = {'version': self.version} @@ -2722,8 +2805,8 @@ def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2732,13 +2815,13 @@ def delete_dialog_node(self, workspace_id, dialog_node, **kwargs): ######################### def list_logs(self, - workspace_id, + workspace_id: str, *, - sort=None, - filter=None, - page_limit=None, - cursor=None, - **kwargs): + sort: str = None, + filter: str = None, + page_limit: int = None, + cursor: str = None, + **kwargs) -> 'DetailedResponse': """ List log events in a workspace. @@ -2769,7 +2852,9 @@ def list_logs(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'list_logs') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_logs') headers.update(sdk_headers) params = { @@ -2785,18 +2870,18 @@ def list_logs(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def list_all_logs(self, - filter, + filter: str, *, - sort=None, - page_limit=None, - cursor=None, - **kwargs): + sort: str = None, + page_limit: int = None, + cursor: str = None, + **kwargs) -> 'DetailedResponse': """ List log events in all workspaces. @@ -2829,7 +2914,9 @@ def list_all_logs(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'list_all_logs') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_all_logs') headers.update(sdk_headers) params = { @@ -2844,8 +2931,8 @@ def list_all_logs(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2853,7 +2940,8 @@ def list_all_logs(self, # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -2863,6 +2951,8 @@ def delete_user_data(self, customer_id, **kwargs): 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). + This operation is limited to 4 requests per minute. For more information, see + **Rate limiting**. :param str customer_id: The customer ID for which all data is to be deleted. @@ -2877,7 +2967,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V1', 'delete_user_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data') headers.update(sdk_headers) params = {'version': self.version, 'customer_id': customer_id} @@ -2886,8 +2978,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -3001,23 +3093,23 @@ class CaptureGroup(): A recognized capture group for a pattern-based entity. :attr str group: A recognized capture group for the entity. - :attr list[int] location: (optional) Zero-based character offsets that indicate + :attr List[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ - def __init__(self, group, *, location=None): + def __init__(self, group: str, *, location: List[int] = None) -> None: """ Initialize a CaptureGroup object. :param str group: A recognized capture group for the entity. - :param list[int] location: (optional) Zero-based character offsets that + :param List[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ self.group = group self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CaptureGroup': """Initialize a CaptureGroup object from a json dictionary.""" args = {} valid_keys = ['group', 'location'] @@ -3035,7 +3127,12 @@ def _from_dict(cls, _dict): args['location'] = _dict.get('location') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CaptureGroup 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, 'group') and self.group is not None: @@ -3044,17 +3141,21 @@ def _to_dict(self): _dict['location'] = self.location return _dict - def __str__(self): + 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 CaptureGroup object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CaptureGroup') -> 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): + def __ne__(self, other: 'CaptureGroup') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3072,10 +3173,10 @@ class Context(): def __init__(self, *, - conversation_id=None, - system=None, - metadata=None, - **kwargs): + conversation_id: str = None, + system: 'SystemResponse' = None, + metadata: 'MessageContextMetadata' = None, + **kwargs) -> None: """ Initialize a Context object. @@ -3093,7 +3194,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Context': """Initialize a Context object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -3110,7 +3211,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Context 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, @@ -3127,7 +3233,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {'conversation_id', 'system', 'metadata'} if not hasattr(self, '_additionalProperties'): super(Context, self).__setattr__('_additionalProperties', set()) @@ -3135,17 +3245,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(Context, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this Context object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Context') -> 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): + def __ne__(self, other: 'Context') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3163,7 +3273,11 @@ class Counterexample(): the object. """ - def __init__(self, text, *, created=None, updated=None): + def __init__(self, + text: str, + *, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a Counterexample object. @@ -3181,7 +3295,7 @@ def __init__(self, text, *, created=None, updated=None): self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Counterexample': """Initialize a Counterexample object from a json dictionary.""" args = {} valid_keys = ['text', 'created', 'updated'] @@ -3201,7 +3315,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Counterexample 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, 'text') and self.text is not None: @@ -3212,17 +3331,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 Counterexample object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Counterexample') -> 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): + def __ne__(self, other: 'Counterexample') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3231,16 +3354,17 @@ class CounterexampleCollection(): """ CounterexampleCollection. - :attr list[Counterexample] counterexamples: An array of objects describing the + :attr List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, counterexamples, pagination): + def __init__(self, counterexamples: List['Counterexample'], + pagination: 'Pagination') -> None: """ Initialize a CounterexampleCollection object. - :param list[Counterexample] counterexamples: An array of objects describing + :param List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. :param Pagination pagination: The pagination data for the returned objects. """ @@ -3248,7 +3372,7 @@ def __init__(self, counterexamples, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CounterexampleCollection': """Initialize a CounterexampleCollection object from a json dictionary.""" args = {} valid_keys = ['counterexamples', 'pagination'] @@ -3274,7 +3398,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CounterexampleCollection 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, @@ -3286,17 +3415,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 CounterexampleCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CounterexampleCollection') -> 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): + def __ne__(self, other: 'CounterexampleCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3318,19 +3451,19 @@ class CreateEntity(): :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. - :attr list[CreateValue] values: (optional) An array of objects describing the + :attr List[CreateValue] values: (optional) An array of objects describing the entity values. """ def __init__(self, - entity, + entity: str, *, - description=None, - metadata=None, - fuzzy_match=None, - created=None, - updated=None, - values=None): + description: str = None, + metadata: dict = None, + fuzzy_match: bool = None, + created: datetime = None, + updated: datetime = None, + values: List['CreateValue'] = None) -> None: """ Initialize a CreateEntity object. @@ -3350,7 +3483,7 @@ def __init__(self, object. :param datetime updated: (optional) The timestamp for the most recent update to the object. - :param list[CreateValue] values: (optional) An array of objects describing + :param List[CreateValue] values: (optional) An array of objects describing the entity values. """ self.entity = entity @@ -3362,7 +3495,7 @@ def __init__(self, self.values = values @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CreateEntity': """Initialize a CreateEntity object from a json dictionary.""" args = {} valid_keys = [ @@ -3395,7 +3528,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateEntity 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, 'entity') and self.entity is not None: @@ -3414,17 +3552,21 @@ def _to_dict(self): _dict['values'] = [x._to_dict() for x in self.values] return _dict - def __str__(self): + 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 CreateEntity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CreateEntity') -> 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): + def __ne__(self, other: 'CreateEntity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3443,17 +3585,17 @@ class CreateIntent(): :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. - :attr list[Example] examples: (optional) An array of user input examples for the + :attr List[Example] examples: (optional) An array of user input examples for the intent. """ def __init__(self, - intent, + intent: str, *, - description=None, - created=None, - updated=None, - examples=None): + description: str = None, + created: datetime = None, + updated: datetime = None, + examples: List['Example'] = None) -> None: """ Initialize a CreateIntent object. @@ -3468,7 +3610,7 @@ def __init__(self, object. :param datetime updated: (optional) The timestamp for the most recent update to the object. - :param list[Example] examples: (optional) An array of user input examples + :param List[Example] examples: (optional) An array of user input examples for the intent. """ self.intent = intent @@ -3478,7 +3620,7 @@ def __init__(self, self.examples = examples @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CreateIntent': """Initialize a CreateIntent object from a json dictionary.""" args = {} valid_keys = ['intent', 'description', 'created', 'updated', 'examples'] @@ -3504,7 +3646,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateIntent 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, 'intent') and self.intent is not None: @@ -3519,17 +3666,21 @@ def _to_dict(self): _dict['examples'] = [x._to_dict() for x in self.examples] return _dict - def __str__(self): + 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 CreateIntent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CreateIntent') -> 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): + def __ne__(self, other: 'CreateIntent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3544,12 +3695,12 @@ class CreateValue(): - It cannot consist of only whitespace characters. :attr dict metadata: (optional) Any metadata related to the entity value. :attr str type: (optional) Specifies the type of entity value. - :attr list[str] synonyms: (optional) An array of synonyms for the entity value. + :attr List[str] synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr list[str] patterns: (optional) An array of patterns for the entity value. + :attr List[str] patterns: (optional) An array of patterns for the 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 @@ -3560,14 +3711,14 @@ class CreateValue(): """ def __init__(self, - value, + value: str, *, - metadata=None, - type=None, - synonyms=None, - patterns=None, - created=None, - updated=None): + metadata: dict = None, + type: str = None, + synonyms: List[str] = None, + patterns: List[str] = None, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a CreateValue object. @@ -3577,13 +3728,13 @@ def __init__(self, - It cannot consist of only whitespace characters. :param dict metadata: (optional) Any metadata related to the entity value. :param str type: (optional) Specifies the type of entity value. - :param list[str] synonyms: (optional) An array of synonyms for the entity + :param List[str] synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param list[str] patterns: (optional) An array of patterns for the entity + :param List[str] patterns: (optional) An array of patterns for the 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 @@ -3602,7 +3753,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CreateValue': """Initialize a CreateValue object from a json dictionary.""" args = {} valid_keys = [ @@ -3633,7 +3784,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateValue 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: @@ -3652,17 +3808,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 CreateValue object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CreateValue') -> 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): + def __ne__(self, other: 'CreateValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3705,7 +3865,7 @@ class DialogNode(): :attr str event_name: (optional) How an `event_handler` node is processed. :attr str variable: (optional) The location in the dialog context where output is stored. - :attr list[DialogNodeAction] actions: (optional) An array of objects describing + :attr List[DialogNodeAction] actions: (optional) An array of objects describing any actions to be invoked by the dialog node. :attr str digress_in: (optional) Whether this top-level dialog node can be digressed into. @@ -3724,29 +3884,29 @@ class DialogNode(): """ def __init__(self, - dialog_node, + dialog_node: str, *, - description=None, - conditions=None, - parent=None, - previous_sibling=None, - output=None, - context=None, - metadata=None, - next_step=None, - title=None, - type=None, - event_name=None, - variable=None, - actions=None, - digress_in=None, - digress_out=None, - digress_out_slots=None, - user_label=None, - disambiguation_opt_out=None, - disabled=None, - created=None, - updated=None): + description: str = None, + conditions: str = None, + parent: str = None, + previous_sibling: str = None, + output: 'DialogNodeOutput' = None, + context: dict = None, + metadata: dict = None, + next_step: 'DialogNodeNextStep' = None, + title: str = None, + type: str = None, + event_name: str = None, + variable: str = None, + actions: List['DialogNodeAction'] = None, + digress_in: str = None, + digress_out: str = None, + digress_out_slots: str = None, + user_label: str = None, + disambiguation_opt_out: bool = None, + disabled: bool = None, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a DialogNode object. @@ -3779,7 +3939,7 @@ def __init__(self, :param str event_name: (optional) How an `event_handler` node is processed. :param str variable: (optional) The location in the dialog context where output is stored. - :param list[DialogNodeAction] actions: (optional) An array of objects + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions to be invoked by the dialog node. :param str digress_in: (optional) Whether this top-level dialog node can be digressed into. @@ -3821,7 +3981,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNode': """Initialize a DialogNode object from a json dictionary.""" args = {} valid_keys = [ @@ -3889,7 +4049,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNode 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, 'dialog_node') and self.dialog_node is not None: @@ -3941,17 +4106,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 DialogNode object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNode') -> 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): + def __ne__(self, other: 'DialogNode') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4020,12 +4189,12 @@ class DialogNodeAction(): """ def __init__(self, - name, - result_variable, + name: str, + result_variable: str, *, - type=None, - parameters=None, - credentials=None): + type: str = None, + parameters: dict = None, + credentials: str = None) -> None: """ Initialize a DialogNodeAction object. @@ -4045,7 +4214,7 @@ def __init__(self, self.credentials = credentials @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': """Initialize a DialogNodeAction object from a json dictionary.""" args = {} valid_keys = [ @@ -4076,7 +4245,12 @@ def _from_dict(cls, _dict): args['credentials'] = _dict.get('credentials') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeAction 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, 'name') and self.name is not None: @@ -4092,17 +4266,21 @@ def _to_dict(self): _dict['credentials'] = self.credentials return _dict - def __str__(self): + 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 DialogNodeAction object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeAction') -> 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): + def __ne__(self, other: 'DialogNodeAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4121,16 +4299,17 @@ class DialogNodeCollection(): """ An array of dialog nodes. - :attr list[DialogNode] dialog_nodes: An array of objects describing the dialog + :attr List[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, dialog_nodes, pagination): + def __init__(self, dialog_nodes: List['DialogNode'], + pagination: 'Pagination') -> None: """ Initialize a DialogNodeCollection object. - :param list[DialogNode] dialog_nodes: An array of objects describing the + :param List[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. """ @@ -4138,7 +4317,7 @@ def __init__(self, dialog_nodes, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeCollection': """Initialize a DialogNodeCollection object from a json dictionary.""" args = {} valid_keys = ['dialog_nodes', 'pagination'] @@ -4163,7 +4342,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeCollection 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, 'dialog_nodes') and self.dialog_nodes is not None: @@ -4172,17 +4356,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 DialogNodeCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeCollection') -> 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): + def __ne__(self, other: 'DialogNodeCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4217,7 +4405,11 @@ class DialogNodeNextStep(): :attr str selector: (optional) Which part of the dialog node to process next. """ - def __init__(self, behavior, *, dialog_node=None, selector=None): + def __init__(self, + behavior: str, + *, + dialog_node: str = None, + selector: str = None) -> None: """ Initialize a DialogNodeNextStep object. @@ -4252,7 +4444,7 @@ def __init__(self, behavior, *, dialog_node=None, selector=None): self.selector = selector @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeNextStep': """Initialize a DialogNodeNextStep object from a json dictionary.""" args = {} valid_keys = ['behavior', 'dialog_node', 'selector'] @@ -4273,7 +4465,12 @@ def _from_dict(cls, _dict): args['selector'] = _dict.get('selector') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeNextStep 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, 'behavior') and self.behavior is not None: @@ -4284,17 +4481,21 @@ def _to_dict(self): _dict['selector'] = self.selector return _dict - def __str__(self): + 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 DialogNodeNextStep object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeNextStep') -> 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): + def __ne__(self, other: 'DialogNodeNextStep') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4345,17 +4546,21 @@ class DialogNodeOutput(): output, see the [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :attr list[DialogNodeOutputGeneric] generic: (optional) An array of objects + :attr List[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. :attr DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. """ - def __init__(self, *, generic=None, modifiers=None, **kwargs): + def __init__(self, + *, + generic: List['DialogNodeOutputGeneric'] = None, + modifiers: 'DialogNodeOutputModifiers' = None, + **kwargs) -> None: """ Initialize a DialogNodeOutput object. - :param list[DialogNodeOutputGeneric] generic: (optional) An array of + :param List[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. @@ -4367,7 +4572,7 @@ def __init__(self, *, generic=None, modifiers=None, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': """Initialize a DialogNodeOutput object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -4384,7 +4589,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutput 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, 'generic') and self.generic is not None: @@ -4398,7 +4608,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {'generic', 'modifiers'} if not hasattr(self, '_additionalProperties'): super(DialogNodeOutput, self).__setattr__('_additionalProperties', @@ -4407,17 +4621,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(DialogNodeOutput, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this DialogNodeOutput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutput') -> 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): + def __ne__(self, other: 'DialogNodeOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4430,7 +4644,7 @@ class DialogNodeOutputGeneric(): specified response type must be supported by the client application or channel. **Note:** The **search_skill** response type is available only for Plus and Premium users, and is used only by the v2 runtime API. - :attr list[DialogNodeOutputTextValuesElement] values: (optional) A list of one + :attr List[DialogNodeOutputTextValuesElement] values: (optional) A list of one or more objects defining text responses. Required when **response_type**=`text`. :attr str selection_policy: (optional) How a response is selected from the list, if more than one response is specified. Valid only when @@ -4450,7 +4664,7 @@ class DialogNodeOutputGeneric(): response. Valid only when **response_type**=`image` or `option`. :attr str preference: (optional) The preferred type of control to display, if supported by the channel. Valid only when **response_type**=`option`. - :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of + :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. You can include up to 20 options. Required when **response_type**=`option`. :attr str message_to_human_agent: (optional) An optional message to be sent to @@ -4473,23 +4687,23 @@ class DialogNodeOutputGeneric(): """ def __init__(self, - response_type, + response_type: str, *, - values=None, - selection_policy=None, - delimiter=None, - time=None, - typing=None, - source=None, - title=None, - description=None, - preference=None, - options=None, - message_to_human_agent=None, - query=None, - query_type=None, - filter=None, - discovery_version=None): + values: List['DialogNodeOutputTextValuesElement'] = None, + selection_policy: str = None, + delimiter: str = None, + time: int = None, + typing: bool = None, + source: str = None, + title: str = None, + description: str = None, + preference: str = None, + options: List['DialogNodeOutputOptionsElement'] = None, + message_to_human_agent: str = None, + query: str = None, + query_type: str = None, + filter: str = None, + discovery_version: str = None) -> None: """ Initialize a DialogNodeOutputGeneric object. @@ -4498,7 +4712,7 @@ def __init__(self, channel. **Note:** The **search_skill** response type is available only for Plus and Premium users, and is used only by the v2 runtime API. - :param list[DialogNodeOutputTextValuesElement] values: (optional) A list of + :param List[DialogNodeOutputTextValuesElement] values: (optional) A list of one or more objects defining text responses. Required when **response_type**=`text`. :param str selection_policy: (optional) How a response is selected from the @@ -4519,7 +4733,7 @@ def __init__(self, response. Valid only when **response_type**=`image` or `option`. :param str preference: (optional) The preferred type of control to display, if supported by the channel. Valid only when **response_type**=`option`. - :param list[DialogNodeOutputOptionsElement] options: (optional) An array of + :param List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. You can include up to 20 options. Required when **response_type**=`option`. :param str message_to_human_agent: (optional) An optional message to be @@ -4558,7 +4772,7 @@ def __init__(self, self.discovery_version = discovery_version @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputGeneric': """Initialize a DialogNodeOutputGeneric object from a json dictionary.""" args = {} valid_keys = [ @@ -4616,7 +4830,12 @@ def _from_dict(cls, _dict): args['discovery_version'] = _dict.get('discovery_version') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputGeneric 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, 'response_type') and self.response_type is not None: @@ -4656,17 +4875,21 @@ def _to_dict(self): _dict['discovery_version'] = self.discovery_version return _dict - def __str__(self): + 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 DialogNodeOutputGeneric object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputGeneric') -> 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): + def __ne__(self, other: 'DialogNodeOutputGeneric') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4719,7 +4942,7 @@ class DialogNodeOutputModifiers(): values. """ - def __init__(self, *, overwrite=None): + def __init__(self, *, overwrite: bool = None) -> None: """ Initialize a DialogNodeOutputModifiers object. @@ -4731,7 +4954,7 @@ def __init__(self, *, overwrite=None): self.overwrite = overwrite @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputModifiers': """Initialize a DialogNodeOutputModifiers object from a json dictionary.""" args = {} valid_keys = ['overwrite'] @@ -4744,24 +4967,33 @@ def _from_dict(cls, _dict): args['overwrite'] = _dict.get('overwrite') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputModifiers 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, 'overwrite') and self.overwrite is not None: _dict['overwrite'] = self.overwrite return _dict - def __str__(self): + 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 DialogNodeOutputModifiers object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputModifiers') -> 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): + def __ne__(self, other: 'DialogNodeOutputModifiers') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4776,7 +5008,8 @@ class DialogNodeOutputOptionsElement(): corresponding option. """ - def __init__(self, label, value): + def __init__(self, label: str, + value: 'DialogNodeOutputOptionsElementValue') -> None: """ Initialize a DialogNodeOutputOptionsElement object. @@ -4789,7 +5022,7 @@ def __init__(self, label, value): self.value = value @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} valid_keys = ['label', 'value'] @@ -4813,7 +5046,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputOptionsElement 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, 'label') and self.label is not None: @@ -4822,17 +5060,21 @@ def _to_dict(self): _dict['value'] = self.value._to_dict() return _dict - def __str__(self): + 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 DialogNodeOutputOptionsElement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> 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): + def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4844,27 +5086,31 @@ class DialogNodeOutputOptionsElementValue(): :attr MessageInput input: (optional) An input object that includes the input text. - :attr list[RuntimeIntent] intents: (optional) An array of intents to be used + :attr List[RuntimeIntent] intents: (optional) An array of intents to be used while processing the input. **Note:** This property is supported for backward compatibility with applications that use the v1 **Get response to user input** method. - :attr list[RuntimeEntity] entities: (optional) An array of entities to be used + :attr List[RuntimeEntity] entities: (optional) An array of entities to be used while processing the user input. **Note:** This property is supported for backward compatibility with applications that use the v1 **Get response to user input** method. """ - def __init__(self, *, input=None, intents=None, entities=None): + def __init__(self, + *, + input: 'MessageInput' = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None) -> None: """ Initialize a DialogNodeOutputOptionsElementValue object. :param MessageInput input: (optional) An input object that includes the input text. - :param list[RuntimeIntent] intents: (optional) An array of intents to be + :param List[RuntimeIntent] intents: (optional) An array of intents to be used while processing the input. **Note:** This property is supported for backward compatibility with applications that use the v1 **Get response to user input** method. - :param list[RuntimeEntity] entities: (optional) An array of entities to be + :param List[RuntimeEntity] entities: (optional) An array of entities to be used while processing the user input. **Note:** This property is supported for backward compatibility with applications that use the v1 **Get response to user input** method. @@ -4874,7 +5120,7 @@ def __init__(self, *, input=None, intents=None, entities=None): self.entities = entities @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} valid_keys = ['input', 'intents', 'entities'] @@ -4895,7 +5141,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputOptionsElementValue 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, 'input') and self.input is not None: @@ -4906,17 +5157,21 @@ def _to_dict(self): _dict['entities'] = [x._to_dict() for x in self.entities] return _dict - def __str__(self): + 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 DialogNodeOutputOptionsElementValue object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> 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): + def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4930,7 +5185,7 @@ class DialogNodeOutputTextValuesElement(): supported by the channel. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a DialogNodeOutputTextValuesElement object. @@ -4941,7 +5196,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputTextValuesElement': """Initialize a DialogNodeOutputTextValuesElement object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -4954,24 +5209,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputTextValuesElement 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, 'text') and self.text is not None: _dict['text'] = self.text return _dict - def __str__(self): + 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 DialogNodeOutputTextValuesElement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputTextValuesElement') -> 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): + def __ne__(self, other: 'DialogNodeOutputTextValuesElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4986,7 +5250,11 @@ class DialogNodeVisitedDetails(): :attr str conditions: (optional) The conditions that trigger the dialog node. """ - def __init__(self, *, dialog_node=None, title=None, conditions=None): + def __init__(self, + *, + dialog_node: str = None, + title: str = None, + conditions: str = None) -> None: """ Initialize a DialogNodeVisitedDetails object. @@ -5001,7 +5269,7 @@ def __init__(self, *, dialog_node=None, title=None, conditions=None): self.conditions = conditions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeVisitedDetails': """Initialize a DialogNodeVisitedDetails object from a json dictionary.""" args = {} valid_keys = ['dialog_node', 'title', 'conditions'] @@ -5018,7 +5286,12 @@ def _from_dict(cls, _dict): args['conditions'] = _dict.get('conditions') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeVisitedDetails 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, 'dialog_node') and self.dialog_node is not None: @@ -5029,17 +5302,21 @@ def _to_dict(self): _dict['conditions'] = self.conditions return _dict - def __str__(self): + 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 DialogNodeVisitedDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeVisitedDetails') -> 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): + def __ne__(self, other: 'DialogNodeVisitedDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5062,7 +5339,12 @@ class DialogSuggestion(): the dialog node's **user_label** property. """ - def __init__(self, label, value, *, output=None, dialog_node=None): + def __init__(self, + label: str, + value: 'DialogSuggestionValue', + *, + output: 'DialogSuggestionOutput' = None, + dialog_node: str = None) -> None: """ Initialize a DialogSuggestion object. @@ -5085,7 +5367,7 @@ def __init__(self, label, value, *, output=None, dialog_node=None): self.dialog_node = dialog_node @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': """Initialize a DialogSuggestion object from a json dictionary.""" args = {} valid_keys = ['label', 'value', 'output', 'dialog_node'] @@ -5113,9 +5395,14 @@ def _from_dict(cls, _dict): args['dialog_node'] = _dict.get('dialog_node') return cls(**args) - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestion 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, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: @@ -5126,17 +5413,21 @@ def _to_dict(self): _dict['dialog_node'] = self.dialog_node return _dict - def __str__(self): + 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 DialogSuggestion object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestion') -> 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): + def __ne__(self, other: 'DialogSuggestion') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5146,40 +5437,40 @@ class DialogSuggestionOutput(): The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. - :attr list[str] nodes_visited: (optional) An array of the nodes that were + :attr List[str] nodes_visited: (optional) An array of the nodes that were triggered to create the response, in the order in which they were visited. This information is useful for debugging and for tracing the path taken through the node tree. - :attr list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array + :attr List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message request. - :attr list[str] text: An array of responses to the user. - :attr list[DialogSuggestionResponseGeneric] generic: (optional) Output intended + :attr List[str] text: An array of responses to the user. + :attr List[DialogSuggestionResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. """ def __init__(self, - text, + text: List[str], *, - nodes_visited=None, - nodes_visited_details=None, - generic=None, - **kwargs): + nodes_visited: List[str] = None, + nodes_visited_details: List['DialogNodeVisitedDetails'] = None, + generic: List['DialogSuggestionResponseGeneric'] = None, + **kwargs) -> None: """ Initialize a DialogSuggestionOutput object. - :param list[str] text: An array of responses to the user. - :param list[str] nodes_visited: (optional) An array of the nodes that were + :param List[str] text: An array of responses to the user. + :param List[str] nodes_visited: (optional) An array of the nodes that were triggered to create the response, in the order in which they were visited. This information is useful for debugging and for tracing the path taken through the node tree. - :param list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An + :param List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message request. - :param list[DialogSuggestionResponseGeneric] generic: (optional) Output + :param List[DialogSuggestionResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. :param **kwargs: (optional) Any additional properties. @@ -5192,7 +5483,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionOutput': """Initialize a DialogSuggestionOutput object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -5221,7 +5512,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestionOutput 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, 'nodes_visited') and self.nodes_visited is not None: @@ -5242,7 +5538,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = { 'nodes_visited', 'nodes_visited_details', 'text', 'generic' } @@ -5253,17 +5553,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(DialogSuggestionOutput, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this DialogSuggestionOutput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestionOutput') -> 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): + def __ne__(self, other: 'DialogSuggestionOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5287,7 +5587,7 @@ class DialogSuggestionResponseGeneric(): response. :attr str description: (optional) The description to show with the the response. :attr str preference: (optional) The preferred type of control to display. - :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of + :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. @@ -5299,19 +5599,19 @@ class DialogSuggestionResponseGeneric(): """ def __init__(self, - response_type, + response_type: str, *, - text=None, - time=None, - typing=None, - source=None, - title=None, - description=None, - preference=None, - options=None, - message_to_human_agent=None, - topic=None, - dialog_node=None): + text: str = None, + time: int = None, + typing: bool = None, + source: str = None, + title: str = None, + description: str = None, + preference: str = None, + options: List['DialogNodeOutputOptionsElement'] = None, + message_to_human_agent: str = None, + topic: str = None, + dialog_node: str = None) -> None: """ Initialize a DialogSuggestionResponseGeneric object. @@ -5332,7 +5632,7 @@ def __init__(self, :param str description: (optional) The description to show with the the response. :param str preference: (optional) The preferred type of control to display. - :param list[DialogNodeOutputOptionsElement] options: (optional) An array of + :param List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. @@ -5357,7 +5657,7 @@ def __init__(self, self.dialog_node = dialog_node @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionResponseGeneric': """Initialize a DialogSuggestionResponseGeneric object from a json dictionary.""" args = {} valid_keys = [ @@ -5403,7 +5703,12 @@ def _from_dict(cls, _dict): args['dialog_node'] = _dict.get('dialog_node') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestionResponseGeneric 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, 'response_type') and self.response_type is not None: @@ -5433,17 +5738,21 @@ def _to_dict(self): _dict['dialog_node'] = self.dialog_node return _dict - def __str__(self): + 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 DialogSuggestionResponseGeneric object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestionResponseGeneric') -> 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): + def __ne__(self, other: 'DialogSuggestionResponseGeneric') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5478,21 +5787,25 @@ class DialogSuggestionValue(): :attr MessageInput input: (optional) An input object that includes the input text. - :attr list[RuntimeIntent] intents: (optional) An array of intents to be sent + :attr List[RuntimeIntent] intents: (optional) An array of intents to be sent along with the user input. - :attr list[RuntimeEntity] entities: (optional) An array of entities to be sent + :attr List[RuntimeEntity] entities: (optional) An array of entities to be sent along with the user input. """ - def __init__(self, *, input=None, intents=None, entities=None): + def __init__(self, + *, + input: 'MessageInput' = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None) -> None: """ Initialize a DialogSuggestionValue object. :param MessageInput input: (optional) An input object that includes the input text. - :param list[RuntimeIntent] intents: (optional) An array of intents to be + :param List[RuntimeIntent] intents: (optional) An array of intents to be sent along with the user input. - :param list[RuntimeEntity] entities: (optional) An array of entities to be + :param List[RuntimeEntity] entities: (optional) An array of entities to be sent along with the user input. """ self.input = input @@ -5500,7 +5813,7 @@ def __init__(self, *, input=None, intents=None, entities=None): self.entities = entities @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} valid_keys = ['input', 'intents', 'entities'] @@ -5521,7 +5834,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestionValue 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, 'input') and self.input is not None: @@ -5532,17 +5850,21 @@ def _to_dict(self): _dict['entities'] = [x._to_dict() for x in self.entities] return _dict - def __str__(self): + 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 DialogSuggestionValue object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestionValue') -> 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): + def __ne__(self, other: 'DialogSuggestionValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5564,19 +5886,19 @@ class Entity(): :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. - :attr list[Value] values: (optional) An array of objects describing the entity + :attr List[Value] values: (optional) An array of objects describing the entity values. """ def __init__(self, - entity, + entity: str, *, - description=None, - metadata=None, - fuzzy_match=None, - created=None, - updated=None, - values=None): + description: str = None, + metadata: dict = None, + fuzzy_match: bool = None, + created: datetime = None, + updated: datetime = None, + values: List['Value'] = None) -> None: """ Initialize a Entity object. @@ -5596,7 +5918,7 @@ def __init__(self, object. :param datetime updated: (optional) The timestamp for the most recent update to the object. - :param list[Value] values: (optional) An array of objects describing the + :param List[Value] values: (optional) An array of objects describing the entity values. """ self.entity = entity @@ -5608,7 +5930,7 @@ def __init__(self, self.values = values @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Entity': """Initialize a Entity object from a json dictionary.""" args = {} valid_keys = [ @@ -5641,7 +5963,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Entity 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, 'entity') and self.entity is not None: @@ -5660,17 +5987,21 @@ def _to_dict(self): _dict['values'] = [x._to_dict() for x in self.values] return _dict - def __str__(self): + 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 Entity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Entity') -> 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): + def __ne__(self, other: 'Entity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5679,16 +6010,17 @@ class EntityCollection(): """ An array of objects describing the entities for the workspace. - :attr list[Entity] entities: An array of objects describing the entities defined + :attr List[Entity] entities: An array of objects describing the entities defined for the workspace. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, entities, pagination): + def __init__(self, entities: List['Entity'], + pagination: 'Pagination') -> None: """ Initialize a EntityCollection object. - :param list[Entity] entities: An array of objects describing the entities + :param List[Entity] entities: An array of objects describing the entities defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. """ @@ -5696,7 +6028,7 @@ def __init__(self, entities, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntityCollection': """Initialize a EntityCollection object from a json dictionary.""" args = {} valid_keys = ['entities', 'pagination'] @@ -5721,7 +6053,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntityCollection 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, 'entities') and self.entities is not None: @@ -5730,17 +6067,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 EntityCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntityCollection') -> 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): + def __ne__(self, other: 'EntityCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5751,17 +6092,17 @@ class EntityMention(): :attr str text: The text of the user input example. :attr str intent: The name of the intent. - :attr list[int] location: An array of zero-based character offsets that indicate + :attr List[int] location: An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. """ - def __init__(self, text, intent, location): + def __init__(self, text: str, intent: str, location: List[int]) -> None: """ Initialize a EntityMention object. :param str text: The text of the user input example. :param str intent: The name of the intent. - :param list[int] location: An array of zero-based character offsets that + :param List[int] location: An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. """ self.text = text @@ -5769,7 +6110,7 @@ def __init__(self, text, intent, location): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} valid_keys = ['text', 'intent', 'location'] @@ -5797,7 +6138,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntityMention 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, 'text') and self.text is not None: @@ -5808,17 +6154,21 @@ def _to_dict(self): _dict['location'] = self.location return _dict - def __str__(self): + 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 EntityMention object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntityMention') -> 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): + def __ne__(self, other: 'EntityMention') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5827,16 +6177,17 @@ class EntityMentionCollection(): """ EntityMentionCollection. - :attr list[EntityMention] examples: An array of objects describing the entity + :attr List[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, examples, pagination): + def __init__(self, examples: List['EntityMention'], + pagination: 'Pagination') -> None: """ Initialize a EntityMentionCollection object. - :param list[EntityMention] examples: An array of objects describing the + :param List[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. :param Pagination pagination: The pagination data for the returned objects. """ @@ -5844,7 +6195,7 @@ def __init__(self, examples, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntityMentionCollection': """Initialize a EntityMentionCollection object from a json dictionary.""" args = {} valid_keys = ['examples', 'pagination'] @@ -5869,7 +6220,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntityMentionCollection 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, 'examples') and self.examples is not None: @@ -5878,17 +6234,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 EntityMentionCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntityMentionCollection') -> 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): + def __ne__(self, other: 'EntityMentionCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5901,13 +6261,18 @@ class Example(): the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr list[Mention] mentions: (optional) An array of contextual entity mentions. + :attr List[Mention] mentions: (optional) An array of contextual entity mentions. :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. """ - def __init__(self, text, *, mentions=None, created=None, updated=None): + def __init__(self, + text: str, + *, + mentions: List['Mention'] = None, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a Example object. @@ -5915,7 +6280,7 @@ def __init__(self, text, *, mentions=None, created=None, updated=None): to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param list[Mention] mentions: (optional) An array of contextual entity + :param List[Mention] mentions: (optional) An array of contextual entity mentions. :param datetime created: (optional) The timestamp for creation of the object. @@ -5928,7 +6293,7 @@ def __init__(self, text, *, mentions=None, created=None, updated=None): self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Example': """Initialize a Example object from a json dictionary.""" args = {} valid_keys = ['text', 'mentions', 'created', 'updated'] @@ -5952,7 +6317,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Example 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, 'text') and self.text is not None: @@ -5965,17 +6335,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 Example object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Example') -> 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): + def __ne__(self, other: 'Example') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5984,16 +6358,17 @@ class ExampleCollection(): """ ExampleCollection. - :attr list[Example] examples: An array of objects describing the examples + :attr List[Example] examples: An array of objects describing the examples defined for the intent. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, examples, pagination): + def __init__(self, examples: List['Example'], + pagination: 'Pagination') -> None: """ Initialize a ExampleCollection object. - :param list[Example] examples: An array of objects describing the examples + :param List[Example] examples: An array of objects describing the examples defined for the intent. :param Pagination pagination: The pagination data for the returned objects. """ @@ -6001,7 +6376,7 @@ def __init__(self, examples, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ExampleCollection': """Initialize a ExampleCollection object from a json dictionary.""" args = {} valid_keys = ['examples', 'pagination'] @@ -6026,7 +6401,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ExampleCollection 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, 'examples') and self.examples is not None: @@ -6035,17 +6415,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 ExampleCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ExampleCollection') -> 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): + def __ne__(self, other: 'ExampleCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6064,17 +6448,17 @@ class Intent(): :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. - :attr list[Example] examples: (optional) An array of user input examples for the + :attr List[Example] examples: (optional) An array of user input examples for the intent. """ def __init__(self, - intent, + intent: str, *, - description=None, - created=None, - updated=None, - examples=None): + description: str = None, + created: datetime = None, + updated: datetime = None, + examples: List['Example'] = None) -> None: """ Initialize a Intent object. @@ -6089,7 +6473,7 @@ def __init__(self, object. :param datetime updated: (optional) The timestamp for the most recent update to the object. - :param list[Example] examples: (optional) An array of user input examples + :param List[Example] examples: (optional) An array of user input examples for the intent. """ self.intent = intent @@ -6099,7 +6483,7 @@ def __init__(self, self.examples = examples @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Intent': """Initialize a Intent object from a json dictionary.""" args = {} valid_keys = ['intent', 'description', 'created', 'updated', 'examples'] @@ -6125,7 +6509,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Intent 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, 'intent') and self.intent is not None: @@ -6140,17 +6529,21 @@ def _to_dict(self): _dict['examples'] = [x._to_dict() for x in self.examples] return _dict - def __str__(self): + 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 Intent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Intent') -> 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): + def __ne__(self, other: 'Intent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6159,16 +6552,17 @@ class IntentCollection(): """ IntentCollection. - :attr list[Intent] intents: An array of objects describing the intents defined + :attr List[Intent] intents: An array of objects describing the intents defined for the workspace. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, intents, pagination): + def __init__(self, intents: List['Intent'], + pagination: 'Pagination') -> None: """ Initialize a IntentCollection object. - :param list[Intent] intents: An array of objects describing the intents + :param List[Intent] intents: An array of objects describing the intents defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. """ @@ -6176,7 +6570,7 @@ def __init__(self, intents, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IntentCollection': """Initialize a IntentCollection object from a json dictionary.""" args = {} valid_keys = ['intents', 'pagination'] @@ -6201,7 +6595,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IntentCollection 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, 'intents') and self.intents is not None: @@ -6210,17 +6609,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 IntentCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IntentCollection') -> 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): + def __ne__(self, other: 'IntentCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6243,8 +6646,9 @@ class Log(): made. """ - def __init__(self, request, response, log_id, request_timestamp, - response_timestamp, workspace_id, language): + def __init__(self, request: 'MessageRequest', response: 'MessageResponse', + log_id: str, request_timestamp: str, response_timestamp: str, + workspace_id: str, language: str) -> None: """ Initialize a Log object. @@ -6270,7 +6674,7 @@ def __init__(self, request, response, log_id, request_timestamp, self.language = language @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Log': """Initialize a Log object from a json dictionary.""" args = {} valid_keys = [ @@ -6321,7 +6725,12 @@ def _from_dict(cls, _dict): 'Required property \'language\' not present in Log JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Log 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, 'request') and self.request is not None: @@ -6343,17 +6752,21 @@ def _to_dict(self): _dict['language'] = self.language return _dict - def __str__(self): + 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 Log object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Log') -> 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): + def __ne__(self, other: 'Log') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6362,15 +6775,15 @@ class LogCollection(): """ LogCollection. - :attr list[Log] logs: An array of objects describing log events. + :attr List[Log] logs: An array of objects describing log events. :attr LogPagination pagination: The pagination data for the returned objects. """ - def __init__(self, logs, pagination): + def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: """ Initialize a LogCollection object. - :param list[Log] logs: An array of objects describing log events. + :param List[Log] logs: An array of objects describing log events. :param LogPagination pagination: The pagination data for the returned objects. """ @@ -6378,7 +6791,7 @@ def __init__(self, logs, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} valid_keys = ['logs', 'pagination'] @@ -6401,7 +6814,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogCollection 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, 'logs') and self.logs is not None: @@ -6410,17 +6828,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 LogCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogCollection') -> 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): + def __ne__(self, other: 'LogCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6433,7 +6855,7 @@ class LogMessage(): :attr str msg: The text of the log message. """ - def __init__(self, level, msg): + def __init__(self, level: str, msg: str) -> None: """ Initialize a LogMessage object. @@ -6444,7 +6866,7 @@ def __init__(self, level, msg): self.msg = msg @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogMessage': """Initialize a LogMessage object from a json dictionary.""" args = {} valid_keys = ['level', 'msg'] @@ -6465,7 +6887,12 @@ def _from_dict(cls, _dict): 'Required property \'msg\' not present in LogMessage JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogMessage 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, 'level') and self.level is not None: @@ -6474,17 +6901,21 @@ def _to_dict(self): _dict['msg'] = self.msg return _dict - def __str__(self): + 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 LogMessage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogMessage') -> 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): + def __ne__(self, other: 'LogMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6507,7 +6938,11 @@ class LogPagination(): :attr str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, *, next_url=None, matched=None, next_cursor=None): + def __init__(self, + *, + next_url: str = None, + matched: int = None, + next_cursor: str = None) -> None: """ Initialize a LogPagination object. @@ -6522,7 +6957,7 @@ def __init__(self, *, next_url=None, matched=None, next_cursor=None): self.next_cursor = next_cursor @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogPagination': """Initialize a LogPagination object from a json dictionary.""" args = {} valid_keys = ['next_url', 'matched', 'next_cursor'] @@ -6539,7 +6974,12 @@ def _from_dict(cls, _dict): args['next_cursor'] = _dict.get('next_cursor') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogPagination 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, 'next_url') and self.next_url is not None: @@ -6550,17 +6990,21 @@ def _to_dict(self): _dict['next_cursor'] = self.next_cursor return _dict - def __str__(self): + 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 LogPagination object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogPagination') -> 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): + def __ne__(self, other: 'LogPagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6570,23 +7014,23 @@ class Mention(): A mention of a contextual entity. :attr str entity: The name of the entity. - :attr list[int] location: An array of zero-based character offsets that indicate + :attr List[int] location: An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. """ - def __init__(self, entity, location): + def __init__(self, entity: str, location: List[int]) -> None: """ Initialize a Mention object. :param str entity: The name of the entity. - :param list[int] location: An array of zero-based character offsets that + :param List[int] location: An array of zero-based character offsets that indicate where the entity mentions begin and end in the input text. """ self.entity = entity self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Mention': """Initialize a Mention object from a json dictionary.""" args = {} valid_keys = ['entity', 'location'] @@ -6607,7 +7051,12 @@ def _from_dict(cls, _dict): 'Required property \'location\' not present in Mention JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Mention 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, 'entity') and self.entity is not None: @@ -6616,17 +7065,21 @@ def _to_dict(self): _dict['location'] = self.location return _dict - def __str__(self): + 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 Mention object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Mention') -> 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): + def __ne__(self, other: 'Mention') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6645,7 +7098,7 @@ class MessageContextMetadata(): string cannot contain carriage return, newline, or tab characters. """ - def __init__(self, *, deployment=None, user_id=None): + def __init__(self, *, deployment: str = None, user_id: str = None) -> None: """ Initialize a MessageContextMetadata object. @@ -6663,7 +7116,7 @@ def __init__(self, *, deployment=None, user_id=None): self.user_id = user_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContextMetadata': """Initialize a MessageContextMetadata object from a json dictionary.""" args = {} valid_keys = ['deployment', 'user_id'] @@ -6678,7 +7131,12 @@ def _from_dict(cls, _dict): args['user_id'] = _dict.get('user_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextMetadata 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, 'deployment') and self.deployment is not None: @@ -6687,17 +7145,21 @@ def _to_dict(self): _dict['user_id'] = self.user_id return _dict - def __str__(self): + 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 MessageContextMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageContextMetadata') -> 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): + def __ne__(self, other: 'MessageContextMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6710,7 +7172,7 @@ class MessageInput(): contain carriage return, newline, or tab characters. """ - def __init__(self, *, text=None, **kwargs): + def __init__(self, *, text: str = None, **kwargs) -> None: """ Initialize a MessageInput object. @@ -6723,7 +7185,7 @@ def __init__(self, *, text=None, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -6733,7 +7195,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInput 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, 'text') and self.text is not None: @@ -6745,7 +7212,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {'text'} if not hasattr(self, '_additionalProperties'): super(MessageInput, self).__setattr__('_additionalProperties', @@ -6754,17 +7225,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(MessageInput, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this MessageInput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageInput') -> 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): + def __ne__(self, other: 'MessageInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6775,10 +7246,10 @@ class MessageRequest(): :attr MessageInput input: (optional) An input object that includes the input text. - :attr list[RuntimeIntent] intents: (optional) Intents to use when evaluating the + :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. - :attr list[RuntimeEntity] entities: (optional) Entities to use when evaluating + :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. :attr bool alternate_intents: (optional) Whether to return more than one intent. @@ -6787,29 +7258,29 @@ class MessageRequest(): maintain state, include the context from the previous response. :attr OutputData output: (optional) An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr list[DialogNodeAction] actions: (optional) An array of objects describing + :attr List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. """ def __init__(self, *, - input=None, - intents=None, - entities=None, - alternate_intents=None, - context=None, - output=None, - actions=None): + input: 'MessageInput' = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + alternate_intents: bool = None, + context: 'Context' = None, + output: 'OutputData' = None, + actions: List['DialogNodeAction'] = None) -> None: """ Initialize a MessageRequest object. :param MessageInput input: (optional) An input object that includes the input text. - :param list[RuntimeIntent] intents: (optional) Intents to use when + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. - :param list[RuntimeEntity] entities: (optional) Entities to use when + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. @@ -6820,7 +7291,7 @@ def __init__(self, :param OutputData output: (optional) An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :param list[DialogNodeAction] actions: (optional) An array of objects + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. """ self.input = input @@ -6832,7 +7303,7 @@ def __init__(self, self.actions = actions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageRequest': """Initialize a MessageRequest object from a json dictionary.""" args = {} valid_keys = [ @@ -6866,7 +7337,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageRequest 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, 'input') and self.input is not None: @@ -6886,17 +7362,21 @@ def _to_dict(self): _dict['actions'] = [x._to_dict() for x in self.actions] return _dict - def __str__(self): + 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 MessageRequest object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageRequest') -> 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): + def __ne__(self, other: 'MessageRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6907,9 +7387,9 @@ class MessageResponse(): entities, and context. :attr MessageInput input: An input object that includes the input text. - :attr list[RuntimeIntent] intents: An array of intents recognized in the user + :attr List[RuntimeIntent] intents: An array of intents recognized in the user input, sorted in descending order of confidence. - :attr list[RuntimeEntity] entities: An array of entities identified in the user + :attr List[RuntimeEntity] entities: An array of entities identified in the user input. :attr bool alternate_intents: (optional) Whether to return more than one intent. A value of `true` indicates that all matching intents are returned. @@ -6917,26 +7397,26 @@ class MessageResponse(): state, include the context from the previous response. :attr OutputData output: An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr list[DialogNodeAction] actions: (optional) An array of objects describing + :attr List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. """ def __init__(self, - input, - intents, - entities, - context, - output, + input: 'MessageInput', + intents: List['RuntimeIntent'], + entities: List['RuntimeEntity'], + context: 'Context', + output: 'OutputData', *, - alternate_intents=None, - actions=None): + alternate_intents: bool = None, + actions: List['DialogNodeAction'] = None) -> None: """ Initialize a MessageResponse object. :param MessageInput input: An input object that includes the input text. - :param list[RuntimeIntent] intents: An array of intents recognized in the + :param List[RuntimeIntent] intents: An array of intents recognized in the user input, sorted in descending order of confidence. - :param list[RuntimeEntity] entities: An array of entities identified in the + :param List[RuntimeEntity] entities: An array of entities identified in the user input. :param Context context: State information for the conversation. To maintain state, include the context from the previous response. @@ -6944,7 +7424,7 @@ def __init__(self, the user, the dialog nodes that were triggered, and messages from the log. :param bool alternate_intents: (optional) Whether to return more than one intent. A value of `true` indicates that all matching intents are returned. - :param list[DialogNodeAction] actions: (optional) An array of objects + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. """ self.input = input @@ -6956,7 +7436,7 @@ def __init__(self, self.actions = actions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageResponse': """Initialize a MessageResponse object from a json dictionary.""" args = {} valid_keys = [ @@ -7010,7 +7490,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageResponse 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, 'input') and self.input is not None: @@ -7030,17 +7515,21 @@ def _to_dict(self): _dict['actions'] = [x._to_dict() for x in self.actions] return _dict - def __str__(self): + 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 MessageResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageResponse') -> 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): + def __ne__(self, other: 'MessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7050,45 +7539,45 @@ class OutputData(): An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr list[str] nodes_visited: (optional) An array of the nodes that were + :attr List[str] nodes_visited: (optional) An array of the nodes that were triggered to create the response, in the order in which they were visited. This information is useful for debugging and for tracing the path taken through the node tree. - :attr list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array + :attr List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message request. - :attr list[LogMessage] log_messages: An array of up to 50 messages logged with + :attr List[LogMessage] log_messages: An array of up to 50 messages logged with the request. - :attr list[str] text: An array of responses to the user. - :attr list[RuntimeResponseGeneric] generic: (optional) Output intended for any + :attr List[str] text: An array of responses to the user. + :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. """ def __init__(self, - log_messages, - text, + log_messages: List['LogMessage'], + text: List[str], *, - nodes_visited=None, - nodes_visited_details=None, - generic=None, - **kwargs): + nodes_visited: List[str] = None, + nodes_visited_details: List['DialogNodeVisitedDetails'] = None, + generic: List['RuntimeResponseGeneric'] = None, + **kwargs) -> None: """ Initialize a OutputData object. - :param list[LogMessage] log_messages: An array of up to 50 messages logged + :param List[LogMessage] log_messages: An array of up to 50 messages logged with the request. - :param list[str] text: An array of responses to the user. - :param list[str] nodes_visited: (optional) An array of the nodes that were + :param List[str] text: An array of responses to the user. + :param List[str] nodes_visited: (optional) An array of the nodes that were triggered to create the response, in the order in which they were visited. This information is useful for debugging and for tracing the path taken through the node tree. - :param list[DialogNodeVisitedDetails] nodes_visited_details: (optional) An + :param List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message request. - :param list[RuntimeResponseGeneric] generic: (optional) Output intended for + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. :param **kwargs: (optional) Any additional properties. @@ -7102,7 +7591,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'OutputData': """Initialize a OutputData object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -7139,7 +7628,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a OutputData 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, 'nodes_visited') and self.nodes_visited is not None: @@ -7162,7 +7656,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = { 'nodes_visited', 'nodes_visited_details', 'log_messages', 'text', 'generic' @@ -7173,17 +7671,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(OutputData, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this OutputData object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'OutputData') -> 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): + def __ne__(self, other: 'OutputData') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7203,13 +7701,13 @@ class Pagination(): """ def __init__(self, - refresh_url, + refresh_url: str, *, - next_url=None, - total=None, - matched=None, - refresh_cursor=None, - next_cursor=None): + next_url: str = None, + total: int = None, + matched: int = None, + refresh_cursor: str = None, + next_cursor: str = None) -> None: """ Initialize a Pagination object. @@ -7231,7 +7729,7 @@ def __init__(self, self.next_cursor = next_cursor @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Pagination': """Initialize a Pagination object from a json dictionary.""" args = {} valid_keys = [ @@ -7261,7 +7759,12 @@ def _from_dict(cls, _dict): args['next_cursor'] = _dict.get('next_cursor') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Pagination 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, 'refresh_url') and self.refresh_url is not None: @@ -7278,17 +7781,21 @@ def _to_dict(self): _dict['next_cursor'] = self.next_cursor return _dict - def __str__(self): + 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 Pagination object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Pagination') -> 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): + def __ne__(self, other: 'Pagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7298,35 +7805,35 @@ class RuntimeEntity(): A term from the request that was identified as an entity. :attr str entity: An entity detected in the input. - :attr list[int] location: An array of zero-based character offsets that indicate + :attr List[int] location: An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. :attr str value: 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. :attr dict metadata: (optional) Any metadata for the entity. - :attr list[CaptureGroup] groups: (optional) The recognized capture groups for + :attr List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. """ def __init__(self, - entity, - location, - value, + entity: str, + location: List[int], + value: str, *, - confidence=None, - metadata=None, - groups=None): + confidence: float = None, + metadata: dict = None, + groups: List['CaptureGroup'] = None) -> None: """ Initialize a RuntimeEntity object. :param str entity: An entity detected in the input. - :param list[int] location: An array of zero-based character offsets that + :param List[int] location: An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. :param str value: 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. :param dict metadata: (optional) Any metadata for the entity. - :param list[CaptureGroup] groups: (optional) The recognized capture groups + :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. """ self.entity = entity @@ -7337,7 +7844,7 @@ def __init__(self, self.groups = groups @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} valid_keys = [ @@ -7375,7 +7882,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntity 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, 'entity') and self.entity is not None: @@ -7392,17 +7904,21 @@ def _to_dict(self): _dict['groups'] = [x._to_dict() for x in self.groups] return _dict - def __str__(self): + 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 RuntimeEntity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeEntity') -> 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): + def __ne__(self, other: 'RuntimeEntity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7416,7 +7932,7 @@ class RuntimeIntent(): in the intent. """ - def __init__(self, intent, confidence): + def __init__(self, intent: str, confidence: float) -> None: """ Initialize a RuntimeIntent object. @@ -7428,7 +7944,7 @@ def __init__(self, intent, confidence): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': """Initialize a RuntimeIntent object from a json dictionary.""" args = {} valid_keys = ['intent', 'confidence'] @@ -7451,7 +7967,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeIntent 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, 'intent') and self.intent is not None: @@ -7460,17 +7981,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 RuntimeIntent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeIntent') -> 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): + def __ne__(self, other: 'RuntimeIntent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7492,7 +8017,7 @@ class RuntimeResponseGeneric(): response. :attr str description: (optional) The description to show with the the response. :attr str preference: (optional) The preferred type of control to display. - :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of + :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. @@ -7501,27 +8026,27 @@ class RuntimeResponseGeneric(): :attr str dialog_node: (optional) The ID of the dialog node that the **topic** property is taken from. The **topic** property is populated using the value of the dialog node's **user_label** property. - :attr list[DialogSuggestion] suggestions: (optional) An array of objects + :attr List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Plus and Premium users. """ def __init__(self, - response_type, + response_type: str, *, - text=None, - time=None, - typing=None, - source=None, - title=None, - description=None, - preference=None, - options=None, - message_to_human_agent=None, - topic=None, - dialog_node=None, - suggestions=None): + text: str = None, + time: int = None, + typing: bool = None, + source: str = None, + title: str = None, + description: str = None, + preference: str = None, + options: List['DialogNodeOutputOptionsElement'] = None, + message_to_human_agent: str = None, + topic: str = None, + dialog_node: str = None, + suggestions: List['DialogSuggestion'] = None) -> None: """ Initialize a RuntimeResponseGeneric object. @@ -7540,7 +8065,7 @@ def __init__(self, :param str description: (optional) The description to show with the the response. :param str preference: (optional) The preferred type of control to display. - :param list[DialogNodeOutputOptionsElement] options: (optional) An array of + :param List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. @@ -7550,7 +8075,7 @@ def __init__(self, :param str dialog_node: (optional) The ID of the dialog node that the **topic** property is taken from. The **topic** property is populated using the value of the dialog node's **user_label** property. - :param list[DialogSuggestion] suggestions: (optional) An array of objects + :param List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation @@ -7571,7 +8096,7 @@ def __init__(self, self.suggestions = suggestions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': """Initialize a RuntimeResponseGeneric object from a json dictionary.""" args = {} valid_keys = [ @@ -7622,7 +8147,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGeneric 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, 'response_type') and self.response_type is not None: @@ -7654,17 +8184,21 @@ def _to_dict(self): _dict['suggestions'] = [x._to_dict() for x in self.suggestions] return _dict - def __str__(self): + 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 RuntimeResponseGeneric object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeResponseGeneric') -> 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): + def __ne__(self, other: 'RuntimeResponseGeneric') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7703,7 +8237,11 @@ class Synonym(): the object. """ - def __init__(self, synonym, *, created=None, updated=None): + def __init__(self, + synonym: str, + *, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a Synonym object. @@ -7721,7 +8259,7 @@ def __init__(self, synonym, *, created=None, updated=None): self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Synonym': """Initialize a Synonym object from a json dictionary.""" args = {} valid_keys = ['synonym', 'created', 'updated'] @@ -7741,7 +8279,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Synonym 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, 'synonym') and self.synonym is not None: @@ -7752,17 +8295,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 Synonym object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Synonym') -> 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): + def __ne__(self, other: 'Synonym') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7771,22 +8318,23 @@ class SynonymCollection(): """ SynonymCollection. - :attr list[Synonym] synonyms: An array of synonyms. + :attr List[Synonym] synonyms: An array of synonyms. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, synonyms, pagination): + def __init__(self, synonyms: List['Synonym'], + pagination: 'Pagination') -> None: """ Initialize a SynonymCollection object. - :param list[Synonym] synonyms: An array of synonyms. + :param List[Synonym] synonyms: An array of synonyms. :param Pagination pagination: The pagination data for the returned objects. """ self.synonyms = synonyms self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SynonymCollection': """Initialize a SynonymCollection object from a json dictionary.""" args = {} valid_keys = ['synonyms', 'pagination'] @@ -7811,7 +8359,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SynonymCollection 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, 'synonyms') and self.synonyms is not None: @@ -7820,17 +8373,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 SynonymCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SynonymCollection') -> 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): + def __ne__(self, other: 'SynonymCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7841,7 +8398,7 @@ class SystemResponse(): """ - def __init__(self, **kwargs): + def __init__(self, **kwargs) -> None: """ Initialize a SystemResponse object. @@ -7851,14 +8408,19 @@ def __init__(self, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SystemResponse': """Initialize a SystemResponse object from a json dictionary.""" args = {} xtra = _dict.copy() args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SystemResponse 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, '_additionalProperties'): @@ -7868,7 +8430,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {} if not hasattr(self, '_additionalProperties'): super(SystemResponse, self).__setattr__('_additionalProperties', @@ -7877,17 +8443,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(SystemResponse, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this SystemResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SystemResponse') -> 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): + def __ne__(self, other: 'SystemResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7902,12 +8468,12 @@ class Value(): - It cannot consist of only whitespace characters. :attr dict metadata: (optional) Any metadata related to the entity value. :attr str type: Specifies the type of entity value. - :attr list[str] synonyms: (optional) An array of synonyms for the entity value. + :attr List[str] synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr list[str] patterns: (optional) An array of patterns for the entity value. + :attr List[str] patterns: (optional) An array of patterns for the 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 @@ -7918,14 +8484,14 @@ class Value(): """ def __init__(self, - value, - type, + value: str, + type: str, *, - metadata=None, - synonyms=None, - patterns=None, - created=None, - updated=None): + metadata: dict = None, + synonyms: List[str] = None, + patterns: List[str] = None, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a Value object. @@ -7935,13 +8501,13 @@ def __init__(self, - It cannot consist of only whitespace characters. :param str type: Specifies the type of entity value. :param dict metadata: (optional) Any metadata related to the entity value. - :param list[str] synonyms: (optional) An array of synonyms for the entity + :param List[str] synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param list[str] patterns: (optional) An array of patterns for the entity + :param List[str] patterns: (optional) An array of patterns for the 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 @@ -7960,7 +8526,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Value': """Initialize a Value object from a json dictionary.""" args = {} valid_keys = [ @@ -7994,7 +8560,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Value 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: @@ -8013,17 +8584,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 Value object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Value') -> 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): + def __ne__(self, other: 'Value') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8039,22 +8614,22 @@ class ValueCollection(): """ ValueCollection. - :attr list[Value] values: An array of entity values. + :attr List[Value] values: An array of entity values. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, values, pagination): + def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: """ Initialize a ValueCollection object. - :param list[Value] values: An array of entity values. + :param List[Value] values: An array of entity values. :param Pagination pagination: The pagination data for the returned objects. """ self.values = values self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ValueCollection': """Initialize a ValueCollection object from a json dictionary.""" args = {} valid_keys = ['values', 'pagination'] @@ -8079,7 +8654,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ValueCollection 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, 'values') and self.values is not None: @@ -8088,17 +8668,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 ValueCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ValueCollection') -> 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): + def __ne__(self, other: 'ValueCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8113,11 +8697,15 @@ class Webhook(): to send HTTP POST requests. :attr str name: The name of the webhook. Currently, `main_webhook` is the only supported value. - :attr list[WebhookHeader] headers: (optional) An optional array of HTTP headers + :attr List[WebhookHeader] headers: (optional) An optional array of HTTP headers to pass with the HTTP request. """ - def __init__(self, url, name, *, headers=None): + def __init__(self, + url: str, + name: str, + *, + headers: List['WebhookHeader'] = None) -> None: """ Initialize a Webhook object. @@ -8125,7 +8713,7 @@ def __init__(self, url, name, *, headers=None): you want to send HTTP POST requests. :param str name: The name of the webhook. Currently, `main_webhook` is the only supported value. - :param list[WebhookHeader] headers: (optional) An optional array of HTTP + :param List[WebhookHeader] headers: (optional) An optional array of HTTP headers to pass with the HTTP request. """ self.url = url @@ -8133,7 +8721,7 @@ def __init__(self, url, name, *, headers=None): self.headers = headers @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Webhook': """Initialize a Webhook object from a json dictionary.""" args = {} valid_keys = ['url', 'name', 'headers'] @@ -8158,7 +8746,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Webhook 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, 'url') and self.url is not None: @@ -8169,17 +8762,21 @@ def _to_dict(self): _dict['headers'] = [x._to_dict() for x in self.headers] return _dict - def __str__(self): + 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 Webhook object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Webhook') -> 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): + def __ne__(self, other: 'Webhook') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8192,7 +8789,7 @@ class WebhookHeader(): :attr str value: The value of an HTTP header. """ - def __init__(self, name, value): + def __init__(self, name: str, value: str) -> None: """ Initialize a WebhookHeader object. @@ -8203,7 +8800,7 @@ def __init__(self, name, value): self.value = value @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WebhookHeader': """Initialize a WebhookHeader object from a json dictionary.""" args = {} valid_keys = ['name', 'value'] @@ -8224,7 +8821,12 @@ def _from_dict(cls, _dict): 'Required property \'value\' not present in WebhookHeader JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WebhookHeader 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, 'name') and self.name is not None: @@ -8233,17 +8835,21 @@ def _to_dict(self): _dict['value'] = self.value return _dict - def __str__(self): + 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 WebhookHeader object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WebhookHeader') -> 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): + def __ne__(self, other: 'WebhookHeader') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8268,33 +8874,33 @@ class Workspace(): :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. - :attr list[Intent] intents: (optional) An array of intents. - :attr list[Entity] entities: (optional) An array of objects describing the + :attr List[Intent] intents: (optional) An array of intents. + :attr List[Entity] entities: (optional) An array of objects describing the entities for the workspace. - :attr list[DialogNode] dialog_nodes: (optional) An array of objects describing + :attr List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. - :attr list[Counterexample] counterexamples: (optional) An array of + :attr List[Counterexample] counterexamples: (optional) An array of counterexamples. - :attr list[Webhook] webhooks: (optional) + :attr List[Webhook] webhooks: (optional) """ def __init__(self, - name, - language, - learning_opt_out, - workspace_id, + name: str, + language: str, + learning_opt_out: bool, + workspace_id: str, *, - description=None, - metadata=None, - system_settings=None, - status=None, - created=None, - updated=None, - intents=None, - entities=None, - dialog_nodes=None, - counterexamples=None, - webhooks=None): + description: str = None, + metadata: dict = None, + system_settings: 'WorkspaceSystemSettings' = None, + status: str = None, + created: datetime = None, + updated: datetime = None, + intents: List['Intent'] = None, + entities: List['Entity'] = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, + webhooks: List['Webhook'] = None) -> None: """ Initialize a Workspace object. @@ -8316,14 +8922,14 @@ def __init__(self, object. :param datetime updated: (optional) The timestamp for the most recent update to the object. - :param list[Intent] intents: (optional) An array of intents. - :param list[Entity] entities: (optional) An array of objects describing the + :param List[Intent] intents: (optional) An array of intents. + :param List[Entity] entities: (optional) An array of objects describing the entities for the workspace. - :param list[DialogNode] dialog_nodes: (optional) An array of objects + :param List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. - :param list[Counterexample] counterexamples: (optional) An array of + :param List[Counterexample] counterexamples: (optional) An array of counterexamples. - :param list[Webhook] webhooks: (optional) + :param List[Webhook] webhooks: (optional) """ self.name = name self.description = description @@ -8342,7 +8948,7 @@ def __init__(self, self.webhooks = webhooks @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Workspace': """Initialize a Workspace object from a json dictionary.""" args = {} valid_keys = [ @@ -8413,7 +9019,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Workspace 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, 'name') and self.name is not None: @@ -8453,17 +9064,21 @@ def _to_dict(self): _dict['webhooks'] = [x._to_dict() for x in self.webhooks] return _dict - def __str__(self): + 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 Workspace object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Workspace') -> 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): + def __ne__(self, other: 'Workspace') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8482,16 +9097,17 @@ class WorkspaceCollection(): """ WorkspaceCollection. - :attr list[Workspace] workspaces: An array of objects describing the workspaces + :attr List[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, workspaces, pagination): + def __init__(self, workspaces: List['Workspace'], + pagination: 'Pagination') -> None: """ Initialize a WorkspaceCollection object. - :param list[Workspace] workspaces: An array of objects describing the + :param List[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. :param Pagination pagination: The pagination data for the returned objects. """ @@ -8499,7 +9115,7 @@ def __init__(self, workspaces, pagination): self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WorkspaceCollection': """Initialize a WorkspaceCollection object from a json dictionary.""" args = {} valid_keys = ['workspaces', 'pagination'] @@ -8524,7 +9140,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceCollection 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, 'workspaces') and self.workspaces is not None: @@ -8533,17 +9154,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 WorkspaceCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WorkspaceCollection') -> 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): + def __ne__(self, other: 'WorkspaceCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8564,10 +9189,10 @@ class WorkspaceSystemSettings(): def __init__(self, *, - tooling=None, - disambiguation=None, - human_agent_assist=None, - off_topic=None): + tooling: 'WorkspaceSystemSettingsTooling' = None, + disambiguation: 'WorkspaceSystemSettingsDisambiguation' = None, + human_agent_assist: dict = None, + off_topic: 'WorkspaceSystemSettingsOffTopic' = None) -> None: """ Initialize a WorkspaceSystemSettings object. @@ -8586,7 +9211,7 @@ def __init__(self, self.off_topic = off_topic @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': """Initialize a WorkspaceSystemSettings object from a json dictionary.""" args = {} valid_keys = [ @@ -8611,7 +9236,12 @@ def _from_dict(cls, _dict): _dict.get('off_topic')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettings 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, 'tooling') and self.tooling is not None: @@ -8626,17 +9256,21 @@ def _to_dict(self): _dict['off_topic'] = self.off_topic._to_dict() return _dict - def __str__(self): + 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 WorkspaceSystemSettings object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WorkspaceSystemSettings') -> 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): + def __ne__(self, other: 'WorkspaceSystemSettings') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8667,13 +9301,13 @@ class WorkspaceSystemSettingsDisambiguation(): def __init__(self, *, - prompt=None, - none_of_the_above_prompt=None, - enabled=None, - sensitivity=None, - randomize=None, - max_suggestions=None, - suggestion_text_policy=None): + prompt: str = None, + none_of_the_above_prompt: str = None, + enabled: bool = None, + sensitivity: str = None, + randomize: bool = None, + max_suggestions: int = None, + suggestion_text_policy: str = None) -> None: """ Initialize a WorkspaceSystemSettingsDisambiguation object. @@ -8704,7 +9338,7 @@ def __init__(self, self.suggestion_text_policy = suggestion_text_policy @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsDisambiguation': """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" args = {} valid_keys = [ @@ -8733,7 +9367,12 @@ def _from_dict(cls, _dict): args['suggestion_text_policy'] = _dict.get('suggestion_text_policy') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettingsDisambiguation 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, 'prompt') and self.prompt is not None: @@ -8755,17 +9394,21 @@ def _to_dict(self): _dict['suggestion_text_policy'] = self.suggestion_text_policy return _dict - def __str__(self): + 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 WorkspaceSystemSettingsDisambiguation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WorkspaceSystemSettingsDisambiguation') -> 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): + def __ne__(self, other: 'WorkspaceSystemSettingsDisambiguation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8787,7 +9430,7 @@ class WorkspaceSystemSettingsOffTopic(): for the workspace. """ - def __init__(self, *, enabled=None): + def __init__(self, *, enabled: bool = None) -> None: """ Initialize a WorkspaceSystemSettingsOffTopic object. @@ -8797,7 +9440,7 @@ def __init__(self, *, enabled=None): self.enabled = enabled @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsOffTopic': """Initialize a WorkspaceSystemSettingsOffTopic object from a json dictionary.""" args = {} valid_keys = ['enabled'] @@ -8810,24 +9453,33 @@ def _from_dict(cls, _dict): args['enabled'] = _dict.get('enabled') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettingsOffTopic 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 __str__(self): + 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 WorkspaceSystemSettingsOffTopic object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WorkspaceSystemSettingsOffTopic') -> 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): + def __ne__(self, other: 'WorkspaceSystemSettingsOffTopic') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8840,7 +9492,7 @@ class WorkspaceSystemSettingsTooling(): displays text responses within the `output.generic` object. """ - def __init__(self, *, store_generic_responses=None): + def __init__(self, *, store_generic_responses: bool = None) -> None: """ Initialize a WorkspaceSystemSettingsTooling object. @@ -8850,7 +9502,7 @@ def __init__(self, *, store_generic_responses=None): self.store_generic_responses = store_generic_responses @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsTooling': """Initialize a WorkspaceSystemSettingsTooling object from a json dictionary.""" args = {} valid_keys = ['store_generic_responses'] @@ -8864,7 +9516,12 @@ def _from_dict(cls, _dict): 'store_generic_responses') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettingsTooling 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, 'store_generic_responses' @@ -8872,16 +9529,20 @@ def _to_dict(self): _dict['store_generic_responses'] = self.store_generic_responses return _dict - def __str__(self): + 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 WorkspaceSystemSettingsTooling object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WorkspaceSystemSettingsTooling') -> 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): + def __ne__(self, other: 'WorkspaceSystemSettingsTooling') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 8ef258a87..458f26b46 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,1576 +1,3565 @@ -# coding: utf-8 +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -import datetime -from dateutil.tz import tzutc +import pytest import responses -import ibm_watson -from ibm_watson import ApiException -from ibm_watson.assistant_v1 import Context, Counterexample, \ - CounterexampleCollection, Entity, EntityCollection, Example, \ - ExampleCollection, MessageInput, Intent, IntentCollection, Synonym, \ - SynonymCollection, Value, ValueCollection, Workspace, WorkspaceCollection, Webhook, WebhookHeader -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -platform_url = 'https://gateway.watsonplatform.net' -service_path = '/assistant/api' -base_url = '{0}{1}'.format(platform_url, service_path) - -######################### -# counterexamples -######################### - - -@responses.activate -def test_create_counterexample(): - endpoint = '/v1/workspaces/{0}/counterexamples'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "I want financial advice today.", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) - service.set_service_url(base_url) - counterexample = service.create_counterexample( - workspace_id='boguswid', text='I want financial advice today.').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert counterexample == response - # Verify that response can be converted to a Counterexample - Counterexample._from_dict(counterexample) - -@responses.activate -def test_rate_limit_exceeded(): - endpoint = '/v1/workspaces/{0}/counterexamples'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - error_code = 429 - error_msg = 'Rate limit exceeded' - responses.add( - responses.POST, - url, - body='Rate limit exceeded', - status=429, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) +import ibm_watson.assistant_v1 +from ibm_watson.assistant_v1 import * + +base_url = 'https://gateway.watsonplatform.net/assistant/api' + +############################################################################## +# Start of Service: Message +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for message +#----------------------------------------------------------------------------- +class TestMessage(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_response(self): + body = self.construct_full_body() + response = fake_response_MessageResponse_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_message_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MessageResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_empty(self): + check_empty_required_params(self, fake_response_MessageResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/message'.format(body['workspace_id']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.message(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"input": MessageInput._from_dict(json.loads("""{"text": "fake_text"}""")), "intents": [], "entities": [], "alternate_intents": True, "context": Context._from_dict(json.loads("""{"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}""")), "output": OutputData._from_dict(json.loads("""{"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}""")), }) + body['nodes_visited_details'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Message +############################################################################## + +############################################################################## +# Start of Service: Workspaces +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_workspaces +#----------------------------------------------------------------------------- +class TestListWorkspaces(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_workspaces_response(self): + body = self.construct_full_body() + response = fake_response_WorkspaceCollection_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_workspaces_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_WorkspaceCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_workspaces_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces' + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_workspaces(**body) + return output + + def construct_full_body(self): + body = dict() + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_workspace +#----------------------------------------------------------------------------- +class TestCreateWorkspace(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_workspace_response(self): + body = self.construct_full_body() + response = fake_response_Workspace_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_create_workspace_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Workspace_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_workspace_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces' + 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=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_workspace(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_workspace +#----------------------------------------------------------------------------- +class TestGetWorkspace(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_workspace_response(self): + body = self.construct_full_body() + response = fake_response_Workspace_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_workspace_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Workspace_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_workspace_empty(self): + check_empty_required_params(self, fake_response_Workspace_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}'.format(body['workspace_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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_workspace(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['export'] = True + body['include_audit'] = True + body['sort'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_workspace +#----------------------------------------------------------------------------- +class TestUpdateWorkspace(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_workspace_response(self): + body = self.construct_full_body() + response = fake_response_Workspace_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_workspace_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Workspace_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_workspace_empty(self): + check_empty_required_params(self, fake_response_Workspace_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}'.format(body['workspace_id']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_workspace(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + body['append'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_workspace +#----------------------------------------------------------------------------- +class TestDeleteWorkspace(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_workspace_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_workspace_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_workspace_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 = '/v1/workspaces/{0}'.format(body['workspace_id']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_workspace(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Workspaces +############################################################################## + +############################################################################## +# Start of Service: Intents +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_intents +#----------------------------------------------------------------------------- +class TestListIntents(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_intents_response(self): + body = self.construct_full_body() + response = fake_response_IntentCollection_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_intents_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_IntentCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_intents_empty(self): + check_empty_required_params(self, fake_response_IntentCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents'.format(body['workspace_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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_intents(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['export'] = True + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_intent +#----------------------------------------------------------------------------- +class TestCreateIntent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_intent_response(self): + body = self.construct_full_body() + response = fake_response_Intent_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_create_intent_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Intent_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_intent_empty(self): + check_empty_required_params(self, fake_response_Intent_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents'.format(body['workspace_id']) + 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=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_intent(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"intent": "string1", "description": "string1", "examples": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"intent": "string1", "description": "string1", "examples": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_intent +#----------------------------------------------------------------------------- +class TestGetIntent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_intent_response(self): + body = self.construct_full_body() + response = fake_response_Intent_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_intent_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Intent_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_intent_empty(self): + check_empty_required_params(self, fake_response_Intent_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_intent(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['export'] = True + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_intent +#----------------------------------------------------------------------------- +class TestUpdateIntent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_intent_response(self): + body = self.construct_full_body() + response = fake_response_Intent_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_intent_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Intent_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_intent_empty(self): + check_empty_required_params(self, fake_response_Intent_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_intent(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_intent +#----------------------------------------------------------------------------- +class TestDeleteIntent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_intent_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_intent_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_intent_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 = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_intent(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Intents +############################################################################## + +############################################################################## +# Start of Service: Examples +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_examples +#----------------------------------------------------------------------------- +class TestListExamples(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_examples_response(self): + body = self.construct_full_body() + response = fake_response_ExampleCollection_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_examples_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ExampleCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_examples_empty(self): + check_empty_required_params(self, fake_response_ExampleCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_examples(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_example +#----------------------------------------------------------------------------- +class TestCreateExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_example_response(self): + body = self.construct_full_body() + response = fake_response_Example_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_create_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Example_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_example_empty(self): + check_empty_required_params(self, fake_response_Example_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) + 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=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body.update({"text": "string1", "mentions": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body.update({"text": "string1", "mentions": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_example +#----------------------------------------------------------------------------- +class TestGetExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_example_response(self): + body = self.construct_full_body() + response = fake_response_Example_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_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Example_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_example_empty(self): + check_empty_required_params(self, fake_response_Example_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_example +#----------------------------------------------------------------------------- +class TestUpdateExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_example_response(self): + body = self.construct_full_body() + response = fake_response_Example_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_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Example_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_example_empty(self): + check_empty_required_params(self, fake_response_Example_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + body.update({"new_text": "string1", "new_mentions": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + body.update({"new_text": "string1", "new_mentions": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_example +#----------------------------------------------------------------------------- +class TestDeleteExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_example_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_example_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_example_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 = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['intent'] = "string1" + body['text'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Examples +############################################################################## + +############################################################################## +# Start of Service: Counterexamples +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_counterexamples +#----------------------------------------------------------------------------- +class TestListCounterexamples(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_counterexamples_response(self): + body = self.construct_full_body() + response = fake_response_CounterexampleCollection_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_counterexamples_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CounterexampleCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_counterexamples_empty(self): + check_empty_required_params(self, fake_response_CounterexampleCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_counterexamples(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_counterexample +#----------------------------------------------------------------------------- +class TestCreateCounterexample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_counterexample_response(self): + body = self.construct_full_body() + response = fake_response_Counterexample_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_create_counterexample_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Counterexample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_counterexample_empty(self): + check_empty_required_params(self, fake_response_Counterexample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_id']) + 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=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_counterexample(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"text": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"text": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_counterexample +#----------------------------------------------------------------------------- +class TestGetCounterexample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_counterexample_response(self): + body = self.construct_full_body() + response = fake_response_Counterexample_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_counterexample_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Counterexample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_counterexample_empty(self): + check_empty_required_params(self, fake_response_Counterexample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_counterexample(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_counterexample +#----------------------------------------------------------------------------- +class TestUpdateCounterexample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_counterexample_response(self): + body = self.construct_full_body() + response = fake_response_Counterexample_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_counterexample_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Counterexample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_counterexample_empty(self): + check_empty_required_params(self, fake_response_Counterexample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_counterexample(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + body.update({"new_text": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + body.update({"new_text": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_counterexample +#----------------------------------------------------------------------------- +class TestDeleteCounterexample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_counterexample_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_counterexample_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_counterexample_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 = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_counterexample(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['text'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Counterexamples +############################################################################## + +############################################################################## +# Start of Service: Entities +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_entities +#----------------------------------------------------------------------------- +class TestListEntities(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_entities_response(self): + body = self.construct_full_body() + response = fake_response_EntityCollection_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_entities_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_EntityCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_entities_empty(self): + check_empty_required_params(self, fake_response_EntityCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities'.format(body['workspace_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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_entities(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['export'] = True + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_entity +#----------------------------------------------------------------------------- +class TestCreateEntity(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_entity_response(self): + body = self.construct_full_body() + response = fake_response_Entity_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_create_entity_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Entity_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_entity_empty(self): + check_empty_required_params(self, fake_response_Entity_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities'.format(body['workspace_id']) + 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=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_entity(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_entity +#----------------------------------------------------------------------------- +class TestGetEntity(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_entity_response(self): + body = self.construct_full_body() + response = fake_response_Entity_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_entity_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Entity_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_entity_empty(self): + check_empty_required_params(self, fake_response_Entity_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_entity(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['export'] = True + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_entity +#----------------------------------------------------------------------------- +class TestUpdateEntity(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_entity_response(self): + body = self.construct_full_body() + response = fake_response_Entity_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_entity_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Entity_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_entity_empty(self): + check_empty_required_params(self, fake_response_Entity_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_entity(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_entity +#----------------------------------------------------------------------------- +class TestDeleteEntity(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_entity_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_entity_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_entity_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 = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_entity(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Entities +############################################################################## + +############################################################################## +# Start of Service: Mentions +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_mentions +#----------------------------------------------------------------------------- +class TestListMentions(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_mentions_response(self): + body = self.construct_full_body() + response = fake_response_EntityMentionCollection_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_mentions_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_EntityMentionCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_mentions_empty(self): + check_empty_required_params(self, fake_response_EntityMentionCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/mentions'.format(body['workspace_id'], body['entity']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_mentions(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['export'] = True + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Mentions +############################################################################## + +############################################################################## +# Start of Service: Values +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_values +#----------------------------------------------------------------------------- +class TestListValues(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_values_response(self): + body = self.construct_full_body() + response = fake_response_ValueCollection_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_values_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ValueCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_values_empty(self): + check_empty_required_params(self, fake_response_ValueCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_values(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['export'] = True + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_value +#----------------------------------------------------------------------------- +class TestCreateValue(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_value_response(self): + body = self.construct_full_body() + response = fake_response_Value_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_create_value_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Value_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_value_empty(self): + check_empty_required_params(self, fake_response_Value_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) + 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=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_value(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_value +#----------------------------------------------------------------------------- +class TestGetValue(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_value_response(self): + body = self.construct_full_body() + response = fake_response_Value_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_value_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Value_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_value_empty(self): + check_empty_required_params(self, fake_response_Value_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_value(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['export'] = True + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_value +#----------------------------------------------------------------------------- +class TestUpdateValue(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_value_response(self): + body = self.construct_full_body() + response = fake_response_Value_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_value_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Value_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_value_empty(self): + check_empty_required_params(self, fake_response_Value_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_value(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_value +#----------------------------------------------------------------------------- +class TestDeleteValue(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_value_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_value_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_value_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 = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_value(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Values +############################################################################## + +############################################################################## +# Start of Service: Synonyms +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_synonyms +#----------------------------------------------------------------------------- +class TestListSynonyms(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_synonyms_response(self): + body = self.construct_full_body() + response = fake_response_SynonymCollection_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_synonyms_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_SynonymCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_synonyms_empty(self): + check_empty_required_params(self, fake_response_SynonymCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_synonyms(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_synonym +#----------------------------------------------------------------------------- +class TestCreateSynonym(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_synonym_response(self): + body = self.construct_full_body() + response = fake_response_Synonym_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_create_synonym_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Synonym_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_synonym_empty(self): + check_empty_required_params(self, fake_response_Synonym_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) + 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=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_synonym(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body.update({"synonym": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body.update({"synonym": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_synonym +#----------------------------------------------------------------------------- +class TestGetSynonym(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_synonym_response(self): + body = self.construct_full_body() + response = fake_response_Synonym_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_synonym_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Synonym_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_synonym_empty(self): + check_empty_required_params(self, fake_response_Synonym_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_synonym(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_synonym +#----------------------------------------------------------------------------- +class TestUpdateSynonym(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_synonym_response(self): + body = self.construct_full_body() + response = fake_response_Synonym_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_synonym_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Synonym_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_synonym_empty(self): + check_empty_required_params(self, fake_response_Synonym_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_synonym(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + body.update({"new_synonym": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + body.update({"new_synonym": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_synonym +#----------------------------------------------------------------------------- +class TestDeleteSynonym(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_synonym_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_synonym_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_synonym_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 = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_synonym(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['entity'] = "string1" + body['value'] = "string1" + body['synonym'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Synonyms +############################################################################## + +############################################################################## +# Start of Service: DialogNodes +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_dialog_nodes +#----------------------------------------------------------------------------- +class TestListDialogNodes(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_dialog_nodes_response(self): + body = self.construct_full_body() + response = fake_response_DialogNodeCollection_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_dialog_nodes_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DialogNodeCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_dialog_nodes_empty(self): + check_empty_required_params(self, fake_response_DialogNodeCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_dialog_nodes(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['page_limit'] = 12345 + body['sort'] = "string1" + body['cursor'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_dialog_node +#----------------------------------------------------------------------------- +class TestCreateDialogNode(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_dialog_node_response(self): + body = self.construct_full_body() + response = fake_response_DialogNode_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_create_dialog_node_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DialogNode_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_dialog_node_empty(self): + check_empty_required_params(self, fake_response_DialogNode_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_id']) + 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=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_dialog_node(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_dialog_node +#----------------------------------------------------------------------------- +class TestGetDialogNode(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_dialog_node_response(self): + body = self.construct_full_body() + response = fake_response_DialogNode_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_dialog_node_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DialogNode_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_dialog_node_empty(self): + check_empty_required_params(self, fake_response_DialogNode_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.get_dialog_node(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + body['include_audit'] = True + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_dialog_node +#----------------------------------------------------------------------------- +class TestUpdateDialogNode(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_dialog_node_response(self): + body = self.construct_full_body() + response = fake_response_DialogNode_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_dialog_node_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DialogNode_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_dialog_node_empty(self): + check_empty_required_params(self, fake_response_DialogNode_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.update_dialog_node(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_dialog_node +#----------------------------------------------------------------------------- +class TestDeleteDialogNode(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_dialog_node_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_dialog_node_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_dialog_node_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 = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_dialog_node(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + body['dialog_node'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: DialogNodes +############################################################################## + +############################################################################## +# Start of Service: Logs +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_logs +#----------------------------------------------------------------------------- +class TestListLogs(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_logs_response(self): + body = self.construct_full_body() + response = fake_response_LogCollection_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_logs_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LogCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_logs_empty(self): + check_empty_required_params(self, fake_response_LogCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/logs'.format(body['workspace_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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_logs(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body['sort'] = "string1" + body['filter'] = "string1" + body['page_limit'] = 12345 + body['cursor'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_all_logs +#----------------------------------------------------------------------------- +class TestListAllLogs(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_all_logs_response(self): + body = self.construct_full_body() + response = fake_response_LogCollection_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_all_logs_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LogCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_all_logs_empty(self): + check_empty_required_params(self, fake_response_LogCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/logs' + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.list_all_logs(**body) + return output + + def construct_full_body(self): + body = dict() + body['filter'] = "string1" + body['sort'] = "string1" + body['page_limit'] = 12345 + body['cursor'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['filter'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Logs +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_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_user_data_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_user_data_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 = '/v1/user_data' + 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=202, + content_type='') + + def call_service(self, body): + service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False try: - service.create_counterexample( - workspace_id='boguswid', text='I want financial advice today.') - except ApiException as ex: - assert len(responses.calls) == 1 - assert isinstance(ex, ApiException) - assert error_code == ex.code - assert error_msg in str(ex) - -@responses.activate -def test_unknown_error(): - endpoint = '/v1/workspaces/{0}/counterexamples'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - error_msg = 'Unknown error' - responses.add( - responses.POST, - url, - status=407, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False try: - service.create_counterexample( - workspace_id='boguswid', text='I want financial advice today.') - except ApiException as ex: - assert len(responses.calls) == 1 - assert error_msg in str(ex) - -@responses.activate -def test_delete_counterexample(): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( - 'boguswid', 'I%20want%20financial%20advice%20today') - url = '{0}{1}'.format(base_url, endpoint) - response = None - responses.add( - responses.DELETE, - url, - body=response, - status=204, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - counterexample = service.delete_counterexample( - workspace_id='boguswid', text='I want financial advice today').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert counterexample is None - - -@responses.activate -def test_get_counterexample(): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( - 'boguswid', 'What%20are%20you%20wearing%3F') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "What are you wearing?", - "created": "2016-07-11T23:53:59.153Z", - "updated": "2016-12-07T18:53:59.153Z" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - counterexample = service.get_counterexample( - workspace_id='boguswid', text='What are you wearing?').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert counterexample == response - # Verify that response can be converted to a Counterexample - Counterexample._from_dict(counterexample) - -@responses.activate -def test_list_counterexamples(): - endpoint = '/v1/workspaces/{0}/counterexamples'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "counterexamples": [{ - "text": "I want financial advice today.", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - }, { - "text": "What are you wearing today", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/counterexamples?version=2017-12-18&page_limit=2", - "next_url": - "/v1/workspaces/pizza_app-e0f3/counterexamples?cursor=base64=&version=2017-12-18&page_limit=2" - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - counterexamples = service.list_counterexamples(workspace_id='boguswid').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert counterexamples == response - # Verify that response can be converted to a CounterexampleCollection - CounterexampleCollection._from_dict(counterexamples) - -@responses.activate -def test_update_counterexample(): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( - 'boguswid', 'What%20are%20you%20wearing%3F') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "What are you wearing?", - "created": "2016-07-11T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - counterexample = service.update_counterexample( - workspace_id='boguswid', - text='What are you wearing?', - new_text='What are you wearing?').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert counterexample == response - # Verify that response can be converted to a Counterexample - Counterexample._from_dict(counterexample) - -######################### -# entities -######################### - - -@responses.activate -def test_create_entity(): - endpoint = '/v1/workspaces/{0}/entities'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "entity": "pizza_toppings", - "description": "Tasty pizza toppings", - "created": "2015-12-06T04:32:20.000Z", - "updated": "2015-12-07T18:53:59.153Z", - "metadata": { - "property": "value" - } - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - entity = service.create_entity( - workspace_id='boguswid', - entity='pizza_toppings', - description='Tasty pizza toppings', - metadata={"property": "value"}, - values=None, - fuzzy_match=None).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert entity == response - # Verify that response can be converted to an Entity - Entity._from_dict(entity) - -@responses.activate -def test_delete_entity(): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format('boguswid', 'pizza_toppings') - url = '{0}{1}'.format(base_url, endpoint) - response = "" - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - entity = service.delete_entity(workspace_id='boguswid', entity='pizza_toppings').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert entity == "" - - -@responses.activate -def test_get_entity(): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format('boguswid', 'pizza_toppings') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "entity": "pizza_toppings", - "description": "Tasty pizza toppings", - "created": "2015-12-06T04:32:20.000Z", - "updated": "2015-12-07T18:53:59.153Z", - "metadata": { - "property": "value" - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - entity = service.get_entity(workspace_id='boguswid', entity='pizza_toppings', export=True).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert entity == response - # Verify that response can be converted to an Entity - Entity._from_dict(entity) - - -@responses.activate -def test_list_entities(): - endpoint = '/v1/workspaces/{0}/entities'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "entities": [{ - "entity": "pizza_toppings", - "description": "Tasty pizza toppings", - "created": "2015-12-06T04:32:20.000Z", - "updated": "2015-12-07T18:53:59.153Z", - "metadata": { - "property": "value" - } - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/entities?version=2017-12-18&filter=name:pizza&include_count=true&page_limit=1", - "next_url": - "/v1/workspaces/pizza_app-e0f3/entities?cursor=base64=&version=2017-12-18&filter=name:pizza&page_limit=1", - "total": - 1, - "matched": - 1 - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - entities = service.list_entities( - workspace_id='boguswid', - export=True).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert entities == response - # Verify that response can be converted to an EntityCollection - EntityCollection._from_dict(entities) - - -@responses.activate -def test_update_entity(): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format('boguswid', 'pizza_toppings') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "entity": "pizza_toppings", - "description": "Tasty pizza toppings", - "created": "2015-12-06T04:32:20.000Z", - "updated": "2015-12-07T18:53:59.153Z", - "metadata": { - "property": "value" - } - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - entity = service.update_entity( - workspace_id='boguswid', - entity='pizza_toppings', - new_entity='pizza_toppings').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert entity == response - # Verify that response can be converted to an Entity - Entity._from_dict(entity) - - -######################### -# examples -######################### - - -@responses.activate -def test_create_example(): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format( - 'boguswid', 'pizza_order') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "Gimme a pizza with pepperoni", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - example = service.create_example( - workspace_id='boguswid', - intent='pizza_order', - text='Gimme a pizza with pepperoni', - mentions=[{'entity': 'xxx', 'location': [0, 1]}]).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert example == response - # Verify that response can be converted to an Example - Example._from_dict(example) - - -@responses.activate -def test_delete_example(): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - 'boguswid', 'pizza_order', 'Gimme%20a%20pizza%20with%20pepperoni') - url = '{0}{1}'.format(base_url, endpoint) - response = {} - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - example = service.delete_example( - workspace_id='boguswid', - intent='pizza_order', - text='Gimme a pizza with pepperoni').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert example is None - - -@responses.activate -def test_get_example(): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - 'boguswid', 'pizza_order', 'Gimme%20a%20pizza%20with%20pepperoni') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "Gimme a pizza with pepperoni", - "created": "2016-07-11T23:53:59.153Z", - "updated": "2016-12-07T18:53:59.153Z" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1(version='2017-02-03', authenticator=authenticator) - example = service.get_example( - workspace_id='boguswid', - intent='pizza_order', - text='Gimme a pizza with pepperoni').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert example == response - # Verify that response can be converted to an Example - Example._from_dict(example) - - -@responses.activate -def test_list_examples(): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format( - 'boguswid', 'pizza_order') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "examples": [{ - "text": "Can I order a pizza?", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - }, { - "text": "Gimme a pizza with pepperoni", - "created": "2016-07-11T16:39:01.774Z", - "updated": "2015-12-07T18:53:59.153Z" - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/intents/order/examples?version=2017-12-18&page_limit=2", - "next_url": - "/v1/workspaces/pizza_app-e0f3/intents/order/examples?cursor=base64=&version=2017-12-18&page_limit=2" - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - examples = service.list_examples( - workspace_id='boguswid', intent='pizza_order').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert examples == response - # Verify that response can be converted to an ExampleCollection - ExampleCollection._from_dict(examples) - - -@responses.activate -def test_update_example(): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - 'boguswid', 'pizza_order', 'Gimme%20a%20pizza%20with%20pepperoni') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "text": "Gimme a pizza with pepperoni", - "created": "2016-07-11T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - example = service.update_example( - workspace_id='boguswid', - intent='pizza_order', - text='Gimme a pizza with pepperoni', - new_text='Gimme a pizza with pepperoni', - new_mentions=[{'entity': 'xxx', 'location': [0, 1]}]).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert example == response - # Verify that response can be converted to an Example - Example._from_dict(example) - - -######################### -# intents -######################### - - -@responses.activate -def test_create_intent(): - endpoint = '/v1/workspaces/{0}/intents'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "intent": "pizza_order", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z", - "description": "User wants to start a new pizza order" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - intent = service.create_intent( - workspace_id='boguswid', - intent='pizza_order', - description='User wants to start a new pizza order').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert intent == response - # Verify that response can be converted to an Intent - Intent._from_dict(intent) - - -@responses.activate -def test_delete_intent(): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format('boguswid', - 'pizza_order') - url = '{0}{1}'.format(base_url, endpoint) - response = None - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - intent = service.delete_intent( - workspace_id='boguswid', intent='pizza_order').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert intent is None - - -@responses.activate -def test_get_intent(): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format('boguswid', - 'pizza_order') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "intent": "pizza_order", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z", - "description": "User wants to start a new pizza order" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - intent = service.get_intent( - workspace_id='boguswid', intent='pizza_order', export=False).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert intent == response - # Verify that response can be converted to an Intent - Intent._from_dict(intent) - -@responses.activate -def test_list_intents(): - endpoint = '/v1/workspaces/{0}/intents'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "intents": [{ - "intent": "pizza_order", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z", - "description": "User wants to start a new pizza order" - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/intents?version=2017-12-18&page_limit=1", - "next_url": - "/v1/workspaces/pizza_app-e0f3/intents?cursor=base64=&version=2017-12-18&page_limit=1" - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - intents = service.list_intents(workspace_id='boguswid', export=False).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert intents == response - # Verify that response can be converted to an IntentCollection - IntentCollection._from_dict(intents) - -@responses.activate -def test_update_intent(): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format('boguswid', - 'pizza_order') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "intent": "pizza_order", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z", - "description": "User wants to start a new pizza order" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - intent = service.update_intent( - workspace_id='boguswid', - intent='pizza_order', - new_intent='pizza_order', - new_description='User wants to start a new pizza order').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert intent == response - # Verify that response can be converted to an Intent - Intent._from_dict(intent) - -def test_intent_models(): - intent = Intent(intent="pizza_order", - created=datetime.datetime(2015, 12, 6, 23, 53, 59, 15300, tzinfo=tzutc()), - updated=datetime.datetime(2015, 12, 7, 18, 53, 59, 15300, tzinfo=tzutc()), - description="User wants to start a new pizza order") - intentDict = intent._to_dict() - check = Intent._from_dict(intentDict) - assert intent == check - - -######################### -# logs -######################### - - -@responses.activate -def test_list_logs(): - endpoint = '/v1/workspaces/{0}/logs'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "logs": [{ - "request": { - "input": { - "text": "Can you turn off the AC" - }, - "context": { - "conversation_id": "f2c7e362-4cc8-4761-8b0f-9ccd70c63bca", - "system": {} - } - }, - "response": { - "input": { - "text": "Can you turn off the AC" - }, - "context": { - "conversation_id": "f2c7e362-4cc8-4761-8b0f-9ccd70c63bca", - "system": { - "dialog_stack": ["root"], - "dialog_turn_counter": 1, - "dialog_request_counter": 1 - }, - "defaultCounter": 0 - }, - "entities": [], - "intents": [{ - "intent": "turn_off", - "confidence": 0.9332477126694649 - }], - "output": { - "log_messages": [], - "text": [ - "Hi. It looks like a nice drive today. What would you like me to do?" - ], - "nodes_visited": ["node_1_1467221909631"] - } - }, - "request_timestamp": "2016-07-16T09:22:38.960Z", - "response_timestamp": "2016-07-16T09:22:39.011Z", - "log_id": "e70d6c12-582d-47a8-a6a2-845120a1f232" - }], - "pagination": { - "next_url": - "/v1/workspaces/15fb0e8a-463d-4fec-86aa-a737d9c38a32/logs?cursor=dOfVSuh6fBpDuOxEL9m1S7JKDV7KLuBmRR+lQG1s1i/rVnBZ0ZBVCuy53ruHgPImC31gQv5prUsJ77e0Mj+6sGu/yfusHYF5&version=2016-07-11&filter=response.top_intent:turn_off&page_limit=1", - "matched": - 215 - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - logs = service.list_logs( - workspace_id='boguswid').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert logs == response - -@responses.activate -def test_list_all_logs(): - endpoint = '/v1/logs' - url = '{0}{1}'.format(base_url, endpoint) - response = { - "logs": [{ - "request": { - "input": { - "text": "Good morning" - }, - "context": { - "metadata": { - "deployment": "deployment_1" - } - } - }, - "response": { - "intents": [{ - "intent": "hello", - "confidence": 1 - }], - "entities": [], - "input": { - "text": "Good morning" - }, - "output": { - "text": ["Hi! What can I do for you?"], - "nodes_visited": ["node_2_1501875253968"], - "log_messages": [] - }, - "context": { - "metadata": { - "deployment": "deployment_1" - }, - "conversation_id": "81a43b48-7dca-4a7d-a0d7-6fed03fcee69", - "system": { - "dialog_stack": [{ - "dialog_node": "root" - }], - "dialog_turn_counter": 1, - "dialog_request_counter": 1, - "_node_output_map": { - "node_2_1501875253968": [0] - }, - "branch_exited": True, - "branch_exited_reason": "completed" - } - } - }, - "language": "en", - "workspace_id": "9978a49e-ea89-4493-b33d-82298d3db20d", - "request_timestamp": "2017-09-13T19:52:32.611Z", - "response_timestamp": "2017-09-13T19:52:32.628Z", - "log_id": "aa886a8a-bac5-4b91-8323-2fd61a69c9d3" - }], - "pagination": {} - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - logs = service.list_all_logs( - 'language::en,request.context.metadata.deployment::deployment_1').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert logs == response - - -######################### -# message -######################### - - -@responses.activate -def test_message(): - - authenticator = BasicAuthenticator('username', 'password') - assistant = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - assistant.set_default_headers({'x-watson-learning-opt-out': "true"}) - - workspace_id = 'f8fdbc65-e0bd-4e43-b9f8-2975a366d4ec' - message_url = '%s/v1/workspaces/%s/message' % (base_url, workspace_id) - url1_str = '%s/v1/workspaces/%s/message?version=2017-02-03' - message_url1 = url1_str % (base_url, workspace_id) - message_response = { - "context": { - "conversation_id": "1b7b67c0-90ed-45dc-8508-9488bc483d5b", - "system": { - "dialog_stack": ["root"], - "dialog_turn_counter": 1, - "dialog_request_counter": 1 - } - }, - "intents": [], - "entities": [], - "input": {}, - "output": { - "text": "okay", - "log_messages": [] - } - } - - responses.add( - responses.POST, - message_url, - body=json.dumps(message_response), - status=200, - content_type='application/json') - - message = assistant.message( - workspace_id=workspace_id, - input={'text': 'Turn on the lights'}, - context=None).get_result() - - assert message is not None - assert responses.calls[0].request.url == message_url1 - assert 'x-watson-learning-opt-out' in responses.calls[0].request.headers - assert responses.calls[0].request.headers['x-watson-learning-opt-out'] == 'true' - assert responses.calls[0].response.text == json.dumps(message_response) - - # test context - responses.add( - responses.POST, - message_url, - body=message_response, - status=200, - content_type='application/json') - - message_ctx = { - 'context': { - 'conversation_id': '1b7b67c0-90ed-45dc-8508-9488bc483d5b', - 'system': { - 'dialog_stack': ['root'], - 'dialog_turn_counter': 2, - 'dialog_request_counter': 1 - } - } - } - message = assistant.message( - workspace_id=workspace_id, - input={'text': 'Turn on the lights'}, - context=json.dumps(message_ctx['context'])).get_result() - - assert message is not None - assert responses.calls[1].request.url == message_url1 - assert responses.calls[1].response.text == json.dumps(message_response) - - assert len(responses.calls) == 2 - -@responses.activate -def test_message_with_models(): - authenticator = BasicAuthenticator('username', 'password') - assistant = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - assistant.set_default_headers({'x-watson-learning-opt-out': "true"}) - - workspace_id = 'f8fdbc65-e0bd-4e43-b9f8-2975a366d4ec' - message_url = '%s/v1/workspaces/%s/message' % (base_url, workspace_id) - url1_str = '%s/v1/workspaces/%s/message?version=2017-02-03' - message_url1 = url1_str % (base_url, workspace_id) - message_response = { - "context": { - "conversation_id": "1b7b67c0-90ed-45dc-8508-9488bc483d5b", - "system": { - "dialog_stack": ["root"], - "dialog_turn_counter": 1, - "dialog_request_counter": 1 - } - }, - "intents": [], - "entities": [], - "input": {}, - "output": { - "text": "okay", - "log_messages": [] - } - } - - responses.add( - responses.POST, - message_url, - body=json.dumps(message_response), - status=200, - content_type='application/json') - - message = assistant.message( - workspace_id=workspace_id, - input=MessageInput(text='Turn on the lights'), - context=None).get_result() - - assert message is not None - assert responses.calls[0].request.url == message_url1 - assert 'x-watson-learning-opt-out' in responses.calls[0].request.headers - assert responses.calls[0].request.headers['x-watson-learning-opt-out'] == 'true' - assert responses.calls[0].response.text == json.dumps(message_response) - - # test context - responses.add( - responses.POST, - message_url, - body=message_response, - status=200, - content_type='application/json') - - message_ctx = Context._from_dict(message_response['context']) - message = assistant.message( - workspace_id=workspace_id, - input=MessageInput(text='Turn on the lights'), - context=message_ctx).get_result() - - assert message is not None - assert responses.calls[1].request.url == message_url1 - assert responses.calls[1].response.text == json.dumps(message_response) - - assert len(responses.calls) == 2 - - -######################### -# synonyms -######################### - - -@responses.activate -def test_create_synonym(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( - 'boguswid', 'aeiou', 'vowel') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "synonym": "aeiou", - "created": "2000-01-23T04:56:07.000+00:00", - "updated": "2000-01-23T04:56:07.000+00:00" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - synonym = service.create_synonym( - workspace_id='boguswid', entity='aeiou', value='vowel', synonym='a').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert synonym == response - # Verify that response can be converted to a Synonym - Synonym._from_dict(synonym) - -@responses.activate -def test_delete_synonym(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - 'boguswid', 'aeiou', 'vowel', 'a') - url = '{0}{1}'.format(base_url, endpoint) - response = None - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - synonym = service.delete_synonym( - workspace_id='boguswid', entity='aeiou', value='vowel', synonym='a').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert synonym is None - - -@responses.activate -def test_get_synonym(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - 'boguswid', 'grilling', 'bbq', 'barbecue') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "synonym": "barbecue", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - synonym = service.get_synonym( - workspace_id='boguswid', entity='grilling', value='bbq', synonym='barbecue').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert synonym == response - # Verify that response can be converted to a Synonym - Synonym._from_dict(synonym) - - -@responses.activate -def test_list_synonyms(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( - 'boguswid', 'grilling', 'bbq') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "synonyms": [{ - "synonym": "BBQ sauce", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - }, { - "synonym": "barbecue", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/entities/sauce/values/types/synonyms?version=2017-12-18&filter=name:b&include_count=true&page_limit=2", - "next_url": - "/v1/workspaces/pizza_app-e0f3/entities/sauce/values/types/synonyms?cursor=base64=&version=2017-12-18&filter=name:b&page_limit=2", - "total": - 8, - "matched": - 2 - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - synonyms = service.list_synonyms( - workspace_id='boguswid', - entity='grilling', - value='bbq').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert synonyms == response - # Verify that response can be converted to a SynonymCollection - SynonymCollection._from_dict(synonyms) - - -@responses.activate -def test_update_synonym(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - 'boguswid', 'grilling', 'bbq', 'barbecue') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "synonym": "barbecue", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - synonym = service.update_synonym( - workspace_id='boguswid', entity='grilling', value='bbq', synonym='barbecue', new_synonym='barbecue').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert synonym == response - # Verify that response can be converted to a Synonym - Synonym._from_dict(synonym) - - -######################### -# values -######################### - - -@responses.activate -def test_create_value(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format('boguswid', 'grilling') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "metadata": "{}", - "created": "2000-01-23T04:56:07.000+00:00", - "value": "aeiou", - "type": "synonyms", - "updated": "2000-01-23T04:56:07.000+00:00" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - value = service.create_value( - workspace_id='boguswid', - entity='grilling', - value='aeiou').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert value == response - # Verify that response can be converted to a Value - Value._from_dict(value) - - -@responses.activate -def test_delete_value(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - 'boguswid', 'grilling', 'bbq') - url = '{0}{1}'.format(base_url, endpoint) - response = "" - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - value = service.delete_value( - workspace_id='boguswid', entity='grilling', value='bbq').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert value == "" - - -@responses.activate -def test_get_value(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - 'boguswid', 'grilling', 'bbq') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "value": "BBQ sauce", - "metadata": { - "code": 1422 - }, - "type": "synonyms", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - value = service.get_value( - workspace_id='boguswid', entity='grilling', value='bbq', export=True).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert value == response - # Verify that response can be converted to a Value - Value._from_dict(value) - - -@responses.activate -def test_list_values(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format('boguswid', 'grilling') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "values": [{ - "value": "BBQ sauce", - "metadata": { - "code": 1422 - }, - "type": "synonyms", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-07T18:53:59.153Z" - }], - "pagination": { - "refresh_url": - "/v1/workspaces/pizza_app-e0f3/entities/sauce/values?version=2017-12-18&filter=name:pizza&include_count=true&page_limit=1", - "next_url": - "/v1/workspaces/pizza_app-e0f3/sauce/values?cursor=base64=&version=2017-12-18&filter=name:pizza&page_limit=1", - "total": - 1, - "matched": - 1 - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - values = service.list_values( - workspace_id='boguswid', - entity='grilling', - export=True).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert values == response - # Verify that response can be converted to a ValueCollection - ValueCollection._from_dict(values) - - -@responses.activate -def test_update_value(): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - 'boguswid', 'grilling', 'bbq') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "value": "BBQ sauce", - "metadata": { - "code": 1422 - }, - "type": "synonyms", - "created": "2015-12-06T23:53:59.153Z", - "updated": "2015-12-06T23:53:59.153Z" - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - value = service.update_value( - workspace_id='boguswid', - entity='grilling', - value='bbq', - new_value='BBQ sauce', - new_metadata={"code": 1422}, - new_synonyms=None).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert value == response - # Verify that response can be converted to a Value - Value._from_dict(value) - - -######################### -# workspaces -######################### - - -@responses.activate -def test_create_workspace(): - endpoint = '/v1/workspaces' - url = '{0}{1}'.format(base_url, endpoint) - response = { - "name": "Pizza app", - "created": "2015-12-06T23:53:59.153Z", - "language": "en", - "metadata": {}, - "updated": "2015-12-06T23:53:59.153Z", - "description": "Pizza app", - "workspace_id": "pizza_app-e0f3", - "learning_opt_out": True - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - workspace = service.create_workspace( - name='Pizza app', description='Pizza app', language='en', metadata={}, - system_settings={'tooling': {'store_generic_responses' : True}}, - webhooks=[Webhook(url='fake-jenkins-url', name='jenkins', headers=[WebhookHeader('fake', 'header')])]).get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert workspace == response - # Verify that response can be converted to a Workspace - Workspace._from_dict(workspace) - -@responses.activate -def test_delete_workspace(): - endpoint = '/v1/workspaces/{0}'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = {} - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - workspace = service.delete_workspace(workspace_id='boguswid').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert workspace is None - - -@responses.activate -def test_get_workspace(): - endpoint = '/v1/workspaces/{0}'.format('boguswid') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "name": "Pizza app", - "created": "2015-12-06T23:53:59.153Z", - "language": "en", - "metadata": {}, - "updated": "2015-12-06T23:53:59.153Z", - "description": "Pizza app", - "status": "Available", - "learning_opt_out": False, - "workspace_id": "pizza_app-e0f3" - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - workspace = service.get_workspace(workspace_id='boguswid', export=True, sort='stable').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert workspace == response - # Verify that response can be converted to a Workspace - Workspace._from_dict(workspace) - - -@responses.activate -def test_list_workspaces(): - endpoint = '/v1/workspaces' - url = '{0}{1}'.format(base_url, endpoint) - response = { - "workspaces": [{ - "name": "Pizza app", - "created": "2015-12-06T23:53:59.153Z", - "language": "en", - "metadata": {}, - "updated": "2015-12-06T23:53:59.153Z", - "description": "Pizza app", - "workspace_id": "pizza_app-e0f3", - "learning_opt_out": True - }], - "pagination": { - "refresh_url": - "/v1/workspaces?version=2016-01-24&page_limit=1", - "next_url": - "/v1/workspaces?cursor=base64=&version=2016-01-24&page_limit=1" - } - } - responses.add( - responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - workspaces = service.list_workspaces().get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert workspaces == response - # Verify that response can be converted to a WorkspaceCollection - WorkspaceCollection._from_dict(workspaces) - - -@responses.activate -def test_update_workspace(): - endpoint = '/v1/workspaces/{0}'.format('pizza_app-e0f3') - url = '{0}{1}'.format(base_url, endpoint) - response = { - "name": "Pizza app", - "created": "2015-12-06T23:53:59.153Z", - "language": "en", - "metadata": {}, - "updated": "2015-12-06T23:53:59.153Z", - "description": "Pizza app", - "workspace_id": "pizza_app-e0f3", - "learning_opt_out": True - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - workspace = service.update_workspace( - workspace_id='pizza_app-e0f3', - name='Pizza app', - description='Pizza app', - language='en', - metadata={}, - system_settings={'tooling': {'store_generic_responses' : True}}, - webhooks=[Webhook(url='fake-jenkins-url', name='jenkins', headers=[WebhookHeader('fake', 'header')])]).get_result() - assert len(responses.calls) == 1 + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) assert responses.calls[0].request.url.startswith(url) - assert workspace == response - # Verify that response can be converted to a Workspace - Workspace._from_dict(workspace) - -@responses.activate -def test_dialog_nodes(): - url = 'https://gateway.watsonplatform.net/assistant/api/v1/workspaces/id/dialog_nodes' - responses.add( - responses.GET, - url, - body='{ "application/json": { "dialog_node": "location-atm" }}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - "{0}/location-done?version=2017-02-03".format(url), - body='{ "application/json": { "dialog_node": "location-done" }}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - "{0}?version=2017-02-03".format(url), - body='{ "application/json": { "dialog_node": "location-done" }}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - "{0}/location-done?version=2017-02-03".format(url), - body='{"description": "deleted successfully"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}/location-done?version=2017-02-03".format(url), - body='{ "application/json": { "dialog_node": "location-atm" }}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - assistant = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - - assistant.create_dialog_node('id', 'location-done', user_label='xxx', disambiguation_opt_out=False) - assert responses.calls[0].response.json()['application/json']['dialog_node'] == 'location-done' - - assistant.update_dialog_node('id', 'location-done', user_label='xxx', new_disambiguation_opt_out=False) - assert responses.calls[1].response.json()['application/json']['dialog_node'] == 'location-done' - - assistant.delete_dialog_node('id', 'location-done') - assert responses.calls[2].response.json() == {"description": "deleted successfully"} - - assistant.get_dialog_node('id', 'location-done') - assert responses.calls[3].response.json() == {"application/json": {"dialog_node": "location-atm"}} - - assistant.list_dialog_nodes('id') - assert responses.calls[4].response.json() == {"application/json": {"dialog_node": "location-atm"}} - - assert len(responses.calls) == 5 - -@responses.activate -def test_delete_user_data(): - url = 'https://gateway.watsonplatform.net/assistant/api/v1/user_data' - responses.add( - responses.DELETE, - url, - body=None, - status=204, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - - response = service.delete_user_data('id').get_result() - assert response is None - assert len(responses.calls) == 1 - -@responses.activate -def test_list_mentions(): - url = 'https://gateway.watsonplatform.net/assistant/api/v1/workspaces/workspace_id/entities/entity1/mentions' - responses.add( - responses.GET, - url, - body='[{"entity": "xxx"}]', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV1( - version='2017-02-03', authenticator=authenticator) - - response = service.list_mentions('workspace_id', 'entity1').get_result() - assert response == [{"entity": "xxx"}] - assert len(responses.calls) == 1 + assert output.get_result() == response + +#################### +## Mock Responses ## +#################### + +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_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": []}""" +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_ExampleCollection_json = """{"examples": [], "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_Example_json = """{"text": "fake_text", "mentions": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Example_json = """{"text": "fake_text", "mentions": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Example_json = """{"text": "fake_text", "mentions": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_CounterexampleCollection_json = """{"counterexamples": [], "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_Counterexample_json = """{"text": "fake_text", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Counterexample_json = """{"text": "fake_text", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Counterexample_json = """{"text": "fake_text", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_EntityCollection_json = """{"entities": [], "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_Entity_json = """{"entity": "fake_entity", "description": "fake_description", "fuzzy_match": false, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "values": []}""" +fake_response_Entity_json = """{"entity": "fake_entity", "description": "fake_description", "fuzzy_match": false, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "values": []}""" +fake_response_Entity_json = """{"entity": "fake_entity", "description": "fake_description", "fuzzy_match": false, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "values": []}""" +fake_response_EntityMentionCollection_json = """{"examples": [], "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_ValueCollection_json = """{"values": [], "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_Value_json = """{"value": "fake_value", "type": "fake_type", "synonyms": [], "patterns": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Value_json = """{"value": "fake_value", "type": "fake_type", "synonyms": [], "patterns": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Value_json = """{"value": "fake_value", "type": "fake_type", "synonyms": [], "patterns": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_SynonymCollection_json = """{"synonyms": [], "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_Synonym_json = """{"synonym": "fake_synonym", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Synonym_json = """{"synonym": "fake_synonym", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Synonym_json = """{"synonym": "fake_synonym", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_DialogNodeCollection_json = """{"dialog_nodes": [], "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_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" +fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" From 4015ec894fb7458047e7fe7b1a9a2f90d8d08031 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 13:34:34 -0500 Subject: [PATCH 172/455] refactor(assisstantv2): regenerate assistantv2 with tests --- ibm_watson/assistant_v2.py | 793 ++++++++++++++++++++++----------- test/unit/test_assistant_v2.py | 409 +++++++++++++---- 2 files changed, 851 insertions(+), 351 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 6489bfab1..60b838104 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,11 +22,15 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator 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 read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from typing import Dict +from typing import List ############################################################################## # Service @@ -36,13 +40,15 @@ class AssistantV2(BaseService): """The Assistant V2 service.""" - default_service_url = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_NAME = 'conversation' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Assistant service. @@ -61,30 +67,20 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('assistant') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('assistant') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Sessions ######################### - def create_session(self, assistant_id, **kwargs): + def create_session(self, assistant_id: str, **kwargs) -> 'DetailedResponse': """ Create a session. @@ -111,7 +107,9 @@ def create_session(self, assistant_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V2', 'create_session') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_session') headers.update(sdk_headers) params = {'version': self.version} @@ -121,12 +119,13 @@ def create_session(self, assistant_id, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_session(self, assistant_id, session_id, **kwargs): + def delete_session(self, assistant_id: str, session_id: str, + **kwargs) -> 'DetailedResponse': """ Delete session. @@ -154,7 +153,9 @@ def delete_session(self, assistant_id, session_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V2', 'delete_session') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_session') headers.update(sdk_headers) params = {'version': self.version} @@ -164,8 +165,8 @@ def delete_session(self, assistant_id, session_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -174,12 +175,12 @@ def delete_session(self, assistant_id, session_id, **kwargs): ######################### def message(self, - assistant_id, - session_id, + assistant_id: str, + session_id: str, *, - input=None, - context=None, - **kwargs): + input: 'MessageInput' = None, + context: 'MessageContext' = None, + **kwargs) -> 'DetailedResponse': """ Send user input to assistant. @@ -216,7 +217,9 @@ def message(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('conversation', 'V2', 'message') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message') headers.update(sdk_headers) params = {'version': self.version} @@ -229,8 +232,8 @@ def message(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -245,23 +248,23 @@ class CaptureGroup(): CaptureGroup. :attr str group: A recognized capture group for the entity. - :attr list[int] location: (optional) Zero-based character offsets that indicate + :attr List[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ - def __init__(self, group, *, location=None): + def __init__(self, group: str, *, location: List[int] = None) -> None: """ Initialize a CaptureGroup object. :param str group: A recognized capture group for the entity. - :param list[int] location: (optional) Zero-based character offsets that + :param List[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ self.group = group self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CaptureGroup': """Initialize a CaptureGroup object from a json dictionary.""" args = {} valid_keys = ['group', 'location'] @@ -279,7 +282,12 @@ def _from_dict(cls, _dict): args['location'] = _dict.get('location') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CaptureGroup 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, 'group') and self.group is not None: @@ -288,17 +296,21 @@ def _to_dict(self): _dict['location'] = self.location return _dict - def __str__(self): + 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 CaptureGroup object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CaptureGroup') -> 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): + def __ne__(self, other: 'CaptureGroup') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -311,7 +323,7 @@ class DialogLogMessage(): :attr str message: The text of the log message. """ - def __init__(self, level, message): + def __init__(self, level: str, message: str) -> None: """ Initialize a DialogLogMessage object. @@ -322,7 +334,7 @@ def __init__(self, level, message): self.message = message @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': """Initialize a DialogLogMessage object from a json dictionary.""" args = {} valid_keys = ['level', 'message'] @@ -345,7 +357,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogLogMessage 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, 'level') and self.level is not None: @@ -354,17 +371,21 @@ def _to_dict(self): _dict['message'] = self.message return _dict - def __str__(self): + 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 DialogLogMessage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogLogMessage') -> 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): + def __ne__(self, other: 'DialogLogMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -392,12 +413,12 @@ class DialogNodeAction(): """ def __init__(self, - name, - result_variable, + name: str, + result_variable: str, *, - type=None, - parameters=None, - credentials=None): + type: str = None, + parameters: dict = None, + credentials: str = None) -> None: """ Initialize a DialogNodeAction object. @@ -417,7 +438,7 @@ def __init__(self, self.credentials = credentials @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': """Initialize a DialogNodeAction object from a json dictionary.""" args = {} valid_keys = [ @@ -448,7 +469,12 @@ def _from_dict(cls, _dict): args['credentials'] = _dict.get('credentials') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeAction 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, 'name') and self.name is not None: @@ -464,17 +490,21 @@ def _to_dict(self): _dict['credentials'] = self.credentials return _dict - def __str__(self): + 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 DialogNodeAction object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeAction') -> 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): + def __ne__(self, other: 'DialogNodeAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -497,7 +527,8 @@ class DialogNodeOutputOptionsElement(): input to be sent to the assistant if the user selects the corresponding option. """ - def __init__(self, label, value): + def __init__(self, label: str, + value: 'DialogNodeOutputOptionsElementValue') -> None: """ Initialize a DialogNodeOutputOptionsElement object. @@ -510,7 +541,7 @@ def __init__(self, label, value): self.value = value @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} valid_keys = ['label', 'value'] @@ -534,7 +565,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputOptionsElement 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, 'label') and self.label is not None: @@ -543,17 +579,21 @@ def _to_dict(self): _dict['value'] = self.value._to_dict() return _dict - def __str__(self): + 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 DialogNodeOutputOptionsElement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> 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): + def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -567,7 +607,7 @@ class DialogNodeOutputOptionsElementValue(): text. """ - def __init__(self, *, input=None): + def __init__(self, *, input: 'MessageInput' = None) -> None: """ Initialize a DialogNodeOutputOptionsElementValue object. @@ -577,7 +617,7 @@ def __init__(self, *, input=None): self.input = input @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} valid_keys = ['input'] @@ -590,24 +630,33 @@ def _from_dict(cls, _dict): args['input'] = MessageInput._from_dict(_dict.get('input')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputOptionsElementValue 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, 'input') and self.input is not None: _dict['input'] = self.input._to_dict() return _dict - def __str__(self): + 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 DialogNodeOutputOptionsElementValue object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> 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): + def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -622,7 +671,11 @@ class DialogNodesVisited(): :attr str conditions: (optional) The conditions that trigger the dialog node. """ - def __init__(self, *, dialog_node=None, title=None, conditions=None): + def __init__(self, + *, + dialog_node: str = None, + title: str = None, + conditions: str = None) -> None: """ Initialize a DialogNodesVisited object. @@ -637,7 +690,7 @@ def __init__(self, *, dialog_node=None, title=None, conditions=None): self.conditions = conditions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogNodesVisited': """Initialize a DialogNodesVisited object from a json dictionary.""" args = {} valid_keys = ['dialog_node', 'title', 'conditions'] @@ -654,7 +707,12 @@ def _from_dict(cls, _dict): args['conditions'] = _dict.get('conditions') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodesVisited 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, 'dialog_node') and self.dialog_node is not None: @@ -665,17 +723,21 @@ def _to_dict(self): _dict['conditions'] = self.conditions return _dict - def __str__(self): + 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 DialogNodesVisited object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogNodesVisited') -> 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): + def __ne__(self, other: 'DialogNodesVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -694,7 +756,11 @@ class DialogSuggestion(): Watson Assistant service if the user selects the corresponding option. """ - def __init__(self, label, value, *, output=None): + def __init__(self, + label: str, + value: 'DialogSuggestionValue', + *, + output: dict = None) -> None: """ Initialize a DialogSuggestion object. @@ -712,7 +778,7 @@ def __init__(self, label, value, *, output=None): self.output = output @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': """Initialize a DialogSuggestion object from a json dictionary.""" args = {} valid_keys = ['label', 'value', 'output'] @@ -737,7 +803,12 @@ def _from_dict(cls, _dict): args['output'] = _dict.get('output') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestion 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, 'label') and self.label is not None: @@ -748,17 +819,21 @@ def _to_dict(self): _dict['output'] = self.output return _dict - def __str__(self): + 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 DialogSuggestion object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestion') -> 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): + def __ne__(self, other: 'DialogSuggestion') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -772,7 +847,7 @@ class DialogSuggestionValue(): text. """ - def __init__(self, *, input=None): + def __init__(self, *, input: 'MessageInput' = None) -> None: """ Initialize a DialogSuggestionValue object. @@ -782,7 +857,7 @@ def __init__(self, *, input=None): self.input = input @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} valid_keys = ['input'] @@ -795,24 +870,33 @@ def _from_dict(cls, _dict): args['input'] = MessageInput._from_dict(_dict.get('input')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogSuggestionValue 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, 'input') and self.input is not None: _dict['input'] = self.input._to_dict() return _dict - def __str__(self): + 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 DialogSuggestionValue object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DialogSuggestionValue') -> 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): + def __ne__(self, other: 'DialogSuggestionValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -830,7 +914,10 @@ class MessageContext(): assistant. """ - def __init__(self, *, global_=None, skills=None): + def __init__(self, + *, + global_: 'MessageContextGlobal' = None, + skills: 'MessageContextSkills' = None) -> None: """ Initialize a MessageContext object. @@ -846,7 +933,7 @@ def __init__(self, *, global_=None, skills=None): self.skills = skills @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContext': """Initialize a MessageContext object from a json dictionary.""" args = {} valid_keys = ['global_', 'global', 'skills'] @@ -863,7 +950,12 @@ def _from_dict(cls, _dict): _dict.get('skills')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContext 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, 'global_') and self.global_ is not None: @@ -872,17 +964,21 @@ def _to_dict(self): _dict['skills'] = self.skills._to_dict() return _dict - def __str__(self): + 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 MessageContext object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageContext') -> 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): + def __ne__(self, other: 'MessageContext') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -895,7 +991,7 @@ class MessageContextGlobal(): that apply to all skills used by the assistant. """ - def __init__(self, *, system=None): + def __init__(self, *, system: 'MessageContextGlobalSystem' = None) -> None: """ Initialize a MessageContextGlobal object. @@ -905,7 +1001,7 @@ def __init__(self, *, system=None): self.system = system @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} valid_keys = ['system'] @@ -919,24 +1015,33 @@ def _from_dict(cls, _dict): _dict.get('system')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextGlobal 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, 'system') and self.system is not None: _dict['system'] = self.system._to_dict() return _dict - def __str__(self): + 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 MessageContextGlobal object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageContextGlobal') -> 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): + def __ne__(self, other: 'MessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -958,7 +1063,11 @@ class MessageContextGlobalSystem(): (for example, triggering the start node of a dialog). """ - def __init__(self, *, timezone=None, user_id=None, turn_count=None): + def __init__(self, + *, + timezone: str = None, + user_id: str = None, + turn_count: int = None) -> None: """ Initialize a MessageContextGlobalSystem object. @@ -981,7 +1090,7 @@ def __init__(self, *, timezone=None, user_id=None, turn_count=None): self.turn_count = turn_count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} valid_keys = ['timezone', 'user_id', 'turn_count'] @@ -998,7 +1107,12 @@ def _from_dict(cls, _dict): args['turn_count'] = _dict.get('turn_count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextGlobalSystem 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, 'timezone') and self.timezone is not None: @@ -1009,17 +1123,21 @@ def _to_dict(self): _dict['turn_count'] = self.turn_count return _dict - def __str__(self): + 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 MessageContextGlobalSystem object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageContextGlobalSystem') -> 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): + def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1030,22 +1148,26 @@ class MessageContextSkill(): :attr dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. + :attr dict system: (optional) For internal use only. """ - def __init__(self, *, user_defined=None): + def __init__(self, *, user_defined: dict = None, + system: dict = None) -> None: """ Initialize a MessageContextSkill object. :param dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. + :param dict system: (optional) For internal use only. """ self.user_defined = user_defined + self.system = system @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': """Initialize a MessageContextSkill object from a json dictionary.""" args = {} - valid_keys = ['user_defined'] + valid_keys = ['user_defined', 'system'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -1053,26 +1175,39 @@ def _from_dict(cls, _dict): + ', '.join(bad_keys)) if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') + if 'system' in _dict: + args['system'] = _dict.get('system') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkill 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, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + _dict['system'] = self.system return _dict - def __str__(self): + 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 MessageContextSkill object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageContextSkill') -> 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): + def __ne__(self, other: 'MessageContextSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1085,7 +1220,7 @@ class MessageContextSkills(): """ - def __init__(self, **kwargs): + def __init__(self, **kwargs) -> None: """ Initialize a MessageContextSkills object. @@ -1095,14 +1230,19 @@ def __init__(self, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': """Initialize a MessageContextSkills object from a json dictionary.""" args = {} xtra = _dict.copy() args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkills 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, '_additionalProperties'): @@ -1112,7 +1252,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {} if not hasattr(self, '_additionalProperties'): super(MessageContextSkills, @@ -1121,17 +1265,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(MessageContextSkills, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this MessageContextSkills object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageContextSkills') -> 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): + def __ne__(self, other: 'MessageContextSkills') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1146,10 +1290,10 @@ class MessageInput(): contain carriage return, newline, or tab characters. :attr MessageInputOptions options: (optional) Optional properties that control how the assistant responds. - :attr list[RuntimeIntent] intents: (optional) Intents to use when evaluating the + :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. - :attr list[RuntimeEntity] entities: (optional) Entities to use when evaluating + :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. :attr str suggestion_id: (optional) For internal use only. @@ -1157,12 +1301,12 @@ class MessageInput(): def __init__(self, *, - message_type=None, - text=None, - options=None, - intents=None, - entities=None, - suggestion_id=None): + message_type: str = None, + text: str = None, + options: 'MessageInputOptions' = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + suggestion_id: str = None) -> None: """ Initialize a MessageInput object. @@ -1172,11 +1316,11 @@ def __init__(self, contain carriage return, newline, or tab characters. :param MessageInputOptions options: (optional) Optional properties that control how the assistant responds. - :param list[RuntimeIntent] intents: (optional) Intents to use when + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. - :param list[RuntimeEntity] entities: (optional) Entities to use when + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. @@ -1190,7 +1334,7 @@ def __init__(self, self.suggestion_id = suggestion_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} valid_keys = [ @@ -1221,7 +1365,12 @@ def _from_dict(cls, _dict): args['suggestion_id'] = _dict.get('suggestion_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInput 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, 'message_type') and self.message_type is not None: @@ -1238,17 +1387,21 @@ def _to_dict(self): _dict['suggestion_id'] = self.suggestion_id return _dict - def __str__(self): + 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 MessageInput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageInput') -> 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): + def __ne__(self, other: 'MessageInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1278,10 +1431,10 @@ class MessageInputOptions(): def __init__(self, *, - debug=None, - restart=None, - alternate_intents=None, - return_context=None): + debug: bool = None, + restart: bool = None, + alternate_intents: bool = None, + return_context: bool = None) -> None: """ Initialize a MessageInputOptions object. @@ -1303,7 +1456,7 @@ def __init__(self, self.return_context = return_context @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': """Initialize a MessageInputOptions object from a json dictionary.""" args = {} valid_keys = ['debug', 'restart', 'alternate_intents', 'return_context'] @@ -1322,7 +1475,12 @@ def _from_dict(cls, _dict): args['return_context'] = _dict.get('return_context') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputOptions 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, 'debug') and self.debug is not None: @@ -1336,17 +1494,21 @@ def _to_dict(self): _dict['return_context'] = self.return_context return _dict - def __str__(self): + 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 MessageInputOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageInputOptions') -> 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): + def __ne__(self, other: 'MessageInputOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1355,14 +1517,14 @@ class MessageOutput(): """ Assistant output to be rendered or processed by the client. - :attr list[RuntimeResponseGeneric] generic: (optional) Output intended for any + :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. - :attr list[RuntimeIntent] intents: (optional) An array of intents recognized in + :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in the user input, sorted in descending order of confidence. - :attr list[RuntimeEntity] entities: (optional) An array of entities identified + :attr List[RuntimeEntity] entities: (optional) An array of entities identified in the user input. - :attr list[DialogNodeAction] actions: (optional) An array of objects describing + :attr List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. :attr MessageOutputDebug debug: (optional) Additional detailed information about a message response and how it was generated. @@ -1373,23 +1535,23 @@ class MessageOutput(): def __init__(self, *, - generic=None, - intents=None, - entities=None, - actions=None, - debug=None, - user_defined=None): + generic: List['RuntimeResponseGeneric'] = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + actions: List['DialogNodeAction'] = None, + debug: 'MessageOutputDebug' = None, + user_defined: dict = None) -> None: """ Initialize a MessageOutput object. - :param list[RuntimeResponseGeneric] generic: (optional) Output intended for + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. - :param list[RuntimeIntent] intents: (optional) An array of intents + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in the user input, sorted in descending order of confidence. - :param list[RuntimeEntity] entities: (optional) An array of entities + :param List[RuntimeEntity] entities: (optional) An array of entities identified in the user input. - :param list[DialogNodeAction] actions: (optional) An array of objects + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. :param MessageOutputDebug debug: (optional) Additional detailed information about a message response and how it was generated. @@ -1406,7 +1568,7 @@ def __init__(self, self.user_defined = user_defined @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageOutput': """Initialize a MessageOutput object from a json dictionary.""" args = {} valid_keys = [ @@ -1440,7 +1602,12 @@ def _from_dict(cls, _dict): args['user_defined'] = _dict.get('user_defined') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutput 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, 'generic') and self.generic is not None: @@ -1457,17 +1624,21 @@ def _to_dict(self): _dict['user_defined'] = self.user_defined return _dict - def __str__(self): + 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 MessageOutput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageOutput') -> 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): + def __ne__(self, other: 'MessageOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1476,10 +1647,10 @@ class MessageOutputDebug(): """ Additional detailed information about a message response and how it was generated. - :attr list[DialogNodesVisited] nodes_visited: (optional) An array of objects + :attr List[DialogNodesVisited] nodes_visited: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. - :attr list[DialogLogMessage] log_messages: (optional) An array of up to 50 + :attr List[DialogLogMessage] log_messages: (optional) An array of up to 50 messages logged with the request. :attr bool branch_exited: (optional) Assistant sets this to true when this message response concludes or interrupts a dialog. @@ -1490,17 +1661,17 @@ class MessageOutputDebug(): def __init__(self, *, - nodes_visited=None, - log_messages=None, - branch_exited=None, - branch_exited_reason=None): + nodes_visited: List['DialogNodesVisited'] = None, + log_messages: List['DialogLogMessage'] = None, + branch_exited: bool = None, + branch_exited_reason: str = None) -> None: """ Initialize a MessageOutputDebug object. - :param list[DialogNodesVisited] nodes_visited: (optional) An array of + :param List[DialogNodesVisited] nodes_visited: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. - :param list[DialogLogMessage] log_messages: (optional) An array of up to 50 + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 messages logged with the request. :param bool branch_exited: (optional) Assistant sets this to true when this message response concludes or interrupts a dialog. @@ -1514,7 +1685,7 @@ def __init__(self, self.branch_exited_reason = branch_exited_reason @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': """Initialize a MessageOutputDebug object from a json dictionary.""" args = {} valid_keys = [ @@ -1542,7 +1713,12 @@ def _from_dict(cls, _dict): args['branch_exited_reason'] = _dict.get('branch_exited_reason') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutputDebug 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, 'nodes_visited') and self.nodes_visited is not None: @@ -1556,17 +1732,21 @@ def _to_dict(self): _dict['branch_exited_reason'] = self.branch_exited_reason return _dict - def __str__(self): + 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 MessageOutputDebug object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageOutputDebug') -> 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): + def __ne__(self, other: 'MessageOutputDebug') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1592,7 +1772,10 @@ class MessageResponse(): **return_context**=`true` in the message request. """ - def __init__(self, output, *, context=None): + def __init__(self, + output: 'MessageOutput', + *, + context: 'MessageContext' = None) -> None: """ Initialize a MessageResponse object. @@ -1608,7 +1791,7 @@ def __init__(self, output, *, context=None): self.context = context @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MessageResponse': """Initialize a MessageResponse object from a json dictionary.""" args = {} valid_keys = ['output', 'context'] @@ -1627,7 +1810,12 @@ def _from_dict(cls, _dict): args['context'] = MessageContext._from_dict(_dict.get('context')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageResponse 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, 'output') and self.output is not None: @@ -1636,17 +1824,21 @@ def _to_dict(self): _dict['context'] = self.context._to_dict() return _dict - def __str__(self): + 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 MessageResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MessageResponse') -> 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): + def __ne__(self, other: 'MessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1656,37 +1848,37 @@ class RuntimeEntity(): The entity value that was recognized in the user input. :attr str entity: An entity detected in the input. - :attr list[int] location: An array of zero-based character offsets that indicate + :attr List[int] location: An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. :attr str value: The term in the input text that was recognized as an entity value. :attr float confidence: (optional) A decimal percentage that represents Watson's confidence in the recognized entity. :attr dict metadata: (optional) Any metadata for the entity. - :attr list[CaptureGroup] groups: (optional) The recognized capture groups for + :attr List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. """ def __init__(self, - entity, - location, - value, + entity: str, + location: List[int], + value: str, *, - confidence=None, - metadata=None, - groups=None): + confidence: float = None, + metadata: dict = None, + groups: List['CaptureGroup'] = None) -> None: """ Initialize a RuntimeEntity object. :param str entity: An entity detected in the input. - :param list[int] location: An array of zero-based character offsets that + :param List[int] location: An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. :param str value: The term in the input text that was recognized as an entity value. :param float confidence: (optional) A decimal percentage that represents Watson's confidence in the recognized entity. :param dict metadata: (optional) Any metadata for the entity. - :param list[CaptureGroup] groups: (optional) The recognized capture groups + :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. """ self.entity = entity @@ -1697,7 +1889,7 @@ def __init__(self, self.groups = groups @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} valid_keys = [ @@ -1735,7 +1927,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntity 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, 'entity') and self.entity is not None: @@ -1752,17 +1949,21 @@ def _to_dict(self): _dict['groups'] = [x._to_dict() for x in self.groups] return _dict - def __str__(self): + 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 RuntimeEntity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeEntity') -> 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): + def __ne__(self, other: 'RuntimeEntity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1776,7 +1977,7 @@ class RuntimeIntent(): in the intent. """ - def __init__(self, intent, confidence): + def __init__(self, intent: str, confidence: float) -> None: """ Initialize a RuntimeIntent object. @@ -1788,7 +1989,7 @@ def __init__(self, intent, confidence): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': """Initialize a RuntimeIntent object from a json dictionary.""" args = {} valid_keys = ['intent', 'confidence'] @@ -1811,7 +2012,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeIntent 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, 'intent') and self.intent is not None: @@ -1820,17 +2026,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 RuntimeIntent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeIntent') -> 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): + def __ne__(self, other: 'RuntimeIntent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1852,38 +2062,38 @@ class RuntimeResponseGeneric(): response. :attr str description: (optional) The description to show with the the response. :attr str preference: (optional) The preferred type of control to display. - :attr list[DialogNodeOutputOptionsElement] options: (optional) An array of + :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :attr str topic: (optional) A label identifying the topic of the conversation, derived from the **user_label** property of the relevant node. - :attr list[DialogSuggestion] suggestions: (optional) An array of objects + :attr List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Premium users. :attr str header: (optional) The title or introductory text to show before the response. This text is defined in the search skill configuration. - :attr list[SearchResult] results: (optional) An array of objects containing + :attr List[SearchResult] results: (optional) An array of objects containing search results. """ def __init__(self, - response_type, + response_type: str, *, - text=None, - time=None, - typing=None, - source=None, - title=None, - description=None, - preference=None, - options=None, - message_to_human_agent=None, - topic=None, - suggestions=None, - header=None, - results=None): + text: str = None, + time: int = None, + typing: bool = None, + source: str = None, + title: str = None, + description: str = None, + preference: str = None, + options: List['DialogNodeOutputOptionsElement'] = None, + message_to_human_agent: str = None, + topic: str = None, + suggestions: List['DialogSuggestion'] = None, + header: str = None, + results: List['SearchResult'] = None) -> None: """ Initialize a RuntimeResponseGeneric object. @@ -1902,21 +2112,21 @@ def __init__(self, :param str description: (optional) The description to show with the the response. :param str preference: (optional) The preferred type of control to display. - :param list[DialogNodeOutputOptionsElement] options: (optional) An array of + :param List[DialogNodeOutputOptionsElement] options: (optional) An array of objects describing the options from which the user can choose. :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :param str topic: (optional) A label identifying the topic of the conversation, derived from the **user_label** property of the relevant node. - :param list[DialogSuggestion] suggestions: (optional) An array of objects + :param List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, which is only available for Premium users. :param str header: (optional) The title or introductory text to show before the response. This text is defined in the search skill configuration. - :param list[SearchResult] results: (optional) An array of objects + :param List[SearchResult] results: (optional) An array of objects containing search results. """ self.response_type = response_type @@ -1935,7 +2145,7 @@ def __init__(self, self.results = results @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': """Initialize a RuntimeResponseGeneric object from a json dictionary.""" args = {} valid_keys = [ @@ -1990,7 +2200,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGeneric 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, 'response_type') and self.response_type is not None: @@ -2024,17 +2239,21 @@ def _to_dict(self): _dict['results'] = [x._to_dict() for x in self.results] return _dict - def __str__(self): + 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 RuntimeResponseGeneric object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RuntimeResponseGeneric') -> 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): + def __ne__(self, other: 'RuntimeResponseGeneric') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2085,13 +2304,13 @@ class SearchResult(): """ def __init__(self, - id, - result_metadata, + id: str, + result_metadata: 'SearchResultMetadata', *, - body=None, - title=None, - url=None, - highlight=None): + body: str = None, + title: str = None, + url: str = None, + highlight: 'SearchResultHighlight' = None) -> None: """ Initialize a SearchResult object. @@ -2121,7 +2340,7 @@ def __init__(self, self.highlight = highlight @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SearchResult': """Initialize a SearchResult object from a json dictionary.""" args = {} valid_keys = [ @@ -2155,7 +2374,12 @@ def _from_dict(cls, _dict): _dict.get('highlight')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResult 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, 'id') and self.id is not None: @@ -2173,17 +2397,21 @@ def _to_dict(self): _dict['highlight'] = self.highlight._to_dict() return _dict - def __str__(self): + 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 SearchResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SearchResult') -> 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): + def __ne__(self, other: 'SearchResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2193,27 +2421,32 @@ class SearchResultHighlight(): An object containing segments of text from search results with query-matching text highlighted using HTML tags. - :attr list[str] body: (optional) An array of strings containing segments taken + :attr List[str] body: (optional) An array of strings containing segments taken from body text in the search results, with query-matching substrings highlighted. - :attr list[str] title: (optional) An array of strings containing segments taken + :attr List[str] title: (optional) An array of strings containing segments taken from title text in the search results, with query-matching substrings highlighted. - :attr list[str] url: (optional) An array of strings containing segments taken + :attr List[str] url: (optional) An array of strings containing segments taken from URLs in the search results, with query-matching substrings highlighted. """ - def __init__(self, *, body=None, title=None, url=None, **kwargs): + def __init__(self, + *, + body: List[str] = None, + title: List[str] = None, + url: List[str] = None, + **kwargs) -> None: """ Initialize a SearchResultHighlight object. - :param list[str] body: (optional) An array of strings containing segments + :param List[str] body: (optional) An array of strings containing segments taken from body text in the search results, with query-matching substrings highlighted. - :param list[str] title: (optional) An array of strings containing segments + :param List[str] title: (optional) An array of strings containing segments taken from title text in the search results, with query-matching substrings highlighted. - :param list[str] url: (optional) An array of strings containing segments + :param List[str] url: (optional) An array of strings containing segments taken from URLs in the search results, with query-matching substrings highlighted. :param **kwargs: (optional) Any additional properties. @@ -2225,7 +2458,7 @@ def __init__(self, *, body=None, title=None, url=None, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': """Initialize a SearchResultHighlight object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -2241,7 +2474,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultHighlight 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, 'body') and self.body is not None: @@ -2257,7 +2495,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {'body', 'title', 'url'} if not hasattr(self, '_additionalProperties'): super(SearchResultHighlight, @@ -2266,17 +2508,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(SearchResultHighlight, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this SearchResultHighlight object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SearchResultHighlight') -> 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): + def __ne__(self, other: 'SearchResultHighlight') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2293,7 +2535,8 @@ class SearchResultMetadata(): indicates a greater match to the query parameters. """ - def __init__(self, *, confidence=None, score=None): + def __init__(self, *, confidence: float = None, + score: float = None) -> None: """ Initialize a SearchResultMetadata object. @@ -2308,7 +2551,7 @@ def __init__(self, *, confidence=None, score=None): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': """Initialize a SearchResultMetadata object from a json dictionary.""" args = {} valid_keys = ['confidence', 'score'] @@ -2323,7 +2566,12 @@ def _from_dict(cls, _dict): args['score'] = _dict.get('score') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultMetadata 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, 'confidence') and self.confidence is not None: @@ -2332,17 +2580,21 @@ def _to_dict(self): _dict['score'] = self.score return _dict - def __str__(self): + 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 SearchResultMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SearchResultMetadata') -> 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): + def __ne__(self, other: 'SearchResultMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2354,7 +2606,7 @@ class SessionResponse(): :attr str session_id: The session ID. """ - def __init__(self, session_id): + def __init__(self, session_id: str) -> None: """ Initialize a SessionResponse object. @@ -2363,7 +2615,7 @@ def __init__(self, session_id): self.session_id = session_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SessionResponse': """Initialize a SessionResponse object from a json dictionary.""" args = {} valid_keys = ['session_id'] @@ -2380,23 +2632,32 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SessionResponse 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, 'session_id') and self.session_id is not None: _dict['session_id'] = self.session_id return _dict - def __str__(self): + 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 SessionResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SessionResponse') -> 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): + def __ne__(self, other: 'SessionResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index d2b3ad534..a43dd8c1b 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,88 +1,327 @@ -# coding: utf-8 +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json +import pytest import responses -import ibm_watson -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -platform_url = 'https://gateway.watsonplatform.net' -service_path = '/assistant/api' -base_url = '{0}{1}'.format(platform_url, service_path) - -@responses.activate -def test_create_session(): - endpoint = '/v2/assistants/{0}/sessions'.format('bogus_id') - url = '{0}{1}'.format(base_url, endpoint) - response = {'session_id': 'session_id'} - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV2( - version='2017-02-03', authenticator=authenticator) - session = service.create_session('bogus_id').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert session == response - - -@responses.activate -def test_delete_session(): - endpoint = '/v2/assistants/{0}/sessions/{1}'.format('bogus_id', - 'session_id') - url = '{0}{1}'.format(base_url, endpoint) - response = {} - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV2( - version='2017-02-03', authenticator=authenticator) - delete_session = service.delete_session('bogus_id', - 'session_id').get_result() - assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert delete_session == response - - -@responses.activate -def test_message(): - endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format( - 'bogus_id', 'session_id') - url = '{0}{1}'.format(base_url, endpoint) - response = { - 'output': { - 'generic': [{ - 'text': - 'I did not understand that. I can help you get pizza, tell a joke or find a movie.', - 'response_type': - 'text' - }], - 'entities': [], - 'intents': [{ - 'confidence': 0.8521236419677736, - 'intent': 'Weather' - }] - } - } - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - service = ibm_watson.AssistantV2( - version='2017-02-03', authenticator=authenticator) - message = service.message( - 'bogus_id', 'session_id', input={ - 'text': 'What\'s the weather like?' - }).get_result() - assert len(responses.calls) == 1 +import ibm_watson.assistant_v2 +from ibm_watson.assistant_v2 import * + +base_url = 'https://gateway.watsonplatform.net/assistant/api' + +############################################################################## +# Start of Service: Sessions +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for create_session +#----------------------------------------------------------------------------- +class TestCreateSession(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_session_response(self): + body = self.construct_full_body() + response = fake_response_SessionResponse_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_create_session_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_SessionResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_session_empty(self): + check_empty_required_params(self, fake_response_SessionResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/assistants/{0}/sessions'.format(body['assistant_id']) + 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=201, + content_type='application/json') + + def call_service(self, body): + service = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.create_session(**body) + return output + + def construct_full_body(self): + body = dict() + body['assistant_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['assistant_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_session +#----------------------------------------------------------------------------- +class TestDeleteSession(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_session_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_session_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_session_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 = '/v2/assistants/{0}/sessions/{1}'.format(body['assistant_id'], body['session_id']) + 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 = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.delete_session(**body) + return output + + def construct_full_body(self): + body = dict() + body['assistant_id'] = "string1" + body['session_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['assistant_id'] = "string1" + body['session_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Sessions +############################################################################## + +############################################################################## +# Start of Service: Message +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for message +#----------------------------------------------------------------------------- +class TestMessage(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_response(self): + body = self.construct_full_body() + response = fake_response_MessageResponse_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_message_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MessageResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_empty(self): + check_empty_required_params(self, fake_response_MessageResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format(body['assistant_id'], body['session_id']) + 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 = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2019-02-28', + ) + service.set_service_url(base_url) + output = service.message(**body) + return output + + def construct_full_body(self): + body = dict() + body['assistant_id'] = "string1" + body['session_id'] = "string1" + body.update({"input": MessageInput._from_dict(json.loads("""{"message_type": "fake_message_type", "text": "fake_text", "options": {"debug": false, "restart": false, "alternate_intents": false, "return_context": true}, "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id"}""")), "context": MessageContext._from_dict(json.loads("""{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10}}, "skills": {}}""")), }) + return body + + def construct_required_body(self): + body = dict() + body['assistant_id'] = "string1" + body['session_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Message +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) assert responses.calls[0].request.url.startswith(url) - assert message == response + assert output.get_result() == response + +#################### +## Mock Responses ## +#################### + +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": {}}}""" From 54ccee6d64b2fadaff201873e464dcdfc256089c Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 13:52:47 -0500 Subject: [PATCH 173/455] refactor(cnc): regenerate compare and comply with tests --- ibm_watson/compare_comply_v1.py | 2172 +++++++++++++++++---------- test/unit/test_compare_comply_v1.py | 1606 +++++++++++++------- 2 files changed, 2433 insertions(+), 1345 deletions(-) diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 9b45d0840..9266c3ffa 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,12 +19,21 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import date +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService 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 import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +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 +from typing import List +from typing import TextIO ############################################################################## # Service @@ -34,13 +43,15 @@ class CompareComplyV1(BaseService): """The Compare Comply V1 service.""" - default_service_url = 'https://gateway.watsonplatform.net/compare-comply/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/compare-comply/api' + DEFAULT_SERVICE_NAME = 'compare-comply' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Compare Comply service. @@ -59,41 +70,31 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('compare_comply') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('compare_comply') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # HTML conversion ######################### def convert_to_html(self, - file, + file: BinaryIO, *, - file_content_type=None, - model=None, - **kwargs): + file_content_type: str = None, + model: str = None, + **kwargs) -> 'DetailedResponse': """ Convert document to HTML. Converts a document to HTML. - :param file file: The document to convert. + :param TextIO file: The document to convert. :param str file_content_type: (optional) The content type of file. :param str model: (optional) The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, @@ -111,7 +112,9 @@ def convert_to_html(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'convert_to_html') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='convert_to_html') headers.update(sdk_headers) params = {'version': self.version, 'model': model} @@ -125,8 +128,8 @@ def convert_to_html(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -135,17 +138,17 @@ def convert_to_html(self, ######################### def classify_elements(self, - file, + file: BinaryIO, *, - file_content_type=None, - model=None, - **kwargs): + file_content_type: str = None, + model: str = None, + **kwargs) -> 'DetailedResponse': """ Classify the elements of a document. Analyzes the structural and semantic elements of a document. - :param file file: The document to classify. + :param TextIO file: The document to classify. :param str file_content_type: (optional) The content type of file. :param str model: (optional) The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, @@ -163,8 +166,9 @@ def classify_elements(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', - 'classify_elements') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='classify_elements') headers.update(sdk_headers) params = {'version': self.version, 'model': model} @@ -178,8 +182,8 @@ def classify_elements(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -188,17 +192,17 @@ def classify_elements(self, ######################### def extract_tables(self, - file, + file: BinaryIO, *, - file_content_type=None, - model=None, - **kwargs): + file_content_type: str = None, + model: str = None, + **kwargs) -> 'DetailedResponse': """ Extract a document's tables. Analyzes the tables in a document. - :param file file: The document on which to run table extraction. + :param TextIO file: The document on which to run table extraction. :param str file_content_type: (optional) The content type of file. :param str model: (optional) The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, @@ -216,7 +220,9 @@ def extract_tables(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'extract_tables') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='extract_tables') headers.update(sdk_headers) params = {'version': self.version, 'model': model} @@ -230,8 +236,8 @@ def extract_tables(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -240,22 +246,22 @@ def extract_tables(self, ######################### def compare_documents(self, - file_1, - file_2, + file_1: BinaryIO, + file_2: BinaryIO, *, - file_1_content_type=None, - file_2_content_type=None, - file_1_label=None, - file_2_label=None, - model=None, - **kwargs): + file_1_content_type: str = None, + file_2_content_type: str = None, + file_1_label: str = None, + file_2_label: str = None, + model: str = None, + **kwargs) -> 'DetailedResponse': """ Compare two documents. Compares two input documents. Documents must be in the same format. - :param file file_1: The first document to compare. - :param file file_2: The second document to compare. + :param TextIO file_1: The first document to compare. + :param TextIO file_2: The second document to compare. :param str file_1_content_type: (optional) The content type of file_1. :param str file_2_content_type: (optional) The content type of file_2. :param str file_1_label: (optional) A text label for the first document. @@ -278,8 +284,9 @@ def compare_documents(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', - 'compare_documents') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='compare_documents') headers.update(sdk_headers) params = { @@ -300,8 +307,8 @@ def compare_documents(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -310,11 +317,11 @@ def compare_documents(self, ######################### def add_feedback(self, - feedback_data, + feedback_data: 'FeedbackDataInput', *, - user_id=None, - comment=None, - **kwargs): + user_id: str = None, + comment: str = None, + **kwargs) -> 'DetailedResponse': """ Add feedback. @@ -340,7 +347,9 @@ def add_feedback(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'add_feedback') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_feedback') headers.update(sdk_headers) params = {'version': self.version} @@ -356,30 +365,30 @@ def add_feedback(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def list_feedback(self, *, - feedback_type=None, - before=None, - after=None, - document_title=None, - model_id=None, - model_version=None, - category_removed=None, - category_added=None, - category_not_changed=None, - type_removed=None, - type_added=None, - type_not_changed=None, - page_limit=None, - cursor=None, - sort=None, - include_total=None, - **kwargs): + feedback_type: str = None, + before: date = None, + after: date = None, + document_title: str = None, + model_id: str = None, + model_version: str = None, + category_removed: str = None, + category_added: str = None, + category_not_changed: str = None, + type_removed: str = None, + type_added: str = None, + type_not_changed: str = None, + page_limit: int = None, + cursor: str = None, + sort: str = None, + include_total: bool = None, + **kwargs) -> 'DetailedResponse': """ List the feedback in a document. @@ -447,7 +456,9 @@ def list_feedback(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'list_feedback') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_feedback') headers.update(sdk_headers) params = { @@ -474,12 +485,13 @@ def list_feedback(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_feedback(self, feedback_id, *, model=None, **kwargs): + def get_feedback(self, feedback_id: str, *, model: str = None, + **kwargs) -> 'DetailedResponse': """ Get a specified feedback entry. @@ -503,7 +515,9 @@ def get_feedback(self, feedback_id, *, model=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'get_feedback') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_feedback') headers.update(sdk_headers) params = {'version': self.version, 'model': model} @@ -512,12 +526,13 @@ def get_feedback(self, feedback_id, *, model=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_feedback(self, feedback_id, *, model=None, **kwargs): + def delete_feedback(self, feedback_id: str, *, model: str = None, + **kwargs) -> 'DetailedResponse': """ Delete a specified feedback entry. @@ -541,7 +556,9 @@ def delete_feedback(self, feedback_id, *, model=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'delete_feedback') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_feedback') headers.update(sdk_headers) params = {'version': self.version, 'model': model} @@ -550,8 +567,8 @@ def delete_feedback(self, feedback_id, *, model=None, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -560,16 +577,16 @@ def delete_feedback(self, feedback_id, *, model=None, **kwargs): ######################### def create_batch(self, - function, - input_credentials_file, - input_bucket_location, - input_bucket_name, - output_credentials_file, - output_bucket_location, - output_bucket_name, + function: str, + input_credentials_file: BinaryIO, + input_bucket_location: str, + input_bucket_name: str, + output_credentials_file: BinaryIO, + output_bucket_location: str, + output_bucket_name: str, *, - model=None, - **kwargs): + model: str = None, + **kwargs) -> 'DetailedResponse': """ Submit a batch-processing request. @@ -582,8 +599,8 @@ def create_batch(self, :param str function: The Compare and Comply method to run across the submitted input documents. - :param file input_credentials_file: A JSON file containing the input Cloud - Object Storage credentials. At a minimum, the credentials must enable + :param TextIO input_credentials_file: A JSON file containing the input + Cloud Object Storage credentials. At a minimum, the credentials must enable `READ` permissions on the bucket defined by the `input_bucket_name` parameter. :param str input_bucket_location: The geographical location of the Cloud @@ -591,7 +608,7 @@ def create_batch(self, Object Storage instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. :param str input_bucket_name: The name of the Cloud Object Storage input bucket. - :param file output_credentials_file: A JSON file that lists the Cloud + :param TextIO output_credentials_file: A JSON file that lists the Cloud Object Storage output credentials. At a minimum, the credentials must enable `READ` and `WRITE` permissions on the bucket defined by the `output_bucket_name` parameter. @@ -629,7 +646,9 @@ def create_batch(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'create_batch') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_batch') headers.update(sdk_headers) params = {'version': self.version, 'function': function, 'model': model} @@ -637,14 +656,18 @@ def create_batch(self, form_data = [] form_data.append(('input_credentials_file', (None, input_credentials_file, 'application/json'))) + input_bucket_location = str(input_bucket_location) form_data.append(('input_bucket_location', (None, input_bucket_location, 'text/plain'))) + input_bucket_name = str(input_bucket_name) form_data.append( ('input_bucket_name', (None, input_bucket_name, 'text/plain'))) form_data.append(('output_credentials_file', (None, output_credentials_file, 'application/json'))) + output_bucket_location = str(output_bucket_location) form_data.append(('output_bucket_location', (None, output_bucket_location, 'text/plain'))) + output_bucket_name = str(output_bucket_name) form_data.append( ('output_bucket_name', (None, output_bucket_name, 'text/plain'))) @@ -653,12 +676,12 @@ def create_batch(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def list_batches(self, **kwargs): + def list_batches(self, **kwargs) -> 'DetailedResponse': """ List submitted batch-processing jobs. @@ -672,7 +695,9 @@ def list_batches(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'list_batches') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_batches') headers.update(sdk_headers) params = {'version': self.version} @@ -681,12 +706,12 @@ def list_batches(self, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_batch(self, batch_id, **kwargs): + def get_batch(self, batch_id: str, **kwargs) -> 'DetailedResponse': """ Get information about a specific batch-processing job. @@ -705,7 +730,9 @@ def get_batch(self, batch_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'get_batch') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_batch') headers.update(sdk_headers) params = {'version': self.version} @@ -714,12 +741,17 @@ def get_batch(self, batch_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def update_batch(self, batch_id, action, *, model=None, **kwargs): + def update_batch(self, + batch_id: str, + action: str, + *, + model: str = None, + **kwargs) -> 'DetailedResponse': """ Update a pending or active batch-processing job. @@ -747,7 +779,9 @@ def update_batch(self, batch_id, action, *, model=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('compare-comply', 'V1', 'update_batch') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_batch') headers.update(sdk_headers) params = {'version': self.version, 'action': action, 'model': model} @@ -756,8 +790,8 @@ def update_batch(self, batch_id, action, *, model=None, **kwargs): request = self.prepare_request(method='PUT', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -965,7 +999,8 @@ class Address(): `end`. """ - def __init__(self, *, text=None, location=None): + def __init__(self, *, text: str = None, + location: 'Location' = None) -> None: """ Initialize a Address object. @@ -978,7 +1013,7 @@ def __init__(self, *, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Address': """Initialize a Address object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -993,7 +1028,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Address 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, 'text') and self.text is not None: @@ -1002,17 +1042,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 Address object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Address') -> 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): + def __ne__(self, other: 'Address') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1021,13 +1065,13 @@ class AlignedElement(): """ AlignedElement. - :attr list[ElementPair] element_pair: (optional) Identifies two elements that + :attr List[ElementPair] element_pair: (optional) Identifies two elements that semantically align between the compared documents. :attr bool identical_text: (optional) Specifies whether the aligned element is identical. Elements are considered identical despite minor differences such as leading punctuation, end-of-sentence punctuation, whitespace, the presence or absence of definite or indefinite articles, and others. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr bool significant_elements: (optional) Indicates that the elements aligned are contractual clauses of significance. @@ -1035,21 +1079,21 @@ class AlignedElement(): def __init__(self, *, - element_pair=None, - identical_text=None, - provenance_ids=None, - significant_elements=None): + element_pair: List['ElementPair'] = None, + identical_text: bool = None, + provenance_ids: List[str] = None, + significant_elements: bool = None) -> None: """ Initialize a AlignedElement object. - :param list[ElementPair] element_pair: (optional) Identifies two elements + :param List[ElementPair] element_pair: (optional) Identifies two elements that semantically align between the compared documents. :param bool identical_text: (optional) Specifies whether the aligned element is identical. Elements are considered identical despite minor differences such as leading punctuation, end-of-sentence punctuation, whitespace, the presence or absence of definite or indefinite articles, and others. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param bool significant_elements: (optional) Indicates that the elements aligned are contractual clauses of significance. @@ -1060,7 +1104,7 @@ def __init__(self, self.significant_elements = significant_elements @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AlignedElement': """Initialize a AlignedElement object from a json dictionary.""" args = {} valid_keys = [ @@ -1084,7 +1128,12 @@ def _from_dict(cls, _dict): args['significant_elements'] = _dict.get('significant_elements') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AlignedElement 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, 'element_pair') and self.element_pair is not None: @@ -1098,17 +1147,21 @@ def _to_dict(self): _dict['significant_elements'] = self.significant_elements return _dict - def __str__(self): + 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 AlignedElement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AlignedElement') -> 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): + def __ne__(self, other: 'AlignedElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1124,7 +1177,11 @@ class Attribute(): `end`. """ - def __init__(self, *, type=None, text=None, location=None): + def __init__(self, + *, + type: str = None, + text: str = None, + location: 'Location' = None) -> None: """ Initialize a Attribute object. @@ -1139,7 +1196,7 @@ def __init__(self, *, type=None, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Attribute': """Initialize a Attribute object from a json dictionary.""" args = {} valid_keys = ['type', 'text', 'location'] @@ -1156,7 +1213,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Attribute 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: @@ -1167,17 +1229,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 Attribute object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Attribute') -> 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): + def __ne__(self, other: 'Attribute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1222,16 +1288,16 @@ class BatchStatus(): def __init__(self, *, - function=None, - input_bucket_location=None, - input_bucket_name=None, - output_bucket_location=None, - output_bucket_name=None, - batch_id=None, - document_counts=None, - status=None, - created=None, - updated=None): + function: str = None, + input_bucket_location: str = None, + input_bucket_name: str = None, + output_bucket_location: str = None, + output_bucket_name: str = None, + batch_id: str = None, + document_counts: 'DocCounts' = None, + status: str = None, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a BatchStatus object. @@ -1268,7 +1334,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'BatchStatus': """Initialize a BatchStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -1304,7 +1370,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a BatchStatus 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, 'function') and self.function is not None: @@ -1335,17 +1406,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 BatchStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'BatchStatus') -> 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): + def __ne__(self, other: 'BatchStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1363,21 +1438,21 @@ class Batches(): """ The results of a successful **List Batches** request. - :attr list[BatchStatus] batches: (optional) A list of the status of all batch + :attr List[BatchStatus] batches: (optional) A list of the status of all batch requests. """ - def __init__(self, *, batches=None): + def __init__(self, *, batches: List['BatchStatus'] = None) -> None: """ Initialize a Batches object. - :param list[BatchStatus] batches: (optional) A list of the status of all + :param List[BatchStatus] batches: (optional) A list of the status of all batch requests. """ self.batches = batches @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Batches': """Initialize a Batches object from a json dictionary.""" args = {} valid_keys = ['batches'] @@ -1392,24 +1467,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Batches 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, 'batches') and self.batches is not None: _dict['batches'] = [x._to_dict() for x in self.batches] return _dict - def __str__(self): + 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 Batches object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Batches') -> 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): + def __ne__(self, other: 'Batches') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1432,39 +1516,39 @@ class BodyCells(): `column` location in the current table. :attr int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :attr list[str] row_header_ids: (optional) An array that contains the `id` value + :attr List[str] row_header_ids: (optional) An array that contains the `id` value of a row header that is applicable to this body cell. - :attr list[str] row_header_texts: (optional) An array that contains the `text` + :attr List[str] row_header_texts: (optional) An array that contains the `text` value of a row header that is applicable to this body cell. - :attr list[str] row_header_texts_normalized: (optional) If you provide + :attr List[str] row_header_texts_normalized: (optional) If you provide customization input, the normalized version of the row header texts according to the customization; otherwise, the same value as `row_header_texts`. - :attr list[str] column_header_ids: (optional) An array that contains the `id` + :attr List[str] column_header_ids: (optional) An array that contains the `id` value of a column header that is applicable to the current cell. - :attr list[str] column_header_texts: (optional) An array that contains the + :attr List[str] column_header_texts: (optional) An array that contains the `text` value of a column header that is applicable to the current cell. - :attr list[str] column_header_texts_normalized: (optional) If you provide + :attr List[str] column_header_texts_normalized: (optional) If you provide customization input, the normalized version of the column header texts according to the customization; otherwise, the same value as `column_header_texts`. - :attr list[Attribute] attributes: (optional) + :attr List[Attribute] attributes: (optional) """ def __init__(self, *, - cell_id=None, - location=None, - text=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None, - row_header_ids=None, - row_header_texts=None, - row_header_texts_normalized=None, - column_header_ids=None, - column_header_texts=None, - column_header_texts_normalized=None, - attributes=None): + cell_id: str = None, + location: 'Location' = None, + text: str = None, + row_index_begin: int = None, + row_index_end: int = None, + column_index_begin: int = None, + column_index_end: int = None, + row_header_ids: List[str] = None, + row_header_texts: List[str] = None, + row_header_texts_normalized: List[str] = None, + column_header_ids: List[str] = None, + column_header_texts: List[str] = None, + column_header_texts_normalized: List[str] = None, + attributes: List['Attribute'] = None) -> None: """ Initialize a BodyCells object. @@ -1483,23 +1567,23 @@ def __init__(self, `column` location in the current table. :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :param list[str] row_header_ids: (optional) An array that contains the `id` + :param List[str] row_header_ids: (optional) An array that contains the `id` value of a row header that is applicable to this body cell. - :param list[str] row_header_texts: (optional) An array that contains the + :param List[str] row_header_texts: (optional) An array that contains the `text` value of a row header that is applicable to this body cell. - :param list[str] row_header_texts_normalized: (optional) If you provide + :param List[str] row_header_texts_normalized: (optional) If you provide customization input, the normalized version of the row header texts according to the customization; otherwise, the same value as `row_header_texts`. - :param list[str] column_header_ids: (optional) An array that contains the + :param List[str] column_header_ids: (optional) An array that contains the `id` value of a column header that is applicable to the current cell. - :param list[str] column_header_texts: (optional) An array that contains the + :param List[str] column_header_texts: (optional) An array that contains the `text` value of a column header that is applicable to the current cell. - :param list[str] column_header_texts_normalized: (optional) If you provide + :param List[str] column_header_texts_normalized: (optional) If you provide customization input, the normalized version of the column header texts according to the customization; otherwise, the same value as `column_header_texts`. - :param list[Attribute] attributes: (optional) + :param List[Attribute] attributes: (optional) """ self.cell_id = cell_id self.location = location @@ -1517,7 +1601,7 @@ def __init__(self, self.attributes = attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'BodyCells': """Initialize a BodyCells object from a json dictionary.""" args = {} valid_keys = [ @@ -1566,7 +1650,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a BodyCells 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, 'cell_id') and self.cell_id is not None: @@ -1611,17 +1700,21 @@ def _to_dict(self): _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict - def __str__(self): + 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 BodyCells object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'BodyCells') -> 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): + def __ne__(self, other: 'BodyCells') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1631,23 +1724,24 @@ class Category(): Information defining an element's subject matter. :attr str label: (optional) The category of the associated element. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. """ - def __init__(self, *, label=None, provenance_ids=None): + def __init__(self, *, label: str = None, + provenance_ids: List[str] = None) -> None: """ Initialize a Category object. :param str label: (optional) The category of the associated element. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. """ self.label = label self.provenance_ids = provenance_ids @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Category': """Initialize a Category object from a json dictionary.""" args = {} valid_keys = ['label', 'provenance_ids'] @@ -1662,7 +1756,12 @@ def _from_dict(cls, _dict): args['provenance_ids'] = _dict.get('provenance_ids') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Category 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, 'label') and self.label is not None: @@ -1671,17 +1770,21 @@ def _to_dict(self): _dict['provenance_ids'] = self.provenance_ids return _dict - def __str__(self): + 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 Category object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Category') -> 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): + def __ne__(self, other: 'Category') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1723,7 +1826,7 @@ class CategoryComparison(): :attr str label: (optional) The category of the associated element. """ - def __init__(self, *, label=None): + def __init__(self, *, label: str = None) -> None: """ Initialize a CategoryComparison object. @@ -1732,7 +1835,7 @@ def __init__(self, *, label=None): self.label = label @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CategoryComparison': """Initialize a CategoryComparison object from a json dictionary.""" args = {} valid_keys = ['label'] @@ -1745,24 +1848,33 @@ def _from_dict(cls, _dict): args['label'] = _dict.get('label') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoryComparison 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, 'label') and self.label is not None: _dict['label'] = self.label return _dict - def __str__(self): + 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 CategoryComparison object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CategoryComparison') -> 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): + def __ne__(self, other: 'CategoryComparison') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1807,47 +1919,47 @@ class ClassifyReturn(): `contracts`. :attr str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. - :attr list[Element] elements: (optional) Document elements identified by the + :attr List[Element] elements: (optional) Document elements identified by the service. - :attr list[EffectiveDates] effective_dates: (optional) The date or dates on + :attr List[EffectiveDates] effective_dates: (optional) The date or dates on which the document becomes effective. - :attr list[ContractAmts] contract_amounts: (optional) The monetary amounts that + :attr List[ContractAmts] contract_amounts: (optional) The monetary amounts that identify the total amount of the contract that needs to be paid from one party to another. - :attr list[TerminationDates] termination_dates: (optional) The dates on which + :attr List[TerminationDates] termination_dates: (optional) The dates on which the document is to be terminated. - :attr list[ContractTypes] contract_types: (optional) The contract type as + :attr List[ContractTypes] contract_types: (optional) The contract type as declared in the document. - :attr list[ContractTerms] contract_terms: (optional) The durations of the + :attr List[ContractTerms] contract_terms: (optional) The durations of the contract. - :attr list[PaymentTerms] payment_terms: (optional) The document's payment + :attr List[PaymentTerms] payment_terms: (optional) The document's payment durations. - :attr list[ContractCurrencies] contract_currencies: (optional) The contract + :attr List[ContractCurrencies] contract_currencies: (optional) The contract currencies as declared in the document. - :attr list[Tables] tables: (optional) Definition of tables identified in the + :attr List[Tables] tables: (optional) Definition of tables identified in the input document. :attr DocStructure document_structure: (optional) The structure of the input document. - :attr list[Parties] parties: (optional) Definitions of the parties identified in + :attr List[Parties] parties: (optional) Definitions of the parties identified in the input document. """ def __init__(self, *, - document=None, - model_id=None, - model_version=None, - elements=None, - effective_dates=None, - contract_amounts=None, - termination_dates=None, - contract_types=None, - contract_terms=None, - payment_terms=None, - contract_currencies=None, - tables=None, - document_structure=None, - parties=None): + document: 'Document' = None, + model_id: str = None, + model_version: str = None, + elements: List['Element'] = None, + effective_dates: List['EffectiveDates'] = None, + contract_amounts: List['ContractAmts'] = None, + termination_dates: List['TerminationDates'] = None, + contract_types: List['ContractTypes'] = None, + contract_terms: List['ContractTerms'] = None, + payment_terms: List['PaymentTerms'] = None, + contract_currencies: List['ContractCurrencies'] = None, + tables: List['Tables'] = None, + document_structure: 'DocStructure' = None, + parties: List['Parties'] = None) -> None: """ Initialize a ClassifyReturn object. @@ -1858,28 +1970,28 @@ def __init__(self, value is `contracts`. :param str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. - :param list[Element] elements: (optional) Document elements identified by + :param List[Element] elements: (optional) Document elements identified by the service. - :param list[EffectiveDates] effective_dates: (optional) The date or dates + :param List[EffectiveDates] effective_dates: (optional) The date or dates on which the document becomes effective. - :param list[ContractAmts] contract_amounts: (optional) The monetary amounts + :param List[ContractAmts] contract_amounts: (optional) The monetary amounts that identify the total amount of the contract that needs to be paid from one party to another. - :param list[TerminationDates] termination_dates: (optional) The dates on + :param List[TerminationDates] termination_dates: (optional) The dates on which the document is to be terminated. - :param list[ContractTypes] contract_types: (optional) The contract type as + :param List[ContractTypes] contract_types: (optional) The contract type as declared in the document. - :param list[ContractTerms] contract_terms: (optional) The durations of the + :param List[ContractTerms] contract_terms: (optional) The durations of the contract. - :param list[PaymentTerms] payment_terms: (optional) The document's payment + :param List[PaymentTerms] payment_terms: (optional) The document's payment durations. - :param list[ContractCurrencies] contract_currencies: (optional) The + :param List[ContractCurrencies] contract_currencies: (optional) The contract currencies as declared in the document. - :param list[Tables] tables: (optional) Definition of tables identified in + :param List[Tables] tables: (optional) Definition of tables identified in the input document. :param DocStructure document_structure: (optional) The structure of the input document. - :param list[Parties] parties: (optional) Definitions of the parties + :param List[Parties] parties: (optional) Definitions of the parties identified in the input document. """ self.document = document @@ -1898,7 +2010,7 @@ def __init__(self, self.parties = parties @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifyReturn': """Initialize a ClassifyReturn object from a json dictionary.""" args = {} valid_keys = [ @@ -1969,7 +2081,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifyReturn 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, 'document') and self.document is not None: @@ -2021,17 +2138,21 @@ def _to_dict(self): _dict['parties'] = [x._to_dict() for x in self.parties] return _dict - def __str__(self): + 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 ClassifyReturn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifyReturn') -> 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): + def __ne__(self, other: 'ClassifyReturn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2062,14 +2183,14 @@ class ColumnHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - text_normalized=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + cell_id: str = None, + location: object = None, + text: str = None, + text_normalized: str = None, + row_index_begin: int = None, + row_index_end: int = None, + column_index_begin: int = None, + column_index_end: int = None) -> None: """ Initialize a ColumnHeaders object. @@ -2102,7 +2223,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ColumnHeaders': """Initialize a ColumnHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -2132,7 +2253,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ColumnHeaders 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, 'cell_id') and self.cell_id is not None: @@ -2158,17 +2284,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 ColumnHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ColumnHeaders') -> 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): + def __ne__(self, other: 'ColumnHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2182,21 +2312,21 @@ class CompareReturn(): `contracts`. :attr str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. - :attr list[Document] documents: (optional) Information about the documents being + :attr List[Document] documents: (optional) Information about the documents being compared. - :attr list[AlignedElement] aligned_elements: (optional) A list of pairs of + :attr List[AlignedElement] aligned_elements: (optional) A list of pairs of elements that semantically align between the compared documents. - :attr list[UnalignedElement] unaligned_elements: (optional) A list of elements + :attr List[UnalignedElement] unaligned_elements: (optional) A list of elements that do not semantically align between the compared documents. """ def __init__(self, *, - model_id=None, - model_version=None, - documents=None, - aligned_elements=None, - unaligned_elements=None): + model_id: str = None, + model_version: str = None, + documents: List['Document'] = None, + aligned_elements: List['AlignedElement'] = None, + unaligned_elements: List['UnalignedElement'] = None) -> None: """ Initialize a CompareReturn object. @@ -2205,11 +2335,11 @@ def __init__(self, value is `contracts`. :param str model_version: (optional) The version of the analysis model identified by the value of the `model_id` key. - :param list[Document] documents: (optional) Information about the documents + :param List[Document] documents: (optional) Information about the documents being compared. - :param list[AlignedElement] aligned_elements: (optional) A list of pairs of + :param List[AlignedElement] aligned_elements: (optional) A list of pairs of elements that semantically align between the compared documents. - :param list[UnalignedElement] unaligned_elements: (optional) A list of + :param List[UnalignedElement] unaligned_elements: (optional) A list of elements that do not semantically align between the compared documents. """ self.model_id = model_id @@ -2219,7 +2349,7 @@ def __init__(self, self.unaligned_elements = unaligned_elements @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CompareReturn': """Initialize a CompareReturn object from a json dictionary.""" args = {} valid_keys = [ @@ -2251,7 +2381,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CompareReturn 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, 'model_id') and self.model_id is not None: @@ -2273,17 +2408,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 CompareReturn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CompareReturn') -> 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): + def __ne__(self, other: 'CompareReturn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2296,7 +2435,7 @@ class Contact(): :attr str role: (optional) A string listing the role of the contact. """ - def __init__(self, *, name=None, role=None): + def __init__(self, *, name: str = None, role: str = None) -> None: """ Initialize a Contact object. @@ -2307,7 +2446,7 @@ def __init__(self, *, name=None, role=None): self.role = role @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Contact': """Initialize a Contact object from a json dictionary.""" args = {} valid_keys = ['name', 'role'] @@ -2322,7 +2461,12 @@ def _from_dict(cls, _dict): args['role'] = _dict.get('role') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Contact 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, 'name') and self.name is not None: @@ -2331,17 +2475,21 @@ def _to_dict(self): _dict['role'] = self.role return _dict - def __str__(self): + 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 Contact object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Contact') -> 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): + def __ne__(self, other: 'Contact') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2357,7 +2505,8 @@ class Contexts(): `end`. """ - def __init__(self, *, text=None, location=None): + def __init__(self, *, text: str = None, + location: 'Location' = None) -> None: """ Initialize a Contexts object. @@ -2370,7 +2519,7 @@ def __init__(self, *, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Contexts': """Initialize a Contexts object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -2385,7 +2534,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Contexts 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, 'text') and self.text is not None: @@ -2394,17 +2548,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 Contexts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Contexts') -> 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): + def __ne__(self, other: 'Contexts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2422,7 +2580,7 @@ class ContractAmts(): :attr Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2431,12 +2589,12 @@ class ContractAmts(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - interpretation=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + interpretation: 'Interpretation' = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a ContractAmts object. @@ -2449,7 +2607,7 @@ def __init__(self, :param Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2463,7 +2621,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ContractAmts': """Initialize a ContractAmts object from a json dictionary.""" args = {} valid_keys = [ @@ -2490,7 +2648,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ContractAmts 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, @@ -2509,17 +2672,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 ContractAmts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ContractAmts') -> 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): + def __ne__(self, other: 'ContractAmts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2543,7 +2710,7 @@ class ContractCurrencies(): currency, which is listed as a string in [ISO-4217](https://www.iso.org/iso-4217-currency-codes.html) format. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2552,11 +2719,11 @@ class ContractCurrencies(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a ContractCurrencies object. @@ -2567,7 +2734,7 @@ def __init__(self, currency, which is listed as a string in [ISO-4217](https://www.iso.org/iso-4217-currency-codes.html) format. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2580,7 +2747,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ContractCurrencies': """Initialize a ContractCurrencies object from a json dictionary.""" args = {} valid_keys = [ @@ -2604,7 +2771,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ContractCurrencies 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, @@ -2621,17 +2793,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 ContractCurrencies object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ContractCurrencies') -> 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): + def __ne__(self, other: 'ContractCurrencies') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2657,7 +2833,7 @@ class ContractTerms(): :attr Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2666,12 +2842,12 @@ class ContractTerms(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - interpretation=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + interpretation: 'Interpretation' = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a ContractTerms object. @@ -2684,7 +2860,7 @@ def __init__(self, :param Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2698,7 +2874,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ContractTerms': """Initialize a ContractTerms object from a json dictionary.""" args = {} valid_keys = [ @@ -2725,7 +2901,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ContractTerms 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, @@ -2744,17 +2925,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 ContractTerms object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ContractTerms') -> 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): + def __ne__(self, other: 'ContractTerms') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2774,7 +2959,7 @@ class ContractTypes(): :attr str confidence_level: (optional) The confidence level in the identification of the contract type. :attr str text: (optional) The contract type. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2783,17 +2968,17 @@ class ContractTypes(): def __init__(self, *, - confidence_level=None, - text=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a ContractTypes object. :param str confidence_level: (optional) The confidence level in the identification of the contract type. :param str text: (optional) The contract type. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -2805,7 +2990,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ContractTypes': """Initialize a ContractTypes object from a json dictionary.""" args = {} valid_keys = ['confidence_level', 'text', 'provenance_ids', 'location'] @@ -2824,7 +3009,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ContractTypes 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, @@ -2838,17 +3028,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 ContractTypes object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ContractTypes') -> 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): + def __ne__(self, other: 'ContractTypes') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2873,10 +3067,10 @@ class DocCounts(): def __init__(self, *, - total=None, - pending=None, - successful=None, - failed=None): + total: int = None, + pending: int = None, + successful: int = None, + failed: int = None) -> None: """ Initialize a DocCounts object. @@ -2893,7 +3087,7 @@ def __init__(self, self.failed = failed @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocCounts': """Initialize a DocCounts object from a json dictionary.""" args = {} valid_keys = ['total', 'pending', 'successful', 'failed'] @@ -2912,7 +3106,12 @@ def _from_dict(cls, _dict): args['failed'] = _dict.get('failed') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocCounts 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, 'total') and self.total is not None: @@ -2925,17 +3124,21 @@ def _to_dict(self): _dict['failed'] = self.failed return _dict - def __str__(self): + 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 DocCounts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocCounts') -> 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): + def __ne__(self, other: 'DocCounts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2950,7 +3153,8 @@ class DocInfo(): :attr str hash: (optional) The MD5 hash of the input document. """ - def __init__(self, *, html=None, title=None, hash=None): + def __init__(self, *, html: str = None, title: str = None, + hash: str = None) -> None: """ Initialize a DocInfo object. @@ -2965,7 +3169,7 @@ def __init__(self, *, html=None, title=None, hash=None): self.hash = hash @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocInfo': """Initialize a DocInfo object from a json dictionary.""" args = {} valid_keys = ['html', 'title', 'hash'] @@ -2982,7 +3186,12 @@ def _from_dict(cls, _dict): args['hash'] = _dict.get('hash') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocInfo 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, 'html') and self.html is not None: @@ -2993,17 +3202,21 @@ def _to_dict(self): _dict['hash'] = self.hash return _dict - def __str__(self): + 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 DocInfo object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocInfo') -> 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): + def __ne__(self, other: 'DocInfo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3012,31 +3225,31 @@ class DocStructure(): """ The structure of the input document. - :attr list[SectionTitles] section_titles: (optional) An array containing one + :attr List[SectionTitles] section_titles: (optional) An array containing one object per section or subsection identified in the input document. - :attr list[LeadingSentence] leading_sentences: (optional) An array containing + :attr List[LeadingSentence] leading_sentences: (optional) An array containing one object per section or subsection, in parallel with the `section_titles` array, that details the leading sentences in the corresponding section or subsection. - :attr list[Paragraphs] paragraphs: (optional) An array containing one object per + :attr List[Paragraphs] paragraphs: (optional) An array containing one object per paragraph, in parallel with the `section_titles` and `leading_sentences` arrays. """ def __init__(self, *, - section_titles=None, - leading_sentences=None, - paragraphs=None): + section_titles: List['SectionTitles'] = None, + leading_sentences: List['LeadingSentence'] = None, + paragraphs: List['Paragraphs'] = None) -> None: """ Initialize a DocStructure object. - :param list[SectionTitles] section_titles: (optional) An array containing + :param List[SectionTitles] section_titles: (optional) An array containing one object per section or subsection identified in the input document. - :param list[LeadingSentence] leading_sentences: (optional) An array + :param List[LeadingSentence] leading_sentences: (optional) An array containing one object per section or subsection, in parallel with the `section_titles` array, that details the leading sentences in the corresponding section or subsection. - :param list[Paragraphs] paragraphs: (optional) An array containing one + :param List[Paragraphs] paragraphs: (optional) An array containing one object per paragraph, in parallel with the `section_titles` and `leading_sentences` arrays. """ @@ -3045,7 +3258,7 @@ def __init__(self, self.paragraphs = paragraphs @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocStructure': """Initialize a DocStructure object from a json dictionary.""" args = {} valid_keys = ['section_titles', 'leading_sentences', 'paragraphs'] @@ -3070,7 +3283,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocStructure 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, 'section_titles') and self.section_titles is not None: @@ -3086,17 +3304,21 @@ def _to_dict(self): _dict['paragraphs'] = [x._to_dict() for x in self.paragraphs] return _dict - def __str__(self): + 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 DocStructure object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocStructure') -> 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): + def __ne__(self, other: 'DocStructure') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3113,7 +3335,12 @@ class Document(): only in the output of the **Comparing two documents** method. """ - def __init__(self, *, title=None, html=None, hash=None, label=None): + def __init__(self, + *, + title: str = None, + html: str = None, + hash: str = None, + label: str = None) -> None: """ Initialize a Document object. @@ -3130,7 +3357,7 @@ def __init__(self, *, title=None, html=None, hash=None, label=None): self.label = label @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Document': """Initialize a Document object from a json dictionary.""" args = {} valid_keys = ['title', 'html', 'hash', 'label'] @@ -3149,7 +3376,12 @@ def _from_dict(cls, _dict): args['label'] = _dict.get('label') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Document 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, 'title') and self.title is not None: @@ -3162,17 +3394,21 @@ def _to_dict(self): _dict['label'] = self.label return _dict - def __str__(self): + 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 Document object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Document') -> 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): + def __ne__(self, other: 'Document') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3187,7 +3423,7 @@ class EffectiveDates(): :attr str text_normalized: (optional) The normalized form of the effective date, which is listed as a string. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -3196,11 +3432,11 @@ class EffectiveDates(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a EffectiveDates object. @@ -3210,7 +3446,7 @@ def __init__(self, :param str text_normalized: (optional) The normalized form of the effective date, which is listed as a string. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -3223,7 +3459,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EffectiveDates': """Initialize a EffectiveDates object from a json dictionary.""" args = {} valid_keys = [ @@ -3247,7 +3483,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EffectiveDates 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, @@ -3264,17 +3505,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 EffectiveDates object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EffectiveDates') -> 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): + def __ne__(self, other: 'EffectiveDates') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3295,20 +3540,20 @@ class Element(): element in the document, represented with two integers labeled `begin` and `end`. :attr str text: (optional) The text of the element. - :attr list[TypeLabel] types: (optional) Description of the action specified by + :attr List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :attr list[Category] categories: (optional) List of functional categories into + :attr List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :attr list[Attribute] attributes: (optional) List of document attributes. + :attr List[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, *, - location=None, - text=None, - types=None, - categories=None, - attributes=None): + location: 'Location' = None, + text: str = None, + types: List['TypeLabel'] = None, + categories: List['Category'] = None, + attributes: List['Attribute'] = None) -> None: """ Initialize a Element object. @@ -3316,12 +3561,12 @@ def __init__(self, element in the document, represented with two integers labeled `begin` and `end`. :param str text: (optional) The text of the element. - :param list[TypeLabel] types: (optional) Description of the action + :param List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :param list[Category] categories: (optional) List of functional categories + :param List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :param list[Attribute] attributes: (optional) List of document attributes. + :param List[Attribute] attributes: (optional) List of document attributes. """ self.location = location self.text = text @@ -3330,7 +3575,7 @@ def __init__(self, self.attributes = attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Element': """Initialize a Element object from a json dictionary.""" args = {} valid_keys = ['location', 'text', 'types', 'categories', 'attributes'] @@ -3357,7 +3602,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Element 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, 'location') and self.location is not None: @@ -3372,17 +3622,21 @@ def _to_dict(self): _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict - def __str__(self): + 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 Element object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Element') -> 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): + def __ne__(self, other: 'Element') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3398,7 +3652,7 @@ class ElementLocations(): element in the input document. """ - def __init__(self, *, begin=None, end=None): + def __init__(self, *, begin: int = None, end: int = None) -> None: """ Initialize a ElementLocations object. @@ -3411,7 +3665,7 @@ def __init__(self, *, begin=None, end=None): self.end = end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ElementLocations': """Initialize a ElementLocations object from a json dictionary.""" args = {} valid_keys = ['begin', 'end'] @@ -3426,7 +3680,12 @@ def _from_dict(cls, _dict): args['end'] = _dict.get('end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ElementLocations 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, 'begin') and self.begin is not None: @@ -3435,17 +3694,21 @@ def _to_dict(self): _dict['end'] = self.end return _dict - def __str__(self): + 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 ElementLocations object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ElementLocations') -> 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): + def __ne__(self, other: 'ElementLocations') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3461,22 +3724,22 @@ class ElementPair(): :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr list[TypeLabelComparison] types: (optional) Description of the action + :attr List[TypeLabelComparison] types: (optional) Description of the action specified by the element and whom it affects. - :attr list[CategoryComparison] categories: (optional) List of functional + :attr List[CategoryComparison] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :attr list[Attribute] attributes: (optional) List of document attributes. + :attr List[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, *, - document_label=None, - text=None, - location=None, - types=None, - categories=None, - attributes=None): + document_label: str = None, + text: str = None, + location: 'Location' = None, + types: List['TypeLabelComparison'] = None, + categories: List['CategoryComparison'] = None, + attributes: List['Attribute'] = None) -> None: """ Initialize a ElementPair object. @@ -3487,12 +3750,12 @@ def __init__(self, :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :param list[TypeLabelComparison] types: (optional) Description of the + :param List[TypeLabelComparison] types: (optional) Description of the action specified by the element and whom it affects. - :param list[CategoryComparison] categories: (optional) List of functional + :param List[CategoryComparison] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :param list[Attribute] attributes: (optional) List of document attributes. + :param List[Attribute] attributes: (optional) List of document attributes. """ self.document_label = document_label self.text = text @@ -3502,7 +3765,7 @@ def __init__(self, self.attributes = attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ElementPair': """Initialize a ElementPair object from a json dictionary.""" args = {} valid_keys = [ @@ -3535,7 +3798,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ElementPair 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, 'document_label') and self.document_label is not None: @@ -3552,17 +3820,21 @@ def _to_dict(self): _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict - def __str__(self): + 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 ElementPair object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ElementPair') -> 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): + def __ne__(self, other: 'ElementPair') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3588,15 +3860,15 @@ class FeedbackDataInput(): """ def __init__(self, - feedback_type, - location, - text, - original_labels, - updated_labels, + feedback_type: str, + location: 'Location', + text: str, + original_labels: 'OriginalLabelsIn', + updated_labels: 'UpdatedLabelsIn', *, - document=None, - model_id=None, - model_version=None): + document: 'ShortDoc' = None, + model_id: str = None, + model_version: str = None) -> None: """ Initialize a FeedbackDataInput object. @@ -3626,7 +3898,7 @@ def __init__(self, self.updated_labels = updated_labels @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeedbackDataInput': """Initialize a FeedbackDataInput object from a json dictionary.""" args = {} valid_keys = [ @@ -3678,9 +3950,14 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeedbackDataInput 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, 'feedback_type') and self.feedback_type is not None: _dict['feedback_type'] = self.feedback_type if hasattr(self, 'document') and self.document is not None: @@ -3700,17 +3977,21 @@ def _to_dict(self): _dict['updated_labels'] = self.updated_labels._to_dict() return _dict - def __str__(self): + 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 FeedbackDataInput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeedbackDataInput') -> 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): + def __ne__(self, other: 'FeedbackDataInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3740,15 +4021,15 @@ class FeedbackDataOutput(): def __init__(self, *, - feedback_type=None, - document=None, - model_id=None, - model_version=None, - location=None, - text=None, - original_labels=None, - updated_labels=None, - pagination=None): + feedback_type: str = None, + document: 'ShortDoc' = None, + model_id: str = None, + model_version: str = None, + location: 'Location' = None, + text: str = None, + original_labels: 'OriginalLabelsOut' = None, + updated_labels: 'UpdatedLabelsOut' = None, + pagination: 'Pagination' = None) -> None: """ Initialize a FeedbackDataOutput object. @@ -3782,7 +4063,7 @@ def __init__(self, self.pagination = pagination @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeedbackDataOutput': """Initialize a FeedbackDataOutput object from a json dictionary.""" args = {} valid_keys = [ @@ -3817,7 +4098,12 @@ def _from_dict(cls, _dict): args['pagination'] = Pagination._from_dict(_dict.get('pagination')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeedbackDataOutput 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, 'feedback_type') and self.feedback_type is not None: @@ -3841,17 +4127,21 @@ def _to_dict(self): _dict['pagination'] = self.pagination._to_dict() return _dict - def __str__(self): + 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 FeedbackDataOutput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeedbackDataOutput') -> 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): + def __ne__(self, other: 'FeedbackDataOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3864,7 +4154,7 @@ class FeedbackDeleted(): :attr str message: (optional) Status message returned from the service. """ - def __init__(self, *, status=None, message=None): + def __init__(self, *, status: int = None, message: str = None) -> None: """ Initialize a FeedbackDeleted object. @@ -3875,7 +4165,7 @@ def __init__(self, *, status=None, message=None): self.message = message @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeedbackDeleted': """Initialize a FeedbackDeleted object from a json dictionary.""" args = {} valid_keys = ['status', 'message'] @@ -3890,7 +4180,12 @@ def _from_dict(cls, _dict): args['message'] = _dict.get('message') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeedbackDeleted 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, 'status') and self.status is not None: @@ -3899,17 +4194,21 @@ def _to_dict(self): _dict['message'] = self.message return _dict - def __str__(self): + 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 FeedbackDeleted object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeedbackDeleted') -> 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): + def __ne__(self, other: 'FeedbackDeleted') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3918,21 +4217,21 @@ class FeedbackList(): """ The results of a successful **List Feedback** request for all feedback. - :attr list[GetFeedback] feedback: (optional) A list of all feedback for the + :attr List[GetFeedback] feedback: (optional) A list of all feedback for the document. """ - def __init__(self, *, feedback=None): + def __init__(self, *, feedback: List['GetFeedback'] = None) -> None: """ Initialize a FeedbackList object. - :param list[GetFeedback] feedback: (optional) A list of all feedback for + :param List[GetFeedback] feedback: (optional) A list of all feedback for the document. """ self.feedback = feedback @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeedbackList': """Initialize a FeedbackList object from a json dictionary.""" args = {} valid_keys = ['feedback'] @@ -3947,24 +4246,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeedbackList 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, 'feedback') and self.feedback is not None: _dict['feedback'] = [x._to_dict() for x in self.feedback] return _dict - def __str__(self): + 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 FeedbackList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeedbackList') -> 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): + def __ne__(self, other: 'FeedbackList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3986,11 +4294,11 @@ class FeedbackReturn(): def __init__(self, *, - feedback_id=None, - user_id=None, - comment=None, - created=None, - feedback_data=None): + feedback_id: str = None, + user_id: str = None, + comment: str = None, + created: datetime = None, + feedback_data: 'FeedbackDataOutput' = None) -> None: """ Initialize a FeedbackReturn object. @@ -4011,7 +4319,7 @@ def __init__(self, self.feedback_data = feedback_data @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeedbackReturn': """Initialize a FeedbackReturn object from a json dictionary.""" args = {} valid_keys = [ @@ -4035,7 +4343,12 @@ def _from_dict(cls, _dict): _dict.get('feedback_data')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeedbackReturn 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, 'feedback_id') and self.feedback_id is not None: @@ -4050,17 +4363,21 @@ def _to_dict(self): _dict['feedback_data'] = self.feedback_data._to_dict() return _dict - def __str__(self): + 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 FeedbackReturn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeedbackReturn') -> 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): + def __ne__(self, other: 'FeedbackReturn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4081,10 +4398,10 @@ class GetFeedback(): def __init__(self, *, - feedback_id=None, - created=None, - comment=None, - feedback_data=None): + feedback_id: str = None, + created: datetime = None, + comment: str = None, + feedback_data: 'FeedbackDataOutput' = None) -> None: """ Initialize a GetFeedback object. @@ -4103,7 +4420,7 @@ def __init__(self, self.feedback_data = feedback_data @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'GetFeedback': """Initialize a GetFeedback object from a json dictionary.""" args = {} valid_keys = ['feedback_id', 'created', 'comment', 'feedback_data'] @@ -4123,7 +4440,12 @@ def _from_dict(cls, _dict): _dict.get('feedback_data')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a GetFeedback 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, 'feedback_id') and self.feedback_id is not None: @@ -4136,17 +4458,21 @@ def _to_dict(self): _dict['feedback_data'] = self.feedback_data._to_dict() return _dict - def __str__(self): + 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 GetFeedback object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'GetFeedback') -> 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): + def __ne__(self, other: 'GetFeedback') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4165,11 +4491,11 @@ class HTMLReturn(): def __init__(self, *, - num_pages=None, - author=None, - publication_date=None, - title=None, - html=None): + num_pages: str = None, + author: str = None, + publication_date: str = None, + title: str = None, + html: str = None) -> None: """ Initialize a HTMLReturn object. @@ -4189,7 +4515,7 @@ def __init__(self, self.html = html @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'HTMLReturn': """Initialize a HTMLReturn object from a json dictionary.""" args = {} valid_keys = [ @@ -4212,7 +4538,12 @@ def _from_dict(cls, _dict): args['html'] = _dict.get('html') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a HTMLReturn 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, 'num_pages') and self.num_pages is not None: @@ -4228,17 +4559,21 @@ def _to_dict(self): _dict['html'] = self.html return _dict - def __str__(self): + 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 HTMLReturn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'HTMLReturn') -> 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): + def __ne__(self, other: 'HTMLReturn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4260,7 +4595,11 @@ class Interpretation(): contains the ambiguous symbol as-is. """ - def __init__(self, *, value=None, numeric_value=None, unit=None): + def __init__(self, + *, + value: str = None, + numeric_value: float = None, + unit: str = None) -> None: """ Initialize a Interpretation object. @@ -4281,7 +4620,7 @@ def __init__(self, *, value=None, numeric_value=None, unit=None): self.unit = unit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Interpretation': """Initialize a Interpretation object from a json dictionary.""" args = {} valid_keys = ['value', 'numeric_value', 'unit'] @@ -4298,7 +4637,12 @@ def _from_dict(cls, _dict): args['unit'] = _dict.get('unit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Interpretation 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: @@ -4309,17 +4653,21 @@ def _to_dict(self): _dict['unit'] = self.unit return _dict - def __str__(self): + 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 Interpretation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Interpretation') -> 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): + def __ne__(self, other: 'Interpretation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4336,7 +4684,11 @@ class Key(): markup. """ - def __init__(self, *, cell_id=None, location=None, text=None): + def __init__(self, + *, + cell_id: str = None, + location: 'Location' = None, + text: str = None) -> None: """ Initialize a Key object. @@ -4352,7 +4704,7 @@ def __init__(self, *, cell_id=None, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Key': """Initialize a Key object from a json dictionary.""" args = {} valid_keys = ['cell_id', 'location', 'text'] @@ -4369,7 +4721,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Key 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, 'cell_id') and self.cell_id is not None: @@ -4380,17 +4737,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 Key object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Key') -> 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): + def __ne__(self, other: 'Key') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4400,21 +4761,22 @@ class KeyValuePair(): Key-value pairs detected across cell boundaries. :attr Key key: (optional) A key in a key-value pair. - :attr list[Value] value: (optional) A list of values in a key-value pair. + :attr List[Value] value: (optional) A list of values in a key-value pair. """ - def __init__(self, *, key=None, value=None): + def __init__(self, *, key: 'Key' = None, + value: List['Value'] = None) -> None: """ Initialize a KeyValuePair object. :param Key key: (optional) A key in a key-value pair. - :param list[Value] value: (optional) A list of values in a key-value pair. + :param List[Value] value: (optional) A list of values in a key-value pair. """ self.key = key self.value = value @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'KeyValuePair': """Initialize a KeyValuePair object from a json dictionary.""" args = {} valid_keys = ['key', 'value'] @@ -4429,7 +4791,12 @@ def _from_dict(cls, _dict): args['value'] = [Value._from_dict(x) for x in (_dict.get('value'))] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a KeyValuePair 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, 'key') and self.key is not None: @@ -4438,17 +4805,21 @@ def _to_dict(self): _dict['value'] = [x._to_dict() for x in self.value] return _dict - def __str__(self): + 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 KeyValuePair object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'KeyValuePair') -> 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): + def __ne__(self, other: 'KeyValuePair') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4463,7 +4834,7 @@ class Label(): :attr str party: The identified `party` of the element. """ - def __init__(self, nature, party): + def __init__(self, nature: str, party: str) -> None: """ Initialize a Label object. @@ -4474,7 +4845,7 @@ def __init__(self, nature, party): self.party = party @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Label': """Initialize a Label object from a json dictionary.""" args = {} valid_keys = ['nature', 'party'] @@ -4495,7 +4866,12 @@ def _from_dict(cls, _dict): 'Required property \'party\' not present in Label JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Label 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, 'nature') and self.nature is not None: @@ -4504,17 +4880,21 @@ def _to_dict(self): _dict['party'] = self.party return _dict - def __str__(self): + 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 Label object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Label') -> 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): + def __ne__(self, other: 'Label') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4527,11 +4907,15 @@ class LeadingSentence(): :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr list[ElementLocations] element_locations: (optional) An array of + :attr List[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected leading sentences. """ - def __init__(self, *, text=None, location=None, element_locations=None): + def __init__(self, + *, + text: str = None, + location: 'Location' = None, + element_locations: List['ElementLocations'] = None) -> None: """ Initialize a LeadingSentence object. @@ -4539,7 +4923,7 @@ def __init__(self, *, text=None, location=None, element_locations=None): :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :param list[ElementLocations] element_locations: (optional) An array of + :param List[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected leading sentences. """ self.text = text @@ -4547,7 +4931,7 @@ def __init__(self, *, text=None, location=None, element_locations=None): self.element_locations = element_locations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LeadingSentence': """Initialize a LeadingSentence object from a json dictionary.""" args = {} valid_keys = ['text', 'location', 'element_locations'] @@ -4567,7 +4951,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LeadingSentence 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, 'text') and self.text is not None: @@ -4581,17 +4970,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 LeadingSentence object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LeadingSentence') -> 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): + def __ne__(self, other: 'LeadingSentence') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4605,7 +4998,7 @@ class Location(): :attr int end: The element's `end` index. """ - def __init__(self, begin, end): + def __init__(self, begin: int, end: int) -> None: """ Initialize a Location object. @@ -4616,7 +5009,7 @@ def __init__(self, begin, end): self.end = end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Location': """Initialize a Location object from a json dictionary.""" args = {} valid_keys = ['begin', 'end'] @@ -4637,7 +5030,12 @@ def _from_dict(cls, _dict): 'Required property \'end\' not present in Location JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Location 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, 'begin') and self.begin is not None: @@ -4646,17 +5044,21 @@ def _to_dict(self): _dict['end'] = self.end return _dict - def __str__(self): + 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 Location object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Location') -> 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): + def __ne__(self, other: 'Location') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4671,7 +5073,8 @@ class Mention(): `end`. """ - def __init__(self, *, text=None, location=None): + def __init__(self, *, text: str = None, + location: 'Location' = None) -> None: """ Initialize a Mention object. @@ -4684,7 +5087,7 @@ def __init__(self, *, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Mention': """Initialize a Mention object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -4699,7 +5102,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Mention 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, 'text') and self.text is not None: @@ -4708,17 +5116,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 Mention object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Mention') -> 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): + def __ne__(self, other: 'Mention') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4727,26 +5139,27 @@ class OriginalLabelsIn(): """ The original labeling from the input document, without the submitted feedback. - :attr list[TypeLabel] types: Description of the action specified by the element + :attr List[TypeLabel] types: Description of the action specified by the element and whom it affects. - :attr list[Category] categories: List of functional categories into which the + :attr List[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ - def __init__(self, types, categories): + def __init__(self, types: List['TypeLabel'], + categories: List['Category']) -> None: """ Initialize a OriginalLabelsIn object. - :param list[TypeLabel] types: Description of the action specified by the + :param List[TypeLabel] types: Description of the action specified by the element and whom it affects. - :param list[Category] categories: List of functional categories into which + :param List[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ self.types = types self.categories = categories @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'OriginalLabelsIn': """Initialize a OriginalLabelsIn object from a json dictionary.""" args = {} valid_keys = ['types', 'categories'] @@ -4773,7 +5186,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a OriginalLabelsIn 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, 'types') and self.types is not None: @@ -4782,17 +5200,21 @@ def _to_dict(self): _dict['categories'] = [x._to_dict() for x in self.categories] return _dict - def __str__(self): + 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 OriginalLabelsIn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'OriginalLabelsIn') -> 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): + def __ne__(self, other: 'OriginalLabelsIn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4801,22 +5223,26 @@ class OriginalLabelsOut(): """ The original labeling from the input document, without the submitted feedback. - :attr list[TypeLabel] types: (optional) Description of the action specified by + :attr List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :attr list[Category] categories: (optional) List of functional categories into + :attr List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :attr str modification: (optional) A string identifying the type of modification the feedback entry in the `updated_labels` array. Possible values are `added`, `not_changed`, and `removed`. """ - def __init__(self, *, types=None, categories=None, modification=None): + def __init__(self, + *, + types: List['TypeLabel'] = None, + categories: List['Category'] = None, + modification: str = None) -> None: """ Initialize a OriginalLabelsOut object. - :param list[TypeLabel] types: (optional) Description of the action + :param List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :param list[Category] categories: (optional) List of functional categories + :param List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :param str modification: (optional) A string identifying the type of @@ -4828,7 +5254,7 @@ def __init__(self, *, types=None, categories=None, modification=None): self.modification = modification @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'OriginalLabelsOut': """Initialize a OriginalLabelsOut object from a json dictionary.""" args = {} valid_keys = ['types', 'categories', 'modification'] @@ -4849,7 +5275,12 @@ def _from_dict(cls, _dict): args['modification'] = _dict.get('modification') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a OriginalLabelsOut 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, 'types') and self.types is not None: @@ -4860,17 +5291,21 @@ def _to_dict(self): _dict['modification'] = self.modification return _dict - def __str__(self): + 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 OriginalLabelsOut object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'OriginalLabelsOut') -> 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): + def __ne__(self, other: 'OriginalLabelsOut') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4899,11 +5334,11 @@ class Pagination(): def __init__(self, *, - refresh_cursor=None, - next_cursor=None, - refresh_url=None, - next_url=None, - total=None): + refresh_cursor: str = None, + next_cursor: str = None, + refresh_url: str = None, + next_url: str = None, + total: int = None) -> None: """ Initialize a Pagination object. @@ -4924,7 +5359,7 @@ def __init__(self, self.total = total @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Pagination': """Initialize a Pagination object from a json dictionary.""" args = {} valid_keys = [ @@ -4947,7 +5382,12 @@ def _from_dict(cls, _dict): args['total'] = _dict.get('total') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Pagination 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, 'refresh_cursor') and self.refresh_cursor is not None: @@ -4962,17 +5402,21 @@ def _to_dict(self): _dict['total'] = self.total return _dict - def __str__(self): + 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 Pagination object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Pagination') -> 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): + def __ne__(self, other: 'Pagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4986,7 +5430,7 @@ class Paragraphs(): `end`. """ - def __init__(self, *, location=None): + def __init__(self, *, location: 'Location' = None) -> None: """ Initialize a Paragraphs object. @@ -4997,7 +5441,7 @@ def __init__(self, *, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Paragraphs': """Initialize a Paragraphs object from a json dictionary.""" args = {} valid_keys = ['location'] @@ -5010,24 +5454,33 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Paragraphs 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, 'location') and self.location is not None: _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 Paragraphs object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Paragraphs') -> 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): + def __ne__(self, other: 'Paragraphs') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5041,22 +5494,22 @@ class Parties(): :attr str role: (optional) A string identifying the party's role. :attr str importance: (optional) A string that identifies the importance of the party. - :attr list[Address] addresses: (optional) A list of the party's address or + :attr List[Address] addresses: (optional) A list of the party's address or addresses. - :attr list[Contact] contacts: (optional) A list of the names and roles of + :attr List[Contact] contacts: (optional) A list of the names and roles of contacts identified in the input document. - :attr list[Mention] mentions: (optional) A list of the party's mentions in the + :attr List[Mention] mentions: (optional) A list of the party's mentions in the input document. """ def __init__(self, *, - party=None, - role=None, - importance=None, - addresses=None, - contacts=None, - mentions=None): + party: str = None, + role: str = None, + importance: str = None, + addresses: List['Address'] = None, + contacts: List['Contact'] = None, + mentions: List['Mention'] = None) -> None: """ Initialize a Parties object. @@ -5064,11 +5517,11 @@ def __init__(self, :param str role: (optional) A string identifying the party's role. :param str importance: (optional) A string that identifies the importance of the party. - :param list[Address] addresses: (optional) A list of the party's address or + :param List[Address] addresses: (optional) A list of the party's address or addresses. - :param list[Contact] contacts: (optional) A list of the names and roles of + :param List[Contact] contacts: (optional) A list of the names and roles of contacts identified in the input document. - :param list[Mention] mentions: (optional) A list of the party's mentions in + :param List[Mention] mentions: (optional) A list of the party's mentions in the input document. """ self.party = party @@ -5079,7 +5532,7 @@ def __init__(self, self.mentions = mentions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Parties': """Initialize a Parties object from a json dictionary.""" args = {} valid_keys = [ @@ -5110,7 +5563,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Parties 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, 'party') and self.party is not None: @@ -5127,17 +5585,21 @@ def _to_dict(self): _dict['mentions'] = [x._to_dict() for x in self.mentions] return _dict - def __str__(self): + 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 Parties object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Parties') -> 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): + def __ne__(self, other: 'Parties') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5162,7 +5624,7 @@ class PaymentTerms(): :attr Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -5171,12 +5633,12 @@ class PaymentTerms(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - interpretation=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + interpretation: 'Interpretation' = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a PaymentTerms object. @@ -5189,7 +5651,7 @@ def __init__(self, :param Interpretation interpretation: (optional) The details of the normalized text, if applicable. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -5203,7 +5665,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'PaymentTerms': """Initialize a PaymentTerms object from a json dictionary.""" args = {} valid_keys = [ @@ -5230,7 +5692,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a PaymentTerms 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, @@ -5249,17 +5716,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 PaymentTerms object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'PaymentTerms') -> 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): + def __ne__(self, other: 'PaymentTerms') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5298,14 +5769,14 @@ class RowHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - text_normalized=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + cell_id: str = None, + location: 'Location' = None, + text: str = None, + text_normalized: str = None, + row_index_begin: int = None, + row_index_end: int = None, + column_index_begin: int = None, + column_index_end: int = None) -> None: """ Initialize a RowHeaders object. @@ -5338,7 +5809,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RowHeaders': """Initialize a RowHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -5368,7 +5839,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RowHeaders 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, 'cell_id') and self.cell_id is not None: @@ -5394,17 +5870,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 RowHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RowHeaders') -> 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): + def __ne__(self, other: 'RowHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5419,7 +5899,8 @@ class SectionTitle(): `end`. """ - def __init__(self, *, text=None, location=None): + def __init__(self, *, text: str = None, + location: 'Location' = None) -> None: """ Initialize a SectionTitle object. @@ -5432,7 +5913,7 @@ def __init__(self, *, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SectionTitle': """Initialize a SectionTitle object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -5447,7 +5928,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SectionTitle 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, 'text') and self.text is not None: @@ -5456,17 +5942,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 SectionTitle object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SectionTitle') -> 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): + def __ne__(self, other: 'SectionTitle') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5485,16 +5975,16 @@ class SectionTitles(): :attr int level: (optional) An integer indicating the level at which the section is located in the input document. For example, `1` represents a top-level section, `2` represents a subsection within the level `1` section, and so forth. - :attr list[ElementLocations] element_locations: (optional) An array of + :attr List[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected section titles. """ def __init__(self, *, - text=None, - location=None, - level=None, - element_locations=None): + text: str = None, + location: 'Location' = None, + level: int = None, + element_locations: List['ElementLocations'] = None) -> None: """ Initialize a SectionTitles object. @@ -5506,7 +5996,7 @@ def __init__(self, section is located in the input document. For example, `1` represents a top-level section, `2` represents a subsection within the level `1` section, and so forth. - :param list[ElementLocations] element_locations: (optional) An array of + :param List[ElementLocations] element_locations: (optional) An array of `location` objects that lists the locations of detected section titles. """ self.text = text @@ -5515,7 +6005,7 @@ def __init__(self, self.element_locations = element_locations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SectionTitles': """Initialize a SectionTitles object from a json dictionary.""" args = {} valid_keys = ['text', 'location', 'level', 'element_locations'] @@ -5537,7 +6027,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SectionTitles 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, 'text') and self.text is not None: @@ -5553,17 +6048,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 SectionTitles object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SectionTitles') -> 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): + def __ne__(self, other: 'SectionTitles') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5576,7 +6075,7 @@ class ShortDoc(): :attr str hash: (optional) The MD5 hash of the input document. """ - def __init__(self, *, title=None, hash=None): + def __init__(self, *, title: str = None, hash: str = None) -> None: """ Initialize a ShortDoc object. @@ -5588,7 +6087,7 @@ def __init__(self, *, title=None, hash=None): self.hash = hash @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ShortDoc': """Initialize a ShortDoc object from a json dictionary.""" args = {} valid_keys = ['title', 'hash'] @@ -5603,7 +6102,12 @@ def _from_dict(cls, _dict): args['hash'] = _dict.get('hash') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ShortDoc 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, 'title') and self.title is not None: @@ -5612,17 +6116,21 @@ def _to_dict(self): _dict['hash'] = self.hash return _dict - def __str__(self): + 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 ShortDoc object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ShortDoc') -> 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): + def __ne__(self, other: 'ShortDoc') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5649,13 +6157,13 @@ class TableHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + cell_id: str = None, + location: object = None, + text: str = None, + row_index_begin: int = None, + row_index_end: int = None, + column_index_begin: int = None, + column_index_end: int = None) -> None: """ Initialize a TableHeaders object. @@ -5684,7 +6192,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableHeaders': """Initialize a TableHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -5712,7 +6220,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableHeaders 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, 'cell_id') and self.cell_id is not None: @@ -5735,17 +6248,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 TableHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableHeaders') -> 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): + def __ne__(self, other: 'TableHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5758,16 +6275,16 @@ class TableReturn(): :attr str model_id: (optional) The ID of the model used to extract the table contents. The value for table extraction is `tables`. :attr str model_version: (optional) The version of the `tables` model ID. - :attr list[Tables] tables: (optional) Definitions of the tables identified in + :attr List[Tables] tables: (optional) Definitions of the tables identified in the input document. """ def __init__(self, *, - document=None, - model_id=None, - model_version=None, - tables=None): + document: 'DocInfo' = None, + model_id: str = None, + model_version: str = None, + tables: List['Tables'] = None) -> None: """ Initialize a TableReturn object. @@ -5776,7 +6293,7 @@ def __init__(self, :param str model_id: (optional) The ID of the model used to extract the table contents. The value for table extraction is `tables`. :param str model_version: (optional) The version of the `tables` model ID. - :param list[Tables] tables: (optional) Definitions of the tables identified + :param List[Tables] tables: (optional) Definitions of the tables identified in the input document. """ self.document = document @@ -5785,7 +6302,7 @@ def __init__(self, self.tables = tables @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableReturn': """Initialize a TableReturn object from a json dictionary.""" args = {} valid_keys = ['document', 'model_id', 'model_version', 'tables'] @@ -5806,7 +6323,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableReturn 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, 'document') and self.document is not None: @@ -5819,17 +6341,21 @@ def _to_dict(self): _dict['tables'] = [x._to_dict() for x in self.tables] return _dict - def __str__(self): + 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 TableReturn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableReturn') -> 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): + def __ne__(self, other: 'TableReturn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5846,7 +6372,8 @@ class TableTitle(): :attr str text: (optional) The text of the identified table title or caption. """ - def __init__(self, *, location=None, text=None): + def __init__(self, *, location: 'Location' = None, + text: str = None) -> None: """ Initialize a TableTitle object. @@ -5860,7 +6387,7 @@ def __init__(self, *, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableTitle': """Initialize a TableTitle object from a json dictionary.""" args = {} valid_keys = ['location', 'text'] @@ -5875,7 +6402,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableTitle 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, 'location') and self.location is not None: @@ -5884,17 +6416,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 TableTitle object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableTitle') -> 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): + def __ne__(self, other: 'TableTitle') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5914,36 +6450,36 @@ class Tables(): current table of the form `Table x.: ...`. Empty when no title is identified. When exposed, the `title` is also excluded from the `contexts` array of the same table. - :attr list[TableHeaders] table_headers: (optional) An array of table-level cells + :attr List[TableHeaders] table_headers: (optional) An array of table-level cells that apply as headers to all the other cells in the current table. - :attr list[RowHeaders] row_headers: (optional) An array of row-level cells, each + :attr List[RowHeaders] row_headers: (optional) An array of row-level cells, each applicable as a header to other cells in the same row as itself, of the current table. - :attr list[ColumnHeaders] column_headers: (optional) An array of column-level + :attr List[ColumnHeaders] column_headers: (optional) An array of column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. - :attr list[BodyCells] body_cells: (optional) An array of cells that are neither + :attr List[BodyCells] body_cells: (optional) An array of cells that are neither table header nor column header nor row header cells, of the current table with corresponding row and column header associations. - :attr list[Contexts] contexts: (optional) An array of objects that list text + :attr List[Contexts] contexts: (optional) An array of objects that list text that is related to the table contents and that precedes or follows the current table. - :attr list[KeyValuePair] key_value_pairs: (optional) An array of key-value pairs + :attr List[KeyValuePair] key_value_pairs: (optional) An array of key-value pairs identified in the current table. """ def __init__(self, *, - location=None, - text=None, - section_title=None, - title=None, - table_headers=None, - row_headers=None, - column_headers=None, - body_cells=None, - contexts=None, - key_value_pairs=None): + location: 'Location' = None, + text: str = None, + section_title: 'SectionTitle' = None, + title: 'TableTitle' = None, + table_headers: List['TableHeaders'] = None, + row_headers: List['RowHeaders'] = None, + column_headers: List['ColumnHeaders'] = None, + body_cells: List['BodyCells'] = None, + contexts: List['Contexts'] = None, + key_value_pairs: List['KeyValuePair'] = None) -> None: """ Initialize a Tables object. @@ -5958,21 +6494,21 @@ def __init__(self, the current table of the form `Table x.: ...`. Empty when no title is identified. When exposed, the `title` is also excluded from the `contexts` array of the same table. - :param list[TableHeaders] table_headers: (optional) An array of table-level + :param List[TableHeaders] table_headers: (optional) An array of table-level cells that apply as headers to all the other cells in the current table. - :param list[RowHeaders] row_headers: (optional) An array of row-level + :param List[RowHeaders] row_headers: (optional) An array of row-level cells, each applicable as a header to other cells in the same row as itself, of the current table. - :param list[ColumnHeaders] column_headers: (optional) An array of + :param List[ColumnHeaders] column_headers: (optional) An array of column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. - :param list[BodyCells] body_cells: (optional) An array of cells that are + :param List[BodyCells] body_cells: (optional) An array of cells that are neither table header nor column header nor row header cells, of the current table with corresponding row and column header associations. - :param list[Contexts] contexts: (optional) An array of objects that list + :param List[Contexts] contexts: (optional) An array of objects that list text that is related to the table contents and that precedes or follows the current table. - :param list[KeyValuePair] key_value_pairs: (optional) An array of key-value + :param List[KeyValuePair] key_value_pairs: (optional) An array of key-value pairs identified in the current table. """ self.location = location @@ -5987,7 +6523,7 @@ def __init__(self, self.key_value_pairs = key_value_pairs @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Tables': """Initialize a Tables object from a json dictionary.""" args = {} valid_keys = [ @@ -6037,7 +6573,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Tables 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, 'location') and self.location is not None: @@ -6067,17 +6608,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 Tables object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Tables') -> 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): + def __ne__(self, other: 'Tables') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6092,7 +6637,7 @@ class TerminationDates(): :attr str text_normalized: (optional) The normalized form of the termination date, which is listed as a string. This element is optional; it is returned only if normalized text exists. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :attr Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -6101,11 +6646,11 @@ class TerminationDates(): def __init__(self, *, - confidence_level=None, - text=None, - text_normalized=None, - provenance_ids=None, - location=None): + confidence_level: str = None, + text: str = None, + text_normalized: str = None, + provenance_ids: List[str] = None, + location: 'Location' = None) -> None: """ Initialize a TerminationDates object. @@ -6115,7 +6660,7 @@ def __init__(self, :param str text_normalized: (optional) The normalized form of the termination date, which is listed as a string. This element is optional; it is returned only if normalized text exists. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. :param Location location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and @@ -6128,7 +6673,7 @@ def __init__(self, self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TerminationDates': """Initialize a TerminationDates object from a json dictionary.""" args = {} valid_keys = [ @@ -6152,7 +6697,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TerminationDates 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, @@ -6169,17 +6719,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 TerminationDates object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TerminationDates') -> 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): + def __ne__(self, other: 'TerminationDates') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6199,25 +6753,28 @@ class TypeLabel(): :attr Label label: (optional) A pair of `nature` and `party` objects. The `nature` object identifies the effect of the element on the identified `party`, and the `party` object identifies the affected party. - :attr list[str] provenance_ids: (optional) Hashed values that you can send to + :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. """ - def __init__(self, *, label=None, provenance_ids=None): + def __init__(self, + *, + label: 'Label' = None, + provenance_ids: List[str] = None) -> None: """ Initialize a TypeLabel object. :param Label label: (optional) A pair of `nature` and `party` objects. The `nature` object identifies the effect of the element on the identified `party`, and the `party` object identifies the affected party. - :param list[str] provenance_ids: (optional) Hashed values that you can send + :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. """ self.label = label self.provenance_ids = provenance_ids @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TypeLabel': """Initialize a TypeLabel object from a json dictionary.""" args = {} valid_keys = ['label', 'provenance_ids'] @@ -6232,7 +6789,12 @@ def _from_dict(cls, _dict): args['provenance_ids'] = _dict.get('provenance_ids') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TypeLabel 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, 'label') and self.label is not None: @@ -6241,17 +6803,21 @@ def _to_dict(self): _dict['provenance_ids'] = self.provenance_ids return _dict - def __str__(self): + 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 TypeLabel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TypeLabel') -> 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): + def __ne__(self, other: 'TypeLabel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6265,7 +6831,7 @@ class TypeLabelComparison(): and the `party` object identifies the affected party. """ - def __init__(self, *, label=None): + def __init__(self, *, label: 'Label' = None) -> None: """ Initialize a TypeLabelComparison object. @@ -6276,7 +6842,7 @@ def __init__(self, *, label=None): self.label = label @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TypeLabelComparison': """Initialize a TypeLabelComparison object from a json dictionary.""" args = {} valid_keys = ['label'] @@ -6289,24 +6855,33 @@ def _from_dict(cls, _dict): args['label'] = Label._from_dict(_dict.get('label')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TypeLabelComparison 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, 'label') and self.label is not None: _dict['label'] = self.label._to_dict() return _dict - def __str__(self): + 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 TypeLabelComparison object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TypeLabelComparison') -> 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): + def __ne__(self, other: 'TypeLabelComparison') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6322,22 +6897,22 @@ class UnalignedElement(): element in the document, represented with two integers labeled `begin` and `end`. :attr str text: (optional) The text of the element. - :attr list[TypeLabelComparison] types: (optional) Description of the action + :attr List[TypeLabelComparison] types: (optional) Description of the action specified by the element and whom it affects. - :attr list[CategoryComparison] categories: (optional) List of functional + :attr List[CategoryComparison] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :attr list[Attribute] attributes: (optional) List of document attributes. + :attr List[Attribute] attributes: (optional) List of document attributes. """ def __init__(self, *, - document_label=None, - location=None, - text=None, - types=None, - categories=None, - attributes=None): + document_label: str = None, + location: 'Location' = None, + text: str = None, + types: List['TypeLabelComparison'] = None, + categories: List['CategoryComparison'] = None, + attributes: List['Attribute'] = None) -> None: """ Initialize a UnalignedElement object. @@ -6348,12 +6923,12 @@ def __init__(self, element in the document, represented with two integers labeled `begin` and `end`. :param str text: (optional) The text of the element. - :param list[TypeLabelComparison] types: (optional) Description of the + :param List[TypeLabelComparison] types: (optional) Description of the action specified by the element and whom it affects. - :param list[CategoryComparison] categories: (optional) List of functional + :param List[CategoryComparison] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :param list[Attribute] attributes: (optional) List of document attributes. + :param List[Attribute] attributes: (optional) List of document attributes. """ self.document_label = document_label self.location = location @@ -6363,7 +6938,7 @@ def __init__(self, self.attributes = attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'UnalignedElement': """Initialize a UnalignedElement object from a json dictionary.""" args = {} valid_keys = [ @@ -6396,7 +6971,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a UnalignedElement 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, 'document_label') and self.document_label is not None: @@ -6413,17 +6993,21 @@ def _to_dict(self): _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict - def __str__(self): + 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 UnalignedElement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'UnalignedElement') -> 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): + def __ne__(self, other: 'UnalignedElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6432,26 +7016,27 @@ class UpdatedLabelsIn(): """ The updated labeling from the input document, accounting for the submitted feedback. - :attr list[TypeLabel] types: Description of the action specified by the element + :attr List[TypeLabel] types: Description of the action specified by the element and whom it affects. - :attr list[Category] categories: List of functional categories into which the + :attr List[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ - def __init__(self, types, categories): + def __init__(self, types: List['TypeLabel'], + categories: List['Category']) -> None: """ Initialize a UpdatedLabelsIn object. - :param list[TypeLabel] types: Description of the action specified by the + :param List[TypeLabel] types: Description of the action specified by the element and whom it affects. - :param list[Category] categories: List of functional categories into which + :param List[Category] categories: List of functional categories into which the element falls; in other words, the subject matter of the element. """ self.types = types self.categories = categories @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsIn': """Initialize a UpdatedLabelsIn object from a json dictionary.""" args = {} valid_keys = ['types', 'categories'] @@ -6478,7 +7063,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a UpdatedLabelsIn 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, 'types') and self.types is not None: @@ -6487,17 +7077,21 @@ def _to_dict(self): _dict['categories'] = [x._to_dict() for x in self.categories] return _dict - def __str__(self): + 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 UpdatedLabelsIn object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'UpdatedLabelsIn') -> 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): + def __ne__(self, other: 'UpdatedLabelsIn') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6506,22 +7100,26 @@ class UpdatedLabelsOut(): """ The updated labeling from the input document, accounting for the submitted feedback. - :attr list[TypeLabel] types: (optional) Description of the action specified by + :attr List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :attr list[Category] categories: (optional) List of functional categories into + :attr List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :attr str modification: (optional) The type of modification the feedback entry in the `updated_labels` array. Possible values are `added`, `not_changed`, and `removed`. """ - def __init__(self, *, types=None, categories=None, modification=None): + def __init__(self, + *, + types: List['TypeLabel'] = None, + categories: List['Category'] = None, + modification: str = None) -> None: """ Initialize a UpdatedLabelsOut object. - :param list[TypeLabel] types: (optional) Description of the action + :param List[TypeLabel] types: (optional) Description of the action specified by the element and whom it affects. - :param list[Category] categories: (optional) List of functional categories + :param List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. :param str modification: (optional) The type of modification the feedback @@ -6533,7 +7131,7 @@ def __init__(self, *, types=None, categories=None, modification=None): self.modification = modification @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsOut': """Initialize a UpdatedLabelsOut object from a json dictionary.""" args = {} valid_keys = ['types', 'categories', 'modification'] @@ -6554,7 +7152,12 @@ def _from_dict(cls, _dict): args['modification'] = _dict.get('modification') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a UpdatedLabelsOut 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, 'types') and self.types is not None: @@ -6565,17 +7168,21 @@ def _to_dict(self): _dict['modification'] = self.modification return _dict - def __str__(self): + 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 UpdatedLabelsOut object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'UpdatedLabelsOut') -> 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): + def __ne__(self, other: 'UpdatedLabelsOut') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6601,7 +7208,11 @@ class Value(): markup. """ - def __init__(self, *, cell_id=None, location=None, text=None): + def __init__(self, + *, + cell_id: str = None, + location: 'Location' = None, + text: str = None) -> None: """ Initialize a Value object. @@ -6617,7 +7228,7 @@ def __init__(self, *, cell_id=None, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Value': """Initialize a Value object from a json dictionary.""" args = {} valid_keys = ['cell_id', 'location', 'text'] @@ -6634,7 +7245,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Value 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, 'cell_id') and self.cell_id is not None: @@ -6645,16 +7261,20 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 Value object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Value') -> 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): + def __ne__(self, other: 'Value') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 640573678..0100cabe8 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -1,577 +1,1045 @@ -# coding: utf-8 -import responses -import ibm_watson +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -import os -import time -import jwt -from unittest import TestCase -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -base_url = "https://gateway.watsonplatform.net/compare-comply/api" -feedback = { - "comment": "test commment", - "user_id": "wonder woman", - "feedback_id": "lala", - "feedback_data": { - "model_id": "contracts", - "original_labels": { - "categories": [ - { - "modification": "unchanged", - "provenance_ids": [], - "label": "Responsibilities" - }, - { - "modification": "removed", - "provenance_ids": [], - "label": "Amendments" - } - ], - "types": [ - { - "modification": "unchanged", - "provenance_ids": [ - "111", - "2222" - ], - "label": { - "party": "IBM", - "nature": "Obligation" - } - }, - { - "modification": "removed", - "provenance_ids": [ - "111", - "2222" - ], - "label": { - "party": "Exclusion", - "nature": "End User" - } - } - ] - }, - "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.", - "feedback_type": "element_classification", - "updated_labels": { - "categories": [ - { - "modification": "unchanged", - "label": "Responsibilities" - }, - { - "modification": "added", - "label": "Audits" - } - ], - "types": [ - { - "modification": "unchanged", - "label": { - "party": "IBM", - "nature": "Obligation" - } - }, - { - "modification": "added", - "label": { - "party": "Buyer", - "nature": "Disclaimer" - } - } - ] - }, - "model_version": "11.00", - "location": { - "begin": "214", - "end": "237" - }, - "document": { - "hash": "", - "title": "doc title" - } - }, - "created": "2018-11-16T22:57:14+0000" -} - - -batch = { - "function": "html_conversion", - "status": "completed", - "updated": "2018-11-12T21:02:43.867+0000", - "document_counts": { - "successful": 4, - "failed": 0, - "total": 4, - "pending": 0 - }, - "created": "2018-11-12T21:02:38.907+0000", - "input_bucket_location": "us-south", - "input_bucket_name": "compare-comply-integration-test-bucket-input", - "batch_id": "xxx", - "output_bucket_name": "compare-comply-integration-test-bucket-output", - "model": "contracts", - "output_bucket_location": "us-south" -} - -def get_access_token(): - access_token_layout = { - "username": "dummy", - "role": "Admin", - "permissions": [ - "administrator", - "manage_catalog" - ], - "sub": "admin", - "iss": "sss", - "aud": "sss", - "uid": "sss", - "iat": 3600, - "exp": int(time.time()) - } - - access_token = jwt.encode(access_token_layout, 'secret', algorithm='HS256', headers={'kid': '230498151c214b788dd97f22b85410a5'}) - return access_token.decode('utf-8') - -class TestCompareComplyV1(TestCase): - - @classmethod - def setUp(cls): - iam_url = "https://iam.cloud.ibm.com/identity/token" - iam_token_response = { - "access_token": get_access_token(), - "token_type": "Bearer", - "expires_in": 3600, - "expiration": 1524167011, - "refresh_token": "jy4gl91BQ" - } - responses.add( - responses.POST, url=iam_url, body=json.dumps(iam_token_response), status=200) - - @responses.activate - def test_convert_to_html(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/html_conversion') - - response = { - "hash": "0d9589556c16fca21c64ce9c8b10d065", - "html": "", - "num_pages": "4", - "publication_date": "2018-11-10", - "title": "Microsoft Word - contract_A.doc" - } - - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - with open( - os.path.join(os.path.dirname(__file__), - '../../resources/contract_A.pdf'), 'rb') as file: - service.convert_to_html( - file, - model_id="contracts", - file_content_type="application/octet-stream") - - assert len(responses.calls) == 2 - - @responses.activate - def test_classify_elements(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/element_classification') - - response = [{ - "text": - "__November 9, 2018______________ date", - "categories": [], - "location": { - "begin": 19373, - "end": 19410 - }, - "types": [], - "attributes": [{ - "text": "November 9, 2018", - "type": "DateTime", - "location": { - "begin": 19375, - "end": 19391 - } - }] - }] - - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), - '../../resources/contract_A.pdf'), 'rb') as file: - service.classify_elements( - file, - model_id="contracts", - file_content_type="application/octet-stream") - - assert len(responses.calls) == 2 - - @responses.activate - def test_extract_tables(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/tables') - - response = { - "model_version": - "0.2.8-SNAPSHOT", - "model_id": - "tables", - "document": { - "hash": "0906a4721a59ffeaf2ec12997aa4f7f7", - "title": "Design and build accessible PDF tables, sample tables" - }, - "tables": [{ - "section_title": { - "text": "Sample tables ", - "location": { - "begin": 2099, - "end": 2113 - } - }, - "text": - "Column header (TH) Column header (TH) Column header (TH) Row header (TH) Data cell (TD) Data cell (TD) Row header(TH) Data cell (TD) Data cell (TD) ", - "table_headers": [], - "row_headers": [], - "location": { - "begin": 2832, - "end": 4801 - }, - "body_cells": [], - }] - } - - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), - '../../resources/sample-tables.pdf'), 'rb') as file: - service.extract_tables(file) - - assert len(responses.calls) == 2 - - @responses.activate - def test_compare_documents(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/comparison') - - response = { - "aligned_elements": [ - { - "element_pair": [{ - "text": - "WITNESSETH: that the Owner and Contractor undertake and agree as follows:", - "types": [], - "document_label": - "file_1", - "attributes": [], - "categories": [], - "location": { - "begin": 3845, - "end": 4085 - } - }, { - "text": - "WITNESSETH: that the Owner and Contractor undertake and agree as follows:", - "types": [], - "document_label": - "file_2", - "attributes": [], - "categories": [], - "location": { - "begin": 3846, - "end": 4086 - } - }], - "provenance_ids": - ["1mSG/96z1wY4De35LAExJzhCo2t0DfvbYnTl+vbavjY="], - }, - ], - "model_id": - "contracts", - "model_version": - "1.0.0" - } - - responses.add( - responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), - '../../resources/contract_A.pdf'), 'rb') as file1: - with open(os.path.join(os.path.dirname(__file__), - '../../resources/contract_B.pdf'), 'rb') as file2: - service.compare_documents(file1, file2) - - assert len(responses.calls) == 2 - - @responses.activate - def test_add_feedback(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/feedback') - - feedback_data = { - "feedback_type": "element_classification", - "document": { - "hash": "", - "title": "doc title" - }, - "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.", - "original_labels": { - "types": [ - { - "label": { - "nature": "Obligation", - "party": "IBM" - }, - "provenance_ids": [ - "85f5981a-ba91-44f5-9efa-0bd22e64b7bc", - "ce0480a1-5ef1-4c3e-9861-3743b5610795" - ] - }, - { - "label": { - "nature": "End User", - "party": "Exclusion" - }, - "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" - } - } - ], - "categories": [ - { - "label": "Responsibilities" - }, - { - "label": "Audits" - } - ] - } - } - - responses.add( - responses.POST, - url, - body=json.dumps(feedback), - status=200, - content_type='application/json') - - result = service.add_feedback( - feedback_data, - user_id="wonder woman", - comment="test commment").get_result() - assert result["feedback_id"] == "lala" - - assert len(responses.calls) == 2 - - @responses.activate - def test_get_feedback(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/feedback/xxx') - - responses.add( - responses.GET, - url, - body=json.dumps(feedback), - status=200, - content_type='application/json') - - result = service.get_feedback("xxx").get_result() - assert result["feedback_id"] == "lala" - - assert len(responses.calls) == 2 - - @responses.activate - def test_list_feedback(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/feedback') - - responses.add( - responses.GET, - url, - body=json.dumps({"feedback":[feedback]}), - status=200, - content_type='application/json') - - result = service.list_feedback().get_result() - assert result["feedback"][0]["feedback_id"] == "lala" - - assert len(responses.calls) == 2 - - @responses.activate - def test_delete_feedback(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/feedback/xxx') - - response = { - "status": 200, - "message": "Successfully deleted the feedback with id - 90ae2cb9-e6c5-43eb-a70f-199959f76019" - } - - responses.add( - responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - result = service.delete_feedback("xxx").get_result() - assert result["status"] == 200 - - assert len(responses.calls) == 2 - - @responses.activate - def test_create_batch(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/batches') +import pytest +import responses +import tempfile +import ibm_watson.compare_comply_v1 +from ibm_watson.compare_comply_v1 import * - responses.add( - responses.POST, - url, - body=json.dumps(batch), - status=200, - content_type='application/json') +base_url = 'https://gateway.watsonplatform.net/compare-comply/api' - with open(os.path.join(os.path.dirname(__file__), - '../../resources/dummy-storage-credentials.json'), 'rb') as input_credentials_file: - with open(os.path.join(os.path.dirname(__file__), - '../../resources/dummy-storage-credentials.json'), 'rb') as output_credentials_file: - result = service.create_batch( - "html_conversion", - input_credentials_file, - "us-south", - "compare-comply-integration-test-bucket-input", - output_credentials_file, - "us-south", - "compare-comply-integration-test-bucket-output").get_result() +############################################################################## +# Start of Service: HTMLConversion +############################################################################## +# region - assert result["batch_id"] == "xxx" - assert len(responses.calls) == 2 +#----------------------------------------------------------------------------- +# Test Class for convert_to_html +#----------------------------------------------------------------------------- +class TestConvertToHtml(): + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_get_batch(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/batches/xxx') - - responses.add( - responses.GET, - url, - body=json.dumps(batch), - status=200, - content_type='application/json') - - result = service.get_batch("xxx").get_result() - assert result["batch_id"] == "xxx" - - assert len(responses.calls) == 2 - + def test_convert_to_html_response(self): + body = self.construct_full_body() + response = fake_response_HTMLReturn_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_batches(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/batches') - - responses.add( - responses.GET, - url, - body=json.dumps({"batches": [batch]}), - status=200, - content_type='application/json') - - result = service.list_batches().get_result() - assert result["batches"][0]["batch_id"] == "xxx" - - assert len(responses.calls) == 2 - + def test_convert_to_html_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_HTMLReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_update_batch(self): - authenticator = IAMAuthenticator('bogusapikey') - service = ibm_watson.CompareComplyV1('2016-10-20', authenticator=authenticator) - - url = "{0}{1}".format(base_url, '/v1/batches/xxx') - - responses.add( - responses.PUT, - url, - body=json.dumps(batch), - status=200, - content_type='application/json') - - result = service.update_batch("xxx", "rescan").get_result() - assert result["batch_id"] == "xxx" - assert len(responses.calls) == 2 + def test_convert_to_html_empty(self): + check_empty_required_params(self, fake_response_HTMLReturn_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/html_conversion' + 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 = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.convert_to_html(**body) + return output + + def construct_full_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + body['file_content_type'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + return body + + +# endregion +############################################################################## +# End of Service: HTMLConversion +############################################################################## + +############################################################################## +# Start of Service: ElementClassification +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for classify_elements +#----------------------------------------------------------------------------- +class TestClassifyElements(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_elements_response(self): + body = self.construct_full_body() + response = fake_response_ClassifyReturn_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_classify_elements_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ClassifyReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_elements_empty(self): + check_empty_required_params(self, fake_response_ClassifyReturn_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/element_classification' + 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 = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.classify_elements(**body) + return output + + def construct_full_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + body['file_content_type'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + return body + + +# endregion +############################################################################## +# End of Service: ElementClassification +############################################################################## + +############################################################################## +# Start of Service: Tables +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for extract_tables +#----------------------------------------------------------------------------- +class TestExtractTables(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_extract_tables_response(self): + body = self.construct_full_body() + response = fake_response_TableReturn_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_extract_tables_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TableReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_extract_tables_empty(self): + check_empty_required_params(self, fake_response_TableReturn_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/tables' + 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 = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.extract_tables(**body) + return output + + def construct_full_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + body['file_content_type'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + return body + + +# endregion +############################################################################## +# End of Service: Tables +############################################################################## + +############################################################################## +# Start of Service: Comparison +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for compare_documents +#----------------------------------------------------------------------------- +class TestCompareDocuments(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_compare_documents_response(self): + body = self.construct_full_body() + response = fake_response_CompareReturn_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_compare_documents_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CompareReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_compare_documents_empty(self): + check_empty_required_params(self, fake_response_CompareReturn_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/comparison' + 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 = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.compare_documents(**body) + return output + + def construct_full_body(self): + body = dict() + body['file_1'] = tempfile.NamedTemporaryFile() + body['file_2'] = tempfile.NamedTemporaryFile() + body['file_1_content_type'] = "string1" + body['file_2_content_type'] = "string1" + body['file_1_label'] = "string1" + body['file_2_label'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['file_1'] = tempfile.NamedTemporaryFile() + body['file_2'] = tempfile.NamedTemporaryFile() + return body + + +# endregion +############################################################################## +# End of Service: Comparison +############################################################################## + +############################################################################## +# Start of Service: Feedback +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for add_feedback +#----------------------------------------------------------------------------- +class TestAddFeedback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_feedback_response(self): + body = self.construct_full_body() + response = fake_response_FeedbackReturn_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_add_feedback_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_FeedbackReturn_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_feedback_empty(self): + check_empty_required_params(self, fake_response_FeedbackReturn_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/feedback' + 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 = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.add_feedback(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_feedback +#----------------------------------------------------------------------------- +class TestListFeedback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_feedback_response(self): + body = self.construct_full_body() + response = fake_response_FeedbackList_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_feedback_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_FeedbackList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_feedback_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/feedback' + 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 = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.list_feedback(**body) + return output + + def construct_full_body(self): + body = dict() + body['feedback_type'] = "string1" + body['before'] = datetime.now().date() + body['after'] = datetime.now().date() + body['document_title'] = "string1" + body['model_id'] = "string1" + body['model_version'] = "string1" + body['category_removed'] = "string1" + body['category_added'] = "string1" + body['category_not_changed'] = "string1" + body['type_removed'] = "string1" + body['type_added'] = "string1" + body['type_not_changed'] = "string1" + body['page_limit'] = 12345 + body['cursor'] = "string1" + body['sort'] = "string1" + body['include_total'] = True + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_feedback +#----------------------------------------------------------------------------- +class TestGetFeedback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_feedback_response(self): + body = self.construct_full_body() + response = fake_response_GetFeedback_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_feedback_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_GetFeedback_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_feedback_empty(self): + check_empty_required_params(self, fake_response_GetFeedback_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/feedback/{0}'.format(body['feedback_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 = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.get_feedback(**body) + return output + + def construct_full_body(self): + body = dict() + body['feedback_id'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['feedback_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_feedback +#----------------------------------------------------------------------------- +class TestDeleteFeedback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_feedback_response(self): + body = self.construct_full_body() + response = fake_response_FeedbackDeleted_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_feedback_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_FeedbackDeleted_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_feedback_empty(self): + check_empty_required_params(self, fake_response_FeedbackDeleted_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/feedback/{0}'.format(body['feedback_id']) + 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='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.delete_feedback(**body) + return output + + def construct_full_body(self): + body = dict() + body['feedback_id'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['feedback_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Feedback +############################################################################## + +############################################################################## +# Start of Service: Batches +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for create_batch +#----------------------------------------------------------------------------- +class TestCreateBatch(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_batch_response(self): + body = self.construct_full_body() + response = fake_response_BatchStatus_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_create_batch_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BatchStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_batch_empty(self): + check_empty_required_params(self, fake_response_BatchStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/batches' + 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 = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.create_batch(**body) + return output + + def construct_full_body(self): + body = dict() + body['function'] = "string1" + body['input_credentials_file'] = tempfile.NamedTemporaryFile() + body['input_bucket_location'] = "string1" + body['input_bucket_name'] = "string1" + body['output_credentials_file'] = tempfile.NamedTemporaryFile() + body['output_bucket_location'] = "string1" + body['output_bucket_name'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['function'] = "string1" + body['input_credentials_file'] = tempfile.NamedTemporaryFile() + body['input_bucket_location'] = "string1" + body['input_bucket_name'] = "string1" + body['output_credentials_file'] = tempfile.NamedTemporaryFile() + body['output_bucket_location'] = "string1" + body['output_bucket_name'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_batches +#----------------------------------------------------------------------------- +class TestListBatches(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_batches_response(self): + body = self.construct_full_body() + response = fake_response_Batches_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_batches_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Batches_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_batches_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/batches' + 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 = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.list_batches(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_batch +#----------------------------------------------------------------------------- +class TestGetBatch(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_batch_response(self): + body = self.construct_full_body() + response = fake_response_BatchStatus_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_batch_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BatchStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_batch_empty(self): + check_empty_required_params(self, fake_response_BatchStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/batches/{0}'.format(body['batch_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 = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.get_batch(**body) + return output + + def construct_full_body(self): + body = dict() + body['batch_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['batch_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_batch +#----------------------------------------------------------------------------- +class TestUpdateBatch(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_batch_response(self): + body = self.construct_full_body() + response = fake_response_BatchStatus_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_batch_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BatchStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_batch_empty(self): + check_empty_required_params(self, fake_response_BatchStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/batches/{0}'.format(body['batch_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version='2018-10-15', + ) + service.set_service_url(base_url) + output = service.update_batch(**body) + return output + + def construct_full_body(self): + body = dict() + body['batch_id'] = "string1" + body['action'] = "string1" + body['model'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['batch_id'] = "string1" + body['action'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Batches +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_HTMLReturn_json = """{"num_pages": "fake_num_pages", "author": "fake_author", "publication_date": "fake_publication_date", "title": "fake_title", "html": "fake_html"}""" +fake_response_ClassifyReturn_json = """{"document": {"title": "fake_title", "html": "fake_html", "hash": "fake_hash", "label": "fake_label"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "elements": [], "effective_dates": [], "contract_amounts": [], "termination_dates": [], "contract_types": [], "contract_terms": [], "payment_terms": [], "contract_currencies": [], "tables": [], "document_structure": {"section_titles": [], "leading_sentences": [], "paragraphs": []}, "parties": []}""" +fake_response_TableReturn_json = """{"document": {"html": "fake_html", "title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "tables": []}""" +fake_response_CompareReturn_json = """{"model_id": "fake_model_id", "model_version": "fake_model_version", "documents": [], "aligned_elements": [], "unaligned_elements": []}""" +fake_response_FeedbackReturn_json = """{"feedback_id": "fake_feedback_id", "user_id": "fake_user_id", "comment": "fake_comment", "created": "2017-05-16T13:56:54.957Z", "feedback_data": {"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "updated_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "pagination": {"refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor", "refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5}}}""" +fake_response_FeedbackList_json = """{"feedback": []}""" +fake_response_GetFeedback_json = """{"feedback_id": "fake_feedback_id", "created": "2017-05-16T13:56:54.957Z", "comment": "fake_comment", "feedback_data": {"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "updated_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "pagination": {"refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor", "refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5}}}""" +fake_response_FeedbackDeleted_json = """{"status": 6, "message": "fake_message"}""" +fake_response_BatchStatus_json = """{"function": "fake_function", "input_bucket_location": "fake_input_bucket_location", "input_bucket_name": "fake_input_bucket_name", "output_bucket_location": "fake_output_bucket_location", "output_bucket_name": "fake_output_bucket_name", "batch_id": "fake_batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Batches_json = """{"batches": []}""" +fake_response_BatchStatus_json = """{"function": "fake_function", "input_bucket_location": "fake_input_bucket_location", "input_bucket_name": "fake_input_bucket_name", "output_bucket_location": "fake_output_bucket_location", "output_bucket_name": "fake_output_bucket_name", "batch_id": "fake_batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_BatchStatus_json = """{"function": "fake_function", "input_bucket_location": "fake_input_bucket_location", "input_bucket_name": "fake_input_bucket_name", "output_bucket_location": "fake_output_bucket_location", "output_bucket_name": "fake_output_bucket_name", "batch_id": "fake_batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" From 2146c308b8ccd5d5e051da0b5fdc4b7dfc650e23 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 14:58:05 -0500 Subject: [PATCH 174/455] refactor(discoveryv1): regenerate discovery v1 with tests --- ibm_watson/discovery_v1.py | 5213 +++++++++++++++++----------- test/unit/test_discovery_v1.py | 5844 +++++++++++++++++++++++++------- 2 files changed, 7903 insertions(+), 3154 deletions(-) diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index eac3e348e..f57693456 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,13 +22,22 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import date +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService 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 import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +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 +from typing import List +from typing import TextIO +import sys ############################################################################## # Service @@ -38,13 +47,15 @@ class DiscoveryV1(BaseService): """The Discovery V1 service.""" - default_service_url = 'https://gateway.watsonplatform.net/discovery/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/discovery/api' + DEFAULT_SERVICE_NAME = 'discovery' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Discovery service. @@ -63,31 +74,25 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('discovery') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('discovery') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Environments ######################### - def create_environment(self, name, *, description=None, size=None, - **kwargs): + def create_environment(self, + name: str, + *, + description: str = None, + size: str = None, + **kwargs) -> 'DetailedResponse': """ Create an environment. @@ -112,7 +117,9 @@ def create_environment(self, name, *, description=None, size=None, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'create_environment') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_environment') headers.update(sdk_headers) params = {'version': self.version} @@ -124,12 +131,13 @@ def create_environment(self, name, *, description=None, size=None, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_environments(self, *, name=None, **kwargs): + def list_environments(self, *, name: str = None, + **kwargs) -> 'DetailedResponse': """ List environments. @@ -144,7 +152,9 @@ def list_environments(self, *, name=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'list_environments') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_environments') headers.update(sdk_headers) params = {'version': self.version, 'name': name} @@ -153,12 +163,13 @@ def list_environments(self, *, name=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_environment(self, environment_id, **kwargs): + def get_environment(self, environment_id: str, + **kwargs) -> 'DetailedResponse': """ Get environment info. @@ -174,7 +185,9 @@ def get_environment(self, environment_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'get_environment') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_environment') headers.update(sdk_headers) params = {'version': self.version} @@ -184,18 +197,18 @@ def get_environment(self, environment_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_environment(self, - environment_id, + environment_id: str, *, - name=None, - description=None, - size=None, - **kwargs): + name: str = None, + description: str = None, + size: str = None, + **kwargs) -> 'DetailedResponse': """ Update an environment. @@ -219,7 +232,9 @@ def update_environment(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'update_environment') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_environment') headers.update(sdk_headers) params = {'version': self.version} @@ -232,12 +247,13 @@ def update_environment(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_environment(self, environment_id, **kwargs): + def delete_environment(self, environment_id: str, + **kwargs) -> 'DetailedResponse': """ Delete environment. @@ -253,7 +269,9 @@ def delete_environment(self, environment_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'delete_environment') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_environment') headers.update(sdk_headers) params = {'version': self.version} @@ -263,12 +281,13 @@ def delete_environment(self, environment_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def list_fields(self, environment_id, collection_ids, **kwargs): + def list_fields(self, environment_id: str, collection_ids: List[str], + **kwargs) -> 'DetailedResponse': """ List fields across collections. @@ -276,7 +295,7 @@ def list_fields(self, environment_id, collection_ids, **kwargs): specified collections. :param str environment_id: The ID of the environment. - :param list[str] collection_ids: A comma-separated list of collection IDs + :param List[str] collection_ids: A comma-separated list of collection IDs to be queried against. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -291,7 +310,9 @@ def list_fields(self, environment_id, collection_ids, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'list_fields') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_fields') headers.update(sdk_headers) params = { @@ -304,8 +325,8 @@ def list_fields(self, environment_id, collection_ids, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -313,16 +334,17 @@ def list_fields(self, environment_id, collection_ids, **kwargs): # Configurations ######################### - def create_configuration(self, - environment_id, - name, - *, - description=None, - conversions=None, - enrichments=None, - normalizations=None, - source=None, - **kwargs): + def create_configuration( + self, + environment_id: str, + name: str, + *, + description: str = None, + conversions: 'Conversions' = None, + enrichments: List['Enrichment'] = None, + normalizations: List['NormalizationOperation'] = None, + source: 'Source' = None, + **kwargs) -> 'DetailedResponse': """ Add configuration. @@ -342,9 +364,9 @@ def create_configuration(self, :param str description: (optional) The description of the configuration, if available. :param Conversions conversions: (optional) Document conversion settings. - :param list[Enrichment] enrichments: (optional) An array of document + :param List[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. - :param list[NormalizationOperation] normalizations: (optional) Defines + :param List[NormalizationOperation] normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. @@ -371,7 +393,9 @@ def create_configuration(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'create_configuration') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_configuration') headers.update(sdk_headers) params = {'version': self.version} @@ -391,12 +415,16 @@ def create_configuration(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_configurations(self, environment_id, *, name=None, **kwargs): + def list_configurations(self, + environment_id: str, + *, + name: str = None, + **kwargs) -> 'DetailedResponse': """ List configurations. @@ -415,7 +443,9 @@ def list_configurations(self, environment_id, *, name=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'list_configurations') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_configurations') headers.update(sdk_headers) params = {'version': self.version, 'name': name} @@ -425,12 +455,13 @@ def list_configurations(self, environment_id, *, name=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_configuration(self, environment_id, configuration_id, **kwargs): + def get_configuration(self, environment_id: str, configuration_id: str, + **kwargs) -> 'DetailedResponse': """ Get configuration details. @@ -449,7 +480,9 @@ def get_configuration(self, environment_id, configuration_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'get_configuration') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_configuration') headers.update(sdk_headers) params = {'version': self.version} @@ -459,22 +492,23 @@ def get_configuration(self, environment_id, configuration_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def update_configuration(self, - environment_id, - configuration_id, - name, - *, - description=None, - conversions=None, - enrichments=None, - normalizations=None, - source=None, - **kwargs): + def update_configuration( + self, + environment_id: str, + configuration_id: str, + name: str, + *, + description: str = None, + conversions: 'Conversions' = None, + enrichments: List['Enrichment'] = None, + normalizations: List['NormalizationOperation'] = None, + source: 'Source' = None, + **kwargs) -> 'DetailedResponse': """ Update a configuration. @@ -494,9 +528,9 @@ def update_configuration(self, :param str description: (optional) The description of the configuration, if available. :param Conversions conversions: (optional) Document conversion settings. - :param list[Enrichment] enrichments: (optional) An array of document + :param List[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. - :param list[NormalizationOperation] normalizations: (optional) Defines + :param List[NormalizationOperation] normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. @@ -525,7 +559,9 @@ def update_configuration(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'update_configuration') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_configuration') headers.update(sdk_headers) params = {'version': self.version} @@ -545,12 +581,13 @@ def update_configuration(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_configuration(self, environment_id, configuration_id, **kwargs): + def delete_configuration(self, environment_id: str, configuration_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a configuration. @@ -576,7 +613,9 @@ def delete_configuration(self, environment_id, configuration_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'delete_configuration') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_configuration') headers.update(sdk_headers) params = {'version': self.version} @@ -586,8 +625,8 @@ def delete_configuration(self, environment_id, configuration_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -596,13 +635,13 @@ def delete_configuration(self, environment_id, configuration_id, **kwargs): ######################### def create_collection(self, - environment_id, - name, + environment_id: str, + name: str, *, - description=None, - configuration_id=None, - language=None, - **kwargs): + description: str = None, + configuration_id: str = None, + language: str = None, + **kwargs) -> 'DetailedResponse': """ Create a collection. @@ -626,7 +665,9 @@ def create_collection(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'create_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -644,12 +685,16 @@ def create_collection(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_collections(self, environment_id, *, name=None, **kwargs): + def list_collections(self, + environment_id: str, + *, + name: str = None, + **kwargs) -> 'DetailedResponse': """ List collections. @@ -668,7 +713,9 @@ def list_collections(self, environment_id, *, name=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'list_collections') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_collections') headers.update(sdk_headers) params = {'version': self.version, 'name': name} @@ -678,12 +725,13 @@ def list_collections(self, environment_id, *, name=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_collection(self, environment_id, collection_id, **kwargs): + def get_collection(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Get collection details. @@ -702,7 +750,9 @@ def get_collection(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'get_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -712,19 +762,19 @@ def get_collection(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_collection(self, - environment_id, - collection_id, - name, + environment_id: str, + collection_id: str, + name: str, *, - description=None, - configuration_id=None, - **kwargs): + description: str = None, + configuration_id: str = None, + **kwargs) -> 'DetailedResponse': """ Update a collection. @@ -743,11 +793,15 @@ def update_collection(self, raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') + if name is None: + raise ValueError('name must be provided') headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'update_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -764,12 +818,13 @@ def update_collection(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_collection(self, environment_id, collection_id, **kwargs): + def delete_collection(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a collection. @@ -788,7 +843,9 @@ def delete_collection(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'delete_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -798,12 +855,13 @@ def delete_collection(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def list_collection_fields(self, environment_id, collection_id, **kwargs): + def list_collection_fields(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ List collection fields. @@ -824,8 +882,9 @@ def list_collection_fields(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'list_collection_fields') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_collection_fields') headers.update(sdk_headers) params = {'version': self.version} @@ -835,8 +894,8 @@ def list_collection_fields(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -844,7 +903,8 @@ def list_collection_fields(self, environment_id, collection_id, **kwargs): # Query modifications ######################### - def list_expansions(self, environment_id, collection_id, **kwargs): + def list_expansions(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Get the expansion list. @@ -866,7 +926,9 @@ def list_expansions(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'list_expansions') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_expansions') headers.update(sdk_headers) params = {'version': self.version} @@ -876,13 +938,14 @@ def list_expansions(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def create_expansions(self, environment_id, collection_id, expansions, - **kwargs): + def create_expansions(self, environment_id: str, collection_id: str, + expansions: List['Expansion'], + **kwargs) -> 'DetailedResponse': """ Create or update expansion list. @@ -892,7 +955,7 @@ def create_expansions(self, environment_id, collection_id, expansions, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param list[Expansion] expansions: An array of query expansion definitions. + :param List[Expansion] expansions: An array of query expansion definitions. Each object in the **expansions** array represents a term or set of terms that will be expanded into other terms. Each expansion object can be configured as bidirectional or unidirectional. Bidirectional means that all @@ -921,7 +984,9 @@ def create_expansions(self, environment_id, collection_id, expansions, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'create_expansions') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_expansions') headers.update(sdk_headers) params = {'version': self.version} @@ -934,12 +999,13 @@ def create_expansions(self, environment_id, collection_id, expansions, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_expansions(self, environment_id, collection_id, **kwargs): + def delete_expansions(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete the expansion list. @@ -961,7 +1027,9 @@ def delete_expansions(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'delete_expansions') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_expansions') headers.update(sdk_headers) params = {'version': self.version} @@ -971,13 +1039,14 @@ def delete_expansions(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response - def get_tokenization_dictionary_status(self, environment_id, collection_id, - **kwargs): + def get_tokenization_dictionary_status(self, environment_id: str, + collection_id: str, + **kwargs) -> 'DetailedResponse': """ Get tokenization dictionary status. @@ -999,8 +1068,10 @@ def get_tokenization_dictionary_status(self, environment_id, collection_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'get_tokenization_dictionary_status') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_tokenization_dictionary_status') headers.update(sdk_headers) params = {'version': self.version} @@ -1010,17 +1081,18 @@ def get_tokenization_dictionary_status(self, environment_id, collection_id, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def create_tokenization_dictionary(self, - environment_id, - collection_id, - *, - tokenization_rules=None, - **kwargs): + def create_tokenization_dictionary( + self, + environment_id: str, + collection_id: str, + *, + tokenization_rules: List['TokenDictRule'] = None, + **kwargs) -> 'DetailedResponse': """ Create tokenization dictionary. @@ -1028,7 +1100,7 @@ def create_tokenization_dictionary(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param list[TokenDictRule] tokenization_rules: (optional) An array of + :param List[TokenDictRule] tokenization_rules: (optional) An array of tokenization rules. Each rule contains, the original `text` string, component `tokens`, any alternate character set `readings`, and which `part_of_speech` the text is from. @@ -1049,8 +1121,10 @@ def create_tokenization_dictionary(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'create_tokenization_dictionary') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_tokenization_dictionary') headers.update(sdk_headers) params = {'version': self.version} @@ -1063,13 +1137,14 @@ def create_tokenization_dictionary(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_tokenization_dictionary(self, environment_id, collection_id, - **kwargs): + def delete_tokenization_dictionary(self, environment_id: str, + collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete tokenization dictionary. @@ -1090,8 +1165,10 @@ def delete_tokenization_dictionary(self, environment_id, collection_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'delete_tokenization_dictionary') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_tokenization_dictionary') headers.update(sdk_headers) params = {'version': self.version} @@ -1101,12 +1178,13 @@ def delete_tokenization_dictionary(self, environment_id, collection_id, request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response - def get_stopword_list_status(self, environment_id, collection_id, **kwargs): + def get_stopword_list_status(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Get stopword list status. @@ -1127,8 +1205,9 @@ def get_stopword_list_status(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'get_stopword_list_status') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_stopword_list_status') headers.update(sdk_headers) params = {'version': self.version} @@ -1138,18 +1217,18 @@ def get_stopword_list_status(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_stopword_list(self, - environment_id, - collection_id, - stopword_file, + environment_id: str, + collection_id: str, + stopword_file: BinaryIO, *, - stopword_filename=None, - **kwargs): + stopword_filename: str = None, + **kwargs) -> 'DetailedResponse': """ Create stopword list. @@ -1157,7 +1236,7 @@ def create_stopword_list(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param file stopword_file: The content of the stopword list to ingest. + :param TextIO stopword_file: The content of the stopword list to ingest. :param str stopword_filename: (optional) The filename for stopword_file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1174,7 +1253,9 @@ def create_stopword_list(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'create_stopword_list') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_stopword_list') headers.update(sdk_headers) params = {'version': self.version} @@ -1193,12 +1274,13 @@ def create_stopword_list(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def delete_stopword_list(self, environment_id, collection_id, **kwargs): + def delete_stopword_list(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom stopword list. @@ -1220,7 +1302,9 @@ def delete_stopword_list(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'delete_stopword_list') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_stopword_list') headers.update(sdk_headers) params = {'version': self.version} @@ -1230,8 +1314,8 @@ def delete_stopword_list(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -1240,14 +1324,14 @@ def delete_stopword_list(self, environment_id, collection_id, **kwargs): ######################### def add_document(self, - environment_id, - collection_id, + environment_id: str, + collection_id: str, *, - file=None, - filename=None, - file_content_type=None, - metadata=None, - **kwargs): + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + **kwargs) -> 'DetailedResponse': """ Add a document. @@ -1274,7 +1358,7 @@ def add_document(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param file file: (optional) The content of the document to ingest. The + :param TextIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. @@ -1298,7 +1382,9 @@ def add_document(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'add_document') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_document') headers.update(sdk_headers) params = {'version': self.version} @@ -1312,6 +1398,7 @@ def add_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: + metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) url = '/v1/environments/{0}/collections/{1}/documents'.format( @@ -1320,13 +1407,13 @@ def add_document(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def get_document_status(self, environment_id, collection_id, document_id, - **kwargs): + def get_document_status(self, environment_id: str, collection_id: str, + document_id: str, **kwargs) -> 'DetailedResponse': """ Get document details. @@ -1353,7 +1440,9 @@ def get_document_status(self, environment_id, collection_id, document_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'get_document_status') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_document_status') headers.update(sdk_headers) params = {'version': self.version} @@ -1363,21 +1452,21 @@ def get_document_status(self, environment_id, collection_id, document_id, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_document(self, - environment_id, - collection_id, - document_id, + environment_id: str, + collection_id: str, + document_id: str, *, - file=None, - filename=None, - file_content_type=None, - metadata=None, - **kwargs): + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + **kwargs) -> 'DetailedResponse': """ Update a document. @@ -1389,7 +1478,7 @@ def update_document(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param file file: (optional) The content of the document to ingest. The + :param TextIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. @@ -1415,7 +1504,9 @@ def update_document(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'update_document') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_document') headers.update(sdk_headers) params = {'version': self.version} @@ -1429,6 +1520,7 @@ def update_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: + metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( @@ -1437,13 +1529,13 @@ def update_document(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def delete_document(self, environment_id, collection_id, document_id, - **kwargs): + def delete_document(self, environment_id: str, collection_id: str, + document_id: str, **kwargs) -> 'DetailedResponse': """ Delete a document. @@ -1469,7 +1561,9 @@ def delete_document(self, environment_id, collection_id, document_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'delete_document') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_document') headers.update(sdk_headers) params = {'version': self.version} @@ -1479,8 +1573,8 @@ def delete_document(self, environment_id, collection_id, document_id, request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -1489,31 +1583,31 @@ def delete_document(self, environment_id, collection_id, document_id, ######################### def query(self, - environment_id, - collection_id, + environment_id: str, + collection_id: str, *, - filter=None, - query=None, - natural_language_query=None, - passages=None, - aggregation=None, - count=None, - return_=None, - offset=None, - sort=None, - highlight=None, - passages_fields=None, - passages_count=None, - passages_characters=None, - deduplicate=None, - deduplicate_field=None, - similar=None, - similar_document_ids=None, - similar_fields=None, - bias=None, - spelling_suggestions=None, - x_watson_logging_opt_out=None, - **kwargs): + filter: str = None, + query: str = None, + natural_language_query: str = None, + passages: bool = None, + aggregation: str = None, + count: int = None, + return_: str = None, + offset: int = None, + sort: str = None, + highlight: bool = None, + passages_fields: str = None, + passages_count: int = None, + passages_characters: int = None, + deduplicate: bool = None, + deduplicate_field: str = None, + similar: bool = None, + similar_document_ids: str = None, + similar_fields: str = None, + bias: str = None, + spelling_suggestions: bool = None, + x_watson_logging_opt_out: bool = None, + **kwargs) -> 'DetailedResponse': """ Query a collection. @@ -1610,7 +1704,9 @@ def query(self, headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'query') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='query') headers.update(sdk_headers) params = {'version': self.version} @@ -1644,33 +1740,33 @@ def query(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def query_notices(self, - environment_id, - collection_id, + environment_id: str, + collection_id: str, *, - filter=None, - query=None, - natural_language_query=None, - passages=None, - aggregation=None, - count=None, - return_=None, - offset=None, - sort=None, - highlight=None, - passages_fields=None, - passages_count=None, - passages_characters=None, - deduplicate_field=None, - similar=None, - similar_document_ids=None, - similar_fields=None, - **kwargs): + filter: str = None, + query: str = None, + natural_language_query: str = None, + passages: bool = None, + aggregation: str = None, + count: int = None, + return_: List[str] = None, + offset: int = None, + sort: List[str] = None, + highlight: bool = None, + passages_fields: List[str] = None, + passages_count: int = None, + passages_characters: int = None, + deduplicate_field: str = None, + similar: bool = None, + similar_document_ids: List[str] = None, + similar_fields: List[str] = None, + **kwargs) -> 'DetailedResponse': """ Query system notices. @@ -1699,20 +1795,20 @@ def query_notices(self, possible aggregations, see the Query reference. :param int count: (optional) Number of results to return. The maximum for the **count** and **offset** values together in any one query is **10000**. - :param list[str] return_: (optional) A comma-separated list of the portion + :param List[str] return_: (optional) A comma-separated list of the portion of the document hierarchy to return. :param int offset: (optional) The number of query results to skip at the beginning. For example, if the total number of results that are returned is 10 and the offset is 8, it returns the last two results. The maximum for the **count** and **offset** values together in any one query is **10000**. - :param list[str] sort: (optional) A comma-separated list of fields in the + :param List[str] sort: (optional) A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. :param bool highlight: (optional) When true, a highlight field is returned for each result which contains the fields which match the query with `` tags around the matching query terms. - :param list[str] passages_fields: (optional) A comma-separated list of + :param List[str] passages_fields: (optional) A comma-separated list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. :param int passages_count: (optional) The maximum number of passages to @@ -1727,13 +1823,13 @@ def query_notices(self, :param bool similar: (optional) When `true`, results are returned based on their similarity to the document IDs specified in the **similar.document_ids** parameter. - :param list[str] similar_document_ids: (optional) A comma-separated list of + :param List[str] similar_document_ids: (optional) A comma-separated list of document IDs to find similar documents. **Tip:** Include the **natural_language_query** parameter to expand the scope of the document similarity search with the natural language query. Other query parameters, such as **filter** and **query**, are subsequently applied and reduce the scope. - :param list[str] similar_fields: (optional) A comma-separated list of field + :param List[str] similar_fields: (optional) A comma-separated list of field names that are used as a basis for comparison to identify similar documents. If not specified, the entire document is used for comparison. :param dict headers: A `dict` containing the request headers @@ -1749,7 +1845,9 @@ def query_notices(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'query_notices') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='query_notices') headers.update(sdk_headers) params = { @@ -1778,36 +1876,36 @@ def query_notices(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def federated_query(self, - environment_id, - collection_ids, + environment_id: str, + collection_ids: str, *, - filter=None, - query=None, - natural_language_query=None, - passages=None, - aggregation=None, - count=None, - return_=None, - offset=None, - sort=None, - highlight=None, - passages_fields=None, - passages_count=None, - passages_characters=None, - deduplicate=None, - deduplicate_field=None, - similar=None, - similar_document_ids=None, - similar_fields=None, - bias=None, - x_watson_logging_opt_out=None, - **kwargs): + filter: str = None, + query: str = None, + natural_language_query: str = None, + passages: bool = None, + aggregation: str = None, + count: int = None, + return_: str = None, + offset: int = None, + sort: str = None, + highlight: bool = None, + passages_fields: str = None, + passages_count: int = None, + passages_characters: int = None, + deduplicate: bool = None, + deduplicate_field: str = None, + similar: bool = None, + similar_document_ids: str = None, + similar_fields: str = None, + bias: str = None, + x_watson_logging_opt_out: bool = None, + **kwargs) -> 'DetailedResponse': """ Query multiple collections. @@ -1893,11 +1991,15 @@ def federated_query(self, if environment_id is None: raise ValueError('environment_id must be provided') + if collection_ids is None: + raise ValueError('collection_ids must be provided') headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'federated_query') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='federated_query') headers.update(sdk_headers) params = {'version': self.version} @@ -1931,29 +2033,29 @@ def federated_query(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def federated_query_notices(self, - environment_id, - collection_ids, + environment_id: str, + collection_ids: List[str], *, - filter=None, - query=None, - natural_language_query=None, - aggregation=None, - count=None, - return_=None, - offset=None, - sort=None, - highlight=None, - deduplicate_field=None, - similar=None, - similar_document_ids=None, - similar_fields=None, - **kwargs): + filter: str = None, + query: str = None, + natural_language_query: str = None, + aggregation: str = None, + count: int = None, + return_: List[str] = None, + offset: int = None, + sort: List[str] = None, + highlight: bool = None, + deduplicate_field: str = None, + similar: bool = None, + similar_document_ids: List[str] = None, + similar_fields: List[str] = None, + **kwargs) -> 'DetailedResponse': """ Query multiple collection system notices. @@ -1964,7 +2066,7 @@ def federated_query_notices(self, for more details on the query language. :param str environment_id: The ID of the environment. - :param list[str] collection_ids: A comma-separated list of collection IDs + :param List[str] collection_ids: A comma-separated list of collection IDs to be queried against. :param str filter: (optional) A cacheable query that excludes documents that don't mention the query content. Filter searches are better for @@ -1981,13 +2083,13 @@ def federated_query_notices(self, possible aggregations, see the Query reference. :param int count: (optional) Number of results to return. The maximum for the **count** and **offset** values together in any one query is **10000**. - :param list[str] return_: (optional) A comma-separated list of the portion + :param List[str] return_: (optional) A comma-separated list of the portion of the document hierarchy to return. :param int offset: (optional) The number of query results to skip at the beginning. For example, if the total number of results that are returned is 10 and the offset is 8, it returns the last two results. The maximum for the **count** and **offset** values together in any one query is **10000**. - :param list[str] sort: (optional) A comma-separated list of fields in the + :param List[str] sort: (optional) A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. @@ -2001,13 +2103,13 @@ def federated_query_notices(self, :param bool similar: (optional) When `true`, results are returned based on their similarity to the document IDs specified in the **similar.document_ids** parameter. - :param list[str] similar_document_ids: (optional) A comma-separated list of + :param List[str] similar_document_ids: (optional) A comma-separated list of document IDs to find similar documents. **Tip:** Include the **natural_language_query** parameter to expand the scope of the document similarity search with the natural language query. Other query parameters, such as **filter** and **query**, are subsequently applied and reduce the scope. - :param list[str] similar_fields: (optional) A comma-separated list of field + :param List[str] similar_fields: (optional) A comma-separated list of field names that are used as a basis for comparison to identify similar documents. If not specified, the entire document is used for comparison. :param dict headers: A `dict` containing the request headers @@ -2023,8 +2125,9 @@ def federated_query_notices(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'federated_query_notices') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='federated_query_notices') headers.update(sdk_headers) params = { @@ -2050,19 +2153,19 @@ def federated_query_notices(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def get_autocompletion(self, - environment_id, - collection_id, - prefix, + environment_id: str, + collection_id: str, + prefix: str, *, - field=None, - count=None, - **kwargs): + field: str = None, + count: int = None, + **kwargs) -> 'DetailedResponse': """ Get Autocomplete Suggestions. @@ -2094,7 +2197,9 @@ def get_autocompletion(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'get_autocompletion') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_autocompletion') headers.update(sdk_headers) params = { @@ -2109,8 +2214,8 @@ def get_autocompletion(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2118,7 +2223,8 @@ def get_autocompletion(self, # Training data ######################### - def list_training_data(self, environment_id, collection_id, **kwargs): + def list_training_data(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ List training data. @@ -2139,7 +2245,9 @@ def list_training_data(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'list_training_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_training_data') headers.update(sdk_headers) params = {'version': self.version} @@ -2149,19 +2257,19 @@ def list_training_data(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def add_training_data(self, - environment_id, - collection_id, + environment_id: str, + collection_id: str, *, - natural_language_query=None, - filter=None, - examples=None, - **kwargs): + natural_language_query: str = None, + filter: str = None, + examples: List['TrainingExample'] = None, + **kwargs) -> 'DetailedResponse': """ Add query to training data. @@ -2174,7 +2282,7 @@ def add_training_data(self, the new training query. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :param list[TrainingExample] examples: (optional) Array of training + :param List[TrainingExample] examples: (optional) Array of training examples. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -2191,7 +2299,9 @@ def add_training_data(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'add_training_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_training_data') headers.update(sdk_headers) params = {'version': self.version} @@ -2208,12 +2318,13 @@ def add_training_data(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_all_training_data(self, environment_id, collection_id, **kwargs): + def delete_all_training_data(self, environment_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete all training data. @@ -2234,8 +2345,9 @@ def delete_all_training_data(self, environment_id, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'delete_all_training_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_all_training_data') headers.update(sdk_headers) params = {'version': self.version} @@ -2245,13 +2357,13 @@ def delete_all_training_data(self, environment_id, collection_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response - def get_training_data(self, environment_id, collection_id, query_id, - **kwargs): + def get_training_data(self, environment_id: str, collection_id: str, + query_id: str, **kwargs) -> 'DetailedResponse': """ Get details about a query. @@ -2276,7 +2388,9 @@ def get_training_data(self, environment_id, collection_id, query_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'get_training_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_training_data') headers.update(sdk_headers) params = {'version': self.version} @@ -2286,13 +2400,13 @@ def get_training_data(self, environment_id, collection_id, query_id, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_training_data(self, environment_id, collection_id, query_id, - **kwargs): + def delete_training_data(self, environment_id: str, collection_id: str, + query_id: str, **kwargs) -> 'DetailedResponse': """ Delete a training data query. @@ -2317,7 +2431,9 @@ def delete_training_data(self, environment_id, collection_id, query_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'delete_training_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_training_data') headers.update(sdk_headers) params = {'version': self.version} @@ -2327,13 +2443,13 @@ def delete_training_data(self, environment_id, collection_id, query_id, request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response - def list_training_examples(self, environment_id, collection_id, query_id, - **kwargs): + def list_training_examples(self, environment_id: str, collection_id: str, + query_id: str, **kwargs) -> 'DetailedResponse': """ List examples for a training data query. @@ -2357,8 +2473,9 @@ def list_training_examples(self, environment_id, collection_id, query_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'list_training_examples') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_training_examples') headers.update(sdk_headers) params = {'version': self.version} @@ -2368,20 +2485,20 @@ def list_training_examples(self, environment_id, collection_id, query_id, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_training_example(self, - environment_id, - collection_id, - query_id, + environment_id: str, + collection_id: str, + query_id: str, *, - document_id=None, - cross_reference=None, - relevance=None, - **kwargs): + document_id: str = None, + cross_reference: str = None, + relevance: int = None, + **kwargs) -> 'DetailedResponse': """ Add example to training data query. @@ -2410,8 +2527,9 @@ def create_training_example(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'create_training_example') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_training_example') headers.update(sdk_headers) params = {'version': self.version} @@ -2428,13 +2546,14 @@ def create_training_example(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_training_example(self, environment_id, collection_id, query_id, - example_id, **kwargs): + def delete_training_example(self, environment_id: str, collection_id: str, + query_id: str, example_id: str, + **kwargs) -> 'DetailedResponse': """ Delete example for training data query. @@ -2461,8 +2580,9 @@ def delete_training_example(self, environment_id, collection_id, query_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'delete_training_example') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_training_example') headers.update(sdk_headers) params = {'version': self.version} @@ -2473,20 +2593,20 @@ def delete_training_example(self, environment_id, collection_id, query_id, request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response def update_training_example(self, - environment_id, - collection_id, - query_id, - example_id, + environment_id: str, + collection_id: str, + query_id: str, + example_id: str, *, - cross_reference=None, - relevance=None, - **kwargs): + cross_reference: str = None, + relevance: int = None, + **kwargs) -> 'DetailedResponse': """ Change label or cross reference for example. @@ -2515,8 +2635,9 @@ def update_training_example(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'update_training_example') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_training_example') headers.update(sdk_headers) params = {'version': self.version} @@ -2530,13 +2651,14 @@ def update_training_example(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_training_example(self, environment_id, collection_id, query_id, - example_id, **kwargs): + def get_training_example(self, environment_id: str, collection_id: str, + query_id: str, example_id: str, + **kwargs) -> 'DetailedResponse': """ Get details for training data example. @@ -2563,7 +2685,9 @@ def get_training_example(self, environment_id, collection_id, query_id, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'get_training_example') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_training_example') headers.update(sdk_headers) params = {'version': self.version} @@ -2574,8 +2698,8 @@ def get_training_example(self, environment_id, collection_id, query_id, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2583,7 +2707,8 @@ def get_training_example(self, environment_id, collection_id, query_id, # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -2607,7 +2732,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'delete_user_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data') headers.update(sdk_headers) params = {'version': self.version, 'customer_id': customer_id} @@ -2616,8 +2743,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -2625,13 +2752,14 @@ def delete_user_data(self, customer_id, **kwargs): # Events and feedback ######################### - def create_event(self, type, data, **kwargs): + def create_event(self, type: str, data: 'EventData', + **kwargs) -> 'DetailedResponse': """ Create event. The **Events** API can be used to create log entries that are associated with specific queries. For example, you can record which documents in the results set - were "clicked" by a user and when that click occured. + were "clicked" by a user and when that click occurred. :param str type: The event type to be created. :param EventData data: Query event data object. @@ -2649,7 +2777,9 @@ def create_event(self, type, data, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'create_event') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_event') headers.update(sdk_headers) params = {'version': self.version} @@ -2661,19 +2791,19 @@ def create_event(self, type, data, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def query_log(self, *, - filter=None, - query=None, - count=None, - offset=None, - sort=None, - **kwargs): + filter: str = None, + query: str = None, + count: int = None, + offset: int = None, + sort: List[str] = None, + **kwargs) -> 'DetailedResponse': """ Search the query and event log. @@ -2693,7 +2823,7 @@ def query_log(self, beginning. For example, if the total number of results that are returned is 10 and the offset is 8, it returns the last two results. The maximum for the **count** and **offset** values together in any one query is **10000**. - :param list[str] sort: (optional) A comma-separated list of fields in the + :param List[str] sort: (optional) A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending is the default sort direction if no prefix is specified. @@ -2705,7 +2835,9 @@ def query_log(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'query_log') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='query_log') headers.update(sdk_headers) params = { @@ -2721,17 +2853,17 @@ def query_log(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def get_metrics_query(self, *, - start_time=None, - end_time=None, - result_type=None, - **kwargs): + start_time: datetime = None, + end_time: datetime = None, + result_type: str = None, + **kwargs) -> 'DetailedResponse': """ Number of queries over time. @@ -2752,7 +2884,9 @@ def get_metrics_query(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'get_metrics_query') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_query') headers.update(sdk_headers) params = { @@ -2766,17 +2900,17 @@ def get_metrics_query(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def get_metrics_query_event(self, *, - start_time=None, - end_time=None, - result_type=None, - **kwargs): + start_time: datetime = None, + end_time: datetime = None, + result_type: str = None, + **kwargs) -> 'DetailedResponse': """ Number of queries with an event over time. @@ -2798,8 +2932,9 @@ def get_metrics_query_event(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'get_metrics_query_event') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_query_event') headers.update(sdk_headers) params = { @@ -2813,17 +2948,17 @@ def get_metrics_query_event(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def get_metrics_query_no_results(self, *, - start_time=None, - end_time=None, - result_type=None, - **kwargs): + start_time: datetime = None, + end_time: datetime = None, + result_type: str = None, + **kwargs) -> 'DetailedResponse': """ Number of queries with no search results over time. @@ -2844,8 +2979,10 @@ def get_metrics_query_no_results(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'get_metrics_query_no_results') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_query_no_results') headers.update(sdk_headers) params = { @@ -2859,17 +2996,17 @@ def get_metrics_query_no_results(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def get_metrics_event_rate(self, *, - start_time=None, - end_time=None, - result_type=None, - **kwargs): + start_time: datetime = None, + end_time: datetime = None, + result_type: str = None, + **kwargs) -> 'DetailedResponse': """ Percentage of queries with an associated event. @@ -2891,8 +3028,9 @@ def get_metrics_event_rate(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'get_metrics_event_rate') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_event_rate') headers.update(sdk_headers) params = { @@ -2906,12 +3044,13 @@ def get_metrics_event_rate(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_metrics_query_token_event(self, *, count=None, **kwargs): + def get_metrics_query_token_event(self, *, count: int = None, + **kwargs) -> 'DetailedResponse': """ Most frequent query tokens with an event. @@ -2930,8 +3069,10 @@ def get_metrics_query_token_event(self, *, count=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', - 'get_metrics_query_token_event') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_query_token_event') headers.update(sdk_headers) params = {'version': self.version, 'count': count} @@ -2940,8 +3081,8 @@ def get_metrics_query_token_event(self, *, count=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2949,7 +3090,8 @@ def get_metrics_query_token_event(self, *, count=None, **kwargs): # Credentials ######################### - def list_credentials(self, environment_id, **kwargs): + def list_credentials(self, environment_id: str, + **kwargs) -> 'DetailedResponse': """ List credentials. @@ -2969,7 +3111,9 @@ def list_credentials(self, environment_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'list_credentials') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_credentials') headers.update(sdk_headers) params = {'version': self.version} @@ -2979,18 +3123,18 @@ def list_credentials(self, environment_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_credentials(self, - environment_id, + environment_id: str, *, - source_type=None, - credential_details=None, - status=None, - **kwargs): + source_type: str = None, + credential_details: 'CredentialDetails' = None, + status: str = None, + **kwargs) -> 'DetailedResponse': """ Create credentials. @@ -3032,7 +3176,9 @@ def create_credentials(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'create_credentials') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_credentials') headers.update(sdk_headers) params = {'version': self.version} @@ -3049,12 +3195,13 @@ def create_credentials(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_credentials(self, environment_id, credential_id, **kwargs): + def get_credentials(self, environment_id: str, credential_id: str, + **kwargs) -> 'DetailedResponse': """ View Credentials. @@ -3078,7 +3225,9 @@ def get_credentials(self, environment_id, credential_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'get_credentials') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_credentials') headers.update(sdk_headers) params = {'version': self.version} @@ -3088,19 +3237,19 @@ def get_credentials(self, environment_id, credential_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_credentials(self, - environment_id, - credential_id, + environment_id: str, + credential_id: str, *, - source_type=None, - credential_details=None, - status=None, - **kwargs): + source_type: str = None, + credential_details: 'CredentialDetails' = None, + status: str = None, + **kwargs) -> 'DetailedResponse': """ Update credentials. @@ -3145,7 +3294,9 @@ def update_credentials(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'update_credentials') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_credentials') headers.update(sdk_headers) params = {'version': self.version} @@ -3162,12 +3313,13 @@ def update_credentials(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_credentials(self, environment_id, credential_id, **kwargs): + def delete_credentials(self, environment_id: str, credential_id: str, + **kwargs) -> 'DetailedResponse': """ Delete credentials. @@ -3189,7 +3341,9 @@ def delete_credentials(self, environment_id, credential_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'delete_credentials') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_credentials') headers.update(sdk_headers) params = {'version': self.version} @@ -3199,8 +3353,8 @@ def delete_credentials(self, environment_id, credential_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -3208,7 +3362,8 @@ def delete_credentials(self, environment_id, credential_id, **kwargs): # gatewayConfiguration ######################### - def list_gateways(self, environment_id, **kwargs): + def list_gateways(self, environment_id: str, + **kwargs) -> 'DetailedResponse': """ List Gateways. @@ -3226,7 +3381,9 @@ def list_gateways(self, environment_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'list_gateways') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_gateways') headers.update(sdk_headers) params = {'version': self.version} @@ -3236,12 +3393,13 @@ def list_gateways(self, environment_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def create_gateway(self, environment_id, *, name=None, **kwargs): + def create_gateway(self, environment_id: str, *, name: str = None, + **kwargs) -> 'DetailedResponse': """ Create Gateway. @@ -3260,7 +3418,9 @@ def create_gateway(self, environment_id, *, name=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'create_gateway') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_gateway') headers.update(sdk_headers) params = {'version': self.version} @@ -3273,12 +3433,13 @@ def create_gateway(self, environment_id, *, name=None, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_gateway(self, environment_id, gateway_id, **kwargs): + def get_gateway(self, environment_id: str, gateway_id: str, + **kwargs) -> 'DetailedResponse': """ List Gateway Details. @@ -3299,7 +3460,9 @@ def get_gateway(self, environment_id, gateway_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'get_gateway') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_gateway') headers.update(sdk_headers) params = {'version': self.version} @@ -3309,12 +3472,13 @@ def get_gateway(self, environment_id, gateway_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_gateway(self, environment_id, gateway_id, **kwargs): + def delete_gateway(self, environment_id: str, gateway_id: str, + **kwargs) -> 'DetailedResponse': """ Delete Gateway. @@ -3335,7 +3499,9 @@ def delete_gateway(self, environment_id, gateway_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V1', 'delete_gateway') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_gateway') headers.update(sdk_headers) params = {'version': self.version} @@ -3345,8 +3511,8 @@ def delete_gateway(self, environment_id, gateway_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -3426,17 +3592,21 @@ class AggregationResult(): :attr str key: (optional) Key that matched the aggregation type. :attr int matching_results: (optional) Number of matching results. - :attr list[QueryAggregation] aggregations: (optional) Aggregations returned in + :attr List[QueryAggregation] aggregations: (optional) Aggregations returned in the case of chained aggregations. """ - def __init__(self, *, key=None, matching_results=None, aggregations=None): + def __init__(self, + *, + key: str = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None) -> None: """ Initialize a AggregationResult object. :param str key: (optional) Key that matched the aggregation type. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations + :param List[QueryAggregation] aggregations: (optional) Aggregations returned in the case of chained aggregations. """ self.key = key @@ -3444,7 +3614,7 @@ def __init__(self, *, key=None, matching_results=None, aggregations=None): self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AggregationResult': """Initialize a AggregationResult object from a json dictionary.""" args = {} valid_keys = ['key', 'matching_results', 'aggregations'] @@ -3464,7 +3634,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AggregationResult 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, 'key') and self.key is not None: @@ -3476,91 +3651,21 @@ def _to_dict(self): _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): - """Return a `str` version of this AggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Calculation(): - """ - Calculation. - - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr float value: (optional) Value of the aggregation. - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - field=None, - value=None): - """ - Initialize a Calculation object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param float value: (optional) Value of the aggregation. - """ - self.field = field - self.value = value - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Calculation object from a json dictionary.""" - args = {} - valid_keys = ['field', 'value'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Calculation: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'value' in _dict: - args['value'] = _dict.get('value') - return cls(**args) - def _to_dict(self): """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value - return _dict + return self.to_dict() - def __str__(self): - """Return a `str` version of this Calculation object.""" + def __str__(self) -> str: + """Return a `str` version of this AggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AggregationResult') -> 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): + def __ne__(self, other: 'AggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3595,19 +3700,19 @@ class Collection(): def __init__(self, *, - collection_id=None, - name=None, - description=None, - created=None, - updated=None, - status=None, - configuration_id=None, - language=None, - document_counts=None, - disk_usage=None, - training_status=None, - crawl_status=None, - smart_document_understanding=None): + collection_id: str = None, + name: str = None, + description: str = None, + created: datetime = None, + updated: datetime = None, + status: str = None, + configuration_id: str = None, + language: str = None, + document_counts: 'DocumentCounts' = None, + disk_usage: 'CollectionDiskUsage' = None, + training_status: 'TrainingStatus' = None, + crawl_status: 'CollectionCrawlStatus' = None, + smart_document_understanding: 'SduStatus' = None) -> None: """ Initialize a Collection object. @@ -3650,7 +3755,7 @@ def __init__(self, self.smart_document_understanding = smart_document_understanding @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} valid_keys = [ @@ -3697,7 +3802,12 @@ def _from_dict(cls, _dict): _dict.get('smart_document_understanding')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection 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, 'collection_id') and self.collection_id is not None: @@ -3734,17 +3844,21 @@ def _to_dict(self): ) return _dict - def __str__(self): + 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 Collection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Collection') -> 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): + def __ne__(self, other: 'Collection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3765,7 +3879,7 @@ class CollectionCrawlStatus(): status information. """ - def __init__(self, *, source_crawl=None): + def __init__(self, *, source_crawl: 'SourceStatus' = None) -> None: """ Initialize a CollectionCrawlStatus object. @@ -3775,7 +3889,7 @@ def __init__(self, *, source_crawl=None): self.source_crawl = source_crawl @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionCrawlStatus': """Initialize a CollectionCrawlStatus object from a json dictionary.""" args = {} valid_keys = ['source_crawl'] @@ -3789,24 +3903,33 @@ def _from_dict(cls, _dict): _dict.get('source_crawl')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionCrawlStatus 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, 'source_crawl') and self.source_crawl is not None: _dict['source_crawl'] = self.source_crawl._to_dict() return _dict - def __str__(self): + 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 CollectionCrawlStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionCrawlStatus') -> 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): + def __ne__(self, other: 'CollectionCrawlStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3818,7 +3941,7 @@ class CollectionDiskUsage(): :attr int used_bytes: (optional) Number of bytes used by the collection. """ - def __init__(self, *, used_bytes=None): + def __init__(self, *, used_bytes: int = None) -> None: """ Initialize a CollectionDiskUsage object. @@ -3827,7 +3950,7 @@ def __init__(self, *, used_bytes=None): self.used_bytes = used_bytes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionDiskUsage': """Initialize a CollectionDiskUsage object from a json dictionary.""" args = {} valid_keys = ['used_bytes'] @@ -3840,24 +3963,33 @@ def _from_dict(cls, _dict): args['used_bytes'] = _dict.get('used_bytes') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionDiskUsage 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, 'used_bytes') and self.used_bytes is not None: _dict['used_bytes'] = self.used_bytes return _dict - def __str__(self): + 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 CollectionDiskUsage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionDiskUsage') -> 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): + def __ne__(self, other: 'CollectionDiskUsage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3871,7 +4003,8 @@ class CollectionUsage(): environment. """ - def __init__(self, *, available=None, maximum_allowed=None): + def __init__(self, *, available: int = None, + maximum_allowed: int = None) -> None: """ Initialize a CollectionUsage object. @@ -3884,7 +4017,7 @@ def __init__(self, *, available=None, maximum_allowed=None): self.maximum_allowed = maximum_allowed @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionUsage': """Initialize a CollectionUsage object from a json dictionary.""" args = {} valid_keys = ['available', 'maximum_allowed'] @@ -3899,7 +4032,12 @@ def _from_dict(cls, _dict): args['maximum_allowed'] = _dict.get('maximum_allowed') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionUsage 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, 'available') and self.available is not None: @@ -3909,17 +4047,21 @@ def _to_dict(self): _dict['maximum_allowed'] = self.maximum_allowed return _dict - def __str__(self): + 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 CollectionUsage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionUsage') -> 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): + def __ne__(self, other: 'CollectionUsage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3928,21 +4070,21 @@ class Completions(): """ An object containing an array of autocompletion suggestions. - :attr list[str] completions: (optional) Array of autcomplete suggestion based on + :attr List[str] completions: (optional) Array of autcomplete suggestion based on the provided prefix. """ - def __init__(self, *, completions=None): + def __init__(self, *, completions: List[str] = None) -> None: """ Initialize a Completions object. - :param list[str] completions: (optional) Array of autcomplete suggestion + :param List[str] completions: (optional) Array of autcomplete suggestion based on the provided prefix. """ self.completions = completions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Completions': """Initialize a Completions object from a json dictionary.""" args = {} valid_keys = ['completions'] @@ -3955,24 +4097,33 @@ def _from_dict(cls, _dict): args['completions'] = _dict.get('completions') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Completions 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, 'completions') and self.completions is not None: _dict['completions'] = self.completions return _dict - def __str__(self): + 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 Completions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Completions') -> 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): + def __ne__(self, other: 'Completions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3991,9 +4142,9 @@ class Configuration(): :attr str description: (optional) The description of the configuration, if available. :attr Conversions conversions: (optional) Document conversion settings. - :attr list[Enrichment] enrichments: (optional) An array of document enrichment + :attr List[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. - :attr list[NormalizationOperation] normalizations: (optional) Defines operations + :attr List[NormalizationOperation] normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. :attr Source source: (optional) Object containing source parameters for the @@ -4001,16 +4152,16 @@ class Configuration(): """ def __init__(self, - name, + name: str, *, - configuration_id=None, - created=None, - updated=None, - description=None, - conversions=None, - enrichments=None, - normalizations=None, - source=None): + configuration_id: str = None, + created: datetime = None, + updated: datetime = None, + description: str = None, + conversions: 'Conversions' = None, + enrichments: List['Enrichment'] = None, + normalizations: List['NormalizationOperation'] = None, + source: 'Source' = None) -> None: """ Initialize a Configuration object. @@ -4024,9 +4175,9 @@ def __init__(self, :param str description: (optional) The description of the configuration, if available. :param Conversions conversions: (optional) Document conversion settings. - :param list[Enrichment] enrichments: (optional) An array of document + :param List[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. - :param list[NormalizationOperation] normalizations: (optional) Defines + :param List[NormalizationOperation] normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. @@ -4044,7 +4195,7 @@ def __init__(self, self.source = source @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Configuration': """Initialize a Configuration object from a json dictionary.""" args = {} valid_keys = [ @@ -4085,7 +4236,12 @@ def _from_dict(cls, _dict): args['source'] = Source._from_dict(_dict.get('source')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Configuration 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, @@ -4111,17 +4267,21 @@ def _to_dict(self): _dict['source'] = self.source._to_dict() return _dict - def __str__(self): + 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 Configuration object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Configuration') -> 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): + def __ne__(self, other: 'Configuration') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4135,7 +4295,7 @@ class Conversions(): :attr HtmlSettings html: (optional) A list of HTML conversion settings. :attr SegmentSettings segment: (optional) A list of Document Segmentation settings. - :attr list[NormalizationOperation] json_normalizations: (optional) Defines + :attr List[NormalizationOperation] json_normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. :attr bool image_text_recognition: (optional) When `true`, automatic text @@ -4148,12 +4308,12 @@ class Conversions(): def __init__(self, *, - pdf=None, - word=None, - html=None, - segment=None, - json_normalizations=None, - image_text_recognition=None): + pdf: 'PdfSettings' = None, + word: 'WordSettings' = None, + html: 'HtmlSettings' = None, + segment: 'SegmentSettings' = None, + json_normalizations: List['NormalizationOperation'] = None, + image_text_recognition: bool = None) -> None: """ Initialize a Conversions object. @@ -4162,7 +4322,7 @@ def __init__(self, :param HtmlSettings html: (optional) A list of HTML conversion settings. :param SegmentSettings segment: (optional) A list of Document Segmentation settings. - :param list[NormalizationOperation] json_normalizations: (optional) Defines + :param List[NormalizationOperation] json_normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. @@ -4181,7 +4341,7 @@ def __init__(self, self.image_text_recognition = image_text_recognition @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Conversions': """Initialize a Conversions object from a json dictionary.""" args = {} valid_keys = [ @@ -4210,7 +4370,12 @@ def _from_dict(cls, _dict): args['image_text_recognition'] = _dict.get('image_text_recognition') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Conversions 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, 'pdf') and self.pdf is not None: @@ -4232,17 +4397,21 @@ def _to_dict(self): _dict['image_text_recognition'] = self.image_text_recognition return _dict - def __str__(self): + 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 Conversions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Conversions') -> 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): + def __ne__(self, other: 'Conversions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4255,7 +4424,7 @@ class CreateEventResponse(): :attr EventData data: (optional) Query event data object. """ - def __init__(self, *, type=None, data=None): + def __init__(self, *, type: str = None, data: 'EventData' = None) -> None: """ Initialize a CreateEventResponse object. @@ -4266,7 +4435,7 @@ def __init__(self, *, type=None, data=None): self.data = data @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CreateEventResponse': """Initialize a CreateEventResponse object from a json dictionary.""" args = {} valid_keys = ['type', 'data'] @@ -4281,7 +4450,12 @@ def _from_dict(cls, _dict): args['data'] = EventData._from_dict(_dict.get('data')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateEventResponse 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: @@ -4290,17 +4464,21 @@ def _to_dict(self): _dict['data'] = self.data._to_dict() return _dict - def __str__(self): - """Return a `str` version of this CreateEventResponse object.""" + 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 CreateEventResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CreateEventResponse') -> 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): + def __ne__(self, other: 'CreateEventResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4396,25 +4574,25 @@ class CredentialDetails(): def __init__(self, *, - credential_type=None, - client_id=None, - enterprise_id=None, - url=None, - username=None, - organization_url=None, - site_collection_path=None, - client_secret=None, - public_key_id=None, - private_key=None, - passphrase=None, - password=None, - gateway_id=None, - source_version=None, - web_application_url=None, - domain=None, - endpoint=None, - access_key_id=None, - secret_access_key=None): + credential_type: str = None, + client_id: str = None, + enterprise_id: str = None, + url: str = None, + username: str = None, + organization_url: str = None, + site_collection_path: str = None, + client_secret: str = None, + public_key_id: str = None, + private_key: str = None, + passphrase: str = None, + password: str = None, + gateway_id: str = None, + source_version: str = None, + web_application_url: str = None, + domain: str = None, + endpoint: str = None, + access_key_id: str = None, + secret_access_key: str = None) -> None: """ Initialize a CredentialDetails object. @@ -4522,7 +4700,7 @@ def __init__(self, self.secret_access_key = secret_access_key @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CredentialDetails': """Initialize a CredentialDetails object from a json dictionary.""" args = {} valid_keys = [ @@ -4577,7 +4755,12 @@ def _from_dict(cls, _dict): args['secret_access_key'] = _dict.get('secret_access_key') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CredentialDetails 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, @@ -4626,17 +4809,21 @@ def _to_dict(self): _dict['secret_access_key'] = self.secret_access_key return _dict - def __str__(self): + 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 CredentialDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CredentialDetails') -> 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): + def __ne__(self, other: 'CredentialDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4696,10 +4883,10 @@ class Credentials(): def __init__(self, *, - credential_id=None, - source_type=None, - credential_details=None, - status=None): + credential_id: str = None, + source_type: str = None, + credential_details: 'CredentialDetails' = None, + status: str = None) -> None: """ Initialize a Credentials object. @@ -4731,7 +4918,7 @@ def __init__(self, self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Credentials': """Initialize a Credentials object from a json dictionary.""" args = {} valid_keys = [ @@ -4753,7 +4940,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Credentials 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, 'credential_id') and self.credential_id is not None: @@ -4768,17 +4960,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 Credentials object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Credentials') -> 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): + def __ne__(self, other: 'Credentials') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4815,21 +5011,21 @@ class CredentialsList(): """ Object containing array of credential definitions. - :attr list[Credentials] credentials: (optional) An array of credential + :attr List[Credentials] credentials: (optional) An array of credential definitions that were created for this instance. """ - def __init__(self, *, credentials=None): + def __init__(self, *, credentials: List['Credentials'] = None) -> None: """ Initialize a CredentialsList object. - :param list[Credentials] credentials: (optional) An array of credential + :param List[Credentials] credentials: (optional) An array of credential definitions that were created for this instance. """ self.credentials = credentials @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CredentialsList': """Initialize a CredentialsList object from a json dictionary.""" args = {} valid_keys = ['credentials'] @@ -4844,24 +5040,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CredentialsList 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, 'credentials') and self.credentials is not None: _dict['credentials'] = [x._to_dict() for x in self.credentials] return _dict - def __str__(self): + 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 CredentialsList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CredentialsList') -> 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): + def __ne__(self, other: 'CredentialsList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4876,7 +5081,7 @@ class DeleteCollectionResponse(): deletion operation is `deleted`. """ - def __init__(self, collection_id, status): + def __init__(self, collection_id: str, status: str) -> None: """ Initialize a DeleteCollectionResponse object. @@ -4889,7 +5094,7 @@ def __init__(self, collection_id, status): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteCollectionResponse': """Initialize a DeleteCollectionResponse object from a json dictionary.""" args = {} valid_keys = ['collection_id', 'status'] @@ -4912,7 +5117,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteCollectionResponse 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, 'collection_id') and self.collection_id is not None: @@ -4921,17 +5131,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteCollectionResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteCollectionResponse') -> 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): + def __ne__(self, other: 'DeleteCollectionResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4950,17 +5164,21 @@ class DeleteConfigurationResponse(): :attr str configuration_id: The unique identifier for the configuration. :attr str status: Status of the configuration. A deleted configuration has the status deleted. - :attr list[Notice] notices: (optional) An array of notice messages, if any. + :attr List[Notice] notices: (optional) An array of notice messages, if any. """ - def __init__(self, configuration_id, status, *, notices=None): + def __init__(self, + configuration_id: str, + status: str, + *, + notices: List['Notice'] = None) -> None: """ Initialize a DeleteConfigurationResponse object. :param str configuration_id: The unique identifier for the configuration. :param str status: Status of the configuration. A deleted configuration has the status deleted. - :param list[Notice] notices: (optional) An array of notice messages, if + :param List[Notice] notices: (optional) An array of notice messages, if any. """ self.configuration_id = configuration_id @@ -4968,7 +5186,7 @@ def __init__(self, configuration_id, status, *, notices=None): self.notices = notices @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteConfigurationResponse': """Initialize a DeleteConfigurationResponse object from a json dictionary.""" args = {} valid_keys = ['configuration_id', 'status', 'notices'] @@ -4995,7 +5213,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteConfigurationResponse 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, @@ -5007,17 +5230,21 @@ def _to_dict(self): _dict['notices'] = [x._to_dict() for x in self.notices] return _dict - def __str__(self): + 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 DeleteConfigurationResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteConfigurationResponse') -> 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): + def __ne__(self, other: 'DeleteConfigurationResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5037,7 +5264,8 @@ class DeleteCredentials(): :attr str status: (optional) The status of the deletion request. """ - def __init__(self, *, credential_id=None, status=None): + def __init__(self, *, credential_id: str = None, + status: str = None) -> None: """ Initialize a DeleteCredentials object. @@ -5049,7 +5277,7 @@ def __init__(self, *, credential_id=None, status=None): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteCredentials': """Initialize a DeleteCredentials object from a json dictionary.""" args = {} valid_keys = ['credential_id', 'status'] @@ -5064,7 +5292,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteCredentials 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, 'credential_id') and self.credential_id is not None: @@ -5073,17 +5306,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteCredentials object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteCredentials') -> 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): + def __ne__(self, other: 'DeleteCredentials') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5103,7 +5340,7 @@ class DeleteDocumentResponse(): status deleted. """ - def __init__(self, *, document_id=None, status=None): + def __init__(self, *, document_id: str = None, status: str = None) -> None: """ Initialize a DeleteDocumentResponse object. @@ -5115,7 +5352,7 @@ def __init__(self, *, document_id=None, status=None): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} valid_keys = ['document_id', 'status'] @@ -5130,7 +5367,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteDocumentResponse 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, 'document_id') and self.document_id is not None: @@ -5139,17 +5381,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteDocumentResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteDocumentResponse') -> 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): + def __ne__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5168,7 +5414,7 @@ class DeleteEnvironmentResponse(): :attr str status: Status of the environment. """ - def __init__(self, environment_id, status): + def __init__(self, environment_id: str, status: str) -> None: """ Initialize a DeleteEnvironmentResponse object. @@ -5179,7 +5425,7 @@ def __init__(self, environment_id, status): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteEnvironmentResponse': """Initialize a DeleteEnvironmentResponse object from a json dictionary.""" args = {} valid_keys = ['environment_id', 'status'] @@ -5202,7 +5448,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteEnvironmentResponse 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, 'environment_id') and self.environment_id is not None: @@ -5211,17 +5462,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteEnvironmentResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteEnvironmentResponse') -> 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): + def __ne__(self, other: 'DeleteEnvironmentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5242,7 +5497,10 @@ class DiskUsage(): the environment's disk capacity. """ - def __init__(self, *, used_bytes=None, maximum_allowed_bytes=None): + def __init__(self, + *, + used_bytes: int = None, + maximum_allowed_bytes: int = None) -> None: """ Initialize a DiskUsage object. @@ -5255,7 +5513,7 @@ def __init__(self, *, used_bytes=None, maximum_allowed_bytes=None): self.maximum_allowed_bytes = maximum_allowed_bytes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DiskUsage': """Initialize a DiskUsage object from a json dictionary.""" args = {} valid_keys = ['used_bytes', 'maximum_allowed_bytes'] @@ -5270,7 +5528,12 @@ def _from_dict(cls, _dict): args['maximum_allowed_bytes'] = _dict.get('maximum_allowed_bytes') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DiskUsage 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, 'used_bytes') and self.used_bytes is not None: @@ -5280,17 +5543,21 @@ def _to_dict(self): _dict['maximum_allowed_bytes'] = self.maximum_allowed_bytes return _dict - def __str__(self): + 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 DiskUsage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DiskUsage') -> 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): + def __ne__(self, other: 'DiskUsage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5305,11 +5572,15 @@ class DocumentAccepted(): status of `processing` is returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. - :attr list[Notice] notices: (optional) Array of notices produced by the + :attr List[Notice] notices: (optional) Array of notices produced by the document-ingestion process. """ - def __init__(self, *, document_id=None, status=None, notices=None): + def __init__(self, + *, + document_id: str = None, + status: str = None, + notices: List['Notice'] = None) -> None: """ Initialize a DocumentAccepted object. @@ -5319,7 +5590,7 @@ def __init__(self, *, document_id=None, status=None, notices=None): process. A status of `processing` is returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. - :param list[Notice] notices: (optional) Array of notices produced by the + :param List[Notice] notices: (optional) Array of notices produced by the document-ingestion process. """ self.document_id = document_id @@ -5327,7 +5598,7 @@ def __init__(self, *, document_id=None, status=None, notices=None): self.notices = notices @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': """Initialize a DocumentAccepted object from a json dictionary.""" args = {} valid_keys = ['document_id', 'status', 'notices'] @@ -5346,7 +5617,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAccepted 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, 'document_id') and self.document_id is not None: @@ -5357,17 +5633,21 @@ def _to_dict(self): _dict['notices'] = [x._to_dict() for x in self.notices] return _dict - def __str__(self): + 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 DocumentAccepted object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentAccepted') -> 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): + def __ne__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5397,10 +5677,10 @@ class DocumentCounts(): def __init__(self, *, - available=None, - processing=None, - failed=None, - pending=None): + available: int = None, + processing: int = None, + failed: int = None, + pending: int = None) -> None: """ Initialize a DocumentCounts object. @@ -5419,7 +5699,7 @@ def __init__(self, self.pending = pending @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentCounts': """Initialize a DocumentCounts object from a json dictionary.""" args = {} valid_keys = ['available', 'processing', 'failed', 'pending'] @@ -5438,7 +5718,12 @@ def _from_dict(cls, _dict): args['pending'] = _dict.get('pending') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentCounts 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, 'available') and self.available is not None: @@ -5451,17 +5736,21 @@ def _to_dict(self): _dict['pending'] = self.pending return _dict - def __str__(self): + 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 DocumentCounts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentCounts') -> 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): + def __ne__(self, other: 'DocumentCounts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5479,27 +5768,27 @@ class DocumentStatus(): :attr str file_type: (optional) The type of the original source file. :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted as a hexadecimal string). - :attr list[Notice] notices: Array of notices produced by the document-ingestion + :attr List[Notice] notices: Array of notices produced by the document-ingestion process. """ def __init__(self, - document_id, - status, - status_description, - notices, + document_id: str, + status: str, + status_description: str, + notices: List['Notice'], *, - configuration_id=None, - filename=None, - file_type=None, - sha1=None): + configuration_id: str = None, + filename: str = None, + file_type: str = None, + sha1: str = None) -> None: """ Initialize a DocumentStatus object. :param str document_id: The unique identifier of the document. :param str status: Status of the document in the ingestion process. :param str status_description: Description of the document status. - :param list[Notice] notices: Array of notices produced by the + :param List[Notice] notices: Array of notices produced by the document-ingestion process. :param str configuration_id: (optional) The unique identifier for the configuration. @@ -5519,7 +5808,7 @@ def __init__(self, self.notices = notices @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentStatus': """Initialize a DocumentStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -5567,7 +5856,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentStatus 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, 'document_id') and self.document_id is not None: @@ -5591,17 +5885,21 @@ def _to_dict(self): _dict['notices'] = [x._to_dict() for x in self.notices] return _dict - def __str__(self): + 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 DocumentStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentStatus') -> 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): + def __ne__(self, other: 'DocumentStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5657,14 +5955,14 @@ class Enrichment(): """ def __init__(self, - destination_field, - source_field, - enrichment, + destination_field: str, + source_field: str, + enrichment: str, *, - description=None, - overwrite=None, - ignore_downstream_errors=None, - options=None): + description: str = None, + overwrite: bool = None, + ignore_downstream_errors: bool = None, + options: 'EnrichmentOptions' = None) -> None: """ Initialize a Enrichment object. @@ -5702,7 +6000,7 @@ def __init__(self, self.options = options @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Enrichment': """Initialize a Enrichment object from a json dictionary.""" args = {} valid_keys = [ @@ -5743,7 +6041,12 @@ def _from_dict(cls, _dict): args['options'] = EnrichmentOptions._from_dict(_dict.get('options')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Enrichment 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, 'description') and self.description is not None: @@ -5764,17 +6067,21 @@ def _to_dict(self): _dict['options'] = self.options._to_dict() return _dict - def __str__(self): + 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 Enrichment object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Enrichment') -> 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): + def __ne__(self, other: 'Enrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5795,7 +6102,11 @@ class EnrichmentOptions(): element extraction model to use. Models available are: `contract`. """ - def __init__(self, *, features=None, language=None, model=None): + def __init__(self, + *, + features: 'NluEnrichmentFeatures' = None, + language: str = None, + model: str = None) -> None: """ Initialize a EnrichmentOptions object. @@ -5815,7 +6126,7 @@ def __init__(self, *, features=None, language=None, model=None): self.model = model @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} valid_keys = ['features', 'language', 'model'] @@ -5833,7 +6144,12 @@ def _from_dict(cls, _dict): args['model'] = _dict.get('model') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnrichmentOptions 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, 'features') and self.features is not None: @@ -5844,17 +6160,21 @@ def _to_dict(self): _dict['model'] = self.model return _dict - def __str__(self): + 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 EnrichmentOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EnrichmentOptions') -> 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): + def __ne__(self, other: 'EnrichmentOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5906,17 +6226,17 @@ class Environment(): def __init__(self, *, - environment_id=None, - name=None, - description=None, - created=None, - updated=None, - status=None, - read_only=None, - size=None, - requested_size=None, - index_capacity=None, - search_status=None): + environment_id: str = None, + name: str = None, + description: str = None, + created: datetime = None, + updated: datetime = None, + status: str = None, + read_only: bool = None, + size: str = None, + requested_size: str = None, + index_capacity: 'IndexCapacity' = None, + search_status: 'SearchStatus' = None) -> None: """ Initialize a Environment object. @@ -5956,7 +6276,7 @@ def __init__(self, self.search_status = search_status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Environment': """Initialize a Environment object from a json dictionary.""" args = {} valid_keys = [ @@ -5995,7 +6315,12 @@ def _from_dict(cls, _dict): _dict.get('search_status')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Environment 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, 'environment_id') and self.environment_id is not None: @@ -6022,17 +6347,21 @@ def _to_dict(self): _dict['search_status'] = self.search_status._to_dict() return _dict - def __str__(self): + 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 Environment object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Environment') -> 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): + def __ne__(self, other: 'Environment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6072,7 +6401,8 @@ class EnvironmentDocuments(): environment's capacity. """ - def __init__(self, *, indexed=None, maximum_allowed=None): + def __init__(self, *, indexed: int = None, + maximum_allowed: int = None) -> None: """ Initialize a EnvironmentDocuments object. @@ -6085,7 +6415,7 @@ def __init__(self, *, indexed=None, maximum_allowed=None): self.maximum_allowed = maximum_allowed @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EnvironmentDocuments': """Initialize a EnvironmentDocuments object from a json dictionary.""" args = {} valid_keys = ['indexed', 'maximum_allowed'] @@ -6100,7 +6430,12 @@ def _from_dict(cls, _dict): args['maximum_allowed'] = _dict.get('maximum_allowed') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnvironmentDocuments 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, 'indexed') and self.indexed is not None: @@ -6110,17 +6445,21 @@ def _to_dict(self): _dict['maximum_allowed'] = self.maximum_allowed return _dict - def __str__(self): + 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 EnvironmentDocuments object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EnvironmentDocuments') -> 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): + def __ne__(self, other: 'EnvironmentDocuments') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6147,14 +6486,14 @@ class EventData(): """ def __init__(self, - environment_id, - session_token, - collection_id, - document_id, + environment_id: str, + session_token: str, + collection_id: str, + document_id: str, *, - client_timestamp=None, - display_rank=None, - query_id=None): + client_timestamp: datetime = None, + display_rank: int = None, + query_id: str = None) -> None: """ Initialize a EventData object. @@ -6184,7 +6523,7 @@ def __init__(self, self.query_id = query_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EventData': """Initialize a EventData object from a json dictionary.""" args = {} valid_keys = [ @@ -6229,7 +6568,12 @@ def _from_dict(cls, _dict): args['query_id'] = _dict.get('query_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EventData 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, 'environment_id') and self.environment_id is not None: @@ -6250,17 +6594,21 @@ def _to_dict(self): _dict['query_id'] = self.query_id return _dict - def __str__(self): + 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 EventData object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EventData') -> 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): + def __ne__(self, other: 'EventData') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6271,21 +6619,24 @@ class Expansion(): example, you could have expansions for the word `hot` in one object, and expansions for the word `cold` in another. - :attr list[str] input_terms: (optional) A list of terms that will be expanded + :attr List[str] input_terms: (optional) A list of terms that will be expanded for this expansion. If specified, only the items in this list are expanded. - :attr list[str] expanded_terms: A list of terms that this expansion will be + :attr List[str] expanded_terms: A list of terms that this expansion will be expanded to. If specified without **input_terms**, it also functions as the input term list. """ - def __init__(self, expanded_terms, *, input_terms=None): + def __init__(self, + expanded_terms: List[str], + *, + input_terms: List[str] = None) -> None: """ Initialize a Expansion object. - :param list[str] expanded_terms: A list of terms that this expansion will + :param List[str] expanded_terms: A list of terms that this expansion will be expanded to. If specified without **input_terms**, it also functions as the input term list. - :param list[str] input_terms: (optional) A list of terms that will be + :param List[str] input_terms: (optional) A list of terms that will be expanded for this expansion. If specified, only the items in this list are expanded. """ @@ -6293,7 +6644,7 @@ def __init__(self, expanded_terms, *, input_terms=None): self.expanded_terms = expanded_terms @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Expansion': """Initialize a Expansion object from a json dictionary.""" args = {} valid_keys = ['input_terms', 'expanded_terms'] @@ -6312,7 +6663,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Expansion 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, 'input_terms') and self.input_terms is not None: @@ -6321,17 +6677,21 @@ def _to_dict(self): _dict['expanded_terms'] = self.expanded_terms return _dict - def __str__(self): + 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 Expansion object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Expansion') -> 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): + def __ne__(self, other: 'Expansion') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6340,7 +6700,7 @@ class Expansions(): """ The query expansion definitions for the specified collection. - :attr list[Expansion] expansions: An array of query expansion definitions. + :attr List[Expansion] expansions: An array of query expansion definitions. Each object in the **expansions** array represents a term or set of terms that will be expanded into other terms. Each expansion object can be configured as bidirectional or unidirectional. Bidirectional means that all terms are expanded @@ -6355,11 +6715,11 @@ class Expansions(): **expanded_terms** array. """ - def __init__(self, expansions): + def __init__(self, expansions: List['Expansion']) -> None: """ Initialize a Expansions object. - :param list[Expansion] expansions: An array of query expansion definitions. + :param List[Expansion] expansions: An array of query expansion definitions. Each object in the **expansions** array represents a term or set of terms that will be expanded into other terms. Each expansion object can be configured as bidirectional or unidirectional. Bidirectional means that all @@ -6376,7 +6736,7 @@ def __init__(self, expansions): self.expansions = expansions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Expansions': """Initialize a Expansions object from a json dictionary.""" args = {} valid_keys = ['expansions'] @@ -6395,24 +6755,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Expansions 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, 'expansions') and self.expansions is not None: _dict['expansions'] = [x._to_dict() for x in self.expansions] return _dict - def __str__(self): + 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 Expansions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Expansions') -> 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): + def __ne__(self, other: 'Expansions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6425,7 +6794,7 @@ class Field(): :attr str type: (optional) The type of the field. """ - def __init__(self, *, field=None, type=None): + def __init__(self, *, field: str = None, type: str = None) -> None: """ Initialize a Field object. @@ -6436,7 +6805,7 @@ def __init__(self, *, field=None, type=None): self.type = type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Field': """Initialize a Field object from a json dictionary.""" args = {} valid_keys = ['field', 'type'] @@ -6451,7 +6820,12 @@ def _from_dict(cls, _dict): args['type'] = _dict.get('type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Field 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, 'field') and self.field is not None: @@ -6460,17 +6834,21 @@ def _to_dict(self): _dict['type'] = self.type return _dict - def __str__(self): + 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 Field object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Field') -> 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): + def __ne__(self, other: 'Field') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6491,70 +6869,6 @@ class TypeEnum(Enum): BINARY = "binary" -class Filter(): - """ - Filter. - - :attr str match: (optional) The match the aggregated results queried for. - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - match=None): - """ - Initialize a Filter object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str match: (optional) The match the aggregated results queried for. - """ - self.match = match - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Filter object from a json dictionary.""" - args = {} - valid_keys = ['match'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Filter: ' + - ', '.join(bad_keys)) - if 'match' in _dict: - args['match'] = _dict.get('match') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'match') and self.match is not None: - _dict['match'] = self.match - return _dict - - def __str__(self): - """Return a `str` version of this Filter object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class FontSetting(): """ Font matching configuration. @@ -6570,12 +6884,12 @@ class FontSetting(): def __init__(self, *, - level=None, - min_size=None, - max_size=None, - bold=None, - italic=None, - name=None): + level: int = None, + min_size: int = None, + max_size: int = None, + bold: bool = None, + italic: bool = None, + name: str = None) -> None: """ Initialize a FontSetting object. @@ -6597,7 +6911,7 @@ def __init__(self, self.name = name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FontSetting': """Initialize a FontSetting object from a json dictionary.""" args = {} valid_keys = ['level', 'min_size', 'max_size', 'bold', 'italic', 'name'] @@ -6620,7 +6934,12 @@ def _from_dict(cls, _dict): args['name'] = _dict.get('name') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FontSetting 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, 'level') and self.level is not None: @@ -6637,17 +6956,21 @@ def _to_dict(self): _dict['name'] = self.name return _dict - def __str__(self): + 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 FontSetting object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FontSetting') -> 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): + def __ne__(self, other: 'FontSetting') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6669,11 +6992,11 @@ class Gateway(): def __init__(self, *, - gateway_id=None, - name=None, - status=None, - token=None, - token_id=None): + gateway_id: str = None, + name: str = None, + status: str = None, + token: str = None, + token_id: str = None) -> None: """ Initialize a Gateway object. @@ -6695,7 +7018,7 @@ def __init__(self, self.token_id = token_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Gateway': """Initialize a Gateway object from a json dictionary.""" args = {} valid_keys = ['gateway_id', 'name', 'status', 'token', 'token_id'] @@ -6716,7 +7039,12 @@ def _from_dict(cls, _dict): args['token_id'] = _dict.get('token_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Gateway 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, 'gateway_id') and self.gateway_id is not None: @@ -6731,17 +7059,21 @@ def _to_dict(self): _dict['token_id'] = self.token_id return _dict - def __str__(self): + 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 Gateway object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Gateway') -> 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): + def __ne__(self, other: 'Gateway') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6762,7 +7094,7 @@ class GatewayDelete(): :attr str status: (optional) The status of the request. """ - def __init__(self, *, gateway_id=None, status=None): + def __init__(self, *, gateway_id: str = None, status: str = None) -> None: """ Initialize a GatewayDelete object. @@ -6773,7 +7105,7 @@ def __init__(self, *, gateway_id=None, status=None): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'GatewayDelete': """Initialize a GatewayDelete object from a json dictionary.""" args = {} valid_keys = ['gateway_id', 'status'] @@ -6788,7 +7120,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a GatewayDelete 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, 'gateway_id') and self.gateway_id is not None: @@ -6797,17 +7134,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 GatewayDelete object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'GatewayDelete') -> 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): + def __ne__(self, other: 'GatewayDelete') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6816,21 +7157,21 @@ class GatewayList(): """ Object containing gateways array. - :attr list[Gateway] gateways: (optional) Array of configured gateway + :attr List[Gateway] gateways: (optional) Array of configured gateway connections. """ - def __init__(self, *, gateways=None): + def __init__(self, *, gateways: List['Gateway'] = None) -> None: """ Initialize a GatewayList object. - :param list[Gateway] gateways: (optional) Array of configured gateway + :param List[Gateway] gateways: (optional) Array of configured gateway connections. """ self.gateways = gateways @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'GatewayList': """Initialize a GatewayList object from a json dictionary.""" args = {} valid_keys = ['gateways'] @@ -6845,100 +7186,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a GatewayList 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, 'gateways') and self.gateways is not None: _dict['gateways'] = [x._to_dict() for x in self.gateways] return _dict - def __str__(self): - """Return a `str` version of this GatewayList object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Histogram(): - """ - Histogram. - - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr int interval: (optional) Interval of the aggregation. (For 'histogram' - type). - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - field=None, - interval=None): - """ - Initialize a Histogram object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param int interval: (optional) Interval of the aggregation. (For - 'histogram' type). - """ - self.field = field - self.interval = interval - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Histogram object from a json dictionary.""" - args = {} - valid_keys = ['field', 'interval'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Histogram: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - return cls(**args) - def _to_dict(self): """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - return _dict + return self.to_dict() - def __str__(self): - """Return a `str` version of this Histogram object.""" + def __str__(self) -> str: + """Return a `str` version of this GatewayList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'GatewayList') -> 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): + def __ne__(self, other: 'GatewayList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6947,42 +7221,42 @@ class HtmlSettings(): """ A list of HTML conversion settings. - :attr list[str] exclude_tags_completely: (optional) Array of HTML tags that are + :attr List[str] exclude_tags_completely: (optional) Array of HTML tags that are excluded completely. - :attr list[str] exclude_tags_keep_content: (optional) Array of HTML tags which + :attr List[str] exclude_tags_keep_content: (optional) Array of HTML tags which are excluded but still retain content. :attr XPathPatterns keep_content: (optional) Object containing an array of XPaths. :attr XPathPatterns exclude_content: (optional) Object containing an array of XPaths. - :attr list[str] keep_tag_attributes: (optional) An array of HTML tag attributes + :attr List[str] keep_tag_attributes: (optional) An array of HTML tag attributes to keep in the converted document. - :attr list[str] exclude_tag_attributes: (optional) Array of HTML tag attributes + :attr List[str] exclude_tag_attributes: (optional) Array of HTML tag attributes to exclude. """ def __init__(self, *, - exclude_tags_completely=None, - exclude_tags_keep_content=None, - keep_content=None, - exclude_content=None, - keep_tag_attributes=None, - exclude_tag_attributes=None): + exclude_tags_completely: List[str] = None, + exclude_tags_keep_content: List[str] = None, + keep_content: 'XPathPatterns' = None, + exclude_content: 'XPathPatterns' = None, + keep_tag_attributes: List[str] = None, + exclude_tag_attributes: List[str] = None) -> None: """ Initialize a HtmlSettings object. - :param list[str] exclude_tags_completely: (optional) Array of HTML tags + :param List[str] exclude_tags_completely: (optional) Array of HTML tags that are excluded completely. - :param list[str] exclude_tags_keep_content: (optional) Array of HTML tags + :param List[str] exclude_tags_keep_content: (optional) Array of HTML tags which are excluded but still retain content. :param XPathPatterns keep_content: (optional) Object containing an array of XPaths. :param XPathPatterns exclude_content: (optional) Object containing an array of XPaths. - :param list[str] keep_tag_attributes: (optional) An array of HTML tag + :param List[str] keep_tag_attributes: (optional) An array of HTML tag attributes to keep in the converted document. - :param list[str] exclude_tag_attributes: (optional) Array of HTML tag + :param List[str] exclude_tag_attributes: (optional) Array of HTML tag attributes to exclude. """ self.exclude_tags_completely = exclude_tags_completely @@ -6993,7 +7267,7 @@ def __init__(self, self.exclude_tag_attributes = exclude_tag_attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'HtmlSettings': """Initialize a HtmlSettings object from a json dictionary.""" args = {} valid_keys = [ @@ -7024,7 +7298,12 @@ def _from_dict(cls, _dict): args['exclude_tag_attributes'] = _dict.get('exclude_tag_attributes') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a HtmlSettings 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, 'exclude_tags_completely' @@ -7047,17 +7326,21 @@ def _to_dict(self): _dict['exclude_tag_attributes'] = self.exclude_tag_attributes return _dict - def __str__(self): + 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 HtmlSettings object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'HtmlSettings') -> 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): + def __ne__(self, other: 'HtmlSettings') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7074,7 +7357,11 @@ class IndexCapacity(): the environment. """ - def __init__(self, *, documents=None, disk_usage=None, collections=None): + def __init__(self, + *, + documents: 'EnvironmentDocuments' = None, + disk_usage: 'DiskUsage' = None, + collections: 'CollectionUsage' = None) -> None: """ Initialize a IndexCapacity object. @@ -7090,7 +7377,7 @@ def __init__(self, *, documents=None, disk_usage=None, collections=None): self.collections = collections @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IndexCapacity': """Initialize a IndexCapacity object from a json dictionary.""" args = {} valid_keys = ['documents', 'disk_usage', 'collections'] @@ -7109,7 +7396,12 @@ def _from_dict(cls, _dict): _dict.get('collections')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IndexCapacity 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, 'documents') and self.documents is not None: @@ -7120,17 +7412,21 @@ def _to_dict(self): _dict['collections'] = self.collections._to_dict() return _dict - def __str__(self): + 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 IndexCapacity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IndexCapacity') -> 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): + def __ne__(self, other: 'IndexCapacity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7148,21 +7444,21 @@ class ListCollectionFieldsResponse(): `v{N}-fullnews-t3-{YEAR}.mappings` (for example, `v5-fullnews-t3-2016.mappings.text.properties.author`). - :attr list[Field] fields: (optional) An array containing information about each + :attr List[Field] fields: (optional) An array containing information about each field in the collections. """ - def __init__(self, *, fields=None): + def __init__(self, *, fields: List['Field'] = None) -> None: """ Initialize a ListCollectionFieldsResponse object. - :param list[Field] fields: (optional) An array containing information about + :param List[Field] fields: (optional) An array containing information about each field in the collections. """ self.fields = fields @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListCollectionFieldsResponse': """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" args = {} valid_keys = ['fields'] @@ -7177,24 +7473,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListCollectionFieldsResponse 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, 'fields') and self.fields is not None: _dict['fields'] = [x._to_dict() for x in self.fields] return _dict - def __str__(self): + 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 ListCollectionFieldsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListCollectionFieldsResponse') -> 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): + def __ne__(self, other: 'ListCollectionFieldsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7203,21 +7508,21 @@ class ListCollectionsResponse(): """ Response object containing an array of collection details. - :attr list[Collection] collections: (optional) An array containing information + :attr List[Collection] collections: (optional) An array containing information about each collection in the environment. """ - def __init__(self, *, collections=None): + def __init__(self, *, collections: List['Collection'] = None) -> None: """ Initialize a ListCollectionsResponse object. - :param list[Collection] collections: (optional) An array containing + :param List[Collection] collections: (optional) An array containing information about each collection in the environment. """ self.collections = collections @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} valid_keys = ['collections'] @@ -7232,24 +7537,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListCollectionsResponse 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, 'collections') and self.collections is not None: _dict['collections'] = [x._to_dict() for x in self.collections] return _dict - def __str__(self): + 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 ListCollectionsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListCollectionsResponse') -> 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): + def __ne__(self, other: 'ListCollectionsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7258,21 +7572,21 @@ class ListConfigurationsResponse(): """ Object containing an array of available configurations. - :attr list[Configuration] configurations: (optional) An array of configurations + :attr List[Configuration] configurations: (optional) An array of configurations that are available for the service instance. """ - def __init__(self, *, configurations=None): + def __init__(self, *, configurations: List['Configuration'] = None) -> None: """ Initialize a ListConfigurationsResponse object. - :param list[Configuration] configurations: (optional) An array of + :param List[Configuration] configurations: (optional) An array of configurations that are available for the service instance. """ self.configurations = configurations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListConfigurationsResponse': """Initialize a ListConfigurationsResponse object from a json dictionary.""" args = {} valid_keys = ['configurations'] @@ -7288,7 +7602,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListConfigurationsResponse 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, 'configurations') and self.configurations is not None: @@ -7297,17 +7616,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 ListConfigurationsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListConfigurationsResponse') -> 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): + def __ne__(self, other: 'ListConfigurationsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7316,21 +7639,21 @@ class ListEnvironmentsResponse(): """ Response object containing an array of configured environments. - :attr list[Environment] environments: (optional) An array of [environments] that + :attr List[Environment] environments: (optional) An array of [environments] that are available for the service instance. """ - def __init__(self, *, environments=None): + def __init__(self, *, environments: List['Environment'] = None) -> None: """ Initialize a ListEnvironmentsResponse object. - :param list[Environment] environments: (optional) An array of + :param List[Environment] environments: (optional) An array of [environments] that are available for the service instance. """ self.environments = environments @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListEnvironmentsResponse': """Initialize a ListEnvironmentsResponse object from a json dictionary.""" args = {} valid_keys = ['environments'] @@ -7345,24 +7668,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListEnvironmentsResponse 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, 'environments') and self.environments is not None: _dict['environments'] = [x._to_dict() for x in self.environments] return _dict - def __str__(self): + 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 ListEnvironmentsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListEnvironmentsResponse') -> 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): + def __ne__(self, other: 'ListEnvironmentsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7372,23 +7704,26 @@ class LogQueryResponse(): Object containing results that match the requested **logs** query. :attr int matching_results: (optional) Number of matching results. - :attr list[LogQueryResponseResult] results: (optional) Array of log query + :attr List[LogQueryResponseResult] results: (optional) Array of log query response results. """ - def __init__(self, *, matching_results=None, results=None): + def __init__(self, + *, + matching_results: int = None, + results: List['LogQueryResponseResult'] = None) -> None: """ Initialize a LogQueryResponse object. :param int matching_results: (optional) Number of matching results. - :param list[LogQueryResponseResult] results: (optional) Array of log query + :param List[LogQueryResponseResult] results: (optional) Array of log query response results. """ self.matching_results = matching_results self.results = results @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogQueryResponse': """Initialize a LogQueryResponse object from a json dictionary.""" args = {} valid_keys = ['matching_results', 'results'] @@ -7406,7 +7741,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogQueryResponse 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, @@ -7416,17 +7756,21 @@ def _to_dict(self): _dict['results'] = [x._to_dict() for x in self.results] return _dict - def __str__(self): + 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 LogQueryResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogQueryResponse') -> 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): + def __ne__(self, other: 'LogQueryResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7489,20 +7833,20 @@ class LogQueryResponseResult(): def __init__(self, *, - environment_id=None, - customer_id=None, - document_type=None, - natural_language_query=None, - document_results=None, - created_timestamp=None, - client_timestamp=None, - query_id=None, - session_token=None, - collection_id=None, - display_rank=None, - document_id=None, - event_type=None, - result_type=None): + environment_id: str = None, + customer_id: str = None, + document_type: str = None, + natural_language_query: str = None, + document_results: 'LogQueryResponseResultDocuments' = None, + created_timestamp: datetime = None, + client_timestamp: datetime = None, + query_id: str = None, + session_token: str = None, + collection_id: str = None, + display_rank: int = None, + document_id: str = None, + event_type: str = None, + result_type: str = None) -> None: """ Initialize a LogQueryResponseResult object. @@ -7574,7 +7918,7 @@ def __init__(self, self.result_type = result_type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResult': """Initialize a LogQueryResponseResult object from a json dictionary.""" args = {} valid_keys = [ @@ -7622,7 +7966,12 @@ def _from_dict(cls, _dict): args['result_type'] = _dict.get('result_type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogQueryResponseResult 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, 'environment_id') and self.environment_id is not None: @@ -7661,17 +8010,21 @@ def _to_dict(self): _dict['result_type'] = self.result_type return _dict - def __str__(self): + 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 LogQueryResponseResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogQueryResponseResult') -> 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): + def __ne__(self, other: 'LogQueryResponseResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7707,17 +8060,20 @@ class LogQueryResponseResultDocuments(): Object containing result information that was returned by the query used to create this log entry. Only returned with logs of type `query`. - :attr list[LogQueryResponseResultDocumentsResult] results: (optional) Array of + :attr List[LogQueryResponseResultDocumentsResult] results: (optional) Array of log query response results. :attr int count: (optional) The number of results returned in the query associate with this log. """ - def __init__(self, *, results=None, count=None): + def __init__(self, + *, + results: List['LogQueryResponseResultDocumentsResult'] = None, + count: int = None) -> None: """ Initialize a LogQueryResponseResultDocuments object. - :param list[LogQueryResponseResultDocumentsResult] results: (optional) + :param List[LogQueryResponseResultDocumentsResult] results: (optional) Array of log query response results. :param int count: (optional) The number of results returned in the query associate with this log. @@ -7726,7 +8082,7 @@ def __init__(self, *, results=None, count=None): self.count = count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocuments': """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" args = {} valid_keys = ['results', 'count'] @@ -7744,7 +8100,12 @@ def _from_dict(cls, _dict): args['count'] = _dict.get('count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogQueryResponseResultDocuments 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, 'results') and self.results is not None: @@ -7753,17 +8114,21 @@ def _to_dict(self): _dict['count'] = self.count return _dict - def __str__(self): + 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 LogQueryResponseResultDocuments object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogQueryResponseResultDocuments') -> 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): + def __ne__(self, other: 'LogQueryResponseResultDocuments') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7787,11 +8152,11 @@ class LogQueryResponseResultDocumentsResult(): def __init__(self, *, - position=None, - document_id=None, - score=None, - confidence=None, - collection_id=None): + position: int = None, + document_id: str = None, + score: float = None, + confidence: float = None, + collection_id: str = None) -> None: """ Initialize a LogQueryResponseResultDocumentsResult object. @@ -7813,7 +8178,7 @@ def __init__(self, self.collection_id = collection_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocumentsResult': """Initialize a LogQueryResponseResultDocumentsResult object from a json dictionary.""" args = {} valid_keys = [ @@ -7836,7 +8201,12 @@ def _from_dict(cls, _dict): args['collection_id'] = _dict.get('collection_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogQueryResponseResultDocumentsResult 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, 'position') and self.position is not None: @@ -7851,17 +8221,21 @@ def _to_dict(self): _dict['collection_id'] = self.collection_id return _dict - def __str__(self): + 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 LogQueryResponseResultDocumentsResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LogQueryResponseResultDocumentsResult') -> 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): + def __ne__(self, other: 'LogQueryResponseResultDocumentsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7874,11 +8248,15 @@ class MetricAggregation(): intervals are always 1 day (`1d`). :attr str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. - :attr list[MetricAggregationResult] results: (optional) Array of metric + :attr List[MetricAggregationResult] results: (optional) Array of metric aggregation query results. """ - def __init__(self, *, interval=None, event_type=None, results=None): + def __init__(self, + *, + interval: str = None, + event_type: str = None, + results: List['MetricAggregationResult'] = None) -> None: """ Initialize a MetricAggregation object. @@ -7886,7 +8264,7 @@ def __init__(self, *, interval=None, event_type=None, results=None): Metric intervals are always 1 day (`1d`). :param str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. - :param list[MetricAggregationResult] results: (optional) Array of metric + :param List[MetricAggregationResult] results: (optional) Array of metric aggregation query results. """ self.interval = interval @@ -7894,7 +8272,7 @@ def __init__(self, *, interval=None, event_type=None, results=None): self.results = results @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricAggregation': """Initialize a MetricAggregation object from a json dictionary.""" args = {} valid_keys = ['interval', 'event_type', 'results'] @@ -7914,7 +8292,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricAggregation 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, 'interval') and self.interval is not None: @@ -7925,17 +8308,21 @@ def _to_dict(self): _dict['results'] = [x._to_dict() for x in self.results] return _dict - def __str__(self): + 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 MetricAggregation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricAggregation') -> 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): + def __ne__(self, other: 'MetricAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7956,10 +8343,10 @@ class MetricAggregationResult(): def __init__(self, *, - key_as_string=None, - key=None, - matching_results=None, - event_rate=None): + key_as_string: datetime = None, + key: int = None, + matching_results: int = None, + event_rate: float = None) -> None: """ Initialize a MetricAggregationResult object. @@ -7978,7 +8365,7 @@ def __init__(self, self.event_rate = event_rate @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricAggregationResult': """Initialize a MetricAggregationResult object from a json dictionary.""" args = {} valid_keys = ['key_as_string', 'key', 'matching_results', 'event_rate'] @@ -7998,7 +8385,12 @@ def _from_dict(cls, _dict): args['event_rate'] = _dict.get('event_rate') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricAggregationResult 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, 'key_as_string') and self.key_as_string is not None: @@ -8012,17 +8404,21 @@ def _to_dict(self): _dict['event_rate'] = self.event_rate return _dict - def __str__(self): + 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 MetricAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricAggregationResult') -> 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): + def __ne__(self, other: 'MetricAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8031,21 +8427,22 @@ class MetricResponse(): """ The response generated from a call to a **metrics** method. - :attr list[MetricAggregation] aggregations: (optional) Array of metric + :attr List[MetricAggregation] aggregations: (optional) Array of metric aggregations. """ - def __init__(self, *, aggregations=None): + def __init__(self, *, + aggregations: List['MetricAggregation'] = None) -> None: """ Initialize a MetricResponse object. - :param list[MetricAggregation] aggregations: (optional) Array of metric + :param List[MetricAggregation] aggregations: (optional) Array of metric aggregations. """ self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricResponse': """Initialize a MetricResponse object from a json dictionary.""" args = {} valid_keys = ['aggregations'] @@ -8061,24 +8458,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricResponse 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, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): + 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 MetricResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricResponse') -> 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): + def __ne__(self, other: 'MetricResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8089,24 +8495,27 @@ class MetricTokenAggregation(): :attr str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. - :attr list[MetricTokenAggregationResult] results: (optional) Array of results + :attr List[MetricTokenAggregationResult] results: (optional) Array of results for the metric token aggregation. """ - def __init__(self, *, event_type=None, results=None): + def __init__(self, + *, + event_type: str = None, + results: List['MetricTokenAggregationResult'] = None) -> None: """ Initialize a MetricTokenAggregation object. :param str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. - :param list[MetricTokenAggregationResult] results: (optional) Array of + :param List[MetricTokenAggregationResult] results: (optional) Array of results for the metric token aggregation. """ self.event_type = event_type self.results = results @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregation': """Initialize a MetricTokenAggregation object from a json dictionary.""" args = {} valid_keys = ['event_type', 'results'] @@ -8124,7 +8533,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricTokenAggregation 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, 'event_type') and self.event_type is not None: @@ -8133,17 +8547,21 @@ def _to_dict(self): _dict['results'] = [x._to_dict() for x in self.results] return _dict - def __str__(self): + 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 MetricTokenAggregation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricTokenAggregation') -> 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): + def __ne__(self, other: 'MetricTokenAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8160,7 +8578,11 @@ class MetricTokenAggregationResult(): stored in the log for 30 days). """ - def __init__(self, *, key=None, matching_results=None, event_rate=None): + def __init__(self, + *, + key: str = None, + matching_results: int = None, + event_rate: float = None) -> None: """ Initialize a MetricTokenAggregationResult object. @@ -8176,7 +8598,7 @@ def __init__(self, *, key=None, matching_results=None, event_rate=None): self.event_rate = event_rate @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregationResult': """Initialize a MetricTokenAggregationResult object from a json dictionary.""" args = {} valid_keys = ['key', 'matching_results', 'event_rate'] @@ -8193,7 +8615,12 @@ def _from_dict(cls, _dict): args['event_rate'] = _dict.get('event_rate') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricTokenAggregationResult 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, 'key') and self.key is not None: @@ -8205,17 +8632,21 @@ def _to_dict(self): _dict['event_rate'] = self.event_rate return _dict - def __str__(self): + 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 MetricTokenAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricTokenAggregationResult') -> 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): + def __ne__(self, other: 'MetricTokenAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8224,21 +8655,22 @@ class MetricTokenResponse(): """ The response generated from a call to a **metrics** method that evaluates tokens. - :attr list[MetricTokenAggregation] aggregations: (optional) Array of metric + :attr List[MetricTokenAggregation] aggregations: (optional) Array of metric token aggregations. """ - def __init__(self, *, aggregations=None): + def __init__(self, *, + aggregations: List['MetricTokenAggregation'] = None) -> None: """ Initialize a MetricTokenResponse object. - :param list[MetricTokenAggregation] aggregations: (optional) Array of + :param List[MetricTokenAggregation] aggregations: (optional) Array of metric token aggregations. """ self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetricTokenResponse': """Initialize a MetricTokenResponse object from a json dictionary.""" args = {} valid_keys = ['aggregations'] @@ -8254,104 +8686,47 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetricTokenResponse 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, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): + 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 MetricTokenResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetricTokenResponse') -> 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): + def __ne__(self, other: 'MetricTokenResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Nested(): +class NluEnrichmentCategories(): """ - Nested. + An object that indicates the Categories enrichment will be applied to the specified + field. - :attr str path: (optional) The area of the results the aggregation was - restricted to. """ - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - path=None): + def __init__(self, **kwargs) -> None: """ - Initialize a Nested object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str path: (optional) The area of the results the aggregation was - restricted to. - """ - self.path = path - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Nested object from a json dictionary.""" - args = {} - valid_keys = ['path'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Nested: ' + - ', '.join(bad_keys)) - if 'path' in _dict: - args['path'] = _dict.get('path') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path - return _dict - - def __str__(self): - """Return a `str` version of this Nested object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentCategories(): - """ - An object that indicates the Categories enrichment will be applied to the specified - field. - - """ - - def __init__(self, **kwargs): - """ - Initialize a NluEnrichmentCategories object. + Initialize a NluEnrichmentCategories object. :param **kwargs: (optional) Any additional properties. """ @@ -8359,14 +8734,19 @@ def __init__(self, **kwargs): setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentCategories': """Initialize a NluEnrichmentCategories object from a json dictionary.""" args = {} xtra = _dict.copy() args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentCategories 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, '_additionalProperties'): @@ -8376,7 +8756,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {} if not hasattr(self, '_additionalProperties'): super(NluEnrichmentCategories, @@ -8385,17 +8769,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(NluEnrichmentCategories, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this NluEnrichmentCategories object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentCategories') -> 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): + def __ne__(self, other: 'NluEnrichmentCategories') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8408,7 +8792,7 @@ class NluEnrichmentConcepts(): from each instance of the specified field. """ - def __init__(self, *, limit=None): + def __init__(self, *, limit: int = None) -> None: """ Initialize a NluEnrichmentConcepts object. @@ -8418,7 +8802,7 @@ def __init__(self, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentConcepts': """Initialize a NluEnrichmentConcepts object from a json dictionary.""" args = {} valid_keys = ['limit'] @@ -8431,24 +8815,33 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentConcepts 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, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict - def __str__(self): + 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 NluEnrichmentConcepts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentConcepts') -> 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): + def __ne__(self, other: 'NluEnrichmentConcepts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8459,24 +8852,25 @@ class NluEnrichmentEmotion(): :attr bool document: (optional) When `true`, emotion detection is performed on the entire field. - :attr list[str] targets: (optional) A comma-separated list of target strings + :attr List[str] targets: (optional) A comma-separated list of target strings that will have any associated emotions detected. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, *, document: bool = None, + targets: List[str] = None) -> None: """ Initialize a NluEnrichmentEmotion object. :param bool document: (optional) When `true`, emotion detection is performed on the entire field. - :param list[str] targets: (optional) A comma-separated list of target + :param List[str] targets: (optional) A comma-separated list of target strings that will have any associated emotions detected. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEmotion': """Initialize a NluEnrichmentEmotion object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -8491,7 +8885,12 @@ def _from_dict(cls, _dict): args['targets'] = _dict.get('targets') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentEmotion 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, 'document') and self.document is not None: @@ -8500,17 +8899,21 @@ def _to_dict(self): _dict['targets'] = self.targets return _dict - def __str__(self): + 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 NluEnrichmentEmotion object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentEmotion') -> 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): + def __ne__(self, other: 'NluEnrichmentEmotion') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8539,13 +8942,13 @@ class NluEnrichmentEntities(): def __init__(self, *, - sentiment=None, - emotion=None, - limit=None, - mentions=None, - mention_types=None, - sentence_locations=None, - model=None): + sentiment: bool = None, + emotion: bool = None, + limit: int = None, + mentions: bool = None, + mention_types: bool = None, + sentence_locations: bool = None, + model: str = None) -> None: """ Initialize a NluEnrichmentEntities object. @@ -8575,7 +8978,7 @@ def __init__(self, self.model = model @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEntities': """Initialize a NluEnrichmentEntities object from a json dictionary.""" args = {} valid_keys = [ @@ -8603,7 +9006,12 @@ def _from_dict(cls, _dict): args['model'] = _dict.get('model') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentEntities 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, 'sentiment') and self.sentiment is not None: @@ -8624,17 +9032,21 @@ def _to_dict(self): _dict['model'] = self.model return _dict - def __str__(self): + 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 NluEnrichmentEntities object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentEntities') -> 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): + def __ne__(self, other: 'NluEnrichmentEntities') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8663,14 +9075,14 @@ class NluEnrichmentFeatures(): def __init__(self, *, - keywords=None, - entities=None, - sentiment=None, - emotion=None, - categories=None, - semantic_roles=None, - relations=None, - concepts=None): + keywords: 'NluEnrichmentKeywords' = None, + entities: 'NluEnrichmentEntities' = None, + sentiment: 'NluEnrichmentSentiment' = None, + emotion: 'NluEnrichmentEmotion' = None, + categories: 'NluEnrichmentCategories' = None, + semantic_roles: 'NluEnrichmentSemanticRoles' = None, + relations: 'NluEnrichmentRelations' = None, + concepts: 'NluEnrichmentConcepts' = None) -> None: """ Initialize a NluEnrichmentFeatures object. @@ -8701,7 +9113,7 @@ def __init__(self, self.concepts = concepts @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentFeatures': """Initialize a NluEnrichmentFeatures object from a json dictionary.""" args = {} valid_keys = [ @@ -8739,7 +9151,12 @@ def _from_dict(cls, _dict): _dict.get('concepts')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentFeatures 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, 'keywords') and self.keywords is not None: @@ -8760,17 +9177,21 @@ def _to_dict(self): _dict['concepts'] = self.concepts._to_dict() return _dict - def __str__(self): + 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 NluEnrichmentFeatures object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentFeatures') -> 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): + def __ne__(self, other: 'NluEnrichmentFeatures') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8787,7 +9208,11 @@ class NluEnrichmentKeywords(): instance of the specified field. """ - def __init__(self, *, sentiment=None, emotion=None, limit=None): + def __init__(self, + *, + sentiment: bool = None, + emotion: bool = None, + limit: int = None) -> None: """ Initialize a NluEnrichmentKeywords object. @@ -8803,7 +9228,7 @@ def __init__(self, *, sentiment=None, emotion=None, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentKeywords': """Initialize a NluEnrichmentKeywords object from a json dictionary.""" args = {} valid_keys = ['sentiment', 'emotion', 'limit'] @@ -8820,7 +9245,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentKeywords 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, 'sentiment') and self.sentiment is not None: @@ -8831,17 +9261,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 NluEnrichmentKeywords object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentKeywords') -> 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): + def __ne__(self, other: 'NluEnrichmentKeywords') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8856,7 +9290,7 @@ class NluEnrichmentRelations(): model is`en-news`. """ - def __init__(self, *, model=None): + def __init__(self, *, model: str = None) -> None: """ Initialize a NluEnrichmentRelations object. @@ -8868,7 +9302,7 @@ def __init__(self, *, model=None): self.model = model @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentRelations': """Initialize a NluEnrichmentRelations object from a json dictionary.""" args = {} valid_keys = ['model'] @@ -8881,24 +9315,33 @@ def _from_dict(cls, _dict): args['model'] = _dict.get('model') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentRelations 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, 'model') and self.model is not None: _dict['model'] = self.model return _dict - def __str__(self): + 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 NluEnrichmentRelations object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentRelations') -> 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): + def __ne__(self, other: 'NluEnrichmentRelations') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8915,7 +9358,11 @@ class NluEnrichmentSemanticRoles(): extact from each instance of the specified field. """ - def __init__(self, *, entities=None, keywords=None, limit=None): + def __init__(self, + *, + entities: bool = None, + keywords: bool = None, + limit: int = None) -> None: """ Initialize a NluEnrichmentSemanticRoles object. @@ -8931,7 +9378,7 @@ def __init__(self, *, entities=None, keywords=None, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSemanticRoles': """Initialize a NluEnrichmentSemanticRoles object from a json dictionary.""" args = {} valid_keys = ['entities', 'keywords', 'limit'] @@ -8948,7 +9395,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentSemanticRoles 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, 'entities') and self.entities is not None: @@ -8959,17 +9411,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 NluEnrichmentSemanticRoles object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentSemanticRoles') -> 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): + def __ne__(self, other: 'NluEnrichmentSemanticRoles') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -8980,24 +9436,25 @@ class NluEnrichmentSentiment(): :attr bool document: (optional) When `true`, sentiment analysis is performed on the entire field. - :attr list[str] targets: (optional) A comma-separated list of target strings + :attr List[str] targets: (optional) A comma-separated list of target strings that will have any associated sentiment analyzed. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, *, document: bool = None, + targets: List[str] = None) -> None: """ Initialize a NluEnrichmentSentiment object. :param bool document: (optional) When `true`, sentiment analysis is performed on the entire field. - :param list[str] targets: (optional) A comma-separated list of target + :param List[str] targets: (optional) A comma-separated list of target strings that will have any associated sentiment analyzed. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSentiment': """Initialize a NluEnrichmentSentiment object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -9012,7 +9469,12 @@ def _from_dict(cls, _dict): args['targets'] = _dict.get('targets') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NluEnrichmentSentiment 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, 'document') and self.document is not None: @@ -9021,17 +9483,21 @@ def _to_dict(self): _dict['targets'] = self.targets return _dict - def __str__(self): + 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 NluEnrichmentSentiment object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NluEnrichmentSentiment') -> 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): + def __ne__(self, other: 'NluEnrichmentSentiment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9071,9 +9537,9 @@ class NormalizationOperation(): def __init__(self, *, - operation=None, - source_field=None, - destination_field=None): + operation: str = None, + source_field: str = None, + destination_field: str = None) -> None: """ Initialize a NormalizationOperation object. @@ -9113,7 +9579,7 @@ def __init__(self, self.destination_field = destination_field @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'NormalizationOperation': """Initialize a NormalizationOperation object from a json dictionary.""" args = {} valid_keys = ['operation', 'source_field', 'destination_field'] @@ -9130,7 +9596,12 @@ def _from_dict(cls, _dict): args['destination_field'] = _dict.get('destination_field') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a NormalizationOperation 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, 'operation') and self.operation is not None: @@ -9142,17 +9613,21 @@ def _to_dict(self): _dict['destination_field'] = self.destination_field return _dict - def __str__(self): + 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 NormalizationOperation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'NormalizationOperation') -> 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): + def __ne__(self, other: 'NormalizationOperation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9223,13 +9698,13 @@ class Notice(): def __init__(self, *, - notice_id=None, - created=None, - document_id=None, - query_id=None, - severity=None, - step=None, - description=None): + notice_id: str = None, + created: datetime = None, + document_id: str = None, + query_id: str = None, + severity: str = None, + step: str = None, + description: str = None) -> None: """ Initialize a Notice object. @@ -9268,7 +9743,7 @@ def __init__(self, self.description = description @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} valid_keys = [ @@ -9296,7 +9771,12 @@ def _from_dict(cls, _dict): args['description'] = _dict.get('description') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Notice 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, 'notice_id') and self.notice_id is not None: @@ -9315,17 +9795,21 @@ def _to_dict(self): _dict['description'] = self.description return _dict - def __str__(self): + 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 Notice object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Notice') -> 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): + def __ne__(self, other: 'Notice') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9341,20 +9825,20 @@ class PdfHeadingDetection(): """ Object containing heading detection conversion settings for PDF documents. - :attr list[FontSetting] fonts: (optional) Array of font matching configurations. + :attr List[FontSetting] fonts: (optional) Array of font matching configurations. """ - def __init__(self, *, fonts=None): + def __init__(self, *, fonts: List['FontSetting'] = None) -> None: """ Initialize a PdfHeadingDetection object. - :param list[FontSetting] fonts: (optional) Array of font matching + :param List[FontSetting] fonts: (optional) Array of font matching configurations. """ self.fonts = fonts @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'PdfHeadingDetection': """Initialize a PdfHeadingDetection object from a json dictionary.""" args = {} valid_keys = ['fonts'] @@ -9369,24 +9853,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a PdfHeadingDetection 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, 'fonts') and self.fonts is not None: _dict['fonts'] = [x._to_dict() for x in self.fonts] return _dict - def __str__(self): + 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 PdfHeadingDetection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'PdfHeadingDetection') -> 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): + def __ne__(self, other: 'PdfHeadingDetection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9399,7 +9892,7 @@ class PdfSettings(): detection conversion settings for PDF documents. """ - def __init__(self, *, heading=None): + def __init__(self, *, heading: 'PdfHeadingDetection' = None) -> None: """ Initialize a PdfSettings object. @@ -9409,7 +9902,7 @@ def __init__(self, *, heading=None): self.heading = heading @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'PdfSettings': """Initialize a PdfSettings object from a json dictionary.""" args = {} valid_keys = ['heading'] @@ -9423,24 +9916,33 @@ def _from_dict(cls, _dict): _dict.get('heading')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a PdfSettings 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, 'heading') and self.heading is not None: _dict['heading'] = self.heading._to_dict() return _dict - def __str__(self): + 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 PdfSettings object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'PdfSettings') -> 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): + def __ne__(self, other: 'PdfSettings') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9451,27 +9953,27 @@ class QueryAggregation(): :attr str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. - :attr list[AggregationResult] results: (optional) Array of aggregation results. + :attr List[AggregationResult] results: (optional) Array of aggregation results. :attr int matching_results: (optional) Number of matching results. - :attr list[QueryAggregation] aggregations: (optional) Aggregations returned by + :attr List[QueryAggregation] aggregations: (optional) Aggregations returned by Discovery. """ def __init__(self, *, - type=None, - results=None, - matching_results=None, - aggregations=None): + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None) -> None: """ Initialize a QueryAggregation object. :param str type: (optional) The type of aggregation command used. For example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation + :param List[AggregationResult] results: (optional) Array of aggregation results. :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations + :param List[QueryAggregation] aggregations: (optional) Aggregations returned by Discovery. """ self.type = type @@ -9480,8 +9982,11 @@ def __init__(self, self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryAggregation': """Initialize a QueryAggregation object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) args = {} valid_keys = ['type', 'results', 'matching_results', 'aggregations'] bad_keys = set(_dict.keys()) - set(valid_keys) @@ -9504,7 +10009,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregation 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: @@ -9518,31 +10028,63 @@ def _to_dict(self): _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): + 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 QueryAggregation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryAggregation') -> 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): + def __ne__(self, other: 'QueryAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['histogram'] = 'Histogram' + mapping['max'] = 'Calculation' + mapping['min'] = 'Calculation' + mapping['average'] = 'Calculation' + mapping['sum'] = 'Calculation' + mapping['unique_count'] = 'Calculation' + mapping['term'] = 'Term' + mapping['filter'] = 'Filter' + mapping['nested'] = 'Nested' + mapping['timeslice'] = 'Timeslice' + mapping['top_hits'] = 'TopHits' + disc_value = _dict.get('type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'type\' not found in QueryAggregation JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + class QueryNoticesResponse(): """ Object containing notice query results. :attr int matching_results: (optional) The number of matching results. - :attr list[QueryNoticesResult] results: (optional) Array of document results + :attr List[QueryNoticesResult] results: (optional) Array of document results that match the query. - :attr list[QueryAggregation] aggregations: (optional) Array of aggregation + :attr List[QueryAggregation] aggregations: (optional) Array of aggregation results that match the query. - :attr list[QueryPassages] passages: (optional) Array of passage results that + :attr List[QueryPassages] passages: (optional) Array of passage results that match the query. :attr int duplicates_removed: (optional) The number of duplicates removed from this notices query. @@ -9550,20 +10092,20 @@ class QueryNoticesResponse(): def __init__(self, *, - matching_results=None, - results=None, - aggregations=None, - passages=None, - duplicates_removed=None): + matching_results: int = None, + results: List['QueryNoticesResult'] = None, + aggregations: List['QueryAggregation'] = None, + passages: List['QueryPassages'] = None, + duplicates_removed: int = None) -> None: """ Initialize a QueryNoticesResponse object. :param int matching_results: (optional) The number of matching results. - :param list[QueryNoticesResult] results: (optional) Array of document + :param List[QueryNoticesResult] results: (optional) Array of document results that match the query. - :param list[QueryAggregation] aggregations: (optional) Array of aggregation + :param List[QueryAggregation] aggregations: (optional) Array of aggregation results that match the query. - :param list[QueryPassages] passages: (optional) Array of passage results + :param List[QueryPassages] passages: (optional) Array of passage results that match the query. :param int duplicates_removed: (optional) The number of duplicates removed from this notices query. @@ -9575,7 +10117,7 @@ def __init__(self, self.duplicates_removed = duplicates_removed @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} valid_keys = [ @@ -9606,7 +10148,12 @@ def _from_dict(cls, _dict): args['duplicates_removed'] = _dict.get('duplicates_removed') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryNoticesResponse 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, @@ -9624,17 +10171,21 @@ def _to_dict(self): _dict['duplicates_removed'] = self.duplicates_removed return _dict - def __str__(self): + 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 QueryNoticesResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryNoticesResponse') -> 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): + def __ne__(self, other: 'QueryNoticesResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9655,21 +10206,21 @@ class QueryNoticesResult(): :attr str file_type: (optional) The type of the original source file. :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted as a hexadecimal string). - :attr list[Notice] notices: (optional) Array of notices for the document. + :attr List[Notice] notices: (optional) Array of notices for the document. """ def __init__(self, *, - id=None, - metadata=None, - collection_id=None, - result_metadata=None, - code=None, - filename=None, - file_type=None, - sha1=None, - notices=None, - **kwargs): + id: str = None, + metadata: dict = None, + collection_id: str = None, + result_metadata: 'QueryResultMetadata' = None, + code: int = None, + filename: str = None, + file_type: str = None, + sha1: str = None, + notices: List['Notice'] = None, + **kwargs) -> None: """ Initialize a QueryNoticesResult object. @@ -9687,7 +10238,7 @@ def __init__(self, :param str file_type: (optional) The type of the original source file. :param str sha1: (optional) The SHA-1 hash of the original source file (formatted as a hexadecimal string). - :param list[Notice] notices: (optional) Array of notices for the document. + :param List[Notice] notices: (optional) Array of notices for the document. :param **kwargs: (optional) Any additional properties. """ self.id = id @@ -9703,7 +10254,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryNoticesResult': """Initialize a QueryNoticesResult object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -9740,7 +10291,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryNoticesResult 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, 'id') and self.id is not None: @@ -9769,7 +10325,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = { 'id', 'metadata', 'collection_id', 'result_metadata', 'code', 'filename', 'file_type', 'sha1', 'notices' @@ -9781,17 +10341,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(QueryNoticesResult, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this QueryNoticesResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryNoticesResult') -> 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): + def __ne__(self, other: 'QueryNoticesResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9824,12 +10384,12 @@ class QueryPassages(): def __init__(self, *, - document_id=None, - passage_score=None, - passage_text=None, - start_offset=None, - end_offset=None, - field=None): + document_id: str = None, + passage_score: float = None, + passage_text: str = None, + start_offset: int = None, + end_offset: int = None, + field: str = None) -> None: """ Initialize a QueryPassages object. @@ -9853,7 +10413,7 @@ def __init__(self, self.field = field @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryPassages': """Initialize a QueryPassages object from a json dictionary.""" args = {} valid_keys = [ @@ -9879,7 +10439,12 @@ def _from_dict(cls, _dict): args['field'] = _dict.get('field') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryPassages 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, 'document_id') and self.document_id is not None: @@ -9896,17 +10461,21 @@ def _to_dict(self): _dict['field'] = self.field return _dict - def __str__(self): + 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 QueryPassages object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryPassages') -> 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): + def __ne__(self, other: 'QueryPassages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9917,11 +10486,11 @@ class QueryResponse(): :attr int matching_results: (optional) The number of matching results for the query. - :attr list[QueryResult] results: (optional) Array of document results for the + :attr List[QueryResult] results: (optional) Array of document results for the query. - :attr list[QueryAggregation] aggregations: (optional) Array of aggregation + :attr List[QueryAggregation] aggregations: (optional) Array of aggregation results for the query. - :attr list[QueryPassages] passages: (optional) Array of passage results for the + :attr List[QueryPassages] passages: (optional) Array of passage results for the query. :attr int duplicates_removed: (optional) The number of duplicate results removed. @@ -9937,24 +10506,24 @@ class QueryResponse(): def __init__(self, *, - matching_results=None, - results=None, - aggregations=None, - passages=None, - duplicates_removed=None, - session_token=None, - retrieval_details=None, - suggested_query=None): + matching_results: int = None, + results: List['QueryResult'] = None, + aggregations: List['QueryAggregation'] = None, + passages: List['QueryPassages'] = None, + duplicates_removed: int = None, + session_token: str = None, + retrieval_details: 'RetrievalDetails' = None, + suggested_query: str = None) -> None: """ Initialize a QueryResponse object. :param int matching_results: (optional) The number of matching results for the query. - :param list[QueryResult] results: (optional) Array of document results for + :param List[QueryResult] results: (optional) Array of document results for the query. - :param list[QueryAggregation] aggregations: (optional) Array of aggregation + :param List[QueryAggregation] aggregations: (optional) Array of aggregation results for the query. - :param list[QueryPassages] passages: (optional) Array of passage results + :param List[QueryPassages] passages: (optional) Array of passage results for the query. :param int duplicates_removed: (optional) The number of duplicate results removed. @@ -9977,7 +10546,7 @@ def __init__(self, self.suggested_query = suggested_query @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResponse': """Initialize a QueryResponse object from a json dictionary.""" args = {} valid_keys = [ @@ -10016,7 +10585,12 @@ def _from_dict(cls, _dict): args['suggested_query'] = _dict.get('suggested_query') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResponse 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, @@ -10042,17 +10616,21 @@ def _to_dict(self): _dict['suggested_query'] = self.suggested_query return _dict - def __str__(self): + 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 QueryResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResponse') -> 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): + def __ne__(self, other: 'QueryResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10071,11 +10649,11 @@ class QueryResult(): def __init__(self, *, - id=None, - metadata=None, - collection_id=None, - result_metadata=None, - **kwargs): + id: str = None, + metadata: dict = None, + collection_id: str = None, + result_metadata: 'QueryResultMetadata' = None, + **kwargs) -> None: """ Initialize a QueryResult object. @@ -10095,7 +10673,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResult': """Initialize a QueryResult object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -10115,7 +10693,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResult 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, 'id') and self.id is not None: @@ -10134,7 +10717,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = {'id', 'metadata', 'collection_id', 'result_metadata'} if not hasattr(self, '_additionalProperties'): super(QueryResult, self).__setattr__('_additionalProperties', set()) @@ -10142,17 +10729,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(QueryResult, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this QueryResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResult') -> 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): + def __ne__(self, other: 'QueryResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10171,7 +10758,7 @@ class QueryResultMetadata(): specified in the `document_retrieval_strategy` field of the result set. """ - def __init__(self, score, *, confidence=None): + def __init__(self, score: float, *, confidence: float = None) -> None: """ Initialize a QueryResultMetadata object. @@ -10189,7 +10776,7 @@ def __init__(self, score, *, confidence=None): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} valid_keys = ['score', 'confidence'] @@ -10208,7 +10795,12 @@ def _from_dict(cls, _dict): args['confidence'] = _dict.get('confidence') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResultMetadata 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, 'score') and self.score is not None: @@ -10217,17 +10809,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 QueryResultMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResultMetadata') -> 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): + def __ne__(self, other: 'QueryResultMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10247,7 +10843,7 @@ class RetrievalDetails(): listed as `untrained`. """ - def __init__(self, *, document_retrieval_strategy=None): + def __init__(self, *, document_retrieval_strategy: str = None) -> None: """ Initialize a RetrievalDetails object. @@ -10265,7 +10861,7 @@ def __init__(self, *, document_retrieval_strategy=None): self.document_retrieval_strategy = document_retrieval_strategy @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': """Initialize a RetrievalDetails object from a json dictionary.""" args = {} valid_keys = ['document_retrieval_strategy'] @@ -10279,7 +10875,12 @@ def _from_dict(cls, _dict): 'document_retrieval_strategy') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RetrievalDetails 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, 'document_retrieval_strategy' @@ -10288,17 +10889,21 @@ def _to_dict(self): 'document_retrieval_strategy'] = self.document_retrieval_strategy return _dict - def __str__(self): + 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 RetrievalDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RetrievalDetails') -> 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): + def __ne__(self, other: 'RetrievalDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10348,11 +10953,11 @@ class SduStatus(): def __init__(self, *, - enabled=None, - total_annotated_pages=None, - total_pages=None, - total_documents=None, - custom_fields=None): + enabled: bool = None, + total_annotated_pages: int = None, + total_pages: int = None, + total_documents: int = None, + custom_fields: 'SduStatusCustomFields' = None) -> None: """ Initialize a SduStatus object. @@ -10385,7 +10990,7 @@ def __init__(self, self.custom_fields = custom_fields @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SduStatus': """Initialize a SduStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -10410,7 +11015,12 @@ def _from_dict(cls, _dict): _dict.get('custom_fields')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SduStatus 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: @@ -10427,17 +11037,21 @@ def _to_dict(self): _dict['custom_fields'] = self.custom_fields._to_dict() return _dict - def __str__(self): + 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 SduStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SduStatus') -> 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): + def __ne__(self, other: 'SduStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10453,7 +11067,8 @@ class SduStatusCustomFields(): are allowed in this collection. """ - def __init__(self, *, defined=None, maximum_allowed=None): + def __init__(self, *, defined: int = None, + maximum_allowed: int = None) -> None: """ Initialize a SduStatusCustomFields object. @@ -10466,7 +11081,7 @@ def __init__(self, *, defined=None, maximum_allowed=None): self.maximum_allowed = maximum_allowed @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SduStatusCustomFields': """Initialize a SduStatusCustomFields object from a json dictionary.""" args = {} valid_keys = ['defined', 'maximum_allowed'] @@ -10481,9 +11096,14 @@ def _from_dict(cls, _dict): args['maximum_allowed'] = _dict.get('maximum_allowed') return cls(**args) - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} + @classmethod + def _from_dict(cls, _dict): + """Initialize a SduStatusCustomFields 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, 'defined') and self.defined is not None: _dict['defined'] = self.defined if hasattr(self, @@ -10491,17 +11111,21 @@ def _to_dict(self): _dict['maximum_allowed'] = self.maximum_allowed return _dict - def __str__(self): + 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 SduStatusCustomFields object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SduStatusCustomFields') -> 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): + def __ne__(self, other: 'SduStatusCustomFields') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10522,10 +11146,10 @@ class SearchStatus(): def __init__(self, *, - scope=None, - status=None, - status_description=None, - last_trained=None): + scope: str = None, + status: str = None, + status_description: str = None, + last_trained: date = None) -> None: """ Initialize a SearchStatus object. @@ -10544,7 +11168,7 @@ def __init__(self, self.last_trained = last_trained @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SearchStatus': """Initialize a SearchStatus object from a json dictionary.""" args = {} valid_keys = ['scope', 'status', 'status_description', 'last_trained'] @@ -10563,7 +11187,12 @@ def _from_dict(cls, _dict): args['last_trained'] = _dict.get('last_trained') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchStatus 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, 'scope') and self.scope is not None: @@ -10578,17 +11207,21 @@ def _to_dict(self): _dict['last_trained'] = self.last_trained return _dict - def __str__(self): + 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 SearchStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SearchStatus') -> 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): + def __ne__(self, other: 'SearchStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10609,12 +11242,12 @@ class SegmentSettings(): :attr bool enabled: (optional) Enables/disables the Document Segmentation feature. - :attr list[str] selector_tags: (optional) Defines the heading level that splits + :attr List[str] selector_tags: (optional) Defines the heading level that splits into document segments. Valid values are h1, h2, h3, h4, h5, h6. The content of the header field that the segmentation splits at is used as the **title** field for that segmented result. Only valid if used with a collection that has **enabled** set to `false` in the **smart_document_understanding** object. - :attr list[str] annotated_fields: (optional) Defines the annotated smart + :attr List[str] annotated_fields: (optional) Defines the annotated smart document understanding fields that the document is split on. The content of the annotated field that the segmentation splits at is used as the **title** field for that segmented result. For example, if the field `sub-title` is specified, @@ -10628,21 +11261,21 @@ class SegmentSettings(): def __init__(self, *, - enabled=None, - selector_tags=None, - annotated_fields=None): + enabled: bool = None, + selector_tags: List[str] = None, + annotated_fields: List[str] = None) -> None: """ Initialize a SegmentSettings object. :param bool enabled: (optional) Enables/disables the Document Segmentation feature. - :param list[str] selector_tags: (optional) Defines the heading level that + :param List[str] selector_tags: (optional) Defines the heading level that splits into document segments. Valid values are h1, h2, h3, h4, h5, h6. The content of the header field that the segmentation splits at is used as the **title** field for that segmented result. Only valid if used with a collection that has **enabled** set to `false` in the **smart_document_understanding** object. - :param list[str] annotated_fields: (optional) Defines the annotated smart + :param List[str] annotated_fields: (optional) Defines the annotated smart document understanding fields that the document is split on. The content of the annotated field that the segmentation splits at is used as the **title** field for that segmented result. For example, if the field @@ -10659,7 +11292,7 @@ def __init__(self, self.annotated_fields = annotated_fields @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SegmentSettings': """Initialize a SegmentSettings object from a json dictionary.""" args = {} valid_keys = ['enabled', 'selector_tags', 'annotated_fields'] @@ -10676,7 +11309,12 @@ def _from_dict(cls, _dict): args['annotated_fields'] = _dict.get('annotated_fields') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SegmentSettings 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: @@ -10688,17 +11326,21 @@ def _to_dict(self): _dict['annotated_fields'] = self.annotated_fields return _dict - def __str__(self): + 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 SegmentSettings object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SegmentSettings') -> 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): + def __ne__(self, other: 'SegmentSettings') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10728,10 +11370,10 @@ class Source(): def __init__(self, *, - type=None, - credential_id=None, - schedule=None, - options=None): + type: str = None, + credential_id: str = None, + schedule: 'SourceSchedule' = None, + options: 'SourceOptions' = None) -> None: """ Initialize a Source object. @@ -10759,7 +11401,7 @@ def __init__(self, self.options = options @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Source': """Initialize a Source object from a json dictionary.""" args = {} valid_keys = ['type', 'credential_id', 'schedule', 'options'] @@ -10778,7 +11420,12 @@ def _from_dict(cls, _dict): args['options'] = SourceOptions._from_dict(_dict.get('options')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Source 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: @@ -10791,17 +11438,21 @@ def _to_dict(self): _dict['options'] = self.options._to_dict() return _dict - def __str__(self): + 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 Source object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Source') -> 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): + def __ne__(self, other: 'Source') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10827,20 +11478,20 @@ class SourceOptions(): """ The **options** object defines which items to crawl from the source system. - :attr list[SourceOptionsFolder] folders: (optional) Array of folders to crawl + :attr List[SourceOptionsFolder] folders: (optional) Array of folders to crawl from the Box source. Only valid, and required, when the **type** field of the **source** object is set to `box`. - :attr list[SourceOptionsObject] objects: (optional) Array of Salesforce document + :attr List[SourceOptionsObject] objects: (optional) Array of Salesforce document object types to crawl from the Salesforce source. Only valid, and required, when the **type** field of the **source** object is set to `salesforce`. - :attr list[SourceOptionsSiteColl] site_collections: (optional) Array of + :attr List[SourceOptionsSiteColl] site_collections: (optional) Array of Microsoft SharePointoint Online site collections to crawl from the SharePoint source. Only valid and required when the **type** field of the **source** object is set to `sharepoint`. - :attr list[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to + :attr List[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to begin crawling the web from. Only valid and required when the **type** field of the **source** object is set to `web_crawl`. - :attr list[SourceOptionsBuckets] buckets: (optional) Array of cloud object store + :attr List[SourceOptionsBuckets] buckets: (optional) Array of cloud object store buckets to begin crawling. Only valid and required when the **type** field of the **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is `false` or not specified. @@ -10851,30 +11502,30 @@ class SourceOptions(): def __init__(self, *, - folders=None, - objects=None, - site_collections=None, - urls=None, - buckets=None, - crawl_all_buckets=None): + folders: List['SourceOptionsFolder'] = None, + objects: List['SourceOptionsObject'] = None, + site_collections: List['SourceOptionsSiteColl'] = None, + urls: List['SourceOptionsWebCrawl'] = None, + buckets: List['SourceOptionsBuckets'] = None, + crawl_all_buckets: bool = None) -> None: """ Initialize a SourceOptions object. - :param list[SourceOptionsFolder] folders: (optional) Array of folders to + :param List[SourceOptionsFolder] folders: (optional) Array of folders to crawl from the Box source. Only valid, and required, when the **type** field of the **source** object is set to `box`. - :param list[SourceOptionsObject] objects: (optional) Array of Salesforce + :param List[SourceOptionsObject] objects: (optional) Array of Salesforce document object types to crawl from the Salesforce source. Only valid, and required, when the **type** field of the **source** object is set to `salesforce`. - :param list[SourceOptionsSiteColl] site_collections: (optional) Array of + :param List[SourceOptionsSiteColl] site_collections: (optional) Array of Microsoft SharePointoint Online site collections to crawl from the SharePoint source. Only valid and required when the **type** field of the **source** object is set to `sharepoint`. - :param list[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs + :param List[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to begin crawling the web from. Only valid and required when the **type** field of the **source** object is set to `web_crawl`. - :param list[SourceOptionsBuckets] buckets: (optional) Array of cloud object + :param List[SourceOptionsBuckets] buckets: (optional) Array of cloud object store buckets to begin crawling. Only valid and required when the **type** field of the **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is `false` or not specified. @@ -10890,7 +11541,7 @@ def __init__(self, self.crawl_all_buckets = crawl_all_buckets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptions': """Initialize a SourceOptions object from a json dictionary.""" args = {} valid_keys = [ @@ -10930,7 +11581,12 @@ def _from_dict(cls, _dict): args['crawl_all_buckets'] = _dict.get('crawl_all_buckets') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptions 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, 'folders') and self.folders is not None: @@ -10951,17 +11607,21 @@ def _to_dict(self): _dict['crawl_all_buckets'] = self.crawl_all_buckets return _dict - def __str__(self): + 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 SourceOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptions') -> 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): + def __ne__(self, other: 'SourceOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -10975,7 +11635,7 @@ class SourceOptionsBuckets(): object store bucket. If not specified, all documents in the bucket are crawled. """ - def __init__(self, name, *, limit=None): + def __init__(self, name: str, *, limit: int = None) -> None: """ Initialize a SourceOptionsBuckets object. @@ -10988,7 +11648,7 @@ def __init__(self, name, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptionsBuckets': """Initialize a SourceOptionsBuckets object from a json dictionary.""" args = {} valid_keys = ['name', 'limit'] @@ -11007,7 +11667,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptionsBuckets 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, 'name') and self.name is not None: @@ -11016,17 +11681,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 SourceOptionsBuckets object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptionsBuckets') -> 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): + def __ne__(self, other: 'SourceOptionsBuckets') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11042,7 +11711,8 @@ class SourceOptionsFolder(): folder. By default, all documents in the folder are crawled. """ - def __init__(self, owner_user_id, folder_id, *, limit=None): + def __init__(self, owner_user_id: str, folder_id: str, *, + limit: int = None) -> None: """ Initialize a SourceOptionsFolder object. @@ -11057,7 +11727,7 @@ def __init__(self, owner_user_id, folder_id, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptionsFolder': """Initialize a SourceOptionsFolder object from a json dictionary.""" args = {} valid_keys = ['owner_user_id', 'folder_id', 'limit'] @@ -11082,7 +11752,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptionsFolder 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, 'owner_user_id') and self.owner_user_id is not None: @@ -11093,17 +11768,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 SourceOptionsFolder object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptionsFolder') -> 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): + def __ne__(self, other: 'SourceOptionsFolder') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11118,7 +11797,7 @@ class SourceOptionsObject(): document object. By default, all documents in the document object are crawled. """ - def __init__(self, name, *, limit=None): + def __init__(self, name: str, *, limit: int = None) -> None: """ Initialize a SourceOptionsObject object. @@ -11132,7 +11811,7 @@ def __init__(self, name, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptionsObject': """Initialize a SourceOptionsObject object from a json dictionary.""" args = {} valid_keys = ['name', 'limit'] @@ -11151,7 +11830,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptionsObject 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, 'name') and self.name is not None: @@ -11160,17 +11844,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 SourceOptionsObject object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptionsObject') -> 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): + def __ne__(self, other: 'SourceOptionsObject') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11187,7 +11875,7 @@ class SourceOptionsSiteColl(): site collection. By default, all documents in the site collection are crawled. """ - def __init__(self, site_collection_path, *, limit=None): + def __init__(self, site_collection_path: str, *, limit: int = None) -> None: """ Initialize a SourceOptionsSiteColl object. @@ -11203,7 +11891,7 @@ def __init__(self, site_collection_path, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptionsSiteColl': """Initialize a SourceOptionsSiteColl object from a json dictionary.""" args = {} valid_keys = ['site_collection_path', 'limit'] @@ -11222,7 +11910,12 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptionsSiteColl 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, 'site_collection_path' @@ -11232,17 +11925,21 @@ def _to_dict(self): _dict['limit'] = self.limit return _dict - def __str__(self): + 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 SourceOptionsSiteColl object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptionsSiteColl') -> 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): + def __ne__(self, other: 'SourceOptionsSiteColl') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11272,22 +11969,22 @@ class SourceOptionsWebCrawl(): any `robots.txt` encountered by the crawler. This should only ever be done when crawling a web site the user owns. This must be be set to `true` when a **gateway_id** is specied in the **credentials**. - :attr list[str] blacklist: (optional) Array of URL's to be excluded while + :attr List[str] blacklist: (optional) Array of URL's to be excluded while crawling. The crawler will not follow links which contains this string. For example, listing `https://ibm.com/watson` also excludes `https://ibm.com/watson/discovery`. """ def __init__(self, - url, + url: str, *, - limit_to_starting_hosts=None, - crawl_speed=None, - allow_untrusted_certificate=None, - maximum_hops=None, - request_timeout=None, - override_robots_txt=None, - blacklist=None): + limit_to_starting_hosts: bool = None, + crawl_speed: str = None, + allow_untrusted_certificate: bool = None, + maximum_hops: int = None, + request_timeout: int = None, + override_robots_txt: bool = None, + blacklist: List[str] = None) -> None: """ Initialize a SourceOptionsWebCrawl object. @@ -11313,7 +12010,7 @@ def __init__(self, ignore any `robots.txt` encountered by the crawler. This should only ever be done when crawling a web site the user owns. This must be be set to `true` when a **gateway_id** is specied in the **credentials**. - :param list[str] blacklist: (optional) Array of URL's to be excluded while + :param List[str] blacklist: (optional) Array of URL's to be excluded while crawling. The crawler will not follow links which contains this string. For example, listing `https://ibm.com/watson` also excludes `https://ibm.com/watson/discovery`. @@ -11328,7 +12025,7 @@ def __init__(self, self.blacklist = blacklist @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceOptionsWebCrawl': """Initialize a SourceOptionsWebCrawl object from a json dictionary.""" args = {} valid_keys = [ @@ -11365,7 +12062,12 @@ def _from_dict(cls, _dict): args['blacklist'] = _dict.get('blacklist') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceOptionsWebCrawl 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, 'url') and self.url is not None: @@ -11392,17 +12094,21 @@ def _to_dict(self): _dict['blacklist'] = self.blacklist return _dict - def __str__(self): + 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 SourceOptionsWebCrawl object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceOptionsWebCrawl') -> 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): + def __ne__(self, other: 'SourceOptionsWebCrawl') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11440,7 +12146,11 @@ class SourceSchedule(): 06:00. """ - def __init__(self, *, enabled=None, time_zone=None, frequency=None): + def __init__(self, + *, + enabled: bool = None, + time_zone: str = None, + frequency: str = None) -> None: """ Initialize a SourceSchedule object. @@ -11465,7 +12175,7 @@ def __init__(self, *, enabled=None, time_zone=None, frequency=None): self.frequency = frequency @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceSchedule': """Initialize a SourceSchedule object from a json dictionary.""" args = {} valid_keys = ['enabled', 'time_zone', 'frequency'] @@ -11482,7 +12192,12 @@ def _from_dict(cls, _dict): args['frequency'] = _dict.get('frequency') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceSchedule 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: @@ -11493,17 +12208,21 @@ def _to_dict(self): _dict['frequency'] = self.frequency return _dict - def __str__(self): + 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 SourceSchedule object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceSchedule') -> 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): + def __ne__(self, other: 'SourceSchedule') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11539,7 +12258,8 @@ class SourceStatus(): time of the next crawl attempt. """ - def __init__(self, *, status=None, next_crawl=None): + def __init__(self, *, status: str = None, + next_crawl: datetime = None) -> None: """ Initialize a SourceStatus object. @@ -11559,7 +12279,7 @@ def __init__(self, *, status=None, next_crawl=None): self.next_crawl = next_crawl @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SourceStatus': """Initialize a SourceStatus object from a json dictionary.""" args = {} valid_keys = ['status', 'next_crawl'] @@ -11574,7 +12294,12 @@ def _from_dict(cls, _dict): args['next_crawl'] = string_to_datetime(_dict.get('next_crawl')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SourceStatus 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, 'status') and self.status is not None: @@ -11583,17 +12308,21 @@ def _to_dict(self): _dict['next_crawl'] = datetime_to_string(self.next_crawl) return _dict - def __str__(self): + 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 SourceStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SourceStatus') -> 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): + def __ne__(self, other: 'SourceStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11615,193 +12344,34 @@ class StatusEnum(Enum): UNKNOWN = "unknown" -class Term(): - """ - Term. - - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr int count: (optional) The number of terms identified. - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - field=None, - count=None): - """ - Initialize a Term object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param int count: (optional) The number of terms identified. - """ - self.field = field - self.count = count - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Term object from a json dictionary.""" - args = {} - valid_keys = ['field', 'count'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Term: ' + - ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'count' in _dict: - args['count'] = _dict.get('count') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - return _dict - - def __str__(self): - """Return a `str` version of this Term object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Timeslice(): - """ - Timeslice. - - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr str interval: (optional) Interval of the aggregation. Valid date interval - values are second/seconds minute/minutes, hour/hours, day/days, week/weeks, - month/months, and year/years. - :attr bool anomaly: (optional) Used to indicate that anomaly detection should be - performed. Anomaly detection is used to locate unusual datapoints within a time - series. - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - field=None, - interval=None, - anomaly=None): - """ - Initialize a Timeslice object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param str interval: (optional) Interval of the aggregation. Valid date - interval values are second/seconds minute/minutes, hour/hours, day/days, - week/weeks, month/months, and year/years. - :param bool anomaly: (optional) Used to indicate that anomaly detection - should be performed. Anomaly detection is used to locate unusual datapoints - within a time series. - """ - self.field = field - self.interval = interval - self.anomaly = anomaly - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Timeslice object from a json dictionary.""" - args = {} - valid_keys = ['field', 'interval', 'anomaly'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Timeslice: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - if 'anomaly' in _dict: - args['anomaly'] = _dict.get('anomaly') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'anomaly') and self.anomaly is not None: - _dict['anomaly'] = self.anomaly - return _dict - - def __str__(self): - """Return a `str` version of this Timeslice object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TokenDictRule(): """ An object defining a single tokenizaion rule. :attr str text: The string to tokenize. - :attr list[str] tokens: Array of tokens that the `text` field is split into when + :attr List[str] tokens: Array of tokens that the `text` field is split into when found. - :attr list[str] readings: (optional) Array of tokens that represent the content + :attr List[str] readings: (optional) Array of tokens that represent the content of the `text` field in an alternate character set. :attr str part_of_speech: The part of speech that the `text` string belongs to. For example `noun`. Custom parts of speech can be specified. """ - def __init__(self, text, tokens, part_of_speech, *, readings=None): + def __init__(self, + text: str, + tokens: List[str], + part_of_speech: str, + *, + readings: List[str] = None) -> None: """ Initialize a TokenDictRule object. :param str text: The string to tokenize. - :param list[str] tokens: Array of tokens that the `text` field is split + :param List[str] tokens: Array of tokens that the `text` field is split into when found. :param str part_of_speech: The part of speech that the `text` string belongs to. For example `noun`. Custom parts of speech can be specified. - :param list[str] readings: (optional) Array of tokens that represent the + :param List[str] readings: (optional) Array of tokens that represent the content of the `text` field in an alternate character set. """ self.text = text @@ -11810,7 +12380,7 @@ def __init__(self, text, tokens, part_of_speech, *, readings=None): self.part_of_speech = part_of_speech @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TokenDictRule': """Initialize a TokenDictRule object from a json dictionary.""" args = {} valid_keys = ['text', 'tokens', 'readings', 'part_of_speech'] @@ -11840,7 +12410,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TokenDictRule 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, 'text') and self.text is not None: @@ -11853,17 +12428,21 @@ def _to_dict(self): _dict['part_of_speech'] = self.part_of_speech return _dict - def __str__(self): - """Return a `str` version of this TokenDictRule object.""" + 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 TokenDictRule object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TokenDictRule') -> 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): + def __ne__(self, other: 'TokenDictRule') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11878,7 +12457,7 @@ class TokenDictStatusResponse(): `tokenization_dictionary` or `stopwords`. """ - def __init__(self, *, status=None, type=None): + def __init__(self, *, status: str = None, type: str = None) -> None: """ Initialize a TokenDictStatusResponse object. @@ -11891,7 +12470,7 @@ def __init__(self, *, status=None, type=None): self.type = type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TokenDictStatusResponse': """Initialize a TokenDictStatusResponse object from a json dictionary.""" args = {} valid_keys = ['status', 'type'] @@ -11906,7 +12485,12 @@ def _from_dict(cls, _dict): args['type'] = _dict.get('type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TokenDictStatusResponse 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, 'status') and self.status is not None: @@ -11915,17 +12499,21 @@ def _to_dict(self): _dict['type'] = self.type return _dict - def __str__(self): + 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 TokenDictStatusResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TokenDictStatusResponse') -> 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): + def __ne__(self, other: 'TokenDictStatusResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11938,100 +12526,31 @@ class StatusEnum(Enum): NOT_FOUND = "not found" -class TopHits(): - """ - TopHits. - - :attr int size: (optional) Number of top hits returned by the aggregation. - :attr TopHitsResults hits: (optional) - """ - - def __init__(self, - *, - type=None, - results=None, - matching_results=None, - aggregations=None, - size=None, - hits=None): - """ - Initialize a TopHits object. - - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param list[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param list[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param int size: (optional) Number of top hits returned by the aggregation. - :param TopHitsResults hits: (optional) - """ - self.size = size - self.hits = hits - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TopHits object from a json dictionary.""" - args = {} - valid_keys = ['size', 'hits'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TopHits: ' + - ', '.join(bad_keys)) - if 'size' in _dict: - args['size'] = _dict.get('size') - if 'hits' in _dict: - args['hits'] = TopHitsResults._from_dict(_dict.get('hits')) - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'size') and self.size is not None: - _dict['size'] = self.size - if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits._to_dict() - return _dict - - def __str__(self): - """Return a `str` version of this TopHits object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TopHitsResults(): """ Top hit information for this query. :attr int matching_results: (optional) Number of matching results. - :attr list[QueryResult] hits: (optional) Top results returned by the + :attr List[QueryResult] hits: (optional) Top results returned by the aggregation. """ - def __init__(self, *, matching_results=None, hits=None): + def __init__(self, + *, + matching_results: int = None, + hits: List['QueryResult'] = None) -> None: """ Initialize a TopHitsResults object. :param int matching_results: (optional) Number of matching results. - :param list[QueryResult] hits: (optional) Top results returned by the + :param List[QueryResult] hits: (optional) Top results returned by the aggregation. """ self.matching_results = matching_results self.hits = hits @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TopHitsResults': """Initialize a TopHitsResults object from a json dictionary.""" args = {} valid_keys = ['matching_results', 'hits'] @@ -12048,7 +12567,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TopHitsResults 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, @@ -12058,17 +12582,21 @@ def _to_dict(self): _dict['hits'] = [x._to_dict() for x in self.hits] return _dict - def __str__(self): + 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 TopHitsResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TopHitsResults') -> 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): + def __ne__(self, other: 'TopHitsResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12081,11 +12609,14 @@ class TrainingDataSet(): training data set. :attr str collection_id: (optional) The collection id associated with this training data set. - :attr list[TrainingQuery] queries: (optional) Array of training queries. + :attr List[TrainingQuery] queries: (optional) Array of training queries. """ - def __init__(self, *, environment_id=None, collection_id=None, - queries=None): + def __init__(self, + *, + environment_id: str = None, + collection_id: str = None, + queries: List['TrainingQuery'] = None) -> None: """ Initialize a TrainingDataSet object. @@ -12093,14 +12624,14 @@ def __init__(self, *, environment_id=None, collection_id=None, this training data set. :param str collection_id: (optional) The collection id associated with this training data set. - :param list[TrainingQuery] queries: (optional) Array of training queries. + :param List[TrainingQuery] queries: (optional) Array of training queries. """ self.environment_id = environment_id self.collection_id = collection_id self.queries = queries @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingDataSet': """Initialize a TrainingDataSet object from a json dictionary.""" args = {} valid_keys = ['environment_id', 'collection_id', 'queries'] @@ -12119,7 +12650,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingDataSet 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, 'environment_id') and self.environment_id is not None: @@ -12130,17 +12666,21 @@ def _to_dict(self): _dict['queries'] = [x._to_dict() for x in self.queries] return _dict - def __str__(self): + 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 TrainingDataSet object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingDataSet') -> 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): + def __ne__(self, other: 'TrainingDataSet') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12158,9 +12698,9 @@ class TrainingExample(): def __init__(self, *, - document_id=None, - cross_reference=None, - relevance=None): + document_id: str = None, + cross_reference: str = None, + relevance: int = None) -> None: """ Initialize a TrainingExample object. @@ -12175,7 +12715,7 @@ def __init__(self, self.relevance = relevance @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingExample': """Initialize a TrainingExample object from a json dictionary.""" args = {} valid_keys = ['document_id', 'cross_reference', 'relevance'] @@ -12192,7 +12732,12 @@ def _from_dict(cls, _dict): args['relevance'] = _dict.get('relevance') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingExample 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, 'document_id') and self.document_id is not None: @@ -12204,17 +12749,21 @@ def _to_dict(self): _dict['relevance'] = self.relevance return _dict - def __str__(self): + 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 TrainingExample object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingExample') -> 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): + def __ne__(self, other: 'TrainingExample') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12223,20 +12772,20 @@ class TrainingExampleList(): """ Object containing an array of training examples. - :attr list[TrainingExample] examples: (optional) Array of training examples. + :attr List[TrainingExample] examples: (optional) Array of training examples. """ - def __init__(self, *, examples=None): + def __init__(self, *, examples: List['TrainingExample'] = None) -> None: """ Initialize a TrainingExampleList object. - :param list[TrainingExample] examples: (optional) Array of training + :param List[TrainingExample] examples: (optional) Array of training examples. """ self.examples = examples @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingExampleList': """Initialize a TrainingExampleList object from a json dictionary.""" args = {} valid_keys = ['examples'] @@ -12251,24 +12800,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingExampleList 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, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] return _dict - def __str__(self): + 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 TrainingExampleList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingExampleList') -> 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): + def __ne__(self, other: 'TrainingExampleList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12282,15 +12840,15 @@ class TrainingQuery(): training query. :attr str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :attr list[TrainingExample] examples: (optional) Array of training examples. + :attr List[TrainingExample] examples: (optional) Array of training examples. """ def __init__(self, *, - query_id=None, - natural_language_query=None, - filter=None, - examples=None): + query_id: str = None, + natural_language_query: str = None, + filter: str = None, + examples: List['TrainingExample'] = None) -> None: """ Initialize a TrainingQuery object. @@ -12300,7 +12858,7 @@ def __init__(self, the training query. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :param list[TrainingExample] examples: (optional) Array of training + :param List[TrainingExample] examples: (optional) Array of training examples. """ self.query_id = query_id @@ -12309,7 +12867,7 @@ def __init__(self, self.examples = examples @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingQuery': """Initialize a TrainingQuery object from a json dictionary.""" args = {} valid_keys = [ @@ -12332,7 +12890,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingQuery 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, 'query_id') and self.query_id is not None: @@ -12346,17 +12909,21 @@ def _to_dict(self): _dict['examples'] = [x._to_dict() for x in self.examples] return _dict - def __str__(self): + 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 TrainingQuery object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingQuery') -> 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): + def __ne__(self, other: 'TrainingQuery') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12387,15 +12954,15 @@ class TrainingStatus(): def __init__(self, *, - total_examples=None, - available=None, - processing=None, - minimum_queries_added=None, - minimum_examples_added=None, - sufficient_label_diversity=None, - notices=None, - successfully_trained=None, - data_updated=None): + total_examples: int = None, + available: bool = None, + processing: bool = None, + minimum_queries_added: bool = None, + minimum_examples_added: bool = None, + sufficient_label_diversity: bool = None, + notices: int = None, + successfully_trained: datetime = None, + data_updated: datetime = None) -> None: """ Initialize a TrainingStatus object. @@ -12430,7 +12997,7 @@ def __init__(self, self.data_updated = data_updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingStatus': """Initialize a TrainingStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -12466,7 +13033,12 @@ def _from_dict(cls, _dict): args['data_updated'] = string_to_datetime(_dict.get('data_updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingStatus 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, 'total_examples') and self.total_examples is not None: @@ -12495,17 +13067,21 @@ def _to_dict(self): _dict['data_updated'] = datetime_to_string(self.data_updated) return _dict - def __str__(self): + 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 TrainingStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingStatus') -> 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): + def __ne__(self, other: 'TrainingStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12514,25 +13090,28 @@ class WordHeadingDetection(): """ Object containing heading detection conversion settings for Microsoft Word documents. - :attr list[FontSetting] fonts: (optional) Array of font matching configurations. - :attr list[WordStyle] styles: (optional) Array of Microsoft Word styles to + :attr List[FontSetting] fonts: (optional) Array of font matching configurations. + :attr List[WordStyle] styles: (optional) Array of Microsoft Word styles to convert. """ - def __init__(self, *, fonts=None, styles=None): + def __init__(self, + *, + fonts: List['FontSetting'] = None, + styles: List['WordStyle'] = None) -> None: """ Initialize a WordHeadingDetection object. - :param list[FontSetting] fonts: (optional) Array of font matching + :param List[FontSetting] fonts: (optional) Array of font matching configurations. - :param list[WordStyle] styles: (optional) Array of Microsoft Word styles to + :param List[WordStyle] styles: (optional) Array of Microsoft Word styles to convert. """ self.fonts = fonts self.styles = styles @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordHeadingDetection': """Initialize a WordHeadingDetection object from a json dictionary.""" args = {} valid_keys = ['fonts', 'styles'] @@ -12551,7 +13130,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordHeadingDetection 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, 'fonts') and self.fonts is not None: @@ -12560,17 +13144,21 @@ def _to_dict(self): _dict['styles'] = [x._to_dict() for x in self.styles] return _dict - def __str__(self): + 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 WordHeadingDetection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordHeadingDetection') -> 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): + def __ne__(self, other: 'WordHeadingDetection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12583,7 +13171,7 @@ class WordSettings(): detection conversion settings for Microsoft Word documents. """ - def __init__(self, *, heading=None): + def __init__(self, *, heading: 'WordHeadingDetection' = None) -> None: """ Initialize a WordSettings object. @@ -12593,7 +13181,7 @@ def __init__(self, *, heading=None): self.heading = heading @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordSettings': """Initialize a WordSettings object from a json dictionary.""" args = {} valid_keys = ['heading'] @@ -12607,24 +13195,33 @@ def _from_dict(cls, _dict): _dict.get('heading')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordSettings 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, 'heading') and self.heading is not None: _dict['heading'] = self.heading._to_dict() return _dict - def __str__(self): + 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 WordSettings object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordSettings') -> 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): + def __ne__(self, other: 'WordSettings') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12635,22 +13232,22 @@ class WordStyle(): :attr int level: (optional) HTML head level that content matching this style is tagged with. - :attr list[str] names: (optional) Array of word style names to convert. + :attr List[str] names: (optional) Array of word style names to convert. """ - def __init__(self, *, level=None, names=None): + def __init__(self, *, level: int = None, names: List[str] = None) -> None: """ Initialize a WordStyle object. :param int level: (optional) HTML head level that content matching this style is tagged with. - :param list[str] names: (optional) Array of word style names to convert. + :param List[str] names: (optional) Array of word style names to convert. """ self.level = level self.names = names @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordStyle': """Initialize a WordStyle object from a json dictionary.""" args = {} valid_keys = ['level', 'names'] @@ -12665,7 +13262,12 @@ def _from_dict(cls, _dict): args['names'] = _dict.get('names') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordStyle 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, 'level') and self.level is not None: @@ -12674,17 +13276,21 @@ def _to_dict(self): _dict['names'] = self.names return _dict - def __str__(self): + 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 WordStyle object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordStyle') -> 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): + def __ne__(self, other: 'WordStyle') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -12693,19 +13299,19 @@ class XPathPatterns(): """ Object containing an array of XPaths. - :attr list[str] xpaths: (optional) An array to XPaths. + :attr List[str] xpaths: (optional) An array to XPaths. """ - def __init__(self, *, xpaths=None): + def __init__(self, *, xpaths: List[str] = None) -> None: """ Initialize a XPathPatterns object. - :param list[str] xpaths: (optional) An array to XPaths. + :param List[str] xpaths: (optional) An array to XPaths. """ self.xpaths = xpaths @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'XPathPatterns': """Initialize a XPathPatterns object from a json dictionary.""" args = {} valid_keys = ['xpaths'] @@ -12718,23 +13324,812 @@ def _from_dict(cls, _dict): args['xpaths'] = _dict.get('xpaths') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a XPathPatterns 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, 'xpaths') and self.xpaths is not None: _dict['xpaths'] = self.xpaths return _dict - def __str__(self): + 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 XPathPatterns object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'XPathPatterns') -> 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: 'XPathPatterns') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Calculation(QueryAggregation): + """ + Calculation. + + :attr str field: (optional) The field where the aggregation is located in the + document. + :attr float value: (optional) Value of the aggregation. + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + field: str = None, + value: float = None) -> None: + """ + Initialize a Calculation object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. + :param float value: (optional) Value of the aggregation. + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.field = field + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Calculation': + """Initialize a Calculation object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'field', + 'value' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Calculation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'value' in _dict: + args['value'] = _dict.get('value') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Calculation 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 + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + 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 Calculation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Calculation') -> 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: 'Calculation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Filter(QueryAggregation): + """ + Filter. + + :attr str match: (optional) The match the aggregated results queried for. + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + match: str = None) -> None: + """ + Initialize a Filter object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str match: (optional) The match the aggregated results queried for. + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.match = match + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Filter': + """Initialize a Filter object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'match' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Filter: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'match' in _dict: + args['match'] = _dict.get('match') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Filter 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 + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'match') and self.match is not None: + _dict['match'] = self.match + 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 Filter object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Filter') -> 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: 'Filter') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Histogram(QueryAggregation): + """ + Histogram. + + :attr str field: (optional) The field where the aggregation is located in the + document. + :attr int interval: (optional) Interval of the aggregation. (For 'histogram' + type). + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + field: str = None, + interval: int = None) -> None: + """ + Initialize a Histogram object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. + :param int interval: (optional) Interval of the aggregation. (For + 'histogram' type). + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.field = field + self.interval = interval + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Histogram': + """Initialize a Histogram object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'field', + 'interval' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Histogram: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'interval' in _dict: + args['interval'] = _dict.get('interval') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Histogram 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 + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'interval') and self.interval is not None: + _dict['interval'] = self.interval + 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 Histogram object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Histogram') -> 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: 'Histogram') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Nested(QueryAggregation): + """ + Nested. + + :attr str path: (optional) The area of the results the aggregation was + restricted to. + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + path: str = None) -> None: + """ + Initialize a Nested object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str path: (optional) The area of the results the aggregation was + restricted to. + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.path = path + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Nested': + """Initialize a Nested object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'path' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Nested: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'path' in _dict: + args['path'] = _dict.get('path') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Nested 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 + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + 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 Nested object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Nested') -> 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: 'Nested') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Term(QueryAggregation): + """ + Term. + + :attr str field: (optional) The field where the aggregation is located in the + document. + :attr int count: (optional) The number of terms identified. + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + field: str = None, + count: int = None) -> None: + """ + Initialize a Term object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. + :param int count: (optional) The number of terms identified. + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.field = field + self.count = count + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Term': + """Initialize a Term object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'field', + 'count' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Term: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'count' in _dict: + args['count'] = _dict.get('count') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Term 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 + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + 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 Term object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Term') -> 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: 'Term') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Timeslice(QueryAggregation): + """ + Timeslice. + + :attr str field: (optional) The field where the aggregation is located in the + document. + :attr str interval: (optional) Interval of the aggregation. Valid date interval + values are second/seconds minute/minutes, hour/hours, day/days, week/weeks, + month/months, and year/years. + :attr bool anomaly: (optional) Used to indicate that anomaly detection should be + performed. Anomaly detection is used to locate unusual datapoints within a time + series. + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + field: str = None, + interval: str = None, + anomaly: bool = None) -> None: + """ + Initialize a Timeslice object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param str field: (optional) The field where the aggregation is located in + the document. + :param str interval: (optional) Interval of the aggregation. Valid date + interval values are second/seconds minute/minutes, hour/hours, day/days, + week/weeks, month/months, and year/years. + :param bool anomaly: (optional) Used to indicate that anomaly detection + should be performed. Anomaly detection is used to locate unusual datapoints + within a time series. + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.field = field + self.interval = interval + self.anomaly = anomaly + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Timeslice': + """Initialize a Timeslice object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'field', + 'interval', 'anomaly' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Timeslice: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'interval' in _dict: + args['interval'] = _dict.get('interval') + if 'anomaly' in _dict: + args['anomaly'] = _dict.get('anomaly') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Timeslice 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 + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'interval') and self.interval is not None: + _dict['interval'] = self.interval + if hasattr(self, 'anomaly') and self.anomaly is not None: + _dict['anomaly'] = self.anomaly + 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 Timeslice object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Timeslice') -> 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: 'Timeslice') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TopHits(QueryAggregation): + """ + TopHits. + + :attr int size: (optional) Number of top hits returned by the aggregation. + :attr TopHitsResults hits: (optional) + """ + + def __init__(self, + *, + type: str = None, + results: List['AggregationResult'] = None, + matching_results: int = None, + aggregations: List['QueryAggregation'] = None, + size: int = None, + hits: 'TopHitsResults' = None) -> None: + """ + Initialize a TopHits object. + + :param str type: (optional) The type of aggregation command used. For + example: term, filter, max, min, etc. + :param List[AggregationResult] results: (optional) Array of aggregation + results. + :param int matching_results: (optional) Number of matching results. + :param List[QueryAggregation] aggregations: (optional) Aggregations + returned by Discovery. + :param int size: (optional) Number of top hits returned by the aggregation. + :param TopHitsResults hits: (optional) + """ + self.type = type + self.results = results + self.matching_results = matching_results + self.aggregations = aggregations + self.size = size + self.hits = hits + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TopHits': + """Initialize a TopHits object from a json dictionary.""" + args = {} + valid_keys = [ + 'type', 'results', 'matching_results', 'aggregations', 'size', + 'hits' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TopHits: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'results' in _dict: + args['results'] = [ + AggregationResult._from_dict(x) for x in (_dict.get('results')) + ] + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + if 'size' in _dict: + args['size'] = _dict.get('size') + if 'hits' in _dict: + args['hits'] = TopHitsResults._from_dict(_dict.get('hits')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TopHits 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 + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'size') and self.size is not None: + _dict['size'] = self.size + if hasattr(self, 'hits') and self.hits is not None: + _dict['hits'] = self.hits._to_dict() + 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 TopHits object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'TopHits') -> 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): + def __ne__(self, other: 'TopHits') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index ac731fb59..e1ed74b89 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,1423 +1,4777 @@ -# coding: utf-8 -import responses -import os +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -import io -import time -import jwt -from unittest import TestCase -import ibm_watson -from ibm_watson.discovery_v1 import TrainingDataSet, TrainingQuery, TrainingExample -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator, IAMAuthenticator - -from urllib.parse import urlparse, urljoin - -base_discovery_url = 'https://gateway.watsonplatform.net/discovery/api/v1/' - -platform_url = 'https://gateway.watsonplatform.net' -service_path = '/discovery/api' -base_url = '{0}{1}'.format(platform_url, service_path) - -version = '2016-12-01' -environment_id = 'envid' -collection_id = 'collid' - - -def get_access_token(): - access_token_layout = { - "username": "dummy", - "role": "Admin", - "permissions": ["administrator", "manage_catalog"], - "sub": "admin", - "iss": "sss", - "aud": "sss", - "uid": "sss", - "iat": 3600, - "exp": int(time.time()) - } - - access_token = jwt.encode( - access_token_layout, - 'secret', - algorithm='HS256', - headers={'kid': '230498151c214b788dd97f22b85410a5'}) - return access_token.decode('utf-8') - - -class TestDiscoveryV1(TestCase): - - @classmethod - def setUp(cls): - iam_url = "https://iam.cloud.ibm.com/identity/token" - iam_token_response = { - "access_token": get_access_token(), - "token_type": "Bearer", - "expires_in": 3600, - "expiration": 1524167011, - "refresh_token": "jy4gl91BQ" - } - responses.add(responses.POST, - url=iam_url, - body=json.dumps(iam_token_response), - status=200) - - @classmethod - @responses.activate - def test_environments(cls): - discovery_url = urljoin(base_discovery_url, 'environments') - discovery_response_body = """{ - "environments": [ - { - "environment_id": "string", - "name": "envname", - "description": "", - "created": "2016-11-20T01:03:17.645Z", - "updated": "2016-11-20T01:03:17.645Z", - "status": "status", - "index_capacity": { - "disk_usage": { - "used_bytes": 0, - "total_bytes": 0, - "used": "string", - "total": "string", - "percent_used": 0 - }, - "memory_usage": { - "used_bytes": 0, - "total_bytes": 0, - "used": "string", - "total": "string", - "percent_used": 0 - } - } - } - ] - }""" +import pytest +import responses +import tempfile +import ibm_watson.discovery_v1 +from ibm_watson.discovery_v1 import * - responses.add(responses.GET, - discovery_url, - body=discovery_response_body, - status=200, - content_type='application/json') +base_url = 'https://gateway.watsonplatform.net/discovery/api' - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - discovery.list_environments() +############################################################################## +# Start of Service: Environments +############################################################################## +# region - url_str = "{0}?version=2018-08-13".format(discovery_url) - assert responses.calls[0].request.url == url_str +#----------------------------------------------------------------------------- +# Test Class for create_environment +#----------------------------------------------------------------------------- +class TestCreateEnvironment(): - assert responses.calls[0].response.text == discovery_response_body + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_environment_response(self): + body = self.construct_full_body() + response = fake_response_Environment_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_get_environment(cls): - discovery_url = urljoin(base_discovery_url, 'environments/envid') - responses.add(responses.GET, - discovery_url, - body="{\"resulting_key\": true}", - status=200, - content_type='application/json') + def test_create_environment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Environment_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_environment_empty(self): + check_empty_required_params(self, fake_response_Environment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments' + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.get_environment(environment_id='envid') - url_str = "{0}?version=2018-08-13".format(discovery_url) - assert responses.calls[0].request.url == url_str + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_environment(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"name": "string1", "description": "string1", "size": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body.update({"name": "string1", "description": "string1", "size": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_environments +#----------------------------------------------------------------------------- +class TestListEnvironments(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_environments_response(self): + body = self.construct_full_body() + response = fake_response_ListEnvironmentsResponse_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_create_environment(cls): + def test_list_environments_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListEnvironmentsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery_url = urljoin(base_discovery_url, 'environments') - responses.add(responses.POST, - discovery_url, - body="{\"resulting_key\": true}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_environments_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments' + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.create_environment(name="my name", - description="my description") + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_environments(**body) + return output + + def construct_full_body(self): + body = dict() + body['name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_environment +#----------------------------------------------------------------------------- +class TestGetEnvironment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_environment_response(self): + body = self.construct_full_body() + response = fake_response_Environment_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_update_environment(cls): - discovery_url = urljoin(base_discovery_url, 'environments/envid') - responses.add(responses.PUT, - discovery_url, - body="{\"resulting_key\": true}", - status=200, - content_type='application/json') + def test_get_environment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Environment_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_environment_empty(self): + check_empty_required_params(self, fake_response_Environment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.update_environment('envid', name="hello", description="new") + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_environment(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_environment +#----------------------------------------------------------------------------- +class TestUpdateEnvironment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_environment_response(self): + body = self.construct_full_body() + response = fake_response_Environment_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_delete_environment(cls): - discovery_url = urljoin(base_discovery_url, 'environments/envid') - responses.add(responses.DELETE, - discovery_url, - body="{\"resulting_key\": true}", - status=200, - content_type='application/json') + def test_update_environment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Environment_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_environment_empty(self): + check_empty_required_params(self, fake_response_Environment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_environment(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "size": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "size": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_environment +#----------------------------------------------------------------------------- +class TestDeleteEnvironment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_environment_response(self): + body = self.construct_full_body() + response = fake_response_DeleteEnvironmentResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.delete_environment('envid') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_environment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteEnvironmentResponse_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_collections(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/collections') + def test_delete_environment_empty(self): + check_empty_required_params(self, fake_response_DeleteEnvironmentResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - responses.add(responses.GET, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_environment(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_fields +#----------------------------------------------------------------------------- +class TestListFields(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_fields_response(self): + body = self.construct_full_body() + response = fake_response_ListCollectionFieldsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_fields_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListCollectionFieldsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.list_collections('envid') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_fields_empty(self): + check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/fields'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_fields(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_ids'] = [] + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_ids'] = [] + return body + + +# endregion +############################################################################## +# End of Service: Environments +############################################################################## + +############################################################################## +# Start of Service: Configurations +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for create_configuration +#----------------------------------------------------------------------------- +class TestCreateConfiguration(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_configuration_response(self): + body = self.construct_full_body() + response = fake_response_Configuration_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_configuration_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Configuration_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_collection(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/collections/collid') + def test_create_configuration_empty(self): + check_empty_required_params(self, fake_response_Configuration_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/configurations'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery_fields = urljoin( - base_discovery_url, 'environments/envid/collections/collid/fields') - config_url = urljoin(base_discovery_url, - 'environments/envid/configurations') + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_configuration(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_configurations +#----------------------------------------------------------------------------- +class TestListConfigurations(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_configurations_response(self): + body = self.construct_full_body() + response = fake_response_ListConfigurationsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.GET, - config_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_configurations_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListConfigurationsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.GET, - discovery_fields, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_configurations_empty(self): + check_empty_required_params(self, fake_response_ListConfigurationsResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/configurations'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): responses.add(responses.GET, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_configurations(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_configuration +#----------------------------------------------------------------------------- +class TestGetConfiguration(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_configuration_response(self): + body = self.construct_full_body() + response = fake_response_Configuration_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.DELETE, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_configuration_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Configuration_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.POST, - urljoin(base_discovery_url, - 'environments/envid/collections'), - body="{\"body\": \"create\"}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_configuration_empty(self): + check_empty_required_params(self, fake_response_Configuration_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_configuration(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_configuration +#----------------------------------------------------------------------------- +class TestUpdateConfiguration(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_configuration_response(self): + body = self.construct_full_body() + response = fake_response_Configuration_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.create_collection(environment_id='envid', - name="name", - description="", - language="", - configuration_id='confid') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_configuration_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Configuration_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.create_collection(environment_id='envid', - name="name", - language="es", - description="") + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_configuration_empty(self): + check_empty_required_params(self, fake_response_Configuration_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.get_collection('envid', 'collid') + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_configuration(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_configuration +#----------------------------------------------------------------------------- +class TestDeleteConfiguration(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_configuration_response(self): + body = self.construct_full_body() + response = fake_response_DeleteConfigurationResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - called_url = urlparse(responses.calls[2].request.url) - test_url = urlparse(discovery_url) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_configuration_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteConfigurationResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_configuration_empty(self): + check_empty_required_params(self, fake_response_DeleteConfigurationResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.delete_collection(environment_id='envid', - collection_id='collid') - discovery.list_collection_fields(environment_id='envid', - collection_id='collid') - assert len(responses.calls) == 5 + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_configuration(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['configuration_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Configurations +############################################################################## + +############################################################################## +# Start of Service: Collections +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for create_collection +#----------------------------------------------------------------------------- +class TestCreateCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_collection_response(self): + body = self.construct_full_body() + response = fake_response_Collection_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_create_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_federated_query(cls): - discovery_url = urljoin(base_discovery_url, 'environments/envid/query') + def test_create_collection_empty(self): + check_empty_required_params(self, fake_response_Collection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): responses.add(responses.POST, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_collections +#----------------------------------------------------------------------------- +class TestListCollections(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collections_response(self): + body = self.construct_full_body() + response = fake_response_ListCollectionsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collections_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListCollectionsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.federated_query('envid', - filter='colls.sha1::9181d244*', - collection_ids=['collid1', 'collid2']) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collections_empty(self): + check_empty_required_params(self, fake_response_ListCollectionsResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_collections(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_collection +#----------------------------------------------------------------------------- +class TestGetCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_collection_response(self): + body = self.construct_full_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Collection_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_federated_query_2(cls): - discovery_url = urljoin(base_discovery_url, 'environments/envid/query') + def test_get_collection_empty(self): + check_empty_required_params(self, fake_response_Collection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - responses.add(responses.POST, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_collection +#----------------------------------------------------------------------------- +class TestUpdateCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_response(self): + body = self.construct_full_body() + response = fake_response_Collection_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_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Collection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_empty(self): + check_empty_required_params(self, fake_response_Collection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_collection +#----------------------------------------------------------------------------- +class TestDeleteCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_collection_response(self): + body = self.construct_full_body() + response = fake_response_DeleteCollectionResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteCollectionResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.federated_query('envid', - collection_ids="'collid1', 'collid2'", - filter='colls.sha1::9181d244*', - bias='1', - logging_opt_out=True) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_collection_empty(self): + check_empty_required_params(self, fake_response_DeleteCollectionResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_collection_fields +#----------------------------------------------------------------------------- +class TestListCollectionFields(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collection_fields_response(self): + body = self.construct_full_body() + response = fake_response_ListCollectionFieldsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_collection_fields_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListCollectionFieldsResponse_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_federated_query_notices(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/notices') + def test_list_collection_fields_empty(self): + check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/fields'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): responses.add(responses.GET, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - discovery.federated_query_notices('envid', - collection_ids=['collid1', 'collid2'], - filter='notices.sha1::9181d244*') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_collection_fields(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Collections +############################################################################## + +############################################################################## +# Start of Service: QueryModifications +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_expansions +#----------------------------------------------------------------------------- +class TestListExpansions(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_expansions_response(self): + body = self.construct_full_body() + response = fake_response_Expansions_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_expansions_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Expansions_json + send_request(self, body, response) + assert len(responses.calls) == 1 - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_expansions_empty(self): + check_empty_required_params(self, fake_response_Expansions_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_expansions(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_expansions +#----------------------------------------------------------------------------- +class TestCreateExpansions(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_expansions_response(self): + body = self.construct_full_body() + response = fake_response_Expansions_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_query(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/collections/collid/query') + def test_create_expansions_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Expansions_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.POST, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - discovery.query('envid', - 'collid', - filter='extracted_metadata.sha1::9181d244*', - count=1, - passages=True, - passages_fields=['x', 'y'], - logging_opt_out='True', - passages_count=2) - - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) - - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path - assert len(responses.calls) == 1 - - @classmethod - @responses.activate - def test_query_2(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/collections/collid/query') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_expansions_empty(self): + check_empty_required_params(self, fake_response_Expansions_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): responses.add(responses.POST, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - discovery.query('envid', - 'collid', - filter='extracted_metadata.sha1::9181d244*', - count=1, - passages=True, - passages_fields=['x', 'y'], - logging_opt_out='True', - passages_count=2, - bias='1', - collection_ids='1,2') - - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) - - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path - assert len(responses.calls) == 1 - - @classmethod - @responses.activate - def test_query_notices(cls): - discovery_url = urljoin( - base_discovery_url, 'environments/envid/collections/collid/notices') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_expansions(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"expansions": [], }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"expansions": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_expansions +#----------------------------------------------------------------------------- +class TestDeleteExpansions(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_expansions_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.GET, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_expansions_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 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_expansions_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 = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.query_notices('envid', 'collid', filter='notices.sha1::*') - called_url = urlparse(responses.calls[0].request.url) - test_url = urlparse(discovery_url) - assert called_url.netloc == test_url.netloc - assert called_url.path == test_url.path + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_expansions(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_tokenization_dictionary_status +#----------------------------------------------------------------------------- +class TestGetTokenizationDictionaryStatus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_tokenization_dictionary_status_response(self): + body = self.construct_full_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_configs(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/configurations') - discovery_config_id = urljoin( - base_discovery_url, 'environments/envid/configurations/confid') + def test_get_tokenization_dictionary_status_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - results = { - "configurations": [{ - "name": "Default Configuration", - "configuration_id": "confid" - }] - } + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_tokenization_dictionary_status_empty(self): + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): responses.add(responses.GET, - discovery_url, - body=json.dumps(results), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_tokenization_dictionary_status(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_tokenization_dictionary +#----------------------------------------------------------------------------- +class TestCreateTokenizationDictionary(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_tokenization_dictionary_response(self): + body = self.construct_full_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.GET, - discovery_config_id, - body=json.dumps(results['configurations'][0]), - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_tokenization_dictionary_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_tokenization_dictionary_empty(self): + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - discovery_url, - body=json.dumps(results['configurations'][0]), - status=200, - content_type='application/json') - responses.add(responses.PUT, - discovery_config_id, - body=json.dumps(results['configurations'][0]), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=202, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_tokenization_dictionary(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"tokenization_rules": [], }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_tokenization_dictionary +#----------------------------------------------------------------------------- +class TestDeleteTokenizationDictionary(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_tokenization_dictionary_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_tokenization_dictionary_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_tokenization_dictionary_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 = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.DELETE, - discovery_config_id, - body=json.dumps({'deleted': 'bogus -- ok'}), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - discovery.list_configurations(environment_id='envid') - - discovery.get_configuration(environment_id='envid', - configuration_id='confid') - - assert len(responses.calls) == 2 - - discovery.create_configuration(environment_id='envid', name='my name') - discovery.create_configuration(environment_id='envid', - name='my name', - source={ - 'type': 'salesforce', - 'credential_id': 'xxx' - }) - discovery.update_configuration(environment_id='envid', - configuration_id='confid', - name='my new name') - discovery.update_configuration(environment_id='envid', - configuration_id='confid', - name='my new name', - source={ - 'type': 'salesforce', - 'credential_id': 'xxx' - }) - discovery.delete_configuration(environment_id='envid', - configuration_id='confid') - - assert len(responses.calls) == 7 - - @classmethod - @responses.activate - def test_document(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/preview') - config_url = urljoin(base_discovery_url, - 'environments/envid/configurations') - responses.add(responses.POST, - discovery_url, - body="{\"configurations\": []}", - status=200, - content_type='application/json') - responses.add(responses.GET, - config_url, - body=json.dumps({ - "configurations": [{ - "name": "Default Configuration", - "configuration_id": "confid" - }] - }), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - add_doc_url = urljoin( - base_discovery_url, - 'environments/envid/collections/collid/documents') - - doc_id_path = 'environments/envid/collections/collid/documents/docid' - - update_doc_url = urljoin(base_discovery_url, doc_id_path) - del_doc_url = urljoin(base_discovery_url, doc_id_path) - responses.add(responses.POST, - add_doc_url, - body="{\"body\": []}", - status=200, - content_type='application/json') - - doc_status = { - "document_id": - "45556e23-f2b1-449d-8f27-489b514000ff", - "configuration_id": - "2e079259-7dd2-40a9-998f-3e716f5a7b88", - "created": - "2016-06-16T10:56:54.957Z", - "updated": - "2017-05-16T13:56:54.957Z", - "status": - "available", - "status_description": - "Document is successfully ingested and indexed with no warnings", - "notices": [] - } + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_tokenization_dictionary(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_stopword_list_status +#----------------------------------------------------------------------------- +class TestGetStopwordListStatus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_stopword_list_status_response(self): + body = self.construct_full_body() + response = fake_response_TokenDictStatusResponse_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_stopword_list_status_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_stopword_list_status_empty(self): + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - del_doc_url, - body=json.dumps(doc_status), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_stopword_list_status(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_stopword_list +#----------------------------------------------------------------------------- +class TestCreateStopwordList(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_stopword_list_response(self): + body = self.construct_full_body() + response = fake_response_TokenDictStatusResponse_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_create_stopword_list_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TokenDictStatusResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_stopword_list_empty(self): + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - update_doc_url, - body="{\"body\": []}", - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_stopword_list(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['stopword_file'] = tempfile.NamedTemporaryFile() + body['stopword_filename'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['stopword_file'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_stopword_list +#----------------------------------------------------------------------------- +class TestDeleteStopwordList(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_stopword_list_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_stopword_list_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_stopword_list_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 = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.DELETE, - del_doc_url, - body="{\"body\": []}", - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_stopword_list(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: QueryModifications +############################################################################## + +############################################################################## +# Start of Service: Documents +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for add_document +#----------------------------------------------------------------------------- +class TestAddDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_document_response(self): + body = self.construct_full_body() + response = fake_response_DocumentAccepted_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_add_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentAccepted_json + send_request(self, body, response) + assert len(responses.calls) == 1 - html_path = os.path.join(os.getcwd(), 'resources', 'simple.html') - with open(html_path) as fileinfo: - conf_id = discovery.add_document(environment_id='envid', - collection_id='collid', - file=fileinfo) - assert conf_id is not None + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_document_empty(self): + check_empty_required_params(self, fake_response_DocumentAccepted_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/documents'.format(body['environment_id'], body['collection_id']) + 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=202, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.add_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['file'] = tempfile.NamedTemporaryFile() + body['filename'] = "string1" + body['file_content_type'] = "string1" + body['metadata'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_document_status +#----------------------------------------------------------------------------- +class TestGetDocumentStatus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_document_status_response(self): + body = self.construct_full_body() + response = fake_response_DocumentStatus_json + send_request(self, body, response) assert len(responses.calls) == 1 - discovery.get_document_status(environment_id='envid', - collection_id='collid', - document_id='docid') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_document_status_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 2 + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_document_status_empty(self): + check_empty_required_params(self, fake_response_DocumentStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.update_document(environment_id='envid', - collection_id='collid', - document_id='docid') + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_document_status(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_document +#----------------------------------------------------------------------------- +class TestUpdateDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_document_response(self): + body = self.construct_full_body() + response = fake_response_DocumentAccepted_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 3 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentAccepted_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.update_document(environment_id='envid', - collection_id='collid', - document_id='docid') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_document_empty(self): + check_empty_required_params(self, fake_response_DocumentAccepted_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - assert len(responses.calls) == 4 + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=202, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + body['file'] = tempfile.NamedTemporaryFile() + body['filename'] = "string1" + body['file_content_type'] = "string1" + body['metadata'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_document +#----------------------------------------------------------------------------- +class TestDeleteDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_response(self): + body = self.construct_full_body() + response = fake_response_DeleteDocumentResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.delete_document(environment_id='envid', - collection_id='collid', - document_id='docid') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteDocumentResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 5 + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_empty(self): + check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - conf_id = discovery.add_document(environment_id='envid', - collection_id='collid', - file=io.StringIO(u'my string of file'), - filename='file.txt') + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['document_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Documents +############################################################################## + +############################################################################## +# Start of Service: Queries +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for query +#----------------------------------------------------------------------------- +class TestQuery(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_response(self): + body = self.construct_full_body() + response = fake_response_QueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 6 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_QueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - conf_id = discovery.add_document( - environment_id='envid', - collection_id='collid', - file=io.StringIO(u'

my string of file

'), - filename='file.html', - file_content_type='application/html') + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_empty(self): + check_empty_required_params(self, fake_response_QueryResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/query'.format(body['environment_id'], body['collection_id']) + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.query(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", "spelling_suggestions": True, }) + body['x_watson_logging_opt_out'] = True + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for query_notices +#----------------------------------------------------------------------------- +class TestQueryNotices(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_notices_response(self): + body = self.construct_full_body() + response = fake_response_QueryNoticesResponse_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_query_notices_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_QueryNoticesResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 7 + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_notices_empty(self): + check_empty_required_params(self, fake_response_QueryNoticesResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/notices'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - conf_id = discovery.add_document( - environment_id='envid', - collection_id='collid', - file=io.StringIO(u'

my string of file

'), - filename='file.html', - file_content_type='application/html', - metadata=io.StringIO(u'{"stuff": "woot!"}')) + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.query_notices(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['filter'] = "string1" + body['query'] = "string1" + body['natural_language_query'] = "string1" + body['passages'] = True + body['aggregation'] = "string1" + body['count'] = 12345 + body['return_'] = [] + body['offset'] = 12345 + body['sort'] = [] + body['highlight'] = True + body['passages_fields'] = [] + body['passages_count'] = 12345 + body['passages_characters'] = 12345 + body['deduplicate_field'] = "string1" + body['similar'] = True + body['similar_document_ids'] = [] + body['similar_fields'] = [] + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for federated_query +#----------------------------------------------------------------------------- +class TestFederatedQuery(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_federated_query_response(self): + body = self.construct_full_body() + response = fake_response_QueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 8 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_federated_query_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_QueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_delete_all_training_data(cls): - training_endpoint = '/v1/environments/{0}/collections/{1}/training_data' - endpoint = training_endpoint.format(environment_id, collection_id) + def test_federated_query_empty(self): + check_empty_required_params(self, fake_response_QueryResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/query'.format(body['environment_id']) url = '{0}{1}'.format(base_url, endpoint) - responses.add(responses.DELETE, url, status=204) + return url - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.federated_query(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) + body['x_watson_logging_opt_out'] = True + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for federated_query_notices +#----------------------------------------------------------------------------- +class TestFederatedQueryNotices(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_federated_query_notices_response(self): + body = self.construct_full_body() + response = fake_response_QueryNoticesResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - response = discovery.delete_all_training_data( - environment_id=environment_id, - collection_id=collection_id).get_result() + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_federated_query_notices_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_QueryNoticesResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert response is None + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_federated_query_notices_empty(self): + check_empty_required_params(self, fake_response_QueryNoticesResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/notices'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - @classmethod + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.federated_query_notices(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_ids'] = [] + body['filter'] = "string1" + body['query'] = "string1" + body['natural_language_query'] = "string1" + body['aggregation'] = "string1" + body['count'] = 12345 + body['return_'] = [] + body['offset'] = 12345 + body['sort'] = [] + body['highlight'] = True + body['deduplicate_field'] = "string1" + body['similar'] = True + body['similar_document_ids'] = [] + body['similar_fields'] = [] + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_ids'] = [] + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_autocompletion +#----------------------------------------------------------------------------- +class TestGetAutocompletion(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_list_training_data(cls): - training_endpoint = '/v1/environments/{0}/collections/{1}/training_data' - endpoint = training_endpoint.format(environment_id, collection_id) + def test_get_autocompletion_response(self): + body = self.construct_full_body() + response = fake_response_Completions_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_autocompletion_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Completions_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_autocompletion_empty(self): + check_empty_required_params(self, fake_response_Completions_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/autocompletion'.format(body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) - mock_response = { - "environment_id": - "string", - "collection_id": - "string", - "queries": [{ - "query_id": - "string", - "natural_language_query": - "string", - "filter": - "string", - "examples": [{ - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - }] - }] - } + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(mock_response), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_autocompletion(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['prefix'] = "string1" + body['field'] = "string1" + body['count'] = 12345 + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['prefix'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Queries +############################################################################## + +############################################################################## +# Start of Service: TrainingData +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_training_data +#----------------------------------------------------------------------------- +class TestListTrainingData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_training_data_response(self): + body = self.construct_full_body() + response = fake_response_TrainingDataSet_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_training_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingDataSet_json + send_request(self, body, response) + assert len(responses.calls) == 1 - response = discovery.list_training_data( - environment_id=environment_id, - collection_id=collection_id).get_result() + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_training_data_empty(self): + check_empty_required_params(self, fake_response_TrainingDataSet_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - assert response == mock_response - # Verify that response can be converted to a TrainingDataSet - TrainingDataSet._from_dict(response) + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_training_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_training_data +#----------------------------------------------------------------------------- +class TestAddTrainingData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_training_data_response(self): + body = self.construct_full_body() + response = fake_response_TrainingQuery_json + send_request(self, body, response) + assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- @responses.activate - def test_add_training_data(cls): - training_endpoint = '/v1/environments/{0}/collections/{1}/training_data' - endpoint = training_endpoint.format(environment_id, collection_id) + def test_add_training_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingQuery_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_training_data_empty(self): + check_empty_required_params(self, fake_response_TrainingQuery_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) - natural_language_query = "why is the sky blue" - filter = "text:meteorology" - examples = [{ - "document_id": "54f95ac0-3e4f-4756-bea6-7a67b2713c81", - "relevance": 1 - }, { - "document_id": "01bcca32-7300-4c9f-8d32-33ed7ea643da", - "cross_reference": "my_id_field:1463", - "relevance": 5 - }] - mock_response = { - "query_id": - "string", - "natural_language_query": - "string", - "filter": - "string", - "examples": [{ - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - }] - } + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(mock_response), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - response = discovery.add_training_data( - environment_id=environment_id, - collection_id=collection_id, - natural_language_query=natural_language_query, - filter=filter, - examples=examples).get_result() - - assert response == mock_response - # Verify that response can be converted to a TrainingQuery - TrainingQuery._from_dict(response) - - @classmethod - @responses.activate - def test_delete_training_data(cls): - training_endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}' - query_id = 'queryid' - endpoint = training_endpoint.format(environment_id, collection_id, - query_id) + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.add_training_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_all_training_data +#----------------------------------------------------------------------------- +class TestDeleteAllTrainingData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_all_training_data_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_all_training_data_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_all_training_data_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 = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) + 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=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_all_training_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_training_data +#----------------------------------------------------------------------------- +class TestGetTrainingData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_data_response(self): + body = self.construct_full_body() + response = fake_response_TrainingQuery_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_training_data_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingQuery_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_data_empty(self): + check_empty_required_params(self, fake_response_TrainingQuery_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) - responses.add(responses.DELETE, url, status=204) + return url - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_training_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_training_data +#----------------------------------------------------------------------------- +class TestDeleteTrainingData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_training_data_response(self): + body = self.construct_full_body() + response = fake_response__json + send_request(self, body, response) + assert len(responses.calls) == 1 - response = discovery.delete_training_data( - environment_id=environment_id, - collection_id=collection_id, - query_id=query_id).get_result() + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_training_data_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 - assert response is None + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_training_data_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 = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url - @classmethod + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_training_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_training_examples +#----------------------------------------------------------------------------- +class TestListTrainingExamples(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_get_training_data(cls): - training_endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}' - query_id = 'queryid' - endpoint = training_endpoint.format(environment_id, collection_id, - query_id) + def test_list_training_examples_response(self): + body = self.construct_full_body() + response = fake_response_TrainingExampleList_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_training_examples_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingExampleList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_training_examples_empty(self): + check_empty_required_params(self, fake_response_TrainingExampleList_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) - mock_response = { - "query_id": - "string", - "natural_language_query": - "string", - "filter": - "string", - "examples": [{ - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - }] - } + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(mock_response), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - response = discovery.get_training_data(environment_id=environment_id, - collection_id=collection_id, - query_id=query_id).get_result() - - assert response == mock_response - # Verify that response can be converted to a TrainingQuery - TrainingQuery._from_dict(response) - - @classmethod - @responses.activate - def test_create_training_example(cls): - examples_endpoint = '/v1/environments/{0}/collections/{1}/training_data' + \ - '/{2}/examples' - query_id = 'queryid' - endpoint = examples_endpoint.format(environment_id, collection_id, - query_id) + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_training_examples(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_training_example +#----------------------------------------------------------------------------- +class TestCreateTrainingExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_training_example_response(self): + body = self.construct_full_body() + response = fake_response_TrainingExample_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_create_training_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingExample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_training_example_empty(self): + check_empty_required_params(self, fake_response_TrainingExample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_id']) url = '{0}{1}'.format(base_url, endpoint) - document_id = "string" - relevance = 0 - cross_reference = "string" - mock_response = { - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - } + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(mock_response), - status=201, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - response = discovery.create_training_example( - environment_id=environment_id, - collection_id=collection_id, - query_id=query_id, - document_id=document_id, - relevance=relevance, - cross_reference=cross_reference).get_result() - - assert response == mock_response - # Verify that response can be converted to a TrainingExample - TrainingExample._from_dict(response) - - @classmethod - @responses.activate - def test_delete_training_example(cls): - examples_endpoint = '/v1/environments/{0}/collections/{1}/training_data' + \ - '/{2}/examples/{3}' - query_id = 'queryid' - example_id = 'exampleid' - endpoint = examples_endpoint.format(environment_id, collection_id, - query_id, example_id) - url = '{0}{1}'.format(base_url, endpoint) - responses.add(responses.DELETE, url, status=204) - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - response = discovery.delete_training_example( - environment_id=environment_id, - collection_id=collection_id, - query_id=query_id, - example_id=example_id).get_result() - - assert response is None - - @classmethod - @responses.activate - def test_get_training_example(cls): - examples_endpoint = '/v1/environments/{0}/collections/{1}/training_data' + \ - '/{2}/examples/{3}' - query_id = 'queryid' - example_id = 'exampleid' - endpoint = examples_endpoint.format(environment_id, collection_id, - query_id, example_id) + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_training_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_training_example +#----------------------------------------------------------------------------- +class TestDeleteTrainingExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_training_example_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_training_example_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_training_example_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 = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) url = '{0}{1}'.format(base_url, endpoint) - mock_response = { - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - } - responses.add(responses.GET, - url, - body=json.dumps(mock_response), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - response = discovery.get_training_example( - environment_id=environment_id, - collection_id=collection_id, - query_id=query_id, - example_id=example_id).get_result() - - assert response == mock_response - # Verify that response can be converted to a TrainingExample - TrainingExample._from_dict(response) - - @classmethod - @responses.activate - def test_update_training_example(cls): - examples_endpoint = '/v1/environments/{0}/collections/{1}/training_data' + \ - '/{2}/examples/{3}' - query_id = 'queryid' - example_id = 'exampleid' - endpoint = examples_endpoint.format(environment_id, collection_id, - query_id, example_id) + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_training_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_training_example +#----------------------------------------------------------------------------- +class TestUpdateTrainingExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_training_example_response(self): + body = self.construct_full_body() + response = fake_response_TrainingExample_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_training_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingExample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_training_example_empty(self): + check_empty_required_params(self, fake_response_TrainingExample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) url = '{0}{1}'.format(base_url, endpoint) - relevance = 0 - cross_reference = "string" - mock_response = { - "document_id": "string", - "cross_reference": "string", - "relevance": 0 - } + return url + + def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(mock_response), - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - response = discovery.update_training_example( - environment_id=environment_id, - collection_id=collection_id, - query_id=query_id, - example_id=example_id, - relevance=relevance, - cross_reference=cross_reference).get_result() - - assert response == mock_response - # Verify that response can be converted to a TrainingExample - TrainingExample._from_dict(response) - - @classmethod - @responses.activate - def test_expansions(cls): - url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/expansions' + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_training_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + body.update({"cross_reference": "string1", "relevance": 12345, }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + body.update({"cross_reference": "string1", "relevance": 12345, }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_training_example +#----------------------------------------------------------------------------- +class TestGetTrainingExample(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_example_response(self): + body = self.construct_full_body() + response = fake_response_TrainingExample_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_training_example_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingExample_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_training_example_empty(self): + check_empty_required_params(self, fake_response_TrainingExample_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body='{"expansions": "results"}', - status=200, - content_type='application_json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_training_example(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['collection_id'] = "string1" + body['query_id'] = "string1" + body['example_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: TrainingData +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_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_user_data_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_user_data_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 = '/v1/user_data' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body='{"description": "success" }', - status=200, - content_type='application_json') + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + +############################################################################## +# Start of Service: EventsAndFeedback +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for create_event +#----------------------------------------------------------------------------- +class TestCreateEvent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_event_response(self): + body = self.construct_full_body() + response = fake_response_CreateEventResponse_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_create_event_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CreateEventResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_event_empty(self): + check_empty_required_params(self, fake_response_CreateEventResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/events' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body='{"expansions": "success" }', - status=200, - content_type='application_json') + url, + body=json.dumps(response), + status=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_event(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) + return body + + def construct_required_body(self): + body = dict() + body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for query_log +#----------------------------------------------------------------------------- +class TestQueryLog(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_log_response(self): + body = self.construct_full_body() + response = fake_response_LogQueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_log_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LogQueryResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.list_expansions('envid', 'colid') - assert responses.calls[0].response.json() == {"expansions": "results"} + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_query_log_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 - discovery.create_expansions('envid', 'colid', [{ - "input_terms": "dumb", - "expanded_terms": "dumb2" - }]) - assert responses.calls[1].response.json() == {"expansions": "success"} + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/logs' + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.delete_expansions('envid', 'colid') - assert responses.calls[2].response.json() == {"description": "success"} + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.query_log(**body) + return output + + def construct_full_body(self): + body = dict() + body['filter'] = "string1" + body['query'] = "string1" + body['count'] = 12345 + body['offset'] = 12345 + body['sort'] = [] + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_metrics_query +#----------------------------------------------------------------------------- +class TestGetMetricsQuery(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_response(self): + body = self.construct_full_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 3 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_delete_user_data(cls): - url = 'https://gateway.watsonplatform.net/discovery/api/v1/user_data' - responses.add(responses.DELETE, - url, - body='{"description": "success" }', - status=204, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - response = discovery.delete_user_data('id').get_result() - assert response is None - assert len(responses.calls) == 1 - - @classmethod - @responses.activate - def test_credentials(cls): - discovery_credentials_url = urljoin(base_discovery_url, - 'environments/envid/credentials') - - results = { - 'credential_id': 'e68305ce-29f3-48ea-b829-06653ca0fdef', - 'source_type': 'salesforce', - 'credential_details': { - 'url': 'https://login.salesforce.com', - 'credential_type': 'username_password', - 'username': 'user@email.com' - } - } - authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + def test_get_metrics_query_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/metrics/number_of_queries' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - "{0}/{1}?version=2018-08-13".format( - discovery_credentials_url, 'credential_id'), - body=json.dumps(results), - status=200, - content_type='application/json') - responses.add( - responses.GET, - "{0}?version=2018-08-13".format(discovery_credentials_url), - body=json.dumps([results]), - status=200, - content_type='application/json') - - responses.add( - responses.POST, - "{0}?version=2018-08-13".format(discovery_credentials_url), - body=json.dumps(results), - status=200, - content_type='application/json') - results['source_type'] = 'ibm' - responses.add(responses.PUT, - "{0}/{1}?version=2018-08-13".format( - discovery_credentials_url, 'credential_id'), - body=json.dumps(results), - status=200, - content_type='application/json') - responses.add(responses.DELETE, - "{0}/{1}?version=2018-08-13".format( - discovery_credentials_url, 'credential_id'), - body=json.dumps({'deleted': 'bogus -- ok'}), - status=200, - content_type='application/json') - - discovery.create_credentials('envid', - source_type='salesforce', - credential_details={ - 'url': 'https://login.salesforce.com', - 'credential_type': 'username_password', - 'username': 'user@email.com' - }) - - discovery.get_credentials('envid', 'credential_id') - - discovery.update_credentials( - environment_id='envid', - credential_id='credential_id', - source_type='salesforce', - credential_details=results['credential_details']) - discovery.list_credentials('envid') - discovery.delete_credentials(environment_id='envid', - credential_id='credential_id') - assert len(responses.calls) == 10 - - @classmethod - @responses.activate - def test_events_and_feedback(cls): - discovery_event_url = urljoin(base_discovery_url, 'events') - discovery_metrics_event_rate_url = urljoin(base_discovery_url, - 'metrics/event_rate') - discovery_metrics_query_url = urljoin(base_discovery_url, - 'metrics/number_of_queries') - discovery_metrics_query_event_url = urljoin( - base_discovery_url, 'metrics/number_of_queries_with_event') - discovery_metrics_query_no_results_url = urljoin( - base_discovery_url, - 'metrics/number_of_queries_with_no_search_results') - discovery_metrics_query_token_event_url = urljoin( - base_discovery_url, 'metrics/top_query_tokens_with_event_rate') - discovery_query_log_url = urljoin(base_discovery_url, 'logs') - - event_data = { - "environment_id": "xxx", - "session_token": "yyy", - "client_timestamp": "2018-08-14T14:39:59.268Z", - "display_rank": 0, - "collection_id": "abc", - "document_id": "xyz", - "query_id": "cde" - } - - create_event_response = {"type": "click", "data": event_data} - - metric_response = { - "aggregations": [{ - "interval": - "1d", - "event_type": - "click", - "results": [{ - "key_as_string": "2018-08-14T14:39:59.309Z", - "key": 1533513600000, - "matching_results": 2, - "event_rate": 0.0 - }] - }] - } - - metric_token_response = { - "aggregations": [{ - "event_type": - "click", - "results": [{ - "key": "content", - "matching_results": 5, - "event_rate": 0.6 - }, { - "key": "first", - "matching_results": 5, - "event_rate": 0.6 - }, { - "key": "of", - "matching_results": 5, - "event_rate": 0.6 - }] - }] - } - - log_query_response = { - "matching_results": - 20, - "results": [{ - "customer_id": "", - "environment_id": "xxx", - "natural_language_query": "The content of the first chapter", - "query_id": "1ICUdh3Pab", - "document_results": { - "count": - 1, - "results": [{ - "collection_id": "b67a82f3-6507-4c25-9757-3485ff4f2a32", - "score": 0.025773458, - "position": 10, - "document_id": "af0be20e-e130-4712-9a2e-37d9c8b9c52f" - }] - }, - "event_type": "query", - "session_token": "1_nbEfQtKVcg9qx3t41ICUdh3Pab", - "created_timestamp": "2018-08-14T18:20:30.460Z" - }] - } + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_metrics_query(**body) + return output + + def construct_full_body(self): + body = dict() + body['start_time'] = datetime.now() + body['end_time'] = datetime.now() + body['result_type'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_metrics_query_event +#----------------------------------------------------------------------------- +class TestGetMetricsQueryEvent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_event_response(self): + body = self.construct_full_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - responses.add(responses.POST, - "{0}?version=2018-08-13".format(discovery_event_url), - body=json.dumps(create_event_response), - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" - .format(discovery_metrics_event_rate_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" - .format(discovery_metrics_query_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" - .format(discovery_metrics_query_event_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') - responses.add( - responses.GET, - "{0}?version=2018-08-13&start_time=2018-08-13T14%3A39%3A59.309Z&end_time=2018-08-14T14%3A39%3A59.309Z&result_type=document" - .format(discovery_metrics_query_no_results_url), - body=json.dumps(metric_response), - status=200, - content_type='application/json') + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_event_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_event_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/metrics/number_of_queries_with_event' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - "{0}?version=2018-08-13&count=2".format( - discovery_metrics_query_token_event_url), - body=json.dumps(metric_token_response), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_metrics_query_event(**body) + return output + + def construct_full_body(self): + body = dict() + body['start_time'] = datetime.now() + body['end_time'] = datetime.now() + body['result_type'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_metrics_query_no_results +#----------------------------------------------------------------------------- +class TestGetMetricsQueryNoResults(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_no_results_response(self): + body = self.construct_full_body() + response = fake_response_MetricResponse_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_metrics_query_no_results_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_no_results_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/metrics/number_of_queries_with_no_search_results' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - "{0}?version=2018-08-13".format(discovery_query_log_url), - body=json.dumps(log_query_response), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_metrics_query_no_results(**body) + return output + + def construct_full_body(self): + body = dict() + body['start_time'] = datetime.now() + body['end_time'] = datetime.now() + body['result_type'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_metrics_event_rate +#----------------------------------------------------------------------------- +class TestGetMetricsEventRate(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_event_rate_response(self): + body = self.construct_full_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_event_rate_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MetricResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.create_event('click', event_data) - assert responses.calls[1].response.json()["data"] == event_data + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_event_rate_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 - discovery.get_metrics_event_rate(start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document') - assert responses.calls[3].response.json() == metric_response + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/metrics/event_rate' + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.get_metrics_query(start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document') - assert responses.calls[5].response.json() == metric_response + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_metrics_event_rate(**body) + return output + + def construct_full_body(self): + body = dict() + body['start_time'] = datetime.now() + body['end_time'] = datetime.now() + body['result_type'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_metrics_query_token_event +#----------------------------------------------------------------------------- +class TestGetMetricsQueryTokenEvent(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_token_event_response(self): + body = self.construct_full_body() + response = fake_response_MetricTokenResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.get_metrics_query_event(start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document') - assert responses.calls[7].response.json() == metric_response + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_token_event_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MetricTokenResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 - discovery.get_metrics_query_no_results( - start_time='2018-08-13T14:39:59.309Z', - end_time='2018-08-14T14:39:59.309Z', - result_type='document') - assert responses.calls[9].response.json() == metric_response + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_metrics_query_token_event_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 - discovery.get_metrics_query_token_event(count=2) - assert responses.calls[11].response.json() == metric_token_response + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/metrics/top_query_tokens_with_event_rate' + url = '{0}{1}'.format(base_url, endpoint) + return url - discovery.query_log() - assert responses.calls[13].response.json() == log_query_response + 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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_metrics_query_token_event(**body) + return output + + def construct_full_body(self): + body = dict() + body['count'] = 12345 + return body + + def construct_required_body(self): + body = dict() + return body + + +# endregion +############################################################################## +# End of Service: EventsAndFeedback +############################################################################## + +############################################################################## +# Start of Service: Credentials +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_credentials +#----------------------------------------------------------------------------- +class TestListCredentials(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_credentials_response(self): + body = self.construct_full_body() + response = fake_response_CredentialsList_json + send_request(self, body, response) + assert len(responses.calls) == 1 - assert len(responses.calls) == 14 + #-------------------------------------------------------- + # Test 2: Send only required fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_credentials_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CredentialsList_json + send_request(self, body, response) + assert len(responses.calls) == 1 - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_tokenization_dictionary(cls): - url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/word_lists/tokenization_dictionary?version=2018-08-13' - responses.add(responses.POST, - url, - body='{"status": "pending"}', - status=200, - content_type='application_json') - responses.add(responses.DELETE, - url, - body='{"status": "pending"}', - status=200) - responses.add( - responses.GET, - url, - body='{"status": "pending", "type":"tokenization_dictionary"}', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - tokenization_rules = [{ - 'text': 'token', - 'tokens': ['token 1', 'token 2'], - 'readings': ['reading 1', 'reading 2'], - 'part_of_speech': 'noun', - }] - - discovery.create_tokenization_dictionary( - 'envid', 'colid', tokenization_rules=tokenization_rules) - assert responses.calls[0].response.json() == {"status": "pending"} - - discovery.get_tokenization_dictionary_status('envid', 'colid') - assert responses.calls[1].response.json() == { - "status": "pending", - "type": "tokenization_dictionary" - } - - discovery.delete_tokenization_dictionary('envid', 'colid') - assert responses.calls[2].response.status_code == 200 - - assert len(responses.calls) == 3 - - @classmethod - @responses.activate - def test_stopword_operations(cls): - url = 'https://gateway.watsonplatform.net/discovery/api/v1/environments/envid/collections/colid/word_lists/stopwords?version=2018-08-13' + def test_list_credentials_empty(self): + check_empty_required_params(self, fake_response_CredentialsList_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/credentials'.format(body['environment_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 = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_credentials(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_credentials +#----------------------------------------------------------------------------- +class TestCreateCredentials(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_credentials_response(self): + body = self.construct_full_body() + response = fake_response_Credentials_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_create_credentials_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Credentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_credentials_empty(self): + check_empty_required_params(self, fake_response_Credentials_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/credentials'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body='{"status": "pending", "type": "stopwords"}', - status=200, - content_type='application_json') - responses.add(responses.DELETE, url, status=200) + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_credentials(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_credentials +#----------------------------------------------------------------------------- +class TestGetCredentials(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_credentials_response(self): + body = self.construct_full_body() + response = fake_response_Credentials_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_credentials_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Credentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_credentials_empty(self): + check_empty_required_params(self, fake_response_Credentials_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body='{"status": "ready", "type": "stopwords"}', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - stopwords_file_path = os.path.join(os.getcwd(), 'resources', - 'stopwords.txt') - with open(stopwords_file_path) as file: - discovery.create_stopword_list('envid', 'colid', file) - assert responses.calls[0].response.json() == { - "status": "pending", - "type": "stopwords" - } - - discovery.get_stopword_list_status('envid', 'colid') - assert responses.calls[1].response.json() == { - "status": "ready", - "type": "stopwords" - } - - discovery.delete_stopword_list('envid', 'colid') - assert responses.calls[2].response.status_code == 200 - - assert len(responses.calls) == 3 - - @classmethod - @responses.activate - def test_gateway_configuration(cls): - discovery_gateway_url = urljoin(base_discovery_url, - 'environments/envid/gateways') - - gateway_details = { - "status": "idle", - "token_id": "9GnaCreixek_prod_ng", - "token": "4FByv9Mmd79x6c", - "name": "test-gateway-configuration-python", - "gateway_id": "gateway_id" - } + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_credentials(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_credentials +#----------------------------------------------------------------------------- +class TestUpdateCredentials(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_credentials_response(self): + body = self.construct_full_body() + response = fake_response_Credentials_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_credentials_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Credentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_credentials_empty(self): + check_empty_required_params(self, fake_response_Credentials_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.update_credentials(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_credentials +#----------------------------------------------------------------------------- +class TestDeleteCredentials(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_credentials_response(self): + body = self.construct_full_body() + response = fake_response_DeleteCredentials_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_credentials_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteCredentials_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_credentials_empty(self): + check_empty_required_params(self, fake_response_DeleteCredentials_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + 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='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_credentials(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['credential_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Credentials +############################################################################## + +############################################################################## +# Start of Service: GatewayConfiguration +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_gateways +#----------------------------------------------------------------------------- +class TestListGateways(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_gateways_response(self): + body = self.construct_full_body() + response = fake_response_GatewayList_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_gateways_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_GatewayList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_gateways_empty(self): + check_empty_required_params(self, fake_response_GatewayList_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/gateways'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - "{0}/{1}?version=2018-08-13".format( - discovery_gateway_url, 'gateway_id'), - body=json.dumps(gateway_details), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.list_gateways(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_gateway +#----------------------------------------------------------------------------- +class TestCreateGateway(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_gateway_response(self): + body = self.construct_full_body() + response = fake_response_Gateway_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_create_gateway_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Gateway_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_gateway_empty(self): + check_empty_required_params(self, fake_response_Gateway_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/gateways'.format(body['environment_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - "{0}?version=2018-08-13".format(discovery_gateway_url), - body=json.dumps(gateway_details), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.create_gateway(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body.update({"name": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_gateway +#----------------------------------------------------------------------------- +class TestGetGateway(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_gateway_response(self): + body = self.construct_full_body() + response = fake_response_Gateway_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_gateway_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Gateway_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_gateway_empty(self): + check_empty_required_params(self, fake_response_Gateway_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - "{0}?version=2018-08-13".format(discovery_gateway_url), - body=json.dumps({'gateways': [gateway_details]}), - status=200, - content_type='application/json') + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.get_gateway(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['gateway_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['gateway_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_gateway +#----------------------------------------------------------------------------- +class TestDeleteGateway(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_gateway_response(self): + body = self.construct_full_body() + response = fake_response_GatewayDelete_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_gateway_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_GatewayDelete_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_gateway_empty(self): + check_empty_required_params(self, fake_response_GatewayDelete_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.DELETE, - "{0}/{1}?version=2018-08-13".format( - discovery_gateway_url, 'gateway_id'), - body=json.dumps({ - 'gateway_id': 'gateway_id', - 'status': 'deleted' - }), - status=200, - content_type='application/json') - - authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - discovery.create_gateway('envid', name='gateway_id') - discovery.list_gateways('envid') - discovery.get_gateway('envid', 'gateway_id') - discovery.delete_gateway(environment_id='envid', - gateway_id='gateway_id') - assert len(responses.calls) == 8 - - @responses.activate - def test_get_autocompletion(self): - endpoint = 'environments/{0}/collections/{1}/autocompletion?version=2018-08-13&field=field&prefix=prefix&count=count'.format( - 'environment_id', 'collection_id').format('collection_id') - url = '{0}{1}'.format(base_discovery_url, endpoint) - print('hello') - print(url) - response = {"completions": ["completions", "completions"]} - responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - authenticator = IAMAuthenticator('iam_apikey') - discovery = ibm_watson.DiscoveryV1('2018-08-13', - authenticator=authenticator) - - detailed_response = discovery.get_autocompletion( - environment_id='environment_id', - collection_id='collection_id', - field='field', - prefix='prefix', - count='count') - result = detailed_response.get_result() - assert result is not None - assert len(responses.calls) == 2 + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version='2019-04-30', + ) + service.set_service_url(base_url) + output = service.delete_gateway(**body) + return output + + def construct_full_body(self): + body = dict() + body['environment_id'] = "string1" + body['gateway_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['environment_id'] = "string1" + body['gateway_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: GatewayConfiguration +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"indexed": 7, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" +fake_response_ListEnvironmentsResponse_json = """{"environments": []}""" +fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"indexed": 7, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" +fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"indexed": 7, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" +fake_response_DeleteEnvironmentResponse_json = """{"environment_id": "fake_environment_id", "status": "fake_status"}""" +fake_response_ListCollectionFieldsResponse_json = """{"fields": []}""" +fake_response_Configuration_json = """{"configuration_id": "fake_configuration_id", "name": "fake_name", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "description": "fake_description", "conversions": {"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}, "enrichments": [], "normalizations": [], "source": {"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}}""" +fake_response_ListConfigurationsResponse_json = """{"configurations": []}""" +fake_response_Configuration_json = """{"configuration_id": "fake_configuration_id", "name": "fake_name", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "description": "fake_description", "conversions": {"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}, "enrichments": [], "normalizations": [], "source": {"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}}""" +fake_response_Configuration_json = """{"configuration_id": "fake_configuration_id", "name": "fake_name", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "description": "fake_description", "conversions": {"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}, "enrichments": [], "normalizations": [], "source": {"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}}""" +fake_response_DeleteConfigurationResponse_json = """{"configuration_id": "fake_configuration_id", "status": "fake_status", "notices": []}""" +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", "status": "fake_status", "configuration_id": "fake_configuration_id", "language": "fake_language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2017-05-16T13:56:54.957Z", "data_updated": "2017-05-16T13:56:54.957Z"}, "crawl_status": {"source_crawl": {"status": "fake_status", "next_crawl": "2017-05-16T13:56:54.957Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}""" +fake_response_ListCollectionsResponse_json = """{"collections": []}""" +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", "status": "fake_status", "configuration_id": "fake_configuration_id", "language": "fake_language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2017-05-16T13:56:54.957Z", "data_updated": "2017-05-16T13:56:54.957Z"}, "crawl_status": {"source_crawl": {"status": "fake_status", "next_crawl": "2017-05-16T13:56:54.957Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}""" +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", "status": "fake_status", "configuration_id": "fake_configuration_id", "language": "fake_language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2017-05-16T13:56:54.957Z", "data_updated": "2017-05-16T13:56:54.957Z"}, "crawl_status": {"source_crawl": {"status": "fake_status", "next_crawl": "2017-05-16T13:56:54.957Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}""" +fake_response_DeleteCollectionResponse_json = """{"collection_id": "fake_collection_id", "status": "fake_status"}""" +fake_response_ListCollectionFieldsResponse_json = """{"fields": []}""" +fake_response_Expansions_json = """{"expansions": []}""" +fake_response_Expansions_json = """{"expansions": []}""" +fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" +fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" +fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" +fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" +fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status", "notices": []}""" +fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "configuration_id": "fake_configuration_id", "status": "fake_status", "status_description": "fake_status_description", "filename": "fake_filename", "file_type": "fake_file_type", "sha1": "fake_sha1", "notices": []}""" +fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status", "notices": []}""" +fake_response_DeleteDocumentResponse_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" +fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18, "session_token": "fake_session_token", "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query"}""" +fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18}""" +fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18, "session_token": "fake_session_token", "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query"}""" +fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18}""" +fake_response_Completions_json = """{"completions": []}""" +fake_response_TrainingDataSet_json = """{"environment_id": "fake_environment_id", "collection_id": "fake_collection_id", "queries": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" +fake_response_TrainingExampleList_json = """{"examples": []}""" +fake_response_TrainingExample_json = """{"document_id": "fake_document_id", "cross_reference": "fake_cross_reference", "relevance": 9}""" +fake_response_TrainingExample_json = """{"document_id": "fake_document_id", "cross_reference": "fake_cross_reference", "relevance": 9}""" +fake_response_TrainingExample_json = """{"document_id": "fake_document_id", "cross_reference": "fake_cross_reference", "relevance": 9}""" +fake_response_CreateEventResponse_json = """{"type": "fake_type", "data": {"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}}""" +fake_response_LogQueryResponse_json = """{"matching_results": 16, "results": []}""" +fake_response_MetricResponse_json = """{"aggregations": []}""" +fake_response_MetricResponse_json = """{"aggregations": []}""" +fake_response_MetricResponse_json = """{"aggregations": []}""" +fake_response_MetricResponse_json = """{"aggregations": []}""" +fake_response_MetricTokenResponse_json = """{"aggregations": []}""" +fake_response_CredentialsList_json = """{"credentials": []}""" +fake_response_Credentials_json = """{"credential_id": "fake_credential_id", "source_type": "fake_source_type", "credential_details": {"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}, "status": "fake_status"}""" +fake_response_Credentials_json = """{"credential_id": "fake_credential_id", "source_type": "fake_source_type", "credential_details": {"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}, "status": "fake_status"}""" +fake_response_Credentials_json = """{"credential_id": "fake_credential_id", "source_type": "fake_source_type", "credential_details": {"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}, "status": "fake_status"}""" +fake_response_DeleteCredentials_json = """{"credential_id": "fake_credential_id", "status": "fake_status"}""" +fake_response_GatewayList_json = """{"gateways": []}""" +fake_response_Gateway_json = """{"gateway_id": "fake_gateway_id", "name": "fake_name", "status": "fake_status", "token": "fake_token", "token_id": "fake_token_id"}""" +fake_response_Gateway_json = """{"gateway_id": "fake_gateway_id", "name": "fake_name", "status": "fake_status", "token": "fake_token", "token_id": "fake_token_id"}""" +fake_response_GatewayDelete_json = """{"gateway_id": "fake_gateway_id", "status": "fake_status"}""" From 2f142fb21953c3afa10c4f0ed6f8e4922cfa8672 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 15:02:07 -0500 Subject: [PATCH 175/455] refactor(discoveryv2): regenerate discovery v2 with tests --- ibm_watson/discovery_v2.py | 3168 +++++++++++++++++++------------- test/unit/test_discovery_v2.py | 341 ++-- 2 files changed, 2091 insertions(+), 1418 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index ef9dc5b8f..0af5456bd 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,13 +22,21 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService 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 import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +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 +from typing import List +from typing import TextIO +import sys ############################################################################## # Service @@ -38,13 +46,15 @@ class DiscoveryV2(BaseService): """The Discovery V2 service.""" - default_service_url = None + DEFAULT_SERVICE_URL = None + DEFAULT_SERVICE_NAME = 'discovery' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Discovery service. @@ -63,30 +73,20 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('discovery') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('discovery') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Collections ######################### - def list_collections(self, project_id, **kwargs): + def list_collections(self, project_id: str, **kwargs) -> 'DetailedResponse': """ List collections. @@ -105,7 +105,9 @@ def list_collections(self, project_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', 'list_collections') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_collections') headers.update(sdk_headers) params = {'version': self.version} @@ -115,8 +117,8 @@ def list_collections(self, project_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -125,23 +127,23 @@ def list_collections(self, project_id, **kwargs): ######################### def query(self, - project_id, + project_id: str, *, - collection_ids=None, - filter=None, - query=None, - natural_language_query=None, - aggregation=None, - count=None, - return_=None, - offset=None, - sort=None, - highlight=None, - spelling_suggestions=None, - table_results=None, - suggested_refinements=None, - passages=None, - **kwargs): + collection_ids: List[str] = None, + filter: str = None, + query: str = None, + natural_language_query: str = None, + aggregation: str = None, + count: int = None, + return_: List[str] = None, + offset: int = None, + sort: str = None, + highlight: bool = None, + spelling_suggestions: bool = None, + table_results: 'QueryLargeTableResults' = None, + suggested_refinements: 'QueryLargeSuggestedRefinements' = None, + passages: 'QueryLargePassages' = None, + **kwargs) -> 'DetailedResponse': """ Query a project. @@ -150,7 +152,7 @@ def query(self, :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. - :param list[str] collection_ids: (optional) A comma-separated list of + :param List[str] collection_ids: (optional) A comma-separated list of collection IDs to be queried against. :param str filter: (optional) A cacheable query that excludes documents that don't mention the query content. Filter searches are better for @@ -167,7 +169,7 @@ def query(self, applications to build lists, tables, and time series. For a full list of possible aggregations, see the Query reference. :param int count: (optional) Number of results to return. - :param list[str] return_: (optional) A list of the fields in the document + :param List[str] return_: (optional) A list of the fields in the document hierarchy to return. If this parameter not specified, then all top-level fields are returned. :param int offset: (optional) The number of query results to skip at the @@ -209,7 +211,9 @@ def query(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', 'query') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query') headers.update(sdk_headers) params = {'version': self.version} @@ -237,19 +241,19 @@ def query(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def get_autocompletion(self, - project_id, - prefix, + project_id: str, + prefix: str, *, - collection_ids=None, - field=None, - count=None, - **kwargs): + collection_ids: List[str] = None, + field: str = None, + count: int = None, + **kwargs) -> 'DetailedResponse': """ Get Autocomplete Suggestions. @@ -260,7 +264,7 @@ def get_autocompletion(self, :param str prefix: The prefix to use for autocompletion. For example, the prefix `Ho` could autocomplete to `Hot`, `Housing`, or `How do I upgrade`. Possible completions are. - :param list[str] collection_ids: (optional) Comma separated list of the + :param List[str] collection_ids: (optional) Comma separated list of the collection IDs. If this parameter is not specified, all collections in the project are used. :param str field: (optional) The field in the result documents that @@ -280,7 +284,9 @@ def get_autocompletion(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', 'get_autocompletion') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_autocompletion') headers.update(sdk_headers) params = { @@ -296,20 +302,20 @@ def get_autocompletion(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def query_notices(self, - project_id, + project_id: str, *, - filter=None, - query=None, - natural_language_query=None, - count=None, - offset=None, - **kwargs): + filter: str = None, + query: str = None, + natural_language_query: str = None, + count: int = None, + offset: int = None, + **kwargs) -> 'DetailedResponse': """ Query system notices. @@ -345,7 +351,9 @@ def query_notices(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', 'query_notices') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query_notices') headers.update(sdk_headers) params = { @@ -362,12 +370,16 @@ def query_notices(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def list_fields(self, project_id, *, collection_ids=None, **kwargs): + def list_fields(self, + project_id: str, + *, + collection_ids: List[str] = None, + **kwargs) -> 'DetailedResponse': """ List fields. @@ -376,7 +388,7 @@ def list_fields(self, project_id, *, collection_ids=None, **kwargs): :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. - :param list[str] collection_ids: (optional) Comma separated list of the + :param List[str] collection_ids: (optional) Comma separated list of the collection IDs. If this parameter is not specified, all collections in the project are used. :param dict headers: A `dict` containing the request headers @@ -390,7 +402,9 @@ def list_fields(self, project_id, *, collection_ids=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', 'list_fields') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_fields') headers.update(sdk_headers) params = { @@ -403,8 +417,8 @@ def list_fields(self, project_id, *, collection_ids=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -412,7 +426,8 @@ def list_fields(self, project_id, *, collection_ids=None, **kwargs): # Component settings ######################### - def get_component_settings(self, project_id, **kwargs): + def get_component_settings(self, project_id: str, + **kwargs) -> 'DetailedResponse': """ Configuration settings for components. @@ -431,8 +446,9 @@ def get_component_settings(self, project_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', - 'get_component_settings') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_component_settings') headers.update(sdk_headers) params = {'version': self.version} @@ -442,8 +458,8 @@ def get_component_settings(self, project_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -452,15 +468,15 @@ def get_component_settings(self, project_id, **kwargs): ######################### def add_document(self, - project_id, - collection_id, + project_id: str, + collection_id: str, *, - file=None, - filename=None, - file_content_type=None, - metadata=None, - x_watson_discovery_force=None, - **kwargs): + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + x_watson_discovery_force: bool = None, + **kwargs) -> 'DetailedResponse': """ Add a document. @@ -485,15 +501,15 @@ def add_document(self, **Note:** Documents can be added with a specific **document_id** by using the **_/v2/projects/{project_id}/collections/{collection_id}/documents** method. **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that conects to an external + uploads. It cannot be used to modify a collection that connects to an external source such as Microsoft SharePoint. :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. :param str collection_id: The ID of the collection. - :param file file: (optional) The content of the document to ingest. The + :param TextIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a confiruration is + megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -518,7 +534,9 @@ def add_document(self, headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', 'add_document') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='add_document') headers.update(sdk_headers) params = {'version': self.version} @@ -532,6 +550,7 @@ def add_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: + metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) url = '/v2/projects/{0}/collections/{1}/documents'.format( @@ -540,22 +559,22 @@ def add_document(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response def update_document(self, - project_id, - collection_id, - document_id, + project_id: str, + collection_id: str, + document_id: str, *, - file=None, - filename=None, - file_content_type=None, - metadata=None, - x_watson_discovery_force=None, - **kwargs): + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + x_watson_discovery_force: bool = None, + **kwargs) -> 'DetailedResponse': """ Update a document. @@ -566,16 +585,16 @@ def update_document(self, **Note:** When uploading a new document with this method it automatically replaces any document stored with the same **document_id** if it exists. **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that conects to an external + uploads. It cannot be used to modify a collection that connects to an external source such as Microsoft SharePoint. :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param file file: (optional) The content of the document to ingest. The + :param TextIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a confiruration is + megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -602,7 +621,9 @@ def update_document(self, headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', 'update_document') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document') headers.update(sdk_headers) params = {'version': self.version} @@ -616,6 +637,7 @@ def update_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: + metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) url = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( @@ -624,18 +646,18 @@ def update_document(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response def delete_document(self, - project_id, - collection_id, - document_id, + project_id: str, + collection_id: str, + document_id: str, *, - x_watson_discovery_force=None, - **kwargs): + x_watson_discovery_force: bool = None, + **kwargs) -> 'DetailedResponse': """ Delete a document. @@ -643,7 +665,7 @@ def delete_document(self, success response is returned (HTTP status code `200`) with the status set to 'deleted'. **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that conects to an external + uploads. It cannot be used to modify a collection that connects to an external source such as Microsoft SharePoint. :param str project_id: The ID of the project. This information can be found @@ -668,7 +690,9 @@ def delete_document(self, headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', 'delete_document') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document') headers.update(sdk_headers) params = {'version': self.version} @@ -678,8 +702,8 @@ def delete_document(self, request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -687,7 +711,8 @@ def delete_document(self, # Training data ######################### - def list_training_queries(self, project_id, **kwargs): + def list_training_queries(self, project_id: str, + **kwargs) -> 'DetailedResponse': """ List training queries. @@ -706,8 +731,9 @@ def list_training_queries(self, project_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', - 'list_training_queries') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_training_queries') headers.update(sdk_headers) params = {'version': self.version} @@ -717,12 +743,13 @@ def list_training_queries(self, project_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_training_queries(self, project_id, **kwargs): + def delete_training_queries(self, project_id: str, + **kwargs) -> 'DetailedResponse': """ Delete training queries. @@ -741,8 +768,9 @@ def delete_training_queries(self, project_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', - 'delete_training_queries') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_training_queries') headers.update(sdk_headers) params = {'version': self.version} @@ -752,18 +780,18 @@ def delete_training_queries(self, project_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response def create_training_query(self, - project_id, - natural_language_query, - examples, + project_id: str, + natural_language_query: str, + examples: List['TrainingExample'], *, - filter=None, - **kwargs): + filter: str = None, + **kwargs) -> 'DetailedResponse': """ Create training query. @@ -774,7 +802,7 @@ def create_training_query(self, from the deploy page of the Discovery administrative tooling. :param str natural_language_query: The natural text query for the training query. - :param list[TrainingExample] examples: Array of training examples. + :param List[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. :param dict headers: A `dict` containing the request headers @@ -784,13 +812,18 @@ def create_training_query(self, if project_id is None: raise ValueError('project_id must be provided') + if natural_language_query is None: + raise ValueError('natural_language_query must be provided') + if examples is None: + raise ValueError('examples must be provided') examples = [self._convert_model(x) for x in examples] headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', - 'create_training_query') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_training_query') headers.update(sdk_headers) params = {'version': self.version} @@ -807,12 +840,13 @@ def create_training_query(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_training_query(self, project_id, query_id, **kwargs): + def get_training_query(self, project_id: str, query_id: str, + **kwargs) -> 'DetailedResponse': """ Get a training data query. @@ -835,7 +869,9 @@ def get_training_query(self, project_id, query_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', 'get_training_query') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_training_query') headers.update(sdk_headers) params = {'version': self.version} @@ -845,19 +881,19 @@ def get_training_query(self, project_id, query_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_training_query(self, - project_id, - query_id, - natural_language_query, - examples, + project_id: str, + query_id: str, + natural_language_query: str, + examples: List['TrainingExample'], *, - filter=None, - **kwargs): + filter: str = None, + **kwargs) -> 'DetailedResponse': """ Update a training query. @@ -868,7 +904,7 @@ def update_training_query(self, :param str query_id: The ID of the query used for training. :param str natural_language_query: The natural text query for the training query. - :param list[TrainingExample] examples: Array of training examples. + :param List[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. :param dict headers: A `dict` containing the request headers @@ -889,8 +925,9 @@ def update_training_query(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('discovery', 'V2', - 'update_training_query') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_training_query') headers.update(sdk_headers) params = {'version': self.version} @@ -907,8 +944,8 @@ def update_training_query(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -954,7 +991,7 @@ class Collection(): :attr str name: (optional) The name of the collection. """ - def __init__(self, *, collection_id=None, name=None): + def __init__(self, *, collection_id: str = None, name: str = None) -> None: """ Initialize a Collection object. @@ -966,7 +1003,7 @@ def __init__(self, *, collection_id=None, name=None): self.name = name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} valid_keys = ['collection_id', 'name'] @@ -981,7 +1018,12 @@ def _from_dict(cls, _dict): args['name'] = _dict.get('name') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection 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, 'collection_id') and self.collection_id is not None: @@ -990,17 +1032,21 @@ def _to_dict(self): _dict['name'] = self.name return _dict - def __str__(self): + 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 Collection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Collection') -> 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): + def __ne__(self, other: 'Collection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1009,21 +1055,21 @@ class Completions(): """ An object containing an array of autocompletion suggestions. - :attr list[str] completions: (optional) Array of autcomplete suggestion based on + :attr List[str] completions: (optional) Array of autcomplete suggestion based on the provided prefix. """ - def __init__(self, *, completions=None): + def __init__(self, *, completions: List[str] = None) -> None: """ Initialize a Completions object. - :param list[str] completions: (optional) Array of autcomplete suggestion + :param List[str] completions: (optional) Array of autcomplete suggestion based on the provided prefix. """ self.completions = completions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Completions': """Initialize a Completions object from a json dictionary.""" args = {} valid_keys = ['completions'] @@ -1036,24 +1082,33 @@ def _from_dict(cls, _dict): args['completions'] = _dict.get('completions') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Completions 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, 'completions') and self.completions is not None: _dict['completions'] = self.completions return _dict - def __str__(self): + 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 Completions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Completions') -> 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): + def __ne__(self, other: 'Completions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1073,10 +1128,10 @@ class ComponentSettingsAggregation(): def __init__(self, *, - name=None, - label=None, - multiple_selections_allowed=None, - visualization_type=None): + name: str = None, + label: str = None, + multiple_selections_allowed: bool = None, + visualization_type: str = None) -> None: """ Initialize a ComponentSettingsAggregation object. @@ -1094,7 +1149,7 @@ def __init__(self, self.visualization_type = visualization_type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': """Initialize a ComponentSettingsAggregation object from a json dictionary.""" args = {} valid_keys = [ @@ -1116,7 +1171,12 @@ def _from_dict(cls, _dict): args['visualization_type'] = _dict.get('visualization_type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsAggregation 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, 'name') and self.name is not None: @@ -1133,17 +1193,21 @@ def _to_dict(self): _dict['visualization_type'] = self.visualization_type return _dict - def __str__(self): + 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 ComponentSettingsAggregation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ComponentSettingsAggregation') -> 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): + def __ne__(self, other: 'ComponentSettingsAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1165,7 +1229,10 @@ class ComponentSettingsFieldsShown(): :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. """ - def __init__(self, *, body=None, title=None): + def __init__(self, + *, + body: 'ComponentSettingsFieldsShownBody' = None, + title: 'ComponentSettingsFieldsShownTitle' = None) -> None: """ Initialize a ComponentSettingsFieldsShown object. @@ -1176,7 +1243,7 @@ def __init__(self, *, body=None, title=None): self.title = title @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" args = {} valid_keys = ['body', 'title'] @@ -1193,7 +1260,12 @@ def _from_dict(cls, _dict): _dict.get('title')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShown 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, 'body') and self.body is not None: @@ -1202,17 +1274,21 @@ def _to_dict(self): _dict['title'] = self.title._to_dict() return _dict - def __str__(self): + 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 ComponentSettingsFieldsShown object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ComponentSettingsFieldsShown') -> 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): + def __ne__(self, other: 'ComponentSettingsFieldsShown') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1225,7 +1301,7 @@ class ComponentSettingsFieldsShownBody(): :attr str field: (optional) Use a specific field as the title. """ - def __init__(self, *, use_passage=None, field=None): + def __init__(self, *, use_passage: bool = None, field: str = None) -> None: """ Initialize a ComponentSettingsFieldsShownBody object. @@ -1236,7 +1312,7 @@ def __init__(self, *, use_passage=None, field=None): self.field = field @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" args = {} valid_keys = ['use_passage', 'field'] @@ -1251,7 +1327,12 @@ def _from_dict(cls, _dict): args['field'] = _dict.get('field') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownBody 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, 'use_passage') and self.use_passage is not None: @@ -1260,17 +1341,21 @@ def _to_dict(self): _dict['field'] = self.field return _dict - def __str__(self): + 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 ComponentSettingsFieldsShownBody object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> 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): + def __ne__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1282,7 +1367,7 @@ class ComponentSettingsFieldsShownTitle(): :attr str field: (optional) Use a specific field as the title. """ - def __init__(self, *, field=None): + def __init__(self, *, field: str = None) -> None: """ Initialize a ComponentSettingsFieldsShownTitle object. @@ -1291,7 +1376,7 @@ def __init__(self, *, field=None): self.field = field @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" args = {} valid_keys = ['field'] @@ -1304,24 +1389,33 @@ def _from_dict(cls, _dict): args['field'] = _dict.get('field') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownTitle 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, 'field') and self.field is not None: _dict['field'] = self.field return _dict - def __str__(self): + 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 ComponentSettingsFieldsShownTitle object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> 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): + def __ne__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1336,17 +1430,18 @@ class ComponentSettingsResponse(): :attr bool structured_search: (optional) Whether or not structured search is enabled. :attr int results_per_page: (optional) Number or results shown per page. - :attr list[ComponentSettingsAggregation] aggregations: (optional) a list of + :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of component setting aggregations. """ def __init__(self, *, - fields_shown=None, - autocomplete=None, - structured_search=None, - results_per_page=None, - aggregations=None): + fields_shown: 'ComponentSettingsFieldsShown' = None, + autocomplete: bool = None, + structured_search: bool = None, + results_per_page: int = None, + aggregations: List['ComponentSettingsAggregation'] = None + ) -> None: """ Initialize a ComponentSettingsResponse object. @@ -1357,7 +1452,7 @@ def __init__(self, :param bool structured_search: (optional) Whether or not structured search is enabled. :param int results_per_page: (optional) Number or results shown per page. - :param list[ComponentSettingsAggregation] aggregations: (optional) a list + :param List[ComponentSettingsAggregation] aggregations: (optional) a list of component setting aggregations. """ self.fields_shown = fields_shown @@ -1367,7 +1462,7 @@ def __init__(self, self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': """Initialize a ComponentSettingsResponse object from a json dictionary.""" args = {} valid_keys = [ @@ -1395,7 +1490,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsResponse 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, 'fields_shown') and self.fields_shown is not None: @@ -1412,17 +1512,21 @@ def _to_dict(self): _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): + 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 ComponentSettingsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ComponentSettingsResponse') -> 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): + def __ne__(self, other: 'ComponentSettingsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1436,7 +1540,7 @@ class DeleteDocumentResponse(): status deleted. """ - def __init__(self, *, document_id=None, status=None): + def __init__(self, *, document_id: str = None, status: str = None) -> None: """ Initialize a DeleteDocumentResponse object. @@ -1448,7 +1552,7 @@ def __init__(self, *, document_id=None, status=None): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} valid_keys = ['document_id', 'status'] @@ -1463,7 +1567,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteDocumentResponse 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, 'document_id') and self.document_id is not None: @@ -1472,17 +1581,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteDocumentResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteDocumentResponse') -> 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): + def __ne__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1505,7 +1618,7 @@ class DocumentAccepted(): others. """ - def __init__(self, *, document_id=None, status=None): + def __init__(self, *, document_id: str = None, status: str = None) -> None: """ Initialize a DocumentAccepted object. @@ -1520,7 +1633,7 @@ def __init__(self, *, document_id=None, status=None): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': """Initialize a DocumentAccepted object from a json dictionary.""" args = {} valid_keys = ['document_id', 'status'] @@ -1535,7 +1648,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAccepted 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, 'document_id') and self.document_id is not None: @@ -1544,17 +1662,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 DocumentAccepted object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentAccepted') -> 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): + def __ne__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1579,7 +1701,11 @@ class DocumentAttribute(): `begin` and `end`. """ - def __init__(self, *, type=None, text=None, location=None): + def __init__(self, + *, + type: str = None, + text: str = None, + location: 'TableElementLocation' = None) -> None: """ Initialize a DocumentAttribute object. @@ -1594,7 +1720,7 @@ def __init__(self, *, type=None, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': """Initialize a DocumentAttribute object from a json dictionary.""" args = {} valid_keys = ['type', 'text', 'location'] @@ -1612,7 +1738,12 @@ def _from_dict(cls, _dict): _dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAttribute 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: @@ -1623,17 +1754,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 DocumentAttribute object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentAttribute') -> 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): + def __ne__(self, other: 'DocumentAttribute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1648,7 +1783,11 @@ class Field(): the field was found. """ - def __init__(self, *, field=None, type=None, collection_id=None): + def __init__(self, + *, + field: str = None, + type: str = None, + collection_id: str = None) -> None: """ Initialize a Field object. @@ -1662,7 +1801,7 @@ def __init__(self, *, field=None, type=None, collection_id=None): self.collection_id = collection_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Field': """Initialize a Field object from a json dictionary.""" args = {} valid_keys = ['field', 'type', 'collection_id'] @@ -1679,7 +1818,12 @@ def _from_dict(cls, _dict): args['collection_id'] = _dict.get('collection_id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Field 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, 'field') and self.field is not None: @@ -1690,17 +1834,21 @@ def _to_dict(self): _dict['collection_id'] = self.collection_id return _dict - def __str__(self): + 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 Field object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Field') -> 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): + def __ne__(self, other: 'Field') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1725,21 +1873,21 @@ class ListCollectionsResponse(): """ Response object containing an array of collection details. - :attr list[Collection] collections: (optional) An array containing information + :attr List[Collection] collections: (optional) An array containing information about each collection in the project. """ - def __init__(self, *, collections=None): + def __init__(self, *, collections: List['Collection'] = None) -> None: """ Initialize a ListCollectionsResponse object. - :param list[Collection] collections: (optional) An array containing + :param List[Collection] collections: (optional) An array containing information about each collection in the project. """ self.collections = collections @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} valid_keys = ['collections'] @@ -1754,24 +1902,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListCollectionsResponse 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, 'collections') and self.collections is not None: _dict['collections'] = [x._to_dict() for x in self.collections] return _dict - def __str__(self): + 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 ListCollectionsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListCollectionsResponse') -> 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): + def __ne__(self, other: 'ListCollectionsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1786,21 +1943,21 @@ class ListFieldsResponse(): example, `warnings.properties.severity` means that the `warnings` object has a property called `severity`). - :attr list[Field] fields: (optional) An array containing information about each + :attr List[Field] fields: (optional) An array containing information about each field in the collections. """ - def __init__(self, *, fields=None): + def __init__(self, *, fields: List['Field'] = None) -> None: """ Initialize a ListFieldsResponse object. - :param list[Field] fields: (optional) An array containing information about + :param List[Field] fields: (optional) An array containing information about each field in the collections. """ self.fields = fields @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': """Initialize a ListFieldsResponse object from a json dictionary.""" args = {} valid_keys = ['fields'] @@ -1815,24 +1972,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListFieldsResponse 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, 'fields') and self.fields is not None: _dict['fields'] = [x._to_dict() for x in self.fields] return _dict - def __str__(self): + 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 ListFieldsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListFieldsResponse') -> 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): + def __ne__(self, other: 'ListFieldsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1869,14 +2035,14 @@ class Notice(): def __init__(self, *, - notice_id=None, - created=None, - document_id=None, - collection_id=None, - query_id=None, - severity=None, - step=None, - description=None): + notice_id: str = None, + created: datetime = None, + document_id: str = None, + collection_id: str = None, + query_id: str = None, + severity: str = None, + step: str = None, + description: str = None) -> None: """ Initialize a Notice object. @@ -1915,7 +2081,7 @@ def __init__(self, self.description = description @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} valid_keys = [ @@ -1945,7 +2111,12 @@ def _from_dict(cls, _dict): args['description'] = _dict.get('description') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Notice 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, 'notice_id') and self.notice_id is not None: @@ -1966,17 +2137,21 @@ def _to_dict(self): _dict['description'] = self.description return _dict - def __str__(self): + 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 Notice object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Notice') -> 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): + def __ne__(self, other: 'Notice') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1997,7 +2172,7 @@ class QueryAggregation(): top_hits. """ - def __init__(self, type): + def __init__(self, type: str) -> None: """ Initialize a QueryAggregation object. @@ -2008,8 +2183,11 @@ def __init__(self, type): self.type = type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryAggregation': """Initialize a QueryAggregation object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) args = {} valid_keys = ['type'] bad_keys = set(_dict.keys()) - set(valid_keys) @@ -2025,352 +2203,170 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregation 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 __str__(self): + 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 QueryAggregation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryAggregation') -> 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): + def __ne__(self, other: 'QueryAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['term'] = 'QueryTermAggregation' + mapping['histogram'] = 'QueryHistogramAggregation' + mapping['timeslice'] = 'QueryTimesliceAggregation' + mapping['nested'] = 'QueryNestedAggregation' + mapping['filter'] = 'QueryFilterAggregation' + mapping['min'] = 'QueryCalculationAggregation' + mapping['max'] = 'QueryCalculationAggregation' + mapping['sum'] = 'QueryCalculationAggregation' + mapping['average'] = 'QueryCalculationAggregation' + mapping['unique_count'] = 'QueryCalculationAggregation' + mapping['top_hits'] = 'QueryTopHitsAggregation' + disc_value = _dict.get('type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'type\' not found in QueryAggregation JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + -class QueryCalculationAggregation(): +class QueryHistogramAggregationResult(): """ - Returns a scalar calculation across all documents for the field specified. Possible - calculations include min, max, sum, average, and unique_count. + Histogram numeric interval result. - :attr str field: The field to perform the calculation on. - :attr float value: (optional) The value of the calculation. + :attr int key: The value of the upper bound for the numeric segment. + :attr int matching_results: Number of documents with the specified key as the + upper bound. + :attr List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. """ - def __init__(self, type, field, *, value=None): + def __init__(self, + key: int, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: """ - Initialize a QueryCalculationAggregation object. + Initialize a QueryHistogramAggregationResult object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str field: The field to perform the calculation on. - :param float value: (optional) The value of the calculation. + :param int key: The value of the upper bound for the numeric segment. + :param int matching_results: Number of documents with the specified key as + the upper bound. + :param List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. """ - self.field = field - self.value = value + self.key = key + self.matching_results = matching_results + self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryCalculationAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': + """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" args = {} - valid_keys = ['field', 'value'] + valid_keys = ['key', 'matching_results', 'aggregations'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryCalculationAggregation: ' + 'Unrecognized keys detected in dictionary for class QueryHistogramAggregationResult: ' + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') + if 'key' in _dict: + args['key'] = _dict.get('key') else: raise ValueError( - 'Required property \'field\' not present in QueryCalculationAggregation JSON' + 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' ) - if 'value' in _dict: - args['value'] = _dict.get('value') + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryHistogramAggregationResult 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, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value + if hasattr(self, 'key') and self.key is not None: + _dict['key'] = self.key + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): - """Return a `str` version of this QueryCalculationAggregation object.""" + 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 QueryHistogramAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryHistogramAggregationResult') -> 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): + def __ne__(self, other: 'QueryHistogramAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryFilterAggregation(): +class QueryLargePassages(): """ - A modifier that will narrow down the document set of the sub aggregations it precedes. - - :attr str match: The filter written in Discovery Query Language syntax applied - to the documents before sub aggregations are run. - :attr int matching_results: Number of documents matching the filter. - :attr list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - - def __init__(self, type, match, matching_results, *, aggregations=None): - """ - Initialize a QueryFilterAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str match: The filter written in Discovery Query Language syntax - applied to the documents before sub aggregations are run. - :param int matching_results: Number of documents matching the filter. - :param list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - self.match = match - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryFilterAggregation object from a json dictionary.""" - args = {} - valid_keys = ['match', 'matching_results', 'aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryFilterAggregation: ' - + ', '.join(bad_keys)) - if 'match' in _dict: - args['match'] = _dict.get('match') - else: - raise ValueError( - 'Required property \'match\' not present in QueryFilterAggregation JSON' - ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' - ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'match') and self.match is not None: - _dict['match'] = self.match - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] - return _dict - - def __str__(self): - """Return a `str` version of this QueryFilterAggregation object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryHistogramAggregation(): - """ - Numeric interval segments to categorize documents by using field values from a single - numeric field to describe the category. - - :attr str field: The numeric field name used to create the histogram. - :attr int interval: The size of the sections the results are split into. - :attr list[QueryHistogramAggregationResult] results: (optional) Array of numeric - intervals. - """ - - def __init__(self, type, field, interval, *, results=None): - """ - Initialize a QueryHistogramAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str field: The numeric field name used to create the histogram. - :param int interval: The size of the sections the results are split into. - :param list[QueryHistogramAggregationResult] results: (optional) Array of - numeric intervals. - """ - self.field = field - self.interval = interval - self.results = results - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryHistogramAggregation object from a json dictionary.""" - args = {} - valid_keys = ['field', 'interval', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryHistogramAggregation: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryHistogramAggregation JSON' - ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - else: - raise ValueError( - 'Required property \'interval\' not present in QueryHistogramAggregation JSON' - ) - if 'results' in _dict: - args['results'] = [ - QueryHistogramAggregationResult._from_dict(x) - for x in (_dict.get('results')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] - return _dict - - def __str__(self): - """Return a `str` version of this QueryHistogramAggregation object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryHistogramAggregationResult(): - """ - Histogram numeric interval result. - - :attr int key: The value of the upper bound for the numeric segment. - :attr int matching_results: Number of documents with the specified key as the - upper bound. - :attr list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - - def __init__(self, key, matching_results, *, aggregations=None): - """ - Initialize a QueryHistogramAggregationResult object. - - :param int key: The value of the upper bound for the numeric segment. - :param int matching_results: Number of documents with the specified key as - the upper bound. - :param list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - self.key = key - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" - args = {} - valid_keys = ['key', 'matching_results', 'aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryHistogramAggregationResult: ' - + ', '.join(bad_keys)) - if 'key' in _dict: - args['key'] = _dict.get('key') - else: - raise ValueError( - 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' - ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' - ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] - return _dict - - def __str__(self): - """Return a `str` version of this QueryHistogramAggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryLargePassages(): - """ - Configuration for passage retrieval. + Configuration for passage retrieval. :attr bool enabled: (optional) A passages query that returns the most relevant passages from the results. :attr bool per_document: (optional) When `true`, passages will be returned - whithin their respective result. + within their respective result. :attr int max_per_document: (optional) Maximum number of passages to return per result. - :attr list[str] fields: (optional) A list of fields that passages are drawn + :attr List[str] fields: (optional) A list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. :attr int count: (optional) The maximum number of passages to return. The search returns fewer passages if the requested total is not found. The default is `10`. @@ -2381,22 +2377,22 @@ class QueryLargePassages(): def __init__(self, *, - enabled=None, - per_document=None, - max_per_document=None, - fields=None, - count=None, - characters=None): + enabled: bool = None, + per_document: bool = None, + max_per_document: int = None, + fields: List[str] = None, + count: int = None, + characters: int = None) -> None: """ Initialize a QueryLargePassages object. :param bool enabled: (optional) A passages query that returns the most relevant passages from the results. :param bool per_document: (optional) When `true`, passages will be returned - whithin their respective result. + within their respective result. :param int max_per_document: (optional) Maximum number of passages to return per result. - :param list[str] fields: (optional) A list of fields that passages are + :param List[str] fields: (optional) A list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. :param int count: (optional) The maximum number of passages to return. The @@ -2413,7 +2409,7 @@ def __init__(self, self.characters = characters @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryLargePassages': """Initialize a QueryLargePassages object from a json dictionary.""" args = {} valid_keys = [ @@ -2439,7 +2435,12 @@ def _from_dict(cls, _dict): args['characters'] = _dict.get('characters') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargePassages 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: @@ -2457,17 +2458,21 @@ def _to_dict(self): _dict['characters'] = self.characters return _dict - def __str__(self): + 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 QueryLargePassages object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryLargePassages') -> 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): + def __ne__(self, other: 'QueryLargePassages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2481,7 +2486,7 @@ class QueryLargeSuggestedRefinements(): returned. The default is `10`. The maximum is `100`. """ - def __init__(self, *, enabled=None, count=None): + def __init__(self, *, enabled: bool = None, count: int = None) -> None: """ Initialize a QueryLargeSuggestedRefinements object. @@ -2493,7 +2498,7 @@ def __init__(self, *, enabled=None, count=None): self.count = count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryLargeSuggestedRefinements': """Initialize a QueryLargeSuggestedRefinements object from a json dictionary.""" args = {} valid_keys = ['enabled', 'count'] @@ -2508,7 +2513,12 @@ def _from_dict(cls, _dict): args['count'] = _dict.get('count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargeSuggestedRefinements 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: @@ -2517,17 +2527,21 @@ def _to_dict(self): _dict['count'] = self.count return _dict - def __str__(self): + 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 QueryLargeSuggestedRefinements object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryLargeSuggestedRefinements') -> 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): + def __ne__(self, other: 'QueryLargeSuggestedRefinements') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2540,7 +2554,7 @@ class QueryLargeTableResults(): :attr int count: (optional) Maximum number of tables to return. """ - def __init__(self, *, enabled=None, count=None): + def __init__(self, *, enabled: bool = None, count: int = None) -> None: """ Initialize a QueryLargeTableResults object. @@ -2551,7 +2565,7 @@ def __init__(self, *, enabled=None, count=None): self.count = count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryLargeTableResults': """Initialize a QueryLargeTableResults object from a json dictionary.""" args = {} valid_keys = ['enabled', 'count'] @@ -2566,7 +2580,12 @@ def _from_dict(cls, _dict): args['count'] = _dict.get('count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargeTableResults 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: @@ -2575,129 +2594,50 @@ def _to_dict(self): _dict['count'] = self.count return _dict - def __str__(self): + 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 QueryLargeTableResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryLargeTableResults') -> 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): + def __ne__(self, other: 'QueryLargeTableResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryNestedAggregation(): +class QueryNoticesResponse(): """ - A restriction that alter the document set used for sub aggregations it precedes to - nested documents found in the field specified. - - :attr str path: The path to the document field to scope sub aggregations to. - :attr int matching_results: Number of nested documents found in the specified - field. - :attr list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - - def __init__(self, type, path, matching_results, *, aggregations=None): - """ - Initialize a QueryNestedAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str path: The path to the document field to scope sub aggregations - to. - :param int matching_results: Number of nested documents found in the - specified field. - :param list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - self.path = path - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryNestedAggregation object from a json dictionary.""" - args = {} - valid_keys = ['path', 'matching_results', 'aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryNestedAggregation: ' - + ', '.join(bad_keys)) - if 'path' in _dict: - args['path'] = _dict.get('path') - else: - raise ValueError( - 'Required property \'path\' not present in QueryNestedAggregation JSON' - ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' - ) - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] - return _dict - - def __str__(self): - """Return a `str` version of this QueryNestedAggregation object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNoticesResponse(): - """ - Object containing notice query results. + Object containing notice query results. :attr int matching_results: (optional) The number of matching results. - :attr list[Notice] notices: (optional) Array of document results that match the + :attr List[Notice] notices: (optional) Array of document results that match the query. """ - def __init__(self, *, matching_results=None, notices=None): + def __init__(self, + *, + matching_results: int = None, + notices: List['Notice'] = None) -> None: """ Initialize a QueryNoticesResponse object. :param int matching_results: (optional) The number of matching results. - :param list[Notice] notices: (optional) Array of document results that + :param List[Notice] notices: (optional) Array of document results that match the query. """ self.matching_results = matching_results self.notices = notices @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} valid_keys = ['matching_results', 'notices'] @@ -2714,7 +2654,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryNoticesResponse 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, @@ -2724,17 +2669,21 @@ def _to_dict(self): _dict['notices'] = [x._to_dict() for x in self.notices] return _dict - def __str__(self): + 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 QueryNoticesResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryNoticesResponse') -> 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): + def __ne__(self, other: 'QueryNoticesResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2745,44 +2694,44 @@ class QueryResponse(): :attr int matching_results: (optional) The number of matching results for the query. - :attr list[QueryResult] results: (optional) Array of document results for the + :attr List[QueryResult] results: (optional) Array of document results for the query. - :attr list[QueryAggregation] aggregations: (optional) Array of aggregations for + :attr List[QueryAggregation] aggregations: (optional) Array of aggregations for the query. :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval type information. :attr str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. - :attr list[QuerySuggestedRefinement] suggested_refinements: (optional) Array of - suggested refinments. - :attr list[QueryTableResult] table_results: (optional) Array of table results. + :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) Array of + suggested refinements. + :attr List[QueryTableResult] table_results: (optional) Array of table results. """ def __init__(self, *, - matching_results=None, - results=None, - aggregations=None, - retrieval_details=None, - suggested_query=None, - suggested_refinements=None, - table_results=None): + matching_results: int = None, + results: List['QueryResult'] = None, + aggregations: List['QueryAggregation'] = None, + retrieval_details: 'RetrievalDetails' = None, + suggested_query: str = None, + suggested_refinements: List['QuerySuggestedRefinement'] = None, + table_results: List['QueryTableResult'] = None) -> None: """ Initialize a QueryResponse object. :param int matching_results: (optional) The number of matching results for the query. - :param list[QueryResult] results: (optional) Array of document results for + :param List[QueryResult] results: (optional) Array of document results for the query. - :param list[QueryAggregation] aggregations: (optional) Array of + :param List[QueryAggregation] aggregations: (optional) Array of aggregations for the query. :param RetrievalDetails retrieval_details: (optional) An object contain retrieval type information. :param str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. - :param list[QuerySuggestedRefinement] suggested_refinements: (optional) - Array of suggested refinments. - :param list[QueryTableResult] table_results: (optional) Array of table + :param List[QuerySuggestedRefinement] suggested_refinements: (optional) + Array of suggested refinements. + :param List[QueryTableResult] table_results: (optional) Array of table results. """ self.matching_results = matching_results @@ -2794,7 +2743,7 @@ def __init__(self, self.table_results = table_results @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResponse': """Initialize a QueryResponse object from a json dictionary.""" args = {} valid_keys = [ @@ -2834,7 +2783,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResponse 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, @@ -2859,17 +2813,21 @@ def _to_dict(self): _dict['table_results'] = [x._to_dict() for x in self.table_results] return _dict - def __str__(self): + 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 QueryResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResponse') -> 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): + def __ne__(self, other: 'QueryResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2881,24 +2839,24 @@ class QueryResult(): :attr str document_id: The unique identifier of the document. :attr dict metadata: (optional) Metadata of the document. :attr QueryResultMetadata result_metadata: Metadata of a query result. - :attr list[QueryResultPassage] document_passages: (optional) Passages returned + :attr List[QueryResultPassage] document_passages: (optional) Passages returned by Discovery. """ def __init__(self, - document_id, - result_metadata, + document_id: str, + result_metadata: 'QueryResultMetadata', *, - metadata=None, - document_passages=None, - **kwargs): + metadata: dict = None, + document_passages: List['QueryResultPassage'] = None, + **kwargs) -> None: """ Initialize a QueryResult object. :param str document_id: The unique identifier of the document. :param QueryResultMetadata result_metadata: Metadata of a query result. :param dict metadata: (optional) Metadata of the document. - :param list[QueryResultPassage] document_passages: (optional) Passages + :param List[QueryResultPassage] document_passages: (optional) Passages returned by Discovery. :param **kwargs: (optional) Any additional properties. """ @@ -2910,7 +2868,7 @@ def __init__(self, setattr(self, _key, _value) @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResult': """Initialize a QueryResult object from a json dictionary.""" args = {} xtra = _dict.copy() @@ -2941,7 +2899,12 @@ def _from_dict(cls, _dict): args.update(xtra) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResult 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, 'document_id') and self.document_id is not None: @@ -2963,7 +2926,11 @@ def _to_dict(self): _dict[_key] = _value return _dict - def __setattr__(self, name, value): + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: properties = { 'document_id', 'metadata', 'result_metadata', 'document_passages' } @@ -2973,17 +2940,17 @@ def __setattr__(self, name, value): self._additionalProperties.add(name) super(QueryResult, self).__setattr__(name, value) - def __str__(self): + def __str__(self) -> str: """Return a `str` version of this QueryResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResult') -> 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): + def __ne__(self, other: 'QueryResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3006,10 +2973,10 @@ class QueryResultMetadata(): """ def __init__(self, - collection_id, + collection_id: str, *, - document_retrieval_source=None, - confidence=None): + document_retrieval_source: str = None, + confidence: float = None) -> None: """ Initialize a QueryResultMetadata object. @@ -3030,7 +2997,7 @@ def __init__(self, self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} valid_keys = [ @@ -3054,7 +3021,12 @@ def _from_dict(cls, _dict): args['confidence'] = _dict.get('confidence') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResultMetadata 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, 'document_retrieval_source' @@ -3066,17 +3038,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 QueryResultMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResultMetadata') -> 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): + def __ne__(self, other: 'QueryResultMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3103,10 +3079,10 @@ class QueryResultPassage(): def __init__(self, *, - passage_text=None, - start_offset=None, - end_offset=None, - field=None): + passage_text: str = None, + start_offset: int = None, + end_offset: int = None, + field: str = None) -> None: """ Initialize a QueryResultPassage object. @@ -3124,7 +3100,7 @@ def __init__(self, self.field = field @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryResultPassage': """Initialize a QueryResultPassage object from a json dictionary.""" args = {} valid_keys = ['passage_text', 'start_offset', 'end_offset', 'field'] @@ -3143,7 +3119,12 @@ def _from_dict(cls, _dict): args['field'] = _dict.get('field') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResultPassage 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, 'passage_text') and self.passage_text is not None: @@ -3156,17 +3137,21 @@ def _to_dict(self): _dict['field'] = self.field return _dict - def __str__(self): + 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 QueryResultPassage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryResultPassage') -> 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): + def __ne__(self, other: 'QueryResultPassage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3178,7 +3163,7 @@ class QuerySuggestedRefinement(): :attr str text: (optional) The text used to filter. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a QuerySuggestedRefinement object. @@ -3187,7 +3172,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QuerySuggestedRefinement': """Initialize a QuerySuggestedRefinement object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -3200,24 +3185,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QuerySuggestedRefinement 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, 'text') and self.text is not None: _dict['text'] = self.text return _dict - def __str__(self): + 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 QuerySuggestedRefinement object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QuerySuggestedRefinement') -> 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): + def __ne__(self, other: 'QuerySuggestedRefinement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3240,12 +3234,12 @@ class QueryTableResult(): def __init__(self, *, - table_id=None, - source_document_id=None, - collection_id=None, - table_html=None, - table_html_offset=None, - table=None): + table_id: str = None, + source_document_id: str = None, + collection_id: str = None, + table_html: str = None, + table_html_offset: int = None, + table: 'TableResultTable' = None) -> None: """ Initialize a QueryTableResult object. @@ -3268,7 +3262,7 @@ def __init__(self, self.table = table @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryTableResult': """Initialize a QueryTableResult object from a json dictionary.""" args = {} valid_keys = [ @@ -3294,7 +3288,12 @@ def _from_dict(cls, _dict): args['table'] = TableResultTable._from_dict(_dict.get('table')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTableResult 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, 'table_id') and self.table_id is not None: @@ -3314,95 +3313,21 @@ def _to_dict(self): _dict['table'] = self.table._to_dict() return _dict - def __str__(self): - """Return a `str` version of this QueryTableResult object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTermAggregation(): - """ - Returns the top values for the field specified. - - :attr str field: The field in the document used to generate top values from. - :attr int count: (optional) The number of top values returned. - :attr list[QueryTermAggregationResult] results: (optional) Array of top values - for the field. - """ - - def __init__(self, type, field, *, count=None, results=None): - """ - Initialize a QueryTermAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str field: The field in the document used to generate top values - from. - :param int count: (optional) The number of top values returned. - :param list[QueryTermAggregationResult] results: (optional) Array of top - values for the field. - """ - self.field = field - self.count = count - self.results = results - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTermAggregation object from a json dictionary.""" - args = {} - valid_keys = ['field', 'count', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTermAggregation: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryTermAggregation JSON' - ) - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'results' in _dict: - args['results'] = [ - QueryTermAggregationResult._from_dict(x) - for x in (_dict.get('results')) - ] - return cls(**args) - def _to_dict(self): """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] - return _dict + return self.to_dict() - def __str__(self): - """Return a `str` version of this QueryTermAggregation object.""" + def __str__(self) -> str: + """Return a `str` version of this QueryTableResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryTableResult') -> 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): + def __ne__(self, other: 'QueryTableResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3413,18 +3338,22 @@ class QueryTermAggregationResult(): :attr str key: Value of the field with a non-zero frequency in the document set. :attr int matching_results: Number of documents containing the 'key'. - :attr list[QueryAggregation] aggregations: (optional) An array of sub + :attr List[QueryAggregation] aggregations: (optional) An array of sub aggregations. """ - def __init__(self, key, matching_results, *, aggregations=None): + def __init__(self, + key: str, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: """ Initialize a QueryTermAggregationResult object. :param str key: Value of the field with a non-zero frequency in the document set. :param int matching_results: Number of documents containing the 'key'. - :param list[QueryAggregation] aggregations: (optional) An array of sub + :param List[QueryAggregation] aggregations: (optional) An array of sub aggregations. """ self.key = key @@ -3432,7 +3361,7 @@ def __init__(self, key, matching_results, *, aggregations=None): self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': """Initialize a QueryTermAggregationResult object from a json dictionary.""" args = {} valid_keys = ['key', 'matching_results', 'aggregations'] @@ -3460,7 +3389,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTermAggregationResult 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, 'key') and self.key is not None: @@ -3472,143 +3406,64 @@ def _to_dict(self): _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): + 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 QueryTermAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryTermAggregationResult') -> 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): + def __ne__(self, other: 'QueryTermAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTimesliceAggregation(): +class QueryTimesliceAggregationResult(): """ - A specialized histogram aggregation that uses dates to create interval segments. + A timeslice interval segment. - :attr str field: The date field name used to create the timeslice. - :attr str interval: The date interval value. Valid values are seconds, minutes, - hours, days, weeks, and years. - :attr list[QueryTimesliceAggregationResult] results: (optional) Array of - aggregation results. + :attr str key_as_string: String date value of the upper bound for the timeslice + interval in ISO-8601 format. + :attr int key: Numeric date value of the upper bound for the timeslice interval + in UNIX milliseconds since epoch. + :attr int matching_results: Number of documents with the specified key as the + upper bound. + :attr List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. """ - def __init__(self, type, field, interval, *, results=None): + def __init__(self, + key_as_string: str, + key: int, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: """ - Initialize a QueryTimesliceAggregation object. + Initialize a QueryTimesliceAggregationResult object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str field: The date field name used to create the timeslice. - :param str interval: The date interval value. Valid values are seconds, - minutes, hours, days, weeks, and years. - :param list[QueryTimesliceAggregationResult] results: (optional) Array of - aggregation results. + :param str key_as_string: String date value of the upper bound for the + timeslice interval in ISO-8601 format. + :param int key: Numeric date value of the upper bound for the timeslice + interval in UNIX milliseconds since epoch. + :param int matching_results: Number of documents with the specified key as + the upper bound. + :param List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. """ - self.field = field - self.interval = interval - self.results = results + self.key_as_string = key_as_string + self.key = key + self.matching_results = matching_results + self.aggregations = aggregations @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" - args = {} - valid_keys = ['field', 'interval', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTimesliceAggregation: ' - + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryTimesliceAggregation JSON' - ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - else: - raise ValueError( - 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' - ) - if 'results' in _dict: - args['results'] = [ - QueryTimesliceAggregationResult._from_dict(x) - for x in (_dict.get('results')) - ] - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] - return _dict - - def __str__(self): - """Return a `str` version of this QueryTimesliceAggregation object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTimesliceAggregationResult(): - """ - A timeslice interval segment. - - :attr str key_as_string: String date value of the upper bound for the timeslice - interval in ISO-8601 format. - :attr int key: Numeric date value of the upper bound for the timeslice interval - in UNIX miliseconds since epoch. - :attr int matching_results: Number of documents with the specified key as the - upper bound. - :attr list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - - def __init__(self, - key_as_string, - key, - matching_results, - *, - aggregations=None): - """ - Initialize a QueryTimesliceAggregationResult object. - - :param str key_as_string: String date value of the upper bound for the - timeslice interval in ISO-8601 format. - :param int key: Numeric date value of the upper bound for the timeslice - interval in UNIX miliseconds since epoch. - :param int matching_results: Number of documents with the specified key as - the upper bound. - :param list[QueryAggregation] aggregations: (optional) An array of sub - aggregations. - """ - self.key_as_string = key_as_string - self.key = key - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" args = {} valid_keys = [ @@ -3644,7 +3499,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTimesliceAggregationResult 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, 'key_as_string') and self.key_as_string is not None: @@ -3658,83 +3518,21 @@ def _to_dict(self): _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict - def __str__(self): - """Return a `str` version of this QueryTimesliceAggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTopHitsAggregation(): - """ - Returns the top documents ranked by the score of the query. - - :attr int size: The number of documents to return. - :attr QueryTopHitsAggregationResult hits: (optional) - """ - - def __init__(self, type, size, *, hits=None): - """ - Initialize a QueryTopHitsAggregation object. - - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param int size: The number of documents to return. - :param QueryTopHitsAggregationResult hits: (optional) - """ - self.size = size - self.hits = hits - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" - args = {} - valid_keys = ['size', 'hits'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTopHitsAggregation: ' - + ', '.join(bad_keys)) - if 'size' in _dict: - args['size'] = _dict.get('size') - else: - raise ValueError( - 'Required property \'size\' not present in QueryTopHitsAggregation JSON' - ) - if 'hits' in _dict: - args['hits'] = QueryTopHitsAggregationResult._from_dict( - _dict.get('hits')) - return cls(**args) - def _to_dict(self): """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'size') and self.size is not None: - _dict['size'] = self.size - if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits._to_dict() - return _dict + return self.to_dict() - def __str__(self): - """Return a `str` version of this QueryTopHitsAggregation object.""" + def __str__(self) -> str: + """Return a `str` version of this QueryTimesliceAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryTimesliceAggregationResult') -> 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): + def __ne__(self, other: 'QueryTimesliceAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3744,21 +3542,22 @@ class QueryTopHitsAggregationResult(): A query response containing the matching documents for the preceding aggregations. :attr int matching_results: Number of matching results. - :attr list[dict] hits: (optional) An array of the document results. + :attr List[dict] hits: (optional) An array of the document results. """ - def __init__(self, matching_results, *, hits=None): + def __init__(self, matching_results: int, *, + hits: List[dict] = None) -> None: """ Initialize a QueryTopHitsAggregationResult object. :param int matching_results: Number of matching results. - :param list[dict] hits: (optional) An array of the document results. + :param List[dict] hits: (optional) An array of the document results. """ self.matching_results = matching_results self.hits = hits @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" args = {} valid_keys = ['matching_results', 'hits'] @@ -3777,7 +3576,12 @@ def _from_dict(cls, _dict): args['hits'] = _dict.get('hits') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTopHitsAggregationResult 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, @@ -3787,17 +3591,21 @@ def _to_dict(self): _dict['hits'] = self.hits return _dict - def __str__(self): + 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 QueryTopHitsAggregationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'QueryTopHitsAggregationResult') -> 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): + def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3806,7 +3614,7 @@ class RetrievalDetails(): """ An object contain retrieval type information. - :attr str document_retrieval_strategy: (optional) Indentifies the document + :attr str document_retrieval_strategy: (optional) Identifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. **Note**: In the event of trained collections being queried, but the trained @@ -3814,11 +3622,11 @@ class RetrievalDetails(): listed as `untrained`. """ - def __init__(self, *, document_retrieval_strategy=None): + def __init__(self, *, document_retrieval_strategy: str = None) -> None: """ Initialize a RetrievalDetails object. - :param str document_retrieval_strategy: (optional) Indentifies the document + :param str document_retrieval_strategy: (optional) Identifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. **Note**: In the event of trained collections being queried, but the @@ -3828,7 +3636,7 @@ def __init__(self, *, document_retrieval_strategy=None): self.document_retrieval_strategy = document_retrieval_strategy @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': """Initialize a RetrievalDetails object from a json dictionary.""" args = {} valid_keys = ['document_retrieval_strategy'] @@ -3842,7 +3650,12 @@ def _from_dict(cls, _dict): 'document_retrieval_strategy') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RetrievalDetails 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, 'document_retrieval_strategy' @@ -3851,23 +3664,27 @@ def _to_dict(self): 'document_retrieval_strategy'] = self.document_retrieval_strategy return _dict - def __str__(self): + 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 RetrievalDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RetrievalDetails') -> 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): + def __ne__(self, other: 'RetrievalDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class DocumentRetrievalStrategyEnum(Enum): """ - Indentifies the document retrieval strategy used for this query. + Identifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. **Note**: In the event of trained collections being queried, but the trained @@ -3896,38 +3713,40 @@ class TableBodyCells(): `column` location in the current table. :attr int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :attr list[TableRowHeaderIds] row_header_ids: (optional) A list of table row + :attr List[TableRowHeaderIds] row_header_ids: (optional) A list of table row header ids. - :attr list[TableRowHeaderTexts] row_header_texts: (optional) A list of table row + :attr List[TableRowHeaderTexts] row_header_texts: (optional) A list of table row header texts. - :attr list[TableRowHeaderTextsNormalized] row_header_texts_normalized: + :attr List[TableRowHeaderTextsNormalized] row_header_texts_normalized: (optional) A list of table row header texts normalized. - :attr list[TableColumnHeaderIds] column_header_ids: (optional) A list of table + :attr List[TableColumnHeaderIds] column_header_ids: (optional) A list of table column header ids. - :attr list[TableColumnHeaderTexts] column_header_texts: (optional) A list of + :attr List[TableColumnHeaderTexts] column_header_texts: (optional) A list of table column header texts. - :attr list[TableColumnHeaderTextsNormalized] column_header_texts_normalized: + :attr List[TableColumnHeaderTextsNormalized] column_header_texts_normalized: (optional) A list of table column header texts normalized. - :attr list[DocumentAttribute] attributes: (optional) A list of document + :attr List[DocumentAttribute] attributes: (optional) A list of document attributes. """ def __init__(self, *, - cell_id=None, - location=None, - text=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None, - row_header_ids=None, - row_header_texts=None, - row_header_texts_normalized=None, - column_header_ids=None, - column_header_texts=None, - column_header_texts_normalized=None, - attributes=None): + cell_id: str = None, + location: 'TableElementLocation' = None, + text: str = None, + row_index_begin: int = None, + row_index_end: int = None, + column_index_begin: int = None, + column_index_end: int = None, + row_header_ids: List['TableRowHeaderIds'] = None, + row_header_texts: List['TableRowHeaderTexts'] = None, + row_header_texts_normalized: List[ + 'TableRowHeaderTextsNormalized'] = None, + column_header_ids: List['TableColumnHeaderIds'] = None, + column_header_texts: List['TableColumnHeaderTexts'] = None, + column_header_texts_normalized: List[ + 'TableColumnHeaderTextsNormalized'] = None, + attributes: List['DocumentAttribute'] = None) -> None: """ Initialize a TableBodyCells object. @@ -3946,20 +3765,20 @@ def __init__(self, `column` location in the current table. :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :param list[TableRowHeaderIds] row_header_ids: (optional) A list of table + :param List[TableRowHeaderIds] row_header_ids: (optional) A list of table row header ids. - :param list[TableRowHeaderTexts] row_header_texts: (optional) A list of + :param List[TableRowHeaderTexts] row_header_texts: (optional) A list of table row header texts. - :param list[TableRowHeaderTextsNormalized] row_header_texts_normalized: + :param List[TableRowHeaderTextsNormalized] row_header_texts_normalized: (optional) A list of table row header texts normalized. - :param list[TableColumnHeaderIds] column_header_ids: (optional) A list of + :param List[TableColumnHeaderIds] column_header_ids: (optional) A list of table column header ids. - :param list[TableColumnHeaderTexts] column_header_texts: (optional) A list + :param List[TableColumnHeaderTexts] column_header_texts: (optional) A list of table column header texts. - :param list[TableColumnHeaderTextsNormalized] + :param List[TableColumnHeaderTextsNormalized] column_header_texts_normalized: (optional) A list of table column header texts normalized. - :param list[DocumentAttribute] attributes: (optional) A list of document + :param List[DocumentAttribute] attributes: (optional) A list of document attributes. """ self.cell_id = cell_id @@ -3978,7 +3797,7 @@ def __init__(self, self.attributes = attributes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableBodyCells': """Initialize a TableBodyCells object from a json dictionary.""" args = {} valid_keys = [ @@ -4045,7 +3864,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableBodyCells 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, 'cell_id') and self.cell_id is not None: @@ -4100,17 +3924,21 @@ def _to_dict(self): _dict['attributes'] = [x._to_dict() for x in self.attributes] return _dict - def __str__(self): + 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 TableBodyCells object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableBodyCells') -> 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): + def __ne__(self, other: 'TableBodyCells') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4127,7 +3955,11 @@ class TableCellKey(): markup. """ - def __init__(self, *, cell_id=None, location=None, text=None): + def __init__(self, + *, + cell_id: str = None, + location: 'TableElementLocation' = None, + text: str = None) -> None: """ Initialize a TableCellKey object. @@ -4143,7 +3975,7 @@ def __init__(self, *, cell_id=None, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableCellKey': """Initialize a TableCellKey object from a json dictionary.""" args = {} valid_keys = ['cell_id', 'location', 'text'] @@ -4161,7 +3993,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableCellKey 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, 'cell_id') and self.cell_id is not None: @@ -4172,17 +4009,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 TableCellKey object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableCellKey') -> 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): + def __ne__(self, other: 'TableCellKey') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4199,7 +4040,11 @@ class TableCellValues(): markup. """ - def __init__(self, *, cell_id=None, location=None, text=None): + def __init__(self, + *, + cell_id: str = None, + location: 'TableElementLocation' = None, + text: str = None) -> None: """ Initialize a TableCellValues object. @@ -4215,7 +4060,7 @@ def __init__(self, *, cell_id=None, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableCellValues': """Initialize a TableCellValues object from a json dictionary.""" args = {} valid_keys = ['cell_id', 'location', 'text'] @@ -4233,7 +4078,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableCellValues 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, 'cell_id') and self.cell_id is not None: @@ -4244,17 +4094,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 TableCellValues object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableCellValues') -> 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): + def __ne__(self, other: 'TableCellValues') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4267,7 +4121,7 @@ class TableColumnHeaderIds(): :attr str id: (optional) The `id` value of a column header. """ - def __init__(self, *, id=None): + def __init__(self, *, id: str = None) -> None: """ Initialize a TableColumnHeaderIds object. @@ -4276,7 +4130,7 @@ def __init__(self, *, id=None): self.id = id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderIds': """Initialize a TableColumnHeaderIds object from a json dictionary.""" args = {} valid_keys = ['id'] @@ -4289,24 +4143,33 @@ def _from_dict(cls, _dict): args['id'] = _dict.get('id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableColumnHeaderIds 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, 'id') and self.id is not None: _dict['id'] = self.id return _dict - def __str__(self): + 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 TableColumnHeaderIds object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableColumnHeaderIds') -> 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): + def __ne__(self, other: 'TableColumnHeaderIds') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4319,7 +4182,7 @@ class TableColumnHeaderTexts(): :attr str text: (optional) The `text` value of a column header. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a TableColumnHeaderTexts object. @@ -4328,7 +4191,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTexts': """Initialize a TableColumnHeaderTexts object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -4341,24 +4204,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableColumnHeaderTexts 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, 'text') and self.text is not None: _dict['text'] = self.text return _dict - def __str__(self): + 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 TableColumnHeaderTexts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableColumnHeaderTexts') -> 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): + def __ne__(self, other: 'TableColumnHeaderTexts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4372,7 +4244,7 @@ class TableColumnHeaderTextsNormalized(): text. """ - def __init__(self, *, text_normalized=None): + def __init__(self, *, text_normalized: str = None) -> None: """ Initialize a TableColumnHeaderTextsNormalized object. @@ -4382,7 +4254,7 @@ def __init__(self, *, text_normalized=None): self.text_normalized = text_normalized @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTextsNormalized': """Initialize a TableColumnHeaderTextsNormalized object from a json dictionary.""" args = {} valid_keys = ['text_normalized'] @@ -4395,7 +4267,12 @@ def _from_dict(cls, _dict): args['text_normalized'] = _dict.get('text_normalized') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableColumnHeaderTextsNormalized 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, @@ -4403,17 +4280,21 @@ def _to_dict(self): _dict['text_normalized'] = self.text_normalized return _dict - def __str__(self): + 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 TableColumnHeaderTextsNormalized object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableColumnHeaderTextsNormalized') -> 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): + def __ne__(self, other: 'TableColumnHeaderTextsNormalized') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4444,14 +4325,14 @@ class TableColumnHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - text_normalized=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + cell_id: str = None, + location: object = None, + text: str = None, + text_normalized: str = None, + row_index_begin: int = None, + row_index_end: int = None, + column_index_begin: int = None, + column_index_end: int = None) -> None: """ Initialize a TableColumnHeaders object. @@ -4484,7 +4365,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableColumnHeaders': """Initialize a TableColumnHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -4514,7 +4395,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableColumnHeaders 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, 'cell_id') and self.cell_id is not None: @@ -4540,17 +4426,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 TableColumnHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableColumnHeaders') -> 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): + def __ne__(self, other: 'TableColumnHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4564,7 +4454,7 @@ class TableElementLocation(): :attr int end: The element's `end` index. """ - def __init__(self, begin, end): + def __init__(self, begin: int, end: int) -> None: """ Initialize a TableElementLocation object. @@ -4575,7 +4465,7 @@ def __init__(self, begin, end): self.end = end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableElementLocation': """Initialize a TableElementLocation object from a json dictionary.""" args = {} valid_keys = ['begin', 'end'] @@ -4598,7 +4488,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableElementLocation 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, 'begin') and self.begin is not None: @@ -4607,17 +4502,21 @@ def _to_dict(self): _dict['end'] = self.end return _dict - def __str__(self): + 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 TableElementLocation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableElementLocation') -> 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): + def __ne__(self, other: 'TableElementLocation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4644,13 +4543,13 @@ class TableHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + cell_id: str = None, + location: object = None, + text: str = None, + row_index_begin: int = None, + row_index_end: int = None, + column_index_begin: int = None, + column_index_end: int = None) -> None: """ Initialize a TableHeaders object. @@ -4679,7 +4578,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableHeaders': """Initialize a TableHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -4707,7 +4606,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableHeaders 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, 'cell_id') and self.cell_id is not None: @@ -4730,17 +4634,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 TableHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableHeaders') -> 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): + def __ne__(self, other: 'TableHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4750,23 +4658,26 @@ class TableKeyValuePairs(): Key-value pairs detected across cell boundaries. :attr TableCellKey key: (optional) A key in a key-value pair. - :attr list[TableCellValues] value: (optional) A list of values in a key-value + :attr List[TableCellValues] value: (optional) A list of values in a key-value pair. """ - def __init__(self, *, key=None, value=None): + def __init__(self, + *, + key: 'TableCellKey' = None, + value: List['TableCellValues'] = None) -> None: """ Initialize a TableKeyValuePairs object. :param TableCellKey key: (optional) A key in a key-value pair. - :param list[TableCellValues] value: (optional) A list of values in a + :param List[TableCellValues] value: (optional) A list of values in a key-value pair. """ self.key = key self.value = value @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableKeyValuePairs': """Initialize a TableKeyValuePairs object from a json dictionary.""" args = {} valid_keys = ['key', 'value'] @@ -4783,7 +4694,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableKeyValuePairs 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, 'key') and self.key is not None: @@ -4792,17 +4708,21 @@ def _to_dict(self): _dict['value'] = [x._to_dict() for x in self.value] return _dict - def __str__(self): - """Return a `str` version of this TableKeyValuePairs object.""" + 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 TableKeyValuePairs object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableKeyValuePairs') -> 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): + def __ne__(self, other: 'TableKeyValuePairs') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4820,35 +4740,35 @@ class TableResultTable(): within a table. :attr TableTextLocation title: (optional) Text and associated location within a table. - :attr list[TableHeaders] table_headers: (optional) An array of table-level cells + :attr List[TableHeaders] table_headers: (optional) An array of table-level cells that apply as headers to all the other cells in the current table. - :attr list[TableRowHeaders] row_headers: (optional) An array of row-level cells, + :attr List[TableRowHeaders] row_headers: (optional) An array of row-level cells, each applicable as a header to other cells in the same row as itself, of the current table. - :attr list[TableColumnHeaders] column_headers: (optional) An array of + :attr List[TableColumnHeaders] column_headers: (optional) An array of column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. - :attr list[TableKeyValuePairs] key_value_pairs: (optional) An array of key-value + :attr List[TableKeyValuePairs] key_value_pairs: (optional) An array of key-value pairs identified in the current table. - :attr list[TableBodyCells] body_cells: (optional) An array of cells that are + :attr List[TableBodyCells] body_cells: (optional) An array of cells that are neither table header nor column header nor row header cells, of the current table with corresponding row and column header associations. - :attr list[TableTextLocation] contexts: (optional) An array of lists of textual + :attr List[TableTextLocation] contexts: (optional) An array of lists of textual entries across the document related to the current table being parsed. """ def __init__(self, *, - location=None, - text=None, - section_title=None, - title=None, - table_headers=None, - row_headers=None, - column_headers=None, - key_value_pairs=None, - body_cells=None, - contexts=None): + location: 'TableElementLocation' = None, + text: str = None, + section_title: 'TableTextLocation' = None, + title: 'TableTextLocation' = None, + table_headers: List['TableHeaders'] = None, + row_headers: List['TableRowHeaders'] = None, + column_headers: List['TableColumnHeaders'] = None, + key_value_pairs: List['TableKeyValuePairs'] = None, + body_cells: List['TableBodyCells'] = None, + contexts: List['TableTextLocation'] = None) -> None: """ Initialize a TableResultTable object. @@ -4861,20 +4781,20 @@ def __init__(self, location within a table. :param TableTextLocation title: (optional) Text and associated location within a table. - :param list[TableHeaders] table_headers: (optional) An array of table-level + :param List[TableHeaders] table_headers: (optional) An array of table-level cells that apply as headers to all the other cells in the current table. - :param list[TableRowHeaders] row_headers: (optional) An array of row-level + :param List[TableRowHeaders] row_headers: (optional) An array of row-level cells, each applicable as a header to other cells in the same row as itself, of the current table. - :param list[TableColumnHeaders] column_headers: (optional) An array of + :param List[TableColumnHeaders] column_headers: (optional) An array of column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. - :param list[TableKeyValuePairs] key_value_pairs: (optional) An array of + :param List[TableKeyValuePairs] key_value_pairs: (optional) An array of key-value pairs identified in the current table. - :param list[TableBodyCells] body_cells: (optional) An array of cells that + :param List[TableBodyCells] body_cells: (optional) An array of cells that are neither table header nor column header nor row header cells, of the current table with corresponding row and column header associations. - :param list[TableTextLocation] contexts: (optional) An array of lists of + :param List[TableTextLocation] contexts: (optional) An array of lists of textual entries across the document related to the current table being parsed. """ @@ -4890,7 +4810,7 @@ def __init__(self, self.contexts = contexts @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableResultTable': """Initialize a TableResultTable object from a json dictionary.""" args = {} valid_keys = [ @@ -4942,7 +4862,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableResultTable 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, 'location') and self.location is not None: @@ -4972,17 +4897,21 @@ def _to_dict(self): _dict['contexts'] = [x._to_dict() for x in self.contexts] return _dict - def __str__(self): + 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 TableResultTable object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableResultTable') -> 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): + def __ne__(self, other: 'TableResultTable') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4995,7 +4924,7 @@ class TableRowHeaderIds(): :attr str id: (optional) The `id` values of a row header. """ - def __init__(self, *, id=None): + def __init__(self, *, id: str = None) -> None: """ Initialize a TableRowHeaderIds object. @@ -5004,7 +4933,7 @@ def __init__(self, *, id=None): self.id = id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableRowHeaderIds': """Initialize a TableRowHeaderIds object from a json dictionary.""" args = {} valid_keys = ['id'] @@ -5017,24 +4946,33 @@ def _from_dict(cls, _dict): args['id'] = _dict.get('id') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableRowHeaderIds 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, 'id') and self.id is not None: _dict['id'] = self.id return _dict - def __str__(self): + 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 TableRowHeaderIds object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableRowHeaderIds') -> 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): + def __ne__(self, other: 'TableRowHeaderIds') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5047,7 +4985,7 @@ class TableRowHeaderTexts(): :attr str text: (optional) The `text` value of a row header. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a TableRowHeaderTexts object. @@ -5056,7 +4994,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTexts': """Initialize a TableRowHeaderTexts object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -5069,24 +5007,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableRowHeaderTexts 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, 'text') and self.text is not None: _dict['text'] = self.text return _dict - def __str__(self): + 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 TableRowHeaderTexts object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableRowHeaderTexts') -> 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): + def __ne__(self, other: 'TableRowHeaderTexts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5100,7 +5047,7 @@ class TableRowHeaderTextsNormalized(): text. """ - def __init__(self, *, text_normalized=None): + def __init__(self, *, text_normalized: str = None) -> None: """ Initialize a TableRowHeaderTextsNormalized object. @@ -5110,7 +5057,7 @@ def __init__(self, *, text_normalized=None): self.text_normalized = text_normalized @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTextsNormalized': """Initialize a TableRowHeaderTextsNormalized object from a json dictionary.""" args = {} valid_keys = ['text_normalized'] @@ -5123,7 +5070,12 @@ def _from_dict(cls, _dict): args['text_normalized'] = _dict.get('text_normalized') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableRowHeaderTextsNormalized 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, @@ -5131,17 +5083,21 @@ def _to_dict(self): _dict['text_normalized'] = self.text_normalized return _dict - def __str__(self): + 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 TableRowHeaderTextsNormalized object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableRowHeaderTextsNormalized') -> 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): + def __ne__(self, other: 'TableRowHeaderTextsNormalized') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5172,14 +5128,14 @@ class TableRowHeaders(): def __init__(self, *, - cell_id=None, - location=None, - text=None, - text_normalized=None, - row_index_begin=None, - row_index_end=None, - column_index_begin=None, - column_index_end=None): + cell_id: str = None, + location: 'TableElementLocation' = None, + text: str = None, + text_normalized: str = None, + row_index_begin: int = None, + row_index_end: int = None, + column_index_begin: int = None, + column_index_end: int = None) -> None: """ Initialize a TableRowHeaders object. @@ -5212,7 +5168,7 @@ def __init__(self, self.column_index_end = column_index_end @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableRowHeaders': """Initialize a TableRowHeaders object from a json dictionary.""" args = {} valid_keys = [ @@ -5243,7 +5199,12 @@ def _from_dict(cls, _dict): args['column_index_end'] = _dict.get('column_index_end') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableRowHeaders 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, 'cell_id') and self.cell_id is not None: @@ -5269,17 +5230,21 @@ def _to_dict(self): _dict['column_index_end'] = self.column_index_end return _dict - def __str__(self): + 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 TableRowHeaders object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableRowHeaders') -> 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): + def __ne__(self, other: 'TableRowHeaders') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5294,7 +5259,10 @@ class TableTextLocation(): `begin` and `end`. """ - def __init__(self, *, text=None, location=None): + def __init__(self, + *, + text: str = None, + location: 'TableElementLocation' = None) -> None: """ Initialize a TableTextLocation object. @@ -5307,7 +5275,7 @@ def __init__(self, *, text=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TableTextLocation': """Initialize a TableTextLocation object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -5323,7 +5291,12 @@ def _from_dict(cls, _dict): _dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TableTextLocation 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, 'text') and self.text is not None: @@ -5332,17 +5305,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 TableTextLocation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TableTextLocation') -> 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): + def __ne__(self, other: 'TableTextLocation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5355,17 +5332,17 @@ class TrainingExample(): :attr str collection_id: The collection ID associated with this training example. :attr int relevance: The relevance of the training example. - :attr date created: (optional) The date and time the example was created. - :attr date updated: (optional) The date and time the example was updated. + :attr datetime created: (optional) The date and time the example was created. + :attr datetime updated: (optional) The date and time the example was updated. """ def __init__(self, - document_id, - collection_id, - relevance, + document_id: str, + collection_id: str, + relevance: int, *, - created=None, - updated=None): + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a TrainingExample object. @@ -5374,8 +5351,10 @@ def __init__(self, :param str collection_id: The collection ID associated with this training example. :param int relevance: The relevance of the training example. - :param date created: (optional) The date and time the example was created. - :param date updated: (optional) The date and time the example was updated. + :param datetime created: (optional) The date and time the example was + created. + :param datetime updated: (optional) The date and time the example was + updated. """ self.document_id = document_id self.collection_id = collection_id @@ -5384,7 +5363,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingExample': """Initialize a TrainingExample object from a json dictionary.""" args = {} valid_keys = [ @@ -5414,12 +5393,17 @@ def _from_dict(cls, _dict): 'Required property \'relevance\' not present in TrainingExample JSON' ) if 'created' in _dict: - args['created'] = _dict.get('created') + args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: - args['updated'] = _dict.get('updated') + args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingExample 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, 'document_id') and self.document_id is not None: @@ -5429,22 +5413,26 @@ def _to_dict(self): if hasattr(self, 'relevance') and self.relevance is not None: _dict['relevance'] = self.relevance if hasattr(self, 'created') and self.created is not None: - _dict['created'] = self.created + _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = self.updated + _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 TrainingExample object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingExample') -> 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): + def __ne__(self, other: 'TrainingExample') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5457,31 +5445,33 @@ class TrainingQuery(): :attr str natural_language_query: The natural text query for the training query. :attr str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :attr date created: (optional) The date and time the query was created. - :attr date updated: (optional) The date and time the query was updated. - :attr list[TrainingExample] examples: Array of training examples. + :attr datetime created: (optional) The date and time the query was created. + :attr datetime updated: (optional) The date and time the query was updated. + :attr List[TrainingExample] examples: Array of training examples. """ def __init__(self, - natural_language_query, - examples, + natural_language_query: str, + examples: List['TrainingExample'], *, - query_id=None, - filter=None, - created=None, - updated=None): + query_id: str = None, + filter: str = None, + created: datetime = None, + updated: datetime = None) -> None: """ Initialize a TrainingQuery object. :param str natural_language_query: The natural text query for the training query. - :param list[TrainingExample] examples: Array of training examples. + :param List[TrainingExample] examples: Array of training examples. :param str query_id: (optional) The query ID associated with the training query. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :param date created: (optional) The date and time the query was created. - :param date updated: (optional) The date and time the query was updated. + :param datetime created: (optional) The date and time the query was + created. + :param datetime updated: (optional) The date and time the query was + updated. """ self.query_id = query_id self.natural_language_query = natural_language_query @@ -5491,7 +5481,7 @@ def __init__(self, self.examples = examples @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingQuery': """Initialize a TrainingQuery object from a json dictionary.""" args = {} valid_keys = [ @@ -5514,9 +5504,9 @@ def _from_dict(cls, _dict): if 'filter' in _dict: args['filter'] = _dict.get('filter') if 'created' in _dict: - args['created'] = _dict.get('created') + args['created'] = string_to_datetime(_dict.get('created')) if 'updated' in _dict: - args['updated'] = _dict.get('updated') + args['updated'] = string_to_datetime(_dict.get('updated')) if 'examples' in _dict: args['examples'] = [ TrainingExample._from_dict(x) for x in (_dict.get('examples')) @@ -5527,7 +5517,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingQuery 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, 'query_id') and self.query_id is not None: @@ -5538,24 +5533,28 @@ def _to_dict(self): if hasattr(self, 'filter') and self.filter is not None: _dict['filter'] = self.filter if hasattr(self, 'created') and self.created is not None: - _dict['created'] = self.created + _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = self.updated + _dict['updated'] = datetime_to_string(self.updated) if hasattr(self, 'examples') and self.examples is not None: _dict['examples'] = [x._to_dict() for x in self.examples] return _dict - def __str__(self): + 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 TrainingQuery object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingQuery') -> 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): + def __ne__(self, other: 'TrainingQuery') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5564,19 +5563,19 @@ class TrainingQuerySet(): """ Object specifying the training queries contained in the identified training set. - :attr list[TrainingQuery] queries: (optional) Array of training queries. + :attr List[TrainingQuery] queries: (optional) Array of training queries. """ - def __init__(self, *, queries=None): + def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: """ Initialize a TrainingQuerySet object. - :param list[TrainingQuery] queries: (optional) Array of training queries. + :param List[TrainingQuery] queries: (optional) Array of training queries. """ self.queries = queries @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingQuerySet': """Initialize a TrainingQuerySet object from a json dictionary.""" args = {} valid_keys = ['queries'] @@ -5591,23 +5590,734 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingQuerySet 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, 'queries') and self.queries is not None: _dict['queries'] = [x._to_dict() for x in self.queries] return _dict - def __str__(self): + 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 TrainingQuerySet object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingQuerySet') -> 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: 'TrainingQuerySet') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryCalculationAggregation(QueryAggregation): + """ + Returns a scalar calculation across all documents for the field specified. Possible + calculations include min, max, sum, average, and unique_count. + + :attr str field: The field to perform the calculation on. + :attr float value: (optional) The value of the calculation. + """ + + def __init__(self, type: str, field: str, *, value: float = None) -> None: + """ + Initialize a QueryCalculationAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str field: The field to perform the calculation on. + :param float value: (optional) The value of the calculation. + """ + self.type = type + self.field = field + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': + """Initialize a QueryCalculationAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'field', 'value'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryCalculationAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryCalculationAggregation JSON' + ) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryCalculationAggregation JSON' + ) + if 'value' in _dict: + args['value'] = _dict.get('value') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryCalculationAggregation 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 + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + 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 QueryCalculationAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryCalculationAggregation') -> 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: 'QueryCalculationAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryFilterAggregation(QueryAggregation): + """ + A modifier that will narrow down the document set of the sub aggregations it precedes. + + :attr str match: The filter written in Discovery Query Language syntax applied + to the documents before sub aggregations are run. + :attr int matching_results: Number of documents matching the filter. + :attr List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + + def __init__(self, + type: str, + match: str, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: + """ + Initialize a QueryFilterAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str match: The filter written in Discovery Query Language syntax + applied to the documents before sub aggregations are run. + :param int matching_results: Number of documents matching the filter. + :param List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + self.type = type + self.match = match + self.matching_results = matching_results + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': + """Initialize a QueryFilterAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'match', 'matching_results', 'aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryFilterAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryFilterAggregation JSON' + ) + if 'match' in _dict: + args['match'] = _dict.get('match') + else: + raise ValueError( + 'Required property \'match\' not present in QueryFilterAggregation JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryFilterAggregation 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 + if hasattr(self, 'match') and self.match is not None: + _dict['match'] = self.match + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + 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 QueryFilterAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryFilterAggregation') -> 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: 'QueryFilterAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryHistogramAggregation(QueryAggregation): + """ + Numeric interval segments to categorize documents by using field values from a single + numeric field to describe the category. + + :attr str field: The numeric field name used to create the histogram. + :attr int interval: The size of the sections the results are split into. + :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric + intervals. + """ + + def __init__(self, + type: str, + field: str, + interval: int, + *, + results: List['QueryHistogramAggregationResult'] = None + ) -> None: + """ + Initialize a QueryHistogramAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str field: The numeric field name used to create the histogram. + :param int interval: The size of the sections the results are split into. + :param List[QueryHistogramAggregationResult] results: (optional) Array of + numeric intervals. + """ + self.type = type + self.field = field + self.interval = interval + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': + """Initialize a QueryHistogramAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'field', 'interval', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryHistogramAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryHistogramAggregation JSON' + ) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryHistogramAggregation JSON' + ) + if 'interval' in _dict: + args['interval'] = _dict.get('interval') + else: + raise ValueError( + 'Required property \'interval\' not present in QueryHistogramAggregation JSON' + ) + if 'results' in _dict: + args['results'] = [ + QueryHistogramAggregationResult._from_dict(x) + for x in (_dict.get('results')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryHistogramAggregation 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 + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'interval') and self.interval is not None: + _dict['interval'] = self.interval + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + 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 QueryHistogramAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryHistogramAggregation') -> 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: 'QueryHistogramAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryNestedAggregation(QueryAggregation): + """ + A restriction that alter the document set used for sub aggregations it precedes to + nested documents found in the field specified. + + :attr str path: The path to the document field to scope sub aggregations to. + :attr int matching_results: Number of nested documents found in the specified + field. + :attr List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + + def __init__(self, + type: str, + path: str, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: + """ + Initialize a QueryNestedAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str path: The path to the document field to scope sub aggregations + to. + :param int matching_results: Number of nested documents found in the + specified field. + :param List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + self.type = type + self.path = path + self.matching_results = matching_results + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': + """Initialize a QueryNestedAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'path', 'matching_results', 'aggregations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryNestedAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryNestedAggregation JSON' + ) + if 'path' in _dict: + args['path'] = _dict.get('path') + else: + raise ValueError( + 'Required property \'path\' not present in QueryNestedAggregation JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryNestedAggregation 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 + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + 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 QueryNestedAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryNestedAggregation') -> 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: 'QueryNestedAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTermAggregation(QueryAggregation): + """ + Returns the top values for the field specified. + + :attr str field: The field in the document used to generate top values from. + :attr int count: (optional) The number of top values returned. + :attr List[QueryTermAggregationResult] results: (optional) Array of top values + for the field. + """ + + def __init__(self, + type: str, + field: str, + *, + count: int = None, + results: List['QueryTermAggregationResult'] = None) -> None: + """ + Initialize a QueryTermAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str field: The field in the document used to generate top values + from. + :param int count: (optional) The number of top values returned. + :param List[QueryTermAggregationResult] results: (optional) Array of top + values for the field. + """ + self.type = type + self.field = field + self.count = count + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': + """Initialize a QueryTermAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'field', 'count', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTermAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryTermAggregation JSON' + ) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryTermAggregation JSON' + ) + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'results' in _dict: + args['results'] = [ + QueryTermAggregationResult._from_dict(x) + for x in (_dict.get('results')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTermAggregation 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 + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + 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 QueryTermAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryTermAggregation') -> 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: 'QueryTermAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTimesliceAggregation(QueryAggregation): + """ + A specialized histogram aggregation that uses dates to create interval segments. + + :attr str field: The date field name used to create the timeslice. + :attr str interval: The date interval value. Valid values are seconds, minutes, + hours, days, weeks, and years. + :attr List[QueryTimesliceAggregationResult] results: (optional) Array of + aggregation results. + """ + + def __init__(self, + type: str, + field: str, + interval: str, + *, + results: List['QueryTimesliceAggregationResult'] = None + ) -> None: + """ + Initialize a QueryTimesliceAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param str field: The date field name used to create the timeslice. + :param str interval: The date interval value. Valid values are seconds, + minutes, hours, days, weeks, and years. + :param List[QueryTimesliceAggregationResult] results: (optional) Array of + aggregation results. + """ + self.type = type + self.field = field + self.interval = interval + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': + """Initialize a QueryTimesliceAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'field', 'interval', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTimesliceAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryTimesliceAggregation JSON' + ) + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryTimesliceAggregation JSON' + ) + if 'interval' in _dict: + args['interval'] = _dict.get('interval') + else: + raise ValueError( + 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' + ) + if 'results' in _dict: + args['results'] = [ + QueryTimesliceAggregationResult._from_dict(x) + for x in (_dict.get('results')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTimesliceAggregation 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 + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'interval') and self.interval is not None: + _dict['interval'] = self.interval + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + 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 QueryTimesliceAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryTimesliceAggregation') -> 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: 'QueryTimesliceAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTopHitsAggregation(QueryAggregation): + """ + Returns the top documents ranked by the score of the query. + + :attr int size: The number of documents to return. + :attr QueryTopHitsAggregationResult hits: (optional) + """ + + def __init__(self, + type: str, + size: int, + *, + hits: 'QueryTopHitsAggregationResult' = None) -> None: + """ + Initialize a QueryTopHitsAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param int size: The number of documents to return. + :param QueryTopHitsAggregationResult hits: (optional) + """ + self.type = type + self.size = size + self.hits = hits + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': + """Initialize a QueryTopHitsAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'size', 'hits'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryTopHitsAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryTopHitsAggregation JSON' + ) + if 'size' in _dict: + args['size'] = _dict.get('size') + else: + raise ValueError( + 'Required property \'size\' not present in QueryTopHitsAggregation JSON' + ) + if 'hits' in _dict: + args['hits'] = QueryTopHitsAggregationResult._from_dict( + _dict.get('hits')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTopHitsAggregation 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 + if hasattr(self, 'size') and self.size is not None: + _dict['size'] = self.size + if hasattr(self, 'hits') and self.hits is not None: + _dict['hits'] = self.hits._to_dict() + 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 QueryTopHitsAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryTopHitsAggregation') -> 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): + def __ne__(self, other: 'QueryTopHitsAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index da2d2caad..fedc9e9bd 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,10 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. +from datetime import datetime from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json +import pytest import responses import tempfile +import ibm_watson.discovery_v2 from ibm_watson.discovery_v2 import * base_url = 'https://fake' @@ -26,7 +30,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_collections #----------------------------------------------------------------------------- @@ -58,8 +61,7 @@ def test_list_collections_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_collections_empty(self): - check_empty_required_params(self, - fake_response_ListCollectionsResponse_json) + check_empty_required_params(self, fake_response_ListCollectionsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -73,14 +75,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.list_collections(**body) return output @@ -106,7 +110,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for query #----------------------------------------------------------------------------- @@ -152,14 +155,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.query(**body) return output @@ -167,39 +172,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['project_id'] = "string1" - body.update({ - "collection_ids": [], - "filter": - "string1", - "query": - "string1", - "natural_language_query": - "string1", - "aggregation": - "string1", - "count": - 12345, - "return_": [], - "offset": - 12345, - "sort": - "string1", - "highlight": - True, - "spelling_suggestions": - True, - "table_results": - QueryLargeTableResults._from_dict( - json.loads("""{"enabled": false, "count": 5}""")), - "suggested_refinements": - QueryLargeSuggestedRefinements._from_dict( - json.loads("""{"enabled": false, "count": 5}""")), - "passages": - QueryLargePassages._from_dict( - json.loads( - """{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""" - )), - }) + body.update({"collection_ids": [], "filter": "string1", "query": "string1", "natural_language_query": "string1", "aggregation": "string1", "count": 12345, "return_": [], "offset": 12345, "sort": "string1", "highlight": True, "spelling_suggestions": True, "table_results": QueryLargeTableResults._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "suggested_refinements": QueryLargeSuggestedRefinements._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "passages": QueryLargePassages._from_dict(json.loads("""{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""")), }) return body def construct_required_body(self): @@ -253,14 +226,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.get_autocompletion(**body) return output @@ -312,8 +287,7 @@ def test_query_notices_required_response(self): #-------------------------------------------------------- @responses.activate def test_query_notices_empty(self): - check_empty_required_params(self, - fake_response_QueryNoticesResponse_json) + check_empty_required_params(self, fake_response_QueryNoticesResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -327,14 +301,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.query_notices(**body) return output @@ -400,14 +376,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.list_fields(**body) return output @@ -434,7 +412,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for get_component_settings #----------------------------------------------------------------------------- @@ -466,8 +443,7 @@ def test_get_component_settings_required_response(self): #-------------------------------------------------------- @responses.activate def test_get_component_settings_empty(self): - check_empty_required_params( - self, fake_response_ComponentSettingsResponse_json) + check_empty_required_params(self, fake_response_ComponentSettingsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -475,21 +451,22 @@ def test_get_component_settings_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/component_settings'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/component_settings'.format(body['project_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.get_component_settings(**body) return output @@ -515,7 +492,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for add_document #----------------------------------------------------------------------------- @@ -555,21 +531,22 @@ def test_add_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents'.format( - body['project_id'], body['collection_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents'.format(body['project_id'], body['collection_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.add_document(**body) return output @@ -631,21 +608,22 @@ def test_update_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( - body['project_id'], body['collection_id'], body['document_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.update_document(**body) return output @@ -701,8 +679,7 @@ def test_delete_document_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_document_empty(self): - check_empty_required_params(self, - fake_response_DeleteDocumentResponse_json) + check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -710,21 +687,22 @@ def test_delete_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( - body['project_id'], body['collection_id'], body['document_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -755,7 +733,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_training_queries #----------------------------------------------------------------------------- @@ -795,21 +772,22 @@ def test_list_training_queries_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.list_training_queries(**body) return output @@ -864,21 +842,22 @@ def test_delete_training_queries_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.delete_training_queries(**body) return output @@ -933,21 +912,22 @@ def test_create_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.create_training_query(**body) return output @@ -955,20 +935,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['project_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - "filter": "string1", - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body def construct_required_body(self): body = dict() body['project_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body @@ -1011,21 +984,22 @@ def test_get_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( - body['project_id'], body['query_id']) + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.get_training_query(**body) return output @@ -1082,21 +1056,22 @@ def test_update_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( - body['project_id'], body['query_id']) + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): - service = DiscoveryV2(authenticator=NoAuthAuthenticator(), - version='2019-11-22') + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) service.set_service_url(base_url) output = service.update_training_query(**body) return output @@ -1105,22 +1080,14 @@ def construct_full_body(self): body = dict() body['project_id'] = "string1" body['query_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - "filter": "string1", - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body def construct_required_body(self): body = dict() body['project_id'] = "string1" body['query_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - "filter": "string1", - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body @@ -1146,7 +1113,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -1163,7 +1129,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -1175,7 +1140,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -1192,7 +1156,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### @@ -1208,6 +1171,6 @@ def send_request(obj, body, response, url=None): fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" fake_response_DeleteDocumentResponse_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" fake_response_TrainingQuerySet_json = """{"queries": []}""" -fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" -fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" -fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" +fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" From 935fd7a8bf932ded30b063b898fa151e5bd12291 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 15:34:02 -0500 Subject: [PATCH 176/455] refactor(ltv3): regenrate language translate v3 with tests --- ibm_watson/language_translator_v3.py | 540 +++++---- test/unit/test_language_translator_v3.py | 1334 ++++++++++++++++------ 2 files changed, 1302 insertions(+), 572 deletions(-) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 9b0612b73..39c70bf37 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,13 +22,20 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService 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 import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +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 +from typing import List +from typing import TextIO ############################################################################## # Service @@ -38,13 +45,15 @@ class LanguageTranslatorV3(BaseService): """The Language Translator V3 service.""" - default_service_url = 'https://gateway.watsonplatform.net/language-translator/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/language-translator/api' + DEFAULT_SERVICE_NAME = 'language_translator' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Language Translator service. @@ -63,43 +72,32 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('language_translator') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'language_translator') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Translation ######################### def translate(self, - text, + text: List[str], *, - model_id=None, - source=None, - target=None, - **kwargs): + model_id: str = None, + source: str = None, + target: str = None, + **kwargs) -> 'DetailedResponse': """ Translate. Translates the input text from the source language to the target language. - :param list[str] text: Input text in UTF-8 encoding. Multiple entries will + :param List[str] text: Input text in UTF-8 encoding. Multiple entries will result in multiple translations in the response. :param str model_id: (optional) A globally unique string that identifies the underlying model that is used for translation. @@ -116,7 +114,9 @@ def translate(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', 'translate') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='translate') headers.update(sdk_headers) params = {'version': self.version} @@ -133,8 +133,8 @@ def translate(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -142,7 +142,7 @@ def translate(self, # Identification ######################### - def list_identifiable_languages(self, **kwargs): + def list_identifiable_languages(self, **kwargs) -> 'DetailedResponse': """ List identifiable languages. @@ -157,8 +157,10 @@ def list_identifiable_languages(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - 'list_identifiable_languages') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_identifiable_languages') headers.update(sdk_headers) params = {'version': self.version} @@ -167,12 +169,12 @@ def list_identifiable_languages(self, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def identify(self, text, **kwargs): + def identify(self, text: str, **kwargs) -> 'DetailedResponse': """ Identify language. @@ -190,7 +192,9 @@ def identify(self, text, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', 'identify') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='identify') headers.update(sdk_headers) params = {'version': self.version} @@ -203,8 +207,8 @@ def identify(self, text, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -212,7 +216,12 @@ def identify(self, text, **kwargs): # Models ######################### - def list_models(self, *, source=None, target=None, default=None, **kwargs): + def list_models(self, + *, + source: str = None, + target: str = None, + default: bool = None, + **kwargs) -> 'DetailedResponse': """ List models. @@ -235,8 +244,9 @@ def list_models(self, *, source=None, target=None, default=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - 'list_models') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_models') headers.update(sdk_headers) params = { @@ -250,18 +260,18 @@ def list_models(self, *, source=None, target=None, default=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def create_model(self, - base_model_id, + base_model_id: str, *, - forced_glossary=None, - parallel_corpus=None, - name=None, - **kwargs): + forced_glossary: BinaryIO = None, + parallel_corpus: BinaryIO = None, + name: str = None, + **kwargs) -> 'DetailedResponse': """ Create model. @@ -284,17 +294,17 @@ def create_model(self, Usually all IBM provided models are customizable. In addition, all your models that have been created via parallel corpus customization, can be further customized with a forced glossary. - :param file forced_glossary: (optional) A TMX file with your + :param TextIO forced_glossary: (optional) A TMX file with your customizations. The customizations in the file completely overwrite the domain translaton data, including high frequency or high confidence phrase translations. You can upload only one glossary with a file size less than 10 MB per call. A forced glossary should contain single words or short phrases. - :param file parallel_corpus: (optional) A TMX file with parallel sentences - for source and target language. You can upload multiple parallel_corpus - files in one request. All uploaded parallel_corpus files combined, your - parallel corpus must contain at least 5,000 parallel sentences to train - successfully. + :param TextIO parallel_corpus: (optional) A TMX file with parallel + sentences for source and target language. You can upload multiple + parallel_corpus files in one request. All uploaded parallel_corpus files + combined, your parallel corpus must contain at least 5,000 parallel + sentences to train successfully. :param str name: (optional) An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces and apostrophes. The maximum length is 32 characters. @@ -309,8 +319,9 @@ def create_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - 'create_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='create_model') headers.update(sdk_headers) params = { @@ -332,12 +343,12 @@ def create_model(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def delete_model(self, model_id, **kwargs): + def delete_model(self, model_id: str, **kwargs) -> 'DetailedResponse': """ Delete model. @@ -355,8 +366,9 @@ def delete_model(self, model_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - 'delete_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='delete_model') headers.update(sdk_headers) params = {'version': self.version} @@ -365,12 +377,12 @@ def delete_model(self, model_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_model(self, model_id, **kwargs): + def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': """ Get model details. @@ -390,7 +402,9 @@ def get_model(self, model_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', 'get_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_model') headers.update(sdk_headers) params = {'version': self.version} @@ -399,8 +413,8 @@ def get_model(self, model_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -408,7 +422,7 @@ def get_model(self, model_id, **kwargs): # Document translation ######################### - def list_documents(self, **kwargs): + def list_documents(self, **kwargs) -> 'DetailedResponse': """ List documents. @@ -422,8 +436,9 @@ def list_documents(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - 'list_documents') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_documents') headers.update(sdk_headers) params = {'version': self.version} @@ -432,21 +447,21 @@ def list_documents(self, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def translate_document(self, - file, + file: BinaryIO, *, - filename=None, - file_content_type=None, - model_id=None, - source=None, - target=None, - document_id=None, - **kwargs): + filename: str = None, + file_content_type: str = None, + model_id: str = None, + source: str = None, + target: str = None, + document_id: str = None, + **kwargs) -> 'DetailedResponse': """ Translate document. @@ -454,7 +469,7 @@ def translate_document(self, `file` parameter, or you can reference a previously submitted document by document ID. - :param file file: The source file to translate. + :param TextIO file: The contents of the source file to translate. [Supported file types](https://cloud.ibm.com/docs/services/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats) Maximum file size: **20 MB**. @@ -480,8 +495,9 @@ def translate_document(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - 'translate_document') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='translate_document') headers.update(sdk_headers) params = {'version': self.version} @@ -494,12 +510,16 @@ def translate_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if model_id: + model_id = str(model_id) form_data.append(('model_id', (None, model_id, 'text/plain'))) if source: + source = str(source) form_data.append(('source', (None, source, 'text/plain'))) if target: + target = str(target) form_data.append(('target', (None, target, 'text/plain'))) if document_id: + document_id = str(document_id) form_data.append(('document_id', (None, document_id, 'text/plain'))) url = '/v3/documents' @@ -507,12 +527,13 @@ def translate_document(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def get_document_status(self, document_id, **kwargs): + def get_document_status(self, document_id: str, + **kwargs) -> 'DetailedResponse': """ Get document status. @@ -530,8 +551,9 @@ def get_document_status(self, document_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - 'get_document_status') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_document_status') headers.update(sdk_headers) params = {'version': self.version} @@ -540,12 +562,12 @@ def get_document_status(self, document_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_document(self, document_id, **kwargs): + def delete_document(self, document_id: str, **kwargs) -> 'DetailedResponse': """ Delete document. @@ -563,8 +585,9 @@ def delete_document(self, document_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - 'delete_document') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='delete_document') headers.update(sdk_headers) params = {'version': self.version} @@ -573,12 +596,16 @@ def delete_document(self, document_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response - def get_translated_document(self, document_id, *, accept=None, **kwargs): + def get_translated_document(self, + document_id: str, + *, + accept: str = None, + **kwargs) -> 'DetailedResponse': """ Get translated document. @@ -611,20 +638,20 @@ def get_translated_document(self, document_id, *, accept=None, **kwargs): headers = {'Accept': accept} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('language_translator', 'V3', - 'get_translated_document') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_translated_document') headers.update(sdk_headers) params = {'version': self.version} url = '/v3/documents/{0}/translated_document'.format( *self._encode_path_vars(document_id)) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - accept_json=(accept is None or accept == 'application/json')) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + response = self.send(request) return response @@ -713,7 +740,7 @@ class DeleteModelResult(): :attr str status: "OK" indicates that the model was successfully deleted. """ - def __init__(self, status): + def __init__(self, status: str) -> None: """ Initialize a DeleteModelResult object. @@ -722,7 +749,7 @@ def __init__(self, status): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteModelResult': """Initialize a DeleteModelResult object from a json dictionary.""" args = {} valid_keys = ['status'] @@ -739,24 +766,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteModelResult 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, 'status') and self.status is not None: _dict['status'] = self.status return _dict - def __str__(self): + 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 DeleteModelResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteModelResult') -> 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): + def __ne__(self, other: 'DeleteModelResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -765,21 +801,21 @@ class DocumentList(): """ DocumentList. - :attr list[DocumentStatus] documents: An array of all previously submitted + :attr List[DocumentStatus] documents: An array of all previously submitted documents. """ - def __init__(self, documents): + def __init__(self, documents: List['DocumentStatus']) -> None: """ Initialize a DocumentList object. - :param list[DocumentStatus] documents: An array of all previously submitted + :param List[DocumentStatus] documents: An array of all previously submitted documents. """ self.documents = documents @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentList': """Initialize a DocumentList object from a json dictionary.""" args = {} valid_keys = ['documents'] @@ -798,24 +834,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentList 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, 'documents') and self.documents is not None: _dict['documents'] = [x._to_dict() for x in self.documents] return _dict - def __str__(self): + 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 DocumentList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentList') -> 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): + def __ne__(self, other: 'DocumentList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -839,25 +884,25 @@ class DocumentStatus(): :attr str target: Translation target language code. :attr datetime created: The time when the document was submitted. :attr datetime completed: (optional) The time when the translation completed. - :attr int word_count: (optional) The number of words in the source document, - present only if status=available. + :attr int word_count: (optional) An estimate of the number of words in the + source document. Returned only if `status` is `available`. :attr int character_count: (optional) The number of characters in the source document, present only if status=available. """ def __init__(self, - document_id, - filename, - status, - model_id, - source, - target, - created, + document_id: str, + filename: str, + status: str, + model_id: str, + source: str, + target: str, + created: datetime, *, - base_model_id=None, - completed=None, - word_count=None, - character_count=None): + base_model_id: str = None, + completed: datetime = None, + word_count: int = None, + character_count: int = None) -> None: """ Initialize a DocumentStatus object. @@ -877,8 +922,8 @@ def __init__(self, be absent or an empty string. :param datetime completed: (optional) The time when the translation completed. - :param int word_count: (optional) The number of words in the source - document, present only if status=available. + :param int word_count: (optional) An estimate of the number of words in the + source document. Returned only if `status` is `available`. :param int character_count: (optional) The number of characters in the source document, present only if status=available. """ @@ -895,7 +940,7 @@ def __init__(self, self.character_count = character_count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentStatus': """Initialize a DocumentStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -960,7 +1005,12 @@ def _from_dict(cls, _dict): args['character_count'] = _dict.get('character_count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentStatus 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, 'document_id') and self.document_id is not None: @@ -988,17 +1038,21 @@ def _to_dict(self): _dict['character_count'] = self.character_count return _dict - def __str__(self): + 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 DocumentStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentStatus') -> 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): + def __ne__(self, other: 'DocumentStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1019,7 +1073,7 @@ class IdentifiableLanguage(): :attr str name: The name of the identifiable language. """ - def __init__(self, language, name): + def __init__(self, language: str, name: str) -> None: """ Initialize a IdentifiableLanguage object. @@ -1030,7 +1084,7 @@ def __init__(self, language, name): self.name = name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguage': """Initialize a IdentifiableLanguage object from a json dictionary.""" args = {} valid_keys = ['language', 'name'] @@ -1053,7 +1107,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IdentifiableLanguage 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, 'language') and self.language is not None: @@ -1062,17 +1121,21 @@ def _to_dict(self): _dict['name'] = self.name return _dict - def __str__(self): + 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 IdentifiableLanguage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IdentifiableLanguage') -> 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): + def __ne__(self, other: 'IdentifiableLanguage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1081,21 +1144,21 @@ class IdentifiableLanguages(): """ IdentifiableLanguages. - :attr list[IdentifiableLanguage] languages: A list of all languages that the + :attr List[IdentifiableLanguage] languages: A list of all languages that the service can identify. """ - def __init__(self, languages): + def __init__(self, languages: List['IdentifiableLanguage']) -> None: """ Initialize a IdentifiableLanguages object. - :param list[IdentifiableLanguage] languages: A list of all languages that + :param List[IdentifiableLanguage] languages: A list of all languages that the service can identify. """ self.languages = languages @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguages': """Initialize a IdentifiableLanguages object from a json dictionary.""" args = {} valid_keys = ['languages'] @@ -1115,24 +1178,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IdentifiableLanguages 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, 'languages') and self.languages is not None: _dict['languages'] = [x._to_dict() for x in self.languages] return _dict - def __str__(self): + 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 IdentifiableLanguages object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IdentifiableLanguages') -> 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): + def __ne__(self, other: 'IdentifiableLanguages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1145,7 +1217,7 @@ class IdentifiedLanguage(): :attr float confidence: The confidence score for the identified language. """ - def __init__(self, language, confidence): + def __init__(self, language: str, confidence: float) -> None: """ Initialize a IdentifiedLanguage object. @@ -1156,7 +1228,7 @@ def __init__(self, language, confidence): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguage': """Initialize a IdentifiedLanguage object from a json dictionary.""" args = {} valid_keys = ['language', 'confidence'] @@ -1179,7 +1251,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IdentifiedLanguage 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, 'language') and self.language is not None: @@ -1188,17 +1265,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 IdentifiedLanguage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IdentifiedLanguage') -> 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): + def __ne__(self, other: 'IdentifiedLanguage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1207,21 +1288,21 @@ class IdentifiedLanguages(): """ IdentifiedLanguages. - :attr list[IdentifiedLanguage] languages: A ranking of identified languages with + :attr List[IdentifiedLanguage] languages: A ranking of identified languages with confidence scores. """ - def __init__(self, languages): + def __init__(self, languages: List['IdentifiedLanguage']) -> None: """ Initialize a IdentifiedLanguages object. - :param list[IdentifiedLanguage] languages: A ranking of identified + :param List[IdentifiedLanguage] languages: A ranking of identified languages with confidence scores. """ self.languages = languages @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguages': """Initialize a IdentifiedLanguages object from a json dictionary.""" args = {} valid_keys = ['languages'] @@ -1241,24 +1322,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a IdentifiedLanguages 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, 'languages') and self.languages is not None: _dict['languages'] = [x._to_dict() for x in self.languages] return _dict - def __str__(self): + 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 IdentifiedLanguages object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'IdentifiedLanguages') -> 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): + def __ne__(self, other: 'IdentifiedLanguages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1270,7 +1360,7 @@ class Translation(): :attr str translation: Translation output in UTF-8. """ - def __init__(self, translation): + def __init__(self, translation: str) -> None: """ Initialize a Translation object. @@ -1279,7 +1369,7 @@ def __init__(self, translation): self.translation = translation @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Translation': """Initialize a Translation object from a json dictionary.""" args = {} valid_keys = ['translation'] @@ -1296,24 +1386,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Translation 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, 'translation') and self.translation is not None: _dict['translation'] = self.translation return _dict - def __str__(self): + 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 Translation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Translation') -> 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): + def __ne__(self, other: 'Translation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1344,17 +1443,17 @@ class TranslationModel(): """ def __init__(self, - model_id, + model_id: str, *, - name=None, - source=None, - target=None, - base_model_id=None, - domain=None, - customizable=None, - default_model=None, - owner=None, - status=None): + name: str = None, + source: str = None, + target: str = None, + base_model_id: str = None, + domain: str = None, + customizable: bool = None, + default_model: bool = None, + owner: str = None, + status: str = None) -> None: """ Initialize a TranslationModel object. @@ -1392,7 +1491,7 @@ def __init__(self, self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TranslationModel': """Initialize a TranslationModel object from a json dictionary.""" args = {} valid_keys = [ @@ -1430,7 +1529,12 @@ def _from_dict(cls, _dict): args['status'] = _dict.get('status') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TranslationModel 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, 'model_id') and self.model_id is not None: @@ -1455,17 +1559,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 TranslationModel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TranslationModel') -> 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): + def __ne__(self, other: 'TranslationModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1489,19 +1597,19 @@ class TranslationModels(): """ The response type for listing existing translation models. - :attr list[TranslationModel] models: An array of available models. + :attr List[TranslationModel] models: An array of available models. """ - def __init__(self, models): + def __init__(self, models: List['TranslationModel']) -> None: """ Initialize a TranslationModels object. - :param list[TranslationModel] models: An array of available models. + :param List[TranslationModel] models: An array of available models. """ self.models = models @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TranslationModels': """Initialize a TranslationModels object from a json dictionary.""" args = {} valid_keys = ['models'] @@ -1520,24 +1628,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TranslationModels 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, 'models') and self.models is not None: _dict['models'] = [x._to_dict() for x in self.models] return _dict - def __str__(self): + 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 TranslationModels object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TranslationModels') -> 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): + def __ne__(self, other: 'TranslationModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1546,19 +1663,21 @@ class TranslationResult(): """ TranslationResult. - :attr int word_count: Number of words in the input text. + :attr int word_count: An estimate of the number of words in the input text. :attr int character_count: Number of characters in the input text. - :attr list[Translation] translations: List of translation output in UTF-8, + :attr List[Translation] translations: List of translation output in UTF-8, corresponding to the input text entries. """ - def __init__(self, word_count, character_count, translations): + def __init__(self, word_count: int, character_count: int, + translations: List['Translation']) -> None: """ Initialize a TranslationResult object. - :param int word_count: Number of words in the input text. + :param int word_count: An estimate of the number of words in the input + text. :param int character_count: Number of characters in the input text. - :param list[Translation] translations: List of translation output in UTF-8, + :param List[Translation] translations: List of translation output in UTF-8, corresponding to the input text entries. """ self.word_count = word_count @@ -1566,7 +1685,7 @@ def __init__(self, word_count, character_count, translations): self.translations = translations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TranslationResult': """Initialize a TranslationResult object from a json dictionary.""" args = {} valid_keys = ['word_count', 'character_count', 'translations'] @@ -1597,7 +1716,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TranslationResult 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, 'word_count') and self.word_count is not None: @@ -1609,16 +1733,20 @@ def _to_dict(self): _dict['translations'] = [x._to_dict() for x in self.translations] return _dict - def __str__(self): + 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 TranslationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TranslationResult') -> 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): + def __ne__(self, other: 'TranslationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index a46144287..54f08512e 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,385 +1,987 @@ -# coding=utf-8 +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json +import pytest import responses -import time -import jwt -from unittest import TestCase -from os.path import join, dirname -import ibm_watson -from ibm_watson.language_translator_v3 import TranslationResult, TranslationModels, TranslationModel, IdentifiedLanguages, IdentifiableLanguages, DeleteModelResult -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator, IAMAuthenticator - -platform_url = 'https://gateway.watsonplatform.net' -service_path = '/language-translator/api' -base_url = '{0}{1}'.format(platform_url, service_path) - -def get_access_token(): - access_token_layout = { - "username": "dummy", - "role": "Admin", - "permissions": [ - "administrator", - "manage_catalog" - ], - "sub": "admin", - "iss": "sss", - "aud": "sss", - "uid": "sss", - "iat": 3600, - "exp": int(time.time()) - } - - access_token = jwt.encode(access_token_layout, 'secret', algorithm='HS256', headers={'kid': '230498151c214b788dd97f22b85410a5'}) - return access_token.decode('utf-8') - -class TestLanguageTranslatorV3(TestCase): - @classmethod - def setUp(cls): - iam_url = "https://iam.cloud.ibm.com/identity/token" - iam_token_response = { - "access_token": get_access_token(), - "token_type": "Bearer", - "expires_in": 3600, - "expiration": 1524167011, - "refresh_token": "jy4gl91BQ" - } - responses.add( - responses.POST, url=iam_url, body=json.dumps(iam_token_response), status=200) - - @classmethod - @responses.activate - def test_translate_source_target(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) +import tempfile +import ibm_watson.language_translator_v3 +from ibm_watson.language_translator_v3 import * + +base_url = 'https://gateway.watsonplatform.net/language-translator/api' + +############################################################################## +# Start of Service: Translation +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for translate +#----------------------------------------------------------------------------- +class TestTranslate(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_translate_response(self): + body = self.construct_full_body() + response = fake_response_TranslationResult_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_translate_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TranslationResult_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_translate_empty(self): + check_empty_required_params(self, fake_response_TranslationResult_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v3/translate' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "character_count": 19, - "translations": [{"translation": u"Hello, how are you ? \u20ac"}], - "word_count": 4 - } - responses.add( - responses.POST, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - - response = service.translate('Hola, cómo estás? €', source='es', target='en').get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - TranslationResult._from_dict(response) - - @classmethod - @responses.activate - def test_translate_model_id(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - endpoint = '/v3/translate' + 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 = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.translate(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) + return body + + +# endregion +############################################################################## +# End of Service: Translation +############################################################################## + +############################################################################## +# Start of Service: Identification +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_identifiable_languages +#----------------------------------------------------------------------------- +class TestListIdentifiableLanguages(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_identifiable_languages_response(self): + body = self.construct_full_body() + response = fake_response_IdentifiableLanguages_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_identifiable_languages_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_IdentifiableLanguages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_identifiable_languages_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/identifiable_languages' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "character_count": 22, - "translations": [ - { - "translation": "Messi es el mejor" - } - ], - "word_count": 5 - } - responses.add( - responses.POST, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.translate('Messi is the best ever', - model_id='en-es-conversational').get_result() - - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - TranslationResult._from_dict(response) - - @classmethod - @responses.activate - def test_identify(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) + 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 = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.list_identifiable_languages(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for identify +#----------------------------------------------------------------------------- +class TestIdentify(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_identify_response(self): + body = self.construct_full_body() + response = fake_response_IdentifiedLanguages_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_identify_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_IdentifiedLanguages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_identify_empty(self): + check_empty_required_params(self, fake_response_IdentifiedLanguages_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v3/identify' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "languages": [ - { - "confidence": 0.477673, - "language": "zh" - }, - { - "confidence": 0.262053, - "language": "zh-TW" - }, - { - "confidence": 0.00958378, - "language": "en" - } - ] - } - responses.add( - responses.POST, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.identify('祝你有美好的一天').get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - IdentifiedLanguages._from_dict(response) - - @classmethod - @responses.activate - def test_list_identifiable_languages(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - endpoint = '/v3/identifiable_languages' + 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 = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.identify(**body) + return output + + def construct_full_body(self): + body = dict() + body['text'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['text'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Identification +############################################################################## + +############################################################################## +# Start of Service: Models +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_models +#----------------------------------------------------------------------------- +class TestListModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_response(self): + body = self.construct_full_body() + response = fake_response_TranslationModels_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_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TranslationModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/models' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "languages": [ - { - "name": "German", - "language": "de" - }, - { - "name": "Greek", - "language": "el" - }, - { - "name": "English", - "language": "en" - }, - { - "name": "Esperanto", - "language": "eo" - }, - { - "name": "Spanish", - "language": "es" - }, - { - "name": "Chinese", - "language": "zh" - } - ] - } - responses.add( - responses.GET, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.list_identifiable_languages().get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - IdentifiableLanguages._from_dict(response) - - @classmethod - @responses.activate - def test_create_model(cls): - authenticator = BasicAuthenticator('xxx', 'yyy') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) + 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 = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.list_models(**body) + return output + + def construct_full_body(self): + body = dict() + body['source'] = "string1" + body['target'] = "string1" + body['default'] = True + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_model +#----------------------------------------------------------------------------- +class TestCreateModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_model_response(self): + body = self.construct_full_body() + response = fake_response_TranslationModel_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_create_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TranslationModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_model_empty(self): + check_empty_required_params(self, fake_response_TranslationModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v3/models' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "status": "available", - "model_id": "en-es-conversational", - "domain": "conversational", - "target": "es", - "customizable": False, - "source": "en", - "base_model_id": "en-es-conversational", - "owner": "", - "default_model": False, - "name": "test_glossary" - } - responses.add( - responses.POST, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - with open(join(dirname(__file__), '../../resources/language_translator_model.tmx'), 'rb') as custom_model: - response = service.create_model('en-fr', - name='test_glossary', - forced_glossary=custom_model).get_result() + 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 = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.create_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['base_model_id'] = "string1" + body['forced_glossary'] = tempfile.NamedTemporaryFile() + body['parallel_corpus'] = tempfile.NamedTemporaryFile() + body['name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['base_model_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_model +#----------------------------------------------------------------------------- +class TestDeleteModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_model_response(self): + body = self.construct_full_body() + response = fake_response_DeleteModelResult_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_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteModelResult_json + send_request(self, body, response) assert len(responses.calls) == 1 - assert responses.calls[0].request.url.startswith(url) - assert response == expected - TranslationModel._from_dict(response) - @classmethod + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- @responses.activate - def test_delete_model(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - model_id = 'en-es-conversational' - endpoint = '/v3/models/' + model_id + def test_delete_model_empty(self): + check_empty_required_params(self, fake_response_DeleteModelResult_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/models/{0}'.format(body['model_id']) url = '{0}{1}'.format(base_url, endpoint) - expected = { - "status": "OK", - } - responses.add( - responses.DELETE, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.delete_model(model_id).get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - DeleteModelResult._from_dict(response) - - @classmethod - @responses.activate - def test_get_model(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - model_id = 'en-es-conversational' - endpoint = '/v3/models/' + model_id + return url + + def add_mock_response(self, url, response): + responses.add(responses.DELETE, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.delete_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['model_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['model_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_model +#----------------------------------------------------------------------------- +class TestGetModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_response(self): + body = self.construct_full_body() + response = fake_response_TranslationModel_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_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TranslationModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_empty(self): + check_empty_required_params(self, fake_response_TranslationModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/models/{0}'.format(body['model_id']) url = '{0}{1}'.format(base_url, endpoint) - expected = { - "status": "available", - "model_id": "en-es-conversational", - "domain": "conversational", - "target": "es", - "customizable": False, - "source": "en", - "base_model_id": "", - "owner": "", - "default_model": False, - "name": "en-es-conversational" - } - responses.add( - responses.GET, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.get_model(model_id).get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - TranslationModel._from_dict(response) - - @classmethod - @responses.activate - def test_list_models(cls): - authenticator = IAMAuthenticator('apikey') - service = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - endpoint = '/v3/models' + 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 = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.get_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['model_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['model_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Models +############################################################################## + +############################################################################## +# Start of Service: DocumentTranslation +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_documents +#----------------------------------------------------------------------------- +class TestListDocuments(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_documents_response(self): + body = self.construct_full_body() + response = fake_response_DocumentList_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_documents_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_documents_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/documents' url = '{0}{1}'.format(base_url, endpoint) - expected = { - "models": [ - { - "status": "available", - "model_id": "en-es-conversational", - "domain": "conversational", - "target": "es", - "customizable": False, - "source": "en", - "base_model_id": "", - "owner": "", - "default_model": False, - "name": "en-es-conversational" - }, - { - "status": "available", - "model_id": "es-en", - "domain": "news", - "target": "en", - "customizable": True, - "source": "es", - "base_model_id": "", - "owner": "", - "default_model": True, - "name": "es-en" - } - ] - } - responses.add( - responses.GET, - url, - body=json.dumps(expected), - status=200, - content_type='application/json') - response = service.list_models().get_result() - assert len(responses.calls) == 2 - assert responses.calls[1].request.url.startswith(url) - assert response == expected - TranslationModels._from_dict(response) - - @classmethod - @responses.activate - def test_document_translation(cls): - document_status = { - 'status': 'processing', - 'model_id': 'en-es', - 'target': 'es', - 'created': '2019-06-05T20:59:37', - 'filename': 'hello_world.txt', - 'source': 'en', - 'document_id': '2a683723'} + 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 = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.list_documents(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for translate_document +#----------------------------------------------------------------------------- +class TestTranslateDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_translate_document_response(self): + body = self.construct_full_body() + response = fake_response_DocumentStatus_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_translate_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_translate_document_empty(self): + check_empty_required_params(self, fake_response_DocumentStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): endpoint = '/v3/documents' url = '{0}{1}'.format(base_url, endpoint) - responses.add( - responses.POST, - url, - body=json.dumps(document_status), - status=200, - content_type='application_json') - responses.add( - responses.DELETE, - url + '/2a683723', - status=200) - responses.add( - responses.GET, - url, - body=json.dumps({'documents': [document_status]}), - status=200, - content_type='application_json') - responses.add( - responses.GET, - url + '/2a683723/translated_document?version=2018-05-01', - body='binary response', - status=200) - responses.add( - responses.GET, - url + '/2a683723?version=2018-05-01', - body=json.dumps(document_status), - status=200, - content_type='application_json') - authenticator = BasicAuthenticator('xxx', 'yyy') - language_translator = ibm_watson.LanguageTranslatorV3('2018-05-01', authenticator=authenticator) - - with open(join(dirname(__file__), '../../resources/hello_world.txt'), 'r') as fileinfo: - translation = language_translator.translate_document( - file=fileinfo, - file_content_type='text/plain', - model_id='en-es').get_result() - assert translation == document_status - - status = language_translator.list_documents().get_result() - assert status['documents'][0]['document_id'] == '2a683723' - - delete_result = language_translator.delete_document('2a683723').get_result() - assert delete_result is None - - response = language_translator.get_translated_document('2a683723', accept='text/plain').get_result() - assert response.content is not None - - doc_status = language_translator.get_document_status('2a683723').get_result() - assert doc_status['document_id'] == '2a683723' - - assert len(responses.calls) == 5 + return url + + def add_mock_response(self, url, response): + responses.add(responses.POST, + url, + body=json.dumps(response), + status=202, + content_type='application/json') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.translate_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + body['filename'] = "string1" + body['file_content_type'] = "string1" + body['model_id'] = "string1" + body['source'] = "string1" + body['target'] = "string1" + body['document_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['file'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_document_status +#----------------------------------------------------------------------------- +class TestGetDocumentStatus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_document_status_response(self): + body = self.construct_full_body() + response = fake_response_DocumentStatus_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_document_status_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DocumentStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_document_status_empty(self): + check_empty_required_params(self, fake_response_DocumentStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/documents/{0}'.format(body['document_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 = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.get_document_status(**body) + return output + + def construct_full_body(self): + body = dict() + body['document_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['document_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_document +#----------------------------------------------------------------------------- +class TestDeleteDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_document_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_document_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_document_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 = '/v3/documents/{0}'.format(body['document_id']) + 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=204, + content_type='') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.delete_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['document_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['document_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_translated_document +#----------------------------------------------------------------------------- +class TestGetTranslatedDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_translated_document_response(self): + body = self.construct_full_body() + response = fake_response_BinaryIO_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_translated_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BinaryIO_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_translated_document_empty(self): + check_empty_required_params(self, fake_response_BinaryIO_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/documents/{0}/translated_document'.format(body['document_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='') + + def call_service(self, body): + service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.get_translated_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['document_id'] = "string1" + body['accept'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['document_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: DocumentTranslation +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_TranslationResult_json = """{"word_count": 10, "character_count": 15, "translations": []}""" +fake_response_IdentifiableLanguages_json = """{"languages": []}""" +fake_response_IdentifiedLanguages_json = """{"languages": []}""" +fake_response_TranslationModels_json = """{"models": []}""" +fake_response_TranslationModel_json = """{"model_id": "fake_model_id", "name": "fake_name", "source": "fake_source", "target": "fake_target", "base_model_id": "fake_base_model_id", "domain": "fake_domain", "customizable": true, "default_model": false, "owner": "fake_owner", "status": "fake_status"}""" +fake_response_DeleteModelResult_json = """{"status": "fake_status"}""" +fake_response_TranslationModel_json = """{"model_id": "fake_model_id", "name": "fake_name", "source": "fake_source", "target": "fake_target", "base_model_id": "fake_base_model_id", "domain": "fake_domain", "customizable": true, "default_model": false, "owner": "fake_owner", "status": "fake_status"}""" +fake_response_DocumentList_json = """{"documents": []}""" +fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "filename": "fake_filename", "status": "fake_status", "model_id": "fake_model_id", "base_model_id": "fake_base_model_id", "source": "fake_source", "target": "fake_target", "created": "2017-05-16T13:56:54.957Z", "completed": "2017-05-16T13:56:54.957Z", "word_count": 10, "character_count": 15}""" +fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "filename": "fake_filename", "status": "fake_status", "model_id": "fake_model_id", "base_model_id": "fake_base_model_id", "source": "fake_source", "target": "fake_target", "created": "2017-05-16T13:56:54.957Z", "completed": "2017-05-16T13:56:54.957Z", "word_count": 10, "character_count": 15}""" +fake_response_BinaryIO_json = """Contents of response byte-stream...""" From 22df14a53bef7182a8061179e0e5af230d697edc Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:32:03 -0500 Subject: [PATCH 177/455] refactor(nlc): regenerate natural language classifier with tests --- ibm_watson/natural_language_classifier_v1.py | 314 +++++--- .../test_natural_language_classifier_v1.py | 678 ++++++++++++++---- 2 files changed, 740 insertions(+), 252 deletions(-) diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 2f7a00d05..2b7ffd4a6 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,12 +21,20 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService 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 import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +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 +from typing import List +from typing import TextIO ############################################################################## # Service @@ -36,12 +44,14 @@ class NaturalLanguageClassifierV1(BaseService): """The Natural Language Classifier V1 service.""" - default_service_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/natural-language-classifier/api' + DEFAULT_SERVICE_NAME = 'natural_language_classifier' def __init__( self, - authenticator=None, - ): + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Natural Language Classifier service. @@ -49,30 +59,20 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('natural_language_classifier') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'natural_language_classifier') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) + self.configure_service(service_name) ######################### # Classify text ######################### - def classify(self, classifier_id, text, **kwargs): + def classify(self, classifier_id: str, text: str, + **kwargs) -> 'DetailedResponse': """ Classify a phrase. @@ -95,8 +95,9 @@ def classify(self, classifier_id, text, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'classify') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='classify') headers.update(sdk_headers) data = {'text': text} @@ -106,12 +107,14 @@ def classify(self, classifier_id, text, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def classify_collection(self, classifier_id, collection, **kwargs): + def classify_collection(self, classifier_id: str, + collection: List['ClassifyInput'], + **kwargs) -> 'DetailedResponse': """ Classify multiple phrases. @@ -120,7 +123,7 @@ def classify_collection(self, classifier_id, collection, **kwargs): Note that classifying Japanese texts is a beta feature. :param str classifier_id: Classifier ID to use. - :param list[ClassifyInput] collection: The submitted phrases. + :param List[ClassifyInput] collection: The submitted phrases. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -135,8 +138,9 @@ def classify_collection(self, classifier_id, collection, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'classify_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='classify_collection') headers.update(sdk_headers) data = {'collection': collection} @@ -146,8 +150,8 @@ def classify_collection(self, classifier_id, collection, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -155,21 +159,23 @@ def classify_collection(self, classifier_id, collection, **kwargs): # Manage classifiers ######################### - def create_classifier(self, training_metadata, training_data, **kwargs): + def create_classifier(self, training_metadata: BinaryIO, + training_data: BinaryIO, + **kwargs) -> 'DetailedResponse': """ Create classifier. Sends data to create and train a classifier and returns information about the new classifier. - :param file training_metadata: Metadata in JSON format. The metadata + :param TextIO training_metadata: Metadata in JSON format. The metadata identifies the language of the data, and an optional name to identify the classifier. Specify the language with the 2-letter primary language code as assigned in ISO standard 639. Supported languages are English (`en`), Arabic (`ar`), French (`fr`), German, (`de`), Italian (`it`), Japanese (`ja`), Korean (`ko`), Brazilian Portuguese (`pt`), and Spanish (`es`). - :param file training_data: Training data in CSV format. Each text value + :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). @@ -186,8 +192,9 @@ def create_classifier(self, training_metadata, training_data, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'create_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_classifier') headers.update(sdk_headers) form_data = [] @@ -199,12 +206,12 @@ def create_classifier(self, training_metadata, training_data, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def list_classifiers(self, **kwargs): + def list_classifiers(self, **kwargs) -> 'DetailedResponse': """ List classifiers. @@ -218,19 +225,19 @@ def list_classifiers(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'list_classifiers') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_classifiers') headers.update(sdk_headers) url = '/v1/classifiers' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def get_classifier(self, classifier_id, **kwargs): + def get_classifier(self, classifier_id: str, + **kwargs) -> 'DetailedResponse': """ Get information about a classifier. @@ -248,20 +255,20 @@ def get_classifier(self, classifier_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'get_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_classifier') headers.update(sdk_headers) url = '/v1/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_classifier(self, classifier_id, **kwargs): + def delete_classifier(self, classifier_id: str, + **kwargs) -> 'DetailedResponse': """ Delete classifier. @@ -277,16 +284,17 @@ def delete_classifier(self, classifier_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural_language_classifier', 'V1', - 'delete_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_classifier') headers.update(sdk_headers) url = '/v1/classifiers/{0}'.format( *self._encode_path_vars(classifier_id)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response @@ -304,17 +312,17 @@ class Classification(): :attr str url: (optional) Link to the classifier. :attr str text: (optional) The submitted phrase. :attr str top_class: (optional) The class with the highest confidence. - :attr list[ClassifiedClass] classes: (optional) An array of up to ten + :attr List[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ def __init__(self, *, - classifier_id=None, - url=None, - text=None, - top_class=None, - classes=None): + classifier_id: str = None, + url: str = None, + text: str = None, + top_class: str = None, + classes: List['ClassifiedClass'] = None) -> None: """ Initialize a Classification object. @@ -322,7 +330,7 @@ def __init__(self, :param str url: (optional) Link to the classifier. :param str text: (optional) The submitted phrase. :param str top_class: (optional) The class with the highest confidence. - :param list[ClassifiedClass] classes: (optional) An array of up to ten + :param List[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ self.classifier_id = classifier_id @@ -332,7 +340,7 @@ def __init__(self, self.classes = classes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Classification': """Initialize a Classification object from a json dictionary.""" args = {} valid_keys = ['classifier_id', 'url', 'text', 'top_class', 'classes'] @@ -355,7 +363,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Classification 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, 'classifier_id') and self.classifier_id is not None: @@ -370,17 +383,21 @@ def _to_dict(self): _dict['classes'] = [x._to_dict() for x in self.classes] return _dict - def __str__(self): + 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 Classification object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Classification') -> 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): + def __ne__(self, other: 'Classification') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -391,17 +408,21 @@ class ClassificationCollection(): :attr str classifier_id: (optional) Unique identifier for this classifier. :attr str url: (optional) Link to the classifier. - :attr list[CollectionItem] collection: (optional) An array of classifier + :attr List[CollectionItem] collection: (optional) An array of classifier responses for each submitted phrase. """ - def __init__(self, *, classifier_id=None, url=None, collection=None): + def __init__(self, + *, + classifier_id: str = None, + url: str = None, + collection: List['CollectionItem'] = None) -> None: """ Initialize a ClassificationCollection object. :param str classifier_id: (optional) Unique identifier for this classifier. :param str url: (optional) Link to the classifier. - :param list[CollectionItem] collection: (optional) An array of classifier + :param List[CollectionItem] collection: (optional) An array of classifier responses for each submitted phrase. """ self.classifier_id = classifier_id @@ -409,7 +430,7 @@ def __init__(self, *, classifier_id=None, url=None, collection=None): self.collection = collection @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassificationCollection': """Initialize a ClassificationCollection object from a json dictionary.""" args = {} valid_keys = ['classifier_id', 'url', 'collection'] @@ -428,7 +449,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassificationCollection 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, 'classifier_id') and self.classifier_id is not None: @@ -439,17 +465,21 @@ def _to_dict(self): _dict['collection'] = [x._to_dict() for x in self.collection] return _dict - def __str__(self): + 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 ClassificationCollection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassificationCollection') -> 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): + def __ne__(self, other: 'ClassificationCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -464,7 +494,8 @@ class ClassifiedClass(): :attr str class_name: (optional) Class label. """ - def __init__(self, *, confidence=None, class_name=None): + def __init__(self, *, confidence: float = None, + class_name: str = None) -> None: """ Initialize a ClassifiedClass object. @@ -477,7 +508,7 @@ def __init__(self, *, confidence=None, class_name=None): self.class_name = class_name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifiedClass': """Initialize a ClassifiedClass object from a json dictionary.""" args = {} valid_keys = ['confidence', 'class_name'] @@ -492,7 +523,12 @@ def _from_dict(cls, _dict): args['class_name'] = _dict.get('class_name') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifiedClass 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, 'confidence') and self.confidence is not None: @@ -501,17 +537,21 @@ def _to_dict(self): _dict['class_name'] = self.class_name return _dict - def __str__(self): + 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 ClassifiedClass object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifiedClass') -> 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): + def __ne__(self, other: 'ClassifiedClass') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -531,14 +571,14 @@ class Classifier(): """ def __init__(self, - url, - classifier_id, + url: str, + classifier_id: str, *, - name=None, - status=None, - created=None, - status_description=None, - language=None): + name: str = None, + status: str = None, + created: datetime = None, + status_description: str = None, + language: str = None) -> None: """ Initialize a Classifier object. @@ -561,7 +601,7 @@ def __init__(self, self.language = language @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Classifier': """Initialize a Classifier object from a json dictionary.""" args = {} valid_keys = [ @@ -596,7 +636,12 @@ def _from_dict(cls, _dict): args['language'] = _dict.get('language') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Classifier 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, 'name') and self.name is not None: @@ -617,17 +662,21 @@ def _to_dict(self): _dict['language'] = self.language return _dict - def __str__(self): + 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 Classifier object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Classifier') -> 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): + def __ne__(self, other: 'Classifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -646,21 +695,21 @@ class ClassifierList(): """ List of available classifiers. - :attr list[Classifier] classifiers: The classifiers available to the user. + :attr List[Classifier] classifiers: The classifiers available to the user. Returns an empty array if no classifiers are available. """ - def __init__(self, classifiers): + def __init__(self, classifiers: List['Classifier']) -> None: """ Initialize a ClassifierList object. - :param list[Classifier] classifiers: The classifiers available to the user. + :param List[Classifier] classifiers: The classifiers available to the user. Returns an empty array if no classifiers are available. """ self.classifiers = classifiers @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifierList': """Initialize a ClassifierList object from a json dictionary.""" args = {} valid_keys = ['classifiers'] @@ -679,24 +728,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifierList 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, 'classifiers') and self.classifiers is not None: _dict['classifiers'] = [x._to_dict() for x in self.classifiers] return _dict - def __str__(self): + 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 ClassifierList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifierList') -> 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): + def __ne__(self, other: 'ClassifierList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -708,7 +766,7 @@ class ClassifyInput(): :attr str text: The submitted phrase. The maximum length is 2048 characters. """ - def __init__(self, text): + def __init__(self, text: str) -> None: """ Initialize a ClassifyInput object. @@ -718,7 +776,7 @@ def __init__(self, text): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifyInput': """Initialize a ClassifyInput object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -734,24 +792,33 @@ def _from_dict(cls, _dict): 'Required property \'text\' not present in ClassifyInput JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifyInput 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, 'text') and self.text is not None: _dict['text'] = self.text return _dict - def __str__(self): + 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 ClassifyInput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifyInput') -> 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): + def __ne__(self, other: 'ClassifyInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -763,18 +830,22 @@ class CollectionItem(): :attr str text: (optional) The submitted phrase. The maximum length is 2048 characters. :attr str top_class: (optional) The class with the highest confidence. - :attr list[ClassifiedClass] classes: (optional) An array of up to ten + :attr List[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ - def __init__(self, *, text=None, top_class=None, classes=None): + def __init__(self, + *, + text: str = None, + top_class: str = None, + classes: List['ClassifiedClass'] = None) -> None: """ Initialize a CollectionItem object. :param str text: (optional) The submitted phrase. The maximum length is 2048 characters. :param str top_class: (optional) The class with the highest confidence. - :param list[ClassifiedClass] classes: (optional) An array of up to ten + :param List[ClassifiedClass] classes: (optional) An array of up to ten class-confidence pairs sorted in descending order of confidence. """ self.text = text @@ -782,7 +853,7 @@ def __init__(self, *, text=None, top_class=None, classes=None): self.classes = classes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionItem': """Initialize a CollectionItem object from a json dictionary.""" args = {} valid_keys = ['text', 'top_class', 'classes'] @@ -801,7 +872,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionItem 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, 'text') and self.text is not None: @@ -812,16 +888,20 @@ def _to_dict(self): _dict['classes'] = [x._to_dict() for x in self.classes] return _dict - def __str__(self): + 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 CollectionItem object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionItem') -> 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): + def __ne__(self, other: 'CollectionItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index 5e923b18d..d02f9bbc8 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -1,136 +1,544 @@ -# coding: utf-8 -import os +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect +import json +import pytest import responses -import ibm_watson -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - - -@responses.activate -def test_success(): - authenticator = BasicAuthenticator('username', 'password') - natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1(authenticator=authenticator) - - list_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers' - list_response = '{"classifiers": [{"url": "https://gateway.watsonplatform.net/natural-language-classifier-' \ - 'experimental/api/v1/classifiers/497EF2-nlc-00", "classifier_id": "497EF2-nlc-00"}]}' - responses.add(responses.GET, list_url, - body=list_response, status=200, - content_type='application/json') - - natural_language_classifier.list_classifiers() - - assert responses.calls[0].request.url == list_url - assert responses.calls[0].response.text == list_response - - status_url = ('https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/' - '497EF2-nlc-00') - status_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/' \ - 'classifiers/497EF2-nlc-00", "status": "Available", "status_description": "The classifier ' \ - 'instance is now available and is ready to take classifier requests.", "classifier_id": ' \ - '"497EF2-nlc-00"}' - - responses.add(responses.GET, status_url, - body=status_response, status=200, - content_type='application/json') - - natural_language_classifier.get_classifier('497EF2-nlc-00') - - assert responses.calls[1].request.url == status_url - assert responses.calls[1].response.text == status_response - - classify_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/' \ - '497EF2-nlc-00/classify' - classify_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/' \ - 'v1", "text": "test", "classes": [{"class_name": "conditions", "confidence": ' \ - '0.6575315710901418}, {"class_name": "temperature", "confidence": 0.3424684289098582}], ' \ - '"classifier_id": "497EF2-nlc-00", "top_class": "conditions"}' - - responses.add(responses.POST, classify_url, - body=classify_response, status=200, - content_type='application/json') - - natural_language_classifier.classify('497EF2-nlc-00', 'test') - - assert responses.calls[2].request.url == classify_url - assert responses.calls[2].response.text == classify_response - - create_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers' - create_response = '{"url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/' \ - 'classifiers/497EF2-nlc-00", "status": "Available", "status_description": "The classifier ' \ - 'instance is now available and is ready to take classifier requests.", "classifier_id": ' \ - '"497EF2-nlc-00"}' - - responses.add(responses.POST, create_url, - body=create_response, status=200, - content_type='application/json') - with open(os.path.join(os.path.dirname(__file__), '../../resources/weather_data_train.csv'), 'rb') as training_data: - natural_language_classifier.create_classifier( - training_metadata='{"language": "en"}', - training_data=training_data) - - assert responses.calls[3].request.url == create_url - assert responses.calls[3].response.text == create_response - - remove_url = status_url - remove_response = '{}' - - responses.add(responses.DELETE, remove_url, - body=remove_response, status=200, - content_type='application/json') - - natural_language_classifier.delete_classifier('497EF2-nlc-00') - - assert responses.calls[4].request.url == remove_url - assert responses.calls[4].response.text == remove_response - - assert len(responses.calls) == 5 - -@responses.activate -def test_classify_collection(): - authenticator = BasicAuthenticator('username', 'password') - natural_language_classifier = ibm_watson.NaturalLanguageClassifierV1(authenticator=authenticator) - classify_collection_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/497EF2-nlc-00/classify_collection' - classify_collection_response = '{ \ - "classifier_id": "497EF2-nlc-00", \ - "url": "https://gateway.watsonplatform.net/natural-language-classifier/api/v1/classifiers/10D41B-nlc-1", \ - "collection": [ \ - { \ - "text": "How hot will it be today?", \ - "top_class": "temperature", \ - "classes": [ \ - { \ - "class_name": "temperature", \ - "confidence": 0.9930558798985937 \ - }, \ - { \ - "class_name": "conditions", \ - "confidence": 0.006944120101406304 \ - } \ - ] \ - }, \ - { \ - "text": "Is it hot outside?", \ - "top_class": "temperature", \ - "classes": [ \ - { \ - "class_name": "temperature", \ - "confidence": 1 \ - }, \ - { \ - "class_name": "conditions", \ - "confidence": 0 \ - } \ - ] \ - } \ - ] \ - }' - responses.add(responses.POST, classify_collection_url, - body=classify_collection_response, status=200, - content_type='application/json') - - classifier_id = '497EF2-nlc-00' - collection = ['{"text":"How hot will it be today?"}', '{"text":"Is it hot outside?"}'] - natural_language_classifier.classify_collection(classifier_id, collection) - - assert responses.calls[0].request.url == classify_collection_url - assert responses.calls[0].response.text == classify_collection_response +import tempfile +import ibm_watson.natural_language_classifier_v1 +from ibm_watson.natural_language_classifier_v1 import * + +base_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api' + +############################################################################## +# Start of Service: ClassifyText +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for classify +#----------------------------------------------------------------------------- +class TestClassify(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_response(self): + body = self.construct_full_body() + response = fake_response_Classification_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_classify_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classification_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_empty(self): + check_empty_required_params(self, fake_response_Classification_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/classifiers/{0}/classify'.format(body['classifier_id']) + 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 = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.classify(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + body.update({ + "text": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + body.update({ + "text": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for classify_collection +#----------------------------------------------------------------------------- +class TestClassifyCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_collection_response(self): + body = self.construct_full_body() + response = fake_response_ClassificationCollection_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_classify_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ClassificationCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_collection_empty(self): + check_empty_required_params( + self, fake_response_ClassificationCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/classifiers/{0}/classify_collection'.format( + body['classifier_id']) + 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 = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.classify_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + body.update({ + "collection": [], + }) + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + body.update({ + "collection": [], + }) + return body + + +# endregion +############################################################################## +# End of Service: ClassifyText +############################################################################## + +############################################################################## +# Start of Service: ManageClassifiers +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for create_classifier +#----------------------------------------------------------------------------- +class TestCreateClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_classifier_response(self): + body = self.construct_full_body() + response = fake_response_Classifier_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_create_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_classifier_empty(self): + check_empty_required_params(self, fake_response_Classifier_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/classifiers' + 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 = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.create_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['training_metadata'] = tempfile.NamedTemporaryFile() + body['training_data'] = tempfile.NamedTemporaryFile() + return body + + def construct_required_body(self): + body = dict() + body['training_metadata'] = tempfile.NamedTemporaryFile() + body['training_data'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_classifiers +#----------------------------------------------------------------------------- +class TestListClassifiers(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_classifiers_response(self): + body = self.construct_full_body() + response = fake_response_ClassifierList_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_classifiers_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ClassifierList_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_classifiers_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/classifiers' + 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 = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_classifiers(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_classifier +#----------------------------------------------------------------------------- +class TestGetClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_classifier_response(self): + body = self.construct_full_body() + response = fake_response_Classifier_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_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_classifier_empty(self): + check_empty_required_params(self, fake_response_Classifier_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/classifiers/{0}'.format(body['classifier_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 = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_classifier +#----------------------------------------------------------------------------- +class TestDeleteClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_classifier_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_classifier_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_classifier_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 = '/v1/classifiers/{0}'.format(body['classifier_id']) + 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 = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: ManageClassifiers +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_Classification_json = """{"classifier_id": "fake_classifier_id", "url": "fake_url", "text": "fake_text", "top_class": "fake_top_class", "classes": []}""" +fake_response_ClassificationCollection_json = """{"classifier_id": "fake_classifier_id", "url": "fake_url", "collection": []}""" +fake_response_Classifier_json = """{"name": "fake_name", "url": "fake_url", "status": "fake_status", "classifier_id": "fake_classifier_id", "created": "2017-05-16T13:56:54.957Z", "status_description": "fake_status_description", "language": "fake_language"}""" +fake_response_ClassifierList_json = """{"classifiers": []}""" +fake_response_Classifier_json = """{"name": "fake_name", "url": "fake_url", "status": "fake_status", "classifier_id": "fake_classifier_id", "created": "2017-05-16T13:56:54.957Z", "status_description": "fake_status_description", "language": "fake_language"}""" From 55b0edf2937367d249c86e04415f9278b2f77d66 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:33:28 -0500 Subject: [PATCH 178/455] refactor(nlu): regenerate natural lang understanding with tests --- .../natural_language_understanding_v1.py | 1432 +++++++++++------ .../test_natural_language_understanding_v1.py | 376 +++++ 2 files changed, 1343 insertions(+), 465 deletions(-) create mode 100644 test/unit/test_natural_language_understanding_v1.py diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 89c5dc027..8fb571cee 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -20,17 +20,23 @@ ignore most advertisements and other unwanted content. You can create [custom models](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) -with Watson Knowledge Studio to detect custom entities, relations, and categories in -Natural Language Understanding. +with Watson Knowledge Studio to detect custom entities and relations in Natural Language +Understanding. """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService 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 import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from os.path import basename +from typing import Dict +from typing import List ############################################################################## # Service @@ -40,13 +46,15 @@ class NaturalLanguageUnderstandingV1(BaseService): """The Natural Language Understanding V1 service.""" - default_service_url = 'https://gateway.watsonplatform.net/natural-language-understanding/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/natural-language-understanding/api' + DEFAULT_SERVICE_NAME = 'natural-language-understanding' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Natural Language Understanding service. @@ -65,43 +73,32 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('natural_language_understanding') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'natural_language_understanding') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Analyze ######################### def analyze(self, - features, + features: 'Features', *, - text=None, - html=None, - url=None, - clean=None, - xpath=None, - fallback_to_raw=None, - return_analyzed_text=None, - language=None, - limit_text_characters=None, - **kwargs): + text: str = None, + html: str = None, + url: str = None, + clean: bool = None, + xpath: str = None, + fallback_to_raw: bool = None, + return_analyzed_text: bool = None, + language: str = None, + limit_text_characters: int = None, + **kwargs) -> 'DetailedResponse': """ Analyze text. @@ -116,6 +113,9 @@ def analyze(self, - Semantic roles - Sentiment - Syntax (Experimental). + If a language for the input text is not specified with the `language` parameter, + the service [automatically detects the + language](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-detectable-languages). :param Features features: Specific features to analyze the document for. :param str text: (optional) The plain text to analyze. One of the `text`, @@ -157,8 +157,9 @@ def analyze(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural-language-understanding', 'V1', - 'analyze') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='analyze') headers.update(sdk_headers) params = {'version': self.version} @@ -181,8 +182,8 @@ def analyze(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -190,7 +191,7 @@ def analyze(self, # Manage models ######################### - def list_models(self, **kwargs): + def list_models(self, **kwargs) -> 'DetailedResponse': """ List models. @@ -206,8 +207,9 @@ def list_models(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural-language-understanding', 'V1', - 'list_models') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_models') headers.update(sdk_headers) params = {'version': self.version} @@ -216,12 +218,12 @@ def list_models(self, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_model(self, model_id, **kwargs): + def delete_model(self, model_id: str, **kwargs) -> 'DetailedResponse': """ Delete model. @@ -239,8 +241,9 @@ def delete_model(self, model_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('natural-language-understanding', 'V1', - 'delete_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_model') headers.update(sdk_headers) params = {'version': self.version} @@ -249,8 +252,8 @@ def delete_model(self, model_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -269,21 +272,21 @@ class AnalysisResults(): :attr str retrieved_url: (optional) URL of the webpage that was analyzed. :attr AnalysisResultsUsage usage: (optional) API usage information for the request. - :attr list[ConceptsResult] concepts: (optional) The general concepts referenced + :attr List[ConceptsResult] concepts: (optional) The general concepts referenced or alluded to in the analyzed text. - :attr list[EntitiesResult] entities: (optional) The entities detected in the + :attr List[EntitiesResult] entities: (optional) The entities detected in the analyzed text. - :attr list[KeywordsResult] keywords: (optional) The keywords from the analyzed + :attr List[KeywordsResult] keywords: (optional) The keywords from the analyzed text. - :attr list[CategoriesResult] categories: (optional) The categories that the + :attr List[CategoriesResult] categories: (optional) The categories that the service assigned to the analyzed text. :attr EmotionResult emotion: (optional) The anger, disgust, fear, joy, or sadness conveyed by the content. :attr AnalysisResultsMetadata metadata: (optional) Webpage metadata, such as the author and the title of the page. - :attr list[RelationsResult] relations: (optional) The relationships between + :attr List[RelationsResult] relations: (optional) The relationships between entities in the content. - :attr list[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into + :attr List[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into `subject`, `action`, and `object` form. :attr SentimentResult sentiment: (optional) The sentiment of the content. :attr SyntaxResult syntax: (optional) Tokens and sentences returned from syntax @@ -292,20 +295,20 @@ class AnalysisResults(): def __init__(self, *, - language=None, - analyzed_text=None, - retrieved_url=None, - usage=None, - concepts=None, - entities=None, - keywords=None, - categories=None, - emotion=None, - metadata=None, - relations=None, - semantic_roles=None, - sentiment=None, - syntax=None): + language: str = None, + analyzed_text: str = None, + retrieved_url: str = None, + usage: 'AnalysisResultsUsage' = None, + concepts: List['ConceptsResult'] = None, + entities: List['EntitiesResult'] = None, + keywords: List['KeywordsResult'] = None, + categories: List['CategoriesResult'] = None, + emotion: 'EmotionResult' = None, + metadata: 'AnalysisResultsMetadata' = None, + relations: List['RelationsResult'] = None, + semantic_roles: List['SemanticRolesResult'] = None, + sentiment: 'SentimentResult' = None, + syntax: 'SyntaxResult' = None) -> None: """ Initialize a AnalysisResults object. @@ -314,21 +317,21 @@ def __init__(self, :param str retrieved_url: (optional) URL of the webpage that was analyzed. :param AnalysisResultsUsage usage: (optional) API usage information for the request. - :param list[ConceptsResult] concepts: (optional) The general concepts + :param List[ConceptsResult] concepts: (optional) The general concepts referenced or alluded to in the analyzed text. - :param list[EntitiesResult] entities: (optional) The entities detected in + :param List[EntitiesResult] entities: (optional) The entities detected in the analyzed text. - :param list[KeywordsResult] keywords: (optional) The keywords from the + :param List[KeywordsResult] keywords: (optional) The keywords from the analyzed text. - :param list[CategoriesResult] categories: (optional) The categories that + :param List[CategoriesResult] categories: (optional) The categories that the service assigned to the analyzed text. :param EmotionResult emotion: (optional) The anger, disgust, fear, joy, or sadness conveyed by the content. :param AnalysisResultsMetadata metadata: (optional) Webpage metadata, such as the author and the title of the page. - :param list[RelationsResult] relations: (optional) The relationships + :param List[RelationsResult] relations: (optional) The relationships between entities in the content. - :param list[SemanticRolesResult] semantic_roles: (optional) Sentences + :param List[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into `subject`, `action`, and `object` form. :param SentimentResult sentiment: (optional) The sentiment of the content. :param SyntaxResult syntax: (optional) Tokens and sentences returned from @@ -350,7 +353,7 @@ def __init__(self, self.syntax = syntax @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AnalysisResults': """Initialize a AnalysisResults object from a json dictionary.""" args = {} valid_keys = [ @@ -409,7 +412,12 @@ def _from_dict(cls, _dict): args['syntax'] = SyntaxResult._from_dict(_dict.get('syntax')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalysisResults 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, 'language') and self.language is not None: @@ -444,17 +452,21 @@ def _to_dict(self): _dict['syntax'] = self.syntax._to_dict() return _dict - def __str__(self): + 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 AnalysisResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AnalysisResults') -> 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): + def __ne__(self, other: 'AnalysisResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -463,30 +475,30 @@ class AnalysisResultsMetadata(): """ Webpage metadata, such as the author and the title of the page. - :attr list[Author] authors: (optional) The authors of the document. + :attr List[Author] authors: (optional) The authors of the document. :attr str publication_date: (optional) The publication date in the format ISO 8601. :attr str title: (optional) The title of the document. :attr str image: (optional) URL of a prominent image on the webpage. - :attr list[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. + :attr List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. """ def __init__(self, *, - authors=None, - publication_date=None, - title=None, - image=None, - feeds=None): + authors: List['Author'] = None, + publication_date: str = None, + title: str = None, + image: str = None, + feeds: List['Feed'] = None) -> None: """ Initialize a AnalysisResultsMetadata object. - :param list[Author] authors: (optional) The authors of the document. + :param List[Author] authors: (optional) The authors of the document. :param str publication_date: (optional) The publication date in the format ISO 8601. :param str title: (optional) The title of the document. :param str image: (optional) URL of a prominent image on the webpage. - :param list[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. + :param List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. """ self.authors = authors self.publication_date = publication_date @@ -495,7 +507,7 @@ def __init__(self, self.feeds = feeds @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AnalysisResultsMetadata': """Initialize a AnalysisResultsMetadata object from a json dictionary.""" args = {} valid_keys = ['authors', 'publication_date', 'title', 'image', 'feeds'] @@ -518,7 +530,12 @@ def _from_dict(cls, _dict): args['feeds'] = [Feed._from_dict(x) for x in (_dict.get('feeds'))] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalysisResultsMetadata 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, 'authors') and self.authors is not None: @@ -534,17 +551,21 @@ def _to_dict(self): _dict['feeds'] = [x._to_dict() for x in self.feeds] return _dict - def __str__(self): + 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 AnalysisResultsMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AnalysisResultsMetadata') -> 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): + def __ne__(self, other: 'AnalysisResultsMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -558,7 +579,11 @@ class AnalysisResultsUsage(): :attr int text_units: (optional) Number of 10,000-character units processed. """ - def __init__(self, *, features=None, text_characters=None, text_units=None): + def __init__(self, + *, + features: int = None, + text_characters: int = None, + text_units: int = None) -> None: """ Initialize a AnalysisResultsUsage object. @@ -572,7 +597,7 @@ def __init__(self, *, features=None, text_characters=None, text_units=None): self.text_units = text_units @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AnalysisResultsUsage': """Initialize a AnalysisResultsUsage object from a json dictionary.""" args = {} valid_keys = ['features', 'text_characters', 'text_units'] @@ -589,7 +614,12 @@ def _from_dict(cls, _dict): args['text_units'] = _dict.get('text_units') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalysisResultsUsage 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, 'features') and self.features is not None: @@ -601,17 +631,21 @@ def _to_dict(self): _dict['text_units'] = self.text_units return _dict - def __str__(self): + 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 AnalysisResultsUsage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AnalysisResultsUsage') -> 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): + def __ne__(self, other: 'AnalysisResultsUsage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -623,7 +657,7 @@ class Author(): :attr str name: (optional) Name of the author. """ - def __init__(self, *, name=None): + def __init__(self, *, name: str = None) -> None: """ Initialize a Author object. @@ -632,7 +666,7 @@ def __init__(self, *, name=None): self.name = name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Author': """Initialize a Author object from a json dictionary.""" args = {} valid_keys = ['name'] @@ -645,24 +679,33 @@ def _from_dict(cls, _dict): args['name'] = _dict.get('name') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Author 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, 'name') and self.name is not None: _dict['name'] = self.name return _dict - def __str__(self): + 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 Author object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Author') -> 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): + def __ne__(self, other: 'Author') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -676,12 +719,9 @@ 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) 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. """ - def __init__(self, *, explanation=None, limit=None, model=None): + def __init__(self, *, explanation: bool = None, limit: int = None) -> None: """ Initialize a CategoriesOptions object. @@ -689,19 +729,15 @@ def __init__(self, *, explanation=None, limit=None, model=None): explanations for each categorization. **This is available only for English categories.**. :param int limit: (optional) Maximum number of categories to return. - :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. """ self.explanation = explanation self.limit = limit - self.model = model @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CategoriesOptions': """Initialize a CategoriesOptions object from a json dictionary.""" args = {} - valid_keys = ['explanation', 'limit', 'model'] + valid_keys = ['explanation', 'limit'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -711,32 +747,37 @@ def _from_dict(cls, _dict): 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) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoriesOptions 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, 'explanation') and self.explanation is not None: _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 __str__(self): + 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 CategoriesOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CategoriesOptions') -> 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): + def __ne__(self, other: 'CategoriesOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -749,7 +790,7 @@ class CategoriesRelevantText(): categorization. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a CategoriesRelevantText object. @@ -759,7 +800,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CategoriesRelevantText': """Initialize a CategoriesRelevantText object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -772,24 +813,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoriesRelevantText 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, 'text') and self.text is not None: _dict['text'] = self.text return _dict - def __str__(self): + 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 CategoriesRelevantText object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CategoriesRelevantText') -> 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): + def __ne__(self, other: 'CategoriesRelevantText') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -808,7 +858,11 @@ class CategoriesResult(): to explain what contributed to the categories result. """ - def __init__(self, *, label=None, score=None, explanation=None): + def __init__(self, + *, + label: str = None, + score: float = None, + explanation: 'CategoriesResultExplanation' = None) -> None: """ Initialize a CategoriesResult object. @@ -827,7 +881,7 @@ def __init__(self, *, label=None, score=None, explanation=None): self.explanation = explanation @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CategoriesResult': """Initialize a CategoriesResult object from a json dictionary.""" args = {} valid_keys = ['label', 'score', 'explanation'] @@ -845,7 +899,12 @@ def _from_dict(cls, _dict): _dict.get('explanation')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoriesResult 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, 'label') and self.label is not None: @@ -856,17 +915,21 @@ def _to_dict(self): _dict['explanation'] = self.explanation._to_dict() return _dict - def __str__(self): + 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 CategoriesResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CategoriesResult') -> 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): + def __ne__(self, other: 'CategoriesResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -875,17 +938,18 @@ class CategoriesResultExplanation(): """ Information that helps to explain what contributed to the categories result. - :attr list[CategoriesRelevantText] relevant_text: (optional) An array of + :attr List[CategoriesRelevantText] relevant_text: (optional) An array of relevant text from the source that contributed to the categorization. The sorted array begins with the phrase that contributed most significantly to the result, followed by phrases that were less and less impactful. """ - def __init__(self, *, relevant_text=None): + def __init__(self, *, + relevant_text: List['CategoriesRelevantText'] = None) -> None: """ Initialize a CategoriesResultExplanation object. - :param list[CategoriesRelevantText] relevant_text: (optional) An array of + :param List[CategoriesRelevantText] relevant_text: (optional) An array of relevant text from the source that contributed to the categorization. The sorted array begins with the phrase that contributed most significantly to the result, followed by phrases that were less and less impactful. @@ -893,7 +957,7 @@ def __init__(self, *, relevant_text=None): self.relevant_text = relevant_text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CategoriesResultExplanation': """Initialize a CategoriesResultExplanation object from a json dictionary.""" args = {} valid_keys = ['relevant_text'] @@ -909,24 +973,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoriesResultExplanation 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, 'relevant_text') and self.relevant_text is not None: _dict['relevant_text'] = [x._to_dict() for x in self.relevant_text] return _dict - def __str__(self): + 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 CategoriesResultExplanation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CategoriesResultExplanation') -> 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): + def __ne__(self, other: 'CategoriesResultExplanation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -942,7 +1015,7 @@ class ConceptsOptions(): :attr int limit: (optional) Maximum number of concepts to return. """ - def __init__(self, *, limit=None): + def __init__(self, *, limit: int = None) -> None: """ Initialize a ConceptsOptions object. @@ -951,7 +1024,7 @@ def __init__(self, *, limit=None): self.limit = limit @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ConceptsOptions': """Initialize a ConceptsOptions object from a json dictionary.""" args = {} valid_keys = ['limit'] @@ -964,24 +1037,33 @@ def _from_dict(cls, _dict): args['limit'] = _dict.get('limit') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ConceptsOptions 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, 'limit') and self.limit is not None: _dict['limit'] = self.limit return _dict - def __str__(self): + 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 ConceptsOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ConceptsOptions') -> 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): + def __ne__(self, other: 'ConceptsOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -997,7 +1079,11 @@ class ConceptsResult(): resource. """ - def __init__(self, *, text=None, relevance=None, dbpedia_resource=None): + def __init__(self, + *, + text: str = None, + relevance: float = None, + dbpedia_resource: str = None) -> None: """ Initialize a ConceptsResult object. @@ -1012,7 +1098,7 @@ def __init__(self, *, text=None, relevance=None, dbpedia_resource=None): self.dbpedia_resource = dbpedia_resource @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ConceptsResult': """Initialize a ConceptsResult object from a json dictionary.""" args = {} valid_keys = ['text', 'relevance', 'dbpedia_resource'] @@ -1029,7 +1115,12 @@ def _from_dict(cls, _dict): args['dbpedia_resource'] = _dict.get('dbpedia_resource') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ConceptsResult 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, 'text') and self.text is not None: @@ -1041,17 +1132,21 @@ def _to_dict(self): _dict['dbpedia_resource'] = self.dbpedia_resource return _dict - def __str__(self): + 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 ConceptsResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ConceptsResult') -> 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): + def __ne__(self, other: 'ConceptsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1063,7 +1158,7 @@ class DeleteModelResults(): :attr str deleted: (optional) model_id of the deleted model. """ - def __init__(self, *, deleted=None): + def __init__(self, *, deleted: str = None) -> None: """ Initialize a DeleteModelResults object. @@ -1072,7 +1167,7 @@ def __init__(self, *, deleted=None): self.deleted = deleted @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DeleteModelResults': """Initialize a DeleteModelResults object from a json dictionary.""" args = {} valid_keys = ['deleted'] @@ -1085,24 +1180,33 @@ def _from_dict(cls, _dict): args['deleted'] = _dict.get('deleted') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteModelResults 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, 'deleted') and self.deleted is not None: _dict['deleted'] = self.deleted return _dict - def __str__(self): + 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 DeleteModelResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DeleteModelResults') -> 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): + def __ne__(self, other: 'DeleteModelResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1114,24 +1218,28 @@ class DisambiguationResult(): :attr str name: (optional) Common entity name. :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. - :attr list[str] subtype: (optional) Entity subtype information. + :attr List[str] subtype: (optional) Entity subtype information. """ - def __init__(self, *, name=None, dbpedia_resource=None, subtype=None): + def __init__(self, + *, + name: str = None, + dbpedia_resource: str = None, + subtype: List[str] = None) -> None: """ Initialize a DisambiguationResult object. :param str name: (optional) Common entity name. :param str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. - :param list[str] subtype: (optional) Entity subtype information. + :param List[str] subtype: (optional) Entity subtype information. """ self.name = name self.dbpedia_resource = dbpedia_resource self.subtype = subtype @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DisambiguationResult': """Initialize a DisambiguationResult object from a json dictionary.""" args = {} valid_keys = ['name', 'dbpedia_resource', 'subtype'] @@ -1148,7 +1256,12 @@ def _from_dict(cls, _dict): args['subtype'] = _dict.get('subtype') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DisambiguationResult 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, 'name') and self.name is not None: @@ -1160,17 +1273,21 @@ def _to_dict(self): _dict['subtype'] = self.subtype return _dict - def __str__(self): + 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 DisambiguationResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DisambiguationResult') -> 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): + def __ne__(self, other: 'DisambiguationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1183,7 +1300,7 @@ class DocumentEmotionResults(): whole. """ - def __init__(self, *, emotion=None): + def __init__(self, *, emotion: 'EmotionScores' = None) -> None: """ Initialize a DocumentEmotionResults object. @@ -1193,7 +1310,7 @@ def __init__(self, *, emotion=None): self.emotion = emotion @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentEmotionResults': """Initialize a DocumentEmotionResults object from a json dictionary.""" args = {} valid_keys = ['emotion'] @@ -1206,24 +1323,33 @@ def _from_dict(cls, _dict): args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentEmotionResults 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, 'emotion') and self.emotion is not None: _dict['emotion'] = self.emotion._to_dict() return _dict - def __str__(self): + 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 DocumentEmotionResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentEmotionResults') -> 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): + def __ne__(self, other: 'DocumentEmotionResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1238,7 +1364,7 @@ class DocumentSentimentResults(): (positive). """ - def __init__(self, *, label=None, score=None): + def __init__(self, *, label: str = None, score: float = None) -> None: """ Initialize a DocumentSentimentResults object. @@ -1251,7 +1377,7 @@ def __init__(self, *, label=None, score=None): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentSentimentResults': """Initialize a DocumentSentimentResults object from a json dictionary.""" args = {} valid_keys = ['label', 'score'] @@ -1266,7 +1392,12 @@ def _from_dict(cls, _dict): args['score'] = _dict.get('score') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentSentimentResults 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, 'label') and self.label is not None: @@ -1275,17 +1406,21 @@ def _to_dict(self): _dict['score'] = self.score return _dict - def __str__(self): + 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 DocumentSentimentResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentSentimentResults') -> 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): + def __ne__(self, other: 'DocumentSentimentResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1300,24 +1435,25 @@ class EmotionOptions(): :attr bool document: (optional) Set this to `false` to hide document-level emotion results. - :attr list[str] targets: (optional) Emotion results will be returned for each + :attr List[str] targets: (optional) Emotion results will be returned for each target string that is found in the document. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, *, document: bool = None, + targets: List[str] = None) -> None: """ Initialize a EmotionOptions object. :param bool document: (optional) Set this to `false` to hide document-level emotion results. - :param list[str] targets: (optional) Emotion results will be returned for + :param List[str] targets: (optional) Emotion results will be returned for each target string that is found in the document. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EmotionOptions': """Initialize a EmotionOptions object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -1332,7 +1468,12 @@ def _from_dict(cls, _dict): args['targets'] = _dict.get('targets') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EmotionOptions 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, 'document') and self.document is not None: @@ -1341,17 +1482,21 @@ def _to_dict(self): _dict['targets'] = self.targets return _dict - def __str__(self): + 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 EmotionOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EmotionOptions') -> 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): + def __ne__(self, other: 'EmotionOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1364,24 +1509,27 @@ class EmotionResult(): :attr DocumentEmotionResults document: (optional) Emotion results for the document as a whole. - :attr list[TargetedEmotionResults] targets: (optional) Emotion results for + :attr List[TargetedEmotionResults] targets: (optional) Emotion results for specified targets. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, + *, + document: 'DocumentEmotionResults' = None, + targets: List['TargetedEmotionResults'] = None) -> None: """ Initialize a EmotionResult object. :param DocumentEmotionResults document: (optional) Emotion results for the document as a whole. - :param list[TargetedEmotionResults] targets: (optional) Emotion results for + :param List[TargetedEmotionResults] targets: (optional) Emotion results for specified targets. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EmotionResult': """Initialize a EmotionResult object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -1400,7 +1548,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EmotionResult 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, 'document') and self.document is not None: @@ -1409,17 +1562,21 @@ def _to_dict(self): _dict['targets'] = [x._to_dict() for x in self.targets] return _dict - def __str__(self): + 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 EmotionResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EmotionResult') -> 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): + def __ne__(self, other: 'EmotionResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1442,11 +1599,11 @@ class EmotionScores(): def __init__(self, *, - anger=None, - disgust=None, - fear=None, - joy=None, - sadness=None): + anger: float = None, + disgust: float = None, + fear: float = None, + joy: float = None, + sadness: float = None) -> None: """ Initialize a EmotionScores object. @@ -1468,7 +1625,7 @@ def __init__(self, self.sadness = sadness @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EmotionScores': """Initialize a EmotionScores object from a json dictionary.""" args = {} valid_keys = ['anger', 'disgust', 'fear', 'joy', 'sadness'] @@ -1489,7 +1646,12 @@ def _from_dict(cls, _dict): args['sadness'] = _dict.get('sadness') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EmotionScores 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, 'anger') and self.anger is not None: @@ -1504,17 +1666,21 @@ def _to_dict(self): _dict['sadness'] = self.sadness return _dict - def __str__(self): + 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 EmotionScores object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EmotionScores') -> 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): + def __ne__(self, other: 'EmotionScores') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1542,11 +1708,11 @@ class EntitiesOptions(): def __init__(self, *, - limit=None, - mentions=None, - model=None, - sentiment=None, - emotion=None): + limit: int = None, + mentions: bool = None, + model: str = None, + sentiment: bool = None, + emotion: bool = None) -> None: """ Initialize a EntitiesOptions object. @@ -1568,7 +1734,7 @@ def __init__(self, self.emotion = emotion @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntitiesOptions': """Initialize a EntitiesOptions object from a json dictionary.""" args = {} valid_keys = ['limit', 'mentions', 'model', 'sentiment', 'emotion'] @@ -1589,7 +1755,12 @@ def _from_dict(cls, _dict): args['emotion'] = _dict.get('emotion') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntitiesOptions 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, 'limit') and self.limit is not None: @@ -1604,17 +1775,21 @@ def _to_dict(self): _dict['emotion'] = self.emotion return _dict - def __str__(self): + 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 EntitiesOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntitiesOptions') -> 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): + def __ne__(self, other: 'EntitiesOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1632,7 +1807,7 @@ class EntitiesResult(): 0 to 1. Higher values indicate higher confidence. In standard entities requests, confidence is returned only for English text. All entities requests that use custom models return the confidence score. - :attr list[EntityMention] mentions: (optional) Entity mentions and locations. + :attr List[EntityMention] mentions: (optional) Entity mentions and locations. :attr int count: (optional) How many times the entity was mentioned in the text. :attr EmotionScores emotion: (optional) Emotion analysis results for the entity, enabled with the `emotion` option. @@ -1644,15 +1819,15 @@ class EntitiesResult(): def __init__(self, *, - type=None, - text=None, - relevance=None, - confidence=None, - mentions=None, - count=None, - emotion=None, - sentiment=None, - disambiguation=None): + type: str = None, + text: str = None, + relevance: float = None, + confidence: float = None, + mentions: List['EntityMention'] = None, + count: int = None, + emotion: 'EmotionScores' = None, + sentiment: 'FeatureSentimentResults' = None, + disambiguation: 'DisambiguationResult' = None) -> None: """ Initialize a EntitiesResult object. @@ -1664,7 +1839,7 @@ def __init__(self, from 0 to 1. Higher values indicate higher confidence. In standard entities requests, confidence is returned only for English text. All entities requests that use custom models return the confidence score. - :param list[EntityMention] mentions: (optional) Entity mentions and + :param List[EntityMention] mentions: (optional) Entity mentions and locations. :param int count: (optional) How many times the entity was mentioned in the text. @@ -1686,7 +1861,7 @@ def __init__(self, self.disambiguation = disambiguation @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntitiesResult': """Initialize a EntitiesResult object from a json dictionary.""" args = {} valid_keys = [ @@ -1722,7 +1897,12 @@ def _from_dict(cls, _dict): _dict.get('disambiguation')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntitiesResult 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: @@ -1745,17 +1925,21 @@ def _to_dict(self): _dict['disambiguation'] = self.disambiguation._to_dict() return _dict - def __str__(self): + 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 EntitiesResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntitiesResult') -> 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): + def __ne__(self, other: 'EntitiesResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1765,7 +1949,7 @@ class EntityMention(): EntityMention. :attr str text: (optional) Entity mention text. - :attr list[int] location: (optional) Character offsets indicating the beginning + :attr List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. :attr float confidence: (optional) Confidence in the entity identification from 0 to 1. Higher values indicate higher confidence. In standard entities requests, @@ -1773,12 +1957,16 @@ class EntityMention(): custom models return the confidence score. """ - def __init__(self, *, text=None, location=None, confidence=None): + def __init__(self, + *, + text: str = None, + location: List[int] = None, + confidence: float = None) -> None: """ Initialize a EntityMention object. :param str text: (optional) Entity mention text. - :param list[int] location: (optional) Character offsets indicating the + :param List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. :param float confidence: (optional) Confidence in the entity identification from 0 to 1. Higher values indicate higher confidence. In standard entities @@ -1790,7 +1978,7 @@ def __init__(self, *, text=None, location=None, confidence=None): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} valid_keys = ['text', 'location', 'confidence'] @@ -1807,7 +1995,12 @@ def _from_dict(cls, _dict): args['confidence'] = _dict.get('confidence') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a EntityMention 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, 'text') and self.text is not None: @@ -1818,17 +2011,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 EntityMention object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'EntityMention') -> 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): + def __ne__(self, other: 'EntityMention') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1841,7 +2038,7 @@ class FeatureSentimentResults(): (positive). """ - def __init__(self, *, score=None): + def __init__(self, *, score: float = None) -> None: """ Initialize a FeatureSentimentResults object. @@ -1851,7 +2048,7 @@ def __init__(self, *, score=None): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FeatureSentimentResults': """Initialize a FeatureSentimentResults object from a json dictionary.""" args = {} valid_keys = ['score'] @@ -1864,24 +2061,33 @@ def _from_dict(cls, _dict): args['score'] = _dict.get('score') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeatureSentimentResults 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, 'score') and self.score is not None: _dict['score'] = self.score return _dict - def __str__(self): + 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 FeatureSentimentResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FeatureSentimentResults') -> 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): + def __ne__(self, other: 'FeatureSentimentResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1940,16 +2146,16 @@ class Features(): def __init__(self, *, - concepts=None, - emotion=None, - entities=None, - keywords=None, - metadata=None, - relations=None, - semantic_roles=None, - sentiment=None, - categories=None, - syntax=None): + concepts: 'ConceptsOptions' = None, + emotion: 'EmotionOptions' = None, + entities: 'EntitiesOptions' = None, + keywords: 'KeywordsOptions' = None, + metadata: 'MetadataOptions' = None, + relations: 'RelationsOptions' = None, + semantic_roles: 'SemanticRolesOptions' = None, + sentiment: 'SentimentOptions' = None, + categories: 'CategoriesOptions' = None, + syntax: 'SyntaxOptions' = None) -> None: """ Initialize a Features object. @@ -2013,7 +2219,7 @@ def __init__(self, self.syntax = syntax @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Features': """Initialize a Features object from a json dictionary.""" args = {} valid_keys = [ @@ -2051,7 +2257,12 @@ def _from_dict(cls, _dict): args['syntax'] = SyntaxOptions._from_dict(_dict.get('syntax')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Features 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, 'concepts') and self.concepts is not None: @@ -2076,17 +2287,21 @@ def _to_dict(self): _dict['syntax'] = self.syntax._to_dict() return _dict - def __str__(self): + 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 Features object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Features') -> 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): + def __ne__(self, other: 'Features') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2098,7 +2313,7 @@ class Feed(): :attr str link: (optional) URL of the RSS or ATOM feed. """ - def __init__(self, *, link=None): + def __init__(self, *, link: str = None) -> None: """ Initialize a Feed object. @@ -2107,7 +2322,7 @@ def __init__(self, *, link=None): self.link = link @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Feed': """Initialize a Feed object from a json dictionary.""" args = {} valid_keys = ['link'] @@ -2120,24 +2335,33 @@ def _from_dict(cls, _dict): args['link'] = _dict.get('link') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Feed 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, 'link') and self.link is not None: _dict['link'] = self.link return _dict - def __str__(self): + 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 Feed object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Feed') -> 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): + def __ne__(self, other: 'Feed') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2155,7 +2379,11 @@ class KeywordsOptions(): detected keywords. """ - def __init__(self, *, limit=None, sentiment=None, emotion=None): + def __init__(self, + *, + limit: int = None, + sentiment: bool = None, + emotion: bool = None) -> None: """ Initialize a KeywordsOptions object. @@ -2170,7 +2398,7 @@ def __init__(self, *, limit=None, sentiment=None, emotion=None): self.emotion = emotion @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'KeywordsOptions': """Initialize a KeywordsOptions object from a json dictionary.""" args = {} valid_keys = ['limit', 'sentiment', 'emotion'] @@ -2187,7 +2415,12 @@ def _from_dict(cls, _dict): args['emotion'] = _dict.get('emotion') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a KeywordsOptions 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, 'limit') and self.limit is not None: @@ -2198,17 +2431,21 @@ def _to_dict(self): _dict['emotion'] = self.emotion return _dict - def __str__(self): + 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 KeywordsOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'KeywordsOptions') -> 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): + def __ne__(self, other: 'KeywordsOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2230,11 +2467,11 @@ class KeywordsResult(): def __init__(self, *, - count=None, - relevance=None, - text=None, - emotion=None, - sentiment=None): + count: int = None, + relevance: float = None, + text: str = None, + emotion: 'EmotionScores' = None, + sentiment: 'FeatureSentimentResults' = None) -> None: """ Initialize a KeywordsResult object. @@ -2255,7 +2492,7 @@ def __init__(self, self.sentiment = sentiment @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'KeywordsResult': """Initialize a KeywordsResult object from a json dictionary.""" args = {} valid_keys = ['count', 'relevance', 'text', 'emotion', 'sentiment'] @@ -2277,7 +2514,12 @@ def _from_dict(cls, _dict): _dict.get('sentiment')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a KeywordsResult 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, 'count') and self.count is not None: @@ -2292,17 +2534,21 @@ def _to_dict(self): _dict['sentiment'] = self.sentiment._to_dict() return _dict - def __str__(self): + 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 KeywordsResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'KeywordsResult') -> 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): + def __ne__(self, other: 'KeywordsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2311,19 +2557,19 @@ class ListModelsResults(): """ Custom models that are available for entities and relations. - :attr list[Model] models: (optional) An array of available models. + :attr List[Model] models: (optional) An array of available models. """ - def __init__(self, *, models=None): + def __init__(self, *, models: List['Model'] = None) -> None: """ Initialize a ListModelsResults object. - :param list[Model] models: (optional) An array of available models. + :param List[Model] models: (optional) An array of available models. """ self.models = models @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ListModelsResults': """Initialize a ListModelsResults object from a json dictionary.""" args = {} valid_keys = ['models'] @@ -2338,24 +2584,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListModelsResults 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, 'models') and self.models is not None: _dict['models'] = [x._to_dict() for x in self.models] return _dict - def __str__(self): + 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 ListModelsResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ListModelsResults') -> 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): + def __ne__(self, other: 'ListModelsResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2367,34 +2622,43 @@ class MetadataOptions(): """ - def __init__(self): + def __init__(self) -> None: """ Initialize a MetadataOptions object. """ @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'MetadataOptions': """Initialize a MetadataOptions object from a json dictionary.""" args = {} return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a MetadataOptions object from a json dictionary.""" + return cls.from_dict(_dict) + + def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} return _dict - def __str__(self): + 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 MetadataOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'MetadataOptions') -> 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): + def __ne__(self, other: 'MetadataOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2421,14 +2685,14 @@ class Model(): def __init__(self, *, - status=None, - model_id=None, - language=None, - description=None, - workspace_id=None, - version=None, - version_description=None, - created=None): + status: str = None, + model_id: str = None, + language: str = None, + description: str = None, + workspace_id: str = None, + version: str = None, + version_description: str = None, + created: datetime = None) -> None: """ Initialize a Model object. @@ -2457,7 +2721,7 @@ def __init__(self, self.created = created @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Model': """Initialize a Model object from a json dictionary.""" args = {} valid_keys = [ @@ -2487,7 +2751,12 @@ def _from_dict(cls, _dict): args['created'] = string_to_datetime(_dict.get('created')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Model 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, 'status') and self.status is not None: @@ -2510,17 +2779,21 @@ def _to_dict(self): _dict['created'] = datetime_to_string(self.created) return _dict - def __str__(self): + 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 Model object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Model') -> 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): + def __ne__(self, other: 'Model') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2529,19 +2802,23 @@ class RelationArgument(): """ RelationArgument. - :attr list[RelationEntity] entities: (optional) An array of extracted entities. - :attr list[int] location: (optional) Character offsets indicating the beginning + :attr List[RelationEntity] entities: (optional) An array of extracted entities. + :attr List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. :attr str text: (optional) Text that corresponds to the argument. """ - def __init__(self, *, entities=None, location=None, text=None): + def __init__(self, + *, + entities: List['RelationEntity'] = None, + location: List[int] = None, + text: str = None) -> None: """ Initialize a RelationArgument object. - :param list[RelationEntity] entities: (optional) An array of extracted + :param List[RelationEntity] entities: (optional) An array of extracted entities. - :param list[int] location: (optional) Character offsets indicating the + :param List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. :param str text: (optional) Text that corresponds to the argument. """ @@ -2550,7 +2827,7 @@ def __init__(self, *, entities=None, location=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RelationArgument': """Initialize a RelationArgument object from a json dictionary.""" args = {} valid_keys = ['entities', 'location', 'text'] @@ -2569,7 +2846,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RelationArgument 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, 'entities') and self.entities is not None: @@ -2580,17 +2862,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 RelationArgument object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RelationArgument') -> 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): + def __ne__(self, other: 'RelationArgument') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2603,7 +2889,7 @@ class RelationEntity(): :attr str type: (optional) Entity type. """ - def __init__(self, *, text=None, type=None): + def __init__(self, *, text: str = None, type: str = None) -> None: """ Initialize a RelationEntity object. @@ -2614,7 +2900,7 @@ def __init__(self, *, text=None, type=None): self.type = type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RelationEntity': """Initialize a RelationEntity object from a json dictionary.""" args = {} valid_keys = ['text', 'type'] @@ -2629,7 +2915,12 @@ def _from_dict(cls, _dict): args['type'] = _dict.get('type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RelationEntity 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, 'text') and self.text is not None: @@ -2638,17 +2929,21 @@ def _to_dict(self): _dict['type'] = self.type return _dict - def __str__(self): + 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 RelationEntity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RelationEntity') -> 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): + def __ne__(self, other: 'RelationEntity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2667,7 +2962,7 @@ class RelationsOptions(): ID to override the default model. """ - def __init__(self, *, model=None): + def __init__(self, *, model: str = None) -> None: """ Initialize a RelationsOptions object. @@ -2678,7 +2973,7 @@ def __init__(self, *, model=None): self.model = model @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RelationsOptions': """Initialize a RelationsOptions object from a json dictionary.""" args = {} valid_keys = ['model'] @@ -2691,24 +2986,33 @@ def _from_dict(cls, _dict): args['model'] = _dict.get('model') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RelationsOptions 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, 'model') and self.model is not None: _dict['model'] = self.model return _dict - def __str__(self): + 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 RelationsOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RelationsOptions') -> 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): + def __ne__(self, other: 'RelationsOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2721,11 +3025,16 @@ class RelationsResult(): indicate greater confidence. :attr str sentence: (optional) The sentence that contains the relation. :attr str type: (optional) The type of the relation. - :attr list[RelationArgument] arguments: (optional) Entity mentions that are + :attr List[RelationArgument] arguments: (optional) Entity mentions that are involved in the relation. """ - def __init__(self, *, score=None, sentence=None, type=None, arguments=None): + def __init__(self, + *, + score: float = None, + sentence: str = None, + type: str = None, + arguments: List['RelationArgument'] = None) -> None: """ Initialize a RelationsResult object. @@ -2733,7 +3042,7 @@ def __init__(self, *, score=None, sentence=None, type=None, arguments=None): values indicate greater confidence. :param str sentence: (optional) The sentence that contains the relation. :param str type: (optional) The type of the relation. - :param list[RelationArgument] arguments: (optional) Entity mentions that + :param List[RelationArgument] arguments: (optional) Entity mentions that are involved in the relation. """ self.score = score @@ -2742,7 +3051,7 @@ def __init__(self, *, score=None, sentence=None, type=None, arguments=None): self.arguments = arguments @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RelationsResult': """Initialize a RelationsResult object from a json dictionary.""" args = {} valid_keys = ['score', 'sentence', 'type', 'arguments'] @@ -2763,7 +3072,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RelationsResult 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, 'score') and self.score is not None: @@ -2776,17 +3090,21 @@ def _to_dict(self): _dict['arguments'] = [x._to_dict() for x in self.arguments] return _dict - def __str__(self): + 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 RelationsResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RelationsResult') -> 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): + def __ne__(self, other: 'RelationsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2799,7 +3117,7 @@ class SemanticRolesEntity(): :attr str text: (optional) The entity text. """ - def __init__(self, *, type=None, text=None): + def __init__(self, *, type: str = None, text: str = None) -> None: """ Initialize a SemanticRolesEntity object. @@ -2810,7 +3128,7 @@ def __init__(self, *, type=None, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesEntity': """Initialize a SemanticRolesEntity object from a json dictionary.""" args = {} valid_keys = ['type', 'text'] @@ -2825,7 +3143,12 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesEntity 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: @@ -2834,17 +3157,21 @@ def _to_dict(self): _dict['text'] = self.text return _dict - def __str__(self): + 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 SemanticRolesEntity object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesEntity') -> 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): + def __ne__(self, other: 'SemanticRolesEntity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2856,7 +3183,7 @@ class SemanticRolesKeyword(): :attr str text: (optional) The keyword text. """ - def __init__(self, *, text=None): + def __init__(self, *, text: str = None) -> None: """ Initialize a SemanticRolesKeyword object. @@ -2865,7 +3192,7 @@ def __init__(self, *, text=None): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesKeyword': """Initialize a SemanticRolesKeyword object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -2878,24 +3205,33 @@ def _from_dict(cls, _dict): args['text'] = _dict.get('text') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesKeyword 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, 'text') and self.text is not None: _dict['text'] = self.text return _dict - def __str__(self): + 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 SemanticRolesKeyword object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesKeyword') -> 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): + def __ne__(self, other: 'SemanticRolesKeyword') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2912,7 +3248,11 @@ class SemanticRolesOptions(): for subjects and objects. """ - def __init__(self, *, limit=None, keywords=None, entities=None): + def __init__(self, + *, + limit: int = None, + keywords: bool = None, + entities: bool = None) -> None: """ Initialize a SemanticRolesOptions object. @@ -2928,7 +3268,7 @@ def __init__(self, *, limit=None, keywords=None, entities=None): self.entities = entities @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesOptions': """Initialize a SemanticRolesOptions object from a json dictionary.""" args = {} valid_keys = ['limit', 'keywords', 'entities'] @@ -2945,7 +3285,12 @@ def _from_dict(cls, _dict): args['entities'] = _dict.get('entities') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesOptions 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, 'limit') and self.limit is not None: @@ -2956,17 +3301,21 @@ def _to_dict(self): _dict['entities'] = self.entities return _dict - def __str__(self): + 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 SemanticRolesOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesOptions') -> 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): + def __ne__(self, other: 'SemanticRolesOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2985,8 +3334,12 @@ class SemanticRolesResult(): sentence. """ - def __init__(self, *, sentence=None, subject=None, action=None, - object=None): + def __init__(self, + *, + sentence: str = None, + subject: 'SemanticRolesResultSubject' = None, + action: 'SemanticRolesResultAction' = None, + object: 'SemanticRolesResultObject' = None) -> None: """ Initialize a SemanticRolesResult object. @@ -3005,7 +3358,7 @@ def __init__(self, *, sentence=None, subject=None, action=None, self.object = object @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesResult': """Initialize a SemanticRolesResult object from a json dictionary.""" args = {} valid_keys = ['sentence', 'subject', 'action', 'object'] @@ -3027,7 +3380,12 @@ def _from_dict(cls, _dict): _dict.get('object')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesResult 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, 'sentence') and self.sentence is not None: @@ -3040,17 +3398,21 @@ def _to_dict(self): _dict['object'] = self.object._to_dict() return _dict - def __str__(self): + 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 SemanticRolesResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesResult') -> 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): + def __ne__(self, other: 'SemanticRolesResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3064,7 +3426,11 @@ class SemanticRolesResultAction(): :attr SemanticRolesVerb verb: (optional) """ - def __init__(self, *, text=None, normalized=None, verb=None): + def __init__(self, + *, + text: str = None, + normalized: str = None, + verb: 'SemanticRolesVerb' = None) -> None: """ Initialize a SemanticRolesResultAction object. @@ -3077,7 +3443,7 @@ def __init__(self, *, text=None, normalized=None, verb=None): self.verb = verb @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultAction': """Initialize a SemanticRolesResultAction object from a json dictionary.""" args = {} valid_keys = ['text', 'normalized', 'verb'] @@ -3094,7 +3460,12 @@ def _from_dict(cls, _dict): args['verb'] = SemanticRolesVerb._from_dict(_dict.get('verb')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesResultAction 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, 'text') and self.text is not None: @@ -3105,17 +3476,21 @@ def _to_dict(self): _dict['verb'] = self.verb._to_dict() return _dict - def __str__(self): + 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 SemanticRolesResultAction object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesResultAction') -> 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): + def __ne__(self, other: 'SemanticRolesResultAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3125,23 +3500,26 @@ class SemanticRolesResultObject(): The extracted object from the sentence. :attr str text: (optional) Object text. - :attr list[SemanticRolesKeyword] keywords: (optional) An array of extracted + :attr List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ - def __init__(self, *, text=None, keywords=None): + def __init__(self, + *, + text: str = None, + keywords: List['SemanticRolesKeyword'] = None) -> None: """ Initialize a SemanticRolesResultObject object. :param str text: (optional) Object text. - :param list[SemanticRolesKeyword] keywords: (optional) An array of + :param List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ self.text = text self.keywords = keywords @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultObject': """Initialize a SemanticRolesResultObject object from a json dictionary.""" args = {} valid_keys = ['text', 'keywords'] @@ -3159,7 +3537,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesResultObject 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, 'text') and self.text is not None: @@ -3168,17 +3551,21 @@ def _to_dict(self): _dict['keywords'] = [x._to_dict() for x in self.keywords] return _dict - def __str__(self): + 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 SemanticRolesResultObject object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesResultObject') -> 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): + def __ne__(self, other: 'SemanticRolesResultObject') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3188,20 +3575,24 @@ class SemanticRolesResultSubject(): The extracted subject from the sentence. :attr str text: (optional) Text that corresponds to the subject role. - :attr list[SemanticRolesEntity] entities: (optional) An array of extracted + :attr List[SemanticRolesEntity] entities: (optional) An array of extracted entities. - :attr list[SemanticRolesKeyword] keywords: (optional) An array of extracted + :attr List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ - def __init__(self, *, text=None, entities=None, keywords=None): + def __init__(self, + *, + text: str = None, + entities: List['SemanticRolesEntity'] = None, + keywords: List['SemanticRolesKeyword'] = None) -> None: """ Initialize a SemanticRolesResultSubject object. :param str text: (optional) Text that corresponds to the subject role. - :param list[SemanticRolesEntity] entities: (optional) An array of extracted + :param List[SemanticRolesEntity] entities: (optional) An array of extracted entities. - :param list[SemanticRolesKeyword] keywords: (optional) An array of + :param List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ self.text = text @@ -3209,7 +3600,7 @@ def __init__(self, *, text=None, entities=None, keywords=None): self.keywords = keywords @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultSubject': """Initialize a SemanticRolesResultSubject object from a json dictionary.""" args = {} valid_keys = ['text', 'entities', 'keywords'] @@ -3232,7 +3623,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesResultSubject 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, 'text') and self.text is not None: @@ -3243,17 +3639,21 @@ def _to_dict(self): _dict['keywords'] = [x._to_dict() for x in self.keywords] return _dict - def __str__(self): + 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 SemanticRolesResultSubject object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesResultSubject') -> 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): + def __ne__(self, other: 'SemanticRolesResultSubject') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3266,7 +3666,7 @@ class SemanticRolesVerb(): :attr str tense: (optional) Verb tense. """ - def __init__(self, *, text=None, tense=None): + def __init__(self, *, text: str = None, tense: str = None) -> None: """ Initialize a SemanticRolesVerb object. @@ -3277,7 +3677,7 @@ def __init__(self, *, text=None, tense=None): self.tense = tense @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SemanticRolesVerb': """Initialize a SemanticRolesVerb object from a json dictionary.""" args = {} valid_keys = ['text', 'tense'] @@ -3292,7 +3692,12 @@ def _from_dict(cls, _dict): args['tense'] = _dict.get('tense') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SemanticRolesVerb 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, 'text') and self.text is not None: @@ -3301,17 +3706,21 @@ def _to_dict(self): _dict['tense'] = self.tense return _dict - def __str__(self): + 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 SemanticRolesVerb object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SemanticRolesVerb') -> 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): + def __ne__(self, other: 'SemanticRolesVerb') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3321,23 +3730,23 @@ class SentenceResult(): SentenceResult. :attr str text: (optional) The sentence. - :attr list[int] location: (optional) Character offsets indicating the beginning + :attr List[int] location: (optional) Character offsets indicating the beginning and end of the sentence in the analyzed text. """ - def __init__(self, *, text=None, location=None): + def __init__(self, *, text: str = None, location: List[int] = None) -> None: """ Initialize a SentenceResult object. :param str text: (optional) The sentence. - :param list[int] location: (optional) Character offsets indicating the + :param List[int] location: (optional) Character offsets indicating the beginning and end of the sentence in the analyzed text. """ self.text = text self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SentenceResult': """Initialize a SentenceResult object from a json dictionary.""" args = {} valid_keys = ['text', 'location'] @@ -3352,7 +3761,12 @@ def _from_dict(cls, _dict): args['location'] = _dict.get('location') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SentenceResult 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, 'text') and self.text is not None: @@ -3361,17 +3775,21 @@ def _to_dict(self): _dict['location'] = self.location return _dict - def __str__(self): + 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 SentenceResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SentenceResult') -> 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): + def __ne__(self, other: 'SentenceResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3386,24 +3804,25 @@ class SentimentOptions(): :attr bool document: (optional) Set this to `false` to hide document-level sentiment results. - :attr list[str] targets: (optional) Sentiment results will be returned for each + :attr List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, *, document: bool = None, + targets: List[str] = None) -> None: """ Initialize a SentimentOptions object. :param bool document: (optional) Set this to `false` to hide document-level sentiment results. - :param list[str] targets: (optional) Sentiment results will be returned for + :param List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SentimentOptions': """Initialize a SentimentOptions object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -3418,7 +3837,12 @@ def _from_dict(cls, _dict): args['targets'] = _dict.get('targets') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SentimentOptions 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, 'document') and self.document is not None: @@ -3427,17 +3851,21 @@ def _to_dict(self): _dict['targets'] = self.targets return _dict - def __str__(self): + 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 SentimentOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SentimentOptions') -> 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): + def __ne__(self, other: 'SentimentOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3448,24 +3876,27 @@ class SentimentResult(): :attr DocumentSentimentResults document: (optional) The document level sentiment. - :attr list[TargetedSentimentResults] targets: (optional) The targeted sentiment + :attr List[TargetedSentimentResults] targets: (optional) The targeted sentiment to analyze. """ - def __init__(self, *, document=None, targets=None): + def __init__(self, + *, + document: 'DocumentSentimentResults' = None, + targets: List['TargetedSentimentResults'] = None) -> None: """ Initialize a SentimentResult object. :param DocumentSentimentResults document: (optional) The document level sentiment. - :param list[TargetedSentimentResults] targets: (optional) The targeted + :param List[TargetedSentimentResults] targets: (optional) The targeted sentiment to analyze. """ self.document = document self.targets = targets @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SentimentResult': """Initialize a SentimentResult object from a json dictionary.""" args = {} valid_keys = ['document', 'targets'] @@ -3484,7 +3915,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SentimentResult 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, 'document') and self.document is not None: @@ -3493,17 +3929,21 @@ def _to_dict(self): _dict['targets'] = [x._to_dict() for x in self.targets] return _dict - def __str__(self): + 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 SentimentResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SentimentResult') -> 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): + def __ne__(self, other: 'SentimentResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3517,7 +3957,10 @@ class SyntaxOptions(): information. """ - def __init__(self, *, tokens=None, sentences=None): + def __init__(self, + *, + tokens: 'SyntaxOptionsTokens' = None, + sentences: bool = None) -> None: """ Initialize a SyntaxOptions object. @@ -3529,7 +3972,7 @@ def __init__(self, *, tokens=None, sentences=None): self.sentences = sentences @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SyntaxOptions': """Initialize a SyntaxOptions object from a json dictionary.""" args = {} valid_keys = ['tokens', 'sentences'] @@ -3544,7 +3987,12 @@ def _from_dict(cls, _dict): args['sentences'] = _dict.get('sentences') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SyntaxOptions 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, 'tokens') and self.tokens is not None: @@ -3553,17 +4001,21 @@ def _to_dict(self): _dict['sentences'] = self.sentences return _dict - def __str__(self): + 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 SyntaxOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SyntaxOptions') -> 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): + def __ne__(self, other: 'SyntaxOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3578,7 +4030,8 @@ class SyntaxOptionsTokens(): speech for each token. """ - def __init__(self, *, lemma=None, part_of_speech=None): + def __init__(self, *, lemma: bool = None, + part_of_speech: bool = None) -> None: """ Initialize a SyntaxOptionsTokens object. @@ -3591,7 +4044,7 @@ def __init__(self, *, lemma=None, part_of_speech=None): self.part_of_speech = part_of_speech @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SyntaxOptionsTokens': """Initialize a SyntaxOptionsTokens object from a json dictionary.""" args = {} valid_keys = ['lemma', 'part_of_speech'] @@ -3606,7 +4059,12 @@ def _from_dict(cls, _dict): args['part_of_speech'] = _dict.get('part_of_speech') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SyntaxOptionsTokens 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, 'lemma') and self.lemma is not None: @@ -3615,17 +4073,21 @@ def _to_dict(self): _dict['part_of_speech'] = self.part_of_speech return _dict - def __str__(self): + 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 SyntaxOptionsTokens object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SyntaxOptionsTokens') -> 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): + def __ne__(self, other: 'SyntaxOptionsTokens') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3634,22 +4096,25 @@ class SyntaxResult(): """ Tokens and sentences returned from syntax analysis. - :attr list[TokenResult] tokens: (optional) - :attr list[SentenceResult] sentences: (optional) + :attr List[TokenResult] tokens: (optional) + :attr List[SentenceResult] sentences: (optional) """ - def __init__(self, *, tokens=None, sentences=None): + def __init__(self, + *, + tokens: List['TokenResult'] = None, + sentences: List['SentenceResult'] = None) -> None: """ Initialize a SyntaxResult object. - :param list[TokenResult] tokens: (optional) - :param list[SentenceResult] sentences: (optional) + :param List[TokenResult] tokens: (optional) + :param List[SentenceResult] sentences: (optional) """ self.tokens = tokens self.sentences = sentences @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SyntaxResult': """Initialize a SyntaxResult object from a json dictionary.""" args = {} valid_keys = ['tokens', 'sentences'] @@ -3668,7 +4133,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SyntaxResult 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, 'tokens') and self.tokens is not None: @@ -3677,17 +4147,21 @@ def _to_dict(self): _dict['sentences'] = [x._to_dict() for x in self.sentences] return _dict - def __str__(self): + 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 SyntaxResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SyntaxResult') -> 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): + def __ne__(self, other: 'SyntaxResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3700,7 +4174,8 @@ class TargetedEmotionResults(): :attr EmotionScores emotion: (optional) The emotion results for the target. """ - def __init__(self, *, text=None, emotion=None): + def __init__(self, *, text: str = None, + emotion: 'EmotionScores' = None) -> None: """ Initialize a TargetedEmotionResults object. @@ -3712,7 +4187,7 @@ def __init__(self, *, text=None, emotion=None): self.emotion = emotion @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TargetedEmotionResults': """Initialize a TargetedEmotionResults object from a json dictionary.""" args = {} valid_keys = ['text', 'emotion'] @@ -3727,7 +4202,12 @@ def _from_dict(cls, _dict): args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TargetedEmotionResults 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, 'text') and self.text is not None: @@ -3736,17 +4216,21 @@ def _to_dict(self): _dict['emotion'] = self.emotion._to_dict() return _dict - def __str__(self): + 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 TargetedEmotionResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TargetedEmotionResults') -> 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): + def __ne__(self, other: 'TargetedEmotionResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3760,7 +4244,7 @@ class TargetedSentimentResults(): (positive). """ - def __init__(self, *, text=None, score=None): + def __init__(self, *, text: str = None, score: float = None) -> None: """ Initialize a TargetedSentimentResults object. @@ -3772,7 +4256,7 @@ def __init__(self, *, text=None, score=None): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TargetedSentimentResults': """Initialize a TargetedSentimentResults object from a json dictionary.""" args = {} valid_keys = ['text', 'score'] @@ -3787,7 +4271,12 @@ def _from_dict(cls, _dict): args['score'] = _dict.get('score') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TargetedSentimentResults 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, 'text') and self.text is not None: @@ -3796,17 +4285,21 @@ def _to_dict(self): _dict['score'] = self.score return _dict - def __str__(self): + 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 TargetedSentimentResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TargetedSentimentResults') -> 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): + def __ne__(self, other: 'TargetedSentimentResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3819,7 +4312,7 @@ class TokenResult(): :attr str part_of_speech: (optional) The part of speech of the token. For descriptions of the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). - :attr list[int] location: (optional) Character offsets indicating the beginning + :attr List[int] location: (optional) Character offsets indicating the beginning and end of the token in the analyzed text. :attr str lemma: (optional) The [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. @@ -3827,10 +4320,10 @@ class TokenResult(): def __init__(self, *, - text=None, - part_of_speech=None, - location=None, - lemma=None): + text: str = None, + part_of_speech: str = None, + location: List[int] = None, + lemma: str = None) -> None: """ Initialize a TokenResult object. @@ -3838,7 +4331,7 @@ def __init__(self, :param str part_of_speech: (optional) The part of speech of the token. For descriptions of the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). - :param list[int] location: (optional) Character offsets indicating the + :param List[int] location: (optional) Character offsets indicating the beginning and end of the token in the analyzed text. :param str lemma: (optional) The [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. @@ -3849,7 +4342,7 @@ def __init__(self, self.lemma = lemma @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TokenResult': """Initialize a TokenResult object from a json dictionary.""" args = {} valid_keys = ['text', 'part_of_speech', 'location', 'lemma'] @@ -3868,7 +4361,12 @@ def _from_dict(cls, _dict): args['lemma'] = _dict.get('lemma') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TokenResult 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, 'text') and self.text is not None: @@ -3881,17 +4379,21 @@ def _to_dict(self): _dict['lemma'] = self.lemma return _dict - def __str__(self): + 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 TokenResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TokenResult') -> 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): + def __ne__(self, other: 'TokenResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py new file mode 100644 index 000000000..e567e8f07 --- /dev/null +++ b/test/unit/test_natural_language_understanding_v1.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect +import json +import pytest +import responses +import tempfile +import ibm_watson.natural_language_understanding_v1 +from ibm_watson.natural_language_understanding_v1 import * + +base_url = 'https://gateway.watsonplatform.net/natural-language-understanding/api' + +############################################################################## +# Start of Service: Analyze +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for analyze +#----------------------------------------------------------------------------- +class TestAnalyze(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_analyze_response(self): + body = self.construct_full_body() + response = fake_response_AnalysisResults_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_analyze_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AnalysisResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_analyze_empty(self): + check_empty_required_params(self, fake_response_AnalysisResults_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/analyze' + 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 = NaturalLanguageUnderstandingV1( + authenticator=NoAuthAuthenticator(), + version='2019-07-12', + ) + service.set_service_url(base_url) + output = service.analyze(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "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}}""" + )), + "text": + "string1", + "html": + "string1", + "url": + "string1", + "clean": + True, + "xpath": + "string1", + "fallback_to_raw": + True, + "return_analyzed_text": + True, + "language": + "string1", + "limit_text_characters": + 12345, + }) + return body + + def construct_required_body(self): + body = dict() + body.update({ + "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}}""" + )), + "text": + "string1", + "html": + "string1", + "url": + "string1", + "clean": + True, + "xpath": + "string1", + "fallback_to_raw": + True, + "return_analyzed_text": + True, + "language": + "string1", + "limit_text_characters": + 12345, + }) + return body + + +# endregion +############################################################################## +# End of Service: Analyze +############################################################################## + +############################################################################## +# Start of Service: ManageModels +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_models +#----------------------------------------------------------------------------- +class TestListModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_response(self): + body = self.construct_full_body() + response = fake_response_ListModelsResults_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_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListModelsResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/models' + 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 = NaturalLanguageUnderstandingV1( + authenticator=NoAuthAuthenticator(), + version='2019-07-12', + ) + service.set_service_url(base_url) + output = service.list_models(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_model +#----------------------------------------------------------------------------- +class TestDeleteModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_model_response(self): + body = self.construct_full_body() + response = fake_response_DeleteModelResults_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_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_DeleteModelResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_model_empty(self): + check_empty_required_params(self, fake_response_DeleteModelResults_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/models/{0}'.format(body['model_id']) + 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='application/json') + + def call_service(self, body): + service = NaturalLanguageUnderstandingV1( + authenticator=NoAuthAuthenticator(), + version='2019-07-12', + ) + service.set_service_url(base_url) + output = service.delete_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['model_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['model_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: ManageModels +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_AnalysisResults_json = """{"language": "fake_language", "analyzed_text": "fake_analyzed_text", "retrieved_url": "fake_retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [], "entities": [], "keywords": [], "categories": [], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": []}, "metadata": {"authors": [], "publication_date": "fake_publication_date", "title": "fake_title", "image": "fake_image", "feeds": []}, "relations": [], "semantic_roles": [], "sentiment": {"document": {"label": "fake_label", "score": 5}, "targets": []}, "syntax": {"tokens": [], "sentences": []}}""" +fake_response_ListModelsResults_json = """{"models": []}""" +fake_response_DeleteModelResults_json = """{"deleted": "fake_deleted"}""" From 68dfef715ec6435ba2c895276ddfb8595b4a8bea Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:34:42 -0500 Subject: [PATCH 179/455] refactor(pi): regenerate personality insights with tests --- ibm_watson/personality_insights_v3.py | 326 +++++++++++++--------- test/unit/test_personality_insights_v3.py | 298 ++++++++++++-------- 2 files changed, 382 insertions(+), 242 deletions(-) diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 2bdd20062..2f99e5075 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -34,11 +34,15 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator 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 read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from typing import Dict +from typing import List ############################################################################## # Service @@ -48,13 +52,15 @@ class PersonalityInsightsV3(BaseService): """The Personality Insights V3 service.""" - default_service_url = 'https://gateway.watsonplatform.net/personality-insights/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/personality-insights/api' + DEFAULT_SERVICE_NAME = 'personality_insights' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Personality Insights service. @@ -73,41 +79,30 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('personality_insights') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'personality_insights') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Methods ######################### def profile(self, - content, - accept, + content: object, + accept: str, *, - content_type=None, - content_language=None, - accept_language=None, - raw_scores=None, - csv_headers=None, - consumption_preferences=None, - **kwargs): + content_type: str = None, + content_language: str = None, + accept_language: str = None, + raw_scores: bool = None, + csv_headers: bool = None, + consumption_preferences: bool = None, + **kwargs) -> 'DetailedResponse': """ Get profile. @@ -200,7 +195,9 @@ def profile(self, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('personality_insights', 'V3', 'profile') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='profile') headers.update(sdk_headers) params = { @@ -216,13 +213,12 @@ def profile(self, data = content url = '/v3/profile' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - accept_json=(accept is None or accept == 'application/json')) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + response = self.send(request) return response @@ -305,7 +301,8 @@ class Behavior(): day. The range is 0 to 1. """ - def __init__(self, trait_id, name, category, percentage): + def __init__(self, trait_id: str, name: str, category: str, + percentage: float) -> None: """ Initialize a Behavior object. @@ -325,7 +322,7 @@ def __init__(self, trait_id, name, category, percentage): self.percentage = percentage @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Behavior': """Initialize a Behavior object from a json dictionary.""" args = {} valid_keys = ['trait_id', 'name', 'category', 'percentage'] @@ -356,7 +353,12 @@ def _from_dict(cls, _dict): 'Required property \'percentage\' not present in Behavior JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Behavior 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, 'trait_id') and self.trait_id is not None: @@ -369,17 +371,21 @@ def _to_dict(self): _dict['percentage'] = self.percentage return _dict - def __str__(self): + 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 Behavior object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Behavior') -> 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): + def __ne__(self, other: 'Behavior') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -401,7 +407,8 @@ class ConsumptionPreferences(): input text, not a normalized percentile. """ - def __init__(self, consumption_preference_id, name, score): + def __init__(self, consumption_preference_id: str, name: str, + score: float) -> None: """ Initialize a ConsumptionPreferences object. @@ -423,7 +430,7 @@ def __init__(self, consumption_preference_id, name, score): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ConsumptionPreferences': """Initialize a ConsumptionPreferences object from a json dictionary.""" args = {} valid_keys = ['consumption_preference_id', 'name', 'score'] @@ -453,7 +460,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ConsumptionPreferences 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, 'consumption_preference_id' @@ -465,17 +477,21 @@ def _to_dict(self): _dict['score'] = self.score return _dict - def __str__(self): + 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 ConsumptionPreferences object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ConsumptionPreferences') -> 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): + def __ne__(self, other: 'ConsumptionPreferences') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -488,12 +504,13 @@ class ConsumptionPreferencesCategory(): identifier of the consumption preferences category to which the results pertain. IDs have the form `consumption_preferences_{category}`. :attr str name: The user-visible name of the consumption preferences category. - :attr list[ConsumptionPreferences] consumption_preferences: Detailed results + :attr List[ConsumptionPreferences] consumption_preferences: Detailed results inferred from the input text for the individual preferences of the category. """ - def __init__(self, consumption_preference_category_id, name, - consumption_preferences): + def __init__(self, consumption_preference_category_id: str, name: str, + consumption_preferences: List['ConsumptionPreferences'] + ) -> None: """ Initialize a ConsumptionPreferencesCategory object. @@ -502,7 +519,7 @@ def __init__(self, consumption_preference_category_id, name, pertain. IDs have the form `consumption_preferences_{category}`. :param str name: The user-visible name of the consumption preferences category. - :param list[ConsumptionPreferences] consumption_preferences: Detailed + :param List[ConsumptionPreferences] consumption_preferences: Detailed results inferred from the input text for the individual preferences of the category. """ @@ -511,7 +528,7 @@ def __init__(self, consumption_preference_category_id, name, self.consumption_preferences = consumption_preferences @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ConsumptionPreferencesCategory': """Initialize a ConsumptionPreferencesCategory object from a json dictionary.""" args = {} valid_keys = [ @@ -547,7 +564,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ConsumptionPreferencesCategory 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, 'consumption_preference_category_id' @@ -563,17 +585,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 ConsumptionPreferencesCategory object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ConsumptionPreferencesCategory') -> 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): + def __ne__(self, other: 'ConsumptionPreferencesCategory') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -582,21 +608,21 @@ class Content(): """ The full input content that the service is to analyze. - :attr list[ContentItem] content_items: An array of `ContentItem` objects that + :attr List[ContentItem] content_items: An array of `ContentItem` objects that provides the text that is to be analyzed. """ - def __init__(self, content_items): + def __init__(self, content_items: List['ContentItem']) -> None: """ Initialize a Content object. - :param list[ContentItem] content_items: An array of `ContentItem` objects + :param List[ContentItem] content_items: An array of `ContentItem` objects that provides the text that is to be analyzed. """ self.content_items = content_items @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Content': """Initialize a Content object from a json dictionary.""" args = {} valid_keys = ['content_items', 'contentItems'] @@ -615,24 +641,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Content 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, 'content_items') and self.content_items is not None: _dict['contentItems'] = [x._to_dict() for x in self.content_items] return _dict - def __str__(self): + 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 Content object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Content') -> 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): + def __ne__(self, other: 'Content') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -673,16 +708,16 @@ class ContentItem(): """ def __init__(self, - content, + content: str, *, - id=None, - created=None, - updated=None, - contenttype=None, - language=None, - parentid=None, - reply=None, - forward=None): + id: str = None, + created: int = None, + updated: int = None, + contenttype: str = None, + language: str = None, + parentid: str = None, + reply: bool = None, + forward: bool = None) -> None: """ Initialize a ContentItem object. @@ -729,7 +764,7 @@ def __init__(self, self.forward = forward @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ContentItem': """Initialize a ContentItem object from a json dictionary.""" args = {} valid_keys = [ @@ -764,7 +799,12 @@ def _from_dict(cls, _dict): args['forward'] = _dict.get('forward') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ContentItem 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, 'content') and self.content is not None: @@ -787,17 +827,21 @@ def _to_dict(self): _dict['forward'] = self.forward return _dict - def __str__(self): + 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 ContentItem object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ContentItem') -> 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): + def __ne__(self, other: 'ContentItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -839,38 +883,39 @@ class Profile(): :attr str word_count_message: (optional) When guidance is appropriate, a string that provides a message that indicates the number of words found and where that value falls in the range of required or suggested number of words. - :attr list[Trait] personality: A recursive array of `Trait` objects that + :attr List[Trait] personality: A recursive array of `Trait` objects that provides detailed results for the Big Five personality characteristics (dimensions and facets) inferred from the input text. - :attr list[Trait] needs: Detailed results for the Needs characteristics inferred + :attr List[Trait] needs: Detailed results for the Needs characteristics inferred from the input text. - :attr list[Trait] values: Detailed results for the Values characteristics + :attr List[Trait] values: Detailed results for the Values characteristics inferred from the input text. - :attr list[Behavior] behavior: (optional) For JSON content that is timestamped, + :attr List[Behavior] behavior: (optional) For JSON content that is timestamped, detailed results about the social behavior disclosed by the input in terms of temporal characteristics. The results include information about the distribution of the content over the days of the week and the hours of the day. - :attr list[ConsumptionPreferencesCategory] consumption_preferences: (optional) + :attr List[ConsumptionPreferencesCategory] consumption_preferences: (optional) If the **consumption_preferences** parameter is `true`, detailed results for each category of consumption preferences. Each element of the array provides information inferred from the input text for the individual preferences of that category. - :attr list[Warning] warnings: An array of warning messages that are associated + :attr List[Warning] warnings: An array of warning messages that are associated with the input text for the request. The array is empty if the input generated no warnings. """ def __init__(self, - processed_language, - word_count, - personality, - needs, - values, - warnings, + processed_language: str, + word_count: int, + personality: List['Trait'], + needs: List['Trait'], + values: List['Trait'], + warnings: List['Warning'], *, - word_count_message=None, - behavior=None, - consumption_preferences=None): + word_count_message: str = None, + behavior: List['Behavior'] = None, + consumption_preferences: List[ + 'ConsumptionPreferencesCategory'] = None) -> None: """ Initialize a Profile object. @@ -878,26 +923,26 @@ def __init__(self, the input. :param int word_count: The number of words from the input that were used to produce the profile. - :param list[Trait] personality: A recursive array of `Trait` objects that + :param List[Trait] personality: A recursive array of `Trait` objects that provides detailed results for the Big Five personality characteristics (dimensions and facets) inferred from the input text. - :param list[Trait] needs: Detailed results for the Needs characteristics + :param List[Trait] needs: Detailed results for the Needs characteristics inferred from the input text. - :param list[Trait] values: Detailed results for the Values characteristics + :param List[Trait] values: Detailed results for the Values characteristics inferred from the input text. - :param list[Warning] warnings: An array of warning messages that are + :param List[Warning] warnings: An array of warning messages that are associated with the input text for the request. The array is empty if the input generated no warnings. :param str word_count_message: (optional) When guidance is appropriate, a string that provides a message that indicates the number of words found and where that value falls in the range of required or suggested number of words. - :param list[Behavior] behavior: (optional) For JSON content that is + :param List[Behavior] behavior: (optional) For JSON content that is timestamped, detailed results about the social behavior disclosed by the input in terms of temporal characteristics. The results include information about the distribution of the content over the days of the week and the hours of the day. - :param list[ConsumptionPreferencesCategory] consumption_preferences: + :param List[ConsumptionPreferencesCategory] consumption_preferences: (optional) If the **consumption_preferences** parameter is `true`, detailed results for each category of consumption preferences. Each element of the array provides information inferred from the input text for the individual @@ -914,7 +959,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Profile': """Initialize a Profile object from a json dictionary.""" args = {} valid_keys = [ @@ -977,7 +1022,12 @@ def _from_dict(cls, _dict): 'Required property \'warnings\' not present in Profile JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Profile 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( @@ -1007,17 +1057,21 @@ def _to_dict(self): _dict['warnings'] = [x._to_dict() for x in self.warnings] return _dict - def __str__(self): + 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 Profile object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Profile') -> 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): + def __ne__(self, other: 'Profile') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1065,20 +1119,20 @@ class Trait(): `false` for the subset of characteristics of Arabic and Korean input for which the service's models are unable to generate meaningful results. **`2016-10-19`**: Not returned. - :attr list[Trait] children: (optional) For `personality` (Big Five) dimensions, + :attr List[Trait] children: (optional) For `personality` (Big Five) dimensions, more detailed results for the facets of each dimension as inferred from the input text. """ def __init__(self, - trait_id, - name, - category, - percentile, + trait_id: str, + name: str, + category: str, + percentile: float, *, - raw_score=None, - significant=None, - children=None): + raw_score: float = None, + significant: bool = None, + children: List['Trait'] = None) -> None: """ Initialize a Trait object. @@ -1113,7 +1167,7 @@ def __init__(self, field is `false` for the subset of characteristics of Arabic and Korean input for which the service's models are unable to generate meaningful results. **`2016-10-19`**: Not returned. - :param list[Trait] children: (optional) For `personality` (Big Five) + :param List[Trait] children: (optional) For `personality` (Big Five) dimensions, more detailed results for the facets of each dimension as inferred from the input text. """ @@ -1126,7 +1180,7 @@ def __init__(self, self.children = children @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Trait': """Initialize a Trait object from a json dictionary.""" args = {} valid_keys = [ @@ -1168,7 +1222,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Trait 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, 'trait_id') and self.trait_id is not None: @@ -1187,17 +1246,21 @@ def _to_dict(self): _dict['children'] = [x._to_dict() for x in self.children] return _dict - def __str__(self): + 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 Trait object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Trait') -> 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): + def __ne__(self, other: 'Trait') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1233,7 +1296,7 @@ class Warning(): of the profile. """ - def __init__(self, warning_id, message): + def __init__(self, warning_id: str, message: str) -> None: """ Initialize a Warning object. @@ -1258,7 +1321,7 @@ def __init__(self, warning_id, message): self.message = message @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Warning': """Initialize a Warning object from a json dictionary.""" args = {} valid_keys = ['warning_id', 'message'] @@ -1279,7 +1342,12 @@ def _from_dict(cls, _dict): 'Required property \'message\' not present in Warning JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Warning 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, 'warning_id') and self.warning_id is not None: @@ -1288,17 +1356,21 @@ def _to_dict(self): _dict['message'] = self.message return _dict - def __str__(self): + 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 Warning object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Warning') -> 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): + def __ne__(self, other: 'Warning') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index 269346959..9fae31cba 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -1,116 +1,184 @@ -# coding: utf-8 +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect +import json +import pytest import responses -import ibm_watson -import os -import codecs -from ibm_watson.personality_insights_v3 import Profile -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -profile_url = 'https://gateway.watsonplatform.net/personality-insights/api/v3/profile' - -@responses.activate -def test_plain_to_json(): - authenticator = BasicAuthenticator('username', 'password') - personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect1.txt'), 'r') as expect_file: - profile_response = expect_file.read() - - responses.add(responses.POST, profile_url, - body=profile_response, status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.txt'), 'rb') as personality_text: - response = personality_insights.profile( - personality_text, 'application/json', content_type='text/plain;charset=utf-8').get_result() - - assert 'version=2016-10-20' in responses.calls[0].request.url - assert responses.calls[0].response.text == profile_response - assert len(responses.calls) == 1 - # Verify that response can be converted to a Profile - Profile._from_dict(response) - -@responses.activate -def test_json_to_json(): - - authenticator = BasicAuthenticator('username', 'password') - personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect2.txt'), 'r') as expect_file: - profile_response = expect_file.read() - - responses.add(responses.POST, profile_url, - body=profile_response, status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.json'), 'rb') as personality_text: - response = personality_insights.profile( - personality_text, accept='application/json', - content_type='application/json', - raw_scores=True, - consumption_preferences=True).get_result() - - assert 'version=2016-10-20' in responses.calls[0].request.url - assert 'raw_scores=true' in responses.calls[0].request.url - assert 'consumption_preferences=true' in responses.calls[0].request.url - assert responses.calls[0].response.text == profile_response - assert len(responses.calls) == 1 - # Verify that response can be converted to a Profile - Profile._from_dict(response) - -@responses.activate -def test_json_to_csv(): - - authenticator = BasicAuthenticator('username', 'password') - personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect3.txt'), 'r') as expect_file: - profile_response = expect_file.read() - - responses.add(responses.POST, profile_url, - body=profile_response, status=200, - content_type='text/csv') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3.json'), 'rb') as personality_text: - personality_insights.profile( - personality_text, - 'text/csv', - content_type='application/json', - csv_headers=True, - raw_scores=True, - consumption_preferences=True) - - assert 'version=2016-10-20' in responses.calls[0].request.url - assert 'raw_scores=true' in responses.calls[0].request.url - assert 'consumption_preferences=true' in responses.calls[0].request.url - assert 'csv_headers=true' in responses.calls[0].request.url - assert responses.calls[0].response.text == profile_response - assert len(responses.calls) == 1 - - -@responses.activate -def test_plain_to_json_es(): - - authenticator = BasicAuthenticator('username', 'password') - personality_insights = ibm_watson.PersonalityInsightsV3('2016-10-20', authenticator=authenticator) - - with codecs.open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-expect4.txt'), 'r') as expect_file: - profile_response = expect_file.read() - - responses.add(responses.POST, profile_url, - body=profile_response, status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality-v3-es.txt'), 'rb') as personality_text: - response = personality_insights.profile( - personality_text, - 'application/json', - content_type='text/plain;charset=utf-8', - content_language='es', - accept_language='es').get_result() - - assert 'version=2016-10-20' in responses.calls[0].request.url - assert responses.calls[0].response.text == profile_response - assert len(responses.calls) == 1 - # Verify that response can be converted to a Profile - Profile._from_dict(response) +import ibm_watson.personality_insights_v3 +from ibm_watson.personality_insights_v3 import * + +base_url = 'https://gateway.watsonplatform.net/personality-insights/api' + +############################################################################## +# Start of Service: Methods +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for profile +#----------------------------------------------------------------------------- +class TestProfile(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_profile_response(self): + body = self.construct_full_body() + response = fake_response_Profile_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_profile_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Profile_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_profile_empty(self): + check_empty_required_params(self, fake_response_Profile_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/profile' + 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 = PersonalityInsightsV3( + authenticator=NoAuthAuthenticator(), + version='2017-10-13', + ) + service.set_service_url(base_url) + output = service.profile(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"content": {"mock": "data"}}) + body['accept'] = "string1" + body['content_type'] = "string1" + body['content_language'] = "string1" + body['accept_language'] = "string1" + body['raw_scores'] = True + body['csv_headers'] = True + body['consumption_preferences'] = True + return body + + def construct_required_body(self): + body = dict() + body.update({"content": {"mock": "data"}}) + body['accept'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Methods +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_Profile_json = """{"processed_language": "fake_processed_language", "word_count": 10, "word_count_message": "fake_word_count_message", "personality": [], "needs": [], "values": [], "behavior": [], "consumption_preferences": [], "warnings": []}""" From 3960fa2821217dbeb5e941bc3bdffe0b414bf923 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:35:20 -0500 Subject: [PATCH 180/455] refactor(ta): regenerate tone analyzer --- ibm_watson/tone_analyzer_v3.py | 346 ++++++++++++++++--------- test/unit/test_tone_analyzer_v3.py | 399 ++++++++++++++++++----------- 2 files changed, 482 insertions(+), 263 deletions(-) diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index c36c9523e..42287778f 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -26,11 +26,15 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator 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 read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from typing import Dict +from typing import List ############################################################################## # Service @@ -40,13 +44,15 @@ class ToneAnalyzerV3(BaseService): """The Tone Analyzer V3 service.""" - default_service_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/tone-analyzer/api' + DEFAULT_SERVICE_NAME = 'tone_analyzer' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Tone Analyzer service. @@ -65,38 +71,28 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('tone_analyzer') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('tone_analyzer') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Methods ######################### def tone(self, - tone_input, + tone_input: object, *, - content_type=None, - sentences=None, - tones=None, - content_language=None, - accept_language=None, - **kwargs): + content_type: str = None, + sentences: bool = None, + tones: List[str] = None, + content_language: str = None, + accept_language: str = None, + **kwargs) -> 'DetailedResponse': """ Analyze general tone. @@ -128,7 +124,7 @@ def tone(self, return an analysis of each individual sentence in addition to its analysis of the full document. If `true` (the default), the service returns results for each sentence. - :param list[str] tones: (optional) **`2017-09-21`:** Deprecated. The + :param List[str] tones: (optional) **`2017-09-21`:** Deprecated. The service continues to accept the parameter for backward-compatibility, but the parameter no longer affects the response. **`2016-05-19`:** A comma-separated list of tones for which the service is @@ -165,7 +161,9 @@ def tone(self, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('tone_analyzer', 'V3', 'tone') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='tone') headers.update(sdk_headers) params = { @@ -184,17 +182,17 @@ def tone(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def tone_chat(self, - utterances, + utterances: List['Utterance'], *, - content_language=None, - accept_language=None, - **kwargs): + content_language: str = None, + accept_language: str = None, + **kwargs) -> 'DetailedResponse': """ Analyze customer-engagement tone. @@ -211,7 +209,7 @@ def tone_chat(self, **See also:** [Using the customer-engagement endpoint](https://cloud.ibm.com/docs/services/tone-analyzer?topic=tone-analyzer-utco#utco). - :param list[Utterance] utterances: An array of `Utterance` objects that + :param List[Utterance] utterances: An array of `Utterance` objects that provides the input content that the service is to analyze. :param str content_language: (optional) The language of the input text for the request: English or French. Regional variants are treated as their @@ -240,7 +238,9 @@ def tone_chat(self, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('tone_analyzer', 'V3', 'tone_chat') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='tone_chat') headers.update(sdk_headers) params = {'version': self.version} @@ -252,8 +252,8 @@ def tone_chat(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -359,12 +359,12 @@ class DocumentAnalysis(): """ The results of the analysis for the full input content. - :attr list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + :attr List[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the document. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. - :attr list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not + :attr List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the full document of the input content. The service returns results only for the tones specified with the `tones` parameter @@ -375,16 +375,20 @@ class DocumentAnalysis(): 100 sentences for sentence-level analysis. **`2016-05-19`:** Not returned. """ - def __init__(self, *, tones=None, tone_categories=None, warning=None): + def __init__(self, + *, + tones: List['ToneScore'] = None, + tone_categories: List['ToneCategory'] = None, + warning: str = None) -> None: """ Initialize a DocumentAnalysis object. - :param list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + :param List[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the document. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. - :param list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not + :param List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the full document of the input content. The service returns results only for the tones specified @@ -400,7 +404,7 @@ def __init__(self, *, tones=None, tone_categories=None, warning=None): self.warning = warning @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DocumentAnalysis': """Initialize a DocumentAnalysis object from a json dictionary.""" args = {} valid_keys = ['tones', 'tone_categories', 'warning'] @@ -422,7 +426,12 @@ def _from_dict(cls, _dict): args['warning'] = _dict.get('warning') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAnalysis 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, 'tones') and self.tones is not None: @@ -436,17 +445,21 @@ def _to_dict(self): _dict['warning'] = self.warning return _dict - def __str__(self): + 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 DocumentAnalysis object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DocumentAnalysis') -> 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): + def __ne__(self, other: 'DocumentAnalysis') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -459,12 +472,12 @@ class SentenceAnalysis(): The first sentence has ID 0, and the ID of each subsequent sentence is incremented by one. :attr str text: The text of the input sentence. - :attr list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + :attr List[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the sentence. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. - :attr list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not + :attr List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the sentence. The service returns results only for the tones specified with the `tones` parameter of the request. @@ -476,13 +489,13 @@ class SentenceAnalysis(): """ def __init__(self, - sentence_id, - text, + sentence_id: int, + text: str, *, - tones=None, - tone_categories=None, - input_from=None, - input_to=None): + tones: List['ToneScore'] = None, + tone_categories: List['ToneCategory'] = None, + input_from: int = None, + input_to: int = None) -> None: """ Initialize a SentenceAnalysis object. @@ -490,12 +503,12 @@ def __init__(self, content. The first sentence has ID 0, and the ID of each subsequent sentence is incremented by one. :param str text: The text of the input sentence. - :param list[ToneScore] tones: (optional) **`2017-09-21`:** An array of + :param List[ToneScore] tones: (optional) **`2017-09-21`:** An array of `ToneScore` objects that provides the results of the analysis for each qualifying tone of the sentence. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. **`2016-05-19`:** Not returned. - :param list[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not + :param List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the results of the tone analysis for the sentence. The service returns results only for the tones specified with the `tones` parameter of @@ -515,7 +528,7 @@ def __init__(self, self.input_to = input_to @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SentenceAnalysis': """Initialize a SentenceAnalysis object from a json dictionary.""" args = {} valid_keys = [ @@ -554,7 +567,12 @@ def _from_dict(cls, _dict): args['input_to'] = _dict.get('input_to') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SentenceAnalysis 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, 'sentence_id') and self.sentence_id is not None: @@ -574,17 +592,21 @@ def _to_dict(self): _dict['input_to'] = self.input_to return _dict - def __str__(self): + 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 SentenceAnalysis object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SentenceAnalysis') -> 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): + def __ne__(self, other: 'SentenceAnalysis') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -595,20 +617,23 @@ class ToneAnalysis(): :attr DocumentAnalysis document_tone: The results of the analysis for the full input content. - :attr list[SentenceAnalysis] sentences_tone: (optional) An array of + :attr List[SentenceAnalysis] sentences_tone: (optional) An array of `SentenceAnalysis` objects that provides the results of the analysis for the individual sentences of the input content. The service returns results only for the first 100 sentences of the input. The field is omitted if the `sentences` parameter of the request is set to `false`. """ - def __init__(self, document_tone, *, sentences_tone=None): + def __init__(self, + document_tone: 'DocumentAnalysis', + *, + sentences_tone: List['SentenceAnalysis'] = None) -> None: """ Initialize a ToneAnalysis object. :param DocumentAnalysis document_tone: The results of the analysis for the full input content. - :param list[SentenceAnalysis] sentences_tone: (optional) An array of + :param List[SentenceAnalysis] sentences_tone: (optional) An array of `SentenceAnalysis` objects that provides the results of the analysis for the individual sentences of the input content. The service returns results only for the first 100 sentences of the input. The field is omitted if the @@ -618,7 +643,7 @@ def __init__(self, document_tone, *, sentences_tone=None): self.sentences_tone = sentences_tone @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ToneAnalysis': """Initialize a ToneAnalysis object from a json dictionary.""" args = {} valid_keys = ['document_tone', 'sentences_tone'] @@ -641,7 +666,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ToneAnalysis 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, 'document_tone') and self.document_tone is not None: @@ -652,17 +682,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 ToneAnalysis object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ToneAnalysis') -> 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): + def __ne__(self, other: 'ToneAnalysis') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -671,7 +705,7 @@ class ToneCategory(): """ The category for a tone from the input content. - :attr list[ToneScore] tones: An array of `ToneScore` objects that provides the + :attr List[ToneScore] tones: An array of `ToneScore` objects that provides the results for the tones of the category. :attr str category_id: The unique, non-localized identifier of the category for the results. The service can return results for the following category IDs: @@ -679,11 +713,12 @@ class ToneCategory(): :attr str category_name: The user-visible, localized name of the category. """ - def __init__(self, tones, category_id, category_name): + def __init__(self, tones: List['ToneScore'], category_id: str, + category_name: str) -> None: """ Initialize a ToneCategory object. - :param list[ToneScore] tones: An array of `ToneScore` objects that provides + :param List[ToneScore] tones: An array of `ToneScore` objects that provides the results for the tones of the category. :param str category_id: The unique, non-localized identifier of the category for the results. The service can return results for the following @@ -695,7 +730,7 @@ def __init__(self, tones, category_id, category_name): self.category_name = category_name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ToneCategory': """Initialize a ToneCategory object from a json dictionary.""" args = {} valid_keys = ['tones', 'category_id', 'category_name'] @@ -725,7 +760,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ToneCategory 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, 'tones') and self.tones is not None: @@ -736,17 +776,21 @@ def _to_dict(self): _dict['category_name'] = self.category_name return _dict - def __str__(self): + 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 ToneCategory object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ToneCategory') -> 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): + def __ne__(self, other: 'ToneCategory') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -764,7 +808,7 @@ class ToneChatScore(): :attr str tone_name: The user-visible, localized name of the tone. """ - def __init__(self, score, tone_id, tone_name): + def __init__(self, score: float, tone_id: str, tone_name: str) -> None: """ Initialize a ToneChatScore object. @@ -781,7 +825,7 @@ def __init__(self, score, tone_id, tone_name): self.tone_name = tone_name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ToneChatScore': """Initialize a ToneChatScore object from a json dictionary.""" args = {} valid_keys = ['score', 'tone_id', 'tone_name'] @@ -809,7 +853,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ToneChatScore 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, 'score') and self.score is not None: @@ -820,17 +869,21 @@ def _to_dict(self): _dict['tone_name'] = self.tone_name return _dict - def __str__(self): + 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 ToneChatScore object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ToneChatScore') -> 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): + def __ne__(self, other: 'ToneChatScore') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -855,7 +908,7 @@ class ToneInput(): :attr str text: The input content that the service is to analyze. """ - def __init__(self, text): + def __init__(self, text: str) -> None: """ Initialize a ToneInput object. @@ -864,7 +917,7 @@ def __init__(self, text): self.text = text @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ToneInput': """Initialize a ToneInput object from a json dictionary.""" args = {} valid_keys = ['text'] @@ -880,24 +933,33 @@ def _from_dict(cls, _dict): 'Required property \'text\' not present in ToneInput JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ToneInput 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, 'text') and self.text is not None: _dict['text'] = self.text return _dict - def __str__(self): + 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 ToneInput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ToneInput') -> 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): + def __ne__(self, other: 'ToneInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -929,7 +991,7 @@ class ToneScore(): :attr str tone_name: The user-visible, localized name of the tone. """ - def __init__(self, score, tone_id, tone_name): + def __init__(self, score: float, tone_id: str, tone_name: str) -> None: """ Initialize a ToneScore object. @@ -960,7 +1022,7 @@ def __init__(self, score, tone_id, tone_name): self.tone_name = tone_name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ToneScore': """Initialize a ToneScore object from a json dictionary.""" args = {} valid_keys = ['score', 'tone_id', 'tone_name'] @@ -986,7 +1048,12 @@ def _from_dict(cls, _dict): 'Required property \'tone_name\' not present in ToneScore JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ToneScore 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, 'score') and self.score is not None: @@ -997,17 +1064,21 @@ def _to_dict(self): _dict['tone_name'] = self.tone_name return _dict - def __str__(self): + 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 ToneScore object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ToneScore') -> 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): + def __ne__(self, other: 'ToneScore') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1022,7 +1093,7 @@ class Utterance(): utterance specified by the `text` parameter. """ - def __init__(self, text, *, user=None): + def __init__(self, text: str, *, user: str = None) -> None: """ Initialize a Utterance object. @@ -1035,7 +1106,7 @@ def __init__(self, text, *, user=None): self.user = user @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Utterance': """Initialize a Utterance object from a json dictionary.""" args = {} valid_keys = ['text', 'user'] @@ -1053,7 +1124,12 @@ def _from_dict(cls, _dict): args['user'] = _dict.get('user') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Utterance 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, 'text') and self.text is not None: @@ -1062,17 +1138,21 @@ def _to_dict(self): _dict['user'] = self.user return _dict - def __str__(self): + 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 Utterance object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Utterance') -> 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): + def __ne__(self, other: 'Utterance') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1081,18 +1161,21 @@ class UtteranceAnalyses(): """ The results of the analysis for the utterances of the input content. - :attr list[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` + :attr List[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` objects that provides the results for each utterance of the input. :attr str warning: (optional) **`2017-09-21`:** A warning message if the content contains more than 50 utterances. The service analyzes only the first 50 utterances. **`2016-05-19`:** Not returned. """ - def __init__(self, utterances_tone, *, warning=None): + def __init__(self, + utterances_tone: List['UtteranceAnalysis'], + *, + warning: str = None) -> None: """ Initialize a UtteranceAnalyses object. - :param list[UtteranceAnalysis] utterances_tone: An array of + :param List[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` objects that provides the results for each utterance of the input. :param str warning: (optional) **`2017-09-21`:** A warning message if the @@ -1103,7 +1186,7 @@ def __init__(self, utterances_tone, *, warning=None): self.warning = warning @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'UtteranceAnalyses': """Initialize a UtteranceAnalyses object from a json dictionary.""" args = {} valid_keys = ['utterances_tone', 'warning'] @@ -1125,7 +1208,12 @@ def _from_dict(cls, _dict): args['warning'] = _dict.get('warning') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a UtteranceAnalyses 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, @@ -1137,17 +1225,21 @@ def _to_dict(self): _dict['warning'] = self.warning return _dict - def __str__(self): + 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 UtteranceAnalyses object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'UtteranceAnalyses') -> 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): + def __ne__(self, other: 'UtteranceAnalyses') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1160,7 +1252,7 @@ class UtteranceAnalysis(): utterance has ID 0, and the ID of each subsequent utterance is incremented by one. :attr str utterance_text: The text of the utterance. - :attr list[ToneChatScore] tones: An array of `ToneChatScore` objects that + :attr List[ToneChatScore] tones: An array of `ToneChatScore` objects that provides results for the most prevalent tones of the utterance. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. @@ -1169,7 +1261,12 @@ class UtteranceAnalysis(): **`2016-05-19`:** Not returned. """ - def __init__(self, utterance_id, utterance_text, tones, *, error=None): + def __init__(self, + utterance_id: int, + utterance_text: str, + tones: List['ToneChatScore'], + *, + error: str = None) -> None: """ Initialize a UtteranceAnalysis object. @@ -1177,7 +1274,7 @@ def __init__(self, utterance_id, utterance_text, tones, *, error=None): utterance has ID 0, and the ID of each subsequent utterance is incremented by one. :param str utterance_text: The text of the utterance. - :param list[ToneChatScore] tones: An array of `ToneChatScore` objects that + :param List[ToneChatScore] tones: An array of `ToneChatScore` objects that provides results for the most prevalent tones of the utterance. The array includes results for any tone whose score is at least 0.5. The array is empty if no tone has a score that meets this threshold. @@ -1191,7 +1288,7 @@ def __init__(self, utterance_id, utterance_text, tones, *, error=None): self.error = error @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'UtteranceAnalysis': """Initialize a UtteranceAnalysis object from a json dictionary.""" args = {} valid_keys = ['utterance_id', 'utterance_text', 'tones', 'error'] @@ -1224,7 +1321,12 @@ def _from_dict(cls, _dict): args['error'] = _dict.get('error') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a UtteranceAnalysis 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, 'utterance_id') and self.utterance_id is not None: @@ -1237,16 +1339,20 @@ def _to_dict(self): _dict['error'] = self.error return _dict - def __str__(self): + 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 UtteranceAnalysis object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'UtteranceAnalysis') -> 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): + def __ne__(self, other: 'UtteranceAnalysis') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index 94e7af5e3..8ff7cb6c4 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -1,145 +1,258 @@ -# coding: utf-8 -import responses -import ibm_watson -from ibm_watson import ApiException -import os +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - - -@responses.activate -# Simple test, just calling tone() with some text -def test_tone(): - tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone' - tone_args = '?version=2016-05-19' - tone_response = None - with open(os.path.join(os.path.dirname(__file__), '../../resources/tone-v3-expect1.json')) as response_json: - tone_response = response_json.read() - - responses.add(responses.POST, tone_url, - body=tone_response, status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality.txt')) as tone_text: - tone_analyzer.tone(tone_text.read(), content_type='application/json') - - assert responses.calls[0].request.url == tone_url + tone_args - assert responses.calls[0].response.text == tone_response - - assert len(responses.calls) == 1 - - -@responses.activate -# Invoking tone() with some modifiers given in 'params': sentences skipped -def test_tone_with_args(): - tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone' - tone_args = {'version': '2016-05-19', 'sentences': 'false'} - tone_response = None - with open(os.path.join(os.path.dirname(__file__), '../../resources/tone-v3-expect1.json')) as response_json: - tone_response = response_json.read() - - responses.add(responses.POST, tone_url, - body=tone_response, status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality.txt')) as tone_text: - authenticator = BasicAuthenticator('username', 'password') - tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) - tone_analyzer.tone(tone_text.read(), content_type='application/json', sentences=False) - - assert responses.calls[0].request.url.split('?')[0] == tone_url - # Compare args. Order is not deterministic! - actualArgs = {} - for arg in responses.calls[0].request.url.split('?')[1].split('&'): - actualArgs[arg.split('=')[0]] = arg.split('=')[1] - assert actualArgs == tone_args - assert responses.calls[0].response.text == tone_response - assert len(responses.calls) == 1 - - -@responses.activate -# Invoking tone() with some modifiers specified as positional parameters: sentences is false -def test_tone_with_positional_args(): - tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone' - tone_args = {'version': '2016-05-19', 'sentences': 'false'} - tone_response = None - with open(os.path.join(os.path.dirname(__file__), '../../resources/tone-v3-expect1.json')) as response_json: - tone_response = response_json.read() - - responses.add(responses.POST, tone_url, - body=tone_response, status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/personality.txt')) as tone_text: - authenticator = BasicAuthenticator('username', 'password') - tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) - tone_analyzer.tone(tone_text.read(), content_type='application/json', sentences=False) - - assert responses.calls[0].request.url.split('?')[0] == tone_url - # Compare args. Order is not deterministic! - actualArgs = {} - for arg in responses.calls[0].request.url.split('?')[1].split('&'): - actualArgs[arg.split('=')[0]] = arg.split('=')[1] - assert actualArgs == tone_args - assert responses.calls[0].response.text == tone_response - assert len(responses.calls) == 1 - - -@responses.activate -# Invoking tone_chat() -def test_tone_chat(): - tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone_chat' - tone_args = '?version=2016-05-19' - tone_response = None - with open(os.path.join(os.path.dirname(__file__), '../../resources/tone-v3-expect2.json')) as response_json: - tone_response = response_json.read() - - responses.add(responses.POST, tone_url, - body=tone_response, status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) - utterances = [{'text': 'I am very happy', 'user': 'glenn'}] - tone_analyzer.tone_chat(utterances) - - assert responses.calls[0].request.url == tone_url + tone_args - assert responses.calls[0].response.text == tone_response - assert len(responses.calls) == 1 - - -######################### -# error response -######################### - - -@responses.activate -def test_error(): - tone_url = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone' - error_code = 400 - error_message = "Invalid JSON input at line 2, column 12" - tone_response = { - "code": error_code, - "sub_code": "C00012", - "error": error_message - } - responses.add(responses.POST, - tone_url, - body=json.dumps(tone_response), - status=error_code, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - tone_analyzer = ibm_watson.ToneAnalyzerV3('2016-05-19', authenticator=authenticator) - - text = 'Team, I know that times are tough!' - try: - tone_analyzer.tone(text, content_type='application/json') - except ApiException as ex: +import pytest +import responses +import ibm_watson.tone_analyzer_v3 +from ibm_watson.tone_analyzer_v3 import * + +base_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' + +############################################################################## +# Start of Service: Methods +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for tone +#----------------------------------------------------------------------------- +class TestTone(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_tone_response(self): + body = self.construct_full_body() + response = fake_response_ToneAnalysis_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_tone_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ToneAnalysis_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_tone_empty(self): + check_empty_required_params(self, fake_response_ToneAnalysis_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/tone' + 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 = ToneAnalyzerV3( + authenticator=NoAuthAuthenticator(), + version='2017-09-21', + ) + service.set_service_url(base_url) + output = service.tone(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"tone_input": {"mock": "data"}}) + body['content_type'] = "string1" + body['sentences'] = True + body['tones'] = [] + body['content_language'] = "string1" + body['accept_language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body.update({"tone_input": {"mock": "data"}}) + return body + + +#----------------------------------------------------------------------------- +# Test Class for tone_chat +#----------------------------------------------------------------------------- +class TestToneChat(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_tone_chat_response(self): + body = self.construct_full_body() + response = fake_response_UtteranceAnalyses_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_tone_chat_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_UtteranceAnalyses_json + send_request(self, body, response) assert len(responses.calls) == 1 - assert isinstance(ex, ApiException) - assert ex.code == error_code - assert ex.message == error_message + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_tone_chat_empty(self): + check_empty_required_params(self, fake_response_UtteranceAnalyses_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/tone_chat' + 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 = ToneAnalyzerV3( + authenticator=NoAuthAuthenticator(), + version='2017-09-21', + ) + service.set_service_url(base_url) + output = service.tone_chat(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "utterances": [], + }) + body['content_language'] = "string1" + body['accept_language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body.update({ + "utterances": [], + }) + return body + + +# endregion +############################################################################## +# End of Service: Methods +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_ToneAnalysis_json = """{"document_tone": {"tones": [], "tone_categories": [], "warning": "fake_warning"}, "sentences_tone": []}""" +fake_response_UtteranceAnalyses_json = """{"utterances_tone": [], "warning": "fake_warning"}""" From 8ba18c79e6c6825526876d57253750cd26e257a4 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:37:10 -0500 Subject: [PATCH 181/455] refactor(vr3): regenerate visual recognition v3 with tests --- ibm_watson/visual_recognition_v3.py | 467 ++++++++----- test/unit/test_visual_recognition_v3.py | 886 ++++++++++++++++++------ 2 files changed, 968 insertions(+), 385 deletions(-) diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index bfa038545..da69b5412 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -20,13 +20,20 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService 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 import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +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 +from typing import List +from typing import TextIO ############################################################################## # Service @@ -36,13 +43,15 @@ class VisualRecognitionV3(BaseService): """The Visual Recognition V3 service.""" - default_service_url = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_NAME = 'watson_vision_combined' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Visual Recognition service. @@ -61,25 +70,14 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('visual_recognition') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'visual_recognition') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # General @@ -87,25 +85,25 @@ def __init__( def classify(self, *, - images_file=None, - images_filename=None, - images_file_content_type=None, - url=None, - threshold=None, - owners=None, - classifier_ids=None, - accept_language=None, - **kwargs): + images_file: BinaryIO = None, + images_filename: str = None, + images_file_content_type: str = None, + url: str = None, + threshold: float = None, + owners: str = None, + classifier_ids: str = None, + accept_language: str = None, + **kwargs) -> 'DetailedResponse': """ Classify images. Classify images with built-in or custom classifiers. - :param file images_file: (optional) An image file (.gif, .jpg, .png, .tif) - or .zip file with images. Maximum image size is 10 MB. Include no more than - 20 images and limit the .zip file to 100 MB. Encode the image and .zip file - names in UTF-8 if they contain non-ASCII characters. The service assumes - UTF-8 encoding if it encounters non-ASCII characters. + :param TextIO images_file: (optional) An image file (.gif, .jpg, .png, + .tif) or .zip file with images. Maximum image size is 10 MB. Include no + more than 20 images and limit the .zip file to 100 MB. Encode the image and + .zip file names in UTF-8 if they contain non-ASCII characters. The service + assumes UTF-8 encoding if it encounters non-ASCII characters. You can also include an image with the **url** parameter. :param str images_filename: (optional) The filename for images_file. :param str images_file_content_type: (optional) The content type of @@ -118,7 +116,7 @@ def classify(self, :param float threshold: (optional) The minimum score a class must have to be displayed in the response. Set the threshold to `0.0` to return all identified classes. - :param list[str] owners: (optional) The categories of classifiers to apply. + :param List[str] owners: (optional) The categories of classifiers to apply. The **classifier_ids** parameter overrides **owners**, so make sure that **classifier_ids** is empty. - Use `IBM` to classify against the `default` general classifier. You get @@ -129,7 +127,7 @@ def classify(self, classifiers to apply. - Use both `IBM` and `me` to analyze the image against both classifier categories. - :param list[str] classifier_ids: (optional) Which classifiers to apply. + :param List[str] classifier_ids: (optional) Which classifiers to apply. Overrides the **owners** parameter. You can specify both custom and built-in classifier IDs. The built-in `default` classifier is used if both **classifier_ids** and **owners** parameters are empty. @@ -147,8 +145,9 @@ def classify(self, headers = {'Accept-Language': accept_language} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'classify') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='classify') headers.update(sdk_headers) params = {'version': self.version} @@ -163,24 +162,26 @@ def classify(self, images_file_content_type or 'application/octet-stream'))) if url: + url = str(url) form_data.append(('url', (None, url, 'text/plain'))) if threshold: - form_data.append( - ('threshold', (None, str(threshold), 'application/json'))) + threshold = str(threshold) + form_data.append(('threshold', (None, threshold, 'text/plain'))) if owners: - owners = self._convert_list(owners) - form_data.append(('owners', (None, owners, 'text/plain'))) + for item in owners: + form_data.append(('owners', (None, item, 'application/json'))) if classifier_ids: - classifier_ids = self._convert_list(classifier_ids) - form_data.append(('classifier_ids', (None, classifier_ids, 'text/plain'))) + for item in classifier_ids: + form_data.append( + ('classifier_ids', (None, item, 'application/json'))) url = '/v3/classify' request = self.prepare_request(method='POST', url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -189,12 +190,12 @@ def classify(self, ######################### def create_classifier(self, - name, - positive_examples, + name: str, + positive_examples: BinaryIO, *, - negative_examples=None, - negative_examples_filename=None, - **kwargs): + negative_examples: BinaryIO = None, + negative_examples_filename: str = None, + **kwargs) -> 'DetailedResponse': """ Create a classifier. @@ -219,14 +220,15 @@ def create_classifier(self, positive example file in a call. Specify the parameter name by appending `_positive_examples` to the class name. For example, `goldenretriever_positive_examples` creates the class - **goldenretriever**. + **goldenretriever**. The string cannot contain the following characters: + ``$ * - { } \ | / ' " ` [ ]``. Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 MB per .zip file. Encode special characters in the file name in UTF-8. - :param file negative_examples: (optional) A .zip file of images that do not - depict the visual subject of any of the classes of the new classifier. Must - contain a minimum of 10 images. + :param TextIO negative_examples: (optional) A .zip file of images that do + not depict the visual subject of any of the classes of the new classifier. + Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. :param str negative_examples_filename: (optional) The filename for negative_examples. @@ -243,21 +245,23 @@ def create_classifier(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'create_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='create_classifier') headers.update(sdk_headers) params = {'version': self.version} form_data = [] + name = str(name) form_data.append(('name', (None, name, 'text/plain'))) for key in positive_examples.keys(): part_name = '%s_positive_examples' % (key) value = positive_examples[key] if hasattr(value, 'name'): filename = basename(value.name) - form_data.append( - (part_name, (filename, value, 'application/octet-stream'))) + form_data.append( + (part_name, (filename, value, 'application/octet-stream'))) if negative_examples: if not negative_examples_filename and hasattr( negative_examples, 'name'): @@ -273,12 +277,13 @@ def create_classifier(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def list_classifiers(self, *, verbose=None, **kwargs): + def list_classifiers(self, *, verbose: bool = None, + **kwargs) -> 'DetailedResponse': """ Retrieve a list of classifiers. @@ -292,8 +297,9 @@ def list_classifiers(self, *, verbose=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'list_classifiers') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_classifiers') headers.update(sdk_headers) params = {'version': self.version, 'verbose': verbose} @@ -302,12 +308,13 @@ def list_classifiers(self, *, verbose=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_classifier(self, classifier_id, **kwargs): + def get_classifier(self, classifier_id: str, + **kwargs) -> 'DetailedResponse': """ Retrieve classifier details. @@ -325,8 +332,9 @@ def get_classifier(self, classifier_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'get_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_classifier') headers.update(sdk_headers) params = {'version': self.version} @@ -336,18 +344,18 @@ def get_classifier(self, classifier_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_classifier(self, - classifier_id, + classifier_id: str, *, - positive_examples={}, - negative_examples=None, - negative_examples_filename=None, - **kwargs): + positive_examples: BinaryIO = {}, + negative_examples: BinaryIO = None, + negative_examples_filename: str = None, + **kwargs) -> 'DetailedResponse': """ Update a classifier. @@ -376,14 +384,15 @@ def update_classifier(self, positive example file in a call. Specify the parameter name by appending `_positive_examples` to the class name. For example, `goldenretriever_positive_examples` creates the class - `goldenretriever`. + `goldenretriever`. The string cannot contain the following characters: ``$ + * - { } \ | / ' " ` [ ]``. Include at least 10 images in .jpg or .png format. The minimum recommended image resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 MB per .zip file. Encode special characters in the file name in UTF-8. - :param file negative_examples: (optional) A .zip file of images that do not - depict the visual subject of any of the classes of the new classifier. Must - contain a minimum of 10 images. + :param TextIO negative_examples: (optional) A .zip file of images that do + not depict the visual subject of any of the classes of the new classifier. + Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. :param str negative_examples_filename: (optional) The filename for negative_examples. @@ -398,8 +407,9 @@ def update_classifier(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'update_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='update_classifier') headers.update(sdk_headers) params = {'version': self.version} @@ -410,8 +420,8 @@ def update_classifier(self, value = positive_examples[key] if hasattr(value, 'name'): filename = basename(value.name) - form_data.append( - (part_name, (filename, value, 'application/octet-stream'))) + form_data.append( + (part_name, (filename, value, 'application/octet-stream'))) if negative_examples: if not negative_examples_filename and hasattr( negative_examples, 'name'): @@ -428,12 +438,13 @@ def update_classifier(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def delete_classifier(self, classifier_id, **kwargs): + def delete_classifier(self, classifier_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a classifier. @@ -449,8 +460,9 @@ def delete_classifier(self, classifier_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'delete_classifier') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='delete_classifier') headers.update(sdk_headers) params = {'version': self.version} @@ -460,8 +472,8 @@ def delete_classifier(self, classifier_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -469,7 +481,8 @@ def delete_classifier(self, classifier_id, **kwargs): # Core ML ######################### - def get_core_ml_model(self, classifier_id, **kwargs): + def get_core_ml_model(self, classifier_id: str, + **kwargs) -> 'DetailedResponse': """ Retrieve a Core ML model of a classifier. @@ -488,8 +501,9 @@ def get_core_ml_model(self, classifier_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'get_core_ml_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_core_ml_model') headers.update(sdk_headers) params = {'version': self.version} @@ -499,8 +513,8 @@ def get_core_ml_model(self, classifier_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -508,7 +522,8 @@ def get_core_ml_model(self, classifier_id, **kwargs): # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -532,8 +547,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V3', - 'delete_user_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='delete_user_data') headers.update(sdk_headers) params = {'version': self.version, 'customer_id': customer_id} @@ -542,8 +558,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -579,7 +595,7 @@ class Class(): :attr str class_: The name of the class. """ - def __init__(self, class_): + def __init__(self, class_: str) -> None: """ Initialize a Class object. @@ -588,7 +604,7 @@ def __init__(self, class_): self.class_ = class_ @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Class': """Initialize a Class object from a json dictionary.""" args = {} valid_keys = ['class_', 'class'] @@ -604,24 +620,33 @@ def _from_dict(cls, _dict): 'Required property \'class\' not present in Class JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Class 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, 'class_') and self.class_ is not None: _dict['class'] = self.class_ return _dict - def __str__(self): + 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 Class object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Class') -> 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): + def __ne__(self, other: 'Class') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -644,7 +669,8 @@ class ClassResult(): identified. """ - def __init__(self, class_, score, *, type_hierarchy=None): + def __init__(self, class_: str, score: float, *, + type_hierarchy: str = None) -> None: """ Initialize a ClassResult object. @@ -668,7 +694,7 @@ def __init__(self, class_, score, *, type_hierarchy=None): self.type_hierarchy = type_hierarchy @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassResult': """Initialize a ClassResult object from a json dictionary.""" args = {} valid_keys = ['class_', 'class', 'score', 'type_hierarchy'] @@ -691,7 +717,12 @@ def _from_dict(cls, _dict): args['type_hierarchy'] = _dict.get('type_hierarchy') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassResult 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, 'class_') and self.class_ is not None: @@ -702,17 +733,21 @@ def _to_dict(self): _dict['type_hierarchy'] = self.type_hierarchy return _dict - def __str__(self): + 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 ClassResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassResult') -> 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): + def __ne__(self, other: 'ClassResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -730,20 +765,20 @@ class ClassifiedImage(): :attr ErrorInfo error: (optional) Information about what might have caused a failure, such as an image that is too large. Not returned when there is no error. - :attr list[ClassifierResult] classifiers: The classifiers. + :attr List[ClassifierResult] classifiers: The classifiers. """ def __init__(self, - classifiers, + classifiers: List['ClassifierResult'], *, - source_url=None, - resolved_url=None, - image=None, - error=None): + source_url: str = None, + resolved_url: str = None, + image: str = None, + error: 'ErrorInfo' = None) -> None: """ Initialize a ClassifiedImage object. - :param list[ClassifierResult] classifiers: The classifiers. + :param List[ClassifierResult] classifiers: The classifiers. :param str source_url: (optional) Source of the image before any redirects. Not returned when the image is uploaded. :param str resolved_url: (optional) Fully resolved URL of the image after @@ -761,7 +796,7 @@ def __init__(self, self.classifiers = classifiers @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifiedImage': """Initialize a ClassifiedImage object from a json dictionary.""" args = {} valid_keys = [ @@ -791,7 +826,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifiedImage 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, 'source_url') and self.source_url is not None: @@ -806,17 +846,21 @@ def _to_dict(self): _dict['classifiers'] = [x._to_dict() for x in self.classifiers] return _dict - def __str__(self): + 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 ClassifiedImage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifiedImage') -> 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): + def __ne__(self, other: 'ClassifiedImage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -829,28 +873,28 @@ class ClassifiedImages(): images. :attr int images_processed: (optional) Number of images processed for the API call. - :attr list[ClassifiedImage] images: Classified images. - :attr list[WarningInfo] warnings: (optional) Information about what might cause + :attr List[ClassifiedImage] images: Classified images. + :attr List[WarningInfo] warnings: (optional) Information about what might cause less than optimal output. For example, a request sent with a corrupt .zip file and a list of image URLs will still complete, but does not return the expected output. Not returned when there is no warning. """ def __init__(self, - images, + images: List['ClassifiedImage'], *, - custom_classes=None, - images_processed=None, - warnings=None): + custom_classes: int = None, + images_processed: int = None, + warnings: List['WarningInfo'] = None) -> None: """ Initialize a ClassifiedImages object. - :param list[ClassifiedImage] images: Classified images. + :param List[ClassifiedImage] images: Classified images. :param int custom_classes: (optional) Number of custom classes identified in the images. :param int images_processed: (optional) Number of images processed for the API call. - :param list[WarningInfo] warnings: (optional) Information about what might + :param List[WarningInfo] warnings: (optional) Information about what might cause less than optimal output. For example, a request sent with a corrupt .zip file and a list of image URLs will still complete, but does not return the expected output. Not returned when there is no warning. @@ -861,7 +905,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifiedImages': """Initialize a ClassifiedImages object from a json dictionary.""" args = {} valid_keys = [ @@ -890,7 +934,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifiedImages 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, 'custom_classes') and self.custom_classes is not None: @@ -904,17 +953,21 @@ def _to_dict(self): _dict['warnings'] = [x._to_dict() for x in self.warnings] return _dict - def __str__(self): + 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 ClassifiedImages object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifiedImages') -> 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): + def __ne__(self, other: 'ClassifiedImages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -934,7 +987,7 @@ class Classifier(): might explain why. :attr datetime created: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was created. - :attr list[Class] classes: (optional) Classes that define a classifier. + :attr List[Class] classes: (optional) Classes that define a classifier. :attr datetime retrained: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was updated. Might not be returned by some requests. Identical to `updated` and retained for backward compatibility. @@ -944,17 +997,17 @@ class Classifier(): """ def __init__(self, - classifier_id, - name, + classifier_id: str, + name: str, *, - owner=None, - status=None, - core_ml_enabled=None, - explanation=None, - created=None, - classes=None, - retrained=None, - updated=None): + owner: str = None, + status: str = None, + core_ml_enabled: bool = None, + explanation: str = None, + created: datetime = None, + classes: List['Class'] = None, + retrained: datetime = None, + updated: datetime = None) -> None: """ Initialize a Classifier object. @@ -969,7 +1022,7 @@ def __init__(self, field might explain why. :param datetime created: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was created. - :param list[Class] classes: (optional) Classes that define a classifier. + :param List[Class] classes: (optional) Classes that define a classifier. :param datetime retrained: (optional) Date and time in Coordinated Universal Time (UTC) that the classifier was updated. Might not be returned by some requests. Identical to `updated` and retained for backward @@ -990,7 +1043,7 @@ def __init__(self, self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Classifier': """Initialize a Classifier object from a json dictionary.""" args = {} valid_keys = [ @@ -1033,7 +1086,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Classifier 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, 'classifier_id') and self.classifier_id is not None: @@ -1059,17 +1117,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 Classifier object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Classifier') -> 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): + def __ne__(self, other: 'Classifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1089,23 +1151,24 @@ class ClassifierResult(): :attr str name: Name of the classifier. :attr str classifier_id: ID of a classifier identified in the image. - :attr list[ClassResult] classes: Classes within the classifier. + :attr List[ClassResult] classes: Classes within the classifier. """ - def __init__(self, name, classifier_id, classes): + def __init__(self, name: str, classifier_id: str, + classes: List['ClassResult']) -> None: """ Initialize a ClassifierResult object. :param str name: Name of the classifier. :param str classifier_id: ID of a classifier identified in the image. - :param list[ClassResult] classes: Classes within the classifier. + :param List[ClassResult] classes: Classes within the classifier. """ self.name = name self.classifier_id = classifier_id self.classes = classes @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ClassifierResult': """Initialize a ClassifierResult object from a json dictionary.""" args = {} valid_keys = ['name', 'classifier_id', 'classes'] @@ -1136,7 +1199,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifierResult 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, 'name') and self.name is not None: @@ -1147,17 +1215,21 @@ def _to_dict(self): _dict['classes'] = [x._to_dict() for x in self.classes] return _dict - def __str__(self): + 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 ClassifierResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ClassifierResult') -> 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): + def __ne__(self, other: 'ClassifierResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1166,19 +1238,19 @@ class Classifiers(): """ A container for the list of classifiers. - :attr list[Classifier] classifiers: List of classifiers. + :attr List[Classifier] classifiers: List of classifiers. """ - def __init__(self, classifiers): + def __init__(self, classifiers: List['Classifier']) -> None: """ Initialize a Classifiers object. - :param list[Classifier] classifiers: List of classifiers. + :param List[Classifier] classifiers: List of classifiers. """ self.classifiers = classifiers @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Classifiers': """Initialize a Classifiers object from a json dictionary.""" args = {} valid_keys = ['classifiers'] @@ -1197,24 +1269,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Classifiers 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, 'classifiers') and self.classifiers is not None: _dict['classifiers'] = [x._to_dict() for x in self.classifiers] return _dict - def __str__(self): + 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 Classifiers object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Classifiers') -> 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): + def __ne__(self, other: 'Classifiers') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1230,7 +1311,7 @@ class ErrorInfo(): :attr str error_id: Codified error string. For example, `limit_exceeded`. """ - def __init__(self, code, description, error_id): + def __init__(self, code: int, description: str, error_id: str) -> None: """ Initialize a ErrorInfo object. @@ -1244,7 +1325,7 @@ def __init__(self, code, description, error_id): self.error_id = error_id @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ErrorInfo': """Initialize a ErrorInfo object from a json dictionary.""" args = {} valid_keys = ['code', 'description', 'error_id'] @@ -1271,7 +1352,12 @@ def _from_dict(cls, _dict): 'Required property \'error_id\' not present in ErrorInfo JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ErrorInfo 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, 'code') and self.code is not None: @@ -1282,17 +1368,21 @@ def _to_dict(self): _dict['error_id'] = self.error_id return _dict - def __str__(self): + 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 ErrorInfo object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ErrorInfo') -> 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): + def __ne__(self, other: 'ErrorInfo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1305,7 +1395,7 @@ class WarningInfo(): :attr str description: Information about the error. """ - def __init__(self, warning_id, description): + def __init__(self, warning_id: str, description: str) -> None: """ Initialize a WarningInfo object. @@ -1316,7 +1406,7 @@ def __init__(self, warning_id, description): self.description = description @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WarningInfo': """Initialize a WarningInfo object from a json dictionary.""" args = {} valid_keys = ['warning_id', 'description'] @@ -1339,7 +1429,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WarningInfo 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, 'warning_id') and self.warning_id is not None: @@ -1348,16 +1443,20 @@ def _to_dict(self): _dict['description'] = self.description return _dict - def __str__(self): + 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 WarningInfo object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WarningInfo') -> 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): + def __ne__(self, other: 'WarningInfo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index d1e879ef5..9aecb805e 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -1,233 +1,717 @@ -# coding: utf-8 -import responses -import ibm_watson +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from datetime import datetime +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -import os -import jwt -import time - -from unittest import TestCase -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -base_url = "https://gateway.watsonplatform.net/visual-recognition/api/" - -def get_access_token(): - access_token_layout = { - "username": "dummy", - "role": "Admin", - "permissions": [ - "administrator", - "manage_catalog" - ], - "sub": "admin", - "iss": "sss", - "aud": "sss", - "uid": "sss", - "iat": 3600, - "exp": int(time.time()) - } - - access_token = jwt.encode(access_token_layout, 'secret', algorithm='HS256', headers={'kid': '230498151c214b788dd97f22b85410a5'}) - return access_token.decode('utf-8') - -class TestVisualRecognitionV3(TestCase): - @classmethod - def setUp(cls): - iam_url = "https://iam.cloud.ibm.com/identity/token" - iam_token_response = { - "access_token": get_access_token(), - "token_type": "Bearer", - "expires_in": 3600, - "expiration": 1524167011, - "refresh_token": "jy4gl91BQ" - } - responses.add(responses.POST, url=iam_url, body=json.dumps(iam_token_response), status=200) - - @responses.activate - def test_get_classifier(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - gc_url = "{0}{1}".format(base_url, 'v3/classifiers/bogusnumber') - - response = { - "classifier_id": "bogusnumber", - "name": "Dog Breeds", - "owner": "58b61352-678c-44d1-9f40-40edf4ea8d19", - "status": "failed", - "created": "2017-08-25T06:39:01.968Z", - "classes": [{"class": "goldenretriever"}] - } - - responses.add(responses.GET, - gc_url, - body=json.dumps(response), - status=200, - content_type='application/json') - vr_service.get_classifier(classifier_id='bogusnumber') - - assert len(responses.calls) == 2 +import pytest +import responses +import tempfile +import ibm_watson.visual_recognition_v3 +from ibm_watson.visual_recognition_v3 import * - @responses.activate - def test_delete_classifier(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) +base_url = 'https://gateway.watsonplatform.net/visual-recognition/api' - gc_url = "{0}{1}".format(base_url, 'v3/classifiers/bogusnumber') +############################################################################## +# Start of Service: General +############################################################################## +# region - responses.add(responses.DELETE, - gc_url, - body=json.dumps({'response': 200}), - status=200, - content_type='application/json') - vr_service.delete_classifier(classifier_id='bogusnumber') - assert len(responses.calls) == 2 +#----------------------------------------------------------------------------- +# Test Class for classify +#----------------------------------------------------------------------------- +class TestClassify(): + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_list_classifiers(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - - gc_url = "{0}{1}".format(base_url, 'v3/classifiers') - - response = {"classifiers": [ - { - "classifier_id": "InsuranceClaims_1362331461", - "name": "Insurance Claims", - "status": "ready" - }, - { - "classifier_id": "DogBreeds_1539707331", - "name": "Dog Breeds", - "status": "ready" - } - ]} - - responses.add(responses.GET, - gc_url, + def test_classify_response(self): + body = self.construct_full_body() + response = fake_response_ClassifiedImages_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_classify_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ClassifiedImages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_classify_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classify' + 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') - vr_service.list_classifiers() - - assert len(responses.calls) == 2 + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.classify(**body) + return output + + def construct_full_body(self): + body = dict() + body['images_file'] = tempfile.NamedTemporaryFile() + body['images_filename'] = "string1" + body['images_file_content_type'] = "string1" + body['url'] = "string1" + body['threshold'] = 12345.0 + body['owners'] = [] + body['classifier_ids'] = [] + body['accept_language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +# endregion +############################################################################## +# End of Service: General +############################################################################## + +############################################################################## +# Start of Service: Custom +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for create_classifier +#----------------------------------------------------------------------------- +class TestCreateClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_create_classifier(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - - gc_url = "{0}{1}".format(base_url, 'v3/classifiers') - - response = { - "classifier_id": "DogBreeds_2014254824", - "name": "Dog Breeds", - "owner": "58b61352-678c-44d1-9f40-40edf4ea8d19", - "status": "failed", - "created": "2017-08-25T06:39:01.968Z", - "classes": [{"class": "goldenretriever"}] - } - + def test_create_classifier_response(self): + body = self.construct_full_body() + response = fake_response_Classifier_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_create_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_classifier_empty(self): + check_empty_required_params(self, fake_response_Classifier_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classifiers' + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - gc_url, + url, body=json.dumps(response), status=200, content_type='application/json') - with open(os.path.join(os.path.dirname(__file__), '../../resources/cars.zip'), 'rb') as cars, \ - open(os.path.join(os.path.dirname(__file__), '../../resources/trucks.zip'), 'rb') as trucks: - vr_service.create_classifier('Cars vs Trucks', positive_examples={'cars': cars}, negative_examples=trucks) - - assert len(responses.calls) == 2 - + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.create_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['name'] = "string1" + body['positive_examples'] = {"mock": "data"} + body['negative_examples'] = tempfile.NamedTemporaryFile() + body['negative_examples_filename'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['name'] = "string1" + body['positive_examples'] = {"mock": "data"} + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_classifiers +#----------------------------------------------------------------------------- +class TestListClassifiers(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_update_classifier(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - - gc_url = "{0}{1}".format(base_url, 'v3/classifiers/bogusid') - - response = { - "classifier_id": "bogusid", - "name": "Insurance Claims", - "owner": "58b61352-678c-44d1-9f40-40edf4ea8d19", - "status": "ready", - "created": "2017-07-17T22:17:14.860Z", - "classes": [ - {"class": "motorcycleaccident"}, - {"class": "flattire"}, - {"class": "brokenwinshield"} - ] - } - - responses.add(responses.POST, - gc_url, + def test_list_classifiers_response(self): + body = self.construct_full_body() + response = fake_response_Classifiers_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_classifiers_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifiers_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_classifiers_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classifiers' + 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') - vr_service.update_classifier(classifier_id="bogusid") - assert len(responses.calls) == 2 - - @responses.activate - def test_classify(self): - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - - gc_url = "{0}{1}".format(base_url, 'v3/classify') - - response = {"images": [ - {"image": "test.jpg", - "classifiers": [ - {"classes": [ - {"score": 0.95, "class": "tiger", "type_hierarchy": "/animal/mammal/carnivore/feline/big cat/tiger"}, - {"score": 0.997, "class": "big cat"}, - {"score": 0.998, "class": "feline"}, - {"score": 0.998, "class": "carnivore"}, - {"score": 0.998, "class": "mammal"}, - {"score": 0.999, "class": "animal"} - ], - "classifier_id": "default", - "name": "default"} - ] - } - ], - "custom_classes": 0, - "images_processed": 1 - } - + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.list_classifiers(**body) + return output + + def construct_full_body(self): + body = dict() + body['verbose'] = True + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_classifier +#----------------------------------------------------------------------------- +class TestGetClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_classifier_response(self): + body = self.construct_full_body() + response = fake_response_Classifier_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_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_classifier_empty(self): + check_empty_required_params(self, fake_response_Classifier_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classifiers/{0}'.format(body['classifier_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.GET, - gc_url, + url, body=json.dumps(response), status=200, content_type='application/json') + + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.get_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_classifier +#----------------------------------------------------------------------------- +class TestUpdateClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_classifier_response(self): + body = self.construct_full_body() + response = fake_response_Classifier_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_classifier_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Classifier_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_classifier_empty(self): + check_empty_required_params(self, fake_response_Classifier_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classifiers/{0}'.format(body['classifier_id']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): responses.add(responses.POST, - gc_url, + url, body=json.dumps(response), status=200, content_type='application/json') - vr_service.classify(parameters='{"url": "http://google.com"}') - - vr_service.classify(parameters=json.dumps({'url': 'http://google.com', 'classifier_ids': ['one', 'two', 'three']})) - vr_service.classify(parameters=json.dumps({'url': 'http://google.com', 'owners': ['me', 'IBM']})) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/test.jpg'), 'rb') as image_file: - vr_service.classify(images_file=image_file) - assert len(responses.calls) == 8 - + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.update_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + body['positive_examples'] = {"mock": "data"} + body['negative_examples'] = tempfile.NamedTemporaryFile() + body['negative_examples_filename'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_classifier +#----------------------------------------------------------------------------- +class TestDeleteClassifier(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- @responses.activate - def test_delete_user_data(self): - url = "{0}{1}".format(base_url, 'v3/user_data') - responses.add( - responses.DELETE, - url, - body='{"description": "success" }', - status=204, - content_type='application_json') - - authenticator = IAMAuthenticator('bogusapikey') - vr_service = ibm_watson.VisualRecognitionV3('2016-10-20', authenticator=authenticator) - response = vr_service.delete_user_data('id').get_result() - assert response is None - assert len(responses.calls) == 2 + def test_delete_classifier_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_classifier_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_classifier_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 = '/v3/classifiers/{0}'.format(body['classifier_id']) + 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 = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.delete_classifier(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Custom +############################################################################## + +############################################################################## +# Start of Service: CoreML +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for get_core_ml_model +#----------------------------------------------------------------------------- +class TestGetCoreMlModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_core_ml_model_response(self): + body = self.construct_full_body() + response = fake_response_BinaryIO_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_core_ml_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BinaryIO_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_core_ml_model_empty(self): + check_empty_required_params(self, fake_response_BinaryIO_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/classifiers/{0}/core_ml_model'.format( + body['classifier_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='') + + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.get_core_ml_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['classifier_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CoreML +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_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_user_data_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_user_data_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 = '/v3/user_data' + 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=202, + content_type='') + + def call_service(self, body): + service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version='2018-03-19', + ) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_ClassifiedImages_json = """{"custom_classes": 14, "images_processed": 16, "images": [], "warnings": []}""" +fake_response_Classifier_json = """{"classifier_id": "fake_classifier_id", "name": "fake_name", "owner": "fake_owner", "status": "fake_status", "core_ml_enabled": false, "explanation": "fake_explanation", "created": "2017-05-16T13:56:54.957Z", "classes": [], "retrained": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Classifiers_json = """{"classifiers": []}""" +fake_response_Classifier_json = """{"classifier_id": "fake_classifier_id", "name": "fake_name", "owner": "fake_owner", "status": "fake_status", "core_ml_enabled": false, "explanation": "fake_explanation", "created": "2017-05-16T13:56:54.957Z", "classes": [], "retrained": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_Classifier_json = """{"classifier_id": "fake_classifier_id", "name": "fake_name", "owner": "fake_owner", "status": "fake_status", "core_ml_enabled": false, "explanation": "fake_explanation", "created": "2017-05-16T13:56:54.957Z", "classes": [], "retrained": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_BinaryIO_json = """Contents of response byte-stream...""" From 652bf7e17f7c773d35f7f66191779c5916202037 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:40:32 -0500 Subject: [PATCH 182/455] chore(vr3): manual changes to vr3 --- ibm_watson/visual_recognition_v3.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index da69b5412..6d0986b7b 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -168,12 +168,11 @@ def classify(self, threshold = str(threshold) form_data.append(('threshold', (None, threshold, 'text/plain'))) if owners: - for item in owners: - form_data.append(('owners', (None, item, 'application/json'))) + owners = self._convert_list(owners) + form_data.append(('owners', (None, owners, 'text/plain'))) if classifier_ids: - for item in classifier_ids: - form_data.append( - ('classifier_ids', (None, item, 'application/json'))) + classifier_ids = self._convert_list(classifier_ids) + form_data.append(('classifier_ids', (None, classifier_ids, 'text/plain'))) url = '/v3/classify' request = self.prepare_request(method='POST', From 511c50919024bbebdcad8dc1410e1f6abe1b9f54 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:41:10 -0500 Subject: [PATCH 183/455] refacor(vr4): regenerate visual recognition v4 with tests --- ibm_watson/visual_recognition_v4.py | 910 ++++++++++++++++-------- test/unit/test_visual_recognition_v4.py | 109 ++- 2 files changed, 667 insertions(+), 352 deletions(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 7ccad5166..05eb8fd1e 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,12 +19,20 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService 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 import read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +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 +from typing import List +from typing import TextIO ############################################################################## # Service @@ -34,13 +42,15 @@ class VisualRecognitionV4(BaseService): """The Visual Recognition V4 service.""" - default_service_url = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_NAME = 'watson_vision_combined' def __init__( self, - version, - authenticator=None, - ): + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Visual Recognition service. @@ -59,38 +69,27 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('visual_recognition') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment( - 'visual_recognition') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) self.version = version + self.configure_service(service_name) ######################### # Analysis ######################### def analyze(self, - collection_ids, - features, + collection_ids: str, + features: str, *, - images_file=None, - image_url=None, - threshold=None, - **kwargs): + images_file: BinaryIO = None, + image_url: str = None, + threshold: float = None, + **kwargs) -> 'DetailedResponse': """ Analyze images. @@ -101,15 +100,15 @@ def analyze(self, characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. - :param list[str] collection_ids: The IDs of the collections to analyze. - :param list[str] features: The features to analyze. + :param List[str] collection_ids: The IDs of the collections to analyze. + :param List[str] features: The features to analyze. :param list[FileWithMetadata] images_file: (optional) An array of image files (.jpg or .png) or .zip files with images. - Include a maximum of 20 images in a request. - Limit the .zip file to 100 MB. - Limit each image file to 10 MB. You can also include an image with the **image_url** parameter. - :param list[str] image_url: (optional) An array of URLs of image files + :param List[str] image_url: (optional) An array of URLs of image files (.jpg or .png). - Include a maximum of 20 images in a request. - Limit each image file to 10 MB. @@ -132,18 +131,19 @@ def analyze(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', 'analyze') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='analyze') headers.update(sdk_headers) params = {'version': self.version} form_data = [] - if collection_ids: - collection_ids = self._convert_list(collection_ids) - form_data.append(('collection_ids', (None, collection_ids, 'text/plain'))) - if features: - features = self._convert_list(features) - form_data.append(('features', (None, features, 'text/plain'))) + for item in collection_ids: + form_data.append( + ('collection_ids', (None, item, 'application/json'))) + for item in features: + form_data.append(('features', (None, item, 'application/json'))) if images_file: for item in images_file: form_data.append(('images_file', (item.filename, item.data, @@ -151,18 +151,19 @@ def analyze(self, 'application/octet-stream'))) if image_url: for item in image_url: - form_data.append(('image_url', (None, item, 'text/plain'))) + form_data.append( + ('image_url', (None, item, 'application/json'))) if threshold: - form_data.append( - ('threshold', (None, str(threshold), 'application/json'))) + threshold = str(threshold) + form_data.append(('threshold', (None, threshold, 'text/plain'))) url = '/v4/analyze' request = self.prepare_request(method='POST', url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response @@ -170,7 +171,11 @@ def analyze(self, # Collections ######################### - def create_collection(self, *, name=None, description=None, **kwargs): + def create_collection(self, + *, + name: str = None, + description: str = None, + **kwargs) -> 'DetailedResponse': """ Create a collection. @@ -192,8 +197,9 @@ def create_collection(self, *, name=None, description=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'create_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='create_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -205,12 +211,12 @@ def create_collection(self, *, name=None, description=None, **kwargs): url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_collections(self, **kwargs): + def list_collections(self, **kwargs) -> 'DetailedResponse': """ List collections. @@ -224,8 +230,9 @@ def list_collections(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'list_collections') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='list_collections') headers.update(sdk_headers) params = {'version': self.version} @@ -234,12 +241,13 @@ def list_collections(self, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_collection(self, collection_id, **kwargs): + def get_collection(self, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Get collection details. @@ -257,8 +265,9 @@ def get_collection(self, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'get_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='get_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -268,17 +277,17 @@ def get_collection(self, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_collection(self, - collection_id, + collection_id: str, *, - name=None, - description=None, - **kwargs): + name: str = None, + description: str = None, + **kwargs) -> 'DetailedResponse': """ Update a collection. @@ -302,8 +311,9 @@ def update_collection(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'update_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='update_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -316,12 +326,13 @@ def update_collection(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def delete_collection(self, collection_id, **kwargs): + def delete_collection(self, collection_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a collection. @@ -339,8 +350,9 @@ def delete_collection(self, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'delete_collection') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='delete_collection') headers.update(sdk_headers) params = {'version': self.version} @@ -350,8 +362,8 @@ def delete_collection(self, collection_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -360,12 +372,12 @@ def delete_collection(self, collection_id, **kwargs): ######################### def add_images(self, - collection_id, + collection_id: str, *, - images_file=None, - image_url=None, - training_data=None, - **kwargs): + images_file: BinaryIO = None, + image_url: str = None, + training_data: str = None, + **kwargs) -> 'DetailedResponse': """ Add images. @@ -381,7 +393,7 @@ def add_images(self, - Limit the .zip file to 100 MB. - Limit each image file to 10 MB. You can also include an image with the **image_url** parameter. - :param list[str] image_url: (optional) The array of URLs of image files + :param List[str] image_url: (optional) The array of URLs of image files (.jpg or .png). - Include a maximum of 20 images in a request. - Limit each image file to 10 MB. @@ -405,8 +417,9 @@ def add_images(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'add_images') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='add_images') headers.update(sdk_headers) params = {'version': self.version} @@ -419,8 +432,10 @@ def add_images(self, 'application/octet-stream'))) if image_url: for item in image_url: - form_data.append(('image_url', (None, item, 'text/plain'))) + form_data.append( + ('image_url', (None, item, 'application/json'))) if training_data: + training_data = str(training_data) form_data.append( ('training_data', (None, training_data, 'text/plain'))) @@ -430,12 +445,12 @@ def add_images(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def list_images(self, collection_id, **kwargs): + def list_images(self, collection_id: str, **kwargs) -> 'DetailedResponse': """ List images. @@ -453,8 +468,9 @@ def list_images(self, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'list_images') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='list_images') headers.update(sdk_headers) params = {'version': self.version} @@ -464,12 +480,13 @@ def list_images(self, collection_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_image_details(self, collection_id, image_id, **kwargs): + def get_image_details(self, collection_id: str, image_id: str, + **kwargs) -> 'DetailedResponse': """ Get image details. @@ -490,8 +507,9 @@ def get_image_details(self, collection_id, image_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'get_image_details') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='get_image_details') headers.update(sdk_headers) params = {'version': self.version} @@ -501,12 +519,13 @@ def get_image_details(self, collection_id, image_id, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def delete_image(self, collection_id, image_id, **kwargs): + def delete_image(self, collection_id: str, image_id: str, + **kwargs) -> 'DetailedResponse': """ Delete an image. @@ -527,8 +546,9 @@ def delete_image(self, collection_id, image_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'delete_image') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='delete_image') headers.update(sdk_headers) params = {'version': self.version} @@ -538,12 +558,17 @@ def delete_image(self, collection_id, image_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_jpeg_image(self, collection_id, image_id, *, size=None, **kwargs): + def get_jpeg_image(self, + collection_id: str, + image_id: str, + *, + size: str = None, + **kwargs) -> 'DetailedResponse': """ Get a JPEG file of an image. @@ -568,8 +593,9 @@ def get_jpeg_image(self, collection_id, image_id, *, size=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'get_jpeg_image') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='get_jpeg_image') headers.update(sdk_headers) params = {'version': self.version, 'size': size} @@ -579,8 +605,8 @@ def get_jpeg_image(self, collection_id, image_id, *, size=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -588,7 +614,7 @@ def get_jpeg_image(self, collection_id, image_id, *, size=None, **kwargs): # Training ######################### - def train(self, collection_id, **kwargs): + def train(self, collection_id: str, **kwargs) -> 'DetailedResponse': """ Train a collection. @@ -608,7 +634,9 @@ def train(self, collection_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', 'train') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='train') headers.update(sdk_headers) params = {'version': self.version} @@ -618,17 +646,17 @@ def train(self, collection_id, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def add_image_training_data(self, - collection_id, - image_id, + collection_id: str, + image_id: str, *, - objects=None, - **kwargs): + objects: List['TrainingDataObject'] = None, + **kwargs) -> 'DetailedResponse': """ Add training data to an image. @@ -642,7 +670,7 @@ def add_image_training_data(self, :param str collection_id: The identifier of the collection. :param str image_id: The identifier of the image. - :param list[TrainingDataObject] objects: (optional) Training data for + :param List[TrainingDataObject] objects: (optional) Training data for specific objects. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -659,8 +687,9 @@ def add_image_training_data(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'add_image_training_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='add_image_training_data') headers.update(sdk_headers) params = {'version': self.version} @@ -673,12 +702,16 @@ def add_image_training_data(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_training_usage(self, *, start_time=None, end_time=None, **kwargs): + def get_training_usage(self, + *, + start_time: str = None, + end_time: str = None, + **kwargs) -> 'DetailedResponse': """ Get training usage. @@ -700,8 +733,9 @@ def get_training_usage(self, *, start_time=None, end_time=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'get_training_usage') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='get_training_usage') headers.update(sdk_headers) params = { @@ -714,8 +748,8 @@ def get_training_usage(self, *, start_time=None, end_time=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -723,7 +757,8 @@ def get_training_usage(self, *, start_time=None, end_time=None, **kwargs): # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -747,8 +782,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('watson_vision_combined', 'V4', - 'delete_user_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V4', + operation_id='delete_user_data') headers.update(sdk_headers) params = {'version': self.version, 'customer_id': customer_id} @@ -757,8 +793,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -793,19 +829,23 @@ class AnalyzeResponse(): """ Results for all images. - :attr list[Image] images: Analyzed images. - :attr list[Warning] warnings: (optional) Information about what might cause less + :attr List[Image] images: Analyzed images. + :attr List[Warning] warnings: (optional) Information about what might cause less than optimal output. :attr str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. """ - def __init__(self, images, *, warnings=None, trace=None): + def __init__(self, + images: List['Image'], + *, + warnings: List['Warning'] = None, + trace: str = None) -> None: """ Initialize a AnalyzeResponse object. - :param list[Image] images: Analyzed images. - :param list[Warning] warnings: (optional) Information about what might + :param List[Image] images: Analyzed images. + :param List[Warning] warnings: (optional) Information about what might cause less than optimal output. :param str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. @@ -815,7 +855,7 @@ def __init__(self, images, *, warnings=None, trace=None): self.trace = trace @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AnalyzeResponse': """Initialize a AnalyzeResponse object from a json dictionary.""" args = {} valid_keys = ['images', 'warnings', 'trace'] @@ -840,7 +880,12 @@ def _from_dict(cls, _dict): args['trace'] = _dict.get('trace') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalyzeResponse 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, 'images') and self.images is not None: @@ -851,17 +896,21 @@ def _to_dict(self): _dict['trace'] = self.trace return _dict - def __str__(self): + 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 AnalyzeResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AnalyzeResponse') -> 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): + def __ne__(self, other: 'AnalyzeResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -882,8 +931,9 @@ class Collection(): collection. """ - def __init__(self, collection_id, name, description, created, updated, - image_count, training_status): + def __init__(self, collection_id: str, name: str, description: str, + created: datetime, updated: datetime, image_count: int, + training_status: 'TrainingStatus') -> None: """ Initialize a Collection object. @@ -907,7 +957,7 @@ def __init__(self, collection_id, name, description, created, updated, self.training_status = training_status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} valid_keys = [ @@ -961,7 +1011,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection 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, 'collection_id') and self.collection_id is not None: @@ -981,17 +1036,21 @@ def _to_dict(self): _dict['training_status'] = self.training_status._to_dict() return _dict - def __str__(self): + 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 Collection object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Collection') -> 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): + def __ne__(self, other: 'Collection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1001,21 +1060,22 @@ class CollectionObjects(): The objects in a collection that are detected in an image. :attr str collection_id: The identifier of the collection. - :attr list[ObjectDetail] objects: The identified objects in a collection. + :attr List[ObjectDetail] objects: The identified objects in a collection. """ - def __init__(self, collection_id, objects): + def __init__(self, collection_id: str, + objects: List['ObjectDetail']) -> None: """ Initialize a CollectionObjects object. :param str collection_id: The identifier of the collection. - :param list[ObjectDetail] objects: The identified objects in a collection. + :param List[ObjectDetail] objects: The identified objects in a collection. """ self.collection_id = collection_id self.objects = objects @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionObjects': """Initialize a CollectionObjects object from a json dictionary.""" args = {} valid_keys = ['collection_id', 'objects'] @@ -1040,7 +1100,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionObjects 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, 'collection_id') and self.collection_id is not None: @@ -1049,17 +1114,21 @@ def _to_dict(self): _dict['objects'] = [x._to_dict() for x in self.objects] return _dict - def __str__(self): + 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 CollectionObjects object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionObjects') -> 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): + def __ne__(self, other: 'CollectionObjects') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1068,20 +1137,20 @@ class CollectionsList(): """ A container for the list of collections. - :attr list[Collection] collections: The collections in this service instance. + :attr List[Collection] collections: The collections in this service instance. """ - def __init__(self, collections): + def __init__(self, collections: List['Collection']) -> None: """ Initialize a CollectionsList object. - :param list[Collection] collections: The collections in this service + :param List[Collection] collections: The collections in this service instance. """ self.collections = collections @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CollectionsList': """Initialize a CollectionsList object from a json dictionary.""" args = {} valid_keys = ['collections'] @@ -1100,24 +1169,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionsList 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, 'collections') and self.collections is not None: _dict['collections'] = [x._to_dict() for x in self.collections] return _dict - def __str__(self): + 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 CollectionsList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CollectionsList') -> 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): + def __ne__(self, other: 'CollectionsList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1126,21 +1204,22 @@ class DetectedObjects(): """ Container for the list of collections that have objects detected in an image. - :attr list[CollectionObjects] collections: (optional) The collections with + :attr List[CollectionObjects] collections: (optional) The collections with identified objects. """ - def __init__(self, *, collections=None): + def __init__(self, *, + collections: List['CollectionObjects'] = None) -> None: """ Initialize a DetectedObjects object. - :param list[CollectionObjects] collections: (optional) The collections with + :param List[CollectionObjects] collections: (optional) The collections with identified objects. """ self.collections = collections @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'DetectedObjects': """Initialize a DetectedObjects object from a json dictionary.""" args = {} valid_keys = ['collections'] @@ -1156,24 +1235,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a DetectedObjects 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, 'collections') and self.collections is not None: _dict['collections'] = [x._to_dict() for x in self.collections] return _dict - def __str__(self): + 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 DetectedObjects object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'DetectedObjects') -> 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): + def __ne__(self, other: 'DetectedObjects') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1189,7 +1277,12 @@ class Error(): problem. """ - def __init__(self, code, message, *, more_info=None, target=None): + def __init__(self, + code: str, + message: str, + *, + more_info: str = None, + target: 'ErrorTarget' = None) -> None: """ Initialize a Error object. @@ -1206,7 +1299,7 @@ def __init__(self, code, message, *, more_info=None, target=None): self.target = target @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Error': """Initialize a Error object from a json dictionary.""" args = {} valid_keys = ['code', 'message', 'more_info', 'target'] @@ -1231,7 +1324,12 @@ def _from_dict(cls, _dict): args['target'] = ErrorTarget._from_dict(_dict.get('target')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Error 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, 'code') and self.code is not None: @@ -1244,17 +1342,21 @@ def _to_dict(self): _dict['target'] = self.target._to_dict() return _dict - def __str__(self): + 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 Error object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Error') -> 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): + def __ne__(self, other: 'Error') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1277,7 +1379,7 @@ class ErrorTarget(): :attr str name: The property that is identified with the problem. """ - def __init__(self, type, name): + def __init__(self, type: str, name: str) -> None: """ Initialize a ErrorTarget object. @@ -1289,7 +1391,7 @@ def __init__(self, type, name): self.name = name @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ErrorTarget': """Initialize a ErrorTarget object from a json dictionary.""" args = {} valid_keys = ['type', 'name'] @@ -1310,7 +1412,12 @@ def _from_dict(cls, _dict): 'Required property \'name\' not present in ErrorTarget JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ErrorTarget 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: @@ -1319,17 +1426,21 @@ def _to_dict(self): _dict['name'] = self.name return _dict - def __str__(self): + 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 ErrorTarget object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ErrorTarget') -> 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): + def __ne__(self, other: 'ErrorTarget') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1350,11 +1461,16 @@ class Image(): :attr ImageDimensions dimensions: Height and width of an image. :attr DetectedObjects objects: Container for the list of collections that have objects detected in an image. - :attr list[Error] errors: (optional) A container for the problems in the + :attr List[Error] errors: (optional) A container for the problems in the request. """ - def __init__(self, source, dimensions, objects, *, errors=None): + def __init__(self, + source: 'ImageSource', + dimensions: 'ImageDimensions', + objects: 'DetectedObjects', + *, + errors: List['Error'] = None) -> None: """ Initialize a Image object. @@ -1362,7 +1478,7 @@ def __init__(self, source, dimensions, objects, *, errors=None): :param ImageDimensions dimensions: Height and width of an image. :param DetectedObjects objects: Container for the list of collections that have objects detected in an image. - :param list[Error] errors: (optional) A container for the problems in the + :param List[Error] errors: (optional) A container for the problems in the request. """ self.source = source @@ -1371,7 +1487,7 @@ def __init__(self, source, dimensions, objects, *, errors=None): self.errors = errors @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Image': """Initialize a Image object from a json dictionary.""" args = {} valid_keys = ['source', 'dimensions', 'objects', 'errors'] @@ -1402,7 +1518,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Image 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, 'source') and self.source is not None: @@ -1415,17 +1536,21 @@ def _to_dict(self): _dict['errors'] = [x._to_dict() for x in self.errors] return _dict - def __str__(self): + 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 Image object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Image') -> 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): + def __ne__(self, other: 'Image') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1441,20 +1566,20 @@ class ImageDetails(): (UTC) that the image was created. :attr ImageSource source: The source type of the image. :attr ImageDimensions dimensions: (optional) Height and width of an image. - :attr list[Error] errors: (optional) + :attr List[Error] errors: (optional) :attr TrainingDataObjects training_data: (optional) Training data for all objects. """ def __init__(self, - source, + source: 'ImageSource', *, - image_id=None, - updated=None, - created=None, - dimensions=None, - errors=None, - training_data=None): + image_id: str = None, + updated: datetime = None, + created: datetime = None, + dimensions: 'ImageDimensions' = None, + errors: List['Error'] = None, + training_data: 'TrainingDataObjects' = None) -> None: """ Initialize a ImageDetails object. @@ -1465,7 +1590,7 @@ def __init__(self, :param datetime created: (optional) Date and time in Coordinated Universal Time (UTC) that the image was created. :param ImageDimensions dimensions: (optional) Height and width of an image. - :param list[Error] errors: (optional) + :param List[Error] errors: (optional) :param TrainingDataObjects training_data: (optional) Training data for all objects. """ @@ -1478,7 +1603,7 @@ def __init__(self, self.training_data = training_data @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageDetails': """Initialize a ImageDetails object from a json dictionary.""" args = {} valid_keys = [ @@ -1513,7 +1638,12 @@ def _from_dict(cls, _dict): _dict.get('training_data')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageDetails 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, 'image_id') and self.image_id is not None: @@ -1532,17 +1662,21 @@ def _to_dict(self): _dict['training_data'] = self.training_data._to_dict() return _dict - def __str__(self): + 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 ImageDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageDetails') -> 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): + def __ne__(self, other: 'ImageDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1551,19 +1685,23 @@ class ImageDetailsList(): """ List of information about the images. - :attr list[ImageDetails] images: (optional) The images in the collection. - :attr list[Warning] warnings: (optional) Information about what might cause less + :attr List[ImageDetails] images: (optional) The images in the collection. + :attr List[Warning] warnings: (optional) Information about what might cause less than optimal output. :attr str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. """ - def __init__(self, *, images=None, warnings=None, trace=None): + def __init__(self, + *, + images: List['ImageDetails'] = None, + warnings: List['Warning'] = None, + trace: str = None) -> None: """ Initialize a ImageDetailsList object. - :param list[ImageDetails] images: (optional) The images in the collection. - :param list[Warning] warnings: (optional) Information about what might + :param List[ImageDetails] images: (optional) The images in the collection. + :param List[Warning] warnings: (optional) Information about what might cause less than optimal output. :param str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. @@ -1573,7 +1711,7 @@ def __init__(self, *, images=None, warnings=None, trace=None): self.trace = trace @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageDetailsList': """Initialize a ImageDetailsList object from a json dictionary.""" args = {} valid_keys = ['images', 'warnings', 'trace'] @@ -1594,7 +1732,12 @@ def _from_dict(cls, _dict): args['trace'] = _dict.get('trace') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageDetailsList 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, 'images') and self.images is not None: @@ -1605,17 +1748,21 @@ def _to_dict(self): _dict['trace'] = self.trace return _dict - def __str__(self): + 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 ImageDetailsList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageDetailsList') -> 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): + def __ne__(self, other: 'ImageDetailsList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1628,7 +1775,7 @@ class ImageDimensions(): :attr int width: (optional) Width in pixels of the image. """ - def __init__(self, *, height=None, width=None): + def __init__(self, *, height: int = None, width: int = None) -> None: """ Initialize a ImageDimensions object. @@ -1639,7 +1786,7 @@ def __init__(self, *, height=None, width=None): self.width = width @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageDimensions': """Initialize a ImageDimensions object from a json dictionary.""" args = {} valid_keys = ['height', 'width'] @@ -1654,7 +1801,12 @@ def _from_dict(cls, _dict): args['width'] = _dict.get('width') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageDimensions 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, 'height') and self.height is not None: @@ -1663,17 +1815,21 @@ def _to_dict(self): _dict['width'] = self.width return _dict - def __str__(self): + 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 ImageDimensions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageDimensions') -> 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): + def __ne__(self, other: 'ImageDimensions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1694,12 +1850,12 @@ class ImageSource(): """ def __init__(self, - type, + type: str, *, - filename=None, - archive_filename=None, - source_url=None, - resolved_url=None): + filename: str = None, + archive_filename: str = None, + source_url: str = None, + resolved_url: str = None) -> None: """ Initialize a ImageSource object. @@ -1720,7 +1876,7 @@ def __init__(self, self.resolved_url = resolved_url @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageSource': """Initialize a ImageSource object from a json dictionary.""" args = {} valid_keys = [ @@ -1746,7 +1902,12 @@ def _from_dict(cls, _dict): args['resolved_url'] = _dict.get('resolved_url') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageSource 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: @@ -1762,17 +1923,21 @@ def _to_dict(self): _dict['resolved_url'] = self.resolved_url return _dict - def __str__(self): + 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 ImageSource object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageSource') -> 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): + def __ne__(self, other: 'ImageSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1793,7 +1958,8 @@ class ImageSummary(): (UTC) that the image was most recently updated. """ - def __init__(self, *, image_id=None, updated=None): + def __init__(self, *, image_id: str = None, + updated: datetime = None) -> None: """ Initialize a ImageSummary object. @@ -1805,7 +1971,7 @@ def __init__(self, *, image_id=None, updated=None): self.updated = updated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageSummary': """Initialize a ImageSummary object from a json dictionary.""" args = {} valid_keys = ['image_id', 'updated'] @@ -1820,7 +1986,12 @@ def _from_dict(cls, _dict): args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageSummary 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, 'image_id') and self.image_id is not None: @@ -1829,17 +2000,21 @@ def _to_dict(self): _dict['updated'] = datetime_to_string(self.updated) return _dict - def __str__(self): + 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 ImageSummary object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageSummary') -> 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): + def __ne__(self, other: 'ImageSummary') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1848,19 +2023,19 @@ class ImageSummaryList(): """ List of images. - :attr list[ImageSummary] images: The images in the collection. + :attr List[ImageSummary] images: The images in the collection. """ - def __init__(self, images): + def __init__(self, images: List['ImageSummary']) -> None: """ Initialize a ImageSummaryList object. - :param list[ImageSummary] images: The images in the collection. + :param List[ImageSummary] images: The images in the collection. """ self.images = images @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ImageSummaryList': """Initialize a ImageSummaryList object from a json dictionary.""" args = {} valid_keys = ['images'] @@ -1879,24 +2054,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ImageSummaryList 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, 'images') and self.images is not None: _dict['images'] = [x._to_dict() for x in self.images] return _dict - def __str__(self): + 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 ImageSummaryList object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ImageSummaryList') -> 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): + def __ne__(self, other: 'ImageSummaryList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1911,7 +2095,7 @@ class Location(): :attr int height: Height in pixels of the bounding box. """ - def __init__(self, top, left, width, height): + def __init__(self, top: int, left: int, width: int, height: int) -> None: """ Initialize a Location object. @@ -1926,7 +2110,7 @@ def __init__(self, top, left, width, height): self.height = height @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Location': """Initialize a Location object from a json dictionary.""" args = {} valid_keys = ['top', 'left', 'width', 'height'] @@ -1957,7 +2141,12 @@ def _from_dict(cls, _dict): 'Required property \'height\' not present in Location JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Location 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, 'top') and self.top is not None: @@ -1970,17 +2159,21 @@ def _to_dict(self): _dict['height'] = self.height return _dict - def __str__(self): + 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 Location object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Location') -> 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): + def __ne__(self, other: 'Location') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1997,7 +2190,7 @@ class ObjectDetail(): location in the image. """ - def __init__(self, object, location, score): + def __init__(self, object: str, location: 'Location', score: float) -> None: """ Initialize a ObjectDetail object. @@ -2013,7 +2206,7 @@ def __init__(self, object, location, score): self.score = score @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ObjectDetail': """Initialize a ObjectDetail object from a json dictionary.""" args = {} valid_keys = ['object', 'location', 'score'] @@ -2040,7 +2233,12 @@ def _from_dict(cls, _dict): 'Required property \'score\' not present in ObjectDetail JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ObjectDetail 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: @@ -2051,17 +2249,21 @@ def _to_dict(self): _dict['score'] = self.score return _dict - def __str__(self): + 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 ObjectDetail object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ObjectDetail') -> 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): + def __ne__(self, other: 'ObjectDetail') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2081,8 +2283,8 @@ class ObjectTrainingStatus(): a success message or information about why training failed. """ - def __init__(self, ready, in_progress, data_changed, latest_failed, - description): + def __init__(self, ready: bool, in_progress: bool, data_changed: bool, + latest_failed: bool, description: str) -> None: """ Initialize a ObjectTrainingStatus object. @@ -2104,7 +2306,7 @@ def __init__(self, ready, in_progress, data_changed, latest_failed, self.description = description @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ObjectTrainingStatus': """Initialize a ObjectTrainingStatus object from a json dictionary.""" args = {} valid_keys = [ @@ -2148,7 +2350,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ObjectTrainingStatus 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, 'ready') and self.ready is not None: @@ -2163,17 +2370,21 @@ def _to_dict(self): _dict['description'] = self.description return _dict - def __str__(self): + 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 ObjectTrainingStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ObjectTrainingStatus') -> 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): + def __ne__(self, other: 'ObjectTrainingStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2187,7 +2398,8 @@ class TrainingDataObject(): around the object. """ - def __init__(self, *, object=None, location=None): + def __init__(self, *, object: str = None, + location: 'Location' = None) -> None: """ Initialize a TrainingDataObject object. @@ -2199,7 +2411,7 @@ def __init__(self, *, object=None, location=None): self.location = location @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingDataObject': """Initialize a TrainingDataObject object from a json dictionary.""" args = {} valid_keys = ['object', 'location'] @@ -2214,7 +2426,12 @@ def _from_dict(cls, _dict): args['location'] = Location._from_dict(_dict.get('location')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingDataObject 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: @@ -2223,17 +2440,21 @@ def _to_dict(self): _dict['location'] = self.location._to_dict() return _dict - def __str__(self): + 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 TrainingDataObject object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingDataObject') -> 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): + def __ne__(self, other: 'TrainingDataObject') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2242,21 +2463,21 @@ class TrainingDataObjects(): """ Training data for all objects. - :attr list[TrainingDataObject] objects: (optional) Training data for specific + :attr List[TrainingDataObject] objects: (optional) Training data for specific objects. """ - def __init__(self, *, objects=None): + def __init__(self, *, objects: List['TrainingDataObject'] = None) -> None: """ Initialize a TrainingDataObjects object. - :param list[TrainingDataObject] objects: (optional) Training data for + :param List[TrainingDataObject] objects: (optional) Training data for specific objects. """ self.objects = objects @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingDataObjects': """Initialize a TrainingDataObjects object from a json dictionary.""" args = {} valid_keys = ['objects'] @@ -2271,24 +2492,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingDataObjects 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, 'objects') and self.objects is not None: _dict['objects'] = [x._to_dict() for x in self.objects] return _dict - def __str__(self): + 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 TrainingDataObjects object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingDataObjects') -> 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): + def __ne__(self, other: 'TrainingDataObjects') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2309,11 +2539,11 @@ class TrainingEvent(): def __init__(self, *, - type=None, - collection_id=None, - completion_time=None, - status=None, - image_count=None): + type: str = None, + collection_id: str = None, + completion_time: datetime = None, + status: str = None, + image_count: int = None) -> None: """ Initialize a TrainingEvent object. @@ -2333,7 +2563,7 @@ def __init__(self, self.image_count = image_count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingEvent': """Initialize a TrainingEvent object from a json dictionary.""" args = {} valid_keys = [ @@ -2357,7 +2587,12 @@ def _from_dict(cls, _dict): args['image_count'] = _dict.get('image_count') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingEvent 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: @@ -2373,17 +2608,21 @@ def _to_dict(self): _dict['image_count'] = self.image_count return _dict - def __str__(self): + 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 TrainingEvent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingEvent') -> 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): + def __ne__(self, other: 'TrainingEvent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2415,17 +2654,17 @@ class TrainingEvents(): the response for the start and end times. :attr int trained_images: (optional) The total number of images that were used in training for the start and end times. - :attr list[TrainingEvent] events: (optional) The completed training events for + :attr List[TrainingEvent] events: (optional) The completed training events for the start and end time. """ def __init__(self, *, - start_time=None, - end_time=None, - completed_events=None, - trained_images=None, - events=None): + start_time: datetime = None, + end_time: datetime = None, + completed_events: int = None, + trained_images: int = None, + events: List['TrainingEvent'] = None) -> None: """ Initialize a TrainingEvents object. @@ -2439,7 +2678,7 @@ def __init__(self, in the response for the start and end times. :param int trained_images: (optional) The total number of images that were used in training for the start and end times. - :param list[TrainingEvent] events: (optional) The completed training events + :param List[TrainingEvent] events: (optional) The completed training events for the start and end time. """ self.start_time = start_time @@ -2449,7 +2688,7 @@ def __init__(self, self.events = events @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingEvents': """Initialize a TrainingEvents object from a json dictionary.""" args = {} valid_keys = [ @@ -2475,7 +2714,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingEvents 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, 'start_time') and self.start_time is not None: @@ -2491,17 +2735,21 @@ def _to_dict(self): _dict['events'] = [x._to_dict() for x in self.events] return _dict - def __str__(self): + 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 TrainingEvents object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingEvents') -> 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): + def __ne__(self, other: 'TrainingEvents') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2514,7 +2762,7 @@ class TrainingStatus(): collection. """ - def __init__(self, objects): + def __init__(self, objects: 'ObjectTrainingStatus') -> None: """ Initialize a TrainingStatus object. @@ -2524,7 +2772,7 @@ def __init__(self, objects): self.objects = objects @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingStatus': """Initialize a TrainingStatus object from a json dictionary.""" args = {} valid_keys = ['objects'] @@ -2542,24 +2790,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingStatus 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, 'objects') and self.objects is not None: _dict['objects'] = self.objects._to_dict() return _dict - def __str__(self): + 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 TrainingStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingStatus') -> 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): + def __ne__(self, other: 'TrainingStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2573,7 +2830,8 @@ class Warning(): :attr str more_info: (optional) A URL for more information about the solution. """ - def __init__(self, code, message, *, more_info=None): + def __init__(self, code: str, message: str, *, + more_info: str = None) -> None: """ Initialize a Warning object. @@ -2587,7 +2845,7 @@ def __init__(self, code, message, *, more_info=None): self.more_info = more_info @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Warning': """Initialize a Warning object from a json dictionary.""" args = {} valid_keys = ['code', 'message', 'more_info'] @@ -2610,7 +2868,12 @@ def _from_dict(cls, _dict): args['more_info'] = _dict.get('more_info') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Warning 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, 'code') and self.code is not None: @@ -2621,17 +2884,21 @@ def _to_dict(self): _dict['more_info'] = self.more_info return _dict - def __str__(self): + 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 Warning object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Warning') -> 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): + def __ne__(self, other: 'Warning') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2650,16 +2917,20 @@ class FileWithMetadata(): """ A file with its associated metadata. - :attr file data: The data / content for the file. + :attr BinaryIO data: The data / content for the file. :attr str filename: (optional) The filename of the file. :attr str content_type: (optional) The content type of the file. """ - def __init__(self, data, *, filename=None, content_type=None): + def __init__(self, + data: BinaryIO, + *, + filename: str = None, + content_type: str = None) -> None: """ Initialize a FileWithMetadata object. - :param file data: The data / content for the file. + :param BinaryIO data: The data / content for the file. :param str filename: (optional) The filename of the file. :param str content_type: (optional) The content type of the file. """ @@ -2668,7 +2939,7 @@ def __init__(self, data, *, filename=None, content_type=None): self.content_type = content_type @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'FileWithMetadata': """Initialize a FileWithMetadata object from a json dictionary.""" args = {} valid_keys = ['data', 'filename', 'content_type'] @@ -2678,7 +2949,7 @@ def _from_dict(cls, _dict): 'Unrecognized keys detected in dictionary for class FileWithMetadata: ' + ', '.join(bad_keys)) if 'data' in _dict: - args['data'] = file._from_dict(_dict.get('data')) + args['data'] = _dict.get('data') else: raise ValueError( 'Required property \'data\' not present in FileWithMetadata JSON' @@ -2689,7 +2960,12 @@ def _from_dict(cls, _dict): args['content_type'] = _dict.get('content_type') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a FileWithMetadata 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, 'data') and self.data is not None: @@ -2700,16 +2976,20 @@ def _to_dict(self): _dict['content_type'] = self.content_type return _dict - def __str__(self): + 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 FileWithMetadata object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'FileWithMetadata') -> 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): + def __ne__(self, other: 'FileWithMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 0c408ad30..1a76c2d4e 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -13,9 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. +from datetime import datetime from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect +import json +import pytest import responses import tempfile +import ibm_watson.visual_recognition_v4 from ibm_watson.visual_recognition_v4 import * base_url = 'https://gateway.watsonplatform.net/visual-recognition/api' @@ -77,25 +82,27 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.analyze(**body) return output def construct_full_body(self): body = dict() - body['collection_ids'] = ['collection_id1, collection_id2'] - body['features'] = ['test'] - body['image_url'] = ['https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/American_Eskimo_Dog.jpg/1280px-American_Eskimo_Dog.jpg'] + body['collection_ids'] = [] + body['features'] = [] + body['images_file'] = [] + body['image_url'] = [] body['threshold'] = 12345.0 - body['images_file'] = [FileWithMetadata(tempfile.NamedTemporaryFile())] return body def construct_required_body(self): body = dict() - body['collection_ids'] = ['fake'] - body['features'] = [AnalyzeEnums.Features.OBJECTS.value] + body['collection_ids'] = [] + body['features'] = [] return body @@ -160,8 +167,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.create_collection(**body) return output @@ -233,8 +242,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.list_collections(**body) return output @@ -299,8 +310,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.get_collection(**body) return output @@ -367,8 +380,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.update_collection(**body) return output @@ -439,8 +454,10 @@ def add_mock_response(self, url, response): content_type='') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.delete_collection(**body) return output @@ -518,8 +535,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.add_images(**body) return output @@ -589,8 +608,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.list_images(**body) return output @@ -658,8 +679,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.get_image_details(**body) return output @@ -729,8 +752,10 @@ def add_mock_response(self, url, response): content_type='') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.delete_image(**body) return output @@ -800,8 +825,10 @@ def add_mock_response(self, url, response): content_type='') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.get_jpeg_image(**body) return output @@ -882,8 +909,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.train(**body) return output @@ -952,8 +981,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.add_image_training_data(**body) return output @@ -1027,8 +1058,10 @@ def add_mock_response(self, url, response): content_type='application/json') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.get_training_usage(**body) return output @@ -1106,8 +1139,10 @@ def add_mock_response(self, url, response): content_type='') def call_service(self, body): - service = VisualRecognitionV4(authenticator=NoAuthAuthenticator(), - version='2019-02-11') + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output From 84269be06baa82b0acc46a01c163917fcd896547 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 16:52:31 -0500 Subject: [PATCH 184/455] chore(vr4): manual changes to vr4 --- ibm_watson/visual_recognition_v4.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 05eb8fd1e..8139a7a69 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -139,11 +139,10 @@ def analyze(self, params = {'version': self.version} form_data = [] - for item in collection_ids: - form_data.append( - ('collection_ids', (None, item, 'application/json'))) - for item in features: - form_data.append(('features', (None, item, 'application/json'))) + collection_ids = self._convert_list(collection_ids) + form_data.append(('collection_ids', (None, collection_ids, 'text/plain'))) + features = self._convert_list(features) + form_data.append(('features', (None, features, 'text/plain'))) if images_file: for item in images_file: form_data.append(('images_file', (item.filename, item.data, @@ -151,8 +150,7 @@ def analyze(self, 'application/octet-stream'))) if image_url: for item in image_url: - form_data.append( - ('image_url', (None, item, 'application/json'))) + form_data.append(('image_url', (None, item, 'text/plain'))) if threshold: threshold = str(threshold) form_data.append(('threshold', (None, threshold, 'text/plain'))) From 776dc8635a98489a9ceb8abf155947bb0f39ad8a Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 17:57:54 -0500 Subject: [PATCH 185/455] feat(stt): New param `end_of_phrase_silence_time` and `split_transcript_at_phrase_end` in `recognize` --- ibm_watson/speech_to_text_v1.py | 73 +++++++++++++++++++++++---------- 1 file changed, 51 insertions(+), 22 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 2697d164e..132a7c6cc 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -152,29 +152,31 @@ def get_model(self, model_id, **kwargs): ######################### def recognize(self, - audio, + audio: BinaryIO, *, - content_type=None, - model=None, - language_customization_id=None, - acoustic_customization_id=None, - base_model_version=None, - customization_weight=None, - inactivity_timeout=None, - keywords=None, - keywords_threshold=None, - max_alternatives=None, - word_alternatives_threshold=None, - word_confidence=None, - timestamps=None, - profanity_filter=None, - smart_formatting=None, - speaker_labels=None, - customization_id=None, - grammar_name=None, - redaction=None, - audio_metrics=None, - **kwargs): + content_type: str = None, + model: str = None, + language_customization_id: str = None, + acoustic_customization_id: str = None, + base_model_version: str = None, + customization_weight: float = None, + inactivity_timeout: int = None, + keywords: List[str] = None, + keywords_threshold: float = None, + max_alternatives: int = None, + word_alternatives_threshold: float = None, + word_confidence: bool = None, + timestamps: bool = None, + profanity_filter: bool = None, + smart_formatting: bool = None, + speaker_labels: bool = None, + customization_id: str = None, + grammar_name: str = None, + redaction: bool = None, + audio_metrics: bool = None, + end_of_phrase_silence_time: float = None, + split_transcript_at_phrase_end: bool = None, + **kwargs) -> 'DetailedResponse': """ Recognize audio. @@ -389,6 +391,33 @@ def recognize(self, 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). + :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 + silence before it reaches the end of the audio stream, its response can + include multiple final results. Silence indicates a point at which the + speaker pauses between spoken words or phrases. + Specify a value for the pause interval in the range of 0.0 to 120.0. + * A value greater than 0 specifies the interval that the service is to use + for speech recognition. + * A value of 0 indicates that the service is to use the default interval. + It is equivalent to omitting the parameter. + 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). + :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 + meaningful phrases such as sentences. The service bases its understanding + of semantic features on the base language model that you use with a + request. Custom language models and grammars can also influence how and + 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). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse From 650baa8a48aec6ce75bdfcb370f46d540fac8d89 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 18:00:13 -0500 Subject: [PATCH 186/455] refactor(stt): regenerate speech to text with tests --- ibm_watson/speech_to_text_v1.py | 1823 ++++++++----- test/unit/test_speech_to_text_v1.py | 3706 ++++++++++++++++++++++----- 2 files changed, 4277 insertions(+), 1252 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 132a7c6cc..b3be2d348 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,11 +35,18 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator 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 read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +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 +from typing import List +from typing import TextIO ############################################################################## # Service @@ -49,12 +56,14 @@ class SpeechToTextV1(BaseService): """The Speech to Text V1 service.""" - default_service_url = 'https://stream.watsonplatform.net/speech-to-text/api' + DEFAULT_SERVICE_URL = 'https://stream.watsonplatform.net/speech-to-text/api' + DEFAULT_SERVICE_NAME = 'speech_to_text' def __init__( self, - authenticator=None, - ): + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Speech to Text service. @@ -62,29 +71,19 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('speech_to_text') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('speech_to_text') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) + self.configure_service(service_name) ######################### # Models ######################### - def list_models(self, **kwargs): + def list_models(self, **kwargs) -> 'DetailedResponse': """ List models. @@ -102,18 +101,18 @@ def list_models(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'list_models') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_models') headers.update(sdk_headers) url = '/v1/models' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def get_model(self, model_id, **kwargs): + def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': """ Get a model. @@ -136,14 +135,14 @@ def get_model(self, model_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'get_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_model') headers.update(sdk_headers) url = '/v1/models/{0}'.format(*self._encode_path_vars(model_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response @@ -250,7 +249,7 @@ def recognize(self, **See also:** [Making a multipart HTTP request](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-http#HTTP-multi). - :param file audio: The audio to transcribe. + :param BinaryIO audio: The audio to transcribe. :param str content_type: (optional) The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. @@ -302,7 +301,7 @@ def recognize(self, 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). - :param list[str] keywords: (optional) An array of keyword strings to spot + :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. @@ -429,7 +428,9 @@ def recognize(self, headers = {'Content-Type': content_type} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'recognize') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='recognize') headers.update(sdk_headers) params = { @@ -451,7 +452,9 @@ def recognize(self, 'customization_id': customization_id, 'grammar_name': grammar_name, 'redaction': redaction, - 'audio_metrics': audio_metrics + 'audio_metrics': audio_metrics, + 'end_of_phrase_silence_time': end_of_phrase_silence_time, + 'split_transcript_at_phrase_end': split_transcript_at_phrase_end } data = audio @@ -461,8 +464,8 @@ def recognize(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response @@ -470,7 +473,11 @@ def recognize(self, # Asynchronous ######################### - def register_callback(self, callback_url, *, user_secret=None, **kwargs): + def register_callback(self, + callback_url: str, + *, + user_secret: str = None, + **kwargs) -> 'DetailedResponse': """ Register a callback. @@ -526,8 +533,9 @@ def register_callback(self, callback_url, *, user_secret=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'register_callback') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='register_callback') headers.update(sdk_headers) params = {'callback_url': callback_url, 'user_secret': user_secret} @@ -536,12 +544,13 @@ def register_callback(self, callback_url, *, user_secret=None, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def unregister_callback(self, callback_url, **kwargs): + def unregister_callback(self, callback_url: str, + **kwargs) -> 'DetailedResponse': """ Unregister a callback. @@ -563,8 +572,9 @@ def unregister_callback(self, callback_url, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'unregister_callback') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='unregister_callback') headers.update(sdk_headers) params = {'callback_url': callback_url} @@ -573,41 +583,43 @@ def unregister_callback(self, callback_url, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response def create_job(self, - audio, + audio: BinaryIO, *, - content_type=None, - model=None, - callback_url=None, - events=None, - user_token=None, - results_ttl=None, - language_customization_id=None, - acoustic_customization_id=None, - base_model_version=None, - customization_weight=None, - inactivity_timeout=None, - keywords=None, - keywords_threshold=None, - max_alternatives=None, - word_alternatives_threshold=None, - word_confidence=None, - timestamps=None, - profanity_filter=None, - smart_formatting=None, - speaker_labels=None, - customization_id=None, - grammar_name=None, - redaction=None, - processing_metrics=None, - processing_metrics_interval=None, - audio_metrics=None, - **kwargs): + content_type: str = None, + model: str = None, + callback_url: str = None, + events: str = None, + user_token: str = None, + results_ttl: int = None, + language_customization_id: str = None, + acoustic_customization_id: str = None, + base_model_version: str = None, + customization_weight: float = None, + inactivity_timeout: int = None, + keywords: List[str] = None, + keywords_threshold: float = None, + max_alternatives: int = None, + word_alternatives_threshold: float = None, + word_confidence: bool = None, + timestamps: bool = None, + profanity_filter: bool = None, + smart_formatting: bool = None, + speaker_labels: bool = None, + customization_id: str = None, + grammar_name: str = None, + redaction: bool = None, + processing_metrics: bool = None, + processing_metrics_interval: float = None, + audio_metrics: bool = None, + end_of_phrase_silence_time: float = None, + split_transcript_at_phrase_end: bool = None, + **kwargs) -> 'DetailedResponse': """ Create a job. @@ -694,7 +706,7 @@ def create_job(self, **See also:** [Audio formats](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). - :param file audio: The audio to transcribe. + :param BinaryIO audio: The audio to transcribe. :param str content_type: (optional) The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. @@ -782,7 +794,7 @@ def create_job(self, 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). - :param list[str] keywords: (optional) An array of keyword strings to spot + :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. @@ -873,6 +885,8 @@ def create_job(self, `processing_metrics_interval` parameter. It also returns processing metrics 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). :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 @@ -885,10 +899,39 @@ def create_job(self, intervals, set the value to a large number. If the value is larger than the 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). :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). + :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 + silence before it reaches the end of the audio stream, its response can + include multiple final results. Silence indicates a point at which the + speaker pauses between spoken words or phrases. + Specify a value for the pause interval in the range of 0.0 to 120.0. + * A value greater than 0 specifies the interval that the service is to use + for speech recognition. + * A value of 0 indicates that the service is to use the default interval. + It is equivalent to omitting the parameter. + 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). + :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 + meaningful phrases such as sentences. The service bases its understanding + of semantic features on the base language model that you use with a + request. Custom language models and grammars can also influence how and + 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). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -900,7 +943,9 @@ def create_job(self, headers = {'Content-Type': content_type} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'create_job') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_job') headers.update(sdk_headers) params = { @@ -928,7 +973,9 @@ def create_job(self, 'redaction': redaction, 'processing_metrics': processing_metrics, 'processing_metrics_interval': processing_metrics_interval, - 'audio_metrics': audio_metrics + 'audio_metrics': audio_metrics, + 'end_of_phrase_silence_time': end_of_phrase_silence_time, + 'split_transcript_at_phrase_end': split_transcript_at_phrase_end } data = audio @@ -938,12 +985,12 @@ def create_job(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def check_jobs(self, **kwargs): + def check_jobs(self, **kwargs) -> 'DetailedResponse': """ Check jobs. @@ -966,18 +1013,18 @@ def check_jobs(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'check_jobs') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='check_jobs') headers.update(sdk_headers) url = '/v1/recognitions' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def check_job(self, id, **kwargs): + def check_job(self, id: str, **kwargs) -> 'DetailedResponse': """ Check a job. @@ -1008,18 +1055,18 @@ def check_job(self, id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'check_job') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='check_job') headers.update(sdk_headers) url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_job(self, id, **kwargs): + def delete_job(self, id: str, **kwargs) -> 'DetailedResponse': """ Delete a job. @@ -1045,14 +1092,16 @@ def delete_job(self, id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'delete_job') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_job') headers.update(sdk_headers) url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=False) + headers=headers) + response = self.send(request) return response @@ -1061,12 +1110,12 @@ def delete_job(self, id, **kwargs): ######################### def create_language_model(self, - name, - base_model_name, + name: str, + base_model_name: str, *, - dialect=None, - description=None, - **kwargs): + dialect: str = None, + description: str = None, + **kwargs) -> 'DetailedResponse': """ Create a custom language model. @@ -1074,9 +1123,9 @@ def create_language_model(self, language model can be used only with the base model for which it is created. The model is owned by the instance of the service whose credentials are used to create it. - You can create a maximum of 1024 custom language models, per credential. The - service returns an error if you attempt to create more than 1024 models. You do - not lose any models, but you cannot create any more until your model count is + You can create a maximum of 1024 custom language models per owning credentials. + The service returns an error if you attempt to create more than 1024 models. You + 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). @@ -1128,8 +1177,9 @@ def create_language_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'create_language_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_language_model') headers.update(sdk_headers) data = { @@ -1143,12 +1193,13 @@ def create_language_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_language_models(self, *, language=None, **kwargs): + def list_language_models(self, *, language: str = None, + **kwargs) -> 'DetailedResponse': """ List custom language models. @@ -1172,8 +1223,9 @@ def list_language_models(self, *, language=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'list_language_models') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_language_models') headers.update(sdk_headers) params = {'language': language} @@ -1182,12 +1234,13 @@ def list_language_models(self, *, language=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_language_model(self, customization_id, **kwargs): + def get_language_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Get a custom language model. @@ -1211,20 +1264,20 @@ def get_language_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'get_language_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_language_model') headers.update(sdk_headers) url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_language_model(self, customization_id, **kwargs): + def delete_language_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom language model. @@ -1250,25 +1303,26 @@ def delete_language_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'delete_language_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_language_model') headers.update(sdk_headers) url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response def train_language_model(self, - customization_id, + customization_id: str, *, - word_type_to_add=None, - customization_weight=None, - **kwargs): + word_type_to_add: str = None, + customization_weight: float = None, + **kwargs) -> 'DetailedResponse': """ Train a custom language model. @@ -1338,8 +1392,9 @@ def train_language_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'train_language_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='train_language_model') headers.update(sdk_headers) params = { @@ -1352,12 +1407,13 @@ def train_language_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def reset_language_model(self, customization_id, **kwargs): + def reset_language_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Reset a custom language model. @@ -1385,20 +1441,20 @@ def reset_language_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'reset_language_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='reset_language_model') headers.update(sdk_headers) url = '/v1/customizations/{0}/reset'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='POST', url=url, headers=headers) + response = self.send(request) return response - def upgrade_language_model(self, customization_id, **kwargs): + def upgrade_language_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Upgrade a custom language model. @@ -1434,16 +1490,15 @@ def upgrade_language_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'upgrade_language_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='upgrade_language_model') headers.update(sdk_headers) url = '/v1/customizations/{0}/upgrade_model'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='POST', url=url, headers=headers) + response = self.send(request) return response @@ -1451,7 +1506,8 @@ def upgrade_language_model(self, customization_id, **kwargs): # Custom corpora ######################### - def list_corpora(self, customization_id, **kwargs): + def list_corpora(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ List corpora. @@ -1477,25 +1533,25 @@ def list_corpora(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'list_corpora') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_corpora') headers.update(sdk_headers) url = '/v1/customizations/{0}/corpora'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response def add_corpus(self, - customization_id, - corpus_name, - corpus_file, + customization_id: str, + corpus_name: str, + corpus_file: BinaryIO, *, - allow_overwrite=None, - **kwargs): + allow_overwrite: bool = None, + **kwargs) -> 'DetailedResponse': """ Add a corpus. @@ -1558,8 +1614,8 @@ def add_corpus(self, custom words that are added or modified by the user. * Do not use the name `base_lm` or `default_lm`. Both names are reserved for future use by the service. - :param file corpus_file: A plain text file that contains the training data - for the corpus. Encode the file in UTF-8 if it contains non-ASCII + :param TextIO corpus_file: A plain text file that contains the training + data for the corpus. Encode the file in UTF-8 if it contains non-ASCII characters; the service assumes UTF-8 encoding if it encounters non-ASCII characters. Make sure that you know the character encoding of the file. You must use @@ -1587,7 +1643,9 @@ def add_corpus(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'add_corpus') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_corpus') headers.update(sdk_headers) params = {'allow_overwrite': allow_overwrite} @@ -1601,12 +1659,13 @@ def add_corpus(self, url=url, headers=headers, params=params, - files=form_data, - accept_json=True) + files=form_data) + response = self.send(request) return response - def get_corpus(self, customization_id, corpus_name, **kwargs): + def get_corpus(self, customization_id: str, corpus_name: str, + **kwargs) -> 'DetailedResponse': """ Get a corpus. @@ -1636,19 +1695,20 @@ def get_corpus(self, customization_id, corpus_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'get_corpus') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_corpus') headers.update(sdk_headers) url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_corpus(self, customization_id, corpus_name, **kwargs): + def delete_corpus(self, customization_id: str, corpus_name: str, + **kwargs) -> 'DetailedResponse': """ Delete a corpus. @@ -1682,15 +1742,17 @@ def delete_corpus(self, customization_id, corpus_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'delete_corpus') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_corpus') headers.update(sdk_headers) url = '/v1/customizations/{0}/corpora/{1}'.format( *self._encode_path_vars(customization_id, corpus_name)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response @@ -1699,11 +1761,11 @@ def delete_corpus(self, customization_id, corpus_name, **kwargs): ######################### def list_words(self, - customization_id, + customization_id: str, *, - word_type=None, - sort=None, - **kwargs): + word_type: str = None, + sort: str = None, + **kwargs) -> 'DetailedResponse': """ List custom words. @@ -1747,7 +1809,9 @@ def list_words(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'list_words') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_words') headers.update(sdk_headers) params = {'word_type': word_type, 'sort': sort} @@ -1757,12 +1821,13 @@ def list_words(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def add_words(self, customization_id, words, **kwargs): + def add_words(self, customization_id: str, words: List['CustomWord'], + **kwargs) -> 'DetailedResponse': """ Add custom words. @@ -1819,7 +1884,7 @@ def add_words(self, customization_id, words, **kwargs): language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. - :param list[CustomWord] words: An array of `CustomWord` objects that + :param List[CustomWord] words: An array of `CustomWord` objects that provides information about each custom word that is to be added to or updated in the custom language model. :param dict headers: A `dict` containing the request headers @@ -1836,7 +1901,9 @@ def add_words(self, customization_id, words, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'add_words') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_words') headers.update(sdk_headers) data = {'words': words} @@ -1846,19 +1913,19 @@ def add_words(self, customization_id, words, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response def add_word(self, - customization_id, - word_name, + customization_id: str, + word_name: str, *, - word=None, - sounds_like=None, - display_as=None, - **kwargs): + word: str = None, + sounds_like: List[str] = None, + display_as: str = None, + **kwargs) -> 'DetailedResponse': """ Add a custom word. @@ -1910,7 +1977,7 @@ def add_word(self, model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the **Add a custom word** method. - :param list[str] sounds_like: (optional) An array of sounds-like + :param List[str] sounds_like: (optional) An array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. * For a word that is not in the service's base vocabulary, omit the @@ -1939,7 +2006,9 @@ def add_word(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'add_word') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_word') headers.update(sdk_headers) data = { @@ -1953,12 +2022,13 @@ def add_word(self, request = self.prepare_request(method='PUT', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_word(self, customization_id, word_name, **kwargs): + def get_word(self, customization_id: str, word_name: str, + **kwargs) -> 'DetailedResponse': """ Get a custom word. @@ -1989,19 +2059,20 @@ def get_word(self, customization_id, word_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'get_word') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_word') headers.update(sdk_headers) url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_word(self, customization_id, word_name, **kwargs): + def delete_word(self, customization_id: str, word_name: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom word. @@ -2036,15 +2107,17 @@ def delete_word(self, customization_id, word_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'delete_word') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_word') headers.update(sdk_headers) url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word_name)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response @@ -2052,7 +2125,8 @@ def delete_word(self, customization_id, word_name, **kwargs): # Custom grammars ######################### - def list_grammars(self, customization_id, **kwargs): + def list_grammars(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ List grammars. @@ -2078,26 +2152,26 @@ def list_grammars(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'list_grammars') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_grammars') headers.update(sdk_headers) url = '/v1/customizations/{0}/grammars'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response def add_grammar(self, - customization_id, - grammar_name, - grammar_file, - content_type, + customization_id: str, + grammar_name: str, + grammar_file: str, + content_type: str, *, - allow_overwrite=None, - **kwargs): + allow_overwrite: bool = None, + **kwargs) -> 'DetailedResponse': """ Add a grammar. @@ -2189,7 +2263,9 @@ def add_grammar(self, headers = {'Content-Type': content_type} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'add_grammar') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_grammar') headers.update(sdk_headers) params = {'allow_overwrite': allow_overwrite} @@ -2202,12 +2278,13 @@ def add_grammar(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_grammar(self, customization_id, grammar_name, **kwargs): + def get_grammar(self, customization_id: str, grammar_name: str, + **kwargs) -> 'DetailedResponse': """ Get a grammar. @@ -2237,19 +2314,20 @@ def get_grammar(self, customization_id, grammar_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'get_grammar') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_grammar') headers.update(sdk_headers) url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_grammar(self, customization_id, grammar_name, **kwargs): + def delete_grammar(self, customization_id: str, grammar_name: str, + **kwargs) -> 'DetailedResponse': """ Delete a grammar. @@ -2282,15 +2360,17 @@ def delete_grammar(self, customization_id, grammar_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'delete_grammar') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_grammar') headers.update(sdk_headers) url = '/v1/customizations/{0}/grammars/{1}'.format( *self._encode_path_vars(customization_id, grammar_name)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response @@ -2299,11 +2379,11 @@ def delete_grammar(self, customization_id, grammar_name, **kwargs): ######################### def create_acoustic_model(self, - name, - base_model_name, + name: str, + base_model_name: str, *, - description=None, - **kwargs): + description: str = None, + **kwargs) -> 'DetailedResponse': """ Create a custom acoustic model. @@ -2311,9 +2391,9 @@ def create_acoustic_model(self, acoustic model can be used only with the base model for which it is created. The model is owned by the instance of the service whose credentials are used to create it. - You can create a maximum of 1024 custom acoustic models, per credential. The - service returns an error if you attempt to create more than 1024 models. You do - not lose any models, but you cannot create any more until your model count is + You can create a maximum of 1024 custom acoustic models per owning credentials. + The service returns an error if you attempt to create more than 1024 models. You + 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). @@ -2345,8 +2425,9 @@ def create_acoustic_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'create_acoustic_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_acoustic_model') headers.update(sdk_headers) data = { @@ -2359,12 +2440,13 @@ def create_acoustic_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_acoustic_models(self, *, language=None, **kwargs): + def list_acoustic_models(self, *, language: str = None, + **kwargs) -> 'DetailedResponse': """ List custom acoustic models. @@ -2388,8 +2470,9 @@ def list_acoustic_models(self, *, language=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'list_acoustic_models') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_acoustic_models') headers.update(sdk_headers) params = {'language': language} @@ -2398,12 +2481,13 @@ def list_acoustic_models(self, *, language=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def get_acoustic_model(self, customization_id, **kwargs): + def get_acoustic_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Get a custom acoustic model. @@ -2427,20 +2511,20 @@ def get_acoustic_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'get_acoustic_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_acoustic_model') headers.update(sdk_headers) url = '/v1/acoustic_customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_acoustic_model(self, customization_id, **kwargs): + def delete_acoustic_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom acoustic model. @@ -2466,24 +2550,25 @@ def delete_acoustic_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'delete_acoustic_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_acoustic_model') headers.update(sdk_headers) url = '/v1/acoustic_customizations/{0}'.format( *self._encode_path_vars(customization_id)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response def train_acoustic_model(self, - customization_id, + customization_id: str, *, - custom_language_model_id=None, - **kwargs): + custom_language_model_id: str = None, + **kwargs) -> 'DetailedResponse': """ Train a custom acoustic model. @@ -2557,8 +2642,9 @@ def train_acoustic_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'train_acoustic_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='train_acoustic_model') headers.update(sdk_headers) params = {'custom_language_model_id': custom_language_model_id} @@ -2568,12 +2654,13 @@ def train_acoustic_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response - def reset_acoustic_model(self, customization_id, **kwargs): + def reset_acoustic_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Reset a custom acoustic model. @@ -2603,25 +2690,24 @@ def reset_acoustic_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'reset_acoustic_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='reset_acoustic_model') headers.update(sdk_headers) url = '/v1/acoustic_customizations/{0}/reset'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='POST', url=url, headers=headers) + response = self.send(request) return response def upgrade_acoustic_model(self, - customization_id, + customization_id: str, *, - custom_language_model_id=None, - force=None, - **kwargs): + custom_language_model_id: str = None, + force: bool = None, + **kwargs) -> 'DetailedResponse': """ Upgrade a custom acoustic model. @@ -2677,8 +2763,9 @@ def upgrade_acoustic_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'upgrade_acoustic_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='upgrade_acoustic_model') headers.update(sdk_headers) params = { @@ -2691,8 +2778,8 @@ def upgrade_acoustic_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -2700,7 +2787,7 @@ def upgrade_acoustic_model(self, # Custom audio resources ######################### - def list_audio(self, customization_id, **kwargs): + def list_audio(self, customization_id: str, **kwargs) -> 'DetailedResponse': """ List audio resources. @@ -2728,27 +2815,27 @@ def list_audio(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'list_audio') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_audio') headers.update(sdk_headers) url = '/v1/acoustic_customizations/{0}/audio'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response def add_audio(self, - customization_id, - audio_name, - audio_resource, + customization_id: str, + audio_name: str, + audio_resource: BinaryIO, *, - content_type=None, - contained_content_type=None, - allow_overwrite=None, - **kwargs): + content_type: str = None, + contained_content_type: str = None, + allow_overwrite: bool = None, + **kwargs) -> 'DetailedResponse': """ Add an audio resource. @@ -2853,8 +2940,8 @@ def add_audio(self, URL-encoded wherever used, their use is strongly discouraged.) * Do not use the name of an audio resource that has already been added to the custom model. - :param file audio_resource: The audio resource that is to be added to the - custom acoustic model, an individual audio file or an archive file. + :param BinaryIO audio_resource: The audio resource that is to be added to + the custom acoustic model, an individual audio file or an archive file. With the `curl` command, use the `--data-binary` option to upload the file for the request. :param str content_type: (optional) For an audio-type resource, the format @@ -2899,7 +2986,9 @@ def add_audio(self, } if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'add_audio') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_audio') headers.update(sdk_headers) params = {'allow_overwrite': allow_overwrite} @@ -2912,12 +3001,13 @@ def add_audio(self, url=url, headers=headers, params=params, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_audio(self, customization_id, audio_name, **kwargs): + def get_audio(self, customization_id: str, audio_name: str, + **kwargs) -> 'DetailedResponse': """ Get an audio resource. @@ -2961,19 +3051,20 @@ def get_audio(self, customization_id, audio_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'get_audio') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_audio') headers.update(sdk_headers) url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_audio(self, customization_id, audio_name, **kwargs): + def delete_audio(self, customization_id: str, audio_name: str, + **kwargs) -> 'DetailedResponse': """ Delete an audio resource. @@ -3007,15 +3098,17 @@ def delete_audio(self, customization_id, audio_name, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', 'delete_audio') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_audio') headers.update(sdk_headers) url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( *self._encode_path_vars(customization_id, audio_name)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=True) + headers=headers) + response = self.send(request) return response @@ -3023,7 +3116,8 @@ def delete_audio(self, customization_id, audio_name, **kwargs): # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -3050,8 +3144,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('speech_to_text', 'V1', - 'delete_user_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data') headers.update(sdk_headers) params = {'customer_id': customer_id} @@ -3060,8 +3155,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -3095,10 +3190,14 @@ class ModelId(Enum): ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' + IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' @@ -3157,10 +3256,14 @@ class Model(Enum): ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' + IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' @@ -3219,10 +3322,14 @@ class Model(Enum): ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' + IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' @@ -3397,7 +3504,7 @@ class AcousticModel(): (YYYY-MM-DDThh:mm:ss.sTZD). :attr str language: (optional) The language identifier of the custom acoustic model (for example, `en-US`). - :attr list[str] versions: (optional) A list of the available versions of the + :attr List[str] versions: (optional) A list of the available versions of the custom acoustic model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded; otherwise, only a single version is shown. @@ -3429,19 +3536,19 @@ class AcousticModel(): """ def __init__(self, - customization_id, + customization_id: str, *, - created=None, - updated=None, - language=None, - versions=None, - owner=None, - name=None, - description=None, - base_model_name=None, - status=None, - progress=None, - warnings=None): + created: str = None, + updated: str = None, + language: str = None, + versions: List[str] = None, + owner: str = None, + name: str = None, + description: str = None, + base_model_name: str = None, + status: str = None, + progress: int = None, + warnings: str = None) -> None: """ Initialize a AcousticModel object. @@ -3458,7 +3565,7 @@ def __init__(self, format (YYYY-MM-DDThh:mm:ss.sTZD). :param str language: (optional) The language identifier of the custom acoustic model (for example, `en-US`). - :param list[str] versions: (optional) A list of the available versions of + :param List[str] versions: (optional) A list of the available versions of the custom acoustic model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded; otherwise, only a single @@ -3505,7 +3612,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AcousticModel': """Initialize a AcousticModel object from a json dictionary.""" args = {} valid_keys = [ @@ -3548,7 +3655,12 @@ def _from_dict(cls, _dict): args['warnings'] = _dict.get('warnings') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AcousticModel 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, @@ -3579,17 +3691,21 @@ def _to_dict(self): _dict['warnings'] = self.warnings return _dict - def __str__(self): + 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 AcousticModel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AcousticModel') -> 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): + def __ne__(self, other: 'AcousticModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3618,18 +3734,18 @@ class AcousticModels(): """ Information about existing custom acoustic models. - :attr list[AcousticModel] customizations: An array of `AcousticModel` objects + :attr List[AcousticModel] customizations: An array of `AcousticModel` objects that provides information about each available custom acoustic model. The array is empty if the requesting credentials own no custom acoustic models (if no language is specified) or own no custom acoustic models for the specified language. """ - def __init__(self, customizations): + def __init__(self, customizations: List['AcousticModel']) -> None: """ Initialize a AcousticModels object. - :param list[AcousticModel] customizations: An array of `AcousticModel` + :param List[AcousticModel] customizations: An array of `AcousticModel` objects that provides information about each available custom acoustic model. The array is empty if the requesting credentials own no custom acoustic models (if no language is specified) or own no custom acoustic @@ -3638,7 +3754,7 @@ def __init__(self, customizations): self.customizations = customizations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AcousticModels': """Initialize a AcousticModels object from a json dictionary.""" args = {} valid_keys = ['customizations'] @@ -3658,7 +3774,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AcousticModels 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, 'customizations') and self.customizations is not None: @@ -3667,17 +3788,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 AcousticModels object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AcousticModels') -> 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): + def __ne__(self, other: 'AcousticModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3707,10 +3832,10 @@ class AudioDetails(): def __init__(self, *, - type=None, - codec=None, - frequency=None, - compression=None): + type: str = None, + codec: str = None, + frequency: int = None, + compression: str = None) -> None: """ Initialize a AudioDetails object. @@ -3738,7 +3863,7 @@ def __init__(self, self.compression = compression @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioDetails': """Initialize a AudioDetails object from a json dictionary.""" args = {} valid_keys = ['type', 'codec', 'frequency', 'compression'] @@ -3757,7 +3882,12 @@ def _from_dict(cls, _dict): args['compression'] = _dict.get('compression') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioDetails 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: @@ -3770,17 +3900,21 @@ def _to_dict(self): _dict['compression'] = self.compression return _dict - def __str__(self): + 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 AudioDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioDetails') -> 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): + def __ne__(self, other: 'AudioDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3834,7 +3968,7 @@ class AudioListing(): :attr AudioResource container: (optional) **For an archive-type resource,** an object of type `AudioResource` that provides information about the resource. Omitted for an audio-type resource. - :attr list[AudioResource] audio: (optional) **For an archive-type resource,** an + :attr List[AudioResource] audio: (optional) **For an archive-type resource,** an array of `AudioResource` objects that provides information about the audio-type resources that are contained in the resource. Omitted for an audio-type resource. @@ -3842,12 +3976,12 @@ class AudioListing(): def __init__(self, *, - duration=None, - name=None, - details=None, - status=None, - container=None, - audio=None): + duration: int = None, + name: str = None, + details: 'AudioDetails' = None, + status: str = None, + container: 'AudioResource' = None, + audio: List['AudioResource'] = None) -> None: """ Initialize a AudioListing object. @@ -3873,7 +4007,7 @@ def __init__(self, :param AudioResource container: (optional) **For an archive-type resource,** an object of type `AudioResource` that provides information about the resource. Omitted for an audio-type resource. - :param list[AudioResource] audio: (optional) **For an archive-type + :param List[AudioResource] audio: (optional) **For an archive-type resource,** an array of `AudioResource` objects that provides information about the audio-type resources that are contained in the resource. Omitted for an audio-type resource. @@ -3886,7 +4020,7 @@ def __init__(self, self.audio = audio @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioListing': """Initialize a AudioListing object from a json dictionary.""" args = {} valid_keys = [ @@ -3913,7 +4047,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioListing 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, 'duration') and self.duration is not None: @@ -3930,17 +4069,21 @@ def _to_dict(self): _dict['audio'] = [x._to_dict() for x in self.audio] return _dict - def __str__(self): + 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 AudioListing object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioListing') -> 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): + def __ne__(self, other: 'AudioListing') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3975,7 +4118,8 @@ class AudioMetrics(): characteristics of the input audio. """ - def __init__(self, sampling_interval, accumulated): + def __init__(self, sampling_interval: float, + accumulated: 'AudioMetricsDetails') -> None: """ Initialize a AudioMetrics object. @@ -3991,7 +4135,7 @@ def __init__(self, sampling_interval, accumulated): self.accumulated = accumulated @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioMetrics': """Initialize a AudioMetrics object from a json dictionary.""" args = {} valid_keys = ['sampling_interval', 'accumulated'] @@ -4015,7 +4159,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioMetrics 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, @@ -4025,17 +4174,21 @@ def _to_dict(self): _dict['accumulated'] = self.accumulated._to_dict() return _dict - def __str__(self): + 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 AudioMetrics object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioMetrics') -> 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): + def __ne__(self, other: 'AudioMetrics') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4064,10 +4217,10 @@ class AudioMetricsDetails(): spectrum. * A value around 0.5 means that detection of the frequency content is unreliable or not available. - :attr list[AudioMetricsHistogramBin] direct_current_offset: An array of + :attr List[AudioMetricsHistogramBin] direct_current_offset: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the cumulative direct current (DC) component of the audio signal. - :attr list[AudioMetricsHistogramBin] clipping_rate: An array of + :attr List[AudioMetricsHistogramBin] clipping_rate: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the clipping rate for the audio segments. The clipping rate is defined as the fraction of samples in the segment that reach the maximum or minimum value that is offered by the @@ -4075,12 +4228,12 @@ class AudioMetricsDetails(): Modulation(PCM) audio range (-32768 to +32767) or a unit range (-1.0 to +1.0). The clipping rate is between 0.0 and 1.0, with higher values indicating possible degradation of speech recognition. - :attr list[AudioMetricsHistogramBin] speech_level: An array of + :attr List[AudioMetricsHistogramBin] speech_level: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in segments of the audio that contain speech. The signal level is computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range 0.0 (minimum level) to 1.0 (maximum level). - :attr list[AudioMetricsHistogramBin] non_speech_level: An array of + :attr List[AudioMetricsHistogramBin] non_speech_level: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in segments of the audio that do not contain speech. The signal level is computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized @@ -4088,16 +4241,16 @@ class AudioMetricsDetails(): """ def __init__(self, - final, - end_time, - speech_ratio, - high_frequency_loss, - direct_current_offset, - clipping_rate, - speech_level, - non_speech_level, + final: bool, + end_time: float, + speech_ratio: float, + high_frequency_loss: float, + direct_current_offset: List['AudioMetricsHistogramBin'], + clipping_rate: List['AudioMetricsHistogramBin'], + speech_level: List['AudioMetricsHistogramBin'], + non_speech_level: List['AudioMetricsHistogramBin'], *, - signal_to_noise_ratio=None): + signal_to_noise_ratio: float = None) -> None: """ Initialize a AudioMetricsDetails object. @@ -4117,10 +4270,10 @@ def __init__(self, full spectrum. * A value around 0.5 means that detection of the frequency content is unreliable or not available. - :param list[AudioMetricsHistogramBin] direct_current_offset: An array of + :param List[AudioMetricsHistogramBin] direct_current_offset: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the cumulative direct current (DC) component of the audio signal. - :param list[AudioMetricsHistogramBin] clipping_rate: An array of + :param List[AudioMetricsHistogramBin] clipping_rate: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the clipping rate for the audio segments. The clipping rate is defined as the fraction of samples in the segment that reach the maximum or minimum value that is @@ -4128,12 +4281,12 @@ def __init__(self, 16-bit Pulse-Code Modulation(PCM) audio range (-32768 to +32767) or a unit range (-1.0 to +1.0). The clipping rate is between 0.0 and 1.0, with higher values indicating possible degradation of speech recognition. - :param list[AudioMetricsHistogramBin] speech_level: An array of + :param List[AudioMetricsHistogramBin] speech_level: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in segments of the audio that contain speech. The signal level is computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range 0.0 (minimum level) to 1.0 (maximum level). - :param list[AudioMetricsHistogramBin] non_speech_level: An array of + :param List[AudioMetricsHistogramBin] non_speech_level: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in segments of the audio that do not contain speech. The signal level is computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale @@ -4155,7 +4308,7 @@ def __init__(self, self.non_speech_level = non_speech_level @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': """Initialize a AudioMetricsDetails object from a json dictionary.""" args = {} valid_keys = [ @@ -4232,7 +4385,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioMetricsDetails 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, 'final') and self.final is not None: @@ -4264,17 +4422,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 AudioMetricsDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioMetricsDetails') -> 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): + def __ne__(self, other: 'AudioMetricsDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4291,7 +4453,7 @@ class AudioMetricsHistogramBin(): :attr int count: The number of values in the bin of the histogram. """ - def __init__(self, begin, end, count): + def __init__(self, begin: float, end: float, count: int) -> None: """ Initialize a AudioMetricsHistogramBin object. @@ -4304,7 +4466,7 @@ def __init__(self, begin, end, count): self.count = count @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioMetricsHistogramBin': """Initialize a AudioMetricsHistogramBin object from a json dictionary.""" args = {} valid_keys = ['begin', 'end', 'count'] @@ -4333,7 +4495,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioMetricsHistogramBin 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, 'begin') and self.begin is not None: @@ -4344,17 +4511,21 @@ def _to_dict(self): _dict['count'] = self.count return _dict - def __str__(self): + 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 AudioMetricsHistogramBin object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioMetricsHistogramBin') -> 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): + def __ne__(self, other: 'AudioMetricsHistogramBin') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4384,7 +4555,8 @@ class AudioResource(): invalid. """ - def __init__(self, duration, name, details, status): + def __init__(self, duration: int, name: str, details: 'AudioDetails', + status: str) -> None: """ Initialize a AudioResource object. @@ -4414,7 +4586,7 @@ def __init__(self, duration, name, details, status): self.status = status @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioResource': """Initialize a AudioResource object from a json dictionary.""" args = {} valid_keys = ['duration', 'name', 'details', 'status'] @@ -4448,7 +4620,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioResource 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, 'duration') and self.duration is not None: @@ -4461,17 +4638,21 @@ def _to_dict(self): _dict['status'] = self.status return _dict - def __str__(self): + 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 AudioResource object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioResource') -> 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): + def __ne__(self, other: 'AudioResource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4501,12 +4682,13 @@ class AudioResources(): summed over all of the valid audio resources for the custom acoustic model. You can use this value to determine whether the custom model has too little or too much audio to begin training. - :attr list[AudioResource] audio: An array of `AudioResource` objects that + :attr List[AudioResource] audio: An array of `AudioResource` objects that provides information about the audio resources of the custom acoustic model. The array is empty if the custom model has no audio resources. """ - def __init__(self, total_minutes_of_audio, audio): + def __init__(self, total_minutes_of_audio: float, + audio: List['AudioResource']) -> None: """ Initialize a AudioResources object. @@ -4514,7 +4696,7 @@ def __init__(self, total_minutes_of_audio, audio): summed over all of the valid audio resources for the custom acoustic model. You can use this value to determine whether the custom model has too little or too much audio to begin training. - :param list[AudioResource] audio: An array of `AudioResource` objects that + :param List[AudioResource] audio: An array of `AudioResource` objects that provides information about the audio resources of the custom acoustic model. The array is empty if the custom model has no audio resources. """ @@ -4522,7 +4704,7 @@ def __init__(self, total_minutes_of_audio, audio): self.audio = audio @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'AudioResources': """Initialize a AudioResources object from a json dictionary.""" args = {} valid_keys = ['total_minutes_of_audio', 'audio'] @@ -4547,7 +4729,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a AudioResources 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, 'total_minutes_of_audio' @@ -4557,17 +4744,21 @@ def _to_dict(self): _dict['audio'] = [x._to_dict() for x in self.audio] return _dict - def __str__(self): + 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 AudioResources object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'AudioResources') -> 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): + def __ne__(self, other: 'AudioResources') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4576,23 +4767,23 @@ class Corpora(): """ Information about the corpora from a custom language model. - :attr list[Corpus] corpora: An array of `Corpus` objects that provides + :attr List[Corpus] corpora: An array of `Corpus` objects that provides information about the corpora for the custom model. The array is empty if the custom model has no corpora. """ - def __init__(self, corpora): + def __init__(self, corpora: List['Corpus']) -> None: """ Initialize a Corpora object. - :param list[Corpus] corpora: An array of `Corpus` objects that provides + :param List[Corpus] corpora: An array of `Corpus` objects that provides information about the corpora for the custom model. The array is empty if the custom model has no corpora. """ self.corpora = corpora @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Corpora': """Initialize a Corpora object from a json dictionary.""" args = {} valid_keys = ['corpora'] @@ -4610,24 +4801,33 @@ def _from_dict(cls, _dict): 'Required property \'corpora\' not present in Corpora JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Corpora 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, 'corpora') and self.corpora is not None: _dict['corpora'] = [x._to_dict() for x in self.corpora] return _dict - def __str__(self): + 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 Corpora object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Corpora') -> 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): + def __ne__(self, other: 'Corpora') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4654,12 +4854,12 @@ class Corpus(): """ def __init__(self, - name, - total_words, - out_of_vocabulary_words, - status, + name: str, + total_words: int, + out_of_vocabulary_words: int, + status: str, *, - error=None): + error: str = None) -> None: """ Initialize a Corpus object. @@ -4686,7 +4886,7 @@ def __init__(self, self.error = error @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Corpus': """Initialize a Corpus object from a json dictionary.""" args = {} valid_keys = [ @@ -4723,7 +4923,12 @@ def _from_dict(cls, _dict): args['error'] = _dict.get('error') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Corpus 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, 'name') and self.name is not None: @@ -4739,17 +4944,21 @@ def _to_dict(self): _dict['error'] = self.error return _dict - def __str__(self): + 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 Corpus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Corpus') -> 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): + def __ne__(self, other: 'Corpus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4777,7 +4986,7 @@ class CustomWord(): include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the **Add a custom word** method. - :attr list[str] sounds_like: (optional) An array of sounds-like pronunciations + :attr List[str] sounds_like: (optional) An array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. * For a word that is not in the service's base vocabulary, omit the parameter to @@ -4795,7 +5004,11 @@ class CustomWord(): spelling in corpora training data. """ - def __init__(self, *, word=None, sounds_like=None, display_as=None): + def __init__(self, + *, + word: str = None, + sounds_like: List[str] = None, + display_as: str = None) -> None: """ Initialize a CustomWord object. @@ -4804,7 +5017,7 @@ def __init__(self, *, word=None, sounds_like=None, display_as=None): model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the **Add a custom word** method. - :param list[str] sounds_like: (optional) An array of sounds-like + :param List[str] sounds_like: (optional) An array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. * For a word that is not in the service's base vocabulary, omit the @@ -4826,7 +5039,7 @@ def __init__(self, *, word=None, sounds_like=None, display_as=None): self.display_as = display_as @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'CustomWord': """Initialize a CustomWord object from a json dictionary.""" args = {} valid_keys = ['word', 'sounds_like', 'display_as'] @@ -4843,7 +5056,12 @@ def _from_dict(cls, _dict): args['display_as'] = _dict.get('display_as') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a CustomWord 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, 'word') and self.word is not None: @@ -4854,17 +5072,21 @@ def _to_dict(self): _dict['display_as'] = self.display_as return _dict - def __str__(self): + 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 CustomWord object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'CustomWord') -> 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): + def __ne__(self, other: 'CustomWord') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4889,7 +5111,12 @@ class Grammar(): flag to 'true'.`. """ - def __init__(self, name, out_of_vocabulary_words, status, *, error=None): + def __init__(self, + name: str, + out_of_vocabulary_words: int, + status: str, + *, + error: str = None) -> None: """ Initialize a Grammar object. @@ -4915,7 +5142,7 @@ def __init__(self, name, out_of_vocabulary_words, status, *, error=None): self.error = error @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Grammar': """Initialize a Grammar object from a json dictionary.""" args = {} valid_keys = ['name', 'out_of_vocabulary_words', 'status', 'error'] @@ -4945,7 +5172,12 @@ def _from_dict(cls, _dict): args['error'] = _dict.get('error') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Grammar 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, 'name') and self.name is not None: @@ -4959,17 +5191,21 @@ def _to_dict(self): _dict['error'] = self.error return _dict - def __str__(self): + 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 Grammar object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Grammar') -> 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): + def __ne__(self, other: 'Grammar') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4992,23 +5228,23 @@ class Grammars(): """ Information about the grammars from a custom language model. - :attr list[Grammar] grammars: An array of `Grammar` objects that provides + :attr List[Grammar] grammars: An array of `Grammar` objects that provides information about the grammars for the custom model. The array is empty if the custom model has no grammars. """ - def __init__(self, grammars): + def __init__(self, grammars: List['Grammar']) -> None: """ Initialize a Grammars object. - :param list[Grammar] grammars: An array of `Grammar` objects that provides + :param List[Grammar] grammars: An array of `Grammar` objects that provides information about the grammars for the custom model. The array is empty if the custom model has no grammars. """ self.grammars = grammars @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Grammars': """Initialize a Grammars object from a json dictionary.""" args = {} valid_keys = ['grammars'] @@ -5026,24 +5262,33 @@ def _from_dict(cls, _dict): 'Required property \'grammars\' not present in Grammars JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Grammars 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, 'grammars') and self.grammars is not None: _dict['grammars'] = [x._to_dict() for x in self.grammars] return _dict - def __str__(self): + 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 Grammars object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Grammars') -> 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): + def __ne__(self, other: 'Grammars') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5060,7 +5305,8 @@ class KeywordResult(): 0.0 to 1.0. """ - def __init__(self, normalized_text, start_time, end_time, confidence): + def __init__(self, normalized_text: str, start_time: float, end_time: float, + confidence: float) -> None: """ Initialize a KeywordResult object. @@ -5077,7 +5323,7 @@ def __init__(self, normalized_text, start_time, end_time, confidence): self.confidence = confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'KeywordResult': """Initialize a KeywordResult object from a json dictionary.""" args = {} valid_keys = ['normalized_text', 'start_time', 'end_time', 'confidence'] @@ -5112,7 +5358,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a KeywordResult 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, @@ -5126,17 +5377,21 @@ def _to_dict(self): _dict['confidence'] = self.confidence return _dict - def __str__(self): + 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 KeywordResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'KeywordResult') -> 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): + def __ne__(self, other: 'KeywordResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5168,7 +5423,7 @@ class LanguageModel(): models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) Dialect values are case-insensitive. - :attr list[str] versions: (optional) A list of the available versions of the + :attr List[str] versions: (optional) A list of the available versions of the custom language model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded; otherwise, only a single version is shown. @@ -5204,21 +5459,21 @@ class LanguageModel(): """ def __init__(self, - customization_id, + customization_id: str, *, - created=None, - updated=None, - language=None, - dialect=None, - versions=None, - owner=None, - name=None, - description=None, - base_model_name=None, - status=None, - progress=None, - error=None, - warnings=None): + created: str = None, + updated: str = None, + language: str = None, + dialect: str = None, + versions: List[str] = None, + owner: str = None, + name: str = None, + description: str = None, + base_model_name: str = None, + status: str = None, + progress: int = None, + error: str = None, + warnings: str = None) -> None: """ Initialize a LanguageModel object. @@ -5245,7 +5500,7 @@ def __init__(self, `es-PE` models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) Dialect values are case-insensitive. - :param list[str] versions: (optional) A list of the available versions of + :param List[str] versions: (optional) A list of the available versions of the custom language model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded; otherwise, only a single @@ -5299,7 +5554,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LanguageModel': """Initialize a LanguageModel object from a json dictionary.""" args = {} valid_keys = [ @@ -5346,7 +5601,12 @@ def _from_dict(cls, _dict): args['warnings'] = _dict.get('warnings') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LanguageModel 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, @@ -5381,17 +5641,21 @@ def _to_dict(self): _dict['warnings'] = self.warnings return _dict - def __str__(self): + 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 LanguageModel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LanguageModel') -> 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): + def __ne__(self, other: 'LanguageModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5420,18 +5684,18 @@ class LanguageModels(): """ Information about existing custom language models. - :attr list[LanguageModel] customizations: An array of `LanguageModel` objects + :attr List[LanguageModel] customizations: An array of `LanguageModel` objects that provides information about each available custom language model. The array is empty if the requesting credentials own no custom language models (if no language is specified) or own no custom language models for the specified language. """ - def __init__(self, customizations): + def __init__(self, customizations: List['LanguageModel']) -> None: """ Initialize a LanguageModels object. - :param list[LanguageModel] customizations: An array of `LanguageModel` + :param List[LanguageModel] customizations: An array of `LanguageModel` objects that provides information about each available custom language model. The array is empty if the requesting credentials own no custom language models (if no language is specified) or own no custom language @@ -5440,7 +5704,7 @@ def __init__(self, customizations): self.customizations = customizations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'LanguageModels': """Initialize a LanguageModels object from a json dictionary.""" args = {} valid_keys = ['customizations'] @@ -5460,7 +5724,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a LanguageModels 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, 'customizations') and self.customizations is not None: @@ -5469,17 +5738,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 LanguageModels object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'LanguageModels') -> 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): + def __ne__(self, other: 'LanguageModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5511,11 +5784,11 @@ class ProcessedAudio(): """ def __init__(self, - received, - seen_by_engine, - transcription, + received: float, + seen_by_engine: float, + transcription: float, *, - speaker_labels=None): + speaker_labels: float = None) -> None: """ Initialize a ProcessedAudio object. @@ -5549,7 +5822,7 @@ def __init__(self, self.speaker_labels = speaker_labels @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ProcessedAudio': """Initialize a ProcessedAudio object from a json dictionary.""" args = {} valid_keys = [ @@ -5582,7 +5855,12 @@ def _from_dict(cls, _dict): args['speaker_labels'] = _dict.get('speaker_labels') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProcessedAudio 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, 'received') and self.received is not None: @@ -5595,17 +5873,21 @@ def _to_dict(self): _dict['speaker_labels'] = self.speaker_labels return _dict - def __str__(self): + 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 ProcessedAudio object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ProcessedAudio') -> 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): + def __ne__(self, other: 'ProcessedAudio') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5638,8 +5920,9 @@ class ProcessingMetrics(): different results if necessary. """ - def __init__(self, processed_audio, wall_clock_since_first_byte_received, - periodic): + def __init__(self, processed_audio: 'ProcessedAudio', + wall_clock_since_first_byte_received: float, + periodic: bool) -> None: """ Initialize a ProcessingMetrics object. @@ -5669,7 +5952,7 @@ def __init__(self, processed_audio, wall_clock_since_first_byte_received, self.periodic = periodic @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'ProcessingMetrics': """Initialize a ProcessingMetrics object from a json dictionary.""" args = {} valid_keys = [ @@ -5703,7 +5986,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProcessingMetrics 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, @@ -5717,17 +6005,21 @@ def _to_dict(self): _dict['periodic'] = self.periodic return _dict - def __str__(self): + 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 ProcessingMetrics object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'ProcessingMetrics') -> 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): + def __ne__(self, other: 'ProcessingMetrics') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5761,11 +6053,11 @@ class RecognitionJob(): :attr str user_token: (optional) The user token associated with a job that was created with a callback URL and a user token. This field can be returned only by the **Check jobs** method. - :attr list[SpeechRecognitionResults] results: (optional) If the status is + :attr List[SpeechRecognitionResults] results: (optional) If the status is `completed`, the results of the recognition request as an array that includes a single instance of a `SpeechRecognitionResults` object. This field is returned only by the **Check a job** method. - :attr list[str] warnings: (optional) An array of warning messages about invalid + :attr List[str] warnings: (optional) An array of warning messages about invalid parameters included with the request. Each warning includes a descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The @@ -5774,15 +6066,15 @@ class RecognitionJob(): """ def __init__(self, - id, - status, - created, + id: str, + status: str, + created: str, *, - updated=None, - url=None, - user_token=None, - results=None, - warnings=None): + updated: str = None, + url: str = None, + user_token: str = None, + results: List['SpeechRecognitionResults'] = None, + warnings: List[str] = None) -> None: """ Initialize a RecognitionJob object. @@ -5812,11 +6104,11 @@ def __init__(self, :param str user_token: (optional) The user token associated with a job that was created with a callback URL and a user token. This field can be returned only by the **Check jobs** method. - :param list[SpeechRecognitionResults] results: (optional) If the status is + :param List[SpeechRecognitionResults] results: (optional) If the status is `completed`, the results of the recognition request as an array that includes a single instance of a `SpeechRecognitionResults` object. This field is returned only by the **Check a job** method. - :param list[str] warnings: (optional) An array of warning messages about + :param List[str] warnings: (optional) An array of warning messages about invalid parameters included with the request. Each warning includes a descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' @@ -5833,7 +6125,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RecognitionJob': """Initialize a RecognitionJob object from a json dictionary.""" args = {} valid_keys = [ @@ -5877,7 +6169,12 @@ def _from_dict(cls, _dict): args['warnings'] = _dict.get('warnings') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RecognitionJob 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, 'id') and self.id is not None: @@ -5898,17 +6195,21 @@ def _to_dict(self): _dict['warnings'] = self.warnings return _dict - def __str__(self): + 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 RecognitionJob object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RecognitionJob') -> 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): + def __ne__(self, other: 'RecognitionJob') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5936,23 +6237,23 @@ class RecognitionJobs(): """ Information about current asynchronous speech recognition jobs. - :attr list[RecognitionJob] recognitions: An array of `RecognitionJob` objects + :attr List[RecognitionJob] recognitions: An array of `RecognitionJob` objects that provides the status for each of the user's current jobs. The array is empty if the user has no current jobs. """ - def __init__(self, recognitions): + def __init__(self, recognitions: List['RecognitionJob']) -> None: """ Initialize a RecognitionJobs object. - :param list[RecognitionJob] recognitions: An array of `RecognitionJob` + :param List[RecognitionJob] recognitions: An array of `RecognitionJob` objects that provides the status for each of the user's current jobs. The array is empty if the user has no current jobs. """ self.recognitions = recognitions @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RecognitionJobs': """Initialize a RecognitionJobs object from a json dictionary.""" args = {} valid_keys = ['recognitions'] @@ -5972,24 +6273,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RecognitionJobs 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, 'recognitions') and self.recognitions is not None: _dict['recognitions'] = [x._to_dict() for x in self.recognitions] return _dict - def __str__(self): + 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 RecognitionJobs object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RecognitionJobs') -> 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): + def __ne__(self, other: 'RecognitionJobs') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6006,7 +6316,7 @@ class RegisterStatus(): :attr str url: The callback URL that is successfully registered. """ - def __init__(self, status, url): + def __init__(self, status: str, url: str) -> None: """ Initialize a RegisterStatus object. @@ -6020,7 +6330,7 @@ def __init__(self, status, url): self.url = url @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'RegisterStatus': """Initialize a RegisterStatus object from a json dictionary.""" args = {} valid_keys = ['status', 'url'] @@ -6042,7 +6352,12 @@ def _from_dict(cls, _dict): 'Required property \'url\' not present in RegisterStatus JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a RegisterStatus 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, 'status') and self.status is not None: @@ -6051,17 +6366,21 @@ def _to_dict(self): _dict['url'] = self.url return _dict - def __str__(self): + 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 RegisterStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'RegisterStatus') -> 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): + def __ne__(self, other: 'RegisterStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6097,7 +6416,8 @@ class SpeakerLabelsResult(): `false` means that the service might send further updates to the results. """ - def __init__(self, from_, to, speaker, confidence, final): + def __init__(self, from_: float, to: float, speaker: int, confidence: float, + final: bool) -> None: """ Initialize a SpeakerLabelsResult object. @@ -6125,7 +6445,7 @@ def __init__(self, from_, to, speaker, confidence, final): self.final = final @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeakerLabelsResult': """Initialize a SpeakerLabelsResult object from a json dictionary.""" args = {} valid_keys = ['from_', 'from', 'to', 'speaker', 'confidence', 'final'] @@ -6166,7 +6486,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeakerLabelsResult 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, 'from_') and self.from_ is not None: @@ -6181,17 +6506,21 @@ def _to_dict(self): _dict['final'] = self.final return _dict - def __str__(self): + 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 SpeakerLabelsResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeakerLabelsResult') -> 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): + def __ne__(self, other: 'SpeakerLabelsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6211,8 +6540,9 @@ class SpeechModel(): :attr str description: A brief description of the model. """ - def __init__(self, name, language, rate, url, supported_features, - description): + def __init__(self, name: str, language: str, rate: int, url: str, + supported_features: 'SupportedFeatures', + description: str) -> None: """ Initialize a SpeechModel object. @@ -6235,7 +6565,7 @@ def __init__(self, name, language, rate, url, supported_features, self.description = description @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeechModel': """Initialize a SpeechModel object from a json dictionary.""" args = {} valid_keys = [ @@ -6283,7 +6613,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeechModel 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, 'name') and self.name is not None: @@ -6302,17 +6637,21 @@ def _to_dict(self): _dict['description'] = self.description return _dict - def __str__(self): + 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 SpeechModel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeechModel') -> 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): + def __ne__(self, other: 'SpeechModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6321,21 +6660,21 @@ class SpeechModels(): """ Information about the available language models. - :attr list[SpeechModel] models: An array of `SpeechModel` objects that provides + :attr List[SpeechModel] models: An array of `SpeechModel` objects that provides information about each available model. """ - def __init__(self, models): + def __init__(self, models: List['SpeechModel']) -> None: """ Initialize a SpeechModels object. - :param list[SpeechModel] models: An array of `SpeechModel` objects that + :param List[SpeechModel] models: An array of `SpeechModel` objects that provides information about each available model. """ self.models = models @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeechModels': """Initialize a SpeechModels object from a json dictionary.""" args = {} valid_keys = ['models'] @@ -6353,24 +6692,33 @@ def _from_dict(cls, _dict): 'Required property \'models\' not present in SpeechModels JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeechModels 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, 'models') and self.models is not None: _dict['models'] = [x._to_dict() for x in self.models] return _dict - def __str__(self): + 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 SpeechModels object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeechModels') -> 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): + def __ne__(self, other: 'SpeechModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6383,12 +6731,12 @@ class SpeechRecognitionAlternative(): :attr float confidence: (optional) A score that indicates the service's confidence in the transcript in the range of 0.0 to 1.0. A confidence score is returned only for the best alternative and only with results marked as final. - :attr list[str] timestamps: (optional) Time alignments for each word from the + :attr List[str] timestamps: (optional) Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds, for example: `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best alternative. - :attr list[str] word_confidence: (optional) A confidence score for each word of + :attr List[str] word_confidence: (optional) A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0.0 to 1.0, for example: `[["hello",0.95],["world",0.866]]`. Confidence scores are returned only for the @@ -6396,11 +6744,11 @@ class SpeechRecognitionAlternative(): """ def __init__(self, - transcript, + transcript: str, *, - confidence=None, - timestamps=None, - word_confidence=None): + confidence: float = None, + timestamps: List[str] = None, + word_confidence: List[str] = None) -> None: """ Initialize a SpeechRecognitionAlternative object. @@ -6409,12 +6757,12 @@ def __init__(self, confidence in the transcript in the range of 0.0 to 1.0. A confidence score is returned only for the best alternative and only with results marked as final. - :param list[str] timestamps: (optional) Time alignments for each word from + :param List[str] timestamps: (optional) Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds, for example: `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best alternative. - :param list[str] word_confidence: (optional) A confidence score for each + :param List[str] word_confidence: (optional) A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0.0 to 1.0, for example: `[["hello",0.95],["world",0.866]]`. Confidence scores are returned @@ -6426,7 +6774,7 @@ def __init__(self, self.word_confidence = word_confidence @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionAlternative': """Initialize a SpeechRecognitionAlternative object from a json dictionary.""" args = {} valid_keys = [ @@ -6451,7 +6799,12 @@ def _from_dict(cls, _dict): args['word_confidence'] = _dict.get('word_confidence') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeechRecognitionAlternative 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, 'transcript') and self.transcript is not None: @@ -6465,17 +6818,21 @@ def _to_dict(self): _dict['word_confidence'] = self.word_confidence return _dict - def __str__(self): + 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 SpeechRecognitionAlternative object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeechRecognitionAlternative') -> 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): + def __ne__(self, other: 'SpeechRecognitionAlternative') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6487,7 +6844,7 @@ class SpeechRecognitionResult(): :attr bool final: An indication of whether the transcription results are final. If `true`, the results for this utterance are not updated further; no additional results are sent for a `result_index` once its results are indicated as final. - :attr list[SpeechRecognitionAlternative] alternatives: An array of alternative + :attr List[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. :attr dict keywords_result: (optional) A dictionary (or associative array) whose @@ -6497,17 +6854,28 @@ class SpeechRecognitionResult(): `KeywordResult` object. A keyword for which no matches are found is omitted from the dictionary. The dictionary is omitted entirely if no matches are found for any keywords. - :attr list[WordAlternativeResults] word_alternatives: (optional) An array of + :attr List[WordAlternativeResults] word_alternatives: (optional) An array of alternative hypotheses found for words of the input audio if a `word_alternatives_threshold` is specified. + :attr str end_of_utterance: (optional) If the `split_transcript_at_phrase_end` + parameter is `true`, describes the reason for the split: + * `end_of_data` - The end of the input audio stream. + * `full_stop` - A full semantic stop, such as for the conclusion of a + grammatical sentence. The insertion of splits is influenced by the base language + model and biased by custom language models and grammars. + * `reset` - The amount of audio that is currently being processed exceeds the + two-minute maximum. The service splits the transcript to avoid excessive memory + use. + * `silence` - A pause or silence that is at least as long as the pause interval. """ def __init__(self, - final, - alternatives, + final: bool, + alternatives: List['SpeechRecognitionAlternative'], *, - keywords_result=None, - word_alternatives=None): + keywords_result: dict = None, + word_alternatives: List['WordAlternativeResults'] = None, + end_of_utterance: str = None) -> None: """ Initialize a SpeechRecognitionResult object. @@ -6515,7 +6883,7 @@ def __init__(self, final. If `true`, the results for this utterance are not updated further; no additional results are sent for a `result_index` once its results are indicated as final. - :param list[SpeechRecognitionAlternative] alternatives: An array of + :param List[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. :param dict keywords_result: (optional) A dictionary (or associative array) @@ -6525,21 +6893,35 @@ def __init__(self, by a `KeywordResult` object. A keyword for which no matches are found is omitted from the dictionary. The dictionary is omitted entirely if no matches are found for any keywords. - :param list[WordAlternativeResults] word_alternatives: (optional) An array + :param List[WordAlternativeResults] word_alternatives: (optional) An array of alternative hypotheses found for words of the input audio if a `word_alternatives_threshold` is specified. + :param str end_of_utterance: (optional) If the + `split_transcript_at_phrase_end` parameter is `true`, describes the reason + for the split: + * `end_of_data` - The end of the input audio stream. + * `full_stop` - A full semantic stop, such as for the conclusion of a + grammatical sentence. The insertion of splits is influenced by the base + language model and biased by custom language models and grammars. + * `reset` - The amount of audio that is currently being processed exceeds + the two-minute maximum. The service splits the transcript to avoid + excessive memory use. + * `silence` - A pause or silence that is at least as long as the pause + interval. """ self.final = final self.alternatives = alternatives self.keywords_result = keywords_result self.word_alternatives = word_alternatives + self.end_of_utterance = end_of_utterance @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': """Initialize a SpeechRecognitionResult object from a json dictionary.""" args = {} valid_keys = [ - 'final', 'alternatives', 'keywords_result', 'word_alternatives' + 'final', 'alternatives', 'keywords_result', 'word_alternatives', + 'end_of_utterance' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -6568,9 +6950,16 @@ def _from_dict(cls, _dict): WordAlternativeResults._from_dict(x) for x in (_dict.get('word_alternatives')) ] + if 'end_of_utterance' in _dict: + args['end_of_utterance'] = _dict.get('end_of_utterance') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeechRecognitionResult 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, 'final') and self.final is not None: @@ -6585,28 +6974,53 @@ def _to_dict(self): _dict['word_alternatives'] = [ x._to_dict() for x in self.word_alternatives ] + if hasattr(self, + 'end_of_utterance') and self.end_of_utterance is not None: + _dict['end_of_utterance'] = self.end_of_utterance return _dict - def __str__(self): + 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 SpeechRecognitionResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeechRecognitionResult') -> 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): + def __ne__(self, other: 'SpeechRecognitionResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class EndOfUtteranceEnum(Enum): + """ + If the `split_transcript_at_phrase_end` parameter is `true`, describes the reason + for the split: + * `end_of_data` - The end of the input audio stream. + * `full_stop` - A full semantic stop, such as for the conclusion of a grammatical + sentence. The insertion of splits is influenced by the base language model and + biased by custom language models and grammars. + * `reset` - The amount of audio that is currently being processed exceeds the + two-minute maximum. The service splits the transcript to avoid excessive memory + use. + * `silence` - A pause or silence that is at least as long as the pause interval. + """ + END_OF_DATA = "end_of_data" + FULL_STOP = "full_stop" + RESET = "reset" + SILENCE = "silence" + class SpeechRecognitionResults(): """ The complete results for a speech recognition request. - :attr list[SpeechRecognitionResult] results: (optional) An array of + :attr List[SpeechRecognitionResult] results: (optional) An array of `SpeechRecognitionResult` objects that can include interim and final results (interim results are returned only if supported by the method). Final results are guaranteed not to change; interim results might be replaced by further @@ -6616,7 +7030,7 @@ class SpeechRecognitionResults(): :attr int result_index: (optional) An index that indicates a change point in the `results` array. The service increments the index only for additional results that it sends for new audio for the same request. - :attr list[SpeakerLabelsResult] speaker_labels: (optional) An array of + :attr List[SpeakerLabelsResult] speaker_labels: (optional) An array of `SpeakerLabelsResult` objects that identifies which words were spoken by which speakers in a multi-person exchange. The array is returned only if the `speaker_labels` parameter is `true`. When interim results are also requested @@ -6628,7 +7042,7 @@ class SpeechRecognitionResults(): method. :attr AudioMetrics audio_metrics: (optional) If audio metrics are requested, information about the signal characteristics of the input audio. - :attr list[str] warnings: (optional) An array of warning messages associated + :attr List[str] warnings: (optional) An array of warning messages associated with the request: * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown arguments:"` or @@ -6646,16 +7060,16 @@ class SpeechRecognitionResults(): def __init__(self, *, - results=None, - result_index=None, - speaker_labels=None, - processing_metrics=None, - audio_metrics=None, - warnings=None): + results: List['SpeechRecognitionResult'] = None, + result_index: int = None, + speaker_labels: List['SpeakerLabelsResult'] = None, + processing_metrics: 'ProcessingMetrics' = None, + audio_metrics: 'AudioMetrics' = None, + warnings: List[str] = None) -> None: """ Initialize a SpeechRecognitionResults object. - :param list[SpeechRecognitionResult] results: (optional) An array of + :param List[SpeechRecognitionResult] results: (optional) An array of `SpeechRecognitionResult` objects that can include interim and final results (interim results are returned only if supported by the method). Final results are guaranteed not to change; interim results might be @@ -6666,7 +7080,7 @@ def __init__(self, :param int result_index: (optional) An index that indicates a change point in the `results` array. The service increments the index only for additional results that it sends for new audio for the same request. - :param list[SpeakerLabelsResult] speaker_labels: (optional) An array of + :param List[SpeakerLabelsResult] speaker_labels: (optional) An array of `SpeakerLabelsResult` objects that identifies which words were spoken by which speakers in a multi-person exchange. The array is returned only if the `speaker_labels` parameter is `true`. When interim results are also @@ -6679,7 +7093,7 @@ def __init__(self, **Recognize audio** method. :param AudioMetrics audio_metrics: (optional) If audio metrics are requested, information about the signal characteristics of the input audio. - :param list[str] warnings: (optional) An array of warning messages + :param List[str] warnings: (optional) An array of warning messages associated with the request: * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown @@ -6702,7 +7116,7 @@ def __init__(self, self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResults': """Initialize a SpeechRecognitionResults object from a json dictionary.""" args = {} valid_keys = [ @@ -6736,7 +7150,12 @@ def _from_dict(cls, _dict): args['warnings'] = _dict.get('warnings') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeechRecognitionResults 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, 'results') and self.results is not None: @@ -6757,17 +7176,21 @@ def _to_dict(self): _dict['warnings'] = self.warnings return _dict - def __str__(self): + 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 SpeechRecognitionResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SpeechRecognitionResults') -> 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): + def __ne__(self, other: 'SpeechRecognitionResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6782,7 +7205,8 @@ class SupportedFeatures(): be used with the language model. """ - def __init__(self, custom_language_model, speaker_labels): + def __init__(self, custom_language_model: bool, + speaker_labels: bool) -> None: """ Initialize a SupportedFeatures object. @@ -6796,7 +7220,7 @@ def __init__(self, custom_language_model, speaker_labels): self.speaker_labels = speaker_labels @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} valid_keys = ['custom_language_model', 'speaker_labels'] @@ -6819,7 +7243,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SupportedFeatures 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, 'custom_language_model' @@ -6829,17 +7258,21 @@ def _to_dict(self): _dict['speaker_labels'] = self.speaker_labels return _dict - def __str__(self): + 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 SupportedFeatures object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SupportedFeatures') -> 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): + def __ne__(self, other: 'SupportedFeatures') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6848,18 +7281,18 @@ class TrainingResponse(): """ The response from training of a custom language or custom acoustic model. - :attr list[TrainingWarning] warnings: (optional) An array of `TrainingWarning` + :attr List[TrainingWarning] warnings: (optional) An array of `TrainingWarning` objects that lists any invalid resources contained in the custom model. For custom language models, invalid resources are grouped and identified by type of resource. The method can return warnings only if the `strict` parameter is set to `false`. """ - def __init__(self, *, warnings=None): + def __init__(self, *, warnings: List['TrainingWarning'] = None) -> None: """ Initialize a TrainingResponse object. - :param list[TrainingWarning] warnings: (optional) An array of + :param List[TrainingWarning] warnings: (optional) An array of `TrainingWarning` objects that lists any invalid resources contained in the custom model. For custom language models, invalid resources are grouped and identified by type of resource. The method can return warnings only if the @@ -6868,7 +7301,7 @@ def __init__(self, *, warnings=None): self.warnings = warnings @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingResponse': """Initialize a TrainingResponse object from a json dictionary.""" args = {} valid_keys = ['warnings'] @@ -6883,24 +7316,33 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingResponse 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, 'warnings') and self.warnings is not None: _dict['warnings'] = [x._to_dict() for x in self.warnings] return _dict - def __str__(self): + 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 TrainingResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingResponse') -> 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): + def __ne__(self, other: 'TrainingResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6918,7 +7360,7 @@ class TrainingWarning(): training.`. """ - def __init__(self, code, message): + def __init__(self, code: str, message: str) -> None: """ Initialize a TrainingWarning object. @@ -6934,7 +7376,7 @@ def __init__(self, code, message): self.message = message @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'TrainingWarning': """Initialize a TrainingWarning object from a json dictionary.""" args = {} valid_keys = ['code', 'message'] @@ -6957,7 +7399,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingWarning 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, 'code') and self.code is not None: @@ -6966,17 +7413,21 @@ def _to_dict(self): _dict['message'] = self.message return _dict - def __str__(self): + 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 TrainingWarning object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'TrainingWarning') -> 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): + def __ne__(self, other: 'TrainingWarning') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6996,7 +7447,7 @@ class Word(): :attr str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :attr list[str] sounds_like: An array of pronunciations for the word. The array + :attr List[str] sounds_like: An array of pronunciations for the word. The array can include the sounds-like pronunciation automatically generated by the service if none is provided for the word; the service adds this pronunciation when it finishes processing the word. @@ -7010,30 +7461,30 @@ class Word(): it is added by any corpora, the count begins at `1`; if the word is added from a corpus first and later modified, the count reflects only the number of times it is found in corpora. - :attr list[str] source: An array of sources that describes how the word was + :attr List[str] source: An array of sources that describes how the word was added to the custom model's words resource. For OOV words added from a corpus, includes the name of the corpus; if the word was added by multiple corpora, the names of all corpora are listed. If the word was modified or added by the user directly, the field includes the string `user`. - :attr list[WordError] error: (optional) If the service discovered one or more + :attr List[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. """ def __init__(self, - word, - sounds_like, - display_as, - count, - source, + word: str, + sounds_like: List[str], + display_as: str, + count: int, + source: List[str], *, - error=None): + error: List['WordError'] = None) -> None: """ Initialize a Word object. :param str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :param list[str] sounds_like: An array of pronunciations for the word. The + :param List[str] sounds_like: An array of pronunciations for the word. The array can include the sounds-like pronunciation automatically generated by the service if none is provided for the word; the service adds this pronunciation when it finishes processing the word. @@ -7047,12 +7498,12 @@ def __init__(self, before it is added by any corpora, the count begins at `1`; if the word is added from a corpus first and later modified, the count reflects only the number of times it is found in corpora. - :param list[str] source: An array of sources that describes how the word + :param List[str] source: An array of sources that describes how the word was added to the custom model's words resource. For OOV words added from a corpus, includes the name of the corpus; if the word was added by multiple corpora, the names of all corpora are listed. If the word was modified or added by the user directly, the field includes the string `user`. - :param list[WordError] error: (optional) If the service discovered one or + :param List[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. """ @@ -7064,7 +7515,7 @@ def __init__(self, self.error = error @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} valid_keys = [ @@ -7106,7 +7557,12 @@ def _from_dict(cls, _dict): ] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Word 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, 'word') and self.word is not None: @@ -7123,17 +7579,21 @@ def _to_dict(self): _dict['error'] = [x._to_dict() for x in self.error] return _dict - def __str__(self): + 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 Word object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Word') -> 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): + def __ne__(self, other: 'Word') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7147,7 +7607,7 @@ class WordAlternativeResult(): :attr str word: An alternative hypothesis for a word from the input audio. """ - def __init__(self, confidence, word): + def __init__(self, confidence: float, word: str) -> None: """ Initialize a WordAlternativeResult object. @@ -7159,7 +7619,7 @@ def __init__(self, confidence, word): self.word = word @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordAlternativeResult': """Initialize a WordAlternativeResult object from a json dictionary.""" args = {} valid_keys = ['confidence', 'word'] @@ -7182,7 +7642,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordAlternativeResult 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, 'confidence') and self.confidence is not None: @@ -7191,17 +7656,21 @@ def _to_dict(self): _dict['word'] = self.word return _dict - def __str__(self): + 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 WordAlternativeResult object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordAlternativeResult') -> 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): + def __ne__(self, other: 'WordAlternativeResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7214,11 +7683,12 @@ class WordAlternativeResults(): audio that corresponds to the word alternatives. :attr float end_time: The end time in seconds of the word from the input audio that corresponds to the word alternatives. - :attr list[WordAlternativeResult] alternatives: An array of alternative + :attr List[WordAlternativeResult] alternatives: An array of alternative hypotheses for a word from the input audio. """ - def __init__(self, start_time, end_time, alternatives): + def __init__(self, start_time: float, end_time: float, + alternatives: List['WordAlternativeResult']) -> None: """ Initialize a WordAlternativeResults object. @@ -7226,7 +7696,7 @@ def __init__(self, start_time, end_time, alternatives): input audio that corresponds to the word alternatives. :param float end_time: The end time in seconds of the word from the input audio that corresponds to the word alternatives. - :param list[WordAlternativeResult] alternatives: An array of alternative + :param List[WordAlternativeResult] alternatives: An array of alternative hypotheses for a word from the input audio. """ self.start_time = start_time @@ -7234,7 +7704,7 @@ def __init__(self, start_time, end_time, alternatives): self.alternatives = alternatives @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordAlternativeResults': """Initialize a WordAlternativeResults object from a json dictionary.""" args = {} valid_keys = ['start_time', 'end_time', 'alternatives'] @@ -7266,7 +7736,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordAlternativeResults 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, 'start_time') and self.start_time is not None: @@ -7277,17 +7752,21 @@ def _to_dict(self): _dict['alternatives'] = [x._to_dict() for x in self.alternatives] return _dict - def __str__(self): + 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 WordAlternativeResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordAlternativeResults') -> 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): + def __ne__(self, other: 'WordAlternativeResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7305,7 +7784,7 @@ class WordError(): '{suggested_string}'."`. """ - def __init__(self, element): + def __init__(self, element: str) -> None: """ Initialize a WordError object. @@ -7320,7 +7799,7 @@ def __init__(self, element): self.element = element @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'WordError': """Initialize a WordError object from a json dictionary.""" args = {} valid_keys = ['element'] @@ -7336,24 +7815,33 @@ def _from_dict(cls, _dict): 'Required property \'element\' not present in WordError JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a WordError 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, 'element') and self.element is not None: _dict['element'] = self.element return _dict - def __str__(self): + 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 WordError object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'WordError') -> 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): + def __ne__(self, other: 'WordError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -7362,23 +7850,23 @@ class Words(): """ Information about the words from a custom language model. - :attr list[Word] words: An array of `Word` objects that provides information + :attr List[Word] words: An array of `Word` objects that provides information about each word in the custom model's words resource. The array is empty if the custom model has no words. """ - def __init__(self, words): + def __init__(self, words: List['Word']) -> None: """ Initialize a Words object. - :param list[Word] words: An array of `Word` objects that provides + :param List[Word] words: An array of `Word` objects that provides information about each word in the custom model's words resource. The array is empty if the custom model has no words. """ self.words = words @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} valid_keys = ['words'] @@ -7394,23 +7882,32 @@ def _from_dict(cls, _dict): 'Required property \'words\' not present in Words JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Words 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, 'words') and self.words is not None: _dict['words'] = [x._to_dict() for x in self.words] return _dict - def __str__(self): + 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 Words object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Words') -> 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): + def __ne__(self, other: 'Words') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index dd02220d8..c3a534087 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,592 +1,3120 @@ -# coding=utf-8 -import os +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json +import pytest import responses -import ibm_watson -from ibm_watson.speech_to_text_v1 import CustomWord -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - - -@responses.activate -def test_success(): - models_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/models' - models_response = '{"models": [{"url": "https://stream.watsonplatform.net/speech-to-text/api/v1/models/' \ - 'WatsonModel", "rate": 16000, "name": "WatsonModel", "language": "en-US", "description": ' \ - '"Watson model \'v7w_134k.3\' for Attila 2-5 reco engine."}]}' - - responses.add( - responses.GET, - models_url, - body=models_response, - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - speech_to_text.list_models() - - assert responses.calls[0].request.url == models_url - assert responses.calls[0].response.text == models_response - - recognize_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize' - recognize_response = '{"results":[{"alternatives":[{"transcript":"thunderstorms could produce large hail ' \ - 'isolated tornadoes and heavy rain "}],"final":true}],"result_index":0}' - - responses.add( - responses.POST, - recognize_url, - body=recognize_response, - status=200, - content_type='application/json') - - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: - speech_to_text.recognize( - audio=audio_file, content_type='audio/l16; rate=44100') - - request_url = responses.calls[1].request.url - assert request_url == recognize_url - assert responses.calls[1].response.text == recognize_response - - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: - speech_to_text.recognize( - audio=audio_file, customization_id='x', content_type='audio/l16; rate=44100') - expected_url = "{0}?customization_id=x".format(recognize_url) - assert expected_url == responses.calls[2].request.url - assert len(responses.calls) == 3 - - -@responses.activate -def test_get_model(): - model_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/models/modelid' - responses.add( - responses.GET, - model_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - speech_to_text.get_model(model_id='modelid') - assert len(responses.calls) == 1 - - -def _decode_body(body): +import tempfile +import ibm_watson.speech_to_text_v1 +from ibm_watson.speech_to_text_v1 import * + +base_url = 'https://stream.watsonplatform.net/speech-to-text/api' + +############################################################################## +# Start of Service: Models +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_models +#----------------------------------------------------------------------------- +class TestListModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_response(self): + body = self.construct_full_body() + response = fake_response_SpeechModels_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_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_SpeechModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/models' + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_models(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_model +#----------------------------------------------------------------------------- +class TestGetModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_response(self): + body = self.construct_full_body() + response = fake_response_SpeechModel_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_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_SpeechModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_empty(self): + check_empty_required_params(self, fake_response_SpeechModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/models/{0}'.format(body['model_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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['model_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['model_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Models +############################################################################## + +############################################################################## +# Start of Service: Synchronous +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for recognize +#----------------------------------------------------------------------------- +class TestRecognize(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_recognize_response(self): + body = self.construct_full_body() + response = fake_response_SpeechRecognitionResults_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_recognize_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_SpeechRecognitionResults_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_recognize_empty(self): + check_empty_required_params( + self, fake_response_SpeechRecognitionResults_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/recognize' + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.recognize(**body) + return output + + def construct_full_body(self): + body = dict() + body['audio'] = tempfile.NamedTemporaryFile() + body['content_type'] = "string1" + body['model'] = "string1" + body['language_customization_id'] = "string1" + body['acoustic_customization_id'] = "string1" + body['base_model_version'] = "string1" + body['customization_weight'] = 12345.0 + body['inactivity_timeout'] = 12345 + body['keywords'] = [] + body['keywords_threshold'] = 12345.0 + body['max_alternatives'] = 12345 + body['word_alternatives_threshold'] = 12345.0 + body['word_confidence'] = True + body['timestamps'] = True + body['profanity_filter'] = True + body['smart_formatting'] = True + body['speaker_labels'] = True + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + body['redaction'] = True + body['audio_metrics'] = True + body['end_of_phrase_silence_time'] = 12345.0 + body['split_transcript_at_phrase_end'] = True + return body + + def construct_required_body(self): + body = dict() + body['audio'] = tempfile.NamedTemporaryFile() + return body + + +# endregion +############################################################################## +# End of Service: Synchronous +############################################################################## + +############################################################################## +# Start of Service: Asynchronous +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for register_callback +#----------------------------------------------------------------------------- +class TestRegisterCallback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_register_callback_response(self): + body = self.construct_full_body() + response = fake_response_RegisterStatus_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_register_callback_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_RegisterStatus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_register_callback_empty(self): + check_empty_required_params(self, fake_response_RegisterStatus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/register_callback' + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.register_callback(**body) + return output + + def construct_full_body(self): + body = dict() + body['callback_url'] = "string1" + body['user_secret'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['callback_url'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for unregister_callback +#----------------------------------------------------------------------------- +class TestUnregisterCallback(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_unregister_callback_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_unregister_callback_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_unregister_callback_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 = '/v1/unregister_callback' + 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='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.unregister_callback(**body) + return output + + def construct_full_body(self): + body = dict() + body['callback_url'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['callback_url'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_job +#----------------------------------------------------------------------------- +class TestCreateJob(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_job_response(self): + body = self.construct_full_body() + response = fake_response_RecognitionJob_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_create_job_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_RecognitionJob_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_job_empty(self): + check_empty_required_params(self, fake_response_RecognitionJob_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/recognitions' + 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=201, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.create_job(**body) + return output + + def construct_full_body(self): + body = dict() + body['audio'] = tempfile.NamedTemporaryFile() + body['content_type'] = "string1" + body['model'] = "string1" + body['callback_url'] = "string1" + body['events'] = "string1" + body['user_token'] = "string1" + body['results_ttl'] = 12345 + body['language_customization_id'] = "string1" + body['acoustic_customization_id'] = "string1" + body['base_model_version'] = "string1" + body['customization_weight'] = 12345.0 + body['inactivity_timeout'] = 12345 + body['keywords'] = [] + body['keywords_threshold'] = 12345.0 + body['max_alternatives'] = 12345 + body['word_alternatives_threshold'] = 12345.0 + body['word_confidence'] = True + body['timestamps'] = True + body['profanity_filter'] = True + body['smart_formatting'] = True + body['speaker_labels'] = True + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + body['redaction'] = True + body['processing_metrics'] = True + body['processing_metrics_interval'] = 12345.0 + body['audio_metrics'] = True + body['end_of_phrase_silence_time'] = 12345.0 + body['split_transcript_at_phrase_end'] = True + return body + + def construct_required_body(self): + body = dict() + body['audio'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for check_jobs +#----------------------------------------------------------------------------- +class TestCheckJobs(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_check_jobs_response(self): + body = self.construct_full_body() + response = fake_response_RecognitionJobs_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_check_jobs_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_RecognitionJobs_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_check_jobs_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/recognitions' + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.check_jobs(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for check_job +#----------------------------------------------------------------------------- +class TestCheckJob(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_check_job_response(self): + body = self.construct_full_body() + response = fake_response_RecognitionJob_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_check_job_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_RecognitionJob_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_check_job_empty(self): + check_empty_required_params(self, fake_response_RecognitionJob_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/recognitions/{0}'.format(body['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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.check_job(**body) + return output + + def construct_full_body(self): + body = dict() + body['id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_job +#----------------------------------------------------------------------------- +class TestDeleteJob(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_job_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_job_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_job_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 = '/v1/recognitions/{0}'.format(body['id']) + 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=204, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_job(**body) + return output + + def construct_full_body(self): + body = dict() + body['id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Asynchronous +############################################################################## + +############################################################################## +# Start of Service: CustomLanguageModels +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for create_language_model +#----------------------------------------------------------------------------- +class TestCreateLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_language_model_response(self): + body = self.construct_full_body() + response = fake_response_LanguageModel_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_create_language_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LanguageModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_language_model_empty(self): + check_empty_required_params(self, fake_response_LanguageModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations' + 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=201, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.create_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "name": "string1", + "base_model_name": "string1", + "dialect": "string1", + "description": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body.update({ + "name": "string1", + "base_model_name": "string1", + "dialect": "string1", + "description": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_language_models +#----------------------------------------------------------------------------- +class TestListLanguageModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_language_models_response(self): + body = self.construct_full_body() + response = fake_response_LanguageModels_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_language_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LanguageModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_language_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations' + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_language_models(**body) + return output + + def construct_full_body(self): + body = dict() + body['language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_language_model +#----------------------------------------------------------------------------- +class TestGetLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_language_model_response(self): + body = self.construct_full_body() + response = fake_response_LanguageModel_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_language_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LanguageModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_language_model_empty(self): + check_empty_required_params(self, fake_response_LanguageModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}'.format(body['customization_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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_language_model +#----------------------------------------------------------------------------- +class TestDeleteLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_language_model_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_language_model_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_language_model_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 = '/v1/customizations/{0}'.format(body['customization_id']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for train_language_model +#----------------------------------------------------------------------------- +class TestTrainLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_train_language_model_response(self): + body = self.construct_full_body() + response = fake_response_TrainingResponse_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_train_language_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_train_language_model_empty(self): + check_empty_required_params(self, fake_response_TrainingResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/train'.format( + body['customization_id']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.train_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_type_to_add'] = "string1" + body['customization_weight'] = 12345.0 + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for reset_language_model +#----------------------------------------------------------------------------- +class TestResetLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_reset_language_model_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_reset_language_model_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_reset_language_model_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 = '/v1/customizations/{0}/reset'.format( + body['customization_id']) + 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='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.reset_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for upgrade_language_model +#----------------------------------------------------------------------------- +class TestUpgradeLanguageModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_upgrade_language_model_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_upgrade_language_model_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_upgrade_language_model_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 = '/v1/customizations/{0}/upgrade_model'.format( + body['customization_id']) + 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='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.upgrade_language_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomLanguageModels +############################################################################## + +############################################################################## +# Start of Service: CustomCorpora +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_corpora +#----------------------------------------------------------------------------- +class TestListCorpora(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_corpora_response(self): + body = self.construct_full_body() + response = fake_response_Corpora_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_corpora_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Corpora_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_corpora_empty(self): + check_empty_required_params(self, fake_response_Corpora_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/corpora'.format( + body['customization_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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_corpora(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_corpus +#----------------------------------------------------------------------------- +class TestAddCorpus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_corpus_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_add_corpus_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_add_corpus_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 = '/v1/customizations/{0}/corpora/{1}'.format( + body['customization_id'], body['corpus_name']) + 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=201, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_corpus(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + body['corpus_file'] = tempfile.NamedTemporaryFile() + body['allow_overwrite'] = True + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + body['corpus_file'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_corpus +#----------------------------------------------------------------------------- +class TestGetCorpus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_corpus_response(self): + body = self.construct_full_body() + response = fake_response_Corpus_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_corpus_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Corpus_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_corpus_empty(self): + check_empty_required_params(self, fake_response_Corpus_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/corpora/{1}'.format( + body['customization_id'], body['corpus_name']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_corpus(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_corpus +#----------------------------------------------------------------------------- +class TestDeleteCorpus(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_corpus_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_corpus_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_corpus_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 = '/v1/customizations/{0}/corpora/{1}'.format( + body['customization_id'], body['corpus_name']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_corpus(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['corpus_name'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomCorpora +############################################################################## + +############################################################################## +# Start of Service: CustomWords +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_words +#----------------------------------------------------------------------------- +class TestListWords(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_words_response(self): + body = self.construct_full_body() + response = fake_response_Words_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_words_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Words_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_words_empty(self): + check_empty_required_params(self, fake_response_Words_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words'.format( + body['customization_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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_words(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_type'] = "string1" + body['sort'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_words +#----------------------------------------------------------------------------- +class TestAddWords(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_words_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_add_words_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_add_words_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 = '/v1/customizations/{0}/words'.format( + body['customization_id']) + 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=201, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_words(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "words": [], + }) + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "words": [], + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_word +#----------------------------------------------------------------------------- +class TestAddWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_word_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_add_word_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_add_word_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 = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word_name']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=201, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + body.update({ + "word": "string1", + "sounds_like": [], + "display_as": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + body.update({ + "word": "string1", + "sounds_like": [], + "display_as": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_word +#----------------------------------------------------------------------------- +class TestGetWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_word_response(self): + body = self.construct_full_body() + response = fake_response_Word_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_word_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Word_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_word_empty(self): + check_empty_required_params(self, fake_response_Word_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word_name']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_word +#----------------------------------------------------------------------------- +class TestDeleteWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_word_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_word_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_word_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 = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word_name']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word_name'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomWords +############################################################################## + +############################################################################## +# Start of Service: CustomGrammars +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_grammars +#----------------------------------------------------------------------------- +class TestListGrammars(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_grammars_response(self): + body = self.construct_full_body() + response = fake_response_Grammars_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_grammars_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Grammars_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_grammars_empty(self): + check_empty_required_params(self, fake_response_Grammars_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/grammars'.format( + body['customization_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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_grammars(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_grammar +#----------------------------------------------------------------------------- +class TestAddGrammar(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_grammar_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_add_grammar_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_add_grammar_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 = '/v1/customizations/{0}/grammars/{1}'.format( + body['customization_id'], body['grammar_name']) + 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=201, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_grammar(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + body['grammar_file'] = "string1" + body['content_type'] = "string1" + body['allow_overwrite'] = True + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + body['grammar_file'] = "string1" + body['content_type'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_grammar +#----------------------------------------------------------------------------- +class TestGetGrammar(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_grammar_response(self): + body = self.construct_full_body() + response = fake_response_Grammar_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_grammar_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Grammar_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_grammar_empty(self): + check_empty_required_params(self, fake_response_Grammar_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/grammars/{1}'.format( + body['customization_id'], body['grammar_name']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_grammar(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_grammar +#----------------------------------------------------------------------------- +class TestDeleteGrammar(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_grammar_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_grammar_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_grammar_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 = '/v1/customizations/{0}/grammars/{1}'.format( + body['customization_id'], body['grammar_name']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_grammar(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['grammar_name'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomGrammars +############################################################################## + +############################################################################## +# Start of Service: CustomAcousticModels +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for create_acoustic_model +#----------------------------------------------------------------------------- +class TestCreateAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_acoustic_model_response(self): + body = self.construct_full_body() + response = fake_response_AcousticModel_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_create_acoustic_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AcousticModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_acoustic_model_empty(self): + check_empty_required_params(self, fake_response_AcousticModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations' + 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=201, + content_type='application/json') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.create_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "name": "string1", + "base_model_name": "string1", + "description": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body.update({ + "name": "string1", + "base_model_name": "string1", + "description": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_acoustic_models +#----------------------------------------------------------------------------- +class TestListAcousticModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_acoustic_models_response(self): + body = self.construct_full_body() + response = fake_response_AcousticModels_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_acoustic_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AcousticModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_acoustic_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations' + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_acoustic_models(**body) + return output + + def construct_full_body(self): + body = dict() + body['language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_acoustic_model +#----------------------------------------------------------------------------- +class TestGetAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_acoustic_model_response(self): + body = self.construct_full_body() + response = fake_response_AcousticModel_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_acoustic_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AcousticModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_acoustic_model_empty(self): + check_empty_required_params(self, fake_response_AcousticModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}'.format( + body['customization_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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_acoustic_model +#----------------------------------------------------------------------------- +class TestDeleteAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_acoustic_model_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_acoustic_model_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_acoustic_model_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 = '/v1/acoustic_customizations/{0}'.format( + body['customization_id']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for train_acoustic_model +#----------------------------------------------------------------------------- +class TestTrainAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_train_acoustic_model_response(self): + body = self.construct_full_body() + response = fake_response_TrainingResponse_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_train_acoustic_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_TrainingResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_train_acoustic_model_empty(self): + check_empty_required_params(self, fake_response_TrainingResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}/train'.format( + body['customization_id']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.train_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['custom_language_model_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for reset_acoustic_model +#----------------------------------------------------------------------------- +class TestResetAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_reset_acoustic_model_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_reset_acoustic_model_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_reset_acoustic_model_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 = '/v1/acoustic_customizations/{0}/reset'.format( + body['customization_id']) + 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='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.reset_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for upgrade_acoustic_model +#----------------------------------------------------------------------------- +class TestUpgradeAcousticModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_upgrade_acoustic_model_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_upgrade_acoustic_model_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_upgrade_acoustic_model_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 = '/v1/acoustic_customizations/{0}/upgrade_model'.format( + body['customization_id']) + 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='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.upgrade_acoustic_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['custom_language_model_id'] = "string1" + body['force'] = True + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomAcousticModels +############################################################################## + +############################################################################## +# Start of Service: CustomAudioResources +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_audio +#----------------------------------------------------------------------------- +class TestListAudio(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_audio_response(self): + body = self.construct_full_body() + response = fake_response_AudioResources_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_audio_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AudioResources_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_audio_empty(self): + check_empty_required_params(self, fake_response_AudioResources_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}/audio'.format( + body['customization_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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_audio(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_audio +#----------------------------------------------------------------------------- +class TestAddAudio(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_audio_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_add_audio_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_add_audio_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 = '/v1/acoustic_customizations/{0}/audio/{1}'.format( + body['customization_id'], body['audio_name']) + 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=201, + content_type='') + + def call_service(self, body): + service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_audio(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + body['audio_resource'] = tempfile.NamedTemporaryFile() + body['content_type'] = "string1" + body['contained_content_type'] = "string1" + body['allow_overwrite'] = True + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + body['audio_resource'] = tempfile.NamedTemporaryFile() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_audio +#----------------------------------------------------------------------------- +class TestGetAudio(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_audio_response(self): + body = self.construct_full_body() + response = fake_response_AudioListing_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_audio_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AudioListing_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_audio_empty(self): + check_empty_required_params(self, fake_response_AudioListing_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format( + body['customization_id'], body['audio_name']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_audio(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_audio +#----------------------------------------------------------------------------- +class TestDeleteAudio(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_audio_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_audio_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_audio_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 = '/v1/acoustic_customizations/{0}/audio/{1}'.format( + body['customization_id'], body['audio_name']) + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_audio(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['audio_name'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomAudioResources +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_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_user_data_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_user_data_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 = '/v1/user_data' + 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 = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False try: - return body.decode('utf-8') - except: - return body - - -@responses.activate -def test_recognitions(): - url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognitions' - get_response = '{"recognitions": [{"created": "2018-02-01T17:43:15.432Z","id": "6193190c-0777-11e8-9b4b-43ad845196dd","updated": "2018-02-01T17:43:17.998Z","status": "failed"}]}' - responses.add( - responses.GET, - url, - body=get_response, - status=200, - content_type='application/json') - - responses.add( - responses.POST, - url, - body='{"status": "waiting"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - "{0}/jobid".format(url), - body='{"description": "deleted successfully"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}/jobid".format(url), - body='{"status": "waiting"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - speech_to_text.check_jobs() - assert responses.calls[0].response.json()['recognitions'][0][ - 'id'] == '6193190c-0777-11e8-9b4b-43ad845196dd' - - speech_to_text.check_job('jobid') - assert responses.calls[1].response.json() == {'status': 'waiting'} - - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: - speech_to_text.create_job(audio=audio_file, content_type='audio/basic') - assert responses.calls[2].response.json() == {'status': 'waiting'} - - speech_to_text.delete_job('jobid') - assert responses.calls[3].response.json() == { - "description": "deleted successfully" - } - - assert len(responses.calls) == 4 - - -@responses.activate -def test_callbacks(): - base_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1' - responses.add( - responses.POST, - "{0}/register_callback".format(base_url), - body='{"status": "created", "url": "monitorcalls.com"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - "{0}/unregister_callback".format(base_url), - body='{"response": "The callback URL was successfully unregistered"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - speech_to_text.register_callback("monitorcalls.com") - assert responses.calls[0].response.json() == { - "status": "created", - "url": "monitorcalls.com" - } - - speech_to_text.unregister_callback("monitorcalls.com") - assert responses.calls[1].response.json() == { - "response": "The callback URL was successfully unregistered" - } - - assert len(responses.calls) == 2 - - -@responses.activate -def test_custom_model(): - customization_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations' - train_url = "{0}/{1}/train".format(customization_url, 'customid') - - responses.add( - responses.GET, - customization_url, - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - customization_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}/modelid".format(customization_url), - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - "{0}/modelid".format(customization_url), - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - train_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - speech_to_text.list_language_models() - - speech_to_text.create_language_model( - name="Example model", - base_model_name="en-US_BroadbandModel") - - parsed_body = json.loads(_decode_body(responses.calls[1].request.body)) - assert parsed_body['name'] == 'Example model' - - speech_to_text.create_language_model( - name="Example model Two", - base_model_name="en-US_BroadbandModel") - - parsed_body = json.loads(_decode_body(responses.calls[2].request.body)) - assert parsed_body['name'] == 'Example model Two' - assert parsed_body['base_model_name'] == 'en-US_BroadbandModel' - - speech_to_text.train_language_model('customid') - speech_to_text.get_language_model(customization_id='modelid') - speech_to_text.delete_language_model(customization_id='modelid') - - assert len(responses.calls) == 6 - - -@responses.activate -def test_acoustic_model(): - acoustic_customization_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations' - train_url = "{0}/{1}/train".format(acoustic_customization_url, 'customid') - - responses.add( - responses.GET, - acoustic_customization_url, - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - acoustic_customization_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - "{0}/modelid".format(acoustic_customization_url), - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - "{0}/modelid".format(acoustic_customization_url), - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - train_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - speech_to_text.list_acoustic_models() - - speech_to_text.create_acoustic_model( - name="Example model", - base_model_name="en-US_BroadbandModel", - description="Example custom language model") - - parsed_body = json.loads(_decode_body(responses.calls[1].request.body)) - assert parsed_body['name'] == 'Example model' - - speech_to_text.create_acoustic_model( - name="Example model Two", - base_model_name="en-US_BroadbandModel") - - parsed_body = json.loads(_decode_body(responses.calls[2].request.body)) - assert parsed_body['name'] == 'Example model Two' - assert parsed_body['base_model_name'] == 'en-US_BroadbandModel' - - speech_to_text.train_acoustic_model('customid') - speech_to_text.get_acoustic_model(customization_id='modelid') - speech_to_text.delete_acoustic_model(customization_id='modelid') - - assert len(responses.calls) == 6 - -@responses.activate -def test_upgrade_acoustic_model(): - acoustic_customization_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations' - upgrade_url = "{0}/{1}/upgrade_model".format(acoustic_customization_url, 'customid') - - responses.add( - responses.POST, - upgrade_url, - body='{"bogus_response": "yep"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - speech_to_text.upgrade_acoustic_model( - 'customid', - custom_language_model_id='model_x', - force=True) - assert responses.calls[0].response.json() == {"bogus_response": "yep"} - - assert len(responses.calls) == 1 - - -def test_custom_corpora(): - - corpora_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/corpora' - get_corpora_url = '{0}/{1}'.format( - corpora_url.format('customid'), 'corpus') - - with responses.RequestsMock(assert_all_requests_are_fired=True) as rsps: - rsps.add( - responses.GET, - corpora_url.format('customid'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - rsps.add( - responses.POST, - get_corpora_url, - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - rsps.add( - responses.GET, - get_corpora_url, - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - rsps.add( - responses.DELETE, - get_corpora_url, - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - speech_to_text.list_corpora(customization_id='customid') - - file_path = '../../resources/speech_to_text/corpus-short-1.txt' - full_path = os.path.join(os.path.dirname(__file__), file_path) - with open(full_path) as corpus_file: - speech_to_text.add_corpus( - customization_id='customid', - corpus_name="corpus", - corpus_file=corpus_file) - - speech_to_text.get_corpus( - customization_id='customid', corpus_name='corpus') - - speech_to_text.delete_corpus( - customization_id='customid', corpus_name='corpus') - - -@responses.activate -def test_custom_words(): - words_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/words' - word_url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/words/{1}' - - responses.add( - responses.PUT, - word_url.format('custid', 'IEEE'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.PUT, - word_url.format('custid', 'wordname'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - word_url.format('custid', 'IEEE'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - word_url.format('custid', 'wordname'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - word_url.format('custid', 'IEEE'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - word_url.format('custid', 'wordname'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.POST, - words_url.format('custid'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - words_url.format('custid'), - body='{"get response": "yep"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - custom_word = CustomWord( - word="IEEE", sounds_like=["i triple e"], display_as="IEEE") - - speech_to_text.add_word( - customization_id='custid', - word_name="IEEE", - sounds_like=["i triple e"], - display_as="IEEE") - - speech_to_text.delete_word(customization_id='custid', word_name="wordname") - - speech_to_text.delete_word(customization_id='custid', word_name='IEEE') - - custom_words = [custom_word, custom_word, custom_word] - speech_to_text.add_words( - customization_id='custid', - words=custom_words) - - speech_to_text.get_word(customization_id='custid', word_name="IEEE") - - speech_to_text.get_word(customization_id='custid', word_name='wordname') - - speech_to_text.list_words(customization_id='custid') - speech_to_text.list_words(customization_id='custid', sort='alphabetical') - - speech_to_text.list_words(customization_id='custid', word_type='all') - - assert len(responses.calls) == 9 - - -@responses.activate -def test_custom_audio_resources(): - url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations/{0}/audio/{1}' - - responses.add( - responses.POST, - url.format('custid', 'hiee'), - body='{"post response": "done"}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - url.format('custid', 'hiee'), - body='{"delete response": "done"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - url.format('custid', 'hiee'), - body='{"get response": "done"}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - 'https://stream.watsonplatform.net/speech-to-text/api/v1/acoustic_customizations/custid/audio', - body='{"get response all": "done"}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech.wav'), 'rb') as audio_file: - speech_to_text.add_audio( - customization_id='custid', - audio_name="hiee", - audio_resource=audio_file, - content_type="application/json") - assert responses.calls[0].response.json() == {"post response": "done"} - - speech_to_text.delete_audio('custid', 'hiee') - assert responses.calls[1].response.json() == {"delete response": "done"} - - speech_to_text.get_audio('custid', 'hiee') - assert responses.calls[2].response.json() == {"get response": "done"} - - speech_to_text.list_audio('custid') - assert responses.calls[3].response.json() == {"get response all": "done"} - -@responses.activate -def test_delete_user_data(): - url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/user_data' - responses.add( - responses.DELETE, - url, - body='{"description": "success" }', - status=204, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - response = speech_to_text.delete_user_data('id').get_result() - assert response is None - assert len(responses.calls) == 1 - -@responses.activate -def test_custom_grammars(): - url = 'https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/{0}/grammars/{1}' - - responses.add( - responses.POST, - url.format('customization_id', 'grammar_name'), - body='{}', - status=200, - content_type='application/json') - - responses.add( - responses.DELETE, - url.format('customization_id', 'grammar_name'), - status=200, - content_type='application/json') - - responses.add( - responses.GET, - url.format('customization_id', 'grammar_name'), - body='{"status": "analyzed", "name": "test-add-grammar-python", "out_of_vocabulary_words": 0}', - status=200, - content_type='application/json') - - responses.add( - responses.GET, - url='https://stream.watsonplatform.net/speech-to-text/api/v1/customizations/customization_id/grammars', - body='{"grammars":[{"status": "analyzed", "name": "test-add-grammar-python", "out_of_vocabulary_words": 0}]}', - status=200, - content_type='application/json') - - authenticator = BasicAuthenticator('username', 'password') - speech_to_text = ibm_watson.SpeechToTextV1(authenticator=authenticator) - - with open(os.path.join(os.path.dirname(__file__), '../../resources/confirm-grammar.xml'), 'rb') as grammar_file: - speech_to_text.add_grammar( - "customization_id", - grammar_name='grammar_name', - grammar_file=grammar_file, - content_type='application/srgs+xml', - allow_overwrite=True) - assert responses.calls[0].response.json() == {} - - speech_to_text.delete_grammar('customization_id', 'grammar_name') - assert responses.calls[1].response.status_code == 200 - - speech_to_text.get_grammar('customization_id', 'grammar_name') - assert responses.calls[2].response.json() == {"status": "analyzed", "name": "test-add-grammar-python", "out_of_vocabulary_words": 0} - - speech_to_text.list_grammars('customization_id') - assert responses.calls[3].response.json() == {"grammars":[{"status": "analyzed", "name": "test-add-grammar-python", "out_of_vocabulary_words": 0}]} + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_SpeechModels_json = """{"models": []}""" +fake_response_SpeechModel_json = """{"name": "fake_name", "language": "fake_language", "rate": 4, "url": "fake_url", "supported_features": {"custom_language_model": false, "speaker_labels": true}, "description": "fake_description"}""" +fake_response_SpeechRecognitionResults_json = """{"results": [], "result_index": 12, "speaker_labels": [], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [], "clipping_rate": [], "speech_level": [], "non_speech_level": []}}, "warnings": []}""" +fake_response_RegisterStatus_json = """{"status": "fake_status", "url": "fake_url"}""" +fake_response_RecognitionJob_json = """{"id": "fake_id", "status": "fake_status", "created": "fake_created", "updated": "fake_updated", "url": "fake_url", "user_token": "fake_user_token", "results": [], "warnings": []}""" +fake_response_RecognitionJobs_json = """{"recognitions": []}""" +fake_response_RecognitionJob_json = """{"id": "fake_id", "status": "fake_status", "created": "fake_created", "updated": "fake_updated", "url": "fake_url", "user_token": "fake_user_token", "results": [], "warnings": []}""" +fake_response_LanguageModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "dialect": "fake_dialect", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "error": "fake_error", "warnings": "fake_warnings"}""" +fake_response_LanguageModels_json = """{"customizations": []}""" +fake_response_LanguageModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "dialect": "fake_dialect", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "error": "fake_error", "warnings": "fake_warnings"}""" +fake_response_TrainingResponse_json = """{"warnings": []}""" +fake_response_Corpora_json = """{"corpora": []}""" +fake_response_Corpus_json = """{"name": "fake_name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "fake_status", "error": "fake_error"}""" +fake_response_Words_json = """{"words": []}""" +fake_response_Word_json = """{"word": "fake_word", "sounds_like": [], "display_as": "fake_display_as", "count": 5, "source": [], "error": []}""" +fake_response_Grammars_json = """{"grammars": []}""" +fake_response_Grammar_json = """{"name": "fake_name", "out_of_vocabulary_words": 23, "status": "fake_status", "error": "fake_error"}""" +fake_response_AcousticModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "warnings": "fake_warnings"}""" +fake_response_AcousticModels_json = """{"customizations": []}""" +fake_response_AcousticModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "warnings": "fake_warnings"}""" +fake_response_TrainingResponse_json = """{"warnings": []}""" +fake_response_AudioResources_json = """{"total_minutes_of_audio": 22, "audio": []}""" +fake_response_AudioListing_json = """{"duration": 8, "name": "fake_name", "details": {"type": "fake_type", "codec": "fake_codec", "frequency": 9, "compression": "fake_compression"}, "status": "fake_status", "container": {"duration": 8, "name": "fake_name", "details": {"type": "fake_type", "codec": "fake_codec", "frequency": 9, "compression": "fake_compression"}, "status": "fake_status"}, "audio": []}""" From 040946f88d6b652f8b8e5638429b69fb1035e79a Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 18:04:26 -0500 Subject: [PATCH 187/455] feat(stt): New param `end_of_phrase_silence_time` and `split_transcription` in recognize_using_websocket --- ibm_watson/speech_to_text_v1_adapter.py | 27 +++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 9f59e4721..c813b5370 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -51,6 +51,8 @@ def recognize_using_websocket(self, processing_metrics=None, processing_metrics_interval=None, audio_metrics=None, + end_of_phrase_silence_time=None, + split_transcript_at_phrase_end=None, **kwargs): """ Sends audio for speech recognition using web sockets. @@ -188,6 +190,31 @@ def recognize_using_websocket(self, :param bool audio_metrics: 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. + :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 + silence before it reaches the end of the audio stream, its response can + include multiple final results. Silence indicates a point at which the + speaker pauses between spoken words or phrases. + Specify a value for the pause interval in the range of 0.0 to 120.0. + * A value greater than 0 specifies the interval that the service is to use + for speech recognition. + * A value of 0 indicates that the service is to use the default interval. + It is equivalent to omitting the parameter. + 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). + :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 + meaningful phrases such as sentences. The service bases its understanding + of semantic features on the base language model that you use with a + request. Custom language models and grammars can also influence how and + 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). :param dict headers: A `dict` containing the request headers :return: A `dict` containing the `SpeechRecognitionResults` response. :rtype: dict From aa8fe87da8554daeefd2611e7e9f6e007fbff45c Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 18:05:27 -0500 Subject: [PATCH 188/455] refactor(tts): regenerate text to speech with tests --- ibm_watson/text_to_speech_v1.py | 499 +++++---- test/unit/test_text_to_speech_v1.py | 1470 ++++++++++++++++++++++----- 2 files changed, 1530 insertions(+), 439 deletions(-) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 2b8084043..371bdf07f 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -31,11 +31,16 @@ """ import json +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator 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 read_external_sources +from ibm_cloud_sdk_core import read_external_sources, DetailedResponse +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from os.path import basename +from typing import Dict +from typing import List ############################################################################## # Service @@ -45,12 +50,14 @@ class TextToSpeechV1(BaseService): """The Text to Speech V1 service.""" - default_service_url = 'https://stream.watsonplatform.net/text-to-speech/api' + DEFAULT_SERVICE_URL = 'https://stream.watsonplatform.net/text-to-speech/api' + DEFAULT_SERVICE_NAME = 'text_to_speech' def __init__( self, - authenticator=None, - ): + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, + ) -> None: """ Construct a new client for the Text to Speech service. @@ -58,29 +65,19 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - - service_url = self.default_service_url - disable_ssl_verification = False - - config = read_external_sources('text_to_speech') - if config.get('URL'): - service_url = config.get('URL') - if config.get('DISABLE_SSL'): - disable_ssl_verification = config.get('DISABLE_SSL') - if not authenticator: - authenticator = get_authenticator_from_environment('text_to_speech') - + authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, - service_url=service_url, + service_url=self.DEFAULT_SERVICE_URL, authenticator=authenticator, - disable_ssl_verification=disable_ssl_verification) + disable_ssl_verification=False) + self.configure_service(service_name) ######################### # Voices ######################### - def list_voices(self, **kwargs): + def list_voices(self, **kwargs) -> 'DetailedResponse': """ List voices. @@ -98,18 +95,19 @@ def list_voices(self, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'list_voices') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_voices') headers.update(sdk_headers) url = '/v1/voices' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def get_voice(self, voice, *, customization_id=None, **kwargs): + def get_voice(self, voice: str, *, customization_id: str = None, + **kwargs) -> 'DetailedResponse': """ Get a voice. @@ -138,7 +136,9 @@ def get_voice(self, voice, *, customization_id=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'get_voice') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_voice') headers.update(sdk_headers) params = {'customization_id': customization_id} @@ -147,8 +147,8 @@ def get_voice(self, voice, *, customization_id=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -157,12 +157,12 @@ def get_voice(self, voice, *, customization_id=None, **kwargs): ######################### def synthesize(self, - text, + text: str, *, - accept=None, - voice=None, - customization_id=None, - **kwargs): + accept: str = None, + voice: str = None, + customization_id: str = None, + **kwargs) -> 'DetailedResponse': """ Synthesize audio. @@ -248,7 +248,9 @@ def synthesize(self, headers = {'Accept': accept} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'synthesize') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='synthesize') headers.update(sdk_headers) params = {'voice': voice, 'customization_id': customization_id} @@ -260,8 +262,8 @@ def synthesize(self, url=url, headers=headers, params=params, - data=data, - accept_json=False) + data=data) + response = self.send(request) return response @@ -270,12 +272,12 @@ def synthesize(self, ######################### def get_pronunciation(self, - text, + text: str, *, - voice=None, - format=None, - customization_id=None, - **kwargs): + voice: str = None, + format: str = None, + customization_id: str = None, + **kwargs) -> 'DetailedResponse': """ Get pronunciation. @@ -283,7 +285,8 @@ def get_pronunciation(self, pronunciation for a specific format. You can also request the pronunciation for a specific voice to see the default translation for the language of that voice or for a specific custom voice model to see the translation for that voice model. - **Note:** This method is currently a beta release. + **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). @@ -313,8 +316,9 @@ def get_pronunciation(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - 'get_pronunciation') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_pronunciation') headers.update(sdk_headers) params = { @@ -328,8 +332,8 @@ def get_pronunciation(self, request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response @@ -338,11 +342,11 @@ def get_pronunciation(self, ######################### def create_voice_model(self, - name, + name: str, *, - language=None, - description=None, - **kwargs): + language: str = None, + description: str = None, + **kwargs) -> 'DetailedResponse': """ Create a custom model. @@ -350,7 +354,8 @@ def create_voice_model(self, model. You can optionally specify the language and a description for the new model. The model is owned by the instance of the service whose credentials are used to create it. - **Note:** This method is currently a beta release. + **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). @@ -370,8 +375,9 @@ def create_voice_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - 'create_voice_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_voice_model') headers.update(sdk_headers) data = {'name': name, 'language': language, 'description': description} @@ -380,12 +386,13 @@ def create_voice_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_voice_models(self, *, language=None, **kwargs): + def list_voice_models(self, *, language: str = None, + **kwargs) -> 'DetailedResponse': """ List custom models. @@ -410,8 +417,9 @@ def list_voice_models(self, *, language=None, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - 'list_voice_models') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_voice_models') headers.update(sdk_headers) params = {'language': language} @@ -420,18 +428,18 @@ def list_voice_models(self, *, language=None, **kwargs): request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - accept_json=True) + params=params) + response = self.send(request) return response def update_voice_model(self, - customization_id, + customization_id: str, *, - name=None, - description=None, - words=None, - **kwargs): + name: str = None, + description: str = None, + words: List['Word'] = None, + **kwargs) -> 'DetailedResponse': """ Update a custom model. @@ -466,7 +474,7 @@ def update_voice_model(self, :param str name: (optional) A new name for the custom voice model. :param str description: (optional) A new description for the custom voice model. - :param list[Word] words: (optional) An array of `Word` objects that + :param List[Word] words: (optional) An array of `Word` objects that provides the words and their translations that are to be added or updated for the custom voice model. Pass an empty array to make no additions or updates. @@ -483,8 +491,9 @@ def update_voice_model(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - 'update_voice_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_voice_model') headers.update(sdk_headers) data = {'name': name, 'description': description, 'words': words} @@ -494,12 +503,13 @@ def update_voice_model(self, request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def get_voice_model(self, customization_id, **kwargs): + def get_voice_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Get a custom model. @@ -525,19 +535,20 @@ def get_voice_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'get_voice_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_voice_model') headers.update(sdk_headers) url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_voice_model(self, customization_id, **kwargs): + def delete_voice_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom model. @@ -561,16 +572,17 @@ def delete_voice_model(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - 'delete_voice_model') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_voice_model') headers.update(sdk_headers) url = '/v1/customizations/{0}'.format( *self._encode_path_vars(customization_id)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=False) + headers=headers) + response = self.send(request) return response @@ -578,7 +590,8 @@ def delete_voice_model(self, customization_id, **kwargs): # Custom words ######################### - def add_words(self, customization_id, words, **kwargs): + def add_words(self, customization_id: str, words: List['Word'], + **kwargs) -> 'DetailedResponse': """ Add custom words. @@ -609,7 +622,7 @@ def add_words(self, customization_id, words, **kwargs): :param str customization_id: The customization ID (GUID) of the custom voice model. You must make the request with credentials for the instance of the service that owns the custom model. - :param list[Word] words: The **Add custom words** method accepts an array + :param List[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom voice model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each @@ -631,7 +644,9 @@ def add_words(self, customization_id, words, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'add_words') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_words') headers.update(sdk_headers) data = {'words': words} @@ -641,12 +656,12 @@ def add_words(self, customization_id, words, **kwargs): request = self.prepare_request(method='POST', url=url, headers=headers, - data=data, - accept_json=True) + data=data) + response = self.send(request) return response - def list_words(self, customization_id, **kwargs): + def list_words(self, customization_id: str, **kwargs) -> 'DetailedResponse': """ List custom words. @@ -672,25 +687,25 @@ def list_words(self, customization_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'list_words') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_words') headers.update(sdk_headers) url = '/v1/customizations/{0}/words'.format( *self._encode_path_vars(customization_id)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response def add_word(self, - customization_id, - word, - translation, + customization_id: str, + word: str, + translation: str, *, - part_of_speech=None, - **kwargs): + part_of_speech: str = None, + **kwargs) -> 'DetailedResponse': """ Add a custom word. @@ -750,7 +765,9 @@ def add_word(self, headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'add_word') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_word') headers.update(sdk_headers) data = {'translation': translation, 'part_of_speech': part_of_speech} @@ -760,12 +777,13 @@ def add_word(self, request = self.prepare_request(method='PUT', url=url, headers=headers, - data=data, - accept_json=False) + data=data) + response = self.send(request) return response - def get_word(self, customization_id, word, **kwargs): + def get_word(self, customization_id: str, word: str, + **kwargs) -> 'DetailedResponse': """ Get a custom word. @@ -794,19 +812,20 @@ def get_word(self, customization_id, word, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'get_word') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_word') headers.update(sdk_headers) url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - accept_json=True) + request = self.prepare_request(method='GET', url=url, headers=headers) + response = self.send(request) return response - def delete_word(self, customization_id, word, **kwargs): + def delete_word(self, customization_id: str, word: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom word. @@ -834,15 +853,17 @@ def delete_word(self, customization_id, word, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', 'delete_word') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_word') headers.update(sdk_headers) url = '/v1/customizations/{0}/words/{1}'.format( *self._encode_path_vars(customization_id, word)) request = self.prepare_request(method='DELETE', url=url, - headers=headers, - accept_json=False) + headers=headers) + response = self.send(request) return response @@ -850,7 +871,8 @@ def delete_word(self, customization_id, word, **kwargs): # User data ######################### - def delete_user_data(self, customer_id, **kwargs): + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': """ Delete labeled data. @@ -877,8 +899,9 @@ def delete_user_data(self, customer_id, **kwargs): headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - sdk_headers = get_sdk_headers('text_to_speech', 'V1', - 'delete_user_data') + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data') headers.update(sdk_headers) params = {'customer_id': customer_id} @@ -887,8 +910,8 @@ def delete_user_data(self, customer_id, **kwargs): request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - accept_json=False) + params=params) + response = self.send(request) return response @@ -956,6 +979,7 @@ class Voice(Enum): """ The voice to use for synthesis. """ + AR_AR_OMARVOICE = 'ar-AR_OmarVoice' DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERVOICE = 'de-DE_DieterVoice' @@ -982,8 +1006,13 @@ class Voice(Enum): IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' + NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' + NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' + ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' + ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' class GetPronunciationEnums(object): @@ -1066,7 +1095,7 @@ class Pronunciation(): pronunciation also reflects that custom voice. """ - def __init__(self, pronunciation): + def __init__(self, pronunciation: str) -> None: """ Initialize a Pronunciation object. @@ -1077,7 +1106,7 @@ def __init__(self, pronunciation): self.pronunciation = pronunciation @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Pronunciation': """Initialize a Pronunciation object from a json dictionary.""" args = {} valid_keys = ['pronunciation'] @@ -1094,24 +1123,33 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Pronunciation 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, 'pronunciation') and self.pronunciation is not None: _dict['pronunciation'] = self.pronunciation return _dict - def __str__(self): + 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 Pronunciation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Pronunciation') -> 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): + def __ne__(self, other: 'Pronunciation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1127,7 +1165,8 @@ class SupportedFeatures(): cannot be transformed. """ - def __init__(self, custom_pronunciation, voice_transformation): + def __init__(self, custom_pronunciation: bool, + voice_transformation: bool) -> None: """ Initialize a SupportedFeatures object. @@ -1141,7 +1180,7 @@ def __init__(self, custom_pronunciation, voice_transformation): self.voice_transformation = voice_transformation @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} valid_keys = ['custom_pronunciation', 'voice_transformation'] @@ -1164,7 +1203,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a SupportedFeatures 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, 'custom_pronunciation' @@ -1175,17 +1219,21 @@ def _to_dict(self): _dict['voice_transformation'] = self.voice_transformation return _dict - def __str__(self): + 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 SupportedFeatures object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'SupportedFeatures') -> 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): + def __ne__(self, other: 'SupportedFeatures') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1206,7 +1254,7 @@ class Translation(): entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes). """ - def __init__(self, translation, *, part_of_speech=None): + def __init__(self, translation: str, *, part_of_speech: str = None) -> None: """ Initialize a Translation object. @@ -1227,7 +1275,7 @@ def __init__(self, translation, *, part_of_speech=None): self.part_of_speech = part_of_speech @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Translation': """Initialize a Translation object from a json dictionary.""" args = {} valid_keys = ['translation', 'part_of_speech'] @@ -1246,7 +1294,12 @@ def _from_dict(cls, _dict): args['part_of_speech'] = _dict.get('part_of_speech') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Translation 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, 'translation') and self.translation is not None: @@ -1255,17 +1308,21 @@ def _to_dict(self): _dict['part_of_speech'] = self.part_of_speech return _dict - def __str__(self): + 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 Translation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Translation') -> 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): + def __ne__(self, other: 'Translation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1318,15 +1375,15 @@ class Voice(): """ def __init__(self, - url, - gender, - name, - language, - description, - customizable, - supported_features, + url: str, + gender: str, + name: str, + language: str, + description: str, + customizable: bool, + supported_features: 'SupportedFeatures', *, - customization=None): + customization: 'VoiceModel' = None) -> None: """ Initialize a Voice object. @@ -1357,7 +1414,7 @@ def __init__(self, self.customization = customization @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Voice': """Initialize a Voice object from a json dictionary.""" args = {} valid_keys = [ @@ -1411,7 +1468,12 @@ def _from_dict(cls, _dict): _dict.get('customization')) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Voice 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, 'url') and self.url is not None: @@ -1434,17 +1496,21 @@ def _to_dict(self): _dict['customization'] = self.customization._to_dict() return _dict - def __str__(self): + 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 Voice object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Voice') -> 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): + def __ne__(self, other: 'Voice') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1470,7 +1536,7 @@ class VoiceModel(): updated. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). :attr str description: (optional) The description of the custom voice model. - :attr list[Word] words: (optional) An array of `Word` objects that lists the + :attr List[Word] words: (optional) An array of `Word` objects that lists the words and their translations from the custom voice model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if the custom model contains no words. This field is returned @@ -1479,15 +1545,15 @@ class VoiceModel(): """ def __init__(self, - customization_id, + customization_id: str, *, - name=None, - language=None, - owner=None, - created=None, - last_modified=None, - description=None, - words=None): + name: str = None, + language: str = None, + owner: str = None, + created: str = None, + last_modified: str = None, + description: str = None, + words: List['Word'] = None) -> None: """ Initialize a VoiceModel object. @@ -1509,7 +1575,7 @@ def __init__(self, (`YYYY-MM-DDThh:mm:ss.sTZD`). :param str description: (optional) The description of the custom voice model. - :param list[Word] words: (optional) An array of `Word` objects that lists + :param List[Word] words: (optional) An array of `Word` objects that lists the words and their translations from the custom voice model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if the custom model contains no @@ -1526,7 +1592,7 @@ def __init__(self, self.words = words @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'VoiceModel': """Initialize a VoiceModel object from a json dictionary.""" args = {} valid_keys = [ @@ -1560,7 +1626,12 @@ def _from_dict(cls, _dict): args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a VoiceModel 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, @@ -1582,17 +1653,21 @@ def _to_dict(self): _dict['words'] = [x._to_dict() for x in self.words] return _dict - def __str__(self): + 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 VoiceModel object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'VoiceModel') -> 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): + def __ne__(self, other: 'VoiceModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1601,17 +1676,17 @@ class VoiceModels(): """ Information about existing custom voice models. - :attr list[VoiceModel] customizations: An array of `VoiceModel` objects that + :attr List[VoiceModel] customizations: An array of `VoiceModel` objects that provides information about each available custom voice model. The array is empty if the requesting credentials own no custom voice models (if no language is specified) or own no custom voice models for the specified language. """ - def __init__(self, customizations): + def __init__(self, customizations: List['VoiceModel']) -> None: """ Initialize a VoiceModels object. - :param list[VoiceModel] customizations: An array of `VoiceModel` objects + :param List[VoiceModel] customizations: An array of `VoiceModel` objects that provides information about each available custom voice model. The array is empty if the requesting credentials own no custom voice models (if no language is specified) or own no custom voice models for the specified @@ -1620,7 +1695,7 @@ def __init__(self, customizations): self.customizations = customizations @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'VoiceModels': """Initialize a VoiceModels object from a json dictionary.""" args = {} valid_keys = ['customizations'] @@ -1639,7 +1714,12 @@ def _from_dict(cls, _dict): ) return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a VoiceModels 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, 'customizations') and self.customizations is not None: @@ -1648,17 +1728,21 @@ def _to_dict(self): ] return _dict - def __str__(self): + 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 VoiceModels object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'VoiceModels') -> 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): + def __ne__(self, other: 'VoiceModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1667,19 +1751,19 @@ class Voices(): """ Information about all available voice models. - :attr list[Voice] voices: A list of available voices. + :attr List[Voice] voices: A list of available voices. """ - def __init__(self, voices): + def __init__(self, voices: List['Voice']) -> None: """ Initialize a Voices object. - :param list[Voice] voices: A list of available voices. + :param List[Voice] voices: A list of available voices. """ self.voices = voices @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Voices': """Initialize a Voices object from a json dictionary.""" args = {} valid_keys = ['voices'] @@ -1697,24 +1781,33 @@ def _from_dict(cls, _dict): 'Required property \'voices\' not present in Voices JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Voices 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, 'voices') and self.voices is not None: _dict['voices'] = [x._to_dict() for x in self.voices] return _dict - def __str__(self): + 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 Voices object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Voices') -> 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): + def __ne__(self, other: 'Voices') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1737,7 +1830,11 @@ class Word(): entries](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-rules#jaNotes). """ - def __init__(self, word, translation, *, part_of_speech=None): + def __init__(self, + word: str, + translation: str, + *, + part_of_speech: str = None) -> None: """ Initialize a Word object. @@ -1760,7 +1857,7 @@ def __init__(self, word, translation, *, part_of_speech=None): self.part_of_speech = part_of_speech @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} valid_keys = ['word', 'translation', 'part_of_speech'] @@ -1783,7 +1880,12 @@ def _from_dict(cls, _dict): args['part_of_speech'] = _dict.get('part_of_speech') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Word 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, 'word') and self.word is not None: @@ -1794,17 +1896,21 @@ def _to_dict(self): _dict['part_of_speech'] = self.part_of_speech return _dict - def __str__(self): + 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 Word object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Word') -> 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): + def __ne__(self, other: 'Word') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1843,7 +1949,7 @@ class Words(): For the **List custom words** method, the words and their translations from the custom voice model. - :attr list[Word] words: The **Add custom words** method accepts an array of + :attr List[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom voice model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each object @@ -1852,11 +1958,11 @@ class Words(): letters. The array is empty if the custom model contains no words. """ - def __init__(self, words): + def __init__(self, words: List['Word']) -> None: """ Initialize a Words object. - :param list[Word] words: The **Add custom words** method accepts an array + :param List[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom voice model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each @@ -1868,7 +1974,7 @@ def __init__(self, words): self.words = words @classmethod - def _from_dict(cls, _dict): + def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} valid_keys = ['words'] @@ -1884,23 +1990,32 @@ def _from_dict(cls, _dict): 'Required property \'words\' not present in Words JSON') return cls(**args) - def _to_dict(self): + @classmethod + def _from_dict(cls, _dict): + """Initialize a Words 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, 'words') and self.words is not None: _dict['words'] = [x._to_dict() for x in self.words] return _dict - def __str__(self): + 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 Words object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other): + def __eq__(self, other: 'Words') -> 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): + def __ne__(self, other: 'Words') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 454ce955c..2d8efd6f1 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,248 +1,1224 @@ -# coding=utf-8 -import responses -import ibm_watson +# -*- coding: utf-8 -*- +# (C) Copyright IBM Corp. 2020. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +import inspect import json -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -@responses.activate -def test_success(): - voices_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/voices' - voices_response = { - "voices": [{ - "url": - "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEnUsLisa", - "gender": - "female", - "name": - "VoiceEnUsLisa", - "language": - "en-US" - }, { - "url": - "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEsEsEnrique", - "gender": - "male", - "name": - "VoiceEsEsEnrique", - "language": - "es-ES" - }, { - "url": - "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEnUsMichael", - "gender": - "male", - "name": - "VoiceEnUsMichael", - "language": - "en-US" - }, { - "url": - "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/VoiceEnUsAllison", - "gender": - "female", - "name": - "VoiceEnUsAllison", - "language": - "en-US" - }] - } - voice_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/voices/en-us_AllisonVoice' - voice_response = { - "url": - "https://stream.watsonplatform.net/text-to-speech/api/v1/voices/en-US_AllisonVoice", - "name": - "en-US_AllisonVoice", - "language": - "en-US", - "customizable": - True, - "gender": - "female", - "description": - "Allison: American English female voice.", - "supported_features": { - "custom_pronunciation": True, - "voice_transformation": True - } - } - synthesize_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize' - synthesize_response_body = '' - - responses.add( - responses.GET, - voices_url, - body=json.dumps(voices_response), - status=200, - content_type='application/json') - responses.add( - responses.GET, - voice_url, - body=json.dumps(voice_response), - status=200, - content_type='application/json') - responses.add( - responses.POST, - synthesize_url, - body=synthesize_response_body, - status=200, - content_type='application/json', - match_querystring=True) - - authenticator = BasicAuthenticator('username', 'password') - text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) - - text_to_speech.list_voices() - assert responses.calls[0].request.url == voices_url - assert responses.calls[0].response.text == json.dumps(voices_response) - - text_to_speech.get_voice('en-us_AllisonVoice') - assert responses.calls[1].request.url == voice_url - assert responses.calls[1].response.text == json.dumps(voice_response) - - text_to_speech.synthesize('hello') - assert responses.calls[2].request.url == synthesize_url - assert responses.calls[2].response.text == synthesize_response_body - - assert len(responses.calls) == 3 - - -@responses.activate -def test_get_pronunciation(): - - responses.add( - responses.GET, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/pronunciation', - body='{"pronunciation": "pronunciation info" }', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) - - text_to_speech.get_pronunciation(text="this is some text") - text_to_speech.get_pronunciation(text="yo", voice="VoiceEnUsLisa") - text_to_speech.get_pronunciation( - text="yo", voice="VoiceEnUsLisa", format='ipa') - - assert len(responses.calls) == 3 - - -@responses.activate -def test_custom_voice_models(): - responses.add( - responses.GET, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations', - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.POST, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations', - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.GET, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations/custid', - body='{"customization": "yep, just one" }', - status=200, - content_type='application_json') - responses.add( - responses.POST, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations/custid', - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.DELETE, - 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations/custid', - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) - - text_to_speech.list_voice_models() - text_to_speech.list_voice_models(language="en-US") - assert len(responses.calls) == 2 - - text_to_speech.create_voice_model(name="name", description="description") - text_to_speech.get_voice_model(customization_id='custid') - text_to_speech.update_voice_model( - customization_id="custid", name="name", description="description") - text_to_speech.delete_voice_model(customization_id="custid") - - assert len(responses.calls) == 6 - - -@responses.activate -def test_custom_words(): - base_url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/customizations' - responses.add( - responses.GET, - "{0}/{1}/words".format(base_url, "custid"), - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.POST, - "{0}/{1}/words".format(base_url, "custid"), - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.GET, - "{0}/{1}/words/{2}".format(base_url, "custid", "word"), - body='{"customization": "yep, just one" }', - status=200, - content_type='application_json') - responses.add( - responses.POST, - "{0}/{1}/words/{2}".format(base_url, "custid", "word"), - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.PUT, - "{0}/{1}/words/{2}".format(base_url, "custid", "word"), - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - responses.add( - responses.DELETE, - "{0}/{1}/words/{2}".format(base_url, "custid", "word"), - body='{"customizations": "yep" }', - status=200, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) - - text_to_speech.list_words(customization_id="custid") - text_to_speech.add_words( - customization_id="custid", words=[{"word": "one", "translation": "one"}, {"word": "two", "translation": "two"}]) - text_to_speech.get_word(customization_id="custid", word="word") - text_to_speech.add_word( - customization_id='custid', word="word", translation="I'm translated") - text_to_speech.delete_word(customization_id="custid", word="word") - - assert len(responses.calls) == 5 - -@responses.activate - -def test_delete_user_data(): - url = 'https://stream.watsonplatform.net/text-to-speech/api/v1/user_data' - responses.add( - responses.DELETE, - url, - body='{"description": "success" }', - status=204, - content_type='application_json') - - authenticator = BasicAuthenticator('username', 'password') - text_to_speech = ibm_watson.TextToSpeechV1(authenticator=authenticator) - - response = text_to_speech.delete_user_data('id').get_result() - assert response is None - assert len(responses.calls) == 1 +import pytest +import responses +import tempfile +import ibm_watson.text_to_speech_v1 +from ibm_watson.text_to_speech_v1 import * + +base_url = 'https://stream.watsonplatform.net/text-to-speech/api' + +############################################################################## +# Start of Service: Voices +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for list_voices +#----------------------------------------------------------------------------- +class TestListVoices(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_voices_response(self): + body = self.construct_full_body() + response = fake_response_Voices_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_voices_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Voices_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_voices_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/voices' + 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 = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_voices(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_voice +#----------------------------------------------------------------------------- +class TestGetVoice(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_voice_response(self): + body = self.construct_full_body() + response = fake_response_Voice_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_voice_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Voice_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_voice_empty(self): + check_empty_required_params(self, fake_response_Voice_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/voices/{0}'.format(body['voice']) + 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 = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_voice(**body) + return output + + def construct_full_body(self): + body = dict() + body['voice'] = "string1" + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['voice'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Voices +############################################################################## + +############################################################################## +# Start of Service: Synthesis +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for synthesize +#----------------------------------------------------------------------------- +class TestSynthesize(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_synthesize_response(self): + body = self.construct_full_body() + response = fake_response_BinaryIO_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_synthesize_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BinaryIO_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_synthesize_empty(self): + check_empty_required_params(self, fake_response_BinaryIO_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/synthesize' + 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='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.synthesize(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "text": "string1", + }) + body['accept'] = "string1" + body['voice'] = "string1" + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body.update({ + "text": "string1", + }) + return body + + +# endregion +############################################################################## +# End of Service: Synthesis +############################################################################## + +############################################################################## +# Start of Service: Pronunciation +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for get_pronunciation +#----------------------------------------------------------------------------- +class TestGetPronunciation(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_pronunciation_response(self): + body = self.construct_full_body() + response = fake_response_Pronunciation_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_pronunciation_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Pronunciation_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_pronunciation_empty(self): + check_empty_required_params(self, fake_response_Pronunciation_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/pronunciation' + 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 = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_pronunciation(**body) + return output + + def construct_full_body(self): + body = dict() + body['text'] = "string1" + body['voice'] = "string1" + body['format'] = "string1" + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['text'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Pronunciation +############################################################################## + +############################################################################## +# Start of Service: CustomModels +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for create_voice_model +#----------------------------------------------------------------------------- +class TestCreateVoiceModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_voice_model_response(self): + body = self.construct_full_body() + response = fake_response_VoiceModel_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_create_voice_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_VoiceModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_voice_model_empty(self): + check_empty_required_params(self, fake_response_VoiceModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations' + 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=201, + content_type='application/json') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.create_voice_model(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({ + "name": "string1", + "language": "string1", + "description": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body.update({ + "name": "string1", + "language": "string1", + "description": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_voice_models +#----------------------------------------------------------------------------- +class TestListVoiceModels(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_voice_models_response(self): + body = self.construct_full_body() + response = fake_response_VoiceModels_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_voice_models_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_VoiceModels_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_voice_models_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations' + 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 = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_voice_models(**body) + return output + + def construct_full_body(self): + body = dict() + body['language'] = "string1" + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_voice_model +#----------------------------------------------------------------------------- +class TestUpdateVoiceModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_voice_model_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_update_voice_model_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_update_voice_model_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 = '/v1/customizations/{0}'.format(body['customization_id']) + 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='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.update_voice_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "name": "string1", + "description": "string1", + "words": [], + }) + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "name": "string1", + "description": "string1", + "words": [], + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_voice_model +#----------------------------------------------------------------------------- +class TestGetVoiceModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_voice_model_response(self): + body = self.construct_full_body() + response = fake_response_VoiceModel_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_voice_model_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_VoiceModel_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_voice_model_empty(self): + check_empty_required_params(self, fake_response_VoiceModel_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}'.format(body['customization_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 = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_voice_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_voice_model +#----------------------------------------------------------------------------- +class TestDeleteVoiceModel(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_voice_model_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_voice_model_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_voice_model_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 = '/v1/customizations/{0}'.format(body['customization_id']) + 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=204, + content_type='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_voice_model(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomModels +############################################################################## + +############################################################################## +# Start of Service: CustomWords +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for add_words +#----------------------------------------------------------------------------- +class TestAddWords(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_words_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_add_words_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_add_words_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 = '/v1/customizations/{0}/words'.format( + body['customization_id']) + 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='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_words(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "words": [], + }) + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body.update({ + "words": [], + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for list_words +#----------------------------------------------------------------------------- +class TestListWords(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_words_response(self): + body = self.construct_full_body() + response = fake_response_Words_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_words_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Words_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_words_empty(self): + check_empty_required_params(self, fake_response_Words_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words'.format( + body['customization_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 = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.list_words(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for add_word +#----------------------------------------------------------------------------- +class TestAddWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_add_word_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_add_word_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_add_word_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 = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word']) + url = '{0}{1}'.format(base_url, endpoint) + return url + + def add_mock_response(self, url, response): + responses.add(responses.PUT, + url, + body=json.dumps(response), + status=200, + content_type='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.add_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + body.update({ + "translation": "string1", + "part_of_speech": "string1", + }) + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + body.update({ + "translation": "string1", + "part_of_speech": "string1", + }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_word +#----------------------------------------------------------------------------- +class TestGetWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_word_response(self): + body = self.construct_full_body() + response = fake_response_Translation_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_word_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Translation_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_word_empty(self): + check_empty_required_params(self, fake_response_Translation_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word']) + 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 = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.get_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_word +#----------------------------------------------------------------------------- +class TestDeleteWord(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_word_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_word_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_word_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 = '/v1/customizations/{0}/words/{1}'.format( + body['customization_id'], body['word']) + 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=204, + content_type='') + + def call_service(self, body): + service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_word(**body) + return output + + def construct_full_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customization_id'] = "string1" + body['word'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: CustomWords +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_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_user_data_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_user_data_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 = '/v1/user_data' + 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 = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + + +def check_empty_required_params(obj, response): + """Test function to assert that the operation will throw an error when given empty required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + body = {k: None for k in body.keys()} + error = False + try: + send_request(obj, body, response) + except ValueError as e: + error = True + assert error + + +def check_missing_required_params(obj): + """Test function to assert that the operation will throw an error when missing required data + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + error = False + try: + send_request(obj, {}, {}, url=url) + except TypeError as e: + error = True + assert error + + +def check_empty_response(obj): + """Test function to assert that the operation will return an empty response when given an empty request + + Args: + obj: The generated test function + + """ + body = obj.construct_full_body() + url = obj.make_url(body) + send_request(obj, {}, {}, url=url) + + +def send_request(obj, body, response, url=None): + """Test function to create a request, send it, and assert its accuracy to the mock response + + Args: + obj: The generated test function + body: Dict filled with fake data for calling the service + response_str: Mock response string + + """ + if not url: + url = obj.make_url(body) + obj.add_mock_response(url, response) + output = obj.call_service(body) + assert responses.calls[0].request.url.startswith(url) + assert output.get_result() == response + + +#################### +## Mock Responses ## +#################### + +fake_response__json = None +fake_response_Voices_json = """{"voices": []}""" +fake_response_Voice_json = """{"url": "fake_url", "gender": "fake_gender", "name": "fake_name", "language": "fake_language", "description": "fake_description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}}""" +fake_response_BinaryIO_json = """Contents of response byte-stream...""" +fake_response_Pronunciation_json = """{"pronunciation": "fake_pronunciation"}""" +fake_response_VoiceModel_json = """{"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}""" +fake_response_VoiceModels_json = """{"customizations": []}""" +fake_response_VoiceModel_json = """{"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}""" +fake_response_Words_json = """{"words": []}""" +fake_response_Translation_json = """{"translation": "fake_translation", "part_of_speech": "fake_part_of_speech"}""" From 88106fb9c9460e60363a814565b51a512805f8b9 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 18:19:39 -0500 Subject: [PATCH 189/455] feat(core): Update core version --- requirements-dev.txt | 2 +- requirements.txt | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 282f872f9..4c72280d9 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ python_dotenv>=0.1.5;python_version!='3.2' pylint>=1.4.4 tox>=2.9.1 pytest-rerunfailures>=3.1 -ibm_cloud_sdk_core==1.0.0 +ibm_cloud_sdk_core==1.5.1 # code coverage coverage<5 diff --git a/requirements.txt b/requirements.txt index d5fca9ef9..fea3e1c8c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 -ibm_cloud_sdk_core==1.0.0 +ibm_cloud_sdk_core==1.5.1 diff --git a/setup.py b/setup.py index fb53120b9..8e949081a 100644 --- a/setup.py +++ b/setup.py @@ -64,7 +64,7 @@ def run_tests(self): version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.0.0'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.5.1'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='IBM Watson', From 6efe91ddb8608db85d3c855a821bd3edc0e262a2 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 18:26:23 -0500 Subject: [PATCH 190/455] chore(style): run yapf on tests --- test/unit/test_assistant_v1.py | 1080 +++++++++----- test/unit/test_assistant_v2.py | 61 +- test/unit/test_common.py | 7 +- test/unit/test_compare_comply_v1.py | 178 ++- test/unit/test_discovery_v1.py | 1261 +++++++++++------ test/unit/test_discovery_v2.py | 274 ++-- test/unit/test_language_translator_v3.py | 172 ++- .../test_natural_language_understanding.py | 146 -- 8 files changed, 1958 insertions(+), 1221 deletions(-) delete mode 100644 test/unit/test_natural_language_understanding.py diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 458f26b46..59237d056 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -29,6 +29,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for message #----------------------------------------------------------------------------- @@ -74,16 +75,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.message(**body) return output @@ -91,7 +92,25 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"input": MessageInput._from_dict(json.loads("""{"text": "fake_text"}""")), "intents": [], "entities": [], "alternate_intents": True, "context": Context._from_dict(json.loads("""{"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}""")), "output": OutputData._from_dict(json.loads("""{"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}""")), }) + body.update({ + "input": + MessageInput._from_dict(json.loads("""{"text": "fake_text"}""") + ), + "intents": [], + "entities": [], + "alternate_intents": + True, + "context": + Context._from_dict( + json.loads( + """{"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}""" + )), + "output": + OutputData._from_dict( + json.loads( + """{"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}""" + )), + }) body['nodes_visited_details'] = True return body @@ -111,6 +130,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_workspaces #----------------------------------------------------------------------------- @@ -155,16 +175,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_workspaces(**body) return output @@ -226,23 +246,45 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_workspace(**body) return output def construct_full_body(self): body = dict() - body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + body.update({ + "name": + "string1", + "description": + "string1", + "language": + "string1", + "metadata": { + "mock": "data" + }, + "learning_opt_out": + True, + "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}}""" + )), + "intents": [], + "entities": [], + "dialog_nodes": [], + "counterexamples": [], + "webhooks": [], + }) return body def construct_required_body(self): @@ -295,16 +337,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_workspace(**body) return output @@ -368,16 +410,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_workspace(**body) return output @@ -385,7 +427,29 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + body.update({ + "name": + "string1", + "description": + "string1", + "language": + "string1", + "metadata": { + "mock": "data" + }, + "learning_opt_out": + True, + "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}}""" + )), + "intents": [], + "entities": [], + "dialog_nodes": [], + "counterexamples": [], + "webhooks": [], + }) body['append'] = True return body @@ -440,16 +504,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_workspace(**body) return output @@ -475,6 +539,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_intents #----------------------------------------------------------------------------- @@ -520,16 +585,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_intents(**body) return output @@ -595,16 +660,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_intent(**body) return output @@ -612,13 +677,21 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"intent": "string1", "description": "string1", "examples": [], }) + body.update({ + "intent": "string1", + "description": "string1", + "examples": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"intent": "string1", "description": "string1", "examples": [], }) + body.update({ + "intent": "string1", + "description": "string1", + "examples": [], + }) return body @@ -661,22 +734,23 @@ def test_get_intent_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}'.format( + body['workspace_id'], body['intent']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_intent(**body) return output @@ -735,22 +809,23 @@ def test_update_intent_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}'.format( + body['workspace_id'], body['intent']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_intent(**body) return output @@ -759,14 +834,22 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) + body.update({ + "new_intent": "string1", + "new_description": "string1", + "new_examples": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) + body.update({ + "new_intent": "string1", + "new_description": "string1", + "new_examples": [], + }) return body @@ -809,22 +892,23 @@ def test_delete_intent_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}'.format( + body['workspace_id'], body['intent']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_intent(**body) return output @@ -852,6 +936,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_examples #----------------------------------------------------------------------------- @@ -891,22 +976,23 @@ def test_list_examples_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format( + body['workspace_id'], body['intent']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_examples(**body) return output @@ -967,22 +1053,23 @@ def test_create_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format( + body['workspace_id'], body['intent']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_example(**body) return output @@ -991,14 +1078,20 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({"text": "string1", "mentions": [], }) + body.update({ + "text": "string1", + "mentions": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({"text": "string1", "mentions": [], }) + body.update({ + "text": "string1", + "mentions": [], + }) return body @@ -1041,22 +1134,23 @@ def test_get_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( + body['workspace_id'], body['intent'], body['text']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_example(**body) return output @@ -1116,22 +1210,23 @@ def test_update_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( + body['workspace_id'], body['intent'], body['text']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_example(**body) return output @@ -1141,7 +1236,10 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['intent'] = "string1" body['text'] = "string1" - body.update({"new_text": "string1", "new_mentions": [], }) + body.update({ + "new_text": "string1", + "new_mentions": [], + }) return body def construct_required_body(self): @@ -1149,7 +1247,10 @@ def construct_required_body(self): body['workspace_id'] = "string1" body['intent'] = "string1" body['text'] = "string1" - body.update({"new_text": "string1", "new_mentions": [], }) + body.update({ + "new_text": "string1", + "new_mentions": [], + }) return body @@ -1192,22 +1293,23 @@ def test_delete_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( + body['workspace_id'], body['intent'], body['text']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_example(**body) return output @@ -1237,6 +1339,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_counterexamples #----------------------------------------------------------------------------- @@ -1268,7 +1371,8 @@ def test_list_counterexamples_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_counterexamples_empty(self): - check_empty_required_params(self, fake_response_CounterexampleCollection_json) + check_empty_required_params( + self, fake_response_CounterexampleCollection_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1276,22 +1380,23 @@ def test_list_counterexamples_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_id']) + endpoint = '/v1/workspaces/{0}/counterexamples'.format( + body['workspace_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_counterexamples(**body) return output @@ -1350,22 +1455,23 @@ def test_create_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_id']) + endpoint = '/v1/workspaces/{0}/counterexamples'.format( + body['workspace_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_counterexample(**body) return output @@ -1373,13 +1479,17 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"text": "string1", }) + body.update({ + "text": "string1", + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"text": "string1", }) + body.update({ + "text": "string1", + }) return body @@ -1422,22 +1532,23 @@ def test_get_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( + body['workspace_id'], body['text']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_counterexample(**body) return output @@ -1495,22 +1606,23 @@ def test_update_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( + body['workspace_id'], body['text']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_counterexample(**body) return output @@ -1519,14 +1631,18 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['text'] = "string1" - body.update({"new_text": "string1", }) + body.update({ + "new_text": "string1", + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['text'] = "string1" - body.update({"new_text": "string1", }) + body.update({ + "new_text": "string1", + }) return body @@ -1569,22 +1685,23 @@ def test_delete_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( + body['workspace_id'], body['text']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_counterexample(**body) return output @@ -1612,6 +1729,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_entities #----------------------------------------------------------------------------- @@ -1657,16 +1775,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_entities(**body) return output @@ -1732,16 +1850,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_entity(**body) return output @@ -1749,13 +1867,29 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) + body.update({ + "entity": "string1", + "description": "string1", + "metadata": { + "mock": "data" + }, + "fuzzy_match": True, + "values": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) + body.update({ + "entity": "string1", + "description": "string1", + "metadata": { + "mock": "data" + }, + "fuzzy_match": True, + "values": [], + }) return body @@ -1798,22 +1932,23 @@ def test_get_entity_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}'.format( + body['workspace_id'], body['entity']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_entity(**body) return output @@ -1872,22 +2007,23 @@ def test_update_entity_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}'.format( + body['workspace_id'], body['entity']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_entity(**body) return output @@ -1896,14 +2032,30 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) + body.update({ + "new_entity": "string1", + "new_description": "string1", + "new_metadata": { + "mock": "data" + }, + "new_fuzzy_match": True, + "new_values": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) + body.update({ + "new_entity": "string1", + "new_description": "string1", + "new_metadata": { + "mock": "data" + }, + "new_fuzzy_match": True, + "new_values": [], + }) return body @@ -1946,22 +2098,23 @@ def test_delete_entity_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}'.format( + body['workspace_id'], body['entity']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_entity(**body) return output @@ -1989,6 +2142,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_mentions #----------------------------------------------------------------------------- @@ -2020,7 +2174,8 @@ def test_list_mentions_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_mentions_empty(self): - check_empty_required_params(self, fake_response_EntityMentionCollection_json) + check_empty_required_params(self, + fake_response_EntityMentionCollection_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2028,22 +2183,23 @@ def test_list_mentions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/mentions'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}/mentions'.format( + body['workspace_id'], body['entity']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_mentions(**body) return output @@ -2073,6 +2229,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_values #----------------------------------------------------------------------------- @@ -2112,22 +2269,23 @@ def test_list_values_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format( + body['workspace_id'], body['entity']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_values(**body) return output @@ -2189,22 +2347,23 @@ def test_create_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format( + body['workspace_id'], body['entity']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_value(**body) return output @@ -2213,14 +2372,30 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) + body.update({ + "value": "string1", + "metadata": { + "mock": "data" + }, + "type": "string1", + "synonyms": [], + "patterns": [], + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) + body.update({ + "value": "string1", + "metadata": { + "mock": "data" + }, + "type": "string1", + "synonyms": [], + "patterns": [], + }) return body @@ -2263,22 +2438,23 @@ def test_get_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( + body['workspace_id'], body['entity'], body['value']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_value(**body) return output @@ -2339,22 +2515,23 @@ def test_update_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( + body['workspace_id'], body['entity'], body['value']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_value(**body) return output @@ -2364,7 +2541,15 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) + body.update({ + "new_value": "string1", + "new_metadata": { + "mock": "data" + }, + "new_type": "string1", + "new_synonyms": [], + "new_patterns": [], + }) return body def construct_required_body(self): @@ -2372,7 +2557,15 @@ def construct_required_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) + body.update({ + "new_value": "string1", + "new_metadata": { + "mock": "data" + }, + "new_type": "string1", + "new_synonyms": [], + "new_patterns": [], + }) return body @@ -2415,22 +2608,23 @@ def test_delete_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( + body['workspace_id'], body['entity'], body['value']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_value(**body) return output @@ -2460,6 +2654,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_synonyms #----------------------------------------------------------------------------- @@ -2499,22 +2694,23 @@ def test_list_synonyms_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( + body['workspace_id'], body['entity'], body['value']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_synonyms(**body) return output @@ -2577,22 +2773,23 @@ def test_create_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( + body['workspace_id'], body['entity'], body['value']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_synonym(**body) return output @@ -2602,7 +2799,9 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({"synonym": "string1", }) + body.update({ + "synonym": "string1", + }) return body def construct_required_body(self): @@ -2610,7 +2809,9 @@ def construct_required_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({"synonym": "string1", }) + body.update({ + "synonym": "string1", + }) return body @@ -2653,22 +2854,24 @@ def test_get_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( + body['workspace_id'], body['entity'], body['value'], + body['synonym']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_synonym(**body) return output @@ -2730,22 +2933,24 @@ def test_update_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( + body['workspace_id'], body['entity'], body['value'], + body['synonym']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_synonym(**body) return output @@ -2756,7 +2961,9 @@ def construct_full_body(self): body['entity'] = "string1" body['value'] = "string1" body['synonym'] = "string1" - body.update({"new_synonym": "string1", }) + body.update({ + "new_synonym": "string1", + }) return body def construct_required_body(self): @@ -2765,7 +2972,9 @@ def construct_required_body(self): body['entity'] = "string1" body['value'] = "string1" body['synonym'] = "string1" - body.update({"new_synonym": "string1", }) + body.update({ + "new_synonym": "string1", + }) return body @@ -2808,22 +3017,24 @@ def test_delete_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( + body['workspace_id'], body['entity'], body['value'], + body['synonym']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_synonym(**body) return output @@ -2855,6 +3066,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_dialog_nodes #----------------------------------------------------------------------------- @@ -2886,7 +3098,8 @@ def test_list_dialog_nodes_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_dialog_nodes_empty(self): - check_empty_required_params(self, fake_response_DialogNodeCollection_json) + check_empty_required_params(self, + fake_response_DialogNodeCollection_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2894,22 +3107,23 @@ def test_list_dialog_nodes_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_id']) + endpoint = '/v1/workspaces/{0}/dialog_nodes'.format( + body['workspace_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_dialog_nodes(**body) return output @@ -2968,22 +3182,23 @@ def test_create_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_id']) + endpoint = '/v1/workspaces/{0}/dialog_nodes'.format( + body['workspace_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_dialog_node(**body) return output @@ -2991,13 +3206,105 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) + body.update({ + "dialog_node": + "string1", + "description": + "string1", + "conditions": + "string1", + "parent": + "string1", + "previous_sibling": + "string1", + "output": + DialogNodeOutput._from_dict( + json.loads( + """{"generic": [], "modifiers": {"overwrite": false}}""" + )), + "context": { + "mock": "data" + }, + "metadata": { + "mock": "data" + }, + "next_step": + DialogNodeNextStep._from_dict( + json.loads( + """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" + )), + "title": + "string1", + "type": + "string1", + "event_name": + "string1", + "variable": + "string1", + "actions": [], + "digress_in": + "string1", + "digress_out": + "string1", + "digress_out_slots": + "string1", + "user_label": + "string1", + "disambiguation_opt_out": + True, + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) + body.update({ + "dialog_node": + "string1", + "description": + "string1", + "conditions": + "string1", + "parent": + "string1", + "previous_sibling": + "string1", + "output": + DialogNodeOutput._from_dict( + json.loads( + """{"generic": [], "modifiers": {"overwrite": false}}""" + )), + "context": { + "mock": "data" + }, + "metadata": { + "mock": "data" + }, + "next_step": + DialogNodeNextStep._from_dict( + json.loads( + """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" + )), + "title": + "string1", + "type": + "string1", + "event_name": + "string1", + "variable": + "string1", + "actions": [], + "digress_in": + "string1", + "digress_out": + "string1", + "digress_out_slots": + "string1", + "user_label": + "string1", + "disambiguation_opt_out": + True, + }) return body @@ -3040,22 +3347,23 @@ def test_get_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( + body['workspace_id'], body['dialog_node']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.get_dialog_node(**body) return output @@ -3113,22 +3421,23 @@ def test_update_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( + body['workspace_id'], body['dialog_node']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.update_dialog_node(**body) return output @@ -3137,14 +3446,106 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['dialog_node'] = "string1" - body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) + body.update({ + "new_dialog_node": + "string1", + "new_description": + "string1", + "new_conditions": + "string1", + "new_parent": + "string1", + "new_previous_sibling": + "string1", + "new_output": + DialogNodeOutput._from_dict( + json.loads( + """{"generic": [], "modifiers": {"overwrite": false}}""" + )), + "new_context": { + "mock": "data" + }, + "new_metadata": { + "mock": "data" + }, + "new_next_step": + DialogNodeNextStep._from_dict( + json.loads( + """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" + )), + "new_title": + "string1", + "new_type": + "string1", + "new_event_name": + "string1", + "new_variable": + "string1", + "new_actions": [], + "new_digress_in": + "string1", + "new_digress_out": + "string1", + "new_digress_out_slots": + "string1", + "new_user_label": + "string1", + "new_disambiguation_opt_out": + True, + }) return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['dialog_node'] = "string1" - body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) + body.update({ + "new_dialog_node": + "string1", + "new_description": + "string1", + "new_conditions": + "string1", + "new_parent": + "string1", + "new_previous_sibling": + "string1", + "new_output": + DialogNodeOutput._from_dict( + json.loads( + """{"generic": [], "modifiers": {"overwrite": false}}""" + )), + "new_context": { + "mock": "data" + }, + "new_metadata": { + "mock": "data" + }, + "new_next_step": + DialogNodeNextStep._from_dict( + json.loads( + """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" + )), + "new_title": + "string1", + "new_type": + "string1", + "new_event_name": + "string1", + "new_variable": + "string1", + "new_actions": [], + "new_digress_in": + "string1", + "new_digress_out": + "string1", + "new_digress_out_slots": + "string1", + "new_user_label": + "string1", + "new_disambiguation_opt_out": + True, + }) return body @@ -3187,22 +3588,23 @@ def test_delete_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( + body['workspace_id'], body['dialog_node']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_dialog_node(**body) return output @@ -3230,6 +3632,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_logs #----------------------------------------------------------------------------- @@ -3275,16 +3678,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_logs(**body) return output @@ -3349,16 +3752,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.list_all_logs(**body) return output @@ -3387,6 +3790,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for delete_user_data #----------------------------------------------------------------------------- @@ -3432,16 +3836,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=202, - content_type='') - + url, + body=json.dumps(response), + status=202, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output @@ -3479,6 +3883,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -3495,6 +3900,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -3506,6 +3912,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -3522,6 +3929,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index a43dd8c1b..0c2cb1abd 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -28,6 +28,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_session #----------------------------------------------------------------------------- @@ -73,16 +74,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.create_session(**body) return output @@ -137,22 +138,23 @@ def test_delete_session_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/assistants/{0}/sessions/{1}'.format(body['assistant_id'], body['session_id']) + endpoint = '/v2/assistants/{0}/sessions/{1}'.format( + body['assistant_id'], body['session_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.delete_session(**body) return output @@ -180,6 +182,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for message #----------------------------------------------------------------------------- @@ -219,22 +222,23 @@ def test_message_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format(body['assistant_id'], body['session_id']) + endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format( + body['assistant_id'], body['session_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), version='2019-02-28', - ) + ) service.set_service_url(base_url) output = service.message(**body) return output @@ -243,7 +247,18 @@ def construct_full_body(self): body = dict() body['assistant_id'] = "string1" body['session_id'] = "string1" - body.update({"input": MessageInput._from_dict(json.loads("""{"message_type": "fake_message_type", "text": "fake_text", "options": {"debug": false, "restart": false, "alternate_intents": false, "return_context": true}, "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id"}""")), "context": MessageContext._from_dict(json.loads("""{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10}}, "skills": {}}""")), }) + body.update({ + "input": + MessageInput._from_dict( + json.loads( + """{"message_type": "fake_message_type", "text": "fake_text", "options": {"debug": false, "restart": false, "alternate_intents": false, "return_context": true}, "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id"}""" + )), + "context": + MessageContext._from_dict( + json.loads( + """{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10}}, "skills": {}}""" + )), + }) return body def construct_required_body(self): @@ -275,6 +290,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -291,6 +307,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -302,6 +319,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -318,6 +336,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_common.py b/test/unit/test_common.py index a2553e86f..110f26259 100644 --- a/test/unit/test_common.py +++ b/test/unit/test_common.py @@ -17,11 +17,16 @@ from ibm_watson import get_sdk_headers import unittest + class TestCommon(unittest.TestCase): + def test_get_sdk_headers(self): headers = get_sdk_headers('my_service', 'v1', 'my_operation') self.assertIsNotNone(headers) self.assertIsNotNone(headers.get('X-IBMCloud-SDK-Analytics')) self.assertIsNotNone(headers.get('User-Agent')) self.assertIn('watson-apis-python-sdk', headers.get('User-Agent')) - self.assertEqual(headers.get('X-IBMCloud-SDK-Analytics'), 'service_name=my_service;service_version=v1;operation_id=my_operation') + self.assertEqual( + headers.get('X-IBMCloud-SDK-Analytics'), + 'service_name=my_service;service_version=v1;operation_id=my_operation' + ) diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 0100cabe8..171458bd1 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -30,6 +30,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for convert_to_html #----------------------------------------------------------------------------- @@ -75,16 +76,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.convert_to_html(**body) return output @@ -112,6 +113,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for classify_elements #----------------------------------------------------------------------------- @@ -157,16 +159,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.classify_elements(**body) return output @@ -194,6 +196,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for extract_tables #----------------------------------------------------------------------------- @@ -239,16 +242,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.extract_tables(**body) return output @@ -276,6 +279,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for compare_documents #----------------------------------------------------------------------------- @@ -321,16 +325,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.compare_documents(**body) return output @@ -363,6 +367,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for add_feedback #----------------------------------------------------------------------------- @@ -408,28 +413,48 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.add_feedback(**body) return output def construct_full_body(self): body = dict() - body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) + body.update({ + "feedback_data": + FeedbackDataInput._from_dict( + json.loads( + """{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""" + )), + "user_id": + "string1", + "comment": + "string1", + }) return body def construct_required_body(self): body = dict() - body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) + body.update({ + "feedback_data": + FeedbackDataInput._from_dict( + json.loads( + """{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""" + )), + "user_id": + "string1", + "comment": + "string1", + }) return body @@ -477,16 +502,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.list_feedback(**body) return output @@ -561,16 +586,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.get_feedback(**body) return output @@ -632,16 +657,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.delete_feedback(**body) return output @@ -668,6 +693,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_batch #----------------------------------------------------------------------------- @@ -713,16 +739,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.create_batch(**body) return output @@ -795,16 +821,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.list_batches(**body) return output @@ -863,16 +889,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.get_batch(**body) return output @@ -933,16 +959,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.update_batch(**body) return output @@ -983,6 +1009,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -999,6 +1026,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -1010,6 +1038,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -1026,6 +1055,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index e1ed74b89..363c5d6e9 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -30,6 +30,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_environment #----------------------------------------------------------------------------- @@ -75,28 +76,36 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_environment(**body) return output def construct_full_body(self): body = dict() - body.update({"name": "string1", "description": "string1", "size": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "size": "string1", + }) return body def construct_required_body(self): body = dict() - body.update({"name": "string1", "description": "string1", "size": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "size": "string1", + }) return body @@ -144,16 +153,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_environments(**body) return output @@ -213,16 +222,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_environment(**body) return output @@ -283,16 +292,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_environment(**body) return output @@ -300,13 +309,21 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "size": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "size": "string1", + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "size": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "size": "string1", + }) return body @@ -341,7 +358,8 @@ def test_delete_environment_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_environment_empty(self): - check_empty_required_params(self, fake_response_DeleteEnvironmentResponse_json) + check_empty_required_params( + self, fake_response_DeleteEnvironmentResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -355,16 +373,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_environment(**body) return output @@ -411,7 +429,8 @@ def test_list_fields_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_fields_empty(self): - check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) + check_empty_required_params( + self, fake_response_ListCollectionFieldsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -425,16 +444,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_fields(**body) return output @@ -462,6 +481,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_configuration #----------------------------------------------------------------------------- @@ -501,22 +521,23 @@ def test_create_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/configurations'.format( + body['environment_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_configuration(**body) return output @@ -524,13 +545,47 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + body.update({ + "name": + "string1", + "description": + "string1", + "conversions": + Conversions._from_dict( + json.loads( + """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" + )), + "enrichments": [], + "normalizations": [], + "source": + Source._from_dict( + json.loads( + """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" + )), + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + body.update({ + "name": + "string1", + "description": + "string1", + "conversions": + Conversions._from_dict( + json.loads( + """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" + )), + "enrichments": [], + "normalizations": [], + "source": + Source._from_dict( + json.loads( + """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" + )), + }) return body @@ -565,7 +620,8 @@ def test_list_configurations_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_configurations_empty(self): - check_empty_required_params(self, fake_response_ListConfigurationsResponse_json) + check_empty_required_params( + self, fake_response_ListConfigurationsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -573,22 +629,23 @@ def test_list_configurations_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/configurations'.format( + body['environment_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_configurations(**body) return output @@ -644,22 +701,23 @@ def test_get_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + endpoint = '/v1/environments/{0}/configurations/{1}'.format( + body['environment_id'], body['configuration_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_configuration(**body) return output @@ -716,22 +774,23 @@ def test_update_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + endpoint = '/v1/environments/{0}/configurations/{1}'.format( + body['environment_id'], body['configuration_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_configuration(**body) return output @@ -740,14 +799,48 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['configuration_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + body.update({ + "name": + "string1", + "description": + "string1", + "conversions": + Conversions._from_dict( + json.loads( + """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" + )), + "enrichments": [], + "normalizations": [], + "source": + Source._from_dict( + json.loads( + """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" + )), + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['configuration_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) + body.update({ + "name": + "string1", + "description": + "string1", + "conversions": + Conversions._from_dict( + json.loads( + """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" + )), + "enrichments": [], + "normalizations": [], + "source": + Source._from_dict( + json.loads( + """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" + )), + }) return body @@ -782,7 +875,8 @@ def test_delete_configuration_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_configuration_empty(self): - check_empty_required_params(self, fake_response_DeleteConfigurationResponse_json) + check_empty_required_params( + self, fake_response_DeleteConfigurationResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -790,22 +884,23 @@ def test_delete_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) + endpoint = '/v1/environments/{0}/configurations/{1}'.format( + body['environment_id'], body['configuration_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_configuration(**body) return output @@ -833,6 +928,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_collection #----------------------------------------------------------------------------- @@ -872,22 +968,23 @@ def test_create_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/collections'.format( + body['environment_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_collection(**body) return output @@ -895,13 +992,23 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "configuration_id": "string1", + "language": "string1", + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "configuration_id": "string1", + "language": "string1", + }) return body @@ -936,7 +1043,8 @@ def test_list_collections_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_collections_empty(self): - check_empty_required_params(self, fake_response_ListCollectionsResponse_json) + check_empty_required_params(self, + fake_response_ListCollectionsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -944,22 +1052,23 @@ def test_list_collections_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/collections'.format( + body['environment_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_collections(**body) return output @@ -1015,22 +1124,23 @@ def test_get_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}'.format( + body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_collection(**body) return output @@ -1087,22 +1197,23 @@ def test_update_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}'.format( + body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_collection(**body) return output @@ -1111,14 +1222,22 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "configuration_id": "string1", + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) + body.update({ + "name": "string1", + "description": "string1", + "configuration_id": "string1", + }) return body @@ -1153,7 +1272,8 @@ def test_delete_collection_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_collection_empty(self): - check_empty_required_params(self, fake_response_DeleteCollectionResponse_json) + check_empty_required_params( + self, fake_response_DeleteCollectionResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1161,22 +1281,23 @@ def test_delete_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}'.format( + body['environment_id'], body['collection_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_collection(**body) return output @@ -1225,7 +1346,8 @@ def test_list_collection_fields_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_collection_fields_empty(self): - check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) + check_empty_required_params( + self, fake_response_ListCollectionFieldsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1233,22 +1355,23 @@ def test_list_collection_fields_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/fields'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/fields'.format( + body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_collection_fields(**body) return output @@ -1276,6 +1399,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_expansions #----------------------------------------------------------------------------- @@ -1315,22 +1439,23 @@ def test_list_expansions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format( + body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_expansions(**body) return output @@ -1387,22 +1512,23 @@ def test_create_expansions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format( + body['environment_id'], body['collection_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_expansions(**body) return output @@ -1411,14 +1537,18 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"expansions": [], }) + body.update({ + "expansions": [], + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"expansions": [], }) + body.update({ + "expansions": [], + }) return body @@ -1461,22 +1591,23 @@ def test_delete_expansions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format( + body['environment_id'], body['collection_id']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_expansions(**body) return output @@ -1525,7 +1656,8 @@ def test_get_tokenization_dictionary_status_required_response(self): #-------------------------------------------------------- @responses.activate def test_get_tokenization_dictionary_status_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, + fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1533,22 +1665,23 @@ def test_get_tokenization_dictionary_status_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( + body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_tokenization_dictionary_status(**body) return output @@ -1597,7 +1730,8 @@ def test_create_tokenization_dictionary_required_response(self): #-------------------------------------------------------- @responses.activate def test_create_tokenization_dictionary_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, + fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1605,22 +1739,23 @@ def test_create_tokenization_dictionary_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( + body['environment_id'], body['collection_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_tokenization_dictionary(**body) return output @@ -1629,7 +1764,9 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"tokenization_rules": [], }) + body.update({ + "tokenization_rules": [], + }) return body def construct_required_body(self): @@ -1678,22 +1815,23 @@ def test_delete_tokenization_dictionary_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( + body['environment_id'], body['collection_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_tokenization_dictionary(**body) return output @@ -1742,7 +1880,8 @@ def test_get_stopword_list_status_required_response(self): #-------------------------------------------------------- @responses.activate def test_get_stopword_list_status_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, + fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1750,22 +1889,23 @@ def test_get_stopword_list_status_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( + body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_stopword_list_status(**body) return output @@ -1814,7 +1954,8 @@ def test_create_stopword_list_required_response(self): #-------------------------------------------------------- @responses.activate def test_create_stopword_list_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, + fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1822,22 +1963,23 @@ def test_create_stopword_list_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( + body['environment_id'], body['collection_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_stopword_list(**body) return output @@ -1897,22 +2039,23 @@ def test_delete_stopword_list_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( + body['environment_id'], body['collection_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_stopword_list(**body) return output @@ -1940,6 +2083,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for add_document #----------------------------------------------------------------------------- @@ -1979,22 +2123,23 @@ def test_add_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents'.format( + body['environment_id'], body['collection_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.add_document(**body) return output @@ -2055,22 +2200,23 @@ def test_get_document_status_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( + body['environment_id'], body['collection_id'], body['document_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_document_status(**body) return output @@ -2129,22 +2275,23 @@ def test_update_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( + body['environment_id'], body['collection_id'], body['document_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_document(**body) return output @@ -2199,7 +2346,8 @@ def test_delete_document_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_document_empty(self): - check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) + check_empty_required_params(self, + fake_response_DeleteDocumentResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2207,22 +2355,23 @@ def test_delete_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( + body['environment_id'], body['collection_id'], body['document_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -2252,6 +2401,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for query #----------------------------------------------------------------------------- @@ -2291,22 +2441,23 @@ def test_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/query'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/query'.format( + body['environment_id'], body['collection_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.query(**body) return output @@ -2315,7 +2466,28 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", "spelling_suggestions": True, }) + body.update({ + "filter": "string1", + "query": "string1", + "natural_language_query": "string1", + "passages": True, + "aggregation": "string1", + "count": 12345, + "return_": "string1", + "offset": 12345, + "sort": "string1", + "highlight": True, + "passages_fields": "string1", + "passages_count": 12345, + "passages_characters": 12345, + "deduplicate": True, + "deduplicate_field": "string1", + "similar": True, + "similar_document_ids": "string1", + "similar_fields": "string1", + "bias": "string1", + "spelling_suggestions": True, + }) body['x_watson_logging_opt_out'] = True return body @@ -2357,7 +2529,8 @@ def test_query_notices_required_response(self): #-------------------------------------------------------- @responses.activate def test_query_notices_empty(self): - check_empty_required_params(self, fake_response_QueryNoticesResponse_json) + check_empty_required_params(self, + fake_response_QueryNoticesResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2365,22 +2538,23 @@ def test_query_notices_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/notices'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/notices'.format( + body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.query_notices(**body) return output @@ -2460,16 +2634,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.federated_query(**body) return output @@ -2477,14 +2651,56 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) + body.update({ + "collection_ids": "string1", + "filter": "string1", + "query": "string1", + "natural_language_query": "string1", + "passages": True, + "aggregation": "string1", + "count": 12345, + "return_": "string1", + "offset": 12345, + "sort": "string1", + "highlight": True, + "passages_fields": "string1", + "passages_count": 12345, + "passages_characters": 12345, + "deduplicate": True, + "deduplicate_field": "string1", + "similar": True, + "similar_document_ids": "string1", + "similar_fields": "string1", + "bias": "string1", + }) body['x_watson_logging_opt_out'] = True return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) + body.update({ + "collection_ids": "string1", + "filter": "string1", + "query": "string1", + "natural_language_query": "string1", + "passages": True, + "aggregation": "string1", + "count": 12345, + "return_": "string1", + "offset": 12345, + "sort": "string1", + "highlight": True, + "passages_fields": "string1", + "passages_count": 12345, + "passages_characters": 12345, + "deduplicate": True, + "deduplicate_field": "string1", + "similar": True, + "similar_document_ids": "string1", + "similar_fields": "string1", + "bias": "string1", + }) return body @@ -2519,7 +2735,8 @@ def test_federated_query_notices_required_response(self): #-------------------------------------------------------- @responses.activate def test_federated_query_notices_empty(self): - check_empty_required_params(self, fake_response_QueryNoticesResponse_json) + check_empty_required_params(self, + fake_response_QueryNoticesResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2533,16 +2750,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.federated_query_notices(**body) return output @@ -2612,22 +2829,23 @@ def test_get_autocompletion_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/autocompletion'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/autocompletion'.format( + body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_autocompletion(**body) return output @@ -2659,6 +2877,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_training_data #----------------------------------------------------------------------------- @@ -2698,22 +2917,23 @@ def test_list_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format( + body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_training_data(**body) return output @@ -2770,22 +2990,23 @@ def test_add_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format( + body['environment_id'], body['collection_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.add_training_data(**body) return output @@ -2794,14 +3015,22 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) + body.update({ + "natural_language_query": "string1", + "filter": "string1", + "examples": [], + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) + body.update({ + "natural_language_query": "string1", + "filter": "string1", + "examples": [], + }) return body @@ -2844,22 +3073,23 @@ def test_delete_all_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format( + body['environment_id'], body['collection_id']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_all_training_data(**body) return output @@ -2916,22 +3146,23 @@ def test_get_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( + body['environment_id'], body['collection_id'], body['query_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_training_data(**body) return output @@ -2990,22 +3221,23 @@ def test_delete_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( + body['environment_id'], body['collection_id'], body['query_id']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_training_data(**body) return output @@ -3056,7 +3288,8 @@ def test_list_training_examples_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_training_examples_empty(self): - check_empty_required_params(self, fake_response_TrainingExampleList_json) + check_empty_required_params(self, + fake_response_TrainingExampleList_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -3064,22 +3297,23 @@ def test_list_training_examples_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( + body['environment_id'], body['collection_id'], body['query_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_training_examples(**body) return output @@ -3138,22 +3372,23 @@ def test_create_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( + body['environment_id'], body['collection_id'], body['query_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_training_example(**body) return output @@ -3163,7 +3398,11 @@ def construct_full_body(self): body['environment_id'] = "string1" body['collection_id'] = "string1" body['query_id'] = "string1" - body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) + body.update({ + "document_id": "string1", + "cross_reference": "string1", + "relevance": 12345, + }) return body def construct_required_body(self): @@ -3171,7 +3410,11 @@ def construct_required_body(self): body['environment_id'] = "string1" body['collection_id'] = "string1" body['query_id'] = "string1" - body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) + body.update({ + "document_id": "string1", + "cross_reference": "string1", + "relevance": 12345, + }) return body @@ -3214,22 +3457,24 @@ def test_delete_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( + body['environment_id'], body['collection_id'], body['query_id'], + body['example_id']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_training_example(**body) return output @@ -3290,22 +3535,24 @@ def test_update_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( + body['environment_id'], body['collection_id'], body['query_id'], + body['example_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_training_example(**body) return output @@ -3316,7 +3563,10 @@ def construct_full_body(self): body['collection_id'] = "string1" body['query_id'] = "string1" body['example_id'] = "string1" - body.update({"cross_reference": "string1", "relevance": 12345, }) + body.update({ + "cross_reference": "string1", + "relevance": 12345, + }) return body def construct_required_body(self): @@ -3325,7 +3575,10 @@ def construct_required_body(self): body['collection_id'] = "string1" body['query_id'] = "string1" body['example_id'] = "string1" - body.update({"cross_reference": "string1", "relevance": 12345, }) + body.update({ + "cross_reference": "string1", + "relevance": 12345, + }) return body @@ -3368,22 +3621,24 @@ def test_get_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( + body['environment_id'], body['collection_id'], body['query_id'], + body['example_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_training_example(**body) return output @@ -3415,6 +3670,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for delete_user_data #----------------------------------------------------------------------------- @@ -3460,16 +3716,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output @@ -3495,6 +3751,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for create_event #----------------------------------------------------------------------------- @@ -3526,7 +3783,8 @@ def test_create_event_required_response(self): #-------------------------------------------------------- @responses.activate def test_create_event_empty(self): - check_empty_required_params(self, fake_response_CreateEventResponse_json) + check_empty_required_params(self, + fake_response_CreateEventResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -3540,28 +3798,44 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_event(**body) return output def construct_full_body(self): body = dict() - body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) + body.update({ + "type": + "string1", + "data": + EventData._from_dict( + json.loads( + """{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""" + )), + }) return body def construct_required_body(self): body = dict() - body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) + body.update({ + "type": + "string1", + "data": + EventData._from_dict( + json.loads( + """{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""" + )), + }) return body @@ -3609,16 +3883,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.query_log(**body) return output @@ -3681,16 +3955,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query(**body) return output @@ -3751,16 +4025,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query_event(**body) return output @@ -3821,16 +4095,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query_no_results(**body) return output @@ -3891,16 +4165,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_event_rate(**body) return output @@ -3961,16 +4235,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query_token_event(**body) return output @@ -3995,6 +4269,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_credentials #----------------------------------------------------------------------------- @@ -4034,22 +4309,23 @@ def test_list_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/credentials'.format( + body['environment_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_credentials(**body) return output @@ -4104,22 +4380,23 @@ def test_create_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/credentials'.format( + body['environment_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_credentials(**body) return output @@ -4127,13 +4404,33 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + body.update({ + "source_type": + "string1", + "credential_details": + CredentialDetails._from_dict( + json.loads( + """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" + )), + "status": + "string1", + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + body.update({ + "source_type": + "string1", + "credential_details": + CredentialDetails._from_dict( + json.loads( + """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" + )), + "status": + "string1", + }) return body @@ -4176,22 +4473,23 @@ def test_get_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + endpoint = '/v1/environments/{0}/credentials/{1}'.format( + body['environment_id'], body['credential_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_credentials(**body) return output @@ -4248,22 +4546,23 @@ def test_update_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + endpoint = '/v1/environments/{0}/credentials/{1}'.format( + body['environment_id'], body['credential_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_credentials(**body) return output @@ -4272,14 +4571,34 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['credential_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + body.update({ + "source_type": + "string1", + "credential_details": + CredentialDetails._from_dict( + json.loads( + """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" + )), + "status": + "string1", + }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['credential_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) + body.update({ + "source_type": + "string1", + "credential_details": + CredentialDetails._from_dict( + json.loads( + """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" + )), + "status": + "string1", + }) return body @@ -4322,22 +4641,23 @@ def test_delete_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) + endpoint = '/v1/environments/{0}/credentials/{1}'.format( + body['environment_id'], body['credential_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_credentials(**body) return output @@ -4365,6 +4685,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_gateways #----------------------------------------------------------------------------- @@ -4404,22 +4725,23 @@ def test_list_gateways_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/gateways'.format( + body['environment_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_gateways(**body) return output @@ -4474,22 +4796,23 @@ def test_create_gateway_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways'.format(body['environment_id']) + endpoint = '/v1/environments/{0}/gateways'.format( + body['environment_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_gateway(**body) return output @@ -4497,7 +4820,9 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({"name": "string1", }) + body.update({ + "name": "string1", + }) return body def construct_required_body(self): @@ -4545,22 +4870,23 @@ def test_get_gateway_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_id']) + endpoint = '/v1/environments/{0}/gateways/{1}'.format( + body['environment_id'], body['gateway_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_gateway(**body) return output @@ -4617,22 +4943,23 @@ def test_delete_gateway_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_id']) + endpoint = '/v1/environments/{0}/gateways/{1}'.format( + body['environment_id'], body['gateway_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_gateway(**body) return output @@ -4672,6 +4999,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -4688,6 +5016,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -4699,6 +5028,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -4715,6 +5045,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index fedc9e9bd..0276527c2 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -30,6 +30,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_collections #----------------------------------------------------------------------------- @@ -61,7 +62,8 @@ def test_list_collections_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_collections_empty(self): - check_empty_required_params(self, fake_response_ListCollectionsResponse_json) + check_empty_required_params(self, + fake_response_ListCollectionsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -75,16 +77,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.list_collections(**body) return output @@ -110,6 +112,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for query #----------------------------------------------------------------------------- @@ -155,16 +158,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.query(**body) return output @@ -172,7 +175,39 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['project_id'] = "string1" - body.update({"collection_ids": [], "filter": "string1", "query": "string1", "natural_language_query": "string1", "aggregation": "string1", "count": 12345, "return_": [], "offset": 12345, "sort": "string1", "highlight": True, "spelling_suggestions": True, "table_results": QueryLargeTableResults._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "suggested_refinements": QueryLargeSuggestedRefinements._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "passages": QueryLargePassages._from_dict(json.loads("""{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""")), }) + body.update({ + "collection_ids": [], + "filter": + "string1", + "query": + "string1", + "natural_language_query": + "string1", + "aggregation": + "string1", + "count": + 12345, + "return_": [], + "offset": + 12345, + "sort": + "string1", + "highlight": + True, + "spelling_suggestions": + True, + "table_results": + QueryLargeTableResults._from_dict( + json.loads("""{"enabled": false, "count": 5}""")), + "suggested_refinements": + QueryLargeSuggestedRefinements._from_dict( + json.loads("""{"enabled": false, "count": 5}""")), + "passages": + QueryLargePassages._from_dict( + json.loads( + """{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""" + )), + }) return body def construct_required_body(self): @@ -226,16 +261,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.get_autocompletion(**body) return output @@ -287,7 +322,8 @@ def test_query_notices_required_response(self): #-------------------------------------------------------- @responses.activate def test_query_notices_empty(self): - check_empty_required_params(self, fake_response_QueryNoticesResponse_json) + check_empty_required_params(self, + fake_response_QueryNoticesResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -301,16 +337,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.query_notices(**body) return output @@ -376,16 +412,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.list_fields(**body) return output @@ -412,6 +448,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for get_component_settings #----------------------------------------------------------------------------- @@ -443,7 +480,8 @@ def test_get_component_settings_required_response(self): #-------------------------------------------------------- @responses.activate def test_get_component_settings_empty(self): - check_empty_required_params(self, fake_response_ComponentSettingsResponse_json) + check_empty_required_params( + self, fake_response_ComponentSettingsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -451,22 +489,23 @@ def test_get_component_settings_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/component_settings'.format(body['project_id']) + endpoint = '/v2/projects/{0}/component_settings'.format( + body['project_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.get_component_settings(**body) return output @@ -492,6 +531,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for add_document #----------------------------------------------------------------------------- @@ -531,22 +571,23 @@ def test_add_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents'.format(body['project_id'], body['collection_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents'.format( + body['project_id'], body['collection_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.add_document(**body) return output @@ -608,22 +649,23 @@ def test_update_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( + body['project_id'], body['collection_id'], body['document_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.update_document(**body) return output @@ -679,7 +721,8 @@ def test_delete_document_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_document_empty(self): - check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) + check_empty_required_params(self, + fake_response_DeleteDocumentResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -687,22 +730,23 @@ def test_delete_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( + body['project_id'], body['collection_id'], body['document_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -733,6 +777,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_training_queries #----------------------------------------------------------------------------- @@ -772,22 +817,23 @@ def test_list_training_queries_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format( + body['project_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.list_training_queries(**body) return output @@ -842,22 +888,23 @@ def test_delete_training_queries_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format( + body['project_id']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.delete_training_queries(**body) return output @@ -912,22 +959,23 @@ def test_create_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format( + body['project_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.create_training_query(**body) return output @@ -935,13 +983,21 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['project_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) + body.update({ + "natural_language_query": "string1", + "examples": [], + "filter": "string1", + }) return body def construct_required_body(self): body = dict() body['project_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) + body.update({ + "natural_language_query": "string1", + "examples": [], + "filter": "string1", + }) return body @@ -984,22 +1040,23 @@ def test_get_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_id']) + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( + body['project_id'], body['query_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.get_training_query(**body) return output @@ -1056,22 +1113,23 @@ def test_update_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_id']) + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( + body['project_id'], body['query_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.update_training_query(**body) return output @@ -1080,14 +1138,22 @@ def construct_full_body(self): body = dict() body['project_id'] = "string1" body['query_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) + body.update({ + "natural_language_query": "string1", + "examples": [], + "filter": "string1", + }) return body def construct_required_body(self): body = dict() body['project_id'] = "string1" body['query_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) + body.update({ + "natural_language_query": "string1", + "examples": [], + "filter": "string1", + }) return body @@ -1113,6 +1179,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -1129,6 +1196,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -1140,6 +1208,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -1156,6 +1225,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 54f08512e..2a8a15d89 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -30,6 +30,7 @@ ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for translate #----------------------------------------------------------------------------- @@ -75,28 +76,38 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.translate(**body) return output def construct_full_body(self): body = dict() - body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) + body.update({ + "text": [], + "model_id": "string1", + "source": "string1", + "target": "string1", + }) return body def construct_required_body(self): body = dict() - body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) + body.update({ + "text": [], + "model_id": "string1", + "source": "string1", + "target": "string1", + }) return body @@ -110,6 +121,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_identifiable_languages #----------------------------------------------------------------------------- @@ -154,16 +166,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.list_identifiable_languages(**body) return output @@ -208,7 +220,8 @@ def test_identify_required_response(self): #-------------------------------------------------------- @responses.activate def test_identify_empty(self): - check_empty_required_params(self, fake_response_IdentifiedLanguages_json) + check_empty_required_params(self, + fake_response_IdentifiedLanguages_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -222,16 +235,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.identify(**body) return output @@ -257,6 +270,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_models #----------------------------------------------------------------------------- @@ -301,16 +315,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.list_models(**body) return output @@ -372,16 +386,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.create_model(**body) return output @@ -445,16 +459,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.delete_model(**body) return output @@ -515,16 +529,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.get_model(**body) return output @@ -550,6 +564,7 @@ def construct_required_body(self): ############################################################################## # region + #----------------------------------------------------------------------------- # Test Class for list_documents #----------------------------------------------------------------------------- @@ -594,16 +609,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.list_documents(**body) return output @@ -662,16 +677,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.translate_document(**body) return output @@ -738,16 +753,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.get_document_status(**body) return output @@ -808,16 +823,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -872,22 +887,23 @@ def test_get_translated_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v3/documents/{0}/translated_document'.format(body['document_id']) + endpoint = '/v3/documents/{0}/translated_document'.format( + body['document_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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.get_translated_document(**body) return output @@ -926,6 +942,7 @@ def check_empty_required_params(obj, response): error = True assert error + def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -942,6 +959,7 @@ def check_missing_required_params(obj): error = True assert error + def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -953,6 +971,7 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) + def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -969,6 +988,7 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response + #################### ## Mock Responses ## #################### diff --git a/test/unit/test_natural_language_understanding.py b/test/unit/test_natural_language_understanding.py deleted file mode 100644 index d5b01db4c..000000000 --- a/test/unit/test_natural_language_understanding.py +++ /dev/null @@ -1,146 +0,0 @@ -# coding: utf-8 -from unittest import TestCase -from ibm_watson import NaturalLanguageUnderstandingV1 -from ibm_watson.natural_language_understanding_v1 import \ - Features, ConceptsOptions, EntitiesOptions, KeywordsOptions, CategoriesOptions, \ - EmotionOptions, MetadataOptions, SemanticRolesOptions, RelationsOptions, \ - SentimentOptions -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -import os -import pytest -import responses - - -base_url = 'https://gateway.watsonplatform.net' -default_url = '{0}/natural-language-understanding/api'.format(base_url) - - -class TestFeatures(TestCase): - def test_concepts(self): - c = Features(concepts=ConceptsOptions()) - assert c._to_dict() == {'concepts': {}} - c = Features(concepts=ConceptsOptions(limit=10)) - assert c._to_dict() == {'concepts': {'limit': 10}} - - def test_entities(self): - e = Features(entities=EntitiesOptions()) - assert e._to_dict() == {'entities': {}} - - def test_keywords(self): - k = Features(keywords=KeywordsOptions()) - assert k._to_dict() == {'keywords': {}} - - def test_categories(self): - c = Features(categories=CategoriesOptions()) - assert c._to_dict() == {'categories': {}} - - def test_emotion(self): - e = Features(emotion=EmotionOptions()) - assert e._to_dict() == {'emotion': {}} - - def test_metadata(self): - m = Features(metadata=MetadataOptions()) - assert m._to_dict() == {'metadata': {}} - - def test_semantic_roles(self): - s = Features(semantic_roles=SemanticRolesOptions()) - assert s._to_dict() == {'semantic_roles': {}} - - def test_relations(self): - r = Features(relations=RelationsOptions()) - assert r._to_dict() == {'relations': {}} - - def test_sentiment(self): - s = Features(sentiment=SentimentOptions()) - assert s._to_dict() == {'sentiment': {}} - - -class TestNaturalLanguageUnderstanding(TestCase): - def test_version_date(self): - with pytest.raises(TypeError): - NaturalLanguageUnderstandingV1() # pylint: disable=E1120 - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - assert nlu - - @pytest.mark.skipif(os.getenv('VCAP_SERVICES') is not None, - reason='credentials may come from VCAP_SERVICES') - def test_missing_credentials(self): - with pytest.raises(ValueError): - NaturalLanguageUnderstandingV1(version='2016-01-23') - with pytest.raises(ValueError): - NaturalLanguageUnderstandingV1(version='2016-01-23') - - def test_analyze_throws(self): - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - with pytest.raises(ValueError): - nlu.analyze(None, text="this will not work") - - @responses.activate - def test_text_analyze(self): - nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze" - responses.add(responses.POST, nlu_url, - body="{\"resulting_key\": true}", status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - nlu.analyze(Features(sentiment=SentimentOptions()), text="hello this is a test") - assert len(responses.calls) == 1 - - @responses.activate - def test_html_analyze(self): - nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze" - responses.add(responses.POST, nlu_url, - body="{\"resulting_key\": true}", status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - nlu.analyze(Features(sentiment=SentimentOptions(), - emotion=EmotionOptions(document=False)), - html="hello this is a test") - assert len(responses.calls) == 1 - - @responses.activate - def test_url_analyze(self): - nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/analyze" - responses.add(responses.POST, nlu_url, - body="{\"resulting_key\": true}", status=200, - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - nlu.analyze(Features(sentiment=SentimentOptions(), - emotion=EmotionOptions(document=False)), - url="http://cnn.com", - xpath="/bogus/xpath", language="en") - assert len(responses.calls) == 1 - - @responses.activate - def test_list_models(self): - nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models" - responses.add(responses.GET, nlu_url, status=200, - body="{\"resulting_key\": true}", - content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - nlu.list_models() - assert len(responses.calls) == 1 - - @responses.activate - def test_delete_model(self): - model_id = "invalid_model_id" - nlu_url = "https://gateway.watsonplatform.net/natural-language-understanding/api/v1/models/" + model_id - responses.add(responses.DELETE, nlu_url, status=200, - body="{}", content_type='application/json') - authenticator = BasicAuthenticator('username', 'password') - nlu = NaturalLanguageUnderstandingV1(version='2016-01-23', - authenticator=authenticator) - nlu.delete_model(model_id) - assert len(responses.calls) == 1 From 7960f62ae8ab0c517902e822c713e9aae5d07048 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 14 Jan 2020 19:01:55 -0500 Subject: [PATCH 191/455] chore(all): Manually remove unused imports --- ibm_watson/assistant_v1.py | 2 -- ibm_watson/assistant_v2.py | 2 -- ibm_watson/compare_comply_v1.py | 4 ---- ibm_watson/discovery_v1.py | 3 --- ibm_watson/discovery_v2.py | 3 --- ibm_watson/language_translator_v3.py | 3 --- ibm_watson/natural_language_classifier_v1.py | 4 ---- ibm_watson/natural_language_understanding_v1.py | 3 --- ibm_watson/personality_insights_v3.py | 2 -- ibm_watson/speech_to_text_v1.py | 4 ---- ibm_watson/text_to_speech_v1.py | 3 --- ibm_watson/tone_analyzer_v3.py | 2 -- ibm_watson/visual_recognition_v3.py | 3 --- ibm_watson/visual_recognition_v4.py | 4 ---- 14 files changed, 42 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 393be33e2..b48cd04da 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -29,8 +29,6 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 60b838104..dd10f4d60 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -27,8 +27,6 @@ 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 read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 9266c3ffa..c7ef88c6f 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -27,13 +27,9 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources, DetailedResponse -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 from typing import List -from typing import TextIO ############################################################################## # Service diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index f57693456..a0a7b5db6 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -30,13 +30,10 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources, DetailedResponse -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 from typing import List -from typing import TextIO import sys ############################################################################## diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 0af5456bd..ffc9563a3 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -29,13 +29,10 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources, DetailedResponse -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 from typing import List -from typing import TextIO import sys ############################################################################## diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 39c70bf37..defddcbcd 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -29,13 +29,10 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources, DetailedResponse -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 from typing import List -from typing import TextIO ############################################################################## # Service diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 2b7ffd4a6..a32357a57 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -28,13 +28,9 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources, DetailedResponse -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 from typing import List -from typing import TextIO ############################################################################## # Service diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 8fb571cee..f3d22e304 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -32,9 +32,6 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from os.path import basename from typing import Dict from typing import List diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 2f99e5075..afa52b76f 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -39,8 +39,6 @@ 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 read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index b3be2d348..601f7fa12 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -40,13 +40,9 @@ 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 read_external_sources, DetailedResponse -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 from typing import List -from typing import TextIO ############################################################################## # Service diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 371bdf07f..e09c5fb00 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -36,9 +36,6 @@ 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 read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from os.path import basename from typing import Dict from typing import List diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 42287778f..608e4561e 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -31,8 +31,6 @@ 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 read_external_sources, DetailedResponse -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 6d0986b7b..c1d117c7f 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -27,13 +27,10 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources, DetailedResponse -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 from typing import List -from typing import TextIO ############################################################################## # Service diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 8139a7a69..4ad597ff2 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -26,13 +26,9 @@ from ibm_cloud_sdk_core import BaseService 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 import read_external_sources, DetailedResponse -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 from typing import List -from typing import TextIO ############################################################################## # Service From ca3132c1e0d9709b51694b5405db60d47dc88c10 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 15 Jan 2020 12:53:04 -0500 Subject: [PATCH 192/455] chore(travis): update travis integration test values --- .env.enc | Bin 1792 -> 2112 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/.env.enc b/.env.enc index 314487b935a79d4c97b851c97835575d10fd900b..612fb7711487b21a9837e7382aaf4a83fabb0c27 100644 GIT binary patch literal 2112 zcmV-G2*39u_@t;Rprm1?I~j9`+L;k4$}#SPn%PgDyF$A75#!7>d1uWuiXn(_#rhthQdf1-u(GNZvfitv+zkfhNN3hejQ$!- z*l@hcaX7G)HMvzF)BW}4bReyG-Kt)!C_}iT=$E{(fskbYhmV!}t2}G_5J*e5RnGNP zUZ^k{vY>71Z&OvxAMM8)gYkJjR50AMmd~`r#<|})7e2yYp;>V%<)xmmchUe(Tv77X z2iCPcNX`R{eF2Gc*<5V|&Crq)h3De53orF{Dx<%5RR@6k2NtbF#e7LKurIE>Tpsw} zT*$qa?v8Drl6t{ZhO{$2F&IZ}waL;(2R=9JQrIE5cwRUbScmI2phV+yZ0{$4Cgwf1 zud7+7fG=Zu9Q6Uf1by3K9Rlac%QvH2{4<@&=vR{OSM8C}J`=)|;?o(z??FA;pSPei zP@(UnUu@T@&x_oB{U;6?v=^%gE_jJPCRH^Mb5oWh;L}gG7bk%1j4GQzW7nk!DpHJ> zksbE`odgerxs*F1Nln_di`7esJ`A3z+IZ=awo}PSVB2)>-ZCGkB`jUdXJ%!}S};=2 zp|`o*u0S)xm2$XgeS>MM+yYab$|3_+kX_jxGNRO&Tlgr3AmJ0AW*;JP{x8#%Gk9ch zan!+kBUG`%1dh(Qh%I5}#2etQl?l{2oniIy&BavE%Zp!Vet=Iip1yO?bMWQkF!H03 zGhO_J?gc>Chbm zBaU=zn^~{(dIg5$iSg~}oFwr>JK!wGS52F-F?k@K2G{Q^UnINUn5(E*+z&)`Q7leL_{m5V%NhT zMB4-4Jvz%*+e^Xw3&Cj7Kjb9Wi`g3aZt;HF^pPz&scu??I+5>|T$ZRkBD^c8TZnXr zlf7Z;L`WKO@ewAyKGG@qNKaS<;O~uwl(SRuiKSq__T+fxfmQVx0;$MN=(GsAnC!ga z{!vEu(0I@c^Y9Ic3y+u-?HV4YF{5su@Ffq&;tR*B;p1%;A>L7e=t3kL^6y3)Ss^O= zmrAUey9-Z)`JZ%vG&Ut%zmGKd$&4%~LiTeLZd=Y&LgNFCG<@6414mixPyIe1GN*5< z(g1Tx37z-vViXh;14sa@cEmV5_N%(bqln%%o)+#8?#o7x4-|HWv6we0?ZAHTjt3?H zR;J|v0#gw(^3xiuPVqz*m8hu|@hb!hoAp-sG-F@jO`MHlf;s6-Jv{h7eL+Z!<#>I- zY1nIb1|EDey-O|&H|skc13L~#mw&W*gXKPh<#JK==x=b!uhi)EKABzOF1|D((zi$9De zhvriDee((nO{3cQh7vz*?2bD3(Cv^KFA6EeLdusV-jX|my71Xz)&yIrG;hNAGQ&cj z^CId#xJ&Vhxn}NU9d0E!zB^BK;8|s4>m+$0&O8(Z@7OmADm2 z279$oRG^tP8TyHt6G6XqNd5wE2*Nta2iLQUSPZMpRMG-}PC~l~8L_ZK(T+)mBORY9 zD_t(IEJ`z5(Zkys6j{}v-TQMBa&VzFJrDT_rIv;v?isn|v+&uG(C#+fImPLoagx05 zOkk~RllFLxos9=T3~oTQ{f+8VU}v=Jtsy~hjLH`m@I*t6GP}V0`48n$*av#Nq3VD0 zc-6h$hfWQQEbHoAa57_p9GJEg5tZ6%<%1KTVot7ueFcQa?UW=db&?5-bJQU*4IdKD zSw|WM!gzeP;7OmYLOjj(k$n*2@XbiQSiY80cn~KR5UVG}+BF;5rN@2(l2Q6Zx=t_jGGi&Mq!BD38;}zBsFCdTfeGl;WGmwV zM2JvTTqamHW12J_UdN_T)y)GiA{@Q&J+&ux5qk>B308qpdn~t z(}sBHxiBg_;DgOS50xXTrn5~M_JwQ+hCqJa@6>@;70t+4%~5Sd*9Vc;;=eRO2F@3_ qHi8gvW~n#{^Q2aHvUHqNk&c5&7OdtpRDX(O<+&!J@t%Sg(ArvkIT)Y- literal 1792 zcmV+b2mkofCg_VMQQ-b2GupQ4;73}wQ=Z1`5iUqv)8<{whT{GvuJ7TtG!dRJz(Pi$ z#RF$f7H~>ZLaqh zMbzR&zFcCMUvGVJ~VcU=d0NkSPhB_Zb(nQcjEvMdr(xAo4#5aNyyJx+(^8z_D)d~5n0 zozTG@-py9nZ^B!glYX7=0-0I{1E+#Yo*DdUzPG|6F?tm+ttJi_O0)OT(32~znGN>= zc1<6?$u>rIh!O4gc7R+NRu% z!{=PBRgvV~T`LNFN*3^M38lI384JDxt;jKGPJUvvTt`WHcv_MwCj@V1IcVFpe z*u(Nm<^#Sbafs%RQTk0?^xPLYGWc{l+_x5Jq=?Pc0ZPdx?+ zUW+TTzb-1h3kC)L{k@vNhEaH`TsqGs6O(H;o~>gOoMuaJSx6K8C_=yif2JNg-^hC+ z-&*%p)4N!CnE~Y`qX&}=$8JiLb*Gq}SRerD{gN<=xeY>Ekwl*owPA6bn~@XU(L~!2 z1%K)BV>g0LvNb%j=RuvJA2P1hkV8JhZE=B-q*_4#HR4R)j_o1>9Un!;Q-cT87(>B5 zVg7tG?l_9jgu=5Tu~$(L`6?nKe4CN;zWCGJAh3)9s~B7 z=lnv-t&PI;>G|XeGj<-}-c+tF)1ef~xG!&@rPz5<^U8^uQ?|%6!9O@*=2zS^GK@#s z-`4RFeP5#Wiwv@p9pl-D@~6ULFf^kD#qvCfxD6l)&}HSKz)hX&IE$pqGd4zRbcX^> zWZtF4z{xYk0J=1y`ZGu#K49^HGAGZTfBSFc7BNj)AYKn2rAo1v1ZlCh7(|4nFbXNWdci32ERulOZ`<)LK&tWikaaKZUm&}91(l> z_^O2YxIQ0?j?eM!lGSx&3Sv>&taT`X=UZg}vkzzGkeRW6Yb3DZhF z;u0;8{OGR$4m#0KDNfm_Y&rBd#96^4xQc_(4EgRD6h{-7LUX5PX90Tl>-CO&B%@~J z@tAHEy#Qn_y)#}fzi5Ea2ThY6oH%mEVW5r$+5?889$+52O-p#IsYTn=DG!7rp_M0h z#F*I>7C783^g_a9@=Zd!j&K;OF0mWseWr}guf*Lws&&?XKv+XG_I~ya>H3eg!u!%Q z+^~+^4n;Z2^pQ{A8){eh+)4Im7)5_Z0jDTamTKsN8qx2^(xI2chN8||Mo*GLCg)t4 iDd=ohlcEt-zm3{#0D5ai*Twu1StE2IF^TgT0OyHb#C(SU From 4bd210197d92d7bc82a809093647b82da08f24a5 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 16 Jan 2020 13:49:07 -0500 Subject: [PATCH 193/455] chore(copyright): correct copyright year --- ibm_watson/assistant_v1.py | 2 +- ibm_watson/assistant_v2.py | 2 +- ibm_watson/compare_comply_v1.py | 2 +- ibm_watson/discovery_v1.py | 2 +- ibm_watson/discovery_v2.py | 2 +- ibm_watson/language_translator_v3.py | 2 +- ibm_watson/natural_language_classifier_v1.py | 2 +- ibm_watson/natural_language_understanding_v1.py | 2 +- ibm_watson/personality_insights_v3.py | 2 +- ibm_watson/speech_to_text_v1.py | 2 +- ibm_watson/speech_to_text_v1_adapter.py | 2 +- ibm_watson/text_to_speech_v1.py | 2 +- ibm_watson/tone_analyzer_v3.py | 2 +- ibm_watson/visual_recognition_v3.py | 2 +- ibm_watson/visual_recognition_v4.py | 2 +- setup.py | 2 +- test/unit/test_assistant_v1.py | 2 +- test/unit/test_assistant_v2.py | 2 +- test/unit/test_common.py | 2 +- test/unit/test_compare_comply_v1.py | 2 +- test/unit/test_discovery_v1.py | 2 +- test/unit/test_discovery_v2.py | 2 +- test/unit/test_language_translator_v3.py | 2 +- test/unit/test_natural_language_classifier_v1.py | 2 +- test/unit/test_personality_insights_v3.py | 2 +- test/unit/test_speech_to_text_v1.py | 2 +- test/unit/test_text_to_speech_v1.py | 2 +- test/unit/test_tone_analyzer_v3.py | 2 +- test/unit/test_visual_recognition_v3.py | 2 +- test/unit/test_visual_recognition_v4.py | 2 +- 30 files changed, 30 insertions(+), 30 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index b48cd04da..b03b97e85 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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_v2.py b/ibm_watson/assistant_v2.py index dd10f4d60..c3384fb0e 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index c7ef88c6f..df8283d41 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/discovery_v1.py b/ibm_watson/discovery_v1.py index a0a7b5db6..c06230534 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/discovery_v2.py b/ibm_watson/discovery_v2.py index ffc9563a3..4b23c8d5b 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/language_translator_v3.py b/ibm_watson/language_translator_v3.py index defddcbcd..d899c478e 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index a32357a57..632f2a28a 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index f3d22e304..60948e696 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index afa52b76f..37c29ba51 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 601f7fa12..70b37757e 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index c813b5370..3585eefb6 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2018 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2018, 2020. # # 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 e09c5fb00..08edf24c8 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 608e4561e..0aed13498 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index c1d117c7f..77964b699 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 4ad597ff2..22294f14f 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/setup.py b/setup.py index 8e949081a..392c4fd66 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# Copyright 2016 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 59237d056..8dfa617fe 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 0c2cb1abd..8755ee6d5 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_common.py b/test/unit/test_common.py index 110f26259..62e0bbf6b 100644 --- a/test/unit/test_common.py +++ b/test/unit/test_common.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2019 IBM All Rights Reserved. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 171458bd1..7b54f1773 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 363c5d6e9..07c5b3914 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 0276527c2..12cdef354 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 2a8a15d89..f0a4f3098 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index d02f9bbc8..105fe8264 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index 9fae31cba..22cab9e9f 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index c3a534087..1cb6cf5b3 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 2d8efd6f1..8cc3a8c83 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index 8ff7cb6c4..d9db2185d 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index 9aecb805e..fb2b7d779 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 1a76c2d4e..0c06d3194 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. From 8bbc0ed3194d28cc4d0bd32b513988896c65087e Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 16 Jan 2020 15:05:14 -0500 Subject: [PATCH 194/455] chore(servicename): Manual changes to service name --- .env.enc | Bin 2112 -> 1792 bytes ibm_watson/assistant_v1.py | 2 +- ibm_watson/assistant_v2.py | 2 +- ibm_watson/compare_comply_v1.py | 2 +- ibm_watson/visual_recognition_v3.py | 2 +- ibm_watson/visual_recognition_v4.py | 2 +- 6 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.env.enc b/.env.enc index 612fb7711487b21a9837e7382aaf4a83fabb0c27..2ce119a8345c896d40fa79e8c11cbb3240481f78 100644 GIT binary patch literal 1792 zcmV+b2mknBubJpO&gX#hB52B27T>;ohes7tHO9E1FskTFm@Pz31VtUp+Kl$uwplq0 zva)YFyTM{koP@8B;tO4(gEzq<0kEu zOZTN~*X*y5Y7t!74bjONP++|0lh`BCnrNSV-E3Lz(c7aMc0GNo$}`sv&7_HEt}O>{ zV$+avXO*d&{_GxV|2vK&4pKpbsoEE+ueuZ8+FpE}Wq>v|5KN7KSC4eje1q-R=d5E5 zrphd+hL?Rmx=jlP$h@r_hf|_5q@dZXLSMuTu7a%;}v1C>kPclo9_5{jVcKO^BZbT zl|#?s42%1^O)+m;K2?yrJOx>(=Lj-PR%=1zYM~5S3u7;l|1~ScaKu4WNIFjVMI-Qc zjL2|O{d0auj0ATQWi;6}=_`$XhHQ)aHSbN~@gaZF-=*;ygI<8QjB@7jz89T?oDhyu z`Q^aaN2i-fph@=N2a5nYF6z@4G6SucV+C(!N8?<-VgD{NX@+5OXc%rv+bcPQB4%NW z##82S4U^u3IQ;G$EySQBVV<5LSFlF!48n^wBH@u!aVe+7+O*hH8+{?hKP-1K^*Kb> z8AZpuq2W;xM%~sa*Eq-tVWA;~MAJM$Peu{bu?(pLq}N-ecIq5Um3~W#RHAso6bXhF zd;sze_5hg>3cEZjU`RQ-Uzz#x52Z(gsEdMZ@eko)fsd99f8jZ`{Ae^7ugsec>!iUugupbnb z1_IgdxlBW_`HJIJD)FGAW7_eTU!s^hAO_daG8e#OyXY)?(N$D}j6qHN1AxV@430vA zI_s1^pyx4*(8h`7^Q`7xk#3(14NkoS3@t<;4F}9kC7l#@?Iv_XxjN>8xnngqF;MUd zDUFBTS+YnXqg5nlye@9^7E``~x#p4d1!gIcldYBUEQV=!uz$!N+wgvj1s*lF?JG<* z_Lrj!u*0VB${tE{_+sdk4@Q7nDISw-ci3^Cry>n+j3LntUYu$304`}+Yq0H~jbB|r zCXo9lN z%CWFlISUZp>$0WMPRi~GgVfvNiKOAfOK> z;66VOdCg}wRu0jLT4YZs{H}C{uNY1gYs#Y>0(q=q4Y5-_^8UJzkYbP__p38=B`H_g zrQFZV8t6W50eXon``(2uu||o{107qp+F(J5a`#4s3Pk_-+%?^RO_gFOR_xz5$QUmZ z)A--qIar_?2hh0jcEI&^b2WBHSYk}FXO&2gy}m#(?kDEk>Snc_ck0ZW)z9s3fRG?l zeERqr=HW8n0@(|ZBQy@K=w`G8Y*hxo;C&vxlJXQf&}rqEBv$}RMfIr|t*`NR%Zq4y zNTRnhLL@z%$I6J=@eADc=g>K4aOWU8fI}{x`epg?28_FztN#Xah$N_ELN%1oKHW2;n;uu3LdtXKES${DIBx6IIC%xYmnrrRuejP{*1fL@^Mg6)&)q=UnTugS{SLvUe*&XsX(2Q&U{`@j0wfDjGDdmS5 z$70)GE6NAIS$hG`aogy^lrI@-9XMS;F{=-FSk~qkR*Ry7jBkw+&9FWVL%qMXHj4D> zVI*Dl!j?q|t6OAo>?j%zB*e35(;Z+iM?&|Ime^_vLp?{>4=|?px*wZ`N@+c@aj{mY iZJh-Es-ot;5e-hJ!OnC$3bsem0n4d1uWuiXn(_#rhthQdf1-u(GNZvfitv+zkfhNN3hejQ$!- z*l@hcaX7G)HMvzF)BW}4bReyG-Kt)!C_}iT=$E{(fskbYhmV!}t2}G_5J*e5RnGNP zUZ^k{vY>71Z&OvxAMM8)gYkJjR50AMmd~`r#<|})7e2yYp;>V%<)xmmchUe(Tv77X z2iCPcNX`R{eF2Gc*<5V|&Crq)h3De53orF{Dx<%5RR@6k2NtbF#e7LKurIE>Tpsw} zT*$qa?v8Drl6t{ZhO{$2F&IZ}waL;(2R=9JQrIE5cwRUbScmI2phV+yZ0{$4Cgwf1 zud7+7fG=Zu9Q6Uf1by3K9Rlac%QvH2{4<@&=vR{OSM8C}J`=)|;?o(z??FA;pSPei zP@(UnUu@T@&x_oB{U;6?v=^%gE_jJPCRH^Mb5oWh;L}gG7bk%1j4GQzW7nk!DpHJ> zksbE`odgerxs*F1Nln_di`7esJ`A3z+IZ=awo}PSVB2)>-ZCGkB`jUdXJ%!}S};=2 zp|`o*u0S)xm2$XgeS>MM+yYab$|3_+kX_jxGNRO&Tlgr3AmJ0AW*;JP{x8#%Gk9ch zan!+kBUG`%1dh(Qh%I5}#2etQl?l{2oniIy&BavE%Zp!Vet=Iip1yO?bMWQkF!H03 zGhO_J?gc>Chbm zBaU=zn^~{(dIg5$iSg~}oFwr>JK!wGS52F-F?k@K2G{Q^UnINUn5(E*+z&)`Q7leL_{m5V%NhT zMB4-4Jvz%*+e^Xw3&Cj7Kjb9Wi`g3aZt;HF^pPz&scu??I+5>|T$ZRkBD^c8TZnXr zlf7Z;L`WKO@ewAyKGG@qNKaS<;O~uwl(SRuiKSq__T+fxfmQVx0;$MN=(GsAnC!ga z{!vEu(0I@c^Y9Ic3y+u-?HV4YF{5su@Ffq&;tR*B;p1%;A>L7e=t3kL^6y3)Ss^O= zmrAUey9-Z)`JZ%vG&Ut%zmGKd$&4%~LiTeLZd=Y&LgNFCG<@6414mixPyIe1GN*5< z(g1Tx37z-vViXh;14sa@cEmV5_N%(bqln%%o)+#8?#o7x4-|HWv6we0?ZAHTjt3?H zR;J|v0#gw(^3xiuPVqz*m8hu|@hb!hoAp-sG-F@jO`MHlf;s6-Jv{h7eL+Z!<#>I- zY1nIb1|EDey-O|&H|skc13L~#mw&W*gXKPh<#JK==x=b!uhi)EKABzOF1|D((zi$9De zhvriDee((nO{3cQh7vz*?2bD3(Cv^KFA6EeLdusV-jX|my71Xz)&yIrG;hNAGQ&cj z^CId#xJ&Vhxn}NU9d0E!zB^BK;8|s4>m+$0&O8(Z@7OmADm2 z279$oRG^tP8TyHt6G6XqNd5wE2*Nta2iLQUSPZMpRMG-}PC~l~8L_ZK(T+)mBORY9 zD_t(IEJ`z5(Zkys6j{}v-TQMBa&VzFJrDT_rIv;v?isn|v+&uG(C#+fImPLoagx05 zOkk~RllFLxos9=T3~oTQ{f+8VU}v=Jtsy~hjLH`m@I*t6GP}V0`48n$*av#Nq3VD0 zc-6h$hfWQQEbHoAa57_p9GJEg5tZ6%<%1KTVot7ueFcQa?UW=db&?5-bJQU*4IdKD zSw|WM!gzeP;7OmYLOjj(k$n*2@XbiQSiY80cn~KR5UVG}+BF;5rN@2(l2Q6Zx=t_jGGi&Mq!BD38;}zBsFCdTfeGl;WGmwV zM2JvTTqamHW12J_UdN_T)y)GiA{@Q&J+&ux5qk>B308qpdn~t z(}sBHxiBg_;DgOS50xXTrn5~M_JwQ+hCqJa@6>@;70t+4%~5Sd*9Vc;;=eRO2F@3_ qHi8gvW~n#{^Q2aHvUHqNk&c5&7OdtpRDX(O<+&!J@t%Sg(ArvkIT)Y- diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index b03b97e85..42a0b126c 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -41,7 +41,7 @@ class AssistantV1(BaseService): """The Assistant V1 service.""" DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' - DEFAULT_SERVICE_NAME = 'conversation' + DEFAULT_SERVICE_NAME = 'assistant' def __init__( self, diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index c3384fb0e..11157bbac 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -39,7 +39,7 @@ class AssistantV2(BaseService): """The Assistant V2 service.""" DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' - DEFAULT_SERVICE_NAME = 'conversation' + DEFAULT_SERVICE_NAME = 'assistant' def __init__( self, diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index df8283d41..01339bdbd 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -40,7 +40,7 @@ class CompareComplyV1(BaseService): """The Compare Comply V1 service.""" DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/compare-comply/api' - DEFAULT_SERVICE_NAME = 'compare-comply' + DEFAULT_SERVICE_NAME = 'compare_comply' def __init__( self, diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 77964b699..9428e5ab8 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -41,7 +41,7 @@ class VisualRecognitionV3(BaseService): """The Visual Recognition V3 service.""" DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' - DEFAULT_SERVICE_NAME = 'watson_vision_combined' + DEFAULT_SERVICE_NAME = 'visual_recognition' def __init__( self, diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 22294f14f..cdabfac4c 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -39,7 +39,7 @@ class VisualRecognitionV4(BaseService): """The Visual Recognition V4 service.""" DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' - DEFAULT_SERVICE_NAME = 'watson_vision_combined' + DEFAULT_SERVICE_NAME = 'visual_recognition' def __init__( self, From 0d09c8f52632652c07703388652c60c4a1d42733 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 16 Jan 2020 22:35:47 +0000 Subject: [PATCH 195/455] =?UTF-8?q?Bump=20version:=204.1.0=20=E2=86=92=204?= =?UTF-8?q?.2.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 0951758da..6ac62c5dc 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.1.0 +current_version = 4.2.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index fa721b497..ea5d65fc7 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.1.0' +__version__ = '4.2.0' diff --git a/setup.py b/setup.py index 392c4fd66..91f4987c3 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.1.0' +__version__ = '4.2.0' if sys.argv[-1] == 'publish': From d5ae0704ab5c8e4ebb9a2fd2f4258b4d492281ff Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 16 Jan 2020 22:35:47 +0000 Subject: [PATCH 196/455] chore(release): 4.2.0 release notes # [4.2.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.1.0...v4.2.0) (2020-01-16) ### Features * **core:** Update core version ([88106fb](https://github.com/watson-developer-cloud/python-sdk/commit/88106fb9c9460e60363a814565b51a512805f8b9)) * **stt:** New param `end_of_phrase_silence_time` and `split_transcript_at_phrase_end` in `recognize` ([776dc86](https://github.com/watson-developer-cloud/python-sdk/commit/776dc8635a98489a9ceb8abf155947bb0f39ad8a)) * **stt:** New param `end_of_phrase_silence_time` and `split_transcription` in recognize_using_websocket ([040946f](https://github.com/watson-developer-cloud/python-sdk/commit/040946f88d6b652f8b8e5638429b69fb1035e79a)) --- CHANGELOG.md | 9 +++ package-lock.json | 171 +++++++++++++++++----------------------------- 2 files changed, 70 insertions(+), 110 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c425f246..292541a5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +# [4.2.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.1.0...v4.2.0) (2020-01-16) + + +### Features + +* **core:** Update core version ([88106fb](https://github.com/watson-developer-cloud/python-sdk/commit/88106fb9c9460e60363a814565b51a512805f8b9)) +* **stt:** New param `end_of_phrase_silence_time` and `split_transcript_at_phrase_end` in `recognize` ([776dc86](https://github.com/watson-developer-cloud/python-sdk/commit/776dc8635a98489a9ceb8abf155947bb0f39ad8a)) +* **stt:** New param `end_of_phrase_silence_time` and `split_transcription` in recognize_using_websocket ([040946f](https://github.com/watson-developer-cloud/python-sdk/commit/040946f88d6b652f8b8e5638429b69fb1035e79a)) + # [4.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.0.4...v4.1.0) (2019-11-27) diff --git a/package-lock.json b/package-lock.json index 3603f0197..6dfeb67ad 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3,17 +3,17 @@ "lockfileVersion": 1, "dependencies": { "@babel/code-frame": { - "version": "7.5.5", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.5.5.tgz", - "integrity": "sha512-27d4lZoomVyo51VegxI20xZPuSHusqbQag/ztrBC7wegWoQ1nLREPVSKSW8byhTlzTKyNE4ifaTA6lCp7JjpFw==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz", + "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==", "requires": { - "@babel/highlight": "^7.0.0" + "@babel/highlight": "^7.8.3" } }, "@babel/highlight": { - "version": "7.5.0", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.5.0.tgz", - "integrity": "sha512-7dV4eu9gBxoM0dAnj/BCFDW9LFU0zvTrkq0ugM7pnHEgguOEeOz1so2ZghEdzviYzQEED0r4EAgpsBChKy1TRQ==", + "version": "7.8.3", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.8.3.tgz", + "integrity": "sha512-PX4y5xQUvy0fnEVHrYOarRPXVWafSjTW9T0Hab8gVIawpl2Sj0ORyrygANq+KjcNlSSTw0YCLSNA8OyZ1I4yEg==", "requires": { "chalk": "^2.0.0", "esutils": "^2.0.2", @@ -79,9 +79,9 @@ } }, "@octokit/rest": { - "version": "16.35.0", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.35.0.tgz", - "integrity": "sha512-9ShFqYWo0CLoGYhA1FdtdykJuMzS/9H6vSbbQWDX4pWr4p9v+15MsH/wpd/3fIU+tSxylaNO48+PIHqOkBRx3w==", + "version": "16.36.0", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.36.0.tgz", + "integrity": "sha512-zoZj7Ya4vWBK4fjTwK2Cnmu7XBB1p9ygSvTk2TthN6DVJXM4hQZQoAiknWFLJWSTix4dnA3vuHtjPZbExYoCZA==", "requires": { "@octokit/request": "^5.2.0", "@octokit/request-error": "^1.0.2", @@ -122,39 +122,37 @@ "integrity": "sha512-9Tj/qn+y2j+sjCI3Jd+qseGtHjOAeg7dU2/lVcqIQ9TV3QDaDXDYXcoOHU+7o2Hwh8L8ymL4gfuO7KxDs3q2zg==" }, "@semantic-release/exec": { - "version": "3.3.8", - "resolved": "https://registry.npmjs.org/@semantic-release/exec/-/exec-3.3.8.tgz", - "integrity": "sha512-GH1v5BwXRIUAnvrXjil+R+9DjI+ELgk2NMdQUAnp2/qZ6YItZt6KI8HrY3zAFDrG0YGaOwC9XxuUNKeldsOK7A==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@semantic-release/exec/-/exec-4.0.0.tgz", + "integrity": "sha512-cOvPeWllHaTkwA0Y/Ffskrc1Fcu2VB5YmOYGfDmznTtUIPMk42UuwqsNVYwQPBsHYIggOFkjlnXvInZsGzEe2Q==", "requires": { "@semantic-release/error": "^2.1.0", "aggregate-error": "^3.0.0", "debug": "^4.0.0", - "execa": "^3.2.0", + "execa": "^4.0.0", "lodash": "^4.17.4", "parse-json": "^5.0.0" } }, "@semantic-release/git": { - "version": "7.0.18", - "resolved": "https://registry.npmjs.org/@semantic-release/git/-/git-7.0.18.tgz", - "integrity": "sha512-VwnsGUXpNdvPcsq05BQyLBZxGUlEiJCMKNi8ttLvZZAhjI1mAp9dwypOeyxSJ5eFQ+iGMBLdoKF1LL0pmA/d0A==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/@semantic-release/git/-/git-8.0.0.tgz", + "integrity": "sha512-CfjEXtxd4zmhAPtPfrerHQi5QkdMzDhoZY7bUi4zjz3S6PaAlJrpAt09/iV+JKmePEJWiWFla/+a0Y9Qull7YQ==", "requires": { "@semantic-release/error": "^2.1.0", "aggregate-error": "^3.0.0", "debug": "^4.0.0", "dir-glob": "^3.0.0", - "execa": "^3.2.0", - "fs-extra": "^8.0.0", - "globby": "^10.0.0", + "execa": "^4.0.0", "lodash": "^4.17.4", "micromatch": "^4.0.0", "p-reduce": "^2.0.0" } }, "@semantic-release/github": { - "version": "5.5.5", - "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-5.5.5.tgz", - "integrity": "sha512-Wo9OIULMRydbq+HpFh9yiLvra1XyEULPro9Tp4T5MQJ0WZyAQ3YQm74IdT8Pe/UmVDq2nfpT1oHrWkwOc4loHg==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-6.0.1.tgz", + "integrity": "sha512-4/xMKFe7svbv5ltvBxoqPY8fBSPyllVtnf2RMHaddeRKC8C/7FqakwRDmui7jgC3alVrVsRtz/jdTdZjB4J28Q==", "requires": { "@octokit/rest": "^16.27.0", "@semantic-release/error": "^2.2.0", @@ -164,9 +162,9 @@ "dir-glob": "^3.0.0", "fs-extra": "^8.0.0", "globby": "^10.0.0", - "http-proxy-agent": "^2.1.0", - "https-proxy-agent": "^3.0.0", - "issue-parser": "^5.0.0", + "http-proxy-agent": "^3.0.0", + "https-proxy-agent": "^4.0.0", + "issue-parser": "^6.0.0", "lodash": "^4.17.4", "mime": "^2.4.3", "p-filter": "^2.0.0", @@ -195,9 +193,9 @@ "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==" }, "@types/node": { - "version": "12.12.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-12.12.14.tgz", - "integrity": "sha512-u/SJDyXwuihpwjXy7hOOghagLEV1KdAST6syfnOk6QZAMzZuWZqXy5aYYZbh8Jdpd4escVFP0MvftHNDb9pruA==" + "version": "13.1.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.1.7.tgz", + "integrity": "sha512-HU0q9GXazqiKwviVxg9SI/+t/nAsGkvLDkIdxz+ObejG2nX6Si00TeLqHMoS+a/1tjH7a8YpKVQwtgHuMQsldg==" }, "@types/retry": { "version": "0.12.0", @@ -205,12 +203,9 @@ "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==" }, "agent-base": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-4.3.0.tgz", - "integrity": "sha512-salcGninV0nPrwpGNn4VTXBb1SOuXQBiqbrNXoeizJsHrsL6ERFM2Ne3JUSBWRE6aeNJI2ROP/WEEIDUiDe3cg==", - "requires": { - "es6-promisify": "^5.0.0" - } + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-5.1.1.tgz", + "integrity": "sha512-TMeqbNl2fMW0nMjTEPOwe3J/PRFP4vqeoNuQMG0HlMrtm5QxKqdvAkZ1pRBQ/ulIyDD5Yq0nJ7YbdD8ey0TO3g==" }, "aggregate-error": { "version": "3.0.1", @@ -356,19 +351,6 @@ "is-arrayish": "^0.2.1" } }, - "es6-promise": { - "version": "4.2.8", - "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.8.tgz", - "integrity": "sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w==" - }, - "es6-promisify": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/es6-promisify/-/es6-promisify-5.0.0.tgz", - "integrity": "sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM=", - "requires": { - "es6-promise": "^4.0.3" - } - }, "escape-string-regexp": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", @@ -380,9 +362,9 @@ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==" }, "execa": { - "version": "3.4.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-3.4.0.tgz", - "integrity": "sha512-r9vdGQk4bmCuK1yKQu1KTwcT2zwfWdbdaXfCtAh+5nU/4fSX+JAb7vZGvI5naJrQlvONrEB20jeruESI69530g==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.0.tgz", + "integrity": "sha512-JbDUxwV3BoT5ZVXQrSVbAiaXhXUkIwvbhPIwZ0N13kX+5yCzOhUNdocxB/UQRuYOHRYYwAxKYwJYc0T4D12pDA==", "requires": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", @@ -391,15 +373,14 @@ "merge-stream": "^2.0.0", "npm-run-path": "^4.0.0", "onetime": "^5.1.0", - "p-finally": "^2.0.0", "signal-exit": "^3.0.2", "strip-final-newline": "^2.0.0" } }, "fast-glob": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.1.0.tgz", - "integrity": "sha512-TrUz3THiq2Vy3bjfQUB2wNyPdGBeGmdjbzzBLhfHN4YFurYptCKwGq/TfiRavbGywFRzY6U2CdmQ1zmsY5yYaw==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.1.1.tgz", + "integrity": "sha512-nTCREpBY8w8r+boyFYAx21iL6faSsQynliPHM4Uf56SbkyohCNxpVPEH9xrF5TXKy+IsjkPUHDKiUkzBVRXn9g==", "requires": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", @@ -469,9 +450,9 @@ } }, "globby": { - "version": "10.0.1", - "resolved": "https://registry.npmjs.org/globby/-/globby-10.0.1.tgz", - "integrity": "sha512-sSs4inE1FB2YQiymcmTv6NWENryABjUNPeWhOvmn4SjtKybglsyPZxFB3U1/+L1bYi0rNZDqCLlHyLYDl1Pq5A==", + "version": "10.0.2", + "resolved": "https://registry.npmjs.org/globby/-/globby-10.0.2.tgz", + "integrity": "sha512-7dUi7RvCoT/xast/o/dLN53oqND4yk0nsHkhRgn9w65C4PofCLOoJ39iSOg+qVDdWQPIEj+eszMHQ+aLVwwQSg==", "requires": { "@types/glob": "^7.1.1", "array-union": "^2.1.0", @@ -494,46 +475,21 @@ "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=" }, "http-proxy-agent": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-2.1.0.tgz", - "integrity": "sha512-qwHbBLV7WviBl0rQsOzH6o5lwyOIvwp/BdFnvVxXORldu5TmjFfjzBcWUWS5kWAZhmv+JtiDhSuQCp4sBfbIgg==", + "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==", "requires": { - "agent-base": "4", - "debug": "3.1.0" - }, - "dependencies": { - "debug": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", - "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", - "requires": { - "ms": "2.0.0" - } - }, - "ms": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" - } + "agent-base": "5", + "debug": "4" } }, "https-proxy-agent": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-3.0.1.tgz", - "integrity": "sha512-+ML2Rbh6DAuee7d07tYGEKOEi2voWPUGan+ExdPbPW6Z3svq+JCqr0v8WmKPOkz1vOVykPCBSuobe7G8GJUtVg==", + "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==", "requires": { - "agent-base": "^4.3.0", - "debug": "^3.1.0" - }, - "dependencies": { - "debug": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", - "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", - "requires": { - "ms": "^2.1.1" - } - } + "agent-base": "5", + "debug": "4" } }, "human-signals": { @@ -612,9 +568,9 @@ "integrity": "sha512-S/2fF5wH8SJA/kmwr6HYhK/RI/OkhD84k8ntalo0iJjZikgq1XFvR5M8NPT1x5F7fBwCG3qHfnzeP/Vh/ZxCUA==" }, "issue-parser": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/issue-parser/-/issue-parser-5.0.0.tgz", - "integrity": "sha512-q/16W7EPHRL0FKVz9NU++TUsoygXGj6JOi88oulyAcQG+IEZ0T6teVdE+VLbe19OfL/tbV8Wi3Dfo0HedeHW0Q==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/issue-parser/-/issue-parser-6.0.0.tgz", + "integrity": "sha512-zKa/Dxq2lGsBIXQ7CUZWTHfvxPC2ej0KfO7fIPqLlHB9J2hJ7rGhZ5rilhuufylr4RXYPzJUeFjKxz305OsNlA==", "requires": { "lodash.capitalize": "^4.2.1", "lodash.escaperegexp": "^4.1.2", @@ -749,9 +705,9 @@ "integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==" }, "npm-run-path": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.0.tgz", - "integrity": "sha512-8eyAOAH+bYXFPSnNnKr3J+yoybe8O87Is5rtAQ8qRczJz1ajcsjg8l2oZqP+Ppx15Ii3S1vUTjQN2h4YO2tWWQ==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", "requires": { "path-key": "^3.0.0" } @@ -795,9 +751,9 @@ } }, "p-finally": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-2.0.1.tgz", - "integrity": "sha512-vpm09aKwq6H9phqRQzecoDpD8TmVyGw70qmWlyq5onxY7tqyTTFVvxMykxQSQKILBSFlbXpypIw2T1Ml7+DDtw==" + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" }, "p-map": { "version": "2.1.0", @@ -845,9 +801,9 @@ "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==" }, "picomatch": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.1.1.tgz", - "integrity": "sha512-OYMyqkKzK7blWO/+XZYP6w8hH0LDvkBvdvKukti+7kqYFCiEAk+gI3DWnryapc0Dau05ugGTy0foQ6mqn4AHYA==" + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.1.tgz", + "integrity": "sha512-ISBaA8xQNmwELC7eOjqFKMESB2VIqt4PPDD0nsS95b/9dZXvVKOlz9keMSnoGGKcOHXfTvDD6WMaRoSc9UuhRA==" }, "pump": { "version": "3.0.0", @@ -1008,11 +964,6 @@ "path-key": "^2.0.0" } }, - "p-finally": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", - "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" - }, "path-key": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", From 6d5ed3404408a32daa90490daa9be24f53512998 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Fri, 17 Jan 2020 15:57:07 -0500 Subject: [PATCH 197/455] fix(nlu): Add model property back in CategoriesOptions --- ibm_watson/natural_language_understanding_v1.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 60948e696..abe046a73 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -716,9 +716,15 @@ 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. """ - def __init__(self, *, explanation: bool = None, limit: int = None) -> None: + def __init__(self, *, explanation: bool = None, limit: int = None, model: str = None) -> None: """ Initialize a CategoriesOptions object. @@ -726,6 +732,12 @@ def __init__(self, *, explanation: bool = None, limit: int = None) -> None: 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. """ self.explanation = explanation self.limit = limit From 5085f0af81068e70e7e62275e61c586f8dbd4adf Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 17 Jan 2020 22:00:55 +0000 Subject: [PATCH 198/455] =?UTF-8?q?Bump=20version:=204.2.0=20=E2=86=92=204?= =?UTF-8?q?.2.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 6ac62c5dc..b6567fb01 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.2.0 +current_version = 4.2.1 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index ea5d65fc7..0d6a4f2bf 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.2.0' +__version__ = '4.2.1' diff --git a/setup.py b/setup.py index 91f4987c3..0ea62d9c5 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.2.0' +__version__ = '4.2.1' if sys.argv[-1] == 'publish': From e0e5f833e4935f9b52c17c4fae653c08b2bc323f Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 17 Jan 2020 22:00:55 +0000 Subject: [PATCH 199/455] chore(release): 4.2.1 release notes ## [4.2.1](https://github.com/watson-developer-cloud/python-sdk/compare/v4.2.0...v4.2.1) (2020-01-17) ### Bug Fixes * **nlu:** Add model property back in CategoriesOptions ([6d5ed34](https://github.com/watson-developer-cloud/python-sdk/commit/6d5ed3404408a32daa90490daa9be24f53512998)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 6 +++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 292541a5f..05e771fee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [4.2.1](https://github.com/watson-developer-cloud/python-sdk/compare/v4.2.0...v4.2.1) (2020-01-17) + + +### Bug Fixes + +* **nlu:** Add model property back in CategoriesOptions ([6d5ed34](https://github.com/watson-developer-cloud/python-sdk/commit/6d5ed3404408a32daa90490daa9be24f53512998)) + # [4.2.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.1.0...v4.2.0) (2020-01-16) diff --git a/package-lock.json b/package-lock.json index 6dfeb67ad..845b68c01 100644 --- a/package-lock.json +++ b/package-lock.json @@ -193,9 +193,9 @@ "integrity": "sha512-tHq6qdbT9U1IRSGf14CL0pUlULksvY9OZ+5eEgl1N7t+OA3tGvNpxJCzuKQlsNgCVwbAs670L1vcVQi8j9HjnA==" }, "@types/node": { - "version": "13.1.7", - "resolved": "https://registry.npmjs.org/@types/node/-/node-13.1.7.tgz", - "integrity": "sha512-HU0q9GXazqiKwviVxg9SI/+t/nAsGkvLDkIdxz+ObejG2nX6Si00TeLqHMoS+a/1tjH7a8YpKVQwtgHuMQsldg==" + "version": "13.1.8", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.1.8.tgz", + "integrity": "sha512-6XzyyNM9EKQW4HKuzbo/CkOIjn/evtCmsU+MUM1xDfJ+3/rNjBttM1NgN7AOQvN6tP1Sl1D1PIKMreTArnxM9A==" }, "@types/retry": { "version": "0.12.0", From f46567a645792ff698a1f9083e1fccc4a5aee044 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Mon, 27 Jan 2020 21:56:04 -0500 Subject: [PATCH 200/455] doc(transaction-id): Add doc for getting transaction id --- README.md | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/README.md b/README.md index 20c1ecbc3..95589227f 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 response from the SDK will contain a transaction ID. 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. From 1e73b02e50afe3fdae3fe3eca31953c223ed2b40 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 29 Jan 2020 13:08:20 -0500 Subject: [PATCH 201/455] refactor(doc): Udpate doc for transaction id --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 95589227f..16b4120fc 100755 --- a/README.md +++ b/README.md @@ -364,7 +364,7 @@ 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 response from the SDK will contain a transaction ID. This transaction ID is useful for troubleshooting and accessing relevant logs from your service instance. +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 From fef0f780dbee037307f28e49b72a6d528cfd4bbf Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 29 Jan 2020 13:09:07 -0500 Subject: [PATCH 202/455] test(env): Update key for personality insights --- .env.enc | Bin 1792 -> 1792 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/.env.enc b/.env.enc index 2ce119a8345c896d40fa79e8c11cbb3240481f78..96f424b136900ec5af4a793d668c76c11c54ff44 100644 GIT binary patch literal 1792 zcmV+b2mknu@=L-{JC#DF2`=zCZey8SH~%42jAJ*`LDY=9?w$a&XO3I*x8ula(A;6K zUgQQzHIOg-TfwWBSD&MugB(%v-&4tIA7rp6o66Xg=$I)yg<(0dcVpp_Bzv7C$_xU= zUHrA*i~34esP#9Mv7^y%%49+TLHo^?a>o71KMGwoe{`COJ(dkMGf)hgQOp2y-tFc( zus_+1ez)_%NGdp&I^JT16s1!*9#V%HQg&th&iub@y_ z)rOh~iFanX>p$>@82~c4uflq67(iT}o>WViYBb{hc$=$W5V%b_*kzYW-S{t79`=4C z@DX8t9~3-;;Ryx8R&>OFR$q<`Ro6y>19TvGRH&ovqGxPhpZ$i1XVn4M4Lyb4Nf^P3 zEddC7SlrluxxyaSNW;rXa_W_IqGE5Af|L_nFm?cS18*e_n*#3x$)l3~8ajs*-v}FZ z%gZFq^F>lruyFov&=w+Z*`$)a3t(w{nuK?BGU!{=GmFDc{sQ=26|*2QXS9WiyYdN{ zTu0JM%iw)G^BWlIivrn+|2W3^;QK_9xjE^#0lVHOg+zE!k3Ur()=sb`c>$o?#YD)eM4PA<)j<~S~;KR;R-LB+{l$6 zc(Own-Pi^ibB*x!53XUE-M)4Ej!OE~`?cu9gx~ujF4W00d>!7~XPGL!a6aQd%Qdno zJGD5@aR%C6S#2bvHNiZ!AU(!0yj)52E@=DVa@LvXtFgI&18W(q*yE&gDIw?aJeq@) zrHVeXz28X&_PtT~=ky=BiEy+dRt-t&%v}tlTI;0LDB}n1qeHvAEq!Z*m81PT4BSZq z4i$8o`DNSC18XN77B8{j*+Zi_t|N}^>DUue9et8EJK7?GT?}4B2p*VsQQS1jI>96u z#u?bh(?oF<#$y_9XplvrG(*=EK}6A+6yiBb3dn`FILTu!uQkTrgpzD5 zABUGsv;(OKUyxf)BPzOG+EQoR=-m>K=wvFKNp+dj3V?u!p&f$T+;GM-6wtYm_SOR1yN8i7Q7^Xm2$Fj7e>r83F#Oz zu5_^m&SCZj1AWSW08rJNtNzeU75dTR+}C;f;hxhdwY`WR7Qbnn3Ztk$>4!SiS_K&iSD^o`6a^u_ci*dsM-Y;nurt=>kSx2<{Gt*;ZJFT#1SgFMp6-dO`(BLsHYPLzKIax*J?#pF zzj^`+r+dVuT}zzc=fg^on-M17UXSfieTA<36!QRUljEP>ZZwkw_thE&UCMG@rGAT@ ztPL;Hzvi)Pw>4NnQD&bWWhQp$QcRJod#q20t}uJjsRuC~k^Bc!e%t0-OeXZR(fLd! zY=Wr3NhYjaM9OD$4=*TK$RV#3v7#nHo#t}M8CS9*5>L0{R{z_WfwkEFb5Y8A&(oSN zUb@&vHKA()RlL#{uT^%AQ5&ZvaV~rHI0xdc_*3+H;khW*ZywAmgIK6F-6D@`VNs8y zB^Vu)EjkNoC>H+&(7PsQ()x2p?gCbM=Ck9+ePjfZcY(U&==3@uOXKM~f;q?6U(f%- zmIx;HP9T+<<|~ChhcM^$B8ydW1hysan7diobhE7g3WSC712R1r4$X(i#zt&EPcZpg|uj>8j;@+1SId6~w z5DjQ}q^CnqqfjY{`@My}*4P=u!s3Vz6J8*v0IclKoXZ-deIw{P5u(DlyUF{+9+av$ z^}w;t5%sZyWNhjDwihA0hEjU#ZJJ)z`A6Y}y&)`JGy9|x+4w6dSw>J|`Iw*_xNkUM iE6BoOdB$z1eB+nLC0YyHq$Z5qfH%YXq=GC#$bk|(w0eF3 literal 1792 zcmV+b2mknBubJpO&gX#hB52B27T>;ohes7tHO9E1FskTFm@Pz31VtUp+Kl$uwplq0 zva)YFyTM{koP@8B;tO4(gEzq<0kEu zOZTN~*X*y5Y7t!74bjONP++|0lh`BCnrNSV-E3Lz(c7aMc0GNo$}`sv&7_HEt}O>{ zV$+avXO*d&{_GxV|2vK&4pKpbsoEE+ueuZ8+FpE}Wq>v|5KN7KSC4eje1q-R=d5E5 zrphd+hL?Rmx=jlP$h@r_hf|_5q@dZXLSMuTu7a%;}v1C>kPclo9_5{jVcKO^BZbT zl|#?s42%1^O)+m;K2?yrJOx>(=Lj-PR%=1zYM~5S3u7;l|1~ScaKu4WNIFjVMI-Qc zjL2|O{d0auj0ATQWi;6}=_`$XhHQ)aHSbN~@gaZF-=*;ygI<8QjB@7jz89T?oDhyu z`Q^aaN2i-fph@=N2a5nYF6z@4G6SucV+C(!N8?<-VgD{NX@+5OXc%rv+bcPQB4%NW z##82S4U^u3IQ;G$EySQBVV<5LSFlF!48n^wBH@u!aVe+7+O*hH8+{?hKP-1K^*Kb> z8AZpuq2W;xM%~sa*Eq-tVWA;~MAJM$Peu{bu?(pLq}N-ecIq5Um3~W#RHAso6bXhF zd;sze_5hg>3cEZjU`RQ-Uzz#x52Z(gsEdMZ@eko)fsd99f8jZ`{Ae^7ugsec>!iUugupbnb z1_IgdxlBW_`HJIJD)FGAW7_eTU!s^hAO_daG8e#OyXY)?(N$D}j6qHN1AxV@430vA zI_s1^pyx4*(8h`7^Q`7xk#3(14NkoS3@t<;4F}9kC7l#@?Iv_XxjN>8xnngqF;MUd zDUFBTS+YnXqg5nlye@9^7E``~x#p4d1!gIcldYBUEQV=!uz$!N+wgvj1s*lF?JG<* z_Lrj!u*0VB${tE{_+sdk4@Q7nDISw-ci3^Cry>n+j3LntUYu$304`}+Yq0H~jbB|r zCXo9lN z%CWFlISUZp>$0WMPRi~GgVfvNiKOAfOK> z;66VOdCg}wRu0jLT4YZs{H}C{uNY1gYs#Y>0(q=q4Y5-_^8UJzkYbP__p38=B`H_g zrQFZV8t6W50eXon``(2uu||o{107qp+F(J5a`#4s3Pk_-+%?^RO_gFOR_xz5$QUmZ z)A--qIar_?2hh0jcEI&^b2WBHSYk}FXO&2gy}m#(?kDEk>Snc_ck0ZW)z9s3fRG?l zeERqr=HW8n0@(|ZBQy@K=w`G8Y*hxo;C&vxlJXQf&}rqEBv$}RMfIr|t*`NR%Zq4y zNTRnhLL@z%$I6J=@eADc=g>K4aOWU8fI}{x`epg?28_FztN#Xah$N_ELN%1oKHW2;n;uu3LdtXKES${DIBx6IIC%xYmnrrRuejP{*1fL@^Mg6)&)q=UnTugS{SLvUe*&XsX(2Q&U{`@j0wfDjGDdmS5 z$70)GE6NAIS$hG`aogy^lrI@-9XMS;F{=-FSk~qkR*Ry7jBkw+&9FWVL%qMXHj4D> zVI*Dl!j?q|t6OAo>?j%zB*e35(;Z+iM?&|Ime^_vLp?{>4=|?px*wZ`N@+c@aj{mY iZJh-Es-ot;5e-hJ!OnC$3bsem0n4 Date: Wed, 29 Jan 2020 13:18:24 -0500 Subject: [PATCH 203/455] test(env): Update key for personality insights --- .env.enc | Bin 1792 -> 1792 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/.env.enc b/.env.enc index 96f424b136900ec5af4a793d668c76c11c54ff44..1597a8b620c7089c137f7890cc4972c983b18c4d 100644 GIT binary patch literal 1792 zcmV+b2mkodc;6r=n4QWcZ0uQ9EPtVQ`bwGp)3n5cLtEAorX+285$$9M$Yxf6Le;d? zoBK;nh@$I!vr|zS1UA(x8SfaxDG#|>3sxJC-{tEU5(JuOIFD#e5tDt1599TWIAN!W z_0_TG#2qMZt7#FH6+j#O@lYG%6=Dn#4I24khU_`JM6_xl5?=PHV;L)b95_G}{kwUR zXnR^^<RlV9GxL?*oKbNWt5YP*cxHquTR0^0#^oLbgZkpPYI!=G8 z`KmU^ZLebKVO0V1ms2#;x`iA=`R`IE;f$jf;_OCDdsET7!0}5m9gdxzkg_`K>~h!X zwe`~m?HZsEVfZ8X7CG>pTlN>?8mL*0W(Pgv7?tf&1U})U*^uL)@>>Q9tu!^3EM(Yk zeUd8l@Ms=`%*G$!+LN5?AMFlM3*-5aZnM34|%#fVhqFXE^$ha@n$(1p) zFnQ!!KcAs-;!m+zY>=z1D&dEhp$gsZn470xu{X(|V+?~=zr9?Lv-tk#Kak+hUM6bq zsv<5$zA!V89r5v%jP)Z*Ap-tMy1M2jr>o<1qAX+Y;a>szy#8t-qg@Y;PMD})#I;|| zle#9I+1njxG-T_?WKtK^BDBfcGep9+@6FAc0iW43#{s+#y}jQAMH>oUb5p<9 znXS6R_-Q_-&?W}ah1k$r62*z#RR7J&2Qolz|BHS&&t3yOL*$D*@w$+tWch<(BtOs?oZmHLXO`wku+AiCpDYU~=Mgqlf4 z@4+Au=+D_h1?0!wU{{kJo{aZeV73N?CQx;3y<#A7678K(A8F@DP8oW;nxk7K_b=&e zKGF+lC9T|-&9WMo@+1gr~qTtBoCKd!Ia)yg@9uN9&5hJK2--Cl1vK32$b^qv`Ac21SSxM@ES>)o7%%j zk(5l$^w4N974v8jlxFXCj7)aCBCrSOBg@AwITlw&q~$tAonEjRx0PkiZU?nca@=#T zJAtg)0@4(KX_Nd8T93f0Q=;me=Kx_5v$^fHHkD5s*0=5+sBc+MG8Rv>O%!nfV3U9< zu|O|r&)-4>aOnx>HzMu~4B@VGQJ+bQgm~a9e0~p6t+px5*(a;$7B%G{nyBX* zVWgL4akHss@_*~iK~nK1w1UQSrb&@-g{|1bH3`8>|G5@DqG`K3l3^kopQbJ~tOvs% zGRDhih6*f;p5Mg7LjcsEZc6WnMD9R5R)x5QS9-E!fiz26_aTqWLSG%Yz(nG8PpBUa zj7tg?ga{azU|%;*=PEkatK+j69@CJ)-zP`ey^n=VXKEZM`y8!~yuGfHf)HhIGJZJL zywome6`gMFxC;^5`k8Qb6ES`$!Ix0C0sn~E`CfbXGm@-`4yjC)XQOOQ z-^@Y*Z9MC_pJm2k@UNh;Lf!-mgBt&@EmV1Z*+>^0-@@_j6@-^so`1U$K6++ww9uIr z0abb%feRN7heGctR5}nsqq0hWZ{n^@SOk+s!|aB`<)3Jy9ixDN<-n{x%`2-jm;{Gd zOLW*A6XjIM6@s$nDV$=Du~{offr9sAfWvF%Rf!d@-8S%!5^okU32ZuIze&!WxB6WH z4iNosgisGD20IIgo(e0l#|zMD5BaT!w(JV7f8ek3INb+KyO2-s8>&K}HEw9~Wb4~BcKV*(OTDUKG(HbzGjlz+ru iK8SUHVpTv#)bGfMZwd{00+&!oTG-45&1{WWm?3q=|7Y|7 literal 1792 zcmV+b2mknu@=L-{JC#DF2`=zCZey8SH~%42jAJ*`LDY=9?w$a&XO3I*x8ula(A;6K zUgQQzHIOg-TfwWBSD&MugB(%v-&4tIA7rp6o66Xg=$I)yg<(0dcVpp_Bzv7C$_xU= zUHrA*i~34esP#9Mv7^y%%49+TLHo^?a>o71KMGwoe{`COJ(dkMGf)hgQOp2y-tFc( zus_+1ez)_%NGdp&I^JT16s1!*9#V%HQg&th&iub@y_ z)rOh~iFanX>p$>@82~c4uflq67(iT}o>WViYBb{hc$=$W5V%b_*kzYW-S{t79`=4C z@DX8t9~3-;;Ryx8R&>OFR$q<`Ro6y>19TvGRH&ovqGxPhpZ$i1XVn4M4Lyb4Nf^P3 zEddC7SlrluxxyaSNW;rXa_W_IqGE5Af|L_nFm?cS18*e_n*#3x$)l3~8ajs*-v}FZ z%gZFq^F>lruyFov&=w+Z*`$)a3t(w{nuK?BGU!{=GmFDc{sQ=26|*2QXS9WiyYdN{ zTu0JM%iw)G^BWlIivrn+|2W3^;QK_9xjE^#0lVHOg+zE!k3Ur()=sb`c>$o?#YD)eM4PA<)j<~S~;KR;R-LB+{l$6 zc(Own-Pi^ibB*x!53XUE-M)4Ej!OE~`?cu9gx~ujF4W00d>!7~XPGL!a6aQd%Qdno zJGD5@aR%C6S#2bvHNiZ!AU(!0yj)52E@=DVa@LvXtFgI&18W(q*yE&gDIw?aJeq@) zrHVeXz28X&_PtT~=ky=BiEy+dRt-t&%v}tlTI;0LDB}n1qeHvAEq!Z*m81PT4BSZq z4i$8o`DNSC18XN77B8{j*+Zi_t|N}^>DUue9et8EJK7?GT?}4B2p*VsQQS1jI>96u z#u?bh(?oF<#$y_9XplvrG(*=EK}6A+6yiBb3dn`FILTu!uQkTrgpzD5 zABUGsv;(OKUyxf)BPzOG+EQoR=-m>K=wvFKNp+dj3V?u!p&f$T+;GM-6wtYm_SOR1yN8i7Q7^Xm2$Fj7e>r83F#Oz zu5_^m&SCZj1AWSW08rJNtNzeU75dTR+}C;f;hxhdwY`WR7Qbnn3Ztk$>4!SiS_K&iSD^o`6a^u_ci*dsM-Y;nurt=>kSx2<{Gt*;ZJFT#1SgFMp6-dO`(BLsHYPLzKIax*J?#pF zzj^`+r+dVuT}zzc=fg^on-M17UXSfieTA<36!QRUljEP>ZZwkw_thE&UCMG@rGAT@ ztPL;Hzvi)Pw>4NnQD&bWWhQp$QcRJod#q20t}uJjsRuC~k^Bc!e%t0-OeXZR(fLd! zY=Wr3NhYjaM9OD$4=*TK$RV#3v7#nHo#t}M8CS9*5>L0{R{z_WfwkEFb5Y8A&(oSN zUb@&vHKA()RlL#{uT^%AQ5&ZvaV~rHI0xdc_*3+H;khW*ZywAmgIK6F-6D@`VNs8y zB^Vu)EjkNoC>H+&(7PsQ()x2p?gCbM=Ck9+ePjfZcY(U&==3@uOXKM~f;q?6U(f%- zmIx;HP9T+<<|~ChhcM^$B8ydW1hysan7diobhE7g3WSC712R1r4$X(i#zt&EPcZpg|uj>8j;@+1SId6~w z5DjQ}q^CnqqfjY{`@My}*4P=u!s3Vz6J8*v0IclKoXZ-deIw{P5u(DlyUF{+9+av$ z^}w;t5%sZyWNhjDwihA0hEjU#ZJJ)z`A6Y}y&)`JGy9|x+4w6dSw>J|`Iw*_xNkUM iE6BoOdB$z1eB+nLC0YyHq$Z5qfH%YXq=GC#$bk|(w0eF3 From bdfd2c36d6a36ccaf9e17f5dfaa4f5de98bd7103 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 29 Jan 2020 14:14:00 -0500 Subject: [PATCH 204/455] test(env): Update key for personality insights --- .env.enc | Bin 1792 -> 1840 bytes examples/personality_insights_v3.py | 7 ++++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/.env.enc b/.env.enc index 1597a8b620c7089c137f7890cc4972c983b18c4d..09dbc43b497dcb7ea1c298d7081c00ff1cf3cd02 100644 GIT binary patch literal 1840 zcmV-02haFDg-1|QqVl1wRt1lD7eTqV`%9X)C)n%vZFvRPaXw}<;g7X#G665i5bLn$iY1}`Y?60TGPfyCP~9jK{d#f*3ejox zbuK72t8X$=FN!-o8mxI?b);o@;ZL0Od(lotaC>nh*ppwjnb!~ZK2TZPQaW0M5 ztj&lx<~1xIMjDaAWQYUUvltW8=aa7`vkxQ&?kFNhI#^AAg>T43TIqnS`Cz?dC2&`^ z?Eb}P-tmf#>7mnF(|85grCtsYr9=lgfDk+v?o(Zsx#FO(TYOc=CzeE!wszRi)*3`u z-s`KBPDr+CHiO)ieUl;C$lkXPf-T^fY!r$=eJ$##=J6zyEw#D0Ib+G_b)6H~@r+qMLtP(Eg>VlQ}Bn+u&3C(cW8+5hCCv+Bw5Eiw(Vgb=1X%!fzR6V`7%nQvg6W6%`LCV&bNd0i08f{ZN4`@ z{h!X=OxbEj;wsNlX4Ppco*NF22_)+&&aUB7-T8gL(KeLy+33?gA~SjL92nT1VVc3I z*wF)6bx;G(dJT{uF6+!1&8S7%pO<9>7~mp0Mu|dx{R!TC8Aek33-xsgLU+XMqDx?i@*azqWHpr0Gl+zyJe}hYoxFH z9!G7whsxieXXVK$@)PF=QYbUgVThl*EpMfto(af(Hw@jvaH zz*7OY4pAOc1iLN?wW*vGf8IMo3wML~LinTT6dk&YZSm93f|8Fl(kev|cSyeUWl~Zc z8;^wi*yvLECC$4Ef+Dz<#7kB%c9T*=R`N|E!KYG-5c}qF>7ckGp^l|j9;KcPUJC9c zD4M-3m!kaTErO>?pf5U7OMDw@#&D!K4WJG4CHE$p4NM}Ikpv!c-4Xd8Vsl?*#|Y#5 zqTl{?!|LCzY(nE-nd}QE&28$Wv(hFa&_yy0UDSnw4H}4=tqpokoPrE-HaN1<}rS)WOg|TNqXR;$L=ogcQ&S}#Zia3 zuZ^NuWoMy0UmwF8^+@u4KN#`&RJmzn)TlT~)%^php-?NKBpk3qL6>Xu>LLi+zl}&z zSS$Xa_1KV(^f+1spme9Osos9ldWPKl#dFabsz9PCC*04s_11{p(#v=%OpGAf;4U z`cB8%yT6Ju{KQ0Um)>qr8$T(h6;Ak9fSwd&wmoho#dB?L0Z&mM989bsY; z$f>E&;qFt0RUQ;T3`dWDbi0ES5zt;r3u|hm!!yOsKsthyXL&xkdlf^WzqvEF`#yW? zoKDqx8PE^0YlJsQDUKmI=0R?ai6<)l3YSFHlSOS%{Agi{&o^Rn)$^Jg>w3UvKIXhF zDeax!mwF}g2{z4H{g`+-4{~Km-4*2{Urq}GCL9V#Y98i6hrBvd3NW3_Y|5U#iLj?} zQ$=n1^AYU|5kXM3Dud(X`S@~wM~OC^Gfh|oj-Efxh&*RJoE3Qb4IJ)8%u+7>Z_L_^ zg`Fb^z#U@+Lxq=>yktkRHEG!pZz7v<$jPXmrQ6OdIo{n}G@(EHW%TAwqD|8$QYBLu zr?)2$mf*PuI<))z1L4pC?qdgXQjy3sxJC-{tEU5(JuOIFD#e5tDt1599TWIAN!W z_0_TG#2qMZt7#FH6+j#O@lYG%6=Dn#4I24khU_`JM6_xl5?=PHV;L)b95_G}{kwUR zXnR^^<RlV9GxL?*oKbNWt5YP*cxHquTR0^0#^oLbgZkpPYI!=G8 z`KmU^ZLebKVO0V1ms2#;x`iA=`R`IE;f$jf;_OCDdsET7!0}5m9gdxzkg_`K>~h!X zwe`~m?HZsEVfZ8X7CG>pTlN>?8mL*0W(Pgv7?tf&1U})U*^uL)@>>Q9tu!^3EM(Yk zeUd8l@Ms=`%*G$!+LN5?AMFlM3*-5aZnM34|%#fVhqFXE^$ha@n$(1p) zFnQ!!KcAs-;!m+zY>=z1D&dEhp$gsZn470xu{X(|V+?~=zr9?Lv-tk#Kak+hUM6bq zsv<5$zA!V89r5v%jP)Z*Ap-tMy1M2jr>o<1qAX+Y;a>szy#8t-qg@Y;PMD})#I;|| zle#9I+1njxG-T_?WKtK^BDBfcGep9+@6FAc0iW43#{s+#y}jQAMH>oUb5p<9 znXS6R_-Q_-&?W}ah1k$r62*z#RR7J&2Qolz|BHS&&t3yOL*$D*@w$+tWch<(BtOs?oZmHLXO`wku+AiCpDYU~=Mgqlf4 z@4+Au=+D_h1?0!wU{{kJo{aZeV73N?CQx;3y<#A7678K(A8F@DP8oW;nxk7K_b=&e zKGF+lC9T|-&9WMo@+1gr~qTtBoCKd!Ia)yg@9uN9&5hJK2--Cl1vK32$b^qv`Ac21SSxM@ES>)o7%%j zk(5l$^w4N974v8jlxFXCj7)aCBCrSOBg@AwITlw&q~$tAonEjRx0PkiZU?nca@=#T zJAtg)0@4(KX_Nd8T93f0Q=;me=Kx_5v$^fHHkD5s*0=5+sBc+MG8Rv>O%!nfV3U9< zu|O|r&)-4>aOnx>HzMu~4B@VGQJ+bQgm~a9e0~p6t+px5*(a;$7B%G{nyBX* zVWgL4akHss@_*~iK~nK1w1UQSrb&@-g{|1bH3`8>|G5@DqG`K3l3^kopQbJ~tOvs% zGRDhih6*f;p5Mg7LjcsEZc6WnMD9R5R)x5QS9-E!fiz26_aTqWLSG%Yz(nG8PpBUa zj7tg?ga{azU|%;*=PEkatK+j69@CJ)-zP`ey^n=VXKEZM`y8!~yuGfHf)HhIGJZJL zywome6`gMFxC;^5`k8Qb6ES`$!Ix0C0sn~E`CfbXGm@-`4yjC)XQOOQ z-^@Y*Z9MC_pJm2k@UNh;Lf!-mgBt&@EmV1Z*+>^0-@@_j6@-^so`1U$K6++ww9uIr z0abb%feRN7heGctR5}nsqq0hWZ{n^@SOk+s!|aB`<)3Jy9ixDN<-n{x%`2-jm;{Gd zOLW*A6XjIM6@s$nDV$=Du~{offr9sAfWvF%Rf!d@-8S%!5^okU32ZuIze&!WxB6WH z4iNosgisGD20IIgo(e0l#|zMD5BaT!w(JV7f8ek3INb+KyO2-s8>&K}HEw9~Wb4~BcKV*(OTDUKG(HbzGjlz+ru iK8SUHVpTv#)bGfMZwd{00+&!oTG-45&1{WWm?3q=|7Y|7 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 # From e44cb16771620f0cbc6f6c03e215c088c5a1beb6 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 14:12:18 -0500 Subject: [PATCH 205/455] feat(assistantv1): New param `include_audit` in `create_workspace` and `update_workspace` --- ibm_watson/assistant_v1.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 42a0b126c..8f0b21d1e 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -243,6 +243,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 +274,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 +302,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 +401,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 +434,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 +472,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, From d52370646cd9d5aa88bfd67da294dfd5f8ba9800 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 14:14:29 -0500 Subject: [PATCH 206/455] feat(assistantv1): New param `include_audit` in `create_intent` --- ibm_watson/assistant_v1.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 8f0b21d1e..6bc153559 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -615,6 +615,7 @@ def create_intent(self, *, description: str = None, examples: List['Example'] = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Create intent. @@ -635,6 +636,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 @@ -655,7 +658,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, From 3b015f9b660241c2ab6f6b7f371843edf2c12c59 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 14:17:06 -0500 Subject: [PATCH 207/455] feat(assistantv1): New params `append` and `include_audit` in `update_intent` --- ibm_watson/assistant_v1.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 6bc153559..6ac745af2 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -741,6 +741,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. @@ -763,6 +765,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 @@ -783,7 +796,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, From b1f99ec1e4fad3655ff526cab7de5f18e29607a0 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 14:29:12 -0500 Subject: [PATCH 208/455] feat(assistantv1): New param `include_audit` in `create_example`, `update_example`, `create_counterexample`, `update_counterexample`, `create_entity` --- ibm_watson/assistant_v1.py | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 6ac745af2..9cb3c08d8 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -934,6 +934,7 @@ def create_example(self, text: str, *, mentions: List['Mention'] = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Create user input example. @@ -952,6 +953,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 @@ -974,7 +977,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} @@ -1047,6 +1050,7 @@ def update_example(self, *, new_text: str = None, new_mentions: List['Mention'] = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Update user input example. @@ -1066,6 +1070,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 @@ -1088,7 +1094,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} @@ -1211,7 +1217,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. @@ -1228,6 +1238,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 @@ -1246,7 +1258,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} @@ -1315,6 +1327,7 @@ def update_counterexample(self, text: str, *, new_text: str = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Update counterexample. @@ -1333,6 +1346,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 @@ -1351,7 +1366,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} @@ -1487,6 +1502,7 @@ def create_entity(self, metadata: dict = None, fuzzy_match: bool = None, values: List['CreateValue'] = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Create entity. @@ -1512,6 +1528,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 @@ -1532,7 +1550,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, From e36783d015e7681b626a1cc8c99ee68a9cbf614f Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 14:33:41 -0500 Subject: [PATCH 209/455] feat(assistantv1): New params `include_audit` and `append` in `update_entity` --- ibm_watson/assistant_v1.py | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 9cb3c08d8..5ba91d4ef 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1637,6 +1637,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. @@ -1662,6 +1664,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 @@ -1682,7 +1695,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, From 4d32257464bd87886934c00f5a4e569896a4ac32 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 14:40:26 -0500 Subject: [PATCH 210/455] feat(assistantv1): New param `include_audit` in `create_value` --- ibm_watson/assistant_v1.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 5ba91d4ef..69436de44 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1904,6 +1904,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. @@ -1932,7 +1933,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 @@ -1953,7 +1956,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, From 8bac230a824d996f7807f943650c737ca3ae553d Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 14:42:41 -0500 Subject: [PATCH 211/455] feat(assistantv1): New params `audit` and `include_audit` in `update_value` --- ibm_watson/assistant_v1.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 69436de44..1b5c178ba 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -2047,6 +2047,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. @@ -2078,7 +2080,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 @@ -2099,7 +2113,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, From fbe1081309aaa380d47b3c9016aaedc0a7bb5005 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 18:41:36 -0500 Subject: [PATCH 212/455] feat(assistantv1): New param `include_audi` in `create_synonym` and `update_synonym` and `update_dialog_node ` --- ibm_watson/assistant_v1.py | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 1b5c178ba..19fd2b9c0 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -2253,8 +2253,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. @@ -2272,6 +2278,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 @@ -2294,7 +2302,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} @@ -2371,6 +2379,7 @@ def update_synonym(self, synonym: str, *, new_synonym: str = None, + include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ Update entity value synonym. @@ -2390,6 +2399,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 @@ -2412,7 +2423,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} @@ -2559,6 +2570,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. @@ -2611,6 +2623,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 @@ -2635,7 +2649,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, @@ -2740,6 +2754,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. @@ -2794,6 +2809,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 @@ -2818,7 +2835,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, From a44ace8638db57f17d319932863aa5c5af51dd93 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 18:46:16 -0500 Subject: [PATCH 213/455] feat(assistantv1): New params `interpretation` and `role` in `RuntimeEntity` model --- ibm_watson/assistant_v1.py | 544 ++++++++++++++++++++++++++++++++++++- 1 file changed, 543 insertions(+), 1 deletion(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 19fd2b9c0..4e1d65f07 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -7936,6 +7936,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 @@ -7943,13 +7954,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: @@ -7981,6 +7995,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 @@ -8003,6 +8022,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): @@ -8024,6 +8047,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. @@ -9585,6 +10065,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. From c62e27cf09c260993fc20f5beb2c8fe99e1a1ac9 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 18:47:09 -0500 Subject: [PATCH 214/455] chore(assistantv1): regenerate assistant v1 --- ibm_watson/assistant_v1.py | 74 ++++++++++++++++++++++++++------------ 1 file changed, 51 insertions(+), 23 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 4e1d65f07..5300246ba 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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. @@ -2598,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 @@ -2783,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 @@ -2937,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 @@ -2996,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 (`-`). @@ -3051,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**. @@ -3805,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. @@ -3839,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 @@ -3953,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 @@ -4027,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 @@ -4645,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. @@ -7914,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, @@ -7923,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. @@ -9058,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. @@ -9092,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 @@ -9764,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. @@ -9783,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 @@ -9796,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: @@ -9812,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')) @@ -9833,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 From 9b7e56e85d9fdec8b264c1a2865882c031046998 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 19:01:08 -0500 Subject: [PATCH 215/455] feat(assistantv2): New params `locale` and `reference_time` in `MessageContextGlobalSystem` --- ibm_watson/assistant_v2.py | 51 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 49 insertions(+), 2 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 11157bbac..356ed6697 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1059,13 +1059,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 +1100,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 +1142,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 +1162,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): From 5ef087f4b27b0771e098aaec8488e42d94ecd1ce Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 19:14:53 -0500 Subject: [PATCH 216/455] feat(assistantv2): `interpretation`, `alternatives` and `role` properties in `RuntimeEntity` --- ibm_watson/assistant_v2.py | 589 ++++++++++++++++++++++++++++++++++++- 1 file changed, 587 insertions(+), 2 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 356ed6697..d85494776 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1902,6 +1902,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, @@ -1911,7 +1927,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. @@ -1925,6 +1944,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 @@ -1932,13 +1969,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: @@ -1970,6 +2011,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 @@ -1992,6 +2043,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): @@ -2013,6 +2070,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. From ef288e34258e6d1d75e7ec6df70a0de10a23c5df Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 19:15:19 -0500 Subject: [PATCH 217/455] chore(assistantv2): regenerate assistantv2 --- ibm_watson/assistant_v2.py | 40 +++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index d85494776..2197febab 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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 @@ -1186,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(): """ From 65dd5fe004f761c5565c3019d46dd67e40489200 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 19:21:35 -0500 Subject: [PATCH 218/455] chore(cnc): regeberate compare and comply --- ibm_watson/compare_comply_v1.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 01339bdbd..2a9c547af 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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 From d105198b5e42f279f1e20dd7b1df23696f00e2c0 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 19:21:54 -0500 Subject: [PATCH 219/455] chore(discovery): regenerate discovery --- ibm_watson/discovery_v1.py | 5 +++-- ibm_watson/discovery_v2.py | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index c06230534..203cb8792 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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..ec0829e9d 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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 From 8b4ed8c36beecbae8b980b0df7bcf892092a1d67 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 19:22:18 -0500 Subject: [PATCH 220/455] chore(ltv3): regenerate ltv3 --- ibm_watson/language_translator_v3.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index d899c478e..80b3b82a1 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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 From 5e25765b01593e9d5b9a7535db93327feb92eea1 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 19:22:39 -0500 Subject: [PATCH 221/455] chore(nlc): regenerate natural language classifier --- ibm_watson/natural_language_classifier_v1.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 632f2a28a..61cf7c534 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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 From 3b694b9e20dbc383b1489806fb252ccae2ddd2f8 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 19:24:58 -0500 Subject: [PATCH 222/455] chore(PI): regenerate personality insighs --- ibm_watson/personality_insights_v3.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 37c29ba51..9686c8387 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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. From b44d1eb71cd31ae0698b0ea6c27ddba0b31476db Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 19:25:23 -0500 Subject: [PATCH 223/455] chore(stt): regenerate speech to text --- ibm_watson/speech_to_text_v1.py | 215 ++++++++++++++++---------------- 1 file changed, 108 insertions(+), 107 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 70b37757e..8bb117684 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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' From 87cfca29f16d89691406c0fe91ad75d16e1601d8 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 19:25:55 -0500 Subject: [PATCH 224/455] chore(tts): regenerate text to speech --- ibm_watson/text_to_speech_v1.py | 63 +++++++++++++++++---------------- 1 file changed, 32 insertions(+), 31 deletions(-) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 08edf24c8..abd14c285 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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" From 990d75a7d0ce7b57f85aeb27208a1ac2e113ee99 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Tue, 11 Feb 2020 19:26:11 -0500 Subject: [PATCH 225/455] chore(ta): regenerate tone analyzer --- ibm_watson/tone_analyzer_v3.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 0aed13498..e695cbe59 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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. From cc9eaced7ac1e693392e0ea2e6eb2ed27c63af9a Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 12 Feb 2020 14:59:58 -0500 Subject: [PATCH 226/455] feat(vr4): New objects operations --- ibm_watson/visual_recognition_v4.py | 402 +++++++++++++++++- .../integration/test_visual_recognition_v4.py | 26 +- 2 files changed, 424 insertions(+), 4 deletions(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index cdabfac4c..cc90fa42b 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index 036e3510e..29ce62c59 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -86,7 +86,7 @@ def test_03_analyze(self): 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', @@ -115,6 +115,27 @@ 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 @@ -124,5 +145,8 @@ def test_04_training(self): 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) From da15f4dd7a68078a21fa7acd81261d5014fe4f2f Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 12 Feb 2020 15:03:35 -0500 Subject: [PATCH 227/455] chore(nlu): regenerate NLU --- .../natural_language_understanding_v1.py | 46 ++++++++++++------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index abe046a73..5088eff12 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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): From c1219537bebc72c30a6303cd349c7b9a682e7cd5 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 12 Feb 2020 15:12:15 -0500 Subject: [PATCH 228/455] test(all): Update all unit tests --- test/unit/test_assistant_v1.py | 31 +- test/unit/test_assistant_v2.py | 6 +- test/unit/test_compare_comply_v1.py | 2 +- test/unit/test_discovery_v1.py | 2 +- test/unit/test_discovery_v2.py | 2 +- test/unit/test_language_translator_v3.py | 2 +- .../test_natural_language_classifier_v1.py | 2 +- .../test_natural_language_understanding_v1.py | 5 +- test/unit/test_personality_insights_v3.py | 2 +- test/unit/test_speech_to_text_v1.py | 2 +- test/unit/test_text_to_speech_v1.py | 3 +- test/unit/test_tone_analyzer_v3.py | 2 +- test/unit/test_visual_recognition_v3.py | 2 +- test/unit/test_visual_recognition_v4.py | 312 +++++++++++++++++- 14 files changed, 351 insertions(+), 24 deletions(-) diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 8dfa617fe..a5593d95b 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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..f138cdf97 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 7b54f1773..171458bd1 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # 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/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 07c5b3914..363c5d6e9 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2020. # # 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/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 12cdef354..0276527c2 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # 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/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index f0a4f3098..2a8a15d89 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # 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/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index 105fe8264..d02f9bbc8 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2020. # # 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/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_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index 22cab9e9f..9fae31cba 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # 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/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 1cb6cf5b3..c3a534087 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2020. # # 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/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 8cc3a8c83..149120ab6 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index d9db2185d..8ff7cb6c4 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # 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/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index fb2b7d779..9aecb805e 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2020. # # 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/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 0c06d3194..5c50841ed 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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": []}""" From 9024b356daf07cdcb729fc3c37c8af44411df62e Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 12 Feb 2020 15:12:57 -0500 Subject: [PATCH 229/455] test(all): run yapf on all integration tests --- test/integration/test_compare_comply_v1.py | 138 +++++++-------- test/integration/test_discovery_v1.py | 160 +++++++++++------- test/integration/test_examples.py | 9 +- .../test_language_translator_v3.py | 29 ++-- .../test_natural_language_classifier_v1.py | 27 ++- test/integration/test_text_to_speech_v1.py | 44 ++--- .../integration/test_visual_recognition_v3.py | 26 +-- .../integration/test_visual_recognition_v4.py | 70 ++++---- 8 files changed, 282 insertions(+), 221 deletions(-) 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 29ce62c59..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,7 +87,9 @@ 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)) @@ -90,13 +97,16 @@ 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)], @@ -116,7 +126,8 @@ def test_04_objects_and_training(self): assert training_data is not None # list objects metadata - object_metadata_list = self.visual_recognition.list_object_metadata(collection_id=collection_id).get_result() + 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 @@ -124,8 +135,7 @@ def test_04_objects_and_training(self): 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() + new_object='updated giraffe training data').get_result() assert updated_object_metadata is not None # get object metadata @@ -142,11 +152,13 @@ def test_04_objects_and_training(self): 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') + self.visual_recognition.delete_object( + collection_id, object='updated giraffe training data') # delete collection self.visual_recognition.delete_collection(collection_id) From 3003314942b091ac2ff8124cffc87d27567b2a34 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 12 Feb 2020 15:13:33 -0500 Subject: [PATCH 230/455] chore(examples): Update copyrights of example files --- examples/__init__.py | 2 +- examples/assistant_tone_analyzer_integration/__init__.py | 2 +- examples/assistant_tone_analyzer_integration/tone_detection.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) 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. From d6a4db51f1ed3ff1036e65c4e69ef63c79e5e3b3 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 12 Feb 2020 15:14:45 -0500 Subject: [PATCH 231/455] chore(vr3): regenerate vr3 --- ibm_watson/visual_recognition_v3.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 9428e5ab8..1101cf970 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -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. From 635e087121180ab2d7a0a04ed45477434d439218 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 12 Feb 2020 15:15:44 -0500 Subject: [PATCH 232/455] chore(copyrights): initial copyrights of unedited files --- ibm_watson/text_to_speech_adapter_v1.py | 2 +- ibm_watson/websocket/__init__.py | 2 +- ibm_watson/websocket/audio_source.py | 2 +- ibm_watson/websocket/recognize_abstract_callback.py | 2 +- ibm_watson/websocket/recognize_listener.py | 2 +- ibm_watson/websocket/synthesize_callback.py | 2 +- ibm_watson/websocket/synthesize_listener.py | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) 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/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. From d3d47030e45a431f45e82fa65d1435da0feab1ba Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 12 Feb 2020 15:19:52 -0500 Subject: [PATCH 233/455] chore(copyrights): correct copyrights by running linter --- ibm_watson/__init__.py | 2 +- ibm_watson/assistant_v1.py | 2 +- ibm_watson/assistant_v2.py | 2 +- ibm_watson/compare_comply_v1.py | 2 +- ibm_watson/discovery_v1.py | 2 +- ibm_watson/discovery_v2.py | 2 +- ibm_watson/language_translator_v3.py | 2 +- ibm_watson/natural_language_classifier_v1.py | 2 +- ibm_watson/natural_language_understanding_v1.py | 2 +- ibm_watson/personality_insights_v3.py | 2 +- ibm_watson/speech_to_text_v1.py | 2 +- ibm_watson/text_to_speech_v1.py | 2 +- ibm_watson/tone_analyzer_v3.py | 2 +- ibm_watson/visual_recognition_v3.py | 2 +- ibm_watson/visual_recognition_v4.py | 2 +- test/unit/test_assistant_v1.py | 2 +- test/unit/test_assistant_v2.py | 2 +- test/unit/test_compare_comply_v1.py | 2 +- test/unit/test_discovery_v1.py | 2 +- test/unit/test_discovery_v2.py | 2 +- test/unit/test_language_translator_v3.py | 2 +- test/unit/test_natural_language_classifier_v1.py | 2 +- test/unit/test_personality_insights_v3.py | 2 +- test/unit/test_speech_to_text_v1.py | 2 +- test/unit/test_text_to_speech_v1.py | 2 +- test/unit/test_tone_analyzer_v3.py | 2 +- test/unit/test_visual_recognition_v3.py | 2 +- test/unit/test_visual_recognition_v4.py | 2 +- 28 files changed, 28 insertions(+), 28 deletions(-) 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 5300246ba..2020c9bfe 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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_v2.py b/ibm_watson/assistant_v2.py index 2197febab..4d95d4fa0 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 2a9c547af..f701adc77 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/discovery_v1.py b/ibm_watson/discovery_v1.py index 203cb8792..15717d031 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/discovery_v2.py b/ibm_watson/discovery_v2.py index ec0829e9d..4578d4d8e 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 80b3b82a1..047af98cb 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 61cf7c534..282fecef8 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 5088eff12..961999177 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 9686c8387..f04105bc4 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 8bb117684..50c30446e 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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 abd14c285..616918c3e 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index e695cbe59..88ec65e8d 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 1101cf970..84f904a69 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index cc90fa42b..8c320eddd 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index a5593d95b..c3fbcabf0 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index f138cdf97..46887549b 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 171458bd1..7b54f1773 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 363c5d6e9..07c5b3914 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 0276527c2..12cdef354 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 2a8a15d89..f0a4f3098 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index d02f9bbc8..105fe8264 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index 9fae31cba..22cab9e9f 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index c3a534087..1cb6cf5b3 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 149120ab6..90225cdbb 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index 8ff7cb6c4..d9db2185d 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index 9aecb805e..fb2b7d779 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 5c50841ed..99dc2df07 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. From a056facca69bc07585142c81581b307e7f63208d Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 12 Feb 2020 15:26:57 -0500 Subject: [PATCH 234/455] doc(vr4): Add exaxmple for object operation --- examples/visual_recognition_v4.py | 7 +++++++ 1 file changed, 7 insertions(+) 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)) From 77128d3df269a23378dfa5414196939542218817 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 13 Feb 2020 19:49:51 +0000 Subject: [PATCH 235/455] =?UTF-8?q?Bump=20version:=204.2.1=20=E2=86=92=204?= =?UTF-8?q?.3.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) 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/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/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': From 8aa75243e9b3290744d337af3bd47301bb9f8f5c Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 13 Feb 2020 19:49:51 +0000 Subject: [PATCH 236/455] chore(release): 4.3.0 release notes # [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)) --- CHANGELOG.md | 18 ++++ package-lock.json | 225 +++++++++++++++++++--------------------------- 2 files changed, 109 insertions(+), 134 deletions(-) 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/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", From 02f47b6514ac2bb80de98316fd29f1faaa612189 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Tue, 31 Mar 2020 16:20:38 -0400 Subject: [PATCH 237/455] docs: update instructions on where to ask questions --- .github/ISSUE_TEMPLATE/bug_report.md | 2 +- .github/ISSUE_TEMPLATE/feature_request.md | 2 +- CONTRIBUTING.md | 3 +-- README.md | 4 ++++ 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index f99646058..a6d58b0b9 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -7,7 +7,7 @@ assignees: '' --- -Remember, an issue is not the place to ask questions. You can use [Stack Overflow](http://stackoverflow.com/questions/tagged/ibm-watson) for that, or you may want to start a discussion on the [dW Answers](https://developer.ibm.com/answers/questions/ask/?topics=watson). +Remember, an issue is not the place to ask questions. If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+python). Before you open an issue, please check if a similar issue already exists or has been closed before. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index c86f075d1..d326a686d 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -7,7 +7,7 @@ assignees: '' --- -Remember, an issue is not the place to ask questions. You can use [Stack Overflow](http://stackoverflow.com/questions/tagged/ibm-watson) for that, or you may want to start a discussion on the [dW Answers](https://developer.ibm.com/answers/questions/ask/?topics=watson). +Remember, an issue is not the place to ask questions. If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+python). Before you open an issue, please check if a similar issue already exists or has been closed before. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3ac3a86ae..f46847fe0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,8 +2,7 @@ ## Questions -If you are having difficulties using the APIs or have a question about the IBM Watson Services, -please ask a question on [dW Answers][dw] or [Stack Overflow][stackoverflow]. +If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+python). ## Issues diff --git a/README.md b/README.md index 16b4120fc..83c75e46e 100755 --- a/README.md +++ b/README.md @@ -225,6 +225,10 @@ discovery.set_service_url('') Tested on Python 3.5, 3.6, and 3.7. +## Questions + +If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+python). + ## Changes for v1.0 Version 1.0 focuses on the move to programmatically-generated code for many of the services. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. From 230878a256d375c92cef0647e2f5efa51b8a5cf0 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 16 Apr 2020 10:03:13 -0400 Subject: [PATCH 238/455] feat(LanguageTranslator): add support for auto correct --- ibm_watson/language_translator_v3.py | 89 +++++++++++++++++++++++----- 1 file changed, 75 insertions(+), 14 deletions(-) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 047af98cb..7e98d4908 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -93,14 +93,21 @@ def translate(self, """ Translate. - Translates the input text from the source language to the target language. + Translates the input text from the source language to the target language. A + target language or translation model ID is required. The service attempts to + detect the language of the source text if it is not specified. :param List[str] text: Input text in UTF-8 encoding. Multiple entries will result in multiple translations in the response. - :param str model_id: (optional) A globally unique string that identifies - the underlying model that is used for translation. - :param str source: (optional) Translation source language code. - :param str target: (optional) Translation target language code. + :param str model_id: (optional) The model to use for translation. For + example, `en-de` selects the IBM provided base model for English to German + translation. A model ID overrides the source and target parameters and is + required if you use a custom model. If no model ID is specified, you must + specify a target language. + :param str source: (optional) Language code that specifies the language of + the source document. + :param str target: (optional) Language code that specifies the target + language for translation. Required if model ID is not specified. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -469,16 +476,19 @@ def translate_document(self, :param TextIO file: The contents of the source file to translate. [Supported file - types](https://cloud.ibm.com/docs/services/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats) + types](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats) Maximum file size: **20 MB**. :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. - :param str model_id: (optional) The model to use for translation. - `model_id` or both `source` and `target` are required. + :param str model_id: (optional) The model to use for translation. For + example, `en-de` selects the IBM provided base model for English to German + translation. A model ID overrides the source and target parameters and is + required if you use a custom model. If no model ID is specified, you must + specify a target language. :param str source: (optional) Language code that specifies the language of the source document. :param str target: (optional) Language code that specifies the target - language for translation. + language for translation. Required if model ID is not specified. :param str document_id: (optional) To use a previously submitted document as the source for a new translation, enter the `document_id` of the document. @@ -879,6 +889,10 @@ class DocumentStatus(): customize the model. If the model is not a custom model, this will be absent or an empty string. :attr str source: Translation source language code. + :attr float detected_language_confidence: (optional) A score between 0 and 1 + indicating the confidence of source language detection. A higher value indicates + greater confidence. This is returned only when the service automatically detects + the source language. :attr str target: Translation target language code. :attr datetime created: The time when the document was submitted. :attr datetime completed: (optional) The time when the translation completed. @@ -898,6 +912,7 @@ def __init__(self, created: datetime, *, base_model_id: str = None, + detected_language_confidence: float = None, completed: datetime = None, word_count: int = None, character_count: int = None) -> None: @@ -918,6 +933,10 @@ def __init__(self, :param str base_model_id: (optional) Model ID of the base model that was used to customize the model. If the model is not a custom model, this will be absent or an empty string. + :param float detected_language_confidence: (optional) A score between 0 and + 1 indicating the confidence of source language detection. A higher value + indicates greater confidence. This is returned only when the service + automatically detects the source language. :param datetime completed: (optional) The time when the translation completed. :param int word_count: (optional) An estimate of the number of words in the @@ -931,6 +950,7 @@ def __init__(self, self.model_id = model_id self.base_model_id = base_model_id self.source = source + self.detected_language_confidence = detected_language_confidence self.target = target self.created = created self.completed = completed @@ -943,8 +963,8 @@ def from_dict(cls, _dict: Dict) -> 'DocumentStatus': args = {} valid_keys = [ 'document_id', 'filename', 'status', 'model_id', 'base_model_id', - 'source', 'target', 'created', 'completed', 'word_count', - 'character_count' + 'source', 'detected_language_confidence', 'target', 'created', + 'completed', 'word_count', 'character_count' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -983,6 +1003,9 @@ def from_dict(cls, _dict: Dict) -> 'DocumentStatus': raise ValueError( 'Required property \'source\' not present in DocumentStatus JSON' ) + if 'detected_language_confidence' in _dict: + args['detected_language_confidence'] = _dict.get( + 'detected_language_confidence') if 'target' in _dict: args['target'] = _dict.get('target') else: @@ -1023,6 +1046,10 @@ def to_dict(self) -> Dict: _dict['base_model_id'] = self.base_model_id if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source + if hasattr(self, 'detected_language_confidence' + ) and self.detected_language_confidence is not None: + _dict[ + 'detected_language_confidence'] = self.detected_language_confidence if hasattr(self, 'target') and self.target is not None: _dict['target'] = self.target if hasattr(self, 'created') and self.created is not None: @@ -1663,12 +1690,23 @@ class TranslationResult(): :attr int word_count: An estimate of the number of words in the input text. :attr int character_count: Number of characters in the input text. + :attr str detected_language: (optional) The language code of the source text if + the source language was automatically detected. + :attr float detected_language_confidence: (optional) A score between 0 and 1 + indicating the confidence of source language detection. A higher value indicates + greater confidence. This is returned only when the service automatically detects + the source language. :attr List[Translation] translations: List of translation output in UTF-8, corresponding to the input text entries. """ - def __init__(self, word_count: int, character_count: int, - translations: List['Translation']) -> None: + def __init__(self, + word_count: int, + character_count: int, + translations: List['Translation'], + *, + detected_language: str = None, + detected_language_confidence: float = None) -> None: """ Initialize a TranslationResult object. @@ -1677,16 +1715,27 @@ def __init__(self, word_count: int, character_count: int, :param int character_count: Number of characters in the input text. :param List[Translation] translations: List of translation output in UTF-8, corresponding to the input text entries. + :param str detected_language: (optional) The language code of the source + text if the source language was automatically detected. + :param float detected_language_confidence: (optional) A score between 0 and + 1 indicating the confidence of source language detection. A higher value + indicates greater confidence. This is returned only when the service + automatically detects the source language. """ self.word_count = word_count self.character_count = character_count + self.detected_language = detected_language + self.detected_language_confidence = detected_language_confidence self.translations = translations @classmethod def from_dict(cls, _dict: Dict) -> 'TranslationResult': """Initialize a TranslationResult object from a json dictionary.""" args = {} - valid_keys = ['word_count', 'character_count', 'translations'] + valid_keys = [ + 'word_count', 'character_count', 'detected_language', + 'detected_language_confidence', 'translations' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -1704,6 +1753,11 @@ def from_dict(cls, _dict: Dict) -> 'TranslationResult': raise ValueError( 'Required property \'character_count\' not present in TranslationResult JSON' ) + if 'detected_language' in _dict: + args['detected_language'] = _dict.get('detected_language') + if 'detected_language_confidence' in _dict: + args['detected_language_confidence'] = _dict.get( + 'detected_language_confidence') if 'translations' in _dict: args['translations'] = [ Translation._from_dict(x) for x in (_dict.get('translations')) @@ -1727,6 +1781,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'character_count') and self.character_count is not None: _dict['character_count'] = self.character_count + if hasattr(self, + 'detected_language') and self.detected_language is not None: + _dict['detected_language'] = self.detected_language + if hasattr(self, 'detected_language_confidence' + ) and self.detected_language_confidence is not None: + _dict[ + 'detected_language_confidence'] = self.detected_language_confidence if hasattr(self, 'translations') and self.translations is not None: _dict['translations'] = [x._to_dict() for x in self.translations] return _dict From 9aa13e94558c37ca815d61ff36d0988943c55bf7 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 16 Apr 2020 10:04:17 -0400 Subject: [PATCH 239/455] feat(SpeechToText): add support for speech_detector_sensitivity and background_audio_suppression in --- ibm_watson/speech_to_text_v1.py | 206 +++++++++++++++++------- ibm_watson/speech_to_text_v1_adapter.py | 82 +++++++--- 2 files changed, 209 insertions(+), 79 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 50c30446e..e23fa4e1a 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -29,9 +29,9 @@ customization to adapt a base model for the acoustic characteristics of your audio. For language model customization, the service also supports grammars. A grammar is a formal language specification that lets you restrict the phrases that the service can recognize. -Language model customization is generally available for production use with most supported -languages. Acoustic model customization is beta functionality that is available for all -supported languages. +Language model customization and acoustic model customization are generally available for +production use with all language models that are generally available. Grammars are beta +functionality for all language models that support language model customization. """ import json @@ -172,6 +172,8 @@ def recognize(self, audio_metrics: bool = None, end_of_phrase_silence_time: float = None, split_transcript_at_phrase_end: bool = None, + speech_detector_sensitivity: float = None, + background_audio_suppression: float = None, **kwargs) -> 'DetailedResponse': """ Recognize audio. @@ -302,8 +304,13 @@ def recognize(self, 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 + Omit the parameter or specify an empty array if you do not need to spot + keywords. + You can spot a maximum of 1000 keywords with a single request. A single + keyword can have a maximum length of 1024 characters, though the maximum + effective length for double-byte languages might be shorter. Keywords are + case-insensitive. + See [Keyword 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 @@ -351,11 +358,11 @@ def recognize(self, multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - **Note:** Applies to US English, Japanese, and Spanish (both broadband and - narrowband models) and UK English (narrowband model) transcription only. To - determine whether a language model supports speaker labels, you can also - use the **Get a model** method and check that the attribute - `speaker_labels` is set to `true`. + **Note:** Applies to US English, German, Japanese, Korean, and Spanish + (both broadband and narrowband models) and UK English (narrowband model) + transcription only. To determine whether a language model supports speaker + labels, you can also 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/speech-to-text?topic=speech-to-text-output#speaker_labels). :param str customization_id: (optional) **Deprecated.** Use the @@ -414,6 +421,30 @@ def recognize(self, transcripts based solely on the pause interval. See [Split transcript at phrase end](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#split_transcript). + :param float speech_detector_sensitivity: (optional) The sensitivity of + speech activity detection that the service is to perform. Use the parameter + to suppress word insertions from music, coughing, and other non-speech + events. The service biases the audio it passes for speech recognition by + evaluating the input audio against prior models of speech and non-speech + activity. + Specify a value between 0.0 and 1.0: + * 0.0 suppresses all audio (no speech is transcribed). + * 0.5 (the default) provides a reasonable compromise for the level of + sensitivity. + * 1.0 suppresses no audio (speech detection sensitivity is disabled). + The values increase on a monotonic curve. See [Speech Activity + Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). + :param float background_audio_suppression: (optional) The level to which + the service is to suppress background audio based on its volume to prevent + it from being transcribed as speech. Use the parameter to suppress side + conversations or background noise. + Specify a value in the range of 0.0 to 1.0: + * 0.0 (the default) provides no suppression (background audio suppression + is disabled). + * 0.5 provides a reasonable level of audio suppression for general usage. + * 1.0 suppresses all audio (no audio is transcribed). + The values increase on a monotonic curve. See [Speech Activity + Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -451,7 +482,9 @@ def recognize(self, 'redaction': redaction, 'audio_metrics': audio_metrics, 'end_of_phrase_silence_time': end_of_phrase_silence_time, - 'split_transcript_at_phrase_end': split_transcript_at_phrase_end + 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, + 'speech_detector_sensitivity': speech_detector_sensitivity, + 'background_audio_suppression': background_audio_suppression } data = audio @@ -616,6 +649,8 @@ def create_job(self, audio_metrics: bool = None, end_of_phrase_silence_time: float = None, split_transcript_at_phrase_end: bool = None, + speech_detector_sensitivity: float = None, + background_audio_suppression: float = None, **kwargs) -> 'DetailedResponse': """ Create a job. @@ -795,8 +830,13 @@ def create_job(self, 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 + Omit the parameter or specify an empty array if you do not need to spot + keywords. + You can spot a maximum of 1000 keywords with a single request. A single + keyword can have a maximum length of 1024 characters, though the maximum + effective length for double-byte languages might be shorter. Keywords are + case-insensitive. + See [Keyword 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 @@ -844,11 +884,11 @@ def create_job(self, multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - **Note:** Applies to US English, Japanese, and Spanish (both broadband and - narrowband models) and UK English (narrowband model) transcription only. To - determine whether a language model supports speaker labels, you can also - use the **Get a model** method and check that the attribute - `speaker_labels` is set to `true`. + **Note:** Applies to US English, German, Japanese, Korean, and Spanish + (both broadband and narrowband models) and UK English (narrowband model) + transcription only. To determine whether a language model supports speaker + labels, you can also 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/speech-to-text?topic=speech-to-text-output#speaker_labels). :param str customization_id: (optional) **Deprecated.** Use the @@ -929,6 +969,30 @@ def create_job(self, transcripts based solely on the pause interval. See [Split transcript at phrase end](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#split_transcript). + :param float speech_detector_sensitivity: (optional) The sensitivity of + speech activity detection that the service is to perform. Use the parameter + to suppress word insertions from music, coughing, and other non-speech + events. The service biases the audio it passes for speech recognition by + evaluating the input audio against prior models of speech and non-speech + activity. + Specify a value between 0.0 and 1.0: + * 0.0 suppresses all audio (no speech is transcribed). + * 0.5 (the default) provides a reasonable compromise for the level of + sensitivity. + * 1.0 suppresses no audio (speech detection sensitivity is disabled). + The values increase on a monotonic curve. See [Speech Activity + Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). + :param float background_audio_suppression: (optional) The level to which + the service is to suppress background audio based on its volume to prevent + it from being transcribed as speech. Use the parameter to suppress side + conversations or background noise. + Specify a value in the range of 0.0 to 1.0: + * 0.0 (the default) provides no suppression (background audio suppression + is disabled). + * 0.5 provides a reasonable level of audio suppression for general usage. + * 1.0 suppresses all audio (no audio is transcribed). + The values increase on a monotonic curve. See [Speech Activity + Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -972,7 +1036,9 @@ def create_job(self, 'processing_metrics_interval': processing_metrics_interval, 'audio_metrics': audio_metrics, 'end_of_phrase_silence_time': end_of_phrase_silence_time, - 'split_transcript_at_phrase_end': split_transcript_at_phrase_end + 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, + 'speech_detector_sensitivity': speech_detector_sensitivity, + 'background_audio_suppression': background_audio_suppression } data = audio @@ -1195,7 +1261,9 @@ def create_language_model(self, response = self.send(request) return response - def list_language_models(self, *, language: str = None, + def list_language_models(self, + *, + language: str = None, **kwargs) -> 'DetailedResponse': """ List custom language models. @@ -1563,17 +1631,19 @@ def add_corpus(self, better the service's recognition accuracy. The call returns an HTTP 201 response code if the corpus is valid. The service then asynchronously processes the contents of the corpus and automatically - extracts new words that it finds. This can take on the order of a minute or two to - complete depending on the total number of words and the number of new words in the - corpus, as well as the current load on the service. You cannot submit requests to - add additional resources to the custom model or to train the model until the + extracts new words that it finds. This operation can take on the order of minutes + to complete depending on the total number of words and the number of new words in + the corpus, as well as the current load on the service. You cannot submit requests + to add additional resources to the custom model or to train the model until the service's analysis of the corpus for the current request completes. Use the **List a corpus** method to check the status of the analysis. The service auto-populates the model's words resource with words from the corpus - that are not found in its base vocabulary. These are referred to as - out-of-vocabulary (OOV) words. You can use the **List custom words** method to - examine the words resource. You can use other words method to eliminate typos and - modify how words are pronounced as needed. + that are not found in its base vocabulary. These words are referred to as + out-of-vocabulary (OOV) words. After adding a corpus, you must validate the words + resource to ensure that each OOV word's definition is complete and valid. You can + use the **List custom words** method to examine the words resource. You can use + other words method to eliminate typos and modify how words are pronounced as + needed. To add a corpus file that has the same name as an existing corpus, set the `allow_overwrite` parameter to `true`; otherwise, the request fails. Overwriting an existing corpus causes the service to process the corpus text file and extract @@ -1587,10 +1657,12 @@ def add_corpus(self, that the service extracts from corpora and grammars, and words that you add directly. **See also:** + * [Add a corpus to the custom language + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addCorpus) * [Working with 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/speech-to-text?topic=speech-to-text-languageCreate#addCorpus). + * [Validating a words + resource](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel). :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 @@ -1848,7 +1920,10 @@ def add_words(self, customization_id: str, words: List['CustomWord'], the parameter for words that are difficult to pronounce, foreign words, acronyms, and so on. For example, you might specify that the word `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like pronunciations for a - word. + word. If you omit the `sounds_like` field, the service attempts to set the field + to its pronunciation of the word. It cannot generate a pronunciation for all + words, so you must review the word's definition to ensure that it is complete and + valid. * The `display_as` field provides a different way of spelling the word in a transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might @@ -1872,10 +1947,12 @@ def add_words(self, customization_id: str, words: List['CustomWord'], `error` field that describes the problem. You can use other words-related methods to correct errors, eliminate typos, and modify how words are pronounced as needed. **See also:** + * [Add words to the custom language + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords) * [Working with custom 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/speech-to-text?topic=speech-to-text-languageCreate#addWords). + * [Validating a words + resource](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel). :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 @@ -1944,7 +2021,10 @@ def add_word(self, the parameter for words that are difficult to pronounce, foreign words, acronyms, and so on. For example, you might specify that the word `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like pronunciations for a - word. + word. If you omit the `sounds_like` field, the service attempts to set the field + to its pronunciation of the word. It cannot generate a pronunciation for all + words, so you must review the word's definition to ensure that it is complete and + valid. * The `display_as` field provides a different way of spelling the word in a transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might @@ -1954,10 +2034,12 @@ def add_word(self, service encounters an error, it does not add the word to the words resource. Use the **List a custom word** method to review the word that you add. **See also:** + * [Add words to the custom language + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords) * [Working with custom 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/speech-to-text?topic=speech-to-text-languageCreate#addWords). + * [Validating a words + resource](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel). :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 @@ -2180,12 +2262,12 @@ def add_grammar(self, custom language model** method. The call returns an HTTP 201 response code if the grammar is valid. The service then asynchronously processes the contents of the grammar and automatically - extracts new words that it finds. This can take a few seconds to complete - depending on the size and complexity of the grammar, as well as the current load - on the service. You cannot submit requests to add additional resources to the - custom model or to train the model until the service's analysis of the grammar for - the current request completes. Use the **Get a grammar** method to check the - status of the analysis. + extracts new words that it finds. This operation can take a few seconds or minutes + to complete depending on the size and complexity of the grammar, as well as the + current load on the service. You cannot submit requests to add additional + resources to the custom model or to train the model until the service's analysis + of the grammar for the current request completes. Use the **Get a grammar** method + to check the status of the analysis. The service populates the model's words resource with any word that is recognized by the grammar that is not found in the model's base vocabulary. These are referred to as out-of-vocabulary (OOV) words. You can use the **List custom @@ -2442,7 +2524,9 @@ def create_acoustic_model(self, response = self.send(request) return response - def list_acoustic_models(self, *, language: str = None, + def list_acoustic_models(self, + *, + language: str = None, **kwargs) -> 'DetailedResponse': """ List custom acoustic models. @@ -2579,7 +2663,7 @@ def train_acoustic_model(self, to complete depending on the total amount of audio data on which the custom acoustic model is being trained and the current load on the service. Typically, training a custom acoustic model takes approximately two to four times the length - of its audio data. The range of time depends on the model being trained and the + of its audio data. The actual time depends on the model being trained and the nature of the audio, such as whether the audio is clean or noisy. The method returns an HTTP 200 response code to indicate that the training process has begun. You can monitor the status of the training by using the **Get a custom acoustic @@ -2595,8 +2679,9 @@ def train_acoustic_model(self, Train with a custom language model if you have verbatim transcriptions of the audio files that you have added to the custom model or you have either corpora (text files) or a list of words that are relevant to the contents of the audio - files. Both of the custom models must be based on the same version of the same - base model for training to succeed. + files. For training to succeed, both of the custom models must be based on the + same version of the same base model, and the custom language model must be fully + trained and available. **See also:** * [Train the custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#trainModel-acoustic) @@ -2608,6 +2693,9 @@ def train_acoustic_model(self, another training request or a request to add audio resources to the model. * The custom model contains less than 10 minutes or more than 200 hours of audio data. + * You passed a custom language model with the `custom_language_model_id` query + parameter that is not in the available state. A custom language model must be + fully trained and available to be used to train a custom acoustic model. * You passed an incompatible custom language model with the `custom_language_model_id` query parameter. Both custom models must be based on the same version of the same base model. @@ -2626,8 +2714,9 @@ def train_acoustic_model(self, verbatim transcriptions of the audio resources or that contains words that are relevant to the contents of the audio resources. The custom language model must be based on the same version of the same base model as the - custom acoustic model. The credentials specified with the request must own - both custom models. + custom acoustic model, and the custom language model must be fully trained + and available. The credentials specified with the request must own both + custom models. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2740,8 +2829,9 @@ def upgrade_acoustic_model(self, :param str custom_language_model_id: (optional) If the custom acoustic model was trained with a custom language model, the customization ID (GUID) of that custom language model. The custom language model must be upgraded - before the custom acoustic model can be upgraded. The credentials specified - with the request must own both custom models. + before the custom acoustic model can be upgraded. The custom language model + must be fully trained and available. The credentials specified with the + request must own both custom models. :param bool force: (optional) If `true`, forces the upgrade of a custom acoustic model for which no input data has been modified since it was last trained. Use this parameter only to force the upgrade of a custom acoustic @@ -2854,14 +2944,14 @@ def add_audio(self, archive-type, can be larger than 100 MB. To add an audio resource that has the same name as an existing audio resource, set the `allow_overwrite` parameter to `true`; otherwise, the request fails. - The method is asynchronous. It can take several seconds to complete depending on - the duration of the audio and, in the case of an archive file, the total number of - audio files being processed. The service returns a 201 response code if the audio - is valid. It then asynchronously analyzes the contents of the audio file or files - and automatically extracts information about the audio such as its length, - sampling rate, and encoding. You cannot submit requests to train or upgrade the - model until the service's analysis of all audio resources for current requests - completes. + The method is asynchronous. It can take several seconds or minutes to complete + depending on the duration of the audio and, in the case of an archive file, the + total number of audio files being processed. The service returns a 201 response + code if the audio is valid. It then asynchronously analyzes the contents of the + audio file or files and automatically extracts information about the audio such as + its length, sampling rate, and encoding. You cannot submit requests to train or + upgrade the model until the service's analysis of all audio resources for current + requests completes. To determine the status of the service's analysis of the audio, use the **Get an audio resource** method to poll the status of the audio. The method accepts the customization ID of the custom model and the name of the audio resource, and it diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 3585eefb6..22a565c79 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -53,6 +53,8 @@ def recognize_using_websocket(self, audio_metrics=None, end_of_phrase_silence_time=None, split_transcript_at_phrase_end=None, + speech_detector_sensitivity = None, + background_audio_suppression = None, **kwargs): """ Sends audio for speech recognition using web sockets. @@ -72,7 +74,7 @@ def recognize_using_websocket(self, `model` parameter. You must make the request with service credentials created 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). + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#custom). **Note:** Use this parameter instead of the deprecated `customization_id` parameter. :param str acoustic_customization_id: The customization ID (GUID) of a custom @@ -102,16 +104,23 @@ def recognize_using_websocket(self, 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. For more information, 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 int inactivity_timeout: The time in seconds after which, if only silence (no speech) is detected in submitted audio, the connection is closed with a 400 error. Useful for stopping audio submission from a live microphone when a user simply walks away. Use `-1` for infinity. - :param list[str] keywords: An array of keyword strings to spot in the audio. Each - keyword string can include one or more tokens. Keywords are spotted only in the - final hypothesis, not in interim results. 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. + :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. + Omit the parameter or specify an empty array if you do not need to spot + keywords. + You can spot a maximum of 1000 keywords with a single request. A single + keyword can have a maximum length of 1024 characters, though the maximum + effective length for double-byte languages might be shorter. Keywords are + case-insensitive. + See [Keyword + spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#keyword_spotting). :param float keywords_threshold: 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 and 1 @@ -138,15 +147,18 @@ def recognize_using_websocket(self, request. For US English, also converts certain keyword strings to punctuation symbols. By default, no smart formatting is performed. Applies to US English and Spanish transcription only. - :param bool speaker_labels: If `true`, the response includes labels that identify - which words were spoken by which participants in a multi-person exchange. By - default, no speaker labels are returned. Setting `speaker_labels` to `true` forces - the `timestamps` parameter to be `true`, regardless of whether you specify `false` - for the parameter. - To determine whether a language model supports speaker labels, use the **Get - models** method and check that the attribute `speaker_labels` is set to `true`. - You can also refer to [Speaker - labels](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#speaker_labels). + :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. + Setting `speaker_labels` to `true` forces the `timestamps` parameter to be + `true`, regardless of whether you specify `false` for the parameter. + **Note:** Applies to US English, German, Japanese, Korean, and Spanish + (both broadband and narrowband models) and UK English (narrowband model) + transcription only. To determine whether a language model supports speaker + labels, you can also 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/speech-to-text?topic=speech-to-text-output#speaker_labels). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. :param str customization_id: **Deprecated.** Use the `language_customization_id` @@ -159,7 +171,7 @@ def recognize_using_websocket(self, 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/output.html). + [Grammars](https://cloud.ibm.com/docs/speech-to-text/output.html). :param bool redaction: 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` character. It is intended @@ -172,7 +184,7 @@ def recognize_using_websocket(self, (forces the `max_alternatives` parameter to be `1`). **Note:** Applies to US English, Japanese, and Korean transcription only. See [Numeric - redaction](https://cloud.ibm.com/docs/services/speech-to-text/output.html#redaction). + redaction](https://cloud.ibm.com/docs/speech-to-text/output.html#redaction). :param bool processing_metrics: 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 `processing_metrics_interval` parameter. It also @@ -204,7 +216,7 @@ def recognize_using_websocket(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 @@ -214,7 +226,31 @@ def recognize_using_websocket(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 float speech_detector_sensitivity: (optional) The sensitivity of + speech activity detection that the service is to perform. Use the parameter + to suppress word insertions from music, coughing, and other non-speech + events. The service biases the audio it passes for speech recognition by + evaluating the input audio against prior models of speech and non-speech + activity. + Specify a value between 0.0 and 1.0: + * 0.0 suppresses all audio (no speech is transcribed). + * 0.5 (the default) provides a reasonable compromise for the level of + sensitivity. + * 1.0 suppresses no audio (speech detection sensitivity is disabled). + The values increase on a monotonic curve. See [Speech Activity + Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). + :param float background_audio_suppression: (optional) The level to which + the service is to suppress background audio based on its volume to prevent + it from being transcribed as speech. Use the parameter to suppress side + conversations or background noise. + Specify a value in the range of 0.0 to 1.0: + * 0.0 (the default) provides no suppression (background audio suppression + is disabled). + * 0.5 provides a reasonable level of audio suppression for general usage. + * 1.0 suppresses all audio (no audio is transcribed). + The values increase on a monotonic curve. See [Speech Activity + Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). :param dict headers: A `dict` containing the request headers :return: A `dict` containing the `SpeechRecognitionResults` response. :rtype: dict @@ -276,7 +312,11 @@ def recognize_using_websocket(self, 'redaction': redaction, 'processing_metrics': processing_metrics, 'processing_metrics_interval': processing_metrics_interval, - 'audio_metrics': audio_metrics + 'audio_metrics': audio_metrics, + 'end_of_phrase_silence_time': end_of_phrase_silence_time, + 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, + 'speech_detector_sensitivity': speech_detector_sensitivity, + 'background_audio_suppression': background_audio_suppression } options = {k: v for k, v in options.items() if v is not None} request['options'] = options From e9ea20cc68a09da4e948c0622e254c31b27b481b Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 16 Apr 2020 10:04:43 -0400 Subject: [PATCH 240/455] feat: regenerate services using current API def --- ibm_watson/assistant_v1.py | 135 +++++++++++++--- ibm_watson/assistant_v2.py | 153 +++++++++++++++--- ibm_watson/compare_comply_v1.py | 47 ++++-- ibm_watson/discovery_v1.py | 90 +++++++---- ibm_watson/discovery_v2.py | 98 +++++++---- ibm_watson/natural_language_classifier_v1.py | 4 +- .../natural_language_understanding_v1.py | 59 ++++--- ibm_watson/personality_insights_v3.py | 31 ++-- ibm_watson/text_to_speech_adapter_v1.py | 10 +- ibm_watson/text_to_speech_v1.py | 111 +++++++++---- ibm_watson/visual_recognition_v3.py | 9 +- ibm_watson/visual_recognition_v4.py | 42 ++--- 12 files changed, 582 insertions(+), 207 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 2020c9bfe..25a8df958 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -941,7 +941,7 @@ def create_example(self, Create user input example. Add a new user input example to an intent. - If you want to add multiple exaples with a single API call, consider using the + If you want to add multiple examples with a single API call, consider using the **[Update intent](#update-intent)** method instead. This operation is limited to 1000 requests per 30 minutes. For more information, see **Rate limiting**. @@ -2623,7 +2623,8 @@ def create_dialog_node(self, :param str user_label: (optional) A label that can be displayed externally 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. + should be excluded from disambiguation suggestions. Valid only when + **type**=`standard` or `frame`. :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 @@ -2809,7 +2810,8 @@ def update_dialog_node(self, :param str new_user_label: (optional) A label that can be displayed 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. + should be excluded from disambiguation suggestions. Valid only when + **type**=`standard` or `frame`. :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 @@ -3978,7 +3980,8 @@ class DialogNode(): :attr str user_label: (optional) A label that can be displayed externally to describe the purpose of the node to users. :attr bool disambiguation_opt_out: (optional) Whether the dialog node should be - excluded from disambiguation suggestions. + excluded from disambiguation suggestions. Valid only when **type**=`standard` or + `frame`. :attr bool disabled: (optional) For internal use only. :attr datetime created: (optional) The timestamp for creation of the object. :attr datetime updated: (optional) The timestamp for the most recent update to @@ -4052,7 +4055,8 @@ def __init__(self, :param str user_label: (optional) A label that can be displayed externally 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. + should be excluded from disambiguation suggestions. Valid only when + **type**=`standard` or `frame`. :param bool disabled: (optional) For internal use only. :param datetime created: (optional) The timestamp for creation of the object. @@ -4776,14 +4780,14 @@ class DialogNodeOutputGeneric(): natural-language query or a query that uses the Discovery query language syntax, depending on the value of the **query_type** property. For more information, see the [Discovery service - documentation](https://cloud.ibm.com/docs/services/discovery/query-operators.html#query-operators). + documentation](https://cloud.ibm.com/docs/discovery/query-operators.html#query-operators). Required when **response_type**=`search_skill`. :attr str query_type: (optional) The type of the search query. Required when **response_type**=`search_skill`. :attr str filter: (optional) An optional filter that narrows the set of documents to be searched. For more information, see the [Discovery service documentation]([Discovery service - documentation](https://cloud.ibm.com/docs/services/discovery/query-parameters.html#filter). + documentation](https://cloud.ibm.com/docs/discovery/query-parameters.html#filter). :attr str discovery_version: (optional) The version of the Discovery service API to use for the query. """ @@ -4845,14 +4849,14 @@ def __init__(self, either a natural-language query or a query that uses the Discovery query language syntax, depending on the value of the **query_type** property. For more information, see the [Discovery service - documentation](https://cloud.ibm.com/docs/services/discovery/query-operators.html#query-operators). + documentation](https://cloud.ibm.com/docs/discovery/query-operators.html#query-operators). Required when **response_type**=`search_skill`. :param str query_type: (optional) The type of the search query. Required when **response_type**=`search_skill`. :param str filter: (optional) An optional filter that narrows the set of documents to be searched. For more information, see the [Discovery service documentation]([Discovery service - documentation](https://cloud.ibm.com/docs/services/discovery/query-parameters.html#filter). + documentation](https://cloud.ibm.com/docs/discovery/query-parameters.html#filter). :param str discovery_version: (optional) The version of the Discovery service API to use for the query. """ @@ -5694,10 +5698,10 @@ class DialogSuggestionResponseGeneric(): :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :attr str topic: (optional) A label identifying the topic of the conversation, - derived from the **user_label** property of the relevant node. + derived from the **title** property of the relevant node. :attr str dialog_node: (optional) The ID of the dialog node that the **topic** property is taken from. The **topic** property is populated using the value of - the dialog node's **user_label** property. + the dialog node's **title** property. """ def __init__(self, @@ -5739,11 +5743,10 @@ def __init__(self, :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :param str topic: (optional) A label identifying the topic of the - conversation, derived from the **user_label** property of the relevant - node. + conversation, derived from the **title** property of the relevant node. :param str dialog_node: (optional) The ID of the dialog node that the **topic** property is taken from. The **topic** property is populated using - the value of the dialog node's **user_label** property. + the value of the dialog node's **title** property. """ self.response_type = response_type self.text = text @@ -7921,6 +7924,12 @@ class RuntimeEntity(): 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 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 + workspace. :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 @@ -7936,6 +7945,7 @@ def __init__(self, metadata: dict = None, groups: List['CaptureGroup'] = None, interpretation: 'RuntimeEntityInterpretation' = None, + alternatives: List['RuntimeEntityAlternative'] = None, role: 'RuntimeEntityRole' = None) -> None: """ Initialize a RuntimeEntity object. @@ -7956,6 +7966,13 @@ def __init__(self, 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 workspace. :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 @@ -7968,6 +7985,7 @@ def __init__(self, self.metadata = metadata self.groups = groups self.interpretation = interpretation + self.alternatives = alternatives self.role = role @classmethod @@ -7976,7 +7994,7 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': args = {} valid_keys = [ 'entity', 'location', 'value', 'confidence', 'metadata', 'groups', - 'interpretation', 'role' + 'interpretation', 'alternatives', 'role' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -8011,6 +8029,11 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': 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) @@ -8037,6 +8060,8 @@ def to_dict(self) -> Dict: _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 @@ -8060,6 +8085,77 @@ 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. @@ -8616,10 +8712,10 @@ class RuntimeResponseGeneric(): :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :attr str topic: (optional) A label identifying the topic of the conversation, - derived from the **user_label** property of the relevant node. + derived from the **title** property of the relevant node. :attr str dialog_node: (optional) The ID of the dialog node that the **topic** property is taken from. The **topic** property is populated using the value of - the dialog node's **user_label** property. + the dialog node's **title** property. :attr List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. **Note:** The **suggestions** property is part of the disambiguation feature, @@ -8664,11 +8760,10 @@ def __init__(self, :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. :param str topic: (optional) A label identifying the topic of the - conversation, derived from the **user_label** property of the relevant - node. + conversation, derived from the **title** property of the relevant node. :param str dialog_node: (optional) The ID of the dialog node that the **topic** property is taken from. The **topic** property is populated using - the value of the dialog node's **user_label** property. + the value of the dialog node's **title** property. :param List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 4d95d4fa0..9f0e1fbc2 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1219,17 +1219,21 @@ class MessageContextSkill(): :attr dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. - :attr dict system: (optional) For internal use only. + :attr MessageContextSkillSystem system: (optional) System context data used by + the skill. """ - def __init__(self, *, user_defined: dict = None, - system: dict = None) -> None: + def __init__(self, + *, + user_defined: dict = None, + system: 'MessageContextSkillSystem' = None) -> None: """ Initialize a MessageContextSkill object. :param dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. - :param dict system: (optional) For internal use only. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. """ self.user_defined = user_defined self.system = system @@ -1247,7 +1251,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') if 'system' in _dict: - args['system'] = _dict.get('system') + args['system'] = MessageContextSkillSystem._from_dict( + _dict.get('system')) return cls(**args) @classmethod @@ -1261,7 +1266,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system + _dict['system'] = self.system._to_dict() return _dict def _to_dict(self): @@ -1283,6 +1288,89 @@ def __ne__(self, other: 'MessageContextSkill') -> bool: return not self == other +class MessageContextSkillSystem(): + """ + System context data used by the skill. + + :attr str state: (optional) An encoded string representing the current + conversation state. By saving this value and then sending it in the context of a + subsequent message request, you can restore the conversation to the same state. + This can be useful if you need to return to an earlier point in the conversation + or resume a paused conversation after the session has expired. + """ + + def __init__(self, *, state: str = None, **kwargs) -> None: + """ + Initialize a MessageContextSkillSystem object. + + :param str state: (optional) An encoded string representing the current + conversation state. By saving this value and then sending it in the context + of a subsequent message request, you can restore the conversation to the + same state. This can be useful if you need to return to an earlier point in + the conversation or resume a paused conversation after the session has + expired. + :param **kwargs: (optional) Any additional properties. + """ + self.state = state + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': + """Initialize a MessageContextSkillSystem object from a json dictionary.""" + args = {} + xtra = _dict.copy() + if 'state' in _dict: + args['state'] = _dict.get('state') + del xtra['state'] + args.update(xtra) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkillSystem 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, 'state') and self.state is not None: + _dict['state'] = self.state + if hasattr(self, '_additionalProperties'): + for _key in self._additionalProperties: + _value = getattr(self, _key, None) + if _value is not None: + _dict[_key] = _value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: + properties = {'state'} + if not hasattr(self, '_additionalProperties'): + super(MessageContextSkillSystem, + self).__setattr__('_additionalProperties', set()) + if name not in properties: + self._additionalProperties.add(name) + super(MessageContextSkillSystem, self).__setattr__(name, value) + + def __str__(self) -> str: + """Return a `str` version of this MessageContextSkillSystem object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkillSystem') -> 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: 'MessageContextSkillSystem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageContextSkills(): """ Information specific to particular skills used by the Assistant. @@ -1488,16 +1576,23 @@ class MessageInputOptions(): Optional properties that control how the assistant responds. :attr bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information under the - `output.debug` key. + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. :attr bool restart: (optional) Whether to restart dialog processing at the root of the dialog, regardless of any previously visited nodes. **Note:** This does not affect `turn_count` or any other context variables. :attr bool alternate_intents: (optional) Whether to return more than one intent. Set to `true` to return all matching intents. :attr bool return_context: (optional) Whether to return session context with the - response. If you specify `true`, the response will include the `context` - property. + response. If you specify `true`, the response includes the `context` property. + If you also specify **debug**=`true`, the returned skill context includes the + `system.state` property. + :attr bool export: (optional) Whether to return session context, including full + conversation state. If you specify `true`, the response includes the `context` + property, and the skill context includes the `system.state` property. + **Note:** If **export**=`true`, the context is returned regardless of the value + of **return_context**. """ def __init__(self, @@ -1505,32 +1600,44 @@ def __init__(self, debug: bool = None, restart: bool = None, alternate_intents: bool = None, - return_context: bool = None) -> None: + return_context: bool = None, + export: bool = None) -> None: """ Initialize a MessageInputOptions object. :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information under the - `output.debug` key. + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. :param bool restart: (optional) Whether to restart dialog processing at the root of the dialog, regardless of any previously visited nodes. **Note:** This does not affect `turn_count` or any other context variables. :param bool alternate_intents: (optional) Whether to return more than one intent. Set to `true` to return all matching intents. :param bool return_context: (optional) Whether to return session context - with the response. If you specify `true`, the response will include the - `context` property. + with the response. If you specify `true`, the response includes the + `context` property. If you also specify **debug**=`true`, the returned + skill context includes the `system.state` property. + :param bool export: (optional) Whether to return session context, including + full conversation state. If you specify `true`, the response includes the + `context` property, and the skill context includes the `system.state` + property. + **Note:** If **export**=`true`, the context is returned regardless of the + value of **return_context**. """ self.debug = debug self.restart = restart self.alternate_intents = alternate_intents self.return_context = return_context + self.export = export @classmethod def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': """Initialize a MessageInputOptions object from a json dictionary.""" args = {} - valid_keys = ['debug', 'restart', 'alternate_intents', 'return_context'] + valid_keys = [ + 'debug', 'restart', 'alternate_intents', 'return_context', 'export' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -1544,6 +1651,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': args['alternate_intents'] = _dict.get('alternate_intents') if 'return_context' in _dict: args['return_context'] = _dict.get('return_context') + if 'export' in _dict: + args['export'] = _dict.get('export') return cls(**args) @classmethod @@ -1563,6 +1672,8 @@ def to_dict(self) -> Dict: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'return_context') and self.return_context is not None: _dict['return_context'] = self.return_context + if hasattr(self, 'export') and self.export is not None: + _dict['export'] = self.export return _dict def _to_dict(self): @@ -1836,8 +1947,8 @@ class MessageResponse(): :attr MessageOutput output: Assistant output to be rendered or processed by the client. - :attr MessageContext context: (optional) State information for the conversation. - The context is stored by the assistant on a per-session basis. You can use this + :attr MessageContext context: (optional) Context data for the conversation. The + context is stored by the assistant on a per-session basis. You can use this property to access context variables. **Note:** The context is included in message responses only if **return_context**=`true` in the message request. @@ -1852,7 +1963,7 @@ def __init__(self, :param MessageOutput output: Assistant output to be rendered or processed by the client. - :param MessageContext context: (optional) State information for the + :param MessageContext context: (optional) Context data for the conversation. The context is stored by the assistant on a per-session basis. You can use this property to access context variables. **Note:** The context is included in message responses only if @@ -3191,7 +3302,9 @@ class SearchResultMetadata(): indicates a greater match to the query parameters. """ - def __init__(self, *, confidence: float = None, + def __init__(self, + *, + confidence: float = None, score: float = None) -> None: """ Initialize a SearchResultMetadata object. diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index f701adc77..85ef86f45 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -487,7 +487,10 @@ def list_feedback(self, response = self.send(request) return response - def get_feedback(self, feedback_id: str, *, model: str = None, + def get_feedback(self, + feedback_id: str, + *, + model: str = None, **kwargs) -> 'DetailedResponse': """ Get a specified feedback entry. @@ -528,7 +531,10 @@ def get_feedback(self, feedback_id: str, *, model: str = None, response = self.send(request) return response - def delete_feedback(self, feedback_id: str, *, model: str = None, + def delete_feedback(self, + feedback_id: str, + *, + model: str = None, **kwargs) -> 'DetailedResponse': """ Delete a specified feedback entry. @@ -589,10 +595,10 @@ def create_batch(self, Run Compare and Comply methods over a collection of input documents. **Important:** Batch processing requires the use of the [IBM Cloud Object Storage - service](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-about#about-ibm-cloud-object-storage). + service](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-about#about-ibm-cloud-object-storage). The use of IBM Cloud Object Storage with Compare and Comply is discussed at [Using batch - processing](https://cloud.ibm.com/docs/services/compare-comply?topic=compare-comply-batching#before-you-batch). + processing](https://cloud.ibm.com/docs/compare-comply?topic=compare-comply-batching#before-you-batch). :param str function: The Compare and Comply method to run across the submitted input documents. @@ -996,7 +1002,9 @@ class Address(): `end`. """ - def __init__(self, *, text: str = None, + def __init__(self, + *, + text: str = None, location: 'Location' = None) -> None: """ Initialize a Address object. @@ -1725,7 +1733,9 @@ class Category(): IBM to provide feedback or receive support. """ - def __init__(self, *, label: str = None, + def __init__(self, + *, + label: str = None, provenance_ids: List[str] = None) -> None: """ Initialize a Category object. @@ -2502,7 +2512,9 @@ class Contexts(): `end`. """ - def __init__(self, *, text: str = None, + def __init__(self, + *, + text: str = None, location: 'Location' = None) -> None: """ Initialize a Contexts object. @@ -3150,7 +3162,10 @@ class DocInfo(): :attr str hash: (optional) The MD5 hash of the input document. """ - def __init__(self, *, html: str = None, title: str = None, + def __init__(self, + *, + html: str = None, + title: str = None, hash: str = None) -> None: """ Initialize a DocInfo object. @@ -4761,7 +4776,9 @@ class KeyValuePair(): :attr List[Value] value: (optional) A list of values in a key-value pair. """ - def __init__(self, *, key: 'Key' = None, + def __init__(self, + *, + key: 'Key' = None, value: List['Value'] = None) -> None: """ Initialize a KeyValuePair object. @@ -5070,7 +5087,9 @@ class Mention(): `end`. """ - def __init__(self, *, text: str = None, + def __init__(self, + *, + text: str = None, location: 'Location' = None) -> None: """ Initialize a Mention object. @@ -5896,7 +5915,9 @@ class SectionTitle(): `end`. """ - def __init__(self, *, text: str = None, + def __init__(self, + *, + text: str = None, location: 'Location' = None) -> None: """ Initialize a SectionTitle object. @@ -6369,7 +6390,9 @@ class TableTitle(): :attr str text: (optional) The text of the identified table title or caption. """ - def __init__(self, *, location: 'Location' = None, + def __init__(self, + *, + location: 'Location' = None, text: str = None) -> None: """ Initialize a TableTitle object. diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 15717d031..2fa04f3b4 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -134,7 +134,9 @@ def create_environment(self, response = self.send(request) return response - def list_environments(self, *, name: str = None, + def list_environments(self, + *, + name: str = None, **kwargs) -> 'DetailedResponse': """ List environments. @@ -1611,7 +1613,7 @@ def query(self, By using this method, you can construct long queries. For details, see the [Discovery - documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-query-concepts#query-concepts). + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts). :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. @@ -1771,7 +1773,7 @@ def query_notices(self, Queries for notices (errors or warnings) that might have been generated by the system. Notices are generated when ingesting documents and performing relevance training. See the [Discovery - documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-query-concepts#query-concepts) + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts) for more details on the query language. :param str environment_id: The ID of the environment. @@ -1909,7 +1911,7 @@ def federated_query(self, By using this method, you can construct long queries that search multiple collection. For details, see the [Discovery - documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-query-concepts#query-concepts). + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts). :param str environment_id: The ID of the environment. :param str collection_ids: A comma-separated list of collection IDs to be @@ -2060,7 +2062,7 @@ def federated_query_notices(self, Queries for notices (errors or warnings) that might have been generated by the system. Notices are generated when ingesting documents and performing relevance training. See the [Discovery - documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-query-concepts#query-concepts) + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts) for more details on the query language. :param str environment_id: The ID of the environment. @@ -2715,7 +2717,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/discovery?topic=discovery-information-security#information-security). + security](https://cloud.ibm.com/docs/discovery?topic=discovery-information-security#information-security). :param str customer_id: The customer ID for which all data is to be deleted. @@ -3047,7 +3049,9 @@ def get_metrics_event_rate(self, response = self.send(request) return response - def get_metrics_query_token_event(self, *, count: int = None, + def get_metrics_query_token_event(self, + *, + count: int = None, **kwargs) -> 'DetailedResponse': """ Most frequent query tokens with an event. @@ -3396,7 +3400,10 @@ def list_gateways(self, environment_id: str, response = self.send(request) return response - def create_gateway(self, environment_id: str, *, name: str = None, + def create_gateway(self, + environment_id: str, + *, + name: str = None, **kwargs) -> 'DetailedResponse': """ Create Gateway. @@ -4001,7 +4008,9 @@ class CollectionUsage(): environment. """ - def __init__(self, *, available: int = None, + def __init__(self, + *, + available: int = None, maximum_allowed: int = None) -> None: """ Initialize a CollectionUsage object. @@ -4562,12 +4571,12 @@ class CredentialDetails(): object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). + documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). :attr str secret_access_key: (optional) The secret access key associated with the cloud object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). + documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). """ def __init__(self, @@ -4669,13 +4678,13 @@ def __init__(self, cloud object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). + documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). :param str secret_access_key: (optional) The secret access key associated with the cloud object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/services/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). + documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). """ self.credential_type = credential_type self.client_id = client_id @@ -5262,7 +5271,9 @@ class DeleteCredentials(): :attr str status: (optional) The status of the deletion request. """ - def __init__(self, *, credential_id: str = None, + def __init__(self, + *, + credential_id: str = None, status: str = None) -> None: """ Initialize a DeleteCredentials object. @@ -5944,7 +5955,7 @@ class Enrichment(): Classification options. Additionally, when using the `elements` enrichment the configuration specified and files ingested must meet all the criteria specified in [the - documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-element-classification#element-classification). + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-element-classification#element-classification). :attr bool ignore_downstream_errors: (optional) If true, then most errors generated during the enrichment process will be treated as warnings and will not cause the document to fail processing. @@ -5979,7 +5990,7 @@ def __init__(self, Classification options. Additionally, when using the `elements` enrichment the configuration specified and files ingested must meet all the criteria specified in [the - documentation](https://cloud.ibm.com/docs/services/discovery?topic=discovery-element-classification#element-classification). + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-element-classification#element-classification). :param str description: (optional) Describes what the enrichment step does. :param bool overwrite: (optional) Indicates that the enrichments will overwrite the destination_field field if it already exists. @@ -6394,36 +6405,38 @@ class EnvironmentDocuments(): """ Summary of the document usage statistics for the environment. - :attr int indexed: (optional) Number of documents indexed for the environment. + :attr int available: (optional) Number of documents indexed for the environment. :attr int maximum_allowed: (optional) Total number of documents allowed in the environment's capacity. """ - def __init__(self, *, indexed: int = None, + def __init__(self, + *, + available: int = None, maximum_allowed: int = None) -> None: """ Initialize a EnvironmentDocuments object. - :param int indexed: (optional) Number of documents indexed for the + :param int available: (optional) Number of documents indexed for the environment. :param int maximum_allowed: (optional) Total number of documents allowed in the environment's capacity. """ - self.indexed = indexed + self.available = available self.maximum_allowed = maximum_allowed @classmethod def from_dict(cls, _dict: Dict) -> 'EnvironmentDocuments': """Initialize a EnvironmentDocuments object from a json dictionary.""" args = {} - valid_keys = ['indexed', 'maximum_allowed'] + valid_keys = ['available', 'maximum_allowed'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class EnvironmentDocuments: ' + ', '.join(bad_keys)) - if 'indexed' in _dict: - args['indexed'] = _dict.get('indexed') + if 'available' in _dict: + args['available'] = _dict.get('available') if 'maximum_allowed' in _dict: args['maximum_allowed'] = _dict.get('maximum_allowed') return cls(**args) @@ -6436,8 +6449,8 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'indexed') and self.indexed is not None: - _dict['indexed'] = self.indexed + if hasattr(self, 'available') and self.available is not None: + _dict['available'] = self.available if hasattr(self, 'maximum_allowed') and self.maximum_allowed is not None: _dict['maximum_allowed'] = self.maximum_allowed @@ -8429,7 +8442,8 @@ class MetricResponse(): aggregations. """ - def __init__(self, *, + def __init__(self, + *, aggregations: List['MetricAggregation'] = None) -> None: """ Initialize a MetricResponse object. @@ -8657,7 +8671,8 @@ class MetricTokenResponse(): token aggregations. """ - def __init__(self, *, + def __init__(self, + *, aggregations: List['MetricTokenAggregation'] = None) -> None: """ Initialize a MetricTokenResponse object. @@ -8854,7 +8869,9 @@ class NluEnrichmentEmotion(): that will have any associated emotions detected. """ - def __init__(self, *, document: bool = None, + def __init__(self, + *, + document: bool = None, targets: List[str] = None) -> None: """ Initialize a NluEnrichmentEmotion object. @@ -9438,7 +9455,9 @@ class NluEnrichmentSentiment(): that will have any associated sentiment analyzed. """ - def __init__(self, *, document: bool = None, + def __init__(self, + *, + document: bool = None, targets: List[str] = None) -> None: """ Initialize a NluEnrichmentSentiment object. @@ -11065,7 +11084,9 @@ class SduStatusCustomFields(): are allowed in this collection. """ - def __init__(self, *, defined: int = None, + def __init__(self, + *, + defined: int = None, maximum_allowed: int = None) -> None: """ Initialize a SduStatusCustomFields object. @@ -11709,7 +11730,10 @@ class SourceOptionsFolder(): folder. By default, all documents in the folder are crawled. """ - def __init__(self, owner_user_id: str, folder_id: str, *, + def __init__(self, + owner_user_id: str, + folder_id: str, + *, limit: int = None) -> None: """ Initialize a SourceOptionsFolder object. @@ -12256,7 +12280,9 @@ class SourceStatus(): time of the next crawl attempt. """ - def __init__(self, *, status: str = None, + def __init__(self, + *, + status: str = None, next_crawl: datetime = None) -> None: """ Initialize a SourceStatus object. diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 4578d4d8e..569b17cf7 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -146,7 +146,7 @@ def query(self, Query a project. By using this method, you can construct queries. For details, see the [Discovery - documentation](https://cloud.ibm.com/docs/services/discovery-data?topic=discovery-data-query-concepts). + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-concepts). :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. @@ -1432,14 +1432,14 @@ class ComponentSettingsResponse(): component setting aggregations. """ - def __init__(self, - *, - fields_shown: 'ComponentSettingsFieldsShown' = None, - autocomplete: bool = None, - structured_search: bool = None, - results_per_page: int = None, - aggregations: List['ComponentSettingsAggregation'] = None - ) -> None: + def __init__( + self, + *, + fields_shown: 'ComponentSettingsFieldsShown' = None, + autocomplete: bool = None, + structured_search: bool = None, + results_per_page: int = None, + aggregations: List['ComponentSettingsAggregation'] = None) -> None: """ Initialize a ComponentSettingsResponse object. @@ -3543,7 +3543,9 @@ class QueryTopHitsAggregationResult(): :attr List[dict] hits: (optional) An array of the document results. """ - def __init__(self, matching_results: int, *, + def __init__(self, + matching_results: int, + *, hits: List[dict] = None) -> None: """ Initialize a QueryTopHitsAggregationResult object. @@ -5817,17 +5819,20 @@ class QueryHistogramAggregation(QueryAggregation): :attr str field: The numeric field name used to create the histogram. :attr int interval: The size of the sections the results are split into. + :attr str name: (optional) Identifier specified in the query request of this + aggregation. :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric intervals. """ - def __init__(self, - type: str, - field: str, - interval: int, - *, - results: List['QueryHistogramAggregationResult'] = None - ) -> None: + def __init__( + self, + type: str, + field: str, + interval: int, + *, + name: str = None, + results: List['QueryHistogramAggregationResult'] = None) -> None: """ Initialize a QueryHistogramAggregation object. @@ -5836,19 +5841,22 @@ def __init__(self, unique_count, and top_hits. :param str field: The numeric field name used to create the histogram. :param int interval: The size of the sections the results are split into. + :param str name: (optional) Identifier specified in the query request of + this aggregation. :param List[QueryHistogramAggregationResult] results: (optional) Array of numeric intervals. """ self.type = type self.field = field self.interval = interval + self.name = name self.results = results @classmethod def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': """Initialize a QueryHistogramAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'field', 'interval', 'results'] + valid_keys = ['type', 'field', 'interval', 'name', 'results'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -5872,6 +5880,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': raise ValueError( 'Required property \'interval\' not present in QueryHistogramAggregation JSON' ) + if 'name' in _dict: + args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ QueryHistogramAggregationResult._from_dict(x) @@ -5893,6 +5903,8 @@ def to_dict(self) -> Dict: _dict['field'] = self.field if hasattr(self, 'interval') and self.interval is not None: _dict['interval'] = self.interval + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] return _dict @@ -6031,6 +6043,8 @@ class QueryTermAggregation(QueryAggregation): :attr str field: The field in the document used to generate top values from. :attr int count: (optional) The number of top values returned. + :attr str name: (optional) Identifier specified in the query request of this + aggregation. :attr List[QueryTermAggregationResult] results: (optional) Array of top values for the field. """ @@ -6040,6 +6054,7 @@ def __init__(self, field: str, *, count: int = None, + name: str = None, results: List['QueryTermAggregationResult'] = None) -> None: """ Initialize a QueryTermAggregation object. @@ -6050,19 +6065,22 @@ def __init__(self, :param str field: The field in the document used to generate top values from. :param int count: (optional) The number of top values returned. + :param str name: (optional) Identifier specified in the query request of + this aggregation. :param List[QueryTermAggregationResult] results: (optional) Array of top values for the field. """ self.type = type self.field = field self.count = count + self.name = name self.results = results @classmethod def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': """Initialize a QueryTermAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'field', 'count', 'results'] + valid_keys = ['type', 'field', 'count', 'name', 'results'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -6082,6 +6100,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': ) if 'count' in _dict: args['count'] = _dict.get('count') + if 'name' in _dict: + args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ QueryTermAggregationResult._from_dict(x) @@ -6103,6 +6123,8 @@ def to_dict(self) -> Dict: _dict['field'] = self.field if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] return _dict @@ -6133,17 +6155,20 @@ class QueryTimesliceAggregation(QueryAggregation): :attr str field: The date field name used to create the timeslice. :attr str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. + :attr str name: (optional) Identifier specified in the query request of this + aggregation. :attr List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ - def __init__(self, - type: str, - field: str, - interval: str, - *, - results: List['QueryTimesliceAggregationResult'] = None - ) -> None: + def __init__( + self, + type: str, + field: str, + interval: str, + *, + name: str = None, + results: List['QueryTimesliceAggregationResult'] = None) -> None: """ Initialize a QueryTimesliceAggregation object. @@ -6153,19 +6178,22 @@ def __init__(self, :param str field: The date field name used to create the timeslice. :param str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. + :param str name: (optional) Identifier specified in the query request of + this aggregation. :param List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ self.type = type self.field = field self.interval = interval + self.name = name self.results = results @classmethod def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': """Initialize a QueryTimesliceAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'field', 'interval', 'results'] + valid_keys = ['type', 'field', 'interval', 'name', 'results'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -6189,6 +6217,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': raise ValueError( 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' ) + if 'name' in _dict: + args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ QueryTimesliceAggregationResult._from_dict(x) @@ -6210,6 +6240,8 @@ def to_dict(self) -> Dict: _dict['field'] = self.field if hasattr(self, 'interval') and self.interval is not None: _dict['interval'] = self.interval + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: _dict['results'] = [x._to_dict() for x in self.results] return _dict @@ -6238,6 +6270,8 @@ class QueryTopHitsAggregation(QueryAggregation): Returns the top documents ranked by the score of the query. :attr int size: The number of documents to return. + :attr str name: (optional) Identifier specified in the query request of this + aggregation. :attr QueryTopHitsAggregationResult hits: (optional) """ @@ -6245,6 +6279,7 @@ def __init__(self, type: str, size: int, *, + name: str = None, hits: 'QueryTopHitsAggregationResult' = None) -> None: """ Initialize a QueryTopHitsAggregation object. @@ -6253,17 +6288,20 @@ def __init__(self, term, histogram, timeslice, nested, filter, min, max, sum, average, unique_count, and top_hits. :param int size: The number of documents to return. + :param str name: (optional) Identifier specified in the query request of + this aggregation. :param QueryTopHitsAggregationResult hits: (optional) """ self.type = type self.size = size + self.name = name self.hits = hits @classmethod def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': """Initialize a QueryTopHitsAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'size', 'hits'] + valid_keys = ['type', 'size', 'name', 'hits'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -6281,6 +6319,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': raise ValueError( 'Required property \'size\' not present in QueryTopHitsAggregation JSON' ) + if 'name' in _dict: + args['name'] = _dict.get('name') if 'hits' in _dict: args['hits'] = QueryTopHitsAggregationResult._from_dict( _dict.get('hits')) @@ -6298,6 +6338,8 @@ def to_dict(self) -> Dict: _dict['type'] = self.type if hasattr(self, 'size') and self.size is not None: _dict['size'] = self.size + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name if hasattr(self, 'hits') and self.hits is not None: _dict['hits'] = self.hits._to_dict() return _dict diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 282fecef8..5441a6f68 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -491,7 +491,9 @@ class ClassifiedClass(): :attr str class_name: (optional) Class label. """ - def __init__(self, *, confidence: float = None, + def __init__(self, + *, + confidence: float = None, class_name: str = None) -> None: """ Initialize a ClassifiedClass object. diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 961999177..d1ab59e6d 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -19,7 +19,7 @@ request. The service cleans HTML content before analysis by default, so the results can ignore most advertisements and other unwanted content. You can create [custom -models](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) +models](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) with Watson Knowledge Studio to detect custom entities and relations in Natural Language Understanding. """ @@ -113,7 +113,7 @@ def analyze(self, - Syntax (Experimental). If a language for the input text is not specified with the `language` parameter, the service [automatically detects the - language](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-detectable-languages). + language](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-detectable-languages). :param Features features: Specific features to analyze the document for. :param str text: (optional) The plain text to analyze. One of the `text`, @@ -124,10 +124,10 @@ def analyze(self, `html`, or `url` parameters is required. :param bool clean: (optional) Set this to `false` to disable webpage cleaning. To learn more about webpage cleaning, see the [Analyzing - webpages](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages) + webpages](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages) documentation. :param str xpath: (optional) An [XPath - query](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages#xpath) + query](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages#xpath) to perform on `html` or `url` input. Results of the query will be appended to the cleaned webpage text before it is analyzed. To analyze only the results of the XPath query, set the `clean` parameter to `false`. @@ -139,7 +139,7 @@ def analyze(self, of your text. This overrides automatic language detection. Language support differs depending on the features you include in your analysis. See [Language - support](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-language-support) + support](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-language-support) for more information. :param int limit_text_characters: (optional) Sets the maximum number of characters that are processed by the service. @@ -194,7 +194,7 @@ def list_models(self, **kwargs) -> 'DetailedResponse': List models. Lists Watson Knowledge Studio [custom entities and relations - models](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + models](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) that are deployed to your Natural Language Understanding service. :param dict headers: A `dict` containing the request headers @@ -718,7 +718,7 @@ class CategoriesOptions(): each categorization. **This is available only for English categories.**. :attr int limit: (optional) Maximum number of categories to return. :attr str model: (optional) Enter a [custom - model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + model](https://cloud.ibm.com/docs/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 @@ -740,7 +740,7 @@ def __init__(self, categories.**. :param int limit: (optional) Maximum number of categories to return. :param str model: (optional) Enter a [custom - model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + model](https://cloud.ibm.com/docs/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 @@ -873,7 +873,7 @@ class CategoriesResult(): :attr str label: (optional) The path to the category through the 5-level taxonomy hierarchy. For the complete list of categories, see the [Categories - hierarchy](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) + hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) documentation. :attr float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. @@ -892,7 +892,7 @@ def __init__(self, :param str label: (optional) The path to the category through the 5-level taxonomy hierarchy. For the complete list of categories, see the [Categories - hierarchy](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) + hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) documentation. :param float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. @@ -967,7 +967,8 @@ class CategoriesResultExplanation(): followed by phrases that were less and less impactful. """ - def __init__(self, *, + def __init__(self, + *, relevant_text: List['CategoriesRelevantText'] = None) -> None: """ Initialize a CategoriesResultExplanation object. @@ -1462,7 +1463,9 @@ class EmotionOptions(): target string that is found in the document. """ - def __init__(self, *, document: bool = None, + def __init__(self, + *, + document: bool = None, targets: List[str] = None) -> None: """ Initialize a EmotionOptions object. @@ -1712,7 +1715,7 @@ class EntitiesOptions(): """ Identifies people, cities, organizations, and other entities in the content. See [Entity types and - subtypes](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. @@ -1721,7 +1724,7 @@ class EntitiesOptions(): :attr bool mentions: (optional) Set this to `true` to return locations of entity mentions. :attr str model: (optional) Enter a [custom - model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the standard entity detection model. :attr bool sentiment: (optional) Set this to `true` to return sentiment information for detected entities. @@ -1743,7 +1746,7 @@ def __init__(self, :param bool mentions: (optional) Set this to `true` to return locations of entity mentions. :param str model: (optional) Enter a [custom - model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the standard entity detection model. :param bool sentiment: (optional) Set this to `true` to return sentiment information for detected entities. @@ -2131,7 +2134,7 @@ class Features(): Supported languages: English. :attr EntitiesOptions entities: (optional) Identifies people, cities, organizations, and other entities in the content. See [Entity types and - subtypes](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. @@ -2146,7 +2149,7 @@ class Features(): related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". See [Relation - types](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-relations). + types](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-relations). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. @@ -2195,7 +2198,7 @@ def __init__(self, Supported languages: English. :param EntitiesOptions entities: (optional) Identifies people, cities, organizations, and other entities in the content. See [Entity types and - subtypes](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. @@ -2210,7 +2213,7 @@ def __init__(self, are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". See [Relation - types](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-relations). + types](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-relations). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. @@ -2976,12 +2979,12 @@ class RelationsOptions(): Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". See [Relation - types](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-relations). + types](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-relations). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. :attr str model: (optional) Enter a [custom - model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the default model. """ @@ -2990,7 +2993,7 @@ def __init__(self, *, model: str = None) -> None: Initialize a RelationsOptions object. :param str model: (optional) Enter a [custom - model](https://cloud.ibm.com/docs/services/natural-language-understanding?topic=natural-language-understanding-customizing) + model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the default model. """ self.model = model @@ -3831,7 +3834,9 @@ class SentimentOptions(): target string that is found in the document. """ - def __init__(self, *, document: bool = None, + def __init__(self, + *, + document: bool = None, targets: List[str] = None) -> None: """ Initialize a SentimentOptions object. @@ -4053,7 +4058,9 @@ class SyntaxOptionsTokens(): speech for each token. """ - def __init__(self, *, lemma: bool = None, + def __init__(self, + *, + lemma: bool = None, part_of_speech: bool = None) -> None: """ Initialize a SyntaxOptionsTokens object. @@ -4197,7 +4204,9 @@ class TargetedEmotionResults(): :attr EmotionScores emotion: (optional) The emotion results for the target. """ - def __init__(self, *, text: str = None, + def __init__(self, + *, + text: str = None, emotion: 'EmotionScores' = None) -> None: """ Initialize a TargetedEmotionResults object. diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index f04105bc4..7ba3c2986 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -507,9 +507,9 @@ class ConsumptionPreferencesCategory(): inferred from the input text for the individual preferences of the category. """ - def __init__(self, consumption_preference_category_id: str, name: str, - consumption_preferences: List['ConsumptionPreferences'] - ) -> None: + def __init__( + self, consumption_preference_category_id: str, name: str, + consumption_preferences: List['ConsumptionPreferences']) -> None: """ Initialize a ConsumptionPreferencesCategory object. @@ -903,18 +903,19 @@ class Profile(): no warnings. """ - def __init__(self, - processed_language: str, - word_count: int, - personality: List['Trait'], - needs: List['Trait'], - values: List['Trait'], - warnings: List['Warning'], - *, - word_count_message: str = None, - behavior: List['Behavior'] = None, - consumption_preferences: List[ - 'ConsumptionPreferencesCategory'] = None) -> None: + def __init__( + self, + processed_language: str, + word_count: int, + personality: List['Trait'], + needs: List['Trait'], + values: List['Trait'], + warnings: List['Warning'], + *, + word_count_message: str = None, + behavior: List['Behavior'] = None, + consumption_preferences: List['ConsumptionPreferencesCategory'] = None + ) -> None: """ Initialize a Profile object. diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index 4deab9ab9..899b84e28 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -41,25 +41,25 @@ def synthesize_using_websocket(self, :param str text: Provides the text that is to be synthesized. The client can pass plain text or text that is annotated with the Speech Synthesis Markup Language (SSML). For more - information, see [Specifying input text](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-usingHTTP#input). + information, see [Specifying input text](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-usingHTTP#input). SSML input can also include the element; - see [Specifying an SSML mark](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-timing#mark). + see [Specifying an SSML mark](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-timing#mark). The client can pass a maximum of 5 KB of text with the request. :param SynthesizeCallback synthesize_callback: The callback method for the websocket. :param str accept: Specifies the requested format (MIME type) of the audio. For more information, see [Specifying - an audio format](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-usingHTTP#format). In addition to the + an audio format](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-usingHTTP#format). In addition to the supported specifications, you can use */* to specify the default audio format, audio/ogg;codecs=opus. :param str voice: The voice to use for synthesis. :param list[str] timings: Specifies that the service is to return word timing information for all strings of the input text. The service returns the start and end time of each string of the input. Specify words as the lone element of the array to request word timings. Specify an empty array or omit the parameter to receive no word timings. For - more information, see [Obtaining word timings](https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-timing#timing). + more information, see [Obtaining word timings](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-timing#timing). Not supported for Japanese input text. :param str customization_id: Specifies the globally unique identifier (GUID) for a custom voice model that is to be used for the synthesis. A custom voice model is guaranteed to work only if it matches the language of the voice that is used for the synthesis. If you include a customization ID, you must call the method with the service credentials of the custom model's owner. Omit the parameter to use the specified voice with no customization. For more information, see [Understanding customization] - (https://cloud.ibm.com/docs/services/text-to-speech?topic=text-to-speech-customIntro#customIntro). + (https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customIntro#customIntro). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. :param dict headers: A `dict` containing the request headers diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 616918c3e..7dd168947 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -27,7 +27,8 @@ or more words that, when combined, sound like the word. A phonetic translation is based on the SSML phoneme format for representing a word. You can specify a phonetic translation in standard International Phonetic Alphabet (IPA) representation or in the proprietary IBM -Symbolic Phonetic Representation (SPR). +Symbolic Phonetic Representation (SPR). The Arabic, Chinese, Dutch, and Korean languages +support only IPA. """ import json @@ -104,7 +105,10 @@ def list_voices(self, **kwargs) -> 'DetailedResponse': response = self.send(request) return response - def get_voice(self, voice: str, *, customization_id: str = None, + def get_voice(self, + voice: str, + *, + customization_id: str = None, **kwargs) -> 'DetailedResponse': """ Get a voice. @@ -231,10 +235,10 @@ def synthesize(self, :param str voice: (optional) The voice to use for synthesis. :param str customization_id: (optional) The customization ID (GUID) of a custom voice model to use for the synthesis. If a custom voice model is - specified, it is guaranteed to work only if it matches the language of the - indicated voice. You must make the request with credentials for the - instance of the service that owns the custom model. Omit the parameter to - use the specified voice with no customization. + specified, it works only if it matches the language of the indicated voice. + You must make the request with credentials for the instance of the service + that owns the custom model. Omit the parameter to use the specified voice + with no customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -283,8 +287,7 @@ def get_pronunciation(self, pronunciation for a specific format. You can also request the pronunciation for a specific voice to see the default translation for the language of that voice or for a specific custom voice model to see the translation for that voice model. - **Note:** This method is currently a beta release. The method does not support the - Arabic, Chinese, and Dutch languages. + **Note:** This method is currently a beta release. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). @@ -293,8 +296,9 @@ def get_pronunciation(self, the pronunciation is to be returned. All voices for the same language (for example, `en-US`) return the same translation. :param str format: (optional) The phoneme format in which to return the - pronunciation. Omit the parameter to obtain the pronunciation in the - default format. + pronunciation. The Arabic, Chinese, Dutch, and Korean languages support + only IPA. Omit the parameter to obtain the pronunciation in the default + format. :param str customization_id: (optional) The customization ID (GUID) of a custom voice model for which the pronunciation is to be returned. The language of a specified custom model must match the language of the @@ -352,14 +356,16 @@ def create_voice_model(self, model. You can optionally specify the language and a description for the new model. The model is owned by the instance of the service whose credentials are used to create it. - **Note:** This method is currently a beta release. The service does not support - voice model customization for the Arabic, Chinese, and Dutch languages. + **Note:** This method is currently a beta release. **See also:** [Creating a custom 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. - Omit the parameter to use the the default language, `en-US`. + You create a custom voice model for a specific language, not for a specific + voice. A custom model can be used with any voice, standard or neural, for + its specified language. Omit the parameter to use the the default language, + `en-US`. :param str description: (optional) A description of the new custom voice model. Specifying a description is recommended. :param dict headers: A `dict` containing the request headers @@ -389,7 +395,9 @@ def create_voice_model(self, response = self.send(request) return response - def list_voice_models(self, *, language: str = None, + def list_voice_models(self, + *, + language: str = None, **kwargs) -> 'DetailedResponse': """ List custom models. @@ -739,8 +747,9 @@ def add_word(self, :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR - translation. A sounds-like is one or more words that, when combined, sound - like the word. + translation. The Arabic, Chinese, Dutch, and Korean languages support only + IPA. A sounds-like is one or more words that, when combined, sound like the + word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -920,18 +929,24 @@ class Voice(Enum): """ The voice for which information is to be returned. """ + AR_AR_OMARVOICE = 'ar-AR_OmarVoice' DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' + DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONVOICE = 'en-US_AllisonVoice' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' + EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' EN_US_LISAVOICE = 'en-US_LisaVoice' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' EN_US_MICHAELVOICE = 'en-US_MichaelVoice' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' + EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' ES_ES_LAURAVOICE = 'es-ES_LauraVoice' @@ -946,8 +961,15 @@ class Voice(Enum): IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' + KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' + KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' + NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' + NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' + ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' + ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' class SynthesizeEnums(object): @@ -982,14 +1004,19 @@ class Voice(Enum): DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' + DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONVOICE = 'en-US_AllisonVoice' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' + EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' EN_US_LISAVOICE = 'en-US_LisaVoice' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' EN_US_MICHAELVOICE = 'en-US_MichaelVoice' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' + EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' ES_ES_LAURAVOICE = 'es-ES_LauraVoice' @@ -1004,6 +1031,8 @@ class Voice(Enum): IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' + KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' + KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' @@ -1021,18 +1050,24 @@ class Voice(Enum): All voices for the same language (for example, `en-US`) return the same translation. """ + AR_AR_OMARVOICE = 'ar-AR_OmarVoice' DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' + DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONVOICE = 'en-US_AllisonVoice' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' + EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' EN_US_LISAVOICE = 'en-US_LisaVoice' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' EN_US_MICHAELVOICE = 'en-US_MichaelVoice' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' + EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' ES_ES_LAURAVOICE = 'es-ES_LauraVoice' @@ -1047,13 +1082,21 @@ class Voice(Enum): IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' + KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' + KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' + NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' + NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' + ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' + ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' class Format(Enum): """ - The phoneme format in which to return the pronunciation. Omit the parameter to - obtain the pronunciation in the default format. + The phoneme format in which to return the pronunciation. The Arabic, Chinese, + Dutch, and Korean languages support only IPA. Omit the parameter to obtain the + pronunciation in the default format. """ IBM = 'ibm' IPA = 'ipa' @@ -1067,6 +1110,7 @@ class Language(Enum): credentials are to be returned. Omit the parameter to see all custom voice models that are owned by the requester. """ + AR_AR = 'ar-AR' DE_DE = 'de-DE' EN_GB = 'en-GB' EN_US = 'en-US' @@ -1076,7 +1120,10 @@ class Language(Enum): 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' ############################################################################## @@ -1242,8 +1289,9 @@ class Translation(): :attr str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic - string of a word either as an IPA translation or as an IBM SPR translation. A - sounds-like is one or more words that, when combined, sound like the word. + string of a word either as an IPA translation or as an IBM SPR translation. The + Arabic, Chinese, Dutch, and Korean languages support only IPA. A sounds-like is + one or more words that, when combined, sound like the word. :attr str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of @@ -1259,8 +1307,9 @@ def __init__(self, translation: str, *, part_of_speech: str = None) -> None: :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR - translation. A sounds-like is one or more words that, when combined, sound - like the word. + translation. The Arabic, Chinese, Dutch, and Korean languages support only + IPA. A sounds-like is one or more words that, when combined, sound like the + word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -1814,12 +1863,14 @@ class Word(): """ Information about a word for the custom voice model. - :attr str word: The word for the custom voice model. + :attr str word: The word for the custom voice model. The maximum length of a + word is 49 characters. :attr str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic - string of a word either as an IPA or IBM SPR translation. A sounds-like - translation consists of one or more words that, when combined, sound like the - word. + string of a word either as an IPA or IBM SPR translation. The Arabic, Chinese, + Dutch, and Korean languages support only IPA. A sounds-like translation consists + of one or more words that, when combined, sound like the word. The maximum + length of a translation is 499 characters. :attr str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of @@ -1836,12 +1887,14 @@ def __init__(self, """ Initialize a Word object. - :param str word: The word for the custom voice model. + :param str word: The word for the custom voice model. The maximum length of + a word is 49 characters. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing - the phonetic string of a word either as an IPA or IBM SPR translation. A + the phonetic string of a word either as an IPA or IBM SPR translation. The + Arabic, Chinese, Dutch, and Korean languages support only IPA. A sounds-like translation consists of one or more words that, when combined, - sound like the word. + sound like the word. The maximum length of a translation is 499 characters. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 84f904a69..524daef6b 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -279,7 +279,9 @@ def create_classifier(self, response = self.send(request) return response - def list_classifiers(self, *, verbose: bool = None, + def list_classifiers(self, + *, + verbose: bool = None, **kwargs) -> 'DetailedResponse': """ Retrieve a list of classifiers. @@ -666,7 +668,10 @@ class ClassResult(): identified. """ - def __init__(self, class_: str, score: float, *, + def __init__(self, + class_: str, + score: float, + *, type_hierarchy: str = None) -> None: """ Initialize a ClassResult object. diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 8c320eddd..6711750cd 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -137,10 +137,11 @@ def analyze(self, params = {'version': self.version} form_data = [] - collection_ids = self._convert_list(collection_ids) - form_data.append(('collection_ids', (None, collection_ids, 'text/plain'))) - features = self._convert_list(features) - form_data.append(('features', (None, features, 'text/plain'))) + for item in collection_ids: + form_data.append( + ('collection_ids', (None, item, 'application/json'))) + for item in features: + form_data.append(('features', (None, item, 'application/json'))) if images_file: for item in images_file: form_data.append(('images_file', (item.filename, item.data, @@ -148,7 +149,8 @@ def analyze(self, 'application/octet-stream'))) if image_url: for item in image_url: - form_data.append(('image_url', (None, item, 'text/plain'))) + form_data.append( + ('image_url', (None, item, 'application/json'))) if threshold: threshold = str(threshold) form_data.append(('threshold', (None, threshold, 'text/plain'))) @@ -1371,7 +1373,8 @@ class DetectedObjects(): identified objects. """ - def __init__(self, *, + def __init__(self, + *, collections: List['CollectionObjects'] = None) -> None: """ Initialize a DetectedObjects object. @@ -2121,7 +2124,9 @@ class ImageSummary(): (UTC) that the image was most recently updated. """ - def __init__(self, *, image_id: str = None, + def __init__(self, + *, + image_id: str = None, updated: datetime = None) -> None: """ Initialize a ImageSummary object. @@ -2707,7 +2712,9 @@ class TrainingDataObject(): around the object. """ - def __init__(self, *, object: str = None, + def __init__(self, + *, + object: str = None, location: 'Location' = None) -> None: """ Initialize a TrainingDataObject object. @@ -3137,19 +3144,19 @@ class UpdateObjectMetadata(): :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. + :attr int count: (optional) Number of bounding boxes in the collection with the + updated object name. """ - def __init__(self, object: str, count: int) -> None: + def __init__(self, object: str, *, count: int = None) -> 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. + :param int count: (optional) Number of bounding boxes in the collection + with the updated object name. """ self.object = object self.count = count @@ -3172,10 +3179,6 @@ def from_dict(cls, _dict: Dict) -> 'UpdateObjectMetadata': ) if 'count' in _dict: args['count'] = _dict.get('count') - else: - raise ValueError( - 'Required property \'count\' not present in UpdateObjectMetadata JSON' - ) return cls(**args) @classmethod @@ -3220,7 +3223,10 @@ class Warning(): :attr str more_info: (optional) A URL for more information about the solution. """ - def __init__(self, code: str, message: str, *, + def __init__(self, + code: str, + message: str, + *, more_info: str = None) -> None: """ Initialize a Warning object. From 46e831801efec3a9124305632f0469b1adf6c804 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 16 Apr 2020 10:05:23 -0400 Subject: [PATCH 241/455] test: add tests for new updates and update formatting in tests --- .../test_language_translator_v3.py | 3 + test/unit/test_assistant_v1.py | 1170 +++++---------- test/unit/test_assistant_v2.py | 67 +- test/unit/test_compare_comply_v1.py | 178 +-- test/unit/test_discovery_v1.py | 1267 ++++++----------- test/unit/test_discovery_v2.py | 274 ++-- test/unit/test_language_translator_v3.py | 178 +-- .../test_natural_language_classifier_v1.py | 106 +- .../test_natural_language_understanding_v1.py | 94 +- test/unit/test_personality_insights_v3.py | 17 +- test/unit/test_speech_to_text_v1.py | 716 +++++----- test/unit/test_text_to_speech_v1.py | 285 ++-- test/unit/test_tone_analyzer_v3.py | 37 +- test/unit/test_visual_recognition_v3.py | 107 +- test/unit/test_visual_recognition_v4.py | 298 ++-- 15 files changed, 1900 insertions(+), 2897 deletions(-) diff --git a/test/integration/test_language_translator_v3.py b/test/integration/test_language_translator_v3.py index 5e0b6db04..b44ece2a7 100644 --- a/test/integration/test_language_translator_v3.py +++ b/test/integration/test_language_translator_v3.py @@ -19,6 +19,9 @@ def test_translate(self): translation = self.language_translator.translate( text='Hello', model_id='en-es').get_result() assert translation is not None + translation = self.language_translator.translate( + text='Hello, how are you?', target='es').get_result() + assert translation is not None def test_document_translation(self): with open(join(dirname(__file__), '../../resources/hello_world.txt'), diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index c3fbcabf0..6adccb3fb 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -29,7 +29,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for message #----------------------------------------------------------------------------- @@ -75,16 +74,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.message(**body) return output @@ -92,25 +91,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({ - "input": - MessageInput._from_dict(json.loads("""{"text": "fake_text"}""") - ), - "intents": [], - "entities": [], - "alternate_intents": - True, - "context": - Context._from_dict( - json.loads( - """{"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}""" - )), - "output": - OutputData._from_dict( - json.loads( - """{"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}""" - )), - }) + body.update({"input": MessageInput._from_dict(json.loads("""{"text": "fake_text"}""")), "intents": [], "entities": [], "alternate_intents": True, "context": Context._from_dict(json.loads("""{"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}""")), "output": OutputData._from_dict(json.loads("""{"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}""")), }) body['nodes_visited_details'] = True return body @@ -130,7 +111,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_workspaces #----------------------------------------------------------------------------- @@ -175,16 +155,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.list_workspaces(**body) return output @@ -246,45 +226,23 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.create_workspace(**body) return output def construct_full_body(self): body = dict() - body.update({ - "name": - "string1", - "description": - "string1", - "language": - "string1", - "metadata": { - "mock": "data" - }, - "learning_opt_out": - True, - "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"}, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""" - )), - "intents": [], - "entities": [], - "dialog_nodes": [], - "counterexamples": [], - "webhooks": [], - }) + body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) body['include_audit'] = True return body @@ -338,16 +296,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.get_workspace(**body) return output @@ -411,16 +369,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.update_workspace(**body) return output @@ -428,29 +386,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({ - "name": - "string1", - "description": - "string1", - "language": - "string1", - "metadata": { - "mock": "data" - }, - "learning_opt_out": - True, - "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"}, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""" - )), - "intents": [], - "entities": [], - "dialog_nodes": [], - "counterexamples": [], - "webhooks": [], - }) + body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) body['append'] = True body['include_audit'] = True return body @@ -506,16 +442,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.delete_workspace(**body) return output @@ -541,7 +477,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_intents #----------------------------------------------------------------------------- @@ -587,16 +522,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.list_intents(**body) return output @@ -662,16 +597,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.create_intent(**body) return output @@ -679,22 +614,14 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({ - "intent": "string1", - "description": "string1", - "examples": [], - }) + body.update({"intent": "string1", "description": "string1", "examples": [], }) body['include_audit'] = True return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({ - "intent": "string1", - "description": "string1", - "examples": [], - }) + body.update({"intent": "string1", "description": "string1", "examples": [], }) return body @@ -737,23 +664,22 @@ def test_get_intent_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format( - body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.get_intent(**body) return output @@ -812,23 +738,22 @@ def test_update_intent_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format( - body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.update_intent(**body) return output @@ -837,11 +762,7 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({ - "new_intent": "string1", - "new_description": "string1", - "new_examples": [], - }) + body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) body['append'] = True body['include_audit'] = True return body @@ -850,11 +771,7 @@ def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({ - "new_intent": "string1", - "new_description": "string1", - "new_examples": [], - }) + body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) return body @@ -897,23 +814,22 @@ def test_delete_intent_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format( - body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.delete_intent(**body) return output @@ -941,7 +857,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_examples #----------------------------------------------------------------------------- @@ -981,23 +896,22 @@ def test_list_examples_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format( - body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.list_examples(**body) return output @@ -1058,23 +972,22 @@ def test_create_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format( - body['workspace_id'], body['intent']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.create_example(**body) return output @@ -1083,10 +996,7 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({ - "text": "string1", - "mentions": [], - }) + body.update({"text": "string1", "mentions": [], }) body['include_audit'] = True return body @@ -1094,10 +1004,7 @@ def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['intent'] = "string1" - body.update({ - "text": "string1", - "mentions": [], - }) + body.update({"text": "string1", "mentions": [], }) return body @@ -1140,23 +1047,22 @@ def test_get_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - body['workspace_id'], body['intent'], body['text']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.get_example(**body) return output @@ -1216,23 +1122,22 @@ def test_update_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - body['workspace_id'], body['intent'], body['text']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.update_example(**body) return output @@ -1242,10 +1147,7 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['intent'] = "string1" body['text'] = "string1" - body.update({ - "new_text": "string1", - "new_mentions": [], - }) + body.update({"new_text": "string1", "new_mentions": [], }) body['include_audit'] = True return body @@ -1254,10 +1156,7 @@ def construct_required_body(self): body['workspace_id'] = "string1" body['intent'] = "string1" body['text'] = "string1" - body.update({ - "new_text": "string1", - "new_mentions": [], - }) + body.update({"new_text": "string1", "new_mentions": [], }) return body @@ -1300,23 +1199,22 @@ def test_delete_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - body['workspace_id'], body['intent'], body['text']) + endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.delete_example(**body) return output @@ -1346,7 +1244,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_counterexamples #----------------------------------------------------------------------------- @@ -1378,8 +1275,7 @@ def test_list_counterexamples_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_counterexamples_empty(self): - check_empty_required_params( - self, fake_response_CounterexampleCollection_json) + check_empty_required_params(self, fake_response_CounterexampleCollection_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1387,23 +1283,22 @@ def test_list_counterexamples_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples'.format( - body['workspace_id']) + endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.list_counterexamples(**body) return output @@ -1462,23 +1357,22 @@ def test_create_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples'.format( - body['workspace_id']) + endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.create_counterexample(**body) return output @@ -1486,18 +1380,14 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({ - "text": "string1", - }) + body.update({"text": "string1", }) body['include_audit'] = True return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({ - "text": "string1", - }) + body.update({"text": "string1", }) return body @@ -1540,23 +1430,22 @@ def test_get_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( - body['workspace_id'], body['text']) + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.get_counterexample(**body) return output @@ -1614,23 +1503,22 @@ def test_update_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( - body['workspace_id'], body['text']) + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.update_counterexample(**body) return output @@ -1639,9 +1527,7 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['text'] = "string1" - body.update({ - "new_text": "string1", - }) + body.update({"new_text": "string1", }) body['include_audit'] = True return body @@ -1649,9 +1535,7 @@ def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['text'] = "string1" - body.update({ - "new_text": "string1", - }) + body.update({"new_text": "string1", }) return body @@ -1694,23 +1578,22 @@ def test_delete_counterexample_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format( - body['workspace_id'], body['text']) + endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.delete_counterexample(**body) return output @@ -1738,7 +1621,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_entities #----------------------------------------------------------------------------- @@ -1784,16 +1666,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.list_entities(**body) return output @@ -1859,16 +1741,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.create_entity(**body) return output @@ -1876,30 +1758,14 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({ - "entity": "string1", - "description": "string1", - "metadata": { - "mock": "data" - }, - "fuzzy_match": True, - "values": [], - }) + body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) body['include_audit'] = True return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({ - "entity": "string1", - "description": "string1", - "metadata": { - "mock": "data" - }, - "fuzzy_match": True, - "values": [], - }) + body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) return body @@ -1942,23 +1808,22 @@ def test_get_entity_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format( - body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.get_entity(**body) return output @@ -2017,23 +1882,22 @@ def test_update_entity_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format( - body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.update_entity(**body) return output @@ -2042,15 +1906,7 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({ - "new_entity": "string1", - "new_description": "string1", - "new_metadata": { - "mock": "data" - }, - "new_fuzzy_match": True, - "new_values": [], - }) + body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) body['append'] = True body['include_audit'] = True return body @@ -2059,15 +1915,7 @@ def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({ - "new_entity": "string1", - "new_description": "string1", - "new_metadata": { - "mock": "data" - }, - "new_fuzzy_match": True, - "new_values": [], - }) + body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) return body @@ -2110,23 +1958,22 @@ def test_delete_entity_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format( - body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.delete_entity(**body) return output @@ -2154,7 +2001,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_mentions #----------------------------------------------------------------------------- @@ -2186,8 +2032,7 @@ def test_list_mentions_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_mentions_empty(self): - check_empty_required_params(self, - fake_response_EntityMentionCollection_json) + check_empty_required_params(self, fake_response_EntityMentionCollection_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2195,23 +2040,22 @@ def test_list_mentions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/mentions'.format( - body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}/mentions'.format(body['workspace_id'], body['entity']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.list_mentions(**body) return output @@ -2241,7 +2085,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_values #----------------------------------------------------------------------------- @@ -2281,23 +2124,22 @@ def test_list_values_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format( - body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.list_values(**body) return output @@ -2359,23 +2201,22 @@ def test_create_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format( - body['workspace_id'], body['entity']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.create_value(**body) return output @@ -2384,15 +2225,7 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({ - "value": "string1", - "metadata": { - "mock": "data" - }, - "type": "string1", - "synonyms": [], - "patterns": [], - }) + body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) body['include_audit'] = True return body @@ -2400,15 +2233,7 @@ def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['entity'] = "string1" - body.update({ - "value": "string1", - "metadata": { - "mock": "data" - }, - "type": "string1", - "synonyms": [], - "patterns": [], - }) + body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) return body @@ -2451,23 +2276,22 @@ def test_get_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.get_value(**body) return output @@ -2528,23 +2352,22 @@ def test_update_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.update_value(**body) return output @@ -2554,15 +2377,7 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({ - "new_value": "string1", - "new_metadata": { - "mock": "data" - }, - "new_type": "string1", - "new_synonyms": [], - "new_patterns": [], - }) + body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) body['append'] = True body['include_audit'] = True return body @@ -2572,15 +2387,7 @@ def construct_required_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({ - "new_value": "string1", - "new_metadata": { - "mock": "data" - }, - "new_type": "string1", - "new_synonyms": [], - "new_patterns": [], - }) + body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) return body @@ -2623,23 +2430,22 @@ def test_delete_value_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.delete_value(**body) return output @@ -2669,7 +2475,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_synonyms #----------------------------------------------------------------------------- @@ -2709,23 +2514,22 @@ def test_list_synonyms_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( - body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.list_synonyms(**body) return output @@ -2788,23 +2592,22 @@ def test_create_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( - body['workspace_id'], body['entity'], body['value']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.create_synonym(**body) return output @@ -2814,9 +2617,7 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({ - "synonym": "string1", - }) + body.update({"synonym": "string1", }) body['include_audit'] = True return body @@ -2825,9 +2626,7 @@ def construct_required_body(self): body['workspace_id'] = "string1" body['entity'] = "string1" body['value'] = "string1" - body.update({ - "synonym": "string1", - }) + body.update({"synonym": "string1", }) return body @@ -2870,24 +2669,22 @@ def test_get_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - body['workspace_id'], body['entity'], body['value'], - body['synonym']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.get_synonym(**body) return output @@ -2949,24 +2746,22 @@ def test_update_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - body['workspace_id'], body['entity'], body['value'], - body['synonym']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.update_synonym(**body) return output @@ -2977,9 +2772,7 @@ def construct_full_body(self): body['entity'] = "string1" body['value'] = "string1" body['synonym'] = "string1" - body.update({ - "new_synonym": "string1", - }) + body.update({"new_synonym": "string1", }) body['include_audit'] = True return body @@ -2989,9 +2782,7 @@ def construct_required_body(self): body['entity'] = "string1" body['value'] = "string1" body['synonym'] = "string1" - body.update({ - "new_synonym": "string1", - }) + body.update({"new_synonym": "string1", }) return body @@ -3034,24 +2825,22 @@ def test_delete_synonym_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - body['workspace_id'], body['entity'], body['value'], - body['synonym']) + endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.delete_synonym(**body) return output @@ -3083,7 +2872,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_dialog_nodes #----------------------------------------------------------------------------- @@ -3115,8 +2903,7 @@ def test_list_dialog_nodes_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_dialog_nodes_empty(self): - check_empty_required_params(self, - fake_response_DialogNodeCollection_json) + check_empty_required_params(self, fake_response_DialogNodeCollection_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -3124,23 +2911,22 @@ def test_list_dialog_nodes_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes'.format( - body['workspace_id']) + endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.list_dialog_nodes(**body) return output @@ -3199,23 +2985,22 @@ def test_create_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes'.format( - body['workspace_id']) + endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.create_dialog_node(**body) return output @@ -3223,106 +3008,14 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({ - "dialog_node": - "string1", - "description": - "string1", - "conditions": - "string1", - "parent": - "string1", - "previous_sibling": - "string1", - "output": - DialogNodeOutput._from_dict( - json.loads( - """{"generic": [], "modifiers": {"overwrite": false}}""" - )), - "context": { - "mock": "data" - }, - "metadata": { - "mock": "data" - }, - "next_step": - DialogNodeNextStep._from_dict( - json.loads( - """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" - )), - "title": - "string1", - "type": - "string1", - "event_name": - "string1", - "variable": - "string1", - "actions": [], - "digress_in": - "string1", - "digress_out": - "string1", - "digress_out_slots": - "string1", - "user_label": - "string1", - "disambiguation_opt_out": - True, - }) + body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) body['include_audit'] = True return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({ - "dialog_node": - "string1", - "description": - "string1", - "conditions": - "string1", - "parent": - "string1", - "previous_sibling": - "string1", - "output": - DialogNodeOutput._from_dict( - json.loads( - """{"generic": [], "modifiers": {"overwrite": false}}""" - )), - "context": { - "mock": "data" - }, - "metadata": { - "mock": "data" - }, - "next_step": - DialogNodeNextStep._from_dict( - json.loads( - """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" - )), - "title": - "string1", - "type": - "string1", - "event_name": - "string1", - "variable": - "string1", - "actions": [], - "digress_in": - "string1", - "digress_out": - "string1", - "digress_out_slots": - "string1", - "user_label": - "string1", - "disambiguation_opt_out": - True, - }) + body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) return body @@ -3365,23 +3058,22 @@ def test_get_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( - body['workspace_id'], body['dialog_node']) + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.get_dialog_node(**body) return output @@ -3439,23 +3131,22 @@ def test_update_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( - body['workspace_id'], body['dialog_node']) + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.update_dialog_node(**body) return output @@ -3464,53 +3155,7 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['dialog_node'] = "string1" - body.update({ - "new_dialog_node": - "string1", - "new_description": - "string1", - "new_conditions": - "string1", - "new_parent": - "string1", - "new_previous_sibling": - "string1", - "new_output": - DialogNodeOutput._from_dict( - json.loads( - """{"generic": [], "modifiers": {"overwrite": false}}""" - )), - "new_context": { - "mock": "data" - }, - "new_metadata": { - "mock": "data" - }, - "new_next_step": - DialogNodeNextStep._from_dict( - json.loads( - """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" - )), - "new_title": - "string1", - "new_type": - "string1", - "new_event_name": - "string1", - "new_variable": - "string1", - "new_actions": [], - "new_digress_in": - "string1", - "new_digress_out": - "string1", - "new_digress_out_slots": - "string1", - "new_user_label": - "string1", - "new_disambiguation_opt_out": - True, - }) + body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) body['include_audit'] = True return body @@ -3518,53 +3163,7 @@ def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['dialog_node'] = "string1" - body.update({ - "new_dialog_node": - "string1", - "new_description": - "string1", - "new_conditions": - "string1", - "new_parent": - "string1", - "new_previous_sibling": - "string1", - "new_output": - DialogNodeOutput._from_dict( - json.loads( - """{"generic": [], "modifiers": {"overwrite": false}}""" - )), - "new_context": { - "mock": "data" - }, - "new_metadata": { - "mock": "data" - }, - "new_next_step": - DialogNodeNextStep._from_dict( - json.loads( - """{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""" - )), - "new_title": - "string1", - "new_type": - "string1", - "new_event_name": - "string1", - "new_variable": - "string1", - "new_actions": [], - "new_digress_in": - "string1", - "new_digress_out": - "string1", - "new_digress_out_slots": - "string1", - "new_user_label": - "string1", - "new_disambiguation_opt_out": - True, - }) + body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) return body @@ -3607,23 +3206,22 @@ def test_delete_dialog_node_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( - body['workspace_id'], body['dialog_node']) + endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.delete_dialog_node(**body) return output @@ -3651,7 +3249,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_logs #----------------------------------------------------------------------------- @@ -3697,16 +3294,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.list_logs(**body) return output @@ -3771,16 +3368,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.list_all_logs(**body) return output @@ -3809,7 +3406,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for delete_user_data #----------------------------------------------------------------------------- @@ -3855,16 +3451,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=202, - content_type='') - + url, + body=json.dumps(response), + status=202, + content_type='') + def call_service(self, body): service = AssistantV1( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output @@ -3902,7 +3498,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -3919,7 +3514,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -3931,7 +3525,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -3948,7 +3541,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 46887549b..30824422a 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -28,7 +28,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_session #----------------------------------------------------------------------------- @@ -74,16 +73,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.create_session(**body) return output @@ -138,23 +137,22 @@ def test_delete_session_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/assistants/{0}/sessions/{1}'.format( - body['assistant_id'], body['session_id']) + endpoint = '/v2/assistants/{0}/sessions/{1}'.format(body['assistant_id'], body['session_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.delete_session(**body) return output @@ -182,7 +180,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for message #----------------------------------------------------------------------------- @@ -222,23 +219,22 @@ def test_message_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format( - body['assistant_id'], body['session_id']) + endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format(body['assistant_id'], body['session_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), - version='2019-02-28', - ) + version='2020-04-01', + ) service.set_service_url(base_url) output = service.message(**body) return output @@ -247,18 +243,7 @@ def construct_full_body(self): body = dict() body['assistant_id'] = "string1" body['session_id'] = "string1" - body.update({ - "input": - MessageInput._from_dict( - json.loads( - """{"message_type": "fake_message_type", "text": "fake_text", "options": {"debug": false, "restart": false, "alternate_intents": false, "return_context": true}, "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id"}""" - )), - "context": - MessageContext._from_dict( - json.loads( - """{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}}, "skills": {}}""" - )), - }) + body.update({"input": MessageInput._from_dict(json.loads("""{"message_type": "fake_message_type", "text": "fake_text", "options": {"debug": false, "restart": false, "alternate_intents": false, "return_context": true, "export": true}, "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id"}""")), "context": MessageContext._from_dict(json.loads("""{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}}, "skills": {}}""")), }) return body def construct_required_body(self): @@ -290,7 +275,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -307,7 +291,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -319,7 +302,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -336,7 +318,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 7b54f1773..753607be4 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -30,7 +30,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for convert_to_html #----------------------------------------------------------------------------- @@ -76,16 +75,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.convert_to_html(**body) return output @@ -113,7 +112,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for classify_elements #----------------------------------------------------------------------------- @@ -159,16 +157,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.classify_elements(**body) return output @@ -196,7 +194,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for extract_tables #----------------------------------------------------------------------------- @@ -242,16 +239,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.extract_tables(**body) return output @@ -279,7 +276,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for compare_documents #----------------------------------------------------------------------------- @@ -325,16 +321,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.compare_documents(**body) return output @@ -367,7 +363,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for add_feedback #----------------------------------------------------------------------------- @@ -413,48 +408,28 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.add_feedback(**body) return output def construct_full_body(self): body = dict() - body.update({ - "feedback_data": - FeedbackDataInput._from_dict( - json.loads( - """{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""" - )), - "user_id": - "string1", - "comment": - "string1", - }) + body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) return body def construct_required_body(self): body = dict() - body.update({ - "feedback_data": - FeedbackDataInput._from_dict( - json.loads( - """{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""" - )), - "user_id": - "string1", - "comment": - "string1", - }) + body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) return body @@ -502,16 +477,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.list_feedback(**body) return output @@ -586,16 +561,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.get_feedback(**body) return output @@ -657,16 +632,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.delete_feedback(**body) return output @@ -693,7 +668,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_batch #----------------------------------------------------------------------------- @@ -739,16 +713,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.create_batch(**body) return output @@ -821,16 +795,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.list_batches(**body) return output @@ -889,16 +863,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.get_batch(**body) return output @@ -959,16 +933,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version='2018-10-15', - ) + ) service.set_service_url(base_url) output = service.update_batch(**body) return output @@ -1009,7 +983,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -1026,7 +999,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -1038,7 +1010,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -1055,7 +1026,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 07c5b3914..d18699074 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -30,7 +30,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_environment #----------------------------------------------------------------------------- @@ -76,36 +75,28 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_environment(**body) return output def construct_full_body(self): body = dict() - body.update({ - "name": "string1", - "description": "string1", - "size": "string1", - }) + body.update({"name": "string1", "description": "string1", "size": "string1", }) return body def construct_required_body(self): body = dict() - body.update({ - "name": "string1", - "description": "string1", - "size": "string1", - }) + body.update({"name": "string1", "description": "string1", "size": "string1", }) return body @@ -153,16 +144,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_environments(**body) return output @@ -222,16 +213,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_environment(**body) return output @@ -292,16 +283,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_environment(**body) return output @@ -309,21 +300,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({ - "name": "string1", - "description": "string1", - "size": "string1", - }) + body.update({"name": "string1", "description": "string1", "size": "string1", }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({ - "name": "string1", - "description": "string1", - "size": "string1", - }) + body.update({"name": "string1", "description": "string1", "size": "string1", }) return body @@ -358,8 +341,7 @@ def test_delete_environment_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_environment_empty(self): - check_empty_required_params( - self, fake_response_DeleteEnvironmentResponse_json) + check_empty_required_params(self, fake_response_DeleteEnvironmentResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -373,16 +355,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_environment(**body) return output @@ -429,8 +411,7 @@ def test_list_fields_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_fields_empty(self): - check_empty_required_params( - self, fake_response_ListCollectionFieldsResponse_json) + check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -444,16 +425,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_fields(**body) return output @@ -481,7 +462,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_configuration #----------------------------------------------------------------------------- @@ -521,23 +501,22 @@ def test_create_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations'.format( - body['environment_id']) + endpoint = '/v1/environments/{0}/configurations'.format(body['environment_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_configuration(**body) return output @@ -545,47 +524,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({ - "name": - "string1", - "description": - "string1", - "conversions": - Conversions._from_dict( - json.loads( - """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" - )), - "enrichments": [], - "normalizations": [], - "source": - Source._from_dict( - json.loads( - """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" - )), - }) + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({ - "name": - "string1", - "description": - "string1", - "conversions": - Conversions._from_dict( - json.loads( - """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" - )), - "enrichments": [], - "normalizations": [], - "source": - Source._from_dict( - json.loads( - """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" - )), - }) + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) return body @@ -620,8 +565,7 @@ def test_list_configurations_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_configurations_empty(self): - check_empty_required_params( - self, fake_response_ListConfigurationsResponse_json) + check_empty_required_params(self, fake_response_ListConfigurationsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -629,23 +573,22 @@ def test_list_configurations_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations'.format( - body['environment_id']) + endpoint = '/v1/environments/{0}/configurations'.format(body['environment_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_configurations(**body) return output @@ -701,23 +644,22 @@ def test_get_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format( - body['environment_id'], body['configuration_id']) + endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_configuration(**body) return output @@ -774,23 +716,22 @@ def test_update_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format( - body['environment_id'], body['configuration_id']) + endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_configuration(**body) return output @@ -799,48 +740,14 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['configuration_id'] = "string1" - body.update({ - "name": - "string1", - "description": - "string1", - "conversions": - Conversions._from_dict( - json.loads( - """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" - )), - "enrichments": [], - "normalizations": [], - "source": - Source._from_dict( - json.loads( - """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" - )), - }) + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['configuration_id'] = "string1" - body.update({ - "name": - "string1", - "description": - "string1", - "conversions": - Conversions._from_dict( - json.loads( - """{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""" - )), - "enrichments": [], - "normalizations": [], - "source": - Source._from_dict( - json.loads( - """{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""" - )), - }) + body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) return body @@ -875,8 +782,7 @@ def test_delete_configuration_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_configuration_empty(self): - check_empty_required_params( - self, fake_response_DeleteConfigurationResponse_json) + check_empty_required_params(self, fake_response_DeleteConfigurationResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -884,23 +790,22 @@ def test_delete_configuration_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format( - body['environment_id'], body['configuration_id']) + endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_configuration(**body) return output @@ -928,7 +833,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_collection #----------------------------------------------------------------------------- @@ -968,23 +872,22 @@ def test_create_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections'.format( - body['environment_id']) + endpoint = '/v1/environments/{0}/collections'.format(body['environment_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_collection(**body) return output @@ -992,23 +895,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({ - "name": "string1", - "description": "string1", - "configuration_id": "string1", - "language": "string1", - }) + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({ - "name": "string1", - "description": "string1", - "configuration_id": "string1", - "language": "string1", - }) + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) return body @@ -1043,8 +936,7 @@ def test_list_collections_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_collections_empty(self): - check_empty_required_params(self, - fake_response_ListCollectionsResponse_json) + check_empty_required_params(self, fake_response_ListCollectionsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1052,23 +944,22 @@ def test_list_collections_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections'.format( - body['environment_id']) + endpoint = '/v1/environments/{0}/collections'.format(body['environment_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_collections(**body) return output @@ -1124,23 +1015,22 @@ def test_get_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_collection(**body) return output @@ -1197,23 +1087,22 @@ def test_update_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_collection(**body) return output @@ -1222,22 +1111,14 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({ - "name": "string1", - "description": "string1", - "configuration_id": "string1", - }) + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({ - "name": "string1", - "description": "string1", - "configuration_id": "string1", - }) + body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) return body @@ -1272,8 +1153,7 @@ def test_delete_collection_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_collection_empty(self): - check_empty_required_params( - self, fake_response_DeleteCollectionResponse_json) + check_empty_required_params(self, fake_response_DeleteCollectionResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1281,23 +1161,22 @@ def test_delete_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_collection(**body) return output @@ -1346,8 +1225,7 @@ def test_list_collection_fields_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_collection_fields_empty(self): - check_empty_required_params( - self, fake_response_ListCollectionFieldsResponse_json) + check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1355,23 +1233,22 @@ def test_list_collection_fields_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/fields'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/fields'.format(body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_collection_fields(**body) return output @@ -1399,7 +1276,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_expansions #----------------------------------------------------------------------------- @@ -1439,23 +1315,22 @@ def test_list_expansions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_expansions(**body) return output @@ -1512,23 +1387,22 @@ def test_create_expansions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_expansions(**body) return output @@ -1537,18 +1411,14 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({ - "expansions": [], - }) + body.update({"expansions": [], }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({ - "expansions": [], - }) + body.update({"expansions": [], }) return body @@ -1591,23 +1461,22 @@ def test_delete_expansions_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_expansions(**body) return output @@ -1656,8 +1525,7 @@ def test_get_tokenization_dictionary_status_required_response(self): #-------------------------------------------------------- @responses.activate def test_get_tokenization_dictionary_status_empty(self): - check_empty_required_params(self, - fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1665,23 +1533,22 @@ def test_get_tokenization_dictionary_status_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_tokenization_dictionary_status(**body) return output @@ -1730,8 +1597,7 @@ def test_create_tokenization_dictionary_required_response(self): #-------------------------------------------------------- @responses.activate def test_create_tokenization_dictionary_empty(self): - check_empty_required_params(self, - fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1739,23 +1605,22 @@ def test_create_tokenization_dictionary_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_tokenization_dictionary(**body) return output @@ -1764,9 +1629,7 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({ - "tokenization_rules": [], - }) + body.update({"tokenization_rules": [], }) return body def construct_required_body(self): @@ -1815,23 +1678,22 @@ def test_delete_tokenization_dictionary_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_tokenization_dictionary(**body) return output @@ -1880,8 +1742,7 @@ def test_get_stopword_list_status_required_response(self): #-------------------------------------------------------- @responses.activate def test_get_stopword_list_status_empty(self): - check_empty_required_params(self, - fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1889,23 +1750,22 @@ def test_get_stopword_list_status_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_stopword_list_status(**body) return output @@ -1954,8 +1814,7 @@ def test_create_stopword_list_required_response(self): #-------------------------------------------------------- @responses.activate def test_create_stopword_list_empty(self): - check_empty_required_params(self, - fake_response_TokenDictStatusResponse_json) + check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1963,23 +1822,22 @@ def test_create_stopword_list_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_stopword_list(**body) return output @@ -2039,23 +1897,22 @@ def test_delete_stopword_list_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_stopword_list(**body) return output @@ -2083,7 +1940,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for add_document #----------------------------------------------------------------------------- @@ -2123,23 +1979,22 @@ def test_add_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents'.format(body['environment_id'], body['collection_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.add_document(**body) return output @@ -2200,23 +2055,22 @@ def test_get_document_status_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( - body['environment_id'], body['collection_id'], body['document_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_document_status(**body) return output @@ -2275,23 +2129,22 @@ def test_update_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( - body['environment_id'], body['collection_id'], body['document_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_document(**body) return output @@ -2346,8 +2199,7 @@ def test_delete_document_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_document_empty(self): - check_empty_required_params(self, - fake_response_DeleteDocumentResponse_json) + check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2355,23 +2207,22 @@ def test_delete_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( - body['environment_id'], body['collection_id'], body['document_id']) + endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -2401,7 +2252,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for query #----------------------------------------------------------------------------- @@ -2441,23 +2291,22 @@ def test_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/query'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/query'.format(body['environment_id'], body['collection_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.query(**body) return output @@ -2466,28 +2315,7 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({ - "filter": "string1", - "query": "string1", - "natural_language_query": "string1", - "passages": True, - "aggregation": "string1", - "count": 12345, - "return_": "string1", - "offset": 12345, - "sort": "string1", - "highlight": True, - "passages_fields": "string1", - "passages_count": 12345, - "passages_characters": 12345, - "deduplicate": True, - "deduplicate_field": "string1", - "similar": True, - "similar_document_ids": "string1", - "similar_fields": "string1", - "bias": "string1", - "spelling_suggestions": True, - }) + body.update({"filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", "spelling_suggestions": True, }) body['x_watson_logging_opt_out'] = True return body @@ -2529,8 +2357,7 @@ def test_query_notices_required_response(self): #-------------------------------------------------------- @responses.activate def test_query_notices_empty(self): - check_empty_required_params(self, - fake_response_QueryNoticesResponse_json) + check_empty_required_params(self, fake_response_QueryNoticesResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2538,23 +2365,22 @@ def test_query_notices_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/notices'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/notices'.format(body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.query_notices(**body) return output @@ -2634,16 +2460,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.federated_query(**body) return output @@ -2651,56 +2477,14 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({ - "collection_ids": "string1", - "filter": "string1", - "query": "string1", - "natural_language_query": "string1", - "passages": True, - "aggregation": "string1", - "count": 12345, - "return_": "string1", - "offset": 12345, - "sort": "string1", - "highlight": True, - "passages_fields": "string1", - "passages_count": 12345, - "passages_characters": 12345, - "deduplicate": True, - "deduplicate_field": "string1", - "similar": True, - "similar_document_ids": "string1", - "similar_fields": "string1", - "bias": "string1", - }) + body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) body['x_watson_logging_opt_out'] = True return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({ - "collection_ids": "string1", - "filter": "string1", - "query": "string1", - "natural_language_query": "string1", - "passages": True, - "aggregation": "string1", - "count": 12345, - "return_": "string1", - "offset": 12345, - "sort": "string1", - "highlight": True, - "passages_fields": "string1", - "passages_count": 12345, - "passages_characters": 12345, - "deduplicate": True, - "deduplicate_field": "string1", - "similar": True, - "similar_document_ids": "string1", - "similar_fields": "string1", - "bias": "string1", - }) + body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) return body @@ -2735,8 +2519,7 @@ def test_federated_query_notices_required_response(self): #-------------------------------------------------------- @responses.activate def test_federated_query_notices_empty(self): - check_empty_required_params(self, - fake_response_QueryNoticesResponse_json) + check_empty_required_params(self, fake_response_QueryNoticesResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -2750,16 +2533,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.federated_query_notices(**body) return output @@ -2829,23 +2612,22 @@ def test_get_autocompletion_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/autocompletion'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/autocompletion'.format(body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_autocompletion(**body) return output @@ -2877,7 +2659,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_training_data #----------------------------------------------------------------------------- @@ -2917,23 +2698,22 @@ def test_list_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_training_data(**body) return output @@ -2990,23 +2770,22 @@ def test_add_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.add_training_data(**body) return output @@ -3015,22 +2794,14 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "filter": "string1", - "examples": [], - }) + body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['collection_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "filter": "string1", - "examples": [], - }) + body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) return body @@ -3073,23 +2844,22 @@ def test_delete_all_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format( - body['environment_id'], body['collection_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_all_training_data(**body) return output @@ -3146,23 +2916,22 @@ def test_get_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( - body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_training_data(**body) return output @@ -3221,23 +2990,22 @@ def test_delete_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( - body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_id']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_training_data(**body) return output @@ -3288,8 +3056,7 @@ def test_list_training_examples_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_training_examples_empty(self): - check_empty_required_params(self, - fake_response_TrainingExampleList_json) + check_empty_required_params(self, fake_response_TrainingExampleList_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -3297,23 +3064,22 @@ def test_list_training_examples_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( - body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_training_examples(**body) return output @@ -3372,23 +3138,22 @@ def test_create_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( - body['environment_id'], body['collection_id'], body['query_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_training_example(**body) return output @@ -3398,11 +3163,7 @@ def construct_full_body(self): body['environment_id'] = "string1" body['collection_id'] = "string1" body['query_id'] = "string1" - body.update({ - "document_id": "string1", - "cross_reference": "string1", - "relevance": 12345, - }) + body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) return body def construct_required_body(self): @@ -3410,11 +3171,7 @@ def construct_required_body(self): body['environment_id'] = "string1" body['collection_id'] = "string1" body['query_id'] = "string1" - body.update({ - "document_id": "string1", - "cross_reference": "string1", - "relevance": 12345, - }) + body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) return body @@ -3457,24 +3214,22 @@ def test_delete_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( - body['environment_id'], body['collection_id'], body['query_id'], - body['example_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_training_example(**body) return output @@ -3535,24 +3290,22 @@ def test_update_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( - body['environment_id'], body['collection_id'], body['query_id'], - body['example_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_training_example(**body) return output @@ -3563,10 +3316,7 @@ def construct_full_body(self): body['collection_id'] = "string1" body['query_id'] = "string1" body['example_id'] = "string1" - body.update({ - "cross_reference": "string1", - "relevance": 12345, - }) + body.update({"cross_reference": "string1", "relevance": 12345, }) return body def construct_required_body(self): @@ -3575,10 +3325,7 @@ def construct_required_body(self): body['collection_id'] = "string1" body['query_id'] = "string1" body['example_id'] = "string1" - body.update({ - "cross_reference": "string1", - "relevance": 12345, - }) + body.update({"cross_reference": "string1", "relevance": 12345, }) return body @@ -3621,24 +3368,22 @@ def test_get_training_example_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( - body['environment_id'], body['collection_id'], body['query_id'], - body['example_id']) + endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_training_example(**body) return output @@ -3670,7 +3415,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for delete_user_data #----------------------------------------------------------------------------- @@ -3716,16 +3460,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output @@ -3751,7 +3495,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_event #----------------------------------------------------------------------------- @@ -3783,8 +3526,7 @@ def test_create_event_required_response(self): #-------------------------------------------------------- @responses.activate def test_create_event_empty(self): - check_empty_required_params(self, - fake_response_CreateEventResponse_json) + check_empty_required_params(self, fake_response_CreateEventResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -3798,44 +3540,28 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_event(**body) return output def construct_full_body(self): body = dict() - body.update({ - "type": - "string1", - "data": - EventData._from_dict( - json.loads( - """{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""" - )), - }) + body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) return body def construct_required_body(self): body = dict() - body.update({ - "type": - "string1", - "data": - EventData._from_dict( - json.loads( - """{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""" - )), - }) + body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) return body @@ -3883,16 +3609,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.query_log(**body) return output @@ -3955,16 +3681,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query(**body) return output @@ -4025,16 +3751,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query_event(**body) return output @@ -4095,16 +3821,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query_no_results(**body) return output @@ -4165,16 +3891,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_event_rate(**body) return output @@ -4235,16 +3961,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_metrics_query_token_event(**body) return output @@ -4269,7 +3995,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_credentials #----------------------------------------------------------------------------- @@ -4309,23 +4034,22 @@ def test_list_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials'.format( - body['environment_id']) + endpoint = '/v1/environments/{0}/credentials'.format(body['environment_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_credentials(**body) return output @@ -4380,23 +4104,22 @@ def test_create_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials'.format( - body['environment_id']) + endpoint = '/v1/environments/{0}/credentials'.format(body['environment_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_credentials(**body) return output @@ -4404,33 +4127,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({ - "source_type": - "string1", - "credential_details": - CredentialDetails._from_dict( - json.loads( - """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" - )), - "status": - "string1", - }) + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" - body.update({ - "source_type": - "string1", - "credential_details": - CredentialDetails._from_dict( - json.loads( - """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" - )), - "status": - "string1", - }) + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) return body @@ -4473,23 +4176,22 @@ def test_get_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format( - body['environment_id'], body['credential_id']) + endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_credentials(**body) return output @@ -4546,23 +4248,22 @@ def test_update_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format( - body['environment_id'], body['credential_id']) + endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.update_credentials(**body) return output @@ -4571,34 +4272,14 @@ def construct_full_body(self): body = dict() body['environment_id'] = "string1" body['credential_id'] = "string1" - body.update({ - "source_type": - "string1", - "credential_details": - CredentialDetails._from_dict( - json.loads( - """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" - )), - "status": - "string1", - }) + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) return body def construct_required_body(self): body = dict() body['environment_id'] = "string1" body['credential_id'] = "string1" - body.update({ - "source_type": - "string1", - "credential_details": - CredentialDetails._from_dict( - json.loads( - """{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""" - )), - "status": - "string1", - }) + body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) return body @@ -4641,23 +4322,22 @@ def test_delete_credentials_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format( - body['environment_id'], body['credential_id']) + endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_credentials(**body) return output @@ -4685,7 +4365,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_gateways #----------------------------------------------------------------------------- @@ -4725,23 +4404,22 @@ def test_list_gateways_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways'.format( - body['environment_id']) + endpoint = '/v1/environments/{0}/gateways'.format(body['environment_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.list_gateways(**body) return output @@ -4796,23 +4474,22 @@ def test_create_gateway_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways'.format( - body['environment_id']) + endpoint = '/v1/environments/{0}/gateways'.format(body['environment_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.create_gateway(**body) return output @@ -4820,9 +4497,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['environment_id'] = "string1" - body.update({ - "name": "string1", - }) + body.update({"name": "string1", }) return body def construct_required_body(self): @@ -4870,23 +4545,22 @@ def test_get_gateway_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways/{1}'.format( - body['environment_id'], body['gateway_id']) + endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.get_gateway(**body) return output @@ -4943,23 +4617,22 @@ def test_delete_gateway_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways/{1}'.format( - body['environment_id'], body['gateway_id']) + endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version='2019-04-30', - ) + ) service.set_service_url(base_url) output = service.delete_gateway(**body) return output @@ -4999,7 +4672,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -5016,7 +4688,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -5028,7 +4699,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -5045,16 +4715,15 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### fake_response__json = None -fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"indexed": 7, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" +fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" fake_response_ListEnvironmentsResponse_json = """{"environments": []}""" -fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"indexed": 7, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" -fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"indexed": 7, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" +fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" +fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" fake_response_DeleteEnvironmentResponse_json = """{"environment_id": "fake_environment_id", "status": "fake_status"}""" fake_response_ListCollectionFieldsResponse_json = """{"fields": []}""" fake_response_Configuration_json = """{"configuration_id": "fake_configuration_id", "name": "fake_name", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "description": "fake_description", "conversions": {"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}, "enrichments": [], "normalizations": [], "source": {"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}}""" diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 12cdef354..d5f320933 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -30,7 +30,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_collections #----------------------------------------------------------------------------- @@ -62,8 +61,7 @@ def test_list_collections_required_response(self): #-------------------------------------------------------- @responses.activate def test_list_collections_empty(self): - check_empty_required_params(self, - fake_response_ListCollectionsResponse_json) + check_empty_required_params(self, fake_response_ListCollectionsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -77,16 +75,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.list_collections(**body) return output @@ -112,7 +110,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for query #----------------------------------------------------------------------------- @@ -158,16 +155,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.query(**body) return output @@ -175,39 +172,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['project_id'] = "string1" - body.update({ - "collection_ids": [], - "filter": - "string1", - "query": - "string1", - "natural_language_query": - "string1", - "aggregation": - "string1", - "count": - 12345, - "return_": [], - "offset": - 12345, - "sort": - "string1", - "highlight": - True, - "spelling_suggestions": - True, - "table_results": - QueryLargeTableResults._from_dict( - json.loads("""{"enabled": false, "count": 5}""")), - "suggested_refinements": - QueryLargeSuggestedRefinements._from_dict( - json.loads("""{"enabled": false, "count": 5}""")), - "passages": - QueryLargePassages._from_dict( - json.loads( - """{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""" - )), - }) + body.update({"collection_ids": [], "filter": "string1", "query": "string1", "natural_language_query": "string1", "aggregation": "string1", "count": 12345, "return_": [], "offset": 12345, "sort": "string1", "highlight": True, "spelling_suggestions": True, "table_results": QueryLargeTableResults._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "suggested_refinements": QueryLargeSuggestedRefinements._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "passages": QueryLargePassages._from_dict(json.loads("""{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""")), }) return body def construct_required_body(self): @@ -261,16 +226,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.get_autocompletion(**body) return output @@ -322,8 +287,7 @@ def test_query_notices_required_response(self): #-------------------------------------------------------- @responses.activate def test_query_notices_empty(self): - check_empty_required_params(self, - fake_response_QueryNoticesResponse_json) + check_empty_required_params(self, fake_response_QueryNoticesResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -337,16 +301,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.query_notices(**body) return output @@ -412,16 +376,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.list_fields(**body) return output @@ -448,7 +412,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for get_component_settings #----------------------------------------------------------------------------- @@ -480,8 +443,7 @@ def test_get_component_settings_required_response(self): #-------------------------------------------------------- @responses.activate def test_get_component_settings_empty(self): - check_empty_required_params( - self, fake_response_ComponentSettingsResponse_json) + check_empty_required_params(self, fake_response_ComponentSettingsResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -489,23 +451,22 @@ def test_get_component_settings_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/component_settings'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/component_settings'.format(body['project_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.get_component_settings(**body) return output @@ -531,7 +492,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for add_document #----------------------------------------------------------------------------- @@ -571,23 +531,22 @@ def test_add_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents'.format( - body['project_id'], body['collection_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents'.format(body['project_id'], body['collection_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.add_document(**body) return output @@ -649,23 +608,22 @@ def test_update_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( - body['project_id'], body['collection_id'], body['document_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) 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=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.update_document(**body) return output @@ -721,8 +679,7 @@ def test_delete_document_required_response(self): #-------------------------------------------------------- @responses.activate def test_delete_document_empty(self): - check_empty_required_params(self, - fake_response_DeleteDocumentResponse_json) + check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -730,23 +687,22 @@ def test_delete_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( - body['project_id'], body['collection_id'], body['document_id']) + endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) 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='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -777,7 +733,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_training_queries #----------------------------------------------------------------------------- @@ -817,23 +772,22 @@ def test_list_training_queries_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.list_training_queries(**body) return output @@ -888,23 +842,22 @@ def test_delete_training_queries_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.delete_training_queries(**body) return output @@ -959,23 +912,22 @@ def test_create_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format( - body['project_id']) + endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.create_training_query(**body) return output @@ -983,21 +935,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['project_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - "filter": "string1", - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body def construct_required_body(self): body = dict() body['project_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - "filter": "string1", - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body @@ -1040,23 +984,22 @@ def test_get_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( - body['project_id'], body['query_id']) + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.get_training_query(**body) return output @@ -1113,23 +1056,22 @@ def test_update_training_query_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format( - body['project_id'], body['query_id']) + endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_id']) 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=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version='2019-11-22', - ) + ) service.set_service_url(base_url) output = service.update_training_query(**body) return output @@ -1138,22 +1080,14 @@ def construct_full_body(self): body = dict() body['project_id'] = "string1" body['query_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - "filter": "string1", - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body def construct_required_body(self): body = dict() body['project_id'] = "string1" body['query_id'] = "string1" - body.update({ - "natural_language_query": "string1", - "examples": [], - "filter": "string1", - }) + body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) return body @@ -1179,7 +1113,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -1196,7 +1129,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -1208,7 +1140,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -1225,7 +1156,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index f0a4f3098..65586dff3 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -30,7 +30,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for translate #----------------------------------------------------------------------------- @@ -76,38 +75,28 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.translate(**body) return output def construct_full_body(self): body = dict() - body.update({ - "text": [], - "model_id": "string1", - "source": "string1", - "target": "string1", - }) + body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) return body def construct_required_body(self): body = dict() - body.update({ - "text": [], - "model_id": "string1", - "source": "string1", - "target": "string1", - }) + body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) return body @@ -121,7 +110,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_identifiable_languages #----------------------------------------------------------------------------- @@ -166,16 +154,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.list_identifiable_languages(**body) return output @@ -220,8 +208,7 @@ def test_identify_required_response(self): #-------------------------------------------------------- @responses.activate def test_identify_empty(self): - check_empty_required_params(self, - fake_response_IdentifiedLanguages_json) + check_empty_required_params(self, fake_response_IdentifiedLanguages_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -235,16 +222,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.identify(**body) return output @@ -270,7 +257,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_models #----------------------------------------------------------------------------- @@ -315,16 +301,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.list_models(**body) return output @@ -386,16 +372,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.create_model(**body) return output @@ -459,16 +445,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.delete_model(**body) return output @@ -529,16 +515,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.get_model(**body) return output @@ -564,7 +550,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_documents #----------------------------------------------------------------------------- @@ -609,16 +594,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.list_documents(**body) return output @@ -677,16 +662,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.translate_document(**body) return output @@ -753,16 +738,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.get_document_status(**body) return output @@ -823,16 +808,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.delete_document(**body) return output @@ -887,23 +872,22 @@ def test_get_translated_document_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v3/documents/{0}/translated_document'.format( - body['document_id']) + endpoint = '/v3/documents/{0}/translated_document'.format(body['document_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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version='2018-05-01', - ) + ) service.set_service_url(base_url) output = service.get_translated_document(**body) return output @@ -942,7 +926,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -959,7 +942,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -971,7 +953,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -988,13 +969,12 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### fake_response__json = None -fake_response_TranslationResult_json = """{"word_count": 10, "character_count": 15, "translations": []}""" +fake_response_TranslationResult_json = """{"word_count": 10, "character_count": 15, "detected_language": "fake_detected_language", "detected_language_confidence": 28, "translations": []}""" fake_response_IdentifiableLanguages_json = """{"languages": []}""" fake_response_IdentifiedLanguages_json = """{"languages": []}""" fake_response_TranslationModels_json = """{"models": []}""" @@ -1002,6 +982,6 @@ def send_request(obj, body, response, url=None): fake_response_DeleteModelResult_json = """{"status": "fake_status"}""" fake_response_TranslationModel_json = """{"model_id": "fake_model_id", "name": "fake_name", "source": "fake_source", "target": "fake_target", "base_model_id": "fake_base_model_id", "domain": "fake_domain", "customizable": true, "default_model": false, "owner": "fake_owner", "status": "fake_status"}""" fake_response_DocumentList_json = """{"documents": []}""" -fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "filename": "fake_filename", "status": "fake_status", "model_id": "fake_model_id", "base_model_id": "fake_base_model_id", "source": "fake_source", "target": "fake_target", "created": "2017-05-16T13:56:54.957Z", "completed": "2017-05-16T13:56:54.957Z", "word_count": 10, "character_count": 15}""" -fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "filename": "fake_filename", "status": "fake_status", "model_id": "fake_model_id", "base_model_id": "fake_base_model_id", "source": "fake_source", "target": "fake_target", "created": "2017-05-16T13:56:54.957Z", "completed": "2017-05-16T13:56:54.957Z", "word_count": 10, "character_count": 15}""" +fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "filename": "fake_filename", "status": "fake_status", "model_id": "fake_model_id", "base_model_id": "fake_base_model_id", "source": "fake_source", "detected_language_confidence": 28, "target": "fake_target", "created": "2017-05-16T13:56:54.957Z", "completed": "2017-05-16T13:56:54.957Z", "word_count": 10, "character_count": 15}""" +fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "filename": "fake_filename", "status": "fake_status", "model_id": "fake_model_id", "base_model_id": "fake_base_model_id", "source": "fake_source", "detected_language_confidence": 28, "target": "fake_target", "created": "2017-05-16T13:56:54.957Z", "completed": "2017-05-16T13:56:54.957Z", "word_count": 10, "character_count": 15}""" fake_response_BinaryIO_json = """Contents of response byte-stream...""" diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index 105fe8264..3c142ef6c 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -30,7 +30,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for classify #----------------------------------------------------------------------------- @@ -76,14 +75,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(),) + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.classify(**body) return output @@ -91,17 +91,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['classifier_id'] = "string1" - body.update({ - "text": "string1", - }) + body.update({"text": "string1", }) return body def construct_required_body(self): body = dict() body['classifier_id'] = "string1" - body.update({ - "text": "string1", - }) + body.update({"text": "string1", }) return body @@ -136,8 +132,7 @@ def test_classify_collection_required_response(self): #-------------------------------------------------------- @responses.activate def test_classify_collection_empty(self): - check_empty_required_params( - self, fake_response_ClassificationCollection_json) + check_empty_required_params(self, fake_response_ClassificationCollection_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -145,21 +140,21 @@ def test_classify_collection_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/classifiers/{0}/classify_collection'.format( - body['classifier_id']) + endpoint = '/v1/classifiers/{0}/classify_collection'.format(body['classifier_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(),) + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.classify_collection(**body) return output @@ -167,17 +162,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['classifier_id'] = "string1" - body.update({ - "collection": [], - }) + body.update({"collection": [], }) return body def construct_required_body(self): body = dict() body['classifier_id'] = "string1" - body.update({ - "collection": [], - }) + body.update({"collection": [], }) return body @@ -191,7 +182,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_classifier #----------------------------------------------------------------------------- @@ -237,14 +227,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(),) + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.create_classifier(**body) return output @@ -306,14 +297,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(),) + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.list_classifiers(**body) return output @@ -372,14 +364,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(),) + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_classifier(**body) return output @@ -440,14 +433,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(),) + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_classifier(**body) return output @@ -485,7 +479,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -502,7 +495,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -514,7 +506,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -531,7 +522,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 18f6b0a08..0857daea3 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -29,7 +29,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for analyze #----------------------------------------------------------------------------- @@ -75,76 +74,28 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = NaturalLanguageUnderstandingV1( authenticator=NoAuthAuthenticator(), version='2019-07-12', - ) + ) service.set_service_url(base_url) output = service.analyze(**body) return output def construct_full_body(self): body = dict() - body.update({ - "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, "model": "fake_model"}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""" - )), - "text": - "string1", - "html": - "string1", - "url": - "string1", - "clean": - True, - "xpath": - "string1", - "fallback_to_raw": - True, - "return_analyzed_text": - True, - "language": - "string1", - "limit_text_characters": - 12345, - }) + body.update({"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, "model": "fake_model"}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""")), "text": "string1", "html": "string1", "url": "string1", "clean": True, "xpath": "string1", "fallback_to_raw": True, "return_analyzed_text": True, "language": "string1", "limit_text_characters": 12345, }) return body def construct_required_body(self): body = dict() - body.update({ - "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, "model": "fake_model"}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""" - )), - "text": - "string1", - "html": - "string1", - "url": - "string1", - "clean": - True, - "xpath": - "string1", - "fallback_to_raw": - True, - "return_analyzed_text": - True, - "language": - "string1", - "limit_text_characters": - 12345, - }) + body.update({"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, "model": "fake_model"}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""")), "text": "string1", "html": "string1", "url": "string1", "clean": True, "xpath": "string1", "fallback_to_raw": True, "return_analyzed_text": True, "language": "string1", "limit_text_characters": 12345, }) return body @@ -158,7 +109,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_models #----------------------------------------------------------------------------- @@ -203,16 +153,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = NaturalLanguageUnderstandingV1( authenticator=NoAuthAuthenticator(), version='2019-07-12', - ) + ) service.set_service_url(base_url) output = service.list_models(**body) return output @@ -271,16 +221,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = NaturalLanguageUnderstandingV1( authenticator=NoAuthAuthenticator(), version='2019-07-12', - ) + ) service.set_service_url(base_url) output = service.delete_model(**body) return output @@ -318,7 +268,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -335,7 +284,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -347,7 +295,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -364,7 +311,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index 22cab9e9f..fe646402f 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -28,7 +28,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for profile #----------------------------------------------------------------------------- @@ -74,16 +73,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = PersonalityInsightsV3( authenticator=NoAuthAuthenticator(), version='2017-10-13', - ) + ) service.set_service_url(base_url) output = service.profile(**body) return output @@ -129,7 +128,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -146,7 +144,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -158,7 +155,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -175,7 +171,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 1cb6cf5b3..8b8aff3e2 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -29,7 +29,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_models #----------------------------------------------------------------------------- @@ -74,13 +73,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.list_models(**body) return output @@ -139,13 +140,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_model(**body) return output @@ -171,7 +174,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for recognize #----------------------------------------------------------------------------- @@ -203,8 +205,7 @@ def test_recognize_required_response(self): #-------------------------------------------------------- @responses.activate def test_recognize_empty(self): - check_empty_required_params( - self, fake_response_SpeechRecognitionResults_json) + check_empty_required_params(self, fake_response_SpeechRecognitionResults_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -218,13 +219,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.recognize(**body) return output @@ -254,6 +257,8 @@ def construct_full_body(self): body['audio_metrics'] = True body['end_of_phrase_silence_time'] = 12345.0 body['split_transcript_at_phrase_end'] = True + body['speech_detector_sensitivity'] = 12345.0 + body['background_audio_suppression'] = 12345.0 return body def construct_required_body(self): @@ -272,7 +277,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for register_callback #----------------------------------------------------------------------------- @@ -318,13 +322,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.register_callback(**body) return output @@ -386,13 +392,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.unregister_callback(**body) return output @@ -453,13 +461,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.create_job(**body) return output @@ -495,6 +505,8 @@ def construct_full_body(self): body['audio_metrics'] = True body['end_of_phrase_silence_time'] = 12345.0 body['split_transcript_at_phrase_end'] = True + body['speech_detector_sensitivity'] = 12345.0 + body['background_audio_suppression'] = 12345.0 return body def construct_required_body(self): @@ -547,13 +559,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.check_jobs(**body) return output @@ -612,13 +626,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.check_job(**body) return output @@ -679,13 +695,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_job(**body) return output @@ -711,7 +729,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_language_model #----------------------------------------------------------------------------- @@ -757,35 +774,27 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.create_language_model(**body) return output def construct_full_body(self): body = dict() - body.update({ - "name": "string1", - "base_model_name": "string1", - "dialect": "string1", - "description": "string1", - }) + body.update({"name": "string1", "base_model_name": "string1", "dialect": "string1", "description": "string1", }) return body def construct_required_body(self): body = dict() - body.update({ - "name": "string1", - "base_model_name": "string1", - "dialect": "string1", - "description": "string1", - }) + body.update({"name": "string1", "base_model_name": "string1", "dialect": "string1", "description": "string1", }) return body @@ -833,13 +842,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.list_language_models(**body) return output @@ -899,13 +910,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_language_model(**body) return output @@ -966,13 +979,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_language_model(**body) return output @@ -1027,20 +1042,21 @@ def test_train_language_model_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/train'.format( - body['customization_id']) + endpoint = '/v1/customizations/{0}/train'.format(body['customization_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.train_language_model(**body) return output @@ -1097,20 +1113,21 @@ def test_reset_language_model_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/reset'.format( - body['customization_id']) + endpoint = '/v1/customizations/{0}/reset'.format(body['customization_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.reset_language_model(**body) return output @@ -1165,20 +1182,21 @@ def test_upgrade_language_model_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/upgrade_model'.format( - body['customization_id']) + endpoint = '/v1/customizations/{0}/upgrade_model'.format(body['customization_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.upgrade_language_model(**body) return output @@ -1204,7 +1222,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_corpora #----------------------------------------------------------------------------- @@ -1244,20 +1261,21 @@ def test_list_corpora_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/corpora'.format( - body['customization_id']) + endpoint = '/v1/customizations/{0}/corpora'.format(body['customization_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.list_corpora(**body) return output @@ -1312,20 +1330,21 @@ def test_add_corpus_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/corpora/{1}'.format( - body['customization_id'], body['corpus_name']) + endpoint = '/v1/customizations/{0}/corpora/{1}'.format(body['customization_id'], body['corpus_name']) 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=201, - content_type='') - + url, + body=json.dumps(response), + status=201, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.add_corpus(**body) return output @@ -1385,20 +1404,21 @@ def test_get_corpus_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/corpora/{1}'.format( - body['customization_id'], body['corpus_name']) + endpoint = '/v1/customizations/{0}/corpora/{1}'.format(body['customization_id'], body['corpus_name']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_corpus(**body) return output @@ -1455,20 +1475,21 @@ def test_delete_corpus_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/corpora/{1}'.format( - body['customization_id'], body['corpus_name']) + endpoint = '/v1/customizations/{0}/corpora/{1}'.format(body['customization_id'], body['corpus_name']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_corpus(**body) return output @@ -1496,7 +1517,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_words #----------------------------------------------------------------------------- @@ -1536,20 +1556,21 @@ def test_list_words_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/words'.format( - body['customization_id']) + endpoint = '/v1/customizations/{0}/words'.format(body['customization_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.list_words(**body) return output @@ -1606,20 +1627,21 @@ def test_add_words_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/words'.format( - body['customization_id']) + endpoint = '/v1/customizations/{0}/words'.format(body['customization_id']) 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=201, - content_type='') - + url, + body=json.dumps(response), + status=201, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.add_words(**body) return output @@ -1627,17 +1649,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['customization_id'] = "string1" - body.update({ - "words": [], - }) + body.update({"words": [], }) return body def construct_required_body(self): body = dict() body['customization_id'] = "string1" - body.update({ - "words": [], - }) + body.update({"words": [], }) return body @@ -1680,20 +1698,21 @@ def test_add_word_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/words/{1}'.format( - body['customization_id'], body['word_name']) + endpoint = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word_name']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=201, - content_type='') - + url, + body=json.dumps(response), + status=201, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.add_word(**body) return output @@ -1702,22 +1721,14 @@ def construct_full_body(self): body = dict() body['customization_id'] = "string1" body['word_name'] = "string1" - body.update({ - "word": "string1", - "sounds_like": [], - "display_as": "string1", - }) + body.update({"word": "string1", "sounds_like": [], "display_as": "string1", }) return body def construct_required_body(self): body = dict() body['customization_id'] = "string1" body['word_name'] = "string1" - body.update({ - "word": "string1", - "sounds_like": [], - "display_as": "string1", - }) + body.update({"word": "string1", "sounds_like": [], "display_as": "string1", }) return body @@ -1760,20 +1771,21 @@ def test_get_word_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/words/{1}'.format( - body['customization_id'], body['word_name']) + endpoint = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word_name']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_word(**body) return output @@ -1830,20 +1842,21 @@ def test_delete_word_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/words/{1}'.format( - body['customization_id'], body['word_name']) + endpoint = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word_name']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_word(**body) return output @@ -1871,7 +1884,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_grammars #----------------------------------------------------------------------------- @@ -1911,20 +1923,21 @@ def test_list_grammars_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/grammars'.format( - body['customization_id']) + endpoint = '/v1/customizations/{0}/grammars'.format(body['customization_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.list_grammars(**body) return output @@ -1979,20 +1992,21 @@ def test_add_grammar_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/grammars/{1}'.format( - body['customization_id'], body['grammar_name']) + endpoint = '/v1/customizations/{0}/grammars/{1}'.format(body['customization_id'], body['grammar_name']) 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=201, - content_type='') - + url, + body=json.dumps(response), + status=201, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.add_grammar(**body) return output @@ -2054,20 +2068,21 @@ def test_get_grammar_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/grammars/{1}'.format( - body['customization_id'], body['grammar_name']) + endpoint = '/v1/customizations/{0}/grammars/{1}'.format(body['customization_id'], body['grammar_name']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_grammar(**body) return output @@ -2124,20 +2139,21 @@ def test_delete_grammar_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/grammars/{1}'.format( - body['customization_id'], body['grammar_name']) + endpoint = '/v1/customizations/{0}/grammars/{1}'.format(body['customization_id'], body['grammar_name']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_grammar(**body) return output @@ -2165,7 +2181,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_acoustic_model #----------------------------------------------------------------------------- @@ -2211,33 +2226,27 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.create_acoustic_model(**body) return output def construct_full_body(self): body = dict() - body.update({ - "name": "string1", - "base_model_name": "string1", - "description": "string1", - }) + body.update({"name": "string1", "base_model_name": "string1", "description": "string1", }) return body def construct_required_body(self): body = dict() - body.update({ - "name": "string1", - "base_model_name": "string1", - "description": "string1", - }) + body.update({"name": "string1", "base_model_name": "string1", "description": "string1", }) return body @@ -2285,13 +2294,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.list_acoustic_models(**body) return output @@ -2345,20 +2356,21 @@ def test_get_acoustic_model_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}'.format( - body['customization_id']) + endpoint = '/v1/acoustic_customizations/{0}'.format(body['customization_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_acoustic_model(**body) return output @@ -2413,20 +2425,21 @@ def test_delete_acoustic_model_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}'.format( - body['customization_id']) + endpoint = '/v1/acoustic_customizations/{0}'.format(body['customization_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_acoustic_model(**body) return output @@ -2481,20 +2494,21 @@ def test_train_acoustic_model_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/train'.format( - body['customization_id']) + endpoint = '/v1/acoustic_customizations/{0}/train'.format(body['customization_id']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.train_acoustic_model(**body) return output @@ -2550,20 +2564,21 @@ def test_reset_acoustic_model_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/reset'.format( - body['customization_id']) + endpoint = '/v1/acoustic_customizations/{0}/reset'.format(body['customization_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.reset_acoustic_model(**body) return output @@ -2618,20 +2633,21 @@ def test_upgrade_acoustic_model_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/upgrade_model'.format( - body['customization_id']) + endpoint = '/v1/acoustic_customizations/{0}/upgrade_model'.format(body['customization_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.upgrade_acoustic_model(**body) return output @@ -2659,7 +2675,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_audio #----------------------------------------------------------------------------- @@ -2699,20 +2714,21 @@ def test_list_audio_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/audio'.format( - body['customization_id']) + endpoint = '/v1/acoustic_customizations/{0}/audio'.format(body['customization_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.list_audio(**body) return output @@ -2767,20 +2783,21 @@ def test_add_audio_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format( - body['customization_id'], body['audio_name']) + endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format(body['customization_id'], body['audio_name']) 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=201, - content_type='') - + url, + body=json.dumps(response), + status=201, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.add_audio(**body) return output @@ -2842,20 +2859,21 @@ def test_get_audio_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format( - body['customization_id'], body['audio_name']) + endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format(body['customization_id'], body['audio_name']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_audio(**body) return output @@ -2912,20 +2930,21 @@ def test_delete_audio_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format( - body['customization_id'], body['audio_name']) + endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format(body['customization_id'], body['audio_name']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_audio(**body) return output @@ -2953,7 +2972,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for delete_user_data #----------------------------------------------------------------------------- @@ -2999,13 +3017,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = SpeechToTextV1(authenticator=NoAuthAuthenticator(),) + service = SpeechToTextV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output @@ -3043,7 +3063,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -3060,7 +3079,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -3072,7 +3090,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -3089,7 +3106,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 90225cdbb..b9b89e2a7 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -28,7 +28,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_voices #----------------------------------------------------------------------------- @@ -73,13 +72,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.list_voices(**body) return output @@ -138,13 +139,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_voice(**body) return output @@ -171,7 +174,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for synthesize #----------------------------------------------------------------------------- @@ -217,22 +219,22 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.synthesize(**body) return output def construct_full_body(self): body = dict() - body.update({ - "text": "string1", - }) + body.update({"text": "string1", }) body['accept'] = "string1" body['voice'] = "string1" body['customization_id'] = "string1" @@ -240,9 +242,7 @@ def construct_full_body(self): def construct_required_body(self): body = dict() - body.update({ - "text": "string1", - }) + body.update({"text": "string1", }) return body @@ -256,7 +256,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for get_pronunciation #----------------------------------------------------------------------------- @@ -302,13 +301,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_pronunciation(**body) return output @@ -337,7 +338,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_voice_model #----------------------------------------------------------------------------- @@ -383,33 +383,27 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - + url, + body=json.dumps(response), + status=201, + content_type='application/json') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.create_voice_model(**body) return output def construct_full_body(self): body = dict() - body.update({ - "name": "string1", - "language": "string1", - "description": "string1", - }) + body.update({"name": "string1", "language": "string1", "description": "string1", }) return body def construct_required_body(self): body = dict() - body.update({ - "name": "string1", - "language": "string1", - "description": "string1", - }) + body.update({"name": "string1", "language": "string1", "description": "string1", }) return body @@ -457,13 +451,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.list_voice_models(**body) return output @@ -523,13 +519,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.update_voice_model(**body) return output @@ -537,21 +535,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['customization_id'] = "string1" - body.update({ - "name": "string1", - "description": "string1", - "words": [], - }) + body.update({"name": "string1", "description": "string1", "words": [], }) return body def construct_required_body(self): body = dict() body['customization_id'] = "string1" - body.update({ - "name": "string1", - "description": "string1", - "words": [], - }) + body.update({"name": "string1", "description": "string1", "words": [], }) return body @@ -600,13 +590,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_voice_model(**body) return output @@ -667,13 +659,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_voice_model(**body) return output @@ -699,7 +693,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for add_words #----------------------------------------------------------------------------- @@ -739,20 +732,21 @@ def test_add_words_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/words'.format( - body['customization_id']) + endpoint = '/v1/customizations/{0}/words'.format(body['customization_id']) 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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.add_words(**body) return output @@ -760,17 +754,13 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['customization_id'] = "string1" - body.update({ - "words": [], - }) + body.update({"words": [], }) return body def construct_required_body(self): body = dict() body['customization_id'] = "string1" - body.update({ - "words": [], - }) + body.update({"words": [], }) return body @@ -813,20 +803,21 @@ def test_list_words_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/words'.format( - body['customization_id']) + endpoint = '/v1/customizations/{0}/words'.format(body['customization_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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.list_words(**body) return output @@ -881,20 +872,21 @@ def test_add_word_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/words/{1}'.format( - body['customization_id'], body['word']) + endpoint = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word']) url = '{0}{1}'.format(base_url, endpoint) return url def add_mock_response(self, url, response): responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.add_word(**body) return output @@ -903,20 +895,14 @@ def construct_full_body(self): body = dict() body['customization_id'] = "string1" body['word'] = "string1" - body.update({ - "translation": "string1", - "part_of_speech": "string1", - }) + body.update({"translation": "string1", "part_of_speech": "string1", }) return body def construct_required_body(self): body = dict() body['customization_id'] = "string1" body['word'] = "string1" - body.update({ - "translation": "string1", - "part_of_speech": "string1", - }) + body.update({"translation": "string1", "part_of_speech": "string1", }) return body @@ -959,20 +945,21 @@ def test_get_word_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/words/{1}'.format( - body['customization_id'], body['word']) + endpoint = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word']) 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') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.get_word(**body) return output @@ -1029,20 +1016,21 @@ def test_delete_word_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v1/customizations/{0}/words/{1}'.format( - body['customization_id'], body['word']) + endpoint = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word']) 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=204, - content_type='') - + url, + body=json.dumps(response), + status=204, + content_type='') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_word(**body) return output @@ -1070,7 +1058,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for delete_user_data #----------------------------------------------------------------------------- @@ -1116,13 +1103,15 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): - service = TextToSpeechV1(authenticator=NoAuthAuthenticator(),) + service = TextToSpeechV1( + authenticator=NoAuthAuthenticator(), + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output @@ -1160,7 +1149,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -1177,7 +1165,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -1189,7 +1176,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -1206,7 +1192,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index d9db2185d..f9e5a577e 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -28,7 +28,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for tone #----------------------------------------------------------------------------- @@ -74,16 +73,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = ToneAnalyzerV3( authenticator=NoAuthAuthenticator(), version='2017-09-21', - ) + ) service.set_service_url(base_url) output = service.tone(**body) return output @@ -149,34 +148,30 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = ToneAnalyzerV3( authenticator=NoAuthAuthenticator(), version='2017-09-21', - ) + ) service.set_service_url(base_url) output = service.tone_chat(**body) return output def construct_full_body(self): body = dict() - body.update({ - "utterances": [], - }) + body.update({"utterances": [], }) body['content_language'] = "string1" body['accept_language'] = "string1" return body def construct_required_body(self): body = dict() - body.update({ - "utterances": [], - }) + body.update({"utterances": [], }) return body @@ -202,7 +197,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -219,7 +213,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -231,7 +224,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -248,7 +240,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index fb2b7d779..a469b83c9 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -30,7 +30,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for classify #----------------------------------------------------------------------------- @@ -75,16 +74,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = VisualRecognitionV3( authenticator=NoAuthAuthenticator(), version='2018-03-19', - ) + ) service.set_service_url(base_url) output = service.classify(**body) return output @@ -116,7 +115,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_classifier #----------------------------------------------------------------------------- @@ -162,16 +160,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = VisualRecognitionV3( authenticator=NoAuthAuthenticator(), version='2018-03-19', - ) + ) service.set_service_url(base_url) output = service.create_classifier(**body) return output @@ -235,16 +233,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = VisualRecognitionV3( authenticator=NoAuthAuthenticator(), version='2018-03-19', - ) + ) service.set_service_url(base_url) output = service.list_classifiers(**body) return output @@ -304,16 +302,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = VisualRecognitionV3( authenticator=NoAuthAuthenticator(), version='2018-03-19', - ) + ) service.set_service_url(base_url) output = service.get_classifier(**body) return output @@ -374,16 +372,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + url, + body=json.dumps(response), + status=200, + content_type='application/json') + def call_service(self, body): service = VisualRecognitionV3( authenticator=NoAuthAuthenticator(), version='2018-03-19', - ) + ) service.set_service_url(base_url) output = service.update_classifier(**body) return output @@ -447,16 +445,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = VisualRecognitionV3( authenticator=NoAuthAuthenticator(), version='2018-03-19', - ) + ) service.set_service_url(base_url) output = service.delete_classifier(**body) return output @@ -482,7 +480,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for get_core_ml_model #----------------------------------------------------------------------------- @@ -522,23 +519,22 @@ def test_get_core_ml_model_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v3/classifiers/{0}/core_ml_model'.format( - body['classifier_id']) + endpoint = '/v3/classifiers/{0}/core_ml_model'.format(body['classifier_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='') - + url, + body=json.dumps(response), + status=200, + content_type='') + def call_service(self, body): service = VisualRecognitionV3( authenticator=NoAuthAuthenticator(), version='2018-03-19', - ) + ) service.set_service_url(base_url) output = service.get_core_ml_model(**body) return output @@ -564,7 +560,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for delete_user_data #----------------------------------------------------------------------------- @@ -610,16 +605,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=202, - content_type='') - + url, + body=json.dumps(response), + status=202, + content_type='') + def call_service(self, body): service = VisualRecognitionV3( authenticator=NoAuthAuthenticator(), version='2018-03-19', - ) + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output @@ -657,7 +652,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -674,7 +668,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -686,7 +679,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -703,7 +695,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 99dc2df07..e1b9dbd56 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -30,7 +30,6 @@ ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for analyze #----------------------------------------------------------------------------- @@ -76,16 +75,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + 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.analyze(**body) return output @@ -116,7 +115,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for create_collection #----------------------------------------------------------------------------- @@ -161,34 +159,28 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + 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.create_collection(**body) return output def construct_full_body(self): body = dict() - body.update({ - "name": "string1", - "description": "string1", - }) + body.update({"name": "string1", "description": "string1", }) return body def construct_required_body(self): body = dict() - body.update({ - "name": "string1", - "description": "string1", - }) + body.update({"name": "string1", "description": "string1", }) return body @@ -236,16 +228,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + 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_collections(**body) return output @@ -304,16 +296,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + 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_collection(**body) return output @@ -374,16 +366,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + 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_collection(**body) return output @@ -391,10 +383,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['collection_id'] = "string1" - body.update({ - "name": "string1", - "description": "string1", - }) + body.update({"name": "string1", "description": "string1", }) return body def construct_required_body(self): @@ -448,16 +437,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - + 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_collection(**body) return output @@ -483,7 +472,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for add_images #----------------------------------------------------------------------------- @@ -529,16 +517,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + 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.add_images(**body) return output @@ -602,16 +590,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + 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_images(**body) return output @@ -666,23 +654,22 @@ def test_get_image_details_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v4/collections/{0}/images/{1}'.format( - body['collection_id'], body['image_id']) + endpoint = '/v4/collections/{0}/images/{1}'.format(body['collection_id'], body['image_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') - + 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_image_details(**body) return output @@ -739,23 +726,22 @@ def test_delete_image_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v4/collections/{0}/images/{1}'.format( - body['collection_id'], body['image_id']) + endpoint = '/v4/collections/{0}/images/{1}'.format(body['collection_id'], body['image_id']) 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='') - + 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_image(**body) return output @@ -812,23 +798,22 @@ def test_get_jpeg_image_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v4/collections/{0}/images/{1}/jpeg'.format( - body['collection_id'], body['image_id']) + endpoint = '/v4/collections/{0}/images/{1}/jpeg'.format(body['collection_id'], body['image_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='') - + 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.get_jpeg_image(**body) return output @@ -857,7 +842,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for list_object_metadata #----------------------------------------------------------------------------- @@ -903,16 +887,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + 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 @@ -959,8 +943,7 @@ def test_update_object_metadata_required_response(self): #-------------------------------------------------------- @responses.activate def test_update_object_metadata_empty(self): - check_empty_required_params(self, - fake_response_UpdateObjectMetadata_json) + check_empty_required_params(self, fake_response_UpdateObjectMetadata_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -968,23 +951,22 @@ def test_update_object_metadata_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v4/collections/{0}/objects/{1}'.format( - body['collection_id'], body['object']) + 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') - + 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 @@ -993,18 +975,14 @@ def construct_full_body(self): body = dict() body['collection_id'] = "string1" body['object'] = "string1" - body.update({ - "new_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", - }) + body.update({"new_object": "string1", }) return body @@ -1047,23 +1025,22 @@ def test_get_object_metadata_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v4/collections/{0}/objects/{1}'.format( - body['collection_id'], body['object']) + 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') - + 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 @@ -1120,23 +1097,22 @@ def test_delete_object_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v4/collections/{0}/objects/{1}'.format( - body['collection_id'], body['object']) + 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='') - + 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 @@ -1164,7 +1140,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for train #----------------------------------------------------------------------------- @@ -1210,16 +1185,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - + url, + body=json.dumps(response), + status=202, + 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.train(**body) return output @@ -1266,8 +1241,7 @@ def test_add_image_training_data_required_response(self): #-------------------------------------------------------- @responses.activate def test_add_image_training_data_empty(self): - check_empty_required_params(self, - fake_response_TrainingDataObjects_json) + check_empty_required_params(self, fake_response_TrainingDataObjects_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -1275,23 +1249,22 @@ def test_add_image_training_data_empty(self): #- Helpers - #----------- def make_url(self, body): - endpoint = '/v4/collections/{0}/images/{1}/training_data'.format( - body['collection_id'], body['image_id']) + endpoint = '/v4/collections/{0}/images/{1}/training_data'.format(body['collection_id'], body['image_id']) 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') - + 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.add_image_training_data(**body) return output @@ -1300,18 +1273,14 @@ def construct_full_body(self): body = dict() body['collection_id'] = "string1" body['image_id'] = "string1" - body.update({ - "objects": [], - }) + body.update({"objects": [], }) return body def construct_required_body(self): body = dict() body['collection_id'] = "string1" body['image_id'] = "string1" - body.update({ - "objects": [], - }) + body.update({"objects": [], }) return body @@ -1359,16 +1328,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - + 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_training_usage(**body) return output @@ -1394,7 +1363,6 @@ def construct_required_body(self): ############################################################################## # region - #----------------------------------------------------------------------------- # Test Class for delete_user_data #----------------------------------------------------------------------------- @@ -1440,16 +1408,16 @@ def make_url(self, body): def add_mock_response(self, url, response): responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=202, - content_type='') - + url, + body=json.dumps(response), + status=202, + content_type='') + def call_service(self, body): service = VisualRecognitionV4( authenticator=NoAuthAuthenticator(), version='2019-02-11', - ) + ) service.set_service_url(base_url) output = service.delete_user_data(**body) return output @@ -1487,7 +1455,6 @@ def check_empty_required_params(obj, response): error = True assert error - def check_missing_required_params(obj): """Test function to assert that the operation will throw an error when missing required data @@ -1504,7 +1471,6 @@ def check_missing_required_params(obj): error = True assert error - def check_empty_response(obj): """Test function to assert that the operation will return an empty response when given an empty request @@ -1516,7 +1482,6 @@ def check_empty_response(obj): url = obj.make_url(body) send_request(obj, {}, {}, url=url) - def send_request(obj, body, response, url=None): """Test function to create a request, send it, and assert its accuracy to the mock response @@ -1533,7 +1498,6 @@ def send_request(obj, body, response, url=None): assert responses.calls[0].request.url.startswith(url) assert output.get_result() == response - #################### ## Mock Responses ## #################### From 9df996837611f80ba8581eb640423ddcef10537c Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 16 Apr 2020 10:05:46 -0400 Subject: [PATCH 242/455] chore: update formatting and gitignore --- .gitignore | 3 +++ README.md | 4 ++-- .../assistant_tone_analyzer_integration/tone_detection.py | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 5d029b821..35ef69fba 100644 --- a/.gitignore +++ b/.gitignore @@ -69,3 +69,6 @@ test/__init__.py # ignore detect secrets files .pre-commit-config.yaml .secrets.baseline + +.openapi-generator-ignore +.openapi-generator/ \ No newline at end of file diff --git a/README.md b/README.md index 83c75e46e..cf620b72e 100755 --- a/README.md +++ b/README.md @@ -164,7 +164,7 @@ IBM Cloud has migrated to token-based Identity and Access Management (IAM) authe You supply either an IAM service **API key** or a **bearer token**: - Use the API key to have the SDK manage the lifecycle of the access token. The SDK requests an access token, ensures that the access token is valid, and refreshes it if necessary. -- Use the access token if you want to manage the lifecycle yourself. For details, see [Authenticating with IAM tokens](https://cloud.ibm.com/docs/services/watson?topic=watson-iam). +- Use the access token if you want to manage the lifecycle yourself. For details, see [Authenticating with IAM tokens](https://cloud.ibm.com/docs/watson?topic=watson-iam). - Use a server-side to generate access tokens using your IAM API key for untrusted environments like client-side scripts. The generated access tokens will be valid for one hour and can be refreshed. #### Supplying the API key @@ -513,5 +513,5 @@ This library is licensed under the [Apache 2.0 license][license]. [examples]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples [CONTRIBUTING]: https://github.com/watson-developer-cloud/python-sdk/blob/master/CONTRIBUTING.md [license]: http://www.apache.org/licenses/LICENSE-2.0 -[vcap_services]: https://cloud.ibm.com/docs/services/watson?topic=watson-vcapServices +[vcap_services]: https://cloud.ibm.com/docs/watson?topic=watson-vcapServices [ibm-cloud-onboarding]: https://cloud.ibm.com/registration?target=/developer/watson&cm_sp=WatsonPlatform-WatsonServices-_-OnPageNavLink-IBMWatson_SDKs-_-Python diff --git a/examples/assistant_tone_analyzer_integration/tone_detection.py b/examples/assistant_tone_analyzer_integration/tone_detection.py index dc8e36a01..d0f91fbdd 100644 --- a/examples/assistant_tone_analyzer_integration/tone_detection.py +++ b/examples/assistant_tone_analyzer_integration/tone_detection.py @@ -15,7 +15,7 @@ * Thresholds for identifying meaningful tones returned by the Watson Tone Analyzer. Current values are * based on the recommendations made by the Watson Tone Analyzer at - * https://cloud.ibm.com/docs/services/tone-analyzer?topic=tone-analyzer-utgpe + * https://cloud.ibm.com/docs/tone-analyzer?topic=tone-analyzer-utgpe * These thresholds can be adjusted to client/domain requirements. """ From a4311fb79906335742fa6d8d72ee84fc6007872c Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 16 Apr 2020 10:14:08 -0400 Subject: [PATCH 243/455] refactor: keep cout as required param --- ibm_watson/visual_recognition_v4.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 6711750cd..9f86c28d4 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -137,11 +137,10 @@ def analyze(self, params = {'version': self.version} form_data = [] - for item in collection_ids: - form_data.append( - ('collection_ids', (None, item, 'application/json'))) - for item in features: - form_data.append(('features', (None, item, 'application/json'))) + collection_ids = self._convert_list(collection_ids) + form_data.append(('collection_ids', (None, collection_ids, 'text/plain'))) + features = self._convert_list(features) + form_data.append(('features', (None, features, 'text/plain'))) if images_file: for item in images_file: form_data.append(('images_file', (item.filename, item.data, @@ -3144,18 +3143,18 @@ class UpdateObjectMetadata(): :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: (optional) Number of bounding boxes in the collection with the + :attr int count: Number of bounding boxes in the collection with the updated object name. """ - def __init__(self, object: str, *, count: int = None) -> None: + 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: (optional) Number of bounding boxes in the collection + :param int count: Number of bounding boxes in the collection with the updated object name. """ self.object = object @@ -3179,6 +3178,10 @@ def from_dict(cls, _dict: Dict) -> 'UpdateObjectMetadata': ) if 'count' in _dict: args['count'] = _dict.get('count') + else: + raise ValueError( + 'Required property \'count\' not present in UpdateObjectMetadata JSON' + ) return cls(**args) @classmethod From 46a812c6f74a9d32a96ad566e2d25d883c24d2f7 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 20 Apr 2020 10:25:12 -0400 Subject: [PATCH 244/455] feat(AssistantV2): regenerate based on current API def --- ibm_watson/assistant_v2.py | 96 ++----------------------- ibm_watson/speech_to_text_v1_adapter.py | 4 +- ibm_watson/visual_recognition_v3.py | 3 +- ibm_watson/visual_recognition_v4.py | 3 +- 4 files changed, 11 insertions(+), 95 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 9f0e1fbc2..addaea126 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1219,21 +1219,19 @@ class MessageContextSkill(): :attr dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. - :attr MessageContextSkillSystem system: (optional) System context data used by - the skill. + :attr dict system: (optional) System context data used by the skill. """ def __init__(self, *, user_defined: dict = None, - system: 'MessageContextSkillSystem' = None) -> None: + system: dict = None) -> None: """ Initialize a MessageContextSkill object. :param dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data - used by the skill. + :param dict system: (optional) System context data used by the skill. """ self.user_defined = user_defined self.system = system @@ -1251,8 +1249,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') if 'system' in _dict: - args['system'] = MessageContextSkillSystem._from_dict( - _dict.get('system')) + args['system'] = _dict.get('system') return cls(**args) @classmethod @@ -1266,7 +1263,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system._to_dict() + _dict['system'] = self.system return _dict def _to_dict(self): @@ -1288,89 +1285,6 @@ def __ne__(self, other: 'MessageContextSkill') -> bool: return not self == other -class MessageContextSkillSystem(): - """ - System context data used by the skill. - - :attr str state: (optional) An encoded string representing the current - conversation state. By saving this value and then sending it in the context of a - subsequent message request, you can restore the conversation to the same state. - This can be useful if you need to return to an earlier point in the conversation - or resume a paused conversation after the session has expired. - """ - - def __init__(self, *, state: str = None, **kwargs) -> None: - """ - Initialize a MessageContextSkillSystem object. - - :param str state: (optional) An encoded string representing the current - conversation state. By saving this value and then sending it in the context - of a subsequent message request, you can restore the conversation to the - same state. This can be useful if you need to return to an earlier point in - the conversation or resume a paused conversation after the session has - expired. - :param **kwargs: (optional) Any additional properties. - """ - self.state = state - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': - """Initialize a MessageContextSkillSystem object from a json dictionary.""" - args = {} - xtra = _dict.copy() - if 'state' in _dict: - args['state'] = _dict.get('state') - del xtra['state'] - args.update(xtra) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MessageContextSkillSystem 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, 'state') and self.state is not None: - _dict['state'] = self.state - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __setattr__(self, name: str, value: object) -> None: - properties = {'state'} - if not hasattr(self, '_additionalProperties'): - super(MessageContextSkillSystem, - self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(MessageContextSkillSystem, self).__setattr__(name, value) - - def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillSystem object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other: 'MessageContextSkillSystem') -> 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: 'MessageContextSkillSystem') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class MessageContextSkills(): """ Information specific to particular skills used by the Assistant. diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 22a565c79..11bd2d38d 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -53,8 +53,8 @@ def recognize_using_websocket(self, audio_metrics=None, end_of_phrase_silence_time=None, split_transcript_at_phrase_end=None, - speech_detector_sensitivity = None, - background_audio_suppression = None, + speech_detector_sensitivity=None, + background_audio_suppression=None, **kwargs): """ Sends audio for speech recognition using web sockets. diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 524daef6b..efef3065a 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -170,7 +170,8 @@ def classify(self, form_data.append(('owners', (None, owners, 'text/plain'))) if classifier_ids: classifier_ids = self._convert_list(classifier_ids) - form_data.append(('classifier_ids', (None, classifier_ids, 'text/plain'))) + form_data.append( + ('classifier_ids', (None, classifier_ids, 'text/plain'))) url = '/v3/classify' request = self.prepare_request(method='POST', diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 9f86c28d4..c7c66bdf4 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -138,7 +138,8 @@ def analyze(self, form_data = [] collection_ids = self._convert_list(collection_ids) - form_data.append(('collection_ids', (None, collection_ids, 'text/plain'))) + form_data.append( + ('collection_ids', (None, collection_ids, 'text/plain'))) features = self._convert_list(features) form_data.append(('features', (None, features, 'text/plain'))) if images_file: From 3a40b82f5a04af187a5243480db98b382fe954a0 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 24 Apr 2020 13:21:00 +0000 Subject: [PATCH 245/455] =?UTF-8?q?Bump=20version:=204.3.0=20=E2=86=92=204?= =?UTF-8?q?.4.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index a12707dfe..efca55923 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.3.0 +current_version = 4.4.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 5ee6158c5..26a6c390a 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.3.0' +__version__ = '4.4.0' diff --git a/setup.py b/setup.py index 7f93f020b..23bbfcc98 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.3.0' +__version__ = '4.4.0' if sys.argv[-1] == 'publish': From 9c81b37717249c52e3ad210433108e771aefe18c Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 24 Apr 2020 13:21:00 +0000 Subject: [PATCH 246/455] chore(release): 4.4.0 release notes # [4.4.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.3.0...v4.4.0) (2020-04-24) ### Features * **AssistantV2:** regenerate based on current API def ([46a812c](https://github.com/watson-developer-cloud/python-sdk/commit/46a812c6f74a9d32a96ad566e2d25d883c24d2f7)) * regenerate services using current API def ([e9ea20c](https://github.com/watson-developer-cloud/python-sdk/commit/e9ea20cc68a09da4e948c0622e254c31b27b481b)) * **LanguageTranslator:** add support for auto correct ([230878a](https://github.com/watson-developer-cloud/python-sdk/commit/230878a256d375c92cef0647e2f5efa51b8a5cf0)) * **SpeechToText:** add support for speech_detector_sensitivity and background_audio_suppression in ([9aa13e9](https://github.com/watson-developer-cloud/python-sdk/commit/9aa13e94558c37ca815d61ff36d0988943c55bf7)) --- CHANGELOG.md | 10 ++ package-lock.json | 267 +++++++++++++++++++++++----------------------- 2 files changed, 143 insertions(+), 134 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a5dd5bb13..3db80b5cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,13 @@ +# [4.4.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.3.0...v4.4.0) (2020-04-24) + + +### Features + +* **AssistantV2:** regenerate based on current API def ([46a812c](https://github.com/watson-developer-cloud/python-sdk/commit/46a812c6f74a9d32a96ad566e2d25d883c24d2f7)) +* regenerate services using current API def ([e9ea20c](https://github.com/watson-developer-cloud/python-sdk/commit/e9ea20cc68a09da4e948c0622e254c31b27b481b)) +* **LanguageTranslator:** add support for auto correct ([230878a](https://github.com/watson-developer-cloud/python-sdk/commit/230878a256d375c92cef0647e2f5efa51b8a5cf0)) +* **SpeechToText:** add support for speech_detector_sensitivity and background_audio_suppression in ([9aa13e9](https://github.com/watson-developer-cloud/python-sdk/commit/9aa13e94558c37ca815d61ff36d0988943c55bf7)) + # [4.3.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.2.1...v4.3.0) (2020-02-13) diff --git a/package-lock.json b/package-lock.json index ee51a62e1..c151f747d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,13 +10,18 @@ "@babel/highlight": "^7.8.3" } }, + "@babel/helper-validator-identifier": { + "version": "7.9.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.9.5.tgz", + "integrity": "sha512-/8arLKUFq882w4tWGj9JYzRpAlZgiWUJ+dtteNTDqrRBz9Iguck9Rn3ykuBDoUwh2TO4tSAJlrxDUOXWklJe4g==" + }, "@babel/highlight": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.8.3.tgz", - "integrity": "sha512-PX4y5xQUvy0fnEVHrYOarRPXVWafSjTW9T0Hab8gVIawpl2Sj0ORyrygANq+KjcNlSSTw0YCLSNA8OyZ1I4yEg==", + "version": "7.9.0", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.9.0.tgz", + "integrity": "sha512-lJZPilxX7Op3Nv/2cvFdnlepPXDxi29wxteT57Q965oc5R9v86ztx0jfxVrTcBk8C2kcPkkDa2Z4T3ZsPPVWsQ==", "requires": { + "@babel/helper-validator-identifier": "^7.9.0", "chalk": "^2.0.0", - "esutils": "^2.0.2", "js-tokens": "^4.0.0" } }, @@ -51,22 +56,55 @@ "@octokit/types": "^2.0.0" } }, - "@octokit/endpoint": { - "version": "5.5.2", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-5.5.2.tgz", - "integrity": "sha512-ICDcRA0C2vtTZZGud1nXRrBLXZqFayodXAKZfo3dkdcLNqcHsgaz3YSTupbURusYeucSVRjjG+RTcQhx6HPPcg==", + "@octokit/core": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-2.5.0.tgz", + "integrity": "sha512-uvzmkemQrBgD8xuGbjhxzJN1darJk9L2cS+M99cHrDG2jlSVpxNJVhoV86cXdYBqdHCc9Z995uLCczaaHIYA6Q==", "requires": { + "@octokit/auth-token": "^2.4.0", + "@octokit/graphql": "^4.3.1", + "@octokit/request": "^5.4.0", "@octokit/types": "^2.0.0", + "before-after-hook": "^2.1.0", + "universal-user-agent": "^5.0.0" + } + }, + "@octokit/endpoint": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.1.tgz", + "integrity": "sha512-pOPHaSz57SFT/m3R5P8MUu4wLPszokn5pXcB/pzavLTQf2jbU+6iayTvzaY6/BiotuRS0qyEUkx3QglT4U958A==", + "requires": { + "@octokit/types": "^2.11.1", "is-plain-object": "^3.0.0", + "universal-user-agent": "^5.0.0" + } + }, + "@octokit/graphql": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.3.1.tgz", + "integrity": "sha512-hCdTjfvrK+ilU2keAdqNBWOk+gm1kai1ZcdjRfB30oA3/T6n53UVJb7w0L5cR3/rhU91xT3HSqCd+qbvH06yxA==", + "requires": { + "@octokit/request": "^5.3.0", + "@octokit/types": "^2.0.0", "universal-user-agent": "^4.0.0" + }, + "dependencies": { + "universal-user-agent": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-4.0.1.tgz", + "integrity": "sha512-LnST3ebHwVL2aNe4mejI9IQh2HfZ1RLo8Io2HugSif8ekzD1TlWpHpColOB/eh8JHMLkGH3Akqf040I+4ylNxg==", + "requires": { + "os-name": "^3.1.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==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.2.0.tgz", + "integrity": "sha512-KoNxC3PLNar8UJwR+1VMQOw2IoOrrFdo5YOiDKnBhpVbKpw+zkBKNMNKwM44UWL25Vkn0Sl3nYIEGKY+gW5ebw==", "requires": { - "@octokit/types": "^2.0.1" + "@octokit/types": "^2.12.1" } }, "@octokit/plugin-request-log": { @@ -75,33 +113,33 @@ "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==", + "version": "3.8.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-3.8.0.tgz", + "integrity": "sha512-LUkTgZ53adPFC/Hw6mxvAtShUtGy3zbpcfCAJMWAN7SvsStV4p6TK7TocSv0Aak4TNmDLhbShTagGhpgz9mhYw==", "requires": { - "@octokit/types": "^2.0.1", + "@octokit/types": "^2.12.1", "deprecation": "^2.3.1" } }, "@octokit/request": { - "version": "5.3.1", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.3.1.tgz", - "integrity": "sha512-5/X0AL1ZgoU32fAepTfEoggFinO3rxsMLtzhlUX+RctLrusn/CApJuGFCd0v7GMFhF+8UiCsTTfsu7Fh1HnEJg==", + "version": "5.4.2", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.2.tgz", + "integrity": "sha512-zKdnGuQ2TQ2vFk9VU8awFT4+EYf92Z/v3OlzRaSh4RIP0H6cvW1BFPXq4XYvNez+TPQjqN+0uSkCYnMFFhcFrw==", "requires": { - "@octokit/endpoint": "^5.5.0", - "@octokit/request-error": "^1.0.1", - "@octokit/types": "^2.0.0", + "@octokit/endpoint": "^6.0.1", + "@octokit/request-error": "^2.0.0", + "@octokit/types": "^2.11.1", "deprecation": "^2.0.0", "is-plain-object": "^3.0.0", "node-fetch": "^2.3.0", "once": "^1.4.0", - "universal-user-agent": "^4.0.0" + "universal-user-agent": "^5.0.0" } }, "@octokit/request-error": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-1.2.1.tgz", - "integrity": "sha512-+6yDyk1EES6WK+l3viRDElw96MvwfJxCt45GvmjDUKWjYIb3PJZQkq3i46TwGwoPD4h8NmTrENmtyA1FwbmhRA==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.0.tgz", + "integrity": "sha512-rtYicB4Absc60rUv74Rjpzek84UbVHGHJRu4fNVlZ1mCcyUPPuzFfG9Rn6sjHrd95DEsmjSt1Axlc699ZlbDkw==", "requires": { "@octokit/types": "^2.0.0", "deprecation": "^2.0.0", @@ -109,44 +147,32 @@ } }, "@octokit/rest": { - "version": "16.43.1", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-16.43.1.tgz", - "integrity": "sha512-gfFKwRT/wFxq5qlNjnW2dh+qh74XgTQ2B179UX5K1HYCluioWj8Ndbgqw2PVqa1NnVJkGHp2ovMpVn/DImlmkw==", + "version": "17.6.0", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-17.6.0.tgz", + "integrity": "sha512-knh+4hPBA26AMXflFRupTPT3u9NcQmQzeBJl4Gcuf14Gn7dUh6Loc1ICWF0Pz18A6ElFZQt+wB9tFINSruIa+g==", "requires": { - "@octokit/auth-token": "^2.4.0", - "@octokit/plugin-paginate-rest": "^1.1.1", + "@octokit/core": "^2.4.3", + "@octokit/plugin-paginate-rest": "^2.2.0", "@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", - "before-after-hook": "^2.0.0", - "btoa-lite": "^1.0.0", - "deprecation": "^2.0.0", - "lodash.get": "^4.4.2", - "lodash.set": "^4.3.2", - "lodash.uniq": "^4.5.0", - "octokit-pagination-methods": "^1.1.0", - "once": "^1.4.0", - "universal-user-agent": "^4.0.0" + "@octokit/plugin-rest-endpoint-methods": "3.8.0" } }, "@octokit/types": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-2.1.1.tgz", - "integrity": "sha512-89LOYH+d/vsbDX785NOfLxTW88GjNd0lWRz1DVPVsZgg9Yett5O+3MOvwo7iHgvUwbFz0mf/yPIjBkUbs4kxoQ==", + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-2.12.1.tgz", + "integrity": "sha512-LRLR1tjbcCfAmUElvTmMvLEzstpx6Xt/aQVTg2xvd+kHA2Ekp1eWl5t+gU7bcwjXHYEAzh4hH4WH+kS3vh+wRw==", "requires": { "@types/node": ">= 8" } }, "@semantic-release/changelog": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@semantic-release/changelog/-/changelog-5.0.0.tgz", - "integrity": "sha512-A1uKqWtQG4WX9Vh4QI5b2ddhqx1qAJFlbow8szSNiXn+TaJg15LSUA9NVqyu0VxQFy3hKUJYwbBHGRXCxCy2fg==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/@semantic-release/changelog/-/changelog-5.0.1.tgz", + "integrity": "sha512-unvqHo5jk4dvAf2nZ3aw4imrlwQ2I50eVVvq9D47Qc3R+keNqepx1vDYwkjF8guFXnOYaYcR28yrZWno1hFbiw==", "requires": { "@semantic-release/error": "^2.1.0", "aggregate-error": "^3.0.0", - "fs-extra": "^8.0.0", + "fs-extra": "^9.0.0", "lodash": "^4.17.4" } }, @@ -184,17 +210,17 @@ } }, "@semantic-release/github": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-7.0.3.tgz", - "integrity": "sha512-4Y2nqruKHsdoayq/H/lMWudONXHLbYtSBDZPktoTrvdJZNQkLhjnxCwDUTKo8G29aI81RuoYKUHv6GSgyJDtGQ==", + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-7.0.5.tgz", + "integrity": "sha512-1nJCMeomspRIXKiFO3VXtkUMbIBEreYLFNBdWoLjvlUNcEK0/pEbupEZJA3XHfJuSzv43u3OLpPhF/JBrMuv+A==", "requires": { - "@octokit/rest": "^16.43.0", + "@octokit/rest": "^17.0.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", + "fs-extra": "^9.0.0", "globby": "^11.0.0", "http-proxy-agent": "^4.0.0", "https-proxy-agent": "^5.0.0", @@ -207,14 +233,14 @@ } }, "@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==" + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", + "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==" }, "@types/node": { - "version": "13.7.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-13.7.1.tgz", - "integrity": "sha512-Zq8gcQGmn4txQEJeiXo/KiLpon8TzAl0kmKH4zdWctPj05nWwp1ClMdAVEloqrQKfaC48PNLdgN/aVaLqUrluA==" + "version": "13.13.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.13.2.tgz", + "integrity": "sha512-LB2R1Oyhpg8gu4SON/mfforE525+Hi/M1ineICEDftqNVTyFg1aRIeGuTvXAoWHc4nbrFncWtJgMmoyRvuGh7A==" }, "@types/retry": { "version": "0.12.0", @@ -251,10 +277,10 @@ "resolved": "https://registry.npmjs.org/array-union/-/array-union-2.1.0.tgz", "integrity": "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==" }, - "atob-lite": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/atob-lite/-/atob-lite-2.0.0.tgz", - "integrity": "sha1-D+9a1G8b16hQLGVyfwNn1e5D1pY=" + "at-least-node": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/at-least-node/-/at-least-node-1.0.0.tgz", + "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==" }, "before-after-hook": { "version": "2.1.0", @@ -274,11 +300,6 @@ "fill-range": "^7.0.1" } }, - "btoa-lite": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/btoa-lite/-/btoa-lite-1.0.0.tgz", - "integrity": "sha1-M3dm2hWAEhD92VbCLpxokaudAzc=" - }, "chalk": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", @@ -308,9 +329,9 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "cross-spawn": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.1.tgz", - "integrity": "sha512-u7v4o84SwFpD32Z8IIcPZ6z1/ie24O6RU3RbtL5Y316l3KuHVPx9ItBgWQ6VlfAFnRnTtMUrsQ9MUUTuEZjogg==", + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.2.tgz", + "integrity": "sha512-PD6G8QG3S4FK/XCGFbEQrDqO2AnMMsy0meR7lerlIOHAAbkuavGU/pOqprrlvfTNjvowivTeBsjebAL0NSoMxw==", "requires": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -359,11 +380,6 @@ "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, - "esutils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", - "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==" - }, "execa": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.0.tgz", @@ -381,23 +397,24 @@ } }, "fast-glob": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.1.1.tgz", - "integrity": "sha512-nTCREpBY8w8r+boyFYAx21iL6faSsQynliPHM4Uf56SbkyohCNxpVPEH9xrF5TXKy+IsjkPUHDKiUkzBVRXn9g==", + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.2.tgz", + "integrity": "sha512-UDV82o4uQyljznxwMxyVRJgZZt3O5wENYojjzbaGEGZgeOxkLFf+V4cnUD+krzb2F72E18RhamkMZ7AdeggF7A==", "requires": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.0", "merge2": "^1.3.0", - "micromatch": "^4.0.2" + "micromatch": "^4.0.2", + "picomatch": "^2.2.1" } }, "fastq": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.6.0.tgz", - "integrity": "sha512-jmxqQ3Z/nXoeyDmWAzF9kH1aGZSis6e/SbfPmJpUnyZ0ogr6iscHQaml4wsEepEWSdtmpy+eVXmCRIMpxaXqOA==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.7.0.tgz", + "integrity": "sha512-YOadQRnHd5q6PogvAR/x62BGituF2ufiEA6s8aavQANw5YKHERI4AREboX6KotzP8oX2klxYF2wcV/7bn1clfQ==", "requires": { - "reusify": "^1.0.0" + "reusify": "^1.0.4" } }, "fill-range": { @@ -409,13 +426,14 @@ } }, "fs-extra": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", - "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.0.0.tgz", + "integrity": "sha512-pmEYSk3vYsG/bF651KPUXZ+hvjpgWYw/Gc7W9NFUe3ZVLczKKWIij3IKpOrQcdw4TILtibFslZ0UmR8Vvzig4g==", "requires": { + "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", - "jsonfile": "^4.0.0", - "universalify": "^0.1.0" + "jsonfile": "^6.0.1", + "universalify": "^1.0.0" } }, "get-stream": { @@ -427,9 +445,9 @@ } }, "glob-parent": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.0.tgz", - "integrity": "sha512-qjtRgnIVmOfnKUE3NJAQEdk+lKrxfw8t5ke7SXtfMTHcjsBfOfWXCQfdb30zfDoZQ2IRSIiidmjtbHZPZ++Ihw==", + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz", + "integrity": "sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==", "requires": { "is-glob": "^4.0.1" } @@ -560,11 +578,12 @@ "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==" }, "jsonfile": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", - "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.0.1.tgz", + "integrity": "sha512-jR2b5v7d2vIOust+w3wtFKZIfpC2pnRmFAhAC/BuweZFQR8qZzxH1OyrQ10HmdVYiXWkYUqPVsz91cG7EL2FBg==", "requires": { - "graceful-fs": "^4.1.6" + "graceful-fs": "^4.1.6", + "universalify": "^1.0.0" } }, "lines-and-columns": { @@ -587,11 +606,6 @@ "resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz", "integrity": "sha1-ZHYsSGGAglGKw99Mz11YhtriA0c=" }, - "lodash.get": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", - "integrity": "sha1-LRd/ZS+jHpObRDjVNBSZ36OCXpk=" - }, "lodash.isplainobject": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", @@ -602,16 +616,6 @@ "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=" }, - "lodash.set": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/lodash.set/-/lodash.set-4.3.2.tgz", - "integrity": "sha1-2HV7HagH3eJIFrDWqEvqGnYjCyM=" - }, - "lodash.uniq": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz", - "integrity": "sha1-0CJTc662Uq3BvILklFM5qEJ1R3M=" - }, "lodash.uniqby": { "version": "4.7.0", "resolved": "https://registry.npmjs.org/lodash.uniqby/-/lodash.uniqby-4.7.0.tgz", @@ -674,11 +678,6 @@ "path-key": "^3.0.0" } }, - "octokit-pagination-methods": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/octokit-pagination-methods/-/octokit-pagination-methods-1.1.0.tgz", - "integrity": "sha512-fZ4qZdQ2nxJvtcasX7Ghl+WlWS/d9IgnBIwFZXVNNZUmzpno91SX5bc5vuxiuKoCtK78XxGGNuSCrDC7xYB3OQ==" - }, "once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -758,9 +757,9 @@ "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==" }, "picomatch": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.1.tgz", - "integrity": "sha512-ISBaA8xQNmwELC7eOjqFKMESB2VIqt4PPDD0nsS95b/9dZXvVKOlz9keMSnoGGKcOHXfTvDD6WMaRoSc9UuhRA==" + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", + "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==" }, "pump": { "version": "3.0.0", @@ -805,9 +804,9 @@ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" }, "signal-exit": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.2.tgz", - "integrity": "sha1-tf3AjxKH6hF4Yo5BXiUTK3NkbG0=" + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.3.tgz", + "integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==" }, "slash": { "version": "3.0.0", @@ -841,17 +840,17 @@ } }, "universal-user-agent": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-4.0.0.tgz", - "integrity": "sha512-eM8knLpev67iBDizr/YtqkJsF3GK8gzDc6st/WKzrTuPtcsOKW/0IdL4cnMBsU69pOx0otavLWBDGTwg+dB0aA==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-5.0.0.tgz", + "integrity": "sha512-B5TPtzZleXyPrUMKCpEHFmVhMN6EhmJYjG5PQna9s7mXeSqGTLap4OpqLl5FCEFUI3UBmllkETwKf/db66Y54Q==", "requires": { "os-name": "^3.1.0" } }, "universalify": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", - "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==" + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-1.0.0.tgz", + "integrity": "sha512-rb6X1W158d7pRQBg5gkR8uPaSfiids68LTJQYOtEUhoJUWBdaQHsuT/EUduxXYxcrt4r5PJ4fuHW1MHT6p0qug==" }, "url-join": { "version": "4.0.1", @@ -867,9 +866,9 @@ } }, "windows-release": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/windows-release/-/windows-release-3.2.0.tgz", - "integrity": "sha512-QTlz2hKLrdqukrsapKsINzqMgOUpQW268eJ0OaOpJN32h272waxR9fkB9VoWRtK7uKHG5EHJcTXQBD8XZVJkFA==", + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/windows-release/-/windows-release-3.3.0.tgz", + "integrity": "sha512-2HetyTg1Y+R+rUgrKeUEhAG/ZuOmTrI1NBb3ZyAGQMYmOJjBBPe4MTodghRkmLJZHwkuPi02anbeGP+Zf401LQ==", "requires": { "execa": "^1.0.0" }, From 737fd961ca22740d41ffdf2327d1cb6e624ca4d1 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Fri, 24 Apr 2020 11:44:12 -0400 Subject: [PATCH 247/455] docs: update old doc links --- ibm_watson/assistant_v1.py | 8 ++++---- ibm_watson/speech_to_text_v1_adapter.py | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 25a8df958..7366a2289 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -4780,14 +4780,14 @@ class DialogNodeOutputGeneric(): natural-language query or a query that uses the Discovery query language syntax, depending on the value of the **query_type** property. For more information, see the [Discovery service - documentation](https://cloud.ibm.com/docs/discovery/query-operators.html#query-operators). + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators). Required when **response_type**=`search_skill`. :attr str query_type: (optional) The type of the search query. Required when **response_type**=`search_skill`. :attr str filter: (optional) An optional filter that narrows the set of documents to be searched. For more information, see the [Discovery service documentation]([Discovery service - documentation](https://cloud.ibm.com/docs/discovery/query-parameters.html#filter). + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). :attr str discovery_version: (optional) The version of the Discovery service API to use for the query. """ @@ -4849,14 +4849,14 @@ def __init__(self, either a natural-language query or a query that uses the Discovery query language syntax, depending on the value of the **query_type** property. For more information, see the [Discovery service - documentation](https://cloud.ibm.com/docs/discovery/query-operators.html#query-operators). + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators). Required when **response_type**=`search_skill`. :param str query_type: (optional) The type of the search query. Required when **response_type**=`search_skill`. :param str filter: (optional) An optional filter that narrows the set of documents to be searched. For more information, see the [Discovery service documentation]([Discovery service - documentation](https://cloud.ibm.com/docs/discovery/query-parameters.html#filter). + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). :param str discovery_version: (optional) The version of the Discovery service API to use for the query. """ diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 11bd2d38d..7cf5087f3 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -171,7 +171,7 @@ def recognize_using_websocket(self, 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/speech-to-text/output.html). + [Grammars](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output). :param bool redaction: 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` character. It is intended @@ -184,7 +184,7 @@ def recognize_using_websocket(self, (forces the `max_alternatives` parameter to be `1`). **Note:** Applies to US English, Japanese, and Korean transcription only. See [Numeric - redaction](https://cloud.ibm.com/docs/speech-to-text/output.html#redaction). + redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#redaction). :param bool processing_metrics: 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 `processing_metrics_interval` parameter. It also From 03a3509f497dca9a534fc19cc59498ce80f2f51e Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Wed, 6 May 2020 07:32:35 -0400 Subject: [PATCH 248/455] fix: loading creds from top level directory --- requirements-dev.txt | 2 +- requirements.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 4c72280d9..45e0ba840 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ python_dotenv>=0.1.5;python_version!='3.2' pylint>=1.4.4 tox>=2.9.1 pytest-rerunfailures>=3.1 -ibm_cloud_sdk_core==1.5.1 +ibm_cloud_sdk_core==1.7.3 # code coverage coverage<5 diff --git a/requirements.txt b/requirements.txt index fea3e1c8c..85f94adb4 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 -ibm_cloud_sdk_core==1.5.1 +ibm_cloud_sdk_core==1.7.3 From e1aad21544a5581c3dc70be2f34050623022bc4d Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 11 May 2020 07:46:26 -0400 Subject: [PATCH 249/455] test: update vis rec instance and skip some tests for now --- .env.enc | Bin 1840 -> 1840 bytes .travis.yml | 21 +-- .../integration/test_visual_recognition_v4.py | 121 +++++++++--------- 3 files changed, 68 insertions(+), 74 deletions(-) diff --git a/.env.enc b/.env.enc index 09dbc43b497dcb7ea1c298d7081c00ff1cf3cd02..9af01f6f5eec6e1459ccd45018d0ae0d47126089 100644 GIT binary patch literal 1840 zcmV-02haH3F3N$tR>nSUd;{27)sq5`{UOdN^{*?Vj8V<#E+oV)t+K^Drj;}@vhnQh zm8fo#O7xsN@0_k5CAmZKFoi|B;W*dmZN4G%_8T*qvI&xo7Nj>i0(yg?_4Uh3SSmg-+ z;af6yN)PX{*8|*3YIf-q9dPpv(=M_IB*xHa2I*z{8K(F?CGta=|7js3`m)+R{Lbr_ zbSvO*naOM%${v%wMA20wVCZ%Nwhi?S1D6XU(_nAR{Yc1h5QYNBf`XwehuKsY)Pa`8C&^8S9xSSDxaSmzp0En&G3? z;*`94lxhuaF8Y-h*HrFWkCE?7KtrVbiW$TS?;f*;#8^B9?8q&5?{NxAa?{j4`?P5! zUx%zHPBmJC2S*(;XEu)7wq4CO4EbOu$A8Z3RKNO^ZzRM}(VGXAmQ>JqV4H$}dL#>8&U4GFxw%O!CRU!Y@jLuE-kC9ok+|KQ06?dO06oiL5w` z;Z50<%N^%*{-Lx*UvV*a`cGO?&_ zIXvshS&?h&uhT?Ml6MKVgo5y`P-?Ki$1C@WG;(pHUpJu+K~){(bx=_|NYY>^``JPu zp=wu_6f8~l;}e0RM4*XZd472BFDn@Jv#^5}*%JRe%TjD&v_+rI;YJ$4N$Pg%k>y_Z z`*o{;YV>b6b7zAB4)($NJiMfna5Z@w4Qlg5p!52P(B-86sWN|fEZ>0d?!V8^-hK31 z7NH;Q?n8>%9i5+tv`0C^2!XY&0^BmX>T3E z9|2fD??NmD-_c=DtEBZj11=M@mXaA`GHgh>6m)k0nXPmo;u&acbg_FFGzRD2Qu_+U z;&4a7U+7|}4x`3FPI4wayhWMVQ`O|1FtPqP)jbn9AQcOw!=bG>fi7N2KoiBlAY&-{ zOVjZhtW8a`+3iDEqgR$kNUYm>5erlfE72pHu8B zGLABmNO~7`z4HRgy41L(DO*(~N3q?FzJzh=KWU9r=0s%H-1&Y#@Ofx@`^h}wb4|6m z@S|O)WWa??P75r(isvj@#D5XE-6FuUo0wPx3@>tFqlTA3$%O>!8#v>tA;o7=F16js zE{~1h1+e;8n7JMTH0r*_IlCiXfUykvnY<@bGZx+JH^`yx5-f~7lk z^gGX=!3dXhf3Jlwm&7JhW6&RJ$@~{vlqi1jwvh6@I+(tVwxLo3=9oZjw&gMP@S>6h?zbEF>t#d eljlX6>!k^lK77lL_*pt-2JQH<$RLAMk^ib@WRdm& literal 1840 zcmV-02haFDg-1|QqVl1wRt1lD7eTqV`%9X)C)n%vZFvRPaXw}<;g7X#G665i5bLn$iY1}`Y?60TGPfyCP~9jK{d#f*3ejox zbuK72t8X$=FN!-o8mxI?b);o@;ZL0Od(lotaC>nh*ppwjnb!~ZK2TZPQaW0M5 ztj&lx<~1xIMjDaAWQYUUvltW8=aa7`vkxQ&?kFNhI#^AAg>T43TIqnS`Cz?dC2&`^ z?Eb}P-tmf#>7mnF(|85grCtsYr9=lgfDk+v?o(Zsx#FO(TYOc=CzeE!wszRi)*3`u z-s`KBPDr+CHiO)ieUl;C$lkXPf-T^fY!r$=eJ$##=J6zyEw#D0Ib+G_b)6H~@r+qMLtP(Eg>VlQ}Bn+u&3C(cW8+5hCCv+Bw5Eiw(Vgb=1X%!fzR6V`7%nQvg6W6%`LCV&bNd0i08f{ZN4`@ z{h!X=OxbEj;wsNlX4Ppco*NF22_)+&&aUB7-T8gL(KeLy+33?gA~SjL92nT1VVc3I z*wF)6bx;G(dJT{uF6+!1&8S7%pO<9>7~mp0Mu|dx{R!TC8Aek33-xsgLU+XMqDx?i@*azqWHpr0Gl+zyJe}hYoxFH z9!G7whsxieXXVK$@)PF=QYbUgVThl*EpMfto(af(Hw@jvaH zz*7OY4pAOc1iLN?wW*vGf8IMo3wML~LinTT6dk&YZSm93f|8Fl(kev|cSyeUWl~Zc z8;^wi*yvLECC$4Ef+Dz<#7kB%c9T*=R`N|E!KYG-5c}qF>7ckGp^l|j9;KcPUJC9c zD4M-3m!kaTErO>?pf5U7OMDw@#&D!K4WJG4CHE$p4NM}Ikpv!c-4Xd8Vsl?*#|Y#5 zqTl{?!|LCzY(nE-nd}QE&28$Wv(hFa&_yy0UDSnw4H}4=tqpokoPrE-HaN1<}rS)WOg|TNqXR;$L=ogcQ&S}#Zia3 zuZ^NuWoMy0UmwF8^+@u4KN#`&RJmzn)TlT~)%^php-?NKBpk3qL6>Xu>LLi+zl}&z zSS$Xa_1KV(^f+1spme9Osos9ldWPKl#dFabsz9PCC*04s_11{p(#v=%OpGAf;4U z`cB8%yT6Ju{KQ0Um)>qr8$T(h6;Ak9fSwd&wmoho#dB?L0Z&mM989bsY; z$f>E&;qFt0RUQ;T3`dWDbi0ES5zt;r3u|hm!!yOsKsthyXL&xkdlf^WzqvEF`#yW? zoKDqx8PE^0YlJsQDUKmI=0R?ai6<)l3YSFHlSOS%{Agi{&o^Rn)$^Jg>w3UvKIXhF zDeax!mwF}g2{z4H{g`+-4{~Km-4*2{Urq}GCL9V#Y98i6hrBvd3NW3_Y|5U#iLj?} zQ$=n1^AYU|5kXM3Dud(X`S@~wM~OC^Gfh|oj-Efxh&*RJoE3Qb4IJ)8%u+7>Z_L_^ zg`Fb^z#U@+Lxq=>yktkRHEG!pZz7v<$jPXmrQ6OdIo{n}G@(EHW%TAwqD|8$QYBLu zr?)2$mf*PuI<))z1L4pC?qdgXQjy Date: Mon, 11 May 2020 12:31:54 +0000 Subject: [PATCH 250/455] =?UTF-8?q?Bump=20version:=204.4.0=20=E2=86=92=204?= =?UTF-8?q?.4.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index efca55923..77e1c749b 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.4.0 +current_version = 4.4.1 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 26a6c390a..6dd6cf9b2 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.4.0' +__version__ = '4.4.1' diff --git a/setup.py b/setup.py index 23bbfcc98..ab203c1bd 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.4.0' +__version__ = '4.4.1' if sys.argv[-1] == 'publish': From fa0f80a9e9282d617c27ef3fdba7efd49c5385eb Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Mon, 11 May 2020 12:31:55 +0000 Subject: [PATCH 251/455] chore(release): 4.4.1 release notes ## [4.4.1](https://github.com/watson-developer-cloud/python-sdk/compare/v4.4.0...v4.4.1) (2020-05-11) ### Bug Fixes * loading creds from top level directory ([03a3509](https://github.com/watson-developer-cloud/python-sdk/commit/03a3509f497dca9a534fc19cc59498ce80f2f51e)) --- CHANGELOG.md | 7 ++++++ package-lock.json | 64 ++++++++++++++++++++--------------------------- 2 files changed, 34 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3db80b5cf..05c413e86 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [4.4.1](https://github.com/watson-developer-cloud/python-sdk/compare/v4.4.0...v4.4.1) (2020-05-11) + + +### Bug Fixes + +* loading creds from top level directory ([03a3509](https://github.com/watson-developer-cloud/python-sdk/commit/03a3509f497dca9a534fc19cc59498ce80f2f51e)) + # [4.4.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.3.0...v4.4.0) (2020-04-24) diff --git a/package-lock.json b/package-lock.json index c151f747d..bf3323635 100644 --- a/package-lock.json +++ b/package-lock.json @@ -80,23 +80,13 @@ } }, "@octokit/graphql": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.3.1.tgz", - "integrity": "sha512-hCdTjfvrK+ilU2keAdqNBWOk+gm1kai1ZcdjRfB30oA3/T6n53UVJb7w0L5cR3/rhU91xT3HSqCd+qbvH06yxA==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.4.0.tgz", + "integrity": "sha512-Du3hAaSROQ8EatmYoSAJjzAz3t79t9Opj/WY1zUgxVUGfIKn0AEjg+hlOLscF6fv6i/4y/CeUvsWgIfwMkTccw==", "requires": { "@octokit/request": "^5.3.0", "@octokit/types": "^2.0.0", - "universal-user-agent": "^4.0.0" - }, - "dependencies": { - "universal-user-agent": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-4.0.1.tgz", - "integrity": "sha512-LnST3ebHwVL2aNe4mejI9IQh2HfZ1RLo8Io2HugSif8ekzD1TlWpHpColOB/eh8JHMLkGH3Akqf040I+4ylNxg==", - "requires": { - "os-name": "^3.1.0" - } - } + "universal-user-agent": "^5.0.0" } }, "@octokit/plugin-paginate-rest": { @@ -113,11 +103,11 @@ "integrity": "sha512-ywoxP68aOT3zHCLgWZgwUJatiENeHE7xJzYjfz8WI0goynp96wETBF+d95b8g/uL4QmS6owPVlaxiz3wyMAzcw==" }, "@octokit/plugin-rest-endpoint-methods": { - "version": "3.8.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-3.8.0.tgz", - "integrity": "sha512-LUkTgZ53adPFC/Hw6mxvAtShUtGy3zbpcfCAJMWAN7SvsStV4p6TK7TocSv0Aak4TNmDLhbShTagGhpgz9mhYw==", + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-3.10.0.tgz", + "integrity": "sha512-Z2DBsdnkWKuVBVFiLoEUKP/82ylH4Ij5F1Mss106hnQYXTxDfCWAyHW+hJ6ophuHVJ9Flaaue3fYn4CggzkHTg==", "requires": { - "@octokit/types": "^2.12.1", + "@octokit/types": "^2.14.0", "deprecation": "^2.3.1" } }, @@ -147,20 +137,20 @@ } }, "@octokit/rest": { - "version": "17.6.0", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-17.6.0.tgz", - "integrity": "sha512-knh+4hPBA26AMXflFRupTPT3u9NcQmQzeBJl4Gcuf14Gn7dUh6Loc1ICWF0Pz18A6ElFZQt+wB9tFINSruIa+g==", + "version": "17.8.0", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-17.8.0.tgz", + "integrity": "sha512-m2pdo9+DoEoqQ7wRXV1ihffhE1gbvoC20nvchphluEusbZI6Y9HyXABGiXL+mByy2uUMR2cgBDqBJQQ6bY8Uvg==", "requires": { "@octokit/core": "^2.4.3", "@octokit/plugin-paginate-rest": "^2.2.0", "@octokit/plugin-request-log": "^1.0.0", - "@octokit/plugin-rest-endpoint-methods": "3.8.0" + "@octokit/plugin-rest-endpoint-methods": "3.10.0" } }, "@octokit/types": { - "version": "2.12.1", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-2.12.1.tgz", - "integrity": "sha512-LRLR1tjbcCfAmUElvTmMvLEzstpx6Xt/aQVTg2xvd+kHA2Ekp1eWl5t+gU7bcwjXHYEAzh4hH4WH+kS3vh+wRw==", + "version": "2.15.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-2.15.0.tgz", + "integrity": "sha512-0mnpenB8rLhBVu8VUklp38gWi+EatjvcEcLWcdProMKauSaQWWepOAybZ714sOGsEyhXPlIcHICggn8HUsCXVw==", "requires": { "@types/node": ">= 8" } @@ -238,9 +228,9 @@ "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==" }, "@types/node": { - "version": "13.13.2", - "resolved": "https://registry.npmjs.org/@types/node/-/node-13.13.2.tgz", - "integrity": "sha512-LB2R1Oyhpg8gu4SON/mfforE525+Hi/M1ineICEDftqNVTyFg1aRIeGuTvXAoWHc4nbrFncWtJgMmoyRvuGh7A==" + "version": "13.13.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-13.13.5.tgz", + "integrity": "sha512-3ySmiBYJPqgjiHA7oEaIo2Rzz0HrOZ7yrNO5HWyaE5q0lQ3BppDZ3N53Miz8bw2I7gh1/zir2MGVZBvpb1zq9g==" }, "@types/retry": { "version": "0.12.0", @@ -381,9 +371,9 @@ "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, "execa": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.0.tgz", - "integrity": "sha512-JbDUxwV3BoT5ZVXQrSVbAiaXhXUkIwvbhPIwZ0N13kX+5yCzOhUNdocxB/UQRuYOHRYYwAxKYwJYc0T4D12pDA==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.1.tgz", + "integrity": "sha512-SCjM/zlBdOK8Q5TIjOn6iEHZaPHFsMoTxXQ2nvUvtPnuohz3H2dIozSg+etNR98dGoYUp2ENSKLL/XaMmbxVgw==", "requires": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", @@ -466,9 +456,9 @@ } }, "graceful-fs": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.3.tgz", - "integrity": "sha512-a30VEBm4PEdx1dRB7MFK7BejejvCvBronbLjht+sHuGYj8PHs7M/5Z+rt5lw551vZ7yfTCj4Vuyy3mSJytDWRQ==" + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz", + "integrity": "sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw==" }, "has-flag": { "version": "3.0.0", @@ -646,9 +636,9 @@ } }, "mime": { - "version": "2.4.4", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.4.tgz", - "integrity": "sha512-LRxmNwziLPT828z+4YkNzloCFC2YM4wrB99k+AV5ZbEyfGNWfG8SO1FUXLmLDBSo89NrJZ4DIWeLjy1CHGhMGA==" + "version": "2.4.5", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.5.tgz", + "integrity": "sha512-3hQhEUF027BuxZjQA3s7rIv/7VCQPa27hN9u9g87sEkWaKwQPuXOkVKtOeiyUrnWqTDiOs8Ed2rwg733mB0R5w==" }, "mimic-fn": { "version": "2.1.0", From 858af780c60edcff5e6c47281f23d3d9c5011861 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 28 May 2020 09:27:17 -0400 Subject: [PATCH 252/455] feat(AssistantV1): add support for spelling suggestions --- ibm_watson/assistant_v1.py | 107 ++++++++++++++++++++++++++++++++- test/unit/test_assistant_v1.py | 14 ++--- 2 files changed, 111 insertions(+), 10 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 7366a2289..a8f34d5f9 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -7275,17 +7275,61 @@ class MessageInput(): :attr str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. + :attr bool spelling_suggestions: (optional) Whether to use spelling correction + when processing the input. This property overrides the value of the + **spelling_suggestions** property in the workspace settings. + :attr bool spelling_auto_correct: (optional) Whether to use autocorrection when + processing the input. If spelling correction is used and this property is + `false`, any suggested corrections are returned in the **suggested_text** + property of the message response. If this property is `true`, any corrections + are automatically applied to the user input, and the original text is returned + in the **original_text** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the workspace + settings. + :attr str suggested_text: (optional) Any suggested corrections of the input + text. This property is returned only if spelling correction is enabled and + autocorrection is disabled. + :attr str original_text: (optional) The original user input text. This property + is returned only if autocorrection is enabled and the user input was corrected. """ - def __init__(self, *, text: str = None, **kwargs) -> None: + def __init__(self, + *, + text: str = None, + spelling_suggestions: bool = None, + spelling_auto_correct: bool = None, + suggested_text: str = None, + original_text: str = None, + **kwargs) -> None: """ Initialize a MessageInput object. :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. + :param bool spelling_suggestions: (optional) Whether to use spelling + correction when processing the input. This property overrides the value of + the **spelling_suggestions** property in the workspace settings. + :param bool spelling_auto_correct: (optional) Whether to use autocorrection + when processing the input. If spelling correction is used and this property + is `false`, any suggested corrections are returned in the + **suggested_text** property of the message response. If this property is + `true`, any corrections are automatically applied to the user input, and + the original text is returned in the **original_text** property of the + message response. This property overrides the value of the + **spelling_auto_correct** property in the workspace settings. + :param str suggested_text: (optional) Any suggested corrections of the + input text. This property is returned only if spelling correction is + enabled and autocorrection is disabled. + :param str original_text: (optional) The original user input text. This + property is returned only if autocorrection is enabled and the user input + was corrected. :param **kwargs: (optional) Any additional properties. """ self.text = text + self.spelling_suggestions = spelling_suggestions + self.spelling_auto_correct = spelling_auto_correct + self.suggested_text = suggested_text + self.original_text = original_text for _key, _value in kwargs.items(): setattr(self, _key, _value) @@ -7297,6 +7341,18 @@ def from_dict(cls, _dict: Dict) -> 'MessageInput': if 'text' in _dict: args['text'] = _dict.get('text') del xtra['text'] + if 'spelling_suggestions' in _dict: + args['spelling_suggestions'] = _dict.get('spelling_suggestions') + del xtra['spelling_suggestions'] + if 'spelling_auto_correct' in _dict: + args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') + del xtra['spelling_auto_correct'] + if 'suggested_text' in _dict: + args['suggested_text'] = _dict.get('suggested_text') + del xtra['suggested_text'] + if 'original_text' in _dict: + args['original_text'] = _dict.get('original_text') + del xtra['original_text'] args.update(xtra) return cls(**args) @@ -7310,6 +7366,16 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text + if hasattr(self, 'spelling_suggestions' + ) and self.spelling_suggestions is not None: + _dict['spelling_suggestions'] = self.spelling_suggestions + if hasattr(self, 'spelling_auto_correct' + ) and self.spelling_auto_correct is not None: + _dict['spelling_auto_correct'] = self.spelling_auto_correct + if hasattr(self, 'suggested_text') and self.suggested_text is not None: + _dict['suggested_text'] = self.suggested_text + if hasattr(self, 'original_text') and self.original_text is not None: + _dict['original_text'] = self.original_text if hasattr(self, '_additionalProperties'): for _key in self._additionalProperties: _value = getattr(self, _key, None) @@ -7322,7 +7388,10 @@ def _to_dict(self): return self.to_dict() def __setattr__(self, name: str, value: object) -> None: - properties = {'text'} + properties = { + 'text', 'spelling_suggestions', 'spelling_auto_correct', + 'suggested_text', 'original_text' + } if not hasattr(self, '_additionalProperties'): super(MessageInput, self).__setattr__('_additionalProperties', set()) @@ -9872,6 +9941,14 @@ 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 bool spelling_suggestions: (optional) Whether spelling correction is + enabled for the workspace. + :attr bool spelling_auto_correct: (optional) Whether autocorrection is enabled + for the workspace. If spelling correction is enabled and this property is + `false`, any suggested corrections are returned in the **suggested_text** + property of the message response. If this property is `true`, any corrections + are automatically applied to the user input, and the original text is returned + in the **original_text** property of the message response. :attr WorkspaceSystemSettingsSystemEntities system_entities: (optional) Workspace settings related to the behavior of system entities. :attr WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings @@ -9884,6 +9961,8 @@ def __init__( tooling: 'WorkspaceSystemSettingsTooling' = None, disambiguation: 'WorkspaceSystemSettingsDisambiguation' = None, human_agent_assist: dict = None, + spelling_suggestions: bool = None, + spelling_auto_correct: bool = None, system_entities: 'WorkspaceSystemSettingsSystemEntities' = None, off_topic: 'WorkspaceSystemSettingsOffTopic' = None) -> None: """ @@ -9895,6 +9974,15 @@ def __init__( 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 bool spelling_suggestions: (optional) Whether spelling correction is + enabled for the workspace. + :param bool spelling_auto_correct: (optional) Whether autocorrection is + enabled for the workspace. If spelling correction is enabled and this + property is `false`, any suggested corrections are returned in the + **suggested_text** property of the message response. If this property is + `true`, any corrections are automatically applied to the user input, and + the original text is returned in the **original_text** property of the + message response. :param WorkspaceSystemSettingsSystemEntities system_entities: (optional) Workspace settings related to the behavior of system entities. :param WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace @@ -9903,6 +9991,8 @@ def __init__( self.tooling = tooling self.disambiguation = disambiguation self.human_agent_assist = human_agent_assist + self.spelling_suggestions = spelling_suggestions + self.spelling_auto_correct = spelling_auto_correct self.system_entities = system_entities self.off_topic = off_topic @@ -9912,7 +10002,8 @@ def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': args = {} valid_keys = [ 'tooling', 'disambiguation', 'human_agent_assist', - 'system_entities', 'off_topic' + 'spelling_suggestions', 'spelling_auto_correct', 'system_entities', + 'off_topic' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -9928,6 +10019,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 'spelling_suggestions' in _dict: + args['spelling_suggestions'] = _dict.get('spelling_suggestions') + if 'spelling_auto_correct' in _dict: + args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') if 'system_entities' in _dict: args[ 'system_entities'] = WorkspaceSystemSettingsSystemEntities._from_dict( @@ -9953,6 +10048,12 @@ 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, 'spelling_suggestions' + ) and self.spelling_suggestions is not None: + _dict['spelling_suggestions'] = self.spelling_suggestions + if hasattr(self, 'spelling_auto_correct' + ) and self.spelling_auto_correct is not None: + _dict['spelling_auto_correct'] = self.spelling_auto_correct if hasattr(self, 'system_entities') and self.system_entities is not None: _dict['system_entities'] = self.system_entities._to_dict() diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 6adccb3fb..bc1ed2ad3 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -91,7 +91,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"input": MessageInput._from_dict(json.loads("""{"text": "fake_text"}""")), "intents": [], "entities": [], "alternate_intents": True, "context": Context._from_dict(json.loads("""{"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}""")), "output": OutputData._from_dict(json.loads("""{"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}""")), }) + body.update({"input": MessageInput._from_dict(json.loads("""{"text": "fake_text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "fake_suggested_text", "original_text": "fake_original_text"}""")), "intents": [], "entities": [], "alternate_intents": True, "context": Context._from_dict(json.loads("""{"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}""")), "output": OutputData._from_dict(json.loads("""{"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}""")), }) body['nodes_visited_details'] = True return body @@ -242,7 +242,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() - body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) body['include_audit'] = True return body @@ -386,7 +386,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) body['append'] = True body['include_audit'] = True return body @@ -3546,11 +3546,11 @@ 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_MessageResponse_json = """{"input": {"text": "fake_text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "fake_suggested_text", "original_text": "fake_original_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"}, "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_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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "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": []}""" From c57f248ea920c12bb439b5571ae78fcce144707b Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 28 May 2020 09:27:42 -0400 Subject: [PATCH 253/455] feat(AssistantV2): add support for stateless messages --- ibm_watson/assistant_v2.py | 976 ++++++++++++++++++++++++++++++--- test/unit/test_assistant_v2.py | 76 ++- 2 files changed, 983 insertions(+), 69 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index addaea126..8e0da3ad0 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -181,9 +181,11 @@ def message(self, context: 'MessageContext' = None, **kwargs) -> 'DetailedResponse': """ - Send user input to assistant. + Send user input to assistant (stateful). - Send user input to an assistant and receive a response. + Send user input to an assistant and receive a response, with conversation state + (including context data) stored by Watson Assistant for the duration of the + session. There is no rate limit for this operation. :param str assistant_id: Unique identifier of the assistant. To find the @@ -195,10 +197,12 @@ def message(self, :param str session_id: Unique identifier of the session. :param MessageInput input: (optional) An input object that includes the input text. - :param MessageContext context: (optional) State information for the - conversation. The context is stored by the assistant on a per-session - basis. You can use this property to set or modify context variables, which - can also be accessed by dialog nodes. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -236,6 +240,69 @@ def message(self, response = self.send(request) return response + def message_stateless(self, + assistant_id: str, + *, + input: 'MessageInputStateless' = None, + context: 'MessageContextStateless' = None, + **kwargs) -> 'DetailedResponse': + """ + Send user input to assistant (stateless). + + Send user input to an assistant and receive a response, with conversation state + (including context data) managed by your application. + There is no rate limit for this operation. + + :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/assistant?topic=assistant-assistant-add#assistant-add-task). + **Note:** Currently, the v2 API does not support creating assistants. + :param MessageInputStateless input: (optional) An input object that + includes the input text. + :param MessageContextStateless context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is not stored by + the assistant. To maintain session state, include the context from the + previous response. + **Note:** The total size of the context data for a stateless session cannot + exceed 250KB. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if assistant_id is None: + raise ValueError('assistant_id must be provided') + if input is not None: + input = self._convert_model(input) + if context is not None: + context = self._convert_model(context) + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message_stateless') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'input': input, 'context': context} + + url = '/v2/assistants/{0}/message'.format( + *self._encode_path_vars(assistant_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + ############################################################################## # Models @@ -904,13 +971,12 @@ class MessageContext(): """ MessageContext. - :attr MessageContextGlobal global_: (optional) Information that is shared by all - skills used by the Assistant. + :attr MessageContextGlobal global_: (optional) Session context data that is + shared by all skills used by the Assistant. :attr MessageContextSkills skills: (optional) Information specific to particular - skills used by the Assistant. - **Note:** Currently, only a single property named `main skill` is supported. - This object contains variables that apply to the dialog skill used by the - assistant. + skills used by the assistant. + **Note:** Currently, only a single child property is supported, containing + variables that apply to the dialog skill used by the assistant. """ def __init__(self, @@ -920,13 +986,12 @@ def __init__(self, """ Initialize a MessageContext object. - :param MessageContextGlobal global_: (optional) Information that is shared - by all skills used by the Assistant. + :param MessageContextGlobal global_: (optional) Session context data that + is shared by all skills used by the Assistant. :param MessageContextSkills skills: (optional) Information specific to - particular skills used by the Assistant. - **Note:** Currently, only a single property named `main skill` is - supported. This object contains variables that apply to the dialog skill - used by the assistant. + particular skills used by the assistant. + **Note:** Currently, only a single child property is supported, containing + variables that apply to the dialog skill used by the assistant. """ self.global_ = global_ self.skills = skills @@ -984,26 +1049,32 @@ def __ne__(self, other: 'MessageContext') -> bool: class MessageContextGlobal(): """ - Information that is shared by all skills used by the Assistant. + Session context data that is shared by all skills used by the Assistant. :attr MessageContextGlobalSystem system: (optional) Built-in system properties that apply to all skills used by the assistant. + :attr str session_id: (optional) The session ID. """ - def __init__(self, *, system: 'MessageContextGlobalSystem' = None) -> None: + def __init__(self, + *, + system: 'MessageContextGlobalSystem' = None, + session_id: str = None) -> None: """ Initialize a MessageContextGlobal object. :param MessageContextGlobalSystem system: (optional) Built-in system properties that apply to all skills used by the assistant. + :param str session_id: (optional) The session ID. """ self.system = system + self.session_id = session_id @classmethod def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} - valid_keys = ['system'] + valid_keys = ['system', 'session_id'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -1012,6 +1083,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': if 'system' in _dict: args['system'] = MessageContextGlobalSystem._from_dict( _dict.get('system')) + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') return cls(**args) @classmethod @@ -1024,6 +1097,8 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'system') and self.system is not None: _dict['system'] = self.system._to_dict() + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id return _dict def _to_dict(self): @@ -1045,6 +1120,79 @@ def __ne__(self, other: 'MessageContextGlobal') -> bool: return not self == other +class MessageContextGlobalStateless(): + """ + Session context data that is shared by all skills used by the Assistant. + + :attr MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :attr str session_id: (optional) The unique identifier of the session. + """ + + def __init__(self, + *, + system: 'MessageContextGlobalSystem' = None, + session_id: str = None) -> None: + """ + Initialize a MessageContextGlobalStateless object. + + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. + """ + self.system = system + self.session_id = session_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': + """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + args = {} + valid_keys = ['system', 'session_id'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class MessageContextGlobalStateless: ' + + ', '.join(bad_keys)) + if 'system' in _dict: + args['system'] = MessageContextGlobalSystem._from_dict( + _dict.get('system')) + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextGlobalStateless 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, 'system') and self.system is not None: + _dict['system'] = self.system._to_dict() + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + 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 MessageContextGlobalStateless object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextGlobalStateless') -> 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: 'MessageContextGlobalStateless') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageContextGlobalSystem(): """ Built-in system properties that apply to all skills used by the assistant. @@ -1215,17 +1363,19 @@ class LocaleEnum(Enum): class MessageContextSkill(): """ - Contains information specific to a particular skill used by the Assistant. + Contains information specific to a particular skill used by the Assistant. The + property name must be the same as the name of the skill (for example, `main skill`). :attr dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. - :attr dict system: (optional) System context data used by the skill. + :attr MessageContextSkillSystem system: (optional) System context data used by + the skill. """ def __init__(self, *, user_defined: dict = None, - system: dict = None) -> None: + system: 'MessageContextSkillSystem' = None) -> None: """ Initialize a MessageContextSkill object. @@ -1285,11 +1435,96 @@ def __ne__(self, other: 'MessageContextSkill') -> bool: return not self == other +class MessageContextSkillSystem(): + """ + System context data used by the skill. + + :attr str state: (optional) An encoded string representing the current + conversation state. By saving this value and then sending it in the context of a + subsequent message request, you can restore the conversation to the same state. + This can be useful if you need to return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session has expired. + """ + + def __init__(self, *, state: str = None, **kwargs) -> None: + """ + Initialize a MessageContextSkillSystem object. + + :param str state: (optional) An encoded string representing the current + conversation state. By saving this value and then sending it in the context + of a subsequent message request, you can restore the conversation to the + same state. This can be useful if you need to return to an earlier point in + the conversation. If you are using stateful sessions, you can also use a + stored state value to restore a paused conversation whose session has + expired. + :param **kwargs: (optional) Any additional properties. + """ + self.state = state + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': + """Initialize a MessageContextSkillSystem object from a json dictionary.""" + args = {} + xtra = _dict.copy() + if 'state' in _dict: + args['state'] = _dict.get('state') + del xtra['state'] + args.update(xtra) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkillSystem 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, 'state') and self.state is not None: + _dict['state'] = self.state + if hasattr(self, '_additionalProperties'): + for _key in self._additionalProperties: + _value = getattr(self, _key, None) + if _value is not None: + _dict[_key] = _value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: + properties = {'state'} + if not hasattr(self, '_additionalProperties'): + super(MessageContextSkillSystem, + self).__setattr__('_additionalProperties', set()) + if name not in properties: + self._additionalProperties.add(name) + super(MessageContextSkillSystem, self).__setattr__(name, value) + + def __str__(self) -> str: + """Return a `str` version of this MessageContextSkillSystem object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkillSystem') -> 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: 'MessageContextSkillSystem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageContextSkills(): """ - Information specific to particular skills used by the Assistant. - **Note:** Currently, only a single property named `main skill` is supported. This - object contains variables that apply to the dialog skill used by the assistant. + Information specific to particular skills used by the assistant. + **Note:** Currently, only a single child property is supported, containing variables + that apply to the dialog skill used by the assistant. """ @@ -1353,6 +1588,86 @@ def __ne__(self, other: 'MessageContextSkills') -> bool: return not self == other +class MessageContextStateless(): + """ + MessageContextStateless. + + :attr MessageContextGlobalStateless global_: (optional) Session context data + that is shared by all skills used by the Assistant. + :attr MessageContextSkills skills: (optional) Information specific to particular + skills used by the assistant. + **Note:** Currently, only a single child property is supported, containing + variables that apply to the dialog skill used by the assistant. + """ + + def __init__(self, + *, + global_: 'MessageContextGlobalStateless' = None, + skills: 'MessageContextSkills' = None) -> None: + """ + Initialize a MessageContextStateless object. + + :param MessageContextGlobalStateless global_: (optional) Session context + data that is shared by all skills used by the Assistant. + :param MessageContextSkills skills: (optional) Information specific to + particular skills used by the assistant. + **Note:** Currently, only a single child property is supported, containing + variables that apply to the dialog skill used by the assistant. + """ + self.global_ = global_ + self.skills = skills + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': + """Initialize a MessageContextStateless object from a json dictionary.""" + args = {} + valid_keys = ['global_', 'global', 'skills'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class MessageContextStateless: ' + + ', '.join(bad_keys)) + if 'global' in _dict: + args['global_'] = MessageContextGlobalStateless._from_dict( + _dict.get('global')) + if 'skills' in _dict: + args['skills'] = MessageContextSkills._from_dict( + _dict.get('skills')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextStateless 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, 'global_') and self.global_ is not None: + _dict['global'] = self.global_._to_dict() + if hasattr(self, 'skills') and self.skills is not None: + _dict['skills'] = self.skills._to_dict() + 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 MessageContextStateless object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextStateless') -> 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: 'MessageContextStateless') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageInput(): """ An input object that includes the input text. @@ -1361,8 +1676,6 @@ class MessageInput(): input is supported. :attr str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. - :attr MessageInputOptions options: (optional) Optional properties that control - how the assistant responds. :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the new input. @@ -1370,16 +1683,18 @@ class MessageInput(): the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. :attr str suggestion_id: (optional) For internal use only. + :attr MessageInputOptions options: (optional) Optional properties that control + how the assistant responds. """ def __init__(self, *, message_type: str = None, text: str = None, - options: 'MessageInputOptions' = None, intents: List['RuntimeIntent'] = None, entities: List['RuntimeEntity'] = None, - suggestion_id: str = None) -> None: + suggestion_id: str = None, + options: 'MessageInputOptions' = None) -> None: """ Initialize a MessageInput object. @@ -1387,8 +1702,6 @@ def __init__(self, text input is supported. :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. - :param MessageInputOptions options: (optional) Optional properties that - control how the assistant responds. :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating the user input. Include intents from the previous response to continue using those intents rather than trying to recognize intents in the @@ -1398,21 +1711,23 @@ def __init__(self, continue using those entities rather than detecting entities in the new input. :param str suggestion_id: (optional) For internal use only. + :param MessageInputOptions options: (optional) Optional properties that + control how the assistant responds. """ self.message_type = message_type self.text = text - self.options = options self.intents = intents self.entities = entities self.suggestion_id = suggestion_id + self.options = options @classmethod def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} valid_keys = [ - 'message_type', 'text', 'options', 'intents', 'entities', - 'suggestion_id' + 'message_type', 'text', 'intents', 'entities', 'suggestion_id', + 'options' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -1423,9 +1738,6 @@ def from_dict(cls, _dict: Dict) -> 'MessageInput': args['message_type'] = _dict.get('message_type') if 'text' in _dict: args['text'] = _dict.get('text') - if 'options' in _dict: - args['options'] = MessageInputOptions._from_dict( - _dict.get('options')) if 'intents' in _dict: args['intents'] = [ RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) @@ -1436,6 +1748,9 @@ def from_dict(cls, _dict: Dict) -> 'MessageInput': ] if 'suggestion_id' in _dict: args['suggestion_id'] = _dict.get('suggestion_id') + if 'options' in _dict: + args['options'] = MessageInputOptions._from_dict( + _dict.get('options')) return cls(**args) @classmethod @@ -1450,14 +1765,14 @@ def to_dict(self) -> Dict: _dict['message_type'] = self.message_type if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options._to_dict() if hasattr(self, 'intents') and self.intents is not None: _dict['intents'] = [x._to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x._to_dict() for x in self.entities] if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = self.options._to_dict() return _dict def _to_dict(self): @@ -1489,15 +1804,18 @@ class MessageInputOptions(): """ Optional properties that control how the assistant responds. - :attr bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. :attr bool restart: (optional) Whether to restart dialog processing at the root of the dialog, regardless of any previously visited nodes. **Note:** This does not affect `turn_count` or any other context variables. :attr bool alternate_intents: (optional) Whether to return more than one intent. Set to `true` to return all matching intents. + :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :attr bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. :attr bool return_context: (optional) Whether to return session context with the response. If you specify `true`, the response includes the `context` property. If you also specify **debug**=`true`, the returned skill context includes the @@ -1511,23 +1829,27 @@ class MessageInputOptions(): def __init__(self, *, - debug: bool = None, restart: bool = None, alternate_intents: bool = None, + spelling: 'MessageInputOptionsSpelling' = None, + debug: bool = None, return_context: bool = None, export: bool = None) -> None: """ Initialize a MessageInputOptions object. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. :param bool restart: (optional) Whether to restart dialog processing at the root of the dialog, regardless of any previously visited nodes. **Note:** This does not affect `turn_count` or any other context variables. :param bool alternate_intents: (optional) Whether to return more than one intent. Set to `true` to return all matching intents. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. :param bool return_context: (optional) Whether to return session context with the response. If you specify `true`, the response includes the `context` property. If you also specify **debug**=`true`, the returned @@ -1539,9 +1861,10 @@ def __init__(self, **Note:** If **export**=`true`, the context is returned regardless of the value of **return_context**. """ - self.debug = debug self.restart = restart self.alternate_intents = alternate_intents + self.spelling = spelling + self.debug = debug self.return_context = return_context self.export = export @@ -1550,19 +1873,23 @@ def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': """Initialize a MessageInputOptions object from a json dictionary.""" args = {} valid_keys = [ - 'debug', 'restart', 'alternate_intents', 'return_context', 'export' + 'restart', 'alternate_intents', 'spelling', 'debug', + 'return_context', 'export' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( 'Unrecognized keys detected in dictionary for class MessageInputOptions: ' + ', '.join(bad_keys)) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') if 'restart' in _dict: args['restart'] = _dict.get('restart') if 'alternate_intents' in _dict: args['alternate_intents'] = _dict.get('alternate_intents') + if 'spelling' in _dict: + args['spelling'] = MessageInputOptionsSpelling._from_dict( + _dict.get('spelling')) + if 'debug' in _dict: + args['debug'] = _dict.get('debug') if 'return_context' in _dict: args['return_context'] = _dict.get('return_context') if 'export' in _dict: @@ -1577,13 +1904,15 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug if hasattr(self, 'restart') and self.restart is not None: _dict['restart'] = self.restart if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'spelling') and self.spelling is not None: + _dict['spelling'] = self.spelling._to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug if hasattr(self, 'return_context') and self.return_context is not None: _dict['return_context'] = self.return_context if hasattr(self, 'export') and self.export is not None: @@ -1609,6 +1938,333 @@ def __ne__(self, other: 'MessageInputOptions') -> bool: return not self == other +class MessageInputOptionsSpelling(): + """ + Spelling correction options for the message. Any options specified on an individual + message override the settings configured for the skill. + + :attr bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** is + `true`, any spelling corrections are automatically applied to the user input. If + **auto_correct** is `false`, any suggested corrections are returned in the + **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property in + the workspace settings for the skill. + :attr bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned in + the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the workspace + settings for the skill. + """ + + def __init__(self, + *, + suggestions: bool = None, + auto_correct: bool = None) -> None: + """ + Initialize a MessageInputOptionsSpelling object. + + :param bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** + is `true`, any spelling corrections are automatically applied to the user + input. If **auto_correct** is `false`, any suggested corrections are + returned in the **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property + in the workspace settings for the skill. + :param bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned + in the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the + workspace settings for the skill. + """ + self.suggestions = suggestions + self.auto_correct = auto_correct + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': + """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + args = {} + valid_keys = ['suggestions', 'auto_correct'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class MessageInputOptionsSpelling: ' + + ', '.join(bad_keys)) + if 'suggestions' in _dict: + args['suggestions'] = _dict.get('suggestions') + if 'auto_correct' in _dict: + args['auto_correct'] = _dict.get('auto_correct') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputOptionsSpelling 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, 'suggestions') and self.suggestions is not None: + _dict['suggestions'] = self.suggestions + if hasattr(self, 'auto_correct') and self.auto_correct is not None: + _dict['auto_correct'] = self.auto_correct + 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 MessageInputOptionsSpelling object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputOptionsSpelling') -> 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: 'MessageInputOptionsSpelling') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageInputOptionsStateless(): + """ + Optional properties that control how the assistant responds. + + :attr bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :attr bool alternate_intents: (optional) Whether to return more than one intent. + Set to `true` to return all matching intents. + :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :attr bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. + """ + + def __init__(self, + *, + restart: bool = None, + alternate_intents: bool = None, + spelling: 'MessageInputOptionsSpelling' = None, + debug: bool = None) -> None: + """ + Initialize a MessageInputOptionsStateless object. + + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. + """ + self.restart = restart + self.alternate_intents = alternate_intents + self.spelling = spelling + self.debug = debug + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': + """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + args = {} + valid_keys = ['restart', 'alternate_intents', 'spelling', 'debug'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class MessageInputOptionsStateless: ' + + ', '.join(bad_keys)) + if 'restart' in _dict: + args['restart'] = _dict.get('restart') + if 'alternate_intents' in _dict: + args['alternate_intents'] = _dict.get('alternate_intents') + if 'spelling' in _dict: + args['spelling'] = MessageInputOptionsSpelling._from_dict( + _dict.get('spelling')) + if 'debug' in _dict: + args['debug'] = _dict.get('debug') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputOptionsStateless 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, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'spelling') and self.spelling is not None: + _dict['spelling'] = self.spelling._to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug + 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 MessageInputOptionsStateless object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputOptionsStateless') -> 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: 'MessageInputOptionsStateless') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageInputStateless(): + """ + An input object that includes the input text. + + :attr str message_type: (optional) The type of user input. Currently, only text + input is supported. + :attr str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the + user input. Include intents from the previous response to continue using those + intents rather than trying to recognize intents in the new input. + :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :attr str suggestion_id: (optional) For internal use only. + :attr MessageInputOptionsStateless options: (optional) Optional properties that + control how the assistant responds. + """ + + def __init__(self, + *, + message_type: str = None, + text: str = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + suggestion_id: str = None, + options: 'MessageInputOptionsStateless' = None) -> None: + """ + Initialize a MessageInputStateless object. + + :param str message_type: (optional) The type of user input. Currently, only + text input is supported. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param MessageInputOptionsStateless options: (optional) Optional properties + that control how the assistant responds. + """ + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.options = options + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': + """Initialize a MessageInputStateless object from a json dictionary.""" + args = {} + valid_keys = [ + 'message_type', 'text', 'intents', 'entities', 'suggestion_id', + 'options' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class MessageInputStateless: ' + + ', '.join(bad_keys)) + if 'message_type' in _dict: + args['message_type'] = _dict.get('message_type') + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + ] + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + ] + if 'suggestion_id' in _dict: + args['suggestion_id'] = _dict.get('suggestion_id') + if 'options' in _dict: + args['options'] = MessageInputOptionsStateless._from_dict( + _dict.get('options')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputStateless 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, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + _dict['intents'] = [x._to_dict() for x in self.intents] + if hasattr(self, 'entities') and self.entities is not None: + _dict['entities'] = [x._to_dict() for x in self.entities] + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = self.options._to_dict() + 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 MessageInputStateless object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputStateless') -> 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: 'MessageInputStateless') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageTypeEnum(Enum): + """ + The type of user input. Currently, only text input is supported. + """ + TEXT = "text" + + class MessageOutput(): """ Assistant output to be rendered or processed by the client. @@ -1627,6 +2283,8 @@ class MessageOutput(): :attr dict user_defined: (optional) An object containing any custom properties included in the response. This object includes any arbitrary properties defined in the dialog JSON editor as part of the dialog node output. + :attr MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ def __init__(self, @@ -1636,7 +2294,8 @@ def __init__(self, entities: List['RuntimeEntity'] = None, actions: List['DialogNodeAction'] = None, debug: 'MessageOutputDebug' = None, - user_defined: dict = None) -> None: + user_defined: dict = None, + spelling: 'MessageOutputSpelling' = None) -> None: """ Initialize a MessageOutput object. @@ -1655,6 +2314,8 @@ def __init__(self, properties included in the response. This object includes any arbitrary properties defined in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ self.generic = generic self.intents = intents @@ -1662,13 +2323,15 @@ def __init__(self, self.actions = actions self.debug = debug self.user_defined = user_defined + self.spelling = spelling @classmethod def from_dict(cls, _dict: Dict) -> 'MessageOutput': """Initialize a MessageOutput object from a json dictionary.""" args = {} valid_keys = [ - 'generic', 'intents', 'entities', 'actions', 'debug', 'user_defined' + 'generic', 'intents', 'entities', 'actions', 'debug', + 'user_defined', 'spelling' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -1696,6 +2359,9 @@ def from_dict(cls, _dict: Dict) -> 'MessageOutput': args['debug'] = MessageOutputDebug._from_dict(_dict.get('debug')) if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') + if 'spelling' in _dict: + args['spelling'] = MessageOutputSpelling._from_dict( + _dict.get('spelling')) return cls(**args) @classmethod @@ -1718,6 +2384,8 @@ def to_dict(self) -> Dict: _dict['debug'] = self.debug._to_dict() if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + _dict['spelling'] = self.spelling._to_dict() return _dict def _to_dict(self): @@ -1855,15 +2523,104 @@ class BranchExitedReasonEnum(Enum): FALLBACK = "fallback" +class MessageOutputSpelling(): + """ + Properties describing any spelling corrections in the user input that was received. + + :attr str text: (optional) The user input text that was used to generate the + response. If spelling autocorrection is enabled, this text reflects any spelling + corrections that were applied. + :attr str original_text: (optional) The original user input text. This property + is returned only if autocorrection is enabled and the user input was corrected. + :attr str suggested_text: (optional) Any suggested corrections of the input + text. This property is returned only if spelling correction is enabled and + autocorrection is disabled. + """ + + def __init__(self, + *, + text: str = None, + original_text: str = None, + suggested_text: str = None) -> None: + """ + Initialize a MessageOutputSpelling object. + + :param str text: (optional) The user input text that was used to generate + the response. If spelling autocorrection is enabled, this text reflects any + spelling corrections that were applied. + :param str original_text: (optional) The original user input text. This + property is returned only if autocorrection is enabled and the user input + was corrected. + :param str suggested_text: (optional) Any suggested corrections of the + input text. This property is returned only if spelling correction is + enabled and autocorrection is disabled. + """ + self.text = text + self.original_text = original_text + self.suggested_text = suggested_text + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': + """Initialize a MessageOutputSpelling object from a json dictionary.""" + args = {} + valid_keys = ['text', 'original_text', 'suggested_text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class MessageOutputSpelling: ' + + ', '.join(bad_keys)) + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'original_text' in _dict: + args['original_text'] = _dict.get('original_text') + if 'suggested_text' in _dict: + args['suggested_text'] = _dict.get('suggested_text') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutputSpelling 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, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'original_text') and self.original_text is not None: + _dict['original_text'] = self.original_text + if hasattr(self, 'suggested_text') and self.suggested_text is not None: + _dict['suggested_text'] = self.suggested_text + 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 MessageOutputSpelling object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'MessageOutputSpelling') -> 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: 'MessageOutputSpelling') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageResponse(): """ A response from the Watson Assistant service. :attr MessageOutput output: Assistant output to be rendered or processed by the client. - :attr MessageContext context: (optional) Context data for the conversation. The - context is stored by the assistant on a per-session basis. You can use this - property to access context variables. + :attr MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. **Note:** The context is included in message responses only if **return_context**=`true` in the message request. """ @@ -1878,8 +2635,8 @@ def __init__(self, :param MessageOutput output: Assistant output to be rendered or processed by the client. :param MessageContext context: (optional) Context data for the - conversation. The context is stored by the assistant on a per-session - basis. You can use this property to access context variables. + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. **Note:** The context is included in message responses only if **return_context**=`true` in the message request. """ @@ -1939,6 +2696,91 @@ def __ne__(self, other: 'MessageResponse') -> bool: return not self == other +class MessageResponseStateless(): + """ + A stateless response from the Watson Assistant service. + + :attr MessageOutput output: Assistant output to be rendered or processed by the + client. + :attr MessageContextStateless context: Context data for the conversation. You + can use this property to access context variables. The context is not stored by + the assistant; to maintain session state, include the context from the response + in the next message. + """ + + def __init__(self, output: 'MessageOutput', + context: 'MessageContextStateless') -> None: + """ + Initialize a MessageResponseStateless object. + + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param MessageContextStateless context: Context data for the conversation. + You can use this property to access context variables. The context is not + stored by the assistant; to maintain session state, include the context + from the response in the next message. + """ + self.output = output + self.context = context + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': + """Initialize a MessageResponseStateless object from a json dictionary.""" + args = {} + valid_keys = ['output', 'context'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class MessageResponseStateless: ' + + ', '.join(bad_keys)) + if 'output' in _dict: + args['output'] = MessageOutput._from_dict(_dict.get('output')) + else: + raise ValueError( + 'Required property \'output\' not present in MessageResponseStateless JSON' + ) + if 'context' in _dict: + args['context'] = MessageContextStateless._from_dict( + _dict.get('context')) + else: + raise ValueError( + 'Required property \'context\' not present in MessageResponseStateless JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageResponseStateless 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, 'output') and self.output is not None: + _dict['output'] = self.output._to_dict() + if hasattr(self, 'context') and self.context is not None: + _dict['context'] = self.context._to_dict() + 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 MessageResponseStateless object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'MessageResponseStateless') -> 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: 'MessageResponseStateless') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuntimeEntity(): """ The entity value that was recognized in the user input. @@ -2980,8 +3822,8 @@ class SearchResult(): :attr str url: (optional) The URL of the original data object in its native data source. :attr SearchResultHighlight highlight: (optional) An object containing segments - of text from search results with query-matching text highlighted using HTML - tags. + of text from search results with query-matching text highlighted using HTML + `` tags. """ def __init__(self, @@ -3011,7 +3853,7 @@ def __init__(self, native data source. :param SearchResultHighlight highlight: (optional) An object containing segments of text from search results with query-matching text highlighted - using HTML tags. + using HTML `` tags. """ self.id = id self.result_metadata = result_metadata @@ -3100,7 +3942,7 @@ def __ne__(self, other: 'SearchResult') -> bool: class SearchResultHighlight(): """ An object containing segments of text from search results with query-matching text - highlighted using HTML tags. + highlighted using HTML `` tags. :attr List[str] body: (optional) An array of strings containing segments taken from body text in the search results, with query-matching substrings diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 30824422a..c9782ee8a 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -243,7 +243,7 @@ def construct_full_body(self): body = dict() body['assistant_id'] = "string1" body['session_id'] = "string1" - body.update({"input": MessageInput._from_dict(json.loads("""{"message_type": "fake_message_type", "text": "fake_text", "options": {"debug": false, "restart": false, "alternate_intents": false, "return_context": true, "export": true}, "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id"}""")), "context": MessageContext._from_dict(json.loads("""{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}}, "skills": {}}""")), }) + body.update({"input": MessageInput._from_dict(json.loads("""{"message_type": "fake_message_type", "text": "fake_text", "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}""")), "context": MessageContext._from_dict(json.loads("""{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}""")), }) return body def construct_required_body(self): @@ -253,6 +253,77 @@ def construct_required_body(self): return body +#----------------------------------------------------------------------------- +# Test Class for message_stateless +#----------------------------------------------------------------------------- +class TestMessageStateless(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_stateless_response(self): + body = self.construct_full_body() + response = fake_response_MessageResponseStateless_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_message_stateless_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_MessageResponseStateless_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_message_stateless_empty(self): + check_empty_required_params(self, fake_response_MessageResponseStateless_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/assistants/{0}/message'.format(body['assistant_id']) + 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 = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2020-04-01', + ) + service.set_service_url(base_url) + output = service.message_stateless(**body) + return output + + def construct_full_body(self): + body = dict() + body['assistant_id'] = "string1" + body.update({"input": MessageInputStateless._from_dict(json.loads("""{"message_type": "fake_message_type", "text": "fake_text", "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false}}""")), "context": MessageContextStateless._from_dict(json.loads("""{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}""")), }) + return body + + def construct_required_body(self): + body = dict() + body['assistant_id'] = "string1" + return body + + # endregion ############################################################################## # End of Service: Message @@ -324,4 +395,5 @@ 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, "locale": "fake_locale", "reference_time": "fake_reference_time"}}, "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"}, "spelling": {"text": "fake_text", "original_text": "fake_original_text", "suggested_text": "fake_suggested_text"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}}""" +fake_response_MessageResponseStateless_json = """{"output": {"generic": [], "intents": [], "entities": [], "actions": [], "debug": {"nodes_visited": [], "log_messages": [], "branch_exited": false, "branch_exited_reason": "fake_branch_exited_reason"}, "spelling": {"text": "fake_text", "original_text": "fake_original_text", "suggested_text": "fake_suggested_text"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}}""" From fa2cd1b8e8c0a867e6c509875418d8c32e9e4d06 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 28 May 2020 09:30:14 -0400 Subject: [PATCH 254/455] feat(VisualRecognitionV4): add support for downloading a model file --- ibm_watson/visual_recognition_v4.py | 89 +++++++++++++++++++++++-- test/unit/test_visual_recognition_v4.py | 83 +++++++++++++++++++++-- 2 files changed, 164 insertions(+), 8 deletions(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index c7c66bdf4..d256258f7 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -365,6 +365,58 @@ def delete_collection(self, collection_id: str, response = self.send(request) return response + def get_model_file(self, collection_id: str, feature: str, + model_format: str, **kwargs) -> 'DetailedResponse': + """ + Get a model. + + Download a model that you can deploy to detect objects in images. The collection + must include a generated model, which is indicated in the response for the + collection details as `"rscnn_ready": true`. If the value is `false`, train or + retrain the collection to generate the model. + Currently, the model format is specific to Android apps. For more information + about how to deploy the model to your app, see the [Watson Visual Recognition on + Android](https://github.com/matt-ny/rscnn) project in GitHub. + + :param str collection_id: The identifier of the collection. + :param str feature: The feature for the model. + :param str model_format: The format of the returned model. + :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 feature is None: + raise ValueError('feature must be provided') + if model_format is None: + raise ValueError('model_format 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_model_file') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'feature': feature, + 'model_format': model_format + } + + url = '/v4/collections/{0}/model'.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 + ######################### # Images ######################### @@ -973,6 +1025,21 @@ class Features(Enum): OBJECTS = 'objects' +class GetModelFileEnums(object): + + class Feature(Enum): + """ + The feature for the model. + """ + OBJECTS = 'objects' + + class ModelFormat(Enum): + """ + The format of the returned model. + """ + RSCNN = 'rscnn' + + class GetJpegImageEnums(object): class Size(Enum): @@ -1732,7 +1799,7 @@ class ImageDetails(): (UTC) that the image was created. :attr ImageSource source: The source type of the image. :attr ImageDimensions dimensions: (optional) Height and width of an image. - :attr List[Error] errors: (optional) + :attr List[Error] errors: (optional) Details about the errors. :attr TrainingDataObjects training_data: (optional) Training data for all objects. """ @@ -1756,7 +1823,7 @@ def __init__(self, :param datetime created: (optional) Date and time in Coordinated Universal Time (UTC) that the image was created. :param ImageDimensions dimensions: (optional) Height and width of an image. - :param List[Error] errors: (optional) + :param List[Error] errors: (optional) Details about the errors. :param TrainingDataObjects training_data: (optional) Training data for all objects. """ @@ -2592,13 +2659,16 @@ class ObjectTrainingStatus(): :attr bool data_changed: Whether there are changes to the training data since the most recent training. :attr bool latest_failed: Whether the most recent training failed. + :attr bool rscnn_ready: Whether the model can be downloaded after the training + status is `ready`. :attr str description: Details about the training. If training is in progress, includes information about the status. If training is not in progress, includes a success message or information about why training failed. """ def __init__(self, ready: bool, in_progress: bool, data_changed: bool, - latest_failed: bool, description: str) -> None: + latest_failed: bool, rscnn_ready: bool, + description: str) -> None: """ Initialize a ObjectTrainingStatus object. @@ -2608,6 +2678,8 @@ def __init__(self, ready: bool, in_progress: bool, data_changed: bool, :param bool data_changed: Whether there are changes to the training data since the most recent training. :param bool latest_failed: Whether the most recent training failed. + :param bool rscnn_ready: Whether the model can be downloaded after the + training status is `ready`. :param str description: Details about the training. If training is in progress, includes information about the status. If training is not in progress, includes a success message or information about why training @@ -2617,6 +2689,7 @@ def __init__(self, ready: bool, in_progress: bool, data_changed: bool, self.in_progress = in_progress self.data_changed = data_changed self.latest_failed = latest_failed + self.rscnn_ready = rscnn_ready self.description = description @classmethod @@ -2625,7 +2698,7 @@ def from_dict(cls, _dict: Dict) -> 'ObjectTrainingStatus': args = {} valid_keys = [ 'ready', 'in_progress', 'data_changed', 'latest_failed', - 'description' + 'rscnn_ready', 'description' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -2656,6 +2729,12 @@ def from_dict(cls, _dict: Dict) -> 'ObjectTrainingStatus': raise ValueError( 'Required property \'latest_failed\' not present in ObjectTrainingStatus JSON' ) + if 'rscnn_ready' in _dict: + args['rscnn_ready'] = _dict.get('rscnn_ready') + else: + raise ValueError( + 'Required property \'rscnn_ready\' not present in ObjectTrainingStatus JSON' + ) if 'description' in _dict: args['description'] = _dict.get('description') else: @@ -2680,6 +2759,8 @@ def to_dict(self) -> Dict: _dict['data_changed'] = self.data_changed if hasattr(self, 'latest_failed') and self.latest_failed is not None: _dict['latest_failed'] = self.latest_failed + if hasattr(self, 'rscnn_ready') and self.rscnn_ready is not None: + _dict['rscnn_ready'] = self.rscnn_ready if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description return _dict diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index e1b9dbd56..ee589767d 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -462,6 +462,80 @@ def construct_required_body(self): return body +#----------------------------------------------------------------------------- +# Test Class for get_model_file +#----------------------------------------------------------------------------- +class TestGetModelFile(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_file_response(self): + body = self.construct_full_body() + response = fake_response_BinaryIO_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_model_file_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BinaryIO_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_model_file_empty(self): + check_empty_required_params(self, fake_response_BinaryIO_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v4/collections/{0}/model'.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='') + + def call_service(self, body): + service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version='2019-02-11', + ) + service.set_service_url(base_url) + output = service.get_model_file(**body) + return output + + def construct_full_body(self): + body = dict() + body['collection_id'] = "string1" + body['feature'] = "string1" + body['model_format'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['collection_id'] = "string1" + body['feature'] = "string1" + body['model_format'] = "string1" + return body + + # endregion ############################################################################## # End of Service: Collections @@ -1504,10 +1578,11 @@ def send_request(obj, body, response, url=None): fake_response__json = None fake_response_AnalyzeResponse_json = """{"images": [], "warnings": [], "trace": "fake_trace"}""" -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_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, "rscnn_ready": false, "description": "fake_description"}}}""" fake_response_CollectionsList_json = """{"collections": []}""" -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_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_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, "rscnn_ready": false, "description": "fake_description"}}}""" +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, "rscnn_ready": false, "description": "fake_description"}}}""" +fake_response_BinaryIO_json = """Contents of response byte-stream...""" fake_response_ImageDetailsList_json = """{"images": [], "warnings": [], "trace": "fake_trace"}""" 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": []}}""" @@ -1515,6 +1590,6 @@ def send_request(obj, body, response, url=None): 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_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, "rscnn_ready": 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": []}""" From c538bd23b28c220cec2261e9d2a770ebedbba860 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 28 May 2020 09:31:32 -0400 Subject: [PATCH 255/455] feat: regenerate services based on current API def --- ibm_watson/discovery_v2.py | 4 ++++ .../natural_language_understanding_v1.py | 18 ++++++++++++---- ibm_watson/text_to_speech_v1.py | 21 ++++++++++--------- 3 files changed, 29 insertions(+), 14 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 569b17cf7..f4341d9cb 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -585,6 +585,8 @@ def update_document(self, **Note:** This operation only works on collections created to accept direct file uploads. It cannot be used to modify a collection that connects to an external source such as Microsoft SharePoint. + **Note:** If an uploaded document is segmented, all segments will be overwritten, + even if the updated version of the document has fewer segments. :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. @@ -665,6 +667,8 @@ def delete_document(self, **Note:** This operation only works on collections created to accept direct file uploads. It cannot be used to modify a collection that connects to an external source such as Microsoft SharePoint. + **Note:** Segments of an uploaded document cannot be deleted individually. Delete + all segments by deleting using the `parent_document_id` of a segment result. :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index d1ab59e6d..22ee86f76 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -2701,8 +2701,10 @@ class Model(): :attr str description: (optional) Model description. :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. - :attr str version: (optional) The model version, if it was manually provided in - Watson Knowledge Studio. + :attr str model_version: (optional) The model version, if it was manually + provided in Watson Knowledge Studio. + :attr str version: (optional) (Deprecated — use `model_version`) The model + version, if it was manually provided in Watson Knowledge Studio. :attr str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. :attr datetime created: (optional) A dateTime indicating when the model was @@ -2716,6 +2718,7 @@ def __init__(self, language: str = None, description: str = None, workspace_id: str = None, + model_version: str = None, version: str = None, version_description: str = None, created: datetime = None) -> None: @@ -2730,8 +2733,10 @@ def __init__(self, :param str description: (optional) Model description. :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. - :param str version: (optional) The model version, if it was manually + :param str model_version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. + :param str version: (optional) (Deprecated — use `model_version`) The model + version, if it was manually provided in Watson Knowledge Studio. :param str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. :param datetime created: (optional) A dateTime indicating when the model @@ -2742,6 +2747,7 @@ def __init__(self, self.language = language self.description = description self.workspace_id = workspace_id + self.model_version = model_version self.version = version self.version_description = version_description self.created = created @@ -2752,7 +2758,7 @@ def from_dict(cls, _dict: Dict) -> 'Model': args = {} valid_keys = [ 'status', 'model_id', 'language', 'description', 'workspace_id', - 'version', 'version_description', 'created' + 'model_version', 'version', 'version_description', 'created' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -2769,6 +2775,8 @@ def from_dict(cls, _dict: Dict) -> 'Model': args['description'] = _dict.get('description') if 'workspace_id' in _dict: args['workspace_id'] = _dict.get('workspace_id') + if 'model_version' in _dict: + args['model_version'] = _dict.get('model_version') if 'version' in _dict: args['version'] = _dict.get('version') if 'version_description' in _dict: @@ -2795,6 +2803,8 @@ def to_dict(self) -> Dict: _dict['description'] = self.description if hasattr(self, 'workspace_id') and self.workspace_id is not None: _dict['workspace_id'] = self.workspace_id + if hasattr(self, 'model_version') and self.model_version is not None: + _dict['model_version'] = self.model_version if hasattr(self, 'version') and self.version is not None: _dict['version'] = self.version if hasattr( diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 7dd168947..6fb28a941 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -19,16 +19,17 @@ dialects, and voices. The service supports at least one male or female voice, sometimes both, for each language. The audio is streamed back to the client with minimal delay. For speech synthesis, the service supports a synchronous HTTP Representational State -Transfer (REST) interface. It also supports a WebSocket interface that provides both plain -text and SSML input, including the SSML <mark> element and word timings. SSML is an -XML-based markup language that provides text annotation for speech-synthesis applications. -The service also offers a customization interface. You can use the interface to define -sounds-like or phonetic translations for words. A sounds-like translation consists of one -or more words that, when combined, sound like the word. A phonetic translation is based on -the SSML phoneme format for representing a word. You can specify a phonetic translation in -standard International Phonetic Alphabet (IPA) representation or in the proprietary IBM -Symbolic Phonetic Representation (SPR). The Arabic, Chinese, Dutch, and Korean languages -support only IPA. +Transfer (REST) interface and a WebSocket interface. Both interfaces support plain text +and SSML input. SSML is an XML-based markup language that provides text annotation for +speech-synthesis applications. The WebSocket interface also supports the SSML +<mark> element and word timings. +The service offers a customization interface that you can use to define sounds-like or +phonetic translations for words. A sounds-like translation consists of one or more words +that, when combined, sound like the word. A phonetic translation is based on the SSML +phoneme format for representing a word. You can specify a phonetic translation in standard +International Phonetic Alphabet (IPA) representation or in the proprietary IBM Symbolic +Phonetic Representation (SPR). The Arabic, Chinese, Dutch, and Korean languages support +only IPA. """ import json From 1b1a1c7e66ce689bfc04305bacd16f09975f990c Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 28 May 2020 11:11:02 -0400 Subject: [PATCH 256/455] test: update creds for vis rec tests --- .env.enc | Bin 1840 -> 1840 bytes .../integration/test_visual_recognition_v3.py | 2 +- .../integration/test_visual_recognition_v4.py | 9 +++++---- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/.env.enc b/.env.enc index 9af01f6f5eec6e1459ccd45018d0ae0d47126089..ccff317bca9a941e6ed4397440483ae562200127 100644 GIT binary patch literal 1840 zcmV-02haGORQQ-Vd!QK;?YHFc;kFDvhQqOpSdDrC!Y00B_uBr0fZ%NRd7RBttnr$> zdvkKk8FQPGwICK_xLTfSd}Hp9ax8osXqG(M-WB#JCYB>aL8cd&9MbV}q;6$}=t)mz z$*#i@1oL)zti+BTgmpQVsrcpY`Hh|>8Yf+0;sTInWkb$T9n8wGKCcumHMry6d;fIH zjvt5lx*RM4;6Vc5`?{=EXu#1~4r0l#v(#|t5CAe2ZSWbbk@zDrBCJ`d@+26&Z91x}> zN8*oASNCZWHdglN*~LG89QQ#Ss4>D_F&{eMnvOFGC=_uaEP=L8=VRF2=UIstTj2G$IkG^7pO&i3!;Pz!M#_T{JI-&j4?90oZ z#N7~hnn{HL{tZglUR#Gn4Hcj(>cXlh+}NyIe$4Gm^8^a3%<{BZoE1=_LJHR<-{(a5H8p4i<8$VghNrFm`& zL*1L8J)Jmju5cMD9?_<69FA&j4|$?0^wVRFt6uRAaxL@_!T3Ajx|;D#uTQJlR8Aqk zN)#14vAPTq1}vt0CbR4ku!)EWJE&(f=U^c47!-X}vsSV3@A}FcQU}x#21~aW8O>^` zKKjLGLXb^h$4CCmC`<3=Mkmz%m>_h(Nz!yx4DMpk*odp1spMGvVNpL5sUCVvV+U_5 zzf!0&8`lRy|B0~!2d;dX-wv=*N(Ah1YC;fnGfC9=9x|Hgup0nmNV>IJ#1w)f3=}XR zHm~+gF)@S|4y5|m)WzZ3DDzgZv{w=y`auw z$^);KJ)04>R2JiB=N;JLjv*sSZ?M9YBd%m;+}$;O;` zyY`8RI@9n)Oxux!5}om#o016Z1<>Xgk|9YVAw~8m4>tb+yh>4_h)pZzqMqMO9J(e$ zXJ)ajW@3WmlmJ~WII+UO8}lGHCTm@^_n7o6!GUT0mo=O>e;LxZv8W}N?^aRPZQRdr!i@TEdrR(+x=Vemu zp*mwIGg#ZSjisj!0yPP%FpE;e4oSbeF(w*vdrz%WrcUOu{Guv8dG(tPdhL?`A!J+1 z>_{z6C)Hv*;0aZA(>F=GID2MrU%sv4+HNgXG6{EaY(1(AQ97ZmC;pVOQ`QqBBoRh$ zVUPhEK30hr{A*i>f3rsM0tH6-#_7rGb^Hafxerjd9k{YJ>Y^o%PnJ0~kOr8&fm-Nj zoTKlc@J%ydUJd4QCN34u^zzn)M}UDV^TTJDBe@u`FP zO=T8C(pwX1UJIf%Of$Nm(j^?V!aJ^egEHBm@r|B-14z#n?;S@ojiQxNnzz_H7uIYw zgM9_ShWUd(-6J@!YC`~UJ3f93@xv5}5`vdl*g+S)U><;uoiAa;V&jNC8cpf&n0f=y zLqXH-F7R>!o}A!M=E7oXx$|9QM{+WG}+0RT?E=n*dMPmu9Mp zCF28o9ST(SLm!C2T7ib#z2&hl$4@Hu*~waYNMWazUS#RzXl^B*>Mo#t8d(u25n=&0 z(FJ`&L#+;C*pM`nSUd;{27)sq5`{UOdN^{*?Vj8V<#E+oV)t+K^Drj;}@vhnQh zm8fo#O7xsN@0_k5CAmZKFoi|B;W*dmZN4G%_8T*qvI&xo7Nj>i0(yg?_4Uh3SSmg-+ z;af6yN)PX{*8|*3YIf-q9dPpv(=M_IB*xHa2I*z{8K(F?CGta=|7js3`m)+R{Lbr_ zbSvO*naOM%${v%wMA20wVCZ%Nwhi?S1D6XU(_nAR{Yc1h5QYNBf`XwehuKsY)Pa`8C&^8S9xSSDxaSmzp0En&G3? z;*`94lxhuaF8Y-h*HrFWkCE?7KtrVbiW$TS?;f*;#8^B9?8q&5?{NxAa?{j4`?P5! zUx%zHPBmJC2S*(;XEu)7wq4CO4EbOu$A8Z3RKNO^ZzRM}(VGXAmQ>JqV4H$}dL#>8&U4GFxw%O!CRU!Y@jLuE-kC9ok+|KQ06?dO06oiL5w` z;Z50<%N^%*{-Lx*UvV*a`cGO?&_ zIXvshS&?h&uhT?Ml6MKVgo5y`P-?Ki$1C@WG;(pHUpJu+K~){(bx=_|NYY>^``JPu zp=wu_6f8~l;}e0RM4*XZd472BFDn@Jv#^5}*%JRe%TjD&v_+rI;YJ$4N$Pg%k>y_Z z`*o{;YV>b6b7zAB4)($NJiMfna5Z@w4Qlg5p!52P(B-86sWN|fEZ>0d?!V8^-hK31 z7NH;Q?n8>%9i5+tv`0C^2!XY&0^BmX>T3E z9|2fD??NmD-_c=DtEBZj11=M@mXaA`GHgh>6m)k0nXPmo;u&acbg_FFGzRD2Qu_+U z;&4a7U+7|}4x`3FPI4wayhWMVQ`O|1FtPqP)jbn9AQcOw!=bG>fi7N2KoiBlAY&-{ zOVjZhtW8a`+3iDEqgR$kNUYm>5erlfE72pHu8B zGLABmNO~7`z4HRgy41L(DO*(~N3q?FzJzh=KWU9r=0s%H-1&Y#@Ofx@`^h}wb4|6m z@S|O)WWa??P75r(isvj@#D5XE-6FuUo0wPx3@>tFqlTA3$%O>!8#v>tA;o7=F16js zE{~1h1+e;8n7JMTH0r*_IlCiXfUykvnY<@bGZx+JH^`yx5-f~7lk z^gGX=!3dXhf3Jlwm&7JhW6&RJ$@~{vlqi1jwvh6@I+(tVwxLo3=9oZjw&gMP@S>6h?zbEF>t#d eljlX6>!k^lK77lL_*pt-2JQH<$RLAMk^ib@WRdm& diff --git a/test/integration/test_visual_recognition_v3.py b/test/integration/test_visual_recognition_v3.py index b74fe6c3c..1dff4ee0c 100644 --- a/test/integration/test_visual_recognition_v3.py +++ b/test/integration/test_visual_recognition_v3.py @@ -19,7 +19,7 @@ def setup_class(cls): 'X-Watson-Learning-Opt-Out': '1', 'X-Watson-Test': '1' }) - cls.classifier_id = 'sdkxtestxclassifierxdoxnotxdel_1089651138' + cls.classifier_id = 'sdk-classifier-do-not-delete_1118105040' def test_classify(self): dog_path = abspath('resources/dog.jpg') diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index c78f7636d..577571002 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -19,7 +19,7 @@ def setup_class(cls): 'X-Watson-Learning-Opt-Out': '1', 'X-Watson-Test': '1' }) - cls.collection_id = '9e5d8394-e9d2-4b53-b88f-da6fce7ad4e3' + cls.collection_id = 'a06f7036-0529-49ee-bdf6-82ddec276923' def test_01_colllections(self): # collection = self.visual_recognition.create_collection( @@ -30,7 +30,7 @@ def test_01_colllections(self): my_collection = self.visual_recognition.get_collection( collection_id=self.collection_id).get_result() assert my_collection is not None - assert my_collection.get('name') == 'do-not-delete-sdk-collection' + assert my_collection.get('name') == 'sdk-collection-do-not-delete' # updated_collection = self.visual_recognition.update_collection( # collection_id=self.collection_id, @@ -58,9 +58,10 @@ def test_02_images(self): # assert add_images is not None # image_id = add_images.get('images')[0].get('image_id') - image_id = 'South_Africa_Luca_Galuzzi_2004_202349062c2307571a3f7edc71fe819f' + image_id = 'giraffe_00_202349062c2307571a3f7edc71fe819f' list_images = self.visual_recognition.list_images( self.collection_id).get_result() + print(list_images) assert list_images is not None image_details = self.visual_recognition.get_image_details( @@ -116,7 +117,7 @@ def test_04_objects_and_training(self): # assert add_images_result is not None # image_id = add_images_result.get('images')[0].get('image_id') # assert image_id is not None - image_id = '1280px-Giraffe_Ithala_KZN_South_202349062c2307571a3f7edc71fe819f' + image_id = 'giraffe_00_202349062c2307571a3f7edc71fe819f' # add image training data training_data = self.visual_recognition.add_image_training_data( From 421482d730d7be04642459c9799b719c279714e5 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 28 May 2020 12:59:33 -0400 Subject: [PATCH 257/455] refactor: update assistant context skill and vis rec v4 tests --- ibm_watson/assistant_v2.py | 5 +- .../integration/test_visual_recognition_v4.py | 49 +++++++++---------- 2 files changed, 26 insertions(+), 28 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 8e0da3ad0..c0a3cb07e 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1368,14 +1368,13 @@ class MessageContextSkill(): :attr dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. - :attr MessageContextSkillSystem system: (optional) System context data used by - the skill. + :attr dict system: (optional) System context data used by the skill. """ def __init__(self, *, user_defined: dict = None, - system: 'MessageContextSkillSystem' = None) -> None: + system: dict = None) -> None: """ Initialize a MessageContextSkill object. diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index 577571002..91b2a242f 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -48,17 +48,15 @@ def test_02_images(self): # name='my_collection', description='just for fun').get_result() # collection_id = collection.get('collection_id') - # add_images = self.visual_recognition.add_images( - # self.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" - # ], - # ).get_result() - # assert add_images is not None - # image_id = add_images.get('images')[0].get('image_id') - - image_id = 'giraffe_00_202349062c2307571a3f7edc71fe819f' + add_images = self.visual_recognition.add_images( + self.collection_id, + image_url=[ + "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( self.collection_id).get_result() print(list_images) @@ -72,7 +70,7 @@ def test_02_images(self): self.collection_id, image_id).get_result() assert response.content is not None - # self.visual_recognition.delete_image(self.collection_id, image_id) + self.visual_recognition.delete_image(self.collection_id, image_id) # self.visual_recognition.delete_collection(collection_id) def test_03_analyze(self): @@ -105,19 +103,18 @@ def test_04_objects_and_training(self): # 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: - # add_images_result = self.visual_recognition.add_images( - # self.collection_id, - # images_file=[FileWithMetadata(giraffe_info)], - # ).get_result() - # assert add_images_result is not None - # image_id = add_images_result.get('images')[0].get('image_id') - # assert image_id is not None - image_id = 'giraffe_00_202349062c2307571a3f7edc71fe819f' + 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( + self.collection_id, + images_file=[FileWithMetadata(giraffe_info)], + ).get_result() + assert add_images_result is not None + image_id = add_images_result.get('images')[0].get('image_id') + assert image_id is not None # add image training data training_data = self.visual_recognition.add_image_training_data( @@ -164,5 +161,7 @@ def test_04_objects_and_training(self): self.visual_recognition.delete_object( self.collection_id, object='updated giraffe training data') + self.visual_recognition.delete_image(self.collection_id, image_id) + # delete collection # self.visual_recognition.delete_collection(collection_id) From 87b145e5e0de613b31964af13064082005ea0f0c Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 4 Jun 2020 08:50:38 -0400 Subject: [PATCH 258/455] test: refactor vis rec v4 test after new instance --- .../integration/test_visual_recognition_v4.py | 81 +++++++++---------- 1 file changed, 39 insertions(+), 42 deletions(-) diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index 91b2a242f..96d07f8c2 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -19,38 +19,38 @@ def setup_class(cls): 'X-Watson-Learning-Opt-Out': '1', 'X-Watson-Test': '1' }) - cls.collection_id = 'a06f7036-0529-49ee-bdf6-82ddec276923' def test_01_colllections(self): - # collection = self.visual_recognition.create_collection( - # name='my_collection', description='just for fun').get_result() - # collection_id = collection.get('collection_id') - # assert collection_id is not None + collection = self.visual_recognition.create_collection( + 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=self.collection_id).get_result() + collection_id=collection.get('collection_id')).get_result() assert my_collection is not None - assert my_collection.get('name') == 'sdk-collection-do-not-delete' + assert my_collection.get('name') == 'my_collection' - # updated_collection = self.visual_recognition.update_collection( - # collection_id=self.collection_id, - # description='new description').get_result() - # assert updated_collection is not None + updated_collection = self.visual_recognition.update_collection( + collection_id=collection_id, + description='new description').get_result() + assert updated_collection is not None collections = self.visual_recognition.list_collections().get_result( ).get('collections') assert collections is not None - # self.visual_recognition.delete_collection(collection_id=collection_id) + 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() - # collection_id = collection.get('collection_id') + collection = self.visual_recognition.create_collection( + name='my_collection', description='just for fun').get_result() + collection_id = collection.get('collection_id') add_images = self.visual_recognition.add_images( - self.collection_id, + 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" ], ).get_result() @@ -58,20 +58,19 @@ def test_02_images(self): image_id = add_images.get('images')[0].get('image_id') list_images = self.visual_recognition.list_images( - self.collection_id).get_result() - print(list_images) + collection_id).get_result() assert list_images is not None image_details = self.visual_recognition.get_image_details( - self.collection_id, image_id).get_result() + collection_id, image_id).get_result() assert image_details is not None response = self.visual_recognition.get_jpeg_image( - self.collection_id, image_id).get_result() + collection_id, image_id).get_result() assert response.content is not None - self.visual_recognition.delete_image(self.collection_id, image_id) - # self.visual_recognition.delete_collection(collection_id) + 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__), @@ -82,7 +81,7 @@ def test_03_analyze(self): with open(dog_path, 'rb') as dog_file, open(giraffe_path, 'rb') as giraffe_files: analyze_images = self.visual_recognition.analyze( - collection_ids=[self.collection_id], + collection_ids=['a06f7036-0529-49ee-bdf6-82ddec276923'], features=[AnalyzeEnums.Features.OBJECTS.value], images_file=[ FileWithMetadata(dog_file), @@ -95,12 +94,12 @@ def test_03_analyze(self): print(json.dumps(analyze_images, indent=2)) def test_04_objects_and_training(self): - # create a collection - # my_collection = self.visual_recognition.create_collection( - # name='my_test_collection', - # description='testing for python').get_result() - # collection_id = my_collection.get('collection_id') - # assert collection_id is not None + # create a classifier + my_collection = self.visual_recognition.create_collection( + name='my_test_collection', + description='testing for python').get_result() + collection_id = my_collection.get('collection_id') + assert collection_id is not None # add images with open( @@ -109,7 +108,7 @@ def test_04_objects_and_training(self): '../../resources/South_Africa_Luca_Galuzzi_2004.jpeg'), 'rb') as giraffe_info: add_images_result = self.visual_recognition.add_images( - self.collection_id, + collection_id, images_file=[FileWithMetadata(giraffe_info)], ).get_result() assert add_images_result is not None @@ -118,7 +117,7 @@ def test_04_objects_and_training(self): # add image training data training_data = self.visual_recognition.add_image_training_data( - self.collection_id, + collection_id, image_id, objects=[ TrainingDataObject(object='giraffe training data', @@ -128,40 +127,38 @@ def test_04_objects_and_training(self): # list objects metadata object_metadata_list = self.visual_recognition.list_object_metadata( - collection_id=self.collection_id).get_result() + 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=self.collection_id, + 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=self.collection_id, + 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(self.collection_id).get_result() + 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() - # assert training_usage is not None + 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( - self.collection_id, object='updated giraffe training data') - - self.visual_recognition.delete_image(self.collection_id, image_id) + collection_id, object='updated giraffe training data') # delete collection - # self.visual_recognition.delete_collection(collection_id) + self.visual_recognition.delete_collection(collection_id) From b4faa529ea38dbec94cf80d50609813e509c2b1a Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 4 Jun 2020 14:30:56 +0000 Subject: [PATCH 259/455] =?UTF-8?q?Bump=20version:=204.4.1=20=E2=86=92=204?= =?UTF-8?q?.5.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 3 +-- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 77e1c749b..8d4e2c603 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.4.1 +current_version = 4.5.0 commit = True [bumpversion:file:ibm_watson/version.py] @@ -9,4 +9,3 @@ replace = __version__ = '{new_version}' [bumpversion:file:setup.py] search = __version__ = '{current_version}' replace = __version__ = '{new_version}' - diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 6dd6cf9b2..330025d80 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.4.1' +__version__ = '4.5.0' diff --git a/setup.py b/setup.py index ab203c1bd..a18cc4a0d 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.4.1' +__version__ = '4.5.0' if sys.argv[-1] == 'publish': From e0b10797883fb3a920a666e114e502701a6e6a5f Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 4 Jun 2020 14:30:56 +0000 Subject: [PATCH 260/455] chore(release): 4.5.0 release notes # [4.5.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.4.1...v4.5.0) (2020-06-04) ### Features * regenerate services based on current API def ([c538bd2](https://github.com/watson-developer-cloud/python-sdk/commit/c538bd23b28c220cec2261e9d2a770ebedbba860)) * **AssistantV1:** add support for spelling suggestions ([858af78](https://github.com/watson-developer-cloud/python-sdk/commit/858af780c60edcff5e6c47281f23d3d9c5011861)) * **AssistantV2:** add support for stateless messages ([c57f248](https://github.com/watson-developer-cloud/python-sdk/commit/c57f248ea920c12bb439b5571ae78fcce144707b)) * **VisualRecognitionV4:** add support for downloading a model file ([fa2cd1b](https://github.com/watson-developer-cloud/python-sdk/commit/fa2cd1b8e8c0a867e6c509875418d8c32e9e4d06)) --- CHANGELOG.md | 10 +++ package-lock.json | 160 +++++++++++++++++++++++----------------------- 2 files changed, 90 insertions(+), 80 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 05c413e86..9cdbe2f7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,13 @@ +# [4.5.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.4.1...v4.5.0) (2020-06-04) + + +### Features + +* regenerate services based on current API def ([c538bd2](https://github.com/watson-developer-cloud/python-sdk/commit/c538bd23b28c220cec2261e9d2a770ebedbba860)) +* **AssistantV1:** add support for spelling suggestions ([858af78](https://github.com/watson-developer-cloud/python-sdk/commit/858af780c60edcff5e6c47281f23d3d9c5011861)) +* **AssistantV2:** add support for stateless messages ([c57f248](https://github.com/watson-developer-cloud/python-sdk/commit/c57f248ea920c12bb439b5571ae78fcce144707b)) +* **VisualRecognitionV4:** add support for downloading a model file ([fa2cd1b](https://github.com/watson-developer-cloud/python-sdk/commit/fa2cd1b8e8c0a867e6c509875418d8c32e9e4d06)) + ## [4.4.1](https://github.com/watson-developer-cloud/python-sdk/compare/v4.4.0...v4.4.1) (2020-05-11) diff --git a/package-lock.json b/package-lock.json index bf3323635..1c9dd997c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3,24 +3,24 @@ "lockfileVersion": 1, "dependencies": { "@babel/code-frame": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz", - "integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==", + "version": "7.10.1", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.1.tgz", + "integrity": "sha512-IGhtTmpjGbYzcEDOw7DcQtbQSXcG9ftmAXtWTu9V936vDye4xjjekktFAtgZsWpzTj/X01jocB46mTywm/4SZw==", "requires": { - "@babel/highlight": "^7.8.3" + "@babel/highlight": "^7.10.1" } }, "@babel/helper-validator-identifier": { - "version": "7.9.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.9.5.tgz", - "integrity": "sha512-/8arLKUFq882w4tWGj9JYzRpAlZgiWUJ+dtteNTDqrRBz9Iguck9Rn3ykuBDoUwh2TO4tSAJlrxDUOXWklJe4g==" + "version": "7.10.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.10.1.tgz", + "integrity": "sha512-5vW/JXLALhczRCWP0PnFDMCJAchlBvM7f4uk/jXritBnIa6E1KmqmtrS3yn1LAnxFBypQ3eneLuXjsnfQsgILw==" }, "@babel/highlight": { - "version": "7.9.0", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.9.0.tgz", - "integrity": "sha512-lJZPilxX7Op3Nv/2cvFdnlepPXDxi29wxteT57Q965oc5R9v86ztx0jfxVrTcBk8C2kcPkkDa2Z4T3ZsPPVWsQ==", + "version": "7.10.1", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.10.1.tgz", + "integrity": "sha512-8rMof+gVP8mxYZApLF/JgNDAkdKa+aJt3ZYxF8z6+j/hpeXL7iMsKCPHa2jNMHu/qqBwzQF4OHNoYi8dMA/rYg==", "requires": { - "@babel/helper-validator-identifier": "^7.9.0", + "@babel/helper-validator-identifier": "^7.10.1", "chalk": "^2.0.0", "js-tokens": "^4.0.0" } @@ -49,52 +49,52 @@ } }, "@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==", + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.1.tgz", + "integrity": "sha512-NB81O5h39KfHYGtgfWr2booRxp2bWOJoqbWwbyUg2hw6h35ArWYlAST5B3XwAkbdcx13yt84hFXyFP5X0QToWA==", "requires": { - "@octokit/types": "^2.0.0" + "@octokit/types": "^4.0.1" } }, "@octokit/core": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-2.5.0.tgz", - "integrity": "sha512-uvzmkemQrBgD8xuGbjhxzJN1darJk9L2cS+M99cHrDG2jlSVpxNJVhoV86cXdYBqdHCc9Z995uLCczaaHIYA6Q==", + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-2.5.3.tgz", + "integrity": "sha512-23AHK9xBW0v79Ck8h5U+5iA4MW7aosqv+Yr6uZXolVGNzzHwryNH5wM386/6+etiKUTwLFZTqyMU9oQpIBZcFA==", "requires": { "@octokit/auth-token": "^2.4.0", "@octokit/graphql": "^4.3.1", "@octokit/request": "^5.4.0", - "@octokit/types": "^2.0.0", + "@octokit/types": "^4.0.1", "before-after-hook": "^2.1.0", "universal-user-agent": "^5.0.0" } }, "@octokit/endpoint": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.1.tgz", - "integrity": "sha512-pOPHaSz57SFT/m3R5P8MUu4wLPszokn5pXcB/pzavLTQf2jbU+6iayTvzaY6/BiotuRS0qyEUkx3QglT4U958A==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.2.tgz", + "integrity": "sha512-xs1mmCEZ2y4shXCpFjNq3UbmNR+bLzxtZim2L0zfEtj9R6O6kc4qLDvYw66hvO6lUsYzPTM5hMkltbuNAbRAcQ==", "requires": { - "@octokit/types": "^2.11.1", + "@octokit/types": "^4.0.1", "is-plain-object": "^3.0.0", "universal-user-agent": "^5.0.0" } }, "@octokit/graphql": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.4.0.tgz", - "integrity": "sha512-Du3hAaSROQ8EatmYoSAJjzAz3t79t9Opj/WY1zUgxVUGfIKn0AEjg+hlOLscF6fv6i/4y/CeUvsWgIfwMkTccw==", + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.0.tgz", + "integrity": "sha512-StJWfn0M1QfhL3NKBz31e1TdDNZrHLLS57J2hin92SIfzlOVBuUaRkp31AGkGOAFOAVtyEX6ZiZcsjcJDjeb5g==", "requires": { "@octokit/request": "^5.3.0", - "@octokit/types": "^2.0.0", + "@octokit/types": "^4.0.1", "universal-user-agent": "^5.0.0" } }, "@octokit/plugin-paginate-rest": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.2.0.tgz", - "integrity": "sha512-KoNxC3PLNar8UJwR+1VMQOw2IoOrrFdo5YOiDKnBhpVbKpw+zkBKNMNKwM44UWL25Vkn0Sl3nYIEGKY+gW5ebw==", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.2.1.tgz", + "integrity": "sha512-/tHpIF2XpN40AyhIq295YRjb4g7Q5eKob0qM3thYJ0Z+CgmNsWKM/fWse/SUR8+LdprP1O4ZzSKQE+71TCwK+w==", "requires": { - "@octokit/types": "^2.12.1" + "@octokit/types": "^4.0.1" } }, "@octokit/plugin-request-log": { @@ -103,22 +103,22 @@ "integrity": "sha512-ywoxP68aOT3zHCLgWZgwUJatiENeHE7xJzYjfz8WI0goynp96wETBF+d95b8g/uL4QmS6owPVlaxiz3wyMAzcw==" }, "@octokit/plugin-rest-endpoint-methods": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-3.10.0.tgz", - "integrity": "sha512-Z2DBsdnkWKuVBVFiLoEUKP/82ylH4Ij5F1Mss106hnQYXTxDfCWAyHW+hJ6ophuHVJ9Flaaue3fYn4CggzkHTg==", + "version": "3.14.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-3.14.0.tgz", + "integrity": "sha512-KTLPiXZ45WaDNilFUN3+o2pns0vFWkcWLsKf8mw3Z7AJTST7mI3ukoDk2bJ0FPnLTCHvQYR1qrwMFp8UShR7cQ==", "requires": { - "@octokit/types": "^2.14.0", + "@octokit/types": "^4.1.5", "deprecation": "^2.3.1" } }, "@octokit/request": { - "version": "5.4.2", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.2.tgz", - "integrity": "sha512-zKdnGuQ2TQ2vFk9VU8awFT4+EYf92Z/v3OlzRaSh4RIP0H6cvW1BFPXq4XYvNez+TPQjqN+0uSkCYnMFFhcFrw==", + "version": "5.4.4", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.4.tgz", + "integrity": "sha512-vqv1lz41c6VTxUvF9nM+a6U+vvP3vGk7drDpr0DVQg4zyqlOiKVrY17DLD6de5okj+YLHKcoqaUZTBtlNZ1BtQ==", "requires": { "@octokit/endpoint": "^6.0.1", "@octokit/request-error": "^2.0.0", - "@octokit/types": "^2.11.1", + "@octokit/types": "^4.0.1", "deprecation": "^2.0.0", "is-plain-object": "^3.0.0", "node-fetch": "^2.3.0", @@ -127,30 +127,30 @@ } }, "@octokit/request-error": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.0.tgz", - "integrity": "sha512-rtYicB4Absc60rUv74Rjpzek84UbVHGHJRu4fNVlZ1mCcyUPPuzFfG9Rn6sjHrd95DEsmjSt1Axlc699ZlbDkw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.1.tgz", + "integrity": "sha512-5lqBDJ9/TOehK82VvomQ6zFiZjPeSom8fLkFVLuYL3sKiIb5RB8iN/lenLkY7oBmyQcGP7FBMGiIZTO8jufaRQ==", "requires": { - "@octokit/types": "^2.0.0", + "@octokit/types": "^4.0.1", "deprecation": "^2.0.0", "once": "^1.4.0" } }, "@octokit/rest": { - "version": "17.8.0", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-17.8.0.tgz", - "integrity": "sha512-m2pdo9+DoEoqQ7wRXV1ihffhE1gbvoC20nvchphluEusbZI6Y9HyXABGiXL+mByy2uUMR2cgBDqBJQQ6bY8Uvg==", + "version": "17.9.3", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-17.9.3.tgz", + "integrity": "sha512-by1mGtNX4I5CFQDr8rN6lquE+EvEk1IstoJHUb3BmEPMMo27ftvYMHZjm1sl7f39sZlH26B0vcJWbWiDZFcsNQ==", "requires": { "@octokit/core": "^2.4.3", "@octokit/plugin-paginate-rest": "^2.2.0", "@octokit/plugin-request-log": "^1.0.0", - "@octokit/plugin-rest-endpoint-methods": "3.10.0" + "@octokit/plugin-rest-endpoint-methods": "^3.14.0" } }, "@octokit/types": { - "version": "2.15.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-2.15.0.tgz", - "integrity": "sha512-0mnpenB8rLhBVu8VUklp38gWi+EatjvcEcLWcdProMKauSaQWWepOAybZ714sOGsEyhXPlIcHICggn8HUsCXVw==", + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-4.1.6.tgz", + "integrity": "sha512-/gN/VeZirpFb0GIpbDF6SgtfDp9EQ+ymqPf595wjRkEoRgkrCnJGctGAd8MrynStBvYRmMWF1P64qzZFzhW7Vg==", "requires": { "@types/node": ">= 8" } @@ -200,9 +200,9 @@ } }, "@semantic-release/github": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-7.0.5.tgz", - "integrity": "sha512-1nJCMeomspRIXKiFO3VXtkUMbIBEreYLFNBdWoLjvlUNcEK0/pEbupEZJA3XHfJuSzv43u3OLpPhF/JBrMuv+A==", + "version": "7.0.7", + "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-7.0.7.tgz", + "integrity": "sha512-Sai2UucYQ+5rJzKVEVJ4eiZNDdoo0/CzfpValBdeU5h97uJE7t4CoBTmUWkiXlPOx46CSw1+JhI+PHC1PUxVZw==", "requires": { "@octokit/rest": "^17.0.0", "@semantic-release/error": "^2.2.0", @@ -228,9 +228,9 @@ "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==" }, "@types/node": { - "version": "13.13.5", - "resolved": "https://registry.npmjs.org/@types/node/-/node-13.13.5.tgz", - "integrity": "sha512-3ySmiBYJPqgjiHA7oEaIo2Rzz0HrOZ7yrNO5HWyaE5q0lQ3BppDZ3N53Miz8bw2I7gh1/zir2MGVZBvpb1zq9g==" + "version": "14.0.10", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.0.10.tgz", + "integrity": "sha512-Bz23oN/5bi0rniKT24ExLf4cK0JdvN3dH/3k0whYkdN4eI4vS2ZW/2ENNn2uxHCzWcbdHIa/GRuWQytfzCjRYw==" }, "@types/retry": { "version": "0.12.0", @@ -319,9 +319,9 @@ "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=" }, "cross-spawn": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.2.tgz", - "integrity": "sha512-PD6G8QG3S4FK/XCGFbEQrDqO2AnMMsy0meR7lerlIOHAAbkuavGU/pOqprrlvfTNjvowivTeBsjebAL0NSoMxw==", + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "requires": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", @@ -371,9 +371,9 @@ "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, "execa": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.1.tgz", - "integrity": "sha512-SCjM/zlBdOK8Q5TIjOn6iEHZaPHFsMoTxXQ2nvUvtPnuohz3H2dIozSg+etNR98dGoYUp2ENSKLL/XaMmbxVgw==", + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.2.tgz", + "integrity": "sha512-QI2zLa6CjGWdiQsmSkZoGtDx2N+cQIGb3yNolGTdjSQzydzLgYYf8LRuagp7S7fPimjcrzUDSUFd/MgzELMi4Q==", "requires": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", @@ -400,9 +400,9 @@ } }, "fastq": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.7.0.tgz", - "integrity": "sha512-YOadQRnHd5q6PogvAR/x62BGituF2ufiEA6s8aavQANw5YKHERI4AREboX6KotzP8oX2klxYF2wcV/7bn1clfQ==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.8.0.tgz", + "integrity": "sha512-SMIZoZdLh/fgofivvIkmknUXyPnvxRE3DhtZ5Me3Mrsk5gyPL42F0xr51TdRXskBxHfMp+07bcYzfsYEsSQA9Q==", "requires": { "reusify": "^1.0.4" } @@ -416,9 +416,9 @@ } }, "fs-extra": { - "version": "9.0.0", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.0.0.tgz", - "integrity": "sha512-pmEYSk3vYsG/bF651KPUXZ+hvjpgWYw/Gc7W9NFUe3ZVLczKKWIij3IKpOrQcdw4TILtibFslZ0UmR8Vvzig4g==", + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.0.1.tgz", + "integrity": "sha512-h2iAoN838FqAFJY2/qVpzFXy+EBxfVE220PalAqQLDVsFOHLJrZvut5puAbCdNv6WJk+B8ihI+k0c7JK5erwqQ==", "requires": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", @@ -443,9 +443,9 @@ } }, "globby": { - "version": "11.0.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.0.tgz", - "integrity": "sha512-iuehFnR3xu5wBBtm4xi0dMe92Ob87ufyu/dHwpDYfbcpYpIbrO5OnS8M1vWvrBhSGEJ3/Ecj7gnX76P8YxpPEg==", + "version": "11.0.1", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.1.tgz", + "integrity": "sha512-iH9RmgwCmUJHi2z5o2l3eTtGBtXek1OYlHrbcxOYugyHLmAsZrPj43OtHThd62Buh/Vv6VyCBD2bdyWcGNQqoQ==", "requires": { "array-union": "^2.1.0", "dir-glob": "^3.0.1", @@ -490,9 +490,9 @@ "integrity": "sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==" }, "ignore": { - "version": "5.1.4", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.4.tgz", - "integrity": "sha512-MzbUSahkTW1u7JpKKjY7LCARd1fU5W2rLdxlM4kdkayuCwZImjkpluF9CM1aLewYJguPDqewLam18Y6AU69A8A==" + "version": "5.1.8", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.1.8.tgz", + "integrity": "sha512-BMpfD7PpiETpBl/A6S498BaIJ6Y/ABT93ETbby2fP00v4EbvPBXWEoaR1UBPKs3iR53pJY7EtZk5KACI57i1Uw==" }, "indent-string": { "version": "4.0.0", @@ -622,9 +622,9 @@ "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==" }, "merge2": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.3.0.tgz", - "integrity": "sha512-2j4DAdlBOkiSZIsaXk4mTE3sRS02yBHAtfy127xRV3bQUFqXkjHCHLW6Scv7DwNRbIWNHH8zpnz9zMaKXIdvYw==" + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==" }, "micromatch": { "version": "4.0.2", @@ -636,9 +636,9 @@ } }, "mime": { - "version": "2.4.5", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.5.tgz", - "integrity": "sha512-3hQhEUF027BuxZjQA3s7rIv/7VCQPa27hN9u9g87sEkWaKwQPuXOkVKtOeiyUrnWqTDiOs8Ed2rwg733mB0R5w==" + "version": "2.4.6", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.6.tgz", + "integrity": "sha512-RZKhC3EmpBchfTGBVb8fb+RL2cWyw/32lshnsETttkBAyAUXSGHxbEJWWRXc751DrIxG1q04b8QwMbAwkRPpUA==" }, "mimic-fn": { "version": "2.1.0", From 38aeb67b8a1d3b8d7f66233d5631d7509cb60bca Mon Sep 17 00:00:00 2001 From: Mike Kistler Date: Tue, 9 Jun 2020 11:20:32 -0500 Subject: [PATCH 261/455] Fix code example in README --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cf620b72e..4f58b11d9 100755 --- a/README.md +++ b/README.md @@ -170,7 +170,7 @@ You supply either an IAM service **API key** or a **bearer token**: #### Supplying the API key ```python from ibm_watson import DiscoveryV1 -import from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator # In the constructor, letting the SDK manage the token authenticator = IAMAuthenticator('apikey', From 6b87f9bc834f9b23e62a1d7047e8024839a50e36 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:18:28 -0400 Subject: [PATCH 262/455] feat(AssistantV2): add support for list logs and delete user data --- examples/assistant_v2.py | 5 + ibm_watson/assistant_v2.py | 588 +++++++++++++++++++++++++++++++++++-- 2 files changed, 568 insertions(+), 25 deletions(-) diff --git a/examples/assistant_v2.py b/examples/assistant_v2.py index bf81d13ab..90cd62728 100644 --- a/examples/assistant_v2.py +++ b/examples/assistant_v2.py @@ -31,3 +31,8 @@ } }).get_result() print(json.dumps(message, indent=2)) + +# logs = assistant.list_logs( +# "" +# ) +# print(json.dumps(logs, indent=2)) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index c0a3cb07e..9fa7594cf 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -39,7 +39,7 @@ class AssistantV2(BaseService): """The Assistant V2 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.assistant.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'assistant' def __init__( @@ -186,7 +186,6 @@ def message(self, Send user input to an assistant and receive a response, with conversation state (including context data) stored by Watson Assistant for the duration of the session. - There is no rate limit for this operation. :param str assistant_id: Unique identifier of the assistant. To find the assistant ID in the Watson Assistant user interface, open the assistant @@ -251,7 +250,6 @@ def message_stateless(self, Send user input to an assistant and receive a response, with conversation state (including context data) managed by your application. - There is no rate limit for this operation. :param str assistant_id: Unique identifier of the assistant. To find the assistant ID in the Watson Assistant user interface, open the assistant @@ -303,6 +301,121 @@ def message_stateless(self, response = self.send(request) return response + ######################### + # Logs + ######################### + + def list_logs(self, + assistant_id: str, + *, + sort: str = None, + filter: str = None, + page_limit: int = None, + cursor: str = None, + **kwargs) -> 'DetailedResponse': + """ + List log events for an assistant. + + List the events from the log of an assistant. + This method is available only with Premium plans. + + :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/assistant?topic=assistant-assistant-add#assistant-add-task). + **Note:** Currently, the v2 API does not support creating assistants. + :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 (`-`). + :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/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 + retrieve. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if assistant_id is None: + raise ValueError('assistant_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='V2', + operation_id='list_logs') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'sort': sort, + 'filter': filter, + 'page_limit': page_limit, + 'cursor': cursor + } + + url = '/v2/assistants/{0}/logs'.format( + *self._encode_path_vars(assistant_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + ######################### + # User data + ######################### + + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': + """ + Delete labeled data. + + Deletes all data associated with a specified customer ID. The method has no effect + if no data is associated with the customer ID. + 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/assistant?topic=assistant-information-security#information-security). + This operation is limited to 4 requests per minute. For more information, see + **Rate limiting**. + + :param str customer_id: The customer ID for which all data is to be + deleted. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if customer_id is None: + raise ValueError('customer_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='V2', + operation_id='delete_user_data') + headers.update(sdk_headers) + + params = {'version': self.version, 'customer_id': customer_id} + + url = '/v2/user_data' + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + ############################################################################## # Models @@ -812,9 +925,9 @@ class DialogSuggestion(): """ DialogSuggestion. - :attr str label: The user-facing label for the disambiguation option. This label - is taken from the **title** or **user_label** property of the corresponding - dialog node, depending on the disambiguation options. + :attr str label: The user-facing label for the suggestion. This label is taken + from the **title** or **user_label** property of the corresponding dialog node, + depending on the disambiguation options. :attr DialogSuggestionValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. @@ -830,9 +943,9 @@ def __init__(self, """ Initialize a DialogSuggestion object. - :param str label: The user-facing label for the disambiguation option. This - label is taken from the **title** or **user_label** property of the - corresponding dialog node, depending on the disambiguation options. + :param str label: The user-facing label for the suggestion. This label is + taken from the **title** or **user_label** property of the corresponding + dialog node, depending on the disambiguation options. :param DialogSuggestionValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. @@ -967,6 +1080,357 @@ def __ne__(self, other: 'DialogSuggestionValue') -> bool: return not self == other +class Log(): + """ + Log. + + :attr str log_id: A unique identifier for the logged event. + :attr MessageRequest request: A stateful message request formatted for the + Watson Assistant service. + :attr MessageResponse response: A response from the Watson Assistant service. + :attr str assistant_id: Unique identifier of the assistant. + :attr str session_id: The ID of the session the message was part of. + :attr str skill_id: The unique identifier of the skill that responded to the + message. + :attr str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :attr str request_timestamp: The timestamp for receipt of the message. + :attr str response_timestamp: The timestamp for the system response to the + message. + :attr str language: The language of the assistant to which the message request + was made. + :attr str customer_id: (optional) The customer ID specified for the message, if + any. + """ + + def __init__(self, + log_id: str, + request: 'MessageRequest', + response: 'MessageResponse', + assistant_id: str, + session_id: str, + skill_id: str, + snapshot: str, + request_timestamp: str, + response_timestamp: str, + language: str, + *, + customer_id: str = None) -> None: + """ + Initialize a Log object. + + :param str log_id: A unique identifier for the logged event. + :param MessageRequest request: A stateful message request formatted for the + Watson Assistant service. + :param MessageResponse response: A response from the Watson Assistant + service. + :param str assistant_id: Unique identifier of the assistant. + :param str session_id: The ID of the session the message was part of. + :param str skill_id: The unique identifier of the skill that responded to + the message. + :param str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the + message. + :param str language: The language of the assistant to which the message + request was made. + :param str customer_id: (optional) The customer ID specified for the + message, if any. + """ + self.log_id = log_id + self.request = request + self.response = response + self.assistant_id = assistant_id + self.session_id = session_id + self.skill_id = skill_id + self.snapshot = snapshot + self.request_timestamp = request_timestamp + self.response_timestamp = response_timestamp + self.language = language + self.customer_id = customer_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Log': + """Initialize a Log object from a json dictionary.""" + args = {} + valid_keys = [ + 'log_id', 'request', 'response', 'assistant_id', 'session_id', + 'skill_id', 'snapshot', 'request_timestamp', 'response_timestamp', + 'language', 'customer_id' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Log: ' + + ', '.join(bad_keys)) + if 'log_id' in _dict: + args['log_id'] = _dict.get('log_id') + else: + raise ValueError( + 'Required property \'log_id\' not present in Log JSON') + if 'request' in _dict: + args['request'] = MessageRequest._from_dict(_dict.get('request')) + else: + raise ValueError( + 'Required property \'request\' not present in Log JSON') + if 'response' in _dict: + args['response'] = MessageResponse._from_dict(_dict.get('response')) + else: + raise ValueError( + 'Required property \'response\' not present in Log JSON') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + else: + raise ValueError( + 'Required property \'assistant_id\' not present in Log JSON') + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') + else: + raise ValueError( + 'Required property \'session_id\' not present in Log JSON') + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + else: + raise ValueError( + 'Required property \'skill_id\' not present in Log JSON') + if 'snapshot' in _dict: + args['snapshot'] = _dict.get('snapshot') + else: + raise ValueError( + 'Required property \'snapshot\' not present in Log JSON') + if 'request_timestamp' in _dict: + args['request_timestamp'] = _dict.get('request_timestamp') + else: + raise ValueError( + 'Required property \'request_timestamp\' not present in Log JSON' + ) + if 'response_timestamp' in _dict: + args['response_timestamp'] = _dict.get('response_timestamp') + else: + raise ValueError( + 'Required property \'response_timestamp\' not present in Log JSON' + ) + if 'language' in _dict: + args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in Log JSON') + if 'customer_id' in _dict: + args['customer_id'] = _dict.get('customer_id') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Log 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, 'log_id') and self.log_id is not None: + _dict['log_id'] = self.log_id + if hasattr(self, 'request') and self.request is not None: + _dict['request'] = self.request._to_dict() + if hasattr(self, 'response') and self.response is not None: + _dict['response'] = self.response._to_dict() + if hasattr(self, 'assistant_id') and self.assistant_id is not None: + _dict['assistant_id'] = self.assistant_id + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + if hasattr(self, + 'request_timestamp') and self.request_timestamp is not None: + _dict['request_timestamp'] = self.request_timestamp + if hasattr( + self, + 'response_timestamp') and self.response_timestamp is not None: + _dict['response_timestamp'] = self.response_timestamp + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'customer_id') and self.customer_id is not None: + _dict['customer_id'] = self.customer_id + 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 Log object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Log') -> 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: 'Log') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogCollection(): + """ + LogCollection. + + :attr List[Log] logs: An array of objects describing log events. + :attr LogPagination pagination: The pagination data for the returned objects. + """ + + def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: + """ + Initialize a LogCollection object. + + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned + objects. + """ + self.logs = logs + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogCollection': + """Initialize a LogCollection object from a json dictionary.""" + args = {} + valid_keys = ['logs', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class LogCollection: ' + + ', '.join(bad_keys)) + if 'logs' in _dict: + args['logs'] = [Log._from_dict(x) for x in (_dict.get('logs'))] + else: + raise ValueError( + 'Required property \'logs\' not present in LogCollection JSON') + if 'pagination' in _dict: + args['pagination'] = LogPagination._from_dict( + _dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in LogCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogCollection 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, 'logs') and self.logs is not None: + _dict['logs'] = [x._to_dict() for x in self.logs] + if hasattr(self, 'pagination') and self.pagination is not None: + _dict['pagination'] = self.pagination._to_dict() + 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 LogCollection object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'LogCollection') -> 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: 'LogCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogPagination(): + """ + The pagination data for the returned objects. + + :attr str next_url: (optional) The URL that will return the next page of + results, if any. + :attr int matched: (optional) Reserved for future use. + :attr str next_cursor: (optional) A token identifying the next page of results. + """ + + def __init__(self, + *, + next_url: str = None, + matched: int = None, + next_cursor: str = None) -> None: + """ + Initialize a LogPagination object. + + :param str next_url: (optional) The URL that will return the next page of + results, if any. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of + results. + """ + self.next_url = next_url + self.matched = matched + self.next_cursor = next_cursor + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogPagination': + """Initialize a LogPagination object from a json dictionary.""" + args = {} + valid_keys = ['next_url', 'matched', 'next_cursor'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class LogPagination: ' + + ', '.join(bad_keys)) + if 'next_url' in _dict: + args['next_url'] = _dict.get('next_url') + if 'matched' in _dict: + args['matched'] = _dict.get('matched') + if 'next_cursor' in _dict: + args['next_cursor'] = _dict.get('next_cursor') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogPagination 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, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor + 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 LogPagination object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'LogPagination') -> 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: 'LogPagination') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageContext(): """ MessageContext. @@ -2611,6 +3075,88 @@ def __ne__(self, other: 'MessageOutputSpelling') -> bool: return not self == other +class MessageRequest(): + """ + A stateful message request formatted for the Watson Assistant service. + + :attr MessageInput input: (optional) An input object that includes the input + text. + :attr MessageContext context: (optional) Context data for the conversation. You + can use this property to set or modify context variables, which can also be + accessed by dialog nodes. The context is stored by the assistant on a + per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + """ + + def __init__(self, + *, + input: 'MessageInput' = None, + context: 'MessageContext' = None) -> None: + """ + Initialize a MessageRequest object. + + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + """ + self.input = input + self.context = context + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageRequest': + """Initialize a MessageRequest object from a json dictionary.""" + args = {} + valid_keys = ['input', 'context'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class MessageRequest: ' + + ', '.join(bad_keys)) + if 'input' in _dict: + args['input'] = MessageInput._from_dict(_dict.get('input')) + if 'context' in _dict: + args['context'] = MessageContext._from_dict(_dict.get('context')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageRequest 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, 'input') and self.input is not None: + _dict['input'] = self.input._to_dict() + if hasattr(self, 'context') and self.context is not None: + _dict['context'] = self.context._to_dict() + 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 MessageRequest object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'MessageRequest') -> 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: 'MessageRequest') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageResponse(): """ A response from the Watson Assistant service. @@ -2621,7 +3167,8 @@ class MessageResponse(): can use this property to access context variables. The context is stored by the assistant on a per-session basis. **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. + **return_context**=`true` in the message request. Full context is always + included in logs. """ def __init__(self, @@ -2637,7 +3184,8 @@ def __init__(self, conversation. You can use this property to access context variables. The context is stored by the assistant on a per-session basis. **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. + **return_context**=`true` in the message request. Full context is always + included in logs. """ self.output = output self.context = context @@ -3573,8 +4121,6 @@ class RuntimeResponseGeneric(): :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Premium users. :attr str text: (optional) The text of the response. :attr int time: (optional) How long to pause, in milliseconds. :attr bool typing: (optional) Whether to send a "user is typing" event during @@ -3592,8 +4138,6 @@ class RuntimeResponseGeneric(): derived from the **user_label** property of the relevant node. :attr List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation feature, - which is only available for Premium users. :attr str header: (optional) The title or introductory text to show before the response. This text is defined in the search skill configuration. :attr List[SearchResult] results: (optional) An array of objects containing @@ -3622,8 +4166,6 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Premium users. :param str text: (optional) The text of the response. :param int time: (optional) How long to pause, in milliseconds. :param bool typing: (optional) Whether to send a "user is typing" event @@ -3644,8 +4186,6 @@ def __init__(self, :param List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation - feature, which is only available for Premium users. :param str header: (optional) The title or introductory text to show before the response. This text is defined in the search skill configuration. :param List[SearchResult] results: (optional) An array of objects @@ -3783,8 +4323,6 @@ class ResponseTypeEnum(Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation feature, - which is only available for Premium users. """ TEXT = "text" PAUSE = "pause" @@ -3808,8 +4346,8 @@ class SearchResult(): :attr str id: The unique identifier of the document in the Discovery service collection. - This property is included in responses from search skills, which are a beta - feature available only to Plus or Premium plan users. + This property is included in responses from search skills, which are available + only to Plus or Premium plan users. :attr SearchResultMetadata result_metadata: An object containing search result metadata from the Discovery service. :attr str body: (optional) A description of the search result. This is taken @@ -3838,8 +4376,8 @@ def __init__(self, :param str id: The unique identifier of the document in the Discovery service collection. - This property is included in responses from search skills, which are a beta - feature available only to Plus or Premium plan users. + This property is included in responses from search skills, which are + available only to Plus or Premium plan users. :param SearchResultMetadata result_metadata: An object containing search result metadata from the Discovery service. :param str body: (optional) A description of the search result. This is From de83e96e5d4b0a9f2221fc48ca38ef66b0a0c68d Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:19:37 -0400 Subject: [PATCH 263/455] feat(languageTranslatorV3): add support for list languages --- ibm_watson/language_translator_v3.py | 429 +++++++++++++++--- .../test_language_translator_v3.py | 4 + 2 files changed, 380 insertions(+), 53 deletions(-) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 7e98d4908..072f7a1de 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -15,7 +15,7 @@ # limitations under the License. """ IBM Watson™ Language Translator translates text from one language to another. The -service offers multiple IBM provided translation models that you can customize based on +service offers multiple IBM-provided translation models that you can customize based on your unique terminology and language. Use Language Translator to take news from across the globe and present it in your language, communicate with your customers in their own language, and more. @@ -43,7 +43,7 @@ class LanguageTranslatorV3(BaseService): """The Language Translator V3 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/language-translator/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.language-translator.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'language_translator' def __init__( @@ -79,6 +79,42 @@ def __init__( self.version = version self.configure_service(service_name) + ######################### + # Languages + ######################### + + def list_languages(self, **kwargs) -> 'DetailedResponse': + """ + List supported languages. + + Lists all supported languages. The method returns an array of supported languages + with information about each language. Languages are listed in alphabetical order + by language code (for example, `af`, `ar`). + + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_languages') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v3/languages' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + ######################### # Translation ######################### @@ -93,19 +129,24 @@ def translate(self, """ Translate. - Translates the input text from the source language to the target language. A - target language or translation model ID is required. The service attempts to - detect the language of the source text if it is not specified. + Translates the input text from the source language to the target language. Specify + a model ID that indicates the source and target languages, or specify the source + and target languages individually. You can omit the source language to have the + service attempt to detect the language from the input text. If you omit the source + language, the request must contain sufficient input text for the service to + identify the source language. - :param List[str] text: Input text in UTF-8 encoding. Multiple entries will + :param List[str] text: Input text in UTF-8 encoding. Multiple entries result in multiple translations in the response. :param str model_id: (optional) The model to use for translation. For - example, `en-de` selects the IBM provided base model for English to German - translation. A model ID overrides the source and target parameters and is - required if you use a custom model. If no model ID is specified, you must - specify a target language. + example, `en-de` selects the IBM-provided base model for English-to-German + translation. A model ID overrides the `source` and `target` parameters and + is required if you use a custom model. If no model ID is specified, you + must specify at least a target language. :param str source: (optional) Language code that specifies the language of - the source document. + the input text. If omitted, the service derives the source language from + the input text. The input must contain sufficient text for the service to + identify the language reliably. :param str target: (optional) Language code that specifies the target language for translation. Required if model ID is not specified. :param dict headers: A `dict` containing the request headers @@ -236,11 +277,11 @@ def list_models(self, source language. :param str target: (optional) Specify a language code to filter results by target language. - :param bool default: (optional) If the default parameter isn't specified, - the service will return all models (default and non-default) for each - language pair. To return only default models, set this to `true`. To return - only non-default models, set this to `false`. There is exactly one default - model per language pair, the IBM provided base model. + :param bool default: (optional) If the `default` parameter isn't specified, + the service returns all models (default and non-default) for each language + pair. To return only default models, set this parameter to `true`. To + return only non-default models, set this parameter to `false`. There is + exactly one default model, the IBM-provided base model, per language pair. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -280,39 +321,90 @@ def create_model(self, """ Create model. - Uploads Translation Memory eXchange (TMX) files to customize a translation model. - You can either customize a model with a forced glossary or with a corpus that - contains parallel sentences. To create a model that is customized with a parallel - corpus and a forced glossary, proceed in two steps: customize with a - parallel corpus first and then customize the resulting model with a glossary. - Depending on the type of customization and the size of the uploaded corpora, - training can range from minutes for a glossary to several hours for a large - parallel corpus. You can upload a single forced glossary file and this file must - be less than 10 MB. You can upload multiple parallel corpora tmx files. The - cumulative file size of all uploaded files is limited to 250 MB. To - successfully train with a parallel corpus you must have at least 5,000 parallel - sentences in your corpus. - You can have a maximum of 10 custom models per language pair. - - :param str base_model_id: The model ID of the model to use as the base for - customization. To see available models, use the `List models` method. - Usually all IBM provided models are customizable. In addition, all your - models that have been created via parallel corpus customization, can be - further customized with a forced glossary. - :param TextIO forced_glossary: (optional) A TMX file with your - customizations. The customizations in the file completely overwrite the - domain translaton data, including high frequency or high confidence phrase - translations. You can upload only one glossary with a file size less than - 10 MB per call. A forced glossary should contain single words or short - phrases. - :param TextIO parallel_corpus: (optional) A TMX file with parallel - sentences for source and target language. You can upload multiple - parallel_corpus files in one request. All uploaded parallel_corpus files - combined, your parallel corpus must contain at least 5,000 parallel - sentences to train successfully. + Uploads training files to customize a translation model. You can customize a model + with a forced glossary or with a parallel corpus: + * Use a *forced glossary* to force certain terms and phrases to be translated in a + specific way. You can upload only a single forced glossary file for a model. The + size of a forced glossary file for a custom model is limited to 10 MB. + * Use a *parallel corpus* when you want your custom model to learn from general + translation patterns in parallel sentences in your samples. What your model learns + from a parallel corpus can improve translation results for input text that the + model has not been trained on. You can upload multiple parallel corpora files with + a request. To successfully train with parallel corpora, the corpora files must + contain a cumulative total of at least 5000 parallel sentences. The cumulative + size of all uploaded corpus files for a custom model is limited to 250 MB. + Depending on the type of customization and the size of the uploaded files, + training time can range from minutes for a glossary to several hours for a large + parallel corpus. To create a model that is customized with a parallel corpus and a + forced glossary, customize the model with a parallel corpus first and then + customize the resulting model with a forced glossary. + You can create a maximum of 10 custom models per language pair. For more + information about customizing a translation model, including the formatting and + character restrictions for data files, see [Customizing your + model](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing). + #### Supported file formats + You can provide your training data for customization in the following document + formats: + * **TMX** (`.tmx`) - Translation Memory eXchange (TMX) is an XML specification for + the exchange of translation memories. + * **XLIFF** (`.xliff`) - XML Localization Interchange File Format (XLIFF) is an + XML specification for the exchange of translation memories. + * **CSV** (`.csv`) - Comma-separated values (CSV) file with two columns for + aligned sentences and phrases. The first row contains the language code. + * **TSV** (`.tsv` or `.tab`) - Tab-separated values (TSV) file with two columns + for aligned sentences and phrases. The first row contains the language code. + * **JSON** (`.json`) - Custom JSON format for specifying aligned sentences and + phrases. + * **Microsoft Excel** (`.xls` or `.xlsx`) - Excel file with the first two columns + for aligned sentences and phrases. The first row contains the language code. + You must encode all text data in UTF-8 format. For more information, see + [Supported document formats for training + data](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing#supported-document-formats-for-training-data). + #### Specifying file formats + You can indicate the format of a file by including the file extension with the + file name. Use the file extensions shown in **Supported file formats**. + Alternatively, you can omit the file extension and specify one of the following + `content-type` specifications for the file: + * **TMX** - `application/x-tmx+xml` + * **XLIFF** - `application/xliff+xml` + * **CSV** - `text/csv` + * **TSV** - `text/tab-separated-values` + * **JSON** - `application/json` + * **Microsoft Excel** - + `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` + For example, with `curl`, use the following `content-type` specification to + indicate the format of a CSV file named **glossary**: + `--form "forced_glossary=@glossary;type=text/csv"`. + + :param str base_model_id: The ID of the translation model to use as the + base for customization. To see available models and IDs, use the `List + models` method. Most models that are provided with the service are + customizable. In addition, all models that you create with parallel corpora + customization can be further customized with a forced glossary. + :param TextIO forced_glossary: (optional) A file with forced glossary terms + for the source and target languages. The customizations in the file + completely overwrite the domain translation data, including high frequency + or high confidence phrase translations. + You can upload only one glossary file for a custom model, and the glossary + can have a maximum size of 10 MB. A forced glossary must contain single + words or short phrases. For more information, see **Supported file + formats** in the method description. + *With `curl`, use `--form forced_glossary=@{filename}`.*. + :param TextIO parallel_corpus: (optional) A file with parallel sentences + for the source and target languages. You can upload multiple parallel + corpus files in one request by repeating the parameter. All uploaded + parallel corpus files combined must contain at least 5000 parallel + sentences to train successfully. You can provide a maximum of 500,000 + parallel sentences across all corpora. + A single entry in a corpus file can contain a maximum of 80 words. All + corpora files for a custom model can have a cumulative maximum size of 250 + MB. For more information, see **Supported file formats** in the method + description. + *With `curl`, use `--form parallel_corpus=@{filename}`.*. :param str name: (optional) An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, - underscores, spaces and apostrophes. The maximum length is 32 characters. + underscores, spaces, and apostrophes. The maximum length of the name is 32 + characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -393,7 +485,7 @@ def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': Gets information about a translation model, including training status for custom models. Use this API call to poll the status of your customization request. A - successfully completed training will have a status of `available`. + successfully completed training has a status of `available`. :param str model_id: Model ID of the model to get. :param dict headers: A `dict` containing the request headers @@ -481,12 +573,14 @@ def translate_document(self, :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str model_id: (optional) The model to use for translation. For - example, `en-de` selects the IBM provided base model for English to German - translation. A model ID overrides the source and target parameters and is - required if you use a custom model. If no model ID is specified, you must - specify a target language. + example, `en-de` selects the IBM-provided base model for English-to-German + translation. A model ID overrides the `source` and `target` parameters and + is required if you use a custom model. If no model ID is specified, you + must specify at least a target language. :param str source: (optional) Language code that specifies the language of - the source document. + the source document. If omitted, the service derives the source language + from the input text. The input must contain sufficient text for the service + to identify the language reliably. :param str target: (optional) Language code that specifies the target language for translation. Required if model ID is not specified. :param str document_id: (optional) To use a previously submitted document @@ -1378,6 +1472,235 @@ def __ne__(self, other: 'IdentifiedLanguages') -> bool: return not self == other +class Language(): + """ + Response payload for languages. + + :attr str language: (optional) The language code for the language (for example, + `af`). + :attr str language_name: (optional) The name of the language in English (for + example, `Afrikaans`). + :attr str native_language_name: (optional) The native name of the language (for + example, `Afrikaans`). + :attr str country_code: (optional) The country code for the language (for + example, `ZA` for South Africa). + :attr bool words_separated: (optional) Indicates whether words of the language + are separated by whitespace: `true` if the words are separated; `false` + otherwise. + :attr str direction: (optional) Indicates the direction of the language: + `right_to_left` or `left_to_right`. + :attr bool supported_as_source: (optional) Indicates whether the language can be + used as the source for translation: `true` if the language can be used as the + source; `false` otherwise. + :attr bool supported_as_target: (optional) Indicates whether the language can be + used as the target for translation: `true` if the language can be used as the + target; `false` otherwise. + :attr bool identifiable: (optional) Indicates whether the language supports + automatic detection: `true` if the language can be detected automatically; + `false` otherwise. + """ + + def __init__(self, + *, + language: str = None, + language_name: str = None, + native_language_name: str = None, + country_code: str = None, + words_separated: bool = None, + direction: str = None, + supported_as_source: bool = None, + supported_as_target: bool = None, + identifiable: bool = None) -> None: + """ + Initialize a Language object. + + :param str language: (optional) The language code for the language (for + example, `af`). + :param str language_name: (optional) The name of the language in English + (for example, `Afrikaans`). + :param str native_language_name: (optional) The native name of the language + (for example, `Afrikaans`). + :param str country_code: (optional) The country code for the language (for + example, `ZA` for South Africa). + :param bool words_separated: (optional) Indicates whether words of the + language are separated by whitespace: `true` if the words are separated; + `false` otherwise. + :param str direction: (optional) Indicates the direction of the language: + `right_to_left` or `left_to_right`. + :param bool supported_as_source: (optional) Indicates whether the language + can be used as the source for translation: `true` if the language can be + used as the source; `false` otherwise. + :param bool supported_as_target: (optional) Indicates whether the language + can be used as the target for translation: `true` if the language can be + used as the target; `false` otherwise. + :param bool identifiable: (optional) Indicates whether the language + supports automatic detection: `true` if the language can be detected + automatically; `false` otherwise. + """ + self.language = language + self.language_name = language_name + self.native_language_name = native_language_name + self.country_code = country_code + self.words_separated = words_separated + self.direction = direction + self.supported_as_source = supported_as_source + self.supported_as_target = supported_as_target + self.identifiable = identifiable + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Language': + """Initialize a Language object from a json dictionary.""" + args = {} + valid_keys = [ + 'language', 'language_name', 'native_language_name', 'country_code', + 'words_separated', 'direction', 'supported_as_source', + 'supported_as_target', 'identifiable' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Language: ' + + ', '.join(bad_keys)) + if 'language' in _dict: + args['language'] = _dict.get('language') + if 'language_name' in _dict: + args['language_name'] = _dict.get('language_name') + if 'native_language_name' in _dict: + args['native_language_name'] = _dict.get('native_language_name') + if 'country_code' in _dict: + args['country_code'] = _dict.get('country_code') + if 'words_separated' in _dict: + args['words_separated'] = _dict.get('words_separated') + if 'direction' in _dict: + args['direction'] = _dict.get('direction') + if 'supported_as_source' in _dict: + args['supported_as_source'] = _dict.get('supported_as_source') + if 'supported_as_target' in _dict: + args['supported_as_target'] = _dict.get('supported_as_target') + if 'identifiable' in _dict: + args['identifiable'] = _dict.get('identifiable') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Language 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, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'language_name') and self.language_name is not None: + _dict['language_name'] = self.language_name + if hasattr(self, 'native_language_name' + ) and self.native_language_name is not None: + _dict['native_language_name'] = self.native_language_name + if hasattr(self, 'country_code') and self.country_code is not None: + _dict['country_code'] = self.country_code + if hasattr(self, + 'words_separated') and self.words_separated is not None: + _dict['words_separated'] = self.words_separated + if hasattr(self, 'direction') and self.direction is not None: + _dict['direction'] = self.direction + if hasattr( + self, + 'supported_as_source') and self.supported_as_source is not None: + _dict['supported_as_source'] = self.supported_as_source + if hasattr( + self, + 'supported_as_target') and self.supported_as_target is not None: + _dict['supported_as_target'] = self.supported_as_target + if hasattr(self, 'identifiable') and self.identifiable is not None: + _dict['identifiable'] = self.identifiable + 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 Language object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Language') -> 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: 'Language') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Languages(): + """ + The response type for listing supported languages. + + :attr List[Language] languages: An array of supported languages with information + about each language. + """ + + def __init__(self, languages: List['Language']) -> None: + """ + Initialize a Languages object. + + :param List[Language] languages: An array of supported languages with + information about each language. + """ + self.languages = languages + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Languages': + """Initialize a Languages object from a json dictionary.""" + args = {} + valid_keys = ['languages'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Languages: ' + + ', '.join(bad_keys)) + if 'languages' in _dict: + args['languages'] = [ + Language._from_dict(x) for x in (_dict.get('languages')) + ] + else: + raise ValueError( + 'Required property \'languages\' not present in Languages JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Languages 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, 'languages') and self.languages is not None: + _dict['languages'] = [x._to_dict() for x in self.languages] + 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 Languages object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Languages') -> 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: 'Languages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Translation(): """ Translation. diff --git a/test/integration/test_language_translator_v3.py b/test/integration/test_language_translator_v3.py index b44ece2a7..439a5322f 100644 --- a/test/integration/test_language_translator_v3.py +++ b/test/integration/test_language_translator_v3.py @@ -23,6 +23,10 @@ def test_translate(self): text='Hello, how are you?', target='es').get_result() assert translation is not None + def test_list_languages(self): + languages = self.language_translator.list_languages() + assert languages is not None + def test_document_translation(self): with open(join(dirname(__file__), '../../resources/hello_world.txt'), 'r') as fileinfo: From 4388ea276b5473b13249592127a51e2004a1d82c Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:23:09 -0400 Subject: [PATCH 264/455] feat(discoV2): add new apis for enrichments, collections and projects --- ibm_watson/discovery_v2.py | 3757 ++++++++++++++++++++----- test/integration/test_discovery_v2.py | 110 + 2 files changed, 3193 insertions(+), 674 deletions(-) create mode 100644 test/integration/test_discovery_v2.py diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index f4341d9cb..947486b88 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -14,11 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. """ -IBM Watson™ Discovery for IBM Cloud Pak for Data is a cognitive search and content -analytics engine that you can add to applications to identify patterns, trends and -actionable insights to drive better decision-making. Securely unify structured and -unstructured data with pre-enriched content, and use a simplified query language to -eliminate the need for manual filtering of results. +IBM Watson™ Discovery is a cognitive search and content analytics engine that you +can add to applications to identify patterns, trends and actionable insights to drive +better decision-making. Securely unify structured and unstructured data with pre-enriched +content, and use a simplified query language to eliminate the need for manual filtering of +results. """ import json @@ -44,7 +44,7 @@ class DiscoveryV2(BaseService): """The Discovery V2 service.""" - DEFAULT_SERVICE_URL = None + DEFAULT_SERVICE_URL = 'https://api.us-south.discovery.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'discovery' def __init__( @@ -120,6 +120,206 @@ def list_collections(self, project_id: str, **kwargs) -> 'DetailedResponse': response = self.send(request) return response + def create_collection(self, + project_id: str, + name: str, + *, + description: str = None, + language: str = None, + enrichments: List['CollectionEnrichment'] = None, + **kwargs) -> 'DetailedResponse': + """ + Create a collection. + + Create a new collection in the specified project. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str name: The name of the collection. + :param str description: (optional) A description of the collection. + :param str language: (optional) The language of the collection. + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if name is None: + raise ValueError('name must be provided') + if enrichments is not None: + enrichments = [self._convert_model(x) for x in enrichments] + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'name': name, + 'description': description, + 'language': language, + 'enrichments': enrichments + } + + url = '/v2/projects/{0}/collections'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def get_collection(self, project_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': + """ + Get collection. + + Get details about the specified collection. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str collection_id: The ID 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 project_id is None: + raise ValueError('project_id must be provided') + 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='V2', + operation_id='get_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/collections/{1}'.format( + *self._encode_path_vars(project_id, collection_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def update_collection(self, + project_id: str, + collection_id: str, + *, + name: str = None, + description: str = None, + enrichments: List['CollectionEnrichment'] = None, + **kwargs) -> 'DetailedResponse': + """ + Update a collection. + + Updates the specified collection's name, description, and enrichments. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str collection_id: The ID of the collection. + :param str name: (optional) The name of the collection. + :param str description: (optional) A description of the collection. + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + if enrichments is not None: + enrichments = [self._convert_model(x) for x in enrichments] + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'name': name, + 'description': description, + 'enrichments': enrichments + } + + url = '/v2/projects/{0}/collections/{1}'.format( + *self._encode_path_vars(project_id, collection_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def delete_collection(self, project_id: str, collection_id: str, + **kwargs) -> 'DetailedResponse': + """ + Delete a collection. + + Deletes the specified collection from the project. All documents stored in the + specified collection and not shared is also deleted. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str collection_id: The ID 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 project_id is None: + raise ValueError('project_id must be provided') + 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='V2', + operation_id='delete_collection') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/collections/{1}'.format( + *self._encode_path_vars(project_id, collection_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + ######################### # Queries ######################### @@ -147,6 +347,12 @@ def query(self, By using this method, you can construct queries. For details, see the [Discovery documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-concepts). + The default query parameters are defined by the settings for this project, see the + [Discovery + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-project-defaults) + for an overview of the standard default settings, and see [the Projects API + documentation](#create-project) for details about how to set custom default query + settings. :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. @@ -427,7 +633,7 @@ def list_fields(self, def get_component_settings(self, project_id: str, **kwargs) -> 'DetailedResponse': """ - Configuration settings for components. + List component settings. Returns default configuration settings for components. @@ -512,7 +718,8 @@ def add_document(self, :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { + 1 MB. Metadata parts larger than 1 MB are rejected. + Example: ``` { "Creator": "Johnny Appleseed", "Subject": "Apples" } ```. @@ -599,7 +806,8 @@ def update_document(self, :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { + 1 MB. Metadata parts larger than 1 MB are rejected. + Example: ``` { "Creator": "Johnny Appleseed", "Subject": "Apples" } ```. @@ -951,149 +1159,1768 @@ def update_training_query(self, response = self.send(request) return response + ######################### + # enrichments + ######################### -class AddDocumentEnums(object): - - class FileContentType(Enum): + def list_enrichments(self, project_id: str, **kwargs) -> 'DetailedResponse': """ - The content type of file. - """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + List Enrichments. + List the enrichments available to this project. -class UpdateDocumentEnums(object): - - class FileContentType(Enum): - """ - The content type of file. + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + if project_id is None: + raise ValueError('project_id must be provided') -############################################################################## -# Models -############################################################################## + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_enrichments') + headers.update(sdk_headers) + params = {'version': self.version} -class Collection(): - """ - A collection for storing documents. + url = '/v2/projects/{0}/enrichments'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: (optional) The name of the collection. - """ + response = self.send(request) + return response - def __init__(self, *, collection_id: str = None, name: str = None) -> None: + def create_enrichment(self, + project_id: str, + enrichment: 'CreateEnrichment', + *, + file: BinaryIO = None, + **kwargs) -> 'DetailedResponse': """ - Initialize a Collection object. + Create an enrichment. - :param str collection_id: (optional) The unique identifier of the - collection. - :param str name: (optional) The name of the collection. - """ - self.collection_id = collection_id - self.name = name + Create an enrichment for use with the specified project/. - @classmethod - def from_dict(cls, _dict: Dict) -> 'Collection': - """Initialize a Collection object from a json dictionary.""" - args = {} - valid_keys = ['collection_id', 'name'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Collection: ' - + ', '.join(bad_keys)) - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - return cls(**args) + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param CreateEnrichment enrichment: + :param TextIO file: (optional) The enrichment file to upload. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ - @classmethod - def _from_dict(cls, _dict): - """Initialize a Collection object from a json dictionary.""" - return cls.from_dict(_dict) + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment is None: + raise ValueError('enrichment must be provided') - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - return _dict + print(enrichment) + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_enrichment') + headers.update(sdk_headers) - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + params = {'version': self.version} - def __str__(self) -> str: - """Return a `str` version of this Collection object.""" - return json.dumps(self._to_dict(), indent=2) + form_data = [] + form_data.append(('enrichment', (None, json.dumps(enrichment), 'application/json'))) + if file: + form_data.append(('file', (None, file, 'application/octet-stream'))) - def __eq__(self, other: 'Collection') -> bool: + url = '/v2/projects/{0}/enrichments'.format( + *self._encode_path_vars(project_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request) + return response + + def get_enrichment(self, project_id: str, enrichment_id: str, + **kwargs) -> 'DetailedResponse': + """ + Get enrichment. + + Get details about a specific enrichment. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str enrichment_id: The ID of the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment_id is None: + raise ValueError('enrichment_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='V2', + operation_id='get_enrichment') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/enrichments/{1}'.format( + *self._encode_path_vars(project_id, enrichment_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def update_enrichment(self, + project_id: str, + enrichment_id: str, + name: str, + *, + description: str = None, + **kwargs) -> 'DetailedResponse': + """ + Update an enrichment. + + Updates an existing enrichment's name and description. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str enrichment_id: The ID of the enrichment. + :param str name: A new name for the enrichment. + :param str description: (optional) A new description for the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment_id is None: + raise ValueError('enrichment_id must be provided') + if name is None: + raise ValueError('name 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='V2', + operation_id='update_enrichment') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'name': name, 'description': description} + + url = '/v2/projects/{0}/enrichments/{1}'.format( + *self._encode_path_vars(project_id, enrichment_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def delete_enrichment(self, project_id: str, enrichment_id: str, + **kwargs) -> 'DetailedResponse': + """ + Delete an enrichment. + + Deletes an existing enrichment from the specified project. + **Note:** Only enrichments that have been manually created can be deleted. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str enrichment_id: The ID of the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment_id is None: + raise ValueError('enrichment_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='V2', + operation_id='delete_enrichment') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}/enrichments/{1}'.format( + *self._encode_path_vars(project_id, enrichment_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + ######################### + # projects + ######################### + + def list_projects(self, **kwargs) -> 'DetailedResponse': + """ + List projects. + + Lists existing projects for this instance. + + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_projects') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def create_project(self, + name: str, + type: str, + *, + default_query_parameters: 'DefaultQueryParams' = None, + **kwargs) -> 'DetailedResponse': + """ + Create a Project. + + Create a new project for this instance. + + :param str name: The human readable name of this project. + :param str type: The project type of this project. + :param DefaultQueryParams default_query_parameters: (optional) Default + query parameters for this project. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if name is None: + raise ValueError('name must be provided') + if type is None: + raise ValueError('type must be provided') + if default_query_parameters is not None: + default_query_parameters = self._convert_model( + default_query_parameters) + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_project') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'name': name, + 'type': type, + 'default_query_parameters': default_query_parameters + } + + url = '/v2/projects' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def get_project(self, project_id: str, **kwargs) -> 'DetailedResponse': + """ + Get project. + + Get details on the specified project. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_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='V2', + operation_id='get_project') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}'.format(*self._encode_path_vars(project_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def update_project(self, + project_id: str, + *, + name: str = None, + **kwargs) -> 'DetailedResponse': + """ + Update a project. + + Update the specified project's name. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str name: (optional) The new name to give this project. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_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='V2', + operation_id='update_project') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'name': name} + + url = '/v2/projects/{0}'.format(*self._encode_path_vars(project_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def delete_project(self, project_id: str, **kwargs) -> 'DetailedResponse': + """ + Delete a project. + + Deletes the specified project. + **Important:** Deleting a project deletes everything that is part of the specified + project, including all collections. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_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='V2', + operation_id='delete_project') + headers.update(sdk_headers) + + params = {'version': self.version} + + url = '/v2/projects/{0}'.format(*self._encode_path_vars(project_id)) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + ######################### + # userData + ######################### + + def delete_user_data(self, customer_id: str, + **kwargs) -> 'DetailedResponse': + """ + Delete labeled data. + + Deletes all data associated with a specified customer ID. The method has no effect + if no data is associated with the customer ID. + 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/discovery-data?topic=discovery-data-information-security#information-security). + **Note:** This method is only supported on IBM Cloud instances of Discovery. + + :param str customer_id: The customer ID for which all data is to be + deleted. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if customer_id is None: + raise ValueError('customer_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='V2', + operation_id='delete_user_data') + headers.update(sdk_headers) + + params = {'version': self.version, 'customer_id': customer_id} + + url = '/v2/user_data' + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + +class AddDocumentEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +class UpdateDocumentEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +############################################################################## +# Models +############################################################################## + + +class Collection(): + """ + A collection for storing documents. + + :attr str collection_id: (optional) The unique identifier of the collection. + :attr str name: (optional) The name of the collection. + """ + + def __init__(self, *, collection_id: str = None, name: str = None) -> None: + """ + Initialize a Collection object. + + :param str collection_id: (optional) The unique identifier of the + collection. + :param str name: (optional) The name of the collection. + """ + self.collection_id = collection_id + self.name = name + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Collection': + """Initialize a Collection object from a json dictionary.""" + args = {} + valid_keys = ['collection_id', 'name'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Collection: ' + + ', '.join(bad_keys)) + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection 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, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + 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 Collection object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Collection') -> 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: 'Collection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionDetails(): + """ + A collection for storing documents. + + :attr str collection_id: (optional) The unique identifier of the collection. + :attr str name: The name of the collection. + :attr str description: (optional) A description of the collection. + :attr datetime created: (optional) The date that the collection was created. + :attr str language: (optional) The language of the collection. + :attr List[CollectionEnrichment] enrichments: (optional) An array of enrichments + that are applied to this collection. + """ + + def __init__(self, + name: str, + *, + collection_id: str = None, + description: str = None, + created: datetime = None, + language: str = None, + enrichments: List['CollectionEnrichment'] = None) -> None: + """ + Initialize a CollectionDetails object. + + :param str name: The name of the collection. + :param str collection_id: (optional) The unique identifier of the + collection. + :param str description: (optional) A description of the collection. + :param datetime created: (optional) The date that the collection was + created. + :param str language: (optional) The language of the collection. + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. + """ + self.collection_id = collection_id + self.name = name + self.description = description + self.created = created + self.language = language + self.enrichments = enrichments + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CollectionDetails': + """Initialize a CollectionDetails object from a json dictionary.""" + args = {} + valid_keys = [ + 'collection_id', 'name', 'description', 'created', 'language', + 'enrichments' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class CollectionDetails: ' + + ', '.join(bad_keys)) + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in CollectionDetails JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'language' in _dict: + args['language'] = _dict.get('language') + if 'enrichments' in _dict: + args['enrichments'] = [ + CollectionEnrichment._from_dict(x) + for x in (_dict.get('enrichments')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionDetails 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, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'enrichments') and self.enrichments is not None: + _dict['enrichments'] = [x._to_dict() for x in self.enrichments] + 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 CollectionDetails object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'CollectionDetails') -> 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: 'CollectionDetails') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionEnrichment(): + """ + An object describing an Enrichment for a collection. + + :attr str enrichment_id: (optional) The unique identifier of this enrichment. + :attr List[str] fields: (optional) An array of field names that the enrichment + is applied to. + """ + + def __init__(self, + *, + enrichment_id: str = None, + fields: List[str] = None) -> None: + """ + Initialize a CollectionEnrichment object. + + :param str enrichment_id: (optional) The unique identifier of this + enrichment. + :param List[str] fields: (optional) An array of field names that the + enrichment is applied to. + """ + self.enrichment_id = enrichment_id + self.fields = fields + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CollectionEnrichment': + """Initialize a CollectionEnrichment object from a json dictionary.""" + args = {} + valid_keys = ['enrichment_id', 'fields'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class CollectionEnrichment: ' + + ', '.join(bad_keys)) + if 'enrichment_id' in _dict: + args['enrichment_id'] = _dict.get('enrichment_id') + if 'fields' in _dict: + args['fields'] = _dict.get('fields') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionEnrichment 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, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + 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 CollectionEnrichment object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'CollectionEnrichment') -> 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: 'CollectionEnrichment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Completions(): + """ + An object containing an array of autocompletion suggestions. + + :attr List[str] completions: (optional) Array of autcomplete suggestion based on + the provided prefix. + """ + + def __init__(self, *, completions: List[str] = None) -> None: + """ + Initialize a Completions object. + + :param List[str] completions: (optional) Array of autcomplete suggestion + based on the provided prefix. + """ + self.completions = completions + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Completions': + """Initialize a Completions object from a json dictionary.""" + args = {} + valid_keys = ['completions'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Completions: ' + + ', '.join(bad_keys)) + if 'completions' in _dict: + args['completions'] = _dict.get('completions') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Completions 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, 'completions') and self.completions is not None: + _dict['completions'] = self.completions + 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 Completions object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Completions') -> 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: 'Completions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsAggregation(): + """ + Display settings for aggregations. + + :attr str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :attr str label: (optional) User-friendly alias for the aggregation. + :attr bool multiple_selections_allowed: (optional) Whether users is allowed to + select more than one of the aggregation terms. + :attr str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + + def __init__(self, + *, + name: str = None, + label: str = None, + multiple_selections_allowed: bool = None, + visualization_type: str = None) -> None: + """ + Initialize a ComponentSettingsAggregation object. + + :param str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :param str label: (optional) User-friendly alias for the aggregation. + :param bool multiple_selections_allowed: (optional) Whether users is + allowed to select more than one of the aggregation terms. + :param str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + self.name = name + self.label = label + self.multiple_selections_allowed = multiple_selections_allowed + self.visualization_type = visualization_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': + """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + args = {} + valid_keys = [ + 'name', 'label', 'multiple_selections_allowed', 'visualization_type' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsAggregation: ' + + ', '.join(bad_keys)) + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'label' in _dict: + args['label'] = _dict.get('label') + if 'multiple_selections_allowed' in _dict: + args['multiple_selections_allowed'] = _dict.get( + 'multiple_selections_allowed') + if 'visualization_type' in _dict: + args['visualization_type'] = _dict.get('visualization_type') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsAggregation 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'multiple_selections_allowed' + ) and self.multiple_selections_allowed is not None: + _dict[ + 'multiple_selections_allowed'] = self.multiple_selections_allowed + if hasattr( + self, + 'visualization_type') and self.visualization_type is not None: + _dict['visualization_type'] = self.visualization_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 ComponentSettingsAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsAggregation') -> 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: 'ComponentSettingsAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class VisualizationTypeEnum(Enum): + """ + Type of visualization to use when rendering the aggregation. + """ + AUTO = "auto" + FACET_TABLE = "facet_table" + WORD_CLOUD = "word_cloud" + MAP = "map" + + +class ComponentSettingsFieldsShown(): + """ + Fields shown in the results section of the UI. + + :attr ComponentSettingsFieldsShownBody body: (optional) Body label. + :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + """ + + def __init__(self, + *, + body: 'ComponentSettingsFieldsShownBody' = None, + title: 'ComponentSettingsFieldsShownTitle' = None) -> None: + """ + Initialize a ComponentSettingsFieldsShown object. + + :param ComponentSettingsFieldsShownBody body: (optional) Body label. + :param ComponentSettingsFieldsShownTitle title: (optional) Title label. + """ + self.body = body + self.title = title + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': + """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + args = {} + valid_keys = ['body', 'title'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShown: ' + + ', '.join(bad_keys)) + if 'body' in _dict: + args['body'] = ComponentSettingsFieldsShownBody._from_dict( + _dict.get('body')) + if 'title' in _dict: + args['title'] = ComponentSettingsFieldsShownTitle._from_dict( + _dict.get('title')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShown 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, 'body') and self.body is not None: + _dict['body'] = self.body._to_dict() + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title._to_dict() + 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 ComponentSettingsFieldsShown object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsFieldsShown') -> 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: 'ComponentSettingsFieldsShown') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsFieldsShownBody(): + """ + Body label. + + :attr bool use_passage: (optional) Use the whole passage as the body. + :attr str field: (optional) Use a specific field as the title. + """ + + def __init__(self, *, use_passage: bool = None, field: str = None) -> None: + """ + Initialize a ComponentSettingsFieldsShownBody object. + + :param bool use_passage: (optional) Use the whole passage as the body. + :param str field: (optional) Use a specific field as the title. + """ + self.use_passage = use_passage + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': + """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + args = {} + valid_keys = ['use_passage', 'field'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownBody: ' + + ', '.join(bad_keys)) + if 'use_passage' in _dict: + args['use_passage'] = _dict.get('use_passage') + if 'field' in _dict: + args['field'] = _dict.get('field') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownBody 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, 'use_passage') and self.use_passage is not None: + _dict['use_passage'] = self.use_passage + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + 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 ComponentSettingsFieldsShownBody object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> 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: 'ComponentSettingsFieldsShownBody') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsFieldsShownTitle(): + """ + Title label. + + :attr str field: (optional) Use a specific field as the title. + """ + + def __init__(self, *, field: str = None) -> None: + """ + Initialize a ComponentSettingsFieldsShownTitle object. + + :param str field: (optional) Use a specific field as the title. + """ + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': + """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + args = {} + valid_keys = ['field'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownTitle: ' + + ', '.join(bad_keys)) + if 'field' in _dict: + args['field'] = _dict.get('field') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownTitle 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, 'field') and self.field is not None: + _dict['field'] = self.field + 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 ComponentSettingsFieldsShownTitle object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> 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: 'ComponentSettingsFieldsShownTitle') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsResponse(): + """ + The default component settings for this project. + + :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the + results section of the UI. + :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. + :attr bool structured_search: (optional) Whether or not structured search is + enabled. + :attr int results_per_page: (optional) Number or results shown per page. + :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of + component setting aggregations. + """ + + def __init__( + self, + *, + fields_shown: 'ComponentSettingsFieldsShown' = None, + autocomplete: bool = None, + structured_search: bool = None, + results_per_page: int = None, + aggregations: List['ComponentSettingsAggregation'] = None) -> None: + """ + Initialize a ComponentSettingsResponse object. + + :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown + in the results section of the UI. + :param bool autocomplete: (optional) Whether or not autocomplete is + enabled. + :param bool structured_search: (optional) Whether or not structured search + is enabled. + :param int results_per_page: (optional) Number or results shown per page. + :param List[ComponentSettingsAggregation] aggregations: (optional) a list + of component setting aggregations. + """ + self.fields_shown = fields_shown + self.autocomplete = autocomplete + self.structured_search = structured_search + self.results_per_page = results_per_page + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': + """Initialize a ComponentSettingsResponse object from a json dictionary.""" + args = {} + valid_keys = [ + 'fields_shown', 'autocomplete', 'structured_search', + 'results_per_page', 'aggregations' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ComponentSettingsResponse: ' + + ', '.join(bad_keys)) + if 'fields_shown' in _dict: + args['fields_shown'] = ComponentSettingsFieldsShown._from_dict( + _dict.get('fields_shown')) + if 'autocomplete' in _dict: + args['autocomplete'] = _dict.get('autocomplete') + if 'structured_search' in _dict: + args['structured_search'] = _dict.get('structured_search') + if 'results_per_page' in _dict: + args['results_per_page'] = _dict.get('results_per_page') + if 'aggregations' in _dict: + args['aggregations'] = [ + ComponentSettingsAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsResponse 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, 'fields_shown') and self.fields_shown is not None: + _dict['fields_shown'] = self.fields_shown._to_dict() + if hasattr(self, 'autocomplete') and self.autocomplete is not None: + _dict['autocomplete'] = self.autocomplete + if hasattr(self, + 'structured_search') and self.structured_search is not None: + _dict['structured_search'] = self.structured_search + if hasattr(self, + 'results_per_page') and self.results_per_page is not None: + _dict['results_per_page'] = self.results_per_page + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + 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 ComponentSettingsResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsResponse') -> 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: 'ComponentSettingsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CreateEnrichment(): + """ + Information about a specific enrichment. + + :attr str name: (optional) The human readable name for this enrichment. + :attr str description: (optional) The description of this enrichment. + :attr str type: (optional) The type of this enrichment. + :attr EnrichmentOptions options: (optional) A object containing options for the + current enrichment. + """ + + def __init__(self, + *, + name: str = None, + description: str = None, + type: str = None, + options: 'EnrichmentOptions' = None) -> None: + """ + Initialize a CreateEnrichment object. + + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. + :param EnrichmentOptions options: (optional) A object containing options + for the current enrichment. + """ + self.name = name + self.description = description + self.type = type + self.options = options + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': + """Initialize a CreateEnrichment object from a json dictionary.""" + args = {} + valid_keys = ['name', 'description', 'type', 'options'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class CreateEnrichment: ' + + ', '.join(bad_keys)) + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'options' in _dict: + args['options'] = EnrichmentOptions._from_dict(_dict.get('options')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateEnrichment 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = self.options._to_dict() + 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 CreateEnrichment object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'CreateEnrichment') -> 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: 'CreateEnrichment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(Enum): + """ + The type of this enrichment. + """ + DICTIONARY = "dictionary" + REGULAR_EXPRESSION = "regular_expression" + UIMA_ANNOTATOR = "uima_annotator" + RULE_BASED = "rule_based" + WATSON_KNOWLEDGE_STUDIO_MODEL = "watson_knowledge_studio_model" + + +class DefaultQueryParams(): + """ + Default query parameters for this project. + + :attr List[str] collection_ids: (optional) An array of collection identifiers to + query. If empty or omitted all collections in the project are queried. + :attr DefaultQueryParamsPassages passages: (optional) Default settings + configuration for passage search options. + :attr DefaultQueryParamsTableResults table_results: (optional) Default project + query settings for table results. + :attr str aggregation: (optional) A string representing the default aggregation + query for the project. + :attr DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) + Object containing suggested refinement settings. + :attr bool spelling_suggestions: (optional) When `true`, a spelling suggestions + for the query are retuned by default. + :attr bool highlight: (optional) When `true`, a highlights for the query are + retuned by default. + :attr int count: (optional) The number of document results returned by default. + :attr str sort: (optional) A comma separated list of document fields to sort + results by default. + :attr List[str] return_: (optional) An array of field names to return in + document results if present by default. + """ + + def __init__(self, + *, + collection_ids: List[str] = None, + passages: 'DefaultQueryParamsPassages' = None, + table_results: 'DefaultQueryParamsTableResults' = None, + aggregation: str = None, + suggested_refinements: + 'DefaultQueryParamsSuggestedRefinements' = None, + spelling_suggestions: bool = None, + highlight: bool = None, + count: int = None, + sort: str = None, + return_: List[str] = None) -> None: + """ + Initialize a DefaultQueryParams object. + + :param List[str] collection_ids: (optional) An array of collection + identifiers to query. If empty or omitted all collections in the project + are queried. + :param DefaultQueryParamsPassages passages: (optional) Default settings + configuration for passage search options. + :param DefaultQueryParamsTableResults table_results: (optional) Default + project query settings for table results. + :param str aggregation: (optional) A string representing the default + aggregation query for the project. + :param DefaultQueryParamsSuggestedRefinements suggested_refinements: + (optional) Object containing suggested refinement settings. + :param bool spelling_suggestions: (optional) When `true`, a spelling + suggestions for the query are retuned by default. + :param bool highlight: (optional) When `true`, a highlights for the query + are retuned by default. + :param int count: (optional) The number of document results returned by + default. + :param str sort: (optional) A comma separated list of document fields to + sort results by default. + :param List[str] return_: (optional) An array of field names to return in + document results if present by default. + """ + self.collection_ids = collection_ids + self.passages = passages + self.table_results = table_results + self.aggregation = aggregation + self.suggested_refinements = suggested_refinements + self.spelling_suggestions = spelling_suggestions + self.highlight = highlight + self.count = count + self.sort = sort + self.return_ = return_ + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParams': + """Initialize a DefaultQueryParams object from a json dictionary.""" + args = {} + valid_keys = [ + 'collection_ids', 'passages', 'table_results', 'aggregation', + 'suggested_refinements', 'spelling_suggestions', 'highlight', + 'count', 'sort', 'return_', 'return' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DefaultQueryParams: ' + + ', '.join(bad_keys)) + if 'collection_ids' in _dict: + args['collection_ids'] = _dict.get('collection_ids') + if 'passages' in _dict: + args['passages'] = DefaultQueryParamsPassages._from_dict( + _dict.get('passages')) + if 'table_results' in _dict: + args['table_results'] = DefaultQueryParamsTableResults._from_dict( + _dict.get('table_results')) + if 'aggregation' in _dict: + args['aggregation'] = _dict.get('aggregation') + if 'suggested_refinements' in _dict: + args[ + 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements._from_dict( + _dict.get('suggested_refinements')) + if 'spelling_suggestions' in _dict: + args['spelling_suggestions'] = _dict.get('spelling_suggestions') + if 'highlight' in _dict: + args['highlight'] = _dict.get('highlight') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'sort' in _dict: + args['sort'] = _dict.get('sort') + if 'return' in _dict: + args['return_'] = _dict.get('return') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DefaultQueryParams 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, 'collection_ids') and self.collection_ids is not None: + _dict['collection_ids'] = self.collection_ids + if hasattr(self, 'passages') and self.passages is not None: + _dict['passages'] = self.passages._to_dict() + if hasattr(self, 'table_results') and self.table_results is not None: + _dict['table_results'] = self.table_results._to_dict() + if hasattr(self, 'aggregation') and self.aggregation is not None: + _dict['aggregation'] = self.aggregation + if hasattr(self, 'suggested_refinements' + ) and self.suggested_refinements is not None: + _dict[ + 'suggested_refinements'] = self.suggested_refinements._to_dict( + ) + if hasattr(self, 'spelling_suggestions' + ) and self.spelling_suggestions is not None: + _dict['spelling_suggestions'] = self.spelling_suggestions + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'sort') and self.sort is not None: + _dict['sort'] = self.sort + if hasattr(self, 'return_') and self.return_ is not None: + _dict['return'] = self.return_ + 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 DefaultQueryParams object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'DefaultQueryParams') -> 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: 'DefaultQueryParams') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DefaultQueryParamsPassages(): + """ + Default settings configuration for passage search options. + + :attr bool enabled: (optional) When `true`, a passage search is performed by + default. + :attr int count: (optional) The number of passages to return. + :attr List[str] fields: (optional) An array of field names to perfom the passage + search on. + :attr int characters: (optional) The approximate number of characters that each + returned passage will contain. + :attr bool per_document: (optional) When `true` the number of passages that can + be returned from a single document is restricted to the *max_per_document* + value. + :attr int max_per_document: (optional) The default maximum number of passages + that can be taken from a single document as the result of a passage query. + """ + + def __init__(self, + *, + enabled: bool = None, + count: int = None, + fields: List[str] = None, + characters: int = None, + per_document: bool = None, + max_per_document: int = None) -> None: + """ + Initialize a DefaultQueryParamsPassages object. + + :param bool enabled: (optional) When `true`, a passage search is performed + by default. + :param int count: (optional) The number of passages to return. + :param List[str] fields: (optional) An array of field names to perfom the + passage search on. + :param int characters: (optional) The approximate number of characters that + each returned passage will contain. + :param bool per_document: (optional) When `true` the number of passages + that can be returned from a single document is restricted to the + *max_per_document* value. + :param int max_per_document: (optional) The default maximum number of + passages that can be taken from a single document as the result of a + passage query. + """ + self.enabled = enabled + self.count = count + self.fields = fields + self.characters = characters + self.per_document = per_document + self.max_per_document = max_per_document + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsPassages': + """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" + args = {} + valid_keys = [ + 'enabled', 'count', 'fields', 'characters', 'per_document', + 'max_per_document' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DefaultQueryParamsPassages: ' + + ', '.join(bad_keys)) + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'fields' in _dict: + args['fields'] = _dict.get('fields') + if 'characters' in _dict: + args['characters'] = _dict.get('characters') + if 'per_document' in _dict: + args['per_document'] = _dict.get('per_document') + if 'max_per_document' in _dict: + args['max_per_document'] = _dict.get('max_per_document') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DefaultQueryParamsPassages 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 + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + if hasattr(self, 'characters') and self.characters is not None: + _dict['characters'] = self.characters + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document + if hasattr(self, + 'max_per_document') and self.max_per_document is not None: + _dict['max_per_document'] = self.max_per_document + 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 DefaultQueryParamsPassages object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'DefaultQueryParamsPassages') -> 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: 'DefaultQueryParamsPassages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DefaultQueryParamsSuggestedRefinements(): + """ + Object containing suggested refinement settings. + + :attr bool enabled: (optional) When `true`, a suggested refinements for the + query are retuned by default. + :attr int count: (optional) The number of suggested refinements to return by + default. + """ + + def __init__(self, *, enabled: bool = None, count: int = None) -> None: + """ + Initialize a DefaultQueryParamsSuggestedRefinements object. + + :param bool enabled: (optional) When `true`, a suggested refinements for + the query are retuned by default. + :param int count: (optional) The number of suggested refinements to return + by default. + """ + self.enabled = enabled + self.count = count + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsSuggestedRefinements': + """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" + args = {} + valid_keys = ['enabled', 'count'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DefaultQueryParamsSuggestedRefinements: ' + + ', '.join(bad_keys)) + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DefaultQueryParamsSuggestedRefinements 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 + 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 DefaultQueryParamsSuggestedRefinements object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> 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: 'Collection') -> bool: + def __ne__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Completions(): +class DefaultQueryParamsTableResults(): """ - An object containing an array of autocompletion suggestions. + Default project query settings for table results. - :attr List[str] completions: (optional) Array of autcomplete suggestion based on - the provided prefix. + :attr bool enabled: (optional) When `true`, a table results for the query are + retuned by default. + :attr int count: (optional) The number of table results to return by default. + :attr int per_document: (optional) The number of table results to include in + each result document. """ - def __init__(self, *, completions: List[str] = None) -> None: + def __init__(self, + *, + enabled: bool = None, + count: int = None, + per_document: int = None) -> None: """ - Initialize a Completions object. + Initialize a DefaultQueryParamsTableResults object. - :param List[str] completions: (optional) Array of autcomplete suggestion - based on the provided prefix. + :param bool enabled: (optional) When `true`, a table results for the query + are retuned by default. + :param int count: (optional) The number of table results to return by + default. + :param int per_document: (optional) The number of table results to include + in each result document. """ - self.completions = completions + self.enabled = enabled + self.count = count + self.per_document = per_document @classmethod - def from_dict(cls, _dict: Dict) -> 'Completions': - """Initialize a Completions object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsTableResults': + """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" args = {} - valid_keys = ['completions'] + valid_keys = ['enabled', 'count', 'per_document'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class Completions: ' + 'Unrecognized keys detected in dictionary for class DefaultQueryParamsTableResults: ' + ', '.join(bad_keys)) - if 'completions' in _dict: - args['completions'] = _dict.get('completions') + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'per_document' in _dict: + args['per_document'] = _dict.get('per_document') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Completions object from a json dictionary.""" + """Initialize a DefaultQueryParamsTableResults 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, 'completions') and self.completions is not None: - _dict['completions'] = self.completions + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document return _dict def _to_dict(self): @@ -1101,98 +2928,241 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Completions object.""" + """Return a `str` version of this DefaultQueryParamsTableResults object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'Completions') -> bool: + def __eq__(self, other: 'DefaultQueryParamsTableResults') -> 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: 'Completions') -> bool: + def __ne__(self, other: 'DefaultQueryParamsTableResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsAggregation(): +class DeleteDocumentResponse(): """ - Display settings for aggregations. + Information returned when a document is deleted. - :attr str name: (optional) Identifier used to map aggregation settings to - aggregation configuration. - :attr str label: (optional) User-friendly alias for the aggregation. - :attr bool multiple_selections_allowed: (optional) Whether users is allowed to - select more than one of the aggregation terms. - :attr str visualization_type: (optional) Type of visualization to use when - rendering the aggregation. + :attr str document_id: (optional) The unique identifier of the document. + :attr str status: (optional) Status of the document. A deleted document has the + status deleted. + """ + + def __init__(self, *, document_id: str = None, status: str = None) -> None: + """ + Initialize a DeleteDocumentResponse object. + + :param str document_id: (optional) The unique identifier of the document. + :param str status: (optional) Status of the document. A deleted document + has the status deleted. + """ + self.document_id = document_id + self.status = status + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': + """Initialize a DeleteDocumentResponse object from a json dictionary.""" + args = {} + valid_keys = ['document_id', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DeleteDocumentResponse: ' + + ', '.join(bad_keys)) + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DeleteDocumentResponse 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, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + 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 DeleteDocumentResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'DeleteDocumentResponse') -> 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: 'DeleteDocumentResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(Enum): + """ + Status of the document. A deleted document has the status deleted. + """ + DELETED = "deleted" + + +class DocumentAccepted(): + """ + Information returned after an uploaded document is accepted. + + :attr str document_id: (optional) The unique identifier of the ingested + document. + :attr str status: (optional) Status of the document in the ingestion process. A + status of `processing` is returned for documents that are ingested with a + *version* date before `2019-01-01`. The `pending` status is returned for all + others. + """ + + def __init__(self, *, document_id: str = None, status: str = None) -> None: + """ + Initialize a DocumentAccepted object. + + :param str document_id: (optional) The unique identifier of the ingested + document. + :param str status: (optional) Status of the document in the ingestion + process. A status of `processing` is returned for documents that are + ingested with a *version* date before `2019-01-01`. The `pending` status is + returned for all others. + """ + self.document_id = document_id + self.status = status + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': + """Initialize a DocumentAccepted object from a json dictionary.""" + args = {} + valid_keys = ['document_id', 'status'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DocumentAccepted: ' + + ', '.join(bad_keys)) + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DocumentAccepted 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, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + 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 DocumentAccepted object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'DocumentAccepted') -> 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: 'DocumentAccepted') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(Enum): + """ + Status of the document in the ingestion process. A status of `processing` is + returned for documents that are ingested with a *version* date before + `2019-01-01`. The `pending` status is returned for all others. + """ + PROCESSING = "processing" + PENDING = "pending" + + +class DocumentAttribute(): + """ + List of document attributes. + + :attr str type: (optional) The type of attribute. + :attr str text: (optional) The text associated with the attribute. + :attr TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. """ def __init__(self, *, - name: str = None, - label: str = None, - multiple_selections_allowed: bool = None, - visualization_type: str = None) -> None: + type: str = None, + text: str = None, + location: 'TableElementLocation' = None) -> None: """ - Initialize a ComponentSettingsAggregation object. + Initialize a DocumentAttribute object. - :param str name: (optional) Identifier used to map aggregation settings to - aggregation configuration. - :param str label: (optional) User-friendly alias for the aggregation. - :param bool multiple_selections_allowed: (optional) Whether users is - allowed to select more than one of the aggregation terms. - :param str visualization_type: (optional) Type of visualization to use when - rendering the aggregation. + :param str type: (optional) The type of attribute. + :param str text: (optional) The text associated with the attribute. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. """ - self.name = name - self.label = label - self.multiple_selections_allowed = multiple_selections_allowed - self.visualization_type = visualization_type + self.type = type + self.text = text + self.location = location @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': - """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': + """Initialize a DocumentAttribute object from a json dictionary.""" args = {} - valid_keys = [ - 'name', 'label', 'multiple_selections_allowed', 'visualization_type' - ] + valid_keys = ['type', 'text', 'location'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsAggregation: ' + 'Unrecognized keys detected in dictionary for class DocumentAttribute: ' + ', '.join(bad_keys)) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'multiple_selections_allowed' in _dict: - args['multiple_selections_allowed'] = _dict.get( - 'multiple_selections_allowed') - if 'visualization_type' in _dict: - args['visualization_type'] = _dict.get('visualization_type') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'location' in _dict: + args['location'] = TableElementLocation._from_dict( + _dict.get('location')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + """Initialize a DocumentAttribute 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'multiple_selections_allowed' - ) and self.multiple_selections_allowed is not None: - _dict[ - 'multiple_selections_allowed'] = self.multiple_selections_allowed - if hasattr( - self, - 'visualization_type') and self.visualization_type is not None: - _dict['visualization_type'] = self.visualization_type + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location._to_dict() return _dict def _to_dict(self): @@ -1200,80 +3170,96 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsAggregation object.""" + """Return a `str` version of this DocumentAttribute object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsAggregation') -> bool: + def __eq__(self, other: 'DocumentAttribute') -> 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: 'ComponentSettingsAggregation') -> bool: + def __ne__(self, other: 'DocumentAttribute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class VisualizationTypeEnum(Enum): - """ - Type of visualization to use when rendering the aggregation. - """ - AUTO = "auto" - FACET_TABLE = "facet_table" - WORD_CLOUD = "word_cloud" - MAP = "map" - -class ComponentSettingsFieldsShown(): +class Enrichment(): """ - Fields shown in the results section of the UI. - - :attr ComponentSettingsFieldsShownBody body: (optional) Body label. - :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + Information about a specific enrichment. + + :attr str enrichment_id: (optional) The unique identifier of this enrichment. + :attr str name: (optional) The human readable name for this enrichment. + :attr str description: (optional) The description of this enrichment. + :attr str type: (optional) The type of this enrichment. + :attr EnrichmentOptions options: (optional) A object containing options for the + current enrichment. """ def __init__(self, *, - body: 'ComponentSettingsFieldsShownBody' = None, - title: 'ComponentSettingsFieldsShownTitle' = None) -> None: + enrichment_id: str = None, + name: str = None, + description: str = None, + type: str = None, + options: 'EnrichmentOptions' = None) -> None: """ - Initialize a ComponentSettingsFieldsShown object. + Initialize a Enrichment object. - :param ComponentSettingsFieldsShownBody body: (optional) Body label. - :param ComponentSettingsFieldsShownTitle title: (optional) Title label. + :param str enrichment_id: (optional) The unique identifier of this + enrichment. + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. + :param EnrichmentOptions options: (optional) A object containing options + for the current enrichment. """ - self.body = body - self.title = title + self.enrichment_id = enrichment_id + self.name = name + self.description = description + self.type = type + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': - """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Enrichment': + """Initialize a Enrichment object from a json dictionary.""" args = {} - valid_keys = ['body', 'title'] + valid_keys = ['enrichment_id', 'name', 'description', 'type', 'options'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShown: ' + 'Unrecognized keys detected in dictionary for class Enrichment: ' + ', '.join(bad_keys)) - if 'body' in _dict: - args['body'] = ComponentSettingsFieldsShownBody._from_dict( - _dict.get('body')) - if 'title' in _dict: - args['title'] = ComponentSettingsFieldsShownTitle._from_dict( - _dict.get('title')) + if 'enrichment_id' in _dict: + args['enrichment_id'] = _dict.get('enrichment_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'options' in _dict: + args['options'] = EnrichmentOptions._from_dict(_dict.get('options')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + """Initialize a Enrichment 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, 'body') and self.body is not None: - _dict['body'] = self.body._to_dict() - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title._to_dict() + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = self.options._to_dict() return _dict def _to_dict(self): @@ -1281,66 +3267,117 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShown object.""" + """Return a `str` version of this Enrichment object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShown') -> bool: + def __eq__(self, other: 'Enrichment') -> 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: 'ComponentSettingsFieldsShown') -> bool: + def __ne__(self, other: 'Enrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The type of this enrichment. + """ + PART_OF_SPEECH = "part_of_speech" + SENTIMENT = "sentiment" + NATURAL_LANGUAGE_UNDERSTANDING = "natural_language_understanding" + DICTIONARY = "dictionary" + REGULAR_EXPRESSION = "regular_expression" + UIMA_ANNOTATOR = "uima_annotator" + RULE_BASED = "rule_based" + WATSON_KNOWLEDGE_STUDIO_MODEL = "watson_knowledge_studio_model" -class ComponentSettingsFieldsShownBody(): - """ - Body label. - :attr bool use_passage: (optional) Use the whole passage as the body. - :attr str field: (optional) Use a specific field as the title. +class EnrichmentOptions(): + """ + A object containing options for the current enrichment. + + :attr List[str] languages: (optional) An array of supported languages for this + enrichment. + :attr str entity_type: (optional) The type of entity. Required when creating + `dictionary` and `regular_expression` **type** enrichment. Not valid when + creating any other type of enrichment. + :attr str regular_expression: (optional) The regular expression to apply for + this enrichment. Required only when the **type** of enrichment being created is + a `regular_expression`. Not valid when creating any other type of enrichment. + :attr str result_field: (optional) The name of the result document field that + this enrichment creates. Required only when the enrichment **type** is + `rule_based`. Not valid when creating any other type of enrichment. """ - def __init__(self, *, use_passage: bool = None, field: str = None) -> None: - """ - Initialize a ComponentSettingsFieldsShownBody object. - - :param bool use_passage: (optional) Use the whole passage as the body. - :param str field: (optional) Use a specific field as the title. - """ - self.use_passage = use_passage - self.field = field + def __init__(self, + *, + languages: List[str] = None, + entity_type: str = None, + regular_expression: str = None, + result_field: str = None) -> None: + """ + Initialize a EnrichmentOptions object. + + :param List[str] languages: (optional) An array of supported languages for + this enrichment. + :param str entity_type: (optional) The type of entity. Required when + creating `dictionary` and `regular_expression` **type** enrichment. Not + valid when creating any other type of enrichment. + :param str regular_expression: (optional) The regular expression to apply + for this enrichment. Required only when the **type** of enrichment being + created is a `regular_expression`. Not valid when creating any other type + of enrichment. + :param str result_field: (optional) The name of the result document field + that this enrichment creates. Required only when the enrichment **type** is + `rule_based`. Not valid when creating any other type of enrichment. + """ + self.languages = languages + self.entity_type = entity_type + self.regular_expression = regular_expression + self.result_field = result_field @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': - """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': + """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} - valid_keys = ['use_passage', 'field'] + valid_keys = [ + 'languages', 'entity_type', 'regular_expression', 'result_field' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownBody: ' + 'Unrecognized keys detected in dictionary for class EnrichmentOptions: ' + ', '.join(bad_keys)) - if 'use_passage' in _dict: - args['use_passage'] = _dict.get('use_passage') - if 'field' in _dict: - args['field'] = _dict.get('field') + if 'languages' in _dict: + args['languages'] = _dict.get('languages') + if 'entity_type' in _dict: + args['entity_type'] = _dict.get('entity_type') + if 'regular_expression' in _dict: + args['regular_expression'] = _dict.get('regular_expression') + if 'result_field' in _dict: + args['result_field'] = _dict.get('result_field') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + """Initialize a EnrichmentOptions 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, 'use_passage') and self.use_passage is not None: - _dict['use_passage'] = self.use_passage - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field + if hasattr(self, 'languages') and self.languages is not None: + _dict['languages'] = self.languages + if hasattr(self, 'entity_type') and self.entity_type is not None: + _dict['entity_type'] = self.entity_type + if hasattr( + self, + 'regular_expression') and self.regular_expression is not None: + _dict['regular_expression'] = self.regular_expression + if hasattr(self, 'result_field') and self.result_field is not None: + _dict['result_field'] = self.result_field return _dict def _to_dict(self): @@ -1348,59 +3385,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShownBody object.""" + """Return a `str` version of this EnrichmentOptions object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + def __eq__(self, other: 'EnrichmentOptions') -> 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: 'ComponentSettingsFieldsShownBody') -> bool: + def __ne__(self, other: 'EnrichmentOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsFieldsShownTitle(): +class Enrichments(): """ - Title label. + An object containing an array of enrichment definitions. - :attr str field: (optional) Use a specific field as the title. + :attr List[Enrichment] enrichments: (optional) An array of enrichment + definitions. """ - def __init__(self, *, field: str = None) -> None: + def __init__(self, *, enrichments: List['Enrichment'] = None) -> None: """ - Initialize a ComponentSettingsFieldsShownTitle object. + Initialize a Enrichments object. - :param str field: (optional) Use a specific field as the title. + :param List[Enrichment] enrichments: (optional) An array of enrichment + definitions. """ - self.field = field + self.enrichments = enrichments @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': - """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Enrichments': + """Initialize a Enrichments object from a json dictionary.""" args = {} - valid_keys = ['field'] + valid_keys = ['enrichments'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownTitle: ' + 'Unrecognized keys detected in dictionary for class Enrichments: ' + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') + if 'enrichments' in _dict: + args['enrichments'] = [ + Enrichment._from_dict(x) for x in (_dict.get('enrichments')) + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + """Initialize a Enrichments 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, 'field') and self.field is not None: - _dict['field'] = self.field + if hasattr(self, 'enrichments') and self.enrichments is not None: + _dict['enrichments'] = [x._to_dict() for x in self.enrichments] return _dict def _to_dict(self): @@ -1408,110 +3449,79 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShownTitle object.""" + """Return a `str` version of this Enrichments object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: + def __eq__(self, other: 'Enrichments') -> 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: 'ComponentSettingsFieldsShownTitle') -> bool: + def __ne__(self, other: 'Enrichments') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsResponse(): +class Field(): """ - A response containing the default component settings. + Object containing field details. - :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the - results section of the UI. - :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. - :attr bool structured_search: (optional) Whether or not structured search is - enabled. - :attr int results_per_page: (optional) Number or results shown per page. - :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of - component setting aggregations. + :attr str field: (optional) The name of the field. + :attr str type: (optional) The type of the field. + :attr str collection_id: (optional) The collection Id of the collection where + the field was found. """ - def __init__( - self, - *, - fields_shown: 'ComponentSettingsFieldsShown' = None, - autocomplete: bool = None, - structured_search: bool = None, - results_per_page: int = None, - aggregations: List['ComponentSettingsAggregation'] = None) -> None: + def __init__(self, + *, + field: str = None, + type: str = None, + collection_id: str = None) -> None: """ - Initialize a ComponentSettingsResponse object. + Initialize a Field object. - :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown - in the results section of the UI. - :param bool autocomplete: (optional) Whether or not autocomplete is - enabled. - :param bool structured_search: (optional) Whether or not structured search - is enabled. - :param int results_per_page: (optional) Number or results shown per page. - :param List[ComponentSettingsAggregation] aggregations: (optional) a list - of component setting aggregations. + :param str field: (optional) The name of the field. + :param str type: (optional) The type of the field. + :param str collection_id: (optional) The collection Id of the collection + where the field was found. """ - self.fields_shown = fields_shown - self.autocomplete = autocomplete - self.structured_search = structured_search - self.results_per_page = results_per_page - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': - """Initialize a ComponentSettingsResponse object from a json dictionary.""" - args = {} - valid_keys = [ - 'fields_shown', 'autocomplete', 'structured_search', - 'results_per_page', 'aggregations' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsResponse: ' - + ', '.join(bad_keys)) - if 'fields_shown' in _dict: - args['fields_shown'] = ComponentSettingsFieldsShown._from_dict( - _dict.get('fields_shown')) - if 'autocomplete' in _dict: - args['autocomplete'] = _dict.get('autocomplete') - if 'structured_search' in _dict: - args['structured_search'] = _dict.get('structured_search') - if 'results_per_page' in _dict: - args['results_per_page'] = _dict.get('results_per_page') - if 'aggregations' in _dict: - args['aggregations'] = [ - ComponentSettingsAggregation._from_dict(x) - for x in (_dict.get('aggregations')) - ] + self.field = field + self.type = type + self.collection_id = collection_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Field': + """Initialize a Field object from a json dictionary.""" + args = {} + valid_keys = ['field', 'type', 'collection_id'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Field: ' + + ', '.join(bad_keys)) + if 'field' in _dict: + args['field'] = _dict.get('field') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsResponse object from a json dictionary.""" + """Initialize a Field 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, 'fields_shown') and self.fields_shown is not None: - _dict['fields_shown'] = self.fields_shown._to_dict() - if hasattr(self, 'autocomplete') and self.autocomplete is not None: - _dict['autocomplete'] = self.autocomplete - if hasattr(self, - 'structured_search') and self.structured_search is not None: - _dict['structured_search'] = self.structured_search - if hasattr(self, - 'results_per_page') and self.results_per_page is not None: - _dict['results_per_page'] = self.results_per_page - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id return _dict def _to_dict(self): @@ -1519,68 +3529,79 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsResponse object.""" + """Return a `str` version of this Field object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsResponse') -> bool: + def __eq__(self, other: 'Field') -> 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: 'ComponentSettingsResponse') -> bool: + def __ne__(self, other: 'Field') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The type of the field. + """ + NESTED = "nested" + STRING = "string" + DATE = "date" + LONG = "long" + INTEGER = "integer" + SHORT = "short" + BYTE = "byte" + DOUBLE = "double" + FLOAT = "float" + BOOLEAN = "boolean" + BINARY = "binary" + -class DeleteDocumentResponse(): +class ListCollectionsResponse(): """ - Information returned when a document is deleted. + Response object containing an array of collection details. - :attr str document_id: (optional) The unique identifier of the document. - :attr str status: (optional) Status of the document. A deleted document has the - status deleted. + :attr List[Collection] collections: (optional) An array containing information + about each collection in the project. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__(self, *, collections: List['Collection'] = None) -> None: """ - Initialize a DeleteDocumentResponse object. + Initialize a ListCollectionsResponse object. - :param str document_id: (optional) The unique identifier of the document. - :param str status: (optional) Status of the document. A deleted document - has the status deleted. + :param List[Collection] collections: (optional) An array containing + information about each collection in the project. """ - self.document_id = document_id - self.status = status + self.collections = collections @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': - """Initialize a DeleteDocumentResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': + """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} - valid_keys = ['document_id', 'status'] + valid_keys = ['collections'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class DeleteDocumentResponse: ' + 'Unrecognized keys detected in dictionary for class ListCollectionsResponse: ' + ', '.join(bad_keys)) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if 'collections' in _dict: + args['collections'] = [ + Collection._from_dict(x) for x in (_dict.get('collections')) + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DeleteDocumentResponse object from a json dictionary.""" + """Initialize a ListCollectionsResponse 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, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status + if hasattr(self, 'collections') and self.collections is not None: + _dict['collections'] = [x._to_dict() for x in self.collections] return _dict def _to_dict(self): @@ -1588,80 +3609,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DeleteDocumentResponse object.""" + """Return a `str` version of this ListCollectionsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'DeleteDocumentResponse') -> bool: + def __eq__(self, other: 'ListCollectionsResponse') -> 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: 'DeleteDocumentResponse') -> bool: + def __ne__(self, other: 'ListCollectionsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): - """ - Status of the document. A deleted document has the status deleted. - """ - DELETED = "deleted" - -class DocumentAccepted(): +class ListFieldsResponse(): """ - Information returned after an uploaded document is accepted. + The list of fetched fields. + The fields are returned using a fully qualified name format, however, the format + differs slightly from that used by the query operations. + * Fields which contain nested objects are assigned a type of "nested". + * Fields which belong to a nested object are prefixed with `.properties` (for + example, `warnings.properties.severity` means that the `warnings` object has a + property called `severity`). - :attr str document_id: (optional) The unique identifier of the ingested - document. - :attr str status: (optional) Status of the document in the ingestion process. A - status of `processing` is returned for documents that are ingested with a - *version* date before `2019-01-01`. The `pending` status is returned for all - others. + :attr List[Field] fields: (optional) An array containing information about each + field in the collections. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__(self, *, fields: List['Field'] = None) -> None: """ - Initialize a DocumentAccepted object. + Initialize a ListFieldsResponse object. - :param str document_id: (optional) The unique identifier of the ingested - document. - :param str status: (optional) Status of the document in the ingestion - process. A status of `processing` is returned for documents that are - ingested with a *version* date before `2019-01-01`. The `pending` status is - returned for all others. + :param List[Field] fields: (optional) An array containing information about + each field in the collections. """ - self.document_id = document_id - self.status = status + self.fields = fields @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': - """Initialize a DocumentAccepted object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': + """Initialize a ListFieldsResponse object from a json dictionary.""" args = {} - valid_keys = ['document_id', 'status'] + valid_keys = ['fields'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentAccepted: ' + 'Unrecognized keys detected in dictionary for class ListFieldsResponse: ' + ', '.join(bad_keys)) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if 'fields' in _dict: + args['fields'] = [ + Field._from_dict(x) for x in (_dict.get('fields')) + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DocumentAccepted object from a json dictionary.""" + """Initialize a ListFieldsResponse 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, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = [x._to_dict() for x in self.fields] return _dict def _to_dict(self): @@ -1669,91 +3679,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DocumentAccepted object.""" + """Return a `str` version of this ListFieldsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'DocumentAccepted') -> bool: + def __eq__(self, other: 'ListFieldsResponse') -> 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: 'DocumentAccepted') -> bool: + def __ne__(self, other: 'ListFieldsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): - """ - Status of the document in the ingestion process. A status of `processing` is - returned for documents that are ingested with a *version* date before - `2019-01-01`. The `pending` status is returned for all others. - """ - PROCESSING = "processing" - PENDING = "pending" - -class DocumentAttribute(): +class ListProjectsResponse(): """ - List of document attributes. + A list of projects in this instance. - :attr str type: (optional) The type of attribute. - :attr str text: (optional) The text associated with the attribute. - :attr TableElementLocation location: (optional) The numeric location of the - identified element in the document, represented with two integers labeled - `begin` and `end`. + :attr List[ProjectListDetails] projects: (optional) An array of project details. """ - def __init__(self, - *, - type: str = None, - text: str = None, - location: 'TableElementLocation' = None) -> None: + def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: """ - Initialize a DocumentAttribute object. + Initialize a ListProjectsResponse object. - :param str type: (optional) The type of attribute. - :param str text: (optional) The text associated with the attribute. - :param TableElementLocation location: (optional) The numeric location of - the identified element in the document, represented with two integers - labeled `begin` and `end`. + :param List[ProjectListDetails] projects: (optional) An array of project + details. """ - self.type = type - self.text = text - self.location = location + self.projects = projects @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': - """Initialize a DocumentAttribute object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ListProjectsResponse': + """Initialize a ListProjectsResponse object from a json dictionary.""" args = {} - valid_keys = ['type', 'text', 'location'] + valid_keys = ['projects'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentAttribute: ' + 'Unrecognized keys detected in dictionary for class ListProjectsResponse: ' + ', '.join(bad_keys)) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = TableElementLocation._from_dict( - _dict.get('location')) + if 'projects' in _dict: + args['projects'] = [ + ProjectListDetails._from_dict(x) + for x in (_dict.get('projects')) + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DocumentAttribute object from a json dictionary.""" + """Initialize a ListProjectsResponse 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 - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + if hasattr(self, 'projects') and self.projects is not None: + _dict['projects'] = [x._to_dict() for x in self.projects] return _dict def _to_dict(self): @@ -1761,79 +3743,152 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DocumentAttribute object.""" + """Return a `str` version of this ListProjectsResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'DocumentAttribute') -> bool: + def __eq__(self, other: 'ListProjectsResponse') -> 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: 'DocumentAttribute') -> bool: + def __ne__(self, other: 'ListProjectsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Field(): +class Notice(): """ - Object containing field details. + A notice produced for the collection. - :attr str field: (optional) The name of the field. - :attr str type: (optional) The type of the field. - :attr str collection_id: (optional) The collection Id of the collection where - the field was found. + :attr str notice_id: (optional) Identifies the notice. Many notices might have + the same ID. This field exists so that user applications can programmatically + identify a notice and take automatic corrective action. Typical notice IDs + include: `index_failed`, `index_failed_too_many_requests`, + `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, + `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, + `missing_model`, `unsupported_model`, + `smart_document_understanding_failed_incompatible_field`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_warning`, + `smart_document_understanding_page_error`, + `smart_document_understanding_page_warning`. **Note:** This is not a complete + list, other values might be returned. + :attr datetime created: (optional) The creation date of the collection in the + format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :attr str document_id: (optional) Unique identifier of the document. + :attr str collection_id: (optional) Unique identifier of the collection. + :attr str query_id: (optional) Unique identifier of the query used for relevance + training. + :attr str severity: (optional) Severity level of the notice. + :attr str step: (optional) Ingestion or training step in which the notice + occurred. + :attr str description: (optional) The description of the notice. """ def __init__(self, *, - field: str = None, - type: str = None, - collection_id: str = None) -> None: + notice_id: str = None, + created: datetime = None, + document_id: str = None, + collection_id: str = None, + query_id: str = None, + severity: str = None, + step: str = None, + description: str = None) -> None: """ - Initialize a Field object. + Initialize a Notice object. - :param str field: (optional) The name of the field. - :param str type: (optional) The type of the field. - :param str collection_id: (optional) The collection Id of the collection - where the field was found. + :param str notice_id: (optional) Identifies the notice. Many notices might + have the same ID. This field exists so that user applications can + programmatically identify a notice and take automatic corrective action. + Typical notice IDs include: `index_failed`, + `index_failed_too_many_requests`, `index_failed_incompatible_field`, + `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, + `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, + `smart_document_understanding_failed_incompatible_field`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_internal_error`, + `smart_document_understanding_failed_warning`, + `smart_document_understanding_page_error`, + `smart_document_understanding_page_warning`. **Note:** This is not a + complete list, other values might be returned. + :param datetime created: (optional) The creation date of the collection in + the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :param str document_id: (optional) Unique identifier of the document. + :param str collection_id: (optional) Unique identifier of the collection. + :param str query_id: (optional) Unique identifier of the query used for + relevance training. + :param str severity: (optional) Severity level of the notice. + :param str step: (optional) Ingestion or training step in which the notice + occurred. + :param str description: (optional) The description of the notice. """ - self.field = field - self.type = type + self.notice_id = notice_id + self.created = created + self.document_id = document_id self.collection_id = collection_id + self.query_id = query_id + self.severity = severity + self.step = step + self.description = description @classmethod - def from_dict(cls, _dict: Dict) -> 'Field': - """Initialize a Field object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Notice': + """Initialize a Notice object from a json dictionary.""" args = {} - valid_keys = ['field', 'type', 'collection_id'] + valid_keys = [ + 'notice_id', 'created', 'document_id', 'collection_id', 'query_id', + 'severity', 'step', 'description' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class Field: ' + + 'Unrecognized keys detected in dictionary for class Notice: ' + ', '.join(bad_keys)) - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'type' in _dict: - args['type'] = _dict.get('type') + if 'notice_id' in _dict: + args['notice_id'] = _dict.get('notice_id') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') + if 'query_id' in _dict: + args['query_id'] = _dict.get('query_id') + if 'severity' in _dict: + args['severity'] = _dict.get('severity') + if 'step' in _dict: + args['step'] = _dict.get('step') + if 'description' in _dict: + args['description'] = _dict.get('description') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Field object from a json dictionary.""" + """Initialize a Notice 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, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type + if hasattr(self, 'notice_id') and self.notice_id is not None: + _dict['notice_id'] = self.notice_id + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id + if hasattr(self, 'query_id') and self.query_id is not None: + _dict['query_id'] = self.query_id + if hasattr(self, 'severity') and self.severity is not None: + _dict['severity'] = self.severity + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description return _dict def _to_dict(self): @@ -1841,79 +3896,128 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Field object.""" + """Return a `str` version of this Notice object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'Field') -> bool: + def __eq__(self, other: 'Notice') -> 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: 'Field') -> bool: + def __ne__(self, other: 'Notice') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class SeverityEnum(Enum): """ - The type of the field. + Severity level of the notice. """ - NESTED = "nested" - STRING = "string" - DATE = "date" - LONG = "long" - INTEGER = "integer" - SHORT = "short" - BYTE = "byte" - DOUBLE = "double" - FLOAT = "float" - BOOLEAN = "boolean" - BINARY = "binary" + WARNING = "warning" + ERROR = "error" -class ListCollectionsResponse(): +class ProjectDetails(): """ - Response object containing an array of collection details. - - :attr List[Collection] collections: (optional) An array containing information - about each collection in the project. + Detailed information about the specified project. + + :attr str project_id: (optional) The unique identifier of this project. + :attr str name: (optional) The human readable name of this project. + :attr str type: (optional) The project type of this project. + :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + (optional) Relevancy training status information for this project. + :attr int collection_count: (optional) The number of collections configured in + this project. + :attr DefaultQueryParams default_query_parameters: (optional) Default query + parameters for this project. """ - def __init__(self, *, collections: List['Collection'] = None) -> None: - """ - Initialize a ListCollectionsResponse object. - - :param List[Collection] collections: (optional) An array containing - information about each collection in the project. - """ - self.collections = collections + def __init__(self, + *, + project_id: str = None, + name: str = None, + type: str = None, + relevancy_training_status: + 'ProjectListDetailsRelevancyTrainingStatus' = None, + collection_count: int = None, + default_query_parameters: 'DefaultQueryParams' = None) -> None: + """ + Initialize a ProjectDetails object. + + :param str project_id: (optional) The unique identifier of this project. + :param str name: (optional) The human readable name of this project. + :param str type: (optional) The project type of this project. + :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + (optional) Relevancy training status information for this project. + :param int collection_count: (optional) The number of collections + configured in this project. + :param DefaultQueryParams default_query_parameters: (optional) Default + query parameters for this project. + """ + self.project_id = project_id + self.name = name + self.type = type + self.relevancy_training_status = relevancy_training_status + self.collection_count = collection_count + self.default_query_parameters = default_query_parameters @classmethod - def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': - """Initialize a ListCollectionsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProjectDetails': + """Initialize a ProjectDetails object from a json dictionary.""" args = {} - valid_keys = ['collections'] + valid_keys = [ + 'project_id', 'name', 'type', 'relevancy_training_status', + 'collection_count', 'default_query_parameters' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ListCollectionsResponse: ' + 'Unrecognized keys detected in dictionary for class ProjectDetails: ' + ', '.join(bad_keys)) - if 'collections' in _dict: - args['collections'] = [ - Collection._from_dict(x) for x in (_dict.get('collections')) - ] + if 'project_id' in _dict: + args['project_id'] = _dict.get('project_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'relevancy_training_status' in _dict: + args[ + 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus._from_dict( + _dict.get('relevancy_training_status')) + if 'collection_count' in _dict: + args['collection_count'] = _dict.get('collection_count') + if 'default_query_parameters' in _dict: + args['default_query_parameters'] = DefaultQueryParams._from_dict( + _dict.get('default_query_parameters')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ListCollectionsResponse object from a json dictionary.""" + """Initialize a ProjectDetails 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, 'collections') and self.collections is not None: - _dict['collections'] = [x._to_dict() for x in self.collections] + if hasattr(self, 'project_id') and self.project_id is not None: + _dict['project_id'] = self.project_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'relevancy_training_status' + ) and self.relevancy_training_status is not None: + _dict[ + 'relevancy_training_status'] = self.relevancy_training_status._to_dict( + ) + if hasattr(self, + 'collection_count') and self.collection_count is not None: + _dict['collection_count'] = self.collection_count + if hasattr(self, 'default_query_parameters' + ) and self.default_query_parameters is not None: + _dict[ + 'default_query_parameters'] = self.default_query_parameters._to_dict( + ) return _dict def _to_dict(self): @@ -1921,69 +4025,116 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ListCollectionsResponse object.""" + """Return a `str` version of this ProjectDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ListCollectionsResponse') -> bool: + def __eq__(self, other: 'ProjectDetails') -> 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: 'ListCollectionsResponse') -> bool: + def __ne__(self, other: 'ProjectDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(Enum): + """ + The project type of this project. + """ + DOCUMENT_RETRIEVAL = "document_retrieval" + ANSWER_RETRIEVAL = "answer_retrieval" + CONTENT_MINING = "content_mining" + OTHER = "other" + -class ListFieldsResponse(): +class ProjectListDetails(): """ - The list of fetched fields. - The fields are returned using a fully qualified name format, however, the format - differs slightly from that used by the query operations. - * Fields which contain nested objects are assigned a type of "nested". - * Fields which belong to a nested object are prefixed with `.properties` (for - example, `warnings.properties.severity` means that the `warnings` object has a - property called `severity`). - - :attr List[Field] fields: (optional) An array containing information about each - field in the collections. + Details about a specific project. + + :attr str project_id: (optional) The unique identifier of this project. + :attr str name: (optional) The human readable name of this project. + :attr str type: (optional) The project type of this project. + :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + (optional) Relevancy training status information for this project. + :attr int collection_count: (optional) The number of collections configured in + this project. """ - def __init__(self, *, fields: List['Field'] = None) -> None: + def __init__(self, + *, + project_id: str = None, + name: str = None, + type: str = None, + relevancy_training_status: + 'ProjectListDetailsRelevancyTrainingStatus' = None, + collection_count: int = None) -> None: """ - Initialize a ListFieldsResponse object. + Initialize a ProjectListDetails object. - :param List[Field] fields: (optional) An array containing information about - each field in the collections. + :param str project_id: (optional) The unique identifier of this project. + :param str name: (optional) The human readable name of this project. + :param str type: (optional) The project type of this project. + :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + (optional) Relevancy training status information for this project. + :param int collection_count: (optional) The number of collections + configured in this project. """ - self.fields = fields + self.project_id = project_id + self.name = name + self.type = type + self.relevancy_training_status = relevancy_training_status + self.collection_count = collection_count @classmethod - def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': - """Initialize a ListFieldsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProjectListDetails': + """Initialize a ProjectListDetails object from a json dictionary.""" args = {} - valid_keys = ['fields'] + valid_keys = [ + 'project_id', 'name', 'type', 'relevancy_training_status', + 'collection_count' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ListFieldsResponse: ' + 'Unrecognized keys detected in dictionary for class ProjectListDetails: ' + ', '.join(bad_keys)) - if 'fields' in _dict: - args['fields'] = [ - Field._from_dict(x) for x in (_dict.get('fields')) - ] + if 'project_id' in _dict: + args['project_id'] = _dict.get('project_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'relevancy_training_status' in _dict: + args[ + 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus._from_dict( + _dict.get('relevancy_training_status')) + if 'collection_count' in _dict: + args['collection_count'] = _dict.get('collection_count') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ListFieldsResponse object from a json dictionary.""" + """Initialize a ProjectListDetails 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, 'fields') and self.fields is not None: - _dict['fields'] = [x._to_dict() for x in self.fields] + if hasattr(self, 'project_id') and self.project_id is not None: + _dict['project_id'] = self.project_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'relevancy_training_status' + ) and self.relevancy_training_status is not None: + _dict[ + 'relevancy_training_status'] = self.relevancy_training_status._to_dict( + ) + if hasattr(self, + 'collection_count') and self.collection_count is not None: + _dict['collection_count'] = self.collection_count return _dict def _to_dict(self): @@ -1991,152 +4142,159 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ListFieldsResponse object.""" + """Return a `str` version of this ProjectListDetails object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ListFieldsResponse') -> bool: + def __eq__(self, other: 'ProjectListDetails') -> 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: 'ListFieldsResponse') -> bool: + def __ne__(self, other: 'ProjectListDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - -class Notice(): - """ - A notice produced for the collection. - - :attr str notice_id: (optional) Identifies the notice. Many notices might have - the same ID. This field exists so that user applications can programmatically - identify a notice and take automatic corrective action. Typical notice IDs - include: `index_failed`, `index_failed_too_many_requests`, - `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, - `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, - `missing_model`, `unsupported_model`, - `smart_document_understanding_failed_incompatible_field`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_warning`, - `smart_document_understanding_page_error`, - `smart_document_understanding_page_warning`. **Note:** This is not a complete - list, other values might be returned. - :attr datetime created: (optional) The creation date of the collection in the - format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str document_id: (optional) Unique identifier of the document. - :attr str collection_id: (optional) Unique identifier of the collection. - :attr str query_id: (optional) Unique identifier of the query used for relevance - training. - :attr str severity: (optional) Severity level of the notice. - :attr str step: (optional) Ingestion or training step in which the notice - occurred. - :attr str description: (optional) The description of the notice. + class TypeEnum(Enum): + """ + The project type of this project. + """ + DOCUMENT_RETRIEVAL = "document_retrieval" + ANSWER_RETRIEVAL = "answer_retrieval" + CONTENT_MINING = "content_mining" + OTHER = "other" + + +class ProjectListDetailsRelevancyTrainingStatus(): + """ + Relevancy training status information for this project. + + :attr str data_updated: (optional) When the training data was updated. + :attr int total_examples: (optional) The total number of examples. + :attr bool sufficient_label_diversity: (optional) When `true`, sufficent label + diversity is present to allow training for this project. + :attr bool processing: (optional) When `true`, the relevancy training is in + processing. + :attr bool minimum_examples_added: (optional) When `true`, the minimum number of + examples required to train has been met. + :attr str successfully_trained: (optional) The time that the most recent + successful training occured. + :attr bool available: (optional) When `true`, relevancy training is available + when querying collections in the project. + :attr int notices: (optional) The number of notices generated during the + relevancy training. + :attr bool minimum_queries_added: (optional) When `true`, the minimum number of + queries required to train has been met. """ def __init__(self, *, - notice_id: str = None, - created: datetime = None, - document_id: str = None, - collection_id: str = None, - query_id: str = None, - severity: str = None, - step: str = None, - description: str = None) -> None: - """ - Initialize a Notice object. - - :param str notice_id: (optional) Identifies the notice. Many notices might - have the same ID. This field exists so that user applications can - programmatically identify a notice and take automatic corrective action. - Typical notice IDs include: `index_failed`, - `index_failed_too_many_requests`, `index_failed_incompatible_field`, - `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, - `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, - `smart_document_understanding_failed_incompatible_field`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_warning`, - `smart_document_understanding_page_error`, - `smart_document_understanding_page_warning`. **Note:** This is not a - complete list, other values might be returned. - :param datetime created: (optional) The creation date of the collection in - the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param str document_id: (optional) Unique identifier of the document. - :param str collection_id: (optional) Unique identifier of the collection. - :param str query_id: (optional) Unique identifier of the query used for - relevance training. - :param str severity: (optional) Severity level of the notice. - :param str step: (optional) Ingestion or training step in which the notice - occurred. - :param str description: (optional) The description of the notice. - """ - self.notice_id = notice_id - self.created = created - self.document_id = document_id - self.collection_id = collection_id - self.query_id = query_id - self.severity = severity - self.step = step - self.description = description + data_updated: str = None, + total_examples: int = None, + sufficient_label_diversity: bool = None, + processing: bool = None, + minimum_examples_added: bool = None, + successfully_trained: str = None, + available: bool = None, + notices: int = None, + minimum_queries_added: bool = None) -> None: + """ + Initialize a ProjectListDetailsRelevancyTrainingStatus object. + + :param str data_updated: (optional) When the training data was updated. + :param int total_examples: (optional) The total number of examples. + :param bool sufficient_label_diversity: (optional) When `true`, sufficent + label diversity is present to allow training for this project. + :param bool processing: (optional) When `true`, the relevancy training is + in processing. + :param bool minimum_examples_added: (optional) When `true`, the minimum + number of examples required to train has been met. + :param str successfully_trained: (optional) The time that the most recent + successful training occured. + :param bool available: (optional) When `true`, relevancy training is + available when querying collections in the project. + :param int notices: (optional) The number of notices generated during the + relevancy training. + :param bool minimum_queries_added: (optional) When `true`, the minimum + number of queries required to train has been met. + """ + self.data_updated = data_updated + self.total_examples = total_examples + self.sufficient_label_diversity = sufficient_label_diversity + self.processing = processing + self.minimum_examples_added = minimum_examples_added + self.successfully_trained = successfully_trained + self.available = available + self.notices = notices + self.minimum_queries_added = minimum_queries_added @classmethod - def from_dict(cls, _dict: Dict) -> 'Notice': - """Initialize a Notice object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'ProjectListDetailsRelevancyTrainingStatus': + """Initialize a ProjectListDetailsRelevancyTrainingStatus object from a json dictionary.""" args = {} valid_keys = [ - 'notice_id', 'created', 'document_id', 'collection_id', 'query_id', - 'severity', 'step', 'description' + 'data_updated', 'total_examples', 'sufficient_label_diversity', + 'processing', 'minimum_examples_added', 'successfully_trained', + 'available', 'notices', 'minimum_queries_added' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class Notice: ' + - ', '.join(bad_keys)) - if 'notice_id' in _dict: - args['notice_id'] = _dict.get('notice_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'severity' in _dict: - args['severity'] = _dict.get('severity') - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'description' in _dict: - args['description'] = _dict.get('description') + 'Unrecognized keys detected in dictionary for class ProjectListDetailsRelevancyTrainingStatus: ' + + ', '.join(bad_keys)) + if 'data_updated' in _dict: + args['data_updated'] = _dict.get('data_updated') + if 'total_examples' in _dict: + args['total_examples'] = _dict.get('total_examples') + if 'sufficient_label_diversity' in _dict: + args['sufficient_label_diversity'] = _dict.get( + 'sufficient_label_diversity') + if 'processing' in _dict: + args['processing'] = _dict.get('processing') + if 'minimum_examples_added' in _dict: + args['minimum_examples_added'] = _dict.get('minimum_examples_added') + if 'successfully_trained' in _dict: + args['successfully_trained'] = _dict.get('successfully_trained') + if 'available' in _dict: + args['available'] = _dict.get('available') + if 'notices' in _dict: + args['notices'] = _dict.get('notices') + if 'minimum_queries_added' in _dict: + args['minimum_queries_added'] = _dict.get('minimum_queries_added') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Notice object from a json dictionary.""" + """Initialize a ProjectListDetailsRelevancyTrainingStatus 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, 'notice_id') and self.notice_id is not None: - _dict['notice_id'] = self.notice_id - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'query_id') and self.query_id is not None: - _dict['query_id'] = self.query_id - if hasattr(self, 'severity') and self.severity is not None: - _dict['severity'] = self.severity - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description + if hasattr(self, 'data_updated') and self.data_updated is not None: + _dict['data_updated'] = self.data_updated + if hasattr(self, 'total_examples') and self.total_examples is not None: + _dict['total_examples'] = self.total_examples + if hasattr(self, 'sufficient_label_diversity' + ) and self.sufficient_label_diversity is not None: + _dict[ + 'sufficient_label_diversity'] = self.sufficient_label_diversity + if hasattr(self, 'processing') and self.processing is not None: + _dict['processing'] = self.processing + if hasattr(self, 'minimum_examples_added' + ) and self.minimum_examples_added is not None: + _dict['minimum_examples_added'] = self.minimum_examples_added + if hasattr(self, 'successfully_trained' + ) and self.successfully_trained is not None: + _dict['successfully_trained'] = self.successfully_trained + if hasattr(self, 'available') and self.available is not None: + _dict['available'] = self.available + if hasattr(self, 'notices') and self.notices is not None: + _dict['notices'] = self.notices + if hasattr(self, 'minimum_queries_added' + ) and self.minimum_queries_added is not None: + _dict['minimum_queries_added'] = self.minimum_queries_added return _dict def _to_dict(self): @@ -2144,26 +4302,21 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Notice object.""" + """Return a `str` version of this ProjectListDetailsRelevancyTrainingStatus object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'Notice') -> bool: + def __eq__(self, + other: 'ProjectListDetailsRelevancyTrainingStatus') -> 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: 'Notice') -> bool: + def __ne__(self, + other: 'ProjectListDetailsRelevancyTrainingStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class SeverityEnum(Enum): - """ - Severity level of the notice. - """ - WARNING = "warning" - ERROR = "error" - class QueryAggregation(): """ @@ -2249,6 +4402,7 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping['average'] = 'QueryCalculationAggregation' mapping['unique_count'] = 'QueryCalculationAggregation' mapping['top_hits'] = 'QueryTopHitsAggregation' + mapping['group_by'] = 'QueryGroupByAggregation' disc_value = _dict.get('type') if disc_value is None: raise ValueError( @@ -2264,6 +4418,140 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) +class QueryGroupByAggregationResult(): + """ + Top value result for the term aggregation. + + :attr str key: Value of the field with a non-zero frequency in the document set. + :attr int matching_results: Number of documents containing the 'key'. + :attr float relevancy: (optional) The relevancy for this group. + :attr int total_matching_documents: (optional) The number of documents which + have the group as the value of specified field in the whole set of documents in + this collection. Returned only when the `relevancy` parameter is set to `true`. + :attr int estimated_matching_documents: (optional) The estimated number of + documents which would match the query and also meet the condition. Returned only + when the `relevancy` parameter is set to `true`. + :attr List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + + def __init__(self, + key: str, + matching_results: int, + *, + relevancy: float = None, + total_matching_documents: int = None, + estimated_matching_documents: int = None, + aggregations: List['QueryAggregation'] = None) -> None: + """ + Initialize a QueryGroupByAggregationResult object. + + :param str key: Value of the field with a non-zero frequency in the + document set. + :param int matching_results: Number of documents containing the 'key'. + :param float relevancy: (optional) The relevancy for this group. + :param int total_matching_documents: (optional) The number of documents + which have the group as the value of specified field in the whole set of + documents in this collection. Returned only when the `relevancy` parameter + is set to `true`. + :param int estimated_matching_documents: (optional) The estimated number of + documents which would match the query and also meet the condition. Returned + only when the `relevancy` parameter is set to `true`. + :param List[QueryAggregation] aggregations: (optional) An array of sub + aggregations. + """ + self.key = key + self.matching_results = matching_results + self.relevancy = relevancy + self.total_matching_documents = total_matching_documents + self.estimated_matching_documents = estimated_matching_documents + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregationResult': + """Initialize a QueryGroupByAggregationResult object from a json dictionary.""" + args = {} + valid_keys = [ + 'key', 'matching_results', 'relevancy', 'total_matching_documents', + 'estimated_matching_documents', 'aggregations' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryGroupByAggregationResult: ' + + ', '.join(bad_keys)) + if 'key' in _dict: + args['key'] = _dict.get('key') + else: + raise ValueError( + 'Required property \'key\' not present in QueryGroupByAggregationResult JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryGroupByAggregationResult JSON' + ) + if 'relevancy' in _dict: + args['relevancy'] = _dict.get('relevancy') + if 'total_matching_documents' in _dict: + args['total_matching_documents'] = _dict.get( + 'total_matching_documents') + if 'estimated_matching_documents' in _dict: + args['estimated_matching_documents'] = _dict.get( + 'estimated_matching_documents') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation._from_dict(x) + for x in (_dict.get('aggregations')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryGroupByAggregationResult 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, 'key') and self.key is not None: + _dict['key'] = self.key + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'relevancy') and self.relevancy is not None: + _dict['relevancy'] = self.relevancy + if hasattr(self, 'total_matching_documents' + ) and self.total_matching_documents is not None: + _dict['total_matching_documents'] = self.total_matching_documents + if hasattr(self, 'estimated_matching_documents' + ) and self.estimated_matching_documents is not None: + _dict[ + 'estimated_matching_documents'] = self.estimated_matching_documents + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + 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 QueryGroupByAggregationResult object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryGroupByAggregationResult') -> 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: 'QueryGroupByAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryHistogramAggregationResult(): """ Histogram numeric interval result. @@ -2371,8 +4659,8 @@ class QueryLargePassages(): :attr List[str] fields: (optional) A list of fields that passages are drawn from. If this parameter not specified, then all top-level fields are included. :attr int count: (optional) The maximum number of passages to return. The search - returns fewer passages if the requested total is not found. The default is `10`. - The maximum is `100`. + returns fewer passages if the requested total is not found. The maximum is + `100`. :attr int characters: (optional) The approximate number of characters that any one passage will have. """ @@ -2399,7 +4687,7 @@ def __init__(self, included. :param int count: (optional) The maximum number of passages to return. The search returns fewer passages if the requested total is not found. The - default is `10`. The maximum is `100`. + maximum is `100`. :param int characters: (optional) The approximate number of characters that any one passage will have. """ @@ -2485,7 +4773,7 @@ class QueryLargeSuggestedRefinements(): :attr bool enabled: (optional) Whether to perform suggested refinements. :attr int count: (optional) Maximum number of suggested refinements texts to be - returned. The default is `10`. The maximum is `100`. + returned. The maximum is `100`. """ def __init__(self, *, enabled: bool = None, count: int = None) -> None: @@ -2494,7 +4782,7 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: :param bool enabled: (optional) Whether to perform suggested refinements. :param int count: (optional) Maximum number of suggested refinements texts - to be returned. The default is `10`. The maximum is `100`. + to be returned. The maximum is `100`. """ self.enabled = enabled self.count = count @@ -3340,6 +5628,13 @@ class QueryTermAggregationResult(): :attr str key: Value of the field with a non-zero frequency in the document set. :attr int matching_results: Number of documents containing the 'key'. + :attr float relevancy: (optional) The relevancy for this term. + :attr int total_matching_documents: (optional) The number of documents which + have the term as the value of specified field in the whole set of documents in + this collection. Returned only when the `relevancy` parameter is set to `true`. + :attr int estimated_matching_documents: (optional) The estimated number of + documents which would match the query and also meet the condition. Returned only + when the `relevancy` parameter is set to `true`. :attr List[QueryAggregation] aggregations: (optional) An array of sub aggregations. """ @@ -3348,6 +5643,9 @@ def __init__(self, key: str, matching_results: int, *, + relevancy: float = None, + total_matching_documents: int = None, + estimated_matching_documents: int = None, aggregations: List['QueryAggregation'] = None) -> None: """ Initialize a QueryTermAggregationResult object. @@ -3355,18 +5653,32 @@ def __init__(self, :param str key: Value of the field with a non-zero frequency in the document set. :param int matching_results: Number of documents containing the 'key'. + :param float relevancy: (optional) The relevancy for this term. + :param int total_matching_documents: (optional) The number of documents + which have the term as the value of specified field in the whole set of + documents in this collection. Returned only when the `relevancy` parameter + is set to `true`. + :param int estimated_matching_documents: (optional) The estimated number of + documents which would match the query and also meet the condition. Returned + only when the `relevancy` parameter is set to `true`. :param List[QueryAggregation] aggregations: (optional) An array of sub aggregations. """ self.key = key self.matching_results = matching_results + self.relevancy = relevancy + self.total_matching_documents = total_matching_documents + self.estimated_matching_documents = estimated_matching_documents self.aggregations = aggregations @classmethod def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': """Initialize a QueryTermAggregationResult object from a json dictionary.""" args = {} - valid_keys = ['key', 'matching_results', 'aggregations'] + valid_keys = [ + 'key', 'matching_results', 'relevancy', 'total_matching_documents', + 'estimated_matching_documents', 'aggregations' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -3384,6 +5696,14 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': raise ValueError( 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' ) + if 'relevancy' in _dict: + args['relevancy'] = _dict.get('relevancy') + if 'total_matching_documents' in _dict: + args['total_matching_documents'] = _dict.get( + 'total_matching_documents') + if 'estimated_matching_documents' in _dict: + args['estimated_matching_documents'] = _dict.get( + 'estimated_matching_documents') if 'aggregations' in _dict: args['aggregations'] = [ QueryAggregation._from_dict(x) @@ -3404,6 +5724,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results + if hasattr(self, 'relevancy') and self.relevancy is not None: + _dict['relevancy'] = self.relevancy + if hasattr(self, 'total_matching_documents' + ) and self.total_matching_documents is not None: + _dict['total_matching_documents'] = self.total_matching_documents + if hasattr(self, 'estimated_matching_documents' + ) and self.estimated_matching_documents is not None: + _dict[ + 'estimated_matching_documents'] = self.estimated_matching_documents if hasattr(self, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x._to_dict() for x in self.aggregations] return _dict @@ -5816,6 +8145,86 @@ def __ne__(self, other: 'QueryFilterAggregation') -> bool: return not self == other +class QueryGroupByAggregation(QueryAggregation): + """ + Returns the top values for the field specified. + + :attr List[QueryGroupByAggregationResult] results: (optional) Array of top + values for the field. + """ + + def __init__(self, + type: str, + *, + results: List['QueryGroupByAggregationResult'] = None) -> None: + """ + Initialize a QueryGroupByAggregation object. + + :param str type: The type of aggregation command used. Options include: + term, histogram, timeslice, nested, filter, min, max, sum, average, + unique_count, and top_hits. + :param List[QueryGroupByAggregationResult] results: (optional) Array of top + values for the field. + """ + self.type = type + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregation': + """Initialize a QueryGroupByAggregation object from a json dictionary.""" + args = {} + valid_keys = ['type', 'results'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryGroupByAggregation: ' + + ', '.join(bad_keys)) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in QueryGroupByAggregation JSON' + ) + if 'results' in _dict: + args['results'] = [ + QueryGroupByAggregationResult._from_dict(x) + for x in (_dict.get('results')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryGroupByAggregation 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 + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x._to_dict() for x in self.results] + 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 QueryGroupByAggregation object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryGroupByAggregation') -> 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: 'QueryGroupByAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryHistogramAggregation(QueryAggregation): """ Numeric interval segments to categorize documents by using field values from a single diff --git a/test/integration/test_discovery_v2.py b/test/integration/test_discovery_v2.py new file mode 100644 index 000000000..03779a640 --- /dev/null +++ b/test/integration/test_discovery_v2.py @@ -0,0 +1,110 @@ +# coding: utf-8 +from unittest import TestCase +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +from ibm_watson.discovery_v2 import CreateEnrichment, EnrichmentOptions +import os +import ibm_watson +import pytest + + +@pytest.mark.skipif(os.getenv('TEST_DISCO_V2') is None, + reason='only test in cpd and prem') +class Discoveryv2(TestCase): + discovery = None + project_id = 'f0b9920b-caa8-4b89-abf7-e250989eee5a' # This project is created for integration testing + collection_id = None + collection_name = 'python_test_collection' + + @classmethod + def setup_class(cls): + authenticator = IAMAuthenticator('apikey') + cls.discovery = ibm_watson.DiscoveryV2( + version='2020-08-12', + authenticator=authenticator + ) + cls.discovery.set_service_url('url') + cls.discovery.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) + + collections = cls.discovery.list_collections( + cls.project_id).get_result()['collections'] + for collection in collections: + if collection['name'] == cls.collection_name: + cls.collection_id = collection['collection_id'] + + if cls.collection_id is None: + print("Creating a new temporary collection") + cls.collection_id = cls.discovery.create_collection( + cls.project_id, + cls.collection_name, + description="Integration test for python sdk").get_result( + )['collection_id'] + + @classmethod + def teardown_class(cls): + collections = cls.discovery.list_collections( + cls.project_id).get_result()['collections'] + for collection in collections: + if collection['name'] == cls.collection_name: + print('Deleting the temporary collection') + cls.discovery.delete_collection(cls.project_id, + cls.collection_id) + break + + def test_projects(self): + projs = self.discovery.list_projects().get_result() + assert projs is not None + proj = self.discovery.get_project( + self.project_id).get_result() + assert proj is not None + + def test_collections(self): + cols = self.discovery.list_collections(self.project_id).get_result() + assert cols is not None + col = self.discovery.get_collection( + self.project_id, + self.collection_id + ).get_result() + assert col is not None + + def test_enrichments(self): + enrs = self.discovery.list_enrichments(self.project_id).get_result() + print(enrs) + assert enrs is not None + + enrichmentOptions = EnrichmentOptions( + languages=["en"], + entity_type="keyword" + ) + enrichment = CreateEnrichment( + name="python test enrichment", + description="test enrichment", + type="dictionary", + options=enrichmentOptions + ) + with open(os.path.join(os.path.dirname(__file__), '../../resources/TestEnrichments.csv'), 'r') as fileinfo: + enr = self.discovery.create_enrichment( + project_id=self.project_id, + enrichment=enrichment._to_dict(), + file=fileinfo + ).get_result() + assert enr is not None + enrichment_id = enr["enrichment_id"] + enrichment = self.discovery.get_enrichment( + self.project_id, + enrichment_id + ).get_result() + assert enrichment is not None + enr = self.discovery.update_enrichment( + project_id=self.project_id, + enrichment_id=enrichment_id, + name="python test enrichment", + description="updated description" + ).get_result() + assert enr is not None + self.discovery.delete_enrichment( + self.project_id, + enrichment_id + ) From 9ef3c6e2df323a2bb7403bef417ddbd34ca6b462 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:28:21 -0400 Subject: [PATCH 265/455] feat: regenrate all services using current api def --- ibm_watson/assistant_v1.py | 141 ++------------- ibm_watson/compare_comply_v1.py | 2 +- ibm_watson/discovery_v1.py | 2 +- ibm_watson/natural_language_classifier_v1.py | 2 +- .../natural_language_understanding_v1.py | 71 ++++---- ibm_watson/personality_insights_v3.py | 2 +- ibm_watson/speech_to_text_v1.py | 161 +++++++++++++----- ibm_watson/text_to_speech_v1.py | 29 +++- ibm_watson/tone_analyzer_v3.py | 2 +- ibm_watson/visual_recognition_v3.py | 2 +- ibm_watson/visual_recognition_v4.py | 2 +- 11 files changed, 200 insertions(+), 216 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index a8f34d5f9..e6bac2d3e 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -41,7 +41,7 @@ class AssistantV1(BaseService): """The Assistant V1 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/assistant/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.assistant.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'assistant' def __init__( @@ -100,7 +100,6 @@ def message(self, 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/assistant?topic=assistant-api-overview). - There is no rate limit for this operation. :param str workspace_id: Unique identifier of the workspace. :param MessageInput input: (optional) An input object that includes the @@ -189,8 +188,6 @@ def list_workspaces(self, List workspaces. List the workspaces associated with a Watson Assistant service instance. - This operation is limited to 500 requests per 30 minutes. For more information, - see **Rate limiting**. :param int page_limit: (optional) The number of records to return in each page of results. @@ -251,8 +248,6 @@ def create_workspace(self, Create a workspace based on component objects. You must provide workspace components defining the content of the new workspace. - This operation is limited to 30 requests per 30 minutes. For more information, see - **Rate limiting**. :param str name: (optional) The name of the workspace. This string cannot contain carriage return, newline, or tab characters. @@ -340,9 +335,6 @@ def get_workspace(self, Get information about a workspace. Get information about a workspace, optionally including all workspace content. - With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. - With **export**=`true`, the limit is 20 requests per 30 minutes. For more - information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param bool export: (optional) Whether to include all element content in @@ -409,8 +401,6 @@ def update_workspace(self, Update an existing workspace with new or modified data. You must provide component objects defining the content of the updated workspace. - This operation is limited to 30 request per 30 minutes. For more information, see - **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str name: (optional) The name of the workspace. This string cannot @@ -509,8 +499,6 @@ def delete_workspace(self, workspace_id: str, Delete workspace. Delete a workspace from the service instance. - This operation is limited to 30 requests per 30 minutes. For more information, see - **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param dict headers: A `dict` containing the request headers @@ -557,9 +545,6 @@ def list_intents(self, List intents. List the intents for a workspace. - With **export**=`false`, this operation is limited to 2000 requests per 30 - minutes. With **export**=`true`, the limit is 400 requests per 30 minutes. For - more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param bool export: (optional) Whether to include all element content in @@ -624,8 +609,6 @@ def create_intent(self, Create a new intent. If you want to create multiple intents with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 2000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The name of the intent. This string must conform to the @@ -689,9 +672,6 @@ def get_intent(self, Get intent. Get information about an intent, optionally including all intent content. - With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. - With **export**=`true`, the limit is 400 requests per 30 minutes. For more - information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -752,8 +732,6 @@ def update_intent(self, objects defining the content of the updated intent. If you want to update multiple intents with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 2000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -826,8 +804,6 @@ def delete_intent(self, workspace_id: str, intent: str, Delete intent. Delete an intent from a workspace. - This operation is limited to 2000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -879,8 +855,6 @@ def list_examples(self, List the user input examples for an intent, optionally including contextual entity mentions. - This operation is limited to 2500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -943,8 +917,6 @@ def create_example(self, Add a new user input example to an intent. If you want to add multiple examples with a single API call, consider using the **[Update intent](#update-intent)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -1004,8 +976,6 @@ def get_example(self, Get user input example. Get information about a user input example. - This operation is limited to 6000 requests per 5 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -1059,8 +1029,6 @@ def update_example(self, Update the text of a user input example. If you want to update multiple examples with a single API call, consider using the **[Update intent](#update-intent)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -1116,8 +1084,6 @@ def delete_example(self, workspace_id: str, intent: str, text: str, Delete user input example. Delete a user input example from an intent. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str intent: The intent name. @@ -1171,8 +1137,6 @@ def list_counterexamples(self, List the counterexamples for a workspace. Counterexamples are examples that have been marked as irrelevant input. - This operation is limited to 2500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param int page_limit: (optional) The number of records to return in each @@ -1231,8 +1195,6 @@ def create_counterexample(self, been marked as irrelevant input. If you want to add multiple counterexamples with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str text: The text of a user input marked as irrelevant input. This @@ -1285,8 +1247,6 @@ def get_counterexample(self, Get information about a counterexample. Counterexamples are examples that have been marked as irrelevant input. - This operation is limited to 6000 requests per 5 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str text: The text of a user input counterexample (for example, @@ -1335,10 +1295,6 @@ def update_counterexample(self, Update the text of a counterexample. Counterexamples are examples that have been marked as irrelevant input. - If you want to update multiple counterexamples with a single API call, consider - using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str text: The text of a user input counterexample (for example, @@ -1389,8 +1345,6 @@ def delete_counterexample(self, workspace_id: str, text: str, Delete a counterexample from a workspace. Counterexamples are examples that have been marked as irrelevant input. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str text: The text of a user input counterexample (for example, @@ -1442,9 +1396,6 @@ def list_entities(self, List entities. List the entities for a workspace. - With **export**=`false`, this operation is limited to 1000 requests per 30 - minutes. With **export**=`true`, the limit is 200 requests per 30 minutes. For - more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param bool export: (optional) Whether to include all element content in @@ -1511,8 +1462,6 @@ def create_entity(self, Create a new entity, or enable a system entity. If you want to create multiple entities with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. This string must conform to the @@ -1583,9 +1532,6 @@ def get_entity(self, Get entity. Get information about an entity, optionally including all entity content. - With **export**=`false`, this operation is limited to 6000 requests per 5 minutes. - With **export**=`true`, the limit is 200 requests per 30 minutes. For more - information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1648,8 +1594,6 @@ def update_entity(self, objects defining the content of the updated entity. If you want to update multiple entities with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1727,8 +1671,6 @@ def delete_entity(self, workspace_id: str, entity: str, Delete entity. Delete an entity from a workspace, or disable a system entity. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1778,8 +1720,6 @@ def list_mentions(self, List mentions for a contextual entity. An entity mention is an occurrence of a contextual entity in the context of an intent user input example. - This operation is limited to 200 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1841,8 +1781,6 @@ def list_values(self, List entity values. List the values for an entity. - This operation is limited to 2500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1913,8 +1851,6 @@ def create_value(self, Create a new value for an entity. If you want to create multiple entity values with a single API call, consider using the **[Update entity](#update-entity)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -1990,8 +1926,6 @@ def get_value(self, Get entity value. Get information about an entity value. - This operation is limited to 6000 requests per 5 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2058,8 +1992,6 @@ def update_value(self, component objects defining the content of the updated entity value. If you want to update multiple entity values with a single API call, consider using the **[Update entity](#update-entity)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2145,8 +2077,6 @@ def delete_value(self, workspace_id: str, entity: str, value: str, Delete entity value. Delete a value from an entity. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2201,8 +2131,6 @@ def list_synonyms(self, List entity value synonyms. List the synonyms for an entity value. - This operation is limited to 2500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2269,8 +2197,6 @@ def create_synonym(self, If you want to create multiple synonyms with a single API call, consider using the **[Update entity](#update-entity)** or **[Update entity value](#update-entity-value)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2330,8 +2256,6 @@ def get_synonym(self, Get entity value synonym. Get information about a synonym of an entity value. - This operation is limited to 6000 requests per 5 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2389,8 +2313,6 @@ def update_synonym(self, If you want to update multiple synonyms with a single API call, consider using the **[Update entity](#update-entity)** or **[Update entity value](#update-entity-value)** method instead. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2445,8 +2367,6 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, Delete entity value synonym. Delete a synonym from an entity value. - This operation is limited to 1000 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str entity: The name of the entity. @@ -2502,8 +2422,6 @@ def list_dialog_nodes(self, List dialog nodes. List the dialog nodes for a workspace. - This operation is limited to 2500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param int page_limit: (optional) The number of records to return in each @@ -2579,8 +2497,6 @@ def create_dialog_node(self, Create a new dialog node. If you want to create multiple dialog nodes with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID. This string must conform to the @@ -2696,8 +2612,6 @@ def get_dialog_node(self, Get dialog node. Get information about a dialog node. - This operation is limited to 6000 requests per 5 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID (for example, `get_order`). @@ -2764,8 +2678,6 @@ def update_dialog_node(self, Update an existing dialog node with new or modified data. If you want to update multiple dialog nodes with a single API call, consider using the **[Update workspace](#update-workspace)** method instead. - This operation is limited to 500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID (for example, `get_order`). @@ -2879,8 +2791,6 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, Delete dialog node. Delete a dialog node from a workspace. - This operation is limited to 500 requests per 30 minutes. For more information, - see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str dialog_node: The dialog node ID (for example, `get_order`). @@ -2930,9 +2840,6 @@ def list_logs(self, List log events in a workspace. List the events from the log of a specific workspace. - If **cursor** is not specified, this operation is limited to 40 requests per 30 - minutes. If **cursor** is specified, the limit is 120 requests per minute. For - more information, see **Rate limiting**. :param str workspace_id: Unique identifier of the workspace. :param str sort: (optional) How to sort the returned log events. You can @@ -2990,9 +2897,6 @@ def list_all_logs(self, List log events in all workspaces. List the events from the logs of all workspaces in the service instance. - If **cursor** is not specified, this operation is limited to 40 requests per 30 - minutes. If **cursor** is specified, the limit is 120 requests per minute. For - more information, see **Rate limiting**. :param str filter: A cacheable parameter that limits the results to those matching the specified filter. You must specify a filter query that @@ -3055,8 +2959,6 @@ def delete_user_data(self, customer_id: str, with a request that passes data. For more information about personal data and customer IDs, see [Information 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**. :param str customer_id: The customer ID for which all data is to be deleted. @@ -4748,8 +4650,7 @@ class DialogNodeOutputGeneric(): :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **search_skill** response type is available only for Plus and - Premium users, and is used only by the v2 runtime API. + **Note:** The **search_skill** response type is used only by the v2 runtime API. :attr List[DialogNodeOutputTextValuesElement] values: (optional) A list of one or more objects defining text responses. Required when **response_type**=`text`. :attr str selection_policy: (optional) How a response is selected from the list, @@ -4816,8 +4717,8 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **search_skill** response type is available only for Plus and - Premium users, and is used only by the v2 runtime API. + **Note:** The **search_skill** response type is used only by the v2 runtime + API. :param List[DialogNodeOutputTextValuesElement] values: (optional) A list of one or more objects defining text responses. Required when **response_type**=`text`. @@ -5003,8 +4904,7 @@ class ResponseTypeEnum(Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **search_skill** response type is available only for Plus and - Premium users, and is used only by the v2 runtime API. + **Note:** The **search_skill** response type is used only by the v2 runtime API. """ TEXT = "text" PAUSE = "pause" @@ -5680,10 +5580,8 @@ class DialogSuggestionResponseGeneric(): :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Plus and Premium users. The - **search_skill** response type is available only for Plus and Premium users, and - is used only by the v2 runtime API. + **Note:** The **search_skill** response type is is used only by the v2 runtime + API. :attr str text: (optional) The text of the response. :attr int time: (optional) How long to pause, in milliseconds. :attr bool typing: (optional) Whether to send a "user is typing" event during @@ -5724,10 +5622,8 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Plus and Premium users. The - **search_skill** response type is available only for Plus and Premium - users, and is used only by the v2 runtime API. + **Note:** The **search_skill** response type is is used only by the v2 + runtime API. :param str text: (optional) The text of the response. :param int time: (optional) How long to pause, in milliseconds. :param bool typing: (optional) Whether to send a "user is typing" event @@ -5865,10 +5761,8 @@ class ResponseTypeEnum(Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation feature, - which is only available for Plus and Premium users. The **search_skill** response - type is available only for Plus and Premium users, and is used only by the v2 - runtime API. + **Note:** The **search_skill** response type is is used only by the v2 runtime + API. """ TEXT = "text" PAUSE = "pause" @@ -8765,8 +8659,6 @@ class RuntimeResponseGeneric(): :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Plus and Premium users. :attr str text: (optional) The text of the response. :attr int time: (optional) How long to pause, in milliseconds. :attr bool typing: (optional) Whether to send a "user is typing" event during @@ -8787,8 +8679,6 @@ class RuntimeResponseGeneric(): the dialog node's **title** property. :attr List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation feature, - which is only available for Plus and Premium users. """ def __init__(self, @@ -8812,8 +8702,6 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation - feature, which is only available for Plus and Premium users. :param str text: (optional) The text of the response. :param int time: (optional) How long to pause, in milliseconds. :param bool typing: (optional) Whether to send a "user is typing" event @@ -8836,8 +8724,6 @@ def __init__(self, :param List[DialogSuggestion] suggestions: (optional) An array of objects describing the possible matching dialog nodes from which the user can choose. - **Note:** The **suggestions** property is part of the disambiguation - feature, which is only available for Plus and Premium users. """ self.response_type = response_type self.text = text @@ -8964,8 +8850,6 @@ class ResponseTypeEnum(Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - **Note:** The **suggestion** response type is part of the disambiguation feature, - which is only available for Plus and Premium users. """ TEXT = "text" PAUSE = "pause" @@ -9939,7 +9823,6 @@ class WorkspaceSystemSettings(): related to the Watson Assistant user interface. :attr WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace 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 bool spelling_suggestions: (optional) Whether spelling correction is enabled for the workspace. @@ -9972,7 +9855,6 @@ def __init__( settings related to the Watson Assistant user interface. :param WorkspaceSystemSettingsDisambiguation disambiguation: (optional) 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 bool spelling_suggestions: (optional) Whether spelling correction is enabled for the workspace. @@ -10083,7 +9965,6 @@ def __ne__(self, other: 'WorkspaceSystemSettings') -> bool: class WorkspaceSystemSettingsDisambiguation(): """ Workspace settings related to the disambiguation feature. - **Note:** This feature is available only to Plus and Premium users. :attr str prompt: (optional) The text of the introductory prompt that accompanies disambiguation options presented to the user. diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 85ef86f45..82f5bf54d 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -40,7 +40,7 @@ class CompareComplyV1(BaseService): """The Compare Comply V1 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/compare-comply/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.compare-comply.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'compare_comply' def __init__( diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 2fa04f3b4..7894a3c55 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -45,7 +45,7 @@ class DiscoveryV1(BaseService): """The Discovery V1 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/discovery/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.discovery.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'discovery' def __init__( diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 5441a6f68..77c43d7f7 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -41,7 +41,7 @@ class NaturalLanguageClassifierV1(BaseService): """The Natural Language Classifier V1 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/natural-language-classifier/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.natural-language-classifier.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'natural_language_classifier' def __init__( diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 22ee86f76..d778867c0 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -44,7 +44,7 @@ class NaturalLanguageUnderstandingV1(BaseService): """The Natural Language Understanding V1 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/natural-language-understanding/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.natural-language-understanding.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'natural-language-understanding' def __init__( @@ -110,7 +110,7 @@ def analyze(self, - Relations - Semantic roles - Sentiment - - Syntax (Experimental). + - Syntax. If a language for the input text is not specified with the `language` parameter, the service [automatically detects the language](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-detectable-languages). @@ -123,9 +123,8 @@ def analyze(self, :param str url: (optional) The webpage to analyze. One of the `text`, `html`, or `url` parameters is required. :param bool clean: (optional) Set this to `false` to disable webpage - cleaning. To learn more about webpage cleaning, see the [Analyzing - webpages](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages) - documentation. + cleaning. For more information about webpage cleaning, see [Analyzing + webpages](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages). :param str xpath: (optional) An [XPath query](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-analyzing-webpages#xpath) to perform on `html` or `url` input. Results of the query will be appended @@ -137,10 +136,9 @@ def analyze(self, analyzed text. :param str language: (optional) ISO 639-1 code that specifies the language of your text. This overrides automatic language detection. Language support - differs depending on the features you include in your analysis. See - [Language - support](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-language-support) - for more information. + differs depending on the features you include in your analysis. For more + information, see [Language + support](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-language-support). :param int limit_text_characters: (optional) Sets the maximum number of characters that are processed by the service. :param dict headers: A `dict` containing the request headers @@ -872,9 +870,8 @@ class CategoriesResult(): A categorization of the analyzed text. :attr str label: (optional) The path to the category through the 5-level - taxonomy hierarchy. For the complete list of categories, see the [Categories - hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) - documentation. + taxonomy hierarchy. For more information about the categories, see [Categories + hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). :attr float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. :attr CategoriesResultExplanation explanation: (optional) Information that helps @@ -890,10 +887,9 @@ def __init__(self, Initialize a CategoriesResult object. :param str label: (optional) The path to the category through the 5-level - taxonomy hierarchy. For the complete list of categories, see the + taxonomy hierarchy. For more information about the categories, see [Categories - hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy) - documentation. + hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). :param float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. :param CategoriesResultExplanation explanation: (optional) Information that @@ -1713,8 +1709,8 @@ def __ne__(self, other: 'EmotionScores') -> bool: class EntitiesOptions(): """ - Identifies people, cities, organizations, and other entities in the content. See - [Entity types and + Identifies people, cities, organizations, and other entities in the content. For more + information, see [Entity types and subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through @@ -2133,7 +2129,8 @@ class Features(): entities with `entities.emotion` and for keywords with `keywords.emotion`. Supported languages: English. :attr EntitiesOptions entities: (optional) Identifies people, cities, - organizations, and other entities in the content. See [Entity types and + organizations, and other entities in the content. For more information, see + [Entity types and subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported @@ -2147,8 +2144,8 @@ class Features(): and publication date. Supports URL and HTML input types only. :attr RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` - relation might connect the entities "Nobel Prize" and "Albert Einstein". See - [Relation + relation might connect the entities "Nobel Prize" and "Albert Einstein". For + more information, see [Relation types](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-relations). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also @@ -2197,7 +2194,8 @@ def __init__(self, `keywords.emotion`. Supported languages: English. :param EntitiesOptions entities: (optional) Identifies people, cities, - organizations, and other entities in the content. See [Entity types and + organizations, and other entities in the content. For more information, see + [Entity types and subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are @@ -2212,7 +2210,7 @@ def __init__(self, :param RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert - Einstein". See [Relation + Einstein". For more information, see [Relation types](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-relations). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also @@ -2696,7 +2694,7 @@ class Model(): :attr str status: (optional) When the status is `available`, the model is ready to use. :attr str model_id: (optional) Unique model ID. - :attr str language: (optional) ISO 639-1 code indicating the language of the + :attr str language: (optional) ISO 639-1 code that indicates the language of the model. :attr str description: (optional) Model description. :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace @@ -2728,8 +2726,8 @@ def __init__(self, :param str status: (optional) When the status is `available`, the model is ready to use. :param str model_id: (optional) Unique model ID. - :param str language: (optional) ISO 639-1 code indicating the language of - the model. + :param str language: (optional) ISO 639-1 code that indicates the language + of the model. :param str description: (optional) Model description. :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. @@ -2833,6 +2831,17 @@ def __ne__(self, other: 'Model') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(Enum): + """ + When the status is `available`, the model is ready to use. + """ + STARTING = "starting" + TRAINING = "training" + DEPLOYING = "deploying" + AVAILABLE = "available" + ERROR = "error" + DELETED = "deleted" + class RelationArgument(): """ @@ -2988,7 +2997,7 @@ class RelationsOptions(): """ Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert - Einstein". See [Relation + Einstein". For more information, see [Relation types](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-relations). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. @@ -4351,8 +4360,8 @@ class TokenResult(): TokenResult. :attr str text: (optional) The token as it appears in the analyzed text. - :attr str part_of_speech: (optional) The part of speech of the token. For - descriptions of the values, see [Universal Dependencies POS + :attr str part_of_speech: (optional) The part of speech of the token. For more + information about the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). :attr List[int] location: (optional) Character offsets indicating the beginning and end of the token in the analyzed text. @@ -4371,7 +4380,7 @@ def __init__(self, :param str text: (optional) The token as it appears in the analyzed text. :param str part_of_speech: (optional) The part of speech of the token. For - descriptions of the values, see [Universal Dependencies POS + more information about the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). :param List[int] location: (optional) Character offsets indicating the beginning and end of the token in the analyzed text. @@ -4441,8 +4450,8 @@ def __ne__(self, other: 'TokenResult') -> bool: class PartOfSpeechEnum(Enum): """ - The part of speech of the token. For descriptions of the values, see [Universal - Dependencies POS tags](https://universaldependencies.org/u/pos/). + The part of speech of the token. For more information about the values, see + [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). """ ADJ = "ADJ" ADP = "ADP" diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 7ba3c2986..d964df64b 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -51,7 +51,7 @@ class PersonalityInsightsV3(BaseService): """The Personality Insights V3 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/personality-insights/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.personality-insights.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'personality_insights' def __init__( diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index e23fa4e1a..f1cabb45a 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -14,12 +14,12 @@ # See the License for the specific language governing permissions and # limitations under the License. """ -The IBM® Speech to Text service provides APIs that use IBM's speech-recognition -capabilities to produce transcripts of spoken audio. The service can transcribe speech -from various languages and audio formats. In addition to basic transcription, the service -can produce detailed information about many different aspects of the audio. For most -languages, the service supports two sampling rates, broadband and narrowband. It returns -all JSON response content in the UTF-8 character set. +The IBM Watson™ Speech to Text service provides APIs that use IBM's +speech-recognition capabilities to produce transcripts of spoken audio. The service can +transcribe speech from various languages and audio formats. In addition to basic +transcription, the service can produce detailed information about many different aspects +of the audio. For most languages, the service supports two sampling rates, broadband and +narrowband. It returns all JSON response content in the UTF-8 character set. For speech recognition, the service supports synchronous and asynchronous HTTP Representational State Transfer (REST) interfaces. It also supports a WebSocket interface that provides a full-duplex, low-latency communication channel: Clients send requests and @@ -53,7 +53,7 @@ class SpeechToTextV1(BaseService): """The Speech to Text V1 service.""" - DEFAULT_SERVICE_URL = 'https://stream.watsonplatform.net/speech-to-text/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.speech-to-text.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'speech_to_text' def __init__( @@ -86,7 +86,8 @@ def list_models(self, **kwargs) -> 'DetailedResponse': Lists all language models that are available for use with the service. The information includes the name of the model and its minimum sampling rate in Hertz, - among other things. + among other things. The ordering of the list of models can change from call to + call; do not rely on an alphabetized or static list of models. **See also:** [Languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). @@ -358,11 +359,9 @@ def recognize(self, multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - **Note:** Applies to US English, German, Japanese, Korean, and Spanish - (both broadband and narrowband models) and UK English (narrowband model) - transcription only. To determine whether a language model supports speaker - labels, you can also use the **Get a model** method and check that the - attribute `speaker_labels` is set to `true`. + **Note:** Applies to US English, Australian English, German, Japanese, + Korean, and Spanish (both broadband and narrowband models) and UK English + (narrowband model) transcription only. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#speaker_labels). :param str customization_id: (optional) **Deprecated.** Use the @@ -512,9 +511,9 @@ def register_callback(self, Register a callback. Registers a callback URL with the service for use with subsequent asynchronous - recognition requests. The service attempts to register, or white-list, the - callback URL if it is not already registered by sending a `GET` request to the - callback URL. The service passes a random alphanumeric challenge string via the + recognition requests. The service attempts to register, or allowlist, the callback + URL if it is not already registered by sending a `GET` request to the callback + URL. The service passes a random alphanumeric challenge string via the `challenge_string` parameter of the request. The request includes an `Accept` header that specifies `text/plain` as the required response type. To be registered successfully, the callback URL must respond to the `GET` request @@ -524,9 +523,9 @@ def register_callback(self, registration request with response code 201. The service sends only a single `GET` request to the callback URL. If the service does not receive a reply with a response code of 200 and a body that echoes the - challenge string sent by the service within five seconds, it does not white-list + challenge string sent by the service within five seconds, it does not allowlist the URL; it instead sends status code 400 in response to the **Register a - callback** request. If the requested callback URL is already white-listed, the + callback** request. If the requested callback URL is already allowlisted, the service responds to the initial registration request with response code 200. If you specify a user secret with the request, the service uses it as a key to calculate an HMAC-SHA1 signature of the challenge string in its response to the @@ -542,7 +541,7 @@ def register_callback(self, 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 + notifications are to be sent. To be allowlisted, the URL must successfully echo the challenge string during URL verification. During verification, the client can also check the signature that the service sends in the `X-Callback-Signature` header to verify the origin of the request. @@ -584,7 +583,7 @@ def unregister_callback(self, callback_url: str, """ Unregister a callback. - Unregisters a callback URL that was previously white-listed with a **Register a + Unregisters a callback URL that was previously allowlisted with a **Register a 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 @@ -746,7 +745,7 @@ def create_job(self, for the recognition request. See [Languages and 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 + are to be sent. The URL must already be successfully allowlisted by using the **Register a callback** method. You can include the same callback URL with any number of job creation requests. Omit the parameter to poll the service for job completion and results. @@ -884,11 +883,9 @@ def create_job(self, multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - **Note:** Applies to US English, German, Japanese, Korean, and Spanish - (both broadband and narrowband models) and UK English (narrowband model) - transcription only. To determine whether a language model supports speaker - labels, you can also use the **Get a model** method and check that the - attribute `speaker_labels` is set to `true`. + **Note:** Applies to US English, Australian English, German, Japanese, + Korean, and Spanish (both broadband and narrowband models) and UK English + (narrowband model) transcription only. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#speaker_labels). :param str customization_id: (optional) **Deprecated.** Use the @@ -1277,9 +1274,11 @@ def list_language_models(self, 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, - `en-US`). Omit the parameter to see all custom language or custom acoustic - models that are owned by the requesting credentials. + custom language or custom acoustic models are to be returned. Omit the + parameter to see all custom language or custom acoustic models that are + owned by the requesting credentials. **Note:** The `ar-AR` (Modern Standard + Arabic) and `zh-CN` (Mandarin Chinese) languages are not available for + language model customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2540,9 +2539,11 @@ def list_acoustic_models(self, 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, - `en-US`). Omit the parameter to see all custom language or custom acoustic - models that are owned by the requesting credentials. + custom language or custom acoustic models are to be returned. Omit the + parameter to see all custom language or custom acoustic models that are + owned by the requesting credentials. **Note:** The `ar-AR` (Modern Standard + Arabic) and `zh-CN` (Mandarin Chinese) languages are not available for + language model customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3212,9 +3213,14 @@ def delete_user_data(self, customer_id: str, deletes all data for the customer ID, regardless of the method by which the information was added. The method has no effect if no data is associated with the customer ID. You must issue the request with credentials for the same instance of - the service that was used to associate the customer ID with the data. - You associate a customer ID with data by passing the `X-Watson-Metadata` header - with a request that passes the data. + the service that was used to associate the customer ID with the data. You + associate a customer ID with data by passing the `X-Watson-Metadata` header with a + request that passes the data. + **Note:** If you delete an instance of the service from the service console, all + data associated with that service instance is automatically deleted. This includes + all custom language models, corpora, grammars, and words; all custom acoustic + models and audio resources; all registered endpoints for the asynchronous HTTP + interface; and all data related to speech recognition requests. **See also:** [Information security](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-information-security#information-security). @@ -3258,6 +3264,8 @@ class ModelId(Enum): AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' + EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' @@ -3324,6 +3332,8 @@ class Model(Enum): AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' + EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' @@ -3390,6 +3400,8 @@ class Model(Enum): AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' + EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' @@ -3448,6 +3460,35 @@ class Events(Enum): RECOGNITIONS_FAILED = 'recognitions.failed' +class ListLanguageModelsEnums(object): + + class Language(Enum): + """ + The identifier of the language for which custom language or custom acoustic models + are to be returned. Omit the parameter to see all custom language or custom + acoustic models that are owned by the requesting credentials. **Note:** The + `ar-AR` (Modern Standard Arabic) and `zh-CN` (Mandarin Chinese) languages are not + available for language model customization. + """ + AR_AR = 'ar-AR' + DE_DE = 'de-DE' + EN_GB = 'en-GB' + EN_US = 'en-US' + ES_AR = 'es-AR' + ES_ES = 'es-ES' + ES_CL = 'es-CL' + ES_CO = 'es-CO' + ES_MX = 'es-MX' + ES_PE = 'es-PE' + 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' + + class TrainLanguageModelEnums(object): class WordTypeToAdd(Enum): @@ -3508,6 +3549,35 @@ class ContentType(Enum): APPLICATION_SRGS_XML = 'application/srgs+xml' +class ListAcousticModelsEnums(object): + + class Language(Enum): + """ + The identifier of the language for which custom language or custom acoustic models + are to be returned. Omit the parameter to see all custom language or custom + acoustic models that are owned by the requesting credentials. **Note:** The + `ar-AR` (Modern Standard Arabic) and `zh-CN` (Mandarin Chinese) languages are not + available for language model customization. + """ + AR_AR = 'ar-AR' + DE_DE = 'de-DE' + EN_GB = 'en-GB' + EN_US = 'en-US' + ES_AR = 'es-AR' + ES_ES = 'es-ES' + ES_CL = 'es-CL' + ES_CO = 'es-CO' + ES_MX = 'es-MX' + ES_PE = 'es-PE' + 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' + + class AddAudioEnums(object): class ContentType(Enum): @@ -6397,9 +6467,9 @@ class RegisterStatus(): recognition. :attr str status: The current status of the job: - * `created`: The service successfully white-listed the callback URL as a result + * `created`: The service successfully allowlisted the callback URL as a result of the call. - * `already created`: The URL was already white-listed. + * `already created`: The URL was already allowlisted. :attr str url: The callback URL that is successfully registered. """ @@ -6408,9 +6478,9 @@ def __init__(self, status: str, url: str) -> None: Initialize a RegisterStatus object. :param str status: The current status of the job: - * `created`: The service successfully white-listed the callback URL as a + * `created`: The service successfully allowlisted the callback URL as a result of the call. - * `already created`: The URL was already white-listed. + * `already created`: The URL was already allowlisted. :param str url: The callback URL that is successfully registered. """ self.status = status @@ -6474,9 +6544,9 @@ def __ne__(self, other: 'RegisterStatus') -> bool: class StatusEnum(Enum): """ The current status of the job: - * `created`: The service successfully white-listed the callback URL as a result of + * `created`: The service successfully allowlisted the callback URL as a result of the call. - * `already created`: The URL was already white-listed. + * `already created`: The URL was already allowlisted. """ CREATED = "created" ALREADY_CREATED = "already created" @@ -7290,6 +7360,10 @@ class SupportedFeatures(): can be used to create a custom language model based on the language model. :attr bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. + **Note:** The field returns `true` for all models. However, speaker labels are + supported only for US English, Australian English, German, Japanese, Korean, and + Spanish (both broadband and narrowband models) and UK English (narrowband model + only). Speaker labels are not supported for any other models. """ def __init__(self, custom_language_model: bool, @@ -7302,6 +7376,11 @@ def __init__(self, custom_language_model: bool, language model. :param bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. + **Note:** The field returns `true` for all models. However, speaker labels + are supported only for US English, Australian English, German, Japanese, + Korean, and Spanish (both broadband and narrowband models) and UK English + (narrowband model only). Speaker labels are not supported for any other + models. """ self.custom_language_model = custom_language_model self.speaker_labels = speaker_labels diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 6fb28a941..1fd76b89e 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. """ -The IBM® Text to Speech service provides APIs that use IBM's speech-synthesis +The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, dialects, and voices. The service supports at least one male or female voice, sometimes both, for each language. The audio is streamed back to the client with minimal delay. @@ -50,7 +50,7 @@ class TextToSpeechV1(BaseService): """The Text to Speech V1 service.""" - DEFAULT_SERVICE_URL = 'https://stream.watsonplatform.net/text-to-speech/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.text-to-speech.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'text_to_speech' def __init__( @@ -82,8 +82,10 @@ def list_voices(self, **kwargs) -> 'DetailedResponse': List voices. Lists all voices available for use with the service. The information includes the - name, language, gender, and other details about the voice. To see information - about a specific voice, use the **Get a voice** method. + name, language, gender, and other details about the voice. The ordering of the + list of voices can change from call to call; do not rely on an alphabetized or + static list of voices. To see information about a specific voice, use the **Get a + voice** method. **See also:** [Listing all available voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoices). @@ -888,9 +890,13 @@ def delete_user_data(self, customer_id: str, deletes all data for the customer ID, regardless of the method by which the information was added. The method has no effect if no data is associated with the customer ID. You must issue the request with credentials for the same instance of - the service that was used to associate the customer ID with the data. - You associate a customer ID with data by passing the `X-Watson-Metadata` header - with a request that passes the data. + the service that was used to associate the customer ID with the data. You + associate a customer ID with data by passing the `X-Watson-Metadata` header with a + request that passes the data. + **Note:** If you delete an instance of the service from the service console, all + data associated with that service instance is automatically deleted. This includes + all custom voice models and word/translation pairs, and all data related to speech + synthesis requests. **See also:** [Information security](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-information-security#information-security). @@ -936,6 +942,8 @@ class Voice(Enum): DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' + EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONVOICE = 'en-US_AllisonVoice' @@ -956,6 +964,7 @@ class Voice(Enum): ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' @@ -1006,6 +1015,8 @@ class Voice(Enum): DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' + EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONVOICE = 'en-US_AllisonVoice' @@ -1026,6 +1037,7 @@ class Voice(Enum): ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' @@ -1057,6 +1069,8 @@ class Voice(Enum): DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' + EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONVOICE = 'en-US_AllisonVoice' @@ -1077,6 +1091,7 @@ class Voice(Enum): ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 88ec65e8d..d9fd44f14 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -43,7 +43,7 @@ class ToneAnalyzerV3(BaseService): """The Tone Analyzer V3 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/tone-analyzer/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'tone_analyzer' def __init__( diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index efef3065a..47e97fafb 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -41,7 +41,7 @@ class VisualRecognitionV3(BaseService): """The Visual Recognition V3 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'visual_recognition' def __init__( diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index d256258f7..79b32f3fd 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -40,7 +40,7 @@ class VisualRecognitionV4(BaseService): """The Visual Recognition V4 service.""" - DEFAULT_SERVICE_URL = 'https://gateway.watsonplatform.net/visual-recognition/api' + DEFAULT_SERVICE_URL = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'visual_recognition' def __init__( From 99555f017a08fa42457fbebdaf4d03a854482683 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:28:59 -0400 Subject: [PATCH 266/455] feat: generate unit tests using current api defs --- test/unit/test_assistant_v1.py | 4 +- test/unit/test_assistant_v2.py | 169 ++- test/unit/test_compare_comply_v1.py | 4 +- test/unit/test_discovery_v1.py | 4 +- test/unit/test_discovery_v2.py | 1114 ++++++++++++++++- test/unit/test_language_translator_v3.py | 82 +- .../test_natural_language_classifier_v1.py | 4 +- .../test_natural_language_understanding_v1.py | 2 +- test/unit/test_personality_insights_v3.py | 4 +- test/unit/test_speech_to_text_v1.py | 4 +- test/unit/test_text_to_speech_v1.py | 4 +- test/unit/test_tone_analyzer_v3.py | 4 +- test/unit/test_visual_recognition_v3.py | 4 +- test/unit/test_visual_recognition_v4.py | 4 +- 14 files changed, 1380 insertions(+), 27 deletions(-) diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index bc1ed2ad3..e0db9de56 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import ibm_watson.assistant_v1 from ibm_watson.assistant_v1 import * -base_url = 'https://gateway.watsonplatform.net/assistant/api' +base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' ############################################################################## # Start of Service: Message diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index c9782ee8a..9056aa0ba 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import ibm_watson.assistant_v2 from ibm_watson.assistant_v2 import * -base_url = 'https://gateway.watsonplatform.net/assistant/api' +base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' ############################################################################## # Start of Service: Sessions @@ -329,6 +329,170 @@ def construct_required_body(self): # End of Service: Message ############################################################################## +############################################################################## +# Start of Service: Logs +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_logs +#----------------------------------------------------------------------------- +class TestListLogs(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_logs_response(self): + body = self.construct_full_body() + response = fake_response_LogCollection_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_logs_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_LogCollection_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_logs_empty(self): + check_empty_required_params(self, fake_response_LogCollection_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/assistants/{0}/logs'.format(body['assistant_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 = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2020-04-01', + ) + service.set_service_url(base_url) + output = service.list_logs(**body) + return output + + def construct_full_body(self): + body = dict() + body['assistant_id'] = "string1" + body['sort'] = "string1" + body['filter'] = "string1" + body['page_limit'] = 12345 + body['cursor'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['assistant_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Logs +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_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_user_data_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_user_data_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 = '/v2/user_data' + 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=202, + content_type='') + + def call_service(self, body): + service = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2020-04-01', + ) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + def check_empty_required_params(obj, response): """Test function to assert that the operation will throw an error when given empty required data @@ -397,3 +561,4 @@ def send_request(obj, body, response, url=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"}, "spelling": {"text": "fake_text", "original_text": "fake_original_text", "suggested_text": "fake_suggested_text"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}}""" fake_response_MessageResponseStateless_json = """{"output": {"generic": [], "intents": [], "entities": [], "actions": [], "debug": {"nodes_visited": [], "log_messages": [], "branch_exited": false, "branch_exited_reason": "fake_branch_exited_reason"}, "spelling": {"text": "fake_text", "original_text": "fake_original_text", "suggested_text": "fake_suggested_text"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}}""" +fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 753607be4..b3753aa22 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.compare_comply_v1 from ibm_watson.compare_comply_v1 import * -base_url = 'https://gateway.watsonplatform.net/compare-comply/api' +base_url = 'https://api.us-south.compare-comply.watson.cloud.ibm.com' ############################################################################## # Start of Service: HTMLConversion diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index d18699074..b3294d735 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.discovery_v1 from ibm_watson.discovery_v1 import * -base_url = 'https://gateway.watsonplatform.net/discovery/api' +base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' ############################################################################## # Start of Service: Environments diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index d5f320933..bccc2efcf 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.discovery_v2 from ibm_watson.discovery_v2 import * -base_url = 'https://fake' +base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' ############################################################################## # Start of Service: Collections @@ -100,6 +100,296 @@ def construct_required_body(self): return body +#----------------------------------------------------------------------------- +# Test Class for create_collection +#----------------------------------------------------------------------------- +class TestCreateCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_collection_response(self): + body = self.construct_full_body() + response = fake_response_CollectionDetails_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_create_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CollectionDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_collection_empty(self): + check_empty_required_params(self, fake_response_CollectionDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections'.format(body['project_id']) + 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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.create_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body.update({"name": "string1", "description": "string1", "language": "string1", "enrichments": [], }) + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body.update({"name": "string1", "description": "string1", "language": "string1", "enrichments": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_collection +#----------------------------------------------------------------------------- +class TestGetCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_collection_response(self): + body = self.construct_full_body() + response = fake_response_CollectionDetails_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_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CollectionDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_collection_empty(self): + check_empty_required_params(self, fake_response_CollectionDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections/{1}'.format(body['project_id'], 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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.get_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_collection +#----------------------------------------------------------------------------- +class TestUpdateCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_response(self): + body = self.construct_full_body() + response = fake_response_CollectionDetails_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_collection_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_CollectionDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_collection_empty(self): + check_empty_required_params(self, fake_response_CollectionDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections/{1}'.format(body['project_id'], body['collection_id']) + 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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.update_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + body.update({"name": "string1", "description": "string1", "enrichments": [], }) + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + body.update({"name": "string1", "description": "string1", "enrichments": [], }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_collection +#----------------------------------------------------------------------------- +class TestDeleteCollection(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_collection_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_collection_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_collection_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 = '/v2/projects/{0}/collections/{1}'.format(body['project_id'], body['collection_id']) + 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=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.delete_collection(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + return body + + # endregion ############################################################################## # End of Service: Collections @@ -1096,6 +1386,815 @@ def construct_required_body(self): # End of Service: TrainingData ############################################################################## +############################################################################## +# Start of Service: Enrichments +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_enrichments +#----------------------------------------------------------------------------- +class TestListEnrichments(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_enrichments_response(self): + body = self.construct_full_body() + response = fake_response_Enrichments_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_enrichments_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Enrichments_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_enrichments_empty(self): + check_empty_required_params(self, fake_response_Enrichments_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/enrichments'.format(body['project_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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.list_enrichments(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_enrichment +#----------------------------------------------------------------------------- +class TestCreateEnrichment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_enrichment_response(self): + body = self.construct_full_body() + response = fake_response_Enrichment_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_create_enrichment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Enrichment_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_enrichment_empty(self): + check_empty_required_params(self, fake_response_Enrichment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/enrichments'.format(body['project_id']) + 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=201, + content_type='application/json') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.create_enrichment(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment'] = {"enrichment": {"mock": "data"}} + body['file'] = tempfile.NamedTemporaryFile() + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment'] = {"enrichment": {"mock": "data"}} + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_enrichment +#----------------------------------------------------------------------------- +class TestGetEnrichment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_enrichment_response(self): + body = self.construct_full_body() + response = fake_response_Enrichment_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_enrichment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Enrichment_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_enrichment_empty(self): + check_empty_required_params(self, fake_response_Enrichment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/enrichments/{1}'.format(body['project_id'], body['enrichment_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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.get_enrichment(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_enrichment +#----------------------------------------------------------------------------- +class TestUpdateEnrichment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_enrichment_response(self): + body = self.construct_full_body() + response = fake_response_Enrichment_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_enrichment_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Enrichment_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_enrichment_empty(self): + check_empty_required_params(self, fake_response_Enrichment_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/enrichments/{1}'.format(body['project_id'], body['enrichment_id']) + 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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.update_enrichment(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + body.update({"name": "string1", "description": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + body.update({"name": "string1", "description": "string1", }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_enrichment +#----------------------------------------------------------------------------- +class TestDeleteEnrichment(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_enrichment_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_enrichment_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_enrichment_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 = '/v2/projects/{0}/enrichments/{1}'.format(body['project_id'], body['enrichment_id']) + 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=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.delete_enrichment(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['enrichment_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Enrichments +############################################################################## + +############################################################################## +# Start of Service: Projects +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_projects +#----------------------------------------------------------------------------- +class TestListProjects(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_projects_response(self): + body = self.construct_full_body() + response = fake_response_ListProjectsResponse_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_projects_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ListProjectsResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_projects_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects' + 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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.list_projects(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +#----------------------------------------------------------------------------- +# Test Class for create_project +#----------------------------------------------------------------------------- +class TestCreateProject(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_project_response(self): + body = self.construct_full_body() + response = fake_response_ProjectDetails_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_create_project_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ProjectDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_create_project_empty(self): + check_empty_required_params(self, fake_response_ProjectDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects' + 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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.create_project(**body) + return output + + def construct_full_body(self): + body = dict() + body.update({"name": "string1", "type": "string1", "default_query_parameters": DefaultQueryParams._from_dict(json.loads("""{"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}""")), }) + return body + + def construct_required_body(self): + body = dict() + body.update({"name": "string1", "type": "string1", "default_query_parameters": DefaultQueryParams._from_dict(json.loads("""{"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}""")), }) + return body + + +#----------------------------------------------------------------------------- +# Test Class for get_project +#----------------------------------------------------------------------------- +class TestGetProject(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_project_response(self): + body = self.construct_full_body() + response = fake_response_ProjectDetails_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_project_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ProjectDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_get_project_empty(self): + check_empty_required_params(self, fake_response_ProjectDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}'.format(body['project_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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.get_project(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for update_project +#----------------------------------------------------------------------------- +class TestUpdateProject(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_project_response(self): + body = self.construct_full_body() + response = fake_response_ProjectDetails_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_project_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_ProjectDetails_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_update_project_empty(self): + check_empty_required_params(self, fake_response_ProjectDetails_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}'.format(body['project_id']) + 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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.update_project(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body.update({"name": "string1", }) + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +#----------------------------------------------------------------------------- +# Test Class for delete_project +#----------------------------------------------------------------------------- +class TestDeleteProject(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_project_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_project_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_project_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 = '/v2/projects/{0}'.format(body['project_id']) + 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=204, + content_type='') + + def call_service(self, body): + service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.delete_project(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Projects +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for delete_user_data +#----------------------------------------------------------------------------- +class TestDeleteUserData(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_delete_user_data_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_user_data_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_user_data_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 = '/v2/user_data' + 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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.delete_user_data(**body) + return output + + def construct_full_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['customer_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: UserData +############################################################################## + def check_empty_required_params(obj, response): """Test function to assert that the operation will throw an error when given empty required data @@ -1162,6 +2261,9 @@ def send_request(obj, body, response, url=None): fake_response__json = None fake_response_ListCollectionsResponse_json = """{"collections": []}""" +fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" +fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" +fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query", "suggested_refinements": [], "table_results": []}""" fake_response_Completions_json = """{"completions": []}""" fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "notices": []}""" @@ -1174,3 +2276,11 @@ def send_request(obj, body, response, url=None): fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" +fake_response_Enrichments_json = """{"enrichments": []}""" +fake_response_Enrichment_json = """{"enrichment_id": "fake_enrichment_id", "name": "fake_name", "description": "fake_description", "type": "fake_type", "options": {"languages": [], "entity_type": "fake_entity_type", "regular_expression": "fake_regular_expression", "result_field": "fake_result_field"}}""" +fake_response_Enrichment_json = """{"enrichment_id": "fake_enrichment_id", "name": "fake_name", "description": "fake_description", "type": "fake_type", "options": {"languages": [], "entity_type": "fake_entity_type", "regular_expression": "fake_regular_expression", "result_field": "fake_result_field"}}""" +fake_response_Enrichment_json = """{"enrichment_id": "fake_enrichment_id", "name": "fake_name", "description": "fake_description", "type": "fake_type", "options": {"languages": [], "entity_type": "fake_entity_type", "regular_expression": "fake_regular_expression", "result_field": "fake_result_field"}}""" +fake_response_ListProjectsResponse_json = """{"projects": []}""" +fake_response_ProjectDetails_json = """{"project_id": "fake_project_id", "name": "fake_name", "type": "fake_type", "relevancy_training_status": {"data_updated": "fake_data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "fake_successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}}""" +fake_response_ProjectDetails_json = """{"project_id": "fake_project_id", "name": "fake_name", "type": "fake_type", "relevancy_training_status": {"data_updated": "fake_data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "fake_successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}}""" +fake_response_ProjectDetails_json = """{"project_id": "fake_project_id", "name": "fake_name", "type": "fake_type", "relevancy_training_status": {"data_updated": "fake_data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "fake_successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}}""" diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 65586dff3..5d732d7f6 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,84 @@ import ibm_watson.language_translator_v3 from ibm_watson.language_translator_v3 import * -base_url = 'https://gateway.watsonplatform.net/language-translator/api' +base_url = 'https://api.us-south.language-translator.watson.cloud.ibm.com' + +############################################################################## +# Start of Service: Languages +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for list_languages +#----------------------------------------------------------------------------- +class TestListLanguages(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_languages_response(self): + body = self.construct_full_body() + response = fake_response_Languages_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_languages_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_Languages_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_list_languages_empty(self): + check_empty_response(self) + assert len(responses.calls) == 1 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v3/languages' + 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 = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version='2018-05-01', + ) + service.set_service_url(base_url) + output = service.list_languages(**body) + return output + + def construct_full_body(self): + body = dict() + return body + + def construct_required_body(self): + body = dict() + return body + + +# endregion +############################################################################## +# End of Service: Languages +############################################################################## ############################################################################## # Start of Service: Translation @@ -974,6 +1051,7 @@ def send_request(obj, body, response, url=None): #################### fake_response__json = None +fake_response_Languages_json = """{"languages": []}""" fake_response_TranslationResult_json = """{"word_count": 10, "character_count": 15, "detected_language": "fake_detected_language", "detected_language_confidence": 28, "translations": []}""" fake_response_IdentifiableLanguages_json = """{"languages": []}""" fake_response_IdentifiedLanguages_json = """{"languages": []}""" diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index 3c142ef6c..3fb8d18ab 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.natural_language_classifier_v1 from ibm_watson.natural_language_classifier_v1 import * -base_url = 'https://gateway.watsonplatform.net/natural-language-classifier/api' +base_url = 'https://api.us-south.natural-language-classifier.watson.cloud.ibm.com' ############################################################################## # Start of Service: ClassifyText diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 0857daea3..2def05826 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -22,7 +22,7 @@ import ibm_watson.natural_language_understanding_v1 from ibm_watson.natural_language_understanding_v1 import * -base_url = 'https://gateway.watsonplatform.net/natural-language-understanding/api' +base_url = 'https://api.us-south.natural-language-understanding.watson.cloud.ibm.com' ############################################################################## # Start of Service: Analyze diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index fe646402f..dcbc29a2d 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import ibm_watson.personality_insights_v3 from ibm_watson.personality_insights_v3 import * -base_url = 'https://gateway.watsonplatform.net/personality-insights/api' +base_url = 'https://api.us-south.personality-insights.watson.cloud.ibm.com' ############################################################################## # Start of Service: Methods diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 8b8aff3e2..415c54fe8 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -22,7 +22,7 @@ import ibm_watson.speech_to_text_v1 from ibm_watson.speech_to_text_v1 import * -base_url = 'https://stream.watsonplatform.net/speech-to-text/api' +base_url = 'https://api.us-south.speech-to-text.watson.cloud.ibm.com' ############################################################################## # Start of Service: Models diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index b9b89e2a7..57eda15aa 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import ibm_watson.text_to_speech_v1 from ibm_watson.text_to_speech_v1 import * -base_url = 'https://stream.watsonplatform.net/text-to-speech/api' +base_url = 'https://api.us-south.text-to-speech.watson.cloud.ibm.com' ############################################################################## # Start of Service: Voices diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index f9e5a577e..13a2928e5 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -21,7 +21,7 @@ import ibm_watson.tone_analyzer_v3 from ibm_watson.tone_analyzer_v3 import * -base_url = 'https://gateway.watsonplatform.net/tone-analyzer/api' +base_url = 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com' ############################################################################## # Start of Service: Methods diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index a469b83c9..af2790c7a 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.visual_recognition_v3 from ibm_watson.visual_recognition_v3 import * -base_url = 'https://gateway.watsonplatform.net/visual-recognition/api' +base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' ############################################################################## # Start of Service: General diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index ee589767d..a5850db62 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +23,7 @@ import ibm_watson.visual_recognition_v4 from ibm_watson.visual_recognition_v4 import * -base_url = 'https://gateway.watsonplatform.net/visual-recognition/api' +base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' ############################################################################## # Start of Service: Analysis From 7ddb0c3a43cdb9ece492c51ad45d134b52909e87 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:29:39 -0400 Subject: [PATCH 267/455] test: add test doc for create enrichment test --- resources/TestEnrichments.csv | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 resources/TestEnrichments.csv diff --git a/resources/TestEnrichments.csv b/resources/TestEnrichments.csv new file mode 100644 index 000000000..0acd7812b --- /dev/null +++ b/resources/TestEnrichments.csv @@ -0,0 +1,2 @@ +engine,gasket,piston,valves +flag,green,yellow,red \ No newline at end of file From a091f2418df33ebba7017d1d9e59e03b413069c5 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 24 Aug 2020 09:32:16 -0400 Subject: [PATCH 268/455] chore: fix copyrights --- test/unit/test_assistant_v1.py | 2 +- test/unit/test_assistant_v2.py | 2 +- test/unit/test_compare_comply_v1.py | 2 +- test/unit/test_discovery_v1.py | 2 +- test/unit/test_discovery_v2.py | 2 +- test/unit/test_language_translator_v3.py | 2 +- test/unit/test_natural_language_classifier_v1.py | 2 +- test/unit/test_personality_insights_v3.py | 2 +- test/unit/test_speech_to_text_v1.py | 2 +- test/unit/test_text_to_speech_v1.py | 2 +- test/unit/test_tone_analyzer_v3.py | 2 +- test/unit/test_visual_recognition_v3.py | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index e0db9de56..cff1fdcc1 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 9056aa0ba..a0b8cf62b 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index b3753aa22..577a098a8 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index b3294d735..9d5dff330 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index bccc2efcf..9a36411c9 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2020. # # 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/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 5d732d7f6..105e27faf 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index 3fb8d18ab..8485c8f02 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index dcbc29a2d..e36cce0c1 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 415c54fe8..5a9dd4a4a 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 57eda15aa..31b2f739e 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2015, 2020. # # 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/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index 13a2928e5..12ca4aaa8 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index af2790c7a..1608ba69a 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2016, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. From a1d6443ac655d7a78c0cda40090a421a22375184 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 25 Aug 2020 20:06:05 +0000 Subject: [PATCH 269/455] =?UTF-8?q?Bump=20version:=204.5.0=20=E2=86=92=204?= =?UTF-8?q?.6.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 8d4e2c603..f25309bc7 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.5.0 +current_version = 4.6.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 330025d80..52fde385e 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.5.0' +__version__ = '4.6.0' diff --git a/setup.py b/setup.py index a18cc4a0d..e0959ef99 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.5.0' +__version__ = '4.6.0' if sys.argv[-1] == 'publish': From 5dcd1675c30aec7beb3eab6d2f57c625d4a902ba Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 25 Aug 2020 20:06:05 +0000 Subject: [PATCH 270/455] chore(release): 4.6.0 release notes # [4.6.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.5.0...v4.6.0) (2020-08-25) ### Features * generate unit tests using current api defs ([99555f0](https://github.com/watson-developer-cloud/python-sdk/commit/99555f017a08fa42457fbebdaf4d03a854482683)) * regenrate all services using current api def ([9ef3c6e](https://github.com/watson-developer-cloud/python-sdk/commit/9ef3c6e2df323a2bb7403bef417ddbd34ca6b462)) * **AssistantV2:** add support for list logs and delete user data ([6b87f9b](https://github.com/watson-developer-cloud/python-sdk/commit/6b87f9bc834f9b23e62a1d7047e8024839a50e36)) * **discoV2:** add new apis for enrichments, collections and projects ([4388ea2](https://github.com/watson-developer-cloud/python-sdk/commit/4388ea276b5473b13249592127a51e2004a1d82c)) * **languageTranslatorV3:** add support for list languages ([de83e96](https://github.com/watson-developer-cloud/python-sdk/commit/de83e96e5d4b0a9f2221fc48ca38ef66b0a0c68d)) --- CHANGELOG.md | 11 +++ package-lock.json | 231 +++++++++++++++++++++++++--------------------- 2 files changed, 138 insertions(+), 104 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cdbe2f7a..a7b02e979 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,14 @@ +# [4.6.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.5.0...v4.6.0) (2020-08-25) + + +### Features + +* generate unit tests using current api defs ([99555f0](https://github.com/watson-developer-cloud/python-sdk/commit/99555f017a08fa42457fbebdaf4d03a854482683)) +* regenrate all services using current api def ([9ef3c6e](https://github.com/watson-developer-cloud/python-sdk/commit/9ef3c6e2df323a2bb7403bef417ddbd34ca6b462)) +* **AssistantV2:** add support for list logs and delete user data ([6b87f9b](https://github.com/watson-developer-cloud/python-sdk/commit/6b87f9bc834f9b23e62a1d7047e8024839a50e36)) +* **discoV2:** add new apis for enrichments, collections and projects ([4388ea2](https://github.com/watson-developer-cloud/python-sdk/commit/4388ea276b5473b13249592127a51e2004a1d82c)) +* **languageTranslatorV3:** add support for list languages ([de83e96](https://github.com/watson-developer-cloud/python-sdk/commit/de83e96e5d4b0a9f2221fc48ca38ef66b0a0c68d)) + # [4.5.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.4.1...v4.5.0) (2020-06-04) diff --git a/package-lock.json b/package-lock.json index 1c9dd997c..50be76ca0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3,24 +3,24 @@ "lockfileVersion": 1, "dependencies": { "@babel/code-frame": { - "version": "7.10.1", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.1.tgz", - "integrity": "sha512-IGhtTmpjGbYzcEDOw7DcQtbQSXcG9ftmAXtWTu9V936vDye4xjjekktFAtgZsWpzTj/X01jocB46mTywm/4SZw==", + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", + "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", "requires": { - "@babel/highlight": "^7.10.1" + "@babel/highlight": "^7.10.4" } }, "@babel/helper-validator-identifier": { - "version": "7.10.1", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.10.1.tgz", - "integrity": "sha512-5vW/JXLALhczRCWP0PnFDMCJAchlBvM7f4uk/jXritBnIa6E1KmqmtrS3yn1LAnxFBypQ3eneLuXjsnfQsgILw==" + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.10.4.tgz", + "integrity": "sha512-3U9y+43hz7ZM+rzG24Qe2mufW5KhvFg/NhnNph+i9mgCtdTCtMJuI1TMkrIUiK7Ix4PYlRF9I5dhqaLYA/ADXw==" }, "@babel/highlight": { - "version": "7.10.1", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.10.1.tgz", - "integrity": "sha512-8rMof+gVP8mxYZApLF/JgNDAkdKa+aJt3ZYxF8z6+j/hpeXL7iMsKCPHa2jNMHu/qqBwzQF4OHNoYi8dMA/rYg==", + "version": "7.10.4", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.10.4.tgz", + "integrity": "sha512-i6rgnR/YgPEQzZZnbTHHuZdlE8qyoBNalD6F+q4vAFlcMEcqmkoG+mPqJYJCo63qPf74+Y1UZsl3l6f7/RIkmA==", "requires": { - "@babel/helper-validator-identifier": "^7.10.1", + "@babel/helper-validator-identifier": "^7.10.4", "chalk": "^2.0.0", "js-tokens": "^4.0.0" } @@ -49,52 +49,66 @@ } }, "@octokit/auth-token": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.1.tgz", - "integrity": "sha512-NB81O5h39KfHYGtgfWr2booRxp2bWOJoqbWwbyUg2hw6h35ArWYlAST5B3XwAkbdcx13yt84hFXyFP5X0QToWA==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.2.tgz", + "integrity": "sha512-jE/lE/IKIz2v1+/P0u4fJqv0kYwXOTujKemJMFr6FeopsxlIK3+wKDCJGnysg81XID5TgZQbIfuJ5J0lnTiuyQ==", "requires": { - "@octokit/types": "^4.0.1" + "@octokit/types": "^5.0.0" } }, "@octokit/core": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-2.5.3.tgz", - "integrity": "sha512-23AHK9xBW0v79Ck8h5U+5iA4MW7aosqv+Yr6uZXolVGNzzHwryNH5wM386/6+etiKUTwLFZTqyMU9oQpIBZcFA==", + "version": "2.5.4", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-2.5.4.tgz", + "integrity": "sha512-HCp8yKQfTITYK+Nd09MHzAlP1v3Ii/oCohv0/TW9rhSLvzb98BOVs2QmVYuloE6a3l6LsfyGIwb6Pc4ycgWlIQ==", "requires": { "@octokit/auth-token": "^2.4.0", "@octokit/graphql": "^4.3.1", "@octokit/request": "^5.4.0", - "@octokit/types": "^4.0.1", + "@octokit/types": "^5.0.0", "before-after-hook": "^2.1.0", "universal-user-agent": "^5.0.0" } }, "@octokit/endpoint": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.2.tgz", - "integrity": "sha512-xs1mmCEZ2y4shXCpFjNq3UbmNR+bLzxtZim2L0zfEtj9R6O6kc4qLDvYw66hvO6lUsYzPTM5hMkltbuNAbRAcQ==", + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.5.tgz", + "integrity": "sha512-70K5u6zd45ItOny6aHQAsea8HHQjlQq85yqOMe+Aj8dkhN2qSJ9T+Q3YjUjEYfPRBcuUWNgMn62DQnP/4LAIiQ==", "requires": { - "@octokit/types": "^4.0.1", - "is-plain-object": "^3.0.0", - "universal-user-agent": "^5.0.0" + "@octokit/types": "^5.0.0", + "is-plain-object": "^4.0.0", + "universal-user-agent": "^6.0.0" + }, + "dependencies": { + "universal-user-agent": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", + "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" + } } }, "@octokit/graphql": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.0.tgz", - "integrity": "sha512-StJWfn0M1QfhL3NKBz31e1TdDNZrHLLS57J2hin92SIfzlOVBuUaRkp31AGkGOAFOAVtyEX6ZiZcsjcJDjeb5g==", + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.4.tgz", + "integrity": "sha512-ITpZ+dQc0cXAW1FmDkHJJM+8Lb6anUnin0VB5hLBilnYVdLC0ICFU/KIvT7OXfW9S81DE3U4Vx2EypDG1OYaPA==", "requires": { "@octokit/request": "^5.3.0", - "@octokit/types": "^4.0.1", - "universal-user-agent": "^5.0.0" + "@octokit/types": "^5.0.0", + "universal-user-agent": "^6.0.0" + }, + "dependencies": { + "universal-user-agent": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", + "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" + } } }, "@octokit/plugin-paginate-rest": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.2.1.tgz", - "integrity": "sha512-/tHpIF2XpN40AyhIq295YRjb4g7Q5eKob0qM3thYJ0Z+CgmNsWKM/fWse/SUR8+LdprP1O4ZzSKQE+71TCwK+w==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.3.0.tgz", + "integrity": "sha512-Ye2ZJreP0ZlqJQz8fz+hXvrEAEYK4ay7br1eDpWzr6j76VXs/gKqxFcH8qRzkB3fo/2xh4Vy9VtGii4ZDc9qlA==", "requires": { - "@octokit/types": "^4.0.1" + "@octokit/types": "^5.2.0" } }, "@octokit/plugin-request-log": { @@ -103,54 +117,71 @@ "integrity": "sha512-ywoxP68aOT3zHCLgWZgwUJatiENeHE7xJzYjfz8WI0goynp96wETBF+d95b8g/uL4QmS6owPVlaxiz3wyMAzcw==" }, "@octokit/plugin-rest-endpoint-methods": { - "version": "3.14.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-3.14.0.tgz", - "integrity": "sha512-KTLPiXZ45WaDNilFUN3+o2pns0vFWkcWLsKf8mw3Z7AJTST7mI3ukoDk2bJ0FPnLTCHvQYR1qrwMFp8UShR7cQ==", + "version": "3.17.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-3.17.0.tgz", + "integrity": "sha512-NFV3vq7GgoO2TrkyBRUOwflkfTYkFKS0tLAPym7RNpkwLCttqShaEGjthOsPEEL+7LFcYv3mU24+F2yVd3npmg==", "requires": { - "@octokit/types": "^4.1.5", + "@octokit/types": "^4.1.6", "deprecation": "^2.3.1" + }, + "dependencies": { + "@octokit/types": { + "version": "4.1.10", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-4.1.10.tgz", + "integrity": "sha512-/wbFy1cUIE5eICcg0wTKGXMlKSbaAxEr00qaBXzscLXpqhcwgXeS6P8O0pkysBhRfyjkKjJaYrvR1ExMO5eOXQ==", + "requires": { + "@types/node": ">= 8" + } + } } }, "@octokit/request": { - "version": "5.4.4", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.4.tgz", - "integrity": "sha512-vqv1lz41c6VTxUvF9nM+a6U+vvP3vGk7drDpr0DVQg4zyqlOiKVrY17DLD6de5okj+YLHKcoqaUZTBtlNZ1BtQ==", + "version": "5.4.7", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.7.tgz", + "integrity": "sha512-FN22xUDP0i0uF38YMbOfx6TotpcENP5W8yJM1e/LieGXn6IoRxDMnBf7tx5RKSW4xuUZ/1P04NFZy5iY3Rax1A==", "requires": { "@octokit/endpoint": "^6.0.1", "@octokit/request-error": "^2.0.0", - "@octokit/types": "^4.0.1", + "@octokit/types": "^5.0.0", "deprecation": "^2.0.0", - "is-plain-object": "^3.0.0", + "is-plain-object": "^4.0.0", "node-fetch": "^2.3.0", "once": "^1.4.0", - "universal-user-agent": "^5.0.0" + "universal-user-agent": "^6.0.0" + }, + "dependencies": { + "universal-user-agent": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", + "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" + } } }, "@octokit/request-error": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.1.tgz", - "integrity": "sha512-5lqBDJ9/TOehK82VvomQ6zFiZjPeSom8fLkFVLuYL3sKiIb5RB8iN/lenLkY7oBmyQcGP7FBMGiIZTO8jufaRQ==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.2.tgz", + "integrity": "sha512-2BrmnvVSV1MXQvEkrb9zwzP0wXFNbPJij922kYBTLIlIafukrGOb+ABBT2+c6wZiuyWDH1K1zmjGQ0toN/wMWw==", "requires": { - "@octokit/types": "^4.0.1", + "@octokit/types": "^5.0.1", "deprecation": "^2.0.0", "once": "^1.4.0" } }, "@octokit/rest": { - "version": "17.9.3", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-17.9.3.tgz", - "integrity": "sha512-by1mGtNX4I5CFQDr8rN6lquE+EvEk1IstoJHUb3BmEPMMo27ftvYMHZjm1sl7f39sZlH26B0vcJWbWiDZFcsNQ==", + "version": "17.11.2", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-17.11.2.tgz", + "integrity": "sha512-4jTmn8WossTUaLfNDfXk4fVJgbz5JgZE8eCs4BvIb52lvIH8rpVMD1fgRCrHbSd6LRPE5JFZSfAEtszrOq3ZFQ==", "requires": { "@octokit/core": "^2.4.3", "@octokit/plugin-paginate-rest": "^2.2.0", "@octokit/plugin-request-log": "^1.0.0", - "@octokit/plugin-rest-endpoint-methods": "^3.14.0" + "@octokit/plugin-rest-endpoint-methods": "3.17.0" } }, "@octokit/types": { - "version": "4.1.6", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-4.1.6.tgz", - "integrity": "sha512-/gN/VeZirpFb0GIpbDF6SgtfDp9EQ+ymqPf595wjRkEoRgkrCnJGctGAd8MrynStBvYRmMWF1P64qzZFzhW7Vg==", + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-5.4.1.tgz", + "integrity": "sha512-OlMlSySBJoJ6uozkr/i03nO5dlYQyE05vmQNZhAh9MyO4DPBP88QlwsDVLmVjIMFssvIZB6WO0ctIGMRG+xsJQ==", "requires": { "@types/node": ">= 8" } @@ -228,9 +259,9 @@ "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==" }, "@types/node": { - "version": "14.0.10", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.0.10.tgz", - "integrity": "sha512-Bz23oN/5bi0rniKT24ExLf4cK0JdvN3dH/3k0whYkdN4eI4vS2ZW/2ENNn2uxHCzWcbdHIa/GRuWQytfzCjRYw==" + "version": "14.6.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.6.0.tgz", + "integrity": "sha512-mikldZQitV94akrc4sCcSjtJfsTKt4p+e/s0AGscVA6XArQ9kFclP+ZiYUMnq987rc6QlYxXv/EivqlfSLxpKA==" }, "@types/retry": { "version": "0.12.0", @@ -238,17 +269,17 @@ "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==" }, "agent-base": { - "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==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.1.tgz", + "integrity": "sha512-01q25QQDwLSsyfhrKbn8yuur+JNw0H+0Y4JiGIKd3z9aYk/w/2kxD/Upc+t2ZBBSUNff50VjPsSW2YxM8QYKVg==", "requires": { "debug": "4" } }, "aggregate-error": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.0.1.tgz", - "integrity": "sha512-quoaXsZ9/BLNae5yiNoUz+Nhkwz83GhWwtYFglcjEQB2NDHCIpApbqXxIFnm4Pq/Nvhrsq5sYJFyohrrxnTGAA==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", + "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", "requires": { "clean-stack": "^2.0.0", "indent-string": "^4.0.0" @@ -371,9 +402,9 @@ "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, "execa": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.2.tgz", - "integrity": "sha512-QI2zLa6CjGWdiQsmSkZoGtDx2N+cQIGb3yNolGTdjSQzydzLgYYf8LRuagp7S7fPimjcrzUDSUFd/MgzELMi4Q==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.3.tgz", + "integrity": "sha512-WFDXGHckXPWZX19t1kCsXzOpqX9LWYNqn4C+HqZlk/V0imTkzJZqf87ZBhvpHaftERYknpk0fjSylnXVlVgI0A==", "requires": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", @@ -387,9 +418,9 @@ } }, "fast-glob": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.2.tgz", - "integrity": "sha512-UDV82o4uQyljznxwMxyVRJgZZt3O5wENYojjzbaGEGZgeOxkLFf+V4cnUD+krzb2F72E18RhamkMZ7AdeggF7A==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.4.tgz", + "integrity": "sha512-kr/Oo6PX51265qeuCYsyGypiO5uJFgBS0jksyG7FUeCyQzNwYnzrNIMR1NXfkZXsMYXYLRAHgISHBz8gQcxKHQ==", "requires": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", @@ -427,9 +458,9 @@ } }, "get-stream": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.1.0.tgz", - "integrity": "sha512-EXr1FOzrzTfGeL0gQdeFEvOMm2mzMOglyiOXSTpPC+iAjAKftbr3jpCMWynogwYnM+eSj9sHGc6wjIcDvYiygw==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", "requires": { "pump": "^3.0.0" } @@ -523,12 +554,9 @@ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" }, "is-plain-object": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-3.0.0.tgz", - "integrity": "sha512-tZIpofR+P05k8Aocp7UI/2UTa9lTJSebCXpFFoR9aibpokDj/uXBsJ8luUu0tTVYKkMU6URDUuOfJZ7koewXvg==", - "requires": { - "isobject": "^4.0.0" - } + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-4.1.1.tgz", + "integrity": "sha512-5Aw8LLVsDlZsETVMhoMXzqsXwQqr/0vlnBYzIXJbYo2F4yYlhLHs+Ez7Bod7IIQKWkJbJfxrWD7pA1Dw1TKrwA==" }, "is-stream": { "version": "2.0.0", @@ -540,11 +568,6 @@ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=" }, - "isobject": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/isobject/-/isobject-4.0.0.tgz", - "integrity": "sha512-S/2fF5wH8SJA/kmwr6HYhK/RI/OkhD84k8ntalo0iJjZikgq1XFvR5M8NPT1x5F7fBwCG3qHfnzeP/Vh/ZxCUA==" - }, "issue-parser": { "version": "6.0.0", "resolved": "https://registry.npmjs.org/issue-parser/-/issue-parser-6.0.0.tgz", @@ -562,10 +585,10 @@ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, - "json-parse-better-errors": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/json-parse-better-errors/-/json-parse-better-errors-1.0.2.tgz", - "integrity": "sha512-mrqyZKfX5EhL7hvqcV6WG1yYjnjeuYDzDhhcAAUrq8Po85NBQBJP+ZDUT75qZQ98IkUoBqdkExkukOU7Ts2wrw==" + "json-parse-even-better-errors": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.0.tgz", + "integrity": "sha512-o3aP+RsWDJZayj1SbHNQAI8x0v3T3SKiGoZlNYfbUP1S3omJQ6i9CnqADqkSPaOAxwua4/1YWx5CM7oiChJt2Q==" }, "jsonfile": { "version": "6.0.1", @@ -582,9 +605,9 @@ "integrity": "sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA=" }, "lodash": { - "version": "4.17.15", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.15.tgz", - "integrity": "sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A==" + "version": "4.17.20", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz", + "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==" }, "lodash.capitalize": { "version": "4.2.1", @@ -612,9 +635,9 @@ "integrity": "sha1-2ZwHpmnp5tJOE2Lf4mbGdhavEwI=" }, "macos-release": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/macos-release/-/macos-release-2.3.0.tgz", - "integrity": "sha512-OHhSbtcviqMPt7yfw5ef5aghS2jzFVKEFyCJndQt2YpSQ9qRVSEv2axSJI1paVThEu+FFGs584h/1YhxjVqajA==" + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/macos-release/-/macos-release-2.4.1.tgz", + "integrity": "sha512-H/QHeBIN1fIGJX517pvK8IEK53yQOW7YcEI55oYtgjDdoCQQz7eJS94qt5kNrscReEyuD/JcdFCm2XBEcGOITg==" }, "merge-stream": { "version": "2.0.0", @@ -677,9 +700,9 @@ } }, "onetime": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.0.tgz", - "integrity": "sha512-5NcSkPHhwTVFIQN+TUqXoS5+dlElHXdpAWu9I0HP20YOtIi+aZ0Ct82jdlILDxjLEAWwvm+qj1m6aEtsDVmm6Q==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", "requires": { "mimic-fn": "^2.1.0" } @@ -726,13 +749,13 @@ } }, "parse-json": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.0.0.tgz", - "integrity": "sha512-OOY5b7PAEFV0E2Fir1KOkxchnZNCdowAJgQ5NuxjpBKTRP3pQhwkrkxqQjeoKJ+fO7bCpmIZaogI4eZGDMEGOw==", + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.1.0.tgz", + "integrity": "sha512-+mi/lmVVNKFNVyLXV31ERiy2CY5E1/F6QtJFEzoChPRwwngMNXRDQ9GJ5WdE2Z2P4AujsOi0/+2qHID68KwfIQ==", "requires": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", - "json-parse-better-errors": "^1.0.1", + "json-parse-even-better-errors": "^2.3.0", "lines-and-columns": "^1.1.6" } }, @@ -856,9 +879,9 @@ } }, "windows-release": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/windows-release/-/windows-release-3.3.0.tgz", - "integrity": "sha512-2HetyTg1Y+R+rUgrKeUEhAG/ZuOmTrI1NBb3ZyAGQMYmOJjBBPe4MTodghRkmLJZHwkuPi02anbeGP+Zf401LQ==", + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/windows-release/-/windows-release-3.3.3.tgz", + "integrity": "sha512-OSOGH1QYiW5yVor9TtmXKQvt2vjQqbYS+DqmsZw+r7xDwLXEeT3JGW0ZppFmHx4diyXmxt238KFR3N9jzevBRg==", "requires": { "execa": "^1.0.0" }, From 6353f53361f0c1998b746308a7713f1c0dbc172d Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Wed, 2 Sep 2020 18:15:00 -0400 Subject: [PATCH 271/455] feat(DiscoveryV2): add support for analyze document --- ibm_watson/discovery_v2.py | 244 +++++++++++++++++++++++++- test/integration/test_discovery_v2.py | 23 ++- test/unit/test_discovery_v2.py | 87 +++++++++ 3 files changed, 352 insertions(+), 2 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 947486b88..49127fdda 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1159,6 +1159,87 @@ def update_training_query(self, response = self.send(request) return response + ######################### + # analyze + ######################### + + def analyze_document(self, + project_id: str, + collection_id: str, + *, + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + **kwargs) -> 'DetailedResponse': + """ + Analyze a Document. + + Process a document using the specified collection's settings and return it for + realtime use. + **Note:** Documents processed using this method are not added to the specified + collection. + **Note:** This method is only supported on IBM Cloud Pak for Data instances of + Discovery. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str collection_id: The ID of the collection. + :param TextIO file: (optional) The content of the document to ingest. The + maximum supported file size when adding a file to a collection is 50 + megabytes, the maximum supported file size when testing a configuration is + 1 megabyte. Files larger than the supported size are rejected. + :param str filename: (optional) The filename for file. + :param str file_content_type: (optional) The content type of file. + :param str metadata: (optional) The maximum supported metadata file size is + 1 MB. Metadata parts larger than 1 MB are rejected. + Example: ``` { + "Creator": "Johnny Appleseed", + "Subject": "Apples" + } ```. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + 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='V2', + operation_id='analyze_document') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + if file: + if not filename and hasattr(file, 'name'): + filename = basename(file.name) + if not filename: + raise ValueError('filename must be provided') + form_data.append(('file', (filename, file, file_content_type or + 'application/octet-stream'))) + if metadata: + metadata = str(metadata) + form_data.append(('metadata', (None, metadata, 'text/plain'))) + + url = '/v2/projects/{0}/collections/{1}/analyze'.format( + *self._encode_path_vars(project_id, collection_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request) + return response + ######################### # enrichments ######################### @@ -1224,7 +1305,6 @@ def create_enrichment(self, if enrichment is None: raise ValueError('enrichment must be provided') - print(enrichment) headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1662,11 +1742,173 @@ class FileContentType(Enum): APPLICATION_XHTML_XML = 'application/xhtml+xml' +class AnalyzeDocumentEnums(object): + + class FileContentType(Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + ############################################################################## # Models ############################################################################## +class AnalyzedDocument(): + """ + An object containing the converted document and any identifed enrichments. + + :attr List[Notice] notices: (optional) Array of document results that match the + query. + :attr AnalyzedResult result: (optional) Result of the document analysis. + """ + + def __init__(self, + *, + notices: List['Notice'] = None, + result: 'AnalyzedResult' = None) -> None: + """ + Initialize a AnalyzedDocument object. + + :param List[Notice] notices: (optional) Array of document results that + match the query. + :param AnalyzedResult result: (optional) Result of the document analysis. + """ + self.notices = notices + self.result = result + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AnalyzedDocument': + """Initialize a AnalyzedDocument object from a json dictionary.""" + args = {} + valid_keys = ['notices', 'result'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class AnalyzedDocument: ' + + ', '.join(bad_keys)) + if 'notices' in _dict: + args['notices'] = [ + Notice._from_dict(x) for x in (_dict.get('notices')) + ] + if 'result' in _dict: + args['result'] = AnalyzedResult._from_dict(_dict.get('result')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalyzedDocument 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, 'notices') and self.notices is not None: + _dict['notices'] = [x._to_dict() for x in self.notices] + if hasattr(self, 'result') and self.result is not None: + _dict['result'] = self.result._to_dict() + 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 AnalyzedDocument object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'AnalyzedDocument') -> 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: 'AnalyzedDocument') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AnalyzedResult(): + """ + Result of the document analysis. + + :attr dict metadata: (optional) Metadata of the document. + """ + + def __init__(self, *, metadata: dict = None, **kwargs) -> None: + """ + Initialize a AnalyzedResult object. + + :param dict metadata: (optional) Metadata of the document. + :param **kwargs: (optional) Any additional properties. + """ + self.metadata = metadata + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': + """Initialize a AnalyzedResult object from a json dictionary.""" + args = {} + xtra = _dict.copy() + if 'metadata' in _dict: + args['metadata'] = _dict.get('metadata') + del xtra['metadata'] + args.update(xtra) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalyzedResult 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, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + if hasattr(self, '_additionalProperties'): + for _key in self._additionalProperties: + _value = getattr(self, _key, None) + if _value is not None: + _dict[_key] = _value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: + properties = {'metadata'} + if not hasattr(self, '_additionalProperties'): + super(AnalyzedResult, self).__setattr__('_additionalProperties', + set()) + if name not in properties: + self._additionalProperties.add(name) + super(AnalyzedResult, self).__setattr__(name, value) + + def __str__(self) -> str: + """Return a `str` version of this AnalyzedResult object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'AnalyzedResult') -> 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: 'AnalyzedResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Collection(): """ A collection for storing documents. diff --git a/test/integration/test_discovery_v2.py b/test/integration/test_discovery_v2.py index 03779a640..a06391f39 100644 --- a/test/integration/test_discovery_v2.py +++ b/test/integration/test_discovery_v2.py @@ -1,7 +1,8 @@ # coding: utf-8 from unittest import TestCase -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator, BearerTokenAuthenticator from ibm_watson.discovery_v2 import CreateEnrichment, EnrichmentOptions +from os.path import abspath import os import ibm_watson import pytest @@ -108,3 +109,23 @@ def test_enrichments(self): self.project_id, enrichment_id ) + + # can only test in CPD + def test_analyze(self): + authenticator = BearerTokenAuthenticator('') + discovery_cpd = ibm_watson.DiscoveryV2( + version='2020-08-12', + authenticator=authenticator + ) + discovery_cpd.service_url = "" + discovery_cpd.set_disable_ssl_verification(True) + test_file = abspath('resources/problem.json') + with open(test_file, 'rb') as file: + result = discovery_cpd.analyze_document( + project_id="", + collection_id="", + file=file, + file_content_type="application/json" + ).get_result() + assert result is not None + diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 9a36411c9..b25fd6ce6 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1386,6 +1386,92 @@ def construct_required_body(self): # End of Service: TrainingData ############################################################################## +############################################################################## +# Start of Service: Analyze +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for analyze_document +#----------------------------------------------------------------------------- +class TestAnalyzeDocument(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_analyze_document_response(self): + body = self.construct_full_body() + response = fake_response_AnalyzedDocument_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_analyze_document_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_AnalyzedDocument_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_analyze_document_empty(self): + check_empty_required_params(self, fake_response_AnalyzedDocument_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/projects/{0}/collections/{1}/analyze'.format(body['project_id'], body['collection_id']) + 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 = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version='2019-11-22', + ) + service.set_service_url(base_url) + output = service.analyze_document(**body) + return output + + def construct_full_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + body['file'] = tempfile.NamedTemporaryFile() + body['filename'] = "string1" + body['file_content_type'] = "string1" + body['metadata'] = "string1" + return body + + def construct_required_body(self): + body = dict() + body['project_id'] = "string1" + body['collection_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: Analyze +############################################################################## + ############################################################################## # Start of Service: Enrichments ############################################################################## @@ -2276,6 +2362,7 @@ def send_request(obj, body, response, url=None): fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" +fake_response_AnalyzedDocument_json = """{"notices": [], "result": {}}""" fake_response_Enrichments_json = """{"enrichments": []}""" fake_response_Enrichment_json = """{"enrichment_id": "fake_enrichment_id", "name": "fake_name", "description": "fake_description", "type": "fake_type", "options": {"languages": [], "entity_type": "fake_entity_type", "regular_expression": "fake_regular_expression", "result_field": "fake_result_field"}}""" fake_response_Enrichment_json = """{"enrichment_id": "fake_enrichment_id", "name": "fake_name", "description": "fake_description", "type": "fake_type", "options": {"languages": [], "entity_type": "fake_entity_type", "regular_expression": "fake_regular_expression", "result_field": "fake_result_field"}}""" From 795c7f30a2178766537f243af90ccebf8b1e94df Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 3 Sep 2020 00:07:55 +0000 Subject: [PATCH 272/455] =?UTF-8?q?Bump=20version:=204.6.0=20=E2=86=92=204?= =?UTF-8?q?.7.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index f25309bc7..6479f5cc1 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.6.0 +current_version = 4.7.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 52fde385e..372a50797 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.6.0' +__version__ = '4.7.0' diff --git a/setup.py b/setup.py index e0959ef99..1e530924b 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.6.0' +__version__ = '4.7.0' if sys.argv[-1] == 'publish': From 23db316ca15541678ed98b5cc7f2331f5a64c2fa Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 3 Sep 2020 00:07:55 +0000 Subject: [PATCH 273/455] chore(release): 4.7.0 release notes # [4.7.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.6.0...v4.7.0) (2020-09-03) ### Features * **DiscoveryV2:** add support for analyze document ([6353f53](https://github.com/watson-developer-cloud/python-sdk/commit/6353f53361f0c1998b746308a7713f1c0dbc172d)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 20 ++++++++++---------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a7b02e979..859632288 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# [4.7.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.6.0...v4.7.0) (2020-09-03) + + +### Features + +* **DiscoveryV2:** add support for analyze document ([6353f53](https://github.com/watson-developer-cloud/python-sdk/commit/6353f53361f0c1998b746308a7713f1c0dbc172d)) + # [4.6.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.5.0...v4.6.0) (2020-08-25) diff --git a/package-lock.json b/package-lock.json index 50be76ca0..09aceeeb4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -104,11 +104,11 @@ } }, "@octokit/plugin-paginate-rest": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.3.0.tgz", - "integrity": "sha512-Ye2ZJreP0ZlqJQz8fz+hXvrEAEYK4ay7br1eDpWzr6j76VXs/gKqxFcH8qRzkB3fo/2xh4Vy9VtGii4ZDc9qlA==", + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.3.1.tgz", + "integrity": "sha512-81A+ONLpcSX7vWxnEmVZteQPNsbdeScSVUqjgMYPSk1trzG69iYkhS42wPRWtN0nYw6OEmT48DNeQCjHeyroYw==", "requires": { - "@octokit/types": "^5.2.0" + "@octokit/types": "^5.3.0" } }, "@octokit/plugin-request-log": { @@ -259,9 +259,9 @@ "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==" }, "@types/node": { - "version": "14.6.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.6.0.tgz", - "integrity": "sha512-mikldZQitV94akrc4sCcSjtJfsTKt4p+e/s0AGscVA6XArQ9kFclP+ZiYUMnq987rc6QlYxXv/EivqlfSLxpKA==" + "version": "14.6.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.6.3.tgz", + "integrity": "sha512-pC/hkcREG6YfDfui1FBmj8e20jFU5Exjw4NYDm8kEdrW+mOh0T1Zve8DWKnS7ZIZvgncrctcNCXF4Q2I+loyww==" }, "@types/retry": { "version": "0.12.0", @@ -586,9 +586,9 @@ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" }, "json-parse-even-better-errors": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.0.tgz", - "integrity": "sha512-o3aP+RsWDJZayj1SbHNQAI8x0v3T3SKiGoZlNYfbUP1S3omJQ6i9CnqADqkSPaOAxwua4/1YWx5CM7oiChJt2Q==" + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==" }, "jsonfile": { "version": "6.0.1", From 18d5997faa44af4e3c11b217f598dd4e3c75115c Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 3 Sep 2020 16:31:35 -0400 Subject: [PATCH 274/455] fix: lock the cloud sdk library version --- setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.py b/setup.py index 1e530924b..0ef5ff6ad 100644 --- a/setup.py +++ b/setup.py @@ -64,7 +64,7 @@ def run_tests(self): version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.5.1'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.7.3'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='IBM Watson', From e5080d894374bd0472014977a022b9a1e310eef5 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 3 Sep 2020 22:01:24 +0000 Subject: [PATCH 275/455] =?UTF-8?q?Bump=20version:=204.7.0=20=E2=86=92=204?= =?UTF-8?q?.7.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 6479f5cc1..0f09a7752 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.7.0 +current_version = 4.7.1 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 372a50797..3c9329b27 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.7.0' +__version__ = '4.7.1' diff --git a/setup.py b/setup.py index 0ef5ff6ad..8f98d0019 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.7.0' +__version__ = '4.7.1' if sys.argv[-1] == 'publish': From bceece83a1e96b4451673e0298701985a784b339 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 3 Sep 2020 22:01:24 +0000 Subject: [PATCH 276/455] chore(release): 4.7.1 release notes ## [4.7.1](https://github.com/watson-developer-cloud/python-sdk/compare/v4.7.0...v4.7.1) (2020-09-03) ### Bug Fixes * lock the cloud sdk library version ([18d5997](https://github.com/watson-developer-cloud/python-sdk/commit/18d5997faa44af4e3c11b217f598dd4e3c75115c)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 6 +++--- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 859632288..38b32d320 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [4.7.1](https://github.com/watson-developer-cloud/python-sdk/compare/v4.7.0...v4.7.1) (2020-09-03) + + +### Bug Fixes + +* lock the cloud sdk library version ([18d5997](https://github.com/watson-developer-cloud/python-sdk/commit/18d5997faa44af4e3c11b217f598dd4e3c75115c)) + # [4.7.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.6.0...v4.7.0) (2020-09-03) diff --git a/package-lock.json b/package-lock.json index 09aceeeb4..9de6f7980 100644 --- a/package-lock.json +++ b/package-lock.json @@ -104,9 +104,9 @@ } }, "@octokit/plugin-paginate-rest": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.3.1.tgz", - "integrity": "sha512-81A+ONLpcSX7vWxnEmVZteQPNsbdeScSVUqjgMYPSk1trzG69iYkhS42wPRWtN0nYw6OEmT48DNeQCjHeyroYw==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.3.2.tgz", + "integrity": "sha512-PjHbMhKryxClCrmfvRpGaKCTxUcHIf2zirWRV9SMGf0EmxD/rFew/abSqbMiLl9uQgRZvqtTyCRMGMlUv1ZsBg==", "requires": { "@octokit/types": "^5.3.0" } From 587a16da3137e19786f500c5c44d23b89ab29b15 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Fri, 30 Oct 2020 11:15:36 -0500 Subject: [PATCH 277/455] docs(readme): document how to set global transaction id --- README.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4f58b11d9..c44d0aa11 100755 --- a/README.md +++ b/README.md @@ -368,14 +368,15 @@ 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. +Every SDK call returns a response with a transaction ID in the `X-Global-Transaction-Id` header. Together the service instance region, this ID helps support teams troubleshoot issues from relevant logs. + ### Suceess ```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')) +print(response_headers.get('X-Global-Transaction-Id')) ``` ### Failure @@ -388,7 +389,16 @@ try: except ApiException as e: print(e.global_transaction_id) # OR - print(e.http_response.headers.get('x-global-transaction-id')) + print(e.http_response.headers.get('X-Global-Transaction-Id')) +``` + +However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace in the following example with a unique transaction ID. + +```python +from ibm_watson import MyService + +service = MyService(authenticator=my_authenticator) +service.my_service_call(headers={'X-Global-Transaction-Id': ''}) ``` ## Using Websockets From 74eb3aaf1bdffd056f8ca437f9d829d4cd743a01 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Fri, 30 Oct 2020 11:45:16 -0500 Subject: [PATCH 278/455] docs: add missing backticks --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c44d0aa11..ce25e54dd 100755 --- a/README.md +++ b/README.md @@ -392,7 +392,7 @@ except ApiException as e: print(e.http_response.headers.get('X-Global-Transaction-Id')) ``` -However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace in the following example with a unique transaction ID. +However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace `` in the following example with a unique transaction ID. ```python from ibm_watson import MyService From e64ac24aabe1110c23c85ce5628c8fa7a8db71d2 Mon Sep 17 00:00:00 2001 From: Jeffrey Stylos Date: Fri, 30 Oct 2020 14:28:05 -0400 Subject: [PATCH 279/455] Update README.md with latest Discovery date --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 4f58b11d9..944201e7a 100755 --- a/README.md +++ b/README.md @@ -124,7 +124,7 @@ The file downloaded will be called `ibm-credentials.env`. This is the name the S As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following: ```python -discovery = DiscoveryV1(version='2018-08-01') +discovery = DiscoveryV1(version='2019-04-30') ``` And that's it! @@ -175,7 +175,7 @@ from ibm_cloud_sdk_core.authenticators import IAMAuthenticator # In the constructor, letting the SDK manage the token authenticator = IAMAuthenticator('apikey', url='') # optional - the default value is https://iam.cloud.ibm.com/identity/token -discovery = DiscoveryV1(version='2018-08-01', +discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) discovery.set_service_url('') ``` @@ -196,7 +196,7 @@ from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator # in the constructor, assuming control of managing the token authenticator = BearerTokenAuthenticator('your bearer token') -discovery = DiscoveryV1(version='2018-08-01', +discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) discovery.set_service_url('') ``` @@ -207,7 +207,7 @@ from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators import BasicAuthenticator authenticator = BasicAuthenticator('username', 'password') -discovery = DiscoveryV1(version='2018-08-01', authenticator=authenticator) +discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) discovery.set_service_url('') ``` @@ -217,7 +217,7 @@ from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator authenticator = NoAuthAuthenticator() -discovery = DiscoveryV1(version='2018-08-01', authenticator=authenticator) +discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) discovery.set_service_url('') ``` From 5fbb7812f3298b2c55fac7a58c091cfe8c698db9 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Mon, 2 Nov 2020 14:58:36 -0600 Subject: [PATCH 280/455] docs: Add announcements section and PI deprecation --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 79f7de788..b3e314386 100755 --- a/README.md +++ b/README.md @@ -42,6 +42,12 @@ Python client library to quickly get started with the various [Watson APIs][wdc] +## ANNOUNCEMENTS! +### Personality Insights Deprecation +IBM® will begin sunsetting IBM Watson™ Personality Insights on 1 December 2020. For a period of one year from this date, you will still be able to use Watson Personality Insights. However, as of 1 December 2021, the offering will no longer be available. + +As an alternative, we encourage you to consider migrating to IBM Watson™ [Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-understanding), a service on IBM Cloud® that uses deep learning to extract data and insights from text such as keywords, categories, sentiment, emotion, and syntax to provide insights for your business or industry. For more information, see About Natural Language Understanding. + ## Before you begin * You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support `python 3.5` and above From 12ee072189d54a7b6462c82cb0e5d4d123822ea5 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 16 Nov 2020 09:45:12 -0500 Subject: [PATCH 281/455] feat(TextToSpeechV1): change voice model signaturess to custom models BREAKING CHANGE: This update breaks the users using any methods of type _voice_models --- examples/text_to_speech_v1.py | 14 +- ibm_watson/text_to_speech_v1.py | 773 ++++++++++----------- test/integration/test_text_to_speech_v1.py | 8 +- test/unit/test_text_to_speech_v1.py | 82 +-- 4 files changed, 429 insertions(+), 448 deletions(-) diff --git a/examples/text_to_speech_v1.py b/examples/text_to_speech_v1.py index 3f60b9cbf..22c28ec21 100644 --- a/examples/text_to_speech_v1.py +++ b/examples/text_to_speech_v1.py @@ -22,18 +22,18 @@ pronunciation = service.get_pronunciation('Watson', format='spr').get_result() print(json.dumps(pronunciation, indent=2)) -voice_models = service.list_voice_models().get_result() +voice_models = service.list_custom_models().get_result() print(json.dumps(voice_models, indent=2)) -# voice_model = service.create_voice_model('test-customization').get_result() -# print(json.dumps(voice_model, indent=2)) +# voice_model = service.create_custom_model('test-customization').get_result() +# print(json.dumps(custom_model, indent=2)) -# updated_voice_model = service.update_voice_model( +# updated_custom_model = service.update_custom_model( # 'YOUR CUSTOMIZATION ID', name='new name').get_result() -# print(updated_voice_model) +# print(updated_custom_model) -# voice_model = service.get_voice_model('YOUR CUSTOMIZATION ID').get_result() -# print(json.dumps(voice_model, indent=2)) +# custom_model = service.get_custom_model('YOUR CUSTOMIZATION ID').get_result() +# print(json.dumps(custom_model, indent=2)) # words = service.list_words('YOUR CUSTOMIZATIONID').get_result() # print(json.dumps(words, indent=2)) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 1fd76b89e..1be14651e 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -54,9 +54,9 @@ class TextToSpeechV1(BaseService): DEFAULT_SERVICE_NAME = 'text_to_speech' def __init__( - self, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Text to Speech service. @@ -118,16 +118,16 @@ def get_voice(self, Gets information about the specified voice. The information includes the name, language, gender, and other details about the voice. Specify a customization ID to - obtain information for a custom voice model that is defined for the language of - the specified voice. To list information about all available voices, use the - **List voices** method. + obtain information for a custom model that is defined for the language of 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/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 - custom voice model for which information is to be returned. You must make - the request with credentials for the instance of the service that owns the + custom model for which information is to be returned. You must make the + request with credentials for the instance of the service that owns the custom model. Omit the parameter to see information about the specified voice with no customization. :param dict headers: A `dict` containing the request headers @@ -237,11 +237,11 @@ def synthesize(self, see **Audio formats (accept types)** in the method description. :param str voice: (optional) The voice to use for synthesis. :param str customization_id: (optional) The customization ID (GUID) of a - custom voice model to use for the synthesis. If a custom voice model is - specified, it works only if it matches the language of the indicated voice. - You must make the request with credentials for the instance of the service - that owns the custom model. Omit the parameter to use the specified voice - with no customization. + custom model to use for the synthesis. If a custom model is specified, it + works only if it matches the language of the indicated voice. You must make + the request with credentials for the instance of the service that owns the + custom model. Omit the parameter to use the specified voice with no + customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -289,8 +289,7 @@ def get_pronunciation(self, Gets the phonetic pronunciation for the specified word. You can request the pronunciation for a specific format. You can also request the pronunciation for a specific voice to see the default translation for the language of that voice or - for a specific custom voice model to see the translation for that voice model. - **Note:** This method is currently a beta release. + for a specific custom model to see the translation for that model. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). @@ -303,13 +302,13 @@ def get_pronunciation(self, only IPA. Omit the parameter to obtain the pronunciation in the default format. :param str customization_id: (optional) The customization ID (GUID) of a - custom voice model for which the pronunciation is to be returned. The - language of a specified custom model must match the language of the - specified voice. If the word is not defined in the specified custom model, - the service returns the default translation for the custom model's - language. You must make the request with credentials for the instance of - the service that owns the custom model. Omit the parameter to see the - translation for the specified voice with no customization. + custom model for which the pronunciation is to be returned. The language of + a specified custom model must match the language of the specified voice. If + the word is not defined in the specified custom model, the service returns + the default translation for the custom model's language. You must make the + request with credentials for the instance of the service that owns the + custom model. Omit the parameter to see the translation for the specified + voice with no customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -346,31 +345,30 @@ def get_pronunciation(self, # Custom models ######################### - def create_voice_model(self, - name: str, - *, - language: str = None, - description: str = None, - **kwargs) -> 'DetailedResponse': + def create_custom_model(self, + name: str, + *, + language: str = None, + description: str = None, + **kwargs) -> 'DetailedResponse': """ Create a custom model. - Creates a new empty custom voice model. You must specify a name for the new custom + Creates a new empty custom model. You must specify a name for the new custom model. You can optionally specify the language and a description for the new model. The model is owned by the instance of the service whose credentials are used to create it. - **Note:** This method is currently a beta release. **See also:** [Creating a custom 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. - You create a custom voice model for a specific language, not for a specific - voice. A custom model can be used with any voice, standard or neural, for - its specified language. Omit the parameter to use the the default language, + :param str name: The name of the new custom model. + :param str language: (optional) The language of the new custom model. You + create a custom model for a specific language, not for a specific voice. A + custom model can be used with any voice, standard or neural, for its + specified language. Omit the parameter to use the the default language, `en-US`. - :param str description: (optional) A description of the new custom voice - model. Specifying a description is recommended. + :param str description: (optional) A description of the new custom model. + Specifying a description is recommended. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -384,7 +382,7 @@ def create_voice_model(self, headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='create_voice_model') + operation_id='create_custom_model') headers.update(sdk_headers) data = {'name': name, 'language': language, 'description': description} @@ -398,26 +396,25 @@ def create_voice_model(self, response = self.send(request) return response - def list_voice_models(self, - *, - language: str = None, - **kwargs) -> 'DetailedResponse': + def list_custom_models(self, + *, + language: str = None, + **kwargs) -> 'DetailedResponse': """ List custom models. - Lists metadata such as the name and description for all custom voice models that - are owned by an instance of the service. Specify a language to list the voice - models for that language only. To see the words in addition to the metadata for a - specific voice model, use the **List a custom model** method. You must use + Lists metadata such as the name and description for all custom models that are + owned by an instance of the service. Specify a language to list the custom models + for that language only. To see the words in addition to the metadata for a + specific custom model, use the **List a custom model** method. You must use credentials for the instance of the service that owns a model to list information about it. - **Note:** This method is currently a beta release. **See also:** [Querying all custom 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 - parameter to see all custom voice models that are owned by the requester. + :param str language: (optional) The language for which custom models that + are owned by the requesting credentials are to be returned. Omit the + parameter to see all custom models that are owned by the requester. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -428,7 +425,7 @@ def list_voice_models(self, headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='list_voice_models') + operation_id='list_custom_models') headers.update(sdk_headers) params = {'language': language} @@ -442,22 +439,22 @@ def list_voice_models(self, response = self.send(request) return response - def update_voice_model(self, - customization_id: str, - *, - name: str = None, - description: str = None, - words: List['Word'] = None, - **kwargs) -> 'DetailedResponse': + def update_custom_model(self, + customization_id: str, + *, + name: str = None, + description: str = None, + words: List['Word'] = None, + **kwargs) -> 'DetailedResponse': """ Update a custom model. - Updates information for the specified custom voice model. You can update metadata - such as the name and description of the voice model. You can also update the words - in the model and their translations. Adding a new translation for a word that - already exists in a custom model overwrites the word's existing translation. A - custom model can contain no more than 20,000 entries. You must use credentials for - the instance of the service that owns a model to update it. + Updates information for the specified custom model. You can update metadata such + as the name and description of the model. You can also update the words in the + model and their translations. Adding a new translation for a word that already + exists in a custom model overwrites the word's existing translation. A custom + model can contain no more than 20,000 entries. You must use credentials for the + instance of the service that owns a model to update it. You can define sounds-like or phonetic translations for words. A sounds-like translation consists of one or more words that, when combined, sound like the word. Phonetic translations are based on the SSML phoneme format for representing @@ -468,7 +465,6 @@ def update_voice_model(self, or in the proprietary IBM Symbolic Phonetic Representation (SPR) <phoneme alphabet="ibm" ph="1gAstroEntxrYFXs"></phoneme> - **Note:** This method is currently a beta release. **See also:** * [Updating a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsUpdate) @@ -478,15 +474,13 @@ def update_voice_model(self, 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 - the service that owns the custom model. - :param str name: (optional) A new name for the custom voice model. - :param str description: (optional) A new description for the custom voice - model. + model. You must make the request with credentials for the instance of the + service that owns the custom model. + :param str name: (optional) A new name for the custom model. + :param str description: (optional) A new description for the custom model. :param List[Word] words: (optional) An array of `Word` objects that provides the words and their translations that are to be added or updated - for the custom voice model. Pass an empty array to make no additions or - updates. + for the custom model. Pass an empty array to make no additions or updates. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -502,7 +496,7 @@ def update_voice_model(self, headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='update_voice_model') + operation_id='update_custom_model') headers.update(sdk_headers) data = {'name': name, 'description': description, 'words': words} @@ -517,22 +511,21 @@ def update_voice_model(self, response = self.send(request) return response - def get_voice_model(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + def get_custom_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Get a custom model. - Gets all information about a specified custom voice model. In addition to metadata - such as the name and description of the voice model, the output includes the words - and their translations as defined in the model. To see just the metadata for a - voice model, use the **List custom models** method. - **Note:** This method is currently a beta release. + Gets all information about a specified custom model. In addition to metadata such + as the name and description of the custom model, the output includes the words and + their translations as defined in the model. To see just the metadata for a model, + use the **List custom models** method. **See also:** [Querying a custom 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 - the service that owns the custom model. + model. You must make the request with credentials for the instance of the + service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -546,7 +539,7 @@ def get_voice_model(self, customization_id: str, headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='get_voice_model') + operation_id='get_custom_model') headers.update(sdk_headers) url = '/v1/customizations/{0}'.format( @@ -556,20 +549,19 @@ def get_voice_model(self, customization_id: str, response = self.send(request) return response - def delete_voice_model(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + def delete_custom_model(self, customization_id: str, + **kwargs) -> 'DetailedResponse': """ Delete a custom model. - Deletes the specified custom voice model. You must use credentials for the - instance of the service that owns a model to delete it. - **Note:** This method is currently a beta release. + Deletes the specified custom model. You must use credentials for the instance of + the service that owns a model to delete it. **See also:** [Deleting a custom 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 - the service that owns the custom model. + model. You must make the request with credentials for the instance of the + service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -583,7 +575,7 @@ def delete_voice_model(self, customization_id: str, headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='delete_voice_model') + operation_id='delete_custom_model') headers.update(sdk_headers) url = '/v1/customizations/{0}'.format( @@ -604,7 +596,7 @@ def add_words(self, customization_id: str, words: List['Word'], """ Add custom words. - Adds one or more words and their translations to the specified custom voice model. + Adds one or more words and their translations to the specified custom model. Adding a new translation for a word that already exists in a custom model overwrites the word's existing translation. A custom model can contain no more than 20,000 entries. You must use credentials for the instance of the service that @@ -619,7 +611,6 @@ def add_words(self, customization_id: str, words: List['Word'], or in the proprietary IBM Symbolic Phonetic Representation (SPR) <phoneme alphabet="ibm" ph="1gAstroEntxrYFXs"></phoneme> - **Note:** This method is currently a beta release. **See also:** * [Adding multiple words to a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsAdd) @@ -629,16 +620,16 @@ def add_words(self, customization_id: str, words: List['Word'], 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 - the service that owns the custom model. + model. You must make the request with credentials for the instance of the + service that owns the custom model. :param List[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or - updated for the custom voice model and the word's translation. + updated for the custom model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each - object shows a word and its translation from the custom voice model. The - words are listed in alphabetical order, with uppercase letters listed - before lowercase letters. The array is empty if the custom model contains - no words. + object shows a word and its translation from the custom model. The words + are listed in alphabetical order, with uppercase letters listed before + lowercase letters. The array is empty if the custom model contains no + words. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -674,17 +665,15 @@ def list_words(self, customization_id: str, **kwargs) -> 'DetailedResponse': """ List custom words. - Lists all of the words and their translations for the specified custom voice - model. The output shows the translations as they are defined in the model. You - must use credentials for the instance of the service that owns a model to list its - words. - **Note:** This method is currently a beta release. + Lists all of the words and their translations for the specified custom model. The + output shows the translations as they are defined in the model. You must use + credentials for the instance of the service that owns a model to list its words. **See also:** [Querying all words from a custom 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 - the service that owns the custom model. + model. You must make the request with credentials for the instance of the + service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -718,11 +707,11 @@ def add_word(self, """ Add a custom word. - Adds a single word and its translation to the specified custom voice model. Adding - a new translation for a word that already exists in a custom model overwrites the - word's existing translation. A custom model can contain no more than 20,000 - entries. You must use credentials for the instance of the service that owns a - model to add a word to it. + Adds a single word and its translation to the specified custom model. Adding a new + translation for a word that already exists in a custom model overwrites the word's + existing translation. A custom model can contain no more than 20,000 entries. You + must use credentials for the instance of the service that owns a model to add a + word to it. You can define sounds-like or phonetic translations for words. A sounds-like translation consists of one or more words that, when combined, sound like the word. Phonetic translations are based on the SSML phoneme format for representing @@ -733,7 +722,6 @@ def add_word(self, or in the proprietary IBM Symbolic Phonetic Representation (SPR) <phoneme alphabet="ibm" ph="1gAstroEntxrYFXs"></phoneme> - **Note:** This method is currently a beta release. **See also:** * [Adding a single word to a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordAdd) @@ -743,10 +731,10 @@ def add_word(self, 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 - the service that owns the custom model. + model. You must make the request with credentials for the instance of the + service that owns the custom model. :param str word: The word that is to be added or updated for the custom - voice model. + model. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR @@ -800,15 +788,13 @@ def get_word(self, customization_id: str, word: str, Gets the translation for a single word from the specified custom model. The output shows the translation as it is defined in the model. You must use credentials for 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/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 - the service that owns the custom model. - :param str word: The word that is to be queried from the custom voice - model. + model. You must make the request with credentials for the instance of the + service that owns the custom model. + :param str word: The word that is to be queried from the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -839,17 +825,15 @@ def delete_word(self, customization_id: str, word: str, """ Delete a custom word. - Deletes a single word from the specified custom voice model. You must use - credentials for the instance of the service that owns a model to delete its words. - **Note:** This method is currently a beta release. + Deletes a single word from the specified custom model. 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 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 - the service that owns the custom model. - :param str word: The word that is to be deleted from the custom voice - model. + model. You must make the request with credentials for the instance of the + service that owns the custom model. + :param str word: The word that is to be deleted from the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -895,7 +879,7 @@ def delete_user_data(self, customer_id: str, request that passes the data. **Note:** If you delete an instance of the service from the service console, all data associated with that service instance is automatically deleted. This includes - all custom voice models and word/translation pairs, and all data related to speech + all custom models and word/translation pairs, and all data related to speech synthesis requests. **See also:** [Information security](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-information-security#information-security). @@ -1118,13 +1102,13 @@ class Format(Enum): IPA = 'ipa' -class ListVoiceModelsEnums(object): +class ListCustomModelsEnums(object): class Language(Enum): """ - The language for which custom voice models that are owned by the requesting - credentials are to be returned. Omit the parameter to see all custom voice models - that are owned by the requester. + The language for which custom models that are owned by the requesting credentials + are to be returned. Omit the parameter to see all custom models that are owned by + the requester. """ AR_AR = 'ar-AR' DE_DE = 'de-DE' @@ -1147,13 +1131,243 @@ class Language(Enum): ############################################################################## +class CustomModel(): + """ + Information about an existing custom model. + + :attr str customization_id: The customization ID (GUID) of the custom model. The + **Create a custom model** method returns only this field. It does not not return + the other fields of this object. + :attr str name: (optional) The name of the custom model. + :attr str language: (optional) The language identifier of the custom model (for + example, `en-US`). + :attr str owner: (optional) The GUID of the credentials for the instance of the + service that owns the custom model. + :attr str created: (optional) The date and time in Coordinated Universal Time + (UTC) at which the custom model was created. The value is provided in full ISO + 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). + :attr str last_modified: (optional) The date and time in Coordinated Universal + Time (UTC) at which the custom model was last modified. The `created` and + `updated` fields are equal when a model is first added but has yet to be + updated. The value is provided in full ISO 8601 format + (`YYYY-MM-DDThh:mm:ss.sTZD`). + :attr str description: (optional) The description of the custom model. + :attr List[Word] words: (optional) An array of `Word` objects that lists the + words and their translations from the custom model. The words are listed in + alphabetical order, with uppercase letters listed before lowercase letters. The + array is empty if the custom model contains no words. This field is returned + only by the **Get a voice** method and only when you specify the customization + ID of a custom model. + """ + + def __init__(self, + customization_id: str, + *, + name: str = None, + language: str = None, + owner: str = None, + created: str = None, + last_modified: str = None, + description: str = None, + words: List['Word'] = None) -> None: + """ + Initialize a CustomModel object. + + :param str customization_id: The customization ID (GUID) of the custom + model. The **Create a custom model** method returns only this field. It + does not not return the other fields of this object. + :param str name: (optional) The name of the custom model. + :param str language: (optional) The language identifier of the custom model + (for example, `en-US`). + :param str owner: (optional) The GUID of the credentials for the instance + of the service that owns the custom model. + :param str created: (optional) The date and time in Coordinated Universal + Time (UTC) at which the custom model was created. The value is provided in + full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). + :param str last_modified: (optional) The date and time in Coordinated + Universal Time (UTC) at which the custom model was last modified. The + `created` and `updated` fields are equal when a model is first added but + has yet to be updated. The value is provided in full ISO 8601 format + (`YYYY-MM-DDThh:mm:ss.sTZD`). + :param str description: (optional) The description of the custom model. + :param List[Word] words: (optional) An array of `Word` objects that lists + the words and their translations from the custom model. The words are + listed in alphabetical order, with uppercase letters listed before + lowercase letters. The array is empty if the custom model contains no + words. This field is returned only by the **Get a voice** method and only + when you specify the customization ID of a custom model. + """ + self.customization_id = customization_id + self.name = name + self.language = language + self.owner = owner + self.created = created + self.last_modified = last_modified + self.description = description + self.words = words + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CustomModel': + """Initialize a CustomModel object from a json dictionary.""" + args = {} + valid_keys = [ + 'customization_id', 'name', 'language', 'owner', 'created', + 'last_modified', 'description', 'words' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class CustomModel: ' + + ', '.join(bad_keys)) + if 'customization_id' in _dict: + args['customization_id'] = _dict.get('customization_id') + else: + raise ValueError( + 'Required property \'customization_id\' not present in CustomModel JSON' + ) + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'language' in _dict: + args['language'] = _dict.get('language') + if 'owner' in _dict: + args['owner'] = _dict.get('owner') + if 'created' in _dict: + args['created'] = _dict.get('created') + if 'last_modified' in _dict: + args['last_modified'] = _dict.get('last_modified') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'words' in _dict: + args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CustomModel 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, + 'customization_id') and self.customization_id is not None: + _dict['customization_id'] = self.customization_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'owner') and self.owner is not None: + _dict['owner'] = self.owner + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = self.created + if hasattr(self, 'last_modified') and self.last_modified is not None: + _dict['last_modified'] = self.last_modified + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'words') and self.words is not None: + _dict['words'] = [x._to_dict() for x in self.words] + 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 CustomModel object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'CustomModel') -> 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: 'CustomModel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CustomModels(): + """ + Information about existing custom models. + + :attr List[CustomModel] customizations: An array of `CustomModel` objects that + provides information about each available custom model. The array is empty if + the requesting credentials own no custom models (if no language is specified) or + own no custom models for the specified language. + """ + + def __init__(self, customizations: List['CustomModel']) -> None: + """ + Initialize a CustomModels object. + + :param List[CustomModel] customizations: An array of `CustomModel` objects + that provides information about each available custom model. The array is + empty if the requesting credentials own no custom models (if no language is + specified) or own no custom models for the specified language. + """ + self.customizations = customizations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CustomModels': + """Initialize a CustomModels object from a json dictionary.""" + args = {} + valid_keys = ['customizations'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class CustomModels: ' + + ', '.join(bad_keys)) + if 'customizations' in _dict: + args['customizations'] = [ + CustomModel._from_dict(x) for x in (_dict.get('customizations')) + ] + else: + raise ValueError( + 'Required property \'customizations\' not present in CustomModels JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CustomModels 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, 'customizations') and self.customizations is not None: + _dict['customizations'] = [ + x._to_dict() for x in self.customizations + ] + 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 CustomModels object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'CustomModels') -> 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: 'CustomModels') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Pronunciation(): """ The pronunciation of the specified text. :attr str pronunciation: The pronunciation of the specified text in the - requested voice and format. If a custom voice model is specified, the - pronunciation also reflects that custom voice. + requested voice and format. If a custom model is specified, the pronunciation + also reflects that custom model. """ def __init__(self, pronunciation: str) -> None: @@ -1161,8 +1375,8 @@ def __init__(self, pronunciation: str) -> None: Initialize a Pronunciation object. :param str pronunciation: The pronunciation of the specified text in the - requested voice and format. If a custom voice model is specified, the - pronunciation also reflects that custom voice. + requested voice and format. If a custom model is specified, the + pronunciation also reflects that custom model. """ self.pronunciation = pronunciation @@ -1419,7 +1633,7 @@ class PartOfSpeechEnum(Enum): class Voice(): """ - Information about an available voice model. + Information about an available voice. :attr str url: The URI of the voice. :attr str gender: The gender of the voice: `male` or `female`. @@ -1432,9 +1646,9 @@ class Voice(): backward compatibility.). :attr SupportedFeatures supported_features: Additional service features that are supported with the voice. - :attr VoiceModel customization: (optional) Returns information about a specified - custom voice model. This field is returned only by the **Get a voice** method - and only when you specify the customization ID of a custom voice model. + :attr CustomModel customization: (optional) Returns information about a + specified custom model. This field is returned only by the **Get a voice** + method and only when you specify the customization ID of a custom model. """ def __init__(self, @@ -1446,7 +1660,7 @@ def __init__(self, customizable: bool, supported_features: 'SupportedFeatures', *, - customization: 'VoiceModel' = None) -> None: + customization: 'CustomModel' = None) -> None: """ Initialize a Voice object. @@ -1462,10 +1676,9 @@ def __init__(self, maintained for backward compatibility.). :param SupportedFeatures supported_features: Additional service features that are supported with the voice. - :param VoiceModel customization: (optional) Returns information about a - specified custom voice model. This field is returned only by the **Get a - voice** method and only when you specify the customization ID of a custom - voice model. + :param CustomModel customization: (optional) Returns information about a + specified custom model. This field is returned only by the **Get a voice** + method and only when you specify the customization ID of a custom model. """ self.url = url self.gender = gender @@ -1527,7 +1740,7 @@ def from_dict(cls, _dict: Dict) -> 'Voice': 'Required property \'supported_features\' not present in Voice JSON' ) if 'customization' in _dict: - args['customization'] = VoiceModel._from_dict( + args['customization'] = CustomModel._from_dict( _dict.get('customization')) return cls(**args) @@ -1578,241 +1791,9 @@ def __ne__(self, other: 'Voice') -> bool: return not self == other -class VoiceModel(): - """ - Information about an existing custom voice model. - - :attr str customization_id: The customization ID (GUID) of the custom voice - model. The **Create a custom model** method returns only this field. It does not - not return the other fields of this object. - :attr str name: (optional) The name of the custom voice model. - :attr str language: (optional) The language identifier of the custom voice model - (for example, `en-US`). - :attr str owner: (optional) The GUID of the credentials for the instance of the - service that owns the custom voice model. - :attr str created: (optional) The date and time in Coordinated Universal Time - (UTC) at which the custom voice model was created. The value is provided in full - ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str last_modified: (optional) The date and time in Coordinated Universal - Time (UTC) at which the custom voice model was last modified. The `created` and - `updated` fields are equal when a voice model is first added but has yet to be - updated. The value is provided in full ISO 8601 format - (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str description: (optional) The description of the custom voice model. - :attr List[Word] words: (optional) An array of `Word` objects that lists the - words and their translations from the custom voice model. The words are listed - in alphabetical order, with uppercase letters listed before lowercase letters. - The array is empty if the custom model contains no words. This field is returned - only by the **Get a voice** method and only when you specify the customization - ID of a custom voice model. - """ - - def __init__(self, - customization_id: str, - *, - name: str = None, - language: str = None, - owner: str = None, - created: str = None, - last_modified: str = None, - description: str = None, - words: List['Word'] = None) -> None: - """ - Initialize a VoiceModel object. - - :param str customization_id: The customization ID (GUID) of the custom - voice model. The **Create a custom model** method returns only this field. - It does not not return the other fields of this object. - :param str name: (optional) The name of the custom voice model. - :param str language: (optional) The language identifier of the custom voice - model (for example, `en-US`). - :param str owner: (optional) The GUID of the credentials for the instance - of the service that owns the custom voice model. - :param str created: (optional) The date and time in Coordinated Universal - Time (UTC) at which the custom voice model was created. The value is - provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :param str last_modified: (optional) The date and time in Coordinated - Universal Time (UTC) at which the custom voice model was last modified. The - `created` and `updated` fields are equal when a voice model is first added - but has yet to be updated. The value is provided in full ISO 8601 format - (`YYYY-MM-DDThh:mm:ss.sTZD`). - :param str description: (optional) The description of the custom voice - model. - :param List[Word] words: (optional) An array of `Word` objects that lists - the words and their translations from the custom voice model. The words are - listed in alphabetical order, with uppercase letters listed before - lowercase letters. The array is empty if the custom model contains no - words. This field is returned only by the **Get a voice** method and only - when you specify the customization ID of a custom voice model. - """ - self.customization_id = customization_id - self.name = name - self.language = language - self.owner = owner - self.created = created - self.last_modified = last_modified - self.description = description - self.words = words - - @classmethod - def from_dict(cls, _dict: Dict) -> 'VoiceModel': - """Initialize a VoiceModel object from a json dictionary.""" - args = {} - valid_keys = [ - 'customization_id', 'name', 'language', 'owner', 'created', - 'last_modified', 'description', 'words' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class VoiceModel: ' - + ', '.join(bad_keys)) - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') - else: - raise ValueError( - 'Required property \'customization_id\' not present in VoiceModel JSON' - ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'created' in _dict: - args['created'] = _dict.get('created') - if 'last_modified' in _dict: - args['last_modified'] = _dict.get('last_modified') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'words' in _dict: - args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a VoiceModel 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, - 'customization_id') and self.customization_id is not None: - _dict['customization_id'] = self.customization_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'owner') and self.owner is not None: - _dict['owner'] = self.owner - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = self.created - if hasattr(self, 'last_modified') and self.last_modified is not None: - _dict['last_modified'] = self.last_modified - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x._to_dict() for x in self.words] - 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 VoiceModel object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other: 'VoiceModel') -> 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: 'VoiceModel') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class VoiceModels(): - """ - Information about existing custom voice models. - - :attr List[VoiceModel] customizations: An array of `VoiceModel` objects that - provides information about each available custom voice model. The array is empty - if the requesting credentials own no custom voice models (if no language is - specified) or own no custom voice models for the specified language. - """ - - def __init__(self, customizations: List['VoiceModel']) -> None: - """ - Initialize a VoiceModels object. - - :param List[VoiceModel] customizations: An array of `VoiceModel` objects - that provides information about each available custom voice model. The - array is empty if the requesting credentials own no custom voice models (if - no language is specified) or own no custom voice models for the specified - language. - """ - self.customizations = customizations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'VoiceModels': - """Initialize a VoiceModels object from a json dictionary.""" - args = {} - valid_keys = ['customizations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class VoiceModels: ' - + ', '.join(bad_keys)) - if 'customizations' in _dict: - args['customizations'] = [ - VoiceModel._from_dict(x) for x in (_dict.get('customizations')) - ] - else: - raise ValueError( - 'Required property \'customizations\' not present in VoiceModels JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a VoiceModels 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, 'customizations') and self.customizations is not None: - _dict['customizations'] = [ - x._to_dict() for x in self.customizations - ] - 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 VoiceModels object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other: 'VoiceModels') -> 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: 'VoiceModels') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class Voices(): """ - Information about all available voice models. + Information about all available voices. :attr List[Voice] voices: A list of available voices. """ @@ -1877,10 +1858,10 @@ def __ne__(self, other: 'Voices') -> bool: class Word(): """ - Information about a word for the custom voice model. + Information about a word for the custom model. - :attr str word: The word for the custom voice model. The maximum length of a - word is 49 characters. + :attr str word: The word for the custom model. The maximum length of a word is + 49 characters. :attr str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. The Arabic, Chinese, @@ -1903,8 +1884,8 @@ def __init__(self, """ Initialize a Word object. - :param str word: The word for the custom voice model. The maximum length of - a word is 49 characters. + :param str word: The word for the custom model. The maximum length of a + word is 49 characters. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. The @@ -2012,17 +1993,17 @@ class PartOfSpeechEnum(Enum): class Words(): """ For the **Add custom words** method, one or more words that are to be added or updated - for the custom voice model and the translation for each specified word. + for the custom model and the translation for each specified word. For the **List custom words** method, the words and their translations from the custom - voice model. + model. :attr List[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for - the custom voice model and the word's translation. + the custom model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each object - shows a word and its translation from the custom voice model. The words are - listed in alphabetical order, with uppercase letters listed before lowercase - letters. The array is empty if the custom model contains no words. + shows a word and its translation from the custom model. The words are listed in + alphabetical order, with uppercase letters listed before lowercase letters. The + array is empty if the custom model contains no words. """ def __init__(self, words: List['Word']) -> None: @@ -2031,12 +2012,12 @@ def __init__(self, words: List['Word']) -> None: :param List[Word] words: The **Add custom words** method accepts an array of `Word` objects. Each object provides a word that is to be added or - updated for the custom voice model and the word's translation. + updated for the custom model and the word's translation. The **List custom words** method returns an array of `Word` objects. Each - object shows a word and its translation from the custom voice model. The - words are listed in alphabetical order, with uppercase letters listed - before lowercase letters. The array is empty if the custom model contains - no words. + object shows a word and its translation from the custom model. The words + are listed in alphabetical order, with uppercase letters listed before + lowercase letters. The array is empty if the custom model contains no + words. """ self.words = words diff --git a/test/integration/test_text_to_speech_v1.py b/test/integration/test_text_to_speech_v1.py index 6a2a99cc3..80498a08e 100644 --- a/test/integration/test_text_to_speech_v1.py +++ b/test/integration/test_text_to_speech_v1.py @@ -20,16 +20,16 @@ def setup_class(cls): 'X-Watson-Learning-Opt-Out': '1', 'X-Watson-Test': '1' }) - cls.original_customizations = cls.text_to_speech.list_voice_models( + cls.original_customizations = cls.text_to_speech.list_custom_models( ).get_result() - cls.created_customization = cls.text_to_speech.create_voice_model( + cls.created_customization = cls.text_to_speech.create_custom_model( name="test_integration_customization", description="customization for tests").get_result() @classmethod def teardown_class(cls): custid = cls.created_customization.get('customization_id') - cls.text_to_speech.delete_voice_model(customization_id=custid) + cls.text_to_speech.delete_custom_model(customization_id=custid) def test_voices(self): output = self.text_to_speech.list_voices().get_result() @@ -51,7 +51,7 @@ 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() + new_length = len(self.text_to_speech.list_custom_models().get_result() ['customizations']) assert new_length - old_length >= 1 diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 31b2f739e..27585b063 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -339,17 +339,17 @@ def construct_required_body(self): # region #----------------------------------------------------------------------------- -# Test Class for create_voice_model +# Test Class for create_custom_model #----------------------------------------------------------------------------- -class TestCreateVoiceModel(): +class TestCreateCustomModel(): #-------------------------------------------------------- # Test 1: Send fake data and check response #-------------------------------------------------------- @responses.activate - def test_create_voice_model_response(self): + def test_create_custom_model_response(self): body = self.construct_full_body() - response = fake_response_VoiceModel_json + response = fake_response_CustomModel_json send_request(self, body, response) assert len(responses.calls) == 1 @@ -357,10 +357,10 @@ def test_create_voice_model_response(self): # Test 2: Send only required fake data and check response #-------------------------------------------------------- @responses.activate - def test_create_voice_model_required_response(self): + def test_create_custom_model_required_response(self): # Check response with required params body = self.construct_required_body() - response = fake_response_VoiceModel_json + response = fake_response_CustomModel_json send_request(self, body, response) assert len(responses.calls) == 1 @@ -368,8 +368,8 @@ def test_create_voice_model_required_response(self): # Test 3: Send empty data and check response #-------------------------------------------------------- @responses.activate - def test_create_voice_model_empty(self): - check_empty_required_params(self, fake_response_VoiceModel_json) + def test_create_custom_model_empty(self): + check_empty_required_params(self, fake_response_CustomModel_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -393,7 +393,7 @@ def call_service(self, body): authenticator=NoAuthAuthenticator(), ) service.set_service_url(base_url) - output = service.create_voice_model(**body) + output = service.create_custom_model(**body) return output def construct_full_body(self): @@ -408,17 +408,17 @@ def construct_required_body(self): #----------------------------------------------------------------------------- -# Test Class for list_voice_models +# Test Class for list_custom_models #----------------------------------------------------------------------------- -class TestListVoiceModels(): +class TestListCustomModels(): #-------------------------------------------------------- # Test 1: Send fake data and check response #-------------------------------------------------------- @responses.activate - def test_list_voice_models_response(self): + def test_list_custom_models_response(self): body = self.construct_full_body() - response = fake_response_VoiceModels_json + response = fake_response_CustomModels_json send_request(self, body, response) assert len(responses.calls) == 1 @@ -426,10 +426,10 @@ def test_list_voice_models_response(self): # Test 2: Send only required fake data and check response #-------------------------------------------------------- @responses.activate - def test_list_voice_models_required_response(self): + def test_list_custom_models_required_response(self): # Check response with required params body = self.construct_required_body() - response = fake_response_VoiceModels_json + response = fake_response_CustomModels_json send_request(self, body, response) assert len(responses.calls) == 1 @@ -437,7 +437,7 @@ def test_list_voice_models_required_response(self): # Test 3: Send empty data and check response #-------------------------------------------------------- @responses.activate - def test_list_voice_models_empty(self): + def test_list_custom_models_empty(self): check_empty_response(self) assert len(responses.calls) == 1 @@ -461,7 +461,7 @@ def call_service(self, body): authenticator=NoAuthAuthenticator(), ) service.set_service_url(base_url) - output = service.list_voice_models(**body) + output = service.list_custom_models(**body) return output def construct_full_body(self): @@ -475,15 +475,15 @@ def construct_required_body(self): #----------------------------------------------------------------------------- -# Test Class for update_voice_model +# Test Class for update_custom_model #----------------------------------------------------------------------------- -class TestUpdateVoiceModel(): +class TestUpdateCustomModel(): #-------------------------------------------------------- # Test 1: Send fake data and check response #-------------------------------------------------------- @responses.activate - def test_update_voice_model_response(self): + def test_update_custom_model_response(self): body = self.construct_full_body() response = fake_response__json send_request(self, body, response) @@ -493,7 +493,7 @@ def test_update_voice_model_response(self): # Test 2: Send only required fake data and check response #-------------------------------------------------------- @responses.activate - def test_update_voice_model_required_response(self): + def test_update_custom_model_required_response(self): # Check response with required params body = self.construct_required_body() response = fake_response__json @@ -504,7 +504,7 @@ def test_update_voice_model_required_response(self): # Test 3: Send empty data and check response #-------------------------------------------------------- @responses.activate - def test_update_voice_model_empty(self): + def test_update_custom_model_empty(self): check_empty_required_params(self, fake_response__json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -529,7 +529,7 @@ def call_service(self, body): authenticator=NoAuthAuthenticator(), ) service.set_service_url(base_url) - output = service.update_voice_model(**body) + output = service.update_custom_model(**body) return output def construct_full_body(self): @@ -546,17 +546,17 @@ def construct_required_body(self): #----------------------------------------------------------------------------- -# Test Class for get_voice_model +# Test Class for get_custom_model #----------------------------------------------------------------------------- -class TestGetVoiceModel(): +class TestGetCustomModel(): #-------------------------------------------------------- # Test 1: Send fake data and check response #-------------------------------------------------------- @responses.activate - def test_get_voice_model_response(self): + def test_get_custom_model_response(self): body = self.construct_full_body() - response = fake_response_VoiceModel_json + response = fake_response_CustomModel_json send_request(self, body, response) assert len(responses.calls) == 1 @@ -564,10 +564,10 @@ def test_get_voice_model_response(self): # Test 2: Send only required fake data and check response #-------------------------------------------------------- @responses.activate - def test_get_voice_model_required_response(self): + def test_get_custom_model_required_response(self): # Check response with required params body = self.construct_required_body() - response = fake_response_VoiceModel_json + response = fake_response_CustomModel_json send_request(self, body, response) assert len(responses.calls) == 1 @@ -575,8 +575,8 @@ def test_get_voice_model_required_response(self): # Test 3: Send empty data and check response #-------------------------------------------------------- @responses.activate - def test_get_voice_model_empty(self): - check_empty_required_params(self, fake_response_VoiceModel_json) + def test_get_custom_model_empty(self): + check_empty_required_params(self, fake_response_CustomModel_json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -600,7 +600,7 @@ def call_service(self, body): authenticator=NoAuthAuthenticator(), ) service.set_service_url(base_url) - output = service.get_voice_model(**body) + output = service.get_custom_model(**body) return output def construct_full_body(self): @@ -615,15 +615,15 @@ def construct_required_body(self): #----------------------------------------------------------------------------- -# Test Class for delete_voice_model +# Test Class for delete_custom_model #----------------------------------------------------------------------------- -class TestDeleteVoiceModel(): +class TestDeleteCustomModel(): #-------------------------------------------------------- # Test 1: Send fake data and check response #-------------------------------------------------------- @responses.activate - def test_delete_voice_model_response(self): + def test_delete_custom_model_response(self): body = self.construct_full_body() response = fake_response__json send_request(self, body, response) @@ -633,7 +633,7 @@ def test_delete_voice_model_response(self): # Test 2: Send only required fake data and check response #-------------------------------------------------------- @responses.activate - def test_delete_voice_model_required_response(self): + def test_delete_custom_model_required_response(self): # Check response with required params body = self.construct_required_body() response = fake_response__json @@ -644,7 +644,7 @@ def test_delete_voice_model_required_response(self): # Test 3: Send empty data and check response #-------------------------------------------------------- @responses.activate - def test_delete_voice_model_empty(self): + def test_delete_custom_model_empty(self): check_empty_required_params(self, fake_response__json) check_missing_required_params(self) assert len(responses.calls) == 0 @@ -669,7 +669,7 @@ def call_service(self, body): authenticator=NoAuthAuthenticator(), ) service.set_service_url(base_url) - output = service.delete_voice_model(**body) + output = service.delete_custom_model(**body) return output def construct_full_body(self): @@ -1201,8 +1201,8 @@ def send_request(obj, body, response, url=None): fake_response_Voice_json = """{"url": "fake_url", "gender": "fake_gender", "name": "fake_name", "language": "fake_language", "description": "fake_description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}}""" fake_response_BinaryIO_json = """Contents of response byte-stream...""" fake_response_Pronunciation_json = """{"pronunciation": "fake_pronunciation"}""" -fake_response_VoiceModel_json = """{"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}""" -fake_response_VoiceModels_json = """{"customizations": []}""" -fake_response_VoiceModel_json = """{"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}""" +fake_response_CustomModel_json = """{"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}""" +fake_response_CustomModels_json = """{"customizations": []}""" +fake_response_CustomModel_json = """{"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}""" fake_response_Words_json = """{"words": []}""" fake_response_Translation_json = """{"translation": "fake_translation", "part_of_speech": "fake_part_of_speech"}""" From 59e7dede81f530ea027b480fd007f9df67180ab1 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 16 Nov 2020 10:27:28 -0500 Subject: [PATCH 282/455] feat: regenerate services using latest api def and generator --- ibm_watson/discovery_v1.py | 8 +-- ibm_watson/natural_language_classifier_v1.py | 6 +- ibm_watson/personality_insights_v3.py | 22 ++++++-- ibm_watson/speech_to_text_v1.py | 59 ++++++++++++-------- ibm_watson/tone_analyzer_v3.py | 8 +-- ibm_watson/visual_recognition_v3.py | 8 +-- 6 files changed, 68 insertions(+), 43 deletions(-) diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 7894a3c55..8511b5856 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -49,10 +49,10 @@ class DiscoveryV1(BaseService): DEFAULT_SERVICE_NAME = 'discovery' def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Discovery service. diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 77c43d7f7..6417b9571 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -45,9 +45,9 @@ class NaturalLanguageClassifierV1(BaseService): DEFAULT_SERVICE_NAME = 'natural_language_classifier' def __init__( - self, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Natural Language Classifier service. diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index d964df64b..abba73225 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -14,8 +14,18 @@ # See the License for the specific language governing permissions and # limitations under the License. """ -The IBM Watson™ Personality Insights service enables applications to derive insights -from social media, enterprise data, or other digital communications. The service uses +IBM® will begin sunsetting IBM Watson™ Personality Insights on 1 December 2020. +For a period of one year from this date, you will still be able to use Watson Personality +Insights. However, as of 1 December 2021, the offering will no longer be +available.

As an alternative, we encourage you to consider migrating to IBM +Watson™ Natural Language Understanding, a service on IBM Cloud® that uses deep +learning to extract data and insights from text such as keywords, categories, sentiment, +emotion, and syntax to provide insights for your business or industry. For more +information, see [About Natural Language +Understanding](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-about). +{: deprecated} +The IBM Watson Personality Insights service enables applications to derive insights from +social media, enterprise data, or other digital communications. The service uses linguistic analytics to infer individuals' intrinsic personality characteristics, including Big Five, Needs, and Values, from digital communications such as email, text messages, tweets, and forum posts. @@ -55,10 +65,10 @@ class PersonalityInsightsV3(BaseService): DEFAULT_SERVICE_NAME = 'personality_insights' def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Personality Insights service. diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index f1cabb45a..39da8b2d6 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -57,9 +57,9 @@ class SpeechToTextV1(BaseService): DEFAULT_SERVICE_NAME = 'speech_to_text' def __init__( - self, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Speech to Text service. @@ -1276,9 +1276,10 @@ def list_language_models(self, :param str language: (optional) The identifier of the language for which custom language or custom acoustic models are to be returned. Omit the parameter to see all custom language or custom acoustic models that are - owned by the requesting credentials. **Note:** The `ar-AR` (Modern Standard - Arabic) and `zh-CN` (Mandarin Chinese) languages are not available for - language model customization. + owned by the requesting credentials. + To determine the languages for which customization is available, see + [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2541,9 +2542,10 @@ def list_acoustic_models(self, :param str language: (optional) The identifier of the language for which custom language or custom acoustic models are to be returned. Omit the parameter to see all custom language or custom acoustic models that are - owned by the requesting credentials. **Note:** The `ar-AR` (Modern Standard - Arabic) and `zh-CN` (Mandarin Chinese) languages are not available for - language model customization. + owned by the requesting credentials. + To determine the languages for which customization is available, see + [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2660,13 +2662,14 @@ def train_acoustic_model(self, data. The custom acoustic model does not reflect its changed data until you train it. You must use credentials for the instance of the service that owns a model to train it. - The training method is asynchronous. It can take on the order of minutes or hours - to complete depending on the total amount of audio data on which the custom - acoustic model is being trained and the current load on the service. Typically, - training a custom acoustic model takes approximately two to four times the length - of its audio data. The actual time depends on the model being trained and the - nature of the audio, such as whether the audio is clean or noisy. The method - returns an HTTP 200 response code to indicate that the training process has begun. + The training method is asynchronous. Training time depends on the cumulative + amount of audio data that the custom acoustic model contains and the current load + on the service. When you train or retrain a model, the service uses all of the + model's audio data in the training. Training a custom acoustic model takes + approximately as long as the length of its cumulative audio data. For example, it + takes approximately 2 hours to train a model that contains a total of 2 hours of + audio. The method returns an HTTP 200 response code to indicate that the training + process has begun. You can monitor the status of the training by using the **Get a custom acoustic model** method to poll the model's status. Use a loop to check the status once a minute. The method returns an `AcousticModel` object that includes `status` and @@ -3283,6 +3286,8 @@ class ModelId(Enum): ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' @@ -3351,6 +3356,8 @@ class Model(Enum): ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' @@ -3419,6 +3426,8 @@ class Model(Enum): ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' @@ -3466,12 +3475,14 @@ class Language(Enum): """ The identifier of the language for which custom language or custom acoustic models are to be returned. Omit the parameter to see all custom language or custom - acoustic models that are owned by the requesting credentials. **Note:** The - `ar-AR` (Modern Standard Arabic) and `zh-CN` (Mandarin Chinese) languages are not - available for language model customization. + acoustic models that are owned by the requesting credentials. + To determine the languages for which customization is available, see [Language + support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). """ AR_AR = 'ar-AR' DE_DE = 'de-DE' + EN_AU = 'en-AU' EN_GB = 'en-GB' EN_US = 'en-US' ES_AR = 'es-AR' @@ -3480,6 +3491,7 @@ class Language(Enum): ES_CO = 'es-CO' ES_MX = 'es-MX' ES_PE = 'es-PE' + FR_CA = 'fr-CA' FR_FR = 'fr-FR' IT_IT = 'it-IT' JA_JP = 'ja-JP' @@ -3555,12 +3567,14 @@ class Language(Enum): """ The identifier of the language for which custom language or custom acoustic models are to be returned. Omit the parameter to see all custom language or custom - acoustic models that are owned by the requesting credentials. **Note:** The - `ar-AR` (Modern Standard Arabic) and `zh-CN` (Mandarin Chinese) languages are not - available for language model customization. + acoustic models that are owned by the requesting credentials. + To determine the languages for which customization is available, see [Language + support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). """ AR_AR = 'ar-AR' DE_DE = 'de-DE' + EN_AU = 'en-AU' EN_GB = 'en-GB' EN_US = 'en-US' ES_AR = 'es-AR' @@ -3569,6 +3583,7 @@ class Language(Enum): ES_CO = 'es-CO' ES_MX = 'es-MX' ES_PE = 'es-PE' + FR_CA = 'fr-CA' FR_FR = 'fr-FR' IT_IT = 'it-IT' JA_JP = 'ja-JP' diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index d9fd44f14..2753a87bd 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -47,10 +47,10 @@ class ToneAnalyzerV3(BaseService): DEFAULT_SERVICE_NAME = 'tone_analyzer' def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Tone Analyzer service. diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 47e97fafb..e88faa4e9 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -45,10 +45,10 @@ class VisualRecognitionV3(BaseService): DEFAULT_SERVICE_NAME = 'visual_recognition' def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Visual Recognition service. From 5af17b7557b2bd3f178c17b7ba7de907c0a3045e Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 16 Nov 2020 13:09:52 -0500 Subject: [PATCH 283/455] feat(CompareComply): remove before and after from list feedback BREAKING CHANGE: remove before and after from list feedback --- ibm_watson/compare_comply_v1.py | 113 ++++++++++++---------------- test/unit/test_compare_comply_v1.py | 6 +- 2 files changed, 50 insertions(+), 69 deletions(-) diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 82f5bf54d..dd5823ea1 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -21,7 +21,6 @@ import json from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers -from datetime import date from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService @@ -44,10 +43,10 @@ class CompareComplyV1(BaseService): DEFAULT_SERVICE_NAME = 'compare_comply' def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Compare Comply service. @@ -370,8 +369,6 @@ def add_feedback(self, def list_feedback(self, *, feedback_type: str = None, - before: date = None, - after: date = None, document_title: str = None, model_id: str = None, model_version: str = None, @@ -394,12 +391,6 @@ def list_feedback(self, :param str feedback_type: (optional) An optional string that filters the output to include only feedback with the specified feedback type. The only permitted value is `element_classification`. - :param date before: (optional) An optional string in the format - `YYYY-MM-DD` that filters the output to include only feedback that was - added before the specified date. - :param date after: (optional) An optional string in the format `YYYY-MM-DD` - that filters the output to include only feedback that was added after the - specified date. :param str document_title: (optional) An optional string that filters the output to include only feedback from the document with the specified `document_title`. @@ -461,8 +452,6 @@ def list_feedback(self, params = { 'version': self.version, 'feedback_type': feedback_type, - 'before': before, - 'after': after, 'document_title': document_title, 'model_id': model_id, 'model_version': model_version, @@ -1731,27 +1720,33 @@ class Category(): :attr str label: (optional) The category of the associated element. :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. + :attr str modification: (optional) The type of modification of the feedback + entry in the updated labels response. """ def __init__(self, *, label: str = None, - provenance_ids: List[str] = None) -> None: + provenance_ids: List[str] = None, + modification: str = None) -> None: """ Initialize a Category object. :param str label: (optional) The category of the associated element. :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. + :param str modification: (optional) The type of modification of the + feedback entry in the updated labels response. """ self.label = label self.provenance_ids = provenance_ids + self.modification = modification @classmethod def from_dict(cls, _dict: Dict) -> 'Category': """Initialize a Category object from a json dictionary.""" args = {} - valid_keys = ['label', 'provenance_ids'] + valid_keys = ['label', 'provenance_ids', 'modification'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -1761,6 +1756,8 @@ def from_dict(cls, _dict: Dict) -> 'Category': args['label'] = _dict.get('label') if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') + if 'modification' in _dict: + args['modification'] = _dict.get('modification') return cls(**args) @classmethod @@ -1775,6 +1772,8 @@ def to_dict(self) -> Dict: _dict['label'] = self.label if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids + if hasattr(self, 'modification') and self.modification is not None: + _dict['modification'] = self.modification return _dict def _to_dict(self): @@ -1825,6 +1824,14 @@ class LabelEnum(Enum): TERM_TERMINATION = "Term & Termination" WARRANTIES = "Warranties" + class ModificationEnum(Enum): + """ + The type of modification of the feedback entry in the updated labels response. + """ + ADDED = "added" + UNCHANGED = "unchanged" + REMOVED = "removed" + class CategoryComparison(): """ @@ -5243,16 +5250,12 @@ class OriginalLabelsOut(): the element and whom it affects. :attr List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :attr str modification: (optional) A string identifying the type of modification - the feedback entry in the `updated_labels` array. Possible values are `added`, - `not_changed`, and `removed`. """ def __init__(self, *, types: List['TypeLabel'] = None, - categories: List['Category'] = None, - modification: str = None) -> None: + categories: List['Category'] = None) -> None: """ Initialize a OriginalLabelsOut object. @@ -5261,19 +5264,15 @@ def __init__(self, :param List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :param str modification: (optional) A string identifying the type of - modification the feedback entry in the `updated_labels` array. Possible - values are `added`, `not_changed`, and `removed`. """ self.types = types self.categories = categories - self.modification = modification @classmethod def from_dict(cls, _dict: Dict) -> 'OriginalLabelsOut': """Initialize a OriginalLabelsOut object from a json dictionary.""" args = {} - valid_keys = ['types', 'categories', 'modification'] + valid_keys = ['types', 'categories'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -5287,8 +5286,6 @@ def from_dict(cls, _dict: Dict) -> 'OriginalLabelsOut': args['categories'] = [ Category._from_dict(x) for x in (_dict.get('categories')) ] - if 'modification' in _dict: - args['modification'] = _dict.get('modification') return cls(**args) @classmethod @@ -5303,8 +5300,6 @@ def to_dict(self) -> Dict: _dict['types'] = [x._to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = [x._to_dict() for x in self.categories] - if hasattr(self, 'modification') and self.modification is not None: - _dict['modification'] = self.modification return _dict def _to_dict(self): @@ -5325,15 +5320,6 @@ def __ne__(self, other: 'OriginalLabelsOut') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ModificationEnum(Enum): - """ - A string identifying the type of modification the feedback entry in the - `updated_labels` array. Possible values are `added`, `not_changed`, and `removed`. - """ - ADDED = "added" - NOT_CHANGED = "not_changed" - REMOVED = "removed" - class Pagination(): """ @@ -6775,12 +6761,15 @@ class TypeLabel(): and the `party` object identifies the affected party. :attr List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. + :attr str modification: (optional) The type of modification of the feedback + entry in the updated labels response. """ def __init__(self, *, label: 'Label' = None, - provenance_ids: List[str] = None) -> None: + provenance_ids: List[str] = None, + modification: str = None) -> None: """ Initialize a TypeLabel object. @@ -6789,15 +6778,18 @@ def __init__(self, `party`, and the `party` object identifies the affected party. :param List[str] provenance_ids: (optional) Hashed values that you can send to IBM to provide feedback or receive support. + :param str modification: (optional) The type of modification of the + feedback entry in the updated labels response. """ self.label = label self.provenance_ids = provenance_ids + self.modification = modification @classmethod def from_dict(cls, _dict: Dict) -> 'TypeLabel': """Initialize a TypeLabel object from a json dictionary.""" args = {} - valid_keys = ['label', 'provenance_ids'] + valid_keys = ['label', 'provenance_ids', 'modification'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -6807,6 +6799,8 @@ def from_dict(cls, _dict: Dict) -> 'TypeLabel': args['label'] = Label._from_dict(_dict.get('label')) if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') + if 'modification' in _dict: + args['modification'] = _dict.get('modification') return cls(**args) @classmethod @@ -6821,6 +6815,8 @@ def to_dict(self) -> Dict: _dict['label'] = self.label._to_dict() if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids + if hasattr(self, 'modification') and self.modification is not None: + _dict['modification'] = self.modification return _dict def _to_dict(self): @@ -6841,6 +6837,14 @@ def __ne__(self, other: 'TypeLabel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ModificationEnum(Enum): + """ + The type of modification of the feedback entry in the updated labels response. + """ + ADDED = "added" + UNCHANGED = "unchanged" + REMOVED = "removed" + class TypeLabelComparison(): """ @@ -7124,16 +7128,12 @@ class UpdatedLabelsOut(): the element and whom it affects. :attr List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :attr str modification: (optional) The type of modification the feedback entry - in the `updated_labels` array. Possible values are `added`, `not_changed`, and - `removed`. """ def __init__(self, *, types: List['TypeLabel'] = None, - categories: List['Category'] = None, - modification: str = None) -> None: + categories: List['Category'] = None) -> None: """ Initialize a UpdatedLabelsOut object. @@ -7142,19 +7142,15 @@ def __init__(self, :param List[Category] categories: (optional) List of functional categories into which the element falls; in other words, the subject matter of the element. - :param str modification: (optional) The type of modification the feedback - entry in the `updated_labels` array. Possible values are `added`, - `not_changed`, and `removed`. """ self.types = types self.categories = categories - self.modification = modification @classmethod def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsOut': """Initialize a UpdatedLabelsOut object from a json dictionary.""" args = {} - valid_keys = ['types', 'categories', 'modification'] + valid_keys = ['types', 'categories'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( @@ -7168,8 +7164,6 @@ def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsOut': args['categories'] = [ Category._from_dict(x) for x in (_dict.get('categories')) ] - if 'modification' in _dict: - args['modification'] = _dict.get('modification') return cls(**args) @classmethod @@ -7184,8 +7178,6 @@ def to_dict(self) -> Dict: _dict['types'] = [x._to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = [x._to_dict() for x in self.categories] - if hasattr(self, 'modification') and self.modification is not None: - _dict['modification'] = self.modification return _dict def _to_dict(self): @@ -7206,15 +7198,6 @@ def __ne__(self, other: 'UpdatedLabelsOut') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ModificationEnum(Enum): - """ - The type of modification the feedback entry in the `updated_labels` array. - Possible values are `added`, `not_changed`, and `removed`. - """ - ADDED = "added" - NOT_CHANGED = "not_changed" - REMOVED = "removed" - class Value(): """ diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 577a098a8..6819e6a71 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -494,8 +494,6 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['feedback_type'] = "string1" - body['before'] = datetime.now().date() - body['after'] = datetime.now().date() body['document_title'] = "string1" body['model_id'] = "string1" body['model_version'] = "string1" @@ -1035,9 +1033,9 @@ def send_request(obj, body, response, url=None): fake_response_ClassifyReturn_json = """{"document": {"title": "fake_title", "html": "fake_html", "hash": "fake_hash", "label": "fake_label"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "elements": [], "effective_dates": [], "contract_amounts": [], "termination_dates": [], "contract_types": [], "contract_terms": [], "payment_terms": [], "contract_currencies": [], "tables": [], "document_structure": {"section_titles": [], "leading_sentences": [], "paragraphs": []}, "parties": []}""" fake_response_TableReturn_json = """{"document": {"html": "fake_html", "title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "tables": []}""" fake_response_CompareReturn_json = """{"model_id": "fake_model_id", "model_version": "fake_model_version", "documents": [], "aligned_elements": [], "unaligned_elements": []}""" -fake_response_FeedbackReturn_json = """{"feedback_id": "fake_feedback_id", "user_id": "fake_user_id", "comment": "fake_comment", "created": "2017-05-16T13:56:54.957Z", "feedback_data": {"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "updated_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "pagination": {"refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor", "refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5}}}""" +fake_response_FeedbackReturn_json = """{"feedback_id": "fake_feedback_id", "user_id": "fake_user_id", "comment": "fake_comment", "created": "2017-05-16T13:56:54.957Z", "feedback_data": {"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}, "pagination": {"refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor", "refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5}}}""" fake_response_FeedbackList_json = """{"feedback": []}""" -fake_response_GetFeedback_json = """{"feedback_id": "fake_feedback_id", "created": "2017-05-16T13:56:54.957Z", "comment": "fake_comment", "feedback_data": {"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "updated_labels": {"types": [], "categories": [], "modification": "fake_modification"}, "pagination": {"refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor", "refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5}}}""" +fake_response_GetFeedback_json = """{"feedback_id": "fake_feedback_id", "created": "2017-05-16T13:56:54.957Z", "comment": "fake_comment", "feedback_data": {"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}, "pagination": {"refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor", "refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5}}}""" fake_response_FeedbackDeleted_json = """{"status": 6, "message": "fake_message"}""" fake_response_BatchStatus_json = """{"function": "fake_function", "input_bucket_location": "fake_input_bucket_location", "input_bucket_name": "fake_input_bucket_name", "output_bucket_location": "fake_output_bucket_location", "output_bucket_name": "fake_output_bucket_name", "batch_id": "fake_batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" fake_response_Batches_json = """{"batches": []}""" From 8fdebc45f0dfd1044d848969cb5cb3b8cb15a313 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 16 Nov 2020 13:10:50 -0500 Subject: [PATCH 284/455] feat: regenrate language translator --- ibm_watson/language_translator_v3.py | 51 ++++++++++++++++++---------- 1 file changed, 34 insertions(+), 17 deletions(-) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 072f7a1de..a6f848347 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -47,10 +47,10 @@ class LanguageTranslatorV3(BaseService): DEFAULT_SERVICE_NAME = 'language_translator' def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Language Translator service. @@ -87,9 +87,12 @@ def list_languages(self, **kwargs) -> 'DetailedResponse': """ List supported languages. - Lists all supported languages. The method returns an array of supported languages - with information about each language. Languages are listed in alphabetical order - by language code (for example, `af`, `ar`). + Lists all supported languages for translation. The method returns an array of + supported languages with information about each language. Languages are listed in + alphabetical order by language code (for example, `af`, `ar`). In addition to + basic information about each language, the response indicates whether the language + is `supported_as_source` for translation and `supported_as_target` for + translation. It also lists whether the language is `identifiable`. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -135,9 +138,12 @@ def translate(self, service attempt to detect the language from the input text. If you omit the source language, the request must contain sufficient input text for the service to identify the source language. + You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. + All input text must be encoded in UTF-8 format. - :param List[str] text: Input text in UTF-8 encoding. Multiple entries - result in multiple translations in the response. + :param List[str] text: Input text in UTF-8 encoding. Submit a maximum of 50 + KB (51,200 bytes) of text with a single request. Multiple elements result + in multiple translations in the response. :param str model_id: (optional) The model to use for translation. For example, `en-de` selects the IBM-provided base model for English-to-German translation. A model ID overrides the `source` and `target` parameters and @@ -350,9 +356,13 @@ def create_model(self, * **XLIFF** (`.xliff`) - XML Localization Interchange File Format (XLIFF) is an XML specification for the exchange of translation memories. * **CSV** (`.csv`) - Comma-separated values (CSV) file with two columns for - aligned sentences and phrases. The first row contains the language code. + aligned sentences and phrases. The first row must have two language codes. The + first column is for the source language code, and the second column is for the + target language code. * **TSV** (`.tsv` or `.tab`) - Tab-separated values (TSV) file with two columns - for aligned sentences and phrases. The first row contains the language code. + for aligned sentences and phrases. The first row must have two language codes. The + first column is for the source language code, and the second column is for the + target language code. * **JSON** (`.json`) - Custom JSON format for specifying aligned sentences and phrases. * **Microsoft Excel** (`.xls` or `.xlsx`) - Excel file with the first two columns @@ -564,12 +574,16 @@ def translate_document(self, Submit a document for translation. You can submit the document contents in the `file` parameter, or you can reference a previously submitted document by document - ID. - - :param TextIO file: The contents of the source file to translate. - [Supported file - types](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats) - Maximum file size: **20 MB**. + ID. The maximum file size for document translation is + * 20 MB for service instances on the Standard, Advanced, and Premium plans + * 2 MB for service instances on the Lite plan. + + :param TextIO file: The contents of the source file to translate. The + maximum file size for document translation is 20 MB for service instances + on the Standard, Advanced, and Premium plans, and 2 MB for service + instances on the Lite plan. For more information, see [Supported file + formats + (Beta)](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str model_id: (optional) The model to use for translation. For @@ -785,6 +799,9 @@ class FileContentType(Enum): TEXT_PLAIN = 'text/plain' TEXT_RICHTEXT = 'text/richtext' TEXT_RTF = 'text/rtf' + TEXT_SBV = 'text/sbv' + TEXT_SRT = 'text/srt' + TEXT_VTT = 'text/vtt' TEXT_XML = 'text/xml' From f2f40e7a6e9aa90f3938d576081998cb5667a0f8 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 16 Nov 2020 13:13:07 -0500 Subject: [PATCH 285/455] feat(VisRecV4): change start time and end time to date from string BREAKING CHANGE: change start and end time for training usage to date time format --- ibm_watson/visual_recognition_v4.py | 27 +++++++++++-------------- test/unit/test_visual_recognition_v4.py | 4 ++-- 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 79b32f3fd..a258262e3 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -21,6 +21,7 @@ import json from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from .common import get_sdk_headers +from datetime import date from datetime import datetime from enum import Enum from ibm_cloud_sdk_core import BaseService @@ -44,10 +45,10 @@ class VisualRecognitionV4(BaseService): DEFAULT_SERVICE_NAME = 'visual_recognition' def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Visual Recognition service. @@ -926,8 +927,8 @@ def add_image_training_data(self, def get_training_usage(self, *, - start_time: str = None, - end_time: str = None, + start_time: date = None, + end_time: date = None, **kwargs) -> 'DetailedResponse': """ Get training usage. @@ -935,10 +936,10 @@ def get_training_usage(self, Information about the completed training events. You can use this information to determine how close you are to the training limits for the month. - :param str start_time: (optional) The earliest day to include training + :param date start_time: (optional) The earliest day to include training events. Specify dates in YYYY-MM-DD format. If empty or not specified, the earliest training event is included. - :param str end_time: (optional) The most recent day to include training + :param date end_time: (optional) The most recent day to include training events. Specify dates in YYYY-MM-DD format. All events for the day are included. If empty or not specified, the current day is used. Specify the same value as `start_time` to request events for a single day. @@ -3225,18 +3226,18 @@ class UpdateObjectMetadata(): :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 + :attr int count: (optional) Number of bounding boxes in the collection with the updated object name. """ - def __init__(self, object: str, count: int) -> None: + def __init__(self, object: str, *, count: int = None) -> 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 + :param int count: (optional) Number of bounding boxes in the collection with the updated object name. """ self.object = object @@ -3260,10 +3261,6 @@ def from_dict(cls, _dict: Dict) -> 'UpdateObjectMetadata': ) if 'count' in _dict: args['count'] = _dict.get('count') - else: - raise ValueError( - 'Required property \'count\' not present in UpdateObjectMetadata JSON' - ) return cls(**args) @classmethod diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index a5850db62..6db7d26a5 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1418,8 +1418,8 @@ def call_service(self, body): def construct_full_body(self): body = dict() - body['start_time'] = "string1" - body['end_time'] = "string1" + body['start_time'] = datetime.now().date() + body['end_time'] = datetime.now().date() return body def construct_required_body(self): From e17b24cc565bf6ee603497aeb5c11436ee09b0dc Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 16 Nov 2020 15:52:47 -0500 Subject: [PATCH 286/455] feat(AssistantV1): add support for bulkClassify --- ibm_watson/assistant_v1.py | 5156 ++++++++++++++++++++------------ test/unit/test_assistant_v1.py | 114 +- 2 files changed, 3319 insertions(+), 1951 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index e6bac2d3e..38e5a33b9 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -32,6 +32,7 @@ from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List +import sys ############################################################################## # Service @@ -45,10 +46,10 @@ class AssistantV1(BaseService): DEFAULT_SERVICE_NAME = 'assistant' def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Assistant service. @@ -180,6 +181,7 @@ def message(self, def list_workspaces(self, *, page_limit: int = None, + include_count: bool = None, sort: str = None, cursor: str = None, include_audit: bool = None, @@ -191,6 +193,10 @@ def list_workspaces(self, :param int page_limit: (optional) The number of records to return in each page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. :param str sort: (optional) The attribute by which returned workspaces will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -214,6 +220,7 @@ def list_workspaces(self, params = { 'version': self.version, 'page_limit': page_limit, + 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -233,14 +240,14 @@ def create_workspace(self, name: str = None, description: str = None, language: str = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, metadata: dict = None, learning_opt_out: bool = None, system_settings: 'WorkspaceSystemSettings' = None, + webhooks: List['Webhook'] = None, intents: List['CreateIntent'] = None, entities: List['CreateEntity'] = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - webhooks: List['Webhook'] = None, include_audit: bool = None, **kwargs) -> 'DetailedResponse': """ @@ -254,6 +261,10 @@ def create_workspace(self, :param str description: (optional) The description of the workspace. This string cannot contain carriage return, newline, or tab characters. :param str language: (optional) The language of the workspace. + :param List[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. + :param List[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. :param dict metadata: (optional) Any metadata related to the workspace. :param bool learning_opt_out: (optional) Whether training data from the workspace (including artifacts such as intents and entities) can be used by @@ -261,15 +272,11 @@ def create_workspace(self, training data is not to be used. :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. + :param List[Webhook] webhooks: (optional) :param List[CreateIntent] intents: (optional) An array of objects defining the intents for the workspace. :param List[CreateEntity] entities: (optional) An array of objects describing the entities for the workspace. - :param List[DialogNode] dialog_nodes: (optional) An array of objects - describing the dialog nodes in the workspace. - :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 @@ -277,18 +284,18 @@ def create_workspace(self, :rtype: DetailedResponse """ - if system_settings is not None: - system_settings = self._convert_model(system_settings) - if intents is not None: - intents = [self._convert_model(x) for x in intents] - if entities is not None: - entities = [self._convert_model(x) for x in entities] if dialog_nodes is not None: dialog_nodes = [self._convert_model(x) for x in dialog_nodes] if counterexamples is not None: counterexamples = [self._convert_model(x) for x in counterexamples] + if system_settings is not None: + system_settings = self._convert_model(system_settings) if webhooks is not None: webhooks = [self._convert_model(x) for x in webhooks] + if intents is not None: + intents = [self._convert_model(x) for x in intents] + if entities is not None: + entities = [self._convert_model(x) for x in entities] headers = {} if 'headers' in kwargs: @@ -304,14 +311,14 @@ def create_workspace(self, 'name': name, 'description': description, 'language': language, + 'dialog_nodes': dialog_nodes, + 'counterexamples': counterexamples, 'metadata': metadata, 'learning_opt_out': learning_opt_out, 'system_settings': system_settings, + 'webhooks': webhooks, 'intents': intents, - 'entities': entities, - 'dialog_nodes': dialog_nodes, - 'counterexamples': counterexamples, - 'webhooks': webhooks + 'entities': entities } url = '/v1/workspaces' @@ -385,14 +392,14 @@ def update_workspace(self, name: str = None, description: str = None, language: str = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, metadata: dict = None, learning_opt_out: bool = None, system_settings: 'WorkspaceSystemSettings' = None, + webhooks: List['Webhook'] = None, intents: List['CreateIntent'] = None, entities: List['CreateEntity'] = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - webhooks: List['Webhook'] = None, append: bool = None, include_audit: bool = None, **kwargs) -> 'DetailedResponse': @@ -408,6 +415,10 @@ def update_workspace(self, :param str description: (optional) The description of the workspace. This string cannot contain carriage return, newline, or tab characters. :param str language: (optional) The language of the workspace. + :param List[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. + :param List[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. :param dict metadata: (optional) Any metadata related to the workspace. :param bool learning_opt_out: (optional) Whether training data from the workspace (including artifacts such as intents and entities) can be used by @@ -415,15 +426,11 @@ def update_workspace(self, training data is not to be used. :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. + :param List[Webhook] webhooks: (optional) :param List[CreateIntent] intents: (optional) An array of objects defining the intents for the workspace. :param List[CreateEntity] entities: (optional) An array of objects describing the entities for the workspace. - :param List[DialogNode] dialog_nodes: (optional) An array of objects - describing the dialog nodes in the workspace. - :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 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, @@ -442,18 +449,18 @@ def update_workspace(self, if workspace_id is None: raise ValueError('workspace_id must be provided') - if system_settings is not None: - system_settings = self._convert_model(system_settings) - if intents is not None: - intents = [self._convert_model(x) for x in intents] - if entities is not None: - entities = [self._convert_model(x) for x in entities] if dialog_nodes is not None: dialog_nodes = [self._convert_model(x) for x in dialog_nodes] if counterexamples is not None: counterexamples = [self._convert_model(x) for x in counterexamples] + if system_settings is not None: + system_settings = self._convert_model(system_settings) if webhooks is not None: webhooks = [self._convert_model(x) for x in webhooks] + if intents is not None: + intents = [self._convert_model(x) for x in intents] + if entities is not None: + entities = [self._convert_model(x) for x in entities] headers = {} if 'headers' in kwargs: @@ -473,14 +480,14 @@ def update_workspace(self, 'name': name, 'description': description, 'language': language, + 'dialog_nodes': dialog_nodes, + 'counterexamples': counterexamples, 'metadata': metadata, 'learning_opt_out': learning_opt_out, 'system_settings': system_settings, + 'webhooks': webhooks, 'intents': intents, - 'entities': entities, - 'dialog_nodes': dialog_nodes, - 'counterexamples': counterexamples, - 'webhooks': webhooks + 'entities': entities } url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) @@ -537,6 +544,7 @@ def list_intents(self, *, export: bool = None, page_limit: int = None, + include_count: bool = None, sort: str = None, cursor: str = None, include_audit: bool = None, @@ -553,6 +561,10 @@ def list_intents(self, including subelements, is included. :param int page_limit: (optional) The number of records to return in each page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. :param str sort: (optional) The attribute by which returned intents will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -580,6 +592,7 @@ def list_intents(self, 'version': self.version, 'export': export, 'page_limit': page_limit, + 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -846,6 +859,7 @@ def list_examples(self, intent: str, *, page_limit: int = None, + include_count: bool = None, sort: str = None, cursor: str = None, include_audit: bool = None, @@ -860,6 +874,10 @@ def list_examples(self, :param str intent: The intent name. :param int page_limit: (optional) The number of records to return in each page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. :param str sort: (optional) The attribute by which returned examples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -888,6 +906,7 @@ def list_examples(self, params = { 'version': self.version, 'page_limit': page_limit, + 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -1128,6 +1147,7 @@ def list_counterexamples(self, workspace_id: str, *, page_limit: int = None, + include_count: bool = None, sort: str = None, cursor: str = None, include_audit: bool = None, @@ -1141,6 +1161,10 @@ def list_counterexamples(self, :param str workspace_id: Unique identifier of the workspace. :param int page_limit: (optional) The number of records to return in each page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. :param str sort: (optional) The attribute by which returned counterexamples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -1167,6 +1191,7 @@ def list_counterexamples(self, params = { 'version': self.version, 'page_limit': page_limit, + 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -1388,6 +1413,7 @@ def list_entities(self, *, export: bool = None, page_limit: int = None, + include_count: bool = None, sort: str = None, cursor: str = None, include_audit: bool = None, @@ -1404,6 +1430,10 @@ def list_entities(self, including subelements, is included. :param int page_limit: (optional) The number of records to return in each page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. :param str sort: (optional) The attribute by which returned entities will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -1431,6 +1461,7 @@ def list_entities(self, 'version': self.version, 'export': export, 'page_limit': page_limit, + 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -1773,6 +1804,7 @@ def list_values(self, *, export: bool = None, page_limit: int = None, + include_count: bool = None, sort: str = None, cursor: str = None, include_audit: bool = None, @@ -1790,6 +1822,10 @@ def list_values(self, including subelements, is included. :param int page_limit: (optional) The number of records to return in each page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. :param str sort: (optional) The attribute by which returned entity values will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -1819,6 +1855,7 @@ def list_values(self, 'version': self.version, 'export': export, 'page_limit': page_limit, + 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -2123,6 +2160,7 @@ def list_synonyms(self, value: str, *, page_limit: int = None, + include_count: bool = None, sort: str = None, cursor: str = None, include_audit: bool = None, @@ -2137,6 +2175,10 @@ def list_synonyms(self, :param str value: The text of the entity value. :param int page_limit: (optional) The number of records to return in each page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. :param str sort: (optional) The attribute by which returned entity value synonyms will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -2167,6 +2209,7 @@ def list_synonyms(self, params = { 'version': self.version, 'page_limit': page_limit, + 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -2414,6 +2457,7 @@ def list_dialog_nodes(self, workspace_id: str, *, page_limit: int = None, + include_count: bool = None, sort: str = None, cursor: str = None, include_audit: bool = None, @@ -2426,6 +2470,10 @@ def list_dialog_nodes(self, :param str workspace_id: Unique identifier of the workspace. :param int page_limit: (optional) The number of records to return in each page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. :param str sort: (optional) The attribute by which returned dialog nodes will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -2452,6 +2500,7 @@ def list_dialog_nodes(self, params = { 'version': self.version, 'page_limit': page_limit, + 'include_count': include_count, 'sort': sort, 'cursor': cursor, 'include_audit': include_audit @@ -2476,7 +2525,7 @@ def create_dialog_node(self, parent: str = None, previous_sibling: str = None, output: 'DialogNodeOutput' = None, - context: dict = None, + context: 'DialogNodeContext' = None, metadata: dict = None, next_step: 'DialogNodeNextStep' = None, title: str = None, @@ -2516,7 +2565,8 @@ def create_dialog_node(self, :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/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :param dict context: (optional) The context for the dialog node. + :param DialogNodeContext 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 following this dialog node. @@ -2554,6 +2604,8 @@ def create_dialog_node(self, raise ValueError('dialog_node must be provided') if output is not None: output = self._convert_model(output) + if context is not None: + context = self._convert_model(context) if next_step is not None: next_step = self._convert_model(next_step) if actions is not None: @@ -2657,7 +2709,7 @@ def update_dialog_node(self, new_parent: str = None, new_previous_sibling: str = None, new_output: 'DialogNodeOutput' = None, - new_context: dict = None, + new_context: 'DialogNodeContext' = None, new_metadata: dict = None, new_next_step: 'DialogNodeNextStep' = None, new_title: str = None, @@ -2698,7 +2750,8 @@ def update_dialog_node(self, :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/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :param dict new_context: (optional) The context for the dialog node. + :param DialogNodeContext 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 execute following this dialog node. @@ -2737,6 +2790,8 @@ def update_dialog_node(self, raise ValueError('dialog_node must be provided') if new_output is not None: new_output = self._convert_model(new_output) + if new_context is not None: + new_context = self._convert_model(new_context) if new_next_step is not None: new_next_step = self._convert_model(new_next_step) if new_actions is not None: @@ -2989,6 +3044,59 @@ def delete_user_data(self, customer_id: str, response = self.send(request) return response + ######################### + # bulkClassify + ######################### + + def bulk_classify(self, + workspace_id: str, + *, + input: List['BulkClassifyUtterance'] = None, + **kwargs) -> 'DetailedResponse': + """ + Identify intents and entities in multiple user utterances. + + Send multiple user inputs to a workspace in a single request and receive + information about the intents and entities recognized in each input. This method + is useful for testing and comparing the performance of different workspaces. + This method is available only with Premium plans. + + :param str workspace_id: Unique identifier of the workspace. + :param List[BulkClassifyUtterance] input: (optional) An array of input + utterances to classify. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if workspace_id is None: + raise ValueError('workspace_id must be provided') + if input is not None: + input = [self._convert_model(x) for x in input] + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='bulk_classify') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'input': input} + + url = '/v1/workspaces/{0}/bulk_classify'.format( + *self._encode_path_vars(workspace_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + class ListWorkspacesEnums(object): @@ -3094,57 +3202,73 @@ class Sort(Enum): ############################################################################## -class CaptureGroup(): +class BulkClassifyOutput(): """ - A recognized capture group for a pattern-based entity. - - :attr str group: A recognized capture group for the entity. - :attr List[int] location: (optional) Zero-based character offsets that indicate - where the entity value begins and ends in the input text. + BulkClassifyOutput. + + :attr BulkClassifyUtterance input: (optional) The user input utterance to + classify. + :attr List[RuntimeEntity] entities: (optional) An array of entities identified + in the utterance. + :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + the utterance. """ - def __init__(self, group: str, *, location: List[int] = None) -> None: + def __init__(self, + *, + input: 'BulkClassifyUtterance' = None, + entities: List['RuntimeEntity'] = None, + intents: List['RuntimeIntent'] = None) -> None: """ - Initialize a CaptureGroup object. + Initialize a BulkClassifyOutput object. - :param str group: A recognized capture group for the entity. - :param List[int] location: (optional) Zero-based character offsets that - indicate where the entity value begins and ends in the input text. + :param BulkClassifyUtterance input: (optional) The user input utterance to + classify. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the utterance. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the utterance. """ - self.group = group - self.location = location + self.input = input + self.entities = entities + self.intents = intents @classmethod - def from_dict(cls, _dict: Dict) -> 'CaptureGroup': - """Initialize a CaptureGroup object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': + """Initialize a BulkClassifyOutput object from a json dictionary.""" args = {} - valid_keys = ['group', 'location'] + valid_keys = ['input', 'entities', 'intents'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class CaptureGroup: ' + 'Unrecognized keys detected in dictionary for class BulkClassifyOutput: ' + ', '.join(bad_keys)) - if 'group' in _dict: - args['group'] = _dict.get('group') - else: - raise ValueError( - 'Required property \'group\' not present in CaptureGroup JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') + if 'input' in _dict: + args['input'] = BulkClassifyUtterance._from_dict(_dict.get('input')) + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + ] + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CaptureGroup object from a json dictionary.""" + """Initialize a BulkClassifyOutput 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, 'group') and self.group is not None: - _dict['group'] = self.group - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location + if hasattr(self, 'input') and self.input is not None: + _dict['input'] = self.input._to_dict() + if hasattr(self, 'entities') and self.entities is not None: + _dict['entities'] = [x._to_dict() for x in self.entities] + if hasattr(self, 'intents') and self.intents is not None: + _dict['intents'] = [x._to_dict() for x in self.intents] return _dict def _to_dict(self): @@ -3152,148 +3276,348 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CaptureGroup object.""" + """Return a `str` version of this BulkClassifyOutput object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'CaptureGroup') -> bool: + def __eq__(self, other: 'BulkClassifyOutput') -> 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: 'CaptureGroup') -> bool: + def __ne__(self, other: 'BulkClassifyOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Context(): +class BulkClassifyResponse(): """ - State information for the conversation. To maintain state, include the context from - the previous response. + BulkClassifyResponse. - :attr str conversation_id: (optional) The unique identifier of the conversation. - :attr SystemResponse system: (optional) For internal use only. - :attr MessageContextMetadata metadata: (optional) Metadata related to the - message. + :attr List[BulkClassifyOutput] output: (optional) An array of objects that + contain classification information for the submitted input utterances. """ - def __init__(self, - *, - conversation_id: str = None, - system: 'SystemResponse' = None, - metadata: 'MessageContextMetadata' = None, - **kwargs) -> None: + def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: """ - Initialize a Context object. + Initialize a BulkClassifyResponse object. - :param str conversation_id: (optional) The unique identifier of the - conversation. - :param SystemResponse system: (optional) For internal use only. - :param MessageContextMetadata metadata: (optional) Metadata related to the - message. - :param **kwargs: (optional) Any additional properties. + :param List[BulkClassifyOutput] output: (optional) An array of objects that + contain classification information for the submitted input utterances. """ - self.conversation_id = conversation_id - self.system = system - self.metadata = metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.output = output @classmethod - def from_dict(cls, _dict: Dict) -> 'Context': - """Initialize a Context object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': + """Initialize a BulkClassifyResponse object from a json dictionary.""" args = {} - xtra = _dict.copy() - if 'conversation_id' in _dict: - args['conversation_id'] = _dict.get('conversation_id') - del xtra['conversation_id'] - if 'system' in _dict: - args['system'] = SystemResponse._from_dict(_dict.get('system')) - del xtra['system'] - if 'metadata' in _dict: - args['metadata'] = MessageContextMetadata._from_dict( - _dict.get('metadata')) - del xtra['metadata'] - args.update(xtra) + valid_keys = ['output'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class BulkClassifyResponse: ' + + ', '.join(bad_keys)) + if 'output' in _dict: + args['output'] = [ + BulkClassifyOutput._from_dict(x) for x in (_dict.get('output')) + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Context object from a json dictionary.""" + """Initialize a BulkClassifyResponse 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, - 'conversation_id') and self.conversation_id is not None: - _dict['conversation_id'] = self.conversation_id - if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system._to_dict() - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata._to_dict() - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + if hasattr(self, 'output') and self.output is not None: + _dict['output'] = [x._to_dict() for x in self.output] return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = {'conversation_id', 'system', 'metadata'} - if not hasattr(self, '_additionalProperties'): - super(Context, self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(Context, self).__setattr__(name, value) - def __str__(self) -> str: - """Return a `str` version of this Context object.""" + """Return a `str` version of this BulkClassifyResponse object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'Context') -> bool: + def __eq__(self, other: 'BulkClassifyResponse') -> 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: 'Context') -> bool: + def __ne__(self, other: 'BulkClassifyResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Counterexample(): +class BulkClassifyUtterance(): """ - Counterexample. + The user input utterance to classify. - :attr str text: The text of a user input marked as 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. - :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. + :attr str text: The text of the input utterance. """ - def __init__(self, - text: str, - *, - created: datetime = None, - updated: datetime = None) -> None: + def __init__(self, text: str) -> None: """ - Initialize a Counterexample object. + Initialize a BulkClassifyUtterance object. - :param str text: The text of a user input marked as 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 datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent + :param str text: The text of the input utterance. + """ + self.text = text + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': + """Initialize a BulkClassifyUtterance object from a json dictionary.""" + args = {} + valid_keys = ['text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class BulkClassifyUtterance: ' + + ', '.join(bad_keys)) + if 'text' in _dict: + args['text'] = _dict.get('text') + else: + raise ValueError( + 'Required property \'text\' not present in BulkClassifyUtterance JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BulkClassifyUtterance 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, 'text') and self.text is not None: + _dict['text'] = self.text + 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 BulkClassifyUtterance object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'BulkClassifyUtterance') -> 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: 'BulkClassifyUtterance') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CaptureGroup(): + """ + A recognized capture group for a pattern-based entity. + + :attr str group: A recognized capture group for the entity. + :attr List[int] location: (optional) Zero-based character offsets that indicate + where the entity value begins and ends in the input text. + """ + + def __init__(self, group: str, *, location: List[int] = None) -> None: + """ + Initialize a CaptureGroup object. + + :param str group: A recognized capture group for the entity. + :param List[int] location: (optional) Zero-based character offsets that + indicate where the entity value begins and ends in the input text. + """ + self.group = group + self.location = location + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CaptureGroup': + """Initialize a CaptureGroup object from a json dictionary.""" + args = {} + valid_keys = ['group', 'location'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class CaptureGroup: ' + + ', '.join(bad_keys)) + if 'group' in _dict: + args['group'] = _dict.get('group') + else: + raise ValueError( + 'Required property \'group\' not present in CaptureGroup JSON') + if 'location' in _dict: + args['location'] = _dict.get('location') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CaptureGroup 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, 'group') and self.group is not None: + _dict['group'] = self.group + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + 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 CaptureGroup object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'CaptureGroup') -> 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: 'CaptureGroup') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Context(): + """ + State information for the conversation. To maintain state, include the context from + the previous response. + + :attr str conversation_id: (optional) The unique identifier of the conversation. + :attr SystemResponse system: (optional) For internal use only. + :attr MessageContextMetadata metadata: (optional) Metadata related to the + message. + """ + + def __init__(self, + *, + conversation_id: str = None, + system: 'SystemResponse' = None, + metadata: 'MessageContextMetadata' = None, + **kwargs) -> None: + """ + Initialize a Context object. + + :param str conversation_id: (optional) The unique identifier of the + conversation. + :param SystemResponse system: (optional) For internal use only. + :param MessageContextMetadata metadata: (optional) Metadata related to the + message. + :param **kwargs: (optional) Any additional properties. + """ + self.conversation_id = conversation_id + self.system = system + self.metadata = metadata + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Context': + """Initialize a Context object from a json dictionary.""" + args = {} + xtra = _dict.copy() + if 'conversation_id' in _dict: + args['conversation_id'] = _dict.get('conversation_id') + del xtra['conversation_id'] + if 'system' in _dict: + args['system'] = SystemResponse._from_dict(_dict.get('system')) + del xtra['system'] + if 'metadata' in _dict: + args['metadata'] = MessageContextMetadata._from_dict( + _dict.get('metadata')) + del xtra['metadata'] + args.update(xtra) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Context 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, + 'conversation_id') and self.conversation_id is not None: + _dict['conversation_id'] = self.conversation_id + if hasattr(self, 'system') and self.system is not None: + _dict['system'] = self.system._to_dict() + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata._to_dict() + if hasattr(self, '_additionalProperties'): + for _key in self._additionalProperties: + _value = getattr(self, _key, None) + if _value is not None: + _dict[_key] = _value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: + properties = {'conversation_id', 'system', 'metadata'} + if not hasattr(self, '_additionalProperties'): + super(Context, self).__setattr__('_additionalProperties', set()) + if name not in properties: + self._additionalProperties.add(name) + super(Context, self).__setattr__(name, value) + + def __str__(self) -> str: + """Return a `str` version of this Context object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Context') -> 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: 'Context') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Counterexample(): + """ + Counterexample. + + :attr str text: The text of a user input marked as 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. + :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. + """ + + def __init__(self, + text: str, + *, + created: datetime = None, + updated: datetime = None) -> None: + """ + Initialize a Counterexample object. + + :param str text: The text of a user input marked as 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 datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ self.text = text @@ -3859,7 +4183,7 @@ class DialogNode(): :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/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :attr dict context: (optional) The context for the dialog node. + :attr DialogNodeContext 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 following this dialog node. @@ -3898,7 +4222,7 @@ def __init__(self, parent: str = None, previous_sibling: str = None, output: 'DialogNodeOutput' = None, - context: dict = None, + context: 'DialogNodeContext' = None, metadata: dict = None, next_step: 'DialogNodeNextStep' = None, title: str = None, @@ -3934,7 +4258,8 @@ def __init__(self, :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/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :param dict context: (optional) The context for the dialog node. + :param DialogNodeContext 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 following this dialog node. @@ -4021,7 +4346,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogNode': if 'output' in _dict: args['output'] = DialogNodeOutput._from_dict(_dict.get('output')) if 'context' in _dict: - args['context'] = _dict.get('context') + args['context'] = DialogNodeContext._from_dict(_dict.get('context')) if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'next_step' in _dict: @@ -4079,7 +4404,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output._to_dict() if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context + _dict['context'] = self.context._to_dict() if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'next_step') and self.next_step is not None: @@ -4383,18 +4708,94 @@ def __ne__(self, other: 'DialogNodeCollection') -> bool: return not self == other -class DialogNodeNextStep(): +class DialogNodeContext(): """ - The next step to execute following this dialog node. + The context for the dialog node. - :attr str behavior: What happens after the dialog node completes. The valid - values depend on the node type: - - The following values are valid for any node: - - `get_user_input` - - `skip_user_input` - - `jump_to` - - If the node is of type `event_handler` and its parent node is of type `slot` - or `frame`, additional values are also valid: + :attr dict integrations: (optional) Context data intended for specific + integrations. + """ + + def __init__(self, *, integrations: dict = None, **kwargs) -> None: + """ + Initialize a DialogNodeContext object. + + :param dict integrations: (optional) Context data intended for specific + integrations. + :param **kwargs: (optional) Any additional properties. + """ + self.integrations = integrations + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DialogNodeContext': + """Initialize a DialogNodeContext object from a json dictionary.""" + args = {} + xtra = _dict.copy() + if 'integrations' in _dict: + args['integrations'] = _dict.get('integrations') + del xtra['integrations'] + args.update(xtra) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeContext 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, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations + if hasattr(self, '_additionalProperties'): + for _key in self._additionalProperties: + _value = getattr(self, _key, None) + if _value is not None: + _dict[_key] = _value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: + properties = {'integrations'} + if not hasattr(self, '_additionalProperties'): + super(DialogNodeContext, self).__setattr__('_additionalProperties', + set()) + if name not in properties: + self._additionalProperties.add(name) + super(DialogNodeContext, self).__setattr__(name, value) + + def __str__(self) -> str: + """Return a `str` version of this DialogNodeContext object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'DialogNodeContext') -> 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: 'DialogNodeContext') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DialogNodeNextStep(): + """ + The next step to execute following this dialog node. + + :attr str behavior: What happens after the dialog node completes. The valid + values depend on the node type: + - The following values are valid for any node: + - `get_user_input` + - `skip_user_input` + - `jump_to` + - If the node is of type `event_handler` and its parent node is of type `slot` + or `frame`, additional values are also valid: - if **event_name**=`filled` and the type of the parent node is `slot`: - `reprompt` - `skip_all_slots` @@ -4556,6 +4957,9 @@ class DialogNodeOutput(): :attr List[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. + :attr dict integrations: (optional) Output intended for specific integrations. + For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-responses-json). :attr DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. """ @@ -4563,6 +4967,7 @@ class DialogNodeOutput(): def __init__(self, *, generic: List['DialogNodeOutputGeneric'] = None, + integrations: dict = None, modifiers: 'DialogNodeOutputModifiers' = None, **kwargs) -> None: """ @@ -4570,11 +4975,15 @@ def __init__(self, :param List[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. + :param dict integrations: (optional) Output intended for specific + integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-responses-json). :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. :param **kwargs: (optional) Any additional properties. """ self.generic = generic + self.integrations = integrations self.modifiers = modifiers for _key, _value in kwargs.items(): setattr(self, _key, _value) @@ -4590,6 +4999,9 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': for x in (_dict.get('generic')) ] del xtra['generic'] + if 'integrations' in _dict: + args['integrations'] = _dict.get('integrations') + del xtra['integrations'] if 'modifiers' in _dict: args['modifiers'] = DialogNodeOutputModifiers._from_dict( _dict.get('modifiers')) @@ -4607,6 +5019,8 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'generic') and self.generic is not None: _dict['generic'] = [x._to_dict() for x in self.generic] + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations if hasattr(self, 'modifiers') and self.modifiers is not None: _dict['modifiers'] = self.modifiers._to_dict() if hasattr(self, '_additionalProperties'): @@ -4621,7 +5035,7 @@ def _to_dict(self): return self.to_dict() def __setattr__(self, name: str, value: object) -> None: - properties = {'generic', 'modifiers'} + properties = {'generic', 'integrations', 'modifiers'} if not hasattr(self, '_additionalProperties'): super(DialogNodeOutput, self).__setattr__('_additionalProperties', set()) @@ -4644,242 +5058,46 @@ def __ne__(self, other: 'DialogNodeOutput') -> bool: return not self == other -class DialogNodeOutputGeneric(): +class DialogNodeOutputConnectToAgentTransferInfo(): """ - DialogNodeOutputGeneric. + Routing or other contextual information to be used by target service desk systems. - :attr str response_type: The type of response returned by the dialog node. The - specified response type must be supported by the client application or channel. - **Note:** The **search_skill** response type is used only by the v2 runtime API. - :attr List[DialogNodeOutputTextValuesElement] values: (optional) A list of one - or more objects defining text responses. Required when **response_type**=`text`. - :attr str selection_policy: (optional) How a response is selected from the list, - if more than one response is specified. Valid only when - **response_type**=`text`. - :attr str delimiter: (optional) The delimiter to use as a separator between - responses when `selection_policy`=`multiline`. - :attr int time: (optional) How long to pause, in milliseconds. The valid values - are from 0 to 10000. Valid only when **response_type**=`pause`. - :attr bool typing: (optional) Whether to send a "user is typing" event during - the pause. Ignored if the channel does not support this event. Valid only when - **response_type**=`pause`. - :attr str source: (optional) The URL of the image. Required when - **response_type**=`image`. - :attr str title: (optional) An optional title to show before the response. Valid - only when **response_type**=`image` or `option`. - :attr str description: (optional) An optional description to show with the - response. Valid only when **response_type**=`image` or `option`. - :attr str preference: (optional) The preferred type of control to display, if - supported by the channel. Valid only when **response_type**=`option`. - :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of - objects describing the options from which the user can choose. You can include - up to 20 options. Required when **response_type**=`option`. - :attr str message_to_human_agent: (optional) An optional message to be sent to - the human agent who will be taking over the conversation. Valid only when - **reponse_type**=`connect_to_agent`. - :attr str query: (optional) The text of the search query. This can be either a - natural-language query or a query that uses the Discovery query language syntax, - depending on the value of the **query_type** property. For more information, see - the [Discovery service - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators). - Required when **response_type**=`search_skill`. - :attr str query_type: (optional) The type of the search query. Required when - **response_type**=`search_skill`. - :attr str filter: (optional) An optional filter that narrows the set of - documents to be searched. For more information, see the [Discovery service - documentation]([Discovery service - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). - :attr str discovery_version: (optional) The version of the Discovery service API - to use for the query. + :attr dict target: (optional) """ - def __init__(self, - response_type: str, - *, - values: List['DialogNodeOutputTextValuesElement'] = None, - selection_policy: str = None, - delimiter: str = None, - time: int = None, - typing: bool = None, - source: str = None, - title: str = None, - description: str = None, - preference: str = None, - options: List['DialogNodeOutputOptionsElement'] = None, - message_to_human_agent: str = None, - query: str = None, - query_type: str = None, - filter: str = None, - discovery_version: str = None) -> None: + def __init__(self, *, target: dict = None) -> None: """ - Initialize a DialogNodeOutputGeneric object. + Initialize a DialogNodeOutputConnectToAgentTransferInfo object. - :param str response_type: The type of response returned by the dialog node. - The specified response type must be supported by the client application or - channel. - **Note:** The **search_skill** response type is used only by the v2 runtime - API. - :param List[DialogNodeOutputTextValuesElement] values: (optional) A list of - one or more objects defining text responses. Required when - **response_type**=`text`. - :param str selection_policy: (optional) How a response is selected from the - list, if more than one response is specified. Valid only when - **response_type**=`text`. - :param str delimiter: (optional) The delimiter to use as a separator - between responses when `selection_policy`=`multiline`. - :param int time: (optional) How long to pause, in milliseconds. The valid - values are from 0 to 10000. Valid only when **response_type**=`pause`. - :param bool typing: (optional) Whether to send a "user is typing" event - during the pause. Ignored if the channel does not support this event. Valid - only when **response_type**=`pause`. - :param str source: (optional) The URL of the image. Required when - **response_type**=`image`. - :param str title: (optional) An optional title to show before the response. - Valid only when **response_type**=`image` or `option`. - :param str description: (optional) An optional description to show with the - response. Valid only when **response_type**=`image` or `option`. - :param str preference: (optional) The preferred type of control to display, - if supported by the channel. Valid only when **response_type**=`option`. - :param List[DialogNodeOutputOptionsElement] options: (optional) An array of - objects describing the options from which the user can choose. You can - include up to 20 options. Required when **response_type**=`option`. - :param str message_to_human_agent: (optional) An optional message to be - sent to the human agent who will be taking over the conversation. Valid - only when **reponse_type**=`connect_to_agent`. - :param str query: (optional) The text of the search query. This can be - either a natural-language query or a query that uses the Discovery query - language syntax, depending on the value of the **query_type** property. For - more information, see the [Discovery service - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators). - Required when **response_type**=`search_skill`. - :param str query_type: (optional) The type of the search query. Required - when **response_type**=`search_skill`. - :param str filter: (optional) An optional filter that narrows the set of - documents to be searched. For more information, see the [Discovery service - documentation]([Discovery service - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). - :param str discovery_version: (optional) The version of the Discovery - service API to use for the query. + :param dict target: (optional) """ - self.response_type = response_type - self.values = values - self.selection_policy = selection_policy - self.delimiter = delimiter - self.time = time - self.typing = typing - self.source = source - self.title = title - self.description = description - self.preference = preference - self.options = options - self.message_to_human_agent = message_to_human_agent - self.query = query - self.query_type = query_type - self.filter = filter - self.discovery_version = discovery_version + self.target = target @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputGeneric': - """Initialize a DialogNodeOutputGeneric object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': + """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" args = {} - valid_keys = [ - 'response_type', 'values', 'selection_policy', 'delimiter', 'time', - 'typing', 'source', 'title', 'description', 'preference', 'options', - 'message_to_human_agent', 'query', 'query_type', 'filter', - 'discovery_version' - ] + valid_keys = ['target'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputGeneric: ' + 'Unrecognized keys detected in dictionary for class DialogNodeOutputConnectToAgentTransferInfo: ' + ', '.join(bad_keys)) - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') - else: - raise ValueError( - 'Required property \'response_type\' not present in DialogNodeOutputGeneric JSON' - ) - if 'values' in _dict: - args['values'] = [ - DialogNodeOutputTextValuesElement._from_dict(x) - for x in (_dict.get('values')) - ] - if 'selection_policy' in _dict: - args['selection_policy'] = _dict.get('selection_policy') - if 'delimiter' in _dict: - args['delimiter'] = _dict.get('delimiter') - if 'time' in _dict: - args['time'] = _dict.get('time') - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'source' in _dict: - args['source'] = _dict.get('source') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: - args['options'] = [ - DialogNodeOutputOptionsElement._from_dict(x) - for x in (_dict.get('options')) - ] - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'query' in _dict: - args['query'] = _dict.get('query') - if 'query_type' in _dict: - args['query_type'] = _dict.get('query_type') - if 'filter' in _dict: - args['filter'] = _dict.get('filter') - if 'discovery_version' in _dict: - args['discovery_version'] = _dict.get('discovery_version') + if 'target' in _dict: + args['target'] = _dict.get('target') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputGeneric object from a json dictionary.""" + """Initialize a DialogNodeOutputConnectToAgentTransferInfo 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, 'response_type') and self.response_type is not None: - _dict['response_type'] = self.response_type - if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x._to_dict() for x in self.values] - if hasattr(self, - 'selection_policy') and self.selection_policy is not None: - _dict['selection_policy'] = self.selection_policy - if hasattr(self, 'delimiter') and self.delimiter is not None: - _dict['delimiter'] = self.delimiter - if hasattr(self, 'time') and self.time is not None: - _dict['time'] = self.time - if hasattr(self, 'typing') and self.typing is not None: - _dict['typing'] = self.typing - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'preference') and self.preference is not None: - _dict['preference'] = self.preference - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x._to_dict() for x in self.options] - if hasattr(self, 'message_to_human_agent' - ) and self.message_to_human_agent is not None: - _dict['message_to_human_agent'] = self.message_to_human_agent - if hasattr(self, 'query') and self.query is not None: - _dict['query'] = self.query - if hasattr(self, 'query_type') and self.query_type is not None: - _dict['query_type'] = self.query_type - if hasattr(self, 'filter') and self.filter is not None: - _dict['filter'] = self.filter - if hasattr(self, - 'discovery_version') and self.discovery_version is not None: - _dict['discovery_version'] = self.discovery_version + if hasattr(self, 'target') and self.target is not None: + _dict['target'] = self.target return _dict def _to_dict(self): @@ -4887,55 +5105,94 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputGeneric object.""" + """Return a `str` version of this DialogNodeOutputConnectToAgentTransferInfo object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeOutputGeneric') -> bool: + def __eq__(self, + other: 'DialogNodeOutputConnectToAgentTransferInfo') -> 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: 'DialogNodeOutputGeneric') -> bool: + def __ne__(self, + other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - **Note:** The **search_skill** response type is used only by the v2 runtime API. - """ - TEXT = "text" - PAUSE = "pause" - IMAGE = "image" - OPTION = "option" - CONNECT_TO_AGENT = "connect_to_agent" - SEARCH_SKILL = "search_skill" - class SelectionPolicyEnum(Enum): - """ - How a response is selected from the list, if more than one response is specified. - Valid only when **response_type**=`text`. - """ - SEQUENTIAL = "sequential" - RANDOM = "random" - MULTILINE = "multiline" +class DialogNodeOutputGeneric(): + """ + DialogNodeOutputGeneric. - class PreferenceEnum(Enum): - """ - The preferred type of control to display, if supported by the channel. Valid only - when **response_type**=`option`. - """ - DROPDOWN = "dropdown" - BUTTON = "button" + """ - class QueryTypeEnum(Enum): + def __init__(self) -> None: """ - The type of the search query. Required when **response_type**=`search_skill`. + Initialize a DialogNodeOutputGeneric object. + """ - NATURAL_LANGUAGE = "natural_language" - DISCOVERY_QUERY_LANGUAGE = "discovery_query_language" + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputGeneric': + """Initialize a DialogNodeOutputGeneric object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class '{0}'. The discriminator value should map to a valid subclass: {1}".format( + cls.__name__, ", ".join([ + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a DialogNodeOutputGeneric object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'connect_to_agent'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent' + mapping[ + 'image'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage' + mapping[ + 'option'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption' + mapping[ + 'pause'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause' + mapping[ + 'search_skill'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill' + mapping[ + 'text'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in DialogNodeOutputGeneric JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) class DialogNodeOutputModifiers(): @@ -5337,9 +5594,8 @@ class DialogSuggestion(): :attr DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. - :attr DialogSuggestionOutput output: (optional) The dialog output that will be - returned from the Watson Assistant service if the user selects the corresponding - option. + :attr dict output: (optional) The dialog output that will be returned from the + Watson Assistant service if the user selects the corresponding option. :attr str dialog_node: (optional) The ID of the dialog node that the **label** property is taken from. The **label** property is populated using the value of the dialog node's **user_label** property. @@ -5349,7 +5605,7 @@ def __init__(self, label: str, value: 'DialogSuggestionValue', *, - output: 'DialogSuggestionOutput' = None, + output: dict = None, dialog_node: str = None) -> None: """ Initialize a DialogSuggestion object. @@ -5360,9 +5616,8 @@ def __init__(self, :param DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. - :param DialogSuggestionOutput output: (optional) The dialog output that - will be returned from the Watson Assistant service if the user selects the - corresponding option. + :param dict output: (optional) The dialog output that will be returned from + the Watson Assistant service if the user selects the corresponding option. :param str dialog_node: (optional) The ID of the dialog node that the **label** property is taken from. The **label** property is populated using the value of the dialog node's **user_label** property. @@ -5395,8 +5650,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': 'Required property \'value\' not present in DialogSuggestion JSON' ) if 'output' in _dict: - args['output'] = DialogSuggestionOutput._from_dict( - _dict.get('output')) + args['output'] = _dict.get('output') if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') return cls(**args) @@ -5414,7 +5668,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'value') and self.value is not None: _dict['value'] = self.value._to_dict() if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output._to_dict() + _dict['output'] = self.output if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node return _dict @@ -5438,527 +5692,186 @@ def __ne__(self, other: 'DialogSuggestion') -> bool: return not self == other -class DialogSuggestionOutput(): +class DialogSuggestionValue(): """ - The dialog output that will be returned from the Watson Assistant service if the user - selects the corresponding option. + An object defining the message input, intents, and entities to be sent to the Watson + Assistant service if the user selects the corresponding disambiguation option. - :attr List[str] nodes_visited: (optional) An array of the nodes that were - triggered to create the response, in the order in which they were visited. This - information is useful for debugging and for tracing the path taken through the - node tree. - :attr List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array - of objects containing detailed diagnostic information about the nodes that were - triggered during processing of the input message. Included only if - **nodes_visited_details** is set to `true` in the message request. - :attr List[str] text: An array of responses to the user. - :attr List[DialogSuggestionResponseGeneric] generic: (optional) Output intended - for any channel. It is the responsibility of the client application to implement - the supported response types. + :attr MessageInput input: (optional) An input object that includes the input + text. + :attr List[RuntimeIntent] intents: (optional) An array of intents to be sent + along with the user input. + :attr List[RuntimeEntity] entities: (optional) An array of entities to be sent + along with the user input. """ def __init__(self, - text: List[str], *, - nodes_visited: List[str] = None, - nodes_visited_details: List['DialogNodeVisitedDetails'] = None, - generic: List['DialogSuggestionResponseGeneric'] = None, - **kwargs) -> None: + input: 'MessageInput' = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None) -> None: """ - Initialize a DialogSuggestionOutput object. + Initialize a DialogSuggestionValue object. - :param List[str] text: An array of responses to the user. - :param List[str] nodes_visited: (optional) An array of the nodes that were - triggered to create the response, in the order in which they were visited. - This information is useful for debugging and for tracing the path taken - through the node tree. - :param List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An - array of objects containing detailed diagnostic information about the nodes - that were triggered during processing of the input message. Included only - if **nodes_visited_details** is set to `true` in the message request. - :param List[DialogSuggestionResponseGeneric] generic: (optional) Output - intended for any channel. It is the responsibility of the client - application to implement the supported response types. - :param **kwargs: (optional) Any additional properties. + :param MessageInput input: (optional) An input object that includes the + input text. + :param List[RuntimeIntent] intents: (optional) An array of intents to be + sent along with the user input. + :param List[RuntimeEntity] entities: (optional) An array of entities to be + sent along with the user input. """ - self.nodes_visited = nodes_visited - self.nodes_visited_details = nodes_visited_details - self.text = text - self.generic = generic - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.input = input + self.intents = intents + self.entities = entities @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogSuggestionOutput': - """Initialize a DialogSuggestionOutput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': + """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - xtra = _dict.copy() - if 'nodes_visited' in _dict: - args['nodes_visited'] = _dict.get('nodes_visited') - del xtra['nodes_visited'] - if 'nodes_visited_details' in _dict: - args['nodes_visited_details'] = [ - DialogNodeVisitedDetails._from_dict(x) - for x in (_dict.get('nodes_visited_details')) - ] - del xtra['nodes_visited_details'] - if 'text' in _dict: - args['text'] = _dict.get('text') - del xtra['text'] - else: + valid_keys = ['input', 'intents', 'entities'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: raise ValueError( - 'Required property \'text\' not present in DialogSuggestionOutput JSON' - ) - if 'generic' in _dict: - args['generic'] = [ - DialogSuggestionResponseGeneric._from_dict(x) - for x in (_dict.get('generic')) + 'Unrecognized keys detected in dictionary for class DialogSuggestionValue: ' + + ', '.join(bad_keys)) + if 'input' in _dict: + args['input'] = MessageInput._from_dict(_dict.get('input')) + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + ] + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) ] - del xtra['generic'] - args.update(xtra) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogSuggestionOutput object from a json dictionary.""" + """Initialize a DialogSuggestionValue 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, 'nodes_visited') and self.nodes_visited is not None: - _dict['nodes_visited'] = self.nodes_visited - if hasattr(self, 'nodes_visited_details' - ) and self.nodes_visited_details is not None: - _dict['nodes_visited_details'] = [ - x._to_dict() for x in self.nodes_visited_details - ] - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x._to_dict() for x in self.generic] - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + if hasattr(self, 'input') and self.input is not None: + _dict['input'] = self.input._to_dict() + if hasattr(self, 'intents') and self.intents is not None: + _dict['intents'] = [x._to_dict() for x in self.intents] + if hasattr(self, 'entities') and self.entities is not None: + _dict['entities'] = [x._to_dict() for x in self.entities] return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = { - 'nodes_visited', 'nodes_visited_details', 'text', 'generic' - } - if not hasattr(self, '_additionalProperties'): - super(DialogSuggestionOutput, - self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(DialogSuggestionOutput, self).__setattr__(name, value) - def __str__(self) -> str: - """Return a `str` version of this DialogSuggestionOutput object.""" + """Return a `str` version of this DialogSuggestionValue object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'DialogSuggestionOutput') -> bool: + def __eq__(self, other: 'DialogSuggestionValue') -> 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: 'DialogSuggestionOutput') -> bool: + def __ne__(self, other: 'DialogSuggestionValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogSuggestionResponseGeneric(): +class Entity(): """ - DialogSuggestionResponseGeneric. + Entity. - :attr str response_type: The type of response returned by the dialog node. The - specified response type must be supported by the client application or channel. - **Note:** The **search_skill** response type is is used only by the v2 runtime - API. - :attr str text: (optional) The text of the response. - :attr int time: (optional) How long to pause, in milliseconds. - :attr bool typing: (optional) Whether to send a "user is typing" event during - the pause. - :attr str source: (optional) The URL of the image. - :attr str title: (optional) The title or introductory text to show before the - response. - :attr str description: (optional) The description to show with the the response. - :attr str preference: (optional) The preferred type of control to display. - :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of - objects describing the options from which the user can choose. - :attr str message_to_human_agent: (optional) A message to be sent to the human - agent who will be taking over the conversation. - :attr str topic: (optional) A label identifying the topic of the conversation, - derived from the **title** property of the relevant node. - :attr str dialog_node: (optional) The ID of the dialog node that the **topic** - property is taken from. The **topic** property is populated using the value of - the dialog node's **title** property. + :attr str entity: The name of the entity. This string must conform to the + following restrictions: + - It can contain only Unicode alphanumeric, underscore, and hyphen characters. + - If you specify an entity name beginning with the reserved prefix `sys-`, it + must be the name of a system entity that you want to enable. (Any entity content + specified with the request is ignored.). + :attr str description: (optional) The description of the entity. This string + cannot contain carriage return, newline, or tab characters. + :attr dict metadata: (optional) Any metadata related to the entity. + :attr bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. + :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. + :attr List[Value] values: (optional) An array of objects describing the entity + values. """ def __init__(self, - response_type: str, + entity: str, *, - text: str = None, - time: int = None, - typing: bool = None, - source: str = None, - title: str = None, description: str = None, - preference: str = None, - options: List['DialogNodeOutputOptionsElement'] = None, - message_to_human_agent: str = None, - topic: str = None, - dialog_node: str = None) -> None: + metadata: dict = None, + fuzzy_match: bool = None, + created: datetime = None, + updated: datetime = None, + values: List['Value'] = None) -> None: """ - Initialize a DialogSuggestionResponseGeneric object. + Initialize a Entity object. - :param str response_type: The type of response returned by the dialog node. - The specified response type must be supported by the client application or - channel. - **Note:** The **search_skill** response type is is used only by the v2 - runtime API. - :param str text: (optional) The text of the response. - :param int time: (optional) How long to pause, in milliseconds. - :param bool typing: (optional) Whether to send a "user is typing" event - during the pause. - :param str source: (optional) The URL of the image. - :param str title: (optional) The title or introductory text to show before - the response. - :param str description: (optional) The description to show with the the - response. - :param str preference: (optional) The preferred type of control to display. - :param List[DialogNodeOutputOptionsElement] options: (optional) An array of - objects describing the options from which the user can choose. - :param str message_to_human_agent: (optional) A message to be sent to the - human agent who will be taking over the conversation. - :param str topic: (optional) A label identifying the topic of the - conversation, derived from the **title** property of the relevant node. - :param str dialog_node: (optional) The ID of the dialog node that the - **topic** property is taken from. The **topic** property is populated using - the value of the dialog node's **title** property. + :param str entity: The name of the entity. This string must conform to the + following restrictions: + - It can contain only Unicode alphanumeric, underscore, and hyphen + characters. + - If you specify an entity name beginning with the reserved prefix `sys-`, + it must be the name of a system entity that you want to enable. (Any entity + content specified with the request is ignored.). + :param str description: (optional) The description of the entity. This + string cannot contain carriage return, newline, or tab characters. + :param dict metadata: (optional) Any metadata related to the entity. + :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the + entity. + :param datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. + :param List[Value] values: (optional) An array of objects describing the + entity values. """ - self.response_type = response_type - self.text = text - self.time = time - self.typing = typing - self.source = source - self.title = title + self.entity = entity self.description = description - self.preference = preference - self.options = options - self.message_to_human_agent = message_to_human_agent - self.topic = topic - self.dialog_node = dialog_node + self.metadata = metadata + self.fuzzy_match = fuzzy_match + self.created = created + self.updated = updated + self.values = values @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogSuggestionResponseGeneric': - """Initialize a DialogSuggestionResponseGeneric object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Entity': + """Initialize a Entity object from a json dictionary.""" args = {} valid_keys = [ - 'response_type', 'text', 'time', 'typing', 'source', 'title', - 'description', 'preference', 'options', 'message_to_human_agent', - 'topic', 'dialog_node' + 'entity', 'description', 'metadata', 'fuzzy_match', 'created', + 'updated', 'values' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogSuggestionResponseGeneric: ' - + ', '.join(bad_keys)) - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + 'Unrecognized keys detected in dictionary for class Entity: ' + + ', '.join(bad_keys)) + if 'entity' in _dict: + args['entity'] = _dict.get('entity') else: raise ValueError( - 'Required property \'response_type\' not present in DialogSuggestionResponseGeneric JSON' - ) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'time' in _dict: - args['time'] = _dict.get('time') - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'source' in _dict: - args['source'] = _dict.get('source') - if 'title' in _dict: - args['title'] = _dict.get('title') + 'Required property \'entity\' not present in Entity JSON') if 'description' in _dict: args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: - args['options'] = [ - DialogNodeOutputOptionsElement._from_dict(x) - for x in (_dict.get('options')) - ] - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'topic' in _dict: - args['topic'] = _dict.get('topic') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DialogSuggestionResponseGeneric 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, 'response_type') and self.response_type is not None: - _dict['response_type'] = self.response_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'time') and self.time is not None: - _dict['time'] = self.time - if hasattr(self, 'typing') and self.typing is not None: - _dict['typing'] = self.typing - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'preference') and self.preference is not None: - _dict['preference'] = self.preference - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x._to_dict() for x in self.options] - if hasattr(self, 'message_to_human_agent' - ) and self.message_to_human_agent is not None: - _dict['message_to_human_agent'] = self.message_to_human_agent - if hasattr(self, 'topic') and self.topic is not None: - _dict['topic'] = self.topic - if hasattr(self, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node - 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 DialogSuggestionResponseGeneric object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other: 'DialogSuggestionResponseGeneric') -> 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: 'DialogSuggestionResponseGeneric') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ResponseTypeEnum(Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - **Note:** The **search_skill** response type is is used only by the v2 runtime - API. - """ - TEXT = "text" - PAUSE = "pause" - IMAGE = "image" - OPTION = "option" - CONNECT_TO_AGENT = "connect_to_agent" - SEARCH_SKILL = "search_skill" - - class PreferenceEnum(Enum): - """ - The preferred type of control to display. - """ - DROPDOWN = "dropdown" - BUTTON = "button" - - -class DialogSuggestionValue(): - """ - An object defining the message input, intents, and entities to be sent to the Watson - Assistant service if the user selects the corresponding disambiguation option. - - :attr MessageInput input: (optional) An input object that includes the input - text. - :attr List[RuntimeIntent] intents: (optional) An array of intents to be sent - along with the user input. - :attr List[RuntimeEntity] entities: (optional) An array of entities to be sent - along with the user input. - """ - - def __init__(self, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None) -> None: - """ - Initialize a DialogSuggestionValue object. - - :param MessageInput input: (optional) An input object that includes the - input text. - :param List[RuntimeIntent] intents: (optional) An array of intents to be - sent along with the user input. - :param List[RuntimeEntity] entities: (optional) An array of entities to be - sent along with the user input. - """ - self.input = input - self.intents = intents - self.entities = entities - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': - """Initialize a DialogSuggestionValue object from a json dictionary.""" - args = {} - valid_keys = ['input', 'intents', 'entities'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogSuggestionValue: ' - + ', '.join(bad_keys)) - if 'input' in _dict: - args['input'] = MessageInput._from_dict(_dict.get('input')) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DialogSuggestionValue 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, 'input') and self.input is not None: - _dict['input'] = self.input._to_dict() - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] - 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 DialogSuggestionValue object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other: 'DialogSuggestionValue') -> 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: 'DialogSuggestionValue') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Entity(): - """ - Entity. - - :attr str entity: The name of the entity. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - - If you specify an entity name beginning with the reserved prefix `sys-`, it - must be the name of a system entity that you want to enable. (Any entity content - specified with the request is ignored.). - :attr str description: (optional) The description of the entity. This string - cannot contain carriage return, newline, or tab characters. - :attr dict metadata: (optional) Any metadata related to the entity. - :attr bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :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. - :attr List[Value] values: (optional) An array of objects describing the entity - values. - """ - - def __init__(self, - entity: str, - *, - description: str = None, - metadata: dict = None, - fuzzy_match: bool = None, - created: datetime = None, - updated: datetime = None, - values: List['Value'] = None) -> None: - """ - Initialize a Entity object. - - :param str entity: The name of the entity. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, underscore, and hyphen - characters. - - If you specify an entity name beginning with the reserved prefix `sys-`, - it must be the name of a system entity that you want to enable. (Any entity - content specified with the request is ignored.). - :param str description: (optional) The description of the entity. This - string cannot contain carriage return, newline, or tab characters. - :param dict metadata: (optional) Any metadata related to the entity. - :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the - entity. - :param datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. - :param List[Value] values: (optional) An array of objects describing the - entity values. - """ - self.entity = entity - self.description = description - self.metadata = metadata - self.fuzzy_match = fuzzy_match - self.created = created - self.updated = updated - self.values = values - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Entity': - """Initialize a Entity object from a json dictionary.""" - args = {} - valid_keys = [ - 'entity', 'description', 'metadata', 'fuzzy_match', 'created', - 'updated', 'values' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Entity: ' + - ', '.join(bad_keys)) - if 'entity' in _dict: - args['entity'] = _dict.get('entity') - else: - raise ValueError( - 'Required property \'entity\' not present in Entity JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'fuzzy_match' in _dict: - args['fuzzy_match'] = _dict.get('fuzzy_match') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'values' in _dict: - args['values'] = [ - Value._from_dict(x) for x in (_dict.get('values')) + if 'metadata' in _dict: + args['metadata'] = _dict.get('metadata') + if 'fuzzy_match' in _dict: + args['fuzzy_match'] = _dict.get('fuzzy_match') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + if 'values' in _dict: + args['values'] = [ + Value._from_dict(x) for x in (_dict.get('values')) ] return cls(**args) @@ -7761,7 +7674,9 @@ class Pagination(): :attr str refresh_url: The URL that will return the same page of results. :attr str next_url: (optional) The URL that will return the next page of results. - :attr int total: (optional) Reserved for future use. + :attr int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the current + page. :attr int matched: (optional) Reserved for future use. :attr str refresh_cursor: (optional) A token identifying the current page of results. @@ -7782,7 +7697,9 @@ def __init__(self, :param str refresh_url: The URL that will return the same page of results. :param str next_url: (optional) The URL that will return the next page of results. - :param int total: (optional) Reserved for future use. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the + current page. :param int matched: (optional) Reserved for future use. :param str refresh_cursor: (optional) A token identifying the current page of results. @@ -8536,14 +8453,1269 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityRole object from a json dictionary.""" + """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. + + :attr str intent: The name of the recognized intent. + :attr float confidence: A decimal percentage that represents Watson's confidence + in the intent. + """ + + def __init__(self, intent: str, confidence: float) -> None: + """ + Initialize a RuntimeIntent object. + + :param str intent: The name of the recognized intent. + :param float confidence: A decimal percentage that represents Watson's + confidence in the intent. + """ + self.intent = intent + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': + """Initialize a RuntimeIntent object from a json dictionary.""" + args = {} + valid_keys = ['intent', 'confidence'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeIntent: ' + + ', '.join(bad_keys)) + if 'intent' in _dict: + args['intent'] = _dict.get('intent') + else: + raise ValueError( + 'Required property \'intent\' not present in RuntimeIntent JSON' + ) + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + else: + raise ValueError( + 'Required property \'confidence\' not present in RuntimeIntent JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeIntent 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, 'intent') and self.intent is not None: + _dict['intent'] = self.intent + 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 RuntimeIntent object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeIntent') -> 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: 'RuntimeIntent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGeneric(): + """ + RuntimeResponseGeneric. + + """ + + def __init__(self) -> None: + """ + Initialize a RuntimeResponseGeneric object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class '{0}'. The discriminator value should map to a valid subclass: {1}".format( + cls.__name__, ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' + mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' + mapping[ + 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' + mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class Synonym(): + """ + Synonym. + + :attr str synonym: The text of the synonym. This string must conform to the + following restrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + :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. + """ + + def __init__(self, + synonym: str, + *, + created: datetime = None, + updated: datetime = None) -> None: + """ + Initialize a Synonym object. + + :param str synonym: The text of the synonym. 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 datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. + """ + self.synonym = synonym + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Synonym': + """Initialize a Synonym object from a json dictionary.""" + args = {} + valid_keys = ['synonym', 'created', 'updated'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Synonym: ' + + ', '.join(bad_keys)) + if 'synonym' in _dict: + args['synonym'] = _dict.get('synonym') + else: + raise ValueError( + 'Required property \'synonym\' not present in Synonym JSON') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Synonym 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, 'synonym') and self.synonym is not None: + _dict['synonym'] = self.synonym + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'updated') and self.updated is not None: + _dict['updated'] = datetime_to_string(self.updated) + 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 Synonym object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Synonym') -> 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: 'Synonym') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SynonymCollection(): + """ + SynonymCollection. + + :attr List[Synonym] synonyms: An array of synonyms. + :attr Pagination pagination: The pagination data for the returned objects. + """ + + def __init__(self, synonyms: List['Synonym'], + pagination: 'Pagination') -> None: + """ + Initialize a SynonymCollection object. + + :param List[Synonym] synonyms: An array of synonyms. + :param Pagination pagination: The pagination data for the returned objects. + """ + self.synonyms = synonyms + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SynonymCollection': + """Initialize a SynonymCollection object from a json dictionary.""" + args = {} + valid_keys = ['synonyms', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class SynonymCollection: ' + + ', '.join(bad_keys)) + if 'synonyms' in _dict: + args['synonyms'] = [ + Synonym._from_dict(x) for x in (_dict.get('synonyms')) + ] + else: + raise ValueError( + 'Required property \'synonyms\' not present in SynonymCollection JSON' + ) + if 'pagination' in _dict: + args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in SynonymCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SynonymCollection 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, 'synonyms') and self.synonyms is not None: + _dict['synonyms'] = [x._to_dict() for x in self.synonyms] + if hasattr(self, 'pagination') and self.pagination is not None: + _dict['pagination'] = self.pagination._to_dict() + 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 SynonymCollection object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'SynonymCollection') -> 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: 'SynonymCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SystemResponse(): + """ + For internal use only. + + """ + + def __init__(self, **kwargs) -> None: + """ + Initialize a SystemResponse object. + + :param **kwargs: (optional) Any additional properties. + """ + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SystemResponse': + """Initialize a SystemResponse object from a json dictionary.""" + args = {} + xtra = _dict.copy() + args.update(xtra) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SystemResponse 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, '_additionalProperties'): + for _key in self._additionalProperties: + _value = getattr(self, _key, None) + if _value is not None: + _dict[_key] = _value + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def __setattr__(self, name: str, value: object) -> None: + properties = {} + if not hasattr(self, '_additionalProperties'): + super(SystemResponse, self).__setattr__('_additionalProperties', + set()) + if name not in properties: + self._additionalProperties.add(name) + super(SystemResponse, self).__setattr__(name, value) + + def __str__(self) -> str: + """Return a `str` version of this SystemResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'SystemResponse') -> 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: 'SystemResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Value(): + """ + Value. + + :attr str value: The text of the entity value. This string must conform to the + following restrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + :attr dict metadata: (optional) Any metadata related to the entity value. + :attr str type: Specifies the type of entity value. + :attr List[str] synonyms: (optional) An array of synonyms for the entity value. + A value can specify either synonyms or patterns (depending on the value type), + but not both. A synonym must conform to the following resrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + :attr List[str] patterns: (optional) An array of patterns for the 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/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. + """ + + def __init__(self, + value: str, + type: str, + *, + metadata: dict = None, + synonyms: List[str] = None, + patterns: List[str] = None, + created: datetime = None, + updated: datetime = None) -> None: + """ + Initialize a Value object. + + :param str value: The text of the entity value. 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 str type: Specifies the type of entity value. + :param dict metadata: (optional) Any metadata related to the entity value. + :param List[str] synonyms: (optional) An array of synonyms for the entity + value. A value can specify either synonyms or patterns (depending on the + value type), but not both. A synonym must conform to the following + resrictions: + - It cannot contain carriage return, newline, or tab characters. + - It cannot consist of only whitespace characters. + :param List[str] patterns: (optional) An array of patterns for the 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/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 + update to the object. + """ + self.value = value + self.metadata = metadata + self.type = type + self.synonyms = synonyms + self.patterns = patterns + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Value': + """Initialize a Value object from a json dictionary.""" + args = {} + valid_keys = [ + 'value', 'metadata', 'type', 'synonyms', 'patterns', 'created', + 'updated' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Value: ' + + ', '.join(bad_keys)) + if 'value' in _dict: + args['value'] = _dict.get('value') + else: + raise ValueError( + 'Required property \'value\' not present in Value JSON') + if 'metadata' in _dict: + args['metadata'] = _dict.get('metadata') + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in Value JSON') + if 'synonyms' in _dict: + args['synonyms'] = _dict.get('synonyms') + if 'patterns' in _dict: + args['patterns'] = _dict.get('patterns') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Value 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, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'synonyms') and self.synonyms is not None: + _dict['synonyms'] = self.synonyms + if hasattr(self, 'patterns') and self.patterns is not None: + _dict['patterns'] = self.patterns + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'updated') and self.updated is not None: + _dict['updated'] = datetime_to_string(self.updated) + 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 Value object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Value') -> 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: 'Value') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(Enum): + """ + Specifies the type of entity value. + """ + SYNONYMS = "synonyms" + PATTERNS = "patterns" + + +class ValueCollection(): + """ + ValueCollection. + + :attr List[Value] values: An array of entity values. + :attr Pagination pagination: The pagination data for the returned objects. + """ + + def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: + """ + Initialize a ValueCollection object. + + :param List[Value] values: An array of entity values. + :param Pagination pagination: The pagination data for the returned objects. + """ + self.values = values + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ValueCollection': + """Initialize a ValueCollection object from a json dictionary.""" + args = {} + valid_keys = ['values', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class ValueCollection: ' + + ', '.join(bad_keys)) + if 'values' in _dict: + args['values'] = [ + Value._from_dict(x) for x in (_dict.get('values')) + ] + else: + raise ValueError( + 'Required property \'values\' not present in ValueCollection JSON' + ) + if 'pagination' in _dict: + args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in ValueCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ValueCollection 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, 'values') and self.values is not None: + _dict['values'] = [x._to_dict() for x in self.values] + if hasattr(self, 'pagination') and self.pagination is not None: + _dict['pagination'] = self.pagination._to_dict() + 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 ValueCollection object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'ValueCollection') -> 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: 'ValueCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Webhook(): + """ + A webhook that can be used by dialog nodes to make programmatic calls to an external + function. + **Note:** Currently, only a single webhook named `main_webhook` is supported. + + :attr str url: The URL for the external service or application to which you want + to send HTTP POST requests. + :attr str name: The name of the webhook. Currently, `main_webhook` is the only + supported value. + :attr List[WebhookHeader] headers: (optional) An optional array of HTTP headers + to pass with the HTTP request. + """ + + def __init__(self, + url: str, + name: str, + *, + headers: List['WebhookHeader'] = None) -> None: + """ + Initialize a Webhook object. + + :param str url: The URL for the external service or application to which + you want to send HTTP POST requests. + :param str name: The name of the webhook. Currently, `main_webhook` is the + only supported value. + :param List[WebhookHeader] headers: (optional) An optional array of HTTP + headers to pass with the HTTP request. + """ + self.url = url + self.name = name + self.headers = headers + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Webhook': + """Initialize a Webhook object from a json dictionary.""" + args = {} + valid_keys = ['url', 'name', 'headers'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Webhook: ' + + ', '.join(bad_keys)) + if 'url' in _dict: + args['url'] = _dict.get('url') + else: + raise ValueError( + 'Required property \'url\' not present in Webhook JSON') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in Webhook JSON') + if 'headers' in _dict: + args['headers'] = [ + WebhookHeader._from_dict(x) for x in (_dict.get('headers')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Webhook 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, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'headers') and self.headers is not None: + _dict['headers'] = [x._to_dict() for x in self.headers] + 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 Webhook object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Webhook') -> 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: 'Webhook') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class WebhookHeader(): + """ + A key/value pair defining an HTTP header and a value. + + :attr str name: The name of an HTTP header (for example, `Authorization`). + :attr str value: The value of an HTTP header. + """ + + def __init__(self, name: str, value: str) -> None: + """ + Initialize a WebhookHeader object. + + :param str name: The name of an HTTP header (for example, `Authorization`). + :param str value: The value of an HTTP header. + """ + self.name = name + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WebhookHeader': + """Initialize a WebhookHeader object from a json dictionary.""" + args = {} + valid_keys = ['name', 'value'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class WebhookHeader: ' + + ', '.join(bad_keys)) + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in WebhookHeader JSON') + if 'value' in _dict: + args['value'] = _dict.get('value') + else: + raise ValueError( + 'Required property \'value\' not present in WebhookHeader JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WebhookHeader 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + 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 WebhookHeader object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'WebhookHeader') -> 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: 'WebhookHeader') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Workspace(): + """ + Workspace. + + :attr str name: The name of the workspace. This string cannot contain carriage + return, newline, or tab characters. + :attr str description: (optional) The description of the workspace. This string + cannot contain carriage return, newline, or tab characters. + :attr str language: The language of the workspace. + :attr str workspace_id: The workspace ID of the workspace. + :attr List[DialogNode] dialog_nodes: (optional) An array of objects describing + the dialog nodes in the workspace. + :attr List[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. + :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. + :attr dict metadata: (optional) Any metadata related to the workspace. + :attr bool learning_opt_out: Whether training data from the workspace (including + artifacts such as intents and entities) can be used by IBM for general service + improvements. `true` indicates that workspace training data is not to be used. + :attr WorkspaceSystemSettings system_settings: (optional) Global settings for + the workspace. + :attr str status: (optional) The current status of the workspace. + :attr List[Webhook] webhooks: (optional) + :attr List[Intent] intents: (optional) An array of intents. + :attr List[Entity] entities: (optional) An array of objects describing the + entities for the workspace. + """ + + def __init__(self, + name: str, + language: str, + workspace_id: str, + learning_opt_out: bool, + *, + description: str = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, + created: datetime = None, + updated: datetime = None, + metadata: dict = None, + system_settings: 'WorkspaceSystemSettings' = None, + status: str = None, + webhooks: List['Webhook'] = None, + intents: List['Intent'] = None, + entities: List['Entity'] = None) -> None: + """ + Initialize a Workspace object. + + :param str name: The name of the workspace. This string cannot contain + carriage return, newline, or tab characters. + :param str language: The language of the workspace. + :param str workspace_id: The workspace ID of the workspace. + :param bool learning_opt_out: Whether training data from the workspace + (including artifacts such as intents and entities) can be used by IBM for + general service improvements. `true` indicates that workspace training data + is not to be used. + :param str description: (optional) The description of the workspace. This + string cannot contain carriage return, newline, or tab characters. + :param List[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. + :param List[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. + :param datetime created: (optional) The timestamp for creation of the + object. + :param datetime updated: (optional) The timestamp for the most recent + update to the object. + :param dict metadata: (optional) Any metadata related to the workspace. + :param WorkspaceSystemSettings system_settings: (optional) Global settings + for the workspace. + :param str status: (optional) The current status of the workspace. + :param List[Webhook] webhooks: (optional) + :param List[Intent] intents: (optional) An array of intents. + :param List[Entity] entities: (optional) An array of objects describing the + entities for the workspace. + """ + self.name = name + self.description = description + self.language = language + self.workspace_id = workspace_id + self.dialog_nodes = dialog_nodes + self.counterexamples = counterexamples + self.created = created + self.updated = updated + self.metadata = metadata + self.learning_opt_out = learning_opt_out + self.system_settings = system_settings + self.status = status + self.webhooks = webhooks + self.intents = intents + self.entities = entities + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Workspace': + """Initialize a Workspace object from a json dictionary.""" + args = {} + valid_keys = [ + 'name', 'description', 'language', 'workspace_id', 'dialog_nodes', + 'counterexamples', 'created', 'updated', 'metadata', + 'learning_opt_out', 'system_settings', 'status', 'webhooks', + 'intents', 'entities' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Workspace: ' + + ', '.join(bad_keys)) + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in Workspace JSON') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'language' in _dict: + args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in Workspace JSON') + if 'workspace_id' in _dict: + args['workspace_id'] = _dict.get('workspace_id') + else: + raise ValueError( + 'Required property \'workspace_id\' not present in Workspace JSON' + ) + if 'dialog_nodes' in _dict: + args['dialog_nodes'] = [ + DialogNode._from_dict(x) for x in (_dict.get('dialog_nodes')) + ] + if 'counterexamples' in _dict: + args['counterexamples'] = [ + Counterexample._from_dict(x) + for x in (_dict.get('counterexamples')) + ] + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + if 'metadata' in _dict: + args['metadata'] = _dict.get('metadata') + if 'learning_opt_out' in _dict: + args['learning_opt_out'] = _dict.get('learning_opt_out') + else: + raise ValueError( + 'Required property \'learning_opt_out\' not present in Workspace JSON' + ) + if 'system_settings' in _dict: + args['system_settings'] = WorkspaceSystemSettings._from_dict( + _dict.get('system_settings')) + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'webhooks' in _dict: + args['webhooks'] = [ + Webhook._from_dict(x) for x in (_dict.get('webhooks')) + ] + if 'intents' in _dict: + args['intents'] = [ + Intent._from_dict(x) for x in (_dict.get('intents')) + ] + if 'entities' in _dict: + args['entities'] = [ + Entity._from_dict(x) for x in (_dict.get('entities')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Workspace 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'workspace_id') and self.workspace_id is not None: + _dict['workspace_id'] = self.workspace_id + if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: + _dict['dialog_nodes'] = [x._to_dict() for x in self.dialog_nodes] + if hasattr(self, + 'counterexamples') and self.counterexamples is not None: + _dict['counterexamples'] = [ + x._to_dict() for x in self.counterexamples + ] + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'updated') and self.updated is not None: + _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + if hasattr(self, + 'learning_opt_out') and self.learning_opt_out is not None: + _dict['learning_opt_out'] = self.learning_opt_out + if hasattr(self, + 'system_settings') and self.system_settings is not None: + _dict['system_settings'] = self.system_settings._to_dict() + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + if hasattr(self, 'webhooks') and self.webhooks is not None: + _dict['webhooks'] = [x._to_dict() for x in self.webhooks] + if hasattr(self, 'intents') and self.intents is not None: + _dict['intents'] = [x._to_dict() for x in self.intents] + if hasattr(self, 'entities') and self.entities is not None: + _dict['entities'] = [x._to_dict() for x in self.entities] + 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 Workspace object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'Workspace') -> 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: 'Workspace') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(Enum): + """ + The current status of the workspace. + """ + NON_EXISTENT = "Non Existent" + TRAINING = "Training" + FAILED = "Failed" + AVAILABLE = "Available" + UNAVAILABLE = "Unavailable" + + +class WorkspaceCollection(): + """ + WorkspaceCollection. + + :attr List[Workspace] workspaces: An array of objects describing the workspaces + associated with the service instance. + :attr Pagination pagination: The pagination data for the returned objects. + """ + + def __init__(self, workspaces: List['Workspace'], + pagination: 'Pagination') -> None: + """ + Initialize a WorkspaceCollection object. + + :param List[Workspace] workspaces: An array of objects describing the + workspaces associated with the service instance. + :param Pagination pagination: The pagination data for the returned objects. + """ + self.workspaces = workspaces + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WorkspaceCollection': + """Initialize a WorkspaceCollection object from a json dictionary.""" + args = {} + valid_keys = ['workspaces', 'pagination'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class WorkspaceCollection: ' + + ', '.join(bad_keys)) + if 'workspaces' in _dict: + args['workspaces'] = [ + Workspace._from_dict(x) for x in (_dict.get('workspaces')) + ] + else: + raise ValueError( + 'Required property \'workspaces\' not present in WorkspaceCollection JSON' + ) + if 'pagination' in _dict: + args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in WorkspaceCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceCollection 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, 'workspaces') and self.workspaces is not None: + _dict['workspaces'] = [x._to_dict() for x in self.workspaces] + if hasattr(self, 'pagination') and self.pagination is not None: + _dict['pagination'] = self.pagination._to_dict() + 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 WorkspaceCollection object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'WorkspaceCollection') -> 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: 'WorkspaceCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class WorkspaceSystemSettings(): + """ + Global settings for the workspace. + + :attr WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings + related to the Watson Assistant user interface. + :attr WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace + settings related to the disambiguation feature. + :attr dict human_agent_assist: (optional) For internal use only. + :attr bool spelling_suggestions: (optional) Whether spelling correction is + enabled for the workspace. + :attr bool spelling_auto_correct: (optional) Whether autocorrection is enabled + for the workspace. If spelling correction is enabled and this property is + `false`, any suggested corrections are returned in the **suggested_text** + property of the message response. If this property is `true`, any corrections + are automatically applied to the user input, and the original text is returned + in the **original_text** property of the message response. + :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, + spelling_suggestions: bool = None, + spelling_auto_correct: bool = None, + system_entities: 'WorkspaceSystemSettingsSystemEntities' = None, + off_topic: 'WorkspaceSystemSettingsOffTopic' = None) -> None: + """ + Initialize a WorkspaceSystemSettings object. + + :param WorkspaceSystemSettingsTooling tooling: (optional) Workspace + settings related to the Watson Assistant user interface. + :param WorkspaceSystemSettingsDisambiguation disambiguation: (optional) + Workspace settings related to the disambiguation feature. + :param dict human_agent_assist: (optional) For internal use only. + :param bool spelling_suggestions: (optional) Whether spelling correction is + enabled for the workspace. + :param bool spelling_auto_correct: (optional) Whether autocorrection is + enabled for the workspace. If spelling correction is enabled and this + property is `false`, any suggested corrections are returned in the + **suggested_text** property of the message response. If this property is + `true`, any corrections are automatically applied to the user input, and + the original text is returned in the **original_text** property of the + message response. + :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.spelling_suggestions = spelling_suggestions + self.spelling_auto_correct = spelling_auto_correct + self.system_entities = system_entities + self.off_topic = off_topic + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': + """Initialize a WorkspaceSystemSettings object from a json dictionary.""" + args = {} + valid_keys = [ + 'tooling', 'disambiguation', 'human_agent_assist', + 'spelling_suggestions', 'spelling_auto_correct', 'system_entities', + 'off_topic' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettings: ' + + ', '.join(bad_keys)) + if 'tooling' in _dict: + args['tooling'] = WorkspaceSystemSettingsTooling._from_dict( + _dict.get('tooling')) + if 'disambiguation' in _dict: + args[ + 'disambiguation'] = WorkspaceSystemSettingsDisambiguation._from_dict( + _dict.get('disambiguation')) + if 'human_agent_assist' in _dict: + args['human_agent_assist'] = _dict.get('human_agent_assist') + if 'spelling_suggestions' in _dict: + args['spelling_suggestions'] = _dict.get('spelling_suggestions') + if 'spelling_auto_correct' in _dict: + args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') + 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')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettings 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 + if hasattr(self, 'tooling') and self.tooling is not None: + _dict['tooling'] = self.tooling._to_dict() + if hasattr(self, 'disambiguation') and self.disambiguation is not None: + _dict['disambiguation'] = self.disambiguation._to_dict() + if hasattr( + self, + 'human_agent_assist') and self.human_agent_assist is not None: + _dict['human_agent_assist'] = self.human_agent_assist + if hasattr(self, 'spelling_suggestions' + ) and self.spelling_suggestions is not None: + _dict['spelling_suggestions'] = self.spelling_suggestions + if hasattr(self, 'spelling_auto_correct' + ) and self.spelling_auto_correct is not None: + _dict['spelling_auto_correct'] = self.spelling_auto_correct + 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 def _to_dict(self): @@ -8551,87 +9723,136 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityRole object.""" + """Return a `str` version of this WorkspaceSystemSettings object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityRole') -> bool: + def __eq__(self, other: 'WorkspaceSystemSettings') -> 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: + def __ne__(self, other: 'WorkspaceSystemSettings') -> 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(): +class WorkspaceSystemSettingsDisambiguation(): """ - An intent identified in the user input. + Workspace settings related to the disambiguation feature. - :attr str intent: The name of the recognized intent. - :attr float confidence: A decimal percentage that represents Watson's confidence - in the intent. + :attr str prompt: (optional) The text of the introductory prompt that + accompanies disambiguation options presented to the user. + :attr str none_of_the_above_prompt: (optional) The user-facing label for the + option users can select if none of the suggested options is correct. If no value + is specified for this property, this option does not appear. + :attr bool enabled: (optional) Whether the disambiguation feature is enabled for + the workspace. + :attr str sensitivity: (optional) The sensitivity of the disambiguation feature + to intent detection conflicts. Set to **high** if you want the disambiguation + feature to be triggered more often. This can be useful for testing or + demonstration purposes. + :attr bool randomize: (optional) Whether the order in which disambiguation + suggestions are presented should be randomized (but still influenced by relative + confidence). + :attr int max_suggestions: (optional) The maximum number of disambigation + suggestions that can be included in a `suggestion` response. + :attr str suggestion_text_policy: (optional) For internal use only. """ - def __init__(self, intent: str, confidence: float) -> None: + def __init__(self, + *, + prompt: str = None, + none_of_the_above_prompt: str = None, + enabled: bool = None, + sensitivity: str = None, + randomize: bool = None, + max_suggestions: int = None, + suggestion_text_policy: str = None) -> None: """ - Initialize a RuntimeIntent object. + Initialize a WorkspaceSystemSettingsDisambiguation object. - :param str intent: The name of the recognized intent. - :param float confidence: A decimal percentage that represents Watson's - confidence in the intent. + :param str prompt: (optional) The text of the introductory prompt that + accompanies disambiguation options presented to the user. + :param str none_of_the_above_prompt: (optional) The user-facing label for + the option users can select if none of the suggested options is correct. If + no value is specified for this property, this option does not appear. + :param bool enabled: (optional) Whether the disambiguation feature is + enabled for the workspace. + :param str sensitivity: (optional) The sensitivity of the disambiguation + feature to intent detection conflicts. Set to **high** if you want the + disambiguation feature to be triggered more often. This can be useful for + testing or demonstration purposes. + :param bool randomize: (optional) Whether the order in which disambiguation + suggestions are presented should be randomized (but still influenced by + relative confidence). + :param int max_suggestions: (optional) The maximum number of disambigation + suggestions that can be included in a `suggestion` response. + :param str suggestion_text_policy: (optional) For internal use only. """ - self.intent = intent - self.confidence = confidence + self.prompt = prompt + self.none_of_the_above_prompt = none_of_the_above_prompt + self.enabled = enabled + self.sensitivity = sensitivity + self.randomize = randomize + self.max_suggestions = max_suggestions + self.suggestion_text_policy = suggestion_text_policy @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': - """Initialize a RuntimeIntent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsDisambiguation': + """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" args = {} - valid_keys = ['intent', 'confidence'] + valid_keys = [ + 'prompt', 'none_of_the_above_prompt', 'enabled', 'sensitivity', + 'randomize', 'max_suggestions', 'suggestion_text_policy' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeIntent: ' + 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsDisambiguation: ' + ', '.join(bad_keys)) - if 'intent' in _dict: - args['intent'] = _dict.get('intent') - else: - raise ValueError( - 'Required property \'intent\' not present in RuntimeIntent JSON' - ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - else: - raise ValueError( - 'Required property \'confidence\' not present in RuntimeIntent JSON' - ) + if 'prompt' in _dict: + args['prompt'] = _dict.get('prompt') + if 'none_of_the_above_prompt' in _dict: + args['none_of_the_above_prompt'] = _dict.get( + 'none_of_the_above_prompt') + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'sensitivity' in _dict: + args['sensitivity'] = _dict.get('sensitivity') + if 'randomize' in _dict: + args['randomize'] = _dict.get('randomize') + if 'max_suggestions' in _dict: + args['max_suggestions'] = _dict.get('max_suggestions') + if 'suggestion_text_policy' in _dict: + args['suggestion_text_policy'] = _dict.get('suggestion_text_policy') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeIntent object from a json dictionary.""" + """Initialize a WorkspaceSystemSettingsDisambiguation 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, 'intent') and self.intent is not None: - _dict['intent'] = self.intent - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'prompt') and self.prompt is not None: + _dict['prompt'] = self.prompt + if hasattr(self, 'none_of_the_above_prompt' + ) and self.none_of_the_above_prompt is not None: + _dict['none_of_the_above_prompt'] = self.none_of_the_above_prompt + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'sensitivity') and self.sensitivity is not None: + _dict['sensitivity'] = self.sensitivity + if hasattr(self, 'randomize') and self.randomize is not None: + _dict['randomize'] = self.randomize + if hasattr(self, + 'max_suggestions') and self.max_suggestions is not None: + _dict['max_suggestions'] = self.max_suggestions + if hasattr(self, 'suggestion_text_policy' + ) and self.suggestion_text_policy is not None: + _dict['suggestion_text_policy'] = self.suggestion_text_policy return _dict def _to_dict(self): @@ -8639,193 +9860,70 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeIntent object.""" + """Return a `str` version of this WorkspaceSystemSettingsDisambiguation object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'RuntimeIntent') -> bool: + def __eq__(self, other: 'WorkspaceSystemSettingsDisambiguation') -> 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: 'RuntimeIntent') -> bool: + def __ne__(self, other: 'WorkspaceSystemSettingsDisambiguation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class SensitivityEnum(Enum): + """ + The sensitivity of the disambiguation feature to intent detection conflicts. Set + to **high** if you want the disambiguation feature to be triggered more often. + This can be useful for testing or demonstration purposes. + """ + AUTO = "auto" + HIGH = "high" + -class RuntimeResponseGeneric(): +class WorkspaceSystemSettingsOffTopic(): """ - RuntimeResponseGeneric. + Workspace settings related to detection of irrelevant input. - :attr str response_type: The type of response returned by the dialog node. The - specified response type must be supported by the client application or channel. - :attr str text: (optional) The text of the response. - :attr int time: (optional) How long to pause, in milliseconds. - :attr bool typing: (optional) Whether to send a "user is typing" event during - the pause. - :attr str source: (optional) The URL of the image. - :attr str title: (optional) The title or introductory text to show before the - response. - :attr str description: (optional) The description to show with the the response. - :attr str preference: (optional) The preferred type of control to display. - :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of - objects describing the options from which the user can choose. - :attr str message_to_human_agent: (optional) A message to be sent to the human - agent who will be taking over the conversation. - :attr str topic: (optional) A label identifying the topic of the conversation, - derived from the **title** property of the relevant node. - :attr str dialog_node: (optional) The ID of the dialog node that the **topic** - property is taken from. The **topic** property is populated using the value of - the dialog node's **title** property. - :attr List[DialogSuggestion] suggestions: (optional) An array of objects - describing the possible matching dialog nodes from which the user can choose. + :attr bool enabled: (optional) Whether enhanced irrelevance detection is enabled + for the workspace. """ - def __init__(self, - response_type: str, - *, - text: str = None, - time: int = None, - typing: bool = None, - source: str = None, - title: str = None, - description: str = None, - preference: str = None, - options: List['DialogNodeOutputOptionsElement'] = None, - message_to_human_agent: str = None, - topic: str = None, - dialog_node: str = None, - suggestions: List['DialogSuggestion'] = None) -> None: + def __init__(self, *, enabled: bool = None) -> None: """ - Initialize a RuntimeResponseGeneric object. + Initialize a WorkspaceSystemSettingsOffTopic object. - :param str response_type: The type of response returned by the dialog node. - The specified response type must be supported by the client application or - channel. - :param str text: (optional) The text of the response. - :param int time: (optional) How long to pause, in milliseconds. - :param bool typing: (optional) Whether to send a "user is typing" event - during the pause. - :param str source: (optional) The URL of the image. - :param str title: (optional) The title or introductory text to show before - the response. - :param str description: (optional) The description to show with the the - response. - :param str preference: (optional) The preferred type of control to display. - :param List[DialogNodeOutputOptionsElement] options: (optional) An array of - objects describing the options from which the user can choose. - :param str message_to_human_agent: (optional) A message to be sent to the - human agent who will be taking over the conversation. - :param str topic: (optional) A label identifying the topic of the - conversation, derived from the **title** property of the relevant node. - :param str dialog_node: (optional) The ID of the dialog node that the - **topic** property is taken from. The **topic** property is populated using - the value of the dialog node's **title** property. - :param List[DialogSuggestion] suggestions: (optional) An array of objects - describing the possible matching dialog nodes from which the user can - choose. - """ - self.response_type = response_type - self.text = text - self.time = time - self.typing = typing - self.source = source - self.title = title - self.description = description - self.preference = preference - self.options = options - self.message_to_human_agent = message_to_human_agent - self.topic = topic - self.dialog_node = dialog_node - self.suggestions = suggestions + :param bool enabled: (optional) Whether enhanced irrelevance detection is + enabled for the workspace. + """ + self.enabled = enabled @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsOffTopic': + """Initialize a WorkspaceSystemSettingsOffTopic object from a json dictionary.""" args = {} - valid_keys = [ - 'response_type', 'text', 'time', 'typing', 'source', 'title', - 'description', 'preference', 'options', 'message_to_human_agent', - 'topic', 'dialog_node', 'suggestions' - ] + valid_keys = ['enabled'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGeneric: ' + 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsOffTopic: ' + ', '.join(bad_keys)) - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') - else: - raise ValueError( - 'Required property \'response_type\' not present in RuntimeResponseGeneric JSON' - ) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'time' in _dict: - args['time'] = _dict.get('time') - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'source' in _dict: - args['source'] = _dict.get('source') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: - args['options'] = [ - DialogNodeOutputOptionsElement._from_dict(x) - for x in (_dict.get('options')) - ] - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'topic' in _dict: - args['topic'] = _dict.get('topic') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'suggestions' in _dict: - args['suggestions'] = [ - DialogSuggestion._from_dict(x) - for x in (_dict.get('suggestions')) - ] + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + """Initialize a WorkspaceSystemSettingsOffTopic 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, 'response_type') and self.response_type is not None: - _dict['response_type'] = self.response_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'time') and self.time is not None: - _dict['time'] = self.time - if hasattr(self, 'typing') and self.typing is not None: - _dict['typing'] = self.typing - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'preference') and self.preference is not None: - _dict['preference'] = self.preference - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x._to_dict() for x in self.options] - if hasattr(self, 'message_to_human_agent' - ) and self.message_to_human_agent is not None: - _dict['message_to_human_agent'] = self.message_to_human_agent - if hasattr(self, 'topic') and self.topic is not None: - _dict['topic'] = self.topic - if hasattr(self, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node - if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x._to_dict() for x in self.suggestions] + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled return _dict def _to_dict(self): @@ -8833,108 +9931,61 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeResponseGeneric object.""" + """Return a `str` version of this WorkspaceSystemSettingsOffTopic object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'RuntimeResponseGeneric') -> bool: + def __eq__(self, other: 'WorkspaceSystemSettingsOffTopic') -> 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: 'RuntimeResponseGeneric') -> bool: + def __ne__(self, other: 'WorkspaceSystemSettingsOffTopic') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - TEXT = "text" - PAUSE = "pause" - IMAGE = "image" - OPTION = "option" - CONNECT_TO_AGENT = "connect_to_agent" - SUGGESTION = "suggestion" - - class PreferenceEnum(Enum): - """ - The preferred type of control to display. - """ - DROPDOWN = "dropdown" - BUTTON = "button" - -class Synonym(): +class WorkspaceSystemSettingsSystemEntities(): """ - Synonym. + Workspace settings related to the behavior of system entities. - :attr str synonym: The text of the synonym. This string must conform to the - following restrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - :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. + :attr bool enabled: (optional) Whether the new system entities are enabled for + the workspace. """ - def __init__(self, - synonym: str, - *, - created: datetime = None, - updated: datetime = None) -> None: + def __init__(self, *, enabled: bool = None) -> None: """ - Initialize a Synonym object. + Initialize a WorkspaceSystemSettingsSystemEntities object. - :param str synonym: The text of the synonym. 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 datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. + :param bool enabled: (optional) Whether the new system entities are enabled + for the workspace. """ - self.synonym = synonym - self.created = created - self.updated = updated + self.enabled = enabled @classmethod - def from_dict(cls, _dict: Dict) -> 'Synonym': - """Initialize a Synonym object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsSystemEntities': + """Initialize a WorkspaceSystemSettingsSystemEntities object from a json dictionary.""" args = {} - valid_keys = ['synonym', 'created', 'updated'] + valid_keys = ['enabled'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class Synonym: ' + - ', '.join(bad_keys)) - if 'synonym' in _dict: - args['synonym'] = _dict.get('synonym') - else: - raise ValueError( - 'Required property \'synonym\' not present in Synonym JSON') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + '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 Synonym object from a json dictionary.""" + """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, 'synonym') and self.synonym is not None: - _dict['synonym'] = self.synonym - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled return _dict def _to_dict(self): @@ -8942,77 +9993,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Synonym object.""" + """Return a `str` version of this WorkspaceSystemSettingsSystemEntities object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'Synonym') -> bool: + 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: 'Synonym') -> bool: + def __ne__(self, other: 'WorkspaceSystemSettingsSystemEntities') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SynonymCollection(): +class WorkspaceSystemSettingsTooling(): """ - SynonymCollection. + Workspace settings related to the Watson Assistant user interface. - :attr List[Synonym] synonyms: An array of synonyms. - :attr Pagination pagination: The pagination data for the returned objects. + :attr bool store_generic_responses: (optional) Whether the dialog JSON editor + displays text responses within the `output.generic` object. """ - def __init__(self, synonyms: List['Synonym'], - pagination: 'Pagination') -> None: + def __init__(self, *, store_generic_responses: bool = None) -> None: """ - Initialize a SynonymCollection object. + Initialize a WorkspaceSystemSettingsTooling object. - :param List[Synonym] synonyms: An array of synonyms. - :param Pagination pagination: The pagination data for the returned objects. + :param bool store_generic_responses: (optional) Whether the dialog JSON + editor displays text responses within the `output.generic` object. """ - self.synonyms = synonyms - self.pagination = pagination + self.store_generic_responses = store_generic_responses @classmethod - def from_dict(cls, _dict: Dict) -> 'SynonymCollection': - """Initialize a SynonymCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsTooling': + """Initialize a WorkspaceSystemSettingsTooling object from a json dictionary.""" args = {} - valid_keys = ['synonyms', 'pagination'] + valid_keys = ['store_generic_responses'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class SynonymCollection: ' + 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsTooling: ' + ', '.join(bad_keys)) - if 'synonyms' in _dict: - args['synonyms'] = [ - Synonym._from_dict(x) for x in (_dict.get('synonyms')) - ] - else: - raise ValueError( - 'Required property \'synonyms\' not present in SynonymCollection JSON' - ) - if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) - else: - raise ValueError( - 'Required property \'pagination\' not present in SynonymCollection JSON' - ) + if 'store_generic_responses' in _dict: + args['store_generic_responses'] = _dict.get( + 'store_generic_responses') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SynonymCollection object from a json dictionary.""" + """Initialize a WorkspaceSystemSettingsTooling 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, 'synonyms') and self.synonyms is not None: - _dict['synonyms'] = [x._to_dict() for x in self.synonyms] - if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + if hasattr(self, 'store_generic_responses' + ) and self.store_generic_responses is not None: + _dict['store_generic_responses'] = self.store_generic_responses return _dict def _to_dict(self): @@ -9020,210 +10057,242 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SynonymCollection object.""" + """Return a `str` version of this WorkspaceSystemSettingsTooling object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'SynonymCollection') -> bool: + def __eq__(self, other: 'WorkspaceSystemSettingsTooling') -> 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: 'SynonymCollection') -> bool: + def __ne__(self, other: 'WorkspaceSystemSettingsTooling') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SystemResponse(): +class DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent( + DialogNodeOutputGeneric): """ - For internal use only. + An object that describes a response with response type `connect_to_agent`. + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str message_to_human_agent: (optional) An optional message to be sent to + the human agent who will be taking over the conversation. + :attr str agent_available: (optional) An optional message to be displayed to the + user to indicate that the conversation will be transferred to the next available + agent. + :attr str agent_unavailable: (optional) An optional message to be displayed to + the user to indicate that no online agent is available to take over the + conversation. + :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + Routing or other contextual information to be used by target service desk + systems. """ - def __init__(self, **kwargs) -> None: + def __init__( + self, + response_type: str, + *, + message_to_human_agent: str = None, + agent_available: str = None, + agent_unavailable: str = None, + transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None + ) -> None: """ - Initialize a SystemResponse object. + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object. - :param **kwargs: (optional) Any additional properties. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str message_to_human_agent: (optional) An optional message to be + sent to the human agent who will be taking over the conversation. + :param str agent_available: (optional) An optional message to be displayed + to the user to indicate that the conversation will be transferred to the + next available agent. + :param str agent_unavailable: (optional) An optional message to be + displayed to the user to indicate that no online agent is available to take + over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + Routing or other contextual information to be used by target service desk + systems. """ - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.response_type = response_type + self.message_to_human_agent = message_to_human_agent + self.agent_available = agent_available + self.agent_unavailable = agent_unavailable + self.transfer_info = transfer_info @classmethod - def from_dict(cls, _dict: Dict) -> 'SystemResponse': - """Initialize a SystemResponse object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object from a json dictionary.""" args = {} - xtra = _dict.copy() - args.update(xtra) + valid_keys = [ + 'response_type', 'message_to_human_agent', 'agent_available', + 'agent_unavailable', 'transfer_info' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent: ' + + ', '.join(bad_keys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent JSON' + ) + if 'message_to_human_agent' in _dict: + args['message_to_human_agent'] = _dict.get('message_to_human_agent') + if 'agent_available' in _dict: + args['agent_available'] = _dict.get('agent_available') + if 'agent_unavailable' in _dict: + args['agent_unavailable'] = _dict.get('agent_unavailable') + if 'transfer_info' in _dict: + args[ + 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo._from_dict( + _dict.get('transfer_info')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SystemResponse object from a json dictionary.""" + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent 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, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'message_to_human_agent' + ) and self.message_to_human_agent is not None: + _dict['message_to_human_agent'] = self.message_to_human_agent + if hasattr(self, + 'agent_available') and self.agent_available is not None: + _dict['agent_available'] = self.agent_available + if hasattr(self, + 'agent_unavailable') and self.agent_unavailable is not None: + _dict['agent_unavailable'] = self.agent_unavailable + if hasattr(self, 'transfer_info') and self.transfer_info is not None: + _dict['transfer_info'] = self.transfer_info._to_dict() return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = {} - if not hasattr(self, '_additionalProperties'): - super(SystemResponse, self).__setattr__('_additionalProperties', - set()) - if name not in properties: - self._additionalProperties.add(name) - super(SystemResponse, self).__setattr__(name, value) - def __str__(self) -> str: - """Return a `str` version of this SystemResponse object.""" + """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'SystemResponse') -> bool: + def __eq__( + self, + other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent' + ) -> 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: 'SystemResponse') -> bool: + def __ne__( + self, + other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + CONNECT_TO_AGENT = "connect_to_agent" + -class Value(): +class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage( + DialogNodeOutputGeneric): """ - Value. + An object that describes a response with response type `image`. - :attr str value: The text of the entity value. This string must conform to the - following restrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - :attr dict metadata: (optional) Any metadata related to the entity value. - :attr str type: Specifies the type of entity value. - :attr List[str] synonyms: (optional) An array of synonyms for the entity value. - A value can specify either synonyms or patterns (depending on the value type), - but not both. A synonym must conform to the following resrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - :attr List[str] patterns: (optional) An array of patterns for the 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/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. + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str source: The URL of the image. + :attr str title: (optional) An optional title to show before the response. + :attr str description: (optional) An optional description to show with the + response. """ def __init__(self, - value: str, - type: str, + response_type: str, + source: str, *, - metadata: dict = None, - synonyms: List[str] = None, - patterns: List[str] = None, - created: datetime = None, - updated: datetime = None) -> None: + title: str = None, + description: str = None) -> None: """ - Initialize a Value object. + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object. - :param str value: The text of the entity value. 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 str type: Specifies the type of entity value. - :param dict metadata: (optional) Any metadata related to the entity value. - :param List[str] synonyms: (optional) An array of synonyms for the entity - value. A value can specify either synonyms or patterns (depending on the - value type), but not both. A synonym must conform to the following - resrictions: - - It cannot contain carriage return, newline, or tab characters. - - It cannot consist of only whitespace characters. - :param List[str] patterns: (optional) An array of patterns for the 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/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 - update to the object. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The URL of the image. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the + response. """ - self.value = value - self.metadata = metadata - self.type = type - self.synonyms = synonyms - self.patterns = patterns - self.created = created - self.updated = updated + self.response_type = response_type + self.source = source + self.title = title + self.description = description @classmethod - def from_dict(cls, _dict: Dict) -> 'Value': - """Initialize a Value object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object from a json dictionary.""" args = {} - valid_keys = [ - 'value', 'metadata', 'type', 'synonyms', 'patterns', 'created', - 'updated' - ] + valid_keys = ['response_type', 'source', 'title', 'description'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class Value: ' + - ', '.join(bad_keys)) - if 'value' in _dict: - args['value'] = _dict.get('value') + 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage: ' + + ', '.join(bad_keys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') else: raise ValueError( - 'Required property \'value\' not present in Value JSON') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'type' in _dict: - args['type'] = _dict.get('type') + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' + ) + if 'source' in _dict: + args['source'] = _dict.get('source') else: raise ValueError( - 'Required property \'type\' not present in Value JSON') - if 'synonyms' in _dict: - args['synonyms'] = _dict.get('synonyms') - if 'patterns' in _dict: - args['patterns'] = _dict.get('patterns') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Value object from a json dictionary.""" + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage 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, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'synonyms') and self.synonyms is not None: - _dict['synonyms'] = self.synonyms - if hasattr(self, 'patterns') and self.patterns is not None: - _dict['patterns'] = self.patterns - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description return _dict def _to_dict(self): @@ -9231,83 +10300,135 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Value object.""" + """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'Value') -> bool: + def __eq__( + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage' + ) -> 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: 'Value') -> bool: + def __ne__( + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class ResponseTypeEnum(Enum): """ - Specifies the type of entity value. + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. """ - SYNONYMS = "synonyms" - PATTERNS = "patterns" + IMAGE = "image" -class ValueCollection(): +class DialogNodeOutputGenericDialogNodeOutputResponseTypeOption( + DialogNodeOutputGeneric): """ - ValueCollection. + An object that describes a response with response type `option`. - :attr List[Value] values: An array of entity values. - :attr Pagination pagination: The pagination data for the returned objects. + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str title: An optional title to show before the response. + :attr str description: (optional) An optional description to show with the + response. + :attr str preference: (optional) The preferred type of control to display, if + supported by the channel. + :attr List[DialogNodeOutputOptionsElement] options: An array of objects + describing the options from which the user can choose. You can include up to 20 + options. """ - def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: + def __init__(self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: str = None, + preference: str = None) -> None: """ - Initialize a ValueCollection object. + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object. - :param List[Value] values: An array of entity values. - :param Pagination pagination: The pagination data for the returned objects. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str title: An optional title to show before the response. + :param List[DialogNodeOutputOptionsElement] options: An array of objects + describing the options from which the user can choose. You can include up + to 20 options. + :param str description: (optional) An optional description to show with the + response. + :param str preference: (optional) The preferred type of control to display, + if supported by the channel. """ - self.values = values - self.pagination = pagination + self.response_type = response_type + self.title = title + self.description = description + self.preference = preference + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'ValueCollection': - """Initialize a ValueCollection object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object from a json dictionary.""" args = {} - valid_keys = ['values', 'pagination'] + valid_keys = [ + 'response_type', 'title', 'description', 'preference', 'options' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class ValueCollection: ' + 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypeOption: ' + ', '.join(bad_keys)) - if 'values' in _dict: - args['values'] = [ - Value._from_dict(x) for x in (_dict.get('values')) - ] + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') else: raise ValueError( - 'Required property \'values\' not present in ValueCollection JSON' + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + if 'title' in _dict: + args['title'] = _dict.get('title') else: raise ValueError( - 'Required property \'pagination\' not present in ValueCollection JSON' + 'Required property \'title\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'preference' in _dict: + args['preference'] = _dict.get('preference') + if 'options' in _dict: + args['options'] = [ + DialogNodeOutputOptionsElement._from_dict(x) + for x in (_dict.get('options')) + ] + else: + raise ValueError( + 'Required property \'options\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ValueCollection object from a json dictionary.""" + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption 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, 'values') and self.values is not None: - _dict['values'] = [x._to_dict() for x in self.values] - if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'preference') and self.preference is not None: + _dict['preference'] = self.preference + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = [x._to_dict() for x in self.options] return _dict def _to_dict(self): @@ -9315,93 +10436,113 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ValueCollection object.""" + """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'ValueCollection') -> bool: + def __eq__( + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption' + ) -> 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: 'ValueCollection') -> bool: + def __ne__( + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + OPTION = "option" + + class PreferenceEnum(Enum): + """ + The preferred type of control to display, if supported by the channel. + """ + DROPDOWN = "dropdown" + BUTTON = "button" + -class Webhook(): +class DialogNodeOutputGenericDialogNodeOutputResponseTypePause( + DialogNodeOutputGeneric): """ - A webhook that can be used by dialog nodes to make programmatic calls to an external - function. - **Note:** Currently, only a single webhook named `main_webhook` is supported. + An object that describes a response with response type `pause`. - :attr str url: The URL for the external service or application to which you want - to send HTTP POST requests. - :attr str name: The name of the webhook. Currently, `main_webhook` is the only - supported value. - :attr List[WebhookHeader] headers: (optional) An optional array of HTTP headers - to pass with the HTTP request. + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr int time: How long to pause, in milliseconds. The valid values are from 0 + to 10000. + :attr bool typing: (optional) Whether to send a "user is typing" event during + the pause. Ignored if the channel does not support this event. """ def __init__(self, - url: str, - name: str, + response_type: str, + time: int, *, - headers: List['WebhookHeader'] = None) -> None: + typing: bool = None) -> None: """ - Initialize a Webhook object. + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypePause object. - :param str url: The URL for the external service or application to which - you want to send HTTP POST requests. - :param str name: The name of the webhook. Currently, `main_webhook` is the - only supported value. - :param List[WebhookHeader] headers: (optional) An optional array of HTTP - headers to pass with the HTTP request. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param int time: How long to pause, in milliseconds. The valid values are + from 0 to 10000. + :param bool typing: (optional) Whether to send a "user is typing" event + during the pause. Ignored if the channel does not support this event. """ - self.url = url - self.name = name - self.headers = headers + self.response_type = response_type + self.time = time + self.typing = typing @classmethod - def from_dict(cls, _dict: Dict) -> 'Webhook': - """Initialize a Webhook object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypePause object from a json dictionary.""" args = {} - valid_keys = ['url', 'name', 'headers'] + valid_keys = ['response_type', 'time', 'typing'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class Webhook: ' + - ', '.join(bad_keys)) - if 'url' in _dict: - args['url'] = _dict.get('url') + 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypePause: ' + + ', '.join(bad_keys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') else: raise ValueError( - 'Required property \'url\' not present in Webhook JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypePause JSON' + ) + if 'time' in _dict: + args['time'] = _dict.get('time') else: raise ValueError( - 'Required property \'name\' not present in Webhook JSON') - if 'headers' in _dict: - args['headers'] = [ - WebhookHeader._from_dict(x) for x in (_dict.get('headers')) - ] + 'Required property \'time\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypePause JSON' + ) + if 'typing' in _dict: + args['typing'] = _dict.get('typing') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Webhook object from a json dictionary.""" + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypePause 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, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'headers') and self.headers is not None: - _dict['headers'] = [x._to_dict() for x in self.headers] + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'time') and self.time is not None: + _dict['time'] = self.time + if hasattr(self, 'typing') and self.typing is not None: + _dict['typing'] = self.typing return _dict def _to_dict(self): @@ -9409,72 +10550,145 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Webhook object.""" + """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypePause object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'Webhook') -> bool: + def __eq__( + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause' + ) -> 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: 'Webhook') -> bool: + def __ne__( + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + PAUSE = "pause" + -class WebhookHeader(): +class DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill( + DialogNodeOutputGeneric): """ - A key/value pair defining an HTTP header and a value. + An object that describes a response with response type `search_skill`. - :attr str name: The name of an HTTP header (for example, `Authorization`). - :attr str value: The value of an HTTP header. + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + **Note:** The **search_skill** response type is used only by the v2 runtime API. + :attr str query: The text of the search query. This can be either a + natural-language query or a query that uses the Discovery query language syntax, + depending on the value of the **query_type** property. For more information, see + the [Discovery service + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators). + :attr str query_type: The type of the search query. + :attr str filter: (optional) An optional filter that narrows the set of + documents to be searched. For more information, see the [Discovery service + documentation]([Discovery service + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). + :attr str discovery_version: (optional) The version of the Discovery service API + to use for the query. """ - def __init__(self, name: str, value: str) -> None: + def __init__(self, + response_type: str, + query: str, + query_type: str, + *, + filter: str = None, + discovery_version: str = None) -> None: """ - Initialize a WebhookHeader object. + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object. - :param str name: The name of an HTTP header (for example, `Authorization`). - :param str value: The value of an HTTP header. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + **Note:** The **search_skill** response type is used only by the v2 runtime + API. + :param str query: The text of the search query. This can be either a + natural-language query or a query that uses the Discovery query language + syntax, depending on the value of the **query_type** property. For more + information, see the [Discovery service + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators). + :param str query_type: The type of the search query. + :param str filter: (optional) An optional filter that narrows the set of + documents to be searched. For more information, see the [Discovery service + documentation]([Discovery service + documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). + :param str discovery_version: (optional) The version of the Discovery + service API to use for the query. """ - self.name = name - self.value = value + self.response_type = response_type + self.query = query + self.query_type = query_type + self.filter = filter + self.discovery_version = discovery_version @classmethod - def from_dict(cls, _dict: Dict) -> 'WebhookHeader': - """Initialize a WebhookHeader object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object from a json dictionary.""" args = {} - valid_keys = ['name', 'value'] + valid_keys = [ + 'response_type', 'query', 'query_type', 'filter', + 'discovery_version' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class WebhookHeader: ' + 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill: ' + ', '.join(bad_keys)) - if 'name' in _dict: - args['name'] = _dict.get('name') + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') else: raise ValueError( - 'Required property \'name\' not present in WebhookHeader JSON') - if 'value' in _dict: - args['value'] = _dict.get('value') + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' + ) + if 'query' in _dict: + args['query'] = _dict.get('query') else: raise ValueError( - 'Required property \'value\' not present in WebhookHeader JSON') + 'Required property \'query\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' + ) + if 'query_type' in _dict: + args['query_type'] = _dict.get('query_type') + else: + raise ValueError( + 'Required property \'query_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' + ) + if 'filter' in _dict: + args['filter'] = _dict.get('filter') + if 'discovery_version' in _dict: + args['discovery_version'] = _dict.get('discovery_version') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a WebhookHeader object from a json dictionary.""" + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'query') and self.query is not None: + _dict['query'] = self.query + if hasattr(self, 'query_type') and self.query_type is not None: + _dict['query_type'] = self.query_type + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, + 'discovery_version') and self.discovery_version is not None: + _dict['discovery_version'] = self.discovery_version return _dict def _to_dict(self): @@ -9482,228 +10696,132 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this WebhookHeader object.""" + """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'WebhookHeader') -> bool: + def __eq__( + self, + other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill' + ) -> 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: 'WebhookHeader') -> bool: + def __ne__( + self, + other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + **Note:** The **search_skill** response type is used only by the v2 runtime API. + """ + SEARCH_SKILL = "search_skill" -class Workspace(): - """ - Workspace. + class QueryTypeEnum(Enum): + """ + The type of the search query. + """ + NATURAL_LANGUAGE = "natural_language" + DISCOVERY_QUERY_LANGUAGE = "discovery_query_language" - :attr str name: The name of the workspace. This string cannot contain carriage - return, newline, or tab characters. - :attr str description: (optional) The description of the workspace. This string - cannot contain carriage return, newline, or tab characters. - :attr str language: The language of the workspace. - :attr dict metadata: (optional) Any metadata related to the workspace. - :attr bool learning_opt_out: Whether training data from the workspace (including - artifacts such as intents and entities) can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. - :attr WorkspaceSystemSettings system_settings: (optional) Global settings for - the workspace. - :attr str workspace_id: The workspace ID of the workspace. - :attr str status: (optional) The current status of the workspace. - :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. - :attr List[Intent] intents: (optional) An array of intents. - :attr List[Entity] entities: (optional) An array of objects describing the - entities for the workspace. - :attr List[DialogNode] dialog_nodes: (optional) An array of objects describing - the dialog nodes in the workspace. - :attr List[Counterexample] counterexamples: (optional) An array of - counterexamples. - :attr List[Webhook] webhooks: (optional) + +class DialogNodeOutputGenericDialogNodeOutputResponseTypeText( + DialogNodeOutputGeneric): """ + An object that describes a response with response type `text`. - def __init__(self, - name: str, - language: str, - learning_opt_out: bool, - workspace_id: str, - *, - description: str = None, - metadata: dict = None, - system_settings: 'WorkspaceSystemSettings' = None, - status: str = None, - created: datetime = None, - updated: datetime = None, - intents: List['Intent'] = None, - entities: List['Entity'] = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - webhooks: List['Webhook'] = None) -> None: + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr List[DialogNodeOutputTextValuesElement] values: A list of one or more + objects defining text responses. + :attr str selection_policy: (optional) How a response is selected from the list, + if more than one response is specified. + :attr str delimiter: (optional) The delimiter to use as a separator between + responses when `selection_policy`=`multiline`. + """ + + def __init__(self, + response_type: str, + values: List['DialogNodeOutputTextValuesElement'], + *, + selection_policy: str = None, + delimiter: str = None) -> None: """ - Initialize a Workspace object. + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeText object. - :param str name: The name of the workspace. This string cannot contain - carriage return, newline, or tab characters. - :param str language: The language of the workspace. - :param bool learning_opt_out: Whether training data from the workspace - (including artifacts such as intents and entities) can be used by IBM for - general service improvements. `true` indicates that workspace training data - is not to be used. - :param str workspace_id: The workspace ID of the workspace. - :param str description: (optional) The description of the workspace. This - string cannot contain carriage return, newline, or tab characters. - :param dict metadata: (optional) Any metadata related to the workspace. - :param WorkspaceSystemSettings system_settings: (optional) Global settings - for the workspace. - :param str status: (optional) The current status of the workspace. - :param datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. - :param List[Intent] intents: (optional) An array of intents. - :param List[Entity] entities: (optional) An array of objects describing the - entities for the workspace. - :param List[DialogNode] dialog_nodes: (optional) An array of objects - describing the dialog nodes in the workspace. - :param List[Counterexample] counterexamples: (optional) An array of - counterexamples. - :param List[Webhook] webhooks: (optional) + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param List[DialogNodeOutputTextValuesElement] values: A list of one or + more objects defining text responses. + :param str selection_policy: (optional) How a response is selected from the + list, if more than one response is specified. + :param str delimiter: (optional) The delimiter to use as a separator + between responses when `selection_policy`=`multiline`. """ - self.name = name - self.description = description - self.language = language - self.metadata = metadata - self.learning_opt_out = learning_opt_out - self.system_settings = system_settings - self.workspace_id = workspace_id - self.status = status - self.created = created - self.updated = updated - self.intents = intents - self.entities = entities - self.dialog_nodes = dialog_nodes - self.counterexamples = counterexamples - self.webhooks = webhooks + self.response_type = response_type + self.values = values + self.selection_policy = selection_policy + self.delimiter = delimiter @classmethod - def from_dict(cls, _dict: Dict) -> 'Workspace': - """Initialize a Workspace object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeText object from a json dictionary.""" args = {} valid_keys = [ - 'name', 'description', 'language', 'metadata', 'learning_opt_out', - 'system_settings', 'workspace_id', 'status', 'created', 'updated', - 'intents', 'entities', 'dialog_nodes', 'counterexamples', 'webhooks' + 'response_type', 'values', 'selection_policy', 'delimiter' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class Workspace: ' + 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypeText: ' + ', '.join(bad_keys)) - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in Workspace JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'language' in _dict: - args['language'] = _dict.get('language') - else: - raise ValueError( - 'Required property \'language\' not present in Workspace JSON') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'learning_opt_out' in _dict: - args['learning_opt_out'] = _dict.get('learning_opt_out') + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') else: raise ValueError( - 'Required property \'learning_opt_out\' not present in Workspace JSON' + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeText JSON' ) - if 'system_settings' in _dict: - args['system_settings'] = WorkspaceSystemSettings._from_dict( - _dict.get('system_settings')) - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') + if 'values' in _dict: + args['values'] = [ + DialogNodeOutputTextValuesElement._from_dict(x) + for x in (_dict.get('values')) + ] else: raise ValueError( - 'Required property \'workspace_id\' not present in Workspace JSON' + 'Required property \'values\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeText JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'intents' in _dict: - args['intents'] = [ - Intent._from_dict(x) for x in (_dict.get('intents')) - ] - if 'entities' in _dict: - args['entities'] = [ - Entity._from_dict(x) for x in (_dict.get('entities')) - ] - if 'dialog_nodes' in _dict: - args['dialog_nodes'] = [ - DialogNode._from_dict(x) for x in (_dict.get('dialog_nodes')) - ] - if 'counterexamples' in _dict: - args['counterexamples'] = [ - Counterexample._from_dict(x) - for x in (_dict.get('counterexamples')) - ] - if 'webhooks' in _dict: - args['webhooks'] = [ - Webhook._from_dict(x) for x in (_dict.get('webhooks')) - ] + if 'selection_policy' in _dict: + args['selection_policy'] = _dict.get('selection_policy') + if 'delimiter' in _dict: + args['delimiter'] = _dict.get('delimiter') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Workspace object from a json dictionary.""" + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeText 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - if hasattr(self, - 'learning_opt_out') and self.learning_opt_out is not None: - _dict['learning_opt_out'] = self.learning_opt_out - if hasattr(self, - 'system_settings') and self.system_settings is not None: - _dict['system_settings'] = self.system_settings._to_dict() - if hasattr(self, 'workspace_id') and self.workspace_id is not None: - _dict['workspace_id'] = self.workspace_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] - if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: - _dict['dialog_nodes'] = [x._to_dict() for x in self.dialog_nodes] + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'values') and self.values is not None: + _dict['values'] = [x._to_dict() for x in self.values] if hasattr(self, - 'counterexamples') and self.counterexamples is not None: - _dict['counterexamples'] = [ - x._to_dict() for x in self.counterexamples - ] - if hasattr(self, 'webhooks') and self.webhooks is not None: - _dict['webhooks'] = [x._to_dict() for x in self.webhooks] + 'selection_policy') and self.selection_policy is not None: + _dict['selection_policy'] = self.selection_policy + if hasattr(self, 'delimiter') and self.delimiter is not None: + _dict['delimiter'] = self.delimiter return _dict def _to_dict(self): @@ -9711,89 +10829,169 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Workspace object.""" + """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeText object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'Workspace') -> bool: + def __eq__( + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText' + ) -> 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: 'Workspace') -> bool: + def __ne__( + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class ResponseTypeEnum(Enum): """ - The current status of the workspace. + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. """ - NON_EXISTENT = "Non Existent" - TRAINING = "Training" - FAILED = "Failed" - AVAILABLE = "Available" - UNAVAILABLE = "Unavailable" + TEXT = "text" + + class SelectionPolicyEnum(Enum): + """ + How a response is selected from the list, if more than one response is specified. + """ + SEQUENTIAL = "sequential" + RANDOM = "random" + MULTILINE = "multiline" -class WorkspaceCollection(): +class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( + RuntimeResponseGeneric): """ - WorkspaceCollection. + An object that describes a response with response type `connect_to_agent`. - :attr List[Workspace] workspaces: An array of objects describing the workspaces - associated with the service instance. - :attr Pagination pagination: The pagination data for the returned objects. + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str message_to_human_agent: (optional) A message to be sent to the human + agent who will be taking over the conversation. + :attr str agent_available: (optional) An optional message to be displayed to the + user to indicate that the conversation will be transferred to the next available + agent. + :attr str agent_unavailable: (optional) An optional message to be displayed to + the user to indicate that no online agent is available to take over the + conversation. + :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + Routing or other contextual information to be used by target service desk + systems. + :attr str topic: (optional) A label identifying the topic of the conversation, + derived from the **title** property of the relevant node or the **topic** + property of the dialog node response. + :attr str dialog_node: (optional) The ID of the dialog node that the **topic** + property is taken from. The **topic** property is populated using the value of + the dialog node's **title** property. """ - def __init__(self, workspaces: List['Workspace'], - pagination: 'Pagination') -> None: + def __init__( + self, + response_type: str, + *, + message_to_human_agent: str = None, + agent_available: str = None, + agent_unavailable: str = None, + transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, + topic: str = None, + dialog_node: str = None) -> None: """ - Initialize a WorkspaceCollection object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object. - :param List[Workspace] workspaces: An array of objects describing the - workspaces associated with the service instance. - :param Pagination pagination: The pagination data for the returned objects. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str message_to_human_agent: (optional) A message to be sent to the + human agent who will be taking over the conversation. + :param str agent_available: (optional) An optional message to be displayed + to the user to indicate that the conversation will be transferred to the + next available agent. + :param str agent_unavailable: (optional) An optional message to be + displayed to the user to indicate that no online agent is available to take + over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + Routing or other contextual information to be used by target service desk + systems. + :param str topic: (optional) A label identifying the topic of the + conversation, derived from the **title** property of the relevant node or + the **topic** property of the dialog node response. + :param str dialog_node: (optional) The ID of the dialog node that the + **topic** property is taken from. The **topic** property is populated using + the value of the dialog node's **title** property. """ - self.workspaces = workspaces - self.pagination = pagination + self.response_type = response_type + self.message_to_human_agent = message_to_human_agent + self.agent_available = agent_available + self.agent_unavailable = agent_unavailable + self.transfer_info = transfer_info + self.topic = topic + self.dialog_node = dialog_node @classmethod - def from_dict(cls, _dict: Dict) -> 'WorkspaceCollection': - """Initialize a WorkspaceCollection object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" args = {} - valid_keys = ['workspaces', 'pagination'] + valid_keys = [ + 'response_type', 'message_to_human_agent', 'agent_available', + 'agent_unavailable', 'transfer_info', 'topic', 'dialog_node' + ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class WorkspaceCollection: ' + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent: ' + ', '.join(bad_keys)) - if 'workspaces' in _dict: - args['workspaces'] = [ - Workspace._from_dict(x) for x in (_dict.get('workspaces')) - ] - else: - raise ValueError( - 'Required property \'workspaces\' not present in WorkspaceCollection JSON' - ) - if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') else: raise ValueError( - 'Required property \'pagination\' not present in WorkspaceCollection JSON' + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeConnectToAgent JSON' ) + if 'message_to_human_agent' in _dict: + args['message_to_human_agent'] = _dict.get('message_to_human_agent') + if 'agent_available' in _dict: + args['agent_available'] = _dict.get('agent_available') + if 'agent_unavailable' in _dict: + args['agent_unavailable'] = _dict.get('agent_unavailable') + if 'transfer_info' in _dict: + args[ + 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo._from_dict( + _dict.get('transfer_info')) + if 'topic' in _dict: + args['topic'] = _dict.get('topic') + if 'dialog_node' in _dict: + args['dialog_node'] = _dict.get('dialog_node') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a WorkspaceCollection object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent 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, 'workspaces') and self.workspaces is not None: - _dict['workspaces'] = [x._to_dict() for x in self.workspaces] - if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'message_to_human_agent' + ) and self.message_to_human_agent is not None: + _dict['message_to_human_agent'] = self.message_to_human_agent + if hasattr(self, + 'agent_available') and self.agent_available is not None: + _dict['agent_available'] = self.agent_available + if hasattr(self, + 'agent_unavailable') and self.agent_unavailable is not None: + _dict['agent_unavailable'] = self.agent_unavailable + if hasattr(self, 'transfer_info') and self.transfer_info is not None: + _dict['transfer_info'] = self.transfer_info._to_dict() + if hasattr(self, 'topic') and self.topic is not None: + _dict['topic'] = self.topic + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node return _dict def _to_dict(self): @@ -9801,146 +10999,112 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this WorkspaceCollection object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'WorkspaceCollection') -> bool: + def __eq__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + ) -> 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: 'WorkspaceCollection') -> bool: + def __ne__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + CONNECT_TO_AGENT = "connect_to_agent" + -class WorkspaceSystemSettings(): +class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): """ - Global settings for the workspace. + An object that describes a response with response type `image`. - :attr WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings - related to the Watson Assistant user interface. - :attr WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace - settings related to the disambiguation feature. - :attr dict human_agent_assist: (optional) For internal use only. - :attr bool spelling_suggestions: (optional) Whether spelling correction is - enabled for the workspace. - :attr bool spelling_auto_correct: (optional) Whether autocorrection is enabled - for the workspace. If spelling correction is enabled and this property is - `false`, any suggested corrections are returned in the **suggested_text** - property of the message response. If this property is `true`, any corrections - are automatically applied to the user input, and the original text is returned - in the **original_text** property of the message response. - :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. + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str source: The URL of the image. + :attr str title: (optional) The title or introductory text to show before the + response. + :attr str description: (optional) The description to show with the the response. """ - def __init__( - self, - *, - tooling: 'WorkspaceSystemSettingsTooling' = None, - disambiguation: 'WorkspaceSystemSettingsDisambiguation' = None, - human_agent_assist: dict = None, - spelling_suggestions: bool = None, - spelling_auto_correct: bool = None, - system_entities: 'WorkspaceSystemSettingsSystemEntities' = None, - off_topic: 'WorkspaceSystemSettingsOffTopic' = None) -> None: + def __init__(self, + response_type: str, + source: str, + *, + title: str = None, + description: str = None) -> None: """ - Initialize a WorkspaceSystemSettings object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. - :param WorkspaceSystemSettingsTooling tooling: (optional) Workspace - settings related to the Watson Assistant user interface. - :param WorkspaceSystemSettingsDisambiguation disambiguation: (optional) - Workspace settings related to the disambiguation feature. - :param dict human_agent_assist: (optional) For internal use only. - :param bool spelling_suggestions: (optional) Whether spelling correction is - enabled for the workspace. - :param bool spelling_auto_correct: (optional) Whether autocorrection is - enabled for the workspace. If spelling correction is enabled and this - property is `false`, any suggested corrections are returned in the - **suggested_text** property of the message response. If this property is - `true`, any corrections are automatically applied to the user input, and - the original text is returned in the **original_text** property of the - message response. - :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. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The URL of the image. + :param str title: (optional) The title or introductory text to show before + the response. + :param str description: (optional) The description to show with the the + response. """ - self.tooling = tooling - self.disambiguation = disambiguation - self.human_agent_assist = human_agent_assist - self.spelling_suggestions = spelling_suggestions - self.spelling_auto_correct = spelling_auto_correct - self.system_entities = system_entities - self.off_topic = off_topic + self.response_type = response_type + self.source = source + self.title = title + self.description = description @classmethod - def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': - """Initialize a WorkspaceSystemSettings object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeImage': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object from a json dictionary.""" args = {} - valid_keys = [ - 'tooling', 'disambiguation', 'human_agent_assist', - 'spelling_suggestions', 'spelling_auto_correct', 'system_entities', - 'off_topic' - ] + valid_keys = ['response_type', 'source', 'title', 'description'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettings: ' + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeImage: ' + ', '.join(bad_keys)) - if 'tooling' in _dict: - args['tooling'] = WorkspaceSystemSettingsTooling._from_dict( - _dict.get('tooling')) - if 'disambiguation' in _dict: - args[ - 'disambiguation'] = WorkspaceSystemSettingsDisambiguation._from_dict( - _dict.get('disambiguation')) - if 'human_agent_assist' in _dict: - args['human_agent_assist'] = _dict.get('human_agent_assist') - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'spelling_auto_correct' in _dict: - args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') - 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')) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' + ) + if 'source' in _dict: + args['source'] = _dict.get('source') + else: + raise ValueError( + 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a WorkspaceSystemSettings object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage 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, 'tooling') and self.tooling is not None: - _dict['tooling'] = self.tooling._to_dict() - if hasattr(self, 'disambiguation') and self.disambiguation is not None: - _dict['disambiguation'] = self.disambiguation._to_dict() - if hasattr( - self, - 'human_agent_assist') and self.human_agent_assist is not None: - _dict['human_agent_assist'] = self.human_agent_assist - if hasattr(self, 'spelling_suggestions' - ) and self.spelling_suggestions is not None: - _dict['spelling_suggestions'] = self.spelling_suggestions - if hasattr(self, 'spelling_auto_correct' - ) and self.spelling_auto_correct is not None: - _dict['spelling_auto_correct'] = self.spelling_auto_correct - 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() + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description return _dict def _to_dict(self): @@ -9948,136 +11112,128 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this WorkspaceSystemSettings object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeImage object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'WorkspaceSystemSettings') -> bool: + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeImage') -> 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: 'WorkspaceSystemSettings') -> bool: + def __ne__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeImage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + IMAGE = "image" -class WorkspaceSystemSettingsDisambiguation(): + +class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): """ - Workspace settings related to the disambiguation feature. + An object that describes a response with response type `option`. - :attr str prompt: (optional) The text of the introductory prompt that - accompanies disambiguation options presented to the user. - :attr str none_of_the_above_prompt: (optional) The user-facing label for the - option users can select if none of the suggested options is correct. If no value - is specified for this property, this option does not appear. - :attr bool enabled: (optional) Whether the disambiguation feature is enabled for - the workspace. - :attr str sensitivity: (optional) The sensitivity of the disambiguation feature - to intent detection conflicts. Set to **high** if you want the disambiguation - feature to be triggered more often. This can be useful for testing or - demonstration purposes. - :attr bool randomize: (optional) Whether the order in which disambiguation - suggestions are presented should be randomized (but still influenced by relative - confidence). - :attr int max_suggestions: (optional) The maximum number of disambigation - suggestions that can be included in a `suggestion` response. - :attr str suggestion_text_policy: (optional) For internal use only. + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str title: The title or introductory text to show before the response. + :attr str description: (optional) The description to show with the the response. + :attr str preference: (optional) The preferred type of control to display. + :attr List[DialogNodeOutputOptionsElement] options: An array of objects + describing the options from which the user can choose. """ def __init__(self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], *, - prompt: str = None, - none_of_the_above_prompt: str = None, - enabled: bool = None, - sensitivity: str = None, - randomize: bool = None, - max_suggestions: int = None, - suggestion_text_policy: str = None) -> None: + description: str = None, + preference: str = None) -> None: """ - Initialize a WorkspaceSystemSettingsDisambiguation object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object. - :param str prompt: (optional) The text of the introductory prompt that - accompanies disambiguation options presented to the user. - :param str none_of_the_above_prompt: (optional) The user-facing label for - the option users can select if none of the suggested options is correct. If - no value is specified for this property, this option does not appear. - :param bool enabled: (optional) Whether the disambiguation feature is - enabled for the workspace. - :param str sensitivity: (optional) The sensitivity of the disambiguation - feature to intent detection conflicts. Set to **high** if you want the - disambiguation feature to be triggered more often. This can be useful for - testing or demonstration purposes. - :param bool randomize: (optional) Whether the order in which disambiguation - suggestions are presented should be randomized (but still influenced by - relative confidence). - :param int max_suggestions: (optional) The maximum number of disambigation - suggestions that can be included in a `suggestion` response. - :param str suggestion_text_policy: (optional) For internal use only. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str title: The title or introductory text to show before the + response. + :param List[DialogNodeOutputOptionsElement] options: An array of objects + describing the options from which the user can choose. + :param str description: (optional) The description to show with the the + response. + :param str preference: (optional) The preferred type of control to display. """ - self.prompt = prompt - self.none_of_the_above_prompt = none_of_the_above_prompt - self.enabled = enabled - self.sensitivity = sensitivity - self.randomize = randomize - self.max_suggestions = max_suggestions - self.suggestion_text_policy = suggestion_text_policy + self.response_type = response_type + self.title = title + self.description = description + self.preference = preference + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsDisambiguation': - """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeOption': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object from a json dictionary.""" args = {} valid_keys = [ - 'prompt', 'none_of_the_above_prompt', 'enabled', 'sensitivity', - 'randomize', 'max_suggestions', 'suggestion_text_policy' + 'response_type', 'title', 'description', 'preference', 'options' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsDisambiguation: ' - + ', '.join(bad_keys)) - if 'prompt' in _dict: - args['prompt'] = _dict.get('prompt') - if 'none_of_the_above_prompt' in _dict: - args['none_of_the_above_prompt'] = _dict.get( - 'none_of_the_above_prompt') - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'sensitivity' in _dict: - args['sensitivity'] = _dict.get('sensitivity') - if 'randomize' in _dict: - args['randomize'] = _dict.get('randomize') - if 'max_suggestions' in _dict: - args['max_suggestions'] = _dict.get('max_suggestions') - if 'suggestion_text_policy' in _dict: - args['suggestion_text_policy'] = _dict.get('suggestion_text_policy') + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeOption: ' + + ', '.join(bad_keys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + else: + raise ValueError( + 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'preference' in _dict: + args['preference'] = _dict.get('preference') + if 'options' in _dict: + args['options'] = [ + DialogNodeOutputOptionsElement._from_dict(x) + for x in (_dict.get('options')) + ] + else: + raise ValueError( + 'Required property \'options\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption 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, 'prompt') and self.prompt is not None: - _dict['prompt'] = self.prompt - if hasattr(self, 'none_of_the_above_prompt' - ) and self.none_of_the_above_prompt is not None: - _dict['none_of_the_above_prompt'] = self.none_of_the_above_prompt - if hasattr(self, 'enabled') and self.enabled is not None: - _dict['enabled'] = self.enabled - if hasattr(self, 'sensitivity') and self.sensitivity is not None: - _dict['sensitivity'] = self.sensitivity - if hasattr(self, 'randomize') and self.randomize is not None: - _dict['randomize'] = self.randomize - if hasattr(self, - 'max_suggestions') and self.max_suggestions is not None: - _dict['max_suggestions'] = self.max_suggestions - if hasattr(self, 'suggestion_text_policy' - ) and self.suggestion_text_policy is not None: - _dict['suggestion_text_policy'] = self.suggestion_text_policy + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'preference') and self.preference is not None: + _dict['preference'] = self.preference + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = [x._to_dict() for x in self.options] return _dict def _to_dict(self): @@ -10085,70 +11241,110 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this WorkspaceSystemSettingsDisambiguation object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeOption object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'WorkspaceSystemSettingsDisambiguation') -> bool: + def __eq__( + self, + other: 'RuntimeResponseGenericRuntimeResponseTypeOption') -> 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: 'WorkspaceSystemSettingsDisambiguation') -> bool: + def __ne__( + self, + other: 'RuntimeResponseGenericRuntimeResponseTypeOption') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class SensitivityEnum(Enum): + class ResponseTypeEnum(Enum): """ - The sensitivity of the disambiguation feature to intent detection conflicts. Set - to **high** if you want the disambiguation feature to be triggered more often. - This can be useful for testing or demonstration purposes. + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. """ - AUTO = "auto" - HIGH = "high" + OPTION = "option" + + class PreferenceEnum(Enum): + """ + The preferred type of control to display. + """ + DROPDOWN = "dropdown" + BUTTON = "button" -class WorkspaceSystemSettingsOffTopic(): +class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): """ - Workspace settings related to detection of irrelevant input. + An object that describes a response with response type `pause`. - :attr bool enabled: (optional) Whether enhanced irrelevance detection is enabled - for the workspace. + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr int time: How long to pause, in milliseconds. + :attr bool typing: (optional) Whether to send a "user is typing" event during + the pause. """ - def __init__(self, *, enabled: bool = None) -> None: + def __init__(self, + response_type: str, + time: int, + *, + typing: bool = None) -> None: """ - Initialize a WorkspaceSystemSettingsOffTopic object. + Initialize a RuntimeResponseGenericRuntimeResponseTypePause object. - :param bool enabled: (optional) Whether enhanced irrelevance detection is - enabled for the workspace. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param int time: How long to pause, in milliseconds. + :param bool typing: (optional) Whether to send a "user is typing" event + during the pause. """ - self.enabled = enabled + self.response_type = response_type + self.time = time + self.typing = typing @classmethod - def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsOffTopic': - """Initialize a WorkspaceSystemSettingsOffTopic object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypePause': + """Initialize a RuntimeResponseGenericRuntimeResponseTypePause object from a json dictionary.""" args = {} - valid_keys = ['enabled'] + valid_keys = ['response_type', 'time', 'typing'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsOffTopic: ' + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypePause: ' + ', '.join(bad_keys)) - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' + ) + if 'time' in _dict: + args['time'] = _dict.get('time') + else: + raise ValueError( + 'Required property \'time\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' + ) + if 'typing' in _dict: + args['typing'] = _dict.get('typing') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a WorkspaceSystemSettingsOffTopic object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypePause 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 + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'time') and self.time is not None: + _dict['time'] = self.time + if hasattr(self, 'typing') and self.typing is not None: + _dict['typing'] = self.typing return _dict def _to_dict(self): @@ -10156,61 +11352,107 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this WorkspaceSystemSettingsOffTopic object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypePause object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'WorkspaceSystemSettingsOffTopic') -> bool: + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypePause') -> 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: 'WorkspaceSystemSettingsOffTopic') -> bool: + def __ne__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypePause') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + PAUSE = "pause" -class WorkspaceSystemSettingsSystemEntities(): + +class RuntimeResponseGenericRuntimeResponseTypeSuggestion( + RuntimeResponseGeneric): """ - Workspace settings related to the behavior of system entities. + An object that describes a response with response type `suggestion`. - :attr bool enabled: (optional) Whether the new system entities are enabled for - the workspace. + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str title: The title or introductory text to show before the response. + :attr List[DialogSuggestion] suggestions: An array of objects describing the + possible matching dialog nodes from which the user can choose. """ - def __init__(self, *, enabled: bool = None) -> None: + def __init__(self, response_type: str, title: str, + suggestions: List['DialogSuggestion']) -> None: """ - Initialize a WorkspaceSystemSettingsSystemEntities object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object. - :param bool enabled: (optional) Whether the new system entities are enabled - for the workspace. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str title: The title or introductory text to show before the + response. + :param List[DialogSuggestion] suggestions: An array of objects describing + the possible matching dialog nodes from which the user can choose. """ - self.enabled = enabled + self.response_type = response_type + self.title = title + self.suggestions = suggestions @classmethod - def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsSystemEntities': - """Initialize a WorkspaceSystemSettingsSystemEntities object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeSuggestion': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object from a json dictionary.""" args = {} - valid_keys = ['enabled'] + valid_keys = ['response_type', 'title', 'suggestions'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsSystemEntities: ' + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeSuggestion: ' + ', '.join(bad_keys)) - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + else: + raise ValueError( + 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' + ) + if 'suggestions' in _dict: + args['suggestions'] = [ + DialogSuggestion._from_dict(x) + for x in (_dict.get('suggestions')) + ] + else: + raise ValueError( + 'Required property \'suggestions\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a WorkspaceSystemSettingsSystemEntities object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion 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 + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'suggestions') and self.suggestions is not None: + _dict['suggestions'] = [x._to_dict() for x in self.suggestions] return _dict def _to_dict(self): @@ -10218,63 +11460,90 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this WorkspaceSystemSettingsSystemEntities object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeSuggestion object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'WorkspaceSystemSettingsSystemEntities') -> bool: + def __eq__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + ) -> 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: + def __ne__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + SUGGESTION = "suggestion" + -class WorkspaceSystemSettingsTooling(): +class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): """ - Workspace settings related to the Watson Assistant user interface. + An object that describes a response with response type `text`. - :attr bool store_generic_responses: (optional) Whether the dialog JSON editor - displays text responses within the `output.generic` object. + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str text: The text of the response. """ - def __init__(self, *, store_generic_responses: bool = None) -> None: + def __init__(self, response_type: str, text: str) -> None: """ - Initialize a WorkspaceSystemSettingsTooling object. + Initialize a RuntimeResponseGenericRuntimeResponseTypeText object. - :param bool store_generic_responses: (optional) Whether the dialog JSON - editor displays text responses within the `output.generic` object. + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str text: The text of the response. """ - self.store_generic_responses = store_generic_responses + self.response_type = response_type + self.text = text @classmethod - def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsTooling': - """Initialize a WorkspaceSystemSettingsTooling object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeText': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeText object from a json dictionary.""" args = {} - valid_keys = ['store_generic_responses'] + valid_keys = ['response_type', 'text'] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: raise ValueError( - 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsTooling: ' + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeText: ' + ', '.join(bad_keys)) - if 'store_generic_responses' in _dict: - args['store_generic_responses'] = _dict.get( - 'store_generic_responses') + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' + ) + if 'text' in _dict: + args['text'] = _dict.get('text') + else: + raise ValueError( + 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a WorkspaceSystemSettingsTooling object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeText 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, 'store_generic_responses' - ) and self.store_generic_responses is not None: - _dict['store_generic_responses'] = self.store_generic_responses + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text return _dict def _to_dict(self): @@ -10282,15 +11551,24 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this WorkspaceSystemSettingsTooling object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeText object.""" return json.dumps(self._to_dict(), indent=2) - def __eq__(self, other: 'WorkspaceSystemSettingsTooling') -> bool: + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeText') -> 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: 'WorkspaceSystemSettingsTooling') -> bool: + def __ne__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeText') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + TEXT = "text" diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index cff1fdcc1..7f954261f 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -172,6 +172,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['page_limit'] = 12345 + body['include_count'] = True body['sort'] = "string1" body['cursor'] = "string1" body['include_audit'] = True @@ -242,7 +243,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() - body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + body.update({"name": "string1", "description": "string1", "language": "string1", "dialog_nodes": [], "counterexamples": [], "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "webhooks": [], "intents": [], "entities": [], }) body['include_audit'] = True return body @@ -386,7 +387,7 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"name": "string1", "description": "string1", "language": "string1", "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "intents": [], "entities": [], "dialog_nodes": [], "counterexamples": [], "webhooks": [], }) + body.update({"name": "string1", "description": "string1", "language": "string1", "dialog_nodes": [], "counterexamples": [], "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "webhooks": [], "intents": [], "entities": [], }) body['append'] = True body['include_audit'] = True return body @@ -541,6 +542,7 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['export'] = True body['page_limit'] = 12345 + body['include_count'] = True body['sort'] = "string1" body['cursor'] = "string1" body['include_audit'] = True @@ -921,6 +923,7 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['intent'] = "string1" body['page_limit'] = 12345 + body['include_count'] = True body['sort'] = "string1" body['cursor'] = "string1" body['include_audit'] = True @@ -1307,6 +1310,7 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['page_limit'] = 12345 + body['include_count'] = True body['sort'] = "string1" body['cursor'] = "string1" body['include_audit'] = True @@ -1685,6 +1689,7 @@ def construct_full_body(self): body['workspace_id'] = "string1" body['export'] = True body['page_limit'] = 12345 + body['include_count'] = True body['sort'] = "string1" body['cursor'] = "string1" body['include_audit'] = True @@ -2150,6 +2155,7 @@ def construct_full_body(self): body['entity'] = "string1" body['export'] = True body['page_limit'] = 12345 + body['include_count'] = True body['sort'] = "string1" body['cursor'] = "string1" body['include_audit'] = True @@ -2540,6 +2546,7 @@ def construct_full_body(self): body['entity'] = "string1" body['value'] = "string1" body['page_limit'] = 12345 + body['include_count'] = True body['sort'] = "string1" body['cursor'] = "string1" body['include_audit'] = True @@ -2935,6 +2942,7 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['page_limit'] = 12345 + body['include_count'] = True body['sort'] = "string1" body['cursor'] = "string1" body['include_audit'] = True @@ -3008,14 +3016,14 @@ def call_service(self, body): def construct_full_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) + body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": DialogNodeContext._from_dict(json.loads("""{}""")), "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) body['include_audit'] = True return body def construct_required_body(self): body = dict() body['workspace_id'] = "string1" - body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": {"mock": "data"}, "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) + body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": DialogNodeContext._from_dict(json.loads("""{}""")), "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) return body @@ -3155,7 +3163,7 @@ def construct_full_body(self): body = dict() body['workspace_id'] = "string1" body['dialog_node'] = "string1" - body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) + body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": DialogNodeContext._from_dict(json.loads("""{}""")), "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) body['include_audit'] = True return body @@ -3163,7 +3171,7 @@ def construct_required_body(self): body = dict() body['workspace_id'] = "string1" body['dialog_node'] = "string1" - body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": {"mock": "data"}, "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) + body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": DialogNodeContext._from_dict(json.loads("""{}""")), "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) return body @@ -3481,6 +3489,87 @@ def construct_required_body(self): # End of Service: UserData ############################################################################## +############################################################################## +# Start of Service: BulkClassify +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for bulk_classify +#----------------------------------------------------------------------------- +class TestBulkClassify(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_bulk_classify_response(self): + body = self.construct_full_body() + response = fake_response_BulkClassifyResponse_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_bulk_classify_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BulkClassifyResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_bulk_classify_empty(self): + check_empty_required_params(self, fake_response_BulkClassifyResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v1/workspaces/{0}/bulk_classify'.format(body['workspace_id']) + 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 = AssistantV1( + authenticator=NoAuthAuthenticator(), + version='2020-04-01', + ) + service.set_service_url(base_url) + output = service.bulk_classify(**body) + return output + + def construct_full_body(self): + body = dict() + body['workspace_id'] = "string1" + body.update({"input": [], }) + return body + + def construct_required_body(self): + body = dict() + body['workspace_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: BulkClassify +############################################################################## + def check_empty_required_params(obj, response): """Test function to assert that the operation will throw an error when given empty required data @@ -3548,9 +3637,9 @@ def send_request(obj, body, response, url=None): fake_response__json = None fake_response_MessageResponse_json = """{"input": {"text": "fake_text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "fake_suggested_text", "original_text": "fake_original_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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "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", "workspace_id": "fake_workspace_id", "dialog_nodes": [], "counterexamples": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "fake_status", "webhooks": [], "intents": [], "entities": []}""" +fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "workspace_id": "fake_workspace_id", "dialog_nodes": [], "counterexamples": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "fake_status", "webhooks": [], "intents": [], "entities": []}""" +fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "workspace_id": "fake_workspace_id", "dialog_nodes": [], "counterexamples": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "fake_status", "webhooks": [], "intents": [], "entities": []}""" 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": []}""" @@ -3577,8 +3666,9 @@ def send_request(obj, body, response, url=None): fake_response_Synonym_json = """{"synonym": "fake_synonym", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" fake_response_Synonym_json = """{"synonym": "fake_synonym", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" fake_response_DialogNodeCollection_json = """{"dialog_nodes": [], "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_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "context": {}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "context": {}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" +fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "context": {}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" +fake_response_BulkClassifyResponse_json = """{"output": []}""" From 8b14dda82de980f09a031b1e15ab53573a5b55d8 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 16 Nov 2020 15:53:59 -0500 Subject: [PATCH 287/455] feat(AssistantV2): add support for bulkClassify --- ibm_watson/assistant_v2.py | 1466 +++++++++++++++++++++++++++----- test/unit/test_assistant_v2.py | 94 +- 2 files changed, 1331 insertions(+), 229 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 9fa7594cf..411ac37b0 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -30,6 +30,7 @@ from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment from typing import Dict from typing import List +import sys ############################################################################## # Service @@ -43,10 +44,10 @@ class AssistantV2(BaseService): DEFAULT_SERVICE_NAME = 'assistant' def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Assistant service. @@ -416,12 +417,284 @@ def delete_user_data(self, customer_id: str, response = self.send(request) return response + ######################### + # bulkClassify + ######################### + + def bulk_classify(self, + skill_id: str, + *, + input: List['BulkClassifyUtterance'] = None, + **kwargs) -> 'DetailedResponse': + """ + Identify intents and entities in multiple user utterances. + + Send multiple user inputs to a dialog skill in a single request and receive + information about the intents and entities recognized in each input. This method + is useful for testing and comparing the performance of different skills or skill + versions. + This method is available only with Premium plans. + + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the Watson Assistant user interface, open the skill settings and click + **API Details**. + :param List[BulkClassifyUtterance] input: (optional) An array of input + utterances to classify. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if skill_id is None: + raise ValueError('skill_id must be provided') + if input is not None: + input = [self._convert_model(x) for x in input] + + headers = {} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='bulk_classify') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'input': input} + + url = '/v2/skills/{0}/workspace/bulk_classify'.format( + *self._encode_path_vars(skill_id)) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + ############################################################################## # Models ############################################################################## +class BulkClassifyOutput(): + """ + BulkClassifyOutput. + + :attr BulkClassifyUtterance input: (optional) The user input utterance to + classify. + :attr List[RuntimeEntity] entities: (optional) An array of entities identified + in the utterance. + :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + the utterance. + """ + + def __init__(self, + *, + input: 'BulkClassifyUtterance' = None, + entities: List['RuntimeEntity'] = None, + intents: List['RuntimeIntent'] = None) -> None: + """ + Initialize a BulkClassifyOutput object. + + :param BulkClassifyUtterance input: (optional) The user input utterance to + classify. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the utterance. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the utterance. + """ + self.input = input + self.entities = entities + self.intents = intents + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': + """Initialize a BulkClassifyOutput object from a json dictionary.""" + args = {} + valid_keys = ['input', 'entities', 'intents'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class BulkClassifyOutput: ' + + ', '.join(bad_keys)) + if 'input' in _dict: + args['input'] = BulkClassifyUtterance._from_dict(_dict.get('input')) + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + ] + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BulkClassifyOutput 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, 'input') and self.input is not None: + _dict['input'] = self.input._to_dict() + if hasattr(self, 'entities') and self.entities is not None: + _dict['entities'] = [x._to_dict() for x in self.entities] + if hasattr(self, 'intents') and self.intents is not None: + _dict['intents'] = [x._to_dict() for x in self.intents] + 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 BulkClassifyOutput object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'BulkClassifyOutput') -> 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: 'BulkClassifyOutput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class BulkClassifyResponse(): + """ + BulkClassifyResponse. + + :attr List[BulkClassifyOutput] output: (optional) An array of objects that + contain classification information for the submitted input utterances. + """ + + def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: + """ + Initialize a BulkClassifyResponse object. + + :param List[BulkClassifyOutput] output: (optional) An array of objects that + contain classification information for the submitted input utterances. + """ + self.output = output + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': + """Initialize a BulkClassifyResponse object from a json dictionary.""" + args = {} + valid_keys = ['output'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class BulkClassifyResponse: ' + + ', '.join(bad_keys)) + if 'output' in _dict: + args['output'] = [ + BulkClassifyOutput._from_dict(x) for x in (_dict.get('output')) + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BulkClassifyResponse 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, 'output') and self.output is not None: + _dict['output'] = [x._to_dict() for x in self.output] + 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 BulkClassifyResponse object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'BulkClassifyResponse') -> 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: 'BulkClassifyResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class BulkClassifyUtterance(): + """ + The user input utterance to classify. + + :attr str text: The text of the input utterance. + """ + + def __init__(self, text: str) -> None: + """ + Initialize a BulkClassifyUtterance object. + + :param str text: The text of the input utterance. + """ + self.text = text + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': + """Initialize a BulkClassifyUtterance object from a json dictionary.""" + args = {} + valid_keys = ['text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class BulkClassifyUtterance: ' + + ', '.join(bad_keys)) + if 'text' in _dict: + args['text'] = _dict.get('text') + else: + raise ValueError( + 'Required property \'text\' not present in BulkClassifyUtterance JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BulkClassifyUtterance 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, 'text') and self.text is not None: + _dict['text'] = self.text + 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 BulkClassifyUtterance object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'BulkClassifyUtterance') -> 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: 'BulkClassifyUtterance') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class CaptureGroup(): """ CaptureGroup. @@ -697,6 +970,69 @@ class TypeEnum(Enum): CLOUD_FUNCTION = "cloud-function" +class DialogNodeOutputConnectToAgentTransferInfo(): + """ + Routing or other contextual information to be used by target service desk systems. + + :attr dict target: (optional) + """ + + def __init__(self, *, target: dict = None) -> None: + """ + Initialize a DialogNodeOutputConnectToAgentTransferInfo object. + + :param dict target: (optional) + """ + self.target = target + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': + """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" + args = {} + valid_keys = ['target'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class DialogNodeOutputConnectToAgentTransferInfo: ' + + ', '.join(bad_keys)) + if 'target' in _dict: + args['target'] = _dict.get('target') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputConnectToAgentTransferInfo 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, 'target') and self.target is not None: + _dict['target'] = self.target + 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 DialogNodeOutputConnectToAgentTransferInfo object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, + other: 'DialogNodeOutputConnectToAgentTransferInfo') -> 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: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class DialogNodeOutputOptionsElement(): """ DialogNodeOutputOptionsElement. @@ -1832,19 +2168,21 @@ class MessageContextSkill(): :attr dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. - :attr dict system: (optional) System context data used by the skill. + :attr MessageContextSkillSystem system: (optional) System context data used by + the skill. """ def __init__(self, *, user_defined: dict = None, - system: dict = None) -> None: + system: 'MessageContextSkillSystem' = None) -> None: """ Initialize a MessageContextSkill object. :param dict user_defined: (optional) Arbitrary variables that can be read and written by a particular skill. - :param dict system: (optional) System context data used by the skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. """ self.user_defined = user_defined self.system = system @@ -1862,7 +2200,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') if 'system' in _dict: - args['system'] = _dict.get('system') + args['system'] = MessageContextSkillSystem._from_dict( + _dict.get('system')) return cls(**args) @classmethod @@ -1876,7 +2215,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system + _dict['system'] = self.system._to_dict() return _dict def _to_dict(self): @@ -1902,25 +2241,22 @@ class MessageContextSkillSystem(): """ System context data used by the skill. - :attr str state: (optional) An encoded string representing the current + :attr str state: (optional) An encoded string that represents the current conversation state. By saving this value and then sending it in the context of a - subsequent message request, you can restore the conversation to the same state. - This can be useful if you need to return to an earlier point in the + subsequent message request, you can return to an earlier point in the conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session has expired. + state value to restore a paused conversation whose session is expired. """ def __init__(self, *, state: str = None, **kwargs) -> None: """ Initialize a MessageContextSkillSystem object. - :param str state: (optional) An encoded string representing the current + :param str state: (optional) An encoded string that represents the current conversation state. By saving this value and then sending it in the context - of a subsequent message request, you can restore the conversation to the - same state. This can be useful if you need to return to an earlier point in - the conversation. If you are using stateful sessions, you can also use a - stored state value to restore a paused conversation whose session has - expired. + of a subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. :param **kwargs: (optional) Any additional properties. """ self.state = state @@ -4119,225 +4455,73 @@ class RuntimeResponseGeneric(): """ RuntimeResponseGeneric. - :attr str response_type: The type of response returned by the dialog node. The - specified response type must be supported by the client application or channel. - :attr str text: (optional) The text of the response. - :attr int time: (optional) How long to pause, in milliseconds. - :attr bool typing: (optional) Whether to send a "user is typing" event during - the pause. - :attr str source: (optional) The URL of the image. - :attr str title: (optional) The title or introductory text to show before the - response. - :attr str description: (optional) The description to show with the the response. - :attr str preference: (optional) The preferred type of control to display. - :attr List[DialogNodeOutputOptionsElement] options: (optional) An array of - objects describing the options from which the user can choose. - :attr str message_to_human_agent: (optional) A message to be sent to the human - agent who will be taking over the conversation. - :attr str topic: (optional) A label identifying the topic of the conversation, - derived from the **user_label** property of the relevant node. - :attr List[DialogSuggestion] suggestions: (optional) An array of objects - describing the possible matching dialog nodes from which the user can choose. - :attr str header: (optional) The title or introductory text to show before the - response. This text is defined in the search skill configuration. - :attr List[SearchResult] results: (optional) An array of objects containing - search results. """ - def __init__(self, - response_type: str, - *, - text: str = None, - time: int = None, - typing: bool = None, - source: str = None, - title: str = None, - description: str = None, - preference: str = None, - options: List['DialogNodeOutputOptionsElement'] = None, - message_to_human_agent: str = None, - topic: str = None, - suggestions: List['DialogSuggestion'] = None, - header: str = None, - results: List['SearchResult'] = None) -> None: + def __init__(self) -> None: """ Initialize a RuntimeResponseGeneric object. - :param str response_type: The type of response returned by the dialog node. - The specified response type must be supported by the client application or - channel. - :param str text: (optional) The text of the response. - :param int time: (optional) How long to pause, in milliseconds. - :param bool typing: (optional) Whether to send a "user is typing" event - during the pause. - :param str source: (optional) The URL of the image. - :param str title: (optional) The title or introductory text to show before - the response. - :param str description: (optional) The description to show with the the - response. - :param str preference: (optional) The preferred type of control to display. - :param List[DialogNodeOutputOptionsElement] options: (optional) An array of - objects describing the options from which the user can choose. - :param str message_to_human_agent: (optional) A message to be sent to the - human agent who will be taking over the conversation. - :param str topic: (optional) A label identifying the topic of the - conversation, derived from the **user_label** property of the relevant - node. - :param List[DialogSuggestion] suggestions: (optional) An array of objects - describing the possible matching dialog nodes from which the user can - choose. - :param str header: (optional) The title or introductory text to show before - the response. This text is defined in the search skill configuration. - :param List[SearchResult] results: (optional) An array of objects - containing search results. """ - self.response_type = response_type - self.text = text - self.time = time - self.typing = typing - self.source = source - self.title = title - self.description = description - self.preference = preference - self.options = options - self.message_to_human_agent = message_to_human_agent - self.topic = topic - self.suggestions = suggestions - self.header = header - self.results = results + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeSearch' + ])) + raise Exception(msg) @classmethod def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - args = {} - valid_keys = [ - 'response_type', 'text', 'time', 'typing', 'source', 'title', - 'description', 'preference', 'options', 'message_to_human_agent', - 'topic', 'suggestions', 'header', 'results' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGeneric: ' - + ', '.join(bad_keys)) - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') - else: - raise ValueError( - 'Required property \'response_type\' not present in RuntimeResponseGeneric JSON' - ) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'time' in _dict: - args['time'] = _dict.get('time') - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'source' in _dict: - args['source'] = _dict.get('source') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: - args['options'] = [ - DialogNodeOutputOptionsElement._from_dict(x) - for x in (_dict.get('options')) - ] - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'topic' in _dict: - args['topic'] = _dict.get('topic') - if 'suggestions' in _dict: - args['suggestions'] = [ - DialogSuggestion._from_dict(x) - for x in (_dict.get('suggestions')) - ] - if 'header' in _dict: - args['header'] = _dict.get('header') - if 'results' in _dict: - args['results'] = [ - SearchResult._from_dict(x) for x in (_dict.get('results')) - ] - return cls(**args) + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class '{0}'. The discriminator value should map to a valid subclass: {1}".format( + cls.__name__, ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeSearch' + ])) + raise Exception(msg) @classmethod - def _from_dict(cls, _dict): + def _from_dict(cls, _dict: Dict): """Initialize a RuntimeResponseGeneric 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, 'response_type') and self.response_type is not None: - _dict['response_type'] = self.response_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'time') and self.time is not None: - _dict['time'] = self.time - if hasattr(self, 'typing') and self.typing is not None: - _dict['typing'] = self.typing - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'preference') and self.preference is not None: - _dict['preference'] = self.preference - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x._to_dict() for x in self.options] - if hasattr(self, 'message_to_human_agent' - ) and self.message_to_human_agent is not None: - _dict['message_to_human_agent'] = self.message_to_human_agent - if hasattr(self, 'topic') and self.topic is not None: - _dict['topic'] = self.topic - if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x._to_dict() for x in self.suggestions] - if hasattr(self, 'header') and self.header is not None: - _dict['header'] = self.header - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] - 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 RuntimeResponseGeneric object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other: 'RuntimeResponseGeneric') -> 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: 'RuntimeResponseGeneric') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ResponseTypeEnum(Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - TEXT = "text" - PAUSE = "pause" - IMAGE = "image" - OPTION = "option" - CONNECT_TO_AGENT = "connect_to_agent" - SUGGESTION = "suggestion" - SEARCH = "search" - - class PreferenceEnum(Enum): - """ - The preferred type of control to display. - """ - DROPDOWN = "dropdown" - BUTTON = "button" + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' + mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' + mapping[ + 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' + mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' + mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) class SearchResult(): @@ -4723,3 +4907,839 @@ def __eq__(self, other: 'SessionResponse') -> bool: def __ne__(self, other: 'SessionResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + + +class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( + RuntimeResponseGeneric): + """ + An object that describes a response with response type `connect_to_agent`. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str message_to_human_agent: (optional) A message to be sent to the human + agent who will be taking over the conversation. + :attr str agent_available: (optional) An optional message to be displayed to the + user to indicate that the conversation will be transferred to the next available + agent. + :attr str agent_unavailable: (optional) An optional message to be displayed to + the user to indicate that no online agent is available to take over the + conversation. + :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + Routing or other contextual information to be used by target service desk + systems. + :attr str topic: (optional) A label identifying the topic of the conversation, + derived from the **title** property of the relevant node or the **topic** + property of the dialog node response. + """ + + def __init__( + self, + response_type: str, + *, + message_to_human_agent: str = None, + agent_available: str = None, + agent_unavailable: str = None, + transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, + topic: str = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str message_to_human_agent: (optional) A message to be sent to the + human agent who will be taking over the conversation. + :param str agent_available: (optional) An optional message to be displayed + to the user to indicate that the conversation will be transferred to the + next available agent. + :param str agent_unavailable: (optional) An optional message to be + displayed to the user to indicate that no online agent is available to take + over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + Routing or other contextual information to be used by target service desk + systems. + :param str topic: (optional) A label identifying the topic of the + conversation, derived from the **title** property of the relevant node or + the **topic** property of the dialog node response. + """ + self.response_type = response_type + self.message_to_human_agent = message_to_human_agent + self.agent_available = agent_available + self.agent_unavailable = agent_unavailable + self.transfer_info = transfer_info + self.topic = topic + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" + args = {} + valid_keys = [ + 'response_type', 'message_to_human_agent', 'agent_available', + 'agent_unavailable', 'transfer_info', 'topic' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent: ' + + ', '.join(bad_keys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeConnectToAgent JSON' + ) + if 'message_to_human_agent' in _dict: + args['message_to_human_agent'] = _dict.get('message_to_human_agent') + if 'agent_available' in _dict: + args['agent_available'] = _dict.get('agent_available') + if 'agent_unavailable' in _dict: + args['agent_unavailable'] = _dict.get('agent_unavailable') + if 'transfer_info' in _dict: + args[ + 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo._from_dict( + _dict.get('transfer_info')) + if 'topic' in _dict: + args['topic'] = _dict.get('topic') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'message_to_human_agent' + ) and self.message_to_human_agent is not None: + _dict['message_to_human_agent'] = self.message_to_human_agent + if hasattr(self, + 'agent_available') and self.agent_available is not None: + _dict['agent_available'] = self.agent_available + if hasattr(self, + 'agent_unavailable') and self.agent_unavailable is not None: + _dict['agent_unavailable'] = self.agent_unavailable + if hasattr(self, 'transfer_info') and self.transfer_info is not None: + _dict['transfer_info'] = self.transfer_info._to_dict() + if hasattr(self, 'topic') and self.topic is not None: + _dict['topic'] = self.topic + 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 RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + ) -> 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: 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + CONNECT_TO_AGENT = "connect_to_agent" + + +class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): + """ + An object that describes a response with response type `image`. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str source: The URL of the image. + :attr str title: (optional) The title to show before the response. + :attr str description: (optional) The description to show with the the response. + """ + + def __init__(self, + response_type: str, + source: str, + *, + title: str = None, + description: str = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The URL of the image. + :param str title: (optional) The title to show before the response. + :param str description: (optional) The description to show with the the + response. + """ + self.response_type = response_type + self.source = source + self.title = title + self.description = description + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeImage': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object from a json dictionary.""" + args = {} + valid_keys = ['response_type', 'source', 'title', 'description'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeImage: ' + + ', '.join(bad_keys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' + ) + if 'source' in _dict: + args['source'] = _dict.get('source') + else: + raise ValueError( + 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + 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 RuntimeResponseGenericRuntimeResponseTypeImage object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeImage') -> 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: 'RuntimeResponseGenericRuntimeResponseTypeImage') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + IMAGE = "image" + + +class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): + """ + An object that describes a response with response type `option`. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str title: The title or introductory text to show before the response. + :attr str description: (optional) The description to show with the the response. + :attr str preference: (optional) The preferred type of control to display. + :attr List[DialogNodeOutputOptionsElement] options: An array of objects + describing the options from which the user can choose. + """ + + def __init__(self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: str = None, + preference: str = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str title: The title or introductory text to show before the + response. + :param List[DialogNodeOutputOptionsElement] options: An array of objects + describing the options from which the user can choose. + :param str description: (optional) The description to show with the the + response. + :param str preference: (optional) The preferred type of control to display. + """ + self.response_type = response_type + self.title = title + self.description = description + self.preference = preference + self.options = options + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeOption': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object from a json dictionary.""" + args = {} + valid_keys = [ + 'response_type', 'title', 'description', 'preference', 'options' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeOption: ' + + ', '.join(bad_keys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + else: + raise ValueError( + 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'preference' in _dict: + args['preference'] = _dict.get('preference') + if 'options' in _dict: + args['options'] = [ + DialogNodeOutputOptionsElement._from_dict(x) + for x in (_dict.get('options')) + ] + else: + raise ValueError( + 'Required property \'options\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'preference') and self.preference is not None: + _dict['preference'] = self.preference + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = [x._to_dict() for x in self.options] + 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 RuntimeResponseGenericRuntimeResponseTypeOption object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__( + self, + other: 'RuntimeResponseGenericRuntimeResponseTypeOption') -> 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: 'RuntimeResponseGenericRuntimeResponseTypeOption') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + OPTION = "option" + + class PreferenceEnum(Enum): + """ + The preferred type of control to display. + """ + DROPDOWN = "dropdown" + BUTTON = "button" + + +class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): + """ + An object that describes a response with response type `pause`. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr int time: How long to pause, in milliseconds. + :attr bool typing: (optional) Whether to send a "user is typing" event during + the pause. + """ + + def __init__(self, + response_type: str, + time: int, + *, + typing: bool = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypePause object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param int time: How long to pause, in milliseconds. + :param bool typing: (optional) Whether to send a "user is typing" event + during the pause. + """ + self.response_type = response_type + self.time = time + self.typing = typing + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypePause': + """Initialize a RuntimeResponseGenericRuntimeResponseTypePause object from a json dictionary.""" + args = {} + valid_keys = ['response_type', 'time', 'typing'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypePause: ' + + ', '.join(bad_keys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' + ) + if 'time' in _dict: + args['time'] = _dict.get('time') + else: + raise ValueError( + 'Required property \'time\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' + ) + if 'typing' in _dict: + args['typing'] = _dict.get('typing') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypePause 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'time') and self.time is not None: + _dict['time'] = self.time + if hasattr(self, 'typing') and self.typing is not None: + _dict['typing'] = self.typing + 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 RuntimeResponseGenericRuntimeResponseTypePause object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypePause') -> 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: 'RuntimeResponseGenericRuntimeResponseTypePause') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + PAUSE = "pause" + + +class RuntimeResponseGenericRuntimeResponseTypeSearch(RuntimeResponseGeneric): + """ + An object that describes a response with response type `search`. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str header: The title or introductory text to show before the response. + This text is defined in the search skill configuration. + :attr List[SearchResult] primary_results: An array of objects that contains the + search results to be displayed in the initial response to the user. + :attr List[SearchResult] additional_results: An array of objects that contains + additional search results that can be displayed to the user upon request. + """ + + def __init__(self, response_type: str, header: str, + primary_results: List['SearchResult'], + additional_results: List['SearchResult']) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeSearch object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str header: The title or introductory text to show before the + response. This text is defined in the search skill configuration. + :param List[SearchResult] primary_results: An array of objects that + contains the search results to be displayed in the initial response to the + user. + :param List[SearchResult] additional_results: An array of objects that + contains additional search results that can be displayed to the user upon + request. + """ + self.response_type = response_type + self.header = header + self.primary_results = primary_results + self.additional_results = additional_results + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeSearch': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeSearch object from a json dictionary.""" + args = {} + valid_keys = [ + 'response_type', 'header', 'primary_results', 'additional_results' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeSearch: ' + + ', '.join(bad_keys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' + ) + if 'header' in _dict: + args['header'] = _dict.get('header') + else: + raise ValueError( + 'Required property \'header\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' + ) + if 'primary_results' in _dict: + args['primary_results'] = [ + SearchResult._from_dict(x) + for x in (_dict.get('primary_results')) + ] + else: + raise ValueError( + 'Required property \'primary_results\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' + ) + if 'additional_results' in _dict: + args['additional_results'] = [ + SearchResult._from_dict(x) + for x in (_dict.get('additional_results')) + ] + else: + raise ValueError( + 'Required property \'additional_results\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeSearch 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'header') and self.header is not None: + _dict['header'] = self.header + if hasattr(self, + 'primary_results') and self.primary_results is not None: + _dict['primary_results'] = [ + x._to_dict() for x in self.primary_results + ] + if hasattr( + self, + 'additional_results') and self.additional_results is not None: + _dict['additional_results'] = [ + x._to_dict() for x in self.additional_results + ] + 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 RuntimeResponseGenericRuntimeResponseTypeSearch object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__( + self, + other: 'RuntimeResponseGenericRuntimeResponseTypeSearch') -> 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: 'RuntimeResponseGenericRuntimeResponseTypeSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + SEARCH = "search" + + +class RuntimeResponseGenericRuntimeResponseTypeSuggestion( + RuntimeResponseGeneric): + """ + An object that describes a response with response type `suggestion`. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str title: The title or introductory text to show before the response. + :attr List[DialogSuggestion] suggestions: An array of objects describing the + possible matching dialog nodes from which the user can choose. + """ + + def __init__(self, response_type: str, title: str, + suggestions: List['DialogSuggestion']) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str title: The title or introductory text to show before the + response. + :param List[DialogSuggestion] suggestions: An array of objects describing + the possible matching dialog nodes from which the user can choose. + """ + self.response_type = response_type + self.title = title + self.suggestions = suggestions + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeSuggestion': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object from a json dictionary.""" + args = {} + valid_keys = ['response_type', 'title', 'suggestions'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeSuggestion: ' + + ', '.join(bad_keys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + else: + raise ValueError( + 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' + ) + if 'suggestions' in _dict: + args['suggestions'] = [ + DialogSuggestion._from_dict(x) + for x in (_dict.get('suggestions')) + ] + else: + raise ValueError( + 'Required property \'suggestions\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'suggestions') and self.suggestions is not None: + _dict['suggestions'] = [x._to_dict() for x in self.suggestions] + 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 RuntimeResponseGenericRuntimeResponseTypeSuggestion object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + ) -> 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: 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + SUGGESTION = "suggestion" + + +class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): + """ + An object that describes a response with response type `text`. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str text: The text of the response. + """ + + def __init__(self, response_type: str, text: str) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeText object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str text: The text of the response. + """ + self.response_type = response_type + self.text = text + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeText': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeText object from a json dictionary.""" + args = {} + valid_keys = ['response_type', 'text'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeText: ' + + ', '.join(bad_keys)) + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' + ) + if 'text' in _dict: + args['text'] = _dict.get('text') + else: + raise ValueError( + 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeText 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + 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 RuntimeResponseGenericRuntimeResponseTypeText object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeText') -> 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: 'RuntimeResponseGenericRuntimeResponseTypeText') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ResponseTypeEnum(Enum): + """ + The type of response returned by the dialog node. The specified response type must + be supported by the client application or channel. + """ + TEXT = "text" diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index a0b8cf62b..caf5aefac 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -81,7 +81,7 @@ def add_mock_response(self, url, response): def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), - version='2020-04-01', + version='2020-09-24', ) service.set_service_url(base_url) output = service.create_session(**body) @@ -151,7 +151,7 @@ def add_mock_response(self, url, response): def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), - version='2020-04-01', + version='2020-09-24', ) service.set_service_url(base_url) output = service.delete_session(**body) @@ -233,7 +233,7 @@ def add_mock_response(self, url, response): def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), - version='2020-04-01', + version='2020-09-24', ) service.set_service_url(base_url) output = service.message(**body) @@ -306,7 +306,7 @@ def add_mock_response(self, url, response): def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), - version='2020-04-01', + version='2020-09-24', ) service.set_service_url(base_url) output = service.message_stateless(**body) @@ -387,7 +387,7 @@ def add_mock_response(self, url, response): def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), - version='2020-04-01', + version='2020-09-24', ) service.set_service_url(base_url) output = service.list_logs(**body) @@ -471,7 +471,7 @@ def add_mock_response(self, url, response): def call_service(self, body): service = AssistantV2( authenticator=NoAuthAuthenticator(), - version='2020-04-01', + version='2020-09-24', ) service.set_service_url(base_url) output = service.delete_user_data(**body) @@ -493,6 +493,87 @@ def construct_required_body(self): # End of Service: UserData ############################################################################## +############################################################################## +# Start of Service: BulkClassify +############################################################################## +# region + +#----------------------------------------------------------------------------- +# Test Class for bulk_classify +#----------------------------------------------------------------------------- +class TestBulkClassify(): + + #-------------------------------------------------------- + # Test 1: Send fake data and check response + #-------------------------------------------------------- + @responses.activate + def test_bulk_classify_response(self): + body = self.construct_full_body() + response = fake_response_BulkClassifyResponse_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_bulk_classify_required_response(self): + # Check response with required params + body = self.construct_required_body() + response = fake_response_BulkClassifyResponse_json + send_request(self, body, response) + assert len(responses.calls) == 1 + + #-------------------------------------------------------- + # Test 3: Send empty data and check response + #-------------------------------------------------------- + @responses.activate + def test_bulk_classify_empty(self): + check_empty_required_params(self, fake_response_BulkClassifyResponse_json) + check_missing_required_params(self) + assert len(responses.calls) == 0 + + #----------- + #- Helpers - + #----------- + def make_url(self, body): + endpoint = '/v2/skills/{0}/workspace/bulk_classify'.format(body['skill_id']) + 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 = AssistantV2( + authenticator=NoAuthAuthenticator(), + version='2020-09-24', + ) + service.set_service_url(base_url) + output = service.bulk_classify(**body) + return output + + def construct_full_body(self): + body = dict() + body['skill_id'] = "string1" + body.update({"input": [], }) + return body + + def construct_required_body(self): + body = dict() + body['skill_id'] = "string1" + return body + + +# endregion +############################################################################## +# End of Service: BulkClassify +############################################################################## + def check_empty_required_params(obj, response): """Test function to assert that the operation will throw an error when given empty required data @@ -562,3 +643,4 @@ def send_request(obj, body, response, url=None): fake_response_MessageResponse_json = """{"output": {"generic": [], "intents": [], "entities": [], "actions": [], "debug": {"nodes_visited": [], "log_messages": [], "branch_exited": false, "branch_exited_reason": "fake_branch_exited_reason"}, "spelling": {"text": "fake_text", "original_text": "fake_original_text", "suggested_text": "fake_suggested_text"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}}""" fake_response_MessageResponseStateless_json = """{"output": {"generic": [], "intents": [], "entities": [], "actions": [], "debug": {"nodes_visited": [], "log_messages": [], "branch_exited": false, "branch_exited_reason": "fake_branch_exited_reason"}, "spelling": {"text": "fake_text", "original_text": "fake_original_text", "suggested_text": "fake_suggested_text"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}}""" fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" +fake_response_BulkClassifyResponse_json = """{"output": []}""" From e84a0cb0636cd0add767903391de150bd65a4cd2 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 16 Nov 2020 15:55:16 -0500 Subject: [PATCH 288/455] feat: regenrate services using current api def and generator --- ibm_watson/discovery_v2.py | 188 +++++++++++++++--- .../natural_language_understanding_v1.py | 17 +- test/unit/test_discovery_v2.py | 2 +- .../test_natural_language_understanding_v1.py | 6 +- 4 files changed, 175 insertions(+), 38 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 49127fdda..e4aa4bedc 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -48,10 +48,10 @@ class DiscoveryV2(BaseService): DEFAULT_SERVICE_NAME = 'discovery' def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Discovery service. @@ -1763,7 +1763,7 @@ class FileContentType(Enum): class AnalyzedDocument(): """ - An object containing the converted document and any identifed enrichments. + An object containing the converted document and any identified enrichments. :attr List[Notice] notices: (optional) Array of document results that match the query. @@ -2170,15 +2170,15 @@ class Completions(): """ An object containing an array of autocompletion suggestions. - :attr List[str] completions: (optional) Array of autcomplete suggestion based on - the provided prefix. + :attr List[str] completions: (optional) Array of autocomplete suggestion based + on the provided prefix. """ def __init__(self, *, completions: List[str] = None) -> None: """ Initialize a Completions object. - :param List[str] completions: (optional) Array of autcomplete suggestion + :param List[str] completions: (optional) Array of autocomplete suggestion based on the provided prefix. """ self.completions = completions @@ -2759,9 +2759,9 @@ class DefaultQueryParams(): :attr DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) Object containing suggested refinement settings. :attr bool spelling_suggestions: (optional) When `true`, a spelling suggestions - for the query are retuned by default. + for the query are returned by default. :attr bool highlight: (optional) When `true`, a highlights for the query are - retuned by default. + returned by default. :attr int count: (optional) The number of document results returned by default. :attr str sort: (optional) A comma separated list of document fields to sort results by default. @@ -2797,9 +2797,9 @@ def __init__(self, :param DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) Object containing suggested refinement settings. :param bool spelling_suggestions: (optional) When `true`, a spelling - suggestions for the query are retuned by default. + suggestions for the query are returned by default. :param bool highlight: (optional) When `true`, a highlights for the query - are retuned by default. + are returned by default. :param int count: (optional) The number of document results returned by default. :param str sort: (optional) A comma separated list of document fields to @@ -2918,8 +2918,8 @@ class DefaultQueryParamsPassages(): :attr bool enabled: (optional) When `true`, a passage search is performed by default. :attr int count: (optional) The number of passages to return. - :attr List[str] fields: (optional) An array of field names to perfom the passage - search on. + :attr List[str] fields: (optional) An array of field names to perform the + passage search on. :attr int characters: (optional) The approximate number of characters that each returned passage will contain. :attr bool per_document: (optional) When `true` the number of passages that can @@ -2943,7 +2943,7 @@ def __init__(self, :param bool enabled: (optional) When `true`, a passage search is performed by default. :param int count: (optional) The number of passages to return. - :param List[str] fields: (optional) An array of field names to perfom the + :param List[str] fields: (optional) An array of field names to perform the passage search on. :param int characters: (optional) The approximate number of characters that each returned passage will contain. @@ -3035,7 +3035,7 @@ class DefaultQueryParamsSuggestedRefinements(): Object containing suggested refinement settings. :attr bool enabled: (optional) When `true`, a suggested refinements for the - query are retuned by default. + query are returned by default. :attr int count: (optional) The number of suggested refinements to return by default. """ @@ -3045,7 +3045,7 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: Initialize a DefaultQueryParamsSuggestedRefinements object. :param bool enabled: (optional) When `true`, a suggested refinements for - the query are retuned by default. + the query are returned by default. :param int count: (optional) The number of suggested refinements to return by default. """ @@ -3106,7 +3106,7 @@ class DefaultQueryParamsTableResults(): Default project query settings for table results. :attr bool enabled: (optional) When `true`, a table results for the query are - retuned by default. + returned by default. :attr int count: (optional) The number of table results to return by default. :attr int per_document: (optional) The number of table results to include in each result document. @@ -3121,7 +3121,7 @@ def __init__(self, Initialize a DefaultQueryParamsTableResults object. :param bool enabled: (optional) When `true`, a table results for the query - are retuned by default. + are returned by default. :param int count: (optional) The number of table results to return by default. :param int per_document: (optional) The number of table results to include @@ -4413,14 +4413,14 @@ class ProjectListDetailsRelevancyTrainingStatus(): :attr str data_updated: (optional) When the training data was updated. :attr int total_examples: (optional) The total number of examples. - :attr bool sufficient_label_diversity: (optional) When `true`, sufficent label + :attr bool sufficient_label_diversity: (optional) When `true`, sufficient label diversity is present to allow training for this project. :attr bool processing: (optional) When `true`, the relevancy training is in processing. :attr bool minimum_examples_added: (optional) When `true`, the minimum number of examples required to train has been met. :attr str successfully_trained: (optional) The time that the most recent - successful training occured. + successful training occurred. :attr bool available: (optional) When `true`, relevancy training is available when querying collections in the project. :attr int notices: (optional) The number of notices generated during the @@ -4445,14 +4445,14 @@ def __init__(self, :param str data_updated: (optional) When the training data was updated. :param int total_examples: (optional) The total number of examples. - :param bool sufficient_label_diversity: (optional) When `true`, sufficent + :param bool sufficient_label_diversity: (optional) When `true`, sufficient label diversity is present to allow training for this project. :param bool processing: (optional) When `true`, the relevancy training is in processing. :param bool minimum_examples_added: (optional) When `true`, the minimum number of examples required to train has been met. :param str successfully_trained: (optional) The time that the most recent - successful training occured. + successful training occurred. :param bool available: (optional) When `true`, relevancy training is available when querying collections in the project. :param int notices: (optional) The number of notices generated during the @@ -5237,6 +5237,8 @@ class QueryResponse(): :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) Array of suggested refinements. :attr List[QueryTableResult] table_results: (optional) Array of table results. + :attr List[QueryResponsePassage] passages: (optional) Passages returned by + Discovery. """ def __init__(self, @@ -5247,7 +5249,8 @@ def __init__(self, retrieval_details: 'RetrievalDetails' = None, suggested_query: str = None, suggested_refinements: List['QuerySuggestedRefinement'] = None, - table_results: List['QueryTableResult'] = None) -> None: + table_results: List['QueryTableResult'] = None, + passages: List['QueryResponsePassage'] = None) -> None: """ Initialize a QueryResponse object. @@ -5265,6 +5268,8 @@ def __init__(self, Array of suggested refinements. :param List[QueryTableResult] table_results: (optional) Array of table results. + :param List[QueryResponsePassage] passages: (optional) Passages returned by + Discovery. """ self.matching_results = matching_results self.results = results @@ -5273,6 +5278,7 @@ def __init__(self, self.suggested_query = suggested_query self.suggested_refinements = suggested_refinements self.table_results = table_results + self.passages = passages @classmethod def from_dict(cls, _dict: Dict) -> 'QueryResponse': @@ -5280,7 +5286,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponse': args = {} valid_keys = [ 'matching_results', 'results', 'aggregations', 'retrieval_details', - 'suggested_query', 'suggested_refinements', 'table_results' + 'suggested_query', 'suggested_refinements', 'table_results', + 'passages' ] bad_keys = set(_dict.keys()) - set(valid_keys) if bad_keys: @@ -5313,6 +5320,11 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponse': QueryTableResult._from_dict(x) for x in (_dict.get('table_results')) ] + if 'passages' in _dict: + args['passages'] = [ + QueryResponsePassage._from_dict(x) + for x in (_dict.get('passages')) + ] return cls(**args) @classmethod @@ -5343,6 +5355,8 @@ def to_dict(self) -> Dict: ] if hasattr(self, 'table_results') and self.table_results is not None: _dict['table_results'] = [x._to_dict() for x in self.table_results] + if hasattr(self, 'passages') and self.passages is not None: + _dict['passages'] = [x._to_dict() for x in self.passages] return _dict def _to_dict(self): @@ -5364,6 +5378,130 @@ def __ne__(self, other: 'QueryResponse') -> bool: return not self == other +class QueryResponsePassage(): + """ + A passage query response. + + :attr str passage_text: (optional) The content of the extracted passage. + :attr float passage_score: (optional) The confidence score of the passage's + analysis. A higher score indicates greater confidence. + :attr str document_id: (optional) The unique identifier of the ingested + document. + :attr str collection_id: (optional) The unique identifier of the collection. + :attr int start_offset: (optional) The position of the first character of the + extracted passage in the originating field. + :attr int end_offset: (optional) The position of the last character of the + extracted passage in the originating field. + :attr str field: (optional) The label of the field from which the passage has + been extracted. + """ + + def __init__(self, + *, + passage_text: str = None, + passage_score: float = None, + document_id: str = None, + collection_id: str = None, + start_offset: int = None, + end_offset: int = None, + field: str = None) -> None: + """ + Initialize a QueryResponsePassage object. + + :param str passage_text: (optional) The content of the extracted passage. + :param float passage_score: (optional) The confidence score of the + passage's analysis. A higher score indicates greater confidence. + :param str document_id: (optional) The unique identifier of the ingested + document. + :param str collection_id: (optional) The unique identifier of the + collection. + :param int start_offset: (optional) The position of the first character of + the extracted passage in the originating field. + :param int end_offset: (optional) The position of the last character of the + extracted passage in the originating field. + :param str field: (optional) The label of the field from which the passage + has been extracted. + """ + self.passage_text = passage_text + self.passage_score = passage_score + self.document_id = document_id + self.collection_id = collection_id + self.start_offset = start_offset + self.end_offset = end_offset + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryResponsePassage': + """Initialize a QueryResponsePassage object from a json dictionary.""" + args = {} + valid_keys = [ + 'passage_text', 'passage_score', 'document_id', 'collection_id', + 'start_offset', 'end_offset', 'field' + ] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class QueryResponsePassage: ' + + ', '.join(bad_keys)) + if 'passage_text' in _dict: + args['passage_text'] = _dict.get('passage_text') + if 'passage_score' in _dict: + args['passage_score'] = _dict.get('passage_score') + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'start_offset' in _dict: + args['start_offset'] = _dict.get('start_offset') + if 'end_offset' in _dict: + args['end_offset'] = _dict.get('end_offset') + if 'field' in _dict: + args['field'] = _dict.get('field') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryResponsePassage 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, 'passage_text') and self.passage_text is not None: + _dict['passage_text'] = self.passage_text + if hasattr(self, 'passage_score') and self.passage_score is not None: + _dict['passage_score'] = self.passage_score + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'collection_id') and self.collection_id is not None: + _dict['collection_id'] = self.collection_id + if hasattr(self, 'start_offset') and self.start_offset is not None: + _dict['start_offset'] = self.start_offset + if hasattr(self, 'end_offset') and self.end_offset is not None: + _dict['end_offset'] = self.end_offset + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field + 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 QueryResponsePassage object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other: 'QueryResponsePassage') -> 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: 'QueryResponsePassage') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryResult(): """ Result document for the specified query. diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index d778867c0..4c9c909fb 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -48,10 +48,10 @@ class NaturalLanguageUnderstandingV1(BaseService): DEFAULT_SERVICE_NAME = 'natural-language-understanding' def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, + self, + version: str, + authenticator: Authenticator = None, + service_name: str = DEFAULT_SERVICE_NAME, ) -> None: """ Construct a new client for the Natural Language Understanding service. @@ -110,7 +110,8 @@ def analyze(self, - Relations - Semantic roles - Sentiment - - Syntax. + - Syntax + - Summarization (Experimental) If a language for the input text is not specified with the `language` parameter, the service [automatically detects the language](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-detectable-languages). @@ -2701,8 +2702,7 @@ class Model(): that deployed this model to Natural Language Understanding. :attr str model_version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. - :attr str version: (optional) (Deprecated — use `model_version`) The model - version, if it was manually provided in Watson Knowledge Studio. + :attr str version: (optional) Deprecated — use `model_version`. :attr str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. :attr datetime created: (optional) A dateTime indicating when the model was @@ -2733,8 +2733,7 @@ def __init__(self, workspace that deployed this model to Natural Language Understanding. :param str model_version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. - :param str version: (optional) (Deprecated — use `model_version`) The model - version, if it was manually provided in Watson Knowledge Studio. + :param str version: (optional) Deprecated — use `model_version`. :param str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. :param datetime created: (optional) A dateTime indicating when the model diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index b25fd6ce6..c94fe745b 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -2350,7 +2350,7 @@ def send_request(obj, body, response, url=None): fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" -fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query", "suggested_refinements": [], "table_results": []}""" +fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query", "suggested_refinements": [], "table_results": [], "passages": []}""" fake_response_Completions_json = """{"completions": []}""" fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "notices": []}""" fake_response_ListFieldsResponse_json = """{"fields": []}""" diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 2def05826..da828d354 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -82,7 +82,7 @@ def add_mock_response(self, url, response): def call_service(self, body): service = NaturalLanguageUnderstandingV1( authenticator=NoAuthAuthenticator(), - version='2019-07-12', + version='2020-08-01', ) service.set_service_url(base_url) output = service.analyze(**body) @@ -161,7 +161,7 @@ def add_mock_response(self, url, response): def call_service(self, body): service = NaturalLanguageUnderstandingV1( authenticator=NoAuthAuthenticator(), - version='2019-07-12', + version='2020-08-01', ) service.set_service_url(base_url) output = service.list_models(**body) @@ -229,7 +229,7 @@ def add_mock_response(self, url, response): def call_service(self, body): service = NaturalLanguageUnderstandingV1( authenticator=NoAuthAuthenticator(), - version='2019-07-12', + version='2020-08-01', ) service.set_service_url(base_url) output = service.delete_model(**body) From e818abb0fbef26b300473c8fac0dd655f0a8f6ce Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Wed, 18 Nov 2020 11:21:47 -0500 Subject: [PATCH 289/455] docs: add migration guide --- MIGRATION-V5.md | 175 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 MIGRATION-V5.md diff --git a/MIGRATION-V5.md b/MIGRATION-V5.md new file mode 100644 index 000000000..88b36428f --- /dev/null +++ b/MIGRATION-V5.md @@ -0,0 +1,175 @@ +## Python SDK V5 Migration guide + +### Service changes + +#### Assistant v1 + +* `include_count` is now a parameter of the `list_workspaces()` method +* `include_count` is now a parameter of the `list_intents()` method +* `include_count` is now a parameter of the `list_examples()` method +* `include_count` is now a parameter of the `list_counterexamples()` method +* `include_count` is now a parameter of the `list_entities()` method +* `include_count` is now a parameter of the `list_values()` method +* `include_count` is now a parameter of the `list_synonyms()` method +* `include_count` is now a parameter of the `list_dialogNodes()` method +* `context` type was changed from `dict` to `DialogNodeContext` in the `create_dialog_node()` method +* `new_context` type was changed from `dict` to `DialogNodeContext` in the `update_dialog_node()` method +* `bulk_classify()` method was addded + +##### Models Added + +`BulkClassifyOutput`, +`BulkClassifyResponse`, +`BulkClassifyUtterance`, +`DialogNodeContext`, +`DialogNodeOutputConnectToAgentTransferInfo`, +`DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent`, +`DialogNodeOutputGenericDialogNodeOutputResponseTypeImage`, +`DialogNodeOutputGenericDialogNodeOutputResponseTypeOption`, +`DialogNodeOutputGenericDialogNodeOutputResponseTypePause`, +`DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill`, +`DialogNodeOutputGenericDialogNodeOutputResponseTypeText`, +`RuntimeResponseGenericRuntimeResponseTypeConnectToAgent`, +`RuntimeResponseGenericRuntimeResponseTypeImage`, +`RuntimeResponseGenericRuntimeResponseTypeOption`, +`RuntimeResponseGenericRuntimeResponseTypePause`, +`RuntimeResponseGenericRuntimeResponseTypeSuggestion`, +`RuntimeResponseGenericRuntimeResponseTypeText` + +##### Models Removed + +`DialogSuggestionOutput`, +`DialogSuggestionResponseGeneric` + +##### Model Properties Changed + +`DialogNode` +* `context` property type changed from `Dictionary` to `DialogNodeContext` + +`DialogNodeOutput` +* Added `Integrations` property with getter and setter + +`DialogNodeOutputGeneric`, `RuntimeResponseGeneric` +* Added `agent_available`, `agent_unavailable`, and `transfer_info` properties + +`DialogSuggestion` +* `output` property type changed from `DialogSuggestionOutput` to `Dictionary` + +#### Assistant v2 + +* `bulk_classify()` method was addded + +##### Models Added + +`BulkClassifyOutput`, +`BulkClassifyResponse`, +`BulkClassifyUtterance`, +`DialogNodeOutputConnectToAgentTransferInfo`, +`RuntimeResponseGenericRuntimeResponseTypeConnectToAgent`, +`RuntimeResponseGenericRuntimeResponseTypeImage`, +`RuntimeResponseGenericRuntimeResponseTypeOption`, +`RuntimeResponseGenericRuntimeResponseTypePause`, +`RuntimeResponseGenericRuntimeResponseTypeSearch`, +`RuntimeResponseGenericRuntimeResponseTypeSuggestion`, +`RuntimeResponseGenericRuntimeResponseTypeText` + +##### Model Properties Changed + +`MessageContext`, `MessageContextStateless` +* `Skills` property type changed from `MessageContextSkills` to `Dictionary` + +`MessageContextSkill` +* `System` property type changed from `Dictionary` to `MessageContextSkillSystem` + +`RuntimeResponseGeneric` +* Added `agent_available`, `agent_unavailable`, and `transfer_info` properties + +#### Compare Comply v1 + +* `before` and `after` parameters were removed from `list_feedback` method + +##### Model Properties Changed + +`Category`, `TypeLabel` +* Added `modification` property + +`OriginalLabelsOut`, `UpdatedLabelsOut` +* Removed `modification` property + +#### Discovery v1 + +No changes + +#### Discovery v2 + +##### Models Added + +`QueryResponsePassage` + +##### Models Removed + +`QueryNoticesResult` + +##### Model Properties Changed + +`QueryResponse` +* Added `Passages` property + +#### Language Translator v3 + +No changes + +#### Natural Language Classifier v1 + +No changes + +#### Natural Language Understanding v1 + +No changes + +#### Personality Insights + +No changes + +#### Speech To Text v1 + +No changes + +#### Text To Speech v1 + +* Renamed `CreateVoiceModel()` method to `CreateCustomModel()` + +* Renamed `ListVoiceModels()` method to `ListCustomModels()` + +* Renamed `UpdateVoiceModel()` method to `UpdateCustomModel()` + +* Renamed `GetVoiceModel()` method to `GetCustomModel()` + +* Renamed `DeleteVoiceModel()` method to `GetCustomModel()` + +##### Models Added + +`CustomModel`, +`CustomModels` + +##### Models Removed + +`VoiceModel`, +`VoiceModels` + +##### Model Properties Changed + +`Voice` +* Change return type of `customization` from `VoiceModel` to `CustomModel` + +#### Tone Analyzer v3 + +No changes + +#### Visual Recognition v3 + +No changes + +#### Visual Recognition v4 + +* Changed `start_time` and `end_time` parameter types from `string` to `date` in `get_training_usage()` method \ No newline at end of file From 54972e83cab7e57d3afa126ffc2e385a5c48a25b Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Tue, 1 Dec 2020 10:44:37 -0600 Subject: [PATCH 290/455] [docs] Revise PI deprecation, add VisRec deprecation --- README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b3e314386..b6db673ce 100755 --- a/README.md +++ b/README.md @@ -43,11 +43,14 @@ Python client library to quickly get started with the various [Watson APIs][wdc] ## ANNOUNCEMENTS! -### Personality Insights Deprecation -IBM® will begin sunsetting IBM Watson™ Personality Insights on 1 December 2020. For a period of one year from this date, you will still be able to use Watson Personality Insights. However, as of 1 December 2021, the offering will no longer be available. +### Personality Insights deprecation +IBM Watson™ Personality Insights is discontinued. For a period of one year from 1 December 2020, you will still be able to use Watson Personality Insights. However, as of 1 December 2021, the offering will no longer be available. As an alternative, we encourage you to consider migrating to IBM Watson™ [Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-understanding), a service on IBM Cloud® that uses deep learning to extract data and insights from text such as keywords, categories, sentiment, emotion, and syntax to provide insights for your business or industry. For more information, see About Natural Language Understanding. +### Visual Recognition deprecation +IBM Watson™ Visual Recognition is discontinued. Existing instances are supported until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance that is provisioned on 1 December 2021 will be deleted. + ## Before you begin * You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support `python 3.5` and above From c3e1f07697b15d05f87cec39e36a9a2d28db7b91 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Tue, 1 Dec 2020 15:56:46 -0500 Subject: [PATCH 291/455] feat: regenerate using current api def and add deprecation warnings --- ibm_watson/personality_insights_v3.py | 4 ++++ ibm_watson/text_to_speech_v1.py | 1 - ibm_watson/visual_recognition_v3.py | 11 ++++++++--- ibm_watson/visual_recognition_v4.py | 9 +++++++-- 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index abba73225..a57f408cc 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -911,6 +911,9 @@ class Profile(): :attr List[Warning] warnings: An array of warning messages that are associated with the input text for the request. The array is empty if the input generated no warnings. + Deprecated On 1 December 2021, Personality Insights will no longer be available. + Consider migrating to Watson Natural Language Understanding. + For more information, see [Personality Insights Deprecation](https://github.com/watson-developer-cloud/ruby-sdk/tree/master#personality-insights-deprecation). """ def __init__( @@ -958,6 +961,7 @@ def __init__( array provides information inferred from the input text for the individual preferences of that category. """ + print('warning: On 1 December 2021, Personality Insights will no longer be available. For more information, see the README.') self.processed_language = processed_language self.word_count = word_count self.word_count_message = word_count_message diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 1be14651e..437230a06 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1110,7 +1110,6 @@ class Language(Enum): are to be returned. Omit the parameter to see all custom models that are owned by the requester. """ - AR_AR = 'ar-AR' DE_DE = 'de-DE' EN_GB = 'en-GB' EN_US = 'en-US' diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index e88faa4e9..da7c810bc 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -14,9 +14,13 @@ # See the License for the specific language governing permissions and # limitations under the License. """ -The IBM Watson™ Visual Recognition service uses deep learning algorithms to identify -scenes and objects in images that you upload to the service. You can create and train a -custom classifier to identify subjects that suit your needs. +IBM Watson™ Visual Recognition is discontinued. Existing instances are supported +until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance +that is provisioned on 1 December 2021 will be deleted. +{: deprecated} +The IBM Watson Visual Recognition service uses deep learning algorithms to identify scenes +and objects in images that you upload to the service. You can create and train a custom +classifier to identify subjects that suit your needs. """ import json @@ -68,6 +72,7 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + print('warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see the README.') if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index a258262e3..0848c9f8b 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -14,8 +14,12 @@ # See the License for the specific language governing permissions and # limitations under the License. """ -Provide images to the IBM Watson™ Visual Recognition service for analysis. The -service detects objects based on a set of images with training data. +IBM Watson™ Visual Recognition is discontinued. Existing instances are supported +until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance +that is provisioned on 1 December 2021 will be deleted. +{: deprecated} +Provide images to the IBM Watson Visual Recognition service for analysis. The service +detects objects based on a set of images with training data. """ import json @@ -68,6 +72,7 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + print('warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see the README.') if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, From fd63a78e178618ca311eaf26670699805927e02b Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 3 Dec 2020 16:27:56 -0500 Subject: [PATCH 292/455] docs: Add url to deprecation notices --- ibm_watson/personality_insights_v3.py | 2 +- ibm_watson/visual_recognition_v3.py | 2 +- ibm_watson/visual_recognition_v4.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index a57f408cc..50188ae01 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -961,7 +961,7 @@ def __init__( array provides information inferred from the input text for the individual preferences of that category. """ - print('warning: On 1 December 2021, Personality Insights will no longer be available. For more information, see the README.') + print('warning: On 1 December 2021, Personality Insights will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#personality-insights-deprecation.') self.processed_language = processed_language self.word_count = word_count self.word_count_message = word_count_message diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index da7c810bc..e996b39e3 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -72,7 +72,7 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - print('warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see the README.') + print('warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#visual-recognition-deprecation.') if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 0848c9f8b..1354af1a4 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -72,7 +72,7 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - print('warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see the README.') + print('warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#visual-recognition-deprecation.') if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, From 33e0d9356ac43b7f988200c853b46b6cf4f703ab Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 10 Dec 2020 00:15:50 -0500 Subject: [PATCH 293/455] feat: regenrate using current api def and generator 3.21 --- examples/__init__.py | 2 +- .../__init__.py | 2 +- .../tone_detection.py | 2 +- ibm_watson/__init__.py | 2 +- ibm_watson/assistant_v1.py | 2684 ++- ibm_watson/assistant_v2.py | 1137 +- ibm_watson/compare_comply_v1.py | 1479 +- ibm_watson/discovery_v1.py | 3267 ++-- ibm_watson/language_translator_v3.py | 405 +- ibm_watson/natural_language_classifier_v1.py | 231 +- .../natural_language_understanding_v1.py | 985 +- ibm_watson/personality_insights_v3.py | 236 +- ibm_watson/speech_to_text_v1.py | 1311 +- ibm_watson/text_to_speech_adapter_v1.py | 2 +- ibm_watson/text_to_speech_v1.py | 452 +- ibm_watson/tone_analyzer_v3.py | 242 +- ibm_watson/visual_recognition_v3.py | 315 +- ibm_watson/visual_recognition_v4.py | 1045 +- ibm_watson/websocket/__init__.py | 2 +- ibm_watson/websocket/audio_source.py | 2 +- .../websocket/recognize_abstract_callback.py | 2 +- ibm_watson/websocket/recognize_listener.py | 2 +- ibm_watson/websocket/synthesize_callback.py | 2 +- ibm_watson/websocket/synthesize_listener.py | 2 +- test/unit/test_assistant_v1.py | 13198 ++++++++++---- test/unit/test_assistant_v2.py | 4577 ++++- test/unit/test_compare_comply_v1.py | 5058 +++++- test/unit/test_discovery_v1.py | 14691 +++++++++++----- test/unit/test_discovery_v2.py | 7549 ++++++-- test/unit/test_language_translator_v3.py | 2243 ++- .../test_natural_language_classifier_v1.py | 1036 +- .../test_natural_language_understanding_v1.py | 2472 ++- test/unit/test_personality_insights_v3.py | 593 +- test/unit/test_speech_to_text_v1.py | 7152 +++++--- test/unit/test_text_to_speech_v1.py | 2384 ++- test/unit/test_tone_analyzer_v3.py | 795 +- test/unit/test_visual_recognition_v3.py | 1508 +- test/unit/test_visual_recognition_v4.py | 4070 +++-- 38 files changed, 55219 insertions(+), 25918 deletions(-) diff --git a/examples/__init__.py b/examples/__init__.py index e38a9fff7..d932b9f38 100644 --- a/examples/__init__.py +++ b/examples/__init__.py @@ -1,4 +1,4 @@ -# (C) Copyright IBM Corp. 2015, 2016. +# (C) Copyright IBM Corp. 2015, 2020. # # 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 6183fadf7..5264e58b4 100644 --- a/examples/assistant_tone_analyzer_integration/__init__.py +++ b/examples/assistant_tone_analyzer_integration/__init__.py @@ -1,4 +1,4 @@ -# (C) Copyright IBM Corp. 2016, 2019. +# (C) Copyright IBM Corp. 2016, 2020. # # 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 d0f91fbdd..c5717893c 100644 --- a/examples/assistant_tone_analyzer_integration/tone_detection.py +++ b/examples/assistant_tone_analyzer_integration/tone_detection.py @@ -1,4 +1,4 @@ -# (C) Copyright IBM Corp. 2016, 2019. +# (C) Copyright IBM Corp. 2016, 2020. # # 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/__init__.py b/ibm_watson/__init__.py index ae48a10b0..105e04d40 100755 --- a/ibm_watson/__init__.py +++ b/ibm_watson/__init__.py @@ -1,5 +1,5 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2016, 2019. +# (C) Copyright IBM Corp. 2016, 2020. # # 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 38e5a33b9..c6c2035bc 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -21,19 +23,19 @@ update a workspace. """ -import json -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers 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.get_authenticator import get_authenticator_from_environment -from typing import Dict -from typing import List +from typing import Dict, List +import json import sys +from ibm_cloud_sdk_core import BaseService, DetailedResponse +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from ibm_cloud_sdk_core.utils import convert_model, datetime_to_string, string_to_datetime + +from .common import get_sdk_headers + ############################################################################## # Service ############################################################################## @@ -54,27 +56,21 @@ def __init__( """ Construct a new client for the Assistant service. - :param str version: The API version date to use with the service, in - "YYYY-MM-DD" format. Whenever the API is changed in a backwards - incompatible way, a new minor version of the API is released. - The service uses the API version for the date you specify, or - the most recent version before that date. Note that you should - not programmatically specify the current date at runtime, in - case the API has been updated since your application's release. - Instead, specify a version date that is compatible with your - application, and don't change it until your application is - ready for a later version. + :param str version: Release date of the API version you want to use. + Specify dates in YYYY-MM-DD format. The current version is `2020-04-01`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + if version is None: + raise ValueError('version must be provided') + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.version = version self.configure_service(service_name) @@ -92,7 +88,7 @@ def message(self, context: 'Context' = None, output: 'OutputData' = None, nodes_visited_details: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get response to user input. @@ -125,25 +121,22 @@ def message(self, processing of the message. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `MessageResponse` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if input is not None: - input = self._convert_model(input) + input = convert_model(input) if intents is not None: - intents = [self._convert_model(x) for x in intents] + intents = [convert_model(x) for x in intents] if entities is not None: - entities = [self._convert_model(x) for x in entities] + entities = [convert_model(x) for x in entities] if context is not None: - context = self._convert_model(context) + context = convert_model(context) if output is not None: - output = self._convert_model(output) - + output = convert_model(output) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='message') @@ -162,9 +155,18 @@ def message(self, 'context': context, 'output': output } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/workspaces/{0}/message'.format( - *self._encode_path_vars(workspace_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/message'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -185,7 +187,7 @@ def list_workspaces(self, sort: str = None, cursor: str = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List workspaces. @@ -206,12 +208,10 @@ def list_workspaces(self, 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 + :rtype: DetailedResponse with `dict` result representing a `WorkspaceCollection` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='list_workspaces') @@ -226,6 +226,10 @@ def list_workspaces(self, 'include_audit': include_audit } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/workspaces' request = self.prepare_request(method='GET', url=url, @@ -249,7 +253,7 @@ def create_workspace(self, intents: List['CreateIntent'] = None, entities: List['CreateEntity'] = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create workspace. @@ -281,25 +285,22 @@ def create_workspace(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Workspace` object """ if dialog_nodes is not None: - dialog_nodes = [self._convert_model(x) for x in dialog_nodes] + dialog_nodes = [convert_model(x) for x in dialog_nodes] if counterexamples is not None: - counterexamples = [self._convert_model(x) for x in counterexamples] + counterexamples = [convert_model(x) for x in counterexamples] if system_settings is not None: - system_settings = self._convert_model(system_settings) + system_settings = convert_model(system_settings) if webhooks is not None: - webhooks = [self._convert_model(x) for x in webhooks] + webhooks = [convert_model(x) for x in webhooks] if intents is not None: - intents = [self._convert_model(x) for x in intents] + intents = [convert_model(x) for x in intents] if entities is not None: - entities = [self._convert_model(x) for x in entities] - + entities = [convert_model(x) for x in entities] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_workspace') @@ -320,6 +321,13 @@ def create_workspace(self, 'intents': intents, 'entities': entities } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v1/workspaces' request = self.prepare_request(method='POST', @@ -337,7 +345,7 @@ def get_workspace(self, export: bool = None, include_audit: bool = None, sort: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get information about a workspace. @@ -356,15 +364,12 @@ def get_workspace(self, ascending alphabetical order. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Workspace` object """ if workspace_id is None: raise ValueError('workspace_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='V1', operation_id='get_workspace') @@ -377,7 +382,14 @@ def get_workspace(self, 'sort': sort } - url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -402,7 +414,7 @@ def update_workspace(self, entities: List['CreateEntity'] = None, append: bool = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update workspace. @@ -444,27 +456,24 @@ def update_workspace(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Workspace` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if dialog_nodes is not None: - dialog_nodes = [self._convert_model(x) for x in dialog_nodes] + dialog_nodes = [convert_model(x) for x in dialog_nodes] if counterexamples is not None: - counterexamples = [self._convert_model(x) for x in counterexamples] + counterexamples = [convert_model(x) for x in counterexamples] if system_settings is not None: - system_settings = self._convert_model(system_settings) + system_settings = convert_model(system_settings) if webhooks is not None: - webhooks = [self._convert_model(x) for x in webhooks] + webhooks = [convert_model(x) for x in webhooks] if intents is not None: - intents = [self._convert_model(x) for x in intents] + intents = [convert_model(x) for x in intents] if entities is not None: - entities = [self._convert_model(x) for x in entities] - + entities = [convert_model(x) for x in entities] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='update_workspace') @@ -489,8 +498,18 @@ def update_workspace(self, 'intents': intents, 'entities': entities } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -500,8 +519,7 @@ def update_workspace(self, response = self.send(request) return response - def delete_workspace(self, workspace_id: str, - **kwargs) -> 'DetailedResponse': + def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: """ Delete workspace. @@ -515,10 +533,7 @@ def delete_workspace(self, workspace_id: str, if workspace_id is None: raise ValueError('workspace_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='V1', operation_id='delete_workspace') @@ -526,7 +541,14 @@ def delete_workspace(self, workspace_id: str, params = {'version': self.version} - url = '/v1/workspaces/{0}'.format(*self._encode_path_vars(workspace_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -548,7 +570,7 @@ def list_intents(self, sort: str = None, cursor: str = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List intents. @@ -574,15 +596,12 @@ def list_intents(self, 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 + :rtype: DetailedResponse with `dict` result representing a `IntentCollection` object """ if workspace_id is None: raise ValueError('workspace_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='V1', operation_id='list_intents') @@ -598,8 +617,14 @@ def list_intents(self, 'include_audit': include_audit } - url = '/v1/workspaces/{0}/intents'.format( - *self._encode_path_vars(workspace_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/intents'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -615,7 +640,7 @@ def create_intent(self, description: str = None, examples: List['Example'] = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create intent. @@ -637,7 +662,7 @@ def create_intent(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Intent` object """ if workspace_id is None: @@ -645,11 +670,8 @@ def create_intent(self, if intent is None: raise ValueError('intent must be provided') if examples is not None: - examples = [self._convert_model(x) for x in examples] - + examples = [convert_model(x) for x in examples] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_intent') @@ -662,9 +684,18 @@ def create_intent(self, 'description': description, 'examples': examples } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/workspaces/{0}/intents'.format( - *self._encode_path_vars(workspace_id)) + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/intents'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -680,7 +711,7 @@ def get_intent(self, *, export: bool = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get intent. @@ -696,17 +727,14 @@ def get_intent(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Intent` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent 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='V1', operation_id='get_intent') @@ -718,8 +746,15 @@ def get_intent(self, 'include_audit': include_audit } - url = '/v1/workspaces/{0}/intents/{1}'.format( - *self._encode_path_vars(workspace_id, intent)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'intent'] + path_param_values = self.encode_path_vars(workspace_id, intent) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -737,7 +772,7 @@ def update_intent(self, new_examples: List['Example'] = None, append: bool = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update intent. @@ -770,7 +805,7 @@ def update_intent(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Intent` object """ if workspace_id is None: @@ -778,11 +813,8 @@ def update_intent(self, if intent is None: raise ValueError('intent must be provided') if new_examples is not None: - new_examples = [self._convert_model(x) for x in new_examples] - + new_examples = [convert_model(x) for x in new_examples] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='update_intent') @@ -799,9 +831,19 @@ def update_intent(self, 'description': new_description, 'examples': new_examples } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/workspaces/{0}/intents/{1}'.format( - *self._encode_path_vars(workspace_id, intent)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'intent'] + path_param_values = self.encode_path_vars(workspace_id, intent) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -812,7 +854,7 @@ def update_intent(self, return response def delete_intent(self, workspace_id: str, intent: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete intent. @@ -829,10 +871,7 @@ def delete_intent(self, workspace_id: str, intent: str, raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent 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='V1', operation_id='delete_intent') @@ -840,8 +879,15 @@ def delete_intent(self, workspace_id: str, intent: str, params = {'version': self.version} - url = '/v1/workspaces/{0}/intents/{1}'.format( - *self._encode_path_vars(workspace_id, intent)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'intent'] + path_param_values = self.encode_path_vars(workspace_id, intent) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -863,7 +909,7 @@ def list_examples(self, sort: str = None, cursor: str = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List user input examples. @@ -887,17 +933,14 @@ def list_examples(self, 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 + :rtype: DetailedResponse with `dict` result representing a `ExampleCollection` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent 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='V1', operation_id='list_examples') @@ -912,8 +955,15 @@ def list_examples(self, 'include_audit': include_audit } - url = '/v1/workspaces/{0}/intents/{1}/examples'.format( - *self._encode_path_vars(workspace_id, intent)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'intent'] + path_param_values = self.encode_path_vars(workspace_id, intent) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -929,7 +979,7 @@ def create_example(self, *, mentions: List['Mention'] = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create user input example. @@ -949,7 +999,7 @@ def create_example(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Example` object """ if workspace_id is None: @@ -959,11 +1009,8 @@ def create_example(self, if text is None: raise ValueError('text must be provided') if mentions is not None: - mentions = [self._convert_model(x) for x in mentions] - + mentions = [convert_model(x) for x in mentions] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_example') @@ -972,9 +1019,19 @@ def create_example(self, params = {'version': self.version, 'include_audit': include_audit} data = {'text': text, 'mentions': mentions} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/workspaces/{0}/intents/{1}/examples'.format( - *self._encode_path_vars(workspace_id, intent)) + path_param_keys = ['workspace_id', 'intent'] + path_param_values = self.encode_path_vars(workspace_id, intent) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -990,7 +1047,7 @@ def get_example(self, text: str, *, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get user input example. @@ -1003,7 +1060,7 @@ def get_example(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Example` object """ if workspace_id is None: @@ -1012,10 +1069,7 @@ def get_example(self, raise ValueError('intent must be provided') if text is None: raise ValueError('text 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='V1', operation_id='get_example') @@ -1023,8 +1077,15 @@ def get_example(self, params = {'version': self.version, 'include_audit': include_audit} - url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - *self._encode_path_vars(workspace_id, intent, text)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'intent', 'text'] + path_param_values = self.encode_path_vars(workspace_id, intent, text) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1041,7 +1102,7 @@ def update_example(self, new_text: str = None, new_mentions: List['Mention'] = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update user input example. @@ -1062,7 +1123,7 @@ def update_example(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Example` object """ if workspace_id is None: @@ -1072,11 +1133,8 @@ def update_example(self, if text is None: raise ValueError('text must be provided') if new_mentions is not None: - new_mentions = [self._convert_model(x) for x in new_mentions] - + new_mentions = [convert_model(x) for x in new_mentions] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='update_example') @@ -1085,9 +1143,19 @@ def update_example(self, params = {'version': self.version, 'include_audit': include_audit} data = {'text': new_text, 'mentions': new_mentions} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - *self._encode_path_vars(workspace_id, intent, text)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'intent', 'text'] + path_param_values = self.encode_path_vars(workspace_id, intent, text) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1098,7 +1166,7 @@ def update_example(self, return response def delete_example(self, workspace_id: str, intent: str, text: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete user input example. @@ -1118,10 +1186,7 @@ def delete_example(self, workspace_id: str, intent: str, text: str, raise ValueError('intent must be provided') if text is None: raise ValueError('text 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='V1', operation_id='delete_example') @@ -1129,8 +1194,15 @@ def delete_example(self, workspace_id: str, intent: str, text: str, params = {'version': self.version} - url = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format( - *self._encode_path_vars(workspace_id, intent, text)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'intent', 'text'] + path_param_values = self.encode_path_vars(workspace_id, intent, text) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1151,7 +1223,7 @@ def list_counterexamples(self, sort: str = None, cursor: str = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List counterexamples. @@ -1174,15 +1246,12 @@ def list_counterexamples(self, 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 + :rtype: DetailedResponse with `dict` result representing a `CounterexampleCollection` object """ if workspace_id is None: raise ValueError('workspace_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='V1', operation_id='list_counterexamples') @@ -1197,8 +1266,15 @@ def list_counterexamples(self, 'include_audit': include_audit } - url = '/v1/workspaces/{0}/counterexamples'.format( - *self._encode_path_vars(workspace_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/counterexamples'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1212,7 +1288,7 @@ def create_counterexample(self, text: str, *, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create counterexample. @@ -1230,17 +1306,14 @@ def create_counterexample(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if text is None: raise ValueError('text 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='V1', operation_id='create_counterexample') @@ -1249,9 +1322,19 @@ def create_counterexample(self, params = {'version': self.version, 'include_audit': include_audit} data = {'text': text} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/workspaces/{0}/counterexamples'.format( - *self._encode_path_vars(workspace_id)) + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/counterexamples'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1266,7 +1349,7 @@ def get_counterexample(self, text: str, *, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get counterexample. @@ -1280,17 +1363,14 @@ def get_counterexample(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if text is None: raise ValueError('text 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='V1', operation_id='get_counterexample') @@ -1298,8 +1378,15 @@ def get_counterexample(self, params = {'version': self.version, 'include_audit': include_audit} - url = '/v1/workspaces/{0}/counterexamples/{1}'.format( - *self._encode_path_vars(workspace_id, text)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'text'] + path_param_values = self.encode_path_vars(workspace_id, text) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1314,7 +1401,7 @@ def update_counterexample(self, *, new_text: str = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update counterexample. @@ -1332,17 +1419,14 @@ def update_counterexample(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if text is None: raise ValueError('text 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='V1', operation_id='update_counterexample') @@ -1351,9 +1435,19 @@ def update_counterexample(self, params = {'version': self.version, 'include_audit': include_audit} data = {'text': new_text} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/workspaces/{0}/counterexamples/{1}'.format( - *self._encode_path_vars(workspace_id, text)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'text'] + path_param_values = self.encode_path_vars(workspace_id, text) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1364,7 +1458,7 @@ def update_counterexample(self, return response def delete_counterexample(self, workspace_id: str, text: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete counterexample. @@ -1383,10 +1477,7 @@ def delete_counterexample(self, workspace_id: str, text: str, raise ValueError('workspace_id must be provided') if text is None: raise ValueError('text 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='V1', operation_id='delete_counterexample') @@ -1394,8 +1485,15 @@ def delete_counterexample(self, workspace_id: str, text: str, params = {'version': self.version} - url = '/v1/workspaces/{0}/counterexamples/{1}'.format( - *self._encode_path_vars(workspace_id, text)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'text'] + path_param_values = self.encode_path_vars(workspace_id, text) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1417,7 +1515,7 @@ def list_entities(self, sort: str = None, cursor: str = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List entities. @@ -1443,15 +1541,12 @@ def list_entities(self, 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 + :rtype: DetailedResponse with `dict` result representing a `EntityCollection` object """ if workspace_id is None: raise ValueError('workspace_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='V1', operation_id='list_entities') @@ -1467,8 +1562,14 @@ def list_entities(self, 'include_audit': include_audit } - url = '/v1/workspaces/{0}/entities'.format( - *self._encode_path_vars(workspace_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1486,7 +1587,7 @@ def create_entity(self, fuzzy_match: bool = None, values: List['CreateValue'] = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create entity. @@ -1513,7 +1614,7 @@ def create_entity(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Entity` object """ if workspace_id is None: @@ -1521,11 +1622,8 @@ def create_entity(self, if entity is None: raise ValueError('entity must be provided') if values is not None: - values = [self._convert_model(x) for x in values] - + values = [convert_model(x) for x in values] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_entity') @@ -1540,9 +1638,18 @@ def create_entity(self, 'fuzzy_match': fuzzy_match, 'values': values } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/workspaces/{0}/entities'.format( - *self._encode_path_vars(workspace_id)) + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1558,7 +1665,7 @@ def get_entity(self, *, export: bool = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get entity. @@ -1574,17 +1681,14 @@ def get_entity(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Entity` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity 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='V1', operation_id='get_entity') @@ -1596,8 +1700,15 @@ def get_entity(self, 'include_audit': include_audit } - url = '/v1/workspaces/{0}/entities/{1}'.format( - *self._encode_path_vars(workspace_id, entity)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity'] + path_param_values = self.encode_path_vars(workspace_id, entity) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1617,7 +1728,7 @@ def update_entity(self, new_values: List['CreateValue'] = None, append: bool = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update entity. @@ -1653,7 +1764,7 @@ def update_entity(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Entity` object """ if workspace_id is None: @@ -1661,11 +1772,8 @@ def update_entity(self, if entity is None: raise ValueError('entity must be provided') if new_values is not None: - new_values = [self._convert_model(x) for x in new_values] - + new_values = [convert_model(x) for x in new_values] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='update_entity') @@ -1684,9 +1792,19 @@ def update_entity(self, 'fuzzy_match': new_fuzzy_match, 'values': new_values } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/workspaces/{0}/entities/{1}'.format( - *self._encode_path_vars(workspace_id, entity)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity'] + path_param_values = self.encode_path_vars(workspace_id, entity) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1697,7 +1815,7 @@ def update_entity(self, return response def delete_entity(self, workspace_id: str, entity: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete entity. @@ -1714,10 +1832,7 @@ def delete_entity(self, workspace_id: str, entity: str, raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity 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='V1', operation_id='delete_entity') @@ -1725,8 +1840,15 @@ def delete_entity(self, workspace_id: str, entity: str, params = {'version': self.version} - url = '/v1/workspaces/{0}/entities/{1}'.format( - *self._encode_path_vars(workspace_id, entity)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity'] + path_param_values = self.encode_path_vars(workspace_id, entity) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1745,7 +1867,7 @@ def list_mentions(self, *, export: bool = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List entity mentions. @@ -1762,17 +1884,14 @@ def list_mentions(self, 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 + :rtype: DetailedResponse with `dict` result representing a `EntityMentionCollection` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity 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='V1', operation_id='list_mentions') @@ -1784,8 +1903,15 @@ def list_mentions(self, 'include_audit': include_audit } - url = '/v1/workspaces/{0}/entities/{1}/mentions'.format( - *self._encode_path_vars(workspace_id, entity)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity'] + path_param_values = self.encode_path_vars(workspace_id, entity) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}/mentions'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1808,7 +1934,7 @@ def list_values(self, sort: str = None, cursor: str = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List entity values. @@ -1835,17 +1961,14 @@ def list_values(self, 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 + :rtype: DetailedResponse with `dict` result representing a `ValueCollection` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity 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='V1', operation_id='list_values') @@ -1861,8 +1984,15 @@ def list_values(self, 'include_audit': include_audit } - url = '/v1/workspaces/{0}/entities/{1}/values'.format( - *self._encode_path_vars(workspace_id, entity)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity'] + path_param_values = self.encode_path_vars(workspace_id, entity) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}/values'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1881,7 +2011,7 @@ def create_value(self, synonyms: List[str] = None, patterns: List[str] = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create entity value. @@ -1912,7 +2042,7 @@ def create_value(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Value` object """ if workspace_id is None: @@ -1921,10 +2051,7 @@ def create_value(self, raise ValueError('entity must be provided') if value is None: raise ValueError('value 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='V1', operation_id='create_value') @@ -1939,9 +2066,19 @@ def create_value(self, 'synonyms': synonyms, 'patterns': patterns } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/workspaces/{0}/entities/{1}/values'.format( - *self._encode_path_vars(workspace_id, entity)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity'] + path_param_values = self.encode_path_vars(workspace_id, entity) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}/values'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1958,7 +2095,7 @@ def get_value(self, *, export: bool = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get entity value. @@ -1975,7 +2112,7 @@ def get_value(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Value` object """ if workspace_id is None: @@ -1984,10 +2121,7 @@ def get_value(self, raise ValueError('entity must be provided') if value is None: raise ValueError('value 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='V1', operation_id='get_value') @@ -1999,8 +2133,15 @@ def get_value(self, 'include_audit': include_audit } - url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - *self._encode_path_vars(workspace_id, entity, value)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity', 'value'] + path_param_values = self.encode_path_vars(workspace_id, entity, value) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2021,7 +2162,7 @@ def update_value(self, new_patterns: List[str] = None, append: bool = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update entity value. @@ -2065,7 +2206,7 @@ def update_value(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Value` object """ if workspace_id is None: @@ -2074,10 +2215,7 @@ def update_value(self, raise ValueError('entity must be provided') if value is None: raise ValueError('value 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='V1', operation_id='update_value') @@ -2096,9 +2234,19 @@ def update_value(self, 'synonyms': new_synonyms, 'patterns': new_patterns } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - *self._encode_path_vars(workspace_id, entity, value)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity', 'value'] + path_param_values = self.encode_path_vars(workspace_id, entity, value) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -2109,7 +2257,7 @@ def update_value(self, return response def delete_value(self, workspace_id: str, entity: str, value: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete entity value. @@ -2129,10 +2277,7 @@ def delete_value(self, workspace_id: str, entity: str, value: str, raise ValueError('entity must be provided') if value is None: raise ValueError('value 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='V1', operation_id='delete_value') @@ -2140,8 +2285,15 @@ def delete_value(self, workspace_id: str, entity: str, value: str, params = {'version': self.version} - url = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format( - *self._encode_path_vars(workspace_id, entity, value)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity', 'value'] + path_param_values = self.encode_path_vars(workspace_id, entity, value) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -2164,7 +2316,7 @@ def list_synonyms(self, sort: str = None, cursor: str = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List entity value synonyms. @@ -2188,7 +2340,7 @@ def list_synonyms(self, 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 + :rtype: DetailedResponse with `dict` result representing a `SynonymCollection` object """ if workspace_id is None: @@ -2197,10 +2349,7 @@ def list_synonyms(self, raise ValueError('entity must be provided') if value is None: raise ValueError('value 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='V1', operation_id='list_synonyms') @@ -2215,8 +2364,15 @@ def list_synonyms(self, 'include_audit': include_audit } - url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( - *self._encode_path_vars(workspace_id, entity, value)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity', 'value'] + path_param_values = self.encode_path_vars(workspace_id, entity, value) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2232,7 +2388,7 @@ def create_synonym(self, synonym: str, *, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create entity value synonym. @@ -2252,7 +2408,7 @@ def create_synonym(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ if workspace_id is None: @@ -2263,10 +2419,7 @@ def create_synonym(self, raise ValueError('value must be provided') if synonym is None: raise ValueError('synonym 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='V1', operation_id='create_synonym') @@ -2275,9 +2428,19 @@ def create_synonym(self, params = {'version': self.version, 'include_audit': include_audit} data = {'synonym': synonym} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format( - *self._encode_path_vars(workspace_id, entity, value)) + path_param_keys = ['workspace_id', 'entity', 'value'] + path_param_values = self.encode_path_vars(workspace_id, entity, value) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -2294,7 +2457,7 @@ def get_synonym(self, synonym: str, *, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get entity value synonym. @@ -2308,7 +2471,7 @@ def get_synonym(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ if workspace_id is None: @@ -2319,10 +2482,7 @@ def get_synonym(self, raise ValueError('value must be provided') if synonym is None: raise ValueError('synonym 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='V1', operation_id='get_synonym') @@ -2330,8 +2490,16 @@ def get_synonym(self, params = {'version': self.version, 'include_audit': include_audit} - url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - *self._encode_path_vars(workspace_id, entity, value, synonym)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] + path_param_values = self.encode_path_vars(workspace_id, entity, value, + synonym) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2348,7 +2516,7 @@ def update_synonym(self, *, new_synonym: str = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update entity value synonym. @@ -2369,7 +2537,7 @@ def update_synonym(self, 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 + :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ if workspace_id is None: @@ -2380,10 +2548,7 @@ def update_synonym(self, raise ValueError('value must be provided') if synonym is None: raise ValueError('synonym 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='V1', operation_id='update_synonym') @@ -2392,9 +2557,20 @@ def update_synonym(self, params = {'version': self.version, 'include_audit': include_audit} data = {'synonym': new_synonym} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - *self._encode_path_vars(workspace_id, entity, value, synonym)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] + path_param_values = self.encode_path_vars(workspace_id, entity, value, + synonym) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -2405,7 +2581,7 @@ def update_synonym(self, return response def delete_synonym(self, workspace_id: str, entity: str, value: str, - synonym: str, **kwargs) -> 'DetailedResponse': + synonym: str, **kwargs) -> DetailedResponse: """ Delete entity value synonym. @@ -2428,10 +2604,7 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, raise ValueError('value must be provided') if synonym is None: raise ValueError('synonym 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='V1', operation_id='delete_synonym') @@ -2439,8 +2612,16 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, params = {'version': self.version} - url = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format( - *self._encode_path_vars(workspace_id, entity, value, synonym)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] + path_param_values = self.encode_path_vars(workspace_id, entity, value, + synonym) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -2461,7 +2642,7 @@ def list_dialog_nodes(self, sort: str = None, cursor: str = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List dialog nodes. @@ -2483,15 +2664,12 @@ def list_dialog_nodes(self, 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 + :rtype: DetailedResponse with `dict` result representing a `DialogNodeCollection` object """ if workspace_id is None: raise ValueError('workspace_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='V1', operation_id='list_dialog_nodes') @@ -2506,8 +2684,15 @@ def list_dialog_nodes(self, 'include_audit': include_audit } - url = '/v1/workspaces/{0}/dialog_nodes'.format( - *self._encode_path_vars(workspace_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/dialog_nodes'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2539,7 +2724,7 @@ def create_dialog_node(self, user_label: str = None, disambiguation_opt_out: bool = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create dialog node. @@ -2595,7 +2780,7 @@ def create_dialog_node(self, 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 + :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ if workspace_id is None: @@ -2603,17 +2788,14 @@ def create_dialog_node(self, if dialog_node is None: raise ValueError('dialog_node must be provided') if output is not None: - output = self._convert_model(output) + output = convert_model(output) if context is not None: - context = self._convert_model(context) + context = convert_model(context) if next_step is not None: - next_step = self._convert_model(next_step) + next_step = convert_model(next_step) if actions is not None: - actions = [self._convert_model(x) for x in actions] - + actions = [convert_model(x) for x in actions] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_dialog_node') @@ -2642,9 +2824,19 @@ def create_dialog_node(self, 'user_label': user_label, 'disambiguation_opt_out': disambiguation_opt_out } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/workspaces/{0}/dialog_nodes'.format( - *self._encode_path_vars(workspace_id)) + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/dialog_nodes'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -2659,7 +2851,7 @@ def get_dialog_node(self, dialog_node: str, *, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get dialog node. @@ -2671,17 +2863,14 @@ def get_dialog_node(self, 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 + :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if dialog_node is None: raise ValueError('dialog_node 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='V1', operation_id='get_dialog_node') @@ -2689,8 +2878,15 @@ def get_dialog_node(self, params = {'version': self.version, 'include_audit': include_audit} - url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( - *self._encode_path_vars(workspace_id, dialog_node)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'dialog_node'] + path_param_values = self.encode_path_vars(workspace_id, dialog_node) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2723,7 +2919,7 @@ def update_dialog_node(self, new_user_label: str = None, new_disambiguation_opt_out: bool = None, include_audit: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update dialog node. @@ -2781,7 +2977,7 @@ def update_dialog_node(self, 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 + :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ if workspace_id is None: @@ -2789,17 +2985,14 @@ def update_dialog_node(self, if dialog_node is None: raise ValueError('dialog_node must be provided') if new_output is not None: - new_output = self._convert_model(new_output) + new_output = convert_model(new_output) if new_context is not None: - new_context = self._convert_model(new_context) + new_context = convert_model(new_context) if new_next_step is not None: - new_next_step = self._convert_model(new_next_step) + new_next_step = convert_model(new_next_step) if new_actions is not None: - new_actions = [self._convert_model(x) for x in new_actions] - + new_actions = [convert_model(x) for x in new_actions] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='update_dialog_node') @@ -2828,9 +3021,19 @@ def update_dialog_node(self, 'user_label': new_user_label, 'disambiguation_opt_out': new_disambiguation_opt_out } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( - *self._encode_path_vars(workspace_id, dialog_node)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'dialog_node'] + path_param_values = self.encode_path_vars(workspace_id, dialog_node) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -2841,7 +3044,7 @@ def update_dialog_node(self, return response def delete_dialog_node(self, workspace_id: str, dialog_node: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete dialog node. @@ -2858,10 +3061,7 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, raise ValueError('workspace_id must be provided') if dialog_node is None: raise ValueError('dialog_node 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='V1', operation_id='delete_dialog_node') @@ -2869,8 +3069,15 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, params = {'version': self.version} - url = '/v1/workspaces/{0}/dialog_nodes/{1}'.format( - *self._encode_path_vars(workspace_id, dialog_node)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id', 'dialog_node'] + path_param_values = self.encode_path_vars(workspace_id, dialog_node) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -2890,7 +3097,7 @@ def list_logs(self, filter: str = None, page_limit: int = None, cursor: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List log events in a workspace. @@ -2909,15 +3116,12 @@ def list_logs(self, retrieve. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ if workspace_id is None: raise ValueError('workspace_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='V1', operation_id='list_logs') @@ -2931,8 +3135,14 @@ def list_logs(self, 'cursor': cursor } - url = '/v1/workspaces/{0}/logs'.format( - *self._encode_path_vars(workspace_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/logs'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2947,7 +3157,7 @@ def list_all_logs(self, sort: str = None, page_limit: int = None, cursor: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List log events in all workspaces. @@ -2968,15 +3178,12 @@ def list_all_logs(self, retrieve. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ if filter is None: raise ValueError('filter 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='V1', operation_id='list_all_logs') @@ -2990,6 +3197,10 @@ def list_all_logs(self, 'cursor': cursor } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/logs' request = self.prepare_request(method='GET', url=url, @@ -3003,8 +3214,7 @@ def list_all_logs(self, # User data ######################### - def delete_user_data(self, customer_id: str, - **kwargs) -> 'DetailedResponse': + def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: """ Delete labeled data. @@ -3024,10 +3234,7 @@ def delete_user_data(self, customer_id: str, if customer_id is None: raise ValueError('customer_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='V1', operation_id='delete_user_data') @@ -3035,6 +3242,10 @@ def delete_user_data(self, customer_id: str, params = {'version': self.version, 'customer_id': customer_id} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/user_data' request = self.prepare_request(method='DELETE', url=url, @@ -3052,7 +3263,7 @@ def bulk_classify(self, workspace_id: str, *, input: List['BulkClassifyUtterance'] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Identify intents and entities in multiple user utterances. @@ -3066,17 +3277,14 @@ def bulk_classify(self, utterances to classify. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object """ if workspace_id is None: raise ValueError('workspace_id must be provided') if input is not None: - input = [self._convert_model(x) for x in input] - + input = [convert_model(x) for x in input] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='bulk_classify') @@ -3085,9 +3293,19 @@ def bulk_classify(self, params = {'version': self.version} data = {'input': input} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/workspaces/{0}/bulk_classify'.format( - *self._encode_path_vars(workspace_id)) + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/bulk_classify'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -3098,9 +3316,12 @@ def bulk_classify(self, return response -class ListWorkspacesEnums(object): +class ListWorkspacesEnums: + """ + Enums for list_workspaces parameters. + """ - class Sort(Enum): + class Sort(str, Enum): """ The attribute by which returned workspaces will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -3109,9 +3330,12 @@ class Sort(Enum): UPDATED = 'updated' -class GetWorkspaceEnums(object): +class GetWorkspaceEnums: + """ + Enums for get_workspace parameters. + """ - class Sort(Enum): + class Sort(str, Enum): """ Indicates how the returned workspace data will be sorted. This parameter is valid only if **export**=`true`. Specify `sort=stable` to sort all workspace objects by @@ -3120,9 +3344,12 @@ class Sort(Enum): STABLE = 'stable' -class ListIntentsEnums(object): +class ListIntentsEnums: + """ + Enums for list_intents parameters. + """ - class Sort(Enum): + class Sort(str, Enum): """ The attribute by which returned intents will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -3131,9 +3358,12 @@ class Sort(Enum): UPDATED = 'updated' -class ListExamplesEnums(object): +class ListExamplesEnums: + """ + Enums for list_examples parameters. + """ - class Sort(Enum): + class Sort(str, Enum): """ The attribute by which returned examples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -3142,9 +3372,12 @@ class Sort(Enum): UPDATED = 'updated' -class ListCounterexamplesEnums(object): +class ListCounterexamplesEnums: + """ + Enums for list_counterexamples parameters. + """ - class Sort(Enum): + class Sort(str, Enum): """ The attribute by which returned counterexamples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -3153,9 +3386,12 @@ class Sort(Enum): UPDATED = 'updated' -class ListEntitiesEnums(object): +class ListEntitiesEnums: + """ + Enums for list_entities parameters. + """ - class Sort(Enum): + class Sort(str, Enum): """ The attribute by which returned entities will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -3164,9 +3400,12 @@ class Sort(Enum): UPDATED = 'updated' -class ListValuesEnums(object): +class ListValuesEnums: + """ + Enums for list_values parameters. + """ - class Sort(Enum): + class Sort(str, Enum): """ The attribute by which returned entity values will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -3175,9 +3414,12 @@ class Sort(Enum): UPDATED = 'updated' -class ListSynonymsEnums(object): +class ListSynonymsEnums: + """ + Enums for list_synonyms parameters. + """ - class Sort(Enum): + class Sort(str, Enum): """ The attribute by which returned entity value synonyms will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -3186,9 +3428,12 @@ class Sort(Enum): UPDATED = 'updated' -class ListDialogNodesEnums(object): +class ListDialogNodesEnums: + """ + Enums for list_dialog_nodes parameters. + """ - class Sort(Enum): + class Sort(str, Enum): """ The attribute by which returned dialog nodes will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). @@ -3237,21 +3482,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': """Initialize a BulkClassifyOutput object from a json dictionary.""" args = {} - valid_keys = ['input', 'entities', 'intents'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BulkClassifyOutput: ' - + ', '.join(bad_keys)) if 'input' in _dict: - args['input'] = BulkClassifyUtterance._from_dict(_dict.get('input')) + args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) if 'entities' in _dict: args['entities'] = [ - RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + RuntimeEntity.from_dict(x) for x in _dict.get('entities') ] if 'intents' in _dict: args['intents'] = [ - RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + RuntimeIntent.from_dict(x) for x in _dict.get('intents') ] return cls(**args) @@ -3264,11 +3503,11 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input._to_dict() + _dict['input'] = self.input.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] + _dict['intents'] = [x.to_dict() for x in self.intents] return _dict def _to_dict(self): @@ -3277,7 +3516,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this BulkClassifyOutput object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'BulkClassifyOutput') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3311,15 +3550,9 @@ def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': """Initialize a BulkClassifyResponse object from a json dictionary.""" args = {} - valid_keys = ['output'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BulkClassifyResponse: ' - + ', '.join(bad_keys)) if 'output' in _dict: args['output'] = [ - BulkClassifyOutput._from_dict(x) for x in (_dict.get('output')) + BulkClassifyOutput.from_dict(x) for x in _dict.get('output') ] return cls(**args) @@ -3332,7 +3565,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'output') and self.output is not None: - _dict['output'] = [x._to_dict() for x in self.output] + _dict['output'] = [x.to_dict() for x in self.output] return _dict def _to_dict(self): @@ -3341,7 +3574,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this BulkClassifyResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'BulkClassifyResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3373,12 +3606,6 @@ def __init__(self, text: str) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': """Initialize a BulkClassifyUtterance object from a json dictionary.""" args = {} - valid_keys = ['text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BulkClassifyUtterance: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -3405,7 +3632,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this BulkClassifyUtterance object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'BulkClassifyUtterance') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3442,12 +3669,6 @@ def __init__(self, group: str, *, location: List[int] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CaptureGroup': """Initialize a CaptureGroup object from a json dictionary.""" args = {} - valid_keys = ['group', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CaptureGroup: ' - + ', '.join(bad_keys)) if 'group' in _dict: args['group'] = _dict.get('group') else: @@ -3477,7 +3698,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CaptureGroup object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CaptureGroup') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3496,15 +3717,18 @@ class Context(): the previous response. :attr str conversation_id: (optional) The unique identifier of the conversation. - :attr SystemResponse system: (optional) For internal use only. + :attr dict system: (optional) For internal use only. :attr MessageContextMetadata metadata: (optional) Metadata related to the message. """ + # The set of defined properties for the class + _properties = frozenset(['conversation_id', 'system', 'metadata']) + def __init__(self, *, conversation_id: str = None, - system: 'SystemResponse' = None, + system: dict = None, metadata: 'MessageContextMetadata' = None, **kwargs) -> None: """ @@ -3512,7 +3736,7 @@ def __init__(self, :param str conversation_id: (optional) The unique identifier of the conversation. - :param SystemResponse system: (optional) For internal use only. + :param dict system: (optional) For internal use only. :param MessageContextMetadata metadata: (optional) Metadata related to the message. :param **kwargs: (optional) Any additional properties. @@ -3527,18 +3751,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Context': """Initialize a Context object from a json dictionary.""" args = {} - xtra = _dict.copy() if 'conversation_id' in _dict: args['conversation_id'] = _dict.get('conversation_id') - del xtra['conversation_id'] if 'system' in _dict: - args['system'] = SystemResponse._from_dict(_dict.get('system')) - del xtra['system'] + args['system'] = _dict.get('system') if 'metadata' in _dict: - args['metadata'] = MessageContextMetadata._from_dict( + args['metadata'] = MessageContextMetadata.from_dict( _dict.get('metadata')) - del xtra['metadata'] - args.update(xtra) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -3553,31 +3774,23 @@ def to_dict(self) -> Dict: 'conversation_id') and self.conversation_id is not None: _dict['conversation_id'] = self.conversation_id if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system._to_dict() + _dict['system'] = self.system if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata._to_dict() - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + _dict['metadata'] = self.metadata.to_dict() + for _key in [ + k for k in vars(self).keys() if k not in Context._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = {'conversation_id', 'system', 'metadata'} - if not hasattr(self, '_additionalProperties'): - super(Context, self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(Context, self).__setattr__(name, value) - def __str__(self) -> str: """Return a `str` version of this Context object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Context') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3615,10 +3828,6 @@ def __init__(self, string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. """ self.text = text self.created = created @@ -3628,12 +3837,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Counterexample': """Initialize a Counterexample object from a json dictionary.""" args = {} - valid_keys = ['text', 'created', 'updated'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Counterexample: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -3655,10 +3858,10 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) return _dict def _to_dict(self): @@ -3667,7 +3870,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Counterexample object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Counterexample') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3705,23 +3908,17 @@ def __init__(self, counterexamples: List['Counterexample'], def from_dict(cls, _dict: Dict) -> 'CounterexampleCollection': """Initialize a CounterexampleCollection object from a json dictionary.""" args = {} - valid_keys = ['counterexamples', 'pagination'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CounterexampleCollection: ' - + ', '.join(bad_keys)) if 'counterexamples' in _dict: args['counterexamples'] = [ - Counterexample._from_dict(x) - for x in (_dict.get('counterexamples')) + Counterexample.from_dict(x) + for x in _dict.get('counterexamples') ] else: raise ValueError( 'Required property \'counterexamples\' not present in CounterexampleCollection JSON' ) if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in CounterexampleCollection JSON' @@ -3739,10 +3936,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'counterexamples') and self.counterexamples is not None: _dict['counterexamples'] = [ - x._to_dict() for x in self.counterexamples + x.to_dict() for x in self.counterexamples ] if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -3751,7 +3948,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CounterexampleCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CounterexampleCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3809,10 +4006,6 @@ def __init__(self, :param dict metadata: (optional) Any metadata related to the entity. :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :param datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. :param List[CreateValue] values: (optional) An array of objects describing the entity values. """ @@ -3828,15 +4021,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateEntity': """Initialize a CreateEntity object from a json dictionary.""" args = {} - valid_keys = [ - 'entity', 'description', 'metadata', 'fuzzy_match', 'created', - 'updated', 'values' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CreateEntity: ' - + ', '.join(bad_keys)) if 'entity' in _dict: args['entity'] = _dict.get('entity') else: @@ -3854,7 +4038,7 @@ def from_dict(cls, _dict: Dict) -> 'CreateEntity': args['updated'] = string_to_datetime(_dict.get('updated')) if 'values' in _dict: args['values'] = [ - CreateValue._from_dict(x) for x in (_dict.get('values')) + CreateValue.from_dict(x) for x in _dict.get('values') ] return cls(**args) @@ -3874,12 +4058,12 @@ def to_dict(self) -> Dict: _dict['metadata'] = self.metadata if hasattr(self, 'fuzzy_match') and self.fuzzy_match is not None: _dict['fuzzy_match'] = self.fuzzy_match - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x._to_dict() for x in self.values] + _dict['values'] = [x.to_dict() for x in self.values] return _dict def _to_dict(self): @@ -3888,7 +4072,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CreateEntity object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CreateEntity') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3936,10 +4120,6 @@ def __init__(self, - It cannot begin with the reserved prefix `sys-`. :param str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :param datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. :param List[Example] examples: (optional) An array of user input examples for the intent. """ @@ -3953,12 +4133,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateIntent': """Initialize a CreateIntent object from a json dictionary.""" args = {} - valid_keys = ['intent', 'description', 'created', 'updated', 'examples'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CreateIntent: ' - + ', '.join(bad_keys)) if 'intent' in _dict: args['intent'] = _dict.get('intent') else: @@ -3972,7 +4146,7 @@ def from_dict(cls, _dict: Dict) -> 'CreateIntent': args['updated'] = string_to_datetime(_dict.get('updated')) if 'examples' in _dict: args['examples'] = [ - Example._from_dict(x) for x in (_dict.get('examples')) + Example.from_dict(x) for x in _dict.get('examples') ] return cls(**args) @@ -3988,12 +4162,12 @@ def to_dict(self) -> Dict: _dict['intent'] = self.intent if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x._to_dict() for x in self.examples] + _dict['examples'] = [x.to_dict() for x in self.examples] return _dict def _to_dict(self): @@ -4002,7 +4176,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CreateIntent object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CreateIntent') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4069,10 +4243,6 @@ def __init__(self, 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/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 - update to the object. """ self.value = value self.metadata = metadata @@ -4086,15 +4256,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateValue': """Initialize a CreateValue object from a json dictionary.""" args = {} - valid_keys = [ - 'value', 'metadata', 'type', 'synonyms', 'patterns', 'created', - 'updated' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CreateValue: ' - + ', '.join(bad_keys)) if 'value' in _dict: args['value'] = _dict.get('value') else: @@ -4132,10 +4293,10 @@ def to_dict(self) -> Dict: _dict['synonyms'] = self.synonyms if hasattr(self, 'patterns') and self.patterns is not None: _dict['patterns'] = self.patterns - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) return _dict def _to_dict(self): @@ -4144,7 +4305,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CreateValue object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CreateValue') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4156,12 +4317,12 @@ def __ne__(self, other: 'CreateValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ Specifies the type of entity value. """ - SYNONYMS = "synonyms" - PATTERNS = "patterns" + SYNONYMS = 'synonyms' + PATTERNS = 'patterns' class DialogNode(): @@ -4284,11 +4445,6 @@ def __init__(self, :param bool disambiguation_opt_out: (optional) Whether the dialog node should be excluded from disambiguation suggestions. Valid only when **type**=`standard` or `frame`. - :param bool disabled: (optional) For internal use only. - :param datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. """ self.dialog_node = dialog_node self.description = description @@ -4317,18 +4473,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNode': """Initialize a DialogNode object from a json dictionary.""" args = {} - valid_keys = [ - 'dialog_node', 'description', 'conditions', 'parent', - 'previous_sibling', 'output', 'context', 'metadata', 'next_step', - 'title', 'type', 'event_name', 'variable', 'actions', 'digress_in', - 'digress_out', 'digress_out_slots', 'user_label', - 'disambiguation_opt_out', 'disabled', 'created', 'updated' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNode: ' - + ', '.join(bad_keys)) if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') else: @@ -4344,13 +4488,13 @@ def from_dict(cls, _dict: Dict) -> 'DialogNode': if 'previous_sibling' in _dict: args['previous_sibling'] = _dict.get('previous_sibling') if 'output' in _dict: - args['output'] = DialogNodeOutput._from_dict(_dict.get('output')) + args['output'] = DialogNodeOutput.from_dict(_dict.get('output')) if 'context' in _dict: - args['context'] = DialogNodeContext._from_dict(_dict.get('context')) + args['context'] = DialogNodeContext.from_dict(_dict.get('context')) if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') if 'next_step' in _dict: - args['next_step'] = DialogNodeNextStep._from_dict( + args['next_step'] = DialogNodeNextStep.from_dict( _dict.get('next_step')) if 'title' in _dict: args['title'] = _dict.get('title') @@ -4362,7 +4506,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogNode': args['variable'] = _dict.get('variable') if 'actions' in _dict: args['actions'] = [ - DialogNodeAction._from_dict(x) for x in (_dict.get('actions')) + DialogNodeAction.from_dict(x) for x in _dict.get('actions') ] if 'digress_in' in _dict: args['digress_in'] = _dict.get('digress_in') @@ -4402,13 +4546,13 @@ def to_dict(self) -> Dict: 'previous_sibling') and self.previous_sibling is not None: _dict['previous_sibling'] = self.previous_sibling if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output._to_dict() + _dict['output'] = self.output.to_dict() if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context._to_dict() + _dict['context'] = self.context.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'next_step') and self.next_step is not None: - _dict['next_step'] = self.next_step._to_dict() + _dict['next_step'] = self.next_step.to_dict() if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'type') and self.type is not None: @@ -4418,7 +4562,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'variable') and self.variable is not None: _dict['variable'] = self.variable if hasattr(self, 'actions') and self.actions is not None: - _dict['actions'] = [x._to_dict() for x in self.actions] + _dict['actions'] = [x.to_dict() for x in self.actions] if hasattr(self, 'digress_in') and self.digress_in is not None: _dict['digress_in'] = self.digress_in if hasattr(self, 'digress_out') and self.digress_out is not None: @@ -4431,12 +4575,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'disambiguation_opt_out' ) and self.disambiguation_opt_out is not None: _dict['disambiguation_opt_out'] = self.disambiguation_opt_out - if hasattr(self, 'disabled') and self.disabled is not None: - _dict['disabled'] = self.disabled - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'disabled') and getattr(self, 'disabled') is not None: + _dict['disabled'] = getattr(self, 'disabled') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) return _dict def _to_dict(self): @@ -4445,7 +4589,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNode object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNode') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4457,54 +4601,54 @@ def __ne__(self, other: 'DialogNode') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ How the dialog node is processed. """ - STANDARD = "standard" - EVENT_HANDLER = "event_handler" - FRAME = "frame" - SLOT = "slot" - RESPONSE_CONDITION = "response_condition" - FOLDER = "folder" + STANDARD = 'standard' + EVENT_HANDLER = 'event_handler' + FRAME = 'frame' + SLOT = 'slot' + RESPONSE_CONDITION = 'response_condition' + FOLDER = 'folder' - class EventNameEnum(Enum): + class EventNameEnum(str, Enum): """ How an `event_handler` node is processed. """ - FOCUS = "focus" - INPUT = "input" - FILLED = "filled" - VALIDATE = "validate" - FILLED_MULTIPLE = "filled_multiple" - GENERIC = "generic" - NOMATCH = "nomatch" - NOMATCH_RESPONSES_DEPLETED = "nomatch_responses_depleted" - DIGRESSION_RETURN_PROMPT = "digression_return_prompt" + FOCUS = 'focus' + INPUT = 'input' + FILLED = 'filled' + VALIDATE = 'validate' + FILLED_MULTIPLE = 'filled_multiple' + GENERIC = 'generic' + NOMATCH = 'nomatch' + NOMATCH_RESPONSES_DEPLETED = 'nomatch_responses_depleted' + DIGRESSION_RETURN_PROMPT = 'digression_return_prompt' - class DigressInEnum(Enum): + class DigressInEnum(str, Enum): """ Whether this top-level dialog node can be digressed into. """ - NOT_AVAILABLE = "not_available" - RETURNS = "returns" - DOES_NOT_RETURN = "does_not_return" + NOT_AVAILABLE = 'not_available' + RETURNS = 'returns' + DOES_NOT_RETURN = 'does_not_return' - class DigressOutEnum(Enum): + class DigressOutEnum(str, Enum): """ Whether this dialog node can be returned to after a digression. """ - ALLOW_RETURNING = "allow_returning" - ALLOW_ALL = "allow_all" - ALLOW_ALL_NEVER_RETURN = "allow_all_never_return" + ALLOW_RETURNING = 'allow_returning' + ALLOW_ALL = 'allow_all' + ALLOW_ALL_NEVER_RETURN = 'allow_all_never_return' - class DigressOutSlotsEnum(Enum): + class DigressOutSlotsEnum(str, Enum): """ Whether the user can digress to top-level nodes while filling out slots. """ - NOT_ALLOWED = "not_allowed" - ALLOW_RETURNING = "allow_returning" - ALLOW_ALL = "allow_all" + NOT_ALLOWED = 'not_allowed' + ALLOW_RETURNING = 'allow_returning' + ALLOW_ALL = 'allow_all' class DialogNodeAction(): @@ -4550,14 +4694,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': """Initialize a DialogNodeAction object from a json dictionary.""" args = {} - valid_keys = [ - 'name', 'type', 'parameters', 'result_variable', 'credentials' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeAction: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -4605,7 +4741,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeAction object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeAction') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4617,15 +4753,15 @@ def __ne__(self, other: 'DialogNodeAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The type of action to invoke. """ - CLIENT = "client" - SERVER = "server" - CLOUD_FUNCTION = "cloud_function" - WEB_ACTION = "web_action" - WEBHOOK = "webhook" + CLIENT = 'client' + SERVER = 'server' + CLOUD_FUNCTION = 'cloud_function' + WEB_ACTION = 'web_action' + WEBHOOK = 'webhook' class DialogNodeCollection(): @@ -4653,22 +4789,16 @@ def __init__(self, dialog_nodes: List['DialogNode'], def from_dict(cls, _dict: Dict) -> 'DialogNodeCollection': """Initialize a DialogNodeCollection object from a json dictionary.""" args = {} - valid_keys = ['dialog_nodes', 'pagination'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeCollection: ' - + ', '.join(bad_keys)) if 'dialog_nodes' in _dict: args['dialog_nodes'] = [ - DialogNode._from_dict(x) for x in (_dict.get('dialog_nodes')) + DialogNode.from_dict(x) for x in _dict.get('dialog_nodes') ] else: raise ValueError( 'Required property \'dialog_nodes\' not present in DialogNodeCollection JSON' ) if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in DialogNodeCollection JSON' @@ -4684,9 +4814,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: - _dict['dialog_nodes'] = [x._to_dict() for x in self.dialog_nodes] + _dict['dialog_nodes'] = [x.to_dict() for x in self.dialog_nodes] if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -4695,7 +4825,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4716,6 +4846,9 @@ class DialogNodeContext(): integrations. """ + # The set of defined properties for the class + _properties = frozenset(['integrations']) + def __init__(self, *, integrations: dict = None, **kwargs) -> None: """ Initialize a DialogNodeContext object. @@ -4732,11 +4865,10 @@ def __init__(self, *, integrations: dict = None, **kwargs) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeContext': """Initialize a DialogNodeContext object from a json dictionary.""" args = {} - xtra = _dict.copy() if 'integrations' in _dict: args['integrations'] = _dict.get('integrations') - del xtra['integrations'] - args.update(xtra) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -4749,29 +4881,21 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + for _key in [ + k for k in vars(self).keys() + if k not in DialogNodeContext._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = {'integrations'} - if not hasattr(self, '_additionalProperties'): - super(DialogNodeContext, self).__setattr__('_additionalProperties', - set()) - if name not in properties: - self._additionalProperties.add(name) - super(DialogNodeContext, self).__setattr__(name, value) - def __str__(self) -> str: """Return a `str` version of this DialogNodeContext object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeContext') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4856,12 +4980,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeNextStep': """Initialize a DialogNodeNextStep object from a json dictionary.""" args = {} - valid_keys = ['behavior', 'dialog_node', 'selector'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeNextStep: ' - + ', '.join(bad_keys)) if 'behavior' in _dict: args['behavior'] = _dict.get('behavior') else: @@ -4896,7 +5014,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeNextStep object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeNextStep') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4908,7 +5026,7 @@ def __ne__(self, other: 'DialogNodeNextStep') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class BehaviorEnum(Enum): + class BehaviorEnum(str, Enum): """ What happens after the dialog node completes. The valid values depend on the node type: @@ -4932,21 +5050,21 @@ class BehaviorEnum(Enum): If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. """ - GET_USER_INPUT = "get_user_input" - SKIP_USER_INPUT = "skip_user_input" - JUMP_TO = "jump_to" - REPROMPT = "reprompt" - SKIP_SLOT = "skip_slot" - SKIP_ALL_SLOTS = "skip_all_slots" + GET_USER_INPUT = 'get_user_input' + SKIP_USER_INPUT = 'skip_user_input' + JUMP_TO = 'jump_to' + REPROMPT = 'reprompt' + SKIP_SLOT = 'skip_slot' + SKIP_ALL_SLOTS = 'skip_all_slots' - class SelectorEnum(Enum): + class SelectorEnum(str, Enum): """ Which part of the dialog node to process next. """ - CONDITION = "condition" - CLIENT = "client" - USER_INPUT = "user_input" - BODY = "body" + CONDITION = 'condition' + CLIENT = 'client' + USER_INPUT = 'user_input' + BODY = 'body' class DialogNodeOutput(): @@ -4964,6 +5082,9 @@ class DialogNodeOutput(): specified output is handled. """ + # The set of defined properties for the class + _properties = frozenset(['generic', 'integrations', 'modifiers']) + def __init__(self, *, generic: List['DialogNodeOutputGeneric'] = None, @@ -4992,21 +5113,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': """Initialize a DialogNodeOutput object from a json dictionary.""" args = {} - xtra = _dict.copy() if 'generic' in _dict: args['generic'] = [ - DialogNodeOutputGeneric._from_dict(x) - for x in (_dict.get('generic')) + DialogNodeOutputGeneric.from_dict(x) + for x in _dict.get('generic') ] - del xtra['generic'] if 'integrations' in _dict: args['integrations'] = _dict.get('integrations') - del xtra['integrations'] if 'modifiers' in _dict: - args['modifiers'] = DialogNodeOutputModifiers._from_dict( + args['modifiers'] = DialogNodeOutputModifiers.from_dict( _dict.get('modifiers')) - del xtra['modifiers'] - args.update(xtra) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -5018,34 +5136,26 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x._to_dict() for x in self.generic] + _dict['generic'] = [x.to_dict() for x in self.generic] if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations if hasattr(self, 'modifiers') and self.modifiers is not None: - _dict['modifiers'] = self.modifiers._to_dict() - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + _dict['modifiers'] = self.modifiers.to_dict() + for _key in [ + k for k in vars(self).keys() + if k not in DialogNodeOutput._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = {'generic', 'integrations', 'modifiers'} - if not hasattr(self, '_additionalProperties'): - super(DialogNodeOutput, self).__setattr__('_additionalProperties', - set()) - if name not in properties: - self._additionalProperties.add(name) - super(DialogNodeOutput, self).__setattr__(name, value) - def __str__(self) -> str: """Return a `str` version of this DialogNodeOutput object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeOutput') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5078,12 +5188,6 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" args = {} - valid_keys = ['target'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputConnectToAgentTransferInfo: ' - + ', '.join(bad_keys)) if 'target' in _dict: args['target'] = _dict.get('target') return cls(**args) @@ -5106,7 +5210,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputConnectToAgentTransferInfo object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: @@ -5149,15 +5253,17 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputGeneric': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = "Cannot convert dictionary into an instance of base class '{0}'. The discriminator value should map to a valid subclass: {1}".format( - cls.__name__, ", ".join([ - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill' - ])) + msg = ( + "Cannot convert dictionary into an instance of base class 'DialogNodeOutputGeneric'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill' + ])) raise Exception(msg) @classmethod @@ -5220,12 +5326,6 @@ def __init__(self, *, overwrite: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputModifiers': """Initialize a DialogNodeOutputModifiers object from a json dictionary.""" args = {} - valid_keys = ['overwrite'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputModifiers: ' - + ', '.join(bad_keys)) if 'overwrite' in _dict: args['overwrite'] = _dict.get('overwrite') return cls(**args) @@ -5248,7 +5348,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputModifiers object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeOutputModifiers') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5288,12 +5388,6 @@ def __init__(self, label: str, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} - valid_keys = ['label', 'value'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputOptionsElement: ' - + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') else: @@ -5301,7 +5395,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' ) if 'value' in _dict: - args['value'] = DialogNodeOutputOptionsElementValue._from_dict( + args['value'] = DialogNodeOutputOptionsElementValue.from_dict( _dict.get('value')) else: raise ValueError( @@ -5320,7 +5414,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value._to_dict() + _dict['value'] = self.value.to_dict() return _dict def _to_dict(self): @@ -5329,7 +5423,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputOptionsElement object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5386,21 +5480,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} - valid_keys = ['input', 'intents', 'entities'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputOptionsElementValue: ' - + ', '.join(bad_keys)) if 'input' in _dict: - args['input'] = MessageInput._from_dict(_dict.get('input')) + args['input'] = MessageInput.from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + RuntimeIntent.from_dict(x) for x in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + RuntimeEntity.from_dict(x) for x in _dict.get('entities') ] return cls(**args) @@ -5413,11 +5501,11 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input._to_dict() + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] + _dict['intents'] = [x.to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] return _dict def _to_dict(self): @@ -5426,7 +5514,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputOptionsElementValue object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5462,12 +5550,6 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputTextValuesElement': """Initialize a DialogNodeOutputTextValuesElement object from a json dictionary.""" args = {} - valid_keys = ['text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputTextValuesElement: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -5490,7 +5572,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputTextValuesElement object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeOutputTextValuesElement') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5535,12 +5617,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeVisitedDetails': """Initialize a DialogNodeVisitedDetails object from a json dictionary.""" args = {} - valid_keys = ['dialog_node', 'title', 'conditions'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeVisitedDetails: ' - + ', '.join(bad_keys)) if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') if 'title' in _dict: @@ -5571,7 +5647,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeVisitedDetails object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeVisitedDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5631,12 +5707,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - valid_keys = ['label', 'value', 'output', 'dialog_node'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogSuggestion: ' - + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') else: @@ -5644,7 +5714,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': 'Required property \'label\' not present in DialogSuggestion JSON' ) if 'value' in _dict: - args['value'] = DialogSuggestionValue._from_dict(_dict.get('value')) + args['value'] = DialogSuggestionValue.from_dict(_dict.get('value')) else: raise ValueError( 'Required property \'value\' not present in DialogSuggestion JSON' @@ -5666,7 +5736,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value._to_dict() + _dict['value'] = self.value.to_dict() if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output if hasattr(self, 'dialog_node') and self.dialog_node is not None: @@ -5679,7 +5749,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogSuggestion object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogSuggestion') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5728,21 +5798,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - valid_keys = ['input', 'intents', 'entities'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogSuggestionValue: ' - + ', '.join(bad_keys)) if 'input' in _dict: - args['input'] = MessageInput._from_dict(_dict.get('input')) + args['input'] = MessageInput.from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + RuntimeIntent.from_dict(x) for x in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + RuntimeEntity.from_dict(x) for x in _dict.get('entities') ] return cls(**args) @@ -5755,11 +5819,11 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input._to_dict() + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] + _dict['intents'] = [x.to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] return _dict def _to_dict(self): @@ -5768,7 +5832,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogSuggestionValue object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogSuggestionValue') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5826,10 +5890,6 @@ def __init__(self, :param dict metadata: (optional) Any metadata related to the entity. :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :param datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. :param List[Value] values: (optional) An array of objects describing the entity values. """ @@ -5845,15 +5905,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Entity': """Initialize a Entity object from a json dictionary.""" args = {} - valid_keys = [ - 'entity', 'description', 'metadata', 'fuzzy_match', 'created', - 'updated', 'values' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Entity: ' + - ', '.join(bad_keys)) if 'entity' in _dict: args['entity'] = _dict.get('entity') else: @@ -5870,9 +5921,7 @@ def from_dict(cls, _dict: Dict) -> 'Entity': if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'values' in _dict: - args['values'] = [ - Value._from_dict(x) for x in (_dict.get('values')) - ] + args['values'] = [Value.from_dict(x) for x in _dict.get('values')] return cls(**args) @classmethod @@ -5891,12 +5940,12 @@ def to_dict(self) -> Dict: _dict['metadata'] = self.metadata if hasattr(self, 'fuzzy_match') and self.fuzzy_match is not None: _dict['fuzzy_match'] = self.fuzzy_match - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x._to_dict() for x in self.values] + _dict['values'] = [x.to_dict() for x in self.values] return _dict def _to_dict(self): @@ -5905,7 +5954,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Entity object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Entity') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5943,22 +5992,16 @@ def __init__(self, entities: List['Entity'], def from_dict(cls, _dict: Dict) -> 'EntityCollection': """Initialize a EntityCollection object from a json dictionary.""" args = {} - valid_keys = ['entities', 'pagination'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EntityCollection: ' - + ', '.join(bad_keys)) if 'entities' in _dict: args['entities'] = [ - Entity._from_dict(x) for x in (_dict.get('entities')) + Entity.from_dict(x) for x in _dict.get('entities') ] else: raise ValueError( 'Required property \'entities\' not present in EntityCollection JSON' ) if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in EntityCollection JSON' @@ -5974,9 +6017,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -5985,7 +6028,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EntityCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EntityCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6025,12 +6068,6 @@ def __init__(self, text: str, intent: str, location: List[int]) -> None: def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} - valid_keys = ['text', 'intent', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EntityMention: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -6072,7 +6109,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EntityMention object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EntityMention') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6110,22 +6147,16 @@ def __init__(self, examples: List['EntityMention'], def from_dict(cls, _dict: Dict) -> 'EntityMentionCollection': """Initialize a EntityMentionCollection object from a json dictionary.""" args = {} - valid_keys = ['examples', 'pagination'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EntityMentionCollection: ' - + ', '.join(bad_keys)) if 'examples' in _dict: args['examples'] = [ - EntityMention._from_dict(x) for x in (_dict.get('examples')) + EntityMention.from_dict(x) for x in _dict.get('examples') ] else: raise ValueError( 'Required property \'examples\' not present in EntityMentionCollection JSON' ) if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in EntityMentionCollection JSON' @@ -6141,9 +6172,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x._to_dict() for x in self.examples] + _dict['examples'] = [x.to_dict() for x in self.examples] if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6152,7 +6183,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EntityMentionCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EntityMentionCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6194,10 +6225,6 @@ def __init__(self, - It cannot consist of only whitespace characters. :param List[Mention] mentions: (optional) An array of contextual entity mentions. - :param datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. """ self.text = text self.mentions = mentions @@ -6208,12 +6235,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Example': """Initialize a Example object from a json dictionary.""" args = {} - valid_keys = ['text', 'mentions', 'created', 'updated'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Example: ' + - ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -6221,7 +6242,7 @@ def from_dict(cls, _dict: Dict) -> 'Example': 'Required property \'text\' not present in Example JSON') if 'mentions' in _dict: args['mentions'] = [ - Mention._from_dict(x) for x in (_dict.get('mentions')) + Mention.from_dict(x) for x in _dict.get('mentions') ] if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) @@ -6240,11 +6261,11 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = [x._to_dict() for x in self.mentions] - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + _dict['mentions'] = [x.to_dict() for x in self.mentions] + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) return _dict def _to_dict(self): @@ -6253,7 +6274,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Example object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Example') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6291,22 +6312,16 @@ def __init__(self, examples: List['Example'], def from_dict(cls, _dict: Dict) -> 'ExampleCollection': """Initialize a ExampleCollection object from a json dictionary.""" args = {} - valid_keys = ['examples', 'pagination'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ExampleCollection: ' - + ', '.join(bad_keys)) if 'examples' in _dict: args['examples'] = [ - Example._from_dict(x) for x in (_dict.get('examples')) + Example.from_dict(x) for x in _dict.get('examples') ] else: raise ValueError( 'Required property \'examples\' not present in ExampleCollection JSON' ) if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in ExampleCollection JSON' @@ -6322,9 +6337,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x._to_dict() for x in self.examples] + _dict['examples'] = [x.to_dict() for x in self.examples] if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6333,7 +6348,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ExampleCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ExampleCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6381,10 +6396,6 @@ def __init__(self, - It cannot begin with the reserved prefix `sys-`. :param str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :param datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. :param List[Example] examples: (optional) An array of user input examples for the intent. """ @@ -6398,12 +6409,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Intent': """Initialize a Intent object from a json dictionary.""" args = {} - valid_keys = ['intent', 'description', 'created', 'updated', 'examples'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Intent: ' + - ', '.join(bad_keys)) if 'intent' in _dict: args['intent'] = _dict.get('intent') else: @@ -6417,7 +6422,7 @@ def from_dict(cls, _dict: Dict) -> 'Intent': args['updated'] = string_to_datetime(_dict.get('updated')) if 'examples' in _dict: args['examples'] = [ - Example._from_dict(x) for x in (_dict.get('examples')) + Example.from_dict(x) for x in _dict.get('examples') ] return cls(**args) @@ -6433,12 +6438,12 @@ def to_dict(self) -> Dict: _dict['intent'] = self.intent if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x._to_dict() for x in self.examples] + _dict['examples'] = [x.to_dict() for x in self.examples] return _dict def _to_dict(self): @@ -6447,7 +6452,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Intent object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Intent') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6485,22 +6490,16 @@ def __init__(self, intents: List['Intent'], def from_dict(cls, _dict: Dict) -> 'IntentCollection': """Initialize a IntentCollection object from a json dictionary.""" args = {} - valid_keys = ['intents', 'pagination'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class IntentCollection: ' - + ', '.join(bad_keys)) if 'intents' in _dict: args['intents'] = [ - Intent._from_dict(x) for x in (_dict.get('intents')) + Intent.from_dict(x) for x in _dict.get('intents') ] else: raise ValueError( 'Required property \'intents\' not present in IntentCollection JSON' ) if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in IntentCollection JSON' @@ -6516,9 +6515,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] + _dict['intents'] = [x.to_dict() for x in self.intents] if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6527,7 +6526,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this IntentCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'IntentCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6589,22 +6588,13 @@ def __init__(self, request: 'MessageRequest', response: 'MessageResponse', def from_dict(cls, _dict: Dict) -> 'Log': """Initialize a Log object from a json dictionary.""" args = {} - valid_keys = [ - 'request', 'response', 'log_id', 'request_timestamp', - 'response_timestamp', 'workspace_id', 'language' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Log: ' + - ', '.join(bad_keys)) if 'request' in _dict: - args['request'] = MessageRequest._from_dict(_dict.get('request')) + args['request'] = MessageRequest.from_dict(_dict.get('request')) else: raise ValueError( 'Required property \'request\' not present in Log JSON') if 'response' in _dict: - args['response'] = MessageResponse._from_dict(_dict.get('response')) + args['response'] = MessageResponse.from_dict(_dict.get('response')) else: raise ValueError( 'Required property \'response\' not present in Log JSON') @@ -6646,9 +6636,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'request') and self.request is not None: - _dict['request'] = self.request._to_dict() + _dict['request'] = self.request.to_dict() if hasattr(self, 'response') and self.response is not None: - _dict['response'] = self.response._to_dict() + _dict['response'] = self.response.to_dict() if hasattr(self, 'log_id') and self.log_id is not None: _dict['log_id'] = self.log_id if hasattr(self, @@ -6670,7 +6660,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Log object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Log') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6706,19 +6696,13 @@ def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} - valid_keys = ['logs', 'pagination'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LogCollection: ' - + ', '.join(bad_keys)) if 'logs' in _dict: - args['logs'] = [Log._from_dict(x) for x in (_dict.get('logs'))] + args['logs'] = [Log.from_dict(x) for x in _dict.get('logs')] else: raise ValueError( 'Required property \'logs\' not present in LogCollection JSON') if 'pagination' in _dict: - args['pagination'] = LogPagination._from_dict( + args['pagination'] = LogPagination.from_dict( _dict.get('pagination')) else: raise ValueError( @@ -6735,9 +6719,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'logs') and self.logs is not None: - _dict['logs'] = [x._to_dict() for x in self.logs] + _dict['logs'] = [x.to_dict() for x in self.logs] if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6746,7 +6730,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LogCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LogCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6781,12 +6765,6 @@ def __init__(self, level: str, msg: str) -> None: def from_dict(cls, _dict: Dict) -> 'LogMessage': """Initialize a LogMessage object from a json dictionary.""" args = {} - valid_keys = ['level', 'msg'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LogMessage: ' - + ', '.join(bad_keys)) if 'level' in _dict: args['level'] = _dict.get('level') else: @@ -6819,7 +6797,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LogMessage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LogMessage') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6831,13 +6809,13 @@ def __ne__(self, other: 'LogMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LevelEnum(Enum): + class LevelEnum(str, Enum): """ The severity of the log message. """ - INFO = "info" - ERROR = "error" - WARN = "warn" + INFO = 'info' + ERROR = 'error' + WARN = 'warn' class LogPagination(): @@ -6872,12 +6850,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogPagination': """Initialize a LogPagination object from a json dictionary.""" args = {} - valid_keys = ['next_url', 'matched', 'next_cursor'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LogPagination: ' - + ', '.join(bad_keys)) if 'next_url' in _dict: args['next_url'] = _dict.get('next_url') if 'matched' in _dict: @@ -6908,7 +6880,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LogPagination object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LogPagination') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6945,12 +6917,6 @@ def __init__(self, entity: str, location: List[int]) -> None: def from_dict(cls, _dict: Dict) -> 'Mention': """Initialize a Mention object from a json dictionary.""" args = {} - valid_keys = ['entity', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Mention: ' + - ', '.join(bad_keys)) if 'entity' in _dict: args['entity'] = _dict.get('entity') else: @@ -6983,7 +6949,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Mention object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Mention') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7031,12 +6997,6 @@ def __init__(self, *, deployment: str = None, user_id: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'MessageContextMetadata': """Initialize a MessageContextMetadata object from a json dictionary.""" args = {} - valid_keys = ['deployment', 'user_id'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageContextMetadata: ' - + ', '.join(bad_keys)) if 'deployment' in _dict: args['deployment'] = _dict.get('deployment') if 'user_id' in _dict: @@ -7063,7 +7023,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageContextMetadata object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageContextMetadata') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7100,6 +7060,12 @@ class MessageInput(): is returned only if autocorrection is enabled and the user input was corrected. """ + # The set of defined properties for the class + _properties = frozenset([ + 'text', 'spelling_suggestions', 'spelling_auto_correct', + 'suggested_text', 'original_text' + ]) + def __init__(self, *, text: str = None, @@ -7124,12 +7090,6 @@ def __init__(self, the original text is returned in the **original_text** property of the message response. This property overrides the value of the **spelling_auto_correct** property in the workspace settings. - :param str suggested_text: (optional) Any suggested corrections of the - input text. This property is returned only if spelling correction is - enabled and autocorrection is disabled. - :param str original_text: (optional) The original user input text. This - property is returned only if autocorrection is enabled and the user input - was corrected. :param **kwargs: (optional) Any additional properties. """ self.text = text @@ -7144,23 +7104,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} - xtra = _dict.copy() if 'text' in _dict: args['text'] = _dict.get('text') - del xtra['text'] if 'spelling_suggestions' in _dict: args['spelling_suggestions'] = _dict.get('spelling_suggestions') - del xtra['spelling_suggestions'] if 'spelling_auto_correct' in _dict: args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') - del xtra['spelling_auto_correct'] if 'suggested_text' in _dict: args['suggested_text'] = _dict.get('suggested_text') - del xtra['suggested_text'] if 'original_text' in _dict: args['original_text'] = _dict.get('original_text') - del xtra['original_text'] - args.update(xtra) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -7179,36 +7134,27 @@ def to_dict(self) -> Dict: if hasattr(self, 'spelling_auto_correct' ) and self.spelling_auto_correct is not None: _dict['spelling_auto_correct'] = self.spelling_auto_correct - if hasattr(self, 'suggested_text') and self.suggested_text is not None: - _dict['suggested_text'] = self.suggested_text - if hasattr(self, 'original_text') and self.original_text is not None: - _dict['original_text'] = self.original_text - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + if hasattr(self, 'suggested_text') and getattr( + self, 'suggested_text') is not None: + _dict['suggested_text'] = getattr(self, 'suggested_text') + if hasattr(self, 'original_text') and getattr( + self, 'original_text') is not None: + _dict['original_text'] = getattr(self, 'original_text') + for _key in [ + k for k in vars(self).keys() + if k not in MessageInput._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = { - 'text', 'spelling_suggestions', 'spelling_auto_correct', - 'suggested_text', 'original_text' - } - if not hasattr(self, '_additionalProperties'): - super(MessageInput, self).__setattr__('_additionalProperties', - set()) - if name not in properties: - self._additionalProperties.add(name) - super(MessageInput, self).__setattr__(name, value) - def __str__(self) -> str: """Return a `str` version of this MessageInput object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageInput') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7272,8 +7218,6 @@ def __init__(self, :param OutputData output: (optional) An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :param List[DialogNodeAction] actions: (optional) An array of objects - describing any actions requested by the dialog node. """ self.input = input self.intents = intents @@ -7287,34 +7231,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageRequest': """Initialize a MessageRequest object from a json dictionary.""" args = {} - valid_keys = [ - 'input', 'intents', 'entities', 'alternate_intents', 'context', - 'output', 'actions' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageRequest: ' - + ', '.join(bad_keys)) if 'input' in _dict: - args['input'] = MessageInput._from_dict(_dict.get('input')) + args['input'] = MessageInput.from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + RuntimeIntent.from_dict(x) for x in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + RuntimeEntity.from_dict(x) for x in _dict.get('entities') ] if 'alternate_intents' in _dict: args['alternate_intents'] = _dict.get('alternate_intents') if 'context' in _dict: - args['context'] = Context._from_dict(_dict.get('context')) + args['context'] = Context.from_dict(_dict.get('context')) if 'output' in _dict: - args['output'] = OutputData._from_dict(_dict.get('output')) + args['output'] = OutputData.from_dict(_dict.get('output')) if 'actions' in _dict: args['actions'] = [ - DialogNodeAction._from_dict(x) for x in (_dict.get('actions')) + DialogNodeAction.from_dict(x) for x in _dict.get('actions') ] return cls(**args) @@ -7327,20 +7262,20 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input._to_dict() + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] + _dict['intents'] = [x.to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context._to_dict() + _dict['context'] = self.context.to_dict() if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output._to_dict() - if hasattr(self, 'actions') and self.actions is not None: - _dict['actions'] = [x._to_dict() for x in self.actions] + _dict['output'] = self.output.to_dict() + if hasattr(self, 'actions') and getattr(self, 'actions') is not None: + _dict['actions'] = [x.to_dict() for x in getattr(self, 'actions')] return _dict def _to_dict(self): @@ -7349,7 +7284,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageRequest object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageRequest') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7405,8 +7340,6 @@ def __init__(self, the user, the dialog nodes that were triggered, and messages from the log. :param bool alternate_intents: (optional) Whether to return more than one intent. A value of `true` indicates that all matching intents are returned. - :param List[DialogNodeAction] actions: (optional) An array of objects - describing any actions requested by the dialog node. """ self.input = input self.intents = intents @@ -7420,24 +7353,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageResponse': """Initialize a MessageResponse object from a json dictionary.""" args = {} - valid_keys = [ - 'input', 'intents', 'entities', 'alternate_intents', 'context', - 'output', 'actions' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageResponse: ' - + ', '.join(bad_keys)) if 'input' in _dict: - args['input'] = MessageInput._from_dict(_dict.get('input')) + args['input'] = MessageInput.from_dict(_dict.get('input')) else: raise ValueError( 'Required property \'input\' not present in MessageResponse JSON' ) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + RuntimeIntent.from_dict(x) for x in _dict.get('intents') ] else: raise ValueError( @@ -7445,7 +7369,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageResponse': ) if 'entities' in _dict: args['entities'] = [ - RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + RuntimeEntity.from_dict(x) for x in _dict.get('entities') ] else: raise ValueError( @@ -7454,20 +7378,20 @@ def from_dict(cls, _dict: Dict) -> 'MessageResponse': if 'alternate_intents' in _dict: args['alternate_intents'] = _dict.get('alternate_intents') if 'context' in _dict: - args['context'] = Context._from_dict(_dict.get('context')) + args['context'] = Context.from_dict(_dict.get('context')) else: raise ValueError( 'Required property \'context\' not present in MessageResponse JSON' ) if 'output' in _dict: - args['output'] = OutputData._from_dict(_dict.get('output')) + args['output'] = OutputData.from_dict(_dict.get('output')) else: raise ValueError( 'Required property \'output\' not present in MessageResponse JSON' ) if 'actions' in _dict: args['actions'] = [ - DialogNodeAction._from_dict(x) for x in (_dict.get('actions')) + DialogNodeAction.from_dict(x) for x in _dict.get('actions') ] return cls(**args) @@ -7480,20 +7404,20 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input._to_dict() + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] + _dict['intents'] = [x.to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context._to_dict() + _dict['context'] = self.context.to_dict() if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output._to_dict() - if hasattr(self, 'actions') and self.actions is not None: - _dict['actions'] = [x._to_dict() for x in self.actions] + _dict['output'] = self.output.to_dict() + if hasattr(self, 'actions') and getattr(self, 'actions') is not None: + _dict['actions'] = [x.to_dict() for x in getattr(self, 'actions')] return _dict def _to_dict(self): @@ -7502,7 +7426,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7536,6 +7460,12 @@ class OutputData(): supported response types. """ + # The set of defined properties for the class + _properties = frozenset([ + 'nodes_visited', 'nodes_visited_details', 'log_messages', 'text', + 'generic' + ]) + def __init__(self, log_messages: List['LogMessage'], text: List[str], @@ -7575,38 +7505,33 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'OutputData': """Initialize a OutputData object from a json dictionary.""" args = {} - xtra = _dict.copy() if 'nodes_visited' in _dict: args['nodes_visited'] = _dict.get('nodes_visited') - del xtra['nodes_visited'] if 'nodes_visited_details' in _dict: args['nodes_visited_details'] = [ - DialogNodeVisitedDetails._from_dict(x) - for x in (_dict.get('nodes_visited_details')) + DialogNodeVisitedDetails.from_dict(x) + for x in _dict.get('nodes_visited_details') ] - del xtra['nodes_visited_details'] if 'log_messages' in _dict: args['log_messages'] = [ - LogMessage._from_dict(x) for x in (_dict.get('log_messages')) + LogMessage.from_dict(x) for x in _dict.get('log_messages') ] - del xtra['log_messages'] else: raise ValueError( 'Required property \'log_messages\' not present in OutputData JSON' ) if 'text' in _dict: args['text'] = _dict.get('text') - del xtra['text'] else: raise ValueError( 'Required property \'text\' not present in OutputData JSON') if 'generic' in _dict: args['generic'] = [ - RuntimeResponseGeneric._from_dict(x) - for x in (_dict.get('generic')) + RuntimeResponseGeneric.from_dict(x) + for x in _dict.get('generic') ] - del xtra['generic'] - args.update(xtra) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -7622,39 +7547,28 @@ def to_dict(self) -> Dict: if hasattr(self, 'nodes_visited_details' ) and self.nodes_visited_details is not None: _dict['nodes_visited_details'] = [ - x._to_dict() for x in self.nodes_visited_details + x.to_dict() for x in self.nodes_visited_details ] if hasattr(self, 'log_messages') and self.log_messages is not None: - _dict['log_messages'] = [x._to_dict() for x in self.log_messages] + _dict['log_messages'] = [x.to_dict() for x in self.log_messages] if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x._to_dict() for x in self.generic] - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + _dict['generic'] = [x.to_dict() for x in self.generic] + for _key in [ + k for k in vars(self).keys() if k not in OutputData._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = { - 'nodes_visited', 'nodes_visited_details', 'log_messages', 'text', - 'generic' - } - if not hasattr(self, '_additionalProperties'): - super(OutputData, self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(OutputData, self).__setattr__(name, value) - def __str__(self) -> str: """Return a `str` version of this OutputData object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'OutputData') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7717,15 +7631,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Pagination': """Initialize a Pagination object from a json dictionary.""" args = {} - valid_keys = [ - 'refresh_url', 'next_url', 'total', 'matched', 'refresh_cursor', - 'next_cursor' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Pagination: ' - + ', '.join(bad_keys)) if 'refresh_url' in _dict: args['refresh_url'] = _dict.get('refresh_url') else: @@ -7772,7 +7677,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Pagination object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Pagination') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7872,15 +7777,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} - valid_keys = [ - 'entity', 'location', 'value', 'confidence', 'metadata', 'groups', - 'interpretation', 'alternatives', 'role' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeEntity: ' - + ', '.join(bad_keys)) if 'entity' in _dict: args['entity'] = _dict.get('entity') else: @@ -7904,18 +7800,18 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': args['metadata'] = _dict.get('metadata') if 'groups' in _dict: args['groups'] = [ - CaptureGroup._from_dict(x) for x in (_dict.get('groups')) + CaptureGroup.from_dict(x) for x in _dict.get('groups') ] if 'interpretation' in _dict: - args['interpretation'] = RuntimeEntityInterpretation._from_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')) + RuntimeEntityAlternative.from_dict(x) + for x in _dict.get('alternatives') ] if 'role' in _dict: - args['role'] = RuntimeEntityRole._from_dict(_dict.get('role')) + args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) return cls(**args) @classmethod @@ -7937,13 +7833,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'groups') and self.groups is not None: - _dict['groups'] = [x._to_dict() for x in self.groups] + _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() + _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] + _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() + _dict['role'] = self.role.to_dict() return _dict def _to_dict(self): @@ -7952,7 +7848,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeEntity object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeEntity') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7991,12 +7887,6 @@ def __init__(self, *, value: str = None, confidence: float = None) -> None: 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: @@ -8023,7 +7913,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeEntityAlternative object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8246,21 +8136,6 @@ def __init__(self, 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: @@ -8390,7 +8265,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeEntityInterpretation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8402,22 +8277,22 @@ def __ne__(self, other: 'RuntimeEntityInterpretation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class GranularityEnum(Enum): + class GranularityEnum(str, 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" + DAY = 'day' + FORTNIGHT = 'fortnight' + HOUR = 'hour' + INSTANT = 'instant' + MINUTE = 'minute' + MONTH = 'month' + QUARTER = 'quarter' + SECOND = 'second' + WEEK = 'week' + WEEKEND = 'weekend' + YEAR = 'year' class RuntimeEntityRole(): @@ -8441,12 +8316,6 @@ def __init__(self, *, type: str = None) -> None: 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) @@ -8469,7 +8338,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeEntityRole object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeEntityRole') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8481,16 +8350,16 @@ def __ne__(self, other: 'RuntimeEntityRole') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, 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" + 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(): @@ -8517,12 +8386,6 @@ def __init__(self, intent: str, confidence: float) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': """Initialize a RuntimeIntent object from a json dictionary.""" args = {} - valid_keys = ['intent', 'confidence'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeIntent: ' - + ', '.join(bad_keys)) if 'intent' in _dict: args['intent'] = _dict.get('intent') else: @@ -8557,7 +8420,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeIntent object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeIntent') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8598,15 +8461,17 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = "Cannot convert dictionary into an instance of base class '{0}'. The discriminator value should map to a valid subclass: {1}".format( - cls.__name__, ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' - ])) + msg = ( + "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + ])) raise Exception(msg) @classmethod @@ -8665,10 +8530,6 @@ def __init__(self, the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :param datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. """ self.synonym = synonym self.created = created @@ -8678,12 +8539,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Synonym': """Initialize a Synonym object from a json dictionary.""" args = {} - valid_keys = ['synonym', 'created', 'updated'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Synonym: ' + - ', '.join(bad_keys)) if 'synonym' in _dict: args['synonym'] = _dict.get('synonym') else: @@ -8705,10 +8560,10 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'synonym') and self.synonym is not None: _dict['synonym'] = self.synonym - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) return _dict def _to_dict(self): @@ -8717,7 +8572,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Synonym object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Synonym') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8753,22 +8608,16 @@ def __init__(self, synonyms: List['Synonym'], def from_dict(cls, _dict: Dict) -> 'SynonymCollection': """Initialize a SynonymCollection object from a json dictionary.""" args = {} - valid_keys = ['synonyms', 'pagination'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SynonymCollection: ' - + ', '.join(bad_keys)) if 'synonyms' in _dict: args['synonyms'] = [ - Synonym._from_dict(x) for x in (_dict.get('synonyms')) + Synonym.from_dict(x) for x in _dict.get('synonyms') ] else: raise ValueError( 'Required property \'synonyms\' not present in SynonymCollection JSON' ) if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in SynonymCollection JSON' @@ -8784,9 +8633,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'synonyms') and self.synonyms is not None: - _dict['synonyms'] = [x._to_dict() for x in self.synonyms] + _dict['synonyms'] = [x.to_dict() for x in self.synonyms] if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -8795,7 +8644,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SynonymCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SynonymCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8808,72 +8657,6 @@ def __ne__(self, other: 'SynonymCollection') -> bool: return not self == other -class SystemResponse(): - """ - For internal use only. - - """ - - def __init__(self, **kwargs) -> None: - """ - Initialize a SystemResponse object. - - :param **kwargs: (optional) Any additional properties. - """ - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SystemResponse': - """Initialize a SystemResponse object from a json dictionary.""" - args = {} - xtra = _dict.copy() - args.update(xtra) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SystemResponse 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, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __setattr__(self, name: str, value: object) -> None: - properties = {} - if not hasattr(self, '_additionalProperties'): - super(SystemResponse, self).__setattr__('_additionalProperties', - set()) - if name not in properties: - self._additionalProperties.add(name) - super(SystemResponse, self).__setattr__(name, value) - - def __str__(self) -> str: - """Return a `str` version of this SystemResponse object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other: 'SystemResponse') -> 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: 'SystemResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class Value(): """ Value. @@ -8928,10 +8711,6 @@ def __init__(self, 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/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 - update to the object. """ self.value = value self.metadata = metadata @@ -8945,15 +8724,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Value': """Initialize a Value object from a json dictionary.""" args = {} - valid_keys = [ - 'value', 'metadata', 'type', 'synonyms', 'patterns', 'created', - 'updated' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Value: ' + - ', '.join(bad_keys)) if 'value' in _dict: args['value'] = _dict.get('value') else: @@ -8994,10 +8764,10 @@ def to_dict(self) -> Dict: _dict['synonyms'] = self.synonyms if hasattr(self, 'patterns') and self.patterns is not None: _dict['patterns'] = self.patterns - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) return _dict def _to_dict(self): @@ -9006,7 +8776,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Value object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Value') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9018,12 +8788,12 @@ def __ne__(self, other: 'Value') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ Specifies the type of entity value. """ - SYNONYMS = "synonyms" - PATTERNS = "patterns" + SYNONYMS = 'synonyms' + PATTERNS = 'patterns' class ValueCollection(): @@ -9048,22 +8818,14 @@ def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: def from_dict(cls, _dict: Dict) -> 'ValueCollection': """Initialize a ValueCollection object from a json dictionary.""" args = {} - valid_keys = ['values', 'pagination'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ValueCollection: ' - + ', '.join(bad_keys)) if 'values' in _dict: - args['values'] = [ - Value._from_dict(x) for x in (_dict.get('values')) - ] + args['values'] = [Value.from_dict(x) for x in _dict.get('values')] else: raise ValueError( 'Required property \'values\' not present in ValueCollection JSON' ) if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in ValueCollection JSON' @@ -9079,9 +8841,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x._to_dict() for x in self.values] + _dict['values'] = [x.to_dict() for x in self.values] if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -9090,7 +8852,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ValueCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ValueCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9113,7 +8875,7 @@ class Webhook(): to send HTTP POST requests. :attr str name: The name of the webhook. Currently, `main_webhook` is the only supported value. - :attr List[WebhookHeader] headers: (optional) An optional array of HTTP headers + :attr List[WebhookHeader] headers_: (optional) An optional array of HTTP headers to pass with the HTTP request. """ @@ -9121,7 +8883,7 @@ def __init__(self, url: str, name: str, *, - headers: List['WebhookHeader'] = None) -> None: + headers_: List['WebhookHeader'] = None) -> None: """ Initialize a Webhook object. @@ -9129,23 +8891,17 @@ def __init__(self, you want to send HTTP POST requests. :param str name: The name of the webhook. Currently, `main_webhook` is the only supported value. - :param List[WebhookHeader] headers: (optional) An optional array of HTTP + :param List[WebhookHeader] headers_: (optional) An optional array of HTTP headers to pass with the HTTP request. """ self.url = url self.name = name - self.headers = headers + self.headers_ = headers_ @classmethod def from_dict(cls, _dict: Dict) -> 'Webhook': """Initialize a Webhook object from a json dictionary.""" args = {} - valid_keys = ['url', 'name', 'headers'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Webhook: ' + - ', '.join(bad_keys)) if 'url' in _dict: args['url'] = _dict.get('url') else: @@ -9157,8 +8913,8 @@ def from_dict(cls, _dict: Dict) -> 'Webhook': raise ValueError( 'Required property \'name\' not present in Webhook JSON') if 'headers' in _dict: - args['headers'] = [ - WebhookHeader._from_dict(x) for x in (_dict.get('headers')) + args['headers_'] = [ + WebhookHeader.from_dict(x) for x in _dict.get('headers') ] return cls(**args) @@ -9174,8 +8930,8 @@ def to_dict(self) -> Dict: _dict['url'] = self.url if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name - if hasattr(self, 'headers') and self.headers is not None: - _dict['headers'] = [x._to_dict() for x in self.headers] + if hasattr(self, 'headers_') and self.headers_ is not None: + _dict['headers'] = [x.to_dict() for x in self.headers_] return _dict def _to_dict(self): @@ -9184,7 +8940,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Webhook object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Webhook') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9219,12 +8975,6 @@ def __init__(self, name: str, value: str) -> None: def from_dict(cls, _dict: Dict) -> 'WebhookHeader': """Initialize a WebhookHeader object from a json dictionary.""" args = {} - valid_keys = ['name', 'value'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WebhookHeader: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -9257,7 +9007,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WebhookHeader object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WebhookHeader') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9334,14 +9084,9 @@ def __init__(self, describing the dialog nodes in the workspace. :param List[Counterexample] counterexamples: (optional) An array of objects defining input examples that have been marked as irrelevant input. - :param datetime created: (optional) The timestamp for creation of the - object. - :param datetime updated: (optional) The timestamp for the most recent - update to the object. :param dict metadata: (optional) Any metadata related to the workspace. :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. - :param str status: (optional) The current status of the workspace. :param List[Webhook] webhooks: (optional) :param List[Intent] intents: (optional) An array of intents. :param List[Entity] entities: (optional) An array of objects describing the @@ -9367,17 +9112,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Workspace': """Initialize a Workspace object from a json dictionary.""" args = {} - valid_keys = [ - 'name', 'description', 'language', 'workspace_id', 'dialog_nodes', - 'counterexamples', 'created', 'updated', 'metadata', - 'learning_opt_out', 'system_settings', 'status', 'webhooks', - 'intents', 'entities' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Workspace: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -9398,12 +9132,12 @@ def from_dict(cls, _dict: Dict) -> 'Workspace': ) if 'dialog_nodes' in _dict: args['dialog_nodes'] = [ - DialogNode._from_dict(x) for x in (_dict.get('dialog_nodes')) + DialogNode.from_dict(x) for x in _dict.get('dialog_nodes') ] if 'counterexamples' in _dict: args['counterexamples'] = [ - Counterexample._from_dict(x) - for x in (_dict.get('counterexamples')) + Counterexample.from_dict(x) + for x in _dict.get('counterexamples') ] if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) @@ -9418,21 +9152,21 @@ def from_dict(cls, _dict: Dict) -> 'Workspace': 'Required property \'learning_opt_out\' not present in Workspace JSON' ) if 'system_settings' in _dict: - args['system_settings'] = WorkspaceSystemSettings._from_dict( + args['system_settings'] = WorkspaceSystemSettings.from_dict( _dict.get('system_settings')) if 'status' in _dict: args['status'] = _dict.get('status') if 'webhooks' in _dict: args['webhooks'] = [ - Webhook._from_dict(x) for x in (_dict.get('webhooks')) + Webhook.from_dict(x) for x in _dict.get('webhooks') ] if 'intents' in _dict: args['intents'] = [ - Intent._from_dict(x) for x in (_dict.get('intents')) + Intent.from_dict(x) for x in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - Entity._from_dict(x) for x in (_dict.get('entities')) + Entity.from_dict(x) for x in _dict.get('entities') ] return cls(**args) @@ -9450,19 +9184,20 @@ def to_dict(self) -> Dict: _dict['description'] = self.description if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language - if hasattr(self, 'workspace_id') and self.workspace_id is not None: - _dict['workspace_id'] = self.workspace_id + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: - _dict['dialog_nodes'] = [x._to_dict() for x in self.dialog_nodes] + _dict['dialog_nodes'] = [x.to_dict() for x in self.dialog_nodes] if hasattr(self, 'counterexamples') and self.counterexamples is not None: _dict['counterexamples'] = [ - x._to_dict() for x in self.counterexamples + x.to_dict() for x in self.counterexamples ] - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, @@ -9470,15 +9205,15 @@ def to_dict(self) -> Dict: _dict['learning_opt_out'] = self.learning_opt_out if hasattr(self, 'system_settings') and self.system_settings is not None: - _dict['system_settings'] = self.system_settings._to_dict() - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status + _dict['system_settings'] = self.system_settings.to_dict() + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') if hasattr(self, 'webhooks') and self.webhooks is not None: - _dict['webhooks'] = [x._to_dict() for x in self.webhooks] + _dict['webhooks'] = [x.to_dict() for x in self.webhooks] if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] + _dict['intents'] = [x.to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] return _dict def _to_dict(self): @@ -9487,7 +9222,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Workspace object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Workspace') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9499,15 +9234,15 @@ def __ne__(self, other: 'Workspace') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The current status of the workspace. """ - NON_EXISTENT = "Non Existent" - TRAINING = "Training" - FAILED = "Failed" - AVAILABLE = "Available" - UNAVAILABLE = "Unavailable" + NON_EXISTENT = 'Non Existent' + TRAINING = 'Training' + FAILED = 'Failed' + AVAILABLE = 'Available' + UNAVAILABLE = 'Unavailable' class WorkspaceCollection(): @@ -9535,22 +9270,16 @@ def __init__(self, workspaces: List['Workspace'], def from_dict(cls, _dict: Dict) -> 'WorkspaceCollection': """Initialize a WorkspaceCollection object from a json dictionary.""" args = {} - valid_keys = ['workspaces', 'pagination'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WorkspaceCollection: ' - + ', '.join(bad_keys)) if 'workspaces' in _dict: args['workspaces'] = [ - Workspace._from_dict(x) for x in (_dict.get('workspaces')) + Workspace.from_dict(x) for x in _dict.get('workspaces') ] else: raise ValueError( 'Required property \'workspaces\' not present in WorkspaceCollection JSON' ) if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) else: raise ValueError( 'Required property \'pagination\' not present in WorkspaceCollection JSON' @@ -9566,9 +9295,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'workspaces') and self.workspaces is not None: - _dict['workspaces'] = [x._to_dict() for x in self.workspaces] + _dict['workspaces'] = [x.to_dict() for x in self.workspaces] if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -9577,7 +9306,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WorkspaceCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WorkspaceCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9657,22 +9386,12 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': """Initialize a WorkspaceSystemSettings object from a json dictionary.""" args = {} - valid_keys = [ - 'tooling', 'disambiguation', 'human_agent_assist', - 'spelling_suggestions', 'spelling_auto_correct', 'system_entities', - 'off_topic' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettings: ' - + ', '.join(bad_keys)) if 'tooling' in _dict: - args['tooling'] = WorkspaceSystemSettingsTooling._from_dict( + args['tooling'] = WorkspaceSystemSettingsTooling.from_dict( _dict.get('tooling')) if 'disambiguation' in _dict: args[ - 'disambiguation'] = WorkspaceSystemSettingsDisambiguation._from_dict( + 'disambiguation'] = WorkspaceSystemSettingsDisambiguation.from_dict( _dict.get('disambiguation')) if 'human_agent_assist' in _dict: args['human_agent_assist'] = _dict.get('human_agent_assist') @@ -9682,10 +9401,10 @@ def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') if 'system_entities' in _dict: args[ - 'system_entities'] = WorkspaceSystemSettingsSystemEntities._from_dict( + 'system_entities'] = WorkspaceSystemSettingsSystemEntities.from_dict( _dict.get('system_entities')) if 'off_topic' in _dict: - args['off_topic'] = WorkspaceSystemSettingsOffTopic._from_dict( + args['off_topic'] = WorkspaceSystemSettingsOffTopic.from_dict( _dict.get('off_topic')) return cls(**args) @@ -9698,9 +9417,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tooling') and self.tooling is not None: - _dict['tooling'] = self.tooling._to_dict() + _dict['tooling'] = self.tooling.to_dict() if hasattr(self, 'disambiguation') and self.disambiguation is not None: - _dict['disambiguation'] = self.disambiguation._to_dict() + _dict['disambiguation'] = self.disambiguation.to_dict() if hasattr( self, 'human_agent_assist') and self.human_agent_assist is not None: @@ -9713,9 +9432,9 @@ def to_dict(self) -> Dict: _dict['spelling_auto_correct'] = self.spelling_auto_correct if hasattr(self, 'system_entities') and self.system_entities is not None: - _dict['system_entities'] = self.system_entities._to_dict() + _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() + _dict['off_topic'] = self.off_topic.to_dict() return _dict def _to_dict(self): @@ -9724,7 +9443,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WorkspaceSystemSettings object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WorkspaceSystemSettings') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9802,15 +9521,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsDisambiguation': """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" args = {} - valid_keys = [ - 'prompt', 'none_of_the_above_prompt', 'enabled', 'sensitivity', - 'randomize', 'max_suggestions', 'suggestion_text_policy' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsDisambiguation: ' - + ', '.join(bad_keys)) if 'prompt' in _dict: args['prompt'] = _dict.get('prompt') if 'none_of_the_above_prompt' in _dict: @@ -9861,7 +9571,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WorkspaceSystemSettingsDisambiguation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WorkspaceSystemSettingsDisambiguation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9873,14 +9583,14 @@ def __ne__(self, other: 'WorkspaceSystemSettingsDisambiguation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class SensitivityEnum(Enum): + class SensitivityEnum(str, Enum): """ The sensitivity of the disambiguation feature to intent detection conflicts. Set to **high** if you want the disambiguation feature to be triggered more often. This can be useful for testing or demonstration purposes. """ - AUTO = "auto" - HIGH = "high" + AUTO = 'auto' + HIGH = 'high' class WorkspaceSystemSettingsOffTopic(): @@ -9904,12 +9614,6 @@ def __init__(self, *, enabled: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsOffTopic': """Initialize a WorkspaceSystemSettingsOffTopic 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 WorkspaceSystemSettingsOffTopic: ' - + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') return cls(**args) @@ -9932,7 +9636,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WorkspaceSystemSettingsOffTopic object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WorkspaceSystemSettingsOffTopic') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9966,12 +9670,6 @@ def __init__(self, *, enabled: bool = None) -> None: 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) @@ -9994,7 +9692,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WorkspaceSystemSettingsSystemEntities object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WorkspaceSystemSettingsSystemEntities') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -10028,12 +9726,6 @@ def __init__(self, *, store_generic_responses: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsTooling': """Initialize a WorkspaceSystemSettingsTooling object from a json dictionary.""" args = {} - valid_keys = ['store_generic_responses'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WorkspaceSystemSettingsTooling: ' - + ', '.join(bad_keys)) if 'store_generic_responses' in _dict: args['store_generic_responses'] = _dict.get( 'store_generic_responses') @@ -10058,7 +9750,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WorkspaceSystemSettingsTooling object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WorkspaceSystemSettingsTooling') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -10118,6 +9810,7 @@ def __init__( Routing or other contextual information to be used by target service desk systems. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.message_to_human_agent = message_to_human_agent self.agent_available = agent_available @@ -10130,15 +9823,6 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object from a json dictionary.""" args = {} - valid_keys = [ - 'response_type', 'message_to_human_agent', 'agent_available', - 'agent_unavailable', 'transfer_info' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -10153,7 +9837,7 @@ def from_dict( args['agent_unavailable'] = _dict.get('agent_unavailable') if 'transfer_info' in _dict: args[ - 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo._from_dict( + 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( _dict.get('transfer_info')) return cls(**args) @@ -10177,7 +9861,7 @@ def to_dict(self) -> Dict: 'agent_unavailable') and self.agent_unavailable is not None: _dict['agent_unavailable'] = self.agent_unavailable if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info._to_dict() + _dict['transfer_info'] = self.transfer_info.to_dict() return _dict def _to_dict(self): @@ -10186,7 +9870,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, @@ -10204,12 +9888,12 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - CONNECT_TO_AGENT = "connect_to_agent" + CONNECT_TO_AGENT = 'connect_to_agent' class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage( @@ -10242,6 +9926,7 @@ def __init__(self, :param str description: (optional) An optional description to show with the response. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.source = source self.title = title @@ -10253,12 +9938,6 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object from a json dictionary.""" args = {} - valid_keys = ['response_type', 'source', 'title', 'description'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -10301,7 +9980,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage' @@ -10317,12 +9996,12 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - IMAGE = "image" + IMAGE = 'image' class DialogNodeOutputGenericDialogNodeOutputResponseTypeOption( @@ -10364,6 +10043,7 @@ def __init__(self, :param str preference: (optional) The preferred type of control to display, if supported by the channel. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.title = title self.description = description @@ -10376,14 +10056,6 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object from a json dictionary.""" args = {} - valid_keys = [ - 'response_type', 'title', 'description', 'preference', 'options' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypeOption: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -10402,8 +10074,8 @@ def from_dict( args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ - DialogNodeOutputOptionsElement._from_dict(x) - for x in (_dict.get('options')) + DialogNodeOutputOptionsElement.from_dict(x) + for x in _dict.get('options') ] else: raise ValueError( @@ -10428,7 +10100,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x._to_dict() for x in self.options] + _dict['options'] = [x.to_dict() for x in self.options] return _dict def _to_dict(self): @@ -10437,7 +10109,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption' @@ -10453,19 +10125,19 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - OPTION = "option" + OPTION = 'option' - class PreferenceEnum(Enum): + class PreferenceEnum(str, Enum): """ The preferred type of control to display, if supported by the channel. """ - DROPDOWN = "dropdown" - BUTTON = "button" + DROPDOWN = 'dropdown' + BUTTON = 'button' class DialogNodeOutputGenericDialogNodeOutputResponseTypePause( @@ -10497,6 +10169,7 @@ def __init__(self, :param bool typing: (optional) Whether to send a "user is typing" event during the pause. Ignored if the channel does not support this event. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.time = time self.typing = typing @@ -10507,12 +10180,6 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypePause object from a json dictionary.""" args = {} - valid_keys = ['response_type', 'time', 'typing'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypePause: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -10551,7 +10218,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypePause object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause' @@ -10567,12 +10234,12 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - PAUSE = "pause" + PAUSE = 'pause' class DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill( @@ -10625,6 +10292,7 @@ def __init__(self, :param str discovery_version: (optional) The version of the Discovery service API to use for the query. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.query = query self.query_type = query_type @@ -10637,15 +10305,6 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object from a json dictionary.""" args = {} - valid_keys = [ - 'response_type', 'query', 'query_type', 'filter', - 'discovery_version' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -10697,7 +10356,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, @@ -10715,20 +10374,20 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The **search_skill** response type is used only by the v2 runtime API. """ - SEARCH_SKILL = "search_skill" + SEARCH_SKILL = 'search_skill' - class QueryTypeEnum(Enum): + class QueryTypeEnum(str, Enum): """ The type of the search query. """ - NATURAL_LANGUAGE = "natural_language" - DISCOVERY_QUERY_LANGUAGE = "discovery_query_language" + NATURAL_LANGUAGE = 'natural_language' + DISCOVERY_QUERY_LANGUAGE = 'discovery_query_language' class DialogNodeOutputGenericDialogNodeOutputResponseTypeText( @@ -10765,6 +10424,7 @@ def __init__(self, :param str delimiter: (optional) The delimiter to use as a separator between responses when `selection_policy`=`multiline`. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.values = values self.selection_policy = selection_policy @@ -10776,14 +10436,6 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeText object from a json dictionary.""" args = {} - valid_keys = [ - 'response_type', 'values', 'selection_policy', 'delimiter' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputGenericDialogNodeOutputResponseTypeText: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -10792,8 +10444,8 @@ def from_dict( ) if 'values' in _dict: args['values'] = [ - DialogNodeOutputTextValuesElement._from_dict(x) - for x in (_dict.get('values')) + DialogNodeOutputTextValuesElement.from_dict(x) + for x in _dict.get('values') ] else: raise ValueError( @@ -10816,7 +10468,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'response_type') and self.response_type is not None: _dict['response_type'] = self.response_type if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x._to_dict() for x in self.values] + _dict['values'] = [x.to_dict() for x in self.values] if hasattr(self, 'selection_policy') and self.selection_policy is not None: _dict['selection_policy'] = self.selection_policy @@ -10830,7 +10482,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeText object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText' @@ -10846,20 +10498,20 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - TEXT = "text" + TEXT = 'text' - class SelectionPolicyEnum(Enum): + class SelectionPolicyEnum(str, Enum): """ How a response is selected from the list, if more than one response is specified. """ - SEQUENTIAL = "sequential" - RANDOM = "random" - MULTILINE = "multiline" + SEQUENTIAL = 'sequential' + RANDOM = 'random' + MULTILINE = 'multiline' class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( @@ -10922,6 +10574,7 @@ def __init__( **topic** property is taken from. The **topic** property is populated using the value of the dialog node's **title** property. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.message_to_human_agent = message_to_human_agent self.agent_available = agent_available @@ -10936,15 +10589,6 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent': """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" args = {} - valid_keys = [ - 'response_type', 'message_to_human_agent', 'agent_available', - 'agent_unavailable', 'transfer_info', 'topic', 'dialog_node' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -10959,7 +10603,7 @@ def from_dict( args['agent_unavailable'] = _dict.get('agent_unavailable') if 'transfer_info' in _dict: args[ - 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo._from_dict( + 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( _dict.get('transfer_info')) if 'topic' in _dict: args['topic'] = _dict.get('topic') @@ -10987,7 +10631,7 @@ def to_dict(self) -> Dict: 'agent_unavailable') and self.agent_unavailable is not None: _dict['agent_unavailable'] = self.agent_unavailable if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info._to_dict() + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'topic') and self.topic is not None: _dict['topic'] = self.topic if hasattr(self, 'dialog_node') and self.dialog_node is not None: @@ -11000,7 +10644,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, other: 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' @@ -11016,12 +10660,12 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - CONNECT_TO_AGENT = "connect_to_agent" + CONNECT_TO_AGENT = 'connect_to_agent' class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): @@ -11054,6 +10698,7 @@ def __init__(self, :param str description: (optional) The description to show with the the response. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.source = source self.title = title @@ -11065,12 +10710,6 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeImage': """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object from a json dictionary.""" args = {} - valid_keys = ['response_type', 'source', 'title', 'description'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeImage: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -11113,7 +10752,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeImage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeResponseGenericRuntimeResponseTypeImage') -> bool: @@ -11127,12 +10766,12 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - IMAGE = "image" + IMAGE = 'image' class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): @@ -11169,6 +10808,7 @@ def __init__(self, response. :param str preference: (optional) The preferred type of control to display. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.title = title self.description = description @@ -11181,14 +10821,6 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeOption': """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object from a json dictionary.""" args = {} - valid_keys = [ - 'response_type', 'title', 'description', 'preference', 'options' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeOption: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -11207,8 +10839,8 @@ def from_dict( args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ - DialogNodeOutputOptionsElement._from_dict(x) - for x in (_dict.get('options')) + DialogNodeOutputOptionsElement.from_dict(x) + for x in _dict.get('options') ] else: raise ValueError( @@ -11233,7 +10865,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x._to_dict() for x in self.options] + _dict['options'] = [x.to_dict() for x in self.options] return _dict def _to_dict(self): @@ -11242,7 +10874,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeOption object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, @@ -11258,19 +10890,19 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - OPTION = "option" + OPTION = 'option' - class PreferenceEnum(Enum): + class PreferenceEnum(str, Enum): """ The preferred type of control to display. """ - DROPDOWN = "dropdown" - BUTTON = "button" + DROPDOWN = 'dropdown' + BUTTON = 'button' class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): @@ -11299,6 +10931,7 @@ def __init__(self, :param bool typing: (optional) Whether to send a "user is typing" event during the pause. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.time = time self.typing = typing @@ -11309,12 +10942,6 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypePause': """Initialize a RuntimeResponseGenericRuntimeResponseTypePause object from a json dictionary.""" args = {} - valid_keys = ['response_type', 'time', 'typing'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypePause: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -11353,7 +10980,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypePause object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeResponseGenericRuntimeResponseTypePause') -> bool: @@ -11367,12 +10994,12 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - PAUSE = "pause" + PAUSE = 'pause' class RuntimeResponseGenericRuntimeResponseTypeSuggestion( @@ -11400,6 +11027,7 @@ def __init__(self, response_type: str, title: str, :param List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.title = title self.suggestions = suggestions @@ -11410,12 +11038,6 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeSuggestion': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object from a json dictionary.""" args = {} - valid_keys = ['response_type', 'title', 'suggestions'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeSuggestion: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -11430,8 +11052,7 @@ def from_dict( ) if 'suggestions' in _dict: args['suggestions'] = [ - DialogSuggestion._from_dict(x) - for x in (_dict.get('suggestions')) + DialogSuggestion.from_dict(x) for x in _dict.get('suggestions') ] else: raise ValueError( @@ -11452,7 +11073,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x._to_dict() for x in self.suggestions] + _dict['suggestions'] = [x.to_dict() for x in self.suggestions] return _dict def _to_dict(self): @@ -11461,7 +11082,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeSuggestion object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, other: 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' @@ -11477,12 +11098,12 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - SUGGESTION = "suggestion" + SUGGESTION = 'suggestion' class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): @@ -11503,6 +11124,7 @@ def __init__(self, response_type: str, text: str) -> None: channel. :param str text: The text of the response. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.text = text @@ -11512,12 +11134,6 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeText': """Initialize a RuntimeResponseGenericRuntimeResponseTypeText object from a json dictionary.""" args = {} - valid_keys = ['response_type', 'text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeText: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -11552,7 +11168,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeText object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeResponseGenericRuntimeResponseTypeText') -> bool: @@ -11566,9 +11182,9 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - TEXT = "text" + TEXT = 'text' diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 411ac37b0..39d99dabf 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -21,16 +23,17 @@ input to an assistant and receive a response. """ +from enum import Enum +from typing import Dict, List import json +import sys + +from ibm_cloud_sdk_core import BaseService, DetailedResponse from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers -from enum import Enum -from ibm_cloud_sdk_core import BaseService -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 -import sys +from ibm_cloud_sdk_core.utils import convert_model + +from .common import get_sdk_headers ############################################################################## # Service @@ -52,27 +55,21 @@ def __init__( """ Construct a new client for the Assistant service. - :param str version: The API version date to use with the service, in - "YYYY-MM-DD" format. Whenever the API is changed in a backwards - incompatible way, a new minor version of the API is released. - The service uses the API version for the date you specify, or - the most recent version before that date. Note that you should - not programmatically specify the current date at runtime, in - case the API has been updated since your application's release. - Instead, specify a version date that is compatible with your - application, and don't change it until your application is - ready for a later version. + :param str version: Release date of the API version you want to use. + Specify dates in YYYY-MM-DD format. The current version is `2020-04-01`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + if version is None: + raise ValueError('version must be provided') + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.version = version self.configure_service(service_name) @@ -80,7 +77,7 @@ def __init__( # Sessions ######################### - def create_session(self, assistant_id: str, **kwargs) -> 'DetailedResponse': + def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: """ Create a session. @@ -98,15 +95,12 @@ def create_session(self, assistant_id: str, **kwargs) -> 'DetailedResponse': **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. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `SessionResponse` object """ if assistant_id is None: raise ValueError('assistant_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='V2', operation_id='create_session') @@ -114,8 +108,14 @@ def create_session(self, assistant_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v2/assistants/{0}/sessions'.format( - *self._encode_path_vars(assistant_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/sessions'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -125,7 +125,7 @@ def create_session(self, assistant_id: str, **kwargs) -> 'DetailedResponse': return response def delete_session(self, assistant_id: str, session_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete session. @@ -149,10 +149,7 @@ def delete_session(self, assistant_id: str, session_id: str, raise ValueError('assistant_id must be provided') if session_id is None: raise ValueError('session_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='V2', operation_id='delete_session') @@ -160,8 +157,15 @@ def delete_session(self, assistant_id: str, session_id: str, params = {'version': self.version} - url = '/v2/assistants/{0}/sessions/{1}'.format( - *self._encode_path_vars(assistant_id, session_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id', 'session_id'] + path_param_values = self.encode_path_vars(assistant_id, session_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/sessions/{session_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -180,7 +184,7 @@ def message(self, *, input: 'MessageInput' = None, context: 'MessageContext' = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Send user input to assistant (stateful). @@ -205,7 +209,7 @@ def message(self, cannot exceed 100KB. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `MessageResponse` object """ if assistant_id is None: @@ -213,13 +217,10 @@ def message(self, if session_id is None: raise ValueError('session_id must be provided') if input is not None: - input = self._convert_model(input) + input = convert_model(input) if context is not None: - context = self._convert_model(context) - + context = convert_model(context) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='message') @@ -228,9 +229,19 @@ def message(self, params = {'version': self.version} data = {'input': input, 'context': context} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v2/assistants/{0}/sessions/{1}/message'.format( - *self._encode_path_vars(assistant_id, session_id)) + path_param_keys = ['assistant_id', 'session_id'] + path_param_values = self.encode_path_vars(assistant_id, session_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/sessions/{session_id}/message'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -245,7 +256,7 @@ def message_stateless(self, *, input: 'MessageInputStateless' = None, context: 'MessageContextStateless' = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Send user input to assistant (stateless). @@ -269,19 +280,16 @@ def message_stateless(self, exceed 250KB. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `MessageResponseStateless` object """ if assistant_id is None: raise ValueError('assistant_id must be provided') if input is not None: - input = self._convert_model(input) + input = convert_model(input) if context is not None: - context = self._convert_model(context) - + context = convert_model(context) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='message_stateless') @@ -290,9 +298,18 @@ def message_stateless(self, params = {'version': self.version} data = {'input': input, 'context': context} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v2/assistants/{0}/message'.format( - *self._encode_path_vars(assistant_id)) + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/message'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -313,7 +330,7 @@ def list_logs(self, filter: str = None, page_limit: int = None, cursor: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List log events for an assistant. @@ -338,15 +355,12 @@ def list_logs(self, retrieve. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ if assistant_id is None: raise ValueError('assistant_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='V2', operation_id='list_logs') @@ -360,8 +374,14 @@ def list_logs(self, 'cursor': cursor } - url = '/v2/assistants/{0}/logs'.format( - *self._encode_path_vars(assistant_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/logs'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -374,8 +394,7 @@ def list_logs(self, # User data ######################### - def delete_user_data(self, customer_id: str, - **kwargs) -> 'DetailedResponse': + def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: """ Delete labeled data. @@ -397,10 +416,7 @@ def delete_user_data(self, customer_id: str, if customer_id is None: raise ValueError('customer_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='V2', operation_id='delete_user_data') @@ -408,6 +424,10 @@ def delete_user_data(self, customer_id: str, params = {'version': self.version, 'customer_id': customer_id} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v2/user_data' request = self.prepare_request(method='DELETE', url=url, @@ -425,7 +445,7 @@ def bulk_classify(self, skill_id: str, *, input: List['BulkClassifyUtterance'] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Identify intents and entities in multiple user utterances. @@ -442,17 +462,14 @@ def bulk_classify(self, utterances to classify. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object """ if skill_id is None: raise ValueError('skill_id must be provided') if input is not None: - input = [self._convert_model(x) for x in input] - + input = [convert_model(x) for x in input] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='bulk_classify') @@ -461,9 +478,19 @@ def bulk_classify(self, params = {'version': self.version} data = {'input': input} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v2/skills/{0}/workspace/bulk_classify'.format( - *self._encode_path_vars(skill_id)) + path_param_keys = ['skill_id'] + path_param_values = self.encode_path_vars(skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/skills/{skill_id}/workspace/bulk_classify'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -514,21 +541,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': """Initialize a BulkClassifyOutput object from a json dictionary.""" args = {} - valid_keys = ['input', 'entities', 'intents'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BulkClassifyOutput: ' - + ', '.join(bad_keys)) if 'input' in _dict: - args['input'] = BulkClassifyUtterance._from_dict(_dict.get('input')) + args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) if 'entities' in _dict: args['entities'] = [ - RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + RuntimeEntity.from_dict(x) for x in _dict.get('entities') ] if 'intents' in _dict: args['intents'] = [ - RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + RuntimeIntent.from_dict(x) for x in _dict.get('intents') ] return cls(**args) @@ -541,11 +562,11 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input._to_dict() + _dict['input'] = self.input.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] + _dict['intents'] = [x.to_dict() for x in self.intents] return _dict def _to_dict(self): @@ -554,7 +575,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this BulkClassifyOutput object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'BulkClassifyOutput') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -588,15 +609,9 @@ def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': """Initialize a BulkClassifyResponse object from a json dictionary.""" args = {} - valid_keys = ['output'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BulkClassifyResponse: ' - + ', '.join(bad_keys)) if 'output' in _dict: args['output'] = [ - BulkClassifyOutput._from_dict(x) for x in (_dict.get('output')) + BulkClassifyOutput.from_dict(x) for x in _dict.get('output') ] return cls(**args) @@ -609,7 +624,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'output') and self.output is not None: - _dict['output'] = [x._to_dict() for x in self.output] + _dict['output'] = [x.to_dict() for x in self.output] return _dict def _to_dict(self): @@ -618,7 +633,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this BulkClassifyResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'BulkClassifyResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -650,12 +665,6 @@ def __init__(self, text: str) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': """Initialize a BulkClassifyUtterance object from a json dictionary.""" args = {} - valid_keys = ['text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BulkClassifyUtterance: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -682,7 +691,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this BulkClassifyUtterance object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'BulkClassifyUtterance') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -719,12 +728,6 @@ def __init__(self, group: str, *, location: List[int] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CaptureGroup': """Initialize a CaptureGroup object from a json dictionary.""" args = {} - valid_keys = ['group', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CaptureGroup: ' - + ', '.join(bad_keys)) if 'group' in _dict: args['group'] = _dict.get('group') else: @@ -754,7 +757,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CaptureGroup object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CaptureGroup') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -789,12 +792,6 @@ def __init__(self, level: str, message: str) -> None: def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': """Initialize a DialogLogMessage object from a json dictionary.""" args = {} - valid_keys = ['level', 'message'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogLogMessage: ' - + ', '.join(bad_keys)) if 'level' in _dict: args['level'] = _dict.get('level') else: @@ -829,7 +826,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogLogMessage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogLogMessage') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -841,13 +838,13 @@ def __ne__(self, other: 'DialogLogMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LevelEnum(Enum): + class LevelEnum(str, Enum): """ The severity of the log message. """ - INFO = "info" - ERROR = "error" - WARN = "warn" + INFO = 'info' + ERROR = 'error' + WARN = 'warn' class DialogNodeAction(): @@ -893,14 +890,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': """Initialize a DialogNodeAction object from a json dictionary.""" args = {} - valid_keys = [ - 'name', 'type', 'parameters', 'result_variable', 'credentials' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeAction: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -948,7 +937,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeAction object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeAction') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -960,14 +949,14 @@ def __ne__(self, other: 'DialogNodeAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The type of action to invoke. """ - CLIENT = "client" - SERVER = "server" - WEB_ACTION = "web-action" - CLOUD_FUNCTION = "cloud-function" + CLIENT = 'client' + SERVER = 'server' + WEB_ACTION = 'web-action' + CLOUD_FUNCTION = 'cloud-function' class DialogNodeOutputConnectToAgentTransferInfo(): @@ -990,12 +979,6 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" args = {} - valid_keys = ['target'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputConnectToAgentTransferInfo: ' - + ', '.join(bad_keys)) if 'target' in _dict: args['target'] = _dict.get('target') return cls(**args) @@ -1018,7 +1001,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputConnectToAgentTransferInfo object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: @@ -1059,12 +1042,6 @@ def __init__(self, label: str, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} - valid_keys = ['label', 'value'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputOptionsElement: ' - + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') else: @@ -1072,7 +1049,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' ) if 'value' in _dict: - args['value'] = DialogNodeOutputOptionsElementValue._from_dict( + args['value'] = DialogNodeOutputOptionsElementValue.from_dict( _dict.get('value')) else: raise ValueError( @@ -1091,7 +1068,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value._to_dict() + _dict['value'] = self.value.to_dict() return _dict def _to_dict(self): @@ -1100,7 +1077,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputOptionsElement object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1135,14 +1112,8 @@ def __init__(self, *, input: 'MessageInput' = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} - valid_keys = ['input'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodeOutputOptionsElementValue: ' - + ', '.join(bad_keys)) if 'input' in _dict: - args['input'] = MessageInput._from_dict(_dict.get('input')) + args['input'] = MessageInput.from_dict(_dict.get('input')) return cls(**args) @classmethod @@ -1154,7 +1125,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input._to_dict() + _dict['input'] = self.input.to_dict() return _dict def _to_dict(self): @@ -1163,7 +1134,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodeOutputOptionsElementValue object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1208,12 +1179,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodesVisited': """Initialize a DialogNodesVisited object from a json dictionary.""" args = {} - valid_keys = ['dialog_node', 'title', 'conditions'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogNodesVisited: ' - + ', '.join(bad_keys)) if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') if 'title' in _dict: @@ -1244,7 +1209,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogNodesVisited object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogNodesVisited') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1296,12 +1261,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - valid_keys = ['label', 'value', 'output'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogSuggestion: ' - + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') else: @@ -1309,7 +1268,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': 'Required property \'label\' not present in DialogSuggestion JSON' ) if 'value' in _dict: - args['value'] = DialogSuggestionValue._from_dict(_dict.get('value')) + args['value'] = DialogSuggestionValue.from_dict(_dict.get('value')) else: raise ValueError( 'Required property \'value\' not present in DialogSuggestion JSON' @@ -1329,7 +1288,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value._to_dict() + _dict['value'] = self.value.to_dict() if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output return _dict @@ -1340,7 +1299,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogSuggestion object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogSuggestion') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1375,14 +1334,8 @@ def __init__(self, *, input: 'MessageInput' = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - valid_keys = ['input'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DialogSuggestionValue: ' - + ', '.join(bad_keys)) if 'input' in _dict: - args['input'] = MessageInput._from_dict(_dict.get('input')) + args['input'] = MessageInput.from_dict(_dict.get('input')) return cls(**args) @classmethod @@ -1394,7 +1347,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input._to_dict() + _dict['input'] = self.input.to_dict() return _dict def _to_dict(self): @@ -1403,7 +1356,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DialogSuggestionValue object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DialogSuggestionValue') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1490,28 +1443,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Log': """Initialize a Log object from a json dictionary.""" args = {} - valid_keys = [ - 'log_id', 'request', 'response', 'assistant_id', 'session_id', - 'skill_id', 'snapshot', 'request_timestamp', 'response_timestamp', - 'language', 'customer_id' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Log: ' + - ', '.join(bad_keys)) if 'log_id' in _dict: args['log_id'] = _dict.get('log_id') else: raise ValueError( 'Required property \'log_id\' not present in Log JSON') if 'request' in _dict: - args['request'] = MessageRequest._from_dict(_dict.get('request')) + args['request'] = MessageRequest.from_dict(_dict.get('request')) else: raise ValueError( 'Required property \'request\' not present in Log JSON') if 'response' in _dict: - args['response'] = MessageResponse._from_dict(_dict.get('response')) + args['response'] = MessageResponse.from_dict(_dict.get('response')) else: raise ValueError( 'Required property \'response\' not present in Log JSON') @@ -1567,9 +1510,9 @@ def to_dict(self) -> Dict: if hasattr(self, 'log_id') and self.log_id is not None: _dict['log_id'] = self.log_id if hasattr(self, 'request') and self.request is not None: - _dict['request'] = self.request._to_dict() + _dict['request'] = self.request.to_dict() if hasattr(self, 'response') and self.response is not None: - _dict['response'] = self.response._to_dict() + _dict['response'] = self.response.to_dict() if hasattr(self, 'assistant_id') and self.assistant_id is not None: _dict['assistant_id'] = self.assistant_id if hasattr(self, 'session_id') and self.session_id is not None: @@ -1597,7 +1540,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Log object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Log') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1633,19 +1576,13 @@ def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} - valid_keys = ['logs', 'pagination'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LogCollection: ' - + ', '.join(bad_keys)) if 'logs' in _dict: - args['logs'] = [Log._from_dict(x) for x in (_dict.get('logs'))] + args['logs'] = [Log.from_dict(x) for x in _dict.get('logs')] else: raise ValueError( 'Required property \'logs\' not present in LogCollection JSON') if 'pagination' in _dict: - args['pagination'] = LogPagination._from_dict( + args['pagination'] = LogPagination.from_dict( _dict.get('pagination')) else: raise ValueError( @@ -1662,9 +1599,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'logs') and self.logs is not None: - _dict['logs'] = [x._to_dict() for x in self.logs] + _dict['logs'] = [x.to_dict() for x in self.logs] if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -1673,7 +1610,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LogCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LogCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1718,12 +1655,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogPagination': """Initialize a LogPagination object from a json dictionary.""" args = {} - valid_keys = ['next_url', 'matched', 'next_cursor'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LogPagination: ' - + ', '.join(bad_keys)) if 'next_url' in _dict: args['next_url'] = _dict.get('next_url') if 'matched' in _dict: @@ -1754,7 +1685,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LogPagination object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LogPagination') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1773,8 +1704,8 @@ class MessageContext(): :attr MessageContextGlobal global_: (optional) Session context data that is shared by all skills used by the Assistant. - :attr MessageContextSkills skills: (optional) Information specific to particular - skills used by the assistant. + :attr dict skills: (optional) Information specific to particular skills used by + the assistant. **Note:** Currently, only a single child property is supported, containing variables that apply to the dialog skill used by the assistant. """ @@ -1782,14 +1713,14 @@ class MessageContext(): def __init__(self, *, global_: 'MessageContextGlobal' = None, - skills: 'MessageContextSkills' = None) -> None: + skills: dict = None) -> None: """ Initialize a MessageContext object. :param MessageContextGlobal global_: (optional) Session context data that is shared by all skills used by the Assistant. - :param MessageContextSkills skills: (optional) Information specific to - particular skills used by the assistant. + :param dict skills: (optional) Information specific to particular skills + used by the assistant. **Note:** Currently, only a single child property is supported, containing variables that apply to the dialog skill used by the assistant. """ @@ -1800,18 +1731,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContext': """Initialize a MessageContext object from a json dictionary.""" args = {} - valid_keys = ['global_', 'global', 'skills'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageContext: ' - + ', '.join(bad_keys)) if 'global' in _dict: - args['global_'] = MessageContextGlobal._from_dict( + args['global_'] = MessageContextGlobal.from_dict( _dict.get('global')) if 'skills' in _dict: - args['skills'] = MessageContextSkills._from_dict( - _dict.get('skills')) + args['skills'] = { + k: MessageContextSkill.from_dict(v) + for k, v in _dict.get('skills').items() + } return cls(**args) @classmethod @@ -1823,9 +1750,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'global_') and self.global_ is not None: - _dict['global'] = self.global_._to_dict() + _dict['global'] = self.global_.to_dict() if hasattr(self, 'skills') and self.skills is not None: - _dict['skills'] = self.skills._to_dict() + _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} return _dict def _to_dict(self): @@ -1834,7 +1761,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageContext object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageContext') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1865,7 +1792,6 @@ def __init__(self, :param MessageContextGlobalSystem system: (optional) Built-in system properties that apply to all skills used by the assistant. - :param str session_id: (optional) The session ID. """ self.system = system self.session_id = session_id @@ -1874,14 +1800,8 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} - valid_keys = ['system', 'session_id'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageContextGlobal: ' - + ', '.join(bad_keys)) if 'system' in _dict: - args['system'] = MessageContextGlobalSystem._from_dict( + args['system'] = MessageContextGlobalSystem.from_dict( _dict.get('system')) if 'session_id' in _dict: args['session_id'] = _dict.get('session_id') @@ -1896,9 +1816,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system._to_dict() - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and getattr(self, + 'session_id') is not None: + _dict['session_id'] = getattr(self, 'session_id') return _dict def _to_dict(self): @@ -1907,7 +1828,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageContextGlobal object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageContextGlobal') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1947,14 +1868,8 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': """Initialize a MessageContextGlobalStateless object from a json dictionary.""" args = {} - valid_keys = ['system', 'session_id'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageContextGlobalStateless: ' - + ', '.join(bad_keys)) if 'system' in _dict: - args['system'] = MessageContextGlobalSystem._from_dict( + args['system'] = MessageContextGlobalSystem.from_dict( _dict.get('system')) if 'session_id' in _dict: args['session_id'] = _dict.get('session_id') @@ -1969,7 +1884,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system._to_dict() + _dict['system'] = self.system.to_dict() if hasattr(self, 'session_id') and self.session_id is not None: _dict['session_id'] = self.session_id return _dict @@ -1980,7 +1895,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageContextGlobalStateless object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageContextGlobalStateless') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2077,14 +1992,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} - valid_keys = [ - 'timezone', 'user_id', 'turn_count', 'locale', 'reference_time' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageContextGlobalSystem: ' - + ', '.join(bad_keys)) if 'timezone' in _dict: args['timezone'] = _dict.get('timezone') if 'user_id' in _dict: @@ -2123,7 +2030,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageContextGlobalSystem object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2135,7 +2042,7 @@ def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LocaleEnum(Enum): + class LocaleEnum(str, 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 @@ -2144,21 +2051,21 @@ class LocaleEnum(Enum): 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" + 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(): @@ -2191,16 +2098,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': """Initialize a MessageContextSkill object from a json dictionary.""" args = {} - valid_keys = ['user_defined', 'system'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageContextSkill: ' - + ', '.join(bad_keys)) if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') if 'system' in _dict: - args['system'] = MessageContextSkillSystem._from_dict( + args['system'] = MessageContextSkillSystem.from_dict( _dict.get('system')) return cls(**args) @@ -2215,7 +2116,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system._to_dict() + _dict['system'] = self.system.to_dict() return _dict def _to_dict(self): @@ -2224,7 +2125,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageContextSkill object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageContextSkill') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2248,6 +2149,9 @@ class MessageContextSkillSystem(): state value to restore a paused conversation whose session is expired. """ + # The set of defined properties for the class + _properties = frozenset(['state']) + def __init__(self, *, state: str = None, **kwargs) -> None: """ Initialize a MessageContextSkillSystem object. @@ -2267,11 +2171,10 @@ def __init__(self, *, state: str = None, **kwargs) -> None: def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': """Initialize a MessageContextSkillSystem object from a json dictionary.""" args = {} - xtra = _dict.copy() if 'state' in _dict: args['state'] = _dict.get('state') - del xtra['state'] - args.update(xtra) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -2284,29 +2187,21 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'state') and self.state is not None: _dict['state'] = self.state - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = {'state'} - if not hasattr(self, '_additionalProperties'): - super(MessageContextSkillSystem, - self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(MessageContextSkillSystem, self).__setattr__(name, value) - def __str__(self) -> str: """Return a `str` version of this MessageContextSkillSystem object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageContextSkillSystem') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2319,82 +2214,14 @@ def __ne__(self, other: 'MessageContextSkillSystem') -> bool: return not self == other -class MessageContextSkills(): - """ - Information specific to particular skills used by the assistant. - **Note:** Currently, only a single child property is supported, containing variables - that apply to the dialog skill used by the assistant. - - """ - - def __init__(self, **kwargs) -> None: - """ - Initialize a MessageContextSkills object. - - :param **kwargs: (optional) Any additional properties. - """ - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': - """Initialize a MessageContextSkills object from a json dictionary.""" - args = {} - xtra = _dict.copy() - args.update(xtra) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MessageContextSkills 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, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __setattr__(self, name: str, value: object) -> None: - properties = {} - if not hasattr(self, '_additionalProperties'): - super(MessageContextSkills, - self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(MessageContextSkills, self).__setattr__(name, value) - - def __str__(self) -> str: - """Return a `str` version of this MessageContextSkills object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other: 'MessageContextSkills') -> 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: 'MessageContextSkills') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class MessageContextStateless(): """ MessageContextStateless. :attr MessageContextGlobalStateless global_: (optional) Session context data that is shared by all skills used by the Assistant. - :attr MessageContextSkills skills: (optional) Information specific to particular - skills used by the assistant. + :attr dict skills: (optional) Information specific to particular skills used by + the assistant. **Note:** Currently, only a single child property is supported, containing variables that apply to the dialog skill used by the assistant. """ @@ -2402,14 +2229,14 @@ class MessageContextStateless(): def __init__(self, *, global_: 'MessageContextGlobalStateless' = None, - skills: 'MessageContextSkills' = None) -> None: + skills: dict = None) -> None: """ Initialize a MessageContextStateless object. :param MessageContextGlobalStateless global_: (optional) Session context data that is shared by all skills used by the Assistant. - :param MessageContextSkills skills: (optional) Information specific to - particular skills used by the assistant. + :param dict skills: (optional) Information specific to particular skills + used by the assistant. **Note:** Currently, only a single child property is supported, containing variables that apply to the dialog skill used by the assistant. """ @@ -2420,18 +2247,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': """Initialize a MessageContextStateless object from a json dictionary.""" args = {} - valid_keys = ['global_', 'global', 'skills'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageContextStateless: ' - + ', '.join(bad_keys)) if 'global' in _dict: - args['global_'] = MessageContextGlobalStateless._from_dict( + args['global_'] = MessageContextGlobalStateless.from_dict( _dict.get('global')) if 'skills' in _dict: - args['skills'] = MessageContextSkills._from_dict( - _dict.get('skills')) + args['skills'] = { + k: MessageContextSkill.from_dict(v) + for k, v in _dict.get('skills').items() + } return cls(**args) @classmethod @@ -2443,9 +2266,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'global_') and self.global_ is not None: - _dict['global'] = self.global_._to_dict() + _dict['global'] = self.global_.to_dict() if hasattr(self, 'skills') and self.skills is not None: - _dict['skills'] = self.skills._to_dict() + _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} return _dict def _to_dict(self): @@ -2454,7 +2277,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageContextStateless object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageContextStateless') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2524,31 +2347,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} - valid_keys = [ - 'message_type', 'text', 'intents', 'entities', 'suggestion_id', - 'options' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageInput: ' - + ', '.join(bad_keys)) if 'message_type' in _dict: args['message_type'] = _dict.get('message_type') if 'text' in _dict: args['text'] = _dict.get('text') if 'intents' in _dict: args['intents'] = [ - RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + RuntimeIntent.from_dict(x) for x in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + RuntimeEntity.from_dict(x) for x in _dict.get('entities') ] if 'suggestion_id' in _dict: args['suggestion_id'] = _dict.get('suggestion_id') if 'options' in _dict: - args['options'] = MessageInputOptions._from_dict( + args['options'] = MessageInputOptions.from_dict( _dict.get('options')) return cls(**args) @@ -2565,13 +2379,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] + _dict['intents'] = [x.to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: _dict['suggestion_id'] = self.suggestion_id if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options._to_dict() + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -2580,7 +2394,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageInput object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageInput') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2592,11 +2406,11 @@ def __ne__(self, other: 'MessageInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(Enum): + class MessageTypeEnum(str, Enum): """ The type of user input. Currently, only text input is supported. """ - TEXT = "text" + TEXT = 'text' class MessageInputOptions(): @@ -2671,21 +2485,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': """Initialize a MessageInputOptions object from a json dictionary.""" args = {} - valid_keys = [ - 'restart', 'alternate_intents', 'spelling', 'debug', - 'return_context', 'export' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageInputOptions: ' - + ', '.join(bad_keys)) if 'restart' in _dict: args['restart'] = _dict.get('restart') if 'alternate_intents' in _dict: args['alternate_intents'] = _dict.get('alternate_intents') if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling._from_dict( + args['spelling'] = MessageInputOptionsSpelling.from_dict( _dict.get('spelling')) if 'debug' in _dict: args['debug'] = _dict.get('debug') @@ -2709,7 +2514,7 @@ def to_dict(self) -> Dict: 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling._to_dict() + _dict['spelling'] = self.spelling.to_dict() if hasattr(self, 'debug') and self.debug is not None: _dict['debug'] = self.debug if hasattr(self, 'return_context') and self.return_context is not None: @@ -2724,7 +2529,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageInputOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageInputOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2785,12 +2590,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" args = {} - valid_keys = ['suggestions', 'auto_correct'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageInputOptionsSpelling: ' - + ', '.join(bad_keys)) if 'suggestions' in _dict: args['suggestions'] = _dict.get('suggestions') if 'auto_correct' in _dict: @@ -2817,7 +2616,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageInputOptionsSpelling object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageInputOptionsSpelling') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2877,18 +2676,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': """Initialize a MessageInputOptionsStateless object from a json dictionary.""" args = {} - valid_keys = ['restart', 'alternate_intents', 'spelling', 'debug'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageInputOptionsStateless: ' - + ', '.join(bad_keys)) if 'restart' in _dict: args['restart'] = _dict.get('restart') if 'alternate_intents' in _dict: args['alternate_intents'] = _dict.get('alternate_intents') if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling._from_dict( + args['spelling'] = MessageInputOptionsSpelling.from_dict( _dict.get('spelling')) if 'debug' in _dict: args['debug'] = _dict.get('debug') @@ -2908,7 +2701,7 @@ def to_dict(self) -> Dict: 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling._to_dict() + _dict['spelling'] = self.spelling.to_dict() if hasattr(self, 'debug') and self.debug is not None: _dict['debug'] = self.debug return _dict @@ -2919,7 +2712,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageInputOptionsStateless object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageInputOptionsStateless') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2989,31 +2782,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': """Initialize a MessageInputStateless object from a json dictionary.""" args = {} - valid_keys = [ - 'message_type', 'text', 'intents', 'entities', 'suggestion_id', - 'options' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageInputStateless: ' - + ', '.join(bad_keys)) if 'message_type' in _dict: args['message_type'] = _dict.get('message_type') if 'text' in _dict: args['text'] = _dict.get('text') if 'intents' in _dict: args['intents'] = [ - RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + RuntimeIntent.from_dict(x) for x in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + RuntimeEntity.from_dict(x) for x in _dict.get('entities') ] if 'suggestion_id' in _dict: args['suggestion_id'] = _dict.get('suggestion_id') if 'options' in _dict: - args['options'] = MessageInputOptionsStateless._from_dict( + args['options'] = MessageInputOptionsStateless.from_dict( _dict.get('options')) return cls(**args) @@ -3030,13 +2814,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] + _dict['intents'] = [x.to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: _dict['suggestion_id'] = self.suggestion_id if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options._to_dict() + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -3045,7 +2829,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageInputStateless object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageInputStateless') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3057,11 +2841,11 @@ def __ne__(self, other: 'MessageInputStateless') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(Enum): + class MessageTypeEnum(str, Enum): """ The type of user input. Currently, only text input is supported. """ - TEXT = "text" + TEXT = 'text' class MessageOutput(): @@ -3128,38 +2912,29 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageOutput': """Initialize a MessageOutput object from a json dictionary.""" args = {} - valid_keys = [ - 'generic', 'intents', 'entities', 'actions', 'debug', - 'user_defined', 'spelling' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageOutput: ' - + ', '.join(bad_keys)) if 'generic' in _dict: args['generic'] = [ - RuntimeResponseGeneric._from_dict(x) - for x in (_dict.get('generic')) + RuntimeResponseGeneric.from_dict(x) + for x in _dict.get('generic') ] if 'intents' in _dict: args['intents'] = [ - RuntimeIntent._from_dict(x) for x in (_dict.get('intents')) + RuntimeIntent.from_dict(x) for x in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity._from_dict(x) for x in (_dict.get('entities')) + RuntimeEntity.from_dict(x) for x in _dict.get('entities') ] if 'actions' in _dict: args['actions'] = [ - DialogNodeAction._from_dict(x) for x in (_dict.get('actions')) + DialogNodeAction.from_dict(x) for x in _dict.get('actions') ] if 'debug' in _dict: - args['debug'] = MessageOutputDebug._from_dict(_dict.get('debug')) + args['debug'] = MessageOutputDebug.from_dict(_dict.get('debug')) if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') if 'spelling' in _dict: - args['spelling'] = MessageOutputSpelling._from_dict( + args['spelling'] = MessageOutputSpelling.from_dict( _dict.get('spelling')) return cls(**args) @@ -3172,19 +2947,19 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x._to_dict() for x in self.generic] + _dict['generic'] = [x.to_dict() for x in self.generic] if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x._to_dict() for x in self.intents] + _dict['intents'] = [x.to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'actions') and self.actions is not None: - _dict['actions'] = [x._to_dict() for x in self.actions] + _dict['actions'] = [x.to_dict() for x in self.actions] if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug._to_dict() + _dict['debug'] = self.debug.to_dict() if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling._to_dict() + _dict['spelling'] = self.spelling.to_dict() return _dict def _to_dict(self): @@ -3193,7 +2968,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageOutput object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageOutput') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3251,24 +3026,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': """Initialize a MessageOutputDebug object from a json dictionary.""" args = {} - valid_keys = [ - 'nodes_visited', 'log_messages', 'branch_exited', - 'branch_exited_reason' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageOutputDebug: ' - + ', '.join(bad_keys)) if 'nodes_visited' in _dict: args['nodes_visited'] = [ - DialogNodesVisited._from_dict(x) - for x in (_dict.get('nodes_visited')) + DialogNodesVisited.from_dict(x) + for x in _dict.get('nodes_visited') ] if 'log_messages' in _dict: args['log_messages'] = [ - DialogLogMessage._from_dict(x) - for x in (_dict.get('log_messages')) + DialogLogMessage.from_dict(x) for x in _dict.get('log_messages') ] if 'branch_exited' in _dict: args['branch_exited'] = _dict.get('branch_exited') @@ -3285,9 +3050,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: - _dict['nodes_visited'] = [x._to_dict() for x in self.nodes_visited] + _dict['nodes_visited'] = [x.to_dict() for x in self.nodes_visited] if hasattr(self, 'log_messages') and self.log_messages is not None: - _dict['log_messages'] = [x._to_dict() for x in self.log_messages] + _dict['log_messages'] = [x.to_dict() for x in self.log_messages] if hasattr(self, 'branch_exited') and self.branch_exited is not None: _dict['branch_exited'] = self.branch_exited if hasattr(self, 'branch_exited_reason' @@ -3301,7 +3066,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageOutputDebug object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageOutputDebug') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3313,13 +3078,13 @@ def __ne__(self, other: 'MessageOutputDebug') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class BranchExitedReasonEnum(Enum): + class BranchExitedReasonEnum(str, Enum): """ When `branch_exited` is set to `true` by the Assistant, the `branch_exited_reason` specifies whether the dialog completed by itself or got interrupted. """ - COMPLETED = "completed" - FALLBACK = "fallback" + COMPLETED = 'completed' + FALLBACK = 'fallback' class MessageOutputSpelling(): @@ -3362,12 +3127,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': """Initialize a MessageOutputSpelling object from a json dictionary.""" args = {} - valid_keys = ['text', 'original_text', 'suggested_text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageOutputSpelling: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'original_text' in _dict: @@ -3398,7 +3157,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageOutputSpelling object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageOutputSpelling') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3448,16 +3207,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageRequest': """Initialize a MessageRequest object from a json dictionary.""" args = {} - valid_keys = ['input', 'context'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageRequest: ' - + ', '.join(bad_keys)) if 'input' in _dict: - args['input'] = MessageInput._from_dict(_dict.get('input')) + args['input'] = MessageInput.from_dict(_dict.get('input')) if 'context' in _dict: - args['context'] = MessageContext._from_dict(_dict.get('context')) + args['context'] = MessageContext.from_dict(_dict.get('context')) return cls(**args) @classmethod @@ -3469,9 +3222,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input._to_dict() + _dict['input'] = self.input.to_dict() if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context._to_dict() + _dict['context'] = self.context.to_dict() return _dict def _to_dict(self): @@ -3480,7 +3233,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageRequest object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageRequest') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3530,20 +3283,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageResponse': """Initialize a MessageResponse object from a json dictionary.""" args = {} - valid_keys = ['output', 'context'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageResponse: ' - + ', '.join(bad_keys)) if 'output' in _dict: - args['output'] = MessageOutput._from_dict(_dict.get('output')) + args['output'] = MessageOutput.from_dict(_dict.get('output')) else: raise ValueError( 'Required property \'output\' not present in MessageResponse JSON' ) if 'context' in _dict: - args['context'] = MessageContext._from_dict(_dict.get('context')) + args['context'] = MessageContext.from_dict(_dict.get('context')) return cls(**args) @classmethod @@ -3555,9 +3302,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output._to_dict() + _dict['output'] = self.output.to_dict() if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context._to_dict() + _dict['context'] = self.context.to_dict() return _dict def _to_dict(self): @@ -3566,7 +3313,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3610,20 +3357,14 @@ def __init__(self, output: 'MessageOutput', def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': """Initialize a MessageResponseStateless object from a json dictionary.""" args = {} - valid_keys = ['output', 'context'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MessageResponseStateless: ' - + ', '.join(bad_keys)) if 'output' in _dict: - args['output'] = MessageOutput._from_dict(_dict.get('output')) + args['output'] = MessageOutput.from_dict(_dict.get('output')) else: raise ValueError( 'Required property \'output\' not present in MessageResponseStateless JSON' ) if 'context' in _dict: - args['context'] = MessageContextStateless._from_dict( + args['context'] = MessageContextStateless.from_dict( _dict.get('context')) else: raise ValueError( @@ -3640,9 +3381,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output._to_dict() + _dict['output'] = self.output.to_dict() if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context._to_dict() + _dict['context'] = self.context.to_dict() return _dict def _to_dict(self): @@ -3651,7 +3392,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MessageResponseStateless object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MessageResponseStateless') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3753,15 +3494,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} - valid_keys = [ - 'entity', 'location', 'value', 'confidence', 'metadata', 'groups', - 'interpretation', 'alternatives', 'role' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeEntity: ' - + ', '.join(bad_keys)) if 'entity' in _dict: args['entity'] = _dict.get('entity') else: @@ -3785,18 +3517,18 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': args['metadata'] = _dict.get('metadata') if 'groups' in _dict: args['groups'] = [ - CaptureGroup._from_dict(x) for x in (_dict.get('groups')) + CaptureGroup.from_dict(x) for x in _dict.get('groups') ] if 'interpretation' in _dict: - args['interpretation'] = RuntimeEntityInterpretation._from_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')) + RuntimeEntityAlternative.from_dict(x) + for x in _dict.get('alternatives') ] if 'role' in _dict: - args['role'] = RuntimeEntityRole._from_dict(_dict.get('role')) + args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) return cls(**args) @classmethod @@ -3818,13 +3550,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'groups') and self.groups is not None: - _dict['groups'] = [x._to_dict() for x in self.groups] + _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() + _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] + _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() + _dict['role'] = self.role.to_dict() return _dict def _to_dict(self): @@ -3833,7 +3565,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeEntity object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeEntity') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3872,12 +3604,6 @@ def __init__(self, *, value: str = None, confidence: float = None) -> None: 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: @@ -3904,7 +3630,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeEntityAlternative object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4127,21 +3853,6 @@ def __init__(self, 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: @@ -4271,7 +3982,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeEntityInterpretation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4283,22 +3994,22 @@ def __ne__(self, other: 'RuntimeEntityInterpretation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class GranularityEnum(Enum): + class GranularityEnum(str, 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" + DAY = 'day' + FORTNIGHT = 'fortnight' + HOUR = 'hour' + INSTANT = 'instant' + MINUTE = 'minute' + MONTH = 'month' + QUARTER = 'quarter' + SECOND = 'second' + WEEK = 'week' + WEEKEND = 'weekend' + YEAR = 'year' class RuntimeEntityRole(): @@ -4322,12 +4033,6 @@ def __init__(self, *, type: str = None) -> None: 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) @@ -4350,7 +4055,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeEntityRole object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeEntityRole') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4362,16 +4067,16 @@ def __ne__(self, other: 'RuntimeEntityRole') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, 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" + 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(): @@ -4398,12 +4103,6 @@ def __init__(self, intent: str, confidence: float) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': """Initialize a RuntimeIntent object from a json dictionary.""" args = {} - valid_keys = ['intent', 'confidence'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeIntent: ' - + ', '.join(bad_keys)) if 'intent' in _dict: args['intent'] = _dict.get('intent') else: @@ -4438,7 +4137,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeIntent object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeIntent') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4480,16 +4179,18 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = "Cannot convert dictionary into an instance of base class '{0}'. The discriminator value should map to a valid subclass: {1}".format( - cls.__name__, ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeSearch' - ])) + msg = ( + "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeSearch' + ])) raise Exception(msg) @classmethod @@ -4587,21 +4288,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchResult': """Initialize a SearchResult object from a json dictionary.""" args = {} - valid_keys = [ - 'id', 'result_metadata', 'body', 'title', 'url', 'highlight' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SearchResult: ' - + ', '.join(bad_keys)) if 'id' in _dict: args['id'] = _dict.get('id') else: raise ValueError( 'Required property \'id\' not present in SearchResult JSON') if 'result_metadata' in _dict: - args['result_metadata'] = SearchResultMetadata._from_dict( + args['result_metadata'] = SearchResultMetadata.from_dict( _dict.get('result_metadata')) else: raise ValueError( @@ -4614,7 +4307,7 @@ def from_dict(cls, _dict: Dict) -> 'SearchResult': if 'url' in _dict: args['url'] = _dict.get('url') if 'highlight' in _dict: - args['highlight'] = SearchResultHighlight._from_dict( + args['highlight'] = SearchResultHighlight.from_dict( _dict.get('highlight')) return cls(**args) @@ -4630,7 +4323,7 @@ def to_dict(self) -> Dict: _dict['id'] = self.id if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata._to_dict() + _dict['result_metadata'] = self.result_metadata.to_dict() if hasattr(self, 'body') and self.body is not None: _dict['body'] = self.body if hasattr(self, 'title') and self.title is not None: @@ -4638,7 +4331,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight._to_dict() + _dict['highlight'] = self.highlight.to_dict() return _dict def _to_dict(self): @@ -4647,7 +4340,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SearchResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SearchResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4675,6 +4368,9 @@ class SearchResultHighlight(): from URLs in the search results, with query-matching substrings highlighted. """ + # The set of defined properties for the class + _properties = frozenset(['body', 'title', 'url']) + def __init__(self, *, body: List[str] = None, @@ -4705,17 +4401,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': """Initialize a SearchResultHighlight object from a json dictionary.""" args = {} - xtra = _dict.copy() if 'body' in _dict: args['body'] = _dict.get('body') - del xtra['body'] if 'title' in _dict: args['title'] = _dict.get('title') - del xtra['title'] if 'url' in _dict: args['url'] = _dict.get('url') - del xtra['url'] - args.update(xtra) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -4732,29 +4425,21 @@ def to_dict(self) -> Dict: _dict['title'] = self.title if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = {'body', 'title', 'url'} - if not hasattr(self, '_additionalProperties'): - super(SearchResultHighlight, - self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(SearchResultHighlight, self).__setattr__(name, value) - def __str__(self) -> str: """Return a `str` version of this SearchResultHighlight object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SearchResultHighlight') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4800,12 +4485,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': """Initialize a SearchResultMetadata object from a json dictionary.""" args = {} - valid_keys = ['confidence', 'score'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SearchResultMetadata: ' - + ', '.join(bad_keys)) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') if 'score' in _dict: @@ -4832,7 +4511,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SearchResultMetadata object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SearchResultMetadata') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4864,12 +4543,6 @@ def __init__(self, session_id: str) -> None: def from_dict(cls, _dict: Dict) -> 'SessionResponse': """Initialize a SessionResponse object from a json dictionary.""" args = {} - valid_keys = ['session_id'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SessionResponse: ' - + ', '.join(bad_keys)) if 'session_id' in _dict: args['session_id'] = _dict.get('session_id') else: @@ -4896,7 +4569,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SessionResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SessionResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4962,6 +4635,7 @@ def __init__( conversation, derived from the **title** property of the relevant node or the **topic** property of the dialog node response. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.message_to_human_agent = message_to_human_agent self.agent_available = agent_available @@ -4975,15 +4649,6 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent': """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" args = {} - valid_keys = [ - 'response_type', 'message_to_human_agent', 'agent_available', - 'agent_unavailable', 'transfer_info', 'topic' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -4998,7 +4663,7 @@ def from_dict( args['agent_unavailable'] = _dict.get('agent_unavailable') if 'transfer_info' in _dict: args[ - 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo._from_dict( + 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( _dict.get('transfer_info')) if 'topic' in _dict: args['topic'] = _dict.get('topic') @@ -5024,7 +4689,7 @@ def to_dict(self) -> Dict: 'agent_unavailable') and self.agent_unavailable is not None: _dict['agent_unavailable'] = self.agent_unavailable if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info._to_dict() + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'topic') and self.topic is not None: _dict['topic'] = self.topic return _dict @@ -5035,7 +4700,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, other: 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' @@ -5051,12 +4716,12 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - CONNECT_TO_AGENT = "connect_to_agent" + CONNECT_TO_AGENT = 'connect_to_agent' class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): @@ -5087,6 +4752,7 @@ def __init__(self, :param str description: (optional) The description to show with the the response. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.source = source self.title = title @@ -5098,12 +4764,6 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeImage': """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object from a json dictionary.""" args = {} - valid_keys = ['response_type', 'source', 'title', 'description'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeImage: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -5146,7 +4806,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeImage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeResponseGenericRuntimeResponseTypeImage') -> bool: @@ -5160,12 +4820,12 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - IMAGE = "image" + IMAGE = 'image' class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): @@ -5202,6 +4862,7 @@ def __init__(self, response. :param str preference: (optional) The preferred type of control to display. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.title = title self.description = description @@ -5214,14 +4875,6 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeOption': """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object from a json dictionary.""" args = {} - valid_keys = [ - 'response_type', 'title', 'description', 'preference', 'options' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeOption: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -5240,8 +4893,8 @@ def from_dict( args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ - DialogNodeOutputOptionsElement._from_dict(x) - for x in (_dict.get('options')) + DialogNodeOutputOptionsElement.from_dict(x) + for x in _dict.get('options') ] else: raise ValueError( @@ -5266,7 +4919,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x._to_dict() for x in self.options] + _dict['options'] = [x.to_dict() for x in self.options] return _dict def _to_dict(self): @@ -5275,7 +4928,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeOption object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, @@ -5291,19 +4944,19 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - OPTION = "option" + OPTION = 'option' - class PreferenceEnum(Enum): + class PreferenceEnum(str, Enum): """ The preferred type of control to display. """ - DROPDOWN = "dropdown" - BUTTON = "button" + DROPDOWN = 'dropdown' + BUTTON = 'button' class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): @@ -5332,6 +4985,7 @@ def __init__(self, :param bool typing: (optional) Whether to send a "user is typing" event during the pause. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.time = time self.typing = typing @@ -5342,12 +4996,6 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypePause': """Initialize a RuntimeResponseGenericRuntimeResponseTypePause object from a json dictionary.""" args = {} - valid_keys = ['response_type', 'time', 'typing'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypePause: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -5386,7 +5034,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypePause object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeResponseGenericRuntimeResponseTypePause') -> bool: @@ -5400,12 +5048,12 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - PAUSE = "pause" + PAUSE = 'pause' class RuntimeResponseGenericRuntimeResponseTypeSearch(RuntimeResponseGeneric): @@ -5440,6 +5088,7 @@ def __init__(self, response_type: str, header: str, contains additional search results that can be displayed to the user upon request. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.header = header self.primary_results = primary_results @@ -5451,14 +5100,6 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeSearch': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSearch object from a json dictionary.""" args = {} - valid_keys = [ - 'response_type', 'header', 'primary_results', 'additional_results' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeSearch: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -5473,8 +5114,7 @@ def from_dict( ) if 'primary_results' in _dict: args['primary_results'] = [ - SearchResult._from_dict(x) - for x in (_dict.get('primary_results')) + SearchResult.from_dict(x) for x in _dict.get('primary_results') ] else: raise ValueError( @@ -5482,8 +5122,8 @@ def from_dict( ) if 'additional_results' in _dict: args['additional_results'] = [ - SearchResult._from_dict(x) - for x in (_dict.get('additional_results')) + SearchResult.from_dict(x) + for x in _dict.get('additional_results') ] else: raise ValueError( @@ -5506,13 +5146,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'primary_results') and self.primary_results is not None: _dict['primary_results'] = [ - x._to_dict() for x in self.primary_results + x.to_dict() for x in self.primary_results ] if hasattr( self, 'additional_results') and self.additional_results is not None: _dict['additional_results'] = [ - x._to_dict() for x in self.additional_results + x.to_dict() for x in self.additional_results ] return _dict @@ -5522,7 +5162,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeSearch object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, @@ -5538,12 +5178,12 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - SEARCH = "search" + SEARCH = 'search' class RuntimeResponseGenericRuntimeResponseTypeSuggestion( @@ -5571,6 +5211,7 @@ def __init__(self, response_type: str, title: str, :param List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.title = title self.suggestions = suggestions @@ -5581,12 +5222,6 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeSuggestion': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object from a json dictionary.""" args = {} - valid_keys = ['response_type', 'title', 'suggestions'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeSuggestion: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -5601,8 +5236,7 @@ def from_dict( ) if 'suggestions' in _dict: args['suggestions'] = [ - DialogSuggestion._from_dict(x) - for x in (_dict.get('suggestions')) + DialogSuggestion.from_dict(x) for x in _dict.get('suggestions') ] else: raise ValueError( @@ -5623,7 +5257,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x._to_dict() for x in self.suggestions] + _dict['suggestions'] = [x.to_dict() for x in self.suggestions] return _dict def _to_dict(self): @@ -5632,7 +5266,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeSuggestion object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__( self, other: 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' @@ -5648,12 +5282,12 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - SUGGESTION = "suggestion" + SUGGESTION = 'suggestion' class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): @@ -5674,6 +5308,7 @@ def __init__(self, response_type: str, text: str) -> None: channel. :param str text: The text of the response. """ + # pylint: disable=super-init-not-called self.response_type = response_type self.text = text @@ -5683,12 +5318,6 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeText': """Initialize a RuntimeResponseGenericRuntimeResponseTypeText object from a json dictionary.""" args = {} - valid_keys = ['response_type', 'text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RuntimeResponseGenericRuntimeResponseTypeText: ' - + ', '.join(bad_keys)) if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: @@ -5723,7 +5352,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeText object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RuntimeResponseGenericRuntimeResponseTypeText') -> bool: @@ -5737,9 +5366,9 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(Enum): + class ResponseTypeEnum(str, Enum): """ The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - TEXT = "text" + TEXT = 'text' diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index dd5823ea1..1a77ebed3 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -13,23 +13,24 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ IBM Watson™ Compare and Comply analyzes governing documents to provide details about critical aspects of the documents. """ -import json -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers 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 typing import BinaryIO, Dict, List +import json + +from ibm_cloud_sdk_core import BaseService, DetailedResponse +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator 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 ibm_cloud_sdk_core.utils import convert_model, datetime_to_string, string_to_datetime + +from .common import get_sdk_headers ############################################################################## # Service @@ -51,27 +52,21 @@ def __init__( """ Construct a new client for the Compare Comply service. - :param str version: The API version date to use with the service, in - "YYYY-MM-DD" format. Whenever the API is changed in a backwards - incompatible way, a new minor version of the API is released. - The service uses the API version for the date you specify, or - the most recent version before that date. Note that you should - not programmatically specify the current date at runtime, in - case the API has been updated since your application's release. - Instead, specify a version date that is compatible with your - application, and don't change it until your application is - ready for a later version. + :param str version: Release date of the version of the API you want to use. + Specify dates in YYYY-MM-DD format. The current version is `2018-10-15`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + if version is None: + raise ValueError('version must be provided') + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.version = version self.configure_service(service_name) @@ -84,13 +79,13 @@ def convert_to_html(self, *, file_content_type: str = None, model: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Convert document to HTML. Converts a document to HTML. - :param TextIO file: The document to convert. + :param BinaryIO file: The document to convert. :param str file_content_type: (optional) The content type of file. :param str model: (optional) The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, @@ -99,15 +94,12 @@ def convert_to_html(self, the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `HTMLReturn` object """ if file is None: raise ValueError('file 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='V1', operation_id='convert_to_html') @@ -119,6 +111,10 @@ def convert_to_html(self, form_data.append(('file', (None, file, file_content_type or 'application/octet-stream'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/html_conversion' request = self.prepare_request(method='POST', url=url, @@ -138,13 +134,13 @@ def classify_elements(self, *, file_content_type: str = None, model: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Classify the elements of a document. Analyzes the structural and semantic elements of a document. - :param TextIO file: The document to classify. + :param BinaryIO file: The document to classify. :param str file_content_type: (optional) The content type of file. :param str model: (optional) The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, @@ -153,15 +149,12 @@ def classify_elements(self, the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ClassifyReturn` object """ if file is None: raise ValueError('file 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='V1', operation_id='classify_elements') @@ -173,6 +166,10 @@ def classify_elements(self, form_data.append(('file', (None, file, file_content_type or 'application/octet-stream'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/element_classification' request = self.prepare_request(method='POST', url=url, @@ -192,13 +189,13 @@ def extract_tables(self, *, file_content_type: str = None, model: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Extract a document's tables. Analyzes the tables in a document. - :param TextIO file: The document on which to run table extraction. + :param BinaryIO file: The document on which to run table extraction. :param str file_content_type: (optional) The content type of file. :param str model: (optional) The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, @@ -207,15 +204,12 @@ def extract_tables(self, the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TableReturn` object """ if file is None: raise ValueError('file 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='V1', operation_id='extract_tables') @@ -227,6 +221,10 @@ def extract_tables(self, form_data.append(('file', (None, file, file_content_type or 'application/octet-stream'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/tables' request = self.prepare_request(method='POST', url=url, @@ -250,14 +248,14 @@ def compare_documents(self, file_1_label: str = None, file_2_label: str = None, model: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Compare two documents. Compares two input documents. Documents must be in the same format. - :param TextIO file_1: The first document to compare. - :param TextIO file_2: The second document to compare. + :param BinaryIO file_1: The first document to compare. + :param BinaryIO file_2: The second document to compare. :param str file_1_content_type: (optional) The content type of file_1. :param str file_2_content_type: (optional) The content type of file_2. :param str file_1_label: (optional) A text label for the first document. @@ -269,17 +267,14 @@ def compare_documents(self, the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `CompareReturn` object """ if file_1 is None: raise ValueError('file_1 must be provided') if file_2 is None: raise ValueError('file_2 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='V1', operation_id='compare_documents') @@ -298,6 +293,10 @@ def compare_documents(self, form_data.append(('file_2', (None, file_2, file_2_content_type or 'application/octet-stream'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/comparison' request = self.prepare_request(method='POST', url=url, @@ -317,7 +316,7 @@ def add_feedback(self, *, user_id: str = None, comment: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add feedback. @@ -333,16 +332,13 @@ def add_feedback(self, feedback. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `FeedbackReturn` object """ if feedback_data is None: raise ValueError('feedback_data must be provided') - feedback_data = self._convert_model(feedback_data) - + feedback_data = convert_model(feedback_data) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='add_feedback') @@ -355,6 +351,13 @@ def add_feedback(self, 'user_id': user_id, 'comment': comment } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v1/feedback' request = self.prepare_request(method='POST', @@ -382,7 +385,7 @@ def list_feedback(self, cursor: str = None, sort: str = None, include_total: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List the feedback in a document. @@ -438,12 +441,10 @@ def list_feedback(self, called `total` that gives the total count of feedback created. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `FeedbackList` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='list_feedback') @@ -467,6 +468,10 @@ def list_feedback(self, 'include_total': include_total } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/feedback' request = self.prepare_request(method='GET', url=url, @@ -480,7 +485,7 @@ def get_feedback(self, feedback_id: str, *, model: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get a specified feedback entry. @@ -495,15 +500,12 @@ def get_feedback(self, the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `GetFeedback` object """ if feedback_id is None: raise ValueError('feedback_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='V1', operation_id='get_feedback') @@ -511,7 +513,14 @@ def get_feedback(self, params = {'version': self.version, 'model': model} - url = '/v1/feedback/{0}'.format(*self._encode_path_vars(feedback_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['feedback_id'] + path_param_values = self.encode_path_vars(feedback_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/feedback/{feedback_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -524,7 +533,7 @@ def delete_feedback(self, feedback_id: str, *, model: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a specified feedback entry. @@ -539,15 +548,12 @@ def delete_feedback(self, the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `FeedbackDeleted` object """ if feedback_id is None: raise ValueError('feedback_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='V1', operation_id='delete_feedback') @@ -555,7 +561,14 @@ def delete_feedback(self, params = {'version': self.version, 'model': model} - url = '/v1/feedback/{0}'.format(*self._encode_path_vars(feedback_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['feedback_id'] + path_param_values = self.encode_path_vars(feedback_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/feedback/{feedback_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -578,7 +591,7 @@ def create_batch(self, output_bucket_name: str, *, model: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Submit a batch-processing request. @@ -591,7 +604,7 @@ def create_batch(self, :param str function: The Compare and Comply method to run across the submitted input documents. - :param TextIO input_credentials_file: A JSON file containing the input + :param BinaryIO input_credentials_file: A JSON file containing the input Cloud Object Storage credentials. At a minimum, the credentials must enable `READ` permissions on the bucket defined by the `input_bucket_name` parameter. @@ -600,7 +613,7 @@ def create_batch(self, Object Storage instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. :param str input_bucket_name: The name of the Cloud Object Storage input bucket. - :param TextIO output_credentials_file: A JSON file that lists the Cloud + :param BinaryIO output_credentials_file: A JSON file that lists the Cloud Object Storage output credentials. At a minimum, the credentials must enable `READ` and `WRITE` permissions on the bucket defined by the `output_bucket_name` parameter. @@ -617,7 +630,7 @@ def create_batch(self, the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `BatchStatus` object """ if function is None: @@ -634,10 +647,7 @@ def create_batch(self, raise ValueError('output_bucket_location must be provided') if output_bucket_name is None: raise ValueError('output_bucket_name 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='V1', operation_id='create_batch') @@ -648,21 +658,21 @@ def create_batch(self, form_data = [] form_data.append(('input_credentials_file', (None, input_credentials_file, 'application/json'))) - input_bucket_location = str(input_bucket_location) form_data.append(('input_bucket_location', (None, input_bucket_location, 'text/plain'))) - input_bucket_name = str(input_bucket_name) form_data.append( ('input_bucket_name', (None, input_bucket_name, 'text/plain'))) form_data.append(('output_credentials_file', (None, output_credentials_file, 'application/json'))) - output_bucket_location = str(output_bucket_location) form_data.append(('output_bucket_location', (None, output_bucket_location, 'text/plain'))) - output_bucket_name = str(output_bucket_name) form_data.append( ('output_bucket_name', (None, output_bucket_name, 'text/plain'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/batches' request = self.prepare_request(method='POST', url=url, @@ -673,7 +683,7 @@ def create_batch(self, response = self.send(request) return response - def list_batches(self, **kwargs) -> 'DetailedResponse': + def list_batches(self, **kwargs) -> DetailedResponse: """ List submitted batch-processing jobs. @@ -681,12 +691,10 @@ def list_batches(self, **kwargs) -> 'DetailedResponse': :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Batches` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='list_batches') @@ -694,6 +702,10 @@ def list_batches(self, **kwargs) -> 'DetailedResponse': params = {'version': self.version} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/batches' request = self.prepare_request(method='GET', url=url, @@ -703,7 +715,7 @@ def list_batches(self, **kwargs) -> 'DetailedResponse': response = self.send(request) return response - def get_batch(self, batch_id: str, **kwargs) -> 'DetailedResponse': + def get_batch(self, batch_id: str, **kwargs) -> DetailedResponse: """ Get information about a specific batch-processing job. @@ -713,15 +725,12 @@ def get_batch(self, batch_id: str, **kwargs) -> 'DetailedResponse': you want to retrieve. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `BatchStatus` object """ if batch_id is None: raise ValueError('batch_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='V1', operation_id='get_batch') @@ -729,7 +738,14 @@ def get_batch(self, batch_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v1/batches/{0}'.format(*self._encode_path_vars(batch_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['batch_id'] + path_param_values = self.encode_path_vars(batch_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/batches/{batch_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -743,7 +759,7 @@ def update_batch(self, action: str, *, model: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update a pending or active batch-processing job. @@ -760,17 +776,14 @@ def update_batch(self, the methods' use in batch-processing requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `BatchStatus` object """ if batch_id is None: raise ValueError('batch_id must be provided') if action is None: raise ValueError('action 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='V1', operation_id='update_batch') @@ -778,7 +791,14 @@ def update_batch(self, params = {'version': self.version, 'action': action, 'model': model} - url = '/v1/batches/{0}'.format(*self._encode_path_vars(batch_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['batch_id'] + path_param_values = self.encode_path_vars(batch_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/batches/{batch_id}'.format(**path_param_dict) request = self.prepare_request(method='PUT', url=url, headers=headers, @@ -788,9 +808,12 @@ def update_batch(self, return response -class ConvertToHtmlEnums(object): +class ConvertToHtmlEnums: + """ + Enums for convert_to_html parameters. + """ - class FileContentType(Enum): + class FileContentType(str, Enum): """ The content type of file. """ @@ -804,7 +827,7 @@ class FileContentType(Enum): IMAGE_TIFF = 'image/tiff' TEXT_PLAIN = 'text/plain' - class Model(Enum): + class Model(str, Enum): """ The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, the default is `contracts`. For the @@ -815,9 +838,12 @@ class Model(Enum): TABLES = 'tables' -class ClassifyElementsEnums(object): +class ClassifyElementsEnums: + """ + Enums for classify_elements parameters. + """ - class FileContentType(Enum): + class FileContentType(str, Enum): """ The content type of file. """ @@ -830,7 +856,7 @@ class FileContentType(Enum): IMAGE_PNG = 'image/png' IMAGE_TIFF = 'image/tiff' - class Model(Enum): + class Model(str, Enum): """ The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, the default is `contracts`. For the @@ -841,9 +867,12 @@ class Model(Enum): TABLES = 'tables' -class ExtractTablesEnums(object): +class ExtractTablesEnums: + """ + Enums for extract_tables parameters. + """ - class FileContentType(Enum): + class FileContentType(str, Enum): """ The content type of file. """ @@ -857,7 +886,7 @@ class FileContentType(Enum): IMAGE_TIFF = 'image/tiff' TEXT_PLAIN = 'text/plain' - class Model(Enum): + class Model(str, Enum): """ The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, the default is `contracts`. For the @@ -868,9 +897,12 @@ class Model(Enum): TABLES = 'tables' -class CompareDocumentsEnums(object): +class CompareDocumentsEnums: + """ + Enums for compare_documents parameters. + """ - class File1ContentType(Enum): + class File1ContentType(str, Enum): """ The content type of file_1. """ @@ -884,7 +916,7 @@ class File1ContentType(Enum): IMAGE_PNG = 'image/png' IMAGE_TIFF = 'image/tiff' - class File2ContentType(Enum): + class File2ContentType(str, Enum): """ The content type of file_2. """ @@ -898,7 +930,7 @@ class File2ContentType(Enum): IMAGE_PNG = 'image/png' IMAGE_TIFF = 'image/tiff' - class Model(Enum): + class Model(str, Enum): """ The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, the default is `contracts`. For the @@ -909,9 +941,12 @@ class Model(Enum): TABLES = 'tables' -class GetFeedbackEnums(object): +class GetFeedbackEnums: + """ + Enums for get_feedback parameters. + """ - class Model(Enum): + class Model(str, Enum): """ The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, the default is `contracts`. For the @@ -922,9 +957,12 @@ class Model(Enum): TABLES = 'tables' -class DeleteFeedbackEnums(object): +class DeleteFeedbackEnums: + """ + Enums for delete_feedback parameters. + """ - class Model(Enum): + class Model(str, Enum): """ The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, the default is `contracts`. For the @@ -935,9 +973,12 @@ class Model(Enum): TABLES = 'tables' -class CreateBatchEnums(object): +class CreateBatchEnums: + """ + Enums for create_batch parameters. + """ - class Function(Enum): + class Function(str, Enum): """ The Compare and Comply method to run across the submitted input documents. """ @@ -945,7 +986,7 @@ class Function(Enum): ELEMENT_CLASSIFICATION = 'element_classification' TABLES = 'tables' - class Model(Enum): + class Model(str, Enum): """ The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, the default is `contracts`. For the @@ -956,16 +997,19 @@ class Model(Enum): TABLES = 'tables' -class UpdateBatchEnums(object): +class UpdateBatchEnums: + """ + Enums for update_batch parameters. + """ - class Action(Enum): + class Action(str, Enum): """ The action you want to perform on the specified batch-processing job. """ RESCAN = 'rescan' CANCEL = 'cancel' - class Model(Enum): + class Model(str, Enum): """ The analysis model to be used by the service. For the **Element classification** and **Compare two documents** methods, the default is `contracts`. For the @@ -1010,16 +1054,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Address': """Initialize a Address object from a json dictionary.""" args = {} - valid_keys = ['text', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Address: ' + - ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -1033,7 +1071,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -1042,7 +1080,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Address object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Address') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1101,18 +1139,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AlignedElement': """Initialize a AlignedElement object from a json dictionary.""" args = {} - valid_keys = [ - 'element_pair', 'identical_text', 'provenance_ids', - 'significant_elements' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AlignedElement: ' - + ', '.join(bad_keys)) if 'element_pair' in _dict: args['element_pair'] = [ - ElementPair._from_dict(x) for x in (_dict.get('element_pair')) + ElementPair.from_dict(x) for x in _dict.get('element_pair') ] if 'identical_text' in _dict: args['identical_text'] = _dict.get('identical_text') @@ -1131,7 +1160,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'element_pair') and self.element_pair is not None: - _dict['element_pair'] = [x._to_dict() for x in self.element_pair] + _dict['element_pair'] = [x.to_dict() for x in self.element_pair] if hasattr(self, 'identical_text') and self.identical_text is not None: _dict['identical_text'] = self.identical_text if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: @@ -1147,7 +1176,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AlignedElement object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AlignedElement') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1193,18 +1222,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Attribute': """Initialize a Attribute object from a json dictionary.""" args = {} - valid_keys = ['type', 'text', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Attribute: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -1220,7 +1243,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -1229,7 +1252,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Attribute object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Attribute') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1241,19 +1264,19 @@ def __ne__(self, other: 'Attribute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The type of attribute. """ - CURRENCY = "Currency" - DATETIME = "DateTime" - DEFINEDTERM = "DefinedTerm" - DURATION = "Duration" - LOCATION = "Location" - NUMBER = "Number" - ORGANIZATION = "Organization" - PERCENTAGE = "Percentage" - PERSON = "Person" + CURRENCY = 'Currency' + DATETIME = 'DateTime' + DEFINEDTERM = 'DefinedTerm' + DURATION = 'Duration' + LOCATION = 'Location' + NUMBER = 'Number' + ORGANIZATION = 'Organization' + PERCENTAGE = 'Percentage' + PERSON = 'Person' class BatchStatus(): @@ -1331,16 +1354,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'BatchStatus': """Initialize a BatchStatus object from a json dictionary.""" args = {} - valid_keys = [ - 'function', 'input_bucket_location', 'input_bucket_name', - 'output_bucket_location', 'output_bucket_name', 'batch_id', - 'document_counts', 'status', 'created', 'updated' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BatchStatus: ' - + ', '.join(bad_keys)) if 'function' in _dict: args['function'] = _dict.get('function') if 'input_bucket_location' in _dict: @@ -1354,7 +1367,7 @@ def from_dict(cls, _dict: Dict) -> 'BatchStatus': if 'batch_id' in _dict: args['batch_id'] = _dict.get('batch_id') if 'document_counts' in _dict: - args['document_counts'] = DocCounts._from_dict( + args['document_counts'] = DocCounts.from_dict( _dict.get('document_counts')) if 'status' in _dict: args['status'] = _dict.get('status') @@ -1391,7 +1404,7 @@ def to_dict(self) -> Dict: _dict['batch_id'] = self.batch_id if hasattr(self, 'document_counts') and self.document_counts is not None: - _dict['document_counts'] = self.document_counts._to_dict() + _dict['document_counts'] = self.document_counts.to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'created') and self.created is not None: @@ -1406,7 +1419,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this BatchStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'BatchStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1418,14 +1431,14 @@ def __ne__(self, other: 'BatchStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class FunctionEnum(Enum): + class FunctionEnum(str, Enum): """ The method to be run against the documents. Possible values are `html_conversion`, `element_classification`, and `tables`. """ - ELEMENT_CLASSIFICATION = "element_classification" - HTML_CONVERSION = "html_conversion" - TABLES = "tables" + ELEMENT_CLASSIFICATION = 'element_classification' + HTML_CONVERSION = 'html_conversion' + TABLES = 'tables' class Batches(): @@ -1449,15 +1462,9 @@ def __init__(self, *, batches: List['BatchStatus'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'Batches': """Initialize a Batches object from a json dictionary.""" args = {} - valid_keys = ['batches'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Batches: ' + - ', '.join(bad_keys)) if 'batches' in _dict: args['batches'] = [ - BatchStatus._from_dict(x) for x in (_dict.get('batches')) + BatchStatus.from_dict(x) for x in _dict.get('batches') ] return cls(**args) @@ -1470,7 +1477,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'batches') and self.batches is not None: - _dict['batches'] = [x._to_dict() for x in self.batches] + _dict['batches'] = [x.to_dict() for x in self.batches] return _dict def _to_dict(self): @@ -1479,7 +1486,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Batches object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Batches') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1598,22 +1605,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'BodyCells': """Initialize a BodyCells object from a json dictionary.""" args = {} - valid_keys = [ - 'cell_id', 'location', 'text', 'row_index_begin', 'row_index_end', - 'column_index_begin', 'column_index_end', 'row_header_ids', - 'row_header_texts', 'row_header_texts_normalized', - 'column_header_ids', 'column_header_texts', - 'column_header_texts_normalized', 'attributes' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BodyCells: ' - + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'row_index_begin' in _dict: @@ -1640,7 +1635,7 @@ def from_dict(cls, _dict: Dict) -> 'BodyCells': 'column_header_texts_normalized') if 'attributes' in _dict: args['attributes'] = [ - Attribute._from_dict(x) for x in (_dict.get('attributes')) + Attribute.from_dict(x) for x in _dict.get('attributes') ] return cls(**args) @@ -1655,7 +1650,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -1691,7 +1686,7 @@ def to_dict(self) -> Dict: _dict[ 'column_header_texts_normalized'] = self.column_header_texts_normalized if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x._to_dict() for x in self.attributes] + _dict['attributes'] = [x.to_dict() for x in self.attributes] return _dict def _to_dict(self): @@ -1700,7 +1695,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this BodyCells object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'BodyCells') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1746,12 +1741,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Category': """Initialize a Category object from a json dictionary.""" args = {} - valid_keys = ['label', 'provenance_ids', 'modification'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Category: ' - + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') if 'provenance_ids' in _dict: @@ -1782,7 +1771,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Category object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Category') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1794,43 +1783,43 @@ def __ne__(self, other: 'Category') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LabelEnum(Enum): + class LabelEnum(str, Enum): """ The category of the associated element. """ - AMENDMENTS = "Amendments" - ASSET_USE = "Asset Use" - ASSIGNMENTS = "Assignments" - AUDITS = "Audits" - BUSINESS_CONTINUITY = "Business Continuity" - COMMUNICATION = "Communication" - CONFIDENTIALITY = "Confidentiality" - DELIVERABLES = "Deliverables" - DELIVERY = "Delivery" - DISPUTE_RESOLUTION = "Dispute Resolution" - FORCE_MAJEURE = "Force Majeure" - INDEMNIFICATION = "Indemnification" - INSURANCE = "Insurance" - INTELLECTUAL_PROPERTY = "Intellectual Property" - LIABILITY = "Liability" - ORDER_OF_PRECEDENCE = "Order of Precedence" - PAYMENT_TERMS_BILLING = "Payment Terms & Billing" - PRICING_TAXES = "Pricing & Taxes" - PRIVACY = "Privacy" - RESPONSIBILITIES = "Responsibilities" - SAFETY_AND_SECURITY = "Safety and Security" - SCOPE_OF_WORK = "Scope of Work" - SUBCONTRACTS = "Subcontracts" - TERM_TERMINATION = "Term & Termination" - WARRANTIES = "Warranties" - - class ModificationEnum(Enum): + AMENDMENTS = 'Amendments' + ASSET_USE = 'Asset Use' + ASSIGNMENTS = 'Assignments' + AUDITS = 'Audits' + BUSINESS_CONTINUITY = 'Business Continuity' + COMMUNICATION = 'Communication' + CONFIDENTIALITY = 'Confidentiality' + DELIVERABLES = 'Deliverables' + DELIVERY = 'Delivery' + DISPUTE_RESOLUTION = 'Dispute Resolution' + FORCE_MAJEURE = 'Force Majeure' + INDEMNIFICATION = 'Indemnification' + INSURANCE = 'Insurance' + INTELLECTUAL_PROPERTY = 'Intellectual Property' + LIABILITY = 'Liability' + ORDER_OF_PRECEDENCE = 'Order of Precedence' + PAYMENT_TERMS_BILLING = 'Payment Terms & Billing' + PRICING_TAXES = 'Pricing & Taxes' + PRIVACY = 'Privacy' + RESPONSIBILITIES = 'Responsibilities' + SAFETY_AND_SECURITY = 'Safety and Security' + SCOPE_OF_WORK = 'Scope of Work' + SUBCONTRACTS = 'Subcontracts' + TERM_TERMINATION = 'Term & Termination' + WARRANTIES = 'Warranties' + + class ModificationEnum(str, Enum): """ The type of modification of the feedback entry in the updated labels response. """ - ADDED = "added" - UNCHANGED = "unchanged" - REMOVED = "removed" + ADDED = 'added' + UNCHANGED = 'unchanged' + REMOVED = 'removed' class CategoryComparison(): @@ -1852,12 +1841,6 @@ def __init__(self, *, label: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'CategoryComparison': """Initialize a CategoryComparison object from a json dictionary.""" args = {} - valid_keys = ['label'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CategoryComparison: ' - + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') return cls(**args) @@ -1880,7 +1863,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CategoryComparison object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CategoryComparison') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1892,35 +1875,35 @@ def __ne__(self, other: 'CategoryComparison') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LabelEnum(Enum): + class LabelEnum(str, Enum): """ The category of the associated element. """ - AMENDMENTS = "Amendments" - ASSET_USE = "Asset Use" - ASSIGNMENTS = "Assignments" - AUDITS = "Audits" - BUSINESS_CONTINUITY = "Business Continuity" - COMMUNICATION = "Communication" - CONFIDENTIALITY = "Confidentiality" - DELIVERABLES = "Deliverables" - DELIVERY = "Delivery" - DISPUTE_RESOLUTION = "Dispute Resolution" - FORCE_MAJEURE = "Force Majeure" - INDEMNIFICATION = "Indemnification" - INSURANCE = "Insurance" - INTELLECTUAL_PROPERTY = "Intellectual Property" - LIABILITY = "Liability" - ORDER_OF_PRECEDENCE = "Order of Precedence" - PAYMENT_TERMS_BILLING = "Payment Terms & Billing" - PRICING_TAXES = "Pricing & Taxes" - PRIVACY = "Privacy" - RESPONSIBILITIES = "Responsibilities" - SAFETY_AND_SECURITY = "Safety and Security" - SCOPE_OF_WORK = "Scope of Work" - SUBCONTRACTS = "Subcontracts" - TERM_TERMINATION = "Term & Termination" - WARRANTIES = "Warranties" + AMENDMENTS = 'Amendments' + ASSET_USE = 'Asset Use' + ASSIGNMENTS = 'Assignments' + AUDITS = 'Audits' + BUSINESS_CONTINUITY = 'Business Continuity' + COMMUNICATION = 'Communication' + CONFIDENTIALITY = 'Confidentiality' + DELIVERABLES = 'Deliverables' + DELIVERY = 'Delivery' + DISPUTE_RESOLUTION = 'Dispute Resolution' + FORCE_MAJEURE = 'Force Majeure' + INDEMNIFICATION = 'Indemnification' + INSURANCE = 'Insurance' + INTELLECTUAL_PROPERTY = 'Intellectual Property' + LIABILITY = 'Liability' + ORDER_OF_PRECEDENCE = 'Order of Precedence' + PAYMENT_TERMS_BILLING = 'Payment Terms & Billing' + PRICING_TAXES = 'Pricing & Taxes' + PRIVACY = 'Privacy' + RESPONSIBILITIES = 'Responsibilities' + SAFETY_AND_SECURITY = 'Safety and Security' + SCOPE_OF_WORK = 'Scope of Work' + SUBCONTRACTS = 'Subcontracts' + TERM_TERMINATION = 'Term & Termination' + WARRANTIES = 'Warranties' class ClassifyReturn(): @@ -2027,71 +2010,55 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassifyReturn': """Initialize a ClassifyReturn object from a json dictionary.""" args = {} - valid_keys = [ - 'document', 'model_id', 'model_version', 'elements', - 'effective_dates', 'contract_amounts', 'termination_dates', - 'contract_types', 'contract_terms', 'payment_terms', - 'contract_currencies', 'tables', 'document_structure', 'parties' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ClassifyReturn: ' - + ', '.join(bad_keys)) if 'document' in _dict: - args['document'] = Document._from_dict(_dict.get('document')) + args['document'] = Document.from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: args['model_version'] = _dict.get('model_version') if 'elements' in _dict: args['elements'] = [ - Element._from_dict(x) for x in (_dict.get('elements')) + Element.from_dict(x) for x in _dict.get('elements') ] if 'effective_dates' in _dict: args['effective_dates'] = [ - EffectiveDates._from_dict(x) - for x in (_dict.get('effective_dates')) + EffectiveDates.from_dict(x) + for x in _dict.get('effective_dates') ] if 'contract_amounts' in _dict: args['contract_amounts'] = [ - ContractAmts._from_dict(x) - for x in (_dict.get('contract_amounts')) + ContractAmts.from_dict(x) for x in _dict.get('contract_amounts') ] if 'termination_dates' in _dict: args['termination_dates'] = [ - TerminationDates._from_dict(x) - for x in (_dict.get('termination_dates')) + TerminationDates.from_dict(x) + for x in _dict.get('termination_dates') ] if 'contract_types' in _dict: args['contract_types'] = [ - ContractTypes._from_dict(x) - for x in (_dict.get('contract_types')) + ContractTypes.from_dict(x) for x in _dict.get('contract_types') ] if 'contract_terms' in _dict: args['contract_terms'] = [ - ContractTerms._from_dict(x) - for x in (_dict.get('contract_terms')) + ContractTerms.from_dict(x) for x in _dict.get('contract_terms') ] if 'payment_terms' in _dict: args['payment_terms'] = [ - PaymentTerms._from_dict(x) for x in (_dict.get('payment_terms')) + PaymentTerms.from_dict(x) for x in _dict.get('payment_terms') ] if 'contract_currencies' in _dict: args['contract_currencies'] = [ - ContractCurrencies._from_dict(x) - for x in (_dict.get('contract_currencies')) + ContractCurrencies.from_dict(x) + for x in _dict.get('contract_currencies') ] if 'tables' in _dict: - args['tables'] = [ - Tables._from_dict(x) for x in (_dict.get('tables')) - ] + args['tables'] = [Tables.from_dict(x) for x in _dict.get('tables')] if 'document_structure' in _dict: - args['document_structure'] = DocStructure._from_dict( + args['document_structure'] = DocStructure.from_dict( _dict.get('document_structure')) if 'parties' in _dict: args['parties'] = [ - Parties._from_dict(x) for x in (_dict.get('parties')) + Parties.from_dict(x) for x in _dict.get('parties') ] return cls(**args) @@ -2104,52 +2071,48 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document._to_dict() + _dict['document'] = self.document.to_dict() if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'model_version') and self.model_version is not None: _dict['model_version'] = self.model_version if hasattr(self, 'elements') and self.elements is not None: - _dict['elements'] = [x._to_dict() for x in self.elements] + _dict['elements'] = [x.to_dict() for x in self.elements] if hasattr(self, 'effective_dates') and self.effective_dates is not None: _dict['effective_dates'] = [ - x._to_dict() for x in self.effective_dates + x.to_dict() for x in self.effective_dates ] if hasattr(self, 'contract_amounts') and self.contract_amounts is not None: _dict['contract_amounts'] = [ - x._to_dict() for x in self.contract_amounts + x.to_dict() for x in self.contract_amounts ] if hasattr(self, 'termination_dates') and self.termination_dates is not None: _dict['termination_dates'] = [ - x._to_dict() for x in self.termination_dates + x.to_dict() for x in self.termination_dates ] if hasattr(self, 'contract_types') and self.contract_types is not None: - _dict['contract_types'] = [ - x._to_dict() for x in self.contract_types - ] + _dict['contract_types'] = [x.to_dict() for x in self.contract_types] if hasattr(self, 'contract_terms') and self.contract_terms is not None: - _dict['contract_terms'] = [ - x._to_dict() for x in self.contract_terms - ] + _dict['contract_terms'] = [x.to_dict() for x in self.contract_terms] if hasattr(self, 'payment_terms') and self.payment_terms is not None: - _dict['payment_terms'] = [x._to_dict() for x in self.payment_terms] + _dict['payment_terms'] = [x.to_dict() for x in self.payment_terms] if hasattr( self, 'contract_currencies') and self.contract_currencies is not None: _dict['contract_currencies'] = [ - x._to_dict() for x in self.contract_currencies + x.to_dict() for x in self.contract_currencies ] if hasattr(self, 'tables') and self.tables is not None: - _dict['tables'] = [x._to_dict() for x in self.tables] + _dict['tables'] = [x.to_dict() for x in self.tables] if hasattr( self, 'document_structure') and self.document_structure is not None: - _dict['document_structure'] = self.document_structure._to_dict() + _dict['document_structure'] = self.document_structure.to_dict() if hasattr(self, 'parties') and self.parties is not None: - _dict['parties'] = [x._to_dict() for x in self.parties] + _dict['parties'] = [x.to_dict() for x in self.parties] return _dict def _to_dict(self): @@ -2158,7 +2121,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ClassifyReturn object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ClassifyReturn') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2240,15 +2203,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ColumnHeaders': """Initialize a ColumnHeaders object from a json dictionary.""" args = {} - valid_keys = [ - 'cell_id', 'location', 'text', 'text_normalized', 'row_index_begin', - 'row_index_end', 'column_index_begin', 'column_index_end' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ColumnHeaders: ' - + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: @@ -2304,7 +2258,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ColumnHeaders object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ColumnHeaders') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2366,32 +2320,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CompareReturn': """Initialize a CompareReturn object from a json dictionary.""" args = {} - valid_keys = [ - 'model_id', 'model_version', 'documents', 'aligned_elements', - 'unaligned_elements' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CompareReturn: ' - + ', '.join(bad_keys)) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: args['model_version'] = _dict.get('model_version') if 'documents' in _dict: args['documents'] = [ - Document._from_dict(x) for x in (_dict.get('documents')) + Document.from_dict(x) for x in _dict.get('documents') ] if 'aligned_elements' in _dict: args['aligned_elements'] = [ - AlignedElement._from_dict(x) - for x in (_dict.get('aligned_elements')) + AlignedElement.from_dict(x) + for x in _dict.get('aligned_elements') ] if 'unaligned_elements' in _dict: args['unaligned_elements'] = [ - UnalignedElement._from_dict(x) - for x in (_dict.get('unaligned_elements')) + UnalignedElement.from_dict(x) + for x in _dict.get('unaligned_elements') ] return cls(**args) @@ -2408,17 +2353,17 @@ def to_dict(self) -> Dict: if hasattr(self, 'model_version') and self.model_version is not None: _dict['model_version'] = self.model_version if hasattr(self, 'documents') and self.documents is not None: - _dict['documents'] = [x._to_dict() for x in self.documents] + _dict['documents'] = [x.to_dict() for x in self.documents] if hasattr(self, 'aligned_elements') and self.aligned_elements is not None: _dict['aligned_elements'] = [ - x._to_dict() for x in self.aligned_elements + x.to_dict() for x in self.aligned_elements ] if hasattr( self, 'unaligned_elements') and self.unaligned_elements is not None: _dict['unaligned_elements'] = [ - x._to_dict() for x in self.unaligned_elements + x.to_dict() for x in self.unaligned_elements ] return _dict @@ -2428,7 +2373,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CompareReturn object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CompareReturn') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2463,12 +2408,6 @@ def __init__(self, *, name: str = None, role: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Contact': """Initialize a Contact object from a json dictionary.""" args = {} - valid_keys = ['name', 'role'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Contact: ' + - ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') if 'role' in _dict: @@ -2495,7 +2434,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Contact object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Contact') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2538,16 +2477,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Contexts': """Initialize a Contexts object from a json dictionary.""" args = {} - valid_keys = ['text', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Contexts: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -2561,7 +2494,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -2570,7 +2503,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Contexts object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Contexts') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2640,15 +2573,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ContractAmts': """Initialize a ContractAmts object from a json dictionary.""" args = {} - valid_keys = [ - 'confidence_level', 'text', 'text_normalized', 'interpretation', - 'provenance_ids', 'location' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ContractAmts: ' - + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -2656,12 +2580,12 @@ def from_dict(cls, _dict: Dict) -> 'ContractAmts': if 'text_normalized' in _dict: args['text_normalized'] = _dict.get('text_normalized') if 'interpretation' in _dict: - args['interpretation'] = Interpretation._from_dict( + args['interpretation'] = Interpretation.from_dict( _dict.get('interpretation')) if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -2681,11 +2605,11 @@ def to_dict(self) -> Dict: 'text_normalized') and self.text_normalized is not None: _dict['text_normalized'] = self.text_normalized if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation._to_dict() + _dict['interpretation'] = self.interpretation.to_dict() if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -2694,7 +2618,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ContractAmts object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ContractAmts') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2706,13 +2630,13 @@ def __ne__(self, other: 'ContractAmts') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConfidenceLevelEnum(Enum): + class ConfidenceLevelEnum(str, Enum): """ The confidence level in the identification of the contract amount. """ - HIGH = "High" - MEDIUM = "Medium" - LOW = "Low" + HIGH = 'High' + MEDIUM = 'Medium' + LOW = 'Low' class ContractCurrencies(): @@ -2766,15 +2690,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ContractCurrencies': """Initialize a ContractCurrencies object from a json dictionary.""" args = {} - valid_keys = [ - 'confidence_level', 'text', 'text_normalized', 'provenance_ids', - 'location' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ContractCurrencies: ' - + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -2784,7 +2699,7 @@ def from_dict(cls, _dict: Dict) -> 'ContractCurrencies': if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -2806,7 +2721,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -2815,7 +2730,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ContractCurrencies object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ContractCurrencies') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2827,13 +2742,13 @@ def __ne__(self, other: 'ContractCurrencies') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConfidenceLevelEnum(Enum): + class ConfidenceLevelEnum(str, Enum): """ The confidence level in the identification of the contract currency. """ - HIGH = "High" - MEDIUM = "Medium" - LOW = "Low" + HIGH = 'High' + MEDIUM = 'Medium' + LOW = 'Low' class ContractTerms(): @@ -2893,15 +2808,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ContractTerms': """Initialize a ContractTerms object from a json dictionary.""" args = {} - valid_keys = [ - 'confidence_level', 'text', 'text_normalized', 'interpretation', - 'provenance_ids', 'location' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ContractTerms: ' - + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -2909,12 +2815,12 @@ def from_dict(cls, _dict: Dict) -> 'ContractTerms': if 'text_normalized' in _dict: args['text_normalized'] = _dict.get('text_normalized') if 'interpretation' in _dict: - args['interpretation'] = Interpretation._from_dict( + args['interpretation'] = Interpretation.from_dict( _dict.get('interpretation')) if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -2934,11 +2840,11 @@ def to_dict(self) -> Dict: 'text_normalized') and self.text_normalized is not None: _dict['text_normalized'] = self.text_normalized if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation._to_dict() + _dict['interpretation'] = self.interpretation.to_dict() if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -2947,7 +2853,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ContractTerms object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ContractTerms') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2959,13 +2865,13 @@ def __ne__(self, other: 'ContractTerms') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConfidenceLevelEnum(Enum): + class ConfidenceLevelEnum(str, Enum): """ The confidence level in the identification of the contract term. """ - HIGH = "High" - MEDIUM = "Medium" - LOW = "Low" + HIGH = 'High' + MEDIUM = 'Medium' + LOW = 'Low' class ContractTypes(): @@ -3009,12 +2915,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ContractTypes': """Initialize a ContractTypes object from a json dictionary.""" args = {} - valid_keys = ['confidence_level', 'text', 'provenance_ids', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ContractTypes: ' - + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -3022,7 +2922,7 @@ def from_dict(cls, _dict: Dict) -> 'ContractTypes': if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -3041,7 +2941,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -3050,7 +2950,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ContractTypes object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ContractTypes') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3062,13 +2962,13 @@ def __ne__(self, other: 'ContractTypes') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConfidenceLevelEnum(Enum): + class ConfidenceLevelEnum(str, Enum): """ The confidence level in the identification of the contract type. """ - HIGH = "High" - MEDIUM = "Medium" - LOW = "Low" + HIGH = 'High' + MEDIUM = 'Medium' + LOW = 'Low' class DocCounts(): @@ -3106,12 +3006,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocCounts': """Initialize a DocCounts object from a json dictionary.""" args = {} - valid_keys = ['total', 'pending', 'successful', 'failed'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocCounts: ' - + ', '.join(bad_keys)) if 'total' in _dict: args['total'] = _dict.get('total') if 'pending' in _dict: @@ -3146,7 +3040,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocCounts object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocCounts') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3191,12 +3085,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocInfo': """Initialize a DocInfo object from a json dictionary.""" args = {} - valid_keys = ['html', 'title', 'hash'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocInfo: ' + - ', '.join(bad_keys)) if 'html' in _dict: args['html'] = _dict.get('html') if 'title' in _dict: @@ -3227,7 +3115,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocInfo object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocInfo') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3280,25 +3168,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocStructure': """Initialize a DocStructure object from a json dictionary.""" args = {} - valid_keys = ['section_titles', 'leading_sentences', 'paragraphs'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocStructure: ' - + ', '.join(bad_keys)) if 'section_titles' in _dict: args['section_titles'] = [ - SectionTitles._from_dict(x) - for x in (_dict.get('section_titles')) + SectionTitles.from_dict(x) for x in _dict.get('section_titles') ] if 'leading_sentences' in _dict: args['leading_sentences'] = [ - LeadingSentence._from_dict(x) - for x in (_dict.get('leading_sentences')) + LeadingSentence.from_dict(x) + for x in _dict.get('leading_sentences') ] if 'paragraphs' in _dict: args['paragraphs'] = [ - Paragraphs._from_dict(x) for x in (_dict.get('paragraphs')) + Paragraphs.from_dict(x) for x in _dict.get('paragraphs') ] return cls(**args) @@ -3311,16 +3192,14 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'section_titles') and self.section_titles is not None: - _dict['section_titles'] = [ - x._to_dict() for x in self.section_titles - ] + _dict['section_titles'] = [x.to_dict() for x in self.section_titles] if hasattr(self, 'leading_sentences') and self.leading_sentences is not None: _dict['leading_sentences'] = [ - x._to_dict() for x in self.leading_sentences + x.to_dict() for x in self.leading_sentences ] if hasattr(self, 'paragraphs') and self.paragraphs is not None: - _dict['paragraphs'] = [x._to_dict() for x in self.paragraphs] + _dict['paragraphs'] = [x.to_dict() for x in self.paragraphs] return _dict def _to_dict(self): @@ -3329,7 +3208,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocStructure object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocStructure') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3379,12 +3258,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Document': """Initialize a Document object from a json dictionary.""" args = {} - valid_keys = ['title', 'html', 'hash', 'label'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Document: ' - + ', '.join(bad_keys)) if 'title' in _dict: args['title'] = _dict.get('title') if 'html' in _dict: @@ -3419,7 +3292,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Document object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Document') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3481,15 +3354,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EffectiveDates': """Initialize a EffectiveDates object from a json dictionary.""" args = {} - valid_keys = [ - 'confidence_level', 'text', 'text_normalized', 'provenance_ids', - 'location' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EffectiveDates: ' - + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -3499,7 +3363,7 @@ def from_dict(cls, _dict: Dict) -> 'EffectiveDates': if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -3521,7 +3385,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -3530,7 +3394,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EffectiveDates object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EffectiveDates') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3542,13 +3406,13 @@ def __ne__(self, other: 'EffectiveDates') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConfidenceLevelEnum(Enum): + class ConfidenceLevelEnum(str, Enum): """ The confidence level in the identification of the effective date. """ - HIGH = "High" - MEDIUM = "Medium" - LOW = "Low" + HIGH = 'High' + MEDIUM = 'Medium' + LOW = 'Low' class Element(): @@ -3597,27 +3461,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Element': """Initialize a Element object from a json dictionary.""" args = {} - valid_keys = ['location', 'text', 'types', 'categories', 'attributes'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Element: ' + - ', '.join(bad_keys)) if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'types' in _dict: - args['types'] = [ - TypeLabel._from_dict(x) for x in (_dict.get('types')) - ] + args['types'] = [TypeLabel.from_dict(x) for x in _dict.get('types')] if 'categories' in _dict: args['categories'] = [ - Category._from_dict(x) for x in (_dict.get('categories')) + Category.from_dict(x) for x in _dict.get('categories') ] if 'attributes' in _dict: args['attributes'] = [ - Attribute._from_dict(x) for x in (_dict.get('attributes')) + Attribute.from_dict(x) for x in _dict.get('attributes') ] return cls(**args) @@ -3630,15 +3486,15 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'types') and self.types is not None: - _dict['types'] = [x._to_dict() for x in self.types] + _dict['types'] = [x.to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x._to_dict() for x in self.categories] + _dict['categories'] = [x.to_dict() for x in self.categories] if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x._to_dict() for x in self.attributes] + _dict['attributes'] = [x.to_dict() for x in self.attributes] return _dict def _to_dict(self): @@ -3647,7 +3503,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Element object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Element') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3687,12 +3543,6 @@ def __init__(self, *, begin: int = None, end: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'ElementLocations': """Initialize a ElementLocations object from a json dictionary.""" args = {} - valid_keys = ['begin', 'end'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ElementLocations: ' - + ', '.join(bad_keys)) if 'begin' in _dict: args['begin'] = _dict.get('begin') if 'end' in _dict: @@ -3719,7 +3569,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ElementLocations object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ElementLocations') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3787,33 +3637,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ElementPair': """Initialize a ElementPair object from a json dictionary.""" args = {} - valid_keys = [ - 'document_label', 'text', 'location', 'types', 'categories', - 'attributes' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ElementPair: ' - + ', '.join(bad_keys)) if 'document_label' in _dict: args['document_label'] = _dict.get('document_label') if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'types' in _dict: args['types'] = [ - TypeLabelComparison._from_dict(x) for x in (_dict.get('types')) + TypeLabelComparison.from_dict(x) for x in _dict.get('types') ] if 'categories' in _dict: args['categories'] = [ - CategoryComparison._from_dict(x) - for x in (_dict.get('categories')) + CategoryComparison.from_dict(x) for x in _dict.get('categories') ] if 'attributes' in _dict: args['attributes'] = [ - Attribute._from_dict(x) for x in (_dict.get('attributes')) + Attribute.from_dict(x) for x in _dict.get('attributes') ] return cls(**args) @@ -3830,13 +3670,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'types') and self.types is not None: - _dict['types'] = [x._to_dict() for x in self.types] + _dict['types'] = [x.to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x._to_dict() for x in self.categories] + _dict['categories'] = [x.to_dict() for x in self.categories] if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x._to_dict() for x in self.attributes] + _dict['attributes'] = [x.to_dict() for x in self.attributes] return _dict def _to_dict(self): @@ -3845,7 +3685,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ElementPair object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ElementPair') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3920,15 +3760,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'FeedbackDataInput': """Initialize a FeedbackDataInput object from a json dictionary.""" args = {} - valid_keys = [ - 'feedback_type', 'document', 'model_id', 'model_version', - 'location', 'text', 'original_labels', 'updated_labels' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class FeedbackDataInput: ' - + ', '.join(bad_keys)) if 'feedback_type' in _dict: args['feedback_type'] = _dict.get('feedback_type') else: @@ -3936,13 +3767,13 @@ def from_dict(cls, _dict: Dict) -> 'FeedbackDataInput': 'Required property \'feedback_type\' not present in FeedbackDataInput JSON' ) if 'document' in _dict: - args['document'] = ShortDoc._from_dict(_dict.get('document')) + args['document'] = ShortDoc.from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: args['model_version'] = _dict.get('model_version') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) else: raise ValueError( 'Required property \'location\' not present in FeedbackDataInput JSON' @@ -3954,14 +3785,14 @@ def from_dict(cls, _dict: Dict) -> 'FeedbackDataInput': 'Required property \'text\' not present in FeedbackDataInput JSON' ) if 'original_labels' in _dict: - args['original_labels'] = OriginalLabelsIn._from_dict( + args['original_labels'] = OriginalLabelsIn.from_dict( _dict.get('original_labels')) else: raise ValueError( 'Required property \'original_labels\' not present in FeedbackDataInput JSON' ) if 'updated_labels' in _dict: - args['updated_labels'] = UpdatedLabelsIn._from_dict( + args['updated_labels'] = UpdatedLabelsIn.from_dict( _dict.get('updated_labels')) else: raise ValueError( @@ -3980,20 +3811,20 @@ def to_dict(self) -> Dict: if hasattr(self, 'feedback_type') and self.feedback_type is not None: _dict['feedback_type'] = self.feedback_type if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document._to_dict() + _dict['document'] = self.document.to_dict() if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'model_version') and self.model_version is not None: _dict['model_version'] = self.model_version if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'original_labels') and self.original_labels is not None: - _dict['original_labels'] = self.original_labels._to_dict() + _dict['original_labels'] = self.original_labels.to_dict() if hasattr(self, 'updated_labels') and self.updated_labels is not None: - _dict['updated_labels'] = self.updated_labels._to_dict() + _dict['updated_labels'] = self.updated_labels.to_dict() return _dict def _to_dict(self): @@ -4002,7 +3833,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this FeedbackDataInput object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'FeedbackDataInput') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4085,36 +3916,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'FeedbackDataOutput': """Initialize a FeedbackDataOutput object from a json dictionary.""" args = {} - valid_keys = [ - 'feedback_type', 'document', 'model_id', 'model_version', - 'location', 'text', 'original_labels', 'updated_labels', - 'pagination' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class FeedbackDataOutput: ' - + ', '.join(bad_keys)) if 'feedback_type' in _dict: args['feedback_type'] = _dict.get('feedback_type') if 'document' in _dict: - args['document'] = ShortDoc._from_dict(_dict.get('document')) + args['document'] = ShortDoc.from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: args['model_version'] = _dict.get('model_version') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'original_labels' in _dict: - args['original_labels'] = OriginalLabelsOut._from_dict( + args['original_labels'] = OriginalLabelsOut.from_dict( _dict.get('original_labels')) if 'updated_labels' in _dict: - args['updated_labels'] = UpdatedLabelsOut._from_dict( + args['updated_labels'] = UpdatedLabelsOut.from_dict( _dict.get('updated_labels')) if 'pagination' in _dict: - args['pagination'] = Pagination._from_dict(_dict.get('pagination')) + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) return cls(**args) @classmethod @@ -4128,22 +3949,22 @@ def to_dict(self) -> Dict: if hasattr(self, 'feedback_type') and self.feedback_type is not None: _dict['feedback_type'] = self.feedback_type if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document._to_dict() + _dict['document'] = self.document.to_dict() if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'model_version') and self.model_version is not None: _dict['model_version'] = self.model_version if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'original_labels') and self.original_labels is not None: - _dict['original_labels'] = self.original_labels._to_dict() + _dict['original_labels'] = self.original_labels.to_dict() if hasattr(self, 'updated_labels') and self.updated_labels is not None: - _dict['updated_labels'] = self.updated_labels._to_dict() + _dict['updated_labels'] = self.updated_labels.to_dict() if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination._to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -4152,7 +3973,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this FeedbackDataOutput object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'FeedbackDataOutput') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4187,12 +4008,6 @@ def __init__(self, *, status: int = None, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'FeedbackDeleted': """Initialize a FeedbackDeleted object from a json dictionary.""" args = {} - valid_keys = ['status', 'message'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class FeedbackDeleted: ' - + ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') if 'message' in _dict: @@ -4219,7 +4034,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this FeedbackDeleted object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'FeedbackDeleted') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4253,15 +4068,9 @@ def __init__(self, *, feedback: List['GetFeedback'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'FeedbackList': """Initialize a FeedbackList object from a json dictionary.""" args = {} - valid_keys = ['feedback'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class FeedbackList: ' - + ', '.join(bad_keys)) if 'feedback' in _dict: args['feedback'] = [ - GetFeedback._from_dict(x) for x in (_dict.get('feedback')) + GetFeedback.from_dict(x) for x in _dict.get('feedback') ] return cls(**args) @@ -4274,7 +4083,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'feedback') and self.feedback is not None: - _dict['feedback'] = [x._to_dict() for x in self.feedback] + _dict['feedback'] = [x.to_dict() for x in self.feedback] return _dict def _to_dict(self): @@ -4283,7 +4092,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this FeedbackList object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'FeedbackList') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4341,14 +4150,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'FeedbackReturn': """Initialize a FeedbackReturn object from a json dictionary.""" args = {} - valid_keys = [ - 'feedback_id', 'user_id', 'comment', 'created', 'feedback_data' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class FeedbackReturn: ' - + ', '.join(bad_keys)) if 'feedback_id' in _dict: args['feedback_id'] = _dict.get('feedback_id') if 'user_id' in _dict: @@ -4358,7 +4159,7 @@ def from_dict(cls, _dict: Dict) -> 'FeedbackReturn': if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'feedback_data' in _dict: - args['feedback_data'] = FeedbackDataOutput._from_dict( + args['feedback_data'] = FeedbackDataOutput.from_dict( _dict.get('feedback_data')) return cls(**args) @@ -4379,7 +4180,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'feedback_data') and self.feedback_data is not None: - _dict['feedback_data'] = self.feedback_data._to_dict() + _dict['feedback_data'] = self.feedback_data.to_dict() return _dict def _to_dict(self): @@ -4388,7 +4189,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this FeedbackReturn object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'FeedbackReturn') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4442,12 +4243,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'GetFeedback': """Initialize a GetFeedback object from a json dictionary.""" args = {} - valid_keys = ['feedback_id', 'created', 'comment', 'feedback_data'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class GetFeedback: ' - + ', '.join(bad_keys)) if 'feedback_id' in _dict: args['feedback_id'] = _dict.get('feedback_id') if 'created' in _dict: @@ -4455,7 +4250,7 @@ def from_dict(cls, _dict: Dict) -> 'GetFeedback': if 'comment' in _dict: args['comment'] = _dict.get('comment') if 'feedback_data' in _dict: - args['feedback_data'] = FeedbackDataOutput._from_dict( + args['feedback_data'] = FeedbackDataOutput.from_dict( _dict.get('feedback_data')) return cls(**args) @@ -4474,7 +4269,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'comment') and self.comment is not None: _dict['comment'] = self.comment if hasattr(self, 'feedback_data') and self.feedback_data is not None: - _dict['feedback_data'] = self.feedback_data._to_dict() + _dict['feedback_data'] = self.feedback_data.to_dict() return _dict def _to_dict(self): @@ -4483,7 +4278,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this GetFeedback object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'GetFeedback') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4537,14 +4332,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'HTMLReturn': """Initialize a HTMLReturn object from a json dictionary.""" args = {} - valid_keys = [ - 'num_pages', 'author', 'publication_date', 'title', 'html' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class HTMLReturn: ' - + ', '.join(bad_keys)) if 'num_pages' in _dict: args['num_pages'] = _dict.get('num_pages') if 'author' in _dict: @@ -4584,7 +4371,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this HTMLReturn object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'HTMLReturn') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4642,12 +4429,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Interpretation': """Initialize a Interpretation object from a json dictionary.""" args = {} - valid_keys = ['value', 'numeric_value', 'unit'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Interpretation: ' - + ', '.join(bad_keys)) if 'value' in _dict: args['value'] = _dict.get('value') if 'numeric_value' in _dict: @@ -4678,7 +4459,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Interpretation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Interpretation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4726,16 +4507,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Key': """Initialize a Key object from a json dictionary.""" args = {} - valid_keys = ['cell_id', 'location', 'text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Key: ' + - ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -4751,7 +4526,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict @@ -4762,7 +4537,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Key object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Key') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4800,16 +4575,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'KeyValuePair': """Initialize a KeyValuePair object from a json dictionary.""" args = {} - valid_keys = ['key', 'value'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class KeyValuePair: ' - + ', '.join(bad_keys)) if 'key' in _dict: - args['key'] = Key._from_dict(_dict.get('key')) + args['key'] = Key.from_dict(_dict.get('key')) if 'value' in _dict: - args['value'] = [Value._from_dict(x) for x in (_dict.get('value'))] + args['value'] = [Value.from_dict(x) for x in _dict.get('value')] return cls(**args) @classmethod @@ -4821,9 +4590,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key._to_dict() + _dict['key'] = self.key.to_dict() if hasattr(self, 'value') and self.value is not None: - _dict['value'] = [x._to_dict() for x in self.value] + _dict['value'] = [x.to_dict() for x in self.value] return _dict def _to_dict(self): @@ -4832,7 +4601,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this KeyValuePair object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'KeyValuePair') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4869,12 +4638,6 @@ def __init__(self, nature: str, party: str) -> None: def from_dict(cls, _dict: Dict) -> 'Label': """Initialize a Label object from a json dictionary.""" args = {} - valid_keys = ['nature', 'party'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Label: ' + - ', '.join(bad_keys)) if 'nature' in _dict: args['nature'] = _dict.get('nature') else: @@ -4907,7 +4670,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Label object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Label') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4955,20 +4718,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LeadingSentence': """Initialize a LeadingSentence object from a json dictionary.""" args = {} - valid_keys = ['text', 'location', 'element_locations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LeadingSentence: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'element_locations' in _dict: args['element_locations'] = [ - ElementLocations._from_dict(x) - for x in (_dict.get('element_locations')) + ElementLocations.from_dict(x) + for x in _dict.get('element_locations') ] return cls(**args) @@ -4983,11 +4740,11 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'element_locations') and self.element_locations is not None: _dict['element_locations'] = [ - x._to_dict() for x in self.element_locations + x.to_dict() for x in self.element_locations ] return _dict @@ -4997,7 +4754,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LeadingSentence object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LeadingSentence') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5033,12 +4790,6 @@ def __init__(self, begin: int, end: int) -> None: def from_dict(cls, _dict: Dict) -> 'Location': """Initialize a Location object from a json dictionary.""" args = {} - valid_keys = ['begin', 'end'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Location: ' - + ', '.join(bad_keys)) if 'begin' in _dict: args['begin'] = _dict.get('begin') else: @@ -5071,7 +4822,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Location object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Location') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5113,16 +4864,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Mention': """Initialize a Mention object from a json dictionary.""" args = {} - valid_keys = ['text', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Mention: ' + - ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -5136,7 +4881,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -5145,7 +4890,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Mention object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Mention') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5185,23 +4930,15 @@ def __init__(self, types: List['TypeLabel'], def from_dict(cls, _dict: Dict) -> 'OriginalLabelsIn': """Initialize a OriginalLabelsIn object from a json dictionary.""" args = {} - valid_keys = ['types', 'categories'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class OriginalLabelsIn: ' - + ', '.join(bad_keys)) if 'types' in _dict: - args['types'] = [ - TypeLabel._from_dict(x) for x in (_dict.get('types')) - ] + args['types'] = [TypeLabel.from_dict(x) for x in _dict.get('types')] else: raise ValueError( 'Required property \'types\' not present in OriginalLabelsIn JSON' ) if 'categories' in _dict: args['categories'] = [ - Category._from_dict(x) for x in (_dict.get('categories')) + Category.from_dict(x) for x in _dict.get('categories') ] else: raise ValueError( @@ -5218,9 +4955,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'types') and self.types is not None: - _dict['types'] = [x._to_dict() for x in self.types] + _dict['types'] = [x.to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x._to_dict() for x in self.categories] + _dict['categories'] = [x.to_dict() for x in self.categories] return _dict def _to_dict(self): @@ -5229,7 +4966,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this OriginalLabelsIn object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'OriginalLabelsIn') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5272,19 +5009,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'OriginalLabelsOut': """Initialize a OriginalLabelsOut object from a json dictionary.""" args = {} - valid_keys = ['types', 'categories'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class OriginalLabelsOut: ' - + ', '.join(bad_keys)) if 'types' in _dict: - args['types'] = [ - TypeLabel._from_dict(x) for x in (_dict.get('types')) - ] + args['types'] = [TypeLabel.from_dict(x) for x in _dict.get('types')] if 'categories' in _dict: args['categories'] = [ - Category._from_dict(x) for x in (_dict.get('categories')) + Category.from_dict(x) for x in _dict.get('categories') ] return cls(**args) @@ -5297,9 +5026,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'types') and self.types is not None: - _dict['types'] = [x._to_dict() for x in self.types] + _dict['types'] = [x.to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x._to_dict() for x in self.categories] + _dict['categories'] = [x.to_dict() for x in self.categories] return _dict def _to_dict(self): @@ -5308,7 +5037,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this OriginalLabelsOut object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'OriginalLabelsOut') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5364,14 +5093,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Pagination': """Initialize a Pagination object from a json dictionary.""" args = {} - valid_keys = [ - 'refresh_cursor', 'next_cursor', 'refresh_url', 'next_url', 'total' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Pagination: ' - + ', '.join(bad_keys)) if 'refresh_cursor' in _dict: args['refresh_cursor'] = _dict.get('refresh_cursor') if 'next_cursor' in _dict: @@ -5410,7 +5131,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Pagination object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Pagination') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5446,14 +5167,8 @@ def __init__(self, *, location: 'Location' = None) -> None: def from_dict(cls, _dict: Dict) -> 'Paragraphs': """Initialize a Paragraphs object from a json dictionary.""" args = {} - valid_keys = ['location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Paragraphs: ' - + ', '.join(bad_keys)) if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -5465,7 +5180,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -5474,7 +5189,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Paragraphs object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Paragraphs') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5537,14 +5252,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Parties': """Initialize a Parties object from a json dictionary.""" args = {} - valid_keys = [ - 'party', 'role', 'importance', 'addresses', 'contacts', 'mentions' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Parties: ' + - ', '.join(bad_keys)) if 'party' in _dict: args['party'] = _dict.get('party') if 'role' in _dict: @@ -5553,15 +5260,15 @@ def from_dict(cls, _dict: Dict) -> 'Parties': args['importance'] = _dict.get('importance') if 'addresses' in _dict: args['addresses'] = [ - Address._from_dict(x) for x in (_dict.get('addresses')) + Address.from_dict(x) for x in _dict.get('addresses') ] if 'contacts' in _dict: args['contacts'] = [ - Contact._from_dict(x) for x in (_dict.get('contacts')) + Contact.from_dict(x) for x in _dict.get('contacts') ] if 'mentions' in _dict: args['mentions'] = [ - Mention._from_dict(x) for x in (_dict.get('mentions')) + Mention.from_dict(x) for x in _dict.get('mentions') ] return cls(**args) @@ -5580,11 +5287,11 @@ def to_dict(self) -> Dict: if hasattr(self, 'importance') and self.importance is not None: _dict['importance'] = self.importance if hasattr(self, 'addresses') and self.addresses is not None: - _dict['addresses'] = [x._to_dict() for x in self.addresses] + _dict['addresses'] = [x.to_dict() for x in self.addresses] if hasattr(self, 'contacts') and self.contacts is not None: - _dict['contacts'] = [x._to_dict() for x in self.contacts] + _dict['contacts'] = [x.to_dict() for x in self.contacts] if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = [x._to_dict() for x in self.mentions] + _dict['mentions'] = [x.to_dict() for x in self.mentions] return _dict def _to_dict(self): @@ -5593,7 +5300,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Parties object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Parties') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5605,12 +5312,12 @@ def __ne__(self, other: 'Parties') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ImportanceEnum(Enum): + class ImportanceEnum(str, Enum): """ A string that identifies the importance of the party. """ - PRIMARY = "Primary" - UNKNOWN = "Unknown" + PRIMARY = 'Primary' + UNKNOWN = 'Unknown' class PaymentTerms(): @@ -5670,15 +5377,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'PaymentTerms': """Initialize a PaymentTerms object from a json dictionary.""" args = {} - valid_keys = [ - 'confidence_level', 'text', 'text_normalized', 'interpretation', - 'provenance_ids', 'location' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class PaymentTerms: ' - + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -5686,12 +5384,12 @@ def from_dict(cls, _dict: Dict) -> 'PaymentTerms': if 'text_normalized' in _dict: args['text_normalized'] = _dict.get('text_normalized') if 'interpretation' in _dict: - args['interpretation'] = Interpretation._from_dict( + args['interpretation'] = Interpretation.from_dict( _dict.get('interpretation')) if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -5711,11 +5409,11 @@ def to_dict(self) -> Dict: 'text_normalized') and self.text_normalized is not None: _dict['text_normalized'] = self.text_normalized if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation._to_dict() + _dict['interpretation'] = self.interpretation.to_dict() if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -5724,7 +5422,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this PaymentTerms object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'PaymentTerms') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5736,13 +5434,13 @@ def __ne__(self, other: 'PaymentTerms') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConfidenceLevelEnum(Enum): + class ConfidenceLevelEnum(str, Enum): """ The confidence level in the identification of the payment term. """ - HIGH = "High" - MEDIUM = "Medium" - LOW = "Low" + HIGH = 'High' + MEDIUM = 'Medium' + LOW = 'Low' class RowHeaders(): @@ -5814,19 +5512,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RowHeaders': """Initialize a RowHeaders object from a json dictionary.""" args = {} - valid_keys = [ - 'cell_id', 'location', 'text', 'text_normalized', 'row_index_begin', - 'row_index_end', 'column_index_begin', 'column_index_end' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RowHeaders: ' - + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'text_normalized' in _dict: @@ -5852,7 +5541,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -5878,7 +5567,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RowHeaders object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RowHeaders') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5920,16 +5609,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SectionTitle': """Initialize a SectionTitle object from a json dictionary.""" args = {} - valid_keys = ['text', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SectionTitle: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -5943,7 +5626,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -5952,7 +5635,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SectionTitle object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SectionTitle') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6012,22 +5695,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SectionTitles': """Initialize a SectionTitles object from a json dictionary.""" args = {} - valid_keys = ['text', 'location', 'level', 'element_locations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SectionTitles: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'level' in _dict: args['level'] = _dict.get('level') if 'element_locations' in _dict: args['element_locations'] = [ - ElementLocations._from_dict(x) - for x in (_dict.get('element_locations')) + ElementLocations.from_dict(x) + for x in _dict.get('element_locations') ] return cls(**args) @@ -6042,13 +5719,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'level') and self.level is not None: _dict['level'] = self.level if hasattr(self, 'element_locations') and self.element_locations is not None: _dict['element_locations'] = [ - x._to_dict() for x in self.element_locations + x.to_dict() for x in self.element_locations ] return _dict @@ -6058,7 +5735,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SectionTitles object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SectionTitles') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6094,12 +5771,6 @@ def __init__(self, *, title: str = None, hash: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ShortDoc': """Initialize a ShortDoc object from a json dictionary.""" args = {} - valid_keys = ['title', 'hash'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ShortDoc: ' - + ', '.join(bad_keys)) if 'title' in _dict: args['title'] = _dict.get('title') if 'hash' in _dict: @@ -6126,7 +5797,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ShortDoc object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ShortDoc') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6199,15 +5870,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableHeaders': """Initialize a TableHeaders object from a json dictionary.""" args = {} - valid_keys = [ - 'cell_id', 'location', 'text', 'row_index_begin', 'row_index_end', - 'column_index_begin', 'column_index_end' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableHeaders: ' - + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: @@ -6258,7 +5920,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableHeaders object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableHeaders') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6309,22 +5971,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableReturn': """Initialize a TableReturn object from a json dictionary.""" args = {} - valid_keys = ['document', 'model_id', 'model_version', 'tables'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableReturn: ' - + ', '.join(bad_keys)) if 'document' in _dict: - args['document'] = DocInfo._from_dict(_dict.get('document')) + args['document'] = DocInfo.from_dict(_dict.get('document')) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') if 'model_version' in _dict: args['model_version'] = _dict.get('model_version') if 'tables' in _dict: - args['tables'] = [ - Tables._from_dict(x) for x in (_dict.get('tables')) - ] + args['tables'] = [Tables.from_dict(x) for x in _dict.get('tables')] return cls(**args) @classmethod @@ -6336,13 +5990,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document._to_dict() + _dict['document'] = self.document.to_dict() if hasattr(self, 'model_id') and self.model_id is not None: _dict['model_id'] = self.model_id if hasattr(self, 'model_version') and self.model_version is not None: _dict['model_version'] = self.model_version if hasattr(self, 'tables') and self.tables is not None: - _dict['tables'] = [x._to_dict() for x in self.tables] + _dict['tables'] = [x.to_dict() for x in self.tables] return _dict def _to_dict(self): @@ -6351,7 +6005,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableReturn object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableReturn') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6396,14 +6050,8 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableTitle': """Initialize a TableTitle object from a json dictionary.""" args = {} - valid_keys = ['location', 'text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableTitle: ' - + ', '.join(bad_keys)) if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -6417,7 +6065,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict @@ -6428,7 +6076,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableTitle object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableTitle') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6532,50 +6180,38 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Tables': """Initialize a Tables object from a json dictionary.""" args = {} - valid_keys = [ - 'location', 'text', 'section_title', 'title', 'table_headers', - 'row_headers', 'column_headers', 'body_cells', 'contexts', - 'key_value_pairs' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Tables: ' + - ', '.join(bad_keys)) if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'section_title' in _dict: - args['section_title'] = SectionTitle._from_dict( + args['section_title'] = SectionTitle.from_dict( _dict.get('section_title')) if 'title' in _dict: - args['title'] = TableTitle._from_dict(_dict.get('title')) + args['title'] = TableTitle.from_dict(_dict.get('title')) if 'table_headers' in _dict: args['table_headers'] = [ - TableHeaders._from_dict(x) for x in (_dict.get('table_headers')) + TableHeaders.from_dict(x) for x in _dict.get('table_headers') ] if 'row_headers' in _dict: args['row_headers'] = [ - RowHeaders._from_dict(x) for x in (_dict.get('row_headers')) + RowHeaders.from_dict(x) for x in _dict.get('row_headers') ] if 'column_headers' in _dict: args['column_headers'] = [ - ColumnHeaders._from_dict(x) - for x in (_dict.get('column_headers')) + ColumnHeaders.from_dict(x) for x in _dict.get('column_headers') ] if 'body_cells' in _dict: args['body_cells'] = [ - BodyCells._from_dict(x) for x in (_dict.get('body_cells')) + BodyCells.from_dict(x) for x in _dict.get('body_cells') ] if 'contexts' in _dict: args['contexts'] = [ - Contexts._from_dict(x) for x in (_dict.get('contexts')) + Contexts.from_dict(x) for x in _dict.get('contexts') ] if 'key_value_pairs' in _dict: args['key_value_pairs'] = [ - KeyValuePair._from_dict(x) - for x in (_dict.get('key_value_pairs')) + KeyValuePair.from_dict(x) for x in _dict.get('key_value_pairs') ] return cls(**args) @@ -6588,29 +6224,27 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'section_title') and self.section_title is not None: - _dict['section_title'] = self.section_title._to_dict() + _dict['section_title'] = self.section_title.to_dict() if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title._to_dict() + _dict['title'] = self.title.to_dict() if hasattr(self, 'table_headers') and self.table_headers is not None: - _dict['table_headers'] = [x._to_dict() for x in self.table_headers] + _dict['table_headers'] = [x.to_dict() for x in self.table_headers] if hasattr(self, 'row_headers') and self.row_headers is not None: - _dict['row_headers'] = [x._to_dict() for x in self.row_headers] + _dict['row_headers'] = [x.to_dict() for x in self.row_headers] if hasattr(self, 'column_headers') and self.column_headers is not None: - _dict['column_headers'] = [ - x._to_dict() for x in self.column_headers - ] + _dict['column_headers'] = [x.to_dict() for x in self.column_headers] if hasattr(self, 'body_cells') and self.body_cells is not None: - _dict['body_cells'] = [x._to_dict() for x in self.body_cells] + _dict['body_cells'] = [x.to_dict() for x in self.body_cells] if hasattr(self, 'contexts') and self.contexts is not None: - _dict['contexts'] = [x._to_dict() for x in self.contexts] + _dict['contexts'] = [x.to_dict() for x in self.contexts] if hasattr(self, 'key_value_pairs') and self.key_value_pairs is not None: _dict['key_value_pairs'] = [ - x._to_dict() for x in self.key_value_pairs + x.to_dict() for x in self.key_value_pairs ] return _dict @@ -6620,7 +6254,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Tables object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Tables') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6682,15 +6316,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TerminationDates': """Initialize a TerminationDates object from a json dictionary.""" args = {} - valid_keys = [ - 'confidence_level', 'text', 'text_normalized', 'provenance_ids', - 'location' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TerminationDates: ' - + ', '.join(bad_keys)) if 'confidence_level' in _dict: args['confidence_level'] = _dict.get('confidence_level') if 'text' in _dict: @@ -6700,7 +6325,7 @@ def from_dict(cls, _dict: Dict) -> 'TerminationDates': if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -6722,7 +6347,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -6731,7 +6356,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TerminationDates object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TerminationDates') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6743,13 +6368,13 @@ def __ne__(self, other: 'TerminationDates') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConfidenceLevelEnum(Enum): + class ConfidenceLevelEnum(str, Enum): """ The confidence level in the identification of the termination date. """ - HIGH = "High" - MEDIUM = "Medium" - LOW = "Low" + HIGH = 'High' + MEDIUM = 'Medium' + LOW = 'Low' class TypeLabel(): @@ -6789,14 +6414,8 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TypeLabel': """Initialize a TypeLabel object from a json dictionary.""" args = {} - valid_keys = ['label', 'provenance_ids', 'modification'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TypeLabel: ' - + ', '.join(bad_keys)) if 'label' in _dict: - args['label'] = Label._from_dict(_dict.get('label')) + args['label'] = Label.from_dict(_dict.get('label')) if 'provenance_ids' in _dict: args['provenance_ids'] = _dict.get('provenance_ids') if 'modification' in _dict: @@ -6812,7 +6431,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label._to_dict() + _dict['label'] = self.label.to_dict() if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: _dict['provenance_ids'] = self.provenance_ids if hasattr(self, 'modification') and self.modification is not None: @@ -6825,7 +6444,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TypeLabel object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TypeLabel') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6837,13 +6456,13 @@ def __ne__(self, other: 'TypeLabel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ModificationEnum(Enum): + class ModificationEnum(str, Enum): """ The type of modification of the feedback entry in the updated labels response. """ - ADDED = "added" - UNCHANGED = "unchanged" - REMOVED = "removed" + ADDED = 'added' + UNCHANGED = 'unchanged' + REMOVED = 'removed' class TypeLabelComparison(): @@ -6869,14 +6488,8 @@ def __init__(self, *, label: 'Label' = None) -> None: def from_dict(cls, _dict: Dict) -> 'TypeLabelComparison': """Initialize a TypeLabelComparison object from a json dictionary.""" args = {} - valid_keys = ['label'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TypeLabelComparison: ' - + ', '.join(bad_keys)) if 'label' in _dict: - args['label'] = Label._from_dict(_dict.get('label')) + args['label'] = Label.from_dict(_dict.get('label')) return cls(**args) @classmethod @@ -6888,7 +6501,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label._to_dict() + _dict['label'] = self.label.to_dict() return _dict def _to_dict(self): @@ -6897,7 +6510,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TypeLabelComparison object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TypeLabelComparison') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6965,33 +6578,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'UnalignedElement': """Initialize a UnalignedElement object from a json dictionary.""" args = {} - valid_keys = [ - 'document_label', 'location', 'text', 'types', 'categories', - 'attributes' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class UnalignedElement: ' - + ', '.join(bad_keys)) if 'document_label' in _dict: args['document_label'] = _dict.get('document_label') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'types' in _dict: args['types'] = [ - TypeLabelComparison._from_dict(x) for x in (_dict.get('types')) + TypeLabelComparison.from_dict(x) for x in _dict.get('types') ] if 'categories' in _dict: args['categories'] = [ - CategoryComparison._from_dict(x) - for x in (_dict.get('categories')) + CategoryComparison.from_dict(x) for x in _dict.get('categories') ] if 'attributes' in _dict: args['attributes'] = [ - Attribute._from_dict(x) for x in (_dict.get('attributes')) + Attribute.from_dict(x) for x in _dict.get('attributes') ] return cls(**args) @@ -7006,15 +6609,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'document_label') and self.document_label is not None: _dict['document_label'] = self.document_label if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'types') and self.types is not None: - _dict['types'] = [x._to_dict() for x in self.types] + _dict['types'] = [x.to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x._to_dict() for x in self.categories] + _dict['categories'] = [x.to_dict() for x in self.categories] if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x._to_dict() for x in self.attributes] + _dict['attributes'] = [x.to_dict() for x in self.attributes] return _dict def _to_dict(self): @@ -7023,7 +6626,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this UnalignedElement object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'UnalignedElement') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7063,23 +6666,15 @@ def __init__(self, types: List['TypeLabel'], def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsIn': """Initialize a UpdatedLabelsIn object from a json dictionary.""" args = {} - valid_keys = ['types', 'categories'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class UpdatedLabelsIn: ' - + ', '.join(bad_keys)) if 'types' in _dict: - args['types'] = [ - TypeLabel._from_dict(x) for x in (_dict.get('types')) - ] + args['types'] = [TypeLabel.from_dict(x) for x in _dict.get('types')] else: raise ValueError( 'Required property \'types\' not present in UpdatedLabelsIn JSON' ) if 'categories' in _dict: args['categories'] = [ - Category._from_dict(x) for x in (_dict.get('categories')) + Category.from_dict(x) for x in _dict.get('categories') ] else: raise ValueError( @@ -7096,9 +6691,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'types') and self.types is not None: - _dict['types'] = [x._to_dict() for x in self.types] + _dict['types'] = [x.to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x._to_dict() for x in self.categories] + _dict['categories'] = [x.to_dict() for x in self.categories] return _dict def _to_dict(self): @@ -7107,7 +6702,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this UpdatedLabelsIn object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'UpdatedLabelsIn') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7150,19 +6745,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsOut': """Initialize a UpdatedLabelsOut object from a json dictionary.""" args = {} - valid_keys = ['types', 'categories'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class UpdatedLabelsOut: ' - + ', '.join(bad_keys)) if 'types' in _dict: - args['types'] = [ - TypeLabel._from_dict(x) for x in (_dict.get('types')) - ] + args['types'] = [TypeLabel.from_dict(x) for x in _dict.get('types')] if 'categories' in _dict: args['categories'] = [ - Category._from_dict(x) for x in (_dict.get('categories')) + Category.from_dict(x) for x in _dict.get('categories') ] return cls(**args) @@ -7175,9 +6762,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'types') and self.types is not None: - _dict['types'] = [x._to_dict() for x in self.types] + _dict['types'] = [x.to_dict() for x in self.types] if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x._to_dict() for x in self.categories] + _dict['categories'] = [x.to_dict() for x in self.categories] return _dict def _to_dict(self): @@ -7186,7 +6773,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this UpdatedLabelsOut object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'UpdatedLabelsOut') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7234,16 +6821,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Value': """Initialize a Value object from a json dictionary.""" args = {} - valid_keys = ['cell_id', 'location', 'text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Value: ' + - ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -7259,7 +6840,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict @@ -7270,7 +6851,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Value object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Value') -> bool: """Return `true` when self and other are equal, false otherwise.""" diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 8511b5856..4eb67664e 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ IBM Watson™ Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive @@ -21,22 +23,21 @@ results. """ -import json -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers from datetime import date 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.get_authenticator import get_authenticator_from_environment from os.path import basename -from typing import BinaryIO -from typing import Dict -from typing import List +from typing import BinaryIO, Dict, List +import json import sys +from ibm_cloud_sdk_core import BaseService, DetailedResponse +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from ibm_cloud_sdk_core.utils import convert_list, convert_model, date_to_string, datetime_to_string, string_to_date, string_to_datetime + +from .common import get_sdk_headers + ############################################################################## # Service ############################################################################## @@ -57,27 +58,21 @@ def __init__( """ Construct a new client for the Discovery service. - :param str version: The API version date to use with the service, in - "YYYY-MM-DD" format. Whenever the API is changed in a backwards - incompatible way, a new minor version of the API is released. - The service uses the API version for the date you specify, or - the most recent version before that date. Note that you should - not programmatically specify the current date at runtime, in - case the API has been updated since your application's release. - Instead, specify a version date that is compatible with your - application, and don't change it until your application is - ready for a later version. + :param str version: Release date of the version of the API you want to use. + Specify dates in YYYY-MM-DD format. The current version is `2019-04-30`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + if version is None: + raise ValueError('version must be provided') + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.version = version self.configure_service(service_name) @@ -90,7 +85,7 @@ def create_environment(self, *, description: str = None, size: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create an environment. @@ -106,15 +101,12 @@ def create_environment(self, `S`. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Environment` object """ if name is None: raise ValueError('name 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='V1', operation_id='create_environment') @@ -123,6 +115,13 @@ def create_environment(self, params = {'version': self.version} data = {'name': name, 'description': description, 'size': size} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v1/environments' request = self.prepare_request(method='POST', @@ -137,7 +136,7 @@ def create_environment(self, def list_environments(self, *, name: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List environments. @@ -146,12 +145,10 @@ def list_environments(self, :param str name: (optional) Show only the environment with the given name. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ListEnvironmentsResponse` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='list_environments') @@ -159,6 +156,10 @@ def list_environments(self, params = {'version': self.version, 'name': name} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/environments' request = self.prepare_request(method='GET', url=url, @@ -169,22 +170,19 @@ def list_environments(self, return response def get_environment(self, environment_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get environment info. :param str environment_id: The ID of the environment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Environment` object """ if environment_id is None: raise ValueError('environment_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='V1', operation_id='get_environment') @@ -192,8 +190,14 @@ def get_environment(self, environment_id: str, params = {'version': self.version} - url = '/v1/environments/{0}'.format( - *self._encode_path_vars(environment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -208,7 +212,7 @@ def update_environment(self, name: str = None, description: str = None, size: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update an environment. @@ -223,15 +227,12 @@ def update_environment(self, size can only increased and not decreased. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Environment` object """ if environment_id is None: raise ValueError('environment_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='V1', operation_id='update_environment') @@ -240,9 +241,18 @@ def update_environment(self, params = {'version': self.version} data = {'name': name, 'description': description, 'size': size} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/environments/{0}'.format( - *self._encode_path_vars(environment_id)) + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}'.format(**path_param_dict) request = self.prepare_request(method='PUT', url=url, headers=headers, @@ -253,22 +263,19 @@ def update_environment(self, return response def delete_environment(self, environment_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete environment. :param str environment_id: The ID of the environment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DeleteEnvironmentResponse` object """ if environment_id is None: raise ValueError('environment_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='V1', operation_id='delete_environment') @@ -276,8 +283,14 @@ def delete_environment(self, environment_id: str, params = {'version': self.version} - url = '/v1/environments/{0}'.format( - *self._encode_path_vars(environment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -287,7 +300,7 @@ def delete_environment(self, environment_id: str, return response def list_fields(self, environment_id: str, collection_ids: List[str], - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List fields across collections. @@ -299,17 +312,14 @@ def list_fields(self, environment_id: str, collection_ids: List[str], to be queried against. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ListCollectionFieldsResponse` object """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_ids is None: raise ValueError('collection_ids 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='V1', operation_id='list_fields') @@ -317,11 +327,18 @@ def list_fields(self, environment_id: str, collection_ids: List[str], params = { 'version': self.version, - 'collection_ids': self._convert_list(collection_ids) + 'collection_ids': convert_list(collection_ids) } - url = '/v1/environments/{0}/fields'.format( - *self._encode_path_vars(environment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/fields'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -344,7 +361,7 @@ def create_configuration( enrichments: List['Enrichment'] = None, normalizations: List['NormalizationOperation'] = None, source: 'Source' = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add configuration. @@ -374,7 +391,7 @@ def create_configuration( the configuration. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Configuration` object """ if environment_id is None: @@ -382,17 +399,14 @@ def create_configuration( if name is None: raise ValueError('name must be provided') if conversions is not None: - conversions = self._convert_model(conversions) + conversions = convert_model(conversions) if enrichments is not None: - enrichments = [self._convert_model(x) for x in enrichments] + enrichments = [convert_model(x) for x in enrichments] if normalizations is not None: - normalizations = [self._convert_model(x) for x in normalizations] + normalizations = [convert_model(x) for x in normalizations] if source is not None: - source = self._convert_model(source) - + source = convert_model(source) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_configuration') @@ -408,9 +422,19 @@ def create_configuration( 'normalizations': normalizations, 'source': source } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/environments/{0}/configurations'.format( - *self._encode_path_vars(environment_id)) + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/configurations'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -424,7 +448,7 @@ def list_configurations(self, environment_id: str, *, name: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List configurations. @@ -434,15 +458,12 @@ def list_configurations(self, :param str name: (optional) Find configurations with the given name. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ListConfigurationsResponse` object """ if environment_id is None: raise ValueError('environment_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='V1', operation_id='list_configurations') @@ -450,8 +471,15 @@ def list_configurations(self, params = {'version': self.version, 'name': name} - url = '/v1/environments/{0}/configurations'.format( - *self._encode_path_vars(environment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/configurations'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -461,7 +489,7 @@ def list_configurations(self, return response def get_configuration(self, environment_id: str, configuration_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get configuration details. @@ -469,17 +497,14 @@ def get_configuration(self, environment_id: str, configuration_id: str, :param str configuration_id: The ID of the configuration. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Configuration` object """ if environment_id is None: raise ValueError('environment_id must be provided') if configuration_id is None: raise ValueError('configuration_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='V1', operation_id='get_configuration') @@ -487,8 +512,16 @@ def get_configuration(self, environment_id: str, configuration_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/configurations/{1}'.format( - *self._encode_path_vars(environment_id, configuration_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'configuration_id'] + path_param_values = self.encode_path_vars(environment_id, + configuration_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -508,7 +541,7 @@ def update_configuration( enrichments: List['Enrichment'] = None, normalizations: List['NormalizationOperation'] = None, source: 'Source' = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update a configuration. @@ -538,7 +571,7 @@ def update_configuration( the configuration. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Configuration` object """ if environment_id is None: @@ -548,17 +581,14 @@ def update_configuration( if name is None: raise ValueError('name must be provided') if conversions is not None: - conversions = self._convert_model(conversions) + conversions = convert_model(conversions) if enrichments is not None: - enrichments = [self._convert_model(x) for x in enrichments] + enrichments = [convert_model(x) for x in enrichments] if normalizations is not None: - normalizations = [self._convert_model(x) for x in normalizations] + normalizations = [convert_model(x) for x in normalizations] if source is not None: - source = self._convert_model(source) - + source = convert_model(source) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='update_configuration') @@ -574,9 +604,20 @@ def update_configuration( 'normalizations': normalizations, 'source': source } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/environments/{0}/configurations/{1}'.format( - *self._encode_path_vars(environment_id, configuration_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'configuration_id'] + path_param_values = self.encode_path_vars(environment_id, + configuration_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( + **path_param_dict) request = self.prepare_request(method='PUT', url=url, headers=headers, @@ -587,7 +628,7 @@ def update_configuration( return response def delete_configuration(self, environment_id: str, configuration_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a configuration. @@ -602,17 +643,14 @@ def delete_configuration(self, environment_id: str, configuration_id: str, :param str configuration_id: The ID of the configuration. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DeleteConfigurationResponse` object """ if environment_id is None: raise ValueError('environment_id must be provided') if configuration_id is None: raise ValueError('configuration_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='V1', operation_id='delete_configuration') @@ -620,8 +658,16 @@ def delete_configuration(self, environment_id: str, configuration_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/configurations/{1}'.format( - *self._encode_path_vars(environment_id, configuration_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'configuration_id'] + path_param_values = self.encode_path_vars(environment_id, + configuration_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -641,7 +687,7 @@ def create_collection(self, description: str = None, configuration_id: str = None, language: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create a collection. @@ -654,17 +700,14 @@ def create_collection(self, collection, in the form of an ISO 639-1 language code. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Collection` object """ if environment_id is None: raise ValueError('environment_id must be provided') if name is None: raise ValueError('name 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='V1', operation_id='create_collection') @@ -678,9 +721,19 @@ def create_collection(self, 'configuration_id': configuration_id, 'language': language } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/environments/{0}/collections'.format( - *self._encode_path_vars(environment_id)) + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -694,7 +747,7 @@ def list_collections(self, environment_id: str, *, name: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List collections. @@ -704,15 +757,12 @@ def list_collections(self, :param str name: (optional) Find collections with the given name. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object """ if environment_id is None: raise ValueError('environment_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='V1', operation_id='list_collections') @@ -720,8 +770,15 @@ def list_collections(self, params = {'version': self.version, 'name': name} - url = '/v1/environments/{0}/collections'.format( - *self._encode_path_vars(environment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -731,7 +788,7 @@ def list_collections(self, return response def get_collection(self, environment_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get collection details. @@ -739,17 +796,14 @@ def get_collection(self, environment_id: str, collection_id: str, :param str collection_id: The ID 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 + :rtype: DetailedResponse with `dict` result representing a `Collection` object """ if environment_id is None: raise ValueError('environment_id must be provided') 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='V1', operation_id='get_collection') @@ -757,8 +811,15 @@ def get_collection(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -774,7 +835,7 @@ def update_collection(self, *, description: str = None, configuration_id: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update a collection. @@ -786,7 +847,7 @@ def update_collection(self, which the collection is to be updated. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Collection` object """ if environment_id is None: @@ -795,10 +856,7 @@ def update_collection(self, raise ValueError('collection_id must be provided') if name is None: raise ValueError('name 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='V1', operation_id='update_collection') @@ -811,9 +869,19 @@ def update_collection(self, 'description': description, 'configuration_id': configuration_id } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/environments/{0}/collections/{1}'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( + **path_param_dict) request = self.prepare_request(method='PUT', url=url, headers=headers, @@ -824,7 +892,7 @@ def update_collection(self, return response def delete_collection(self, environment_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a collection. @@ -832,17 +900,14 @@ def delete_collection(self, environment_id: str, collection_id: str, :param str collection_id: The ID 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 + :rtype: DetailedResponse with `dict` result representing a `DeleteCollectionResponse` object """ if environment_id is None: raise ValueError('environment_id must be provided') 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='V1', operation_id='delete_collection') @@ -850,8 +915,15 @@ def delete_collection(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -861,7 +933,7 @@ def delete_collection(self, environment_id: str, collection_id: str, return response def list_collection_fields(self, environment_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List collection fields. @@ -871,17 +943,14 @@ def list_collection_fields(self, environment_id: str, collection_id: str, :param str collection_id: The ID 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 + :rtype: DetailedResponse with `dict` result representing a `ListCollectionFieldsResponse` object """ if environment_id is None: raise ValueError('environment_id must be provided') 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='V1', operation_id='list_collection_fields') @@ -889,8 +958,15 @@ def list_collection_fields(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/fields'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/fields'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -904,7 +980,7 @@ def list_collection_fields(self, environment_id: str, collection_id: str, ######################### def list_expansions(self, environment_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get the expansion list. @@ -915,17 +991,14 @@ def list_expansions(self, environment_id: str, collection_id: str, :param str collection_id: The ID 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 + :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ if environment_id is None: raise ValueError('environment_id must be provided') 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='V1', operation_id='list_expansions') @@ -933,8 +1006,15 @@ def list_expansions(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/expansions'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -945,7 +1025,7 @@ def list_expansions(self, environment_id: str, collection_id: str, def create_expansions(self, environment_id: str, collection_id: str, expansions: List['Expansion'], - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create or update expansion list. @@ -970,7 +1050,7 @@ def create_expansions(self, environment_id: str, collection_id: str, items listed in the **expanded_terms** array. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ if environment_id is None: @@ -979,11 +1059,8 @@ def create_expansions(self, environment_id: str, collection_id: str, raise ValueError('collection_id must be provided') if expansions is None: raise ValueError('expansions must be provided') - expansions = [self._convert_model(x) for x in expansions] - + expansions = [convert_model(x) for x in expansions] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_expansions') @@ -992,9 +1069,19 @@ def create_expansions(self, environment_id: str, collection_id: str, params = {'version': self.version} data = {'expansions': expansions} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/environments/{0}/collections/{1}/expansions'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1005,7 +1092,7 @@ def create_expansions(self, environment_id: str, collection_id: str, return response def delete_expansions(self, environment_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete the expansion list. @@ -1023,10 +1110,7 @@ def delete_expansions(self, environment_id: str, collection_id: str, raise ValueError('environment_id must be provided') 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='V1', operation_id='delete_expansions') @@ -1034,8 +1118,14 @@ def delete_expansions(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/expansions'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1046,7 +1136,7 @@ def delete_expansions(self, environment_id: str, collection_id: str, def get_tokenization_dictionary_status(self, environment_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get tokenization dictionary status. @@ -1057,17 +1147,14 @@ def get_tokenization_dictionary_status(self, environment_id: str, :param str collection_id: The ID 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 + :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ if environment_id is None: raise ValueError('environment_id must be provided') 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='V1', @@ -1076,8 +1163,15 @@ def get_tokenization_dictionary_status(self, environment_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1092,7 +1186,7 @@ def create_tokenization_dictionary( collection_id: str, *, tokenization_rules: List['TokenDictRule'] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create tokenization dictionary. @@ -1106,7 +1200,7 @@ def create_tokenization_dictionary( `part_of_speech` the text is from. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ if environment_id is None: @@ -1114,13 +1208,8 @@ def create_tokenization_dictionary( if collection_id is None: raise ValueError('collection_id must be provided') if tokenization_rules is not None: - tokenization_rules = [ - self._convert_model(x) for x in tokenization_rules - ] - + tokenization_rules = [convert_model(x) for x in tokenization_rules] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', @@ -1130,9 +1219,19 @@ def create_tokenization_dictionary( params = {'version': self.version} data = {'tokenization_rules': tokenization_rules} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1144,7 +1243,7 @@ def create_tokenization_dictionary( def delete_tokenization_dictionary(self, environment_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete tokenization dictionary. @@ -1161,10 +1260,7 @@ def delete_tokenization_dictionary(self, environment_id: str, raise ValueError('environment_id must be provided') 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='V1', @@ -1173,8 +1269,14 @@ def delete_tokenization_dictionary(self, environment_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1184,7 +1286,7 @@ def delete_tokenization_dictionary(self, environment_id: str, return response def get_stopword_list_status(self, environment_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get stopword list status. @@ -1194,17 +1296,14 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, :param str collection_id: The ID 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 + :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ if environment_id is None: raise ValueError('environment_id must be provided') 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='V1', operation_id='get_stopword_list_status') @@ -1212,8 +1311,15 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1228,7 +1334,7 @@ def create_stopword_list(self, stopword_file: BinaryIO, *, stopword_filename: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create stopword list. @@ -1236,11 +1342,11 @@ def create_stopword_list(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param TextIO stopword_file: The content of the stopword list to ingest. + :param BinaryIO stopword_file: The content of the stopword list to ingest. :param str stopword_filename: (optional) The filename for stopword_file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ if environment_id is None: @@ -1249,10 +1355,7 @@ def create_stopword_list(self, raise ValueError('collection_id must be provided') if stopword_file is None: raise ValueError('stopword_file 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='V1', operation_id='create_stopword_list') @@ -1268,8 +1371,15 @@ def create_stopword_list(self, form_data.append(('stopword_file', (stopword_filename, stopword_file, 'application/octet-stream'))) - url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1280,7 +1390,7 @@ def create_stopword_list(self, return response def delete_stopword_list(self, environment_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a custom stopword list. @@ -1298,10 +1408,7 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, raise ValueError('environment_id must be provided') 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='V1', operation_id='delete_stopword_list') @@ -1309,8 +1416,14 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1331,7 +1444,7 @@ def add_document(self, filename: str = None, file_content_type: str = None, metadata: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add a document. @@ -1353,12 +1466,12 @@ def add_document(self, * Fields containing the following characters after normalization are filtered out before indexing: `#` and `,` **Note:** Documents can be added with a specific **document_id** by using the - **_/v1/environments/{environment_id}/collections/{collection_id}/documents** + **/v1/environments/{environment_id}/collections/{collection_id}/documents** method. :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. - :param TextIO file: (optional) The content of the document to ingest. The + :param BinaryIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. @@ -1371,17 +1484,14 @@ def add_document(self, } ```. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ if environment_id is None: raise ValueError('environment_id must be provided') 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='V1', operation_id='add_document') @@ -1398,11 +1508,17 @@ def add_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: - metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) - url = '/v1/environments/{0}/collections/{1}/documents'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/documents'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1413,7 +1529,7 @@ def add_document(self, return response def get_document_status(self, environment_id: str, collection_id: str, - document_id: str, **kwargs) -> 'DetailedResponse': + document_id: str, **kwargs) -> DetailedResponse: """ Get document details. @@ -1427,7 +1543,7 @@ def get_document_status(self, environment_id: str, collection_id: str, :param str document_id: The ID of the document. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object """ if environment_id is None: @@ -1436,10 +1552,7 @@ def get_document_status(self, environment_id: str, collection_id: str, raise ValueError('collection_id must be provided') if document_id is None: raise ValueError('document_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='V1', operation_id='get_document_status') @@ -1447,8 +1560,16 @@ def get_document_status(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( - *self._encode_path_vars(environment_id, collection_id, document_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id', 'document_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id, + document_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1466,7 +1587,7 @@ def update_document(self, filename: str = None, file_content_type: str = None, metadata: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update a document. @@ -1478,7 +1599,7 @@ def update_document(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param TextIO file: (optional) The content of the document to ingest. The + :param BinaryIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. @@ -1491,7 +1612,7 @@ def update_document(self, } ```. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ if environment_id is None: @@ -1500,10 +1621,7 @@ def update_document(self, raise ValueError('collection_id must be provided') if document_id is None: raise ValueError('document_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='V1', operation_id='update_document') @@ -1520,11 +1638,18 @@ def update_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: - metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) - url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( - *self._encode_path_vars(environment_id, collection_id, document_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id', 'document_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id, + document_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1535,7 +1660,7 @@ def update_document(self, return response def delete_document(self, environment_id: str, collection_id: str, - document_id: str, **kwargs) -> 'DetailedResponse': + document_id: str, **kwargs) -> DetailedResponse: """ Delete a document. @@ -1548,7 +1673,7 @@ def delete_document(self, environment_id: str, collection_id: str, :param str document_id: The ID of the document. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DeleteDocumentResponse` object """ if environment_id is None: @@ -1557,10 +1682,7 @@ def delete_document(self, environment_id: str, collection_id: str, raise ValueError('collection_id must be provided') if document_id is None: raise ValueError('document_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='V1', operation_id='delete_document') @@ -1568,8 +1690,16 @@ def delete_document(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/documents/{2}'.format( - *self._encode_path_vars(environment_id, collection_id, document_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id', 'document_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id, + document_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1607,7 +1737,7 @@ def query(self, bias: str = None, spelling_suggestions: bool = None, x_watson_logging_opt_out: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Query a collection. @@ -1693,17 +1823,14 @@ def query(self, stored in the Discovery **Logs** endpoint. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') - headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='query') @@ -1733,9 +1860,19 @@ def query(self, 'bias': bias, 'spelling_suggestions': spelling_suggestions } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/environments/{0}/collections/{1}/query'.format( - *self._encode_path_vars(environment_id, collection_id)) + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/query'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1766,7 +1903,7 @@ def query_notices(self, similar: bool = None, similar_document_ids: List[str] = None, similar_fields: List[str] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Query system notices. @@ -1834,17 +1971,14 @@ def query_notices(self, documents. If not specified, the entire document is used for comparison. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ if environment_id is None: raise ValueError('environment_id must be provided') 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='V1', operation_id='query_notices') @@ -1858,21 +1992,28 @@ def query_notices(self, 'passages': passages, 'aggregation': aggregation, 'count': count, - 'return': self._convert_list(return_), + 'return': convert_list(return_), 'offset': offset, - 'sort': self._convert_list(sort), + 'sort': convert_list(sort), 'highlight': highlight, - 'passages.fields': self._convert_list(passages_fields), + 'passages.fields': convert_list(passages_fields), 'passages.count': passages_count, 'passages.characters': passages_characters, 'deduplicate.field': deduplicate_field, 'similar': similar, - 'similar.document_ids': self._convert_list(similar_document_ids), - 'similar.fields': self._convert_list(similar_fields) + 'similar.document_ids': convert_list(similar_document_ids), + 'similar.fields': convert_list(similar_fields) } - url = '/v1/environments/{0}/collections/{1}/notices'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/notices'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1905,7 +2046,7 @@ def federated_query(self, similar_fields: str = None, bias: str = None, x_watson_logging_opt_out: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Query multiple collections. @@ -1986,17 +2127,14 @@ def federated_query(self, stored in the Discovery **Logs** endpoint. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_ids is None: raise ValueError('collection_ids must be provided') - headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='federated_query') @@ -2026,9 +2164,19 @@ def federated_query(self, 'similar.fields': similar_fields, 'bias': bias } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/environments/{0}/query'.format( - *self._encode_path_vars(environment_id)) + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/query'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -2055,7 +2203,7 @@ def federated_query_notices(self, similar: bool = None, similar_document_ids: List[str] = None, similar_fields: List[str] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Query multiple collection system notices. @@ -2114,17 +2262,14 @@ def federated_query_notices(self, documents. If not specified, the entire document is used for comparison. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ if environment_id is None: raise ValueError('environment_id must be provided') if collection_ids is None: raise ValueError('collection_ids 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='V1', operation_id='federated_query_notices') @@ -2132,24 +2277,31 @@ def federated_query_notices(self, params = { 'version': self.version, - 'collection_ids': self._convert_list(collection_ids), + 'collection_ids': convert_list(collection_ids), 'filter': filter, 'query': query, 'natural_language_query': natural_language_query, 'aggregation': aggregation, 'count': count, - 'return': self._convert_list(return_), + 'return': convert_list(return_), 'offset': offset, - 'sort': self._convert_list(sort), + 'sort': convert_list(sort), 'highlight': highlight, 'deduplicate.field': deduplicate_field, 'similar': similar, - 'similar.document_ids': self._convert_list(similar_document_ids), - 'similar.fields': self._convert_list(similar_fields) + 'similar.document_ids': convert_list(similar_document_ids), + 'similar.fields': convert_list(similar_fields) } - url = '/v1/environments/{0}/notices'.format( - *self._encode_path_vars(environment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/notices'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2165,7 +2317,7 @@ def get_autocompletion(self, *, field: str = None, count: int = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get Autocomplete Suggestions. @@ -2184,7 +2336,7 @@ def get_autocompletion(self, return. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Completions` object """ if environment_id is None: @@ -2193,10 +2345,7 @@ def get_autocompletion(self, raise ValueError('collection_id must be provided') if prefix is None: raise ValueError('prefix 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='V1', operation_id='get_autocompletion') @@ -2209,8 +2358,15 @@ def get_autocompletion(self, 'count': count } - url = '/v1/environments/{0}/collections/{1}/autocompletion'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/autocompletion'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2224,7 +2380,7 @@ def get_autocompletion(self, ######################### def list_training_data(self, environment_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List training data. @@ -2234,17 +2390,14 @@ def list_training_data(self, environment_id: str, collection_id: str, :param str collection_id: The ID 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 + :rtype: DetailedResponse with `dict` result representing a `TrainingDataSet` object """ if environment_id is None: raise ValueError('environment_id must be provided') 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='V1', operation_id='list_training_data') @@ -2252,8 +2405,15 @@ def list_training_data(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/training_data'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2269,7 +2429,7 @@ def add_training_data(self, natural_language_query: str = None, filter: str = None, examples: List['TrainingExample'] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add query to training data. @@ -2286,7 +2446,7 @@ def add_training_data(self, examples. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ if environment_id is None: @@ -2294,11 +2454,8 @@ def add_training_data(self, if collection_id is None: raise ValueError('collection_id must be provided') if examples is not None: - examples = [self._convert_model(x) for x in examples] - + examples = [convert_model(x) for x in examples] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='add_training_data') @@ -2311,9 +2468,19 @@ def add_training_data(self, 'filter': filter, 'examples': examples } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/environments/{0}/collections/{1}/training_data'.format( - *self._encode_path_vars(environment_id, collection_id)) + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -2324,7 +2491,7 @@ def add_training_data(self, return response def delete_all_training_data(self, environment_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete all training data. @@ -2341,10 +2508,7 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, raise ValueError('environment_id must be provided') 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='V1', operation_id='delete_all_training_data') @@ -2352,8 +2516,14 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/training_data'.format( - *self._encode_path_vars(environment_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['environment_id', 'collection_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -2363,7 +2533,7 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, return response def get_training_data(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> 'DetailedResponse': + query_id: str, **kwargs) -> DetailedResponse: """ Get details about a query. @@ -2375,7 +2545,7 @@ def get_training_data(self, environment_id: str, collection_id: str, :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ if environment_id is None: @@ -2384,10 +2554,7 @@ def get_training_data(self, environment_id: str, collection_id: str, raise ValueError('collection_id must be provided') if query_id is None: raise ValueError('query_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='V1', operation_id='get_training_data') @@ -2395,8 +2562,16 @@ def get_training_data(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( - *self._encode_path_vars(environment_id, collection_id, query_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id', 'query_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id, + query_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2406,7 +2581,7 @@ def get_training_data(self, environment_id: str, collection_id: str, return response def delete_training_data(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> 'DetailedResponse': + query_id: str, **kwargs) -> DetailedResponse: """ Delete a training data query. @@ -2427,10 +2602,7 @@ def delete_training_data(self, environment_id: str, collection_id: str, raise ValueError('collection_id must be provided') if query_id is None: raise ValueError('query_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='V1', operation_id='delete_training_data') @@ -2438,8 +2610,15 @@ def delete_training_data(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format( - *self._encode_path_vars(environment_id, collection_id, query_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['environment_id', 'collection_id', 'query_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id, + query_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -2449,7 +2628,7 @@ def delete_training_data(self, environment_id: str, collection_id: str, return response def list_training_examples(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> 'DetailedResponse': + query_id: str, **kwargs) -> DetailedResponse: """ List examples for a training data query. @@ -2460,7 +2639,7 @@ def list_training_examples(self, environment_id: str, collection_id: str, :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingExampleList` object """ if environment_id is None: @@ -2469,10 +2648,7 @@ def list_training_examples(self, environment_id: str, collection_id: str, raise ValueError('collection_id must be provided') if query_id is None: raise ValueError('query_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='V1', operation_id='list_training_examples') @@ -2480,8 +2656,16 @@ def list_training_examples(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( - *self._encode_path_vars(environment_id, collection_id, query_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id', 'query_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id, + query_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2498,7 +2682,7 @@ def create_training_example(self, document_id: str = None, cross_reference: str = None, relevance: int = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add example to training data query. @@ -2514,7 +2698,7 @@ def create_training_example(self, :param int relevance: (optional) The relevance of the training example. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object """ if environment_id is None: @@ -2523,10 +2707,7 @@ def create_training_example(self, raise ValueError('collection_id must be provided') if query_id is None: raise ValueError('query_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='V1', operation_id='create_training_example') @@ -2539,9 +2720,20 @@ def create_training_example(self, 'cross_reference': cross_reference, 'relevance': relevance } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format( - *self._encode_path_vars(environment_id, collection_id, query_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'collection_id', 'query_id'] + path_param_values = self.encode_path_vars(environment_id, collection_id, + query_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -2553,7 +2745,7 @@ def create_training_example(self, def delete_training_example(self, environment_id: str, collection_id: str, query_id: str, example_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete example for training data query. @@ -2576,10 +2768,7 @@ def delete_training_example(self, environment_id: str, collection_id: str, raise ValueError('query_id must be provided') if example_id is None: raise ValueError('example_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='V1', operation_id='delete_training_example') @@ -2587,9 +2776,17 @@ def delete_training_example(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( - *self._encode_path_vars(environment_id, collection_id, query_id, - example_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = [ + 'environment_id', 'collection_id', 'query_id', 'example_id' + ] + path_param_values = self.encode_path_vars(environment_id, collection_id, + query_id, example_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -2606,7 +2803,7 @@ def update_training_example(self, *, cross_reference: str = None, relevance: int = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Change label or cross reference for example. @@ -2620,7 +2817,7 @@ def update_training_example(self, :param int relevance: (optional) The relevance value for this example. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object """ if environment_id is None: @@ -2631,10 +2828,7 @@ def update_training_example(self, raise ValueError('query_id must be provided') if example_id is None: raise ValueError('example_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='V1', operation_id='update_training_example') @@ -2643,10 +2837,22 @@ def update_training_example(self, params = {'version': self.version} data = {'cross_reference': cross_reference, 'relevance': relevance} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( - *self._encode_path_vars(environment_id, collection_id, query_id, - example_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = [ + 'environment_id', 'collection_id', 'query_id', 'example_id' + ] + path_param_values = self.encode_path_vars(environment_id, collection_id, + query_id, example_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( + **path_param_dict) request = self.prepare_request(method='PUT', url=url, headers=headers, @@ -2658,7 +2864,7 @@ def update_training_example(self, def get_training_example(self, environment_id: str, collection_id: str, query_id: str, example_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get details for training data example. @@ -2670,7 +2876,7 @@ def get_training_example(self, environment_id: str, collection_id: str, :param str example_id: The ID of the document as it is indexed. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object """ if environment_id is None: @@ -2681,10 +2887,7 @@ def get_training_example(self, environment_id: str, collection_id: str, raise ValueError('query_id must be provided') if example_id is None: raise ValueError('example_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='V1', operation_id='get_training_example') @@ -2692,9 +2895,18 @@ def get_training_example(self, environment_id: str, collection_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format( - *self._encode_path_vars(environment_id, collection_id, query_id, - example_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = [ + 'environment_id', 'collection_id', 'query_id', 'example_id' + ] + path_param_values = self.encode_path_vars(environment_id, collection_id, + query_id, example_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -2707,8 +2919,7 @@ def get_training_example(self, environment_id: str, collection_id: str, # User data ######################### - def delete_user_data(self, customer_id: str, - **kwargs) -> 'DetailedResponse': + def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: """ Delete labeled data. @@ -2728,10 +2939,7 @@ def delete_user_data(self, customer_id: str, if customer_id is None: raise ValueError('customer_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='V1', operation_id='delete_user_data') @@ -2739,6 +2947,9 @@ def delete_user_data(self, customer_id: str, params = {'version': self.version, 'customer_id': customer_id} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + url = '/v1/user_data' request = self.prepare_request(method='DELETE', url=url, @@ -2753,7 +2964,7 @@ def delete_user_data(self, customer_id: str, ######################### def create_event(self, type: str, data: 'EventData', - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create event. @@ -2765,18 +2976,15 @@ def create_event(self, type: str, data: 'EventData', :param EventData data: Query event data object. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `CreateEventResponse` object """ if type is None: raise ValueError('type must be provided') if data is None: raise ValueError('data must be provided') - data = self._convert_model(data) - + data = convert_model(data) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_event') @@ -2785,6 +2993,13 @@ def create_event(self, type: str, data: 'EventData', params = {'version': self.version} data = {'type': type, 'data': data} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v1/events' request = self.prepare_request(method='POST', @@ -2803,7 +3018,7 @@ def query_log(self, count: int = None, offset: int = None, sort: List[str] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Search the query and event log. @@ -2829,12 +3044,10 @@ def query_log(self, is the default sort direction if no prefix is specified. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `LogQueryResponse` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='query_log') @@ -2846,9 +3059,13 @@ def query_log(self, 'query': query, 'count': count, 'offset': offset, - 'sort': self._convert_list(sort) + 'sort': convert_list(sort) } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/logs' request = self.prepare_request(method='GET', url=url, @@ -2863,7 +3080,7 @@ def get_metrics_query(self, start_time: datetime = None, end_time: datetime = None, result_type: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Number of queries over time. @@ -2878,12 +3095,10 @@ def get_metrics_query(self, calculating the metric. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='get_metrics_query') @@ -2896,6 +3111,10 @@ def get_metrics_query(self, 'result_type': result_type } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/metrics/number_of_queries' request = self.prepare_request(method='GET', url=url, @@ -2910,7 +3129,7 @@ def get_metrics_query_event(self, start_time: datetime = None, end_time: datetime = None, result_type: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Number of queries with an event over time. @@ -2926,12 +3145,10 @@ def get_metrics_query_event(self, calculating the metric. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='get_metrics_query_event') @@ -2944,6 +3161,10 @@ def get_metrics_query_event(self, 'result_type': result_type } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/metrics/number_of_queries_with_event' request = self.prepare_request(method='GET', url=url, @@ -2958,7 +3179,7 @@ def get_metrics_query_no_results(self, start_time: datetime = None, end_time: datetime = None, result_type: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Number of queries with no search results over time. @@ -2973,12 +3194,10 @@ def get_metrics_query_no_results(self, calculating the metric. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', @@ -2992,6 +3211,10 @@ def get_metrics_query_no_results(self, 'result_type': result_type } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/metrics/number_of_queries_with_no_search_results' request = self.prepare_request(method='GET', url=url, @@ -3006,7 +3229,7 @@ def get_metrics_event_rate(self, start_time: datetime = None, end_time: datetime = None, result_type: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Percentage of queries with an associated event. @@ -3022,12 +3245,10 @@ def get_metrics_event_rate(self, calculating the metric. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='get_metrics_event_rate') @@ -3040,6 +3261,10 @@ def get_metrics_event_rate(self, 'result_type': result_type } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/metrics/event_rate' request = self.prepare_request(method='GET', url=url, @@ -3052,7 +3277,7 @@ def get_metrics_event_rate(self, def get_metrics_query_token_event(self, *, count: int = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Most frequent query tokens with an event. @@ -3065,12 +3290,10 @@ def get_metrics_query_token_event(self, the **count** and **offset** values together in any one query is **10000**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `MetricTokenResponse` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', @@ -3079,6 +3302,10 @@ def get_metrics_query_token_event(self, params = {'version': self.version, 'count': count} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/metrics/top_query_tokens_with_event_rate' request = self.prepare_request(method='GET', url=url, @@ -3093,7 +3320,7 @@ def get_metrics_query_token_event(self, ######################### def list_credentials(self, environment_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List credentials. @@ -3104,15 +3331,12 @@ def list_credentials(self, environment_id: str, :param str environment_id: The ID of the environment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `CredentialsList` object """ if environment_id is None: raise ValueError('environment_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='V1', operation_id='list_credentials') @@ -3120,8 +3344,15 @@ def list_credentials(self, environment_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/credentials'.format( - *self._encode_path_vars(environment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/credentials'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -3136,7 +3367,7 @@ def create_credentials(self, source_type: str = None, credential_details: 'CredentialDetails' = None, status: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create credentials. @@ -3167,17 +3398,14 @@ def create_credentials(self, corrected before they can be used with a collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Credentials` object """ if environment_id is None: raise ValueError('environment_id must be provided') if credential_details is not None: - credential_details = self._convert_model(credential_details) - + credential_details = convert_model(credential_details) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_credentials') @@ -3190,9 +3418,19 @@ def create_credentials(self, 'credential_details': credential_details, 'status': status } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/environments/{0}/credentials'.format( - *self._encode_path_vars(environment_id)) + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/credentials'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -3203,7 +3441,7 @@ def create_credentials(self, return response def get_credentials(self, environment_id: str, credential_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ View Credentials. @@ -3216,17 +3454,14 @@ def get_credentials(self, environment_id: str, credential_id: str, credentials. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Credentials` object """ if environment_id is None: raise ValueError('environment_id must be provided') if credential_id is None: raise ValueError('credential_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='V1', operation_id='get_credentials') @@ -3234,8 +3469,15 @@ def get_credentials(self, environment_id: str, credential_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/credentials/{1}'.format( - *self._encode_path_vars(environment_id, credential_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'credential_id'] + path_param_values = self.encode_path_vars(environment_id, credential_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -3251,7 +3493,7 @@ def update_credentials(self, source_type: str = None, credential_details: 'CredentialDetails' = None, status: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update credentials. @@ -3283,7 +3525,7 @@ def update_credentials(self, corrected before they can be used with a collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Credentials` object """ if environment_id is None: @@ -3291,11 +3533,8 @@ def update_credentials(self, if credential_id is None: raise ValueError('credential_id must be provided') if credential_details is not None: - credential_details = self._convert_model(credential_details) - + credential_details = convert_model(credential_details) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='update_credentials') @@ -3308,9 +3547,19 @@ def update_credentials(self, 'credential_details': credential_details, 'status': status } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/environments/{0}/credentials/{1}'.format( - *self._encode_path_vars(environment_id, credential_id)) + path_param_keys = ['environment_id', 'credential_id'] + path_param_values = self.encode_path_vars(environment_id, credential_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( + **path_param_dict) request = self.prepare_request(method='PUT', url=url, headers=headers, @@ -3321,7 +3570,7 @@ def update_credentials(self, return response def delete_credentials(self, environment_id: str, credential_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete credentials. @@ -3332,17 +3581,14 @@ def delete_credentials(self, environment_id: str, credential_id: str, credentials. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DeleteCredentials` object """ if environment_id is None: raise ValueError('environment_id must be provided') if credential_id is None: raise ValueError('credential_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='V1', operation_id='delete_credentials') @@ -3350,8 +3596,15 @@ def delete_credentials(self, environment_id: str, credential_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/credentials/{1}'.format( - *self._encode_path_vars(environment_id, credential_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'credential_id'] + path_param_values = self.encode_path_vars(environment_id, credential_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -3364,8 +3617,7 @@ def delete_credentials(self, environment_id: str, credential_id: str, # gatewayConfiguration ######################### - def list_gateways(self, environment_id: str, - **kwargs) -> 'DetailedResponse': + def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: """ List Gateways. @@ -3374,15 +3626,12 @@ def list_gateways(self, environment_id: str, :param str environment_id: The ID of the environment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `GatewayList` object """ if environment_id is None: raise ValueError('environment_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='V1', operation_id='list_gateways') @@ -3390,8 +3639,15 @@ def list_gateways(self, environment_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/gateways'.format( - *self._encode_path_vars(environment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/gateways'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -3404,7 +3660,7 @@ def create_gateway(self, environment_id: str, *, name: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create Gateway. @@ -3414,15 +3670,12 @@ def create_gateway(self, :param str name: (optional) User-defined name. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Gateway` object """ if environment_id is None: raise ValueError('environment_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='V1', operation_id='create_gateway') @@ -3431,9 +3684,19 @@ def create_gateway(self, params = {'version': self.version} data = {'name': name} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/environments/{0}/gateways'.format( - *self._encode_path_vars(environment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id'] + path_param_values = self.encode_path_vars(environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/gateways'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -3444,7 +3707,7 @@ def create_gateway(self, return response def get_gateway(self, environment_id: str, gateway_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List Gateway Details. @@ -3454,17 +3717,14 @@ def get_gateway(self, environment_id: str, gateway_id: str, :param str gateway_id: The requested gateway ID. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Gateway` object """ if environment_id is None: raise ValueError('environment_id must be provided') if gateway_id is None: raise ValueError('gateway_id must be provided') - - headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) + headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='get_gateway') @@ -3472,8 +3732,15 @@ def get_gateway(self, environment_id: str, gateway_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/gateways/{1}'.format( - *self._encode_path_vars(environment_id, gateway_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'gateway_id'] + path_param_values = self.encode_path_vars(environment_id, gateway_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -3483,7 +3750,7 @@ def get_gateway(self, environment_id: str, gateway_id: str, return response def delete_gateway(self, environment_id: str, gateway_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete Gateway. @@ -3493,17 +3760,14 @@ def delete_gateway(self, environment_id: str, gateway_id: str, :param str gateway_id: The requested gateway ID. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `GatewayDelete` object """ if environment_id is None: raise ValueError('environment_id must be provided') if gateway_id is None: raise ValueError('gateway_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='V1', operation_id='delete_gateway') @@ -3511,8 +3775,15 @@ def delete_gateway(self, environment_id: str, gateway_id: str, params = {'version': self.version} - url = '/v1/environments/{0}/gateways/{1}'.format( - *self._encode_path_vars(environment_id, gateway_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['environment_id', 'gateway_id'] + path_param_values = self.encode_path_vars(environment_id, gateway_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -3522,9 +3793,12 @@ def delete_gateway(self, environment_id: str, gateway_id: str, return response -class AddDocumentEnums(object): +class AddDocumentEnums: + """ + Enums for add_document parameters. + """ - class FileContentType(Enum): + class FileContentType(str, Enum): """ The content type of file. """ @@ -3536,9 +3810,12 @@ class FileContentType(Enum): APPLICATION_XHTML_XML = 'application/xhtml+xml' -class UpdateDocumentEnums(object): +class UpdateDocumentEnums: + """ + Enums for update_document parameters. + """ - class FileContentType(Enum): + class FileContentType(str, Enum): """ The content type of file. """ @@ -3550,36 +3827,48 @@ class FileContentType(Enum): APPLICATION_XHTML_XML = 'application/xhtml+xml' -class GetMetricsQueryEnums(object): +class GetMetricsQueryEnums: + """ + Enums for get_metrics_query parameters. + """ - class ResultType(Enum): + class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ DOCUMENT = 'document' -class GetMetricsQueryEventEnums(object): +class GetMetricsQueryEventEnums: + """ + Enums for get_metrics_query_event parameters. + """ - class ResultType(Enum): + class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ DOCUMENT = 'document' -class GetMetricsQueryNoResultsEnums(object): +class GetMetricsQueryNoResultsEnums: + """ + Enums for get_metrics_query_no_results parameters. + """ - class ResultType(Enum): + class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ DOCUMENT = 'document' -class GetMetricsEventRateEnums(object): +class GetMetricsEventRateEnums: + """ + Enums for get_metrics_event_rate parameters. + """ - class ResultType(Enum): + class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ @@ -3622,20 +3911,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AggregationResult': """Initialize a AggregationResult object from a json dictionary.""" args = {} - valid_keys = ['key', 'matching_results', 'aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AggregationResult: ' - + ', '.join(bad_keys)) if 'key' in _dict: args['key'] = _dict.get('key') if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] return cls(**args) @@ -3653,7 +3935,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -3662,7 +3944,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AggregationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3721,15 +4003,8 @@ def __init__(self, """ Initialize a Collection object. - :param str collection_id: (optional) The unique identifier of the - collection. :param str name: (optional) The name of the collection. :param str description: (optional) The description of the collection. - :param datetime created: (optional) The creation date of the collection in - the format yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. - :param datetime updated: (optional) The timestamp of when the collection - was last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param str status: (optional) The status of the collection. :param str configuration_id: (optional) The unique identifier of the collection's configuration. :param str language: (optional) The language of the documents stored in the @@ -3763,17 +4038,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} - valid_keys = [ - 'collection_id', 'name', 'description', 'created', 'updated', - 'status', 'configuration_id', 'language', 'document_counts', - 'disk_usage', 'training_status', 'crawl_status', - 'smart_document_understanding' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Collection: ' - + ', '.join(bad_keys)) if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') if 'name' in _dict: @@ -3791,19 +4055,19 @@ def from_dict(cls, _dict: Dict) -> 'Collection': if 'language' in _dict: args['language'] = _dict.get('language') if 'document_counts' in _dict: - args['document_counts'] = DocumentCounts._from_dict( + args['document_counts'] = DocumentCounts.from_dict( _dict.get('document_counts')) if 'disk_usage' in _dict: - args['disk_usage'] = CollectionDiskUsage._from_dict( + args['disk_usage'] = CollectionDiskUsage.from_dict( _dict.get('disk_usage')) if 'training_status' in _dict: - args['training_status'] = TrainingStatus._from_dict( + args['training_status'] = TrainingStatus.from_dict( _dict.get('training_status')) if 'crawl_status' in _dict: - args['crawl_status'] = CollectionCrawlStatus._from_dict( + args['crawl_status'] = CollectionCrawlStatus.from_dict( _dict.get('crawl_status')) if 'smart_document_understanding' in _dict: - args['smart_document_understanding'] = SduStatus._from_dict( + args['smart_document_understanding'] = SduStatus.from_dict( _dict.get('smart_document_understanding')) return cls(**args) @@ -3815,18 +4079,19 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id + if hasattr(self, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') if hasattr(self, 'configuration_id') and self.configuration_id is not None: _dict['configuration_id'] = self.configuration_id @@ -3834,18 +4099,18 @@ def to_dict(self) -> Dict: _dict['language'] = self.language if hasattr(self, 'document_counts') and self.document_counts is not None: - _dict['document_counts'] = self.document_counts._to_dict() + _dict['document_counts'] = self.document_counts.to_dict() if hasattr(self, 'disk_usage') and self.disk_usage is not None: - _dict['disk_usage'] = self.disk_usage._to_dict() + _dict['disk_usage'] = self.disk_usage.to_dict() if hasattr(self, 'training_status') and self.training_status is not None: - _dict['training_status'] = self.training_status._to_dict() + _dict['training_status'] = self.training_status.to_dict() if hasattr(self, 'crawl_status') and self.crawl_status is not None: - _dict['crawl_status'] = self.crawl_status._to_dict() + _dict['crawl_status'] = self.crawl_status.to_dict() if hasattr(self, 'smart_document_understanding' ) and self.smart_document_understanding is not None: _dict[ - 'smart_document_understanding'] = self.smart_document_understanding._to_dict( + 'smart_document_understanding'] = self.smart_document_understanding.to_dict( ) return _dict @@ -3855,7 +4120,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Collection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Collection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3867,13 +4132,13 @@ def __ne__(self, other: 'Collection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The status of the collection. """ - ACTIVE = "active" - PENDING = "pending" - MAINTENANCE = "maintenance" + ACTIVE = 'active' + PENDING = 'pending' + MAINTENANCE = 'maintenance' class CollectionCrawlStatus(): @@ -3897,14 +4162,8 @@ def __init__(self, *, source_crawl: 'SourceStatus' = None) -> None: def from_dict(cls, _dict: Dict) -> 'CollectionCrawlStatus': """Initialize a CollectionCrawlStatus object from a json dictionary.""" args = {} - valid_keys = ['source_crawl'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CollectionCrawlStatus: ' - + ', '.join(bad_keys)) if 'source_crawl' in _dict: - args['source_crawl'] = SourceStatus._from_dict( + args['source_crawl'] = SourceStatus.from_dict( _dict.get('source_crawl')) return cls(**args) @@ -3917,7 +4176,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'source_crawl') and self.source_crawl is not None: - _dict['source_crawl'] = self.source_crawl._to_dict() + _dict['source_crawl'] = self.source_crawl.to_dict() return _dict def _to_dict(self): @@ -3926,7 +4185,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CollectionCrawlStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CollectionCrawlStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3950,7 +4209,6 @@ def __init__(self, *, used_bytes: int = None) -> None: """ Initialize a CollectionDiskUsage object. - :param int used_bytes: (optional) Number of bytes used by the collection. """ self.used_bytes = used_bytes @@ -3958,12 +4216,6 @@ def __init__(self, *, used_bytes: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'CollectionDiskUsage': """Initialize a CollectionDiskUsage object from a json dictionary.""" args = {} - valid_keys = ['used_bytes'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CollectionDiskUsage: ' - + ', '.join(bad_keys)) if 'used_bytes' in _dict: args['used_bytes'] = _dict.get('used_bytes') return cls(**args) @@ -3976,8 +4228,9 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'used_bytes') and self.used_bytes is not None: - _dict['used_bytes'] = self.used_bytes + if hasattr(self, 'used_bytes') and getattr(self, + 'used_bytes') is not None: + _dict['used_bytes'] = getattr(self, 'used_bytes') return _dict def _to_dict(self): @@ -3986,7 +4239,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CollectionDiskUsage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CollectionDiskUsage') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4015,10 +4268,6 @@ def __init__(self, """ Initialize a CollectionUsage object. - :param int available: (optional) Number of active collections in the - environment. - :param int maximum_allowed: (optional) Total number of collections allowed - in the environment. """ self.available = available self.maximum_allowed = maximum_allowed @@ -4027,12 +4276,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CollectionUsage': """Initialize a CollectionUsage object from a json dictionary.""" args = {} - valid_keys = ['available', 'maximum_allowed'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CollectionUsage: ' - + ', '.join(bad_keys)) if 'available' in _dict: args['available'] = _dict.get('available') if 'maximum_allowed' in _dict: @@ -4047,11 +4290,12 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'available') and self.available is not None: - _dict['available'] = self.available - if hasattr(self, - 'maximum_allowed') and self.maximum_allowed is not None: - _dict['maximum_allowed'] = self.maximum_allowed + if hasattr(self, 'available') and getattr(self, + 'available') is not None: + _dict['available'] = getattr(self, 'available') + if hasattr(self, 'maximum_allowed') and getattr( + self, 'maximum_allowed') is not None: + _dict['maximum_allowed'] = getattr(self, 'maximum_allowed') return _dict def _to_dict(self): @@ -4060,7 +4304,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CollectionUsage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CollectionUsage') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4094,12 +4338,6 @@ def __init__(self, *, completions: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'Completions': """Initialize a Completions object from a json dictionary.""" args = {} - valid_keys = ['completions'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Completions: ' - + ', '.join(bad_keys)) if 'completions' in _dict: args['completions'] = _dict.get('completions') return cls(**args) @@ -4122,7 +4360,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Completions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Completions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4173,12 +4411,6 @@ def __init__(self, Initialize a Configuration object. :param str name: The name of the configuration. - :param str configuration_id: (optional) The unique identifier of the - configuration. - :param datetime created: (optional) The creation date of the configuration - in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param datetime updated: (optional) The timestamp of when the configuration - was last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :param str description: (optional) The description of the configuration, if available. :param Conversions conversions: (optional) Document conversion settings. @@ -4205,15 +4437,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Configuration': """Initialize a Configuration object from a json dictionary.""" args = {} - valid_keys = [ - 'configuration_id', 'name', 'created', 'updated', 'description', - 'conversions', 'enrichments', 'normalizations', 'source' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Configuration: ' - + ', '.join(bad_keys)) if 'configuration_id' in _dict: args['configuration_id'] = _dict.get('configuration_id') if 'name' in _dict: @@ -4228,19 +4451,19 @@ def from_dict(cls, _dict: Dict) -> 'Configuration': if 'description' in _dict: args['description'] = _dict.get('description') if 'conversions' in _dict: - args['conversions'] = Conversions._from_dict( + args['conversions'] = Conversions.from_dict( _dict.get('conversions')) if 'enrichments' in _dict: args['enrichments'] = [ - Enrichment._from_dict(x) for x in (_dict.get('enrichments')) + Enrichment.from_dict(x) for x in _dict.get('enrichments') ] if 'normalizations' in _dict: args['normalizations'] = [ - NormalizationOperation._from_dict(x) - for x in (_dict.get('normalizations')) + NormalizationOperation.from_dict(x) + for x in _dict.get('normalizations') ] if 'source' in _dict: - args['source'] = Source._from_dict(_dict.get('source')) + args['source'] = Source.from_dict(_dict.get('source')) return cls(**args) @classmethod @@ -4251,27 +4474,25 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, - 'configuration_id') and self.configuration_id is not None: - _dict['configuration_id'] = self.configuration_id + if hasattr(self, 'configuration_id') and getattr( + self, 'configuration_id') is not None: + _dict['configuration_id'] = getattr(self, 'configuration_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'conversions') and self.conversions is not None: - _dict['conversions'] = self.conversions._to_dict() + _dict['conversions'] = self.conversions.to_dict() if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x._to_dict() for x in self.enrichments] + _dict['enrichments'] = [x.to_dict() for x in self.enrichments] if hasattr(self, 'normalizations') and self.normalizations is not None: - _dict['normalizations'] = [ - x._to_dict() for x in self.normalizations - ] + _dict['normalizations'] = [x.to_dict() for x in self.normalizations] if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source._to_dict() + _dict['source'] = self.source.to_dict() return _dict def _to_dict(self): @@ -4280,7 +4501,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Configuration object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Configuration') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4351,27 +4572,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Conversions': """Initialize a Conversions object from a json dictionary.""" args = {} - valid_keys = [ - 'pdf', 'word', 'html', 'segment', 'json_normalizations', - 'image_text_recognition' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Conversions: ' - + ', '.join(bad_keys)) if 'pdf' in _dict: - args['pdf'] = PdfSettings._from_dict(_dict.get('pdf')) + args['pdf'] = PdfSettings.from_dict(_dict.get('pdf')) if 'word' in _dict: - args['word'] = WordSettings._from_dict(_dict.get('word')) + args['word'] = WordSettings.from_dict(_dict.get('word')) if 'html' in _dict: - args['html'] = HtmlSettings._from_dict(_dict.get('html')) + args['html'] = HtmlSettings.from_dict(_dict.get('html')) if 'segment' in _dict: - args['segment'] = SegmentSettings._from_dict(_dict.get('segment')) + args['segment'] = SegmentSettings.from_dict(_dict.get('segment')) if 'json_normalizations' in _dict: args['json_normalizations'] = [ - NormalizationOperation._from_dict(x) - for x in (_dict.get('json_normalizations')) + NormalizationOperation.from_dict(x) + for x in _dict.get('json_normalizations') ] if 'image_text_recognition' in _dict: args['image_text_recognition'] = _dict.get('image_text_recognition') @@ -4386,18 +4598,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'pdf') and self.pdf is not None: - _dict['pdf'] = self.pdf._to_dict() + _dict['pdf'] = self.pdf.to_dict() if hasattr(self, 'word') and self.word is not None: - _dict['word'] = self.word._to_dict() + _dict['word'] = self.word.to_dict() if hasattr(self, 'html') and self.html is not None: - _dict['html'] = self.html._to_dict() + _dict['html'] = self.html.to_dict() if hasattr(self, 'segment') and self.segment is not None: - _dict['segment'] = self.segment._to_dict() + _dict['segment'] = self.segment.to_dict() if hasattr( self, 'json_normalizations') and self.json_normalizations is not None: _dict['json_normalizations'] = [ - x._to_dict() for x in self.json_normalizations + x.to_dict() for x in self.json_normalizations ] if hasattr(self, 'image_text_recognition' ) and self.image_text_recognition is not None: @@ -4410,7 +4622,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Conversions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Conversions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4445,16 +4657,10 @@ def __init__(self, *, type: str = None, data: 'EventData' = None) -> None: def from_dict(cls, _dict: Dict) -> 'CreateEventResponse': """Initialize a CreateEventResponse object from a json dictionary.""" args = {} - valid_keys = ['type', 'data'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CreateEventResponse: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'data' in _dict: - args['data'] = EventData._from_dict(_dict.get('data')) + args['data'] = EventData.from_dict(_dict.get('data')) return cls(**args) @classmethod @@ -4468,7 +4674,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'data') and self.data is not None: - _dict['data'] = self.data._to_dict() + _dict['data'] = self.data.to_dict() return _dict def _to_dict(self): @@ -4477,7 +4683,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CreateEventResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CreateEventResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4489,11 +4695,11 @@ def __ne__(self, other: 'CreateEventResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The event type that was created. """ - CLICK = "click" + CLICK = 'click' class CredentialDetails(): @@ -4710,18 +4916,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CredentialDetails': """Initialize a CredentialDetails object from a json dictionary.""" args = {} - valid_keys = [ - 'credential_type', 'client_id', 'enterprise_id', 'url', 'username', - 'organization_url', 'site_collection_path', 'site_collection.path', - 'client_secret', 'public_key_id', 'private_key', 'passphrase', - 'password', 'gateway_id', 'source_version', 'web_application_url', - 'domain', 'endpoint', 'access_key_id', 'secret_access_key' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CredentialDetails: ' - + ', '.join(bad_keys)) if 'credential_type' in _dict: args['credential_type'] = _dict.get('credential_type') if 'client_id' in _dict: @@ -4822,7 +5016,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CredentialDetails object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CredentialDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4834,7 +5028,7 @@ def __ne__(self, other: 'CredentialDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class CredentialTypeEnum(Enum): + class CredentialTypeEnum(str, Enum): """ The authentication method for this credentials definition. The **credential_type** specified must be supported by the **source_type**. The @@ -4846,20 +5040,20 @@ class CredentialTypeEnum(Enum): - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. """ - OAUTH2 = "oauth2" - SAML = "saml" - USERNAME_PASSWORD = "username_password" - NOAUTH = "noauth" - BASIC = "basic" - NTLM_V1 = "ntlm_v1" - AWS4_HMAC = "aws4_hmac" + OAUTH2 = 'oauth2' + SAML = 'saml' + USERNAME_PASSWORD = 'username_password' + NOAUTH = 'noauth' + BASIC = 'basic' + NTLM_V1 = 'ntlm_v1' + AWS4_HMAC = 'aws4_hmac' - class SourceVersionEnum(Enum): + class SourceVersionEnum(str, Enum): """ The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of `sharepoint`. """ - ONLINE = "online" + ONLINE = 'online' class Credentials(): @@ -4897,8 +5091,6 @@ def __init__(self, """ Initialize a Credentials object. - :param str credential_id: (optional) Unique identifier for this set of - credentials. :param str source_type: (optional) The source that this credentials object connects to. - `box` indicates the credentials are used to connect an instance of @@ -4928,20 +5120,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Credentials': """Initialize a Credentials object from a json dictionary.""" args = {} - valid_keys = [ - 'credential_id', 'source_type', 'credential_details', 'status' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Credentials: ' - + ', '.join(bad_keys)) if 'credential_id' in _dict: args['credential_id'] = _dict.get('credential_id') if 'source_type' in _dict: args['source_type'] = _dict.get('source_type') if 'credential_details' in _dict: - args['credential_details'] = CredentialDetails._from_dict( + args['credential_details'] = CredentialDetails.from_dict( _dict.get('credential_details')) if 'status' in _dict: args['status'] = _dict.get('status') @@ -4955,14 +5139,15 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'credential_id') and self.credential_id is not None: - _dict['credential_id'] = self.credential_id + if hasattr(self, 'credential_id') and getattr( + self, 'credential_id') is not None: + _dict['credential_id'] = getattr(self, 'credential_id') if hasattr(self, 'source_type') and self.source_type is not None: _dict['source_type'] = self.source_type if hasattr( self, 'credential_details') and self.credential_details is not None: - _dict['credential_details'] = self.credential_details._to_dict() + _dict['credential_details'] = self.credential_details.to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict @@ -4973,7 +5158,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Credentials object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Credentials') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4985,7 +5170,7 @@ def __ne__(self, other: 'Credentials') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class SourceTypeEnum(Enum): + class SourceTypeEnum(str, Enum): """ The source that this credentials object connects to. - `box` indicates the credentials are used to connect an instance of Enterprise @@ -4997,21 +5182,21 @@ class SourceTypeEnum(Enum): = `cloud_object_storage` indicates the credentials are used to connect to an IBM Cloud Object Store. """ - BOX = "box" - SALESFORCE = "salesforce" - SHAREPOINT = "sharepoint" - WEB_CRAWL = "web_crawl" - CLOUD_OBJECT_STORAGE = "cloud_object_storage" + BOX = 'box' + SALESFORCE = 'salesforce' + SHAREPOINT = 'sharepoint' + WEB_CRAWL = 'web_crawl' + CLOUD_OBJECT_STORAGE = 'cloud_object_storage' - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The current status of this set of credentials. `connected` indicates that the credentials are available to use with the source configuration of a collection. `invalid` refers to the credentials (for example, the password provided has expired) and must be corrected before they can be used with a collection. """ - CONNECTED = "connected" - INVALID = "invalid" + CONNECTED = 'connected' + INVALID = 'invalid' class CredentialsList(): @@ -5035,15 +5220,9 @@ def __init__(self, *, credentials: List['Credentials'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CredentialsList': """Initialize a CredentialsList object from a json dictionary.""" args = {} - valid_keys = ['credentials'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CredentialsList: ' - + ', '.join(bad_keys)) if 'credentials' in _dict: args['credentials'] = [ - Credentials._from_dict(x) for x in (_dict.get('credentials')) + Credentials.from_dict(x) for x in _dict.get('credentials') ] return cls(**args) @@ -5056,7 +5235,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credentials') and self.credentials is not None: - _dict['credentials'] = [x._to_dict() for x in self.credentials] + _dict['credentials'] = [x.to_dict() for x in self.credentials] return _dict def _to_dict(self): @@ -5065,7 +5244,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CredentialsList object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CredentialsList') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5104,12 +5283,6 @@ def __init__(self, collection_id: str, status: str) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteCollectionResponse': """Initialize a DeleteCollectionResponse object from a json dictionary.""" args = {} - valid_keys = ['collection_id', 'status'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DeleteCollectionResponse: ' - + ', '.join(bad_keys)) if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') else: @@ -5144,7 +5317,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DeleteCollectionResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DeleteCollectionResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5156,12 +5329,12 @@ def __ne__(self, other: 'DeleteCollectionResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The status of the collection. The status of a successful deletion operation is `deleted`. """ - DELETED = "deleted" + DELETED = 'deleted' class DeleteConfigurationResponse(): @@ -5196,12 +5369,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DeleteConfigurationResponse': """Initialize a DeleteConfigurationResponse object from a json dictionary.""" args = {} - valid_keys = ['configuration_id', 'status', 'notices'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DeleteConfigurationResponse: ' - + ', '.join(bad_keys)) if 'configuration_id' in _dict: args['configuration_id'] = _dict.get('configuration_id') else: @@ -5216,7 +5383,7 @@ def from_dict(cls, _dict: Dict) -> 'DeleteConfigurationResponse': ) if 'notices' in _dict: args['notices'] = [ - Notice._from_dict(x) for x in (_dict.get('notices')) + Notice.from_dict(x) for x in _dict.get('notices') ] return cls(**args) @@ -5234,7 +5401,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x._to_dict() for x in self.notices] + _dict['notices'] = [x.to_dict() for x in self.notices] return _dict def _to_dict(self): @@ -5243,7 +5410,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DeleteConfigurationResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DeleteConfigurationResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5255,11 +5422,11 @@ def __ne__(self, other: 'DeleteConfigurationResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Status of the configuration. A deleted configuration has the status deleted. """ - DELETED = "deleted" + DELETED = 'deleted' class DeleteCredentials(): @@ -5289,12 +5456,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DeleteCredentials': """Initialize a DeleteCredentials object from a json dictionary.""" args = {} - valid_keys = ['credential_id', 'status'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DeleteCredentials: ' - + ', '.join(bad_keys)) if 'credential_id' in _dict: args['credential_id'] = _dict.get('credential_id') if 'status' in _dict: @@ -5321,7 +5482,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DeleteCredentials object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DeleteCredentials') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5333,11 +5494,11 @@ def __ne__(self, other: 'DeleteCredentials') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The status of the deletion request. """ - DELETED = "deleted" + DELETED = 'deleted' class DeleteDocumentResponse(): @@ -5364,12 +5525,6 @@ def __init__(self, *, document_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} - valid_keys = ['document_id', 'status'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DeleteDocumentResponse: ' - + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'status' in _dict: @@ -5396,7 +5551,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DeleteDocumentResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5408,11 +5563,11 @@ def __ne__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Status of the document. A deleted document has the status deleted. """ - DELETED = "deleted" + DELETED = 'deleted' class DeleteEnvironmentResponse(): @@ -5437,12 +5592,6 @@ def __init__(self, environment_id: str, status: str) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteEnvironmentResponse': """Initialize a DeleteEnvironmentResponse object from a json dictionary.""" args = {} - valid_keys = ['environment_id', 'status'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DeleteEnvironmentResponse: ' - + ', '.join(bad_keys)) if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') else: @@ -5477,7 +5626,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DeleteEnvironmentResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DeleteEnvironmentResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5489,11 +5638,11 @@ def __ne__(self, other: 'DeleteEnvironmentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Status of the environment. """ - DELETED = "deleted" + DELETED = 'deleted' class DiskUsage(): @@ -5513,10 +5662,6 @@ def __init__(self, """ Initialize a DiskUsage object. - :param int used_bytes: (optional) Number of bytes within the environment's - disk capacity that are currently used to store data. - :param int maximum_allowed_bytes: (optional) Total number of bytes - available in the environment's disk capacity. """ self.used_bytes = used_bytes self.maximum_allowed_bytes = maximum_allowed_bytes @@ -5525,12 +5670,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DiskUsage': """Initialize a DiskUsage object from a json dictionary.""" args = {} - valid_keys = ['used_bytes', 'maximum_allowed_bytes'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DiskUsage: ' - + ', '.join(bad_keys)) if 'used_bytes' in _dict: args['used_bytes'] = _dict.get('used_bytes') if 'maximum_allowed_bytes' in _dict: @@ -5545,11 +5684,13 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'used_bytes') and self.used_bytes is not None: - _dict['used_bytes'] = self.used_bytes - if hasattr(self, 'maximum_allowed_bytes' - ) and self.maximum_allowed_bytes is not None: - _dict['maximum_allowed_bytes'] = self.maximum_allowed_bytes + if hasattr(self, 'used_bytes') and getattr(self, + 'used_bytes') is not None: + _dict['used_bytes'] = getattr(self, 'used_bytes') + if hasattr(self, 'maximum_allowed_bytes') and getattr( + self, 'maximum_allowed_bytes') is not None: + _dict['maximum_allowed_bytes'] = getattr(self, + 'maximum_allowed_bytes') return _dict def _to_dict(self): @@ -5558,7 +5699,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DiskUsage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DiskUsage') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5610,19 +5751,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': """Initialize a DocumentAccepted object from a json dictionary.""" args = {} - valid_keys = ['document_id', 'status', 'notices'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentAccepted: ' - + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'status' in _dict: args['status'] = _dict.get('status') if 'notices' in _dict: args['notices'] = [ - Notice._from_dict(x) for x in (_dict.get('notices')) + Notice.from_dict(x) for x in _dict.get('notices') ] return cls(**args) @@ -5639,7 +5774,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x._to_dict() for x in self.notices] + _dict['notices'] = [x.to_dict() for x in self.notices] return _dict def _to_dict(self): @@ -5648,7 +5783,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocumentAccepted object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5660,14 +5795,14 @@ def __ne__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Status of the document in the ingestion process. A status of `processing` is returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. """ - PROCESSING = "processing" - PENDING = "pending" + PROCESSING = 'processing' + PENDING = 'pending' class DocumentCounts(): @@ -5693,14 +5828,6 @@ def __init__(self, """ Initialize a DocumentCounts object. - :param int available: (optional) The total number of available documents in - the collection. - :param int processing: (optional) The number of documents in the collection - that are currently being processed. - :param int failed: (optional) The number of documents in the collection - that failed to be ingested. - :param int pending: (optional) The number of documents that have been - uploaded to the collection, but have not yet started processing. """ self.available = available self.processing = processing @@ -5711,12 +5838,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentCounts': """Initialize a DocumentCounts object from a json dictionary.""" args = {} - valid_keys = ['available', 'processing', 'failed', 'pending'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentCounts: ' - + ', '.join(bad_keys)) if 'available' in _dict: args['available'] = _dict.get('available') if 'processing' in _dict: @@ -5735,14 +5856,16 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'available') and self.available is not None: - _dict['available'] = self.available - if hasattr(self, 'processing') and self.processing is not None: - _dict['processing'] = self.processing - if hasattr(self, 'failed') and self.failed is not None: - _dict['failed'] = self.failed - if hasattr(self, 'pending') and self.pending is not None: - _dict['pending'] = self.pending + if hasattr(self, 'available') and getattr(self, + 'available') is not None: + _dict['available'] = getattr(self, 'available') + if hasattr(self, 'processing') and getattr(self, + 'processing') is not None: + _dict['processing'] = getattr(self, 'processing') + if hasattr(self, 'failed') and getattr(self, 'failed') is not None: + _dict['failed'] = getattr(self, 'failed') + if hasattr(self, 'pending') and getattr(self, 'pending') is not None: + _dict['pending'] = getattr(self, 'pending') return _dict def _to_dict(self): @@ -5751,7 +5874,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocumentCounts object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocumentCounts') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5799,8 +5922,6 @@ def __init__(self, :param str status_description: Description of the document status. :param List[Notice] notices: Array of notices produced by the document-ingestion process. - :param str configuration_id: (optional) The unique identifier for the - configuration. :param str filename: (optional) Name of the original source file (if available). :param str file_type: (optional) The type of the original source file. @@ -5820,15 +5941,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentStatus': """Initialize a DocumentStatus object from a json dictionary.""" args = {} - valid_keys = [ - 'document_id', 'configuration_id', 'status', 'status_description', - 'filename', 'file_type', 'sha1', 'notices' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentStatus: ' - + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') else: @@ -5857,7 +5969,7 @@ def from_dict(cls, _dict: Dict) -> 'DocumentStatus': args['sha1'] = _dict.get('sha1') if 'notices' in _dict: args['notices'] = [ - Notice._from_dict(x) for x in (_dict.get('notices')) + Notice.from_dict(x) for x in _dict.get('notices') ] else: raise ValueError( @@ -5873,25 +5985,25 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, - 'configuration_id') and self.configuration_id is not None: - _dict['configuration_id'] = self.configuration_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr( - self, - 'status_description') and self.status_description is not None: - _dict['status_description'] = self.status_description + if hasattr(self, 'document_id') and getattr(self, + 'document_id') is not None: + _dict['document_id'] = getattr(self, 'document_id') + if hasattr(self, 'configuration_id') and getattr( + self, 'configuration_id') is not None: + _dict['configuration_id'] = getattr(self, 'configuration_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') if hasattr(self, 'filename') and self.filename is not None: _dict['filename'] = self.filename if hasattr(self, 'file_type') and self.file_type is not None: _dict['file_type'] = self.file_type if hasattr(self, 'sha1') and self.sha1 is not None: _dict['sha1'] = self.sha1 - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x._to_dict() for x in self.notices] + if hasattr(self, 'notices') and getattr(self, 'notices') is not None: + _dict['notices'] = [x.to_dict() for x in getattr(self, 'notices')] return _dict def _to_dict(self): @@ -5900,7 +6012,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocumentStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocumentStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5912,24 +6024,24 @@ def __ne__(self, other: 'DocumentStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Status of the document in the ingestion process. """ - AVAILABLE = "available" - AVAILABLE_WITH_NOTICES = "available with notices" - FAILED = "failed" - PROCESSING = "processing" - PENDING = "pending" + AVAILABLE = 'available' + AVAILABLE_WITH_NOTICES = 'available with notices' + FAILED = 'failed' + PROCESSING = 'processing' + PENDING = 'pending' - class FileTypeEnum(Enum): + class FileTypeEnum(str, Enum): """ The type of the original source file. """ - PDF = "pdf" - HTML = "html" - WORD = "word" - JSON = "json" + PDF = 'pdf' + HTML = 'html' + WORD = 'word' + JSON = 'json' class Enrichment(): @@ -6012,15 +6124,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Enrichment': """Initialize a Enrichment object from a json dictionary.""" args = {} - valid_keys = [ - 'description', 'destination_field', 'source_field', 'overwrite', - 'enrichment', 'ignore_downstream_errors', 'options' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Enrichment: ' - + ', '.join(bad_keys)) if 'description' in _dict: args['description'] = _dict.get('description') if 'destination_field' in _dict: @@ -6047,7 +6150,7 @@ def from_dict(cls, _dict: Dict) -> 'Enrichment': args['ignore_downstream_errors'] = _dict.get( 'ignore_downstream_errors') if 'options' in _dict: - args['options'] = EnrichmentOptions._from_dict(_dict.get('options')) + args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) return cls(**args) @classmethod @@ -6073,7 +6176,7 @@ def to_dict(self) -> Dict: ) and self.ignore_downstream_errors is not None: _dict['ignore_downstream_errors'] = self.ignore_downstream_errors if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options._to_dict() + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -6082,7 +6185,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Enrichment object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Enrichment') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6138,14 +6241,8 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} - valid_keys = ['features', 'language', 'model'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EnrichmentOptions: ' - + ', '.join(bad_keys)) if 'features' in _dict: - args['features'] = NluEnrichmentFeatures._from_dict( + args['features'] = NluEnrichmentFeatures.from_dict( _dict.get('features')) if 'language' in _dict: args['language'] = _dict.get('language') @@ -6162,7 +6259,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'features') and self.features is not None: - _dict['features'] = self.features._to_dict() + _dict['features'] = self.features.to_dict() if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'model') and self.model is not None: @@ -6175,7 +6272,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EnrichmentOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EnrichmentOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6187,7 +6284,7 @@ def __ne__(self, other: 'EnrichmentOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LanguageEnum(Enum): + class LanguageEnum(str, Enum): """ ISO 639-1 code indicating the language to use for the analysis. This code overrides the automatic language detection performed by the service. Valid codes @@ -6195,15 +6292,15 @@ class LanguageEnum(Enum): `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. """ - AR = "ar" - EN = "en" - FR = "fr" - DE = "de" - IT = "it" - PT = "pt" - RU = "ru" - ES = "es" - SV = "sv" + AR = 'ar' + EN = 'en' + FR = 'fr' + DE = 'de' + IT = 'it' + PT = 'pt' + RU = 'ru' + ES = 'es' + SV = 'sv' class Environment(): @@ -6249,19 +6346,8 @@ def __init__(self, """ Initialize a Environment object. - :param str environment_id: (optional) Unique identifier for the - environment. :param str name: (optional) Name that identifies the environment. :param str description: (optional) Description of the environment. - :param datetime created: (optional) Creation date of the environment, in - the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :param datetime updated: (optional) Date of most recent environment update, - in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :param str status: (optional) Current status of the environment. `resizing` - is displayed when a request to increase the environment size has been made, - but is still in the process of being completed. - :param bool read_only: (optional) If `true`, the environment contains - read-only collections that are maintained by IBM. :param str size: (optional) Current size of the environment. :param str requested_size: (optional) The new size requested for this environment. Only returned when the environment *status* is `resizing`. @@ -6288,16 +6374,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Environment': """Initialize a Environment object from a json dictionary.""" args = {} - valid_keys = [ - 'environment_id', 'name', 'description', 'created', 'updated', - 'status', 'read_only', 'size', 'requested_size', 'index_capacity', - 'search_status' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Environment: ' - + ', '.join(bad_keys)) if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') if 'name' in _dict: @@ -6317,10 +6393,10 @@ def from_dict(cls, _dict: Dict) -> 'Environment': if 'requested_size' in _dict: args['requested_size'] = _dict.get('requested_size') if 'index_capacity' in _dict: - args['index_capacity'] = IndexCapacity._from_dict( + args['index_capacity'] = IndexCapacity.from_dict( _dict.get('index_capacity')) if 'search_status' in _dict: - args['search_status'] = SearchStatus._from_dict( + args['search_status'] = SearchStatus.from_dict( _dict.get('search_status')) return cls(**args) @@ -6332,28 +6408,30 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'environment_id') and self.environment_id is not None: - _dict['environment_id'] = self.environment_id + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'read_only') and self.read_only is not None: - _dict['read_only'] = self.read_only + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'read_only') and getattr(self, + 'read_only') is not None: + _dict['read_only'] = getattr(self, 'read_only') if hasattr(self, 'size') and self.size is not None: _dict['size'] = self.size if hasattr(self, 'requested_size') and self.requested_size is not None: _dict['requested_size'] = self.requested_size if hasattr(self, 'index_capacity') and self.index_capacity is not None: - _dict['index_capacity'] = self.index_capacity._to_dict() + _dict['index_capacity'] = self.index_capacity.to_dict() if hasattr(self, 'search_status') and self.search_status is not None: - _dict['search_status'] = self.search_status._to_dict() + _dict['search_status'] = self.search_status.to_dict() return _dict def _to_dict(self): @@ -6362,7 +6440,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Environment object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Environment') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6374,31 +6452,31 @@ def __ne__(self, other: 'Environment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Current status of the environment. `resizing` is displayed when a request to increase the environment size has been made, but is still in the process of being completed. """ - ACTIVE = "active" - PENDING = "pending" - MAINTENANCE = "maintenance" - RESIZING = "resizing" + ACTIVE = 'active' + PENDING = 'pending' + MAINTENANCE = 'maintenance' + RESIZING = 'resizing' - class SizeEnum(Enum): + class SizeEnum(str, Enum): """ Current size of the environment. """ - LT = "LT" - XS = "XS" - S = "S" - MS = "MS" - M = "M" - ML = "ML" - L = "L" - XL = "XL" - XXL = "XXL" - XXXL = "XXXL" + LT = 'LT' + XS = 'XS' + S = 'S' + MS = 'MS' + M = 'M' + ML = 'ML' + L = 'L' + XL = 'XL' + XXL = 'XXL' + XXXL = 'XXXL' class EnvironmentDocuments(): @@ -6417,10 +6495,6 @@ def __init__(self, """ Initialize a EnvironmentDocuments object. - :param int available: (optional) Number of documents indexed for the - environment. - :param int maximum_allowed: (optional) Total number of documents allowed in - the environment's capacity. """ self.available = available self.maximum_allowed = maximum_allowed @@ -6429,12 +6503,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnvironmentDocuments': """Initialize a EnvironmentDocuments object from a json dictionary.""" args = {} - valid_keys = ['available', 'maximum_allowed'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EnvironmentDocuments: ' - + ', '.join(bad_keys)) if 'available' in _dict: args['available'] = _dict.get('available') if 'maximum_allowed' in _dict: @@ -6449,11 +6517,12 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'available') and self.available is not None: - _dict['available'] = self.available - if hasattr(self, - 'maximum_allowed') and self.maximum_allowed is not None: - _dict['maximum_allowed'] = self.maximum_allowed + if hasattr(self, 'available') and getattr(self, + 'available') is not None: + _dict['available'] = getattr(self, 'available') + if hasattr(self, 'maximum_allowed') and getattr( + self, 'maximum_allowed') is not None: + _dict['maximum_allowed'] = getattr(self, 'maximum_allowed') return _dict def _to_dict(self): @@ -6462,7 +6531,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EnvironmentDocuments object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EnvironmentDocuments') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6521,9 +6590,6 @@ def __init__(self, created in the log was used. :param int display_rank: (optional) The rank of the result item which the event is associated with. - :param str query_id: (optional) The query identifier stored in the log. The - query and any events associated with that query are stored with the same - **query_id**. """ self.environment_id = environment_id self.session_token = session_token @@ -6537,15 +6603,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EventData': """Initialize a EventData object from a json dictionary.""" args = {} - valid_keys = [ - 'environment_id', 'session_token', 'client_timestamp', - 'display_rank', 'collection_id', 'document_id', 'query_id' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EventData: ' - + ', '.join(bad_keys)) if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') else: @@ -6601,8 +6658,8 @@ def to_dict(self) -> Dict: _dict['collection_id'] = self.collection_id if hasattr(self, 'document_id') and self.document_id is not None: _dict['document_id'] = self.document_id - if hasattr(self, 'query_id') and self.query_id is not None: - _dict['query_id'] = self.query_id + if hasattr(self, 'query_id') and getattr(self, 'query_id') is not None: + _dict['query_id'] = getattr(self, 'query_id') return _dict def _to_dict(self): @@ -6611,7 +6668,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EventData object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EventData') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6658,12 +6715,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Expansion': """Initialize a Expansion object from a json dictionary.""" args = {} - valid_keys = ['input_terms', 'expanded_terms'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Expansion: ' - + ', '.join(bad_keys)) if 'input_terms' in _dict: args['input_terms'] = _dict.get('input_terms') if 'expanded_terms' in _dict: @@ -6694,7 +6745,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Expansion object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Expansion') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6750,15 +6801,9 @@ def __init__(self, expansions: List['Expansion']) -> None: def from_dict(cls, _dict: Dict) -> 'Expansions': """Initialize a Expansions object from a json dictionary.""" args = {} - valid_keys = ['expansions'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Expansions: ' - + ', '.join(bad_keys)) if 'expansions' in _dict: args['expansions'] = [ - Expansion._from_dict(x) for x in (_dict.get('expansions')) + Expansion.from_dict(x) for x in _dict.get('expansions') ] else: raise ValueError( @@ -6775,7 +6820,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'expansions') and self.expansions is not None: - _dict['expansions'] = [x._to_dict() for x in self.expansions] + _dict['expansions'] = [x.to_dict() for x in self.expansions] return _dict def _to_dict(self): @@ -6784,7 +6829,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Expansions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Expansions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6809,8 +6854,6 @@ def __init__(self, *, field: str = None, type: str = None) -> None: """ Initialize a Field object. - :param str field: (optional) The name of the field. - :param str type: (optional) The type of the field. """ self.field = field self.type = type @@ -6819,12 +6862,6 @@ def __init__(self, *, field: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Field': """Initialize a Field object from a json dictionary.""" args = {} - valid_keys = ['field', 'type'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Field: ' + - ', '.join(bad_keys)) if 'field' in _dict: args['field'] = _dict.get('field') if 'type' in _dict: @@ -6839,10 +6876,10 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type + if hasattr(self, 'field') and getattr(self, 'field') is not None: + _dict['field'] = getattr(self, 'field') + if hasattr(self, 'type') and getattr(self, 'type') is not None: + _dict['type'] = getattr(self, 'type') return _dict def _to_dict(self): @@ -6851,7 +6888,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Field object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Field') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6863,21 +6900,21 @@ def __ne__(self, other: 'Field') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The type of the field. """ - NESTED = "nested" - STRING = "string" - DATE = "date" - LONG = "long" - INTEGER = "integer" - SHORT = "short" - BYTE = "byte" - DOUBLE = "double" - FLOAT = "float" - BOOLEAN = "boolean" - BINARY = "binary" + NESTED = 'nested' + STRING = 'string' + DATE = 'date' + LONG = 'long' + INTEGER = 'integer' + SHORT = 'short' + BYTE = 'byte' + DOUBLE = 'double' + FLOAT = 'float' + BOOLEAN = 'boolean' + BINARY = 'binary' class FontSetting(): @@ -6925,12 +6962,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'FontSetting': """Initialize a FontSetting object from a json dictionary.""" args = {} - valid_keys = ['level', 'min_size', 'max_size', 'bold', 'italic', 'name'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class FontSetting: ' - + ', '.join(bad_keys)) if 'level' in _dict: args['level'] = _dict.get('level') if 'min_size' in _dict: @@ -6973,7 +7004,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this FontSetting object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'FontSetting') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7032,12 +7063,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Gateway': """Initialize a Gateway object from a json dictionary.""" args = {} - valid_keys = ['gateway_id', 'name', 'status', 'token', 'token_id'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Gateway: ' + - ', '.join(bad_keys)) if 'gateway_id' in _dict: args['gateway_id'] = _dict.get('gateway_id') if 'name' in _dict: @@ -7076,7 +7101,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Gateway object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Gateway') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7088,13 +7113,13 @@ def __ne__(self, other: 'Gateway') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The current status of the gateway. `connected` means the gateway is connected to the remotly installed gateway. `idle` means this gateway is not currently in use. """ - CONNECTED = "connected" - IDLE = "idle" + CONNECTED = 'connected' + IDLE = 'idle' class GatewayDelete(): @@ -7119,12 +7144,6 @@ def __init__(self, *, gateway_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'GatewayDelete': """Initialize a GatewayDelete object from a json dictionary.""" args = {} - valid_keys = ['gateway_id', 'status'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class GatewayDelete: ' - + ', '.join(bad_keys)) if 'gateway_id' in _dict: args['gateway_id'] = _dict.get('gateway_id') if 'status' in _dict: @@ -7151,7 +7170,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this GatewayDelete object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'GatewayDelete') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7185,15 +7204,9 @@ def __init__(self, *, gateways: List['Gateway'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'GatewayList': """Initialize a GatewayList object from a json dictionary.""" args = {} - valid_keys = ['gateways'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class GatewayList: ' - + ', '.join(bad_keys)) if 'gateways' in _dict: args['gateways'] = [ - Gateway._from_dict(x) for x in (_dict.get('gateways')) + Gateway.from_dict(x) for x in _dict.get('gateways') ] return cls(**args) @@ -7206,7 +7219,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'gateways') and self.gateways is not None: - _dict['gateways'] = [x._to_dict() for x in self.gateways] + _dict['gateways'] = [x.to_dict() for x in self.gateways] return _dict def _to_dict(self): @@ -7215,7 +7228,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this GatewayList object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'GatewayList') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7281,16 +7294,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'HtmlSettings': """Initialize a HtmlSettings object from a json dictionary.""" args = {} - valid_keys = [ - 'exclude_tags_completely', 'exclude_tags_keep_content', - 'keep_content', 'exclude_content', 'keep_tag_attributes', - 'exclude_tag_attributes' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class HtmlSettings: ' - + ', '.join(bad_keys)) if 'exclude_tags_completely' in _dict: args['exclude_tags_completely'] = _dict.get( 'exclude_tags_completely') @@ -7298,10 +7301,10 @@ def from_dict(cls, _dict: Dict) -> 'HtmlSettings': args['exclude_tags_keep_content'] = _dict.get( 'exclude_tags_keep_content') if 'keep_content' in _dict: - args['keep_content'] = XPathPatterns._from_dict( + args['keep_content'] = XPathPatterns.from_dict( _dict.get('keep_content')) if 'exclude_content' in _dict: - args['exclude_content'] = XPathPatterns._from_dict( + args['exclude_content'] = XPathPatterns.from_dict( _dict.get('exclude_content')) if 'keep_tag_attributes' in _dict: args['keep_tag_attributes'] = _dict.get('keep_tag_attributes') @@ -7324,10 +7327,10 @@ def to_dict(self) -> Dict: ) and self.exclude_tags_keep_content is not None: _dict['exclude_tags_keep_content'] = self.exclude_tags_keep_content if hasattr(self, 'keep_content') and self.keep_content is not None: - _dict['keep_content'] = self.keep_content._to_dict() + _dict['keep_content'] = self.keep_content.to_dict() if hasattr(self, 'exclude_content') and self.exclude_content is not None: - _dict['exclude_content'] = self.exclude_content._to_dict() + _dict['exclude_content'] = self.exclude_content.to_dict() if hasattr( self, 'keep_tag_attributes') and self.keep_tag_attributes is not None: @@ -7343,7 +7346,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this HtmlSettings object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'HtmlSettings') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7391,19 +7394,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'IndexCapacity': """Initialize a IndexCapacity object from a json dictionary.""" args = {} - valid_keys = ['documents', 'disk_usage', 'collections'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class IndexCapacity: ' - + ', '.join(bad_keys)) if 'documents' in _dict: - args['documents'] = EnvironmentDocuments._from_dict( + args['documents'] = EnvironmentDocuments.from_dict( _dict.get('documents')) if 'disk_usage' in _dict: - args['disk_usage'] = DiskUsage._from_dict(_dict.get('disk_usage')) + args['disk_usage'] = DiskUsage.from_dict(_dict.get('disk_usage')) if 'collections' in _dict: - args['collections'] = CollectionUsage._from_dict( + args['collections'] = CollectionUsage.from_dict( _dict.get('collections')) return cls(**args) @@ -7416,11 +7413,11 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'documents') and self.documents is not None: - _dict['documents'] = self.documents._to_dict() + _dict['documents'] = self.documents.to_dict() if hasattr(self, 'disk_usage') and self.disk_usage is not None: - _dict['disk_usage'] = self.disk_usage._to_dict() + _dict['disk_usage'] = self.disk_usage.to_dict() if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = self.collections._to_dict() + _dict['collections'] = self.collections.to_dict() return _dict def _to_dict(self): @@ -7429,7 +7426,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this IndexCapacity object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'IndexCapacity') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7472,16 +7469,8 @@ def __init__(self, *, fields: List['Field'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListCollectionFieldsResponse': """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" args = {} - valid_keys = ['fields'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ListCollectionFieldsResponse: ' - + ', '.join(bad_keys)) if 'fields' in _dict: - args['fields'] = [ - Field._from_dict(x) for x in (_dict.get('fields')) - ] + args['fields'] = [Field.from_dict(x) for x in _dict.get('fields')] return cls(**args) @classmethod @@ -7493,7 +7482,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = [x._to_dict() for x in self.fields] + _dict['fields'] = [x.to_dict() for x in self.fields] return _dict def _to_dict(self): @@ -7502,7 +7491,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ListCollectionFieldsResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ListCollectionFieldsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7536,15 +7525,9 @@ def __init__(self, *, collections: List['Collection'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} - valid_keys = ['collections'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ListCollectionsResponse: ' - + ', '.join(bad_keys)) if 'collections' in _dict: args['collections'] = [ - Collection._from_dict(x) for x in (_dict.get('collections')) + Collection.from_dict(x) for x in _dict.get('collections') ] return cls(**args) @@ -7557,7 +7540,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = [x._to_dict() for x in self.collections] + _dict['collections'] = [x.to_dict() for x in self.collections] return _dict def _to_dict(self): @@ -7566,7 +7549,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ListCollectionsResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ListCollectionsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7600,16 +7583,9 @@ def __init__(self, *, configurations: List['Configuration'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListConfigurationsResponse': """Initialize a ListConfigurationsResponse object from a json dictionary.""" args = {} - valid_keys = ['configurations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ListConfigurationsResponse: ' - + ', '.join(bad_keys)) if 'configurations' in _dict: args['configurations'] = [ - Configuration._from_dict(x) - for x in (_dict.get('configurations')) + Configuration.from_dict(x) for x in _dict.get('configurations') ] return cls(**args) @@ -7622,9 +7598,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'configurations') and self.configurations is not None: - _dict['configurations'] = [ - x._to_dict() for x in self.configurations - ] + _dict['configurations'] = [x.to_dict() for x in self.configurations] return _dict def _to_dict(self): @@ -7633,7 +7607,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ListConfigurationsResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ListConfigurationsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7667,15 +7641,9 @@ def __init__(self, *, environments: List['Environment'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListEnvironmentsResponse': """Initialize a ListEnvironmentsResponse object from a json dictionary.""" args = {} - valid_keys = ['environments'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ListEnvironmentsResponse: ' - + ', '.join(bad_keys)) if 'environments' in _dict: args['environments'] = [ - Environment._from_dict(x) for x in (_dict.get('environments')) + Environment.from_dict(x) for x in _dict.get('environments') ] return cls(**args) @@ -7688,7 +7656,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'environments') and self.environments is not None: - _dict['environments'] = [x._to_dict() for x in self.environments] + _dict['environments'] = [x.to_dict() for x in self.environments] return _dict def _to_dict(self): @@ -7697,7 +7665,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ListEnvironmentsResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ListEnvironmentsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7737,18 +7705,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponse': """Initialize a LogQueryResponse object from a json dictionary.""" args = {} - valid_keys = ['matching_results', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LogQueryResponse: ' - + ', '.join(bad_keys)) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - LogQueryResponseResult._from_dict(x) - for x in (_dict.get('results')) + LogQueryResponseResult.from_dict(x) + for x in _dict.get('results') ] return cls(**args) @@ -7764,7 +7726,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] return _dict def _to_dict(self): @@ -7773,7 +7735,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LogQueryResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LogQueryResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7932,17 +7894,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResult': """Initialize a LogQueryResponseResult object from a json dictionary.""" args = {} - valid_keys = [ - 'environment_id', 'customer_id', 'document_type', - 'natural_language_query', 'document_results', 'created_timestamp', - 'client_timestamp', 'query_id', 'session_token', 'collection_id', - 'display_rank', 'document_id', 'event_type', 'result_type' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LogQueryResponseResult: ' - + ', '.join(bad_keys)) if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') if 'customer_id' in _dict: @@ -7953,7 +7904,7 @@ def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResult': args['natural_language_query'] = _dict.get('natural_language_query') if 'document_results' in _dict: args[ - 'document_results'] = LogQueryResponseResultDocuments._from_dict( + 'document_results'] = LogQueryResponseResultDocuments.from_dict( _dict.get('document_results')) if 'created_timestamp' in _dict: args['created_timestamp'] = string_to_datetime( @@ -7996,7 +7947,7 @@ def to_dict(self) -> Dict: _dict['natural_language_query'] = self.natural_language_query if hasattr(self, 'document_results') and self.document_results is not None: - _dict['document_results'] = self.document_results._to_dict() + _dict['document_results'] = self.document_results.to_dict() if hasattr(self, 'created_timestamp') and self.created_timestamp is not None: _dict['created_timestamp'] = datetime_to_string( @@ -8027,7 +7978,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LogQueryResponseResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LogQueryResponseResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8039,31 +7990,31 @@ def __ne__(self, other: 'LogQueryResponseResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class DocumentTypeEnum(Enum): + class DocumentTypeEnum(str, Enum): """ The type of log entry returned. **query** indicates that the log represents the results of a call to the single collection **query** method. **event** indicates that the log represents a call to the **events** API. """ - QUERY = "query" - EVENT = "event" + QUERY = 'query' + EVENT = 'event' - class EventTypeEnum(Enum): + class EventTypeEnum(str, Enum): """ The type of event that this object respresents. Possible values are - `query` the log of a query to a collection - `click` the result of a call to the **events** endpoint. """ - CLICK = "click" - QUERY = "query" + CLICK = 'click' + QUERY = 'query' - class ResultTypeEnum(Enum): + class ResultTypeEnum(str, Enum): """ The type of result that this **event** is associated with. Only returned with logs of type `event`. """ - DOCUMENT = "document" + DOCUMENT = 'document' class LogQueryResponseResultDocuments(): @@ -8096,16 +8047,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocuments': """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" args = {} - valid_keys = ['results', 'count'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LogQueryResponseResultDocuments: ' - + ', '.join(bad_keys)) if 'results' in _dict: args['results'] = [ - LogQueryResponseResultDocumentsResult._from_dict(x) - for x in (_dict.get('results')) + LogQueryResponseResultDocumentsResult.from_dict(x) + for x in _dict.get('results') ] if 'count' in _dict: args['count'] = _dict.get('count') @@ -8120,7 +8065,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count return _dict @@ -8131,7 +8076,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LogQueryResponseResultDocuments object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LogQueryResponseResultDocuments') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8192,14 +8137,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocumentsResult': """Initialize a LogQueryResponseResultDocumentsResult object from a json dictionary.""" args = {} - valid_keys = [ - 'position', 'document_id', 'score', 'confidence', 'collection_id' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LogQueryResponseResultDocumentsResult: ' - + ', '.join(bad_keys)) if 'position' in _dict: args['position'] = _dict.get('position') if 'document_id' in _dict: @@ -8238,7 +8175,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LogQueryResponseResultDocumentsResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LogQueryResponseResultDocumentsResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8286,20 +8223,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricAggregation': """Initialize a MetricAggregation object from a json dictionary.""" args = {} - valid_keys = ['interval', 'event_type', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MetricAggregation: ' - + ', '.join(bad_keys)) if 'interval' in _dict: args['interval'] = _dict.get('interval') if 'event_type' in _dict: args['event_type'] = _dict.get('event_type') if 'results' in _dict: args['results'] = [ - MetricAggregationResult._from_dict(x) - for x in (_dict.get('results')) + MetricAggregationResult.from_dict(x) + for x in _dict.get('results') ] return cls(**args) @@ -8316,7 +8247,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'event_type') and self.event_type is not None: _dict['event_type'] = self.event_type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] return _dict def _to_dict(self): @@ -8325,7 +8256,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MetricAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MetricAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8379,12 +8310,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricAggregationResult': """Initialize a MetricAggregationResult object from a json dictionary.""" args = {} - valid_keys = ['key_as_string', 'key', 'matching_results', 'event_rate'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MetricAggregationResult: ' - + ', '.join(bad_keys)) if 'key_as_string' in _dict: args['key_as_string'] = string_to_datetime( _dict.get('key_as_string')) @@ -8421,7 +8346,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MetricAggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MetricAggregationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8457,16 +8382,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricResponse': """Initialize a MetricResponse object from a json dictionary.""" args = {} - valid_keys = ['aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MetricResponse: ' - + ', '.join(bad_keys)) if 'aggregations' in _dict: args['aggregations'] = [ - MetricAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + MetricAggregation.from_dict(x) + for x in _dict.get('aggregations') ] return cls(**args) @@ -8479,7 +8398,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -8488,7 +8407,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MetricResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MetricResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8530,18 +8449,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregation': """Initialize a MetricTokenAggregation object from a json dictionary.""" args = {} - valid_keys = ['event_type', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MetricTokenAggregation: ' - + ', '.join(bad_keys)) if 'event_type' in _dict: args['event_type'] = _dict.get('event_type') if 'results' in _dict: args['results'] = [ - MetricTokenAggregationResult._from_dict(x) - for x in (_dict.get('results')) + MetricTokenAggregationResult.from_dict(x) + for x in _dict.get('results') ] return cls(**args) @@ -8556,7 +8469,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'event_type') and self.event_type is not None: _dict['event_type'] = self.event_type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] return _dict def _to_dict(self): @@ -8565,7 +8478,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MetricTokenAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MetricTokenAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8613,12 +8526,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregationResult': """Initialize a MetricTokenAggregationResult object from a json dictionary.""" args = {} - valid_keys = ['key', 'matching_results', 'event_rate'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MetricTokenAggregationResult: ' - + ', '.join(bad_keys)) if 'key' in _dict: args['key'] = _dict.get('key') if 'matching_results' in _dict: @@ -8650,7 +8557,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MetricTokenAggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MetricTokenAggregationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8686,16 +8593,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricTokenResponse': """Initialize a MetricTokenResponse object from a json dictionary.""" args = {} - valid_keys = ['aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class MetricTokenResponse: ' - + ', '.join(bad_keys)) if 'aggregations' in _dict: args['aggregations'] = [ - MetricTokenAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + MetricTokenAggregation.from_dict(x) + for x in _dict.get('aggregations') ] return cls(**args) @@ -8708,7 +8609,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -8717,7 +8618,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this MetricTokenResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'MetricTokenResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8730,73 +8631,6 @@ def __ne__(self, other: 'MetricTokenResponse') -> bool: return not self == other -class NluEnrichmentCategories(): - """ - An object that indicates the Categories enrichment will be applied to the specified - field. - - """ - - def __init__(self, **kwargs) -> None: - """ - Initialize a NluEnrichmentCategories object. - - :param **kwargs: (optional) Any additional properties. - """ - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentCategories': - """Initialize a NluEnrichmentCategories object from a json dictionary.""" - args = {} - xtra = _dict.copy() - args.update(xtra) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentCategories 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, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def __setattr__(self, name: str, value: object) -> None: - properties = {} - if not hasattr(self, '_additionalProperties'): - super(NluEnrichmentCategories, - self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(NluEnrichmentCategories, self).__setattr__(name, value) - - def __str__(self) -> str: - """Return a `str` version of this NluEnrichmentCategories object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentCategories') -> 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: 'NluEnrichmentCategories') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class NluEnrichmentConcepts(): """ An object specifiying the concepts enrichment and related parameters. @@ -8818,12 +8652,6 @@ def __init__(self, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'NluEnrichmentConcepts': """Initialize a NluEnrichmentConcepts object from a json dictionary.""" args = {} - valid_keys = ['limit'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class NluEnrichmentConcepts: ' - + ', '.join(bad_keys)) if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) @@ -8846,7 +8674,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this NluEnrichmentConcepts object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'NluEnrichmentConcepts') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8888,12 +8716,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEmotion': """Initialize a NluEnrichmentEmotion object from a json dictionary.""" args = {} - valid_keys = ['document', 'targets'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class NluEnrichmentEmotion: ' - + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: @@ -8920,7 +8742,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this NluEnrichmentEmotion object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'NluEnrichmentEmotion') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8996,15 +8818,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEntities': """Initialize a NluEnrichmentEntities object from a json dictionary.""" args = {} - valid_keys = [ - 'sentiment', 'emotion', 'limit', 'mentions', 'mention_types', - 'sentence_locations', 'model' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class NluEnrichmentEntities: ' - + ', '.join(bad_keys)) if 'sentiment' in _dict: args['sentiment'] = _dict.get('sentiment') if 'emotion' in _dict: @@ -9053,7 +8866,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this NluEnrichmentEntities object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'NluEnrichmentEntities') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9078,8 +8891,8 @@ class NluEnrichmentFeatures(): sentiment extraction enrichment and related parameters. :attr NluEnrichmentEmotion emotion: (optional) An object specifying the emotion detection enrichment and related parameters. - :attr NluEnrichmentCategories categories: (optional) An object that indicates - the Categories enrichment will be applied to the specified field. + :attr dict categories: (optional) An object that indicates the Categories + enrichment will be applied to the specified field. :attr NluEnrichmentSemanticRoles semantic_roles: (optional) An object specifiying the semantic roles enrichment and related parameters. :attr NluEnrichmentRelations relations: (optional) An object specifying the @@ -9094,7 +8907,7 @@ def __init__(self, entities: 'NluEnrichmentEntities' = None, sentiment: 'NluEnrichmentSentiment' = None, emotion: 'NluEnrichmentEmotion' = None, - categories: 'NluEnrichmentCategories' = None, + categories: dict = None, semantic_roles: 'NluEnrichmentSemanticRoles' = None, relations: 'NluEnrichmentRelations' = None, concepts: 'NluEnrichmentConcepts' = None) -> None: @@ -9109,8 +8922,8 @@ def __init__(self, the sentiment extraction enrichment and related parameters. :param NluEnrichmentEmotion emotion: (optional) An object specifying the emotion detection enrichment and related parameters. - :param NluEnrichmentCategories categories: (optional) An object that - indicates the Categories enrichment will be applied to the specified field. + :param dict categories: (optional) An object that indicates the Categories + enrichment will be applied to the specified field. :param NluEnrichmentSemanticRoles semantic_roles: (optional) An object specifiying the semantic roles enrichment and related parameters. :param NluEnrichmentRelations relations: (optional) An object specifying @@ -9131,38 +8944,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentFeatures': """Initialize a NluEnrichmentFeatures object from a json dictionary.""" args = {} - valid_keys = [ - 'keywords', 'entities', 'sentiment', 'emotion', 'categories', - 'semantic_roles', 'relations', 'concepts' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class NluEnrichmentFeatures: ' - + ', '.join(bad_keys)) if 'keywords' in _dict: - args['keywords'] = NluEnrichmentKeywords._from_dict( + args['keywords'] = NluEnrichmentKeywords.from_dict( _dict.get('keywords')) if 'entities' in _dict: - args['entities'] = NluEnrichmentEntities._from_dict( + args['entities'] = NluEnrichmentEntities.from_dict( _dict.get('entities')) if 'sentiment' in _dict: - args['sentiment'] = NluEnrichmentSentiment._from_dict( + args['sentiment'] = NluEnrichmentSentiment.from_dict( _dict.get('sentiment')) if 'emotion' in _dict: - args['emotion'] = NluEnrichmentEmotion._from_dict( + args['emotion'] = NluEnrichmentEmotion.from_dict( _dict.get('emotion')) if 'categories' in _dict: - args['categories'] = NluEnrichmentCategories._from_dict( - _dict.get('categories')) + args['categories'] = _dict.get('categories') if 'semantic_roles' in _dict: - args['semantic_roles'] = NluEnrichmentSemanticRoles._from_dict( + args['semantic_roles'] = NluEnrichmentSemanticRoles.from_dict( _dict.get('semantic_roles')) if 'relations' in _dict: - args['relations'] = NluEnrichmentRelations._from_dict( + args['relations'] = NluEnrichmentRelations.from_dict( _dict.get('relations')) if 'concepts' in _dict: - args['concepts'] = NluEnrichmentConcepts._from_dict( + args['concepts'] = NluEnrichmentConcepts.from_dict( _dict.get('concepts')) return cls(**args) @@ -9175,21 +8978,21 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = self.keywords._to_dict() + _dict['keywords'] = self.keywords.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = self.entities._to_dict() + _dict['entities'] = self.entities.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment._to_dict() + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion._to_dict() + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = self.categories._to_dict() + _dict['categories'] = self.categories if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = self.semantic_roles._to_dict() + _dict['semantic_roles'] = self.semantic_roles.to_dict() if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = self.relations._to_dict() + _dict['relations'] = self.relations.to_dict() if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = self.concepts._to_dict() + _dict['concepts'] = self.concepts.to_dict() return _dict def _to_dict(self): @@ -9198,7 +9001,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this NluEnrichmentFeatures object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'NluEnrichmentFeatures') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9246,12 +9049,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentKeywords': """Initialize a NluEnrichmentKeywords object from a json dictionary.""" args = {} - valid_keys = ['sentiment', 'emotion', 'limit'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class NluEnrichmentKeywords: ' - + ', '.join(bad_keys)) if 'sentiment' in _dict: args['sentiment'] = _dict.get('sentiment') if 'emotion' in _dict: @@ -9282,7 +9079,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this NluEnrichmentKeywords object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'NluEnrichmentKeywords') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9320,12 +9117,6 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'NluEnrichmentRelations': """Initialize a NluEnrichmentRelations object from a json dictionary.""" args = {} - valid_keys = ['model'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class NluEnrichmentRelations: ' - + ', '.join(bad_keys)) if 'model' in _dict: args['model'] = _dict.get('model') return cls(**args) @@ -9348,7 +9139,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this NluEnrichmentRelations object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'NluEnrichmentRelations') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9396,12 +9187,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSemanticRoles': """Initialize a NluEnrichmentSemanticRoles object from a json dictionary.""" args = {} - valid_keys = ['entities', 'keywords', 'limit'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class NluEnrichmentSemanticRoles: ' - + ', '.join(bad_keys)) if 'entities' in _dict: args['entities'] = _dict.get('entities') if 'keywords' in _dict: @@ -9432,7 +9217,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this NluEnrichmentSemanticRoles object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'NluEnrichmentSemanticRoles') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9474,12 +9259,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSentiment': """Initialize a NluEnrichmentSentiment object from a json dictionary.""" args = {} - valid_keys = ['document', 'targets'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class NluEnrichmentSentiment: ' - + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: @@ -9506,7 +9285,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this NluEnrichmentSentiment object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'NluEnrichmentSentiment') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9599,12 +9378,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NormalizationOperation': """Initialize a NormalizationOperation object from a json dictionary.""" args = {} - valid_keys = ['operation', 'source_field', 'destination_field'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class NormalizationOperation: ' - + ', '.join(bad_keys)) if 'operation' in _dict: args['operation'] = _dict.get('operation') if 'source_field' in _dict: @@ -9636,7 +9409,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this NormalizationOperation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'NormalizationOperation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9648,7 +9421,7 @@ def __ne__(self, other: 'NormalizationOperation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class OperationEnum(Enum): + class OperationEnum(str, Enum): """ Identifies what type of operation to perform. **copy** - Copies the value of the **source_field** to the **destination_field** @@ -9675,11 +9448,11 @@ class OperationEnum(Enum): **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it can be time-expensive). """ - COPY = "copy" - MOVE = "move" - MERGE = "merge" - REMOVE = "remove" - REMOVE_NULLS = "remove_nulls" + COPY = 'copy' + MOVE = 'move' + MERGE = 'merge' + REMOVE = 'remove' + REMOVE_NULLS = 'remove_nulls' class Notice(): @@ -9725,31 +9498,6 @@ def __init__(self, """ Initialize a Notice object. - :param str notice_id: (optional) Identifies the notice. Many notices might - have the same ID. This field exists so that user applications can - programmatically identify a notice and take automatic corrective action. - Typical notice IDs include: `index_failed`, - `index_failed_too_many_requests`, `index_failed_incompatible_field`, - `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, - `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, - `smart_document_understanding_failed_incompatible_field`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_warning`, - `smart_document_understanding_page_error`, - `smart_document_understanding_page_warning`. **Note:** This is not a - complete list, other values might be returned. - :param datetime created: (optional) The creation date of the collection in - the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param str document_id: (optional) Unique identifier of the document. - :param str query_id: (optional) Unique identifier of the query used for - relevance training. - :param str severity: (optional) Severity level of the notice. - :param str step: (optional) Ingestion or training step in which the notice - occurred. Typical step values include: `classify_elements`, - `smartDocumentUnderstanding`, `ingestion`, `indexing`, `convert`. **Note:** - This is not a complete list, other values might be returned. - :param str description: (optional) The description of the notice. """ self.notice_id = notice_id self.created = created @@ -9763,15 +9511,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} - valid_keys = [ - 'notice_id', 'created', 'document_id', 'query_id', 'severity', - 'step', 'description' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Notice: ' + - ', '.join(bad_keys)) if 'notice_id' in _dict: args['notice_id'] = _dict.get('notice_id') if 'created' in _dict: @@ -9796,20 +9535,23 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'notice_id') and self.notice_id is not None: - _dict['notice_id'] = self.notice_id - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'query_id') and self.query_id is not None: - _dict['query_id'] = self.query_id - if hasattr(self, 'severity') and self.severity is not None: - _dict['severity'] = self.severity - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description + if hasattr(self, 'notice_id') and getattr(self, + 'notice_id') is not None: + _dict['notice_id'] = getattr(self, 'notice_id') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'document_id') and getattr(self, + 'document_id') is not None: + _dict['document_id'] = getattr(self, 'document_id') + if hasattr(self, 'query_id') and getattr(self, 'query_id') is not None: + _dict['query_id'] = getattr(self, 'query_id') + if hasattr(self, 'severity') and getattr(self, 'severity') is not None: + _dict['severity'] = getattr(self, 'severity') + if hasattr(self, 'step') and getattr(self, 'step') is not None: + _dict['step'] = getattr(self, 'step') + if hasattr(self, 'description') and getattr(self, + 'description') is not None: + _dict['description'] = getattr(self, 'description') return _dict def _to_dict(self): @@ -9818,7 +9560,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Notice object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Notice') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9830,12 +9572,12 @@ def __ne__(self, other: 'Notice') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class SeverityEnum(Enum): + class SeverityEnum(str, Enum): """ Severity level of the notice. """ - WARNING = "warning" - ERROR = "error" + WARNING = 'warning' + ERROR = 'error' class PdfHeadingDetection(): @@ -9858,15 +9600,9 @@ def __init__(self, *, fonts: List['FontSetting'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'PdfHeadingDetection': """Initialize a PdfHeadingDetection object from a json dictionary.""" args = {} - valid_keys = ['fonts'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class PdfHeadingDetection: ' - + ', '.join(bad_keys)) if 'fonts' in _dict: args['fonts'] = [ - FontSetting._from_dict(x) for x in (_dict.get('fonts')) + FontSetting.from_dict(x) for x in _dict.get('fonts') ] return cls(**args) @@ -9879,7 +9615,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fonts') and self.fonts is not None: - _dict['fonts'] = [x._to_dict() for x in self.fonts] + _dict['fonts'] = [x.to_dict() for x in self.fonts] return _dict def _to_dict(self): @@ -9888,7 +9624,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this PdfHeadingDetection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'PdfHeadingDetection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9922,14 +9658,8 @@ def __init__(self, *, heading: 'PdfHeadingDetection' = None) -> None: def from_dict(cls, _dict: Dict) -> 'PdfSettings': """Initialize a PdfSettings object from a json dictionary.""" args = {} - valid_keys = ['heading'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class PdfSettings: ' - + ', '.join(bad_keys)) if 'heading' in _dict: - args['heading'] = PdfHeadingDetection._from_dict( + args['heading'] = PdfHeadingDetection.from_dict( _dict.get('heading')) return cls(**args) @@ -9942,7 +9672,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'heading') and self.heading is not None: - _dict['heading'] = self.heading._to_dict() + _dict['heading'] = self.heading.to_dict() return _dict def _to_dict(self): @@ -9951,7 +9681,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this PdfSettings object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'PdfSettings') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -10005,24 +9735,17 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregation': if disc_class != cls: return disc_class.from_dict(_dict) args = {} - valid_keys = ['type', 'results', 'matching_results', 'aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryAggregation: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'results' in _dict: args['results'] = [ - AggregationResult._from_dict(x) for x in (_dict.get('results')) + AggregationResult.from_dict(x) for x in _dict.get('results') ] if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] return cls(**args) @@ -10037,12 +9760,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -10051,7 +9774,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -10137,29 +9860,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} - valid_keys = [ - 'matching_results', 'results', 'aggregations', 'passages', - 'duplicates_removed' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryNoticesResponse: ' - + ', '.join(bad_keys)) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - QueryNoticesResult._from_dict(x) for x in (_dict.get('results')) + QueryNoticesResult.from_dict(x) for x in _dict.get('results') ] if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] if 'passages' in _dict: args['passages'] = [ - QueryPassages._from_dict(x) for x in (_dict.get('passages')) + QueryPassages.from_dict(x) for x in _dict.get('passages') ] if 'duplicates_removed' in _dict: args['duplicates_removed'] = _dict.get('duplicates_removed') @@ -10177,11 +9890,11 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x._to_dict() for x in self.passages] + _dict['passages'] = [x.to_dict() for x in self.passages] if hasattr( self, 'duplicates_removed') and self.duplicates_removed is not None: @@ -10194,7 +9907,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryNoticesResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryNoticesResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -10226,6 +9939,12 @@ class QueryNoticesResult(): :attr List[Notice] notices: (optional) Array of notices for the document. """ + # The set of defined properties for the class + _properties = frozenset([ + 'id', 'metadata', 'collection_id', 'result_metadata', 'code', + 'filename', 'file_type', 'sha1', 'notices' + ]) + def __init__(self, *, id: str = None, @@ -10274,38 +9993,29 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNoticesResult': """Initialize a QueryNoticesResult object from a json dictionary.""" args = {} - xtra = _dict.copy() if 'id' in _dict: args['id'] = _dict.get('id') - del xtra['id'] if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') - del xtra['metadata'] if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') - del xtra['collection_id'] if 'result_metadata' in _dict: - args['result_metadata'] = QueryResultMetadata._from_dict( + args['result_metadata'] = QueryResultMetadata.from_dict( _dict.get('result_metadata')) - del xtra['result_metadata'] if 'code' in _dict: args['code'] = _dict.get('code') - del xtra['code'] if 'filename' in _dict: args['filename'] = _dict.get('filename') - del xtra['filename'] if 'file_type' in _dict: args['file_type'] = _dict.get('file_type') - del xtra['file_type'] if 'sha1' in _dict: args['sha1'] = _dict.get('sha1') - del xtra['sha1'] if 'notices' in _dict: args['notices'] = [ - Notice._from_dict(x) for x in (_dict.get('notices')) + Notice.from_dict(x) for x in _dict.get('notices') ] - del xtra['notices'] - args.update(xtra) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -10324,7 +10034,7 @@ def to_dict(self) -> Dict: _dict['collection_id'] = self.collection_id if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata._to_dict() + _dict['result_metadata'] = self.result_metadata.to_dict() if hasattr(self, 'code') and self.code is not None: _dict['code'] = self.code if hasattr(self, 'filename') and self.filename is not None: @@ -10334,33 +10044,22 @@ def to_dict(self) -> Dict: if hasattr(self, 'sha1') and self.sha1 is not None: _dict['sha1'] = self.sha1 if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x._to_dict() for x in self.notices] - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + _dict['notices'] = [x.to_dict() for x in self.notices] + for _key in [ + k for k in vars(self).keys() + if k not in QueryNoticesResult._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = { - 'id', 'metadata', 'collection_id', 'result_metadata', 'code', - 'filename', 'file_type', 'sha1', 'notices' - } - if not hasattr(self, '_additionalProperties'): - super(QueryNoticesResult, self).__setattr__('_additionalProperties', - set()) - if name not in properties: - self._additionalProperties.add(name) - super(QueryNoticesResult, self).__setattr__(name, value) - def __str__(self) -> str: """Return a `str` version of this QueryNoticesResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryNoticesResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -10372,14 +10071,14 @@ def __ne__(self, other: 'QueryNoticesResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class FileTypeEnum(Enum): + class FileTypeEnum(str, Enum): """ The type of the original source file. """ - PDF = "pdf" - HTML = "html" - WORD = "word" - JSON = "json" + PDF = 'pdf' + HTML = 'html' + WORD = 'word' + JSON = 'json' class QueryPassages(): @@ -10433,15 +10132,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryPassages': """Initialize a QueryPassages object from a json dictionary.""" args = {} - valid_keys = [ - 'document_id', 'passage_score', 'passage_text', 'start_offset', - 'end_offset', 'field' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryPassages: ' - + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'passage_score' in _dict: @@ -10484,7 +10174,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryPassages object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryPassages') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -10566,37 +10256,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResponse': """Initialize a QueryResponse object from a json dictionary.""" args = {} - valid_keys = [ - 'matching_results', 'results', 'aggregations', 'passages', - 'duplicates_removed', 'session_token', 'retrieval_details', - 'suggested_query' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryResponse: ' - + ', '.join(bad_keys)) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - QueryResult._from_dict(x) for x in (_dict.get('results')) + QueryResult.from_dict(x) for x in _dict.get('results') ] if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] if 'passages' in _dict: args['passages'] = [ - QueryPassages._from_dict(x) for x in (_dict.get('passages')) + QueryPassages.from_dict(x) for x in _dict.get('passages') ] if 'duplicates_removed' in _dict: args['duplicates_removed'] = _dict.get('duplicates_removed') if 'session_token' in _dict: args['session_token'] = _dict.get('session_token') if 'retrieval_details' in _dict: - args['retrieval_details'] = RetrievalDetails._from_dict( + args['retrieval_details'] = RetrievalDetails.from_dict( _dict.get('retrieval_details')) if 'suggested_query' in _dict: args['suggested_query'] = _dict.get('suggested_query') @@ -10614,11 +10293,11 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x._to_dict() for x in self.passages] + _dict['passages'] = [x.to_dict() for x in self.passages] if hasattr( self, 'duplicates_removed') and self.duplicates_removed is not None: @@ -10627,7 +10306,7 @@ def to_dict(self) -> Dict: _dict['session_token'] = self.session_token if hasattr(self, 'retrieval_details') and self.retrieval_details is not None: - _dict['retrieval_details'] = self.retrieval_details._to_dict() + _dict['retrieval_details'] = self.retrieval_details.to_dict() if hasattr(self, 'suggested_query') and self.suggested_query is not None: _dict['suggested_query'] = self.suggested_query @@ -10639,7 +10318,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -10664,6 +10343,10 @@ class QueryResult(): result. """ + # The set of defined properties for the class + _properties = frozenset( + ['id', 'metadata', 'collection_id', 'result_metadata']) + def __init__(self, *, id: str = None, @@ -10693,21 +10376,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResult': """Initialize a QueryResult object from a json dictionary.""" args = {} - xtra = _dict.copy() if 'id' in _dict: args['id'] = _dict.get('id') - del xtra['id'] if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') - del xtra['metadata'] if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') - del xtra['collection_id'] if 'result_metadata' in _dict: - args['result_metadata'] = QueryResultMetadata._from_dict( + args['result_metadata'] = QueryResultMetadata.from_dict( _dict.get('result_metadata')) - del xtra['result_metadata'] - args.update(xtra) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -10726,29 +10405,21 @@ def to_dict(self) -> Dict: _dict['collection_id'] = self.collection_id if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata._to_dict() - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + _dict['result_metadata'] = self.result_metadata.to_dict() + for _key in [ + k for k in vars(self).keys() if k not in QueryResult._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = {'id', 'metadata', 'collection_id', 'result_metadata'} - if not hasattr(self, '_additionalProperties'): - super(QueryResult, self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(QueryResult, self).__setattr__(name, value) - def __str__(self) -> str: """Return a `str` version of this QueryResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -10796,12 +10467,6 @@ def __init__(self, score: float, *, confidence: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} - valid_keys = ['score', 'confidence'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryResultMetadata: ' - + ', '.join(bad_keys)) if 'score' in _dict: args['score'] = _dict.get('score') else: @@ -10832,7 +10497,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryResultMetadata object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryResultMetadata') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -10881,12 +10546,6 @@ def __init__(self, *, document_retrieval_strategy: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': """Initialize a RetrievalDetails object from a json dictionary.""" args = {} - valid_keys = ['document_retrieval_strategy'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RetrievalDetails: ' - + ', '.join(bad_keys)) if 'document_retrieval_strategy' in _dict: args['document_retrieval_strategy'] = _dict.get( 'document_retrieval_strategy') @@ -10912,7 +10571,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RetrievalDetails object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RetrievalDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -10924,7 +10583,7 @@ def __ne__(self, other: 'RetrievalDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class DocumentRetrievalStrategyEnum(Enum): + class DocumentRetrievalStrategyEnum(str, Enum): """ Indentifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy @@ -10936,9 +10595,9 @@ class DocumentRetrievalStrategyEnum(Enum): model is not used to return results, the **document_retrieval_strategy** will be listed as `untrained`. """ - UNTRAINED = "untrained" - RELEVANCY_TRAINING = "relevancy_training" - CONTINUOUS_RELEVANCY_TRAINING = "continuous_relevancy_training" + UNTRAINED = 'untrained' + RELEVANCY_TRAINING = 'relevancy_training' + CONTINUOUS_RELEVANCY_TRAINING = 'continuous_relevancy_training' class SduStatus(): @@ -11010,15 +10669,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SduStatus': """Initialize a SduStatus object from a json dictionary.""" args = {} - valid_keys = [ - 'enabled', 'total_annotated_pages', 'total_pages', - 'total_documents', 'custom_fields' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SduStatus: ' - + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'total_annotated_pages' in _dict: @@ -11028,7 +10678,7 @@ def from_dict(cls, _dict: Dict) -> 'SduStatus': if 'total_documents' in _dict: args['total_documents'] = _dict.get('total_documents') if 'custom_fields' in _dict: - args['custom_fields'] = SduStatusCustomFields._from_dict( + args['custom_fields'] = SduStatusCustomFields.from_dict( _dict.get('custom_fields')) return cls(**args) @@ -11051,7 +10701,7 @@ def to_dict(self) -> Dict: 'total_documents') and self.total_documents is not None: _dict['total_documents'] = self.total_documents if hasattr(self, 'custom_fields') and self.custom_fields is not None: - _dict['custom_fields'] = self.custom_fields._to_dict() + _dict['custom_fields'] = self.custom_fields.to_dict() return _dict def _to_dict(self): @@ -11060,7 +10710,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SduStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SduStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -11103,12 +10753,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SduStatusCustomFields': """Initialize a SduStatusCustomFields object from a json dictionary.""" args = {} - valid_keys = ['defined', 'maximum_allowed'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SduStatusCustomFields: ' - + ', '.join(bad_keys)) if 'defined' in _dict: args['defined'] = _dict.get('defined') if 'maximum_allowed' in _dict: @@ -11136,7 +10780,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SduStatusCustomFields object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SduStatusCustomFields') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -11190,12 +10834,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchStatus': """Initialize a SearchStatus object from a json dictionary.""" args = {} - valid_keys = ['scope', 'status', 'status_description', 'last_trained'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SearchStatus: ' - + ', '.join(bad_keys)) if 'scope' in _dict: args['scope'] = _dict.get('scope') if 'status' in _dict: @@ -11203,7 +10841,7 @@ def from_dict(cls, _dict: Dict) -> 'SearchStatus': if 'status_description' in _dict: args['status_description'] = _dict.get('status_description') if 'last_trained' in _dict: - args['last_trained'] = _dict.get('last_trained') + args['last_trained'] = string_to_date(_dict.get('last_trained')) return cls(**args) @classmethod @@ -11223,7 +10861,7 @@ def to_dict(self) -> Dict: 'status_description') and self.status_description is not None: _dict['status_description'] = self.status_description if hasattr(self, 'last_trained') and self.last_trained is not None: - _dict['last_trained'] = self.last_trained + _dict['last_trained'] = date_to_string(self.last_trained) return _dict def _to_dict(self): @@ -11232,7 +10870,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SearchStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SearchStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -11244,15 +10882,15 @@ def __ne__(self, other: 'SearchStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The current status of Continuous Relevancy Training for this environment. """ - NO_DATA = "NO_DATA" - INSUFFICENT_DATA = "INSUFFICENT_DATA" - TRAINING = "TRAINING" - TRAINED = "TRAINED" - NOT_APPLICABLE = "NOT_APPLICABLE" + NO_DATA = 'NO_DATA' + INSUFFICENT_DATA = 'INSUFFICENT_DATA' + TRAINING = 'TRAINING' + TRAINED = 'TRAINED' + NOT_APPLICABLE = 'NOT_APPLICABLE' class SegmentSettings(): @@ -11314,12 +10952,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SegmentSettings': """Initialize a SegmentSettings object from a json dictionary.""" args = {} - valid_keys = ['enabled', 'selector_tags', 'annotated_fields'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SegmentSettings: ' - + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'selector_tags' in _dict: @@ -11351,7 +10983,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SegmentSettings object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SegmentSettings') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -11423,20 +11055,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Source': """Initialize a Source object from a json dictionary.""" args = {} - valid_keys = ['type', 'credential_id', 'schedule', 'options'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Source: ' + - ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'credential_id' in _dict: args['credential_id'] = _dict.get('credential_id') if 'schedule' in _dict: - args['schedule'] = SourceSchedule._from_dict(_dict.get('schedule')) + args['schedule'] = SourceSchedule.from_dict(_dict.get('schedule')) if 'options' in _dict: - args['options'] = SourceOptions._from_dict(_dict.get('options')) + args['options'] = SourceOptions.from_dict(_dict.get('options')) return cls(**args) @classmethod @@ -11452,9 +11078,9 @@ def to_dict(self) -> Dict: if hasattr(self, 'credential_id') and self.credential_id is not None: _dict['credential_id'] = self.credential_id if hasattr(self, 'schedule') and self.schedule is not None: - _dict['schedule'] = self.schedule._to_dict() + _dict['schedule'] = self.schedule.to_dict() if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options._to_dict() + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -11463,7 +11089,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Source object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Source') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -11475,7 +11101,7 @@ def __ne__(self, other: 'Source') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The type of source to connect to. - `box` indicates the configuration is to connect an instance of Enterprise Box. @@ -11486,11 +11112,11 @@ class TypeEnum(Enum): - `cloud_object_storage` indicates the configuration is to connect to a cloud object store. """ - BOX = "box" - SALESFORCE = "salesforce" - SHAREPOINT = "sharepoint" - WEB_CRAWL = "web_crawl" - CLOUD_OBJECT_STORAGE = "cloud_object_storage" + BOX = 'box' + SALESFORCE = 'salesforce' + SHAREPOINT = 'sharepoint' + WEB_CRAWL = 'web_crawl' + CLOUD_OBJECT_STORAGE = 'cloud_object_storage' class SourceOptions(): @@ -11563,38 +11189,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceOptions': """Initialize a SourceOptions object from a json dictionary.""" args = {} - valid_keys = [ - 'folders', 'objects', 'site_collections', 'urls', 'buckets', - 'crawl_all_buckets' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SourceOptions: ' - + ', '.join(bad_keys)) if 'folders' in _dict: args['folders'] = [ - SourceOptionsFolder._from_dict(x) - for x in (_dict.get('folders')) + SourceOptionsFolder.from_dict(x) for x in _dict.get('folders') ] if 'objects' in _dict: args['objects'] = [ - SourceOptionsObject._from_dict(x) - for x in (_dict.get('objects')) + SourceOptionsObject.from_dict(x) for x in _dict.get('objects') ] if 'site_collections' in _dict: args['site_collections'] = [ - SourceOptionsSiteColl._from_dict(x) - for x in (_dict.get('site_collections')) + SourceOptionsSiteColl.from_dict(x) + for x in _dict.get('site_collections') ] if 'urls' in _dict: args['urls'] = [ - SourceOptionsWebCrawl._from_dict(x) for x in (_dict.get('urls')) + SourceOptionsWebCrawl.from_dict(x) for x in _dict.get('urls') ] if 'buckets' in _dict: args['buckets'] = [ - SourceOptionsBuckets._from_dict(x) - for x in (_dict.get('buckets')) + SourceOptionsBuckets.from_dict(x) for x in _dict.get('buckets') ] if 'crawl_all_buckets' in _dict: args['crawl_all_buckets'] = _dict.get('crawl_all_buckets') @@ -11609,18 +11223,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'folders') and self.folders is not None: - _dict['folders'] = [x._to_dict() for x in self.folders] + _dict['folders'] = [x.to_dict() for x in self.folders] if hasattr(self, 'objects') and self.objects is not None: - _dict['objects'] = [x._to_dict() for x in self.objects] + _dict['objects'] = [x.to_dict() for x in self.objects] if hasattr(self, 'site_collections') and self.site_collections is not None: _dict['site_collections'] = [ - x._to_dict() for x in self.site_collections + x.to_dict() for x in self.site_collections ] if hasattr(self, 'urls') and self.urls is not None: - _dict['urls'] = [x._to_dict() for x in self.urls] + _dict['urls'] = [x.to_dict() for x in self.urls] if hasattr(self, 'buckets') and self.buckets is not None: - _dict['buckets'] = [x._to_dict() for x in self.buckets] + _dict['buckets'] = [x.to_dict() for x in self.buckets] if hasattr(self, 'crawl_all_buckets') and self.crawl_all_buckets is not None: _dict['crawl_all_buckets'] = self.crawl_all_buckets @@ -11632,7 +11246,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SourceOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SourceOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -11670,12 +11284,6 @@ def __init__(self, name: str, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'SourceOptionsBuckets': """Initialize a SourceOptionsBuckets object from a json dictionary.""" args = {} - valid_keys = ['name', 'limit'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SourceOptionsBuckets: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -11706,7 +11314,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SourceOptionsBuckets object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SourceOptionsBuckets') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -11752,12 +11360,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceOptionsFolder': """Initialize a SourceOptionsFolder object from a json dictionary.""" args = {} - valid_keys = ['owner_user_id', 'folder_id', 'limit'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SourceOptionsFolder: ' - + ', '.join(bad_keys)) if 'owner_user_id' in _dict: args['owner_user_id'] = _dict.get('owner_user_id') else: @@ -11796,7 +11398,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SourceOptionsFolder object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SourceOptionsFolder') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -11836,12 +11438,6 @@ def __init__(self, name: str, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'SourceOptionsObject': """Initialize a SourceOptionsObject object from a json dictionary.""" args = {} - valid_keys = ['name', 'limit'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SourceOptionsObject: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -11872,7 +11468,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SourceOptionsObject object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SourceOptionsObject') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -11916,12 +11512,6 @@ def __init__(self, site_collection_path: str, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'SourceOptionsSiteColl': """Initialize a SourceOptionsSiteColl object from a json dictionary.""" args = {} - valid_keys = ['site_collection_path', 'limit'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SourceOptionsSiteColl: ' - + ', '.join(bad_keys)) if 'site_collection_path' in _dict: args['site_collection_path'] = _dict.get('site_collection_path') else: @@ -11953,7 +11543,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SourceOptionsSiteColl object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SourceOptionsSiteColl') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -12050,16 +11640,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceOptionsWebCrawl': """Initialize a SourceOptionsWebCrawl object from a json dictionary.""" args = {} - valid_keys = [ - 'url', 'limit_to_starting_hosts', 'crawl_speed', - 'allow_untrusted_certificate', 'maximum_hops', 'request_timeout', - 'override_robots_txt', 'blacklist' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SourceOptionsWebCrawl: ' - + ', '.join(bad_keys)) if 'url' in _dict: args['url'] = _dict.get('url') else: @@ -12122,7 +11702,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SourceOptionsWebCrawl object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SourceOptionsWebCrawl') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -12134,7 +11714,7 @@ def __ne__(self, other: 'SourceOptionsWebCrawl') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class CrawlSpeedEnum(Enum): + class CrawlSpeedEnum(str, Enum): """ The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a time with a delay between each call. `normal` means as many as two URLs are @@ -12142,9 +11722,9 @@ class CrawlSpeedEnum(Enum): that up to ten URLs are fetched concurrently with a short delay between fetch calls. """ - GENTLE = "gentle" - NORMAL = "normal" - AGGRESSIVE = "aggressive" + GENTLE = 'gentle' + NORMAL = 'normal' + AGGRESSIVE = 'aggressive' class SourceSchedule(): @@ -12200,12 +11780,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceSchedule': """Initialize a SourceSchedule object from a json dictionary.""" args = {} - valid_keys = ['enabled', 'time_zone', 'frequency'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SourceSchedule: ' - + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'time_zone' in _dict: @@ -12236,7 +11810,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SourceSchedule object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SourceSchedule') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -12248,7 +11822,7 @@ def __ne__(self, other: 'SourceSchedule') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class FrequencyEnum(Enum): + class FrequencyEnum(str, Enum): """ The crawl schedule in the specified **time_zone**. - `five_minutes`: Runs every five minutes. @@ -12257,11 +11831,11 @@ class FrequencyEnum(Enum): - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - `monthly`: Runs the on the first Sunday of every month between 00:00 and 06:00. """ - DAILY = "daily" - WEEKLY = "weekly" - MONTHLY = "monthly" - FIVE_MINUTES = "five_minutes" - HOURLY = "hourly" + DAILY = 'daily' + WEEKLY = 'weekly' + MONTHLY = 'monthly' + FIVE_MINUTES = 'five_minutes' + HOURLY = 'hourly' class SourceStatus(): @@ -12306,12 +11880,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceStatus': """Initialize a SourceStatus object from a json dictionary.""" args = {} - valid_keys = ['status', 'next_crawl'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SourceStatus: ' - + ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') if 'next_crawl' in _dict: @@ -12338,7 +11906,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SourceStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SourceStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -12350,7 +11918,7 @@ def __ne__(self, other: 'SourceStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The current status of the source crawl for this collection. This field returns `not_configured` if the default configuration for this source does not have a @@ -12361,11 +11929,11 @@ class StatusEnum(Enum): automatically restart when possible. - `unknown` indicates that an unidentified error has occured in the service. """ - RUNNING = "running" - COMPLETE = "complete" - NOT_CONFIGURED = "not_configured" - QUEUED = "queued" - UNKNOWN = "unknown" + RUNNING = 'running' + COMPLETE = 'complete' + NOT_CONFIGURED = 'not_configured' + QUEUED = 'queued' + UNKNOWN = 'unknown' class TokenDictRule(): @@ -12407,12 +11975,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TokenDictRule': """Initialize a TokenDictRule object from a json dictionary.""" args = {} - valid_keys = ['text', 'tokens', 'readings', 'part_of_speech'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TokenDictRule: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -12458,7 +12020,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TokenDictRule object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TokenDictRule') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -12497,12 +12059,6 @@ def __init__(self, *, status: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TokenDictStatusResponse': """Initialize a TokenDictStatusResponse object from a json dictionary.""" args = {} - valid_keys = ['status', 'type'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TokenDictStatusResponse: ' - + ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') if 'type' in _dict: @@ -12529,7 +12085,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TokenDictStatusResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TokenDictStatusResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -12541,13 +12097,13 @@ def __ne__(self, other: 'TokenDictStatusResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Current wordlist status for the specified collection. """ - ACTIVE = "active" - PENDING = "pending" - NOT_FOUND = "not found" + ACTIVE = 'active' + PENDING = 'pending' + NOT_FOUND = 'not found' class TopHitsResults(): @@ -12577,18 +12133,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TopHitsResults': """Initialize a TopHitsResults object from a json dictionary.""" args = {} - valid_keys = ['matching_results', 'hits'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TopHitsResults: ' - + ', '.join(bad_keys)) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'hits' in _dict: - args['hits'] = [ - QueryResult._from_dict(x) for x in (_dict.get('hits')) - ] + args['hits'] = [QueryResult.from_dict(x) for x in _dict.get('hits')] return cls(**args) @classmethod @@ -12603,7 +12151,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = [x._to_dict() for x in self.hits] + _dict['hits'] = [x.to_dict() for x in self.hits] return _dict def _to_dict(self): @@ -12612,7 +12160,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TopHitsResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TopHitsResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -12658,19 +12206,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingDataSet': """Initialize a TrainingDataSet object from a json dictionary.""" args = {} - valid_keys = ['environment_id', 'collection_id', 'queries'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingDataSet: ' - + ', '.join(bad_keys)) if 'environment_id' in _dict: args['environment_id'] = _dict.get('environment_id') if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') if 'queries' in _dict: args['queries'] = [ - TrainingQuery._from_dict(x) for x in (_dict.get('queries')) + TrainingQuery.from_dict(x) for x in _dict.get('queries') ] return cls(**args) @@ -12687,7 +12229,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'queries') and self.queries is not None: - _dict['queries'] = [x._to_dict() for x in self.queries] + _dict['queries'] = [x.to_dict() for x in self.queries] return _dict def _to_dict(self): @@ -12696,7 +12238,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingDataSet object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingDataSet') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -12742,12 +12284,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingExample': """Initialize a TrainingExample object from a json dictionary.""" args = {} - valid_keys = ['document_id', 'cross_reference', 'relevance'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingExample: ' - + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'cross_reference' in _dict: @@ -12779,7 +12315,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingExample object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingExample') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -12812,15 +12348,9 @@ def __init__(self, *, examples: List['TrainingExample'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingExampleList': """Initialize a TrainingExampleList object from a json dictionary.""" args = {} - valid_keys = ['examples'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingExampleList: ' - + ', '.join(bad_keys)) if 'examples' in _dict: args['examples'] = [ - TrainingExample._from_dict(x) for x in (_dict.get('examples')) + TrainingExample.from_dict(x) for x in _dict.get('examples') ] return cls(**args) @@ -12833,7 +12363,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x._to_dict() for x in self.examples] + _dict['examples'] = [x.to_dict() for x in self.examples] return _dict def _to_dict(self): @@ -12842,7 +12372,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingExampleList object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingExampleList') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -12894,14 +12424,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingQuery': """Initialize a TrainingQuery object from a json dictionary.""" args = {} - valid_keys = [ - 'query_id', 'natural_language_query', 'filter', 'examples' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingQuery: ' - + ', '.join(bad_keys)) if 'query_id' in _dict: args['query_id'] = _dict.get('query_id') if 'natural_language_query' in _dict: @@ -12910,7 +12432,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingQuery': args['filter'] = _dict.get('filter') if 'examples' in _dict: args['examples'] = [ - TrainingExample._from_dict(x) for x in (_dict.get('examples')) + TrainingExample.from_dict(x) for x in _dict.get('examples') ] return cls(**args) @@ -12930,7 +12452,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'filter') and self.filter is not None: _dict['filter'] = self.filter if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x._to_dict() for x in self.examples] + _dict['examples'] = [x.to_dict() for x in self.examples] return _dict def _to_dict(self): @@ -12939,7 +12461,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingQuery object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingQuery') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -13024,17 +12546,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingStatus': """Initialize a TrainingStatus object from a json dictionary.""" args = {} - valid_keys = [ - 'total_examples', 'available', 'processing', - 'minimum_queries_added', 'minimum_examples_added', - 'sufficient_label_diversity', 'notices', 'successfully_trained', - 'data_updated' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingStatus: ' - + ', '.join(bad_keys)) if 'total_examples' in _dict: args['total_examples'] = _dict.get('total_examples') if 'available' in _dict: @@ -13097,7 +12608,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -13138,19 +12649,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'WordHeadingDetection': """Initialize a WordHeadingDetection object from a json dictionary.""" args = {} - valid_keys = ['fonts', 'styles'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WordHeadingDetection: ' - + ', '.join(bad_keys)) if 'fonts' in _dict: args['fonts'] = [ - FontSetting._from_dict(x) for x in (_dict.get('fonts')) + FontSetting.from_dict(x) for x in _dict.get('fonts') ] if 'styles' in _dict: args['styles'] = [ - WordStyle._from_dict(x) for x in (_dict.get('styles')) + WordStyle.from_dict(x) for x in _dict.get('styles') ] return cls(**args) @@ -13163,9 +12668,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fonts') and self.fonts is not None: - _dict['fonts'] = [x._to_dict() for x in self.fonts] + _dict['fonts'] = [x.to_dict() for x in self.fonts] if hasattr(self, 'styles') and self.styles is not None: - _dict['styles'] = [x._to_dict() for x in self.styles] + _dict['styles'] = [x.to_dict() for x in self.styles] return _dict def _to_dict(self): @@ -13174,7 +12679,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WordHeadingDetection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WordHeadingDetection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -13208,14 +12713,8 @@ def __init__(self, *, heading: 'WordHeadingDetection' = None) -> None: def from_dict(cls, _dict: Dict) -> 'WordSettings': """Initialize a WordSettings object from a json dictionary.""" args = {} - valid_keys = ['heading'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WordSettings: ' - + ', '.join(bad_keys)) if 'heading' in _dict: - args['heading'] = WordHeadingDetection._from_dict( + args['heading'] = WordHeadingDetection.from_dict( _dict.get('heading')) return cls(**args) @@ -13228,7 +12727,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'heading') and self.heading is not None: - _dict['heading'] = self.heading._to_dict() + _dict['heading'] = self.heading.to_dict() return _dict def _to_dict(self): @@ -13237,7 +12736,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WordSettings object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WordSettings') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -13274,12 +12773,6 @@ def __init__(self, *, level: int = None, names: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'WordStyle': """Initialize a WordStyle object from a json dictionary.""" args = {} - valid_keys = ['level', 'names'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WordStyle: ' - + ', '.join(bad_keys)) if 'level' in _dict: args['level'] = _dict.get('level') if 'names' in _dict: @@ -13306,7 +12799,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WordStyle object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WordStyle') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -13338,12 +12831,6 @@ def __init__(self, *, xpaths: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'XPathPatterns': """Initialize a XPathPatterns object from a json dictionary.""" args = {} - valid_keys = ['xpaths'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class XPathPatterns: ' - + ', '.join(bad_keys)) if 'xpaths' in _dict: args['xpaths'] = _dict.get('xpaths') return cls(**args) @@ -13366,7 +12853,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this XPathPatterns object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'XPathPatterns') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -13421,27 +12908,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Calculation': """Initialize a Calculation object from a json dictionary.""" args = {} - valid_keys = [ - 'type', 'results', 'matching_results', 'aggregations', 'field', - 'value' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Calculation: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'results' in _dict: args['results'] = [ - AggregationResult._from_dict(x) for x in (_dict.get('results')) + AggregationResult.from_dict(x) for x in _dict.get('results') ] if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] if 'field' in _dict: args['field'] = _dict.get('field') @@ -13460,12 +12937,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'value') and self.value is not None: @@ -13478,7 +12955,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Calculation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Calculation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -13527,26 +13004,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Filter': """Initialize a Filter object from a json dictionary.""" args = {} - valid_keys = [ - 'type', 'results', 'matching_results', 'aggregations', 'match' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Filter: ' + - ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'results' in _dict: args['results'] = [ - AggregationResult._from_dict(x) for x in (_dict.get('results')) + AggregationResult.from_dict(x) for x in _dict.get('results') ] if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] if 'match' in _dict: args['match'] = _dict.get('match') @@ -13563,12 +13031,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'match') and self.match is not None: _dict['match'] = self.match return _dict @@ -13579,7 +13047,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Filter object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Filter') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -13636,27 +13104,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Histogram': """Initialize a Histogram object from a json dictionary.""" args = {} - valid_keys = [ - 'type', 'results', 'matching_results', 'aggregations', 'field', - 'interval' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Histogram: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'results' in _dict: args['results'] = [ - AggregationResult._from_dict(x) for x in (_dict.get('results')) + AggregationResult.from_dict(x) for x in _dict.get('results') ] if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] if 'field' in _dict: args['field'] = _dict.get('field') @@ -13675,12 +13133,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'interval') and self.interval is not None: @@ -13693,7 +13151,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Histogram object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Histogram') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -13744,26 +13202,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Nested': """Initialize a Nested object from a json dictionary.""" args = {} - valid_keys = [ - 'type', 'results', 'matching_results', 'aggregations', 'path' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Nested: ' + - ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'results' in _dict: args['results'] = [ - AggregationResult._from_dict(x) for x in (_dict.get('results')) + AggregationResult.from_dict(x) for x in _dict.get('results') ] if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] if 'path' in _dict: args['path'] = _dict.get('path') @@ -13780,12 +13229,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'path') and self.path is not None: _dict['path'] = self.path return _dict @@ -13796,7 +13245,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Nested object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Nested') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -13851,27 +13300,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Term': """Initialize a Term object from a json dictionary.""" args = {} - valid_keys = [ - 'type', 'results', 'matching_results', 'aggregations', 'field', - 'count' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Term: ' + - ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'results' in _dict: args['results'] = [ - AggregationResult._from_dict(x) for x in (_dict.get('results')) + AggregationResult.from_dict(x) for x in _dict.get('results') ] if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] if 'field' in _dict: args['field'] = _dict.get('field') @@ -13890,12 +13329,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'count') and self.count is not None: @@ -13908,7 +13347,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Term object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Term') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -13975,27 +13414,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Timeslice': """Initialize a Timeslice object from a json dictionary.""" args = {} - valid_keys = [ - 'type', 'results', 'matching_results', 'aggregations', 'field', - 'interval', 'anomaly' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Timeslice: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'results' in _dict: args['results'] = [ - AggregationResult._from_dict(x) for x in (_dict.get('results')) + AggregationResult.from_dict(x) for x in _dict.get('results') ] if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] if 'field' in _dict: args['field'] = _dict.get('field') @@ -14016,12 +13445,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'interval') and self.interval is not None: @@ -14036,7 +13465,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Timeslice object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Timeslice') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -14089,32 +13518,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TopHits': """Initialize a TopHits object from a json dictionary.""" args = {} - valid_keys = [ - 'type', 'results', 'matching_results', 'aggregations', 'size', - 'hits' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TopHits: ' + - ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'results' in _dict: args['results'] = [ - AggregationResult._from_dict(x) for x in (_dict.get('results')) + AggregationResult.from_dict(x) for x in _dict.get('results') ] if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] if 'size' in _dict: args['size'] = _dict.get('size') if 'hits' in _dict: - args['hits'] = TopHitsResults._from_dict(_dict.get('hits')) + args['hits'] = TopHitsResults.from_dict(_dict.get('hits')) return cls(**args) @classmethod @@ -14128,16 +13547,16 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'size') and self.size is not None: _dict['size'] = self.size if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits._to_dict() + _dict['hits'] = self.hits.to_dict() return _dict def _to_dict(self): @@ -14146,7 +13565,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TopHits object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TopHits') -> bool: """Return `true` when self and other are equal, false otherwise.""" diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index a6f848347..9a069d4dc 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM-provided translation models that you can customize based on @@ -21,19 +23,18 @@ language, and more. """ -import json -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers 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.get_authenticator import get_authenticator_from_environment from os.path import basename -from typing import BinaryIO -from typing import Dict -from typing import List +from typing import BinaryIO, Dict, List, TextIO, Union +import json + +from ibm_cloud_sdk_core import BaseService, DetailedResponse +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime + +from .common import get_sdk_headers ############################################################################## # Service @@ -55,27 +56,21 @@ def __init__( """ Construct a new client for the Language Translator service. - :param str version: The API version date to use with the service, in - "YYYY-MM-DD" format. Whenever the API is changed in a backwards - incompatible way, a new minor version of the API is released. - The service uses the API version for the date you specify, or - the most recent version before that date. Note that you should - not programmatically specify the current date at runtime, in - case the API has been updated since your application's release. - Instead, specify a version date that is compatible with your - application, and don't change it until your application is - ready for a later version. + :param str version: Release date of the version of the API you want to use. + Specify dates in YYYY-MM-DD format. The current version is `2018-05-01`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + if version is None: + raise ValueError('version must be provided') + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.version = version self.configure_service(service_name) @@ -83,7 +78,7 @@ def __init__( # Languages ######################### - def list_languages(self, **kwargs) -> 'DetailedResponse': + def list_languages(self, **kwargs) -> DetailedResponse: """ List supported languages. @@ -96,12 +91,10 @@ def list_languages(self, **kwargs) -> 'DetailedResponse': :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Languages` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='list_languages') @@ -109,6 +102,10 @@ def list_languages(self, **kwargs) -> 'DetailedResponse': params = {'version': self.version} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v3/languages' request = self.prepare_request(method='GET', url=url, @@ -128,7 +125,7 @@ def translate(self, model_id: str = None, source: str = None, target: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Translate. @@ -157,15 +154,12 @@ def translate(self, language for translation. Required if model ID is not specified. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TranslationResult` object """ if text is None: raise ValueError('text 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='V3', operation_id='translate') @@ -179,6 +173,13 @@ def translate(self, 'source': source, 'target': target } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v3/translate' request = self.prepare_request(method='POST', @@ -194,7 +195,7 @@ def translate(self, # Identification ######################### - def list_identifiable_languages(self, **kwargs) -> 'DetailedResponse': + def list_identifiable_languages(self, **kwargs) -> DetailedResponse: """ List identifiable languages. @@ -203,12 +204,10 @@ def list_identifiable_languages(self, **kwargs) -> 'DetailedResponse': :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `IdentifiableLanguages` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', @@ -217,6 +216,10 @@ def list_identifiable_languages(self, **kwargs) -> 'DetailedResponse': params = {'version': self.version} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v3/identifiable_languages' request = self.prepare_request(method='GET', url=url, @@ -226,7 +229,7 @@ def list_identifiable_languages(self, **kwargs) -> 'DetailedResponse': response = self.send(request) return response - def identify(self, text: str, **kwargs) -> 'DetailedResponse': + def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: """ Identify language. @@ -235,15 +238,12 @@ def identify(self, text: str, **kwargs) -> 'DetailedResponse': :param str text: Input text in UTF-8 format. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `IdentifiedLanguages` object """ if text is None: raise ValueError('text 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='V3', operation_id='identify') @@ -254,6 +254,10 @@ def identify(self, text: str, **kwargs) -> 'DetailedResponse': data = text headers['content-type'] = 'text/plain' + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v3/identify' request = self.prepare_request(method='POST', url=url, @@ -273,7 +277,7 @@ def list_models(self, source: str = None, target: str = None, default: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List models. @@ -290,12 +294,10 @@ def list_models(self, exactly one default model, the IBM-provided base model, per language pair. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TranslationModels` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='list_models') @@ -308,6 +310,10 @@ def list_models(self, 'default': default } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v3/models' request = self.prepare_request(method='GET', url=url, @@ -323,7 +329,7 @@ def create_model(self, forced_glossary: BinaryIO = None, parallel_corpus: BinaryIO = None, name: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create model. @@ -391,8 +397,8 @@ def create_model(self, models` method. Most models that are provided with the service are customizable. In addition, all models that you create with parallel corpora customization can be further customized with a forced glossary. - :param TextIO forced_glossary: (optional) A file with forced glossary terms - for the source and target languages. The customizations in the file + :param BinaryIO forced_glossary: (optional) A file with forced glossary + terms for the source and target languages. The customizations in the file completely overwrite the domain translation data, including high frequency or high confidence phrase translations. You can upload only one glossary file for a custom model, and the glossary @@ -400,7 +406,7 @@ def create_model(self, words or short phrases. For more information, see **Supported file formats** in the method description. *With `curl`, use `--form forced_glossary=@{filename}`.*. - :param TextIO parallel_corpus: (optional) A file with parallel sentences + :param BinaryIO parallel_corpus: (optional) A file with parallel sentences for the source and target languages. You can upload multiple parallel corpus files in one request by repeating the parameter. All uploaded parallel corpus files combined must contain at least 5000 parallel @@ -417,15 +423,12 @@ def create_model(self, characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object """ if base_model_id is None: raise ValueError('base_model_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='V3', operation_id='create_model') @@ -445,6 +448,10 @@ def create_model(self, form_data.append(('parallel_corpus', (None, parallel_corpus, 'application/octet-stream'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v3/models' request = self.prepare_request(method='POST', url=url, @@ -455,7 +462,7 @@ def create_model(self, response = self.send(request) return response - def delete_model(self, model_id: str, **kwargs) -> 'DetailedResponse': + def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: """ Delete model. @@ -464,15 +471,12 @@ def delete_model(self, model_id: str, **kwargs) -> 'DetailedResponse': :param str model_id: Model ID of the model to delete. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DeleteModelResult` object """ if model_id is None: raise ValueError('model_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='V3', operation_id='delete_model') @@ -480,7 +484,14 @@ def delete_model(self, model_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v3/models/{0}'.format(*self._encode_path_vars(model_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v3/models/{model_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -489,7 +500,7 @@ def delete_model(self, model_id: str, **kwargs) -> 'DetailedResponse': response = self.send(request) return response - def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': + def get_model(self, model_id: str, **kwargs) -> DetailedResponse: """ Get model details. @@ -500,15 +511,12 @@ def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': :param str model_id: Model ID of the model to get. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object """ if model_id is None: raise ValueError('model_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='V3', operation_id='get_model') @@ -516,7 +524,14 @@ def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v3/models/{0}'.format(*self._encode_path_vars(model_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v3/models/{model_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -529,7 +544,7 @@ def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': # Document translation ######################### - def list_documents(self, **kwargs) -> 'DetailedResponse': + def list_documents(self, **kwargs) -> DetailedResponse: """ List documents. @@ -537,12 +552,10 @@ def list_documents(self, **kwargs) -> 'DetailedResponse': :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DocumentList` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='list_documents') @@ -550,6 +563,10 @@ def list_documents(self, **kwargs) -> 'DetailedResponse': params = {'version': self.version} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v3/documents' request = self.prepare_request(method='GET', url=url, @@ -568,7 +585,7 @@ def translate_document(self, source: str = None, target: str = None, document_id: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Translate document. @@ -578,7 +595,7 @@ def translate_document(self, * 20 MB for service instances on the Standard, Advanced, and Premium plans * 2 MB for service instances on the Lite plan. - :param TextIO file: The contents of the source file to translate. The + :param BinaryIO file: The contents of the source file to translate. The maximum file size for document translation is 20 MB for service instances on the Standard, Advanced, and Premium plans, and 2 MB for service instances on the Lite plan. For more information, see [Supported file @@ -602,15 +619,12 @@ def translate_document(self, document. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object """ if file is None: raise ValueError('file 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='V3', operation_id='translate_document') @@ -626,18 +640,18 @@ def translate_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if model_id: - model_id = str(model_id) form_data.append(('model_id', (None, model_id, 'text/plain'))) if source: - source = str(source) form_data.append(('source', (None, source, 'text/plain'))) if target: - target = str(target) form_data.append(('target', (None, target, 'text/plain'))) if document_id: - document_id = str(document_id) form_data.append(('document_id', (None, document_id, 'text/plain'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v3/documents' request = self.prepare_request(method='POST', url=url, @@ -649,7 +663,7 @@ def translate_document(self, return response def get_document_status(self, document_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get document status. @@ -658,15 +672,12 @@ def get_document_status(self, document_id: str, :param str document_id: The document ID of the document. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object """ if document_id is None: raise ValueError('document_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='V3', operation_id='get_document_status') @@ -674,7 +685,14 @@ def get_document_status(self, document_id: str, params = {'version': self.version} - url = '/v3/documents/{0}'.format(*self._encode_path_vars(document_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['document_id'] + path_param_values = self.encode_path_vars(document_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v3/documents/{document_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -683,7 +701,7 @@ def get_document_status(self, document_id: str, response = self.send(request) return response - def delete_document(self, document_id: str, **kwargs) -> 'DetailedResponse': + def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: """ Delete document. @@ -697,10 +715,7 @@ def delete_document(self, document_id: str, **kwargs) -> 'DetailedResponse': if document_id is None: raise ValueError('document_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='V3', operation_id='delete_document') @@ -708,7 +723,13 @@ def delete_document(self, document_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v3/documents/{0}'.format(*self._encode_path_vars(document_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['document_id'] + path_param_values = self.encode_path_vars(document_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v3/documents/{document_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -721,7 +742,7 @@ def get_translated_document(self, document_id: str, *, accept: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get translated document. @@ -745,15 +766,12 @@ def get_translated_document(self, example, 'text/html;charset=utf-8'. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `BinaryIO` result """ if document_id is None: raise ValueError('document_id must be provided') - headers = {'Accept': accept} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='get_translated_document') @@ -761,8 +779,14 @@ def get_translated_document(self, params = {'version': self.version} - url = '/v3/documents/{0}/translated_document'.format( - *self._encode_path_vars(document_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['document_id'] + path_param_values = self.encode_path_vars(document_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v3/documents/{document_id}/translated_document'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -772,9 +796,12 @@ def get_translated_document(self, return response -class TranslateDocumentEnums(object): +class TranslateDocumentEnums: + """ + Enums for translate_document parameters. + """ - class FileContentType(Enum): + class FileContentType(str, Enum): """ The content type of file. """ @@ -805,9 +832,12 @@ class FileContentType(Enum): TEXT_XML = 'text/xml' -class GetTranslatedDocumentEnums(object): +class GetTranslatedDocumentEnums: + """ + Enums for get_translated_document parameters. + """ - class Accept(Enum): + class Accept(str, Enum): """ The type of the response: application/powerpoint, application/mspowerpoint, application/x-rtf, application/json, application/xml, application/vnd.ms-excel, @@ -871,12 +901,6 @@ def __init__(self, status: str) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteModelResult': """Initialize a DeleteModelResult object from a json dictionary.""" args = {} - valid_keys = ['status'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DeleteModelResult: ' - + ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') else: @@ -903,7 +927,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DeleteModelResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DeleteModelResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -937,15 +961,9 @@ def __init__(self, documents: List['DocumentStatus']) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentList': """Initialize a DocumentList object from a json dictionary.""" args = {} - valid_keys = ['documents'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentList: ' - + ', '.join(bad_keys)) if 'documents' in _dict: args['documents'] = [ - DocumentStatus._from_dict(x) for x in (_dict.get('documents')) + DocumentStatus.from_dict(x) for x in _dict.get('documents') ] else: raise ValueError( @@ -962,7 +980,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'documents') and self.documents is not None: - _dict['documents'] = [x._to_dict() for x in self.documents] + _dict['documents'] = [x.to_dict() for x in self.documents] return _dict def _to_dict(self): @@ -971,7 +989,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocumentList object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocumentList') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1072,16 +1090,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentStatus': """Initialize a DocumentStatus object from a json dictionary.""" args = {} - valid_keys = [ - 'document_id', 'filename', 'status', 'model_id', 'base_model_id', - 'source', 'detected_language_confidence', 'target', 'created', - 'completed', 'word_count', 'character_count' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentStatus: ' - + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') else: @@ -1180,7 +1188,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocumentStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocumentStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1192,13 +1200,13 @@ def __ne__(self, other: 'DocumentStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The status of the translation job associated with a submitted document. """ - PROCESSING = "processing" - AVAILABLE = "available" - FAILED = "failed" + PROCESSING = 'processing' + AVAILABLE = 'available' + FAILED = 'failed' class IdentifiableLanguage(): @@ -1223,12 +1231,6 @@ def __init__(self, language: str, name: str) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguage': """Initialize a IdentifiableLanguage object from a json dictionary.""" args = {} - valid_keys = ['language', 'name'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class IdentifiableLanguage: ' - + ', '.join(bad_keys)) if 'language' in _dict: args['language'] = _dict.get('language') else: @@ -1263,7 +1265,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this IdentifiableLanguage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'IdentifiableLanguage') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1297,16 +1299,10 @@ def __init__(self, languages: List['IdentifiableLanguage']) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguages': """Initialize a IdentifiableLanguages object from a json dictionary.""" args = {} - valid_keys = ['languages'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class IdentifiableLanguages: ' - + ', '.join(bad_keys)) if 'languages' in _dict: args['languages'] = [ - IdentifiableLanguage._from_dict(x) - for x in (_dict.get('languages')) + IdentifiableLanguage.from_dict(x) + for x in _dict.get('languages') ] else: raise ValueError( @@ -1323,7 +1319,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x._to_dict() for x in self.languages] + _dict['languages'] = [x.to_dict() for x in self.languages] return _dict def _to_dict(self): @@ -1332,7 +1328,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this IdentifiableLanguages object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'IdentifiableLanguages') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1367,12 +1363,6 @@ def __init__(self, language: str, confidence: float) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguage': """Initialize a IdentifiedLanguage object from a json dictionary.""" args = {} - valid_keys = ['language', 'confidence'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class IdentifiedLanguage: ' - + ', '.join(bad_keys)) if 'language' in _dict: args['language'] = _dict.get('language') else: @@ -1407,7 +1397,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this IdentifiedLanguage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'IdentifiedLanguage') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1441,16 +1431,9 @@ def __init__(self, languages: List['IdentifiedLanguage']) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguages': """Initialize a IdentifiedLanguages object from a json dictionary.""" args = {} - valid_keys = ['languages'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class IdentifiedLanguages: ' - + ', '.join(bad_keys)) if 'languages' in _dict: args['languages'] = [ - IdentifiedLanguage._from_dict(x) - for x in (_dict.get('languages')) + IdentifiedLanguage.from_dict(x) for x in _dict.get('languages') ] else: raise ValueError( @@ -1467,7 +1450,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x._to_dict() for x in self.languages] + _dict['languages'] = [x.to_dict() for x in self.languages] return _dict def _to_dict(self): @@ -1476,7 +1459,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this IdentifiedLanguages object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'IdentifiedLanguages') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1568,16 +1551,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Language': """Initialize a Language object from a json dictionary.""" args = {} - valid_keys = [ - 'language', 'language_name', 'native_language_name', 'country_code', - 'words_separated', 'direction', 'supported_as_source', - 'supported_as_target', 'identifiable' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Language: ' - + ', '.join(bad_keys)) if 'language' in _dict: args['language'] = _dict.get('language') if 'language_name' in _dict: @@ -1638,7 +1611,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Language object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Language') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1672,15 +1645,9 @@ def __init__(self, languages: List['Language']) -> None: def from_dict(cls, _dict: Dict) -> 'Languages': """Initialize a Languages object from a json dictionary.""" args = {} - valid_keys = ['languages'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Languages: ' - + ', '.join(bad_keys)) if 'languages' in _dict: args['languages'] = [ - Language._from_dict(x) for x in (_dict.get('languages')) + Language.from_dict(x) for x in _dict.get('languages') ] else: raise ValueError( @@ -1696,7 +1663,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x._to_dict() for x in self.languages] + _dict['languages'] = [x.to_dict() for x in self.languages] return _dict def _to_dict(self): @@ -1705,7 +1672,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Languages object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Languages') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1737,12 +1704,6 @@ def __init__(self, translation: str) -> None: def from_dict(cls, _dict: Dict) -> 'Translation': """Initialize a Translation object from a json dictionary.""" args = {} - valid_keys = ['translation'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Translation: ' - + ', '.join(bad_keys)) if 'translation' in _dict: args['translation'] = _dict.get('translation') else: @@ -1769,7 +1730,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Translation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Translation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1859,15 +1820,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TranslationModel': """Initialize a TranslationModel object from a json dictionary.""" args = {} - valid_keys = [ - 'model_id', 'name', 'source', 'target', 'base_model_id', 'domain', - 'customizable', 'default_model', 'owner', 'status' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TranslationModel: ' - + ', '.join(bad_keys)) if 'model_id' in _dict: args['model_id'] = _dict.get('model_id') else: @@ -1930,7 +1882,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TranslationModel object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TranslationModel') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1942,20 +1894,20 @@ def __ne__(self, other: 'TranslationModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Availability of a model. """ - UPLOADING = "uploading" - UPLOADED = "uploaded" - DISPATCHING = "dispatching" - QUEUED = "queued" - TRAINING = "training" - TRAINED = "trained" - PUBLISHING = "publishing" - AVAILABLE = "available" - DELETED = "deleted" - ERROR = "error" + UPLOADING = 'uploading' + UPLOADED = 'uploaded' + DISPATCHING = 'dispatching' + QUEUED = 'queued' + TRAINING = 'training' + TRAINED = 'trained' + PUBLISHING = 'publishing' + AVAILABLE = 'available' + DELETED = 'deleted' + ERROR = 'error' class TranslationModels(): @@ -1977,15 +1929,9 @@ def __init__(self, models: List['TranslationModel']) -> None: def from_dict(cls, _dict: Dict) -> 'TranslationModels': """Initialize a TranslationModels object from a json dictionary.""" args = {} - valid_keys = ['models'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TranslationModels: ' - + ', '.join(bad_keys)) if 'models' in _dict: args['models'] = [ - TranslationModel._from_dict(x) for x in (_dict.get('models')) + TranslationModel.from_dict(x) for x in _dict.get('models') ] else: raise ValueError( @@ -2002,7 +1948,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x._to_dict() for x in self.models] + _dict['models'] = [x.to_dict() for x in self.models] return _dict def _to_dict(self): @@ -2011,7 +1957,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TranslationModels object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TranslationModels') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2072,15 +2018,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TranslationResult': """Initialize a TranslationResult object from a json dictionary.""" args = {} - valid_keys = [ - 'word_count', 'character_count', 'detected_language', - 'detected_language_confidence', 'translations' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TranslationResult: ' - + ', '.join(bad_keys)) if 'word_count' in _dict: args['word_count'] = _dict.get('word_count') else: @@ -2100,7 +2037,7 @@ def from_dict(cls, _dict: Dict) -> 'TranslationResult': 'detected_language_confidence') if 'translations' in _dict: args['translations'] = [ - Translation._from_dict(x) for x in (_dict.get('translations')) + Translation.from_dict(x) for x in _dict.get('translations') ] else: raise ValueError( @@ -2129,7 +2066,7 @@ def to_dict(self) -> Dict: _dict[ 'detected_language_confidence'] = self.detected_language_confidence if hasattr(self, 'translations') and self.translations is not None: - _dict['translations'] = [x._to_dict() for x in self.translations] + _dict['translations'] = [x.to_dict() for x in self.translations] return _dict def _to_dict(self): @@ -2138,7 +2075,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TranslationResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TranslationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 6417b9571..16144ce72 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ IBM Watson™ Natural Language Classifier uses machine learning algorithms to return the top matching predefined classes for short text input. You create and train a @@ -20,18 +22,17 @@ those classes to new inputs. """ -import json -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers 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 typing import BinaryIO, Dict, List +import json + +from ibm_cloud_sdk_core import BaseService, DetailedResponse +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator 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 ibm_cloud_sdk_core.utils import convert_model, datetime_to_string, string_to_datetime + +from .common import get_sdk_headers ############################################################################## # Service @@ -60,8 +61,7 @@ def __init__( authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.configure_service(service_name) ######################### @@ -69,7 +69,7 @@ def __init__( ######################### def classify(self, classifier_id: str, text: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Classify a phrase. @@ -81,26 +81,33 @@ def classify(self, classifier_id: str, text: str, characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Classification` object """ if classifier_id is None: raise ValueError('classifier_id must be provided') if text is None: raise ValueError('text 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='V1', operation_id='classify') headers.update(sdk_headers) data = {'text': text} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/classifiers/{0}/classify'.format( - *self._encode_path_vars(classifier_id)) + path_param_keys = ['classifier_id'] + path_param_values = self.encode_path_vars(classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/classifiers/{classifier_id}/classify'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -111,7 +118,7 @@ def classify(self, classifier_id: str, text: str, def classify_collection(self, classifier_id: str, collection: List['ClassifyInput'], - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Classify multiple phrases. @@ -123,27 +130,34 @@ def classify_collection(self, classifier_id: str, :param List[ClassifyInput] collection: The submitted phrases. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ClassificationCollection` object """ if classifier_id is None: raise ValueError('classifier_id must be provided') if collection is None: raise ValueError('collection must be provided') - collection = [self._convert_model(x) for x in collection] - + collection = [convert_model(x) for x in collection] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='classify_collection') headers.update(sdk_headers) data = {'collection': collection} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/classifiers/{0}/classify_collection'.format( - *self._encode_path_vars(classifier_id)) + path_param_keys = ['classifier_id'] + path_param_values = self.encode_path_vars(classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/classifiers/{classifier_id}/classify_collection'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -158,37 +172,34 @@ def classify_collection(self, classifier_id: str, def create_classifier(self, training_metadata: BinaryIO, training_data: BinaryIO, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create classifier. Sends data to create and train a classifier and returns information about the new classifier. - :param TextIO training_metadata: Metadata in JSON format. The metadata + :param BinaryIO training_metadata: Metadata in JSON format. The metadata identifies the language of the data, and an optional name to identify the classifier. Specify the language with the 2-letter primary language code as assigned in ISO standard 639. Supported languages are English (`en`), Arabic (`ar`), French (`fr`), German, (`de`), Italian (`it`), Japanese (`ja`), Korean (`ko`), Brazilian Portuguese (`pt`), and Spanish (`es`). - :param TextIO training_data: Training data in CSV format. Each text value + :param BinaryIO 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/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 + :rtype: DetailedResponse with `dict` result representing a `Classifier` object """ if training_metadata is None: raise ValueError('training_metadata must be provided') if training_data is None: raise ValueError('training_data 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='V1', operation_id='create_classifier') @@ -199,6 +210,10 @@ def create_classifier(self, training_metadata: BinaryIO, 'application/json'))) form_data.append(('training_data', (None, training_data, 'text/csv'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/classifiers' request = self.prepare_request(method='POST', url=url, @@ -208,7 +223,7 @@ def create_classifier(self, training_metadata: BinaryIO, response = self.send(request) return response - def list_classifiers(self, **kwargs) -> 'DetailedResponse': + def list_classifiers(self, **kwargs) -> DetailedResponse: """ List classifiers. @@ -216,25 +231,26 @@ def list_classifiers(self, **kwargs) -> 'DetailedResponse': :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ClassifierList` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='list_classifiers') headers.update(sdk_headers) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/classifiers' request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response - def get_classifier(self, classifier_id: str, - **kwargs) -> 'DetailedResponse': + def get_classifier(self, classifier_id: str, **kwargs) -> DetailedResponse: """ Get information about a classifier. @@ -243,29 +259,32 @@ def get_classifier(self, classifier_id: str, :param str classifier_id: Classifier ID to query. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Classifier` object """ if classifier_id is None: raise ValueError('classifier_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='V1', operation_id='get_classifier') headers.update(sdk_headers) - url = '/v1/classifiers/{0}'.format( - *self._encode_path_vars(classifier_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['classifier_id'] + path_param_values = self.encode_path_vars(classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/classifiers/{classifier_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response def delete_classifier(self, classifier_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete classifier. @@ -277,17 +296,20 @@ def delete_classifier(self, classifier_id: str, if classifier_id is None: raise ValueError('classifier_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='V1', operation_id='delete_classifier') headers.update(sdk_headers) - url = '/v1/classifiers/{0}'.format( - *self._encode_path_vars(classifier_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['classifier_id'] + path_param_values = self.encode_path_vars(classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/classifiers/{classifier_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers) @@ -340,12 +362,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Classification': """Initialize a Classification object from a json dictionary.""" args = {} - valid_keys = ['classifier_id', 'url', 'text', 'top_class', 'classes'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Classification: ' - + ', '.join(bad_keys)) if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') if 'url' in _dict: @@ -356,7 +372,7 @@ def from_dict(cls, _dict: Dict) -> 'Classification': args['top_class'] = _dict.get('top_class') if 'classes' in _dict: args['classes'] = [ - ClassifiedClass._from_dict(x) for x in (_dict.get('classes')) + ClassifiedClass.from_dict(x) for x in _dict.get('classes') ] return cls(**args) @@ -377,7 +393,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'top_class') and self.top_class is not None: _dict['top_class'] = self.top_class if hasattr(self, 'classes') and self.classes is not None: - _dict['classes'] = [x._to_dict() for x in self.classes] + _dict['classes'] = [x.to_dict() for x in self.classes] return _dict def _to_dict(self): @@ -386,7 +402,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Classification object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Classification') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -430,19 +446,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassificationCollection': """Initialize a ClassificationCollection object from a json dictionary.""" args = {} - valid_keys = ['classifier_id', 'url', 'collection'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ClassificationCollection: ' - + ', '.join(bad_keys)) if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') if 'url' in _dict: args['url'] = _dict.get('url') if 'collection' in _dict: args['collection'] = [ - CollectionItem._from_dict(x) for x in (_dict.get('collection')) + CollectionItem.from_dict(x) for x in _dict.get('collection') ] return cls(**args) @@ -459,7 +469,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url if hasattr(self, 'collection') and self.collection is not None: - _dict['collection'] = [x._to_dict() for x in self.collection] + _dict['collection'] = [x.to_dict() for x in self.collection] return _dict def _to_dict(self): @@ -468,7 +478,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ClassificationCollection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ClassificationCollection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -510,12 +520,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassifiedClass': """Initialize a ClassifiedClass object from a json dictionary.""" args = {} - valid_keys = ['confidence', 'class_name'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ClassifiedClass: ' - + ', '.join(bad_keys)) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') if 'class_name' in _dict: @@ -542,7 +546,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ClassifiedClass object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ClassifiedClass') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -584,11 +588,6 @@ def __init__(self, :param str url: Link to the classifier. :param str classifier_id: Unique identifier for this classifier. :param str name: (optional) User-supplied name for the classifier. - :param str status: (optional) The state of the classifier. - :param datetime created: (optional) Date and time (UTC) the classifier was - created. - :param str status_description: (optional) Additional detail about the - status. :param str language: (optional) The language used for the classifier. """ self.name = name @@ -603,15 +602,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Classifier': """Initialize a Classifier object from a json dictionary.""" args = {} - valid_keys = [ - 'name', 'url', 'status', 'classifier_id', 'created', - 'status_description', 'language' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Classifier: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') if 'url' in _dict: @@ -647,16 +637,15 @@ def to_dict(self) -> Dict: _dict['name'] = self.name if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') if hasattr(self, 'classifier_id') and self.classifier_id is not None: _dict['classifier_id'] = self.classifier_id - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr( - self, - 'status_description') and self.status_description is not None: - _dict['status_description'] = self.status_description + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language return _dict @@ -667,7 +656,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Classifier object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Classifier') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -679,15 +668,15 @@ def __ne__(self, other: 'Classifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The state of the classifier. """ - NON_EXISTENT = "Non Existent" - TRAINING = "Training" - FAILED = "Failed" - AVAILABLE = "Available" - UNAVAILABLE = "Unavailable" + NON_EXISTENT = 'Non Existent' + TRAINING = 'Training' + FAILED = 'Failed' + AVAILABLE = 'Available' + UNAVAILABLE = 'Unavailable' class ClassifierList(): @@ -711,15 +700,9 @@ def __init__(self, classifiers: List['Classifier']) -> None: def from_dict(cls, _dict: Dict) -> 'ClassifierList': """Initialize a ClassifierList object from a json dictionary.""" args = {} - valid_keys = ['classifiers'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ClassifierList: ' - + ', '.join(bad_keys)) if 'classifiers' in _dict: args['classifiers'] = [ - Classifier._from_dict(x) for x in (_dict.get('classifiers')) + Classifier.from_dict(x) for x in _dict.get('classifiers') ] else: raise ValueError( @@ -736,7 +719,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'classifiers') and self.classifiers is not None: - _dict['classifiers'] = [x._to_dict() for x in self.classifiers] + _dict['classifiers'] = [x.to_dict() for x in self.classifiers] return _dict def _to_dict(self): @@ -745,7 +728,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ClassifierList object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ClassifierList') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -778,12 +761,6 @@ def __init__(self, text: str) -> None: def from_dict(cls, _dict: Dict) -> 'ClassifyInput': """Initialize a ClassifyInput object from a json dictionary.""" args = {} - valid_keys = ['text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ClassifyInput: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -809,7 +786,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ClassifyInput object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ClassifyInput') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -855,19 +832,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CollectionItem': """Initialize a CollectionItem object from a json dictionary.""" args = {} - valid_keys = ['text', 'top_class', 'classes'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CollectionItem: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'top_class' in _dict: args['top_class'] = _dict.get('top_class') if 'classes' in _dict: args['classes'] = [ - ClassifiedClass._from_dict(x) for x in (_dict.get('classes')) + ClassifiedClass.from_dict(x) for x in _dict.get('classes') ] return cls(**args) @@ -884,7 +855,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'top_class') and self.top_class is not None: _dict['top_class'] = self.top_class if hasattr(self, 'classes') and self.classes is not None: - _dict['classes'] = [x._to_dict() for x in self.classes] + _dict['classes'] = [x.to_dict() for x in self.classes] return _dict def _to_dict(self): @@ -893,7 +864,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CollectionItem object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CollectionItem') -> bool: """Return `true` when self and other are equal, false otherwise.""" diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 4c9c909fb..a48bae47e 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you @@ -24,17 +26,17 @@ Understanding. """ -import json -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers 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 typing import Dict, List +import json + +from ibm_cloud_sdk_core import BaseService, DetailedResponse +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from typing import Dict -from typing import List +from ibm_cloud_sdk_core.utils import convert_model, datetime_to_string, string_to_datetime + +from .common import get_sdk_headers ############################################################################## # Service @@ -56,27 +58,21 @@ def __init__( """ Construct a new client for the Natural Language Understanding service. - :param str version: The API version date to use with the service, in - "YYYY-MM-DD" format. Whenever the API is changed in a backwards - incompatible way, a new minor version of the API is released. - The service uses the API version for the date you specify, or - the most recent version before that date. Note that you should - not programmatically specify the current date at runtime, in - case the API has been updated since your application's release. - Instead, specify a version date that is compatible with your - application, and don't change it until your application is - ready for a later version. + :param str version: Release date of the API version you want to use. + Specify dates in YYYY-MM-DD format. The current version is `2020-08-01`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + if version is None: + raise ValueError('version must be provided') + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.version = version self.configure_service(service_name) @@ -96,7 +92,7 @@ def analyze(self, return_analyzed_text: bool = None, language: str = None, limit_text_characters: int = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Analyze text. @@ -144,16 +140,13 @@ def analyze(self, characters that are processed by the service. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `AnalysisResults` object """ if features is None: raise ValueError('features must be provided') - features = self._convert_model(features) - + features = convert_model(features) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='analyze') @@ -173,6 +166,13 @@ def analyze(self, 'language': language, 'limit_text_characters': limit_text_characters } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v1/analyze' request = self.prepare_request(method='POST', @@ -188,7 +188,7 @@ def analyze(self, # Manage models ######################### - def list_models(self, **kwargs) -> 'DetailedResponse': + def list_models(self, **kwargs) -> DetailedResponse: """ List models. @@ -198,12 +198,10 @@ def list_models(self, **kwargs) -> 'DetailedResponse': :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ListModelsResults` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='list_models') @@ -211,6 +209,10 @@ def list_models(self, **kwargs) -> 'DetailedResponse': params = {'version': self.version} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/models' request = self.prepare_request(method='GET', url=url, @@ -220,7 +222,7 @@ def list_models(self, **kwargs) -> 'DetailedResponse': response = self.send(request) return response - def delete_model(self, model_id: str, **kwargs) -> 'DetailedResponse': + def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: """ Delete model. @@ -229,15 +231,12 @@ def delete_model(self, model_id: str, **kwargs) -> 'DetailedResponse': :param str model_id: Model ID of the model to delete. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object """ if model_id is None: raise ValueError('model_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='V1', operation_id='delete_model') @@ -245,7 +244,14 @@ def delete_model(self, model_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v1/models/{0}'.format(*self._encode_path_vars(model_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/models/{model_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -279,7 +285,7 @@ class AnalysisResults(): service assigned to the analyzed text. :attr EmotionResult emotion: (optional) The anger, disgust, fear, joy, or sadness conveyed by the content. - :attr AnalysisResultsMetadata metadata: (optional) Webpage metadata, such as the + :attr FeaturesResultsMetadata metadata: (optional) Webpage metadata, such as the author and the title of the page. :attr List[RelationsResult] relations: (optional) The relationships between entities in the content. @@ -301,7 +307,7 @@ def __init__(self, keywords: List['KeywordsResult'] = None, categories: List['CategoriesResult'] = None, emotion: 'EmotionResult' = None, - metadata: 'AnalysisResultsMetadata' = None, + metadata: 'FeaturesResultsMetadata' = None, relations: List['RelationsResult'] = None, semantic_roles: List['SemanticRolesResult'] = None, sentiment: 'SentimentResult' = None, @@ -324,7 +330,7 @@ def __init__(self, the service assigned to the analyzed text. :param EmotionResult emotion: (optional) The anger, disgust, fear, joy, or sadness conveyed by the content. - :param AnalysisResultsMetadata metadata: (optional) Webpage metadata, such + :param FeaturesResultsMetadata metadata: (optional) Webpage metadata, such as the author and the title of the page. :param List[RelationsResult] relations: (optional) The relationships between entities in the content. @@ -353,16 +359,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalysisResults': """Initialize a AnalysisResults object from a json dictionary.""" args = {} - valid_keys = [ - 'language', 'analyzed_text', 'retrieved_url', 'usage', 'concepts', - 'entities', 'keywords', 'categories', 'emotion', 'metadata', - 'relations', 'semantic_roles', 'sentiment', 'syntax' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AnalysisResults: ' - + ', '.join(bad_keys)) if 'language' in _dict: args['language'] = _dict.get('language') if 'analyzed_text' in _dict: @@ -370,43 +366,42 @@ def from_dict(cls, _dict: Dict) -> 'AnalysisResults': if 'retrieved_url' in _dict: args['retrieved_url'] = _dict.get('retrieved_url') if 'usage' in _dict: - args['usage'] = AnalysisResultsUsage._from_dict(_dict.get('usage')) + args['usage'] = AnalysisResultsUsage.from_dict(_dict.get('usage')) if 'concepts' in _dict: args['concepts'] = [ - ConceptsResult._from_dict(x) for x in (_dict.get('concepts')) + ConceptsResult.from_dict(x) for x in _dict.get('concepts') ] if 'entities' in _dict: args['entities'] = [ - EntitiesResult._from_dict(x) for x in (_dict.get('entities')) + EntitiesResult.from_dict(x) for x in _dict.get('entities') ] if 'keywords' in _dict: args['keywords'] = [ - KeywordsResult._from_dict(x) for x in (_dict.get('keywords')) + KeywordsResult.from_dict(x) for x in _dict.get('keywords') ] if 'categories' in _dict: args['categories'] = [ - CategoriesResult._from_dict(x) - for x in (_dict.get('categories')) + CategoriesResult.from_dict(x) for x in _dict.get('categories') ] if 'emotion' in _dict: - args['emotion'] = EmotionResult._from_dict(_dict.get('emotion')) + args['emotion'] = EmotionResult.from_dict(_dict.get('emotion')) if 'metadata' in _dict: - args['metadata'] = AnalysisResultsMetadata._from_dict( + args['metadata'] = FeaturesResultsMetadata.from_dict( _dict.get('metadata')) if 'relations' in _dict: args['relations'] = [ - RelationsResult._from_dict(x) for x in (_dict.get('relations')) + RelationsResult.from_dict(x) for x in _dict.get('relations') ] if 'semantic_roles' in _dict: args['semantic_roles'] = [ - SemanticRolesResult._from_dict(x) - for x in (_dict.get('semantic_roles')) + SemanticRolesResult.from_dict(x) + for x in _dict.get('semantic_roles') ] if 'sentiment' in _dict: - args['sentiment'] = SentimentResult._from_dict( + args['sentiment'] = SentimentResult.from_dict( _dict.get('sentiment')) if 'syntax' in _dict: - args['syntax'] = SyntaxResult._from_dict(_dict.get('syntax')) + args['syntax'] = SyntaxResult.from_dict(_dict.get('syntax')) return cls(**args) @classmethod @@ -424,29 +419,27 @@ def to_dict(self) -> Dict: if hasattr(self, 'retrieved_url') and self.retrieved_url is not None: _dict['retrieved_url'] = self.retrieved_url if hasattr(self, 'usage') and self.usage is not None: - _dict['usage'] = self.usage._to_dict() + _dict['usage'] = self.usage.to_dict() if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = [x._to_dict() for x in self.concepts] + _dict['concepts'] = [x.to_dict() for x in self.concepts] if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x._to_dict() for x in self.keywords] + _dict['keywords'] = [x.to_dict() for x in self.keywords] if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x._to_dict() for x in self.categories] + _dict['categories'] = [x.to_dict() for x in self.categories] if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion._to_dict() + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata._to_dict() + _dict['metadata'] = self.metadata.to_dict() if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = [x._to_dict() for x in self.relations] + _dict['relations'] = [x.to_dict() for x in self.relations] if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = [ - x._to_dict() for x in self.semantic_roles - ] + _dict['semantic_roles'] = [x.to_dict() for x in self.semantic_roles] if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment._to_dict() + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'syntax') and self.syntax is not None: - _dict['syntax'] = self.syntax._to_dict() + _dict['syntax'] = self.syntax.to_dict() return _dict def _to_dict(self): @@ -455,7 +448,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AnalysisResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AnalysisResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -468,105 +461,6 @@ def __ne__(self, other: 'AnalysisResults') -> bool: return not self == other -class AnalysisResultsMetadata(): - """ - Webpage metadata, such as the author and the title of the page. - - :attr List[Author] authors: (optional) The authors of the document. - :attr str publication_date: (optional) The publication date in the format ISO - 8601. - :attr str title: (optional) The title of the document. - :attr str image: (optional) URL of a prominent image on the webpage. - :attr List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. - """ - - def __init__(self, - *, - authors: List['Author'] = None, - publication_date: str = None, - title: str = None, - image: str = None, - feeds: List['Feed'] = None) -> None: - """ - Initialize a AnalysisResultsMetadata object. - - :param List[Author] authors: (optional) The authors of the document. - :param str publication_date: (optional) The publication date in the format - ISO 8601. - :param str title: (optional) The title of the document. - :param str image: (optional) URL of a prominent image on the webpage. - :param List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. - """ - self.authors = authors - self.publication_date = publication_date - self.title = title - self.image = image - self.feeds = feeds - - @classmethod - def from_dict(cls, _dict: Dict) -> 'AnalysisResultsMetadata': - """Initialize a AnalysisResultsMetadata object from a json dictionary.""" - args = {} - valid_keys = ['authors', 'publication_date', 'title', 'image', 'feeds'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AnalysisResultsMetadata: ' - + ', '.join(bad_keys)) - if 'authors' in _dict: - args['authors'] = [ - Author._from_dict(x) for x in (_dict.get('authors')) - ] - if 'publication_date' in _dict: - args['publication_date'] = _dict.get('publication_date') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'image' in _dict: - args['image'] = _dict.get('image') - if 'feeds' in _dict: - args['feeds'] = [Feed._from_dict(x) for x in (_dict.get('feeds'))] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a AnalysisResultsMetadata 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, 'authors') and self.authors is not None: - _dict['authors'] = [x._to_dict() for x in self.authors] - if hasattr(self, - 'publication_date') and self.publication_date is not None: - _dict['publication_date'] = self.publication_date - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'image') and self.image is not None: - _dict['image'] = self.image - if hasattr(self, 'feeds') and self.feeds is not None: - _dict['feeds'] = [x._to_dict() for x in self.feeds] - 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 AnalysisResultsMetadata object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other: 'AnalysisResultsMetadata') -> 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: 'AnalysisResultsMetadata') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class AnalysisResultsUsage(): """ API usage information for the request. @@ -597,12 +491,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalysisResultsUsage': """Initialize a AnalysisResultsUsage object from a json dictionary.""" args = {} - valid_keys = ['features', 'text_characters', 'text_units'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AnalysisResultsUsage: ' - + ', '.join(bad_keys)) if 'features' in _dict: args['features'] = _dict.get('features') if 'text_characters' in _dict: @@ -634,7 +522,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AnalysisResultsUsage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AnalysisResultsUsage') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -666,12 +554,6 @@ def __init__(self, *, name: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Author': """Initialize a Author object from a json dictionary.""" args = {} - valid_keys = ['name'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Author: ' + - ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') return cls(**args) @@ -694,7 +576,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Author object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Author') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -755,12 +637,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesOptions': """Initialize a CategoriesOptions object from a json dictionary.""" args = {} - valid_keys = ['explanation', 'limit', 'model'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CategoriesOptions: ' - + ', '.join(bad_keys)) if 'explanation' in _dict: args['explanation'] = _dict.get('explanation') if 'limit' in _dict: @@ -791,7 +667,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CategoriesOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CategoriesOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -825,12 +701,6 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'CategoriesRelevantText': """Initialize a CategoriesRelevantText object from a json dictionary.""" args = {} - valid_keys = ['text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CategoriesRelevantText: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -853,7 +723,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CategoriesRelevantText object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CategoriesRelevantText') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -904,18 +774,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesResult': """Initialize a CategoriesResult object from a json dictionary.""" args = {} - valid_keys = ['label', 'score', 'explanation'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CategoriesResult: ' - + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') if 'score' in _dict: args['score'] = _dict.get('score') if 'explanation' in _dict: - args['explanation'] = CategoriesResultExplanation._from_dict( + args['explanation'] = CategoriesResultExplanation.from_dict( _dict.get('explanation')) return cls(**args) @@ -932,7 +796,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'explanation') and self.explanation is not None: - _dict['explanation'] = self.explanation._to_dict() + _dict['explanation'] = self.explanation.to_dict() return _dict def _to_dict(self): @@ -941,7 +805,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CategoriesResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CategoriesResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -981,16 +845,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesResultExplanation': """Initialize a CategoriesResultExplanation object from a json dictionary.""" args = {} - valid_keys = ['relevant_text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CategoriesResultExplanation: ' - + ', '.join(bad_keys)) if 'relevant_text' in _dict: args['relevant_text'] = [ - CategoriesRelevantText._from_dict(x) - for x in (_dict.get('relevant_text')) + CategoriesRelevantText.from_dict(x) + for x in _dict.get('relevant_text') ] return cls(**args) @@ -1003,7 +861,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'relevant_text') and self.relevant_text is not None: - _dict['relevant_text'] = [x._to_dict() for x in self.relevant_text] + _dict['relevant_text'] = [x.to_dict() for x in self.relevant_text] return _dict def _to_dict(self): @@ -1012,7 +870,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CategoriesResultExplanation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CategoriesResultExplanation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1048,12 +906,6 @@ def __init__(self, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'ConceptsOptions': """Initialize a ConceptsOptions object from a json dictionary.""" args = {} - valid_keys = ['limit'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ConceptsOptions: ' - + ', '.join(bad_keys)) if 'limit' in _dict: args['limit'] = _dict.get('limit') return cls(**args) @@ -1076,7 +928,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ConceptsOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ConceptsOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1122,12 +974,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ConceptsResult': """Initialize a ConceptsResult object from a json dictionary.""" args = {} - valid_keys = ['text', 'relevance', 'dbpedia_resource'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ConceptsResult: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'relevance' in _dict: @@ -1159,7 +1005,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ConceptsResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ConceptsResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1191,12 +1037,6 @@ def __init__(self, *, deleted: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteModelResults': """Initialize a DeleteModelResults object from a json dictionary.""" args = {} - valid_keys = ['deleted'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DeleteModelResults: ' - + ', '.join(bad_keys)) if 'deleted' in _dict: args['deleted'] = _dict.get('deleted') return cls(**args) @@ -1219,7 +1059,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DeleteModelResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DeleteModelResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1263,12 +1103,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DisambiguationResult': """Initialize a DisambiguationResult object from a json dictionary.""" args = {} - valid_keys = ['name', 'dbpedia_resource', 'subtype'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DisambiguationResult: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') if 'dbpedia_resource' in _dict: @@ -1300,7 +1134,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DisambiguationResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DisambiguationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1334,14 +1168,8 @@ def __init__(self, *, emotion: 'EmotionScores' = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentEmotionResults': """Initialize a DocumentEmotionResults object from a json dictionary.""" args = {} - valid_keys = ['emotion'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentEmotionResults: ' - + ', '.join(bad_keys)) if 'emotion' in _dict: - args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) + args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) return cls(**args) @classmethod @@ -1353,7 +1181,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion._to_dict() + _dict['emotion'] = self.emotion.to_dict() return _dict def _to_dict(self): @@ -1362,7 +1190,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocumentEmotionResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocumentEmotionResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1401,12 +1229,6 @@ def __init__(self, *, label: str = None, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentSentimentResults': """Initialize a DocumentSentimentResults object from a json dictionary.""" args = {} - valid_keys = ['label', 'score'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentSentimentResults: ' - + ', '.join(bad_keys)) if 'label' in _dict: args['label'] = _dict.get('label') if 'score' in _dict: @@ -1433,7 +1255,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocumentSentimentResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocumentSentimentResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1479,12 +1301,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionOptions': """Initialize a EmotionOptions object from a json dictionary.""" args = {} - valid_keys = ['document', 'targets'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EmotionOptions: ' - + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: @@ -1511,7 +1327,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EmotionOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EmotionOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1555,19 +1371,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionResult': """Initialize a EmotionResult object from a json dictionary.""" args = {} - valid_keys = ['document', 'targets'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EmotionResult: ' - + ', '.join(bad_keys)) if 'document' in _dict: - args['document'] = DocumentEmotionResults._from_dict( + args['document'] = DocumentEmotionResults.from_dict( _dict.get('document')) if 'targets' in _dict: args['targets'] = [ - TargetedEmotionResults._from_dict(x) - for x in (_dict.get('targets')) + TargetedEmotionResults.from_dict(x) + for x in _dict.get('targets') ] return cls(**args) @@ -1580,9 +1390,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document._to_dict() + _dict['document'] = self.document.to_dict() if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = [x._to_dict() for x in self.targets] + _dict['targets'] = [x.to_dict() for x in self.targets] return _dict def _to_dict(self): @@ -1591,7 +1401,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EmotionResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EmotionResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1651,12 +1461,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionScores': """Initialize a EmotionScores object from a json dictionary.""" args = {} - valid_keys = ['anger', 'disgust', 'fear', 'joy', 'sadness'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EmotionScores: ' - + ', '.join(bad_keys)) if 'anger' in _dict: args['anger'] = _dict.get('anger') if 'disgust' in _dict: @@ -1695,7 +1499,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EmotionScores object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EmotionScores') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1760,12 +1564,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntitiesOptions': """Initialize a EntitiesOptions object from a json dictionary.""" args = {} - valid_keys = ['limit', 'mentions', 'model', 'sentiment', 'emotion'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EntitiesOptions: ' - + ', '.join(bad_keys)) if 'limit' in _dict: args['limit'] = _dict.get('limit') if 'mentions' in _dict: @@ -1804,7 +1602,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EntitiesOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EntitiesOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1887,15 +1685,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntitiesResult': """Initialize a EntitiesResult object from a json dictionary.""" args = {} - valid_keys = [ - 'type', 'text', 'relevance', 'confidence', 'mentions', 'count', - 'emotion', 'sentiment', 'disambiguation' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EntitiesResult: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'text' in _dict: @@ -1906,17 +1695,17 @@ def from_dict(cls, _dict: Dict) -> 'EntitiesResult': args['confidence'] = _dict.get('confidence') if 'mentions' in _dict: args['mentions'] = [ - EntityMention._from_dict(x) for x in (_dict.get('mentions')) + EntityMention.from_dict(x) for x in _dict.get('mentions') ] if 'count' in _dict: args['count'] = _dict.get('count') if 'emotion' in _dict: - args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) + args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) if 'sentiment' in _dict: - args['sentiment'] = FeatureSentimentResults._from_dict( + args['sentiment'] = FeatureSentimentResults.from_dict( _dict.get('sentiment')) if 'disambiguation' in _dict: - args['disambiguation'] = DisambiguationResult._from_dict( + args['disambiguation'] = DisambiguationResult.from_dict( _dict.get('disambiguation')) return cls(**args) @@ -1937,15 +1726,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = [x._to_dict() for x in self.mentions] + _dict['mentions'] = [x.to_dict() for x in self.mentions] if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion._to_dict() + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment._to_dict() + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'disambiguation') and self.disambiguation is not None: - _dict['disambiguation'] = self.disambiguation._to_dict() + _dict['disambiguation'] = self.disambiguation.to_dict() return _dict def _to_dict(self): @@ -1954,7 +1743,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EntitiesResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EntitiesResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2004,12 +1793,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} - valid_keys = ['text', 'location', 'confidence'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EntityMention: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: @@ -2040,7 +1823,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EntityMention object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EntityMention') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2074,12 +1857,6 @@ def __init__(self, *, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'FeatureSentimentResults': """Initialize a FeatureSentimentResults object from a json dictionary.""" args = {} - valid_keys = ['score'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class FeatureSentimentResults: ' - + ', '.join(bad_keys)) if 'score' in _dict: args['score'] = _dict.get('score') return cls(**args) @@ -2102,7 +1879,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this FeatureSentimentResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'FeatureSentimentResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2140,9 +1917,9 @@ class Features(): content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :attr MetadataOptions metadata: (optional) Returns information from the - document, including author name, title, RSS/ATOM feeds, prominent page image, - and publication date. Supports URL and HTML input types only. + :attr object metadata: (optional) Returns information from the document, + including author name, title, RSS/ATOM feeds, prominent page image, and + publication date. Supports URL and HTML input types only. :attr RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". For @@ -2174,7 +1951,7 @@ def __init__(self, emotion: 'EmotionOptions' = None, entities: 'EntitiesOptions' = None, keywords: 'KeywordsOptions' = None, - metadata: 'MetadataOptions' = None, + metadata: object = None, relations: 'RelationsOptions' = None, semantic_roles: 'SemanticRolesOptions' = None, sentiment: 'SentimentOptions' = None, @@ -2205,9 +1982,9 @@ def __init__(self, the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :param MetadataOptions metadata: (optional) Returns information from the - document, including author name, title, RSS/ATOM feeds, prominent page - image, and publication date. Supports URL and HTML input types only. + :param object metadata: (optional) Returns information from the document, + including author name, title, RSS/ATOM feeds, prominent page image, and + publication date. Supports URL and HTML input types only. :param RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert @@ -2247,39 +2024,30 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Features': """Initialize a Features object from a json dictionary.""" args = {} - valid_keys = [ - 'concepts', 'emotion', 'entities', 'keywords', 'metadata', - 'relations', 'semantic_roles', 'sentiment', 'categories', 'syntax' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Features: ' - + ', '.join(bad_keys)) if 'concepts' in _dict: - args['concepts'] = ConceptsOptions._from_dict(_dict.get('concepts')) + args['concepts'] = ConceptsOptions.from_dict(_dict.get('concepts')) if 'emotion' in _dict: - args['emotion'] = EmotionOptions._from_dict(_dict.get('emotion')) + args['emotion'] = EmotionOptions.from_dict(_dict.get('emotion')) if 'entities' in _dict: - args['entities'] = EntitiesOptions._from_dict(_dict.get('entities')) + args['entities'] = EntitiesOptions.from_dict(_dict.get('entities')) if 'keywords' in _dict: - args['keywords'] = KeywordsOptions._from_dict(_dict.get('keywords')) + args['keywords'] = KeywordsOptions.from_dict(_dict.get('keywords')) if 'metadata' in _dict: - args['metadata'] = MetadataOptions._from_dict(_dict.get('metadata')) + args['metadata'] = _dict.get('metadata') if 'relations' in _dict: - args['relations'] = RelationsOptions._from_dict( + args['relations'] = RelationsOptions.from_dict( _dict.get('relations')) if 'semantic_roles' in _dict: - args['semantic_roles'] = SemanticRolesOptions._from_dict( + args['semantic_roles'] = SemanticRolesOptions.from_dict( _dict.get('semantic_roles')) if 'sentiment' in _dict: - args['sentiment'] = SentimentOptions._from_dict( + args['sentiment'] = SentimentOptions.from_dict( _dict.get('sentiment')) if 'categories' in _dict: - args['categories'] = CategoriesOptions._from_dict( + args['categories'] = CategoriesOptions.from_dict( _dict.get('categories')) if 'syntax' in _dict: - args['syntax'] = SyntaxOptions._from_dict(_dict.get('syntax')) + args['syntax'] = SyntaxOptions.from_dict(_dict.get('syntax')) return cls(**args) @classmethod @@ -2291,25 +2059,25 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = self.concepts._to_dict() + _dict['concepts'] = self.concepts.to_dict() if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion._to_dict() + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = self.entities._to_dict() + _dict['entities'] = self.entities.to_dict() if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = self.keywords._to_dict() + _dict['keywords'] = self.keywords.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata._to_dict() + _dict['metadata'] = self.metadata if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = self.relations._to_dict() + _dict['relations'] = self.relations.to_dict() if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = self.semantic_roles._to_dict() + _dict['semantic_roles'] = self.semantic_roles.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment._to_dict() + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = self.categories._to_dict() + _dict['categories'] = self.categories.to_dict() if hasattr(self, 'syntax') and self.syntax is not None: - _dict['syntax'] = self.syntax._to_dict() + _dict['syntax'] = self.syntax.to_dict() return _dict def _to_dict(self): @@ -2318,7 +2086,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Features object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Features') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2331,6 +2099,99 @@ def __ne__(self, other: 'Features') -> bool: return not self == other +class FeaturesResultsMetadata(): + """ + Webpage metadata, such as the author and the title of the page. + + :attr List[Author] authors: (optional) The authors of the document. + :attr str publication_date: (optional) The publication date in the format ISO + 8601. + :attr str title: (optional) The title of the document. + :attr str image: (optional) URL of a prominent image on the webpage. + :attr List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. + """ + + def __init__(self, + *, + authors: List['Author'] = None, + publication_date: str = None, + title: str = None, + image: str = None, + feeds: List['Feed'] = None) -> None: + """ + Initialize a FeaturesResultsMetadata object. + + :param List[Author] authors: (optional) The authors of the document. + :param str publication_date: (optional) The publication date in the format + ISO 8601. + :param str title: (optional) The title of the document. + :param str image: (optional) URL of a prominent image on the webpage. + :param List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. + """ + self.authors = authors + self.publication_date = publication_date + self.title = title + self.image = image + self.feeds = feeds + + @classmethod + def from_dict(cls, _dict: Dict) -> 'FeaturesResultsMetadata': + """Initialize a FeaturesResultsMetadata object from a json dictionary.""" + args = {} + if 'authors' in _dict: + args['authors'] = [ + Author.from_dict(x) for x in _dict.get('authors') + ] + if 'publication_date' in _dict: + args['publication_date'] = _dict.get('publication_date') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'image' in _dict: + args['image'] = _dict.get('image') + if 'feeds' in _dict: + args['feeds'] = [Feed.from_dict(x) for x in _dict.get('feeds')] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a FeaturesResultsMetadata 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, 'authors') and self.authors is not None: + _dict['authors'] = [x.to_dict() for x in self.authors] + if hasattr(self, + 'publication_date') and self.publication_date is not None: + _dict['publication_date'] = self.publication_date + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'image') and self.image is not None: + _dict['image'] = self.image + if hasattr(self, 'feeds') and self.feeds is not None: + _dict['feeds'] = [x.to_dict() for x in self.feeds] + 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 FeaturesResultsMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'FeaturesResultsMetadata') -> 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: 'FeaturesResultsMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Feed(): """ RSS or ATOM feed found on the webpage. @@ -2350,12 +2211,6 @@ def __init__(self, *, link: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Feed': """Initialize a Feed object from a json dictionary.""" args = {} - valid_keys = ['link'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Feed: ' + - ', '.join(bad_keys)) if 'link' in _dict: args['link'] = _dict.get('link') return cls(**args) @@ -2378,7 +2233,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Feed object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Feed') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2426,12 +2281,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'KeywordsOptions': """Initialize a KeywordsOptions object from a json dictionary.""" args = {} - valid_keys = ['limit', 'sentiment', 'emotion'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class KeywordsOptions: ' - + ', '.join(bad_keys)) if 'limit' in _dict: args['limit'] = _dict.get('limit') if 'sentiment' in _dict: @@ -2462,7 +2311,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this KeywordsOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'KeywordsOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2520,12 +2369,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'KeywordsResult': """Initialize a KeywordsResult object from a json dictionary.""" args = {} - valid_keys = ['count', 'relevance', 'text', 'emotion', 'sentiment'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class KeywordsResult: ' - + ', '.join(bad_keys)) if 'count' in _dict: args['count'] = _dict.get('count') if 'relevance' in _dict: @@ -2533,9 +2376,9 @@ def from_dict(cls, _dict: Dict) -> 'KeywordsResult': if 'text' in _dict: args['text'] = _dict.get('text') if 'emotion' in _dict: - args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) + args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) if 'sentiment' in _dict: - args['sentiment'] = FeatureSentimentResults._from_dict( + args['sentiment'] = FeatureSentimentResults.from_dict( _dict.get('sentiment')) return cls(**args) @@ -2554,9 +2397,9 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion._to_dict() + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment._to_dict() + _dict['sentiment'] = self.sentiment.to_dict() return _dict def _to_dict(self): @@ -2565,7 +2408,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this KeywordsResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'KeywordsResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2597,16 +2440,8 @@ def __init__(self, *, models: List['Model'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListModelsResults': """Initialize a ListModelsResults object from a json dictionary.""" args = {} - valid_keys = ['models'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ListModelsResults: ' - + ', '.join(bad_keys)) if 'models' in _dict: - args['models'] = [ - Model._from_dict(x) for x in (_dict.get('models')) - ] + args['models'] = [Model.from_dict(x) for x in _dict.get('models')] return cls(**args) @classmethod @@ -2618,7 +2453,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x._to_dict() for x in self.models] + _dict['models'] = [x.to_dict() for x in self.models] return _dict def _to_dict(self): @@ -2627,7 +2462,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ListModelsResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ListModelsResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2640,54 +2475,6 @@ def __ne__(self, other: 'ListModelsResults') -> bool: return not self == other -class MetadataOptions(): - """ - Returns information from the document, including author name, title, RSS/ATOM feeds, - prominent page image, and publication date. Supports URL and HTML input types only. - - """ - - def __init__(self) -> None: - """ - Initialize a MetadataOptions object. - - """ - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetadataOptions': - """Initialize a MetadataOptions object from a json dictionary.""" - args = {} - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetadataOptions object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - 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 MetadataOptions object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other: 'MetadataOptions') -> 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: 'MetadataOptions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class Model(): """ Model. @@ -2753,15 +2540,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Model': """Initialize a Model object from a json dictionary.""" args = {} - valid_keys = [ - 'status', 'model_id', 'language', 'description', 'workspace_id', - 'model_version', 'version', 'version_description', 'created' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Model: ' + - ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') if 'model_id' in _dict: @@ -2818,7 +2596,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Model object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Model') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2830,16 +2608,16 @@ def __ne__(self, other: 'Model') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ When the status is `available`, the model is ready to use. """ - STARTING = "starting" - TRAINING = "training" - DEPLOYING = "deploying" - AVAILABLE = "available" - ERROR = "error" - DELETED = "deleted" + STARTING = 'starting' + TRAINING = 'training' + DEPLOYING = 'deploying' + AVAILABLE = 'available' + ERROR = 'error' + DELETED = 'deleted' class RelationArgument(): @@ -2874,15 +2652,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RelationArgument': """Initialize a RelationArgument object from a json dictionary.""" args = {} - valid_keys = ['entities', 'location', 'text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RelationArgument: ' - + ', '.join(bad_keys)) if 'entities' in _dict: args['entities'] = [ - RelationEntity._from_dict(x) for x in (_dict.get('entities')) + RelationEntity.from_dict(x) for x in _dict.get('entities') ] if 'location' in _dict: args['location'] = _dict.get('location') @@ -2899,7 +2671,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location if hasattr(self, 'text') and self.text is not None: @@ -2912,7 +2684,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RelationArgument object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RelationArgument') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2947,12 +2719,6 @@ def __init__(self, *, text: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RelationEntity': """Initialize a RelationEntity object from a json dictionary.""" args = {} - valid_keys = ['text', 'type'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RelationEntity: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'type' in _dict: @@ -2979,7 +2745,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RelationEntity object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RelationEntity') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3020,12 +2786,6 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RelationsOptions': """Initialize a RelationsOptions object from a json dictionary.""" args = {} - valid_keys = ['model'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RelationsOptions: ' - + ', '.join(bad_keys)) if 'model' in _dict: args['model'] = _dict.get('model') return cls(**args) @@ -3048,7 +2808,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RelationsOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RelationsOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3098,12 +2858,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RelationsResult': """Initialize a RelationsResult object from a json dictionary.""" args = {} - valid_keys = ['score', 'sentence', 'type', 'arguments'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RelationsResult: ' - + ', '.join(bad_keys)) if 'score' in _dict: args['score'] = _dict.get('score') if 'sentence' in _dict: @@ -3112,7 +2866,7 @@ def from_dict(cls, _dict: Dict) -> 'RelationsResult': args['type'] = _dict.get('type') if 'arguments' in _dict: args['arguments'] = [ - RelationArgument._from_dict(x) for x in (_dict.get('arguments')) + RelationArgument.from_dict(x) for x in _dict.get('arguments') ] return cls(**args) @@ -3131,7 +2885,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'arguments') and self.arguments is not None: - _dict['arguments'] = [x._to_dict() for x in self.arguments] + _dict['arguments'] = [x.to_dict() for x in self.arguments] return _dict def _to_dict(self): @@ -3140,7 +2894,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RelationsResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RelationsResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3175,12 +2929,6 @@ def __init__(self, *, type: str = None, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesEntity': """Initialize a SemanticRolesEntity object from a json dictionary.""" args = {} - valid_keys = ['type', 'text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SemanticRolesEntity: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'text' in _dict: @@ -3207,7 +2955,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SemanticRolesEntity object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SemanticRolesEntity') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3239,12 +2987,6 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesKeyword': """Initialize a SemanticRolesKeyword object from a json dictionary.""" args = {} - valid_keys = ['text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SemanticRolesKeyword: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -3267,7 +3009,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SemanticRolesKeyword object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SemanticRolesKeyword') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3315,12 +3057,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesOptions': """Initialize a SemanticRolesOptions object from a json dictionary.""" args = {} - valid_keys = ['limit', 'keywords', 'entities'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SemanticRolesOptions: ' - + ', '.join(bad_keys)) if 'limit' in _dict: args['limit'] = _dict.get('limit') if 'keywords' in _dict: @@ -3351,7 +3087,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SemanticRolesOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SemanticRolesOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3405,22 +3141,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResult': """Initialize a SemanticRolesResult object from a json dictionary.""" args = {} - valid_keys = ['sentence', 'subject', 'action', 'object'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SemanticRolesResult: ' - + ', '.join(bad_keys)) if 'sentence' in _dict: args['sentence'] = _dict.get('sentence') if 'subject' in _dict: - args['subject'] = SemanticRolesResultSubject._from_dict( + args['subject'] = SemanticRolesResultSubject.from_dict( _dict.get('subject')) if 'action' in _dict: - args['action'] = SemanticRolesResultAction._from_dict( + args['action'] = SemanticRolesResultAction.from_dict( _dict.get('action')) if 'object' in _dict: - args['object'] = SemanticRolesResultObject._from_dict( + args['object'] = SemanticRolesResultObject.from_dict( _dict.get('object')) return cls(**args) @@ -3435,11 +3165,11 @@ def to_dict(self) -> Dict: if hasattr(self, 'sentence') and self.sentence is not None: _dict['sentence'] = self.sentence if hasattr(self, 'subject') and self.subject is not None: - _dict['subject'] = self.subject._to_dict() + _dict['subject'] = self.subject.to_dict() if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action._to_dict() + _dict['action'] = self.action.to_dict() if hasattr(self, 'object') and self.object is not None: - _dict['object'] = self.object._to_dict() + _dict['object'] = self.object.to_dict() return _dict def _to_dict(self): @@ -3448,7 +3178,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SemanticRolesResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SemanticRolesResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3490,18 +3220,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultAction': """Initialize a SemanticRolesResultAction object from a json dictionary.""" args = {} - valid_keys = ['text', 'normalized', 'verb'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SemanticRolesResultAction: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'normalized' in _dict: args['normalized'] = _dict.get('normalized') if 'verb' in _dict: - args['verb'] = SemanticRolesVerb._from_dict(_dict.get('verb')) + args['verb'] = SemanticRolesVerb.from_dict(_dict.get('verb')) return cls(**args) @classmethod @@ -3517,7 +3241,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'normalized') and self.normalized is not None: _dict['normalized'] = self.normalized if hasattr(self, 'verb') and self.verb is not None: - _dict['verb'] = self.verb._to_dict() + _dict['verb'] = self.verb.to_dict() return _dict def _to_dict(self): @@ -3526,7 +3250,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SemanticRolesResultAction object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SemanticRolesResultAction') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3566,18 +3290,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultObject': """Initialize a SemanticRolesResultObject object from a json dictionary.""" args = {} - valid_keys = ['text', 'keywords'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SemanticRolesResultObject: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'keywords' in _dict: args['keywords'] = [ - SemanticRolesKeyword._from_dict(x) - for x in (_dict.get('keywords')) + SemanticRolesKeyword.from_dict(x) for x in _dict.get('keywords') ] return cls(**args) @@ -3592,7 +3309,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x._to_dict() for x in self.keywords] + _dict['keywords'] = [x.to_dict() for x in self.keywords] return _dict def _to_dict(self): @@ -3601,7 +3318,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SemanticRolesResultObject object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SemanticRolesResultObject') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3647,23 +3364,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultSubject': """Initialize a SemanticRolesResultSubject object from a json dictionary.""" args = {} - valid_keys = ['text', 'entities', 'keywords'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SemanticRolesResultSubject: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'entities' in _dict: args['entities'] = [ - SemanticRolesEntity._from_dict(x) - for x in (_dict.get('entities')) + SemanticRolesEntity.from_dict(x) for x in _dict.get('entities') ] if 'keywords' in _dict: args['keywords'] = [ - SemanticRolesKeyword._from_dict(x) - for x in (_dict.get('keywords')) + SemanticRolesKeyword.from_dict(x) for x in _dict.get('keywords') ] return cls(**args) @@ -3678,9 +3387,9 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x._to_dict() for x in self.entities] + _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x._to_dict() for x in self.keywords] + _dict['keywords'] = [x.to_dict() for x in self.keywords] return _dict def _to_dict(self): @@ -3689,7 +3398,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SemanticRolesResultSubject object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SemanticRolesResultSubject') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3724,12 +3433,6 @@ def __init__(self, *, text: str = None, tense: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesVerb': """Initialize a SemanticRolesVerb object from a json dictionary.""" args = {} - valid_keys = ['text', 'tense'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SemanticRolesVerb: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'tense' in _dict: @@ -3756,7 +3459,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SemanticRolesVerb object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SemanticRolesVerb') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3793,12 +3496,6 @@ def __init__(self, *, text: str = None, location: List[int] = None) -> None: def from_dict(cls, _dict: Dict) -> 'SentenceResult': """Initialize a SentenceResult object from a json dictionary.""" args = {} - valid_keys = ['text', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SentenceResult: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: @@ -3825,7 +3522,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SentenceResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SentenceResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3871,12 +3568,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SentimentOptions': """Initialize a SentimentOptions object from a json dictionary.""" args = {} - valid_keys = ['document', 'targets'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SentimentOptions: ' - + ', '.join(bad_keys)) if 'document' in _dict: args['document'] = _dict.get('document') if 'targets' in _dict: @@ -3903,7 +3594,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SentimentOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SentimentOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3945,19 +3636,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SentimentResult': """Initialize a SentimentResult object from a json dictionary.""" args = {} - valid_keys = ['document', 'targets'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SentimentResult: ' - + ', '.join(bad_keys)) if 'document' in _dict: - args['document'] = DocumentSentimentResults._from_dict( + args['document'] = DocumentSentimentResults.from_dict( _dict.get('document')) if 'targets' in _dict: args['targets'] = [ - TargetedSentimentResults._from_dict(x) - for x in (_dict.get('targets')) + TargetedSentimentResults.from_dict(x) + for x in _dict.get('targets') ] return cls(**args) @@ -3970,9 +3655,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document._to_dict() + _dict['document'] = self.document.to_dict() if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = [x._to_dict() for x in self.targets] + _dict['targets'] = [x.to_dict() for x in self.targets] return _dict def _to_dict(self): @@ -3981,7 +3666,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SentimentResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SentimentResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4021,14 +3706,8 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxOptions': """Initialize a SyntaxOptions object from a json dictionary.""" args = {} - valid_keys = ['tokens', 'sentences'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SyntaxOptions: ' - + ', '.join(bad_keys)) if 'tokens' in _dict: - args['tokens'] = SyntaxOptionsTokens._from_dict(_dict.get('tokens')) + args['tokens'] = SyntaxOptionsTokens.from_dict(_dict.get('tokens')) if 'sentences' in _dict: args['sentences'] = _dict.get('sentences') return cls(**args) @@ -4042,7 +3721,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tokens') and self.tokens is not None: - _dict['tokens'] = self.tokens._to_dict() + _dict['tokens'] = self.tokens.to_dict() if hasattr(self, 'sentences') and self.sentences is not None: _dict['sentences'] = self.sentences return _dict @@ -4053,7 +3732,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SyntaxOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SyntaxOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4095,12 +3774,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxOptionsTokens': """Initialize a SyntaxOptionsTokens object from a json dictionary.""" args = {} - valid_keys = ['lemma', 'part_of_speech'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SyntaxOptionsTokens: ' - + ', '.join(bad_keys)) if 'lemma' in _dict: args['lemma'] = _dict.get('lemma') if 'part_of_speech' in _dict: @@ -4127,7 +3800,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SyntaxOptionsTokens object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SyntaxOptionsTokens') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4165,19 +3838,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxResult': """Initialize a SyntaxResult object from a json dictionary.""" args = {} - valid_keys = ['tokens', 'sentences'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SyntaxResult: ' - + ', '.join(bad_keys)) if 'tokens' in _dict: args['tokens'] = [ - TokenResult._from_dict(x) for x in (_dict.get('tokens')) + TokenResult.from_dict(x) for x in _dict.get('tokens') ] if 'sentences' in _dict: args['sentences'] = [ - SentenceResult._from_dict(x) for x in (_dict.get('sentences')) + SentenceResult.from_dict(x) for x in _dict.get('sentences') ] return cls(**args) @@ -4190,9 +3857,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tokens') and self.tokens is not None: - _dict['tokens'] = [x._to_dict() for x in self.tokens] + _dict['tokens'] = [x.to_dict() for x in self.tokens] if hasattr(self, 'sentences') and self.sentences is not None: - _dict['sentences'] = [x._to_dict() for x in self.sentences] + _dict['sentences'] = [x.to_dict() for x in self.sentences] return _dict def _to_dict(self): @@ -4201,7 +3868,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SyntaxResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SyntaxResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4240,16 +3907,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TargetedEmotionResults': """Initialize a TargetedEmotionResults object from a json dictionary.""" args = {} - valid_keys = ['text', 'emotion'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TargetedEmotionResults: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'emotion' in _dict: - args['emotion'] = EmotionScores._from_dict(_dict.get('emotion')) + args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) return cls(**args) @classmethod @@ -4263,7 +3924,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion._to_dict() + _dict['emotion'] = self.emotion.to_dict() return _dict def _to_dict(self): @@ -4272,7 +3933,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TargetedEmotionResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TargetedEmotionResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4309,12 +3970,6 @@ def __init__(self, *, text: str = None, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'TargetedSentimentResults': """Initialize a TargetedSentimentResults object from a json dictionary.""" args = {} - valid_keys = ['text', 'score'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TargetedSentimentResults: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'score' in _dict: @@ -4341,7 +3996,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TargetedSentimentResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TargetedSentimentResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4395,12 +4050,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TokenResult': """Initialize a TokenResult object from a json dictionary.""" args = {} - valid_keys = ['text', 'part_of_speech', 'location', 'lemma'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TokenResult: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'part_of_speech' in _dict: @@ -4435,7 +4084,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TokenResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TokenResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4447,25 +4096,25 @@ def __ne__(self, other: 'TokenResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class PartOfSpeechEnum(Enum): + class PartOfSpeechEnum(str, Enum): """ The part of speech of the token. For more information about the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). """ - ADJ = "ADJ" - ADP = "ADP" - ADV = "ADV" - AUX = "AUX" - CCONJ = "CCONJ" - DET = "DET" - INTJ = "INTJ" - NOUN = "NOUN" - NUM = "NUM" - PART = "PART" - PRON = "PRON" - PROPN = "PROPN" - PUNCT = "PUNCT" - SCONJ = "SCONJ" - SYM = "SYM" - VERB = "VERB" - X = "X" + ADJ = 'ADJ' + ADP = 'ADP' + ADV = 'ADV' + AUX = 'AUX' + CCONJ = 'CCONJ' + DET = 'DET' + INTJ = 'INTJ' + NOUN = 'NOUN' + NUM = 'NUM' + PART = 'PART' + PRON = 'PRON' + PROPN = 'PROPN' + PUNCT = 'PUNCT' + SCONJ = 'SCONJ' + SYM = 'SYM' + VERB = 'VERB' + X = 'X' diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 50188ae01..01481f7cf 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ IBM® will begin sunsetting IBM Watson™ Personality Insights on 1 December 2020. For a period of one year from this date, you will still be able to use Watson Personality @@ -43,15 +45,16 @@ or retain data from requests and responses. """ +from enum import Enum +from typing import Dict, List, TextIO, Union import json + +from ibm_cloud_sdk_core import BaseService, DetailedResponse from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers -from enum import Enum -from ibm_cloud_sdk_core import BaseService -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 +from ibm_cloud_sdk_core.utils import convert_model + +from .common import get_sdk_headers ############################################################################## # Service @@ -73,27 +76,21 @@ def __init__( """ Construct a new client for the Personality Insights service. - :param str version: The API version date to use with the service, in - "YYYY-MM-DD" format. Whenever the API is changed in a backwards - incompatible way, a new minor version of the API is released. - The service uses the API version for the date you specify, or - the most recent version before that date. Note that you should - not programmatically specify the current date at runtime, in - case the API has been updated since your application's release. - Instead, specify a version date that is compatible with your - application, and don't change it until your application is - ready for a later version. + :param str version: Release date of the version of the API you want to use. + Specify dates in YYYY-MM-DD format. The current version is `2017-10-13`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + if version is None: + raise ValueError('version must be provided') + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.version = version self.configure_service(service_name) @@ -102,7 +99,7 @@ def __init__( ######################### def profile(self, - content: object, + content: Union['Content', str, TextIO], accept: str, *, content_type: str = None, @@ -111,7 +108,7 @@ def profile(self, raw_scores: bool = None, csv_headers: bool = None, consumption_preferences: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get profile. @@ -186,7 +183,7 @@ def profile(self, consumption preferences are returned. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Profile` object """ if content is None: @@ -194,16 +191,14 @@ def profile(self, if accept is None: raise ValueError('accept must be provided') if isinstance(content, Content): - content = self._convert_model(content) - + content = convert_model(content) + content_type = content_type or 'application/json' headers = { 'Accept': accept, 'Content-Type': content_type, 'Content-Language': content_language, 'Accept-Language': accept_language } - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='profile') @@ -216,11 +211,16 @@ def profile(self, 'consumption_preferences': consumption_preferences } - if content_type == 'application/json' and isinstance(content, dict): + if isinstance(content, dict): data = json.dumps(content) + if content_type is None: + headers['Content-Type'] = 'application/json' else: data = content + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + url = '/v3/profile' request = self.prepare_request(method='POST', url=url, @@ -232,9 +232,12 @@ def profile(self, return response -class ProfileEnums(object): +class ProfileEnums: + """ + Enums for profile parameters. + """ - class Accept(Enum): + class Accept(str, Enum): """ The type of the response. For more information, see **Accept types** in the method description. @@ -242,7 +245,7 @@ class Accept(Enum): APPLICATION_JSON = 'application/json' TEXT_CSV = 'text/csv' - class ContentType(Enum): + class ContentType(str, Enum): """ The type of the input. For more information, see **Content types** in the method description. @@ -251,7 +254,7 @@ class ContentType(Enum): TEXT_HTML = 'text/html' TEXT_PLAIN = 'text/plain' - class ContentLanguage(Enum): + class ContentLanguage(str, Enum): """ The language of the input text for the request: Arabic, English, Japanese, Korean, or Spanish. Regional variants are treated as their parent language; for example, @@ -271,7 +274,7 @@ class ContentLanguage(Enum): JA = 'ja' KO = 'ko' - class AcceptLanguage(Enum): + class AcceptLanguage(str, Enum): """ The desired language of the response. For two-character arguments, regional variants are treated as their parent language; for example, `en-US` is interpreted @@ -334,12 +337,6 @@ def __init__(self, trait_id: str, name: str, category: str, def from_dict(cls, _dict: Dict) -> 'Behavior': """Initialize a Behavior object from a json dictionary.""" args = {} - valid_keys = ['trait_id', 'name', 'category', 'percentage'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Behavior: ' - + ', '.join(bad_keys)) if 'trait_id' in _dict: args['trait_id'] = _dict.get('trait_id') else: @@ -386,7 +383,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Behavior object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Behavior') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -442,12 +439,6 @@ def __init__(self, consumption_preference_id: str, name: str, def from_dict(cls, _dict: Dict) -> 'ConsumptionPreferences': """Initialize a ConsumptionPreferences object from a json dictionary.""" args = {} - valid_keys = ['consumption_preference_id', 'name', 'score'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ConsumptionPreferences: ' - + ', '.join(bad_keys)) if 'consumption_preference_id' in _dict: args['consumption_preference_id'] = _dict.get( 'consumption_preference_id') @@ -492,7 +483,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ConsumptionPreferences object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ConsumptionPreferences') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -540,15 +531,6 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'ConsumptionPreferencesCategory': """Initialize a ConsumptionPreferencesCategory object from a json dictionary.""" args = {} - valid_keys = [ - 'consumption_preference_category_id', 'name', - 'consumption_preferences' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ConsumptionPreferencesCategory: ' - + ', '.join(bad_keys)) if 'consumption_preference_category_id' in _dict: args['consumption_preference_category_id'] = _dict.get( 'consumption_preference_category_id') @@ -564,8 +546,8 @@ def from_dict(cls, _dict: Dict) -> 'ConsumptionPreferencesCategory': ) if 'consumption_preferences' in _dict: args['consumption_preferences'] = [ - ConsumptionPreferences._from_dict(x) - for x in (_dict.get('consumption_preferences')) + ConsumptionPreferences.from_dict(x) + for x in _dict.get('consumption_preferences') ] else: raise ValueError( @@ -590,7 +572,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'consumption_preferences' ) and self.consumption_preferences is not None: _dict['consumption_preferences'] = [ - x._to_dict() for x in self.consumption_preferences + x.to_dict() for x in self.consumption_preferences ] return _dict @@ -600,7 +582,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ConsumptionPreferencesCategory object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ConsumptionPreferencesCategory') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -634,15 +616,9 @@ def __init__(self, content_items: List['ContentItem']) -> None: def from_dict(cls, _dict: Dict) -> 'Content': """Initialize a Content object from a json dictionary.""" args = {} - valid_keys = ['content_items', 'contentItems'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Content: ' + - ', '.join(bad_keys)) if 'contentItems' in _dict: args['content_items'] = [ - ContentItem._from_dict(x) for x in (_dict.get('contentItems')) + ContentItem.from_dict(x) for x in _dict.get('contentItems') ] else: raise ValueError( @@ -659,7 +635,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'content_items') and self.content_items is not None: - _dict['contentItems'] = [x._to_dict() for x in self.content_items] + _dict['contentItems'] = [x.to_dict() for x in self.content_items] return _dict def _to_dict(self): @@ -668,7 +644,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Content object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Content') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -776,15 +752,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ContentItem': """Initialize a ContentItem object from a json dictionary.""" args = {} - valid_keys = [ - 'content', 'id', 'created', 'updated', 'contenttype', 'language', - 'parentid', 'reply', 'forward' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ContentItem: ' - + ', '.join(bad_keys)) if 'content' in _dict: args['content'] = _dict.get('content') else: @@ -842,7 +809,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ContentItem object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ContentItem') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -854,15 +821,15 @@ def __ne__(self, other: 'ContentItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ContenttypeEnum(Enum): + class ContenttypeEnum(str, Enum): """ The MIME type of the content. The default is plain text. The tags are stripped from HTML content before it is analyzed; plain text is processed as submitted. """ - TEXT_PLAIN = "text/plain" - TEXT_HTML = "text/html" + TEXT_PLAIN = 'text/plain' + TEXT_HTML = 'text/html' - class LanguageEnum(Enum): + class LanguageEnum(str, Enum): """ The language identifier (two-letter ISO 639-1 identifier) for the language of the content item. The default is `en` (English). Regional variants are treated as @@ -874,11 +841,11 @@ class LanguageEnum(Enum): different language are ignored. You can specify any combination of languages for the input and response content. """ - AR = "ar" - EN = "en" - ES = "es" - JA = "ja" - KO = "ko" + AR = 'ar' + EN = 'en' + ES = 'es' + JA = 'ja' + KO = 'ko' class Profile(): @@ -911,9 +878,6 @@ class Profile(): :attr List[Warning] warnings: An array of warning messages that are associated with the input text for the request. The array is empty if the input generated no warnings. - Deprecated On 1 December 2021, Personality Insights will no longer be available. - Consider migrating to Watson Natural Language Understanding. - For more information, see [Personality Insights Deprecation](https://github.com/watson-developer-cloud/ruby-sdk/tree/master#personality-insights-deprecation). """ def __init__( @@ -961,7 +925,6 @@ def __init__( array provides information inferred from the input text for the individual preferences of that category. """ - print('warning: On 1 December 2021, Personality Insights will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#personality-insights-deprecation.') self.processed_language = processed_language self.word_count = word_count self.word_count_message = word_count_message @@ -976,16 +939,6 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'Profile': """Initialize a Profile object from a json dictionary.""" args = {} - valid_keys = [ - 'processed_language', 'word_count', 'word_count_message', - 'personality', 'needs', 'values', 'behavior', - 'consumption_preferences', 'warnings' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Profile: ' + - ', '.join(bad_keys)) if 'processed_language' in _dict: args['processed_language'] = _dict.get('processed_language') else: @@ -1001,35 +954,33 @@ def from_dict(cls, _dict: Dict) -> 'Profile': args['word_count_message'] = _dict.get('word_count_message') if 'personality' in _dict: args['personality'] = [ - Trait._from_dict(x) for x in (_dict.get('personality')) + Trait.from_dict(x) for x in _dict.get('personality') ] else: raise ValueError( 'Required property \'personality\' not present in Profile JSON') if 'needs' in _dict: - args['needs'] = [Trait._from_dict(x) for x in (_dict.get('needs'))] + args['needs'] = [Trait.from_dict(x) for x in _dict.get('needs')] else: raise ValueError( 'Required property \'needs\' not present in Profile JSON') if 'values' in _dict: - args['values'] = [ - Trait._from_dict(x) for x in (_dict.get('values')) - ] + args['values'] = [Trait.from_dict(x) for x in _dict.get('values')] else: raise ValueError( 'Required property \'values\' not present in Profile JSON') if 'behavior' in _dict: args['behavior'] = [ - Behavior._from_dict(x) for x in (_dict.get('behavior')) + Behavior.from_dict(x) for x in _dict.get('behavior') ] if 'consumption_preferences' in _dict: args['consumption_preferences'] = [ - ConsumptionPreferencesCategory._from_dict(x) - for x in (_dict.get('consumption_preferences')) + ConsumptionPreferencesCategory.from_dict(x) + for x in _dict.get('consumption_preferences') ] if 'warnings' in _dict: args['warnings'] = [ - Warning._from_dict(x) for x in (_dict.get('warnings')) + Warning.from_dict(x) for x in _dict.get('warnings') ] else: raise ValueError( @@ -1055,20 +1006,20 @@ def to_dict(self) -> Dict: 'word_count_message') and self.word_count_message is not None: _dict['word_count_message'] = self.word_count_message if hasattr(self, 'personality') and self.personality is not None: - _dict['personality'] = [x._to_dict() for x in self.personality] + _dict['personality'] = [x.to_dict() for x in self.personality] if hasattr(self, 'needs') and self.needs is not None: - _dict['needs'] = [x._to_dict() for x in self.needs] + _dict['needs'] = [x.to_dict() for x in self.needs] if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x._to_dict() for x in self.values] + _dict['values'] = [x.to_dict() for x in self.values] if hasattr(self, 'behavior') and self.behavior is not None: - _dict['behavior'] = [x._to_dict() for x in self.behavior] + _dict['behavior'] = [x.to_dict() for x in self.behavior] if hasattr(self, 'consumption_preferences' ) and self.consumption_preferences is not None: _dict['consumption_preferences'] = [ - x._to_dict() for x in self.consumption_preferences + x.to_dict() for x in self.consumption_preferences ] if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x._to_dict() for x in self.warnings] + _dict['warnings'] = [x.to_dict() for x in self.warnings] return _dict def _to_dict(self): @@ -1077,7 +1028,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Profile object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Profile') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1089,15 +1040,15 @@ def __ne__(self, other: 'Profile') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ProcessedLanguageEnum(Enum): + class ProcessedLanguageEnum(str, Enum): """ The language model that was used to process the input. """ - AR = "ar" - EN = "en" - ES = "es" - JA = "ja" - KO = "ko" + AR = 'ar' + EN = 'en' + ES = 'es' + JA = 'ja' + KO = 'ko' class Trait(): @@ -1197,15 +1148,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Trait': """Initialize a Trait object from a json dictionary.""" args = {} - valid_keys = [ - 'trait_id', 'name', 'category', 'percentile', 'raw_score', - 'significant', 'children' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Trait: ' + - ', '.join(bad_keys)) if 'trait_id' in _dict: args['trait_id'] = _dict.get('trait_id') else: @@ -1232,7 +1174,7 @@ def from_dict(cls, _dict: Dict) -> 'Trait': args['significant'] = _dict.get('significant') if 'children' in _dict: args['children'] = [ - Trait._from_dict(x) for x in (_dict.get('children')) + Trait.from_dict(x) for x in _dict.get('children') ] return cls(**args) @@ -1257,7 +1199,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'significant') and self.significant is not None: _dict['significant'] = self.significant if hasattr(self, 'children') and self.children is not None: - _dict['children'] = [x._to_dict() for x in self.children] + _dict['children'] = [x.to_dict() for x in self.children] return _dict def _to_dict(self): @@ -1266,7 +1208,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Trait object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Trait') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1278,14 +1220,14 @@ def __ne__(self, other: 'Trait') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class CategoryEnum(Enum): + class CategoryEnum(str, Enum): """ The category of the characteristic: `personality` for Big Five personality characteristics, `needs` for Needs, and `values` for Values. """ - PERSONALITY = "personality" - NEEDS = "needs" - VALUES = "values" + PERSONALITY = 'personality' + NEEDS = 'needs' + VALUES = 'values' class Warning(): @@ -1338,12 +1280,6 @@ def __init__(self, warning_id: str, message: str) -> None: def from_dict(cls, _dict: Dict) -> 'Warning': """Initialize a Warning object from a json dictionary.""" args = {} - valid_keys = ['warning_id', 'message'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Warning: ' + - ', '.join(bad_keys)) if 'warning_id' in _dict: args['warning_id'] = _dict.get('warning_id') else: @@ -1376,7 +1312,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Warning object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Warning') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1388,11 +1324,11 @@ def __ne__(self, other: 'Warning') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class WarningIdEnum(Enum): + class WarningIdEnum(str, Enum): """ The identifier of the warning message. """ - WORD_COUNT_MESSAGE = "WORD_COUNT_MESSAGE" - JSON_AS_TEXT = "JSON_AS_TEXT" - CONTENT_TRUNCATED = "CONTENT_TRUNCATED" - PARTIAL_TEXT_USED = "PARTIAL_TEXT_USED" + WORD_COUNT_MESSAGE = 'WORD_COUNT_MESSAGE' + JSON_AS_TEXT = 'JSON_AS_TEXT' + CONTENT_TRUNCATED = 'CONTENT_TRUNCATED' + PARTIAL_TEXT_USED = 'PARTIAL_TEXT_USED' diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 39da8b2d6..97716c530 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's speech-recognition capabilities to produce transcripts of spoken audio. The service can @@ -34,16 +36,16 @@ functionality for all language models that support language model customization. """ +from enum import Enum +from typing import BinaryIO, Dict, List, TextIO, Union import json + +from ibm_cloud_sdk_core import BaseService, DetailedResponse from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers -from enum import Enum -from ibm_cloud_sdk_core import BaseService -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 +from ibm_cloud_sdk_core.utils import convert_list, convert_model + +from .common import get_sdk_headers ############################################################################## # Service @@ -72,15 +74,14 @@ def __init__( authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.configure_service(service_name) ######################### # Models ######################### - def list_models(self, **kwargs) -> 'DetailedResponse': + def list_models(self, **kwargs) -> DetailedResponse: """ List models. @@ -93,24 +94,26 @@ def list_models(self, **kwargs) -> 'DetailedResponse': :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `SpeechModels` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='list_models') headers.update(sdk_headers) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/models' request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response - def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': + def get_model(self, model_id: str, **kwargs) -> DetailedResponse: """ Get a model. @@ -124,21 +127,25 @@ def get_model(self, model_id: str, **kwargs) -> 'DetailedResponse': from the output of the **Get a model** method. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `SpeechModel` object """ if model_id is None: raise ValueError('model_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='V1', operation_id='get_model') headers.update(sdk_headers) - url = '/v1/models/{0}'.format(*self._encode_path_vars(model_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/models/{model_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) @@ -175,7 +182,7 @@ def recognize(self, split_transcript_at_phrase_end: bool = None, speech_detector_sensitivity: float = None, background_audio_suppression: float = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Recognize audio. @@ -446,15 +453,12 @@ def recognize(self, Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `SpeechRecognitionResults` object """ if audio is None: raise ValueError('audio must be provided') - headers = {'Content-Type': content_type} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='recognize') @@ -467,7 +471,7 @@ def recognize(self, 'base_model_version': base_model_version, 'customization_weight': customization_weight, 'inactivity_timeout': inactivity_timeout, - 'keywords': self._convert_list(keywords), + 'keywords': convert_list(keywords), 'keywords_threshold': keywords_threshold, 'max_alternatives': max_alternatives, 'word_alternatives_threshold': word_alternatives_threshold, @@ -488,6 +492,10 @@ def recognize(self, data = audio + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/recognize' request = self.prepare_request(method='POST', url=url, @@ -506,7 +514,7 @@ def register_callback(self, callback_url: str, *, user_secret: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Register a callback. @@ -553,15 +561,12 @@ def register_callback(self, the parameter, the service does not send the header. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `RegisterStatus` object """ if callback_url is None: raise ValueError('callback_url 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='V1', operation_id='register_callback') @@ -569,6 +574,10 @@ def register_callback(self, params = {'callback_url': callback_url, 'user_secret': user_secret} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/register_callback' request = self.prepare_request(method='POST', url=url, @@ -579,7 +588,7 @@ def register_callback(self, return response def unregister_callback(self, callback_url: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Unregister a callback. @@ -597,10 +606,7 @@ def unregister_callback(self, callback_url: str, if callback_url is None: raise ValueError('callback_url 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='V1', operation_id='unregister_callback') @@ -608,6 +614,9 @@ def unregister_callback(self, callback_url: str, params = {'callback_url': callback_url} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + url = '/v1/unregister_callback' request = self.prepare_request(method='POST', url=url, @@ -650,7 +659,7 @@ def create_job(self, split_transcript_at_phrase_end: bool = None, speech_detector_sensitivity: float = None, background_audio_suppression: float = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create a job. @@ -992,15 +1001,12 @@ def create_job(self, Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `RecognitionJob` object """ if audio is None: raise ValueError('audio must be provided') - headers = {'Content-Type': content_type} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_job') @@ -1017,7 +1023,7 @@ def create_job(self, 'base_model_version': base_model_version, 'customization_weight': customization_weight, 'inactivity_timeout': inactivity_timeout, - 'keywords': self._convert_list(keywords), + 'keywords': convert_list(keywords), 'keywords_threshold': keywords_threshold, 'max_alternatives': max_alternatives, 'word_alternatives_threshold': word_alternatives_threshold, @@ -1040,6 +1046,10 @@ def create_job(self, data = audio + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/recognitions' request = self.prepare_request(method='POST', url=url, @@ -1050,7 +1060,7 @@ def create_job(self, response = self.send(request) return response - def check_jobs(self, **kwargs) -> 'DetailedResponse': + def check_jobs(self, **kwargs) -> DetailedResponse: """ Check jobs. @@ -1067,24 +1077,26 @@ def check_jobs(self, **kwargs) -> 'DetailedResponse': :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `RecognitionJobs` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='check_jobs') headers.update(sdk_headers) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/recognitions' request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response - def check_job(self, id: str, **kwargs) -> 'DetailedResponse': + def check_job(self, id: str, **kwargs) -> DetailedResponse: """ Check a job. @@ -1106,27 +1118,31 @@ def check_job(self, id: str, **kwargs) -> 'DetailedResponse': instance of the service that owns the job. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `RecognitionJob` object """ if id is None: raise ValueError('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='V1', operation_id='check_job') headers.update(sdk_headers) - url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['id'] + path_param_values = self.encode_path_vars(id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/recognitions/{id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response - def delete_job(self, id: str, **kwargs) -> 'DetailedResponse': + def delete_job(self, id: str, **kwargs) -> DetailedResponse: """ Delete a job. @@ -1148,16 +1164,19 @@ def delete_job(self, id: str, **kwargs) -> 'DetailedResponse': if id is None: raise ValueError('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='V1', operation_id='delete_job') headers.update(sdk_headers) - url = '/v1/recognitions/{0}'.format(*self._encode_path_vars(id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['id'] + path_param_values = self.encode_path_vars(id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/recognitions/{id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers) @@ -1175,7 +1194,7 @@ def create_language_model(self, *, dialect: str = None, description: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create a custom language model. @@ -1226,17 +1245,14 @@ def create_language_model(self, model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `LanguageModel` object """ if name is None: raise ValueError('name must be provided') if base_model_name is None: raise ValueError('base_model_name 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='V1', operation_id='create_language_model') @@ -1248,6 +1264,13 @@ def create_language_model(self, 'dialect': dialect, 'description': description } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v1/customizations' request = self.prepare_request(method='POST', @@ -1261,7 +1284,7 @@ def create_language_model(self, def list_language_models(self, *, language: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List custom language models. @@ -1282,12 +1305,10 @@ def list_language_models(self, customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `LanguageModels` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='list_language_models') @@ -1295,6 +1316,10 @@ def list_language_models(self, params = {'language': language} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/customizations' request = self.prepare_request(method='GET', url=url, @@ -1305,7 +1330,7 @@ def list_language_models(self, return response def get_language_model(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get a custom language model. @@ -1320,29 +1345,32 @@ def get_language_model(self, customization_id: str, custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `LanguageModel` object """ if customization_id is None: raise ValueError('customization_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='V1', operation_id='get_language_model') headers.update(sdk_headers) - url = '/v1/customizations/{0}'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response def delete_language_model(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a custom language model. @@ -1364,17 +1392,20 @@ def delete_language_model(self, customization_id: str, if customization_id is None: raise ValueError('customization_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='V1', operation_id='delete_language_model') headers.update(sdk_headers) - url = '/v1/customizations/{0}'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers) @@ -1387,7 +1418,7 @@ def train_language_model(self, *, word_type_to_add: str = None, customization_weight: float = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Train a custom language model. @@ -1448,15 +1479,12 @@ def train_language_model(self, customization weight for that request. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object """ if customization_id is None: raise ValueError('customization_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='V1', operation_id='train_language_model') @@ -1467,8 +1495,15 @@ def train_language_model(self, 'customization_weight': customization_weight } - url = '/v1/customizations/{0}/train'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/train'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1478,7 +1513,7 @@ def train_language_model(self, return response def reset_language_model(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Reset a custom language model. @@ -1502,24 +1537,28 @@ def reset_language_model(self, customization_id: str, if customization_id is None: raise ValueError('customization_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='V1', operation_id='reset_language_model') headers.update(sdk_headers) - url = '/v1/customizations/{0}/reset'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/reset'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers) response = self.send(request) return response def upgrade_language_model(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Upgrade a custom language model. @@ -1551,17 +1590,21 @@ def upgrade_language_model(self, customization_id: str, if customization_id is None: raise ValueError('customization_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='V1', operation_id='upgrade_language_model') headers.update(sdk_headers) - url = '/v1/customizations/{0}/upgrade_model'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/upgrade_model'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers) response = self.send(request) @@ -1571,8 +1614,7 @@ def upgrade_language_model(self, customization_id: str, # Custom corpora ######################### - def list_corpora(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: """ List corpora. @@ -1589,22 +1631,26 @@ def list_corpora(self, customization_id: str, custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Corpora` object """ if customization_id is None: raise ValueError('customization_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='V1', operation_id='list_corpora') headers.update(sdk_headers) - url = '/v1/customizations/{0}/corpora'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/corpora'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) @@ -1616,7 +1662,7 @@ def add_corpus(self, corpus_file: BinaryIO, *, allow_overwrite: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add a corpus. @@ -1683,7 +1729,7 @@ def add_corpus(self, custom words that are added or modified by the user. * Do not use the name `base_lm` or `default_lm`. Both names are reserved for future use by the service. - :param TextIO corpus_file: A plain text file that contains the training + :param BinaryIO corpus_file: A plain text file that contains the training data for the corpus. Encode the file in UTF-8 if it contains non-ASCII characters; the service assumes UTF-8 encoding if it encounters non-ASCII characters. @@ -1708,10 +1754,7 @@ def add_corpus(self, raise ValueError('corpus_name must be provided') if corpus_file is None: raise ValueError('corpus_file 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='V1', operation_id='add_corpus') @@ -1722,8 +1765,15 @@ def add_corpus(self, form_data = [] form_data.append(('corpus_file', (None, corpus_file, 'text/plain'))) - url = '/v1/customizations/{0}/corpora/{1}'.format( - *self._encode_path_vars(customization_id, corpus_name)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'corpus_name'] + path_param_values = self.encode_path_vars(customization_id, corpus_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1734,7 +1784,7 @@ def add_corpus(self, return response def get_corpus(self, customization_id: str, corpus_name: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get a corpus. @@ -1753,31 +1803,35 @@ def get_corpus(self, customization_id: str, corpus_name: str, model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Corpus` object """ if customization_id is None: raise ValueError('customization_id must be provided') if corpus_name is None: raise ValueError('corpus_name 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='V1', operation_id='get_corpus') headers.update(sdk_headers) - url = '/v1/customizations/{0}/corpora/{1}'.format( - *self._encode_path_vars(customization_id, corpus_name)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'corpus_name'] + path_param_values = self.encode_path_vars(customization_id, corpus_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response def delete_corpus(self, customization_id: str, corpus_name: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a corpus. @@ -1807,17 +1861,21 @@ def delete_corpus(self, customization_id: str, corpus_name: str, raise ValueError('customization_id must be provided') if corpus_name is None: raise ValueError('corpus_name 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='V1', operation_id='delete_corpus') headers.update(sdk_headers) - url = '/v1/customizations/{0}/corpora/{1}'.format( - *self._encode_path_vars(customization_id, corpus_name)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'corpus_name'] + path_param_values = self.encode_path_vars(customization_id, corpus_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers) @@ -1834,7 +1892,7 @@ def list_words(self, *, word_type: str = None, sort: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List custom words. @@ -1869,15 +1927,12 @@ def list_words(self, the `curl` command, URL-encode the `+` symbol as `%2B`. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Words` object """ if customization_id is None: raise ValueError('customization_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='V1', operation_id='list_words') @@ -1885,8 +1940,15 @@ def list_words(self, params = {'word_type': word_type, 'sort': sort} - url = '/v1/customizations/{0}/words'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/words'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1896,7 +1958,7 @@ def list_words(self, return response def add_words(self, customization_id: str, words: List['CustomWord'], - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add custom words. @@ -1970,20 +2032,27 @@ def add_words(self, customization_id: str, words: List['CustomWord'], raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') - words = [self._convert_model(x) for x in words] - + words = [convert_model(x) for x in words] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='add_words') headers.update(sdk_headers) data = {'words': words} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/customizations/{0}/words'.format( - *self._encode_path_vars(customization_id)) + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/words'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1999,7 +2068,7 @@ def add_word(self, word: str = None, sounds_like: List[str] = None, display_as: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add a custom word. @@ -2081,10 +2150,7 @@ def add_word(self, raise ValueError('customization_id must be provided') if word_name is None: raise ValueError('word_name 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='V1', operation_id='add_word') @@ -2095,9 +2161,19 @@ def add_word(self, 'sounds_like': sounds_like, 'display_as': display_as } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/customizations/{0}/words/{1}'.format( - *self._encode_path_vars(customization_id, word_name)) + path_param_keys = ['customization_id', 'word_name'] + path_param_values = self.encode_path_vars(customization_id, word_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/words/{word_name}'.format( + **path_param_dict) request = self.prepare_request(method='PUT', url=url, headers=headers, @@ -2107,7 +2183,7 @@ def add_word(self, return response def get_word(self, customization_id: str, word_name: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get a custom word. @@ -2127,31 +2203,35 @@ def get_word(self, customization_id: str, word_name: str, 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 + :rtype: DetailedResponse with `dict` result representing a `Word` object """ if customization_id is None: raise ValueError('customization_id must be provided') if word_name is None: raise ValueError('word_name 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='V1', operation_id='get_word') headers.update(sdk_headers) - url = '/v1/customizations/{0}/words/{1}'.format( - *self._encode_path_vars(customization_id, word_name)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'word_name'] + path_param_values = self.encode_path_vars(customization_id, word_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/words/{word_name}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response def delete_word(self, customization_id: str, word_name: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a custom word. @@ -2182,17 +2262,21 @@ def delete_word(self, customization_id: str, word_name: str, raise ValueError('customization_id must be provided') if word_name is None: raise ValueError('word_name 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='V1', operation_id='delete_word') headers.update(sdk_headers) - url = '/v1/customizations/{0}/words/{1}'.format( - *self._encode_path_vars(customization_id, word_name)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'word_name'] + path_param_values = self.encode_path_vars(customization_id, word_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/words/{word_name}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers) @@ -2205,7 +2289,7 @@ def delete_word(self, customization_id: str, word_name: str, ######################### def list_grammars(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List grammars. @@ -2222,22 +2306,26 @@ def list_grammars(self, customization_id: str, custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Grammars` object """ if customization_id is None: raise ValueError('customization_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='V1', operation_id='list_grammars') headers.update(sdk_headers) - url = '/v1/customizations/{0}/grammars'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/grammars'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) @@ -2246,11 +2334,11 @@ def list_grammars(self, customization_id: str, def add_grammar(self, customization_id: str, grammar_name: str, - grammar_file: str, + grammar_file: Union[str, TextIO], content_type: str, *, allow_overwrite: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add a grammar. @@ -2338,10 +2426,7 @@ def add_grammar(self, raise ValueError('grammar_file must be provided') if content_type is None: raise ValueError('content_type must be provided') - headers = {'Content-Type': content_type} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='add_grammar') @@ -2351,8 +2436,16 @@ def add_grammar(self, data = grammar_file - url = '/v1/customizations/{0}/grammars/{1}'.format( - *self._encode_path_vars(customization_id, grammar_name)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'grammar_name'] + path_param_values = self.encode_path_vars(customization_id, + grammar_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -2363,7 +2456,7 @@ def add_grammar(self, return response def get_grammar(self, customization_id: str, grammar_name: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get a grammar. @@ -2382,31 +2475,36 @@ def get_grammar(self, customization_id: str, grammar_name: str, model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Grammar` object """ if customization_id is None: raise ValueError('customization_id must be provided') if grammar_name is None: raise ValueError('grammar_name 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='V1', operation_id='get_grammar') headers.update(sdk_headers) - url = '/v1/customizations/{0}/grammars/{1}'.format( - *self._encode_path_vars(customization_id, grammar_name)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'grammar_name'] + path_param_values = self.encode_path_vars(customization_id, + grammar_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response def delete_grammar(self, customization_id: str, grammar_name: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a grammar. @@ -2435,17 +2533,22 @@ def delete_grammar(self, customization_id: str, grammar_name: str, raise ValueError('customization_id must be provided') if grammar_name is None: raise ValueError('grammar_name 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='V1', operation_id='delete_grammar') headers.update(sdk_headers) - url = '/v1/customizations/{0}/grammars/{1}'.format( - *self._encode_path_vars(customization_id, grammar_name)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'grammar_name'] + path_param_values = self.encode_path_vars(customization_id, + grammar_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers) @@ -2462,7 +2565,7 @@ def create_acoustic_model(self, base_model_name: str, *, description: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create a custom acoustic model. @@ -2493,17 +2596,14 @@ def create_acoustic_model(self, model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `AcousticModel` object """ if name is None: raise ValueError('name must be provided') if base_model_name is None: raise ValueError('base_model_name 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='V1', operation_id='create_acoustic_model') @@ -2514,6 +2614,13 @@ def create_acoustic_model(self, 'base_model_name': base_model_name, 'description': description } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v1/acoustic_customizations' request = self.prepare_request(method='POST', @@ -2527,7 +2634,7 @@ def create_acoustic_model(self, def list_acoustic_models(self, *, language: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List custom acoustic models. @@ -2548,12 +2655,10 @@ def list_acoustic_models(self, customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `AcousticModels` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='list_acoustic_models') @@ -2561,6 +2666,10 @@ def list_acoustic_models(self, params = {'language': language} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/acoustic_customizations' request = self.prepare_request(method='GET', url=url, @@ -2571,7 +2680,7 @@ def list_acoustic_models(self, return response def get_acoustic_model(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get a custom acoustic model. @@ -2586,29 +2695,33 @@ def get_acoustic_model(self, customization_id: str, custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `AcousticModel` object """ if customization_id is None: raise ValueError('customization_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='V1', operation_id='get_acoustic_model') headers.update(sdk_headers) - url = '/v1/acoustic_customizations/{0}'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/acoustic_customizations/{customization_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response def delete_acoustic_model(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a custom acoustic model. @@ -2630,17 +2743,21 @@ def delete_acoustic_model(self, customization_id: str, if customization_id is None: raise ValueError('customization_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='V1', operation_id='delete_acoustic_model') headers.update(sdk_headers) - url = '/v1/acoustic_customizations/{0}'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/acoustic_customizations/{customization_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers) @@ -2652,7 +2769,7 @@ def train_acoustic_model(self, customization_id: str, *, custom_language_model_id: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Train a custom acoustic model. @@ -2723,15 +2840,12 @@ def train_acoustic_model(self, custom models. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object """ if customization_id is None: raise ValueError('customization_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='V1', operation_id='train_acoustic_model') @@ -2739,8 +2853,15 @@ def train_acoustic_model(self, params = {'custom_language_model_id': custom_language_model_id} - url = '/v1/acoustic_customizations/{0}/train'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/acoustic_customizations/{customization_id}/train'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -2750,7 +2871,7 @@ def train_acoustic_model(self, return response def reset_acoustic_model(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Reset a custom acoustic model. @@ -2776,17 +2897,21 @@ def reset_acoustic_model(self, customization_id: str, if customization_id is None: raise ValueError('customization_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='V1', operation_id='reset_acoustic_model') headers.update(sdk_headers) - url = '/v1/acoustic_customizations/{0}/reset'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/acoustic_customizations/{customization_id}/reset'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers) response = self.send(request) @@ -2797,7 +2922,7 @@ def upgrade_acoustic_model(self, *, custom_language_model_id: str = None, force: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Upgrade a custom acoustic model. @@ -2850,10 +2975,7 @@ def upgrade_acoustic_model(self, if customization_id is None: raise ValueError('customization_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='V1', operation_id='upgrade_acoustic_model') @@ -2864,8 +2986,15 @@ def upgrade_acoustic_model(self, 'force': force } - url = '/v1/acoustic_customizations/{0}/upgrade_model'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/acoustic_customizations/{customization_id}/upgrade_model'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -2878,7 +3007,7 @@ def upgrade_acoustic_model(self, # Custom audio resources ######################### - def list_audio(self, customization_id: str, **kwargs) -> 'DetailedResponse': + def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: """ List audio resources. @@ -2897,22 +3026,26 @@ def list_audio(self, customization_id: str, **kwargs) -> 'DetailedResponse': custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `AudioResources` object """ if customization_id is None: raise ValueError('customization_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='V1', operation_id='list_audio') headers.update(sdk_headers) - url = '/v1/acoustic_customizations/{0}/audio'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/acoustic_customizations/{customization_id}/audio'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) @@ -2926,7 +3059,7 @@ def add_audio(self, content_type: str = None, contained_content_type: str = None, allow_overwrite: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add an audio resource. @@ -3070,13 +3203,10 @@ def add_audio(self, raise ValueError('audio_name must be provided') if audio_resource is None: raise ValueError('audio_resource must be provided') - headers = { 'Content-Type': content_type, 'Contained-Content-Type': contained_content_type } - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='add_audio') @@ -3086,8 +3216,15 @@ def add_audio(self, data = audio_resource - url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( - *self._encode_path_vars(customization_id, audio_name)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'audio_name'] + path_param_values = self.encode_path_vars(customization_id, audio_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -3098,7 +3235,7 @@ def add_audio(self, return response def get_audio(self, customization_id: str, audio_name: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get an audio resource. @@ -3131,31 +3268,35 @@ def get_audio(self, customization_id: str, audio_name: str, acoustic model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `AudioListing` object """ if customization_id is None: raise ValueError('customization_id must be provided') if audio_name is None: raise ValueError('audio_name 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='V1', operation_id='get_audio') headers.update(sdk_headers) - url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( - *self._encode_path_vars(customization_id, audio_name)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'audio_name'] + path_param_values = self.encode_path_vars(customization_id, audio_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response def delete_audio(self, customization_id: str, audio_name: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete an audio resource. @@ -3185,17 +3326,21 @@ def delete_audio(self, customization_id: str, audio_name: str, raise ValueError('customization_id must be provided') if audio_name is None: raise ValueError('audio_name 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='V1', operation_id='delete_audio') headers.update(sdk_headers) - url = '/v1/acoustic_customizations/{0}/audio/{1}'.format( - *self._encode_path_vars(customization_id, audio_name)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'audio_name'] + path_param_values = self.encode_path_vars(customization_id, audio_name) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers) @@ -3207,8 +3352,7 @@ def delete_audio(self, customization_id: str, audio_name: str, # User data ######################### - def delete_user_data(self, customer_id: str, - **kwargs) -> 'DetailedResponse': + def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: """ Delete labeled data. @@ -3236,10 +3380,7 @@ def delete_user_data(self, customer_id: str, if customer_id is None: raise ValueError('customer_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='V1', operation_id='delete_user_data') @@ -3247,6 +3388,9 @@ def delete_user_data(self, customer_id: str, params = {'customer_id': customer_id} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + url = '/v1/user_data' request = self.prepare_request(method='DELETE', url=url, @@ -3257,9 +3401,12 @@ def delete_user_data(self, customer_id: str, return response -class GetModelEnums(object): +class GetModelEnums: + """ + Enums for get_model parameters. + """ - class ModelId(Enum): + class ModelId(str, Enum): """ The identifier of the model in the form of its name from the output of the **Get a model** method. @@ -3304,9 +3451,12 @@ class ModelId(Enum): ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' -class RecognizeEnums(object): +class RecognizeEnums: + """ + Enums for recognize parameters. + """ - class ContentType(Enum): + class ContentType(str, Enum): """ The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. @@ -3328,7 +3478,7 @@ class ContentType(Enum): AUDIO_WEBM_CODECS_OPUS = 'audio/webm;codecs=opus' AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' - class Model(Enum): + class Model(str, Enum): """ The identifier of the model that is to be used for the recognition request. See [Languages and @@ -3374,9 +3524,12 @@ class Model(Enum): ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' -class CreateJobEnums(object): +class CreateJobEnums: + """ + Enums for create_job parameters. + """ - class ContentType(Enum): + class ContentType(str, Enum): """ The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. @@ -3398,7 +3551,7 @@ class ContentType(Enum): AUDIO_WEBM_CODECS_OPUS = 'audio/webm;codecs=opus' AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' - class Model(Enum): + class Model(str, Enum): """ The identifier of the model that is to be used for the recognition request. See [Languages and @@ -3443,7 +3596,7 @@ class Model(Enum): ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' - class Events(Enum): + class Events(str, Enum): """ If the job includes a callback URL, a comma-separated list of notification events to which to subscribe. Valid events are @@ -3469,9 +3622,12 @@ class Events(Enum): RECOGNITIONS_FAILED = 'recognitions.failed' -class ListLanguageModelsEnums(object): +class ListLanguageModelsEnums: + """ + Enums for list_language_models parameters. + """ - class Language(Enum): + class Language(str, Enum): """ The identifier of the language for which custom language or custom acoustic models are to be returned. Omit the parameter to see all custom language or custom @@ -3501,9 +3657,12 @@ class Language(Enum): ZH_CN = 'zh-CN' -class TrainLanguageModelEnums(object): +class TrainLanguageModelEnums: + """ + Enums for train_language_model parameters. + """ - class WordTypeToAdd(Enum): + class WordTypeToAdd(str, Enum): """ The type of words from the custom language model's words resource on which to train the model: @@ -3518,9 +3677,12 @@ class WordTypeToAdd(Enum): USER = 'user' -class ListWordsEnums(object): +class ListWordsEnums: + """ + Enums for list_words parameters. + """ - class WordType(Enum): + class WordType(str, Enum): """ The type of words to be listed from the custom language model's words resource: * `all` (the default) shows all words. @@ -3533,7 +3695,7 @@ class WordType(Enum): CORPORA = 'corpora' GRAMMARS = 'grammars' - class Sort(Enum): + class Sort(str, Enum): """ Indicates the order in which the words are to be listed, `alphabetical` or by `count`. You can prepend an optional `+` or `-` to an argument to indicate whether @@ -3547,9 +3709,12 @@ class Sort(Enum): COUNT = 'count' -class AddGrammarEnums(object): +class AddGrammarEnums: + """ + Enums for add_grammar parameters. + """ - class ContentType(Enum): + class ContentType(str, Enum): """ The format (MIME type) of the grammar file: * `application/srgs` for Augmented Backus-Naur Form (ABNF), which uses a @@ -3561,9 +3726,12 @@ class ContentType(Enum): APPLICATION_SRGS_XML = 'application/srgs+xml' -class ListAcousticModelsEnums(object): +class ListAcousticModelsEnums: + """ + Enums for list_acoustic_models parameters. + """ - class Language(Enum): + class Language(str, Enum): """ The identifier of the language for which custom language or custom acoustic models are to be returned. Omit the parameter to see all custom language or custom @@ -3593,9 +3761,12 @@ class Language(Enum): ZH_CN = 'zh-CN' -class AddAudioEnums(object): +class AddAudioEnums: + """ + Enums for add_audio parameters. + """ - class ContentType(Enum): + class ContentType(str, Enum): """ For an audio-type resource, the format (MIME type) of the audio. For more information, see **Content types for audio-type resources** in the method @@ -3622,7 +3793,7 @@ class ContentType(Enum): AUDIO_WEBM_CODECS_OPUS = 'audio/webm;codecs=opus' AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' - class ContainedContentType(Enum): + class ContainedContentType(str, Enum): """ **For an archive-type resource,** specify the format of the audio files that are contained in the archive file if they are of type `audio/alaw`, `audio/basic`, @@ -3787,16 +3958,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AcousticModel': """Initialize a AcousticModel object from a json dictionary.""" args = {} - valid_keys = [ - 'customization_id', 'created', 'updated', 'language', 'versions', - 'owner', 'name', 'description', 'base_model_name', 'status', - 'progress', 'warnings' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AcousticModel: ' - + ', '.join(bad_keys)) if 'customization_id' in _dict: args['customization_id'] = _dict.get('customization_id') else: @@ -3869,7 +4030,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AcousticModel object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AcousticModel') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3881,7 +4042,7 @@ def __ne__(self, other: 'AcousticModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The current status of the custom acoustic model: * `pending`: The model was created but is waiting either for valid training data @@ -3894,12 +4055,12 @@ class StatusEnum(Enum): * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. """ - PENDING = "pending" - READY = "ready" - TRAINING = "training" - AVAILABLE = "available" - UPGRADING = "upgrading" - FAILED = "failed" + PENDING = 'pending' + READY = 'ready' + TRAINING = 'training' + AVAILABLE = 'available' + UPGRADING = 'upgrading' + FAILED = 'failed' class AcousticModels(): @@ -3929,16 +4090,9 @@ def __init__(self, customizations: List['AcousticModel']) -> None: def from_dict(cls, _dict: Dict) -> 'AcousticModels': """Initialize a AcousticModels object from a json dictionary.""" args = {} - valid_keys = ['customizations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AcousticModels: ' - + ', '.join(bad_keys)) if 'customizations' in _dict: args['customizations'] = [ - AcousticModel._from_dict(x) - for x in (_dict.get('customizations')) + AcousticModel.from_dict(x) for x in _dict.get('customizations') ] else: raise ValueError( @@ -3955,9 +4109,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [ - x._to_dict() for x in self.customizations - ] + _dict['customizations'] = [x.to_dict() for x in self.customizations] return _dict def _to_dict(self): @@ -3966,7 +4118,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AcousticModels object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AcousticModels') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4038,12 +4190,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioDetails': """Initialize a AudioDetails object from a json dictionary.""" args = {} - valid_keys = ['type', 'codec', 'frequency', 'compression'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AudioDetails: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'codec' in _dict: @@ -4078,7 +4224,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AudioDetails object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AudioDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4090,7 +4236,7 @@ def __ne__(self, other: 'AudioDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The type of the audio resource: * `audio` for an individual audio file @@ -4100,19 +4246,19 @@ class TypeEnum(Enum): the user mistakenly passes a file that does not contain audio, such as a JPEG file). """ - AUDIO = "audio" - ARCHIVE = "archive" - UNDETERMINED = "undetermined" + AUDIO = 'audio' + ARCHIVE = 'archive' + UNDETERMINED = 'undetermined' - class CompressionEnum(Enum): + class CompressionEnum(str, Enum): """ **For an archive-type resource,** the format of the compressed archive: * `zip` for a **.zip** file * `gzip` for a **.tar.gz** file Omitted for an audio-type resource. """ - ZIP = "zip" - GZIP = "gzip" + ZIP = 'zip' + GZIP = 'gzip' class AudioListing(): @@ -4195,27 +4341,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioListing': """Initialize a AudioListing object from a json dictionary.""" args = {} - valid_keys = [ - 'duration', 'name', 'details', 'status', 'container', 'audio' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AudioListing: ' - + ', '.join(bad_keys)) if 'duration' in _dict: args['duration'] = _dict.get('duration') if 'name' in _dict: args['name'] = _dict.get('name') if 'details' in _dict: - args['details'] = AudioDetails._from_dict(_dict.get('details')) + args['details'] = AudioDetails.from_dict(_dict.get('details')) if 'status' in _dict: args['status'] = _dict.get('status') if 'container' in _dict: - args['container'] = AudioResource._from_dict(_dict.get('container')) + args['container'] = AudioResource.from_dict(_dict.get('container')) if 'audio' in _dict: args['audio'] = [ - AudioResource._from_dict(x) for x in (_dict.get('audio')) + AudioResource.from_dict(x) for x in _dict.get('audio') ] return cls(**args) @@ -4232,13 +4370,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'details') and self.details is not None: - _dict['details'] = self.details._to_dict() + _dict['details'] = self.details.to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'container') and self.container is not None: - _dict['container'] = self.container._to_dict() + _dict['container'] = self.container.to_dict() if hasattr(self, 'audio') and self.audio is not None: - _dict['audio'] = [x._to_dict() for x in self.audio] + _dict['audio'] = [x.to_dict() for x in self.audio] return _dict def _to_dict(self): @@ -4247,7 +4385,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AudioListing object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AudioListing') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4259,7 +4397,7 @@ def __ne__(self, other: 'AudioListing') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ **For an audio-type resource,** the status of the resource: * `ok`: The service successfully analyzed the audio data. The data can be used to @@ -4271,9 +4409,9 @@ class StatusEnum(Enum): because it has the wrong format or sampling rate, or because it is corrupted). Omitted for an archive-type resource. """ - OK = "ok" - BEING_PROCESSED = "being_processed" - INVALID = "invalid" + OK = 'ok' + BEING_PROCESSED = 'being_processed' + INVALID = 'invalid' class AudioMetrics(): @@ -4310,12 +4448,6 @@ def __init__(self, sampling_interval: float, def from_dict(cls, _dict: Dict) -> 'AudioMetrics': """Initialize a AudioMetrics object from a json dictionary.""" args = {} - valid_keys = ['sampling_interval', 'accumulated'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AudioMetrics: ' - + ', '.join(bad_keys)) if 'sampling_interval' in _dict: args['sampling_interval'] = _dict.get('sampling_interval') else: @@ -4323,7 +4455,7 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetrics': 'Required property \'sampling_interval\' not present in AudioMetrics JSON' ) if 'accumulated' in _dict: - args['accumulated'] = AudioMetricsDetails._from_dict( + args['accumulated'] = AudioMetricsDetails.from_dict( _dict.get('accumulated')) else: raise ValueError( @@ -4343,7 +4475,7 @@ def to_dict(self) -> Dict: 'sampling_interval') and self.sampling_interval is not None: _dict['sampling_interval'] = self.sampling_interval if hasattr(self, 'accumulated') and self.accumulated is not None: - _dict['accumulated'] = self.accumulated._to_dict() + _dict['accumulated'] = self.accumulated.to_dict() return _dict def _to_dict(self): @@ -4352,7 +4484,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AudioMetrics object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AudioMetrics') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4483,16 +4615,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': """Initialize a AudioMetricsDetails object from a json dictionary.""" args = {} - valid_keys = [ - 'final', 'end_time', 'signal_to_noise_ratio', 'speech_ratio', - 'high_frequency_loss', 'direct_current_offset', 'clipping_rate', - 'speech_level', 'non_speech_level' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AudioMetricsDetails: ' - + ', '.join(bad_keys)) if 'final' in _dict: args['final'] = _dict.get('final') else: @@ -4521,8 +4643,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'direct_current_offset' in _dict: args['direct_current_offset'] = [ - AudioMetricsHistogramBin._from_dict(x) - for x in (_dict.get('direct_current_offset')) + AudioMetricsHistogramBin.from_dict(x) + for x in _dict.get('direct_current_offset') ] else: raise ValueError( @@ -4530,8 +4652,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'clipping_rate' in _dict: args['clipping_rate'] = [ - AudioMetricsHistogramBin._from_dict(x) - for x in (_dict.get('clipping_rate')) + AudioMetricsHistogramBin.from_dict(x) + for x in _dict.get('clipping_rate') ] else: raise ValueError( @@ -4539,8 +4661,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'speech_level' in _dict: args['speech_level'] = [ - AudioMetricsHistogramBin._from_dict(x) - for x in (_dict.get('speech_level')) + AudioMetricsHistogramBin.from_dict(x) + for x in _dict.get('speech_level') ] else: raise ValueError( @@ -4548,8 +4670,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'non_speech_level' in _dict: args['non_speech_level'] = [ - AudioMetricsHistogramBin._from_dict(x) - for x in (_dict.get('non_speech_level')) + AudioMetricsHistogramBin.from_dict(x) + for x in _dict.get('non_speech_level') ] else: raise ValueError( @@ -4581,16 +4703,16 @@ def to_dict(self) -> Dict: if hasattr(self, 'direct_current_offset' ) and self.direct_current_offset is not None: _dict['direct_current_offset'] = [ - x._to_dict() for x in self.direct_current_offset + x.to_dict() for x in self.direct_current_offset ] if hasattr(self, 'clipping_rate') and self.clipping_rate is not None: - _dict['clipping_rate'] = [x._to_dict() for x in self.clipping_rate] + _dict['clipping_rate'] = [x.to_dict() for x in self.clipping_rate] if hasattr(self, 'speech_level') and self.speech_level is not None: - _dict['speech_level'] = [x._to_dict() for x in self.speech_level] + _dict['speech_level'] = [x.to_dict() for x in self.speech_level] if hasattr(self, 'non_speech_level') and self.non_speech_level is not None: _dict['non_speech_level'] = [ - x._to_dict() for x in self.non_speech_level + x.to_dict() for x in self.non_speech_level ] return _dict @@ -4600,7 +4722,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AudioMetricsDetails object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AudioMetricsDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4641,12 +4763,6 @@ def __init__(self, begin: float, end: float, count: int) -> None: def from_dict(cls, _dict: Dict) -> 'AudioMetricsHistogramBin': """Initialize a AudioMetricsHistogramBin object from a json dictionary.""" args = {} - valid_keys = ['begin', 'end', 'count'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AudioMetricsHistogramBin: ' - + ', '.join(bad_keys)) if 'begin' in _dict: args['begin'] = _dict.get('begin') else: @@ -4689,7 +4805,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AudioMetricsHistogramBin object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AudioMetricsHistogramBin') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4761,12 +4877,6 @@ def __init__(self, duration: int, name: str, details: 'AudioDetails', def from_dict(cls, _dict: Dict) -> 'AudioResource': """Initialize a AudioResource object from a json dictionary.""" args = {} - valid_keys = ['duration', 'name', 'details', 'status'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AudioResource: ' - + ', '.join(bad_keys)) if 'duration' in _dict: args['duration'] = _dict.get('duration') else: @@ -4779,7 +4889,7 @@ def from_dict(cls, _dict: Dict) -> 'AudioResource': raise ValueError( 'Required property \'name\' not present in AudioResource JSON') if 'details' in _dict: - args['details'] = AudioDetails._from_dict(_dict.get('details')) + args['details'] = AudioDetails.from_dict(_dict.get('details')) else: raise ValueError( 'Required property \'details\' not present in AudioResource JSON' @@ -4805,7 +4915,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'details') and self.details is not None: - _dict['details'] = self.details._to_dict() + _dict['details'] = self.details.to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict @@ -4816,7 +4926,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AudioResource object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AudioResource') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4828,7 +4938,7 @@ def __ne__(self, other: 'AudioResource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The status of the audio resource: * `ok`: The service successfully analyzed the audio data. The data can be used to @@ -4841,9 +4951,9 @@ class StatusEnum(Enum): an archive file, the entire archive is invalid if any of its audio files are invalid. """ - OK = "ok" - BEING_PROCESSED = "being_processed" - INVALID = "invalid" + OK = 'ok' + BEING_PROCESSED = 'being_processed' + INVALID = 'invalid' class AudioResources(): @@ -4879,12 +4989,6 @@ def __init__(self, total_minutes_of_audio: float, def from_dict(cls, _dict: Dict) -> 'AudioResources': """Initialize a AudioResources object from a json dictionary.""" args = {} - valid_keys = ['total_minutes_of_audio', 'audio'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AudioResources: ' - + ', '.join(bad_keys)) if 'total_minutes_of_audio' in _dict: args['total_minutes_of_audio'] = _dict.get('total_minutes_of_audio') else: @@ -4893,7 +4997,7 @@ def from_dict(cls, _dict: Dict) -> 'AudioResources': ) if 'audio' in _dict: args['audio'] = [ - AudioResource._from_dict(x) for x in (_dict.get('audio')) + AudioResource.from_dict(x) for x in _dict.get('audio') ] else: raise ValueError( @@ -4913,7 +5017,7 @@ def to_dict(self) -> Dict: ) and self.total_minutes_of_audio is not None: _dict['total_minutes_of_audio'] = self.total_minutes_of_audio if hasattr(self, 'audio') and self.audio is not None: - _dict['audio'] = [x._to_dict() for x in self.audio] + _dict['audio'] = [x.to_dict() for x in self.audio] return _dict def _to_dict(self): @@ -4922,7 +5026,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AudioResources object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AudioResources') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4958,15 +5062,9 @@ def __init__(self, corpora: List['Corpus']) -> None: def from_dict(cls, _dict: Dict) -> 'Corpora': """Initialize a Corpora object from a json dictionary.""" args = {} - valid_keys = ['corpora'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Corpora: ' + - ', '.join(bad_keys)) if 'corpora' in _dict: args['corpora'] = [ - Corpus._from_dict(x) for x in (_dict.get('corpora')) + Corpus.from_dict(x) for x in _dict.get('corpora') ] else: raise ValueError( @@ -4982,7 +5080,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'corpora') and self.corpora is not None: - _dict['corpora'] = [x._to_dict() for x in self.corpora] + _dict['corpora'] = [x.to_dict() for x in self.corpora] return _dict def _to_dict(self): @@ -4991,7 +5089,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Corpora object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Corpora') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5061,14 +5159,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Corpus': """Initialize a Corpus object from a json dictionary.""" args = {} - valid_keys = [ - 'name', 'total_words', 'out_of_vocabulary_words', 'status', 'error' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Corpus: ' + - ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -5122,7 +5212,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Corpus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Corpus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5134,7 +5224,7 @@ def __ne__(self, other: 'Corpus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The status of the corpus: * `analyzed`: The service successfully analyzed the corpus. The custom model can @@ -5144,9 +5234,9 @@ class StatusEnum(Enum): * `undetermined`: The service encountered an error while processing the corpus. The `error` field describes the failure. """ - ANALYZED = "analyzed" - BEING_PROCESSED = "being_processed" - UNDETERMINED = "undetermined" + ANALYZED = 'analyzed' + BEING_PROCESSED = 'being_processed' + UNDETERMINED = 'undetermined' class CustomWord(): @@ -5214,12 +5304,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CustomWord': """Initialize a CustomWord object from a json dictionary.""" args = {} - valid_keys = ['word', 'sounds_like', 'display_as'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CustomWord: ' - + ', '.join(bad_keys)) if 'word' in _dict: args['word'] = _dict.get('word') if 'sounds_like' in _dict: @@ -5250,7 +5334,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CustomWord object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CustomWord') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5317,12 +5401,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Grammar': """Initialize a Grammar object from a json dictionary.""" args = {} - valid_keys = ['name', 'out_of_vocabulary_words', 'status', 'error'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Grammar: ' + - ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -5369,7 +5447,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Grammar object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Grammar') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5381,7 +5459,7 @@ def __ne__(self, other: 'Grammar') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The status of the grammar: * `analyzed`: The service successfully analyzed the grammar. The custom model can @@ -5391,9 +5469,9 @@ class StatusEnum(Enum): * `undetermined`: The service encountered an error while processing the grammar. The `error` field describes the failure. """ - ANALYZED = "analyzed" - BEING_PROCESSED = "being_processed" - UNDETERMINED = "undetermined" + ANALYZED = 'analyzed' + BEING_PROCESSED = 'being_processed' + UNDETERMINED = 'undetermined' class Grammars(): @@ -5419,15 +5497,9 @@ def __init__(self, grammars: List['Grammar']) -> None: def from_dict(cls, _dict: Dict) -> 'Grammars': """Initialize a Grammars object from a json dictionary.""" args = {} - valid_keys = ['grammars'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Grammars: ' - + ', '.join(bad_keys)) if 'grammars' in _dict: args['grammars'] = [ - Grammar._from_dict(x) for x in (_dict.get('grammars')) + Grammar.from_dict(x) for x in _dict.get('grammars') ] else: raise ValueError( @@ -5443,7 +5515,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'grammars') and self.grammars is not None: - _dict['grammars'] = [x._to_dict() for x in self.grammars] + _dict['grammars'] = [x.to_dict() for x in self.grammars] return _dict def _to_dict(self): @@ -5452,7 +5524,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Grammars object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Grammars') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5498,12 +5570,6 @@ def __init__(self, normalized_text: str, start_time: float, end_time: float, def from_dict(cls, _dict: Dict) -> 'KeywordResult': """Initialize a KeywordResult object from a json dictionary.""" args = {} - valid_keys = ['normalized_text', 'start_time', 'end_time', 'confidence'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class KeywordResult: ' - + ', '.join(bad_keys)) if 'normalized_text' in _dict: args['normalized_text'] = _dict.get('normalized_text') else: @@ -5555,7 +5621,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this KeywordResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'KeywordResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5729,16 +5795,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LanguageModel': """Initialize a LanguageModel object from a json dictionary.""" args = {} - valid_keys = [ - 'customization_id', 'created', 'updated', 'language', 'dialect', - 'versions', 'owner', 'name', 'description', 'base_model_name', - 'status', 'progress', 'error', 'warnings' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LanguageModel: ' - + ', '.join(bad_keys)) if 'customization_id' in _dict: args['customization_id'] = _dict.get('customization_id') else: @@ -5819,7 +5875,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LanguageModel object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LanguageModel') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5831,7 +5887,7 @@ def __ne__(self, other: 'LanguageModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The current status of the custom language model: * `pending`: The model was created but is waiting either for valid training data @@ -5844,12 +5900,12 @@ class StatusEnum(Enum): * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. """ - PENDING = "pending" - READY = "ready" - TRAINING = "training" - AVAILABLE = "available" - UPGRADING = "upgrading" - FAILED = "failed" + PENDING = 'pending' + READY = 'ready' + TRAINING = 'training' + AVAILABLE = 'available' + UPGRADING = 'upgrading' + FAILED = 'failed' class LanguageModels(): @@ -5879,16 +5935,9 @@ def __init__(self, customizations: List['LanguageModel']) -> None: def from_dict(cls, _dict: Dict) -> 'LanguageModels': """Initialize a LanguageModels object from a json dictionary.""" args = {} - valid_keys = ['customizations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class LanguageModels: ' - + ', '.join(bad_keys)) if 'customizations' in _dict: args['customizations'] = [ - LanguageModel._from_dict(x) - for x in (_dict.get('customizations')) + LanguageModel.from_dict(x) for x in _dict.get('customizations') ] else: raise ValueError( @@ -5905,9 +5954,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [ - x._to_dict() for x in self.customizations - ] + _dict['customizations'] = [x.to_dict() for x in self.customizations] return _dict def _to_dict(self): @@ -5916,7 +5963,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this LanguageModels object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'LanguageModels') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5997,14 +6044,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProcessedAudio': """Initialize a ProcessedAudio object from a json dictionary.""" args = {} - valid_keys = [ - 'received', 'seen_by_engine', 'transcription', 'speaker_labels' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ProcessedAudio: ' - + ', '.join(bad_keys)) if 'received' in _dict: args['received'] = _dict.get('received') else: @@ -6051,7 +6090,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ProcessedAudio object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ProcessedAudio') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6127,17 +6166,8 @@ def __init__(self, processed_audio: 'ProcessedAudio', def from_dict(cls, _dict: Dict) -> 'ProcessingMetrics': """Initialize a ProcessingMetrics object from a json dictionary.""" args = {} - valid_keys = [ - 'processed_audio', 'wall_clock_since_first_byte_received', - 'periodic' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ProcessingMetrics: ' - + ', '.join(bad_keys)) if 'processed_audio' in _dict: - args['processed_audio'] = ProcessedAudio._from_dict( + args['processed_audio'] = ProcessedAudio.from_dict( _dict.get('processed_audio')) else: raise ValueError( @@ -6168,7 +6198,7 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'processed_audio') and self.processed_audio is not None: - _dict['processed_audio'] = self.processed_audio._to_dict() + _dict['processed_audio'] = self.processed_audio.to_dict() if hasattr(self, 'wall_clock_since_first_byte_received' ) and self.wall_clock_since_first_byte_received is not None: _dict[ @@ -6183,7 +6213,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ProcessingMetrics object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ProcessingMetrics') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6300,15 +6330,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RecognitionJob': """Initialize a RecognitionJob object from a json dictionary.""" args = {} - valid_keys = [ - 'id', 'status', 'created', 'updated', 'url', 'user_token', - 'results', 'warnings' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RecognitionJob: ' - + ', '.join(bad_keys)) if 'id' in _dict: args['id'] = _dict.get('id') else: @@ -6334,8 +6355,8 @@ def from_dict(cls, _dict: Dict) -> 'RecognitionJob': args['user_token'] = _dict.get('user_token') if 'results' in _dict: args['results'] = [ - SpeechRecognitionResults._from_dict(x) - for x in (_dict.get('results')) + SpeechRecognitionResults.from_dict(x) + for x in _dict.get('results') ] if 'warnings' in _dict: args['warnings'] = _dict.get('warnings') @@ -6362,7 +6383,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_token') and self.user_token is not None: _dict['user_token'] = self.user_token if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings return _dict @@ -6373,7 +6394,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RecognitionJob object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RecognitionJob') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6385,7 +6406,7 @@ def __ne__(self, other: 'RecognitionJob') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The current status of the job: * `waiting`: The service is preparing the job for processing. The service returns @@ -6399,10 +6420,10 @@ class StatusEnum(Enum): results by checking the individual job. * `failed`: The job failed. """ - WAITING = "waiting" - PROCESSING = "processing" - COMPLETED = "completed" - FAILED = "failed" + WAITING = 'waiting' + PROCESSING = 'processing' + COMPLETED = 'completed' + FAILED = 'failed' class RecognitionJobs(): @@ -6428,16 +6449,9 @@ def __init__(self, recognitions: List['RecognitionJob']) -> None: def from_dict(cls, _dict: Dict) -> 'RecognitionJobs': """Initialize a RecognitionJobs object from a json dictionary.""" args = {} - valid_keys = ['recognitions'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RecognitionJobs: ' - + ', '.join(bad_keys)) if 'recognitions' in _dict: args['recognitions'] = [ - RecognitionJob._from_dict(x) - for x in (_dict.get('recognitions')) + RecognitionJob.from_dict(x) for x in _dict.get('recognitions') ] else: raise ValueError( @@ -6454,7 +6468,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'recognitions') and self.recognitions is not None: - _dict['recognitions'] = [x._to_dict() for x in self.recognitions] + _dict['recognitions'] = [x.to_dict() for x in self.recognitions] return _dict def _to_dict(self): @@ -6463,7 +6477,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RecognitionJobs object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RecognitionJobs') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6505,12 +6519,6 @@ def __init__(self, status: str, url: str) -> None: def from_dict(cls, _dict: Dict) -> 'RegisterStatus': """Initialize a RegisterStatus object from a json dictionary.""" args = {} - valid_keys = ['status', 'url'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RegisterStatus: ' - + ', '.join(bad_keys)) if 'status' in _dict: args['status'] = _dict.get('status') else: @@ -6544,7 +6552,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RegisterStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RegisterStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6556,15 +6564,15 @@ def __ne__(self, other: 'RegisterStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ The current status of the job: * `created`: The service successfully allowlisted the callback URL as a result of the call. * `already created`: The URL was already allowlisted. """ - CREATED = "created" - ALREADY_CREATED = "already created" + CREATED = 'created' + ALREADY_CREATED = 'already created' class SpeakerLabelsResult(): @@ -6620,12 +6628,6 @@ def __init__(self, from_: float, to: float, speaker: int, confidence: float, def from_dict(cls, _dict: Dict) -> 'SpeakerLabelsResult': """Initialize a SpeakerLabelsResult object from a json dictionary.""" args = {} - valid_keys = ['from_', 'from', 'to', 'speaker', 'confidence', 'final'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SpeakerLabelsResult: ' - + ', '.join(bad_keys)) if 'from' in _dict: args['from_'] = _dict.get('from') else: @@ -6684,7 +6686,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SpeakerLabelsResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SpeakerLabelsResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6740,15 +6742,6 @@ def __init__(self, name: str, language: str, rate: int, url: str, def from_dict(cls, _dict: Dict) -> 'SpeechModel': """Initialize a SpeechModel object from a json dictionary.""" args = {} - valid_keys = [ - 'name', 'language', 'rate', 'url', 'supported_features', - 'description' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SpeechModel: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -6771,7 +6764,7 @@ def from_dict(cls, _dict: Dict) -> 'SpeechModel': raise ValueError( 'Required property \'url\' not present in SpeechModel JSON') if 'supported_features' in _dict: - args['supported_features'] = SupportedFeatures._from_dict( + args['supported_features'] = SupportedFeatures.from_dict( _dict.get('supported_features')) else: raise ValueError( @@ -6804,7 +6797,7 @@ def to_dict(self) -> Dict: if hasattr( self, 'supported_features') and self.supported_features is not None: - _dict['supported_features'] = self.supported_features._to_dict() + _dict['supported_features'] = self.supported_features.to_dict() if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description return _dict @@ -6815,7 +6808,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SpeechModel object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SpeechModel') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6849,15 +6842,9 @@ def __init__(self, models: List['SpeechModel']) -> None: def from_dict(cls, _dict: Dict) -> 'SpeechModels': """Initialize a SpeechModels object from a json dictionary.""" args = {} - valid_keys = ['models'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SpeechModels: ' - + ', '.join(bad_keys)) if 'models' in _dict: args['models'] = [ - SpeechModel._from_dict(x) for x in (_dict.get('models')) + SpeechModel.from_dict(x) for x in _dict.get('models') ] else: raise ValueError( @@ -6873,7 +6860,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x._to_dict() for x in self.models] + _dict['models'] = [x.to_dict() for x in self.models] return _dict def _to_dict(self): @@ -6882,7 +6869,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SpeechModels object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SpeechModels') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6949,14 +6936,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionAlternative': """Initialize a SpeechRecognitionAlternative object from a json dictionary.""" args = {} - valid_keys = [ - 'transcript', 'confidence', 'timestamps', 'word_confidence' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SpeechRecognitionAlternative: ' - + ', '.join(bad_keys)) if 'transcript' in _dict: args['transcript'] = _dict.get('transcript') else: @@ -6996,7 +6975,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SpeechRecognitionAlternative object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SpeechRecognitionAlternative') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7091,15 +7070,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': """Initialize a SpeechRecognitionResult object from a json dictionary.""" args = {} - valid_keys = [ - 'final', 'alternatives', 'keywords_result', 'word_alternatives', - 'end_of_utterance' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SpeechRecognitionResult: ' - + ', '.join(bad_keys)) if 'final' in _dict: args['final'] = _dict.get('final') else: @@ -7108,8 +7078,8 @@ def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': ) if 'alternatives' in _dict: args['alternatives'] = [ - SpeechRecognitionAlternative._from_dict(x) - for x in (_dict.get('alternatives')) + SpeechRecognitionAlternative.from_dict(x) + for x in _dict.get('alternatives') ] else: raise ValueError( @@ -7119,8 +7089,8 @@ def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': args['keywords_result'] = _dict.get('keywords_result') if 'word_alternatives' in _dict: args['word_alternatives'] = [ - WordAlternativeResults._from_dict(x) - for x in (_dict.get('word_alternatives')) + WordAlternativeResults.from_dict(x) + for x in _dict.get('word_alternatives') ] if 'end_of_utterance' in _dict: args['end_of_utterance'] = _dict.get('end_of_utterance') @@ -7137,14 +7107,14 @@ def to_dict(self) -> Dict: if hasattr(self, 'final') and self.final is not None: _dict['final'] = self.final if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x._to_dict() for x in self.alternatives] + _dict['alternatives'] = [x.to_dict() for x in self.alternatives] if hasattr(self, 'keywords_result') and self.keywords_result is not None: _dict['keywords_result'] = self.keywords_result if hasattr(self, 'word_alternatives') and self.word_alternatives is not None: _dict['word_alternatives'] = [ - x._to_dict() for x in self.word_alternatives + x.to_dict() for x in self.word_alternatives ] if hasattr(self, 'end_of_utterance') and self.end_of_utterance is not None: @@ -7157,7 +7127,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SpeechRecognitionResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SpeechRecognitionResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7169,7 +7139,7 @@ def __ne__(self, other: 'SpeechRecognitionResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class EndOfUtteranceEnum(Enum): + class EndOfUtteranceEnum(str, Enum): """ If the `split_transcript_at_phrase_end` parameter is `true`, describes the reason for the split: @@ -7182,10 +7152,10 @@ class EndOfUtteranceEnum(Enum): use. * `silence` - A pause or silence that is at least as long as the pause interval. """ - END_OF_DATA = "end_of_data" - FULL_STOP = "full_stop" - RESET = "reset" - SILENCE = "silence" + END_OF_DATA = 'end_of_data' + FULL_STOP = 'full_stop' + RESET = 'reset' + SILENCE = 'silence' class SpeechRecognitionResults(): @@ -7291,32 +7261,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResults': """Initialize a SpeechRecognitionResults object from a json dictionary.""" args = {} - valid_keys = [ - 'results', 'result_index', 'speaker_labels', 'processing_metrics', - 'audio_metrics', 'warnings' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SpeechRecognitionResults: ' - + ', '.join(bad_keys)) if 'results' in _dict: args['results'] = [ - SpeechRecognitionResult._from_dict(x) - for x in (_dict.get('results')) + SpeechRecognitionResult.from_dict(x) + for x in _dict.get('results') ] if 'result_index' in _dict: args['result_index'] = _dict.get('result_index') if 'speaker_labels' in _dict: args['speaker_labels'] = [ - SpeakerLabelsResult._from_dict(x) - for x in (_dict.get('speaker_labels')) + SpeakerLabelsResult.from_dict(x) + for x in _dict.get('speaker_labels') ] if 'processing_metrics' in _dict: - args['processing_metrics'] = ProcessingMetrics._from_dict( + args['processing_metrics'] = ProcessingMetrics.from_dict( _dict.get('processing_metrics')) if 'audio_metrics' in _dict: - args['audio_metrics'] = AudioMetrics._from_dict( + args['audio_metrics'] = AudioMetrics.from_dict( _dict.get('audio_metrics')) if 'warnings' in _dict: args['warnings'] = _dict.get('warnings') @@ -7331,19 +7292,17 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'result_index') and self.result_index is not None: _dict['result_index'] = self.result_index if hasattr(self, 'speaker_labels') and self.speaker_labels is not None: - _dict['speaker_labels'] = [ - x._to_dict() for x in self.speaker_labels - ] + _dict['speaker_labels'] = [x.to_dict() for x in self.speaker_labels] if hasattr( self, 'processing_metrics') and self.processing_metrics is not None: - _dict['processing_metrics'] = self.processing_metrics._to_dict() + _dict['processing_metrics'] = self.processing_metrics.to_dict() if hasattr(self, 'audio_metrics') and self.audio_metrics is not None: - _dict['audio_metrics'] = self.audio_metrics._to_dict() + _dict['audio_metrics'] = self.audio_metrics.to_dict() if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings return _dict @@ -7354,7 +7313,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SpeechRecognitionResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SpeechRecognitionResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7404,12 +7363,6 @@ def __init__(self, custom_language_model: bool, def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} - valid_keys = ['custom_language_model', 'speaker_labels'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SupportedFeatures: ' - + ', '.join(bad_keys)) if 'custom_language_model' in _dict: args['custom_language_model'] = _dict.get('custom_language_model') else: @@ -7445,7 +7398,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SupportedFeatures object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SupportedFeatures') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7485,15 +7438,9 @@ def __init__(self, *, warnings: List['TrainingWarning'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingResponse': """Initialize a TrainingResponse object from a json dictionary.""" args = {} - valid_keys = ['warnings'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingResponse: ' - + ', '.join(bad_keys)) if 'warnings' in _dict: args['warnings'] = [ - TrainingWarning._from_dict(x) for x in (_dict.get('warnings')) + TrainingWarning.from_dict(x) for x in _dict.get('warnings') ] return cls(**args) @@ -7506,7 +7453,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x._to_dict() for x in self.warnings] + _dict['warnings'] = [x.to_dict() for x in self.warnings] return _dict def _to_dict(self): @@ -7515,7 +7462,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7560,12 +7507,6 @@ def __init__(self, code: str, message: str) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingWarning': """Initialize a TrainingWarning object from a json dictionary.""" args = {} - valid_keys = ['code', 'message'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingWarning: ' - + ', '.join(bad_keys)) if 'code' in _dict: args['code'] = _dict.get('code') else: @@ -7600,7 +7541,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingWarning object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingWarning') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7612,14 +7553,14 @@ def __ne__(self, other: 'TrainingWarning') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class CodeEnum(Enum): + class CodeEnum(str, Enum): """ An identifier for the type of invalid resources listed in the `description` field. """ - INVALID_AUDIO_FILES = "invalid_audio_files" - INVALID_CORPUS_FILES = "invalid_corpus_files" - INVALID_GRAMMAR_FILES = "invalid_grammar_files" - INVALID_WORDS = "invalid_words" + INVALID_AUDIO_FILES = 'invalid_audio_files' + INVALID_CORPUS_FILES = 'invalid_corpus_files' + INVALID_GRAMMAR_FILES = 'invalid_grammar_files' + INVALID_WORDS = 'invalid_words' class Word(): @@ -7699,14 +7640,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} - valid_keys = [ - 'word', 'sounds_like', 'display_as', 'count', 'source', 'error' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Word: ' + - ', '.join(bad_keys)) if 'word' in _dict: args['word'] = _dict.get('word') else: @@ -7733,9 +7666,7 @@ def from_dict(cls, _dict: Dict) -> 'Word': raise ValueError( 'Required property \'source\' not present in Word JSON') if 'error' in _dict: - args['error'] = [ - WordError._from_dict(x) for x in (_dict.get('error')) - ] + args['error'] = [WordError.from_dict(x) for x in _dict.get('error')] return cls(**args) @classmethod @@ -7757,7 +7688,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source if hasattr(self, 'error') and self.error is not None: - _dict['error'] = [x._to_dict() for x in self.error] + _dict['error'] = [x.to_dict() for x in self.error] return _dict def _to_dict(self): @@ -7766,7 +7697,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Word object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Word') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7803,12 +7734,6 @@ def __init__(self, confidence: float, word: str) -> None: def from_dict(cls, _dict: Dict) -> 'WordAlternativeResult': """Initialize a WordAlternativeResult object from a json dictionary.""" args = {} - valid_keys = ['confidence', 'word'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WordAlternativeResult: ' - + ', '.join(bad_keys)) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') else: @@ -7843,7 +7768,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WordAlternativeResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WordAlternativeResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7888,12 +7813,6 @@ def __init__(self, start_time: float, end_time: float, def from_dict(cls, _dict: Dict) -> 'WordAlternativeResults': """Initialize a WordAlternativeResults object from a json dictionary.""" args = {} - valid_keys = ['start_time', 'end_time', 'alternatives'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WordAlternativeResults: ' - + ', '.join(bad_keys)) if 'start_time' in _dict: args['start_time'] = _dict.get('start_time') else: @@ -7908,8 +7827,8 @@ def from_dict(cls, _dict: Dict) -> 'WordAlternativeResults': ) if 'alternatives' in _dict: args['alternatives'] = [ - WordAlternativeResult._from_dict(x) - for x in (_dict.get('alternatives')) + WordAlternativeResult.from_dict(x) + for x in _dict.get('alternatives') ] else: raise ValueError( @@ -7930,7 +7849,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'end_time') and self.end_time is not None: _dict['end_time'] = self.end_time if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x._to_dict() for x in self.alternatives] + _dict['alternatives'] = [x.to_dict() for x in self.alternatives] return _dict def _to_dict(self): @@ -7939,7 +7858,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WordAlternativeResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WordAlternativeResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7983,12 +7902,6 @@ def __init__(self, element: str) -> None: def from_dict(cls, _dict: Dict) -> 'WordError': """Initialize a WordError object from a json dictionary.""" args = {} - valid_keys = ['element'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WordError: ' - + ', '.join(bad_keys)) if 'element' in _dict: args['element'] = _dict.get('element') else: @@ -8014,7 +7927,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WordError object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WordError') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8050,14 +7963,8 @@ def __init__(self, words: List['Word']) -> None: def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} - valid_keys = ['words'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Words: ' + - ', '.join(bad_keys)) if 'words' in _dict: - args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] + args['words'] = [Word.from_dict(x) for x in _dict.get('words')] else: raise ValueError( 'Required property \'words\' not present in Words JSON') @@ -8072,7 +7979,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x._to_dict() for x in self.words] + _dict['words'] = [x.to_dict() for x in self.words] return _dict def _to_dict(self): @@ -8081,7 +7988,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Words object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Words') -> bool: """Return `true` when self and other are equal, false otherwise.""" diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index 899b84e28..c05763a08 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 -# (C) Copyright IBM Corp. 2018, 2019. +# (C) Copyright IBM Corp. 2018, 2020. # # 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 437230a06..3834a376d 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, @@ -32,15 +34,16 @@ only IPA. """ +from enum import Enum +from typing import Dict, List import json + +from ibm_cloud_sdk_core import BaseService, DetailedResponse from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers -from enum import Enum -from ibm_cloud_sdk_core import BaseService -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 +from ibm_cloud_sdk_core.utils import convert_model + +from .common import get_sdk_headers ############################################################################## # Service @@ -69,15 +72,14 @@ def __init__( authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.configure_service(service_name) ######################### # Voices ######################### - def list_voices(self, **kwargs) -> 'DetailedResponse': + def list_voices(self, **kwargs) -> DetailedResponse: """ List voices. @@ -91,17 +93,19 @@ def list_voices(self, **kwargs) -> 'DetailedResponse': :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Voices` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='list_voices') headers.update(sdk_headers) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/voices' request = self.prepare_request(method='GET', url=url, headers=headers) @@ -112,7 +116,7 @@ def get_voice(self, voice: str, *, customization_id: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get a voice. @@ -132,15 +136,12 @@ def get_voice(self, voice with no customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Voice` object """ if voice is None: raise ValueError('voice 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='V1', operation_id='get_voice') @@ -148,7 +149,14 @@ def get_voice(self, params = {'customization_id': customization_id} - url = '/v1/voices/{0}'.format(*self._encode_path_vars(voice)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['voice'] + path_param_values = self.encode_path_vars(voice) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/voices/{voice}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -167,7 +175,7 @@ def synthesize(self, accept: str = None, voice: str = None, customization_id: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Synthesize audio. @@ -244,15 +252,12 @@ def synthesize(self, customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `BinaryIO` result """ if text is None: raise ValueError('text must be provided') - headers = {'Accept': accept} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='synthesize') @@ -261,6 +266,12 @@ def synthesize(self, params = {'voice': voice, 'customization_id': customization_id} data = {'text': text} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) url = '/v1/synthesize' request = self.prepare_request(method='POST', @@ -282,7 +293,7 @@ def get_pronunciation(self, voice: str = None, format: str = None, customization_id: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get pronunciation. @@ -311,15 +322,12 @@ def get_pronunciation(self, voice with no customization. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Pronunciation` object """ if text is None: raise ValueError('text 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='V1', operation_id='get_pronunciation') @@ -332,6 +340,10 @@ def get_pronunciation(self, 'customization_id': customization_id } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/pronunciation' request = self.prepare_request(method='GET', url=url, @@ -350,7 +362,7 @@ def create_custom_model(self, *, language: str = None, description: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create a custom model. @@ -371,21 +383,25 @@ def create_custom_model(self, Specifying a description is recommended. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `CustomModel` object """ if name is None: raise ValueError('name 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='V1', operation_id='create_custom_model') headers.update(sdk_headers) data = {'name': name, 'language': language, 'description': description} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v1/customizations' request = self.prepare_request(method='POST', @@ -399,7 +415,7 @@ def create_custom_model(self, def list_custom_models(self, *, language: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List custom models. @@ -417,12 +433,10 @@ def list_custom_models(self, parameter to see all custom models that are owned by the requester. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `CustomModels` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='list_custom_models') @@ -430,6 +444,10 @@ def list_custom_models(self, params = {'language': language} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v1/customizations' request = self.prepare_request(method='GET', url=url, @@ -445,7 +463,7 @@ def update_custom_model(self, name: str = None, description: str = None, words: List['Word'] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update a custom model. @@ -489,20 +507,26 @@ def update_custom_model(self, if customization_id is None: raise ValueError('customization_id must be provided') if words is not None: - words = [self._convert_model(x) for x in words] - + words = [convert_model(x) for x in words] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='update_custom_model') headers.update(sdk_headers) data = {'name': name, 'description': description, 'words': words} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/customizations/{0}'.format( - *self._encode_path_vars(customization_id)) + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -512,7 +536,7 @@ def update_custom_model(self, return response def get_custom_model(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get a custom model. @@ -528,29 +552,32 @@ def get_custom_model(self, customization_id: str, service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `CustomModel` object """ if customization_id is None: raise ValueError('customization_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='V1', operation_id='get_custom_model') headers.update(sdk_headers) - url = '/v1/customizations/{0}'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response def delete_custom_model(self, customization_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a custom model. @@ -569,17 +596,19 @@ def delete_custom_model(self, customization_id: str, if customization_id is None: raise ValueError('customization_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='V1', operation_id='delete_custom_model') headers.update(sdk_headers) - url = '/v1/customizations/{0}'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers) @@ -592,7 +621,7 @@ def delete_custom_model(self, customization_id: str, ######################### def add_words(self, customization_id: str, words: List['Word'], - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add custom words. @@ -639,20 +668,27 @@ def add_words(self, customization_id: str, words: List['Word'], raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') - words = [self._convert_model(x) for x in words] - + words = [convert_model(x) for x in words] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='add_words') headers.update(sdk_headers) data = {'words': words} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v1/customizations/{0}/words'.format( - *self._encode_path_vars(customization_id)) + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/words'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -661,7 +697,7 @@ def add_words(self, customization_id: str, words: List['Word'], response = self.send(request) return response - def list_words(self, customization_id: str, **kwargs) -> 'DetailedResponse': + def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: """ List custom words. @@ -676,22 +712,26 @@ def list_words(self, customization_id: str, **kwargs) -> 'DetailedResponse': service that owns the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Words` object """ if customization_id is None: raise ValueError('customization_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='V1', operation_id='list_words') headers.update(sdk_headers) - url = '/v1/customizations/{0}/words'.format( - *self._encode_path_vars(customization_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/words'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) @@ -703,7 +743,7 @@ def add_word(self, translation: str, *, part_of_speech: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add a custom word. @@ -759,19 +799,25 @@ def add_word(self, raise ValueError('word must be provided') if translation is None: raise ValueError('translation 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='V1', operation_id='add_word') headers.update(sdk_headers) data = {'translation': translation, 'part_of_speech': part_of_speech} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v1/customizations/{0}/words/{1}'.format( - *self._encode_path_vars(customization_id, word)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['customization_id', 'word'] + path_param_values = self.encode_path_vars(customization_id, word) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/words/{word}'.format( + **path_param_dict) request = self.prepare_request(method='PUT', url=url, headers=headers, @@ -781,7 +827,7 @@ def add_word(self, return response def get_word(self, customization_id: str, word: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get a custom word. @@ -797,31 +843,35 @@ def get_word(self, customization_id: str, word: str, :param str word: The word that is to be queried from the custom model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Translation` object """ if customization_id is None: raise ValueError('customization_id must be provided') if word is None: raise ValueError('word 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='V1', operation_id='get_word') headers.update(sdk_headers) - url = '/v1/customizations/{0}/words/{1}'.format( - *self._encode_path_vars(customization_id, word)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'word'] + path_param_values = self.encode_path_vars(customization_id, word) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/words/{word}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) response = self.send(request) return response def delete_word(self, customization_id: str, word: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a custom word. @@ -843,17 +893,20 @@ def delete_word(self, customization_id: str, word: str, raise ValueError('customization_id must be provided') if word is None: raise ValueError('word 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='V1', operation_id='delete_word') headers.update(sdk_headers) - url = '/v1/customizations/{0}/words/{1}'.format( - *self._encode_path_vars(customization_id, word)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['customization_id', 'word'] + path_param_values = self.encode_path_vars(customization_id, word) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/words/{word}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers) @@ -865,8 +918,7 @@ def delete_word(self, customization_id: str, word: str, # User data ######################### - def delete_user_data(self, customer_id: str, - **kwargs) -> 'DetailedResponse': + def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: """ Delete labeled data. @@ -893,10 +945,7 @@ def delete_user_data(self, customer_id: str, if customer_id is None: raise ValueError('customer_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='V1', operation_id='delete_user_data') @@ -904,6 +953,9 @@ def delete_user_data(self, customer_id: str, params = {'customer_id': customer_id} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + url = '/v1/user_data' request = self.prepare_request(method='DELETE', url=url, @@ -914,9 +966,12 @@ def delete_user_data(self, customer_id: str, return response -class GetVoiceEnums(object): +class GetVoiceEnums: + """ + Enums for get_voice parameters. + """ - class Voice(Enum): + class Voice(str, Enum): """ The voice for which information is to be returned. """ @@ -966,9 +1021,12 @@ class Voice(Enum): ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' -class SynthesizeEnums(object): +class SynthesizeEnums: + """ + Enums for synthesize parameters. + """ - class Accept(Enum): + class Accept(str, Enum): """ The requested format (MIME type) of the audio. You can use the `Accept` header or the `accept` parameter to specify the audio format. For more information about @@ -989,7 +1047,7 @@ class Accept(Enum): AUDIO_WEBM_CODECS_OPUS = 'audio/webm;codecs=opus' AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' - class Voice(Enum): + class Voice(str, Enum): """ The voice to use for synthesis. """ @@ -1039,9 +1097,12 @@ class Voice(Enum): ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' -class GetPronunciationEnums(object): +class GetPronunciationEnums: + """ + Enums for get_pronunciation parameters. + """ - class Voice(Enum): + class Voice(str, Enum): """ A voice that specifies the language in which the pronunciation is to be returned. All voices for the same language (for example, `en-US`) return the same @@ -1092,7 +1153,7 @@ class Voice(Enum): ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' - class Format(Enum): + class Format(str, Enum): """ The phoneme format in which to return the pronunciation. The Arabic, Chinese, Dutch, and Korean languages support only IPA. Omit the parameter to obtain the @@ -1102,9 +1163,12 @@ class Format(Enum): IPA = 'ipa' -class ListCustomModelsEnums(object): +class ListCustomModelsEnums: + """ + Enums for list_custom_models parameters. + """ - class Language(Enum): + class Language(str, Enum): """ The language for which custom models that are owned by the requesting credentials are to be returned. Omit the parameter to see all custom models that are owned by @@ -1209,15 +1273,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CustomModel': """Initialize a CustomModel object from a json dictionary.""" args = {} - valid_keys = [ - 'customization_id', 'name', 'language', 'owner', 'created', - 'last_modified', 'description', 'words' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CustomModel: ' - + ', '.join(bad_keys)) if 'customization_id' in _dict: args['customization_id'] = _dict.get('customization_id') else: @@ -1237,7 +1292,7 @@ def from_dict(cls, _dict: Dict) -> 'CustomModel': if 'description' in _dict: args['description'] = _dict.get('description') if 'words' in _dict: - args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] + args['words'] = [Word.from_dict(x) for x in _dict.get('words')] return cls(**args) @classmethod @@ -1264,7 +1319,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x._to_dict() for x in self.words] + _dict['words'] = [x.to_dict() for x in self.words] return _dict def _to_dict(self): @@ -1273,7 +1328,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CustomModel object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CustomModel') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1311,15 +1366,9 @@ def __init__(self, customizations: List['CustomModel']) -> None: def from_dict(cls, _dict: Dict) -> 'CustomModels': """Initialize a CustomModels object from a json dictionary.""" args = {} - valid_keys = ['customizations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CustomModels: ' - + ', '.join(bad_keys)) if 'customizations' in _dict: args['customizations'] = [ - CustomModel._from_dict(x) for x in (_dict.get('customizations')) + CustomModel.from_dict(x) for x in _dict.get('customizations') ] else: raise ValueError( @@ -1336,9 +1385,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [ - x._to_dict() for x in self.customizations - ] + _dict['customizations'] = [x.to_dict() for x in self.customizations] return _dict def _to_dict(self): @@ -1347,7 +1394,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CustomModels object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CustomModels') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1383,12 +1430,6 @@ def __init__(self, pronunciation: str) -> None: def from_dict(cls, _dict: Dict) -> 'Pronunciation': """Initialize a Pronunciation object from a json dictionary.""" args = {} - valid_keys = ['pronunciation'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Pronunciation: ' - + ', '.join(bad_keys)) if 'pronunciation' in _dict: args['pronunciation'] = _dict.get('pronunciation') else: @@ -1415,7 +1456,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Pronunciation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Pronunciation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1457,12 +1498,6 @@ def __init__(self, custom_pronunciation: bool, def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} - valid_keys = ['custom_pronunciation', 'voice_transformation'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SupportedFeatures: ' - + ', '.join(bad_keys)) if 'custom_pronunciation' in _dict: args['custom_pronunciation'] = _dict.get('custom_pronunciation') else: @@ -1499,7 +1534,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SupportedFeatures object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SupportedFeatures') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1554,12 +1589,6 @@ def __init__(self, translation: str, *, part_of_speech: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Translation': """Initialize a Translation object from a json dictionary.""" args = {} - valid_keys = ['translation', 'part_of_speech'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Translation: ' - + ', '.join(bad_keys)) if 'translation' in _dict: args['translation'] = _dict.get('translation') else: @@ -1590,7 +1619,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Translation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Translation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1602,7 +1631,7 @@ def __ne__(self, other: 'Translation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class PartOfSpeechEnum(Enum): + class PartOfSpeechEnum(str, Enum): """ **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, @@ -1611,23 +1640,23 @@ class PartOfSpeechEnum(Enum): see [Working with Japanese entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ - DOSI = "Dosi" - FUKU = "Fuku" - GOBI = "Gobi" - HOKA = "Hoka" - JODO = "Jodo" - JOSI = "Josi" - KATO = "Kato" - KEDO = "Kedo" - KEYO = "Keyo" - KIGO = "Kigo" - KOYU = "Koyu" - MESI = "Mesi" - RETA = "Reta" - STBI = "Stbi" - STTO = "Stto" - STZO = "Stzo" - SUJI = "Suji" + DOSI = 'Dosi' + FUKU = 'Fuku' + GOBI = 'Gobi' + HOKA = 'Hoka' + JODO = 'Jodo' + JOSI = 'Josi' + KATO = 'Kato' + KEDO = 'Kedo' + KEYO = 'Keyo' + KIGO = 'Kigo' + KOYU = 'Koyu' + MESI = 'Mesi' + RETA = 'Reta' + STBI = 'Stbi' + STTO = 'Stto' + STZO = 'Stzo' + SUJI = 'Suji' class Voice(): @@ -1692,15 +1721,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Voice': """Initialize a Voice object from a json dictionary.""" args = {} - valid_keys = [ - 'url', 'gender', 'name', 'language', 'description', 'customizable', - 'supported_features', 'customization' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Voice: ' + - ', '.join(bad_keys)) if 'url' in _dict: args['url'] = _dict.get('url') else: @@ -1732,14 +1752,14 @@ def from_dict(cls, _dict: Dict) -> 'Voice': raise ValueError( 'Required property \'customizable\' not present in Voice JSON') if 'supported_features' in _dict: - args['supported_features'] = SupportedFeatures._from_dict( + args['supported_features'] = SupportedFeatures.from_dict( _dict.get('supported_features')) else: raise ValueError( 'Required property \'supported_features\' not present in Voice JSON' ) if 'customization' in _dict: - args['customization'] = CustomModel._from_dict( + args['customization'] = CustomModel.from_dict( _dict.get('customization')) return cls(**args) @@ -1766,9 +1786,9 @@ def to_dict(self) -> Dict: if hasattr( self, 'supported_features') and self.supported_features is not None: - _dict['supported_features'] = self.supported_features._to_dict() + _dict['supported_features'] = self.supported_features.to_dict() if hasattr(self, 'customization') and self.customization is not None: - _dict['customization'] = self.customization._to_dict() + _dict['customization'] = self.customization.to_dict() return _dict def _to_dict(self): @@ -1777,7 +1797,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Voice object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Voice') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1809,16 +1829,8 @@ def __init__(self, voices: List['Voice']) -> None: def from_dict(cls, _dict: Dict) -> 'Voices': """Initialize a Voices object from a json dictionary.""" args = {} - valid_keys = ['voices'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Voices: ' + - ', '.join(bad_keys)) if 'voices' in _dict: - args['voices'] = [ - Voice._from_dict(x) for x in (_dict.get('voices')) - ] + args['voices'] = [Voice.from_dict(x) for x in _dict.get('voices')] else: raise ValueError( 'Required property \'voices\' not present in Voices JSON') @@ -1833,7 +1845,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'voices') and self.voices is not None: - _dict['voices'] = [x._to_dict() for x in self.voices] + _dict['voices'] = [x.to_dict() for x in self.voices] return _dict def _to_dict(self): @@ -1842,7 +1854,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Voices object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Voices') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1907,12 +1919,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} - valid_keys = ['word', 'translation', 'part_of_speech'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Word: ' + - ', '.join(bad_keys)) if 'word' in _dict: args['word'] = _dict.get('word') else: @@ -1949,7 +1955,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Word object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Word') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1961,7 +1967,7 @@ def __ne__(self, other: 'Word') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class PartOfSpeechEnum(Enum): + class PartOfSpeechEnum(str, Enum): """ **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, @@ -1970,23 +1976,23 @@ class PartOfSpeechEnum(Enum): see [Working with Japanese entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ - DOSI = "Dosi" - FUKU = "Fuku" - GOBI = "Gobi" - HOKA = "Hoka" - JODO = "Jodo" - JOSI = "Josi" - KATO = "Kato" - KEDO = "Kedo" - KEYO = "Keyo" - KIGO = "Kigo" - KOYU = "Koyu" - MESI = "Mesi" - RETA = "Reta" - STBI = "Stbi" - STTO = "Stto" - STZO = "Stzo" - SUJI = "Suji" + DOSI = 'Dosi' + FUKU = 'Fuku' + GOBI = 'Gobi' + HOKA = 'Hoka' + JODO = 'Jodo' + JOSI = 'Josi' + KATO = 'Kato' + KEDO = 'Kedo' + KEYO = 'Keyo' + KIGO = 'Kigo' + KOYU = 'Koyu' + MESI = 'Mesi' + RETA = 'Reta' + STBI = 'Stbi' + STTO = 'Stto' + STZO = 'Stzo' + SUJI = 'Suji' class Words(): @@ -2024,14 +2030,8 @@ def __init__(self, words: List['Word']) -> None: def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} - valid_keys = ['words'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Words: ' + - ', '.join(bad_keys)) if 'words' in _dict: - args['words'] = [Word._from_dict(x) for x in (_dict.get('words'))] + args['words'] = [Word.from_dict(x) for x in _dict.get('words')] else: raise ValueError( 'Required property \'words\' not present in Words JSON') @@ -2046,7 +2046,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x._to_dict() for x in self.words] + _dict['words'] = [x.to_dict() for x in self.words] return _dict def _to_dict(self): @@ -2055,7 +2055,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Words object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Words') -> bool: """Return `true` when self and other are equal, false otherwise.""" diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index 2753a87bd..c1f45c4a2 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ The IBM Watson™ Tone Analyzer service uses linguistic analysis to detect emotional and language tones in written text. The service can analyze tone at both the document and @@ -25,15 +27,16 @@ data from requests and responses. """ +from enum import Enum +from typing import Dict, List, TextIO, Union import json + +from ibm_cloud_sdk_core import BaseService, DetailedResponse from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers -from enum import Enum -from ibm_cloud_sdk_core import BaseService -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 +from ibm_cloud_sdk_core.utils import convert_list, convert_model + +from .common import get_sdk_headers ############################################################################## # Service @@ -55,27 +58,21 @@ def __init__( """ Construct a new client for the Tone Analyzer service. - :param str version: The API version date to use with the service, in - "YYYY-MM-DD" format. Whenever the API is changed in a backwards - incompatible way, a new minor version of the API is released. - The service uses the API version for the date you specify, or - the most recent version before that date. Note that you should - not programmatically specify the current date at runtime, in - case the API has been updated since your application's release. - Instead, specify a version date that is compatible with your - application, and don't change it until your application is - ready for a later version. + :param str version: Release date of the version of the API you want to use. + Specify dates in YYYY-MM-DD format. The current version is `2017-09-21`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + if version is None: + raise ValueError('version must be provided') + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.version = version self.configure_service(service_name) @@ -84,14 +81,14 @@ def __init__( ######################### def tone(self, - tone_input: object, + tone_input: Union['ToneInput', str, TextIO], *, content_type: str = None, sentences: bool = None, tones: List[str] = None, content_language: str = None, accept_language: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Analyze general tone. @@ -145,21 +142,19 @@ def tone(self, use different languages for **Content-Language** and **Accept-Language**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ToneAnalysis` object """ if tone_input is None: raise ValueError('tone_input must be provided') if isinstance(tone_input, ToneInput): - tone_input = self._convert_model(tone_input) - + tone_input = convert_model(tone_input) + content_type = content_type or 'application/json' headers = { 'Content-Type': content_type, 'Content-Language': content_language, 'Accept-Language': accept_language } - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='tone') @@ -168,14 +163,20 @@ def tone(self, params = { 'version': self.version, 'sentences': sentences, - 'tones': self._convert_list(tones) + 'tones': convert_list(tones) } - if content_type == 'application/json' and isinstance(tone_input, dict): + if isinstance(tone_input, dict): data = json.dumps(tone_input) + if content_type is None: + headers['Content-Type'] = 'application/json' else: data = tone_input + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v3/tone' request = self.prepare_request(method='POST', url=url, @@ -191,7 +192,7 @@ def tone_chat(self, *, content_language: str = None, accept_language: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Analyze customer-engagement tone. @@ -224,19 +225,16 @@ def tone_chat(self, use different languages for **Content-Language** and **Accept-Language**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `UtteranceAnalyses` object """ if utterances is None: raise ValueError('utterances must be provided') - utterances = [self._convert_model(x) for x in utterances] - + utterances = [convert_model(x) for x in utterances] headers = { 'Content-Language': content_language, 'Accept-Language': accept_language } - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='tone_chat') @@ -245,6 +243,13 @@ def tone_chat(self, params = {'version': self.version} data = {'utterances': utterances} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v3/tone_chat' request = self.prepare_request(method='POST', @@ -257,9 +262,12 @@ def tone_chat(self, return response -class ToneEnums(object): +class ToneEnums: + """ + Enums for tone parameters. + """ - class ContentType(Enum): + class ContentType(str, Enum): """ The type of the input. A character encoding can be specified by including a `charset` parameter. For example, 'text/plain;charset=utf-8'. @@ -268,7 +276,7 @@ class ContentType(Enum): TEXT_PLAIN = 'text/plain' TEXT_HTML = 'text/html' - class Tones(Enum): + class Tones(str, Enum): """ **`2017-09-21`:** Deprecated. The service continues to accept the parameter for backward-compatibility, but the parameter no longer affects the response. @@ -281,7 +289,7 @@ class Tones(Enum): LANGUAGE = 'language' SOCIAL = 'social' - class ContentLanguage(Enum): + class ContentLanguage(str, Enum): """ The language of the input text for the request: English or French. Regional variants are treated as their parent language; for example, `en-US` is interpreted @@ -294,7 +302,7 @@ class ContentLanguage(Enum): EN = 'en' FR = 'fr' - class AcceptLanguage(Enum): + class AcceptLanguage(str, Enum): """ The desired language of the response. For two-character arguments, regional variants are treated as their parent language; for example, `en-US` is interpreted @@ -314,9 +322,12 @@ class AcceptLanguage(Enum): ZH_TW = 'zh-tw' -class ToneChatEnums(object): +class ToneChatEnums: + """ + Enums for tone_chat parameters. + """ - class ContentLanguage(Enum): + class ContentLanguage(str, Enum): """ The language of the input text for the request: English or French. Regional variants are treated as their parent language; for example, `en-US` is interpreted @@ -329,7 +340,7 @@ class ContentLanguage(Enum): EN = 'en' FR = 'fr' - class AcceptLanguage(Enum): + class AcceptLanguage(str, Enum): """ The desired language of the response. For two-character arguments, regional variants are treated as their parent language; for example, `en-US` is interpreted @@ -406,20 +417,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentAnalysis': """Initialize a DocumentAnalysis object from a json dictionary.""" args = {} - valid_keys = ['tones', 'tone_categories', 'warning'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentAnalysis: ' - + ', '.join(bad_keys)) if 'tones' in _dict: - args['tones'] = [ - ToneScore._from_dict(x) for x in (_dict.get('tones')) - ] + args['tones'] = [ToneScore.from_dict(x) for x in _dict.get('tones')] if 'tone_categories' in _dict: args['tone_categories'] = [ - ToneCategory._from_dict(x) - for x in (_dict.get('tone_categories')) + ToneCategory.from_dict(x) for x in _dict.get('tone_categories') ] if 'warning' in _dict: args['warning'] = _dict.get('warning') @@ -434,11 +436,11 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tones') and self.tones is not None: - _dict['tones'] = [x._to_dict() for x in self.tones] + _dict['tones'] = [x.to_dict() for x in self.tones] if hasattr(self, 'tone_categories') and self.tone_categories is not None: _dict['tone_categories'] = [ - x._to_dict() for x in self.tone_categories + x.to_dict() for x in self.tone_categories ] if hasattr(self, 'warning') and self.warning is not None: _dict['warning'] = self.warning @@ -450,7 +452,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocumentAnalysis object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocumentAnalysis') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -530,15 +532,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SentenceAnalysis': """Initialize a SentenceAnalysis object from a json dictionary.""" args = {} - valid_keys = [ - 'sentence_id', 'text', 'tones', 'tone_categories', 'input_from', - 'input_to' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class SentenceAnalysis: ' - + ', '.join(bad_keys)) if 'sentence_id' in _dict: args['sentence_id'] = _dict.get('sentence_id') else: @@ -552,13 +545,10 @@ def from_dict(cls, _dict: Dict) -> 'SentenceAnalysis': 'Required property \'text\' not present in SentenceAnalysis JSON' ) if 'tones' in _dict: - args['tones'] = [ - ToneScore._from_dict(x) for x in (_dict.get('tones')) - ] + args['tones'] = [ToneScore.from_dict(x) for x in _dict.get('tones')] if 'tone_categories' in _dict: args['tone_categories'] = [ - ToneCategory._from_dict(x) - for x in (_dict.get('tone_categories')) + ToneCategory.from_dict(x) for x in _dict.get('tone_categories') ] if 'input_from' in _dict: args['input_from'] = _dict.get('input_from') @@ -579,11 +569,11 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'tones') and self.tones is not None: - _dict['tones'] = [x._to_dict() for x in self.tones] + _dict['tones'] = [x.to_dict() for x in self.tones] if hasattr(self, 'tone_categories') and self.tone_categories is not None: _dict['tone_categories'] = [ - x._to_dict() for x in self.tone_categories + x.to_dict() for x in self.tone_categories ] if hasattr(self, 'input_from') and self.input_from is not None: _dict['input_from'] = self.input_from @@ -597,7 +587,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this SentenceAnalysis object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'SentenceAnalysis') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -645,14 +635,8 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ToneAnalysis': """Initialize a ToneAnalysis object from a json dictionary.""" args = {} - valid_keys = ['document_tone', 'sentences_tone'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ToneAnalysis: ' - + ', '.join(bad_keys)) if 'document_tone' in _dict: - args['document_tone'] = DocumentAnalysis._from_dict( + args['document_tone'] = DocumentAnalysis.from_dict( _dict.get('document_tone')) else: raise ValueError( @@ -660,8 +644,8 @@ def from_dict(cls, _dict: Dict) -> 'ToneAnalysis': ) if 'sentences_tone' in _dict: args['sentences_tone'] = [ - SentenceAnalysis._from_dict(x) - for x in (_dict.get('sentences_tone')) + SentenceAnalysis.from_dict(x) + for x in _dict.get('sentences_tone') ] return cls(**args) @@ -674,11 +658,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document_tone') and self.document_tone is not None: - _dict['document_tone'] = self.document_tone._to_dict() + _dict['document_tone'] = self.document_tone.to_dict() if hasattr(self, 'sentences_tone') and self.sentences_tone is not None: - _dict['sentences_tone'] = [ - x._to_dict() for x in self.sentences_tone - ] + _dict['sentences_tone'] = [x.to_dict() for x in self.sentences_tone] return _dict def _to_dict(self): @@ -687,7 +669,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ToneAnalysis object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ToneAnalysis') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -732,16 +714,8 @@ def __init__(self, tones: List['ToneScore'], category_id: str, def from_dict(cls, _dict: Dict) -> 'ToneCategory': """Initialize a ToneCategory object from a json dictionary.""" args = {} - valid_keys = ['tones', 'category_id', 'category_name'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ToneCategory: ' - + ', '.join(bad_keys)) if 'tones' in _dict: - args['tones'] = [ - ToneScore._from_dict(x) for x in (_dict.get('tones')) - ] + args['tones'] = [ToneScore.from_dict(x) for x in _dict.get('tones')] else: raise ValueError( 'Required property \'tones\' not present in ToneCategory JSON') @@ -768,7 +742,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tones') and self.tones is not None: - _dict['tones'] = [x._to_dict() for x in self.tones] + _dict['tones'] = [x.to_dict() for x in self.tones] if hasattr(self, 'category_id') and self.category_id is not None: _dict['category_id'] = self.category_id if hasattr(self, 'category_name') and self.category_name is not None: @@ -781,7 +755,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ToneCategory object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ToneCategory') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -827,12 +801,6 @@ def __init__(self, score: float, tone_id: str, tone_name: str) -> None: def from_dict(cls, _dict: Dict) -> 'ToneChatScore': """Initialize a ToneChatScore object from a json dictionary.""" args = {} - valid_keys = ['score', 'tone_id', 'tone_name'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ToneChatScore: ' - + ', '.join(bad_keys)) if 'score' in _dict: args['score'] = _dict.get('score') else: @@ -874,7 +842,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ToneChatScore object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ToneChatScore') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -886,18 +854,18 @@ def __ne__(self, other: 'ToneChatScore') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ToneIdEnum(Enum): + class ToneIdEnum(str, Enum): """ The unique, non-localized identifier of the tone for the results. The service returns results only for tones whose scores meet a minimum threshold of 0.5. """ - EXCITED = "excited" - FRUSTRATED = "frustrated" - IMPOLITE = "impolite" - POLITE = "polite" - SAD = "sad" - SATISFIED = "satisfied" - SYMPATHETIC = "sympathetic" + EXCITED = 'excited' + FRUSTRATED = 'frustrated' + IMPOLITE = 'impolite' + POLITE = 'polite' + SAD = 'sad' + SATISFIED = 'satisfied' + SYMPATHETIC = 'sympathetic' class ToneInput(): @@ -919,12 +887,6 @@ def __init__(self, text: str) -> None: def from_dict(cls, _dict: Dict) -> 'ToneInput': """Initialize a ToneInput object from a json dictionary.""" args = {} - valid_keys = ['text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ToneInput: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -950,7 +912,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ToneInput object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ToneInput') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1024,12 +986,6 @@ def __init__(self, score: float, tone_id: str, tone_name: str) -> None: def from_dict(cls, _dict: Dict) -> 'ToneScore': """Initialize a ToneScore object from a json dictionary.""" args = {} - valid_keys = ['score', 'tone_id', 'tone_name'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ToneScore: ' - + ', '.join(bad_keys)) if 'score' in _dict: args['score'] = _dict.get('score') else: @@ -1069,7 +1025,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ToneScore object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ToneScore') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1108,12 +1064,6 @@ def __init__(self, text: str, *, user: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Utterance': """Initialize a Utterance object from a json dictionary.""" args = {} - valid_keys = ['text', 'user'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Utterance: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') else: @@ -1143,7 +1093,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Utterance object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Utterance') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1188,16 +1138,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'UtteranceAnalyses': """Initialize a UtteranceAnalyses object from a json dictionary.""" args = {} - valid_keys = ['utterances_tone', 'warning'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class UtteranceAnalyses: ' - + ', '.join(bad_keys)) if 'utterances_tone' in _dict: args['utterances_tone'] = [ - UtteranceAnalysis._from_dict(x) - for x in (_dict.get('utterances_tone')) + UtteranceAnalysis.from_dict(x) + for x in _dict.get('utterances_tone') ] else: raise ValueError( @@ -1218,7 +1162,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'utterances_tone') and self.utterances_tone is not None: _dict['utterances_tone'] = [ - x._to_dict() for x in self.utterances_tone + x.to_dict() for x in self.utterances_tone ] if hasattr(self, 'warning') and self.warning is not None: _dict['warning'] = self.warning @@ -1230,7 +1174,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this UtteranceAnalyses object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'UtteranceAnalyses') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1290,12 +1234,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'UtteranceAnalysis': """Initialize a UtteranceAnalysis object from a json dictionary.""" args = {} - valid_keys = ['utterance_id', 'utterance_text', 'tones', 'error'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class UtteranceAnalysis: ' - + ', '.join(bad_keys)) if 'utterance_id' in _dict: args['utterance_id'] = _dict.get('utterance_id') else: @@ -1310,7 +1248,7 @@ def from_dict(cls, _dict: Dict) -> 'UtteranceAnalysis': ) if 'tones' in _dict: args['tones'] = [ - ToneChatScore._from_dict(x) for x in (_dict.get('tones')) + ToneChatScore.from_dict(x) for x in _dict.get('tones') ] else: raise ValueError( @@ -1333,7 +1271,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'utterance_text') and self.utterance_text is not None: _dict['utterance_text'] = self.utterance_text if hasattr(self, 'tones') and self.tones is not None: - _dict['tones'] = [x._to_dict() for x in self.tones] + _dict['tones'] = [x.to_dict() for x in self.tones] if hasattr(self, 'error') and self.error is not None: _dict['error'] = self.error return _dict @@ -1344,7 +1282,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this UtteranceAnalysis object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'UtteranceAnalysis') -> bool: """Return `true` when self and other are equal, false otherwise.""" diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index e996b39e3..4a5358a45 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ IBM Watson™ Visual Recognition is discontinued. Existing instances are supported until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance @@ -23,19 +25,18 @@ classifier to identify subjects that suit your needs. """ -import json -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers 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.get_authenticator import get_authenticator_from_environment from os.path import basename -from typing import BinaryIO -from typing import Dict -from typing import List +from typing import BinaryIO, Dict, List +import json + +from ibm_cloud_sdk_core import BaseService, DetailedResponse +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime + +from .common import get_sdk_headers ############################################################################## # Service @@ -57,28 +58,21 @@ def __init__( """ Construct a new client for the Visual Recognition service. - :param str version: The API version date to use with the service, in - "YYYY-MM-DD" format. Whenever the API is changed in a backwards - incompatible way, a new minor version of the API is released. - The service uses the API version for the date you specify, or - the most recent version before that date. Note that you should - not programmatically specify the current date at runtime, in - case the API has been updated since your application's release. - Instead, specify a version date that is compatible with your - application, and don't change it until your application is - ready for a later version. + :param str version: Release date of the API version you want to use. + Specify dates in YYYY-MM-DD format. The current version is `2018-03-19`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - print('warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#visual-recognition-deprecation.') + if version is None: + raise ValueError('version must be provided') + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.version = version self.configure_service(service_name) @@ -93,16 +87,16 @@ def classify(self, images_file_content_type: str = None, url: str = None, threshold: float = None, - owners: str = None, - classifier_ids: str = None, + owners: List[str] = None, + classifier_ids: List[str] = None, accept_language: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Classify images. Classify images with built-in or custom classifiers. - :param TextIO images_file: (optional) An image file (.gif, .jpg, .png, + :param BinaryIO images_file: (optional) An image file (.gif, .jpg, .png, .tif) or .zip file with images. Maximum image size is 10 MB. Include no more than 20 images and limit the .zip file to 100 MB. Encode the image and .zip file names in UTF-8 if they contain non-ASCII characters. The service @@ -142,12 +136,10 @@ def classify(self, response. See the response for details. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ClassifiedImages` object """ headers = {'Accept-Language': accept_language} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='classify') @@ -165,18 +157,20 @@ def classify(self, images_file_content_type or 'application/octet-stream'))) if url: - url = str(url) form_data.append(('url', (None, url, 'text/plain'))) if threshold: - threshold = str(threshold) - form_data.append(('threshold', (None, threshold, 'text/plain'))) + form_data.append( + ('threshold', (None, str(threshold), 'text/plain'))) if owners: - owners = self._convert_list(owners) - form_data.append(('owners', (None, owners, 'text/plain'))) + for item in owners: + form_data.append(('owners', (None, item, 'text/plain'))) if classifier_ids: - classifier_ids = self._convert_list(classifier_ids) - form_data.append( - ('classifier_ids', (None, classifier_ids, 'text/plain'))) + for item in classifier_ids: + form_data.append(('classifier_ids', (None, item, 'text/plain'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v3/classify' request = self.prepare_request(method='POST', @@ -194,11 +188,11 @@ def classify(self, def create_classifier(self, name: str, - positive_examples: BinaryIO, + positive_examples: Dict[str, BinaryIO], *, negative_examples: BinaryIO = None, negative_examples_filename: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create a classifier. @@ -229,7 +223,7 @@ def create_classifier(self, image resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 MB per .zip file. Encode special characters in the file name in UTF-8. - :param TextIO negative_examples: (optional) A .zip file of images that do + :param BinaryIO negative_examples: (optional) A .zip file of images that do not depict the visual subject of any of the classes of the new classifier. Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. @@ -237,17 +231,14 @@ def create_classifier(self, negative_examples. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Classifier` object """ if name is None: raise ValueError('name must be provided') if not positive_examples: raise ValueError('positive_examples 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='V3', operation_id='create_classifier') @@ -256,15 +247,15 @@ def create_classifier(self, params = {'version': self.version} form_data = [] - name = str(name) form_data.append(('name', (None, name, 'text/plain'))) for key in positive_examples.keys(): part_name = '%s_positive_examples' % (key) value = positive_examples[key] + filename = None if hasattr(value, 'name'): filename = basename(value.name) - form_data.append( - (part_name, (filename, value, 'application/octet-stream'))) + form_data.append( + (part_name, (filename, value, 'application/octet-stream'))) if negative_examples: if not negative_examples_filename and hasattr( negative_examples, 'name'): @@ -275,6 +266,10 @@ def create_classifier(self, (negative_examples_filename, negative_examples, 'application/octet-stream'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v3/classifiers' request = self.prepare_request(method='POST', url=url, @@ -288,7 +283,7 @@ def create_classifier(self, def list_classifiers(self, *, verbose: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Retrieve a list of classifiers. @@ -296,12 +291,10 @@ def list_classifiers(self, classifiers. Omit this parameter to return a brief list of classifiers. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Classifiers` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='list_classifiers') @@ -309,6 +302,10 @@ def list_classifiers(self, params = {'version': self.version, 'verbose': verbose} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v3/classifiers' request = self.prepare_request(method='GET', url=url, @@ -318,8 +315,7 @@ def list_classifiers(self, response = self.send(request) return response - def get_classifier(self, classifier_id: str, - **kwargs) -> 'DetailedResponse': + def get_classifier(self, classifier_id: str, **kwargs) -> DetailedResponse: """ Retrieve classifier details. @@ -328,15 +324,12 @@ def get_classifier(self, classifier_id: str, :param str classifier_id: The ID of the classifier. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Classifier` object """ if classifier_id is None: raise ValueError('classifier_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='V3', operation_id='get_classifier') @@ -344,8 +337,14 @@ def get_classifier(self, classifier_id: str, params = {'version': self.version} - url = '/v3/classifiers/{0}'.format( - *self._encode_path_vars(classifier_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['classifier_id'] + path_param_values = self.encode_path_vars(classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v3/classifiers/{classifier_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -357,10 +356,10 @@ def get_classifier(self, classifier_id: str, def update_classifier(self, classifier_id: str, *, - positive_examples: BinaryIO = {}, + positive_examples: Dict[str, BinaryIO] = {}, negative_examples: BinaryIO = None, negative_examples_filename: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update a classifier. @@ -395,7 +394,7 @@ def update_classifier(self, image resolution is 32X32 pixels. The maximum number of images is 10,000 images or 100 MB per .zip file. Encode special characters in the file name in UTF-8. - :param TextIO negative_examples: (optional) A .zip file of images that do + :param BinaryIO negative_examples: (optional) A .zip file of images that do not depict the visual subject of any of the classes of the new classifier. Must contain a minimum of 10 images. Encode special characters in the file name in UTF-8. @@ -403,15 +402,12 @@ def update_classifier(self, negative_examples. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Classifier` object """ if classifier_id is None: raise ValueError('classifier_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='V3', operation_id='update_classifier') @@ -423,10 +419,11 @@ def update_classifier(self, for key in positive_examples.keys(): part_name = '%s_positive_examples' % (key) value = positive_examples[key] + filename = None if hasattr(value, 'name'): filename = basename(value.name) - form_data.append( - (part_name, (filename, value, 'application/octet-stream'))) + form_data.append( + (part_name, (filename, value, 'application/octet-stream'))) if negative_examples: if not negative_examples_filename and hasattr( negative_examples, 'name'): @@ -437,8 +434,14 @@ def update_classifier(self, (negative_examples_filename, negative_examples, 'application/octet-stream'))) - url = '/v3/classifiers/{0}'.format( - *self._encode_path_vars(classifier_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['classifier_id'] + path_param_values = self.encode_path_vars(classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v3/classifiers/{classifier_id}'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -449,7 +452,7 @@ def update_classifier(self, return response def delete_classifier(self, classifier_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a classifier. @@ -461,10 +464,7 @@ def delete_classifier(self, classifier_id: str, if classifier_id is None: raise ValueError('classifier_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='V3', operation_id='delete_classifier') @@ -472,8 +472,14 @@ def delete_classifier(self, classifier_id: str, params = {'version': self.version} - url = '/v3/classifiers/{0}'.format( - *self._encode_path_vars(classifier_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['classifier_id'] + path_param_values = self.encode_path_vars(classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v3/classifiers/{classifier_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -487,7 +493,7 @@ def delete_classifier(self, classifier_id: str, ######################### def get_core_ml_model(self, classifier_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Retrieve a Core ML model of a classifier. @@ -497,15 +503,12 @@ def get_core_ml_model(self, classifier_id: str, :param str classifier_id: The ID of the classifier. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `BinaryIO` result """ if classifier_id is None: raise ValueError('classifier_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='V3', operation_id='get_core_ml_model') @@ -513,8 +516,15 @@ def get_core_ml_model(self, classifier_id: str, params = {'version': self.version} - url = '/v3/classifiers/{0}/core_ml_model'.format( - *self._encode_path_vars(classifier_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/octet-stream' + + path_param_keys = ['classifier_id'] + path_param_values = self.encode_path_vars(classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v3/classifiers/{classifier_id}/core_ml_model'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -527,8 +537,7 @@ def get_core_ml_model(self, classifier_id: str, # User data ######################### - def delete_user_data(self, customer_id: str, - **kwargs) -> 'DetailedResponse': + def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: """ Delete labeled data. @@ -548,10 +557,7 @@ def delete_user_data(self, customer_id: str, if customer_id is None: raise ValueError('customer_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='V3', operation_id='delete_user_data') @@ -559,6 +565,10 @@ def delete_user_data(self, customer_id: str, params = {'version': self.version, 'customer_id': customer_id} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v3/user_data' request = self.prepare_request(method='DELETE', url=url, @@ -569,9 +579,12 @@ def delete_user_data(self, customer_id: str, return response -class ClassifyEnums(object): +class ClassifyEnums: + """ + Enums for classify parameters. + """ - class AcceptLanguage(Enum): + class AcceptLanguage(str, Enum): """ The desired language of parts of the response. See the response for details. """ @@ -612,12 +625,6 @@ def __init__(self, class_: str) -> None: def from_dict(cls, _dict: Dict) -> 'Class': """Initialize a Class object from a json dictionary.""" args = {} - valid_keys = ['class_', 'class'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Class: ' + - ', '.join(bad_keys)) if 'class' in _dict: args['class_'] = _dict.get('class') else: @@ -643,7 +650,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Class object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Class') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -705,12 +712,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassResult': """Initialize a ClassResult object from a json dictionary.""" args = {} - valid_keys = ['class_', 'class', 'score', 'type_hierarchy'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ClassResult: ' - + ', '.join(bad_keys)) if 'class' in _dict: args['class_'] = _dict.get('class') else: @@ -747,7 +748,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ClassResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ClassResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -807,14 +808,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassifiedImage': """Initialize a ClassifiedImage object from a json dictionary.""" args = {} - valid_keys = [ - 'source_url', 'resolved_url', 'image', 'error', 'classifiers' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ClassifiedImage: ' - + ', '.join(bad_keys)) if 'source_url' in _dict: args['source_url'] = _dict.get('source_url') if 'resolved_url' in _dict: @@ -822,11 +815,10 @@ def from_dict(cls, _dict: Dict) -> 'ClassifiedImage': if 'image' in _dict: args['image'] = _dict.get('image') if 'error' in _dict: - args['error'] = ErrorInfo._from_dict(_dict.get('error')) + args['error'] = ErrorInfo.from_dict(_dict.get('error')) if 'classifiers' in _dict: args['classifiers'] = [ - ClassifierResult._from_dict(x) - for x in (_dict.get('classifiers')) + ClassifierResult.from_dict(x) for x in _dict.get('classifiers') ] else: raise ValueError( @@ -849,9 +841,9 @@ def to_dict(self) -> Dict: if hasattr(self, 'image') and self.image is not None: _dict['image'] = self.image if hasattr(self, 'error') and self.error is not None: - _dict['error'] = self.error._to_dict() + _dict['error'] = self.error.to_dict() if hasattr(self, 'classifiers') and self.classifiers is not None: - _dict['classifiers'] = [x._to_dict() for x in self.classifiers] + _dict['classifiers'] = [x.to_dict() for x in self.classifiers] return _dict def _to_dict(self): @@ -860,7 +852,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ClassifiedImage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ClassifiedImage') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -916,21 +908,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassifiedImages': """Initialize a ClassifiedImages object from a json dictionary.""" args = {} - valid_keys = [ - 'custom_classes', 'images_processed', 'images', 'warnings' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ClassifiedImages: ' - + ', '.join(bad_keys)) if 'custom_classes' in _dict: args['custom_classes'] = _dict.get('custom_classes') if 'images_processed' in _dict: args['images_processed'] = _dict.get('images_processed') if 'images' in _dict: args['images'] = [ - ClassifiedImage._from_dict(x) for x in (_dict.get('images')) + ClassifiedImage.from_dict(x) for x in _dict.get('images') ] else: raise ValueError( @@ -938,7 +922,7 @@ def from_dict(cls, _dict: Dict) -> 'ClassifiedImages': ) if 'warnings' in _dict: args['warnings'] = [ - WarningInfo._from_dict(x) for x in (_dict.get('warnings')) + WarningInfo.from_dict(x) for x in _dict.get('warnings') ] return cls(**args) @@ -956,9 +940,9 @@ def to_dict(self) -> Dict: 'images_processed') and self.images_processed is not None: _dict['images_processed'] = self.images_processed if hasattr(self, 'images') and self.images is not None: - _dict['images'] = [x._to_dict() for x in self.images] + _dict['images'] = [x.to_dict() for x in self.images] if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x._to_dict() for x in self.warnings] + _dict['warnings'] = [x.to_dict() for x in self.warnings] return _dict def _to_dict(self): @@ -967,7 +951,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ClassifiedImages object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ClassifiedImages') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1054,15 +1038,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Classifier': """Initialize a Classifier object from a json dictionary.""" args = {} - valid_keys = [ - 'classifier_id', 'name', 'owner', 'status', 'core_ml_enabled', - 'explanation', 'created', 'classes', 'retrained', 'updated' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Classifier: ' - + ', '.join(bad_keys)) if 'classifier_id' in _dict: args['classifier_id'] = _dict.get('classifier_id') else: @@ -1085,9 +1060,7 @@ def from_dict(cls, _dict: Dict) -> 'Classifier': if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'classes' in _dict: - args['classes'] = [ - Class._from_dict(x) for x in (_dict.get('classes')) - ] + args['classes'] = [Class.from_dict(x) for x in _dict.get('classes')] if 'retrained' in _dict: args['retrained'] = string_to_datetime(_dict.get('retrained')) if 'updated' in _dict: @@ -1118,7 +1091,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'classes') and self.classes is not None: - _dict['classes'] = [x._to_dict() for x in self.classes] + _dict['classes'] = [x.to_dict() for x in self.classes] if hasattr(self, 'retrained') and self.retrained is not None: _dict['retrained'] = datetime_to_string(self.retrained) if hasattr(self, 'updated') and self.updated is not None: @@ -1131,7 +1104,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Classifier object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Classifier') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1143,14 +1116,14 @@ def __ne__(self, other: 'Classifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Training status of classifier. """ - READY = "ready" - TRAINING = "training" - RETRAINING = "retraining" - FAILED = "failed" + READY = 'ready' + TRAINING = 'training' + RETRAINING = 'retraining' + FAILED = 'failed' class ClassifierResult(): @@ -1179,12 +1152,6 @@ def __init__(self, name: str, classifier_id: str, def from_dict(cls, _dict: Dict) -> 'ClassifierResult': """Initialize a ClassifierResult object from a json dictionary.""" args = {} - valid_keys = ['name', 'classifier_id', 'classes'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ClassifierResult: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') else: @@ -1199,7 +1166,7 @@ def from_dict(cls, _dict: Dict) -> 'ClassifierResult': ) if 'classes' in _dict: args['classes'] = [ - ClassResult._from_dict(x) for x in (_dict.get('classes')) + ClassResult.from_dict(x) for x in _dict.get('classes') ] else: raise ValueError( @@ -1220,7 +1187,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'classifier_id') and self.classifier_id is not None: _dict['classifier_id'] = self.classifier_id if hasattr(self, 'classes') and self.classes is not None: - _dict['classes'] = [x._to_dict() for x in self.classes] + _dict['classes'] = [x.to_dict() for x in self.classes] return _dict def _to_dict(self): @@ -1229,7 +1196,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ClassifierResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ClassifierResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1261,15 +1228,9 @@ def __init__(self, classifiers: List['Classifier']) -> None: def from_dict(cls, _dict: Dict) -> 'Classifiers': """Initialize a Classifiers object from a json dictionary.""" args = {} - valid_keys = ['classifiers'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Classifiers: ' - + ', '.join(bad_keys)) if 'classifiers' in _dict: args['classifiers'] = [ - Classifier._from_dict(x) for x in (_dict.get('classifiers')) + Classifier.from_dict(x) for x in _dict.get('classifiers') ] else: raise ValueError( @@ -1286,7 +1247,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'classifiers') and self.classifiers is not None: - _dict['classifiers'] = [x._to_dict() for x in self.classifiers] + _dict['classifiers'] = [x.to_dict() for x in self.classifiers] return _dict def _to_dict(self): @@ -1295,7 +1256,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Classifiers object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Classifiers') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1336,12 +1297,6 @@ def __init__(self, code: int, description: str, error_id: str) -> None: def from_dict(cls, _dict: Dict) -> 'ErrorInfo': """Initialize a ErrorInfo object from a json dictionary.""" args = {} - valid_keys = ['code', 'description', 'error_id'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ErrorInfo: ' - + ', '.join(bad_keys)) if 'code' in _dict: args['code'] = _dict.get('code') else: @@ -1382,7 +1337,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ErrorInfo object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ErrorInfo') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1417,12 +1372,6 @@ def __init__(self, warning_id: str, description: str) -> None: def from_dict(cls, _dict: Dict) -> 'WarningInfo': """Initialize a WarningInfo object from a json dictionary.""" args = {} - valid_keys = ['warning_id', 'description'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class WarningInfo: ' - + ', '.join(bad_keys)) if 'warning_id' in _dict: args['warning_id'] = _dict.get('warning_id') else: @@ -1457,7 +1406,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this WarningInfo object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'WarningInfo') -> bool: """Return `true` when self and other are equal, false otherwise.""" diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 1354af1a4..dc459dd54 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 """ IBM Watson™ Visual Recognition is discontinued. Existing instances are supported until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance @@ -22,20 +24,18 @@ detects objects based on a set of images with training data. """ -import json -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers from datetime import date 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 typing import BinaryIO, Dict, List +import json + +from ibm_cloud_sdk_core import BaseService, DetailedResponse +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator 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 +from ibm_cloud_sdk_core.utils import convert_model, datetime_to_string, string_to_datetime + +from .common import get_sdk_headers ############################################################################## # Service @@ -57,28 +57,21 @@ def __init__( """ Construct a new client for the Visual Recognition service. - :param str version: The API version date to use with the service, in - "YYYY-MM-DD" format. Whenever the API is changed in a backwards - incompatible way, a new minor version of the API is released. - The service uses the API version for the date you specify, or - the most recent version before that date. Note that you should - not programmatically specify the current date at runtime, in - case the API has been updated since your application's release. - Instead, specify a version date that is compatible with your - application, and don't change it until your application is - ready for a later version. + :param str version: Release date of the API version you want to use. + Specify dates in YYYY-MM-DD format. The current version is `2019-02-11`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ - print('warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#visual-recognition-deprecation.') + if version is None: + raise ValueError('version must be provided') + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.version = version self.configure_service(service_name) @@ -87,13 +80,13 @@ def __init__( ######################### def analyze(self, - collection_ids: str, - features: str, + collection_ids: List[str], + features: List[str], *, - images_file: BinaryIO = None, - image_url: str = None, + images_file: List[BinaryIO] = None, + image_url: List[str] = None, threshold: float = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Analyze images. @@ -124,17 +117,14 @@ def analyze(self, be returned. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `AnalyzeResponse` object """ if collection_ids is None: raise ValueError('collection_ids must be provided') if features is None: raise ValueError('features 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='analyze') @@ -143,23 +133,26 @@ def analyze(self, params = {'version': self.version} form_data = [] - collection_ids = self._convert_list(collection_ids) - form_data.append( - ('collection_ids', (None, collection_ids, 'text/plain'))) - features = self._convert_list(features) - form_data.append(('features', (None, features, 'text/plain'))) + for item in collection_ids: + form_data.append(('collection_ids', (None, item, 'text/plain'))) + for item in features: + form_data.append(('features', (None, item, 'text/plain'))) if images_file: for item in images_file: - form_data.append(('images_file', (item.filename, item.data, - item.content_type or - 'application/octet-stream'))) + item = convert_model(item) + _file = (item.get('filename') or None, item['data'], + item.get('content_type') or 'application/octet-stream') + form_data.append(('images_file', _file)) if image_url: for item in image_url: - form_data.append( - ('image_url', (None, item, 'application/json'))) + form_data.append(('image_url', (None, item, 'text/plain'))) if threshold: - threshold = str(threshold) - form_data.append(('threshold', (None, threshold, 'text/plain'))) + form_data.append( + ('threshold', (None, str(threshold), 'text/plain'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v4/analyze' request = self.prepare_request(method='POST', @@ -179,7 +172,8 @@ def create_collection(self, *, name: str = None, description: str = None, - **kwargs) -> 'DetailedResponse': + training_status: 'TrainingStatus' = None, + **kwargs) -> DetailedResponse: """ Create a collection. @@ -193,14 +187,16 @@ def create_collection(self, contain alphanumeric, underscore, hyphen, and dot characters. It cannot begin with the reserved prefix `sys-`. :param str description: (optional) The description of the collection. + :param TrainingStatus training_status: (optional) Training status + information for the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Collection` object """ + if training_status is not None: + training_status = convert_model(training_status) 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='create_collection') @@ -208,7 +204,18 @@ def create_collection(self, params = {'version': self.version} - data = {'name': name, 'description': description} + data = { + 'name': name, + 'description': description, + 'training_status': training_status + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v4/collections' request = self.prepare_request(method='POST', @@ -220,7 +227,7 @@ def create_collection(self, response = self.send(request) return response - def list_collections(self, **kwargs) -> 'DetailedResponse': + def list_collections(self, **kwargs) -> DetailedResponse: """ List collections. @@ -228,12 +235,10 @@ def list_collections(self, **kwargs) -> 'DetailedResponse': :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `CollectionsList` object """ 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_collections') @@ -241,6 +246,10 @@ def list_collections(self, **kwargs) -> 'DetailedResponse': params = {'version': self.version} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v4/collections' request = self.prepare_request(method='GET', url=url, @@ -250,8 +259,7 @@ def list_collections(self, **kwargs) -> 'DetailedResponse': response = self.send(request) return response - def get_collection(self, collection_id: str, - **kwargs) -> 'DetailedResponse': + def get_collection(self, collection_id: str, **kwargs) -> DetailedResponse: """ Get collection details. @@ -260,15 +268,12 @@ def get_collection(self, collection_id: str, :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 + :rtype: DetailedResponse with `dict` result representing a `Collection` object """ 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='get_collection') @@ -276,8 +281,14 @@ def get_collection(self, collection_id: str, params = {'version': self.version} - url = '/v4/collections/{0}'.format( - *self._encode_path_vars(collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['collection_id'] + path_param_values = self.encode_path_vars(collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -291,7 +302,8 @@ def update_collection(self, *, name: str = None, description: str = None, - **kwargs) -> 'DetailedResponse': + training_status: 'TrainingStatus' = None, + **kwargs) -> DetailedResponse: """ Update a collection. @@ -304,17 +316,18 @@ def update_collection(self, contain alphanumeric, underscore, hyphen, and dot characters. It cannot begin with the reserved prefix `sys-`. :param str description: (optional) The description of the collection. + :param TrainingStatus training_status: (optional) Training status + information for the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Collection` object """ if collection_id is None: raise ValueError('collection_id must be provided') - + if training_status is not None: + training_status = convert_model(training_status) 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_collection') @@ -322,10 +335,23 @@ def update_collection(self, params = {'version': self.version} - data = {'name': name, 'description': description} + data = { + 'name': name, + 'description': description, + 'training_status': training_status + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v4/collections/{0}'.format( - *self._encode_path_vars(collection_id)) + path_param_keys = ['collection_id'] + path_param_values = self.encode_path_vars(collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -336,7 +362,7 @@ def update_collection(self, return response def delete_collection(self, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a collection. @@ -350,10 +376,7 @@ def delete_collection(self, collection_id: str, 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='delete_collection') @@ -361,8 +384,14 @@ def delete_collection(self, collection_id: str, params = {'version': self.version} - url = '/v4/collections/{0}'.format( - *self._encode_path_vars(collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['collection_id'] + path_param_values = self.encode_path_vars(collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -372,7 +401,7 @@ def delete_collection(self, collection_id: str, return response def get_model_file(self, collection_id: str, feature: str, - model_format: str, **kwargs) -> 'DetailedResponse': + model_format: str, **kwargs) -> DetailedResponse: """ Get a model. @@ -389,7 +418,7 @@ def get_model_file(self, collection_id: str, feature: str, :param str model_format: The format of the returned model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `BinaryIO` result """ if collection_id is None: @@ -398,10 +427,7 @@ def get_model_file(self, collection_id: str, feature: str, raise ValueError('feature must be provided') if model_format is None: raise ValueError('model_format 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_model_file') @@ -413,8 +439,14 @@ def get_model_file(self, collection_id: str, feature: str, 'model_format': model_format } - url = '/v4/collections/{0}/model'.format( - *self._encode_path_vars(collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/octet-stream' + + path_param_keys = ['collection_id'] + path_param_values = self.encode_path_vars(collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/model'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -430,10 +462,10 @@ def get_model_file(self, collection_id: str, feature: str, def add_images(self, collection_id: str, *, - images_file: BinaryIO = None, - image_url: str = None, + images_file: List[BinaryIO] = None, + image_url: List[str] = None, training_data: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add images. @@ -464,15 +496,12 @@ def add_images(self, must be no longer than 32 characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ImageDetailsList` object """ 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='add_images') @@ -483,20 +512,25 @@ def add_images(self, form_data = [] if images_file: for item in images_file: - form_data.append(('images_file', (item.filename, item.data, - item.content_type or - 'application/octet-stream'))) + item = convert_model(item) + _file = (item.get('filename') or None, item['data'], + item.get('content_type') or 'application/octet-stream') + form_data.append(('images_file', _file)) if image_url: for item in image_url: - form_data.append( - ('image_url', (None, item, 'application/json'))) + form_data.append(('image_url', (None, item, 'text/plain'))) if training_data: - training_data = str(training_data) form_data.append( ('training_data', (None, training_data, 'text/plain'))) - url = '/v4/collections/{0}/images'.format( - *self._encode_path_vars(collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['collection_id'] + path_param_values = self.encode_path_vars(collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/images'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -506,7 +540,7 @@ def add_images(self, response = self.send(request) return response - def list_images(self, collection_id: str, **kwargs) -> 'DetailedResponse': + def list_images(self, collection_id: str, **kwargs) -> DetailedResponse: """ List images. @@ -515,15 +549,12 @@ def list_images(self, collection_id: str, **kwargs) -> 'DetailedResponse': :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 + :rtype: DetailedResponse with `dict` result representing a `ImageSummaryList` object """ 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_images') @@ -531,8 +562,14 @@ def list_images(self, collection_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v4/collections/{0}/images'.format( - *self._encode_path_vars(collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['collection_id'] + path_param_values = self.encode_path_vars(collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/images'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -542,7 +579,7 @@ def list_images(self, collection_id: str, **kwargs) -> 'DetailedResponse': return response def get_image_details(self, collection_id: str, image_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get image details. @@ -552,17 +589,14 @@ def get_image_details(self, collection_id: str, image_id: str, :param str image_id: The identifier of the image. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ImageDetails` object """ if collection_id is None: raise ValueError('collection_id must be provided') if image_id is None: raise ValueError('image_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='get_image_details') @@ -570,8 +604,15 @@ def get_image_details(self, collection_id: str, image_id: str, params = {'version': self.version} - url = '/v4/collections/{0}/images/{1}'.format( - *self._encode_path_vars(collection_id, image_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['collection_id', 'image_id'] + path_param_values = self.encode_path_vars(collection_id, image_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/images/{image_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -581,7 +622,7 @@ def get_image_details(self, collection_id: str, image_id: str, return response def delete_image(self, collection_id: str, image_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete an image. @@ -598,10 +639,7 @@ def delete_image(self, collection_id: str, image_id: str, raise ValueError('collection_id must be provided') if image_id is None: raise ValueError('image_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='delete_image') @@ -609,8 +647,15 @@ def delete_image(self, collection_id: str, image_id: str, params = {'version': self.version} - url = '/v4/collections/{0}/images/{1}'.format( - *self._encode_path_vars(collection_id, image_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['collection_id', 'image_id'] + path_param_values = self.encode_path_vars(collection_id, image_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/images/{image_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -624,7 +669,7 @@ def get_jpeg_image(self, image_id: str, *, size: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get a JPEG file of an image. @@ -638,17 +683,14 @@ def get_jpeg_image(self, is resized to 160 x 200 pixels. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `BinaryIO` result """ if collection_id is None: raise ValueError('collection_id must be provided') if image_id is None: raise ValueError('image_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='get_jpeg_image') @@ -656,8 +698,15 @@ def get_jpeg_image(self, params = {'version': self.version, 'size': size} - url = '/v4/collections/{0}/images/{1}/jpeg'.format( - *self._encode_path_vars(collection_id, image_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'image/jpeg' + + path_param_keys = ['collection_id', 'image_id'] + path_param_values = self.encode_path_vars(collection_id, image_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/images/{image_id}/jpeg'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -671,7 +720,7 @@ def get_jpeg_image(self, ######################### def list_object_metadata(self, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List object metadata. @@ -680,15 +729,12 @@ def list_object_metadata(self, collection_id: str, :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 + :rtype: DetailedResponse with `dict` result representing a `ObjectMetadataList` object """ 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') @@ -696,8 +742,15 @@ def list_object_metadata(self, collection_id: str, params = {'version': self.version} - url = '/v4/collections/{0}/objects'.format( - *self._encode_path_vars(collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['collection_id'] + path_param_values = self.encode_path_vars(collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/objects'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -707,7 +760,7 @@ def list_object_metadata(self, collection_id: str, return response def update_object_metadata(self, collection_id: str, object: str, - new_object: str, **kwargs) -> 'DetailedResponse': + new_object: str, **kwargs) -> DetailedResponse: """ Update an object name. @@ -721,7 +774,7 @@ def update_object_metadata(self, collection_id: str, object: str, 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 + :rtype: DetailedResponse with `dict` result representing a `UpdateObjectMetadata` object """ if collection_id is None: @@ -730,10 +783,7 @@ def update_object_metadata(self, collection_id: str, object: str, 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') @@ -742,9 +792,19 @@ def update_object_metadata(self, collection_id: str, object: str, params = {'version': self.version} data = {'object': new_object} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v4/collections/{0}/objects/{1}'.format( - *self._encode_path_vars(collection_id, object)) + path_param_keys = ['collection_id', 'object'] + path_param_values = self.encode_path_vars(collection_id, object) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/objects/{object}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -755,7 +815,7 @@ def update_object_metadata(self, collection_id: str, object: str, return response def get_object_metadata(self, collection_id: str, object: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get object metadata. @@ -765,17 +825,14 @@ def get_object_metadata(self, collection_id: str, object: str, :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 + :rtype: DetailedResponse with `dict` result representing a `ObjectMetadata` object """ 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') @@ -783,8 +840,15 @@ def get_object_metadata(self, collection_id: str, object: str, params = {'version': self.version} - url = '/v4/collections/{0}/objects/{1}'.format( - *self._encode_path_vars(collection_id, object)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['collection_id', 'object'] + path_param_values = self.encode_path_vars(collection_id, object) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/objects/{object}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -794,7 +858,7 @@ def get_object_metadata(self, collection_id: str, object: str, return response def delete_object(self, collection_id: str, object: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete an object. @@ -812,10 +876,7 @@ def delete_object(self, collection_id: str, object: str, 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') @@ -823,8 +884,15 @@ def delete_object(self, collection_id: str, object: str, params = {'version': self.version} - url = '/v4/collections/{0}/objects/{1}'.format( - *self._encode_path_vars(collection_id, object)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['collection_id', 'object'] + path_param_values = self.encode_path_vars(collection_id, object) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/objects/{object}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -837,7 +905,7 @@ def delete_object(self, collection_id: str, object: str, # Training ######################### - def train(self, collection_id: str, **kwargs) -> 'DetailedResponse': + def train(self, collection_id: str, **kwargs) -> DetailedResponse: """ Train a collection. @@ -848,15 +916,12 @@ def train(self, collection_id: str, **kwargs) -> 'DetailedResponse': :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 + :rtype: DetailedResponse with `dict` result representing a `Collection` object """ 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='train') @@ -864,8 +929,14 @@ def train(self, collection_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v4/collections/{0}/train'.format( - *self._encode_path_vars(collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['collection_id'] + path_param_values = self.encode_path_vars(collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/train'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -879,7 +950,7 @@ def add_image_training_data(self, image_id: str, *, objects: List['TrainingDataObject'] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add training data to an image. @@ -897,7 +968,7 @@ def add_image_training_data(self, specific objects. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingDataObjects` object """ if collection_id is None: @@ -905,11 +976,8 @@ def add_image_training_data(self, if image_id is None: raise ValueError('image_id must be provided') if objects is not None: - objects = [self._convert_model(x) for x in objects] - + objects = [convert_model(x) for x in objects] 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='add_image_training_data') @@ -918,9 +986,19 @@ def add_image_training_data(self, params = {'version': self.version} data = {'objects': objects} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v4/collections/{0}/images/{1}/training_data'.format( - *self._encode_path_vars(collection_id, image_id)) + path_param_keys = ['collection_id', 'image_id'] + path_param_values = self.encode_path_vars(collection_id, image_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v4/collections/{collection_id}/images/{image_id}/training_data'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -934,7 +1012,7 @@ def get_training_usage(self, *, start_time: date = None, end_time: date = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get training usage. @@ -950,12 +1028,10 @@ def get_training_usage(self, same value as `start_time` to request events for a single day. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingEvents` object """ 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_training_usage') @@ -967,6 +1043,10 @@ def get_training_usage(self, 'end_time': end_time } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v4/training_usage' request = self.prepare_request(method='GET', url=url, @@ -980,8 +1060,7 @@ def get_training_usage(self, # User data ######################### - def delete_user_data(self, customer_id: str, - **kwargs) -> 'DetailedResponse': + def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: """ Delete labeled data. @@ -1001,10 +1080,7 @@ def delete_user_data(self, customer_id: str, if customer_id is None: raise ValueError('customer_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='delete_user_data') @@ -1012,6 +1088,10 @@ def delete_user_data(self, customer_id: str, params = {'version': self.version, 'customer_id': customer_id} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v4/user_data' request = self.prepare_request(method='DELETE', url=url, @@ -1022,33 +1102,42 @@ def delete_user_data(self, customer_id: str, return response -class AnalyzeEnums(object): +class AnalyzeEnums: + """ + Enums for analyze parameters. + """ - class Features(Enum): + class Features(str, Enum): """ The features to analyze. """ OBJECTS = 'objects' -class GetModelFileEnums(object): +class GetModelFileEnums: + """ + Enums for get_model_file parameters. + """ - class Feature(Enum): + class Feature(str, Enum): """ The feature for the model. """ OBJECTS = 'objects' - class ModelFormat(Enum): + class ModelFormat(str, Enum): """ The format of the returned model. """ RSCNN = 'rscnn' -class GetJpegImageEnums(object): +class GetJpegImageEnums: + """ + Enums for get_jpeg_image parameters. + """ - class Size(Enum): + class Size(str, Enum): """ The image size. Specify `thumbnail` to return a version that maintains the original aspect ratio but is no larger than 200 pixels in the larger dimension. @@ -1096,23 +1185,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalyzeResponse': """Initialize a AnalyzeResponse object from a json dictionary.""" args = {} - valid_keys = ['images', 'warnings', 'trace'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AnalyzeResponse: ' - + ', '.join(bad_keys)) if 'images' in _dict: - args['images'] = [ - Image._from_dict(x) for x in (_dict.get('images')) - ] + args['images'] = [Image.from_dict(x) for x in _dict.get('images')] else: raise ValueError( 'Required property \'images\' not present in AnalyzeResponse JSON' ) if 'warnings' in _dict: args['warnings'] = [ - Warning._from_dict(x) for x in (_dict.get('warnings')) + Warning.from_dict(x) for x in _dict.get('warnings') ] if 'trace' in _dict: args['trace'] = _dict.get('trace') @@ -1127,9 +1208,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'images') and self.images is not None: - _dict['images'] = [x._to_dict() for x in self.images] + _dict['images'] = [x.to_dict() for x in self.images] if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x._to_dict() for x in self.warnings] + _dict['warnings'] = [x.to_dict() for x in self.warnings] if hasattr(self, 'trace') and self.trace is not None: _dict['trace'] = self.trace return _dict @@ -1140,7 +1221,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AnalyzeResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AnalyzeResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1165,13 +1246,13 @@ class Collection(): :attr datetime updated: Date and time in Coordinated Universal Time (UTC) that the collection was most recently updated. :attr int image_count: Number of images in the collection. - :attr TrainingStatus training_status: Training status information for the - collection. + :attr CollectionTrainingStatus training_status: Training status information for + the collection. """ def __init__(self, collection_id: str, name: str, description: str, created: datetime, updated: datetime, image_count: int, - training_status: 'TrainingStatus') -> None: + training_status: 'CollectionTrainingStatus') -> None: """ Initialize a Collection object. @@ -1183,8 +1264,8 @@ def __init__(self, collection_id: str, name: str, description: str, :param datetime updated: Date and time in Coordinated Universal Time (UTC) that the collection was most recently updated. :param int image_count: Number of images in the collection. - :param TrainingStatus training_status: Training status information for the - collection. + :param CollectionTrainingStatus training_status: Training status + information for the collection. """ self.collection_id = collection_id self.name = name @@ -1198,15 +1279,6 @@ def __init__(self, collection_id: str, name: str, description: str, def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} - valid_keys = [ - 'collection_id', 'name', 'description', 'created', 'updated', - 'image_count', 'training_status' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Collection: ' - + ', '.join(bad_keys)) if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') else: @@ -1241,7 +1313,7 @@ def from_dict(cls, _dict: Dict) -> 'Collection': 'Required property \'image_count\' not present in Collection JSON' ) if 'training_status' in _dict: - args['training_status'] = TrainingStatus._from_dict( + args['training_status'] = CollectionTrainingStatus.from_dict( _dict.get('training_status')) else: raise ValueError( @@ -1257,21 +1329,23 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id + if hasattr(self, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) - if hasattr(self, 'image_count') and self.image_count is not None: - _dict['image_count'] = self.image_count + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + if hasattr(self, 'image_count') and getattr(self, + 'image_count') is not None: + _dict['image_count'] = getattr(self, 'image_count') if hasattr(self, 'training_status') and self.training_status is not None: - _dict['training_status'] = self.training_status._to_dict() + _dict['training_status'] = self.training_status.to_dict() return _dict def _to_dict(self): @@ -1280,7 +1354,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Collection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Collection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1316,12 +1390,6 @@ def __init__(self, collection_id: str, def from_dict(cls, _dict: Dict) -> 'CollectionObjects': """Initialize a CollectionObjects object from a json dictionary.""" args = {} - valid_keys = ['collection_id', 'objects'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CollectionObjects: ' - + ', '.join(bad_keys)) if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') else: @@ -1330,7 +1398,7 @@ def from_dict(cls, _dict: Dict) -> 'CollectionObjects': ) if 'objects' in _dict: args['objects'] = [ - ObjectDetail._from_dict(x) for x in (_dict.get('objects')) + ObjectDetail.from_dict(x) for x in _dict.get('objects') ] else: raise ValueError( @@ -1349,7 +1417,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'objects') and self.objects is not None: - _dict['objects'] = [x._to_dict() for x in self.objects] + _dict['objects'] = [x.to_dict() for x in self.objects] return _dict def _to_dict(self): @@ -1358,7 +1426,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CollectionObjects object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CollectionObjects') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1371,6 +1439,67 @@ def __ne__(self, other: 'CollectionObjects') -> bool: return not self == other +class CollectionTrainingStatus(): + """ + Training status information for the collection. + + :attr ObjectTrainingStatus objects: Training status for the objects in the + collection. + """ + + def __init__(self, objects: 'ObjectTrainingStatus') -> None: + """ + Initialize a CollectionTrainingStatus object. + + :param ObjectTrainingStatus objects: Training status for the objects in the + collection. + """ + self.objects = objects + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CollectionTrainingStatus': + """Initialize a CollectionTrainingStatus object from a json dictionary.""" + args = {} + if 'objects' in _dict: + args['objects'] = ObjectTrainingStatus.from_dict( + _dict.get('objects')) + else: + raise ValueError( + 'Required property \'objects\' not present in CollectionTrainingStatus JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionTrainingStatus 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, 'objects') and self.objects is not None: + _dict['objects'] = self.objects.to_dict() + 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 CollectionTrainingStatus object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CollectionTrainingStatus') -> 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: 'CollectionTrainingStatus') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class CollectionsList(): """ A container for the list of collections. @@ -1391,15 +1520,9 @@ def __init__(self, collections: List['Collection']) -> None: def from_dict(cls, _dict: Dict) -> 'CollectionsList': """Initialize a CollectionsList object from a json dictionary.""" args = {} - valid_keys = ['collections'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CollectionsList: ' - + ', '.join(bad_keys)) if 'collections' in _dict: args['collections'] = [ - Collection._from_dict(x) for x in (_dict.get('collections')) + Collection.from_dict(x) for x in _dict.get('collections') ] else: raise ValueError( @@ -1416,7 +1539,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = [x._to_dict() for x in self.collections] + _dict['collections'] = [x.to_dict() for x in self.collections] return _dict def _to_dict(self): @@ -1425,7 +1548,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CollectionsList object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CollectionsList') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1461,16 +1584,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DetectedObjects': """Initialize a DetectedObjects object from a json dictionary.""" args = {} - valid_keys = ['collections'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DetectedObjects: ' - + ', '.join(bad_keys)) if 'collections' in _dict: args['collections'] = [ - CollectionObjects._from_dict(x) - for x in (_dict.get('collections')) + CollectionObjects.from_dict(x) for x in _dict.get('collections') ] return cls(**args) @@ -1483,7 +1599,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = [x._to_dict() for x in self.collections] + _dict['collections'] = [x.to_dict() for x in self.collections] return _dict def _to_dict(self): @@ -1492,7 +1608,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DetectedObjects object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DetectedObjects') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1541,12 +1657,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Error': """Initialize a Error object from a json dictionary.""" args = {} - valid_keys = ['code', 'message', 'more_info', 'target'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Error: ' + - ', '.join(bad_keys)) if 'code' in _dict: args['code'] = _dict.get('code') else: @@ -1560,7 +1670,7 @@ def from_dict(cls, _dict: Dict) -> 'Error': if 'more_info' in _dict: args['more_info'] = _dict.get('more_info') if 'target' in _dict: - args['target'] = ErrorTarget._from_dict(_dict.get('target')) + args['target'] = ErrorTarget.from_dict(_dict.get('target')) return cls(**args) @classmethod @@ -1578,7 +1688,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'more_info') and self.more_info is not None: _dict['more_info'] = self.more_info if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target._to_dict() + _dict['target'] = self.target.to_dict() return _dict def _to_dict(self): @@ -1587,7 +1697,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Error object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Error') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1599,15 +1709,15 @@ def __ne__(self, other: 'Error') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class CodeEnum(Enum): + class CodeEnum(str, Enum): """ Identifier of the problem. """ - INVALID_FIELD = "invalid_field" - INVALID_HEADER = "invalid_header" - INVALID_METHOD = "invalid_method" - MISSING_FIELD = "missing_field" - SERVER_ERROR = "server_error" + INVALID_FIELD = 'invalid_field' + INVALID_HEADER = 'invalid_header' + INVALID_METHOD = 'invalid_method' + MISSING_FIELD = 'missing_field' + SERVER_ERROR = 'server_error' class ErrorTarget(): @@ -1633,12 +1743,6 @@ def __init__(self, type: str, name: str) -> None: def from_dict(cls, _dict: Dict) -> 'ErrorTarget': """Initialize a ErrorTarget object from a json dictionary.""" args = {} - valid_keys = ['type', 'name'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ErrorTarget: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') else: @@ -1671,7 +1775,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ErrorTarget object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ErrorTarget') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1683,13 +1787,13 @@ def __ne__(self, other: 'ErrorTarget') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The parameter or property that is the focus of the problem. """ - FIELD = "field" - PARAMETER = "parameter" - HEADER = "header" + FIELD = 'field' + PARAMETER = 'parameter' + HEADER = 'header' class Image(): @@ -1729,32 +1833,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Image': """Initialize a Image object from a json dictionary.""" args = {} - valid_keys = ['source', 'dimensions', 'objects', 'errors'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Image: ' + - ', '.join(bad_keys)) if 'source' in _dict: - args['source'] = ImageSource._from_dict(_dict.get('source')) + args['source'] = ImageSource.from_dict(_dict.get('source')) else: raise ValueError( 'Required property \'source\' not present in Image JSON') if 'dimensions' in _dict: - args['dimensions'] = ImageDimensions._from_dict( + args['dimensions'] = ImageDimensions.from_dict( _dict.get('dimensions')) else: raise ValueError( 'Required property \'dimensions\' not present in Image JSON') if 'objects' in _dict: - args['objects'] = DetectedObjects._from_dict(_dict.get('objects')) + args['objects'] = DetectedObjects.from_dict(_dict.get('objects')) else: raise ValueError( 'Required property \'objects\' not present in Image JSON') if 'errors' in _dict: - args['errors'] = [ - Error._from_dict(x) for x in (_dict.get('errors')) - ] + args['errors'] = [Error.from_dict(x) for x in _dict.get('errors')] return cls(**args) @classmethod @@ -1766,13 +1862,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source._to_dict() + _dict['source'] = self.source.to_dict() if hasattr(self, 'dimensions') and self.dimensions is not None: - _dict['dimensions'] = self.dimensions._to_dict() + _dict['dimensions'] = self.dimensions.to_dict() if hasattr(self, 'objects') and self.objects is not None: - _dict['objects'] = self.objects._to_dict() + _dict['objects'] = self.objects.to_dict() if hasattr(self, 'errors') and self.errors is not None: - _dict['errors'] = [x._to_dict() for x in self.errors] + _dict['errors'] = [x.to_dict() for x in self.errors] return _dict def _to_dict(self): @@ -1781,7 +1877,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Image object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Image') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1845,15 +1941,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ImageDetails': """Initialize a ImageDetails object from a json dictionary.""" args = {} - valid_keys = [ - 'image_id', 'updated', 'created', 'source', 'dimensions', 'errors', - 'training_data' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ImageDetails: ' - + ', '.join(bad_keys)) if 'image_id' in _dict: args['image_id'] = _dict.get('image_id') if 'updated' in _dict: @@ -1861,19 +1948,17 @@ def from_dict(cls, _dict: Dict) -> 'ImageDetails': if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) if 'source' in _dict: - args['source'] = ImageSource._from_dict(_dict.get('source')) + args['source'] = ImageSource.from_dict(_dict.get('source')) else: raise ValueError( 'Required property \'source\' not present in ImageDetails JSON') if 'dimensions' in _dict: - args['dimensions'] = ImageDimensions._from_dict( + args['dimensions'] = ImageDimensions.from_dict( _dict.get('dimensions')) if 'errors' in _dict: - args['errors'] = [ - Error._from_dict(x) for x in (_dict.get('errors')) - ] + args['errors'] = [Error.from_dict(x) for x in _dict.get('errors')] if 'training_data' in _dict: - args['training_data'] = TrainingDataObjects._from_dict( + args['training_data'] = TrainingDataObjects.from_dict( _dict.get('training_data')) return cls(**args) @@ -1892,13 +1977,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source._to_dict() + _dict['source'] = self.source.to_dict() if hasattr(self, 'dimensions') and self.dimensions is not None: - _dict['dimensions'] = self.dimensions._to_dict() + _dict['dimensions'] = self.dimensions.to_dict() if hasattr(self, 'errors') and self.errors is not None: - _dict['errors'] = [x._to_dict() for x in self.errors] + _dict['errors'] = [x.to_dict() for x in self.errors] if hasattr(self, 'training_data') and self.training_data is not None: - _dict['training_data'] = self.training_data._to_dict() + _dict['training_data'] = self.training_data.to_dict() return _dict def _to_dict(self): @@ -1907,7 +1992,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ImageDetails object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ImageDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1953,19 +2038,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ImageDetailsList': """Initialize a ImageDetailsList object from a json dictionary.""" args = {} - valid_keys = ['images', 'warnings', 'trace'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ImageDetailsList: ' - + ', '.join(bad_keys)) if 'images' in _dict: args['images'] = [ - ImageDetails._from_dict(x) for x in (_dict.get('images')) + ImageDetails.from_dict(x) for x in _dict.get('images') ] if 'warnings' in _dict: args['warnings'] = [ - Warning._from_dict(x) for x in (_dict.get('warnings')) + Warning.from_dict(x) for x in _dict.get('warnings') ] if 'trace' in _dict: args['trace'] = _dict.get('trace') @@ -1980,9 +2059,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'images') and self.images is not None: - _dict['images'] = [x._to_dict() for x in self.images] + _dict['images'] = [x.to_dict() for x in self.images] if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x._to_dict() for x in self.warnings] + _dict['warnings'] = [x.to_dict() for x in self.warnings] if hasattr(self, 'trace') and self.trace is not None: _dict['trace'] = self.trace return _dict @@ -1993,7 +2072,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ImageDetailsList object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ImageDetailsList') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2028,12 +2107,6 @@ def __init__(self, *, height: int = None, width: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'ImageDimensions': """Initialize a ImageDimensions object from a json dictionary.""" args = {} - valid_keys = ['height', 'width'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ImageDimensions: ' - + ', '.join(bad_keys)) if 'height' in _dict: args['height'] = _dict.get('height') if 'width' in _dict: @@ -2060,7 +2133,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ImageDimensions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ImageDimensions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2118,14 +2191,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ImageSource': """Initialize a ImageSource object from a json dictionary.""" args = {} - valid_keys = [ - 'type', 'filename', 'archive_filename', 'source_url', 'resolved_url' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ImageSource: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') else: @@ -2168,7 +2233,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ImageSource object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ImageSource') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2180,12 +2245,12 @@ def __ne__(self, other: 'ImageSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The source type of the image. """ - FILE = "file" - URL = "url" + FILE = 'file' + URL = 'url' class ImageSummary(): @@ -2215,12 +2280,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ImageSummary': """Initialize a ImageSummary object from a json dictionary.""" args = {} - valid_keys = ['image_id', 'updated'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ImageSummary: ' - + ', '.join(bad_keys)) if 'image_id' in _dict: args['image_id'] = _dict.get('image_id') if 'updated' in _dict: @@ -2247,7 +2306,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ImageSummary object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ImageSummary') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2279,15 +2338,9 @@ def __init__(self, images: List['ImageSummary']) -> None: def from_dict(cls, _dict: Dict) -> 'ImageSummaryList': """Initialize a ImageSummaryList object from a json dictionary.""" args = {} - valid_keys = ['images'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ImageSummaryList: ' - + ', '.join(bad_keys)) if 'images' in _dict: args['images'] = [ - ImageSummary._from_dict(x) for x in (_dict.get('images')) + ImageSummary.from_dict(x) for x in _dict.get('images') ] else: raise ValueError( @@ -2304,7 +2357,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'images') and self.images is not None: - _dict['images'] = [x._to_dict() for x in self.images] + _dict['images'] = [x.to_dict() for x in self.images] return _dict def _to_dict(self): @@ -2313,7 +2366,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ImageSummaryList object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ImageSummaryList') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2354,12 +2407,6 @@ def __init__(self, top: int, left: int, width: int, height: int) -> None: def from_dict(cls, _dict: Dict) -> 'Location': """Initialize a Location object from a json dictionary.""" args = {} - valid_keys = ['top', 'left', 'width', 'height'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Location: ' - + ', '.join(bad_keys)) if 'top' in _dict: args['top'] = _dict.get('top') else: @@ -2406,7 +2453,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Location object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Location') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2424,20 +2471,21 @@ class ObjectDetail(): Details about an object in the collection. :attr str object: The label for the object. - :attr Location location: Defines the location of the bounding box around the - object. + :attr ObjectDetailLocation location: Defines the location of the bounding box + around the object. :attr float score: Confidence score for the object in the range of 0 to 1. A higher score indicates greater likelihood that the object is depicted at this location in the image. """ - def __init__(self, object: str, location: 'Location', score: float) -> None: + def __init__(self, object: str, location: 'ObjectDetailLocation', + score: float) -> None: """ Initialize a ObjectDetail object. :param str object: The label for the object. - :param Location location: Defines the location of the bounding box around - the object. + :param ObjectDetailLocation location: Defines the location of the bounding + box around the object. :param float score: Confidence score for the object in the range of 0 to 1. A higher score indicates greater likelihood that the object is depicted at this location in the image. @@ -2450,19 +2498,14 @@ def __init__(self, object: str, location: 'Location', score: float) -> None: def from_dict(cls, _dict: Dict) -> 'ObjectDetail': """Initialize a ObjectDetail object from a json dictionary.""" args = {} - valid_keys = ['object', 'location', 'score'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ObjectDetail: ' - + ', '.join(bad_keys)) if 'object' in _dict: args['object'] = _dict.get('object') else: raise ValueError( 'Required property \'object\' not present in ObjectDetail JSON') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = ObjectDetailLocation.from_dict( + _dict.get('location')) else: raise ValueError( 'Required property \'location\' not present in ObjectDetail JSON' @@ -2485,7 +2528,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'object') and self.object is not None: _dict['object'] = self.object if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score return _dict @@ -2496,7 +2539,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ObjectDetail object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ObjectDetail') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2509,6 +2552,97 @@ def __ne__(self, other: 'ObjectDetail') -> bool: return not self == other +class ObjectDetailLocation(): + """ + Defines the location of the bounding box around the object. + + :attr int top: Y-position of top-left pixel of the bounding box. + :attr int left: X-position of top-left pixel of the bounding box. + :attr int width: Width in pixels of of the bounding box. + :attr int height: Height in pixels of the bounding box. + """ + + def __init__(self, top: int, left: int, width: int, height: int) -> None: + """ + Initialize a ObjectDetailLocation object. + + :param int top: Y-position of top-left pixel of the bounding box. + :param int left: X-position of top-left pixel of the bounding box. + :param int width: Width in pixels of of the bounding box. + :param int height: Height in pixels of the bounding box. + """ + self.top = top + self.left = left + self.width = width + self.height = height + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ObjectDetailLocation': + """Initialize a ObjectDetailLocation object from a json dictionary.""" + args = {} + if 'top' in _dict: + args['top'] = _dict.get('top') + else: + raise ValueError( + 'Required property \'top\' not present in ObjectDetailLocation JSON' + ) + if 'left' in _dict: + args['left'] = _dict.get('left') + else: + raise ValueError( + 'Required property \'left\' not present in ObjectDetailLocation JSON' + ) + if 'width' in _dict: + args['width'] = _dict.get('width') + else: + raise ValueError( + 'Required property \'width\' not present in ObjectDetailLocation JSON' + ) + if 'height' in _dict: + args['height'] = _dict.get('height') + else: + raise ValueError( + 'Required property \'height\' not present in ObjectDetailLocation JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ObjectDetailLocation 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, 'top') and self.top is not None: + _dict['top'] = self.top + if hasattr(self, 'left') and self.left is not None: + _dict['left'] = self.left + if hasattr(self, 'width') and self.width is not None: + _dict['width'] = self.width + if hasattr(self, 'height') and self.height is not None: + _dict['height'] = self.height + 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 ObjectDetailLocation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ObjectDetailLocation') -> 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: 'ObjectDetailLocation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ObjectMetadata(): """ Basic information about an object. @@ -2523,8 +2657,6 @@ 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 @@ -2533,12 +2665,6 @@ def __init__(self, *, object: str = None, count: int = None) -> None: 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: @@ -2555,8 +2681,8 @@ def to_dict(self) -> Dict: _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 + if hasattr(self, 'count') and getattr(self, 'count') is not None: + _dict['count'] = getattr(self, 'count') return _dict def _to_dict(self): @@ -2565,7 +2691,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ObjectMetadata object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ObjectMetadata') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2604,12 +2730,6 @@ def __init__(self, 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: @@ -2618,7 +2738,7 @@ def from_dict(cls, _dict: Dict) -> 'ObjectMetadataList': ) if 'objects' in _dict: args['objects'] = [ - ObjectMetadata._from_dict(x) for x in (_dict.get('objects')) + ObjectMetadata.from_dict(x) for x in _dict.get('objects') ] return cls(**args) @@ -2630,10 +2750,11 @@ def _from_dict(cls, _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, 'object_count') and getattr( + self, 'object_count') is not None: + _dict['object_count'] = getattr(self, 'object_count') if hasattr(self, 'objects') and self.objects is not None: - _dict['objects'] = [x._to_dict() for x in self.objects] + _dict['objects'] = [x.to_dict() for x in self.objects] return _dict def _to_dict(self): @@ -2642,7 +2763,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ObjectMetadataList object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ObjectMetadataList') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2702,15 +2823,6 @@ def __init__(self, ready: bool, in_progress: bool, data_changed: bool, def from_dict(cls, _dict: Dict) -> 'ObjectTrainingStatus': """Initialize a ObjectTrainingStatus object from a json dictionary.""" args = {} - valid_keys = [ - 'ready', 'in_progress', 'data_changed', 'latest_failed', - 'rscnn_ready', 'description' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ObjectTrainingStatus: ' - + ', '.join(bad_keys)) if 'ready' in _dict: args['ready'] = _dict.get('ready') else: @@ -2777,7 +2889,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ObjectTrainingStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ObjectTrainingStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2817,16 +2929,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingDataObject': """Initialize a TrainingDataObject object from a json dictionary.""" args = {} - valid_keys = ['object', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingDataObject: ' - + ', '.join(bad_keys)) if 'object' in _dict: args['object'] = _dict.get('object') if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) + args['location'] = Location.from_dict(_dict.get('location')) return cls(**args) @classmethod @@ -2840,7 +2946,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'object') and self.object is not None: _dict['object'] = self.object if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -2849,7 +2955,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingDataObject object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingDataObject') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2883,15 +2989,9 @@ def __init__(self, *, objects: List['TrainingDataObject'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingDataObjects': """Initialize a TrainingDataObjects object from a json dictionary.""" args = {} - valid_keys = ['objects'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingDataObjects: ' - + ', '.join(bad_keys)) if 'objects' in _dict: args['objects'] = [ - TrainingDataObject._from_dict(x) for x in (_dict.get('objects')) + TrainingDataObject.from_dict(x) for x in _dict.get('objects') ] return cls(**args) @@ -2904,7 +3004,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'objects') and self.objects is not None: - _dict['objects'] = [x._to_dict() for x in self.objects] + _dict['objects'] = [x.to_dict() for x in self.objects] return _dict def _to_dict(self): @@ -2913,7 +3013,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingDataObjects object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingDataObjects') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2969,14 +3069,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingEvent': """Initialize a TrainingEvent object from a json dictionary.""" args = {} - valid_keys = [ - 'type', 'collection_id', 'completion_time', 'status', 'image_count' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingEvent: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'collection_id' in _dict: @@ -3017,7 +3109,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingEvent object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingEvent') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3029,18 +3121,18 @@ def __ne__(self, other: 'TrainingEvent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ Trained object type. Only `objects` is currently supported. """ - OBJECTS = "objects" + OBJECTS = 'objects' - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Training status of the training event. """ - FAILED = "failed" - SUCCEEDED = "succeeded" + FAILED = 'failed' + SUCCEEDED = 'succeeded' class TrainingEvents(): @@ -3094,15 +3186,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingEvents': """Initialize a TrainingEvents object from a json dictionary.""" args = {} - valid_keys = [ - 'start_time', 'end_time', 'completed_events', 'trained_images', - 'events' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingEvents: ' - + ', '.join(bad_keys)) if 'start_time' in _dict: args['start_time'] = string_to_datetime(_dict.get('start_time')) if 'end_time' in _dict: @@ -3113,7 +3196,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingEvents': args['trained_images'] = _dict.get('trained_images') if 'events' in _dict: args['events'] = [ - TrainingEvent._from_dict(x) for x in (_dict.get('events')) + TrainingEvent.from_dict(x) for x in _dict.get('events') ] return cls(**args) @@ -3135,7 +3218,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'trained_images') and self.trained_images is not None: _dict['trained_images'] = self.trained_images if hasattr(self, 'events') and self.events is not None: - _dict['events'] = [x._to_dict() for x in self.events] + _dict['events'] = [x.to_dict() for x in self.events] return _dict def _to_dict(self): @@ -3144,7 +3227,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingEvents object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingEvents') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3178,14 +3261,8 @@ def __init__(self, objects: 'ObjectTrainingStatus') -> None: def from_dict(cls, _dict: Dict) -> 'TrainingStatus': """Initialize a TrainingStatus object from a json dictionary.""" args = {} - valid_keys = ['objects'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingStatus: ' - + ', '.join(bad_keys)) if 'objects' in _dict: - args['objects'] = ObjectTrainingStatus._from_dict( + args['objects'] = ObjectTrainingStatus.from_dict( _dict.get('objects')) else: raise ValueError( @@ -3202,7 +3279,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'objects') and self.objects is not None: - _dict['objects'] = self.objects._to_dict() + _dict['objects'] = self.objects.to_dict() return _dict def _to_dict(self): @@ -3211,7 +3288,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingStatus') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3242,8 +3319,6 @@ def __init__(self, object: str, *, count: int = None) -> None: :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: (optional) Number of bounding boxes in the collection - with the updated object name. """ self.object = object self.count = count @@ -3252,12 +3327,6 @@ def __init__(self, object: str, *, count: int = None) -> None: 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: @@ -3278,8 +3347,8 @@ def to_dict(self) -> Dict: _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 + if hasattr(self, 'count') and getattr(self, 'count') is not None: + _dict['count'] = getattr(self, 'count') return _dict def _to_dict(self): @@ -3288,7 +3357,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this UpdateObjectMetadata object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'UpdateObjectMetadata') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3331,12 +3400,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Warning': """Initialize a Warning object from a json dictionary.""" args = {} - valid_keys = ['code', 'message', 'more_info'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Warning: ' + - ', '.join(bad_keys)) if 'code' in _dict: args['code'] = _dict.get('code') else: @@ -3373,7 +3436,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Warning object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Warning') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3385,15 +3448,15 @@ def __ne__(self, other: 'Warning') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class CodeEnum(Enum): + class CodeEnum(str, Enum): """ Identifier of the problem. """ - INVALID_FIELD = "invalid_field" - INVALID_HEADER = "invalid_header" - INVALID_METHOD = "invalid_method" - MISSING_FIELD = "missing_field" - SERVER_ERROR = "server_error" + INVALID_FIELD = 'invalid_field' + INVALID_HEADER = 'invalid_header' + INVALID_METHOD = 'invalid_method' + MISSING_FIELD = 'missing_field' + SERVER_ERROR = 'server_error' class FileWithMetadata(): @@ -3425,12 +3488,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'FileWithMetadata': """Initialize a FileWithMetadata object from a json dictionary.""" args = {} - valid_keys = ['data', 'filename', 'content_type'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class FileWithMetadata: ' - + ', '.join(bad_keys)) if 'data' in _dict: args['data'] = _dict.get('data') else: @@ -3465,7 +3522,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this FileWithMetadata object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'FileWithMetadata') -> bool: """Return `true` when self and other are equal, false otherwise.""" diff --git a/ibm_watson/websocket/__init__.py b/ibm_watson/websocket/__init__.py index 391670869..f50ad9fdf 100644 --- a/ibm_watson/websocket/__init__.py +++ b/ibm_watson/websocket/__init__.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2018, 2019. +# (C) Copyright IBM Corp. 2018, 2020. # # 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 68f48e9ff..181eeab18 100644 --- a/ibm_watson/websocket/audio_source.py +++ b/ibm_watson/websocket/audio_source.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2018, 2019. +# (C) Copyright IBM Corp. 2018, 2020. # # 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 87824bc19..a8574c6d0 100644 --- a/ibm_watson/websocket/recognize_abstract_callback.py +++ b/ibm_watson/websocket/recognize_abstract_callback.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2018, 2019. +# (C) Copyright IBM Corp. 2018, 2020. # # 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 e3432ce10..3931a2529 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2018, 2019. +# (C) Copyright IBM Corp. 2018, 2020. # # 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 86bb41a16..ec62ea493 100644 --- a/ibm_watson/websocket/synthesize_callback.py +++ b/ibm_watson/websocket/synthesize_callback.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2018, 2019. +# (C) Copyright IBM Corp. 2018, 2020. # # 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 73035257d..e6fcec22c 100644 --- a/ibm_watson/websocket/synthesize_listener.py +++ b/ibm_watson/websocket/synthesize_listener.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2018, 2019. +# (C) Copyright IBM Corp. 2018, 2020. # # 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/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 7f954261f..217d21e46 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -13,92 +13,276 @@ # See the License for the specific language governing permissions and # limitations under the License. -from datetime import datetime +""" +Unit Tests for AssistantV1 +""" + +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect import json import pytest +import re +import requests import responses -import ibm_watson.assistant_v1 +import urllib from ibm_watson.assistant_v1 import * +version = 'testString' + +service = AssistantV1( + authenticator=NoAuthAuthenticator(), + version=version + ) + base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: Message ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for message -#----------------------------------------------------------------------------- class TestMessage(): + """ + Test Class for message + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_message_response(self): - body = self.construct_full_body() - response = fake_response_MessageResponse_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_message_all_params(self): + """ + message() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/message') + mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a MessageInput model + message_input_model = {} + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a RuntimeIntent model + runtime_intent_model = {} + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + # Construct a dict representation of a CaptureGroup model + capture_group_model = {} + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + # Construct a dict representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model = {} + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + # Construct a dict representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model = {} + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + # Construct a dict representation of a RuntimeEntityRole model + runtime_entity_role_model = {} + runtime_entity_role_model['type'] = 'date_from' + + # Construct a dict representation of a RuntimeEntity model + runtime_entity_model = {} + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + # Construct a dict representation of a MessageContextMetadata model + message_context_metadata_model = {} + message_context_metadata_model['deployment'] = 'testString' + message_context_metadata_model['user_id'] = 'testString' + + # Construct a dict representation of a Context model + context_model = {} + context_model['conversation_id'] = 'testString' + context_model['system'] = {} + context_model['metadata'] = message_context_metadata_model + context_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeVisitedDetails model + dialog_node_visited_details_model = {} + dialog_node_visited_details_model['dialog_node'] = 'testString' + dialog_node_visited_details_model['title'] = 'testString' + dialog_node_visited_details_model['conditions'] = 'testString' + + # Construct a dict representation of a LogMessage model + log_message_model = {} + log_message_model['level'] = 'info' + log_message_model['msg'] = 'testString' + + # Construct a dict representation of a DialogNodeOutputOptionsElementValue model + dialog_node_output_options_element_value_model = {} + dialog_node_output_options_element_value_model['input'] = message_input_model + dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] + dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] + + # Construct a dict representation of a DialogNodeOutputOptionsElement model + dialog_node_output_options_element_model = {} + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + # Construct a dict representation of a RuntimeResponseGenericRuntimeResponseTypeOption model + runtime_response_generic_model = {} + runtime_response_generic_model['response_type'] = 'option' + runtime_response_generic_model['title'] = 'testString' + runtime_response_generic_model['description'] = 'testString' + runtime_response_generic_model['preference'] = 'dropdown' + runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + + # Construct a dict representation of a OutputData model + output_data_model = {} + output_data_model['nodes_visited'] = ['testString'] + output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] + output_data_model['log_messages'] = [log_message_model] + output_data_model['text'] = ['testString'] + output_data_model['generic'] = [runtime_response_generic_model] + output_data_model['foo'] = { 'foo': 'bar' } + + # Set up parameter values + workspace_id = 'testString' + input = message_input_model + intents = [runtime_intent_model] + entities = [runtime_entity_model] + alternate_intents = True + context = context_model + output = output_data_model + nodes_visited_details = True + + # Invoke method + response = service.message( + workspace_id, + input=input, + intents=intents, + entities=entities, + alternate_intents=alternate_intents, + context=context, + output=output, + nodes_visited_details=nodes_visited_details, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'nodes_visited_details={}'.format('true' if nodes_visited_details else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == message_input_model + assert req_body['intents'] == [runtime_intent_model] + assert req_body['entities'] == [runtime_entity_model] + assert req_body['alternate_intents'] == True + assert req_body['context'] == context_model + assert req_body['output'] == output_data_model + + + @responses.activate + def test_message_required_params(self): + """ + test_message_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/message') + mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_message_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_MessageResponse_json - send_request(self, body, response) + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = service.message( + workspace_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_message_empty(self): - check_empty_required_params(self, fake_response_MessageResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_message_value_error(self): + """ + test_message_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/message') + mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/message'.format(body['workspace_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.message(**req_copy) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.message(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body.update({"input": MessageInput._from_dict(json.loads("""{"text": "fake_text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "fake_suggested_text", "original_text": "fake_original_text"}""")), "intents": [], "entities": [], "alternate_intents": True, "context": Context._from_dict(json.loads("""{"conversation_id": "fake_conversation_id", "system": {}, "metadata": {"deployment": "fake_deployment", "user_id": "fake_user_id"}}""")), "output": OutputData._from_dict(json.loads("""{"nodes_visited": [], "nodes_visited_details": [], "log_messages": [], "text": [], "generic": []}""")), }) - body['nodes_visited_details'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - return body # endregion @@ -111,361 +295,829 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_workspaces -#----------------------------------------------------------------------------- class TestListWorkspaces(): + """ + Test Class for list_workspaces + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_workspaces_response(self): - body = self.construct_full_body() - response = fake_response_WorkspaceCollection_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_workspaces_all_params(self): + """ + list_workspaces() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces') + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + page_limit = 38 + include_count = True + sort = 'name' + cursor = 'testString' + include_audit = True + + # Invoke method + response = service.list_workspaces( + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_list_workspaces_required_params(self): + """ + test_list_workspaces_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces') + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_workspaces_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_WorkspaceCollection_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Invoke method + response = service.list_workspaces() - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_workspaces_empty(self): - check_empty_response(self) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_workspaces_value_error(self): + """ + test_list_workspaces_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces') + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.list_workspaces(**body) - return output - - def construct_full_body(self): - body = dict() - body['page_limit'] = 12345 - body['include_count'] = True - body['sort'] = "string1" - body['cursor'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_workspace -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_workspaces(**req_copy) + + + class TestCreateWorkspace(): + """ + Test Class for create_workspace + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_workspace_response(self): - body = self.construct_full_body() - response = fake_response_Workspace_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_workspace_all_params(self): + """ + create_workspace() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Construct a dict representation of a DialogNode model + dialog_node_model = {} + dialog_node_model['dialog_node'] = 'testString' + dialog_node_model['description'] = 'testString' + dialog_node_model['conditions'] = 'testString' + dialog_node_model['parent'] = 'testString' + dialog_node_model['previous_sibling'] = 'testString' + dialog_node_model['output'] = dialog_node_output_model + dialog_node_model['context'] = dialog_node_context_model + dialog_node_model['metadata'] = {} + dialog_node_model['next_step'] = dialog_node_next_step_model + dialog_node_model['title'] = 'testString' + dialog_node_model['type'] = 'standard' + dialog_node_model['event_name'] = 'focus' + dialog_node_model['variable'] = 'testString' + dialog_node_model['actions'] = [dialog_node_action_model] + dialog_node_model['digress_in'] = 'not_available' + dialog_node_model['digress_out'] = 'allow_returning' + dialog_node_model['digress_out_slots'] = 'not_allowed' + dialog_node_model['user_label'] = 'testString' + dialog_node_model['disambiguation_opt_out'] = True + + # Construct a dict representation of a Counterexample model + counterexample_model = {} + counterexample_model['text'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsTooling model + workspace_system_settings_tooling_model = {} + workspace_system_settings_tooling_model['store_generic_responses'] = True + + # Construct a dict representation of a WorkspaceSystemSettingsDisambiguation model + workspace_system_settings_disambiguation_model = {} + workspace_system_settings_disambiguation_model['prompt'] = 'testString' + workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model['enabled'] = True + workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model['randomize'] = True + workspace_system_settings_disambiguation_model['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsSystemEntities model + workspace_system_settings_system_entities_model = {} + workspace_system_settings_system_entities_model['enabled'] = True + + # Construct a dict representation of a WorkspaceSystemSettingsOffTopic model + workspace_system_settings_off_topic_model = {} + workspace_system_settings_off_topic_model['enabled'] = True + + # Construct a dict representation of a WorkspaceSystemSettings model + workspace_system_settings_model = {} + workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model + workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model + workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['spelling_suggestions'] = True + workspace_system_settings_model['spelling_auto_correct'] = True + workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model + workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + # Construct a dict representation of a Webhook model + webhook_model = {} + webhook_model['url'] = 'testString' + webhook_model['name'] = 'testString' + webhook_model['headers'] = [webhook_header_model] + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Construct a dict representation of a CreateIntent model + create_intent_model = {} + create_intent_model['intent'] = 'testString' + create_intent_model['description'] = 'testString' + create_intent_model['examples'] = [example_model] + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Construct a dict representation of a CreateEntity model + create_entity_model = {} + create_entity_model['entity'] = 'testString' + create_entity_model['description'] = 'testString' + create_entity_model['metadata'] = {} + create_entity_model['fuzzy_match'] = True + create_entity_model['values'] = [create_value_model] + + # Set up parameter values + name = 'testString' + description = 'testString' + language = 'testString' + dialog_nodes = [dialog_node_model] + counterexamples = [counterexample_model] + metadata = {} + learning_opt_out = True + system_settings = workspace_system_settings_model + webhooks = [webhook_model] + intents = [create_intent_model] + entities = [create_entity_model] + include_audit = True + + # Invoke method + response = service.create_workspace( + name=name, + description=description, + language=language, + dialog_nodes=dialog_nodes, + counterexamples=counterexamples, + metadata=metadata, + learning_opt_out=learning_opt_out, + system_settings=system_settings, + webhooks=webhooks, + intents=intents, + entities=entities, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['language'] == 'testString' + assert req_body['dialog_nodes'] == [dialog_node_model] + assert req_body['counterexamples'] == [counterexample_model] + assert req_body['metadata'] == {} + assert req_body['learning_opt_out'] == True + assert req_body['system_settings'] == workspace_system_settings_model + assert req_body['webhooks'] == [webhook_model] + assert req_body['intents'] == [create_intent_model] + assert req_body['entities'] == [create_entity_model] + + + @responses.activate + def test_create_workspace_required_params(self): + """ + test_create_workspace_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_workspace_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Workspace_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Invoke method + response = service.create_workspace() - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_workspace_empty(self): - check_empty_response(self) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_create_workspace_value_error(self): + """ + test_create_workspace_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.create_workspace(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"name": "string1", "description": "string1", "language": "string1", "dialog_nodes": [], "counterexamples": [], "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "webhooks": [], "intents": [], "entities": [], }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_workspace -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=201) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_workspace(**req_copy) + + + class TestGetWorkspace(): + """ + Test Class for get_workspace + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_workspace_response(self): - body = self.construct_full_body() - response = fake_response_Workspace_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_workspace_all_params(self): + """ + get_workspace() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + export = True + include_audit = True + sort = 'stable' + + # Invoke method + response = service.get_workspace( + workspace_id, + export=export, + include_audit=include_audit, + sort=sort, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'export={}'.format('true' if export else 'false') in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + + + @responses.activate + def test_get_workspace_required_params(self): + """ + test_get_workspace_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_workspace_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Workspace_json - send_request(self, body, response) + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = service.get_workspace( + workspace_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_workspace_empty(self): - check_empty_required_params(self, fake_response_Workspace_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_workspace_value_error(self): + """ + test_get_workspace_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_workspace(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}'.format(body['workspace_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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.get_workspace(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['export'] = True - body['include_audit'] = True - body['sort'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_workspace -#----------------------------------------------------------------------------- class TestUpdateWorkspace(): + """ + Test Class for update_workspace + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_workspace_response(self): - body = self.construct_full_body() - response = fake_response_Workspace_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_workspace_all_params(self): + """ + update_workspace() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Construct a dict representation of a DialogNode model + dialog_node_model = {} + dialog_node_model['dialog_node'] = 'testString' + dialog_node_model['description'] = 'testString' + dialog_node_model['conditions'] = 'testString' + dialog_node_model['parent'] = 'testString' + dialog_node_model['previous_sibling'] = 'testString' + dialog_node_model['output'] = dialog_node_output_model + dialog_node_model['context'] = dialog_node_context_model + dialog_node_model['metadata'] = {} + dialog_node_model['next_step'] = dialog_node_next_step_model + dialog_node_model['title'] = 'testString' + dialog_node_model['type'] = 'standard' + dialog_node_model['event_name'] = 'focus' + dialog_node_model['variable'] = 'testString' + dialog_node_model['actions'] = [dialog_node_action_model] + dialog_node_model['digress_in'] = 'not_available' + dialog_node_model['digress_out'] = 'allow_returning' + dialog_node_model['digress_out_slots'] = 'not_allowed' + dialog_node_model['user_label'] = 'testString' + dialog_node_model['disambiguation_opt_out'] = True + + # Construct a dict representation of a Counterexample model + counterexample_model = {} + counterexample_model['text'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsTooling model + workspace_system_settings_tooling_model = {} + workspace_system_settings_tooling_model['store_generic_responses'] = True + + # Construct a dict representation of a WorkspaceSystemSettingsDisambiguation model + workspace_system_settings_disambiguation_model = {} + workspace_system_settings_disambiguation_model['prompt'] = 'testString' + workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model['enabled'] = True + workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model['randomize'] = True + workspace_system_settings_disambiguation_model['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsSystemEntities model + workspace_system_settings_system_entities_model = {} + workspace_system_settings_system_entities_model['enabled'] = True + + # Construct a dict representation of a WorkspaceSystemSettingsOffTopic model + workspace_system_settings_off_topic_model = {} + workspace_system_settings_off_topic_model['enabled'] = True + + # Construct a dict representation of a WorkspaceSystemSettings model + workspace_system_settings_model = {} + workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model + workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model + workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['spelling_suggestions'] = True + workspace_system_settings_model['spelling_auto_correct'] = True + workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model + workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + # Construct a dict representation of a Webhook model + webhook_model = {} + webhook_model['url'] = 'testString' + webhook_model['name'] = 'testString' + webhook_model['headers'] = [webhook_header_model] + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Construct a dict representation of a CreateIntent model + create_intent_model = {} + create_intent_model['intent'] = 'testString' + create_intent_model['description'] = 'testString' + create_intent_model['examples'] = [example_model] + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Construct a dict representation of a CreateEntity model + create_entity_model = {} + create_entity_model['entity'] = 'testString' + create_entity_model['description'] = 'testString' + create_entity_model['metadata'] = {} + create_entity_model['fuzzy_match'] = True + create_entity_model['values'] = [create_value_model] + + # Set up parameter values + workspace_id = 'testString' + name = 'testString' + description = 'testString' + language = 'testString' + dialog_nodes = [dialog_node_model] + counterexamples = [counterexample_model] + metadata = {} + learning_opt_out = True + system_settings = workspace_system_settings_model + webhooks = [webhook_model] + intents = [create_intent_model] + entities = [create_entity_model] + append = True + include_audit = True + + # Invoke method + response = service.update_workspace( + workspace_id, + name=name, + description=description, + language=language, + dialog_nodes=dialog_nodes, + counterexamples=counterexamples, + metadata=metadata, + learning_opt_out=learning_opt_out, + system_settings=system_settings, + webhooks=webhooks, + intents=intents, + entities=entities, + append=append, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'append={}'.format('true' if append else 'false') in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['language'] == 'testString' + assert req_body['dialog_nodes'] == [dialog_node_model] + assert req_body['counterexamples'] == [counterexample_model] + assert req_body['metadata'] == {} + assert req_body['learning_opt_out'] == True + assert req_body['system_settings'] == workspace_system_settings_model + assert req_body['webhooks'] == [webhook_model] + assert req_body['intents'] == [create_intent_model] + assert req_body['entities'] == [create_entity_model] + + + @responses.activate + def test_update_workspace_required_params(self): + """ + test_update_workspace_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_workspace_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Workspace_json - send_request(self, body, response) + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = service.update_workspace( + workspace_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_workspace_empty(self): - check_empty_required_params(self, fake_response_Workspace_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_update_workspace_value_error(self): + """ + test_update_workspace_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_workspace(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}'.format(body['workspace_id']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.update_workspace(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body.update({"name": "string1", "description": "string1", "language": "string1", "dialog_nodes": [], "counterexamples": [], "metadata": {"mock": "data"}, "learning_opt_out": True, "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}""")), "webhooks": [], "intents": [], "entities": [], }) - body['append'] = True - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_workspace -#----------------------------------------------------------------------------- class TestDeleteWorkspace(): + """ + Test Class for delete_workspace + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_workspace_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_workspace_all_params(self): + """ + delete_workspace() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString') + responses.add(responses.DELETE, + url, + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_workspace_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = service.delete_workspace( + workspace_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_workspace_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_workspace_value_error(self): + """ + test_delete_workspace_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}'.format(body['workspace_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_workspace(**req_copy) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.delete_workspace(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - return body # endregion @@ -478,375 +1130,632 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_intents -#----------------------------------------------------------------------------- class TestListIntents(): + """ + Test Class for list_intents + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_intents_response(self): - body = self.construct_full_body() - response = fake_response_IntentCollection_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_intents_all_params(self): + """ + list_intents() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + export = True + page_limit = 38 + include_count = True + sort = 'intent' + cursor = 'testString' + include_audit = True + + # Invoke method + response = service.list_intents( + workspace_id, + export=export, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'export={}'.format('true' if export else 'false') in query_string + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_list_intents_required_params(self): + """ + test_list_intents_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_intents_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_IntentCollection_json - send_request(self, body, response) + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = service.list_intents( + workspace_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_intents_empty(self): - check_empty_required_params(self, fake_response_IntentCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_intents_value_error(self): + """ + test_list_intents_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_intents(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents'.format(body['workspace_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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.list_intents(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['export'] = True - body['page_limit'] = 12345 - body['include_count'] = True - body['sort'] = "string1" - body['cursor'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_intent -#----------------------------------------------------------------------------- class TestCreateIntent(): + """ + Test Class for create_intent + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_intent_response(self): - body = self.construct_full_body() - response = fake_response_Intent_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_intent_all_params(self): + """ + create_intent() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + description = 'testString' + examples = [example_model] + include_audit = True + + # Invoke method + response = service.create_intent( + workspace_id, + intent, + description=description, + examples=examples, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_intent_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Intent_json - send_request(self, body, response) + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['intent'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['examples'] == [example_model] + + + @responses.activate + def test_create_intent_required_params(self): + """ + test_create_intent_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + description = 'testString' + examples = [example_model] + + # Invoke method + response = service.create_intent( + workspace_id, + intent, + description=description, + examples=examples, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['intent'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['examples'] == [example_model] + + + @responses.activate + def test_create_intent_value_error(self): + """ + test_create_intent_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + description = 'testString' + examples = [example_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "intent": intent, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_intent(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_intent_empty(self): - check_empty_required_params(self, fake_response_Intent_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents'.format(body['workspace_id']) - 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=201, - content_type='application/json') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.create_intent(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body.update({"intent": "string1", "description": "string1", "examples": [], }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body.update({"intent": "string1", "description": "string1", "examples": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_intent -#----------------------------------------------------------------------------- class TestGetIntent(): + """ + Test Class for get_intent + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_intent_response(self): - body = self.construct_full_body() - response = fake_response_Intent_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_intent_all_params(self): + """ + get_intent() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + export = True + include_audit = True + + # Invoke method + response = service.get_intent( + workspace_id, + intent, + export=export, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_intent_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Intent_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'export={}'.format('true' if export else 'false') in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_get_intent_required_params(self): + """ + test_get_intent_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + + # Invoke method + response = service.get_intent( + workspace_id, + intent, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_intent_empty(self): - check_empty_required_params(self, fake_response_Intent_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_intent_value_error(self): + """ + test_get_intent_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "intent": intent, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_intent(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.get_intent(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body['export'] = True - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_intent -#----------------------------------------------------------------------------- class TestUpdateIntent(): + """ + Test Class for update_intent + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_intent_response(self): - body = self.construct_full_body() - response = fake_response_Intent_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_intent_all_params(self): + """ + update_intent() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + new_intent = 'testString' + new_description = 'testString' + new_examples = [example_model] + append = True + include_audit = True + + # Invoke method + response = service.update_intent( + workspace_id, + intent, + new_intent=new_intent, + new_description=new_description, + new_examples=new_examples, + append=append, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_intent_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Intent_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'append={}'.format('true' if append else 'false') in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['intent'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['examples'] == [example_model] + + + @responses.activate + def test_update_intent_required_params(self): + """ + test_update_intent_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + new_intent = 'testString' + new_description = 'testString' + new_examples = [example_model] + + # Invoke method + response = service.update_intent( + workspace_id, + intent, + new_intent=new_intent, + new_description=new_description, + new_examples=new_examples, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['intent'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['examples'] == [example_model] + + + @responses.activate + def test_update_intent_value_error(self): + """ + test_update_intent_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + new_intent = 'testString' + new_description = 'testString' + new_examples = [example_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "intent": intent, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_intent(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_intent_empty(self): - check_empty_required_params(self, fake_response_Intent_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.update_intent(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) - body['append'] = True - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body.update({"new_intent": "string1", "new_description": "string1", "new_examples": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_intent -#----------------------------------------------------------------------------- class TestDeleteIntent(): + """ + Test Class for delete_intent + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_intent_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_intent_all_params(self): + """ + delete_intent() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') + responses.add(responses.DELETE, + url, + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_intent_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + + # Invoke method + response = service.delete_intent( + workspace_id, + intent, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_intent_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_intent_value_error(self): + """ + test_delete_intent_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}'.format(body['workspace_id'], body['intent']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "intent": intent, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_intent(**req_copy) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.delete_intent(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - return body # endregion @@ -859,382 +1768,607 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_examples -#----------------------------------------------------------------------------- class TestListExamples(): + """ + Test Class for list_examples + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_examples_response(self): - body = self.construct_full_body() - response = fake_response_ExampleCollection_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_examples_all_params(self): + """ + list_examples() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + page_limit = 38 + include_count = True + sort = 'text' + cursor = 'testString' + include_audit = True + + # Invoke method + response = service.list_examples( + workspace_id, + intent, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_examples_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ExampleCollection_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_list_examples_required_params(self): + """ + test_list_examples_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + + # Invoke method + response = service.list_examples( + workspace_id, + intent, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_examples_empty(self): - check_empty_required_params(self, fake_response_ExampleCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_examples_value_error(self): + """ + test_list_examples_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "intent": intent, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_examples(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.list_examples(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body['page_limit'] = 12345 - body['include_count'] = True - body['sort'] = "string1" - body['cursor'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_example -#----------------------------------------------------------------------------- class TestCreateExample(): + """ + Test Class for create_example + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_example_response(self): - body = self.construct_full_body() - response = fake_response_Example_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_example_all_params(self): + """ + create_example() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + text = 'testString' + mentions = [mention_model] + include_audit = True + + # Invoke method + response = service.create_example( + workspace_id, + intent, + text, + mentions=mentions, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_example_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Example_json - send_request(self, body, response) + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == 'testString' + assert req_body['mentions'] == [mention_model] + + + @responses.activate + def test_create_example_required_params(self): + """ + test_create_example_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + text = 'testString' + mentions = [mention_model] + + # Invoke method + response = service.create_example( + workspace_id, + intent, + text, + mentions=mentions, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == 'testString' + assert req_body['mentions'] == [mention_model] + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_example_empty(self): - check_empty_required_params(self, fake_response_Example_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_create_example_value_error(self): + """ + test_create_example_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + text = 'testString' + mentions = [mention_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "intent": intent, + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_example(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples'.format(body['workspace_id'], body['intent']) - 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=201, - content_type='application/json') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.create_example(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body.update({"text": "string1", "mentions": [], }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body.update({"text": "string1", "mentions": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_example -#----------------------------------------------------------------------------- class TestGetExample(): + """ + Test Class for get_example + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_example_response(self): - body = self.construct_full_body() - response = fake_response_Example_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_example_all_params(self): + """ + get_example() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + text = 'testString' + include_audit = True + + # Invoke method + response = service.get_example( + workspace_id, + intent, + text, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_example_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Example_json - send_request(self, body, response) + def test_get_example_required_params(self): + """ + test_get_example_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + text = 'testString' + + # Invoke method + response = service.get_example( + workspace_id, + intent, + text, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_example_empty(self): - check_empty_required_params(self, fake_response_Example_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_example_value_error(self): + """ + test_get_example_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + text = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "intent": intent, + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_example(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.get_example(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body['text'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body['text'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_example -#----------------------------------------------------------------------------- class TestUpdateExample(): + """ + Test Class for update_example + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_example_response(self): - body = self.construct_full_body() - response = fake_response_Example_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_example_all_params(self): + """ + update_example() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + text = 'testString' + new_text = 'testString' + new_mentions = [mention_model] + include_audit = True + + # Invoke method + response = service.update_example( + workspace_id, + intent, + text, + new_text=new_text, + new_mentions=new_mentions, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_example_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Example_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == 'testString' + assert req_body['mentions'] == [mention_model] + + + @responses.activate + def test_update_example_required_params(self): + """ + test_update_example_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + text = 'testString' + new_text = 'testString' + new_mentions = [mention_model] + + # Invoke method + response = service.update_example( + workspace_id, + intent, + text, + new_text=new_text, + new_mentions=new_mentions, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == 'testString' + assert req_body['mentions'] == [mention_model] + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_example_empty(self): - check_empty_required_params(self, fake_response_Example_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_update_example_value_error(self): + """ + test_update_example_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + text = 'testString' + new_text = 'testString' + new_mentions = [mention_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "intent": intent, + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_example(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.update_example(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body['text'] = "string1" - body.update({"new_text": "string1", "new_mentions": [], }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body['text'] = "string1" - body.update({"new_text": "string1", "new_mentions": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_example -#----------------------------------------------------------------------------- class TestDeleteExample(): + """ + Test Class for delete_example + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_example_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_example_all_params(self): + """ + delete_example() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + text = 'testString' + + # Invoke method + response = service.delete_example( + workspace_id, + intent, + text, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_example_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_example_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_example_value_error(self): + """ + test_delete_example_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/intents/{1}/examples/{2}'.format(body['workspace_id'], body['intent'], body['text']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + workspace_id = 'testString' + intent = 'testString' + text = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "intent": intent, + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_example(**req_copy) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.delete_example(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body['text'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['intent'] = "string1" - body['text'] = "string1" - return body # endregion @@ -1247,377 +2381,540 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_counterexamples -#----------------------------------------------------------------------------- class TestListCounterexamples(): + """ + Test Class for list_counterexamples + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_counterexamples_response(self): - body = self.construct_full_body() - response = fake_response_CounterexampleCollection_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_counterexamples_all_params(self): + """ + list_counterexamples() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + page_limit = 38 + include_count = True + sort = 'text' + cursor = 'testString' + include_audit = True + + # Invoke method + response = service.list_counterexamples( + workspace_id, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_list_counterexamples_required_params(self): + """ + test_list_counterexamples_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_counterexamples_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_CounterexampleCollection_json - send_request(self, body, response) + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = service.list_counterexamples( + workspace_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_counterexamples_empty(self): - check_empty_required_params(self, fake_response_CounterexampleCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_counterexamples_value_error(self): + """ + test_list_counterexamples_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_counterexamples(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.list_counterexamples(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['page_limit'] = 12345 - body['include_count'] = True - body['sort'] = "string1" - body['cursor'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_counterexample -#----------------------------------------------------------------------------- class TestCreateCounterexample(): + """ + Test Class for create_counterexample + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_counterexample_response(self): - body = self.construct_full_body() - response = fake_response_Counterexample_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_counterexample_all_params(self): + """ + create_counterexample() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + workspace_id = 'testString' + text = 'testString' + include_audit = True + + # Invoke method + response = service.create_counterexample( + workspace_id, + text, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_counterexample_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Counterexample_json - send_request(self, body, response) + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == 'testString' + + + @responses.activate + def test_create_counterexample_required_params(self): + """ + test_create_counterexample_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + workspace_id = 'testString' + text = 'testString' + + # Invoke method + response = service.create_counterexample( + workspace_id, + text, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_counterexample_empty(self): - check_empty_required_params(self, fake_response_Counterexample_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_create_counterexample_value_error(self): + """ + test_create_counterexample_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + workspace_id = 'testString' + text = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_counterexample(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples'.format(body['workspace_id']) - 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=201, - content_type='application/json') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.create_counterexample(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body.update({"text": "string1", }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body.update({"text": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_counterexample -#----------------------------------------------------------------------------- class TestGetCounterexample(): + """ + Test Class for get_counterexample + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_counterexample_response(self): - body = self.construct_full_body() - response = fake_response_Counterexample_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_counterexample_all_params(self): + """ + get_counterexample() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + text = 'testString' + include_audit = True + + # Invoke method + response = service.get_counterexample( + workspace_id, + text, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_counterexample_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Counterexample_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_counterexample_empty(self): - check_empty_required_params(self, fake_response_Counterexample_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_counterexample_required_params(self): + """ + test_get_counterexample_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + text = 'testString' + + # Invoke method + response = service.get_counterexample( + workspace_id, + text, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_get_counterexample_value_error(self): + """ + test_get_counterexample_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.get_counterexample(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['text'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['text'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_counterexample -#----------------------------------------------------------------------------- -class TestUpdateCounterexample(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_counterexample_response(self): - body = self.construct_full_body() - response = fake_response_Counterexample_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + workspace_id = 'testString' + text = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_counterexample_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Counterexample_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_counterexample(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_counterexample_empty(self): - check_empty_required_params(self, fake_response_Counterexample_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.update_counterexample(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['text'] = "string1" - body.update({"new_text": "string1", }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['text'] = "string1" - body.update({"new_text": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_counterexample -#----------------------------------------------------------------------------- -class TestDeleteCounterexample(): +class TestUpdateCounterexample(): + """ + Test Class for update_counterexample + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_counterexample_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_counterexample_all_params(self): + """ + update_counterexample() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + text = 'testString' + new_text = 'testString' + include_audit = True + + # Invoke method + response = service.update_counterexample( + workspace_id, + text, + new_text=new_text, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_counterexample_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == 'testString' + + + @responses.activate + def test_update_counterexample_required_params(self): + """ + test_update_counterexample_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + text = 'testString' + new_text = 'testString' + + # Invoke method + response = service.update_counterexample( + workspace_id, + text, + new_text=new_text, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_counterexample_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_update_counterexample_value_error(self): + """ + test_update_counterexample_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/counterexamples/{1}'.format(body['workspace_id'], body['text']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + workspace_id = 'testString' + text = 'testString' + new_text = 'testString' - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.delete_counterexample(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['text'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['text'] = "string1" - return body + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_counterexample(**req_copy) -# endregion -############################################################################## -# End of Service: Counterexamples + +class TestDeleteCounterexample(): + """ + Test Class for delete_counterexample + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_counterexample_all_params(self): + """ + delete_counterexample() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + workspace_id = 'testString' + text = 'testString' + + # Invoke method + response = service.delete_counterexample( + workspace_id, + text, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_delete_counterexample_value_error(self): + """ + test_delete_counterexample_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + workspace_id = 'testString' + text = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_counterexample(**req_copy) + + + +# endregion +############################################################################## +# End of Service: Counterexamples ############################################################################## ############################################################################## @@ -1625,375 +2922,648 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_entities -#----------------------------------------------------------------------------- class TestListEntities(): + """ + Test Class for list_entities + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_entities_response(self): - body = self.construct_full_body() - response = fake_response_EntityCollection_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_entities_all_params(self): + """ + list_entities() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + export = True + page_limit = 38 + include_count = True + sort = 'entity' + cursor = 'testString' + include_audit = True + + # Invoke method + response = service.list_entities( + workspace_id, + export=export, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'export={}'.format('true' if export else 'false') in query_string + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_list_entities_required_params(self): + """ + test_list_entities_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_entities_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_EntityCollection_json - send_request(self, body, response) + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = service.list_entities( + workspace_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_entities_empty(self): - check_empty_required_params(self, fake_response_EntityCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_entities_value_error(self): + """ + test_list_entities_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_entities(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities'.format(body['workspace_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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.list_entities(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['export'] = True - body['page_limit'] = 12345 - body['include_count'] = True - body['sort'] = "string1" - body['cursor'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_entity -#----------------------------------------------------------------------------- class TestCreateEntity(): + """ + Test Class for create_entity + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_entity_response(self): - body = self.construct_full_body() - response = fake_response_Entity_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_entity_all_params(self): + """ + create_entity() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + description = 'testString' + metadata = {} + fuzzy_match = True + values = [create_value_model] + include_audit = True + + # Invoke method + response = service.create_entity( + workspace_id, + entity, + description=description, + metadata=metadata, + fuzzy_match=fuzzy_match, + values=values, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_entity_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Entity_json - send_request(self, body, response) + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['entity'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['metadata'] == {} + assert req_body['fuzzy_match'] == True + assert req_body['values'] == [create_value_model] + + + @responses.activate + def test_create_entity_required_params(self): + """ + test_create_entity_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + description = 'testString' + metadata = {} + fuzzy_match = True + values = [create_value_model] + + # Invoke method + response = service.create_entity( + workspace_id, + entity, + description=description, + metadata=metadata, + fuzzy_match=fuzzy_match, + values=values, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['entity'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['metadata'] == {} + assert req_body['fuzzy_match'] == True + assert req_body['values'] == [create_value_model] + + + @responses.activate + def test_create_entity_value_error(self): + """ + test_create_entity_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + description = 'testString' + metadata = {} + fuzzy_match = True + values = [create_value_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_entity(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_entity_empty(self): - check_empty_required_params(self, fake_response_Entity_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities'.format(body['workspace_id']) - 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=201, - content_type='application/json') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.create_entity(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body.update({"entity": "string1", "description": "string1", "metadata": {"mock": "data"}, "fuzzy_match": True, "values": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_entity -#----------------------------------------------------------------------------- class TestGetEntity(): + """ + Test Class for get_entity + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_entity_response(self): - body = self.construct_full_body() - response = fake_response_Entity_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_entity_all_params(self): + """ + get_entity() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + export = True + include_audit = True + + # Invoke method + response = service.get_entity( + workspace_id, + entity, + export=export, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_entity_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Entity_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'export={}'.format('true' if export else 'false') in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_get_entity_required_params(self): + """ + test_get_entity_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + + # Invoke method + response = service.get_entity( + workspace_id, + entity, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_entity_empty(self): - check_empty_required_params(self, fake_response_Entity_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_entity_value_error(self): + """ + test_get_entity_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_entity(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.get_entity(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['export'] = True - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_entity -#----------------------------------------------------------------------------- class TestUpdateEntity(): + """ + Test Class for update_entity + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_entity_response(self): - body = self.construct_full_body() - response = fake_response_Entity_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_entity_all_params(self): + """ + update_entity() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + new_entity = 'testString' + new_description = 'testString' + new_metadata = {} + new_fuzzy_match = True + new_values = [create_value_model] + append = True + include_audit = True + + # Invoke method + response = service.update_entity( + workspace_id, + entity, + new_entity=new_entity, + new_description=new_description, + new_metadata=new_metadata, + new_fuzzy_match=new_fuzzy_match, + new_values=new_values, + append=append, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_entity_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Entity_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'append={}'.format('true' if append else 'false') in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['entity'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['metadata'] == {} + assert req_body['fuzzy_match'] == True + assert req_body['values'] == [create_value_model] + + + @responses.activate + def test_update_entity_required_params(self): + """ + test_update_entity_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + new_entity = 'testString' + new_description = 'testString' + new_metadata = {} + new_fuzzy_match = True + new_values = [create_value_model] + + # Invoke method + response = service.update_entity( + workspace_id, + entity, + new_entity=new_entity, + new_description=new_description, + new_metadata=new_metadata, + new_fuzzy_match=new_fuzzy_match, + new_values=new_values, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['entity'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['metadata'] == {} + assert req_body['fuzzy_match'] == True + assert req_body['values'] == [create_value_model] + + + @responses.activate + def test_update_entity_value_error(self): + """ + test_update_entity_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + new_entity = 'testString' + new_description = 'testString' + new_metadata = {} + new_fuzzy_match = True + new_values = [create_value_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_entity(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_entity_empty(self): - check_empty_required_params(self, fake_response_Entity_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.update_entity(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) - body['append'] = True - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body.update({"new_entity": "string1", "new_description": "string1", "new_metadata": {"mock": "data"}, "new_fuzzy_match": True, "new_values": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_entity -#----------------------------------------------------------------------------- class TestDeleteEntity(): + """ + Test Class for delete_entity + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_entity_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_entity_all_params(self): + """ + delete_entity() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') + responses.add(responses.DELETE, + url, + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_entity_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + + # Invoke method + response = service.delete_entity( + workspace_id, + entity, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_entity_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_entity_value_error(self): + """ + test_delete_entity_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}'.format(body['workspace_id'], body['entity']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_entity(**req_copy) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.delete_entity(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - return body # endregion @@ -2006,78 +3576,117 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_mentions -#----------------------------------------------------------------------------- class TestListMentions(): + """ + Test Class for list_mentions + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_mentions_response(self): - body = self.construct_full_body() - response = fake_response_EntityMentionCollection_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_mentions_all_params(self): + """ + list_mentions() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/mentions') + mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + export = True + include_audit = True + + # Invoke method + response = service.list_mentions( + workspace_id, + entity, + export=export, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_mentions_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_EntityMentionCollection_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'export={}'.format('true' if export else 'false') in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_list_mentions_required_params(self): + """ + test_list_mentions_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/mentions') + mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + + # Invoke method + response = service.list_mentions( + workspace_id, + entity, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_mentions_empty(self): - check_empty_required_params(self, fake_response_EntityMentionCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_mentions_value_error(self): + """ + test_list_mentions_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/mentions') + mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/mentions'.format(body['workspace_id'], body['entity']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_mentions(**req_copy) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.list_mentions(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['export'] = True - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - return body # endregion @@ -2090,385 +3699,628 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_values -#----------------------------------------------------------------------------- class TestListValues(): + """ + Test Class for list_values + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_values_response(self): - body = self.construct_full_body() - response = fake_response_ValueCollection_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_values_all_params(self): + """ + list_values() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + export = True + page_limit = 38 + include_count = True + sort = 'value' + cursor = 'testString' + include_audit = True + + # Invoke method + response = service.list_values( + workspace_id, + entity, + export=export, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_values_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ValueCollection_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'export={}'.format('true' if export else 'false') in query_string + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_list_values_required_params(self): + """ + test_list_values_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + + # Invoke method + response = service.list_values( + workspace_id, + entity, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_values_empty(self): - check_empty_required_params(self, fake_response_ValueCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_values_value_error(self): + """ + test_list_values_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_values(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.list_values(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['export'] = True - body['page_limit'] = 12345 - body['include_count'] = True - body['sort'] = "string1" - body['cursor'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_value -#----------------------------------------------------------------------------- class TestCreateValue(): + """ + Test Class for create_value + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_value_response(self): - body = self.construct_full_body() - response = fake_response_Value_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_value_all_params(self): + """ + create_value() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + metadata = {} + type = 'synonyms' + synonyms = ['testString'] + patterns = ['testString'] + include_audit = True + + # Invoke method + response = service.create_value( + workspace_id, + entity, + value, + metadata=metadata, + type=type, + synonyms=synonyms, + patterns=patterns, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_value_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Value_json - send_request(self, body, response) + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['value'] == 'testString' + assert req_body['metadata'] == {} + assert req_body['type'] == 'synonyms' + assert req_body['synonyms'] == ['testString'] + assert req_body['patterns'] == ['testString'] + + + @responses.activate + def test_create_value_required_params(self): + """ + test_create_value_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + metadata = {} + type = 'synonyms' + synonyms = ['testString'] + patterns = ['testString'] + + # Invoke method + response = service.create_value( + workspace_id, + entity, + value, + metadata=metadata, + type=type, + synonyms=synonyms, + patterns=patterns, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['value'] == 'testString' + assert req_body['metadata'] == {} + assert req_body['type'] == 'synonyms' + assert req_body['synonyms'] == ['testString'] + assert req_body['patterns'] == ['testString'] + + + @responses.activate + def test_create_value_value_error(self): + """ + test_create_value_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + metadata = {} + type = 'synonyms' + synonyms = ['testString'] + patterns = ['testString'] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + "value": value, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_value(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_value_empty(self): - check_empty_required_params(self, fake_response_Value_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values'.format(body['workspace_id'], body['entity']) - 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=201, - content_type='application/json') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.create_value(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body.update({"value": "string1", "metadata": {"mock": "data"}, "type": "string1", "synonyms": [], "patterns": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_value -#----------------------------------------------------------------------------- class TestGetValue(): + """ + Test Class for get_value + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_value_response(self): - body = self.construct_full_body() - response = fake_response_Value_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_value_all_params(self): + """ + get_value() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + export = True + include_audit = True + + # Invoke method + response = service.get_value( + workspace_id, + entity, + value, + export=export, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_value_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Value_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'export={}'.format('true' if export else 'false') in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_get_value_required_params(self): + """ + test_get_value_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + + # Invoke method + response = service.get_value( + workspace_id, + entity, + value, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_value_empty(self): - check_empty_required_params(self, fake_response_Value_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_value_value_error(self): + """ + test_get_value_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + "value": value, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_value(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.get_value(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body['export'] = True - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_value -#----------------------------------------------------------------------------- class TestUpdateValue(): + """ + Test Class for update_value + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_value_response(self): - body = self.construct_full_body() - response = fake_response_Value_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_value_all_params(self): + """ + update_value() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + new_value = 'testString' + new_metadata = {} + new_type = 'synonyms' + new_synonyms = ['testString'] + new_patterns = ['testString'] + append = True + include_audit = True + + # Invoke method + response = service.update_value( + workspace_id, + entity, + value, + new_value=new_value, + new_metadata=new_metadata, + new_type=new_type, + new_synonyms=new_synonyms, + new_patterns=new_patterns, + append=append, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_value_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Value_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'append={}'.format('true' if append else 'false') in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['value'] == 'testString' + assert req_body['metadata'] == {} + assert req_body['type'] == 'synonyms' + assert req_body['synonyms'] == ['testString'] + assert req_body['patterns'] == ['testString'] + + + @responses.activate + def test_update_value_required_params(self): + """ + test_update_value_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + new_value = 'testString' + new_metadata = {} + new_type = 'synonyms' + new_synonyms = ['testString'] + new_patterns = ['testString'] + + # Invoke method + response = service.update_value( + workspace_id, + entity, + value, + new_value=new_value, + new_metadata=new_metadata, + new_type=new_type, + new_synonyms=new_synonyms, + new_patterns=new_patterns, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['value'] == 'testString' + assert req_body['metadata'] == {} + assert req_body['type'] == 'synonyms' + assert req_body['synonyms'] == ['testString'] + assert req_body['patterns'] == ['testString'] + + + @responses.activate + def test_update_value_value_error(self): + """ + test_update_value_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + new_value = 'testString' + new_metadata = {} + new_type = 'synonyms' + new_synonyms = ['testString'] + new_patterns = ['testString'] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + "value": value, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_value(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_value_empty(self): - check_empty_required_params(self, fake_response_Value_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.update_value(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) - body['append'] = True - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body.update({"new_value": "string1", "new_metadata": {"mock": "data"}, "new_type": "string1", "new_synonyms": [], "new_patterns": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_value -#----------------------------------------------------------------------------- class TestDeleteValue(): + """ + Test Class for delete_value + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_value_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_value_all_params(self): + """ + delete_value() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + + # Invoke method + response = service.delete_value( + workspace_id, + entity, + value, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_value_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_value_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_value_value_error(self): + """ + test_delete_value_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}'.format(body['workspace_id'], body['entity'], body['value']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + "value": value, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_value(**req_copy) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.delete_value(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - return body # endregion @@ -2481,392 +4333,591 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_synonyms -#----------------------------------------------------------------------------- class TestListSynonyms(): + """ + Test Class for list_synonyms + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_synonyms_response(self): - body = self.construct_full_body() - response = fake_response_SynonymCollection_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_synonyms_all_params(self): + """ + list_synonyms() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + page_limit = 38 + include_count = True + sort = 'synonym' + cursor = 'testString' + include_audit = True + + # Invoke method + response = service.list_synonyms( + workspace_id, + entity, + value, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_synonyms_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_SynonymCollection_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_list_synonyms_required_params(self): + """ + test_list_synonyms_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + + # Invoke method + response = service.list_synonyms( + workspace_id, + entity, + value, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_synonyms_empty(self): - check_empty_required_params(self, fake_response_SynonymCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_synonyms_value_error(self): + """ + test_list_synonyms_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + "value": value, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_synonyms(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.list_synonyms(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body['page_limit'] = 12345 - body['include_count'] = True - body['sort'] = "string1" - body['cursor'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_synonym -#----------------------------------------------------------------------------- class TestCreateSynonym(): + """ + Test Class for create_synonym + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_synonym_response(self): - body = self.construct_full_body() - response = fake_response_Synonym_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_synonym_all_params(self): + """ + create_synonym() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + synonym = 'testString' + include_audit = True + + # Invoke method + response = service.create_synonym( + workspace_id, + entity, + value, + synonym, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_synonym_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Synonym_json - send_request(self, body, response) + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['synonym'] == 'testString' + + + @responses.activate + def test_create_synonym_required_params(self): + """ + test_create_synonym_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + synonym = 'testString' + + # Invoke method + response = service.create_synonym( + workspace_id, + entity, + value, + synonym, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['synonym'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_synonym_empty(self): - check_empty_required_params(self, fake_response_Synonym_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_create_synonym_value_error(self): + """ + test_create_synonym_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + synonym = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + "value": value, + "synonym": synonym, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_synonym(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms'.format(body['workspace_id'], body['entity'], body['value']) - 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=201, - content_type='application/json') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.create_synonym(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body.update({"synonym": "string1", }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body.update({"synonym": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_synonym -#----------------------------------------------------------------------------- class TestGetSynonym(): + """ + Test Class for get_synonym + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_synonym_response(self): - body = self.construct_full_body() - response = fake_response_Synonym_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_synonym_all_params(self): + """ + get_synonym() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + synonym = 'testString' + include_audit = True + + # Invoke method + response = service.get_synonym( + workspace_id, + entity, + value, + synonym, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_synonym_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Synonym_json - send_request(self, body, response) + def test_get_synonym_required_params(self): + """ + test_get_synonym_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + synonym = 'testString' + + # Invoke method + response = service.get_synonym( + workspace_id, + entity, + value, + synonym, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_synonym_empty(self): - check_empty_required_params(self, fake_response_Synonym_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_synonym_value_error(self): + """ + test_get_synonym_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + synonym = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + "value": value, + "synonym": synonym, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_synonym(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.get_synonym(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body['synonym'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body['synonym'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_synonym -#----------------------------------------------------------------------------- class TestUpdateSynonym(): + """ + Test Class for update_synonym + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_synonym_response(self): - body = self.construct_full_body() - response = fake_response_Synonym_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_synonym_all_params(self): + """ + update_synonym() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + synonym = 'testString' + new_synonym = 'testString' + include_audit = True + + # Invoke method + response = service.update_synonym( + workspace_id, + entity, + value, + synonym, + new_synonym=new_synonym, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_synonym_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Synonym_json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['synonym'] == 'testString' + + + @responses.activate + def test_update_synonym_required_params(self): + """ + test_update_synonym_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + synonym = 'testString' + new_synonym = 'testString' + + # Invoke method + response = service.update_synonym( + workspace_id, + entity, + value, + synonym, + new_synonym=new_synonym, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['synonym'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_synonym_empty(self): - check_empty_required_params(self, fake_response_Synonym_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_update_synonym_value_error(self): + """ + test_update_synonym_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + synonym = 'testString' + new_synonym = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + "value": value, + "synonym": synonym, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_synonym(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.update_synonym(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body['synonym'] = "string1" - body.update({"new_synonym": "string1", }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body['synonym'] = "string1" - body.update({"new_synonym": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_synonym -#----------------------------------------------------------------------------- class TestDeleteSynonym(): + """ + Test Class for delete_synonym + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_synonym_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_synonym_all_params(self): + """ + delete_synonym() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + synonym = 'testString' + + # Invoke method + response = service.delete_synonym( + workspace_id, + entity, + value, + synonym, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_synonym_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_synonym_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_synonym_value_error(self): + """ + test_delete_synonym_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/entities/{1}/values/{2}/synonyms/{3}'.format(body['workspace_id'], body['entity'], body['value'], body['synonym']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + workspace_id = 'testString' + entity = 'testString' + value = 'testString' + synonym = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "entity": entity, + "value": value, + "synonym": synonym, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_synonym(**req_copy) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.delete_synonym(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body['synonym'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['entity'] = "string1" - body['value'] = "string1" - body['synonym'] = "string1" - return body # endregion @@ -2879,372 +4930,1009 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_dialog_nodes -#----------------------------------------------------------------------------- class TestListDialogNodes(): + """ + Test Class for list_dialog_nodes + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_dialog_nodes_response(self): - body = self.construct_full_body() - response = fake_response_DialogNodeCollection_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_dialog_nodes_all_params(self): + """ + list_dialog_nodes() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + page_limit = 38 + include_count = True + sort = 'dialog_node' + cursor = 'testString' + include_audit = True + + # Invoke method + response = service.list_dialog_nodes( + workspace_id, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + + @responses.activate + def test_list_dialog_nodes_required_params(self): + """ + test_list_dialog_nodes_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_dialog_nodes_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DialogNodeCollection_json - send_request(self, body, response) + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = service.list_dialog_nodes( + workspace_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_dialog_nodes_empty(self): - check_empty_required_params(self, fake_response_DialogNodeCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_dialog_nodes_value_error(self): + """ + test_list_dialog_nodes_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_dialog_nodes(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.list_dialog_nodes(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['page_limit'] = 12345 - body['include_count'] = True - body['sort'] = "string1" - body['cursor'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_dialog_node -#----------------------------------------------------------------------------- class TestCreateDialogNode(): + """ + Test Class for create_dialog_node + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_dialog_node_response(self): - body = self.construct_full_body() - response = fake_response_DialogNode_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_dialog_node_all_params(self): + """ + create_dialog_node() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Set up parameter values + workspace_id = 'testString' + dialog_node = 'testString' + description = 'testString' + conditions = 'testString' + parent = 'testString' + previous_sibling = 'testString' + output = dialog_node_output_model + context = dialog_node_context_model + metadata = {} + next_step = dialog_node_next_step_model + title = 'testString' + type = 'standard' + event_name = 'focus' + variable = 'testString' + actions = [dialog_node_action_model] + digress_in = 'not_available' + digress_out = 'allow_returning' + digress_out_slots = 'not_allowed' + user_label = 'testString' + disambiguation_opt_out = True + include_audit = True + + # Invoke method + response = service.create_dialog_node( + workspace_id, + dialog_node, + description=description, + conditions=conditions, + parent=parent, + previous_sibling=previous_sibling, + output=output, + context=context, + metadata=metadata, + next_step=next_step, + title=title, + type=type, + event_name=event_name, + variable=variable, + actions=actions, + digress_in=digress_in, + digress_out=digress_out, + digress_out_slots=digress_out_slots, + user_label=user_label, + disambiguation_opt_out=disambiguation_opt_out, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_dialog_node_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DialogNode_json - send_request(self, body, response) + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['dialog_node'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['conditions'] == 'testString' + assert req_body['parent'] == 'testString' + assert req_body['previous_sibling'] == 'testString' + assert req_body['output'] == dialog_node_output_model + assert req_body['context'] == dialog_node_context_model + assert req_body['metadata'] == {} + assert req_body['next_step'] == dialog_node_next_step_model + assert req_body['title'] == 'testString' + assert req_body['type'] == 'standard' + assert req_body['event_name'] == 'focus' + assert req_body['variable'] == 'testString' + assert req_body['actions'] == [dialog_node_action_model] + assert req_body['digress_in'] == 'not_available' + assert req_body['digress_out'] == 'allow_returning' + assert req_body['digress_out_slots'] == 'not_allowed' + assert req_body['user_label'] == 'testString' + assert req_body['disambiguation_opt_out'] == True + + + @responses.activate + def test_create_dialog_node_required_params(self): + """ + test_create_dialog_node_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Set up parameter values + workspace_id = 'testString' + dialog_node = 'testString' + description = 'testString' + conditions = 'testString' + parent = 'testString' + previous_sibling = 'testString' + output = dialog_node_output_model + context = dialog_node_context_model + metadata = {} + next_step = dialog_node_next_step_model + title = 'testString' + type = 'standard' + event_name = 'focus' + variable = 'testString' + actions = [dialog_node_action_model] + digress_in = 'not_available' + digress_out = 'allow_returning' + digress_out_slots = 'not_allowed' + user_label = 'testString' + disambiguation_opt_out = True + + # Invoke method + response = service.create_dialog_node( + workspace_id, + dialog_node, + description=description, + conditions=conditions, + parent=parent, + previous_sibling=previous_sibling, + output=output, + context=context, + metadata=metadata, + next_step=next_step, + title=title, + type=type, + event_name=event_name, + variable=variable, + actions=actions, + digress_in=digress_in, + digress_out=digress_out, + digress_out_slots=digress_out_slots, + user_label=user_label, + disambiguation_opt_out=disambiguation_opt_out, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['dialog_node'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['conditions'] == 'testString' + assert req_body['parent'] == 'testString' + assert req_body['previous_sibling'] == 'testString' + assert req_body['output'] == dialog_node_output_model + assert req_body['context'] == dialog_node_context_model + assert req_body['metadata'] == {} + assert req_body['next_step'] == dialog_node_next_step_model + assert req_body['title'] == 'testString' + assert req_body['type'] == 'standard' + assert req_body['event_name'] == 'focus' + assert req_body['variable'] == 'testString' + assert req_body['actions'] == [dialog_node_action_model] + assert req_body['digress_in'] == 'not_available' + assert req_body['digress_out'] == 'allow_returning' + assert req_body['digress_out_slots'] == 'not_allowed' + assert req_body['user_label'] == 'testString' + assert req_body['disambiguation_opt_out'] == True + + + @responses.activate + def test_create_dialog_node_value_error(self): + """ + test_create_dialog_node_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Set up parameter values + workspace_id = 'testString' + dialog_node = 'testString' + description = 'testString' + conditions = 'testString' + parent = 'testString' + previous_sibling = 'testString' + output = dialog_node_output_model + context = dialog_node_context_model + metadata = {} + next_step = dialog_node_next_step_model + title = 'testString' + type = 'standard' + event_name = 'focus' + variable = 'testString' + actions = [dialog_node_action_model] + digress_in = 'not_available' + digress_out = 'allow_returning' + digress_out_slots = 'not_allowed' + user_label = 'testString' + disambiguation_opt_out = True + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "dialog_node": dialog_node, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_dialog_node(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_dialog_node_empty(self): - check_empty_required_params(self, fake_response_DialogNode_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes'.format(body['workspace_id']) - 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=201, - content_type='application/json') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.create_dialog_node(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": DialogNodeContext._from_dict(json.loads("""{}""")), "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body.update({"dialog_node": "string1", "description": "string1", "conditions": "string1", "parent": "string1", "previous_sibling": "string1", "output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "context": DialogNodeContext._from_dict(json.loads("""{}""")), "metadata": {"mock": "data"}, "next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "title": "string1", "type": "string1", "event_name": "string1", "variable": "string1", "actions": [], "digress_in": "string1", "digress_out": "string1", "digress_out_slots": "string1", "user_label": "string1", "disambiguation_opt_out": True, }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_dialog_node -#----------------------------------------------------------------------------- class TestGetDialogNode(): + """ + Test Class for get_dialog_node + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_dialog_node_response(self): - body = self.construct_full_body() - response = fake_response_DialogNode_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_dialog_node_all_params(self): + """ + get_dialog_node() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + dialog_node = 'testString' + include_audit = True + + # Invoke method + response = service.get_dialog_node( + workspace_id, + dialog_node, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_dialog_node_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DialogNode_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_dialog_node_empty(self): - check_empty_required_params(self, fake_response_DialogNode_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_dialog_node_required_params(self): + """ + test_get_dialog_node_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + dialog_node = 'testString' + + # Invoke method + response = service.get_dialog_node( + workspace_id, + dialog_node, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_get_dialog_node_value_error(self): + """ + test_get_dialog_node_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.get_dialog_node(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['dialog_node'] = "string1" - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['dialog_node'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_dialog_node -#----------------------------------------------------------------------------- -class TestUpdateDialogNode(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_dialog_node_response(self): - body = self.construct_full_body() - response = fake_response_DialogNode_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + workspace_id = 'testString' + dialog_node = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_dialog_node_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DialogNode_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "dialog_node": dialog_node, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_dialog_node(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_dialog_node_empty(self): - check_empty_required_params(self, fake_response_DialogNode_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.update_dialog_node(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['dialog_node'] = "string1" - body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": DialogNodeContext._from_dict(json.loads("""{}""")), "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) - body['include_audit'] = True - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['dialog_node'] = "string1" - body.update({"new_dialog_node": "string1", "new_description": "string1", "new_conditions": "string1", "new_parent": "string1", "new_previous_sibling": "string1", "new_output": DialogNodeOutput._from_dict(json.loads("""{"generic": [], "modifiers": {"overwrite": false}}""")), "new_context": DialogNodeContext._from_dict(json.loads("""{}""")), "new_metadata": {"mock": "data"}, "new_next_step": DialogNodeNextStep._from_dict(json.loads("""{"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}""")), "new_title": "string1", "new_type": "string1", "new_event_name": "string1", "new_variable": "string1", "new_actions": [], "new_digress_in": "string1", "new_digress_out": "string1", "new_digress_out_slots": "string1", "new_user_label": "string1", "new_disambiguation_opt_out": True, }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_dialog_node -#----------------------------------------------------------------------------- -class TestDeleteDialogNode(): +class TestUpdateDialogNode(): + """ + Test Class for update_dialog_node + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_dialog_node_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_dialog_node_all_params(self): + """ + update_dialog_node() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Set up parameter values + workspace_id = 'testString' + dialog_node = 'testString' + new_dialog_node = 'testString' + new_description = 'testString' + new_conditions = 'testString' + new_parent = 'testString' + new_previous_sibling = 'testString' + new_output = dialog_node_output_model + new_context = dialog_node_context_model + new_metadata = {} + new_next_step = dialog_node_next_step_model + new_title = 'testString' + new_type = 'standard' + new_event_name = 'focus' + new_variable = 'testString' + new_actions = [dialog_node_action_model] + new_digress_in = 'not_available' + new_digress_out = 'allow_returning' + new_digress_out_slots = 'not_allowed' + new_user_label = 'testString' + new_disambiguation_opt_out = True + include_audit = True + + # Invoke method + response = service.update_dialog_node( + workspace_id, + dialog_node, + new_dialog_node=new_dialog_node, + new_description=new_description, + new_conditions=new_conditions, + new_parent=new_parent, + new_previous_sibling=new_previous_sibling, + new_output=new_output, + new_context=new_context, + new_metadata=new_metadata, + new_next_step=new_next_step, + new_title=new_title, + new_type=new_type, + new_event_name=new_event_name, + new_variable=new_variable, + new_actions=new_actions, + new_digress_in=new_digress_in, + new_digress_out=new_digress_out, + new_digress_out_slots=new_digress_out_slots, + new_user_label=new_user_label, + new_disambiguation_opt_out=new_disambiguation_opt_out, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_dialog_node_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['dialog_node'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['conditions'] == 'testString' + assert req_body['parent'] == 'testString' + assert req_body['previous_sibling'] == 'testString' + assert req_body['output'] == dialog_node_output_model + assert req_body['context'] == dialog_node_context_model + assert req_body['metadata'] == {} + assert req_body['next_step'] == dialog_node_next_step_model + assert req_body['title'] == 'testString' + assert req_body['type'] == 'standard' + assert req_body['event_name'] == 'focus' + assert req_body['variable'] == 'testString' + assert req_body['actions'] == [dialog_node_action_model] + assert req_body['digress_in'] == 'not_available' + assert req_body['digress_out'] == 'allow_returning' + assert req_body['digress_out_slots'] == 'not_allowed' + assert req_body['user_label'] == 'testString' + assert req_body['disambiguation_opt_out'] == True + + + @responses.activate + def test_update_dialog_node_required_params(self): + """ + test_update_dialog_node_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Set up parameter values + workspace_id = 'testString' + dialog_node = 'testString' + new_dialog_node = 'testString' + new_description = 'testString' + new_conditions = 'testString' + new_parent = 'testString' + new_previous_sibling = 'testString' + new_output = dialog_node_output_model + new_context = dialog_node_context_model + new_metadata = {} + new_next_step = dialog_node_next_step_model + new_title = 'testString' + new_type = 'standard' + new_event_name = 'focus' + new_variable = 'testString' + new_actions = [dialog_node_action_model] + new_digress_in = 'not_available' + new_digress_out = 'allow_returning' + new_digress_out_slots = 'not_allowed' + new_user_label = 'testString' + new_disambiguation_opt_out = True + + # Invoke method + response = service.update_dialog_node( + workspace_id, + dialog_node, + new_dialog_node=new_dialog_node, + new_description=new_description, + new_conditions=new_conditions, + new_parent=new_parent, + new_previous_sibling=new_previous_sibling, + new_output=new_output, + new_context=new_context, + new_metadata=new_metadata, + new_next_step=new_next_step, + new_title=new_title, + new_type=new_type, + new_event_name=new_event_name, + new_variable=new_variable, + new_actions=new_actions, + new_digress_in=new_digress_in, + new_digress_out=new_digress_out, + new_digress_out_slots=new_digress_out_slots, + new_user_label=new_user_label, + new_disambiguation_opt_out=new_disambiguation_opt_out, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['dialog_node'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['conditions'] == 'testString' + assert req_body['parent'] == 'testString' + assert req_body['previous_sibling'] == 'testString' + assert req_body['output'] == dialog_node_output_model + assert req_body['context'] == dialog_node_context_model + assert req_body['metadata'] == {} + assert req_body['next_step'] == dialog_node_next_step_model + assert req_body['title'] == 'testString' + assert req_body['type'] == 'standard' + assert req_body['event_name'] == 'focus' + assert req_body['variable'] == 'testString' + assert req_body['actions'] == [dialog_node_action_model] + assert req_body['digress_in'] == 'not_available' + assert req_body['digress_out'] == 'allow_returning' + assert req_body['digress_out_slots'] == 'not_allowed' + assert req_body['user_label'] == 'testString' + assert req_body['disambiguation_opt_out'] == True + + + @responses.activate + def test_update_dialog_node_value_error(self): + """ + test_update_dialog_node_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Set up parameter values + workspace_id = 'testString' + dialog_node = 'testString' + new_dialog_node = 'testString' + new_description = 'testString' + new_conditions = 'testString' + new_parent = 'testString' + new_previous_sibling = 'testString' + new_output = dialog_node_output_model + new_context = dialog_node_context_model + new_metadata = {} + new_next_step = dialog_node_next_step_model + new_title = 'testString' + new_type = 'standard' + new_event_name = 'focus' + new_variable = 'testString' + new_actions = [dialog_node_action_model] + new_digress_in = 'not_available' + new_digress_out = 'allow_returning' + new_digress_out_slots = 'not_allowed' + new_user_label = 'testString' + new_disambiguation_opt_out = True + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "dialog_node": dialog_node, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_dialog_node(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_dialog_node_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 = '/v1/workspaces/{0}/dialog_nodes/{1}'.format(body['workspace_id'], body['dialog_node']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): +class TestDeleteDialogNode(): + """ + Test Class for delete_dialog_node + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_dialog_node_all_params(self): + """ + delete_dialog_node() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.delete_dialog_node(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['dialog_node'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - body['dialog_node'] = "string1" - return body + url, + status=200) + + # Set up parameter values + workspace_id = 'testString' + dialog_node = 'testString' + + # Invoke method + response = service.delete_dialog_node( + workspace_id, + dialog_node, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_delete_dialog_node_value_error(self): + """ + test_delete_dialog_node_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + workspace_id = 'testString' + dialog_node = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + "dialog_node": dialog_node, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_dialog_node(**req_copy) + # endregion @@ -3257,151 +5945,232 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_logs -#----------------------------------------------------------------------------- class TestListLogs(): + """ + Test Class for list_logs + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_logs_response(self): - body = self.construct_full_body() - response = fake_response_LogCollection_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_logs_all_params(self): + """ + list_logs() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + sort = 'testString' + filter = 'testString' + page_limit = 38 + cursor = 'testString' + + # Invoke method + response = service.list_logs( + workspace_id, + sort=sort, + filter=filter, + page_limit=page_limit, + cursor=cursor, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'sort={}'.format(sort) in query_string + assert 'filter={}'.format(filter) in query_string + assert 'page_limit={}'.format(page_limit) in query_string + assert 'cursor={}'.format(cursor) in query_string + + + @responses.activate + def test_list_logs_required_params(self): + """ + test_list_logs_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_logs_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_LogCollection_json - send_request(self, body, response) + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = service.list_logs( + workspace_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_logs_empty(self): - check_empty_required_params(self, fake_response_LogCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_logs_value_error(self): + """ + test_list_logs_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_logs(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/logs'.format(body['workspace_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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.list_logs(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body['sort'] = "string1" - body['filter'] = "string1" - body['page_limit'] = 12345 - body['cursor'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_all_logs -#----------------------------------------------------------------------------- class TestListAllLogs(): + """ + Test Class for list_all_logs + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_all_logs_response(self): - body = self.construct_full_body() - response = fake_response_LogCollection_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_all_logs_all_params(self): + """ + list_all_logs() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + filter = 'testString' + sort = 'testString' + page_limit = 38 + cursor = 'testString' + + # Invoke method + response = service.list_all_logs( + filter, + sort=sort, + page_limit=page_limit, + cursor=cursor, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'filter={}'.format(filter) in query_string + assert 'sort={}'.format(sort) in query_string + assert 'page_limit={}'.format(page_limit) in query_string + assert 'cursor={}'.format(cursor) in query_string + + + @responses.activate + def test_list_all_logs_required_params(self): + """ + test_list_all_logs_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_all_logs_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_LogCollection_json - send_request(self, body, response) + # Set up parameter values + filter = 'testString' + + # Invoke method + response = service.list_all_logs( + filter, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'filter={}'.format(filter) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_all_logs_empty(self): - check_empty_required_params(self, fake_response_LogCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_all_logs_value_error(self): + """ + test_list_all_logs_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/logs' - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + filter = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "filter": filter, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_all_logs(**req_copy) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.list_all_logs(**body) - return output - - def construct_full_body(self): - body = dict() - body['filter'] = "string1" - body['sort'] = "string1" - body['page_limit'] = 12345 - body['cursor'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['filter'] = "string1" - return body # endregion @@ -3414,74 +6183,72 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for delete_user_data -#----------------------------------------------------------------------------- class TestDeleteUserData(): + """ + Test Class for delete_user_data + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_user_data_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_user_data_all_params(self): + """ + delete_user_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/user_data') + responses.add(responses.DELETE, + url, + status=202) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_user_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + # Set up parameter values + customer_id = 'testString' + + # Invoke method + response = service.delete_user_data( + customer_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'customer_id={}'.format(customer_id) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_user_data_value_error(self): + """ + test_delete_user_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/user_data') + responses.add(responses.DELETE, + url, + status=202) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/user_data' - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + customer_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customer_id": customer_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_user_data(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=202, - content_type='') - - def call_service(self, body): - service = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.delete_user_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['customer_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customer_id'] = "string1" - return body # endregion @@ -3494,75 +6261,111 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for bulk_classify -#----------------------------------------------------------------------------- class TestBulkClassify(): + """ + Test Class for bulk_classify + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_bulk_classify_response(self): - body = self.construct_full_body() - response = fake_response_BulkClassifyResponse_json - send_request(self, body, response) + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_bulk_classify_all_params(self): + """ + bulk_classify() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' + + # Set up parameter values + workspace_id = 'testString' + input = [bulk_classify_utterance_model] + + # Invoke method + response = service.bulk_classify( + workspace_id, + input=input, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == [bulk_classify_utterance_model] + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_bulk_classify_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_BulkClassifyResponse_json - send_request(self, body, response) + def test_bulk_classify_required_params(self): + """ + test_bulk_classify_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = service.bulk_classify( + workspace_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_bulk_classify_empty(self): - check_empty_required_params(self, fake_response_BulkClassifyResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_bulk_classify_value_error(self): + """ + test_bulk_classify_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/workspaces/{0}/bulk_classify'.format(body['workspace_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.bulk_classify(**req_copy) - 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 = AssistantV1( - authenticator=NoAuthAuthenticator(), - version='2020-04-01', - ) - service.set_service_url(base_url) - output = service.bulk_classify(**body) - return output - - def construct_full_body(self): - body = dict() - body['workspace_id'] = "string1" - body.update({"input": [], }) - return body - - def construct_required_body(self): - body = dict() - body['workspace_id'] = "string1" - return body # endregion @@ -3571,104 +6374,4251 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error - -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error - -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) - -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response - - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string - - """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response - -#################### -## Mock Responses ## -#################### - -fake_response__json = None -fake_response_MessageResponse_json = """{"input": {"text": "fake_text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "fake_suggested_text", "original_text": "fake_original_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", "workspace_id": "fake_workspace_id", "dialog_nodes": [], "counterexamples": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "fake_status", "webhooks": [], "intents": [], "entities": []}""" -fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "workspace_id": "fake_workspace_id", "dialog_nodes": [], "counterexamples": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "fake_status", "webhooks": [], "intents": [], "entities": []}""" -fake_response_Workspace_json = """{"name": "fake_name", "description": "fake_description", "language": "fake_language", "workspace_id": "fake_workspace_id", "dialog_nodes": [], "counterexamples": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "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"}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "fake_status", "webhooks": [], "intents": [], "entities": []}""" -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": []}""" -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_ExampleCollection_json = """{"examples": [], "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_Example_json = """{"text": "fake_text", "mentions": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_Example_json = """{"text": "fake_text", "mentions": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_Example_json = """{"text": "fake_text", "mentions": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_CounterexampleCollection_json = """{"counterexamples": [], "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_Counterexample_json = """{"text": "fake_text", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_Counterexample_json = """{"text": "fake_text", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_Counterexample_json = """{"text": "fake_text", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_EntityCollection_json = """{"entities": [], "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_Entity_json = """{"entity": "fake_entity", "description": "fake_description", "fuzzy_match": false, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "values": []}""" -fake_response_Entity_json = """{"entity": "fake_entity", "description": "fake_description", "fuzzy_match": false, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "values": []}""" -fake_response_Entity_json = """{"entity": "fake_entity", "description": "fake_description", "fuzzy_match": false, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "values": []}""" -fake_response_EntityMentionCollection_json = """{"examples": [], "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_ValueCollection_json = """{"values": [], "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_Value_json = """{"value": "fake_value", "type": "fake_type", "synonyms": [], "patterns": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_Value_json = """{"value": "fake_value", "type": "fake_type", "synonyms": [], "patterns": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_Value_json = """{"value": "fake_value", "type": "fake_type", "synonyms": [], "patterns": [], "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_SynonymCollection_json = """{"synonyms": [], "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_Synonym_json = """{"synonym": "fake_synonym", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_Synonym_json = """{"synonym": "fake_synonym", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_Synonym_json = """{"synonym": "fake_synonym", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_DialogNodeCollection_json = """{"dialog_nodes": [], "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_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "context": {}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "context": {}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_DialogNode_json = """{"dialog_node": "fake_dialog_node", "description": "fake_description", "conditions": "fake_conditions", "parent": "fake_parent", "previous_sibling": "fake_previous_sibling", "output": {"generic": [], "modifiers": {"overwrite": false}}, "context": {}, "next_step": {"behavior": "fake_behavior", "dialog_node": "fake_dialog_node", "selector": "fake_selector"}, "title": "fake_title", "type": "fake_type", "event_name": "fake_event_name", "variable": "fake_variable", "actions": [], "digress_in": "fake_digress_in", "digress_out": "fake_digress_out", "digress_out_slots": "fake_digress_out_slots", "user_label": "fake_user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" -fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" -fake_response_BulkClassifyResponse_json = """{"output": []}""" +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestBulkClassifyOutput(): + """ + Test Class for BulkClassifyOutput + """ + + def test_bulk_classify_output_serialization(self): + """ + Test serialization/deserialization for BulkClassifyOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + # Construct a json representation of a BulkClassifyOutput model + bulk_classify_output_model_json = {} + bulk_classify_output_model_json['input'] = bulk_classify_utterance_model + bulk_classify_output_model_json['entities'] = [runtime_entity_model] + bulk_classify_output_model_json['intents'] = [runtime_intent_model] + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model = BulkClassifyOutput.from_dict(bulk_classify_output_model_json) + assert bulk_classify_output_model != False + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model_dict = BulkClassifyOutput.from_dict(bulk_classify_output_model_json).__dict__ + bulk_classify_output_model2 = BulkClassifyOutput(**bulk_classify_output_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_output_model == bulk_classify_output_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() + assert bulk_classify_output_model_json2 == bulk_classify_output_model_json + +class TestBulkClassifyResponse(): + """ + Test Class for BulkClassifyResponse + """ + + def test_bulk_classify_response_serialization(self): + """ + Test serialization/deserialization for BulkClassifyResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + bulk_classify_output_model = {} # BulkClassifyOutput + bulk_classify_output_model['input'] = bulk_classify_utterance_model + bulk_classify_output_model['entities'] = [runtime_entity_model] + bulk_classify_output_model['intents'] = [runtime_intent_model] + + # Construct a json representation of a BulkClassifyResponse model + bulk_classify_response_model_json = {} + bulk_classify_response_model_json['output'] = [bulk_classify_output_model] + + # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation + bulk_classify_response_model = BulkClassifyResponse.from_dict(bulk_classify_response_model_json) + assert bulk_classify_response_model != False + + # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation + bulk_classify_response_model_dict = BulkClassifyResponse.from_dict(bulk_classify_response_model_json).__dict__ + bulk_classify_response_model2 = BulkClassifyResponse(**bulk_classify_response_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_response_model == bulk_classify_response_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() + assert bulk_classify_response_model_json2 == bulk_classify_response_model_json + +class TestBulkClassifyUtterance(): + """ + Test Class for BulkClassifyUtterance + """ + + def test_bulk_classify_utterance_serialization(self): + """ + Test serialization/deserialization for BulkClassifyUtterance + """ + + # Construct a json representation of a BulkClassifyUtterance model + bulk_classify_utterance_model_json = {} + bulk_classify_utterance_model_json['text'] = 'testString' + + # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation + bulk_classify_utterance_model = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json) + assert bulk_classify_utterance_model != False + + # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation + bulk_classify_utterance_model_dict = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json).__dict__ + bulk_classify_utterance_model2 = BulkClassifyUtterance(**bulk_classify_utterance_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_utterance_model == bulk_classify_utterance_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() + assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json + +class TestCaptureGroup(): + """ + Test Class for CaptureGroup + """ + + def test_capture_group_serialization(self): + """ + Test serialization/deserialization for CaptureGroup + """ + + # Construct a json representation of a CaptureGroup model + capture_group_model_json = {} + capture_group_model_json['group'] = 'testString' + capture_group_model_json['location'] = [38] + + # Construct a model instance of CaptureGroup by calling from_dict on the json representation + capture_group_model = CaptureGroup.from_dict(capture_group_model_json) + assert capture_group_model != False + + # Construct a model instance of CaptureGroup by calling from_dict on the json representation + capture_group_model_dict = CaptureGroup.from_dict(capture_group_model_json).__dict__ + capture_group_model2 = CaptureGroup(**capture_group_model_dict) + + # Verify the model instances are equivalent + assert capture_group_model == capture_group_model2 + + # Convert model instance back to dict and verify no loss of data + capture_group_model_json2 = capture_group_model.to_dict() + assert capture_group_model_json2 == capture_group_model_json + +class TestContext(): + """ + Test Class for Context + """ + + def test_context_serialization(self): + """ + Test serialization/deserialization for Context + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model['deployment'] = 'testString' + message_context_metadata_model['user_id'] = 'testString' + + # Construct a json representation of a Context model + context_model_json = {} + context_model_json['conversation_id'] = 'testString' + context_model_json['system'] = {} + context_model_json['metadata'] = message_context_metadata_model + context_model_json['foo'] = { 'foo': 'bar' } + + # Construct a model instance of Context by calling from_dict on the json representation + context_model = Context.from_dict(context_model_json) + assert context_model != False + + # Construct a model instance of Context by calling from_dict on the json representation + context_model_dict = Context.from_dict(context_model_json).__dict__ + context_model2 = Context(**context_model_dict) + + # Verify the model instances are equivalent + assert context_model == context_model2 + + # Convert model instance back to dict and verify no loss of data + context_model_json2 = context_model.to_dict() + assert context_model_json2 == context_model_json + +class TestCounterexample(): + """ + Test Class for Counterexample + """ + + def test_counterexample_serialization(self): + """ + Test serialization/deserialization for Counterexample + """ + + # Construct a json representation of a Counterexample model + counterexample_model_json = {} + counterexample_model_json['text'] = 'testString' + counterexample_model_json['created'] = '2020-01-28T18:40:40.123456Z' + counterexample_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of Counterexample by calling from_dict on the json representation + counterexample_model = Counterexample.from_dict(counterexample_model_json) + assert counterexample_model != False + + # Construct a model instance of Counterexample by calling from_dict on the json representation + counterexample_model_dict = Counterexample.from_dict(counterexample_model_json).__dict__ + counterexample_model2 = Counterexample(**counterexample_model_dict) + + # Verify the model instances are equivalent + assert counterexample_model == counterexample_model2 + + # Convert model instance back to dict and verify no loss of data + counterexample_model_json2 = counterexample_model.to_dict() + assert counterexample_model_json2 == counterexample_model_json + +class TestCounterexampleCollection(): + """ + Test Class for CounterexampleCollection + """ + + def test_counterexample_collection_serialization(self): + """ + Test serialization/deserialization for CounterexampleCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + counterexample_model = {} # Counterexample + counterexample_model['text'] = 'testString' + counterexample_model['created'] = '2020-01-28T18:40:40.123456Z' + counterexample_model['updated'] = '2020-01-28T18:40:40.123456Z' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a CounterexampleCollection model + counterexample_collection_model_json = {} + counterexample_collection_model_json['counterexamples'] = [counterexample_model] + counterexample_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of CounterexampleCollection by calling from_dict on the json representation + counterexample_collection_model = CounterexampleCollection.from_dict(counterexample_collection_model_json) + assert counterexample_collection_model != False + + # Construct a model instance of CounterexampleCollection by calling from_dict on the json representation + counterexample_collection_model_dict = CounterexampleCollection.from_dict(counterexample_collection_model_json).__dict__ + counterexample_collection_model2 = CounterexampleCollection(**counterexample_collection_model_dict) + + # Verify the model instances are equivalent + assert counterexample_collection_model == counterexample_collection_model2 + + # Convert model instance back to dict and verify no loss of data + counterexample_collection_model_json2 = counterexample_collection_model.to_dict() + assert counterexample_collection_model_json2 == counterexample_collection_model_json + +class TestCreateEntity(): + """ + Test Class for CreateEntity + """ + + def test_create_entity_serialization(self): + """ + Test serialization/deserialization for CreateEntity + """ + + # Construct dict forms of any model objects needed in order to build this model. + + create_value_model = {} # CreateValue + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + create_value_model['created'] = '2020-01-28T18:40:40.123456Z' + create_value_model['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a json representation of a CreateEntity model + create_entity_model_json = {} + create_entity_model_json['entity'] = 'testString' + create_entity_model_json['description'] = 'testString' + create_entity_model_json['metadata'] = {} + create_entity_model_json['fuzzy_match'] = True + create_entity_model_json['created'] = '2020-01-28T18:40:40.123456Z' + create_entity_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + create_entity_model_json['values'] = [create_value_model] + + # Construct a model instance of CreateEntity by calling from_dict on the json representation + create_entity_model = CreateEntity.from_dict(create_entity_model_json) + assert create_entity_model != False + + # Construct a model instance of CreateEntity by calling from_dict on the json representation + create_entity_model_dict = CreateEntity.from_dict(create_entity_model_json).__dict__ + create_entity_model2 = CreateEntity(**create_entity_model_dict) + + # Verify the model instances are equivalent + assert create_entity_model == create_entity_model2 + + # Convert model instance back to dict and verify no loss of data + create_entity_model_json2 = create_entity_model.to_dict() + assert create_entity_model_json2 == create_entity_model_json + +class TestCreateIntent(): + """ + Test Class for CreateIntent + """ + + def test_create_intent_serialization(self): + """ + Test serialization/deserialization for CreateIntent + """ + + # Construct dict forms of any model objects needed in order to build this model. + + mention_model = {} # Mention + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + example_model = {} # Example + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + example_model['created'] = '2020-01-28T18:40:40.123456Z' + example_model['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a json representation of a CreateIntent model + create_intent_model_json = {} + create_intent_model_json['intent'] = 'testString' + create_intent_model_json['description'] = 'testString' + create_intent_model_json['created'] = '2020-01-28T18:40:40.123456Z' + create_intent_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + create_intent_model_json['examples'] = [example_model] + + # Construct a model instance of CreateIntent by calling from_dict on the json representation + create_intent_model = CreateIntent.from_dict(create_intent_model_json) + assert create_intent_model != False + + # Construct a model instance of CreateIntent by calling from_dict on the json representation + create_intent_model_dict = CreateIntent.from_dict(create_intent_model_json).__dict__ + create_intent_model2 = CreateIntent(**create_intent_model_dict) + + # Verify the model instances are equivalent + assert create_intent_model == create_intent_model2 + + # Convert model instance back to dict and verify no loss of data + create_intent_model_json2 = create_intent_model.to_dict() + assert create_intent_model_json2 == create_intent_model_json + +class TestCreateValue(): + """ + Test Class for CreateValue + """ + + def test_create_value_serialization(self): + """ + Test serialization/deserialization for CreateValue + """ + + # Construct a json representation of a CreateValue model + create_value_model_json = {} + create_value_model_json['value'] = 'testString' + create_value_model_json['metadata'] = {} + create_value_model_json['type'] = 'synonyms' + create_value_model_json['synonyms'] = ['testString'] + create_value_model_json['patterns'] = ['testString'] + create_value_model_json['created'] = '2020-01-28T18:40:40.123456Z' + create_value_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of CreateValue by calling from_dict on the json representation + create_value_model = CreateValue.from_dict(create_value_model_json) + assert create_value_model != False + + # Construct a model instance of CreateValue by calling from_dict on the json representation + create_value_model_dict = CreateValue.from_dict(create_value_model_json).__dict__ + create_value_model2 = CreateValue(**create_value_model_dict) + + # Verify the model instances are equivalent + assert create_value_model == create_value_model2 + + # Convert model instance back to dict and verify no loss of data + create_value_model_json2 = create_value_model.to_dict() + assert create_value_model_json2 == create_value_model_json + +class TestDialogNode(): + """ + Test Class for DialogNode + """ + + def test_dialog_node_serialization(self): + """ + Test serialization/deserialization for DialogNode + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeImage + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model['overwrite'] = True + + dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Construct a json representation of a DialogNode model + dialog_node_model_json = {} + dialog_node_model_json['dialog_node'] = 'testString' + dialog_node_model_json['description'] = 'testString' + dialog_node_model_json['conditions'] = 'testString' + dialog_node_model_json['parent'] = 'testString' + dialog_node_model_json['previous_sibling'] = 'testString' + dialog_node_model_json['output'] = dialog_node_output_model + dialog_node_model_json['context'] = dialog_node_context_model + dialog_node_model_json['metadata'] = {} + dialog_node_model_json['next_step'] = dialog_node_next_step_model + dialog_node_model_json['title'] = 'testString' + dialog_node_model_json['type'] = 'standard' + dialog_node_model_json['event_name'] = 'focus' + dialog_node_model_json['variable'] = 'testString' + dialog_node_model_json['actions'] = [dialog_node_action_model] + dialog_node_model_json['digress_in'] = 'not_available' + dialog_node_model_json['digress_out'] = 'allow_returning' + dialog_node_model_json['digress_out_slots'] = 'not_allowed' + dialog_node_model_json['user_label'] = 'testString' + dialog_node_model_json['disambiguation_opt_out'] = True + dialog_node_model_json['disabled'] = True + dialog_node_model_json['created'] = '2020-01-28T18:40:40.123456Z' + dialog_node_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of DialogNode by calling from_dict on the json representation + dialog_node_model = DialogNode.from_dict(dialog_node_model_json) + assert dialog_node_model != False + + # Construct a model instance of DialogNode by calling from_dict on the json representation + dialog_node_model_dict = DialogNode.from_dict(dialog_node_model_json).__dict__ + dialog_node_model2 = DialogNode(**dialog_node_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_model == dialog_node_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_model_json2 = dialog_node_model.to_dict() + assert dialog_node_model_json2 == dialog_node_model_json + +class TestDialogNodeAction(): + """ + Test Class for DialogNodeAction + """ + + def test_dialog_node_action_serialization(self): + """ + Test serialization/deserialization for DialogNodeAction + """ + + # Construct a json representation of a DialogNodeAction model + dialog_node_action_model_json = {} + dialog_node_action_model_json['name'] = 'testString' + dialog_node_action_model_json['type'] = 'client' + dialog_node_action_model_json['parameters'] = {} + dialog_node_action_model_json['result_variable'] = 'testString' + dialog_node_action_model_json['credentials'] = 'testString' + + # Construct a model instance of DialogNodeAction by calling from_dict on the json representation + dialog_node_action_model = DialogNodeAction.from_dict(dialog_node_action_model_json) + assert dialog_node_action_model != False + + # Construct a model instance of DialogNodeAction by calling from_dict on the json representation + dialog_node_action_model_dict = DialogNodeAction.from_dict(dialog_node_action_model_json).__dict__ + dialog_node_action_model2 = DialogNodeAction(**dialog_node_action_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_action_model == dialog_node_action_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_action_model_json2 = dialog_node_action_model.to_dict() + assert dialog_node_action_model_json2 == dialog_node_action_model_json + +class TestDialogNodeCollection(): + """ + Test Class for DialogNodeCollection + """ + + def test_dialog_node_collection_serialization(self): + """ + Test serialization/deserialization for DialogNodeCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeImage + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model['overwrite'] = True + + dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_model = {} # DialogNode + dialog_node_model['dialog_node'] = 'testString' + dialog_node_model['description'] = 'testString' + dialog_node_model['conditions'] = 'testString' + dialog_node_model['parent'] = 'testString' + dialog_node_model['previous_sibling'] = 'testString' + dialog_node_model['output'] = dialog_node_output_model + dialog_node_model['context'] = dialog_node_context_model + dialog_node_model['metadata'] = {} + dialog_node_model['next_step'] = dialog_node_next_step_model + dialog_node_model['title'] = 'testString' + dialog_node_model['type'] = 'standard' + dialog_node_model['event_name'] = 'focus' + dialog_node_model['variable'] = 'testString' + dialog_node_model['actions'] = [dialog_node_action_model] + dialog_node_model['digress_in'] = 'not_available' + dialog_node_model['digress_out'] = 'allow_returning' + dialog_node_model['digress_out_slots'] = 'not_allowed' + dialog_node_model['user_label'] = 'testString' + dialog_node_model['disambiguation_opt_out'] = True + dialog_node_model['disabled'] = True + dialog_node_model['created'] = '2020-01-28T18:40:40.123456Z' + dialog_node_model['updated'] = '2020-01-28T18:40:40.123456Z' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a DialogNodeCollection model + dialog_node_collection_model_json = {} + dialog_node_collection_model_json['dialog_nodes'] = [dialog_node_model] + dialog_node_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of DialogNodeCollection by calling from_dict on the json representation + dialog_node_collection_model = DialogNodeCollection.from_dict(dialog_node_collection_model_json) + assert dialog_node_collection_model != False + + # Construct a model instance of DialogNodeCollection by calling from_dict on the json representation + dialog_node_collection_model_dict = DialogNodeCollection.from_dict(dialog_node_collection_model_json).__dict__ + dialog_node_collection_model2 = DialogNodeCollection(**dialog_node_collection_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_collection_model == dialog_node_collection_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_collection_model_json2 = dialog_node_collection_model.to_dict() + assert dialog_node_collection_model_json2 == dialog_node_collection_model_json + +class TestDialogNodeContext(): + """ + Test Class for DialogNodeContext + """ + + def test_dialog_node_context_serialization(self): + """ + Test serialization/deserialization for DialogNodeContext + """ + + # Construct a json representation of a DialogNodeContext model + dialog_node_context_model_json = {} + dialog_node_context_model_json['integrations'] = {} + dialog_node_context_model_json['foo'] = { 'foo': 'bar' } + + # Construct a model instance of DialogNodeContext by calling from_dict on the json representation + dialog_node_context_model = DialogNodeContext.from_dict(dialog_node_context_model_json) + assert dialog_node_context_model != False + + # Construct a model instance of DialogNodeContext by calling from_dict on the json representation + dialog_node_context_model_dict = DialogNodeContext.from_dict(dialog_node_context_model_json).__dict__ + dialog_node_context_model2 = DialogNodeContext(**dialog_node_context_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_context_model == dialog_node_context_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_context_model_json2 = dialog_node_context_model.to_dict() + assert dialog_node_context_model_json2 == dialog_node_context_model_json + +class TestDialogNodeNextStep(): + """ + Test Class for DialogNodeNextStep + """ + + def test_dialog_node_next_step_serialization(self): + """ + Test serialization/deserialization for DialogNodeNextStep + """ + + # Construct a json representation of a DialogNodeNextStep model + dialog_node_next_step_model_json = {} + dialog_node_next_step_model_json['behavior'] = 'get_user_input' + dialog_node_next_step_model_json['dialog_node'] = 'testString' + dialog_node_next_step_model_json['selector'] = 'condition' + + # Construct a model instance of DialogNodeNextStep by calling from_dict on the json representation + dialog_node_next_step_model = DialogNodeNextStep.from_dict(dialog_node_next_step_model_json) + assert dialog_node_next_step_model != False + + # Construct a model instance of DialogNodeNextStep by calling from_dict on the json representation + dialog_node_next_step_model_dict = DialogNodeNextStep.from_dict(dialog_node_next_step_model_json).__dict__ + dialog_node_next_step_model2 = DialogNodeNextStep(**dialog_node_next_step_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_next_step_model == dialog_node_next_step_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_next_step_model_json2 = dialog_node_next_step_model.to_dict() + assert dialog_node_next_step_model_json2 == dialog_node_next_step_model_json + +class TestDialogNodeOutput(): + """ + Test Class for DialogNodeOutput + """ + + def test_dialog_node_output_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeImage + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a json representation of a DialogNodeOutput model + dialog_node_output_model_json = {} + dialog_node_output_model_json['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model_json['integrations'] = {} + dialog_node_output_model_json['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model_json['foo'] = { 'foo': 'bar' } + + # Construct a model instance of DialogNodeOutput by calling from_dict on the json representation + dialog_node_output_model = DialogNodeOutput.from_dict(dialog_node_output_model_json) + assert dialog_node_output_model != False + + # Construct a model instance of DialogNodeOutput by calling from_dict on the json representation + dialog_node_output_model_dict = DialogNodeOutput.from_dict(dialog_node_output_model_json).__dict__ + dialog_node_output_model2 = DialogNodeOutput(**dialog_node_output_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_model == dialog_node_output_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_model_json2 = dialog_node_output_model.to_dict() + assert dialog_node_output_model_json2 == dialog_node_output_model_json + +class TestDialogNodeOutputConnectToAgentTransferInfo(): + """ + Test Class for DialogNodeOutputConnectToAgentTransferInfo + """ + + def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputConnectToAgentTransferInfo + """ + + # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model + dialog_node_output_connect_to_agent_transfer_info_model_json = {} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {} + + # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation + dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) + assert dialog_node_output_connect_to_agent_transfer_info_model != False + + # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation + dialog_node_output_connect_to_agent_transfer_info_model_dict = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json).__dict__ + dialog_node_output_connect_to_agent_transfer_info_model2 = DialogNodeOutputConnectToAgentTransferInfo(**dialog_node_output_connect_to_agent_transfer_info_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_connect_to_agent_transfer_info_model == dialog_node_output_connect_to_agent_transfer_info_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() + assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json + +class TestDialogNodeOutputModifiers(): + """ + Test Class for DialogNodeOutputModifiers + """ + + def test_dialog_node_output_modifiers_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputModifiers + """ + + # Construct a json representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model_json = {} + dialog_node_output_modifiers_model_json['overwrite'] = True + + # Construct a model instance of DialogNodeOutputModifiers by calling from_dict on the json representation + dialog_node_output_modifiers_model = DialogNodeOutputModifiers.from_dict(dialog_node_output_modifiers_model_json) + assert dialog_node_output_modifiers_model != False + + # Construct a model instance of DialogNodeOutputModifiers by calling from_dict on the json representation + dialog_node_output_modifiers_model_dict = DialogNodeOutputModifiers.from_dict(dialog_node_output_modifiers_model_json).__dict__ + dialog_node_output_modifiers_model2 = DialogNodeOutputModifiers(**dialog_node_output_modifiers_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_modifiers_model == dialog_node_output_modifiers_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_modifiers_model_json2 = dialog_node_output_modifiers_model.to_dict() + assert dialog_node_output_modifiers_model_json2 == dialog_node_output_modifiers_model_json + +class TestDialogNodeOutputOptionsElement(): + """ + Test Class for DialogNodeOutputOptionsElement + """ + + def test_dialog_node_output_options_element_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputOptionsElement + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] + dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] + + # Construct a json representation of a DialogNodeOutputOptionsElement model + dialog_node_output_options_element_model_json = {} + dialog_node_output_options_element_model_json['label'] = 'testString' + dialog_node_output_options_element_model_json['value'] = dialog_node_output_options_element_value_model + + # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation + dialog_node_output_options_element_model = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json) + assert dialog_node_output_options_element_model != False + + # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation + dialog_node_output_options_element_model_dict = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json).__dict__ + dialog_node_output_options_element_model2 = DialogNodeOutputOptionsElement(**dialog_node_output_options_element_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_options_element_model == dialog_node_output_options_element_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() + assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json + +class TestDialogNodeOutputOptionsElementValue(): + """ + Test Class for DialogNodeOutputOptionsElementValue + """ + + def test_dialog_node_output_options_element_value_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputOptionsElementValue + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + # Construct a json representation of a DialogNodeOutputOptionsElementValue model + dialog_node_output_options_element_value_model_json = {} + dialog_node_output_options_element_value_model_json['input'] = message_input_model + dialog_node_output_options_element_value_model_json['intents'] = [runtime_intent_model] + dialog_node_output_options_element_value_model_json['entities'] = [runtime_entity_model] + + # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation + dialog_node_output_options_element_value_model = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json) + assert dialog_node_output_options_element_value_model != False + + # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation + dialog_node_output_options_element_value_model_dict = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json).__dict__ + dialog_node_output_options_element_value_model2 = DialogNodeOutputOptionsElementValue(**dialog_node_output_options_element_value_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_options_element_value_model == dialog_node_output_options_element_value_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() + assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json + +class TestDialogNodeOutputTextValuesElement(): + """ + Test Class for DialogNodeOutputTextValuesElement + """ + + def test_dialog_node_output_text_values_element_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputTextValuesElement + """ + + # Construct a json representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model_json = {} + dialog_node_output_text_values_element_model_json['text'] = 'testString' + + # Construct a model instance of DialogNodeOutputTextValuesElement by calling from_dict on the json representation + dialog_node_output_text_values_element_model = DialogNodeOutputTextValuesElement.from_dict(dialog_node_output_text_values_element_model_json) + assert dialog_node_output_text_values_element_model != False + + # Construct a model instance of DialogNodeOutputTextValuesElement by calling from_dict on the json representation + dialog_node_output_text_values_element_model_dict = DialogNodeOutputTextValuesElement.from_dict(dialog_node_output_text_values_element_model_json).__dict__ + dialog_node_output_text_values_element_model2 = DialogNodeOutputTextValuesElement(**dialog_node_output_text_values_element_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_text_values_element_model == dialog_node_output_text_values_element_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_text_values_element_model_json2 = dialog_node_output_text_values_element_model.to_dict() + assert dialog_node_output_text_values_element_model_json2 == dialog_node_output_text_values_element_model_json + +class TestDialogNodeVisitedDetails(): + """ + Test Class for DialogNodeVisitedDetails + """ + + def test_dialog_node_visited_details_serialization(self): + """ + Test serialization/deserialization for DialogNodeVisitedDetails + """ + + # Construct a json representation of a DialogNodeVisitedDetails model + dialog_node_visited_details_model_json = {} + dialog_node_visited_details_model_json['dialog_node'] = 'testString' + dialog_node_visited_details_model_json['title'] = 'testString' + dialog_node_visited_details_model_json['conditions'] = 'testString' + + # Construct a model instance of DialogNodeVisitedDetails by calling from_dict on the json representation + dialog_node_visited_details_model = DialogNodeVisitedDetails.from_dict(dialog_node_visited_details_model_json) + assert dialog_node_visited_details_model != False + + # Construct a model instance of DialogNodeVisitedDetails by calling from_dict on the json representation + dialog_node_visited_details_model_dict = DialogNodeVisitedDetails.from_dict(dialog_node_visited_details_model_json).__dict__ + dialog_node_visited_details_model2 = DialogNodeVisitedDetails(**dialog_node_visited_details_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_visited_details_model == dialog_node_visited_details_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_visited_details_model_json2 = dialog_node_visited_details_model.to_dict() + assert dialog_node_visited_details_model_json2 == dialog_node_visited_details_model_json + +class TestDialogSuggestion(): + """ + Test Class for DialogSuggestion + """ + + def test_dialog_suggestion_serialization(self): + """ + Test serialization/deserialization for DialogSuggestion + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model['input'] = message_input_model + dialog_suggestion_value_model['intents'] = [runtime_intent_model] + dialog_suggestion_value_model['entities'] = [runtime_entity_model] + + # Construct a json representation of a DialogSuggestion model + dialog_suggestion_model_json = {} + dialog_suggestion_model_json['label'] = 'testString' + dialog_suggestion_model_json['value'] = dialog_suggestion_value_model + dialog_suggestion_model_json['output'] = {} + dialog_suggestion_model_json['dialog_node'] = 'testString' + + # Construct a model instance of DialogSuggestion by calling from_dict on the json representation + dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) + assert dialog_suggestion_model != False + + # Construct a model instance of DialogSuggestion by calling from_dict on the json representation + dialog_suggestion_model_dict = DialogSuggestion.from_dict(dialog_suggestion_model_json).__dict__ + dialog_suggestion_model2 = DialogSuggestion(**dialog_suggestion_model_dict) + + # Verify the model instances are equivalent + assert dialog_suggestion_model == dialog_suggestion_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() + assert dialog_suggestion_model_json2 == dialog_suggestion_model_json + +class TestDialogSuggestionValue(): + """ + Test Class for DialogSuggestionValue + """ + + def test_dialog_suggestion_value_serialization(self): + """ + Test serialization/deserialization for DialogSuggestionValue + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + # Construct a json representation of a DialogSuggestionValue model + dialog_suggestion_value_model_json = {} + dialog_suggestion_value_model_json['input'] = message_input_model + dialog_suggestion_value_model_json['intents'] = [runtime_intent_model] + dialog_suggestion_value_model_json['entities'] = [runtime_entity_model] + + # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation + dialog_suggestion_value_model = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json) + assert dialog_suggestion_value_model != False + + # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation + dialog_suggestion_value_model_dict = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json).__dict__ + dialog_suggestion_value_model2 = DialogSuggestionValue(**dialog_suggestion_value_model_dict) + + # Verify the model instances are equivalent + assert dialog_suggestion_value_model == dialog_suggestion_value_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() + assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json + +class TestEntity(): + """ + Test Class for Entity + """ + + def test_entity_serialization(self): + """ + Test serialization/deserialization for Entity + """ + + # Construct dict forms of any model objects needed in order to build this model. + + value_model = {} # Value + value_model['value'] = 'testString' + value_model['metadata'] = {} + value_model['type'] = 'synonyms' + value_model['synonyms'] = ['testString'] + value_model['patterns'] = ['testString'] + value_model['created'] = '2020-01-28T18:40:40.123456Z' + value_model['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a json representation of a Entity model + entity_model_json = {} + entity_model_json['entity'] = 'testString' + entity_model_json['description'] = 'testString' + entity_model_json['metadata'] = {} + entity_model_json['fuzzy_match'] = True + entity_model_json['created'] = '2020-01-28T18:40:40.123456Z' + entity_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + entity_model_json['values'] = [value_model] + + # Construct a model instance of Entity by calling from_dict on the json representation + entity_model = Entity.from_dict(entity_model_json) + assert entity_model != False + + # Construct a model instance of Entity by calling from_dict on the json representation + entity_model_dict = Entity.from_dict(entity_model_json).__dict__ + entity_model2 = Entity(**entity_model_dict) + + # Verify the model instances are equivalent + assert entity_model == entity_model2 + + # Convert model instance back to dict and verify no loss of data + entity_model_json2 = entity_model.to_dict() + assert entity_model_json2 == entity_model_json + +class TestEntityCollection(): + """ + Test Class for EntityCollection + """ + + def test_entity_collection_serialization(self): + """ + Test serialization/deserialization for EntityCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + value_model = {} # Value + value_model['value'] = 'testString' + value_model['metadata'] = {} + value_model['type'] = 'synonyms' + value_model['synonyms'] = ['testString'] + value_model['patterns'] = ['testString'] + value_model['created'] = '2020-01-28T18:40:40.123456Z' + value_model['updated'] = '2020-01-28T18:40:40.123456Z' + + entity_model = {} # Entity + entity_model['entity'] = 'testString' + entity_model['description'] = 'testString' + entity_model['metadata'] = {} + entity_model['fuzzy_match'] = True + entity_model['created'] = '2020-01-28T18:40:40.123456Z' + entity_model['updated'] = '2020-01-28T18:40:40.123456Z' + entity_model['values'] = [value_model] + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a EntityCollection model + entity_collection_model_json = {} + entity_collection_model_json['entities'] = [entity_model] + entity_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of EntityCollection by calling from_dict on the json representation + entity_collection_model = EntityCollection.from_dict(entity_collection_model_json) + assert entity_collection_model != False + + # Construct a model instance of EntityCollection by calling from_dict on the json representation + entity_collection_model_dict = EntityCollection.from_dict(entity_collection_model_json).__dict__ + entity_collection_model2 = EntityCollection(**entity_collection_model_dict) + + # Verify the model instances are equivalent + assert entity_collection_model == entity_collection_model2 + + # Convert model instance back to dict and verify no loss of data + entity_collection_model_json2 = entity_collection_model.to_dict() + assert entity_collection_model_json2 == entity_collection_model_json + +class TestEntityMention(): + """ + Test Class for EntityMention + """ + + def test_entity_mention_serialization(self): + """ + Test serialization/deserialization for EntityMention + """ + + # Construct a json representation of a EntityMention model + entity_mention_model_json = {} + entity_mention_model_json['text'] = 'testString' + entity_mention_model_json['intent'] = 'testString' + entity_mention_model_json['location'] = [38] + + # Construct a model instance of EntityMention by calling from_dict on the json representation + entity_mention_model = EntityMention.from_dict(entity_mention_model_json) + assert entity_mention_model != False + + # Construct a model instance of EntityMention by calling from_dict on the json representation + entity_mention_model_dict = EntityMention.from_dict(entity_mention_model_json).__dict__ + entity_mention_model2 = EntityMention(**entity_mention_model_dict) + + # Verify the model instances are equivalent + assert entity_mention_model == entity_mention_model2 + + # Convert model instance back to dict and verify no loss of data + entity_mention_model_json2 = entity_mention_model.to_dict() + assert entity_mention_model_json2 == entity_mention_model_json + +class TestEntityMentionCollection(): + """ + Test Class for EntityMentionCollection + """ + + def test_entity_mention_collection_serialization(self): + """ + Test serialization/deserialization for EntityMentionCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + entity_mention_model = {} # EntityMention + entity_mention_model['text'] = 'testString' + entity_mention_model['intent'] = 'testString' + entity_mention_model['location'] = [38] + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a EntityMentionCollection model + entity_mention_collection_model_json = {} + entity_mention_collection_model_json['examples'] = [entity_mention_model] + entity_mention_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of EntityMentionCollection by calling from_dict on the json representation + entity_mention_collection_model = EntityMentionCollection.from_dict(entity_mention_collection_model_json) + assert entity_mention_collection_model != False + + # Construct a model instance of EntityMentionCollection by calling from_dict on the json representation + entity_mention_collection_model_dict = EntityMentionCollection.from_dict(entity_mention_collection_model_json).__dict__ + entity_mention_collection_model2 = EntityMentionCollection(**entity_mention_collection_model_dict) + + # Verify the model instances are equivalent + assert entity_mention_collection_model == entity_mention_collection_model2 + + # Convert model instance back to dict and verify no loss of data + entity_mention_collection_model_json2 = entity_mention_collection_model.to_dict() + assert entity_mention_collection_model_json2 == entity_mention_collection_model_json + +class TestExample(): + """ + Test Class for Example + """ + + def test_example_serialization(self): + """ + Test serialization/deserialization for Example + """ + + # Construct dict forms of any model objects needed in order to build this model. + + mention_model = {} # Mention + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a json representation of a Example model + example_model_json = {} + example_model_json['text'] = 'testString' + example_model_json['mentions'] = [mention_model] + example_model_json['created'] = '2020-01-28T18:40:40.123456Z' + example_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of Example by calling from_dict on the json representation + example_model = Example.from_dict(example_model_json) + assert example_model != False + + # Construct a model instance of Example by calling from_dict on the json representation + example_model_dict = Example.from_dict(example_model_json).__dict__ + example_model2 = Example(**example_model_dict) + + # Verify the model instances are equivalent + assert example_model == example_model2 + + # Convert model instance back to dict and verify no loss of data + example_model_json2 = example_model.to_dict() + assert example_model_json2 == example_model_json + +class TestExampleCollection(): + """ + Test Class for ExampleCollection + """ + + def test_example_collection_serialization(self): + """ + Test serialization/deserialization for ExampleCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + mention_model = {} # Mention + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + example_model = {} # Example + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + example_model['created'] = '2020-01-28T18:40:40.123456Z' + example_model['updated'] = '2020-01-28T18:40:40.123456Z' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a ExampleCollection model + example_collection_model_json = {} + example_collection_model_json['examples'] = [example_model] + example_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of ExampleCollection by calling from_dict on the json representation + example_collection_model = ExampleCollection.from_dict(example_collection_model_json) + assert example_collection_model != False + + # Construct a model instance of ExampleCollection by calling from_dict on the json representation + example_collection_model_dict = ExampleCollection.from_dict(example_collection_model_json).__dict__ + example_collection_model2 = ExampleCollection(**example_collection_model_dict) + + # Verify the model instances are equivalent + assert example_collection_model == example_collection_model2 + + # Convert model instance back to dict and verify no loss of data + example_collection_model_json2 = example_collection_model.to_dict() + assert example_collection_model_json2 == example_collection_model_json + +class TestIntent(): + """ + Test Class for Intent + """ + + def test_intent_serialization(self): + """ + Test serialization/deserialization for Intent + """ + + # Construct dict forms of any model objects needed in order to build this model. + + mention_model = {} # Mention + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + example_model = {} # Example + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + example_model['created'] = '2020-01-28T18:40:40.123456Z' + example_model['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a json representation of a Intent model + intent_model_json = {} + intent_model_json['intent'] = 'testString' + intent_model_json['description'] = 'testString' + intent_model_json['created'] = '2020-01-28T18:40:40.123456Z' + intent_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + intent_model_json['examples'] = [example_model] + + # Construct a model instance of Intent by calling from_dict on the json representation + intent_model = Intent.from_dict(intent_model_json) + assert intent_model != False + + # Construct a model instance of Intent by calling from_dict on the json representation + intent_model_dict = Intent.from_dict(intent_model_json).__dict__ + intent_model2 = Intent(**intent_model_dict) + + # Verify the model instances are equivalent + assert intent_model == intent_model2 + + # Convert model instance back to dict and verify no loss of data + intent_model_json2 = intent_model.to_dict() + assert intent_model_json2 == intent_model_json + +class TestIntentCollection(): + """ + Test Class for IntentCollection + """ + + def test_intent_collection_serialization(self): + """ + Test serialization/deserialization for IntentCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + mention_model = {} # Mention + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + example_model = {} # Example + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + example_model['created'] = '2020-01-28T18:40:40.123456Z' + example_model['updated'] = '2020-01-28T18:40:40.123456Z' + + intent_model = {} # Intent + intent_model['intent'] = 'testString' + intent_model['description'] = 'testString' + intent_model['created'] = '2020-01-28T18:40:40.123456Z' + intent_model['updated'] = '2020-01-28T18:40:40.123456Z' + intent_model['examples'] = [example_model] + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a IntentCollection model + intent_collection_model_json = {} + intent_collection_model_json['intents'] = [intent_model] + intent_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of IntentCollection by calling from_dict on the json representation + intent_collection_model = IntentCollection.from_dict(intent_collection_model_json) + assert intent_collection_model != False + + # Construct a model instance of IntentCollection by calling from_dict on the json representation + intent_collection_model_dict = IntentCollection.from_dict(intent_collection_model_json).__dict__ + intent_collection_model2 = IntentCollection(**intent_collection_model_dict) + + # Verify the model instances are equivalent + assert intent_collection_model == intent_collection_model2 + + # Convert model instance back to dict and verify no loss of data + intent_collection_model_json2 = intent_collection_model.to_dict() + assert intent_collection_model_json2 == intent_collection_model_json + +class TestLog(): + """ + Test Class for Log + """ + + def test_log_serialization(self): + """ + Test serialization/deserialization for Log + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model['deployment'] = 'testString' + message_context_metadata_model['user_id'] = 'testString' + + context_model = {} # Context + context_model['conversation_id'] = 'testString' + context_model['system'] = {} + context_model['metadata'] = message_context_metadata_model + context_model['foo'] = { 'foo': 'bar' } + + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model['dialog_node'] = 'testString' + dialog_node_visited_details_model['title'] = 'testString' + dialog_node_visited_details_model['conditions'] = 'testString' + + log_message_model = {} # LogMessage + log_message_model['level'] = 'info' + log_message_model['msg'] = 'testString' + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] + dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption + runtime_response_generic_model['response_type'] = 'option' + runtime_response_generic_model['title'] = 'testString' + runtime_response_generic_model['description'] = 'testString' + runtime_response_generic_model['preference'] = 'dropdown' + runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + + output_data_model = {} # OutputData + output_data_model['nodes_visited'] = ['testString'] + output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] + output_data_model['log_messages'] = [log_message_model] + output_data_model['text'] = ['testString'] + output_data_model['generic'] = [runtime_response_generic_model] + output_data_model['foo'] = { 'foo': 'bar' } + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + message_request_model = {} # MessageRequest + message_request_model['input'] = message_input_model + message_request_model['intents'] = [runtime_intent_model] + message_request_model['entities'] = [runtime_entity_model] + message_request_model['alternate_intents'] = True + message_request_model['context'] = context_model + message_request_model['output'] = output_data_model + message_request_model['actions'] = [dialog_node_action_model] + + message_response_model = {} # MessageResponse + message_response_model['input'] = message_input_model + message_response_model['intents'] = [runtime_intent_model] + message_response_model['entities'] = [runtime_entity_model] + message_response_model['alternate_intents'] = True + message_response_model['context'] = context_model + message_response_model['output'] = output_data_model + message_response_model['actions'] = [dialog_node_action_model] + + # Construct a json representation of a Log model + log_model_json = {} + log_model_json['request'] = message_request_model + log_model_json['response'] = message_response_model + log_model_json['log_id'] = 'testString' + log_model_json['request_timestamp'] = 'testString' + log_model_json['response_timestamp'] = 'testString' + log_model_json['workspace_id'] = 'testString' + log_model_json['language'] = 'testString' + + # Construct a model instance of Log by calling from_dict on the json representation + log_model = Log.from_dict(log_model_json) + assert log_model != False + + # Construct a model instance of Log by calling from_dict on the json representation + log_model_dict = Log.from_dict(log_model_json).__dict__ + log_model2 = Log(**log_model_dict) + + # Verify the model instances are equivalent + assert log_model == log_model2 + + # Convert model instance back to dict and verify no loss of data + log_model_json2 = log_model.to_dict() + assert log_model_json2 == log_model_json + +class TestLogCollection(): + """ + Test Class for LogCollection + """ + + def test_log_collection_serialization(self): + """ + Test serialization/deserialization for LogCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model['deployment'] = 'testString' + message_context_metadata_model['user_id'] = 'testString' + + context_model = {} # Context + context_model['conversation_id'] = 'testString' + context_model['system'] = {} + context_model['metadata'] = message_context_metadata_model + context_model['foo'] = { 'foo': 'bar' } + + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model['dialog_node'] = 'testString' + dialog_node_visited_details_model['title'] = 'testString' + dialog_node_visited_details_model['conditions'] = 'testString' + + log_message_model = {} # LogMessage + log_message_model['level'] = 'info' + log_message_model['msg'] = 'testString' + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] + dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption + runtime_response_generic_model['response_type'] = 'option' + runtime_response_generic_model['title'] = 'testString' + runtime_response_generic_model['description'] = 'testString' + runtime_response_generic_model['preference'] = 'dropdown' + runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + + output_data_model = {} # OutputData + output_data_model['nodes_visited'] = ['testString'] + output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] + output_data_model['log_messages'] = [log_message_model] + output_data_model['text'] = ['testString'] + output_data_model['generic'] = [runtime_response_generic_model] + output_data_model['foo'] = { 'foo': 'bar' } + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + message_request_model = {} # MessageRequest + message_request_model['input'] = message_input_model + message_request_model['intents'] = [runtime_intent_model] + message_request_model['entities'] = [runtime_entity_model] + message_request_model['alternate_intents'] = True + message_request_model['context'] = context_model + message_request_model['output'] = output_data_model + message_request_model['actions'] = [dialog_node_action_model] + + message_response_model = {} # MessageResponse + message_response_model['input'] = message_input_model + message_response_model['intents'] = [runtime_intent_model] + message_response_model['entities'] = [runtime_entity_model] + message_response_model['alternate_intents'] = True + message_response_model['context'] = context_model + message_response_model['output'] = output_data_model + message_response_model['actions'] = [dialog_node_action_model] + + log_model = {} # Log + log_model['request'] = message_request_model + log_model['response'] = message_response_model + log_model['log_id'] = 'testString' + log_model['request_timestamp'] = 'testString' + log_model['response_timestamp'] = 'testString' + log_model['workspace_id'] = 'testString' + log_model['language'] = 'testString' + + log_pagination_model = {} # LogPagination + log_pagination_model['next_url'] = 'testString' + log_pagination_model['matched'] = 38 + log_pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a LogCollection model + log_collection_model_json = {} + log_collection_model_json['logs'] = [log_model] + log_collection_model_json['pagination'] = log_pagination_model + + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model = LogCollection.from_dict(log_collection_model_json) + assert log_collection_model != False + + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model_dict = LogCollection.from_dict(log_collection_model_json).__dict__ + log_collection_model2 = LogCollection(**log_collection_model_dict) + + # Verify the model instances are equivalent + assert log_collection_model == log_collection_model2 + + # Convert model instance back to dict and verify no loss of data + log_collection_model_json2 = log_collection_model.to_dict() + assert log_collection_model_json2 == log_collection_model_json + +class TestLogMessage(): + """ + Test Class for LogMessage + """ + + def test_log_message_serialization(self): + """ + Test serialization/deserialization for LogMessage + """ + + # Construct a json representation of a LogMessage model + log_message_model_json = {} + log_message_model_json['level'] = 'info' + log_message_model_json['msg'] = 'testString' + + # Construct a model instance of LogMessage by calling from_dict on the json representation + log_message_model = LogMessage.from_dict(log_message_model_json) + assert log_message_model != False + + # Construct a model instance of LogMessage by calling from_dict on the json representation + log_message_model_dict = LogMessage.from_dict(log_message_model_json).__dict__ + log_message_model2 = LogMessage(**log_message_model_dict) + + # Verify the model instances are equivalent + assert log_message_model == log_message_model2 + + # Convert model instance back to dict and verify no loss of data + log_message_model_json2 = log_message_model.to_dict() + assert log_message_model_json2 == log_message_model_json + +class TestLogPagination(): + """ + Test Class for LogPagination + """ + + def test_log_pagination_serialization(self): + """ + Test serialization/deserialization for LogPagination + """ + + # Construct a json representation of a LogPagination model + log_pagination_model_json = {} + log_pagination_model_json['next_url'] = 'testString' + log_pagination_model_json['matched'] = 38 + log_pagination_model_json['next_cursor'] = 'testString' + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model = LogPagination.from_dict(log_pagination_model_json) + assert log_pagination_model != False + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model_dict = LogPagination.from_dict(log_pagination_model_json).__dict__ + log_pagination_model2 = LogPagination(**log_pagination_model_dict) + + # Verify the model instances are equivalent + assert log_pagination_model == log_pagination_model2 + + # Convert model instance back to dict and verify no loss of data + log_pagination_model_json2 = log_pagination_model.to_dict() + assert log_pagination_model_json2 == log_pagination_model_json + +class TestMention(): + """ + Test Class for Mention + """ + + def test_mention_serialization(self): + """ + Test serialization/deserialization for Mention + """ + + # Construct a json representation of a Mention model + mention_model_json = {} + mention_model_json['entity'] = 'testString' + mention_model_json['location'] = [38] + + # Construct a model instance of Mention by calling from_dict on the json representation + mention_model = Mention.from_dict(mention_model_json) + assert mention_model != False + + # Construct a model instance of Mention by calling from_dict on the json representation + mention_model_dict = Mention.from_dict(mention_model_json).__dict__ + mention_model2 = Mention(**mention_model_dict) + + # Verify the model instances are equivalent + assert mention_model == mention_model2 + + # Convert model instance back to dict and verify no loss of data + mention_model_json2 = mention_model.to_dict() + assert mention_model_json2 == mention_model_json + +class TestMessageContextMetadata(): + """ + Test Class for MessageContextMetadata + """ + + def test_message_context_metadata_serialization(self): + """ + Test serialization/deserialization for MessageContextMetadata + """ + + # Construct a json representation of a MessageContextMetadata model + message_context_metadata_model_json = {} + message_context_metadata_model_json['deployment'] = 'testString' + message_context_metadata_model_json['user_id'] = 'testString' + + # Construct a model instance of MessageContextMetadata by calling from_dict on the json representation + message_context_metadata_model = MessageContextMetadata.from_dict(message_context_metadata_model_json) + assert message_context_metadata_model != False + + # Construct a model instance of MessageContextMetadata by calling from_dict on the json representation + message_context_metadata_model_dict = MessageContextMetadata.from_dict(message_context_metadata_model_json).__dict__ + message_context_metadata_model2 = MessageContextMetadata(**message_context_metadata_model_dict) + + # Verify the model instances are equivalent + assert message_context_metadata_model == message_context_metadata_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_metadata_model_json2 = message_context_metadata_model.to_dict() + assert message_context_metadata_model_json2 == message_context_metadata_model_json + +class TestMessageInput(): + """ + Test Class for MessageInput + """ + + def test_message_input_serialization(self): + """ + Test serialization/deserialization for MessageInput + """ + + # Construct a json representation of a MessageInput model + message_input_model_json = {} + message_input_model_json['text'] = 'testString' + message_input_model_json['spelling_suggestions'] = True + message_input_model_json['spelling_auto_correct'] = True + message_input_model_json['suggested_text'] = 'testString' + message_input_model_json['original_text'] = 'testString' + message_input_model_json['foo'] = { 'foo': 'bar' } + + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model = MessageInput.from_dict(message_input_model_json) + assert message_input_model != False + + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ + message_input_model2 = MessageInput(**message_input_model_dict) + + # Verify the model instances are equivalent + assert message_input_model == message_input_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_model_json2 = message_input_model.to_dict() + assert message_input_model_json2 == message_input_model_json + +class TestMessageRequest(): + """ + Test Class for MessageRequest + """ + + def test_message_request_serialization(self): + """ + Test serialization/deserialization for MessageRequest + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model['deployment'] = 'testString' + message_context_metadata_model['user_id'] = 'testString' + + context_model = {} # Context + context_model['conversation_id'] = 'testString' + context_model['system'] = {} + context_model['metadata'] = message_context_metadata_model + context_model['foo'] = { 'foo': 'bar' } + + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model['dialog_node'] = 'testString' + dialog_node_visited_details_model['title'] = 'testString' + dialog_node_visited_details_model['conditions'] = 'testString' + + log_message_model = {} # LogMessage + log_message_model['level'] = 'info' + log_message_model['msg'] = 'testString' + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] + dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption + runtime_response_generic_model['response_type'] = 'option' + runtime_response_generic_model['title'] = 'testString' + runtime_response_generic_model['description'] = 'testString' + runtime_response_generic_model['preference'] = 'dropdown' + runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + + output_data_model = {} # OutputData + output_data_model['nodes_visited'] = ['testString'] + output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] + output_data_model['log_messages'] = [log_message_model] + output_data_model['text'] = ['testString'] + output_data_model['generic'] = [runtime_response_generic_model] + output_data_model['foo'] = { 'foo': 'bar' } + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Construct a json representation of a MessageRequest model + message_request_model_json = {} + message_request_model_json['input'] = message_input_model + message_request_model_json['intents'] = [runtime_intent_model] + message_request_model_json['entities'] = [runtime_entity_model] + message_request_model_json['alternate_intents'] = True + message_request_model_json['context'] = context_model + message_request_model_json['output'] = output_data_model + message_request_model_json['actions'] = [dialog_node_action_model] + + # Construct a model instance of MessageRequest by calling from_dict on the json representation + message_request_model = MessageRequest.from_dict(message_request_model_json) + assert message_request_model != False + + # Construct a model instance of MessageRequest by calling from_dict on the json representation + message_request_model_dict = MessageRequest.from_dict(message_request_model_json).__dict__ + message_request_model2 = MessageRequest(**message_request_model_dict) + + # Verify the model instances are equivalent + assert message_request_model == message_request_model2 + + # Convert model instance back to dict and verify no loss of data + message_request_model_json2 = message_request_model.to_dict() + assert message_request_model_json2 == message_request_model_json + +class TestMessageResponse(): + """ + Test Class for MessageResponse + """ + + def test_message_response_serialization(self): + """ + Test serialization/deserialization for MessageResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model['deployment'] = 'testString' + message_context_metadata_model['user_id'] = 'testString' + + context_model = {} # Context + context_model['conversation_id'] = 'testString' + context_model['system'] = {} + context_model['metadata'] = message_context_metadata_model + context_model['foo'] = { 'foo': 'bar' } + + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model['dialog_node'] = 'testString' + dialog_node_visited_details_model['title'] = 'testString' + dialog_node_visited_details_model['conditions'] = 'testString' + + log_message_model = {} # LogMessage + log_message_model['level'] = 'info' + log_message_model['msg'] = 'testString' + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] + dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption + runtime_response_generic_model['response_type'] = 'option' + runtime_response_generic_model['title'] = 'testString' + runtime_response_generic_model['description'] = 'testString' + runtime_response_generic_model['preference'] = 'dropdown' + runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + + output_data_model = {} # OutputData + output_data_model['nodes_visited'] = ['testString'] + output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] + output_data_model['log_messages'] = [log_message_model] + output_data_model['text'] = ['testString'] + output_data_model['generic'] = [runtime_response_generic_model] + output_data_model['foo'] = { 'foo': 'bar' } + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Construct a json representation of a MessageResponse model + message_response_model_json = {} + message_response_model_json['input'] = message_input_model + message_response_model_json['intents'] = [runtime_intent_model] + message_response_model_json['entities'] = [runtime_entity_model] + message_response_model_json['alternate_intents'] = True + message_response_model_json['context'] = context_model + message_response_model_json['output'] = output_data_model + message_response_model_json['actions'] = [dialog_node_action_model] + + # Construct a model instance of MessageResponse by calling from_dict on the json representation + message_response_model = MessageResponse.from_dict(message_response_model_json) + assert message_response_model != False + + # Construct a model instance of MessageResponse by calling from_dict on the json representation + message_response_model_dict = MessageResponse.from_dict(message_response_model_json).__dict__ + message_response_model2 = MessageResponse(**message_response_model_dict) + + # Verify the model instances are equivalent + assert message_response_model == message_response_model2 + + # Convert model instance back to dict and verify no loss of data + message_response_model_json2 = message_response_model.to_dict() + assert message_response_model_json2 == message_response_model_json + +class TestOutputData(): + """ + Test Class for OutputData + """ + + def test_output_data_serialization(self): + """ + Test serialization/deserialization for OutputData + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model['dialog_node'] = 'testString' + dialog_node_visited_details_model['title'] = 'testString' + dialog_node_visited_details_model['conditions'] = 'testString' + + log_message_model = {} # LogMessage + log_message_model['level'] = 'info' + log_message_model['msg'] = 'testString' + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] + dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption + runtime_response_generic_model['response_type'] = 'option' + runtime_response_generic_model['title'] = 'testString' + runtime_response_generic_model['description'] = 'testString' + runtime_response_generic_model['preference'] = 'dropdown' + runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + + # Construct a json representation of a OutputData model + output_data_model_json = {} + output_data_model_json['nodes_visited'] = ['testString'] + output_data_model_json['nodes_visited_details'] = [dialog_node_visited_details_model] + output_data_model_json['log_messages'] = [log_message_model] + output_data_model_json['text'] = ['testString'] + output_data_model_json['generic'] = [runtime_response_generic_model] + output_data_model_json['foo'] = { 'foo': 'bar' } + + # Construct a model instance of OutputData by calling from_dict on the json representation + output_data_model = OutputData.from_dict(output_data_model_json) + assert output_data_model != False + + # Construct a model instance of OutputData by calling from_dict on the json representation + output_data_model_dict = OutputData.from_dict(output_data_model_json).__dict__ + output_data_model2 = OutputData(**output_data_model_dict) + + # Verify the model instances are equivalent + assert output_data_model == output_data_model2 + + # Convert model instance back to dict and verify no loss of data + output_data_model_json2 = output_data_model.to_dict() + assert output_data_model_json2 == output_data_model_json + +class TestPagination(): + """ + Test Class for Pagination + """ + + def test_pagination_serialization(self): + """ + Test serialization/deserialization for Pagination + """ + + # Construct a json representation of a Pagination model + pagination_model_json = {} + pagination_model_json['refresh_url'] = 'testString' + pagination_model_json['next_url'] = 'testString' + pagination_model_json['total'] = 38 + pagination_model_json['matched'] = 38 + pagination_model_json['refresh_cursor'] = 'testString' + pagination_model_json['next_cursor'] = 'testString' + + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model = Pagination.from_dict(pagination_model_json) + assert pagination_model != False + + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ + pagination_model2 = Pagination(**pagination_model_dict) + + # Verify the model instances are equivalent + assert pagination_model == pagination_model2 + + # Convert model instance back to dict and verify no loss of data + pagination_model_json2 = pagination_model.to_dict() + assert pagination_model_json2 == pagination_model_json + +class TestRuntimeEntity(): + """ + Test Class for RuntimeEntity + """ + + def test_runtime_entity_serialization(self): + """ + Test serialization/deserialization for RuntimeEntity + """ + + # Construct dict forms of any model objects needed in order to build this model. + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + # Construct a json representation of a RuntimeEntity model + runtime_entity_model_json = {} + runtime_entity_model_json['entity'] = 'testString' + runtime_entity_model_json['location'] = [38] + runtime_entity_model_json['value'] = 'testString' + runtime_entity_model_json['confidence'] = 72.5 + runtime_entity_model_json['metadata'] = {} + runtime_entity_model_json['groups'] = [capture_group_model] + runtime_entity_model_json['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model_json['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model_json['role'] = runtime_entity_role_model + + # Construct a model instance of RuntimeEntity by calling from_dict on the json representation + runtime_entity_model = RuntimeEntity.from_dict(runtime_entity_model_json) + assert runtime_entity_model != False + + # Construct a model instance of RuntimeEntity by calling from_dict on the json representation + runtime_entity_model_dict = RuntimeEntity.from_dict(runtime_entity_model_json).__dict__ + runtime_entity_model2 = RuntimeEntity(**runtime_entity_model_dict) + + # Verify the model instances are equivalent + assert runtime_entity_model == runtime_entity_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_entity_model_json2 = runtime_entity_model.to_dict() + assert runtime_entity_model_json2 == runtime_entity_model_json + +class TestRuntimeEntityAlternative(): + """ + Test Class for RuntimeEntityAlternative + """ + + def test_runtime_entity_alternative_serialization(self): + """ + Test serialization/deserialization for RuntimeEntityAlternative + """ + + # Construct a json representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model_json = {} + runtime_entity_alternative_model_json['value'] = 'testString' + runtime_entity_alternative_model_json['confidence'] = 72.5 + + # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation + runtime_entity_alternative_model = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json) + assert runtime_entity_alternative_model != False + + # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation + runtime_entity_alternative_model_dict = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json).__dict__ + runtime_entity_alternative_model2 = RuntimeEntityAlternative(**runtime_entity_alternative_model_dict) + + # Verify the model instances are equivalent + assert runtime_entity_alternative_model == runtime_entity_alternative_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() + assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json + +class TestRuntimeEntityInterpretation(): + """ + Test Class for RuntimeEntityInterpretation + """ + + def test_runtime_entity_interpretation_serialization(self): + """ + Test serialization/deserialization for RuntimeEntityInterpretation + """ + + # Construct a json representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model_json = {} + runtime_entity_interpretation_model_json['calendar_type'] = 'testString' + runtime_entity_interpretation_model_json['datetime_link'] = 'testString' + runtime_entity_interpretation_model_json['festival'] = 'testString' + runtime_entity_interpretation_model_json['granularity'] = 'day' + runtime_entity_interpretation_model_json['range_link'] = 'testString' + runtime_entity_interpretation_model_json['range_modifier'] = 'testString' + runtime_entity_interpretation_model_json['relative_day'] = 72.5 + runtime_entity_interpretation_model_json['relative_month'] = 72.5 + runtime_entity_interpretation_model_json['relative_week'] = 72.5 + runtime_entity_interpretation_model_json['relative_weekend'] = 72.5 + runtime_entity_interpretation_model_json['relative_year'] = 72.5 + runtime_entity_interpretation_model_json['specific_day'] = 72.5 + runtime_entity_interpretation_model_json['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model_json['specific_month'] = 72.5 + runtime_entity_interpretation_model_json['specific_quarter'] = 72.5 + runtime_entity_interpretation_model_json['specific_year'] = 72.5 + runtime_entity_interpretation_model_json['numeric_value'] = 72.5 + runtime_entity_interpretation_model_json['subtype'] = 'testString' + runtime_entity_interpretation_model_json['part_of_day'] = 'testString' + runtime_entity_interpretation_model_json['relative_hour'] = 72.5 + runtime_entity_interpretation_model_json['relative_minute'] = 72.5 + runtime_entity_interpretation_model_json['relative_second'] = 72.5 + runtime_entity_interpretation_model_json['specific_hour'] = 72.5 + runtime_entity_interpretation_model_json['specific_minute'] = 72.5 + runtime_entity_interpretation_model_json['specific_second'] = 72.5 + runtime_entity_interpretation_model_json['timezone'] = 'testString' + + # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation + runtime_entity_interpretation_model = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json) + assert runtime_entity_interpretation_model != False + + # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation + runtime_entity_interpretation_model_dict = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json).__dict__ + runtime_entity_interpretation_model2 = RuntimeEntityInterpretation(**runtime_entity_interpretation_model_dict) + + # Verify the model instances are equivalent + assert runtime_entity_interpretation_model == runtime_entity_interpretation_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() + assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json + +class TestRuntimeEntityRole(): + """ + Test Class for RuntimeEntityRole + """ + + def test_runtime_entity_role_serialization(self): + """ + Test serialization/deserialization for RuntimeEntityRole + """ + + # Construct a json representation of a RuntimeEntityRole model + runtime_entity_role_model_json = {} + runtime_entity_role_model_json['type'] = 'date_from' + + # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation + runtime_entity_role_model = RuntimeEntityRole.from_dict(runtime_entity_role_model_json) + assert runtime_entity_role_model != False + + # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation + runtime_entity_role_model_dict = RuntimeEntityRole.from_dict(runtime_entity_role_model_json).__dict__ + runtime_entity_role_model2 = RuntimeEntityRole(**runtime_entity_role_model_dict) + + # Verify the model instances are equivalent + assert runtime_entity_role_model == runtime_entity_role_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() + assert runtime_entity_role_model_json2 == runtime_entity_role_model_json + +class TestRuntimeIntent(): + """ + Test Class for RuntimeIntent + """ + + def test_runtime_intent_serialization(self): + """ + Test serialization/deserialization for RuntimeIntent + """ + + # Construct a json representation of a RuntimeIntent model + runtime_intent_model_json = {} + runtime_intent_model_json['intent'] = 'testString' + runtime_intent_model_json['confidence'] = 72.5 + + # Construct a model instance of RuntimeIntent by calling from_dict on the json representation + runtime_intent_model = RuntimeIntent.from_dict(runtime_intent_model_json) + assert runtime_intent_model != False + + # Construct a model instance of RuntimeIntent by calling from_dict on the json representation + runtime_intent_model_dict = RuntimeIntent.from_dict(runtime_intent_model_json).__dict__ + runtime_intent_model2 = RuntimeIntent(**runtime_intent_model_dict) + + # Verify the model instances are equivalent + assert runtime_intent_model == runtime_intent_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_intent_model_json2 = runtime_intent_model.to_dict() + assert runtime_intent_model_json2 == runtime_intent_model_json + +class TestSynonym(): + """ + Test Class for Synonym + """ + + def test_synonym_serialization(self): + """ + Test serialization/deserialization for Synonym + """ + + # Construct a json representation of a Synonym model + synonym_model_json = {} + synonym_model_json['synonym'] = 'testString' + synonym_model_json['created'] = '2020-01-28T18:40:40.123456Z' + synonym_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of Synonym by calling from_dict on the json representation + synonym_model = Synonym.from_dict(synonym_model_json) + assert synonym_model != False + + # Construct a model instance of Synonym by calling from_dict on the json representation + synonym_model_dict = Synonym.from_dict(synonym_model_json).__dict__ + synonym_model2 = Synonym(**synonym_model_dict) + + # Verify the model instances are equivalent + assert synonym_model == synonym_model2 + + # Convert model instance back to dict and verify no loss of data + synonym_model_json2 = synonym_model.to_dict() + assert synonym_model_json2 == synonym_model_json + +class TestSynonymCollection(): + """ + Test Class for SynonymCollection + """ + + def test_synonym_collection_serialization(self): + """ + Test serialization/deserialization for SynonymCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + synonym_model = {} # Synonym + synonym_model['synonym'] = 'testString' + synonym_model['created'] = '2020-01-28T18:40:40.123456Z' + synonym_model['updated'] = '2020-01-28T18:40:40.123456Z' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a SynonymCollection model + synonym_collection_model_json = {} + synonym_collection_model_json['synonyms'] = [synonym_model] + synonym_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of SynonymCollection by calling from_dict on the json representation + synonym_collection_model = SynonymCollection.from_dict(synonym_collection_model_json) + assert synonym_collection_model != False + + # Construct a model instance of SynonymCollection by calling from_dict on the json representation + synonym_collection_model_dict = SynonymCollection.from_dict(synonym_collection_model_json).__dict__ + synonym_collection_model2 = SynonymCollection(**synonym_collection_model_dict) + + # Verify the model instances are equivalent + assert synonym_collection_model == synonym_collection_model2 + + # Convert model instance back to dict and verify no loss of data + synonym_collection_model_json2 = synonym_collection_model.to_dict() + assert synonym_collection_model_json2 == synonym_collection_model_json + +class TestValue(): + """ + Test Class for Value + """ + + def test_value_serialization(self): + """ + Test serialization/deserialization for Value + """ + + # Construct a json representation of a Value model + value_model_json = {} + value_model_json['value'] = 'testString' + value_model_json['metadata'] = {} + value_model_json['type'] = 'synonyms' + value_model_json['synonyms'] = ['testString'] + value_model_json['patterns'] = ['testString'] + value_model_json['created'] = '2020-01-28T18:40:40.123456Z' + value_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of Value by calling from_dict on the json representation + value_model = Value.from_dict(value_model_json) + assert value_model != False + + # Construct a model instance of Value by calling from_dict on the json representation + value_model_dict = Value.from_dict(value_model_json).__dict__ + value_model2 = Value(**value_model_dict) + + # Verify the model instances are equivalent + assert value_model == value_model2 + + # Convert model instance back to dict and verify no loss of data + value_model_json2 = value_model.to_dict() + assert value_model_json2 == value_model_json + +class TestValueCollection(): + """ + Test Class for ValueCollection + """ + + def test_value_collection_serialization(self): + """ + Test serialization/deserialization for ValueCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + value_model = {} # Value + value_model['value'] = 'testString' + value_model['metadata'] = {} + value_model['type'] = 'synonyms' + value_model['synonyms'] = ['testString'] + value_model['patterns'] = ['testString'] + value_model['created'] = '2020-01-28T18:40:40.123456Z' + value_model['updated'] = '2020-01-28T18:40:40.123456Z' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a ValueCollection model + value_collection_model_json = {} + value_collection_model_json['values'] = [value_model] + value_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of ValueCollection by calling from_dict on the json representation + value_collection_model = ValueCollection.from_dict(value_collection_model_json) + assert value_collection_model != False + + # Construct a model instance of ValueCollection by calling from_dict on the json representation + value_collection_model_dict = ValueCollection.from_dict(value_collection_model_json).__dict__ + value_collection_model2 = ValueCollection(**value_collection_model_dict) + + # Verify the model instances are equivalent + assert value_collection_model == value_collection_model2 + + # Convert model instance back to dict and verify no loss of data + value_collection_model_json2 = value_collection_model.to_dict() + assert value_collection_model_json2 == value_collection_model_json + +class TestWebhook(): + """ + Test Class for Webhook + """ + + def test_webhook_serialization(self): + """ + Test serialization/deserialization for Webhook + """ + + # Construct dict forms of any model objects needed in order to build this model. + + webhook_header_model = {} # WebhookHeader + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + # Construct a json representation of a Webhook model + webhook_model_json = {} + webhook_model_json['url'] = 'testString' + webhook_model_json['name'] = 'testString' + webhook_model_json['headers'] = [webhook_header_model] + + # Construct a model instance of Webhook by calling from_dict on the json representation + webhook_model = Webhook.from_dict(webhook_model_json) + assert webhook_model != False + + # Construct a model instance of Webhook by calling from_dict on the json representation + webhook_model_dict = Webhook.from_dict(webhook_model_json).__dict__ + webhook_model2 = Webhook(**webhook_model_dict) + + # Verify the model instances are equivalent + assert webhook_model == webhook_model2 + + # Convert model instance back to dict and verify no loss of data + webhook_model_json2 = webhook_model.to_dict() + assert webhook_model_json2 == webhook_model_json + +class TestWebhookHeader(): + """ + Test Class for WebhookHeader + """ + + def test_webhook_header_serialization(self): + """ + Test serialization/deserialization for WebhookHeader + """ + + # Construct a json representation of a WebhookHeader model + webhook_header_model_json = {} + webhook_header_model_json['name'] = 'testString' + webhook_header_model_json['value'] = 'testString' + + # Construct a model instance of WebhookHeader by calling from_dict on the json representation + webhook_header_model = WebhookHeader.from_dict(webhook_header_model_json) + assert webhook_header_model != False + + # Construct a model instance of WebhookHeader by calling from_dict on the json representation + webhook_header_model_dict = WebhookHeader.from_dict(webhook_header_model_json).__dict__ + webhook_header_model2 = WebhookHeader(**webhook_header_model_dict) + + # Verify the model instances are equivalent + assert webhook_header_model == webhook_header_model2 + + # Convert model instance back to dict and verify no loss of data + webhook_header_model_json2 = webhook_header_model.to_dict() + assert webhook_header_model_json2 == webhook_header_model_json + +class TestWorkspace(): + """ + Test Class for Workspace + """ + + def test_workspace_serialization(self): + """ + Test serialization/deserialization for Workspace + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeImage + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model['overwrite'] = True + + dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_model = {} # DialogNode + dialog_node_model['dialog_node'] = 'testString' + dialog_node_model['description'] = 'testString' + dialog_node_model['conditions'] = 'testString' + dialog_node_model['parent'] = 'testString' + dialog_node_model['previous_sibling'] = 'testString' + dialog_node_model['output'] = dialog_node_output_model + dialog_node_model['context'] = dialog_node_context_model + dialog_node_model['metadata'] = {} + dialog_node_model['next_step'] = dialog_node_next_step_model + dialog_node_model['title'] = 'testString' + dialog_node_model['type'] = 'standard' + dialog_node_model['event_name'] = 'focus' + dialog_node_model['variable'] = 'testString' + dialog_node_model['actions'] = [dialog_node_action_model] + dialog_node_model['digress_in'] = 'not_available' + dialog_node_model['digress_out'] = 'allow_returning' + dialog_node_model['digress_out_slots'] = 'not_allowed' + dialog_node_model['user_label'] = 'testString' + dialog_node_model['disambiguation_opt_out'] = True + dialog_node_model['disabled'] = True + dialog_node_model['created'] = '2020-01-28T18:40:40.123456Z' + dialog_node_model['updated'] = '2020-01-28T18:40:40.123456Z' + + counterexample_model = {} # Counterexample + counterexample_model['text'] = 'testString' + counterexample_model['created'] = '2020-01-28T18:40:40.123456Z' + counterexample_model['updated'] = '2020-01-28T18:40:40.123456Z' + + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model['store_generic_responses'] = True + + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model['prompt'] = 'testString' + workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model['enabled'] = True + workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model['randomize'] = True + workspace_system_settings_disambiguation_model['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' + + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model['enabled'] = True + + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model['enabled'] = True + + workspace_system_settings_model = {} # WorkspaceSystemSettings + workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model + workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model + workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['spelling_suggestions'] = True + workspace_system_settings_model['spelling_auto_correct'] = True + workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model + workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + + webhook_header_model = {} # WebhookHeader + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + webhook_model = {} # Webhook + webhook_model['url'] = 'testString' + webhook_model['name'] = 'testString' + webhook_model['headers'] = [webhook_header_model] + + mention_model = {} # Mention + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + example_model = {} # Example + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + example_model['created'] = '2020-01-28T18:40:40.123456Z' + example_model['updated'] = '2020-01-28T18:40:40.123456Z' + + intent_model = {} # Intent + intent_model['intent'] = 'testString' + intent_model['description'] = 'testString' + intent_model['created'] = '2020-01-28T18:40:40.123456Z' + intent_model['updated'] = '2020-01-28T18:40:40.123456Z' + intent_model['examples'] = [example_model] + + value_model = {} # Value + value_model['value'] = 'testString' + value_model['metadata'] = {} + value_model['type'] = 'synonyms' + value_model['synonyms'] = ['testString'] + value_model['patterns'] = ['testString'] + value_model['created'] = '2020-01-28T18:40:40.123456Z' + value_model['updated'] = '2020-01-28T18:40:40.123456Z' + + entity_model = {} # Entity + entity_model['entity'] = 'testString' + entity_model['description'] = 'testString' + entity_model['metadata'] = {} + entity_model['fuzzy_match'] = True + entity_model['created'] = '2020-01-28T18:40:40.123456Z' + entity_model['updated'] = '2020-01-28T18:40:40.123456Z' + entity_model['values'] = [value_model] + + # Construct a json representation of a Workspace model + workspace_model_json = {} + workspace_model_json['name'] = 'testString' + workspace_model_json['description'] = 'testString' + workspace_model_json['language'] = 'testString' + workspace_model_json['workspace_id'] = 'testString' + workspace_model_json['dialog_nodes'] = [dialog_node_model] + workspace_model_json['counterexamples'] = [counterexample_model] + workspace_model_json['created'] = '2020-01-28T18:40:40.123456Z' + workspace_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + workspace_model_json['metadata'] = {} + workspace_model_json['learning_opt_out'] = True + workspace_model_json['system_settings'] = workspace_system_settings_model + workspace_model_json['status'] = 'Non Existent' + workspace_model_json['webhooks'] = [webhook_model] + workspace_model_json['intents'] = [intent_model] + workspace_model_json['entities'] = [entity_model] + + # Construct a model instance of Workspace by calling from_dict on the json representation + workspace_model = Workspace.from_dict(workspace_model_json) + assert workspace_model != False + + # Construct a model instance of Workspace by calling from_dict on the json representation + workspace_model_dict = Workspace.from_dict(workspace_model_json).__dict__ + workspace_model2 = Workspace(**workspace_model_dict) + + # Verify the model instances are equivalent + assert workspace_model == workspace_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_model_json2 = workspace_model.to_dict() + assert workspace_model_json2 == workspace_model_json + +class TestWorkspaceCollection(): + """ + Test Class for WorkspaceCollection + """ + + def test_workspace_collection_serialization(self): + """ + Test serialization/deserialization for WorkspaceCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeImage + dialog_node_output_generic_model['response_type'] = 'image' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model['overwrite'] = True + + dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = { 'foo': 'bar' } + + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {} + dialog_node_context_model['foo'] = { 'foo': 'bar' } + + dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_model = {} # DialogNode + dialog_node_model['dialog_node'] = 'testString' + dialog_node_model['description'] = 'testString' + dialog_node_model['conditions'] = 'testString' + dialog_node_model['parent'] = 'testString' + dialog_node_model['previous_sibling'] = 'testString' + dialog_node_model['output'] = dialog_node_output_model + dialog_node_model['context'] = dialog_node_context_model + dialog_node_model['metadata'] = {} + dialog_node_model['next_step'] = dialog_node_next_step_model + dialog_node_model['title'] = 'testString' + dialog_node_model['type'] = 'standard' + dialog_node_model['event_name'] = 'focus' + dialog_node_model['variable'] = 'testString' + dialog_node_model['actions'] = [dialog_node_action_model] + dialog_node_model['digress_in'] = 'not_available' + dialog_node_model['digress_out'] = 'allow_returning' + dialog_node_model['digress_out_slots'] = 'not_allowed' + dialog_node_model['user_label'] = 'testString' + dialog_node_model['disambiguation_opt_out'] = True + dialog_node_model['disabled'] = True + dialog_node_model['created'] = '2020-01-28T18:40:40.123456Z' + dialog_node_model['updated'] = '2020-01-28T18:40:40.123456Z' + + counterexample_model = {} # Counterexample + counterexample_model['text'] = 'testString' + counterexample_model['created'] = '2020-01-28T18:40:40.123456Z' + counterexample_model['updated'] = '2020-01-28T18:40:40.123456Z' + + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model['store_generic_responses'] = True + + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model['prompt'] = 'testString' + workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model['enabled'] = True + workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model['randomize'] = True + workspace_system_settings_disambiguation_model['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' + + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model['enabled'] = True + + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model['enabled'] = True + + workspace_system_settings_model = {} # WorkspaceSystemSettings + workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model + workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model + workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['spelling_suggestions'] = True + workspace_system_settings_model['spelling_auto_correct'] = True + workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model + workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + + webhook_header_model = {} # WebhookHeader + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + webhook_model = {} # Webhook + webhook_model['url'] = 'testString' + webhook_model['name'] = 'testString' + webhook_model['headers'] = [webhook_header_model] + + mention_model = {} # Mention + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + example_model = {} # Example + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + example_model['created'] = '2020-01-28T18:40:40.123456Z' + example_model['updated'] = '2020-01-28T18:40:40.123456Z' + + intent_model = {} # Intent + intent_model['intent'] = 'testString' + intent_model['description'] = 'testString' + intent_model['created'] = '2020-01-28T18:40:40.123456Z' + intent_model['updated'] = '2020-01-28T18:40:40.123456Z' + intent_model['examples'] = [example_model] + + value_model = {} # Value + value_model['value'] = 'testString' + value_model['metadata'] = {} + value_model['type'] = 'synonyms' + value_model['synonyms'] = ['testString'] + value_model['patterns'] = ['testString'] + value_model['created'] = '2020-01-28T18:40:40.123456Z' + value_model['updated'] = '2020-01-28T18:40:40.123456Z' + + entity_model = {} # Entity + entity_model['entity'] = 'testString' + entity_model['description'] = 'testString' + entity_model['metadata'] = {} + entity_model['fuzzy_match'] = True + entity_model['created'] = '2020-01-28T18:40:40.123456Z' + entity_model['updated'] = '2020-01-28T18:40:40.123456Z' + entity_model['values'] = [value_model] + + workspace_model = {} # Workspace + workspace_model['name'] = 'testString' + workspace_model['description'] = 'testString' + workspace_model['language'] = 'testString' + workspace_model['workspace_id'] = 'testString' + workspace_model['dialog_nodes'] = [dialog_node_model] + workspace_model['counterexamples'] = [counterexample_model] + workspace_model['created'] = '2020-01-28T18:40:40.123456Z' + workspace_model['updated'] = '2020-01-28T18:40:40.123456Z' + workspace_model['metadata'] = {} + workspace_model['learning_opt_out'] = True + workspace_model['system_settings'] = workspace_system_settings_model + workspace_model['status'] = 'Non Existent' + workspace_model['webhooks'] = [webhook_model] + workspace_model['intents'] = [intent_model] + workspace_model['entities'] = [entity_model] + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a WorkspaceCollection model + workspace_collection_model_json = {} + workspace_collection_model_json['workspaces'] = [workspace_model] + workspace_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of WorkspaceCollection by calling from_dict on the json representation + workspace_collection_model = WorkspaceCollection.from_dict(workspace_collection_model_json) + assert workspace_collection_model != False + + # Construct a model instance of WorkspaceCollection by calling from_dict on the json representation + workspace_collection_model_dict = WorkspaceCollection.from_dict(workspace_collection_model_json).__dict__ + workspace_collection_model2 = WorkspaceCollection(**workspace_collection_model_dict) + + # Verify the model instances are equivalent + assert workspace_collection_model == workspace_collection_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_collection_model_json2 = workspace_collection_model.to_dict() + assert workspace_collection_model_json2 == workspace_collection_model_json + +class TestWorkspaceSystemSettings(): + """ + Test Class for WorkspaceSystemSettings + """ + + def test_workspace_system_settings_serialization(self): + """ + Test serialization/deserialization for WorkspaceSystemSettings + """ + + # Construct dict forms of any model objects needed in order to build this model. + + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model['store_generic_responses'] = True + + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model['prompt'] = 'testString' + workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model['enabled'] = True + workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model['randomize'] = True + workspace_system_settings_disambiguation_model['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' + + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model['enabled'] = True + + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model['enabled'] = True + + # Construct a json representation of a WorkspaceSystemSettings model + workspace_system_settings_model_json = {} + workspace_system_settings_model_json['tooling'] = workspace_system_settings_tooling_model + workspace_system_settings_model_json['disambiguation'] = workspace_system_settings_disambiguation_model + workspace_system_settings_model_json['human_agent_assist'] = {} + workspace_system_settings_model_json['spelling_suggestions'] = True + workspace_system_settings_model_json['spelling_auto_correct'] = True + workspace_system_settings_model_json['system_entities'] = workspace_system_settings_system_entities_model + workspace_system_settings_model_json['off_topic'] = workspace_system_settings_off_topic_model + + # Construct a model instance of WorkspaceSystemSettings by calling from_dict on the json representation + workspace_system_settings_model = WorkspaceSystemSettings.from_dict(workspace_system_settings_model_json) + assert workspace_system_settings_model != False + + # Construct a model instance of WorkspaceSystemSettings by calling from_dict on the json representation + workspace_system_settings_model_dict = WorkspaceSystemSettings.from_dict(workspace_system_settings_model_json).__dict__ + workspace_system_settings_model2 = WorkspaceSystemSettings(**workspace_system_settings_model_dict) + + # Verify the model instances are equivalent + assert workspace_system_settings_model == workspace_system_settings_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_system_settings_model_json2 = workspace_system_settings_model.to_dict() + assert workspace_system_settings_model_json2 == workspace_system_settings_model_json + +class TestWorkspaceSystemSettingsDisambiguation(): + """ + Test Class for WorkspaceSystemSettingsDisambiguation + """ + + def test_workspace_system_settings_disambiguation_serialization(self): + """ + Test serialization/deserialization for WorkspaceSystemSettingsDisambiguation + """ + + # Construct a json representation of a WorkspaceSystemSettingsDisambiguation model + workspace_system_settings_disambiguation_model_json = {} + workspace_system_settings_disambiguation_model_json['prompt'] = 'testString' + workspace_system_settings_disambiguation_model_json['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model_json['enabled'] = True + workspace_system_settings_disambiguation_model_json['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model_json['randomize'] = True + workspace_system_settings_disambiguation_model_json['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model_json['suggestion_text_policy'] = 'testString' + + # Construct a model instance of WorkspaceSystemSettingsDisambiguation by calling from_dict on the json representation + workspace_system_settings_disambiguation_model = WorkspaceSystemSettingsDisambiguation.from_dict(workspace_system_settings_disambiguation_model_json) + assert workspace_system_settings_disambiguation_model != False + + # Construct a model instance of WorkspaceSystemSettingsDisambiguation by calling from_dict on the json representation + workspace_system_settings_disambiguation_model_dict = WorkspaceSystemSettingsDisambiguation.from_dict(workspace_system_settings_disambiguation_model_json).__dict__ + workspace_system_settings_disambiguation_model2 = WorkspaceSystemSettingsDisambiguation(**workspace_system_settings_disambiguation_model_dict) + + # Verify the model instances are equivalent + assert workspace_system_settings_disambiguation_model == workspace_system_settings_disambiguation_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_system_settings_disambiguation_model_json2 = workspace_system_settings_disambiguation_model.to_dict() + assert workspace_system_settings_disambiguation_model_json2 == workspace_system_settings_disambiguation_model_json + +class TestWorkspaceSystemSettingsOffTopic(): + """ + Test Class for WorkspaceSystemSettingsOffTopic + """ + + def test_workspace_system_settings_off_topic_serialization(self): + """ + Test serialization/deserialization for WorkspaceSystemSettingsOffTopic + """ + + # Construct a json representation of a WorkspaceSystemSettingsOffTopic model + workspace_system_settings_off_topic_model_json = {} + workspace_system_settings_off_topic_model_json['enabled'] = True + + # Construct a model instance of WorkspaceSystemSettingsOffTopic by calling from_dict on the json representation + workspace_system_settings_off_topic_model = WorkspaceSystemSettingsOffTopic.from_dict(workspace_system_settings_off_topic_model_json) + assert workspace_system_settings_off_topic_model != False + + # Construct a model instance of WorkspaceSystemSettingsOffTopic by calling from_dict on the json representation + workspace_system_settings_off_topic_model_dict = WorkspaceSystemSettingsOffTopic.from_dict(workspace_system_settings_off_topic_model_json).__dict__ + workspace_system_settings_off_topic_model2 = WorkspaceSystemSettingsOffTopic(**workspace_system_settings_off_topic_model_dict) + + # Verify the model instances are equivalent + assert workspace_system_settings_off_topic_model == workspace_system_settings_off_topic_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_system_settings_off_topic_model_json2 = workspace_system_settings_off_topic_model.to_dict() + assert workspace_system_settings_off_topic_model_json2 == workspace_system_settings_off_topic_model_json + +class TestWorkspaceSystemSettingsSystemEntities(): + """ + Test Class for WorkspaceSystemSettingsSystemEntities + """ + + def test_workspace_system_settings_system_entities_serialization(self): + """ + Test serialization/deserialization for WorkspaceSystemSettingsSystemEntities + """ + + # Construct a json representation of a WorkspaceSystemSettingsSystemEntities model + workspace_system_settings_system_entities_model_json = {} + workspace_system_settings_system_entities_model_json['enabled'] = True + + # Construct a model instance of WorkspaceSystemSettingsSystemEntities by calling from_dict on the json representation + workspace_system_settings_system_entities_model = WorkspaceSystemSettingsSystemEntities.from_dict(workspace_system_settings_system_entities_model_json) + assert workspace_system_settings_system_entities_model != False + + # Construct a model instance of WorkspaceSystemSettingsSystemEntities by calling from_dict on the json representation + workspace_system_settings_system_entities_model_dict = WorkspaceSystemSettingsSystemEntities.from_dict(workspace_system_settings_system_entities_model_json).__dict__ + workspace_system_settings_system_entities_model2 = WorkspaceSystemSettingsSystemEntities(**workspace_system_settings_system_entities_model_dict) + + # Verify the model instances are equivalent + assert workspace_system_settings_system_entities_model == workspace_system_settings_system_entities_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_system_settings_system_entities_model_json2 = workspace_system_settings_system_entities_model.to_dict() + assert workspace_system_settings_system_entities_model_json2 == workspace_system_settings_system_entities_model_json + +class TestWorkspaceSystemSettingsTooling(): + """ + Test Class for WorkspaceSystemSettingsTooling + """ + + def test_workspace_system_settings_tooling_serialization(self): + """ + Test serialization/deserialization for WorkspaceSystemSettingsTooling + """ + + # Construct a json representation of a WorkspaceSystemSettingsTooling model + workspace_system_settings_tooling_model_json = {} + workspace_system_settings_tooling_model_json['store_generic_responses'] = True + + # Construct a model instance of WorkspaceSystemSettingsTooling by calling from_dict on the json representation + workspace_system_settings_tooling_model = WorkspaceSystemSettingsTooling.from_dict(workspace_system_settings_tooling_model_json) + assert workspace_system_settings_tooling_model != False + + # Construct a model instance of WorkspaceSystemSettingsTooling by calling from_dict on the json representation + workspace_system_settings_tooling_model_dict = WorkspaceSystemSettingsTooling.from_dict(workspace_system_settings_tooling_model_json).__dict__ + workspace_system_settings_tooling_model2 = WorkspaceSystemSettingsTooling(**workspace_system_settings_tooling_model_dict) + + # Verify the model instances are equivalent + assert workspace_system_settings_tooling_model == workspace_system_settings_tooling_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_system_settings_tooling_model_json2 = workspace_system_settings_tooling_model.to_dict() + assert workspace_system_settings_tooling_model_json2 == workspace_system_settings_tooling_model_json + +class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent(): + """ + Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent + """ + + def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent model + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json = {} + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['response_type'] = 'connect_to_agent' + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['message_to_human_agent'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['agent_available'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['agent_unavailable'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['transfer_info'] = dialog_node_output_connect_to_agent_transfer_info_model + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent.from_dict(dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json) + assert dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model != False + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_dict = DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent.from_dict(dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json).__dict__ + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model2 = DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent(**dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model == dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model.to_dict() + assert dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json + +class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeImage(): + """ + Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeImage + """ + + def test_dialog_node_output_generic_dialog_node_output_response_type_image_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeImage + """ + + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + dialog_node_output_generic_dialog_node_output_response_type_image_model_json = {} + dialog_node_output_generic_dialog_node_output_response_type_image_model_json['response_type'] = 'image' + dialog_node_output_generic_dialog_node_output_response_type_image_model_json['source'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_image_model_json['title'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_image_model_json['description'] = 'testString' + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeImage by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_image_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeImage.from_dict(dialog_node_output_generic_dialog_node_output_response_type_image_model_json) + assert dialog_node_output_generic_dialog_node_output_response_type_image_model != False + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeImage by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_image_model_dict = DialogNodeOutputGenericDialogNodeOutputResponseTypeImage.from_dict(dialog_node_output_generic_dialog_node_output_response_type_image_model_json).__dict__ + dialog_node_output_generic_dialog_node_output_response_type_image_model2 = DialogNodeOutputGenericDialogNodeOutputResponseTypeImage(**dialog_node_output_generic_dialog_node_output_response_type_image_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_generic_dialog_node_output_response_type_image_model == dialog_node_output_generic_dialog_node_output_response_type_image_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_generic_dialog_node_output_response_type_image_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_image_model.to_dict() + assert dialog_node_output_generic_dialog_node_output_response_type_image_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_image_model_json + +class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeOption(): + """ + Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeOption + """ + + def test_dialog_node_output_generic_dialog_node_output_response_type_option_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeOption + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] + dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption model + dialog_node_output_generic_dialog_node_output_response_type_option_model_json = {} + dialog_node_output_generic_dialog_node_output_response_type_option_model_json['response_type'] = 'option' + dialog_node_output_generic_dialog_node_output_response_type_option_model_json['title'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_option_model_json['description'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_option_model_json['preference'] = 'dropdown' + dialog_node_output_generic_dialog_node_output_response_type_option_model_json['options'] = [dialog_node_output_options_element_model] + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeOption by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_option_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeOption.from_dict(dialog_node_output_generic_dialog_node_output_response_type_option_model_json) + assert dialog_node_output_generic_dialog_node_output_response_type_option_model != False + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeOption by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_option_model_dict = DialogNodeOutputGenericDialogNodeOutputResponseTypeOption.from_dict(dialog_node_output_generic_dialog_node_output_response_type_option_model_json).__dict__ + dialog_node_output_generic_dialog_node_output_response_type_option_model2 = DialogNodeOutputGenericDialogNodeOutputResponseTypeOption(**dialog_node_output_generic_dialog_node_output_response_type_option_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_generic_dialog_node_output_response_type_option_model == dialog_node_output_generic_dialog_node_output_response_type_option_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_generic_dialog_node_output_response_type_option_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_option_model.to_dict() + assert dialog_node_output_generic_dialog_node_output_response_type_option_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_option_model_json + +class TestDialogNodeOutputGenericDialogNodeOutputResponseTypePause(): + """ + Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypePause + """ + + def test_dialog_node_output_generic_dialog_node_output_response_type_pause_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypePause + """ + + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypePause model + dialog_node_output_generic_dialog_node_output_response_type_pause_model_json = {} + dialog_node_output_generic_dialog_node_output_response_type_pause_model_json['response_type'] = 'pause' + dialog_node_output_generic_dialog_node_output_response_type_pause_model_json['time'] = 38 + dialog_node_output_generic_dialog_node_output_response_type_pause_model_json['typing'] = True + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypePause by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_pause_model = DialogNodeOutputGenericDialogNodeOutputResponseTypePause.from_dict(dialog_node_output_generic_dialog_node_output_response_type_pause_model_json) + assert dialog_node_output_generic_dialog_node_output_response_type_pause_model != False + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypePause by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_pause_model_dict = DialogNodeOutputGenericDialogNodeOutputResponseTypePause.from_dict(dialog_node_output_generic_dialog_node_output_response_type_pause_model_json).__dict__ + dialog_node_output_generic_dialog_node_output_response_type_pause_model2 = DialogNodeOutputGenericDialogNodeOutputResponseTypePause(**dialog_node_output_generic_dialog_node_output_response_type_pause_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_generic_dialog_node_output_response_type_pause_model == dialog_node_output_generic_dialog_node_output_response_type_pause_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_generic_dialog_node_output_response_type_pause_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_pause_model.to_dict() + assert dialog_node_output_generic_dialog_node_output_response_type_pause_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_pause_model_json + +class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill(): + """ + Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill + """ + + def test_dialog_node_output_generic_dialog_node_output_response_type_search_skill_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill + """ + + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill model + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json = {} + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['response_type'] = 'search_skill' + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['query'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['query_type'] = 'natural_language' + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['filter'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['discovery_version'] = 'testString' + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill.from_dict(dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json) + assert dialog_node_output_generic_dialog_node_output_response_type_search_skill_model != False + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_dict = DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill.from_dict(dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json).__dict__ + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model2 = DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill(**dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_generic_dialog_node_output_response_type_search_skill_model == dialog_node_output_generic_dialog_node_output_response_type_search_skill_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_search_skill_model.to_dict() + assert dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json + +class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeText(): + """ + Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeText + """ + + def test_dialog_node_output_generic_dialog_node_output_response_type_text_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeText + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model + dialog_node_output_generic_dialog_node_output_response_type_text_model_json = {} + dialog_node_output_generic_dialog_node_output_response_type_text_model_json['response_type'] = 'text' + dialog_node_output_generic_dialog_node_output_response_type_text_model_json['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_dialog_node_output_response_type_text_model_json['selection_policy'] = 'sequential' + dialog_node_output_generic_dialog_node_output_response_type_text_model_json['delimiter'] = 'testString' + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeText by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_text_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeText.from_dict(dialog_node_output_generic_dialog_node_output_response_type_text_model_json) + assert dialog_node_output_generic_dialog_node_output_response_type_text_model != False + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeText by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_text_model_dict = DialogNodeOutputGenericDialogNodeOutputResponseTypeText.from_dict(dialog_node_output_generic_dialog_node_output_response_type_text_model_json).__dict__ + dialog_node_output_generic_dialog_node_output_response_type_text_model2 = DialogNodeOutputGenericDialogNodeOutputResponseTypeText(**dialog_node_output_generic_dialog_node_output_response_type_text_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_generic_dialog_node_output_response_type_text_model == dialog_node_output_generic_dialog_node_output_response_type_text_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_text_model.to_dict() + assert dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_text_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent + """ + + def test_runtime_response_generic_runtime_response_type_connect_to_agent_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent model + runtime_response_generic_runtime_response_type_connect_to_agent_model_json = {} + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['response_type'] = 'connect_to_agent' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['message_to_human_agent'] = 'testString' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_available'] = 'testString' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_unavailable'] = 'testString' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['transfer_info'] = dialog_node_output_connect_to_agent_transfer_info_model + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['topic'] = 'testString' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['dialog_node'] = 'testString' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeConnectToAgent by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_connect_to_agent_model = RuntimeResponseGenericRuntimeResponseTypeConnectToAgent.from_dict(runtime_response_generic_runtime_response_type_connect_to_agent_model_json) + assert runtime_response_generic_runtime_response_type_connect_to_agent_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeConnectToAgent by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_connect_to_agent_model_dict = RuntimeResponseGenericRuntimeResponseTypeConnectToAgent.from_dict(runtime_response_generic_runtime_response_type_connect_to_agent_model_json).__dict__ + runtime_response_generic_runtime_response_type_connect_to_agent_model2 = RuntimeResponseGenericRuntimeResponseTypeConnectToAgent(**runtime_response_generic_runtime_response_type_connect_to_agent_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_connect_to_agent_model == runtime_response_generic_runtime_response_type_connect_to_agent_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() + assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeImage(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeImage + """ + + def test_runtime_response_generic_runtime_response_type_image_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeImage + """ + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeImage model + runtime_response_generic_runtime_response_type_image_model_json = {} + runtime_response_generic_runtime_response_type_image_model_json['response_type'] = 'image' + runtime_response_generic_runtime_response_type_image_model_json['source'] = 'testString' + runtime_response_generic_runtime_response_type_image_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_image_model_json['description'] = 'testString' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeImage by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_image_model = RuntimeResponseGenericRuntimeResponseTypeImage.from_dict(runtime_response_generic_runtime_response_type_image_model_json) + assert runtime_response_generic_runtime_response_type_image_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeImage by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_image_model_dict = RuntimeResponseGenericRuntimeResponseTypeImage.from_dict(runtime_response_generic_runtime_response_type_image_model_json).__dict__ + runtime_response_generic_runtime_response_type_image_model2 = RuntimeResponseGenericRuntimeResponseTypeImage(**runtime_response_generic_runtime_response_type_image_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_image_model == runtime_response_generic_runtime_response_type_image_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_image_model_json2 = runtime_response_generic_runtime_response_type_image_model.to_dict() + assert runtime_response_generic_runtime_response_type_image_model_json2 == runtime_response_generic_runtime_response_type_image_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeOption(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeOption + """ + + def test_runtime_response_generic_runtime_response_type_option_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeOption + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] + dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeOption model + runtime_response_generic_runtime_response_type_option_model_json = {} + runtime_response_generic_runtime_response_type_option_model_json['response_type'] = 'option' + runtime_response_generic_runtime_response_type_option_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_option_model_json['description'] = 'testString' + runtime_response_generic_runtime_response_type_option_model_json['preference'] = 'dropdown' + runtime_response_generic_runtime_response_type_option_model_json['options'] = [dialog_node_output_options_element_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeOption by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_option_model = RuntimeResponseGenericRuntimeResponseTypeOption.from_dict(runtime_response_generic_runtime_response_type_option_model_json) + assert runtime_response_generic_runtime_response_type_option_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeOption by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_option_model_dict = RuntimeResponseGenericRuntimeResponseTypeOption.from_dict(runtime_response_generic_runtime_response_type_option_model_json).__dict__ + runtime_response_generic_runtime_response_type_option_model2 = RuntimeResponseGenericRuntimeResponseTypeOption(**runtime_response_generic_runtime_response_type_option_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_option_model == runtime_response_generic_runtime_response_type_option_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_option_model_json2 = runtime_response_generic_runtime_response_type_option_model.to_dict() + assert runtime_response_generic_runtime_response_type_option_model_json2 == runtime_response_generic_runtime_response_type_option_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypePause(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypePause + """ + + def test_runtime_response_generic_runtime_response_type_pause_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypePause + """ + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypePause model + runtime_response_generic_runtime_response_type_pause_model_json = {} + runtime_response_generic_runtime_response_type_pause_model_json['response_type'] = 'pause' + runtime_response_generic_runtime_response_type_pause_model_json['time'] = 38 + runtime_response_generic_runtime_response_type_pause_model_json['typing'] = True + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypePause by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_pause_model = RuntimeResponseGenericRuntimeResponseTypePause.from_dict(runtime_response_generic_runtime_response_type_pause_model_json) + assert runtime_response_generic_runtime_response_type_pause_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypePause by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_pause_model_dict = RuntimeResponseGenericRuntimeResponseTypePause.from_dict(runtime_response_generic_runtime_response_type_pause_model_json).__dict__ + runtime_response_generic_runtime_response_type_pause_model2 = RuntimeResponseGenericRuntimeResponseTypePause(**runtime_response_generic_runtime_response_type_pause_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_pause_model == runtime_response_generic_runtime_response_type_pause_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_pause_model_json2 = runtime_response_generic_runtime_response_type_pause_model.to_dict() + assert runtime_response_generic_runtime_response_type_pause_model_json2 == runtime_response_generic_runtime_response_type_pause_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeSuggestion(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeSuggestion + """ + + def test_runtime_response_generic_runtime_response_type_suggestion_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeSuggestion + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_model = {} # MessageInput + message_input_model['text'] = 'testString' + message_input_model['spelling_suggestions'] = True + message_input_model['spelling_auto_correct'] = True + message_input_model['suggested_text'] = 'testString' + message_input_model['original_text'] = 'testString' + message_input_model['foo'] = { 'foo': 'bar' } + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model['input'] = message_input_model + dialog_suggestion_value_model['intents'] = [runtime_intent_model] + dialog_suggestion_value_model['entities'] = [runtime_entity_model] + + dialog_suggestion_model = {} # DialogSuggestion + dialog_suggestion_model['label'] = 'testString' + dialog_suggestion_model['value'] = dialog_suggestion_value_model + dialog_suggestion_model['output'] = {} + dialog_suggestion_model['dialog_node'] = 'testString' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSuggestion model + runtime_response_generic_runtime_response_type_suggestion_model_json = {} + runtime_response_generic_runtime_response_type_suggestion_model_json['response_type'] = 'suggestion' + runtime_response_generic_runtime_response_type_suggestion_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_suggestion_model_json['suggestions'] = [dialog_suggestion_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeSuggestion by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_suggestion_model = RuntimeResponseGenericRuntimeResponseTypeSuggestion.from_dict(runtime_response_generic_runtime_response_type_suggestion_model_json) + assert runtime_response_generic_runtime_response_type_suggestion_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeSuggestion by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_suggestion_model_dict = RuntimeResponseGenericRuntimeResponseTypeSuggestion.from_dict(runtime_response_generic_runtime_response_type_suggestion_model_json).__dict__ + runtime_response_generic_runtime_response_type_suggestion_model2 = RuntimeResponseGenericRuntimeResponseTypeSuggestion(**runtime_response_generic_runtime_response_type_suggestion_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_suggestion_model == runtime_response_generic_runtime_response_type_suggestion_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_suggestion_model_json2 = runtime_response_generic_runtime_response_type_suggestion_model.to_dict() + assert runtime_response_generic_runtime_response_type_suggestion_model_json2 == runtime_response_generic_runtime_response_type_suggestion_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeText(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeText + """ + + def test_runtime_response_generic_runtime_response_type_text_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeText + """ + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeText model + runtime_response_generic_runtime_response_type_text_model_json = {} + runtime_response_generic_runtime_response_type_text_model_json['response_type'] = 'text' + runtime_response_generic_runtime_response_type_text_model_json['text'] = 'testString' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeText by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_text_model = RuntimeResponseGenericRuntimeResponseTypeText.from_dict(runtime_response_generic_runtime_response_type_text_model_json) + assert runtime_response_generic_runtime_response_type_text_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeText by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_text_model_dict = RuntimeResponseGenericRuntimeResponseTypeText.from_dict(runtime_response_generic_runtime_response_type_text_model_json).__dict__ + runtime_response_generic_runtime_response_type_text_model2 = RuntimeResponseGenericRuntimeResponseTypeText(**runtime_response_generic_runtime_response_type_text_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_text_model == runtime_response_generic_runtime_response_type_text_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_text_model_json2 = runtime_response_generic_runtime_response_type_text_model.to_dict() + assert runtime_response_generic_runtime_response_type_text_model_json2 == runtime_response_generic_runtime_response_type_text_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index caf5aefac..708a44320 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -13,161 +13,171 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Unit Tests for AssistantV2 +""" + from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect import json import pytest +import re +import requests import responses -import ibm_watson.assistant_v2 +import urllib from ibm_watson.assistant_v2 import * +version = 'testString' + +service = AssistantV2( + authenticator=NoAuthAuthenticator(), + version=version + ) + base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: Sessions ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_session -#----------------------------------------------------------------------------- class TestCreateSession(): + """ + Test Class for create_session + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_session_response(self): - body = self.construct_full_body() - response = fake_response_SessionResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_session_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_SessionResponse_json - send_request(self, body, response) + def test_create_session_all_params(self): + """ + create_session() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions') + mock_response = '{"session_id": "session_id"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = service.create_session( + assistant_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_session_empty(self): - check_empty_required_params(self, fake_response_SessionResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/assistants/{0}/sessions'.format(body['assistant_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_create_session_value_error(self): + """ + test_create_session_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions') + mock_response = '{"session_id": "session_id"}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - - def call_service(self, body): - service = AssistantV2( - authenticator=NoAuthAuthenticator(), - version='2020-09-24', - ) - service.set_service_url(base_url) - output = service.create_session(**body) - return output - - def construct_full_body(self): - body = dict() - body['assistant_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['assistant_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_session -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_session(**req_copy) + + + class TestDeleteSession(): + """ + Test Class for delete_session + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_session_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_session_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_session_all_params(self): + """ + delete_session() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + assistant_id = 'testString' + session_id = 'testString' + + # Invoke method + response = service.delete_session( + assistant_id, + session_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_session_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 = '/v2/assistants/{0}/sessions/{1}'.format(body['assistant_id'], body['session_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_session_value_error(self): + """ + test_delete_session_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions/testString') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = AssistantV2( - authenticator=NoAuthAuthenticator(), - version='2020-09-24', - ) - service.set_service_url(base_url) - output = service.delete_session(**body) - return output - - def construct_full_body(self): - body = dict() - body['assistant_id'] = "string1" - body['session_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['assistant_id'] = "string1" - body['session_id'] = "string1" - return body + url, + status=200) + + # Set up parameter values + assistant_id = 'testString' + session_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "session_id": session_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_session(**req_copy) + # endregion @@ -180,148 +190,441 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for message -#----------------------------------------------------------------------------- class TestMessage(): + """ + Test Class for message + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_message_response(self): - body = self.construct_full_body() - response = fake_response_MessageResponse_json - send_request(self, body, response) + def test_message_all_params(self): + """ + message() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a RuntimeIntent model + runtime_intent_model = {} + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + # Construct a dict representation of a CaptureGroup model + capture_group_model = {} + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + # Construct a dict representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model = {} + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + # Construct a dict representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model = {} + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + # Construct a dict representation of a RuntimeEntityRole model + runtime_entity_role_model = {} + runtime_entity_role_model['type'] = 'date_from' + + # Construct a dict representation of a RuntimeEntity model + runtime_entity_model = {} + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + # Construct a dict representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model = {} + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a dict representation of a MessageInputOptions model + message_input_options_model = {} + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + # Construct a dict representation of a MessageInput model + message_input_model = {} + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + # Construct a dict representation of a MessageContextGlobalSystem model + message_context_global_system_model = {} + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + + # Construct a dict representation of a MessageContextGlobal model + message_context_global_model = {} + message_context_global_model['system'] = message_context_global_system_model + + # Construct a dict representation of a MessageContextSkillSystem model + message_context_skill_system_model = {} + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a MessageContextSkill model + message_context_skill_model = {} + message_context_skill_model['user_defined'] = {} + message_context_skill_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a MessageContext model + message_context_model = {} + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = {} + + # Set up parameter values + assistant_id = 'testString' + session_id = 'testString' + input = message_input_model + context = message_context_model + + # Invoke method + response = service.message( + assistant_id, + session_id, + input=input, + context=context, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == message_input_model + assert req_body['context'] == message_context_model + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_message_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_MessageResponse_json - send_request(self, body, response) + def test_message_required_params(self): + """ + test_message_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + session_id = 'testString' + + # Invoke method + response = service.message( + assistant_id, + session_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_message_empty(self): - check_empty_required_params(self, fake_response_MessageResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/assistants/{0}/sessions/{1}/message'.format(body['assistant_id'], body['session_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_message_value_error(self): + """ + test_message_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = AssistantV2( - authenticator=NoAuthAuthenticator(), - version='2020-09-24', - ) - service.set_service_url(base_url) - output = service.message(**body) - return output - - def construct_full_body(self): - body = dict() - body['assistant_id'] = "string1" - body['session_id'] = "string1" - body.update({"input": MessageInput._from_dict(json.loads("""{"message_type": "fake_message_type", "text": "fake_text", "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}""")), "context": MessageContext._from_dict(json.loads("""{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}""")), }) - return body - - def construct_required_body(self): - body = dict() - body['assistant_id'] = "string1" - body['session_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for message_stateless -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + session_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "session_id": session_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.message(**req_copy) + + + class TestMessageStateless(): + """ + Test Class for message_stateless + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_message_stateless_response(self): - body = self.construct_full_body() - response = fake_response_MessageResponseStateless_json - send_request(self, body, response) + def test_message_stateless_all_params(self): + """ + message_stateless() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a RuntimeIntent model + runtime_intent_model = {} + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + # Construct a dict representation of a CaptureGroup model + capture_group_model = {} + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + # Construct a dict representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model = {} + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + # Construct a dict representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model = {} + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + # Construct a dict representation of a RuntimeEntityRole model + runtime_entity_role_model = {} + runtime_entity_role_model['type'] = 'date_from' + + # Construct a dict representation of a RuntimeEntity model + runtime_entity_model = {} + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + # Construct a dict representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model = {} + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a dict representation of a MessageInputOptionsStateless model + message_input_options_stateless_model = {} + message_input_options_stateless_model['restart'] = True + message_input_options_stateless_model['alternate_intents'] = True + message_input_options_stateless_model['spelling'] = message_input_options_spelling_model + message_input_options_stateless_model['debug'] = True + + # Construct a dict representation of a MessageInputStateless model + message_input_stateless_model = {} + message_input_stateless_model['message_type'] = 'text' + message_input_stateless_model['text'] = 'testString' + message_input_stateless_model['intents'] = [runtime_intent_model] + message_input_stateless_model['entities'] = [runtime_entity_model] + message_input_stateless_model['suggestion_id'] = 'testString' + message_input_stateless_model['options'] = message_input_options_stateless_model + + # Construct a dict representation of a MessageContextGlobalSystem model + message_context_global_system_model = {} + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + + # Construct a dict representation of a MessageContextGlobalStateless model + message_context_global_stateless_model = {} + message_context_global_stateless_model['system'] = message_context_global_system_model + message_context_global_stateless_model['session_id'] = 'testString' + + # Construct a dict representation of a MessageContextSkillSystem model + message_context_skill_system_model = {} + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = { 'foo': 'bar' } + + # Construct a dict representation of a MessageContextSkill model + message_context_skill_model = {} + message_context_skill_model['user_defined'] = {} + message_context_skill_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a MessageContextStateless model + message_context_stateless_model = {} + message_context_stateless_model['global'] = message_context_global_stateless_model + message_context_stateless_model['skills'] = {} + + # Set up parameter values + assistant_id = 'testString' + input = message_input_stateless_model + context = message_context_stateless_model + + # Invoke method + response = service.message_stateless( + assistant_id, + input=input, + context=context, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == message_input_stateless_model + assert req_body['context'] == message_context_stateless_model + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_message_stateless_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_MessageResponseStateless_json - send_request(self, body, response) + def test_message_stateless_required_params(self): + """ + test_message_stateless_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = service.message_stateless( + assistant_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_message_stateless_empty(self): - check_empty_required_params(self, fake_response_MessageResponseStateless_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/assistants/{0}/message'.format(body['assistant_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_message_stateless_value_error(self): + """ + test_message_stateless_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = AssistantV2( - authenticator=NoAuthAuthenticator(), - version='2020-09-24', - ) - service.set_service_url(base_url) - output = service.message_stateless(**body) - return output - - def construct_full_body(self): - body = dict() - body['assistant_id'] = "string1" - body.update({"input": MessageInputStateless._from_dict(json.loads("""{"message_type": "fake_message_type", "text": "fake_text", "intents": [], "entities": [], "suggestion_id": "fake_suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false}}""")), "context": MessageContextStateless._from_dict(json.loads("""{"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}""")), }) - return body - - def construct_required_body(self): - body = dict() - body['assistant_id'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.message_stateless(**req_copy) + # endregion @@ -334,78 +637,117 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_logs -#----------------------------------------------------------------------------- class TestListLogs(): + """ + Test Class for list_logs + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_logs_response(self): - body = self.construct_full_body() - response = fake_response_LogCollection_json - send_request(self, body, response) + def test_list_logs_all_params(self): + """ + list_logs() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + sort = 'testString' + filter = 'testString' + page_limit = 38 + cursor = 'testString' + + # Invoke method + response = service.list_logs( + assistant_id, + sort=sort, + filter=filter, + page_limit=page_limit, + cursor=cursor, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'sort={}'.format(sort) in query_string + assert 'filter={}'.format(filter) in query_string + assert 'page_limit={}'.format(page_limit) in query_string + assert 'cursor={}'.format(cursor) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_logs_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_LogCollection_json - send_request(self, body, response) + def test_list_logs_required_params(self): + """ + test_list_logs_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = service.list_logs( + assistant_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_logs_empty(self): - check_empty_required_params(self, fake_response_LogCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/assistants/{0}/logs'.format(body['assistant_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_list_logs_value_error(self): + """ + test_list_logs_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = AssistantV2( - authenticator=NoAuthAuthenticator(), - version='2020-09-24', - ) - service.set_service_url(base_url) - output = service.list_logs(**body) - return output - - def construct_full_body(self): - body = dict() - body['assistant_id'] = "string1" - body['sort'] = "string1" - body['filter'] = "string1" - body['page_limit'] = 12345 - body['cursor'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['assistant_id'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_logs(**req_copy) + # endregion @@ -418,74 +760,72 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for delete_user_data -#----------------------------------------------------------------------------- class TestDeleteUserData(): + """ + Test Class for delete_user_data + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_user_data_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_user_data_all_params(self): + """ + delete_user_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/user_data') + responses.add(responses.DELETE, + url, + status=202) + + # Set up parameter values + customer_id = 'testString' + + # Invoke method + response = service.delete_user_data( + customer_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'customer_id={}'.format(customer_id) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_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 = '/v2/user_data' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_user_data_value_error(self): + """ + test_delete_user_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/user_data') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=202, - content_type='') - - def call_service(self, body): - service = AssistantV2( - authenticator=NoAuthAuthenticator(), - version='2020-09-24', - ) - service.set_service_url(base_url) - output = service.delete_user_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['customer_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customer_id'] = "string1" - return body + url, + status=202) + + # Set up parameter values + customer_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customer_id": customer_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_user_data(**req_copy) + # endregion @@ -498,75 +838,111 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for bulk_classify -#----------------------------------------------------------------------------- class TestBulkClassify(): + """ + Test Class for bulk_classify + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_bulk_classify_response(self): - body = self.construct_full_body() - response = fake_response_BulkClassifyResponse_json - send_request(self, body, response) + def test_bulk_classify_all_params(self): + """ + bulk_classify() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' + + # Set up parameter values + skill_id = 'testString' + input = [bulk_classify_utterance_model] + + # Invoke method + response = service.bulk_classify( + skill_id, + input=input, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == [bulk_classify_utterance_model] + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_bulk_classify_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_BulkClassifyResponse_json - send_request(self, body, response) + def test_bulk_classify_required_params(self): + """ + test_bulk_classify_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + skill_id = 'testString' + + # Invoke method + response = service.bulk_classify( + skill_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_bulk_classify_empty(self): - check_empty_required_params(self, fake_response_BulkClassifyResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/skills/{0}/workspace/bulk_classify'.format(body['skill_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_bulk_classify_value_error(self): + """ + test_bulk_classify_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = AssistantV2( - authenticator=NoAuthAuthenticator(), - version='2020-09-24', - ) - service.set_service_url(base_url) - output = service.bulk_classify(**body) - return output - - def construct_full_body(self): - body = dict() - body['skill_id'] = "string1" - body.update({"input": [], }) - return body - - def construct_required_body(self): - body = dict() - body['skill_id'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + skill_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "skill_id": skill_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.bulk_classify(**req_copy) + # endregion @@ -575,72 +951,3313 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestBulkClassifyOutput(): + """ + Test Class for BulkClassifyOutput + """ + + def test_bulk_classify_output_serialization(self): + """ + Test serialization/deserialization for BulkClassifyOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + # Construct a json representation of a BulkClassifyOutput model + bulk_classify_output_model_json = {} + bulk_classify_output_model_json['input'] = bulk_classify_utterance_model + bulk_classify_output_model_json['entities'] = [runtime_entity_model] + bulk_classify_output_model_json['intents'] = [runtime_intent_model] + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model = BulkClassifyOutput.from_dict(bulk_classify_output_model_json) + assert bulk_classify_output_model != False + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model_dict = BulkClassifyOutput.from_dict(bulk_classify_output_model_json).__dict__ + bulk_classify_output_model2 = BulkClassifyOutput(**bulk_classify_output_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_output_model == bulk_classify_output_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() + assert bulk_classify_output_model_json2 == bulk_classify_output_model_json + +class TestBulkClassifyResponse(): + """ + Test Class for BulkClassifyResponse + """ + + def test_bulk_classify_response_serialization(self): + """ + Test serialization/deserialization for BulkClassifyResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + bulk_classify_output_model = {} # BulkClassifyOutput + bulk_classify_output_model['input'] = bulk_classify_utterance_model + bulk_classify_output_model['entities'] = [runtime_entity_model] + bulk_classify_output_model['intents'] = [runtime_intent_model] + + # Construct a json representation of a BulkClassifyResponse model + bulk_classify_response_model_json = {} + bulk_classify_response_model_json['output'] = [bulk_classify_output_model] + + # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation + bulk_classify_response_model = BulkClassifyResponse.from_dict(bulk_classify_response_model_json) + assert bulk_classify_response_model != False + + # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation + bulk_classify_response_model_dict = BulkClassifyResponse.from_dict(bulk_classify_response_model_json).__dict__ + bulk_classify_response_model2 = BulkClassifyResponse(**bulk_classify_response_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_response_model == bulk_classify_response_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() + assert bulk_classify_response_model_json2 == bulk_classify_response_model_json + +class TestBulkClassifyUtterance(): + """ + Test Class for BulkClassifyUtterance + """ + + def test_bulk_classify_utterance_serialization(self): + """ + Test serialization/deserialization for BulkClassifyUtterance + """ + + # Construct a json representation of a BulkClassifyUtterance model + bulk_classify_utterance_model_json = {} + bulk_classify_utterance_model_json['text'] = 'testString' + + # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation + bulk_classify_utterance_model = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json) + assert bulk_classify_utterance_model != False + + # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation + bulk_classify_utterance_model_dict = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json).__dict__ + bulk_classify_utterance_model2 = BulkClassifyUtterance(**bulk_classify_utterance_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_utterance_model == bulk_classify_utterance_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() + assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json + +class TestCaptureGroup(): + """ + Test Class for CaptureGroup + """ + + def test_capture_group_serialization(self): + """ + Test serialization/deserialization for CaptureGroup + """ + + # Construct a json representation of a CaptureGroup model + capture_group_model_json = {} + capture_group_model_json['group'] = 'testString' + capture_group_model_json['location'] = [38] + + # Construct a model instance of CaptureGroup by calling from_dict on the json representation + capture_group_model = CaptureGroup.from_dict(capture_group_model_json) + assert capture_group_model != False + + # Construct a model instance of CaptureGroup by calling from_dict on the json representation + capture_group_model_dict = CaptureGroup.from_dict(capture_group_model_json).__dict__ + capture_group_model2 = CaptureGroup(**capture_group_model_dict) + + # Verify the model instances are equivalent + assert capture_group_model == capture_group_model2 + + # Convert model instance back to dict and verify no loss of data + capture_group_model_json2 = capture_group_model.to_dict() + assert capture_group_model_json2 == capture_group_model_json + +class TestDialogLogMessage(): + """ + Test Class for DialogLogMessage + """ + + def test_dialog_log_message_serialization(self): + """ + Test serialization/deserialization for DialogLogMessage + """ + + # Construct a json representation of a DialogLogMessage model + dialog_log_message_model_json = {} + dialog_log_message_model_json['level'] = 'info' + dialog_log_message_model_json['message'] = 'testString' + + # Construct a model instance of DialogLogMessage by calling from_dict on the json representation + dialog_log_message_model = DialogLogMessage.from_dict(dialog_log_message_model_json) + assert dialog_log_message_model != False + + # Construct a model instance of DialogLogMessage by calling from_dict on the json representation + dialog_log_message_model_dict = DialogLogMessage.from_dict(dialog_log_message_model_json).__dict__ + dialog_log_message_model2 = DialogLogMessage(**dialog_log_message_model_dict) + + # Verify the model instances are equivalent + assert dialog_log_message_model == dialog_log_message_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_log_message_model_json2 = dialog_log_message_model.to_dict() + assert dialog_log_message_model_json2 == dialog_log_message_model_json + +class TestDialogNodeAction(): + """ + Test Class for DialogNodeAction + """ + + def test_dialog_node_action_serialization(self): + """ + Test serialization/deserialization for DialogNodeAction + """ + + # Construct a json representation of a DialogNodeAction model + dialog_node_action_model_json = {} + dialog_node_action_model_json['name'] = 'testString' + dialog_node_action_model_json['type'] = 'client' + dialog_node_action_model_json['parameters'] = {} + dialog_node_action_model_json['result_variable'] = 'testString' + dialog_node_action_model_json['credentials'] = 'testString' + + # Construct a model instance of DialogNodeAction by calling from_dict on the json representation + dialog_node_action_model = DialogNodeAction.from_dict(dialog_node_action_model_json) + assert dialog_node_action_model != False + + # Construct a model instance of DialogNodeAction by calling from_dict on the json representation + dialog_node_action_model_dict = DialogNodeAction.from_dict(dialog_node_action_model_json).__dict__ + dialog_node_action_model2 = DialogNodeAction(**dialog_node_action_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_action_model == dialog_node_action_model2 - Args: - obj: The generated test function + # Convert model instance back to dict and verify no loss of data + dialog_node_action_model_json2 = dialog_node_action_model.to_dict() + assert dialog_node_action_model_json2 == dialog_node_action_model_json +class TestDialogNodeOutputConnectToAgentTransferInfo(): """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error + Test Class for DialogNodeOutputConnectToAgentTransferInfo + """ + + def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputConnectToAgentTransferInfo + """ + + # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model + dialog_node_output_connect_to_agent_transfer_info_model_json = {} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {} + + # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation + dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) + assert dialog_node_output_connect_to_agent_transfer_info_model != False + + # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation + dialog_node_output_connect_to_agent_transfer_info_model_dict = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json).__dict__ + dialog_node_output_connect_to_agent_transfer_info_model2 = DialogNodeOutputConnectToAgentTransferInfo(**dialog_node_output_connect_to_agent_transfer_info_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_connect_to_agent_transfer_info_model == dialog_node_output_connect_to_agent_transfer_info_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() + assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json + +class TestDialogNodeOutputOptionsElement(): + """ + Test Class for DialogNodeOutputOptionsElement + """ + + def test_dialog_node_output_options_element_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputOptionsElement + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' - Args: - obj: The generated test function + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + + # Construct a json representation of a DialogNodeOutputOptionsElement model + dialog_node_output_options_element_model_json = {} + dialog_node_output_options_element_model_json['label'] = 'testString' + dialog_node_output_options_element_model_json['value'] = dialog_node_output_options_element_value_model + + # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation + dialog_node_output_options_element_model = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json) + assert dialog_node_output_options_element_model != False + + # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation + dialog_node_output_options_element_model_dict = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json).__dict__ + dialog_node_output_options_element_model2 = DialogNodeOutputOptionsElement(**dialog_node_output_options_element_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_options_element_model == dialog_node_output_options_element_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() + assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json + +class TestDialogNodeOutputOptionsElementValue(): + """ + Test Class for DialogNodeOutputOptionsElementValue """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request + def test_dialog_node_output_options_element_value_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputOptionsElementValue + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' - Args: - obj: The generated test function + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + # Construct a json representation of a DialogNodeOutputOptionsElementValue model + dialog_node_output_options_element_value_model_json = {} + dialog_node_output_options_element_value_model_json['input'] = message_input_model + + # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation + dialog_node_output_options_element_value_model = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json) + assert dialog_node_output_options_element_value_model != False + + # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation + dialog_node_output_options_element_value_model_dict = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json).__dict__ + dialog_node_output_options_element_value_model2 = DialogNodeOutputOptionsElementValue(**dialog_node_output_options_element_value_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_options_element_value_model == dialog_node_output_options_element_value_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() + assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json + +class TestDialogNodesVisited(): """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) + Test Class for DialogNodesVisited + """ + + def test_dialog_nodes_visited_serialization(self): + """ + Test serialization/deserialization for DialogNodesVisited + """ + + # Construct a json representation of a DialogNodesVisited model + dialog_nodes_visited_model_json = {} + dialog_nodes_visited_model_json['dialog_node'] = 'testString' + dialog_nodes_visited_model_json['title'] = 'testString' + dialog_nodes_visited_model_json['conditions'] = 'testString' + + # Construct a model instance of DialogNodesVisited by calling from_dict on the json representation + dialog_nodes_visited_model = DialogNodesVisited.from_dict(dialog_nodes_visited_model_json) + assert dialog_nodes_visited_model != False -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response + # Construct a model instance of DialogNodesVisited by calling from_dict on the json representation + dialog_nodes_visited_model_dict = DialogNodesVisited.from_dict(dialog_nodes_visited_model_json).__dict__ + dialog_nodes_visited_model2 = DialogNodesVisited(**dialog_nodes_visited_model_dict) - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string + # Verify the model instances are equivalent + assert dialog_nodes_visited_model == dialog_nodes_visited_model2 + # Convert model instance back to dict and verify no loss of data + dialog_nodes_visited_model_json2 = dialog_nodes_visited_model.to_dict() + assert dialog_nodes_visited_model_json2 == dialog_nodes_visited_model_json + +class TestDialogSuggestion(): + """ + Test Class for DialogSuggestion """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response -#################### -## Mock Responses ## -#################### + def test_dialog_suggestion_serialization(self): + """ + Test serialization/deserialization for DialogSuggestion + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 -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"}, "spelling": {"text": "fake_text", "original_text": "fake_original_text", "suggested_text": "fake_suggested_text"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}}""" -fake_response_MessageResponseStateless_json = """{"output": {"generic": [], "intents": [], "entities": [], "actions": [], "debug": {"nodes_visited": [], "log_messages": [], "branch_exited": false, "branch_exited_reason": "fake_branch_exited_reason"}, "spelling": {"text": "fake_text", "original_text": "fake_original_text", "suggested_text": "fake_suggested_text"}}, "context": {"global": {"system": {"timezone": "fake_timezone", "user_id": "fake_user_id", "turn_count": 10, "locale": "fake_locale", "reference_time": "fake_reference_time"}, "session_id": "fake_session_id"}, "skills": {}}}""" -fake_response_LogCollection_json = """{"logs": [], "pagination": {"next_url": "fake_next_url", "matched": 7, "next_cursor": "fake_next_cursor"}}""" -fake_response_BulkClassifyResponse_json = """{"output": []}""" + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model['input'] = message_input_model + + # Construct a json representation of a DialogSuggestion model + dialog_suggestion_model_json = {} + dialog_suggestion_model_json['label'] = 'testString' + dialog_suggestion_model_json['value'] = dialog_suggestion_value_model + dialog_suggestion_model_json['output'] = {} + + # Construct a model instance of DialogSuggestion by calling from_dict on the json representation + dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) + assert dialog_suggestion_model != False + + # Construct a model instance of DialogSuggestion by calling from_dict on the json representation + dialog_suggestion_model_dict = DialogSuggestion.from_dict(dialog_suggestion_model_json).__dict__ + dialog_suggestion_model2 = DialogSuggestion(**dialog_suggestion_model_dict) + + # Verify the model instances are equivalent + assert dialog_suggestion_model == dialog_suggestion_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() + assert dialog_suggestion_model_json2 == dialog_suggestion_model_json + +class TestDialogSuggestionValue(): + """ + Test Class for DialogSuggestionValue + """ + + def test_dialog_suggestion_value_serialization(self): + """ + Test serialization/deserialization for DialogSuggestionValue + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + # Construct a json representation of a DialogSuggestionValue model + dialog_suggestion_value_model_json = {} + dialog_suggestion_value_model_json['input'] = message_input_model + + # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation + dialog_suggestion_value_model = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json) + assert dialog_suggestion_value_model != False + + # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation + dialog_suggestion_value_model_dict = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json).__dict__ + dialog_suggestion_value_model2 = DialogSuggestionValue(**dialog_suggestion_value_model_dict) + + # Verify the model instances are equivalent + assert dialog_suggestion_value_model == dialog_suggestion_value_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() + assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json + +class TestLog(): + """ + Test Class for Log + """ + + def test_log_serialization(self): + """ + Test serialization/deserialization for Log + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = { 'foo': 'bar' } + + message_context_skill_model = {} # MessageContextSkill + message_context_skill_model['user_defined'] = {} + message_context_skill_model['system'] = message_context_skill_system_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = {} + + message_request_model = {} # MessageRequest + message_request_model['input'] = message_input_model + message_request_model['context'] = message_context_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption + runtime_response_generic_model['response_type'] = 'option' + runtime_response_generic_model['title'] = 'testString' + runtime_response_generic_model['description'] = 'testString' + runtime_response_generic_model['preference'] = 'dropdown' + runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_nodes_visited_model = {} # DialogNodesVisited + dialog_nodes_visited_model['dialog_node'] = 'testString' + dialog_nodes_visited_model['title'] = 'testString' + dialog_nodes_visited_model['conditions'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {} + message_output_model['spelling'] = message_output_spelling_model + + message_response_model = {} # MessageResponse + message_response_model['output'] = message_output_model + message_response_model['context'] = message_context_model + + # Construct a json representation of a Log model + log_model_json = {} + log_model_json['log_id'] = 'testString' + log_model_json['request'] = message_request_model + log_model_json['response'] = message_response_model + log_model_json['assistant_id'] = 'testString' + log_model_json['session_id'] = 'testString' + log_model_json['skill_id'] = 'testString' + log_model_json['snapshot'] = 'testString' + log_model_json['request_timestamp'] = 'testString' + log_model_json['response_timestamp'] = 'testString' + log_model_json['language'] = 'testString' + log_model_json['customer_id'] = 'testString' + + # Construct a model instance of Log by calling from_dict on the json representation + log_model = Log.from_dict(log_model_json) + assert log_model != False + + # Construct a model instance of Log by calling from_dict on the json representation + log_model_dict = Log.from_dict(log_model_json).__dict__ + log_model2 = Log(**log_model_dict) + + # Verify the model instances are equivalent + assert log_model == log_model2 + + # Convert model instance back to dict and verify no loss of data + log_model_json2 = log_model.to_dict() + assert log_model_json2 == log_model_json + +class TestLogCollection(): + """ + Test Class for LogCollection + """ + + def test_log_collection_serialization(self): + """ + Test serialization/deserialization for LogCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = { 'foo': 'bar' } + + message_context_skill_model = {} # MessageContextSkill + message_context_skill_model['user_defined'] = {} + message_context_skill_model['system'] = message_context_skill_system_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = {} + + message_request_model = {} # MessageRequest + message_request_model['input'] = message_input_model + message_request_model['context'] = message_context_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption + runtime_response_generic_model['response_type'] = 'option' + runtime_response_generic_model['title'] = 'testString' + runtime_response_generic_model['description'] = 'testString' + runtime_response_generic_model['preference'] = 'dropdown' + runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_nodes_visited_model = {} # DialogNodesVisited + dialog_nodes_visited_model['dialog_node'] = 'testString' + dialog_nodes_visited_model['title'] = 'testString' + dialog_nodes_visited_model['conditions'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {} + message_output_model['spelling'] = message_output_spelling_model + + message_response_model = {} # MessageResponse + message_response_model['output'] = message_output_model + message_response_model['context'] = message_context_model + + log_model = {} # Log + log_model['log_id'] = 'testString' + log_model['request'] = message_request_model + log_model['response'] = message_response_model + log_model['assistant_id'] = 'testString' + log_model['session_id'] = 'testString' + log_model['skill_id'] = 'testString' + log_model['snapshot'] = 'testString' + log_model['request_timestamp'] = 'testString' + log_model['response_timestamp'] = 'testString' + log_model['language'] = 'testString' + log_model['customer_id'] = 'testString' + + log_pagination_model = {} # LogPagination + log_pagination_model['next_url'] = 'testString' + log_pagination_model['matched'] = 38 + log_pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a LogCollection model + log_collection_model_json = {} + log_collection_model_json['logs'] = [log_model] + log_collection_model_json['pagination'] = log_pagination_model + + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model = LogCollection.from_dict(log_collection_model_json) + assert log_collection_model != False + + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model_dict = LogCollection.from_dict(log_collection_model_json).__dict__ + log_collection_model2 = LogCollection(**log_collection_model_dict) + + # Verify the model instances are equivalent + assert log_collection_model == log_collection_model2 + + # Convert model instance back to dict and verify no loss of data + log_collection_model_json2 = log_collection_model.to_dict() + assert log_collection_model_json2 == log_collection_model_json + +class TestLogPagination(): + """ + Test Class for LogPagination + """ + + def test_log_pagination_serialization(self): + """ + Test serialization/deserialization for LogPagination + """ + + # Construct a json representation of a LogPagination model + log_pagination_model_json = {} + log_pagination_model_json['next_url'] = 'testString' + log_pagination_model_json['matched'] = 38 + log_pagination_model_json['next_cursor'] = 'testString' + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model = LogPagination.from_dict(log_pagination_model_json) + assert log_pagination_model != False + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model_dict = LogPagination.from_dict(log_pagination_model_json).__dict__ + log_pagination_model2 = LogPagination(**log_pagination_model_dict) + + # Verify the model instances are equivalent + assert log_pagination_model == log_pagination_model2 + + # Convert model instance back to dict and verify no loss of data + log_pagination_model_json2 = log_pagination_model.to_dict() + assert log_pagination_model_json2 == log_pagination_model_json + +class TestMessageContext(): + """ + Test Class for MessageContext + """ + + def test_message_context_serialization(self): + """ + Test serialization/deserialization for MessageContext + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = { 'foo': 'bar' } + + message_context_skill_model = {} # MessageContextSkill + message_context_skill_model['user_defined'] = {} + message_context_skill_model['system'] = message_context_skill_system_model + + # Construct a json representation of a MessageContext model + message_context_model_json = {} + message_context_model_json['global'] = message_context_global_model + message_context_model_json['skills'] = {} + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model = MessageContext.from_dict(message_context_model_json) + assert message_context_model != False + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ + message_context_model2 = MessageContext(**message_context_model_dict) + + # Verify the model instances are equivalent + assert message_context_model == message_context_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_model_json2 = message_context_model.to_dict() + assert message_context_model_json2 == message_context_model_json + +class TestMessageContextGlobal(): + """ + Test Class for MessageContextGlobal + """ + + def test_message_context_global_serialization(self): + """ + Test serialization/deserialization for MessageContextGlobal + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + + # Construct a json representation of a MessageContextGlobal model + message_context_global_model_json = {} + message_context_global_model_json['system'] = message_context_global_system_model + message_context_global_model_json['session_id'] = 'testString' + + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) + assert message_context_global_model != False + + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ + message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) + + # Verify the model instances are equivalent + assert message_context_global_model == message_context_global_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_global_model_json2 = message_context_global_model.to_dict() + assert message_context_global_model_json2 == message_context_global_model_json + +class TestMessageContextGlobalStateless(): + """ + Test Class for MessageContextGlobalStateless + """ + + def test_message_context_global_stateless_serialization(self): + """ + Test serialization/deserialization for MessageContextGlobalStateless + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + + # Construct a json representation of a MessageContextGlobalStateless model + message_context_global_stateless_model_json = {} + message_context_global_stateless_model_json['system'] = message_context_global_system_model + message_context_global_stateless_model_json['session_id'] = 'testString' + + # Construct a model instance of MessageContextGlobalStateless by calling from_dict on the json representation + message_context_global_stateless_model = MessageContextGlobalStateless.from_dict(message_context_global_stateless_model_json) + assert message_context_global_stateless_model != False + + # Construct a model instance of MessageContextGlobalStateless by calling from_dict on the json representation + message_context_global_stateless_model_dict = MessageContextGlobalStateless.from_dict(message_context_global_stateless_model_json).__dict__ + message_context_global_stateless_model2 = MessageContextGlobalStateless(**message_context_global_stateless_model_dict) + + # Verify the model instances are equivalent + assert message_context_global_stateless_model == message_context_global_stateless_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_global_stateless_model_json2 = message_context_global_stateless_model.to_dict() + assert message_context_global_stateless_model_json2 == message_context_global_stateless_model_json + +class TestMessageContextGlobalSystem(): + """ + Test Class for MessageContextGlobalSystem + """ + + def test_message_context_global_system_serialization(self): + """ + Test serialization/deserialization for MessageContextGlobalSystem + """ + + # Construct a json representation of a MessageContextGlobalSystem model + message_context_global_system_model_json = {} + message_context_global_system_model_json['timezone'] = 'testString' + message_context_global_system_model_json['user_id'] = 'testString' + message_context_global_system_model_json['turn_count'] = 38 + message_context_global_system_model_json['locale'] = 'en-us' + message_context_global_system_model_json['reference_time'] = 'testString' + + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) + assert message_context_global_system_model != False + + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ + message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) + + # Verify the model instances are equivalent + assert message_context_global_system_model == message_context_global_system_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_global_system_model_json2 = message_context_global_system_model.to_dict() + assert message_context_global_system_model_json2 == message_context_global_system_model_json + +class TestMessageContextSkill(): + """ + Test Class for MessageContextSkill + """ + + def test_message_context_skill_serialization(self): + """ + Test serialization/deserialization for MessageContextSkill + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = { 'foo': 'bar' } + + # Construct a json representation of a MessageContextSkill model + message_context_skill_model_json = {} + message_context_skill_model_json['user_defined'] = {} + message_context_skill_model_json['system'] = message_context_skill_system_model + + # Construct a model instance of MessageContextSkill by calling from_dict on the json representation + message_context_skill_model = MessageContextSkill.from_dict(message_context_skill_model_json) + assert message_context_skill_model != False + + # Construct a model instance of MessageContextSkill by calling from_dict on the json representation + message_context_skill_model_dict = MessageContextSkill.from_dict(message_context_skill_model_json).__dict__ + message_context_skill_model2 = MessageContextSkill(**message_context_skill_model_dict) + + # Verify the model instances are equivalent + assert message_context_skill_model == message_context_skill_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_skill_model_json2 = message_context_skill_model.to_dict() + assert message_context_skill_model_json2 == message_context_skill_model_json + +class TestMessageContextSkillSystem(): + """ + Test Class for MessageContextSkillSystem + """ + + def test_message_context_skill_system_serialization(self): + """ + Test serialization/deserialization for MessageContextSkillSystem + """ + + # Construct a json representation of a MessageContextSkillSystem model + message_context_skill_system_model_json = {} + message_context_skill_system_model_json['state'] = 'testString' + message_context_skill_system_model_json['foo'] = { 'foo': 'bar' } + + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) + assert message_context_skill_system_model != False + + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ + message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) + + # Verify the model instances are equivalent + assert message_context_skill_system_model == message_context_skill_system_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() + assert message_context_skill_system_model_json2 == message_context_skill_system_model_json + +class TestMessageContextStateless(): + """ + Test Class for MessageContextStateless + """ + + def test_message_context_stateless_serialization(self): + """ + Test serialization/deserialization for MessageContextStateless + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + + message_context_global_stateless_model = {} # MessageContextGlobalStateless + message_context_global_stateless_model['system'] = message_context_global_system_model + message_context_global_stateless_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = { 'foo': 'bar' } + + message_context_skill_model = {} # MessageContextSkill + message_context_skill_model['user_defined'] = {} + message_context_skill_model['system'] = message_context_skill_system_model + + # Construct a json representation of a MessageContextStateless model + message_context_stateless_model_json = {} + message_context_stateless_model_json['global'] = message_context_global_stateless_model + message_context_stateless_model_json['skills'] = {} + + # Construct a model instance of MessageContextStateless by calling from_dict on the json representation + message_context_stateless_model = MessageContextStateless.from_dict(message_context_stateless_model_json) + assert message_context_stateless_model != False + + # Construct a model instance of MessageContextStateless by calling from_dict on the json representation + message_context_stateless_model_dict = MessageContextStateless.from_dict(message_context_stateless_model_json).__dict__ + message_context_stateless_model2 = MessageContextStateless(**message_context_stateless_model_dict) + + # Verify the model instances are equivalent + assert message_context_stateless_model == message_context_stateless_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_stateless_model_json2 = message_context_stateless_model.to_dict() + assert message_context_stateless_model_json2 == message_context_stateless_model_json + +class TestMessageInput(): + """ + Test Class for MessageInput + """ + + def test_message_input_serialization(self): + """ + Test serialization/deserialization for MessageInput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + # Construct a json representation of a MessageInput model + message_input_model_json = {} + message_input_model_json['message_type'] = 'text' + message_input_model_json['text'] = 'testString' + message_input_model_json['intents'] = [runtime_intent_model] + message_input_model_json['entities'] = [runtime_entity_model] + message_input_model_json['suggestion_id'] = 'testString' + message_input_model_json['options'] = message_input_options_model + + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model = MessageInput.from_dict(message_input_model_json) + assert message_input_model != False + + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ + message_input_model2 = MessageInput(**message_input_model_dict) + + # Verify the model instances are equivalent + assert message_input_model == message_input_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_model_json2 = message_input_model.to_dict() + assert message_input_model_json2 == message_input_model_json + +class TestMessageInputOptions(): + """ + Test Class for MessageInputOptions + """ + + def test_message_input_options_serialization(self): + """ + Test serialization/deserialization for MessageInputOptions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a json representation of a MessageInputOptions model + message_input_options_model_json = {} + message_input_options_model_json['restart'] = True + message_input_options_model_json['alternate_intents'] = True + message_input_options_model_json['spelling'] = message_input_options_spelling_model + message_input_options_model_json['debug'] = True + message_input_options_model_json['return_context'] = True + message_input_options_model_json['export'] = True + + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) + assert message_input_options_model != False + + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ + message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) + + # Verify the model instances are equivalent + assert message_input_options_model == message_input_options_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_options_model_json2 = message_input_options_model.to_dict() + assert message_input_options_model_json2 == message_input_options_model_json + +class TestMessageInputOptionsSpelling(): + """ + Test Class for MessageInputOptionsSpelling + """ + + def test_message_input_options_spelling_serialization(self): + """ + Test serialization/deserialization for MessageInputOptionsSpelling + """ + + # Construct a json representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model_json = {} + message_input_options_spelling_model_json['suggestions'] = True + message_input_options_spelling_model_json['auto_correct'] = True + + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) + assert message_input_options_spelling_model != False + + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ + message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) + + # Verify the model instances are equivalent + assert message_input_options_spelling_model == message_input_options_spelling_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() + assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json + +class TestMessageInputOptionsStateless(): + """ + Test Class for MessageInputOptionsStateless + """ + + def test_message_input_options_stateless_serialization(self): + """ + Test serialization/deserialization for MessageInputOptionsStateless + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a json representation of a MessageInputOptionsStateless model + message_input_options_stateless_model_json = {} + message_input_options_stateless_model_json['restart'] = True + message_input_options_stateless_model_json['alternate_intents'] = True + message_input_options_stateless_model_json['spelling'] = message_input_options_spelling_model + message_input_options_stateless_model_json['debug'] = True + + # Construct a model instance of MessageInputOptionsStateless by calling from_dict on the json representation + message_input_options_stateless_model = MessageInputOptionsStateless.from_dict(message_input_options_stateless_model_json) + assert message_input_options_stateless_model != False + + # Construct a model instance of MessageInputOptionsStateless by calling from_dict on the json representation + message_input_options_stateless_model_dict = MessageInputOptionsStateless.from_dict(message_input_options_stateless_model_json).__dict__ + message_input_options_stateless_model2 = MessageInputOptionsStateless(**message_input_options_stateless_model_dict) + + # Verify the model instances are equivalent + assert message_input_options_stateless_model == message_input_options_stateless_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_options_stateless_model_json2 = message_input_options_stateless_model.to_dict() + assert message_input_options_stateless_model_json2 == message_input_options_stateless_model_json + +class TestMessageInputStateless(): + """ + Test Class for MessageInputStateless + """ + + def test_message_input_stateless_serialization(self): + """ + Test serialization/deserialization for MessageInputStateless + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_stateless_model = {} # MessageInputOptionsStateless + message_input_options_stateless_model['restart'] = True + message_input_options_stateless_model['alternate_intents'] = True + message_input_options_stateless_model['spelling'] = message_input_options_spelling_model + message_input_options_stateless_model['debug'] = True + + # Construct a json representation of a MessageInputStateless model + message_input_stateless_model_json = {} + message_input_stateless_model_json['message_type'] = 'text' + message_input_stateless_model_json['text'] = 'testString' + message_input_stateless_model_json['intents'] = [runtime_intent_model] + message_input_stateless_model_json['entities'] = [runtime_entity_model] + message_input_stateless_model_json['suggestion_id'] = 'testString' + message_input_stateless_model_json['options'] = message_input_options_stateless_model + + # Construct a model instance of MessageInputStateless by calling from_dict on the json representation + message_input_stateless_model = MessageInputStateless.from_dict(message_input_stateless_model_json) + assert message_input_stateless_model != False + + # Construct a model instance of MessageInputStateless by calling from_dict on the json representation + message_input_stateless_model_dict = MessageInputStateless.from_dict(message_input_stateless_model_json).__dict__ + message_input_stateless_model2 = MessageInputStateless(**message_input_stateless_model_dict) + + # Verify the model instances are equivalent + assert message_input_stateless_model == message_input_stateless_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_stateless_model_json2 = message_input_stateless_model.to_dict() + assert message_input_stateless_model_json2 == message_input_stateless_model_json + +class TestMessageOutput(): + """ + Test Class for MessageOutput + """ + + def test_message_output_serialization(self): + """ + Test serialization/deserialization for MessageOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption + runtime_response_generic_model['response_type'] = 'option' + runtime_response_generic_model['title'] = 'testString' + runtime_response_generic_model['description'] = 'testString' + runtime_response_generic_model['preference'] = 'dropdown' + runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_nodes_visited_model = {} # DialogNodesVisited + dialog_nodes_visited_model['dialog_node'] = 'testString' + dialog_nodes_visited_model['title'] = 'testString' + dialog_nodes_visited_model['conditions'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + # Construct a json representation of a MessageOutput model + message_output_model_json = {} + message_output_model_json['generic'] = [runtime_response_generic_model] + message_output_model_json['intents'] = [runtime_intent_model] + message_output_model_json['entities'] = [runtime_entity_model] + message_output_model_json['actions'] = [dialog_node_action_model] + message_output_model_json['debug'] = message_output_debug_model + message_output_model_json['user_defined'] = {} + message_output_model_json['spelling'] = message_output_spelling_model + + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model = MessageOutput.from_dict(message_output_model_json) + assert message_output_model != False + + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model_dict = MessageOutput.from_dict(message_output_model_json).__dict__ + message_output_model2 = MessageOutput(**message_output_model_dict) + + # Verify the model instances are equivalent + assert message_output_model == message_output_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_model_json2 = message_output_model.to_dict() + assert message_output_model_json2 == message_output_model_json + +class TestMessageOutputDebug(): + """ + Test Class for MessageOutputDebug + """ + + def test_message_output_debug_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebug + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_nodes_visited_model = {} # DialogNodesVisited + dialog_nodes_visited_model['dialog_node'] = 'testString' + dialog_nodes_visited_model['title'] = 'testString' + dialog_nodes_visited_model['conditions'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + + # Construct a json representation of a MessageOutputDebug model + message_output_debug_model_json = {} + message_output_debug_model_json['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model_json['log_messages'] = [dialog_log_message_model] + message_output_debug_model_json['branch_exited'] = True + message_output_debug_model_json['branch_exited_reason'] = 'completed' + + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) + assert message_output_debug_model != False + + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model_dict = MessageOutputDebug.from_dict(message_output_debug_model_json).__dict__ + message_output_debug_model2 = MessageOutputDebug(**message_output_debug_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_model == message_output_debug_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_model_json2 = message_output_debug_model.to_dict() + assert message_output_debug_model_json2 == message_output_debug_model_json + +class TestMessageOutputSpelling(): + """ + Test Class for MessageOutputSpelling + """ + + def test_message_output_spelling_serialization(self): + """ + Test serialization/deserialization for MessageOutputSpelling + """ + + # Construct a json representation of a MessageOutputSpelling model + message_output_spelling_model_json = {} + message_output_spelling_model_json['text'] = 'testString' + message_output_spelling_model_json['original_text'] = 'testString' + message_output_spelling_model_json['suggested_text'] = 'testString' + + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model = MessageOutputSpelling.from_dict(message_output_spelling_model_json) + assert message_output_spelling_model != False + + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model_dict = MessageOutputSpelling.from_dict(message_output_spelling_model_json).__dict__ + message_output_spelling_model2 = MessageOutputSpelling(**message_output_spelling_model_dict) + + # Verify the model instances are equivalent + assert message_output_spelling_model == message_output_spelling_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_spelling_model_json2 = message_output_spelling_model.to_dict() + assert message_output_spelling_model_json2 == message_output_spelling_model_json + +class TestMessageRequest(): + """ + Test Class for MessageRequest + """ + + def test_message_request_serialization(self): + """ + Test serialization/deserialization for MessageRequest + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'Hello' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'my_user_id' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = { 'foo': 'bar' } + + message_context_skill_model = {} # MessageContextSkill + message_context_skill_model['user_defined'] = {} + message_context_skill_model['system'] = message_context_skill_system_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = {} + + # Construct a json representation of a MessageRequest model + message_request_model_json = {} + message_request_model_json['input'] = message_input_model + message_request_model_json['context'] = message_context_model + + # Construct a model instance of MessageRequest by calling from_dict on the json representation + message_request_model = MessageRequest.from_dict(message_request_model_json) + assert message_request_model != False + + # Construct a model instance of MessageRequest by calling from_dict on the json representation + message_request_model_dict = MessageRequest.from_dict(message_request_model_json).__dict__ + message_request_model2 = MessageRequest(**message_request_model_dict) + + # Verify the model instances are equivalent + assert message_request_model == message_request_model2 + + # Convert model instance back to dict and verify no loss of data + message_request_model_json2 = message_request_model.to_dict() + assert message_request_model_json2 == message_request_model_json + +class TestMessageResponse(): + """ + Test Class for MessageResponse + """ + + def test_message_response_serialization(self): + """ + Test serialization/deserialization for MessageResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption + runtime_response_generic_model['response_type'] = 'option' + runtime_response_generic_model['title'] = 'testString' + runtime_response_generic_model['description'] = 'testString' + runtime_response_generic_model['preference'] = 'dropdown' + runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_nodes_visited_model = {} # DialogNodesVisited + dialog_nodes_visited_model['dialog_node'] = 'testString' + dialog_nodes_visited_model['title'] = 'testString' + dialog_nodes_visited_model['conditions'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {} + message_output_model['spelling'] = message_output_spelling_model + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = { 'foo': 'bar' } + + message_context_skill_model = {} # MessageContextSkill + message_context_skill_model['user_defined'] = {} + message_context_skill_model['system'] = message_context_skill_system_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = {} + + # Construct a json representation of a MessageResponse model + message_response_model_json = {} + message_response_model_json['output'] = message_output_model + message_response_model_json['context'] = message_context_model + + # Construct a model instance of MessageResponse by calling from_dict on the json representation + message_response_model = MessageResponse.from_dict(message_response_model_json) + assert message_response_model != False + + # Construct a model instance of MessageResponse by calling from_dict on the json representation + message_response_model_dict = MessageResponse.from_dict(message_response_model_json).__dict__ + message_response_model2 = MessageResponse(**message_response_model_dict) + + # Verify the model instances are equivalent + assert message_response_model == message_response_model2 + + # Convert model instance back to dict and verify no loss of data + message_response_model_json2 = message_response_model.to_dict() + assert message_response_model_json2 == message_response_model_json + +class TestMessageResponseStateless(): + """ + Test Class for MessageResponseStateless + """ + + def test_message_response_stateless_serialization(self): + """ + Test serialization/deserialization for MessageResponseStateless + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption + runtime_response_generic_model['response_type'] = 'option' + runtime_response_generic_model['title'] = 'testString' + runtime_response_generic_model['description'] = 'testString' + runtime_response_generic_model['preference'] = 'dropdown' + runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_nodes_visited_model = {} # DialogNodesVisited + dialog_nodes_visited_model['dialog_node'] = 'testString' + dialog_nodes_visited_model['title'] = 'testString' + dialog_nodes_visited_model['conditions'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {} + message_output_model['spelling'] = message_output_spelling_model + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + + message_context_global_stateless_model = {} # MessageContextGlobalStateless + message_context_global_stateless_model['system'] = message_context_global_system_model + message_context_global_stateless_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = { 'foo': 'bar' } + + message_context_skill_model = {} # MessageContextSkill + message_context_skill_model['user_defined'] = {} + message_context_skill_model['system'] = message_context_skill_system_model + + message_context_stateless_model = {} # MessageContextStateless + message_context_stateless_model['global'] = message_context_global_stateless_model + message_context_stateless_model['skills'] = {} + + # Construct a json representation of a MessageResponseStateless model + message_response_stateless_model_json = {} + message_response_stateless_model_json['output'] = message_output_model + message_response_stateless_model_json['context'] = message_context_stateless_model + + # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation + message_response_stateless_model = MessageResponseStateless.from_dict(message_response_stateless_model_json) + assert message_response_stateless_model != False + + # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation + message_response_stateless_model_dict = MessageResponseStateless.from_dict(message_response_stateless_model_json).__dict__ + message_response_stateless_model2 = MessageResponseStateless(**message_response_stateless_model_dict) + + # Verify the model instances are equivalent + assert message_response_stateless_model == message_response_stateless_model2 + + # Convert model instance back to dict and verify no loss of data + message_response_stateless_model_json2 = message_response_stateless_model.to_dict() + assert message_response_stateless_model_json2 == message_response_stateless_model_json + +class TestRuntimeEntity(): + """ + Test Class for RuntimeEntity + """ + + def test_runtime_entity_serialization(self): + """ + Test serialization/deserialization for RuntimeEntity + """ + + # Construct dict forms of any model objects needed in order to build this model. + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + # Construct a json representation of a RuntimeEntity model + runtime_entity_model_json = {} + runtime_entity_model_json['entity'] = 'testString' + runtime_entity_model_json['location'] = [38] + runtime_entity_model_json['value'] = 'testString' + runtime_entity_model_json['confidence'] = 72.5 + runtime_entity_model_json['metadata'] = {} + runtime_entity_model_json['groups'] = [capture_group_model] + runtime_entity_model_json['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model_json['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model_json['role'] = runtime_entity_role_model + + # Construct a model instance of RuntimeEntity by calling from_dict on the json representation + runtime_entity_model = RuntimeEntity.from_dict(runtime_entity_model_json) + assert runtime_entity_model != False + + # Construct a model instance of RuntimeEntity by calling from_dict on the json representation + runtime_entity_model_dict = RuntimeEntity.from_dict(runtime_entity_model_json).__dict__ + runtime_entity_model2 = RuntimeEntity(**runtime_entity_model_dict) + + # Verify the model instances are equivalent + assert runtime_entity_model == runtime_entity_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_entity_model_json2 = runtime_entity_model.to_dict() + assert runtime_entity_model_json2 == runtime_entity_model_json + +class TestRuntimeEntityAlternative(): + """ + Test Class for RuntimeEntityAlternative + """ + + def test_runtime_entity_alternative_serialization(self): + """ + Test serialization/deserialization for RuntimeEntityAlternative + """ + + # Construct a json representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model_json = {} + runtime_entity_alternative_model_json['value'] = 'testString' + runtime_entity_alternative_model_json['confidence'] = 72.5 + + # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation + runtime_entity_alternative_model = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json) + assert runtime_entity_alternative_model != False + + # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation + runtime_entity_alternative_model_dict = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json).__dict__ + runtime_entity_alternative_model2 = RuntimeEntityAlternative(**runtime_entity_alternative_model_dict) + + # Verify the model instances are equivalent + assert runtime_entity_alternative_model == runtime_entity_alternative_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() + assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json + +class TestRuntimeEntityInterpretation(): + """ + Test Class for RuntimeEntityInterpretation + """ + + def test_runtime_entity_interpretation_serialization(self): + """ + Test serialization/deserialization for RuntimeEntityInterpretation + """ + + # Construct a json representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model_json = {} + runtime_entity_interpretation_model_json['calendar_type'] = 'testString' + runtime_entity_interpretation_model_json['datetime_link'] = 'testString' + runtime_entity_interpretation_model_json['festival'] = 'testString' + runtime_entity_interpretation_model_json['granularity'] = 'day' + runtime_entity_interpretation_model_json['range_link'] = 'testString' + runtime_entity_interpretation_model_json['range_modifier'] = 'testString' + runtime_entity_interpretation_model_json['relative_day'] = 72.5 + runtime_entity_interpretation_model_json['relative_month'] = 72.5 + runtime_entity_interpretation_model_json['relative_week'] = 72.5 + runtime_entity_interpretation_model_json['relative_weekend'] = 72.5 + runtime_entity_interpretation_model_json['relative_year'] = 72.5 + runtime_entity_interpretation_model_json['specific_day'] = 72.5 + runtime_entity_interpretation_model_json['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model_json['specific_month'] = 72.5 + runtime_entity_interpretation_model_json['specific_quarter'] = 72.5 + runtime_entity_interpretation_model_json['specific_year'] = 72.5 + runtime_entity_interpretation_model_json['numeric_value'] = 72.5 + runtime_entity_interpretation_model_json['subtype'] = 'testString' + runtime_entity_interpretation_model_json['part_of_day'] = 'testString' + runtime_entity_interpretation_model_json['relative_hour'] = 72.5 + runtime_entity_interpretation_model_json['relative_minute'] = 72.5 + runtime_entity_interpretation_model_json['relative_second'] = 72.5 + runtime_entity_interpretation_model_json['specific_hour'] = 72.5 + runtime_entity_interpretation_model_json['specific_minute'] = 72.5 + runtime_entity_interpretation_model_json['specific_second'] = 72.5 + runtime_entity_interpretation_model_json['timezone'] = 'testString' + + # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation + runtime_entity_interpretation_model = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json) + assert runtime_entity_interpretation_model != False + + # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation + runtime_entity_interpretation_model_dict = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json).__dict__ + runtime_entity_interpretation_model2 = RuntimeEntityInterpretation(**runtime_entity_interpretation_model_dict) + + # Verify the model instances are equivalent + assert runtime_entity_interpretation_model == runtime_entity_interpretation_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() + assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json + +class TestRuntimeEntityRole(): + """ + Test Class for RuntimeEntityRole + """ + + def test_runtime_entity_role_serialization(self): + """ + Test serialization/deserialization for RuntimeEntityRole + """ + + # Construct a json representation of a RuntimeEntityRole model + runtime_entity_role_model_json = {} + runtime_entity_role_model_json['type'] = 'date_from' + + # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation + runtime_entity_role_model = RuntimeEntityRole.from_dict(runtime_entity_role_model_json) + assert runtime_entity_role_model != False + + # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation + runtime_entity_role_model_dict = RuntimeEntityRole.from_dict(runtime_entity_role_model_json).__dict__ + runtime_entity_role_model2 = RuntimeEntityRole(**runtime_entity_role_model_dict) + + # Verify the model instances are equivalent + assert runtime_entity_role_model == runtime_entity_role_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() + assert runtime_entity_role_model_json2 == runtime_entity_role_model_json + +class TestRuntimeIntent(): + """ + Test Class for RuntimeIntent + """ + + def test_runtime_intent_serialization(self): + """ + Test serialization/deserialization for RuntimeIntent + """ + + # Construct a json representation of a RuntimeIntent model + runtime_intent_model_json = {} + runtime_intent_model_json['intent'] = 'testString' + runtime_intent_model_json['confidence'] = 72.5 + + # Construct a model instance of RuntimeIntent by calling from_dict on the json representation + runtime_intent_model = RuntimeIntent.from_dict(runtime_intent_model_json) + assert runtime_intent_model != False + + # Construct a model instance of RuntimeIntent by calling from_dict on the json representation + runtime_intent_model_dict = RuntimeIntent.from_dict(runtime_intent_model_json).__dict__ + runtime_intent_model2 = RuntimeIntent(**runtime_intent_model_dict) + + # Verify the model instances are equivalent + assert runtime_intent_model == runtime_intent_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_intent_model_json2 = runtime_intent_model.to_dict() + assert runtime_intent_model_json2 == runtime_intent_model_json + +class TestSearchResult(): + """ + Test Class for SearchResult + """ + + def test_search_result_serialization(self): + """ + Test serialization/deserialization for SearchResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_result_metadata_model = {} # SearchResultMetadata + search_result_metadata_model['confidence'] = 72.5 + search_result_metadata_model['score'] = 72.5 + + search_result_highlight_model = {} # SearchResultHighlight + search_result_highlight_model['body'] = ['testString'] + search_result_highlight_model['title'] = ['testString'] + search_result_highlight_model['url'] = ['testString'] + search_result_highlight_model['foo'] = ['testString'] + + # Construct a json representation of a SearchResult model + search_result_model_json = {} + search_result_model_json['id'] = 'testString' + search_result_model_json['result_metadata'] = search_result_metadata_model + search_result_model_json['body'] = 'testString' + search_result_model_json['title'] = 'testString' + search_result_model_json['url'] = 'testString' + search_result_model_json['highlight'] = search_result_highlight_model + + # Construct a model instance of SearchResult by calling from_dict on the json representation + search_result_model = SearchResult.from_dict(search_result_model_json) + assert search_result_model != False + + # Construct a model instance of SearchResult by calling from_dict on the json representation + search_result_model_dict = SearchResult.from_dict(search_result_model_json).__dict__ + search_result_model2 = SearchResult(**search_result_model_dict) + + # Verify the model instances are equivalent + assert search_result_model == search_result_model2 + + # Convert model instance back to dict and verify no loss of data + search_result_model_json2 = search_result_model.to_dict() + assert search_result_model_json2 == search_result_model_json + +class TestSearchResultHighlight(): + """ + Test Class for SearchResultHighlight + """ + + def test_search_result_highlight_serialization(self): + """ + Test serialization/deserialization for SearchResultHighlight + """ + + # Construct a json representation of a SearchResultHighlight model + search_result_highlight_model_json = {} + search_result_highlight_model_json['body'] = ['testString'] + search_result_highlight_model_json['title'] = ['testString'] + search_result_highlight_model_json['url'] = ['testString'] + search_result_highlight_model_json['foo'] = ['testString'] + + # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation + search_result_highlight_model = SearchResultHighlight.from_dict(search_result_highlight_model_json) + assert search_result_highlight_model != False + + # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation + search_result_highlight_model_dict = SearchResultHighlight.from_dict(search_result_highlight_model_json).__dict__ + search_result_highlight_model2 = SearchResultHighlight(**search_result_highlight_model_dict) + + # Verify the model instances are equivalent + assert search_result_highlight_model == search_result_highlight_model2 + + # Convert model instance back to dict and verify no loss of data + search_result_highlight_model_json2 = search_result_highlight_model.to_dict() + assert search_result_highlight_model_json2 == search_result_highlight_model_json + +class TestSearchResultMetadata(): + """ + Test Class for SearchResultMetadata + """ + + def test_search_result_metadata_serialization(self): + """ + Test serialization/deserialization for SearchResultMetadata + """ + + # Construct a json representation of a SearchResultMetadata model + search_result_metadata_model_json = {} + search_result_metadata_model_json['confidence'] = 72.5 + search_result_metadata_model_json['score'] = 72.5 + + # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation + search_result_metadata_model = SearchResultMetadata.from_dict(search_result_metadata_model_json) + assert search_result_metadata_model != False + + # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation + search_result_metadata_model_dict = SearchResultMetadata.from_dict(search_result_metadata_model_json).__dict__ + search_result_metadata_model2 = SearchResultMetadata(**search_result_metadata_model_dict) + + # Verify the model instances are equivalent + assert search_result_metadata_model == search_result_metadata_model2 + + # Convert model instance back to dict and verify no loss of data + search_result_metadata_model_json2 = search_result_metadata_model.to_dict() + assert search_result_metadata_model_json2 == search_result_metadata_model_json + +class TestSessionResponse(): + """ + Test Class for SessionResponse + """ + + def test_session_response_serialization(self): + """ + Test serialization/deserialization for SessionResponse + """ + + # Construct a json representation of a SessionResponse model + session_response_model_json = {} + session_response_model_json['session_id'] = 'testString' + + # Construct a model instance of SessionResponse by calling from_dict on the json representation + session_response_model = SessionResponse.from_dict(session_response_model_json) + assert session_response_model != False + + # Construct a model instance of SessionResponse by calling from_dict on the json representation + session_response_model_dict = SessionResponse.from_dict(session_response_model_json).__dict__ + session_response_model2 = SessionResponse(**session_response_model_dict) + + # Verify the model instances are equivalent + assert session_response_model == session_response_model2 + + # Convert model instance back to dict and verify no loss of data + session_response_model_json2 = session_response_model.to_dict() + assert session_response_model_json2 == session_response_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent + """ + + def test_runtime_response_generic_runtime_response_type_connect_to_agent_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent model + runtime_response_generic_runtime_response_type_connect_to_agent_model_json = {} + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['response_type'] = 'connect_to_agent' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['message_to_human_agent'] = 'testString' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_available'] = 'testString' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_unavailable'] = 'testString' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['transfer_info'] = dialog_node_output_connect_to_agent_transfer_info_model + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['topic'] = 'testString' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeConnectToAgent by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_connect_to_agent_model = RuntimeResponseGenericRuntimeResponseTypeConnectToAgent.from_dict(runtime_response_generic_runtime_response_type_connect_to_agent_model_json) + assert runtime_response_generic_runtime_response_type_connect_to_agent_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeConnectToAgent by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_connect_to_agent_model_dict = RuntimeResponseGenericRuntimeResponseTypeConnectToAgent.from_dict(runtime_response_generic_runtime_response_type_connect_to_agent_model_json).__dict__ + runtime_response_generic_runtime_response_type_connect_to_agent_model2 = RuntimeResponseGenericRuntimeResponseTypeConnectToAgent(**runtime_response_generic_runtime_response_type_connect_to_agent_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_connect_to_agent_model == runtime_response_generic_runtime_response_type_connect_to_agent_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() + assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeImage(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeImage + """ + + def test_runtime_response_generic_runtime_response_type_image_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeImage + """ + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeImage model + runtime_response_generic_runtime_response_type_image_model_json = {} + runtime_response_generic_runtime_response_type_image_model_json['response_type'] = 'image' + runtime_response_generic_runtime_response_type_image_model_json['source'] = 'testString' + runtime_response_generic_runtime_response_type_image_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_image_model_json['description'] = 'testString' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeImage by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_image_model = RuntimeResponseGenericRuntimeResponseTypeImage.from_dict(runtime_response_generic_runtime_response_type_image_model_json) + assert runtime_response_generic_runtime_response_type_image_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeImage by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_image_model_dict = RuntimeResponseGenericRuntimeResponseTypeImage.from_dict(runtime_response_generic_runtime_response_type_image_model_json).__dict__ + runtime_response_generic_runtime_response_type_image_model2 = RuntimeResponseGenericRuntimeResponseTypeImage(**runtime_response_generic_runtime_response_type_image_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_image_model == runtime_response_generic_runtime_response_type_image_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_image_model_json2 = runtime_response_generic_runtime_response_type_image_model.to_dict() + assert runtime_response_generic_runtime_response_type_image_model_json2 == runtime_response_generic_runtime_response_type_image_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeOption(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeOption + """ + + def test_runtime_response_generic_runtime_response_type_option_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeOption + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model['label'] = 'testString' + dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeOption model + runtime_response_generic_runtime_response_type_option_model_json = {} + runtime_response_generic_runtime_response_type_option_model_json['response_type'] = 'option' + runtime_response_generic_runtime_response_type_option_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_option_model_json['description'] = 'testString' + runtime_response_generic_runtime_response_type_option_model_json['preference'] = 'dropdown' + runtime_response_generic_runtime_response_type_option_model_json['options'] = [dialog_node_output_options_element_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeOption by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_option_model = RuntimeResponseGenericRuntimeResponseTypeOption.from_dict(runtime_response_generic_runtime_response_type_option_model_json) + assert runtime_response_generic_runtime_response_type_option_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeOption by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_option_model_dict = RuntimeResponseGenericRuntimeResponseTypeOption.from_dict(runtime_response_generic_runtime_response_type_option_model_json).__dict__ + runtime_response_generic_runtime_response_type_option_model2 = RuntimeResponseGenericRuntimeResponseTypeOption(**runtime_response_generic_runtime_response_type_option_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_option_model == runtime_response_generic_runtime_response_type_option_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_option_model_json2 = runtime_response_generic_runtime_response_type_option_model.to_dict() + assert runtime_response_generic_runtime_response_type_option_model_json2 == runtime_response_generic_runtime_response_type_option_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypePause(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypePause + """ + + def test_runtime_response_generic_runtime_response_type_pause_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypePause + """ + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypePause model + runtime_response_generic_runtime_response_type_pause_model_json = {} + runtime_response_generic_runtime_response_type_pause_model_json['response_type'] = 'pause' + runtime_response_generic_runtime_response_type_pause_model_json['time'] = 38 + runtime_response_generic_runtime_response_type_pause_model_json['typing'] = True + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypePause by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_pause_model = RuntimeResponseGenericRuntimeResponseTypePause.from_dict(runtime_response_generic_runtime_response_type_pause_model_json) + assert runtime_response_generic_runtime_response_type_pause_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypePause by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_pause_model_dict = RuntimeResponseGenericRuntimeResponseTypePause.from_dict(runtime_response_generic_runtime_response_type_pause_model_json).__dict__ + runtime_response_generic_runtime_response_type_pause_model2 = RuntimeResponseGenericRuntimeResponseTypePause(**runtime_response_generic_runtime_response_type_pause_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_pause_model == runtime_response_generic_runtime_response_type_pause_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_pause_model_json2 = runtime_response_generic_runtime_response_type_pause_model.to_dict() + assert runtime_response_generic_runtime_response_type_pause_model_json2 == runtime_response_generic_runtime_response_type_pause_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeSearch(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeSearch + """ + + def test_runtime_response_generic_runtime_response_type_search_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeSearch + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_result_metadata_model = {} # SearchResultMetadata + search_result_metadata_model['confidence'] = 72.5 + search_result_metadata_model['score'] = 72.5 + + search_result_highlight_model = {} # SearchResultHighlight + search_result_highlight_model['body'] = ['testString'] + search_result_highlight_model['title'] = ['testString'] + search_result_highlight_model['url'] = ['testString'] + search_result_highlight_model['foo'] = ['testString'] + + search_result_model = {} # SearchResult + search_result_model['id'] = 'testString' + search_result_model['result_metadata'] = search_result_metadata_model + search_result_model['body'] = 'testString' + search_result_model['title'] = 'testString' + search_result_model['url'] = 'testString' + search_result_model['highlight'] = search_result_highlight_model + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSearch model + runtime_response_generic_runtime_response_type_search_model_json = {} + runtime_response_generic_runtime_response_type_search_model_json['response_type'] = 'search' + runtime_response_generic_runtime_response_type_search_model_json['header'] = 'testString' + runtime_response_generic_runtime_response_type_search_model_json['primary_results'] = [search_result_model] + runtime_response_generic_runtime_response_type_search_model_json['additional_results'] = [search_result_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeSearch by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_search_model = RuntimeResponseGenericRuntimeResponseTypeSearch.from_dict(runtime_response_generic_runtime_response_type_search_model_json) + assert runtime_response_generic_runtime_response_type_search_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeSearch by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_search_model_dict = RuntimeResponseGenericRuntimeResponseTypeSearch.from_dict(runtime_response_generic_runtime_response_type_search_model_json).__dict__ + runtime_response_generic_runtime_response_type_search_model2 = RuntimeResponseGenericRuntimeResponseTypeSearch(**runtime_response_generic_runtime_response_type_search_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_search_model == runtime_response_generic_runtime_response_type_search_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_search_model_json2 = runtime_response_generic_runtime_response_type_search_model.to_dict() + assert runtime_response_generic_runtime_response_type_search_model_json2 == runtime_response_generic_runtime_response_type_search_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeSuggestion(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeSuggestion + """ + + def test_runtime_response_generic_runtime_response_type_suggestion_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeSuggestion + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['metadata'] = {} + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = True + message_input_options_model['alternate_intents'] = True + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = True + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['options'] = message_input_options_model + + dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model['input'] = message_input_model + + dialog_suggestion_model = {} # DialogSuggestion + dialog_suggestion_model['label'] = 'testString' + dialog_suggestion_model['value'] = dialog_suggestion_value_model + dialog_suggestion_model['output'] = {} + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSuggestion model + runtime_response_generic_runtime_response_type_suggestion_model_json = {} + runtime_response_generic_runtime_response_type_suggestion_model_json['response_type'] = 'suggestion' + runtime_response_generic_runtime_response_type_suggestion_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_suggestion_model_json['suggestions'] = [dialog_suggestion_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeSuggestion by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_suggestion_model = RuntimeResponseGenericRuntimeResponseTypeSuggestion.from_dict(runtime_response_generic_runtime_response_type_suggestion_model_json) + assert runtime_response_generic_runtime_response_type_suggestion_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeSuggestion by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_suggestion_model_dict = RuntimeResponseGenericRuntimeResponseTypeSuggestion.from_dict(runtime_response_generic_runtime_response_type_suggestion_model_json).__dict__ + runtime_response_generic_runtime_response_type_suggestion_model2 = RuntimeResponseGenericRuntimeResponseTypeSuggestion(**runtime_response_generic_runtime_response_type_suggestion_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_suggestion_model == runtime_response_generic_runtime_response_type_suggestion_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_suggestion_model_json2 = runtime_response_generic_runtime_response_type_suggestion_model.to_dict() + assert runtime_response_generic_runtime_response_type_suggestion_model_json2 == runtime_response_generic_runtime_response_type_suggestion_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeText(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeText + """ + + def test_runtime_response_generic_runtime_response_type_text_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeText + """ + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeText model + runtime_response_generic_runtime_response_type_text_model_json = {} + runtime_response_generic_runtime_response_type_text_model_json['response_type'] = 'text' + runtime_response_generic_runtime_response_type_text_model_json['text'] = 'testString' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeText by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_text_model = RuntimeResponseGenericRuntimeResponseTypeText.from_dict(runtime_response_generic_runtime_response_type_text_model_json) + assert runtime_response_generic_runtime_response_type_text_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeText by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_text_model_dict = RuntimeResponseGenericRuntimeResponseTypeText.from_dict(runtime_response_generic_runtime_response_type_text_model_json).__dict__ + runtime_response_generic_runtime_response_type_text_model2 = RuntimeResponseGenericRuntimeResponseTypeText(**runtime_response_generic_runtime_response_type_text_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_text_model == runtime_response_generic_runtime_response_type_text_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_text_model_json2 = runtime_response_generic_runtime_response_type_text_model.to_dict() + assert runtime_response_generic_runtime_response_type_text_model_json2 == runtime_response_generic_runtime_response_type_text_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 6819e6a71..bfee84b7a 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -13,93 +13,142 @@ # See the License for the specific language governing permissions and # limitations under the License. -from datetime import datetime +""" +Unit Tests for CompareComplyV1 +""" + +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect +import io import json import pytest +import re +import requests import responses import tempfile -import ibm_watson.compare_comply_v1 +import urllib from ibm_watson.compare_comply_v1 import * +version = 'testString' + +service = CompareComplyV1( + authenticator=NoAuthAuthenticator(), + version=version + ) + base_url = 'https://api.us-south.compare-comply.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: HTMLConversion ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for convert_to_html -#----------------------------------------------------------------------------- class TestConvertToHtml(): + """ + Test Class for convert_to_html + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_convert_to_html_response(self): - body = self.construct_full_body() - response = fake_response_HTMLReturn_json - send_request(self, body, response) + def test_convert_to_html_all_params(self): + """ + convert_to_html() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/html_conversion') + mock_response = '{"num_pages": "num_pages", "author": "author", "publication_date": "publication_date", "title": "title", "html": "html"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + file_content_type = 'application/pdf' + model = 'contracts' + + # Invoke method + response = service.convert_to_html( + file, + file_content_type=file_content_type, + model=model, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'model={}'.format(model) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_convert_to_html_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_HTMLReturn_json - send_request(self, body, response) + def test_convert_to_html_required_params(self): + """ + test_convert_to_html_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/html_conversion') + mock_response = '{"num_pages": "num_pages", "author": "author", "publication_date": "publication_date", "title": "title", "html": "html"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = service.convert_to_html( + file, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_convert_to_html_empty(self): - check_empty_required_params(self, fake_response_HTMLReturn_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/html_conversion' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_convert_to_html_value_error(self): + """ + test_convert_to_html_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/html_conversion') + mock_response = '{"num_pages": "num_pages", "author": "author", "publication_date": "publication_date", "title": "title", "html": "html"}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.convert_to_html(**body) - return output - - def construct_full_body(self): - body = dict() - body['file'] = tempfile.NamedTemporaryFile() - body['file_content_type'] = "string1" - body['model'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['file'] = tempfile.NamedTemporaryFile() - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "file": file, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.convert_to_html(**req_copy) + # endregion @@ -112,76 +161,110 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for classify_elements -#----------------------------------------------------------------------------- class TestClassifyElements(): + """ + Test Class for classify_elements + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_classify_elements_response(self): - body = self.construct_full_body() - response = fake_response_ClassifyReturn_json - send_request(self, body, response) + def test_classify_elements_all_params(self): + """ + classify_elements() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/element_classification') + mock_response = '{"document": {"title": "title", "html": "html", "hash": "hash", "label": "label"}, "model_id": "model_id", "model_version": "model_version", "elements": [{"location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "effective_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_amounts": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "termination_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_types": [{"confidence_level": "High", "text": "text", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "payment_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_currencies": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}], "document_structure": {"section_titles": [{"text": "text", "location": {"begin": 5, "end": 3}, "level": 5, "element_locations": [{"begin": 5, "end": 3}]}], "leading_sentences": [{"text": "text", "location": {"begin": 5, "end": 3}, "element_locations": [{"begin": 5, "end": 3}]}], "paragraphs": [{"location": {"begin": 5, "end": 3}}]}, "parties": [{"party": "party", "role": "role", "importance": "Primary", "addresses": [{"text": "text", "location": {"begin": 5, "end": 3}}], "contacts": [{"name": "name", "role": "role"}], "mentions": [{"text": "text", "location": {"begin": 5, "end": 3}}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + file_content_type = 'application/pdf' + model = 'contracts' + + # Invoke method + response = service.classify_elements( + file, + file_content_type=file_content_type, + model=model, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'model={}'.format(model) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_classify_elements_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ClassifyReturn_json - send_request(self, body, response) + def test_classify_elements_required_params(self): + """ + test_classify_elements_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/element_classification') + mock_response = '{"document": {"title": "title", "html": "html", "hash": "hash", "label": "label"}, "model_id": "model_id", "model_version": "model_version", "elements": [{"location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "effective_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_amounts": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "termination_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_types": [{"confidence_level": "High", "text": "text", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "payment_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_currencies": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}], "document_structure": {"section_titles": [{"text": "text", "location": {"begin": 5, "end": 3}, "level": 5, "element_locations": [{"begin": 5, "end": 3}]}], "leading_sentences": [{"text": "text", "location": {"begin": 5, "end": 3}, "element_locations": [{"begin": 5, "end": 3}]}], "paragraphs": [{"location": {"begin": 5, "end": 3}}]}, "parties": [{"party": "party", "role": "role", "importance": "Primary", "addresses": [{"text": "text", "location": {"begin": 5, "end": 3}}], "contacts": [{"name": "name", "role": "role"}], "mentions": [{"text": "text", "location": {"begin": 5, "end": 3}}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = service.classify_elements( + file, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_classify_elements_empty(self): - check_empty_required_params(self, fake_response_ClassifyReturn_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/element_classification' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_classify_elements_value_error(self): + """ + test_classify_elements_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/element_classification') + mock_response = '{"document": {"title": "title", "html": "html", "hash": "hash", "label": "label"}, "model_id": "model_id", "model_version": "model_version", "elements": [{"location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "effective_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_amounts": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "termination_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_types": [{"confidence_level": "High", "text": "text", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "payment_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_currencies": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}], "document_structure": {"section_titles": [{"text": "text", "location": {"begin": 5, "end": 3}, "level": 5, "element_locations": [{"begin": 5, "end": 3}]}], "leading_sentences": [{"text": "text", "location": {"begin": 5, "end": 3}, "element_locations": [{"begin": 5, "end": 3}]}], "paragraphs": [{"location": {"begin": 5, "end": 3}}]}, "parties": [{"party": "party", "role": "role", "importance": "Primary", "addresses": [{"text": "text", "location": {"begin": 5, "end": 3}}], "contacts": [{"name": "name", "role": "role"}], "mentions": [{"text": "text", "location": {"begin": 5, "end": 3}}]}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.classify_elements(**body) - return output - - def construct_full_body(self): - body = dict() - body['file'] = tempfile.NamedTemporaryFile() - body['file_content_type'] = "string1" - body['model'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['file'] = tempfile.NamedTemporaryFile() - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "file": file, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.classify_elements(**req_copy) + # endregion @@ -194,76 +277,110 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for extract_tables -#----------------------------------------------------------------------------- class TestExtractTables(): + """ + Test Class for extract_tables + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_extract_tables_response(self): - body = self.construct_full_body() - response = fake_response_TableReturn_json - send_request(self, body, response) + def test_extract_tables_all_params(self): + """ + extract_tables() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/tables') + mock_response = '{"document": {"html": "html", "title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + file_content_type = 'application/pdf' + model = 'contracts' + + # Invoke method + response = service.extract_tables( + file, + file_content_type=file_content_type, + model=model, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'model={}'.format(model) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_extract_tables_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TableReturn_json - send_request(self, body, response) + def test_extract_tables_required_params(self): + """ + test_extract_tables_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/tables') + mock_response = '{"document": {"html": "html", "title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = service.extract_tables( + file, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_extract_tables_empty(self): - check_empty_required_params(self, fake_response_TableReturn_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/tables' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_extract_tables_value_error(self): + """ + test_extract_tables_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/tables') + mock_response = '{"document": {"html": "html", "title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.extract_tables(**body) - return output - - def construct_full_body(self): - body = dict() - body['file'] = tempfile.NamedTemporaryFile() - body['file_content_type'] = "string1" - body['model'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['file'] = tempfile.NamedTemporaryFile() - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "file": file, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.extract_tables(**req_copy) + # endregion @@ -276,81 +393,124 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for compare_documents -#----------------------------------------------------------------------------- class TestCompareDocuments(): + """ + Test Class for compare_documents + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_compare_documents_response(self): - body = self.construct_full_body() - response = fake_response_CompareReturn_json - send_request(self, body, response) + def test_compare_documents_all_params(self): + """ + compare_documents() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/comparison') + mock_response = '{"model_id": "model_id", "model_version": "model_version", "documents": [{"title": "title", "html": "html", "hash": "hash", "label": "label"}], "aligned_elements": [{"element_pair": [{"document_label": "document_label", "text": "text", "location": {"begin": 5, "end": 3}, "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "identical_text": true, "provenance_ids": ["provenance_ids"], "significant_elements": true}], "unaligned_elements": [{"document_label": "document_label", "location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file_1 = io.BytesIO(b'This is a mock file.').getvalue() + file_2 = io.BytesIO(b'This is a mock file.').getvalue() + file_1_content_type = 'application/pdf' + file_2_content_type = 'application/pdf' + file_1_label = 'testString' + file_2_label = 'testString' + model = 'contracts' + + # Invoke method + response = service.compare_documents( + file_1, + file_2, + file_1_content_type=file_1_content_type, + file_2_content_type=file_2_content_type, + file_1_label=file_1_label, + file_2_label=file_2_label, + model=model, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'file_1_label={}'.format(file_1_label) in query_string + assert 'file_2_label={}'.format(file_2_label) in query_string + assert 'model={}'.format(model) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_compare_documents_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_CompareReturn_json - send_request(self, body, response) + def test_compare_documents_required_params(self): + """ + test_compare_documents_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/comparison') + mock_response = '{"model_id": "model_id", "model_version": "model_version", "documents": [{"title": "title", "html": "html", "hash": "hash", "label": "label"}], "aligned_elements": [{"element_pair": [{"document_label": "document_label", "text": "text", "location": {"begin": 5, "end": 3}, "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "identical_text": true, "provenance_ids": ["provenance_ids"], "significant_elements": true}], "unaligned_elements": [{"document_label": "document_label", "location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file_1 = io.BytesIO(b'This is a mock file.').getvalue() + file_2 = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = service.compare_documents( + file_1, + file_2, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_compare_documents_empty(self): - check_empty_required_params(self, fake_response_CompareReturn_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/comparison' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_compare_documents_value_error(self): + """ + test_compare_documents_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/comparison') + mock_response = '{"model_id": "model_id", "model_version": "model_version", "documents": [{"title": "title", "html": "html", "hash": "hash", "label": "label"}], "aligned_elements": [{"element_pair": [{"document_label": "document_label", "text": "text", "location": {"begin": 5, "end": 3}, "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "identical_text": true, "provenance_ids": ["provenance_ids"], "significant_elements": true}], "unaligned_elements": [{"document_label": "document_label", "location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.compare_documents(**body) - return output - - def construct_full_body(self): - body = dict() - body['file_1'] = tempfile.NamedTemporaryFile() - body['file_2'] = tempfile.NamedTemporaryFile() - body['file_1_content_type'] = "string1" - body['file_2_content_type'] = "string1" - body['file_1_label'] = "string1" - body['file_2_label'] = "string1" - body['model'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['file_1'] = tempfile.NamedTemporaryFile() - body['file_2'] = tempfile.NamedTemporaryFile() - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + file_1 = io.BytesIO(b'This is a mock file.').getvalue() + file_2 = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "file_1": file_1, + "file_2": file_2, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.compare_documents(**req_copy) + # endregion @@ -363,297 +523,521 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for add_feedback -#----------------------------------------------------------------------------- class TestAddFeedback(): + """ + Test Class for add_feedback + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_add_feedback_response(self): - body = self.construct_full_body() - response = fake_response_FeedbackReturn_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_feedback_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_FeedbackReturn_json - send_request(self, body, response) + def test_add_feedback_all_params(self): + """ + add_feedback() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/feedback') + mock_response = '{"feedback_id": "feedback_id", "user_id": "user_id", "comment": "comment", "created": "2019-01-01T12:00:00", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ShortDoc model + short_doc_model = {} + short_doc_model['title'] = 'testString' + short_doc_model['hash'] = 'testString' + + # Construct a dict representation of a Location model + location_model = {} + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a dict representation of a Label model + label_model = {} + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + # Construct a dict representation of a TypeLabel model + type_label_model = {} + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'added' + + # Construct a dict representation of a Category model + category_model = {} + category_model['label'] = 'Amendments' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'added' + + # Construct a dict representation of a OriginalLabelsIn model + original_labels_in_model = {} + original_labels_in_model['types'] = [type_label_model] + original_labels_in_model['categories'] = [category_model] + + # Construct a dict representation of a UpdatedLabelsIn model + updated_labels_in_model = {} + updated_labels_in_model['types'] = [type_label_model] + updated_labels_in_model['categories'] = [category_model] + + # Construct a dict representation of a FeedbackDataInput model + feedback_data_input_model = {} + feedback_data_input_model['feedback_type'] = 'testString' + feedback_data_input_model['document'] = short_doc_model + feedback_data_input_model['model_id'] = 'testString' + feedback_data_input_model['model_version'] = 'testString' + feedback_data_input_model['location'] = location_model + feedback_data_input_model['text'] = 'testString' + feedback_data_input_model['original_labels'] = original_labels_in_model + feedback_data_input_model['updated_labels'] = updated_labels_in_model + + # Set up parameter values + feedback_data = feedback_data_input_model + user_id = 'testString' + comment = 'testString' + + # Invoke method + response = service.add_feedback( + feedback_data, + user_id=user_id, + comment=comment, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['feedback_data'] == feedback_data_input_model + assert req_body['user_id'] == 'testString' + assert req_body['comment'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_feedback_empty(self): - check_empty_required_params(self, fake_response_FeedbackReturn_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/feedback' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_add_feedback_value_error(self): + """ + test_add_feedback_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/feedback') + mock_response = '{"feedback_id": "feedback_id", "user_id": "user_id", "comment": "comment", "created": "2019-01-01T12:00:00", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.add_feedback(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body.update({"feedback_data": FeedbackDataInput._from_dict(json.loads("""{"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}}""")), "user_id": "string1", "comment": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_feedback -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ShortDoc model + short_doc_model = {} + short_doc_model['title'] = 'testString' + short_doc_model['hash'] = 'testString' + + # Construct a dict representation of a Location model + location_model = {} + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a dict representation of a Label model + label_model = {} + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + # Construct a dict representation of a TypeLabel model + type_label_model = {} + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'added' + + # Construct a dict representation of a Category model + category_model = {} + category_model['label'] = 'Amendments' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'added' + + # Construct a dict representation of a OriginalLabelsIn model + original_labels_in_model = {} + original_labels_in_model['types'] = [type_label_model] + original_labels_in_model['categories'] = [category_model] + + # Construct a dict representation of a UpdatedLabelsIn model + updated_labels_in_model = {} + updated_labels_in_model['types'] = [type_label_model] + updated_labels_in_model['categories'] = [category_model] + + # Construct a dict representation of a FeedbackDataInput model + feedback_data_input_model = {} + feedback_data_input_model['feedback_type'] = 'testString' + feedback_data_input_model['document'] = short_doc_model + feedback_data_input_model['model_id'] = 'testString' + feedback_data_input_model['model_version'] = 'testString' + feedback_data_input_model['location'] = location_model + feedback_data_input_model['text'] = 'testString' + feedback_data_input_model['original_labels'] = original_labels_in_model + feedback_data_input_model['updated_labels'] = updated_labels_in_model + + # Set up parameter values + feedback_data = feedback_data_input_model + user_id = 'testString' + comment = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "feedback_data": feedback_data, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_feedback(**req_copy) + + + class TestListFeedback(): + """ + Test Class for list_feedback + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_feedback_response(self): - body = self.construct_full_body() - response = fake_response_FeedbackList_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_feedback_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_FeedbackList_json - send_request(self, body, response) + def test_list_feedback_all_params(self): + """ + list_feedback() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/feedback') + mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + feedback_type = 'testString' + document_title = 'testString' + model_id = 'testString' + model_version = 'testString' + category_removed = 'testString' + category_added = 'testString' + category_not_changed = 'testString' + type_removed = 'testString' + type_added = 'testString' + type_not_changed = 'testString' + page_limit = 100 + cursor = 'testString' + sort = 'testString' + include_total = True + + # Invoke method + response = service.list_feedback( + feedback_type=feedback_type, + document_title=document_title, + model_id=model_id, + model_version=model_version, + category_removed=category_removed, + category_added=category_added, + category_not_changed=category_not_changed, + type_removed=type_removed, + type_added=type_added, + type_not_changed=type_not_changed, + page_limit=page_limit, + cursor=cursor, + sort=sort, + include_total=include_total, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'feedback_type={}'.format(feedback_type) in query_string + assert 'document_title={}'.format(document_title) in query_string + assert 'model_id={}'.format(model_id) in query_string + assert 'model_version={}'.format(model_version) in query_string + assert 'category_removed={}'.format(category_removed) in query_string + assert 'category_added={}'.format(category_added) in query_string + assert 'category_not_changed={}'.format(category_not_changed) in query_string + assert 'type_removed={}'.format(type_removed) in query_string + assert 'type_added={}'.format(type_added) in query_string + assert 'type_not_changed={}'.format(type_not_changed) in query_string + assert 'page_limit={}'.format(page_limit) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'sort={}'.format(sort) in query_string + assert 'include_total={}'.format('true' if include_total else 'false') in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_feedback_empty(self): - check_empty_response(self) + def test_list_feedback_required_params(self): + """ + test_list_feedback_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/feedback') + mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = service.list_feedback() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/feedback' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_feedback_value_error(self): + """ + test_list_feedback_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/feedback') + mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.list_feedback(**body) - return output - - def construct_full_body(self): - body = dict() - body['feedback_type'] = "string1" - body['document_title'] = "string1" - body['model_id'] = "string1" - body['model_version'] = "string1" - body['category_removed'] = "string1" - body['category_added'] = "string1" - body['category_not_changed'] = "string1" - body['type_removed'] = "string1" - body['type_added'] = "string1" - body['type_not_changed'] = "string1" - body['page_limit'] = 12345 - body['cursor'] = "string1" - body['sort'] = "string1" - body['include_total'] = True - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_feedback -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_feedback(**req_copy) + + + class TestGetFeedback(): + """ + Test Class for get_feedback + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_feedback_response(self): - body = self.construct_full_body() - response = fake_response_GetFeedback_json - send_request(self, body, response) + def test_get_feedback_all_params(self): + """ + get_feedback() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/feedback/testString') + mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + feedback_id = 'testString' + model = 'contracts' + + # Invoke method + response = service.get_feedback( + feedback_id, + model=model, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'model={}'.format(model) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_feedback_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_GetFeedback_json - send_request(self, body, response) + def test_get_feedback_required_params(self): + """ + test_get_feedback_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/feedback/testString') + mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + feedback_id = 'testString' + + # Invoke method + response = service.get_feedback( + feedback_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_feedback_empty(self): - check_empty_required_params(self, fake_response_GetFeedback_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/feedback/{0}'.format(body['feedback_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_feedback_value_error(self): + """ + test_get_feedback_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/feedback/testString') + mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.get_feedback(**body) - return output - - def construct_full_body(self): - body = dict() - body['feedback_id'] = "string1" - body['model'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['feedback_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_feedback -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + feedback_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "feedback_id": feedback_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_feedback(**req_copy) + + + class TestDeleteFeedback(): + """ + Test Class for delete_feedback + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_feedback_response(self): - body = self.construct_full_body() - response = fake_response_FeedbackDeleted_json - send_request(self, body, response) + def test_delete_feedback_all_params(self): + """ + delete_feedback() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/feedback/testString') + mock_response = '{"status": 6, "message": "message"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + feedback_id = 'testString' + model = 'contracts' + + # Invoke method + response = service.delete_feedback( + feedback_id, + model=model, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'model={}'.format(model) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_feedback_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_FeedbackDeleted_json - send_request(self, body, response) + def test_delete_feedback_required_params(self): + """ + test_delete_feedback_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/feedback/testString') + mock_response = '{"status": 6, "message": "message"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + feedback_id = 'testString' + + # Invoke method + response = service.delete_feedback( + feedback_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_feedback_empty(self): - check_empty_required_params(self, fake_response_FeedbackDeleted_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/feedback/{0}'.format(body['feedback_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_feedback_value_error(self): + """ + test_delete_feedback_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/feedback/testString') + mock_response = '{"status": 6, "message": "message"}' responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.delete_feedback(**body) - return output - - def construct_full_body(self): - body = dict() - body['feedback_id'] = "string1" - body['model'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['feedback_id'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + feedback_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "feedback_id": feedback_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_feedback(**req_copy) + # endregion @@ -666,297 +1050,395 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_batch -#----------------------------------------------------------------------------- class TestCreateBatch(): + """ + Test Class for create_batch + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_batch_response(self): - body = self.construct_full_body() - response = fake_response_BatchStatus_json - send_request(self, body, response) + def test_create_batch_all_params(self): + """ + create_batch() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/batches') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + function = 'html_conversion' + input_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() + input_bucket_location = 'testString' + input_bucket_name = 'testString' + output_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() + output_bucket_location = 'testString' + output_bucket_name = 'testString' + model = 'contracts' + + # Invoke method + response = service.create_batch( + function, + input_credentials_file, + input_bucket_location, + input_bucket_name, + output_credentials_file, + output_bucket_location, + output_bucket_name, + model=model, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'function={}'.format(function) in query_string + assert 'model={}'.format(model) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_batch_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_BatchStatus_json - send_request(self, body, response) + def test_create_batch_required_params(self): + """ + test_create_batch_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/batches') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + function = 'html_conversion' + input_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() + input_bucket_location = 'testString' + input_bucket_name = 'testString' + output_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() + output_bucket_location = 'testString' + output_bucket_name = 'testString' + + # Invoke method + response = service.create_batch( + function, + input_credentials_file, + input_bucket_location, + input_bucket_name, + output_credentials_file, + output_bucket_location, + output_bucket_name, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'function={}'.format(function) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_batch_empty(self): - check_empty_required_params(self, fake_response_BatchStatus_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/batches' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_create_batch_value_error(self): + """ + test_create_batch_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/batches') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.create_batch(**body) - return output - - def construct_full_body(self): - body = dict() - body['function'] = "string1" - body['input_credentials_file'] = tempfile.NamedTemporaryFile() - body['input_bucket_location'] = "string1" - body['input_bucket_name'] = "string1" - body['output_credentials_file'] = tempfile.NamedTemporaryFile() - body['output_bucket_location'] = "string1" - body['output_bucket_name'] = "string1" - body['model'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['function'] = "string1" - body['input_credentials_file'] = tempfile.NamedTemporaryFile() - body['input_bucket_location'] = "string1" - body['input_bucket_name'] = "string1" - body['output_credentials_file'] = tempfile.NamedTemporaryFile() - body['output_bucket_location'] = "string1" - body['output_bucket_name'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_batches -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + function = 'html_conversion' + input_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() + input_bucket_location = 'testString' + input_bucket_name = 'testString' + output_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() + output_bucket_location = 'testString' + output_bucket_name = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "function": function, + "input_credentials_file": input_credentials_file, + "input_bucket_location": input_bucket_location, + "input_bucket_name": input_bucket_name, + "output_credentials_file": output_credentials_file, + "output_bucket_location": output_bucket_location, + "output_bucket_name": output_bucket_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_batch(**req_copy) + + + class TestListBatches(): + """ + Test Class for list_batches + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_batches_response(self): - body = self.construct_full_body() - response = fake_response_Batches_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_batches_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Batches_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_batches_all_params(self): + """ + list_batches() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/batches') + mock_response = '{"batches": [{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_batches_empty(self): - check_empty_response(self) + # Invoke method + response = service.list_batches() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/batches' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_batches_value_error(self): + """ + test_list_batches_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/batches') + mock_response = '{"batches": [{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.list_batches(**body) - return output - - def construct_full_body(self): - body = dict() - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_batch -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_batches(**req_copy) + + + class TestGetBatch(): + """ + Test Class for get_batch + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_batch_response(self): - body = self.construct_full_body() - response = fake_response_BatchStatus_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_batch_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_BatchStatus_json - send_request(self, body, response) + def test_get_batch_all_params(self): + """ + get_batch() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/batches/testString') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + batch_id = 'testString' + + # Invoke method + response = service.get_batch( + batch_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_batch_empty(self): - check_empty_required_params(self, fake_response_BatchStatus_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/batches/{0}'.format(body['batch_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_batch_value_error(self): + """ + test_get_batch_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/batches/testString') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.get_batch(**body) - return output - - def construct_full_body(self): - body = dict() - body['batch_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['batch_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_batch -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + batch_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "batch_id": batch_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_batch(**req_copy) + + + class TestUpdateBatch(): + """ + Test Class for update_batch + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_batch_response(self): - body = self.construct_full_body() - response = fake_response_BatchStatus_json - send_request(self, body, response) + def test_update_batch_all_params(self): + """ + update_batch() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/batches/testString') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + batch_id = 'testString' + action = 'rescan' + model = 'contracts' + + # Invoke method + response = service.update_batch( + batch_id, + action, + model=model, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'action={}'.format(action) in query_string + assert 'model={}'.format(model) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_batch_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_BatchStatus_json - send_request(self, body, response) + def test_update_batch_required_params(self): + """ + test_update_batch_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/batches/testString') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + batch_id = 'testString' + action = 'rescan' + + # Invoke method + response = service.update_batch( + batch_id, + action, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'action={}'.format(action) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_batch_empty(self): - check_empty_required_params(self, fake_response_BatchStatus_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/batches/{0}'.format(body['batch_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_update_batch_value_error(self): + """ + test_update_batch_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/batches/testString') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version='2018-10-15', - ) - service.set_service_url(base_url) - output = service.update_batch(**body) - return output - - def construct_full_body(self): - body = dict() - body['batch_id'] = "string1" - body['action'] = "string1" - body['model'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['batch_id'] = "string1" - body['action'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + batch_id = 'testString' + action = 'rescan' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "batch_id": batch_id, + "action": action, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_batch(**req_copy) + # endregion @@ -965,79 +1447,3031 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestAddress(): + """ + Test Class for Address + """ + + def test_address_serialization(self): + """ + Test serialization/deserialization for Address + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a Address model + address_model_json = {} + address_model_json['text'] = 'testString' + address_model_json['location'] = location_model + + # Construct a model instance of Address by calling from_dict on the json representation + address_model = Address.from_dict(address_model_json) + assert address_model != False + + # Construct a model instance of Address by calling from_dict on the json representation + address_model_dict = Address.from_dict(address_model_json).__dict__ + address_model2 = Address(**address_model_dict) + + # Verify the model instances are equivalent + assert address_model == address_model2 + + # Convert model instance back to dict and verify no loss of data + address_model_json2 = address_model.to_dict() + assert address_model_json2 == address_model_json + +class TestAlignedElement(): + """ + Test Class for AlignedElement + """ + + def test_aligned_element_serialization(self): + """ + Test serialization/deserialization for AlignedElement + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + type_label_comparison_model = {} # TypeLabelComparison + type_label_comparison_model['label'] = label_model + + category_comparison_model = {} # CategoryComparison + category_comparison_model['label'] = 'Amendments' + + attribute_model = {} # Attribute + attribute_model['type'] = 'Currency' + attribute_model['text'] = 'testString' + attribute_model['location'] = location_model + + element_pair_model = {} # ElementPair + element_pair_model['document_label'] = 'testString' + element_pair_model['text'] = 'testString' + element_pair_model['location'] = location_model + element_pair_model['types'] = [type_label_comparison_model] + element_pair_model['categories'] = [category_comparison_model] + element_pair_model['attributes'] = [attribute_model] + + # Construct a json representation of a AlignedElement model + aligned_element_model_json = {} + aligned_element_model_json['element_pair'] = [element_pair_model] + aligned_element_model_json['identical_text'] = True + aligned_element_model_json['provenance_ids'] = ['testString'] + aligned_element_model_json['significant_elements'] = True + + # Construct a model instance of AlignedElement by calling from_dict on the json representation + aligned_element_model = AlignedElement.from_dict(aligned_element_model_json) + assert aligned_element_model != False + + # Construct a model instance of AlignedElement by calling from_dict on the json representation + aligned_element_model_dict = AlignedElement.from_dict(aligned_element_model_json).__dict__ + aligned_element_model2 = AlignedElement(**aligned_element_model_dict) + + # Verify the model instances are equivalent + assert aligned_element_model == aligned_element_model2 + + # Convert model instance back to dict and verify no loss of data + aligned_element_model_json2 = aligned_element_model.to_dict() + assert aligned_element_model_json2 == aligned_element_model_json + +class TestAttribute(): + """ + Test Class for Attribute + """ + + def test_attribute_serialization(self): + """ + Test serialization/deserialization for Attribute + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a Attribute model + attribute_model_json = {} + attribute_model_json['type'] = 'Currency' + attribute_model_json['text'] = 'testString' + attribute_model_json['location'] = location_model + + # Construct a model instance of Attribute by calling from_dict on the json representation + attribute_model = Attribute.from_dict(attribute_model_json) + assert attribute_model != False + + # Construct a model instance of Attribute by calling from_dict on the json representation + attribute_model_dict = Attribute.from_dict(attribute_model_json).__dict__ + attribute_model2 = Attribute(**attribute_model_dict) + + # Verify the model instances are equivalent + assert attribute_model == attribute_model2 + + # Convert model instance back to dict and verify no loss of data + attribute_model_json2 = attribute_model.to_dict() + assert attribute_model_json2 == attribute_model_json - Args: - obj: The generated test function +class TestBatchStatus(): + """ + Test Class for BatchStatus + """ + + def test_batch_status_serialization(self): + """ + Test serialization/deserialization for BatchStatus + """ + + # Construct dict forms of any model objects needed in order to build this model. + + doc_counts_model = {} # DocCounts + doc_counts_model['total'] = 38 + doc_counts_model['pending'] = 38 + doc_counts_model['successful'] = 38 + doc_counts_model['failed'] = 38 + + # Construct a json representation of a BatchStatus model + batch_status_model_json = {} + batch_status_model_json['function'] = 'element_classification' + batch_status_model_json['input_bucket_location'] = 'testString' + batch_status_model_json['input_bucket_name'] = 'testString' + batch_status_model_json['output_bucket_location'] = 'testString' + batch_status_model_json['output_bucket_name'] = 'testString' + batch_status_model_json['batch_id'] = 'testString' + batch_status_model_json['document_counts'] = doc_counts_model + batch_status_model_json['status'] = 'testString' + batch_status_model_json['created'] = '2020-01-28T18:40:40.123456Z' + batch_status_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of BatchStatus by calling from_dict on the json representation + batch_status_model = BatchStatus.from_dict(batch_status_model_json) + assert batch_status_model != False + + # Construct a model instance of BatchStatus by calling from_dict on the json representation + batch_status_model_dict = BatchStatus.from_dict(batch_status_model_json).__dict__ + batch_status_model2 = BatchStatus(**batch_status_model_dict) + + # Verify the model instances are equivalent + assert batch_status_model == batch_status_model2 + + # Convert model instance back to dict and verify no loss of data + batch_status_model_json2 = batch_status_model.to_dict() + assert batch_status_model_json2 == batch_status_model_json + +class TestBatches(): + """ + Test Class for Batches + """ + + def test_batches_serialization(self): + """ + Test serialization/deserialization for Batches + """ + + # Construct dict forms of any model objects needed in order to build this model. + + doc_counts_model = {} # DocCounts + doc_counts_model['total'] = 38 + doc_counts_model['pending'] = 38 + doc_counts_model['successful'] = 38 + doc_counts_model['failed'] = 38 + + batch_status_model = {} # BatchStatus + batch_status_model['function'] = 'element_classification' + batch_status_model['input_bucket_location'] = 'testString' + batch_status_model['input_bucket_name'] = 'testString' + batch_status_model['output_bucket_location'] = 'testString' + batch_status_model['output_bucket_name'] = 'testString' + batch_status_model['batch_id'] = 'testString' + batch_status_model['document_counts'] = doc_counts_model + batch_status_model['status'] = 'testString' + batch_status_model['created'] = '2020-01-28T18:40:40.123456Z' + batch_status_model['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a json representation of a Batches model + batches_model_json = {} + batches_model_json['batches'] = [batch_status_model] + + # Construct a model instance of Batches by calling from_dict on the json representation + batches_model = Batches.from_dict(batches_model_json) + assert batches_model != False + + # Construct a model instance of Batches by calling from_dict on the json representation + batches_model_dict = Batches.from_dict(batches_model_json).__dict__ + batches_model2 = Batches(**batches_model_dict) + + # Verify the model instances are equivalent + assert batches_model == batches_model2 + + # Convert model instance back to dict and verify no loss of data + batches_model_json2 = batches_model.to_dict() + assert batches_model_json2 == batches_model_json + +class TestBodyCells(): + """ + Test Class for BodyCells + """ + + def test_body_cells_serialization(self): + """ + Test serialization/deserialization for BodyCells + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + attribute_model = {} # Attribute + attribute_model['type'] = 'Currency' + attribute_model['text'] = 'testString' + attribute_model['location'] = location_model + + # Construct a json representation of a BodyCells model + body_cells_model_json = {} + body_cells_model_json['cell_id'] = 'testString' + body_cells_model_json['location'] = location_model + body_cells_model_json['text'] = 'testString' + body_cells_model_json['row_index_begin'] = 26 + body_cells_model_json['row_index_end'] = 26 + body_cells_model_json['column_index_begin'] = 26 + body_cells_model_json['column_index_end'] = 26 + body_cells_model_json['row_header_ids'] = ['testString'] + body_cells_model_json['row_header_texts'] = ['testString'] + body_cells_model_json['row_header_texts_normalized'] = ['testString'] + body_cells_model_json['column_header_ids'] = ['testString'] + body_cells_model_json['column_header_texts'] = ['testString'] + body_cells_model_json['column_header_texts_normalized'] = ['testString'] + body_cells_model_json['attributes'] = [attribute_model] + + # Construct a model instance of BodyCells by calling from_dict on the json representation + body_cells_model = BodyCells.from_dict(body_cells_model_json) + assert body_cells_model != False + + # Construct a model instance of BodyCells by calling from_dict on the json representation + body_cells_model_dict = BodyCells.from_dict(body_cells_model_json).__dict__ + body_cells_model2 = BodyCells(**body_cells_model_dict) + + # Verify the model instances are equivalent + assert body_cells_model == body_cells_model2 + + # Convert model instance back to dict and verify no loss of data + body_cells_model_json2 = body_cells_model.to_dict() + assert body_cells_model_json2 == body_cells_model_json + +class TestCategory(): + """ + Test Class for Category + """ + + def test_category_serialization(self): + """ + Test serialization/deserialization for Category + """ + + # Construct a json representation of a Category model + category_model_json = {} + category_model_json['label'] = 'Amendments' + category_model_json['provenance_ids'] = ['testString'] + category_model_json['modification'] = 'added' + + # Construct a model instance of Category by calling from_dict on the json representation + category_model = Category.from_dict(category_model_json) + assert category_model != False + + # Construct a model instance of Category by calling from_dict on the json representation + category_model_dict = Category.from_dict(category_model_json).__dict__ + category_model2 = Category(**category_model_dict) + + # Verify the model instances are equivalent + assert category_model == category_model2 + + # Convert model instance back to dict and verify no loss of data + category_model_json2 = category_model.to_dict() + assert category_model_json2 == category_model_json + +class TestCategoryComparison(): + """ + Test Class for CategoryComparison + """ + + def test_category_comparison_serialization(self): + """ + Test serialization/deserialization for CategoryComparison + """ + + # Construct a json representation of a CategoryComparison model + category_comparison_model_json = {} + category_comparison_model_json['label'] = 'Amendments' + + # Construct a model instance of CategoryComparison by calling from_dict on the json representation + category_comparison_model = CategoryComparison.from_dict(category_comparison_model_json) + assert category_comparison_model != False + + # Construct a model instance of CategoryComparison by calling from_dict on the json representation + category_comparison_model_dict = CategoryComparison.from_dict(category_comparison_model_json).__dict__ + category_comparison_model2 = CategoryComparison(**category_comparison_model_dict) + + # Verify the model instances are equivalent + assert category_comparison_model == category_comparison_model2 + + # Convert model instance back to dict and verify no loss of data + category_comparison_model_json2 = category_comparison_model.to_dict() + assert category_comparison_model_json2 == category_comparison_model_json + +class TestClassifyReturn(): + """ + Test Class for ClassifyReturn + """ + + def test_classify_return_serialization(self): + """ + Test serialization/deserialization for ClassifyReturn + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_model = {} # Document + document_model['title'] = 'IBM DC QDRO Guidelines' + document_model['html'] = '\n\n ...' + document_model['hash'] = '91edc2ff254d29f7a4922635ad47276a' + document_model['label'] = 'testString' + + location_model = {} # Location + location_model['begin'] = 6958 + location_model['end'] = 7171 + + label_model = {} # Label + label_model['nature'] = 'Obligation' + label_model['party'] = 'You' + + type_label_model = {} # TypeLabel + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'added' + + category_model = {} # Category + category_model['label'] = 'Amendments' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'added' + + attribute_model = {} # Attribute + attribute_model['type'] = 'Currency' + attribute_model['text'] = 'testString' + attribute_model['location'] = location_model + + element_model = {} # Element + element_model['location'] = location_model + element_model['text'] = 'In the following sections, you will find the Plan\'s processing guidelines for determining the qualification of an order and some discussion of plan features and issues that should be considered in drafting a QDRO.' + element_model['types'] = [type_label_model] + element_model['categories'] = [category_model] + element_model['attributes'] = [attribute_model] + + effective_dates_model = {} # EffectiveDates + effective_dates_model['confidence_level'] = 'High' + effective_dates_model['text'] = 'testString' + effective_dates_model['text_normalized'] = 'testString' + effective_dates_model['provenance_ids'] = ['testString'] + effective_dates_model['location'] = location_model + + interpretation_model = {} # Interpretation + interpretation_model['value'] = 'testString' + interpretation_model['numeric_value'] = 72.5 + interpretation_model['unit'] = 'testString' + + contract_amts_model = {} # ContractAmts + contract_amts_model['confidence_level'] = 'High' + contract_amts_model['text'] = 'testString' + contract_amts_model['text_normalized'] = 'testString' + contract_amts_model['interpretation'] = interpretation_model + contract_amts_model['provenance_ids'] = ['testString'] + contract_amts_model['location'] = location_model + + termination_dates_model = {} # TerminationDates + termination_dates_model['confidence_level'] = 'High' + termination_dates_model['text'] = 'testString' + termination_dates_model['text_normalized'] = 'testString' + termination_dates_model['provenance_ids'] = ['testString'] + termination_dates_model['location'] = location_model + + contract_types_model = {} # ContractTypes + contract_types_model['confidence_level'] = 'High' + contract_types_model['text'] = 'testString' + contract_types_model['provenance_ids'] = ['testString'] + contract_types_model['location'] = location_model + + contract_terms_model = {} # ContractTerms + contract_terms_model['confidence_level'] = 'High' + contract_terms_model['text'] = 'testString' + contract_terms_model['text_normalized'] = 'testString' + contract_terms_model['interpretation'] = interpretation_model + contract_terms_model['provenance_ids'] = ['testString'] + contract_terms_model['location'] = location_model + + payment_terms_model = {} # PaymentTerms + payment_terms_model['confidence_level'] = 'High' + payment_terms_model['text'] = 'testString' + payment_terms_model['text_normalized'] = 'testString' + payment_terms_model['interpretation'] = interpretation_model + payment_terms_model['provenance_ids'] = ['testString'] + payment_terms_model['location'] = location_model + + contract_currencies_model = {} # ContractCurrencies + contract_currencies_model['confidence_level'] = 'High' + contract_currencies_model['text'] = 'testString' + contract_currencies_model['text_normalized'] = 'testString' + contract_currencies_model['provenance_ids'] = ['testString'] + contract_currencies_model['location'] = location_model + + section_title_model = {} # SectionTitle + section_title_model['text'] = 'Buyer will pay Supplier certain amounts for the Developed Works and other Services and Deliverables as described below: ' + section_title_model['location'] = location_model + + table_title_model = {} # TableTitle + table_title_model['location'] = location_model + table_title_model['text'] = 'Roles and responsibilities' + + table_headers_model = {} # TableHeaders + table_headers_model['cell_id'] = 'testString' + table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['text'] = 'testString' + table_headers_model['row_index_begin'] = 26 + table_headers_model['row_index_end'] = 26 + table_headers_model['column_index_begin'] = 26 + table_headers_model['column_index_end'] = 26 + + row_headers_model = {} # RowHeaders + row_headers_model['cell_id'] = 'testString' + row_headers_model['location'] = location_model + row_headers_model['text'] = 'testString' + row_headers_model['text_normalized'] = 'testString' + row_headers_model['row_index_begin'] = 26 + row_headers_model['row_index_end'] = 26 + row_headers_model['column_index_begin'] = 26 + row_headers_model['column_index_end'] = 26 + + column_headers_model = {} # ColumnHeaders + column_headers_model['cell_id'] = 'colHeader-23489-23496' + column_headers_model['location'] = { 'foo': 'bar' } + column_headers_model['text'] = 'Res Ref' + column_headers_model['text_normalized'] = 'Res Ref' + column_headers_model['row_index_begin'] = 0 + column_headers_model['row_index_end'] = 0 + column_headers_model['column_index_begin'] = 0 + column_headers_model['column_index_end'] = 0 + + body_cells_model = {} # BodyCells + body_cells_model['cell_id'] = 'bodyCell-24768-24777' + body_cells_model['location'] = location_model + body_cells_model['text'] = 'RBS-RES01' + body_cells_model['row_index_begin'] = 1 + body_cells_model['row_index_end'] = 1 + body_cells_model['column_index_begin'] = 0 + body_cells_model['column_index_end'] = 0 + body_cells_model['row_header_ids'] = ['testString'] + body_cells_model['row_header_texts'] = ['testString'] + body_cells_model['row_header_texts_normalized'] = ['testString'] + body_cells_model['column_header_ids'] = ['testString'] + body_cells_model['column_header_texts'] = ['testString'] + body_cells_model['column_header_texts_normalized'] = ['testString'] + body_cells_model['attributes'] = [attribute_model] + + contexts_model = {} # Contexts + contexts_model['text'] = 'testString' + contexts_model['location'] = location_model + + key_model = {} # Key + key_model['cell_id'] = 'testString' + key_model['location'] = location_model + key_model['text'] = 'testString' + + value_model = {} # Value + value_model['cell_id'] = 'testString' + value_model['location'] = location_model + value_model['text'] = 'testString' + + key_value_pair_model = {} # KeyValuePair + key_value_pair_model['key'] = key_model + key_value_pair_model['value'] = [value_model] + + tables_model = {} # Tables + tables_model['location'] = location_model + tables_model['text'] = 'Res Ref Role Type Estimated Days Rate (per da y) Estimated Total RBS-RES01 CRM Developer 1 (Junior Technical Consultant) 55 £600 £33,000 RBS-RES02 CRM Developer 2 (Junior Technical Consultant) 77 £600 £46,200 RBS-RES03 Specialist Tester (Test Lead) 65 £550 £35,750 Totals £114,950 ' + tables_model['section_title'] = section_title_model + tables_model['title'] = table_title_model + tables_model['table_headers'] = [table_headers_model] + tables_model['row_headers'] = [row_headers_model] + tables_model['column_headers'] = [column_headers_model] + tables_model['body_cells'] = [body_cells_model] + tables_model['contexts'] = [contexts_model] + tables_model['key_value_pairs'] = [key_value_pair_model] + + element_locations_model = {} # ElementLocations + element_locations_model['begin'] = 4174 + element_locations_model['end'] = 4277 + + section_titles_model = {} # SectionTitles + section_titles_model['text'] = '1.0 Scope of Work Summary' + section_titles_model['location'] = location_model + section_titles_model['level'] = 1 + section_titles_model['element_locations'] = [element_locations_model] + + leading_sentence_model = {} # LeadingSentence + leading_sentence_model['text'] = 'testString' + leading_sentence_model['location'] = location_model + leading_sentence_model['element_locations'] = [element_locations_model] + + paragraphs_model = {} # Paragraphs + paragraphs_model['location'] = location_model + + doc_structure_model = {} # DocStructure + doc_structure_model['section_titles'] = [section_titles_model] + doc_structure_model['leading_sentences'] = [leading_sentence_model] + doc_structure_model['paragraphs'] = [paragraphs_model] + + address_model = {} # Address + address_model['text'] = 'testString' + address_model['location'] = location_model + + contact_model = {} # Contact + contact_model['name'] = 'testString' + contact_model['role'] = 'testString' + + mention_model = {} # Mention + mention_model['text'] = 'testString' + mention_model['location'] = location_model + + parties_model = {} # Parties + parties_model['party'] = 'IBM' + parties_model['role'] = 'Unknown' + parties_model['importance'] = 'Primary' + parties_model['addresses'] = [address_model] + parties_model['contacts'] = [contact_model] + parties_model['mentions'] = [mention_model] + + # Construct a json representation of a ClassifyReturn model + classify_return_model_json = {} + classify_return_model_json['document'] = document_model + classify_return_model_json['model_id'] = 'testString' + classify_return_model_json['model_version'] = 'testString' + classify_return_model_json['elements'] = [element_model] + classify_return_model_json['effective_dates'] = [effective_dates_model] + classify_return_model_json['contract_amounts'] = [contract_amts_model] + classify_return_model_json['termination_dates'] = [termination_dates_model] + classify_return_model_json['contract_types'] = [contract_types_model] + classify_return_model_json['contract_terms'] = [contract_terms_model] + classify_return_model_json['payment_terms'] = [payment_terms_model] + classify_return_model_json['contract_currencies'] = [contract_currencies_model] + classify_return_model_json['tables'] = [tables_model] + classify_return_model_json['document_structure'] = doc_structure_model + classify_return_model_json['parties'] = [parties_model] + + # Construct a model instance of ClassifyReturn by calling from_dict on the json representation + classify_return_model = ClassifyReturn.from_dict(classify_return_model_json) + assert classify_return_model != False + + # Construct a model instance of ClassifyReturn by calling from_dict on the json representation + classify_return_model_dict = ClassifyReturn.from_dict(classify_return_model_json).__dict__ + classify_return_model2 = ClassifyReturn(**classify_return_model_dict) + + # Verify the model instances are equivalent + assert classify_return_model == classify_return_model2 + + # Convert model instance back to dict and verify no loss of data + classify_return_model_json2 = classify_return_model.to_dict() + assert classify_return_model_json2 == classify_return_model_json + +class TestColumnHeaders(): + """ + Test Class for ColumnHeaders + """ + def test_column_headers_serialization(self): + """ + Test serialization/deserialization for ColumnHeaders + """ + + # Construct a json representation of a ColumnHeaders model + column_headers_model_json = {} + column_headers_model_json['cell_id'] = 'testString' + column_headers_model_json['location'] = { 'foo': 'bar' } + column_headers_model_json['text'] = 'testString' + column_headers_model_json['text_normalized'] = 'testString' + column_headers_model_json['row_index_begin'] = 26 + column_headers_model_json['row_index_end'] = 26 + column_headers_model_json['column_index_begin'] = 26 + column_headers_model_json['column_index_end'] = 26 + + # Construct a model instance of ColumnHeaders by calling from_dict on the json representation + column_headers_model = ColumnHeaders.from_dict(column_headers_model_json) + assert column_headers_model != False + + # Construct a model instance of ColumnHeaders by calling from_dict on the json representation + column_headers_model_dict = ColumnHeaders.from_dict(column_headers_model_json).__dict__ + column_headers_model2 = ColumnHeaders(**column_headers_model_dict) + + # Verify the model instances are equivalent + assert column_headers_model == column_headers_model2 + + # Convert model instance back to dict and verify no loss of data + column_headers_model_json2 = column_headers_model.to_dict() + assert column_headers_model_json2 == column_headers_model_json + +class TestCompareReturn(): """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error + Test Class for CompareReturn + """ + + def test_compare_return_serialization(self): + """ + Test serialization/deserialization for CompareReturn + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_model = {} # Document + document_model['title'] = '31235_000156459017003570_kodk-ex1013_296.pdf' + document_model['html'] = '...' + document_model['hash'] = '0d9589556c16fca21c64ce9c8b10d065' + document_model['label'] = 'file_1' + + location_model = {} # Location + location_model['begin'] = 5690 + location_model['end'] = 5865 + + label_model = {} # Label + label_model['nature'] = 'Exclusion' + label_model['party'] = 'You' + + type_label_comparison_model = {} # TypeLabelComparison + type_label_comparison_model['label'] = label_model + + category_comparison_model = {} # CategoryComparison + category_comparison_model['label'] = 'Amendments' + + attribute_model = {} # Attribute + attribute_model['type'] = 'Currency' + attribute_model['text'] = 'testString' + attribute_model['location'] = location_model + + element_pair_model = {} # ElementPair + element_pair_model['document_label'] = 'file_1' + element_pair_model['text'] = 'You will not have the rights of a Ishki shareholder with respect to the shares issued to you in payment of your RSUs until the shares are actually issued and delivered to you.' + element_pair_model['location'] = location_model + element_pair_model['types'] = [type_label_comparison_model] + element_pair_model['categories'] = [category_comparison_model] + element_pair_model['attributes'] = [attribute_model] + + aligned_element_model = {} # AlignedElement + aligned_element_model['element_pair'] = [element_pair_model] + aligned_element_model['identical_text'] = True + aligned_element_model['provenance_ids'] = ['testString'] + aligned_element_model['significant_elements'] = True + + unaligned_element_model = {} # UnalignedElement + unaligned_element_model['document_label'] = 'file_1' + unaligned_element_model['location'] = location_model + unaligned_element_model['text'] = 'The RSUs (at the time of vesting or otherwise) will be includible as compensation for pension.' + unaligned_element_model['types'] = [type_label_comparison_model] + unaligned_element_model['categories'] = [category_comparison_model] + unaligned_element_model['attributes'] = [attribute_model] + + # Construct a json representation of a CompareReturn model + compare_return_model_json = {} + compare_return_model_json['model_id'] = 'testString' + compare_return_model_json['model_version'] = 'testString' + compare_return_model_json['documents'] = [document_model] + compare_return_model_json['aligned_elements'] = [aligned_element_model] + compare_return_model_json['unaligned_elements'] = [unaligned_element_model] + + # Construct a model instance of CompareReturn by calling from_dict on the json representation + compare_return_model = CompareReturn.from_dict(compare_return_model_json) + assert compare_return_model != False + + # Construct a model instance of CompareReturn by calling from_dict on the json representation + compare_return_model_dict = CompareReturn.from_dict(compare_return_model_json).__dict__ + compare_return_model2 = CompareReturn(**compare_return_model_dict) + + # Verify the model instances are equivalent + assert compare_return_model == compare_return_model2 + + # Convert model instance back to dict and verify no loss of data + compare_return_model_json2 = compare_return_model.to_dict() + assert compare_return_model_json2 == compare_return_model_json + +class TestContact(): + """ + Test Class for Contact + """ + + def test_contact_serialization(self): + """ + Test serialization/deserialization for Contact + """ + + # Construct a json representation of a Contact model + contact_model_json = {} + contact_model_json['name'] = 'testString' + contact_model_json['role'] = 'testString' + + # Construct a model instance of Contact by calling from_dict on the json representation + contact_model = Contact.from_dict(contact_model_json) + assert contact_model != False + + # Construct a model instance of Contact by calling from_dict on the json representation + contact_model_dict = Contact.from_dict(contact_model_json).__dict__ + contact_model2 = Contact(**contact_model_dict) -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data + # Verify the model instances are equivalent + assert contact_model == contact_model2 - Args: - obj: The generated test function + # Convert model instance back to dict and verify no loss of data + contact_model_json2 = contact_model.to_dict() + assert contact_model_json2 == contact_model_json +class TestContexts(): """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error + Test Class for Contexts + """ + + def test_contexts_serialization(self): + """ + Test serialization/deserialization for Contexts + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request + # Construct a json representation of a Contexts model + contexts_model_json = {} + contexts_model_json['text'] = 'testString' + contexts_model_json['location'] = location_model - Args: - obj: The generated test function + # Construct a model instance of Contexts by calling from_dict on the json representation + contexts_model = Contexts.from_dict(contexts_model_json) + assert contexts_model != False + # Construct a model instance of Contexts by calling from_dict on the json representation + contexts_model_dict = Contexts.from_dict(contexts_model_json).__dict__ + contexts_model2 = Contexts(**contexts_model_dict) + + # Verify the model instances are equivalent + assert contexts_model == contexts_model2 + + # Convert model instance back to dict and verify no loss of data + contexts_model_json2 = contexts_model.to_dict() + assert contexts_model_json2 == contexts_model_json + +class TestContractAmts(): + """ + Test Class for ContractAmts """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response + def test_contract_amts_serialization(self): + """ + Test serialization/deserialization for ContractAmts + """ - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string + # Construct dict forms of any model objects needed in order to build this model. + interpretation_model = {} # Interpretation + interpretation_model['value'] = 'testString' + interpretation_model['numeric_value'] = 72.5 + interpretation_model['unit'] = 'testString' + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a ContractAmts model + contract_amts_model_json = {} + contract_amts_model_json['confidence_level'] = 'High' + contract_amts_model_json['text'] = 'testString' + contract_amts_model_json['text_normalized'] = 'testString' + contract_amts_model_json['interpretation'] = interpretation_model + contract_amts_model_json['provenance_ids'] = ['testString'] + contract_amts_model_json['location'] = location_model + + # Construct a model instance of ContractAmts by calling from_dict on the json representation + contract_amts_model = ContractAmts.from_dict(contract_amts_model_json) + assert contract_amts_model != False + + # Construct a model instance of ContractAmts by calling from_dict on the json representation + contract_amts_model_dict = ContractAmts.from_dict(contract_amts_model_json).__dict__ + contract_amts_model2 = ContractAmts(**contract_amts_model_dict) + + # Verify the model instances are equivalent + assert contract_amts_model == contract_amts_model2 + + # Convert model instance back to dict and verify no loss of data + contract_amts_model_json2 = contract_amts_model.to_dict() + assert contract_amts_model_json2 == contract_amts_model_json + +class TestContractCurrencies(): + """ + Test Class for ContractCurrencies """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response -#################### -## Mock Responses ## -#################### + def test_contract_currencies_serialization(self): + """ + Test serialization/deserialization for ContractCurrencies + """ -fake_response__json = None -fake_response_HTMLReturn_json = """{"num_pages": "fake_num_pages", "author": "fake_author", "publication_date": "fake_publication_date", "title": "fake_title", "html": "fake_html"}""" -fake_response_ClassifyReturn_json = """{"document": {"title": "fake_title", "html": "fake_html", "hash": "fake_hash", "label": "fake_label"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "elements": [], "effective_dates": [], "contract_amounts": [], "termination_dates": [], "contract_types": [], "contract_terms": [], "payment_terms": [], "contract_currencies": [], "tables": [], "document_structure": {"section_titles": [], "leading_sentences": [], "paragraphs": []}, "parties": []}""" -fake_response_TableReturn_json = """{"document": {"html": "fake_html", "title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "tables": []}""" -fake_response_CompareReturn_json = """{"model_id": "fake_model_id", "model_version": "fake_model_version", "documents": [], "aligned_elements": [], "unaligned_elements": []}""" -fake_response_FeedbackReturn_json = """{"feedback_id": "fake_feedback_id", "user_id": "fake_user_id", "comment": "fake_comment", "created": "2017-05-16T13:56:54.957Z", "feedback_data": {"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}, "pagination": {"refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor", "refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5}}}""" -fake_response_FeedbackList_json = """{"feedback": []}""" -fake_response_GetFeedback_json = """{"feedback_id": "fake_feedback_id", "created": "2017-05-16T13:56:54.957Z", "comment": "fake_comment", "feedback_data": {"feedback_type": "fake_feedback_type", "document": {"title": "fake_title", "hash": "fake_hash"}, "model_id": "fake_model_id", "model_version": "fake_model_version", "location": {"begin": 5, "end": 3}, "text": "fake_text", "original_labels": {"types": [], "categories": []}, "updated_labels": {"types": [], "categories": []}, "pagination": {"refresh_cursor": "fake_refresh_cursor", "next_cursor": "fake_next_cursor", "refresh_url": "fake_refresh_url", "next_url": "fake_next_url", "total": 5}}}""" -fake_response_FeedbackDeleted_json = """{"status": 6, "message": "fake_message"}""" -fake_response_BatchStatus_json = """{"function": "fake_function", "input_bucket_location": "fake_input_bucket_location", "input_bucket_name": "fake_input_bucket_name", "output_bucket_location": "fake_output_bucket_location", "output_bucket_name": "fake_output_bucket_name", "batch_id": "fake_batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_Batches_json = """{"batches": []}""" -fake_response_BatchStatus_json = """{"function": "fake_function", "input_bucket_location": "fake_input_bucket_location", "input_bucket_name": "fake_input_bucket_name", "output_bucket_location": "fake_output_bucket_location", "output_bucket_name": "fake_output_bucket_name", "batch_id": "fake_batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_BatchStatus_json = """{"function": "fake_function", "input_bucket_location": "fake_input_bucket_location", "input_bucket_name": "fake_input_bucket_name", "output_bucket_location": "fake_output_bucket_location", "output_bucket_name": "fake_output_bucket_name", "batch_id": "fake_batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "fake_status", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a ContractCurrencies model + contract_currencies_model_json = {} + contract_currencies_model_json['confidence_level'] = 'High' + contract_currencies_model_json['text'] = 'testString' + contract_currencies_model_json['text_normalized'] = 'testString' + contract_currencies_model_json['provenance_ids'] = ['testString'] + contract_currencies_model_json['location'] = location_model + + # Construct a model instance of ContractCurrencies by calling from_dict on the json representation + contract_currencies_model = ContractCurrencies.from_dict(contract_currencies_model_json) + assert contract_currencies_model != False + + # Construct a model instance of ContractCurrencies by calling from_dict on the json representation + contract_currencies_model_dict = ContractCurrencies.from_dict(contract_currencies_model_json).__dict__ + contract_currencies_model2 = ContractCurrencies(**contract_currencies_model_dict) + + # Verify the model instances are equivalent + assert contract_currencies_model == contract_currencies_model2 + + # Convert model instance back to dict and verify no loss of data + contract_currencies_model_json2 = contract_currencies_model.to_dict() + assert contract_currencies_model_json2 == contract_currencies_model_json + +class TestContractTerms(): + """ + Test Class for ContractTerms + """ + + def test_contract_terms_serialization(self): + """ + Test serialization/deserialization for ContractTerms + """ + + # Construct dict forms of any model objects needed in order to build this model. + + interpretation_model = {} # Interpretation + interpretation_model['value'] = 'testString' + interpretation_model['numeric_value'] = 72.5 + interpretation_model['unit'] = 'testString' + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a ContractTerms model + contract_terms_model_json = {} + contract_terms_model_json['confidence_level'] = 'High' + contract_terms_model_json['text'] = 'testString' + contract_terms_model_json['text_normalized'] = 'testString' + contract_terms_model_json['interpretation'] = interpretation_model + contract_terms_model_json['provenance_ids'] = ['testString'] + contract_terms_model_json['location'] = location_model + + # Construct a model instance of ContractTerms by calling from_dict on the json representation + contract_terms_model = ContractTerms.from_dict(contract_terms_model_json) + assert contract_terms_model != False + + # Construct a model instance of ContractTerms by calling from_dict on the json representation + contract_terms_model_dict = ContractTerms.from_dict(contract_terms_model_json).__dict__ + contract_terms_model2 = ContractTerms(**contract_terms_model_dict) + + # Verify the model instances are equivalent + assert contract_terms_model == contract_terms_model2 + + # Convert model instance back to dict and verify no loss of data + contract_terms_model_json2 = contract_terms_model.to_dict() + assert contract_terms_model_json2 == contract_terms_model_json + +class TestContractTypes(): + """ + Test Class for ContractTypes + """ + + def test_contract_types_serialization(self): + """ + Test serialization/deserialization for ContractTypes + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a ContractTypes model + contract_types_model_json = {} + contract_types_model_json['confidence_level'] = 'High' + contract_types_model_json['text'] = 'testString' + contract_types_model_json['provenance_ids'] = ['testString'] + contract_types_model_json['location'] = location_model + + # Construct a model instance of ContractTypes by calling from_dict on the json representation + contract_types_model = ContractTypes.from_dict(contract_types_model_json) + assert contract_types_model != False + + # Construct a model instance of ContractTypes by calling from_dict on the json representation + contract_types_model_dict = ContractTypes.from_dict(contract_types_model_json).__dict__ + contract_types_model2 = ContractTypes(**contract_types_model_dict) + + # Verify the model instances are equivalent + assert contract_types_model == contract_types_model2 + + # Convert model instance back to dict and verify no loss of data + contract_types_model_json2 = contract_types_model.to_dict() + assert contract_types_model_json2 == contract_types_model_json + +class TestDocCounts(): + """ + Test Class for DocCounts + """ + + def test_doc_counts_serialization(self): + """ + Test serialization/deserialization for DocCounts + """ + + # Construct a json representation of a DocCounts model + doc_counts_model_json = {} + doc_counts_model_json['total'] = 38 + doc_counts_model_json['pending'] = 38 + doc_counts_model_json['successful'] = 38 + doc_counts_model_json['failed'] = 38 + + # Construct a model instance of DocCounts by calling from_dict on the json representation + doc_counts_model = DocCounts.from_dict(doc_counts_model_json) + assert doc_counts_model != False + + # Construct a model instance of DocCounts by calling from_dict on the json representation + doc_counts_model_dict = DocCounts.from_dict(doc_counts_model_json).__dict__ + doc_counts_model2 = DocCounts(**doc_counts_model_dict) + + # Verify the model instances are equivalent + assert doc_counts_model == doc_counts_model2 + + # Convert model instance back to dict and verify no loss of data + doc_counts_model_json2 = doc_counts_model.to_dict() + assert doc_counts_model_json2 == doc_counts_model_json + +class TestDocInfo(): + """ + Test Class for DocInfo + """ + + def test_doc_info_serialization(self): + """ + Test serialization/deserialization for DocInfo + """ + + # Construct a json representation of a DocInfo model + doc_info_model_json = {} + doc_info_model_json['html'] = 'testString' + doc_info_model_json['title'] = 'testString' + doc_info_model_json['hash'] = 'testString' + + # Construct a model instance of DocInfo by calling from_dict on the json representation + doc_info_model = DocInfo.from_dict(doc_info_model_json) + assert doc_info_model != False + + # Construct a model instance of DocInfo by calling from_dict on the json representation + doc_info_model_dict = DocInfo.from_dict(doc_info_model_json).__dict__ + doc_info_model2 = DocInfo(**doc_info_model_dict) + + # Verify the model instances are equivalent + assert doc_info_model == doc_info_model2 + + # Convert model instance back to dict and verify no loss of data + doc_info_model_json2 = doc_info_model.to_dict() + assert doc_info_model_json2 == doc_info_model_json + +class TestDocStructure(): + """ + Test Class for DocStructure + """ + + def test_doc_structure_serialization(self): + """ + Test serialization/deserialization for DocStructure + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + element_locations_model = {} # ElementLocations + element_locations_model['begin'] = 38 + element_locations_model['end'] = 38 + + section_titles_model = {} # SectionTitles + section_titles_model['text'] = 'testString' + section_titles_model['location'] = location_model + section_titles_model['level'] = 38 + section_titles_model['element_locations'] = [element_locations_model] + + leading_sentence_model = {} # LeadingSentence + leading_sentence_model['text'] = 'testString' + leading_sentence_model['location'] = location_model + leading_sentence_model['element_locations'] = [element_locations_model] + + paragraphs_model = {} # Paragraphs + paragraphs_model['location'] = location_model + + # Construct a json representation of a DocStructure model + doc_structure_model_json = {} + doc_structure_model_json['section_titles'] = [section_titles_model] + doc_structure_model_json['leading_sentences'] = [leading_sentence_model] + doc_structure_model_json['paragraphs'] = [paragraphs_model] + + # Construct a model instance of DocStructure by calling from_dict on the json representation + doc_structure_model = DocStructure.from_dict(doc_structure_model_json) + assert doc_structure_model != False + + # Construct a model instance of DocStructure by calling from_dict on the json representation + doc_structure_model_dict = DocStructure.from_dict(doc_structure_model_json).__dict__ + doc_structure_model2 = DocStructure(**doc_structure_model_dict) + + # Verify the model instances are equivalent + assert doc_structure_model == doc_structure_model2 + + # Convert model instance back to dict and verify no loss of data + doc_structure_model_json2 = doc_structure_model.to_dict() + assert doc_structure_model_json2 == doc_structure_model_json + +class TestDocument(): + """ + Test Class for Document + """ + + def test_document_serialization(self): + """ + Test serialization/deserialization for Document + """ + + # Construct a json representation of a Document model + document_model_json = {} + document_model_json['title'] = 'testString' + document_model_json['html'] = 'testString' + document_model_json['hash'] = 'testString' + document_model_json['label'] = 'testString' + + # Construct a model instance of Document by calling from_dict on the json representation + document_model = Document.from_dict(document_model_json) + assert document_model != False + + # Construct a model instance of Document by calling from_dict on the json representation + document_model_dict = Document.from_dict(document_model_json).__dict__ + document_model2 = Document(**document_model_dict) + + # Verify the model instances are equivalent + assert document_model == document_model2 + + # Convert model instance back to dict and verify no loss of data + document_model_json2 = document_model.to_dict() + assert document_model_json2 == document_model_json + +class TestEffectiveDates(): + """ + Test Class for EffectiveDates + """ + + def test_effective_dates_serialization(self): + """ + Test serialization/deserialization for EffectiveDates + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a EffectiveDates model + effective_dates_model_json = {} + effective_dates_model_json['confidence_level'] = 'High' + effective_dates_model_json['text'] = 'testString' + effective_dates_model_json['text_normalized'] = 'testString' + effective_dates_model_json['provenance_ids'] = ['testString'] + effective_dates_model_json['location'] = location_model + + # Construct a model instance of EffectiveDates by calling from_dict on the json representation + effective_dates_model = EffectiveDates.from_dict(effective_dates_model_json) + assert effective_dates_model != False + + # Construct a model instance of EffectiveDates by calling from_dict on the json representation + effective_dates_model_dict = EffectiveDates.from_dict(effective_dates_model_json).__dict__ + effective_dates_model2 = EffectiveDates(**effective_dates_model_dict) + + # Verify the model instances are equivalent + assert effective_dates_model == effective_dates_model2 + + # Convert model instance back to dict and verify no loss of data + effective_dates_model_json2 = effective_dates_model.to_dict() + assert effective_dates_model_json2 == effective_dates_model_json + +class TestElement(): + """ + Test Class for Element + """ + + def test_element_serialization(self): + """ + Test serialization/deserialization for Element + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + type_label_model = {} # TypeLabel + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'added' + + category_model = {} # Category + category_model['label'] = 'Amendments' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'added' + + attribute_model = {} # Attribute + attribute_model['type'] = 'Currency' + attribute_model['text'] = 'testString' + attribute_model['location'] = location_model + + # Construct a json representation of a Element model + element_model_json = {} + element_model_json['location'] = location_model + element_model_json['text'] = 'testString' + element_model_json['types'] = [type_label_model] + element_model_json['categories'] = [category_model] + element_model_json['attributes'] = [attribute_model] + + # Construct a model instance of Element by calling from_dict on the json representation + element_model = Element.from_dict(element_model_json) + assert element_model != False + + # Construct a model instance of Element by calling from_dict on the json representation + element_model_dict = Element.from_dict(element_model_json).__dict__ + element_model2 = Element(**element_model_dict) + + # Verify the model instances are equivalent + assert element_model == element_model2 + + # Convert model instance back to dict and verify no loss of data + element_model_json2 = element_model.to_dict() + assert element_model_json2 == element_model_json + +class TestElementLocations(): + """ + Test Class for ElementLocations + """ + + def test_element_locations_serialization(self): + """ + Test serialization/deserialization for ElementLocations + """ + + # Construct a json representation of a ElementLocations model + element_locations_model_json = {} + element_locations_model_json['begin'] = 38 + element_locations_model_json['end'] = 38 + + # Construct a model instance of ElementLocations by calling from_dict on the json representation + element_locations_model = ElementLocations.from_dict(element_locations_model_json) + assert element_locations_model != False + + # Construct a model instance of ElementLocations by calling from_dict on the json representation + element_locations_model_dict = ElementLocations.from_dict(element_locations_model_json).__dict__ + element_locations_model2 = ElementLocations(**element_locations_model_dict) + + # Verify the model instances are equivalent + assert element_locations_model == element_locations_model2 + + # Convert model instance back to dict and verify no loss of data + element_locations_model_json2 = element_locations_model.to_dict() + assert element_locations_model_json2 == element_locations_model_json + +class TestElementPair(): + """ + Test Class for ElementPair + """ + + def test_element_pair_serialization(self): + """ + Test serialization/deserialization for ElementPair + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + type_label_comparison_model = {} # TypeLabelComparison + type_label_comparison_model['label'] = label_model + + category_comparison_model = {} # CategoryComparison + category_comparison_model['label'] = 'Amendments' + + attribute_model = {} # Attribute + attribute_model['type'] = 'Currency' + attribute_model['text'] = 'testString' + attribute_model['location'] = location_model + + # Construct a json representation of a ElementPair model + element_pair_model_json = {} + element_pair_model_json['document_label'] = 'testString' + element_pair_model_json['text'] = 'testString' + element_pair_model_json['location'] = location_model + element_pair_model_json['types'] = [type_label_comparison_model] + element_pair_model_json['categories'] = [category_comparison_model] + element_pair_model_json['attributes'] = [attribute_model] + + # Construct a model instance of ElementPair by calling from_dict on the json representation + element_pair_model = ElementPair.from_dict(element_pair_model_json) + assert element_pair_model != False + + # Construct a model instance of ElementPair by calling from_dict on the json representation + element_pair_model_dict = ElementPair.from_dict(element_pair_model_json).__dict__ + element_pair_model2 = ElementPair(**element_pair_model_dict) + + # Verify the model instances are equivalent + assert element_pair_model == element_pair_model2 + + # Convert model instance back to dict and verify no loss of data + element_pair_model_json2 = element_pair_model.to_dict() + assert element_pair_model_json2 == element_pair_model_json + +class TestFeedbackDataInput(): + """ + Test Class for FeedbackDataInput + """ + + def test_feedback_data_input_serialization(self): + """ + Test serialization/deserialization for FeedbackDataInput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + short_doc_model = {} # ShortDoc + short_doc_model['title'] = 'testString' + short_doc_model['hash'] = 'testString' + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + type_label_model = {} # TypeLabel + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'added' + + category_model = {} # Category + category_model['label'] = 'Amendments' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'added' + + original_labels_in_model = {} # OriginalLabelsIn + original_labels_in_model['types'] = [type_label_model] + original_labels_in_model['categories'] = [category_model] + + updated_labels_in_model = {} # UpdatedLabelsIn + updated_labels_in_model['types'] = [type_label_model] + updated_labels_in_model['categories'] = [category_model] + + # Construct a json representation of a FeedbackDataInput model + feedback_data_input_model_json = {} + feedback_data_input_model_json['feedback_type'] = 'testString' + feedback_data_input_model_json['document'] = short_doc_model + feedback_data_input_model_json['model_id'] = 'testString' + feedback_data_input_model_json['model_version'] = 'testString' + feedback_data_input_model_json['location'] = location_model + feedback_data_input_model_json['text'] = 'testString' + feedback_data_input_model_json['original_labels'] = original_labels_in_model + feedback_data_input_model_json['updated_labels'] = updated_labels_in_model + + # Construct a model instance of FeedbackDataInput by calling from_dict on the json representation + feedback_data_input_model = FeedbackDataInput.from_dict(feedback_data_input_model_json) + assert feedback_data_input_model != False + + # Construct a model instance of FeedbackDataInput by calling from_dict on the json representation + feedback_data_input_model_dict = FeedbackDataInput.from_dict(feedback_data_input_model_json).__dict__ + feedback_data_input_model2 = FeedbackDataInput(**feedback_data_input_model_dict) + + # Verify the model instances are equivalent + assert feedback_data_input_model == feedback_data_input_model2 + + # Convert model instance back to dict and verify no loss of data + feedback_data_input_model_json2 = feedback_data_input_model.to_dict() + assert feedback_data_input_model_json2 == feedback_data_input_model_json + +class TestFeedbackDataOutput(): + """ + Test Class for FeedbackDataOutput + """ + + def test_feedback_data_output_serialization(self): + """ + Test serialization/deserialization for FeedbackDataOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + short_doc_model = {} # ShortDoc + short_doc_model['title'] = 'testString' + short_doc_model['hash'] = 'testString' + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + type_label_model = {} # TypeLabel + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'added' + + category_model = {} # Category + category_model['label'] = 'Amendments' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'added' + + original_labels_out_model = {} # OriginalLabelsOut + original_labels_out_model['types'] = [type_label_model] + original_labels_out_model['categories'] = [category_model] + + updated_labels_out_model = {} # UpdatedLabelsOut + updated_labels_out_model['types'] = [type_label_model] + updated_labels_out_model['categories'] = [category_model] + + pagination_model = {} # Pagination + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 26 + + # Construct a json representation of a FeedbackDataOutput model + feedback_data_output_model_json = {} + feedback_data_output_model_json['feedback_type'] = 'testString' + feedback_data_output_model_json['document'] = short_doc_model + feedback_data_output_model_json['model_id'] = 'testString' + feedback_data_output_model_json['model_version'] = 'testString' + feedback_data_output_model_json['location'] = location_model + feedback_data_output_model_json['text'] = 'testString' + feedback_data_output_model_json['original_labels'] = original_labels_out_model + feedback_data_output_model_json['updated_labels'] = updated_labels_out_model + feedback_data_output_model_json['pagination'] = pagination_model + + # Construct a model instance of FeedbackDataOutput by calling from_dict on the json representation + feedback_data_output_model = FeedbackDataOutput.from_dict(feedback_data_output_model_json) + assert feedback_data_output_model != False + + # Construct a model instance of FeedbackDataOutput by calling from_dict on the json representation + feedback_data_output_model_dict = FeedbackDataOutput.from_dict(feedback_data_output_model_json).__dict__ + feedback_data_output_model2 = FeedbackDataOutput(**feedback_data_output_model_dict) + + # Verify the model instances are equivalent + assert feedback_data_output_model == feedback_data_output_model2 + + # Convert model instance back to dict and verify no loss of data + feedback_data_output_model_json2 = feedback_data_output_model.to_dict() + assert feedback_data_output_model_json2 == feedback_data_output_model_json + +class TestFeedbackDeleted(): + """ + Test Class for FeedbackDeleted + """ + + def test_feedback_deleted_serialization(self): + """ + Test serialization/deserialization for FeedbackDeleted + """ + + # Construct a json representation of a FeedbackDeleted model + feedback_deleted_model_json = {} + feedback_deleted_model_json['status'] = 38 + feedback_deleted_model_json['message'] = 'testString' + + # Construct a model instance of FeedbackDeleted by calling from_dict on the json representation + feedback_deleted_model = FeedbackDeleted.from_dict(feedback_deleted_model_json) + assert feedback_deleted_model != False + + # Construct a model instance of FeedbackDeleted by calling from_dict on the json representation + feedback_deleted_model_dict = FeedbackDeleted.from_dict(feedback_deleted_model_json).__dict__ + feedback_deleted_model2 = FeedbackDeleted(**feedback_deleted_model_dict) + + # Verify the model instances are equivalent + assert feedback_deleted_model == feedback_deleted_model2 + + # Convert model instance back to dict and verify no loss of data + feedback_deleted_model_json2 = feedback_deleted_model.to_dict() + assert feedback_deleted_model_json2 == feedback_deleted_model_json + +class TestFeedbackList(): + """ + Test Class for FeedbackList + """ + + def test_feedback_list_serialization(self): + """ + Test serialization/deserialization for FeedbackList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + short_doc_model = {} # ShortDoc + short_doc_model['title'] = 'Legal Approval SOW' + short_doc_model['hash'] = 'dcd82f59c6bb1a289a514b611d531191' + + location_model = {} # Location + location_model['begin'] = 214 + location_model['end'] = 237 + + label_model = {} # Label + label_model['nature'] = 'Obligation' + label_model['party'] = 'IBM' + + type_label_model = {} # TypeLabel + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'unchanged' + + category_model = {} # Category + category_model['label'] = 'Responsibilities' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'unchanged' + + original_labels_out_model = {} # OriginalLabelsOut + original_labels_out_model['types'] = [type_label_model] + original_labels_out_model['categories'] = [category_model] + + updated_labels_out_model = {} # UpdatedLabelsOut + updated_labels_out_model['types'] = [type_label_model] + updated_labels_out_model['categories'] = [category_model] + + pagination_model = {} # Pagination + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 26 + + feedback_data_output_model = {} # FeedbackDataOutput + feedback_data_output_model['feedback_type'] = 'element_classification' + feedback_data_output_model['document'] = short_doc_model + feedback_data_output_model['model_id'] = 'contracts' + feedback_data_output_model['model_version'] = '10.00' + feedback_data_output_model['location'] = location_model + feedback_data_output_model['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.' + feedback_data_output_model['original_labels'] = original_labels_out_model + feedback_data_output_model['updated_labels'] = updated_labels_out_model + feedback_data_output_model['pagination'] = pagination_model + + get_feedback_model = {} # GetFeedback + get_feedback_model['feedback_id'] = '9730b437-cb86-4d40-9a84-ff6948bb3dd1' + get_feedback_model['created'] = '2020-01-28T18:40:40.123456Z' + get_feedback_model['comment'] = 'testString' + get_feedback_model['feedback_data'] = feedback_data_output_model + + # Construct a json representation of a FeedbackList model + feedback_list_model_json = {} + feedback_list_model_json['feedback'] = [get_feedback_model] + + # Construct a model instance of FeedbackList by calling from_dict on the json representation + feedback_list_model = FeedbackList.from_dict(feedback_list_model_json) + assert feedback_list_model != False + + # Construct a model instance of FeedbackList by calling from_dict on the json representation + feedback_list_model_dict = FeedbackList.from_dict(feedback_list_model_json).__dict__ + feedback_list_model2 = FeedbackList(**feedback_list_model_dict) + + # Verify the model instances are equivalent + assert feedback_list_model == feedback_list_model2 + + # Convert model instance back to dict and verify no loss of data + feedback_list_model_json2 = feedback_list_model.to_dict() + assert feedback_list_model_json2 == feedback_list_model_json + +class TestFeedbackReturn(): + """ + Test Class for FeedbackReturn + """ + + def test_feedback_return_serialization(self): + """ + Test serialization/deserialization for FeedbackReturn + """ + + # Construct dict forms of any model objects needed in order to build this model. + + short_doc_model = {} # ShortDoc + short_doc_model['title'] = 'testString' + short_doc_model['hash'] = 'testString' + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + type_label_model = {} # TypeLabel + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'added' + + category_model = {} # Category + category_model['label'] = 'Amendments' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'added' + + original_labels_out_model = {} # OriginalLabelsOut + original_labels_out_model['types'] = [type_label_model] + original_labels_out_model['categories'] = [category_model] + + updated_labels_out_model = {} # UpdatedLabelsOut + updated_labels_out_model['types'] = [type_label_model] + updated_labels_out_model['categories'] = [category_model] + + pagination_model = {} # Pagination + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 26 + + feedback_data_output_model = {} # FeedbackDataOutput + feedback_data_output_model['feedback_type'] = 'testString' + feedback_data_output_model['document'] = short_doc_model + feedback_data_output_model['model_id'] = 'testString' + feedback_data_output_model['model_version'] = 'testString' + feedback_data_output_model['location'] = location_model + feedback_data_output_model['text'] = 'testString' + feedback_data_output_model['original_labels'] = original_labels_out_model + feedback_data_output_model['updated_labels'] = updated_labels_out_model + feedback_data_output_model['pagination'] = pagination_model + + # Construct a json representation of a FeedbackReturn model + feedback_return_model_json = {} + feedback_return_model_json['feedback_id'] = 'testString' + feedback_return_model_json['user_id'] = 'testString' + feedback_return_model_json['comment'] = 'testString' + feedback_return_model_json['created'] = '2020-01-28T18:40:40.123456Z' + feedback_return_model_json['feedback_data'] = feedback_data_output_model + + # Construct a model instance of FeedbackReturn by calling from_dict on the json representation + feedback_return_model = FeedbackReturn.from_dict(feedback_return_model_json) + assert feedback_return_model != False + + # Construct a model instance of FeedbackReturn by calling from_dict on the json representation + feedback_return_model_dict = FeedbackReturn.from_dict(feedback_return_model_json).__dict__ + feedback_return_model2 = FeedbackReturn(**feedback_return_model_dict) + + # Verify the model instances are equivalent + assert feedback_return_model == feedback_return_model2 + + # Convert model instance back to dict and verify no loss of data + feedback_return_model_json2 = feedback_return_model.to_dict() + assert feedback_return_model_json2 == feedback_return_model_json + +class TestGetFeedback(): + """ + Test Class for GetFeedback + """ + + def test_get_feedback_serialization(self): + """ + Test serialization/deserialization for GetFeedback + """ + + # Construct dict forms of any model objects needed in order to build this model. + + short_doc_model = {} # ShortDoc + short_doc_model['title'] = 'Legal Approval SOW' + short_doc_model['hash'] = '4492935afd3673e04082591d163ad68b' + + location_model = {} # Location + location_model['begin'] = 214 + location_model['end'] = 237 + + label_model = {} # Label + label_model['nature'] = 'Obligation' + label_model['party'] = 'IBM' + + type_label_model = {} # TypeLabel + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'unchanged' + + category_model = {} # Category + category_model['label'] = 'obligation' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'removed' + + original_labels_out_model = {} # OriginalLabelsOut + original_labels_out_model['types'] = [type_label_model] + original_labels_out_model['categories'] = [category_model] + + updated_labels_out_model = {} # UpdatedLabelsOut + updated_labels_out_model['types'] = [type_label_model] + updated_labels_out_model['categories'] = [category_model] + + pagination_model = {} # Pagination + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 26 + + feedback_data_output_model = {} # FeedbackDataOutput + feedback_data_output_model['feedback_type'] = 'element_classification' + feedback_data_output_model['document'] = short_doc_model + feedback_data_output_model['model_id'] = 'contracts' + feedback_data_output_model['model_version'] = '10.00' + feedback_data_output_model['location'] = location_model + feedback_data_output_model['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.' + feedback_data_output_model['original_labels'] = original_labels_out_model + feedback_data_output_model['updated_labels'] = updated_labels_out_model + feedback_data_output_model['pagination'] = pagination_model + + # Construct a json representation of a GetFeedback model + get_feedback_model_json = {} + get_feedback_model_json['feedback_id'] = 'testString' + get_feedback_model_json['created'] = '2020-01-28T18:40:40.123456Z' + get_feedback_model_json['comment'] = 'testString' + get_feedback_model_json['feedback_data'] = feedback_data_output_model + + # Construct a model instance of GetFeedback by calling from_dict on the json representation + get_feedback_model = GetFeedback.from_dict(get_feedback_model_json) + assert get_feedback_model != False + + # Construct a model instance of GetFeedback by calling from_dict on the json representation + get_feedback_model_dict = GetFeedback.from_dict(get_feedback_model_json).__dict__ + get_feedback_model2 = GetFeedback(**get_feedback_model_dict) + + # Verify the model instances are equivalent + assert get_feedback_model == get_feedback_model2 + + # Convert model instance back to dict and verify no loss of data + get_feedback_model_json2 = get_feedback_model.to_dict() + assert get_feedback_model_json2 == get_feedback_model_json + +class TestHTMLReturn(): + """ + Test Class for HTMLReturn + """ + + def test_html_return_serialization(self): + """ + Test serialization/deserialization for HTMLReturn + """ + + # Construct a json representation of a HTMLReturn model + html_return_model_json = {} + html_return_model_json['num_pages'] = 'testString' + html_return_model_json['author'] = 'testString' + html_return_model_json['publication_date'] = 'testString' + html_return_model_json['title'] = 'testString' + html_return_model_json['html'] = 'testString' + + # Construct a model instance of HTMLReturn by calling from_dict on the json representation + html_return_model = HTMLReturn.from_dict(html_return_model_json) + assert html_return_model != False + + # Construct a model instance of HTMLReturn by calling from_dict on the json representation + html_return_model_dict = HTMLReturn.from_dict(html_return_model_json).__dict__ + html_return_model2 = HTMLReturn(**html_return_model_dict) + + # Verify the model instances are equivalent + assert html_return_model == html_return_model2 + + # Convert model instance back to dict and verify no loss of data + html_return_model_json2 = html_return_model.to_dict() + assert html_return_model_json2 == html_return_model_json + +class TestInterpretation(): + """ + Test Class for Interpretation + """ + + def test_interpretation_serialization(self): + """ + Test serialization/deserialization for Interpretation + """ + + # Construct a json representation of a Interpretation model + interpretation_model_json = {} + interpretation_model_json['value'] = 'testString' + interpretation_model_json['numeric_value'] = 72.5 + interpretation_model_json['unit'] = 'testString' + + # Construct a model instance of Interpretation by calling from_dict on the json representation + interpretation_model = Interpretation.from_dict(interpretation_model_json) + assert interpretation_model != False + + # Construct a model instance of Interpretation by calling from_dict on the json representation + interpretation_model_dict = Interpretation.from_dict(interpretation_model_json).__dict__ + interpretation_model2 = Interpretation(**interpretation_model_dict) + + # Verify the model instances are equivalent + assert interpretation_model == interpretation_model2 + + # Convert model instance back to dict and verify no loss of data + interpretation_model_json2 = interpretation_model.to_dict() + assert interpretation_model_json2 == interpretation_model_json + +class TestKey(): + """ + Test Class for Key + """ + + def test_key_serialization(self): + """ + Test serialization/deserialization for Key + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a Key model + key_model_json = {} + key_model_json['cell_id'] = 'testString' + key_model_json['location'] = location_model + key_model_json['text'] = 'testString' + + # Construct a model instance of Key by calling from_dict on the json representation + key_model = Key.from_dict(key_model_json) + assert key_model != False + + # Construct a model instance of Key by calling from_dict on the json representation + key_model_dict = Key.from_dict(key_model_json).__dict__ + key_model2 = Key(**key_model_dict) + + # Verify the model instances are equivalent + assert key_model == key_model2 + + # Convert model instance back to dict and verify no loss of data + key_model_json2 = key_model.to_dict() + assert key_model_json2 == key_model_json + +class TestKeyValuePair(): + """ + Test Class for KeyValuePair + """ + + def test_key_value_pair_serialization(self): + """ + Test serialization/deserialization for KeyValuePair + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + key_model = {} # Key + key_model['cell_id'] = 'testString' + key_model['location'] = location_model + key_model['text'] = 'testString' + + value_model = {} # Value + value_model['cell_id'] = 'testString' + value_model['location'] = location_model + value_model['text'] = 'testString' + + # Construct a json representation of a KeyValuePair model + key_value_pair_model_json = {} + key_value_pair_model_json['key'] = key_model + key_value_pair_model_json['value'] = [value_model] + + # Construct a model instance of KeyValuePair by calling from_dict on the json representation + key_value_pair_model = KeyValuePair.from_dict(key_value_pair_model_json) + assert key_value_pair_model != False + + # Construct a model instance of KeyValuePair by calling from_dict on the json representation + key_value_pair_model_dict = KeyValuePair.from_dict(key_value_pair_model_json).__dict__ + key_value_pair_model2 = KeyValuePair(**key_value_pair_model_dict) + + # Verify the model instances are equivalent + assert key_value_pair_model == key_value_pair_model2 + + # Convert model instance back to dict and verify no loss of data + key_value_pair_model_json2 = key_value_pair_model.to_dict() + assert key_value_pair_model_json2 == key_value_pair_model_json + +class TestLabel(): + """ + Test Class for Label + """ + + def test_label_serialization(self): + """ + Test serialization/deserialization for Label + """ + + # Construct a json representation of a Label model + label_model_json = {} + label_model_json['nature'] = 'testString' + label_model_json['party'] = 'testString' + + # Construct a model instance of Label by calling from_dict on the json representation + label_model = Label.from_dict(label_model_json) + assert label_model != False + + # Construct a model instance of Label by calling from_dict on the json representation + label_model_dict = Label.from_dict(label_model_json).__dict__ + label_model2 = Label(**label_model_dict) + + # Verify the model instances are equivalent + assert label_model == label_model2 + + # Convert model instance back to dict and verify no loss of data + label_model_json2 = label_model.to_dict() + assert label_model_json2 == label_model_json + +class TestLeadingSentence(): + """ + Test Class for LeadingSentence + """ + + def test_leading_sentence_serialization(self): + """ + Test serialization/deserialization for LeadingSentence + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + element_locations_model = {} # ElementLocations + element_locations_model['begin'] = 38 + element_locations_model['end'] = 38 + + # Construct a json representation of a LeadingSentence model + leading_sentence_model_json = {} + leading_sentence_model_json['text'] = 'testString' + leading_sentence_model_json['location'] = location_model + leading_sentence_model_json['element_locations'] = [element_locations_model] + + # Construct a model instance of LeadingSentence by calling from_dict on the json representation + leading_sentence_model = LeadingSentence.from_dict(leading_sentence_model_json) + assert leading_sentence_model != False + + # Construct a model instance of LeadingSentence by calling from_dict on the json representation + leading_sentence_model_dict = LeadingSentence.from_dict(leading_sentence_model_json).__dict__ + leading_sentence_model2 = LeadingSentence(**leading_sentence_model_dict) + + # Verify the model instances are equivalent + assert leading_sentence_model == leading_sentence_model2 + + # Convert model instance back to dict and verify no loss of data + leading_sentence_model_json2 = leading_sentence_model.to_dict() + assert leading_sentence_model_json2 == leading_sentence_model_json + +class TestLocation(): + """ + Test Class for Location + """ + + def test_location_serialization(self): + """ + Test serialization/deserialization for Location + """ + + # Construct a json representation of a Location model + location_model_json = {} + location_model_json['begin'] = 26 + location_model_json['end'] = 26 + + # Construct a model instance of Location by calling from_dict on the json representation + location_model = Location.from_dict(location_model_json) + assert location_model != False + + # Construct a model instance of Location by calling from_dict on the json representation + location_model_dict = Location.from_dict(location_model_json).__dict__ + location_model2 = Location(**location_model_dict) + + # Verify the model instances are equivalent + assert location_model == location_model2 + + # Convert model instance back to dict and verify no loss of data + location_model_json2 = location_model.to_dict() + assert location_model_json2 == location_model_json + +class TestMention(): + """ + Test Class for Mention + """ + + def test_mention_serialization(self): + """ + Test serialization/deserialization for Mention + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a Mention model + mention_model_json = {} + mention_model_json['text'] = 'testString' + mention_model_json['location'] = location_model + + # Construct a model instance of Mention by calling from_dict on the json representation + mention_model = Mention.from_dict(mention_model_json) + assert mention_model != False + + # Construct a model instance of Mention by calling from_dict on the json representation + mention_model_dict = Mention.from_dict(mention_model_json).__dict__ + mention_model2 = Mention(**mention_model_dict) + + # Verify the model instances are equivalent + assert mention_model == mention_model2 + + # Convert model instance back to dict and verify no loss of data + mention_model_json2 = mention_model.to_dict() + assert mention_model_json2 == mention_model_json + +class TestOriginalLabelsIn(): + """ + Test Class for OriginalLabelsIn + """ + + def test_original_labels_in_serialization(self): + """ + Test serialization/deserialization for OriginalLabelsIn + """ + + # Construct dict forms of any model objects needed in order to build this model. + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + type_label_model = {} # TypeLabel + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'added' + + category_model = {} # Category + category_model['label'] = 'Amendments' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'added' + + # Construct a json representation of a OriginalLabelsIn model + original_labels_in_model_json = {} + original_labels_in_model_json['types'] = [type_label_model] + original_labels_in_model_json['categories'] = [category_model] + + # Construct a model instance of OriginalLabelsIn by calling from_dict on the json representation + original_labels_in_model = OriginalLabelsIn.from_dict(original_labels_in_model_json) + assert original_labels_in_model != False + + # Construct a model instance of OriginalLabelsIn by calling from_dict on the json representation + original_labels_in_model_dict = OriginalLabelsIn.from_dict(original_labels_in_model_json).__dict__ + original_labels_in_model2 = OriginalLabelsIn(**original_labels_in_model_dict) + + # Verify the model instances are equivalent + assert original_labels_in_model == original_labels_in_model2 + + # Convert model instance back to dict and verify no loss of data + original_labels_in_model_json2 = original_labels_in_model.to_dict() + assert original_labels_in_model_json2 == original_labels_in_model_json + +class TestOriginalLabelsOut(): + """ + Test Class for OriginalLabelsOut + """ + + def test_original_labels_out_serialization(self): + """ + Test serialization/deserialization for OriginalLabelsOut + """ + + # Construct dict forms of any model objects needed in order to build this model. + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + type_label_model = {} # TypeLabel + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'added' + + category_model = {} # Category + category_model['label'] = 'Amendments' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'added' + + # Construct a json representation of a OriginalLabelsOut model + original_labels_out_model_json = {} + original_labels_out_model_json['types'] = [type_label_model] + original_labels_out_model_json['categories'] = [category_model] + + # Construct a model instance of OriginalLabelsOut by calling from_dict on the json representation + original_labels_out_model = OriginalLabelsOut.from_dict(original_labels_out_model_json) + assert original_labels_out_model != False + + # Construct a model instance of OriginalLabelsOut by calling from_dict on the json representation + original_labels_out_model_dict = OriginalLabelsOut.from_dict(original_labels_out_model_json).__dict__ + original_labels_out_model2 = OriginalLabelsOut(**original_labels_out_model_dict) + + # Verify the model instances are equivalent + assert original_labels_out_model == original_labels_out_model2 + + # Convert model instance back to dict and verify no loss of data + original_labels_out_model_json2 = original_labels_out_model.to_dict() + assert original_labels_out_model_json2 == original_labels_out_model_json + +class TestPagination(): + """ + Test Class for Pagination + """ + + def test_pagination_serialization(self): + """ + Test serialization/deserialization for Pagination + """ + + # Construct a json representation of a Pagination model + pagination_model_json = {} + pagination_model_json['refresh_cursor'] = 'testString' + pagination_model_json['next_cursor'] = 'testString' + pagination_model_json['refresh_url'] = 'testString' + pagination_model_json['next_url'] = 'testString' + pagination_model_json['total'] = 26 + + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model = Pagination.from_dict(pagination_model_json) + assert pagination_model != False + + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ + pagination_model2 = Pagination(**pagination_model_dict) + + # Verify the model instances are equivalent + assert pagination_model == pagination_model2 + + # Convert model instance back to dict and verify no loss of data + pagination_model_json2 = pagination_model.to_dict() + assert pagination_model_json2 == pagination_model_json + +class TestParagraphs(): + """ + Test Class for Paragraphs + """ + + def test_paragraphs_serialization(self): + """ + Test serialization/deserialization for Paragraphs + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a Paragraphs model + paragraphs_model_json = {} + paragraphs_model_json['location'] = location_model + + # Construct a model instance of Paragraphs by calling from_dict on the json representation + paragraphs_model = Paragraphs.from_dict(paragraphs_model_json) + assert paragraphs_model != False + + # Construct a model instance of Paragraphs by calling from_dict on the json representation + paragraphs_model_dict = Paragraphs.from_dict(paragraphs_model_json).__dict__ + paragraphs_model2 = Paragraphs(**paragraphs_model_dict) + + # Verify the model instances are equivalent + assert paragraphs_model == paragraphs_model2 + + # Convert model instance back to dict and verify no loss of data + paragraphs_model_json2 = paragraphs_model.to_dict() + assert paragraphs_model_json2 == paragraphs_model_json + +class TestParties(): + """ + Test Class for Parties + """ + + def test_parties_serialization(self): + """ + Test serialization/deserialization for Parties + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + address_model = {} # Address + address_model['text'] = 'testString' + address_model['location'] = location_model + + contact_model = {} # Contact + contact_model['name'] = 'testString' + contact_model['role'] = 'testString' + + mention_model = {} # Mention + mention_model['text'] = 'testString' + mention_model['location'] = location_model + + # Construct a json representation of a Parties model + parties_model_json = {} + parties_model_json['party'] = 'testString' + parties_model_json['role'] = 'testString' + parties_model_json['importance'] = 'Primary' + parties_model_json['addresses'] = [address_model] + parties_model_json['contacts'] = [contact_model] + parties_model_json['mentions'] = [mention_model] + + # Construct a model instance of Parties by calling from_dict on the json representation + parties_model = Parties.from_dict(parties_model_json) + assert parties_model != False + + # Construct a model instance of Parties by calling from_dict on the json representation + parties_model_dict = Parties.from_dict(parties_model_json).__dict__ + parties_model2 = Parties(**parties_model_dict) + + # Verify the model instances are equivalent + assert parties_model == parties_model2 + + # Convert model instance back to dict and verify no loss of data + parties_model_json2 = parties_model.to_dict() + assert parties_model_json2 == parties_model_json + +class TestPaymentTerms(): + """ + Test Class for PaymentTerms + """ + + def test_payment_terms_serialization(self): + """ + Test serialization/deserialization for PaymentTerms + """ + + # Construct dict forms of any model objects needed in order to build this model. + + interpretation_model = {} # Interpretation + interpretation_model['value'] = 'testString' + interpretation_model['numeric_value'] = 72.5 + interpretation_model['unit'] = 'testString' + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a PaymentTerms model + payment_terms_model_json = {} + payment_terms_model_json['confidence_level'] = 'High' + payment_terms_model_json['text'] = 'testString' + payment_terms_model_json['text_normalized'] = 'testString' + payment_terms_model_json['interpretation'] = interpretation_model + payment_terms_model_json['provenance_ids'] = ['testString'] + payment_terms_model_json['location'] = location_model + + # Construct a model instance of PaymentTerms by calling from_dict on the json representation + payment_terms_model = PaymentTerms.from_dict(payment_terms_model_json) + assert payment_terms_model != False + + # Construct a model instance of PaymentTerms by calling from_dict on the json representation + payment_terms_model_dict = PaymentTerms.from_dict(payment_terms_model_json).__dict__ + payment_terms_model2 = PaymentTerms(**payment_terms_model_dict) + + # Verify the model instances are equivalent + assert payment_terms_model == payment_terms_model2 + + # Convert model instance back to dict and verify no loss of data + payment_terms_model_json2 = payment_terms_model.to_dict() + assert payment_terms_model_json2 == payment_terms_model_json + +class TestRowHeaders(): + """ + Test Class for RowHeaders + """ + + def test_row_headers_serialization(self): + """ + Test serialization/deserialization for RowHeaders + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a RowHeaders model + row_headers_model_json = {} + row_headers_model_json['cell_id'] = 'testString' + row_headers_model_json['location'] = location_model + row_headers_model_json['text'] = 'testString' + row_headers_model_json['text_normalized'] = 'testString' + row_headers_model_json['row_index_begin'] = 26 + row_headers_model_json['row_index_end'] = 26 + row_headers_model_json['column_index_begin'] = 26 + row_headers_model_json['column_index_end'] = 26 + + # Construct a model instance of RowHeaders by calling from_dict on the json representation + row_headers_model = RowHeaders.from_dict(row_headers_model_json) + assert row_headers_model != False + + # Construct a model instance of RowHeaders by calling from_dict on the json representation + row_headers_model_dict = RowHeaders.from_dict(row_headers_model_json).__dict__ + row_headers_model2 = RowHeaders(**row_headers_model_dict) + + # Verify the model instances are equivalent + assert row_headers_model == row_headers_model2 + + # Convert model instance back to dict and verify no loss of data + row_headers_model_json2 = row_headers_model.to_dict() + assert row_headers_model_json2 == row_headers_model_json + +class TestSectionTitle(): + """ + Test Class for SectionTitle + """ + + def test_section_title_serialization(self): + """ + Test serialization/deserialization for SectionTitle + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a SectionTitle model + section_title_model_json = {} + section_title_model_json['text'] = 'testString' + section_title_model_json['location'] = location_model + + # Construct a model instance of SectionTitle by calling from_dict on the json representation + section_title_model = SectionTitle.from_dict(section_title_model_json) + assert section_title_model != False + + # Construct a model instance of SectionTitle by calling from_dict on the json representation + section_title_model_dict = SectionTitle.from_dict(section_title_model_json).__dict__ + section_title_model2 = SectionTitle(**section_title_model_dict) + + # Verify the model instances are equivalent + assert section_title_model == section_title_model2 + + # Convert model instance back to dict and verify no loss of data + section_title_model_json2 = section_title_model.to_dict() + assert section_title_model_json2 == section_title_model_json + +class TestSectionTitles(): + """ + Test Class for SectionTitles + """ + + def test_section_titles_serialization(self): + """ + Test serialization/deserialization for SectionTitles + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + element_locations_model = {} # ElementLocations + element_locations_model['begin'] = 38 + element_locations_model['end'] = 38 + + # Construct a json representation of a SectionTitles model + section_titles_model_json = {} + section_titles_model_json['text'] = 'testString' + section_titles_model_json['location'] = location_model + section_titles_model_json['level'] = 38 + section_titles_model_json['element_locations'] = [element_locations_model] + + # Construct a model instance of SectionTitles by calling from_dict on the json representation + section_titles_model = SectionTitles.from_dict(section_titles_model_json) + assert section_titles_model != False + + # Construct a model instance of SectionTitles by calling from_dict on the json representation + section_titles_model_dict = SectionTitles.from_dict(section_titles_model_json).__dict__ + section_titles_model2 = SectionTitles(**section_titles_model_dict) + + # Verify the model instances are equivalent + assert section_titles_model == section_titles_model2 + + # Convert model instance back to dict and verify no loss of data + section_titles_model_json2 = section_titles_model.to_dict() + assert section_titles_model_json2 == section_titles_model_json + +class TestShortDoc(): + """ + Test Class for ShortDoc + """ + + def test_short_doc_serialization(self): + """ + Test serialization/deserialization for ShortDoc + """ + + # Construct a json representation of a ShortDoc model + short_doc_model_json = {} + short_doc_model_json['title'] = 'testString' + short_doc_model_json['hash'] = 'testString' + + # Construct a model instance of ShortDoc by calling from_dict on the json representation + short_doc_model = ShortDoc.from_dict(short_doc_model_json) + assert short_doc_model != False + + # Construct a model instance of ShortDoc by calling from_dict on the json representation + short_doc_model_dict = ShortDoc.from_dict(short_doc_model_json).__dict__ + short_doc_model2 = ShortDoc(**short_doc_model_dict) + + # Verify the model instances are equivalent + assert short_doc_model == short_doc_model2 + + # Convert model instance back to dict and verify no loss of data + short_doc_model_json2 = short_doc_model.to_dict() + assert short_doc_model_json2 == short_doc_model_json + +class TestTableHeaders(): + """ + Test Class for TableHeaders + """ + + def test_table_headers_serialization(self): + """ + Test serialization/deserialization for TableHeaders + """ + + # Construct a json representation of a TableHeaders model + table_headers_model_json = {} + table_headers_model_json['cell_id'] = 'testString' + table_headers_model_json['location'] = { 'foo': 'bar' } + table_headers_model_json['text'] = 'testString' + table_headers_model_json['row_index_begin'] = 26 + table_headers_model_json['row_index_end'] = 26 + table_headers_model_json['column_index_begin'] = 26 + table_headers_model_json['column_index_end'] = 26 + + # Construct a model instance of TableHeaders by calling from_dict on the json representation + table_headers_model = TableHeaders.from_dict(table_headers_model_json) + assert table_headers_model != False + + # Construct a model instance of TableHeaders by calling from_dict on the json representation + table_headers_model_dict = TableHeaders.from_dict(table_headers_model_json).__dict__ + table_headers_model2 = TableHeaders(**table_headers_model_dict) + + # Verify the model instances are equivalent + assert table_headers_model == table_headers_model2 + + # Convert model instance back to dict and verify no loss of data + table_headers_model_json2 = table_headers_model.to_dict() + assert table_headers_model_json2 == table_headers_model_json + +class TestTableReturn(): + """ + Test Class for TableReturn + """ + + def test_table_return_serialization(self): + """ + Test serialization/deserialization for TableReturn + """ + + # Construct dict forms of any model objects needed in order to build this model. + + doc_info_model = {} # DocInfo + doc_info_model['html'] = 'testString' + doc_info_model['title'] = 'testString' + doc_info_model['hash'] = 'testString' + + location_model = {} # Location + location_model['begin'] = 872 + location_model['end'] = 5879 + + section_title_model = {} # SectionTitle + section_title_model['text'] = 'testString' + section_title_model['location'] = location_model + + table_title_model = {} # TableTitle + table_title_model['location'] = location_model + table_title_model['text'] = 'testString' + + table_headers_model = {} # TableHeaders + table_headers_model['cell_id'] = 'tableHeader-872-873' + table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['text'] = 'testString' + table_headers_model['row_index_begin'] = 0 + table_headers_model['row_index_end'] = 0 + table_headers_model['column_index_begin'] = 0 + table_headers_model['column_index_end'] = 0 + + row_headers_model = {} # RowHeaders + row_headers_model['cell_id'] = 'rowHeader-2244-2262' + row_headers_model['location'] = location_model + row_headers_model['text'] = 'Statutory tax rate' + row_headers_model['text_normalized'] = 'Statutory tax rate' + row_headers_model['row_index_begin'] = 2 + row_headers_model['row_index_end'] = 2 + row_headers_model['column_index_begin'] = 0 + row_headers_model['column_index_end'] = 0 + + column_headers_model = {} # ColumnHeaders + column_headers_model['cell_id'] = 'colHeader-1050-1082' + column_headers_model['location'] = { 'foo': 'bar' } + column_headers_model['text'] = 'Three months ended September 30,' + column_headers_model['text_normalized'] = 'Three months ended September 30,' + column_headers_model['row_index_begin'] = 0 + column_headers_model['row_index_end'] = 0 + column_headers_model['column_index_begin'] = 1 + column_headers_model['column_index_end'] = 2 + + attribute_model = {} # Attribute + attribute_model['type'] = 'Currency' + attribute_model['text'] = 'testString' + attribute_model['location'] = location_model + + body_cells_model = {} # BodyCells + body_cells_model['cell_id'] = 'bodyCell-2450-2455' + body_cells_model['location'] = location_model + body_cells_model['text'] = '35.0%' + body_cells_model['row_index_begin'] = 2 + body_cells_model['row_index_end'] = 2 + body_cells_model['column_index_begin'] = 1 + body_cells_model['column_index_end'] = 1 + body_cells_model['row_header_ids'] = ['testString'] + body_cells_model['row_header_texts'] = ['testString'] + body_cells_model['row_header_texts_normalized'] = ['testString'] + body_cells_model['column_header_ids'] = ['testString'] + body_cells_model['column_header_texts'] = ['testString'] + body_cells_model['column_header_texts_normalized'] = ['testString'] + body_cells_model['attributes'] = [attribute_model] + + contexts_model = {} # Contexts + contexts_model['text'] = 'testString' + contexts_model['location'] = location_model + + key_model = {} # Key + key_model['cell_id'] = 'testString' + key_model['location'] = location_model + key_model['text'] = 'testString' + + value_model = {} # Value + value_model['cell_id'] = 'testString' + value_model['location'] = location_model + value_model['text'] = 'testString' + + key_value_pair_model = {} # KeyValuePair + key_value_pair_model['key'] = key_model + key_value_pair_model['value'] = [value_model] + + tables_model = {} # Tables + tables_model['location'] = location_model + tables_model['text'] = '...' + tables_model['section_title'] = section_title_model + tables_model['title'] = table_title_model + tables_model['table_headers'] = [table_headers_model] + tables_model['row_headers'] = [row_headers_model] + tables_model['column_headers'] = [column_headers_model] + tables_model['body_cells'] = [body_cells_model] + tables_model['contexts'] = [contexts_model] + tables_model['key_value_pairs'] = [key_value_pair_model] + + # Construct a json representation of a TableReturn model + table_return_model_json = {} + table_return_model_json['document'] = doc_info_model + table_return_model_json['model_id'] = 'testString' + table_return_model_json['model_version'] = 'testString' + table_return_model_json['tables'] = [tables_model] + + # Construct a model instance of TableReturn by calling from_dict on the json representation + table_return_model = TableReturn.from_dict(table_return_model_json) + assert table_return_model != False + + # Construct a model instance of TableReturn by calling from_dict on the json representation + table_return_model_dict = TableReturn.from_dict(table_return_model_json).__dict__ + table_return_model2 = TableReturn(**table_return_model_dict) + + # Verify the model instances are equivalent + assert table_return_model == table_return_model2 + + # Convert model instance back to dict and verify no loss of data + table_return_model_json2 = table_return_model.to_dict() + assert table_return_model_json2 == table_return_model_json + +class TestTableTitle(): + """ + Test Class for TableTitle + """ + + def test_table_title_serialization(self): + """ + Test serialization/deserialization for TableTitle + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a TableTitle model + table_title_model_json = {} + table_title_model_json['location'] = location_model + table_title_model_json['text'] = 'testString' + + # Construct a model instance of TableTitle by calling from_dict on the json representation + table_title_model = TableTitle.from_dict(table_title_model_json) + assert table_title_model != False + + # Construct a model instance of TableTitle by calling from_dict on the json representation + table_title_model_dict = TableTitle.from_dict(table_title_model_json).__dict__ + table_title_model2 = TableTitle(**table_title_model_dict) + + # Verify the model instances are equivalent + assert table_title_model == table_title_model2 + + # Convert model instance back to dict and verify no loss of data + table_title_model_json2 = table_title_model.to_dict() + assert table_title_model_json2 == table_title_model_json + +class TestTables(): + """ + Test Class for Tables + """ + + def test_tables_serialization(self): + """ + Test serialization/deserialization for Tables + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + section_title_model = {} # SectionTitle + section_title_model['text'] = 'testString' + section_title_model['location'] = location_model + + table_title_model = {} # TableTitle + table_title_model['location'] = location_model + table_title_model['text'] = 'testString' + + table_headers_model = {} # TableHeaders + table_headers_model['cell_id'] = 'testString' + table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['text'] = 'testString' + table_headers_model['row_index_begin'] = 26 + table_headers_model['row_index_end'] = 26 + table_headers_model['column_index_begin'] = 26 + table_headers_model['column_index_end'] = 26 + + row_headers_model = {} # RowHeaders + row_headers_model['cell_id'] = 'testString' + row_headers_model['location'] = location_model + row_headers_model['text'] = 'testString' + row_headers_model['text_normalized'] = 'testString' + row_headers_model['row_index_begin'] = 26 + row_headers_model['row_index_end'] = 26 + row_headers_model['column_index_begin'] = 26 + row_headers_model['column_index_end'] = 26 + + column_headers_model = {} # ColumnHeaders + column_headers_model['cell_id'] = 'testString' + column_headers_model['location'] = { 'foo': 'bar' } + column_headers_model['text'] = 'testString' + column_headers_model['text_normalized'] = 'testString' + column_headers_model['row_index_begin'] = 26 + column_headers_model['row_index_end'] = 26 + column_headers_model['column_index_begin'] = 26 + column_headers_model['column_index_end'] = 26 + + attribute_model = {} # Attribute + attribute_model['type'] = 'Currency' + attribute_model['text'] = 'testString' + attribute_model['location'] = location_model + + body_cells_model = {} # BodyCells + body_cells_model['cell_id'] = 'testString' + body_cells_model['location'] = location_model + body_cells_model['text'] = 'testString' + body_cells_model['row_index_begin'] = 26 + body_cells_model['row_index_end'] = 26 + body_cells_model['column_index_begin'] = 26 + body_cells_model['column_index_end'] = 26 + body_cells_model['row_header_ids'] = ['testString'] + body_cells_model['row_header_texts'] = ['testString'] + body_cells_model['row_header_texts_normalized'] = ['testString'] + body_cells_model['column_header_ids'] = ['testString'] + body_cells_model['column_header_texts'] = ['testString'] + body_cells_model['column_header_texts_normalized'] = ['testString'] + body_cells_model['attributes'] = [attribute_model] + + contexts_model = {} # Contexts + contexts_model['text'] = 'testString' + contexts_model['location'] = location_model + + key_model = {} # Key + key_model['cell_id'] = 'testString' + key_model['location'] = location_model + key_model['text'] = 'testString' + + value_model = {} # Value + value_model['cell_id'] = 'testString' + value_model['location'] = location_model + value_model['text'] = 'testString' + + key_value_pair_model = {} # KeyValuePair + key_value_pair_model['key'] = key_model + key_value_pair_model['value'] = [value_model] + + # Construct a json representation of a Tables model + tables_model_json = {} + tables_model_json['location'] = location_model + tables_model_json['text'] = 'testString' + tables_model_json['section_title'] = section_title_model + tables_model_json['title'] = table_title_model + tables_model_json['table_headers'] = [table_headers_model] + tables_model_json['row_headers'] = [row_headers_model] + tables_model_json['column_headers'] = [column_headers_model] + tables_model_json['body_cells'] = [body_cells_model] + tables_model_json['contexts'] = [contexts_model] + tables_model_json['key_value_pairs'] = [key_value_pair_model] + + # Construct a model instance of Tables by calling from_dict on the json representation + tables_model = Tables.from_dict(tables_model_json) + assert tables_model != False + + # Construct a model instance of Tables by calling from_dict on the json representation + tables_model_dict = Tables.from_dict(tables_model_json).__dict__ + tables_model2 = Tables(**tables_model_dict) + + # Verify the model instances are equivalent + assert tables_model == tables_model2 + + # Convert model instance back to dict and verify no loss of data + tables_model_json2 = tables_model.to_dict() + assert tables_model_json2 == tables_model_json + +class TestTerminationDates(): + """ + Test Class for TerminationDates + """ + + def test_termination_dates_serialization(self): + """ + Test serialization/deserialization for TerminationDates + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a TerminationDates model + termination_dates_model_json = {} + termination_dates_model_json['confidence_level'] = 'High' + termination_dates_model_json['text'] = 'testString' + termination_dates_model_json['text_normalized'] = 'testString' + termination_dates_model_json['provenance_ids'] = ['testString'] + termination_dates_model_json['location'] = location_model + + # Construct a model instance of TerminationDates by calling from_dict on the json representation + termination_dates_model = TerminationDates.from_dict(termination_dates_model_json) + assert termination_dates_model != False + + # Construct a model instance of TerminationDates by calling from_dict on the json representation + termination_dates_model_dict = TerminationDates.from_dict(termination_dates_model_json).__dict__ + termination_dates_model2 = TerminationDates(**termination_dates_model_dict) + + # Verify the model instances are equivalent + assert termination_dates_model == termination_dates_model2 + + # Convert model instance back to dict and verify no loss of data + termination_dates_model_json2 = termination_dates_model.to_dict() + assert termination_dates_model_json2 == termination_dates_model_json + +class TestTypeLabel(): + """ + Test Class for TypeLabel + """ + + def test_type_label_serialization(self): + """ + Test serialization/deserialization for TypeLabel + """ + + # Construct dict forms of any model objects needed in order to build this model. + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + # Construct a json representation of a TypeLabel model + type_label_model_json = {} + type_label_model_json['label'] = label_model + type_label_model_json['provenance_ids'] = ['testString'] + type_label_model_json['modification'] = 'added' + + # Construct a model instance of TypeLabel by calling from_dict on the json representation + type_label_model = TypeLabel.from_dict(type_label_model_json) + assert type_label_model != False + + # Construct a model instance of TypeLabel by calling from_dict on the json representation + type_label_model_dict = TypeLabel.from_dict(type_label_model_json).__dict__ + type_label_model2 = TypeLabel(**type_label_model_dict) + + # Verify the model instances are equivalent + assert type_label_model == type_label_model2 + + # Convert model instance back to dict and verify no loss of data + type_label_model_json2 = type_label_model.to_dict() + assert type_label_model_json2 == type_label_model_json + +class TestTypeLabelComparison(): + """ + Test Class for TypeLabelComparison + """ + + def test_type_label_comparison_serialization(self): + """ + Test serialization/deserialization for TypeLabelComparison + """ + + # Construct dict forms of any model objects needed in order to build this model. + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + # Construct a json representation of a TypeLabelComparison model + type_label_comparison_model_json = {} + type_label_comparison_model_json['label'] = label_model + + # Construct a model instance of TypeLabelComparison by calling from_dict on the json representation + type_label_comparison_model = TypeLabelComparison.from_dict(type_label_comparison_model_json) + assert type_label_comparison_model != False + + # Construct a model instance of TypeLabelComparison by calling from_dict on the json representation + type_label_comparison_model_dict = TypeLabelComparison.from_dict(type_label_comparison_model_json).__dict__ + type_label_comparison_model2 = TypeLabelComparison(**type_label_comparison_model_dict) + + # Verify the model instances are equivalent + assert type_label_comparison_model == type_label_comparison_model2 + + # Convert model instance back to dict and verify no loss of data + type_label_comparison_model_json2 = type_label_comparison_model.to_dict() + assert type_label_comparison_model_json2 == type_label_comparison_model_json + +class TestUnalignedElement(): + """ + Test Class for UnalignedElement + """ + + def test_unaligned_element_serialization(self): + """ + Test serialization/deserialization for UnalignedElement + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + type_label_comparison_model = {} # TypeLabelComparison + type_label_comparison_model['label'] = label_model + + category_comparison_model = {} # CategoryComparison + category_comparison_model['label'] = 'Amendments' + + attribute_model = {} # Attribute + attribute_model['type'] = 'Currency' + attribute_model['text'] = 'testString' + attribute_model['location'] = location_model + + # Construct a json representation of a UnalignedElement model + unaligned_element_model_json = {} + unaligned_element_model_json['document_label'] = 'testString' + unaligned_element_model_json['location'] = location_model + unaligned_element_model_json['text'] = 'testString' + unaligned_element_model_json['types'] = [type_label_comparison_model] + unaligned_element_model_json['categories'] = [category_comparison_model] + unaligned_element_model_json['attributes'] = [attribute_model] + + # Construct a model instance of UnalignedElement by calling from_dict on the json representation + unaligned_element_model = UnalignedElement.from_dict(unaligned_element_model_json) + assert unaligned_element_model != False + + # Construct a model instance of UnalignedElement by calling from_dict on the json representation + unaligned_element_model_dict = UnalignedElement.from_dict(unaligned_element_model_json).__dict__ + unaligned_element_model2 = UnalignedElement(**unaligned_element_model_dict) + + # Verify the model instances are equivalent + assert unaligned_element_model == unaligned_element_model2 + + # Convert model instance back to dict and verify no loss of data + unaligned_element_model_json2 = unaligned_element_model.to_dict() + assert unaligned_element_model_json2 == unaligned_element_model_json + +class TestUpdatedLabelsIn(): + """ + Test Class for UpdatedLabelsIn + """ + + def test_updated_labels_in_serialization(self): + """ + Test serialization/deserialization for UpdatedLabelsIn + """ + + # Construct dict forms of any model objects needed in order to build this model. + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + type_label_model = {} # TypeLabel + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'added' + + category_model = {} # Category + category_model['label'] = 'Amendments' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'added' + + # Construct a json representation of a UpdatedLabelsIn model + updated_labels_in_model_json = {} + updated_labels_in_model_json['types'] = [type_label_model] + updated_labels_in_model_json['categories'] = [category_model] + + # Construct a model instance of UpdatedLabelsIn by calling from_dict on the json representation + updated_labels_in_model = UpdatedLabelsIn.from_dict(updated_labels_in_model_json) + assert updated_labels_in_model != False + + # Construct a model instance of UpdatedLabelsIn by calling from_dict on the json representation + updated_labels_in_model_dict = UpdatedLabelsIn.from_dict(updated_labels_in_model_json).__dict__ + updated_labels_in_model2 = UpdatedLabelsIn(**updated_labels_in_model_dict) + + # Verify the model instances are equivalent + assert updated_labels_in_model == updated_labels_in_model2 + + # Convert model instance back to dict and verify no loss of data + updated_labels_in_model_json2 = updated_labels_in_model.to_dict() + assert updated_labels_in_model_json2 == updated_labels_in_model_json + +class TestUpdatedLabelsOut(): + """ + Test Class for UpdatedLabelsOut + """ + + def test_updated_labels_out_serialization(self): + """ + Test serialization/deserialization for UpdatedLabelsOut + """ + + # Construct dict forms of any model objects needed in order to build this model. + + label_model = {} # Label + label_model['nature'] = 'testString' + label_model['party'] = 'testString' + + type_label_model = {} # TypeLabel + type_label_model['label'] = label_model + type_label_model['provenance_ids'] = ['testString'] + type_label_model['modification'] = 'added' + + category_model = {} # Category + category_model['label'] = 'Amendments' + category_model['provenance_ids'] = ['testString'] + category_model['modification'] = 'added' + + # Construct a json representation of a UpdatedLabelsOut model + updated_labels_out_model_json = {} + updated_labels_out_model_json['types'] = [type_label_model] + updated_labels_out_model_json['categories'] = [category_model] + + # Construct a model instance of UpdatedLabelsOut by calling from_dict on the json representation + updated_labels_out_model = UpdatedLabelsOut.from_dict(updated_labels_out_model_json) + assert updated_labels_out_model != False + + # Construct a model instance of UpdatedLabelsOut by calling from_dict on the json representation + updated_labels_out_model_dict = UpdatedLabelsOut.from_dict(updated_labels_out_model_json).__dict__ + updated_labels_out_model2 = UpdatedLabelsOut(**updated_labels_out_model_dict) + + # Verify the model instances are equivalent + assert updated_labels_out_model == updated_labels_out_model2 + + # Convert model instance back to dict and verify no loss of data + updated_labels_out_model_json2 = updated_labels_out_model.to_dict() + assert updated_labels_out_model_json2 == updated_labels_out_model_json + +class TestValue(): + """ + Test Class for Value + """ + + def test_value_serialization(self): + """ + Test serialization/deserialization for Value + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['begin'] = 26 + location_model['end'] = 26 + + # Construct a json representation of a Value model + value_model_json = {} + value_model_json['cell_id'] = 'testString' + value_model_json['location'] = location_model + value_model_json['text'] = 'testString' + + # Construct a model instance of Value by calling from_dict on the json representation + value_model = Value.from_dict(value_model_json) + assert value_model != False + + # Construct a model instance of Value by calling from_dict on the json representation + value_model_dict = Value.from_dict(value_model_json).__dict__ + value_model2 = Value(**value_model_dict) + + # Verify the model instances are equivalent + assert value_model == value_model2 + + # Convert model instance back to dict and verify no loss of data + value_model_json2 = value_model.to_dict() + assert value_model_json2 == value_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 9d5dff330..601726d0f 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -13,443 +13,512 @@ # See the License for the specific language governing permissions and # limitations under the License. -from datetime import datetime +""" +Unit Tests for DiscoveryV1 +""" + +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect +import io import json import pytest +import re +import requests import responses import tempfile -import ibm_watson.discovery_v1 +import urllib from ibm_watson.discovery_v1 import * +version = 'testString' + +service = DiscoveryV1( + authenticator=NoAuthAuthenticator(), + version=version + ) + base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: Environments ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_environment -#----------------------------------------------------------------------------- class TestCreateEnvironment(): + """ + Test Class for create_environment + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_environment_response(self): - body = self.construct_full_body() - response = fake_response_Environment_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_environment_all_params(self): + """ + create_environment() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + name = 'testString' + description = 'testString' + size = 'LT' + + # Invoke method + response = service.create_environment( + name, + description=description, + size=size, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['size'] == 'LT' + + + @responses.activate + def test_create_environment_value_error(self): + """ + test_create_environment_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_environment_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Environment_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + name = 'testString' + description = 'testString' + size = 'LT' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_environment(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_environment_empty(self): - check_empty_required_params(self, fake_response_Environment_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments' - 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=201, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.create_environment(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"name": "string1", "description": "string1", "size": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body.update({"name": "string1", "description": "string1", "size": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_environments -#----------------------------------------------------------------------------- class TestListEnvironments(): + """ + Test Class for list_environments + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_environments_response(self): - body = self.construct_full_body() - response = fake_response_ListEnvironmentsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_environments_all_params(self): + """ + list_environments() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments') + mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_environments_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ListEnvironmentsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + name = 'testString' - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_environments_empty(self): - check_empty_response(self) + # Invoke method + response = service.list_environments( + name=name, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'name={}'.format(name) in query_string - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_environments_required_params(self): + """ + test_list_environments_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments') + mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.list_environments(**body) - return output - - def construct_full_body(self): - body = dict() - body['name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_environment -#----------------------------------------------------------------------------- -class TestGetEnvironment(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_environment_response(self): - body = self.construct_full_body() - response = fake_response_Environment_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Invoke method + response = service.list_environments() - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_environment_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Environment_json - send_request(self, body, response) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_environment_empty(self): - check_empty_required_params(self, fake_response_Environment_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_environments_value_error(self): + """ + test_list_environments_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments') + mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_environments(**req_copy) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + +class TestGetEnvironment(): + """ + Test Class for get_environment + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_environment_all_params(self): + """ + get_environment() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_environment(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_environment -#----------------------------------------------------------------------------- -class TestUpdateEnvironment(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_environment_response(self): - body = self.construct_full_body() - response = fake_response_Environment_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_environment_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Environment_json - send_request(self, body, response) + # Invoke method + response = service.get_environment( + environment_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_environment_empty(self): - check_empty_required_params(self, fake_response_Environment_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_environment_value_error(self): + """ + test_get_environment_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_environment(**req_copy) + + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url +class TestUpdateEnvironment(): + """ + Test Class for update_environment + """ - def add_mock_response(self, url, response): + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_environment_all_params(self): + """ + update_environment() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.update_environment(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "size": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "size": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_environment -#----------------------------------------------------------------------------- -class TestDeleteEnvironment(): + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + name = 'testString' + description = 'testString' + size = 'S' + + # Invoke method + response = service.update_environment( + environment_id, + name=name, + description=description, + size=size, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['size'] == 'S' + + + @responses.activate + def test_update_environment_value_error(self): + """ + test_update_environment_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_environment_response(self): - body = self.construct_full_body() - response = fake_response_DeleteEnvironmentResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + name = 'testString' + description = 'testString' + size = 'S' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_environment_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DeleteEnvironmentResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_environment(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_environment_empty(self): - check_empty_required_params(self, fake_response_DeleteEnvironmentResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): +class TestDeleteEnvironment(): + """ + Test Class for delete_environment + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_environment_all_params(self): + """ + delete_environment() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString') + mock_response = '{"environment_id": "environment_id", "status": "deleted"}' responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_environment(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_fields -#----------------------------------------------------------------------------- -class TestListFields(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_fields_response(self): - body = self.construct_full_body() - response = fake_response_ListCollectionFieldsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_fields_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ListCollectionFieldsResponse_json - send_request(self, body, response) + # Invoke method + response = service.delete_environment( + environment_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_fields_empty(self): - check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_environment_value_error(self): + """ + test_delete_environment_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString') + mock_response = '{"environment_id": "environment_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_environment(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/fields'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): +class TestListFields(): + """ + Test Class for list_fields + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_fields_all_params(self): + """ + list_fields() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.list_fields(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_ids'] = [] - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_ids'] = [] - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_ids = ['testString'] + + # Invoke method + response = service.list_fields( + environment_id, + collection_ids, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string + + + @responses.activate + def test_list_fields_value_error(self): + """ + test_list_fields_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_ids = ['testString'] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_ids": collection_ids, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_fields(**req_copy) + # endregion @@ -462,365 +531,1198 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_configuration -#----------------------------------------------------------------------------- class TestCreateConfiguration(): + """ + Test Class for create_configuration + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_configuration_response(self): - body = self.construct_full_body() - response = fake_response_Configuration_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_create_configuration_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Configuration_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_configuration_all_params(self): + """ + create_configuration() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/configurations') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a FontSetting model + font_setting_model = {} + font_setting_model['level'] = 38 + font_setting_model['min_size'] = 38 + font_setting_model['max_size'] = 38 + font_setting_model['bold'] = True + font_setting_model['italic'] = True + font_setting_model['name'] = 'testString' + + # Construct a dict representation of a PdfHeadingDetection model + pdf_heading_detection_model = {} + pdf_heading_detection_model['fonts'] = [font_setting_model] + + # Construct a dict representation of a PdfSettings model + pdf_settings_model = {} + pdf_settings_model['heading'] = pdf_heading_detection_model + + # Construct a dict representation of a WordStyle model + word_style_model = {} + word_style_model['level'] = 38 + word_style_model['names'] = ['testString'] + + # Construct a dict representation of a WordHeadingDetection model + word_heading_detection_model = {} + word_heading_detection_model['fonts'] = [font_setting_model] + word_heading_detection_model['styles'] = [word_style_model] + + # Construct a dict representation of a WordSettings model + word_settings_model = {} + word_settings_model['heading'] = word_heading_detection_model + + # Construct a dict representation of a XPathPatterns model + x_path_patterns_model = {} + x_path_patterns_model['xpaths'] = ['testString'] + + # Construct a dict representation of a HtmlSettings model + html_settings_model = {} + html_settings_model['exclude_tags_completely'] = ['testString'] + html_settings_model['exclude_tags_keep_content'] = ['testString'] + html_settings_model['keep_content'] = x_path_patterns_model + html_settings_model['exclude_content'] = x_path_patterns_model + html_settings_model['keep_tag_attributes'] = ['testString'] + html_settings_model['exclude_tag_attributes'] = ['testString'] + + # Construct a dict representation of a SegmentSettings model + segment_settings_model = {} + segment_settings_model['enabled'] = True + segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['annotated_fields'] = ['testString'] + + # Construct a dict representation of a NormalizationOperation model + normalization_operation_model = {} + normalization_operation_model['operation'] = 'copy' + normalization_operation_model['source_field'] = 'testString' + normalization_operation_model['destination_field'] = 'testString' + + # Construct a dict representation of a Conversions model + conversions_model = {} + conversions_model['pdf'] = pdf_settings_model + conversions_model['word'] = word_settings_model + conversions_model['html'] = html_settings_model + conversions_model['segment'] = segment_settings_model + conversions_model['json_normalizations'] = [normalization_operation_model] + conversions_model['image_text_recognition'] = True + + # Construct a dict representation of a NluEnrichmentKeywords model + nlu_enrichment_keywords_model = {} + nlu_enrichment_keywords_model['sentiment'] = True + nlu_enrichment_keywords_model['emotion'] = True + nlu_enrichment_keywords_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentEntities model + nlu_enrichment_entities_model = {} + nlu_enrichment_entities_model['sentiment'] = True + nlu_enrichment_entities_model['emotion'] = True + nlu_enrichment_entities_model['limit'] = 38 + nlu_enrichment_entities_model['mentions'] = True + nlu_enrichment_entities_model['mention_types'] = True + nlu_enrichment_entities_model['sentence_locations'] = True + nlu_enrichment_entities_model['model'] = 'testString' + + # Construct a dict representation of a NluEnrichmentSentiment model + nlu_enrichment_sentiment_model = {} + nlu_enrichment_sentiment_model['document'] = True + nlu_enrichment_sentiment_model['targets'] = ['testString'] + + # Construct a dict representation of a NluEnrichmentEmotion model + nlu_enrichment_emotion_model = {} + nlu_enrichment_emotion_model['document'] = True + nlu_enrichment_emotion_model['targets'] = ['testString'] + + # Construct a dict representation of a NluEnrichmentSemanticRoles model + nlu_enrichment_semantic_roles_model = {} + nlu_enrichment_semantic_roles_model['entities'] = True + nlu_enrichment_semantic_roles_model['keywords'] = True + nlu_enrichment_semantic_roles_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentRelations model + nlu_enrichment_relations_model = {} + nlu_enrichment_relations_model['model'] = 'testString' + + # Construct a dict representation of a NluEnrichmentConcepts model + nlu_enrichment_concepts_model = {} + nlu_enrichment_concepts_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentFeatures model + nlu_enrichment_features_model = {} + nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model + nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model + nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model + nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model + nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model + nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model + nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model + + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['features'] = nlu_enrichment_features_model + enrichment_options_model['language'] = 'ar' + enrichment_options_model['model'] = 'testString' + + # Construct a dict representation of a Enrichment model + enrichment_model = {} + enrichment_model['description'] = 'testString' + enrichment_model['destination_field'] = 'testString' + enrichment_model['source_field'] = 'testString' + enrichment_model['overwrite'] = True + enrichment_model['enrichment'] = 'testString' + enrichment_model['ignore_downstream_errors'] = True + enrichment_model['options'] = enrichment_options_model + + # Construct a dict representation of a SourceSchedule model + source_schedule_model = {} + source_schedule_model['enabled'] = True + source_schedule_model['time_zone'] = 'testString' + source_schedule_model['frequency'] = 'daily' + + # Construct a dict representation of a SourceOptionsFolder model + source_options_folder_model = {} + source_options_folder_model['owner_user_id'] = 'testString' + source_options_folder_model['folder_id'] = 'testString' + source_options_folder_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsObject model + source_options_object_model = {} + source_options_object_model['name'] = 'testString' + source_options_object_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsSiteColl model + source_options_site_coll_model = {} + source_options_site_coll_model['site_collection_path'] = 'testString' + source_options_site_coll_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsWebCrawl model + source_options_web_crawl_model = {} + source_options_web_crawl_model['url'] = 'testString' + source_options_web_crawl_model['limit_to_starting_hosts'] = True + source_options_web_crawl_model['crawl_speed'] = 'gentle' + source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['maximum_hops'] = 38 + source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['blacklist'] = ['testString'] + + # Construct a dict representation of a SourceOptionsBuckets model + source_options_buckets_model = {} + source_options_buckets_model['name'] = 'testString' + source_options_buckets_model['limit'] = 38 + + # Construct a dict representation of a SourceOptions model + source_options_model = {} + source_options_model['folders'] = [source_options_folder_model] + source_options_model['objects'] = [source_options_object_model] + source_options_model['site_collections'] = [source_options_site_coll_model] + source_options_model['urls'] = [source_options_web_crawl_model] + source_options_model['buckets'] = [source_options_buckets_model] + source_options_model['crawl_all_buckets'] = True + + # Construct a dict representation of a Source model + source_model = {} + source_model['type'] = 'box' + source_model['credential_id'] = 'testString' + source_model['schedule'] = source_schedule_model + source_model['options'] = source_options_model + + # Set up parameter values + environment_id = 'testString' + name = 'testString' + description = 'testString' + conversions = conversions_model + enrichments = [enrichment_model] + normalizations = [normalization_operation_model] + source = source_model + + # Invoke method + response = service.create_configuration( + environment_id, + name, + description=description, + conversions=conversions, + enrichments=enrichments, + normalizations=normalizations, + source=source, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['conversions'] == conversions_model + assert req_body['enrichments'] == [enrichment_model] + assert req_body['normalizations'] == [normalization_operation_model] + assert req_body['source'] == source_model + + + @responses.activate + def test_create_configuration_value_error(self): + """ + test_create_configuration_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/configurations') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a FontSetting model + font_setting_model = {} + font_setting_model['level'] = 38 + font_setting_model['min_size'] = 38 + font_setting_model['max_size'] = 38 + font_setting_model['bold'] = True + font_setting_model['italic'] = True + font_setting_model['name'] = 'testString' + + # Construct a dict representation of a PdfHeadingDetection model + pdf_heading_detection_model = {} + pdf_heading_detection_model['fonts'] = [font_setting_model] + + # Construct a dict representation of a PdfSettings model + pdf_settings_model = {} + pdf_settings_model['heading'] = pdf_heading_detection_model + + # Construct a dict representation of a WordStyle model + word_style_model = {} + word_style_model['level'] = 38 + word_style_model['names'] = ['testString'] + + # Construct a dict representation of a WordHeadingDetection model + word_heading_detection_model = {} + word_heading_detection_model['fonts'] = [font_setting_model] + word_heading_detection_model['styles'] = [word_style_model] + + # Construct a dict representation of a WordSettings model + word_settings_model = {} + word_settings_model['heading'] = word_heading_detection_model + + # Construct a dict representation of a XPathPatterns model + x_path_patterns_model = {} + x_path_patterns_model['xpaths'] = ['testString'] + + # Construct a dict representation of a HtmlSettings model + html_settings_model = {} + html_settings_model['exclude_tags_completely'] = ['testString'] + html_settings_model['exclude_tags_keep_content'] = ['testString'] + html_settings_model['keep_content'] = x_path_patterns_model + html_settings_model['exclude_content'] = x_path_patterns_model + html_settings_model['keep_tag_attributes'] = ['testString'] + html_settings_model['exclude_tag_attributes'] = ['testString'] + + # Construct a dict representation of a SegmentSettings model + segment_settings_model = {} + segment_settings_model['enabled'] = True + segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['annotated_fields'] = ['testString'] + + # Construct a dict representation of a NormalizationOperation model + normalization_operation_model = {} + normalization_operation_model['operation'] = 'copy' + normalization_operation_model['source_field'] = 'testString' + normalization_operation_model['destination_field'] = 'testString' + + # Construct a dict representation of a Conversions model + conversions_model = {} + conversions_model['pdf'] = pdf_settings_model + conversions_model['word'] = word_settings_model + conversions_model['html'] = html_settings_model + conversions_model['segment'] = segment_settings_model + conversions_model['json_normalizations'] = [normalization_operation_model] + conversions_model['image_text_recognition'] = True + + # Construct a dict representation of a NluEnrichmentKeywords model + nlu_enrichment_keywords_model = {} + nlu_enrichment_keywords_model['sentiment'] = True + nlu_enrichment_keywords_model['emotion'] = True + nlu_enrichment_keywords_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentEntities model + nlu_enrichment_entities_model = {} + nlu_enrichment_entities_model['sentiment'] = True + nlu_enrichment_entities_model['emotion'] = True + nlu_enrichment_entities_model['limit'] = 38 + nlu_enrichment_entities_model['mentions'] = True + nlu_enrichment_entities_model['mention_types'] = True + nlu_enrichment_entities_model['sentence_locations'] = True + nlu_enrichment_entities_model['model'] = 'testString' + + # Construct a dict representation of a NluEnrichmentSentiment model + nlu_enrichment_sentiment_model = {} + nlu_enrichment_sentiment_model['document'] = True + nlu_enrichment_sentiment_model['targets'] = ['testString'] + + # Construct a dict representation of a NluEnrichmentEmotion model + nlu_enrichment_emotion_model = {} + nlu_enrichment_emotion_model['document'] = True + nlu_enrichment_emotion_model['targets'] = ['testString'] + + # Construct a dict representation of a NluEnrichmentSemanticRoles model + nlu_enrichment_semantic_roles_model = {} + nlu_enrichment_semantic_roles_model['entities'] = True + nlu_enrichment_semantic_roles_model['keywords'] = True + nlu_enrichment_semantic_roles_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentRelations model + nlu_enrichment_relations_model = {} + nlu_enrichment_relations_model['model'] = 'testString' + + # Construct a dict representation of a NluEnrichmentConcepts model + nlu_enrichment_concepts_model = {} + nlu_enrichment_concepts_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentFeatures model + nlu_enrichment_features_model = {} + nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model + nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model + nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model + nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model + nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model + nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model + nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model + + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['features'] = nlu_enrichment_features_model + enrichment_options_model['language'] = 'ar' + enrichment_options_model['model'] = 'testString' + + # Construct a dict representation of a Enrichment model + enrichment_model = {} + enrichment_model['description'] = 'testString' + enrichment_model['destination_field'] = 'testString' + enrichment_model['source_field'] = 'testString' + enrichment_model['overwrite'] = True + enrichment_model['enrichment'] = 'testString' + enrichment_model['ignore_downstream_errors'] = True + enrichment_model['options'] = enrichment_options_model + + # Construct a dict representation of a SourceSchedule model + source_schedule_model = {} + source_schedule_model['enabled'] = True + source_schedule_model['time_zone'] = 'testString' + source_schedule_model['frequency'] = 'daily' + + # Construct a dict representation of a SourceOptionsFolder model + source_options_folder_model = {} + source_options_folder_model['owner_user_id'] = 'testString' + source_options_folder_model['folder_id'] = 'testString' + source_options_folder_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsObject model + source_options_object_model = {} + source_options_object_model['name'] = 'testString' + source_options_object_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsSiteColl model + source_options_site_coll_model = {} + source_options_site_coll_model['site_collection_path'] = 'testString' + source_options_site_coll_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsWebCrawl model + source_options_web_crawl_model = {} + source_options_web_crawl_model['url'] = 'testString' + source_options_web_crawl_model['limit_to_starting_hosts'] = True + source_options_web_crawl_model['crawl_speed'] = 'gentle' + source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['maximum_hops'] = 38 + source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['blacklist'] = ['testString'] + + # Construct a dict representation of a SourceOptionsBuckets model + source_options_buckets_model = {} + source_options_buckets_model['name'] = 'testString' + source_options_buckets_model['limit'] = 38 + + # Construct a dict representation of a SourceOptions model + source_options_model = {} + source_options_model['folders'] = [source_options_folder_model] + source_options_model['objects'] = [source_options_object_model] + source_options_model['site_collections'] = [source_options_site_coll_model] + source_options_model['urls'] = [source_options_web_crawl_model] + source_options_model['buckets'] = [source_options_buckets_model] + source_options_model['crawl_all_buckets'] = True + + # Construct a dict representation of a Source model + source_model = {} + source_model['type'] = 'box' + source_model['credential_id'] = 'testString' + source_model['schedule'] = source_schedule_model + source_model['options'] = source_options_model + + # Set up parameter values + environment_id = 'testString' + name = 'testString' + description = 'testString' + conversions = conversions_model + enrichments = [enrichment_model] + normalizations = [normalization_operation_model] + source = source_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_configuration(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_configuration_empty(self): - check_empty_required_params(self, fake_response_Configuration_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations'.format(body['environment_id']) - 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=201, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.create_configuration(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_configurations -#----------------------------------------------------------------------------- class TestListConfigurations(): + """ + Test Class for list_configurations + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_configurations_response(self): - body = self.construct_full_body() - response = fake_response_ListConfigurationsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_configurations_all_params(self): + """ + list_configurations() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/configurations') + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + name = 'testString' + + # Invoke method + response = service.list_configurations( + environment_id, + name=name, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'name={}'.format(name) in query_string + + + @responses.activate + def test_list_configurations_required_params(self): + """ + test_list_configurations_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/configurations') + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_configurations_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ListConfigurationsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_configurations_empty(self): - check_empty_required_params(self, fake_response_ListConfigurationsResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + # Invoke method + response = service.list_configurations( + environment_id, + headers={} + ) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.list_configurations(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_configuration -#----------------------------------------------------------------------------- -class TestGetConfiguration(): - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_configuration_response(self): - body = self.construct_full_body() - response = fake_response_Configuration_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_configurations_value_error(self): + """ + test_list_configurations_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/configurations') + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_configuration_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Configuration_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_configuration_empty(self): - check_empty_required_params(self, fake_response_Configuration_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_configurations(**req_copy) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + +class TestGetConfiguration(): + """ + Test Class for get_configuration + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_configuration_all_params(self): + """ + get_configuration() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_configuration(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['configuration_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['configuration_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_configuration -#----------------------------------------------------------------------------- -class TestUpdateConfiguration(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_configuration_response(self): - body = self.construct_full_body() - response = fake_response_Configuration_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + configuration_id = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_configuration_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Configuration_json - send_request(self, body, response) + # Invoke method + response = service.get_configuration( + environment_id, + configuration_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_configuration_empty(self): - check_empty_required_params(self, fake_response_Configuration_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_configuration_value_error(self): + """ + test_get_configuration_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + configuration_id = 'testString' - def add_mock_response(self, url, response): + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "configuration_id": configuration_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_configuration(**req_copy) + + + +class TestUpdateConfiguration(): + """ + Test Class for update_configuration + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_configuration_all_params(self): + """ + update_configuration() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a FontSetting model + font_setting_model = {} + font_setting_model['level'] = 38 + font_setting_model['min_size'] = 38 + font_setting_model['max_size'] = 38 + font_setting_model['bold'] = True + font_setting_model['italic'] = True + font_setting_model['name'] = 'testString' + + # Construct a dict representation of a PdfHeadingDetection model + pdf_heading_detection_model = {} + pdf_heading_detection_model['fonts'] = [font_setting_model] + + # Construct a dict representation of a PdfSettings model + pdf_settings_model = {} + pdf_settings_model['heading'] = pdf_heading_detection_model + + # Construct a dict representation of a WordStyle model + word_style_model = {} + word_style_model['level'] = 38 + word_style_model['names'] = ['testString'] + + # Construct a dict representation of a WordHeadingDetection model + word_heading_detection_model = {} + word_heading_detection_model['fonts'] = [font_setting_model] + word_heading_detection_model['styles'] = [word_style_model] + + # Construct a dict representation of a WordSettings model + word_settings_model = {} + word_settings_model['heading'] = word_heading_detection_model + + # Construct a dict representation of a XPathPatterns model + x_path_patterns_model = {} + x_path_patterns_model['xpaths'] = ['testString'] + + # Construct a dict representation of a HtmlSettings model + html_settings_model = {} + html_settings_model['exclude_tags_completely'] = ['testString'] + html_settings_model['exclude_tags_keep_content'] = ['testString'] + html_settings_model['keep_content'] = x_path_patterns_model + html_settings_model['exclude_content'] = x_path_patterns_model + html_settings_model['keep_tag_attributes'] = ['testString'] + html_settings_model['exclude_tag_attributes'] = ['testString'] + + # Construct a dict representation of a SegmentSettings model + segment_settings_model = {} + segment_settings_model['enabled'] = True + segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['annotated_fields'] = ['testString'] + + # Construct a dict representation of a NormalizationOperation model + normalization_operation_model = {} + normalization_operation_model['operation'] = 'copy' + normalization_operation_model['source_field'] = 'testString' + normalization_operation_model['destination_field'] = 'testString' + + # Construct a dict representation of a Conversions model + conversions_model = {} + conversions_model['pdf'] = pdf_settings_model + conversions_model['word'] = word_settings_model + conversions_model['html'] = html_settings_model + conversions_model['segment'] = segment_settings_model + conversions_model['json_normalizations'] = [normalization_operation_model] + conversions_model['image_text_recognition'] = True + + # Construct a dict representation of a NluEnrichmentKeywords model + nlu_enrichment_keywords_model = {} + nlu_enrichment_keywords_model['sentiment'] = True + nlu_enrichment_keywords_model['emotion'] = True + nlu_enrichment_keywords_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentEntities model + nlu_enrichment_entities_model = {} + nlu_enrichment_entities_model['sentiment'] = True + nlu_enrichment_entities_model['emotion'] = True + nlu_enrichment_entities_model['limit'] = 38 + nlu_enrichment_entities_model['mentions'] = True + nlu_enrichment_entities_model['mention_types'] = True + nlu_enrichment_entities_model['sentence_locations'] = True + nlu_enrichment_entities_model['model'] = 'testString' + + # Construct a dict representation of a NluEnrichmentSentiment model + nlu_enrichment_sentiment_model = {} + nlu_enrichment_sentiment_model['document'] = True + nlu_enrichment_sentiment_model['targets'] = ['testString'] + + # Construct a dict representation of a NluEnrichmentEmotion model + nlu_enrichment_emotion_model = {} + nlu_enrichment_emotion_model['document'] = True + nlu_enrichment_emotion_model['targets'] = ['testString'] + + # Construct a dict representation of a NluEnrichmentSemanticRoles model + nlu_enrichment_semantic_roles_model = {} + nlu_enrichment_semantic_roles_model['entities'] = True + nlu_enrichment_semantic_roles_model['keywords'] = True + nlu_enrichment_semantic_roles_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentRelations model + nlu_enrichment_relations_model = {} + nlu_enrichment_relations_model['model'] = 'testString' + + # Construct a dict representation of a NluEnrichmentConcepts model + nlu_enrichment_concepts_model = {} + nlu_enrichment_concepts_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentFeatures model + nlu_enrichment_features_model = {} + nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model + nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model + nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model + nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model + nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model + nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model + nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model + + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['features'] = nlu_enrichment_features_model + enrichment_options_model['language'] = 'ar' + enrichment_options_model['model'] = 'testString' + + # Construct a dict representation of a Enrichment model + enrichment_model = {} + enrichment_model['description'] = 'testString' + enrichment_model['destination_field'] = 'testString' + enrichment_model['source_field'] = 'testString' + enrichment_model['overwrite'] = True + enrichment_model['enrichment'] = 'testString' + enrichment_model['ignore_downstream_errors'] = True + enrichment_model['options'] = enrichment_options_model + + # Construct a dict representation of a SourceSchedule model + source_schedule_model = {} + source_schedule_model['enabled'] = True + source_schedule_model['time_zone'] = 'testString' + source_schedule_model['frequency'] = 'daily' + + # Construct a dict representation of a SourceOptionsFolder model + source_options_folder_model = {} + source_options_folder_model['owner_user_id'] = 'testString' + source_options_folder_model['folder_id'] = 'testString' + source_options_folder_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsObject model + source_options_object_model = {} + source_options_object_model['name'] = 'testString' + source_options_object_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsSiteColl model + source_options_site_coll_model = {} + source_options_site_coll_model['site_collection_path'] = 'testString' + source_options_site_coll_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsWebCrawl model + source_options_web_crawl_model = {} + source_options_web_crawl_model['url'] = 'testString' + source_options_web_crawl_model['limit_to_starting_hosts'] = True + source_options_web_crawl_model['crawl_speed'] = 'gentle' + source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['maximum_hops'] = 38 + source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['blacklist'] = ['testString'] + + # Construct a dict representation of a SourceOptionsBuckets model + source_options_buckets_model = {} + source_options_buckets_model['name'] = 'testString' + source_options_buckets_model['limit'] = 38 + + # Construct a dict representation of a SourceOptions model + source_options_model = {} + source_options_model['folders'] = [source_options_folder_model] + source_options_model['objects'] = [source_options_object_model] + source_options_model['site_collections'] = [source_options_site_coll_model] + source_options_model['urls'] = [source_options_web_crawl_model] + source_options_model['buckets'] = [source_options_buckets_model] + source_options_model['crawl_all_buckets'] = True + + # Construct a dict representation of a Source model + source_model = {} + source_model['type'] = 'box' + source_model['credential_id'] = 'testString' + source_model['schedule'] = source_schedule_model + source_model['options'] = source_options_model + + # Set up parameter values + environment_id = 'testString' + configuration_id = 'testString' + name = 'testString' + description = 'testString' + conversions = conversions_model + enrichments = [enrichment_model] + normalizations = [normalization_operation_model] + source = source_model + + # Invoke method + response = service.update_configuration( + environment_id, + configuration_id, + name, + description=description, + conversions=conversions, + enrichments=enrichments, + normalizations=normalizations, + source=source, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['conversions'] == conversions_model + assert req_body['enrichments'] == [enrichment_model] + assert req_body['normalizations'] == [normalization_operation_model] + assert req_body['source'] == source_model + + + @responses.activate + def test_update_configuration_value_error(self): + """ + test_update_configuration_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.update_configuration(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['configuration_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['configuration_id'] = "string1" - body.update({"name": "string1", "description": "string1", "conversions": Conversions._from_dict(json.loads("""{"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}""")), "enrichments": [], "normalizations": [], "source": Source._from_dict(json.loads("""{"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}""")), }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_configuration -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a FontSetting model + font_setting_model = {} + font_setting_model['level'] = 38 + font_setting_model['min_size'] = 38 + font_setting_model['max_size'] = 38 + font_setting_model['bold'] = True + font_setting_model['italic'] = True + font_setting_model['name'] = 'testString' + + # Construct a dict representation of a PdfHeadingDetection model + pdf_heading_detection_model = {} + pdf_heading_detection_model['fonts'] = [font_setting_model] + + # Construct a dict representation of a PdfSettings model + pdf_settings_model = {} + pdf_settings_model['heading'] = pdf_heading_detection_model + + # Construct a dict representation of a WordStyle model + word_style_model = {} + word_style_model['level'] = 38 + word_style_model['names'] = ['testString'] + + # Construct a dict representation of a WordHeadingDetection model + word_heading_detection_model = {} + word_heading_detection_model['fonts'] = [font_setting_model] + word_heading_detection_model['styles'] = [word_style_model] + + # Construct a dict representation of a WordSettings model + word_settings_model = {} + word_settings_model['heading'] = word_heading_detection_model + + # Construct a dict representation of a XPathPatterns model + x_path_patterns_model = {} + x_path_patterns_model['xpaths'] = ['testString'] + + # Construct a dict representation of a HtmlSettings model + html_settings_model = {} + html_settings_model['exclude_tags_completely'] = ['testString'] + html_settings_model['exclude_tags_keep_content'] = ['testString'] + html_settings_model['keep_content'] = x_path_patterns_model + html_settings_model['exclude_content'] = x_path_patterns_model + html_settings_model['keep_tag_attributes'] = ['testString'] + html_settings_model['exclude_tag_attributes'] = ['testString'] + + # Construct a dict representation of a SegmentSettings model + segment_settings_model = {} + segment_settings_model['enabled'] = True + segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['annotated_fields'] = ['testString'] + + # Construct a dict representation of a NormalizationOperation model + normalization_operation_model = {} + normalization_operation_model['operation'] = 'copy' + normalization_operation_model['source_field'] = 'testString' + normalization_operation_model['destination_field'] = 'testString' + + # Construct a dict representation of a Conversions model + conversions_model = {} + conversions_model['pdf'] = pdf_settings_model + conversions_model['word'] = word_settings_model + conversions_model['html'] = html_settings_model + conversions_model['segment'] = segment_settings_model + conversions_model['json_normalizations'] = [normalization_operation_model] + conversions_model['image_text_recognition'] = True + + # Construct a dict representation of a NluEnrichmentKeywords model + nlu_enrichment_keywords_model = {} + nlu_enrichment_keywords_model['sentiment'] = True + nlu_enrichment_keywords_model['emotion'] = True + nlu_enrichment_keywords_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentEntities model + nlu_enrichment_entities_model = {} + nlu_enrichment_entities_model['sentiment'] = True + nlu_enrichment_entities_model['emotion'] = True + nlu_enrichment_entities_model['limit'] = 38 + nlu_enrichment_entities_model['mentions'] = True + nlu_enrichment_entities_model['mention_types'] = True + nlu_enrichment_entities_model['sentence_locations'] = True + nlu_enrichment_entities_model['model'] = 'testString' + + # Construct a dict representation of a NluEnrichmentSentiment model + nlu_enrichment_sentiment_model = {} + nlu_enrichment_sentiment_model['document'] = True + nlu_enrichment_sentiment_model['targets'] = ['testString'] + + # Construct a dict representation of a NluEnrichmentEmotion model + nlu_enrichment_emotion_model = {} + nlu_enrichment_emotion_model['document'] = True + nlu_enrichment_emotion_model['targets'] = ['testString'] + + # Construct a dict representation of a NluEnrichmentSemanticRoles model + nlu_enrichment_semantic_roles_model = {} + nlu_enrichment_semantic_roles_model['entities'] = True + nlu_enrichment_semantic_roles_model['keywords'] = True + nlu_enrichment_semantic_roles_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentRelations model + nlu_enrichment_relations_model = {} + nlu_enrichment_relations_model['model'] = 'testString' + + # Construct a dict representation of a NluEnrichmentConcepts model + nlu_enrichment_concepts_model = {} + nlu_enrichment_concepts_model['limit'] = 38 + + # Construct a dict representation of a NluEnrichmentFeatures model + nlu_enrichment_features_model = {} + nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model + nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model + nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model + nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model + nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model + nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model + nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model + + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['features'] = nlu_enrichment_features_model + enrichment_options_model['language'] = 'ar' + enrichment_options_model['model'] = 'testString' + + # Construct a dict representation of a Enrichment model + enrichment_model = {} + enrichment_model['description'] = 'testString' + enrichment_model['destination_field'] = 'testString' + enrichment_model['source_field'] = 'testString' + enrichment_model['overwrite'] = True + enrichment_model['enrichment'] = 'testString' + enrichment_model['ignore_downstream_errors'] = True + enrichment_model['options'] = enrichment_options_model + + # Construct a dict representation of a SourceSchedule model + source_schedule_model = {} + source_schedule_model['enabled'] = True + source_schedule_model['time_zone'] = 'testString' + source_schedule_model['frequency'] = 'daily' + + # Construct a dict representation of a SourceOptionsFolder model + source_options_folder_model = {} + source_options_folder_model['owner_user_id'] = 'testString' + source_options_folder_model['folder_id'] = 'testString' + source_options_folder_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsObject model + source_options_object_model = {} + source_options_object_model['name'] = 'testString' + source_options_object_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsSiteColl model + source_options_site_coll_model = {} + source_options_site_coll_model['site_collection_path'] = 'testString' + source_options_site_coll_model['limit'] = 38 + + # Construct a dict representation of a SourceOptionsWebCrawl model + source_options_web_crawl_model = {} + source_options_web_crawl_model['url'] = 'testString' + source_options_web_crawl_model['limit_to_starting_hosts'] = True + source_options_web_crawl_model['crawl_speed'] = 'gentle' + source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['maximum_hops'] = 38 + source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['blacklist'] = ['testString'] + + # Construct a dict representation of a SourceOptionsBuckets model + source_options_buckets_model = {} + source_options_buckets_model['name'] = 'testString' + source_options_buckets_model['limit'] = 38 + + # Construct a dict representation of a SourceOptions model + source_options_model = {} + source_options_model['folders'] = [source_options_folder_model] + source_options_model['objects'] = [source_options_object_model] + source_options_model['site_collections'] = [source_options_site_coll_model] + source_options_model['urls'] = [source_options_web_crawl_model] + source_options_model['buckets'] = [source_options_buckets_model] + source_options_model['crawl_all_buckets'] = True + + # Construct a dict representation of a Source model + source_model = {} + source_model['type'] = 'box' + source_model['credential_id'] = 'testString' + source_model['schedule'] = source_schedule_model + source_model['options'] = source_options_model + + # Set up parameter values + environment_id = 'testString' + configuration_id = 'testString' + name = 'testString' + description = 'testString' + conversions = conversions_model + enrichments = [enrichment_model] + normalizations = [normalization_operation_model] + source = source_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "configuration_id": configuration_id, + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_configuration(**req_copy) + + + class TestDeleteConfiguration(): + """ + Test Class for delete_configuration + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_configuration_response(self): - body = self.construct_full_body() - response = fake_response_DeleteConfigurationResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_configuration_all_params(self): + """ + delete_configuration() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_configuration_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DeleteConfigurationResponse_json - send_request(self, body, response) + # Set up parameter values + environment_id = 'testString' + configuration_id = 'testString' + + # Invoke method + response = service.delete_configuration( + environment_id, + configuration_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_configuration_empty(self): - check_empty_required_params(self, fake_response_DeleteConfigurationResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_configuration_value_error(self): + """ + test_delete_configuration_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/configurations/{1}'.format(body['environment_id'], body['configuration_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + configuration_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "configuration_id": configuration_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_configuration(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_configuration(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['configuration_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['configuration_id'] = "string1" - return body # endregion @@ -833,437 +1735,508 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_collection -#----------------------------------------------------------------------------- class TestCreateCollection(): + """ + Test Class for create_collection + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_collection_response(self): - body = self.construct_full_body() - response = fake_response_Collection_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_create_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Collection_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_collection_all_params(self): + """ + create_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + environment_id = 'testString' + name = 'testString' + description = 'testString' + configuration_id = 'testString' + language = 'en' + + # Invoke method + response = service.create_collection( + environment_id, + name, + description=description, + configuration_id=configuration_id, + language=language, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['configuration_id'] == 'testString' + assert req_body['language'] == 'en' + + + @responses.activate + def test_create_collection_value_error(self): + """ + test_create_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + environment_id = 'testString' + name = 'testString' + description = 'testString' + configuration_id = 'testString' + language = 'en' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_collection(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_collection_empty(self): - check_empty_required_params(self, fake_response_Collection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections'.format(body['environment_id']) - 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=201, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.create_collection(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", "language": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_collections -#----------------------------------------------------------------------------- class TestListCollections(): + """ + Test Class for list_collections + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_collections_response(self): - body = self.construct_full_body() - response = fake_response_ListCollectionsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_collections_all_params(self): + """ + list_collections() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + name = 'testString' + + # Invoke method + response = service.list_collections( + environment_id, + name=name, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'name={}'.format(name) in query_string + + + @responses.activate + def test_list_collections_required_params(self): + """ + test_list_collections_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_collections_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ListCollectionsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_collections_empty(self): - check_empty_required_params(self, fake_response_ListCollectionsResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + # Invoke method + response = service.list_collections( + environment_id, + headers={} + ) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.list_collections(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_collection -#----------------------------------------------------------------------------- -class TestGetCollection(): - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_collection_response(self): - body = self.construct_full_body() - response = fake_response_Collection_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_collections_value_error(self): + """ + test_list_collections_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Collection_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_collections(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_collection_empty(self): - check_empty_required_params(self, fake_response_Collection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): +class TestGetCollection(): + """ + Test Class for get_collection + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_collection_all_params(self): + """ + get_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_collection(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_collection -#----------------------------------------------------------------------------- -class TestUpdateCollection(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_collection_response(self): - body = self.construct_full_body() - response = fake_response_Collection_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Collection_json - send_request(self, body, response) + # Invoke method + response = service.get_collection( + environment_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_collection_empty(self): - check_empty_required_params(self, fake_response_Collection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_collection_value_error(self): + """ + test_get_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_collection(**req_copy) - def add_mock_response(self, url, response): + + +class TestUpdateCollection(): + """ + Test Class for update_collection + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_collection_all_params(self): + """ + update_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.PUT, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.update_collection(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body.update({"name": "string1", "description": "string1", "configuration_id": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_collection -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + name = 'testString' + description = 'testString' + configuration_id = 'testString' + + # Invoke method + response = service.update_collection( + environment_id, + collection_id, + name, + description=description, + configuration_id=configuration_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['configuration_id'] == 'testString' + + + @responses.activate + def test_update_collection_value_error(self): + """ + test_update_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + name = 'testString' + description = 'testString' + configuration_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_collection(**req_copy) + + + class TestDeleteCollection(): + """ + Test Class for delete_collection + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_collection_response(self): - body = self.construct_full_body() - response = fake_response_DeleteCollectionResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_collection_all_params(self): + """ + delete_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DeleteCollectionResponse_json - send_request(self, body, response) + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = service.delete_collection( + environment_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_collection_empty(self): - check_empty_required_params(self, fake_response_DeleteCollectionResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_collection_value_error(self): + """ + test_delete_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_collection(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}'.format(body['environment_id'], body['collection_id']) - 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='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_collection(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_collection_fields -#----------------------------------------------------------------------------- class TestListCollectionFields(): + """ + Test Class for list_collection_fields + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_collection_fields_response(self): - body = self.construct_full_body() - response = fake_response_ListCollectionFieldsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_collection_fields_all_params(self): + """ + list_collection_fields() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_collection_fields_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ListCollectionFieldsResponse_json - send_request(self, body, response) + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = service.list_collection_fields( + environment_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_collection_fields_empty(self): - check_empty_required_params(self, fake_response_ListCollectionFieldsResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_collection_fields_value_error(self): + """ + test_list_collection_fields_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/fields'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_collection_fields(**req_copy) - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.list_collection_fields(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body # endregion @@ -1276,658 +2249,752 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_expansions -#----------------------------------------------------------------------------- class TestListExpansions(): + """ + Test Class for list_expansions + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_expansions_response(self): - body = self.construct_full_body() - response = fake_response_Expansions_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_expansions_all_params(self): + """ + list_expansions() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_expansions_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Expansions_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_expansions_empty(self): - check_empty_required_params(self, fake_response_Expansions_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + # Invoke method + response = service.list_expansions( + environment_id, + collection_id, + headers={} + ) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.list_expansions(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_expansions -#----------------------------------------------------------------------------- -class TestCreateExpansions(): - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_expansions_response(self): - body = self.construct_full_body() - response = fake_response_Expansions_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_expansions_value_error(self): + """ + test_list_expansions_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_expansions_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Expansions_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_expansions_empty(self): - check_empty_required_params(self, fake_response_Expansions_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_expansions(**req_copy) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.create_expansions(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body.update({"expansions": [], }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body.update({"expansions": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_expansions -#----------------------------------------------------------------------------- -class TestDeleteExpansions(): - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_expansions_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 +class TestCreateExpansions(): + """ + Test Class for create_expansions + """ - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_expansions_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 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_expansions_all_params(self): + """ + create_expansions() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Expansion model + expansion_model = {} + expansion_model['input_terms'] = ['testString'] + expansion_model['expanded_terms'] = ['testString'] + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + expansions = [expansion_model] + + # Invoke method + response = service.create_expansions( + environment_id, + collection_id, + expansions, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['expansions'] == [expansion_model] + + + @responses.activate + def test_create_expansions_value_error(self): + """ + test_create_expansions_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Expansion model + expansion_model = {} + expansion_model['input_terms'] = ['testString'] + expansion_model['expanded_terms'] = ['testString'] + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + expansions = [expansion_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "expansions": expansions, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_expansions(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_expansions_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 = '/v1/environments/{0}/collections/{1}/expansions'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): +class TestDeleteExpansions(): + """ + Test Class for delete_expansions + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_expansions_all_params(self): + """ + delete_expansions() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_expansions(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_tokenization_dictionary_status -#----------------------------------------------------------------------------- -class TestGetTokenizationDictionaryStatus(): + url, + status=204) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_tokenization_dictionary_status_response(self): - body = self.construct_full_body() - response = fake_response_TokenDictStatusResponse_json - send_request(self, body, response) + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = service.delete_expansions( + environment_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_tokenization_dictionary_status_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TokenDictStatusResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_tokenization_dictionary_status_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_expansions_value_error(self): + """ + test_delete_expansions_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_expansions(**req_copy) + + + +class TestGetTokenizationDictionaryStatus(): + """ + Test Class for get_tokenization_dictionary_status + """ - def add_mock_response(self, url, response): + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_tokenization_dictionary_status_all_params(self): + """ + get_tokenization_dictionary_status() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + mock_response = '{"status": "active", "type": "type"}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_tokenization_dictionary_status(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_tokenization_dictionary -#----------------------------------------------------------------------------- -class TestCreateTokenizationDictionary(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_tokenization_dictionary_response(self): - body = self.construct_full_body() - response = fake_response_TokenDictStatusResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_tokenization_dictionary_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TokenDictStatusResponse_json - send_request(self, body, response) + # Invoke method + response = service.get_tokenization_dictionary_status( + environment_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_tokenization_dictionary_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_tokenization_dictionary_status_value_error(self): + """ + test_get_tokenization_dictionary_status_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + mock_response = '{"status": "active", "type": "type"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_tokenization_dictionary_status(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): +class TestCreateTokenizationDictionary(): + """ + Test Class for create_tokenization_dictionary + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_tokenization_dictionary_all_params(self): + """ + create_tokenization_dictionary() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.create_tokenization_dictionary(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body.update({"tokenization_rules": [], }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_tokenization_dictionary -#----------------------------------------------------------------------------- -class TestDeleteTokenizationDictionary(): + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a TokenDictRule model + token_dict_rule_model = {} + token_dict_rule_model['text'] = 'testString' + token_dict_rule_model['tokens'] = ['testString'] + token_dict_rule_model['readings'] = ['testString'] + token_dict_rule_model['part_of_speech'] = 'testString' + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + tokenization_rules = [token_dict_rule_model] + + # Invoke method + response = service.create_tokenization_dictionary( + environment_id, + collection_id, + tokenization_rules=tokenization_rules, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['tokenization_rules'] == [token_dict_rule_model] + + + @responses.activate + def test_create_tokenization_dictionary_required_params(self): + """ + test_create_tokenization_dictionary_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + mock_response = '{"status": "active", "type": "type"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_tokenization_dictionary_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_tokenization_dictionary_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + # Invoke method + response = service.create_tokenization_dictionary( + environment_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_tokenization_dictionary_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_create_tokenization_dictionary_value_error(self): + """ + test_create_tokenization_dictionary_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + mock_response = '{"status": "active", "type": "type"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/tokenization_dictionary'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - def add_mock_response(self, url, response): + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_tokenization_dictionary(**req_copy) + + + +class TestDeleteTokenizationDictionary(): + """ + Test Class for delete_tokenization_dictionary + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_tokenization_dictionary_all_params(self): + """ + delete_tokenization_dictionary() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_tokenization_dictionary(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_stopword_list_status -#----------------------------------------------------------------------------- -class TestGetStopwordListStatus(): + url, + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_stopword_list_status_response(self): - body = self.construct_full_body() - response = fake_response_TokenDictStatusResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_stopword_list_status_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TokenDictStatusResponse_json - send_request(self, body, response) + # Invoke method + response = service.delete_tokenization_dictionary( + environment_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_stopword_list_status_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_tokenization_dictionary_value_error(self): + """ + test_delete_tokenization_dictionary_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_tokenization_dictionary(**req_copy) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + +class TestGetStopwordListStatus(): + """ + Test Class for get_stopword_list_status + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_stopword_list_status_all_params(self): + """ + get_stopword_list_status() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + mock_response = '{"status": "active", "type": "type"}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_stopword_list_status(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_stopword_list -#----------------------------------------------------------------------------- -class TestCreateStopwordList(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_stopword_list_response(self): - body = self.construct_full_body() - response = fake_response_TokenDictStatusResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_stopword_list_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TokenDictStatusResponse_json - send_request(self, body, response) + # Invoke method + response = service.get_stopword_list_status( + environment_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_stopword_list_empty(self): - check_empty_required_params(self, fake_response_TokenDictStatusResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_stopword_list_status_value_error(self): + """ + test_get_stopword_list_status_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + mock_response = '{"status": "active", "type": "type"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_stopword_list_status(**req_copy) + + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url +class TestCreateStopwordList(): + """ + Test Class for create_stopword_list + """ - def add_mock_response(self, url, response): + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_stopword_list_all_params(self): + """ + create_stopword_list() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + mock_response = '{"status": "active", "type": "type"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + stopword_file = io.BytesIO(b'This is a mock file.').getvalue() + stopword_filename = 'testString' + + # Invoke method + response = service.create_stopword_list( + environment_id, + collection_id, + stopword_file, + stopword_filename=stopword_filename, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_create_stopword_list_required_params(self): + """ + test_create_stopword_list_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.create_stopword_list(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['stopword_file'] = tempfile.NamedTemporaryFile() - body['stopword_filename'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['stopword_file'] = tempfile.NamedTemporaryFile() - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_stopword_list -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + stopword_file = io.BytesIO(b'This is a mock file.').getvalue() + stopword_filename = 'testString' + + # Invoke method + response = service.create_stopword_list( + environment_id, + collection_id, + stopword_file, + stopword_filename=stopword_filename, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_create_stopword_list_value_error(self): + """ + test_create_stopword_list_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + mock_response = '{"status": "active", "type": "type"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + stopword_file = io.BytesIO(b'This is a mock file.').getvalue() + stopword_filename = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "stopword_file": stopword_file, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_stopword_list(**req_copy) + + + class TestDeleteStopwordList(): + """ + Test Class for delete_stopword_list + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_stopword_list_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_stopword_list_all_params(self): + """ + delete_stopword_list() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + responses.add(responses.DELETE, + url, + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_stopword_list_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = service.delete_stopword_list( + environment_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_stopword_list_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_stopword_list_value_error(self): + """ + test_delete_stopword_list_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/word_lists/stopwords'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_stopword_list(**req_copy) - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_stopword_list(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body # endregion @@ -1940,306 +3007,390 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for add_document -#----------------------------------------------------------------------------- class TestAddDocument(): + """ + Test Class for add_document + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_add_document_response(self): - body = self.construct_full_body() - response = fake_response_DocumentAccepted_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_add_document_all_params(self): + """ + add_document() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/json' + metadata = 'testString' + + # Invoke method + response = service.add_document( + environment_id, + collection_id, + file=file, + filename=filename, + file_content_type=file_content_type, + metadata=metadata, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + + @responses.activate + def test_add_document_required_params(self): + """ + test_add_document_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_add_document_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DocumentAccepted_json - send_request(self, body, response) + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = service.add_document( + environment_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_document_empty(self): - check_empty_required_params(self, fake_response_DocumentAccepted_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_add_document_value_error(self): + """ + test_add_document_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_document(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents'.format(body['environment_id'], body['collection_id']) - 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=202, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.add_document(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['file'] = tempfile.NamedTemporaryFile() - body['filename'] = "string1" - body['file_content_type'] = "string1" - body['metadata'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_document_status -#----------------------------------------------------------------------------- class TestGetDocumentStatus(): + """ + Test Class for get_document_status + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_document_status_response(self): - body = self.construct_full_body() - response = fake_response_DocumentStatus_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_document_status_all_params(self): + """ + get_document_status() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_document_status_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DocumentStatus_json - send_request(self, body, response) + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Invoke method + response = service.get_document_status( + environment_id, + collection_id, + document_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_document_status_empty(self): - check_empty_required_params(self, fake_response_DocumentStatus_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_document_status_value_error(self): + """ + test_get_document_status_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "document_id": document_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_document_status(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_document_status(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['document_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['document_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_document -#----------------------------------------------------------------------------- class TestUpdateDocument(): + """ + Test Class for update_document + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_document_response(self): - body = self.construct_full_body() - response = fake_response_DocumentAccepted_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_document_all_params(self): + """ + update_document() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/json' + metadata = 'testString' + + # Invoke method + response = service.update_document( + environment_id, + collection_id, + document_id, + file=file, + filename=filename, + file_content_type=file_content_type, + metadata=metadata, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + + @responses.activate + def test_update_document_required_params(self): + """ + test_update_document_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_document_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DocumentAccepted_json - send_request(self, body, response) + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Invoke method + response = service.update_document( + environment_id, + collection_id, + document_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_document_empty(self): - check_empty_required_params(self, fake_response_DocumentAccepted_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_update_document_value_error(self): + """ + test_update_document_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "document_id": document_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_document(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) - 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=202, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.update_document(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['document_id'] = "string1" - body['file'] = tempfile.NamedTemporaryFile() - body['filename'] = "string1" - body['file_content_type'] = "string1" - body['metadata'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['document_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_document -#----------------------------------------------------------------------------- class TestDeleteDocument(): + """ + Test Class for delete_document + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_document_response(self): - body = self.construct_full_body() - response = fake_response_DeleteDocumentResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_document_all_params(self): + """ + delete_document() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_document_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DeleteDocumentResponse_json - send_request(self, body, response) + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Invoke method + response = service.delete_document( + environment_id, + collection_id, + document_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_document_empty(self): - check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_document_value_error(self): + """ + test_delete_document_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/documents/{2}'.format(body['environment_id'], body['collection_id'], body['document_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "document_id": document_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_document(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_document(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['document_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['document_id'] = "string1" - return body # endregion @@ -2252,401 +3403,850 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for query -#----------------------------------------------------------------------------- class TestQuery(): + """ + Test Class for query + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_query_response(self): - body = self.construct_full_body() - response = fake_response_QueryResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_query_all_params(self): + """ + query() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + filter = 'testString' + query = 'testString' + natural_language_query = 'testString' + passages = True + aggregation = 'testString' + count = 38 + return_ = 'testString' + offset = 38 + sort = 'testString' + highlight = True + passages_fields = 'testString' + passages_count = 100 + passages_characters = 50 + deduplicate = True + deduplicate_field = 'testString' + similar = True + similar_document_ids = 'testString' + similar_fields = 'testString' + bias = 'testString' + spelling_suggestions = True + x_watson_logging_opt_out = True + + # Invoke method + response = service.query( + environment_id, + collection_id, + filter=filter, + query=query, + natural_language_query=natural_language_query, + passages=passages, + aggregation=aggregation, + count=count, + return_=return_, + offset=offset, + sort=sort, + highlight=highlight, + passages_fields=passages_fields, + passages_count=passages_count, + passages_characters=passages_characters, + deduplicate=deduplicate, + deduplicate_field=deduplicate_field, + similar=similar, + similar_document_ids=similar_document_ids, + similar_fields=similar_fields, + bias=bias, + spelling_suggestions=spelling_suggestions, + x_watson_logging_opt_out=x_watson_logging_opt_out, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['filter'] == 'testString' + assert req_body['query'] == 'testString' + assert req_body['natural_language_query'] == 'testString' + assert req_body['passages'] == True + assert req_body['aggregation'] == 'testString' + assert req_body['count'] == 38 + assert req_body['return'] == 'testString' + assert req_body['offset'] == 38 + assert req_body['sort'] == 'testString' + assert req_body['highlight'] == True + assert req_body['passages.fields'] == 'testString' + assert req_body['passages.count'] == 100 + assert req_body['passages.characters'] == 50 + assert req_body['deduplicate'] == True + assert req_body['deduplicate.field'] == 'testString' + assert req_body['similar'] == True + assert req_body['similar.document_ids'] == 'testString' + assert req_body['similar.fields'] == 'testString' + assert req_body['bias'] == 'testString' + assert req_body['spelling_suggestions'] == True + + + @responses.activate + def test_query_required_params(self): + """ + test_query_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_query_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_QueryResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_query_empty(self): - check_empty_required_params(self, fake_response_QueryResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + # Invoke method + response = service.query( + environment_id, + collection_id, + headers={} + ) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/query'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.query(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body.update({"filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", "spelling_suggestions": True, }) - body['x_watson_logging_opt_out'] = True - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for query_notices -#----------------------------------------------------------------------------- -class TestQueryNotices(): - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_query_notices_response(self): - body = self.construct_full_body() - response = fake_response_QueryNoticesResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_query_value_error(self): + """ + test_query_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_query_notices_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_QueryNoticesResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.query(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_query_notices_empty(self): - check_empty_required_params(self, fake_response_QueryNoticesResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/notices'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): +class TestQueryNotices(): + """ + Test Class for query_notices + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_query_notices_all_params(self): + """ + query_notices() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.query_notices(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['filter'] = "string1" - body['query'] = "string1" - body['natural_language_query'] = "string1" - body['passages'] = True - body['aggregation'] = "string1" - body['count'] = 12345 - body['return_'] = [] - body['offset'] = 12345 - body['sort'] = [] - body['highlight'] = True - body['passages_fields'] = [] - body['passages_count'] = 12345 - body['passages_characters'] = 12345 - body['deduplicate_field'] = "string1" - body['similar'] = True - body['similar_document_ids'] = [] - body['similar_fields'] = [] - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for federated_query -#----------------------------------------------------------------------------- -class TestFederatedQuery(): + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + filter = 'testString' + query = 'testString' + natural_language_query = 'testString' + passages = True + aggregation = 'testString' + count = 38 + return_ = ['testString'] + offset = 38 + sort = ['testString'] + highlight = True + passages_fields = ['testString'] + passages_count = 100 + passages_characters = 50 + deduplicate_field = 'testString' + similar = True + similar_document_ids = ['testString'] + similar_fields = ['testString'] + + # Invoke method + response = service.query_notices( + environment_id, + collection_id, + filter=filter, + query=query, + natural_language_query=natural_language_query, + passages=passages, + aggregation=aggregation, + count=count, + return_=return_, + offset=offset, + sort=sort, + highlight=highlight, + passages_fields=passages_fields, + passages_count=passages_count, + passages_characters=passages_characters, + deduplicate_field=deduplicate_field, + similar=similar, + similar_document_ids=similar_document_ids, + similar_fields=similar_fields, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'filter={}'.format(filter) in query_string + assert 'query={}'.format(query) in query_string + assert 'natural_language_query={}'.format(natural_language_query) in query_string + assert 'passages={}'.format('true' if passages else 'false') in query_string + assert 'aggregation={}'.format(aggregation) in query_string + assert 'count={}'.format(count) in query_string + assert 'return={}'.format(','.join(return_)) in query_string + assert 'offset={}'.format(offset) in query_string + assert 'sort={}'.format(','.join(sort)) in query_string + assert 'highlight={}'.format('true' if highlight else 'false') in query_string + assert 'passages.fields={}'.format(','.join(passages_fields)) in query_string + assert 'passages.count={}'.format(passages_count) in query_string + assert 'passages.characters={}'.format(passages_characters) in query_string + assert 'deduplicate.field={}'.format(deduplicate_field) in query_string + assert 'similar={}'.format('true' if similar else 'false') in query_string + assert 'similar.document_ids={}'.format(','.join(similar_document_ids)) in query_string + assert 'similar.fields={}'.format(','.join(similar_fields)) in query_string + + + @responses.activate + def test_query_notices_required_params(self): + """ + test_query_notices_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_federated_query_response(self): - body = self.construct_full_body() - response = fake_response_QueryResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_federated_query_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_QueryResponse_json - send_request(self, body, response) + # Invoke method + response = service.query_notices( + environment_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_federated_query_empty(self): - check_empty_required_params(self, fake_response_QueryResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_query_notices_value_error(self): + """ + test_query_notices_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/query'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.federated_query(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) - body['x_watson_logging_opt_out'] = True - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body.update({"collection_ids": "string1", "filter": "string1", "query": "string1", "natural_language_query": "string1", "passages": True, "aggregation": "string1", "count": 12345, "return_": "string1", "offset": 12345, "sort": "string1", "highlight": True, "passages_fields": "string1", "passages_count": 12345, "passages_characters": 12345, "deduplicate": True, "deduplicate_field": "string1", "similar": True, "similar_document_ids": "string1", "similar_fields": "string1", "bias": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for federated_query_notices -#----------------------------------------------------------------------------- -class TestFederatedQueryNotices(): + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.query_notices(**req_copy) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_federated_query_notices_response(self): - body = self.construct_full_body() - response = fake_response_QueryNoticesResponse_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_federated_query_notices_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_QueryNoticesResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_federated_query_notices_empty(self): - check_empty_required_params(self, fake_response_QueryNoticesResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 +class TestFederatedQuery(): + """ + Test Class for federated_query + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_federated_query_all_params(self): + """ + federated_query() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_ids = 'testString' + filter = 'testString' + query = 'testString' + natural_language_query = 'testString' + passages = True + aggregation = 'testString' + count = 38 + return_ = 'testString' + offset = 38 + sort = 'testString' + highlight = True + passages_fields = 'testString' + passages_count = 100 + passages_characters = 50 + deduplicate = True + deduplicate_field = 'testString' + similar = True + similar_document_ids = 'testString' + similar_fields = 'testString' + bias = 'testString' + x_watson_logging_opt_out = True + + # Invoke method + response = service.federated_query( + environment_id, + collection_ids, + filter=filter, + query=query, + natural_language_query=natural_language_query, + passages=passages, + aggregation=aggregation, + count=count, + return_=return_, + offset=offset, + sort=sort, + highlight=highlight, + passages_fields=passages_fields, + passages_count=passages_count, + passages_characters=passages_characters, + deduplicate=deduplicate, + deduplicate_field=deduplicate_field, + similar=similar, + similar_document_ids=similar_document_ids, + similar_fields=similar_fields, + bias=bias, + x_watson_logging_opt_out=x_watson_logging_opt_out, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['collection_ids'] == 'testString' + assert req_body['filter'] == 'testString' + assert req_body['query'] == 'testString' + assert req_body['natural_language_query'] == 'testString' + assert req_body['passages'] == True + assert req_body['aggregation'] == 'testString' + assert req_body['count'] == 38 + assert req_body['return'] == 'testString' + assert req_body['offset'] == 38 + assert req_body['sort'] == 'testString' + assert req_body['highlight'] == True + assert req_body['passages.fields'] == 'testString' + assert req_body['passages.count'] == 100 + assert req_body['passages.characters'] == 50 + assert req_body['deduplicate'] == True + assert req_body['deduplicate.field'] == 'testString' + assert req_body['similar'] == True + assert req_body['similar.document_ids'] == 'testString' + assert req_body['similar.fields'] == 'testString' + assert req_body['bias'] == 'testString' + + + @responses.activate + def test_federated_query_required_params(self): + """ + test_federated_query_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_ids = 'testString' + filter = 'testString' + query = 'testString' + natural_language_query = 'testString' + passages = True + aggregation = 'testString' + count = 38 + return_ = 'testString' + offset = 38 + sort = 'testString' + highlight = True + passages_fields = 'testString' + passages_count = 100 + passages_characters = 50 + deduplicate = True + deduplicate_field = 'testString' + similar = True + similar_document_ids = 'testString' + similar_fields = 'testString' + bias = 'testString' + + # Invoke method + response = service.federated_query( + environment_id, + collection_ids, + filter=filter, + query=query, + natural_language_query=natural_language_query, + passages=passages, + aggregation=aggregation, + count=count, + return_=return_, + offset=offset, + sort=sort, + highlight=highlight, + passages_fields=passages_fields, + passages_count=passages_count, + passages_characters=passages_characters, + deduplicate=deduplicate, + deduplicate_field=deduplicate_field, + similar=similar, + similar_document_ids=similar_document_ids, + similar_fields=similar_fields, + bias=bias, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['collection_ids'] == 'testString' + assert req_body['filter'] == 'testString' + assert req_body['query'] == 'testString' + assert req_body['natural_language_query'] == 'testString' + assert req_body['passages'] == True + assert req_body['aggregation'] == 'testString' + assert req_body['count'] == 38 + assert req_body['return'] == 'testString' + assert req_body['offset'] == 38 + assert req_body['sort'] == 'testString' + assert req_body['highlight'] == True + assert req_body['passages.fields'] == 'testString' + assert req_body['passages.count'] == 100 + assert req_body['passages.characters'] == 50 + assert req_body['deduplicate'] == True + assert req_body['deduplicate.field'] == 'testString' + assert req_body['similar'] == True + assert req_body['similar.document_ids'] == 'testString' + assert req_body['similar.fields'] == 'testString' + assert req_body['bias'] == 'testString' + + + @responses.activate + def test_federated_query_value_error(self): + """ + test_federated_query_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_ids = 'testString' + filter = 'testString' + query = 'testString' + natural_language_query = 'testString' + passages = True + aggregation = 'testString' + count = 38 + return_ = 'testString' + offset = 38 + sort = 'testString' + highlight = True + passages_fields = 'testString' + passages_count = 100 + passages_characters = 50 + deduplicate = True + deduplicate_field = 'testString' + similar = True + similar_document_ids = 'testString' + similar_fields = 'testString' + bias = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_ids": collection_ids, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.federated_query(**req_copy) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/notices'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + +class TestFederatedQueryNotices(): + """ + Test Class for federated_query_notices + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_federated_query_notices_all_params(self): + """ + federated_query_notices() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.federated_query_notices(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_ids'] = [] - body['filter'] = "string1" - body['query'] = "string1" - body['natural_language_query'] = "string1" - body['aggregation'] = "string1" - body['count'] = 12345 - body['return_'] = [] - body['offset'] = 12345 - body['sort'] = [] - body['highlight'] = True - body['deduplicate_field'] = "string1" - body['similar'] = True - body['similar_document_ids'] = [] - body['similar_fields'] = [] - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_ids'] = [] - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_autocompletion -#----------------------------------------------------------------------------- -class TestGetAutocompletion(): + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_ids = ['testString'] + filter = 'testString' + query = 'testString' + natural_language_query = 'testString' + aggregation = 'testString' + count = 38 + return_ = ['testString'] + offset = 38 + sort = ['testString'] + highlight = True + deduplicate_field = 'testString' + similar = True + similar_document_ids = ['testString'] + similar_fields = ['testString'] + + # Invoke method + response = service.federated_query_notices( + environment_id, + collection_ids, + filter=filter, + query=query, + natural_language_query=natural_language_query, + aggregation=aggregation, + count=count, + return_=return_, + offset=offset, + sort=sort, + highlight=highlight, + deduplicate_field=deduplicate_field, + similar=similar, + similar_document_ids=similar_document_ids, + similar_fields=similar_fields, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string + assert 'filter={}'.format(filter) in query_string + assert 'query={}'.format(query) in query_string + assert 'natural_language_query={}'.format(natural_language_query) in query_string + assert 'aggregation={}'.format(aggregation) in query_string + assert 'count={}'.format(count) in query_string + assert 'return={}'.format(','.join(return_)) in query_string + assert 'offset={}'.format(offset) in query_string + assert 'sort={}'.format(','.join(sort)) in query_string + assert 'highlight={}'.format('true' if highlight else 'false') in query_string + assert 'deduplicate.field={}'.format(deduplicate_field) in query_string + assert 'similar={}'.format('true' if similar else 'false') in query_string + assert 'similar.document_ids={}'.format(','.join(similar_document_ids)) in query_string + assert 'similar.fields={}'.format(','.join(similar_fields)) in query_string + + + @responses.activate + def test_federated_query_notices_required_params(self): + """ + test_federated_query_notices_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_ids = ['testString'] + + # Invoke method + response = service.federated_query_notices( + environment_id, + collection_ids, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string + + + @responses.activate + def test_federated_query_notices_value_error(self): + """ + test_federated_query_notices_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_autocompletion_response(self): - body = self.construct_full_body() - response = fake_response_Completions_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_ids = ['testString'] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_ids": collection_ids, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.federated_query_notices(**req_copy) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_autocompletion_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Completions_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_autocompletion_empty(self): - check_empty_required_params(self, fake_response_Completions_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/autocompletion'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url +class TestGetAutocompletion(): + """ + Test Class for get_autocompletion + """ - def add_mock_response(self, url, response): + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_autocompletion_all_params(self): + """ + get_autocompletion() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/autocompletion') + mock_response = '{"completions": ["completions"]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + prefix = 'testString' + field = 'testString' + count = 38 + + # Invoke method + response = service.get_autocompletion( + environment_id, + collection_id, + prefix, + field=field, + count=count, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'prefix={}'.format(prefix) in query_string + assert 'field={}'.format(field) in query_string + assert 'count={}'.format(count) in query_string + + + @responses.activate + def test_get_autocompletion_required_params(self): + """ + test_get_autocompletion_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/autocompletion') + mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_autocompletion(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['prefix'] = "string1" - body['field'] = "string1" - body['count'] = 12345 - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['prefix'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + prefix = 'testString' + + # Invoke method + response = service.get_autocompletion( + environment_id, + collection_id, + prefix, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'prefix={}'.format(prefix) in query_string + + + @responses.activate + def test_get_autocompletion_value_error(self): + """ + test_get_autocompletion_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/autocompletion') + mock_response = '{"completions": ["completions"]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + prefix = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "prefix": prefix, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_autocompletion(**req_copy) + # endregion @@ -2659,750 +4259,816 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_training_data -#----------------------------------------------------------------------------- class TestListTrainingData(): + """ + Test Class for list_training_data + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_training_data_response(self): - body = self.construct_full_body() - response = fake_response_TrainingDataSet_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_training_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingDataSet_json - send_request(self, body, response) - assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_training_data_empty(self): - check_empty_required_params(self, fake_response_TrainingDataSet_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_training_data_all_params(self): + """ + list_training_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.list_training_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for add_training_data -#----------------------------------------------------------------------------- -class TestAddTrainingData(): + # Invoke method + response = service.list_training_data( + environment_id, + collection_id, + headers={} + ) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_add_training_data_response(self): - body = self.construct_full_body() - response = fake_response_TrainingQuery_json - send_request(self, body, response) + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_add_training_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingQuery_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_training_data_empty(self): - check_empty_required_params(self, fake_response_TrainingQuery_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_training_data_value_error(self): + """ + test_list_training_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.add_training_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body.update({"natural_language_query": "string1", "filter": "string1", "examples": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_all_training_data -#----------------------------------------------------------------------------- -class TestDeleteAllTrainingData(): + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_training_data(**req_copy) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_all_training_data_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_all_training_data_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_all_training_data_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 +class TestAddTrainingData(): + """ + Test Class for add_training_data + """ - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data'.format(body['environment_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_add_training_data_all_params(self): + """ + add_training_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a TrainingExample model + training_example_model = {} + training_example_model['document_id'] = 'testString' + training_example_model['cross_reference'] = 'testString' + training_example_model['relevance'] = 38 + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + natural_language_query = 'testString' + filter = 'testString' + examples = [training_example_model] + + # Invoke method + response = service.add_training_data( + environment_id, + collection_id, + natural_language_query=natural_language_query, + filter=filter, + examples=examples, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['natural_language_query'] == 'testString' + assert req_body['filter'] == 'testString' + assert req_body['examples'] == [training_example_model] + + + @responses.activate + def test_add_training_data_value_error(self): + """ + test_add_training_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a TrainingExample model + training_example_model = {} + training_example_model['document_id'] = 'testString' + training_example_model['cross_reference'] = 'testString' + training_example_model['relevance'] = 38 + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + natural_language_query = 'testString' + filter = 'testString' + examples = [training_example_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_training_data(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_all_training_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_training_data -#----------------------------------------------------------------------------- -class TestGetTrainingData(): - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_training_data_response(self): - body = self.construct_full_body() - response = fake_response_TrainingQuery_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_training_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingQuery_json - send_request(self, body, response) - assert len(responses.calls) == 1 +class TestDeleteAllTrainingData(): + """ + Test Class for delete_all_training_data + """ - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_training_data_empty(self): - check_empty_required_params(self, fake_response_TrainingQuery_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_all_training_data_all_params(self): + """ + delete_all_training_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + responses.add(responses.DELETE, + url, + status=204) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_training_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_training_data -#----------------------------------------------------------------------------- -class TestDeleteTrainingData(): + # Invoke method + response = service.delete_all_training_data( + environment_id, + collection_id, + headers={} + ) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_training_data_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_training_data_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_training_data_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_all_training_data_value_error(self): + """ + test_delete_all_training_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + responses.add(responses.DELETE, + url, + status=204) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}'.format(body['environment_id'], body['collection_id'], body['query_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' - def add_mock_response(self, url, response): - responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_training_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_training_examples -#----------------------------------------------------------------------------- -class TestListTrainingExamples(): + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_all_training_data(**req_copy) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_training_examples_response(self): - body = self.construct_full_body() - response = fake_response_TrainingExampleList_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_training_examples_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingExampleList_json - send_request(self, body, response) - assert len(responses.calls) == 1 - - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_training_examples_empty(self): - check_empty_required_params(self, fake_response_TrainingExampleList_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url +class TestGetTrainingData(): + """ + Test Class for get_training_data + """ - def add_mock_response(self, url, response): + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_training_data_all_params(self): + """ + get_training_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.list_training_examples(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_training_example -#----------------------------------------------------------------------------- -class TestCreateTrainingExample(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_training_example_response(self): - body = self.construct_full_body() - response = fake_response_TrainingExample_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_training_example_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingExample_json - send_request(self, body, response) + # Invoke method + response = service.get_training_data( + environment_id, + collection_id, + query_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_training_example_empty(self): - check_empty_required_params(self, fake_response_TrainingExample_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_training_data_value_error(self): + """ + test_get_training_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples'.format(body['environment_id'], body['collection_id'], body['query_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' - def add_mock_response(self, url, response): - responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.create_training_example(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - body.update({"document_id": "string1", "cross_reference": "string1", "relevance": 12345, }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_training_example -#----------------------------------------------------------------------------- -class TestDeleteTrainingExample(): + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "query_id": query_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_training_data(**req_copy) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_training_example_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) + + +class TestDeleteTrainingData(): + """ + Test Class for delete_training_data + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_training_data_all_params(self): + """ + delete_training_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + + # Invoke method + response = service.delete_training_data( + environment_id, + collection_id, + query_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_training_example_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_training_data_value_error(self): + """ + test_delete_training_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "query_id": query_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_training_data(**req_copy) + + + +class TestListTrainingExamples(): + """ + Test Class for list_training_examples + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_training_examples_all_params(self): + """ + list_training_examples() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + + # Invoke method + response = service.list_training_examples( + environment_id, + collection_id, + query_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_training_example_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_training_examples_value_error(self): + """ + test_list_training_examples_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "query_id": query_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_training_examples(**req_copy) + + + +class TestCreateTrainingExample(): + """ + Test Class for create_training_example + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_training_example_all_params(self): + """ + create_training_example() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + document_id = 'testString' + cross_reference = 'testString' + relevance = 38 + + # Invoke method + response = service.create_training_example( + environment_id, + collection_id, + query_id, + document_id=document_id, + cross_reference=cross_reference, + relevance=relevance, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['document_id'] == 'testString' + assert req_body['cross_reference'] == 'testString' + assert req_body['relevance'] == 38 + + + @responses.activate + def test_create_training_example_value_error(self): + """ + test_create_training_example_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + document_id = 'testString' + cross_reference = 'testString' + relevance = 38 + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "query_id": query_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_training_example(**req_copy) + + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url +class TestDeleteTrainingExample(): + """ + Test Class for delete_training_example + """ - def add_mock_response(self, url, response): + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_training_example_all_params(self): + """ + delete_training_example() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_training_example(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - body['example_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - body['example_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_training_example -#----------------------------------------------------------------------------- -class TestUpdateTrainingExample(): + url, + status=204) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_training_example_response(self): - body = self.construct_full_body() - response = fake_response_TrainingExample_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + example_id = 'testString' - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_training_example_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingExample_json - send_request(self, body, response) + # Invoke method + response = service.delete_training_example( + environment_id, + collection_id, + query_id, + example_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_training_example_empty(self): - check_empty_required_params(self, fake_response_TrainingExample_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_training_example_value_error(self): + """ + test_delete_training_example_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + responses.add(responses.DELETE, + url, + status=204) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + example_id = 'testString' - def add_mock_response(self, url, response): - responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.update_training_example(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - body['example_id'] = "string1" - body.update({"cross_reference": "string1", "relevance": 12345, }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - body['example_id'] = "string1" - body.update({"cross_reference": "string1", "relevance": 12345, }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_training_example -#----------------------------------------------------------------------------- -class TestGetTrainingExample(): + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "query_id": query_id, + "example_id": example_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_training_example(**req_copy) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_training_example_response(self): - body = self.construct_full_body() - response = fake_response_TrainingExample_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_training_example_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingExample_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_training_example_empty(self): - check_empty_required_params(self, fake_response_TrainingExample_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 +class TestUpdateTrainingExample(): + """ + Test Class for update_training_example + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_training_example_all_params(self): + """ + update_training_example() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + example_id = 'testString' + cross_reference = 'testString' + relevance = 38 + + # Invoke method + response = service.update_training_example( + environment_id, + collection_id, + query_id, + example_id, + cross_reference=cross_reference, + relevance=relevance, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['cross_reference'] == 'testString' + assert req_body['relevance'] == 38 + + + @responses.activate + def test_update_training_example_value_error(self): + """ + test_update_training_example_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + example_id = 'testString' + cross_reference = 'testString' + relevance = 38 + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "query_id": query_id, + "example_id": example_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_training_example(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/collections/{1}/training_data/{2}/examples/{3}'.format(body['environment_id'], body['collection_id'], body['query_id'], body['example_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): +class TestGetTrainingExample(): + """ + Test Class for get_training_example + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_training_example_all_params(self): + """ + get_training_example() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_training_example(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - body['example_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['collection_id'] = "string1" - body['query_id'] = "string1" - body['example_id'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + example_id = 'testString' + + # Invoke method + response = service.get_training_example( + environment_id, + collection_id, + query_id, + example_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_get_training_example_value_error(self): + """ + test_get_training_example_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + collection_id = 'testString' + query_id = 'testString' + example_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "collection_id": collection_id, + "query_id": query_id, + "example_id": example_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_training_example(**req_copy) + # endregion @@ -3415,74 +5081,72 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for delete_user_data -#----------------------------------------------------------------------------- class TestDeleteUserData(): + """ + Test Class for delete_user_data + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_user_data_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_user_data_all_params(self): + """ + delete_user_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/user_data') + responses.add(responses.DELETE, + url, + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_user_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + # Set up parameter values + customer_id = 'testString' + + # Invoke method + response = service.delete_user_data( + customer_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'customer_id={}'.format(customer_id) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_user_data_value_error(self): + """ + test_delete_user_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/user_data') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/user_data' - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + customer_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customer_id": customer_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_user_data(**req_copy) - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_user_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['customer_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customer_id'] = "string1" - return body # endregion @@ -3495,1159 +5159,1505 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_event -#----------------------------------------------------------------------------- class TestCreateEvent(): + """ + Test Class for create_event + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_event_response(self): - body = self.construct_full_body() - response = fake_response_CreateEventResponse_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_create_event_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_CreateEventResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_event_all_params(self): + """ + create_event() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/events') + mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a EventData model + event_data_model = {} + event_data_model['environment_id'] = 'testString' + event_data_model['session_token'] = 'testString' + event_data_model['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + event_data_model['display_rank'] = 38 + event_data_model['collection_id'] = 'testString' + event_data_model['document_id'] = 'testString' + + # Set up parameter values + type = 'click' + data = event_data_model + + # Invoke method + response = service.create_event( + type, + data, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['type'] == 'click' + assert req_body['data'] == event_data_model + + + @responses.activate + def test_create_event_value_error(self): + """ + test_create_event_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/events') + mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a EventData model + event_data_model = {} + event_data_model['environment_id'] = 'testString' + event_data_model['session_token'] = 'testString' + event_data_model['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + event_data_model['display_rank'] = 38 + event_data_model['collection_id'] = 'testString' + event_data_model['document_id'] = 'testString' + + # Set up parameter values + type = 'click' + data = event_data_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "type": type, + "data": data, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_event(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_event_empty(self): - check_empty_required_params(self, fake_response_CreateEventResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/events' - 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=201, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.create_event(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) - return body - - def construct_required_body(self): - body = dict() - body.update({"type": "string1", "data": EventData._from_dict(json.loads("""{"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}""")), }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for query_log -#----------------------------------------------------------------------------- class TestQueryLog(): + """ + Test Class for query_log + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_query_log_response(self): - body = self.construct_full_body() - response = fake_response_LogQueryResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_query_log_all_params(self): + """ + query_log() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/logs') + mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00", "client_timestamp": "2019-01-01T12:00:00", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + filter = 'testString' + query = 'testString' + count = 38 + offset = 38 + sort = ['testString'] + + # Invoke method + response = service.query_log( + filter=filter, + query=query, + count=count, + offset=offset, + sort=sort, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'filter={}'.format(filter) in query_string + assert 'query={}'.format(query) in query_string + assert 'count={}'.format(count) in query_string + assert 'offset={}'.format(offset) in query_string + assert 'sort={}'.format(','.join(sort)) in query_string + + + @responses.activate + def test_query_log_required_params(self): + """ + test_query_log_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/logs') + mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00", "client_timestamp": "2019-01-01T12:00:00", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_query_log_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_LogQueryResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Invoke method + response = service.query_log() - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_query_log_empty(self): - check_empty_response(self) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/logs' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_query_log_value_error(self): + """ + test_query_log_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/logs') + mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00", "client_timestamp": "2019-01-01T12:00:00", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.query_log(**body) - return output - - def construct_full_body(self): - body = dict() - body['filter'] = "string1" - body['query'] = "string1" - body['count'] = 12345 - body['offset'] = 12345 - body['sort'] = [] - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_metrics_query -#----------------------------------------------------------------------------- -class TestGetMetricsQuery(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_response(self): - body = self.construct_full_body() - response = fake_response_MetricResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.query_log(**req_copy) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_MetricResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_empty(self): - check_empty_response(self) - assert len(responses.calls) == 1 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/metrics/number_of_queries' - url = '{0}{1}'.format(base_url, endpoint) - return url +class TestGetMetricsQuery(): + """ + Test Class for get_metrics_query + """ - def add_mock_response(self, url, response): + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_metrics_query_all_params(self): + """ + get_metrics_query() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_metrics_query(**body) - return output - - def construct_full_body(self): - body = dict() - body['start_time'] = datetime.now() - body['end_time'] = datetime.now() - body['result_type'] = "string1" - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_metrics_query_event -#----------------------------------------------------------------------------- -class TestGetMetricsQueryEvent(): + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + start_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + end_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + result_type = 'document' + + # Invoke method + response = service.get_metrics_query( + start_time=start_time, + end_time=end_time, + result_type=result_type, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'result_type={}'.format(result_type) in query_string + + + @responses.activate + def test_get_metrics_query_required_params(self): + """ + test_get_metrics_query_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_event_response(self): - body = self.construct_full_body() - response = fake_response_MetricResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Invoke method + response = service.get_metrics_query() - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_event_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_MetricResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_event_empty(self): - check_empty_response(self) + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/metrics/number_of_queries_with_event' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_get_metrics_query_value_error(self): + """ + test_get_metrics_query_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_metrics_query_event(**body) - return output - - def construct_full_body(self): - body = dict() - body['start_time'] = datetime.now() - body['end_time'] = datetime.now() - body['result_type'] = "string1" - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_metrics_query_no_results -#----------------------------------------------------------------------------- -class TestGetMetricsQueryNoResults(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_no_results_response(self): - body = self.construct_full_body() - response = fake_response_MetricResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_metrics_query(**req_copy) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_no_results_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_MetricResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_no_results_empty(self): - check_empty_response(self) - assert len(responses.calls) == 1 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/metrics/number_of_queries_with_no_search_results' - url = '{0}{1}'.format(base_url, endpoint) - return url +class TestGetMetricsQueryEvent(): + """ + Test Class for get_metrics_query_event + """ - def add_mock_response(self, url, response): + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_metrics_query_event_all_params(self): + """ + get_metrics_query_event() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_event') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_metrics_query_no_results(**body) - return output - - def construct_full_body(self): - body = dict() - body['start_time'] = datetime.now() - body['end_time'] = datetime.now() - body['result_type'] = "string1" - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_metrics_event_rate -#----------------------------------------------------------------------------- -class TestGetMetricsEventRate(): + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + start_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + end_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + result_type = 'document' + + # Invoke method + response = service.get_metrics_query_event( + start_time=start_time, + end_time=end_time, + result_type=result_type, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'result_type={}'.format(result_type) in query_string + + + @responses.activate + def test_get_metrics_query_event_required_params(self): + """ + test_get_metrics_query_event_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_event') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_event_rate_response(self): - body = self.construct_full_body() - response = fake_response_MetricResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Invoke method + response = service.get_metrics_query_event() - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_event_rate_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_MetricResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_event_rate_empty(self): - check_empty_response(self) + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/metrics/event_rate' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_get_metrics_query_event_value_error(self): + """ + test_get_metrics_query_event_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_event') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_metrics_event_rate(**body) - return output - - def construct_full_body(self): - body = dict() - body['start_time'] = datetime.now() - body['end_time'] = datetime.now() - body['result_type'] = "string1" - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_metrics_query_token_event -#----------------------------------------------------------------------------- -class TestGetMetricsQueryTokenEvent(): + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_token_event_response(self): - body = self.construct_full_body() - response = fake_response_MetricTokenResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_metrics_query_event(**req_copy) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_token_event_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_MetricTokenResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_metrics_query_token_event_empty(self): - check_empty_response(self) - assert len(responses.calls) == 1 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/metrics/top_query_tokens_with_event_rate' - url = '{0}{1}'.format(base_url, endpoint) - return url +class TestGetMetricsQueryNoResults(): + """ + Test Class for get_metrics_query_no_results + """ - def add_mock_response(self, url, response): + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_metrics_query_no_results_all_params(self): + """ + get_metrics_query_no_results() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_no_search_results') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_metrics_query_token_event(**body) - return output - - def construct_full_body(self): - body = dict() - body['count'] = 12345 - return body - - def construct_required_body(self): - body = dict() - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + start_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + end_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + result_type = 'document' + + # Invoke method + response = service.get_metrics_query_no_results( + start_time=start_time, + end_time=end_time, + result_type=result_type, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'result_type={}'.format(result_type) in query_string + + + @responses.activate + def test_get_metrics_query_no_results_required_params(self): + """ + test_get_metrics_query_no_results_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_no_search_results') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + # Invoke method + response = service.get_metrics_query_no_results() -# endregion -############################################################################## -# End of Service: EventsAndFeedback -############################################################################## -############################################################################## -# Start of Service: Credentials -############################################################################## -# region + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 -#----------------------------------------------------------------------------- -# Test Class for list_credentials -#----------------------------------------------------------------------------- -class TestListCredentials(): - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_credentials_response(self): - body = self.construct_full_body() - response = fake_response_CredentialsList_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_get_metrics_query_no_results_value_error(self): + """ + test_get_metrics_query_no_results_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_no_search_results') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_credentials_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_CredentialsList_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_metrics_query_no_results(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_credentials_empty(self): - check_empty_required_params(self, fake_response_CredentialsList_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): +class TestGetMetricsEventRate(): + """ + Test Class for get_metrics_event_rate + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_metrics_event_rate_all_params(self): + """ + get_metrics_event_rate() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/event_rate') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.list_credentials(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_credentials -#----------------------------------------------------------------------------- -class TestCreateCredentials(): + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + start_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + end_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + result_type = 'document' + + # Invoke method + response = service.get_metrics_event_rate( + start_time=start_time, + end_time=end_time, + result_type=result_type, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'result_type={}'.format(result_type) in query_string + + + @responses.activate + def test_get_metrics_event_rate_required_params(self): + """ + test_get_metrics_event_rate_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/event_rate') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_credentials_response(self): - body = self.construct_full_body() - response = fake_response_Credentials_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Invoke method + response = service.get_metrics_event_rate() - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_credentials_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Credentials_json - send_request(self, body, response) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_credentials_empty(self): - check_empty_required_params(self, fake_response_Credentials_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_metrics_event_rate_value_error(self): + """ + test_get_metrics_event_rate_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/event_rate') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_metrics_event_rate(**req_copy) - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.create_credentials(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_credentials -#----------------------------------------------------------------------------- -class TestGetCredentials(): - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_credentials_response(self): - body = self.construct_full_body() - response = fake_response_Credentials_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_credentials_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Credentials_json - send_request(self, body, response) - assert len(responses.calls) == 1 +class TestGetMetricsQueryTokenEvent(): + """ + Test Class for get_metrics_query_token_event + """ - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_credentials_empty(self): - check_empty_required_params(self, fake_response_Credentials_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_metrics_query_token_event_all_params(self): + """ + get_metrics_query_token_event() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/top_query_tokens_with_event_rate') + mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + count = 38 - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_credentials(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['credential_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['credential_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_credentials -#----------------------------------------------------------------------------- -class TestUpdateCredentials(): + # Invoke method + response = service.get_metrics_query_token_event( + count=count, + headers={} + ) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_credentials_response(self): - body = self.construct_full_body() - response = fake_response_Credentials_json - send_request(self, body, response) + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'count={}'.format(count) in query_string - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_credentials_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Credentials_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_credentials_empty(self): - check_empty_required_params(self, fake_response_Credentials_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_metrics_query_token_event_required_params(self): + """ + test_get_metrics_query_token_event_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/top_query_tokens_with_event_rate') + mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Invoke method + response = service.get_metrics_query_token_event() - def add_mock_response(self, url, response): - responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.update_credentials(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['credential_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['credential_id'] = "string1" - body.update({"source_type": "string1", "credential_details": CredentialDetails._from_dict(json.loads("""{"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}""")), "status": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_credentials -#----------------------------------------------------------------------------- -class TestDeleteCredentials(): - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_credentials_response(self): - body = self.construct_full_body() - response = fake_response_DeleteCredentials_json - send_request(self, body, response) + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_credentials_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DeleteCredentials_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_credentials_empty(self): - check_empty_required_params(self, fake_response_DeleteCredentials_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_metrics_query_token_event_value_error(self): + """ + test_get_metrics_query_token_event_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/metrics/top_query_tokens_with_event_rate') + mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/credentials/{1}'.format(body['environment_id'], body['credential_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_metrics_query_token_event(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_credentials(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['credential_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['credential_id'] = "string1" - return body # endregion ############################################################################## -# End of Service: Credentials +# End of Service: EventsAndFeedback ############################################################################## ############################################################################## -# Start of Service: GatewayConfiguration +# Start of Service: Credentials ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_gateways -#----------------------------------------------------------------------------- -class TestListGateways(): - - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_gateways_response(self): - body = self.construct_full_body() - response = fake_response_GatewayList_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_gateways_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_GatewayList_json - send_request(self, body, response) - assert len(responses.calls) == 1 +class TestListCredentials(): + """ + Test Class for list_credentials + """ - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_gateways_empty(self): - check_empty_required_params(self, fake_response_GatewayList_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_credentials_all_params(self): + """ + list_credentials() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/credentials') + mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.list_gateways(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_gateway -#----------------------------------------------------------------------------- -class TestCreateGateway(): + # Invoke method + response = service.list_credentials( + environment_id, + headers={} + ) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_gateway_response(self): - body = self.construct_full_body() - response = fake_response_Gateway_json - send_request(self, body, response) + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_gateway_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Gateway_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_gateway_empty(self): - check_empty_required_params(self, fake_response_Gateway_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_credentials_value_error(self): + """ + test_list_credentials_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/credentials') + mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways'.format(body['environment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + environment_id = 'testString' - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.create_gateway(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body.update({"name": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_gateway -#----------------------------------------------------------------------------- -class TestGetGateway(): + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_credentials(**req_copy) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_gateway_response(self): - body = self.construct_full_body() - response = fake_response_Gateway_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_gateway_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Gateway_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_gateway_empty(self): - check_empty_required_params(self, fake_response_Gateway_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 +class TestCreateCredentials(): + """ + Test Class for create_credentials + """ - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_credentials_all_params(self): + """ + create_credentials() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/credentials') + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CredentialDetails model + credential_details_model = {} + credential_details_model['credential_type'] = 'oauth2' + credential_details_model['client_id'] = 'testString' + credential_details_model['enterprise_id'] = 'testString' + credential_details_model['url'] = 'testString' + credential_details_model['username'] = 'testString' + credential_details_model['organization_url'] = 'testString' + credential_details_model['site_collection.path'] = 'testString' + credential_details_model['client_secret'] = 'testString' + credential_details_model['public_key_id'] = 'testString' + credential_details_model['private_key'] = 'testString' + credential_details_model['passphrase'] = 'testString' + credential_details_model['password'] = 'testString' + credential_details_model['gateway_id'] = 'testString' + credential_details_model['source_version'] = 'online' + credential_details_model['web_application_url'] = 'testString' + credential_details_model['domain'] = 'testString' + credential_details_model['endpoint'] = 'testString' + credential_details_model['access_key_id'] = 'testString' + credential_details_model['secret_access_key'] = 'testString' + + # Set up parameter values + environment_id = 'testString' + source_type = 'box' + credential_details = credential_details_model + status = 'connected' + + # Invoke method + response = service.create_credentials( + environment_id, + source_type=source_type, + credential_details=credential_details, + status=status, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['source_type'] == 'box' + assert req_body['credential_details'] == credential_details_model + assert req_body['status'] == 'connected' + + + @responses.activate + def test_create_credentials_value_error(self): + """ + test_create_credentials_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/credentials') + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CredentialDetails model + credential_details_model = {} + credential_details_model['credential_type'] = 'oauth2' + credential_details_model['client_id'] = 'testString' + credential_details_model['enterprise_id'] = 'testString' + credential_details_model['url'] = 'testString' + credential_details_model['username'] = 'testString' + credential_details_model['organization_url'] = 'testString' + credential_details_model['site_collection.path'] = 'testString' + credential_details_model['client_secret'] = 'testString' + credential_details_model['public_key_id'] = 'testString' + credential_details_model['private_key'] = 'testString' + credential_details_model['passphrase'] = 'testString' + credential_details_model['password'] = 'testString' + credential_details_model['gateway_id'] = 'testString' + credential_details_model['source_version'] = 'online' + credential_details_model['web_application_url'] = 'testString' + credential_details_model['domain'] = 'testString' + credential_details_model['endpoint'] = 'testString' + credential_details_model['access_key_id'] = 'testString' + credential_details_model['secret_access_key'] = 'testString' + + # Set up parameter values + environment_id = 'testString' + source_type = 'box' + credential_details = credential_details_model + status = 'connected' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_credentials(**req_copy) - 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 = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.get_gateway(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['gateway_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['gateway_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_gateway -#----------------------------------------------------------------------------- -class TestDeleteGateway(): - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_gateway_response(self): - body = self.construct_full_body() - response = fake_response_GatewayDelete_json - send_request(self, body, response) - assert len(responses.calls) == 1 - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- +class TestGetCredentials(): + """ + Test Class for get_credentials + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_credentials_all_params(self): + """ + get_credentials() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + credential_id = 'testString' + + # Invoke method + response = service.get_credentials( + environment_id, + credential_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_get_credentials_value_error(self): + """ + test_get_credentials_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + credential_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "credential_id": credential_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_credentials(**req_copy) + + + +class TestUpdateCredentials(): + """ + Test Class for update_credentials + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_credentials_all_params(self): + """ + update_credentials() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CredentialDetails model + credential_details_model = {} + credential_details_model['credential_type'] = 'oauth2' + credential_details_model['client_id'] = 'testString' + credential_details_model['enterprise_id'] = 'testString' + credential_details_model['url'] = 'testString' + credential_details_model['username'] = 'testString' + credential_details_model['organization_url'] = 'testString' + credential_details_model['site_collection.path'] = 'testString' + credential_details_model['client_secret'] = 'testString' + credential_details_model['public_key_id'] = 'testString' + credential_details_model['private_key'] = 'testString' + credential_details_model['passphrase'] = 'testString' + credential_details_model['password'] = 'testString' + credential_details_model['gateway_id'] = 'testString' + credential_details_model['source_version'] = 'online' + credential_details_model['web_application_url'] = 'testString' + credential_details_model['domain'] = 'testString' + credential_details_model['endpoint'] = 'testString' + credential_details_model['access_key_id'] = 'testString' + credential_details_model['secret_access_key'] = 'testString' + + # Set up parameter values + environment_id = 'testString' + credential_id = 'testString' + source_type = 'box' + credential_details = credential_details_model + status = 'connected' + + # Invoke method + response = service.update_credentials( + environment_id, + credential_id, + source_type=source_type, + credential_details=credential_details, + status=status, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['source_type'] == 'box' + assert req_body['credential_details'] == credential_details_model + assert req_body['status'] == 'connected' + + + @responses.activate + def test_update_credentials_value_error(self): + """ + test_update_credentials_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CredentialDetails model + credential_details_model = {} + credential_details_model['credential_type'] = 'oauth2' + credential_details_model['client_id'] = 'testString' + credential_details_model['enterprise_id'] = 'testString' + credential_details_model['url'] = 'testString' + credential_details_model['username'] = 'testString' + credential_details_model['organization_url'] = 'testString' + credential_details_model['site_collection.path'] = 'testString' + credential_details_model['client_secret'] = 'testString' + credential_details_model['public_key_id'] = 'testString' + credential_details_model['private_key'] = 'testString' + credential_details_model['passphrase'] = 'testString' + credential_details_model['password'] = 'testString' + credential_details_model['gateway_id'] = 'testString' + credential_details_model['source_version'] = 'online' + credential_details_model['web_application_url'] = 'testString' + credential_details_model['domain'] = 'testString' + credential_details_model['endpoint'] = 'testString' + credential_details_model['access_key_id'] = 'testString' + credential_details_model['secret_access_key'] = 'testString' + + # Set up parameter values + environment_id = 'testString' + credential_id = 'testString' + source_type = 'box' + credential_details = credential_details_model + status = 'connected' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "credential_id": credential_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_credentials(**req_copy) + + + +class TestDeleteCredentials(): + """ + Test Class for delete_credentials + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_credentials_all_params(self): + """ + delete_credentials() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + mock_response = '{"credential_id": "credential_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + credential_id = 'testString' + + # Invoke method + response = service.delete_credentials( + environment_id, + credential_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_delete_credentials_value_error(self): + """ + test_delete_credentials_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + mock_response = '{"credential_id": "credential_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + credential_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "credential_id": credential_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_credentials(**req_copy) + + + +# endregion +############################################################################## +# End of Service: Credentials +############################################################################## + +############################################################################## +# Start of Service: GatewayConfiguration +############################################################################## +# region + +class TestListGateways(): + """ + Test Class for list_gateways + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_gateways_all_params(self): + """ + list_gateways() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/gateways') + mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + + # Invoke method + response = service.list_gateways( + environment_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_list_gateways_value_error(self): + """ + test_list_gateways_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/gateways') + mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_gateways(**req_copy) + + + +class TestCreateGateway(): + """ + Test Class for create_gateway + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_gateway_all_params(self): + """ + create_gateway() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/gateways') + mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + name = 'testString' + + # Invoke method + response = service.create_gateway( + environment_id, + name=name, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + + + @responses.activate + def test_create_gateway_required_params(self): + """ + test_create_gateway_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/gateways') + mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + + # Invoke method + response = service.create_gateway( + environment_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + @responses.activate - def test_delete_gateway_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_GatewayDelete_json - send_request(self, body, response) + def test_create_gateway_value_error(self): + """ + test_create_gateway_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/gateways') + mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_gateway(**req_copy) + + + +class TestGetGateway(): + """ + Test Class for get_gateway + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_gateway_all_params(self): + """ + get_gateway() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/gateways/testString') + mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + gateway_id = 'testString' + + # Invoke method + response = service.get_gateway( + environment_id, + gateway_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_gateway_empty(self): - check_empty_required_params(self, fake_response_GatewayDelete_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_gateway_value_error(self): + """ + test_get_gateway_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/gateways/testString') + mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + gateway_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "gateway_id": gateway_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_gateway(**req_copy) + + + +class TestDeleteGateway(): + """ + Test Class for delete_gateway + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_gateway_all_params(self): + """ + delete_gateway() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/gateways/testString') + mock_response = '{"gateway_id": "gateway_id", "status": "status"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + gateway_id = 'testString' - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/environments/{0}/gateways/{1}'.format(body['environment_id'], body['gateway_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Invoke method + response = service.delete_gateway( + environment_id, + gateway_id, + headers={} + ) - def add_mock_response(self, url, response): + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_delete_gateway_value_error(self): + """ + test_delete_gateway_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/environments/testString/gateways/testString') + mock_response = '{"gateway_id": "gateway_id", "status": "status"}' responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version='2019-04-30', - ) - service.set_service_url(base_url) - output = service.delete_gateway(**body) - return output - - def construct_full_body(self): - body = dict() - body['environment_id'] = "string1" - body['gateway_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['environment_id'] = "string1" - body['gateway_id'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + environment_id = 'testString' + gateway_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "environment_id": environment_id, + "gateway_id": gateway_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_gateway(**req_copy) + # endregion @@ -4656,122 +6666,4391 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error - -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error - -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) - -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response - - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string - - """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response - -#################### -## Mock Responses ## -#################### - -fake_response__json = None -fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" -fake_response_ListEnvironmentsResponse_json = """{"environments": []}""" -fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" -fake_response_Environment_json = """{"environment_id": "fake_environment_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "status": "fake_status", "read_only": false, "size": "fake_size", "requested_size": "fake_requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "fake_scope", "status": "fake_status", "status_description": "fake_status_description"}}""" -fake_response_DeleteEnvironmentResponse_json = """{"environment_id": "fake_environment_id", "status": "fake_status"}""" -fake_response_ListCollectionFieldsResponse_json = """{"fields": []}""" -fake_response_Configuration_json = """{"configuration_id": "fake_configuration_id", "name": "fake_name", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "description": "fake_description", "conversions": {"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}, "enrichments": [], "normalizations": [], "source": {"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}}""" -fake_response_ListConfigurationsResponse_json = """{"configurations": []}""" -fake_response_Configuration_json = """{"configuration_id": "fake_configuration_id", "name": "fake_name", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "description": "fake_description", "conversions": {"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}, "enrichments": [], "normalizations": [], "source": {"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}}""" -fake_response_Configuration_json = """{"configuration_id": "fake_configuration_id", "name": "fake_name", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "description": "fake_description", "conversions": {"pdf": {"heading": {"fonts": []}}, "word": {"heading": {"fonts": [], "styles": []}}, "html": {"exclude_tags_completely": [], "exclude_tags_keep_content": [], "keep_content": {"xpaths": []}, "exclude_content": {"xpaths": []}, "keep_tag_attributes": [], "exclude_tag_attributes": []}, "segment": {"enabled": false, "selector_tags": [], "annotated_fields": []}, "json_normalizations": [], "image_text_recognition": true}, "enrichments": [], "normalizations": [], "source": {"type": "fake_type", "credential_id": "fake_credential_id", "schedule": {"enabled": false, "time_zone": "fake_time_zone", "frequency": "fake_frequency"}, "options": {"folders": [], "objects": [], "site_collections": [], "urls": [], "buckets": [], "crawl_all_buckets": false}}}""" -fake_response_DeleteConfigurationResponse_json = """{"configuration_id": "fake_configuration_id", "status": "fake_status", "notices": []}""" -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", "status": "fake_status", "configuration_id": "fake_configuration_id", "language": "fake_language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2017-05-16T13:56:54.957Z", "data_updated": "2017-05-16T13:56:54.957Z"}, "crawl_status": {"source_crawl": {"status": "fake_status", "next_crawl": "2017-05-16T13:56:54.957Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}""" -fake_response_ListCollectionsResponse_json = """{"collections": []}""" -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", "status": "fake_status", "configuration_id": "fake_configuration_id", "language": "fake_language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2017-05-16T13:56:54.957Z", "data_updated": "2017-05-16T13:56:54.957Z"}, "crawl_status": {"source_crawl": {"status": "fake_status", "next_crawl": "2017-05-16T13:56:54.957Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}""" -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", "status": "fake_status", "configuration_id": "fake_configuration_id", "language": "fake_language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2017-05-16T13:56:54.957Z", "data_updated": "2017-05-16T13:56:54.957Z"}, "crawl_status": {"source_crawl": {"status": "fake_status", "next_crawl": "2017-05-16T13:56:54.957Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}""" -fake_response_DeleteCollectionResponse_json = """{"collection_id": "fake_collection_id", "status": "fake_status"}""" -fake_response_ListCollectionFieldsResponse_json = """{"fields": []}""" -fake_response_Expansions_json = """{"expansions": []}""" -fake_response_Expansions_json = """{"expansions": []}""" -fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" -fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" -fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" -fake_response_TokenDictStatusResponse_json = """{"status": "fake_status", "type": "fake_type"}""" -fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status", "notices": []}""" -fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "configuration_id": "fake_configuration_id", "status": "fake_status", "status_description": "fake_status_description", "filename": "fake_filename", "file_type": "fake_file_type", "sha1": "fake_sha1", "notices": []}""" -fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status", "notices": []}""" -fake_response_DeleteDocumentResponse_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" -fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18, "session_token": "fake_session_token", "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query"}""" -fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18}""" -fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18, "session_token": "fake_session_token", "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query"}""" -fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "passages": [], "duplicates_removed": 18}""" -fake_response_Completions_json = """{"completions": []}""" -fake_response_TrainingDataSet_json = """{"environment_id": "fake_environment_id", "collection_id": "fake_collection_id", "queries": []}""" -fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" -fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "examples": []}""" -fake_response_TrainingExampleList_json = """{"examples": []}""" -fake_response_TrainingExample_json = """{"document_id": "fake_document_id", "cross_reference": "fake_cross_reference", "relevance": 9}""" -fake_response_TrainingExample_json = """{"document_id": "fake_document_id", "cross_reference": "fake_cross_reference", "relevance": 9}""" -fake_response_TrainingExample_json = """{"document_id": "fake_document_id", "cross_reference": "fake_cross_reference", "relevance": 9}""" -fake_response_CreateEventResponse_json = """{"type": "fake_type", "data": {"environment_id": "fake_environment_id", "session_token": "fake_session_token", "client_timestamp": "2017-05-16T13:56:54.957Z", "display_rank": 12, "collection_id": "fake_collection_id", "document_id": "fake_document_id", "query_id": "fake_query_id"}}""" -fake_response_LogQueryResponse_json = """{"matching_results": 16, "results": []}""" -fake_response_MetricResponse_json = """{"aggregations": []}""" -fake_response_MetricResponse_json = """{"aggregations": []}""" -fake_response_MetricResponse_json = """{"aggregations": []}""" -fake_response_MetricResponse_json = """{"aggregations": []}""" -fake_response_MetricTokenResponse_json = """{"aggregations": []}""" -fake_response_CredentialsList_json = """{"credentials": []}""" -fake_response_Credentials_json = """{"credential_id": "fake_credential_id", "source_type": "fake_source_type", "credential_details": {"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}, "status": "fake_status"}""" -fake_response_Credentials_json = """{"credential_id": "fake_credential_id", "source_type": "fake_source_type", "credential_details": {"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}, "status": "fake_status"}""" -fake_response_Credentials_json = """{"credential_id": "fake_credential_id", "source_type": "fake_source_type", "credential_details": {"credential_type": "fake_credential_type", "client_id": "fake_client_id", "enterprise_id": "fake_enterprise_id", "url": "fake_url", "username": "fake_username", "organization_url": "fake_organization_url", "site_collection.path": "fake_site_collection_path", "client_secret": "fake_client_secret", "public_key_id": "fake_public_key_id", "private_key": "fake_private_key", "passphrase": "fake_passphrase", "password": "fake_password", "gateway_id": "fake_gateway_id", "source_version": "fake_source_version", "web_application_url": "fake_web_application_url", "domain": "fake_domain", "endpoint": "fake_endpoint", "access_key_id": "fake_access_key_id", "secret_access_key": "fake_secret_access_key"}, "status": "fake_status"}""" -fake_response_DeleteCredentials_json = """{"credential_id": "fake_credential_id", "status": "fake_status"}""" -fake_response_GatewayList_json = """{"gateways": []}""" -fake_response_Gateway_json = """{"gateway_id": "fake_gateway_id", "name": "fake_name", "status": "fake_status", "token": "fake_token", "token_id": "fake_token_id"}""" -fake_response_Gateway_json = """{"gateway_id": "fake_gateway_id", "name": "fake_name", "status": "fake_status", "token": "fake_token", "token_id": "fake_token_id"}""" -fake_response_GatewayDelete_json = """{"gateway_id": "fake_gateway_id", "status": "fake_status"}""" +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestAggregationResult(): + """ + Test Class for AggregationResult + """ + + def test_aggregation_result_serialization(self): + """ + Test serialization/deserialization for AggregationResult + """ + + # Construct a json representation of a AggregationResult model + aggregation_result_model_json = {} + aggregation_result_model_json['key'] = 'testString' + aggregation_result_model_json['matching_results'] = 38 + + # Construct a model instance of AggregationResult by calling from_dict on the json representation + aggregation_result_model = AggregationResult.from_dict(aggregation_result_model_json) + assert aggregation_result_model != False + + # Construct a model instance of AggregationResult by calling from_dict on the json representation + aggregation_result_model_dict = AggregationResult.from_dict(aggregation_result_model_json).__dict__ + aggregation_result_model2 = AggregationResult(**aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert aggregation_result_model == aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + aggregation_result_model_json2 = aggregation_result_model.to_dict() + assert aggregation_result_model_json2 == aggregation_result_model_json + +class TestCollection(): + """ + Test Class for Collection + """ + + def test_collection_serialization(self): + """ + Test serialization/deserialization for Collection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_counts_model = {} # DocumentCounts + document_counts_model['available'] = 0 + document_counts_model['processing'] = 0 + document_counts_model['failed'] = 0 + document_counts_model['pending'] = 26 + + collection_disk_usage_model = {} # CollectionDiskUsage + collection_disk_usage_model['used_bytes'] = 260 + + training_status_model = {} # TrainingStatus + training_status_model['total_examples'] = 0 + training_status_model['available'] = False + training_status_model['processing'] = False + training_status_model['minimum_queries_added'] = False + training_status_model['minimum_examples_added'] = False + training_status_model['sufficient_label_diversity'] = False + training_status_model['notices'] = 0 + training_status_model['successfully_trained'] = '2020-01-28T18:40:40.123456Z' + training_status_model['data_updated'] = '2020-01-28T18:40:40.123456Z' + + source_status_model = {} # SourceStatus + source_status_model['status'] = 'complete' + source_status_model['next_crawl'] = '2020-01-28T18:40:40.123456Z' + + collection_crawl_status_model = {} # CollectionCrawlStatus + collection_crawl_status_model['source_crawl'] = source_status_model + + sdu_status_custom_fields_model = {} # SduStatusCustomFields + sdu_status_custom_fields_model['defined'] = 26 + sdu_status_custom_fields_model['maximum_allowed'] = 5 + + sdu_status_model = {} # SduStatus + sdu_status_model['enabled'] = True + sdu_status_model['total_annotated_pages'] = 0 + sdu_status_model['total_pages'] = 0 + sdu_status_model['total_documents'] = 0 + sdu_status_model['custom_fields'] = sdu_status_custom_fields_model + + # Construct a json representation of a Collection model + collection_model_json = {} + collection_model_json['collection_id'] = 'testString' + collection_model_json['name'] = 'testString' + collection_model_json['description'] = 'testString' + collection_model_json['created'] = '2020-01-28T18:40:40.123456Z' + collection_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + collection_model_json['status'] = 'active' + collection_model_json['configuration_id'] = 'testString' + collection_model_json['language'] = 'testString' + collection_model_json['document_counts'] = document_counts_model + collection_model_json['disk_usage'] = collection_disk_usage_model + collection_model_json['training_status'] = training_status_model + collection_model_json['crawl_status'] = collection_crawl_status_model + collection_model_json['smart_document_understanding'] = sdu_status_model + + # Construct a model instance of Collection by calling from_dict on the json representation + collection_model = Collection.from_dict(collection_model_json) + assert collection_model != False + + # Construct a model instance of Collection by calling from_dict on the json representation + collection_model_dict = Collection.from_dict(collection_model_json).__dict__ + collection_model2 = Collection(**collection_model_dict) + + # Verify the model instances are equivalent + assert collection_model == collection_model2 + + # Convert model instance back to dict and verify no loss of data + collection_model_json2 = collection_model.to_dict() + assert collection_model_json2 == collection_model_json + +class TestCollectionCrawlStatus(): + """ + Test Class for CollectionCrawlStatus + """ + + def test_collection_crawl_status_serialization(self): + """ + Test serialization/deserialization for CollectionCrawlStatus + """ + + # Construct dict forms of any model objects needed in order to build this model. + + source_status_model = {} # SourceStatus + source_status_model['status'] = 'running' + source_status_model['next_crawl'] = '2020-01-28T18:40:40.123456Z' + + # Construct a json representation of a CollectionCrawlStatus model + collection_crawl_status_model_json = {} + collection_crawl_status_model_json['source_crawl'] = source_status_model + + # Construct a model instance of CollectionCrawlStatus by calling from_dict on the json representation + collection_crawl_status_model = CollectionCrawlStatus.from_dict(collection_crawl_status_model_json) + assert collection_crawl_status_model != False + + # Construct a model instance of CollectionCrawlStatus by calling from_dict on the json representation + collection_crawl_status_model_dict = CollectionCrawlStatus.from_dict(collection_crawl_status_model_json).__dict__ + collection_crawl_status_model2 = CollectionCrawlStatus(**collection_crawl_status_model_dict) + + # Verify the model instances are equivalent + assert collection_crawl_status_model == collection_crawl_status_model2 + + # Convert model instance back to dict and verify no loss of data + collection_crawl_status_model_json2 = collection_crawl_status_model.to_dict() + assert collection_crawl_status_model_json2 == collection_crawl_status_model_json + +class TestCollectionDiskUsage(): + """ + Test Class for CollectionDiskUsage + """ + + def test_collection_disk_usage_serialization(self): + """ + Test serialization/deserialization for CollectionDiskUsage + """ + + # Construct a json representation of a CollectionDiskUsage model + collection_disk_usage_model_json = {} + collection_disk_usage_model_json['used_bytes'] = 38 + + # Construct a model instance of CollectionDiskUsage by calling from_dict on the json representation + collection_disk_usage_model = CollectionDiskUsage.from_dict(collection_disk_usage_model_json) + assert collection_disk_usage_model != False + + # Construct a model instance of CollectionDiskUsage by calling from_dict on the json representation + collection_disk_usage_model_dict = CollectionDiskUsage.from_dict(collection_disk_usage_model_json).__dict__ + collection_disk_usage_model2 = CollectionDiskUsage(**collection_disk_usage_model_dict) + + # Verify the model instances are equivalent + assert collection_disk_usage_model == collection_disk_usage_model2 + + # Convert model instance back to dict and verify no loss of data + collection_disk_usage_model_json2 = collection_disk_usage_model.to_dict() + assert collection_disk_usage_model_json2 == collection_disk_usage_model_json + +class TestCollectionUsage(): + """ + Test Class for CollectionUsage + """ + + def test_collection_usage_serialization(self): + """ + Test serialization/deserialization for CollectionUsage + """ + + # Construct a json representation of a CollectionUsage model + collection_usage_model_json = {} + collection_usage_model_json['available'] = 38 + collection_usage_model_json['maximum_allowed'] = 38 + + # Construct a model instance of CollectionUsage by calling from_dict on the json representation + collection_usage_model = CollectionUsage.from_dict(collection_usage_model_json) + assert collection_usage_model != False + + # Construct a model instance of CollectionUsage by calling from_dict on the json representation + collection_usage_model_dict = CollectionUsage.from_dict(collection_usage_model_json).__dict__ + collection_usage_model2 = CollectionUsage(**collection_usage_model_dict) + + # Verify the model instances are equivalent + assert collection_usage_model == collection_usage_model2 + + # Convert model instance back to dict and verify no loss of data + collection_usage_model_json2 = collection_usage_model.to_dict() + assert collection_usage_model_json2 == collection_usage_model_json + +class TestCompletions(): + """ + Test Class for Completions + """ + + def test_completions_serialization(self): + """ + Test serialization/deserialization for Completions + """ + + # Construct a json representation of a Completions model + completions_model_json = {} + completions_model_json['completions'] = ['testString'] + + # Construct a model instance of Completions by calling from_dict on the json representation + completions_model = Completions.from_dict(completions_model_json) + assert completions_model != False + + # Construct a model instance of Completions by calling from_dict on the json representation + completions_model_dict = Completions.from_dict(completions_model_json).__dict__ + completions_model2 = Completions(**completions_model_dict) + + # Verify the model instances are equivalent + assert completions_model == completions_model2 + + # Convert model instance back to dict and verify no loss of data + completions_model_json2 = completions_model.to_dict() + assert completions_model_json2 == completions_model_json + +class TestConfiguration(): + """ + Test Class for Configuration + """ + + def test_configuration_serialization(self): + """ + Test serialization/deserialization for Configuration + """ + + # Construct dict forms of any model objects needed in order to build this model. + + font_setting_model = {} # FontSetting + font_setting_model['level'] = 38 + font_setting_model['min_size'] = 38 + font_setting_model['max_size'] = 38 + font_setting_model['bold'] = True + font_setting_model['italic'] = True + font_setting_model['name'] = 'testString' + + pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model['fonts'] = [font_setting_model] + + pdf_settings_model = {} # PdfSettings + pdf_settings_model['heading'] = pdf_heading_detection_model + + word_style_model = {} # WordStyle + word_style_model['level'] = 38 + word_style_model['names'] = ['testString'] + + word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model['fonts'] = [font_setting_model] + word_heading_detection_model['styles'] = [word_style_model] + + word_settings_model = {} # WordSettings + word_settings_model['heading'] = word_heading_detection_model + + x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model['xpaths'] = ['testString'] + + html_settings_model = {} # HtmlSettings + html_settings_model['exclude_tags_completely'] = ['testString'] + html_settings_model['exclude_tags_keep_content'] = ['testString'] + html_settings_model['keep_content'] = x_path_patterns_model + html_settings_model['exclude_content'] = x_path_patterns_model + html_settings_model['keep_tag_attributes'] = ['testString'] + html_settings_model['exclude_tag_attributes'] = ['testString'] + + segment_settings_model = {} # SegmentSettings + segment_settings_model['enabled'] = True + segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['annotated_fields'] = ['testString'] + + normalization_operation_model = {} # NormalizationOperation + normalization_operation_model['operation'] = 'move' + normalization_operation_model['source_field'] = 'extracted_metadata.title' + normalization_operation_model['destination_field'] = 'metadata.title' + + conversions_model = {} # Conversions + conversions_model['pdf'] = pdf_settings_model + conversions_model['word'] = word_settings_model + conversions_model['html'] = html_settings_model + conversions_model['segment'] = segment_settings_model + conversions_model['json_normalizations'] = [normalization_operation_model] + conversions_model['image_text_recognition'] = True + + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model['sentiment'] = True + nlu_enrichment_keywords_model['emotion'] = False + nlu_enrichment_keywords_model['limit'] = 50 + + nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model['sentiment'] = True + nlu_enrichment_entities_model['emotion'] = False + nlu_enrichment_entities_model['limit'] = 50 + nlu_enrichment_entities_model['mentions'] = True + nlu_enrichment_entities_model['mention_types'] = True + nlu_enrichment_entities_model['sentence_locations'] = True + nlu_enrichment_entities_model['model'] = 'WKS-model-id' + + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model['document'] = True + nlu_enrichment_sentiment_model['targets'] = ['testString'] + + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model['document'] = True + nlu_enrichment_emotion_model['targets'] = ['testString'] + + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model['entities'] = True + nlu_enrichment_semantic_roles_model['keywords'] = True + nlu_enrichment_semantic_roles_model['limit'] = 50 + + nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model['model'] = 'WKS-model-id' + + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model['limit'] = 8 + + nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model + nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model + nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model + nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model + nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model + nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model + nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model + + enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model['features'] = nlu_enrichment_features_model + enrichment_options_model['language'] = 'ar' + enrichment_options_model['model'] = 'testString' + + enrichment_model = {} # Enrichment + enrichment_model['description'] = 'testString' + enrichment_model['destination_field'] = 'enriched_title' + enrichment_model['source_field'] = 'title' + enrichment_model['overwrite'] = True + enrichment_model['enrichment'] = 'natural_language_understanding' + enrichment_model['ignore_downstream_errors'] = True + enrichment_model['options'] = enrichment_options_model + + source_schedule_model = {} # SourceSchedule + source_schedule_model['enabled'] = True + source_schedule_model['time_zone'] = 'America/New_York' + source_schedule_model['frequency'] = 'weekly' + + source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model['owner_user_id'] = 'testString' + source_options_folder_model['folder_id'] = 'testString' + source_options_folder_model['limit'] = 38 + + source_options_object_model = {} # SourceOptionsObject + source_options_object_model['name'] = 'testString' + source_options_object_model['limit'] = 38 + + source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model['site_collection_path'] = '/sites/TestSiteA' + source_options_site_coll_model['limit'] = 10 + + source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model['url'] = 'testString' + source_options_web_crawl_model['limit_to_starting_hosts'] = True + source_options_web_crawl_model['crawl_speed'] = 'gentle' + source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['maximum_hops'] = 38 + source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['blacklist'] = ['testString'] + + source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model['name'] = 'testString' + source_options_buckets_model['limit'] = 38 + + source_options_model = {} # SourceOptions + source_options_model['folders'] = [source_options_folder_model] + source_options_model['objects'] = [source_options_object_model] + source_options_model['site_collections'] = [source_options_site_coll_model] + source_options_model['urls'] = [source_options_web_crawl_model] + source_options_model['buckets'] = [source_options_buckets_model] + source_options_model['crawl_all_buckets'] = True + + source_model = {} # Source + source_model['type'] = 'salesforce' + source_model['credential_id'] = '00ad0000-0000-11e8-ba89-0ed5f00f718b' + source_model['schedule'] = source_schedule_model + source_model['options'] = source_options_model + + # Construct a json representation of a Configuration model + configuration_model_json = {} + configuration_model_json['configuration_id'] = 'testString' + configuration_model_json['name'] = 'testString' + configuration_model_json['created'] = '2020-01-28T18:40:40.123456Z' + configuration_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + configuration_model_json['description'] = 'testString' + configuration_model_json['conversions'] = conversions_model + configuration_model_json['enrichments'] = [enrichment_model] + configuration_model_json['normalizations'] = [normalization_operation_model] + configuration_model_json['source'] = source_model + + # Construct a model instance of Configuration by calling from_dict on the json representation + configuration_model = Configuration.from_dict(configuration_model_json) + assert configuration_model != False + + # Construct a model instance of Configuration by calling from_dict on the json representation + configuration_model_dict = Configuration.from_dict(configuration_model_json).__dict__ + configuration_model2 = Configuration(**configuration_model_dict) + + # Verify the model instances are equivalent + assert configuration_model == configuration_model2 + + # Convert model instance back to dict and verify no loss of data + configuration_model_json2 = configuration_model.to_dict() + assert configuration_model_json2 == configuration_model_json + +class TestConversions(): + """ + Test Class for Conversions + """ + + def test_conversions_serialization(self): + """ + Test serialization/deserialization for Conversions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + font_setting_model = {} # FontSetting + font_setting_model['level'] = 38 + font_setting_model['min_size'] = 38 + font_setting_model['max_size'] = 38 + font_setting_model['bold'] = True + font_setting_model['italic'] = True + font_setting_model['name'] = 'testString' + + pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model['fonts'] = [font_setting_model] + + pdf_settings_model = {} # PdfSettings + pdf_settings_model['heading'] = pdf_heading_detection_model + + word_style_model = {} # WordStyle + word_style_model['level'] = 38 + word_style_model['names'] = ['testString'] + + word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model['fonts'] = [font_setting_model] + word_heading_detection_model['styles'] = [word_style_model] + + word_settings_model = {} # WordSettings + word_settings_model['heading'] = word_heading_detection_model + + x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model['xpaths'] = ['testString'] + + html_settings_model = {} # HtmlSettings + html_settings_model['exclude_tags_completely'] = ['testString'] + html_settings_model['exclude_tags_keep_content'] = ['testString'] + html_settings_model['keep_content'] = x_path_patterns_model + html_settings_model['exclude_content'] = x_path_patterns_model + html_settings_model['keep_tag_attributes'] = ['testString'] + html_settings_model['exclude_tag_attributes'] = ['testString'] + + segment_settings_model = {} # SegmentSettings + segment_settings_model['enabled'] = True + segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['annotated_fields'] = ['testString'] + + normalization_operation_model = {} # NormalizationOperation + normalization_operation_model['operation'] = 'copy' + normalization_operation_model['source_field'] = 'testString' + normalization_operation_model['destination_field'] = 'testString' + + # Construct a json representation of a Conversions model + conversions_model_json = {} + conversions_model_json['pdf'] = pdf_settings_model + conversions_model_json['word'] = word_settings_model + conversions_model_json['html'] = html_settings_model + conversions_model_json['segment'] = segment_settings_model + conversions_model_json['json_normalizations'] = [normalization_operation_model] + conversions_model_json['image_text_recognition'] = True + + # Construct a model instance of Conversions by calling from_dict on the json representation + conversions_model = Conversions.from_dict(conversions_model_json) + assert conversions_model != False + + # Construct a model instance of Conversions by calling from_dict on the json representation + conversions_model_dict = Conversions.from_dict(conversions_model_json).__dict__ + conversions_model2 = Conversions(**conversions_model_dict) + + # Verify the model instances are equivalent + assert conversions_model == conversions_model2 + + # Convert model instance back to dict and verify no loss of data + conversions_model_json2 = conversions_model.to_dict() + assert conversions_model_json2 == conversions_model_json + +class TestCreateEventResponse(): + """ + Test Class for CreateEventResponse + """ + + def test_create_event_response_serialization(self): + """ + Test serialization/deserialization for CreateEventResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + event_data_model = {} # EventData + event_data_model['environment_id'] = 'testString' + event_data_model['session_token'] = 'testString' + event_data_model['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + event_data_model['display_rank'] = 38 + event_data_model['collection_id'] = 'testString' + event_data_model['document_id'] = 'testString' + event_data_model['query_id'] = 'testString' + + # Construct a json representation of a CreateEventResponse model + create_event_response_model_json = {} + create_event_response_model_json['type'] = 'click' + create_event_response_model_json['data'] = event_data_model + + # Construct a model instance of CreateEventResponse by calling from_dict on the json representation + create_event_response_model = CreateEventResponse.from_dict(create_event_response_model_json) + assert create_event_response_model != False + + # Construct a model instance of CreateEventResponse by calling from_dict on the json representation + create_event_response_model_dict = CreateEventResponse.from_dict(create_event_response_model_json).__dict__ + create_event_response_model2 = CreateEventResponse(**create_event_response_model_dict) + + # Verify the model instances are equivalent + assert create_event_response_model == create_event_response_model2 + + # Convert model instance back to dict and verify no loss of data + create_event_response_model_json2 = create_event_response_model.to_dict() + assert create_event_response_model_json2 == create_event_response_model_json + +class TestCredentialDetails(): + """ + Test Class for CredentialDetails + """ + + def test_credential_details_serialization(self): + """ + Test serialization/deserialization for CredentialDetails + """ + + # Construct a json representation of a CredentialDetails model + credential_details_model_json = {} + credential_details_model_json['credential_type'] = 'oauth2' + credential_details_model_json['client_id'] = 'testString' + credential_details_model_json['enterprise_id'] = 'testString' + credential_details_model_json['url'] = 'testString' + credential_details_model_json['username'] = 'testString' + credential_details_model_json['organization_url'] = 'testString' + credential_details_model_json['site_collection.path'] = 'testString' + credential_details_model_json['client_secret'] = 'testString' + credential_details_model_json['public_key_id'] = 'testString' + credential_details_model_json['private_key'] = 'testString' + credential_details_model_json['passphrase'] = 'testString' + credential_details_model_json['password'] = 'testString' + credential_details_model_json['gateway_id'] = 'testString' + credential_details_model_json['source_version'] = 'online' + credential_details_model_json['web_application_url'] = 'testString' + credential_details_model_json['domain'] = 'testString' + credential_details_model_json['endpoint'] = 'testString' + credential_details_model_json['access_key_id'] = 'testString' + credential_details_model_json['secret_access_key'] = 'testString' + + # Construct a model instance of CredentialDetails by calling from_dict on the json representation + credential_details_model = CredentialDetails.from_dict(credential_details_model_json) + assert credential_details_model != False + + # Construct a model instance of CredentialDetails by calling from_dict on the json representation + credential_details_model_dict = CredentialDetails.from_dict(credential_details_model_json).__dict__ + credential_details_model2 = CredentialDetails(**credential_details_model_dict) + + # Verify the model instances are equivalent + assert credential_details_model == credential_details_model2 + + # Convert model instance back to dict and verify no loss of data + credential_details_model_json2 = credential_details_model.to_dict() + assert credential_details_model_json2 == credential_details_model_json + +class TestCredentials(): + """ + Test Class for Credentials + """ + + def test_credentials_serialization(self): + """ + Test serialization/deserialization for Credentials + """ + + # Construct dict forms of any model objects needed in order to build this model. + + credential_details_model = {} # CredentialDetails + credential_details_model['credential_type'] = 'username_password' + credential_details_model['client_id'] = 'testString' + credential_details_model['enterprise_id'] = 'testString' + credential_details_model['url'] = 'login.salesforce.com' + credential_details_model['username'] = 'user@email.address' + credential_details_model['organization_url'] = 'testString' + credential_details_model['site_collection.path'] = 'testString' + credential_details_model['client_secret'] = 'testString' + credential_details_model['public_key_id'] = 'testString' + credential_details_model['private_key'] = 'testString' + credential_details_model['passphrase'] = 'testString' + credential_details_model['password'] = 'testString' + credential_details_model['gateway_id'] = 'testString' + credential_details_model['source_version'] = 'online' + credential_details_model['web_application_url'] = 'testString' + credential_details_model['domain'] = 'testString' + credential_details_model['endpoint'] = 'testString' + credential_details_model['access_key_id'] = 'testString' + credential_details_model['secret_access_key'] = 'testString' + + # Construct a json representation of a Credentials model + credentials_model_json = {} + credentials_model_json['credential_id'] = 'testString' + credentials_model_json['source_type'] = 'box' + credentials_model_json['credential_details'] = credential_details_model + credentials_model_json['status'] = 'connected' + + # Construct a model instance of Credentials by calling from_dict on the json representation + credentials_model = Credentials.from_dict(credentials_model_json) + assert credentials_model != False + + # Construct a model instance of Credentials by calling from_dict on the json representation + credentials_model_dict = Credentials.from_dict(credentials_model_json).__dict__ + credentials_model2 = Credentials(**credentials_model_dict) + + # Verify the model instances are equivalent + assert credentials_model == credentials_model2 + + # Convert model instance back to dict and verify no loss of data + credentials_model_json2 = credentials_model.to_dict() + assert credentials_model_json2 == credentials_model_json + +class TestCredentialsList(): + """ + Test Class for CredentialsList + """ + + def test_credentials_list_serialization(self): + """ + Test serialization/deserialization for CredentialsList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + credential_details_model = {} # CredentialDetails + credential_details_model['credential_type'] = 'username_password' + credential_details_model['client_id'] = 'testString' + credential_details_model['enterprise_id'] = 'testString' + credential_details_model['url'] = 'login.salesforce.com' + credential_details_model['username'] = 'user@email.address' + credential_details_model['organization_url'] = 'testString' + credential_details_model['site_collection.path'] = 'testString' + credential_details_model['client_secret'] = 'testString' + credential_details_model['public_key_id'] = 'testString' + credential_details_model['private_key'] = 'testString' + credential_details_model['passphrase'] = 'testString' + credential_details_model['password'] = 'testString' + credential_details_model['gateway_id'] = 'testString' + credential_details_model['source_version'] = 'online' + credential_details_model['web_application_url'] = 'testString' + credential_details_model['domain'] = 'testString' + credential_details_model['endpoint'] = 'testString' + credential_details_model['access_key_id'] = 'testString' + credential_details_model['secret_access_key'] = 'testString' + + credentials_model = {} # Credentials + credentials_model['credential_id'] = '00000d8c-0000-00e8-ba89-0ed5f89f718b' + credentials_model['source_type'] = 'salesforce' + credentials_model['credential_details'] = credential_details_model + credentials_model['status'] = 'connected' + + # Construct a json representation of a CredentialsList model + credentials_list_model_json = {} + credentials_list_model_json['credentials'] = [credentials_model] + + # Construct a model instance of CredentialsList by calling from_dict on the json representation + credentials_list_model = CredentialsList.from_dict(credentials_list_model_json) + assert credentials_list_model != False + + # Construct a model instance of CredentialsList by calling from_dict on the json representation + credentials_list_model_dict = CredentialsList.from_dict(credentials_list_model_json).__dict__ + credentials_list_model2 = CredentialsList(**credentials_list_model_dict) + + # Verify the model instances are equivalent + assert credentials_list_model == credentials_list_model2 + + # Convert model instance back to dict and verify no loss of data + credentials_list_model_json2 = credentials_list_model.to_dict() + assert credentials_list_model_json2 == credentials_list_model_json + +class TestDeleteCollectionResponse(): + """ + Test Class for DeleteCollectionResponse + """ + + def test_delete_collection_response_serialization(self): + """ + Test serialization/deserialization for DeleteCollectionResponse + """ + + # Construct a json representation of a DeleteCollectionResponse model + delete_collection_response_model_json = {} + delete_collection_response_model_json['collection_id'] = 'testString' + delete_collection_response_model_json['status'] = 'deleted' + + # Construct a model instance of DeleteCollectionResponse by calling from_dict on the json representation + delete_collection_response_model = DeleteCollectionResponse.from_dict(delete_collection_response_model_json) + assert delete_collection_response_model != False + + # Construct a model instance of DeleteCollectionResponse by calling from_dict on the json representation + delete_collection_response_model_dict = DeleteCollectionResponse.from_dict(delete_collection_response_model_json).__dict__ + delete_collection_response_model2 = DeleteCollectionResponse(**delete_collection_response_model_dict) + + # Verify the model instances are equivalent + assert delete_collection_response_model == delete_collection_response_model2 + + # Convert model instance back to dict and verify no loss of data + delete_collection_response_model_json2 = delete_collection_response_model.to_dict() + assert delete_collection_response_model_json2 == delete_collection_response_model_json + +class TestDeleteConfigurationResponse(): + """ + Test Class for DeleteConfigurationResponse + """ + + def test_delete_configuration_response_serialization(self): + """ + Test serialization/deserialization for DeleteConfigurationResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['notice_id'] = 'configuration_in_use' + notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['document_id'] = 'testString' + notice_model['query_id'] = 'testString' + notice_model['severity'] = 'warning' + notice_model['step'] = 'testString' + notice_model['description'] = 'The configuration was deleted, but it is referenced by one or more collections.' + + # Construct a json representation of a DeleteConfigurationResponse model + delete_configuration_response_model_json = {} + delete_configuration_response_model_json['configuration_id'] = 'testString' + delete_configuration_response_model_json['status'] = 'deleted' + delete_configuration_response_model_json['notices'] = [notice_model] + + # Construct a model instance of DeleteConfigurationResponse by calling from_dict on the json representation + delete_configuration_response_model = DeleteConfigurationResponse.from_dict(delete_configuration_response_model_json) + assert delete_configuration_response_model != False + + # Construct a model instance of DeleteConfigurationResponse by calling from_dict on the json representation + delete_configuration_response_model_dict = DeleteConfigurationResponse.from_dict(delete_configuration_response_model_json).__dict__ + delete_configuration_response_model2 = DeleteConfigurationResponse(**delete_configuration_response_model_dict) + + # Verify the model instances are equivalent + assert delete_configuration_response_model == delete_configuration_response_model2 + + # Convert model instance back to dict and verify no loss of data + delete_configuration_response_model_json2 = delete_configuration_response_model.to_dict() + assert delete_configuration_response_model_json2 == delete_configuration_response_model_json + +class TestDeleteCredentials(): + """ + Test Class for DeleteCredentials + """ + + def test_delete_credentials_serialization(self): + """ + Test serialization/deserialization for DeleteCredentials + """ + + # Construct a json representation of a DeleteCredentials model + delete_credentials_model_json = {} + delete_credentials_model_json['credential_id'] = 'testString' + delete_credentials_model_json['status'] = 'deleted' + + # Construct a model instance of DeleteCredentials by calling from_dict on the json representation + delete_credentials_model = DeleteCredentials.from_dict(delete_credentials_model_json) + assert delete_credentials_model != False + + # Construct a model instance of DeleteCredentials by calling from_dict on the json representation + delete_credentials_model_dict = DeleteCredentials.from_dict(delete_credentials_model_json).__dict__ + delete_credentials_model2 = DeleteCredentials(**delete_credentials_model_dict) + + # Verify the model instances are equivalent + assert delete_credentials_model == delete_credentials_model2 + + # Convert model instance back to dict and verify no loss of data + delete_credentials_model_json2 = delete_credentials_model.to_dict() + assert delete_credentials_model_json2 == delete_credentials_model_json + +class TestDeleteDocumentResponse(): + """ + Test Class for DeleteDocumentResponse + """ + + def test_delete_document_response_serialization(self): + """ + Test serialization/deserialization for DeleteDocumentResponse + """ + + # Construct a json representation of a DeleteDocumentResponse model + delete_document_response_model_json = {} + delete_document_response_model_json['document_id'] = 'testString' + delete_document_response_model_json['status'] = 'deleted' + + # Construct a model instance of DeleteDocumentResponse by calling from_dict on the json representation + delete_document_response_model = DeleteDocumentResponse.from_dict(delete_document_response_model_json) + assert delete_document_response_model != False + + # Construct a model instance of DeleteDocumentResponse by calling from_dict on the json representation + delete_document_response_model_dict = DeleteDocumentResponse.from_dict(delete_document_response_model_json).__dict__ + delete_document_response_model2 = DeleteDocumentResponse(**delete_document_response_model_dict) + + # Verify the model instances are equivalent + assert delete_document_response_model == delete_document_response_model2 + + # Convert model instance back to dict and verify no loss of data + delete_document_response_model_json2 = delete_document_response_model.to_dict() + assert delete_document_response_model_json2 == delete_document_response_model_json + +class TestDeleteEnvironmentResponse(): + """ + Test Class for DeleteEnvironmentResponse + """ + + def test_delete_environment_response_serialization(self): + """ + Test serialization/deserialization for DeleteEnvironmentResponse + """ + + # Construct a json representation of a DeleteEnvironmentResponse model + delete_environment_response_model_json = {} + delete_environment_response_model_json['environment_id'] = 'testString' + delete_environment_response_model_json['status'] = 'deleted' + + # Construct a model instance of DeleteEnvironmentResponse by calling from_dict on the json representation + delete_environment_response_model = DeleteEnvironmentResponse.from_dict(delete_environment_response_model_json) + assert delete_environment_response_model != False + + # Construct a model instance of DeleteEnvironmentResponse by calling from_dict on the json representation + delete_environment_response_model_dict = DeleteEnvironmentResponse.from_dict(delete_environment_response_model_json).__dict__ + delete_environment_response_model2 = DeleteEnvironmentResponse(**delete_environment_response_model_dict) + + # Verify the model instances are equivalent + assert delete_environment_response_model == delete_environment_response_model2 + + # Convert model instance back to dict and verify no loss of data + delete_environment_response_model_json2 = delete_environment_response_model.to_dict() + assert delete_environment_response_model_json2 == delete_environment_response_model_json + +class TestDiskUsage(): + """ + Test Class for DiskUsage + """ + + def test_disk_usage_serialization(self): + """ + Test serialization/deserialization for DiskUsage + """ + + # Construct a json representation of a DiskUsage model + disk_usage_model_json = {} + disk_usage_model_json['used_bytes'] = 38 + disk_usage_model_json['maximum_allowed_bytes'] = 38 + + # Construct a model instance of DiskUsage by calling from_dict on the json representation + disk_usage_model = DiskUsage.from_dict(disk_usage_model_json) + assert disk_usage_model != False + + # Construct a model instance of DiskUsage by calling from_dict on the json representation + disk_usage_model_dict = DiskUsage.from_dict(disk_usage_model_json).__dict__ + disk_usage_model2 = DiskUsage(**disk_usage_model_dict) + + # Verify the model instances are equivalent + assert disk_usage_model == disk_usage_model2 + + # Convert model instance back to dict and verify no loss of data + disk_usage_model_json2 = disk_usage_model.to_dict() + assert disk_usage_model_json2 == disk_usage_model_json + +class TestDocumentAccepted(): + """ + Test Class for DocumentAccepted + """ + + def test_document_accepted_serialization(self): + """ + Test serialization/deserialization for DocumentAccepted + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['notice_id'] = 'testString' + notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['document_id'] = 'testString' + notice_model['query_id'] = 'testString' + notice_model['severity'] = 'warning' + notice_model['step'] = 'testString' + notice_model['description'] = 'testString' + + # Construct a json representation of a DocumentAccepted model + document_accepted_model_json = {} + document_accepted_model_json['document_id'] = 'testString' + document_accepted_model_json['status'] = 'processing' + document_accepted_model_json['notices'] = [notice_model] + + # Construct a model instance of DocumentAccepted by calling from_dict on the json representation + document_accepted_model = DocumentAccepted.from_dict(document_accepted_model_json) + assert document_accepted_model != False + + # Construct a model instance of DocumentAccepted by calling from_dict on the json representation + document_accepted_model_dict = DocumentAccepted.from_dict(document_accepted_model_json).__dict__ + document_accepted_model2 = DocumentAccepted(**document_accepted_model_dict) + + # Verify the model instances are equivalent + assert document_accepted_model == document_accepted_model2 + + # Convert model instance back to dict and verify no loss of data + document_accepted_model_json2 = document_accepted_model.to_dict() + assert document_accepted_model_json2 == document_accepted_model_json + +class TestDocumentCounts(): + """ + Test Class for DocumentCounts + """ + + def test_document_counts_serialization(self): + """ + Test serialization/deserialization for DocumentCounts + """ + + # Construct a json representation of a DocumentCounts model + document_counts_model_json = {} + document_counts_model_json['available'] = 26 + document_counts_model_json['processing'] = 26 + document_counts_model_json['failed'] = 26 + document_counts_model_json['pending'] = 26 + + # Construct a model instance of DocumentCounts by calling from_dict on the json representation + document_counts_model = DocumentCounts.from_dict(document_counts_model_json) + assert document_counts_model != False + + # Construct a model instance of DocumentCounts by calling from_dict on the json representation + document_counts_model_dict = DocumentCounts.from_dict(document_counts_model_json).__dict__ + document_counts_model2 = DocumentCounts(**document_counts_model_dict) + + # Verify the model instances are equivalent + assert document_counts_model == document_counts_model2 + + # Convert model instance back to dict and verify no loss of data + document_counts_model_json2 = document_counts_model.to_dict() + assert document_counts_model_json2 == document_counts_model_json + +class TestDocumentStatus(): + """ + Test Class for DocumentStatus + """ + + def test_document_status_serialization(self): + """ + Test serialization/deserialization for DocumentStatus + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['notice_id'] = 'index_342' + notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['document_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' + notice_model['query_id'] = 'testString' + notice_model['severity'] = 'warning' + notice_model['step'] = 'indexing' + notice_model['description'] = 'something bad happened' + + # Construct a json representation of a DocumentStatus model + document_status_model_json = {} + document_status_model_json['document_id'] = 'testString' + document_status_model_json['configuration_id'] = 'testString' + document_status_model_json['status'] = 'available' + document_status_model_json['status_description'] = 'testString' + document_status_model_json['filename'] = 'testString' + document_status_model_json['file_type'] = 'pdf' + document_status_model_json['sha1'] = 'testString' + document_status_model_json['notices'] = [notice_model] + + # Construct a model instance of DocumentStatus by calling from_dict on the json representation + document_status_model = DocumentStatus.from_dict(document_status_model_json) + assert document_status_model != False + + # Construct a model instance of DocumentStatus by calling from_dict on the json representation + document_status_model_dict = DocumentStatus.from_dict(document_status_model_json).__dict__ + document_status_model2 = DocumentStatus(**document_status_model_dict) + + # Verify the model instances are equivalent + assert document_status_model == document_status_model2 + + # Convert model instance back to dict and verify no loss of data + document_status_model_json2 = document_status_model.to_dict() + assert document_status_model_json2 == document_status_model_json + +class TestEnrichment(): + """ + Test Class for Enrichment + """ + + def test_enrichment_serialization(self): + """ + Test serialization/deserialization for Enrichment + """ + + # Construct dict forms of any model objects needed in order to build this model. + + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model['sentiment'] = True + nlu_enrichment_keywords_model['emotion'] = True + nlu_enrichment_keywords_model['limit'] = 38 + + nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model['sentiment'] = True + nlu_enrichment_entities_model['emotion'] = True + nlu_enrichment_entities_model['limit'] = 38 + nlu_enrichment_entities_model['mentions'] = True + nlu_enrichment_entities_model['mention_types'] = True + nlu_enrichment_entities_model['sentence_locations'] = True + nlu_enrichment_entities_model['model'] = 'testString' + + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model['document'] = True + nlu_enrichment_sentiment_model['targets'] = ['testString'] + + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model['document'] = True + nlu_enrichment_emotion_model['targets'] = ['testString'] + + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model['entities'] = True + nlu_enrichment_semantic_roles_model['keywords'] = True + nlu_enrichment_semantic_roles_model['limit'] = 38 + + nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model['model'] = 'testString' + + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model['limit'] = 38 + + nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model + nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model + nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model + nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model + nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model + nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model + nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model + + enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model['features'] = nlu_enrichment_features_model + enrichment_options_model['language'] = 'ar' + enrichment_options_model['model'] = 'testString' + + # Construct a json representation of a Enrichment model + enrichment_model_json = {} + enrichment_model_json['description'] = 'testString' + enrichment_model_json['destination_field'] = 'testString' + enrichment_model_json['source_field'] = 'testString' + enrichment_model_json['overwrite'] = True + enrichment_model_json['enrichment'] = 'testString' + enrichment_model_json['ignore_downstream_errors'] = True + enrichment_model_json['options'] = enrichment_options_model + + # Construct a model instance of Enrichment by calling from_dict on the json representation + enrichment_model = Enrichment.from_dict(enrichment_model_json) + assert enrichment_model != False + + # Construct a model instance of Enrichment by calling from_dict on the json representation + enrichment_model_dict = Enrichment.from_dict(enrichment_model_json).__dict__ + enrichment_model2 = Enrichment(**enrichment_model_dict) + + # Verify the model instances are equivalent + assert enrichment_model == enrichment_model2 + + # Convert model instance back to dict and verify no loss of data + enrichment_model_json2 = enrichment_model.to_dict() + assert enrichment_model_json2 == enrichment_model_json + +class TestEnrichmentOptions(): + """ + Test Class for EnrichmentOptions + """ + + def test_enrichment_options_serialization(self): + """ + Test serialization/deserialization for EnrichmentOptions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model['sentiment'] = True + nlu_enrichment_keywords_model['emotion'] = True + nlu_enrichment_keywords_model['limit'] = 38 + + nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model['sentiment'] = True + nlu_enrichment_entities_model['emotion'] = True + nlu_enrichment_entities_model['limit'] = 38 + nlu_enrichment_entities_model['mentions'] = True + nlu_enrichment_entities_model['mention_types'] = True + nlu_enrichment_entities_model['sentence_locations'] = True + nlu_enrichment_entities_model['model'] = 'testString' + + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model['document'] = True + nlu_enrichment_sentiment_model['targets'] = ['testString'] + + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model['document'] = True + nlu_enrichment_emotion_model['targets'] = ['testString'] + + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model['entities'] = True + nlu_enrichment_semantic_roles_model['keywords'] = True + nlu_enrichment_semantic_roles_model['limit'] = 38 + + nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model['model'] = 'testString' + + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model['limit'] = 38 + + nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model + nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model + nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model + nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model + nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model + nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model + nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model + + # Construct a json representation of a EnrichmentOptions model + enrichment_options_model_json = {} + enrichment_options_model_json['features'] = nlu_enrichment_features_model + enrichment_options_model_json['language'] = 'ar' + enrichment_options_model_json['model'] = 'testString' + + # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation + enrichment_options_model = EnrichmentOptions.from_dict(enrichment_options_model_json) + assert enrichment_options_model != False + + # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation + enrichment_options_model_dict = EnrichmentOptions.from_dict(enrichment_options_model_json).__dict__ + enrichment_options_model2 = EnrichmentOptions(**enrichment_options_model_dict) + + # Verify the model instances are equivalent + assert enrichment_options_model == enrichment_options_model2 + + # Convert model instance back to dict and verify no loss of data + enrichment_options_model_json2 = enrichment_options_model.to_dict() + assert enrichment_options_model_json2 == enrichment_options_model_json + +class TestEnvironment(): + """ + Test Class for Environment + """ + + def test_environment_serialization(self): + """ + Test serialization/deserialization for Environment + """ + + # Construct dict forms of any model objects needed in order to build this model. + + environment_documents_model = {} # EnvironmentDocuments + environment_documents_model['available'] = 38 + environment_documents_model['maximum_allowed'] = 1000000 + + disk_usage_model = {} # DiskUsage + disk_usage_model['used_bytes'] = 0 + disk_usage_model['maximum_allowed_bytes'] = 85899345920 + + collection_usage_model = {} # CollectionUsage + collection_usage_model['available'] = 1 + collection_usage_model['maximum_allowed'] = 4 + + index_capacity_model = {} # IndexCapacity + index_capacity_model['documents'] = environment_documents_model + index_capacity_model['disk_usage'] = disk_usage_model + index_capacity_model['collections'] = collection_usage_model + + search_status_model = {} # SearchStatus + search_status_model['scope'] = 'testString' + search_status_model['status'] = 'NO_DATA' + search_status_model['status_description'] = 'testString' + search_status_model['last_trained'] = '2020-01-28' + + # Construct a json representation of a Environment model + environment_model_json = {} + environment_model_json['environment_id'] = 'testString' + environment_model_json['name'] = 'testString' + environment_model_json['description'] = 'testString' + environment_model_json['created'] = '2020-01-28T18:40:40.123456Z' + environment_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + environment_model_json['status'] = 'active' + environment_model_json['read_only'] = True + environment_model_json['size'] = 'LT' + environment_model_json['requested_size'] = 'testString' + environment_model_json['index_capacity'] = index_capacity_model + environment_model_json['search_status'] = search_status_model + + # Construct a model instance of Environment by calling from_dict on the json representation + environment_model = Environment.from_dict(environment_model_json) + assert environment_model != False + + # Construct a model instance of Environment by calling from_dict on the json representation + environment_model_dict = Environment.from_dict(environment_model_json).__dict__ + environment_model2 = Environment(**environment_model_dict) + + # Verify the model instances are equivalent + assert environment_model == environment_model2 + + # Convert model instance back to dict and verify no loss of data + environment_model_json2 = environment_model.to_dict() + assert environment_model_json2 == environment_model_json + +class TestEnvironmentDocuments(): + """ + Test Class for EnvironmentDocuments + """ + + def test_environment_documents_serialization(self): + """ + Test serialization/deserialization for EnvironmentDocuments + """ + + # Construct a json representation of a EnvironmentDocuments model + environment_documents_model_json = {} + environment_documents_model_json['available'] = 38 + environment_documents_model_json['maximum_allowed'] = 38 + + # Construct a model instance of EnvironmentDocuments by calling from_dict on the json representation + environment_documents_model = EnvironmentDocuments.from_dict(environment_documents_model_json) + assert environment_documents_model != False + + # Construct a model instance of EnvironmentDocuments by calling from_dict on the json representation + environment_documents_model_dict = EnvironmentDocuments.from_dict(environment_documents_model_json).__dict__ + environment_documents_model2 = EnvironmentDocuments(**environment_documents_model_dict) + + # Verify the model instances are equivalent + assert environment_documents_model == environment_documents_model2 + + # Convert model instance back to dict and verify no loss of data + environment_documents_model_json2 = environment_documents_model.to_dict() + assert environment_documents_model_json2 == environment_documents_model_json + +class TestEventData(): + """ + Test Class for EventData + """ + + def test_event_data_serialization(self): + """ + Test serialization/deserialization for EventData + """ + + # Construct a json representation of a EventData model + event_data_model_json = {} + event_data_model_json['environment_id'] = 'testString' + event_data_model_json['session_token'] = 'testString' + event_data_model_json['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + event_data_model_json['display_rank'] = 38 + event_data_model_json['collection_id'] = 'testString' + event_data_model_json['document_id'] = 'testString' + event_data_model_json['query_id'] = 'testString' + + # Construct a model instance of EventData by calling from_dict on the json representation + event_data_model = EventData.from_dict(event_data_model_json) + assert event_data_model != False + + # Construct a model instance of EventData by calling from_dict on the json representation + event_data_model_dict = EventData.from_dict(event_data_model_json).__dict__ + event_data_model2 = EventData(**event_data_model_dict) + + # Verify the model instances are equivalent + assert event_data_model == event_data_model2 + + # Convert model instance back to dict and verify no loss of data + event_data_model_json2 = event_data_model.to_dict() + assert event_data_model_json2 == event_data_model_json + +class TestExpansion(): + """ + Test Class for Expansion + """ + + def test_expansion_serialization(self): + """ + Test serialization/deserialization for Expansion + """ + + # Construct a json representation of a Expansion model + expansion_model_json = {} + expansion_model_json['input_terms'] = ['testString'] + expansion_model_json['expanded_terms'] = ['testString'] + + # Construct a model instance of Expansion by calling from_dict on the json representation + expansion_model = Expansion.from_dict(expansion_model_json) + assert expansion_model != False + + # Construct a model instance of Expansion by calling from_dict on the json representation + expansion_model_dict = Expansion.from_dict(expansion_model_json).__dict__ + expansion_model2 = Expansion(**expansion_model_dict) + + # Verify the model instances are equivalent + assert expansion_model == expansion_model2 + + # Convert model instance back to dict and verify no loss of data + expansion_model_json2 = expansion_model.to_dict() + assert expansion_model_json2 == expansion_model_json + +class TestExpansions(): + """ + Test Class for Expansions + """ + + def test_expansions_serialization(self): + """ + Test serialization/deserialization for Expansions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + expansion_model = {} # Expansion + expansion_model['input_terms'] = ['testString'] + expansion_model['expanded_terms'] = ['testString'] + + # Construct a json representation of a Expansions model + expansions_model_json = {} + expansions_model_json['expansions'] = [expansion_model] + + # Construct a model instance of Expansions by calling from_dict on the json representation + expansions_model = Expansions.from_dict(expansions_model_json) + assert expansions_model != False + + # Construct a model instance of Expansions by calling from_dict on the json representation + expansions_model_dict = Expansions.from_dict(expansions_model_json).__dict__ + expansions_model2 = Expansions(**expansions_model_dict) + + # Verify the model instances are equivalent + assert expansions_model == expansions_model2 + + # Convert model instance back to dict and verify no loss of data + expansions_model_json2 = expansions_model.to_dict() + assert expansions_model_json2 == expansions_model_json + +class TestField(): + """ + Test Class for Field + """ + + def test_field_serialization(self): + """ + Test serialization/deserialization for Field + """ + + # Construct a json representation of a Field model + field_model_json = {} + field_model_json['field'] = 'testString' + field_model_json['type'] = 'nested' + + # Construct a model instance of Field by calling from_dict on the json representation + field_model = Field.from_dict(field_model_json) + assert field_model != False + + # Construct a model instance of Field by calling from_dict on the json representation + field_model_dict = Field.from_dict(field_model_json).__dict__ + field_model2 = Field(**field_model_dict) + + # Verify the model instances are equivalent + assert field_model == field_model2 + + # Convert model instance back to dict and verify no loss of data + field_model_json2 = field_model.to_dict() + assert field_model_json2 == field_model_json + +class TestFontSetting(): + """ + Test Class for FontSetting + """ + + def test_font_setting_serialization(self): + """ + Test serialization/deserialization for FontSetting + """ + + # Construct a json representation of a FontSetting model + font_setting_model_json = {} + font_setting_model_json['level'] = 38 + font_setting_model_json['min_size'] = 38 + font_setting_model_json['max_size'] = 38 + font_setting_model_json['bold'] = True + font_setting_model_json['italic'] = True + font_setting_model_json['name'] = 'testString' + + # Construct a model instance of FontSetting by calling from_dict on the json representation + font_setting_model = FontSetting.from_dict(font_setting_model_json) + assert font_setting_model != False + + # Construct a model instance of FontSetting by calling from_dict on the json representation + font_setting_model_dict = FontSetting.from_dict(font_setting_model_json).__dict__ + font_setting_model2 = FontSetting(**font_setting_model_dict) + + # Verify the model instances are equivalent + assert font_setting_model == font_setting_model2 + + # Convert model instance back to dict and verify no loss of data + font_setting_model_json2 = font_setting_model.to_dict() + assert font_setting_model_json2 == font_setting_model_json + +class TestGateway(): + """ + Test Class for Gateway + """ + + def test_gateway_serialization(self): + """ + Test serialization/deserialization for Gateway + """ + + # Construct a json representation of a Gateway model + gateway_model_json = {} + gateway_model_json['gateway_id'] = 'testString' + gateway_model_json['name'] = 'testString' + gateway_model_json['status'] = 'connected' + gateway_model_json['token'] = 'testString' + gateway_model_json['token_id'] = 'testString' + + # Construct a model instance of Gateway by calling from_dict on the json representation + gateway_model = Gateway.from_dict(gateway_model_json) + assert gateway_model != False + + # Construct a model instance of Gateway by calling from_dict on the json representation + gateway_model_dict = Gateway.from_dict(gateway_model_json).__dict__ + gateway_model2 = Gateway(**gateway_model_dict) + + # Verify the model instances are equivalent + assert gateway_model == gateway_model2 + + # Convert model instance back to dict and verify no loss of data + gateway_model_json2 = gateway_model.to_dict() + assert gateway_model_json2 == gateway_model_json + +class TestGatewayDelete(): + """ + Test Class for GatewayDelete + """ + + def test_gateway_delete_serialization(self): + """ + Test serialization/deserialization for GatewayDelete + """ + + # Construct a json representation of a GatewayDelete model + gateway_delete_model_json = {} + gateway_delete_model_json['gateway_id'] = 'testString' + gateway_delete_model_json['status'] = 'testString' + + # Construct a model instance of GatewayDelete by calling from_dict on the json representation + gateway_delete_model = GatewayDelete.from_dict(gateway_delete_model_json) + assert gateway_delete_model != False + + # Construct a model instance of GatewayDelete by calling from_dict on the json representation + gateway_delete_model_dict = GatewayDelete.from_dict(gateway_delete_model_json).__dict__ + gateway_delete_model2 = GatewayDelete(**gateway_delete_model_dict) + + # Verify the model instances are equivalent + assert gateway_delete_model == gateway_delete_model2 + + # Convert model instance back to dict and verify no loss of data + gateway_delete_model_json2 = gateway_delete_model.to_dict() + assert gateway_delete_model_json2 == gateway_delete_model_json + +class TestGatewayList(): + """ + Test Class for GatewayList + """ + + def test_gateway_list_serialization(self): + """ + Test serialization/deserialization for GatewayList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + gateway_model = {} # Gateway + gateway_model['gateway_id'] = 'testString' + gateway_model['name'] = 'testString' + gateway_model['status'] = 'connected' + gateway_model['token'] = 'testString' + gateway_model['token_id'] = 'testString' + + # Construct a json representation of a GatewayList model + gateway_list_model_json = {} + gateway_list_model_json['gateways'] = [gateway_model] + + # Construct a model instance of GatewayList by calling from_dict on the json representation + gateway_list_model = GatewayList.from_dict(gateway_list_model_json) + assert gateway_list_model != False + + # Construct a model instance of GatewayList by calling from_dict on the json representation + gateway_list_model_dict = GatewayList.from_dict(gateway_list_model_json).__dict__ + gateway_list_model2 = GatewayList(**gateway_list_model_dict) + + # Verify the model instances are equivalent + assert gateway_list_model == gateway_list_model2 + + # Convert model instance back to dict and verify no loss of data + gateway_list_model_json2 = gateway_list_model.to_dict() + assert gateway_list_model_json2 == gateway_list_model_json + +class TestHtmlSettings(): + """ + Test Class for HtmlSettings + """ + + def test_html_settings_serialization(self): + """ + Test serialization/deserialization for HtmlSettings + """ + + # Construct dict forms of any model objects needed in order to build this model. + + x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model['xpaths'] = ['testString'] + + # Construct a json representation of a HtmlSettings model + html_settings_model_json = {} + html_settings_model_json['exclude_tags_completely'] = ['testString'] + html_settings_model_json['exclude_tags_keep_content'] = ['testString'] + html_settings_model_json['keep_content'] = x_path_patterns_model + html_settings_model_json['exclude_content'] = x_path_patterns_model + html_settings_model_json['keep_tag_attributes'] = ['testString'] + html_settings_model_json['exclude_tag_attributes'] = ['testString'] + + # Construct a model instance of HtmlSettings by calling from_dict on the json representation + html_settings_model = HtmlSettings.from_dict(html_settings_model_json) + assert html_settings_model != False + + # Construct a model instance of HtmlSettings by calling from_dict on the json representation + html_settings_model_dict = HtmlSettings.from_dict(html_settings_model_json).__dict__ + html_settings_model2 = HtmlSettings(**html_settings_model_dict) + + # Verify the model instances are equivalent + assert html_settings_model == html_settings_model2 + + # Convert model instance back to dict and verify no loss of data + html_settings_model_json2 = html_settings_model.to_dict() + assert html_settings_model_json2 == html_settings_model_json + +class TestIndexCapacity(): + """ + Test Class for IndexCapacity + """ + + def test_index_capacity_serialization(self): + """ + Test serialization/deserialization for IndexCapacity + """ + + # Construct dict forms of any model objects needed in order to build this model. + + environment_documents_model = {} # EnvironmentDocuments + environment_documents_model['available'] = 38 + environment_documents_model['maximum_allowed'] = 38 + + disk_usage_model = {} # DiskUsage + disk_usage_model['used_bytes'] = 38 + disk_usage_model['maximum_allowed_bytes'] = 38 + + collection_usage_model = {} # CollectionUsage + collection_usage_model['available'] = 38 + collection_usage_model['maximum_allowed'] = 38 + + # Construct a json representation of a IndexCapacity model + index_capacity_model_json = {} + index_capacity_model_json['documents'] = environment_documents_model + index_capacity_model_json['disk_usage'] = disk_usage_model + index_capacity_model_json['collections'] = collection_usage_model + + # Construct a model instance of IndexCapacity by calling from_dict on the json representation + index_capacity_model = IndexCapacity.from_dict(index_capacity_model_json) + assert index_capacity_model != False + + # Construct a model instance of IndexCapacity by calling from_dict on the json representation + index_capacity_model_dict = IndexCapacity.from_dict(index_capacity_model_json).__dict__ + index_capacity_model2 = IndexCapacity(**index_capacity_model_dict) + + # Verify the model instances are equivalent + assert index_capacity_model == index_capacity_model2 + + # Convert model instance back to dict and verify no loss of data + index_capacity_model_json2 = index_capacity_model.to_dict() + assert index_capacity_model_json2 == index_capacity_model_json + +class TestListCollectionFieldsResponse(): + """ + Test Class for ListCollectionFieldsResponse + """ + + def test_list_collection_fields_response_serialization(self): + """ + Test serialization/deserialization for ListCollectionFieldsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + field_model = {} # Field + field_model['field'] = 'warnings' + field_model['type'] = 'nested' + + # Construct a json representation of a ListCollectionFieldsResponse model + list_collection_fields_response_model_json = {} + list_collection_fields_response_model_json['fields'] = [field_model] + + # Construct a model instance of ListCollectionFieldsResponse by calling from_dict on the json representation + list_collection_fields_response_model = ListCollectionFieldsResponse.from_dict(list_collection_fields_response_model_json) + assert list_collection_fields_response_model != False + + # Construct a model instance of ListCollectionFieldsResponse by calling from_dict on the json representation + list_collection_fields_response_model_dict = ListCollectionFieldsResponse.from_dict(list_collection_fields_response_model_json).__dict__ + list_collection_fields_response_model2 = ListCollectionFieldsResponse(**list_collection_fields_response_model_dict) + + # Verify the model instances are equivalent + assert list_collection_fields_response_model == list_collection_fields_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_collection_fields_response_model_json2 = list_collection_fields_response_model.to_dict() + assert list_collection_fields_response_model_json2 == list_collection_fields_response_model_json + +class TestListCollectionsResponse(): + """ + Test Class for ListCollectionsResponse + """ + + def test_list_collections_response_serialization(self): + """ + Test serialization/deserialization for ListCollectionsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_counts_model = {} # DocumentCounts + document_counts_model['available'] = 26 + document_counts_model['processing'] = 26 + document_counts_model['failed'] = 26 + document_counts_model['pending'] = 26 + + collection_disk_usage_model = {} # CollectionDiskUsage + collection_disk_usage_model['used_bytes'] = 38 + + training_status_model = {} # TrainingStatus + training_status_model['total_examples'] = 38 + training_status_model['available'] = True + training_status_model['processing'] = True + training_status_model['minimum_queries_added'] = True + training_status_model['minimum_examples_added'] = True + training_status_model['sufficient_label_diversity'] = True + training_status_model['notices'] = 38 + training_status_model['successfully_trained'] = '2020-01-28T18:40:40.123456Z' + training_status_model['data_updated'] = '2020-01-28T18:40:40.123456Z' + + source_status_model = {} # SourceStatus + source_status_model['status'] = 'running' + source_status_model['next_crawl'] = '2020-01-28T18:40:40.123456Z' + + collection_crawl_status_model = {} # CollectionCrawlStatus + collection_crawl_status_model['source_crawl'] = source_status_model + + sdu_status_custom_fields_model = {} # SduStatusCustomFields + sdu_status_custom_fields_model['defined'] = 26 + sdu_status_custom_fields_model['maximum_allowed'] = 26 + + sdu_status_model = {} # SduStatus + sdu_status_model['enabled'] = True + sdu_status_model['total_annotated_pages'] = 26 + sdu_status_model['total_pages'] = 26 + sdu_status_model['total_documents'] = 26 + sdu_status_model['custom_fields'] = sdu_status_custom_fields_model + + collection_model = {} # Collection + collection_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' + collection_model['name'] = 'example' + collection_model['description'] = 'this is a demo collection' + collection_model['created'] = '2020-01-28T18:40:40.123456Z' + collection_model['updated'] = '2020-01-28T18:40:40.123456Z' + collection_model['status'] = 'active' + collection_model['configuration_id'] = '6963be41-2dea-4f79-8f52-127c63c479b0' + collection_model['language'] = 'en' + collection_model['document_counts'] = document_counts_model + collection_model['disk_usage'] = collection_disk_usage_model + collection_model['training_status'] = training_status_model + collection_model['crawl_status'] = collection_crawl_status_model + collection_model['smart_document_understanding'] = sdu_status_model + + # Construct a json representation of a ListCollectionsResponse model + list_collections_response_model_json = {} + list_collections_response_model_json['collections'] = [collection_model] + + # Construct a model instance of ListCollectionsResponse by calling from_dict on the json representation + list_collections_response_model = ListCollectionsResponse.from_dict(list_collections_response_model_json) + assert list_collections_response_model != False + + # Construct a model instance of ListCollectionsResponse by calling from_dict on the json representation + list_collections_response_model_dict = ListCollectionsResponse.from_dict(list_collections_response_model_json).__dict__ + list_collections_response_model2 = ListCollectionsResponse(**list_collections_response_model_dict) + + # Verify the model instances are equivalent + assert list_collections_response_model == list_collections_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_collections_response_model_json2 = list_collections_response_model.to_dict() + assert list_collections_response_model_json2 == list_collections_response_model_json + +class TestListConfigurationsResponse(): + """ + Test Class for ListConfigurationsResponse + """ + + def test_list_configurations_response_serialization(self): + """ + Test serialization/deserialization for ListConfigurationsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + font_setting_model = {} # FontSetting + font_setting_model['level'] = 38 + font_setting_model['min_size'] = 38 + font_setting_model['max_size'] = 38 + font_setting_model['bold'] = True + font_setting_model['italic'] = True + font_setting_model['name'] = 'testString' + + pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model['fonts'] = [font_setting_model] + + pdf_settings_model = {} # PdfSettings + pdf_settings_model['heading'] = pdf_heading_detection_model + + word_style_model = {} # WordStyle + word_style_model['level'] = 38 + word_style_model['names'] = ['testString'] + + word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model['fonts'] = [font_setting_model] + word_heading_detection_model['styles'] = [word_style_model] + + word_settings_model = {} # WordSettings + word_settings_model['heading'] = word_heading_detection_model + + x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model['xpaths'] = ['testString'] + + html_settings_model = {} # HtmlSettings + html_settings_model['exclude_tags_completely'] = ['testString'] + html_settings_model['exclude_tags_keep_content'] = ['testString'] + html_settings_model['keep_content'] = x_path_patterns_model + html_settings_model['exclude_content'] = x_path_patterns_model + html_settings_model['keep_tag_attributes'] = ['testString'] + html_settings_model['exclude_tag_attributes'] = ['testString'] + + segment_settings_model = {} # SegmentSettings + segment_settings_model['enabled'] = True + segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['annotated_fields'] = ['testString'] + + normalization_operation_model = {} # NormalizationOperation + normalization_operation_model['operation'] = 'copy' + normalization_operation_model['source_field'] = 'testString' + normalization_operation_model['destination_field'] = 'testString' + + conversions_model = {} # Conversions + conversions_model['pdf'] = pdf_settings_model + conversions_model['word'] = word_settings_model + conversions_model['html'] = html_settings_model + conversions_model['segment'] = segment_settings_model + conversions_model['json_normalizations'] = [normalization_operation_model] + conversions_model['image_text_recognition'] = True + + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model['sentiment'] = True + nlu_enrichment_keywords_model['emotion'] = True + nlu_enrichment_keywords_model['limit'] = 38 + + nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model['sentiment'] = True + nlu_enrichment_entities_model['emotion'] = True + nlu_enrichment_entities_model['limit'] = 38 + nlu_enrichment_entities_model['mentions'] = True + nlu_enrichment_entities_model['mention_types'] = True + nlu_enrichment_entities_model['sentence_locations'] = True + nlu_enrichment_entities_model['model'] = 'testString' + + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model['document'] = True + nlu_enrichment_sentiment_model['targets'] = ['testString'] + + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model['document'] = True + nlu_enrichment_emotion_model['targets'] = ['testString'] + + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model['entities'] = True + nlu_enrichment_semantic_roles_model['keywords'] = True + nlu_enrichment_semantic_roles_model['limit'] = 38 + + nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model['model'] = 'testString' + + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model['limit'] = 38 + + nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model + nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model + nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model + nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model + nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model + nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model + nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model + + enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model['features'] = nlu_enrichment_features_model + enrichment_options_model['language'] = 'ar' + enrichment_options_model['model'] = 'testString' + + enrichment_model = {} # Enrichment + enrichment_model['description'] = 'testString' + enrichment_model['destination_field'] = 'testString' + enrichment_model['source_field'] = 'testString' + enrichment_model['overwrite'] = True + enrichment_model['enrichment'] = 'testString' + enrichment_model['ignore_downstream_errors'] = True + enrichment_model['options'] = enrichment_options_model + + source_schedule_model = {} # SourceSchedule + source_schedule_model['enabled'] = True + source_schedule_model['time_zone'] = 'testString' + source_schedule_model['frequency'] = 'daily' + + source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model['owner_user_id'] = 'testString' + source_options_folder_model['folder_id'] = 'testString' + source_options_folder_model['limit'] = 38 + + source_options_object_model = {} # SourceOptionsObject + source_options_object_model['name'] = 'testString' + source_options_object_model['limit'] = 38 + + source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model['site_collection_path'] = 'testString' + source_options_site_coll_model['limit'] = 38 + + source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model['url'] = 'testString' + source_options_web_crawl_model['limit_to_starting_hosts'] = True + source_options_web_crawl_model['crawl_speed'] = 'gentle' + source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['maximum_hops'] = 38 + source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['blacklist'] = ['testString'] + + source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model['name'] = 'testString' + source_options_buckets_model['limit'] = 38 + + source_options_model = {} # SourceOptions + source_options_model['folders'] = [source_options_folder_model] + source_options_model['objects'] = [source_options_object_model] + source_options_model['site_collections'] = [source_options_site_coll_model] + source_options_model['urls'] = [source_options_web_crawl_model] + source_options_model['buckets'] = [source_options_buckets_model] + source_options_model['crawl_all_buckets'] = True + + source_model = {} # Source + source_model['type'] = 'box' + source_model['credential_id'] = 'testString' + source_model['schedule'] = source_schedule_model + source_model['options'] = source_options_model + + configuration_model = {} # Configuration + configuration_model['configuration_id'] = 'testString' + configuration_model['name'] = 'testString' + configuration_model['created'] = '2020-01-28T18:40:40.123456Z' + configuration_model['updated'] = '2020-01-28T18:40:40.123456Z' + configuration_model['description'] = 'testString' + configuration_model['conversions'] = conversions_model + configuration_model['enrichments'] = [enrichment_model] + configuration_model['normalizations'] = [normalization_operation_model] + configuration_model['source'] = source_model + + # Construct a json representation of a ListConfigurationsResponse model + list_configurations_response_model_json = {} + list_configurations_response_model_json['configurations'] = [configuration_model] + + # Construct a model instance of ListConfigurationsResponse by calling from_dict on the json representation + list_configurations_response_model = ListConfigurationsResponse.from_dict(list_configurations_response_model_json) + assert list_configurations_response_model != False + + # Construct a model instance of ListConfigurationsResponse by calling from_dict on the json representation + list_configurations_response_model_dict = ListConfigurationsResponse.from_dict(list_configurations_response_model_json).__dict__ + list_configurations_response_model2 = ListConfigurationsResponse(**list_configurations_response_model_dict) + + # Verify the model instances are equivalent + assert list_configurations_response_model == list_configurations_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_configurations_response_model_json2 = list_configurations_response_model.to_dict() + assert list_configurations_response_model_json2 == list_configurations_response_model_json + +class TestListEnvironmentsResponse(): + """ + Test Class for ListEnvironmentsResponse + """ + + def test_list_environments_response_serialization(self): + """ + Test serialization/deserialization for ListEnvironmentsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + environment_documents_model = {} # EnvironmentDocuments + environment_documents_model['available'] = 38 + environment_documents_model['maximum_allowed'] = 38 + + disk_usage_model = {} # DiskUsage + disk_usage_model['used_bytes'] = 38 + disk_usage_model['maximum_allowed_bytes'] = 38 + + collection_usage_model = {} # CollectionUsage + collection_usage_model['available'] = 38 + collection_usage_model['maximum_allowed'] = 38 + + index_capacity_model = {} # IndexCapacity + index_capacity_model['documents'] = environment_documents_model + index_capacity_model['disk_usage'] = disk_usage_model + index_capacity_model['collections'] = collection_usage_model + + search_status_model = {} # SearchStatus + search_status_model['scope'] = 'testString' + search_status_model['status'] = 'NO_DATA' + search_status_model['status_description'] = 'testString' + search_status_model['last_trained'] = '2020-01-28' + + environment_model = {} # Environment + environment_model['environment_id'] = 'ecbda78e-fb06-40b1-a43f-a039fac0adc6' + environment_model['name'] = 'byod_environment' + environment_model['description'] = 'Private Data Environment' + environment_model['created'] = '2020-01-28T18:40:40.123456Z' + environment_model['updated'] = '2020-01-28T18:40:40.123456Z' + environment_model['status'] = 'active' + environment_model['read_only'] = False + environment_model['size'] = 'LT' + environment_model['requested_size'] = 'testString' + environment_model['index_capacity'] = index_capacity_model + environment_model['search_status'] = search_status_model + + # Construct a json representation of a ListEnvironmentsResponse model + list_environments_response_model_json = {} + list_environments_response_model_json['environments'] = [environment_model] + + # Construct a model instance of ListEnvironmentsResponse by calling from_dict on the json representation + list_environments_response_model = ListEnvironmentsResponse.from_dict(list_environments_response_model_json) + assert list_environments_response_model != False + + # Construct a model instance of ListEnvironmentsResponse by calling from_dict on the json representation + list_environments_response_model_dict = ListEnvironmentsResponse.from_dict(list_environments_response_model_json).__dict__ + list_environments_response_model2 = ListEnvironmentsResponse(**list_environments_response_model_dict) + + # Verify the model instances are equivalent + assert list_environments_response_model == list_environments_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_environments_response_model_json2 = list_environments_response_model.to_dict() + assert list_environments_response_model_json2 == list_environments_response_model_json + +class TestLogQueryResponse(): + """ + Test Class for LogQueryResponse + """ + + def test_log_query_response_serialization(self): + """ + Test serialization/deserialization for LogQueryResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult + log_query_response_result_documents_result_model['position'] = 38 + log_query_response_result_documents_result_model['document_id'] = 'testString' + log_query_response_result_documents_result_model['score'] = 72.5 + log_query_response_result_documents_result_model['confidence'] = 72.5 + log_query_response_result_documents_result_model['collection_id'] = 'testString' + + log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments + log_query_response_result_documents_model['results'] = [log_query_response_result_documents_result_model] + log_query_response_result_documents_model['count'] = 38 + + log_query_response_result_model = {} # LogQueryResponseResult + log_query_response_result_model['environment_id'] = 'testString' + log_query_response_result_model['customer_id'] = 'testString' + log_query_response_result_model['document_type'] = 'query' + log_query_response_result_model['natural_language_query'] = 'testString' + log_query_response_result_model['document_results'] = log_query_response_result_documents_model + log_query_response_result_model['created_timestamp'] = '2020-01-28T18:40:40.123456Z' + log_query_response_result_model['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + log_query_response_result_model['query_id'] = 'testString' + log_query_response_result_model['session_token'] = 'testString' + log_query_response_result_model['collection_id'] = 'testString' + log_query_response_result_model['display_rank'] = 38 + log_query_response_result_model['document_id'] = 'testString' + log_query_response_result_model['event_type'] = 'click' + log_query_response_result_model['result_type'] = 'document' + + # Construct a json representation of a LogQueryResponse model + log_query_response_model_json = {} + log_query_response_model_json['matching_results'] = 38 + log_query_response_model_json['results'] = [log_query_response_result_model] + + # Construct a model instance of LogQueryResponse by calling from_dict on the json representation + log_query_response_model = LogQueryResponse.from_dict(log_query_response_model_json) + assert log_query_response_model != False + + # Construct a model instance of LogQueryResponse by calling from_dict on the json representation + log_query_response_model_dict = LogQueryResponse.from_dict(log_query_response_model_json).__dict__ + log_query_response_model2 = LogQueryResponse(**log_query_response_model_dict) + + # Verify the model instances are equivalent + assert log_query_response_model == log_query_response_model2 + + # Convert model instance back to dict and verify no loss of data + log_query_response_model_json2 = log_query_response_model.to_dict() + assert log_query_response_model_json2 == log_query_response_model_json + +class TestLogQueryResponseResult(): + """ + Test Class for LogQueryResponseResult + """ + + def test_log_query_response_result_serialization(self): + """ + Test serialization/deserialization for LogQueryResponseResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult + log_query_response_result_documents_result_model['position'] = 38 + log_query_response_result_documents_result_model['document_id'] = 'testString' + log_query_response_result_documents_result_model['score'] = 72.5 + log_query_response_result_documents_result_model['confidence'] = 72.5 + log_query_response_result_documents_result_model['collection_id'] = 'testString' + + log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments + log_query_response_result_documents_model['results'] = [log_query_response_result_documents_result_model] + log_query_response_result_documents_model['count'] = 38 + + # Construct a json representation of a LogQueryResponseResult model + log_query_response_result_model_json = {} + log_query_response_result_model_json['environment_id'] = 'testString' + log_query_response_result_model_json['customer_id'] = 'testString' + log_query_response_result_model_json['document_type'] = 'query' + log_query_response_result_model_json['natural_language_query'] = 'testString' + log_query_response_result_model_json['document_results'] = log_query_response_result_documents_model + log_query_response_result_model_json['created_timestamp'] = '2020-01-28T18:40:40.123456Z' + log_query_response_result_model_json['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + log_query_response_result_model_json['query_id'] = 'testString' + log_query_response_result_model_json['session_token'] = 'testString' + log_query_response_result_model_json['collection_id'] = 'testString' + log_query_response_result_model_json['display_rank'] = 38 + log_query_response_result_model_json['document_id'] = 'testString' + log_query_response_result_model_json['event_type'] = 'click' + log_query_response_result_model_json['result_type'] = 'document' + + # Construct a model instance of LogQueryResponseResult by calling from_dict on the json representation + log_query_response_result_model = LogQueryResponseResult.from_dict(log_query_response_result_model_json) + assert log_query_response_result_model != False + + # Construct a model instance of LogQueryResponseResult by calling from_dict on the json representation + log_query_response_result_model_dict = LogQueryResponseResult.from_dict(log_query_response_result_model_json).__dict__ + log_query_response_result_model2 = LogQueryResponseResult(**log_query_response_result_model_dict) + + # Verify the model instances are equivalent + assert log_query_response_result_model == log_query_response_result_model2 + + # Convert model instance back to dict and verify no loss of data + log_query_response_result_model_json2 = log_query_response_result_model.to_dict() + assert log_query_response_result_model_json2 == log_query_response_result_model_json + +class TestLogQueryResponseResultDocuments(): + """ + Test Class for LogQueryResponseResultDocuments + """ + + def test_log_query_response_result_documents_serialization(self): + """ + Test serialization/deserialization for LogQueryResponseResultDocuments + """ + + # Construct dict forms of any model objects needed in order to build this model. + + log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult + log_query_response_result_documents_result_model['position'] = 38 + log_query_response_result_documents_result_model['document_id'] = 'testString' + log_query_response_result_documents_result_model['score'] = 72.5 + log_query_response_result_documents_result_model['confidence'] = 72.5 + log_query_response_result_documents_result_model['collection_id'] = 'testString' + + # Construct a json representation of a LogQueryResponseResultDocuments model + log_query_response_result_documents_model_json = {} + log_query_response_result_documents_model_json['results'] = [log_query_response_result_documents_result_model] + log_query_response_result_documents_model_json['count'] = 38 + + # Construct a model instance of LogQueryResponseResultDocuments by calling from_dict on the json representation + log_query_response_result_documents_model = LogQueryResponseResultDocuments.from_dict(log_query_response_result_documents_model_json) + assert log_query_response_result_documents_model != False + + # Construct a model instance of LogQueryResponseResultDocuments by calling from_dict on the json representation + log_query_response_result_documents_model_dict = LogQueryResponseResultDocuments.from_dict(log_query_response_result_documents_model_json).__dict__ + log_query_response_result_documents_model2 = LogQueryResponseResultDocuments(**log_query_response_result_documents_model_dict) + + # Verify the model instances are equivalent + assert log_query_response_result_documents_model == log_query_response_result_documents_model2 + + # Convert model instance back to dict and verify no loss of data + log_query_response_result_documents_model_json2 = log_query_response_result_documents_model.to_dict() + assert log_query_response_result_documents_model_json2 == log_query_response_result_documents_model_json + +class TestLogQueryResponseResultDocumentsResult(): + """ + Test Class for LogQueryResponseResultDocumentsResult + """ + + def test_log_query_response_result_documents_result_serialization(self): + """ + Test serialization/deserialization for LogQueryResponseResultDocumentsResult + """ + + # Construct a json representation of a LogQueryResponseResultDocumentsResult model + log_query_response_result_documents_result_model_json = {} + log_query_response_result_documents_result_model_json['position'] = 38 + log_query_response_result_documents_result_model_json['document_id'] = 'testString' + log_query_response_result_documents_result_model_json['score'] = 72.5 + log_query_response_result_documents_result_model_json['confidence'] = 72.5 + log_query_response_result_documents_result_model_json['collection_id'] = 'testString' + + # Construct a model instance of LogQueryResponseResultDocumentsResult by calling from_dict on the json representation + log_query_response_result_documents_result_model = LogQueryResponseResultDocumentsResult.from_dict(log_query_response_result_documents_result_model_json) + assert log_query_response_result_documents_result_model != False + + # Construct a model instance of LogQueryResponseResultDocumentsResult by calling from_dict on the json representation + log_query_response_result_documents_result_model_dict = LogQueryResponseResultDocumentsResult.from_dict(log_query_response_result_documents_result_model_json).__dict__ + log_query_response_result_documents_result_model2 = LogQueryResponseResultDocumentsResult(**log_query_response_result_documents_result_model_dict) + + # Verify the model instances are equivalent + assert log_query_response_result_documents_result_model == log_query_response_result_documents_result_model2 + + # Convert model instance back to dict and verify no loss of data + log_query_response_result_documents_result_model_json2 = log_query_response_result_documents_result_model.to_dict() + assert log_query_response_result_documents_result_model_json2 == log_query_response_result_documents_result_model_json + +class TestMetricAggregation(): + """ + Test Class for MetricAggregation + """ + + def test_metric_aggregation_serialization(self): + """ + Test serialization/deserialization for MetricAggregation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + metric_aggregation_result_model = {} # MetricAggregationResult + metric_aggregation_result_model['key_as_string'] = '2020-01-28T18:40:40.123456Z' + metric_aggregation_result_model['key'] = 26 + metric_aggregation_result_model['matching_results'] = 38 + metric_aggregation_result_model['event_rate'] = 72.5 + + # Construct a json representation of a MetricAggregation model + metric_aggregation_model_json = {} + metric_aggregation_model_json['interval'] = 'testString' + metric_aggregation_model_json['event_type'] = 'testString' + metric_aggregation_model_json['results'] = [metric_aggregation_result_model] + + # Construct a model instance of MetricAggregation by calling from_dict on the json representation + metric_aggregation_model = MetricAggregation.from_dict(metric_aggregation_model_json) + assert metric_aggregation_model != False + + # Construct a model instance of MetricAggregation by calling from_dict on the json representation + metric_aggregation_model_dict = MetricAggregation.from_dict(metric_aggregation_model_json).__dict__ + metric_aggregation_model2 = MetricAggregation(**metric_aggregation_model_dict) + + # Verify the model instances are equivalent + assert metric_aggregation_model == metric_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + metric_aggregation_model_json2 = metric_aggregation_model.to_dict() + assert metric_aggregation_model_json2 == metric_aggregation_model_json + +class TestMetricAggregationResult(): + """ + Test Class for MetricAggregationResult + """ + + def test_metric_aggregation_result_serialization(self): + """ + Test serialization/deserialization for MetricAggregationResult + """ + + # Construct a json representation of a MetricAggregationResult model + metric_aggregation_result_model_json = {} + metric_aggregation_result_model_json['key_as_string'] = '2020-01-28T18:40:40.123456Z' + metric_aggregation_result_model_json['key'] = 26 + metric_aggregation_result_model_json['matching_results'] = 38 + metric_aggregation_result_model_json['event_rate'] = 72.5 + + # Construct a model instance of MetricAggregationResult by calling from_dict on the json representation + metric_aggregation_result_model = MetricAggregationResult.from_dict(metric_aggregation_result_model_json) + assert metric_aggregation_result_model != False + + # Construct a model instance of MetricAggregationResult by calling from_dict on the json representation + metric_aggregation_result_model_dict = MetricAggregationResult.from_dict(metric_aggregation_result_model_json).__dict__ + metric_aggregation_result_model2 = MetricAggregationResult(**metric_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert metric_aggregation_result_model == metric_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + metric_aggregation_result_model_json2 = metric_aggregation_result_model.to_dict() + assert metric_aggregation_result_model_json2 == metric_aggregation_result_model_json + +class TestMetricResponse(): + """ + Test Class for MetricResponse + """ + + def test_metric_response_serialization(self): + """ + Test serialization/deserialization for MetricResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + metric_aggregation_result_model = {} # MetricAggregationResult + metric_aggregation_result_model['key_as_string'] = '2020-01-28T18:40:40.123456Z' + metric_aggregation_result_model['key'] = 26 + metric_aggregation_result_model['matching_results'] = 38 + metric_aggregation_result_model['event_rate'] = 72.5 + + metric_aggregation_model = {} # MetricAggregation + metric_aggregation_model['interval'] = 'testString' + metric_aggregation_model['event_type'] = 'testString' + metric_aggregation_model['results'] = [metric_aggregation_result_model] + + # Construct a json representation of a MetricResponse model + metric_response_model_json = {} + metric_response_model_json['aggregations'] = [metric_aggregation_model] + + # Construct a model instance of MetricResponse by calling from_dict on the json representation + metric_response_model = MetricResponse.from_dict(metric_response_model_json) + assert metric_response_model != False + + # Construct a model instance of MetricResponse by calling from_dict on the json representation + metric_response_model_dict = MetricResponse.from_dict(metric_response_model_json).__dict__ + metric_response_model2 = MetricResponse(**metric_response_model_dict) + + # Verify the model instances are equivalent + assert metric_response_model == metric_response_model2 + + # Convert model instance back to dict and verify no loss of data + metric_response_model_json2 = metric_response_model.to_dict() + assert metric_response_model_json2 == metric_response_model_json + +class TestMetricTokenAggregation(): + """ + Test Class for MetricTokenAggregation + """ + + def test_metric_token_aggregation_serialization(self): + """ + Test serialization/deserialization for MetricTokenAggregation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + metric_token_aggregation_result_model = {} # MetricTokenAggregationResult + metric_token_aggregation_result_model['key'] = 'testString' + metric_token_aggregation_result_model['matching_results'] = 38 + metric_token_aggregation_result_model['event_rate'] = 72.5 + + # Construct a json representation of a MetricTokenAggregation model + metric_token_aggregation_model_json = {} + metric_token_aggregation_model_json['event_type'] = 'testString' + metric_token_aggregation_model_json['results'] = [metric_token_aggregation_result_model] + + # Construct a model instance of MetricTokenAggregation by calling from_dict on the json representation + metric_token_aggregation_model = MetricTokenAggregation.from_dict(metric_token_aggregation_model_json) + assert metric_token_aggregation_model != False + + # Construct a model instance of MetricTokenAggregation by calling from_dict on the json representation + metric_token_aggregation_model_dict = MetricTokenAggregation.from_dict(metric_token_aggregation_model_json).__dict__ + metric_token_aggregation_model2 = MetricTokenAggregation(**metric_token_aggregation_model_dict) + + # Verify the model instances are equivalent + assert metric_token_aggregation_model == metric_token_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + metric_token_aggregation_model_json2 = metric_token_aggregation_model.to_dict() + assert metric_token_aggregation_model_json2 == metric_token_aggregation_model_json + +class TestMetricTokenAggregationResult(): + """ + Test Class for MetricTokenAggregationResult + """ + + def test_metric_token_aggregation_result_serialization(self): + """ + Test serialization/deserialization for MetricTokenAggregationResult + """ + + # Construct a json representation of a MetricTokenAggregationResult model + metric_token_aggregation_result_model_json = {} + metric_token_aggregation_result_model_json['key'] = 'testString' + metric_token_aggregation_result_model_json['matching_results'] = 38 + metric_token_aggregation_result_model_json['event_rate'] = 72.5 + + # Construct a model instance of MetricTokenAggregationResult by calling from_dict on the json representation + metric_token_aggregation_result_model = MetricTokenAggregationResult.from_dict(metric_token_aggregation_result_model_json) + assert metric_token_aggregation_result_model != False + + # Construct a model instance of MetricTokenAggregationResult by calling from_dict on the json representation + metric_token_aggregation_result_model_dict = MetricTokenAggregationResult.from_dict(metric_token_aggregation_result_model_json).__dict__ + metric_token_aggregation_result_model2 = MetricTokenAggregationResult(**metric_token_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert metric_token_aggregation_result_model == metric_token_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + metric_token_aggregation_result_model_json2 = metric_token_aggregation_result_model.to_dict() + assert metric_token_aggregation_result_model_json2 == metric_token_aggregation_result_model_json + +class TestMetricTokenResponse(): + """ + Test Class for MetricTokenResponse + """ + + def test_metric_token_response_serialization(self): + """ + Test serialization/deserialization for MetricTokenResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + metric_token_aggregation_result_model = {} # MetricTokenAggregationResult + metric_token_aggregation_result_model['key'] = 'testString' + metric_token_aggregation_result_model['matching_results'] = 38 + metric_token_aggregation_result_model['event_rate'] = 72.5 + + metric_token_aggregation_model = {} # MetricTokenAggregation + metric_token_aggregation_model['event_type'] = 'testString' + metric_token_aggregation_model['results'] = [metric_token_aggregation_result_model] + + # Construct a json representation of a MetricTokenResponse model + metric_token_response_model_json = {} + metric_token_response_model_json['aggregations'] = [metric_token_aggregation_model] + + # Construct a model instance of MetricTokenResponse by calling from_dict on the json representation + metric_token_response_model = MetricTokenResponse.from_dict(metric_token_response_model_json) + assert metric_token_response_model != False + + # Construct a model instance of MetricTokenResponse by calling from_dict on the json representation + metric_token_response_model_dict = MetricTokenResponse.from_dict(metric_token_response_model_json).__dict__ + metric_token_response_model2 = MetricTokenResponse(**metric_token_response_model_dict) + + # Verify the model instances are equivalent + assert metric_token_response_model == metric_token_response_model2 + + # Convert model instance back to dict and verify no loss of data + metric_token_response_model_json2 = metric_token_response_model.to_dict() + assert metric_token_response_model_json2 == metric_token_response_model_json + +class TestNluEnrichmentConcepts(): + """ + Test Class for NluEnrichmentConcepts + """ + + def test_nlu_enrichment_concepts_serialization(self): + """ + Test serialization/deserialization for NluEnrichmentConcepts + """ + + # Construct a json representation of a NluEnrichmentConcepts model + nlu_enrichment_concepts_model_json = {} + nlu_enrichment_concepts_model_json['limit'] = 38 + + # Construct a model instance of NluEnrichmentConcepts by calling from_dict on the json representation + nlu_enrichment_concepts_model = NluEnrichmentConcepts.from_dict(nlu_enrichment_concepts_model_json) + assert nlu_enrichment_concepts_model != False + + # Construct a model instance of NluEnrichmentConcepts by calling from_dict on the json representation + nlu_enrichment_concepts_model_dict = NluEnrichmentConcepts.from_dict(nlu_enrichment_concepts_model_json).__dict__ + nlu_enrichment_concepts_model2 = NluEnrichmentConcepts(**nlu_enrichment_concepts_model_dict) + + # Verify the model instances are equivalent + assert nlu_enrichment_concepts_model == nlu_enrichment_concepts_model2 + + # Convert model instance back to dict and verify no loss of data + nlu_enrichment_concepts_model_json2 = nlu_enrichment_concepts_model.to_dict() + assert nlu_enrichment_concepts_model_json2 == nlu_enrichment_concepts_model_json + +class TestNluEnrichmentEmotion(): + """ + Test Class for NluEnrichmentEmotion + """ + + def test_nlu_enrichment_emotion_serialization(self): + """ + Test serialization/deserialization for NluEnrichmentEmotion + """ + + # Construct a json representation of a NluEnrichmentEmotion model + nlu_enrichment_emotion_model_json = {} + nlu_enrichment_emotion_model_json['document'] = True + nlu_enrichment_emotion_model_json['targets'] = ['testString'] + + # Construct a model instance of NluEnrichmentEmotion by calling from_dict on the json representation + nlu_enrichment_emotion_model = NluEnrichmentEmotion.from_dict(nlu_enrichment_emotion_model_json) + assert nlu_enrichment_emotion_model != False + + # Construct a model instance of NluEnrichmentEmotion by calling from_dict on the json representation + nlu_enrichment_emotion_model_dict = NluEnrichmentEmotion.from_dict(nlu_enrichment_emotion_model_json).__dict__ + nlu_enrichment_emotion_model2 = NluEnrichmentEmotion(**nlu_enrichment_emotion_model_dict) + + # Verify the model instances are equivalent + assert nlu_enrichment_emotion_model == nlu_enrichment_emotion_model2 + + # Convert model instance back to dict and verify no loss of data + nlu_enrichment_emotion_model_json2 = nlu_enrichment_emotion_model.to_dict() + assert nlu_enrichment_emotion_model_json2 == nlu_enrichment_emotion_model_json + +class TestNluEnrichmentEntities(): + """ + Test Class for NluEnrichmentEntities + """ + + def test_nlu_enrichment_entities_serialization(self): + """ + Test serialization/deserialization for NluEnrichmentEntities + """ + + # Construct a json representation of a NluEnrichmentEntities model + nlu_enrichment_entities_model_json = {} + nlu_enrichment_entities_model_json['sentiment'] = True + nlu_enrichment_entities_model_json['emotion'] = True + nlu_enrichment_entities_model_json['limit'] = 38 + nlu_enrichment_entities_model_json['mentions'] = True + nlu_enrichment_entities_model_json['mention_types'] = True + nlu_enrichment_entities_model_json['sentence_locations'] = True + nlu_enrichment_entities_model_json['model'] = 'testString' + + # Construct a model instance of NluEnrichmentEntities by calling from_dict on the json representation + nlu_enrichment_entities_model = NluEnrichmentEntities.from_dict(nlu_enrichment_entities_model_json) + assert nlu_enrichment_entities_model != False + + # Construct a model instance of NluEnrichmentEntities by calling from_dict on the json representation + nlu_enrichment_entities_model_dict = NluEnrichmentEntities.from_dict(nlu_enrichment_entities_model_json).__dict__ + nlu_enrichment_entities_model2 = NluEnrichmentEntities(**nlu_enrichment_entities_model_dict) + + # Verify the model instances are equivalent + assert nlu_enrichment_entities_model == nlu_enrichment_entities_model2 + + # Convert model instance back to dict and verify no loss of data + nlu_enrichment_entities_model_json2 = nlu_enrichment_entities_model.to_dict() + assert nlu_enrichment_entities_model_json2 == nlu_enrichment_entities_model_json + +class TestNluEnrichmentFeatures(): + """ + Test Class for NluEnrichmentFeatures + """ + + def test_nlu_enrichment_features_serialization(self): + """ + Test serialization/deserialization for NluEnrichmentFeatures + """ + + # Construct dict forms of any model objects needed in order to build this model. + + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model['sentiment'] = True + nlu_enrichment_keywords_model['emotion'] = True + nlu_enrichment_keywords_model['limit'] = 38 + + nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model['sentiment'] = True + nlu_enrichment_entities_model['emotion'] = True + nlu_enrichment_entities_model['limit'] = 38 + nlu_enrichment_entities_model['mentions'] = True + nlu_enrichment_entities_model['mention_types'] = True + nlu_enrichment_entities_model['sentence_locations'] = True + nlu_enrichment_entities_model['model'] = 'testString' + + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model['document'] = True + nlu_enrichment_sentiment_model['targets'] = ['testString'] + + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model['document'] = True + nlu_enrichment_emotion_model['targets'] = ['testString'] + + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model['entities'] = True + nlu_enrichment_semantic_roles_model['keywords'] = True + nlu_enrichment_semantic_roles_model['limit'] = 38 + + nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model['model'] = 'testString' + + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model['limit'] = 38 + + # Construct a json representation of a NluEnrichmentFeatures model + nlu_enrichment_features_model_json = {} + nlu_enrichment_features_model_json['keywords'] = nlu_enrichment_keywords_model + nlu_enrichment_features_model_json['entities'] = nlu_enrichment_entities_model + nlu_enrichment_features_model_json['sentiment'] = nlu_enrichment_sentiment_model + nlu_enrichment_features_model_json['emotion'] = nlu_enrichment_emotion_model + nlu_enrichment_features_model_json['categories'] = {} + nlu_enrichment_features_model_json['semantic_roles'] = nlu_enrichment_semantic_roles_model + nlu_enrichment_features_model_json['relations'] = nlu_enrichment_relations_model + nlu_enrichment_features_model_json['concepts'] = nlu_enrichment_concepts_model + + # Construct a model instance of NluEnrichmentFeatures by calling from_dict on the json representation + nlu_enrichment_features_model = NluEnrichmentFeatures.from_dict(nlu_enrichment_features_model_json) + assert nlu_enrichment_features_model != False + + # Construct a model instance of NluEnrichmentFeatures by calling from_dict on the json representation + nlu_enrichment_features_model_dict = NluEnrichmentFeatures.from_dict(nlu_enrichment_features_model_json).__dict__ + nlu_enrichment_features_model2 = NluEnrichmentFeatures(**nlu_enrichment_features_model_dict) + + # Verify the model instances are equivalent + assert nlu_enrichment_features_model == nlu_enrichment_features_model2 + + # Convert model instance back to dict and verify no loss of data + nlu_enrichment_features_model_json2 = nlu_enrichment_features_model.to_dict() + assert nlu_enrichment_features_model_json2 == nlu_enrichment_features_model_json + +class TestNluEnrichmentKeywords(): + """ + Test Class for NluEnrichmentKeywords + """ + + def test_nlu_enrichment_keywords_serialization(self): + """ + Test serialization/deserialization for NluEnrichmentKeywords + """ + + # Construct a json representation of a NluEnrichmentKeywords model + nlu_enrichment_keywords_model_json = {} + nlu_enrichment_keywords_model_json['sentiment'] = True + nlu_enrichment_keywords_model_json['emotion'] = True + nlu_enrichment_keywords_model_json['limit'] = 38 + + # Construct a model instance of NluEnrichmentKeywords by calling from_dict on the json representation + nlu_enrichment_keywords_model = NluEnrichmentKeywords.from_dict(nlu_enrichment_keywords_model_json) + assert nlu_enrichment_keywords_model != False + + # Construct a model instance of NluEnrichmentKeywords by calling from_dict on the json representation + nlu_enrichment_keywords_model_dict = NluEnrichmentKeywords.from_dict(nlu_enrichment_keywords_model_json).__dict__ + nlu_enrichment_keywords_model2 = NluEnrichmentKeywords(**nlu_enrichment_keywords_model_dict) + + # Verify the model instances are equivalent + assert nlu_enrichment_keywords_model == nlu_enrichment_keywords_model2 + + # Convert model instance back to dict and verify no loss of data + nlu_enrichment_keywords_model_json2 = nlu_enrichment_keywords_model.to_dict() + assert nlu_enrichment_keywords_model_json2 == nlu_enrichment_keywords_model_json + +class TestNluEnrichmentRelations(): + """ + Test Class for NluEnrichmentRelations + """ + + def test_nlu_enrichment_relations_serialization(self): + """ + Test serialization/deserialization for NluEnrichmentRelations + """ + + # Construct a json representation of a NluEnrichmentRelations model + nlu_enrichment_relations_model_json = {} + nlu_enrichment_relations_model_json['model'] = 'testString' + + # Construct a model instance of NluEnrichmentRelations by calling from_dict on the json representation + nlu_enrichment_relations_model = NluEnrichmentRelations.from_dict(nlu_enrichment_relations_model_json) + assert nlu_enrichment_relations_model != False + + # Construct a model instance of NluEnrichmentRelations by calling from_dict on the json representation + nlu_enrichment_relations_model_dict = NluEnrichmentRelations.from_dict(nlu_enrichment_relations_model_json).__dict__ + nlu_enrichment_relations_model2 = NluEnrichmentRelations(**nlu_enrichment_relations_model_dict) + + # Verify the model instances are equivalent + assert nlu_enrichment_relations_model == nlu_enrichment_relations_model2 + + # Convert model instance back to dict and verify no loss of data + nlu_enrichment_relations_model_json2 = nlu_enrichment_relations_model.to_dict() + assert nlu_enrichment_relations_model_json2 == nlu_enrichment_relations_model_json + +class TestNluEnrichmentSemanticRoles(): + """ + Test Class for NluEnrichmentSemanticRoles + """ + + def test_nlu_enrichment_semantic_roles_serialization(self): + """ + Test serialization/deserialization for NluEnrichmentSemanticRoles + """ + + # Construct a json representation of a NluEnrichmentSemanticRoles model + nlu_enrichment_semantic_roles_model_json = {} + nlu_enrichment_semantic_roles_model_json['entities'] = True + nlu_enrichment_semantic_roles_model_json['keywords'] = True + nlu_enrichment_semantic_roles_model_json['limit'] = 38 + + # Construct a model instance of NluEnrichmentSemanticRoles by calling from_dict on the json representation + nlu_enrichment_semantic_roles_model = NluEnrichmentSemanticRoles.from_dict(nlu_enrichment_semantic_roles_model_json) + assert nlu_enrichment_semantic_roles_model != False + + # Construct a model instance of NluEnrichmentSemanticRoles by calling from_dict on the json representation + nlu_enrichment_semantic_roles_model_dict = NluEnrichmentSemanticRoles.from_dict(nlu_enrichment_semantic_roles_model_json).__dict__ + nlu_enrichment_semantic_roles_model2 = NluEnrichmentSemanticRoles(**nlu_enrichment_semantic_roles_model_dict) + + # Verify the model instances are equivalent + assert nlu_enrichment_semantic_roles_model == nlu_enrichment_semantic_roles_model2 + + # Convert model instance back to dict and verify no loss of data + nlu_enrichment_semantic_roles_model_json2 = nlu_enrichment_semantic_roles_model.to_dict() + assert nlu_enrichment_semantic_roles_model_json2 == nlu_enrichment_semantic_roles_model_json + +class TestNluEnrichmentSentiment(): + """ + Test Class for NluEnrichmentSentiment + """ + + def test_nlu_enrichment_sentiment_serialization(self): + """ + Test serialization/deserialization for NluEnrichmentSentiment + """ + + # Construct a json representation of a NluEnrichmentSentiment model + nlu_enrichment_sentiment_model_json = {} + nlu_enrichment_sentiment_model_json['document'] = True + nlu_enrichment_sentiment_model_json['targets'] = ['testString'] + + # Construct a model instance of NluEnrichmentSentiment by calling from_dict on the json representation + nlu_enrichment_sentiment_model = NluEnrichmentSentiment.from_dict(nlu_enrichment_sentiment_model_json) + assert nlu_enrichment_sentiment_model != False + + # Construct a model instance of NluEnrichmentSentiment by calling from_dict on the json representation + nlu_enrichment_sentiment_model_dict = NluEnrichmentSentiment.from_dict(nlu_enrichment_sentiment_model_json).__dict__ + nlu_enrichment_sentiment_model2 = NluEnrichmentSentiment(**nlu_enrichment_sentiment_model_dict) + + # Verify the model instances are equivalent + assert nlu_enrichment_sentiment_model == nlu_enrichment_sentiment_model2 + + # Convert model instance back to dict and verify no loss of data + nlu_enrichment_sentiment_model_json2 = nlu_enrichment_sentiment_model.to_dict() + assert nlu_enrichment_sentiment_model_json2 == nlu_enrichment_sentiment_model_json + +class TestNormalizationOperation(): + """ + Test Class for NormalizationOperation + """ + + def test_normalization_operation_serialization(self): + """ + Test serialization/deserialization for NormalizationOperation + """ + + # Construct a json representation of a NormalizationOperation model + normalization_operation_model_json = {} + normalization_operation_model_json['operation'] = 'copy' + normalization_operation_model_json['source_field'] = 'testString' + normalization_operation_model_json['destination_field'] = 'testString' + + # Construct a model instance of NormalizationOperation by calling from_dict on the json representation + normalization_operation_model = NormalizationOperation.from_dict(normalization_operation_model_json) + assert normalization_operation_model != False + + # Construct a model instance of NormalizationOperation by calling from_dict on the json representation + normalization_operation_model_dict = NormalizationOperation.from_dict(normalization_operation_model_json).__dict__ + normalization_operation_model2 = NormalizationOperation(**normalization_operation_model_dict) + + # Verify the model instances are equivalent + assert normalization_operation_model == normalization_operation_model2 + + # Convert model instance back to dict and verify no loss of data + normalization_operation_model_json2 = normalization_operation_model.to_dict() + assert normalization_operation_model_json2 == normalization_operation_model_json + +class TestNotice(): + """ + Test Class for Notice + """ + + def test_notice_serialization(self): + """ + Test serialization/deserialization for Notice + """ + + # Construct a json representation of a Notice model + notice_model_json = {} + notice_model_json['notice_id'] = 'testString' + notice_model_json['created'] = '2020-01-28T18:40:40.123456Z' + notice_model_json['document_id'] = 'testString' + notice_model_json['query_id'] = 'testString' + notice_model_json['severity'] = 'warning' + notice_model_json['step'] = 'testString' + notice_model_json['description'] = 'testString' + + # Construct a model instance of Notice by calling from_dict on the json representation + notice_model = Notice.from_dict(notice_model_json) + assert notice_model != False + + # Construct a model instance of Notice by calling from_dict on the json representation + notice_model_dict = Notice.from_dict(notice_model_json).__dict__ + notice_model2 = Notice(**notice_model_dict) + + # Verify the model instances are equivalent + assert notice_model == notice_model2 + + # Convert model instance back to dict and verify no loss of data + notice_model_json2 = notice_model.to_dict() + assert notice_model_json2 == notice_model_json + +class TestPdfHeadingDetection(): + """ + Test Class for PdfHeadingDetection + """ + + def test_pdf_heading_detection_serialization(self): + """ + Test serialization/deserialization for PdfHeadingDetection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + font_setting_model = {} # FontSetting + font_setting_model['level'] = 38 + font_setting_model['min_size'] = 38 + font_setting_model['max_size'] = 38 + font_setting_model['bold'] = True + font_setting_model['italic'] = True + font_setting_model['name'] = 'testString' + + # Construct a json representation of a PdfHeadingDetection model + pdf_heading_detection_model_json = {} + pdf_heading_detection_model_json['fonts'] = [font_setting_model] + + # Construct a model instance of PdfHeadingDetection by calling from_dict on the json representation + pdf_heading_detection_model = PdfHeadingDetection.from_dict(pdf_heading_detection_model_json) + assert pdf_heading_detection_model != False + + # Construct a model instance of PdfHeadingDetection by calling from_dict on the json representation + pdf_heading_detection_model_dict = PdfHeadingDetection.from_dict(pdf_heading_detection_model_json).__dict__ + pdf_heading_detection_model2 = PdfHeadingDetection(**pdf_heading_detection_model_dict) + + # Verify the model instances are equivalent + assert pdf_heading_detection_model == pdf_heading_detection_model2 + + # Convert model instance back to dict and verify no loss of data + pdf_heading_detection_model_json2 = pdf_heading_detection_model.to_dict() + assert pdf_heading_detection_model_json2 == pdf_heading_detection_model_json + +class TestPdfSettings(): + """ + Test Class for PdfSettings + """ + + def test_pdf_settings_serialization(self): + """ + Test serialization/deserialization for PdfSettings + """ + + # Construct dict forms of any model objects needed in order to build this model. + + font_setting_model = {} # FontSetting + font_setting_model['level'] = 38 + font_setting_model['min_size'] = 38 + font_setting_model['max_size'] = 38 + font_setting_model['bold'] = True + font_setting_model['italic'] = True + font_setting_model['name'] = 'testString' + + pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model['fonts'] = [font_setting_model] + + # Construct a json representation of a PdfSettings model + pdf_settings_model_json = {} + pdf_settings_model_json['heading'] = pdf_heading_detection_model + + # Construct a model instance of PdfSettings by calling from_dict on the json representation + pdf_settings_model = PdfSettings.from_dict(pdf_settings_model_json) + assert pdf_settings_model != False + + # Construct a model instance of PdfSettings by calling from_dict on the json representation + pdf_settings_model_dict = PdfSettings.from_dict(pdf_settings_model_json).__dict__ + pdf_settings_model2 = PdfSettings(**pdf_settings_model_dict) + + # Verify the model instances are equivalent + assert pdf_settings_model == pdf_settings_model2 + + # Convert model instance back to dict and verify no loss of data + pdf_settings_model_json2 = pdf_settings_model.to_dict() + assert pdf_settings_model_json2 == pdf_settings_model_json + +class TestQueryAggregation(): + """ + Test Class for QueryAggregation + """ + + def test_query_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryAggregation + """ + + # Construct a json representation of a QueryAggregation model + query_aggregation_model_json = {} + query_aggregation_model_json['type'] = 'testString' + query_aggregation_model_json['matching_results'] = 38 + + # Construct a model instance of QueryAggregation by calling from_dict on the json representation + query_aggregation_model = QueryAggregation.from_dict(query_aggregation_model_json) + assert query_aggregation_model != False + + # Construct a copy of the model instance by calling from_dict on the output of to_dict + query_aggregation_model_json2 = query_aggregation_model.to_dict() + query_aggregation_model2 = QueryAggregation.from_dict(query_aggregation_model_json2) + + # Verify the model instances are equivalent + assert query_aggregation_model == query_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_aggregation_model_json2 = query_aggregation_model.to_dict() + assert query_aggregation_model_json2 == query_aggregation_model_json + +class TestQueryNoticesResponse(): + """ + Test Class for QueryNoticesResponse + """ + + def test_query_notices_response_serialization(self): + """ + Test serialization/deserialization for QueryNoticesResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model['score'] = 72.5 + query_result_metadata_model['confidence'] = 72.5 + + notice_model = {} # Notice + notice_model['notice_id'] = 'xpath_not_found' + notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['document_id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' + notice_model['query_id'] = 'testString' + notice_model['severity'] = 'warning' + notice_model['step'] = 'html-to-html' + notice_model['description'] = 'The xpath expression "boom" was not found.' + + query_notices_result_model = {} # QueryNoticesResult + query_notices_result_model['id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' + query_notices_result_model['metadata'] = {} + query_notices_result_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' + query_notices_result_model['result_metadata'] = query_result_metadata_model + query_notices_result_model['code'] = 200 + query_notices_result_model['filename'] = 'instructions.html' + query_notices_result_model['file_type'] = 'html' + query_notices_result_model['sha1'] = 'de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3' + query_notices_result_model['notices'] = [notice_model] + query_notices_result_model['foo'] = { 'foo': 'bar' } + + query_aggregation_model = {} # Histogram + query_aggregation_model['type'] = 'histogram' + query_aggregation_model['matching_results'] = 38 + query_aggregation_model['field'] = 'testString' + query_aggregation_model['interval'] = 38 + + query_passages_model = {} # QueryPassages + query_passages_model['document_id'] = 'testString' + query_passages_model['passage_score'] = 72.5 + query_passages_model['passage_text'] = 'testString' + query_passages_model['start_offset'] = 38 + query_passages_model['end_offset'] = 38 + query_passages_model['field'] = 'testString' + + # Construct a json representation of a QueryNoticesResponse model + query_notices_response_model_json = {} + query_notices_response_model_json['matching_results'] = 38 + query_notices_response_model_json['results'] = [query_notices_result_model] + query_notices_response_model_json['aggregations'] = [query_aggregation_model] + query_notices_response_model_json['passages'] = [query_passages_model] + query_notices_response_model_json['duplicates_removed'] = 38 + + # Construct a model instance of QueryNoticesResponse by calling from_dict on the json representation + query_notices_response_model = QueryNoticesResponse.from_dict(query_notices_response_model_json) + assert query_notices_response_model != False + + # Construct a model instance of QueryNoticesResponse by calling from_dict on the json representation + query_notices_response_model_dict = QueryNoticesResponse.from_dict(query_notices_response_model_json).__dict__ + query_notices_response_model2 = QueryNoticesResponse(**query_notices_response_model_dict) + + # Verify the model instances are equivalent + assert query_notices_response_model == query_notices_response_model2 + + # Convert model instance back to dict and verify no loss of data + query_notices_response_model_json2 = query_notices_response_model.to_dict() + assert query_notices_response_model_json2 == query_notices_response_model_json + +class TestQueryNoticesResult(): + """ + Test Class for QueryNoticesResult + """ + + def test_query_notices_result_serialization(self): + """ + Test serialization/deserialization for QueryNoticesResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model['score'] = 72.5 + query_result_metadata_model['confidence'] = 72.5 + + notice_model = {} # Notice + notice_model['notice_id'] = 'testString' + notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['document_id'] = 'testString' + notice_model['query_id'] = 'testString' + notice_model['severity'] = 'warning' + notice_model['step'] = 'testString' + notice_model['description'] = 'testString' + + # Construct a json representation of a QueryNoticesResult model + query_notices_result_model_json = {} + query_notices_result_model_json['id'] = 'testString' + query_notices_result_model_json['metadata'] = {} + query_notices_result_model_json['collection_id'] = 'testString' + query_notices_result_model_json['result_metadata'] = query_result_metadata_model + query_notices_result_model_json['code'] = 38 + query_notices_result_model_json['filename'] = 'testString' + query_notices_result_model_json['file_type'] = 'pdf' + query_notices_result_model_json['sha1'] = 'testString' + query_notices_result_model_json['notices'] = [notice_model] + query_notices_result_model_json['foo'] = { 'foo': 'bar' } + + # Construct a model instance of QueryNoticesResult by calling from_dict on the json representation + query_notices_result_model = QueryNoticesResult.from_dict(query_notices_result_model_json) + assert query_notices_result_model != False + + # Construct a model instance of QueryNoticesResult by calling from_dict on the json representation + query_notices_result_model_dict = QueryNoticesResult.from_dict(query_notices_result_model_json).__dict__ + query_notices_result_model2 = QueryNoticesResult(**query_notices_result_model_dict) + + # Verify the model instances are equivalent + assert query_notices_result_model == query_notices_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_notices_result_model_json2 = query_notices_result_model.to_dict() + assert query_notices_result_model_json2 == query_notices_result_model_json + +class TestQueryPassages(): + """ + Test Class for QueryPassages + """ + + def test_query_passages_serialization(self): + """ + Test serialization/deserialization for QueryPassages + """ + + # Construct a json representation of a QueryPassages model + query_passages_model_json = {} + query_passages_model_json['document_id'] = 'testString' + query_passages_model_json['passage_score'] = 72.5 + query_passages_model_json['passage_text'] = 'testString' + query_passages_model_json['start_offset'] = 38 + query_passages_model_json['end_offset'] = 38 + query_passages_model_json['field'] = 'testString' + + # Construct a model instance of QueryPassages by calling from_dict on the json representation + query_passages_model = QueryPassages.from_dict(query_passages_model_json) + assert query_passages_model != False + + # Construct a model instance of QueryPassages by calling from_dict on the json representation + query_passages_model_dict = QueryPassages.from_dict(query_passages_model_json).__dict__ + query_passages_model2 = QueryPassages(**query_passages_model_dict) + + # Verify the model instances are equivalent + assert query_passages_model == query_passages_model2 + + # Convert model instance back to dict and verify no loss of data + query_passages_model_json2 = query_passages_model.to_dict() + assert query_passages_model_json2 == query_passages_model_json + +class TestQueryResponse(): + """ + Test Class for QueryResponse + """ + + def test_query_response_serialization(self): + """ + Test serialization/deserialization for QueryResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model['score'] = 72.5 + query_result_metadata_model['confidence'] = 72.5 + + query_result_model = {} # QueryResult + query_result_model['id'] = 'watson-generated ID' + query_result_model['metadata'] = {} + query_result_model['collection_id'] = 'testString' + query_result_model['result_metadata'] = query_result_metadata_model + query_result_model['foo'] = { 'foo': 'bar' } + + query_aggregation_model = {} # Histogram + query_aggregation_model['type'] = 'histogram' + query_aggregation_model['matching_results'] = 38 + query_aggregation_model['field'] = 'testString' + query_aggregation_model['interval'] = 38 + + query_passages_model = {} # QueryPassages + query_passages_model['document_id'] = 'testString' + query_passages_model['passage_score'] = 72.5 + query_passages_model['passage_text'] = 'testString' + query_passages_model['start_offset'] = 38 + query_passages_model['end_offset'] = 38 + query_passages_model['field'] = 'testString' + + retrieval_details_model = {} # RetrievalDetails + retrieval_details_model['document_retrieval_strategy'] = 'untrained' + + # Construct a json representation of a QueryResponse model + query_response_model_json = {} + query_response_model_json['matching_results'] = 38 + query_response_model_json['results'] = [query_result_model] + query_response_model_json['aggregations'] = [query_aggregation_model] + query_response_model_json['passages'] = [query_passages_model] + query_response_model_json['duplicates_removed'] = 38 + query_response_model_json['session_token'] = 'testString' + query_response_model_json['retrieval_details'] = retrieval_details_model + query_response_model_json['suggested_query'] = 'testString' + + # Construct a model instance of QueryResponse by calling from_dict on the json representation + query_response_model = QueryResponse.from_dict(query_response_model_json) + assert query_response_model != False + + # Construct a model instance of QueryResponse by calling from_dict on the json representation + query_response_model_dict = QueryResponse.from_dict(query_response_model_json).__dict__ + query_response_model2 = QueryResponse(**query_response_model_dict) + + # Verify the model instances are equivalent + assert query_response_model == query_response_model2 + + # Convert model instance back to dict and verify no loss of data + query_response_model_json2 = query_response_model.to_dict() + assert query_response_model_json2 == query_response_model_json + +class TestQueryResult(): + """ + Test Class for QueryResult + """ + + def test_query_result_serialization(self): + """ + Test serialization/deserialization for QueryResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model['score'] = 72.5 + query_result_metadata_model['confidence'] = 72.5 + + # Construct a json representation of a QueryResult model + query_result_model_json = {} + query_result_model_json['id'] = 'testString' + query_result_model_json['metadata'] = {} + query_result_model_json['collection_id'] = 'testString' + query_result_model_json['result_metadata'] = query_result_metadata_model + query_result_model_json['foo'] = { 'foo': 'bar' } + + # Construct a model instance of QueryResult by calling from_dict on the json representation + query_result_model = QueryResult.from_dict(query_result_model_json) + assert query_result_model != False + + # Construct a model instance of QueryResult by calling from_dict on the json representation + query_result_model_dict = QueryResult.from_dict(query_result_model_json).__dict__ + query_result_model2 = QueryResult(**query_result_model_dict) + + # Verify the model instances are equivalent + assert query_result_model == query_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_result_model_json2 = query_result_model.to_dict() + assert query_result_model_json2 == query_result_model_json + +class TestQueryResultMetadata(): + """ + Test Class for QueryResultMetadata + """ + + def test_query_result_metadata_serialization(self): + """ + Test serialization/deserialization for QueryResultMetadata + """ + + # Construct a json representation of a QueryResultMetadata model + query_result_metadata_model_json = {} + query_result_metadata_model_json['score'] = 72.5 + query_result_metadata_model_json['confidence'] = 72.5 + + # Construct a model instance of QueryResultMetadata by calling from_dict on the json representation + query_result_metadata_model = QueryResultMetadata.from_dict(query_result_metadata_model_json) + assert query_result_metadata_model != False + + # Construct a model instance of QueryResultMetadata by calling from_dict on the json representation + query_result_metadata_model_dict = QueryResultMetadata.from_dict(query_result_metadata_model_json).__dict__ + query_result_metadata_model2 = QueryResultMetadata(**query_result_metadata_model_dict) + + # Verify the model instances are equivalent + assert query_result_metadata_model == query_result_metadata_model2 + + # Convert model instance back to dict and verify no loss of data + query_result_metadata_model_json2 = query_result_metadata_model.to_dict() + assert query_result_metadata_model_json2 == query_result_metadata_model_json + +class TestRetrievalDetails(): + """ + Test Class for RetrievalDetails + """ + + def test_retrieval_details_serialization(self): + """ + Test serialization/deserialization for RetrievalDetails + """ + + # Construct a json representation of a RetrievalDetails model + retrieval_details_model_json = {} + retrieval_details_model_json['document_retrieval_strategy'] = 'untrained' + + # Construct a model instance of RetrievalDetails by calling from_dict on the json representation + retrieval_details_model = RetrievalDetails.from_dict(retrieval_details_model_json) + assert retrieval_details_model != False + + # Construct a model instance of RetrievalDetails by calling from_dict on the json representation + retrieval_details_model_dict = RetrievalDetails.from_dict(retrieval_details_model_json).__dict__ + retrieval_details_model2 = RetrievalDetails(**retrieval_details_model_dict) + + # Verify the model instances are equivalent + assert retrieval_details_model == retrieval_details_model2 + + # Convert model instance back to dict and verify no loss of data + retrieval_details_model_json2 = retrieval_details_model.to_dict() + assert retrieval_details_model_json2 == retrieval_details_model_json + +class TestSduStatus(): + """ + Test Class for SduStatus + """ + + def test_sdu_status_serialization(self): + """ + Test serialization/deserialization for SduStatus + """ + + # Construct dict forms of any model objects needed in order to build this model. + + sdu_status_custom_fields_model = {} # SduStatusCustomFields + sdu_status_custom_fields_model['defined'] = 26 + sdu_status_custom_fields_model['maximum_allowed'] = 26 + + # Construct a json representation of a SduStatus model + sdu_status_model_json = {} + sdu_status_model_json['enabled'] = True + sdu_status_model_json['total_annotated_pages'] = 26 + sdu_status_model_json['total_pages'] = 26 + sdu_status_model_json['total_documents'] = 26 + sdu_status_model_json['custom_fields'] = sdu_status_custom_fields_model + + # Construct a model instance of SduStatus by calling from_dict on the json representation + sdu_status_model = SduStatus.from_dict(sdu_status_model_json) + assert sdu_status_model != False + + # Construct a model instance of SduStatus by calling from_dict on the json representation + sdu_status_model_dict = SduStatus.from_dict(sdu_status_model_json).__dict__ + sdu_status_model2 = SduStatus(**sdu_status_model_dict) + + # Verify the model instances are equivalent + assert sdu_status_model == sdu_status_model2 + + # Convert model instance back to dict and verify no loss of data + sdu_status_model_json2 = sdu_status_model.to_dict() + assert sdu_status_model_json2 == sdu_status_model_json + +class TestSduStatusCustomFields(): + """ + Test Class for SduStatusCustomFields + """ + + def test_sdu_status_custom_fields_serialization(self): + """ + Test serialization/deserialization for SduStatusCustomFields + """ + + # Construct a json representation of a SduStatusCustomFields model + sdu_status_custom_fields_model_json = {} + sdu_status_custom_fields_model_json['defined'] = 26 + sdu_status_custom_fields_model_json['maximum_allowed'] = 26 + + # Construct a model instance of SduStatusCustomFields by calling from_dict on the json representation + sdu_status_custom_fields_model = SduStatusCustomFields.from_dict(sdu_status_custom_fields_model_json) + assert sdu_status_custom_fields_model != False + + # Construct a model instance of SduStatusCustomFields by calling from_dict on the json representation + sdu_status_custom_fields_model_dict = SduStatusCustomFields.from_dict(sdu_status_custom_fields_model_json).__dict__ + sdu_status_custom_fields_model2 = SduStatusCustomFields(**sdu_status_custom_fields_model_dict) + + # Verify the model instances are equivalent + assert sdu_status_custom_fields_model == sdu_status_custom_fields_model2 + + # Convert model instance back to dict and verify no loss of data + sdu_status_custom_fields_model_json2 = sdu_status_custom_fields_model.to_dict() + assert sdu_status_custom_fields_model_json2 == sdu_status_custom_fields_model_json + +class TestSearchStatus(): + """ + Test Class for SearchStatus + """ + + def test_search_status_serialization(self): + """ + Test serialization/deserialization for SearchStatus + """ + + # Construct a json representation of a SearchStatus model + search_status_model_json = {} + search_status_model_json['scope'] = 'testString' + search_status_model_json['status'] = 'NO_DATA' + search_status_model_json['status_description'] = 'testString' + search_status_model_json['last_trained'] = '2020-01-28' + + # Construct a model instance of SearchStatus by calling from_dict on the json representation + search_status_model = SearchStatus.from_dict(search_status_model_json) + assert search_status_model != False + + # Construct a model instance of SearchStatus by calling from_dict on the json representation + search_status_model_dict = SearchStatus.from_dict(search_status_model_json).__dict__ + search_status_model2 = SearchStatus(**search_status_model_dict) + + # Verify the model instances are equivalent + assert search_status_model == search_status_model2 + + # Convert model instance back to dict and verify no loss of data + search_status_model_json2 = search_status_model.to_dict() + assert search_status_model_json2 == search_status_model_json + +class TestSegmentSettings(): + """ + Test Class for SegmentSettings + """ + + def test_segment_settings_serialization(self): + """ + Test serialization/deserialization for SegmentSettings + """ + + # Construct a json representation of a SegmentSettings model + segment_settings_model_json = {} + segment_settings_model_json['enabled'] = True + segment_settings_model_json['selector_tags'] = ['testString'] + segment_settings_model_json['annotated_fields'] = ['testString'] + + # Construct a model instance of SegmentSettings by calling from_dict on the json representation + segment_settings_model = SegmentSettings.from_dict(segment_settings_model_json) + assert segment_settings_model != False + + # Construct a model instance of SegmentSettings by calling from_dict on the json representation + segment_settings_model_dict = SegmentSettings.from_dict(segment_settings_model_json).__dict__ + segment_settings_model2 = SegmentSettings(**segment_settings_model_dict) + + # Verify the model instances are equivalent + assert segment_settings_model == segment_settings_model2 + + # Convert model instance back to dict and verify no loss of data + segment_settings_model_json2 = segment_settings_model.to_dict() + assert segment_settings_model_json2 == segment_settings_model_json + +class TestSource(): + """ + Test Class for Source + """ + + def test_source_serialization(self): + """ + Test serialization/deserialization for Source + """ + + # Construct dict forms of any model objects needed in order to build this model. + + source_schedule_model = {} # SourceSchedule + source_schedule_model['enabled'] = True + source_schedule_model['time_zone'] = 'testString' + source_schedule_model['frequency'] = 'daily' + + source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model['owner_user_id'] = 'testString' + source_options_folder_model['folder_id'] = 'testString' + source_options_folder_model['limit'] = 38 + + source_options_object_model = {} # SourceOptionsObject + source_options_object_model['name'] = 'testString' + source_options_object_model['limit'] = 38 + + source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model['site_collection_path'] = 'testString' + source_options_site_coll_model['limit'] = 38 + + source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model['url'] = 'testString' + source_options_web_crawl_model['limit_to_starting_hosts'] = True + source_options_web_crawl_model['crawl_speed'] = 'gentle' + source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['maximum_hops'] = 38 + source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['blacklist'] = ['testString'] + + source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model['name'] = 'testString' + source_options_buckets_model['limit'] = 38 + + source_options_model = {} # SourceOptions + source_options_model['folders'] = [source_options_folder_model] + source_options_model['objects'] = [source_options_object_model] + source_options_model['site_collections'] = [source_options_site_coll_model] + source_options_model['urls'] = [source_options_web_crawl_model] + source_options_model['buckets'] = [source_options_buckets_model] + source_options_model['crawl_all_buckets'] = True + + # Construct a json representation of a Source model + source_model_json = {} + source_model_json['type'] = 'box' + source_model_json['credential_id'] = 'testString' + source_model_json['schedule'] = source_schedule_model + source_model_json['options'] = source_options_model + + # Construct a model instance of Source by calling from_dict on the json representation + source_model = Source.from_dict(source_model_json) + assert source_model != False + + # Construct a model instance of Source by calling from_dict on the json representation + source_model_dict = Source.from_dict(source_model_json).__dict__ + source_model2 = Source(**source_model_dict) + + # Verify the model instances are equivalent + assert source_model == source_model2 + + # Convert model instance back to dict and verify no loss of data + source_model_json2 = source_model.to_dict() + assert source_model_json2 == source_model_json + +class TestSourceOptions(): + """ + Test Class for SourceOptions + """ + + def test_source_options_serialization(self): + """ + Test serialization/deserialization for SourceOptions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model['owner_user_id'] = 'testString' + source_options_folder_model['folder_id'] = 'testString' + source_options_folder_model['limit'] = 38 + + source_options_object_model = {} # SourceOptionsObject + source_options_object_model['name'] = 'testString' + source_options_object_model['limit'] = 38 + + source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model['site_collection_path'] = 'testString' + source_options_site_coll_model['limit'] = 38 + + source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model['url'] = 'testString' + source_options_web_crawl_model['limit_to_starting_hosts'] = True + source_options_web_crawl_model['crawl_speed'] = 'gentle' + source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['maximum_hops'] = 38 + source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['blacklist'] = ['testString'] + + source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model['name'] = 'testString' + source_options_buckets_model['limit'] = 38 + + # Construct a json representation of a SourceOptions model + source_options_model_json = {} + source_options_model_json['folders'] = [source_options_folder_model] + source_options_model_json['objects'] = [source_options_object_model] + source_options_model_json['site_collections'] = [source_options_site_coll_model] + source_options_model_json['urls'] = [source_options_web_crawl_model] + source_options_model_json['buckets'] = [source_options_buckets_model] + source_options_model_json['crawl_all_buckets'] = True + + # Construct a model instance of SourceOptions by calling from_dict on the json representation + source_options_model = SourceOptions.from_dict(source_options_model_json) + assert source_options_model != False + + # Construct a model instance of SourceOptions by calling from_dict on the json representation + source_options_model_dict = SourceOptions.from_dict(source_options_model_json).__dict__ + source_options_model2 = SourceOptions(**source_options_model_dict) + + # Verify the model instances are equivalent + assert source_options_model == source_options_model2 + + # Convert model instance back to dict and verify no loss of data + source_options_model_json2 = source_options_model.to_dict() + assert source_options_model_json2 == source_options_model_json + +class TestSourceOptionsBuckets(): + """ + Test Class for SourceOptionsBuckets + """ + + def test_source_options_buckets_serialization(self): + """ + Test serialization/deserialization for SourceOptionsBuckets + """ + + # Construct a json representation of a SourceOptionsBuckets model + source_options_buckets_model_json = {} + source_options_buckets_model_json['name'] = 'testString' + source_options_buckets_model_json['limit'] = 38 + + # Construct a model instance of SourceOptionsBuckets by calling from_dict on the json representation + source_options_buckets_model = SourceOptionsBuckets.from_dict(source_options_buckets_model_json) + assert source_options_buckets_model != False + + # Construct a model instance of SourceOptionsBuckets by calling from_dict on the json representation + source_options_buckets_model_dict = SourceOptionsBuckets.from_dict(source_options_buckets_model_json).__dict__ + source_options_buckets_model2 = SourceOptionsBuckets(**source_options_buckets_model_dict) + + # Verify the model instances are equivalent + assert source_options_buckets_model == source_options_buckets_model2 + + # Convert model instance back to dict and verify no loss of data + source_options_buckets_model_json2 = source_options_buckets_model.to_dict() + assert source_options_buckets_model_json2 == source_options_buckets_model_json + +class TestSourceOptionsFolder(): + """ + Test Class for SourceOptionsFolder + """ + + def test_source_options_folder_serialization(self): + """ + Test serialization/deserialization for SourceOptionsFolder + """ + + # Construct a json representation of a SourceOptionsFolder model + source_options_folder_model_json = {} + source_options_folder_model_json['owner_user_id'] = 'testString' + source_options_folder_model_json['folder_id'] = 'testString' + source_options_folder_model_json['limit'] = 38 + + # Construct a model instance of SourceOptionsFolder by calling from_dict on the json representation + source_options_folder_model = SourceOptionsFolder.from_dict(source_options_folder_model_json) + assert source_options_folder_model != False + + # Construct a model instance of SourceOptionsFolder by calling from_dict on the json representation + source_options_folder_model_dict = SourceOptionsFolder.from_dict(source_options_folder_model_json).__dict__ + source_options_folder_model2 = SourceOptionsFolder(**source_options_folder_model_dict) + + # Verify the model instances are equivalent + assert source_options_folder_model == source_options_folder_model2 + + # Convert model instance back to dict and verify no loss of data + source_options_folder_model_json2 = source_options_folder_model.to_dict() + assert source_options_folder_model_json2 == source_options_folder_model_json + +class TestSourceOptionsObject(): + """ + Test Class for SourceOptionsObject + """ + + def test_source_options_object_serialization(self): + """ + Test serialization/deserialization for SourceOptionsObject + """ + + # Construct a json representation of a SourceOptionsObject model + source_options_object_model_json = {} + source_options_object_model_json['name'] = 'testString' + source_options_object_model_json['limit'] = 38 + + # Construct a model instance of SourceOptionsObject by calling from_dict on the json representation + source_options_object_model = SourceOptionsObject.from_dict(source_options_object_model_json) + assert source_options_object_model != False + + # Construct a model instance of SourceOptionsObject by calling from_dict on the json representation + source_options_object_model_dict = SourceOptionsObject.from_dict(source_options_object_model_json).__dict__ + source_options_object_model2 = SourceOptionsObject(**source_options_object_model_dict) + + # Verify the model instances are equivalent + assert source_options_object_model == source_options_object_model2 + + # Convert model instance back to dict and verify no loss of data + source_options_object_model_json2 = source_options_object_model.to_dict() + assert source_options_object_model_json2 == source_options_object_model_json + +class TestSourceOptionsSiteColl(): + """ + Test Class for SourceOptionsSiteColl + """ + + def test_source_options_site_coll_serialization(self): + """ + Test serialization/deserialization for SourceOptionsSiteColl + """ + + # Construct a json representation of a SourceOptionsSiteColl model + source_options_site_coll_model_json = {} + source_options_site_coll_model_json['site_collection_path'] = 'testString' + source_options_site_coll_model_json['limit'] = 38 + + # Construct a model instance of SourceOptionsSiteColl by calling from_dict on the json representation + source_options_site_coll_model = SourceOptionsSiteColl.from_dict(source_options_site_coll_model_json) + assert source_options_site_coll_model != False + + # Construct a model instance of SourceOptionsSiteColl by calling from_dict on the json representation + source_options_site_coll_model_dict = SourceOptionsSiteColl.from_dict(source_options_site_coll_model_json).__dict__ + source_options_site_coll_model2 = SourceOptionsSiteColl(**source_options_site_coll_model_dict) + + # Verify the model instances are equivalent + assert source_options_site_coll_model == source_options_site_coll_model2 + + # Convert model instance back to dict and verify no loss of data + source_options_site_coll_model_json2 = source_options_site_coll_model.to_dict() + assert source_options_site_coll_model_json2 == source_options_site_coll_model_json + +class TestSourceOptionsWebCrawl(): + """ + Test Class for SourceOptionsWebCrawl + """ + + def test_source_options_web_crawl_serialization(self): + """ + Test serialization/deserialization for SourceOptionsWebCrawl + """ + + # Construct a json representation of a SourceOptionsWebCrawl model + source_options_web_crawl_model_json = {} + source_options_web_crawl_model_json['url'] = 'testString' + source_options_web_crawl_model_json['limit_to_starting_hosts'] = True + source_options_web_crawl_model_json['crawl_speed'] = 'gentle' + source_options_web_crawl_model_json['allow_untrusted_certificate'] = True + source_options_web_crawl_model_json['maximum_hops'] = 38 + source_options_web_crawl_model_json['request_timeout'] = 38 + source_options_web_crawl_model_json['override_robots_txt'] = True + source_options_web_crawl_model_json['blacklist'] = ['testString'] + + # Construct a model instance of SourceOptionsWebCrawl by calling from_dict on the json representation + source_options_web_crawl_model = SourceOptionsWebCrawl.from_dict(source_options_web_crawl_model_json) + assert source_options_web_crawl_model != False + + # Construct a model instance of SourceOptionsWebCrawl by calling from_dict on the json representation + source_options_web_crawl_model_dict = SourceOptionsWebCrawl.from_dict(source_options_web_crawl_model_json).__dict__ + source_options_web_crawl_model2 = SourceOptionsWebCrawl(**source_options_web_crawl_model_dict) + + # Verify the model instances are equivalent + assert source_options_web_crawl_model == source_options_web_crawl_model2 + + # Convert model instance back to dict and verify no loss of data + source_options_web_crawl_model_json2 = source_options_web_crawl_model.to_dict() + assert source_options_web_crawl_model_json2 == source_options_web_crawl_model_json + +class TestSourceSchedule(): + """ + Test Class for SourceSchedule + """ + + def test_source_schedule_serialization(self): + """ + Test serialization/deserialization for SourceSchedule + """ + + # Construct a json representation of a SourceSchedule model + source_schedule_model_json = {} + source_schedule_model_json['enabled'] = True + source_schedule_model_json['time_zone'] = 'testString' + source_schedule_model_json['frequency'] = 'daily' + + # Construct a model instance of SourceSchedule by calling from_dict on the json representation + source_schedule_model = SourceSchedule.from_dict(source_schedule_model_json) + assert source_schedule_model != False + + # Construct a model instance of SourceSchedule by calling from_dict on the json representation + source_schedule_model_dict = SourceSchedule.from_dict(source_schedule_model_json).__dict__ + source_schedule_model2 = SourceSchedule(**source_schedule_model_dict) + + # Verify the model instances are equivalent + assert source_schedule_model == source_schedule_model2 + + # Convert model instance back to dict and verify no loss of data + source_schedule_model_json2 = source_schedule_model.to_dict() + assert source_schedule_model_json2 == source_schedule_model_json + +class TestSourceStatus(): + """ + Test Class for SourceStatus + """ + + def test_source_status_serialization(self): + """ + Test serialization/deserialization for SourceStatus + """ + + # Construct a json representation of a SourceStatus model + source_status_model_json = {} + source_status_model_json['status'] = 'running' + source_status_model_json['next_crawl'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of SourceStatus by calling from_dict on the json representation + source_status_model = SourceStatus.from_dict(source_status_model_json) + assert source_status_model != False + + # Construct a model instance of SourceStatus by calling from_dict on the json representation + source_status_model_dict = SourceStatus.from_dict(source_status_model_json).__dict__ + source_status_model2 = SourceStatus(**source_status_model_dict) + + # Verify the model instances are equivalent + assert source_status_model == source_status_model2 + + # Convert model instance back to dict and verify no loss of data + source_status_model_json2 = source_status_model.to_dict() + assert source_status_model_json2 == source_status_model_json + +class TestTokenDictRule(): + """ + Test Class for TokenDictRule + """ + + def test_token_dict_rule_serialization(self): + """ + Test serialization/deserialization for TokenDictRule + """ + + # Construct a json representation of a TokenDictRule model + token_dict_rule_model_json = {} + token_dict_rule_model_json['text'] = 'testString' + token_dict_rule_model_json['tokens'] = ['testString'] + token_dict_rule_model_json['readings'] = ['testString'] + token_dict_rule_model_json['part_of_speech'] = 'testString' + + # Construct a model instance of TokenDictRule by calling from_dict on the json representation + token_dict_rule_model = TokenDictRule.from_dict(token_dict_rule_model_json) + assert token_dict_rule_model != False + + # Construct a model instance of TokenDictRule by calling from_dict on the json representation + token_dict_rule_model_dict = TokenDictRule.from_dict(token_dict_rule_model_json).__dict__ + token_dict_rule_model2 = TokenDictRule(**token_dict_rule_model_dict) + + # Verify the model instances are equivalent + assert token_dict_rule_model == token_dict_rule_model2 + + # Convert model instance back to dict and verify no loss of data + token_dict_rule_model_json2 = token_dict_rule_model.to_dict() + assert token_dict_rule_model_json2 == token_dict_rule_model_json + +class TestTokenDictStatusResponse(): + """ + Test Class for TokenDictStatusResponse + """ + + def test_token_dict_status_response_serialization(self): + """ + Test serialization/deserialization for TokenDictStatusResponse + """ + + # Construct a json representation of a TokenDictStatusResponse model + token_dict_status_response_model_json = {} + token_dict_status_response_model_json['status'] = 'active' + token_dict_status_response_model_json['type'] = 'testString' + + # Construct a model instance of TokenDictStatusResponse by calling from_dict on the json representation + token_dict_status_response_model = TokenDictStatusResponse.from_dict(token_dict_status_response_model_json) + assert token_dict_status_response_model != False + + # Construct a model instance of TokenDictStatusResponse by calling from_dict on the json representation + token_dict_status_response_model_dict = TokenDictStatusResponse.from_dict(token_dict_status_response_model_json).__dict__ + token_dict_status_response_model2 = TokenDictStatusResponse(**token_dict_status_response_model_dict) + + # Verify the model instances are equivalent + assert token_dict_status_response_model == token_dict_status_response_model2 + + # Convert model instance back to dict and verify no loss of data + token_dict_status_response_model_json2 = token_dict_status_response_model.to_dict() + assert token_dict_status_response_model_json2 == token_dict_status_response_model_json + +class TestTopHitsResults(): + """ + Test Class for TopHitsResults + """ + + def test_top_hits_results_serialization(self): + """ + Test serialization/deserialization for TopHitsResults + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model['score'] = 72.5 + query_result_metadata_model['confidence'] = 72.5 + + query_result_model = {} # QueryResult + query_result_model['id'] = 'testString' + query_result_model['metadata'] = {} + query_result_model['collection_id'] = 'testString' + query_result_model['result_metadata'] = query_result_metadata_model + query_result_model['foo'] = { 'foo': 'bar' } + + # Construct a json representation of a TopHitsResults model + top_hits_results_model_json = {} + top_hits_results_model_json['matching_results'] = 38 + top_hits_results_model_json['hits'] = [query_result_model] + + # Construct a model instance of TopHitsResults by calling from_dict on the json representation + top_hits_results_model = TopHitsResults.from_dict(top_hits_results_model_json) + assert top_hits_results_model != False + + # Construct a model instance of TopHitsResults by calling from_dict on the json representation + top_hits_results_model_dict = TopHitsResults.from_dict(top_hits_results_model_json).__dict__ + top_hits_results_model2 = TopHitsResults(**top_hits_results_model_dict) + + # Verify the model instances are equivalent + assert top_hits_results_model == top_hits_results_model2 + + # Convert model instance back to dict and verify no loss of data + top_hits_results_model_json2 = top_hits_results_model.to_dict() + assert top_hits_results_model_json2 == top_hits_results_model_json + +class TestTrainingDataSet(): + """ + Test Class for TrainingDataSet + """ + + def test_training_data_set_serialization(self): + """ + Test serialization/deserialization for TrainingDataSet + """ + + # Construct dict forms of any model objects needed in order to build this model. + + training_example_model = {} # TrainingExample + training_example_model['document_id'] = 'testString' + training_example_model['cross_reference'] = 'testString' + training_example_model['relevance'] = 38 + + training_query_model = {} # TrainingQuery + training_query_model['query_id'] = 'testString' + training_query_model['natural_language_query'] = 'testString' + training_query_model['filter'] = 'testString' + training_query_model['examples'] = [training_example_model] + + # Construct a json representation of a TrainingDataSet model + training_data_set_model_json = {} + training_data_set_model_json['environment_id'] = 'testString' + training_data_set_model_json['collection_id'] = 'testString' + training_data_set_model_json['queries'] = [training_query_model] + + # Construct a model instance of TrainingDataSet by calling from_dict on the json representation + training_data_set_model = TrainingDataSet.from_dict(training_data_set_model_json) + assert training_data_set_model != False + + # Construct a model instance of TrainingDataSet by calling from_dict on the json representation + training_data_set_model_dict = TrainingDataSet.from_dict(training_data_set_model_json).__dict__ + training_data_set_model2 = TrainingDataSet(**training_data_set_model_dict) + + # Verify the model instances are equivalent + assert training_data_set_model == training_data_set_model2 + + # Convert model instance back to dict and verify no loss of data + training_data_set_model_json2 = training_data_set_model.to_dict() + assert training_data_set_model_json2 == training_data_set_model_json + +class TestTrainingExample(): + """ + Test Class for TrainingExample + """ + + def test_training_example_serialization(self): + """ + Test serialization/deserialization for TrainingExample + """ + + # Construct a json representation of a TrainingExample model + training_example_model_json = {} + training_example_model_json['document_id'] = 'testString' + training_example_model_json['cross_reference'] = 'testString' + training_example_model_json['relevance'] = 38 + + # Construct a model instance of TrainingExample by calling from_dict on the json representation + training_example_model = TrainingExample.from_dict(training_example_model_json) + assert training_example_model != False + + # Construct a model instance of TrainingExample by calling from_dict on the json representation + training_example_model_dict = TrainingExample.from_dict(training_example_model_json).__dict__ + training_example_model2 = TrainingExample(**training_example_model_dict) + + # Verify the model instances are equivalent + assert training_example_model == training_example_model2 + + # Convert model instance back to dict and verify no loss of data + training_example_model_json2 = training_example_model.to_dict() + assert training_example_model_json2 == training_example_model_json + +class TestTrainingExampleList(): + """ + Test Class for TrainingExampleList + """ + + def test_training_example_list_serialization(self): + """ + Test serialization/deserialization for TrainingExampleList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + training_example_model = {} # TrainingExample + training_example_model['document_id'] = 'testString' + training_example_model['cross_reference'] = 'testString' + training_example_model['relevance'] = 38 + + # Construct a json representation of a TrainingExampleList model + training_example_list_model_json = {} + training_example_list_model_json['examples'] = [training_example_model] + + # Construct a model instance of TrainingExampleList by calling from_dict on the json representation + training_example_list_model = TrainingExampleList.from_dict(training_example_list_model_json) + assert training_example_list_model != False + + # Construct a model instance of TrainingExampleList by calling from_dict on the json representation + training_example_list_model_dict = TrainingExampleList.from_dict(training_example_list_model_json).__dict__ + training_example_list_model2 = TrainingExampleList(**training_example_list_model_dict) + + # Verify the model instances are equivalent + assert training_example_list_model == training_example_list_model2 + + # Convert model instance back to dict and verify no loss of data + training_example_list_model_json2 = training_example_list_model.to_dict() + assert training_example_list_model_json2 == training_example_list_model_json + +class TestTrainingQuery(): + """ + Test Class for TrainingQuery + """ + + def test_training_query_serialization(self): + """ + Test serialization/deserialization for TrainingQuery + """ + + # Construct dict forms of any model objects needed in order to build this model. + + training_example_model = {} # TrainingExample + training_example_model['document_id'] = 'testString' + training_example_model['cross_reference'] = 'testString' + training_example_model['relevance'] = 38 + + # Construct a json representation of a TrainingQuery model + training_query_model_json = {} + training_query_model_json['query_id'] = 'testString' + training_query_model_json['natural_language_query'] = 'testString' + training_query_model_json['filter'] = 'testString' + training_query_model_json['examples'] = [training_example_model] + + # Construct a model instance of TrainingQuery by calling from_dict on the json representation + training_query_model = TrainingQuery.from_dict(training_query_model_json) + assert training_query_model != False + + # Construct a model instance of TrainingQuery by calling from_dict on the json representation + training_query_model_dict = TrainingQuery.from_dict(training_query_model_json).__dict__ + training_query_model2 = TrainingQuery(**training_query_model_dict) + + # Verify the model instances are equivalent + assert training_query_model == training_query_model2 + + # Convert model instance back to dict and verify no loss of data + training_query_model_json2 = training_query_model.to_dict() + assert training_query_model_json2 == training_query_model_json + +class TestTrainingStatus(): + """ + Test Class for TrainingStatus + """ + + def test_training_status_serialization(self): + """ + Test serialization/deserialization for TrainingStatus + """ + + # Construct a json representation of a TrainingStatus model + training_status_model_json = {} + training_status_model_json['total_examples'] = 38 + training_status_model_json['available'] = True + training_status_model_json['processing'] = True + training_status_model_json['minimum_queries_added'] = True + training_status_model_json['minimum_examples_added'] = True + training_status_model_json['sufficient_label_diversity'] = True + training_status_model_json['notices'] = 38 + training_status_model_json['successfully_trained'] = '2020-01-28T18:40:40.123456Z' + training_status_model_json['data_updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of TrainingStatus by calling from_dict on the json representation + training_status_model = TrainingStatus.from_dict(training_status_model_json) + assert training_status_model != False + + # Construct a model instance of TrainingStatus by calling from_dict on the json representation + training_status_model_dict = TrainingStatus.from_dict(training_status_model_json).__dict__ + training_status_model2 = TrainingStatus(**training_status_model_dict) + + # Verify the model instances are equivalent + assert training_status_model == training_status_model2 + + # Convert model instance back to dict and verify no loss of data + training_status_model_json2 = training_status_model.to_dict() + assert training_status_model_json2 == training_status_model_json + +class TestWordHeadingDetection(): + """ + Test Class for WordHeadingDetection + """ + + def test_word_heading_detection_serialization(self): + """ + Test serialization/deserialization for WordHeadingDetection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + font_setting_model = {} # FontSetting + font_setting_model['level'] = 38 + font_setting_model['min_size'] = 38 + font_setting_model['max_size'] = 38 + font_setting_model['bold'] = True + font_setting_model['italic'] = True + font_setting_model['name'] = 'testString' + + word_style_model = {} # WordStyle + word_style_model['level'] = 38 + word_style_model['names'] = ['testString'] + + # Construct a json representation of a WordHeadingDetection model + word_heading_detection_model_json = {} + word_heading_detection_model_json['fonts'] = [font_setting_model] + word_heading_detection_model_json['styles'] = [word_style_model] + + # Construct a model instance of WordHeadingDetection by calling from_dict on the json representation + word_heading_detection_model = WordHeadingDetection.from_dict(word_heading_detection_model_json) + assert word_heading_detection_model != False + + # Construct a model instance of WordHeadingDetection by calling from_dict on the json representation + word_heading_detection_model_dict = WordHeadingDetection.from_dict(word_heading_detection_model_json).__dict__ + word_heading_detection_model2 = WordHeadingDetection(**word_heading_detection_model_dict) + + # Verify the model instances are equivalent + assert word_heading_detection_model == word_heading_detection_model2 + + # Convert model instance back to dict and verify no loss of data + word_heading_detection_model_json2 = word_heading_detection_model.to_dict() + assert word_heading_detection_model_json2 == word_heading_detection_model_json + +class TestWordSettings(): + """ + Test Class for WordSettings + """ + + def test_word_settings_serialization(self): + """ + Test serialization/deserialization for WordSettings + """ + + # Construct dict forms of any model objects needed in order to build this model. + + font_setting_model = {} # FontSetting + font_setting_model['level'] = 38 + font_setting_model['min_size'] = 38 + font_setting_model['max_size'] = 38 + font_setting_model['bold'] = True + font_setting_model['italic'] = True + font_setting_model['name'] = 'testString' + + word_style_model = {} # WordStyle + word_style_model['level'] = 38 + word_style_model['names'] = ['testString'] + + word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model['fonts'] = [font_setting_model] + word_heading_detection_model['styles'] = [word_style_model] + + # Construct a json representation of a WordSettings model + word_settings_model_json = {} + word_settings_model_json['heading'] = word_heading_detection_model + + # Construct a model instance of WordSettings by calling from_dict on the json representation + word_settings_model = WordSettings.from_dict(word_settings_model_json) + assert word_settings_model != False + + # Construct a model instance of WordSettings by calling from_dict on the json representation + word_settings_model_dict = WordSettings.from_dict(word_settings_model_json).__dict__ + word_settings_model2 = WordSettings(**word_settings_model_dict) + + # Verify the model instances are equivalent + assert word_settings_model == word_settings_model2 + + # Convert model instance back to dict and verify no loss of data + word_settings_model_json2 = word_settings_model.to_dict() + assert word_settings_model_json2 == word_settings_model_json + +class TestWordStyle(): + """ + Test Class for WordStyle + """ + + def test_word_style_serialization(self): + """ + Test serialization/deserialization for WordStyle + """ + + # Construct a json representation of a WordStyle model + word_style_model_json = {} + word_style_model_json['level'] = 38 + word_style_model_json['names'] = ['testString'] + + # Construct a model instance of WordStyle by calling from_dict on the json representation + word_style_model = WordStyle.from_dict(word_style_model_json) + assert word_style_model != False + + # Construct a model instance of WordStyle by calling from_dict on the json representation + word_style_model_dict = WordStyle.from_dict(word_style_model_json).__dict__ + word_style_model2 = WordStyle(**word_style_model_dict) + + # Verify the model instances are equivalent + assert word_style_model == word_style_model2 + + # Convert model instance back to dict and verify no loss of data + word_style_model_json2 = word_style_model.to_dict() + assert word_style_model_json2 == word_style_model_json + +class TestXPathPatterns(): + """ + Test Class for XPathPatterns + """ + + def test_x_path_patterns_serialization(self): + """ + Test serialization/deserialization for XPathPatterns + """ + + # Construct a json representation of a XPathPatterns model + x_path_patterns_model_json = {} + x_path_patterns_model_json['xpaths'] = ['testString'] + + # Construct a model instance of XPathPatterns by calling from_dict on the json representation + x_path_patterns_model = XPathPatterns.from_dict(x_path_patterns_model_json) + assert x_path_patterns_model != False + + # Construct a model instance of XPathPatterns by calling from_dict on the json representation + x_path_patterns_model_dict = XPathPatterns.from_dict(x_path_patterns_model_json).__dict__ + x_path_patterns_model2 = XPathPatterns(**x_path_patterns_model_dict) + + # Verify the model instances are equivalent + assert x_path_patterns_model == x_path_patterns_model2 + + # Convert model instance back to dict and verify no loss of data + x_path_patterns_model_json2 = x_path_patterns_model.to_dict() + assert x_path_patterns_model_json2 == x_path_patterns_model_json + +class TestCalculation(): + """ + Test Class for Calculation + """ + + def test_calculation_serialization(self): + """ + Test serialization/deserialization for Calculation + """ + + # Construct a json representation of a Calculation model + calculation_model_json = {} + calculation_model_json['type'] = 'unique_count' + calculation_model_json['matching_results'] = 38 + calculation_model_json['field'] = 'testString' + calculation_model_json['value'] = 72.5 + + # Construct a model instance of Calculation by calling from_dict on the json representation + calculation_model = Calculation.from_dict(calculation_model_json) + assert calculation_model != False + + # Construct a model instance of Calculation by calling from_dict on the json representation + calculation_model_dict = Calculation.from_dict(calculation_model_json).__dict__ + calculation_model2 = Calculation(**calculation_model_dict) + + # Verify the model instances are equivalent + assert calculation_model == calculation_model2 + + # Convert model instance back to dict and verify no loss of data + calculation_model_json2 = calculation_model.to_dict() + assert calculation_model_json2 == calculation_model_json + +class TestFilter(): + """ + Test Class for Filter + """ + + def test_filter_serialization(self): + """ + Test serialization/deserialization for Filter + """ + + # Construct a json representation of a Filter model + filter_model_json = {} + filter_model_json['type'] = 'filter' + filter_model_json['matching_results'] = 38 + filter_model_json['match'] = 'testString' + + # Construct a model instance of Filter by calling from_dict on the json representation + filter_model = Filter.from_dict(filter_model_json) + assert filter_model != False + + # Construct a model instance of Filter by calling from_dict on the json representation + filter_model_dict = Filter.from_dict(filter_model_json).__dict__ + filter_model2 = Filter(**filter_model_dict) + + # Verify the model instances are equivalent + assert filter_model == filter_model2 + + # Convert model instance back to dict and verify no loss of data + filter_model_json2 = filter_model.to_dict() + assert filter_model_json2 == filter_model_json + +class TestHistogram(): + """ + Test Class for Histogram + """ + + def test_histogram_serialization(self): + """ + Test serialization/deserialization for Histogram + """ + + # Construct a json representation of a Histogram model + histogram_model_json = {} + histogram_model_json['type'] = 'histogram' + histogram_model_json['matching_results'] = 38 + histogram_model_json['field'] = 'testString' + histogram_model_json['interval'] = 38 + + # Construct a model instance of Histogram by calling from_dict on the json representation + histogram_model = Histogram.from_dict(histogram_model_json) + assert histogram_model != False + + # Construct a model instance of Histogram by calling from_dict on the json representation + histogram_model_dict = Histogram.from_dict(histogram_model_json).__dict__ + histogram_model2 = Histogram(**histogram_model_dict) + + # Verify the model instances are equivalent + assert histogram_model == histogram_model2 + + # Convert model instance back to dict and verify no loss of data + histogram_model_json2 = histogram_model.to_dict() + assert histogram_model_json2 == histogram_model_json + +class TestNested(): + """ + Test Class for Nested + """ + + def test_nested_serialization(self): + """ + Test serialization/deserialization for Nested + """ + + # Construct a json representation of a Nested model + nested_model_json = {} + nested_model_json['type'] = 'nested' + nested_model_json['matching_results'] = 38 + nested_model_json['path'] = 'testString' + + # Construct a model instance of Nested by calling from_dict on the json representation + nested_model = Nested.from_dict(nested_model_json) + assert nested_model != False + + # Construct a model instance of Nested by calling from_dict on the json representation + nested_model_dict = Nested.from_dict(nested_model_json).__dict__ + nested_model2 = Nested(**nested_model_dict) + + # Verify the model instances are equivalent + assert nested_model == nested_model2 + + # Convert model instance back to dict and verify no loss of data + nested_model_json2 = nested_model.to_dict() + assert nested_model_json2 == nested_model_json + +class TestTerm(): + """ + Test Class for Term + """ + + def test_term_serialization(self): + """ + Test serialization/deserialization for Term + """ + + # Construct a json representation of a Term model + term_model_json = {} + term_model_json['type'] = 'term' + term_model_json['matching_results'] = 38 + term_model_json['field'] = 'testString' + term_model_json['count'] = 38 + + # Construct a model instance of Term by calling from_dict on the json representation + term_model = Term.from_dict(term_model_json) + assert term_model != False + + # Construct a model instance of Term by calling from_dict on the json representation + term_model_dict = Term.from_dict(term_model_json).__dict__ + term_model2 = Term(**term_model_dict) + + # Verify the model instances are equivalent + assert term_model == term_model2 + + # Convert model instance back to dict and verify no loss of data + term_model_json2 = term_model.to_dict() + assert term_model_json2 == term_model_json + +class TestTimeslice(): + """ + Test Class for Timeslice + """ + + def test_timeslice_serialization(self): + """ + Test serialization/deserialization for Timeslice + """ + + # Construct a json representation of a Timeslice model + timeslice_model_json = {} + timeslice_model_json['type'] = 'timeslice' + timeslice_model_json['matching_results'] = 38 + timeslice_model_json['field'] = 'testString' + timeslice_model_json['interval'] = 'testString' + timeslice_model_json['anomaly'] = True + + # Construct a model instance of Timeslice by calling from_dict on the json representation + timeslice_model = Timeslice.from_dict(timeslice_model_json) + assert timeslice_model != False + + # Construct a model instance of Timeslice by calling from_dict on the json representation + timeslice_model_dict = Timeslice.from_dict(timeslice_model_json).__dict__ + timeslice_model2 = Timeslice(**timeslice_model_dict) + + # Verify the model instances are equivalent + assert timeslice_model == timeslice_model2 + + # Convert model instance back to dict and verify no loss of data + timeslice_model_json2 = timeslice_model.to_dict() + assert timeslice_model_json2 == timeslice_model_json + +class TestTopHits(): + """ + Test Class for TopHits + """ + + def test_top_hits_serialization(self): + """ + Test serialization/deserialization for TopHits + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model['score'] = 72.5 + query_result_metadata_model['confidence'] = 72.5 + + query_result_model = {} # QueryResult + query_result_model['id'] = 'testString' + query_result_model['metadata'] = {} + query_result_model['collection_id'] = 'testString' + query_result_model['result_metadata'] = query_result_metadata_model + query_result_model['foo'] = { 'foo': 'bar' } + + top_hits_results_model = {} # TopHitsResults + top_hits_results_model['matching_results'] = 38 + top_hits_results_model['hits'] = [query_result_model] + + # Construct a json representation of a TopHits model + top_hits_model_json = {} + top_hits_model_json['type'] = 'top_hits' + top_hits_model_json['matching_results'] = 38 + top_hits_model_json['size'] = 38 + top_hits_model_json['hits'] = top_hits_results_model + + # Construct a model instance of TopHits by calling from_dict on the json representation + top_hits_model = TopHits.from_dict(top_hits_model_json) + assert top_hits_model != False + + # Construct a model instance of TopHits by calling from_dict on the json representation + top_hits_model_dict = TopHits.from_dict(top_hits_model_json).__dict__ + top_hits_model2 = TopHits(**top_hits_model_dict) + + # Verify the model instances are equivalent + assert top_hits_model == top_hits_model2 + + # Convert model instance back to dict and verify no loss of data + top_hits_model_json2 = top_hits_model.to_dict() + assert top_hits_model_json2 == top_hits_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index c94fe745b..48fd84728 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -13,381 +13,446 @@ # See the License for the specific language governing permissions and # limitations under the License. -from datetime import datetime +""" +Unit Tests for DiscoveryV2 +""" + +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect +import io import json import pytest +import re +import requests import responses import tempfile -import ibm_watson.discovery_v2 +import urllib from ibm_watson.discovery_v2 import * +version = 'testString' + +service = DiscoveryV2( + authenticator=NoAuthAuthenticator(), + version=version + ) + base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: Collections ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_collections -#----------------------------------------------------------------------------- class TestListCollections(): + """ + Test Class for list_collections + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_collections_response(self): - body = self.construct_full_body() - response = fake_response_ListCollectionsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_collections_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ListCollectionsResponse_json - send_request(self, body, response) + def test_list_collections_all_params(self): + """ + list_collections() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = service.list_collections( + project_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_collections_empty(self): - check_empty_required_params(self, fake_response_ListCollectionsResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_collections_value_error(self): + """ + test_list_collections_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_collections(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/collections'.format(body['project_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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.list_collections(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_collection -#----------------------------------------------------------------------------- class TestCreateCollection(): + """ + Test Class for create_collection + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_collection_response(self): - body = self.construct_full_body() - response = fake_response_CollectionDetails_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_CollectionDetails_json - send_request(self, body, response) + def test_create_collection_all_params(self): + """ + create_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Set up parameter values + project_id = 'testString' + name = 'testString' + description = 'testString' + language = 'testString' + enrichments = [collection_enrichment_model] + + # Invoke method + response = service.create_collection( + project_id, + name, + description=description, + language=language, + enrichments=enrichments, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + print(responses.calls[0]) + req_body = json.loads(str(responses.calls[0].request.body)) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['language'] == 'testString' + assert req_body['enrichments'] == [collection_enrichment_model] + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_collection_empty(self): - check_empty_required_params(self, fake_response_CollectionDetails_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_create_collection_value_error(self): + """ + test_create_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Set up parameter values + project_id = 'testString' + name = 'testString' + description = 'testString' + language = 'testString' + enrichments = [collection_enrichment_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_collection(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/collections'.format(body['project_id']) - 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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.create_collection(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body.update({"name": "string1", "description": "string1", "language": "string1", "enrichments": [], }) - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body.update({"name": "string1", "description": "string1", "language": "string1", "enrichments": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_collection -#----------------------------------------------------------------------------- class TestGetCollection(): + """ + Test Class for get_collection + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_collection_response(self): - body = self.construct_full_body() - response = fake_response_CollectionDetails_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_CollectionDetails_json - send_request(self, body, response) + def test_get_collection_all_params(self): + """ + get_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = service.get_collection( + project_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_collection_empty(self): - check_empty_required_params(self, fake_response_CollectionDetails_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_collection_value_error(self): + """ + test_get_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_collection(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}'.format(body['project_id'], 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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.get_collection(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_collection -#----------------------------------------------------------------------------- class TestUpdateCollection(): + """ + Test Class for update_collection + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_collection_response(self): - body = self.construct_full_body() - response = fake_response_CollectionDetails_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_CollectionDetails_json - send_request(self, body, response) + def test_update_collection_all_params(self): + """ + update_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + name = 'testString' + description = 'testString' + enrichments = [collection_enrichment_model] + + # Invoke method + response = service.update_collection( + project_id, + collection_id, + name=name, + description=description, + enrichments=enrichments, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body)) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['enrichments'] == [collection_enrichment_model] + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_collection_empty(self): - check_empty_required_params(self, fake_response_CollectionDetails_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_update_collection_value_error(self): + """ + test_update_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + name = 'testString' + description = 'testString' + enrichments = [collection_enrichment_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_collection(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}'.format(body['project_id'], body['collection_id']) - 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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.update_collection(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - body.update({"name": "string1", "description": "string1", "enrichments": [], }) - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - body.update({"name": "string1", "description": "string1", "enrichments": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_collection -#----------------------------------------------------------------------------- class TestDeleteCollection(): + """ + Test Class for delete_collection + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_collection_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_collection_all_params(self): + """ + delete_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = service.delete_collection( + project_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_collection_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_collection_value_error(self): + """ + test_delete_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') + responses.add(responses.DELETE, + url, + status=204) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}'.format(body['project_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_collection(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.delete_collection(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - return body # endregion @@ -400,296 +465,506 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for query -#----------------------------------------------------------------------------- class TestQuery(): + """ + Test Class for query + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_query_response(self): - body = self.construct_full_body() - response = fake_response_QueryResponse_json - send_request(self, body, response) + def test_query_all_params(self): + """ + query() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/query') + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a QueryLargeTableResults model + query_large_table_results_model = {} + query_large_table_results_model['enabled'] = True + query_large_table_results_model['count'] = 38 + + # Construct a dict representation of a QueryLargeSuggestedRefinements model + query_large_suggested_refinements_model = {} + query_large_suggested_refinements_model['enabled'] = True + query_large_suggested_refinements_model['count'] = 1 + + # Construct a dict representation of a QueryLargePassages model + query_large_passages_model = {} + query_large_passages_model['enabled'] = True + query_large_passages_model['per_document'] = True + query_large_passages_model['max_per_document'] = 38 + query_large_passages_model['fields'] = ['testString'] + query_large_passages_model['count'] = 100 + query_large_passages_model['characters'] = 50 + + # Set up parameter values + project_id = 'testString' + collection_ids = ['testString'] + filter = 'testString' + query = 'testString' + natural_language_query = 'testString' + aggregation = 'testString' + count = 38 + return_ = ['testString'] + offset = 38 + sort = 'testString' + highlight = True + spelling_suggestions = True + table_results = query_large_table_results_model + suggested_refinements = query_large_suggested_refinements_model + passages = query_large_passages_model + + # Invoke method + response = service.query( + project_id, + collection_ids=collection_ids, + filter=filter, + query=query, + natural_language_query=natural_language_query, + aggregation=aggregation, + count=count, + return_=return_, + offset=offset, + sort=sort, + highlight=highlight, + spelling_suggestions=spelling_suggestions, + table_results=table_results, + suggested_refinements=suggested_refinements, + passages=passages, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body)) + assert req_body['collection_ids'] == ['testString'] + assert req_body['filter'] == 'testString' + assert req_body['query'] == 'testString' + assert req_body['natural_language_query'] == 'testString' + assert req_body['aggregation'] == 'testString' + assert req_body['count'] == 38 + assert req_body['return'] == ['testString'] + assert req_body['offset'] == 38 + assert req_body['sort'] == 'testString' + assert req_body['highlight'] == True + assert req_body['spelling_suggestions'] == True + assert req_body['table_results'] == query_large_table_results_model + assert req_body['suggested_refinements'] == query_large_suggested_refinements_model + assert req_body['passages'] == query_large_passages_model + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_query_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_QueryResponse_json - send_request(self, body, response) + def test_query_required_params(self): + """ + test_query_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/query') + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = service.query( + project_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_query_empty(self): - check_empty_required_params(self, fake_response_QueryResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_query_value_error(self): + """ + test_query_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/query') + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.query(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/query'.format(body['project_id']) - 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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.query(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body.update({"collection_ids": [], "filter": "string1", "query": "string1", "natural_language_query": "string1", "aggregation": "string1", "count": 12345, "return_": [], "offset": 12345, "sort": "string1", "highlight": True, "spelling_suggestions": True, "table_results": QueryLargeTableResults._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "suggested_refinements": QueryLargeSuggestedRefinements._from_dict(json.loads("""{"enabled": false, "count": 5}""")), "passages": QueryLargePassages._from_dict(json.loads("""{"enabled": false, "per_document": true, "max_per_document": 16, "fields": [], "count": 5, "characters": 10}""")), }) - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_autocompletion -#----------------------------------------------------------------------------- class TestGetAutocompletion(): + """ + Test Class for get_autocompletion + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_autocompletion_response(self): - body = self.construct_full_body() - response = fake_response_Completions_json - send_request(self, body, response) + def test_get_autocompletion_all_params(self): + """ + get_autocompletion() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/autocompletion') + mock_response = '{"completions": ["completions"]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + prefix = 'testString' + collection_ids = ['testString'] + field = 'testString' + count = 38 + + # Invoke method + response = service.get_autocompletion( + project_id, + prefix, + collection_ids=collection_ids, + field=field, + count=count, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'prefix={}'.format(prefix) in query_string + assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string + assert 'field={}'.format(field) in query_string + assert 'count={}'.format(count) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_autocompletion_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Completions_json - send_request(self, body, response) + def test_get_autocompletion_required_params(self): + """ + test_get_autocompletion_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/autocompletion') + mock_response = '{"completions": ["completions"]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + prefix = 'testString' + + # Invoke method + response = service.get_autocompletion( + project_id, + prefix, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'prefix={}'.format(prefix) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_autocompletion_empty(self): - check_empty_required_params(self, fake_response_Completions_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_autocompletion_value_error(self): + """ + test_get_autocompletion_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/autocompletion') + mock_response = '{"completions": ["completions"]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + prefix = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "prefix": prefix, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_autocompletion(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/autocompletion'.format(body['project_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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.get_autocompletion(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['prefix'] = "string1" - body['collection_ids'] = [] - body['field'] = "string1" - body['count'] = 12345 - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['prefix'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for query_notices -#----------------------------------------------------------------------------- class TestQueryNotices(): + """ + Test Class for query_notices + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_query_notices_response(self): - body = self.construct_full_body() - response = fake_response_QueryNoticesResponse_json - send_request(self, body, response) + def test_query_notices_all_params(self): + """ + query_notices() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/notices') + mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + filter = 'testString' + query = 'testString' + natural_language_query = 'testString' + count = 38 + offset = 38 + + # Invoke method + response = service.query_notices( + project_id, + filter=filter, + query=query, + natural_language_query=natural_language_query, + count=count, + offset=offset, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'filter={}'.format(filter) in query_string + assert 'query={}'.format(query) in query_string + assert 'natural_language_query={}'.format(natural_language_query) in query_string + assert 'count={}'.format(count) in query_string + assert 'offset={}'.format(offset) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_query_notices_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_QueryNoticesResponse_json - send_request(self, body, response) + def test_query_notices_required_params(self): + """ + test_query_notices_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/notices') + mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = service.query_notices( + project_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_query_notices_empty(self): - check_empty_required_params(self, fake_response_QueryNoticesResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_query_notices_value_error(self): + """ + test_query_notices_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/notices') + mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.query_notices(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/notices'.format(body['project_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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.query_notices(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['filter'] = "string1" - body['query'] = "string1" - body['natural_language_query'] = "string1" - body['count'] = 12345 - body['offset'] = 12345 - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_fields -#----------------------------------------------------------------------------- class TestListFields(): + """ + Test Class for list_fields + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_fields_response(self): - body = self.construct_full_body() - response = fake_response_ListFieldsResponse_json - send_request(self, body, response) + def test_list_fields_all_params(self): + """ + list_fields() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_ids = ['testString'] + + # Invoke method + response = service.list_fields( + project_id, + collection_ids=collection_ids, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_fields_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ListFieldsResponse_json - send_request(self, body, response) + def test_list_fields_required_params(self): + """ + test_list_fields_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = service.list_fields( + project_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_fields_empty(self): - check_empty_required_params(self, fake_response_ListFieldsResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_fields_value_error(self): + """ + test_list_fields_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/fields'.format(body['project_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_fields(**req_copy) - 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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.list_fields(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_ids'] = [] - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - return body # endregion @@ -702,74 +977,74 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for get_component_settings -#----------------------------------------------------------------------------- class TestGetComponentSettings(): + """ + Test Class for get_component_settings + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_component_settings_response(self): - body = self.construct_full_body() - response = fake_response_ComponentSettingsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_component_settings_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ComponentSettingsResponse_json - send_request(self, body, response) + def test_get_component_settings_all_params(self): + """ + get_component_settings() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/component_settings') + mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = service.get_component_settings( + project_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_component_settings_empty(self): - check_empty_required_params(self, fake_response_ComponentSettingsResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_component_settings_value_error(self): + """ + test_get_component_settings_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/component_settings') + mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/component_settings'.format(body['project_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_component_settings(**req_copy) - 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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.get_component_settings(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - return body # endregion @@ -782,235 +1057,350 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for add_document -#----------------------------------------------------------------------------- class TestAddDocument(): + """ + Test Class for add_document + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_document_response(self): - body = self.construct_full_body() - response = fake_response_DocumentAccepted_json - send_request(self, body, response) + def test_add_document_all_params(self): + """ + add_document() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/json' + metadata = 'testString' + x_watson_discovery_force = True + + # Invoke method + response = service.add_document( + project_id, + collection_id, + file=file, + filename=filename, + file_content_type=file_content_type, + metadata=metadata, + x_watson_discovery_force=x_watson_discovery_force, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_document_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DocumentAccepted_json - send_request(self, body, response) + def test_add_document_required_params(self): + """ + test_add_document_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = service.add_document( + project_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_document_empty(self): - check_empty_required_params(self, fake_response_DocumentAccepted_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_add_document_value_error(self): + """ + test_add_document_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_document(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents'.format(body['project_id'], body['collection_id']) - 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=202, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.add_document(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - body['file'] = tempfile.NamedTemporaryFile() - body['filename'] = "string1" - body['file_content_type'] = "string1" - body['metadata'] = "string1" - body['x_watson_discovery_force'] = True - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_document -#----------------------------------------------------------------------------- class TestUpdateDocument(): + """ + Test Class for update_document + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_document_response(self): - body = self.construct_full_body() - response = fake_response_DocumentAccepted_json - send_request(self, body, response) + def test_update_document_all_params(self): + """ + update_document() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/json' + metadata = 'testString' + x_watson_discovery_force = True + + # Invoke method + response = service.update_document( + project_id, + collection_id, + document_id, + file=file, + filename=filename, + file_content_type=file_content_type, + metadata=metadata, + x_watson_discovery_force=x_watson_discovery_force, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_document_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DocumentAccepted_json - send_request(self, body, response) + def test_update_document_required_params(self): + """ + test_update_document_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Invoke method + response = service.update_document( + project_id, + collection_id, + document_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_document_empty(self): - check_empty_required_params(self, fake_response_DocumentAccepted_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_update_document_value_error(self): + """ + test_update_document_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + "document_id": document_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_document(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) - 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=202, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.update_document(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - body['document_id'] = "string1" - body['file'] = tempfile.NamedTemporaryFile() - body['filename'] = "string1" - body['file_content_type'] = "string1" - body['metadata'] = "string1" - body['x_watson_discovery_force'] = True - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - body['document_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_document -#----------------------------------------------------------------------------- class TestDeleteDocument(): + """ + Test Class for delete_document + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_document_response(self): - body = self.construct_full_body() - response = fake_response_DeleteDocumentResponse_json - send_request(self, body, response) + def test_delete_document_all_params(self): + """ + delete_document() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + x_watson_discovery_force = True + + # Invoke method + response = service.delete_document( + project_id, + collection_id, + document_id, + x_watson_discovery_force=x_watson_discovery_force, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_document_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DeleteDocumentResponse_json - send_request(self, body, response) + def test_delete_document_required_params(self): + """ + test_delete_document_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Invoke method + response = service.delete_document( + project_id, + collection_id, + document_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_document_empty(self): - check_empty_required_params(self, fake_response_DeleteDocumentResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_document_value_error(self): + """ + test_delete_document_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/documents/{2}'.format(body['project_id'], body['collection_id'], body['document_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + "document_id": document_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_document(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.delete_document(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - body['document_id'] = "string1" - body['x_watson_discovery_force'] = True - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - body['document_id'] = "string1" - return body # endregion @@ -1023,362 +1413,412 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_training_queries -#----------------------------------------------------------------------------- class TestListTrainingQueries(): + """ + Test Class for list_training_queries + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_training_queries_response(self): - body = self.construct_full_body() - response = fake_response_TrainingQuerySet_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_training_queries_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingQuerySet_json - send_request(self, body, response) + def test_list_training_queries_all_params(self): + """ + list_training_queries() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') + mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = service.list_training_queries( + project_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_training_queries_empty(self): - check_empty_required_params(self, fake_response_TrainingQuerySet_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_training_queries_value_error(self): + """ + test_list_training_queries_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') + mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_training_queries(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.list_training_queries(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_training_queries -#----------------------------------------------------------------------------- class TestDeleteTrainingQueries(): + """ + Test Class for delete_training_queries + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_training_queries_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_training_queries_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_training_queries_all_params(self): + """ + delete_training_queries() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = service.delete_training_queries( + project_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_training_queries_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_training_queries_value_error(self): + """ + test_delete_training_queries_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_training_queries(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) - 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=204, - content_type='') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.delete_training_queries(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_training_query -#----------------------------------------------------------------------------- class TestCreateTrainingQuery(): + """ + Test Class for create_training_query + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_training_query_response(self): - body = self.construct_full_body() - response = fake_response_TrainingQuery_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_training_query_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingQuery_json - send_request(self, body, response) + def test_create_training_query_all_params(self): + """ + create_training_query() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a TrainingExample model + training_example_model = {} + training_example_model['document_id'] = 'testString' + training_example_model['collection_id'] = 'testString' + training_example_model['relevance'] = 38 + + # Set up parameter values + project_id = 'testString' + natural_language_query = 'testString' + examples = [training_example_model] + filter = 'testString' + + # Invoke method + response = service.create_training_query( + project_id, + natural_language_query, + examples, + filter=filter, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body)) + assert req_body['natural_language_query'] == 'testString' + assert req_body['examples'] == [training_example_model] + assert req_body['filter'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_training_query_empty(self): - check_empty_required_params(self, fake_response_TrainingQuery_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_create_training_query_value_error(self): + """ + test_create_training_query_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a TrainingExample model + training_example_model = {} + training_example_model['document_id'] = 'testString' + training_example_model['collection_id'] = 'testString' + training_example_model['relevance'] = 38 + + # Set up parameter values + project_id = 'testString' + natural_language_query = 'testString' + examples = [training_example_model] + filter = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "natural_language_query": natural_language_query, + "examples": examples, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_training_query(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries'.format(body['project_id']) - 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=201, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.create_training_query(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_training_query -#----------------------------------------------------------------------------- class TestGetTrainingQuery(): + """ + Test Class for get_training_query + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_training_query_response(self): - body = self.construct_full_body() - response = fake_response_TrainingQuery_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_training_query_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingQuery_json - send_request(self, body, response) + def test_get_training_query_all_params(self): + """ + get_training_query() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + + # Invoke method + response = service.get_training_query( + project_id, + query_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_training_query_empty(self): - check_empty_required_params(self, fake_response_TrainingQuery_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_training_query_value_error(self): + """ + test_get_training_query_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "query_id": query_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_training_query(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.get_training_query(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['query_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['query_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_training_query -#----------------------------------------------------------------------------- class TestUpdateTrainingQuery(): + """ + Test Class for update_training_query + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_training_query_response(self): - body = self.construct_full_body() - response = fake_response_TrainingQuery_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_training_query_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingQuery_json - send_request(self, body, response) + def test_update_training_query_all_params(self): + """ + update_training_query() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a TrainingExample model + training_example_model = {} + training_example_model['document_id'] = 'testString' + training_example_model['collection_id'] = 'testString' + training_example_model['relevance'] = 38 + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + natural_language_query = 'testString' + examples = [training_example_model] + filter = 'testString' + + # Invoke method + response = service.update_training_query( + project_id, + query_id, + natural_language_query, + examples, + filter=filter, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body)) + assert req_body['natural_language_query'] == 'testString' + assert req_body['examples'] == [training_example_model] + assert req_body['filter'] == 'testString' - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_training_query_empty(self): - check_empty_required_params(self, fake_response_TrainingQuery_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/training_data/queries/{1}'.format(body['project_id'], body['query_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_update_training_query_value_error(self): + """ + test_update_training_query_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.update_training_query(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['query_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['query_id'] = "string1" - body.update({"natural_language_query": "string1", "examples": [], "filter": "string1", }) - return body + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a TrainingExample model + training_example_model = {} + training_example_model['document_id'] = 'testString' + training_example_model['collection_id'] = 'testString' + training_example_model['relevance'] = 38 + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + natural_language_query = 'testString' + examples = [training_example_model] + filter = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "query_id": query_id, + "natural_language_query": natural_language_query, + "examples": examples, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_training_query(**req_copy) + # endregion @@ -1391,80 +1831,116 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for analyze_document -#----------------------------------------------------------------------------- class TestAnalyzeDocument(): + """ + Test Class for analyze_document + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_analyze_document_response(self): - body = self.construct_full_body() - response = fake_response_AnalyzedDocument_json - send_request(self, body, response) + def test_analyze_document_all_params(self): + """ + analyze_document() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/json' + metadata = 'testString' + + # Invoke method + response = service.analyze_document( + project_id, + collection_id, + file=file, + filename=filename, + file_content_type=file_content_type, + metadata=metadata, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_analyze_document_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_AnalyzedDocument_json - send_request(self, body, response) + def test_analyze_document_required_params(self): + """ + test_analyze_document_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = service.analyze_document( + project_id, + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_analyze_document_empty(self): - check_empty_required_params(self, fake_response_AnalyzedDocument_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_analyze_document_value_error(self): + """ + test_analyze_document_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/collections/{1}/analyze'.format(body['project_id'], body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.analyze_document(**req_copy) - 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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.analyze_document(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - body['file'] = tempfile.NamedTemporaryFile() - body['filename'] = "string1" - body['file_content_type'] = "string1" - body['metadata'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['collection_id'] = "string1" - return body # endregion @@ -1477,365 +1953,449 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_enrichments -#----------------------------------------------------------------------------- class TestListEnrichments(): + """ + Test Class for list_enrichments + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_enrichments_response(self): - body = self.construct_full_body() - response = fake_response_Enrichments_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_enrichments_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Enrichments_json - send_request(self, body, response) + def test_list_enrichments_all_params(self): + """ + list_enrichments() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments') + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = service.list_enrichments( + project_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_enrichments_empty(self): - check_empty_required_params(self, fake_response_Enrichments_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_enrichments_value_error(self): + """ + test_list_enrichments_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments') + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_enrichments(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/enrichments'.format(body['project_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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.list_enrichments(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_enrichment -#----------------------------------------------------------------------------- class TestCreateEnrichment(): + """ + Test Class for create_enrichment + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_enrichment_response(self): - body = self.construct_full_body() - response = fake_response_Enrichment_json - send_request(self, body, response) + def test_create_enrichment_all_params(self): + """ + create_enrichment() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + + # Construct a dict representation of a CreateEnrichment model + create_enrichment_model = {} + create_enrichment_model['name'] = 'testString' + create_enrichment_model['description'] = 'testString' + create_enrichment_model['type'] = 'dictionary' + create_enrichment_model['options'] = enrichment_options_model + + # Set up parameter values + project_id = 'testString' + enrichment = create_enrichment_model + file = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = service.create_enrichment( + project_id, + enrichment, + file=file, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_enrichment_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Enrichment_json - send_request(self, body, response) + def test_create_enrichment_required_params(self): + """ + test_create_enrichment_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + + # Construct a dict representation of a CreateEnrichment model + create_enrichment_model = {} + create_enrichment_model['name'] = 'testString' + create_enrichment_model['description'] = 'testString' + create_enrichment_model['type'] = 'dictionary' + create_enrichment_model['options'] = enrichment_options_model + + # Set up parameter values + project_id = 'testString' + enrichment = create_enrichment_model + + # Invoke method + response = service.create_enrichment( + project_id, + enrichment, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_enrichment_empty(self): - check_empty_required_params(self, fake_response_Enrichment_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_create_enrichment_value_error(self): + """ + test_create_enrichment_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + + # Construct a dict representation of a CreateEnrichment model + create_enrichment_model = {} + create_enrichment_model['name'] = 'testString' + create_enrichment_model['description'] = 'testString' + create_enrichment_model['type'] = 'dictionary' + create_enrichment_model['options'] = enrichment_options_model + + # Set up parameter values + project_id = 'testString' + enrichment = create_enrichment_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "enrichment": enrichment, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_enrichment(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/enrichments'.format(body['project_id']) - 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=201, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.create_enrichment(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['enrichment'] = {"enrichment": {"mock": "data"}} - body['file'] = tempfile.NamedTemporaryFile() - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['enrichment'] = {"enrichment": {"mock": "data"}} - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_enrichment -#----------------------------------------------------------------------------- class TestGetEnrichment(): + """ + Test Class for get_enrichment + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_enrichment_response(self): - body = self.construct_full_body() - response = fake_response_Enrichment_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_enrichment_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Enrichment_json - send_request(self, body, response) + def test_get_enrichment_all_params(self): + """ + get_enrichment() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + enrichment_id = 'testString' + + # Invoke method + response = service.get_enrichment( + project_id, + enrichment_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_enrichment_empty(self): - check_empty_required_params(self, fake_response_Enrichment_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/enrichments/{1}'.format(body['project_id'], body['enrichment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + @responses.activate + def test_get_enrichment_value_error(self): + """ + test_get_enrichment_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.get_enrichment(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['enrichment_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['enrichment_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_enrichment -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + enrichment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "enrichment_id": enrichment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_enrichment(**req_copy) + + + class TestUpdateEnrichment(): + """ + Test Class for update_enrichment + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_enrichment_response(self): - body = self.construct_full_body() - response = fake_response_Enrichment_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_enrichment_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Enrichment_json - send_request(self, body, response) + def test_update_enrichment_all_params(self): + """ + update_enrichment() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + enrichment_id = 'testString' + name = 'testString' + description = 'testString' + + # Invoke method + response = service.update_enrichment( + project_id, + enrichment_id, + name, + description=description, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body)) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_enrichment_empty(self): - check_empty_required_params(self, fake_response_Enrichment_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_update_enrichment_value_error(self): + """ + test_update_enrichment_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + enrichment_id = 'testString' + name = 'testString' + description = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "enrichment_id": enrichment_id, + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_enrichment(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/enrichments/{1}'.format(body['project_id'], body['enrichment_id']) - 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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.update_enrichment(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['enrichment_id'] = "string1" - body.update({"name": "string1", "description": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['enrichment_id'] = "string1" - body.update({"name": "string1", "description": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_enrichment -#----------------------------------------------------------------------------- class TestDeleteEnrichment(): + """ + Test Class for delete_enrichment + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_enrichment_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_enrichment_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_enrichment_all_params(self): + """ + delete_enrichment() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + enrichment_id = 'testString' + + # Invoke method + response = service.delete_enrichment( + project_id, + enrichment_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_enrichment_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_enrichment_value_error(self): + """ + test_delete_enrichment_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + responses.add(responses.DELETE, + url, + status=204) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}/enrichments/{1}'.format(body['project_id'], body['enrichment_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + project_id = 'testString' + enrichment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "enrichment_id": enrichment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_enrichment(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.delete_enrichment(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body['enrichment_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - body['enrichment_id'] = "string1" - return body # endregion @@ -1848,352 +2408,450 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_projects -#----------------------------------------------------------------------------- class TestListProjects(): + """ + Test Class for list_projects + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_projects_response(self): - body = self.construct_full_body() - response = fake_response_ListProjectsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_projects_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ListProjectsResponse_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_projects_all_params(self): + """ + list_projects() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects') + mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_projects_empty(self): - check_empty_response(self) + # Invoke method + response = service.list_projects() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_projects_value_error(self): + """ + test_list_projects_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects') + mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.list_projects(**body) - return output - - def construct_full_body(self): - body = dict() - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_project -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_projects(**req_copy) + + + class TestCreateProject(): + """ + Test Class for create_project + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_project_response(self): - body = self.construct_full_body() - response = fake_response_ProjectDetails_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_project_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ProjectDetails_json - send_request(self, body, response) + def test_create_project_all_params(self): + """ + create_project() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a DefaultQueryParamsPassages model + default_query_params_passages_model = {} + default_query_params_passages_model['enabled'] = True + default_query_params_passages_model['count'] = 38 + default_query_params_passages_model['fields'] = ['testString'] + default_query_params_passages_model['characters'] = 38 + default_query_params_passages_model['per_document'] = True + default_query_params_passages_model['max_per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsTableResults model + default_query_params_table_results_model = {} + default_query_params_table_results_model['enabled'] = True + default_query_params_table_results_model['count'] = 38 + default_query_params_table_results_model['per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model + default_query_params_suggested_refinements_model = {} + default_query_params_suggested_refinements_model['enabled'] = True + default_query_params_suggested_refinements_model['count'] = 38 + + # Construct a dict representation of a DefaultQueryParams model + default_query_params_model = {} + default_query_params_model['collection_ids'] = ['testString'] + default_query_params_model['passages'] = default_query_params_passages_model + default_query_params_model['table_results'] = default_query_params_table_results_model + default_query_params_model['aggregation'] = 'testString' + default_query_params_model['suggested_refinements'] = default_query_params_suggested_refinements_model + default_query_params_model['spelling_suggestions'] = True + default_query_params_model['highlight'] = True + default_query_params_model['count'] = 38 + default_query_params_model['sort'] = 'testString' + default_query_params_model['return'] = ['testString'] + + # Set up parameter values + name = 'testString' + type = 'document_retrieval' + default_query_parameters = default_query_params_model + + # Invoke method + response = service.create_project( + name, + type, + default_query_parameters=default_query_parameters, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body)) + assert req_body['name'] == 'testString' + assert req_body['type'] == 'document_retrieval' + assert req_body['default_query_parameters'] == default_query_params_model + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_project_empty(self): - check_empty_required_params(self, fake_response_ProjectDetails_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_create_project_value_error(self): + """ + test_create_project_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a DefaultQueryParamsPassages model + default_query_params_passages_model = {} + default_query_params_passages_model['enabled'] = True + default_query_params_passages_model['count'] = 38 + default_query_params_passages_model['fields'] = ['testString'] + default_query_params_passages_model['characters'] = 38 + default_query_params_passages_model['per_document'] = True + default_query_params_passages_model['max_per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsTableResults model + default_query_params_table_results_model = {} + default_query_params_table_results_model['enabled'] = True + default_query_params_table_results_model['count'] = 38 + default_query_params_table_results_model['per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model + default_query_params_suggested_refinements_model = {} + default_query_params_suggested_refinements_model['enabled'] = True + default_query_params_suggested_refinements_model['count'] = 38 + + # Construct a dict representation of a DefaultQueryParams model + default_query_params_model = {} + default_query_params_model['collection_ids'] = ['testString'] + default_query_params_model['passages'] = default_query_params_passages_model + default_query_params_model['table_results'] = default_query_params_table_results_model + default_query_params_model['aggregation'] = 'testString' + default_query_params_model['suggested_refinements'] = default_query_params_suggested_refinements_model + default_query_params_model['spelling_suggestions'] = True + default_query_params_model['highlight'] = True + default_query_params_model['count'] = 38 + default_query_params_model['sort'] = 'testString' + default_query_params_model['return'] = ['testString'] + + # Set up parameter values + name = 'testString' + type = 'document_retrieval' + default_query_parameters = default_query_params_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "name": name, + "type": type, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_project(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects' - 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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.create_project(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"name": "string1", "type": "string1", "default_query_parameters": DefaultQueryParams._from_dict(json.loads("""{"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}""")), }) - return body - - def construct_required_body(self): - body = dict() - body.update({"name": "string1", "type": "string1", "default_query_parameters": DefaultQueryParams._from_dict(json.loads("""{"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}""")), }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_project -#----------------------------------------------------------------------------- class TestGetProject(): + """ + Test Class for get_project + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_project_response(self): - body = self.construct_full_body() - response = fake_response_ProjectDetails_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_project_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ProjectDetails_json - send_request(self, body, response) + def test_get_project_all_params(self): + """ + get_project() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = service.get_project( + project_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_project_empty(self): - check_empty_required_params(self, fake_response_ProjectDetails_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_project_value_error(self): + """ + test_get_project_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_project(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}'.format(body['project_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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.get_project(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_project -#----------------------------------------------------------------------------- class TestUpdateProject(): + """ + Test Class for update_project + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_project_response(self): - body = self.construct_full_body() - response = fake_response_ProjectDetails_json - send_request(self, body, response) + def test_update_project_all_params(self): + """ + update_project() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + name = 'testString' + + # Invoke method + response = service.update_project( + project_id, + name=name, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body)) + assert req_body['name'] == 'testString' + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_project_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ProjectDetails_json - send_request(self, body, response) + def test_update_project_required_params(self): + """ + test_update_project_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = service.update_project( + project_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_project_empty(self): - check_empty_required_params(self, fake_response_ProjectDetails_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_update_project_value_error(self): + """ + test_update_project_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_project(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}'.format(body['project_id']) - 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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.update_project(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - body.update({"name": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_project -#----------------------------------------------------------------------------- class TestDeleteProject(): + """ + Test Class for delete_project + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_project_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_project_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_project_all_params(self): + """ + delete_project() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = service.delete_project( + project_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_project_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_project_value_error(self): + """ + test_delete_project_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/projects/testString') + responses.add(responses.DELETE, + url, + status=204) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/projects/{0}'.format(body['project_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_project(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - - def call_service(self, body): - service = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.delete_project(**body) - return output - - def construct_full_body(self): - body = dict() - body['project_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['project_id'] = "string1" - return body # endregion @@ -2206,74 +2864,72 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for delete_user_data -#----------------------------------------------------------------------------- class TestDeleteUserData(): + """ + Test Class for delete_user_data + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_user_data_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_user_data_all_params(self): + """ + delete_user_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/user_data') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customer_id = 'testString' + + # Invoke method + response = service.delete_user_data( + customer_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'customer_id={}'.format(customer_id) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_user_data_value_error(self): + """ + test_delete_user_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/user_data') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v2/user_data' - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + customer_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customer_id": customer_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_user_data(**req_copy) - 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 = DiscoveryV2( - authenticator=NoAuthAuthenticator(), - version='2019-11-22', - ) - service.set_service_url(base_url) - output = service.delete_user_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['customer_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customer_id'] = "string1" - return body # endregion @@ -2282,92 +2938,3083 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error - -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error - -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) - -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response - - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string - - """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response - -#################### -## Mock Responses ## -#################### - -fake_response__json = None -fake_response_ListCollectionsResponse_json = """{"collections": []}""" -fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" -fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" -fake_response_CollectionDetails_json = """{"collection_id": "fake_collection_id", "name": "fake_name", "description": "fake_description", "created": "2017-05-16T13:56:54.957Z", "language": "fake_language", "enrichments": []}""" -fake_response_QueryResponse_json = """{"matching_results": 16, "results": [], "aggregations": [], "retrieval_details": {"document_retrieval_strategy": "fake_document_retrieval_strategy"}, "suggested_query": "fake_suggested_query", "suggested_refinements": [], "table_results": [], "passages": []}""" -fake_response_Completions_json = """{"completions": []}""" -fake_response_QueryNoticesResponse_json = """{"matching_results": 16, "notices": []}""" -fake_response_ListFieldsResponse_json = """{"fields": []}""" -fake_response_ComponentSettingsResponse_json = """{"fields_shown": {"body": {"use_passage": false, "field": "fake_field"}, "title": {"field": "fake_field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": []}""" -fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" -fake_response_DocumentAccepted_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" -fake_response_DeleteDocumentResponse_json = """{"document_id": "fake_document_id", "status": "fake_status"}""" -fake_response_TrainingQuerySet_json = """{"queries": []}""" -fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" -fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" -fake_response_TrainingQuery_json = """{"query_id": "fake_query_id", "natural_language_query": "fake_natural_language_query", "filter": "fake_filter", "created": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z", "examples": []}""" -fake_response_AnalyzedDocument_json = """{"notices": [], "result": {}}""" -fake_response_Enrichments_json = """{"enrichments": []}""" -fake_response_Enrichment_json = """{"enrichment_id": "fake_enrichment_id", "name": "fake_name", "description": "fake_description", "type": "fake_type", "options": {"languages": [], "entity_type": "fake_entity_type", "regular_expression": "fake_regular_expression", "result_field": "fake_result_field"}}""" -fake_response_Enrichment_json = """{"enrichment_id": "fake_enrichment_id", "name": "fake_name", "description": "fake_description", "type": "fake_type", "options": {"languages": [], "entity_type": "fake_entity_type", "regular_expression": "fake_regular_expression", "result_field": "fake_result_field"}}""" -fake_response_Enrichment_json = """{"enrichment_id": "fake_enrichment_id", "name": "fake_name", "description": "fake_description", "type": "fake_type", "options": {"languages": [], "entity_type": "fake_entity_type", "regular_expression": "fake_regular_expression", "result_field": "fake_result_field"}}""" -fake_response_ListProjectsResponse_json = """{"projects": []}""" -fake_response_ProjectDetails_json = """{"project_id": "fake_project_id", "name": "fake_name", "type": "fake_type", "relevancy_training_status": {"data_updated": "fake_data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "fake_successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}}""" -fake_response_ProjectDetails_json = """{"project_id": "fake_project_id", "name": "fake_name", "type": "fake_type", "relevancy_training_status": {"data_updated": "fake_data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "fake_successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}}""" -fake_response_ProjectDetails_json = """{"project_id": "fake_project_id", "name": "fake_name", "type": "fake_type", "relevancy_training_status": {"data_updated": "fake_data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "fake_successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": [], "passages": {"enabled": false, "count": 5, "fields": [], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "fake_aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "fake_sort", "return": []}}""" +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestAnalyzedDocument(): + """ + Test Class for AnalyzedDocument + """ + + def test_analyzed_document_serialization(self): + """ + Test serialization/deserialization for AnalyzedDocument + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['notice_id'] = 'testString' + notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['document_id'] = 'testString' + notice_model['collection_id'] = 'testString' + notice_model['query_id'] = 'testString' + notice_model['severity'] = 'warning' + notice_model['step'] = 'testString' + notice_model['description'] = 'testString' + + analyzed_result_model = {} # AnalyzedResult + analyzed_result_model['metadata'] = {} + analyzed_result_model['foo'] = { 'foo': 'bar' } + + # Construct a json representation of a AnalyzedDocument model + analyzed_document_model_json = {} + analyzed_document_model_json['notices'] = [notice_model] + analyzed_document_model_json['result'] = analyzed_result_model + + # Construct a model instance of AnalyzedDocument by calling from_dict on the json representation + analyzed_document_model = AnalyzedDocument.from_dict(analyzed_document_model_json) + assert analyzed_document_model != False + + # Construct a model instance of AnalyzedDocument by calling from_dict on the json representation + analyzed_document_model_dict = AnalyzedDocument.from_dict(analyzed_document_model_json).__dict__ + analyzed_document_model2 = AnalyzedDocument(**analyzed_document_model_dict) + + # Verify the model instances are equivalent + assert analyzed_document_model == analyzed_document_model2 + + # Convert model instance back to dict and verify no loss of data + analyzed_document_model_json2 = analyzed_document_model.to_dict() + assert analyzed_document_model_json2 == analyzed_document_model_json + +class TestAnalyzedResult(): + """ + Test Class for AnalyzedResult + """ + + def test_analyzed_result_serialization(self): + """ + Test serialization/deserialization for AnalyzedResult + """ + + # Construct a json representation of a AnalyzedResult model + analyzed_result_model_json = {} + analyzed_result_model_json['metadata'] = {} + analyzed_result_model_json['foo'] = { 'foo': 'bar' } + + # Construct a model instance of AnalyzedResult by calling from_dict on the json representation + analyzed_result_model = AnalyzedResult.from_dict(analyzed_result_model_json) + assert analyzed_result_model != False + + # Construct a model instance of AnalyzedResult by calling from_dict on the json representation + analyzed_result_model_dict = AnalyzedResult.from_dict(analyzed_result_model_json).__dict__ + analyzed_result_model2 = AnalyzedResult(**analyzed_result_model_dict) + + # Verify the model instances are equivalent + assert analyzed_result_model == analyzed_result_model2 + + # Convert model instance back to dict and verify no loss of data + analyzed_result_model_json2 = analyzed_result_model.to_dict() + assert analyzed_result_model_json2 == analyzed_result_model_json + +class TestCollection(): + """ + Test Class for Collection + """ + + def test_collection_serialization(self): + """ + Test serialization/deserialization for Collection + """ + + # Construct a json representation of a Collection model + collection_model_json = {} + collection_model_json['collection_id'] = 'testString' + collection_model_json['name'] = 'testString' + + # Construct a model instance of Collection by calling from_dict on the json representation + collection_model = Collection.from_dict(collection_model_json) + assert collection_model != False + + # Construct a model instance of Collection by calling from_dict on the json representation + collection_model_dict = Collection.from_dict(collection_model_json).__dict__ + collection_model2 = Collection(**collection_model_dict) + + # Verify the model instances are equivalent + assert collection_model == collection_model2 + + # Convert model instance back to dict and verify no loss of data + collection_model_json2 = collection_model.to_dict() + assert collection_model_json2 == collection_model_json + +class TestCollectionDetails(): + """ + Test Class for CollectionDetails + """ + + def test_collection_details_serialization(self): + """ + Test serialization/deserialization for CollectionDetails + """ + + # Construct dict forms of any model objects needed in order to build this model. + + collection_enrichment_model = {} # CollectionEnrichment + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Construct a json representation of a CollectionDetails model + collection_details_model_json = {} + collection_details_model_json['collection_id'] = 'testString' + collection_details_model_json['name'] = 'testString' + collection_details_model_json['description'] = 'testString' + collection_details_model_json['created'] = '2020-01-28T18:40:40.123456Z' + collection_details_model_json['language'] = 'testString' + collection_details_model_json['enrichments'] = [collection_enrichment_model] + + # Construct a model instance of CollectionDetails by calling from_dict on the json representation + collection_details_model = CollectionDetails.from_dict(collection_details_model_json) + assert collection_details_model != False + + # Construct a model instance of CollectionDetails by calling from_dict on the json representation + collection_details_model_dict = CollectionDetails.from_dict(collection_details_model_json).__dict__ + collection_details_model2 = CollectionDetails(**collection_details_model_dict) + + # Verify the model instances are equivalent + assert collection_details_model == collection_details_model2 + + # Convert model instance back to dict and verify no loss of data + collection_details_model_json2 = collection_details_model.to_dict() + assert collection_details_model_json2 == collection_details_model_json + +class TestCollectionEnrichment(): + """ + Test Class for CollectionEnrichment + """ + + def test_collection_enrichment_serialization(self): + """ + Test serialization/deserialization for CollectionEnrichment + """ + + # Construct a json representation of a CollectionEnrichment model + collection_enrichment_model_json = {} + collection_enrichment_model_json['enrichment_id'] = 'testString' + collection_enrichment_model_json['fields'] = ['testString'] + + # Construct a model instance of CollectionEnrichment by calling from_dict on the json representation + collection_enrichment_model = CollectionEnrichment.from_dict(collection_enrichment_model_json) + assert collection_enrichment_model != False + + # Construct a model instance of CollectionEnrichment by calling from_dict on the json representation + collection_enrichment_model_dict = CollectionEnrichment.from_dict(collection_enrichment_model_json).__dict__ + collection_enrichment_model2 = CollectionEnrichment(**collection_enrichment_model_dict) + + # Verify the model instances are equivalent + assert collection_enrichment_model == collection_enrichment_model2 + + # Convert model instance back to dict and verify no loss of data + collection_enrichment_model_json2 = collection_enrichment_model.to_dict() + assert collection_enrichment_model_json2 == collection_enrichment_model_json + +class TestCompletions(): + """ + Test Class for Completions + """ + + def test_completions_serialization(self): + """ + Test serialization/deserialization for Completions + """ + + # Construct a json representation of a Completions model + completions_model_json = {} + completions_model_json['completions'] = ['testString'] + + # Construct a model instance of Completions by calling from_dict on the json representation + completions_model = Completions.from_dict(completions_model_json) + assert completions_model != False + + # Construct a model instance of Completions by calling from_dict on the json representation + completions_model_dict = Completions.from_dict(completions_model_json).__dict__ + completions_model2 = Completions(**completions_model_dict) + + # Verify the model instances are equivalent + assert completions_model == completions_model2 + + # Convert model instance back to dict and verify no loss of data + completions_model_json2 = completions_model.to_dict() + assert completions_model_json2 == completions_model_json + +class TestComponentSettingsAggregation(): + """ + Test Class for ComponentSettingsAggregation + """ + + def test_component_settings_aggregation_serialization(self): + """ + Test serialization/deserialization for ComponentSettingsAggregation + """ + + # Construct a json representation of a ComponentSettingsAggregation model + component_settings_aggregation_model_json = {} + component_settings_aggregation_model_json['name'] = 'testString' + component_settings_aggregation_model_json['label'] = 'testString' + component_settings_aggregation_model_json['multiple_selections_allowed'] = True + component_settings_aggregation_model_json['visualization_type'] = 'auto' + + # Construct a model instance of ComponentSettingsAggregation by calling from_dict on the json representation + component_settings_aggregation_model = ComponentSettingsAggregation.from_dict(component_settings_aggregation_model_json) + assert component_settings_aggregation_model != False + + # Construct a model instance of ComponentSettingsAggregation by calling from_dict on the json representation + component_settings_aggregation_model_dict = ComponentSettingsAggregation.from_dict(component_settings_aggregation_model_json).__dict__ + component_settings_aggregation_model2 = ComponentSettingsAggregation(**component_settings_aggregation_model_dict) + + # Verify the model instances are equivalent + assert component_settings_aggregation_model == component_settings_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + component_settings_aggregation_model_json2 = component_settings_aggregation_model.to_dict() + assert component_settings_aggregation_model_json2 == component_settings_aggregation_model_json + +class TestComponentSettingsFieldsShown(): + """ + Test Class for ComponentSettingsFieldsShown + """ + + def test_component_settings_fields_shown_serialization(self): + """ + Test serialization/deserialization for ComponentSettingsFieldsShown + """ + + # Construct dict forms of any model objects needed in order to build this model. + + component_settings_fields_shown_body_model = {} # ComponentSettingsFieldsShownBody + component_settings_fields_shown_body_model['use_passage'] = True + component_settings_fields_shown_body_model['field'] = 'testString' + + component_settings_fields_shown_title_model = {} # ComponentSettingsFieldsShownTitle + component_settings_fields_shown_title_model['field'] = 'testString' + + # Construct a json representation of a ComponentSettingsFieldsShown model + component_settings_fields_shown_model_json = {} + component_settings_fields_shown_model_json['body'] = component_settings_fields_shown_body_model + component_settings_fields_shown_model_json['title'] = component_settings_fields_shown_title_model + + # Construct a model instance of ComponentSettingsFieldsShown by calling from_dict on the json representation + component_settings_fields_shown_model = ComponentSettingsFieldsShown.from_dict(component_settings_fields_shown_model_json) + assert component_settings_fields_shown_model != False + + # Construct a model instance of ComponentSettingsFieldsShown by calling from_dict on the json representation + component_settings_fields_shown_model_dict = ComponentSettingsFieldsShown.from_dict(component_settings_fields_shown_model_json).__dict__ + component_settings_fields_shown_model2 = ComponentSettingsFieldsShown(**component_settings_fields_shown_model_dict) + + # Verify the model instances are equivalent + assert component_settings_fields_shown_model == component_settings_fields_shown_model2 + + # Convert model instance back to dict and verify no loss of data + component_settings_fields_shown_model_json2 = component_settings_fields_shown_model.to_dict() + assert component_settings_fields_shown_model_json2 == component_settings_fields_shown_model_json + +class TestComponentSettingsFieldsShownBody(): + """ + Test Class for ComponentSettingsFieldsShownBody + """ + + def test_component_settings_fields_shown_body_serialization(self): + """ + Test serialization/deserialization for ComponentSettingsFieldsShownBody + """ + + # Construct a json representation of a ComponentSettingsFieldsShownBody model + component_settings_fields_shown_body_model_json = {} + component_settings_fields_shown_body_model_json['use_passage'] = True + component_settings_fields_shown_body_model_json['field'] = 'testString' + + # Construct a model instance of ComponentSettingsFieldsShownBody by calling from_dict on the json representation + component_settings_fields_shown_body_model = ComponentSettingsFieldsShownBody.from_dict(component_settings_fields_shown_body_model_json) + assert component_settings_fields_shown_body_model != False + + # Construct a model instance of ComponentSettingsFieldsShownBody by calling from_dict on the json representation + component_settings_fields_shown_body_model_dict = ComponentSettingsFieldsShownBody.from_dict(component_settings_fields_shown_body_model_json).__dict__ + component_settings_fields_shown_body_model2 = ComponentSettingsFieldsShownBody(**component_settings_fields_shown_body_model_dict) + + # Verify the model instances are equivalent + assert component_settings_fields_shown_body_model == component_settings_fields_shown_body_model2 + + # Convert model instance back to dict and verify no loss of data + component_settings_fields_shown_body_model_json2 = component_settings_fields_shown_body_model.to_dict() + assert component_settings_fields_shown_body_model_json2 == component_settings_fields_shown_body_model_json + +class TestComponentSettingsFieldsShownTitle(): + """ + Test Class for ComponentSettingsFieldsShownTitle + """ + + def test_component_settings_fields_shown_title_serialization(self): + """ + Test serialization/deserialization for ComponentSettingsFieldsShownTitle + """ + + # Construct a json representation of a ComponentSettingsFieldsShownTitle model + component_settings_fields_shown_title_model_json = {} + component_settings_fields_shown_title_model_json['field'] = 'testString' + + # Construct a model instance of ComponentSettingsFieldsShownTitle by calling from_dict on the json representation + component_settings_fields_shown_title_model = ComponentSettingsFieldsShownTitle.from_dict(component_settings_fields_shown_title_model_json) + assert component_settings_fields_shown_title_model != False + + # Construct a model instance of ComponentSettingsFieldsShownTitle by calling from_dict on the json representation + component_settings_fields_shown_title_model_dict = ComponentSettingsFieldsShownTitle.from_dict(component_settings_fields_shown_title_model_json).__dict__ + component_settings_fields_shown_title_model2 = ComponentSettingsFieldsShownTitle(**component_settings_fields_shown_title_model_dict) + + # Verify the model instances are equivalent + assert component_settings_fields_shown_title_model == component_settings_fields_shown_title_model2 + + # Convert model instance back to dict and verify no loss of data + component_settings_fields_shown_title_model_json2 = component_settings_fields_shown_title_model.to_dict() + assert component_settings_fields_shown_title_model_json2 == component_settings_fields_shown_title_model_json + +class TestComponentSettingsResponse(): + """ + Test Class for ComponentSettingsResponse + """ + + def test_component_settings_response_serialization(self): + """ + Test serialization/deserialization for ComponentSettingsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + component_settings_fields_shown_body_model = {} # ComponentSettingsFieldsShownBody + component_settings_fields_shown_body_model['use_passage'] = True + component_settings_fields_shown_body_model['field'] = 'testString' + + component_settings_fields_shown_title_model = {} # ComponentSettingsFieldsShownTitle + component_settings_fields_shown_title_model['field'] = 'testString' + + component_settings_fields_shown_model = {} # ComponentSettingsFieldsShown + component_settings_fields_shown_model['body'] = component_settings_fields_shown_body_model + component_settings_fields_shown_model['title'] = component_settings_fields_shown_title_model + + component_settings_aggregation_model = {} # ComponentSettingsAggregation + component_settings_aggregation_model['name'] = 'testString' + component_settings_aggregation_model['label'] = 'testString' + component_settings_aggregation_model['multiple_selections_allowed'] = True + component_settings_aggregation_model['visualization_type'] = 'auto' + + # Construct a json representation of a ComponentSettingsResponse model + component_settings_response_model_json = {} + component_settings_response_model_json['fields_shown'] = component_settings_fields_shown_model + component_settings_response_model_json['autocomplete'] = True + component_settings_response_model_json['structured_search'] = True + component_settings_response_model_json['results_per_page'] = 38 + component_settings_response_model_json['aggregations'] = [component_settings_aggregation_model] + + # Construct a model instance of ComponentSettingsResponse by calling from_dict on the json representation + component_settings_response_model = ComponentSettingsResponse.from_dict(component_settings_response_model_json) + assert component_settings_response_model != False + + # Construct a model instance of ComponentSettingsResponse by calling from_dict on the json representation + component_settings_response_model_dict = ComponentSettingsResponse.from_dict(component_settings_response_model_json).__dict__ + component_settings_response_model2 = ComponentSettingsResponse(**component_settings_response_model_dict) + + # Verify the model instances are equivalent + assert component_settings_response_model == component_settings_response_model2 + + # Convert model instance back to dict and verify no loss of data + component_settings_response_model_json2 = component_settings_response_model.to_dict() + assert component_settings_response_model_json2 == component_settings_response_model_json + +class TestCreateEnrichment(): + """ + Test Class for CreateEnrichment + """ + + def test_create_enrichment_serialization(self): + """ + Test serialization/deserialization for CreateEnrichment + """ + + # Construct dict forms of any model objects needed in order to build this model. + + enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + + # Construct a json representation of a CreateEnrichment model + create_enrichment_model_json = {} + create_enrichment_model_json['name'] = 'testString' + create_enrichment_model_json['description'] = 'testString' + create_enrichment_model_json['type'] = 'dictionary' + create_enrichment_model_json['options'] = enrichment_options_model + + # Construct a model instance of CreateEnrichment by calling from_dict on the json representation + create_enrichment_model = CreateEnrichment.from_dict(create_enrichment_model_json) + assert create_enrichment_model != False + + # Construct a model instance of CreateEnrichment by calling from_dict on the json representation + create_enrichment_model_dict = CreateEnrichment.from_dict(create_enrichment_model_json).__dict__ + create_enrichment_model2 = CreateEnrichment(**create_enrichment_model_dict) + + # Verify the model instances are equivalent + assert create_enrichment_model == create_enrichment_model2 + + # Convert model instance back to dict and verify no loss of data + create_enrichment_model_json2 = create_enrichment_model.to_dict() + assert create_enrichment_model_json2 == create_enrichment_model_json + +class TestDefaultQueryParams(): + """ + Test Class for DefaultQueryParams + """ + + def test_default_query_params_serialization(self): + """ + Test serialization/deserialization for DefaultQueryParams + """ + + # Construct dict forms of any model objects needed in order to build this model. + + default_query_params_passages_model = {} # DefaultQueryParamsPassages + default_query_params_passages_model['enabled'] = True + default_query_params_passages_model['count'] = 38 + default_query_params_passages_model['fields'] = ['testString'] + default_query_params_passages_model['characters'] = 38 + default_query_params_passages_model['per_document'] = True + default_query_params_passages_model['max_per_document'] = 38 + + default_query_params_table_results_model = {} # DefaultQueryParamsTableResults + default_query_params_table_results_model['enabled'] = True + default_query_params_table_results_model['count'] = 38 + default_query_params_table_results_model['per_document'] = 38 + + default_query_params_suggested_refinements_model = {} # DefaultQueryParamsSuggestedRefinements + default_query_params_suggested_refinements_model['enabled'] = True + default_query_params_suggested_refinements_model['count'] = 38 + + # Construct a json representation of a DefaultQueryParams model + default_query_params_model_json = {} + default_query_params_model_json['collection_ids'] = ['testString'] + default_query_params_model_json['passages'] = default_query_params_passages_model + default_query_params_model_json['table_results'] = default_query_params_table_results_model + default_query_params_model_json['aggregation'] = 'testString' + default_query_params_model_json['suggested_refinements'] = default_query_params_suggested_refinements_model + default_query_params_model_json['spelling_suggestions'] = True + default_query_params_model_json['highlight'] = True + default_query_params_model_json['count'] = 38 + default_query_params_model_json['sort'] = 'testString' + default_query_params_model_json['return'] = ['testString'] + + # Construct a model instance of DefaultQueryParams by calling from_dict on the json representation + default_query_params_model = DefaultQueryParams.from_dict(default_query_params_model_json) + assert default_query_params_model != False + + # Construct a model instance of DefaultQueryParams by calling from_dict on the json representation + default_query_params_model_dict = DefaultQueryParams.from_dict(default_query_params_model_json).__dict__ + default_query_params_model2 = DefaultQueryParams(**default_query_params_model_dict) + + # Verify the model instances are equivalent + assert default_query_params_model == default_query_params_model2 + + # Convert model instance back to dict and verify no loss of data + default_query_params_model_json2 = default_query_params_model.to_dict() + assert default_query_params_model_json2 == default_query_params_model_json + +class TestDefaultQueryParamsPassages(): + """ + Test Class for DefaultQueryParamsPassages + """ + + def test_default_query_params_passages_serialization(self): + """ + Test serialization/deserialization for DefaultQueryParamsPassages + """ + + # Construct a json representation of a DefaultQueryParamsPassages model + default_query_params_passages_model_json = {} + default_query_params_passages_model_json['enabled'] = True + default_query_params_passages_model_json['count'] = 38 + default_query_params_passages_model_json['fields'] = ['testString'] + default_query_params_passages_model_json['characters'] = 38 + default_query_params_passages_model_json['per_document'] = True + default_query_params_passages_model_json['max_per_document'] = 38 + + # Construct a model instance of DefaultQueryParamsPassages by calling from_dict on the json representation + default_query_params_passages_model = DefaultQueryParamsPassages.from_dict(default_query_params_passages_model_json) + assert default_query_params_passages_model != False + + # Construct a model instance of DefaultQueryParamsPassages by calling from_dict on the json representation + default_query_params_passages_model_dict = DefaultQueryParamsPassages.from_dict(default_query_params_passages_model_json).__dict__ + default_query_params_passages_model2 = DefaultQueryParamsPassages(**default_query_params_passages_model_dict) + + # Verify the model instances are equivalent + assert default_query_params_passages_model == default_query_params_passages_model2 + + # Convert model instance back to dict and verify no loss of data + default_query_params_passages_model_json2 = default_query_params_passages_model.to_dict() + assert default_query_params_passages_model_json2 == default_query_params_passages_model_json + +class TestDefaultQueryParamsSuggestedRefinements(): + """ + Test Class for DefaultQueryParamsSuggestedRefinements + """ + + def test_default_query_params_suggested_refinements_serialization(self): + """ + Test serialization/deserialization for DefaultQueryParamsSuggestedRefinements + """ + + # Construct a json representation of a DefaultQueryParamsSuggestedRefinements model + default_query_params_suggested_refinements_model_json = {} + default_query_params_suggested_refinements_model_json['enabled'] = True + default_query_params_suggested_refinements_model_json['count'] = 38 + + # Construct a model instance of DefaultQueryParamsSuggestedRefinements by calling from_dict on the json representation + default_query_params_suggested_refinements_model = DefaultQueryParamsSuggestedRefinements.from_dict(default_query_params_suggested_refinements_model_json) + assert default_query_params_suggested_refinements_model != False + + # Construct a model instance of DefaultQueryParamsSuggestedRefinements by calling from_dict on the json representation + default_query_params_suggested_refinements_model_dict = DefaultQueryParamsSuggestedRefinements.from_dict(default_query_params_suggested_refinements_model_json).__dict__ + default_query_params_suggested_refinements_model2 = DefaultQueryParamsSuggestedRefinements(**default_query_params_suggested_refinements_model_dict) + + # Verify the model instances are equivalent + assert default_query_params_suggested_refinements_model == default_query_params_suggested_refinements_model2 + + # Convert model instance back to dict and verify no loss of data + default_query_params_suggested_refinements_model_json2 = default_query_params_suggested_refinements_model.to_dict() + assert default_query_params_suggested_refinements_model_json2 == default_query_params_suggested_refinements_model_json + +class TestDefaultQueryParamsTableResults(): + """ + Test Class for DefaultQueryParamsTableResults + """ + + def test_default_query_params_table_results_serialization(self): + """ + Test serialization/deserialization for DefaultQueryParamsTableResults + """ + + # Construct a json representation of a DefaultQueryParamsTableResults model + default_query_params_table_results_model_json = {} + default_query_params_table_results_model_json['enabled'] = True + default_query_params_table_results_model_json['count'] = 38 + default_query_params_table_results_model_json['per_document'] = 38 + + # Construct a model instance of DefaultQueryParamsTableResults by calling from_dict on the json representation + default_query_params_table_results_model = DefaultQueryParamsTableResults.from_dict(default_query_params_table_results_model_json) + assert default_query_params_table_results_model != False + + # Construct a model instance of DefaultQueryParamsTableResults by calling from_dict on the json representation + default_query_params_table_results_model_dict = DefaultQueryParamsTableResults.from_dict(default_query_params_table_results_model_json).__dict__ + default_query_params_table_results_model2 = DefaultQueryParamsTableResults(**default_query_params_table_results_model_dict) + + # Verify the model instances are equivalent + assert default_query_params_table_results_model == default_query_params_table_results_model2 + + # Convert model instance back to dict and verify no loss of data + default_query_params_table_results_model_json2 = default_query_params_table_results_model.to_dict() + assert default_query_params_table_results_model_json2 == default_query_params_table_results_model_json + +class TestDeleteDocumentResponse(): + """ + Test Class for DeleteDocumentResponse + """ + + def test_delete_document_response_serialization(self): + """ + Test serialization/deserialization for DeleteDocumentResponse + """ + + # Construct a json representation of a DeleteDocumentResponse model + delete_document_response_model_json = {} + delete_document_response_model_json['document_id'] = 'testString' + delete_document_response_model_json['status'] = 'deleted' + + # Construct a model instance of DeleteDocumentResponse by calling from_dict on the json representation + delete_document_response_model = DeleteDocumentResponse.from_dict(delete_document_response_model_json) + assert delete_document_response_model != False + + # Construct a model instance of DeleteDocumentResponse by calling from_dict on the json representation + delete_document_response_model_dict = DeleteDocumentResponse.from_dict(delete_document_response_model_json).__dict__ + delete_document_response_model2 = DeleteDocumentResponse(**delete_document_response_model_dict) + + # Verify the model instances are equivalent + assert delete_document_response_model == delete_document_response_model2 + + # Convert model instance back to dict and verify no loss of data + delete_document_response_model_json2 = delete_document_response_model.to_dict() + assert delete_document_response_model_json2 == delete_document_response_model_json + +class TestDocumentAccepted(): + """ + Test Class for DocumentAccepted + """ + + def test_document_accepted_serialization(self): + """ + Test serialization/deserialization for DocumentAccepted + """ + + # Construct a json representation of a DocumentAccepted model + document_accepted_model_json = {} + document_accepted_model_json['document_id'] = 'testString' + document_accepted_model_json['status'] = 'processing' + + # Construct a model instance of DocumentAccepted by calling from_dict on the json representation + document_accepted_model = DocumentAccepted.from_dict(document_accepted_model_json) + assert document_accepted_model != False + + # Construct a model instance of DocumentAccepted by calling from_dict on the json representation + document_accepted_model_dict = DocumentAccepted.from_dict(document_accepted_model_json).__dict__ + document_accepted_model2 = DocumentAccepted(**document_accepted_model_dict) + + # Verify the model instances are equivalent + assert document_accepted_model == document_accepted_model2 + + # Convert model instance back to dict and verify no loss of data + document_accepted_model_json2 = document_accepted_model.to_dict() + assert document_accepted_model_json2 == document_accepted_model_json + +class TestDocumentAttribute(): + """ + Test Class for DocumentAttribute + """ + + def test_document_attribute_serialization(self): + """ + Test serialization/deserialization for DocumentAttribute + """ + + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + + # Construct a json representation of a DocumentAttribute model + document_attribute_model_json = {} + document_attribute_model_json['type'] = 'testString' + document_attribute_model_json['text'] = 'testString' + document_attribute_model_json['location'] = table_element_location_model + + # Construct a model instance of DocumentAttribute by calling from_dict on the json representation + document_attribute_model = DocumentAttribute.from_dict(document_attribute_model_json) + assert document_attribute_model != False + + # Construct a model instance of DocumentAttribute by calling from_dict on the json representation + document_attribute_model_dict = DocumentAttribute.from_dict(document_attribute_model_json).__dict__ + document_attribute_model2 = DocumentAttribute(**document_attribute_model_dict) + + # Verify the model instances are equivalent + assert document_attribute_model == document_attribute_model2 + + # Convert model instance back to dict and verify no loss of data + document_attribute_model_json2 = document_attribute_model.to_dict() + assert document_attribute_model_json2 == document_attribute_model_json + +class TestEnrichment(): + """ + Test Class for Enrichment + """ + + def test_enrichment_serialization(self): + """ + Test serialization/deserialization for Enrichment + """ + + # Construct dict forms of any model objects needed in order to build this model. + + enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + + # Construct a json representation of a Enrichment model + enrichment_model_json = {} + enrichment_model_json['enrichment_id'] = 'testString' + enrichment_model_json['name'] = 'testString' + enrichment_model_json['description'] = 'testString' + enrichment_model_json['type'] = 'part_of_speech' + enrichment_model_json['options'] = enrichment_options_model + + # Construct a model instance of Enrichment by calling from_dict on the json representation + enrichment_model = Enrichment.from_dict(enrichment_model_json) + assert enrichment_model != False + + # Construct a model instance of Enrichment by calling from_dict on the json representation + enrichment_model_dict = Enrichment.from_dict(enrichment_model_json).__dict__ + enrichment_model2 = Enrichment(**enrichment_model_dict) + + # Verify the model instances are equivalent + assert enrichment_model == enrichment_model2 + + # Convert model instance back to dict and verify no loss of data + enrichment_model_json2 = enrichment_model.to_dict() + assert enrichment_model_json2 == enrichment_model_json + +class TestEnrichmentOptions(): + """ + Test Class for EnrichmentOptions + """ + + def test_enrichment_options_serialization(self): + """ + Test serialization/deserialization for EnrichmentOptions + """ + + # Construct a json representation of a EnrichmentOptions model + enrichment_options_model_json = {} + enrichment_options_model_json['languages'] = ['testString'] + enrichment_options_model_json['entity_type'] = 'testString' + enrichment_options_model_json['regular_expression'] = 'testString' + enrichment_options_model_json['result_field'] = 'testString' + + # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation + enrichment_options_model = EnrichmentOptions.from_dict(enrichment_options_model_json) + assert enrichment_options_model != False + + # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation + enrichment_options_model_dict = EnrichmentOptions.from_dict(enrichment_options_model_json).__dict__ + enrichment_options_model2 = EnrichmentOptions(**enrichment_options_model_dict) + + # Verify the model instances are equivalent + assert enrichment_options_model == enrichment_options_model2 + + # Convert model instance back to dict and verify no loss of data + enrichment_options_model_json2 = enrichment_options_model.to_dict() + assert enrichment_options_model_json2 == enrichment_options_model_json + +class TestEnrichments(): + """ + Test Class for Enrichments + """ + + def test_enrichments_serialization(self): + """ + Test serialization/deserialization for Enrichments + """ + + # Construct dict forms of any model objects needed in order to build this model. + + enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + + enrichment_model = {} # Enrichment + enrichment_model['enrichment_id'] = 'testString' + enrichment_model['name'] = 'testString' + enrichment_model['description'] = 'testString' + enrichment_model['type'] = 'part_of_speech' + enrichment_model['options'] = enrichment_options_model + + # Construct a json representation of a Enrichments model + enrichments_model_json = {} + enrichments_model_json['enrichments'] = [enrichment_model] + + # Construct a model instance of Enrichments by calling from_dict on the json representation + enrichments_model = Enrichments.from_dict(enrichments_model_json) + assert enrichments_model != False + + # Construct a model instance of Enrichments by calling from_dict on the json representation + enrichments_model_dict = Enrichments.from_dict(enrichments_model_json).__dict__ + enrichments_model2 = Enrichments(**enrichments_model_dict) + + # Verify the model instances are equivalent + assert enrichments_model == enrichments_model2 + + # Convert model instance back to dict and verify no loss of data + enrichments_model_json2 = enrichments_model.to_dict() + assert enrichments_model_json2 == enrichments_model_json + +class TestField(): + """ + Test Class for Field + """ + + def test_field_serialization(self): + """ + Test serialization/deserialization for Field + """ + + # Construct a json representation of a Field model + field_model_json = {} + field_model_json['field'] = 'testString' + field_model_json['type'] = 'nested' + field_model_json['collection_id'] = 'testString' + + # Construct a model instance of Field by calling from_dict on the json representation + field_model = Field.from_dict(field_model_json) + assert field_model != False + + # Construct a model instance of Field by calling from_dict on the json representation + field_model_dict = Field.from_dict(field_model_json).__dict__ + field_model2 = Field(**field_model_dict) + + # Verify the model instances are equivalent + assert field_model == field_model2 + + # Convert model instance back to dict and verify no loss of data + field_model_json2 = field_model.to_dict() + assert field_model_json2 == field_model_json + +class TestListCollectionsResponse(): + """ + Test Class for ListCollectionsResponse + """ + + def test_list_collections_response_serialization(self): + """ + Test serialization/deserialization for ListCollectionsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + collection_model = {} # Collection + collection_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' + collection_model['name'] = 'example' + + # Construct a json representation of a ListCollectionsResponse model + list_collections_response_model_json = {} + list_collections_response_model_json['collections'] = [collection_model] + + # Construct a model instance of ListCollectionsResponse by calling from_dict on the json representation + list_collections_response_model = ListCollectionsResponse.from_dict(list_collections_response_model_json) + assert list_collections_response_model != False + + # Construct a model instance of ListCollectionsResponse by calling from_dict on the json representation + list_collections_response_model_dict = ListCollectionsResponse.from_dict(list_collections_response_model_json).__dict__ + list_collections_response_model2 = ListCollectionsResponse(**list_collections_response_model_dict) + + # Verify the model instances are equivalent + assert list_collections_response_model == list_collections_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_collections_response_model_json2 = list_collections_response_model.to_dict() + assert list_collections_response_model_json2 == list_collections_response_model_json + +class TestListFieldsResponse(): + """ + Test Class for ListFieldsResponse + """ + + def test_list_fields_response_serialization(self): + """ + Test serialization/deserialization for ListFieldsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + field_model = {} # Field + field_model['field'] = 'testString' + field_model['type'] = 'nested' + field_model['collection_id'] = 'testString' + + # Construct a json representation of a ListFieldsResponse model + list_fields_response_model_json = {} + list_fields_response_model_json['fields'] = [field_model] + + # Construct a model instance of ListFieldsResponse by calling from_dict on the json representation + list_fields_response_model = ListFieldsResponse.from_dict(list_fields_response_model_json) + assert list_fields_response_model != False + + # Construct a model instance of ListFieldsResponse by calling from_dict on the json representation + list_fields_response_model_dict = ListFieldsResponse.from_dict(list_fields_response_model_json).__dict__ + list_fields_response_model2 = ListFieldsResponse(**list_fields_response_model_dict) + + # Verify the model instances are equivalent + assert list_fields_response_model == list_fields_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_fields_response_model_json2 = list_fields_response_model.to_dict() + assert list_fields_response_model_json2 == list_fields_response_model_json + +class TestListProjectsResponse(): + """ + Test Class for ListProjectsResponse + """ + + def test_list_projects_response_serialization(self): + """ + Test serialization/deserialization for ListProjectsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + project_list_details_relevancy_training_status_model = {} # ProjectListDetailsRelevancyTrainingStatus + project_list_details_relevancy_training_status_model['data_updated'] = 'testString' + project_list_details_relevancy_training_status_model['total_examples'] = 38 + project_list_details_relevancy_training_status_model['sufficient_label_diversity'] = True + project_list_details_relevancy_training_status_model['processing'] = True + project_list_details_relevancy_training_status_model['minimum_examples_added'] = True + project_list_details_relevancy_training_status_model['successfully_trained'] = 'testString' + project_list_details_relevancy_training_status_model['available'] = True + project_list_details_relevancy_training_status_model['notices'] = 38 + project_list_details_relevancy_training_status_model['minimum_queries_added'] = True + + project_list_details_model = {} # ProjectListDetails + project_list_details_model['project_id'] = 'testString' + project_list_details_model['name'] = 'testString' + project_list_details_model['type'] = 'document_retrieval' + project_list_details_model['relevancy_training_status'] = project_list_details_relevancy_training_status_model + project_list_details_model['collection_count'] = 38 + + # Construct a json representation of a ListProjectsResponse model + list_projects_response_model_json = {} + list_projects_response_model_json['projects'] = [project_list_details_model] + + # Construct a model instance of ListProjectsResponse by calling from_dict on the json representation + list_projects_response_model = ListProjectsResponse.from_dict(list_projects_response_model_json) + assert list_projects_response_model != False + + # Construct a model instance of ListProjectsResponse by calling from_dict on the json representation + list_projects_response_model_dict = ListProjectsResponse.from_dict(list_projects_response_model_json).__dict__ + list_projects_response_model2 = ListProjectsResponse(**list_projects_response_model_dict) + + # Verify the model instances are equivalent + assert list_projects_response_model == list_projects_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_projects_response_model_json2 = list_projects_response_model.to_dict() + assert list_projects_response_model_json2 == list_projects_response_model_json + +class TestNotice(): + """ + Test Class for Notice + """ + + def test_notice_serialization(self): + """ + Test serialization/deserialization for Notice + """ + + # Construct a json representation of a Notice model + notice_model_json = {} + notice_model_json['notice_id'] = 'testString' + notice_model_json['created'] = '2020-01-28T18:40:40.123456Z' + notice_model_json['document_id'] = 'testString' + notice_model_json['collection_id'] = 'testString' + notice_model_json['query_id'] = 'testString' + notice_model_json['severity'] = 'warning' + notice_model_json['step'] = 'testString' + notice_model_json['description'] = 'testString' + + # Construct a model instance of Notice by calling from_dict on the json representation + notice_model = Notice.from_dict(notice_model_json) + assert notice_model != False + + # Construct a model instance of Notice by calling from_dict on the json representation + notice_model_dict = Notice.from_dict(notice_model_json).__dict__ + notice_model2 = Notice(**notice_model_dict) + + # Verify the model instances are equivalent + assert notice_model == notice_model2 + + # Convert model instance back to dict and verify no loss of data + notice_model_json2 = notice_model.to_dict() + assert notice_model_json2 == notice_model_json + +class TestProjectDetails(): + """ + Test Class for ProjectDetails + """ + + def test_project_details_serialization(self): + """ + Test serialization/deserialization for ProjectDetails + """ + + # Construct dict forms of any model objects needed in order to build this model. + + project_list_details_relevancy_training_status_model = {} # ProjectListDetailsRelevancyTrainingStatus + project_list_details_relevancy_training_status_model['data_updated'] = 'testString' + project_list_details_relevancy_training_status_model['total_examples'] = 38 + project_list_details_relevancy_training_status_model['sufficient_label_diversity'] = True + project_list_details_relevancy_training_status_model['processing'] = True + project_list_details_relevancy_training_status_model['minimum_examples_added'] = True + project_list_details_relevancy_training_status_model['successfully_trained'] = 'testString' + project_list_details_relevancy_training_status_model['available'] = True + project_list_details_relevancy_training_status_model['notices'] = 38 + project_list_details_relevancy_training_status_model['minimum_queries_added'] = True + + default_query_params_passages_model = {} # DefaultQueryParamsPassages + default_query_params_passages_model['enabled'] = True + default_query_params_passages_model['count'] = 38 + default_query_params_passages_model['fields'] = ['testString'] + default_query_params_passages_model['characters'] = 38 + default_query_params_passages_model['per_document'] = True + default_query_params_passages_model['max_per_document'] = 38 + + default_query_params_table_results_model = {} # DefaultQueryParamsTableResults + default_query_params_table_results_model['enabled'] = True + default_query_params_table_results_model['count'] = 38 + default_query_params_table_results_model['per_document'] = 38 + + default_query_params_suggested_refinements_model = {} # DefaultQueryParamsSuggestedRefinements + default_query_params_suggested_refinements_model['enabled'] = True + default_query_params_suggested_refinements_model['count'] = 38 + + default_query_params_model = {} # DefaultQueryParams + default_query_params_model['collection_ids'] = ['testString'] + default_query_params_model['passages'] = default_query_params_passages_model + default_query_params_model['table_results'] = default_query_params_table_results_model + default_query_params_model['aggregation'] = 'testString' + default_query_params_model['suggested_refinements'] = default_query_params_suggested_refinements_model + default_query_params_model['spelling_suggestions'] = True + default_query_params_model['highlight'] = True + default_query_params_model['count'] = 38 + default_query_params_model['sort'] = 'testString' + default_query_params_model['return'] = ['testString'] + + # Construct a json representation of a ProjectDetails model + project_details_model_json = {} + project_details_model_json['project_id'] = 'testString' + project_details_model_json['name'] = 'testString' + project_details_model_json['type'] = 'document_retrieval' + project_details_model_json['relevancy_training_status'] = project_list_details_relevancy_training_status_model + project_details_model_json['collection_count'] = 38 + project_details_model_json['default_query_parameters'] = default_query_params_model + + # Construct a model instance of ProjectDetails by calling from_dict on the json representation + project_details_model = ProjectDetails.from_dict(project_details_model_json) + assert project_details_model != False + + # Construct a model instance of ProjectDetails by calling from_dict on the json representation + project_details_model_dict = ProjectDetails.from_dict(project_details_model_json).__dict__ + project_details_model2 = ProjectDetails(**project_details_model_dict) + + # Verify the model instances are equivalent + assert project_details_model == project_details_model2 + + # Convert model instance back to dict and verify no loss of data + project_details_model_json2 = project_details_model.to_dict() + assert project_details_model_json2 == project_details_model_json + +class TestProjectListDetails(): + """ + Test Class for ProjectListDetails + """ + + def test_project_list_details_serialization(self): + """ + Test serialization/deserialization for ProjectListDetails + """ + + # Construct dict forms of any model objects needed in order to build this model. + + project_list_details_relevancy_training_status_model = {} # ProjectListDetailsRelevancyTrainingStatus + project_list_details_relevancy_training_status_model['data_updated'] = 'testString' + project_list_details_relevancy_training_status_model['total_examples'] = 38 + project_list_details_relevancy_training_status_model['sufficient_label_diversity'] = True + project_list_details_relevancy_training_status_model['processing'] = True + project_list_details_relevancy_training_status_model['minimum_examples_added'] = True + project_list_details_relevancy_training_status_model['successfully_trained'] = 'testString' + project_list_details_relevancy_training_status_model['available'] = True + project_list_details_relevancy_training_status_model['notices'] = 38 + project_list_details_relevancy_training_status_model['minimum_queries_added'] = True + + # Construct a json representation of a ProjectListDetails model + project_list_details_model_json = {} + project_list_details_model_json['project_id'] = 'testString' + project_list_details_model_json['name'] = 'testString' + project_list_details_model_json['type'] = 'document_retrieval' + project_list_details_model_json['relevancy_training_status'] = project_list_details_relevancy_training_status_model + project_list_details_model_json['collection_count'] = 38 + + # Construct a model instance of ProjectListDetails by calling from_dict on the json representation + project_list_details_model = ProjectListDetails.from_dict(project_list_details_model_json) + assert project_list_details_model != False + + # Construct a model instance of ProjectListDetails by calling from_dict on the json representation + project_list_details_model_dict = ProjectListDetails.from_dict(project_list_details_model_json).__dict__ + project_list_details_model2 = ProjectListDetails(**project_list_details_model_dict) + + # Verify the model instances are equivalent + assert project_list_details_model == project_list_details_model2 + + # Convert model instance back to dict and verify no loss of data + project_list_details_model_json2 = project_list_details_model.to_dict() + assert project_list_details_model_json2 == project_list_details_model_json + +class TestProjectListDetailsRelevancyTrainingStatus(): + """ + Test Class for ProjectListDetailsRelevancyTrainingStatus + """ + + def test_project_list_details_relevancy_training_status_serialization(self): + """ + Test serialization/deserialization for ProjectListDetailsRelevancyTrainingStatus + """ + + # Construct a json representation of a ProjectListDetailsRelevancyTrainingStatus model + project_list_details_relevancy_training_status_model_json = {} + project_list_details_relevancy_training_status_model_json['data_updated'] = 'testString' + project_list_details_relevancy_training_status_model_json['total_examples'] = 38 + project_list_details_relevancy_training_status_model_json['sufficient_label_diversity'] = True + project_list_details_relevancy_training_status_model_json['processing'] = True + project_list_details_relevancy_training_status_model_json['minimum_examples_added'] = True + project_list_details_relevancy_training_status_model_json['successfully_trained'] = 'testString' + project_list_details_relevancy_training_status_model_json['available'] = True + project_list_details_relevancy_training_status_model_json['notices'] = 38 + project_list_details_relevancy_training_status_model_json['minimum_queries_added'] = True + + # Construct a model instance of ProjectListDetailsRelevancyTrainingStatus by calling from_dict on the json representation + project_list_details_relevancy_training_status_model = ProjectListDetailsRelevancyTrainingStatus.from_dict(project_list_details_relevancy_training_status_model_json) + assert project_list_details_relevancy_training_status_model != False + + # Construct a model instance of ProjectListDetailsRelevancyTrainingStatus by calling from_dict on the json representation + project_list_details_relevancy_training_status_model_dict = ProjectListDetailsRelevancyTrainingStatus.from_dict(project_list_details_relevancy_training_status_model_json).__dict__ + project_list_details_relevancy_training_status_model2 = ProjectListDetailsRelevancyTrainingStatus(**project_list_details_relevancy_training_status_model_dict) + + # Verify the model instances are equivalent + assert project_list_details_relevancy_training_status_model == project_list_details_relevancy_training_status_model2 + + # Convert model instance back to dict and verify no loss of data + project_list_details_relevancy_training_status_model_json2 = project_list_details_relevancy_training_status_model.to_dict() + assert project_list_details_relevancy_training_status_model_json2 == project_list_details_relevancy_training_status_model_json + +class TestQueryAggregation(): + """ + Test Class for QueryAggregation + """ + + def test_query_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryAggregation + """ + + # Construct a json representation of a QueryAggregation model + query_aggregation_model_json = {} + query_aggregation_model_json['type'] = 'testString' + + # Construct a model instance of QueryAggregation by calling from_dict on the json representation + query_aggregation_model = QueryAggregation.from_dict(query_aggregation_model_json) + assert query_aggregation_model != False + + # Construct a copy of the model instance by calling from_dict on the output of to_dict + query_aggregation_model_json2 = query_aggregation_model.to_dict() + query_aggregation_model2 = QueryAggregation.from_dict(query_aggregation_model_json2) + + # Verify the model instances are equivalent + assert query_aggregation_model == query_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_aggregation_model_json2 = query_aggregation_model.to_dict() + assert query_aggregation_model_json2 == query_aggregation_model_json + +class TestQueryGroupByAggregationResult(): + """ + Test Class for QueryGroupByAggregationResult + """ + + def test_query_group_by_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryGroupByAggregationResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model['type'] = 'filter' + query_aggregation_model['match'] = 'testString' + query_aggregation_model['matching_results'] = 26 + + # Construct a json representation of a QueryGroupByAggregationResult model + query_group_by_aggregation_result_model_json = {} + query_group_by_aggregation_result_model_json['key'] = 'testString' + query_group_by_aggregation_result_model_json['matching_results'] = 38 + query_group_by_aggregation_result_model_json['relevancy'] = 72.5 + query_group_by_aggregation_result_model_json['total_matching_documents'] = 38 + query_group_by_aggregation_result_model_json['estimated_matching_documents'] = 38 + query_group_by_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + + # Construct a model instance of QueryGroupByAggregationResult by calling from_dict on the json representation + query_group_by_aggregation_result_model = QueryGroupByAggregationResult.from_dict(query_group_by_aggregation_result_model_json) + assert query_group_by_aggregation_result_model != False + + # Construct a model instance of QueryGroupByAggregationResult by calling from_dict on the json representation + query_group_by_aggregation_result_model_dict = QueryGroupByAggregationResult.from_dict(query_group_by_aggregation_result_model_json).__dict__ + query_group_by_aggregation_result_model2 = QueryGroupByAggregationResult(**query_group_by_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_group_by_aggregation_result_model == query_group_by_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_group_by_aggregation_result_model_json2 = query_group_by_aggregation_result_model.to_dict() + assert query_group_by_aggregation_result_model_json2 == query_group_by_aggregation_result_model_json + +class TestQueryHistogramAggregationResult(): + """ + Test Class for QueryHistogramAggregationResult + """ + + def test_query_histogram_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryHistogramAggregationResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model['type'] = 'filter' + query_aggregation_model['match'] = 'testString' + query_aggregation_model['matching_results'] = 26 + + # Construct a json representation of a QueryHistogramAggregationResult model + query_histogram_aggregation_result_model_json = {} + query_histogram_aggregation_result_model_json['key'] = 26 + query_histogram_aggregation_result_model_json['matching_results'] = 38 + query_histogram_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + + # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation + query_histogram_aggregation_result_model = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json) + assert query_histogram_aggregation_result_model != False + + # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation + query_histogram_aggregation_result_model_dict = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json).__dict__ + query_histogram_aggregation_result_model2 = QueryHistogramAggregationResult(**query_histogram_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_histogram_aggregation_result_model == query_histogram_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_histogram_aggregation_result_model_json2 = query_histogram_aggregation_result_model.to_dict() + assert query_histogram_aggregation_result_model_json2 == query_histogram_aggregation_result_model_json + +class TestQueryLargePassages(): + """ + Test Class for QueryLargePassages + """ + + def test_query_large_passages_serialization(self): + """ + Test serialization/deserialization for QueryLargePassages + """ + + # Construct a json representation of a QueryLargePassages model + query_large_passages_model_json = {} + query_large_passages_model_json['enabled'] = True + query_large_passages_model_json['per_document'] = True + query_large_passages_model_json['max_per_document'] = 38 + query_large_passages_model_json['fields'] = ['testString'] + query_large_passages_model_json['count'] = 100 + query_large_passages_model_json['characters'] = 50 + + # Construct a model instance of QueryLargePassages by calling from_dict on the json representation + query_large_passages_model = QueryLargePassages.from_dict(query_large_passages_model_json) + assert query_large_passages_model != False + + # Construct a model instance of QueryLargePassages by calling from_dict on the json representation + query_large_passages_model_dict = QueryLargePassages.from_dict(query_large_passages_model_json).__dict__ + query_large_passages_model2 = QueryLargePassages(**query_large_passages_model_dict) + + # Verify the model instances are equivalent + assert query_large_passages_model == query_large_passages_model2 + + # Convert model instance back to dict and verify no loss of data + query_large_passages_model_json2 = query_large_passages_model.to_dict() + assert query_large_passages_model_json2 == query_large_passages_model_json + +class TestQueryLargeSuggestedRefinements(): + """ + Test Class for QueryLargeSuggestedRefinements + """ + + def test_query_large_suggested_refinements_serialization(self): + """ + Test serialization/deserialization for QueryLargeSuggestedRefinements + """ + + # Construct a json representation of a QueryLargeSuggestedRefinements model + query_large_suggested_refinements_model_json = {} + query_large_suggested_refinements_model_json['enabled'] = True + query_large_suggested_refinements_model_json['count'] = 1 + + # Construct a model instance of QueryLargeSuggestedRefinements by calling from_dict on the json representation + query_large_suggested_refinements_model = QueryLargeSuggestedRefinements.from_dict(query_large_suggested_refinements_model_json) + assert query_large_suggested_refinements_model != False + + # Construct a model instance of QueryLargeSuggestedRefinements by calling from_dict on the json representation + query_large_suggested_refinements_model_dict = QueryLargeSuggestedRefinements.from_dict(query_large_suggested_refinements_model_json).__dict__ + query_large_suggested_refinements_model2 = QueryLargeSuggestedRefinements(**query_large_suggested_refinements_model_dict) + + # Verify the model instances are equivalent + assert query_large_suggested_refinements_model == query_large_suggested_refinements_model2 + + # Convert model instance back to dict and verify no loss of data + query_large_suggested_refinements_model_json2 = query_large_suggested_refinements_model.to_dict() + assert query_large_suggested_refinements_model_json2 == query_large_suggested_refinements_model_json + +class TestQueryLargeTableResults(): + """ + Test Class for QueryLargeTableResults + """ + + def test_query_large_table_results_serialization(self): + """ + Test serialization/deserialization for QueryLargeTableResults + """ + + # Construct a json representation of a QueryLargeTableResults model + query_large_table_results_model_json = {} + query_large_table_results_model_json['enabled'] = True + query_large_table_results_model_json['count'] = 38 + + # Construct a model instance of QueryLargeTableResults by calling from_dict on the json representation + query_large_table_results_model = QueryLargeTableResults.from_dict(query_large_table_results_model_json) + assert query_large_table_results_model != False + + # Construct a model instance of QueryLargeTableResults by calling from_dict on the json representation + query_large_table_results_model_dict = QueryLargeTableResults.from_dict(query_large_table_results_model_json).__dict__ + query_large_table_results_model2 = QueryLargeTableResults(**query_large_table_results_model_dict) + + # Verify the model instances are equivalent + assert query_large_table_results_model == query_large_table_results_model2 + + # Convert model instance back to dict and verify no loss of data + query_large_table_results_model_json2 = query_large_table_results_model.to_dict() + assert query_large_table_results_model_json2 == query_large_table_results_model_json + +class TestQueryNoticesResponse(): + """ + Test Class for QueryNoticesResponse + """ + + def test_query_notices_response_serialization(self): + """ + Test serialization/deserialization for QueryNoticesResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['notice_id'] = 'testString' + notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['document_id'] = 'testString' + notice_model['collection_id'] = 'testString' + notice_model['query_id'] = 'testString' + notice_model['severity'] = 'warning' + notice_model['step'] = 'testString' + notice_model['description'] = 'testString' + + # Construct a json representation of a QueryNoticesResponse model + query_notices_response_model_json = {} + query_notices_response_model_json['matching_results'] = 38 + query_notices_response_model_json['notices'] = [notice_model] + + # Construct a model instance of QueryNoticesResponse by calling from_dict on the json representation + query_notices_response_model = QueryNoticesResponse.from_dict(query_notices_response_model_json) + assert query_notices_response_model != False + + # Construct a model instance of QueryNoticesResponse by calling from_dict on the json representation + query_notices_response_model_dict = QueryNoticesResponse.from_dict(query_notices_response_model_json).__dict__ + query_notices_response_model2 = QueryNoticesResponse(**query_notices_response_model_dict) + + # Verify the model instances are equivalent + assert query_notices_response_model == query_notices_response_model2 + + # Convert model instance back to dict and verify no loss of data + query_notices_response_model_json2 = query_notices_response_model.to_dict() + assert query_notices_response_model_json2 == query_notices_response_model_json + +class TestQueryResponse(): + """ + Test Class for QueryResponse + """ + + def test_query_response_serialization(self): + """ + Test serialization/deserialization for QueryResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model['document_retrieval_source'] = 'search' + query_result_metadata_model['collection_id'] = 'testString' + query_result_metadata_model['confidence'] = 72.5 + + query_result_passage_model = {} # QueryResultPassage + query_result_passage_model['passage_text'] = 'testString' + query_result_passage_model['start_offset'] = 38 + query_result_passage_model['end_offset'] = 38 + query_result_passage_model['field'] = 'testString' + + query_result_model = {} # QueryResult + query_result_model['document_id'] = 'testString' + query_result_model['metadata'] = {} + query_result_model['result_metadata'] = query_result_metadata_model + query_result_model['document_passages'] = [query_result_passage_model] + query_result_model['foo'] = { 'foo': 'bar' } + + query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model['type'] = 'filter' + query_aggregation_model['match'] = 'testString' + query_aggregation_model['matching_results'] = 26 + + retrieval_details_model = {} # RetrievalDetails + retrieval_details_model['document_retrieval_strategy'] = 'untrained' + + query_suggested_refinement_model = {} # QuerySuggestedRefinement + query_suggested_refinement_model['text'] = 'testString' + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + + table_text_location_model = {} # TableTextLocation + table_text_location_model['text'] = 'testString' + table_text_location_model['location'] = table_element_location_model + + table_headers_model = {} # TableHeaders + table_headers_model['cell_id'] = 'testString' + table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['text'] = 'testString' + table_headers_model['row_index_begin'] = 26 + table_headers_model['row_index_end'] = 26 + table_headers_model['column_index_begin'] = 26 + table_headers_model['column_index_end'] = 26 + + table_row_headers_model = {} # TableRowHeaders + table_row_headers_model['cell_id'] = 'testString' + table_row_headers_model['location'] = table_element_location_model + table_row_headers_model['text'] = 'testString' + table_row_headers_model['text_normalized'] = 'testString' + table_row_headers_model['row_index_begin'] = 26 + table_row_headers_model['row_index_end'] = 26 + table_row_headers_model['column_index_begin'] = 26 + table_row_headers_model['column_index_end'] = 26 + + table_column_headers_model = {} # TableColumnHeaders + table_column_headers_model['cell_id'] = 'testString' + table_column_headers_model['location'] = { 'foo': 'bar' } + table_column_headers_model['text'] = 'testString' + table_column_headers_model['text_normalized'] = 'testString' + table_column_headers_model['row_index_begin'] = 26 + table_column_headers_model['row_index_end'] = 26 + table_column_headers_model['column_index_begin'] = 26 + table_column_headers_model['column_index_end'] = 26 + + table_cell_key_model = {} # TableCellKey + table_cell_key_model['cell_id'] = 'testString' + table_cell_key_model['location'] = table_element_location_model + table_cell_key_model['text'] = 'testString' + + table_cell_values_model = {} # TableCellValues + table_cell_values_model['cell_id'] = 'testString' + table_cell_values_model['location'] = table_element_location_model + table_cell_values_model['text'] = 'testString' + + table_key_value_pairs_model = {} # TableKeyValuePairs + table_key_value_pairs_model['key'] = table_cell_key_model + table_key_value_pairs_model['value'] = [table_cell_values_model] + + table_row_header_ids_model = {} # TableRowHeaderIds + table_row_header_ids_model['id'] = 'testString' + + table_row_header_texts_model = {} # TableRowHeaderTexts + table_row_header_texts_model['text'] = 'testString' + + table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized + table_row_header_texts_normalized_model['text_normalized'] = 'testString' + + table_column_header_ids_model = {} # TableColumnHeaderIds + table_column_header_ids_model['id'] = 'testString' + + table_column_header_texts_model = {} # TableColumnHeaderTexts + table_column_header_texts_model['text'] = 'testString' + + table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized + table_column_header_texts_normalized_model['text_normalized'] = 'testString' + + document_attribute_model = {} # DocumentAttribute + document_attribute_model['type'] = 'testString' + document_attribute_model['text'] = 'testString' + document_attribute_model['location'] = table_element_location_model + + table_body_cells_model = {} # TableBodyCells + table_body_cells_model['cell_id'] = 'testString' + table_body_cells_model['location'] = table_element_location_model + table_body_cells_model['text'] = 'testString' + table_body_cells_model['row_index_begin'] = 26 + table_body_cells_model['row_index_end'] = 26 + table_body_cells_model['column_index_begin'] = 26 + table_body_cells_model['column_index_end'] = 26 + table_body_cells_model['row_header_ids'] = [table_row_header_ids_model] + table_body_cells_model['row_header_texts'] = [table_row_header_texts_model] + table_body_cells_model['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] + table_body_cells_model['column_header_ids'] = [table_column_header_ids_model] + table_body_cells_model['column_header_texts'] = [table_column_header_texts_model] + table_body_cells_model['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model['attributes'] = [document_attribute_model] + + table_result_table_model = {} # TableResultTable + table_result_table_model['location'] = table_element_location_model + table_result_table_model['text'] = 'testString' + table_result_table_model['section_title'] = table_text_location_model + table_result_table_model['title'] = table_text_location_model + table_result_table_model['table_headers'] = [table_headers_model] + table_result_table_model['row_headers'] = [table_row_headers_model] + table_result_table_model['column_headers'] = [table_column_headers_model] + table_result_table_model['key_value_pairs'] = [table_key_value_pairs_model] + table_result_table_model['body_cells'] = [table_body_cells_model] + table_result_table_model['contexts'] = [table_text_location_model] + + query_table_result_model = {} # QueryTableResult + query_table_result_model['table_id'] = 'testString' + query_table_result_model['source_document_id'] = 'testString' + query_table_result_model['collection_id'] = 'testString' + query_table_result_model['table_html'] = 'testString' + query_table_result_model['table_html_offset'] = 38 + query_table_result_model['table'] = table_result_table_model + + query_response_passage_model = {} # QueryResponsePassage + query_response_passage_model['passage_text'] = 'testString' + query_response_passage_model['passage_score'] = 72.5 + query_response_passage_model['document_id'] = 'testString' + query_response_passage_model['collection_id'] = 'testString' + query_response_passage_model['start_offset'] = 38 + query_response_passage_model['end_offset'] = 38 + query_response_passage_model['field'] = 'testString' + + # Construct a json representation of a QueryResponse model + query_response_model_json = {} + query_response_model_json['matching_results'] = 38 + query_response_model_json['results'] = [query_result_model] + query_response_model_json['aggregations'] = [query_aggregation_model] + query_response_model_json['retrieval_details'] = retrieval_details_model + query_response_model_json['suggested_query'] = 'testString' + query_response_model_json['suggested_refinements'] = [query_suggested_refinement_model] + query_response_model_json['table_results'] = [query_table_result_model] + query_response_model_json['passages'] = [query_response_passage_model] + + # Construct a model instance of QueryResponse by calling from_dict on the json representation + query_response_model = QueryResponse.from_dict(query_response_model_json) + assert query_response_model != False + + # Construct a model instance of QueryResponse by calling from_dict on the json representation + query_response_model_dict = QueryResponse.from_dict(query_response_model_json).__dict__ + query_response_model2 = QueryResponse(**query_response_model_dict) + + # Verify the model instances are equivalent + assert query_response_model == query_response_model2 + + # Convert model instance back to dict and verify no loss of data + query_response_model_json2 = query_response_model.to_dict() + assert query_response_model_json2 == query_response_model_json + +class TestQueryResponsePassage(): + """ + Test Class for QueryResponsePassage + """ + + def test_query_response_passage_serialization(self): + """ + Test serialization/deserialization for QueryResponsePassage + """ + + # Construct a json representation of a QueryResponsePassage model + query_response_passage_model_json = {} + query_response_passage_model_json['passage_text'] = 'testString' + query_response_passage_model_json['passage_score'] = 72.5 + query_response_passage_model_json['document_id'] = 'testString' + query_response_passage_model_json['collection_id'] = 'testString' + query_response_passage_model_json['start_offset'] = 38 + query_response_passage_model_json['end_offset'] = 38 + query_response_passage_model_json['field'] = 'testString' + + # Construct a model instance of QueryResponsePassage by calling from_dict on the json representation + query_response_passage_model = QueryResponsePassage.from_dict(query_response_passage_model_json) + assert query_response_passage_model != False + + # Construct a model instance of QueryResponsePassage by calling from_dict on the json representation + query_response_passage_model_dict = QueryResponsePassage.from_dict(query_response_passage_model_json).__dict__ + query_response_passage_model2 = QueryResponsePassage(**query_response_passage_model_dict) + + # Verify the model instances are equivalent + assert query_response_passage_model == query_response_passage_model2 + + # Convert model instance back to dict and verify no loss of data + query_response_passage_model_json2 = query_response_passage_model.to_dict() + assert query_response_passage_model_json2 == query_response_passage_model_json + +class TestQueryResult(): + """ + Test Class for QueryResult + """ + + def test_query_result_serialization(self): + """ + Test serialization/deserialization for QueryResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model['document_retrieval_source'] = 'search' + query_result_metadata_model['collection_id'] = 'testString' + query_result_metadata_model['confidence'] = 72.5 + + query_result_passage_model = {} # QueryResultPassage + query_result_passage_model['passage_text'] = 'testString' + query_result_passage_model['start_offset'] = 38 + query_result_passage_model['end_offset'] = 38 + query_result_passage_model['field'] = 'testString' + + # Construct a json representation of a QueryResult model + query_result_model_json = {} + query_result_model_json['document_id'] = 'testString' + query_result_model_json['metadata'] = {} + query_result_model_json['result_metadata'] = query_result_metadata_model + query_result_model_json['document_passages'] = [query_result_passage_model] + query_result_model_json['foo'] = { 'foo': 'bar' } + + # Construct a model instance of QueryResult by calling from_dict on the json representation + query_result_model = QueryResult.from_dict(query_result_model_json) + assert query_result_model != False + + # Construct a model instance of QueryResult by calling from_dict on the json representation + query_result_model_dict = QueryResult.from_dict(query_result_model_json).__dict__ + query_result_model2 = QueryResult(**query_result_model_dict) + + # Verify the model instances are equivalent + assert query_result_model == query_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_result_model_json2 = query_result_model.to_dict() + assert query_result_model_json2 == query_result_model_json + +class TestQueryResultMetadata(): + """ + Test Class for QueryResultMetadata + """ + + def test_query_result_metadata_serialization(self): + """ + Test serialization/deserialization for QueryResultMetadata + """ + + # Construct a json representation of a QueryResultMetadata model + query_result_metadata_model_json = {} + query_result_metadata_model_json['document_retrieval_source'] = 'search' + query_result_metadata_model_json['collection_id'] = 'testString' + query_result_metadata_model_json['confidence'] = 72.5 + + # Construct a model instance of QueryResultMetadata by calling from_dict on the json representation + query_result_metadata_model = QueryResultMetadata.from_dict(query_result_metadata_model_json) + assert query_result_metadata_model != False + + # Construct a model instance of QueryResultMetadata by calling from_dict on the json representation + query_result_metadata_model_dict = QueryResultMetadata.from_dict(query_result_metadata_model_json).__dict__ + query_result_metadata_model2 = QueryResultMetadata(**query_result_metadata_model_dict) + + # Verify the model instances are equivalent + assert query_result_metadata_model == query_result_metadata_model2 + + # Convert model instance back to dict and verify no loss of data + query_result_metadata_model_json2 = query_result_metadata_model.to_dict() + assert query_result_metadata_model_json2 == query_result_metadata_model_json + +class TestQueryResultPassage(): + """ + Test Class for QueryResultPassage + """ + + def test_query_result_passage_serialization(self): + """ + Test serialization/deserialization for QueryResultPassage + """ + + # Construct a json representation of a QueryResultPassage model + query_result_passage_model_json = {} + query_result_passage_model_json['passage_text'] = 'testString' + query_result_passage_model_json['start_offset'] = 38 + query_result_passage_model_json['end_offset'] = 38 + query_result_passage_model_json['field'] = 'testString' + + # Construct a model instance of QueryResultPassage by calling from_dict on the json representation + query_result_passage_model = QueryResultPassage.from_dict(query_result_passage_model_json) + assert query_result_passage_model != False + + # Construct a model instance of QueryResultPassage by calling from_dict on the json representation + query_result_passage_model_dict = QueryResultPassage.from_dict(query_result_passage_model_json).__dict__ + query_result_passage_model2 = QueryResultPassage(**query_result_passage_model_dict) + + # Verify the model instances are equivalent + assert query_result_passage_model == query_result_passage_model2 + + # Convert model instance back to dict and verify no loss of data + query_result_passage_model_json2 = query_result_passage_model.to_dict() + assert query_result_passage_model_json2 == query_result_passage_model_json + +class TestQuerySuggestedRefinement(): + """ + Test Class for QuerySuggestedRefinement + """ + + def test_query_suggested_refinement_serialization(self): + """ + Test serialization/deserialization for QuerySuggestedRefinement + """ + + # Construct a json representation of a QuerySuggestedRefinement model + query_suggested_refinement_model_json = {} + query_suggested_refinement_model_json['text'] = 'testString' + + # Construct a model instance of QuerySuggestedRefinement by calling from_dict on the json representation + query_suggested_refinement_model = QuerySuggestedRefinement.from_dict(query_suggested_refinement_model_json) + assert query_suggested_refinement_model != False + + # Construct a model instance of QuerySuggestedRefinement by calling from_dict on the json representation + query_suggested_refinement_model_dict = QuerySuggestedRefinement.from_dict(query_suggested_refinement_model_json).__dict__ + query_suggested_refinement_model2 = QuerySuggestedRefinement(**query_suggested_refinement_model_dict) + + # Verify the model instances are equivalent + assert query_suggested_refinement_model == query_suggested_refinement_model2 + + # Convert model instance back to dict and verify no loss of data + query_suggested_refinement_model_json2 = query_suggested_refinement_model.to_dict() + assert query_suggested_refinement_model_json2 == query_suggested_refinement_model_json + +class TestQueryTableResult(): + """ + Test Class for QueryTableResult + """ + + def test_query_table_result_serialization(self): + """ + Test serialization/deserialization for QueryTableResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + + table_text_location_model = {} # TableTextLocation + table_text_location_model['text'] = 'testString' + table_text_location_model['location'] = table_element_location_model + + table_headers_model = {} # TableHeaders + table_headers_model['cell_id'] = 'testString' + table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['text'] = 'testString' + table_headers_model['row_index_begin'] = 26 + table_headers_model['row_index_end'] = 26 + table_headers_model['column_index_begin'] = 26 + table_headers_model['column_index_end'] = 26 + + table_row_headers_model = {} # TableRowHeaders + table_row_headers_model['cell_id'] = 'testString' + table_row_headers_model['location'] = table_element_location_model + table_row_headers_model['text'] = 'testString' + table_row_headers_model['text_normalized'] = 'testString' + table_row_headers_model['row_index_begin'] = 26 + table_row_headers_model['row_index_end'] = 26 + table_row_headers_model['column_index_begin'] = 26 + table_row_headers_model['column_index_end'] = 26 + + table_column_headers_model = {} # TableColumnHeaders + table_column_headers_model['cell_id'] = 'testString' + table_column_headers_model['location'] = { 'foo': 'bar' } + table_column_headers_model['text'] = 'testString' + table_column_headers_model['text_normalized'] = 'testString' + table_column_headers_model['row_index_begin'] = 26 + table_column_headers_model['row_index_end'] = 26 + table_column_headers_model['column_index_begin'] = 26 + table_column_headers_model['column_index_end'] = 26 + + table_cell_key_model = {} # TableCellKey + table_cell_key_model['cell_id'] = 'testString' + table_cell_key_model['location'] = table_element_location_model + table_cell_key_model['text'] = 'testString' + + table_cell_values_model = {} # TableCellValues + table_cell_values_model['cell_id'] = 'testString' + table_cell_values_model['location'] = table_element_location_model + table_cell_values_model['text'] = 'testString' + + table_key_value_pairs_model = {} # TableKeyValuePairs + table_key_value_pairs_model['key'] = table_cell_key_model + table_key_value_pairs_model['value'] = [table_cell_values_model] + + table_row_header_ids_model = {} # TableRowHeaderIds + table_row_header_ids_model['id'] = 'testString' + + table_row_header_texts_model = {} # TableRowHeaderTexts + table_row_header_texts_model['text'] = 'testString' + + table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized + table_row_header_texts_normalized_model['text_normalized'] = 'testString' + + table_column_header_ids_model = {} # TableColumnHeaderIds + table_column_header_ids_model['id'] = 'testString' + + table_column_header_texts_model = {} # TableColumnHeaderTexts + table_column_header_texts_model['text'] = 'testString' + + table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized + table_column_header_texts_normalized_model['text_normalized'] = 'testString' + + document_attribute_model = {} # DocumentAttribute + document_attribute_model['type'] = 'testString' + document_attribute_model['text'] = 'testString' + document_attribute_model['location'] = table_element_location_model + + table_body_cells_model = {} # TableBodyCells + table_body_cells_model['cell_id'] = 'testString' + table_body_cells_model['location'] = table_element_location_model + table_body_cells_model['text'] = 'testString' + table_body_cells_model['row_index_begin'] = 26 + table_body_cells_model['row_index_end'] = 26 + table_body_cells_model['column_index_begin'] = 26 + table_body_cells_model['column_index_end'] = 26 + table_body_cells_model['row_header_ids'] = [table_row_header_ids_model] + table_body_cells_model['row_header_texts'] = [table_row_header_texts_model] + table_body_cells_model['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] + table_body_cells_model['column_header_ids'] = [table_column_header_ids_model] + table_body_cells_model['column_header_texts'] = [table_column_header_texts_model] + table_body_cells_model['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model['attributes'] = [document_attribute_model] + + table_result_table_model = {} # TableResultTable + table_result_table_model['location'] = table_element_location_model + table_result_table_model['text'] = 'testString' + table_result_table_model['section_title'] = table_text_location_model + table_result_table_model['title'] = table_text_location_model + table_result_table_model['table_headers'] = [table_headers_model] + table_result_table_model['row_headers'] = [table_row_headers_model] + table_result_table_model['column_headers'] = [table_column_headers_model] + table_result_table_model['key_value_pairs'] = [table_key_value_pairs_model] + table_result_table_model['body_cells'] = [table_body_cells_model] + table_result_table_model['contexts'] = [table_text_location_model] + + # Construct a json representation of a QueryTableResult model + query_table_result_model_json = {} + query_table_result_model_json['table_id'] = 'testString' + query_table_result_model_json['source_document_id'] = 'testString' + query_table_result_model_json['collection_id'] = 'testString' + query_table_result_model_json['table_html'] = 'testString' + query_table_result_model_json['table_html_offset'] = 38 + query_table_result_model_json['table'] = table_result_table_model + + # Construct a model instance of QueryTableResult by calling from_dict on the json representation + query_table_result_model = QueryTableResult.from_dict(query_table_result_model_json) + assert query_table_result_model != False + + # Construct a model instance of QueryTableResult by calling from_dict on the json representation + query_table_result_model_dict = QueryTableResult.from_dict(query_table_result_model_json).__dict__ + query_table_result_model2 = QueryTableResult(**query_table_result_model_dict) + + # Verify the model instances are equivalent + assert query_table_result_model == query_table_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_table_result_model_json2 = query_table_result_model.to_dict() + assert query_table_result_model_json2 == query_table_result_model_json + +class TestQueryTermAggregationResult(): + """ + Test Class for QueryTermAggregationResult + """ + + def test_query_term_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryTermAggregationResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model['type'] = 'filter' + query_aggregation_model['match'] = 'testString' + query_aggregation_model['matching_results'] = 26 + + # Construct a json representation of a QueryTermAggregationResult model + query_term_aggregation_result_model_json = {} + query_term_aggregation_result_model_json['key'] = 'testString' + query_term_aggregation_result_model_json['matching_results'] = 38 + query_term_aggregation_result_model_json['relevancy'] = 72.5 + query_term_aggregation_result_model_json['total_matching_documents'] = 38 + query_term_aggregation_result_model_json['estimated_matching_documents'] = 38 + query_term_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + + # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation + query_term_aggregation_result_model = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json) + assert query_term_aggregation_result_model != False + + # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation + query_term_aggregation_result_model_dict = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json).__dict__ + query_term_aggregation_result_model2 = QueryTermAggregationResult(**query_term_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_term_aggregation_result_model == query_term_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_term_aggregation_result_model_json2 = query_term_aggregation_result_model.to_dict() + assert query_term_aggregation_result_model_json2 == query_term_aggregation_result_model_json + +class TestQueryTimesliceAggregationResult(): + """ + Test Class for QueryTimesliceAggregationResult + """ + + def test_query_timeslice_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryTimesliceAggregationResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model['type'] = 'filter' + query_aggregation_model['match'] = 'testString' + query_aggregation_model['matching_results'] = 26 + + # Construct a json representation of a QueryTimesliceAggregationResult model + query_timeslice_aggregation_result_model_json = {} + query_timeslice_aggregation_result_model_json['key_as_string'] = 'testString' + query_timeslice_aggregation_result_model_json['key'] = 26 + query_timeslice_aggregation_result_model_json['matching_results'] = 26 + query_timeslice_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + + # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation + query_timeslice_aggregation_result_model = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json) + assert query_timeslice_aggregation_result_model != False + + # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation + query_timeslice_aggregation_result_model_dict = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json).__dict__ + query_timeslice_aggregation_result_model2 = QueryTimesliceAggregationResult(**query_timeslice_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_timeslice_aggregation_result_model == query_timeslice_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_timeslice_aggregation_result_model_json2 = query_timeslice_aggregation_result_model.to_dict() + assert query_timeslice_aggregation_result_model_json2 == query_timeslice_aggregation_result_model_json + +class TestQueryTopHitsAggregationResult(): + """ + Test Class for QueryTopHitsAggregationResult + """ + + def test_query_top_hits_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryTopHitsAggregationResult + """ + + # Construct a json representation of a QueryTopHitsAggregationResult model + query_top_hits_aggregation_result_model_json = {} + query_top_hits_aggregation_result_model_json['matching_results'] = 38 + query_top_hits_aggregation_result_model_json['hits'] = [{}] + + # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation + query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) + assert query_top_hits_aggregation_result_model != False + + # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation + query_top_hits_aggregation_result_model_dict = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json).__dict__ + query_top_hits_aggregation_result_model2 = QueryTopHitsAggregationResult(**query_top_hits_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_top_hits_aggregation_result_model == query_top_hits_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() + assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json + +class TestRetrievalDetails(): + """ + Test Class for RetrievalDetails + """ + + def test_retrieval_details_serialization(self): + """ + Test serialization/deserialization for RetrievalDetails + """ + + # Construct a json representation of a RetrievalDetails model + retrieval_details_model_json = {} + retrieval_details_model_json['document_retrieval_strategy'] = 'untrained' + + # Construct a model instance of RetrievalDetails by calling from_dict on the json representation + retrieval_details_model = RetrievalDetails.from_dict(retrieval_details_model_json) + assert retrieval_details_model != False + + # Construct a model instance of RetrievalDetails by calling from_dict on the json representation + retrieval_details_model_dict = RetrievalDetails.from_dict(retrieval_details_model_json).__dict__ + retrieval_details_model2 = RetrievalDetails(**retrieval_details_model_dict) + + # Verify the model instances are equivalent + assert retrieval_details_model == retrieval_details_model2 + + # Convert model instance back to dict and verify no loss of data + retrieval_details_model_json2 = retrieval_details_model.to_dict() + assert retrieval_details_model_json2 == retrieval_details_model_json + +class TestTableBodyCells(): + """ + Test Class for TableBodyCells + """ + + def test_table_body_cells_serialization(self): + """ + Test serialization/deserialization for TableBodyCells + """ + + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + + table_row_header_ids_model = {} # TableRowHeaderIds + table_row_header_ids_model['id'] = 'testString' + + table_row_header_texts_model = {} # TableRowHeaderTexts + table_row_header_texts_model['text'] = 'testString' + + table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized + table_row_header_texts_normalized_model['text_normalized'] = 'testString' + + table_column_header_ids_model = {} # TableColumnHeaderIds + table_column_header_ids_model['id'] = 'testString' + + table_column_header_texts_model = {} # TableColumnHeaderTexts + table_column_header_texts_model['text'] = 'testString' + + table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized + table_column_header_texts_normalized_model['text_normalized'] = 'testString' + + document_attribute_model = {} # DocumentAttribute + document_attribute_model['type'] = 'testString' + document_attribute_model['text'] = 'testString' + document_attribute_model['location'] = table_element_location_model + + # Construct a json representation of a TableBodyCells model + table_body_cells_model_json = {} + table_body_cells_model_json['cell_id'] = 'testString' + table_body_cells_model_json['location'] = table_element_location_model + table_body_cells_model_json['text'] = 'testString' + table_body_cells_model_json['row_index_begin'] = 26 + table_body_cells_model_json['row_index_end'] = 26 + table_body_cells_model_json['column_index_begin'] = 26 + table_body_cells_model_json['column_index_end'] = 26 + table_body_cells_model_json['row_header_ids'] = [table_row_header_ids_model] + table_body_cells_model_json['row_header_texts'] = [table_row_header_texts_model] + table_body_cells_model_json['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] + table_body_cells_model_json['column_header_ids'] = [table_column_header_ids_model] + table_body_cells_model_json['column_header_texts'] = [table_column_header_texts_model] + table_body_cells_model_json['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model_json['attributes'] = [document_attribute_model] + + # Construct a model instance of TableBodyCells by calling from_dict on the json representation + table_body_cells_model = TableBodyCells.from_dict(table_body_cells_model_json) + assert table_body_cells_model != False + + # Construct a model instance of TableBodyCells by calling from_dict on the json representation + table_body_cells_model_dict = TableBodyCells.from_dict(table_body_cells_model_json).__dict__ + table_body_cells_model2 = TableBodyCells(**table_body_cells_model_dict) + + # Verify the model instances are equivalent + assert table_body_cells_model == table_body_cells_model2 + + # Convert model instance back to dict and verify no loss of data + table_body_cells_model_json2 = table_body_cells_model.to_dict() + assert table_body_cells_model_json2 == table_body_cells_model_json + +class TestTableCellKey(): + """ + Test Class for TableCellKey + """ + + def test_table_cell_key_serialization(self): + """ + Test serialization/deserialization for TableCellKey + """ + + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + + # Construct a json representation of a TableCellKey model + table_cell_key_model_json = {} + table_cell_key_model_json['cell_id'] = 'testString' + table_cell_key_model_json['location'] = table_element_location_model + table_cell_key_model_json['text'] = 'testString' + + # Construct a model instance of TableCellKey by calling from_dict on the json representation + table_cell_key_model = TableCellKey.from_dict(table_cell_key_model_json) + assert table_cell_key_model != False + + # Construct a model instance of TableCellKey by calling from_dict on the json representation + table_cell_key_model_dict = TableCellKey.from_dict(table_cell_key_model_json).__dict__ + table_cell_key_model2 = TableCellKey(**table_cell_key_model_dict) + + # Verify the model instances are equivalent + assert table_cell_key_model == table_cell_key_model2 + + # Convert model instance back to dict and verify no loss of data + table_cell_key_model_json2 = table_cell_key_model.to_dict() + assert table_cell_key_model_json2 == table_cell_key_model_json + +class TestTableCellValues(): + """ + Test Class for TableCellValues + """ + + def test_table_cell_values_serialization(self): + """ + Test serialization/deserialization for TableCellValues + """ + + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + + # Construct a json representation of a TableCellValues model + table_cell_values_model_json = {} + table_cell_values_model_json['cell_id'] = 'testString' + table_cell_values_model_json['location'] = table_element_location_model + table_cell_values_model_json['text'] = 'testString' + + # Construct a model instance of TableCellValues by calling from_dict on the json representation + table_cell_values_model = TableCellValues.from_dict(table_cell_values_model_json) + assert table_cell_values_model != False + + # Construct a model instance of TableCellValues by calling from_dict on the json representation + table_cell_values_model_dict = TableCellValues.from_dict(table_cell_values_model_json).__dict__ + table_cell_values_model2 = TableCellValues(**table_cell_values_model_dict) + + # Verify the model instances are equivalent + assert table_cell_values_model == table_cell_values_model2 + + # Convert model instance back to dict and verify no loss of data + table_cell_values_model_json2 = table_cell_values_model.to_dict() + assert table_cell_values_model_json2 == table_cell_values_model_json + +class TestTableColumnHeaderIds(): + """ + Test Class for TableColumnHeaderIds + """ + + def test_table_column_header_ids_serialization(self): + """ + Test serialization/deserialization for TableColumnHeaderIds + """ + + # Construct a json representation of a TableColumnHeaderIds model + table_column_header_ids_model_json = {} + table_column_header_ids_model_json['id'] = 'testString' + + # Construct a model instance of TableColumnHeaderIds by calling from_dict on the json representation + table_column_header_ids_model = TableColumnHeaderIds.from_dict(table_column_header_ids_model_json) + assert table_column_header_ids_model != False + + # Construct a model instance of TableColumnHeaderIds by calling from_dict on the json representation + table_column_header_ids_model_dict = TableColumnHeaderIds.from_dict(table_column_header_ids_model_json).__dict__ + table_column_header_ids_model2 = TableColumnHeaderIds(**table_column_header_ids_model_dict) + + # Verify the model instances are equivalent + assert table_column_header_ids_model == table_column_header_ids_model2 + + # Convert model instance back to dict and verify no loss of data + table_column_header_ids_model_json2 = table_column_header_ids_model.to_dict() + assert table_column_header_ids_model_json2 == table_column_header_ids_model_json + +class TestTableColumnHeaderTexts(): + """ + Test Class for TableColumnHeaderTexts + """ + + def test_table_column_header_texts_serialization(self): + """ + Test serialization/deserialization for TableColumnHeaderTexts + """ + + # Construct a json representation of a TableColumnHeaderTexts model + table_column_header_texts_model_json = {} + table_column_header_texts_model_json['text'] = 'testString' + + # Construct a model instance of TableColumnHeaderTexts by calling from_dict on the json representation + table_column_header_texts_model = TableColumnHeaderTexts.from_dict(table_column_header_texts_model_json) + assert table_column_header_texts_model != False + + # Construct a model instance of TableColumnHeaderTexts by calling from_dict on the json representation + table_column_header_texts_model_dict = TableColumnHeaderTexts.from_dict(table_column_header_texts_model_json).__dict__ + table_column_header_texts_model2 = TableColumnHeaderTexts(**table_column_header_texts_model_dict) + + # Verify the model instances are equivalent + assert table_column_header_texts_model == table_column_header_texts_model2 + + # Convert model instance back to dict and verify no loss of data + table_column_header_texts_model_json2 = table_column_header_texts_model.to_dict() + assert table_column_header_texts_model_json2 == table_column_header_texts_model_json + +class TestTableColumnHeaderTextsNormalized(): + """ + Test Class for TableColumnHeaderTextsNormalized + """ + + def test_table_column_header_texts_normalized_serialization(self): + """ + Test serialization/deserialization for TableColumnHeaderTextsNormalized + """ + + # Construct a json representation of a TableColumnHeaderTextsNormalized model + table_column_header_texts_normalized_model_json = {} + table_column_header_texts_normalized_model_json['text_normalized'] = 'testString' + + # Construct a model instance of TableColumnHeaderTextsNormalized by calling from_dict on the json representation + table_column_header_texts_normalized_model = TableColumnHeaderTextsNormalized.from_dict(table_column_header_texts_normalized_model_json) + assert table_column_header_texts_normalized_model != False + + # Construct a model instance of TableColumnHeaderTextsNormalized by calling from_dict on the json representation + table_column_header_texts_normalized_model_dict = TableColumnHeaderTextsNormalized.from_dict(table_column_header_texts_normalized_model_json).__dict__ + table_column_header_texts_normalized_model2 = TableColumnHeaderTextsNormalized(**table_column_header_texts_normalized_model_dict) + + # Verify the model instances are equivalent + assert table_column_header_texts_normalized_model == table_column_header_texts_normalized_model2 + + # Convert model instance back to dict and verify no loss of data + table_column_header_texts_normalized_model_json2 = table_column_header_texts_normalized_model.to_dict() + assert table_column_header_texts_normalized_model_json2 == table_column_header_texts_normalized_model_json + +class TestTableColumnHeaders(): + """ + Test Class for TableColumnHeaders + """ + + def test_table_column_headers_serialization(self): + """ + Test serialization/deserialization for TableColumnHeaders + """ + + # Construct a json representation of a TableColumnHeaders model + table_column_headers_model_json = {} + table_column_headers_model_json['cell_id'] = 'testString' + table_column_headers_model_json['location'] = { 'foo': 'bar' } + table_column_headers_model_json['text'] = 'testString' + table_column_headers_model_json['text_normalized'] = 'testString' + table_column_headers_model_json['row_index_begin'] = 26 + table_column_headers_model_json['row_index_end'] = 26 + table_column_headers_model_json['column_index_begin'] = 26 + table_column_headers_model_json['column_index_end'] = 26 + + # Construct a model instance of TableColumnHeaders by calling from_dict on the json representation + table_column_headers_model = TableColumnHeaders.from_dict(table_column_headers_model_json) + assert table_column_headers_model != False + + # Construct a model instance of TableColumnHeaders by calling from_dict on the json representation + table_column_headers_model_dict = TableColumnHeaders.from_dict(table_column_headers_model_json).__dict__ + table_column_headers_model2 = TableColumnHeaders(**table_column_headers_model_dict) + + # Verify the model instances are equivalent + assert table_column_headers_model == table_column_headers_model2 + + # Convert model instance back to dict and verify no loss of data + table_column_headers_model_json2 = table_column_headers_model.to_dict() + assert table_column_headers_model_json2 == table_column_headers_model_json + +class TestTableElementLocation(): + """ + Test Class for TableElementLocation + """ + + def test_table_element_location_serialization(self): + """ + Test serialization/deserialization for TableElementLocation + """ + + # Construct a json representation of a TableElementLocation model + table_element_location_model_json = {} + table_element_location_model_json['begin'] = 26 + table_element_location_model_json['end'] = 26 + + # Construct a model instance of TableElementLocation by calling from_dict on the json representation + table_element_location_model = TableElementLocation.from_dict(table_element_location_model_json) + assert table_element_location_model != False + + # Construct a model instance of TableElementLocation by calling from_dict on the json representation + table_element_location_model_dict = TableElementLocation.from_dict(table_element_location_model_json).__dict__ + table_element_location_model2 = TableElementLocation(**table_element_location_model_dict) + + # Verify the model instances are equivalent + assert table_element_location_model == table_element_location_model2 + + # Convert model instance back to dict and verify no loss of data + table_element_location_model_json2 = table_element_location_model.to_dict() + assert table_element_location_model_json2 == table_element_location_model_json + +class TestTableHeaders(): + """ + Test Class for TableHeaders + """ + + def test_table_headers_serialization(self): + """ + Test serialization/deserialization for TableHeaders + """ + + # Construct a json representation of a TableHeaders model + table_headers_model_json = {} + table_headers_model_json['cell_id'] = 'testString' + table_headers_model_json['location'] = { 'foo': 'bar' } + table_headers_model_json['text'] = 'testString' + table_headers_model_json['row_index_begin'] = 26 + table_headers_model_json['row_index_end'] = 26 + table_headers_model_json['column_index_begin'] = 26 + table_headers_model_json['column_index_end'] = 26 + + # Construct a model instance of TableHeaders by calling from_dict on the json representation + table_headers_model = TableHeaders.from_dict(table_headers_model_json) + assert table_headers_model != False + + # Construct a model instance of TableHeaders by calling from_dict on the json representation + table_headers_model_dict = TableHeaders.from_dict(table_headers_model_json).__dict__ + table_headers_model2 = TableHeaders(**table_headers_model_dict) + + # Verify the model instances are equivalent + assert table_headers_model == table_headers_model2 + + # Convert model instance back to dict and verify no loss of data + table_headers_model_json2 = table_headers_model.to_dict() + assert table_headers_model_json2 == table_headers_model_json + +class TestTableKeyValuePairs(): + """ + Test Class for TableKeyValuePairs + """ + + def test_table_key_value_pairs_serialization(self): + """ + Test serialization/deserialization for TableKeyValuePairs + """ + + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + + table_cell_key_model = {} # TableCellKey + table_cell_key_model['cell_id'] = 'testString' + table_cell_key_model['location'] = table_element_location_model + table_cell_key_model['text'] = 'testString' + + table_cell_values_model = {} # TableCellValues + table_cell_values_model['cell_id'] = 'testString' + table_cell_values_model['location'] = table_element_location_model + table_cell_values_model['text'] = 'testString' + + # Construct a json representation of a TableKeyValuePairs model + table_key_value_pairs_model_json = {} + table_key_value_pairs_model_json['key'] = table_cell_key_model + table_key_value_pairs_model_json['value'] = [table_cell_values_model] + + # Construct a model instance of TableKeyValuePairs by calling from_dict on the json representation + table_key_value_pairs_model = TableKeyValuePairs.from_dict(table_key_value_pairs_model_json) + assert table_key_value_pairs_model != False + + # Construct a model instance of TableKeyValuePairs by calling from_dict on the json representation + table_key_value_pairs_model_dict = TableKeyValuePairs.from_dict(table_key_value_pairs_model_json).__dict__ + table_key_value_pairs_model2 = TableKeyValuePairs(**table_key_value_pairs_model_dict) + + # Verify the model instances are equivalent + assert table_key_value_pairs_model == table_key_value_pairs_model2 + + # Convert model instance back to dict and verify no loss of data + table_key_value_pairs_model_json2 = table_key_value_pairs_model.to_dict() + assert table_key_value_pairs_model_json2 == table_key_value_pairs_model_json + +class TestTableResultTable(): + """ + Test Class for TableResultTable + """ + + def test_table_result_table_serialization(self): + """ + Test serialization/deserialization for TableResultTable + """ + + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + + table_text_location_model = {} # TableTextLocation + table_text_location_model['text'] = 'testString' + table_text_location_model['location'] = table_element_location_model + + table_headers_model = {} # TableHeaders + table_headers_model['cell_id'] = 'testString' + table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['text'] = 'testString' + table_headers_model['row_index_begin'] = 26 + table_headers_model['row_index_end'] = 26 + table_headers_model['column_index_begin'] = 26 + table_headers_model['column_index_end'] = 26 + + table_row_headers_model = {} # TableRowHeaders + table_row_headers_model['cell_id'] = 'testString' + table_row_headers_model['location'] = table_element_location_model + table_row_headers_model['text'] = 'testString' + table_row_headers_model['text_normalized'] = 'testString' + table_row_headers_model['row_index_begin'] = 26 + table_row_headers_model['row_index_end'] = 26 + table_row_headers_model['column_index_begin'] = 26 + table_row_headers_model['column_index_end'] = 26 + + table_column_headers_model = {} # TableColumnHeaders + table_column_headers_model['cell_id'] = 'testString' + table_column_headers_model['location'] = { 'foo': 'bar' } + table_column_headers_model['text'] = 'testString' + table_column_headers_model['text_normalized'] = 'testString' + table_column_headers_model['row_index_begin'] = 26 + table_column_headers_model['row_index_end'] = 26 + table_column_headers_model['column_index_begin'] = 26 + table_column_headers_model['column_index_end'] = 26 + + table_cell_key_model = {} # TableCellKey + table_cell_key_model['cell_id'] = 'testString' + table_cell_key_model['location'] = table_element_location_model + table_cell_key_model['text'] = 'testString' + + table_cell_values_model = {} # TableCellValues + table_cell_values_model['cell_id'] = 'testString' + table_cell_values_model['location'] = table_element_location_model + table_cell_values_model['text'] = 'testString' + + table_key_value_pairs_model = {} # TableKeyValuePairs + table_key_value_pairs_model['key'] = table_cell_key_model + table_key_value_pairs_model['value'] = [table_cell_values_model] + + table_row_header_ids_model = {} # TableRowHeaderIds + table_row_header_ids_model['id'] = 'testString' + + table_row_header_texts_model = {} # TableRowHeaderTexts + table_row_header_texts_model['text'] = 'testString' + + table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized + table_row_header_texts_normalized_model['text_normalized'] = 'testString' + + table_column_header_ids_model = {} # TableColumnHeaderIds + table_column_header_ids_model['id'] = 'testString' + + table_column_header_texts_model = {} # TableColumnHeaderTexts + table_column_header_texts_model['text'] = 'testString' + + table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized + table_column_header_texts_normalized_model['text_normalized'] = 'testString' + + document_attribute_model = {} # DocumentAttribute + document_attribute_model['type'] = 'testString' + document_attribute_model['text'] = 'testString' + document_attribute_model['location'] = table_element_location_model + + table_body_cells_model = {} # TableBodyCells + table_body_cells_model['cell_id'] = 'testString' + table_body_cells_model['location'] = table_element_location_model + table_body_cells_model['text'] = 'testString' + table_body_cells_model['row_index_begin'] = 26 + table_body_cells_model['row_index_end'] = 26 + table_body_cells_model['column_index_begin'] = 26 + table_body_cells_model['column_index_end'] = 26 + table_body_cells_model['row_header_ids'] = [table_row_header_ids_model] + table_body_cells_model['row_header_texts'] = [table_row_header_texts_model] + table_body_cells_model['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] + table_body_cells_model['column_header_ids'] = [table_column_header_ids_model] + table_body_cells_model['column_header_texts'] = [table_column_header_texts_model] + table_body_cells_model['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model['attributes'] = [document_attribute_model] + + # Construct a json representation of a TableResultTable model + table_result_table_model_json = {} + table_result_table_model_json['location'] = table_element_location_model + table_result_table_model_json['text'] = 'testString' + table_result_table_model_json['section_title'] = table_text_location_model + table_result_table_model_json['title'] = table_text_location_model + table_result_table_model_json['table_headers'] = [table_headers_model] + table_result_table_model_json['row_headers'] = [table_row_headers_model] + table_result_table_model_json['column_headers'] = [table_column_headers_model] + table_result_table_model_json['key_value_pairs'] = [table_key_value_pairs_model] + table_result_table_model_json['body_cells'] = [table_body_cells_model] + table_result_table_model_json['contexts'] = [table_text_location_model] + + # Construct a model instance of TableResultTable by calling from_dict on the json representation + table_result_table_model = TableResultTable.from_dict(table_result_table_model_json) + assert table_result_table_model != False + + # Construct a model instance of TableResultTable by calling from_dict on the json representation + table_result_table_model_dict = TableResultTable.from_dict(table_result_table_model_json).__dict__ + table_result_table_model2 = TableResultTable(**table_result_table_model_dict) + + # Verify the model instances are equivalent + assert table_result_table_model == table_result_table_model2 + + # Convert model instance back to dict and verify no loss of data + table_result_table_model_json2 = table_result_table_model.to_dict() + assert table_result_table_model_json2 == table_result_table_model_json + +class TestTableRowHeaderIds(): + """ + Test Class for TableRowHeaderIds + """ + + def test_table_row_header_ids_serialization(self): + """ + Test serialization/deserialization for TableRowHeaderIds + """ + + # Construct a json representation of a TableRowHeaderIds model + table_row_header_ids_model_json = {} + table_row_header_ids_model_json['id'] = 'testString' + + # Construct a model instance of TableRowHeaderIds by calling from_dict on the json representation + table_row_header_ids_model = TableRowHeaderIds.from_dict(table_row_header_ids_model_json) + assert table_row_header_ids_model != False + + # Construct a model instance of TableRowHeaderIds by calling from_dict on the json representation + table_row_header_ids_model_dict = TableRowHeaderIds.from_dict(table_row_header_ids_model_json).__dict__ + table_row_header_ids_model2 = TableRowHeaderIds(**table_row_header_ids_model_dict) + + # Verify the model instances are equivalent + assert table_row_header_ids_model == table_row_header_ids_model2 + + # Convert model instance back to dict and verify no loss of data + table_row_header_ids_model_json2 = table_row_header_ids_model.to_dict() + assert table_row_header_ids_model_json2 == table_row_header_ids_model_json + +class TestTableRowHeaderTexts(): + """ + Test Class for TableRowHeaderTexts + """ + + def test_table_row_header_texts_serialization(self): + """ + Test serialization/deserialization for TableRowHeaderTexts + """ + + # Construct a json representation of a TableRowHeaderTexts model + table_row_header_texts_model_json = {} + table_row_header_texts_model_json['text'] = 'testString' + + # Construct a model instance of TableRowHeaderTexts by calling from_dict on the json representation + table_row_header_texts_model = TableRowHeaderTexts.from_dict(table_row_header_texts_model_json) + assert table_row_header_texts_model != False + + # Construct a model instance of TableRowHeaderTexts by calling from_dict on the json representation + table_row_header_texts_model_dict = TableRowHeaderTexts.from_dict(table_row_header_texts_model_json).__dict__ + table_row_header_texts_model2 = TableRowHeaderTexts(**table_row_header_texts_model_dict) + + # Verify the model instances are equivalent + assert table_row_header_texts_model == table_row_header_texts_model2 + + # Convert model instance back to dict and verify no loss of data + table_row_header_texts_model_json2 = table_row_header_texts_model.to_dict() + assert table_row_header_texts_model_json2 == table_row_header_texts_model_json + +class TestTableRowHeaderTextsNormalized(): + """ + Test Class for TableRowHeaderTextsNormalized + """ + + def test_table_row_header_texts_normalized_serialization(self): + """ + Test serialization/deserialization for TableRowHeaderTextsNormalized + """ + + # Construct a json representation of a TableRowHeaderTextsNormalized model + table_row_header_texts_normalized_model_json = {} + table_row_header_texts_normalized_model_json['text_normalized'] = 'testString' + + # Construct a model instance of TableRowHeaderTextsNormalized by calling from_dict on the json representation + table_row_header_texts_normalized_model = TableRowHeaderTextsNormalized.from_dict(table_row_header_texts_normalized_model_json) + assert table_row_header_texts_normalized_model != False + + # Construct a model instance of TableRowHeaderTextsNormalized by calling from_dict on the json representation + table_row_header_texts_normalized_model_dict = TableRowHeaderTextsNormalized.from_dict(table_row_header_texts_normalized_model_json).__dict__ + table_row_header_texts_normalized_model2 = TableRowHeaderTextsNormalized(**table_row_header_texts_normalized_model_dict) + + # Verify the model instances are equivalent + assert table_row_header_texts_normalized_model == table_row_header_texts_normalized_model2 + + # Convert model instance back to dict and verify no loss of data + table_row_header_texts_normalized_model_json2 = table_row_header_texts_normalized_model.to_dict() + assert table_row_header_texts_normalized_model_json2 == table_row_header_texts_normalized_model_json + +class TestTableRowHeaders(): + """ + Test Class for TableRowHeaders + """ + + def test_table_row_headers_serialization(self): + """ + Test serialization/deserialization for TableRowHeaders + """ + + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + + # Construct a json representation of a TableRowHeaders model + table_row_headers_model_json = {} + table_row_headers_model_json['cell_id'] = 'testString' + table_row_headers_model_json['location'] = table_element_location_model + table_row_headers_model_json['text'] = 'testString' + table_row_headers_model_json['text_normalized'] = 'testString' + table_row_headers_model_json['row_index_begin'] = 26 + table_row_headers_model_json['row_index_end'] = 26 + table_row_headers_model_json['column_index_begin'] = 26 + table_row_headers_model_json['column_index_end'] = 26 + + # Construct a model instance of TableRowHeaders by calling from_dict on the json representation + table_row_headers_model = TableRowHeaders.from_dict(table_row_headers_model_json) + assert table_row_headers_model != False + + # Construct a model instance of TableRowHeaders by calling from_dict on the json representation + table_row_headers_model_dict = TableRowHeaders.from_dict(table_row_headers_model_json).__dict__ + table_row_headers_model2 = TableRowHeaders(**table_row_headers_model_dict) + + # Verify the model instances are equivalent + assert table_row_headers_model == table_row_headers_model2 + + # Convert model instance back to dict and verify no loss of data + table_row_headers_model_json2 = table_row_headers_model.to_dict() + assert table_row_headers_model_json2 == table_row_headers_model_json + +class TestTableTextLocation(): + """ + Test Class for TableTextLocation + """ + + def test_table_text_location_serialization(self): + """ + Test serialization/deserialization for TableTextLocation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + + # Construct a json representation of a TableTextLocation model + table_text_location_model_json = {} + table_text_location_model_json['text'] = 'testString' + table_text_location_model_json['location'] = table_element_location_model + + # Construct a model instance of TableTextLocation by calling from_dict on the json representation + table_text_location_model = TableTextLocation.from_dict(table_text_location_model_json) + assert table_text_location_model != False + + # Construct a model instance of TableTextLocation by calling from_dict on the json representation + table_text_location_model_dict = TableTextLocation.from_dict(table_text_location_model_json).__dict__ + table_text_location_model2 = TableTextLocation(**table_text_location_model_dict) + + # Verify the model instances are equivalent + assert table_text_location_model == table_text_location_model2 + + # Convert model instance back to dict and verify no loss of data + table_text_location_model_json2 = table_text_location_model.to_dict() + assert table_text_location_model_json2 == table_text_location_model_json + +class TestTrainingExample(): + """ + Test Class for TrainingExample + """ + + def test_training_example_serialization(self): + """ + Test serialization/deserialization for TrainingExample + """ + + # Construct a json representation of a TrainingExample model + training_example_model_json = {} + training_example_model_json['document_id'] = 'testString' + training_example_model_json['collection_id'] = 'testString' + training_example_model_json['relevance'] = 38 + training_example_model_json['created'] = '2020-01-28T18:40:40.123456Z' + training_example_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of TrainingExample by calling from_dict on the json representation + training_example_model = TrainingExample.from_dict(training_example_model_json) + assert training_example_model != False + + # Construct a model instance of TrainingExample by calling from_dict on the json representation + training_example_model_dict = TrainingExample.from_dict(training_example_model_json).__dict__ + training_example_model2 = TrainingExample(**training_example_model_dict) + + # Verify the model instances are equivalent + assert training_example_model == training_example_model2 + + # Convert model instance back to dict and verify no loss of data + training_example_model_json2 = training_example_model.to_dict() + assert training_example_model_json2 == training_example_model_json + +class TestTrainingQuery(): + """ + Test Class for TrainingQuery + """ + + def test_training_query_serialization(self): + """ + Test serialization/deserialization for TrainingQuery + """ + + # Construct dict forms of any model objects needed in order to build this model. + + training_example_model = {} # TrainingExample + training_example_model['document_id'] = 'testString' + training_example_model['collection_id'] = 'testString' + training_example_model['relevance'] = 38 + training_example_model['created'] = '2020-01-28T18:40:40.123456Z' + training_example_model['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a json representation of a TrainingQuery model + training_query_model_json = {} + training_query_model_json['query_id'] = 'testString' + training_query_model_json['natural_language_query'] = 'testString' + training_query_model_json['filter'] = 'testString' + training_query_model_json['created'] = '2020-01-28T18:40:40.123456Z' + training_query_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + training_query_model_json['examples'] = [training_example_model] + + # Construct a model instance of TrainingQuery by calling from_dict on the json representation + training_query_model = TrainingQuery.from_dict(training_query_model_json) + assert training_query_model != False + + # Construct a model instance of TrainingQuery by calling from_dict on the json representation + training_query_model_dict = TrainingQuery.from_dict(training_query_model_json).__dict__ + training_query_model2 = TrainingQuery(**training_query_model_dict) + + # Verify the model instances are equivalent + assert training_query_model == training_query_model2 + + # Convert model instance back to dict and verify no loss of data + training_query_model_json2 = training_query_model.to_dict() + assert training_query_model_json2 == training_query_model_json + +class TestTrainingQuerySet(): + """ + Test Class for TrainingQuerySet + """ + + def test_training_query_set_serialization(self): + """ + Test serialization/deserialization for TrainingQuerySet + """ + + # Construct dict forms of any model objects needed in order to build this model. + + training_example_model = {} # TrainingExample + training_example_model['document_id'] = 'testString' + training_example_model['collection_id'] = 'testString' + training_example_model['relevance'] = 38 + training_example_model['created'] = '2020-01-28T18:40:40.123456Z' + training_example_model['updated'] = '2020-01-28T18:40:40.123456Z' + + training_query_model = {} # TrainingQuery + training_query_model['query_id'] = 'testString' + training_query_model['natural_language_query'] = 'testString' + training_query_model['filter'] = 'testString' + training_query_model['created'] = '2020-01-28T18:40:40.123456Z' + training_query_model['updated'] = '2020-01-28T18:40:40.123456Z' + training_query_model['examples'] = [training_example_model] + + # Construct a json representation of a TrainingQuerySet model + training_query_set_model_json = {} + training_query_set_model_json['queries'] = [training_query_model] + + # Construct a model instance of TrainingQuerySet by calling from_dict on the json representation + training_query_set_model = TrainingQuerySet.from_dict(training_query_set_model_json) + assert training_query_set_model != False + + # Construct a model instance of TrainingQuerySet by calling from_dict on the json representation + training_query_set_model_dict = TrainingQuerySet.from_dict(training_query_set_model_json).__dict__ + training_query_set_model2 = TrainingQuerySet(**training_query_set_model_dict) + + # Verify the model instances are equivalent + assert training_query_set_model == training_query_set_model2 + + # Convert model instance back to dict and verify no loss of data + training_query_set_model_json2 = training_query_set_model.to_dict() + assert training_query_set_model_json2 == training_query_set_model_json + +class TestQueryCalculationAggregation(): + """ + Test Class for QueryCalculationAggregation + """ + + def test_query_calculation_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryCalculationAggregation + """ + + # Construct a json representation of a QueryCalculationAggregation model + query_calculation_aggregation_model_json = {} + query_calculation_aggregation_model_json['type'] = 'unique_count' + query_calculation_aggregation_model_json['field'] = 'testString' + query_calculation_aggregation_model_json['value'] = 72.5 + + # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation + query_calculation_aggregation_model = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json) + assert query_calculation_aggregation_model != False + + # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation + query_calculation_aggregation_model_dict = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json).__dict__ + query_calculation_aggregation_model2 = QueryCalculationAggregation(**query_calculation_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_calculation_aggregation_model == query_calculation_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_calculation_aggregation_model_json2 = query_calculation_aggregation_model.to_dict() + assert query_calculation_aggregation_model_json2 == query_calculation_aggregation_model_json + +class TestQueryFilterAggregation(): + """ + Test Class for QueryFilterAggregation + """ + + def test_query_filter_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryFilterAggregation + """ + + # Construct a json representation of a QueryFilterAggregation model + query_filter_aggregation_model_json = {} + query_filter_aggregation_model_json['type'] = 'filter' + query_filter_aggregation_model_json['match'] = 'testString' + query_filter_aggregation_model_json['matching_results'] = 26 + + # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation + query_filter_aggregation_model = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json) + assert query_filter_aggregation_model != False + + # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation + query_filter_aggregation_model_dict = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json).__dict__ + query_filter_aggregation_model2 = QueryFilterAggregation(**query_filter_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_filter_aggregation_model == query_filter_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_filter_aggregation_model_json2 = query_filter_aggregation_model.to_dict() + assert query_filter_aggregation_model_json2 == query_filter_aggregation_model_json + +class TestQueryGroupByAggregation(): + """ + Test Class for QueryGroupByAggregation + """ + + def test_query_group_by_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryGroupByAggregation + """ + + # Construct a json representation of a QueryGroupByAggregation model + query_group_by_aggregation_model_json = {} + query_group_by_aggregation_model_json['type'] = 'group_by' + + # Construct a model instance of QueryGroupByAggregation by calling from_dict on the json representation + query_group_by_aggregation_model = QueryGroupByAggregation.from_dict(query_group_by_aggregation_model_json) + assert query_group_by_aggregation_model != False + + # Construct a model instance of QueryGroupByAggregation by calling from_dict on the json representation + query_group_by_aggregation_model_dict = QueryGroupByAggregation.from_dict(query_group_by_aggregation_model_json).__dict__ + query_group_by_aggregation_model2 = QueryGroupByAggregation(**query_group_by_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_group_by_aggregation_model == query_group_by_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_group_by_aggregation_model_json2 = query_group_by_aggregation_model.to_dict() + assert query_group_by_aggregation_model_json2 == query_group_by_aggregation_model_json + +class TestQueryHistogramAggregation(): + """ + Test Class for QueryHistogramAggregation + """ + + def test_query_histogram_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryHistogramAggregation + """ + + # Construct a json representation of a QueryHistogramAggregation model + query_histogram_aggregation_model_json = {} + query_histogram_aggregation_model_json['type'] = 'histogram' + query_histogram_aggregation_model_json['field'] = 'testString' + query_histogram_aggregation_model_json['interval'] = 38 + query_histogram_aggregation_model_json['name'] = 'testString' + + # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation + query_histogram_aggregation_model = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json) + assert query_histogram_aggregation_model != False + + # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation + query_histogram_aggregation_model_dict = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json).__dict__ + query_histogram_aggregation_model2 = QueryHistogramAggregation(**query_histogram_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_histogram_aggregation_model == query_histogram_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_histogram_aggregation_model_json2 = query_histogram_aggregation_model.to_dict() + assert query_histogram_aggregation_model_json2 == query_histogram_aggregation_model_json + +class TestQueryNestedAggregation(): + """ + Test Class for QueryNestedAggregation + """ + + def test_query_nested_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryNestedAggregation + """ + + # Construct a json representation of a QueryNestedAggregation model + query_nested_aggregation_model_json = {} + query_nested_aggregation_model_json['type'] = 'nested' + query_nested_aggregation_model_json['path'] = 'testString' + query_nested_aggregation_model_json['matching_results'] = 26 + + # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation + query_nested_aggregation_model = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json) + assert query_nested_aggregation_model != False + + # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation + query_nested_aggregation_model_dict = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json).__dict__ + query_nested_aggregation_model2 = QueryNestedAggregation(**query_nested_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_nested_aggregation_model == query_nested_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_nested_aggregation_model_json2 = query_nested_aggregation_model.to_dict() + assert query_nested_aggregation_model_json2 == query_nested_aggregation_model_json + +class TestQueryTermAggregation(): + """ + Test Class for QueryTermAggregation + """ + + def test_query_term_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryTermAggregation + """ + + # Construct a json representation of a QueryTermAggregation model + query_term_aggregation_model_json = {} + query_term_aggregation_model_json['type'] = 'term' + query_term_aggregation_model_json['field'] = 'testString' + query_term_aggregation_model_json['count'] = 38 + query_term_aggregation_model_json['name'] = 'testString' + + # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation + query_term_aggregation_model = QueryTermAggregation.from_dict(query_term_aggregation_model_json) + assert query_term_aggregation_model != False + + # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation + query_term_aggregation_model_dict = QueryTermAggregation.from_dict(query_term_aggregation_model_json).__dict__ + query_term_aggregation_model2 = QueryTermAggregation(**query_term_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_term_aggregation_model == query_term_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_term_aggregation_model_json2 = query_term_aggregation_model.to_dict() + assert query_term_aggregation_model_json2 == query_term_aggregation_model_json + +class TestQueryTimesliceAggregation(): + """ + Test Class for QueryTimesliceAggregation + """ + + def test_query_timeslice_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryTimesliceAggregation + """ + + # Construct a json representation of a QueryTimesliceAggregation model + query_timeslice_aggregation_model_json = {} + query_timeslice_aggregation_model_json['type'] = 'timeslice' + query_timeslice_aggregation_model_json['field'] = 'testString' + query_timeslice_aggregation_model_json['interval'] = 'testString' + query_timeslice_aggregation_model_json['name'] = 'testString' + + # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation + query_timeslice_aggregation_model = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json) + assert query_timeslice_aggregation_model != False + + # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation + query_timeslice_aggregation_model_dict = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json).__dict__ + query_timeslice_aggregation_model2 = QueryTimesliceAggregation(**query_timeslice_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_timeslice_aggregation_model == query_timeslice_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_timeslice_aggregation_model_json2 = query_timeslice_aggregation_model.to_dict() + assert query_timeslice_aggregation_model_json2 == query_timeslice_aggregation_model_json + +class TestQueryTopHitsAggregation(): + """ + Test Class for QueryTopHitsAggregation + """ + + def test_query_top_hits_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryTopHitsAggregation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult + query_top_hits_aggregation_result_model['matching_results'] = 38 + query_top_hits_aggregation_result_model['hits'] = [{}] + + # Construct a json representation of a QueryTopHitsAggregation model + query_top_hits_aggregation_model_json = {} + query_top_hits_aggregation_model_json['type'] = 'top_hits' + query_top_hits_aggregation_model_json['size'] = 38 + query_top_hits_aggregation_model_json['name'] = 'testString' + query_top_hits_aggregation_model_json['hits'] = query_top_hits_aggregation_result_model + + # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation + query_top_hits_aggregation_model = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json) + assert query_top_hits_aggregation_model != False + + # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation + query_top_hits_aggregation_model_dict = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json).__dict__ + query_top_hits_aggregation_model2 = QueryTopHitsAggregation(**query_top_hits_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_top_hits_aggregation_model == query_top_hits_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_top_hits_aggregation_model_json2 = query_top_hits_aggregation_model.to_dict() + assert query_top_hits_aggregation_model_json2 == query_top_hits_aggregation_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 105e27faf..ab79534bc 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -13,88 +13,97 @@ # See the License for the specific language governing permissions and # limitations under the License. -from datetime import datetime +""" +Unit Tests for LanguageTranslatorV3 +""" + +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect +import io import json import pytest +import re +import requests import responses import tempfile -import ibm_watson.language_translator_v3 +import urllib from ibm_watson.language_translator_v3 import * +version = 'testString' + +service = LanguageTranslatorV3( + authenticator=NoAuthAuthenticator(), + version=version + ) + base_url = 'https://api.us-south.language-translator.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: Languages ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_languages -#----------------------------------------------------------------------------- class TestListLanguages(): + """ + Test Class for list_languages + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_languages_response(self): - body = self.construct_full_body() - response = fake_response_Languages_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_languages_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Languages_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_languages_all_params(self): + """ + list_languages() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/languages') + mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_languages_empty(self): - check_empty_response(self) + # Invoke method + response = service.list_languages() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/languages' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_languages_value_error(self): + """ + test_list_languages_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/languages') + mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.list_languages(**body) - return output - - def construct_full_body(self): - body = dict() - return body - - def construct_required_body(self): - body = dict() - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_languages(**req_copy) + # endregion @@ -107,74 +116,89 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for translate -#----------------------------------------------------------------------------- class TestTranslate(): + """ + Test Class for translate + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_translate_response(self): - body = self.construct_full_body() - response = fake_response_TranslationResult_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_translate_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TranslationResult_json - send_request(self, body, response) + def test_translate_all_params(self): + """ + translate() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/translate') + mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + text = ['testString'] + model_id = 'testString' + source = 'testString' + target = 'testString' + + # Invoke method + response = service.translate( + text, + model_id=model_id, + source=source, + target=target, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == ['testString'] + assert req_body['model_id'] == 'testString' + assert req_body['source'] == 'testString' + assert req_body['target'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_translate_empty(self): - check_empty_required_params(self, fake_response_TranslationResult_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/translate' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_translate_value_error(self): + """ + test_translate_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/translate') + mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.translate(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body.update({"text": [], "model_id": "string1", "source": "string1", "target": "string1", }) - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + text = ['testString'] + model_id = 'testString' + source = 'testString' + target = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.translate(**req_copy) + # endregion @@ -187,141 +211,137 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_identifiable_languages -#----------------------------------------------------------------------------- class TestListIdentifiableLanguages(): + """ + Test Class for list_identifiable_languages + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_identifiable_languages_response(self): - body = self.construct_full_body() - response = fake_response_IdentifiableLanguages_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_identifiable_languages_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_IdentifiableLanguages_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_identifiable_languages_all_params(self): + """ + list_identifiable_languages() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/identifiable_languages') + mock_response = '{"languages": [{"language": "language", "name": "name"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_identifiable_languages_empty(self): - check_empty_response(self) + # Invoke method + response = service.list_identifiable_languages() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/identifiable_languages' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_identifiable_languages_value_error(self): + """ + test_list_identifiable_languages_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/identifiable_languages') + mock_response = '{"languages": [{"language": "language", "name": "name"}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.list_identifiable_languages(**body) - return output - - def construct_full_body(self): - body = dict() - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for identify -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_identifiable_languages(**req_copy) + + + class TestIdentify(): + """ + Test Class for identify + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_identify_response(self): - body = self.construct_full_body() - response = fake_response_IdentifiedLanguages_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_identify_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_IdentifiedLanguages_json - send_request(self, body, response) + def test_identify_all_params(self): + """ + identify() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/identify') + mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + text = 'testString' + + # Invoke method + response = service.identify( + text, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + assert str(responses.calls[0].request.body, 'utf-8') == text + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_identify_empty(self): - check_empty_required_params(self, fake_response_IdentifiedLanguages_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/identify' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_identify_value_error(self): + """ + test_identify_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/identify') + mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.identify(**body) - return output - - def construct_full_body(self): - body = dict() - body['text'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['text'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + text = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.identify(**req_copy) + # endregion @@ -334,287 +354,356 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_models -#----------------------------------------------------------------------------- class TestListModels(): + """ + Test Class for list_models + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_models_response(self): - body = self.construct_full_body() - response = fake_response_TranslationModels_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_models_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TranslationModels_json - send_request(self, body, response) + def test_list_models_all_params(self): + """ + list_models() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/models') + mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + source = 'testString' + target = 'testString' + default = True + + # Invoke method + response = service.list_models( + source=source, + target=target, + default=default, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'source={}'.format(source) in query_string + assert 'target={}'.format(target) in query_string + assert 'default={}'.format('true' if default else 'false') in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_models_empty(self): - check_empty_response(self) + def test_list_models_required_params(self): + """ + test_list_models_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/models') + mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = service.list_models() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/models' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_models_value_error(self): + """ + test_list_models_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/models') + mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.list_models(**body) - return output - - def construct_full_body(self): - body = dict() - body['source'] = "string1" - body['target'] = "string1" - body['default'] = True - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_model -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_models(**req_copy) + + + class TestCreateModel(): + """ + Test Class for create_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_model_response(self): - body = self.construct_full_body() - response = fake_response_TranslationModel_json - send_request(self, body, response) + def test_create_model_all_params(self): + """ + create_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/models') + mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + base_model_id = 'testString' + forced_glossary = io.BytesIO(b'This is a mock file.').getvalue() + parallel_corpus = io.BytesIO(b'This is a mock file.').getvalue() + name = 'testString' + + # Invoke method + response = service.create_model( + base_model_id, + forced_glossary=forced_glossary, + parallel_corpus=parallel_corpus, + name=name, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'base_model_id={}'.format(base_model_id) in query_string + assert 'name={}'.format(name) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TranslationModel_json - send_request(self, body, response) + def test_create_model_required_params(self): + """ + test_create_model_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/models') + mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + base_model_id = 'testString' + + # Invoke method + response = service.create_model( + base_model_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'base_model_id={}'.format(base_model_id) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_model_empty(self): - check_empty_required_params(self, fake_response_TranslationModel_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/models' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_create_model_value_error(self): + """ + test_create_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/models') + mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.create_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['base_model_id'] = "string1" - body['forced_glossary'] = tempfile.NamedTemporaryFile() - body['parallel_corpus'] = tempfile.NamedTemporaryFile() - body['name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['base_model_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_model -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + base_model_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "base_model_id": base_model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_model(**req_copy) + + + class TestDeleteModel(): + """ + Test Class for delete_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_model_response(self): - body = self.construct_full_body() - response = fake_response_DeleteModelResult_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DeleteModelResult_json - send_request(self, body, response) + def test_delete_model_all_params(self): + """ + delete_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/models/testString') + mock_response = '{"status": "status"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Invoke method + response = service.delete_model( + model_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_model_empty(self): - check_empty_required_params(self, fake_response_DeleteModelResult_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/models/{0}'.format(body['model_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_model_value_error(self): + """ + test_delete_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/models/testString') + mock_response = '{"status": "status"}' responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.delete_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['model_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['model_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_model -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_model(**req_copy) + + + class TestGetModel(): + """ + Test Class for get_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_model_response(self): - body = self.construct_full_body() - response = fake_response_TranslationModel_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TranslationModel_json - send_request(self, body, response) + def test_get_model_all_params(self): + """ + get_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/models/testString') + mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Invoke method + response = service.get_model( + model_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_model_empty(self): - check_empty_required_params(self, fake_response_TranslationModel_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/models/{0}'.format(body['model_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_model_value_error(self): + """ + test_get_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/models/testString') + mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.get_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['model_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['model_id'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_model(**req_copy) + # endregion @@ -627,358 +716,412 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_documents -#----------------------------------------------------------------------------- class TestListDocuments(): + """ + Test Class for list_documents + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_documents_response(self): - body = self.construct_full_body() - response = fake_response_DocumentList_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_documents_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DocumentList_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_documents_all_params(self): + """ + list_documents() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents') + mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_documents_empty(self): - check_empty_response(self) + # Invoke method + response = service.list_documents() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/documents' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_documents_value_error(self): + """ + test_list_documents_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents') + mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.list_documents(**body) - return output - - def construct_full_body(self): - body = dict() - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for translate_document -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_documents(**req_copy) + + + class TestTranslateDocument(): + """ + Test Class for translate_document + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_translate_document_response(self): - body = self.construct_full_body() - response = fake_response_DocumentStatus_json - send_request(self, body, response) + def test_translate_document_all_params(self): + """ + translate_document() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents') + mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/powerpoint' + model_id = 'testString' + source = 'testString' + target = 'testString' + document_id = 'testString' + + # Invoke method + response = service.translate_document( + file, + filename=filename, + file_content_type=file_content_type, + model_id=model_id, + source=source, + target=target, + document_id=document_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_translate_document_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DocumentStatus_json - send_request(self, body, response) + def test_translate_document_required_params(self): + """ + test_translate_document_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents') + mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + + # Invoke method + response = service.translate_document( + file, + filename=filename, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_translate_document_empty(self): - check_empty_required_params(self, fake_response_DocumentStatus_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/documents' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_translate_document_value_error(self): + """ + test_translate_document_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents') + mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - content_type='application/json') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.translate_document(**body) - return output - - def construct_full_body(self): - body = dict() - body['file'] = tempfile.NamedTemporaryFile() - body['filename'] = "string1" - body['file_content_type'] = "string1" - body['model_id'] = "string1" - body['source'] = "string1" - body['target'] = "string1" - body['document_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['file'] = tempfile.NamedTemporaryFile() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_document_status -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "file": file, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.translate_document(**req_copy) + + + class TestGetDocumentStatus(): + """ + Test Class for get_document_status + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_document_status_response(self): - body = self.construct_full_body() - response = fake_response_DocumentStatus_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_document_status_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DocumentStatus_json - send_request(self, body, response) + def test_get_document_status_all_params(self): + """ + get_document_status() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents/testString') + mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + document_id = 'testString' + + # Invoke method + response = service.get_document_status( + document_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_document_status_empty(self): - check_empty_required_params(self, fake_response_DocumentStatus_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/documents/{0}'.format(body['document_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_document_status_value_error(self): + """ + test_get_document_status_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents/testString') + mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.get_document_status(**body) - return output - - def construct_full_body(self): - body = dict() - body['document_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['document_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_document -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + document_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "document_id": document_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_document_status(**req_copy) + + + class TestDeleteDocument(): + """ + Test Class for delete_document + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_document_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_document_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_document_all_params(self): + """ + delete_document() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + document_id = 'testString' + + # Invoke method + response = service.delete_document( + document_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_document_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 = '/v3/documents/{0}'.format(body['document_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_document_value_error(self): + """ + test_delete_document_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents/testString') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.delete_document(**body) - return output - - def construct_full_body(self): - body = dict() - body['document_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['document_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_translated_document -#----------------------------------------------------------------------------- + url, + status=204) + + # Set up parameter values + document_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "document_id": document_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_document(**req_copy) + + + class TestGetTranslatedDocument(): + """ + Test Class for get_translated_document + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_translated_document_response(self): - body = self.construct_full_body() - response = fake_response_BinaryIO_json - send_request(self, body, response) + def test_get_translated_document_all_params(self): + """ + get_translated_document() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents/testString/translated_document') + mock_response = 'This is a mock binary response.' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/powerpoint', + status=200) + + # Set up parameter values + document_id = 'testString' + accept = 'application/powerpoint' + + # Invoke method + response = service.get_translated_document( + document_id, + accept=accept, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_translated_document_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_BinaryIO_json - send_request(self, body, response) + def test_get_translated_document_required_params(self): + """ + test_get_translated_document_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents/testString/translated_document') + mock_response = 'This is a mock binary response.' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/powerpoint', + status=200) + + # Set up parameter values + document_id = 'testString' + + # Invoke method + response = service.get_translated_document( + document_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_translated_document_empty(self): - check_empty_required_params(self, fake_response_BinaryIO_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/documents/{0}/translated_document'.format(body['document_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_translated_document_value_error(self): + """ + test_get_translated_document_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/documents/testString/translated_document') + mock_response = 'This is a mock binary response.' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version='2018-05-01', - ) - service.set_service_url(base_url) - output = service.get_translated_document(**body) - return output - - def construct_full_body(self): - body = dict() - body['document_id'] = "string1" - body['accept'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['document_id'] = "string1" - return body + url, + body=mock_response, + content_type='application/powerpoint', + status=200) + + # Set up parameter values + document_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "document_id": document_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_translated_document(**req_copy) + # endregion @@ -987,79 +1130,483 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestDeleteModelResult(): + """ + Test Class for DeleteModelResult + """ + + def test_delete_model_result_serialization(self): + """ + Test serialization/deserialization for DeleteModelResult + """ + + # Construct a json representation of a DeleteModelResult model + delete_model_result_model_json = {} + delete_model_result_model_json['status'] = 'testString' + + # Construct a model instance of DeleteModelResult by calling from_dict on the json representation + delete_model_result_model = DeleteModelResult.from_dict(delete_model_result_model_json) + assert delete_model_result_model != False + + # Construct a model instance of DeleteModelResult by calling from_dict on the json representation + delete_model_result_model_dict = DeleteModelResult.from_dict(delete_model_result_model_json).__dict__ + delete_model_result_model2 = DeleteModelResult(**delete_model_result_model_dict) + + # Verify the model instances are equivalent + assert delete_model_result_model == delete_model_result_model2 + + # Convert model instance back to dict and verify no loss of data + delete_model_result_model_json2 = delete_model_result_model.to_dict() + assert delete_model_result_model_json2 == delete_model_result_model_json + +class TestDocumentList(): + """ + Test Class for DocumentList + """ + + def test_document_list_serialization(self): + """ + Test serialization/deserialization for DocumentList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_status_model = {} # DocumentStatus + document_status_model['document_id'] = 'testString' + document_status_model['filename'] = 'testString' + document_status_model['status'] = 'processing' + document_status_model['model_id'] = 'testString' + document_status_model['base_model_id'] = 'testString' + document_status_model['source'] = 'testString' + document_status_model['detected_language_confidence'] = 0 + document_status_model['target'] = 'testString' + document_status_model['created'] = '2020-01-28T18:40:40.123456Z' + document_status_model['completed'] = '2020-01-28T18:40:40.123456Z' + document_status_model['word_count'] = 38 + document_status_model['character_count'] = 38 + + # Construct a json representation of a DocumentList model + document_list_model_json = {} + document_list_model_json['documents'] = [document_status_model] + + # Construct a model instance of DocumentList by calling from_dict on the json representation + document_list_model = DocumentList.from_dict(document_list_model_json) + assert document_list_model != False + + # Construct a model instance of DocumentList by calling from_dict on the json representation + document_list_model_dict = DocumentList.from_dict(document_list_model_json).__dict__ + document_list_model2 = DocumentList(**document_list_model_dict) + + # Verify the model instances are equivalent + assert document_list_model == document_list_model2 + + # Convert model instance back to dict and verify no loss of data + document_list_model_json2 = document_list_model.to_dict() + assert document_list_model_json2 == document_list_model_json + +class TestDocumentStatus(): + """ + Test Class for DocumentStatus + """ + + def test_document_status_serialization(self): + """ + Test serialization/deserialization for DocumentStatus + """ + + # Construct a json representation of a DocumentStatus model + document_status_model_json = {} + document_status_model_json['document_id'] = 'testString' + document_status_model_json['filename'] = 'testString' + document_status_model_json['status'] = 'processing' + document_status_model_json['model_id'] = 'testString' + document_status_model_json['base_model_id'] = 'testString' + document_status_model_json['source'] = 'testString' + document_status_model_json['detected_language_confidence'] = 0 + document_status_model_json['target'] = 'testString' + document_status_model_json['created'] = '2020-01-28T18:40:40.123456Z' + document_status_model_json['completed'] = '2020-01-28T18:40:40.123456Z' + document_status_model_json['word_count'] = 38 + document_status_model_json['character_count'] = 38 + + # Construct a model instance of DocumentStatus by calling from_dict on the json representation + document_status_model = DocumentStatus.from_dict(document_status_model_json) + assert document_status_model != False + + # Construct a model instance of DocumentStatus by calling from_dict on the json representation + document_status_model_dict = DocumentStatus.from_dict(document_status_model_json).__dict__ + document_status_model2 = DocumentStatus(**document_status_model_dict) + + # Verify the model instances are equivalent + assert document_status_model == document_status_model2 + + # Convert model instance back to dict and verify no loss of data + document_status_model_json2 = document_status_model.to_dict() + assert document_status_model_json2 == document_status_model_json + +class TestIdentifiableLanguage(): + """ + Test Class for IdentifiableLanguage + """ + + def test_identifiable_language_serialization(self): + """ + Test serialization/deserialization for IdentifiableLanguage + """ + + # Construct a json representation of a IdentifiableLanguage model + identifiable_language_model_json = {} + identifiable_language_model_json['language'] = 'testString' + identifiable_language_model_json['name'] = 'testString' - Args: - obj: The generated test function + # Construct a model instance of IdentifiableLanguage by calling from_dict on the json representation + identifiable_language_model = IdentifiableLanguage.from_dict(identifiable_language_model_json) + assert identifiable_language_model != False + # Construct a model instance of IdentifiableLanguage by calling from_dict on the json representation + identifiable_language_model_dict = IdentifiableLanguage.from_dict(identifiable_language_model_json).__dict__ + identifiable_language_model2 = IdentifiableLanguage(**identifiable_language_model_dict) + + # Verify the model instances are equivalent + assert identifiable_language_model == identifiable_language_model2 + + # Convert model instance back to dict and verify no loss of data + identifiable_language_model_json2 = identifiable_language_model.to_dict() + assert identifiable_language_model_json2 == identifiable_language_model_json + +class TestIdentifiableLanguages(): """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error + Test Class for IdentifiableLanguages + """ + + def test_identifiable_languages_serialization(self): + """ + Test serialization/deserialization for IdentifiableLanguages + """ + + # Construct dict forms of any model objects needed in order to build this model. + + identifiable_language_model = {} # IdentifiableLanguage + identifiable_language_model['language'] = 'testString' + identifiable_language_model['name'] = 'testString' + + # Construct a json representation of a IdentifiableLanguages model + identifiable_languages_model_json = {} + identifiable_languages_model_json['languages'] = [identifiable_language_model] + + # Construct a model instance of IdentifiableLanguages by calling from_dict on the json representation + identifiable_languages_model = IdentifiableLanguages.from_dict(identifiable_languages_model_json) + assert identifiable_languages_model != False -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data + # Construct a model instance of IdentifiableLanguages by calling from_dict on the json representation + identifiable_languages_model_dict = IdentifiableLanguages.from_dict(identifiable_languages_model_json).__dict__ + identifiable_languages_model2 = IdentifiableLanguages(**identifiable_languages_model_dict) - Args: - obj: The generated test function + # Verify the model instances are equivalent + assert identifiable_languages_model == identifiable_languages_model2 + # Convert model instance back to dict and verify no loss of data + identifiable_languages_model_json2 = identifiable_languages_model.to_dict() + assert identifiable_languages_model_json2 == identifiable_languages_model_json + +class TestIdentifiedLanguage(): + """ + Test Class for IdentifiedLanguage """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request + def test_identified_language_serialization(self): + """ + Test serialization/deserialization for IdentifiedLanguage + """ + + # Construct a json representation of a IdentifiedLanguage model + identified_language_model_json = {} + identified_language_model_json['language'] = 'testString' + identified_language_model_json['confidence'] = 0 + + # Construct a model instance of IdentifiedLanguage by calling from_dict on the json representation + identified_language_model = IdentifiedLanguage.from_dict(identified_language_model_json) + assert identified_language_model != False - Args: - obj: The generated test function + # Construct a model instance of IdentifiedLanguage by calling from_dict on the json representation + identified_language_model_dict = IdentifiedLanguage.from_dict(identified_language_model_json).__dict__ + identified_language_model2 = IdentifiedLanguage(**identified_language_model_dict) + # Verify the model instances are equivalent + assert identified_language_model == identified_language_model2 + + # Convert model instance back to dict and verify no loss of data + identified_language_model_json2 = identified_language_model.to_dict() + assert identified_language_model_json2 == identified_language_model_json + +class TestIdentifiedLanguages(): """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) + Test Class for IdentifiedLanguages + """ + + def test_identified_languages_serialization(self): + """ + Test serialization/deserialization for IdentifiedLanguages + """ -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response + # Construct dict forms of any model objects needed in order to build this model. - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string + identified_language_model = {} # IdentifiedLanguage + identified_language_model['language'] = 'testString' + identified_language_model['confidence'] = 0 + # Construct a json representation of a IdentifiedLanguages model + identified_languages_model_json = {} + identified_languages_model_json['languages'] = [identified_language_model] + + # Construct a model instance of IdentifiedLanguages by calling from_dict on the json representation + identified_languages_model = IdentifiedLanguages.from_dict(identified_languages_model_json) + assert identified_languages_model != False + + # Construct a model instance of IdentifiedLanguages by calling from_dict on the json representation + identified_languages_model_dict = IdentifiedLanguages.from_dict(identified_languages_model_json).__dict__ + identified_languages_model2 = IdentifiedLanguages(**identified_languages_model_dict) + + # Verify the model instances are equivalent + assert identified_languages_model == identified_languages_model2 + + # Convert model instance back to dict and verify no loss of data + identified_languages_model_json2 = identified_languages_model.to_dict() + assert identified_languages_model_json2 == identified_languages_model_json + +class TestLanguage(): + """ + Test Class for Language + """ + + def test_language_serialization(self): + """ + Test serialization/deserialization for Language + """ + + # Construct a json representation of a Language model + language_model_json = {} + language_model_json['language'] = 'testString' + language_model_json['language_name'] = 'testString' + language_model_json['native_language_name'] = 'testString' + language_model_json['country_code'] = 'testString' + language_model_json['words_separated'] = True + language_model_json['direction'] = 'testString' + language_model_json['supported_as_source'] = True + language_model_json['supported_as_target'] = True + language_model_json['identifiable'] = True + + # Construct a model instance of Language by calling from_dict on the json representation + language_model = Language.from_dict(language_model_json) + assert language_model != False + + # Construct a model instance of Language by calling from_dict on the json representation + language_model_dict = Language.from_dict(language_model_json).__dict__ + language_model2 = Language(**language_model_dict) + + # Verify the model instances are equivalent + assert language_model == language_model2 + + # Convert model instance back to dict and verify no loss of data + language_model_json2 = language_model.to_dict() + assert language_model_json2 == language_model_json + +class TestLanguages(): """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response - -#################### -## Mock Responses ## -#################### - -fake_response__json = None -fake_response_Languages_json = """{"languages": []}""" -fake_response_TranslationResult_json = """{"word_count": 10, "character_count": 15, "detected_language": "fake_detected_language", "detected_language_confidence": 28, "translations": []}""" -fake_response_IdentifiableLanguages_json = """{"languages": []}""" -fake_response_IdentifiedLanguages_json = """{"languages": []}""" -fake_response_TranslationModels_json = """{"models": []}""" -fake_response_TranslationModel_json = """{"model_id": "fake_model_id", "name": "fake_name", "source": "fake_source", "target": "fake_target", "base_model_id": "fake_base_model_id", "domain": "fake_domain", "customizable": true, "default_model": false, "owner": "fake_owner", "status": "fake_status"}""" -fake_response_DeleteModelResult_json = """{"status": "fake_status"}""" -fake_response_TranslationModel_json = """{"model_id": "fake_model_id", "name": "fake_name", "source": "fake_source", "target": "fake_target", "base_model_id": "fake_base_model_id", "domain": "fake_domain", "customizable": true, "default_model": false, "owner": "fake_owner", "status": "fake_status"}""" -fake_response_DocumentList_json = """{"documents": []}""" -fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "filename": "fake_filename", "status": "fake_status", "model_id": "fake_model_id", "base_model_id": "fake_base_model_id", "source": "fake_source", "detected_language_confidence": 28, "target": "fake_target", "created": "2017-05-16T13:56:54.957Z", "completed": "2017-05-16T13:56:54.957Z", "word_count": 10, "character_count": 15}""" -fake_response_DocumentStatus_json = """{"document_id": "fake_document_id", "filename": "fake_filename", "status": "fake_status", "model_id": "fake_model_id", "base_model_id": "fake_base_model_id", "source": "fake_source", "detected_language_confidence": 28, "target": "fake_target", "created": "2017-05-16T13:56:54.957Z", "completed": "2017-05-16T13:56:54.957Z", "word_count": 10, "character_count": 15}""" -fake_response_BinaryIO_json = """Contents of response byte-stream...""" + Test Class for Languages + """ + + def test_languages_serialization(self): + """ + Test serialization/deserialization for Languages + """ + + # Construct dict forms of any model objects needed in order to build this model. + + language_model = {} # Language + language_model['language'] = 'testString' + language_model['language_name'] = 'testString' + language_model['native_language_name'] = 'testString' + language_model['country_code'] = 'testString' + language_model['words_separated'] = True + language_model['direction'] = 'testString' + language_model['supported_as_source'] = True + language_model['supported_as_target'] = True + language_model['identifiable'] = True + + # Construct a json representation of a Languages model + languages_model_json = {} + languages_model_json['languages'] = [language_model] + + # Construct a model instance of Languages by calling from_dict on the json representation + languages_model = Languages.from_dict(languages_model_json) + assert languages_model != False + + # Construct a model instance of Languages by calling from_dict on the json representation + languages_model_dict = Languages.from_dict(languages_model_json).__dict__ + languages_model2 = Languages(**languages_model_dict) + + # Verify the model instances are equivalent + assert languages_model == languages_model2 + + # Convert model instance back to dict and verify no loss of data + languages_model_json2 = languages_model.to_dict() + assert languages_model_json2 == languages_model_json + +class TestTranslation(): + """ + Test Class for Translation + """ + + def test_translation_serialization(self): + """ + Test serialization/deserialization for Translation + """ + + # Construct a json representation of a Translation model + translation_model_json = {} + translation_model_json['translation'] = 'testString' + + # Construct a model instance of Translation by calling from_dict on the json representation + translation_model = Translation.from_dict(translation_model_json) + assert translation_model != False + + # Construct a model instance of Translation by calling from_dict on the json representation + translation_model_dict = Translation.from_dict(translation_model_json).__dict__ + translation_model2 = Translation(**translation_model_dict) + + # Verify the model instances are equivalent + assert translation_model == translation_model2 + + # Convert model instance back to dict and verify no loss of data + translation_model_json2 = translation_model.to_dict() + assert translation_model_json2 == translation_model_json + +class TestTranslationModel(): + """ + Test Class for TranslationModel + """ + + def test_translation_model_serialization(self): + """ + Test serialization/deserialization for TranslationModel + """ + + # Construct a json representation of a TranslationModel model + translation_model_model_json = {} + translation_model_model_json['model_id'] = 'testString' + translation_model_model_json['name'] = 'testString' + translation_model_model_json['source'] = 'testString' + translation_model_model_json['target'] = 'testString' + translation_model_model_json['base_model_id'] = 'testString' + translation_model_model_json['domain'] = 'testString' + translation_model_model_json['customizable'] = True + translation_model_model_json['default_model'] = True + translation_model_model_json['owner'] = 'testString' + translation_model_model_json['status'] = 'uploading' + + # Construct a model instance of TranslationModel by calling from_dict on the json representation + translation_model_model = TranslationModel.from_dict(translation_model_model_json) + assert translation_model_model != False + + # Construct a model instance of TranslationModel by calling from_dict on the json representation + translation_model_model_dict = TranslationModel.from_dict(translation_model_model_json).__dict__ + translation_model_model2 = TranslationModel(**translation_model_model_dict) + + # Verify the model instances are equivalent + assert translation_model_model == translation_model_model2 + + # Convert model instance back to dict and verify no loss of data + translation_model_model_json2 = translation_model_model.to_dict() + assert translation_model_model_json2 == translation_model_model_json + +class TestTranslationModels(): + """ + Test Class for TranslationModels + """ + + def test_translation_models_serialization(self): + """ + Test serialization/deserialization for TranslationModels + """ + + # Construct dict forms of any model objects needed in order to build this model. + + translation_model_model = {} # TranslationModel + translation_model_model['model_id'] = 'testString' + translation_model_model['name'] = 'testString' + translation_model_model['source'] = 'testString' + translation_model_model['target'] = 'testString' + translation_model_model['base_model_id'] = 'testString' + translation_model_model['domain'] = 'testString' + translation_model_model['customizable'] = True + translation_model_model['default_model'] = True + translation_model_model['owner'] = 'testString' + translation_model_model['status'] = 'uploading' + + # Construct a json representation of a TranslationModels model + translation_models_model_json = {} + translation_models_model_json['models'] = [translation_model_model] + + # Construct a model instance of TranslationModels by calling from_dict on the json representation + translation_models_model = TranslationModels.from_dict(translation_models_model_json) + assert translation_models_model != False + + # Construct a model instance of TranslationModels by calling from_dict on the json representation + translation_models_model_dict = TranslationModels.from_dict(translation_models_model_json).__dict__ + translation_models_model2 = TranslationModels(**translation_models_model_dict) + + # Verify the model instances are equivalent + assert translation_models_model == translation_models_model2 + + # Convert model instance back to dict and verify no loss of data + translation_models_model_json2 = translation_models_model.to_dict() + assert translation_models_model_json2 == translation_models_model_json + +class TestTranslationResult(): + """ + Test Class for TranslationResult + """ + + def test_translation_result_serialization(self): + """ + Test serialization/deserialization for TranslationResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + translation_model = {} # Translation + translation_model['translation'] = 'testString' + + # Construct a json representation of a TranslationResult model + translation_result_model_json = {} + translation_result_model_json['word_count'] = 38 + translation_result_model_json['character_count'] = 38 + translation_result_model_json['detected_language'] = 'testString' + translation_result_model_json['detected_language_confidence'] = 0 + translation_result_model_json['translations'] = [translation_model] + + # Construct a model instance of TranslationResult by calling from_dict on the json representation + translation_result_model = TranslationResult.from_dict(translation_result_model_json) + assert translation_result_model != False + + # Construct a model instance of TranslationResult by calling from_dict on the json representation + translation_result_model_dict = TranslationResult.from_dict(translation_result_model_json).__dict__ + translation_result_model2 = TranslationResult(**translation_result_model_dict) + + # Verify the model instances are equivalent + assert translation_result_model == translation_result_model2 + + # Convert model instance back to dict and verify no loss of data + translation_result_model_json2 = translation_result_model.to_dict() + assert translation_result_model_json2 == translation_result_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index 8485c8f02..d68cb260f 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -13,163 +13,195 @@ # See the License for the specific language governing permissions and # limitations under the License. -from datetime import datetime +""" +Unit Tests for NaturalLanguageClassifierV1 +""" + +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect +import io import json import pytest +import re import responses import tempfile -import ibm_watson.natural_language_classifier_v1 +import urllib from ibm_watson.natural_language_classifier_v1 import * + +service = NaturalLanguageClassifierV1( + authenticator=NoAuthAuthenticator() + ) + base_url = 'https://api.us-south.natural-language-classifier.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: ClassifyText ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for classify -#----------------------------------------------------------------------------- class TestClassify(): + """ + Test Class for classify + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_classify_response(self): - body = self.construct_full_body() - response = fake_response_Classification_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_classify_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Classification_json - send_request(self, body, response) + def test_classify_all_params(self): + """ + classify() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/classifiers/testString/classify') + mock_response = '{"classifier_id": "classifier_id", "url": "url", "text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + classifier_id = 'testString' + text = 'testString' + + # Invoke method + response = service.classify( + classifier_id, + text, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_classify_empty(self): - check_empty_required_params(self, fake_response_Classification_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/classifiers/{0}/classify'.format(body['classifier_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_classify_value_error(self): + """ + test_classify_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/classifiers/testString/classify') + mock_response = '{"classifier_id": "classifier_id", "url": "url", "text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.classify(**body) - return output - - def construct_full_body(self): - body = dict() - body['classifier_id'] = "string1" - body.update({"text": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['classifier_id'] = "string1" - body.update({"text": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for classify_collection -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + classifier_id = 'testString' + text = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "classifier_id": classifier_id, + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.classify(**req_copy) + + + class TestClassifyCollection(): + """ + Test Class for classify_collection + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_classify_collection_response(self): - body = self.construct_full_body() - response = fake_response_ClassificationCollection_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_classify_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ClassificationCollection_json - send_request(self, body, response) + def test_classify_collection_all_params(self): + """ + classify_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/classifiers/testString/classify_collection') + mock_response = '{"classifier_id": "classifier_id", "url": "url", "collection": [{"text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ClassifyInput model + classify_input_model = {} + classify_input_model['text'] = 'How hot will it be today?' + + # Set up parameter values + classifier_id = 'testString' + collection = [classify_input_model] + + # Invoke method + response = service.classify_collection( + classifier_id, + collection, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['collection'] == [classify_input_model] + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_classify_collection_empty(self): - check_empty_required_params(self, fake_response_ClassificationCollection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/classifiers/{0}/classify_collection'.format(body['classifier_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_classify_collection_value_error(self): + """ + test_classify_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/classifiers/testString/classify_collection') + mock_response = '{"classifier_id": "classifier_id", "url": "url", "collection": [{"text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.classify_collection(**body) - return output - - def construct_full_body(self): - body = dict() - body['classifier_id'] = "string1" - body.update({"collection": [], }) - return body - - def construct_required_body(self): - body = dict() - body['classifier_id'] = "string1" - body.update({"collection": [], }) - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ClassifyInput model + classify_input_model = {} + classify_input_model['text'] = 'How hot will it be today?' + + # Set up parameter values + classifier_id = 'testString' + collection = [classify_input_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "classifier_id": classifier_id, + "collection": collection, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.classify_collection(**req_copy) + # endregion @@ -182,279 +214,249 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_classifier -#----------------------------------------------------------------------------- class TestCreateClassifier(): + """ + Test Class for create_classifier + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_classifier_response(self): - body = self.construct_full_body() - response = fake_response_Classifier_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_classifier_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Classifier_json - send_request(self, body, response) + def test_create_classifier_all_params(self): + """ + create_classifier() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/classifiers') + mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00", "status_description": "status_description", "language": "language"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + training_metadata = io.BytesIO(b'This is a mock file.').getvalue() + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = service.create_classifier( + training_metadata, + training_data, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_classifier_empty(self): - check_empty_required_params(self, fake_response_Classifier_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/classifiers' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_create_classifier_value_error(self): + """ + test_create_classifier_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/classifiers') + mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00", "status_description": "status_description", "language": "language"}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.create_classifier(**body) - return output - - def construct_full_body(self): - body = dict() - body['training_metadata'] = tempfile.NamedTemporaryFile() - body['training_data'] = tempfile.NamedTemporaryFile() - return body - - def construct_required_body(self): - body = dict() - body['training_metadata'] = tempfile.NamedTemporaryFile() - body['training_data'] = tempfile.NamedTemporaryFile() - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_classifiers -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + training_metadata = io.BytesIO(b'This is a mock file.').getvalue() + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "training_metadata": training_metadata, + "training_data": training_data, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_classifier(**req_copy) + + + class TestListClassifiers(): + """ + Test Class for list_classifiers + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_classifiers_response(self): - body = self.construct_full_body() - response = fake_response_ClassifierList_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_classifiers_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ClassifierList_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_classifiers_all_params(self): + """ + list_classifiers() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/classifiers') + mock_response = '{"classifiers": [{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00", "status_description": "status_description", "language": "language"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_classifiers_empty(self): - check_empty_response(self) + # Invoke method + response = service.list_classifiers() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/classifiers' - 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 = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.list_classifiers(**body) - return output - - def construct_full_body(self): - body = dict() - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_classifier -#----------------------------------------------------------------------------- class TestGetClassifier(): + """ + Test Class for get_classifier + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_classifier_response(self): - body = self.construct_full_body() - response = fake_response_Classifier_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_classifier_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Classifier_json - send_request(self, body, response) + def test_get_classifier_all_params(self): + """ + get_classifier() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/classifiers/testString') + mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00", "status_description": "status_description", "language": "language"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Invoke method + response = service.get_classifier( + classifier_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_classifier_empty(self): - check_empty_required_params(self, fake_response_Classifier_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/classifiers/{0}'.format(body['classifier_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_classifier_value_error(self): + """ + test_get_classifier_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/classifiers/testString') + mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00", "status_description": "status_description", "language": "language"}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_classifier(**body) - return output - - def construct_full_body(self): - body = dict() - body['classifier_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['classifier_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_classifier -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "classifier_id": classifier_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_classifier(**req_copy) + + + class TestDeleteClassifier(): + """ + Test Class for delete_classifier + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_classifier_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_classifier_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_classifier_all_params(self): + """ + delete_classifier() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/classifiers/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Invoke method + response = service.delete_classifier( + classifier_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_classifier_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 = '/v1/classifiers/{0}'.format(body['classifier_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_classifier_value_error(self): + """ + test_delete_classifier_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/classifiers/testString') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_classifier(**body) - return output - - def construct_full_body(self): - body = dict() - body['classifier_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['classifier_id'] = "string1" - return body + url, + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "classifier_id": classifier_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_classifier(**req_copy) + # endregion @@ -463,72 +465,264 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestClassification(): + """ + Test Class for Classification + """ + + def test_classification_serialization(self): + """ + Test serialization/deserialization for Classification + """ + + # Construct dict forms of any model objects needed in order to build this model. + + classified_class_model = {} # ClassifiedClass + classified_class_model['confidence'] = 72.5 + classified_class_model['class_name'] = 'testString' + + # Construct a json representation of a Classification model + classification_model_json = {} + classification_model_json['classifier_id'] = 'testString' + classification_model_json['url'] = 'testString' + classification_model_json['text'] = 'testString' + classification_model_json['top_class'] = 'testString' + classification_model_json['classes'] = [classified_class_model] + + # Construct a model instance of Classification by calling from_dict on the json representation + classification_model = Classification.from_dict(classification_model_json) + assert classification_model != False - Args: - obj: The generated test function + # Construct a model instance of Classification by calling from_dict on the json representation + classification_model_dict = Classification.from_dict(classification_model_json).__dict__ + classification_model2 = Classification(**classification_model_dict) + # Verify the model instances are equivalent + assert classification_model == classification_model2 + + # Convert model instance back to dict and verify no loss of data + classification_model_json2 = classification_model.to_dict() + assert classification_model_json2 == classification_model_json + +class TestClassificationCollection(): + """ + Test Class for ClassificationCollection + """ + + def test_classification_collection_serialization(self): + """ + Test serialization/deserialization for ClassificationCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + classified_class_model = {} # ClassifiedClass + classified_class_model['confidence'] = 72.5 + classified_class_model['class_name'] = 'testString' + + collection_item_model = {} # CollectionItem + collection_item_model['text'] = 'testString' + collection_item_model['top_class'] = 'testString' + collection_item_model['classes'] = [classified_class_model] + + # Construct a json representation of a ClassificationCollection model + classification_collection_model_json = {} + classification_collection_model_json['classifier_id'] = 'testString' + classification_collection_model_json['url'] = 'testString' + classification_collection_model_json['collection'] = [collection_item_model] + + # Construct a model instance of ClassificationCollection by calling from_dict on the json representation + classification_collection_model = ClassificationCollection.from_dict(classification_collection_model_json) + assert classification_collection_model != False + + # Construct a model instance of ClassificationCollection by calling from_dict on the json representation + classification_collection_model_dict = ClassificationCollection.from_dict(classification_collection_model_json).__dict__ + classification_collection_model2 = ClassificationCollection(**classification_collection_model_dict) + + # Verify the model instances are equivalent + assert classification_collection_model == classification_collection_model2 + + # Convert model instance back to dict and verify no loss of data + classification_collection_model_json2 = classification_collection_model.to_dict() + assert classification_collection_model_json2 == classification_collection_model_json + +class TestClassifiedClass(): """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error + Test Class for ClassifiedClass + """ + + def test_classified_class_serialization(self): + """ + Test serialization/deserialization for ClassifiedClass + """ -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data + # Construct a json representation of a ClassifiedClass model + classified_class_model_json = {} + classified_class_model_json['confidence'] = 72.5 + classified_class_model_json['class_name'] = 'testString' - Args: - obj: The generated test function + # Construct a model instance of ClassifiedClass by calling from_dict on the json representation + classified_class_model = ClassifiedClass.from_dict(classified_class_model_json) + assert classified_class_model != False + # Construct a model instance of ClassifiedClass by calling from_dict on the json representation + classified_class_model_dict = ClassifiedClass.from_dict(classified_class_model_json).__dict__ + classified_class_model2 = ClassifiedClass(**classified_class_model_dict) + + # Verify the model instances are equivalent + assert classified_class_model == classified_class_model2 + + # Convert model instance back to dict and verify no loss of data + classified_class_model_json2 = classified_class_model.to_dict() + assert classified_class_model_json2 == classified_class_model_json + +class TestClassifier(): + """ + Test Class for Classifier """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request + def test_classifier_serialization(self): + """ + Test serialization/deserialization for Classifier + """ + + # Construct a json representation of a Classifier model + classifier_model_json = {} + classifier_model_json['name'] = 'testString' + classifier_model_json['url'] = 'testString' + classifier_model_json['status'] = 'Non Existent' + classifier_model_json['classifier_id'] = 'testString' + classifier_model_json['created'] = '2020-01-28T18:40:40.123456Z' + classifier_model_json['status_description'] = 'testString' + classifier_model_json['language'] = 'testString' + + # Construct a model instance of Classifier by calling from_dict on the json representation + classifier_model = Classifier.from_dict(classifier_model_json) + assert classifier_model != False + + # Construct a model instance of Classifier by calling from_dict on the json representation + classifier_model_dict = Classifier.from_dict(classifier_model_json).__dict__ + classifier_model2 = Classifier(**classifier_model_dict) + + # Verify the model instances are equivalent + assert classifier_model == classifier_model2 + + # Convert model instance back to dict and verify no loss of data + classifier_model_json2 = classifier_model.to_dict() + assert classifier_model_json2 == classifier_model_json + +class TestClassifierList(): + """ + Test Class for ClassifierList + """ + + def test_classifier_list_serialization(self): + """ + Test serialization/deserialization for ClassifierList + """ + + # Construct dict forms of any model objects needed in order to build this model. - Args: - obj: The generated test function + classifier_model = {} # Classifier + classifier_model['name'] = 'testString' + classifier_model['url'] = 'testString' + classifier_model['status'] = 'Non Existent' + classifier_model['classifier_id'] = 'testString' + classifier_model['created'] = '2020-01-28T18:40:40.123456Z' + classifier_model['status_description'] = 'testString' + classifier_model['language'] = 'testString' + # Construct a json representation of a ClassifierList model + classifier_list_model_json = {} + classifier_list_model_json['classifiers'] = [classifier_model] + + # Construct a model instance of ClassifierList by calling from_dict on the json representation + classifier_list_model = ClassifierList.from_dict(classifier_list_model_json) + assert classifier_list_model != False + + # Construct a model instance of ClassifierList by calling from_dict on the json representation + classifier_list_model_dict = ClassifierList.from_dict(classifier_list_model_json).__dict__ + classifier_list_model2 = ClassifierList(**classifier_list_model_dict) + + # Verify the model instances are equivalent + assert classifier_list_model == classifier_list_model2 + + # Convert model instance back to dict and verify no loss of data + classifier_list_model_json2 = classifier_list_model.to_dict() + assert classifier_list_model_json2 == classifier_list_model_json + +class TestClassifyInput(): + """ + Test Class for ClassifyInput """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response + def test_classify_input_serialization(self): + """ + Test serialization/deserialization for ClassifyInput + """ + + # Construct a json representation of a ClassifyInput model + classify_input_model_json = {} + classify_input_model_json['text'] = 'testString' + + # Construct a model instance of ClassifyInput by calling from_dict on the json representation + classify_input_model = ClassifyInput.from_dict(classify_input_model_json) + assert classify_input_model != False - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string + # Construct a model instance of ClassifyInput by calling from_dict on the json representation + classify_input_model_dict = ClassifyInput.from_dict(classify_input_model_json).__dict__ + classify_input_model2 = ClassifyInput(**classify_input_model_dict) + # Verify the model instances are equivalent + assert classify_input_model == classify_input_model2 + + # Convert model instance back to dict and verify no loss of data + classify_input_model_json2 = classify_input_model.to_dict() + assert classify_input_model_json2 == classify_input_model_json + +class TestCollectionItem(): """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response - -#################### -## Mock Responses ## -#################### - -fake_response__json = None -fake_response_Classification_json = """{"classifier_id": "fake_classifier_id", "url": "fake_url", "text": "fake_text", "top_class": "fake_top_class", "classes": []}""" -fake_response_ClassificationCollection_json = """{"classifier_id": "fake_classifier_id", "url": "fake_url", "collection": []}""" -fake_response_Classifier_json = """{"name": "fake_name", "url": "fake_url", "status": "fake_status", "classifier_id": "fake_classifier_id", "created": "2017-05-16T13:56:54.957Z", "status_description": "fake_status_description", "language": "fake_language"}""" -fake_response_ClassifierList_json = """{"classifiers": []}""" -fake_response_Classifier_json = """{"name": "fake_name", "url": "fake_url", "status": "fake_status", "classifier_id": "fake_classifier_id", "created": "2017-05-16T13:56:54.957Z", "status_description": "fake_status_description", "language": "fake_language"}""" + Test Class for CollectionItem + """ + + def test_collection_item_serialization(self): + """ + Test serialization/deserialization for CollectionItem + """ + + # Construct dict forms of any model objects needed in order to build this model. + + classified_class_model = {} # ClassifiedClass + classified_class_model['confidence'] = 72.5 + classified_class_model['class_name'] = 'testString' + + # Construct a json representation of a CollectionItem model + collection_item_model_json = {} + collection_item_model_json['text'] = 'testString' + collection_item_model_json['top_class'] = 'testString' + collection_item_model_json['classes'] = [classified_class_model] + + # Construct a model instance of CollectionItem by calling from_dict on the json representation + collection_item_model = CollectionItem.from_dict(collection_item_model_json) + assert collection_item_model != False + + # Construct a model instance of CollectionItem by calling from_dict on the json representation + collection_item_model_dict = CollectionItem.from_dict(collection_item_model_json).__dict__ + collection_item_model2 = CollectionItem(**collection_item_model_dict) + + # Verify the model instances are equivalent + assert collection_item_model == collection_item_model2 + + # Convert model instance back to dict and verify no loss of data + collection_item_model_json2 = collection_item_model.to_dict() + assert collection_item_model_json2 == collection_item_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index da828d354..60a362251 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -13,90 +13,277 @@ # See the License for the specific language governing permissions and # limitations under the License. -from datetime import datetime +""" +Unit Tests for NaturalLanguageUnderstandingV1 +""" + +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect import json import pytest +import re +import requests import responses -import ibm_watson.natural_language_understanding_v1 +import urllib from ibm_watson.natural_language_understanding_v1 import * +version = 'testString' + +service = NaturalLanguageUnderstandingV1( + authenticator=NoAuthAuthenticator(), + version=version + ) + base_url = 'https://api.us-south.natural-language-understanding.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: Analyze ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for analyze -#----------------------------------------------------------------------------- class TestAnalyze(): + """ + Test Class for analyze + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_analyze_response(self): - body = self.construct_full_body() - response = fake_response_AnalysisResults_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_analyze_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_AnalysisResults_json - send_request(self, body, response) + def test_analyze_all_params(self): + """ + analyze() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/analyze') + mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ConceptsOptions model + concepts_options_model = {} + concepts_options_model['limit'] = 50 + + # Construct a dict representation of a EmotionOptions model + emotion_options_model = {} + emotion_options_model['document'] = True + emotion_options_model['targets'] = ['testString'] + + # Construct a dict representation of a EntitiesOptions model + entities_options_model = {} + entities_options_model['limit'] = 250 + entities_options_model['mentions'] = True + entities_options_model['model'] = 'testString' + entities_options_model['sentiment'] = True + entities_options_model['emotion'] = True + + # Construct a dict representation of a KeywordsOptions model + keywords_options_model = {} + keywords_options_model['limit'] = 250 + keywords_options_model['sentiment'] = True + keywords_options_model['emotion'] = True + + # Construct a dict representation of a RelationsOptions model + relations_options_model = {} + relations_options_model['model'] = 'testString' + + # Construct a dict representation of a SemanticRolesOptions model + semantic_roles_options_model = {} + semantic_roles_options_model['limit'] = 38 + semantic_roles_options_model['keywords'] = True + semantic_roles_options_model['entities'] = True + + # Construct a dict representation of a SentimentOptions model + sentiment_options_model = {} + sentiment_options_model['document'] = True + sentiment_options_model['targets'] = ['testString'] + + # Construct a dict representation of a CategoriesOptions model + categories_options_model = {} + categories_options_model['explanation'] = True + categories_options_model['limit'] = 10 + categories_options_model['model'] = 'testString' + + # Construct a dict representation of a SyntaxOptionsTokens model + syntax_options_tokens_model = {} + syntax_options_tokens_model['lemma'] = True + syntax_options_tokens_model['part_of_speech'] = True + + # Construct a dict representation of a SyntaxOptions model + syntax_options_model = {} + syntax_options_model['tokens'] = syntax_options_tokens_model + syntax_options_model['sentences'] = True + + # Construct a dict representation of a Features model + features_model = {} + features_model['concepts'] = concepts_options_model + features_model['emotion'] = emotion_options_model + features_model['entities'] = entities_options_model + features_model['keywords'] = keywords_options_model + features_model['metadata'] = { 'foo': 'bar' } + features_model['relations'] = relations_options_model + features_model['semantic_roles'] = semantic_roles_options_model + features_model['sentiment'] = sentiment_options_model + features_model['categories'] = categories_options_model + features_model['syntax'] = syntax_options_model + + # Set up parameter values + features = features_model + text = 'testString' + html = 'testString' + url = 'testString' + clean = True + xpath = 'testString' + fallback_to_raw = True + return_analyzed_text = True + language = 'testString' + limit_text_characters = 38 + + # Invoke method + response = service.analyze( + features, + text=text, + html=html, + url=url, + clean=clean, + xpath=xpath, + fallback_to_raw=fallback_to_raw, + return_analyzed_text=return_analyzed_text, + language=language, + limit_text_characters=limit_text_characters, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['features'] == features_model + assert req_body['text'] == 'testString' + assert req_body['html'] == 'testString' + assert req_body['url'] == 'testString' + assert req_body['clean'] == True + assert req_body['xpath'] == 'testString' + assert req_body['fallback_to_raw'] == True + assert req_body['return_analyzed_text'] == True + assert req_body['language'] == 'testString' + assert req_body['limit_text_characters'] == 38 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_analyze_empty(self): - check_empty_required_params(self, fake_response_AnalysisResults_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/analyze' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_analyze_value_error(self): + """ + test_analyze_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/analyze') + mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = NaturalLanguageUnderstandingV1( - authenticator=NoAuthAuthenticator(), - version='2020-08-01', - ) - service.set_service_url(base_url) - output = service.analyze(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"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, "model": "fake_model"}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""")), "text": "string1", "html": "string1", "url": "string1", "clean": True, "xpath": "string1", "fallback_to_raw": True, "return_analyzed_text": True, "language": "string1", "limit_text_characters": 12345, }) - return body - - def construct_required_body(self): - body = dict() - body.update({"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, "model": "fake_model"}, "syntax": {"tokens": {"lemma": false, "part_of_speech": true}, "sentences": false}}""")), "text": "string1", "html": "string1", "url": "string1", "clean": True, "xpath": "string1", "fallback_to_raw": True, "return_analyzed_text": True, "language": "string1", "limit_text_characters": 12345, }) - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ConceptsOptions model + concepts_options_model = {} + concepts_options_model['limit'] = 50 + + # Construct a dict representation of a EmotionOptions model + emotion_options_model = {} + emotion_options_model['document'] = True + emotion_options_model['targets'] = ['testString'] + + # Construct a dict representation of a EntitiesOptions model + entities_options_model = {} + entities_options_model['limit'] = 250 + entities_options_model['mentions'] = True + entities_options_model['model'] = 'testString' + entities_options_model['sentiment'] = True + entities_options_model['emotion'] = True + + # Construct a dict representation of a KeywordsOptions model + keywords_options_model = {} + keywords_options_model['limit'] = 250 + keywords_options_model['sentiment'] = True + keywords_options_model['emotion'] = True + + # Construct a dict representation of a RelationsOptions model + relations_options_model = {} + relations_options_model['model'] = 'testString' + + # Construct a dict representation of a SemanticRolesOptions model + semantic_roles_options_model = {} + semantic_roles_options_model['limit'] = 38 + semantic_roles_options_model['keywords'] = True + semantic_roles_options_model['entities'] = True + + # Construct a dict representation of a SentimentOptions model + sentiment_options_model = {} + sentiment_options_model['document'] = True + sentiment_options_model['targets'] = ['testString'] + + # Construct a dict representation of a CategoriesOptions model + categories_options_model = {} + categories_options_model['explanation'] = True + categories_options_model['limit'] = 10 + categories_options_model['model'] = 'testString' + + # Construct a dict representation of a SyntaxOptionsTokens model + syntax_options_tokens_model = {} + syntax_options_tokens_model['lemma'] = True + syntax_options_tokens_model['part_of_speech'] = True + + # Construct a dict representation of a SyntaxOptions model + syntax_options_model = {} + syntax_options_model['tokens'] = syntax_options_tokens_model + syntax_options_model['sentences'] = True + + # Construct a dict representation of a Features model + features_model = {} + features_model['concepts'] = concepts_options_model + features_model['emotion'] = emotion_options_model + features_model['entities'] = entities_options_model + features_model['keywords'] = keywords_options_model + features_model['metadata'] = { 'foo': 'bar' } + features_model['relations'] = relations_options_model + features_model['semantic_roles'] = semantic_roles_options_model + features_model['sentiment'] = sentiment_options_model + features_model['categories'] = categories_options_model + features_model['syntax'] = syntax_options_model + + # Set up parameter values + features = features_model + text = 'testString' + html = 'testString' + url = 'testString' + clean = True + xpath = 'testString' + fallback_to_raw = True + return_analyzed_text = True + language = 'testString' + limit_text_characters = 38 + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "features": features, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.analyze(**req_copy) + # endregion @@ -109,141 +296,135 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_models -#----------------------------------------------------------------------------- class TestListModels(): + """ + Test Class for list_models + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_models_response(self): - body = self.construct_full_body() - response = fake_response_ListModelsResults_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_models_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ListModelsResults_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_models_all_params(self): + """ + list_models() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/models') + mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_models_empty(self): - check_empty_response(self) + # Invoke method + response = service.list_models() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/models' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_models_value_error(self): + """ + test_list_models_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/models') + mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00"}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = NaturalLanguageUnderstandingV1( - authenticator=NoAuthAuthenticator(), - version='2020-08-01', - ) - service.set_service_url(base_url) - output = service.list_models(**body) - return output - - def construct_full_body(self): - body = dict() - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_model -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_models(**req_copy) + + + class TestDeleteModel(): + """ + Test Class for delete_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_model_response(self): - body = self.construct_full_body() - response = fake_response_DeleteModelResults_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_DeleteModelResults_json - send_request(self, body, response) + def test_delete_model_all_params(self): + """ + delete_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/models/testString') + mock_response = '{"deleted": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Invoke method + response = service.delete_model( + model_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_model_empty(self): - check_empty_required_params(self, fake_response_DeleteModelResults_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/models/{0}'.format(body['model_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_model_value_error(self): + """ + test_delete_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/models/testString') + mock_response = '{"deleted": "deleted"}' responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = NaturalLanguageUnderstandingV1( - authenticator=NoAuthAuthenticator(), - version='2020-08-01', - ) - service.set_service_url(base_url) - output = service.delete_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['model_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['model_id'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_model(**req_copy) + # endregion @@ -252,70 +433,1901 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestAnalysisResults(): + """ + Test Class for AnalysisResults + """ + + def test_analysis_results_serialization(self): + """ + Test serialization/deserialization for AnalysisResults + """ + + # Construct dict forms of any model objects needed in order to build this model. + + analysis_results_usage_model = {} # AnalysisResultsUsage + analysis_results_usage_model['features'] = 38 + analysis_results_usage_model['text_characters'] = 38 + analysis_results_usage_model['text_units'] = 38 + + concepts_result_model = {} # ConceptsResult + concepts_result_model['text'] = 'Social network service' + concepts_result_model['relevance'] = 0.92186 + concepts_result_model['dbpedia_resource'] = 'http://dbpedia.org/resource/Social_network_service' + + entity_mention_model = {} # EntityMention + entity_mention_model['text'] = 'testString' + entity_mention_model['location'] = [38] + entity_mention_model['confidence'] = 72.5 + + emotion_scores_model = {} # EmotionScores + emotion_scores_model['anger'] = 72.5 + emotion_scores_model['disgust'] = 72.5 + emotion_scores_model['fear'] = 72.5 + emotion_scores_model['joy'] = 72.5 + emotion_scores_model['sadness'] = 72.5 + + feature_sentiment_results_model = {} # FeatureSentimentResults + feature_sentiment_results_model['score'] = 72.5 + + disambiguation_result_model = {} # DisambiguationResult + disambiguation_result_model['name'] = 'testString' + disambiguation_result_model['dbpedia_resource'] = 'testString' + disambiguation_result_model['subtype'] = ['testString'] + + entities_result_model = {} # EntitiesResult + entities_result_model['type'] = 'testString' + entities_result_model['text'] = 'Social network service' + entities_result_model['relevance'] = 0.92186 + entities_result_model['confidence'] = 72.5 + entities_result_model['mentions'] = [entity_mention_model] + entities_result_model['count'] = 38 + entities_result_model['emotion'] = emotion_scores_model + entities_result_model['sentiment'] = feature_sentiment_results_model + entities_result_model['disambiguation'] = disambiguation_result_model + + keywords_result_model = {} # KeywordsResult + keywords_result_model['count'] = 1 + keywords_result_model['relevance'] = 0.864624 + keywords_result_model['text'] = 'curated online courses' + keywords_result_model['emotion'] = emotion_scores_model + keywords_result_model['sentiment'] = feature_sentiment_results_model + + categories_relevant_text_model = {} # CategoriesRelevantText + categories_relevant_text_model['text'] = 'testString' + + categories_result_explanation_model = {} # CategoriesResultExplanation + categories_result_explanation_model['relevant_text'] = [categories_relevant_text_model] + + categories_result_model = {} # CategoriesResult + categories_result_model['label'] = '/technology and computing/software' + categories_result_model['score'] = 0.594296 + categories_result_model['explanation'] = categories_result_explanation_model + + document_emotion_results_model = {} # DocumentEmotionResults + document_emotion_results_model['emotion'] = emotion_scores_model + + targeted_emotion_results_model = {} # TargetedEmotionResults + targeted_emotion_results_model['text'] = 'testString' + targeted_emotion_results_model['emotion'] = emotion_scores_model + + emotion_result_model = {} # EmotionResult + emotion_result_model['document'] = document_emotion_results_model + emotion_result_model['targets'] = [targeted_emotion_results_model] + + author_model = {} # Author + author_model['name'] = 'testString' + + feed_model = {} # Feed + feed_model['link'] = 'testString' + + features_results_metadata_model = {} # FeaturesResultsMetadata + features_results_metadata_model['authors'] = [author_model] + features_results_metadata_model['publication_date'] = 'testString' + features_results_metadata_model['title'] = 'testString' + features_results_metadata_model['image'] = 'testString' + features_results_metadata_model['feeds'] = [feed_model] + + relation_entity_model = {} # RelationEntity + relation_entity_model['text'] = 'Best Actor' + relation_entity_model['type'] = 'EntertainmentAward' + + relation_argument_model = {} # RelationArgument + relation_argument_model['entities'] = [relation_entity_model] + relation_argument_model['location'] = [38] + relation_argument_model['text'] = 'Best Actor' + + relations_result_model = {} # RelationsResult + relations_result_model['score'] = 0.680715 + relations_result_model['sentence'] = 'Leonardo DiCaprio won Best Actor in a Leading Role for his performance.' + relations_result_model['type'] = 'awardedTo' + relations_result_model['arguments'] = [relation_argument_model] + + semantic_roles_entity_model = {} # SemanticRolesEntity + semantic_roles_entity_model['type'] = 'testString' + semantic_roles_entity_model['text'] = 'testString' + + semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model['text'] = 'testString' + + semantic_roles_result_subject_model = {} # SemanticRolesResultSubject + semantic_roles_result_subject_model['text'] = 'IBM' + semantic_roles_result_subject_model['entities'] = [semantic_roles_entity_model] + semantic_roles_result_subject_model['keywords'] = [semantic_roles_keyword_model] + + semantic_roles_verb_model = {} # SemanticRolesVerb + semantic_roles_verb_model['text'] = 'have' + semantic_roles_verb_model['tense'] = 'present' + + semantic_roles_result_action_model = {} # SemanticRolesResultAction + semantic_roles_result_action_model['text'] = 'has' + semantic_roles_result_action_model['normalized'] = 'have' + semantic_roles_result_action_model['verb'] = semantic_roles_verb_model + + semantic_roles_result_object_model = {} # SemanticRolesResultObject + semantic_roles_result_object_model['text'] = 'one of the largest workforces in the world' + semantic_roles_result_object_model['keywords'] = [semantic_roles_keyword_model] + + semantic_roles_result_model = {} # SemanticRolesResult + semantic_roles_result_model['sentence'] = 'IBM has one of the largest workforces in the world' + semantic_roles_result_model['subject'] = semantic_roles_result_subject_model + semantic_roles_result_model['action'] = semantic_roles_result_action_model + semantic_roles_result_model['object'] = semantic_roles_result_object_model + + document_sentiment_results_model = {} # DocumentSentimentResults + document_sentiment_results_model['label'] = 'testString' + document_sentiment_results_model['score'] = 72.5 + + targeted_sentiment_results_model = {} # TargetedSentimentResults + targeted_sentiment_results_model['text'] = 'testString' + targeted_sentiment_results_model['score'] = 72.5 + + sentiment_result_model = {} # SentimentResult + sentiment_result_model['document'] = document_sentiment_results_model + sentiment_result_model['targets'] = [targeted_sentiment_results_model] + + token_result_model = {} # TokenResult + token_result_model['text'] = 'testString' + token_result_model['part_of_speech'] = 'ADJ' + token_result_model['location'] = [38] + token_result_model['lemma'] = 'testString' + + sentence_result_model = {} # SentenceResult + sentence_result_model['text'] = 'testString' + sentence_result_model['location'] = [38] + + syntax_result_model = {} # SyntaxResult + syntax_result_model['tokens'] = [token_result_model] + syntax_result_model['sentences'] = [sentence_result_model] + + # Construct a json representation of a AnalysisResults model + analysis_results_model_json = {} + analysis_results_model_json['language'] = 'testString' + analysis_results_model_json['analyzed_text'] = 'testString' + analysis_results_model_json['retrieved_url'] = 'testString' + analysis_results_model_json['usage'] = analysis_results_usage_model + analysis_results_model_json['concepts'] = [concepts_result_model] + analysis_results_model_json['entities'] = [entities_result_model] + analysis_results_model_json['keywords'] = [keywords_result_model] + analysis_results_model_json['categories'] = [categories_result_model] + analysis_results_model_json['emotion'] = emotion_result_model + analysis_results_model_json['metadata'] = features_results_metadata_model + analysis_results_model_json['relations'] = [relations_result_model] + analysis_results_model_json['semantic_roles'] = [semantic_roles_result_model] + analysis_results_model_json['sentiment'] = sentiment_result_model + analysis_results_model_json['syntax'] = syntax_result_model + + # Construct a model instance of AnalysisResults by calling from_dict on the json representation + analysis_results_model = AnalysisResults.from_dict(analysis_results_model_json) + assert analysis_results_model != False + + # Construct a model instance of AnalysisResults by calling from_dict on the json representation + analysis_results_model_dict = AnalysisResults.from_dict(analysis_results_model_json).__dict__ + analysis_results_model2 = AnalysisResults(**analysis_results_model_dict) + + # Verify the model instances are equivalent + assert analysis_results_model == analysis_results_model2 + + # Convert model instance back to dict and verify no loss of data + analysis_results_model_json2 = analysis_results_model.to_dict() + assert analysis_results_model_json2 == analysis_results_model_json + +class TestAnalysisResultsUsage(): + """ + Test Class for AnalysisResultsUsage + """ + + def test_analysis_results_usage_serialization(self): + """ + Test serialization/deserialization for AnalysisResultsUsage + """ + + # Construct a json representation of a AnalysisResultsUsage model + analysis_results_usage_model_json = {} + analysis_results_usage_model_json['features'] = 38 + analysis_results_usage_model_json['text_characters'] = 38 + analysis_results_usage_model_json['text_units'] = 38 + + # Construct a model instance of AnalysisResultsUsage by calling from_dict on the json representation + analysis_results_usage_model = AnalysisResultsUsage.from_dict(analysis_results_usage_model_json) + assert analysis_results_usage_model != False + + # Construct a model instance of AnalysisResultsUsage by calling from_dict on the json representation + analysis_results_usage_model_dict = AnalysisResultsUsage.from_dict(analysis_results_usage_model_json).__dict__ + analysis_results_usage_model2 = AnalysisResultsUsage(**analysis_results_usage_model_dict) + + # Verify the model instances are equivalent + assert analysis_results_usage_model == analysis_results_usage_model2 + + # Convert model instance back to dict and verify no loss of data + analysis_results_usage_model_json2 = analysis_results_usage_model.to_dict() + assert analysis_results_usage_model_json2 == analysis_results_usage_model_json + +class TestAuthor(): + """ + Test Class for Author + """ + + def test_author_serialization(self): + """ + Test serialization/deserialization for Author + """ + + # Construct a json representation of a Author model + author_model_json = {} + author_model_json['name'] = 'testString' + + # Construct a model instance of Author by calling from_dict on the json representation + author_model = Author.from_dict(author_model_json) + assert author_model != False + + # Construct a model instance of Author by calling from_dict on the json representation + author_model_dict = Author.from_dict(author_model_json).__dict__ + author_model2 = Author(**author_model_dict) + + # Verify the model instances are equivalent + assert author_model == author_model2 + + # Convert model instance back to dict and verify no loss of data + author_model_json2 = author_model.to_dict() + assert author_model_json2 == author_model_json + +class TestCategoriesOptions(): + """ + Test Class for CategoriesOptions + """ + + def test_categories_options_serialization(self): + """ + Test serialization/deserialization for CategoriesOptions + """ + + # Construct a json representation of a CategoriesOptions model + categories_options_model_json = {} + categories_options_model_json['explanation'] = True + categories_options_model_json['limit'] = 10 + categories_options_model_json['model'] = 'testString' + + # Construct a model instance of CategoriesOptions by calling from_dict on the json representation + categories_options_model = CategoriesOptions.from_dict(categories_options_model_json) + assert categories_options_model != False + + # Construct a model instance of CategoriesOptions by calling from_dict on the json representation + categories_options_model_dict = CategoriesOptions.from_dict(categories_options_model_json).__dict__ + categories_options_model2 = CategoriesOptions(**categories_options_model_dict) + + # Verify the model instances are equivalent + assert categories_options_model == categories_options_model2 + + # Convert model instance back to dict and verify no loss of data + categories_options_model_json2 = categories_options_model.to_dict() + assert categories_options_model_json2 == categories_options_model_json + +class TestCategoriesRelevantText(): + """ + Test Class for CategoriesRelevantText + """ + + def test_categories_relevant_text_serialization(self): + """ + Test serialization/deserialization for CategoriesRelevantText + """ + + # Construct a json representation of a CategoriesRelevantText model + categories_relevant_text_model_json = {} + categories_relevant_text_model_json['text'] = 'testString' + + # Construct a model instance of CategoriesRelevantText by calling from_dict on the json representation + categories_relevant_text_model = CategoriesRelevantText.from_dict(categories_relevant_text_model_json) + assert categories_relevant_text_model != False + + # Construct a model instance of CategoriesRelevantText by calling from_dict on the json representation + categories_relevant_text_model_dict = CategoriesRelevantText.from_dict(categories_relevant_text_model_json).__dict__ + categories_relevant_text_model2 = CategoriesRelevantText(**categories_relevant_text_model_dict) + + # Verify the model instances are equivalent + assert categories_relevant_text_model == categories_relevant_text_model2 + + # Convert model instance back to dict and verify no loss of data + categories_relevant_text_model_json2 = categories_relevant_text_model.to_dict() + assert categories_relevant_text_model_json2 == categories_relevant_text_model_json + +class TestCategoriesResult(): + """ + Test Class for CategoriesResult + """ + + def test_categories_result_serialization(self): + """ + Test serialization/deserialization for CategoriesResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + categories_relevant_text_model = {} # CategoriesRelevantText + categories_relevant_text_model['text'] = 'testString' + + categories_result_explanation_model = {} # CategoriesResultExplanation + categories_result_explanation_model['relevant_text'] = [categories_relevant_text_model] + + # Construct a json representation of a CategoriesResult model + categories_result_model_json = {} + categories_result_model_json['label'] = 'testString' + categories_result_model_json['score'] = 72.5 + categories_result_model_json['explanation'] = categories_result_explanation_model + + # Construct a model instance of CategoriesResult by calling from_dict on the json representation + categories_result_model = CategoriesResult.from_dict(categories_result_model_json) + assert categories_result_model != False + + # Construct a model instance of CategoriesResult by calling from_dict on the json representation + categories_result_model_dict = CategoriesResult.from_dict(categories_result_model_json).__dict__ + categories_result_model2 = CategoriesResult(**categories_result_model_dict) + + # Verify the model instances are equivalent + assert categories_result_model == categories_result_model2 + + # Convert model instance back to dict and verify no loss of data + categories_result_model_json2 = categories_result_model.to_dict() + assert categories_result_model_json2 == categories_result_model_json + +class TestCategoriesResultExplanation(): + """ + Test Class for CategoriesResultExplanation + """ + + def test_categories_result_explanation_serialization(self): + """ + Test serialization/deserialization for CategoriesResultExplanation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + categories_relevant_text_model = {} # CategoriesRelevantText + categories_relevant_text_model['text'] = 'testString' + + # Construct a json representation of a CategoriesResultExplanation model + categories_result_explanation_model_json = {} + categories_result_explanation_model_json['relevant_text'] = [categories_relevant_text_model] + + # Construct a model instance of CategoriesResultExplanation by calling from_dict on the json representation + categories_result_explanation_model = CategoriesResultExplanation.from_dict(categories_result_explanation_model_json) + assert categories_result_explanation_model != False + + # Construct a model instance of CategoriesResultExplanation by calling from_dict on the json representation + categories_result_explanation_model_dict = CategoriesResultExplanation.from_dict(categories_result_explanation_model_json).__dict__ + categories_result_explanation_model2 = CategoriesResultExplanation(**categories_result_explanation_model_dict) + + # Verify the model instances are equivalent + assert categories_result_explanation_model == categories_result_explanation_model2 + + # Convert model instance back to dict and verify no loss of data + categories_result_explanation_model_json2 = categories_result_explanation_model.to_dict() + assert categories_result_explanation_model_json2 == categories_result_explanation_model_json + +class TestConceptsOptions(): + """ + Test Class for ConceptsOptions + """ + + def test_concepts_options_serialization(self): + """ + Test serialization/deserialization for ConceptsOptions + """ + + # Construct a json representation of a ConceptsOptions model + concepts_options_model_json = {} + concepts_options_model_json['limit'] = 50 + + # Construct a model instance of ConceptsOptions by calling from_dict on the json representation + concepts_options_model = ConceptsOptions.from_dict(concepts_options_model_json) + assert concepts_options_model != False + + # Construct a model instance of ConceptsOptions by calling from_dict on the json representation + concepts_options_model_dict = ConceptsOptions.from_dict(concepts_options_model_json).__dict__ + concepts_options_model2 = ConceptsOptions(**concepts_options_model_dict) + + # Verify the model instances are equivalent + assert concepts_options_model == concepts_options_model2 + + # Convert model instance back to dict and verify no loss of data + concepts_options_model_json2 = concepts_options_model.to_dict() + assert concepts_options_model_json2 == concepts_options_model_json + +class TestConceptsResult(): + """ + Test Class for ConceptsResult + """ + + def test_concepts_result_serialization(self): + """ + Test serialization/deserialization for ConceptsResult + """ + + # Construct a json representation of a ConceptsResult model + concepts_result_model_json = {} + concepts_result_model_json['text'] = 'testString' + concepts_result_model_json['relevance'] = 72.5 + concepts_result_model_json['dbpedia_resource'] = 'testString' + + # Construct a model instance of ConceptsResult by calling from_dict on the json representation + concepts_result_model = ConceptsResult.from_dict(concepts_result_model_json) + assert concepts_result_model != False + + # Construct a model instance of ConceptsResult by calling from_dict on the json representation + concepts_result_model_dict = ConceptsResult.from_dict(concepts_result_model_json).__dict__ + concepts_result_model2 = ConceptsResult(**concepts_result_model_dict) + + # Verify the model instances are equivalent + assert concepts_result_model == concepts_result_model2 + + # Convert model instance back to dict and verify no loss of data + concepts_result_model_json2 = concepts_result_model.to_dict() + assert concepts_result_model_json2 == concepts_result_model_json + +class TestDeleteModelResults(): + """ + Test Class for DeleteModelResults + """ + + def test_delete_model_results_serialization(self): + """ + Test serialization/deserialization for DeleteModelResults + """ + + # Construct a json representation of a DeleteModelResults model + delete_model_results_model_json = {} + delete_model_results_model_json['deleted'] = 'testString' + + # Construct a model instance of DeleteModelResults by calling from_dict on the json representation + delete_model_results_model = DeleteModelResults.from_dict(delete_model_results_model_json) + assert delete_model_results_model != False + + # Construct a model instance of DeleteModelResults by calling from_dict on the json representation + delete_model_results_model_dict = DeleteModelResults.from_dict(delete_model_results_model_json).__dict__ + delete_model_results_model2 = DeleteModelResults(**delete_model_results_model_dict) - Args: - obj: The generated test function + # Verify the model instances are equivalent + assert delete_model_results_model == delete_model_results_model2 + # Convert model instance back to dict and verify no loss of data + delete_model_results_model_json2 = delete_model_results_model.to_dict() + assert delete_model_results_model_json2 == delete_model_results_model_json + +class TestDisambiguationResult(): + """ + Test Class for DisambiguationResult + """ + + def test_disambiguation_result_serialization(self): + """ + Test serialization/deserialization for DisambiguationResult + """ + + # Construct a json representation of a DisambiguationResult model + disambiguation_result_model_json = {} + disambiguation_result_model_json['name'] = 'testString' + disambiguation_result_model_json['dbpedia_resource'] = 'testString' + disambiguation_result_model_json['subtype'] = ['testString'] + + # Construct a model instance of DisambiguationResult by calling from_dict on the json representation + disambiguation_result_model = DisambiguationResult.from_dict(disambiguation_result_model_json) + assert disambiguation_result_model != False + + # Construct a model instance of DisambiguationResult by calling from_dict on the json representation + disambiguation_result_model_dict = DisambiguationResult.from_dict(disambiguation_result_model_json).__dict__ + disambiguation_result_model2 = DisambiguationResult(**disambiguation_result_model_dict) + + # Verify the model instances are equivalent + assert disambiguation_result_model == disambiguation_result_model2 + + # Convert model instance back to dict and verify no loss of data + disambiguation_result_model_json2 = disambiguation_result_model.to_dict() + assert disambiguation_result_model_json2 == disambiguation_result_model_json + +class TestDocumentEmotionResults(): + """ + Test Class for DocumentEmotionResults + """ + + def test_document_emotion_results_serialization(self): + """ + Test serialization/deserialization for DocumentEmotionResults + """ + + # Construct dict forms of any model objects needed in order to build this model. + + emotion_scores_model = {} # EmotionScores + emotion_scores_model['anger'] = 72.5 + emotion_scores_model['disgust'] = 72.5 + emotion_scores_model['fear'] = 72.5 + emotion_scores_model['joy'] = 72.5 + emotion_scores_model['sadness'] = 72.5 + + # Construct a json representation of a DocumentEmotionResults model + document_emotion_results_model_json = {} + document_emotion_results_model_json['emotion'] = emotion_scores_model + + # Construct a model instance of DocumentEmotionResults by calling from_dict on the json representation + document_emotion_results_model = DocumentEmotionResults.from_dict(document_emotion_results_model_json) + assert document_emotion_results_model != False + + # Construct a model instance of DocumentEmotionResults by calling from_dict on the json representation + document_emotion_results_model_dict = DocumentEmotionResults.from_dict(document_emotion_results_model_json).__dict__ + document_emotion_results_model2 = DocumentEmotionResults(**document_emotion_results_model_dict) + + # Verify the model instances are equivalent + assert document_emotion_results_model == document_emotion_results_model2 + + # Convert model instance back to dict and verify no loss of data + document_emotion_results_model_json2 = document_emotion_results_model.to_dict() + assert document_emotion_results_model_json2 == document_emotion_results_model_json + +class TestDocumentSentimentResults(): + """ + Test Class for DocumentSentimentResults + """ + + def test_document_sentiment_results_serialization(self): + """ + Test serialization/deserialization for DocumentSentimentResults + """ + + # Construct a json representation of a DocumentSentimentResults model + document_sentiment_results_model_json = {} + document_sentiment_results_model_json['label'] = 'testString' + document_sentiment_results_model_json['score'] = 72.5 + + # Construct a model instance of DocumentSentimentResults by calling from_dict on the json representation + document_sentiment_results_model = DocumentSentimentResults.from_dict(document_sentiment_results_model_json) + assert document_sentiment_results_model != False + + # Construct a model instance of DocumentSentimentResults by calling from_dict on the json representation + document_sentiment_results_model_dict = DocumentSentimentResults.from_dict(document_sentiment_results_model_json).__dict__ + document_sentiment_results_model2 = DocumentSentimentResults(**document_sentiment_results_model_dict) + + # Verify the model instances are equivalent + assert document_sentiment_results_model == document_sentiment_results_model2 + + # Convert model instance back to dict and verify no loss of data + document_sentiment_results_model_json2 = document_sentiment_results_model.to_dict() + assert document_sentiment_results_model_json2 == document_sentiment_results_model_json + +class TestEmotionOptions(): + """ + Test Class for EmotionOptions + """ + + def test_emotion_options_serialization(self): + """ + Test serialization/deserialization for EmotionOptions + """ + + # Construct a json representation of a EmotionOptions model + emotion_options_model_json = {} + emotion_options_model_json['document'] = True + emotion_options_model_json['targets'] = ['testString'] + + # Construct a model instance of EmotionOptions by calling from_dict on the json representation + emotion_options_model = EmotionOptions.from_dict(emotion_options_model_json) + assert emotion_options_model != False + + # Construct a model instance of EmotionOptions by calling from_dict on the json representation + emotion_options_model_dict = EmotionOptions.from_dict(emotion_options_model_json).__dict__ + emotion_options_model2 = EmotionOptions(**emotion_options_model_dict) + + # Verify the model instances are equivalent + assert emotion_options_model == emotion_options_model2 + + # Convert model instance back to dict and verify no loss of data + emotion_options_model_json2 = emotion_options_model.to_dict() + assert emotion_options_model_json2 == emotion_options_model_json + +class TestEmotionResult(): + """ + Test Class for EmotionResult """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data + def test_emotion_result_serialization(self): + """ + Test serialization/deserialization for EmotionResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + emotion_scores_model = {} # EmotionScores + emotion_scores_model['anger'] = 0.041796 + emotion_scores_model['disgust'] = 0.022637 + emotion_scores_model['fear'] = 0.033387 + emotion_scores_model['joy'] = 0.563273 + emotion_scores_model['sadness'] = 0.32665 + + document_emotion_results_model = {} # DocumentEmotionResults + document_emotion_results_model['emotion'] = emotion_scores_model + + targeted_emotion_results_model = {} # TargetedEmotionResults + targeted_emotion_results_model['text'] = 'apples' + targeted_emotion_results_model['emotion'] = emotion_scores_model + + # Construct a json representation of a EmotionResult model + emotion_result_model_json = {} + emotion_result_model_json['document'] = document_emotion_results_model + emotion_result_model_json['targets'] = [targeted_emotion_results_model] + + # Construct a model instance of EmotionResult by calling from_dict on the json representation + emotion_result_model = EmotionResult.from_dict(emotion_result_model_json) + assert emotion_result_model != False + + # Construct a model instance of EmotionResult by calling from_dict on the json representation + emotion_result_model_dict = EmotionResult.from_dict(emotion_result_model_json).__dict__ + emotion_result_model2 = EmotionResult(**emotion_result_model_dict) + + # Verify the model instances are equivalent + assert emotion_result_model == emotion_result_model2 - Args: - obj: The generated test function + # Convert model instance back to dict and verify no loss of data + emotion_result_model_json2 = emotion_result_model.to_dict() + assert emotion_result_model_json2 == emotion_result_model_json +class TestEmotionScores(): """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error + Test Class for EmotionScores + """ + + def test_emotion_scores_serialization(self): + """ + Test serialization/deserialization for EmotionScores + """ + + # Construct a json representation of a EmotionScores model + emotion_scores_model_json = {} + emotion_scores_model_json['anger'] = 72.5 + emotion_scores_model_json['disgust'] = 72.5 + emotion_scores_model_json['fear'] = 72.5 + emotion_scores_model_json['joy'] = 72.5 + emotion_scores_model_json['sadness'] = 72.5 + + # Construct a model instance of EmotionScores by calling from_dict on the json representation + emotion_scores_model = EmotionScores.from_dict(emotion_scores_model_json) + assert emotion_scores_model != False -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request + # Construct a model instance of EmotionScores by calling from_dict on the json representation + emotion_scores_model_dict = EmotionScores.from_dict(emotion_scores_model_json).__dict__ + emotion_scores_model2 = EmotionScores(**emotion_scores_model_dict) - Args: - obj: The generated test function + # Verify the model instances are equivalent + assert emotion_scores_model == emotion_scores_model2 + # Convert model instance back to dict and verify no loss of data + emotion_scores_model_json2 = emotion_scores_model.to_dict() + assert emotion_scores_model_json2 == emotion_scores_model_json + +class TestEntitiesOptions(): + """ + Test Class for EntitiesOptions """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response + def test_entities_options_serialization(self): + """ + Test serialization/deserialization for EntitiesOptions + """ + + # Construct a json representation of a EntitiesOptions model + entities_options_model_json = {} + entities_options_model_json['limit'] = 250 + entities_options_model_json['mentions'] = True + entities_options_model_json['model'] = 'testString' + entities_options_model_json['sentiment'] = True + entities_options_model_json['emotion'] = True + + # Construct a model instance of EntitiesOptions by calling from_dict on the json representation + entities_options_model = EntitiesOptions.from_dict(entities_options_model_json) + assert entities_options_model != False - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string + # Construct a model instance of EntitiesOptions by calling from_dict on the json representation + entities_options_model_dict = EntitiesOptions.from_dict(entities_options_model_json).__dict__ + entities_options_model2 = EntitiesOptions(**entities_options_model_dict) + # Verify the model instances are equivalent + assert entities_options_model == entities_options_model2 + + # Convert model instance back to dict and verify no loss of data + entities_options_model_json2 = entities_options_model.to_dict() + assert entities_options_model_json2 == entities_options_model_json + +class TestEntitiesResult(): """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response + Test Class for EntitiesResult + """ + + def test_entities_result_serialization(self): + """ + Test serialization/deserialization for EntitiesResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + entity_mention_model = {} # EntityMention + entity_mention_model['text'] = 'testString' + entity_mention_model['location'] = [38] + entity_mention_model['confidence'] = 72.5 + + emotion_scores_model = {} # EmotionScores + emotion_scores_model['anger'] = 72.5 + emotion_scores_model['disgust'] = 72.5 + emotion_scores_model['fear'] = 72.5 + emotion_scores_model['joy'] = 72.5 + emotion_scores_model['sadness'] = 72.5 + + feature_sentiment_results_model = {} # FeatureSentimentResults + feature_sentiment_results_model['score'] = 72.5 -#################### -## Mock Responses ## -#################### + disambiguation_result_model = {} # DisambiguationResult + disambiguation_result_model['name'] = 'testString' + disambiguation_result_model['dbpedia_resource'] = 'testString' + disambiguation_result_model['subtype'] = ['testString'] -fake_response__json = None -fake_response_AnalysisResults_json = """{"language": "fake_language", "analyzed_text": "fake_analyzed_text", "retrieved_url": "fake_retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [], "entities": [], "keywords": [], "categories": [], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": []}, "metadata": {"authors": [], "publication_date": "fake_publication_date", "title": "fake_title", "image": "fake_image", "feeds": []}, "relations": [], "semantic_roles": [], "sentiment": {"document": {"label": "fake_label", "score": 5}, "targets": []}, "syntax": {"tokens": [], "sentences": []}}""" -fake_response_ListModelsResults_json = """{"models": []}""" -fake_response_DeleteModelResults_json = """{"deleted": "fake_deleted"}""" + # Construct a json representation of a EntitiesResult model + entities_result_model_json = {} + entities_result_model_json['type'] = 'testString' + entities_result_model_json['text'] = 'testString' + entities_result_model_json['relevance'] = 72.5 + entities_result_model_json['confidence'] = 72.5 + entities_result_model_json['mentions'] = [entity_mention_model] + entities_result_model_json['count'] = 38 + entities_result_model_json['emotion'] = emotion_scores_model + entities_result_model_json['sentiment'] = feature_sentiment_results_model + entities_result_model_json['disambiguation'] = disambiguation_result_model + + # Construct a model instance of EntitiesResult by calling from_dict on the json representation + entities_result_model = EntitiesResult.from_dict(entities_result_model_json) + assert entities_result_model != False + + # Construct a model instance of EntitiesResult by calling from_dict on the json representation + entities_result_model_dict = EntitiesResult.from_dict(entities_result_model_json).__dict__ + entities_result_model2 = EntitiesResult(**entities_result_model_dict) + + # Verify the model instances are equivalent + assert entities_result_model == entities_result_model2 + + # Convert model instance back to dict and verify no loss of data + entities_result_model_json2 = entities_result_model.to_dict() + assert entities_result_model_json2 == entities_result_model_json + +class TestEntityMention(): + """ + Test Class for EntityMention + """ + + def test_entity_mention_serialization(self): + """ + Test serialization/deserialization for EntityMention + """ + + # Construct a json representation of a EntityMention model + entity_mention_model_json = {} + entity_mention_model_json['text'] = 'testString' + entity_mention_model_json['location'] = [38] + entity_mention_model_json['confidence'] = 72.5 + + # Construct a model instance of EntityMention by calling from_dict on the json representation + entity_mention_model = EntityMention.from_dict(entity_mention_model_json) + assert entity_mention_model != False + + # Construct a model instance of EntityMention by calling from_dict on the json representation + entity_mention_model_dict = EntityMention.from_dict(entity_mention_model_json).__dict__ + entity_mention_model2 = EntityMention(**entity_mention_model_dict) + + # Verify the model instances are equivalent + assert entity_mention_model == entity_mention_model2 + + # Convert model instance back to dict and verify no loss of data + entity_mention_model_json2 = entity_mention_model.to_dict() + assert entity_mention_model_json2 == entity_mention_model_json + +class TestFeatureSentimentResults(): + """ + Test Class for FeatureSentimentResults + """ + + def test_feature_sentiment_results_serialization(self): + """ + Test serialization/deserialization for FeatureSentimentResults + """ + + # Construct a json representation of a FeatureSentimentResults model + feature_sentiment_results_model_json = {} + feature_sentiment_results_model_json['score'] = 72.5 + + # Construct a model instance of FeatureSentimentResults by calling from_dict on the json representation + feature_sentiment_results_model = FeatureSentimentResults.from_dict(feature_sentiment_results_model_json) + assert feature_sentiment_results_model != False + + # Construct a model instance of FeatureSentimentResults by calling from_dict on the json representation + feature_sentiment_results_model_dict = FeatureSentimentResults.from_dict(feature_sentiment_results_model_json).__dict__ + feature_sentiment_results_model2 = FeatureSentimentResults(**feature_sentiment_results_model_dict) + + # Verify the model instances are equivalent + assert feature_sentiment_results_model == feature_sentiment_results_model2 + + # Convert model instance back to dict and verify no loss of data + feature_sentiment_results_model_json2 = feature_sentiment_results_model.to_dict() + assert feature_sentiment_results_model_json2 == feature_sentiment_results_model_json + +class TestFeatures(): + """ + Test Class for Features + """ + + def test_features_serialization(self): + """ + Test serialization/deserialization for Features + """ + + # Construct dict forms of any model objects needed in order to build this model. + + concepts_options_model = {} # ConceptsOptions + concepts_options_model['limit'] = 50 + + emotion_options_model = {} # EmotionOptions + emotion_options_model['document'] = True + emotion_options_model['targets'] = ['testString'] + + entities_options_model = {} # EntitiesOptions + entities_options_model['limit'] = 250 + entities_options_model['mentions'] = True + entities_options_model['model'] = 'testString' + entities_options_model['sentiment'] = True + entities_options_model['emotion'] = True + + keywords_options_model = {} # KeywordsOptions + keywords_options_model['limit'] = 250 + keywords_options_model['sentiment'] = True + keywords_options_model['emotion'] = True + + relations_options_model = {} # RelationsOptions + relations_options_model['model'] = 'testString' + + semantic_roles_options_model = {} # SemanticRolesOptions + semantic_roles_options_model['limit'] = 38 + semantic_roles_options_model['keywords'] = True + semantic_roles_options_model['entities'] = True + + sentiment_options_model = {} # SentimentOptions + sentiment_options_model['document'] = True + sentiment_options_model['targets'] = ['testString'] + + categories_options_model = {} # CategoriesOptions + categories_options_model['explanation'] = True + categories_options_model['limit'] = 10 + categories_options_model['model'] = 'testString' + + syntax_options_tokens_model = {} # SyntaxOptionsTokens + syntax_options_tokens_model['lemma'] = True + syntax_options_tokens_model['part_of_speech'] = True + + syntax_options_model = {} # SyntaxOptions + syntax_options_model['tokens'] = syntax_options_tokens_model + syntax_options_model['sentences'] = True + + # Construct a json representation of a Features model + features_model_json = {} + features_model_json['concepts'] = concepts_options_model + features_model_json['emotion'] = emotion_options_model + features_model_json['entities'] = entities_options_model + features_model_json['keywords'] = keywords_options_model + features_model_json['metadata'] = { 'foo': 'bar' } + features_model_json['relations'] = relations_options_model + features_model_json['semantic_roles'] = semantic_roles_options_model + features_model_json['sentiment'] = sentiment_options_model + features_model_json['categories'] = categories_options_model + features_model_json['syntax'] = syntax_options_model + + # Construct a model instance of Features by calling from_dict on the json representation + features_model = Features.from_dict(features_model_json) + assert features_model != False + + # Construct a model instance of Features by calling from_dict on the json representation + features_model_dict = Features.from_dict(features_model_json).__dict__ + features_model2 = Features(**features_model_dict) + + # Verify the model instances are equivalent + assert features_model == features_model2 + + # Convert model instance back to dict and verify no loss of data + features_model_json2 = features_model.to_dict() + assert features_model_json2 == features_model_json + +class TestFeaturesResultsMetadata(): + """ + Test Class for FeaturesResultsMetadata + """ + + def test_features_results_metadata_serialization(self): + """ + Test serialization/deserialization for FeaturesResultsMetadata + """ + + # Construct dict forms of any model objects needed in order to build this model. + + author_model = {} # Author + author_model['name'] = 'testString' + + feed_model = {} # Feed + feed_model['link'] = 'testString' + + # Construct a json representation of a FeaturesResultsMetadata model + features_results_metadata_model_json = {} + features_results_metadata_model_json['authors'] = [author_model] + features_results_metadata_model_json['publication_date'] = 'testString' + features_results_metadata_model_json['title'] = 'testString' + features_results_metadata_model_json['image'] = 'testString' + features_results_metadata_model_json['feeds'] = [feed_model] + + # Construct a model instance of FeaturesResultsMetadata by calling from_dict on the json representation + features_results_metadata_model = FeaturesResultsMetadata.from_dict(features_results_metadata_model_json) + assert features_results_metadata_model != False + + # Construct a model instance of FeaturesResultsMetadata by calling from_dict on the json representation + features_results_metadata_model_dict = FeaturesResultsMetadata.from_dict(features_results_metadata_model_json).__dict__ + features_results_metadata_model2 = FeaturesResultsMetadata(**features_results_metadata_model_dict) + + # Verify the model instances are equivalent + assert features_results_metadata_model == features_results_metadata_model2 + + # Convert model instance back to dict and verify no loss of data + features_results_metadata_model_json2 = features_results_metadata_model.to_dict() + assert features_results_metadata_model_json2 == features_results_metadata_model_json + +class TestFeed(): + """ + Test Class for Feed + """ + + def test_feed_serialization(self): + """ + Test serialization/deserialization for Feed + """ + + # Construct a json representation of a Feed model + feed_model_json = {} + feed_model_json['link'] = 'testString' + + # Construct a model instance of Feed by calling from_dict on the json representation + feed_model = Feed.from_dict(feed_model_json) + assert feed_model != False + + # Construct a model instance of Feed by calling from_dict on the json representation + feed_model_dict = Feed.from_dict(feed_model_json).__dict__ + feed_model2 = Feed(**feed_model_dict) + + # Verify the model instances are equivalent + assert feed_model == feed_model2 + + # Convert model instance back to dict and verify no loss of data + feed_model_json2 = feed_model.to_dict() + assert feed_model_json2 == feed_model_json + +class TestKeywordsOptions(): + """ + Test Class for KeywordsOptions + """ + + def test_keywords_options_serialization(self): + """ + Test serialization/deserialization for KeywordsOptions + """ + + # Construct a json representation of a KeywordsOptions model + keywords_options_model_json = {} + keywords_options_model_json['limit'] = 250 + keywords_options_model_json['sentiment'] = True + keywords_options_model_json['emotion'] = True + + # Construct a model instance of KeywordsOptions by calling from_dict on the json representation + keywords_options_model = KeywordsOptions.from_dict(keywords_options_model_json) + assert keywords_options_model != False + + # Construct a model instance of KeywordsOptions by calling from_dict on the json representation + keywords_options_model_dict = KeywordsOptions.from_dict(keywords_options_model_json).__dict__ + keywords_options_model2 = KeywordsOptions(**keywords_options_model_dict) + + # Verify the model instances are equivalent + assert keywords_options_model == keywords_options_model2 + + # Convert model instance back to dict and verify no loss of data + keywords_options_model_json2 = keywords_options_model.to_dict() + assert keywords_options_model_json2 == keywords_options_model_json + +class TestKeywordsResult(): + """ + Test Class for KeywordsResult + """ + + def test_keywords_result_serialization(self): + """ + Test serialization/deserialization for KeywordsResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + emotion_scores_model = {} # EmotionScores + emotion_scores_model['anger'] = 72.5 + emotion_scores_model['disgust'] = 72.5 + emotion_scores_model['fear'] = 72.5 + emotion_scores_model['joy'] = 72.5 + emotion_scores_model['sadness'] = 72.5 + + feature_sentiment_results_model = {} # FeatureSentimentResults + feature_sentiment_results_model['score'] = 72.5 + + # Construct a json representation of a KeywordsResult model + keywords_result_model_json = {} + keywords_result_model_json['count'] = 38 + keywords_result_model_json['relevance'] = 72.5 + keywords_result_model_json['text'] = 'testString' + keywords_result_model_json['emotion'] = emotion_scores_model + keywords_result_model_json['sentiment'] = feature_sentiment_results_model + + # Construct a model instance of KeywordsResult by calling from_dict on the json representation + keywords_result_model = KeywordsResult.from_dict(keywords_result_model_json) + assert keywords_result_model != False + + # Construct a model instance of KeywordsResult by calling from_dict on the json representation + keywords_result_model_dict = KeywordsResult.from_dict(keywords_result_model_json).__dict__ + keywords_result_model2 = KeywordsResult(**keywords_result_model_dict) + + # Verify the model instances are equivalent + assert keywords_result_model == keywords_result_model2 + + # Convert model instance back to dict and verify no loss of data + keywords_result_model_json2 = keywords_result_model.to_dict() + assert keywords_result_model_json2 == keywords_result_model_json + +class TestListModelsResults(): + """ + Test Class for ListModelsResults + """ + + def test_list_models_results_serialization(self): + """ + Test serialization/deserialization for ListModelsResults + """ + + # Construct dict forms of any model objects needed in order to build this model. + + model_model = {} # Model + model_model['status'] = 'starting' + model_model['model_id'] = 'testString' + model_model['language'] = 'testString' + model_model['description'] = 'testString' + model_model['workspace_id'] = 'testString' + model_model['model_version'] = 'testString' + model_model['version'] = 'testString' + model_model['version_description'] = 'testString' + model_model['created'] = '2020-01-28T18:40:40.123456Z' + + # Construct a json representation of a ListModelsResults model + list_models_results_model_json = {} + list_models_results_model_json['models'] = [model_model] + + # Construct a model instance of ListModelsResults by calling from_dict on the json representation + list_models_results_model = ListModelsResults.from_dict(list_models_results_model_json) + assert list_models_results_model != False + + # Construct a model instance of ListModelsResults by calling from_dict on the json representation + list_models_results_model_dict = ListModelsResults.from_dict(list_models_results_model_json).__dict__ + list_models_results_model2 = ListModelsResults(**list_models_results_model_dict) + + # Verify the model instances are equivalent + assert list_models_results_model == list_models_results_model2 + + # Convert model instance back to dict and verify no loss of data + list_models_results_model_json2 = list_models_results_model.to_dict() + assert list_models_results_model_json2 == list_models_results_model_json + +class TestModel(): + """ + Test Class for Model + """ + + def test_model_serialization(self): + """ + Test serialization/deserialization for Model + """ + + # Construct a json representation of a Model model + model_model_json = {} + model_model_json['status'] = 'starting' + model_model_json['model_id'] = 'testString' + model_model_json['language'] = 'testString' + model_model_json['description'] = 'testString' + model_model_json['workspace_id'] = 'testString' + model_model_json['model_version'] = 'testString' + model_model_json['version'] = 'testString' + model_model_json['version_description'] = 'testString' + model_model_json['created'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of Model by calling from_dict on the json representation + model_model = Model.from_dict(model_model_json) + assert model_model != False + + # Construct a model instance of Model by calling from_dict on the json representation + model_model_dict = Model.from_dict(model_model_json).__dict__ + model_model2 = Model(**model_model_dict) + + # Verify the model instances are equivalent + assert model_model == model_model2 + + # Convert model instance back to dict and verify no loss of data + model_model_json2 = model_model.to_dict() + assert model_model_json2 == model_model_json + +class TestRelationArgument(): + """ + Test Class for RelationArgument + """ + + def test_relation_argument_serialization(self): + """ + Test serialization/deserialization for RelationArgument + """ + + # Construct dict forms of any model objects needed in order to build this model. + + relation_entity_model = {} # RelationEntity + relation_entity_model['text'] = 'testString' + relation_entity_model['type'] = 'testString' + + # Construct a json representation of a RelationArgument model + relation_argument_model_json = {} + relation_argument_model_json['entities'] = [relation_entity_model] + relation_argument_model_json['location'] = [38] + relation_argument_model_json['text'] = 'testString' + + # Construct a model instance of RelationArgument by calling from_dict on the json representation + relation_argument_model = RelationArgument.from_dict(relation_argument_model_json) + assert relation_argument_model != False + + # Construct a model instance of RelationArgument by calling from_dict on the json representation + relation_argument_model_dict = RelationArgument.from_dict(relation_argument_model_json).__dict__ + relation_argument_model2 = RelationArgument(**relation_argument_model_dict) + + # Verify the model instances are equivalent + assert relation_argument_model == relation_argument_model2 + + # Convert model instance back to dict and verify no loss of data + relation_argument_model_json2 = relation_argument_model.to_dict() + assert relation_argument_model_json2 == relation_argument_model_json + +class TestRelationEntity(): + """ + Test Class for RelationEntity + """ + + def test_relation_entity_serialization(self): + """ + Test serialization/deserialization for RelationEntity + """ + + # Construct a json representation of a RelationEntity model + relation_entity_model_json = {} + relation_entity_model_json['text'] = 'testString' + relation_entity_model_json['type'] = 'testString' + + # Construct a model instance of RelationEntity by calling from_dict on the json representation + relation_entity_model = RelationEntity.from_dict(relation_entity_model_json) + assert relation_entity_model != False + + # Construct a model instance of RelationEntity by calling from_dict on the json representation + relation_entity_model_dict = RelationEntity.from_dict(relation_entity_model_json).__dict__ + relation_entity_model2 = RelationEntity(**relation_entity_model_dict) + + # Verify the model instances are equivalent + assert relation_entity_model == relation_entity_model2 + + # Convert model instance back to dict and verify no loss of data + relation_entity_model_json2 = relation_entity_model.to_dict() + assert relation_entity_model_json2 == relation_entity_model_json + +class TestRelationsOptions(): + """ + Test Class for RelationsOptions + """ + + def test_relations_options_serialization(self): + """ + Test serialization/deserialization for RelationsOptions + """ + + # Construct a json representation of a RelationsOptions model + relations_options_model_json = {} + relations_options_model_json['model'] = 'testString' + + # Construct a model instance of RelationsOptions by calling from_dict on the json representation + relations_options_model = RelationsOptions.from_dict(relations_options_model_json) + assert relations_options_model != False + + # Construct a model instance of RelationsOptions by calling from_dict on the json representation + relations_options_model_dict = RelationsOptions.from_dict(relations_options_model_json).__dict__ + relations_options_model2 = RelationsOptions(**relations_options_model_dict) + + # Verify the model instances are equivalent + assert relations_options_model == relations_options_model2 + + # Convert model instance back to dict and verify no loss of data + relations_options_model_json2 = relations_options_model.to_dict() + assert relations_options_model_json2 == relations_options_model_json + +class TestRelationsResult(): + """ + Test Class for RelationsResult + """ + + def test_relations_result_serialization(self): + """ + Test serialization/deserialization for RelationsResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + relation_entity_model = {} # RelationEntity + relation_entity_model['text'] = 'testString' + relation_entity_model['type'] = 'testString' + + relation_argument_model = {} # RelationArgument + relation_argument_model['entities'] = [relation_entity_model] + relation_argument_model['location'] = [38] + relation_argument_model['text'] = 'testString' + + # Construct a json representation of a RelationsResult model + relations_result_model_json = {} + relations_result_model_json['score'] = 72.5 + relations_result_model_json['sentence'] = 'testString' + relations_result_model_json['type'] = 'testString' + relations_result_model_json['arguments'] = [relation_argument_model] + + # Construct a model instance of RelationsResult by calling from_dict on the json representation + relations_result_model = RelationsResult.from_dict(relations_result_model_json) + assert relations_result_model != False + + # Construct a model instance of RelationsResult by calling from_dict on the json representation + relations_result_model_dict = RelationsResult.from_dict(relations_result_model_json).__dict__ + relations_result_model2 = RelationsResult(**relations_result_model_dict) + + # Verify the model instances are equivalent + assert relations_result_model == relations_result_model2 + + # Convert model instance back to dict and verify no loss of data + relations_result_model_json2 = relations_result_model.to_dict() + assert relations_result_model_json2 == relations_result_model_json + +class TestSemanticRolesEntity(): + """ + Test Class for SemanticRolesEntity + """ + + def test_semantic_roles_entity_serialization(self): + """ + Test serialization/deserialization for SemanticRolesEntity + """ + + # Construct a json representation of a SemanticRolesEntity model + semantic_roles_entity_model_json = {} + semantic_roles_entity_model_json['type'] = 'testString' + semantic_roles_entity_model_json['text'] = 'testString' + + # Construct a model instance of SemanticRolesEntity by calling from_dict on the json representation + semantic_roles_entity_model = SemanticRolesEntity.from_dict(semantic_roles_entity_model_json) + assert semantic_roles_entity_model != False + + # Construct a model instance of SemanticRolesEntity by calling from_dict on the json representation + semantic_roles_entity_model_dict = SemanticRolesEntity.from_dict(semantic_roles_entity_model_json).__dict__ + semantic_roles_entity_model2 = SemanticRolesEntity(**semantic_roles_entity_model_dict) + + # Verify the model instances are equivalent + assert semantic_roles_entity_model == semantic_roles_entity_model2 + + # Convert model instance back to dict and verify no loss of data + semantic_roles_entity_model_json2 = semantic_roles_entity_model.to_dict() + assert semantic_roles_entity_model_json2 == semantic_roles_entity_model_json + +class TestSemanticRolesKeyword(): + """ + Test Class for SemanticRolesKeyword + """ + + def test_semantic_roles_keyword_serialization(self): + """ + Test serialization/deserialization for SemanticRolesKeyword + """ + + # Construct a json representation of a SemanticRolesKeyword model + semantic_roles_keyword_model_json = {} + semantic_roles_keyword_model_json['text'] = 'testString' + + # Construct a model instance of SemanticRolesKeyword by calling from_dict on the json representation + semantic_roles_keyword_model = SemanticRolesKeyword.from_dict(semantic_roles_keyword_model_json) + assert semantic_roles_keyword_model != False + + # Construct a model instance of SemanticRolesKeyword by calling from_dict on the json representation + semantic_roles_keyword_model_dict = SemanticRolesKeyword.from_dict(semantic_roles_keyword_model_json).__dict__ + semantic_roles_keyword_model2 = SemanticRolesKeyword(**semantic_roles_keyword_model_dict) + + # Verify the model instances are equivalent + assert semantic_roles_keyword_model == semantic_roles_keyword_model2 + + # Convert model instance back to dict and verify no loss of data + semantic_roles_keyword_model_json2 = semantic_roles_keyword_model.to_dict() + assert semantic_roles_keyword_model_json2 == semantic_roles_keyword_model_json + +class TestSemanticRolesOptions(): + """ + Test Class for SemanticRolesOptions + """ + + def test_semantic_roles_options_serialization(self): + """ + Test serialization/deserialization for SemanticRolesOptions + """ + + # Construct a json representation of a SemanticRolesOptions model + semantic_roles_options_model_json = {} + semantic_roles_options_model_json['limit'] = 38 + semantic_roles_options_model_json['keywords'] = True + semantic_roles_options_model_json['entities'] = True + + # Construct a model instance of SemanticRolesOptions by calling from_dict on the json representation + semantic_roles_options_model = SemanticRolesOptions.from_dict(semantic_roles_options_model_json) + assert semantic_roles_options_model != False + + # Construct a model instance of SemanticRolesOptions by calling from_dict on the json representation + semantic_roles_options_model_dict = SemanticRolesOptions.from_dict(semantic_roles_options_model_json).__dict__ + semantic_roles_options_model2 = SemanticRolesOptions(**semantic_roles_options_model_dict) + + # Verify the model instances are equivalent + assert semantic_roles_options_model == semantic_roles_options_model2 + + # Convert model instance back to dict and verify no loss of data + semantic_roles_options_model_json2 = semantic_roles_options_model.to_dict() + assert semantic_roles_options_model_json2 == semantic_roles_options_model_json + +class TestSemanticRolesResult(): + """ + Test Class for SemanticRolesResult + """ + + def test_semantic_roles_result_serialization(self): + """ + Test serialization/deserialization for SemanticRolesResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + semantic_roles_entity_model = {} # SemanticRolesEntity + semantic_roles_entity_model['type'] = 'testString' + semantic_roles_entity_model['text'] = 'testString' + + semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model['text'] = 'testString' + + semantic_roles_result_subject_model = {} # SemanticRolesResultSubject + semantic_roles_result_subject_model['text'] = 'testString' + semantic_roles_result_subject_model['entities'] = [semantic_roles_entity_model] + semantic_roles_result_subject_model['keywords'] = [semantic_roles_keyword_model] + + semantic_roles_verb_model = {} # SemanticRolesVerb + semantic_roles_verb_model['text'] = 'testString' + semantic_roles_verb_model['tense'] = 'testString' + + semantic_roles_result_action_model = {} # SemanticRolesResultAction + semantic_roles_result_action_model['text'] = 'testString' + semantic_roles_result_action_model['normalized'] = 'testString' + semantic_roles_result_action_model['verb'] = semantic_roles_verb_model + + semantic_roles_result_object_model = {} # SemanticRolesResultObject + semantic_roles_result_object_model['text'] = 'testString' + semantic_roles_result_object_model['keywords'] = [semantic_roles_keyword_model] + + # Construct a json representation of a SemanticRolesResult model + semantic_roles_result_model_json = {} + semantic_roles_result_model_json['sentence'] = 'testString' + semantic_roles_result_model_json['subject'] = semantic_roles_result_subject_model + semantic_roles_result_model_json['action'] = semantic_roles_result_action_model + semantic_roles_result_model_json['object'] = semantic_roles_result_object_model + + # Construct a model instance of SemanticRolesResult by calling from_dict on the json representation + semantic_roles_result_model = SemanticRolesResult.from_dict(semantic_roles_result_model_json) + assert semantic_roles_result_model != False + + # Construct a model instance of SemanticRolesResult by calling from_dict on the json representation + semantic_roles_result_model_dict = SemanticRolesResult.from_dict(semantic_roles_result_model_json).__dict__ + semantic_roles_result_model2 = SemanticRolesResult(**semantic_roles_result_model_dict) + + # Verify the model instances are equivalent + assert semantic_roles_result_model == semantic_roles_result_model2 + + # Convert model instance back to dict and verify no loss of data + semantic_roles_result_model_json2 = semantic_roles_result_model.to_dict() + assert semantic_roles_result_model_json2 == semantic_roles_result_model_json + +class TestSemanticRolesResultAction(): + """ + Test Class for SemanticRolesResultAction + """ + + def test_semantic_roles_result_action_serialization(self): + """ + Test serialization/deserialization for SemanticRolesResultAction + """ + + # Construct dict forms of any model objects needed in order to build this model. + + semantic_roles_verb_model = {} # SemanticRolesVerb + semantic_roles_verb_model['text'] = 'testString' + semantic_roles_verb_model['tense'] = 'testString' + + # Construct a json representation of a SemanticRolesResultAction model + semantic_roles_result_action_model_json = {} + semantic_roles_result_action_model_json['text'] = 'testString' + semantic_roles_result_action_model_json['normalized'] = 'testString' + semantic_roles_result_action_model_json['verb'] = semantic_roles_verb_model + + # Construct a model instance of SemanticRolesResultAction by calling from_dict on the json representation + semantic_roles_result_action_model = SemanticRolesResultAction.from_dict(semantic_roles_result_action_model_json) + assert semantic_roles_result_action_model != False + + # Construct a model instance of SemanticRolesResultAction by calling from_dict on the json representation + semantic_roles_result_action_model_dict = SemanticRolesResultAction.from_dict(semantic_roles_result_action_model_json).__dict__ + semantic_roles_result_action_model2 = SemanticRolesResultAction(**semantic_roles_result_action_model_dict) + + # Verify the model instances are equivalent + assert semantic_roles_result_action_model == semantic_roles_result_action_model2 + + # Convert model instance back to dict and verify no loss of data + semantic_roles_result_action_model_json2 = semantic_roles_result_action_model.to_dict() + assert semantic_roles_result_action_model_json2 == semantic_roles_result_action_model_json + +class TestSemanticRolesResultObject(): + """ + Test Class for SemanticRolesResultObject + """ + + def test_semantic_roles_result_object_serialization(self): + """ + Test serialization/deserialization for SemanticRolesResultObject + """ + + # Construct dict forms of any model objects needed in order to build this model. + + semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model['text'] = 'testString' + + # Construct a json representation of a SemanticRolesResultObject model + semantic_roles_result_object_model_json = {} + semantic_roles_result_object_model_json['text'] = 'testString' + semantic_roles_result_object_model_json['keywords'] = [semantic_roles_keyword_model] + + # Construct a model instance of SemanticRolesResultObject by calling from_dict on the json representation + semantic_roles_result_object_model = SemanticRolesResultObject.from_dict(semantic_roles_result_object_model_json) + assert semantic_roles_result_object_model != False + + # Construct a model instance of SemanticRolesResultObject by calling from_dict on the json representation + semantic_roles_result_object_model_dict = SemanticRolesResultObject.from_dict(semantic_roles_result_object_model_json).__dict__ + semantic_roles_result_object_model2 = SemanticRolesResultObject(**semantic_roles_result_object_model_dict) + + # Verify the model instances are equivalent + assert semantic_roles_result_object_model == semantic_roles_result_object_model2 + + # Convert model instance back to dict and verify no loss of data + semantic_roles_result_object_model_json2 = semantic_roles_result_object_model.to_dict() + assert semantic_roles_result_object_model_json2 == semantic_roles_result_object_model_json + +class TestSemanticRolesResultSubject(): + """ + Test Class for SemanticRolesResultSubject + """ + + def test_semantic_roles_result_subject_serialization(self): + """ + Test serialization/deserialization for SemanticRolesResultSubject + """ + + # Construct dict forms of any model objects needed in order to build this model. + + semantic_roles_entity_model = {} # SemanticRolesEntity + semantic_roles_entity_model['type'] = 'testString' + semantic_roles_entity_model['text'] = 'testString' + + semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model['text'] = 'testString' + + # Construct a json representation of a SemanticRolesResultSubject model + semantic_roles_result_subject_model_json = {} + semantic_roles_result_subject_model_json['text'] = 'testString' + semantic_roles_result_subject_model_json['entities'] = [semantic_roles_entity_model] + semantic_roles_result_subject_model_json['keywords'] = [semantic_roles_keyword_model] + + # Construct a model instance of SemanticRolesResultSubject by calling from_dict on the json representation + semantic_roles_result_subject_model = SemanticRolesResultSubject.from_dict(semantic_roles_result_subject_model_json) + assert semantic_roles_result_subject_model != False + + # Construct a model instance of SemanticRolesResultSubject by calling from_dict on the json representation + semantic_roles_result_subject_model_dict = SemanticRolesResultSubject.from_dict(semantic_roles_result_subject_model_json).__dict__ + semantic_roles_result_subject_model2 = SemanticRolesResultSubject(**semantic_roles_result_subject_model_dict) + + # Verify the model instances are equivalent + assert semantic_roles_result_subject_model == semantic_roles_result_subject_model2 + + # Convert model instance back to dict and verify no loss of data + semantic_roles_result_subject_model_json2 = semantic_roles_result_subject_model.to_dict() + assert semantic_roles_result_subject_model_json2 == semantic_roles_result_subject_model_json + +class TestSemanticRolesVerb(): + """ + Test Class for SemanticRolesVerb + """ + + def test_semantic_roles_verb_serialization(self): + """ + Test serialization/deserialization for SemanticRolesVerb + """ + + # Construct a json representation of a SemanticRolesVerb model + semantic_roles_verb_model_json = {} + semantic_roles_verb_model_json['text'] = 'testString' + semantic_roles_verb_model_json['tense'] = 'testString' + + # Construct a model instance of SemanticRolesVerb by calling from_dict on the json representation + semantic_roles_verb_model = SemanticRolesVerb.from_dict(semantic_roles_verb_model_json) + assert semantic_roles_verb_model != False + + # Construct a model instance of SemanticRolesVerb by calling from_dict on the json representation + semantic_roles_verb_model_dict = SemanticRolesVerb.from_dict(semantic_roles_verb_model_json).__dict__ + semantic_roles_verb_model2 = SemanticRolesVerb(**semantic_roles_verb_model_dict) + + # Verify the model instances are equivalent + assert semantic_roles_verb_model == semantic_roles_verb_model2 + + # Convert model instance back to dict and verify no loss of data + semantic_roles_verb_model_json2 = semantic_roles_verb_model.to_dict() + assert semantic_roles_verb_model_json2 == semantic_roles_verb_model_json + +class TestSentenceResult(): + """ + Test Class for SentenceResult + """ + + def test_sentence_result_serialization(self): + """ + Test serialization/deserialization for SentenceResult + """ + + # Construct a json representation of a SentenceResult model + sentence_result_model_json = {} + sentence_result_model_json['text'] = 'testString' + sentence_result_model_json['location'] = [38] + + # Construct a model instance of SentenceResult by calling from_dict on the json representation + sentence_result_model = SentenceResult.from_dict(sentence_result_model_json) + assert sentence_result_model != False + + # Construct a model instance of SentenceResult by calling from_dict on the json representation + sentence_result_model_dict = SentenceResult.from_dict(sentence_result_model_json).__dict__ + sentence_result_model2 = SentenceResult(**sentence_result_model_dict) + + # Verify the model instances are equivalent + assert sentence_result_model == sentence_result_model2 + + # Convert model instance back to dict and verify no loss of data + sentence_result_model_json2 = sentence_result_model.to_dict() + assert sentence_result_model_json2 == sentence_result_model_json + +class TestSentimentOptions(): + """ + Test Class for SentimentOptions + """ + + def test_sentiment_options_serialization(self): + """ + Test serialization/deserialization for SentimentOptions + """ + + # Construct a json representation of a SentimentOptions model + sentiment_options_model_json = {} + sentiment_options_model_json['document'] = True + sentiment_options_model_json['targets'] = ['testString'] + + # Construct a model instance of SentimentOptions by calling from_dict on the json representation + sentiment_options_model = SentimentOptions.from_dict(sentiment_options_model_json) + assert sentiment_options_model != False + + # Construct a model instance of SentimentOptions by calling from_dict on the json representation + sentiment_options_model_dict = SentimentOptions.from_dict(sentiment_options_model_json).__dict__ + sentiment_options_model2 = SentimentOptions(**sentiment_options_model_dict) + + # Verify the model instances are equivalent + assert sentiment_options_model == sentiment_options_model2 + + # Convert model instance back to dict and verify no loss of data + sentiment_options_model_json2 = sentiment_options_model.to_dict() + assert sentiment_options_model_json2 == sentiment_options_model_json + +class TestSentimentResult(): + """ + Test Class for SentimentResult + """ + + def test_sentiment_result_serialization(self): + """ + Test serialization/deserialization for SentimentResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_sentiment_results_model = {} # DocumentSentimentResults + document_sentiment_results_model['label'] = 'positive' + document_sentiment_results_model['score'] = 0.127034 + + targeted_sentiment_results_model = {} # TargetedSentimentResults + targeted_sentiment_results_model['text'] = 'stocks' + targeted_sentiment_results_model['score'] = 0.279964 + + # Construct a json representation of a SentimentResult model + sentiment_result_model_json = {} + sentiment_result_model_json['document'] = document_sentiment_results_model + sentiment_result_model_json['targets'] = [targeted_sentiment_results_model] + + # Construct a model instance of SentimentResult by calling from_dict on the json representation + sentiment_result_model = SentimentResult.from_dict(sentiment_result_model_json) + assert sentiment_result_model != False + + # Construct a model instance of SentimentResult by calling from_dict on the json representation + sentiment_result_model_dict = SentimentResult.from_dict(sentiment_result_model_json).__dict__ + sentiment_result_model2 = SentimentResult(**sentiment_result_model_dict) + + # Verify the model instances are equivalent + assert sentiment_result_model == sentiment_result_model2 + + # Convert model instance back to dict and verify no loss of data + sentiment_result_model_json2 = sentiment_result_model.to_dict() + assert sentiment_result_model_json2 == sentiment_result_model_json + +class TestSyntaxOptions(): + """ + Test Class for SyntaxOptions + """ + + def test_syntax_options_serialization(self): + """ + Test serialization/deserialization for SyntaxOptions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + syntax_options_tokens_model = {} # SyntaxOptionsTokens + syntax_options_tokens_model['lemma'] = True + syntax_options_tokens_model['part_of_speech'] = True + + # Construct a json representation of a SyntaxOptions model + syntax_options_model_json = {} + syntax_options_model_json['tokens'] = syntax_options_tokens_model + syntax_options_model_json['sentences'] = True + + # Construct a model instance of SyntaxOptions by calling from_dict on the json representation + syntax_options_model = SyntaxOptions.from_dict(syntax_options_model_json) + assert syntax_options_model != False + + # Construct a model instance of SyntaxOptions by calling from_dict on the json representation + syntax_options_model_dict = SyntaxOptions.from_dict(syntax_options_model_json).__dict__ + syntax_options_model2 = SyntaxOptions(**syntax_options_model_dict) + + # Verify the model instances are equivalent + assert syntax_options_model == syntax_options_model2 + + # Convert model instance back to dict and verify no loss of data + syntax_options_model_json2 = syntax_options_model.to_dict() + assert syntax_options_model_json2 == syntax_options_model_json + +class TestSyntaxOptionsTokens(): + """ + Test Class for SyntaxOptionsTokens + """ + + def test_syntax_options_tokens_serialization(self): + """ + Test serialization/deserialization for SyntaxOptionsTokens + """ + + # Construct a json representation of a SyntaxOptionsTokens model + syntax_options_tokens_model_json = {} + syntax_options_tokens_model_json['lemma'] = True + syntax_options_tokens_model_json['part_of_speech'] = True + + # Construct a model instance of SyntaxOptionsTokens by calling from_dict on the json representation + syntax_options_tokens_model = SyntaxOptionsTokens.from_dict(syntax_options_tokens_model_json) + assert syntax_options_tokens_model != False + + # Construct a model instance of SyntaxOptionsTokens by calling from_dict on the json representation + syntax_options_tokens_model_dict = SyntaxOptionsTokens.from_dict(syntax_options_tokens_model_json).__dict__ + syntax_options_tokens_model2 = SyntaxOptionsTokens(**syntax_options_tokens_model_dict) + + # Verify the model instances are equivalent + assert syntax_options_tokens_model == syntax_options_tokens_model2 + + # Convert model instance back to dict and verify no loss of data + syntax_options_tokens_model_json2 = syntax_options_tokens_model.to_dict() + assert syntax_options_tokens_model_json2 == syntax_options_tokens_model_json + +class TestSyntaxResult(): + """ + Test Class for SyntaxResult + """ + + def test_syntax_result_serialization(self): + """ + Test serialization/deserialization for SyntaxResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + token_result_model = {} # TokenResult + token_result_model['text'] = 'testString' + token_result_model['part_of_speech'] = 'ADJ' + token_result_model['location'] = [38] + token_result_model['lemma'] = 'testString' + + sentence_result_model = {} # SentenceResult + sentence_result_model['text'] = 'testString' + sentence_result_model['location'] = [38] + + # Construct a json representation of a SyntaxResult model + syntax_result_model_json = {} + syntax_result_model_json['tokens'] = [token_result_model] + syntax_result_model_json['sentences'] = [sentence_result_model] + + # Construct a model instance of SyntaxResult by calling from_dict on the json representation + syntax_result_model = SyntaxResult.from_dict(syntax_result_model_json) + assert syntax_result_model != False + + # Construct a model instance of SyntaxResult by calling from_dict on the json representation + syntax_result_model_dict = SyntaxResult.from_dict(syntax_result_model_json).__dict__ + syntax_result_model2 = SyntaxResult(**syntax_result_model_dict) + + # Verify the model instances are equivalent + assert syntax_result_model == syntax_result_model2 + + # Convert model instance back to dict and verify no loss of data + syntax_result_model_json2 = syntax_result_model.to_dict() + assert syntax_result_model_json2 == syntax_result_model_json + +class TestTargetedEmotionResults(): + """ + Test Class for TargetedEmotionResults + """ + + def test_targeted_emotion_results_serialization(self): + """ + Test serialization/deserialization for TargetedEmotionResults + """ + + # Construct dict forms of any model objects needed in order to build this model. + + emotion_scores_model = {} # EmotionScores + emotion_scores_model['anger'] = 72.5 + emotion_scores_model['disgust'] = 72.5 + emotion_scores_model['fear'] = 72.5 + emotion_scores_model['joy'] = 72.5 + emotion_scores_model['sadness'] = 72.5 + + # Construct a json representation of a TargetedEmotionResults model + targeted_emotion_results_model_json = {} + targeted_emotion_results_model_json['text'] = 'testString' + targeted_emotion_results_model_json['emotion'] = emotion_scores_model + + # Construct a model instance of TargetedEmotionResults by calling from_dict on the json representation + targeted_emotion_results_model = TargetedEmotionResults.from_dict(targeted_emotion_results_model_json) + assert targeted_emotion_results_model != False + + # Construct a model instance of TargetedEmotionResults by calling from_dict on the json representation + targeted_emotion_results_model_dict = TargetedEmotionResults.from_dict(targeted_emotion_results_model_json).__dict__ + targeted_emotion_results_model2 = TargetedEmotionResults(**targeted_emotion_results_model_dict) + + # Verify the model instances are equivalent + assert targeted_emotion_results_model == targeted_emotion_results_model2 + + # Convert model instance back to dict and verify no loss of data + targeted_emotion_results_model_json2 = targeted_emotion_results_model.to_dict() + assert targeted_emotion_results_model_json2 == targeted_emotion_results_model_json + +class TestTargetedSentimentResults(): + """ + Test Class for TargetedSentimentResults + """ + + def test_targeted_sentiment_results_serialization(self): + """ + Test serialization/deserialization for TargetedSentimentResults + """ + + # Construct a json representation of a TargetedSentimentResults model + targeted_sentiment_results_model_json = {} + targeted_sentiment_results_model_json['text'] = 'testString' + targeted_sentiment_results_model_json['score'] = 72.5 + + # Construct a model instance of TargetedSentimentResults by calling from_dict on the json representation + targeted_sentiment_results_model = TargetedSentimentResults.from_dict(targeted_sentiment_results_model_json) + assert targeted_sentiment_results_model != False + + # Construct a model instance of TargetedSentimentResults by calling from_dict on the json representation + targeted_sentiment_results_model_dict = TargetedSentimentResults.from_dict(targeted_sentiment_results_model_json).__dict__ + targeted_sentiment_results_model2 = TargetedSentimentResults(**targeted_sentiment_results_model_dict) + + # Verify the model instances are equivalent + assert targeted_sentiment_results_model == targeted_sentiment_results_model2 + + # Convert model instance back to dict and verify no loss of data + targeted_sentiment_results_model_json2 = targeted_sentiment_results_model.to_dict() + assert targeted_sentiment_results_model_json2 == targeted_sentiment_results_model_json + +class TestTokenResult(): + """ + Test Class for TokenResult + """ + + def test_token_result_serialization(self): + """ + Test serialization/deserialization for TokenResult + """ + + # Construct a json representation of a TokenResult model + token_result_model_json = {} + token_result_model_json['text'] = 'testString' + token_result_model_json['part_of_speech'] = 'ADJ' + token_result_model_json['location'] = [38] + token_result_model_json['lemma'] = 'testString' + + # Construct a model instance of TokenResult by calling from_dict on the json representation + token_result_model = TokenResult.from_dict(token_result_model_json) + assert token_result_model != False + + # Construct a model instance of TokenResult by calling from_dict on the json representation + token_result_model_dict = TokenResult.from_dict(token_result_model_json).__dict__ + token_result_model2 = TokenResult(**token_result_model_dict) + + # Verify the model instances are equivalent + assert token_result_model == token_result_model2 + + # Convert model instance back to dict and verify no loss of data + token_result_model_json2 = token_result_model.to_dict() + assert token_result_model_json2 == token_result_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index e36cce0c1..5b052a010 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -13,97 +13,205 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Unit Tests for PersonalityInsightsV3 +""" + from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect import json import pytest +import re +import requests import responses -import ibm_watson.personality_insights_v3 +import urllib from ibm_watson.personality_insights_v3 import * +version = 'testString' + +service = PersonalityInsightsV3( + authenticator=NoAuthAuthenticator(), + version=version + ) + base_url = 'https://api.us-south.personality-insights.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: Methods ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for profile -#----------------------------------------------------------------------------- class TestProfile(): + """ + Test Class for profile + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_profile_response(self): - body = self.construct_full_body() - response = fake_response_Profile_json - send_request(self, body, response) + def test_profile_all_params(self): + """ + profile() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/profile') + mock_response = '{"processed_language": "ar", "word_count": 10, "word_count_message": "word_count_message", "personality": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "needs": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "values": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "behavior": [{"trait_id": "trait_id", "name": "name", "category": "category", "percentage": 10}], "consumption_preferences": [{"consumption_preference_category_id": "consumption_preference_category_id", "name": "name", "consumption_preferences": [{"consumption_preference_id": "consumption_preference_id", "name": "name", "score": 0.0}]}], "warnings": [{"warning_id": "WORD_COUNT_MESSAGE", "message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ContentItem model + content_item_model = {} + content_item_model['content'] = 'testString' + content_item_model['id'] = 'testString' + content_item_model['created'] = 26 + content_item_model['updated'] = 26 + content_item_model['contenttype'] = 'text/plain' + content_item_model['language'] = 'ar' + content_item_model['parentid'] = 'testString' + content_item_model['reply'] = True + content_item_model['forward'] = True + + # Construct a dict representation of a Content model + content_model = {} + content_model['contentItems'] = [content_item_model] + + # Set up parameter values + content = content_model + accept = 'application/json' + content_type = 'application/json' + content_language = 'ar' + accept_language = 'ar' + raw_scores = True + csv_headers = True + consumption_preferences = True + + # Invoke method + response = service.profile( + content, + accept, + content_type=content_type, + content_language=content_language, + accept_language=accept_language, + raw_scores=raw_scores, + csv_headers=csv_headers, + consumption_preferences=consumption_preferences, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'raw_scores={}'.format('true' if raw_scores else 'false') in query_string + assert 'csv_headers={}'.format('true' if csv_headers else 'false') in query_string + assert 'consumption_preferences={}'.format('true' if consumption_preferences else 'false') in query_string + # Validate body params + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_profile_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Profile_json - send_request(self, body, response) + def test_profile_required_params(self): + """ + test_profile_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/profile') + mock_response = '{"processed_language": "ar", "word_count": 10, "word_count_message": "word_count_message", "personality": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "needs": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "values": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "behavior": [{"trait_id": "trait_id", "name": "name", "category": "category", "percentage": 10}], "consumption_preferences": [{"consumption_preference_category_id": "consumption_preference_category_id", "name": "name", "consumption_preferences": [{"consumption_preference_id": "consumption_preference_id", "name": "name", "score": 0.0}]}], "warnings": [{"warning_id": "WORD_COUNT_MESSAGE", "message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ContentItem model + content_item_model = {} + content_item_model['content'] = 'testString' + content_item_model['id'] = 'testString' + content_item_model['created'] = 26 + content_item_model['updated'] = 26 + content_item_model['contenttype'] = 'text/plain' + content_item_model['language'] = 'ar' + content_item_model['parentid'] = 'testString' + content_item_model['reply'] = True + content_item_model['forward'] = True + + # Construct a dict representation of a Content model + content_model = {} + content_model['contentItems'] = [content_item_model] + + # Set up parameter values + content = content_model + accept = 'application/json' + + # Invoke method + response = service.profile( + content, + accept, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_profile_empty(self): - check_empty_required_params(self, fake_response_Profile_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/profile' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_profile_value_error(self): + """ + test_profile_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/profile') + mock_response = '{"processed_language": "ar", "word_count": 10, "word_count_message": "word_count_message", "personality": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "needs": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "values": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "behavior": [{"trait_id": "trait_id", "name": "name", "category": "category", "percentage": 10}], "consumption_preferences": [{"consumption_preference_category_id": "consumption_preference_category_id", "name": "name", "consumption_preferences": [{"consumption_preference_id": "consumption_preference_id", "name": "name", "score": 0.0}]}], "warnings": [{"warning_id": "WORD_COUNT_MESSAGE", "message": "message"}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = PersonalityInsightsV3( - authenticator=NoAuthAuthenticator(), - version='2017-10-13', - ) - service.set_service_url(base_url) - output = service.profile(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"content": {"mock": "data"}}) - body['accept'] = "string1" - body['content_type'] = "string1" - body['content_language'] = "string1" - body['accept_language'] = "string1" - body['raw_scores'] = True - body['csv_headers'] = True - body['consumption_preferences'] = True - return body - - def construct_required_body(self): - body = dict() - body.update({"content": {"mock": "data"}}) - body['accept'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ContentItem model + content_item_model = {} + content_item_model['content'] = 'testString' + content_item_model['id'] = 'testString' + content_item_model['created'] = 26 + content_item_model['updated'] = 26 + content_item_model['contenttype'] = 'text/plain' + content_item_model['language'] = 'ar' + content_item_model['parentid'] = 'testString' + content_item_model['reply'] = True + content_item_model['forward'] = True + + # Construct a dict representation of a Content model + content_model = {} + content_model['contentItems'] = [content_item_model] + + # Set up parameter values + content = content_model + accept = 'application/json' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "content": content, + "accept": accept, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.profile(**req_copy) + # endregion @@ -112,68 +220,323 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestBehavior(): + """ + Test Class for Behavior + """ + + def test_behavior_serialization(self): + """ + Test serialization/deserialization for Behavior + """ + + # Construct a json representation of a Behavior model + behavior_model_json = {} + behavior_model_json['trait_id'] = 'testString' + behavior_model_json['name'] = 'testString' + behavior_model_json['category'] = 'testString' + behavior_model_json['percentage'] = 72.5 + + # Construct a model instance of Behavior by calling from_dict on the json representation + behavior_model = Behavior.from_dict(behavior_model_json) + assert behavior_model != False + + # Construct a model instance of Behavior by calling from_dict on the json representation + behavior_model_dict = Behavior.from_dict(behavior_model_json).__dict__ + behavior_model2 = Behavior(**behavior_model_dict) + + # Verify the model instances are equivalent + assert behavior_model == behavior_model2 + + # Convert model instance back to dict and verify no loss of data + behavior_model_json2 = behavior_model.to_dict() + assert behavior_model_json2 == behavior_model_json + +class TestConsumptionPreferences(): + """ + Test Class for ConsumptionPreferences + """ + + def test_consumption_preferences_serialization(self): + """ + Test serialization/deserialization for ConsumptionPreferences + """ + + # Construct a json representation of a ConsumptionPreferences model + consumption_preferences_model_json = {} + consumption_preferences_model_json['consumption_preference_id'] = 'testString' + consumption_preferences_model_json['name'] = 'testString' + consumption_preferences_model_json['score'] = 0.0 + + # Construct a model instance of ConsumptionPreferences by calling from_dict on the json representation + consumption_preferences_model = ConsumptionPreferences.from_dict(consumption_preferences_model_json) + assert consumption_preferences_model != False + + # Construct a model instance of ConsumptionPreferences by calling from_dict on the json representation + consumption_preferences_model_dict = ConsumptionPreferences.from_dict(consumption_preferences_model_json).__dict__ + consumption_preferences_model2 = ConsumptionPreferences(**consumption_preferences_model_dict) + + # Verify the model instances are equivalent + assert consumption_preferences_model == consumption_preferences_model2 + + # Convert model instance back to dict and verify no loss of data + consumption_preferences_model_json2 = consumption_preferences_model.to_dict() + assert consumption_preferences_model_json2 == consumption_preferences_model_json + +class TestConsumptionPreferencesCategory(): + """ + Test Class for ConsumptionPreferencesCategory + """ + + def test_consumption_preferences_category_serialization(self): + """ + Test serialization/deserialization for ConsumptionPreferencesCategory + """ + + # Construct dict forms of any model objects needed in order to build this model. + + consumption_preferences_model = {} # ConsumptionPreferences + consumption_preferences_model['consumption_preference_id'] = 'testString' + consumption_preferences_model['name'] = 'testString' + consumption_preferences_model['score'] = 0.0 + + # Construct a json representation of a ConsumptionPreferencesCategory model + consumption_preferences_category_model_json = {} + consumption_preferences_category_model_json['consumption_preference_category_id'] = 'testString' + consumption_preferences_category_model_json['name'] = 'testString' + consumption_preferences_category_model_json['consumption_preferences'] = [consumption_preferences_model] + + # Construct a model instance of ConsumptionPreferencesCategory by calling from_dict on the json representation + consumption_preferences_category_model = ConsumptionPreferencesCategory.from_dict(consumption_preferences_category_model_json) + assert consumption_preferences_category_model != False - Args: - obj: The generated test function + # Construct a model instance of ConsumptionPreferencesCategory by calling from_dict on the json representation + consumption_preferences_category_model_dict = ConsumptionPreferencesCategory.from_dict(consumption_preferences_category_model_json).__dict__ + consumption_preferences_category_model2 = ConsumptionPreferencesCategory(**consumption_preferences_category_model_dict) + # Verify the model instances are equivalent + assert consumption_preferences_category_model == consumption_preferences_category_model2 + + # Convert model instance back to dict and verify no loss of data + consumption_preferences_category_model_json2 = consumption_preferences_category_model.to_dict() + assert consumption_preferences_category_model_json2 == consumption_preferences_category_model_json + +class TestContent(): + """ + Test Class for Content """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data + def test_content_serialization(self): + """ + Test serialization/deserialization for Content + """ + + # Construct dict forms of any model objects needed in order to build this model. + + content_item_model = {} # ContentItem + content_item_model['content'] = 'testString' + content_item_model['id'] = 'testString' + content_item_model['created'] = 26 + content_item_model['updated'] = 26 + content_item_model['contenttype'] = 'text/plain' + content_item_model['language'] = 'ar' + content_item_model['parentid'] = 'testString' + content_item_model['reply'] = True + content_item_model['forward'] = True + + # Construct a json representation of a Content model + content_model_json = {} + content_model_json['contentItems'] = [content_item_model] + + # Construct a model instance of Content by calling from_dict on the json representation + content_model = Content.from_dict(content_model_json) + assert content_model != False + + # Construct a model instance of Content by calling from_dict on the json representation + content_model_dict = Content.from_dict(content_model_json).__dict__ + content_model2 = Content(**content_model_dict) + + # Verify the model instances are equivalent + assert content_model == content_model2 - Args: - obj: The generated test function + # Convert model instance back to dict and verify no loss of data + content_model_json2 = content_model.to_dict() + assert content_model_json2 == content_model_json +class TestContentItem(): """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error + Test Class for ContentItem + """ + + def test_content_item_serialization(self): + """ + Test serialization/deserialization for ContentItem + """ + + # Construct a json representation of a ContentItem model + content_item_model_json = {} + content_item_model_json['content'] = 'testString' + content_item_model_json['id'] = 'testString' + content_item_model_json['created'] = 26 + content_item_model_json['updated'] = 26 + content_item_model_json['contenttype'] = 'text/plain' + content_item_model_json['language'] = 'ar' + content_item_model_json['parentid'] = 'testString' + content_item_model_json['reply'] = True + content_item_model_json['forward'] = True -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request + # Construct a model instance of ContentItem by calling from_dict on the json representation + content_item_model = ContentItem.from_dict(content_item_model_json) + assert content_item_model != False - Args: - obj: The generated test function + # Construct a model instance of ContentItem by calling from_dict on the json representation + content_item_model_dict = ContentItem.from_dict(content_item_model_json).__dict__ + content_item_model2 = ContentItem(**content_item_model_dict) + # Verify the model instances are equivalent + assert content_item_model == content_item_model2 + + # Convert model instance back to dict and verify no loss of data + content_item_model_json2 = content_item_model.to_dict() + assert content_item_model_json2 == content_item_model_json + +class TestProfile(): """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) + Test Class for Profile + """ + + def test_profile_serialization(self): + """ + Test serialization/deserialization for Profile + """ + + # Construct dict forms of any model objects needed in order to build this model. + + trait_model = {} # Trait + trait_model['trait_id'] = 'big5_openness' + trait_model['name'] = 'Openness' + trait_model['category'] = 'personality' + trait_model['percentile'] = 0.8011555009553 + trait_model['raw_score'] = 0.77565404255038 + trait_model['significant'] = True + + behavior_model = {} # Behavior + behavior_model['trait_id'] = 'behavior_sunday' + behavior_model['name'] = 'Sunday' + behavior_model['category'] = 'behavior' + behavior_model['percentage'] = 0.21392532795156 + + consumption_preferences_model = {} # ConsumptionPreferences + consumption_preferences_model['consumption_preference_id'] = 'consumption_preferences_automobile_ownership_cost' + consumption_preferences_model['name'] = 'Likely to be sensitive to ownership cost when buying automobiles' + consumption_preferences_model['score'] = 0 -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response + consumption_preferences_category_model = {} # ConsumptionPreferencesCategory + consumption_preferences_category_model['consumption_preference_category_id'] = 'consumption_preferences_shopping' + consumption_preferences_category_model['name'] = 'Purchasing Preferences' + consumption_preferences_category_model['consumption_preferences'] = [consumption_preferences_model] - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string + warning_model = {} # Warning + warning_model['warning_id'] = 'WORD_COUNT_MESSAGE' + warning_model['message'] = 'testString' + # Construct a json representation of a Profile model + profile_model_json = {} + profile_model_json['processed_language'] = 'ar' + profile_model_json['word_count'] = 38 + profile_model_json['word_count_message'] = 'testString' + profile_model_json['personality'] = [trait_model] + profile_model_json['needs'] = [trait_model] + profile_model_json['values'] = [trait_model] + profile_model_json['behavior'] = [behavior_model] + profile_model_json['consumption_preferences'] = [consumption_preferences_category_model] + profile_model_json['warnings'] = [warning_model] + + # Construct a model instance of Profile by calling from_dict on the json representation + profile_model = Profile.from_dict(profile_model_json) + assert profile_model != False + + # Construct a model instance of Profile by calling from_dict on the json representation + profile_model_dict = Profile.from_dict(profile_model_json).__dict__ + profile_model2 = Profile(**profile_model_dict) + + # Verify the model instances are equivalent + assert profile_model == profile_model2 + + # Convert model instance back to dict and verify no loss of data + profile_model_json2 = profile_model.to_dict() + assert profile_model_json2 == profile_model_json + +class TestTrait(): + """ + Test Class for Trait + """ + + def test_trait_serialization(self): + """ + Test serialization/deserialization for Trait + """ + + # Construct a json representation of a Trait model + trait_model_json = {} + trait_model_json['trait_id'] = 'testString' + trait_model_json['name'] = 'testString' + trait_model_json['category'] = 'personality' + trait_model_json['percentile'] = 72.5 + trait_model_json['raw_score'] = 72.5 + trait_model_json['significant'] = True + + # Construct a model instance of Trait by calling from_dict on the json representation + trait_model = Trait.from_dict(trait_model_json) + assert trait_model != False + + # Construct a model instance of Trait by calling from_dict on the json representation + trait_model_dict = Trait.from_dict(trait_model_json).__dict__ + trait_model2 = Trait(**trait_model_dict) + + # Verify the model instances are equivalent + assert trait_model == trait_model2 + + # Convert model instance back to dict and verify no loss of data + trait_model_json2 = trait_model.to_dict() + assert trait_model_json2 == trait_model_json + +class TestWarning(): + """ + Test Class for Warning """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response -#################### -## Mock Responses ## -#################### + def test_warning_serialization(self): + """ + Test serialization/deserialization for Warning + """ + + # Construct a json representation of a Warning model + warning_model_json = {} + warning_model_json['warning_id'] = 'WORD_COUNT_MESSAGE' + warning_model_json['message'] = 'testString' + + # Construct a model instance of Warning by calling from_dict on the json representation + warning_model = Warning.from_dict(warning_model_json) + assert warning_model != False + + # Construct a model instance of Warning by calling from_dict on the json representation + warning_model_dict = Warning.from_dict(warning_model_json).__dict__ + warning_model2 = Warning(**warning_model_dict) -fake_response__json = None -fake_response_Profile_json = """{"processed_language": "fake_processed_language", "word_count": 10, "word_count_message": "fake_word_count_message", "personality": [], "needs": [], "values": [], "behavior": [], "consumption_preferences": [], "warnings": []}""" + # Verify the model instances are equivalent + assert warning_model == warning_model2 + + # Convert model instance back to dict and verify no loss of data + warning_model_json2 = warning_model.to_dict() + assert warning_model_json2 == warning_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 5a9dd4a4a..2ef2a470d 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -13,155 +13,140 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Unit Tests for SpeechToTextV1 +""" + from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect +import io import json import pytest +import re +import requests import responses import tempfile -import ibm_watson.speech_to_text_v1 +import urllib from ibm_watson.speech_to_text_v1 import * + +service = SpeechToTextV1( + authenticator=NoAuthAuthenticator() + ) + base_url = 'https://api.us-south.speech-to-text.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: Models ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_models -#----------------------------------------------------------------------------- class TestListModels(): + """ + Test Class for list_models + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_models_response(self): - body = self.construct_full_body() - response = fake_response_SpeechModels_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_models_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_SpeechModels_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_models_all_params(self): + """ + list_models() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/models') + mock_response = '{"models": [{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true}, "description": "description"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_models_empty(self): - check_empty_response(self) + # Invoke method + response = service.list_models() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/models' - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.list_models(**body) - return output - - def construct_full_body(self): - body = dict() - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_model -#----------------------------------------------------------------------------- class TestGetModel(): + """ + Test Class for get_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_model_response(self): - body = self.construct_full_body() - response = fake_response_SpeechModel_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_SpeechModel_json - send_request(self, body, response) + def test_get_model_all_params(self): + """ + get_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/models/ar-AR_BroadbandModel') + mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true}, "description": "description"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'ar-AR_BroadbandModel' + + # Invoke method + response = service.get_model( + model_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_model_empty(self): - check_empty_required_params(self, fake_response_SpeechModel_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_model_value_error(self): + """ + test_get_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/models/ar-AR_BroadbandModel') + mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true}, "description": "description"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/models/{0}'.format(body['model_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + model_id = 'ar-AR_BroadbandModel' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_model(**req_copy) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['model_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['model_id'] = "string1" - return body # endregion @@ -174,97 +159,178 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for recognize -#----------------------------------------------------------------------------- class TestRecognize(): + """ + Test Class for recognize + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_recognize_response(self): - body = self.construct_full_body() - response = fake_response_SpeechRecognitionResults_json - send_request(self, body, response) + def test_recognize_all_params(self): + """ + recognize() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/recognize') + mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + audio = io.BytesIO(b'This is a mock file.').getvalue() + content_type = 'application/octet-stream' + model = 'ar-AR_BroadbandModel' + language_customization_id = 'testString' + acoustic_customization_id = 'testString' + base_model_version = 'testString' + customization_weight = 72.5 + inactivity_timeout = 38 + keywords = ['testString'] + keywords_threshold = 72.5 + max_alternatives = 38 + word_alternatives_threshold = 72.5 + word_confidence = True + timestamps = True + profanity_filter = True + smart_formatting = True + speaker_labels = True + customization_id = 'testString' + grammar_name = 'testString' + redaction = True + audio_metrics = True + end_of_phrase_silence_time = 72.5 + split_transcript_at_phrase_end = True + speech_detector_sensitivity = 72.5 + background_audio_suppression = 72.5 + + # Invoke method + response = service.recognize( + audio, + content_type=content_type, + model=model, + language_customization_id=language_customization_id, + acoustic_customization_id=acoustic_customization_id, + base_model_version=base_model_version, + customization_weight=customization_weight, + inactivity_timeout=inactivity_timeout, + keywords=keywords, + keywords_threshold=keywords_threshold, + max_alternatives=max_alternatives, + word_alternatives_threshold=word_alternatives_threshold, + word_confidence=word_confidence, + timestamps=timestamps, + profanity_filter=profanity_filter, + smart_formatting=smart_formatting, + speaker_labels=speaker_labels, + customization_id=customization_id, + grammar_name=grammar_name, + redaction=redaction, + audio_metrics=audio_metrics, + end_of_phrase_silence_time=end_of_phrase_silence_time, + split_transcript_at_phrase_end=split_transcript_at_phrase_end, + speech_detector_sensitivity=speech_detector_sensitivity, + background_audio_suppression=background_audio_suppression, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'model={}'.format(model) in query_string + assert 'language_customization_id={}'.format(language_customization_id) in query_string + assert 'acoustic_customization_id={}'.format(acoustic_customization_id) in query_string + assert 'base_model_version={}'.format(base_model_version) in query_string + assert 'customization_weight={}'.format(customization_weight) in query_string + assert 'inactivity_timeout={}'.format(inactivity_timeout) in query_string + assert 'keywords={}'.format(','.join(keywords)) in query_string + assert 'keywords_threshold={}'.format(keywords_threshold) in query_string + assert 'max_alternatives={}'.format(max_alternatives) in query_string + assert 'word_alternatives_threshold={}'.format(word_alternatives_threshold) in query_string + assert 'word_confidence={}'.format('true' if word_confidence else 'false') in query_string + assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string + assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string + assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string + assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string + assert 'customization_id={}'.format(customization_id) in query_string + assert 'grammar_name={}'.format(grammar_name) in query_string + assert 'redaction={}'.format('true' if redaction else 'false') in query_string + assert 'audio_metrics={}'.format('true' if audio_metrics else 'false') in query_string + assert 'end_of_phrase_silence_time={}'.format(end_of_phrase_silence_time) in query_string + assert 'split_transcript_at_phrase_end={}'.format('true' if split_transcript_at_phrase_end else 'false') in query_string + assert 'speech_detector_sensitivity={}'.format(speech_detector_sensitivity) in query_string + assert 'background_audio_suppression={}'.format(background_audio_suppression) in query_string + # Validate body params + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_recognize_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_SpeechRecognitionResults_json - send_request(self, body, response) + def test_recognize_required_params(self): + """ + test_recognize_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/recognize') + mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + audio = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = service.recognize( + audio, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_recognize_empty(self): - check_empty_required_params(self, fake_response_SpeechRecognitionResults_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_recognize_value_error(self): + """ + test_recognize_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/recognize') + mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/recognize' - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + audio = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "audio": audio, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.recognize(**req_copy) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.recognize(**body) - return output - - def construct_full_body(self): - body = dict() - body['audio'] = tempfile.NamedTemporaryFile() - body['content_type'] = "string1" - body['model'] = "string1" - body['language_customization_id'] = "string1" - body['acoustic_customization_id'] = "string1" - body['base_model_version'] = "string1" - body['customization_weight'] = 12345.0 - body['inactivity_timeout'] = 12345 - body['keywords'] = [] - body['keywords_threshold'] = 12345.0 - body['max_alternatives'] = 12345 - body['word_alternatives_threshold'] = 12345.0 - body['word_confidence'] = True - body['timestamps'] = True - body['profanity_filter'] = True - body['smart_formatting'] = True - body['speaker_labels'] = True - body['customization_id'] = "string1" - body['grammar_name'] = "string1" - body['redaction'] = True - body['audio_metrics'] = True - body['end_of_phrase_silence_time'] = 12345.0 - body['split_transcript_at_phrase_end'] = True - body['speech_detector_sensitivity'] = 12345.0 - body['background_audio_suppression'] = 12345.0 - return body - - def construct_required_body(self): - body = dict() - body['audio'] = tempfile.NamedTemporaryFile() - return body # endregion @@ -277,446 +343,544 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for register_callback -#----------------------------------------------------------------------------- class TestRegisterCallback(): + """ + Test Class for register_callback + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_register_callback_response(self): - body = self.construct_full_body() - response = fake_response_RegisterStatus_json - send_request(self, body, response) + def test_register_callback_all_params(self): + """ + register_callback() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/register_callback') + mock_response = '{"status": "created", "url": "url"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + callback_url = 'testString' + user_secret = 'testString' + + # Invoke method + response = service.register_callback( + callback_url, + user_secret=user_secret, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'callback_url={}'.format(callback_url) in query_string + assert 'user_secret={}'.format(user_secret) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_register_callback_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_RegisterStatus_json - send_request(self, body, response) + def test_register_callback_required_params(self): + """ + test_register_callback_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/register_callback') + mock_response = '{"status": "created", "url": "url"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + callback_url = 'testString' + + # Invoke method + response = service.register_callback( + callback_url, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'callback_url={}'.format(callback_url) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_register_callback_empty(self): - check_empty_required_params(self, fake_response_RegisterStatus_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_register_callback_value_error(self): + """ + test_register_callback_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/register_callback') + mock_response = '{"status": "created", "url": "url"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + callback_url = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "callback_url": callback_url, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.register_callback(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/register_callback' - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.register_callback(**body) - return output - - def construct_full_body(self): - body = dict() - body['callback_url'] = "string1" - body['user_secret'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['callback_url'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for unregister_callback -#----------------------------------------------------------------------------- class TestUnregisterCallback(): + """ + Test Class for unregister_callback + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_unregister_callback_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_unregister_callback_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_unregister_callback_all_params(self): + """ + unregister_callback() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/unregister_callback') + responses.add(responses.POST, + url, + status=200) + + # Set up parameter values + callback_url = 'testString' + + # Invoke method + response = service.unregister_callback( + callback_url, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'callback_url={}'.format(callback_url) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_unregister_callback_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_unregister_callback_value_error(self): + """ + test_unregister_callback_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/unregister_callback') + responses.add(responses.POST, + url, + status=200) + + # Set up parameter values + callback_url = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "callback_url": callback_url, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.unregister_callback(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/unregister_callback' - 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='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.unregister_callback(**body) - return output - - def construct_full_body(self): - body = dict() - body['callback_url'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['callback_url'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for create_job -#----------------------------------------------------------------------------- class TestCreateJob(): + """ + Test Class for create_job + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_job_response(self): - body = self.construct_full_body() - response = fake_response_RecognitionJob_json - send_request(self, body, response) + def test_create_job_all_params(self): + """ + create_job() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/recognitions') + mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + audio = io.BytesIO(b'This is a mock file.').getvalue() + content_type = 'application/octet-stream' + model = 'ar-AR_BroadbandModel' + callback_url = 'testString' + events = 'recognitions.started' + user_token = 'testString' + results_ttl = 38 + language_customization_id = 'testString' + acoustic_customization_id = 'testString' + base_model_version = 'testString' + customization_weight = 72.5 + inactivity_timeout = 38 + keywords = ['testString'] + keywords_threshold = 72.5 + max_alternatives = 38 + word_alternatives_threshold = 72.5 + word_confidence = True + timestamps = True + profanity_filter = True + smart_formatting = True + speaker_labels = True + customization_id = 'testString' + grammar_name = 'testString' + redaction = True + processing_metrics = True + processing_metrics_interval = 72.5 + audio_metrics = True + end_of_phrase_silence_time = 72.5 + split_transcript_at_phrase_end = True + speech_detector_sensitivity = 72.5 + background_audio_suppression = 72.5 + + # Invoke method + response = service.create_job( + audio, + content_type=content_type, + model=model, + callback_url=callback_url, + events=events, + user_token=user_token, + results_ttl=results_ttl, + language_customization_id=language_customization_id, + acoustic_customization_id=acoustic_customization_id, + base_model_version=base_model_version, + customization_weight=customization_weight, + inactivity_timeout=inactivity_timeout, + keywords=keywords, + keywords_threshold=keywords_threshold, + max_alternatives=max_alternatives, + word_alternatives_threshold=word_alternatives_threshold, + word_confidence=word_confidence, + timestamps=timestamps, + profanity_filter=profanity_filter, + smart_formatting=smart_formatting, + speaker_labels=speaker_labels, + customization_id=customization_id, + grammar_name=grammar_name, + redaction=redaction, + processing_metrics=processing_metrics, + processing_metrics_interval=processing_metrics_interval, + audio_metrics=audio_metrics, + end_of_phrase_silence_time=end_of_phrase_silence_time, + split_transcript_at_phrase_end=split_transcript_at_phrase_end, + speech_detector_sensitivity=speech_detector_sensitivity, + background_audio_suppression=background_audio_suppression, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'model={}'.format(model) in query_string + assert 'callback_url={}'.format(callback_url) in query_string + assert 'events={}'.format(events) in query_string + assert 'user_token={}'.format(user_token) in query_string + assert 'results_ttl={}'.format(results_ttl) in query_string + assert 'language_customization_id={}'.format(language_customization_id) in query_string + assert 'acoustic_customization_id={}'.format(acoustic_customization_id) in query_string + assert 'base_model_version={}'.format(base_model_version) in query_string + assert 'customization_weight={}'.format(customization_weight) in query_string + assert 'inactivity_timeout={}'.format(inactivity_timeout) in query_string + assert 'keywords={}'.format(','.join(keywords)) in query_string + assert 'keywords_threshold={}'.format(keywords_threshold) in query_string + assert 'max_alternatives={}'.format(max_alternatives) in query_string + assert 'word_alternatives_threshold={}'.format(word_alternatives_threshold) in query_string + assert 'word_confidence={}'.format('true' if word_confidence else 'false') in query_string + assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string + assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string + assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string + assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string + assert 'customization_id={}'.format(customization_id) in query_string + assert 'grammar_name={}'.format(grammar_name) in query_string + assert 'redaction={}'.format('true' if redaction else 'false') in query_string + assert 'processing_metrics={}'.format('true' if processing_metrics else 'false') in query_string + assert 'processing_metrics_interval={}'.format(processing_metrics_interval) in query_string + assert 'audio_metrics={}'.format('true' if audio_metrics else 'false') in query_string + assert 'end_of_phrase_silence_time={}'.format(end_of_phrase_silence_time) in query_string + assert 'split_transcript_at_phrase_end={}'.format('true' if split_transcript_at_phrase_end else 'false') in query_string + assert 'speech_detector_sensitivity={}'.format(speech_detector_sensitivity) in query_string + assert 'background_audio_suppression={}'.format(background_audio_suppression) in query_string + # Validate body params + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_job_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_RecognitionJob_json - send_request(self, body, response) + def test_create_job_required_params(self): + """ + test_create_job_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/recognitions') + mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + audio = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = service.create_job( + audio, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_job_empty(self): - check_empty_required_params(self, fake_response_RecognitionJob_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_create_job_value_error(self): + """ + test_create_job_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/recognitions') + mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + audio = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "audio": audio, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_job(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/recognitions' - 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=201, - content_type='application/json') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.create_job(**body) - return output - - def construct_full_body(self): - body = dict() - body['audio'] = tempfile.NamedTemporaryFile() - body['content_type'] = "string1" - body['model'] = "string1" - body['callback_url'] = "string1" - body['events'] = "string1" - body['user_token'] = "string1" - body['results_ttl'] = 12345 - body['language_customization_id'] = "string1" - body['acoustic_customization_id'] = "string1" - body['base_model_version'] = "string1" - body['customization_weight'] = 12345.0 - body['inactivity_timeout'] = 12345 - body['keywords'] = [] - body['keywords_threshold'] = 12345.0 - body['max_alternatives'] = 12345 - body['word_alternatives_threshold'] = 12345.0 - body['word_confidence'] = True - body['timestamps'] = True - body['profanity_filter'] = True - body['smart_formatting'] = True - body['speaker_labels'] = True - body['customization_id'] = "string1" - body['grammar_name'] = "string1" - body['redaction'] = True - body['processing_metrics'] = True - body['processing_metrics_interval'] = 12345.0 - body['audio_metrics'] = True - body['end_of_phrase_silence_time'] = 12345.0 - body['split_transcript_at_phrase_end'] = True - body['speech_detector_sensitivity'] = 12345.0 - body['background_audio_suppression'] = 12345.0 - return body - - def construct_required_body(self): - body = dict() - body['audio'] = tempfile.NamedTemporaryFile() - return body - - -#----------------------------------------------------------------------------- -# Test Class for check_jobs -#----------------------------------------------------------------------------- class TestCheckJobs(): + """ + Test Class for check_jobs + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_check_jobs_response(self): - body = self.construct_full_body() - response = fake_response_RecognitionJobs_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_check_jobs_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_RecognitionJobs_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_check_jobs_all_params(self): + """ + check_jobs() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/recognitions') + mock_response = '{"recognitions": [{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_check_jobs_empty(self): - check_empty_response(self) + # Invoke method + response = service.check_jobs() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/recognitions' - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.check_jobs(**body) - return output - - def construct_full_body(self): - body = dict() - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for check_job -#----------------------------------------------------------------------------- class TestCheckJob(): + """ + Test Class for check_job + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_check_job_response(self): - body = self.construct_full_body() - response = fake_response_RecognitionJob_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_check_job_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_RecognitionJob_json - send_request(self, body, response) + def test_check_job_all_params(self): + """ + check_job() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/recognitions/testString') + mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + id = 'testString' + + # Invoke method + response = service.check_job( + id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_check_job_empty(self): - check_empty_required_params(self, fake_response_RecognitionJob_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_check_job_value_error(self): + """ + test_check_job_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/recognitions/testString') + mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "id": id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.check_job(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/recognitions/{0}'.format(body['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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.check_job(**body) - return output - - def construct_full_body(self): - body = dict() - body['id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_job -#----------------------------------------------------------------------------- class TestDeleteJob(): + """ + Test Class for delete_job + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_job_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_job_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_job_all_params(self): + """ + delete_job() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/recognitions/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + id = 'testString' + + # Invoke method + response = service.delete_job( + id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_job_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_job_value_error(self): + """ + test_delete_job_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/recognitions/testString') + responses.add(responses.DELETE, + url, + status=204) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/recognitions/{0}'.format(body['id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "id": id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_job(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_job(**body) - return output - - def construct_full_body(self): - body = dict() - body['id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['id'] = "string1" - return body # endregion @@ -729,487 +893,528 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_language_model -#----------------------------------------------------------------------------- class TestCreateLanguageModel(): + """ + Test Class for create_language_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_language_model_response(self): - body = self.construct_full_body() - response = fake_response_LanguageModel_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_language_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_LanguageModel_json - send_request(self, body, response) + def test_create_language_model_all_params(self): + """ + create_language_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations') + mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + name = 'testString' + base_model_name = 'de-DE_BroadbandModel' + dialect = 'testString' + description = 'testString' + + # Invoke method + response = service.create_language_model( + name, + base_model_name, + dialect=dialect, + description=description, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['base_model_name'] == 'de-DE_BroadbandModel' + assert req_body['dialect'] == 'testString' + assert req_body['description'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_language_model_empty(self): - check_empty_required_params(self, fake_response_LanguageModel_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_create_language_model_value_error(self): + """ + test_create_language_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations') + mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + name = 'testString' + base_model_name = 'de-DE_BroadbandModel' + dialect = 'testString' + description = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "name": name, + "base_model_name": base_model_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_language_model(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations' - 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=201, - content_type='application/json') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.create_language_model(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"name": "string1", "base_model_name": "string1", "dialect": "string1", "description": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body.update({"name": "string1", "base_model_name": "string1", "dialect": "string1", "description": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_language_models -#----------------------------------------------------------------------------- class TestListLanguageModels(): + """ + Test Class for list_language_models + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_language_models_response(self): - body = self.construct_full_body() - response = fake_response_LanguageModels_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_language_models_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_LanguageModels_json - send_request(self, body, response) + def test_list_language_models_all_params(self): + """ + list_language_models() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations') + mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + language = 'ar-AR' + + # Invoke method + response = service.list_language_models( + language=language, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'language={}'.format(language) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_language_models_empty(self): - check_empty_response(self) + def test_list_language_models_required_params(self): + """ + test_list_language_models_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations') + mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = service.list_language_models() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations' - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.list_language_models(**body) - return output - - def construct_full_body(self): - body = dict() - body['language'] = "string1" - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_language_model -#----------------------------------------------------------------------------- class TestGetLanguageModel(): + """ + Test Class for get_language_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_language_model_response(self): - body = self.construct_full_body() - response = fake_response_LanguageModel_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_language_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_LanguageModel_json - send_request(self, body, response) + def test_get_language_model_all_params(self): + """ + get_language_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString') + mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.get_language_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_language_model_empty(self): - check_empty_required_params(self, fake_response_LanguageModel_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_language_model_value_error(self): + """ + test_get_language_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString') + mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_language_model(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}'.format(body['customization_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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_language_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_language_model -#----------------------------------------------------------------------------- class TestDeleteLanguageModel(): + """ + Test Class for delete_language_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_language_model_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_language_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_language_model_all_params(self): + """ + delete_language_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.delete_language_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_language_model_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_language_model_value_error(self): + """ + test_delete_language_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_language_model(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}'.format(body['customization_id']) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_language_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for train_language_model -#----------------------------------------------------------------------------- class TestTrainLanguageModel(): + """ + Test Class for train_language_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_train_language_model_response(self): - body = self.construct_full_body() - response = fake_response_TrainingResponse_json - send_request(self, body, response) + def test_train_language_model_all_params(self): + """ + train_language_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/train') + mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + word_type_to_add = 'all' + customization_weight = 72.5 + + # Invoke method + response = service.train_language_model( + customization_id, + word_type_to_add=word_type_to_add, + customization_weight=customization_weight, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'word_type_to_add={}'.format(word_type_to_add) in query_string + assert 'customization_weight={}'.format(customization_weight) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_train_language_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingResponse_json - send_request(self, body, response) + def test_train_language_model_required_params(self): + """ + test_train_language_model_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/train') + mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.train_language_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_train_language_model_empty(self): - check_empty_required_params(self, fake_response_TrainingResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_train_language_model_value_error(self): + """ + test_train_language_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/train') + mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.train_language_model(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/train'.format(body['customization_id']) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.train_language_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['word_type_to_add'] = "string1" - body['customization_weight'] = 12345.0 - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for reset_language_model -#----------------------------------------------------------------------------- class TestResetLanguageModel(): + """ + Test Class for reset_language_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_reset_language_model_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_reset_language_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_reset_language_model_all_params(self): + """ + reset_language_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/reset') + responses.add(responses.POST, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.reset_language_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_reset_language_model_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_reset_language_model_value_error(self): + """ + test_reset_language_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/reset') + responses.add(responses.POST, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.reset_language_model(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/reset'.format(body['customization_id']) - 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='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.reset_language_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for upgrade_language_model -#----------------------------------------------------------------------------- class TestUpgradeLanguageModel(): + """ + Test Class for upgrade_language_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_upgrade_language_model_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_upgrade_language_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_upgrade_language_model_all_params(self): + """ + upgrade_language_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/upgrade_model') + responses.add(responses.POST, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.upgrade_language_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_upgrade_language_model_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_upgrade_language_model_value_error(self): + """ + test_upgrade_language_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/upgrade_model') + responses.add(responses.POST, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/upgrade_model'.format(body['customization_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.upgrade_language_model(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.upgrade_language_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body # endregion @@ -1222,289 +1427,323 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_corpora -#----------------------------------------------------------------------------- class TestListCorpora(): + """ + Test Class for list_corpora + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_corpora_response(self): - body = self.construct_full_body() - response = fake_response_Corpora_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_corpora_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Corpora_json - send_request(self, body, response) + def test_list_corpora_all_params(self): + """ + list_corpora() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora') + mock_response = '{"corpora": [{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.list_corpora( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_corpora_empty(self): - check_empty_required_params(self, fake_response_Corpora_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_corpora_value_error(self): + """ + test_list_corpora_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora') + mock_response = '{"corpora": [{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_corpora(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/corpora'.format(body['customization_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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.list_corpora(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for add_corpus -#----------------------------------------------------------------------------- class TestAddCorpus(): + """ + Test Class for add_corpus + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_corpus_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) + def test_add_corpus_all_params(self): + """ + add_corpus() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + responses.add(responses.POST, + url, + status=201) + + # Set up parameter values + customization_id = 'testString' + corpus_name = 'testString' + corpus_file = io.BytesIO(b'This is a mock file.').getvalue() + allow_overwrite = True + + # Invoke method + response = service.add_corpus( + customization_id, + corpus_name, + corpus_file, + allow_overwrite=allow_overwrite, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_corpus_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_add_corpus_required_params(self): + """ + test_add_corpus_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + responses.add(responses.POST, + url, + status=201) + + # Set up parameter values + customization_id = 'testString' + corpus_name = 'testString' + corpus_file = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = service.add_corpus( + customization_id, + corpus_name, + corpus_file, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_corpus_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_add_corpus_value_error(self): + """ + test_add_corpus_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + responses.add(responses.POST, + url, + status=201) + + # Set up parameter values + customization_id = 'testString' + corpus_name = 'testString' + corpus_file = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "corpus_name": corpus_name, + "corpus_file": corpus_file, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_corpus(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/corpora/{1}'.format(body['customization_id'], body['corpus_name']) - 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=201, - content_type='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.add_corpus(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['corpus_name'] = "string1" - body['corpus_file'] = tempfile.NamedTemporaryFile() - body['allow_overwrite'] = True - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['corpus_name'] = "string1" - body['corpus_file'] = tempfile.NamedTemporaryFile() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_corpus -#----------------------------------------------------------------------------- class TestGetCorpus(): + """ + Test Class for get_corpus + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_corpus_response(self): - body = self.construct_full_body() - response = fake_response_Corpus_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_corpus_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Corpus_json - send_request(self, body, response) + def test_get_corpus_all_params(self): + """ + get_corpus() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + mock_response = '{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + corpus_name = 'testString' + + # Invoke method + response = service.get_corpus( + customization_id, + corpus_name, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_corpus_empty(self): - check_empty_required_params(self, fake_response_Corpus_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_corpus_value_error(self): + """ + test_get_corpus_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + mock_response = '{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/corpora/{1}'.format(body['customization_id'], body['corpus_name']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + customization_id = 'testString' + corpus_name = 'testString' - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_corpus(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['corpus_name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['corpus_name'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_corpus -#----------------------------------------------------------------------------- -class TestDeleteCorpus(): + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "corpus_name": corpus_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_corpus(**req_copy) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_corpus_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_corpus_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_corpus_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 +class TestDeleteCorpus(): + """ + Test Class for delete_corpus + """ - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/corpora/{1}'.format(body['customization_id'], body['corpus_name']) - url = '{0}{1}'.format(base_url, endpoint) - return url + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - def add_mock_response(self, url, response): + @responses.activate + def test_delete_corpus_all_params(self): + """ + delete_corpus() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_corpus(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['corpus_name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['corpus_name'] = "string1" - return body + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + corpus_name = 'testString' + + # Invoke method + response = service.delete_corpus( + customization_id, + corpus_name, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_delete_corpus_value_error(self): + """ + test_delete_corpus_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + corpus_name = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "corpus_name": corpus_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_corpus(**req_copy) + # endregion @@ -1517,361 +1756,418 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_words -#----------------------------------------------------------------------------- class TestListWords(): + """ + Test Class for list_words + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_words_response(self): - body = self.construct_full_body() - response = fake_response_Words_json - send_request(self, body, response) + def test_list_words_all_params(self): + """ + list_words() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + word_type = 'all' + sort = 'alphabetical' + + # Invoke method + response = service.list_words( + customization_id, + word_type=word_type, + sort=sort, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'word_type={}'.format(word_type) in query_string + assert 'sort={}'.format(sort) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_words_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Words_json - send_request(self, body, response) + def test_list_words_required_params(self): + """ + test_list_words_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.list_words( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_words_empty(self): - check_empty_required_params(self, fake_response_Words_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_words_value_error(self): + """ + test_list_words_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_words(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/words'.format(body['customization_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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.list_words(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['word_type'] = "string1" - body['sort'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for add_words -#----------------------------------------------------------------------------- class TestAddWords(): + """ + Test Class for add_words + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_add_words_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_words_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_add_words_all_params(self): + """ + add_words() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + responses.add(responses.POST, + url, + status=201) + + # Construct a dict representation of a CustomWord model + custom_word_model = {} + custom_word_model['word'] = 'testString' + custom_word_model['sounds_like'] = ['testString'] + custom_word_model['display_as'] = 'testString' + + # Set up parameter values + customization_id = 'testString' + words = [custom_word_model] + + # Invoke method + response = service.add_words( + customization_id, + words, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['words'] == [custom_word_model] + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_words_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_add_words_value_error(self): + """ + test_add_words_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + responses.add(responses.POST, + url, + status=201) + + # Construct a dict representation of a CustomWord model + custom_word_model = {} + custom_word_model['word'] = 'testString' + custom_word_model['sounds_like'] = ['testString'] + custom_word_model['display_as'] = 'testString' + + # Set up parameter values + customization_id = 'testString' + words = [custom_word_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "words": words, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_words(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/words'.format(body['customization_id']) - 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=201, - content_type='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.add_words(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body.update({"words": [], }) - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body.update({"words": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for add_word -#----------------------------------------------------------------------------- class TestAddWord(): + """ + Test Class for add_word + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_add_word_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_word_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_add_word_all_params(self): + """ + add_word() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + responses.add(responses.PUT, + url, + status=201) + + # Set up parameter values + customization_id = 'testString' + word_name = 'testString' + word = 'testString' + sounds_like = ['testString'] + display_as = 'testString' + + # Invoke method + response = service.add_word( + customization_id, + word_name, + word=word, + sounds_like=sounds_like, + display_as=display_as, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['word'] == 'testString' + assert req_body['sounds_like'] == ['testString'] + assert req_body['display_as'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_word_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_add_word_value_error(self): + """ + test_add_word_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + responses.add(responses.PUT, + url, + status=201) + + # Set up parameter values + customization_id = 'testString' + word_name = 'testString' + word = 'testString' + sounds_like = ['testString'] + display_as = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "word_name": word_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_word(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word_name']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): - responses.add(responses.PUT, - url, - body=json.dumps(response), - status=201, - content_type='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.add_word(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['word_name'] = "string1" - body.update({"word": "string1", "sounds_like": [], "display_as": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['word_name'] = "string1" - body.update({"word": "string1", "sounds_like": [], "display_as": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_word -#----------------------------------------------------------------------------- class TestGetWord(): + """ + Test Class for get_word + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_word_response(self): - body = self.construct_full_body() - response = fake_response_Word_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_word_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Word_json - send_request(self, body, response) + def test_get_word_all_params(self): + """ + get_word() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + word_name = 'testString' + + # Invoke method + response = service.get_word( + customization_id, + word_name, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_word_empty(self): - check_empty_required_params(self, fake_response_Word_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_word_value_error(self): + """ + test_get_word_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + word_name = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "word_name": word_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_word(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word_name']) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_word(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['word_name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['word_name'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_word -#----------------------------------------------------------------------------- class TestDeleteWord(): + """ + Test Class for delete_word + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_word_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_word_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_word_all_params(self): + """ + delete_word() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + word_name = 'testString' + + # Invoke method + response = service.delete_word( + customization_id, + word_name, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_word_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_word_value_error(self): + """ + test_delete_word_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word_name']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + customization_id = 'testString' + word_name = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "word_name": word_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_word(**req_copy) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_word(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['word_name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['word_name'] = "string1" - return body # endregion @@ -1884,291 +2180,331 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_grammars -#----------------------------------------------------------------------------- class TestListGrammars(): + """ + Test Class for list_grammars + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_grammars_response(self): - body = self.construct_full_body() - response = fake_response_Grammars_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_grammars_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Grammars_json - send_request(self, body, response) + def test_list_grammars_all_params(self): + """ + list_grammars() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars') + mock_response = '{"grammars": [{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.list_grammars( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_grammars_empty(self): - check_empty_required_params(self, fake_response_Grammars_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_grammars_value_error(self): + """ + test_list_grammars_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars') + mock_response = '{"grammars": [{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_grammars(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/grammars'.format(body['customization_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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.list_grammars(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for add_grammar -#----------------------------------------------------------------------------- class TestAddGrammar(): + """ + Test Class for add_grammar + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_grammar_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) + def test_add_grammar_all_params(self): + """ + add_grammar() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + responses.add(responses.POST, + url, + status=201) + + # Set up parameter values + customization_id = 'testString' + grammar_name = 'testString' + grammar_file = 'testString' + content_type = 'application/srgs' + allow_overwrite = True + + # Invoke method + response = service.add_grammar( + customization_id, + grammar_name, + grammar_file, + content_type, + allow_overwrite=allow_overwrite, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string + # Validate body params + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_grammar_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_add_grammar_required_params(self): + """ + test_add_grammar_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + responses.add(responses.POST, + url, + status=201) + + # Set up parameter values + customization_id = 'testString' + grammar_name = 'testString' + grammar_file = 'testString' + content_type = 'application/srgs' + + # Invoke method + response = service.add_grammar( + customization_id, + grammar_name, + grammar_file, + content_type, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_grammar_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_add_grammar_value_error(self): + """ + test_add_grammar_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + responses.add(responses.POST, + url, + status=201) + + # Set up parameter values + customization_id = 'testString' + grammar_name = 'testString' + grammar_file = 'testString' + content_type = 'application/srgs' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "grammar_name": grammar_name, + "grammar_file": grammar_file, + "content_type": content_type, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_grammar(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/grammars/{1}'.format(body['customization_id'], body['grammar_name']) - 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=201, - content_type='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.add_grammar(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['grammar_name'] = "string1" - body['grammar_file'] = "string1" - body['content_type'] = "string1" - body['allow_overwrite'] = True - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['grammar_name'] = "string1" - body['grammar_file'] = "string1" - body['content_type'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_grammar -#----------------------------------------------------------------------------- class TestGetGrammar(): + """ + Test Class for get_grammar + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_grammar_response(self): - body = self.construct_full_body() - response = fake_response_Grammar_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_grammar_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Grammar_json - send_request(self, body, response) + def test_get_grammar_all_params(self): + """ + get_grammar() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + mock_response = '{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + grammar_name = 'testString' + + # Invoke method + response = service.get_grammar( + customization_id, + grammar_name, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_grammar_empty(self): - check_empty_required_params(self, fake_response_Grammar_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_grammar_value_error(self): + """ + test_get_grammar_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + mock_response = '{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + grammar_name = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "grammar_name": grammar_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_grammar(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/grammars/{1}'.format(body['customization_id'], body['grammar_name']) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_grammar(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['grammar_name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['grammar_name'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_grammar -#----------------------------------------------------------------------------- class TestDeleteGrammar(): + """ + Test Class for delete_grammar + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_grammar_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_grammar_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_grammar_all_params(self): + """ + delete_grammar() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + grammar_name = 'testString' + + # Invoke method + response = service.delete_grammar( + customization_id, + grammar_name, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_grammar_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_grammar_value_error(self): + """ + test_delete_grammar_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/grammars/{1}'.format(body['customization_id'], body['grammar_name']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + customization_id = 'testString' + grammar_name = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "grammar_name": grammar_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_grammar(**req_copy) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_grammar(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['grammar_name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['grammar_name'] = "string1" - return body # endregion @@ -2181,488 +2517,555 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_acoustic_model -#----------------------------------------------------------------------------- class TestCreateAcousticModel(): + """ + Test Class for create_acoustic_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_acoustic_model_response(self): - body = self.construct_full_body() - response = fake_response_AcousticModel_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_acoustic_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_AcousticModel_json - send_request(self, body, response) + def test_create_acoustic_model_all_params(self): + """ + create_acoustic_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations') + mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + name = 'testString' + base_model_name = 'ar-AR_BroadbandModel' + description = 'testString' + + # Invoke method + response = service.create_acoustic_model( + name, + base_model_name, + description=description, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['base_model_name'] == 'ar-AR_BroadbandModel' + assert req_body['description'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_acoustic_model_empty(self): - check_empty_required_params(self, fake_response_AcousticModel_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_create_acoustic_model_value_error(self): + """ + test_create_acoustic_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations') + mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + name = 'testString' + base_model_name = 'ar-AR_BroadbandModel' + description = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "name": name, + "base_model_name": base_model_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_acoustic_model(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/acoustic_customizations' - 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=201, - content_type='application/json') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.create_acoustic_model(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"name": "string1", "base_model_name": "string1", "description": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body.update({"name": "string1", "base_model_name": "string1", "description": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_acoustic_models -#----------------------------------------------------------------------------- class TestListAcousticModels(): + """ + Test Class for list_acoustic_models + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_acoustic_models_response(self): - body = self.construct_full_body() - response = fake_response_AcousticModels_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_acoustic_models_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_AcousticModels_json - send_request(self, body, response) + def test_list_acoustic_models_all_params(self): + """ + list_acoustic_models() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations') + mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + language = 'ar-AR' + + # Invoke method + response = service.list_acoustic_models( + language=language, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'language={}'.format(language) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_acoustic_models_empty(self): - check_empty_response(self) + def test_list_acoustic_models_required_params(self): + """ + test_list_acoustic_models_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations') + mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = service.list_acoustic_models() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/acoustic_customizations' - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.list_acoustic_models(**body) - return output - - def construct_full_body(self): - body = dict() - body['language'] = "string1" - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_acoustic_model -#----------------------------------------------------------------------------- class TestGetAcousticModel(): + """ + Test Class for get_acoustic_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_acoustic_model_response(self): - body = self.construct_full_body() - response = fake_response_AcousticModel_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_acoustic_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_AcousticModel_json - send_request(self, body, response) + def test_get_acoustic_model_all_params(self): + """ + get_acoustic_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString') + mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.get_acoustic_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_acoustic_model_empty(self): - check_empty_required_params(self, fake_response_AcousticModel_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_acoustic_model_value_error(self): + """ + test_get_acoustic_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString') + mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_acoustic_model(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}'.format(body['customization_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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_acoustic_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_acoustic_model -#----------------------------------------------------------------------------- class TestDeleteAcousticModel(): + """ + Test Class for delete_acoustic_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_acoustic_model_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_acoustic_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_acoustic_model_all_params(self): + """ + delete_acoustic_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.delete_acoustic_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_acoustic_model_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_acoustic_model_value_error(self): + """ + test_delete_acoustic_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_acoustic_model(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}'.format(body['customization_id']) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_acoustic_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for train_acoustic_model -#----------------------------------------------------------------------------- class TestTrainAcousticModel(): + """ + Test Class for train_acoustic_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_train_acoustic_model_response(self): - body = self.construct_full_body() - response = fake_response_TrainingResponse_json - send_request(self, body, response) + def test_train_acoustic_model_all_params(self): + """ + train_acoustic_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/train') + mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + custom_language_model_id = 'testString' + + # Invoke method + response = service.train_acoustic_model( + customization_id, + custom_language_model_id=custom_language_model_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'custom_language_model_id={}'.format(custom_language_model_id) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_train_acoustic_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingResponse_json - send_request(self, body, response) + def test_train_acoustic_model_required_params(self): + """ + test_train_acoustic_model_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/train') + mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.train_acoustic_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_train_acoustic_model_empty(self): - check_empty_required_params(self, fake_response_TrainingResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_train_acoustic_model_value_error(self): + """ + test_train_acoustic_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/train') + mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.train_acoustic_model(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/train'.format(body['customization_id']) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.train_acoustic_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['custom_language_model_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for reset_acoustic_model -#----------------------------------------------------------------------------- class TestResetAcousticModel(): + """ + Test Class for reset_acoustic_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_reset_acoustic_model_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_reset_acoustic_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_reset_acoustic_model_all_params(self): + """ + reset_acoustic_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/reset') + responses.add(responses.POST, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.reset_acoustic_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_reset_acoustic_model_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_reset_acoustic_model_value_error(self): + """ + test_reset_acoustic_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/reset') + responses.add(responses.POST, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.reset_acoustic_model(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/reset'.format(body['customization_id']) - 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='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.reset_acoustic_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for upgrade_acoustic_model -#----------------------------------------------------------------------------- class TestUpgradeAcousticModel(): + """ + Test Class for upgrade_acoustic_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_upgrade_acoustic_model_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) + def test_upgrade_acoustic_model_all_params(self): + """ + upgrade_acoustic_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/upgrade_model') + responses.add(responses.POST, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + custom_language_model_id = 'testString' + force = True + + # Invoke method + response = service.upgrade_acoustic_model( + customization_id, + custom_language_model_id=custom_language_model_id, + force=force, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'custom_language_model_id={}'.format(custom_language_model_id) in query_string + assert 'force={}'.format('true' if force else 'false') in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_upgrade_acoustic_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_upgrade_acoustic_model_required_params(self): + """ + test_upgrade_acoustic_model_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/upgrade_model') + responses.add(responses.POST, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.upgrade_acoustic_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_upgrade_acoustic_model_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_upgrade_acoustic_model_value_error(self): + """ + test_upgrade_acoustic_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/upgrade_model') + responses.add(responses.POST, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/upgrade_model'.format(body['customization_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.upgrade_acoustic_model(**req_copy) - def add_mock_response(self, url, response): - responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.upgrade_acoustic_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['custom_language_model_id'] = "string1" - body['force'] = True - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body # endregion @@ -2675,291 +3078,329 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_audio -#----------------------------------------------------------------------------- class TestListAudio(): + """ + Test Class for list_audio + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_audio_response(self): - body = self.construct_full_body() - response = fake_response_AudioResources_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_audio_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_AudioResources_json - send_request(self, body, response) + def test_list_audio_all_params(self): + """ + list_audio() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio') + mock_response = '{"total_minutes_of_audio": 22, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.list_audio( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_audio_empty(self): - check_empty_required_params(self, fake_response_AudioResources_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_list_audio_value_error(self): + """ + test_list_audio_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio') + mock_response = '{"total_minutes_of_audio": 22, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_audio(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/audio'.format(body['customization_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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.list_audio(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for add_audio -#----------------------------------------------------------------------------- class TestAddAudio(): + """ + Test Class for add_audio + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_add_audio_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_audio_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_add_audio_all_params(self): + """ + add_audio() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + responses.add(responses.POST, + url, + status=201) + + # Set up parameter values + customization_id = 'testString' + audio_name = 'testString' + audio_resource = io.BytesIO(b'This is a mock file.').getvalue() + content_type = 'application/zip' + contained_content_type = 'audio/alaw' + allow_overwrite = True + + # Invoke method + response = service.add_audio( + customization_id, + audio_name, + audio_resource, + content_type=content_type, + contained_content_type=contained_content_type, + allow_overwrite=allow_overwrite, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string + # Validate body params + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_audio_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_add_audio_required_params(self): + """ + test_add_audio_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + responses.add(responses.POST, + url, + status=201) + + # Set up parameter values + customization_id = 'testString' + audio_name = 'testString' + audio_resource = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = service.add_audio( + customization_id, + audio_name, + audio_resource, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format(body['customization_id'], body['audio_name']) - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_add_audio_value_error(self): + """ + test_add_audio_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='') - - def call_service(self, body): - service = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.add_audio(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['audio_name'] = "string1" - body['audio_resource'] = tempfile.NamedTemporaryFile() - body['content_type'] = "string1" - body['contained_content_type'] = "string1" - body['allow_overwrite'] = True - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['audio_name'] = "string1" - body['audio_resource'] = tempfile.NamedTemporaryFile() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_audio -#----------------------------------------------------------------------------- -class TestGetAudio(): + url, + status=201) - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_audio_response(self): - body = self.construct_full_body() - response = fake_response_AudioListing_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Set up parameter values + customization_id = 'testString' + audio_name = 'testString' + audio_resource = io.BytesIO(b'This is a mock file.').getvalue() - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_audio_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_AudioListing_json - send_request(self, body, response) - assert len(responses.calls) == 1 + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "audio_name": audio_name, + "audio_resource": audio_resource, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_audio(**req_copy) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_audio_empty(self): - check_empty_required_params(self, fake_response_AudioListing_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format(body['customization_id'], body['audio_name']) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_audio(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['audio_name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['audio_name'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_audio -#----------------------------------------------------------------------------- -class TestDeleteAudio(): +class TestGetAudio(): + """ + Test Class for get_audio + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_audio_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_audio_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_get_audio_all_params(self): + """ + get_audio() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + mock_response = '{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok", "container": {"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + audio_name = 'testString' + + # Invoke method + response = service.get_audio( + customization_id, + audio_name, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_audio_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_get_audio_value_error(self): + """ + test_get_audio_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + mock_response = '{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok", "container": {"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/acoustic_customizations/{0}/audio/{1}'.format(body['customization_id'], body['audio_name']) - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + customization_id = 'testString' + audio_name = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "audio_name": audio_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_audio(**req_copy) + + + +class TestDeleteAudio(): + """ + Test Class for delete_audio + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_audio_all_params(self): + """ + delete_audio() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + audio_name = 'testString' + + # Invoke method + response = service.delete_audio( + customization_id, + audio_name, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_delete_audio_value_error(self): + """ + test_delete_audio_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + audio_name = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "audio_name": audio_name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_audio(**req_copy) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_audio(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['audio_name'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['audio_name'] = "string1" - return body # endregion @@ -2972,73 +3413,72 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for delete_user_data -#----------------------------------------------------------------------------- class TestDeleteUserData(): + """ + Test Class for delete_user_data + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_user_data_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_user_data_all_params(self): + """ + delete_user_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/user_data') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customer_id = 'testString' + + # Invoke method + response = service.delete_user_data( + customer_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'customer_id={}'.format(customer_id) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_empty(self): - check_empty_required_params(self, fake_response__json) - check_missing_required_params(self) - assert len(responses.calls) == 0 + def test_delete_user_data_value_error(self): + """ + test_delete_user_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/user_data') + responses.add(responses.DELETE, + url, + status=200) - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/user_data' - url = '{0}{1}'.format(base_url, endpoint) - return url + # Set up parameter values + customer_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customer_id": customer_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_user_data(**req_copy) - 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 = SpeechToTextV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_user_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['customer_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customer_id'] = "string1" - return body # endregion @@ -3047,90 +3487,1582 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error - -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error - -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) - -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response - - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string - - """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response - -#################### -## Mock Responses ## -#################### - -fake_response__json = None -fake_response_SpeechModels_json = """{"models": []}""" -fake_response_SpeechModel_json = """{"name": "fake_name", "language": "fake_language", "rate": 4, "url": "fake_url", "supported_features": {"custom_language_model": false, "speaker_labels": true}, "description": "fake_description"}""" -fake_response_SpeechRecognitionResults_json = """{"results": [], "result_index": 12, "speaker_labels": [], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [], "clipping_rate": [], "speech_level": [], "non_speech_level": []}}, "warnings": []}""" -fake_response_RegisterStatus_json = """{"status": "fake_status", "url": "fake_url"}""" -fake_response_RecognitionJob_json = """{"id": "fake_id", "status": "fake_status", "created": "fake_created", "updated": "fake_updated", "url": "fake_url", "user_token": "fake_user_token", "results": [], "warnings": []}""" -fake_response_RecognitionJobs_json = """{"recognitions": []}""" -fake_response_RecognitionJob_json = """{"id": "fake_id", "status": "fake_status", "created": "fake_created", "updated": "fake_updated", "url": "fake_url", "user_token": "fake_user_token", "results": [], "warnings": []}""" -fake_response_LanguageModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "dialect": "fake_dialect", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "error": "fake_error", "warnings": "fake_warnings"}""" -fake_response_LanguageModels_json = """{"customizations": []}""" -fake_response_LanguageModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "dialect": "fake_dialect", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "error": "fake_error", "warnings": "fake_warnings"}""" -fake_response_TrainingResponse_json = """{"warnings": []}""" -fake_response_Corpora_json = """{"corpora": []}""" -fake_response_Corpus_json = """{"name": "fake_name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "fake_status", "error": "fake_error"}""" -fake_response_Words_json = """{"words": []}""" -fake_response_Word_json = """{"word": "fake_word", "sounds_like": [], "display_as": "fake_display_as", "count": 5, "source": [], "error": []}""" -fake_response_Grammars_json = """{"grammars": []}""" -fake_response_Grammar_json = """{"name": "fake_name", "out_of_vocabulary_words": 23, "status": "fake_status", "error": "fake_error"}""" -fake_response_AcousticModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "warnings": "fake_warnings"}""" -fake_response_AcousticModels_json = """{"customizations": []}""" -fake_response_AcousticModel_json = """{"customization_id": "fake_customization_id", "created": "fake_created", "updated": "fake_updated", "language": "fake_language", "versions": [], "owner": "fake_owner", "name": "fake_name", "description": "fake_description", "base_model_name": "fake_base_model_name", "status": "fake_status", "progress": 8, "warnings": "fake_warnings"}""" -fake_response_TrainingResponse_json = """{"warnings": []}""" -fake_response_AudioResources_json = """{"total_minutes_of_audio": 22, "audio": []}""" -fake_response_AudioListing_json = """{"duration": 8, "name": "fake_name", "details": {"type": "fake_type", "codec": "fake_codec", "frequency": 9, "compression": "fake_compression"}, "status": "fake_status", "container": {"duration": 8, "name": "fake_name", "details": {"type": "fake_type", "codec": "fake_codec", "frequency": 9, "compression": "fake_compression"}, "status": "fake_status"}, "audio": []}""" +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestAcousticModel(): + """ + Test Class for AcousticModel + """ + + def test_acoustic_model_serialization(self): + """ + Test serialization/deserialization for AcousticModel + """ + + # Construct a json representation of a AcousticModel model + acoustic_model_model_json = {} + acoustic_model_model_json['customization_id'] = 'testString' + acoustic_model_model_json['created'] = 'testString' + acoustic_model_model_json['updated'] = 'testString' + acoustic_model_model_json['language'] = 'testString' + acoustic_model_model_json['versions'] = ['testString'] + acoustic_model_model_json['owner'] = 'testString' + acoustic_model_model_json['name'] = 'testString' + acoustic_model_model_json['description'] = 'testString' + acoustic_model_model_json['base_model_name'] = 'testString' + acoustic_model_model_json['status'] = 'pending' + acoustic_model_model_json['progress'] = 38 + acoustic_model_model_json['warnings'] = 'testString' + + # Construct a model instance of AcousticModel by calling from_dict on the json representation + acoustic_model_model = AcousticModel.from_dict(acoustic_model_model_json) + assert acoustic_model_model != False + + # Construct a model instance of AcousticModel by calling from_dict on the json representation + acoustic_model_model_dict = AcousticModel.from_dict(acoustic_model_model_json).__dict__ + acoustic_model_model2 = AcousticModel(**acoustic_model_model_dict) + + # Verify the model instances are equivalent + assert acoustic_model_model == acoustic_model_model2 + + # Convert model instance back to dict and verify no loss of data + acoustic_model_model_json2 = acoustic_model_model.to_dict() + assert acoustic_model_model_json2 == acoustic_model_model_json + +class TestAcousticModels(): + """ + Test Class for AcousticModels + """ + + def test_acoustic_models_serialization(self): + """ + Test serialization/deserialization for AcousticModels + """ + + # Construct dict forms of any model objects needed in order to build this model. + + acoustic_model_model = {} # AcousticModel + acoustic_model_model['customization_id'] = 'testString' + acoustic_model_model['created'] = 'testString' + acoustic_model_model['updated'] = 'testString' + acoustic_model_model['language'] = 'testString' + acoustic_model_model['versions'] = ['testString'] + acoustic_model_model['owner'] = 'testString' + acoustic_model_model['name'] = 'testString' + acoustic_model_model['description'] = 'testString' + acoustic_model_model['base_model_name'] = 'testString' + acoustic_model_model['status'] = 'pending' + acoustic_model_model['progress'] = 38 + acoustic_model_model['warnings'] = 'testString' + + # Construct a json representation of a AcousticModels model + acoustic_models_model_json = {} + acoustic_models_model_json['customizations'] = [acoustic_model_model] + + # Construct a model instance of AcousticModels by calling from_dict on the json representation + acoustic_models_model = AcousticModels.from_dict(acoustic_models_model_json) + assert acoustic_models_model != False + + # Construct a model instance of AcousticModels by calling from_dict on the json representation + acoustic_models_model_dict = AcousticModels.from_dict(acoustic_models_model_json).__dict__ + acoustic_models_model2 = AcousticModels(**acoustic_models_model_dict) + + # Verify the model instances are equivalent + assert acoustic_models_model == acoustic_models_model2 + + # Convert model instance back to dict and verify no loss of data + acoustic_models_model_json2 = acoustic_models_model.to_dict() + assert acoustic_models_model_json2 == acoustic_models_model_json + +class TestAudioDetails(): + """ + Test Class for AudioDetails + """ + + def test_audio_details_serialization(self): + """ + Test serialization/deserialization for AudioDetails + """ + + # Construct a json representation of a AudioDetails model + audio_details_model_json = {} + audio_details_model_json['type'] = 'audio' + audio_details_model_json['codec'] = 'testString' + audio_details_model_json['frequency'] = 38 + audio_details_model_json['compression'] = 'zip' + + # Construct a model instance of AudioDetails by calling from_dict on the json representation + audio_details_model = AudioDetails.from_dict(audio_details_model_json) + assert audio_details_model != False + + # Construct a model instance of AudioDetails by calling from_dict on the json representation + audio_details_model_dict = AudioDetails.from_dict(audio_details_model_json).__dict__ + audio_details_model2 = AudioDetails(**audio_details_model_dict) + + # Verify the model instances are equivalent + assert audio_details_model == audio_details_model2 + + # Convert model instance back to dict and verify no loss of data + audio_details_model_json2 = audio_details_model.to_dict() + assert audio_details_model_json2 == audio_details_model_json + +class TestAudioListing(): + """ + Test Class for AudioListing + """ + + def test_audio_listing_serialization(self): + """ + Test serialization/deserialization for AudioListing + """ + + # Construct dict forms of any model objects needed in order to build this model. + + audio_details_model = {} # AudioDetails + audio_details_model['type'] = 'audio' + audio_details_model['codec'] = 'testString' + audio_details_model['frequency'] = 38 + audio_details_model['compression'] = 'zip' + + audio_resource_model = {} # AudioResource + audio_resource_model['duration'] = 38 + audio_resource_model['name'] = 'testString' + audio_resource_model['details'] = audio_details_model + audio_resource_model['status'] = 'ok' + + # Construct a json representation of a AudioListing model + audio_listing_model_json = {} + audio_listing_model_json['duration'] = 38 + audio_listing_model_json['name'] = 'testString' + audio_listing_model_json['details'] = audio_details_model + audio_listing_model_json['status'] = 'ok' + audio_listing_model_json['container'] = audio_resource_model + audio_listing_model_json['audio'] = [audio_resource_model] + + # Construct a model instance of AudioListing by calling from_dict on the json representation + audio_listing_model = AudioListing.from_dict(audio_listing_model_json) + assert audio_listing_model != False + + # Construct a model instance of AudioListing by calling from_dict on the json representation + audio_listing_model_dict = AudioListing.from_dict(audio_listing_model_json).__dict__ + audio_listing_model2 = AudioListing(**audio_listing_model_dict) + + # Verify the model instances are equivalent + assert audio_listing_model == audio_listing_model2 + + # Convert model instance back to dict and verify no loss of data + audio_listing_model_json2 = audio_listing_model.to_dict() + assert audio_listing_model_json2 == audio_listing_model_json + +class TestAudioMetrics(): + """ + Test Class for AudioMetrics + """ + + def test_audio_metrics_serialization(self): + """ + Test serialization/deserialization for AudioMetrics + """ + + # Construct dict forms of any model objects needed in order to build this model. + + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model['begin'] = 72.5 + audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['count'] = 38 + + audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model['final'] = True + audio_metrics_details_model['end_time'] = 72.5 + audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 + audio_metrics_details_model['speech_ratio'] = 72.5 + audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] + + # Construct a json representation of a AudioMetrics model + audio_metrics_model_json = {} + audio_metrics_model_json['sampling_interval'] = 72.5 + audio_metrics_model_json['accumulated'] = audio_metrics_details_model + + # Construct a model instance of AudioMetrics by calling from_dict on the json representation + audio_metrics_model = AudioMetrics.from_dict(audio_metrics_model_json) + assert audio_metrics_model != False + + # Construct a model instance of AudioMetrics by calling from_dict on the json representation + audio_metrics_model_dict = AudioMetrics.from_dict(audio_metrics_model_json).__dict__ + audio_metrics_model2 = AudioMetrics(**audio_metrics_model_dict) + + # Verify the model instances are equivalent + assert audio_metrics_model == audio_metrics_model2 + + # Convert model instance back to dict and verify no loss of data + audio_metrics_model_json2 = audio_metrics_model.to_dict() + assert audio_metrics_model_json2 == audio_metrics_model_json + +class TestAudioMetricsDetails(): + """ + Test Class for AudioMetricsDetails + """ + + def test_audio_metrics_details_serialization(self): + """ + Test serialization/deserialization for AudioMetricsDetails + """ + + # Construct dict forms of any model objects needed in order to build this model. + + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model['begin'] = 72.5 + audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['count'] = 38 + + # Construct a json representation of a AudioMetricsDetails model + audio_metrics_details_model_json = {} + audio_metrics_details_model_json['final'] = True + audio_metrics_details_model_json['end_time'] = 72.5 + audio_metrics_details_model_json['signal_to_noise_ratio'] = 72.5 + audio_metrics_details_model_json['speech_ratio'] = 72.5 + audio_metrics_details_model_json['high_frequency_loss'] = 72.5 + audio_metrics_details_model_json['direct_current_offset'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model_json['clipping_rate'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model_json['speech_level'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model_json['non_speech_level'] = [audio_metrics_histogram_bin_model] + + # Construct a model instance of AudioMetricsDetails by calling from_dict on the json representation + audio_metrics_details_model = AudioMetricsDetails.from_dict(audio_metrics_details_model_json) + assert audio_metrics_details_model != False + + # Construct a model instance of AudioMetricsDetails by calling from_dict on the json representation + audio_metrics_details_model_dict = AudioMetricsDetails.from_dict(audio_metrics_details_model_json).__dict__ + audio_metrics_details_model2 = AudioMetricsDetails(**audio_metrics_details_model_dict) + + # Verify the model instances are equivalent + assert audio_metrics_details_model == audio_metrics_details_model2 + + # Convert model instance back to dict and verify no loss of data + audio_metrics_details_model_json2 = audio_metrics_details_model.to_dict() + assert audio_metrics_details_model_json2 == audio_metrics_details_model_json + +class TestAudioMetricsHistogramBin(): + """ + Test Class for AudioMetricsHistogramBin + """ + + def test_audio_metrics_histogram_bin_serialization(self): + """ + Test serialization/deserialization for AudioMetricsHistogramBin + """ + + # Construct a json representation of a AudioMetricsHistogramBin model + audio_metrics_histogram_bin_model_json = {} + audio_metrics_histogram_bin_model_json['begin'] = 72.5 + audio_metrics_histogram_bin_model_json['end'] = 72.5 + audio_metrics_histogram_bin_model_json['count'] = 38 + + # Construct a model instance of AudioMetricsHistogramBin by calling from_dict on the json representation + audio_metrics_histogram_bin_model = AudioMetricsHistogramBin.from_dict(audio_metrics_histogram_bin_model_json) + assert audio_metrics_histogram_bin_model != False + + # Construct a model instance of AudioMetricsHistogramBin by calling from_dict on the json representation + audio_metrics_histogram_bin_model_dict = AudioMetricsHistogramBin.from_dict(audio_metrics_histogram_bin_model_json).__dict__ + audio_metrics_histogram_bin_model2 = AudioMetricsHistogramBin(**audio_metrics_histogram_bin_model_dict) + + # Verify the model instances are equivalent + assert audio_metrics_histogram_bin_model == audio_metrics_histogram_bin_model2 + + # Convert model instance back to dict and verify no loss of data + audio_metrics_histogram_bin_model_json2 = audio_metrics_histogram_bin_model.to_dict() + assert audio_metrics_histogram_bin_model_json2 == audio_metrics_histogram_bin_model_json + +class TestAudioResource(): + """ + Test Class for AudioResource + """ + + def test_audio_resource_serialization(self): + """ + Test serialization/deserialization for AudioResource + """ + + # Construct dict forms of any model objects needed in order to build this model. + + audio_details_model = {} # AudioDetails + audio_details_model['type'] = 'audio' + audio_details_model['codec'] = 'testString' + audio_details_model['frequency'] = 38 + audio_details_model['compression'] = 'zip' + + # Construct a json representation of a AudioResource model + audio_resource_model_json = {} + audio_resource_model_json['duration'] = 38 + audio_resource_model_json['name'] = 'testString' + audio_resource_model_json['details'] = audio_details_model + audio_resource_model_json['status'] = 'ok' + + # Construct a model instance of AudioResource by calling from_dict on the json representation + audio_resource_model = AudioResource.from_dict(audio_resource_model_json) + assert audio_resource_model != False + + # Construct a model instance of AudioResource by calling from_dict on the json representation + audio_resource_model_dict = AudioResource.from_dict(audio_resource_model_json).__dict__ + audio_resource_model2 = AudioResource(**audio_resource_model_dict) + + # Verify the model instances are equivalent + assert audio_resource_model == audio_resource_model2 + + # Convert model instance back to dict and verify no loss of data + audio_resource_model_json2 = audio_resource_model.to_dict() + assert audio_resource_model_json2 == audio_resource_model_json + +class TestAudioResources(): + """ + Test Class for AudioResources + """ + + def test_audio_resources_serialization(self): + """ + Test serialization/deserialization for AudioResources + """ + + # Construct dict forms of any model objects needed in order to build this model. + + audio_details_model = {} # AudioDetails + audio_details_model['type'] = 'audio' + audio_details_model['codec'] = 'testString' + audio_details_model['frequency'] = 38 + audio_details_model['compression'] = 'zip' + + audio_resource_model = {} # AudioResource + audio_resource_model['duration'] = 38 + audio_resource_model['name'] = 'testString' + audio_resource_model['details'] = audio_details_model + audio_resource_model['status'] = 'ok' + + # Construct a json representation of a AudioResources model + audio_resources_model_json = {} + audio_resources_model_json['total_minutes_of_audio'] = 72.5 + audio_resources_model_json['audio'] = [audio_resource_model] + + # Construct a model instance of AudioResources by calling from_dict on the json representation + audio_resources_model = AudioResources.from_dict(audio_resources_model_json) + assert audio_resources_model != False + + # Construct a model instance of AudioResources by calling from_dict on the json representation + audio_resources_model_dict = AudioResources.from_dict(audio_resources_model_json).__dict__ + audio_resources_model2 = AudioResources(**audio_resources_model_dict) + + # Verify the model instances are equivalent + assert audio_resources_model == audio_resources_model2 + + # Convert model instance back to dict and verify no loss of data + audio_resources_model_json2 = audio_resources_model.to_dict() + assert audio_resources_model_json2 == audio_resources_model_json + +class TestCorpora(): + """ + Test Class for Corpora + """ + + def test_corpora_serialization(self): + """ + Test serialization/deserialization for Corpora + """ + + # Construct dict forms of any model objects needed in order to build this model. + + corpus_model = {} # Corpus + corpus_model['name'] = 'testString' + corpus_model['total_words'] = 38 + corpus_model['out_of_vocabulary_words'] = 38 + corpus_model['status'] = 'analyzed' + corpus_model['error'] = 'testString' + + # Construct a json representation of a Corpora model + corpora_model_json = {} + corpora_model_json['corpora'] = [corpus_model] + + # Construct a model instance of Corpora by calling from_dict on the json representation + corpora_model = Corpora.from_dict(corpora_model_json) + assert corpora_model != False + + # Construct a model instance of Corpora by calling from_dict on the json representation + corpora_model_dict = Corpora.from_dict(corpora_model_json).__dict__ + corpora_model2 = Corpora(**corpora_model_dict) + + # Verify the model instances are equivalent + assert corpora_model == corpora_model2 + + # Convert model instance back to dict and verify no loss of data + corpora_model_json2 = corpora_model.to_dict() + assert corpora_model_json2 == corpora_model_json + +class TestCorpus(): + """ + Test Class for Corpus + """ + + def test_corpus_serialization(self): + """ + Test serialization/deserialization for Corpus + """ + + # Construct a json representation of a Corpus model + corpus_model_json = {} + corpus_model_json['name'] = 'testString' + corpus_model_json['total_words'] = 38 + corpus_model_json['out_of_vocabulary_words'] = 38 + corpus_model_json['status'] = 'analyzed' + corpus_model_json['error'] = 'testString' + + # Construct a model instance of Corpus by calling from_dict on the json representation + corpus_model = Corpus.from_dict(corpus_model_json) + assert corpus_model != False + + # Construct a model instance of Corpus by calling from_dict on the json representation + corpus_model_dict = Corpus.from_dict(corpus_model_json).__dict__ + corpus_model2 = Corpus(**corpus_model_dict) + + # Verify the model instances are equivalent + assert corpus_model == corpus_model2 + + # Convert model instance back to dict and verify no loss of data + corpus_model_json2 = corpus_model.to_dict() + assert corpus_model_json2 == corpus_model_json + +class TestCustomWord(): + """ + Test Class for CustomWord + """ + + def test_custom_word_serialization(self): + """ + Test serialization/deserialization for CustomWord + """ + + # Construct a json representation of a CustomWord model + custom_word_model_json = {} + custom_word_model_json['word'] = 'testString' + custom_word_model_json['sounds_like'] = ['testString'] + custom_word_model_json['display_as'] = 'testString' + + # Construct a model instance of CustomWord by calling from_dict on the json representation + custom_word_model = CustomWord.from_dict(custom_word_model_json) + assert custom_word_model != False + + # Construct a model instance of CustomWord by calling from_dict on the json representation + custom_word_model_dict = CustomWord.from_dict(custom_word_model_json).__dict__ + custom_word_model2 = CustomWord(**custom_word_model_dict) + + # Verify the model instances are equivalent + assert custom_word_model == custom_word_model2 + + # Convert model instance back to dict and verify no loss of data + custom_word_model_json2 = custom_word_model.to_dict() + assert custom_word_model_json2 == custom_word_model_json + +class TestGrammar(): + """ + Test Class for Grammar + """ + + def test_grammar_serialization(self): + """ + Test serialization/deserialization for Grammar + """ + + # Construct a json representation of a Grammar model + grammar_model_json = {} + grammar_model_json['name'] = 'testString' + grammar_model_json['out_of_vocabulary_words'] = 38 + grammar_model_json['status'] = 'analyzed' + grammar_model_json['error'] = 'testString' + + # Construct a model instance of Grammar by calling from_dict on the json representation + grammar_model = Grammar.from_dict(grammar_model_json) + assert grammar_model != False + + # Construct a model instance of Grammar by calling from_dict on the json representation + grammar_model_dict = Grammar.from_dict(grammar_model_json).__dict__ + grammar_model2 = Grammar(**grammar_model_dict) + + # Verify the model instances are equivalent + assert grammar_model == grammar_model2 + + # Convert model instance back to dict and verify no loss of data + grammar_model_json2 = grammar_model.to_dict() + assert grammar_model_json2 == grammar_model_json + +class TestGrammars(): + """ + Test Class for Grammars + """ + + def test_grammars_serialization(self): + """ + Test serialization/deserialization for Grammars + """ + + # Construct dict forms of any model objects needed in order to build this model. + + grammar_model = {} # Grammar + grammar_model['name'] = 'testString' + grammar_model['out_of_vocabulary_words'] = 38 + grammar_model['status'] = 'analyzed' + grammar_model['error'] = 'testString' + + # Construct a json representation of a Grammars model + grammars_model_json = {} + grammars_model_json['grammars'] = [grammar_model] + + # Construct a model instance of Grammars by calling from_dict on the json representation + grammars_model = Grammars.from_dict(grammars_model_json) + assert grammars_model != False + + # Construct a model instance of Grammars by calling from_dict on the json representation + grammars_model_dict = Grammars.from_dict(grammars_model_json).__dict__ + grammars_model2 = Grammars(**grammars_model_dict) + + # Verify the model instances are equivalent + assert grammars_model == grammars_model2 + + # Convert model instance back to dict and verify no loss of data + grammars_model_json2 = grammars_model.to_dict() + assert grammars_model_json2 == grammars_model_json + +class TestKeywordResult(): + """ + Test Class for KeywordResult + """ + + def test_keyword_result_serialization(self): + """ + Test serialization/deserialization for KeywordResult + """ + + # Construct a json representation of a KeywordResult model + keyword_result_model_json = {} + keyword_result_model_json['normalized_text'] = 'testString' + keyword_result_model_json['start_time'] = 72.5 + keyword_result_model_json['end_time'] = 72.5 + keyword_result_model_json['confidence'] = 0 + + # Construct a model instance of KeywordResult by calling from_dict on the json representation + keyword_result_model = KeywordResult.from_dict(keyword_result_model_json) + assert keyword_result_model != False + + # Construct a model instance of KeywordResult by calling from_dict on the json representation + keyword_result_model_dict = KeywordResult.from_dict(keyword_result_model_json).__dict__ + keyword_result_model2 = KeywordResult(**keyword_result_model_dict) + + # Verify the model instances are equivalent + assert keyword_result_model == keyword_result_model2 + + # Convert model instance back to dict and verify no loss of data + keyword_result_model_json2 = keyword_result_model.to_dict() + assert keyword_result_model_json2 == keyword_result_model_json + +class TestLanguageModel(): + """ + Test Class for LanguageModel + """ + + def test_language_model_serialization(self): + """ + Test serialization/deserialization for LanguageModel + """ + + # Construct a json representation of a LanguageModel model + language_model_model_json = {} + language_model_model_json['customization_id'] = 'testString' + language_model_model_json['created'] = 'testString' + language_model_model_json['updated'] = 'testString' + language_model_model_json['language'] = 'testString' + language_model_model_json['dialect'] = 'testString' + language_model_model_json['versions'] = ['testString'] + language_model_model_json['owner'] = 'testString' + language_model_model_json['name'] = 'testString' + language_model_model_json['description'] = 'testString' + language_model_model_json['base_model_name'] = 'testString' + language_model_model_json['status'] = 'pending' + language_model_model_json['progress'] = 38 + language_model_model_json['error'] = 'testString' + language_model_model_json['warnings'] = 'testString' + + # Construct a model instance of LanguageModel by calling from_dict on the json representation + language_model_model = LanguageModel.from_dict(language_model_model_json) + assert language_model_model != False + + # Construct a model instance of LanguageModel by calling from_dict on the json representation + language_model_model_dict = LanguageModel.from_dict(language_model_model_json).__dict__ + language_model_model2 = LanguageModel(**language_model_model_dict) + + # Verify the model instances are equivalent + assert language_model_model == language_model_model2 + + # Convert model instance back to dict and verify no loss of data + language_model_model_json2 = language_model_model.to_dict() + assert language_model_model_json2 == language_model_model_json + +class TestLanguageModels(): + """ + Test Class for LanguageModels + """ + + def test_language_models_serialization(self): + """ + Test serialization/deserialization for LanguageModels + """ + + # Construct dict forms of any model objects needed in order to build this model. + + language_model_model = {} # LanguageModel + language_model_model['customization_id'] = 'testString' + language_model_model['created'] = 'testString' + language_model_model['updated'] = 'testString' + language_model_model['language'] = 'testString' + language_model_model['dialect'] = 'testString' + language_model_model['versions'] = ['testString'] + language_model_model['owner'] = 'testString' + language_model_model['name'] = 'testString' + language_model_model['description'] = 'testString' + language_model_model['base_model_name'] = 'testString' + language_model_model['status'] = 'pending' + language_model_model['progress'] = 38 + language_model_model['error'] = 'testString' + language_model_model['warnings'] = 'testString' + + # Construct a json representation of a LanguageModels model + language_models_model_json = {} + language_models_model_json['customizations'] = [language_model_model] + + # Construct a model instance of LanguageModels by calling from_dict on the json representation + language_models_model = LanguageModels.from_dict(language_models_model_json) + assert language_models_model != False + + # Construct a model instance of LanguageModels by calling from_dict on the json representation + language_models_model_dict = LanguageModels.from_dict(language_models_model_json).__dict__ + language_models_model2 = LanguageModels(**language_models_model_dict) + + # Verify the model instances are equivalent + assert language_models_model == language_models_model2 + + # Convert model instance back to dict and verify no loss of data + language_models_model_json2 = language_models_model.to_dict() + assert language_models_model_json2 == language_models_model_json + +class TestProcessedAudio(): + """ + Test Class for ProcessedAudio + """ + + def test_processed_audio_serialization(self): + """ + Test serialization/deserialization for ProcessedAudio + """ + + # Construct a json representation of a ProcessedAudio model + processed_audio_model_json = {} + processed_audio_model_json['received'] = 72.5 + processed_audio_model_json['seen_by_engine'] = 72.5 + processed_audio_model_json['transcription'] = 72.5 + processed_audio_model_json['speaker_labels'] = 72.5 + + # Construct a model instance of ProcessedAudio by calling from_dict on the json representation + processed_audio_model = ProcessedAudio.from_dict(processed_audio_model_json) + assert processed_audio_model != False + + # Construct a model instance of ProcessedAudio by calling from_dict on the json representation + processed_audio_model_dict = ProcessedAudio.from_dict(processed_audio_model_json).__dict__ + processed_audio_model2 = ProcessedAudio(**processed_audio_model_dict) + + # Verify the model instances are equivalent + assert processed_audio_model == processed_audio_model2 + + # Convert model instance back to dict and verify no loss of data + processed_audio_model_json2 = processed_audio_model.to_dict() + assert processed_audio_model_json2 == processed_audio_model_json + +class TestProcessingMetrics(): + """ + Test Class for ProcessingMetrics + """ + + def test_processing_metrics_serialization(self): + """ + Test serialization/deserialization for ProcessingMetrics + """ + + # Construct dict forms of any model objects needed in order to build this model. + + processed_audio_model = {} # ProcessedAudio + processed_audio_model['received'] = 72.5 + processed_audio_model['seen_by_engine'] = 72.5 + processed_audio_model['transcription'] = 72.5 + processed_audio_model['speaker_labels'] = 72.5 + + # Construct a json representation of a ProcessingMetrics model + processing_metrics_model_json = {} + processing_metrics_model_json['processed_audio'] = processed_audio_model + processing_metrics_model_json['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model_json['periodic'] = True + + # Construct a model instance of ProcessingMetrics by calling from_dict on the json representation + processing_metrics_model = ProcessingMetrics.from_dict(processing_metrics_model_json) + assert processing_metrics_model != False + + # Construct a model instance of ProcessingMetrics by calling from_dict on the json representation + processing_metrics_model_dict = ProcessingMetrics.from_dict(processing_metrics_model_json).__dict__ + processing_metrics_model2 = ProcessingMetrics(**processing_metrics_model_dict) + + # Verify the model instances are equivalent + assert processing_metrics_model == processing_metrics_model2 + + # Convert model instance back to dict and verify no loss of data + processing_metrics_model_json2 = processing_metrics_model.to_dict() + assert processing_metrics_model_json2 == processing_metrics_model_json + +class TestRecognitionJob(): + """ + Test Class for RecognitionJob + """ + + def test_recognition_job_serialization(self): + """ + Test serialization/deserialization for RecognitionJob + """ + + # Construct dict forms of any model objects needed in order to build this model. + + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model['transcript'] = 'testString' + speech_recognition_alternative_model['confidence'] = 0 + speech_recognition_alternative_model['timestamps'] = ['testString'] + speech_recognition_alternative_model['word_confidence'] = ['testString'] + + keyword_result_model = {} # KeywordResult + keyword_result_model['normalized_text'] = 'testString' + keyword_result_model['start_time'] = 72.5 + keyword_result_model['end_time'] = 72.5 + keyword_result_model['confidence'] = 0 + + word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model['confidence'] = 0 + word_alternative_result_model['word'] = 'testString' + + word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model['start_time'] = 72.5 + word_alternative_results_model['end_time'] = 72.5 + word_alternative_results_model['alternatives'] = [word_alternative_result_model] + + speech_recognition_result_model = {} # SpeechRecognitionResult + speech_recognition_result_model['final'] = True + speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] + speech_recognition_result_model['keywords_result'] = {} + speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] + speech_recognition_result_model['end_of_utterance'] = 'end_of_data' + + speaker_labels_result_model = {} # SpeakerLabelsResult + speaker_labels_result_model['from'] = 72.5 + speaker_labels_result_model['to'] = 72.5 + speaker_labels_result_model['speaker'] = 38 + speaker_labels_result_model['confidence'] = 72.5 + speaker_labels_result_model['final'] = True + + processed_audio_model = {} # ProcessedAudio + processed_audio_model['received'] = 72.5 + processed_audio_model['seen_by_engine'] = 72.5 + processed_audio_model['transcription'] = 72.5 + processed_audio_model['speaker_labels'] = 72.5 + + processing_metrics_model = {} # ProcessingMetrics + processing_metrics_model['processed_audio'] = processed_audio_model + processing_metrics_model['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model['periodic'] = True + + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model['begin'] = 72.5 + audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['count'] = 38 + + audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model['final'] = True + audio_metrics_details_model['end_time'] = 72.5 + audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 + audio_metrics_details_model['speech_ratio'] = 72.5 + audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] + + audio_metrics_model = {} # AudioMetrics + audio_metrics_model['sampling_interval'] = 72.5 + audio_metrics_model['accumulated'] = audio_metrics_details_model + + speech_recognition_results_model = {} # SpeechRecognitionResults + speech_recognition_results_model['results'] = [speech_recognition_result_model] + speech_recognition_results_model['result_index'] = 38 + speech_recognition_results_model['speaker_labels'] = [speaker_labels_result_model] + speech_recognition_results_model['processing_metrics'] = processing_metrics_model + speech_recognition_results_model['audio_metrics'] = audio_metrics_model + speech_recognition_results_model['warnings'] = ['testString'] + + # Construct a json representation of a RecognitionJob model + recognition_job_model_json = {} + recognition_job_model_json['id'] = 'testString' + recognition_job_model_json['status'] = 'waiting' + recognition_job_model_json['created'] = 'testString' + recognition_job_model_json['updated'] = 'testString' + recognition_job_model_json['url'] = 'testString' + recognition_job_model_json['user_token'] = 'testString' + recognition_job_model_json['results'] = [speech_recognition_results_model] + recognition_job_model_json['warnings'] = ['testString'] + + # Construct a model instance of RecognitionJob by calling from_dict on the json representation + recognition_job_model = RecognitionJob.from_dict(recognition_job_model_json) + assert recognition_job_model != False + + # Construct a model instance of RecognitionJob by calling from_dict on the json representation + recognition_job_model_dict = RecognitionJob.from_dict(recognition_job_model_json).__dict__ + recognition_job_model2 = RecognitionJob(**recognition_job_model_dict) + + # Verify the model instances are equivalent + assert recognition_job_model == recognition_job_model2 + + # Convert model instance back to dict and verify no loss of data + recognition_job_model_json2 = recognition_job_model.to_dict() + assert recognition_job_model_json2 == recognition_job_model_json + +class TestRecognitionJobs(): + """ + Test Class for RecognitionJobs + """ + + def test_recognition_jobs_serialization(self): + """ + Test serialization/deserialization for RecognitionJobs + """ + + # Construct dict forms of any model objects needed in order to build this model. + + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model['transcript'] = 'testString' + speech_recognition_alternative_model['confidence'] = 0 + speech_recognition_alternative_model['timestamps'] = ['testString'] + speech_recognition_alternative_model['word_confidence'] = ['testString'] + + keyword_result_model = {} # KeywordResult + keyword_result_model['normalized_text'] = 'testString' + keyword_result_model['start_time'] = 72.5 + keyword_result_model['end_time'] = 72.5 + keyword_result_model['confidence'] = 0 + + word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model['confidence'] = 0 + word_alternative_result_model['word'] = 'testString' + + word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model['start_time'] = 72.5 + word_alternative_results_model['end_time'] = 72.5 + word_alternative_results_model['alternatives'] = [word_alternative_result_model] + + speech_recognition_result_model = {} # SpeechRecognitionResult + speech_recognition_result_model['final'] = True + speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] + speech_recognition_result_model['keywords_result'] = {} + speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] + speech_recognition_result_model['end_of_utterance'] = 'end_of_data' + + speaker_labels_result_model = {} # SpeakerLabelsResult + speaker_labels_result_model['from'] = 72.5 + speaker_labels_result_model['to'] = 72.5 + speaker_labels_result_model['speaker'] = 38 + speaker_labels_result_model['confidence'] = 72.5 + speaker_labels_result_model['final'] = True + + processed_audio_model = {} # ProcessedAudio + processed_audio_model['received'] = 72.5 + processed_audio_model['seen_by_engine'] = 72.5 + processed_audio_model['transcription'] = 72.5 + processed_audio_model['speaker_labels'] = 72.5 + + processing_metrics_model = {} # ProcessingMetrics + processing_metrics_model['processed_audio'] = processed_audio_model + processing_metrics_model['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model['periodic'] = True + + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model['begin'] = 72.5 + audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['count'] = 38 + + audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model['final'] = True + audio_metrics_details_model['end_time'] = 72.5 + audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 + audio_metrics_details_model['speech_ratio'] = 72.5 + audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] + + audio_metrics_model = {} # AudioMetrics + audio_metrics_model['sampling_interval'] = 72.5 + audio_metrics_model['accumulated'] = audio_metrics_details_model + + speech_recognition_results_model = {} # SpeechRecognitionResults + speech_recognition_results_model['results'] = [speech_recognition_result_model] + speech_recognition_results_model['result_index'] = 38 + speech_recognition_results_model['speaker_labels'] = [speaker_labels_result_model] + speech_recognition_results_model['processing_metrics'] = processing_metrics_model + speech_recognition_results_model['audio_metrics'] = audio_metrics_model + speech_recognition_results_model['warnings'] = ['testString'] + + recognition_job_model = {} # RecognitionJob + recognition_job_model['id'] = 'testString' + recognition_job_model['status'] = 'waiting' + recognition_job_model['created'] = 'testString' + recognition_job_model['updated'] = 'testString' + recognition_job_model['url'] = 'testString' + recognition_job_model['user_token'] = 'testString' + recognition_job_model['results'] = [speech_recognition_results_model] + recognition_job_model['warnings'] = ['testString'] + + # Construct a json representation of a RecognitionJobs model + recognition_jobs_model_json = {} + recognition_jobs_model_json['recognitions'] = [recognition_job_model] + + # Construct a model instance of RecognitionJobs by calling from_dict on the json representation + recognition_jobs_model = RecognitionJobs.from_dict(recognition_jobs_model_json) + assert recognition_jobs_model != False + + # Construct a model instance of RecognitionJobs by calling from_dict on the json representation + recognition_jobs_model_dict = RecognitionJobs.from_dict(recognition_jobs_model_json).__dict__ + recognition_jobs_model2 = RecognitionJobs(**recognition_jobs_model_dict) + + # Verify the model instances are equivalent + assert recognition_jobs_model == recognition_jobs_model2 + + # Convert model instance back to dict and verify no loss of data + recognition_jobs_model_json2 = recognition_jobs_model.to_dict() + assert recognition_jobs_model_json2 == recognition_jobs_model_json + +class TestRegisterStatus(): + """ + Test Class for RegisterStatus + """ + + def test_register_status_serialization(self): + """ + Test serialization/deserialization for RegisterStatus + """ + + # Construct a json representation of a RegisterStatus model + register_status_model_json = {} + register_status_model_json['status'] = 'created' + register_status_model_json['url'] = 'testString' + + # Construct a model instance of RegisterStatus by calling from_dict on the json representation + register_status_model = RegisterStatus.from_dict(register_status_model_json) + assert register_status_model != False + + # Construct a model instance of RegisterStatus by calling from_dict on the json representation + register_status_model_dict = RegisterStatus.from_dict(register_status_model_json).__dict__ + register_status_model2 = RegisterStatus(**register_status_model_dict) + + # Verify the model instances are equivalent + assert register_status_model == register_status_model2 + + # Convert model instance back to dict and verify no loss of data + register_status_model_json2 = register_status_model.to_dict() + assert register_status_model_json2 == register_status_model_json + +class TestSpeakerLabelsResult(): + """ + Test Class for SpeakerLabelsResult + """ + + def test_speaker_labels_result_serialization(self): + """ + Test serialization/deserialization for SpeakerLabelsResult + """ + + # Construct a json representation of a SpeakerLabelsResult model + speaker_labels_result_model_json = {} + speaker_labels_result_model_json['from'] = 72.5 + speaker_labels_result_model_json['to'] = 72.5 + speaker_labels_result_model_json['speaker'] = 38 + speaker_labels_result_model_json['confidence'] = 72.5 + speaker_labels_result_model_json['final'] = True + + # Construct a model instance of SpeakerLabelsResult by calling from_dict on the json representation + speaker_labels_result_model = SpeakerLabelsResult.from_dict(speaker_labels_result_model_json) + assert speaker_labels_result_model != False + + # Construct a model instance of SpeakerLabelsResult by calling from_dict on the json representation + speaker_labels_result_model_dict = SpeakerLabelsResult.from_dict(speaker_labels_result_model_json).__dict__ + speaker_labels_result_model2 = SpeakerLabelsResult(**speaker_labels_result_model_dict) + + # Verify the model instances are equivalent + assert speaker_labels_result_model == speaker_labels_result_model2 + + # Convert model instance back to dict and verify no loss of data + speaker_labels_result_model_json2 = speaker_labels_result_model.to_dict() + assert speaker_labels_result_model_json2 == speaker_labels_result_model_json + +class TestSpeechModel(): + """ + Test Class for SpeechModel + """ + + def test_speech_model_serialization(self): + """ + Test serialization/deserialization for SpeechModel + """ + + # Construct dict forms of any model objects needed in order to build this model. + + supported_features_model = {} # SupportedFeatures + supported_features_model['custom_language_model'] = True + supported_features_model['speaker_labels'] = True + + # Construct a json representation of a SpeechModel model + speech_model_model_json = {} + speech_model_model_json['name'] = 'testString' + speech_model_model_json['language'] = 'testString' + speech_model_model_json['rate'] = 38 + speech_model_model_json['url'] = 'testString' + speech_model_model_json['supported_features'] = supported_features_model + speech_model_model_json['description'] = 'testString' + + # Construct a model instance of SpeechModel by calling from_dict on the json representation + speech_model_model = SpeechModel.from_dict(speech_model_model_json) + assert speech_model_model != False + + # Construct a model instance of SpeechModel by calling from_dict on the json representation + speech_model_model_dict = SpeechModel.from_dict(speech_model_model_json).__dict__ + speech_model_model2 = SpeechModel(**speech_model_model_dict) + + # Verify the model instances are equivalent + assert speech_model_model == speech_model_model2 + + # Convert model instance back to dict and verify no loss of data + speech_model_model_json2 = speech_model_model.to_dict() + assert speech_model_model_json2 == speech_model_model_json + +class TestSpeechModels(): + """ + Test Class for SpeechModels + """ + + def test_speech_models_serialization(self): + """ + Test serialization/deserialization for SpeechModels + """ + + # Construct dict forms of any model objects needed in order to build this model. + + supported_features_model = {} # SupportedFeatures + supported_features_model['custom_language_model'] = True + supported_features_model['speaker_labels'] = True + + speech_model_model = {} # SpeechModel + speech_model_model['name'] = 'testString' + speech_model_model['language'] = 'testString' + speech_model_model['rate'] = 38 + speech_model_model['url'] = 'testString' + speech_model_model['supported_features'] = supported_features_model + speech_model_model['description'] = 'testString' + + # Construct a json representation of a SpeechModels model + speech_models_model_json = {} + speech_models_model_json['models'] = [speech_model_model] + + # Construct a model instance of SpeechModels by calling from_dict on the json representation + speech_models_model = SpeechModels.from_dict(speech_models_model_json) + assert speech_models_model != False + + # Construct a model instance of SpeechModels by calling from_dict on the json representation + speech_models_model_dict = SpeechModels.from_dict(speech_models_model_json).__dict__ + speech_models_model2 = SpeechModels(**speech_models_model_dict) + + # Verify the model instances are equivalent + assert speech_models_model == speech_models_model2 + + # Convert model instance back to dict and verify no loss of data + speech_models_model_json2 = speech_models_model.to_dict() + assert speech_models_model_json2 == speech_models_model_json + +class TestSpeechRecognitionAlternative(): + """ + Test Class for SpeechRecognitionAlternative + """ + + def test_speech_recognition_alternative_serialization(self): + """ + Test serialization/deserialization for SpeechRecognitionAlternative + """ + + # Construct a json representation of a SpeechRecognitionAlternative model + speech_recognition_alternative_model_json = {} + speech_recognition_alternative_model_json['transcript'] = 'testString' + speech_recognition_alternative_model_json['confidence'] = 0 + speech_recognition_alternative_model_json['timestamps'] = ['testString'] + speech_recognition_alternative_model_json['word_confidence'] = ['testString'] + + # Construct a model instance of SpeechRecognitionAlternative by calling from_dict on the json representation + speech_recognition_alternative_model = SpeechRecognitionAlternative.from_dict(speech_recognition_alternative_model_json) + assert speech_recognition_alternative_model != False + + # Construct a model instance of SpeechRecognitionAlternative by calling from_dict on the json representation + speech_recognition_alternative_model_dict = SpeechRecognitionAlternative.from_dict(speech_recognition_alternative_model_json).__dict__ + speech_recognition_alternative_model2 = SpeechRecognitionAlternative(**speech_recognition_alternative_model_dict) + + # Verify the model instances are equivalent + assert speech_recognition_alternative_model == speech_recognition_alternative_model2 + + # Convert model instance back to dict and verify no loss of data + speech_recognition_alternative_model_json2 = speech_recognition_alternative_model.to_dict() + assert speech_recognition_alternative_model_json2 == speech_recognition_alternative_model_json + +class TestSpeechRecognitionResult(): + """ + Test Class for SpeechRecognitionResult + """ + + def test_speech_recognition_result_serialization(self): + """ + Test serialization/deserialization for SpeechRecognitionResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model['transcript'] = 'testString' + speech_recognition_alternative_model['confidence'] = 0 + speech_recognition_alternative_model['timestamps'] = ['testString'] + speech_recognition_alternative_model['word_confidence'] = ['testString'] + + keyword_result_model = {} # KeywordResult + keyword_result_model['normalized_text'] = 'testString' + keyword_result_model['start_time'] = 72.5 + keyword_result_model['end_time'] = 72.5 + keyword_result_model['confidence'] = 0 + + word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model['confidence'] = 0 + word_alternative_result_model['word'] = 'testString' + + word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model['start_time'] = 72.5 + word_alternative_results_model['end_time'] = 72.5 + word_alternative_results_model['alternatives'] = [word_alternative_result_model] + + # Construct a json representation of a SpeechRecognitionResult model + speech_recognition_result_model_json = {} + speech_recognition_result_model_json['final'] = True + speech_recognition_result_model_json['alternatives'] = [speech_recognition_alternative_model] + speech_recognition_result_model_json['keywords_result'] = {} + speech_recognition_result_model_json['word_alternatives'] = [word_alternative_results_model] + speech_recognition_result_model_json['end_of_utterance'] = 'end_of_data' + + # Construct a model instance of SpeechRecognitionResult by calling from_dict on the json representation + speech_recognition_result_model = SpeechRecognitionResult.from_dict(speech_recognition_result_model_json) + assert speech_recognition_result_model != False + + # Construct a model instance of SpeechRecognitionResult by calling from_dict on the json representation + speech_recognition_result_model_dict = SpeechRecognitionResult.from_dict(speech_recognition_result_model_json).__dict__ + speech_recognition_result_model2 = SpeechRecognitionResult(**speech_recognition_result_model_dict) + + # Verify the model instances are equivalent + assert speech_recognition_result_model == speech_recognition_result_model2 + + # Convert model instance back to dict and verify no loss of data + speech_recognition_result_model_json2 = speech_recognition_result_model.to_dict() + assert speech_recognition_result_model_json2 == speech_recognition_result_model_json + +class TestSpeechRecognitionResults(): + """ + Test Class for SpeechRecognitionResults + """ + + def test_speech_recognition_results_serialization(self): + """ + Test serialization/deserialization for SpeechRecognitionResults + """ + + # Construct dict forms of any model objects needed in order to build this model. + + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model['transcript'] = 'testString' + speech_recognition_alternative_model['confidence'] = 0 + speech_recognition_alternative_model['timestamps'] = ['testString'] + speech_recognition_alternative_model['word_confidence'] = ['testString'] + + keyword_result_model = {} # KeywordResult + keyword_result_model['normalized_text'] = 'testString' + keyword_result_model['start_time'] = 72.5 + keyword_result_model['end_time'] = 72.5 + keyword_result_model['confidence'] = 0 + + word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model['confidence'] = 0 + word_alternative_result_model['word'] = 'testString' + + word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model['start_time'] = 72.5 + word_alternative_results_model['end_time'] = 72.5 + word_alternative_results_model['alternatives'] = [word_alternative_result_model] + + speech_recognition_result_model = {} # SpeechRecognitionResult + speech_recognition_result_model['final'] = True + speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] + speech_recognition_result_model['keywords_result'] = {} + speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] + speech_recognition_result_model['end_of_utterance'] = 'end_of_data' + + speaker_labels_result_model = {} # SpeakerLabelsResult + speaker_labels_result_model['from'] = 72.5 + speaker_labels_result_model['to'] = 72.5 + speaker_labels_result_model['speaker'] = 38 + speaker_labels_result_model['confidence'] = 72.5 + speaker_labels_result_model['final'] = True + + processed_audio_model = {} # ProcessedAudio + processed_audio_model['received'] = 72.5 + processed_audio_model['seen_by_engine'] = 72.5 + processed_audio_model['transcription'] = 72.5 + processed_audio_model['speaker_labels'] = 72.5 + + processing_metrics_model = {} # ProcessingMetrics + processing_metrics_model['processed_audio'] = processed_audio_model + processing_metrics_model['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model['periodic'] = True + + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model['begin'] = 72.5 + audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['count'] = 38 + + audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model['final'] = True + audio_metrics_details_model['end_time'] = 72.5 + audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 + audio_metrics_details_model['speech_ratio'] = 72.5 + audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] + audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] + + audio_metrics_model = {} # AudioMetrics + audio_metrics_model['sampling_interval'] = 72.5 + audio_metrics_model['accumulated'] = audio_metrics_details_model + + # Construct a json representation of a SpeechRecognitionResults model + speech_recognition_results_model_json = {} + speech_recognition_results_model_json['results'] = [speech_recognition_result_model] + speech_recognition_results_model_json['result_index'] = 38 + speech_recognition_results_model_json['speaker_labels'] = [speaker_labels_result_model] + speech_recognition_results_model_json['processing_metrics'] = processing_metrics_model + speech_recognition_results_model_json['audio_metrics'] = audio_metrics_model + speech_recognition_results_model_json['warnings'] = ['testString'] + + # Construct a model instance of SpeechRecognitionResults by calling from_dict on the json representation + speech_recognition_results_model = SpeechRecognitionResults.from_dict(speech_recognition_results_model_json) + assert speech_recognition_results_model != False + + # Construct a model instance of SpeechRecognitionResults by calling from_dict on the json representation + speech_recognition_results_model_dict = SpeechRecognitionResults.from_dict(speech_recognition_results_model_json).__dict__ + speech_recognition_results_model2 = SpeechRecognitionResults(**speech_recognition_results_model_dict) + + # Verify the model instances are equivalent + assert speech_recognition_results_model == speech_recognition_results_model2 + + # Convert model instance back to dict and verify no loss of data + speech_recognition_results_model_json2 = speech_recognition_results_model.to_dict() + assert speech_recognition_results_model_json2 == speech_recognition_results_model_json + +class TestSupportedFeatures(): + """ + Test Class for SupportedFeatures + """ + + def test_supported_features_serialization(self): + """ + Test serialization/deserialization for SupportedFeatures + """ + + # Construct a json representation of a SupportedFeatures model + supported_features_model_json = {} + supported_features_model_json['custom_language_model'] = True + supported_features_model_json['speaker_labels'] = True + + # Construct a model instance of SupportedFeatures by calling from_dict on the json representation + supported_features_model = SupportedFeatures.from_dict(supported_features_model_json) + assert supported_features_model != False + + # Construct a model instance of SupportedFeatures by calling from_dict on the json representation + supported_features_model_dict = SupportedFeatures.from_dict(supported_features_model_json).__dict__ + supported_features_model2 = SupportedFeatures(**supported_features_model_dict) + + # Verify the model instances are equivalent + assert supported_features_model == supported_features_model2 + + # Convert model instance back to dict and verify no loss of data + supported_features_model_json2 = supported_features_model.to_dict() + assert supported_features_model_json2 == supported_features_model_json + +class TestTrainingResponse(): + """ + Test Class for TrainingResponse + """ + + def test_training_response_serialization(self): + """ + Test serialization/deserialization for TrainingResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + training_warning_model = {} # TrainingWarning + training_warning_model['code'] = 'invalid_audio_files' + training_warning_model['message'] = 'testString' + + # Construct a json representation of a TrainingResponse model + training_response_model_json = {} + training_response_model_json['warnings'] = [training_warning_model] + + # Construct a model instance of TrainingResponse by calling from_dict on the json representation + training_response_model = TrainingResponse.from_dict(training_response_model_json) + assert training_response_model != False + + # Construct a model instance of TrainingResponse by calling from_dict on the json representation + training_response_model_dict = TrainingResponse.from_dict(training_response_model_json).__dict__ + training_response_model2 = TrainingResponse(**training_response_model_dict) + + # Verify the model instances are equivalent + assert training_response_model == training_response_model2 + + # Convert model instance back to dict and verify no loss of data + training_response_model_json2 = training_response_model.to_dict() + assert training_response_model_json2 == training_response_model_json + +class TestTrainingWarning(): + """ + Test Class for TrainingWarning + """ + + def test_training_warning_serialization(self): + """ + Test serialization/deserialization for TrainingWarning + """ + + # Construct a json representation of a TrainingWarning model + training_warning_model_json = {} + training_warning_model_json['code'] = 'invalid_audio_files' + training_warning_model_json['message'] = 'testString' + + # Construct a model instance of TrainingWarning by calling from_dict on the json representation + training_warning_model = TrainingWarning.from_dict(training_warning_model_json) + assert training_warning_model != False + + # Construct a model instance of TrainingWarning by calling from_dict on the json representation + training_warning_model_dict = TrainingWarning.from_dict(training_warning_model_json).__dict__ + training_warning_model2 = TrainingWarning(**training_warning_model_dict) + + # Verify the model instances are equivalent + assert training_warning_model == training_warning_model2 + + # Convert model instance back to dict and verify no loss of data + training_warning_model_json2 = training_warning_model.to_dict() + assert training_warning_model_json2 == training_warning_model_json + +class TestWord(): + """ + Test Class for Word + """ + + def test_word_serialization(self): + """ + Test serialization/deserialization for Word + """ + + # Construct dict forms of any model objects needed in order to build this model. + + word_error_model = {} # WordError + word_error_model['element'] = 'testString' + + # Construct a json representation of a Word model + word_model_json = {} + word_model_json['word'] = 'testString' + word_model_json['sounds_like'] = ['testString'] + word_model_json['display_as'] = 'testString' + word_model_json['count'] = 38 + word_model_json['source'] = ['testString'] + word_model_json['error'] = [word_error_model] + + # Construct a model instance of Word by calling from_dict on the json representation + word_model = Word.from_dict(word_model_json) + assert word_model != False + + # Construct a model instance of Word by calling from_dict on the json representation + word_model_dict = Word.from_dict(word_model_json).__dict__ + word_model2 = Word(**word_model_dict) + + # Verify the model instances are equivalent + assert word_model == word_model2 + + # Convert model instance back to dict and verify no loss of data + word_model_json2 = word_model.to_dict() + assert word_model_json2 == word_model_json + +class TestWordAlternativeResult(): + """ + Test Class for WordAlternativeResult + """ + + def test_word_alternative_result_serialization(self): + """ + Test serialization/deserialization for WordAlternativeResult + """ + + # Construct a json representation of a WordAlternativeResult model + word_alternative_result_model_json = {} + word_alternative_result_model_json['confidence'] = 0 + word_alternative_result_model_json['word'] = 'testString' + + # Construct a model instance of WordAlternativeResult by calling from_dict on the json representation + word_alternative_result_model = WordAlternativeResult.from_dict(word_alternative_result_model_json) + assert word_alternative_result_model != False + + # Construct a model instance of WordAlternativeResult by calling from_dict on the json representation + word_alternative_result_model_dict = WordAlternativeResult.from_dict(word_alternative_result_model_json).__dict__ + word_alternative_result_model2 = WordAlternativeResult(**word_alternative_result_model_dict) + + # Verify the model instances are equivalent + assert word_alternative_result_model == word_alternative_result_model2 + + # Convert model instance back to dict and verify no loss of data + word_alternative_result_model_json2 = word_alternative_result_model.to_dict() + assert word_alternative_result_model_json2 == word_alternative_result_model_json + +class TestWordAlternativeResults(): + """ + Test Class for WordAlternativeResults + """ + + def test_word_alternative_results_serialization(self): + """ + Test serialization/deserialization for WordAlternativeResults + """ + + # Construct dict forms of any model objects needed in order to build this model. + + word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model['confidence'] = 0 + word_alternative_result_model['word'] = 'testString' + + # Construct a json representation of a WordAlternativeResults model + word_alternative_results_model_json = {} + word_alternative_results_model_json['start_time'] = 72.5 + word_alternative_results_model_json['end_time'] = 72.5 + word_alternative_results_model_json['alternatives'] = [word_alternative_result_model] + + # Construct a model instance of WordAlternativeResults by calling from_dict on the json representation + word_alternative_results_model = WordAlternativeResults.from_dict(word_alternative_results_model_json) + assert word_alternative_results_model != False + + # Construct a model instance of WordAlternativeResults by calling from_dict on the json representation + word_alternative_results_model_dict = WordAlternativeResults.from_dict(word_alternative_results_model_json).__dict__ + word_alternative_results_model2 = WordAlternativeResults(**word_alternative_results_model_dict) + + # Verify the model instances are equivalent + assert word_alternative_results_model == word_alternative_results_model2 + + # Convert model instance back to dict and verify no loss of data + word_alternative_results_model_json2 = word_alternative_results_model.to_dict() + assert word_alternative_results_model_json2 == word_alternative_results_model_json + +class TestWordError(): + """ + Test Class for WordError + """ + + def test_word_error_serialization(self): + """ + Test serialization/deserialization for WordError + """ + + # Construct a json representation of a WordError model + word_error_model_json = {} + word_error_model_json['element'] = 'testString' + + # Construct a model instance of WordError by calling from_dict on the json representation + word_error_model = WordError.from_dict(word_error_model_json) + assert word_error_model != False + + # Construct a model instance of WordError by calling from_dict on the json representation + word_error_model_dict = WordError.from_dict(word_error_model_json).__dict__ + word_error_model2 = WordError(**word_error_model_dict) + + # Verify the model instances are equivalent + assert word_error_model == word_error_model2 + + # Convert model instance back to dict and verify no loss of data + word_error_model_json2 = word_error_model.to_dict() + assert word_error_model_json2 == word_error_model_json + +class TestWords(): + """ + Test Class for Words + """ + + def test_words_serialization(self): + """ + Test serialization/deserialization for Words + """ + + # Construct dict forms of any model objects needed in order to build this model. + + word_error_model = {} # WordError + word_error_model['element'] = 'testString' + + word_model = {} # Word + word_model['word'] = 'testString' + word_model['sounds_like'] = ['testString'] + word_model['display_as'] = 'testString' + word_model['count'] = 38 + word_model['source'] = ['testString'] + word_model['error'] = [word_error_model] + + # Construct a json representation of a Words model + words_model_json = {} + words_model_json['words'] = [word_model] + + # Construct a model instance of Words by calling from_dict on the json representation + words_model = Words.from_dict(words_model_json) + assert words_model != False + + # Construct a model instance of Words by calling from_dict on the json representation + words_model_dict = Words.from_dict(words_model_json).__dict__ + words_model2 = Words(**words_model_dict) + + # Verify the model instances are equivalent + assert words_model == words_model2 + + # Convert model instance back to dict and verify no loss of data + words_model_json2 = words_model.to_dict() + assert words_model_json2 == words_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 27585b063..ddb5a74d0 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -13,155 +13,172 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Unit Tests for TextToSpeechV1 +""" + from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect import json import pytest +import re +import requests import responses -import ibm_watson.text_to_speech_v1 +import urllib from ibm_watson.text_to_speech_v1 import * + +service = TextToSpeechV1( + authenticator=NoAuthAuthenticator() + ) + base_url = 'https://api.us-south.text-to-speech.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: Voices ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_voices -#----------------------------------------------------------------------------- class TestListVoices(): + """ + Test Class for list_voices + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_voices_response(self): - body = self.construct_full_body() - response = fake_response_Voices_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_voices_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Voices_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_voices_all_params(self): + """ + list_voices() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/voices') + mock_response = '{"voices": [{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_voices_empty(self): - check_empty_response(self) + # Invoke method + response = service.list_voices() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/voices' - 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 = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.list_voices(**body) - return output - - def construct_full_body(self): - body = dict() - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_voice -#----------------------------------------------------------------------------- class TestGetVoice(): + """ + Test Class for get_voice + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_voice_response(self): - body = self.construct_full_body() - response = fake_response_Voice_json - send_request(self, body, response) + def test_get_voice_all_params(self): + """ + get_voice() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/voices/ar-AR_OmarVoice') + mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + voice = 'ar-AR_OmarVoice' + customization_id = 'testString' + + # Invoke method + response = service.get_voice( + voice, + customization_id=customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'customization_id={}'.format(customization_id) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_voice_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Voice_json - send_request(self, body, response) + def test_get_voice_required_params(self): + """ + test_get_voice_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/voices/ar-AR_OmarVoice') + mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + voice = 'ar-AR_OmarVoice' + + # Invoke method + response = service.get_voice( + voice, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_voice_empty(self): - check_empty_required_params(self, fake_response_Voice_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/voices/{0}'.format(body['voice']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_voice_value_error(self): + """ + test_get_voice_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/voices/ar-AR_OmarVoice') + mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_voice(**body) - return output - - def construct_full_body(self): - body = dict() - body['voice'] = "string1" - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['voice'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + voice = 'ar-AR_OmarVoice' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "voice": voice, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_voice(**req_copy) + # endregion @@ -174,76 +191,119 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for synthesize -#----------------------------------------------------------------------------- class TestSynthesize(): + """ + Test Class for synthesize + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_synthesize_response(self): - body = self.construct_full_body() - response = fake_response_BinaryIO_json - send_request(self, body, response) + def test_synthesize_all_params(self): + """ + synthesize() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/synthesize') + mock_response = 'This is a mock binary response.' + responses.add(responses.POST, + url, + body=mock_response, + content_type='audio/basic', + status=200) + + # Set up parameter values + text = 'testString' + accept = 'audio/basic' + voice = 'ar-AR_OmarVoice' + customization_id = 'testString' + + # Invoke method + response = service.synthesize( + text, + accept=accept, + voice=voice, + customization_id=customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'voice={}'.format(voice) in query_string + assert 'customization_id={}'.format(customization_id) in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == 'testString' + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_synthesize_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_BinaryIO_json - send_request(self, body, response) + def test_synthesize_required_params(self): + """ + test_synthesize_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/synthesize') + mock_response = 'This is a mock binary response.' + responses.add(responses.POST, + url, + body=mock_response, + content_type='audio/basic', + status=200) + + # Set up parameter values + text = 'testString' + + # Invoke method + response = service.synthesize( + text, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['text'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_synthesize_empty(self): - check_empty_required_params(self, fake_response_BinaryIO_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/synthesize' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_synthesize_value_error(self): + """ + test_synthesize_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/synthesize') + mock_response = 'This is a mock binary response.' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.synthesize(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"text": "string1", }) - body['accept'] = "string1" - body['voice'] = "string1" - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body.update({"text": "string1", }) - return body + url, + body=mock_response, + content_type='audio/basic', + status=200) + + # Set up parameter values + text = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.synthesize(**req_copy) + # endregion @@ -256,76 +316,119 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for get_pronunciation -#----------------------------------------------------------------------------- class TestGetPronunciation(): + """ + Test Class for get_pronunciation + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_pronunciation_response(self): - body = self.construct_full_body() - response = fake_response_Pronunciation_json - send_request(self, body, response) + def test_get_pronunciation_all_params(self): + """ + get_pronunciation() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/pronunciation') + mock_response = '{"pronunciation": "pronunciation"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + text = 'testString' + voice = 'ar-AR_OmarVoice' + format = 'ibm' + customization_id = 'testString' + + # Invoke method + response = service.get_pronunciation( + text, + voice=voice, + format=format, + customization_id=customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'text={}'.format(text) in query_string + assert 'voice={}'.format(voice) in query_string + assert 'format={}'.format(format) in query_string + assert 'customization_id={}'.format(customization_id) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_pronunciation_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Pronunciation_json - send_request(self, body, response) + def test_get_pronunciation_required_params(self): + """ + test_get_pronunciation_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/pronunciation') + mock_response = '{"pronunciation": "pronunciation"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + text = 'testString' + + # Invoke method + response = service.get_pronunciation( + text, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'text={}'.format(text) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_pronunciation_empty(self): - check_empty_required_params(self, fake_response_Pronunciation_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/pronunciation' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_pronunciation_value_error(self): + """ + test_get_pronunciation_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/pronunciation') + mock_response = '{"pronunciation": "pronunciation"}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_pronunciation(**body) - return output - - def construct_full_body(self): - body = dict() - body['text'] = "string1" - body['voice'] = "string1" - body['format'] = "string1" - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['text'] = "string1" - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + text = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "text": text, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_pronunciation(**req_copy) + # endregion @@ -338,349 +441,378 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_custom_model -#----------------------------------------------------------------------------- class TestCreateCustomModel(): + """ + Test Class for create_custom_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_custom_model_response(self): - body = self.construct_full_body() - response = fake_response_CustomModel_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_custom_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_CustomModel_json - send_request(self, body, response) + def test_create_custom_model_all_params(self): + """ + create_custom_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations') + mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + name = 'testString' + language = 'de-DE' + description = 'testString' + + # Invoke method + response = service.create_custom_model( + name, + language=language, + description=description, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['language'] == 'de-DE' + assert req_body['description'] == 'testString' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_custom_model_empty(self): - check_empty_required_params(self, fake_response_CustomModel_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_create_custom_model_value_error(self): + """ + test_create_custom_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations') + mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=201, - content_type='application/json') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.create_custom_model(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"name": "string1", "language": "string1", "description": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body.update({"name": "string1", "language": "string1", "description": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_custom_models -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + name = 'testString' + language = 'de-DE' + description = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_custom_model(**req_copy) + + + class TestListCustomModels(): + """ + Test Class for list_custom_models + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_custom_models_response(self): - body = self.construct_full_body() - response = fake_response_CustomModels_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_custom_models_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_CustomModels_json - send_request(self, body, response) + def test_list_custom_models_all_params(self): + """ + list_custom_models() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations') + mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + language = 'de-DE' + + # Invoke method + response = service.list_custom_models( + language=language, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'language={}'.format(language) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_custom_models_empty(self): - check_empty_response(self) + def test_list_custom_models_required_params(self): + """ + test_list_custom_models_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations') + mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = service.list_custom_models() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations' - 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 = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.list_custom_models(**body) - return output - - def construct_full_body(self): - body = dict() - body['language'] = "string1" - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_custom_model -#----------------------------------------------------------------------------- class TestUpdateCustomModel(): + """ + Test Class for update_custom_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_update_custom_model_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_custom_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_update_custom_model_all_params(self): + """ + update_custom_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString') + responses.add(responses.POST, + url, + status=200) + + # Construct a dict representation of a Word model + word_model = {} + word_model['word'] = 'testString' + word_model['translation'] = 'testString' + word_model['part_of_speech'] = 'Dosi' + + # Set up parameter values + customization_id = 'testString' + name = 'testString' + description = 'testString' + words = [word_model] + + # Invoke method + response = service.update_custom_model( + customization_id, + name=name, + description=description, + words=words, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['words'] == [word_model] + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_custom_model_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 = '/v1/customizations/{0}'.format(body['customization_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_update_custom_model_value_error(self): + """ + test_update_custom_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString') responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.update_custom_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body.update({"name": "string1", "description": "string1", "words": [], }) - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body.update({"name": "string1", "description": "string1", "words": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_custom_model -#----------------------------------------------------------------------------- + url, + status=200) + + # Construct a dict representation of a Word model + word_model = {} + word_model['word'] = 'testString' + word_model['translation'] = 'testString' + word_model['part_of_speech'] = 'Dosi' + + # Set up parameter values + customization_id = 'testString' + name = 'testString' + description = 'testString' + words = [word_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_custom_model(**req_copy) + + + class TestGetCustomModel(): + """ + Test Class for get_custom_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_custom_model_response(self): - body = self.construct_full_body() - response = fake_response_CustomModel_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_custom_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_CustomModel_json - send_request(self, body, response) + def test_get_custom_model_all_params(self): + """ + get_custom_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString') + mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.get_custom_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_custom_model_empty(self): - check_empty_required_params(self, fake_response_CustomModel_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}'.format(body['customization_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_custom_model_value_error(self): + """ + test_get_custom_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString') + mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_custom_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_custom_model -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_custom_model(**req_copy) + + + class TestDeleteCustomModel(): + """ + Test Class for delete_custom_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_custom_model_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_custom_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_custom_model_all_params(self): + """ + delete_custom_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.delete_custom_model( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_custom_model_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 = '/v1/customizations/{0}'.format(body['customization_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_custom_model_value_error(self): + """ + test_delete_custom_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_custom_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body + url, + status=204) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_custom_model(**req_copy) + # endregion @@ -693,359 +825,378 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for add_words -#----------------------------------------------------------------------------- class TestAddWords(): + """ + Test Class for add_words + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_add_words_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_words_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_add_words_all_params(self): + """ + add_words() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + responses.add(responses.POST, + url, + status=200) + + # Construct a dict representation of a Word model + word_model = {} + word_model['word'] = 'testString' + word_model['translation'] = 'testString' + word_model['part_of_speech'] = 'Dosi' + + # Set up parameter values + customization_id = 'testString' + words = [word_model] + + # Invoke method + response = service.add_words( + customization_id, + words, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['words'] == [word_model] + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_words_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 = '/v1/customizations/{0}/words'.format(body['customization_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_add_words_value_error(self): + """ + test_add_words_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words') responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.add_words(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body.update({"words": [], }) - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body.update({"words": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_words -#----------------------------------------------------------------------------- + url, + status=200) + + # Construct a dict representation of a Word model + word_model = {} + word_model['word'] = 'testString' + word_model['translation'] = 'testString' + word_model['part_of_speech'] = 'Dosi' + + # Set up parameter values + customization_id = 'testString' + words = [word_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "words": words, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_words(**req_copy) + + + class TestListWords(): + """ + Test Class for list_words + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_words_response(self): - body = self.construct_full_body() - response = fake_response_Words_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_words_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Words_json - send_request(self, body, response) + def test_list_words_all_params(self): + """ + list_words() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + mock_response = '{"words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = service.list_words( + customization_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_words_empty(self): - check_empty_required_params(self, fake_response_Words_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/words'.format(body['customization_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_list_words_value_error(self): + """ + test_list_words_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + mock_response = '{"words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.list_words(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for add_word -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_words(**req_copy) + + + class TestAddWord(): + """ + Test Class for add_word + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_add_word_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_word_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_add_word_all_params(self): + """ + add_word() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + responses.add(responses.PUT, + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + word = 'testString' + translation = 'testString' + part_of_speech = 'Dosi' + + # Invoke method + response = service.add_word( + customization_id, + word, + translation, + part_of_speech=part_of_speech, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['translation'] == 'testString' + assert req_body['part_of_speech'] == 'Dosi' + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_word_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 = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_add_word_value_error(self): + """ + test_add_word_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') responses.add(responses.PUT, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.add_word(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['word'] = "string1" - body.update({"translation": "string1", "part_of_speech": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['word'] = "string1" - body.update({"translation": "string1", "part_of_speech": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_word -#----------------------------------------------------------------------------- + url, + status=200) + + # Set up parameter values + customization_id = 'testString' + word = 'testString' + translation = 'testString' + part_of_speech = 'Dosi' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "word": word, + "translation": translation, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_word(**req_copy) + + + class TestGetWord(): + """ + Test Class for get_word + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_word_response(self): - body = self.construct_full_body() - response = fake_response_Translation_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_word_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Translation_json - send_request(self, body, response) + def test_get_word_all_params(self): + """ + get_word() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + mock_response = '{"translation": "translation", "part_of_speech": "Dosi"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + word = 'testString' + + # Invoke method + response = service.get_word( + customization_id, + word, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_word_empty(self): - check_empty_required_params(self, fake_response_Translation_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_word_value_error(self): + """ + test_get_word_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + mock_response = '{"translation": "translation", "part_of_speech": "Dosi"}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.get_word(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['word'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['word'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_word -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + word = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "word": word, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_word(**req_copy) + + + class TestDeleteWord(): + """ + Test Class for delete_word + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_word_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_word_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_word_all_params(self): + """ + delete_word() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + customization_id = 'testString' + word = 'testString' + + # Invoke method + response = service.delete_word( + customization_id, + word, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 204 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_word_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 = '/v1/customizations/{0}/words/{1}'.format(body['customization_id'], body['word']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_word_value_error(self): + """ + test_delete_word_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=204, - content_type='') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_word(**body) - return output - - def construct_full_body(self): - body = dict() - body['customization_id'] = "string1" - body['word'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customization_id'] = "string1" - body['word'] = "string1" - return body + url, + status=204) + + # Set up parameter values + customization_id = 'testString' + word = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "word": word, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_word(**req_copy) + # endregion @@ -1058,73 +1209,72 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for delete_user_data -#----------------------------------------------------------------------------- class TestDeleteUserData(): + """ + Test Class for delete_user_data + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_user_data_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_user_data_all_params(self): + """ + delete_user_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/user_data') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + customer_id = 'testString' + + # Invoke method + response = service.delete_user_data( + customer_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'customer_id={}'.format(customer_id) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_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 = '/v1/user_data' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_user_data_value_error(self): + """ + test_delete_user_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/user_data') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = TextToSpeechV1( - authenticator=NoAuthAuthenticator(), - ) - service.set_service_url(base_url) - output = service.delete_user_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['customer_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customer_id'] = "string1" - return body + url, + status=200) + + # Set up parameter values + customer_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customer_id": customer_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_user_data(**req_copy) + # endregion @@ -1133,76 +1283,374 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestCustomModel(): + """ + Test Class for CustomModel + """ + + def test_custom_model_serialization(self): + """ + Test serialization/deserialization for CustomModel + """ + + # Construct dict forms of any model objects needed in order to build this model. + + word_model = {} # Word + word_model['word'] = 'testString' + word_model['translation'] = 'testString' + word_model['part_of_speech'] = 'Dosi' + + # Construct a json representation of a CustomModel model + custom_model_model_json = {} + custom_model_model_json['customization_id'] = 'testString' + custom_model_model_json['name'] = 'testString' + custom_model_model_json['language'] = 'testString' + custom_model_model_json['owner'] = 'testString' + custom_model_model_json['created'] = 'testString' + custom_model_model_json['last_modified'] = 'testString' + custom_model_model_json['description'] = 'testString' + custom_model_model_json['words'] = [word_model] + + # Construct a model instance of CustomModel by calling from_dict on the json representation + custom_model_model = CustomModel.from_dict(custom_model_model_json) + assert custom_model_model != False + + # Construct a model instance of CustomModel by calling from_dict on the json representation + custom_model_model_dict = CustomModel.from_dict(custom_model_model_json).__dict__ + custom_model_model2 = CustomModel(**custom_model_model_dict) + + # Verify the model instances are equivalent + assert custom_model_model == custom_model_model2 + + # Convert model instance back to dict and verify no loss of data + custom_model_model_json2 = custom_model_model.to_dict() + assert custom_model_model_json2 == custom_model_model_json + +class TestCustomModels(): + """ + Test Class for CustomModels + """ + + def test_custom_models_serialization(self): + """ + Test serialization/deserialization for CustomModels + """ + + # Construct dict forms of any model objects needed in order to build this model. + + word_model = {} # Word + word_model['word'] = 'testString' + word_model['translation'] = 'testString' + word_model['part_of_speech'] = 'Dosi' + + custom_model_model = {} # CustomModel + custom_model_model['customization_id'] = 'testString' + custom_model_model['name'] = 'testString' + custom_model_model['language'] = 'testString' + custom_model_model['owner'] = 'testString' + custom_model_model['created'] = 'testString' + custom_model_model['last_modified'] = 'testString' + custom_model_model['description'] = 'testString' + custom_model_model['words'] = [word_model] + + # Construct a json representation of a CustomModels model + custom_models_model_json = {} + custom_models_model_json['customizations'] = [custom_model_model] + + # Construct a model instance of CustomModels by calling from_dict on the json representation + custom_models_model = CustomModels.from_dict(custom_models_model_json) + assert custom_models_model != False + + # Construct a model instance of CustomModels by calling from_dict on the json representation + custom_models_model_dict = CustomModels.from_dict(custom_models_model_json).__dict__ + custom_models_model2 = CustomModels(**custom_models_model_dict) - Args: - obj: The generated test function + # Verify the model instances are equivalent + assert custom_models_model == custom_models_model2 + # Convert model instance back to dict and verify no loss of data + custom_models_model_json2 = custom_models_model.to_dict() + assert custom_models_model_json2 == custom_models_model_json + +class TestPronunciation(): + """ + Test Class for Pronunciation """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data + def test_pronunciation_serialization(self): + """ + Test serialization/deserialization for Pronunciation + """ + + # Construct a json representation of a Pronunciation model + pronunciation_model_json = {} + pronunciation_model_json['pronunciation'] = 'testString' + + # Construct a model instance of Pronunciation by calling from_dict on the json representation + pronunciation_model = Pronunciation.from_dict(pronunciation_model_json) + assert pronunciation_model != False - Args: - obj: The generated test function + # Construct a model instance of Pronunciation by calling from_dict on the json representation + pronunciation_model_dict = Pronunciation.from_dict(pronunciation_model_json).__dict__ + pronunciation_model2 = Pronunciation(**pronunciation_model_dict) + # Verify the model instances are equivalent + assert pronunciation_model == pronunciation_model2 + + # Convert model instance back to dict and verify no loss of data + pronunciation_model_json2 = pronunciation_model.to_dict() + assert pronunciation_model_json2 == pronunciation_model_json + +class TestSupportedFeatures(): """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error + Test Class for SupportedFeatures + """ + + def test_supported_features_serialization(self): + """ + Test serialization/deserialization for SupportedFeatures + """ -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request + # Construct a json representation of a SupportedFeatures model + supported_features_model_json = {} + supported_features_model_json['custom_pronunciation'] = True + supported_features_model_json['voice_transformation'] = True - Args: - obj: The generated test function + # Construct a model instance of SupportedFeatures by calling from_dict on the json representation + supported_features_model = SupportedFeatures.from_dict(supported_features_model_json) + assert supported_features_model != False + # Construct a model instance of SupportedFeatures by calling from_dict on the json representation + supported_features_model_dict = SupportedFeatures.from_dict(supported_features_model_json).__dict__ + supported_features_model2 = SupportedFeatures(**supported_features_model_dict) + + # Verify the model instances are equivalent + assert supported_features_model == supported_features_model2 + + # Convert model instance back to dict and verify no loss of data + supported_features_model_json2 = supported_features_model.to_dict() + assert supported_features_model_json2 == supported_features_model_json + +class TestTranslation(): + """ + Test Class for Translation """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response + def test_translation_serialization(self): + """ + Test serialization/deserialization for Translation + """ + + # Construct a json representation of a Translation model + translation_model_json = {} + translation_model_json['translation'] = 'testString' + translation_model_json['part_of_speech'] = 'Dosi' + + # Construct a model instance of Translation by calling from_dict on the json representation + translation_model = Translation.from_dict(translation_model_json) + assert translation_model != False + + # Construct a model instance of Translation by calling from_dict on the json representation + translation_model_dict = Translation.from_dict(translation_model_json).__dict__ + translation_model2 = Translation(**translation_model_dict) - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string + # Verify the model instances are equivalent + assert translation_model == translation_model2 + # Convert model instance back to dict and verify no loss of data + translation_model_json2 = translation_model.to_dict() + assert translation_model_json2 == translation_model_json + +class TestVoice(): + """ + Test Class for Voice + """ + + def test_voice_serialization(self): + """ + Test serialization/deserialization for Voice + """ + + # Construct dict forms of any model objects needed in order to build this model. + + supported_features_model = {} # SupportedFeatures + supported_features_model['custom_pronunciation'] = True + supported_features_model['voice_transformation'] = True + + word_model = {} # Word + word_model['word'] = 'testString' + word_model['translation'] = 'testString' + word_model['part_of_speech'] = 'Dosi' + + custom_model_model = {} # CustomModel + custom_model_model['customization_id'] = 'testString' + custom_model_model['name'] = 'testString' + custom_model_model['language'] = 'testString' + custom_model_model['owner'] = 'testString' + custom_model_model['created'] = 'testString' + custom_model_model['last_modified'] = 'testString' + custom_model_model['description'] = 'testString' + custom_model_model['words'] = [word_model] + + # Construct a json representation of a Voice model + voice_model_json = {} + voice_model_json['url'] = 'testString' + voice_model_json['gender'] = 'testString' + voice_model_json['name'] = 'testString' + voice_model_json['language'] = 'testString' + voice_model_json['description'] = 'testString' + voice_model_json['customizable'] = True + voice_model_json['supported_features'] = supported_features_model + voice_model_json['customization'] = custom_model_model + + # Construct a model instance of Voice by calling from_dict on the json representation + voice_model = Voice.from_dict(voice_model_json) + assert voice_model != False + + # Construct a model instance of Voice by calling from_dict on the json representation + voice_model_dict = Voice.from_dict(voice_model_json).__dict__ + voice_model2 = Voice(**voice_model_dict) + + # Verify the model instances are equivalent + assert voice_model == voice_model2 + + # Convert model instance back to dict and verify no loss of data + voice_model_json2 = voice_model.to_dict() + assert voice_model_json2 == voice_model_json + +class TestVoices(): + """ + Test Class for Voices + """ + + def test_voices_serialization(self): + """ + Test serialization/deserialization for Voices + """ + + # Construct dict forms of any model objects needed in order to build this model. + + supported_features_model = {} # SupportedFeatures + supported_features_model['custom_pronunciation'] = True + supported_features_model['voice_transformation'] = True + + word_model = {} # Word + word_model['word'] = 'testString' + word_model['translation'] = 'testString' + word_model['part_of_speech'] = 'Dosi' + + custom_model_model = {} # CustomModel + custom_model_model['customization_id'] = 'testString' + custom_model_model['name'] = 'testString' + custom_model_model['language'] = 'testString' + custom_model_model['owner'] = 'testString' + custom_model_model['created'] = 'testString' + custom_model_model['last_modified'] = 'testString' + custom_model_model['description'] = 'testString' + custom_model_model['words'] = [word_model] + + voice_model = {} # Voice + voice_model['url'] = 'testString' + voice_model['gender'] = 'testString' + voice_model['name'] = 'testString' + voice_model['language'] = 'testString' + voice_model['description'] = 'testString' + voice_model['customizable'] = True + voice_model['supported_features'] = supported_features_model + voice_model['customization'] = custom_model_model + + # Construct a json representation of a Voices model + voices_model_json = {} + voices_model_json['voices'] = [voice_model] + + # Construct a model instance of Voices by calling from_dict on the json representation + voices_model = Voices.from_dict(voices_model_json) + assert voices_model != False + + # Construct a model instance of Voices by calling from_dict on the json representation + voices_model_dict = Voices.from_dict(voices_model_json).__dict__ + voices_model2 = Voices(**voices_model_dict) + + # Verify the model instances are equivalent + assert voices_model == voices_model2 + + # Convert model instance back to dict and verify no loss of data + voices_model_json2 = voices_model.to_dict() + assert voices_model_json2 == voices_model_json + +class TestWord(): + """ + Test Class for Word + """ + + def test_word_serialization(self): + """ + Test serialization/deserialization for Word + """ + + # Construct a json representation of a Word model + word_model_json = {} + word_model_json['word'] = 'testString' + word_model_json['translation'] = 'testString' + word_model_json['part_of_speech'] = 'Dosi' + + # Construct a model instance of Word by calling from_dict on the json representation + word_model = Word.from_dict(word_model_json) + assert word_model != False + + # Construct a model instance of Word by calling from_dict on the json representation + word_model_dict = Word.from_dict(word_model_json).__dict__ + word_model2 = Word(**word_model_dict) + + # Verify the model instances are equivalent + assert word_model == word_model2 + + # Convert model instance back to dict and verify no loss of data + word_model_json2 = word_model.to_dict() + assert word_model_json2 == word_model_json + +class TestWords(): + """ + Test Class for Words """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response - -#################### -## Mock Responses ## -#################### - -fake_response__json = None -fake_response_Voices_json = """{"voices": []}""" -fake_response_Voice_json = """{"url": "fake_url", "gender": "fake_gender", "name": "fake_name", "language": "fake_language", "description": "fake_description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}}""" -fake_response_BinaryIO_json = """Contents of response byte-stream...""" -fake_response_Pronunciation_json = """{"pronunciation": "fake_pronunciation"}""" -fake_response_CustomModel_json = """{"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}""" -fake_response_CustomModels_json = """{"customizations": []}""" -fake_response_CustomModel_json = """{"customization_id": "fake_customization_id", "name": "fake_name", "language": "fake_language", "owner": "fake_owner", "created": "fake_created", "last_modified": "fake_last_modified", "description": "fake_description", "words": []}""" -fake_response_Words_json = """{"words": []}""" -fake_response_Translation_json = """{"translation": "fake_translation", "part_of_speech": "fake_part_of_speech"}""" + + def test_words_serialization(self): + """ + Test serialization/deserialization for Words + """ + + # Construct dict forms of any model objects needed in order to build this model. + + word_model = {} # Word + word_model['word'] = 'testString' + word_model['translation'] = 'testString' + word_model['part_of_speech'] = 'Dosi' + + # Construct a json representation of a Words model + words_model_json = {} + words_model_json['words'] = [word_model] + + # Construct a model instance of Words by calling from_dict on the json representation + words_model = Words.from_dict(words_model_json) + assert words_model != False + + # Construct a model instance of Words by calling from_dict on the json representation + words_model_dict = Words.from_dict(words_model_json).__dict__ + words_model2 = Words(**words_model_dict) + + # Verify the model instances are equivalent + assert words_model == words_model2 + + # Convert model instance back to dict and verify no loss of data + words_model_json2 = words_model.to_dict() + assert words_model_json2 == words_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index 12ca4aaa8..6f5f5843b 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -13,166 +13,283 @@ # See the License for the specific language governing permissions and # limitations under the License. +""" +Unit Tests for ToneAnalyzerV3 +""" + from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect import json import pytest +import re +import requests import responses -import ibm_watson.tone_analyzer_v3 +import urllib from ibm_watson.tone_analyzer_v3 import * +version = 'testString' + +service = ToneAnalyzerV3( + authenticator=NoAuthAuthenticator(), + version=version + ) + base_url = 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: Methods ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for tone -#----------------------------------------------------------------------------- class TestTone(): + """ + Test Class for tone + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_tone_response(self): - body = self.construct_full_body() - response = fake_response_ToneAnalysis_json - send_request(self, body, response) + def test_tone_all_params(self): + """ + tone() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/tone') + mock_response = '{"document_tone": {"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "warning": "warning"}, "sentences_tone": [{"sentence_id": 11, "text": "text", "tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "input_from": 10, "input_to": 8}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ToneInput model + tone_input_model = {} + tone_input_model['text'] = 'testString' + + # Set up parameter values + tone_input = tone_input_model + content_type = 'application/json' + sentences = True + tones = ['emotion'] + content_language = 'en' + accept_language = 'ar' + + # Invoke method + response = service.tone( + tone_input, + content_type=content_type, + sentences=sentences, + tones=tones, + content_language=content_language, + accept_language=accept_language, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'sentences={}'.format('true' if sentences else 'false') in query_string + assert 'tones={}'.format(','.join(tones)) in query_string + # Validate body params + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_tone_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ToneAnalysis_json - send_request(self, body, response) + def test_tone_required_params(self): + """ + test_tone_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/tone') + mock_response = '{"document_tone": {"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "warning": "warning"}, "sentences_tone": [{"sentence_id": 11, "text": "text", "tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "input_from": 10, "input_to": 8}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ToneInput model + tone_input_model = {} + tone_input_model['text'] = 'testString' + + # Set up parameter values + tone_input = tone_input_model + + # Invoke method + response = service.tone( + tone_input, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_tone_empty(self): - check_empty_required_params(self, fake_response_ToneAnalysis_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/tone' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_tone_value_error(self): + """ + test_tone_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/tone') + mock_response = '{"document_tone": {"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "warning": "warning"}, "sentences_tone": [{"sentence_id": 11, "text": "text", "tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "input_from": 10, "input_to": 8}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = ToneAnalyzerV3( - authenticator=NoAuthAuthenticator(), - version='2017-09-21', - ) - service.set_service_url(base_url) - output = service.tone(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"tone_input": {"mock": "data"}}) - body['content_type'] = "string1" - body['sentences'] = True - body['tones'] = [] - body['content_language'] = "string1" - body['accept_language'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body.update({"tone_input": {"mock": "data"}}) - return body - - -#----------------------------------------------------------------------------- -# Test Class for tone_chat -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ToneInput model + tone_input_model = {} + tone_input_model['text'] = 'testString' + + # Set up parameter values + tone_input = tone_input_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "tone_input": tone_input, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.tone(**req_copy) + + + class TestToneChat(): + """ + Test Class for tone_chat + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_tone_chat_response(self): - body = self.construct_full_body() - response = fake_response_UtteranceAnalyses_json - send_request(self, body, response) + def test_tone_chat_all_params(self): + """ + tone_chat() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/tone_chat') + mock_response = '{"utterances_tone": [{"utterance_id": 12, "utterance_text": "utterance_text", "tones": [{"score": 5, "tone_id": "excited", "tone_name": "tone_name"}], "error": "error"}], "warning": "warning"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Utterance model + utterance_model = {} + utterance_model['text'] = 'testString' + utterance_model['user'] = 'testString' + + # Set up parameter values + utterances = [utterance_model] + content_language = 'en' + accept_language = 'ar' + + # Invoke method + response = service.tone_chat( + utterances, + content_language=content_language, + accept_language=accept_language, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['utterances'] == [utterance_model] + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_tone_chat_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_UtteranceAnalyses_json - send_request(self, body, response) + def test_tone_chat_required_params(self): + """ + test_tone_chat_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/tone_chat') + mock_response = '{"utterances_tone": [{"utterance_id": 12, "utterance_text": "utterance_text", "tones": [{"score": 5, "tone_id": "excited", "tone_name": "tone_name"}], "error": "error"}], "warning": "warning"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Utterance model + utterance_model = {} + utterance_model['text'] = 'testString' + utterance_model['user'] = 'testString' + + # Set up parameter values + utterances = [utterance_model] + + # Invoke method + response = service.tone_chat( + utterances, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['utterances'] == [utterance_model] + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_tone_chat_empty(self): - check_empty_required_params(self, fake_response_UtteranceAnalyses_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/tone_chat' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_tone_chat_value_error(self): + """ + test_tone_chat_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/tone_chat') + mock_response = '{"utterances_tone": [{"utterance_id": 12, "utterance_text": "utterance_text", "tones": [{"score": 5, "tone_id": "excited", "tone_name": "tone_name"}], "error": "error"}], "warning": "warning"}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = ToneAnalyzerV3( - authenticator=NoAuthAuthenticator(), - version='2017-09-21', - ) - service.set_service_url(base_url) - output = service.tone_chat(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"utterances": [], }) - body['content_language'] = "string1" - body['accept_language'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body.update({"utterances": [], }) - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Utterance model + utterance_model = {} + utterance_model['text'] = 'testString' + utterance_model['user'] = 'testString' + + # Set up parameter values + utterances = [utterance_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "utterances": utterances, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.tone_chat(**req_copy) + # endregion @@ -181,69 +298,397 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestDocumentAnalysis(): + """ + Test Class for DocumentAnalysis + """ + + def test_document_analysis_serialization(self): + """ + Test serialization/deserialization for DocumentAnalysis + """ + + # Construct dict forms of any model objects needed in order to build this model. + + tone_score_model = {} # ToneScore + tone_score_model['score'] = 72.5 + tone_score_model['tone_id'] = 'testString' + tone_score_model['tone_name'] = 'testString' + + tone_category_model = {} # ToneCategory + tone_category_model['tones'] = [tone_score_model] + tone_category_model['category_id'] = 'testString' + tone_category_model['category_name'] = 'testString' + + # Construct a json representation of a DocumentAnalysis model + document_analysis_model_json = {} + document_analysis_model_json['tones'] = [tone_score_model] + document_analysis_model_json['tone_categories'] = [tone_category_model] + document_analysis_model_json['warning'] = 'testString' + + # Construct a model instance of DocumentAnalysis by calling from_dict on the json representation + document_analysis_model = DocumentAnalysis.from_dict(document_analysis_model_json) + assert document_analysis_model != False + + # Construct a model instance of DocumentAnalysis by calling from_dict on the json representation + document_analysis_model_dict = DocumentAnalysis.from_dict(document_analysis_model_json).__dict__ + document_analysis_model2 = DocumentAnalysis(**document_analysis_model_dict) + + # Verify the model instances are equivalent + assert document_analysis_model == document_analysis_model2 + + # Convert model instance back to dict and verify no loss of data + document_analysis_model_json2 = document_analysis_model.to_dict() + assert document_analysis_model_json2 == document_analysis_model_json + +class TestSentenceAnalysis(): + """ + Test Class for SentenceAnalysis + """ + + def test_sentence_analysis_serialization(self): + """ + Test serialization/deserialization for SentenceAnalysis + """ + + # Construct dict forms of any model objects needed in order to build this model. + + tone_score_model = {} # ToneScore + tone_score_model['score'] = 72.5 + tone_score_model['tone_id'] = 'testString' + tone_score_model['tone_name'] = 'testString' + + tone_category_model = {} # ToneCategory + tone_category_model['tones'] = [tone_score_model] + tone_category_model['category_id'] = 'testString' + tone_category_model['category_name'] = 'testString' + + # Construct a json representation of a SentenceAnalysis model + sentence_analysis_model_json = {} + sentence_analysis_model_json['sentence_id'] = 38 + sentence_analysis_model_json['text'] = 'testString' + sentence_analysis_model_json['tones'] = [tone_score_model] + sentence_analysis_model_json['tone_categories'] = [tone_category_model] + sentence_analysis_model_json['input_from'] = 38 + sentence_analysis_model_json['input_to'] = 38 + + # Construct a model instance of SentenceAnalysis by calling from_dict on the json representation + sentence_analysis_model = SentenceAnalysis.from_dict(sentence_analysis_model_json) + assert sentence_analysis_model != False + + # Construct a model instance of SentenceAnalysis by calling from_dict on the json representation + sentence_analysis_model_dict = SentenceAnalysis.from_dict(sentence_analysis_model_json).__dict__ + sentence_analysis_model2 = SentenceAnalysis(**sentence_analysis_model_dict) + + # Verify the model instances are equivalent + assert sentence_analysis_model == sentence_analysis_model2 + + # Convert model instance back to dict and verify no loss of data + sentence_analysis_model_json2 = sentence_analysis_model.to_dict() + assert sentence_analysis_model_json2 == sentence_analysis_model_json + +class TestToneAnalysis(): + """ + Test Class for ToneAnalysis + """ + + def test_tone_analysis_serialization(self): + """ + Test serialization/deserialization for ToneAnalysis + """ + + # Construct dict forms of any model objects needed in order to build this model. + + tone_score_model = {} # ToneScore + tone_score_model['score'] = 72.5 + tone_score_model['tone_id'] = 'testString' + tone_score_model['tone_name'] = 'testString' + + tone_category_model = {} # ToneCategory + tone_category_model['tones'] = [tone_score_model] + tone_category_model['category_id'] = 'testString' + tone_category_model['category_name'] = 'testString' + + document_analysis_model = {} # DocumentAnalysis + document_analysis_model['tones'] = [tone_score_model] + document_analysis_model['tone_categories'] = [tone_category_model] + document_analysis_model['warning'] = 'testString' + + sentence_analysis_model = {} # SentenceAnalysis + sentence_analysis_model['sentence_id'] = 38 + sentence_analysis_model['text'] = 'testString' + sentence_analysis_model['tones'] = [tone_score_model] + sentence_analysis_model['tone_categories'] = [tone_category_model] + sentence_analysis_model['input_from'] = 38 + sentence_analysis_model['input_to'] = 38 + + # Construct a json representation of a ToneAnalysis model + tone_analysis_model_json = {} + tone_analysis_model_json['document_tone'] = document_analysis_model + tone_analysis_model_json['sentences_tone'] = [sentence_analysis_model] + + # Construct a model instance of ToneAnalysis by calling from_dict on the json representation + tone_analysis_model = ToneAnalysis.from_dict(tone_analysis_model_json) + assert tone_analysis_model != False + + # Construct a model instance of ToneAnalysis by calling from_dict on the json representation + tone_analysis_model_dict = ToneAnalysis.from_dict(tone_analysis_model_json).__dict__ + tone_analysis_model2 = ToneAnalysis(**tone_analysis_model_dict) + + # Verify the model instances are equivalent + assert tone_analysis_model == tone_analysis_model2 + + # Convert model instance back to dict and verify no loss of data + tone_analysis_model_json2 = tone_analysis_model.to_dict() + assert tone_analysis_model_json2 == tone_analysis_model_json + +class TestToneCategory(): + """ + Test Class for ToneCategory + """ + + def test_tone_category_serialization(self): + """ + Test serialization/deserialization for ToneCategory + """ + + # Construct dict forms of any model objects needed in order to build this model. + + tone_score_model = {} # ToneScore + tone_score_model['score'] = 72.5 + tone_score_model['tone_id'] = 'testString' + tone_score_model['tone_name'] = 'testString' + + # Construct a json representation of a ToneCategory model + tone_category_model_json = {} + tone_category_model_json['tones'] = [tone_score_model] + tone_category_model_json['category_id'] = 'testString' + tone_category_model_json['category_name'] = 'testString' - Args: - obj: The generated test function + # Construct a model instance of ToneCategory by calling from_dict on the json representation + tone_category_model = ToneCategory.from_dict(tone_category_model_json) + assert tone_category_model != False + # Construct a model instance of ToneCategory by calling from_dict on the json representation + tone_category_model_dict = ToneCategory.from_dict(tone_category_model_json).__dict__ + tone_category_model2 = ToneCategory(**tone_category_model_dict) + + # Verify the model instances are equivalent + assert tone_category_model == tone_category_model2 + + # Convert model instance back to dict and verify no loss of data + tone_category_model_json2 = tone_category_model.to_dict() + assert tone_category_model_json2 == tone_category_model_json + +class TestToneChatScore(): + """ + Test Class for ToneChatScore """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data + def test_tone_chat_score_serialization(self): + """ + Test serialization/deserialization for ToneChatScore + """ + + # Construct a json representation of a ToneChatScore model + tone_chat_score_model_json = {} + tone_chat_score_model_json['score'] = 72.5 + tone_chat_score_model_json['tone_id'] = 'excited' + tone_chat_score_model_json['tone_name'] = 'testString' + + # Construct a model instance of ToneChatScore by calling from_dict on the json representation + tone_chat_score_model = ToneChatScore.from_dict(tone_chat_score_model_json) + assert tone_chat_score_model != False + + # Construct a model instance of ToneChatScore by calling from_dict on the json representation + tone_chat_score_model_dict = ToneChatScore.from_dict(tone_chat_score_model_json).__dict__ + tone_chat_score_model2 = ToneChatScore(**tone_chat_score_model_dict) - Args: - obj: The generated test function + # Verify the model instances are equivalent + assert tone_chat_score_model == tone_chat_score_model2 + # Convert model instance back to dict and verify no loss of data + tone_chat_score_model_json2 = tone_chat_score_model.to_dict() + assert tone_chat_score_model_json2 == tone_chat_score_model_json + +class TestToneInput(): + """ + Test Class for ToneInput """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request + def test_tone_input_serialization(self): + """ + Test serialization/deserialization for ToneInput + """ + + # Construct a json representation of a ToneInput model + tone_input_model_json = {} + tone_input_model_json['text'] = 'testString' + + # Construct a model instance of ToneInput by calling from_dict on the json representation + tone_input_model = ToneInput.from_dict(tone_input_model_json) + assert tone_input_model != False - Args: - obj: The generated test function + # Construct a model instance of ToneInput by calling from_dict on the json representation + tone_input_model_dict = ToneInput.from_dict(tone_input_model_json).__dict__ + tone_input_model2 = ToneInput(**tone_input_model_dict) + # Verify the model instances are equivalent + assert tone_input_model == tone_input_model2 + + # Convert model instance back to dict and verify no loss of data + tone_input_model_json2 = tone_input_model.to_dict() + assert tone_input_model_json2 == tone_input_model_json + +class TestToneScore(): """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) + Test Class for ToneScore + """ + + def test_tone_score_serialization(self): + """ + Test serialization/deserialization for ToneScore + """ -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response + # Construct a json representation of a ToneScore model + tone_score_model_json = {} + tone_score_model_json['score'] = 72.5 + tone_score_model_json['tone_id'] = 'testString' + tone_score_model_json['tone_name'] = 'testString' - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string + # Construct a model instance of ToneScore by calling from_dict on the json representation + tone_score_model = ToneScore.from_dict(tone_score_model_json) + assert tone_score_model != False + # Construct a model instance of ToneScore by calling from_dict on the json representation + tone_score_model_dict = ToneScore.from_dict(tone_score_model_json).__dict__ + tone_score_model2 = ToneScore(**tone_score_model_dict) + + # Verify the model instances are equivalent + assert tone_score_model == tone_score_model2 + + # Convert model instance back to dict and verify no loss of data + tone_score_model_json2 = tone_score_model.to_dict() + assert tone_score_model_json2 == tone_score_model_json + +class TestUtterance(): + """ + Test Class for Utterance """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response -#################### -## Mock Responses ## -#################### + def test_utterance_serialization(self): + """ + Test serialization/deserialization for Utterance + """ + + # Construct a json representation of a Utterance model + utterance_model_json = {} + utterance_model_json['text'] = 'testString' + utterance_model_json['user'] = 'testString' + + # Construct a model instance of Utterance by calling from_dict on the json representation + utterance_model = Utterance.from_dict(utterance_model_json) + assert utterance_model != False + + # Construct a model instance of Utterance by calling from_dict on the json representation + utterance_model_dict = Utterance.from_dict(utterance_model_json).__dict__ + utterance_model2 = Utterance(**utterance_model_dict) -fake_response__json = None -fake_response_ToneAnalysis_json = """{"document_tone": {"tones": [], "tone_categories": [], "warning": "fake_warning"}, "sentences_tone": []}""" -fake_response_UtteranceAnalyses_json = """{"utterances_tone": [], "warning": "fake_warning"}""" + # Verify the model instances are equivalent + assert utterance_model == utterance_model2 + + # Convert model instance back to dict and verify no loss of data + utterance_model_json2 = utterance_model.to_dict() + assert utterance_model_json2 == utterance_model_json + +class TestUtteranceAnalyses(): + """ + Test Class for UtteranceAnalyses + """ + + def test_utterance_analyses_serialization(self): + """ + Test serialization/deserialization for UtteranceAnalyses + """ + + # Construct dict forms of any model objects needed in order to build this model. + + tone_chat_score_model = {} # ToneChatScore + tone_chat_score_model['score'] = 72.5 + tone_chat_score_model['tone_id'] = 'excited' + tone_chat_score_model['tone_name'] = 'testString' + + utterance_analysis_model = {} # UtteranceAnalysis + utterance_analysis_model['utterance_id'] = 38 + utterance_analysis_model['utterance_text'] = 'testString' + utterance_analysis_model['tones'] = [tone_chat_score_model] + utterance_analysis_model['error'] = 'testString' + + # Construct a json representation of a UtteranceAnalyses model + utterance_analyses_model_json = {} + utterance_analyses_model_json['utterances_tone'] = [utterance_analysis_model] + utterance_analyses_model_json['warning'] = 'testString' + + # Construct a model instance of UtteranceAnalyses by calling from_dict on the json representation + utterance_analyses_model = UtteranceAnalyses.from_dict(utterance_analyses_model_json) + assert utterance_analyses_model != False + + # Construct a model instance of UtteranceAnalyses by calling from_dict on the json representation + utterance_analyses_model_dict = UtteranceAnalyses.from_dict(utterance_analyses_model_json).__dict__ + utterance_analyses_model2 = UtteranceAnalyses(**utterance_analyses_model_dict) + + # Verify the model instances are equivalent + assert utterance_analyses_model == utterance_analyses_model2 + + # Convert model instance back to dict and verify no loss of data + utterance_analyses_model_json2 = utterance_analyses_model.to_dict() + assert utterance_analyses_model_json2 == utterance_analyses_model_json + +class TestUtteranceAnalysis(): + """ + Test Class for UtteranceAnalysis + """ + + def test_utterance_analysis_serialization(self): + """ + Test serialization/deserialization for UtteranceAnalysis + """ + + # Construct dict forms of any model objects needed in order to build this model. + + tone_chat_score_model = {} # ToneChatScore + tone_chat_score_model['score'] = 72.5 + tone_chat_score_model['tone_id'] = 'excited' + tone_chat_score_model['tone_name'] = 'testString' + + # Construct a json representation of a UtteranceAnalysis model + utterance_analysis_model_json = {} + utterance_analysis_model_json['utterance_id'] = 38 + utterance_analysis_model_json['utterance_text'] = 'testString' + utterance_analysis_model_json['tones'] = [tone_chat_score_model] + utterance_analysis_model_json['error'] = 'testString' + + # Construct a model instance of UtteranceAnalysis by calling from_dict on the json representation + utterance_analysis_model = UtteranceAnalysis.from_dict(utterance_analysis_model_json) + assert utterance_analysis_model != False + + # Construct a model instance of UtteranceAnalysis by calling from_dict on the json representation + utterance_analysis_model_dict = UtteranceAnalysis.from_dict(utterance_analysis_model_json).__dict__ + utterance_analysis_model2 = UtteranceAnalysis(**utterance_analysis_model_dict) + + # Verify the model instances are equivalent + assert utterance_analysis_model == utterance_analysis_model2 + + # Convert model instance back to dict and verify no loss of data + utterance_analysis_model_json2 = utterance_analysis_model.to_dict() + assert utterance_analysis_model_json2 == utterance_analysis_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index 1608ba69a..5ebc9de48 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -13,96 +13,139 @@ # See the License for the specific language governing permissions and # limitations under the License. -from datetime import datetime +""" +Unit Tests for VisualRecognitionV3 +""" + +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect +import io import json import pytest +import re +import requests import responses import tempfile -import ibm_watson.visual_recognition_v3 +import urllib from ibm_watson.visual_recognition_v3 import * +version = 'testString' + +service = VisualRecognitionV3( + authenticator=NoAuthAuthenticator(), + version=version + ) + base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: General ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for classify -#----------------------------------------------------------------------------- class TestClassify(): + """ + Test Class for classify + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_classify_response(self): - body = self.construct_full_body() - response = fake_response_ClassifiedImages_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_classify_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ClassifiedImages_json - send_request(self, body, response) + def test_classify_all_params(self): + """ + classify() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classify') + mock_response = '{"custom_classes": 14, "images_processed": 16, "images": [{"source_url": "source_url", "resolved_url": "resolved_url", "image": "image", "error": {"code": 4, "description": "description", "error_id": "error_id"}, "classifiers": [{"name": "name", "classifier_id": "classifier_id", "classes": [{"class": "class_", "score": 0, "type_hierarchy": "type_hierarchy"}]}]}], "warnings": [{"warning_id": "warning_id", "description": "description"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + images_file = io.BytesIO(b'This is a mock file.').getvalue() + images_filename = 'testString' + images_file_content_type = 'testString' + url = 'testString' + threshold = 72.5 + owners = ['testString'] + classifier_ids = ['testString'] + accept_language = 'en' + + # Invoke method + response = service.classify( + images_file=images_file, + images_filename=images_filename, + images_file_content_type=images_file_content_type, + url=url, + threshold=threshold, + owners=owners, + classifier_ids=classifier_ids, + accept_language=accept_language, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_classify_empty(self): - check_empty_response(self) + def test_classify_required_params(self): + """ + test_classify_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classify') + mock_response = '{"custom_classes": 14, "images_processed": 16, "images": [{"source_url": "source_url", "resolved_url": "resolved_url", "image": "image", "error": {"code": 4, "description": "description", "error_id": "error_id"}, "classifiers": [{"name": "name", "classifier_id": "classifier_id", "classes": [{"class": "class_", "score": 0, "type_hierarchy": "type_hierarchy"}]}]}], "warnings": [{"warning_id": "warning_id", "description": "description"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = service.classify() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/classify' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_classify_value_error(self): + """ + test_classify_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classify') + mock_response = '{"custom_classes": 14, "images_processed": 16, "images": [{"source_url": "source_url", "resolved_url": "resolved_url", "image": "image", "error": {"code": 4, "description": "description", "error_id": "error_id"}, "classifiers": [{"name": "name", "classifier_id": "classifier_id", "classes": [{"class": "class_", "score": 0, "type_hierarchy": "type_hierarchy"}]}]}], "warnings": [{"warning_id": "warning_id", "description": "description"}]}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = VisualRecognitionV3( - authenticator=NoAuthAuthenticator(), - version='2018-03-19', - ) - service.set_service_url(base_url) - output = service.classify(**body) - return output - - def construct_full_body(self): - body = dict() - body['images_file'] = tempfile.NamedTemporaryFile() - body['images_filename'] = "string1" - body['images_file_content_type'] = "string1" - body['url'] = "string1" - body['threshold'] = 12345.0 - body['owners'] = [] - body['classifier_ids'] = [] - body['accept_language'] = "string1" - return body - - def construct_required_body(self): - body = dict() - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.classify(**req_copy) + # endregion @@ -115,359 +158,443 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_classifier -#----------------------------------------------------------------------------- class TestCreateClassifier(): + """ + Test Class for create_classifier + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_classifier_response(self): - body = self.construct_full_body() - response = fake_response_Classifier_json - send_request(self, body, response) + def test_create_classifier_all_params(self): + """ + create_classifier() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + name = 'testString' + positive_examples = { 'key': io.BytesIO(b'This is a mock file.').getvalue() } + negative_examples = io.BytesIO(b'This is a mock file.').getvalue() + negative_examples_filename = 'testString' + + # Invoke method + response = service.create_classifier( + name, + positive_examples, + negative_examples=negative_examples, + negative_examples_filename=negative_examples_filename, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_classifier_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Classifier_json - send_request(self, body, response) + def test_create_classifier_required_params(self): + """ + test_create_classifier_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + name = 'testString' + positive_examples = { 'key': io.BytesIO(b'This is a mock file.').getvalue() } + + # Invoke method + response = service.create_classifier( + name, + positive_examples, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_classifier_empty(self): - check_empty_required_params(self, fake_response_Classifier_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/classifiers' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_create_classifier_value_error(self): + """ + test_create_classifier_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = VisualRecognitionV3( - authenticator=NoAuthAuthenticator(), - version='2018-03-19', - ) - service.set_service_url(base_url) - output = service.create_classifier(**body) - return output - - def construct_full_body(self): - body = dict() - body['name'] = "string1" - body['positive_examples'] = {"mock": "data"} - body['negative_examples'] = tempfile.NamedTemporaryFile() - body['negative_examples_filename'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['name'] = "string1" - body['positive_examples'] = {"mock": "data"} - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_classifiers -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + name = 'testString' + positive_examples = { 'key': io.BytesIO(b'This is a mock file.').getvalue() } + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "name": name, + "positive_examples": positive_examples, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_classifier(**req_copy) + + + class TestListClassifiers(): + """ + Test Class for list_classifiers + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_classifiers_response(self): - body = self.construct_full_body() - response = fake_response_Classifiers_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_classifiers_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Classifiers_json - send_request(self, body, response) + def test_list_classifiers_all_params(self): + """ + list_classifiers() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers') + mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + verbose = True + + # Invoke method + response = service.list_classifiers( + verbose=verbose, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'verbose={}'.format('true' if verbose else 'false') in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_classifiers_empty(self): - check_empty_response(self) + def test_list_classifiers_required_params(self): + """ + test_list_classifiers_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers') + mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = service.list_classifiers() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/classifiers' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_classifiers_value_error(self): + """ + test_list_classifiers_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers') + mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = VisualRecognitionV3( - authenticator=NoAuthAuthenticator(), - version='2018-03-19', - ) - service.set_service_url(base_url) - output = service.list_classifiers(**body) - return output - - def construct_full_body(self): - body = dict() - body['verbose'] = True - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_classifier -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_classifiers(**req_copy) + + + class TestGetClassifier(): + """ + Test Class for get_classifier + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_classifier_response(self): - body = self.construct_full_body() - response = fake_response_Classifier_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_classifier_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Classifier_json - send_request(self, body, response) + def test_get_classifier_all_params(self): + """ + get_classifier() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Invoke method + response = service.get_classifier( + classifier_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_classifier_empty(self): - check_empty_required_params(self, fake_response_Classifier_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/classifiers/{0}'.format(body['classifier_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_classifier_value_error(self): + """ + test_get_classifier_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = VisualRecognitionV3( - authenticator=NoAuthAuthenticator(), - version='2018-03-19', - ) - service.set_service_url(base_url) - output = service.get_classifier(**body) - return output - - def construct_full_body(self): - body = dict() - body['classifier_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['classifier_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for update_classifier -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "classifier_id": classifier_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_classifier(**req_copy) + + + class TestUpdateClassifier(): + """ + Test Class for update_classifier + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_classifier_response(self): - body = self.construct_full_body() - response = fake_response_Classifier_json - send_request(self, body, response) + def test_update_classifier_all_params(self): + """ + update_classifier() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + classifier_id = 'testString' + positive_examples = { 'key': io.BytesIO(b'This is a mock file.').getvalue() } + negative_examples = io.BytesIO(b'This is a mock file.').getvalue() + negative_examples_filename = 'testString' + + # Invoke method + response = service.update_classifier( + classifier_id, + positive_examples=positive_examples, + negative_examples=negative_examples, + negative_examples_filename=negative_examples_filename, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_classifier_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Classifier_json - send_request(self, body, response) + def test_update_classifier_required_params(self): + """ + test_update_classifier_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Invoke method + response = service.update_classifier( + classifier_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_classifier_empty(self): - check_empty_required_params(self, fake_response_Classifier_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/classifiers/{0}'.format(body['classifier_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_update_classifier_value_error(self): + """ + test_update_classifier_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=200, - content_type='application/json') - - def call_service(self, body): - service = VisualRecognitionV3( - authenticator=NoAuthAuthenticator(), - version='2018-03-19', - ) - service.set_service_url(base_url) - output = service.update_classifier(**body) - return output - - def construct_full_body(self): - body = dict() - body['classifier_id'] = "string1" - body['positive_examples'] = {"mock": "data"} - body['negative_examples'] = tempfile.NamedTemporaryFile() - body['negative_examples_filename'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['classifier_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_classifier -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "classifier_id": classifier_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_classifier(**req_copy) + + + class TestDeleteClassifier(): + """ + Test Class for delete_classifier + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_classifier_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_classifier_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_classifier_all_params(self): + """ + delete_classifier() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Invoke method + response = service.delete_classifier( + classifier_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_classifier_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 = '/v3/classifiers/{0}'.format(body['classifier_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_classifier_value_error(self): + """ + test_delete_classifier_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers/testString') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = VisualRecognitionV3( - authenticator=NoAuthAuthenticator(), - version='2018-03-19', - ) - service.set_service_url(base_url) - output = service.delete_classifier(**body) - return output - - def construct_full_body(self): - body = dict() - body['classifier_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['classifier_id'] = "string1" - return body + url, + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "classifier_id": classifier_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_classifier(**req_copy) + # endregion @@ -480,74 +607,74 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for get_core_ml_model -#----------------------------------------------------------------------------- class TestGetCoreMlModel(): + """ + Test Class for get_core_ml_model + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_core_ml_model_response(self): - body = self.construct_full_body() - response = fake_response_BinaryIO_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_core_ml_model_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_BinaryIO_json - send_request(self, body, response) + def test_get_core_ml_model_all_params(self): + """ + get_core_ml_model() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers/testString/core_ml_model') + mock_response = 'This is a mock binary response.' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/octet-stream', + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Invoke method + response = service.get_core_ml_model( + classifier_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_core_ml_model_empty(self): - check_empty_required_params(self, fake_response_BinaryIO_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v3/classifiers/{0}/core_ml_model'.format(body['classifier_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_core_ml_model_value_error(self): + """ + test_get_core_ml_model_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/classifiers/testString/core_ml_model') + mock_response = 'This is a mock binary response.' responses.add(responses.GET, - url, - body=json.dumps(response), - status=200, - content_type='') - - def call_service(self, body): - service = VisualRecognitionV3( - authenticator=NoAuthAuthenticator(), - version='2018-03-19', - ) - service.set_service_url(base_url) - output = service.get_core_ml_model(**body) - return output - - def construct_full_body(self): - body = dict() - body['classifier_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['classifier_id'] = "string1" - return body + url, + body=mock_response, + content_type='application/octet-stream', + status=200) + + # Set up parameter values + classifier_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "classifier_id": classifier_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_core_ml_model(**req_copy) + # endregion @@ -560,74 +687,72 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for delete_user_data -#----------------------------------------------------------------------------- class TestDeleteUserData(): + """ + Test Class for delete_user_data + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_user_data_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_user_data_all_params(self): + """ + delete_user_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/user_data') + responses.add(responses.DELETE, + url, + status=202) + + # Set up parameter values + customer_id = 'testString' + + # Invoke method + response = service.delete_user_data( + customer_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'customer_id={}'.format(customer_id) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_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 = '/v3/user_data' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_user_data_value_error(self): + """ + test_delete_user_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v3/user_data') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=202, - content_type='') - - def call_service(self, body): - service = VisualRecognitionV3( - authenticator=NoAuthAuthenticator(), - version='2018-03-19', - ) - service.set_service_url(base_url) - output = service.delete_user_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['customer_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customer_id'] = "string1" - return body + url, + status=202) + + # Set up parameter values + customer_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customer_id": customer_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_user_data(**req_copy) + # endregion @@ -636,73 +761,370 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestClass(): + """ + Test Class for Class + """ + + def test_class_serialization(self): + """ + Test serialization/deserialization for Class + """ + + # Construct a json representation of a Class model + class_model_json = {} + class_model_json['class'] = 'testString' + + # Construct a model instance of Class by calling from_dict on the json representation + class_model = Class.from_dict(class_model_json) + assert class_model != False - Args: - obj: The generated test function + # Construct a model instance of Class by calling from_dict on the json representation + class_model_dict = Class.from_dict(class_model_json).__dict__ + class_model2 = Class(**class_model_dict) + # Verify the model instances are equivalent + assert class_model == class_model2 + + # Convert model instance back to dict and verify no loss of data + class_model_json2 = class_model.to_dict() + assert class_model_json2 == class_model_json + +class TestClassResult(): + """ + Test Class for ClassResult """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data + def test_class_result_serialization(self): + """ + Test serialization/deserialization for ClassResult + """ + + # Construct a json representation of a ClassResult model + class_result_model_json = {} + class_result_model_json['class'] = 'testString' + class_result_model_json['score'] = 0 + class_result_model_json['type_hierarchy'] = 'testString' + + # Construct a model instance of ClassResult by calling from_dict on the json representation + class_result_model = ClassResult.from_dict(class_result_model_json) + assert class_result_model != False - Args: - obj: The generated test function + # Construct a model instance of ClassResult by calling from_dict on the json representation + class_result_model_dict = ClassResult.from_dict(class_result_model_json).__dict__ + class_result_model2 = ClassResult(**class_result_model_dict) + # Verify the model instances are equivalent + assert class_result_model == class_result_model2 + + # Convert model instance back to dict and verify no loss of data + class_result_model_json2 = class_result_model.to_dict() + assert class_result_model_json2 == class_result_model_json + +class TestClassifiedImage(): + """ + Test Class for ClassifiedImage """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request + def test_classified_image_serialization(self): + """ + Test serialization/deserialization for ClassifiedImage + """ + + # Construct dict forms of any model objects needed in order to build this model. + + error_info_model = {} # ErrorInfo + error_info_model['code'] = 38 + error_info_model['description'] = 'testString' + error_info_model['error_id'] = 'testString' + + class_result_model = {} # ClassResult + class_result_model['class'] = 'testString' + class_result_model['score'] = 0 + class_result_model['type_hierarchy'] = 'testString' + + classifier_result_model = {} # ClassifierResult + classifier_result_model['name'] = 'testString' + classifier_result_model['classifier_id'] = 'testString' + classifier_result_model['classes'] = [class_result_model] + + # Construct a json representation of a ClassifiedImage model + classified_image_model_json = {} + classified_image_model_json['source_url'] = 'testString' + classified_image_model_json['resolved_url'] = 'testString' + classified_image_model_json['image'] = 'testString' + classified_image_model_json['error'] = error_info_model + classified_image_model_json['classifiers'] = [classifier_result_model] + + # Construct a model instance of ClassifiedImage by calling from_dict on the json representation + classified_image_model = ClassifiedImage.from_dict(classified_image_model_json) + assert classified_image_model != False + + # Construct a model instance of ClassifiedImage by calling from_dict on the json representation + classified_image_model_dict = ClassifiedImage.from_dict(classified_image_model_json).__dict__ + classified_image_model2 = ClassifiedImage(**classified_image_model_dict) + + # Verify the model instances are equivalent + assert classified_image_model == classified_image_model2 - Args: - obj: The generated test function + # Convert model instance back to dict and verify no loss of data + classified_image_model_json2 = classified_image_model.to_dict() + assert classified_image_model_json2 == classified_image_model_json +class TestClassifiedImages(): """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) + Test Class for ClassifiedImages + """ + + def test_classified_images_serialization(self): + """ + Test serialization/deserialization for ClassifiedImages + """ + + # Construct dict forms of any model objects needed in order to build this model. + + error_info_model = {} # ErrorInfo + error_info_model['code'] = 38 + error_info_model['description'] = 'testString' + error_info_model['error_id'] = 'testString' + + class_result_model = {} # ClassResult + class_result_model['class'] = 'testString' + class_result_model['score'] = 0 + class_result_model['type_hierarchy'] = 'testString' + + classifier_result_model = {} # ClassifierResult + classifier_result_model['name'] = 'testString' + classifier_result_model['classifier_id'] = 'testString' + classifier_result_model['classes'] = [class_result_model] + + classified_image_model = {} # ClassifiedImage + classified_image_model['source_url'] = 'testString' + classified_image_model['resolved_url'] = 'testString' + classified_image_model['image'] = 'testString' + classified_image_model['error'] = error_info_model + classified_image_model['classifiers'] = [classifier_result_model] + + warning_info_model = {} # WarningInfo + warning_info_model['warning_id'] = 'testString' + warning_info_model['description'] = 'testString' + + # Construct a json representation of a ClassifiedImages model + classified_images_model_json = {} + classified_images_model_json['custom_classes'] = 38 + classified_images_model_json['images_processed'] = 38 + classified_images_model_json['images'] = [classified_image_model] + classified_images_model_json['warnings'] = [warning_info_model] + + # Construct a model instance of ClassifiedImages by calling from_dict on the json representation + classified_images_model = ClassifiedImages.from_dict(classified_images_model_json) + assert classified_images_model != False + + # Construct a model instance of ClassifiedImages by calling from_dict on the json representation + classified_images_model_dict = ClassifiedImages.from_dict(classified_images_model_json).__dict__ + classified_images_model2 = ClassifiedImages(**classified_images_model_dict) + + # Verify the model instances are equivalent + assert classified_images_model == classified_images_model2 + + # Convert model instance back to dict and verify no loss of data + classified_images_model_json2 = classified_images_model.to_dict() + assert classified_images_model_json2 == classified_images_model_json + +class TestClassifier(): + """ + Test Class for Classifier + """ + + def test_classifier_serialization(self): + """ + Test serialization/deserialization for Classifier + """ + + # Construct dict forms of any model objects needed in order to build this model. + + class_model = {} # Class + class_model['class'] = 'testString' + + # Construct a json representation of a Classifier model + classifier_model_json = {} + classifier_model_json['classifier_id'] = 'testString' + classifier_model_json['name'] = 'testString' + classifier_model_json['owner'] = 'testString' + classifier_model_json['status'] = 'ready' + classifier_model_json['core_ml_enabled'] = True + classifier_model_json['explanation'] = 'testString' + classifier_model_json['created'] = '2020-01-28T18:40:40.123456Z' + classifier_model_json['classes'] = [class_model] + classifier_model_json['retrained'] = '2020-01-28T18:40:40.123456Z' + classifier_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of Classifier by calling from_dict on the json representation + classifier_model = Classifier.from_dict(classifier_model_json) + assert classifier_model != False + + # Construct a model instance of Classifier by calling from_dict on the json representation + classifier_model_dict = Classifier.from_dict(classifier_model_json).__dict__ + classifier_model2 = Classifier(**classifier_model_dict) + + # Verify the model instances are equivalent + assert classifier_model == classifier_model2 + + # Convert model instance back to dict and verify no loss of data + classifier_model_json2 = classifier_model.to_dict() + assert classifier_model_json2 == classifier_model_json + +class TestClassifierResult(): + """ + Test Class for ClassifierResult + """ + + def test_classifier_result_serialization(self): + """ + Test serialization/deserialization for ClassifierResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + class_result_model = {} # ClassResult + class_result_model['class'] = 'testString' + class_result_model['score'] = 0 + class_result_model['type_hierarchy'] = 'testString' + + # Construct a json representation of a ClassifierResult model + classifier_result_model_json = {} + classifier_result_model_json['name'] = 'testString' + classifier_result_model_json['classifier_id'] = 'testString' + classifier_result_model_json['classes'] = [class_result_model] + + # Construct a model instance of ClassifierResult by calling from_dict on the json representation + classifier_result_model = ClassifierResult.from_dict(classifier_result_model_json) + assert classifier_result_model != False + + # Construct a model instance of ClassifierResult by calling from_dict on the json representation + classifier_result_model_dict = ClassifierResult.from_dict(classifier_result_model_json).__dict__ + classifier_result_model2 = ClassifierResult(**classifier_result_model_dict) + + # Verify the model instances are equivalent + assert classifier_result_model == classifier_result_model2 + + # Convert model instance back to dict and verify no loss of data + classifier_result_model_json2 = classifier_result_model.to_dict() + assert classifier_result_model_json2 == classifier_result_model_json + +class TestClassifiers(): + """ + Test Class for Classifiers + """ + + def test_classifiers_serialization(self): + """ + Test serialization/deserialization for Classifiers + """ + + # Construct dict forms of any model objects needed in order to build this model. + + class_model = {} # Class + class_model['class'] = 'testString' + + classifier_model = {} # Classifier + classifier_model['classifier_id'] = 'testString' + classifier_model['name'] = 'testString' + classifier_model['owner'] = 'testString' + classifier_model['status'] = 'ready' + classifier_model['core_ml_enabled'] = True + classifier_model['explanation'] = 'testString' + classifier_model['created'] = '2020-01-28T18:40:40.123456Z' + classifier_model['classes'] = [class_model] + classifier_model['retrained'] = '2020-01-28T18:40:40.123456Z' + classifier_model['updated'] = '2020-01-28T18:40:40.123456Z' -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response + # Construct a json representation of a Classifiers model + classifiers_model_json = {} + classifiers_model_json['classifiers'] = [classifier_model] - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string + # Construct a model instance of Classifiers by calling from_dict on the json representation + classifiers_model = Classifiers.from_dict(classifiers_model_json) + assert classifiers_model != False + # Construct a model instance of Classifiers by calling from_dict on the json representation + classifiers_model_dict = Classifiers.from_dict(classifiers_model_json).__dict__ + classifiers_model2 = Classifiers(**classifiers_model_dict) + + # Verify the model instances are equivalent + assert classifiers_model == classifiers_model2 + + # Convert model instance back to dict and verify no loss of data + classifiers_model_json2 = classifiers_model.to_dict() + assert classifiers_model_json2 == classifiers_model_json + +class TestErrorInfo(): + """ + Test Class for ErrorInfo + """ + + def test_error_info_serialization(self): + """ + Test serialization/deserialization for ErrorInfo + """ + + # Construct a json representation of a ErrorInfo model + error_info_model_json = {} + error_info_model_json['code'] = 38 + error_info_model_json['description'] = 'testString' + error_info_model_json['error_id'] = 'testString' + + # Construct a model instance of ErrorInfo by calling from_dict on the json representation + error_info_model = ErrorInfo.from_dict(error_info_model_json) + assert error_info_model != False + + # Construct a model instance of ErrorInfo by calling from_dict on the json representation + error_info_model_dict = ErrorInfo.from_dict(error_info_model_json).__dict__ + error_info_model2 = ErrorInfo(**error_info_model_dict) + + # Verify the model instances are equivalent + assert error_info_model == error_info_model2 + + # Convert model instance back to dict and verify no loss of data + error_info_model_json2 = error_info_model.to_dict() + assert error_info_model_json2 == error_info_model_json + +class TestWarningInfo(): + """ + Test Class for WarningInfo """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response -#################### -## Mock Responses ## -#################### + def test_warning_info_serialization(self): + """ + Test serialization/deserialization for WarningInfo + """ + + # Construct a json representation of a WarningInfo model + warning_info_model_json = {} + warning_info_model_json['warning_id'] = 'testString' + warning_info_model_json['description'] = 'testString' + + # Construct a model instance of WarningInfo by calling from_dict on the json representation + warning_info_model = WarningInfo.from_dict(warning_info_model_json) + assert warning_info_model != False + + # Construct a model instance of WarningInfo by calling from_dict on the json representation + warning_info_model_dict = WarningInfo.from_dict(warning_info_model_json).__dict__ + warning_info_model2 = WarningInfo(**warning_info_model_dict) + + # Verify the model instances are equivalent + assert warning_info_model == warning_info_model2 -fake_response__json = None -fake_response_ClassifiedImages_json = """{"custom_classes": 14, "images_processed": 16, "images": [], "warnings": []}""" -fake_response_Classifier_json = """{"classifier_id": "fake_classifier_id", "name": "fake_name", "owner": "fake_owner", "status": "fake_status", "core_ml_enabled": false, "explanation": "fake_explanation", "created": "2017-05-16T13:56:54.957Z", "classes": [], "retrained": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_Classifiers_json = """{"classifiers": []}""" -fake_response_Classifier_json = """{"classifier_id": "fake_classifier_id", "name": "fake_name", "owner": "fake_owner", "status": "fake_status", "core_ml_enabled": false, "explanation": "fake_explanation", "created": "2017-05-16T13:56:54.957Z", "classes": [], "retrained": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_Classifier_json = """{"classifier_id": "fake_classifier_id", "name": "fake_name", "owner": "fake_owner", "status": "fake_status", "core_ml_enabled": false, "explanation": "fake_explanation", "created": "2017-05-16T13:56:54.957Z", "classes": [], "retrained": "2017-05-16T13:56:54.957Z", "updated": "2017-05-16T13:56:54.957Z"}""" -fake_response_BinaryIO_json = """Contents of response byte-stream...""" + # Convert model instance back to dict and verify no loss of data + warning_info_model_json2 = warning_info_model.to_dict() + assert warning_info_model_json2 == warning_info_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 6db7d26a5..a3e28a064 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -13,96 +13,153 @@ # See the License for the specific language governing permissions and # limitations under the License. -from datetime import datetime +""" +Unit Tests for VisualRecognitionV4 +""" + +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import date_to_string import inspect +import io import json import pytest +import re +import requests import responses import tempfile -import ibm_watson.visual_recognition_v4 +import urllib from ibm_watson.visual_recognition_v4 import * +version = 'testString' + +service = VisualRecognitionV4( + authenticator=NoAuthAuthenticator(), + version=version + ) + base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' +service.set_service_url(base_url) ############################################################################## # Start of Service: Analysis ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for analyze -#----------------------------------------------------------------------------- class TestAnalyze(): + """ + Test Class for analyze + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_analyze_response(self): - body = self.construct_full_body() - response = fake_response_AnalyzeResponse_json - send_request(self, body, response) + def test_analyze_all_params(self): + """ + analyze() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/analyze') + mock_response = '{"images": [{"source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "objects": {"collections": [{"collection_id": "collection_id", "objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}, "score": 5}]}]}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}]}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a FileWithMetadata model + file_with_metadata_model = {} + file_with_metadata_model['data'] = io.BytesIO(b'This is a mock file.').getvalue() + file_with_metadata_model['filename'] = 'testString' + file_with_metadata_model['content_type'] = 'testString' + + # Set up parameter values + collection_ids = ['testString'] + features = ['objects'] + images_file = [file_with_metadata_model] + image_url = ['testString'] + threshold = 0.15 + + # Invoke method + response = service.analyze( + collection_ids, + features, + images_file=images_file, + image_url=image_url, + threshold=threshold, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_analyze_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_AnalyzeResponse_json - send_request(self, body, response) + def test_analyze_required_params(self): + """ + test_analyze_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/analyze') + mock_response = '{"images": [{"source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "objects": {"collections": [{"collection_id": "collection_id", "objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}, "score": 5}]}]}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}]}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_ids = ['testString'] + features = ['objects'] + + # Invoke method + response = service.analyze( + collection_ids, + features, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_analyze_empty(self): - check_empty_required_params(self, fake_response_AnalyzeResponse_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/analyze' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_analyze_value_error(self): + """ + test_analyze_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/analyze') + mock_response = '{"images": [{"source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "objects": {"collections": [{"collection_id": "collection_id", "objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}, "score": 5}]}]}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}]}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' 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.analyze(**body) - return output - - def construct_full_body(self): - body = dict() - body['collection_ids'] = [] - body['features'] = [] - body['images_file'] = [] - body['image_url'] = [] - body['threshold'] = 12345.0 - return body - - def construct_required_body(self): - body = dict() - body['collection_ids'] = [] - body['features'] = [] - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_ids = ['testString'] + features = ['objects'] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_ids": collection_ids, + "features": features, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.analyze(**req_copy) + # endregion @@ -115,425 +172,510 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for create_collection -#----------------------------------------------------------------------------- class TestCreateCollection(): + """ + Test Class for create_collection + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_create_collection_response(self): - body = self.construct_full_body() - response = fake_response_Collection_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_create_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Collection_json - send_request(self, body, response) + def test_create_collection_all_params(self): + """ + create_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ObjectTrainingStatus model + object_training_status_model = {} + object_training_status_model['ready'] = True + object_training_status_model['in_progress'] = True + object_training_status_model['data_changed'] = True + object_training_status_model['latest_failed'] = True + object_training_status_model['rscnn_ready'] = True + object_training_status_model['description'] = 'testString' + + # Construct a dict representation of a TrainingStatus model + training_status_model = {} + training_status_model['objects'] = object_training_status_model + + # Set up parameter values + name = 'testString' + description = 'testString' + training_status = training_status_model + + # Invoke method + response = service.create_collection( + name=name, + description=description, + training_status=training_status, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['training_status'] == training_status_model + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_create_collection_empty(self): - check_empty_response(self) - assert len(responses.calls) == 1 + def test_create_collection_value_error(self): + """ + test_create_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ObjectTrainingStatus model + object_training_status_model = {} + object_training_status_model['ready'] = True + object_training_status_model['in_progress'] = True + object_training_status_model['data_changed'] = True + object_training_status_model['latest_failed'] = True + object_training_status_model['rscnn_ready'] = True + object_training_status_model['description'] = 'testString' + + # Construct a dict representation of a TrainingStatus model + training_status_model = {} + training_status_model['objects'] = object_training_status_model + + # Set up parameter values + name = 'testString' + description = 'testString' + training_status = training_status_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.create_collection(**req_copy) + - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/collections' - 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.create_collection(**body) - return output - - def construct_full_body(self): - body = dict() - body.update({"name": "string1", "description": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body.update({"name": "string1", "description": "string1", }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_collections -#----------------------------------------------------------------------------- class TestListCollections(): + """ + Test Class for list_collections + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_collections_response(self): - body = self.construct_full_body() - response = fake_response_CollectionsList_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_collections_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_CollectionsList_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def test_list_collections_all_params(self): + """ + list_collections() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_collections_empty(self): - check_empty_response(self) + # Invoke method + response = service.list_collections() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/collections' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_list_collections_value_error(self): + """ + test_list_collections_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}]}' 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_collections(**body) - return output - - def construct_full_body(self): - body = dict() - return body - - def construct_required_body(self): - body = dict() - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_collection -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_collections(**req_copy) + + + class TestGetCollection(): + """ + Test Class for get_collection + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_collection_response(self): - body = self.construct_full_body() - response = fake_response_Collection_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Collection_json - send_request(self, body, response) + def test_get_collection_all_params(self): + """ + get_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Invoke method + response = service.get_collection( + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_collection_empty(self): - check_empty_required_params(self, fake_response_Collection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/collections/{0}'.format(body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_collection_value_error(self): + """ + test_get_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' 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_collection(**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_collection -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_collection(**req_copy) + + + class TestUpdateCollection(): + """ + Test Class for update_collection + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_collection_response(self): - body = self.construct_full_body() - response = fake_response_Collection_json - send_request(self, body, response) + def test_update_collection_all_params(self): + """ + update_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ObjectTrainingStatus model + object_training_status_model = {} + object_training_status_model['ready'] = True + object_training_status_model['in_progress'] = True + object_training_status_model['data_changed'] = True + object_training_status_model['latest_failed'] = True + object_training_status_model['rscnn_ready'] = True + object_training_status_model['description'] = 'testString' + + # Construct a dict representation of a TrainingStatus model + training_status_model = {} + training_status_model['objects'] = object_training_status_model + + # Set up parameter values + collection_id = 'testString' + name = 'testString' + description = 'testString' + training_status = training_status_model + + # Invoke method + response = service.update_collection( + collection_id, + name=name, + description=description, + training_status=training_status, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['training_status'] == training_status_model + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_update_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Collection_json - send_request(self, body, response) + def test_update_collection_required_params(self): + """ + test_update_collection_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Invoke method + response = service.update_collection( + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_update_collection_empty(self): - check_empty_required_params(self, fake_response_Collection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/collections/{0}'.format(body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_update_collection_value_error(self): + """ + test_update_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' 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_collection(**body) - return output - - def construct_full_body(self): - body = dict() - body['collection_id'] = "string1" - body.update({"name": "string1", "description": "string1", }) - return body - - def construct_required_body(self): - body = dict() - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_collection -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_collection(**req_copy) + + + class TestDeleteCollection(): + """ + Test Class for delete_collection + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_collection_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_collection_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_collection_all_params(self): + """ + delete_collection() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Invoke method + response = service.delete_collection( + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_collection_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}'.format(body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_collection_value_error(self): + """ + test_delete_collection_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString') 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_collection(**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 get_model_file -#----------------------------------------------------------------------------- + url, + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_collection(**req_copy) + + + class TestGetModelFile(): + """ + Test Class for get_model_file + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_model_file_response(self): - body = self.construct_full_body() - response = fake_response_BinaryIO_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_model_file_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_BinaryIO_json - send_request(self, body, response) + def test_get_model_file_all_params(self): + """ + get_model_file() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/model') + mock_response = 'This is a mock binary response.' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/octet-stream', + status=200) + + # Set up parameter values + collection_id = 'testString' + feature = 'objects' + model_format = 'rscnn' + + # Invoke method + response = service.get_model_file( + collection_id, + feature, + model_format, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'feature={}'.format(feature) in query_string + assert 'model_format={}'.format(model_format) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_model_file_empty(self): - check_empty_required_params(self, fake_response_BinaryIO_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/collections/{0}/model'.format(body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_model_file_value_error(self): + """ + test_get_model_file_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/model') + mock_response = 'This is a mock binary response.' responses.add(responses.GET, - 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.get_model_file(**body) - return output - - def construct_full_body(self): - body = dict() - body['collection_id'] = "string1" - body['feature'] = "string1" - body['model_format'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['collection_id'] = "string1" - body['feature'] = "string1" - body['model_format'] = "string1" - return body + url, + body=mock_response, + content_type='application/octet-stream', + status=200) + + # Set up parameter values + collection_id = 'testString' + feature = 'objects' + model_format = 'rscnn' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + "feature": feature, + "model_format": model_format, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_model_file(**req_copy) + # endregion @@ -546,364 +688,436 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for add_images -#----------------------------------------------------------------------------- class TestAddImages(): + """ + Test Class for add_images + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_images_response(self): - body = self.construct_full_body() - response = fake_response_ImageDetailsList_json - send_request(self, body, response) + def test_add_images_all_params(self): + """ + add_images() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images') + mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00", "created": "2019-01-01T12:00:00", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a FileWithMetadata model + file_with_metadata_model = {} + file_with_metadata_model['data'] = io.BytesIO(b'This is a mock file.').getvalue() + file_with_metadata_model['filename'] = 'testString' + file_with_metadata_model['content_type'] = 'testString' + + # Set up parameter values + collection_id = 'testString' + images_file = [file_with_metadata_model] + image_url = ['testString'] + training_data = 'testString' + + # Invoke method + response = service.add_images( + collection_id, + images_file=images_file, + image_url=image_url, + training_data=training_data, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_images_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ImageDetailsList_json - send_request(self, body, response) + def test_add_images_required_params(self): + """ + test_add_images_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images') + mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00", "created": "2019-01-01T12:00:00", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Invoke method + response = service.add_images( + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_images_empty(self): - check_empty_required_params(self, fake_response_ImageDetailsList_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/collections/{0}/images'.format(body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_add_images_value_error(self): + """ + test_add_images_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images') + mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00", "created": "2019-01-01T12:00:00", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' 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.add_images(**body) - return output - - def construct_full_body(self): - body = dict() - body['collection_id'] = "string1" - body['images_file'] = [] - body['image_url'] = [] - body['training_data'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['collection_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for list_images -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_images(**req_copy) + + + class TestListImages(): + """ + Test Class for list_images + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_list_images_response(self): - body = self.construct_full_body() - response = fake_response_ImageSummaryList_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_list_images_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ImageSummaryList_json - send_request(self, body, response) + def test_list_images_all_params(self): + """ + list_images() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images') + mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Invoke method + response = service.list_images( + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_list_images_empty(self): - check_empty_required_params(self, fake_response_ImageSummaryList_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/collections/{0}/images'.format(body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_list_images_value_error(self): + """ + test_list_images_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images') + mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00"}]}' 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_images(**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 get_image_details -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_images(**req_copy) + + + class TestGetImageDetails(): + """ + Test Class for get_image_details + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_image_details_response(self): - body = self.construct_full_body() - response = fake_response_ImageDetails_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_image_details_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_ImageDetails_json - send_request(self, body, response) + def test_get_image_details_all_params(self): + """ + get_image_details() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString') + mock_response = '{"image_id": "image_id", "updated": "2019-01-01T12:00:00", "created": "2019-01-01T12:00:00", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + image_id = 'testString' + + # Invoke method + response = service.get_image_details( + collection_id, + image_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_image_details_empty(self): - check_empty_required_params(self, fake_response_ImageDetails_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/collections/{0}/images/{1}'.format(body['collection_id'], body['image_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_image_details_value_error(self): + """ + test_get_image_details_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString') + mock_response = '{"image_id": "image_id", "updated": "2019-01-01T12:00:00", "created": "2019-01-01T12:00:00", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}' 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_image_details(**body) - return output - - def construct_full_body(self): - body = dict() - body['collection_id'] = "string1" - body['image_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['collection_id'] = "string1" - body['image_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for delete_image -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + image_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + "image_id": image_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_image_details(**req_copy) + + + class TestDeleteImage(): + """ + Test Class for delete_image + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_image_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_image_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_image_all_params(self): + """ + delete_image() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + collection_id = 'testString' + image_id = 'testString' + + # Invoke method + response = service.delete_image( + collection_id, + image_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_image_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}/images/{1}'.format(body['collection_id'], body['image_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_image_value_error(self): + """ + test_delete_image_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString') 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_image(**body) - return output - - def construct_full_body(self): - body = dict() - body['collection_id'] = "string1" - body['image_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['collection_id'] = "string1" - body['image_id'] = "string1" - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_jpeg_image -#----------------------------------------------------------------------------- + url, + status=200) + + # Set up parameter values + collection_id = 'testString' + image_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + "image_id": image_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_image(**req_copy) + + + class TestGetJpegImage(): + """ + Test Class for get_jpeg_image + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_jpeg_image_response(self): - body = self.construct_full_body() - response = fake_response_BinaryIO_json - send_request(self, body, response) + def test_get_jpeg_image_all_params(self): + """ + get_jpeg_image() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString/jpeg') + mock_response = 'This is a mock binary response.' + responses.add(responses.GET, + url, + body=mock_response, + content_type='image/jpeg', + status=200) + + # Set up parameter values + collection_id = 'testString' + image_id = 'testString' + size = 'full' + + # Invoke method + response = service.get_jpeg_image( + collection_id, + image_id, + size=size, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'size={}'.format(size) in query_string + - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_jpeg_image_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_BinaryIO_json - send_request(self, body, response) + def test_get_jpeg_image_required_params(self): + """ + test_get_jpeg_image_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString/jpeg') + mock_response = 'This is a mock binary response.' + responses.add(responses.GET, + url, + body=mock_response, + content_type='image/jpeg', + status=200) + + # Set up parameter values + collection_id = 'testString' + image_id = 'testString' + + # Invoke method + response = service.get_jpeg_image( + collection_id, + image_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_jpeg_image_empty(self): - check_empty_required_params(self, fake_response_BinaryIO_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/collections/{0}/images/{1}/jpeg'.format(body['collection_id'], body['image_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_get_jpeg_image_value_error(self): + """ + test_get_jpeg_image_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString/jpeg') + mock_response = 'This is a mock binary response.' responses.add(responses.GET, - 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.get_jpeg_image(**body) - return output - - def construct_full_body(self): - body = dict() - body['collection_id'] = "string1" - body['image_id'] = "string1" - body['size'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['collection_id'] = "string1" - body['image_id'] = "string1" - return body + url, + body=mock_response, + content_type='image/jpeg', + status=200) + + # Set up parameter values + collection_id = 'testString' + image_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + "image_id": image_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_jpeg_image(**req_copy) + # endregion @@ -916,292 +1130,297 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for list_object_metadata -#----------------------------------------------------------------------------- class TestListObjectMetadata(): + """ + Test Class for list_object_metadata + """ - #-------------------------------------------------------- - # 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 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # 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) + def test_list_object_metadata_all_params(self): + """ + list_object_metadata() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/objects') + mock_response = '{"object_count": 12, "objects": [{"object": "object", "count": 5}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Invoke method + response = service.list_object_metadata( + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # 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): + def test_list_object_metadata_value_error(self): + """ + test_list_object_metadata_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/objects') + mock_response = '{"object_count": 12, "objects": [{"object": "object", "count": 5}]}' 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 -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.list_object_metadata(**req_copy) + + + class TestUpdateObjectMetadata(): + """ + Test Class for update_object_metadata + """ - #-------------------------------------------------------- - # 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 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # 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) + def test_update_object_metadata_all_params(self): + """ + update_object_metadata() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') + mock_response = '{"object": "object", "count": 5}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + object = 'testString' + new_object = 'testString' + + # Invoke method + response = service.update_object_metadata( + collection_id, + object, + new_object, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['object'] == 'testString' + - #-------------------------------------------------------- - # 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): + def test_update_object_metadata_value_error(self): + """ + test_update_object_metadata_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') + mock_response = '{"object": "object", "count": 5}' 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 -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + object = 'testString' + new_object = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + "object": object, + "new_object": new_object, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.update_object_metadata(**req_copy) + + + class TestGetObjectMetadata(): + """ + Test Class for get_object_metadata + """ - #-------------------------------------------------------- - # 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 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # 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) + def test_get_object_metadata_all_params(self): + """ + get_object_metadata() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') + mock_response = '{"object": "object", "count": 5}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + object = 'testString' + + # Invoke method + response = service.get_object_metadata( + collection_id, + object, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # 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): + def test_get_object_metadata_value_error(self): + """ + test_get_object_metadata_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') + mock_response = '{"object": "object", "count": 5}' 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 -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + collection_id = 'testString' + object = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + "object": object, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_object_metadata(**req_copy) + + + class TestDeleteObject(): + """ + Test Class for delete_object + """ - #-------------------------------------------------------- - # 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 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # 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) + def test_delete_object_all_params(self): + """ + delete_object() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + collection_id = 'testString' + object = 'testString' + + # Invoke method + response = service.delete_object( + collection_id, + object, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + - #-------------------------------------------------------- - # 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): + def test_delete_object_value_error(self): + """ + test_delete_object_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') 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 + url, + status=200) + + # Set up parameter values + collection_id = 'testString' + object = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + "object": object, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_object(**req_copy) + # endregion @@ -1214,217 +1433,274 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for train -#----------------------------------------------------------------------------- class TestTrain(): + """ + Test Class for train + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_train_response(self): - body = self.construct_full_body() - response = fake_response_Collection_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_train_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_Collection_json - send_request(self, body, response) + def test_train_all_params(self): + """ + train() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/train') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + collection_id = 'testString' + + # Invoke method + response = service.train( + collection_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_train_empty(self): - check_empty_required_params(self, fake_response_Collection_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/collections/{0}/train'.format(body['collection_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_train_value_error(self): + """ + test_train_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/train') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' responses.add(responses.POST, - url, - body=json.dumps(response), - status=202, - 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.train(**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 add_image_training_data -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.train(**req_copy) + + + class TestAddImageTrainingData(): + """ + Test Class for add_image_training_data + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_add_image_training_data_response(self): - body = self.construct_full_body() - response = fake_response_TrainingDataObjects_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_add_image_training_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingDataObjects_json - send_request(self, body, response) + def test_add_image_training_data_all_params(self): + """ + add_image_training_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString/training_data') + mock_response = '{"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Location model + location_model = {} + location_model['top'] = 38 + location_model['left'] = 38 + location_model['width'] = 38 + location_model['height'] = 38 + + # Construct a dict representation of a TrainingDataObject model + training_data_object_model = {} + training_data_object_model['object'] = 'testString' + training_data_object_model['location'] = location_model + + # Set up parameter values + collection_id = 'testString' + image_id = 'testString' + objects = [training_data_object_model] + + # Invoke method + response = service.add_image_training_data( + collection_id, + image_id, + objects=objects, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['objects'] == [training_data_object_model] + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_add_image_training_data_empty(self): - check_empty_required_params(self, fake_response_TrainingDataObjects_json) - check_missing_required_params(self) - assert len(responses.calls) == 0 - - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/collections/{0}/images/{1}/training_data'.format(body['collection_id'], body['image_id']) - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_add_image_training_data_value_error(self): + """ + test_add_image_training_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString/training_data') + mock_response = '{"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}' 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.add_image_training_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['collection_id'] = "string1" - body['image_id'] = "string1" - body.update({"objects": [], }) - return body - - def construct_required_body(self): - body = dict() - body['collection_id'] = "string1" - body['image_id'] = "string1" - body.update({"objects": [], }) - return body - - -#----------------------------------------------------------------------------- -# Test Class for get_training_usage -#----------------------------------------------------------------------------- + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a Location model + location_model = {} + location_model['top'] = 38 + location_model['left'] = 38 + location_model['width'] = 38 + location_model['height'] = 38 + + # Construct a dict representation of a TrainingDataObject model + training_data_object_model = {} + training_data_object_model['object'] = 'testString' + training_data_object_model['location'] = location_model + + # Set up parameter values + collection_id = 'testString' + image_id = 'testString' + objects = [training_data_object_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "collection_id": collection_id, + "image_id": image_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.add_image_training_data(**req_copy) + + + class TestGetTrainingUsage(): + """ + Test Class for get_training_usage + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_get_training_usage_response(self): - body = self.construct_full_body() - response = fake_response_TrainingEvents_json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_get_training_usage_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response_TrainingEvents_json - send_request(self, body, response) + def test_get_training_usage_all_params(self): + """ + get_training_usage() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/training_usage') + mock_response = '{"start_time": "2019-01-01T12:00:00", "end_time": "2019-01-01T12:00:00", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00", "status": "failed", "image_count": 11}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + start_time = date.fromtimestamp(1580236840.123456) + end_time = date.fromtimestamp(1580236840.123456) + + # Invoke method + response = service.get_training_usage( + start_time=start_time, + end_time=end_time, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'start_time={}'.format(date_to_string(start_time)) in query_string + assert 'end_time={}'.format(date_to_string(end_time)) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_get_training_usage_empty(self): - check_empty_response(self) + def test_get_training_usage_required_params(self): + """ + test_get_training_usage_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/training_usage') + mock_response = '{"start_time": "2019-01-01T12:00:00", "end_time": "2019-01-01T12:00:00", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00", "status": "failed", "image_count": 11}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = service.get_training_usage() + + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 200 - #----------- - #- Helpers - - #----------- - def make_url(self, body): - endpoint = '/v4/training_usage' - url = '{0}{1}'.format(base_url, endpoint) - return url - def add_mock_response(self, url, response): + @responses.activate + def test_get_training_usage_value_error(self): + """ + test_get_training_usage_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/training_usage') + mock_response = '{"start_time": "2019-01-01T12:00:00", "end_time": "2019-01-01T12:00:00", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00", "status": "failed", "image_count": 11}]}' 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_training_usage(**body) - return output - - def construct_full_body(self): - body = dict() - body['start_time'] = datetime.now().date() - body['end_time'] = datetime.now().date() - return body - - def construct_required_body(self): - body = dict() - return body + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.get_training_usage(**req_copy) + # endregion @@ -1437,74 +1713,72 @@ def construct_required_body(self): ############################################################################## # region -#----------------------------------------------------------------------------- -# Test Class for delete_user_data -#----------------------------------------------------------------------------- class TestDeleteUserData(): + """ + Test Class for delete_user_data + """ - #-------------------------------------------------------- - # Test 1: Send fake data and check response - #-------------------------------------------------------- - @responses.activate - def test_delete_user_data_response(self): - body = self.construct_full_body() - response = fake_response__json - send_request(self, body, response) - assert len(responses.calls) == 1 + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') - #-------------------------------------------------------- - # Test 2: Send only required fake data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_required_response(self): - # Check response with required params - body = self.construct_required_body() - response = fake_response__json - send_request(self, body, response) + def test_delete_user_data_all_params(self): + """ + delete_user_data() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/user_data') + responses.add(responses.DELETE, + url, + status=202) + + # Set up parameter values + customer_id = 'testString' + + # Invoke method + response = service.delete_user_data( + customer_id, + headers={} + ) + + # Check for correct operation assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'customer_id={}'.format(customer_id) in query_string + - #-------------------------------------------------------- - # Test 3: Send empty data and check response - #-------------------------------------------------------- @responses.activate - def test_delete_user_data_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/user_data' - url = '{0}{1}'.format(base_url, endpoint) - return url - - def add_mock_response(self, url, response): + def test_delete_user_data_value_error(self): + """ + test_delete_user_data_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v4/user_data') responses.add(responses.DELETE, - url, - body=json.dumps(response), - status=202, - content_type='') - - def call_service(self, body): - service = VisualRecognitionV4( - authenticator=NoAuthAuthenticator(), - version='2019-02-11', - ) - service.set_service_url(base_url) - output = service.delete_user_data(**body) - return output - - def construct_full_body(self): - body = dict() - body['customer_id'] = "string1" - return body - - def construct_required_body(self): - body = dict() - body['customer_id'] = "string1" - return body + url, + status=202) + + # Set up parameter values + customer_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customer_id": customer_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.delete_user_data(**req_copy) + # endregion @@ -1513,83 +1787,1231 @@ def construct_required_body(self): ############################################################################## -def check_empty_required_params(obj, response): - """Test function to assert that the operation will throw an error when given empty required data - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - body = {k: None for k in body.keys()} - error = False - try: - send_request(obj, body, response) - except ValueError as e: - error = True - assert error - -def check_missing_required_params(obj): - """Test function to assert that the operation will throw an error when missing required data - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - url = obj.make_url(body) - error = False - try: - send_request(obj, {}, {}, url=url) - except TypeError as e: - error = True - assert error - -def check_empty_response(obj): - """Test function to assert that the operation will return an empty response when given an empty request - - Args: - obj: The generated test function - - """ - body = obj.construct_full_body() - url = obj.make_url(body) - send_request(obj, {}, {}, url=url) - -def send_request(obj, body, response, url=None): - """Test function to create a request, send it, and assert its accuracy to the mock response - - Args: - obj: The generated test function - body: Dict filled with fake data for calling the service - response_str: Mock response string - - """ - if not url: - url = obj.make_url(body) - obj.add_mock_response(url, response) - output = obj.call_service(body) - assert responses.calls[0].request.url.startswith(url) - assert output.get_result() == response - -#################### -## Mock Responses ## -#################### - -fake_response__json = None -fake_response_AnalyzeResponse_json = """{"images": [], "warnings": [], "trace": "fake_trace"}""" -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, "rscnn_ready": false, "description": "fake_description"}}}""" -fake_response_CollectionsList_json = """{"collections": []}""" -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, "rscnn_ready": false, "description": "fake_description"}}}""" -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, "rscnn_ready": false, "description": "fake_description"}}}""" -fake_response_BinaryIO_json = """Contents of response byte-stream...""" -fake_response_ImageDetailsList_json = """{"images": [], "warnings": [], "trace": "fake_trace"}""" -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, "rscnn_ready": 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": []}""" +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestAnalyzeResponse(): + """ + Test Class for AnalyzeResponse + """ + + def test_analyze_response_serialization(self): + """ + Test serialization/deserialization for AnalyzeResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + image_source_model = {} # ImageSource + image_source_model['type'] = 'file' + image_source_model['filename'] = 'testString' + image_source_model['archive_filename'] = 'testString' + image_source_model['source_url'] = 'testString' + image_source_model['resolved_url'] = 'testString' + + image_dimensions_model = {} # ImageDimensions + image_dimensions_model['height'] = 38 + image_dimensions_model['width'] = 38 + + object_detail_location_model = {} # ObjectDetailLocation + object_detail_location_model['top'] = 38 + object_detail_location_model['left'] = 38 + object_detail_location_model['width'] = 38 + object_detail_location_model['height'] = 38 + + object_detail_model = {} # ObjectDetail + object_detail_model['object'] = 'testString' + object_detail_model['location'] = object_detail_location_model + object_detail_model['score'] = 72.5 + + collection_objects_model = {} # CollectionObjects + collection_objects_model['collection_id'] = 'testString' + collection_objects_model['objects'] = [object_detail_model] + + detected_objects_model = {} # DetectedObjects + detected_objects_model['collections'] = [collection_objects_model] + + error_target_model = {} # ErrorTarget + error_target_model['type'] = 'field' + error_target_model['name'] = 'testString' + + error_model = {} # Error + error_model['code'] = 'invalid_field' + error_model['message'] = 'testString' + error_model['more_info'] = 'testString' + error_model['target'] = error_target_model + + image_model = {} # Image + image_model['source'] = image_source_model + image_model['dimensions'] = image_dimensions_model + image_model['objects'] = detected_objects_model + image_model['errors'] = [error_model] + + warning_model = {} # Warning + warning_model['code'] = 'invalid_field' + warning_model['message'] = 'testString' + warning_model['more_info'] = 'testString' + + # Construct a json representation of a AnalyzeResponse model + analyze_response_model_json = {} + analyze_response_model_json['images'] = [image_model] + analyze_response_model_json['warnings'] = [warning_model] + analyze_response_model_json['trace'] = 'testString' + + # Construct a model instance of AnalyzeResponse by calling from_dict on the json representation + analyze_response_model = AnalyzeResponse.from_dict(analyze_response_model_json) + assert analyze_response_model != False + + # Construct a model instance of AnalyzeResponse by calling from_dict on the json representation + analyze_response_model_dict = AnalyzeResponse.from_dict(analyze_response_model_json).__dict__ + analyze_response_model2 = AnalyzeResponse(**analyze_response_model_dict) + + # Verify the model instances are equivalent + assert analyze_response_model == analyze_response_model2 + + # Convert model instance back to dict and verify no loss of data + analyze_response_model_json2 = analyze_response_model.to_dict() + assert analyze_response_model_json2 == analyze_response_model_json + +class TestCollection(): + """ + Test Class for Collection + """ + + def test_collection_serialization(self): + """ + Test serialization/deserialization for Collection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + object_training_status_model = {} # ObjectTrainingStatus + object_training_status_model['ready'] = True + object_training_status_model['in_progress'] = True + object_training_status_model['data_changed'] = True + object_training_status_model['latest_failed'] = True + object_training_status_model['rscnn_ready'] = True + object_training_status_model['description'] = 'testString' + + collection_training_status_model = {} # CollectionTrainingStatus + collection_training_status_model['objects'] = object_training_status_model + + # Construct a json representation of a Collection model + collection_model_json = {} + collection_model_json['collection_id'] = 'testString' + collection_model_json['name'] = 'testString' + collection_model_json['description'] = 'testString' + collection_model_json['created'] = '2020-01-28T18:40:40.123456Z' + collection_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + collection_model_json['image_count'] = 38 + collection_model_json['training_status'] = collection_training_status_model + + # Construct a model instance of Collection by calling from_dict on the json representation + collection_model = Collection.from_dict(collection_model_json) + assert collection_model != False + + # Construct a model instance of Collection by calling from_dict on the json representation + collection_model_dict = Collection.from_dict(collection_model_json).__dict__ + collection_model2 = Collection(**collection_model_dict) + + # Verify the model instances are equivalent + assert collection_model == collection_model2 + + # Convert model instance back to dict and verify no loss of data + collection_model_json2 = collection_model.to_dict() + assert collection_model_json2 == collection_model_json + +class TestCollectionObjects(): + """ + Test Class for CollectionObjects + """ + + def test_collection_objects_serialization(self): + """ + Test serialization/deserialization for CollectionObjects + """ + + # Construct dict forms of any model objects needed in order to build this model. + + object_detail_location_model = {} # ObjectDetailLocation + object_detail_location_model['top'] = 38 + object_detail_location_model['left'] = 38 + object_detail_location_model['width'] = 38 + object_detail_location_model['height'] = 38 + + object_detail_model = {} # ObjectDetail + object_detail_model['object'] = 'testString' + object_detail_model['location'] = object_detail_location_model + object_detail_model['score'] = 72.5 + + # Construct a json representation of a CollectionObjects model + collection_objects_model_json = {} + collection_objects_model_json['collection_id'] = 'testString' + collection_objects_model_json['objects'] = [object_detail_model] + + # Construct a model instance of CollectionObjects by calling from_dict on the json representation + collection_objects_model = CollectionObjects.from_dict(collection_objects_model_json) + assert collection_objects_model != False + + # Construct a model instance of CollectionObjects by calling from_dict on the json representation + collection_objects_model_dict = CollectionObjects.from_dict(collection_objects_model_json).__dict__ + collection_objects_model2 = CollectionObjects(**collection_objects_model_dict) + + # Verify the model instances are equivalent + assert collection_objects_model == collection_objects_model2 + + # Convert model instance back to dict and verify no loss of data + collection_objects_model_json2 = collection_objects_model.to_dict() + assert collection_objects_model_json2 == collection_objects_model_json + +class TestCollectionTrainingStatus(): + """ + Test Class for CollectionTrainingStatus + """ + + def test_collection_training_status_serialization(self): + """ + Test serialization/deserialization for CollectionTrainingStatus + """ + + # Construct dict forms of any model objects needed in order to build this model. + + object_training_status_model = {} # ObjectTrainingStatus + object_training_status_model['ready'] = True + object_training_status_model['in_progress'] = True + object_training_status_model['data_changed'] = True + object_training_status_model['latest_failed'] = True + object_training_status_model['rscnn_ready'] = True + object_training_status_model['description'] = 'testString' + + # Construct a json representation of a CollectionTrainingStatus model + collection_training_status_model_json = {} + collection_training_status_model_json['objects'] = object_training_status_model + + # Construct a model instance of CollectionTrainingStatus by calling from_dict on the json representation + collection_training_status_model = CollectionTrainingStatus.from_dict(collection_training_status_model_json) + assert collection_training_status_model != False + + # Construct a model instance of CollectionTrainingStatus by calling from_dict on the json representation + collection_training_status_model_dict = CollectionTrainingStatus.from_dict(collection_training_status_model_json).__dict__ + collection_training_status_model2 = CollectionTrainingStatus(**collection_training_status_model_dict) + + # Verify the model instances are equivalent + assert collection_training_status_model == collection_training_status_model2 + + # Convert model instance back to dict and verify no loss of data + collection_training_status_model_json2 = collection_training_status_model.to_dict() + assert collection_training_status_model_json2 == collection_training_status_model_json + +class TestCollectionsList(): + """ + Test Class for CollectionsList + """ + + def test_collections_list_serialization(self): + """ + Test serialization/deserialization for CollectionsList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + object_training_status_model = {} # ObjectTrainingStatus + object_training_status_model['ready'] = True + object_training_status_model['in_progress'] = True + object_training_status_model['data_changed'] = True + object_training_status_model['latest_failed'] = True + object_training_status_model['rscnn_ready'] = True + object_training_status_model['description'] = 'testString' + + collection_training_status_model = {} # CollectionTrainingStatus + collection_training_status_model['objects'] = object_training_status_model + + collection_model = {} # Collection + collection_model['collection_id'] = 'testString' + collection_model['name'] = 'testString' + collection_model['description'] = 'testString' + collection_model['created'] = '2020-01-28T18:40:40.123456Z' + collection_model['updated'] = '2020-01-28T18:40:40.123456Z' + collection_model['image_count'] = 38 + collection_model['training_status'] = collection_training_status_model + + # Construct a json representation of a CollectionsList model + collections_list_model_json = {} + collections_list_model_json['collections'] = [collection_model] + + # Construct a model instance of CollectionsList by calling from_dict on the json representation + collections_list_model = CollectionsList.from_dict(collections_list_model_json) + assert collections_list_model != False + + # Construct a model instance of CollectionsList by calling from_dict on the json representation + collections_list_model_dict = CollectionsList.from_dict(collections_list_model_json).__dict__ + collections_list_model2 = CollectionsList(**collections_list_model_dict) + + # Verify the model instances are equivalent + assert collections_list_model == collections_list_model2 + + # Convert model instance back to dict and verify no loss of data + collections_list_model_json2 = collections_list_model.to_dict() + assert collections_list_model_json2 == collections_list_model_json + +class TestDetectedObjects(): + """ + Test Class for DetectedObjects + """ + + def test_detected_objects_serialization(self): + """ + Test serialization/deserialization for DetectedObjects + """ + + # Construct dict forms of any model objects needed in order to build this model. + + object_detail_location_model = {} # ObjectDetailLocation + object_detail_location_model['top'] = 38 + object_detail_location_model['left'] = 38 + object_detail_location_model['width'] = 38 + object_detail_location_model['height'] = 38 + + object_detail_model = {} # ObjectDetail + object_detail_model['object'] = 'testString' + object_detail_model['location'] = object_detail_location_model + object_detail_model['score'] = 72.5 + + collection_objects_model = {} # CollectionObjects + collection_objects_model['collection_id'] = 'testString' + collection_objects_model['objects'] = [object_detail_model] + + # Construct a json representation of a DetectedObjects model + detected_objects_model_json = {} + detected_objects_model_json['collections'] = [collection_objects_model] + + # Construct a model instance of DetectedObjects by calling from_dict on the json representation + detected_objects_model = DetectedObjects.from_dict(detected_objects_model_json) + assert detected_objects_model != False + + # Construct a model instance of DetectedObjects by calling from_dict on the json representation + detected_objects_model_dict = DetectedObjects.from_dict(detected_objects_model_json).__dict__ + detected_objects_model2 = DetectedObjects(**detected_objects_model_dict) + + # Verify the model instances are equivalent + assert detected_objects_model == detected_objects_model2 + + # Convert model instance back to dict and verify no loss of data + detected_objects_model_json2 = detected_objects_model.to_dict() + assert detected_objects_model_json2 == detected_objects_model_json + +class TestError(): + """ + Test Class for Error + """ + + def test_error_serialization(self): + """ + Test serialization/deserialization for Error + """ + + # Construct dict forms of any model objects needed in order to build this model. + + error_target_model = {} # ErrorTarget + error_target_model['type'] = 'parameter' + error_target_model['name'] = 'version' + + # Construct a json representation of a Error model + error_model_json = {} + error_model_json['code'] = 'invalid_field' + error_model_json['message'] = 'testString' + error_model_json['more_info'] = 'testString' + error_model_json['target'] = error_target_model + + # Construct a model instance of Error by calling from_dict on the json representation + error_model = Error.from_dict(error_model_json) + assert error_model != False + + # Construct a model instance of Error by calling from_dict on the json representation + error_model_dict = Error.from_dict(error_model_json).__dict__ + error_model2 = Error(**error_model_dict) + + # Verify the model instances are equivalent + assert error_model == error_model2 + + # Convert model instance back to dict and verify no loss of data + error_model_json2 = error_model.to_dict() + assert error_model_json2 == error_model_json + +class TestErrorTarget(): + """ + Test Class for ErrorTarget + """ + + def test_error_target_serialization(self): + """ + Test serialization/deserialization for ErrorTarget + """ + + # Construct a json representation of a ErrorTarget model + error_target_model_json = {} + error_target_model_json['type'] = 'field' + error_target_model_json['name'] = 'testString' + + # Construct a model instance of ErrorTarget by calling from_dict on the json representation + error_target_model = ErrorTarget.from_dict(error_target_model_json) + assert error_target_model != False + + # Construct a model instance of ErrorTarget by calling from_dict on the json representation + error_target_model_dict = ErrorTarget.from_dict(error_target_model_json).__dict__ + error_target_model2 = ErrorTarget(**error_target_model_dict) + + # Verify the model instances are equivalent + assert error_target_model == error_target_model2 + + # Convert model instance back to dict and verify no loss of data + error_target_model_json2 = error_target_model.to_dict() + assert error_target_model_json2 == error_target_model_json + +class TestImage(): + """ + Test Class for Image + """ + + def test_image_serialization(self): + """ + Test serialization/deserialization for Image + """ + + # Construct dict forms of any model objects needed in order to build this model. + + image_source_model = {} # ImageSource + image_source_model['type'] = 'file' + image_source_model['filename'] = 'testString' + image_source_model['archive_filename'] = 'testString' + image_source_model['source_url'] = 'testString' + image_source_model['resolved_url'] = 'testString' + + image_dimensions_model = {} # ImageDimensions + image_dimensions_model['height'] = 38 + image_dimensions_model['width'] = 38 + + object_detail_location_model = {} # ObjectDetailLocation + object_detail_location_model['top'] = 38 + object_detail_location_model['left'] = 38 + object_detail_location_model['width'] = 38 + object_detail_location_model['height'] = 38 + + object_detail_model = {} # ObjectDetail + object_detail_model['object'] = 'testString' + object_detail_model['location'] = object_detail_location_model + object_detail_model['score'] = 72.5 + + collection_objects_model = {} # CollectionObjects + collection_objects_model['collection_id'] = 'testString' + collection_objects_model['objects'] = [object_detail_model] + + detected_objects_model = {} # DetectedObjects + detected_objects_model['collections'] = [collection_objects_model] + + error_target_model = {} # ErrorTarget + error_target_model['type'] = 'field' + error_target_model['name'] = 'testString' + + error_model = {} # Error + error_model['code'] = 'invalid_field' + error_model['message'] = 'testString' + error_model['more_info'] = 'testString' + error_model['target'] = error_target_model + + # Construct a json representation of a Image model + image_model_json = {} + image_model_json['source'] = image_source_model + image_model_json['dimensions'] = image_dimensions_model + image_model_json['objects'] = detected_objects_model + image_model_json['errors'] = [error_model] + + # Construct a model instance of Image by calling from_dict on the json representation + image_model = Image.from_dict(image_model_json) + assert image_model != False + + # Construct a model instance of Image by calling from_dict on the json representation + image_model_dict = Image.from_dict(image_model_json).__dict__ + image_model2 = Image(**image_model_dict) + + # Verify the model instances are equivalent + assert image_model == image_model2 + + # Convert model instance back to dict and verify no loss of data + image_model_json2 = image_model.to_dict() + assert image_model_json2 == image_model_json + +class TestImageDetails(): + """ + Test Class for ImageDetails + """ + + def test_image_details_serialization(self): + """ + Test serialization/deserialization for ImageDetails + """ + + # Construct dict forms of any model objects needed in order to build this model. + + image_source_model = {} # ImageSource + image_source_model['type'] = 'file' + image_source_model['filename'] = 'testString' + image_source_model['archive_filename'] = 'testString' + image_source_model['source_url'] = 'testString' + image_source_model['resolved_url'] = 'testString' + + image_dimensions_model = {} # ImageDimensions + image_dimensions_model['height'] = 38 + image_dimensions_model['width'] = 38 + + error_target_model = {} # ErrorTarget + error_target_model['type'] = 'field' + error_target_model['name'] = 'testString' + + error_model = {} # Error + error_model['code'] = 'invalid_field' + error_model['message'] = 'testString' + error_model['more_info'] = 'testString' + error_model['target'] = error_target_model + + location_model = {} # Location + location_model['top'] = 38 + location_model['left'] = 38 + location_model['width'] = 38 + location_model['height'] = 38 + + training_data_object_model = {} # TrainingDataObject + training_data_object_model['object'] = 'testString' + training_data_object_model['location'] = location_model + + training_data_objects_model = {} # TrainingDataObjects + training_data_objects_model['objects'] = [training_data_object_model] + + # Construct a json representation of a ImageDetails model + image_details_model_json = {} + image_details_model_json['image_id'] = 'testString' + image_details_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + image_details_model_json['created'] = '2020-01-28T18:40:40.123456Z' + image_details_model_json['source'] = image_source_model + image_details_model_json['dimensions'] = image_dimensions_model + image_details_model_json['errors'] = [error_model] + image_details_model_json['training_data'] = training_data_objects_model + + # Construct a model instance of ImageDetails by calling from_dict on the json representation + image_details_model = ImageDetails.from_dict(image_details_model_json) + assert image_details_model != False + + # Construct a model instance of ImageDetails by calling from_dict on the json representation + image_details_model_dict = ImageDetails.from_dict(image_details_model_json).__dict__ + image_details_model2 = ImageDetails(**image_details_model_dict) + + # Verify the model instances are equivalent + assert image_details_model == image_details_model2 + + # Convert model instance back to dict and verify no loss of data + image_details_model_json2 = image_details_model.to_dict() + assert image_details_model_json2 == image_details_model_json + +class TestImageDetailsList(): + """ + Test Class for ImageDetailsList + """ + + def test_image_details_list_serialization(self): + """ + Test serialization/deserialization for ImageDetailsList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + image_source_model = {} # ImageSource + image_source_model['type'] = 'file' + image_source_model['filename'] = 'testString' + image_source_model['archive_filename'] = 'testString' + image_source_model['source_url'] = 'testString' + image_source_model['resolved_url'] = 'testString' + + image_dimensions_model = {} # ImageDimensions + image_dimensions_model['height'] = 38 + image_dimensions_model['width'] = 38 + + error_target_model = {} # ErrorTarget + error_target_model['type'] = 'field' + error_target_model['name'] = 'testString' + + error_model = {} # Error + error_model['code'] = 'invalid_field' + error_model['message'] = 'testString' + error_model['more_info'] = 'testString' + error_model['target'] = error_target_model + + location_model = {} # Location + location_model['top'] = 38 + location_model['left'] = 38 + location_model['width'] = 38 + location_model['height'] = 38 + + training_data_object_model = {} # TrainingDataObject + training_data_object_model['object'] = 'testString' + training_data_object_model['location'] = location_model + + training_data_objects_model = {} # TrainingDataObjects + training_data_objects_model['objects'] = [training_data_object_model] + + image_details_model = {} # ImageDetails + image_details_model['image_id'] = 'testString' + image_details_model['updated'] = '2020-01-28T18:40:40.123456Z' + image_details_model['created'] = '2020-01-28T18:40:40.123456Z' + image_details_model['source'] = image_source_model + image_details_model['dimensions'] = image_dimensions_model + image_details_model['errors'] = [error_model] + image_details_model['training_data'] = training_data_objects_model + + warning_model = {} # Warning + warning_model['code'] = 'invalid_field' + warning_model['message'] = 'testString' + warning_model['more_info'] = 'testString' + + # Construct a json representation of a ImageDetailsList model + image_details_list_model_json = {} + image_details_list_model_json['images'] = [image_details_model] + image_details_list_model_json['warnings'] = [warning_model] + image_details_list_model_json['trace'] = 'testString' + + # Construct a model instance of ImageDetailsList by calling from_dict on the json representation + image_details_list_model = ImageDetailsList.from_dict(image_details_list_model_json) + assert image_details_list_model != False + + # Construct a model instance of ImageDetailsList by calling from_dict on the json representation + image_details_list_model_dict = ImageDetailsList.from_dict(image_details_list_model_json).__dict__ + image_details_list_model2 = ImageDetailsList(**image_details_list_model_dict) + + # Verify the model instances are equivalent + assert image_details_list_model == image_details_list_model2 + + # Convert model instance back to dict and verify no loss of data + image_details_list_model_json2 = image_details_list_model.to_dict() + assert image_details_list_model_json2 == image_details_list_model_json + +class TestImageDimensions(): + """ + Test Class for ImageDimensions + """ + + def test_image_dimensions_serialization(self): + """ + Test serialization/deserialization for ImageDimensions + """ + + # Construct a json representation of a ImageDimensions model + image_dimensions_model_json = {} + image_dimensions_model_json['height'] = 38 + image_dimensions_model_json['width'] = 38 + + # Construct a model instance of ImageDimensions by calling from_dict on the json representation + image_dimensions_model = ImageDimensions.from_dict(image_dimensions_model_json) + assert image_dimensions_model != False + + # Construct a model instance of ImageDimensions by calling from_dict on the json representation + image_dimensions_model_dict = ImageDimensions.from_dict(image_dimensions_model_json).__dict__ + image_dimensions_model2 = ImageDimensions(**image_dimensions_model_dict) + + # Verify the model instances are equivalent + assert image_dimensions_model == image_dimensions_model2 + + # Convert model instance back to dict and verify no loss of data + image_dimensions_model_json2 = image_dimensions_model.to_dict() + assert image_dimensions_model_json2 == image_dimensions_model_json + +class TestImageSource(): + """ + Test Class for ImageSource + """ + + def test_image_source_serialization(self): + """ + Test serialization/deserialization for ImageSource + """ + + # Construct a json representation of a ImageSource model + image_source_model_json = {} + image_source_model_json['type'] = 'file' + image_source_model_json['filename'] = 'testString' + image_source_model_json['archive_filename'] = 'testString' + image_source_model_json['source_url'] = 'testString' + image_source_model_json['resolved_url'] = 'testString' + + # Construct a model instance of ImageSource by calling from_dict on the json representation + image_source_model = ImageSource.from_dict(image_source_model_json) + assert image_source_model != False + + # Construct a model instance of ImageSource by calling from_dict on the json representation + image_source_model_dict = ImageSource.from_dict(image_source_model_json).__dict__ + image_source_model2 = ImageSource(**image_source_model_dict) + + # Verify the model instances are equivalent + assert image_source_model == image_source_model2 + + # Convert model instance back to dict and verify no loss of data + image_source_model_json2 = image_source_model.to_dict() + assert image_source_model_json2 == image_source_model_json + +class TestImageSummary(): + """ + Test Class for ImageSummary + """ + + def test_image_summary_serialization(self): + """ + Test serialization/deserialization for ImageSummary + """ + + # Construct a json representation of a ImageSummary model + image_summary_model_json = {} + image_summary_model_json['image_id'] = 'testString' + image_summary_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a model instance of ImageSummary by calling from_dict on the json representation + image_summary_model = ImageSummary.from_dict(image_summary_model_json) + assert image_summary_model != False + + # Construct a model instance of ImageSummary by calling from_dict on the json representation + image_summary_model_dict = ImageSummary.from_dict(image_summary_model_json).__dict__ + image_summary_model2 = ImageSummary(**image_summary_model_dict) + + # Verify the model instances are equivalent + assert image_summary_model == image_summary_model2 + + # Convert model instance back to dict and verify no loss of data + image_summary_model_json2 = image_summary_model.to_dict() + assert image_summary_model_json2 == image_summary_model_json + +class TestImageSummaryList(): + """ + Test Class for ImageSummaryList + """ + + def test_image_summary_list_serialization(self): + """ + Test serialization/deserialization for ImageSummaryList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + image_summary_model = {} # ImageSummary + image_summary_model['image_id'] = 'testString' + image_summary_model['updated'] = '2020-01-28T18:40:40.123456Z' + + # Construct a json representation of a ImageSummaryList model + image_summary_list_model_json = {} + image_summary_list_model_json['images'] = [image_summary_model] + + # Construct a model instance of ImageSummaryList by calling from_dict on the json representation + image_summary_list_model = ImageSummaryList.from_dict(image_summary_list_model_json) + assert image_summary_list_model != False + + # Construct a model instance of ImageSummaryList by calling from_dict on the json representation + image_summary_list_model_dict = ImageSummaryList.from_dict(image_summary_list_model_json).__dict__ + image_summary_list_model2 = ImageSummaryList(**image_summary_list_model_dict) + + # Verify the model instances are equivalent + assert image_summary_list_model == image_summary_list_model2 + + # Convert model instance back to dict and verify no loss of data + image_summary_list_model_json2 = image_summary_list_model.to_dict() + assert image_summary_list_model_json2 == image_summary_list_model_json + +class TestLocation(): + """ + Test Class for Location + """ + + def test_location_serialization(self): + """ + Test serialization/deserialization for Location + """ + + # Construct a json representation of a Location model + location_model_json = {} + location_model_json['top'] = 38 + location_model_json['left'] = 38 + location_model_json['width'] = 38 + location_model_json['height'] = 38 + + # Construct a model instance of Location by calling from_dict on the json representation + location_model = Location.from_dict(location_model_json) + assert location_model != False + + # Construct a model instance of Location by calling from_dict on the json representation + location_model_dict = Location.from_dict(location_model_json).__dict__ + location_model2 = Location(**location_model_dict) + + # Verify the model instances are equivalent + assert location_model == location_model2 + + # Convert model instance back to dict and verify no loss of data + location_model_json2 = location_model.to_dict() + assert location_model_json2 == location_model_json + +class TestObjectDetail(): + """ + Test Class for ObjectDetail + """ + + def test_object_detail_serialization(self): + """ + Test serialization/deserialization for ObjectDetail + """ + + # Construct dict forms of any model objects needed in order to build this model. + + object_detail_location_model = {} # ObjectDetailLocation + object_detail_location_model['top'] = 38 + object_detail_location_model['left'] = 38 + object_detail_location_model['width'] = 38 + object_detail_location_model['height'] = 38 + + # Construct a json representation of a ObjectDetail model + object_detail_model_json = {} + object_detail_model_json['object'] = 'testString' + object_detail_model_json['location'] = object_detail_location_model + object_detail_model_json['score'] = 72.5 + + # Construct a model instance of ObjectDetail by calling from_dict on the json representation + object_detail_model = ObjectDetail.from_dict(object_detail_model_json) + assert object_detail_model != False + + # Construct a model instance of ObjectDetail by calling from_dict on the json representation + object_detail_model_dict = ObjectDetail.from_dict(object_detail_model_json).__dict__ + object_detail_model2 = ObjectDetail(**object_detail_model_dict) + + # Verify the model instances are equivalent + assert object_detail_model == object_detail_model2 + + # Convert model instance back to dict and verify no loss of data + object_detail_model_json2 = object_detail_model.to_dict() + assert object_detail_model_json2 == object_detail_model_json + +class TestObjectDetailLocation(): + """ + Test Class for ObjectDetailLocation + """ + + def test_object_detail_location_serialization(self): + """ + Test serialization/deserialization for ObjectDetailLocation + """ + + # Construct a json representation of a ObjectDetailLocation model + object_detail_location_model_json = {} + object_detail_location_model_json['top'] = 38 + object_detail_location_model_json['left'] = 38 + object_detail_location_model_json['width'] = 38 + object_detail_location_model_json['height'] = 38 + + # Construct a model instance of ObjectDetailLocation by calling from_dict on the json representation + object_detail_location_model = ObjectDetailLocation.from_dict(object_detail_location_model_json) + assert object_detail_location_model != False + + # Construct a model instance of ObjectDetailLocation by calling from_dict on the json representation + object_detail_location_model_dict = ObjectDetailLocation.from_dict(object_detail_location_model_json).__dict__ + object_detail_location_model2 = ObjectDetailLocation(**object_detail_location_model_dict) + + # Verify the model instances are equivalent + assert object_detail_location_model == object_detail_location_model2 + + # Convert model instance back to dict and verify no loss of data + object_detail_location_model_json2 = object_detail_location_model.to_dict() + assert object_detail_location_model_json2 == object_detail_location_model_json + +class TestObjectMetadata(): + """ + Test Class for ObjectMetadata + """ + + def test_object_metadata_serialization(self): + """ + Test serialization/deserialization for ObjectMetadata + """ + + # Construct a json representation of a ObjectMetadata model + object_metadata_model_json = {} + object_metadata_model_json['object'] = 'testString' + object_metadata_model_json['count'] = 38 + + # Construct a model instance of ObjectMetadata by calling from_dict on the json representation + object_metadata_model = ObjectMetadata.from_dict(object_metadata_model_json) + assert object_metadata_model != False + + # Construct a model instance of ObjectMetadata by calling from_dict on the json representation + object_metadata_model_dict = ObjectMetadata.from_dict(object_metadata_model_json).__dict__ + object_metadata_model2 = ObjectMetadata(**object_metadata_model_dict) + + # Verify the model instances are equivalent + assert object_metadata_model == object_metadata_model2 + + # Convert model instance back to dict and verify no loss of data + object_metadata_model_json2 = object_metadata_model.to_dict() + assert object_metadata_model_json2 == object_metadata_model_json + +class TestObjectMetadataList(): + """ + Test Class for ObjectMetadataList + """ + + def test_object_metadata_list_serialization(self): + """ + Test serialization/deserialization for ObjectMetadataList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + object_metadata_model = {} # ObjectMetadata + object_metadata_model['object'] = 'testString' + object_metadata_model['count'] = 38 + + # Construct a json representation of a ObjectMetadataList model + object_metadata_list_model_json = {} + object_metadata_list_model_json['object_count'] = 38 + object_metadata_list_model_json['objects'] = [object_metadata_model] + + # Construct a model instance of ObjectMetadataList by calling from_dict on the json representation + object_metadata_list_model = ObjectMetadataList.from_dict(object_metadata_list_model_json) + assert object_metadata_list_model != False + + # Construct a model instance of ObjectMetadataList by calling from_dict on the json representation + object_metadata_list_model_dict = ObjectMetadataList.from_dict(object_metadata_list_model_json).__dict__ + object_metadata_list_model2 = ObjectMetadataList(**object_metadata_list_model_dict) + + # Verify the model instances are equivalent + assert object_metadata_list_model == object_metadata_list_model2 + + # Convert model instance back to dict and verify no loss of data + object_metadata_list_model_json2 = object_metadata_list_model.to_dict() + assert object_metadata_list_model_json2 == object_metadata_list_model_json + +class TestObjectTrainingStatus(): + """ + Test Class for ObjectTrainingStatus + """ + + def test_object_training_status_serialization(self): + """ + Test serialization/deserialization for ObjectTrainingStatus + """ + + # Construct a json representation of a ObjectTrainingStatus model + object_training_status_model_json = {} + object_training_status_model_json['ready'] = True + object_training_status_model_json['in_progress'] = True + object_training_status_model_json['data_changed'] = True + object_training_status_model_json['latest_failed'] = True + object_training_status_model_json['rscnn_ready'] = True + object_training_status_model_json['description'] = 'testString' + + # Construct a model instance of ObjectTrainingStatus by calling from_dict on the json representation + object_training_status_model = ObjectTrainingStatus.from_dict(object_training_status_model_json) + assert object_training_status_model != False + + # Construct a model instance of ObjectTrainingStatus by calling from_dict on the json representation + object_training_status_model_dict = ObjectTrainingStatus.from_dict(object_training_status_model_json).__dict__ + object_training_status_model2 = ObjectTrainingStatus(**object_training_status_model_dict) + + # Verify the model instances are equivalent + assert object_training_status_model == object_training_status_model2 + + # Convert model instance back to dict and verify no loss of data + object_training_status_model_json2 = object_training_status_model.to_dict() + assert object_training_status_model_json2 == object_training_status_model_json + +class TestTrainingDataObject(): + """ + Test Class for TrainingDataObject + """ + + def test_training_data_object_serialization(self): + """ + Test serialization/deserialization for TrainingDataObject + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['top'] = 38 + location_model['left'] = 38 + location_model['width'] = 38 + location_model['height'] = 38 + + # Construct a json representation of a TrainingDataObject model + training_data_object_model_json = {} + training_data_object_model_json['object'] = 'testString' + training_data_object_model_json['location'] = location_model + + # Construct a model instance of TrainingDataObject by calling from_dict on the json representation + training_data_object_model = TrainingDataObject.from_dict(training_data_object_model_json) + assert training_data_object_model != False + + # Construct a model instance of TrainingDataObject by calling from_dict on the json representation + training_data_object_model_dict = TrainingDataObject.from_dict(training_data_object_model_json).__dict__ + training_data_object_model2 = TrainingDataObject(**training_data_object_model_dict) + + # Verify the model instances are equivalent + assert training_data_object_model == training_data_object_model2 + + # Convert model instance back to dict and verify no loss of data + training_data_object_model_json2 = training_data_object_model.to_dict() + assert training_data_object_model_json2 == training_data_object_model_json + +class TestTrainingDataObjects(): + """ + Test Class for TrainingDataObjects + """ + + def test_training_data_objects_serialization(self): + """ + Test serialization/deserialization for TrainingDataObjects + """ + + # Construct dict forms of any model objects needed in order to build this model. + + location_model = {} # Location + location_model['top'] = 38 + location_model['left'] = 38 + location_model['width'] = 38 + location_model['height'] = 38 + + training_data_object_model = {} # TrainingDataObject + training_data_object_model['object'] = 'testString' + training_data_object_model['location'] = location_model + + # Construct a json representation of a TrainingDataObjects model + training_data_objects_model_json = {} + training_data_objects_model_json['objects'] = [training_data_object_model] + + # Construct a model instance of TrainingDataObjects by calling from_dict on the json representation + training_data_objects_model = TrainingDataObjects.from_dict(training_data_objects_model_json) + assert training_data_objects_model != False + + # Construct a model instance of TrainingDataObjects by calling from_dict on the json representation + training_data_objects_model_dict = TrainingDataObjects.from_dict(training_data_objects_model_json).__dict__ + training_data_objects_model2 = TrainingDataObjects(**training_data_objects_model_dict) + + # Verify the model instances are equivalent + assert training_data_objects_model == training_data_objects_model2 + + # Convert model instance back to dict and verify no loss of data + training_data_objects_model_json2 = training_data_objects_model.to_dict() + assert training_data_objects_model_json2 == training_data_objects_model_json + +class TestTrainingEvent(): + """ + Test Class for TrainingEvent + """ + + def test_training_event_serialization(self): + """ + Test serialization/deserialization for TrainingEvent + """ + + # Construct a json representation of a TrainingEvent model + training_event_model_json = {} + training_event_model_json['type'] = 'objects' + training_event_model_json['collection_id'] = 'testString' + training_event_model_json['completion_time'] = '2020-01-28T18:40:40.123456Z' + training_event_model_json['status'] = 'failed' + training_event_model_json['image_count'] = 38 + + # Construct a model instance of TrainingEvent by calling from_dict on the json representation + training_event_model = TrainingEvent.from_dict(training_event_model_json) + assert training_event_model != False + + # Construct a model instance of TrainingEvent by calling from_dict on the json representation + training_event_model_dict = TrainingEvent.from_dict(training_event_model_json).__dict__ + training_event_model2 = TrainingEvent(**training_event_model_dict) + + # Verify the model instances are equivalent + assert training_event_model == training_event_model2 + + # Convert model instance back to dict and verify no loss of data + training_event_model_json2 = training_event_model.to_dict() + assert training_event_model_json2 == training_event_model_json + +class TestTrainingEvents(): + """ + Test Class for TrainingEvents + """ + + def test_training_events_serialization(self): + """ + Test serialization/deserialization for TrainingEvents + """ + + # Construct dict forms of any model objects needed in order to build this model. + + training_event_model = {} # TrainingEvent + training_event_model['type'] = 'objects' + training_event_model['collection_id'] = 'testString' + training_event_model['completion_time'] = '2020-01-28T18:40:40.123456Z' + training_event_model['status'] = 'failed' + training_event_model['image_count'] = 38 + + # Construct a json representation of a TrainingEvents model + training_events_model_json = {} + training_events_model_json['start_time'] = '2020-01-28T18:40:40.123456Z' + training_events_model_json['end_time'] = '2020-01-28T18:40:40.123456Z' + training_events_model_json['completed_events'] = 38 + training_events_model_json['trained_images'] = 38 + training_events_model_json['events'] = [training_event_model] + + # Construct a model instance of TrainingEvents by calling from_dict on the json representation + training_events_model = TrainingEvents.from_dict(training_events_model_json) + assert training_events_model != False + + # Construct a model instance of TrainingEvents by calling from_dict on the json representation + training_events_model_dict = TrainingEvents.from_dict(training_events_model_json).__dict__ + training_events_model2 = TrainingEvents(**training_events_model_dict) + + # Verify the model instances are equivalent + assert training_events_model == training_events_model2 + + # Convert model instance back to dict and verify no loss of data + training_events_model_json2 = training_events_model.to_dict() + assert training_events_model_json2 == training_events_model_json + +class TestTrainingStatus(): + """ + Test Class for TrainingStatus + """ + + def test_training_status_serialization(self): + """ + Test serialization/deserialization for TrainingStatus + """ + + # Construct dict forms of any model objects needed in order to build this model. + + object_training_status_model = {} # ObjectTrainingStatus + object_training_status_model['ready'] = True + object_training_status_model['in_progress'] = True + object_training_status_model['data_changed'] = True + object_training_status_model['latest_failed'] = True + object_training_status_model['rscnn_ready'] = True + object_training_status_model['description'] = 'testString' + + # Construct a json representation of a TrainingStatus model + training_status_model_json = {} + training_status_model_json['objects'] = object_training_status_model + + # Construct a model instance of TrainingStatus by calling from_dict on the json representation + training_status_model = TrainingStatus.from_dict(training_status_model_json) + assert training_status_model != False + + # Construct a model instance of TrainingStatus by calling from_dict on the json representation + training_status_model_dict = TrainingStatus.from_dict(training_status_model_json).__dict__ + training_status_model2 = TrainingStatus(**training_status_model_dict) + + # Verify the model instances are equivalent + assert training_status_model == training_status_model2 + + # Convert model instance back to dict and verify no loss of data + training_status_model_json2 = training_status_model.to_dict() + assert training_status_model_json2 == training_status_model_json + +class TestUpdateObjectMetadata(): + """ + Test Class for UpdateObjectMetadata + """ + + def test_update_object_metadata_serialization(self): + """ + Test serialization/deserialization for UpdateObjectMetadata + """ + + # Construct a json representation of a UpdateObjectMetadata model + update_object_metadata_model_json = {} + update_object_metadata_model_json['object'] = 'testString' + update_object_metadata_model_json['count'] = 38 + + # Construct a model instance of UpdateObjectMetadata by calling from_dict on the json representation + update_object_metadata_model = UpdateObjectMetadata.from_dict(update_object_metadata_model_json) + assert update_object_metadata_model != False + + # Construct a model instance of UpdateObjectMetadata by calling from_dict on the json representation + update_object_metadata_model_dict = UpdateObjectMetadata.from_dict(update_object_metadata_model_json).__dict__ + update_object_metadata_model2 = UpdateObjectMetadata(**update_object_metadata_model_dict) + + # Verify the model instances are equivalent + assert update_object_metadata_model == update_object_metadata_model2 + + # Convert model instance back to dict and verify no loss of data + update_object_metadata_model_json2 = update_object_metadata_model.to_dict() + assert update_object_metadata_model_json2 == update_object_metadata_model_json + +class TestWarning(): + """ + Test Class for Warning + """ + + def test_warning_serialization(self): + """ + Test serialization/deserialization for Warning + """ + + # Construct a json representation of a Warning model + warning_model_json = {} + warning_model_json['code'] = 'invalid_field' + warning_model_json['message'] = 'testString' + warning_model_json['more_info'] = 'testString' + + # Construct a model instance of Warning by calling from_dict on the json representation + warning_model = Warning.from_dict(warning_model_json) + assert warning_model != False + + # Construct a model instance of Warning by calling from_dict on the json representation + warning_model_dict = Warning.from_dict(warning_model_json).__dict__ + warning_model2 = Warning(**warning_model_dict) + + # Verify the model instances are equivalent + assert warning_model == warning_model2 + + # Convert model instance back to dict and verify no loss of data + warning_model_json2 = warning_model.to_dict() + assert warning_model_json2 == warning_model_json + +class TestFileWithMetadata(): + """ + Test Class for FileWithMetadata + """ + + def test_file_with_metadata_serialization(self): + """ + Test serialization/deserialization for FileWithMetadata + """ + + # Construct a json representation of a FileWithMetadata model + file_with_metadata_model_json = {} + file_with_metadata_model_json['data'] = io.BytesIO(b'This is a mock file.').getvalue() + file_with_metadata_model_json['filename'] = 'testString' + file_with_metadata_model_json['content_type'] = 'testString' + + # Construct a model instance of FileWithMetadata by calling from_dict on the json representation + file_with_metadata_model = FileWithMetadata.from_dict(file_with_metadata_model_json) + assert file_with_metadata_model != False + + # Construct a model instance of FileWithMetadata by calling from_dict on the json representation + file_with_metadata_model_dict = FileWithMetadata.from_dict(file_with_metadata_model_json).__dict__ + file_with_metadata_model2 = FileWithMetadata(**file_with_metadata_model_dict) + + # Verify the model instances are equivalent + assert file_with_metadata_model == file_with_metadata_model2 + + # Convert model instance back to dict and verify no loss of data + file_with_metadata_model_json2 = file_with_metadata_model.to_dict() + assert file_with_metadata_model_json2 == file_with_metadata_model_json + + +# endregion +############################################################################## +# End of Model Tests +############################################################################## From 4faa9380a606eeb8e8794b918b0f72313e4b1d86 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Thu, 10 Dec 2020 12:56:42 -0500 Subject: [PATCH 294/455] feat: regenerate with current API and add deprecation warnings --- ibm_watson/discovery_v2.py | 1931 ++++++++++--------------- ibm_watson/personality_insights_v3.py | 3 + ibm_watson/visual_recognition_v3.py | 15 +- ibm_watson/visual_recognition_v4.py | 3 + test/unit/test_discovery_v2.py | 17 +- 5 files changed, 755 insertions(+), 1214 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index e4aa4bedc..093b27a19 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -13,6 +13,8 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. + +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201210-124536 """ IBM Watson™ Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive @@ -21,21 +23,20 @@ results. """ -import json -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from .common import get_sdk_headers 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.get_authenticator import get_authenticator_from_environment from os.path import basename -from typing import BinaryIO -from typing import Dict -from typing import List +from typing import BinaryIO, Dict, List +import json import sys +from ibm_cloud_sdk_core import BaseService, DetailedResponse +from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator +from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment +from ibm_cloud_sdk_core.utils import convert_list, convert_model, datetime_to_string, string_to_datetime + +from .common import get_sdk_headers + ############################################################################## # Service ############################################################################## @@ -56,27 +57,21 @@ def __init__( """ Construct a new client for the Discovery service. - :param str version: The API version date to use with the service, in - "YYYY-MM-DD" format. Whenever the API is changed in a backwards - incompatible way, a new minor version of the API is released. - The service uses the API version for the date you specify, or - the most recent version before that date. Note that you should - not programmatically specify the current date at runtime, in - case the API has been updated since your application's release. - Instead, specify a version date that is compatible with your - application, and don't change it until your application is - ready for a later version. + :param str version: Release date of the version of the API you want to use. + Specify dates in YYYY-MM-DD format. The current version is `2019-11-22`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + if version is None: + raise ValueError('version must be provided') + if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator, - disable_ssl_verification=False) + authenticator=authenticator) self.version = version self.configure_service(service_name) @@ -84,7 +79,7 @@ def __init__( # Collections ######################### - def list_collections(self, project_id: str, **kwargs) -> 'DetailedResponse': + def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: """ List collections. @@ -94,15 +89,12 @@ def list_collections(self, project_id: str, **kwargs) -> 'DetailedResponse': from the deploy page of the Discovery administrative tooling. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object """ if project_id is None: raise ValueError('project_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='V2', operation_id='list_collections') @@ -110,8 +102,14 @@ def list_collections(self, project_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v2/projects/{0}/collections'.format( - *self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -127,7 +125,7 @@ def create_collection(self, description: str = None, language: str = None, enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create a collection. @@ -142,7 +140,7 @@ def create_collection(self, enrichments that are applied to this collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ if project_id is None: @@ -150,11 +148,8 @@ def create_collection(self, if name is None: raise ValueError('name must be provided') if enrichments is not None: - enrichments = [self._convert_model(x) for x in enrichments] - + enrichments = [convert_model(x) for x in enrichments] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='create_collection') @@ -168,9 +163,18 @@ def create_collection(self, 'language': language, 'enrichments': enrichments } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v2/projects/{0}/collections'.format( - *self._encode_path_vars(project_id)) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -181,7 +185,7 @@ def create_collection(self, return response def get_collection(self, project_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get collection. @@ -192,17 +196,14 @@ def get_collection(self, project_id: str, collection_id: str, :param str collection_id: The ID 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 + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ if project_id is None: raise ValueError('project_id must be provided') 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='V2', operation_id='get_collection') @@ -210,8 +211,15 @@ def get_collection(self, project_id: str, collection_id: str, params = {'version': self.version} - url = '/v2/projects/{0}/collections/{1}'.format( - *self._encode_path_vars(project_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -227,7 +235,7 @@ def update_collection(self, name: str = None, description: str = None, enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update a collection. @@ -242,7 +250,7 @@ def update_collection(self, enrichments that are applied to this collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ if project_id is None: @@ -250,11 +258,8 @@ def update_collection(self, if collection_id is None: raise ValueError('collection_id must be provided') if enrichments is not None: - enrichments = [self._convert_model(x) for x in enrichments] - + enrichments = [convert_model(x) for x in enrichments] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='update_collection') @@ -267,9 +272,19 @@ def update_collection(self, 'description': description, 'enrichments': enrichments } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v2/projects/{0}/collections/{1}'.format( - *self._encode_path_vars(project_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -280,7 +295,7 @@ def update_collection(self, return response def delete_collection(self, project_id: str, collection_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a collection. @@ -299,10 +314,7 @@ def delete_collection(self, project_id: str, collection_id: str, raise ValueError('project_id must be provided') 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='V2', operation_id='delete_collection') @@ -310,8 +322,14 @@ def delete_collection(self, project_id: str, collection_id: str, params = {'version': self.version} - url = '/v2/projects/{0}/collections/{1}'.format( - *self._encode_path_vars(project_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -341,7 +359,7 @@ def query(self, table_results: 'QueryLargeTableResults' = None, suggested_refinements: 'QueryLargeSuggestedRefinements' = None, passages: 'QueryLargePassages' = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Query a project. @@ -400,21 +418,18 @@ def query(self, retrieval. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object """ if project_id is None: raise ValueError('project_id must be provided') if table_results is not None: - table_results = self._convert_model(table_results) + table_results = convert_model(table_results) if suggested_refinements is not None: - suggested_refinements = self._convert_model(suggested_refinements) + suggested_refinements = convert_model(suggested_refinements) if passages is not None: - passages = self._convert_model(passages) - + passages = convert_model(passages) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='query') @@ -438,9 +453,18 @@ def query(self, 'suggested_refinements': suggested_refinements, 'passages': passages } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v2/projects/{0}/query'.format( - *self._encode_path_vars(project_id)) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/query'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -457,7 +481,7 @@ def get_autocompletion(self, collection_ids: List[str] = None, field: str = None, count: int = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get Autocomplete Suggestions. @@ -477,17 +501,14 @@ def get_autocompletion(self, return. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Completions` object """ if project_id is None: raise ValueError('project_id must be provided') if prefix is None: raise ValueError('prefix 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='V2', operation_id='get_autocompletion') @@ -496,13 +517,20 @@ def get_autocompletion(self, params = { 'version': self.version, 'prefix': prefix, - 'collection_ids': self._convert_list(collection_ids), + 'collection_ids': convert_list(collection_ids), 'field': field, 'count': count } - url = '/v2/projects/{0}/autocompletion'.format( - *self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/autocompletion'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -519,7 +547,7 @@ def query_notices(self, natural_language_query: str = None, count: int = None, offset: int = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Query system notices. @@ -546,15 +574,12 @@ def query_notices(self, the **count** and **offset** values together in any one query is **10000**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ if project_id is None: raise ValueError('project_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='V2', operation_id='query_notices') @@ -569,8 +594,14 @@ def query_notices(self, 'offset': offset } - url = '/v2/projects/{0}/notices'.format( - *self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/notices'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -583,7 +614,7 @@ def list_fields(self, project_id: str, *, collection_ids: List[str] = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List fields. @@ -597,15 +628,12 @@ def list_fields(self, project are used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ListFieldsResponse` object """ if project_id is None: raise ValueError('project_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='V2', operation_id='list_fields') @@ -613,11 +641,17 @@ def list_fields(self, params = { 'version': self.version, - 'collection_ids': self._convert_list(collection_ids) + 'collection_ids': convert_list(collection_ids) } - url = '/v2/projects/{0}/fields'.format( - *self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/fields'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -631,7 +665,7 @@ def list_fields(self, ######################### def get_component_settings(self, project_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List component settings. @@ -641,15 +675,12 @@ def get_component_settings(self, project_id: str, from the deploy page of the Discovery administrative tooling. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ComponentSettingsResponse` object """ if project_id is None: raise ValueError('project_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='V2', operation_id='get_component_settings') @@ -657,8 +688,15 @@ def get_component_settings(self, project_id: str, params = {'version': self.version} - url = '/v2/projects/{0}/component_settings'.format( - *self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/component_settings'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -680,7 +718,7 @@ def add_document(self, file_content_type: str = None, metadata: str = None, x_watson_discovery_force: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Add a document. @@ -703,7 +741,7 @@ def add_document(self, If the document is uploaded to a collection that has it's data shared with another collection, the **X-Watson-Discovery-Force** header must be set to `true`. **Note:** Documents can be added with a specific **document_id** by using the - **_/v2/projects/{project_id}/collections/{collection_id}/documents** method. + **/v2/projects/{project_id}/collections/{collection_id}/documents** method. **Note:** This operation only works on collections created to accept direct file uploads. It cannot be used to modify a collection that connects to an external source such as Microsoft SharePoint. @@ -711,7 +749,7 @@ def add_document(self, :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. :param str collection_id: The ID of the collection. - :param TextIO file: (optional) The content of the document to ingest. The + :param BinaryIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. @@ -728,17 +766,14 @@ def add_document(self, shared with other collections. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ if project_id is None: raise ValueError('project_id must be provided') if collection_id is None: raise ValueError('collection_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='add_document') @@ -755,11 +790,17 @@ def add_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: - metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) - url = '/v2/projects/{0}/collections/{1}/documents'.format( - *self._encode_path_vars(project_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/documents'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -779,7 +820,7 @@ def update_document(self, file_content_type: str = None, metadata: str = None, x_watson_discovery_force: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update a document. @@ -799,7 +840,7 @@ def update_document(self, from the deploy page of the Discovery administrative tooling. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param TextIO file: (optional) The content of the document to ingest. The + :param BinaryIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. @@ -816,7 +857,7 @@ def update_document(self, shared with other collections. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ if project_id is None: @@ -825,10 +866,7 @@ def update_document(self, raise ValueError('collection_id must be provided') if document_id is None: raise ValueError('document_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='update_document') @@ -845,11 +883,18 @@ def update_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: - metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) - url = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( - *self._encode_path_vars(project_id, collection_id, document_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id', 'document_id'] + path_param_values = self.encode_path_vars(project_id, collection_id, + document_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -865,7 +910,7 @@ def delete_document(self, document_id: str, *, x_watson_discovery_force: bool = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete a document. @@ -887,7 +932,7 @@ def delete_document(self, shared with other collections. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `DeleteDocumentResponse` object """ if project_id is None: @@ -896,10 +941,7 @@ def delete_document(self, raise ValueError('collection_id must be provided') if document_id is None: raise ValueError('document_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='delete_document') @@ -907,8 +949,16 @@ def delete_document(self, params = {'version': self.version} - url = '/v2/projects/{0}/collections/{1}/documents/{2}'.format( - *self._encode_path_vars(project_id, collection_id, document_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id', 'document_id'] + path_param_values = self.encode_path_vars(project_id, collection_id, + document_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -922,7 +972,7 @@ def delete_document(self, ######################### def list_training_queries(self, project_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ List training queries. @@ -932,15 +982,12 @@ def list_training_queries(self, project_id: str, from the deploy page of the Discovery administrative tooling. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingQuerySet` object """ if project_id is None: raise ValueError('project_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='V2', operation_id='list_training_queries') @@ -948,8 +995,15 @@ def list_training_queries(self, project_id: str, params = {'version': self.version} - url = '/v2/projects/{0}/training_data/queries'.format( - *self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -959,7 +1013,7 @@ def list_training_queries(self, project_id: str, return response def delete_training_queries(self, project_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete training queries. @@ -974,10 +1028,7 @@ def delete_training_queries(self, project_id: str, if project_id is None: raise ValueError('project_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='V2', operation_id='delete_training_queries') @@ -985,8 +1036,14 @@ def delete_training_queries(self, project_id: str, params = {'version': self.version} - url = '/v2/projects/{0}/training_data/queries'.format( - *self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1001,7 +1058,7 @@ def create_training_query(self, examples: List['TrainingExample'], *, filter: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create training query. @@ -1017,7 +1074,7 @@ def create_training_query(self, **natural_language_query** is applied. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ if project_id is None: @@ -1026,11 +1083,8 @@ def create_training_query(self, raise ValueError('natural_language_query must be provided') if examples is None: raise ValueError('examples must be provided') - examples = [self._convert_model(x) for x in examples] - + examples = [convert_model(x) for x in examples] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='create_training_query') @@ -1043,9 +1097,19 @@ def create_training_query(self, 'examples': examples, 'filter': filter } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' - url = '/v2/projects/{0}/training_data/queries'.format( - *self._encode_path_vars(project_id)) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1056,7 +1120,7 @@ def create_training_query(self, return response def get_training_query(self, project_id: str, query_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get a training data query. @@ -1068,17 +1132,14 @@ def get_training_query(self, project_id: str, query_id: str, :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ if project_id is None: raise ValueError('project_id must be provided') if query_id is None: raise ValueError('query_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='V2', operation_id='get_training_query') @@ -1086,8 +1147,15 @@ def get_training_query(self, project_id: str, query_id: str, params = {'version': self.version} - url = '/v2/projects/{0}/training_data/queries/{1}'.format( - *self._encode_path_vars(project_id, query_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1103,7 +1171,7 @@ def update_training_query(self, examples: List['TrainingExample'], *, filter: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update a training query. @@ -1119,7 +1187,7 @@ def update_training_query(self, **natural_language_query** is applied. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ if project_id is None: @@ -1130,11 +1198,8 @@ def update_training_query(self, raise ValueError('natural_language_query must be provided') if examples is None: raise ValueError('examples must be provided') - examples = [self._convert_model(x) for x in examples] - + examples = [convert_model(x) for x in examples] headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='update_training_query') @@ -1147,9 +1212,19 @@ def update_training_query(self, 'examples': examples, 'filter': filter } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v2/projects/{0}/training_data/queries/{1}'.format( - *self._encode_path_vars(project_id, query_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1171,7 +1246,7 @@ def analyze_document(self, filename: str = None, file_content_type: str = None, metadata: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Analyze a Document. @@ -1185,7 +1260,7 @@ def analyze_document(self, :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. :param str collection_id: The ID of the collection. - :param TextIO file: (optional) The content of the document to ingest. The + :param BinaryIO file: (optional) The content of the document to ingest. The maximum supported file size when adding a file to a collection is 50 megabytes, the maximum supported file size when testing a configuration is 1 megabyte. Files larger than the supported size are rejected. @@ -1199,17 +1274,14 @@ def analyze_document(self, } ```. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `AnalyzedDocument` object """ if project_id is None: raise ValueError('project_id must be provided') 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='V2', operation_id='analyze_document') @@ -1226,11 +1298,17 @@ def analyze_document(self, form_data.append(('file', (filename, file, file_content_type or 'application/octet-stream'))) if metadata: - metadata = str(metadata) form_data.append(('metadata', (None, metadata, 'text/plain'))) - url = '/v2/projects/{0}/collections/{1}/analyze'.format( - *self._encode_path_vars(project_id, collection_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/analyze'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1244,7 +1322,7 @@ def analyze_document(self, # enrichments ######################### - def list_enrichments(self, project_id: str, **kwargs) -> 'DetailedResponse': + def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: """ List Enrichments. @@ -1254,15 +1332,12 @@ def list_enrichments(self, project_id: str, **kwargs) -> 'DetailedResponse': from the deploy page of the Discovery administrative tooling. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Enrichments` object """ if project_id is None: raise ValueError('project_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='V2', operation_id='list_enrichments') @@ -1270,8 +1345,14 @@ def list_enrichments(self, project_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v2/projects/{0}/enrichments'.format( - *self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1285,7 +1366,7 @@ def create_enrichment(self, enrichment: 'CreateEnrichment', *, file: BinaryIO = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create an enrichment. @@ -1294,20 +1375,17 @@ def create_enrichment(self, :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. :param CreateEnrichment enrichment: - :param TextIO file: (optional) The enrichment file to upload. + :param BinaryIO file: (optional) The enrichment file to upload. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ if project_id is None: raise ValueError('project_id must be provided') if enrichment is None: raise ValueError('enrichment 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='V2', operation_id='create_enrichment') @@ -1316,12 +1394,19 @@ def create_enrichment(self, params = {'version': self.version} form_data = [] - form_data.append(('enrichment', (None, json.dumps(enrichment), 'application/json'))) + form_data.append( + ('enrichment', (None, json.dumps(enrichment), 'application/json'))) if file: form_data.append(('file', (None, file, 'application/octet-stream'))) - url = '/v2/projects/{0}/enrichments'.format( - *self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1332,7 +1417,7 @@ def create_enrichment(self, return response def get_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Get enrichment. @@ -1343,17 +1428,14 @@ def get_enrichment(self, project_id: str, enrichment_id: str, :param str enrichment_id: The ID of the enrichment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ if project_id is None: raise ValueError('project_id must be provided') if enrichment_id is None: raise ValueError('enrichment_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='V2', operation_id='get_enrichment') @@ -1361,8 +1443,15 @@ def get_enrichment(self, project_id: str, enrichment_id: str, params = {'version': self.version} - url = '/v2/projects/{0}/enrichments/{1}'.format( - *self._encode_path_vars(project_id, enrichment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1377,7 +1466,7 @@ def update_enrichment(self, name: str, *, description: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update an enrichment. @@ -1390,7 +1479,7 @@ def update_enrichment(self, :param str description: (optional) A new description for the enrichment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ if project_id is None: @@ -1399,10 +1488,7 @@ def update_enrichment(self, raise ValueError('enrichment_id must be provided') if name is None: raise ValueError('name 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='V2', operation_id='update_enrichment') @@ -1411,9 +1497,19 @@ def update_enrichment(self, params = {'version': self.version} data = {'name': name, 'description': description} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v2/projects/{0}/enrichments/{1}'.format( - *self._encode_path_vars(project_id, enrichment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1424,7 +1520,7 @@ def update_enrichment(self, return response def delete_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Delete an enrichment. @@ -1443,10 +1539,7 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, raise ValueError('project_id must be provided') if enrichment_id is None: raise ValueError('enrichment_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='V2', operation_id='delete_enrichment') @@ -1454,8 +1547,14 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, params = {'version': self.version} - url = '/v2/projects/{0}/enrichments/{1}'.format( - *self._encode_path_vars(project_id, enrichment_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1468,7 +1567,7 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, # projects ######################### - def list_projects(self, **kwargs) -> 'DetailedResponse': + def list_projects(self, **kwargs) -> DetailedResponse: """ List projects. @@ -1476,12 +1575,10 @@ def list_projects(self, **kwargs) -> 'DetailedResponse': :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ListProjectsResponse` object """ headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='list_projects') @@ -1489,6 +1586,10 @@ def list_projects(self, **kwargs) -> 'DetailedResponse': params = {'version': self.version} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + url = '/v2/projects' request = self.prepare_request(method='GET', url=url, @@ -1503,7 +1604,7 @@ def create_project(self, type: str, *, default_query_parameters: 'DefaultQueryParams' = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Create a Project. @@ -1515,7 +1616,7 @@ def create_project(self, query parameters for this project. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ if name is None: @@ -1523,12 +1624,8 @@ def create_project(self, if type is None: raise ValueError('type must be provided') if default_query_parameters is not None: - default_query_parameters = self._convert_model( - default_query_parameters) - + default_query_parameters = convert_model(default_query_parameters) headers = {} - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='create_project') @@ -1541,6 +1638,13 @@ def create_project(self, 'type': type, 'default_query_parameters': default_query_parameters } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' url = '/v2/projects' request = self.prepare_request(method='POST', @@ -1552,7 +1656,7 @@ def create_project(self, response = self.send(request) return response - def get_project(self, project_id: str, **kwargs) -> 'DetailedResponse': + def get_project(self, project_id: str, **kwargs) -> DetailedResponse: """ Get project. @@ -1562,15 +1666,12 @@ def get_project(self, project_id: str, **kwargs) -> 'DetailedResponse': from the deploy page of the Discovery administrative tooling. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ if project_id is None: raise ValueError('project_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='V2', operation_id='get_project') @@ -1578,7 +1679,14 @@ def get_project(self, project_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v2/projects/{0}'.format(*self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1591,7 +1699,7 @@ def update_project(self, project_id: str, *, name: str = None, - **kwargs) -> 'DetailedResponse': + **kwargs) -> DetailedResponse: """ Update a project. @@ -1602,15 +1710,12 @@ def update_project(self, :param str name: (optional) The new name to give this project. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ if project_id is None: raise ValueError('project_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='V2', operation_id='update_project') @@ -1619,8 +1724,18 @@ def update_project(self, params = {'version': self.version} data = {'name': name} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - url = '/v2/projects/{0}'.format(*self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1630,7 +1745,7 @@ def update_project(self, response = self.send(request) return response - def delete_project(self, project_id: str, **kwargs) -> 'DetailedResponse': + def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: """ Delete a project. @@ -1647,10 +1762,7 @@ def delete_project(self, project_id: str, **kwargs) -> 'DetailedResponse': if project_id is None: raise ValueError('project_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='V2', operation_id='delete_project') @@ -1658,7 +1770,13 @@ def delete_project(self, project_id: str, **kwargs) -> 'DetailedResponse': params = {'version': self.version} - url = '/v2/projects/{0}'.format(*self._encode_path_vars(project_id)) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1671,8 +1789,7 @@ def delete_project(self, project_id: str, **kwargs) -> 'DetailedResponse': # userData ######################### - def delete_user_data(self, customer_id: str, - **kwargs) -> 'DetailedResponse': + def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: """ Delete labeled data. @@ -1693,10 +1810,7 @@ def delete_user_data(self, customer_id: str, if customer_id is None: raise ValueError('customer_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='V2', operation_id='delete_user_data') @@ -1704,6 +1818,9 @@ def delete_user_data(self, customer_id: str, params = {'version': self.version, 'customer_id': customer_id} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + url = '/v2/user_data' request = self.prepare_request(method='DELETE', url=url, @@ -1714,9 +1831,12 @@ def delete_user_data(self, customer_id: str, return response -class AddDocumentEnums(object): +class AddDocumentEnums: + """ + Enums for add_document parameters. + """ - class FileContentType(Enum): + class FileContentType(str, Enum): """ The content type of file. """ @@ -1728,9 +1848,12 @@ class FileContentType(Enum): APPLICATION_XHTML_XML = 'application/xhtml+xml' -class UpdateDocumentEnums(object): +class UpdateDocumentEnums: + """ + Enums for update_document parameters. + """ - class FileContentType(Enum): + class FileContentType(str, Enum): """ The content type of file. """ @@ -1742,9 +1865,12 @@ class FileContentType(Enum): APPLICATION_XHTML_XML = 'application/xhtml+xml' -class AnalyzeDocumentEnums(object): +class AnalyzeDocumentEnums: + """ + Enums for analyze_document parameters. + """ - class FileContentType(Enum): + class FileContentType(str, Enum): """ The content type of file. """ @@ -1788,18 +1914,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalyzedDocument': """Initialize a AnalyzedDocument object from a json dictionary.""" args = {} - valid_keys = ['notices', 'result'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class AnalyzedDocument: ' - + ', '.join(bad_keys)) if 'notices' in _dict: args['notices'] = [ - Notice._from_dict(x) for x in (_dict.get('notices')) + Notice.from_dict(x) for x in _dict.get('notices') ] if 'result' in _dict: - args['result'] = AnalyzedResult._from_dict(_dict.get('result')) + args['result'] = AnalyzedResult.from_dict(_dict.get('result')) return cls(**args) @classmethod @@ -1811,9 +1931,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x._to_dict() for x in self.notices] + _dict['notices'] = [x.to_dict() for x in self.notices] if hasattr(self, 'result') and self.result is not None: - _dict['result'] = self.result._to_dict() + _dict['result'] = self.result.to_dict() return _dict def _to_dict(self): @@ -1822,7 +1942,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this AnalyzedDocument object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AnalyzedDocument') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1842,6 +1962,9 @@ class AnalyzedResult(): :attr dict metadata: (optional) Metadata of the document. """ + # The set of defined properties for the class + _properties = frozenset(['metadata']) + def __init__(self, *, metadata: dict = None, **kwargs) -> None: """ Initialize a AnalyzedResult object. @@ -1857,11 +1980,10 @@ def __init__(self, *, metadata: dict = None, **kwargs) -> None: def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': """Initialize a AnalyzedResult object from a json dictionary.""" args = {} - xtra = _dict.copy() if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') - del xtra['metadata'] - args.update(xtra) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -1874,29 +1996,21 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + for _key in [ + k for k in vars(self).keys() + if k not in AnalyzedResult._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = {'metadata'} - if not hasattr(self, '_additionalProperties'): - super(AnalyzedResult, self).__setattr__('_additionalProperties', - set()) - if name not in properties: - self._additionalProperties.add(name) - super(AnalyzedResult, self).__setattr__(name, value) - def __str__(self) -> str: """Return a `str` version of this AnalyzedResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'AnalyzedResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -1921,8 +2035,6 @@ def __init__(self, *, collection_id: str = None, name: str = None) -> None: """ Initialize a Collection object. - :param str collection_id: (optional) The unique identifier of the - collection. :param str name: (optional) The name of the collection. """ self.collection_id = collection_id @@ -1932,12 +2044,6 @@ def __init__(self, *, collection_id: str = None, name: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} - valid_keys = ['collection_id', 'name'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Collection: ' - + ', '.join(bad_keys)) if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') if 'name' in _dict: @@ -1952,8 +2058,9 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id + if hasattr(self, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name return _dict @@ -1964,7 +2071,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Collection object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Collection') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2002,11 +2109,7 @@ def __init__(self, Initialize a CollectionDetails object. :param str name: The name of the collection. - :param str collection_id: (optional) The unique identifier of the - collection. :param str description: (optional) A description of the collection. - :param datetime created: (optional) The date that the collection was - created. :param str language: (optional) The language of the collection. :param List[CollectionEnrichment] enrichments: (optional) An array of enrichments that are applied to this collection. @@ -2022,15 +2125,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CollectionDetails': """Initialize a CollectionDetails object from a json dictionary.""" args = {} - valid_keys = [ - 'collection_id', 'name', 'description', 'created', 'language', - 'enrichments' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CollectionDetails: ' - + ', '.join(bad_keys)) if 'collection_id' in _dict: args['collection_id'] = _dict.get('collection_id') if 'name' in _dict: @@ -2047,8 +2141,8 @@ def from_dict(cls, _dict: Dict) -> 'CollectionDetails': args['language'] = _dict.get('language') if 'enrichments' in _dict: args['enrichments'] = [ - CollectionEnrichment._from_dict(x) - for x in (_dict.get('enrichments')) + CollectionEnrichment.from_dict(x) + for x in _dict.get('enrichments') ] return cls(**args) @@ -2060,18 +2154,19 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id + if hasattr(self, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x._to_dict() for x in self.enrichments] + _dict['enrichments'] = [x.to_dict() for x in self.enrichments] return _dict def _to_dict(self): @@ -2080,7 +2175,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CollectionDetails object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CollectionDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2121,12 +2216,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CollectionEnrichment': """Initialize a CollectionEnrichment object from a json dictionary.""" args = {} - valid_keys = ['enrichment_id', 'fields'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CollectionEnrichment: ' - + ', '.join(bad_keys)) if 'enrichment_id' in _dict: args['enrichment_id'] = _dict.get('enrichment_id') if 'fields' in _dict: @@ -2153,7 +2242,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CollectionEnrichment object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CollectionEnrichment') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2187,12 +2276,6 @@ def __init__(self, *, completions: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'Completions': """Initialize a Completions object from a json dictionary.""" args = {} - valid_keys = ['completions'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Completions: ' - + ', '.join(bad_keys)) if 'completions' in _dict: args['completions'] = _dict.get('completions') return cls(**args) @@ -2215,7 +2298,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Completions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Completions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2267,14 +2350,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': """Initialize a ComponentSettingsAggregation object from a json dictionary.""" args = {} - valid_keys = [ - 'name', 'label', 'multiple_selections_allowed', 'visualization_type' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsAggregation: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') if 'label' in _dict: @@ -2314,7 +2389,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ComponentSettingsAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ComponentSettingsAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2326,14 +2401,14 @@ def __ne__(self, other: 'ComponentSettingsAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class VisualizationTypeEnum(Enum): + class VisualizationTypeEnum(str, Enum): """ Type of visualization to use when rendering the aggregation. """ - AUTO = "auto" - FACET_TABLE = "facet_table" - WORD_CLOUD = "word_cloud" - MAP = "map" + AUTO = 'auto' + FACET_TABLE = 'facet_table' + WORD_CLOUD = 'word_cloud' + MAP = 'map' class ComponentSettingsFieldsShown(): @@ -2361,17 +2436,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" args = {} - valid_keys = ['body', 'title'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShown: ' - + ', '.join(bad_keys)) if 'body' in _dict: - args['body'] = ComponentSettingsFieldsShownBody._from_dict( + args['body'] = ComponentSettingsFieldsShownBody.from_dict( _dict.get('body')) if 'title' in _dict: - args['title'] = ComponentSettingsFieldsShownTitle._from_dict( + args['title'] = ComponentSettingsFieldsShownTitle.from_dict( _dict.get('title')) return cls(**args) @@ -2384,9 +2453,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body._to_dict() + _dict['body'] = self.body.to_dict() if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title._to_dict() + _dict['title'] = self.title.to_dict() return _dict def _to_dict(self): @@ -2395,7 +2464,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ComponentSettingsFieldsShown object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ComponentSettingsFieldsShown') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2430,12 +2499,6 @@ def __init__(self, *, use_passage: bool = None, field: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" args = {} - valid_keys = ['use_passage', 'field'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownBody: ' - + ', '.join(bad_keys)) if 'use_passage' in _dict: args['use_passage'] = _dict.get('use_passage') if 'field' in _dict: @@ -2462,7 +2525,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ComponentSettingsFieldsShownBody object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2494,12 +2557,6 @@ def __init__(self, *, field: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" args = {} - valid_keys = ['field'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsFieldsShownTitle: ' - + ', '.join(bad_keys)) if 'field' in _dict: args['field'] = _dict.get('field') return cls(**args) @@ -2522,7 +2579,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ComponentSettingsFieldsShownTitle object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2580,17 +2637,8 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': """Initialize a ComponentSettingsResponse object from a json dictionary.""" args = {} - valid_keys = [ - 'fields_shown', 'autocomplete', 'structured_search', - 'results_per_page', 'aggregations' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ComponentSettingsResponse: ' - + ', '.join(bad_keys)) if 'fields_shown' in _dict: - args['fields_shown'] = ComponentSettingsFieldsShown._from_dict( + args['fields_shown'] = ComponentSettingsFieldsShown.from_dict( _dict.get('fields_shown')) if 'autocomplete' in _dict: args['autocomplete'] = _dict.get('autocomplete') @@ -2600,8 +2648,8 @@ def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': args['results_per_page'] = _dict.get('results_per_page') if 'aggregations' in _dict: args['aggregations'] = [ - ComponentSettingsAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + ComponentSettingsAggregation.from_dict(x) + for x in _dict.get('aggregations') ] return cls(**args) @@ -2614,7 +2662,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fields_shown') and self.fields_shown is not None: - _dict['fields_shown'] = self.fields_shown._to_dict() + _dict['fields_shown'] = self.fields_shown.to_dict() if hasattr(self, 'autocomplete') and self.autocomplete is not None: _dict['autocomplete'] = self.autocomplete if hasattr(self, @@ -2624,7 +2672,7 @@ def to_dict(self) -> Dict: 'results_per_page') and self.results_per_page is not None: _dict['results_per_page'] = self.results_per_page if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -2633,7 +2681,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ComponentSettingsResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ComponentSettingsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2681,12 +2729,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': """Initialize a CreateEnrichment object from a json dictionary.""" args = {} - valid_keys = ['name', 'description', 'type', 'options'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class CreateEnrichment: ' - + ', '.join(bad_keys)) if 'name' in _dict: args['name'] = _dict.get('name') if 'description' in _dict: @@ -2694,7 +2736,7 @@ def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': if 'type' in _dict: args['type'] = _dict.get('type') if 'options' in _dict: - args['options'] = EnrichmentOptions._from_dict(_dict.get('options')) + args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) return cls(**args) @classmethod @@ -2712,7 +2754,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options._to_dict() + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -2721,7 +2763,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this CreateEnrichment object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'CreateEnrichment') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2733,15 +2775,15 @@ def __ne__(self, other: 'CreateEnrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The type of this enrichment. """ - DICTIONARY = "dictionary" - REGULAR_EXPRESSION = "regular_expression" - UIMA_ANNOTATOR = "uima_annotator" - RULE_BASED = "rule_based" - WATSON_KNOWLEDGE_STUDIO_MODEL = "watson_knowledge_studio_model" + DICTIONARY = 'dictionary' + REGULAR_EXPRESSION = 'regular_expression' + UIMA_ANNOTATOR = 'uima_annotator' + RULE_BASED = 'rule_based' + WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' class DefaultQueryParams(): @@ -2822,29 +2864,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DefaultQueryParams': """Initialize a DefaultQueryParams object from a json dictionary.""" args = {} - valid_keys = [ - 'collection_ids', 'passages', 'table_results', 'aggregation', - 'suggested_refinements', 'spelling_suggestions', 'highlight', - 'count', 'sort', 'return_', 'return' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DefaultQueryParams: ' - + ', '.join(bad_keys)) if 'collection_ids' in _dict: args['collection_ids'] = _dict.get('collection_ids') if 'passages' in _dict: - args['passages'] = DefaultQueryParamsPassages._from_dict( + args['passages'] = DefaultQueryParamsPassages.from_dict( _dict.get('passages')) if 'table_results' in _dict: - args['table_results'] = DefaultQueryParamsTableResults._from_dict( + args['table_results'] = DefaultQueryParamsTableResults.from_dict( _dict.get('table_results')) if 'aggregation' in _dict: args['aggregation'] = _dict.get('aggregation') if 'suggested_refinements' in _dict: args[ - 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements._from_dict( + 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements.from_dict( _dict.get('suggested_refinements')) if 'spelling_suggestions' in _dict: args['spelling_suggestions'] = _dict.get('spelling_suggestions') @@ -2869,16 +2901,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'collection_ids') and self.collection_ids is not None: _dict['collection_ids'] = self.collection_ids if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = self.passages._to_dict() + _dict['passages'] = self.passages.to_dict() if hasattr(self, 'table_results') and self.table_results is not None: - _dict['table_results'] = self.table_results._to_dict() + _dict['table_results'] = self.table_results.to_dict() if hasattr(self, 'aggregation') and self.aggregation is not None: _dict['aggregation'] = self.aggregation if hasattr(self, 'suggested_refinements' ) and self.suggested_refinements is not None: - _dict[ - 'suggested_refinements'] = self.suggested_refinements._to_dict( - ) + _dict['suggested_refinements'] = self.suggested_refinements.to_dict( + ) if hasattr(self, 'spelling_suggestions' ) and self.spelling_suggestions is not None: _dict['spelling_suggestions'] = self.spelling_suggestions @@ -2898,7 +2929,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DefaultQueryParams object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DefaultQueryParams') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -2965,15 +2996,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsPassages': """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" args = {} - valid_keys = [ - 'enabled', 'count', 'fields', 'characters', 'per_document', - 'max_per_document' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DefaultQueryParamsPassages: ' - + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'count' in _dict: @@ -3017,7 +3039,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DefaultQueryParamsPassages object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DefaultQueryParamsPassages') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3056,12 +3078,6 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsSuggestedRefinements': """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" args = {} - valid_keys = ['enabled', 'count'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DefaultQueryParamsSuggestedRefinements: ' - + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'count' in _dict: @@ -3088,7 +3104,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DefaultQueryParamsSuggestedRefinements object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3135,12 +3151,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsTableResults': """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" args = {} - valid_keys = ['enabled', 'count', 'per_document'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DefaultQueryParamsTableResults: ' - + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'count' in _dict: @@ -3171,7 +3181,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DefaultQueryParamsTableResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DefaultQueryParamsTableResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3208,12 +3218,6 @@ def __init__(self, *, document_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} - valid_keys = ['document_id', 'status'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DeleteDocumentResponse: ' - + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'status' in _dict: @@ -3240,7 +3244,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DeleteDocumentResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3252,11 +3256,11 @@ def __ne__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Status of the document. A deleted document has the status deleted. """ - DELETED = "deleted" + DELETED = 'deleted' class DocumentAccepted(): @@ -3289,12 +3293,6 @@ def __init__(self, *, document_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': """Initialize a DocumentAccepted object from a json dictionary.""" args = {} - valid_keys = ['document_id', 'status'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentAccepted: ' - + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') if 'status' in _dict: @@ -3321,7 +3319,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocumentAccepted object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3333,14 +3331,14 @@ def __ne__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(Enum): + class StatusEnum(str, Enum): """ Status of the document in the ingestion process. A status of `processing` is returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. """ - PROCESSING = "processing" - PENDING = "pending" + PROCESSING = 'processing' + PENDING = 'pending' class DocumentAttribute(): @@ -3376,18 +3374,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': """Initialize a DocumentAttribute object from a json dictionary.""" args = {} - valid_keys = ['type', 'text', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class DocumentAttribute: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: - args['location'] = TableElementLocation._from_dict( + args['location'] = TableElementLocation.from_dict( _dict.get('location')) return cls(**args) @@ -3404,7 +3396,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -3413,7 +3405,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this DocumentAttribute object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'DocumentAttribute') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3448,8 +3440,6 @@ def __init__(self, """ Initialize a Enrichment object. - :param str enrichment_id: (optional) The unique identifier of this - enrichment. :param str name: (optional) The human readable name for this enrichment. :param str description: (optional) The description of this enrichment. :param str type: (optional) The type of this enrichment. @@ -3466,12 +3456,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Enrichment': """Initialize a Enrichment object from a json dictionary.""" args = {} - valid_keys = ['enrichment_id', 'name', 'description', 'type', 'options'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Enrichment: ' - + ', '.join(bad_keys)) if 'enrichment_id' in _dict: args['enrichment_id'] = _dict.get('enrichment_id') if 'name' in _dict: @@ -3481,7 +3465,7 @@ def from_dict(cls, _dict: Dict) -> 'Enrichment': if 'type' in _dict: args['type'] = _dict.get('type') if 'options' in _dict: - args['options'] = EnrichmentOptions._from_dict(_dict.get('options')) + args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) return cls(**args) @classmethod @@ -3492,8 +3476,9 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: - _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'enrichment_id') and getattr( + self, 'enrichment_id') is not None: + _dict['enrichment_id'] = getattr(self, 'enrichment_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'description') and self.description is not None: @@ -3501,7 +3486,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options._to_dict() + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -3510,7 +3495,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Enrichment object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Enrichment') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3522,18 +3507,18 @@ def __ne__(self, other: 'Enrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The type of this enrichment. """ - PART_OF_SPEECH = "part_of_speech" - SENTIMENT = "sentiment" - NATURAL_LANGUAGE_UNDERSTANDING = "natural_language_understanding" - DICTIONARY = "dictionary" - REGULAR_EXPRESSION = "regular_expression" - UIMA_ANNOTATOR = "uima_annotator" - RULE_BASED = "rule_based" - WATSON_KNOWLEDGE_STUDIO_MODEL = "watson_knowledge_studio_model" + PART_OF_SPEECH = 'part_of_speech' + SENTIMENT = 'sentiment' + NATURAL_LANGUAGE_UNDERSTANDING = 'natural_language_understanding' + DICTIONARY = 'dictionary' + REGULAR_EXPRESSION = 'regular_expression' + UIMA_ANNOTATOR = 'uima_annotator' + RULE_BASED = 'rule_based' + WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' class EnrichmentOptions(): @@ -3584,14 +3569,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} - valid_keys = [ - 'languages', 'entity_type', 'regular_expression', 'result_field' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class EnrichmentOptions: ' - + ', '.join(bad_keys)) if 'languages' in _dict: args['languages'] = _dict.get('languages') if 'entity_type' in _dict: @@ -3628,7 +3605,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this EnrichmentOptions object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'EnrichmentOptions') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3662,15 +3639,9 @@ def __init__(self, *, enrichments: List['Enrichment'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'Enrichments': """Initialize a Enrichments object from a json dictionary.""" args = {} - valid_keys = ['enrichments'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Enrichments: ' - + ', '.join(bad_keys)) if 'enrichments' in _dict: args['enrichments'] = [ - Enrichment._from_dict(x) for x in (_dict.get('enrichments')) + Enrichment.from_dict(x) for x in _dict.get('enrichments') ] return cls(**args) @@ -3683,7 +3654,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x._to_dict() for x in self.enrichments] + _dict['enrichments'] = [x.to_dict() for x in self.enrichments] return _dict def _to_dict(self): @@ -3692,7 +3663,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Enrichments object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Enrichments') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3723,10 +3694,6 @@ def __init__(self, """ Initialize a Field object. - :param str field: (optional) The name of the field. - :param str type: (optional) The type of the field. - :param str collection_id: (optional) The collection Id of the collection - where the field was found. """ self.field = field self.type = type @@ -3736,12 +3703,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Field': """Initialize a Field object from a json dictionary.""" args = {} - valid_keys = ['field', 'type', 'collection_id'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Field: ' + - ', '.join(bad_keys)) if 'field' in _dict: args['field'] = _dict.get('field') if 'type' in _dict: @@ -3758,12 +3719,13 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id + if hasattr(self, 'field') and getattr(self, 'field') is not None: + _dict['field'] = getattr(self, 'field') + if hasattr(self, 'type') and getattr(self, 'type') is not None: + _dict['type'] = getattr(self, 'type') + if hasattr(self, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') return _dict def _to_dict(self): @@ -3772,7 +3734,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Field object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Field') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3784,21 +3746,21 @@ def __ne__(self, other: 'Field') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The type of the field. """ - NESTED = "nested" - STRING = "string" - DATE = "date" - LONG = "long" - INTEGER = "integer" - SHORT = "short" - BYTE = "byte" - DOUBLE = "double" - FLOAT = "float" - BOOLEAN = "boolean" - BINARY = "binary" + NESTED = 'nested' + STRING = 'string' + DATE = 'date' + LONG = 'long' + INTEGER = 'integer' + SHORT = 'short' + BYTE = 'byte' + DOUBLE = 'double' + FLOAT = 'float' + BOOLEAN = 'boolean' + BINARY = 'binary' class ListCollectionsResponse(): @@ -3822,15 +3784,9 @@ def __init__(self, *, collections: List['Collection'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} - valid_keys = ['collections'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ListCollectionsResponse: ' - + ', '.join(bad_keys)) if 'collections' in _dict: args['collections'] = [ - Collection._from_dict(x) for x in (_dict.get('collections')) + Collection.from_dict(x) for x in _dict.get('collections') ] return cls(**args) @@ -3843,7 +3799,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = [x._to_dict() for x in self.collections] + _dict['collections'] = [x.to_dict() for x in self.collections] return _dict def _to_dict(self): @@ -3852,7 +3808,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ListCollectionsResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ListCollectionsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3892,16 +3848,8 @@ def __init__(self, *, fields: List['Field'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': """Initialize a ListFieldsResponse object from a json dictionary.""" args = {} - valid_keys = ['fields'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ListFieldsResponse: ' - + ', '.join(bad_keys)) if 'fields' in _dict: - args['fields'] = [ - Field._from_dict(x) for x in (_dict.get('fields')) - ] + args['fields'] = [Field.from_dict(x) for x in _dict.get('fields')] return cls(**args) @classmethod @@ -3913,7 +3861,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = [x._to_dict() for x in self.fields] + _dict['fields'] = [x.to_dict() for x in self.fields] return _dict def _to_dict(self): @@ -3922,7 +3870,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ListFieldsResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ListFieldsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -3955,16 +3903,9 @@ def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListProjectsResponse': """Initialize a ListProjectsResponse object from a json dictionary.""" args = {} - valid_keys = ['projects'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ListProjectsResponse: ' - + ', '.join(bad_keys)) if 'projects' in _dict: args['projects'] = [ - ProjectListDetails._from_dict(x) - for x in (_dict.get('projects')) + ProjectListDetails.from_dict(x) for x in _dict.get('projects') ] return cls(**args) @@ -3977,7 +3918,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'projects') and self.projects is not None: - _dict['projects'] = [x._to_dict() for x in self.projects] + _dict['projects'] = [x.to_dict() for x in self.projects] return _dict def _to_dict(self): @@ -3986,7 +3927,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ListProjectsResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ListProjectsResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4042,30 +3983,6 @@ def __init__(self, """ Initialize a Notice object. - :param str notice_id: (optional) Identifies the notice. Many notices might - have the same ID. This field exists so that user applications can - programmatically identify a notice and take automatic corrective action. - Typical notice IDs include: `index_failed`, - `index_failed_too_many_requests`, `index_failed_incompatible_field`, - `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, - `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, - `smart_document_understanding_failed_incompatible_field`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_warning`, - `smart_document_understanding_page_error`, - `smart_document_understanding_page_warning`. **Note:** This is not a - complete list, other values might be returned. - :param datetime created: (optional) The creation date of the collection in - the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param str document_id: (optional) Unique identifier of the document. - :param str collection_id: (optional) Unique identifier of the collection. - :param str query_id: (optional) Unique identifier of the query used for - relevance training. - :param str severity: (optional) Severity level of the notice. - :param str step: (optional) Ingestion or training step in which the notice - occurred. - :param str description: (optional) The description of the notice. """ self.notice_id = notice_id self.created = created @@ -4080,15 +3997,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} - valid_keys = [ - 'notice_id', 'created', 'document_id', 'collection_id', 'query_id', - 'severity', 'step', 'description' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class Notice: ' + - ', '.join(bad_keys)) if 'notice_id' in _dict: args['notice_id'] = _dict.get('notice_id') if 'created' in _dict: @@ -4115,22 +4023,26 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'notice_id') and self.notice_id is not None: - _dict['notice_id'] = self.notice_id - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'query_id') and self.query_id is not None: - _dict['query_id'] = self.query_id - if hasattr(self, 'severity') and self.severity is not None: - _dict['severity'] = self.severity - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description + if hasattr(self, 'notice_id') and getattr(self, + 'notice_id') is not None: + _dict['notice_id'] = getattr(self, 'notice_id') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'document_id') and getattr(self, + 'document_id') is not None: + _dict['document_id'] = getattr(self, 'document_id') + if hasattr(self, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') + if hasattr(self, 'query_id') and getattr(self, 'query_id') is not None: + _dict['query_id'] = getattr(self, 'query_id') + if hasattr(self, 'severity') and getattr(self, 'severity') is not None: + _dict['severity'] = getattr(self, 'severity') + if hasattr(self, 'step') and getattr(self, 'step') is not None: + _dict['step'] = getattr(self, 'step') + if hasattr(self, 'description') and getattr(self, + 'description') is not None: + _dict['description'] = getattr(self, 'description') return _dict def _to_dict(self): @@ -4139,7 +4051,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this Notice object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'Notice') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4151,12 +4063,12 @@ def __ne__(self, other: 'Notice') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class SeverityEnum(Enum): + class SeverityEnum(str, Enum): """ Severity level of the notice. """ - WARNING = "warning" - ERROR = "error" + WARNING = 'warning' + ERROR = 'error' class ProjectDetails(): @@ -4186,13 +4098,10 @@ def __init__(self, """ Initialize a ProjectDetails object. - :param str project_id: (optional) The unique identifier of this project. :param str name: (optional) The human readable name of this project. :param str type: (optional) The project type of this project. :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. - :param int collection_count: (optional) The number of collections - configured in this project. :param DefaultQueryParams default_query_parameters: (optional) Default query parameters for this project. """ @@ -4207,15 +4116,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProjectDetails': """Initialize a ProjectDetails object from a json dictionary.""" args = {} - valid_keys = [ - 'project_id', 'name', 'type', 'relevancy_training_status', - 'collection_count', 'default_query_parameters' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ProjectDetails: ' - + ', '.join(bad_keys)) if 'project_id' in _dict: args['project_id'] = _dict.get('project_id') if 'name' in _dict: @@ -4224,12 +4124,12 @@ def from_dict(cls, _dict: Dict) -> 'ProjectDetails': args['type'] = _dict.get('type') if 'relevancy_training_status' in _dict: args[ - 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus._from_dict( + 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus.from_dict( _dict.get('relevancy_training_status')) if 'collection_count' in _dict: args['collection_count'] = _dict.get('collection_count') if 'default_query_parameters' in _dict: - args['default_query_parameters'] = DefaultQueryParams._from_dict( + args['default_query_parameters'] = DefaultQueryParams.from_dict( _dict.get('default_query_parameters')) return cls(**args) @@ -4241,8 +4141,9 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'project_id') and self.project_id is not None: - _dict['project_id'] = self.project_id + if hasattr(self, 'project_id') and getattr(self, + 'project_id') is not None: + _dict['project_id'] = getattr(self, 'project_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'type') and self.type is not None: @@ -4250,15 +4151,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'relevancy_training_status' ) and self.relevancy_training_status is not None: _dict[ - 'relevancy_training_status'] = self.relevancy_training_status._to_dict( + 'relevancy_training_status'] = self.relevancy_training_status.to_dict( ) - if hasattr(self, - 'collection_count') and self.collection_count is not None: - _dict['collection_count'] = self.collection_count + if hasattr(self, 'collection_count') and getattr( + self, 'collection_count') is not None: + _dict['collection_count'] = getattr(self, 'collection_count') if hasattr(self, 'default_query_parameters' ) and self.default_query_parameters is not None: _dict[ - 'default_query_parameters'] = self.default_query_parameters._to_dict( + 'default_query_parameters'] = self.default_query_parameters.to_dict( ) return _dict @@ -4268,7 +4169,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ProjectDetails object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ProjectDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4280,14 +4181,14 @@ def __ne__(self, other: 'ProjectDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The project type of this project. """ - DOCUMENT_RETRIEVAL = "document_retrieval" - ANSWER_RETRIEVAL = "answer_retrieval" - CONTENT_MINING = "content_mining" - OTHER = "other" + DOCUMENT_RETRIEVAL = 'document_retrieval' + ANSWER_RETRIEVAL = 'answer_retrieval' + CONTENT_MINING = 'content_mining' + OTHER = 'other' class ProjectListDetails(): @@ -4314,13 +4215,10 @@ def __init__(self, """ Initialize a ProjectListDetails object. - :param str project_id: (optional) The unique identifier of this project. :param str name: (optional) The human readable name of this project. :param str type: (optional) The project type of this project. :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. - :param int collection_count: (optional) The number of collections - configured in this project. """ self.project_id = project_id self.name = name @@ -4332,15 +4230,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProjectListDetails': """Initialize a ProjectListDetails object from a json dictionary.""" args = {} - valid_keys = [ - 'project_id', 'name', 'type', 'relevancy_training_status', - 'collection_count' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ProjectListDetails: ' - + ', '.join(bad_keys)) if 'project_id' in _dict: args['project_id'] = _dict.get('project_id') if 'name' in _dict: @@ -4349,7 +4238,7 @@ def from_dict(cls, _dict: Dict) -> 'ProjectListDetails': args['type'] = _dict.get('type') if 'relevancy_training_status' in _dict: args[ - 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus._from_dict( + 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus.from_dict( _dict.get('relevancy_training_status')) if 'collection_count' in _dict: args['collection_count'] = _dict.get('collection_count') @@ -4363,8 +4252,9 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'project_id') and self.project_id is not None: - _dict['project_id'] = self.project_id + if hasattr(self, 'project_id') and getattr(self, + 'project_id') is not None: + _dict['project_id'] = getattr(self, 'project_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'type') and self.type is not None: @@ -4372,11 +4262,11 @@ def to_dict(self) -> Dict: if hasattr(self, 'relevancy_training_status' ) and self.relevancy_training_status is not None: _dict[ - 'relevancy_training_status'] = self.relevancy_training_status._to_dict( + 'relevancy_training_status'] = self.relevancy_training_status.to_dict( ) - if hasattr(self, - 'collection_count') and self.collection_count is not None: - _dict['collection_count'] = self.collection_count + if hasattr(self, 'collection_count') and getattr( + self, 'collection_count') is not None: + _dict['collection_count'] = getattr(self, 'collection_count') return _dict def _to_dict(self): @@ -4385,7 +4275,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ProjectListDetails object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ProjectListDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4397,14 +4287,14 @@ def __ne__(self, other: 'ProjectListDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(Enum): + class TypeEnum(str, Enum): """ The project type of this project. """ - DOCUMENT_RETRIEVAL = "document_retrieval" - ANSWER_RETRIEVAL = "answer_retrieval" - CONTENT_MINING = "content_mining" - OTHER = "other" + DOCUMENT_RETRIEVAL = 'document_retrieval' + ANSWER_RETRIEVAL = 'answer_retrieval' + CONTENT_MINING = 'content_mining' + OTHER = 'other' class ProjectListDetailsRelevancyTrainingStatus(): @@ -4475,16 +4365,6 @@ def from_dict(cls, _dict: Dict) -> 'ProjectListDetailsRelevancyTrainingStatus': """Initialize a ProjectListDetailsRelevancyTrainingStatus object from a json dictionary.""" args = {} - valid_keys = [ - 'data_updated', 'total_examples', 'sufficient_label_diversity', - 'processing', 'minimum_examples_added', 'successfully_trained', - 'available', 'notices', 'minimum_queries_added' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class ProjectListDetailsRelevancyTrainingStatus: ' - + ', '.join(bad_keys)) if 'data_updated' in _dict: args['data_updated'] = _dict.get('data_updated') if 'total_examples' in _dict: @@ -4545,7 +4425,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this ProjectListDetailsRelevancyTrainingStatus object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'ProjectListDetailsRelevancyTrainingStatus') -> bool: @@ -4586,12 +4466,6 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregation': if disc_class != cls: return disc_class.from_dict(_dict) args = {} - valid_keys = ['type'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryAggregation: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') else: @@ -4618,7 +4492,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4713,15 +4587,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregationResult': """Initialize a QueryGroupByAggregationResult object from a json dictionary.""" args = {} - valid_keys = [ - 'key', 'matching_results', 'relevancy', 'total_matching_documents', - 'estimated_matching_documents', 'aggregations' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryGroupByAggregationResult: ' - + ', '.join(bad_keys)) if 'key' in _dict: args['key'] = _dict.get('key') else: @@ -4744,8 +4609,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregationResult': 'estimated_matching_documents') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] return cls(**args) @@ -4772,7 +4636,7 @@ def to_dict(self) -> Dict: _dict[ 'estimated_matching_documents'] = self.estimated_matching_documents if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -4781,7 +4645,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryGroupByAggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryGroupByAggregationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4827,12 +4691,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" args = {} - valid_keys = ['key', 'matching_results', 'aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryHistogramAggregationResult: ' - + ', '.join(bad_keys)) if 'key' in _dict: args['key'] = _dict.get('key') else: @@ -4847,8 +4705,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] return cls(**args) @@ -4866,7 +4723,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -4875,7 +4732,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryHistogramAggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryHistogramAggregationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -4944,15 +4801,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryLargePassages': """Initialize a QueryLargePassages object from a json dictionary.""" args = {} - valid_keys = [ - 'enabled', 'per_document', 'max_per_document', 'fields', 'count', - 'characters' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryLargePassages: ' - + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'per_document' in _dict: @@ -4996,7 +4844,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryLargePassages object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryLargePassages') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5033,12 +4881,6 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryLargeSuggestedRefinements': """Initialize a QueryLargeSuggestedRefinements object from a json dictionary.""" args = {} - valid_keys = ['enabled', 'count'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryLargeSuggestedRefinements: ' - + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'count' in _dict: @@ -5065,7 +4907,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryLargeSuggestedRefinements object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryLargeSuggestedRefinements') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5100,12 +4942,6 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryLargeTableResults': """Initialize a QueryLargeTableResults object from a json dictionary.""" args = {} - valid_keys = ['enabled', 'count'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryLargeTableResults: ' - + ', '.join(bad_keys)) if 'enabled' in _dict: args['enabled'] = _dict.get('enabled') if 'count' in _dict: @@ -5132,7 +4968,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryLargeTableResults object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryLargeTableResults') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5172,17 +5008,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} - valid_keys = ['matching_results', 'notices'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryNoticesResponse: ' - + ', '.join(bad_keys)) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'notices' in _dict: args['notices'] = [ - Notice._from_dict(x) for x in (_dict.get('notices')) + Notice.from_dict(x) for x in _dict.get('notices') ] return cls(**args) @@ -5198,7 +5028,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x._to_dict() for x in self.notices] + _dict['notices'] = [x.to_dict() for x in self.notices] return _dict def _to_dict(self): @@ -5207,7 +5037,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryNoticesResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryNoticesResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5284,46 +5114,34 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResponse': """Initialize a QueryResponse object from a json dictionary.""" args = {} - valid_keys = [ - 'matching_results', 'results', 'aggregations', 'retrieval_details', - 'suggested_query', 'suggested_refinements', 'table_results', - 'passages' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryResponse: ' - + ', '.join(bad_keys)) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - QueryResult._from_dict(x) for x in (_dict.get('results')) + QueryResult.from_dict(x) for x in _dict.get('results') ] if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] if 'retrieval_details' in _dict: - args['retrieval_details'] = RetrievalDetails._from_dict( + args['retrieval_details'] = RetrievalDetails.from_dict( _dict.get('retrieval_details')) if 'suggested_query' in _dict: args['suggested_query'] = _dict.get('suggested_query') if 'suggested_refinements' in _dict: args['suggested_refinements'] = [ - QuerySuggestedRefinement._from_dict(x) - for x in (_dict.get('suggested_refinements')) + QuerySuggestedRefinement.from_dict(x) + for x in _dict.get('suggested_refinements') ] if 'table_results' in _dict: args['table_results'] = [ - QueryTableResult._from_dict(x) - for x in (_dict.get('table_results')) + QueryTableResult.from_dict(x) + for x in _dict.get('table_results') ] if 'passages' in _dict: args['passages'] = [ - QueryResponsePassage._from_dict(x) - for x in (_dict.get('passages')) + QueryResponsePassage.from_dict(x) for x in _dict.get('passages') ] return cls(**args) @@ -5339,24 +5157,24 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'retrieval_details') and self.retrieval_details is not None: - _dict['retrieval_details'] = self.retrieval_details._to_dict() + _dict['retrieval_details'] = self.retrieval_details.to_dict() if hasattr(self, 'suggested_query') and self.suggested_query is not None: _dict['suggested_query'] = self.suggested_query if hasattr(self, 'suggested_refinements' ) and self.suggested_refinements is not None: _dict['suggested_refinements'] = [ - x._to_dict() for x in self.suggested_refinements + x.to_dict() for x in self.suggested_refinements ] if hasattr(self, 'table_results') and self.table_results is not None: - _dict['table_results'] = [x._to_dict() for x in self.table_results] + _dict['table_results'] = [x.to_dict() for x in self.table_results] if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x._to_dict() for x in self.passages] + _dict['passages'] = [x.to_dict() for x in self.passages] return _dict def _to_dict(self): @@ -5365,7 +5183,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryResponse object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryResponse') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5434,15 +5252,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResponsePassage': """Initialize a QueryResponsePassage object from a json dictionary.""" args = {} - valid_keys = [ - 'passage_text', 'passage_score', 'document_id', 'collection_id', - 'start_offset', 'end_offset', 'field' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryResponsePassage: ' - + ', '.join(bad_keys)) if 'passage_text' in _dict: args['passage_text'] = _dict.get('passage_text') if 'passage_score' in _dict: @@ -5489,7 +5298,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryResponsePassage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryResponsePassage') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5513,6 +5322,10 @@ class QueryResult(): by Discovery. """ + # The set of defined properties for the class + _properties = frozenset( + ['document_id', 'metadata', 'result_metadata', 'document_passages']) + def __init__(self, document_id: str, result_metadata: 'QueryResultMetadata', @@ -5541,32 +5354,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResult': """Initialize a QueryResult object from a json dictionary.""" args = {} - xtra = _dict.copy() if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') - del xtra['document_id'] else: raise ValueError( 'Required property \'document_id\' not present in QueryResult JSON' ) if 'metadata' in _dict: args['metadata'] = _dict.get('metadata') - del xtra['metadata'] if 'result_metadata' in _dict: - args['result_metadata'] = QueryResultMetadata._from_dict( + args['result_metadata'] = QueryResultMetadata.from_dict( _dict.get('result_metadata')) - del xtra['result_metadata'] else: raise ValueError( 'Required property \'result_metadata\' not present in QueryResult JSON' ) if 'document_passages' in _dict: args['document_passages'] = [ - QueryResultPassage._from_dict(x) - for x in (_dict.get('document_passages')) + QueryResultPassage.from_dict(x) + for x in _dict.get('document_passages') ] - del xtra['document_passages'] - args.update(xtra) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -5583,36 +5392,26 @@ def to_dict(self) -> Dict: _dict['metadata'] = self.metadata if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata._to_dict() + _dict['result_metadata'] = self.result_metadata.to_dict() if hasattr(self, 'document_passages') and self.document_passages is not None: _dict['document_passages'] = [ - x._to_dict() for x in self.document_passages + x.to_dict() for x in self.document_passages ] - if hasattr(self, '_additionalProperties'): - for _key in self._additionalProperties: - _value = getattr(self, _key, None) - if _value is not None: - _dict[_key] = _value + for _key in [ + k for k in vars(self).keys() if k not in QueryResult._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def __setattr__(self, name: str, value: object) -> None: - properties = { - 'document_id', 'metadata', 'result_metadata', 'document_passages' - } - if not hasattr(self, '_additionalProperties'): - super(QueryResult, self).__setattr__('_additionalProperties', set()) - if name not in properties: - self._additionalProperties.add(name) - super(QueryResult, self).__setattr__(name, value) - def __str__(self) -> str: """Return a `str` version of this QueryResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5670,14 +5469,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} - valid_keys = [ - 'document_retrieval_source', 'collection_id', 'confidence' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryResultMetadata: ' - + ', '.join(bad_keys)) if 'document_retrieval_source' in _dict: args['document_retrieval_source'] = _dict.get( 'document_retrieval_source') @@ -5714,7 +5505,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryResultMetadata object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryResultMetadata') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5726,12 +5517,12 @@ def __ne__(self, other: 'QueryResultMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class DocumentRetrievalSourceEnum(Enum): + class DocumentRetrievalSourceEnum(str, Enum): """ The document retrieval source that produced this search result. """ - SEARCH = "search" - CURATION = "curation" + SEARCH = 'search' + CURATION = 'curation' class QueryResultPassage(): @@ -5773,12 +5564,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResultPassage': """Initialize a QueryResultPassage object from a json dictionary.""" args = {} - valid_keys = ['passage_text', 'start_offset', 'end_offset', 'field'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryResultPassage: ' - + ', '.join(bad_keys)) if 'passage_text' in _dict: args['passage_text'] = _dict.get('passage_text') if 'start_offset' in _dict: @@ -5813,7 +5598,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryResultPassage object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryResultPassage') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5845,12 +5630,6 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'QuerySuggestedRefinement': """Initialize a QuerySuggestedRefinement object from a json dictionary.""" args = {} - valid_keys = ['text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QuerySuggestedRefinement: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -5873,7 +5652,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QuerySuggestedRefinement object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QuerySuggestedRefinement') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -5935,15 +5714,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTableResult': """Initialize a QueryTableResult object from a json dictionary.""" args = {} - valid_keys = [ - 'table_id', 'source_document_id', 'collection_id', 'table_html', - 'table_html_offset', 'table' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTableResult: ' - + ', '.join(bad_keys)) if 'table_id' in _dict: args['table_id'] = _dict.get('table_id') if 'source_document_id' in _dict: @@ -5955,7 +5725,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTableResult': if 'table_html_offset' in _dict: args['table_html_offset'] = _dict.get('table_html_offset') if 'table' in _dict: - args['table'] = TableResultTable._from_dict(_dict.get('table')) + args['table'] = TableResultTable.from_dict(_dict.get('table')) return cls(**args) @classmethod @@ -5980,7 +5750,7 @@ def to_dict(self) -> Dict: 'table_html_offset') and self.table_html_offset is not None: _dict['table_html_offset'] = self.table_html_offset if hasattr(self, 'table') and self.table is not None: - _dict['table'] = self.table._to_dict() + _dict['table'] = self.table.to_dict() return _dict def _to_dict(self): @@ -5989,7 +5759,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryTableResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryTableResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6055,15 +5825,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': """Initialize a QueryTermAggregationResult object from a json dictionary.""" args = {} - valid_keys = [ - 'key', 'matching_results', 'relevancy', 'total_matching_documents', - 'estimated_matching_documents', 'aggregations' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTermAggregationResult: ' - + ', '.join(bad_keys)) if 'key' in _dict: args['key'] = _dict.get('key') else: @@ -6086,8 +5847,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': 'estimated_matching_documents') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] return cls(**args) @@ -6114,7 +5874,7 @@ def to_dict(self) -> Dict: _dict[ 'estimated_matching_documents'] = self.estimated_matching_documents if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -6123,7 +5883,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryTermAggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryTermAggregationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6177,14 +5937,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" args = {} - valid_keys = [ - 'key_as_string', 'key', 'matching_results', 'aggregations' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTimesliceAggregationResult: ' - + ', '.join(bad_keys)) if 'key_as_string' in _dict: args['key_as_string'] = _dict.get('key_as_string') else: @@ -6205,8 +5957,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] return cls(**args) @@ -6226,7 +5977,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -6235,7 +5986,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryTimesliceAggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryTimesliceAggregationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6273,12 +6024,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" args = {} - valid_keys = ['matching_results', 'hits'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTopHitsAggregationResult: ' - + ', '.join(bad_keys)) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') else: @@ -6310,7 +6055,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryTopHitsAggregationResult object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryTopHitsAggregationResult') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6352,12 +6097,6 @@ def __init__(self, *, document_retrieval_strategy: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': """Initialize a RetrievalDetails object from a json dictionary.""" args = {} - valid_keys = ['document_retrieval_strategy'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class RetrievalDetails: ' - + ', '.join(bad_keys)) if 'document_retrieval_strategy' in _dict: args['document_retrieval_strategy'] = _dict.get( 'document_retrieval_strategy') @@ -6383,7 +6122,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this RetrievalDetails object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'RetrievalDetails') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6395,7 +6134,7 @@ def __ne__(self, other: 'RetrievalDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class DocumentRetrievalStrategyEnum(Enum): + class DocumentRetrievalStrategyEnum(str, Enum): """ Identifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy @@ -6404,8 +6143,8 @@ class DocumentRetrievalStrategyEnum(Enum): model is not used to return results, the **document_retrieval_strategy** will be listed as `untrained`. """ - UNTRAINED = "untrained" - RELEVANCY_TRAINING = "relevancy_training" + UNTRAINED = 'untrained' + RELEVANCY_TRAINING = 'relevancy_training' class TableBodyCells(): @@ -6513,22 +6252,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableBodyCells': """Initialize a TableBodyCells object from a json dictionary.""" args = {} - valid_keys = [ - 'cell_id', 'location', 'text', 'row_index_begin', 'row_index_end', - 'column_index_begin', 'column_index_end', 'row_header_ids', - 'row_header_texts', 'row_header_texts_normalized', - 'column_header_ids', 'column_header_texts', - 'column_header_texts_normalized', 'attributes' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableBodyCells: ' - + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: - args['location'] = TableElementLocation._from_dict( + args['location'] = TableElementLocation.from_dict( _dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') @@ -6542,38 +6269,37 @@ def from_dict(cls, _dict: Dict) -> 'TableBodyCells': args['column_index_end'] = _dict.get('column_index_end') if 'row_header_ids' in _dict: args['row_header_ids'] = [ - TableRowHeaderIds._from_dict(x) - for x in (_dict.get('row_header_ids')) + TableRowHeaderIds.from_dict(x) + for x in _dict.get('row_header_ids') ] if 'row_header_texts' in _dict: args['row_header_texts'] = [ - TableRowHeaderTexts._from_dict(x) - for x in (_dict.get('row_header_texts')) + TableRowHeaderTexts.from_dict(x) + for x in _dict.get('row_header_texts') ] if 'row_header_texts_normalized' in _dict: args['row_header_texts_normalized'] = [ - TableRowHeaderTextsNormalized._from_dict(x) - for x in (_dict.get('row_header_texts_normalized')) + TableRowHeaderTextsNormalized.from_dict(x) + for x in _dict.get('row_header_texts_normalized') ] if 'column_header_ids' in _dict: args['column_header_ids'] = [ - TableColumnHeaderIds._from_dict(x) - for x in (_dict.get('column_header_ids')) + TableColumnHeaderIds.from_dict(x) + for x in _dict.get('column_header_ids') ] if 'column_header_texts' in _dict: args['column_header_texts'] = [ - TableColumnHeaderTexts._from_dict(x) - for x in (_dict.get('column_header_texts')) + TableColumnHeaderTexts.from_dict(x) + for x in _dict.get('column_header_texts') ] if 'column_header_texts_normalized' in _dict: args['column_header_texts_normalized'] = [ - TableColumnHeaderTextsNormalized._from_dict(x) - for x in (_dict.get('column_header_texts_normalized')) + TableColumnHeaderTextsNormalized.from_dict(x) + for x in _dict.get('column_header_texts_normalized') ] if 'attributes' in _dict: args['attributes'] = [ - DocumentAttribute._from_dict(x) - for x in (_dict.get('attributes')) + DocumentAttribute.from_dict(x) for x in _dict.get('attributes') ] return cls(**args) @@ -6588,7 +6314,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -6604,37 +6330,35 @@ def to_dict(self) -> Dict: 'column_index_end') and self.column_index_end is not None: _dict['column_index_end'] = self.column_index_end if hasattr(self, 'row_header_ids') and self.row_header_ids is not None: - _dict['row_header_ids'] = [ - x._to_dict() for x in self.row_header_ids - ] + _dict['row_header_ids'] = [x.to_dict() for x in self.row_header_ids] if hasattr(self, 'row_header_texts') and self.row_header_texts is not None: _dict['row_header_texts'] = [ - x._to_dict() for x in self.row_header_texts + x.to_dict() for x in self.row_header_texts ] if hasattr(self, 'row_header_texts_normalized' ) and self.row_header_texts_normalized is not None: _dict['row_header_texts_normalized'] = [ - x._to_dict() for x in self.row_header_texts_normalized + x.to_dict() for x in self.row_header_texts_normalized ] if hasattr(self, 'column_header_ids') and self.column_header_ids is not None: _dict['column_header_ids'] = [ - x._to_dict() for x in self.column_header_ids + x.to_dict() for x in self.column_header_ids ] if hasattr( self, 'column_header_texts') and self.column_header_texts is not None: _dict['column_header_texts'] = [ - x._to_dict() for x in self.column_header_texts + x.to_dict() for x in self.column_header_texts ] if hasattr(self, 'column_header_texts_normalized' ) and self.column_header_texts_normalized is not None: _dict['column_header_texts_normalized'] = [ - x._to_dict() for x in self.column_header_texts_normalized + x.to_dict() for x in self.column_header_texts_normalized ] if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x._to_dict() for x in self.attributes] + _dict['attributes'] = [x.to_dict() for x in self.attributes] return _dict def _to_dict(self): @@ -6643,7 +6367,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableBodyCells object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableBodyCells') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6691,16 +6415,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableCellKey': """Initialize a TableCellKey object from a json dictionary.""" args = {} - valid_keys = ['cell_id', 'location', 'text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableCellKey: ' - + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: - args['location'] = TableElementLocation._from_dict( + args['location'] = TableElementLocation.from_dict( _dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') @@ -6717,7 +6435,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict @@ -6728,7 +6446,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableCellKey object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableCellKey') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6776,16 +6494,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableCellValues': """Initialize a TableCellValues object from a json dictionary.""" args = {} - valid_keys = ['cell_id', 'location', 'text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableCellValues: ' - + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: - args['location'] = TableElementLocation._from_dict( + args['location'] = TableElementLocation.from_dict( _dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') @@ -6802,7 +6514,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict @@ -6813,7 +6525,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableCellValues object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableCellValues') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6846,12 +6558,6 @@ def __init__(self, *, id: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderIds': """Initialize a TableColumnHeaderIds object from a json dictionary.""" args = {} - valid_keys = ['id'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableColumnHeaderIds: ' - + ', '.join(bad_keys)) if 'id' in _dict: args['id'] = _dict.get('id') return cls(**args) @@ -6874,7 +6580,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableColumnHeaderIds object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableColumnHeaderIds') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6907,12 +6613,6 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTexts': """Initialize a TableColumnHeaderTexts object from a json dictionary.""" args = {} - valid_keys = ['text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableColumnHeaderTexts: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -6935,7 +6635,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableColumnHeaderTexts object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableColumnHeaderTexts') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -6970,12 +6670,6 @@ def __init__(self, *, text_normalized: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTextsNormalized': """Initialize a TableColumnHeaderTextsNormalized object from a json dictionary.""" args = {} - valid_keys = ['text_normalized'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableColumnHeaderTextsNormalized: ' - + ', '.join(bad_keys)) if 'text_normalized' in _dict: args['text_normalized'] = _dict.get('text_normalized') return cls(**args) @@ -6999,7 +6693,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableColumnHeaderTextsNormalized object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableColumnHeaderTextsNormalized') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7081,15 +6775,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableColumnHeaders': """Initialize a TableColumnHeaders object from a json dictionary.""" args = {} - valid_keys = [ - 'cell_id', 'location', 'text', 'text_normalized', 'row_index_begin', - 'row_index_end', 'column_index_begin', 'column_index_end' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableColumnHeaders: ' - + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: @@ -7145,7 +6830,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableColumnHeaders object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableColumnHeaders') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7181,12 +6866,6 @@ def __init__(self, begin: int, end: int) -> None: def from_dict(cls, _dict: Dict) -> 'TableElementLocation': """Initialize a TableElementLocation object from a json dictionary.""" args = {} - valid_keys = ['begin', 'end'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableElementLocation: ' - + ', '.join(bad_keys)) if 'begin' in _dict: args['begin'] = _dict.get('begin') else: @@ -7221,7 +6900,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableElementLocation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableElementLocation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7294,15 +6973,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableHeaders': """Initialize a TableHeaders object from a json dictionary.""" args = {} - valid_keys = [ - 'cell_id', 'location', 'text', 'row_index_begin', 'row_index_end', - 'column_index_begin', 'column_index_end' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableHeaders: ' - + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: @@ -7353,7 +7023,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableHeaders object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableHeaders') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7393,17 +7063,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableKeyValuePairs': """Initialize a TableKeyValuePairs object from a json dictionary.""" args = {} - valid_keys = ['key', 'value'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableKeyValuePairs: ' - + ', '.join(bad_keys)) if 'key' in _dict: - args['key'] = TableCellKey._from_dict(_dict.get('key')) + args['key'] = TableCellKey.from_dict(_dict.get('key')) if 'value' in _dict: args['value'] = [ - TableCellValues._from_dict(x) for x in (_dict.get('value')) + TableCellValues.from_dict(x) for x in _dict.get('value') ] return cls(**args) @@ -7416,9 +7080,9 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key._to_dict() + _dict['key'] = self.key.to_dict() if hasattr(self, 'value') and self.value is not None: - _dict['value'] = [x._to_dict() for x in self.value] + _dict['value'] = [x.to_dict() for x in self.value] return _dict def _to_dict(self): @@ -7427,7 +7091,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableKeyValuePairs object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableKeyValuePairs') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7526,52 +7190,41 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableResultTable': """Initialize a TableResultTable object from a json dictionary.""" args = {} - valid_keys = [ - 'location', 'text', 'section_title', 'title', 'table_headers', - 'row_headers', 'column_headers', 'key_value_pairs', 'body_cells', - 'contexts' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableResultTable: ' - + ', '.join(bad_keys)) if 'location' in _dict: - args['location'] = TableElementLocation._from_dict( + args['location'] = TableElementLocation.from_dict( _dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') if 'section_title' in _dict: - args['section_title'] = TableTextLocation._from_dict( + args['section_title'] = TableTextLocation.from_dict( _dict.get('section_title')) if 'title' in _dict: - args['title'] = TableTextLocation._from_dict(_dict.get('title')) + args['title'] = TableTextLocation.from_dict(_dict.get('title')) if 'table_headers' in _dict: args['table_headers'] = [ - TableHeaders._from_dict(x) for x in (_dict.get('table_headers')) + TableHeaders.from_dict(x) for x in _dict.get('table_headers') ] if 'row_headers' in _dict: args['row_headers'] = [ - TableRowHeaders._from_dict(x) - for x in (_dict.get('row_headers')) + TableRowHeaders.from_dict(x) for x in _dict.get('row_headers') ] if 'column_headers' in _dict: args['column_headers'] = [ - TableColumnHeaders._from_dict(x) - for x in (_dict.get('column_headers')) + TableColumnHeaders.from_dict(x) + for x in _dict.get('column_headers') ] if 'key_value_pairs' in _dict: args['key_value_pairs'] = [ - TableKeyValuePairs._from_dict(x) - for x in (_dict.get('key_value_pairs')) + TableKeyValuePairs.from_dict(x) + for x in _dict.get('key_value_pairs') ] if 'body_cells' in _dict: args['body_cells'] = [ - TableBodyCells._from_dict(x) for x in (_dict.get('body_cells')) + TableBodyCells.from_dict(x) for x in _dict.get('body_cells') ] if 'contexts' in _dict: args['contexts'] = [ - TableTextLocation._from_dict(x) for x in (_dict.get('contexts')) + TableTextLocation.from_dict(x) for x in _dict.get('contexts') ] return cls(**args) @@ -7584,30 +7237,28 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'section_title') and self.section_title is not None: - _dict['section_title'] = self.section_title._to_dict() + _dict['section_title'] = self.section_title.to_dict() if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title._to_dict() + _dict['title'] = self.title.to_dict() if hasattr(self, 'table_headers') and self.table_headers is not None: - _dict['table_headers'] = [x._to_dict() for x in self.table_headers] + _dict['table_headers'] = [x.to_dict() for x in self.table_headers] if hasattr(self, 'row_headers') and self.row_headers is not None: - _dict['row_headers'] = [x._to_dict() for x in self.row_headers] + _dict['row_headers'] = [x.to_dict() for x in self.row_headers] if hasattr(self, 'column_headers') and self.column_headers is not None: - _dict['column_headers'] = [ - x._to_dict() for x in self.column_headers - ] + _dict['column_headers'] = [x.to_dict() for x in self.column_headers] if hasattr(self, 'key_value_pairs') and self.key_value_pairs is not None: _dict['key_value_pairs'] = [ - x._to_dict() for x in self.key_value_pairs + x.to_dict() for x in self.key_value_pairs ] if hasattr(self, 'body_cells') and self.body_cells is not None: - _dict['body_cells'] = [x._to_dict() for x in self.body_cells] + _dict['body_cells'] = [x.to_dict() for x in self.body_cells] if hasattr(self, 'contexts') and self.contexts is not None: - _dict['contexts'] = [x._to_dict() for x in self.contexts] + _dict['contexts'] = [x.to_dict() for x in self.contexts] return _dict def _to_dict(self): @@ -7616,7 +7267,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableResultTable object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableResultTable') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7649,12 +7300,6 @@ def __init__(self, *, id: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableRowHeaderIds': """Initialize a TableRowHeaderIds object from a json dictionary.""" args = {} - valid_keys = ['id'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableRowHeaderIds: ' - + ', '.join(bad_keys)) if 'id' in _dict: args['id'] = _dict.get('id') return cls(**args) @@ -7677,7 +7322,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableRowHeaderIds object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableRowHeaderIds') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7710,12 +7355,6 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTexts': """Initialize a TableRowHeaderTexts object from a json dictionary.""" args = {} - valid_keys = ['text'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableRowHeaderTexts: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') return cls(**args) @@ -7738,7 +7377,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableRowHeaderTexts object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableRowHeaderTexts') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7773,12 +7412,6 @@ def __init__(self, *, text_normalized: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTextsNormalized': """Initialize a TableRowHeaderTextsNormalized object from a json dictionary.""" args = {} - valid_keys = ['text_normalized'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableRowHeaderTextsNormalized: ' - + ', '.join(bad_keys)) if 'text_normalized' in _dict: args['text_normalized'] = _dict.get('text_normalized') return cls(**args) @@ -7802,7 +7435,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableRowHeaderTextsNormalized object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableRowHeaderTextsNormalized') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7884,19 +7517,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableRowHeaders': """Initialize a TableRowHeaders object from a json dictionary.""" args = {} - valid_keys = [ - 'cell_id', 'location', 'text', 'text_normalized', 'row_index_begin', - 'row_index_end', 'column_index_begin', 'column_index_end' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableRowHeaders: ' - + ', '.join(bad_keys)) if 'cell_id' in _dict: args['cell_id'] = _dict.get('cell_id') if 'location' in _dict: - args['location'] = TableElementLocation._from_dict( + args['location'] = TableElementLocation.from_dict( _dict.get('location')) if 'text' in _dict: args['text'] = _dict.get('text') @@ -7923,7 +7547,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -7949,7 +7573,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableRowHeaders object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableRowHeaders') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -7991,16 +7615,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableTextLocation': """Initialize a TableTextLocation object from a json dictionary.""" args = {} - valid_keys = ['text', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TableTextLocation: ' - + ', '.join(bad_keys)) if 'text' in _dict: args['text'] = _dict.get('text') if 'location' in _dict: - args['location'] = TableElementLocation._from_dict( + args['location'] = TableElementLocation.from_dict( _dict.get('location')) return cls(**args) @@ -8015,7 +7633,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -8024,7 +7642,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TableTextLocation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TableTextLocation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8064,10 +7682,6 @@ def __init__(self, :param str collection_id: The collection ID associated with this training example. :param int relevance: The relevance of the training example. - :param datetime created: (optional) The date and time the example was - created. - :param datetime updated: (optional) The date and time the example was - updated. """ self.document_id = document_id self.collection_id = collection_id @@ -8079,14 +7693,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingExample': """Initialize a TrainingExample object from a json dictionary.""" args = {} - valid_keys = [ - 'document_id', 'collection_id', 'relevance', 'created', 'updated' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingExample: ' - + ', '.join(bad_keys)) if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') else: @@ -8125,10 +7731,10 @@ def to_dict(self) -> Dict: _dict['collection_id'] = self.collection_id if hasattr(self, 'relevance') and self.relevance is not None: _dict['relevance'] = self.relevance - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) return _dict def _to_dict(self): @@ -8137,7 +7743,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingExample object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingExample') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8177,14 +7783,8 @@ def __init__(self, :param str natural_language_query: The natural text query for the training query. :param List[TrainingExample] examples: Array of training examples. - :param str query_id: (optional) The query ID associated with the training - query. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :param datetime created: (optional) The date and time the query was - created. - :param datetime updated: (optional) The date and time the query was - updated. """ self.query_id = query_id self.natural_language_query = natural_language_query @@ -8197,15 +7797,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingQuery': """Initialize a TrainingQuery object from a json dictionary.""" args = {} - valid_keys = [ - 'query_id', 'natural_language_query', 'filter', 'created', - 'updated', 'examples' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingQuery: ' - + ', '.join(bad_keys)) if 'query_id' in _dict: args['query_id'] = _dict.get('query_id') if 'natural_language_query' in _dict: @@ -8222,7 +7813,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingQuery': args['updated'] = string_to_datetime(_dict.get('updated')) if 'examples' in _dict: args['examples'] = [ - TrainingExample._from_dict(x) for x in (_dict.get('examples')) + TrainingExample.from_dict(x) for x in _dict.get('examples') ] else: raise ValueError( @@ -8238,19 +7829,19 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'query_id') and self.query_id is not None: - _dict['query_id'] = self.query_id + if hasattr(self, 'query_id') and getattr(self, 'query_id') is not None: + _dict['query_id'] = getattr(self, 'query_id') if hasattr(self, 'natural_language_query' ) and self.natural_language_query is not None: _dict['natural_language_query'] = self.natural_language_query if hasattr(self, 'filter') and self.filter is not None: _dict['filter'] = self.filter - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x._to_dict() for x in self.examples] + _dict['examples'] = [x.to_dict() for x in self.examples] return _dict def _to_dict(self): @@ -8259,7 +7850,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingQuery object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingQuery') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8291,15 +7882,9 @@ def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingQuerySet': """Initialize a TrainingQuerySet object from a json dictionary.""" args = {} - valid_keys = ['queries'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class TrainingQuerySet: ' - + ', '.join(bad_keys)) if 'queries' in _dict: args['queries'] = [ - TrainingQuery._from_dict(x) for x in (_dict.get('queries')) + TrainingQuery.from_dict(x) for x in _dict.get('queries') ] return cls(**args) @@ -8312,7 +7897,7 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'queries') and self.queries is not None: - _dict['queries'] = [x._to_dict() for x in self.queries] + _dict['queries'] = [x.to_dict() for x in self.queries] return _dict def _to_dict(self): @@ -8321,7 +7906,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this TrainingQuerySet object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'TrainingQuerySet') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8361,12 +7946,6 @@ def __init__(self, type: str, field: str, *, value: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': """Initialize a QueryCalculationAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'field', 'value'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryCalculationAggregation: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') else: @@ -8405,7 +7984,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryCalculationAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryCalculationAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8456,12 +8035,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': """Initialize a QueryFilterAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'match', 'matching_results', 'aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryFilterAggregation: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') else: @@ -8482,8 +8055,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] return cls(**args) @@ -8503,7 +8075,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -8512,7 +8084,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryFilterAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryFilterAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8553,12 +8125,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregation': """Initialize a QueryGroupByAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryGroupByAggregation: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') else: @@ -8567,8 +8133,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregation': ) if 'results' in _dict: args['results'] = [ - QueryGroupByAggregationResult._from_dict(x) - for x in (_dict.get('results')) + QueryGroupByAggregationResult.from_dict(x) + for x in _dict.get('results') ] return cls(**args) @@ -8583,7 +8149,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] return _dict def _to_dict(self): @@ -8592,7 +8158,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryGroupByAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryGroupByAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8649,12 +8215,6 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': """Initialize a QueryHistogramAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'field', 'interval', 'name', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryHistogramAggregation: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') else: @@ -8677,8 +8237,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryHistogramAggregationResult._from_dict(x) - for x in (_dict.get('results')) + QueryHistogramAggregationResult.from_dict(x) + for x in _dict.get('results') ] return cls(**args) @@ -8699,7 +8259,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] return _dict def _to_dict(self): @@ -8708,7 +8268,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryHistogramAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryHistogramAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8761,12 +8321,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': """Initialize a QueryNestedAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'path', 'matching_results', 'aggregations'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryNestedAggregation: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') else: @@ -8787,8 +8341,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation._from_dict(x) - for x in (_dict.get('aggregations')) + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] return cls(**args) @@ -8808,7 +8361,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x._to_dict() for x in self.aggregations] + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -8817,7 +8370,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryNestedAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryNestedAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8873,12 +8426,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': """Initialize a QueryTermAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'field', 'count', 'name', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTermAggregation: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') else: @@ -8897,8 +8444,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryTermAggregationResult._from_dict(x) - for x in (_dict.get('results')) + QueryTermAggregationResult.from_dict(x) + for x in _dict.get('results') ] return cls(**args) @@ -8919,7 +8466,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] return _dict def _to_dict(self): @@ -8928,7 +8475,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryTermAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryTermAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -8986,12 +8533,6 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': """Initialize a QueryTimesliceAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'field', 'interval', 'name', 'results'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTimesliceAggregation: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') else: @@ -9014,8 +8555,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryTimesliceAggregationResult._from_dict(x) - for x in (_dict.get('results')) + QueryTimesliceAggregationResult.from_dict(x) + for x in _dict.get('results') ] return cls(**args) @@ -9036,7 +8577,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x._to_dict() for x in self.results] + _dict['results'] = [x.to_dict() for x in self.results] return _dict def _to_dict(self): @@ -9045,7 +8586,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryTimesliceAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryTimesliceAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" @@ -9094,12 +8635,6 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': """Initialize a QueryTopHitsAggregation object from a json dictionary.""" args = {} - valid_keys = ['type', 'size', 'name', 'hits'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class QueryTopHitsAggregation: ' - + ', '.join(bad_keys)) if 'type' in _dict: args['type'] = _dict.get('type') else: @@ -9115,7 +8650,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': if 'name' in _dict: args['name'] = _dict.get('name') if 'hits' in _dict: - args['hits'] = QueryTopHitsAggregationResult._from_dict( + args['hits'] = QueryTopHitsAggregationResult.from_dict( _dict.get('hits')) return cls(**args) @@ -9134,7 +8669,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits._to_dict() + _dict['hits'] = self.hits.to_dict() return _dict def _to_dict(self): @@ -9143,7 +8678,7 @@ def _to_dict(self): def __str__(self) -> str: """Return a `str` version of this QueryTopHitsAggregation object.""" - return json.dumps(self._to_dict(), indent=2) + return json.dumps(self.to_dict(), indent=2) def __eq__(self, other: 'QueryTopHitsAggregation') -> bool: """Return `true` when self and other are equal, false otherwise.""" diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 01481f7cf..39261113f 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -83,6 +83,9 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + print( + 'warning: On 1 December 2021, Personality Insights will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#personality-insights-deprecation.' + ) if version is None: raise ValueError('version must be provided') diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 4a5358a45..cf371461c 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -65,6 +65,9 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + print( + 'warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#visual-recognition-deprecation.' + ) if version is None: raise ValueError('version must be provided') @@ -162,12 +165,12 @@ def classify(self, form_data.append( ('threshold', (None, str(threshold), 'text/plain'))) if owners: - for item in owners: - form_data.append(('owners', (None, item, 'text/plain'))) + owners = self._convert_list(owners) + form_data.append(('owners', (None, owners, 'text/plain'))) if classifier_ids: - for item in classifier_ids: - form_data.append(('classifier_ids', (None, item, 'text/plain'))) - + classifier_ids = self._convert_list(classifier_ids) + form_data.append( + ('classifier_ids', (None, classifier_ids, 'text/plain'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) headers['Accept'] = 'application/json' @@ -233,7 +236,6 @@ def create_classifier(self, :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Classifier` object """ - if name is None: raise ValueError('name must be provided') if not positive_examples: @@ -404,7 +406,6 @@ def update_classifier(self, :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Classifier` object """ - if classifier_id is None: raise ValueError('classifier_id must be provided') headers = {} diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index dc459dd54..f1dd4200d 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -64,6 +64,9 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + print( + 'warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#visual-recognition-deprecation.' + ) if version is None: raise ValueError('version must be provided') diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 48fd84728..a773e75f4 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -169,8 +169,7 @@ def test_create_collection_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 # Validate body params - print(responses.calls[0]) - req_body = json.loads(str(responses.calls[0].request.body)) + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' assert req_body['language'] == 'testString' @@ -343,7 +342,7 @@ def test_update_collection_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 # Validate body params - req_body = json.loads(str(responses.calls[0].request.body)) + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' assert req_body['enrichments'] == [collection_enrichment_model] @@ -553,7 +552,7 @@ def test_query_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 # Validate body params - req_body = json.loads(str(responses.calls[0].request.body)) + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['collection_ids'] == ['testString'] assert req_body['filter'] == 'testString' assert req_body['query'] == 'testString' @@ -1600,7 +1599,7 @@ def test_create_training_query_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 # Validate body params - req_body = json.loads(str(responses.calls[0].request.body)) + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['natural_language_query'] == 'testString' assert req_body['examples'] == [training_example_model] assert req_body['filter'] == 'testString' @@ -1774,7 +1773,7 @@ def test_update_training_query_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 # Validate body params - req_body = json.loads(str(responses.calls[0].request.body)) + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['natural_language_query'] == 'testString' assert req_body['examples'] == [training_example_model] assert req_body['filter'] == 'testString' @@ -2292,7 +2291,7 @@ def test_update_enrichment_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 # Validate body params - req_body = json.loads(str(responses.calls[0].request.body)) + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' @@ -2547,7 +2546,7 @@ def test_create_project_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 # Validate body params - req_body = json.loads(str(responses.calls[0].request.body)) + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['type'] == 'document_retrieval' assert req_body['default_query_parameters'] == default_query_params_model @@ -2730,7 +2729,7 @@ def test_update_project_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 # Validate body params - req_body = json.loads(str(responses.calls[0].request.body)) + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' From fc7dd856f7bfd7a9888bc6e346982ef40d7a869f Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 11 Dec 2020 20:38:01 +0000 Subject: [PATCH 295/455] =?UTF-8?q?Bump=20version:=204.7.1=20=E2=86=92=205?= =?UTF-8?q?.0.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 0f09a7752..3605e0b9e 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.7.1 +current_version = 5.0.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 3c9329b27..a0f66580c 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.7.1' +__version__ = '5.0.0' diff --git a/setup.py b/setup.py index 8f98d0019..8e538165a 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.7.1' +__version__ = '5.0.0' if sys.argv[-1] == 'publish': From 84213a9c0205a30d0d094c5aadbaab0efdda1e03 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Fri, 11 Dec 2020 20:38:01 +0000 Subject: [PATCH 296/455] chore(release): 5.0.0 release notes # [5.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.7.1...v5.0.0) (2020-12-11) ### Features * regenerate services using latest api def and generator ([59e7ded](https://github.com/watson-developer-cloud/python-sdk/commit/59e7dede81f530ea027b480fd007f9df67180ab1)) * regenerate using current api def and add deprecation warnings ([c3e1f07](https://github.com/watson-developer-cloud/python-sdk/commit/c3e1f07697b15d05f87cec39e36a9a2d28db7b91)) * regenerate with current API and add deprecation warnings ([4faa938](https://github.com/watson-developer-cloud/python-sdk/commit/4faa9380a606eeb8e8794b918b0f72313e4b1d86)) * regenrate language translator ([8fdebc4](https://github.com/watson-developer-cloud/python-sdk/commit/8fdebc45f0dfd1044d848969cb5cb3b8cb15a313)) * regenrate services using current api def and generator ([e84a0cb](https://github.com/watson-developer-cloud/python-sdk/commit/e84a0cb0636cd0add767903391de150bd65a4cd2)) * regenrate using current api def and generator 3.21 ([33e0d93](https://github.com/watson-developer-cloud/python-sdk/commit/33e0d9356ac43b7f988200c853b46b6cf4f703ab)) * **AssistantV1:** add support for bulkClassify ([e17b24c](https://github.com/watson-developer-cloud/python-sdk/commit/e17b24cc565bf6ee603497aeb5c11436ee09b0dc)) * **AssistantV2:** add support for bulkClassify ([8b14dda](https://github.com/watson-developer-cloud/python-sdk/commit/8b14dda82de980f09a031b1e15ab53573a5b55d8)) * **CompareComply:** remove before and after from list feedback ([5af17b7](https://github.com/watson-developer-cloud/python-sdk/commit/5af17b7557b2bd3f178c17b7ba7de907c0a3045e)) * **TextToSpeechV1:** change voice model signaturess to custom models ([12ee072](https://github.com/watson-developer-cloud/python-sdk/commit/12ee072189d54a7b6462c82cb0e5d4d123822ea5)) * **VisRecV4:** change start time and end time to date from string ([f2f40e7](https://github.com/watson-developer-cloud/python-sdk/commit/f2f40e7a6e9aa90f3938d576081998cb5667a0f8)) ### BREAKING CHANGES * **VisRecV4:** change start and end time for training usage to date time format * **CompareComply:** remove before and after from list feedback * **TextToSpeechV1:** This update breaks the users using any methods of type _voice_models --- CHANGELOG.md | 24 ++++ package-lock.json | 342 ++++++++++++++-------------------------------- 2 files changed, 126 insertions(+), 240 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38b32d320..f74def5d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,27 @@ +# [5.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.7.1...v5.0.0) (2020-12-11) + + +### Features + +* regenerate services using latest api def and generator ([59e7ded](https://github.com/watson-developer-cloud/python-sdk/commit/59e7dede81f530ea027b480fd007f9df67180ab1)) +* regenerate using current api def and add deprecation warnings ([c3e1f07](https://github.com/watson-developer-cloud/python-sdk/commit/c3e1f07697b15d05f87cec39e36a9a2d28db7b91)) +* regenerate with current API and add deprecation warnings ([4faa938](https://github.com/watson-developer-cloud/python-sdk/commit/4faa9380a606eeb8e8794b918b0f72313e4b1d86)) +* regenrate language translator ([8fdebc4](https://github.com/watson-developer-cloud/python-sdk/commit/8fdebc45f0dfd1044d848969cb5cb3b8cb15a313)) +* regenrate services using current api def and generator ([e84a0cb](https://github.com/watson-developer-cloud/python-sdk/commit/e84a0cb0636cd0add767903391de150bd65a4cd2)) +* regenrate using current api def and generator 3.21 ([33e0d93](https://github.com/watson-developer-cloud/python-sdk/commit/33e0d9356ac43b7f988200c853b46b6cf4f703ab)) +* **AssistantV1:** add support for bulkClassify ([e17b24c](https://github.com/watson-developer-cloud/python-sdk/commit/e17b24cc565bf6ee603497aeb5c11436ee09b0dc)) +* **AssistantV2:** add support for bulkClassify ([8b14dda](https://github.com/watson-developer-cloud/python-sdk/commit/8b14dda82de980f09a031b1e15ab53573a5b55d8)) +* **CompareComply:** remove before and after from list feedback ([5af17b7](https://github.com/watson-developer-cloud/python-sdk/commit/5af17b7557b2bd3f178c17b7ba7de907c0a3045e)) +* **TextToSpeechV1:** change voice model signaturess to custom models ([12ee072](https://github.com/watson-developer-cloud/python-sdk/commit/12ee072189d54a7b6462c82cb0e5d4d123822ea5)) +* **VisRecV4:** change start time and end time to date from string ([f2f40e7](https://github.com/watson-developer-cloud/python-sdk/commit/f2f40e7a6e9aa90f3938d576081998cb5667a0f8)) + + +### BREAKING CHANGES + +* **VisRecV4:** change start and end time for training usage to date time format +* **CompareComply:** remove before and after from list feedback +* **TextToSpeechV1:** This update breaks the users using any methods of type _voice_models + ## [4.7.1](https://github.com/watson-developer-cloud/python-sdk/compare/v4.7.0...v4.7.1) (2020-09-03) diff --git a/package-lock.json b/package-lock.json index 9de6f7980..80c411cd4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -49,140 +49,115 @@ } }, "@octokit/auth-token": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.2.tgz", - "integrity": "sha512-jE/lE/IKIz2v1+/P0u4fJqv0kYwXOTujKemJMFr6FeopsxlIK3+wKDCJGnysg81XID5TgZQbIfuJ5J0lnTiuyQ==", + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.4.tgz", + "integrity": "sha512-LNfGu3Ro9uFAYh10MUZVaT7X2CnNm2C8IDQmabx+3DygYIQjs9FwzFAHN/0t6mu5HEPhxcb1XOuxdpY82vCg2Q==", "requires": { - "@octokit/types": "^5.0.0" + "@octokit/types": "^6.0.0" } }, "@octokit/core": { - "version": "2.5.4", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-2.5.4.tgz", - "integrity": "sha512-HCp8yKQfTITYK+Nd09MHzAlP1v3Ii/oCohv0/TW9rhSLvzb98BOVs2QmVYuloE6a3l6LsfyGIwb6Pc4ycgWlIQ==", - "requires": { - "@octokit/auth-token": "^2.4.0", - "@octokit/graphql": "^4.3.1", - "@octokit/request": "^5.4.0", - "@octokit/types": "^5.0.0", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.2.4.tgz", + "integrity": "sha512-d9dTsqdePBqOn7aGkyRFe7pQpCXdibSJ5SFnrTr0axevObZrpz3qkWm7t/NjYv5a66z6vhfteriaq4FRz3e0Qg==", + "requires": { + "@octokit/auth-token": "^2.4.4", + "@octokit/graphql": "^4.5.8", + "@octokit/request": "^5.4.12", + "@octokit/types": "^6.0.3", "before-after-hook": "^2.1.0", - "universal-user-agent": "^5.0.0" + "universal-user-agent": "^6.0.0" } }, "@octokit/endpoint": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.5.tgz", - "integrity": "sha512-70K5u6zd45ItOny6aHQAsea8HHQjlQq85yqOMe+Aj8dkhN2qSJ9T+Q3YjUjEYfPRBcuUWNgMn62DQnP/4LAIiQ==", + "version": "6.0.10", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.10.tgz", + "integrity": "sha512-9+Xef8nT7OKZglfkOMm7IL6VwxXUQyR7DUSU0LH/F7VNqs8vyd7es5pTfz9E7DwUIx7R3pGscxu1EBhYljyu7Q==", "requires": { - "@octokit/types": "^5.0.0", - "is-plain-object": "^4.0.0", + "@octokit/types": "^6.0.0", + "is-plain-object": "^5.0.0", "universal-user-agent": "^6.0.0" - }, - "dependencies": { - "universal-user-agent": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", - "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" - } } }, "@octokit/graphql": { - "version": "4.5.4", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.4.tgz", - "integrity": "sha512-ITpZ+dQc0cXAW1FmDkHJJM+8Lb6anUnin0VB5hLBilnYVdLC0ICFU/KIvT7OXfW9S81DE3U4Vx2EypDG1OYaPA==", + "version": "4.5.8", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.8.tgz", + "integrity": "sha512-WnCtNXWOrupfPJgXe+vSmprZJUr0VIu14G58PMlkWGj3cH+KLZEfKMmbUQ6C3Wwx6fdhzVW1CD5RTnBdUHxhhA==", "requires": { "@octokit/request": "^5.3.0", - "@octokit/types": "^5.0.0", + "@octokit/types": "^6.0.0", "universal-user-agent": "^6.0.0" - }, - "dependencies": { - "universal-user-agent": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", - "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" - } } }, + "@octokit/openapi-types": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-2.0.0.tgz", + "integrity": "sha512-J4bfM7lf8oZvEAdpS71oTvC1ofKxfEZgU5vKVwzZKi4QPiL82udjpseJwxPid9Pu2FNmyRQOX4iEj6W1iOSnPw==" + }, "@octokit/plugin-paginate-rest": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.3.2.tgz", - "integrity": "sha512-PjHbMhKryxClCrmfvRpGaKCTxUcHIf2zirWRV9SMGf0EmxD/rFew/abSqbMiLl9uQgRZvqtTyCRMGMlUv1ZsBg==", + "version": "2.6.2", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.6.2.tgz", + "integrity": "sha512-3Dy7/YZAwdOaRpGQoNHPeT0VU1fYLpIUdPyvR37IyFLgd6XSij4j9V/xN/+eSjF2KKvmfIulEh9LF1tRPjIiDA==", "requires": { - "@octokit/types": "^5.3.0" + "@octokit/types": "^6.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==" + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-1.0.2.tgz", + "integrity": "sha512-oTJSNAmBqyDR41uSMunLQKMX0jmEXbwD1fpz8FG27lScV3RhtGfBa1/BBLym+PxcC16IBlF7KH9vP1BUYxA+Eg==" }, "@octokit/plugin-rest-endpoint-methods": { - "version": "3.17.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-3.17.0.tgz", - "integrity": "sha512-NFV3vq7GgoO2TrkyBRUOwflkfTYkFKS0tLAPym7RNpkwLCttqShaEGjthOsPEEL+7LFcYv3mU24+F2yVd3npmg==", + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-4.4.1.tgz", + "integrity": "sha512-+v5PcvrUcDeFXf8hv1gnNvNLdm4C0+2EiuWt9EatjjUmfriM1pTMM+r4j1lLHxeBQ9bVDmbywb11e3KjuavieA==", "requires": { - "@octokit/types": "^4.1.6", + "@octokit/types": "^6.1.0", "deprecation": "^2.3.1" - }, - "dependencies": { - "@octokit/types": { - "version": "4.1.10", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-4.1.10.tgz", - "integrity": "sha512-/wbFy1cUIE5eICcg0wTKGXMlKSbaAxEr00qaBXzscLXpqhcwgXeS6P8O0pkysBhRfyjkKjJaYrvR1ExMO5eOXQ==", - "requires": { - "@types/node": ">= 8" - } - } } }, "@octokit/request": { - "version": "5.4.7", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.7.tgz", - "integrity": "sha512-FN22xUDP0i0uF38YMbOfx6TotpcENP5W8yJM1e/LieGXn6IoRxDMnBf7tx5RKSW4xuUZ/1P04NFZy5iY3Rax1A==", + "version": "5.4.12", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.12.tgz", + "integrity": "sha512-MvWYdxengUWTGFpfpefBBpVmmEYfkwMoxonIB3sUGp5rhdgwjXL1ejo6JbgzG/QD9B/NYt/9cJX1pxXeSIUCkg==", "requires": { "@octokit/endpoint": "^6.0.1", "@octokit/request-error": "^2.0.0", - "@octokit/types": "^5.0.0", + "@octokit/types": "^6.0.3", "deprecation": "^2.0.0", - "is-plain-object": "^4.0.0", - "node-fetch": "^2.3.0", + "is-plain-object": "^5.0.0", + "node-fetch": "^2.6.1", "once": "^1.4.0", "universal-user-agent": "^6.0.0" - }, - "dependencies": { - "universal-user-agent": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", - "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" - } } }, "@octokit/request-error": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.2.tgz", - "integrity": "sha512-2BrmnvVSV1MXQvEkrb9zwzP0wXFNbPJij922kYBTLIlIafukrGOb+ABBT2+c6wZiuyWDH1K1zmjGQ0toN/wMWw==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.4.tgz", + "integrity": "sha512-LjkSiTbsxIErBiRh5wSZvpZqT4t0/c9+4dOe0PII+6jXR+oj/h66s7E4a/MghV7iT8W9ffoQ5Skoxzs96+gBPA==", "requires": { - "@octokit/types": "^5.0.1", + "@octokit/types": "^6.0.0", "deprecation": "^2.0.0", "once": "^1.4.0" } }, "@octokit/rest": { - "version": "17.11.2", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-17.11.2.tgz", - "integrity": "sha512-4jTmn8WossTUaLfNDfXk4fVJgbz5JgZE8eCs4BvIb52lvIH8rpVMD1fgRCrHbSd6LRPE5JFZSfAEtszrOq3ZFQ==", + "version": "18.0.12", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-18.0.12.tgz", + "integrity": "sha512-hNRCZfKPpeaIjOVuNJzkEL6zacfZlBPV8vw8ReNeyUkVvbuCvvrrx8K8Gw2eyHHsmd4dPlAxIXIZ9oHhJfkJpw==", "requires": { - "@octokit/core": "^2.4.3", - "@octokit/plugin-paginate-rest": "^2.2.0", - "@octokit/plugin-request-log": "^1.0.0", - "@octokit/plugin-rest-endpoint-methods": "3.17.0" + "@octokit/core": "^3.2.3", + "@octokit/plugin-paginate-rest": "^2.6.2", + "@octokit/plugin-request-log": "^1.0.2", + "@octokit/plugin-rest-endpoint-methods": "4.4.1" } }, "@octokit/types": { - "version": "5.4.1", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-5.4.1.tgz", - "integrity": "sha512-OlMlSySBJoJ6uozkr/i03nO5dlYQyE05vmQNZhAh9MyO4DPBP88QlwsDVLmVjIMFssvIZB6WO0ctIGMRG+xsJQ==", + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.1.1.tgz", + "integrity": "sha512-btm3D6S7VkRrgyYF31etUtVY/eQ1KzrNRqhFt25KSe2mKlXuLXJilglRC6eDA2P6ou94BUnk/Kz5MPEolXgoiw==", "requires": { + "@octokit/openapi-types": "^2.0.0", "@types/node": ">= 8" } }, @@ -231,11 +206,11 @@ } }, "@semantic-release/github": { - "version": "7.0.7", - "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-7.0.7.tgz", - "integrity": "sha512-Sai2UucYQ+5rJzKVEVJ4eiZNDdoo0/CzfpValBdeU5h97uJE7t4CoBTmUWkiXlPOx46CSw1+JhI+PHC1PUxVZw==", + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-7.2.0.tgz", + "integrity": "sha512-tMRnWiiWb43whRHvbDGXq4DGEbKRi56glDpXDJZit4PIiwDPX7Kx3QzmwRtDOcG+8lcpGjpdPabYZ9NBxoI2mw==", "requires": { - "@octokit/rest": "^17.0.0", + "@octokit/rest": "^18.0.0", "@semantic-release/error": "^2.2.0", "aggregate-error": "^3.0.0", "bottleneck": "^2.18.1", @@ -259,9 +234,9 @@ "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==" }, "@types/node": { - "version": "14.6.3", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.6.3.tgz", - "integrity": "sha512-pC/hkcREG6YfDfui1FBmj8e20jFU5Exjw4NYDm8kEdrW+mOh0T1Zve8DWKnS7ZIZvgncrctcNCXF4Q2I+loyww==" + "version": "14.14.12", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.12.tgz", + "integrity": "sha512-ASH8OPHMNlkdjrEdmoILmzFfsJICvhBsFfAum4aKZ/9U4B6M6tTmTPh+f3ttWdD74CEGV5XvXWkbyfSdXaTd7g==" }, "@types/retry": { "version": "0.12.0", @@ -269,9 +244,9 @@ "integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==" }, "agent-base": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.1.tgz", - "integrity": "sha512-01q25QQDwLSsyfhrKbn8yuur+JNw0H+0Y4JiGIKd3z9aYk/w/2kxD/Upc+t2ZBBSUNff50VjPsSW2YxM8QYKVg==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", "requires": { "debug": "4" } @@ -360,11 +335,11 @@ } }, "debug": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", - "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", + "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", "requires": { - "ms": "^2.1.1" + "ms": "2.1.2" } }, "deprecation": { @@ -402,9 +377,9 @@ "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=" }, "execa": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/execa/-/execa-4.0.3.tgz", - "integrity": "sha512-WFDXGHckXPWZX19t1kCsXzOpqX9LWYNqn4C+HqZlk/V0imTkzJZqf87ZBhvpHaftERYknpk0fjSylnXVlVgI0A==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/execa/-/execa-4.1.0.tgz", + "integrity": "sha512-j5W0//W7f8UxAn8hXVnwG8tLwdiUy4FJLcSupCg6maBYZDpyBvTApK7KyuI4bKj8KOh1r2YH+6ucuYtJv1bTZA==", "requires": { "cross-spawn": "^7.0.0", "get-stream": "^5.0.0", @@ -431,9 +406,9 @@ } }, "fastq": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.8.0.tgz", - "integrity": "sha512-SMIZoZdLh/fgofivvIkmknUXyPnvxRE3DhtZ5Me3Mrsk5gyPL42F0xr51TdRXskBxHfMp+07bcYzfsYEsSQA9Q==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.9.0.tgz", + "integrity": "sha512-i7FVWL8HhVY+CTkwFxkN2mk3h+787ixS5S63eb78diVRc1MCssarHq3W5cj0av7YDSwmaV928RNag+U1etRQ7w==", "requires": { "reusify": "^1.0.4" } @@ -554,9 +529,9 @@ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==" }, "is-plain-object": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-4.1.1.tgz", - "integrity": "sha512-5Aw8LLVsDlZsETVMhoMXzqsXwQqr/0vlnBYzIXJbYo2F4yYlhLHs+Ez7Bod7IIQKWkJbJfxrWD7pA1Dw1TKrwA==" + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/is-plain-object/-/is-plain-object-5.0.0.tgz", + "integrity": "sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==" }, "is-stream": { "version": "2.0.0", @@ -591,12 +566,19 @@ "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==" }, "jsonfile": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.0.1.tgz", - "integrity": "sha512-jR2b5v7d2vIOust+w3wtFKZIfpC2pnRmFAhAC/BuweZFQR8qZzxH1OyrQ10HmdVYiXWkYUqPVsz91cG7EL2FBg==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz", + "integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==", "requires": { "graceful-fs": "^4.1.6", - "universalify": "^1.0.0" + "universalify": "^2.0.0" + }, + "dependencies": { + "universalify": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", + "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==" + } } }, "lines-and-columns": { @@ -634,11 +616,6 @@ "resolved": "https://registry.npmjs.org/lodash.uniqby/-/lodash.uniqby-4.7.0.tgz", "integrity": "sha1-2ZwHpmnp5tJOE2Lf4mbGdhavEwI=" }, - "macos-release": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/macos-release/-/macos-release-2.4.1.tgz", - "integrity": "sha512-H/QHeBIN1fIGJX517pvK8IEK53yQOW7YcEI55oYtgjDdoCQQz7eJS94qt5kNrscReEyuD/JcdFCm2XBEcGOITg==" - }, "merge-stream": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", @@ -673,15 +650,10 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" }, - "nice-try": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/nice-try/-/nice-try-1.0.5.tgz", - "integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==" - }, "node-fetch": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz", - "integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==" + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz", + "integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==" }, "npm-run-path": { "version": "4.0.1", @@ -707,15 +679,6 @@ "mimic-fn": "^2.1.0" } }, - "os-name": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/os-name/-/os-name-3.1.0.tgz", - "integrity": "sha512-h8L+8aNjNcMpo/mAIBPn5PXCM16iyPGjHNWo6U1YO8sJTMHtEtyczI6QJnLoplswm6goopQkqc7OAnjhWcugVg==", - "requires": { - "macos-release": "^2.2.0", - "windows-release": "^3.1.0" - } - }, "p-filter": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/p-filter/-/p-filter-2.1.0.tgz", @@ -724,11 +687,6 @@ "p-map": "^2.0.0" } }, - "p-finally": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", - "integrity": "sha1-P7z7FbiZpEEjs0ttzBi3JDNqLK4=" - }, "p-map": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/p-map/-/p-map-2.1.0.tgz", @@ -794,14 +752,9 @@ "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==" }, "run-parallel": { - "version": "1.1.9", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.1.9.tgz", - "integrity": "sha512-DEqnSRTDw/Tc3FXf49zedI638Z9onwUotBMiUFKmrO2sdFKIbXamXGQ3Axd4qgphxKB4kw/qP1w5kTxnfU1B9Q==" - }, - "semver": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.1.tgz", - "integrity": "sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==" + "version": "1.1.10", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.1.10.tgz", + "integrity": "sha512-zb/1OuZ6flOlH6tQyMPUrE3x3Ulxjlo9WIVXR4yVYi4H9UXQaeIsPbLn2R3O3vQCnDKkAl2qHiuocKKX4Tz/Sw==" }, "shebang-command": { "version": "2.0.0", @@ -826,11 +779,6 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==" }, - "strip-eof": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", - "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=" - }, "strip-final-newline": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", @@ -853,12 +801,9 @@ } }, "universal-user-agent": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-5.0.0.tgz", - "integrity": "sha512-B5TPtzZleXyPrUMKCpEHFmVhMN6EhmJYjG5PQna9s7mXeSqGTLap4OpqLl5FCEFUI3UBmllkETwKf/db66Y54Q==", - "requires": { - "os-name": "^3.1.0" - } + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", + "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" }, "universalify": { "version": "1.0.0", @@ -878,89 +823,6 @@ "isexe": "^2.0.0" } }, - "windows-release": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/windows-release/-/windows-release-3.3.3.tgz", - "integrity": "sha512-OSOGH1QYiW5yVor9TtmXKQvt2vjQqbYS+DqmsZw+r7xDwLXEeT3JGW0ZppFmHx4diyXmxt238KFR3N9jzevBRg==", - "requires": { - "execa": "^1.0.0" - }, - "dependencies": { - "cross-spawn": { - "version": "6.0.5", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-6.0.5.tgz", - "integrity": "sha512-eTVLrBSt7fjbDygz805pMnstIs2VTBNkRm0qxZd+M7A5XDdxVRWO5MxGBXZhjY4cqLYLdtrGqRf8mBPmzwSpWQ==", - "requires": { - "nice-try": "^1.0.4", - "path-key": "^2.0.1", - "semver": "^5.5.0", - "shebang-command": "^1.2.0", - "which": "^1.2.9" - } - }, - "execa": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/execa/-/execa-1.0.0.tgz", - "integrity": "sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==", - "requires": { - "cross-spawn": "^6.0.0", - "get-stream": "^4.0.0", - "is-stream": "^1.1.0", - "npm-run-path": "^2.0.0", - "p-finally": "^1.0.0", - "signal-exit": "^3.0.0", - "strip-eof": "^1.0.0" - } - }, - "get-stream": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-4.1.0.tgz", - "integrity": "sha512-GMat4EJ5161kIy2HevLlr4luNjBgvmj413KaQA7jt4V8B4RDsfpHk7WQ9GVqfYyyx8OS/L66Kox+rJRNklLK7w==", - "requires": { - "pump": "^3.0.0" - } - }, - "is-stream": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-1.1.0.tgz", - "integrity": "sha1-EtSj3U5o4Lec6428hBc66A2RykQ=" - }, - "npm-run-path": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-2.0.2.tgz", - "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", - "requires": { - "path-key": "^2.0.0" - } - }, - "path-key": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-2.0.1.tgz", - "integrity": "sha1-QRyttXTFoUDTpLGRDUDYDMn0C0A=" - }, - "shebang-command": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", - "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", - "requires": { - "shebang-regex": "^1.0.0" - } - }, - "shebang-regex": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-1.0.0.tgz", - "integrity": "sha1-2kL0l0DAtC2yypcoVxyxkMmO/qM=" - }, - "which": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", - "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", - "requires": { - "isexe": "^2.0.0" - } - } - } - }, "wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", From 53e532e04ab141d93e54f040965dbca993186543 Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 21 Dec 2020 11:58:43 -0500 Subject: [PATCH 297/455] fix(Assistant): node dialog response should have agent props --- ibm_watson/assistant_v1.py | 266 ++++++++++++++++++++------------- ibm_watson/assistant_v2.py | 204 ++++++++++++++++--------- test/unit/test_assistant_v1.py | 259 ++++++++++++++++++-------------- test/unit/test_assistant_v2.py | 252 +++++++++++++++++-------------- 4 files changed, 579 insertions(+), 402 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index c6c2035bc..158fb1597 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201221-115123 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -176,6 +176,66 @@ def message(self, response = self.send(request) return response + ######################### + # Bulk classify + ######################### + + def bulk_classify(self, + workspace_id: str, + *, + input: List['BulkClassifyUtterance'] = None, + **kwargs) -> DetailedResponse: + """ + Identify intents and entities in multiple user utterances. + + Send multiple user inputs to a workspace in a single request and receive + information about the intents and entities recognized in each input. This method + is useful for testing and comparing the performance of different workspaces. + This method is available only with Premium plans. + + :param str workspace_id: Unique identifier of the workspace. + :param List[BulkClassifyUtterance] input: (optional) An array of input + utterances to classify. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object + """ + + if workspace_id is None: + raise ValueError('workspace_id must be provided') + if input is not None: + input = [convert_model(x) for x in input] + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='bulk_classify') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'input': input} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces/{workspace_id}/bulk_classify'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + ######################### # Workspaces ######################### @@ -3255,66 +3315,6 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: response = self.send(request) return response - ######################### - # bulkClassify - ######################### - - def bulk_classify(self, - workspace_id: str, - *, - input: List['BulkClassifyUtterance'] = None, - **kwargs) -> DetailedResponse: - """ - Identify intents and entities in multiple user utterances. - - Send multiple user inputs to a workspace in a single request and receive - information about the intents and entities recognized in each input. This method - is useful for testing and comparing the performance of different workspaces. - This method is available only with Premium plans. - - :param str workspace_id: Unique identifier of the workspace. - :param List[BulkClassifyUtterance] input: (optional) An array of input - utterances to classify. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object - """ - - if workspace_id is None: - raise ValueError('workspace_id must be provided') - if input is not None: - input = [convert_model(x) for x in input] - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='bulk_classify') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = {'input': input} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['workspace_id'] - path_param_values = self.encode_path_vars(workspace_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/workspaces/{workspace_id}/bulk_classify'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request) - return response - class ListWorkspacesEnums: """ @@ -3447,6 +3447,60 @@ class Sort(str, Enum): ############################################################################## +class AgentAvailabilityMessage(): + """ + AgentAvailabilityMessage. + + :attr str message: (optional) The text of the message. + """ + + def __init__(self, *, message: str = None) -> None: + """ + Initialize a AgentAvailabilityMessage object. + + :param str message: (optional) The text of the message. + """ + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': + """Initialize a AgentAvailabilityMessage object from a json dictionary.""" + args = {} + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AgentAvailabilityMessage 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, 'message') and self.message is not None: + _dict['message'] = self.message + 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 AgentAvailabilityMessage object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AgentAvailabilityMessage') -> 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: 'AgentAvailabilityMessage') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class BulkClassifyOutput(): """ BulkClassifyOutput. @@ -7705,10 +7759,8 @@ class RuntimeEntity(): 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). + For more information about how system entities are interpreted, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-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 @@ -7746,11 +7798,9 @@ def __init__(self, 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). + input. + For more information about how system entities are interpreted, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-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 @@ -9772,12 +9822,12 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent( specified response type must be supported by the client application or channel. :attr str message_to_human_agent: (optional) An optional message to be sent to the human agent who will be taking over the conversation. - :attr str agent_available: (optional) An optional message to be displayed to the - user to indicate that the conversation will be transferred to the next available - agent. - :attr str agent_unavailable: (optional) An optional message to be displayed to - the user to indicate that no online agent is available to take over the - conversation. + :attr AgentAvailabilityMessage agent_available: (optional) An optional message + to be displayed to the user to indicate that the conversation will be + transferred to the next available agent. + :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message + to be displayed to the user to indicate that no online agent is available to + take over the conversation. :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. @@ -9788,8 +9838,8 @@ def __init__( response_type: str, *, message_to_human_agent: str = None, - agent_available: str = None, - agent_unavailable: str = None, + agent_available: 'AgentAvailabilityMessage' = None, + agent_unavailable: 'AgentAvailabilityMessage' = None, transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None ) -> None: """ @@ -9800,12 +9850,12 @@ def __init__( channel. :param str message_to_human_agent: (optional) An optional message to be sent to the human agent who will be taking over the conversation. - :param str agent_available: (optional) An optional message to be displayed - to the user to indicate that the conversation will be transferred to the - next available agent. - :param str agent_unavailable: (optional) An optional message to be - displayed to the user to indicate that no online agent is available to take - over the conversation. + :param AgentAvailabilityMessage agent_available: (optional) An optional + message to be displayed to the user to indicate that the conversation will + be transferred to the next available agent. + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. @@ -9832,9 +9882,11 @@ def from_dict( if 'message_to_human_agent' in _dict: args['message_to_human_agent'] = _dict.get('message_to_human_agent') if 'agent_available' in _dict: - args['agent_available'] = _dict.get('agent_available') + args['agent_available'] = AgentAvailabilityMessage.from_dict( + _dict.get('agent_available')) if 'agent_unavailable' in _dict: - args['agent_unavailable'] = _dict.get('agent_unavailable') + args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( + _dict.get('agent_unavailable')) if 'transfer_info' in _dict: args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( @@ -9856,10 +9908,10 @@ def to_dict(self) -> Dict: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available + _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: _dict['transfer_info'] = self.transfer_info.to_dict() return _dict @@ -10523,12 +10575,12 @@ class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( specified response type must be supported by the client application or channel. :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. - :attr str agent_available: (optional) An optional message to be displayed to the - user to indicate that the conversation will be transferred to the next available - agent. - :attr str agent_unavailable: (optional) An optional message to be displayed to - the user to indicate that no online agent is available to take over the - conversation. + :attr AgentAvailabilityMessage agent_available: (optional) An optional message + to be displayed to the user to indicate that the conversation will be + transferred to the next available agent. + :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message + to be displayed to the user to indicate that no online agent is available to + take over the conversation. :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. @@ -10545,8 +10597,8 @@ def __init__( response_type: str, *, message_to_human_agent: str = None, - agent_available: str = None, - agent_unavailable: str = None, + agent_available: 'AgentAvailabilityMessage' = None, + agent_unavailable: 'AgentAvailabilityMessage' = None, transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, topic: str = None, dialog_node: str = None) -> None: @@ -10558,12 +10610,12 @@ def __init__( channel. :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. - :param str agent_available: (optional) An optional message to be displayed - to the user to indicate that the conversation will be transferred to the - next available agent. - :param str agent_unavailable: (optional) An optional message to be - displayed to the user to indicate that no online agent is available to take - over the conversation. + :param AgentAvailabilityMessage agent_available: (optional) An optional + message to be displayed to the user to indicate that the conversation will + be transferred to the next available agent. + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. @@ -10598,9 +10650,11 @@ def from_dict( if 'message_to_human_agent' in _dict: args['message_to_human_agent'] = _dict.get('message_to_human_agent') if 'agent_available' in _dict: - args['agent_available'] = _dict.get('agent_available') + args['agent_available'] = AgentAvailabilityMessage.from_dict( + _dict.get('agent_available')) if 'agent_unavailable' in _dict: - args['agent_unavailable'] = _dict.get('agent_unavailable') + args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( + _dict.get('agent_unavailable')) if 'transfer_info' in _dict: args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( @@ -10626,10 +10680,10 @@ def to_dict(self) -> Dict: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available + _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'topic') and self.topic is not None: diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 39d99dabf..611202159 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201221-115123 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -319,6 +319,69 @@ def message_stateless(self, response = self.send(request) return response + ######################### + # Bulk classify + ######################### + + def bulk_classify(self, + skill_id: str, + *, + input: List['BulkClassifyUtterance'] = None, + **kwargs) -> DetailedResponse: + """ + Identify intents and entities in multiple user utterances. + + Send multiple user inputs to a dialog skill in a single request and receive + information about the intents and entities recognized in each input. This method + is useful for testing and comparing the performance of different skills or skill + versions. + This method is available only with Premium plans. + + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the Watson Assistant user interface, open the skill settings and click + **API Details**. + :param List[BulkClassifyUtterance] input: (optional) An array of input + utterances to classify. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object + """ + + if skill_id is None: + raise ValueError('skill_id must be provided') + if input is not None: + input = [convert_model(x) for x in input] + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='bulk_classify') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'input': input} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['skill_id'] + path_param_values = self.encode_path_vars(skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/skills/{skill_id}/workspace/bulk_classify'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + ######################### # Logs ######################### @@ -437,73 +500,64 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: response = self.send(request) return response - ######################### - # bulkClassify - ######################### - def bulk_classify(self, - skill_id: str, - *, - input: List['BulkClassifyUtterance'] = None, - **kwargs) -> DetailedResponse: - """ - Identify intents and entities in multiple user utterances. +############################################################################## +# Models +############################################################################## - Send multiple user inputs to a dialog skill in a single request and receive - information about the intents and entities recognized in each input. This method - is useful for testing and comparing the performance of different skills or skill - versions. - This method is available only with Premium plans. - :param str skill_id: Unique identifier of the skill. To find the skill ID - in the Watson Assistant user interface, open the skill settings and click - **API Details**. - :param List[BulkClassifyUtterance] input: (optional) An array of input - utterances to classify. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object +class AgentAvailabilityMessage(): + """ + AgentAvailabilityMessage. + + :attr str message: (optional) The text of the message. + """ + + def __init__(self, *, message: str = None) -> None: """ + Initialize a AgentAvailabilityMessage object. - if skill_id is None: - raise ValueError('skill_id must be provided') - if input is not None: - input = [convert_model(x) for x in input] - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='bulk_classify') - headers.update(sdk_headers) + :param str message: (optional) The text of the message. + """ + self.message = message - params = {'version': self.version} + @classmethod + def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': + """Initialize a AgentAvailabilityMessage object from a json dictionary.""" + args = {} + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) - data = {'input': input} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' + @classmethod + def _from_dict(cls, _dict): + """Initialize a AgentAvailabilityMessage object from a json dictionary.""" + return cls.from_dict(_dict) - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + return _dict - path_param_keys = ['skill_id'] - path_param_values = self.encode_path_vars(skill_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/skills/{skill_id}/workspace/bulk_classify'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() - response = self.send(request) - return response + def __str__(self) -> str: + """Return a `str` version of this AgentAvailabilityMessage object.""" + return json.dumps(self.to_dict(), indent=2) + def __eq__(self, other: 'AgentAvailabilityMessage') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ -############################################################################## -# Models -############################################################################## + def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other class BulkClassifyOutput(): @@ -4591,12 +4645,12 @@ class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( specified response type must be supported by the client application or channel. :attr str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. - :attr str agent_available: (optional) An optional message to be displayed to the - user to indicate that the conversation will be transferred to the next available - agent. - :attr str agent_unavailable: (optional) An optional message to be displayed to - the user to indicate that no online agent is available to take over the - conversation. + :attr AgentAvailabilityMessage agent_available: (optional) An optional message + to be displayed to the user to indicate that the conversation will be + transferred to the next available agent. + :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message + to be displayed to the user to indicate that no online agent is available to + take over the conversation. :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. @@ -4610,8 +4664,8 @@ def __init__( response_type: str, *, message_to_human_agent: str = None, - agent_available: str = None, - agent_unavailable: str = None, + agent_available: 'AgentAvailabilityMessage' = None, + agent_unavailable: 'AgentAvailabilityMessage' = None, transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, topic: str = None) -> None: """ @@ -4622,12 +4676,12 @@ def __init__( channel. :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. - :param str agent_available: (optional) An optional message to be displayed - to the user to indicate that the conversation will be transferred to the - next available agent. - :param str agent_unavailable: (optional) An optional message to be - displayed to the user to indicate that no online agent is available to take - over the conversation. + :param AgentAvailabilityMessage agent_available: (optional) An optional + message to be displayed to the user to indicate that the conversation will + be transferred to the next available agent. + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. @@ -4658,9 +4712,11 @@ def from_dict( if 'message_to_human_agent' in _dict: args['message_to_human_agent'] = _dict.get('message_to_human_agent') if 'agent_available' in _dict: - args['agent_available'] = _dict.get('agent_available') + args['agent_available'] = AgentAvailabilityMessage.from_dict( + _dict.get('agent_available')) if 'agent_unavailable' in _dict: - args['agent_unavailable'] = _dict.get('agent_unavailable') + args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( + _dict.get('agent_unavailable')) if 'transfer_info' in _dict: args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( @@ -4684,10 +4740,10 @@ def to_dict(self) -> Dict: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available + _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'topic') and self.topic is not None: diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 217d21e46..b178ed6c3 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -290,6 +290,123 @@ def test_message_value_error(self): # End of Service: Message ############################################################################## +############################################################################## +# Start of Service: BulkClassify +############################################################################## +# region + +class TestBulkClassify(): + """ + Test Class for bulk_classify + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_bulk_classify_all_params(self): + """ + bulk_classify() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' + + # Set up parameter values + workspace_id = 'testString' + input = [bulk_classify_utterance_model] + + # Invoke method + response = service.bulk_classify( + workspace_id, + input=input, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == [bulk_classify_utterance_model] + + + @responses.activate + def test_bulk_classify_required_params(self): + """ + test_bulk_classify_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = service.bulk_classify( + workspace_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_bulk_classify_value_error(self): + """ + test_bulk_classify_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.bulk_classify(**req_copy) + + + +# endregion +############################################################################## +# End of Service: BulkClassify +############################################################################## + ############################################################################## # Start of Service: Workspaces ############################################################################## @@ -6256,128 +6373,40 @@ def test_delete_user_data_value_error(self): # End of Service: UserData ############################################################################## + ############################################################################## -# Start of Service: BulkClassify +# Start of Model Tests ############################################################################## # region - -class TestBulkClassify(): +class TestAgentAvailabilityMessage(): """ - Test Class for bulk_classify + Test Class for AgentAvailabilityMessage """ - def preprocess_url(self, request_url: str): + def test_agent_availability_message_serialization(self): """ - Preprocess the request URL to ensure the mock response will be found. + Test serialization/deserialization for AgentAvailabilityMessage """ - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_bulk_classify_all_params(self): - """ - bulk_classify() - """ - # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a BulkClassifyUtterance model - bulk_classify_utterance_model = {} - bulk_classify_utterance_model['text'] = 'testString' - # Set up parameter values - workspace_id = 'testString' - input = [bulk_classify_utterance_model] + # Construct a json representation of a AgentAvailabilityMessage model + agent_availability_message_model_json = {} + agent_availability_message_model_json['message'] = 'testString' - # Invoke method - response = service.bulk_classify( - workspace_id, - input=input, - headers={} - ) + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json) + assert agent_availability_message_model != False - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['input'] == [bulk_classify_utterance_model] + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model_dict = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json).__dict__ + agent_availability_message_model2 = AgentAvailabilityMessage(**agent_availability_message_model_dict) + # Verify the model instances are equivalent + assert agent_availability_message_model == agent_availability_message_model2 - @responses.activate - def test_bulk_classify_required_params(self): - """ - test_bulk_classify_required_params() - """ - # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - workspace_id = 'testString' - - # Invoke method - response = service.bulk_classify( - workspace_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_bulk_classify_value_error(self): - """ - test_bulk_classify_value_error() - """ - # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - workspace_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "workspace_id": workspace_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - service.bulk_classify(**req_copy) - - - -# endregion -############################################################################## -# End of Service: BulkClassify -############################################################################## - + # Convert model instance back to dict and verify no loss of data + agent_availability_message_model_json2 = agent_availability_message_model.to_dict() + assert agent_availability_message_model_json2 == agent_availability_message_model_json -############################################################################## -# Start of Model Tests -############################################################################## -# region class TestBulkClassifyOutput(): """ Test Class for BulkClassifyOutput @@ -10007,6 +10036,9 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ # Construct dict forms of any model objects needed in order to build this model. + agent_availability_message_model = {} # AgentAvailabilityMessage + agent_availability_message_model['message'] = 'testString' + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} @@ -10014,8 +10046,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['response_type'] = 'connect_to_agent' dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['message_to_human_agent'] = 'testString' - dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['agent_available'] = 'testString' - dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['agent_unavailable'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['agent_available'] = agent_availability_message_model + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['agent_unavailable'] = agent_availability_message_model dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['transfer_info'] = dialog_node_output_connect_to_agent_transfer_info_model # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent by calling from_dict on the json representation @@ -10284,6 +10316,9 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali # Construct dict forms of any model objects needed in order to build this model. + agent_availability_message_model = {} # AgentAvailabilityMessage + agent_availability_message_model['message'] = 'testString' + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} @@ -10291,8 +10326,8 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json = {} runtime_response_generic_runtime_response_type_connect_to_agent_model_json['response_type'] = 'connect_to_agent' runtime_response_generic_runtime_response_type_connect_to_agent_model_json['message_to_human_agent'] = 'testString' - runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_available'] = 'testString' - runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_unavailable'] = 'testString' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_available'] = agent_availability_message_model + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_unavailable'] = agent_availability_message_model runtime_response_generic_runtime_response_type_connect_to_agent_model_json['transfer_info'] = dialog_node_output_connect_to_agent_transfer_info_model runtime_response_generic_runtime_response_type_connect_to_agent_model_json['topic'] = 'testString' runtime_response_generic_runtime_response_type_connect_to_agent_model_json['dialog_node'] = 'testString' diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 708a44320..a2ab09b5e 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -632,6 +632,123 @@ def test_message_stateless_value_error(self): # End of Service: Message ############################################################################## +############################################################################## +# Start of Service: BulkClassify +############################################################################## +# region + +class TestBulkClassify(): + """ + Test Class for bulk_classify + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_bulk_classify_all_params(self): + """ + bulk_classify() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' + + # Set up parameter values + skill_id = 'testString' + input = [bulk_classify_utterance_model] + + # Invoke method + response = service.bulk_classify( + skill_id, + input=input, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == [bulk_classify_utterance_model] + + + @responses.activate + def test_bulk_classify_required_params(self): + """ + test_bulk_classify_required_params() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + skill_id = 'testString' + + # Invoke method + response = service.bulk_classify( + skill_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_bulk_classify_value_error(self): + """ + test_bulk_classify_value_error() + """ + # Set up mock + url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + skill_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "skill_id": skill_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + service.bulk_classify(**req_copy) + + + +# endregion +############################################################################## +# End of Service: BulkClassify +############################################################################## + ############################################################################## # Start of Service: Logs ############################################################################## @@ -833,128 +950,40 @@ def test_delete_user_data_value_error(self): # End of Service: UserData ############################################################################## + ############################################################################## -# Start of Service: BulkClassify +# Start of Model Tests ############################################################################## # region - -class TestBulkClassify(): +class TestAgentAvailabilityMessage(): """ - Test Class for bulk_classify + Test Class for AgentAvailabilityMessage """ - def preprocess_url(self, request_url: str): + def test_agent_availability_message_serialization(self): """ - Preprocess the request URL to ensure the mock response will be found. + Test serialization/deserialization for AgentAvailabilityMessage """ - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_bulk_classify_all_params(self): - """ - bulk_classify() - """ - # Set up mock - url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a BulkClassifyUtterance model - bulk_classify_utterance_model = {} - bulk_classify_utterance_model['text'] = 'testString' - # Set up parameter values - skill_id = 'testString' - input = [bulk_classify_utterance_model] + # Construct a json representation of a AgentAvailabilityMessage model + agent_availability_message_model_json = {} + agent_availability_message_model_json['message'] = 'testString' - # Invoke method - response = service.bulk_classify( - skill_id, - input=input, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['input'] == [bulk_classify_utterance_model] + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json) + assert agent_availability_message_model != False + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model_dict = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json).__dict__ + agent_availability_message_model2 = AgentAvailabilityMessage(**agent_availability_message_model_dict) - @responses.activate - def test_bulk_classify_required_params(self): - """ - test_bulk_classify_required_params() - """ - # Set up mock - url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - skill_id = 'testString' - - # Invoke method - response = service.bulk_classify( - skill_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_bulk_classify_value_error(self): - """ - test_bulk_classify_value_error() - """ - # Set up mock - url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - skill_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "skill_id": skill_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - service.bulk_classify(**req_copy) - - - -# endregion -############################################################################## -# End of Service: BulkClassify -############################################################################## + # Verify the model instances are equivalent + assert agent_availability_message_model == agent_availability_message_model2 + # Convert model instance back to dict and verify no loss of data + agent_availability_message_model_json2 = agent_availability_message_model.to_dict() + assert agent_availability_message_model_json2 == agent_availability_message_model_json -############################################################################## -# Start of Model Tests -############################################################################## -# region class TestBulkClassifyOutput(): """ Test Class for BulkClassifyOutput @@ -3853,6 +3882,9 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali # Construct dict forms of any model objects needed in order to build this model. + agent_availability_message_model = {} # AgentAvailabilityMessage + agent_availability_message_model['message'] = 'testString' + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} @@ -3860,8 +3892,8 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json = {} runtime_response_generic_runtime_response_type_connect_to_agent_model_json['response_type'] = 'connect_to_agent' runtime_response_generic_runtime_response_type_connect_to_agent_model_json['message_to_human_agent'] = 'testString' - runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_available'] = 'testString' - runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_unavailable'] = 'testString' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_available'] = agent_availability_message_model + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_unavailable'] = agent_availability_message_model runtime_response_generic_runtime_response_type_connect_to_agent_model_json['transfer_info'] = dialog_node_output_connect_to_agent_transfer_info_model runtime_response_generic_runtime_response_type_connect_to_agent_model_json['topic'] = 'testString' From 7235c8aee0b58a5a7ba4cd4bae4739a3d00b505c Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 22 Dec 2020 14:10:50 +0000 Subject: [PATCH 298/455] =?UTF-8?q?Bump=20version:=205.0.0=20=E2=86=92=205?= =?UTF-8?q?.0.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 3605e0b9e..d958dace9 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.0.0 +current_version = 5.0.1 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index a0f66580c..3d96b2761 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '5.0.0' +__version__ = '5.0.1' diff --git a/setup.py b/setup.py index 8e538165a..c4d7854c3 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '5.0.0' +__version__ = '5.0.1' if sys.argv[-1] == 'publish': From 6d7846fd7c634554508f84fddbc0511d30260be7 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 22 Dec 2020 14:10:50 +0000 Subject: [PATCH 299/455] chore(release): 5.0.1 release notes ## [5.0.1](https://github.com/watson-developer-cloud/python-sdk/compare/v5.0.0...v5.0.1) (2020-12-22) ### Bug Fixes * **Assistant:** node dialog response should have agent props ([53e532e](https://github.com/watson-developer-cloud/python-sdk/commit/53e532e04ab141d93e54f040965dbca993186543)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 44 ++++++++++++++++++++++---------------------- 2 files changed, 29 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f74def5d5..2a1ad2820 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [5.0.1](https://github.com/watson-developer-cloud/python-sdk/compare/v5.0.0...v5.0.1) (2020-12-22) + + +### Bug Fixes + +* **Assistant:** node dialog response should have agent props ([53e532e](https://github.com/watson-developer-cloud/python-sdk/commit/53e532e04ab141d93e54f040965dbca993186543)) + # [5.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v4.7.1...v5.0.0) (2020-12-11) diff --git a/package-lock.json b/package-lock.json index 80c411cd4..9543b222a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3,17 +3,17 @@ "lockfileVersion": 1, "dependencies": { "@babel/code-frame": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.10.4.tgz", - "integrity": "sha512-vG6SvB6oYEhvgisZNFRmRCUkLz11c7rp+tbNTynGqc6mS1d5ATd/sGyV6W0KZZnXRKMTzZDRgQT3Ou9jhpAfUg==", + "version": "7.12.11", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", + "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", "requires": { "@babel/highlight": "^7.10.4" } }, "@babel/helper-validator-identifier": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.10.4.tgz", - "integrity": "sha512-3U9y+43hz7ZM+rzG24Qe2mufW5KhvFg/NhnNph+i9mgCtdTCtMJuI1TMkrIUiK7Ix4PYlRF9I5dhqaLYA/ADXw==" + "version": "7.12.11", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.12.11.tgz", + "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==" }, "@babel/highlight": { "version": "7.10.4", @@ -90,9 +90,9 @@ } }, "@octokit/openapi-types": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-2.0.0.tgz", - "integrity": "sha512-J4bfM7lf8oZvEAdpS71oTvC1ofKxfEZgU5vKVwzZKi4QPiL82udjpseJwxPid9Pu2FNmyRQOX4iEj6W1iOSnPw==" + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-2.0.1.tgz", + "integrity": "sha512-9AuC04PUnZrjoLiw3uPtwGh9FE4Q3rTqs51oNlQ0rkwgE8ftYsOC+lsrQyvCvWm85smBbSc0FNRKKumvGyb44Q==" }, "@octokit/plugin-paginate-rest": { "version": "2.6.2", @@ -153,11 +153,11 @@ } }, "@octokit/types": { - "version": "6.1.1", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.1.1.tgz", - "integrity": "sha512-btm3D6S7VkRrgyYF31etUtVY/eQ1KzrNRqhFt25KSe2mKlXuLXJilglRC6eDA2P6ou94BUnk/Kz5MPEolXgoiw==", + "version": "6.1.2", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.1.2.tgz", + "integrity": "sha512-LPCpcLbcky7fWfHCTuc7tMiSHFpFlrThJqVdaHgowBTMS0ijlZFfonQC/C1PrZOjD4xRCYgBqH9yttEATGE/nw==", "requires": { - "@octokit/openapi-types": "^2.0.0", + "@octokit/openapi-types": "^2.0.1", "@types/node": ">= 8" } }, @@ -234,9 +234,9 @@ "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==" }, "@types/node": { - "version": "14.14.12", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.12.tgz", - "integrity": "sha512-ASH8OPHMNlkdjrEdmoILmzFfsJICvhBsFfAum4aKZ/9U4B6M6tTmTPh+f3ttWdD74CEGV5XvXWkbyfSdXaTd7g==" + "version": "14.14.14", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.14.tgz", + "integrity": "sha512-UHnOPWVWV1z+VV8k6L1HhG7UbGBgIdghqF3l9Ny9ApPghbjICXkUJSd/b9gOgQfjM1r+37cipdw/HJ3F6ICEnQ==" }, "@types/retry": { "version": "0.12.0", @@ -406,9 +406,9 @@ } }, "fastq": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.9.0.tgz", - "integrity": "sha512-i7FVWL8HhVY+CTkwFxkN2mk3h+787ixS5S63eb78diVRc1MCssarHq3W5cj0av7YDSwmaV928RNag+U1etRQ7w==", + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.10.0.tgz", + "integrity": "sha512-NL2Qc5L3iQEsyYzweq7qfgy5OtXCmGzGvhElGEd/SoFWEMOEczNh5s5ocaF01HDetxz+p8ecjNPA6cZxxIHmzA==", "requires": { "reusify": "^1.0.4" } @@ -636,9 +636,9 @@ } }, "mime": { - "version": "2.4.6", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.6.tgz", - "integrity": "sha512-RZKhC3EmpBchfTGBVb8fb+RL2cWyw/32lshnsETttkBAyAUXSGHxbEJWWRXc751DrIxG1q04b8QwMbAwkRPpUA==" + "version": "2.4.7", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.7.tgz", + "integrity": "sha512-dhNd1uA2u397uQk3Nv5LM4lm93WYDUXFn3Fu291FJerns4jyTudqhIWe4W04YLy7Uk1tm1Ore04NpjRvQp/NPA==" }, "mimic-fn": { "version": "2.1.0", From 8fcdfc64db1bcf6a230e8be80de6dfcad8e8811f Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Mon, 28 Dec 2020 10:50:26 -0500 Subject: [PATCH 300/455] fix: lock JWT version to 1.7.1 --- requirements-dev.txt | 3 +++ requirements.txt | 1 + 2 files changed, 4 insertions(+) diff --git a/requirements-dev.txt b/requirements-dev.txt index 45e0ba840..01a572c50 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -19,3 +19,6 @@ bumpversion>=0.5.3 # Web sockets websocket-client==0.48.0 + +# lock JWT +PyJWT==1.7.1 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 85f94adb4..8d784044e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 ibm_cloud_sdk_core==1.7.3 +PyJWT==1.7.1 \ No newline at end of file From c646eea736e3415a7a2df203643475fb74957620 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Mon, 28 Dec 2020 22:50:15 +0000 Subject: [PATCH 301/455] =?UTF-8?q?Bump=20version:=205.0.1=20=E2=86=92=205?= =?UTF-8?q?.0.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index d958dace9..4318094c4 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.0.1 +current_version = 5.0.2 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 3d96b2761..6a92b2447 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '5.0.1' +__version__ = '5.0.2' diff --git a/setup.py b/setup.py index c4d7854c3..0972a926d 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '5.0.1' +__version__ = '5.0.2' if sys.argv[-1] == 'publish': From 8a6647636266f987816eb1d747782c07c3cfcba3 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Mon, 28 Dec 2020 22:50:15 +0000 Subject: [PATCH 302/455] chore(release): 5.0.2 release notes ## [5.0.2](https://github.com/watson-developer-cloud/python-sdk/compare/v5.0.1...v5.0.2) (2020-12-28) ### Bug Fixes * lock JWT version to 1.7.1 ([8fcdfc6](https://github.com/watson-developer-cloud/python-sdk/commit/8fcdfc64db1bcf6a230e8be80de6dfcad8e8811f)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 28 ++++++++++++++-------------- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a1ad2820..24178e063 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [5.0.2](https://github.com/watson-developer-cloud/python-sdk/compare/v5.0.1...v5.0.2) (2020-12-28) + + +### Bug Fixes + +* lock JWT version to 1.7.1 ([8fcdfc6](https://github.com/watson-developer-cloud/python-sdk/commit/8fcdfc64db1bcf6a230e8be80de6dfcad8e8811f)) + ## [5.0.1](https://github.com/watson-developer-cloud/python-sdk/compare/v5.0.0...v5.0.1) (2020-12-22) diff --git a/package-lock.json b/package-lock.json index 9543b222a..6f46cd63c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -26,25 +26,25 @@ } }, "@nodelib/fs.scandir": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.3.tgz", - "integrity": "sha512-eGmwYQn3gxo4r7jdQnkrrN6bY478C3P+a/y72IJukF8LjB6ZHeB3c+Ehacj3sYeSmUXGlnA67/PmbM9CVwL7Dw==", + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.4.tgz", + "integrity": "sha512-33g3pMJk3bg5nXbL/+CY6I2eJDzZAni49PfJnL5fghPTggPvBd/pFNSgJsdAgWptuFu7qq/ERvOYFlhvsLTCKA==", "requires": { - "@nodelib/fs.stat": "2.0.3", + "@nodelib/fs.stat": "2.0.4", "run-parallel": "^1.1.9" } }, "@nodelib/fs.stat": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.3.tgz", - "integrity": "sha512-bQBFruR2TAwoevBEd/NWMoAAtNGzTRgdrqnYCc7dhzfoNvqPzLyqlEQnzZ3kVnNrSp25iyxE00/3h2fqGAGArA==" + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.4.tgz", + "integrity": "sha512-IYlHJA0clt2+Vg7bccq+TzRdJvv19c2INqBSsoOLp1je7xjtr7J26+WXR72MCdvU9q1qTzIWDfhMf+DRvQJK4Q==" }, "@nodelib/fs.walk": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.4.tgz", - "integrity": "sha512-1V9XOY4rDW0rehzbrcqAmHnz8e7SKvX27gh8Gt2WgB0+pdzdiLV83p72kZPU+jvMbS1qU5mauP2iOvO8rhmurQ==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.6.tgz", + "integrity": "sha512-8Broas6vTtW4GIXTAHDoE32hnN2M5ykgCpWGbuXHQ15vEMqr23pB76e/GZcYsZCHALv50ktd24qhEyKr6wBtow==", "requires": { - "@nodelib/fs.scandir": "2.1.3", + "@nodelib/fs.scandir": "2.1.4", "fastq": "^1.6.0" } }, @@ -234,9 +234,9 @@ "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==" }, "@types/node": { - "version": "14.14.14", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.14.tgz", - "integrity": "sha512-UHnOPWVWV1z+VV8k6L1HhG7UbGBgIdghqF3l9Ny9ApPghbjICXkUJSd/b9gOgQfjM1r+37cipdw/HJ3F6ICEnQ==" + "version": "14.14.16", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.16.tgz", + "integrity": "sha512-naXYePhweTi+BMv11TgioE2/FXU4fSl29HAH1ffxVciNsH3rYXjNP2yM8wqmSm7jS20gM8TIklKiTen+1iVncw==" }, "@types/retry": { "version": "0.12.0", From aee0f75c5512974b860043dd390994372961ba0f Mon Sep 17 00:00:00 2001 From: Tim Gates Date: Wed, 30 Dec 2020 08:21:10 +1100 Subject: [PATCH 303/455] docs: fix simple typo, retunred -> returned There is a small typo in ibm_watson/discovery_v1.py. Should read `returned` rather than `retunred`. --- ibm_watson/discovery_v1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 4eb67664e..3dc4d4d50 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1815,7 +1815,7 @@ def query(self, parameter. :param bool spelling_suggestions: (optional) When `true` and the **natural_language_query** parameter is used, the **natural_languge_query** - parameter is spell checked. The most likely correction is retunred in the + parameter is spell checked. The most likely correction is returned in the **suggested_query** field of the response (if one exists). **Important:** this parameter is only valid when using the Cloud Pak version of Discovery. From 83d5f6a7ad4c69fc3c2dbecc6cadee0dc69eeadf Mon Sep 17 00:00:00 2001 From: Mamoon Raja Date: Fri, 8 Jan 2021 18:48:34 -0500 Subject: [PATCH 304/455] feat: upate core to use 3.3.6 --- requirements-dev.txt | 5 +---- requirements.txt | 3 +-- setup.py | 2 +- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index 01a572c50..c872f2b75 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ python_dotenv>=0.1.5;python_version!='3.2' pylint>=1.4.4 tox>=2.9.1 pytest-rerunfailures>=3.1 -ibm_cloud_sdk_core==1.7.3 +ibm_cloud_sdk_core==3.3.6 # code coverage coverage<5 @@ -19,6 +19,3 @@ bumpversion>=0.5.3 # Web sockets websocket-client==0.48.0 - -# lock JWT -PyJWT==1.7.1 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 8d784044e..cb4fc4a4e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 -ibm_cloud_sdk_core==1.7.3 -PyJWT==1.7.1 \ No newline at end of file +ibm_cloud_sdk_core==3.3.6 diff --git a/setup.py b/setup.py index 0972a926d..bc41cc797 100644 --- a/setup.py +++ b/setup.py @@ -64,7 +64,7 @@ def run_tests(self): version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==1.7.3'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core>=3.3.6'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='IBM Watson', From 838c40c3788497c2edef21717fd021d5a1cd7b05 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 12 Jan 2021 03:12:16 +0000 Subject: [PATCH 305/455] =?UTF-8?q?Bump=20version:=205.0.2=20=E2=86=92=205?= =?UTF-8?q?.1.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 4318094c4..14256294d 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.0.2 +current_version = 5.1.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 6a92b2447..a5e451313 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '5.0.2' +__version__ = '5.1.0' diff --git a/setup.py b/setup.py index bc41cc797..272147bb6 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '5.0.2' +__version__ = '5.1.0' if sys.argv[-1] == 'publish': From 752fd37a87e87323bb4383e5858f5efdbf6cbe3e Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 12 Jan 2021 03:12:16 +0000 Subject: [PATCH 306/455] chore(release): 5.1.0 release notes # [5.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v5.0.2...v5.1.0) (2021-01-12) ### Features * upate core to use 3.3.6 ([83d5f6a](https://github.com/watson-developer-cloud/python-sdk/commit/83d5f6a7ad4c69fc3c2dbecc6cadee0dc69eeadf)) --- CHANGELOG.md | 7 +++++++ package-lock.json | 32 ++++++++++++++++---------------- 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24178e063..608995fe1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +# [5.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v5.0.2...v5.1.0) (2021-01-12) + + +### Features + +* upate core to use 3.3.6 ([83d5f6a](https://github.com/watson-developer-cloud/python-sdk/commit/83d5f6a7ad4c69fc3c2dbecc6cadee0dc69eeadf)) + ## [5.0.2](https://github.com/watson-developer-cloud/python-sdk/compare/v5.0.1...v5.0.2) (2020-12-28) diff --git a/package-lock.json b/package-lock.json index 6f46cd63c..d0b743bd0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -90,14 +90,14 @@ } }, "@octokit/openapi-types": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-2.0.1.tgz", - "integrity": "sha512-9AuC04PUnZrjoLiw3uPtwGh9FE4Q3rTqs51oNlQ0rkwgE8ftYsOC+lsrQyvCvWm85smBbSc0FNRKKumvGyb44Q==" + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-2.2.0.tgz", + "integrity": "sha512-274lNUDonw10kT8wHg8fCcUc1ZjZHbWv0/TbAwb0ojhBQqZYc1cQ/4yqTVTtPMDeZ//g7xVEYe/s3vURkRghPg==" }, "@octokit/plugin-paginate-rest": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.6.2.tgz", - "integrity": "sha512-3Dy7/YZAwdOaRpGQoNHPeT0VU1fYLpIUdPyvR37IyFLgd6XSij4j9V/xN/+eSjF2KKvmfIulEh9LF1tRPjIiDA==", + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.7.0.tgz", + "integrity": "sha512-+zARyncLjt9b0FjqPAbJo4ss7HOlBi1nprq+cPlw5vu2+qjy7WvlXhtXFdRHQbSL1Pt+bfAKaLADEkkvg8sP8w==", "requires": { "@octokit/types": "^6.0.1" } @@ -153,11 +153,11 @@ } }, "@octokit/types": { - "version": "6.1.2", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.1.2.tgz", - "integrity": "sha512-LPCpcLbcky7fWfHCTuc7tMiSHFpFlrThJqVdaHgowBTMS0ijlZFfonQC/C1PrZOjD4xRCYgBqH9yttEATGE/nw==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.2.1.tgz", + "integrity": "sha512-jHs9OECOiZxuEzxMZcXmqrEO8GYraHF+UzNVH2ACYh8e/Y7YoT+hUf9ldvVd6zIvWv4p3NdxbQ0xx3ku5BnSiA==", "requires": { - "@octokit/openapi-types": "^2.0.1", + "@octokit/openapi-types": "^2.2.0", "@types/node": ">= 8" } }, @@ -234,9 +234,9 @@ "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==" }, "@types/node": { - "version": "14.14.16", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.16.tgz", - "integrity": "sha512-naXYePhweTi+BMv11TgioE2/FXU4fSl29HAH1ffxVciNsH3rYXjNP2yM8wqmSm7jS20gM8TIklKiTen+1iVncw==" + "version": "14.14.20", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.20.tgz", + "integrity": "sha512-Y93R97Ouif9JEOWPIUyU+eyIdyRqQR0I8Ez1dzku4hDx34NWh4HbtIc3WNzwB1Y9ULvNGeu5B8h8bVL5cAk4/A==" }, "@types/retry": { "version": "0.12.0", @@ -449,9 +449,9 @@ } }, "globby": { - "version": "11.0.1", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.1.tgz", - "integrity": "sha512-iH9RmgwCmUJHi2z5o2l3eTtGBtXek1OYlHrbcxOYugyHLmAsZrPj43OtHThd62Buh/Vv6VyCBD2bdyWcGNQqoQ==", + "version": "11.0.2", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.2.tgz", + "integrity": "sha512-2ZThXDvvV8fYFRVIxnrMQBipZQDr7MxKAmQK1vujaj9/7eF0efG7BPUKJ7jP7G5SLF37xKDXvO4S/KKLj/Z0og==", "requires": { "array-union": "^2.1.0", "dir-glob": "^3.0.1", From d3438d94cb4e062d0443f2dfa8e673e5cc98f9a0 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Fri, 22 Jan 2021 15:00:22 -0600 Subject: [PATCH 307/455] docs: Added deprecation notice for C&C and watsonplatform.net urls [skip ci] --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index b6db673ce..84cb23231 100755 --- a/README.md +++ b/README.md @@ -43,6 +43,9 @@ Python client library to quickly get started with the various [Watson APIs][wdc] ## ANNOUNCEMENTS! +### Updating endpoint URLs from watsonplatform.net +Watson API endpoint URLs at watsonplatform.net are changing and will not work after they are retired. Update your calls to use the newer endpoint URLs. Please see https://cloud.ibm.com/docs/watson?topic=watson-endpoint-change for details. + ### Personality Insights deprecation IBM Watson™ Personality Insights is discontinued. For a period of one year from 1 December 2020, you will still be able to use Watson Personality Insights. However, as of 1 December 2021, the offering will no longer be available. @@ -51,6 +54,9 @@ As an alternative, we encourage you to consider migrating to IBM Watson™ [Natu ### Visual Recognition deprecation IBM Watson™ Visual Recognition is discontinued. Existing instances are supported until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance that is provisioned on 1 December 2021 will be deleted. +### Compare and Comply deprecation +Deprecated: IBM Watson™ Compare and Comply is discontinued. Existing instances are supported until 30 November 2021, but as of 1 December 2020, you can't create instances. Any instance that exists on 30 November 2021 will be deleted. Consider migrating to Watson Discovery Premium on IBM Cloud for your Compare and Comply use cases. To start the migration process, visit https://ibm.biz/contact-wdc-premium. + ## Before you begin * You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support `python 3.5` and above From fe9450630933ab28f91095aa90d5c2fc4564ff6d Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Fri, 22 Jan 2021 15:26:33 -0600 Subject: [PATCH 308/455] docs: updated deprecation copy [skip ci] --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 84cb23231..9f45d250b 100755 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ Python client library to quickly get started with the various [Watson APIs][wdc] ## ANNOUNCEMENTS! ### Updating endpoint URLs from watsonplatform.net -Watson API endpoint URLs at watsonplatform.net are changing and will not work after they are retired. Update your calls to use the newer endpoint URLs. Please see https://cloud.ibm.com/docs/watson?topic=watson-endpoint-change for details. +Watson API endpoint URLs at watsonplatform.net are changing and will not work after 26 May 2021. Update your calls to use the newer endpoint URLs. For more information, see https://cloud.ibm.com/docs/watson?topic=watson-endpoint-change. ### Personality Insights deprecation IBM Watson™ Personality Insights is discontinued. For a period of one year from 1 December 2020, you will still be able to use Watson Personality Insights. However, as of 1 December 2021, the offering will no longer be available. @@ -55,7 +55,7 @@ As an alternative, we encourage you to consider migrating to IBM Watson™ [Natu IBM Watson™ Visual Recognition is discontinued. Existing instances are supported until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance that is provisioned on 1 December 2021 will be deleted. ### Compare and Comply deprecation -Deprecated: IBM Watson™ Compare and Comply is discontinued. Existing instances are supported until 30 November 2021, but as of 1 December 2020, you can't create instances. Any instance that exists on 30 November 2021 will be deleted. Consider migrating to Watson Discovery Premium on IBM Cloud for your Compare and Comply use cases. To start the migration process, visit https://ibm.biz/contact-wdc-premium. +IBM Watson™ Compare and Comply is discontinued. Existing instances are supported until 30 November 2021, but as of 1 December 2020, you can't create instances. Any instance that exists on 30 November 2021 will be deleted. Consider migrating to Watson Discovery Premium on IBM Cloud for your Compare and Comply use cases. To start the migration process, visit https://ibm.biz/contact-wdc-premium. ## Before you begin * You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support `python 3.5` and above From 868913754a9ce647779d55e939b5cdba5b3bed52 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 4 Feb 2021 12:44:24 -0500 Subject: [PATCH 309/455] Update README.md --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 9f45d250b..bb28a1649 100755 --- a/README.md +++ b/README.md @@ -387,19 +387,19 @@ Every SDK call returns a response with a transaction ID in the `X-Global-Transac ### Suceess ```python -from ibm_watson import MyService +from ibm_watson import AssistantV1 -service = MyService(authenticator=my_authenticator) +service = AssistantV1(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 +from ibm_watson import AssistantV1, ApiException try: - service = MyService(authenticator=my_authenticators) + service = AssistantV1(authenticator={my_authenticator}) service.my_service_call() except ApiException as e: print(e.global_transaction_id) @@ -410,9 +410,9 @@ except ApiException as e: However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace `` in the following example with a unique transaction ID. ```python -from ibm_watson import MyService +from ibm_watson import AssistantV1 -service = MyService(authenticator=my_authenticator) +service = AssistantV1(authenticator={my_authenticator}) service.my_service_call(headers={'X-Global-Transaction-Id': ''}) ``` From d0069376dcd1e23076c12130feeea1b20010de06 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Tue, 2 Mar 2021 15:10:23 -0700 Subject: [PATCH 310/455] fix(compare-comply): add deprecation notice for CC also updates .gitignore for .venv --- .gitignore | 1 + ibm_watson/compare_comply_v1.py | 3 +++ 2 files changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 35ef69fba..c9e5714d6 100644 --- a/.gitignore +++ b/.gitignore @@ -48,6 +48,7 @@ coverage.xml # virtual env venv/ +.venv/ # python 3 virtual env python3/ diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 1a77ebed3..5320f9de7 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -59,6 +59,9 @@ def __init__( Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. """ + print( + 'warning: On 30 November 2021, Compare and Comply will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk#compare-and-comply-deprecation.' + ) if version is None: raise ValueError('version must be provided') From 1292076590b96ecb807bf23d7cb82225ddc971b1 Mon Sep 17 00:00:00 2001 From: Michael G Mosca Date: Mon, 17 May 2021 07:14:26 -0400 Subject: [PATCH 311/455] ci: 9259 gha (#786) * ci: gha implement GHA * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix --- .github/workflows/build-test.yml | 52 ++++++++++++++++++++++ .github/workflows/deploy.yml | 74 ++++++++++++++++++++++++++++++++ README.md | 6 ++- docs/publish_gha.sh | 31 +++++++++++++ 4 files changed, 162 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/build-test.yml create mode 100644 .github/workflows/deploy.yml create mode 100755 docs/publish_gha.sh diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml new file mode 100644 index 000000000..171875d0e --- /dev/null +++ b/.github/workflows/build-test.yml @@ -0,0 +1,52 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support documentation. +# This workflow will do a clean install of python dependencies, build the source code and run tests across different versions of python +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions + +name: Build and Test + +on: + push: + branches: [ '**' ] + pull_request: + branches: [ master ] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + build_test: + name: Build and Test on Python ${{ matrix.python-version }} and ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + python-version: ['3.5', '3.6', '3.7', '3.8'] + os: [ubuntu-latest] + + steps: + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + pip3 install -r requirements.txt + pip3 install -r requirements-dev.txt + pip3 install --editable . + - name: Execute Python unit tests for code coverage + if: matrix.python-version == '3.5' + run: | + pip3 install -U python-dotenv + py.test --reruns 3 --cov=ibm_watson + - name: Upload coverage to Codecov + if: matrix.python-version == '3.5' + uses: codecov/codecov-action@v1 + with: + name: py${{ matrix.python-version }}-${{ matrix.os }} + - name: Execute Python unit tests + if: matrix.python-version != '3.5' + run: | + pip3 install -U python-dotenv + py.test diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml new file mode 100644 index 000000000..314cb57a9 --- /dev/null +++ b/.github/workflows/deploy.yml @@ -0,0 +1,74 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support documentation. +# This workflow will download a prebuilt Python version, install dependencies, build and deploy/publish a new release +# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions + +name: Deploy and Publish + +on: + workflow_run: + workflows: ["Build and Test"] + branches: [ master ] + types: + - completed + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + deploy: + if: "!contains(github.event.head_commit.message, 'skip ci')" + name: Deploy and Publish + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + with: + persist-credentials: false + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.8' + - name: Setup Node + uses: actions/setup-node@v1 + with: + node-version: 12 + - name: Install dependencies + run: | + pip3 install -r requirements.txt + pip3 install -r requirements-dev.txt + pip3 install --editable . + - name: Install Semantic Release dependencies + run: | + sudo apt-get install bumpversion + npm install -g semantic-release + npm install -g @semantic-release/changelog + npm install -g @semantic-release/exec + npm install -g @semantic-release/git + npm install -g @semantic-release/github + npm install -g @semantic-release/commit-analyzer + npm install -g @semantic-release/release-notes-generator + - name: Publish js docs + if: github.event.workflow_run.conclusion == 'success' && startsWith(github.ref, 'refs/tags') + env: + GH_TOKEN: ${{ secrets.GH_TOKEN }} + GHA_BRANCH: ${{ github.ref }} # non PR only need to get last part + GHA_COMMIT: ${{ github.sha }} + run: | + sudo apt-get install python3-sphinx + docs/publish_gha.sh + - name: Publish to Git Releases and Tags + if: ${{ github.event.workflow_run.conclusion == 'success' }} + env: + GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} + NPM_TOKEN: ${{ secrets.NPM_TOKEN }} + run: npx semantic-release # --dry-run + - name: Publish a Python distribution to PyPI # must have built dist before + if: github.event.workflow_run.conclusion == 'success' && github.event_name == 'push' && startsWith(github.ref, 'refs/tags') + uses: pypa/gh-action-pypi-publish@master + with: + password: ${{ secrets.PYPI_PASSWORD }} + user: watson-devex + repository_url: https://upload.pypi.org/legacy + verbose: false \ No newline at end of file diff --git a/README.md b/README.md index bb28a1649..381e4b659 100755 --- a/README.md +++ b/README.md @@ -1,10 +1,14 @@ # Watson Developer Cloud Python SDK -[![Build Status](https://travis-ci.org/watson-developer-cloud/python-sdk.svg?branch=master)](https://travis-ci.org/watson-developer-cloud/python-sdk) +[![Build and Test](https://github.com/watson-developer-cloud/python-sdk/workflows/Build%20and%20Test/badge.svg?branch=master)](https://github.com/watson-developer-cloud/python-sdk/actions?query=workflow%3A"Build+and+Test") +[![Deploy and Publish](https://github.com/watson-developer-cloud/python-sdk/workflows/Deploy%20and%20Publish/badge.svg?branch=master)](https://github.com/watson-developer-cloud/python-sdk/actions?query=workflow%3A%22Deploy+and+Publish%22) [![Slack](https://wdc-slack-inviter.mybluemix.net/badge.svg)](https://wdc-slack-inviter.mybluemix.net) [![Latest Stable Version](https://img.shields.io/pypi/v/ibm-watson.svg)](https://pypi.python.org/pypi/ibm-watson) [![CLA assistant](https://cla-assistant.io/readme/badge/watson-developer-cloud/python-sdk)](https://cla-assistant.io/watson-developer-cloud/python-sdk) +## Deprecated builds +[![Build Status](https://travis-ci.org/watson-developer-cloud/python-sdk.svg?branch=master)](https://travis-ci.org/watson-developer-cloud/python-sdk) + Python client library to quickly get started with the various [Watson APIs][wdc] services.
diff --git a/docs/publish_gha.sh b/docs/publish_gha.sh new file mode 100755 index 000000000..ff1ff9e98 --- /dev/null +++ b/docs/publish_gha.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# checking the build/job numbers allows it to only +# publish once even though we test against multiple python versions + +[[ -z "$GHA_BRANCH" ]] && { echo "GHA_BRANCH cannot be null" ; exit 1; } +[[ -z "$GH_TOKEN" ]] && { echo "GH_TOKEN cannot be null" ; exit 1; } + +cd $(dirname $0) +pwd + +echo "Create Docs" +make document +echo "Publishing Docs..." + +git config --global user.email "watdevex@us.ibm.com" +git config --global user.name "watdevex" +git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/watson-developer-cloud/python-sdk.git gh-pages > /dev/null + +pushd gh-pages + # on tagged builds, $GHA_BRANCH is the tag (e.g. v1.2.3), otherwise it's the branch name (e.g. master) + rm -rf $GHA_BRANCH + cp -Rf ../_build/html/ $GHA_BRANCH + ../generate_index_html.sh > index.html + + git add -f . + git commit -m "Docs for $GHA_BRANCH ($GHA_COMMIT)" + git push -fq origin gh-pages > /dev/null +popd + +echo -e "Published Docs for $GHA_BRANCH to gh-pages.\n" + From 9869e908b89da082696c8a669aed42ff66951269 Mon Sep 17 00:00:00 2001 From: Michael G Mosca Date: Mon, 17 May 2021 19:20:25 -0400 Subject: [PATCH 312/455] ci: Gha fix (#787) * ci: try to fix hang * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix --- .github/workflows/build-test.yml | 2 +- .github/workflows/deploy.yml | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 171875d0e..657f5dd09 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -33,7 +33,7 @@ jobs: - name: Install dependencies run: | pip3 install -r requirements.txt - pip3 install -r requirements-dev.txt + pip3 install -r requirements-dev.txt --use-deprecated=legacy-resolver pip3 install --editable . - name: Execute Python unit tests for code coverage if: matrix.python-version == '3.5' diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 314cb57a9..d0d179534 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -37,7 +37,7 @@ jobs: - name: Install dependencies run: | pip3 install -r requirements.txt - pip3 install -r requirements-dev.txt + pip3 install -r requirements-dev.txt --use-deprecated=legacy-resolver pip3 install --editable . - name: Install Semantic Release dependencies run: | @@ -64,6 +64,8 @@ jobs: GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN }} run: npx semantic-release # --dry-run + - name: Build binary wheel and a source tarball + run: python setup.py sdist - name: Publish a Python distribution to PyPI # must have built dist before if: github.event.workflow_run.conclusion == 'success' && github.event_name == 'push' && startsWith(github.ref, 'refs/tags') uses: pypa/gh-action-pypi-publish@master From a6d2165473a2f0460a4ab7235c6ea5977194e2a5 Mon Sep 17 00:00:00 2001 From: Michael G Mosca Date: Tue, 18 May 2021 07:15:45 -0400 Subject: [PATCH 313/455] ci: go dryrun for testing later --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index d0d179534..f8691ef31 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -63,7 +63,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN }} - run: npx semantic-release # --dry-run + run: npx semantic-release --dry-run - name: Build binary wheel and a source tarball run: python setup.py sdist - name: Publish a Python distribution to PyPI # must have built dist before From ac146a1efc5e148a636b17540399898c74222a29 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 19 May 2021 14:02:59 -0400 Subject: [PATCH 314/455] feat(assistantv1): generation release changes --- ibm_watson/assistant_v1.py | 1429 +++++++++++++++++++++++---- test/unit/test_assistant_v1.py | 1663 ++++++++++++++++++++++---------- 2 files changed, 2378 insertions(+), 714 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 158fb1597..a5f1d9679 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2019, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201221-115123 +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -87,6 +87,7 @@ def message(self, alternate_intents: bool = None, context: 'Context' = None, output: 'OutputData' = None, + user_id: str = None, nodes_visited_details: bool = None, **kwargs) -> DetailedResponse: """ @@ -116,6 +117,16 @@ def message(self, :param OutputData output: (optional) An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the workspace. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.conversation_id**. + **Note:** This property is the same as the **user_id** property in the + context metadata. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. :param bool nodes_visited_details: (optional) Whether to include additional diagnostic information about the dialog nodes that were visited during processing of the message. @@ -153,7 +164,8 @@ def message(self, 'entities': entities, 'alternate_intents': alternate_intents, 'context': context, - 'output': output + 'output': output, + 'user_id': user_id } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -191,7 +203,7 @@ def bulk_classify(self, Send multiple user inputs to a workspace in a single request and receive information about the intents and entities recognized in each input. This method is useful for testing and comparing the performance of different workspaces. - This method is available only with Premium plans. + This method is available only with Enterprise with Data Isolation plans. :param str workspace_id: Unique identifier of the workspace. :param List[BulkClassifyUtterance] input: (optional) An array of input @@ -2793,20 +2805,21 @@ def create_dialog_node(self, the **[Update workspace](#update-workspace)** method instead. :param str workspace_id: Unique identifier of the workspace. - :param str dialog_node: The dialog node ID. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and - dot characters. + :param str dialog_node: The unique ID of the dialog node. This is an + internal identifier used to refer to the dialog node from other dialog + nodes and in the diagnostic information included with message responses. + This string can contain only Unicode alphanumeric, space, underscore, + hyphen, and dot characters. :param str description: (optional) The description of the dialog node. This string cannot contain carriage return, newline, or tab characters. :param str conditions: (optional) The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters. - :param str parent: (optional) The ID of the parent dialog node. This + :param str parent: (optional) The unique ID of the parent dialog node. This property is omitted if the dialog node has no parent. - :param str previous_sibling: (optional) The ID of the previous sibling - dialog node. This property is omitted if the dialog node has no previous - sibling. + :param str previous_sibling: (optional) The unique ID of the previous + sibling dialog node. This property is omitted if the dialog node has no + previous 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/assistant?topic=assistant-dialog-overview#dialog-overview-responses). @@ -2815,10 +2828,14 @@ def create_dialog_node(self, :param dict metadata: (optional) The metadata for the dialog node. :param DialogNodeNextStep next_step: (optional) The next step to execute following this dialog node. - :param str title: (optional) The alias used to identify the dialog node. - This string must conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and - dot characters. + :param str title: (optional) A human-readable name for the dialog node. If + the node is included in disambiguation, this title is used to populate the + **label** property of the corresponding suggestion in the `suggestion` + response type (unless it is overridden by the **user_label** property). The + title is also used to populate the **topic** property in the + `connect_to_agent` response type. + This string can contain only Unicode alphanumeric, space, underscore, + hyphen, and dot characters. :param str type: (optional) How the dialog node is processed. :param str event_name: (optional) How an `event_handler` node is processed. :param str variable: (optional) The location in the dialog context where @@ -2832,7 +2849,9 @@ def create_dialog_node(self, :param str digress_out_slots: (optional) Whether the user can digress to top-level nodes while filling out slots. :param str user_label: (optional) A label that can be displayed externally - to describe the purpose of the node to users. + to describe the purpose of the node to users. If set, this label is used to + identify the node in disambiguation responses (overriding the value of the + **title** property). :param bool disambiguation_opt_out: (optional) Whether the dialog node should be excluded from disambiguation suggestions. Valid only when **type**=`standard` or `frame`. @@ -2918,7 +2937,8 @@ def get_dialog_node(self, Get information about a dialog node. :param str workspace_id: Unique identifier of the workspace. - :param str dialog_node: The dialog node ID (for example, `get_order`). + :param str dialog_node: The dialog node ID (for example, + `node_1_1479323581900`). :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 @@ -2988,21 +3008,24 @@ def update_dialog_node(self, the **[Update workspace](#update-workspace)** method instead. :param str workspace_id: Unique identifier of the workspace. - :param str dialog_node: The dialog node ID (for example, `get_order`). - :param str new_dialog_node: (optional) The dialog node ID. This string must - conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and - dot characters. + :param str dialog_node: The dialog node ID (for example, + `node_1_1479323581900`). + :param str new_dialog_node: (optional) The unique ID of the dialog node. + This is an internal identifier used to refer to the dialog node from other + dialog nodes and in the diagnostic information included with message + responses. + This string can contain only Unicode alphanumeric, space, underscore, + hyphen, and dot characters. :param str new_description: (optional) The description of the dialog node. This string cannot contain carriage return, newline, or tab characters. :param str new_conditions: (optional) The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters. - :param str new_parent: (optional) The ID of the parent dialog node. This - property is omitted if the dialog node has no parent. - :param str new_previous_sibling: (optional) The ID of the previous sibling - dialog node. This property is omitted if the dialog node has no previous - sibling. + :param str new_parent: (optional) The unique ID of the parent dialog node. + This property is omitted if the dialog node has no parent. + :param str new_previous_sibling: (optional) The unique ID of the previous + sibling dialog node. This property is omitted if the dialog node has no + previous 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/assistant?topic=assistant-dialog-overview#dialog-overview-responses). @@ -3011,10 +3034,14 @@ def update_dialog_node(self, :param dict new_metadata: (optional) The metadata for the dialog node. :param DialogNodeNextStep new_next_step: (optional) The next step to execute following this dialog node. - :param str new_title: (optional) The alias used to identify the dialog - node. This string must conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and - dot characters. + :param str new_title: (optional) A human-readable name for the dialog node. + If the node is included in disambiguation, this title is used to populate + the **label** property of the corresponding suggestion in the `suggestion` + response type (unless it is overridden by the **user_label** property). The + title is also used to populate the **topic** property in the + `connect_to_agent` response type. + This string can contain only Unicode alphanumeric, space, underscore, + hyphen, and dot characters. :param str new_type: (optional) How the dialog node is processed. :param str new_event_name: (optional) How an `event_handler` node is processed. @@ -3029,7 +3056,9 @@ def update_dialog_node(self, :param str new_digress_out_slots: (optional) Whether the user can digress to top-level nodes while filling out slots. :param str new_user_label: (optional) A label that can be displayed - externally to describe the purpose of the node to users. + externally to describe the purpose of the node to users. If set, this label + is used to identify the node in disambiguation responses (overriding the + value of the **title** property). :param bool new_disambiguation_opt_out: (optional) Whether the dialog node should be excluded from disambiguation suggestions. Valid only when **type**=`standard` or `frame`. @@ -3111,7 +3140,8 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, Delete a dialog node from a workspace. :param str workspace_id: Unique identifier of the workspace. - :param str dialog_node: The dialog node ID (for example, `get_order`). + :param str dialog_node: The dialog node ID (for example, + `node_1_1479323581900`). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3162,6 +3192,7 @@ def list_logs(self, List log events in a workspace. List the events from the log of a specific workspace. + This method requires Manager access. :param str workspace_id: Unique identifier of the workspace. :param str sort: (optional) How to sort the returned log events. You can @@ -3284,6 +3315,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: with a request that passes data. For more information about personal data and customer IDs, see [Information security](https://cloud.ibm.com/docs/assistant?topic=assistant-information-security#information-security). + **Note:** This operation is intended only for deleting data associated with a + single specific customer, not for deleting data associated with multiple customers + or for any other purpose. For more information, see [Labeling and deleting data in + Watson + Assistant](https://cloud.ibm.com/docs/assistant?topic=assistant-information-security#information-security-gdpr-wa). :param str customer_id: The customer ID for which all data is to be deleted. @@ -3765,6 +3801,185 @@ def __ne__(self, other: 'CaptureGroup') -> bool: return not self == other +class ChannelTransferInfo(): + """ + Information used by an integration to transfer the conversation to a different + channel. + + :attr ChannelTransferTarget target: An object specifying target channels + available for the transfer. Each property of this object represents an available + transfer target. Currently, the only supported property is **chat**, + representing the web chat integration. + """ + + def __init__(self, target: 'ChannelTransferTarget') -> None: + """ + Initialize a ChannelTransferInfo object. + + :param ChannelTransferTarget target: An object specifying target channels + available for the transfer. Each property of this object represents an + available transfer target. Currently, the only supported property is + **chat**, representing the web chat integration. + """ + self.target = target + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': + """Initialize a ChannelTransferInfo object from a json dictionary.""" + args = {} + if 'target' in _dict: + args['target'] = ChannelTransferTarget.from_dict( + _dict.get('target')) + else: + raise ValueError( + 'Required property \'target\' not present in ChannelTransferInfo JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ChannelTransferInfo 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, 'target') and self.target is not None: + _dict['target'] = self.target.to_dict() + 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 ChannelTransferInfo object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ChannelTransferInfo') -> 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: 'ChannelTransferInfo') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ChannelTransferTarget(): + """ + An object specifying target channels available for the transfer. Each property of this + object represents an available transfer target. Currently, the only supported property + is **chat**, representing the web chat integration. + + :attr ChannelTransferTargetChat chat: (optional) Information for transferring to + the web chat integration. + """ + + def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: + """ + Initialize a ChannelTransferTarget object. + + :param ChannelTransferTargetChat chat: (optional) Information for + transferring to the web chat integration. + """ + self.chat = chat + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': + """Initialize a ChannelTransferTarget object from a json dictionary.""" + args = {} + if 'chat' in _dict: + args['chat'] = ChannelTransferTargetChat.from_dict( + _dict.get('chat')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ChannelTransferTarget 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, 'chat') and self.chat is not None: + _dict['chat'] = self.chat.to_dict() + 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 ChannelTransferTarget object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ChannelTransferTarget') -> 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: 'ChannelTransferTarget') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ChannelTransferTargetChat(): + """ + Information for transferring to the web chat integration. + + :attr str url: (optional) The URL of the target web chat. + """ + + def __init__(self, *, url: str = None) -> None: + """ + Initialize a ChannelTransferTargetChat object. + + :param str url: (optional) The URL of the target web chat. + """ + self.url = url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': + """Initialize a ChannelTransferTargetChat object from a json dictionary.""" + args = {} + if 'url' in _dict: + args['url'] = _dict.get('url') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ChannelTransferTargetChat 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, 'url') and self.url is not None: + _dict['url'] = self.url + 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 ChannelTransferTargetChat object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ChannelTransferTargetChat') -> 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: 'ChannelTransferTargetChat') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Context(): """ State information for the conversation. To maintain state, include the context from @@ -4383,18 +4598,20 @@ class DialogNode(): """ DialogNode. - :attr str dialog_node: The dialog node ID. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot - characters. + :attr str dialog_node: The unique ID of the dialog node. This is an internal + identifier used to refer to the dialog node from other dialog nodes and in the + diagnostic information included with message responses. + This string can contain only Unicode alphanumeric, space, underscore, hyphen, + and dot characters. :attr str description: (optional) The description of the dialog node. This string cannot contain carriage return, newline, or tab characters. :attr str conditions: (optional) The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters. - :attr str parent: (optional) The ID of the parent dialog node. This property is - omitted if the dialog node has no parent. - :attr str previous_sibling: (optional) The ID of the previous sibling dialog - node. This property is omitted if the dialog node has no previous sibling. + :attr str parent: (optional) The unique ID of the parent dialog node. This + property is omitted if the dialog node has no parent. + :attr str previous_sibling: (optional) The unique ID of the previous sibling + dialog 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/assistant?topic=assistant-dialog-overview#dialog-overview-responses). @@ -4402,10 +4619,13 @@ class DialogNode(): :attr dict metadata: (optional) The metadata for the dialog node. :attr DialogNodeNextStep next_step: (optional) The next step to execute following this dialog node. - :attr str title: (optional) The alias used to identify the dialog node. This - string must conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and dot - characters. + :attr str title: (optional) A human-readable name for the dialog node. If the + node is included in disambiguation, this title is used to populate the **label** + property of the corresponding suggestion in the `suggestion` response type + (unless it is overridden by the **user_label** property). The title is also used + to populate the **topic** property in the `connect_to_agent` response type. + This string can contain only Unicode alphanumeric, space, underscore, hyphen, + and dot characters. :attr str type: (optional) How the dialog node is processed. :attr str event_name: (optional) How an `event_handler` node is processed. :attr str variable: (optional) The location in the dialog context where output @@ -4419,7 +4639,9 @@ class DialogNode(): :attr str digress_out_slots: (optional) Whether the user can digress to top-level nodes while filling out slots. :attr str user_label: (optional) A label that can be displayed externally to - describe the purpose of the node to users. + describe the purpose of the node to users. If set, this label is used to + identify the node in disambiguation responses (overriding the value of the + **title** property). :attr bool disambiguation_opt_out: (optional) Whether the dialog node should be excluded from disambiguation suggestions. Valid only when **type**=`standard` or `frame`. @@ -4456,20 +4678,21 @@ def __init__(self, """ Initialize a DialogNode object. - :param str dialog_node: The dialog node ID. This string must conform to the - following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and - dot characters. + :param str dialog_node: The unique ID of the dialog node. This is an + internal identifier used to refer to the dialog node from other dialog + nodes and in the diagnostic information included with message responses. + This string can contain only Unicode alphanumeric, space, underscore, + hyphen, and dot characters. :param str description: (optional) The description of the dialog node. This string cannot contain carriage return, newline, or tab characters. :param str conditions: (optional) The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters. - :param str parent: (optional) The ID of the parent dialog node. This + :param str parent: (optional) The unique ID of the parent dialog node. This property is omitted if the dialog node has no parent. - :param str previous_sibling: (optional) The ID of the previous sibling - dialog node. This property is omitted if the dialog node has no previous - sibling. + :param str previous_sibling: (optional) The unique ID of the previous + sibling dialog node. This property is omitted if the dialog node has no + previous 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/assistant?topic=assistant-dialog-overview#dialog-overview-responses). @@ -4478,10 +4701,14 @@ def __init__(self, :param dict metadata: (optional) The metadata for the dialog node. :param DialogNodeNextStep next_step: (optional) The next step to execute following this dialog node. - :param str title: (optional) The alias used to identify the dialog node. - This string must conform to the following restrictions: - - It can contain only Unicode alphanumeric, space, underscore, hyphen, and - dot characters. + :param str title: (optional) A human-readable name for the dialog node. If + the node is included in disambiguation, this title is used to populate the + **label** property of the corresponding suggestion in the `suggestion` + response type (unless it is overridden by the **user_label** property). The + title is also used to populate the **topic** property in the + `connect_to_agent` response type. + This string can contain only Unicode alphanumeric, space, underscore, + hyphen, and dot characters. :param str type: (optional) How the dialog node is processed. :param str event_name: (optional) How an `event_handler` node is processed. :param str variable: (optional) The location in the dialog context where @@ -4495,7 +4722,9 @@ def __init__(self, :param str digress_out_slots: (optional) Whether the user can digress to top-level nodes while filling out slots. :param str user_label: (optional) A label that can be displayed externally - to describe the purpose of the node to users. + to describe the purpose of the node to users. If set, this label is used to + identify the node in disambiguation responses (overriding the value of the + **title** property). :param bool disambiguation_opt_out: (optional) Whether the dialog node should be excluded from disambiguation suggestions. Valid only when **type**=`standard` or `frame`. @@ -4987,8 +5216,8 @@ class DialogNodeNextStep(): - `skip_all_slots` If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. - :attr str dialog_node: (optional) The ID of the dialog node to process next. - This parameter is required if **behavior**=`jump_to`. + :attr str dialog_node: (optional) The unique ID of the dialog node to process + next. This parameter is required if **behavior**=`jump_to`. :attr str selector: (optional) Which part of the dialog node to process next. """ @@ -5021,8 +5250,8 @@ def __init__(self, - `skip_all_slots` If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. - :param str dialog_node: (optional) The ID of the dialog node to process - next. This parameter is required if **behavior**=`jump_to`. + :param str dialog_node: (optional) The unique ID of the dialog node to + process next. This parameter is required if **behavior**=`jump_to`. :param str selector: (optional) Which part of the dialog node to process next. """ @@ -5297,7 +5526,9 @@ def __init__(self) -> None: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill' + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' ])) raise Exception(msg) @@ -5316,7 +5547,9 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputGeneric': 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill' + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' ])) raise Exception(msg) @@ -5328,6 +5561,8 @@ def _from_dict(cls, _dict: Dict): @classmethod def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping = {} + mapping[ + 'channel_transfer'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer' mapping[ 'connect_to_agent'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent' mapping[ @@ -5340,6 +5575,8 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: 'search_skill'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill' mapping[ 'text'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText' + mapping[ + 'user_defined'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' disc_value = _dict.get('response_type') if disc_value is None: raise ValueError( @@ -5643,8 +5880,8 @@ class DialogNodeVisitedDetails(): """ DialogNodeVisitedDetails. - :attr str dialog_node: (optional) A dialog node that was triggered during - processing of the input message. + :attr str dialog_node: (optional) The unique ID of a dialog node that was + triggered during processing of the input message. :attr str title: (optional) The title of the dialog node. :attr str conditions: (optional) The conditions that trigger the dialog node. """ @@ -5657,8 +5894,8 @@ def __init__(self, """ Initialize a DialogNodeVisitedDetails object. - :param str dialog_node: (optional) A dialog node that was triggered during - processing of the input message. + :param str dialog_node: (optional) The unique ID of a dialog node that was + triggered during processing of the input message. :param str title: (optional) The title of the dialog node. :param str conditions: (optional) The conditions that trigger the dialog node. @@ -5720,15 +5957,15 @@ class DialogSuggestion(): :attr str label: The user-facing label for the disambiguation option. This label is taken from the **title** or **user_label** property of the corresponding - dialog node, depending on the disambiguation options. + dialog node. :attr DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. :attr dict output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. - :attr str dialog_node: (optional) The ID of the dialog node that the **label** - property is taken from. The **label** property is populated using the value of - the dialog node's **user_label** property. + :attr str dialog_node: (optional) The unique ID of the dialog node that the + **label** property is taken from. The **label** property is populated using the + value of the dialog node's **title** or **user_label** property. """ def __init__(self, @@ -5742,15 +5979,15 @@ def __init__(self, :param str label: The user-facing label for the disambiguation option. This label is taken from the **title** or **user_label** property of the - corresponding dialog node, depending on the disambiguation options. + corresponding dialog node. :param DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. :param dict output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. - :param str dialog_node: (optional) The ID of the dialog node that the - **label** property is taken from. The **label** property is populated using - the value of the dialog node's **user_label** property. + :param str dialog_node: (optional) The unique ID of the dialog node that + the **label** property is taken from. The **label** property is populated + using the value of the dialog node's **title** or **user_label** property. """ self.label = label self.value = value @@ -6803,17 +7040,32 @@ class LogMessage(): :attr str level: The severity of the log message. :attr str msg: The text of the log message. + :attr str code: A code that indicates the category to which the error message + belongs. + :attr LogMessageSource source: (optional) An object that identifies the dialog + element that generated the error message. """ - def __init__(self, level: str, msg: str) -> None: + def __init__(self, + level: str, + msg: str, + code: str, + *, + source: 'LogMessageSource' = None) -> None: """ Initialize a LogMessage object. :param str level: The severity of the log message. :param str msg: The text of the log message. + :param str code: A code that indicates the category to which the error + message belongs. + :param LogMessageSource source: (optional) An object that identifies the + dialog element that generated the error message. """ self.level = level self.msg = msg + self.code = code + self.source = source @classmethod def from_dict(cls, _dict: Dict) -> 'LogMessage': @@ -6829,6 +7081,13 @@ def from_dict(cls, _dict: Dict) -> 'LogMessage': else: raise ValueError( 'Required property \'msg\' not present in LogMessage JSON') + if 'code' in _dict: + args['code'] = _dict.get('code') + else: + raise ValueError( + 'Required property \'code\' not present in LogMessage JSON') + if 'source' in _dict: + args['source'] = LogMessageSource.from_dict(_dict.get('source')) return cls(**args) @classmethod @@ -6843,6 +7102,10 @@ def to_dict(self) -> Dict: _dict['level'] = self.level if hasattr(self, 'msg') and self.msg is not None: _dict['msg'] = self.msg + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source.to_dict() return _dict def _to_dict(self): @@ -6872,6 +7135,78 @@ class LevelEnum(str, Enum): WARN = 'warn' +class LogMessageSource(): + """ + An object that identifies the dialog element that generated the error message. + + :attr str type: (optional) A string that indicates the type of dialog element + that generated the error message. + :attr str dialog_node: (optional) The unique identifier of the dialog node that + generated the error message. + """ + + def __init__(self, *, type: str = None, dialog_node: str = None) -> None: + """ + Initialize a LogMessageSource object. + + :param str type: (optional) A string that indicates the type of dialog + element that generated the error message. + :param str dialog_node: (optional) The unique identifier of the dialog node + that generated the error message. + """ + self.type = type + self.dialog_node = dialog_node + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSource': + """Initialize a LogMessageSource object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'dialog_node' in _dict: + args['dialog_node'] = _dict.get('dialog_node') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogMessageSource 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 + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node + 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 LogMessageSource object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogMessageSource') -> 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: 'LogMessageSource') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + A string that indicates the type of dialog element that generated the error + message. + """ + DIALOG_NODE = 'dialog_node' + + class LogPagination(): """ The pagination data for the returned objects. @@ -7025,9 +7360,14 @@ class MessageContextMetadata(): newline, or tab characters. :attr str user_id: (optional) A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for - each individual end user who accesses the application. For Plus and Premium - plans, this user ID is used to identify unique users for billing purposes. This - string cannot contain carriage return, newline, or tab characters. + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.conversation_id**. + **Note:** This property is the same as the **user_id** property at the root of + the message body. If **user_id** is specified in both locations in a message + request, the value specified at the root is used. """ def __init__(self, *, deployment: str = None, user_id: str = None) -> None: @@ -7040,9 +7380,13 @@ def __init__(self, *, deployment: str = None, user_id: str = None) -> None: :param str user_id: (optional) A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For - Plus and Premium plans, this user ID is used to identify unique users for - billing purposes. This string cannot contain carriage return, newline, or - tab characters. + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.conversation_id**. + **Note:** This property is the same as the **user_id** property at the root + of the message body. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. """ self.deployment = deployment self.user_id = user_id @@ -7241,6 +7585,16 @@ class MessageRequest(): to the user, the dialog nodes that were triggered, and messages from the log. :attr List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the workspace. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.conversation_id**. + **Note:** This property is the same as the **user_id** property in the context + metadata. If **user_id** is specified in both locations in a message request, + the value specified at the root is used. """ def __init__(self, @@ -7251,7 +7605,8 @@ def __init__(self, alternate_intents: bool = None, context: 'Context' = None, output: 'OutputData' = None, - actions: List['DialogNodeAction'] = None) -> None: + actions: List['DialogNodeAction'] = None, + user_id: str = None) -> None: """ Initialize a MessageRequest object. @@ -7272,6 +7627,16 @@ def __init__(self, :param OutputData output: (optional) An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the workspace. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.conversation_id**. + **Note:** This property is the same as the **user_id** property in the + context metadata. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. """ self.input = input self.intents = intents @@ -7280,6 +7645,7 @@ def __init__(self, self.context = context self.output = output self.actions = actions + self.user_id = user_id @classmethod def from_dict(cls, _dict: Dict) -> 'MessageRequest': @@ -7305,6 +7671,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageRequest': args['actions'] = [ DialogNodeAction.from_dict(x) for x in _dict.get('actions') ] + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') return cls(**args) @classmethod @@ -7330,6 +7698,8 @@ def to_dict(self) -> Dict: _dict['output'] = self.output.to_dict() if hasattr(self, 'actions') and getattr(self, 'actions') is not None: _dict['actions'] = [x.to_dict() for x in getattr(self, 'actions')] + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -7369,6 +7739,16 @@ class MessageResponse(): user, the dialog nodes that were triggered, and messages from the log. :attr List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. + :attr str user_id: A string value that identifies the user who is interacting + with the workspace. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.conversation_id**. + **Note:** This property is the same as the **user_id** property in the context + metadata. If **user_id** is specified in both locations in a message request, + the value specified at the root is used. """ def __init__(self, @@ -7377,6 +7757,7 @@ def __init__(self, entities: List['RuntimeEntity'], context: 'Context', output: 'OutputData', + user_id: str, *, alternate_intents: bool = None, actions: List['DialogNodeAction'] = None) -> None: @@ -7392,6 +7773,16 @@ def __init__(self, state, include the context from the previous response. :param OutputData output: An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. + :param str user_id: A string value that identifies the user who is + interacting with the workspace. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.conversation_id**. + **Note:** This property is the same as the **user_id** property in the + context metadata. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. :param bool alternate_intents: (optional) Whether to return more than one intent. A value of `true` indicates that all matching intents are returned. """ @@ -7402,6 +7793,7 @@ def __init__(self, self.context = context self.output = output self.actions = actions + self.user_id = user_id @classmethod def from_dict(cls, _dict: Dict) -> 'MessageResponse': @@ -7447,6 +7839,12 @@ def from_dict(cls, _dict: Dict) -> 'MessageResponse': args['actions'] = [ DialogNodeAction.from_dict(x) for x in _dict.get('actions') ] + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') + else: + raise ValueError( + 'Required property \'user_id\' not present in MessageResponse JSON' + ) return cls(**args) @classmethod @@ -7472,6 +7870,8 @@ def to_dict(self) -> Dict: _dict['output'] = self.output.to_dict() if hasattr(self, 'actions') and getattr(self, 'actions') is not None: _dict['actions'] = [x.to_dict() for x in getattr(self, 'actions')] + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -7744,6 +8144,73 @@ def __ne__(self, other: 'Pagination') -> bool: return not self == other +class ResponseGenericChannel(): + """ + ResponseGenericChannel. + + :attr str channel: (optional) A channel for which the response is intended. + """ + + def __init__(self, *, channel: str = None) -> None: + """ + Initialize a ResponseGenericChannel object. + + :param str channel: (optional) A channel for which the response is + intended. + """ + self.channel = channel + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': + """Initialize a ResponseGenericChannel object from a json dictionary.""" + args = {} + if 'channel' in _dict: + args['channel'] = _dict.get('channel') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericChannel 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, 'channel') and self.channel is not None: + _dict['channel'] = self.channel + 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 ResponseGenericChannel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericChannel') -> 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: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ChannelEnum(str, Enum): + """ + A channel for which the response is intended. + """ + CHAT = 'chat' + FACEBOOK = 'facebook' + INTERCOM = 'intercom' + SLACK = 'slack' + TEXT_MESSAGING = 'text_messaging' + VOICE_TELEPHONY = 'voice_telephony' + WHATSAPP = 'whatsapp' + + class RuntimeEntity(): """ A term from the request that was identified as an entity. @@ -8501,7 +8968,9 @@ def __init__(self) -> None: 'RuntimeResponseGenericRuntimeResponseTypeImage', 'RuntimeResponseGenericRuntimeResponseTypeOption', 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' ])) raise Exception(msg) @@ -8520,7 +8989,9 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': 'RuntimeResponseGenericRuntimeResponseTypeImage', 'RuntimeResponseGenericRuntimeResponseTypeOption', 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' ])) raise Exception(msg) @@ -8532,6 +9003,8 @@ def _from_dict(cls, _dict: Dict): @classmethod def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping = {} + mapping[ + 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' mapping[ 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' @@ -8540,6 +9013,8 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + mapping[ + 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' disc_value = _dict.get('response_type') if disc_value is None: raise ValueError( @@ -9813,10 +10288,126 @@ def __ne__(self, other: 'WorkspaceSystemSettingsTooling') -> bool: return not self == other +class DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer( + DialogNodeOutputGeneric): + """ + DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str message_to_user: The message to display to the user when initiating a + channel transfer. + :attr ChannelTransferInfo transfer_info: Information used by an integration to + transfer the conversation to a different channel. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. + """ + + def __init__(self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: List['ResponseGenericChannel'] = None) -> None: + """ + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str message_to_user: The message to display to the user when + initiating a channel transfer. + :param ChannelTransferInfo transfer_info: Information used by an + integration to transfer the conversation to a different channel. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.message_to_user = message_to_user + self.transfer_info = transfer_info + self.channels = channels + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' + ) + if 'message_to_user' in _dict: + args['message_to_user'] = _dict.get('message_to_user') + else: + raise ValueError( + 'Required property \'message_to_user\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' + ) + if 'transfer_info' in _dict: + args['transfer_info'] = ChannelTransferInfo.from_dict( + _dict.get('transfer_info')) + else: + raise ValueError( + 'Required property \'transfer_info\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' + ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, + 'message_to_user') and self.message_to_user is not None: + _dict['message_to_user'] = self.message_to_user + if hasattr(self, 'transfer_info') and self.transfer_info is not None: + _dict['transfer_info'] = self.transfer_info.to_dict() + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + 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 DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer' + ) -> 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: + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent( DialogNodeOutputGeneric): """ - An object that describes a response with response type `connect_to_agent`. + DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. @@ -9831,17 +10422,19 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent( :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. """ def __init__( - self, - response_type: str, - *, - message_to_human_agent: str = None, - agent_available: 'AgentAvailabilityMessage' = None, - agent_unavailable: 'AgentAvailabilityMessage' = None, - transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None - ) -> None: + self, + response_type: str, + *, + message_to_human_agent: str = None, + agent_available: 'AgentAvailabilityMessage' = None, + agent_unavailable: 'AgentAvailabilityMessage' = None, + transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object. @@ -9859,6 +10452,8 @@ def __init__( :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. """ # pylint: disable=super-init-not-called self.response_type = response_type @@ -9866,6 +10461,7 @@ def __init__( self.agent_available = agent_available self.agent_unavailable = agent_unavailable self.transfer_info = transfer_info + self.channels = channels @classmethod def from_dict( @@ -9891,6 +10487,11 @@ def from_dict( args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( _dict.get('transfer_info')) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -9914,6 +10515,8 @@ def to_dict(self) -> Dict: _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: _dict['transfer_info'] = self.transfer_info.to_dict() + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -9940,18 +10543,11 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - CONNECT_TO_AGENT = 'connect_to_agent' - class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage( DialogNodeOutputGeneric): """ - An object that describes a response with response type `image`. + DialogNodeOutputGenericDialogNodeOutputResponseTypeImage. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. @@ -9959,6 +10555,8 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage( :attr str title: (optional) An optional title to show before the response. :attr str description: (optional) An optional description to show with the response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. """ def __init__(self, @@ -9966,7 +10564,8 @@ def __init__(self, source: str, *, title: str = None, - description: str = None) -> None: + description: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object. @@ -9977,12 +10576,15 @@ def __init__(self, :param str title: (optional) An optional title to show before the response. :param str description: (optional) An optional description to show with the response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. """ # pylint: disable=super-init-not-called self.response_type = response_type self.source = source self.title = title self.description = description + self.channels = channels @classmethod def from_dict( @@ -10006,6 +10608,11 @@ def from_dict( args['title'] = _dict.get('title') if 'description' in _dict: args['description'] = _dict.get('description') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -10024,6 +10631,8 @@ def to_dict(self) -> Dict: _dict['title'] = self.title if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -10048,18 +10657,11 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - IMAGE = 'image' - class DialogNodeOutputGenericDialogNodeOutputResponseTypeOption( DialogNodeOutputGeneric): """ - An object that describes a response with response type `option`. + DialogNodeOutputGenericDialogNodeOutputResponseTypeOption. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. @@ -10071,6 +10673,8 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeOption( :attr List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. You can include up to 20 options. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. """ def __init__(self, @@ -10079,7 +10683,8 @@ def __init__(self, options: List['DialogNodeOutputOptionsElement'], *, description: str = None, - preference: str = None) -> None: + preference: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object. @@ -10094,6 +10699,8 @@ def __init__(self, response. :param str preference: (optional) The preferred type of control to display, if supported by the channel. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. """ # pylint: disable=super-init-not-called self.response_type = response_type @@ -10101,6 +10708,7 @@ def __init__(self, self.description = description self.preference = preference self.options = options + self.channels = channels @classmethod def from_dict( @@ -10133,6 +10741,11 @@ def from_dict( raise ValueError( 'Required property \'options\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -10153,6 +10766,8 @@ def to_dict(self) -> Dict: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: _dict['options'] = [x.to_dict() for x in self.options] + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -10177,13 +10792,6 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - OPTION = 'option' - class PreferenceEnum(str, Enum): """ The preferred type of control to display, if supported by the channel. @@ -10195,7 +10803,7 @@ class PreferenceEnum(str, Enum): class DialogNodeOutputGenericDialogNodeOutputResponseTypePause( DialogNodeOutputGeneric): """ - An object that describes a response with response type `pause`. + DialogNodeOutputGenericDialogNodeOutputResponseTypePause. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. @@ -10203,13 +10811,16 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypePause( to 10000. :attr bool typing: (optional) Whether to send a "user is typing" event during the pause. Ignored if the channel does not support this event. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. """ def __init__(self, response_type: str, time: int, *, - typing: bool = None) -> None: + typing: bool = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypePause object. @@ -10220,11 +10831,14 @@ def __init__(self, from 0 to 10000. :param bool typing: (optional) Whether to send a "user is typing" event during the pause. Ignored if the channel does not support this event. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. """ # pylint: disable=super-init-not-called self.response_type = response_type self.time = time self.typing = typing + self.channels = channels @classmethod def from_dict( @@ -10246,6 +10860,11 @@ def from_dict( ) if 'typing' in _dict: args['typing'] = _dict.get('typing') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -10262,6 +10881,8 @@ def to_dict(self) -> Dict: _dict['time'] = self.time if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -10286,18 +10907,11 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - PAUSE = 'pause' - class DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill( DialogNodeOutputGeneric): """ - An object that describes a response with response type `search_skill`. + DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. @@ -10314,6 +10928,8 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill( documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). :attr str discovery_version: (optional) The version of the Discovery service API to use for the query. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. """ def __init__(self, @@ -10322,7 +10938,8 @@ def __init__(self, query_type: str, *, filter: str = None, - discovery_version: str = None) -> None: + discovery_version: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object. @@ -10343,6 +10960,8 @@ def __init__(self, documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). :param str discovery_version: (optional) The version of the Discovery service API to use for the query. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. """ # pylint: disable=super-init-not-called self.response_type = response_type @@ -10350,6 +10969,7 @@ def __init__(self, self.query_type = query_type self.filter = filter self.discovery_version = discovery_version + self.channels = channels @classmethod def from_dict( @@ -10379,6 +10999,11 @@ def from_dict( args['filter'] = _dict.get('filter') if 'discovery_version' in _dict: args['discovery_version'] = _dict.get('discovery_version') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -10400,6 +11025,8 @@ def to_dict(self) -> Dict: if hasattr(self, 'discovery_version') and self.discovery_version is not None: _dict['discovery_version'] = self.discovery_version + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -10426,14 +11053,6 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - **Note:** The **search_skill** response type is used only by the v2 runtime API. - """ - SEARCH_SKILL = 'search_skill' - class QueryTypeEnum(str, Enum): """ The type of the search query. @@ -10445,7 +11064,7 @@ class QueryTypeEnum(str, Enum): class DialogNodeOutputGenericDialogNodeOutputResponseTypeText( DialogNodeOutputGeneric): """ - An object that describes a response with response type `text`. + DialogNodeOutputGenericDialogNodeOutputResponseTypeText. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. @@ -10455,6 +11074,8 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeText( if more than one response is specified. :attr str delimiter: (optional) The delimiter to use as a separator between responses when `selection_policy`=`multiline`. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. """ def __init__(self, @@ -10462,7 +11083,8 @@ def __init__(self, values: List['DialogNodeOutputTextValuesElement'], *, selection_policy: str = None, - delimiter: str = None) -> None: + delimiter: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeText object. @@ -10475,12 +11097,15 @@ def __init__(self, list, if more than one response is specified. :param str delimiter: (optional) The delimiter to use as a separator between responses when `selection_policy`=`multiline`. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. """ # pylint: disable=super-init-not-called self.response_type = response_type self.values = values self.selection_policy = selection_policy self.delimiter = delimiter + self.channels = channels @classmethod def from_dict( @@ -10507,6 +11132,11 @@ def from_dict( args['selection_policy'] = _dict.get('selection_policy') if 'delimiter' in _dict: args['delimiter'] = _dict.get('delimiter') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -10526,6 +11156,8 @@ def to_dict(self) -> Dict: _dict['selection_policy'] = self.selection_policy if hasattr(self, 'delimiter') and self.delimiter is not None: _dict['delimiter'] = self.delimiter + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -10550,13 +11182,6 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - TEXT = 'text' - class SelectionPolicyEnum(str, Enum): """ How a response is selected from the list, if more than one response is specified. @@ -10566,10 +11191,230 @@ class SelectionPolicyEnum(str, Enum): MULTILINE = 'multiline' +class DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined( + DialogNodeOutputGeneric): + """ + DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr dict user_defined: An object containing any properties for the + user-defined response type. The total size of this object cannot exceed 5000 + bytes. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. + """ + + def __init__(self, + response_type: str, + user_defined: dict, + *, + channels: List['ResponseGenericChannel'] = None) -> None: + """ + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param dict user_defined: An object containing any properties for the + user-defined response type. The total size of this object cannot exceed + 5000 bytes. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.user_defined = user_defined + self.channels = channels + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' + ) + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + else: + raise ValueError( + 'Required property \'user_defined\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' + ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + 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 DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' + ) -> 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: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( + RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeChannelTransfer. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str message_to_user: The message to display to the user when initiating a + channel transfer. + :attr ChannelTransferInfo transfer_info: Information used by an integration to + transfer the conversation to a different channel. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended only for a built-in integration and should not + be handled by an API client. + """ + + def __init__(self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: List['ResponseGenericChannel'] = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str message_to_user: The message to display to the user when + initiating a channel transfer. + :param ChannelTransferInfo transfer_info: Information used by an + integration to transfer the conversation to a different channel. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended only for a built-in + integration and should not be handled by an API client. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.message_to_user = message_to_user + self.transfer_info = transfer_info + self.channels = channels + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' + ) + if 'message_to_user' in _dict: + args['message_to_user'] = _dict.get('message_to_user') + else: + raise ValueError( + 'Required property \'message_to_user\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' + ) + if 'transfer_info' in _dict: + args['transfer_info'] = ChannelTransferInfo.from_dict( + _dict.get('transfer_info')) + else: + raise ValueError( + 'Required property \'transfer_info\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' + ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, + 'message_to_user') and self.message_to_user is not None: + _dict['message_to_user'] = self.message_to_user + if hasattr(self, 'transfer_info') and self.transfer_info is not None: + _dict['transfer_info'] = self.transfer_info.to_dict() + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + 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 RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + ) -> 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: 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( RuntimeResponseGeneric): """ - An object that describes a response with response type `connect_to_agent`. + RuntimeResponseGenericRuntimeResponseTypeConnectToAgent. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. @@ -10587,9 +11432,13 @@ class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( :attr str topic: (optional) A label identifying the topic of the conversation, derived from the **title** property of the relevant node or the **topic** property of the dialog node response. - :attr str dialog_node: (optional) The ID of the dialog node that the **topic** - property is taken from. The **topic** property is populated using the value of - the dialog node's **title** property. + :attr str dialog_node: (optional) The unique ID of the dialog node that the + **topic** property is taken from. The **topic** property is populated using the + value of the dialog node's **title** property. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ def __init__( @@ -10601,7 +11450,8 @@ def __init__( agent_unavailable: 'AgentAvailabilityMessage' = None, transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, topic: str = None, - dialog_node: str = None) -> None: + dialog_node: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object. @@ -10622,9 +11472,13 @@ def __init__( :param str topic: (optional) A label identifying the topic of the conversation, derived from the **title** property of the relevant node or the **topic** property of the dialog node response. - :param str dialog_node: (optional) The ID of the dialog node that the - **topic** property is taken from. The **topic** property is populated using - the value of the dialog node's **title** property. + :param str dialog_node: (optional) The unique ID of the dialog node that + the **topic** property is taken from. The **topic** property is populated + using the value of the dialog node's **title** property. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type @@ -10634,6 +11488,7 @@ def __init__( self.transfer_info = transfer_info self.topic = topic self.dialog_node = dialog_node + self.channels = channels @classmethod def from_dict( @@ -10663,6 +11518,11 @@ def from_dict( args['topic'] = _dict.get('topic') if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -10690,6 +11550,8 @@ def to_dict(self) -> Dict: _dict['topic'] = self.topic if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -10714,17 +11576,10 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - CONNECT_TO_AGENT = 'connect_to_agent' - class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): """ - An object that describes a response with response type `image`. + RuntimeResponseGenericRuntimeResponseTypeImage. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. @@ -10732,6 +11587,10 @@ class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): :attr str title: (optional) The title or introductory text to show before the response. :attr str description: (optional) The description to show with the the response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ def __init__(self, @@ -10739,7 +11598,8 @@ def __init__(self, source: str, *, title: str = None, - description: str = None) -> None: + description: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. @@ -10751,12 +11611,17 @@ def __init__(self, the response. :param str description: (optional) The description to show with the the response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type self.source = source self.title = title self.description = description + self.channels = channels @classmethod def from_dict( @@ -10780,6 +11645,11 @@ def from_dict( args['title'] = _dict.get('title') if 'description' in _dict: args['description'] = _dict.get('description') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -10798,6 +11668,8 @@ def to_dict(self) -> Dict: _dict['title'] = self.title if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -10820,17 +11692,10 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - IMAGE = 'image' - class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): """ - An object that describes a response with response type `option`. + RuntimeResponseGenericRuntimeResponseTypeOption. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. @@ -10839,6 +11704,10 @@ class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): :attr str preference: (optional) The preferred type of control to display. :attr List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ def __init__(self, @@ -10847,7 +11716,8 @@ def __init__(self, options: List['DialogNodeOutputOptionsElement'], *, description: str = None, - preference: str = None) -> None: + preference: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object. @@ -10861,6 +11731,10 @@ def __init__(self, :param str description: (optional) The description to show with the the response. :param str preference: (optional) The preferred type of control to display. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type @@ -10868,6 +11742,7 @@ def __init__(self, self.description = description self.preference = preference self.options = options + self.channels = channels @classmethod def from_dict( @@ -10900,6 +11775,11 @@ def from_dict( raise ValueError( 'Required property \'options\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -10920,6 +11800,8 @@ def to_dict(self) -> Dict: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: _dict['options'] = [x.to_dict() for x in self.options] + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -10944,13 +11826,6 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - OPTION = 'option' - class PreferenceEnum(str, Enum): """ The preferred type of control to display. @@ -10961,20 +11836,25 @@ class PreferenceEnum(str, Enum): class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): """ - An object that describes a response with response type `pause`. + RuntimeResponseGenericRuntimeResponseTypePause. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. :attr int time: How long to pause, in milliseconds. :attr bool typing: (optional) Whether to send a "user is typing" event during the pause. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ def __init__(self, response_type: str, time: int, *, - typing: bool = None) -> None: + typing: bool = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypePause object. @@ -10984,11 +11864,16 @@ def __init__(self, :param int time: How long to pause, in milliseconds. :param bool typing: (optional) Whether to send a "user is typing" event during the pause. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type self.time = time self.typing = typing + self.channels = channels @classmethod def from_dict( @@ -11010,6 +11895,11 @@ def from_dict( ) if 'typing' in _dict: args['typing'] = _dict.get('typing') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -11026,6 +11916,8 @@ def to_dict(self) -> Dict: _dict['time'] = self.time if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -11048,28 +11940,29 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - PAUSE = 'pause' - class RuntimeResponseGenericRuntimeResponseTypeSuggestion( RuntimeResponseGeneric): """ - An object that describes a response with response type `suggestion`. + RuntimeResponseGenericRuntimeResponseTypeSuggestion. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. :attr str title: The title or introductory text to show before the response. :attr List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ - def __init__(self, response_type: str, title: str, - suggestions: List['DialogSuggestion']) -> None: + def __init__(self, + response_type: str, + title: str, + suggestions: List['DialogSuggestion'], + *, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object. @@ -11080,11 +11973,16 @@ def __init__(self, response_type: str, title: str, response. :param List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type self.title = title self.suggestions = suggestions + self.channels = channels @classmethod def from_dict( @@ -11112,6 +12010,11 @@ def from_dict( raise ValueError( 'Required property \'suggestions\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -11128,6 +12031,8 @@ def to_dict(self) -> Dict: _dict['title'] = self.title if hasattr(self, 'suggestions') and self.suggestions is not None: _dict['suggestions'] = [x.to_dict() for x in self.suggestions] + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -11152,24 +12057,25 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - SUGGESTION = 'suggestion' - class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): """ - An object that describes a response with response type `text`. + RuntimeResponseGenericRuntimeResponseTypeText. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. :attr str text: The text of the response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ - def __init__(self, response_type: str, text: str) -> None: + def __init__(self, + response_type: str, + text: str, + *, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeText object. @@ -11177,10 +12083,15 @@ def __init__(self, response_type: str, text: str) -> None: The specified response type must be supported by the client application or channel. :param str text: The text of the response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type self.text = text + self.channels = channels @classmethod def from_dict( @@ -11200,6 +12111,11 @@ def from_dict( raise ValueError( 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -11214,6 +12130,8 @@ def to_dict(self) -> Dict: _dict['response_type'] = self.response_type if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -11236,9 +12154,104 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): + +class RuntimeResponseGenericRuntimeResponseTypeUserDefined( + RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeUserDefined. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr dict user_defined: An object containing any properties for the + user-defined response type. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + """ + + def __init__(self, + response_type: str, + user_defined: dict, + *, + channels: List['ResponseGenericChannel'] = None) -> None: """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. + Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param dict user_defined: An object containing any properties for the + user-defined response type. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ - TEXT = 'text' + # pylint: disable=super-init-not-called + self.response_type = response_type + self.user_defined = user_defined + self.channels = channels + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeUserDefined': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' + ) + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + else: + raise ValueError( + 'Required property \'user_defined\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' + ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + 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 RuntimeResponseGenericRuntimeResponseTypeUserDefined object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + ) -> 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: 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index b178ed6c3..a95476083 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect import json import pytest @@ -30,13 +31,13 @@ version = 'testString' -service = AssistantV1( +_service = AssistantV1( authenticator=NoAuthAuthenticator(), version=version ) -base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: Message @@ -63,8 +64,8 @@ def test_message_all_params(self): message() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/message') + mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -156,10 +157,17 @@ def test_message_all_params(self): dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' + # Construct a dict representation of a LogMessageSource model + log_message_source_model = {} + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + # Construct a dict representation of a LogMessage model log_message_model = {} log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' + log_message_model['code'] = 'testString' + log_message_model['source'] = log_message_source_model # Construct a dict representation of a DialogNodeOutputOptionsElementValue model dialog_node_output_options_element_value_model = {} @@ -172,6 +180,10 @@ def test_message_all_params(self): dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + # Construct a dict representation of a RuntimeResponseGenericRuntimeResponseTypeOption model runtime_response_generic_model = {} runtime_response_generic_model['response_type'] = 'option' @@ -179,6 +191,7 @@ def test_message_all_params(self): runtime_response_generic_model['description'] = 'testString' runtime_response_generic_model['preference'] = 'dropdown' runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a OutputData model output_data_model = {} @@ -197,10 +210,11 @@ def test_message_all_params(self): alternate_intents = True context = context_model output = output_data_model + user_id = 'testString' nodes_visited_details = True # Invoke method - response = service.message( + response = _service.message( workspace_id, input=input, intents=intents, @@ -208,6 +222,7 @@ def test_message_all_params(self): alternate_intents=alternate_intents, context=context, output=output, + user_id=user_id, nodes_visited_details=nodes_visited_details, headers={} ) @@ -227,6 +242,7 @@ def test_message_all_params(self): assert req_body['alternate_intents'] == True assert req_body['context'] == context_model assert req_body['output'] == output_data_model + assert req_body['user_id'] == 'testString' @responses.activate @@ -235,8 +251,8 @@ def test_message_required_params(self): test_message_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/message') + mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -247,7 +263,7 @@ def test_message_required_params(self): workspace_id = 'testString' # Invoke method - response = service.message( + response = _service.message( workspace_id, headers={} ) @@ -263,8 +279,8 @@ def test_message_value_error(self): test_message_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/message') + mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -281,7 +297,7 @@ def test_message_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.message(**req_copy) + _service.message(**req_copy) @@ -315,7 +331,7 @@ def test_bulk_classify_all_params(self): bulk_classify() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, @@ -332,7 +348,7 @@ def test_bulk_classify_all_params(self): input = [bulk_classify_utterance_model] # Invoke method - response = service.bulk_classify( + response = _service.bulk_classify( workspace_id, input=input, headers={} @@ -352,7 +368,7 @@ def test_bulk_classify_required_params(self): test_bulk_classify_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, @@ -364,7 +380,7 @@ def test_bulk_classify_required_params(self): workspace_id = 'testString' # Invoke method - response = service.bulk_classify( + response = _service.bulk_classify( workspace_id, headers={} ) @@ -380,7 +396,7 @@ def test_bulk_classify_value_error(self): test_bulk_classify_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/bulk_classify') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, @@ -398,7 +414,7 @@ def test_bulk_classify_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.bulk_classify(**req_copy) + _service.bulk_classify(**req_copy) @@ -432,8 +448,8 @@ def test_list_workspaces_all_params(self): list_workspaces() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces') + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -448,7 +464,7 @@ def test_list_workspaces_all_params(self): include_audit = True # Invoke method - response = service.list_workspaces( + response = _service.list_workspaces( page_limit=page_limit, include_count=include_count, sort=sort, @@ -476,8 +492,8 @@ def test_list_workspaces_required_params(self): test_list_workspaces_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces') + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -485,7 +501,7 @@ def test_list_workspaces_required_params(self): status=200) # Invoke method - response = service.list_workspaces() + response = _service.list_workspaces() # Check for correct operation @@ -499,8 +515,8 @@ def test_list_workspaces_value_error(self): test_list_workspaces_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces') + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -513,7 +529,7 @@ def test_list_workspaces_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_workspaces(**req_copy) + _service.list_workspaces(**req_copy) @@ -537,20 +553,36 @@ def test_create_workspace_all_params(self): create_workspace() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + # Construct a dict representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model = {} + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a dict representation of a ChannelTransferTarget model + channel_transfer_target_model = {} + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a dict representation of a ChannelTransferInfo model + channel_transfer_info_model = {} + channel_transfer_info_model['target'] = channel_transfer_target_model + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -698,7 +730,7 @@ def test_create_workspace_all_params(self): include_audit = True # Invoke method - response = service.create_workspace( + response = _service.create_workspace( name=name, description=description, language=language, @@ -742,8 +774,8 @@ def test_create_workspace_required_params(self): test_create_workspace_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -751,7 +783,7 @@ def test_create_workspace_required_params(self): status=201) # Invoke method - response = service.create_workspace() + response = _service.create_workspace() # Check for correct operation @@ -765,8 +797,8 @@ def test_create_workspace_value_error(self): test_create_workspace_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -779,7 +811,7 @@ def test_create_workspace_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_workspace(**req_copy) + _service.create_workspace(**req_copy) @@ -803,8 +835,8 @@ def test_get_workspace_all_params(self): get_workspace() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -818,7 +850,7 @@ def test_get_workspace_all_params(self): sort = 'stable' # Invoke method - response = service.get_workspace( + response = _service.get_workspace( workspace_id, export=export, include_audit=include_audit, @@ -843,8 +875,8 @@ def test_get_workspace_required_params(self): test_get_workspace_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -855,7 +887,7 @@ def test_get_workspace_required_params(self): workspace_id = 'testString' # Invoke method - response = service.get_workspace( + response = _service.get_workspace( workspace_id, headers={} ) @@ -871,8 +903,8 @@ def test_get_workspace_value_error(self): test_get_workspace_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -889,7 +921,7 @@ def test_get_workspace_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_workspace(**req_copy) + _service.get_workspace(**req_copy) @@ -913,20 +945,36 @@ def test_update_workspace_all_params(self): update_workspace() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + # Construct a dict representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model = {} + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a dict representation of a ChannelTransferTarget model + channel_transfer_target_model = {} + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a dict representation of a ChannelTransferInfo model + channel_transfer_info_model = {} + channel_transfer_info_model['target'] = channel_transfer_target_model + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -1076,7 +1124,7 @@ def test_update_workspace_all_params(self): include_audit = True # Invoke method - response = service.update_workspace( + response = _service.update_workspace( workspace_id, name=name, description=description, @@ -1123,8 +1171,8 @@ def test_update_workspace_required_params(self): test_update_workspace_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -1135,7 +1183,7 @@ def test_update_workspace_required_params(self): workspace_id = 'testString' # Invoke method - response = service.update_workspace( + response = _service.update_workspace( workspace_id, headers={} ) @@ -1151,8 +1199,8 @@ def test_update_workspace_value_error(self): test_update_workspace_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -1169,7 +1217,7 @@ def test_update_workspace_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_workspace(**req_copy) + _service.update_workspace(**req_copy) @@ -1193,7 +1241,7 @@ def test_delete_workspace_all_params(self): delete_workspace() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString') responses.add(responses.DELETE, url, status=200) @@ -1202,7 +1250,7 @@ def test_delete_workspace_all_params(self): workspace_id = 'testString' # Invoke method - response = service.delete_workspace( + response = _service.delete_workspace( workspace_id, headers={} ) @@ -1218,7 +1266,7 @@ def test_delete_workspace_value_error(self): test_delete_workspace_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString') responses.add(responses.DELETE, url, status=200) @@ -1233,7 +1281,7 @@ def test_delete_workspace_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_workspace(**req_copy) + _service.delete_workspace(**req_copy) @@ -1267,8 +1315,8 @@ def test_list_intents_all_params(self): list_intents() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') - mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -1285,7 +1333,7 @@ def test_list_intents_all_params(self): include_audit = True # Invoke method - response = service.list_intents( + response = _service.list_intents( workspace_id, export=export, page_limit=page_limit, @@ -1316,8 +1364,8 @@ def test_list_intents_required_params(self): test_list_intents_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') - mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -1328,7 +1376,7 @@ def test_list_intents_required_params(self): workspace_id = 'testString' # Invoke method - response = service.list_intents( + response = _service.list_intents( workspace_id, headers={} ) @@ -1344,8 +1392,8 @@ def test_list_intents_value_error(self): test_list_intents_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') - mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -1362,7 +1410,7 @@ def test_list_intents_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_intents(**req_copy) + _service.list_intents(**req_copy) @@ -1386,8 +1434,8 @@ def test_create_intent_all_params(self): create_intent() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') - mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -1412,7 +1460,7 @@ def test_create_intent_all_params(self): include_audit = True # Invoke method - response = service.create_intent( + response = _service.create_intent( workspace_id, intent, description=description, @@ -1441,8 +1489,8 @@ def test_create_intent_required_params(self): test_create_intent_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') - mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -1466,7 +1514,7 @@ def test_create_intent_required_params(self): examples = [example_model] # Invoke method - response = service.create_intent( + response = _service.create_intent( workspace_id, intent, description=description, @@ -1490,8 +1538,8 @@ def test_create_intent_value_error(self): test_create_intent_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents') - mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -1522,7 +1570,7 @@ def test_create_intent_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_intent(**req_copy) + _service.create_intent(**req_copy) @@ -1546,8 +1594,8 @@ def test_get_intent_all_params(self): get_intent() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') - mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1561,7 +1609,7 @@ def test_get_intent_all_params(self): include_audit = True # Invoke method - response = service.get_intent( + response = _service.get_intent( workspace_id, intent, export=export, @@ -1585,8 +1633,8 @@ def test_get_intent_required_params(self): test_get_intent_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') - mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1598,7 +1646,7 @@ def test_get_intent_required_params(self): intent = 'testString' # Invoke method - response = service.get_intent( + response = _service.get_intent( workspace_id, intent, headers={} @@ -1615,8 +1663,8 @@ def test_get_intent_value_error(self): test_get_intent_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') - mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1635,7 +1683,7 @@ def test_get_intent_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_intent(**req_copy) + _service.get_intent(**req_copy) @@ -1659,8 +1707,8 @@ def test_update_intent_all_params(self): update_intent() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') - mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -1687,7 +1735,7 @@ def test_update_intent_all_params(self): include_audit = True # Invoke method - response = service.update_intent( + response = _service.update_intent( workspace_id, intent, new_intent=new_intent, @@ -1719,8 +1767,8 @@ def test_update_intent_required_params(self): test_update_intent_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') - mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -1745,7 +1793,7 @@ def test_update_intent_required_params(self): new_examples = [example_model] # Invoke method - response = service.update_intent( + response = _service.update_intent( workspace_id, intent, new_intent=new_intent, @@ -1770,8 +1818,8 @@ def test_update_intent_value_error(self): test_update_intent_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') - mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -1803,7 +1851,7 @@ def test_update_intent_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_intent(**req_copy) + _service.update_intent(**req_copy) @@ -1827,7 +1875,7 @@ def test_delete_intent_all_params(self): delete_intent() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') responses.add(responses.DELETE, url, status=200) @@ -1837,7 +1885,7 @@ def test_delete_intent_all_params(self): intent = 'testString' # Invoke method - response = service.delete_intent( + response = _service.delete_intent( workspace_id, intent, headers={} @@ -1854,7 +1902,7 @@ def test_delete_intent_value_error(self): test_delete_intent_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') responses.add(responses.DELETE, url, status=200) @@ -1871,7 +1919,7 @@ def test_delete_intent_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_intent(**req_copy) + _service.delete_intent(**req_copy) @@ -1905,8 +1953,8 @@ def test_list_examples_all_params(self): list_examples() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') - mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -1923,7 +1971,7 @@ def test_list_examples_all_params(self): include_audit = True # Invoke method - response = service.list_examples( + response = _service.list_examples( workspace_id, intent, page_limit=page_limit, @@ -1953,8 +2001,8 @@ def test_list_examples_required_params(self): test_list_examples_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') - mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -1966,7 +2014,7 @@ def test_list_examples_required_params(self): intent = 'testString' # Invoke method - response = service.list_examples( + response = _service.list_examples( workspace_id, intent, headers={} @@ -1983,8 +2031,8 @@ def test_list_examples_value_error(self): test_list_examples_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') - mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -2003,7 +2051,7 @@ def test_list_examples_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_examples(**req_copy) + _service.list_examples(**req_copy) @@ -2027,8 +2075,8 @@ def test_create_example_all_params(self): create_example() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') - mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2048,7 +2096,7 @@ def test_create_example_all_params(self): include_audit = True # Invoke method - response = service.create_example( + response = _service.create_example( workspace_id, intent, text, @@ -2076,8 +2124,8 @@ def test_create_example_required_params(self): test_create_example_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') - mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2096,7 +2144,7 @@ def test_create_example_required_params(self): mentions = [mention_model] # Invoke method - response = service.create_example( + response = _service.create_example( workspace_id, intent, text, @@ -2119,8 +2167,8 @@ def test_create_example_value_error(self): test_create_example_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples') - mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2147,7 +2195,7 @@ def test_create_example_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_example(**req_copy) + _service.create_example(**req_copy) @@ -2171,8 +2219,8 @@ def test_get_example_all_params(self): get_example() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') - mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -2186,7 +2234,7 @@ def test_get_example_all_params(self): include_audit = True # Invoke method - response = service.get_example( + response = _service.get_example( workspace_id, intent, text, @@ -2209,8 +2257,8 @@ def test_get_example_required_params(self): test_get_example_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') - mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -2223,7 +2271,7 @@ def test_get_example_required_params(self): text = 'testString' # Invoke method - response = service.get_example( + response = _service.get_example( workspace_id, intent, text, @@ -2241,8 +2289,8 @@ def test_get_example_value_error(self): test_get_example_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') - mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -2263,7 +2311,7 @@ def test_get_example_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_example(**req_copy) + _service.get_example(**req_copy) @@ -2287,8 +2335,8 @@ def test_update_example_all_params(self): update_example() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') - mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2309,7 +2357,7 @@ def test_update_example_all_params(self): include_audit = True # Invoke method - response = service.update_example( + response = _service.update_example( workspace_id, intent, text, @@ -2338,8 +2386,8 @@ def test_update_example_required_params(self): test_update_example_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') - mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2359,7 +2407,7 @@ def test_update_example_required_params(self): new_mentions = [mention_model] # Invoke method - response = service.update_example( + response = _service.update_example( workspace_id, intent, text, @@ -2383,8 +2431,8 @@ def test_update_example_value_error(self): test_update_example_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') - mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2412,7 +2460,7 @@ def test_update_example_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_example(**req_copy) + _service.update_example(**req_copy) @@ -2436,7 +2484,7 @@ def test_delete_example_all_params(self): delete_example() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') responses.add(responses.DELETE, url, status=200) @@ -2447,7 +2495,7 @@ def test_delete_example_all_params(self): text = 'testString' # Invoke method - response = service.delete_example( + response = _service.delete_example( workspace_id, intent, text, @@ -2465,7 +2513,7 @@ def test_delete_example_value_error(self): test_delete_example_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') responses.add(responses.DELETE, url, status=200) @@ -2484,7 +2532,7 @@ def test_delete_example_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_example(**req_copy) + _service.delete_example(**req_copy) @@ -2518,8 +2566,8 @@ def test_list_counterexamples_all_params(self): list_counterexamples() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') - mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -2535,7 +2583,7 @@ def test_list_counterexamples_all_params(self): include_audit = True # Invoke method - response = service.list_counterexamples( + response = _service.list_counterexamples( workspace_id, page_limit=page_limit, include_count=include_count, @@ -2564,8 +2612,8 @@ def test_list_counterexamples_required_params(self): test_list_counterexamples_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') - mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -2576,7 +2624,7 @@ def test_list_counterexamples_required_params(self): workspace_id = 'testString' # Invoke method - response = service.list_counterexamples( + response = _service.list_counterexamples( workspace_id, headers={} ) @@ -2592,8 +2640,8 @@ def test_list_counterexamples_value_error(self): test_list_counterexamples_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') - mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -2610,7 +2658,7 @@ def test_list_counterexamples_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_counterexamples(**req_copy) + _service.list_counterexamples(**req_copy) @@ -2634,8 +2682,8 @@ def test_create_counterexample_all_params(self): create_counterexample() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') - mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2648,7 +2696,7 @@ def test_create_counterexample_all_params(self): include_audit = True # Invoke method - response = service.create_counterexample( + response = _service.create_counterexample( workspace_id, text, include_audit=include_audit, @@ -2673,8 +2721,8 @@ def test_create_counterexample_required_params(self): test_create_counterexample_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') - mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2686,7 +2734,7 @@ def test_create_counterexample_required_params(self): text = 'testString' # Invoke method - response = service.create_counterexample( + response = _service.create_counterexample( workspace_id, text, headers={} @@ -2706,8 +2754,8 @@ def test_create_counterexample_value_error(self): test_create_counterexample_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples') - mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2726,7 +2774,7 @@ def test_create_counterexample_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_counterexample(**req_copy) + _service.create_counterexample(**req_copy) @@ -2750,8 +2798,8 @@ def test_get_counterexample_all_params(self): get_counterexample() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') - mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -2764,7 +2812,7 @@ def test_get_counterexample_all_params(self): include_audit = True # Invoke method - response = service.get_counterexample( + response = _service.get_counterexample( workspace_id, text, include_audit=include_audit, @@ -2786,8 +2834,8 @@ def test_get_counterexample_required_params(self): test_get_counterexample_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') - mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -2799,7 +2847,7 @@ def test_get_counterexample_required_params(self): text = 'testString' # Invoke method - response = service.get_counterexample( + response = _service.get_counterexample( workspace_id, text, headers={} @@ -2816,8 +2864,8 @@ def test_get_counterexample_value_error(self): test_get_counterexample_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') - mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -2836,7 +2884,7 @@ def test_get_counterexample_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_counterexample(**req_copy) + _service.get_counterexample(**req_copy) @@ -2860,8 +2908,8 @@ def test_update_counterexample_all_params(self): update_counterexample() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') - mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2875,7 +2923,7 @@ def test_update_counterexample_all_params(self): include_audit = True # Invoke method - response = service.update_counterexample( + response = _service.update_counterexample( workspace_id, text, new_text=new_text, @@ -2901,8 +2949,8 @@ def test_update_counterexample_required_params(self): test_update_counterexample_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') - mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2915,7 +2963,7 @@ def test_update_counterexample_required_params(self): new_text = 'testString' # Invoke method - response = service.update_counterexample( + response = _service.update_counterexample( workspace_id, text, new_text=new_text, @@ -2936,8 +2984,8 @@ def test_update_counterexample_value_error(self): test_update_counterexample_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') - mock_response = '{"text": "text", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -2957,7 +3005,7 @@ def test_update_counterexample_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_counterexample(**req_copy) + _service.update_counterexample(**req_copy) @@ -2981,7 +3029,7 @@ def test_delete_counterexample_all_params(self): delete_counterexample() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') responses.add(responses.DELETE, url, status=200) @@ -2991,7 +3039,7 @@ def test_delete_counterexample_all_params(self): text = 'testString' # Invoke method - response = service.delete_counterexample( + response = _service.delete_counterexample( workspace_id, text, headers={} @@ -3008,7 +3056,7 @@ def test_delete_counterexample_value_error(self): test_delete_counterexample_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/counterexamples/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') responses.add(responses.DELETE, url, status=200) @@ -3025,7 +3073,7 @@ def test_delete_counterexample_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_counterexample(**req_copy) + _service.delete_counterexample(**req_copy) @@ -3059,8 +3107,8 @@ def test_list_entities_all_params(self): list_entities() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3077,7 +3125,7 @@ def test_list_entities_all_params(self): include_audit = True # Invoke method - response = service.list_entities( + response = _service.list_entities( workspace_id, export=export, page_limit=page_limit, @@ -3108,8 +3156,8 @@ def test_list_entities_required_params(self): test_list_entities_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3120,7 +3168,7 @@ def test_list_entities_required_params(self): workspace_id = 'testString' # Invoke method - response = service.list_entities( + response = _service.list_entities( workspace_id, headers={} ) @@ -3136,8 +3184,8 @@ def test_list_entities_value_error(self): test_list_entities_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3154,7 +3202,7 @@ def test_list_entities_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_entities(**req_copy) + _service.list_entities(**req_copy) @@ -3178,8 +3226,8 @@ def test_create_entity_all_params(self): create_entity() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3204,7 +3252,7 @@ def test_create_entity_all_params(self): include_audit = True # Invoke method - response = service.create_entity( + response = _service.create_entity( workspace_id, entity, description=description, @@ -3237,8 +3285,8 @@ def test_create_entity_required_params(self): test_create_entity_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3262,7 +3310,7 @@ def test_create_entity_required_params(self): values = [create_value_model] # Invoke method - response = service.create_entity( + response = _service.create_entity( workspace_id, entity, description=description, @@ -3290,8 +3338,8 @@ def test_create_entity_value_error(self): test_create_entity_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3322,7 +3370,7 @@ def test_create_entity_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_entity(**req_copy) + _service.create_entity(**req_copy) @@ -3346,8 +3394,8 @@ def test_get_entity_all_params(self): get_entity() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3361,7 +3409,7 @@ def test_get_entity_all_params(self): include_audit = True # Invoke method - response = service.get_entity( + response = _service.get_entity( workspace_id, entity, export=export, @@ -3385,8 +3433,8 @@ def test_get_entity_required_params(self): test_get_entity_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3398,7 +3446,7 @@ def test_get_entity_required_params(self): entity = 'testString' # Invoke method - response = service.get_entity( + response = _service.get_entity( workspace_id, entity, headers={} @@ -3415,8 +3463,8 @@ def test_get_entity_value_error(self): test_get_entity_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3435,7 +3483,7 @@ def test_get_entity_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_entity(**req_copy) + _service.get_entity(**req_copy) @@ -3459,8 +3507,8 @@ def test_update_entity_all_params(self): update_entity() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3487,7 +3535,7 @@ def test_update_entity_all_params(self): include_audit = True # Invoke method - response = service.update_entity( + response = _service.update_entity( workspace_id, entity, new_entity=new_entity, @@ -3523,8 +3571,8 @@ def test_update_entity_required_params(self): test_update_entity_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3549,7 +3597,7 @@ def test_update_entity_required_params(self): new_values = [create_value_model] # Invoke method - response = service.update_entity( + response = _service.update_entity( workspace_id, entity, new_entity=new_entity, @@ -3578,8 +3626,8 @@ def test_update_entity_value_error(self): test_update_entity_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3611,7 +3659,7 @@ def test_update_entity_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_entity(**req_copy) + _service.update_entity(**req_copy) @@ -3635,7 +3683,7 @@ def test_delete_entity_all_params(self): delete_entity() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') responses.add(responses.DELETE, url, status=200) @@ -3645,7 +3693,7 @@ def test_delete_entity_all_params(self): entity = 'testString' # Invoke method - response = service.delete_entity( + response = _service.delete_entity( workspace_id, entity, headers={} @@ -3662,7 +3710,7 @@ def test_delete_entity_value_error(self): test_delete_entity_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') responses.add(responses.DELETE, url, status=200) @@ -3679,7 +3727,7 @@ def test_delete_entity_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_entity(**req_copy) + _service.delete_entity(**req_copy) @@ -3713,7 +3761,7 @@ def test_list_mentions_all_params(self): list_mentions() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/mentions') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -3728,7 +3776,7 @@ def test_list_mentions_all_params(self): include_audit = True # Invoke method - response = service.list_mentions( + response = _service.list_mentions( workspace_id, entity, export=export, @@ -3752,7 +3800,7 @@ def test_list_mentions_required_params(self): test_list_mentions_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/mentions') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -3765,7 +3813,7 @@ def test_list_mentions_required_params(self): entity = 'testString' # Invoke method - response = service.list_mentions( + response = _service.list_mentions( workspace_id, entity, headers={} @@ -3782,7 +3830,7 @@ def test_list_mentions_value_error(self): test_list_mentions_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/mentions') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -3802,7 +3850,7 @@ def test_list_mentions_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_mentions(**req_copy) + _service.list_mentions(**req_copy) @@ -3836,8 +3884,8 @@ def test_list_values_all_params(self): list_values() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3855,7 +3903,7 @@ def test_list_values_all_params(self): include_audit = True # Invoke method - response = service.list_values( + response = _service.list_values( workspace_id, entity, export=export, @@ -3887,8 +3935,8 @@ def test_list_values_required_params(self): test_list_values_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3900,7 +3948,7 @@ def test_list_values_required_params(self): entity = 'testString' # Invoke method - response = service.list_values( + response = _service.list_values( workspace_id, entity, headers={} @@ -3917,8 +3965,8 @@ def test_list_values_value_error(self): test_list_values_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3937,7 +3985,7 @@ def test_list_values_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_values(**req_copy) + _service.list_values(**req_copy) @@ -3961,8 +4009,8 @@ def test_create_value_all_params(self): create_value() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -3980,7 +4028,7 @@ def test_create_value_all_params(self): include_audit = True # Invoke method - response = service.create_value( + response = _service.create_value( workspace_id, entity, value, @@ -4014,8 +4062,8 @@ def test_create_value_required_params(self): test_create_value_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4032,7 +4080,7 @@ def test_create_value_required_params(self): patterns = ['testString'] # Invoke method - response = service.create_value( + response = _service.create_value( workspace_id, entity, value, @@ -4061,8 +4109,8 @@ def test_create_value_value_error(self): test_create_value_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4087,7 +4135,7 @@ def test_create_value_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_value(**req_copy) + _service.create_value(**req_copy) @@ -4111,8 +4159,8 @@ def test_get_value_all_params(self): get_value() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4127,7 +4175,7 @@ def test_get_value_all_params(self): include_audit = True # Invoke method - response = service.get_value( + response = _service.get_value( workspace_id, entity, value, @@ -4152,8 +4200,8 @@ def test_get_value_required_params(self): test_get_value_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4166,7 +4214,7 @@ def test_get_value_required_params(self): value = 'testString' # Invoke method - response = service.get_value( + response = _service.get_value( workspace_id, entity, value, @@ -4184,8 +4232,8 @@ def test_get_value_value_error(self): test_get_value_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4206,7 +4254,7 @@ def test_get_value_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_value(**req_copy) + _service.get_value(**req_copy) @@ -4230,8 +4278,8 @@ def test_update_value_all_params(self): update_value() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4251,7 +4299,7 @@ def test_update_value_all_params(self): include_audit = True # Invoke method - response = service.update_value( + response = _service.update_value( workspace_id, entity, value, @@ -4288,8 +4336,8 @@ def test_update_value_required_params(self): test_update_value_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4307,7 +4355,7 @@ def test_update_value_required_params(self): new_patterns = ['testString'] # Invoke method - response = service.update_value( + response = _service.update_value( workspace_id, entity, value, @@ -4337,8 +4385,8 @@ def test_update_value_value_error(self): test_update_value_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4364,7 +4412,7 @@ def test_update_value_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_value(**req_copy) + _service.update_value(**req_copy) @@ -4388,7 +4436,7 @@ def test_delete_value_all_params(self): delete_value() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') responses.add(responses.DELETE, url, status=200) @@ -4399,7 +4447,7 @@ def test_delete_value_all_params(self): value = 'testString' # Invoke method - response = service.delete_value( + response = _service.delete_value( workspace_id, entity, value, @@ -4417,7 +4465,7 @@ def test_delete_value_value_error(self): test_delete_value_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') responses.add(responses.DELETE, url, status=200) @@ -4436,7 +4484,7 @@ def test_delete_value_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_value(**req_copy) + _service.delete_value(**req_copy) @@ -4470,8 +4518,8 @@ def test_list_synonyms_all_params(self): list_synonyms() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') - mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -4489,7 +4537,7 @@ def test_list_synonyms_all_params(self): include_audit = True # Invoke method - response = service.list_synonyms( + response = _service.list_synonyms( workspace_id, entity, value, @@ -4520,8 +4568,8 @@ def test_list_synonyms_required_params(self): test_list_synonyms_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') - mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -4534,7 +4582,7 @@ def test_list_synonyms_required_params(self): value = 'testString' # Invoke method - response = service.list_synonyms( + response = _service.list_synonyms( workspace_id, entity, value, @@ -4552,8 +4600,8 @@ def test_list_synonyms_value_error(self): test_list_synonyms_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') - mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -4574,7 +4622,7 @@ def test_list_synonyms_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_synonyms(**req_copy) + _service.list_synonyms(**req_copy) @@ -4598,8 +4646,8 @@ def test_create_synonym_all_params(self): create_synonym() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') - mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4614,7 +4662,7 @@ def test_create_synonym_all_params(self): include_audit = True # Invoke method - response = service.create_synonym( + response = _service.create_synonym( workspace_id, entity, value, @@ -4641,8 +4689,8 @@ def test_create_synonym_required_params(self): test_create_synonym_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') - mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4656,7 +4704,7 @@ def test_create_synonym_required_params(self): synonym = 'testString' # Invoke method - response = service.create_synonym( + response = _service.create_synonym( workspace_id, entity, value, @@ -4678,8 +4726,8 @@ def test_create_synonym_value_error(self): test_create_synonym_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') - mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4702,7 +4750,7 @@ def test_create_synonym_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_synonym(**req_copy) + _service.create_synonym(**req_copy) @@ -4726,8 +4774,8 @@ def test_get_synonym_all_params(self): get_synonym() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4742,7 +4790,7 @@ def test_get_synonym_all_params(self): include_audit = True # Invoke method - response = service.get_synonym( + response = _service.get_synonym( workspace_id, entity, value, @@ -4766,8 +4814,8 @@ def test_get_synonym_required_params(self): test_get_synonym_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4781,7 +4829,7 @@ def test_get_synonym_required_params(self): synonym = 'testString' # Invoke method - response = service.get_synonym( + response = _service.get_synonym( workspace_id, entity, value, @@ -4800,8 +4848,8 @@ def test_get_synonym_value_error(self): test_get_synonym_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4824,7 +4872,7 @@ def test_get_synonym_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_synonym(**req_copy) + _service.get_synonym(**req_copy) @@ -4848,8 +4896,8 @@ def test_update_synonym_all_params(self): update_synonym() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4865,7 +4913,7 @@ def test_update_synonym_all_params(self): include_audit = True # Invoke method - response = service.update_synonym( + response = _service.update_synonym( workspace_id, entity, value, @@ -4893,8 +4941,8 @@ def test_update_synonym_required_params(self): test_update_synonym_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4909,7 +4957,7 @@ def test_update_synonym_required_params(self): new_synonym = 'testString' # Invoke method - response = service.update_synonym( + response = _service.update_synonym( workspace_id, entity, value, @@ -4932,8 +4980,8 @@ def test_update_synonym_value_error(self): test_update_synonym_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4957,7 +5005,7 @@ def test_update_synonym_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_synonym(**req_copy) + _service.update_synonym(**req_copy) @@ -4981,7 +5029,7 @@ def test_delete_synonym_all_params(self): delete_synonym() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') responses.add(responses.DELETE, url, status=200) @@ -4993,7 +5041,7 @@ def test_delete_synonym_all_params(self): synonym = 'testString' # Invoke method - response = service.delete_synonym( + response = _service.delete_synonym( workspace_id, entity, value, @@ -5012,7 +5060,7 @@ def test_delete_synonym_value_error(self): test_delete_synonym_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') responses.add(responses.DELETE, url, status=200) @@ -5033,7 +5081,7 @@ def test_delete_synonym_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_synonym(**req_copy) + _service.delete_synonym(**req_copy) @@ -5067,8 +5115,8 @@ def test_list_dialog_nodes_all_params(self): list_dialog_nodes() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5084,7 +5132,7 @@ def test_list_dialog_nodes_all_params(self): include_audit = True # Invoke method - response = service.list_dialog_nodes( + response = _service.list_dialog_nodes( workspace_id, page_limit=page_limit, include_count=include_count, @@ -5113,8 +5161,8 @@ def test_list_dialog_nodes_required_params(self): test_list_dialog_nodes_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5125,7 +5173,7 @@ def test_list_dialog_nodes_required_params(self): workspace_id = 'testString' # Invoke method - response = service.list_dialog_nodes( + response = _service.list_dialog_nodes( workspace_id, headers={} ) @@ -5141,8 +5189,8 @@ def test_list_dialog_nodes_value_error(self): test_list_dialog_nodes_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5159,7 +5207,7 @@ def test_list_dialog_nodes_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_dialog_nodes(**req_copy) + _service.list_dialog_nodes(**req_copy) @@ -5183,20 +5231,36 @@ def test_create_dialog_node_all_params(self): create_dialog_node() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + # Construct a dict representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model = {} + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a dict representation of a ChannelTransferTarget model + channel_transfer_target_model = {} + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a dict representation of a ChannelTransferInfo model + channel_transfer_info_model = {} + channel_transfer_info_model['target'] = channel_transfer_target_model + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5252,7 +5316,7 @@ def test_create_dialog_node_all_params(self): include_audit = True # Invoke method - response = service.create_dialog_node( + response = _service.create_dialog_node( workspace_id, dialog_node, description=description, @@ -5313,20 +5377,36 @@ def test_create_dialog_node_required_params(self): test_create_dialog_node_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + # Construct a dict representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model = {} + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a dict representation of a ChannelTransferTarget model + channel_transfer_target_model = {} + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a dict representation of a ChannelTransferInfo model + channel_transfer_info_model = {} + channel_transfer_info_model['target'] = channel_transfer_target_model + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5381,7 +5461,7 @@ def test_create_dialog_node_required_params(self): disambiguation_opt_out = True # Invoke method - response = service.create_dialog_node( + response = _service.create_dialog_node( workspace_id, dialog_node, description=description, @@ -5437,20 +5517,36 @@ def test_create_dialog_node_value_error(self): test_create_dialog_node_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + # Construct a dict representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model = {} + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a dict representation of a ChannelTransferTarget model + channel_transfer_target_model = {} + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a dict representation of a ChannelTransferInfo model + channel_transfer_info_model = {} + channel_transfer_info_model['target'] = channel_transfer_target_model + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5512,7 +5608,7 @@ def test_create_dialog_node_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_dialog_node(**req_copy) + _service.create_dialog_node(**req_copy) @@ -5536,8 +5632,8 @@ def test_get_dialog_node_all_params(self): get_dialog_node() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5550,7 +5646,7 @@ def test_get_dialog_node_all_params(self): include_audit = True # Invoke method - response = service.get_dialog_node( + response = _service.get_dialog_node( workspace_id, dialog_node, include_audit=include_audit, @@ -5572,8 +5668,8 @@ def test_get_dialog_node_required_params(self): test_get_dialog_node_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5585,7 +5681,7 @@ def test_get_dialog_node_required_params(self): dialog_node = 'testString' # Invoke method - response = service.get_dialog_node( + response = _service.get_dialog_node( workspace_id, dialog_node, headers={} @@ -5602,8 +5698,8 @@ def test_get_dialog_node_value_error(self): test_get_dialog_node_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5622,7 +5718,7 @@ def test_get_dialog_node_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_dialog_node(**req_copy) + _service.get_dialog_node(**req_copy) @@ -5646,20 +5742,36 @@ def test_update_dialog_node_all_params(self): update_dialog_node() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + # Construct a dict representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model = {} + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a dict representation of a ChannelTransferTarget model + channel_transfer_target_model = {} + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a dict representation of a ChannelTransferInfo model + channel_transfer_info_model = {} + channel_transfer_info_model['target'] = channel_transfer_target_model + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5716,7 +5828,7 @@ def test_update_dialog_node_all_params(self): include_audit = True # Invoke method - response = service.update_dialog_node( + response = _service.update_dialog_node( workspace_id, dialog_node, new_dialog_node=new_dialog_node, @@ -5778,20 +5890,36 @@ def test_update_dialog_node_required_params(self): test_update_dialog_node_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + # Construct a dict representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model = {} + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a dict representation of a ChannelTransferTarget model + channel_transfer_target_model = {} + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a dict representation of a ChannelTransferInfo model + channel_transfer_info_model = {} + channel_transfer_info_model['target'] = channel_transfer_target_model + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5847,7 +5975,7 @@ def test_update_dialog_node_required_params(self): new_disambiguation_opt_out = True # Invoke method - response = service.update_dialog_node( + response = _service.update_dialog_node( workspace_id, dialog_node, new_dialog_node=new_dialog_node, @@ -5904,20 +6032,36 @@ def test_update_dialog_node_value_error(self): test_update_dialog_node_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "image", "source": "source", "title": "title", "description": "description"}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model + # Construct a dict representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model = {} + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a dict representation of a ChannelTransferTarget model + channel_transfer_target_model = {} + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a dict representation of a ChannelTransferInfo model + channel_transfer_info_model = {} + channel_transfer_info_model['target'] = channel_transfer_target_model + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5980,7 +6124,7 @@ def test_update_dialog_node_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_dialog_node(**req_copy) + _service.update_dialog_node(**req_copy) @@ -6004,7 +6148,7 @@ def test_delete_dialog_node_all_params(self): delete_dialog_node() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') responses.add(responses.DELETE, url, status=200) @@ -6014,7 +6158,7 @@ def test_delete_dialog_node_all_params(self): dialog_node = 'testString' # Invoke method - response = service.delete_dialog_node( + response = _service.delete_dialog_node( workspace_id, dialog_node, headers={} @@ -6031,7 +6175,7 @@ def test_delete_dialog_node_value_error(self): test_delete_dialog_node_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/dialog_nodes/testString') + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') responses.add(responses.DELETE, url, status=200) @@ -6048,7 +6192,7 @@ def test_delete_dialog_node_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_dialog_node(**req_copy) + _service.delete_dialog_node(**req_copy) @@ -6082,8 +6226,8 @@ def test_list_logs_all_params(self): list_logs() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6098,7 +6242,7 @@ def test_list_logs_all_params(self): cursor = 'testString' # Invoke method - response = service.list_logs( + response = _service.list_logs( workspace_id, sort=sort, filter=filter, @@ -6125,8 +6269,8 @@ def test_list_logs_required_params(self): test_list_logs_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6137,7 +6281,7 @@ def test_list_logs_required_params(self): workspace_id = 'testString' # Invoke method - response = service.list_logs( + response = _service.list_logs( workspace_id, headers={} ) @@ -6153,8 +6297,8 @@ def test_list_logs_value_error(self): test_list_logs_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/workspaces/testString/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6171,7 +6315,7 @@ def test_list_logs_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_logs(**req_copy) + _service.list_logs(**req_copy) @@ -6195,8 +6339,8 @@ def test_list_all_logs_all_params(self): list_all_logs() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6210,7 +6354,7 @@ def test_list_all_logs_all_params(self): cursor = 'testString' # Invoke method - response = service.list_all_logs( + response = _service.list_all_logs( filter, sort=sort, page_limit=page_limit, @@ -6236,8 +6380,8 @@ def test_list_all_logs_required_params(self): test_list_all_logs_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6248,7 +6392,7 @@ def test_list_all_logs_required_params(self): filter = 'testString' # Invoke method - response = service.list_all_logs( + response = _service.list_all_logs( filter, headers={} ) @@ -6268,8 +6412,8 @@ def test_list_all_logs_value_error(self): test_list_all_logs_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg"}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}]}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v1/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6286,7 +6430,7 @@ def test_list_all_logs_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_all_logs(**req_copy) + _service.list_all_logs(**req_copy) @@ -6320,7 +6464,7 @@ def test_delete_user_data_all_params(self): delete_user_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/user_data') + url = self.preprocess_url(_base_url + '/v1/user_data') responses.add(responses.DELETE, url, status=202) @@ -6329,7 +6473,7 @@ def test_delete_user_data_all_params(self): customer_id = 'testString' # Invoke method - response = service.delete_user_data( + response = _service.delete_user_data( customer_id, headers={} ) @@ -6349,7 +6493,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/user_data') + url = self.preprocess_url(_base_url + '/v1/user_data') responses.add(responses.DELETE, url, status=202) @@ -6364,7 +6508,7 @@ def test_delete_user_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_user_data(**req_copy) + _service.delete_user_data(**req_copy) @@ -6649,6 +6793,106 @@ def test_capture_group_serialization(self): capture_group_model_json2 = capture_group_model.to_dict() assert capture_group_model_json2 == capture_group_model_json +class TestChannelTransferInfo(): + """ + Test Class for ChannelTransferInfo + """ + + def test_channel_transfer_info_serialization(self): + """ + Test serialization/deserialization for ChannelTransferInfo + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a json representation of a ChannelTransferInfo model + channel_transfer_info_model_json = {} + channel_transfer_info_model_json['target'] = channel_transfer_target_model + + # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation + channel_transfer_info_model = ChannelTransferInfo.from_dict(channel_transfer_info_model_json) + assert channel_transfer_info_model != False + + # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation + channel_transfer_info_model_dict = ChannelTransferInfo.from_dict(channel_transfer_info_model_json).__dict__ + channel_transfer_info_model2 = ChannelTransferInfo(**channel_transfer_info_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_info_model == channel_transfer_info_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() + assert channel_transfer_info_model_json2 == channel_transfer_info_model_json + +class TestChannelTransferTarget(): + """ + Test Class for ChannelTransferTarget + """ + + def test_channel_transfer_target_serialization(self): + """ + Test serialization/deserialization for ChannelTransferTarget + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a json representation of a ChannelTransferTarget model + channel_transfer_target_model_json = {} + channel_transfer_target_model_json['chat'] = channel_transfer_target_chat_model + + # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation + channel_transfer_target_model = ChannelTransferTarget.from_dict(channel_transfer_target_model_json) + assert channel_transfer_target_model != False + + # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation + channel_transfer_target_model_dict = ChannelTransferTarget.from_dict(channel_transfer_target_model_json).__dict__ + channel_transfer_target_model2 = ChannelTransferTarget(**channel_transfer_target_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_target_model == channel_transfer_target_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() + assert channel_transfer_target_model_json2 == channel_transfer_target_model_json + +class TestChannelTransferTargetChat(): + """ + Test Class for ChannelTransferTargetChat + """ + + def test_channel_transfer_target_chat_serialization(self): + """ + Test serialization/deserialization for ChannelTransferTargetChat + """ + + # Construct a json representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model_json = {} + channel_transfer_target_chat_model_json['url'] = 'testString' + + # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation + channel_transfer_target_chat_model = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json) + assert channel_transfer_target_chat_model != False + + # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation + channel_transfer_target_chat_model_dict = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json).__dict__ + channel_transfer_target_chat_model2 = ChannelTransferTargetChat(**channel_transfer_target_chat_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_target_chat_model == channel_transfer_target_chat_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() + assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json + class TestContext(): """ Test Class for Context @@ -6700,8 +6944,8 @@ def test_counterexample_serialization(self): # Construct a json representation of a Counterexample model counterexample_model_json = {} counterexample_model_json['text'] = 'testString' - counterexample_model_json['created'] = '2020-01-28T18:40:40.123456Z' - counterexample_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + counterexample_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + counterexample_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of Counterexample by calling from_dict on the json representation counterexample_model = Counterexample.from_dict(counterexample_model_json) @@ -6732,8 +6976,8 @@ def test_counterexample_collection_serialization(self): counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2020-01-28T18:40:40.123456Z' - counterexample_model['updated'] = '2020-01-28T18:40:40.123456Z' + counterexample_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + counterexample_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -6781,8 +7025,8 @@ def test_create_entity_serialization(self): create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] - create_value_model['created'] = '2020-01-28T18:40:40.123456Z' - create_value_model['updated'] = '2020-01-28T18:40:40.123456Z' + create_value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + create_value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a json representation of a CreateEntity model create_entity_model_json = {} @@ -6790,8 +7034,8 @@ def test_create_entity_serialization(self): create_entity_model_json['description'] = 'testString' create_entity_model_json['metadata'] = {} create_entity_model_json['fuzzy_match'] = True - create_entity_model_json['created'] = '2020-01-28T18:40:40.123456Z' - create_entity_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + create_entity_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + create_entity_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) create_entity_model_json['values'] = [create_value_model] # Construct a model instance of CreateEntity by calling from_dict on the json representation @@ -6828,15 +7072,15 @@ def test_create_intent_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2020-01-28T18:40:40.123456Z' - example_model['updated'] = '2020-01-28T18:40:40.123456Z' + example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a json representation of a CreateIntent model create_intent_model_json = {} create_intent_model_json['intent'] = 'testString' create_intent_model_json['description'] = 'testString' - create_intent_model_json['created'] = '2020-01-28T18:40:40.123456Z' - create_intent_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + create_intent_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + create_intent_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) create_intent_model_json['examples'] = [example_model] # Construct a model instance of CreateIntent by calling from_dict on the json representation @@ -6871,8 +7115,8 @@ def test_create_value_serialization(self): create_value_model_json['type'] = 'synonyms' create_value_model_json['synonyms'] = ['testString'] create_value_model_json['patterns'] = ['testString'] - create_value_model_json['created'] = '2020-01-28T18:40:40.123456Z' - create_value_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + create_value_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + create_value_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of CreateValue by calling from_dict on the json representation create_value_model = CreateValue.from_dict(create_value_model_json) @@ -6901,11 +7145,23 @@ def test_dialog_node_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeImage - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model['target'] = channel_transfer_target_model + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -6954,8 +7210,8 @@ def test_dialog_node_serialization(self): dialog_node_model_json['user_label'] = 'testString' dialog_node_model_json['disambiguation_opt_out'] = True dialog_node_model_json['disabled'] = True - dialog_node_model_json['created'] = '2020-01-28T18:40:40.123456Z' - dialog_node_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + dialog_node_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + dialog_node_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of DialogNode by calling from_dict on the json representation dialog_node_model = DialogNode.from_dict(dialog_node_model_json) @@ -7017,11 +7273,23 @@ def test_dialog_node_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeImage - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model['target'] = channel_transfer_target_model + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -7069,8 +7337,8 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = True dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2020-01-28T18:40:40.123456Z' - dialog_node_model['updated'] = '2020-01-28T18:40:40.123456Z' + dialog_node_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + dialog_node_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -7173,11 +7441,23 @@ def test_dialog_node_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeImage - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model['target'] = channel_transfer_target_model + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -7730,8 +8010,8 @@ def test_entity_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2020-01-28T18:40:40.123456Z' - value_model['updated'] = '2020-01-28T18:40:40.123456Z' + value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a json representation of a Entity model entity_model_json = {} @@ -7739,8 +8019,8 @@ def test_entity_serialization(self): entity_model_json['description'] = 'testString' entity_model_json['metadata'] = {} entity_model_json['fuzzy_match'] = True - entity_model_json['created'] = '2020-01-28T18:40:40.123456Z' - entity_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + entity_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + entity_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) entity_model_json['values'] = [value_model] # Construct a model instance of Entity by calling from_dict on the json representation @@ -7776,16 +8056,16 @@ def test_entity_collection_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2020-01-28T18:40:40.123456Z' - value_model['updated'] = '2020-01-28T18:40:40.123456Z' + value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' entity_model['metadata'] = {} entity_model['fuzzy_match'] = True - entity_model['created'] = '2020-01-28T18:40:40.123456Z' - entity_model['updated'] = '2020-01-28T18:40:40.123456Z' + entity_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + entity_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) entity_model['values'] = [value_model] pagination_model = {} # Pagination @@ -7912,8 +8192,8 @@ def test_example_serialization(self): example_model_json = {} example_model_json['text'] = 'testString' example_model_json['mentions'] = [mention_model] - example_model_json['created'] = '2020-01-28T18:40:40.123456Z' - example_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + example_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of Example by calling from_dict on the json representation example_model = Example.from_dict(example_model_json) @@ -7949,8 +8229,8 @@ def test_example_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2020-01-28T18:40:40.123456Z' - example_model['updated'] = '2020-01-28T18:40:40.123456Z' + example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -7999,15 +8279,15 @@ def test_intent_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2020-01-28T18:40:40.123456Z' - example_model['updated'] = '2020-01-28T18:40:40.123456Z' + example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a json representation of a Intent model intent_model_json = {} intent_model_json['intent'] = 'testString' intent_model_json['description'] = 'testString' - intent_model_json['created'] = '2020-01-28T18:40:40.123456Z' - intent_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + intent_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + intent_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) intent_model_json['examples'] = [example_model] # Construct a model instance of Intent by calling from_dict on the json representation @@ -8044,14 +8324,14 @@ def test_intent_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2020-01-28T18:40:40.123456Z' - example_model['updated'] = '2020-01-28T18:40:40.123456Z' + example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2020-01-28T18:40:40.123456Z' - intent_model['updated'] = '2020-01-28T18:40:40.123456Z' + intent_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + intent_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) intent_model['examples'] = [example_model] pagination_model = {} # Pagination @@ -8171,9 +8451,15 @@ def test_log_serialization(self): dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' + log_message_source_model = {} # LogMessageSource + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' + log_message_model['code'] = 'testString' + log_message_model['source'] = log_message_source_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model @@ -8184,12 +8470,16 @@ def test_log_serialization(self): dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption runtime_response_generic_model['response_type'] = 'option' runtime_response_generic_model['title'] = 'testString' runtime_response_generic_model['description'] = 'testString' runtime_response_generic_model['preference'] = 'dropdown' runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] @@ -8214,6 +8504,7 @@ def test_log_serialization(self): message_request_model['context'] = context_model message_request_model['output'] = output_data_model message_request_model['actions'] = [dialog_node_action_model] + message_request_model['user_id'] = 'testString' message_response_model = {} # MessageResponse message_response_model['input'] = message_input_model @@ -8223,6 +8514,7 @@ def test_log_serialization(self): message_response_model['context'] = context_model message_response_model['output'] = output_data_model message_response_model['actions'] = [dialog_node_action_model] + message_response_model['user_id'] = 'testString' # Construct a json representation of a Log model log_model_json = {} @@ -8338,9 +8630,15 @@ def test_log_collection_serialization(self): dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' + log_message_source_model = {} # LogMessageSource + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' + log_message_model['code'] = 'testString' + log_message_model['source'] = log_message_source_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model @@ -8351,12 +8649,16 @@ def test_log_collection_serialization(self): dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption runtime_response_generic_model['response_type'] = 'option' runtime_response_generic_model['title'] = 'testString' runtime_response_generic_model['description'] = 'testString' runtime_response_generic_model['preference'] = 'dropdown' runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] @@ -8381,6 +8683,7 @@ def test_log_collection_serialization(self): message_request_model['context'] = context_model message_request_model['output'] = output_data_model message_request_model['actions'] = [dialog_node_action_model] + message_request_model['user_id'] = 'testString' message_response_model = {} # MessageResponse message_response_model['input'] = message_input_model @@ -8390,6 +8693,7 @@ def test_log_collection_serialization(self): message_response_model['context'] = context_model message_response_model['output'] = output_data_model message_response_model['actions'] = [dialog_node_action_model] + message_response_model['user_id'] = 'testString' log_model = {} # Log log_model['request'] = message_request_model @@ -8435,10 +8739,18 @@ def test_log_message_serialization(self): Test serialization/deserialization for LogMessage """ + # Construct dict forms of any model objects needed in order to build this model. + + log_message_source_model = {} # LogMessageSource + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + # Construct a json representation of a LogMessage model log_message_model_json = {} log_message_model_json['level'] = 'info' log_message_model_json['msg'] = 'testString' + log_message_model_json['code'] = 'testString' + log_message_model_json['source'] = log_message_source_model # Construct a model instance of LogMessage by calling from_dict on the json representation log_message_model = LogMessage.from_dict(log_message_model_json) @@ -8455,6 +8767,36 @@ def test_log_message_serialization(self): log_message_model_json2 = log_message_model.to_dict() assert log_message_model_json2 == log_message_model_json +class TestLogMessageSource(): + """ + Test Class for LogMessageSource + """ + + def test_log_message_source_serialization(self): + """ + Test serialization/deserialization for LogMessageSource + """ + + # Construct a json representation of a LogMessageSource model + log_message_source_model_json = {} + log_message_source_model_json['type'] = 'dialog_node' + log_message_source_model_json['dialog_node'] = 'testString' + + # Construct a model instance of LogMessageSource by calling from_dict on the json representation + log_message_source_model = LogMessageSource.from_dict(log_message_source_model_json) + assert log_message_source_model != False + + # Construct a model instance of LogMessageSource by calling from_dict on the json representation + log_message_source_model_dict = LogMessageSource.from_dict(log_message_source_model_json).__dict__ + log_message_source_model2 = LogMessageSource(**log_message_source_model_dict) + + # Verify the model instances are equivalent + assert log_message_source_model == log_message_source_model2 + + # Convert model instance back to dict and verify no loss of data + log_message_source_model_json2 = log_message_source_model.to_dict() + assert log_message_source_model_json2 == log_message_source_model_json + class TestLogPagination(): """ Test Class for LogPagination @@ -8669,9 +9011,15 @@ def test_message_request_serialization(self): dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' + log_message_source_model = {} # LogMessageSource + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' + log_message_model['code'] = 'testString' + log_message_model['source'] = log_message_source_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model @@ -8682,12 +9030,16 @@ def test_message_request_serialization(self): dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption runtime_response_generic_model['response_type'] = 'option' runtime_response_generic_model['title'] = 'testString' runtime_response_generic_model['description'] = 'testString' runtime_response_generic_model['preference'] = 'dropdown' runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] @@ -8713,6 +9065,7 @@ def test_message_request_serialization(self): message_request_model_json['context'] = context_model message_request_model_json['output'] = output_data_model message_request_model_json['actions'] = [dialog_node_action_model] + message_request_model_json['user_id'] = 'testString' # Construct a model instance of MessageRequest by calling from_dict on the json representation message_request_model = MessageRequest.from_dict(message_request_model_json) @@ -8818,9 +9171,15 @@ def test_message_response_serialization(self): dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' + log_message_source_model = {} # LogMessageSource + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' + log_message_model['code'] = 'testString' + log_message_model['source'] = log_message_source_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model @@ -8831,12 +9190,16 @@ def test_message_response_serialization(self): dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption runtime_response_generic_model['response_type'] = 'option' runtime_response_generic_model['title'] = 'testString' runtime_response_generic_model['description'] = 'testString' runtime_response_generic_model['preference'] = 'dropdown' runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] @@ -8862,6 +9225,7 @@ def test_message_response_serialization(self): message_response_model_json['context'] = context_model message_response_model_json['output'] = output_data_model message_response_model_json['actions'] = [dialog_node_action_model] + message_response_model_json['user_id'] = 'testString' # Construct a model instance of MessageResponse by calling from_dict on the json representation message_response_model = MessageResponse.from_dict(message_response_model_json) @@ -8895,9 +9259,15 @@ def test_output_data_serialization(self): dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' + log_message_source_model = {} # LogMessageSource + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' + log_message_model['code'] = 'testString' + log_message_model['source'] = log_message_source_model message_input_model = {} # MessageInput message_input_model['text'] = 'testString' @@ -8970,12 +9340,16 @@ def test_output_data_serialization(self): dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption runtime_response_generic_model['response_type'] = 'option' runtime_response_generic_model['title'] = 'testString' runtime_response_generic_model['description'] = 'testString' runtime_response_generic_model['preference'] = 'dropdown' runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['channels'] = [response_generic_channel_model] # Construct a json representation of a OutputData model output_data_model_json = {} @@ -9035,6 +9409,35 @@ def test_pagination_serialization(self): pagination_model_json2 = pagination_model.to_dict() assert pagination_model_json2 == pagination_model_json +class TestResponseGenericChannel(): + """ + Test Class for ResponseGenericChannel + """ + + def test_response_generic_channel_serialization(self): + """ + Test serialization/deserialization for ResponseGenericChannel + """ + + # Construct a json representation of a ResponseGenericChannel model + response_generic_channel_model_json = {} + response_generic_channel_model_json['channel'] = 'chat' + + # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation + response_generic_channel_model = ResponseGenericChannel.from_dict(response_generic_channel_model_json) + assert response_generic_channel_model != False + + # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation + response_generic_channel_model_dict = ResponseGenericChannel.from_dict(response_generic_channel_model_json).__dict__ + response_generic_channel_model2 = ResponseGenericChannel(**response_generic_channel_model_dict) + + # Verify the model instances are equivalent + assert response_generic_channel_model == response_generic_channel_model2 + + # Convert model instance back to dict and verify no loss of data + response_generic_channel_model_json2 = response_generic_channel_model.to_dict() + assert response_generic_channel_model_json2 == response_generic_channel_model_json + class TestRuntimeEntity(): """ Test Class for RuntimeEntity @@ -9269,8 +9672,8 @@ def test_synonym_serialization(self): # Construct a json representation of a Synonym model synonym_model_json = {} synonym_model_json['synonym'] = 'testString' - synonym_model_json['created'] = '2020-01-28T18:40:40.123456Z' - synonym_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + synonym_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + synonym_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of Synonym by calling from_dict on the json representation synonym_model = Synonym.from_dict(synonym_model_json) @@ -9301,8 +9704,8 @@ def test_synonym_collection_serialization(self): synonym_model = {} # Synonym synonym_model['synonym'] = 'testString' - synonym_model['created'] = '2020-01-28T18:40:40.123456Z' - synonym_model['updated'] = '2020-01-28T18:40:40.123456Z' + synonym_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + synonym_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -9349,8 +9752,8 @@ def test_value_serialization(self): value_model_json['type'] = 'synonyms' value_model_json['synonyms'] = ['testString'] value_model_json['patterns'] = ['testString'] - value_model_json['created'] = '2020-01-28T18:40:40.123456Z' - value_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + value_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of Value by calling from_dict on the json representation value_model = Value.from_dict(value_model_json) @@ -9385,8 +9788,8 @@ def test_value_collection_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2020-01-28T18:40:40.123456Z' - value_model['updated'] = '2020-01-28T18:40:40.123456Z' + value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -9495,11 +9898,23 @@ def test_workspace_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeImage - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model['target'] = channel_transfer_target_model + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -9547,13 +9962,13 @@ def test_workspace_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = True dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2020-01-28T18:40:40.123456Z' - dialog_node_model['updated'] = '2020-01-28T18:40:40.123456Z' + dialog_node_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + dialog_node_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2020-01-28T18:40:40.123456Z' - counterexample_model['updated'] = '2020-01-28T18:40:40.123456Z' + counterexample_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + counterexample_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True @@ -9598,14 +10013,14 @@ def test_workspace_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2020-01-28T18:40:40.123456Z' - example_model['updated'] = '2020-01-28T18:40:40.123456Z' + example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2020-01-28T18:40:40.123456Z' - intent_model['updated'] = '2020-01-28T18:40:40.123456Z' + intent_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + intent_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) intent_model['examples'] = [example_model] value_model = {} # Value @@ -9614,16 +10029,16 @@ def test_workspace_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2020-01-28T18:40:40.123456Z' - value_model['updated'] = '2020-01-28T18:40:40.123456Z' + value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' entity_model['metadata'] = {} entity_model['fuzzy_match'] = True - entity_model['created'] = '2020-01-28T18:40:40.123456Z' - entity_model['updated'] = '2020-01-28T18:40:40.123456Z' + entity_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + entity_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) entity_model['values'] = [value_model] # Construct a json representation of a Workspace model @@ -9634,8 +10049,8 @@ def test_workspace_serialization(self): workspace_model_json['workspace_id'] = 'testString' workspace_model_json['dialog_nodes'] = [dialog_node_model] workspace_model_json['counterexamples'] = [counterexample_model] - workspace_model_json['created'] = '2020-01-28T18:40:40.123456Z' - workspace_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + workspace_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + workspace_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) workspace_model_json['metadata'] = {} workspace_model_json['learning_opt_out'] = True workspace_model_json['system_settings'] = workspace_system_settings_model @@ -9671,11 +10086,23 @@ def test_workspace_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeImage - dialog_node_output_generic_model['response_type'] = 'image' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model['target'] = channel_transfer_target_model + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer + dialog_node_output_generic_model['response_type'] = 'channel_transfer' + dialog_node_output_generic_model['message_to_user'] = 'testString' + dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -9723,13 +10150,13 @@ def test_workspace_collection_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = True dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2020-01-28T18:40:40.123456Z' - dialog_node_model['updated'] = '2020-01-28T18:40:40.123456Z' + dialog_node_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + dialog_node_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2020-01-28T18:40:40.123456Z' - counterexample_model['updated'] = '2020-01-28T18:40:40.123456Z' + counterexample_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + counterexample_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True @@ -9774,14 +10201,14 @@ def test_workspace_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2020-01-28T18:40:40.123456Z' - example_model['updated'] = '2020-01-28T18:40:40.123456Z' + example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2020-01-28T18:40:40.123456Z' - intent_model['updated'] = '2020-01-28T18:40:40.123456Z' + intent_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + intent_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) intent_model['examples'] = [example_model] value_model = {} # Value @@ -9790,16 +10217,16 @@ def test_workspace_collection_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2020-01-28T18:40:40.123456Z' - value_model['updated'] = '2020-01-28T18:40:40.123456Z' + value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' entity_model['metadata'] = {} entity_model['fuzzy_match'] = True - entity_model['created'] = '2020-01-28T18:40:40.123456Z' - entity_model['updated'] = '2020-01-28T18:40:40.123456Z' + entity_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + entity_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) entity_model['values'] = [value_model] workspace_model = {} # Workspace @@ -9809,8 +10236,8 @@ def test_workspace_collection_serialization(self): workspace_model['workspace_id'] = 'testString' workspace_model['dialog_nodes'] = [dialog_node_model] workspace_model['counterexamples'] = [counterexample_model] - workspace_model['created'] = '2020-01-28T18:40:40.123456Z' - workspace_model['updated'] = '2020-01-28T18:40:40.123456Z' + workspace_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + workspace_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) workspace_model['metadata'] = {} workspace_model['learning_opt_out'] = True workspace_model['system_settings'] = workspace_system_settings_model @@ -10024,6 +10451,52 @@ def test_workspace_system_settings_tooling_serialization(self): workspace_system_settings_tooling_model_json2 = workspace_system_settings_tooling_model.to_dict() assert workspace_system_settings_tooling_model_json2 == workspace_system_settings_tooling_model_json +class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer(): + """ + Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer + """ + + def test_dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model['target'] = channel_transfer_target_model + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model + dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json = {} + dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json['response_type'] = 'channel_transfer' + dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json['message_to_user'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json['channels'] = [response_generic_channel_model] + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer.from_dict(dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json) + assert dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model != False + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_dict = DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer.from_dict(dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json).__dict__ + dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model2 = DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer(**dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model == dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model.to_dict() + assert dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json + class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent(): """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent @@ -10042,6 +10515,9 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent model dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['response_type'] = 'connect_to_agent' @@ -10049,6 +10525,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['agent_available'] = agent_availability_message_model dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['agent_unavailable'] = agent_availability_message_model dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['transfer_info'] = dialog_node_output_connect_to_agent_transfer_info_model + dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent by calling from_dict on the json representation dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent.from_dict(dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json) @@ -10075,12 +10552,18 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_image_seria Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeImage """ + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model dialog_node_output_generic_dialog_node_output_response_type_image_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_image_model_json['response_type'] = 'image' dialog_node_output_generic_dialog_node_output_response_type_image_model_json['source'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_image_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_image_model_json['description'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_image_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeImage by calling from_dict on the json representation dialog_node_output_generic_dialog_node_output_response_type_image_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeImage.from_dict(dialog_node_output_generic_dialog_node_output_response_type_image_model_json) @@ -10180,6 +10663,9 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption model dialog_node_output_generic_dialog_node_output_response_type_option_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_option_model_json['response_type'] = 'option' @@ -10187,6 +10673,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri dialog_node_output_generic_dialog_node_output_response_type_option_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_option_model_json['preference'] = 'dropdown' dialog_node_output_generic_dialog_node_output_response_type_option_model_json['options'] = [dialog_node_output_options_element_model] + dialog_node_output_generic_dialog_node_output_response_type_option_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeOption by calling from_dict on the json representation dialog_node_output_generic_dialog_node_output_response_type_option_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeOption.from_dict(dialog_node_output_generic_dialog_node_output_response_type_option_model_json) @@ -10213,11 +10700,17 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_pause_seria Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypePause """ + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypePause model dialog_node_output_generic_dialog_node_output_response_type_pause_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_pause_model_json['response_type'] = 'pause' dialog_node_output_generic_dialog_node_output_response_type_pause_model_json['time'] = 38 dialog_node_output_generic_dialog_node_output_response_type_pause_model_json['typing'] = True + dialog_node_output_generic_dialog_node_output_response_type_pause_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypePause by calling from_dict on the json representation dialog_node_output_generic_dialog_node_output_response_type_pause_model = DialogNodeOutputGenericDialogNodeOutputResponseTypePause.from_dict(dialog_node_output_generic_dialog_node_output_response_type_pause_model_json) @@ -10244,6 +10737,11 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_search_skil Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill """ + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill model dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['response_type'] = 'search_skill' @@ -10251,6 +10749,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_search_skil dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['query_type'] = 'natural_language' dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['filter'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['discovery_version'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill by calling from_dict on the json representation dialog_node_output_generic_dialog_node_output_response_type_search_skill_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill.from_dict(dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json) @@ -10282,12 +10781,16 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_dialog_node_output_response_type_text_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_text_model_json['response_type'] = 'text' dialog_node_output_generic_dialog_node_output_response_type_text_model_json['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_dialog_node_output_response_type_text_model_json['selection_policy'] = 'sequential' dialog_node_output_generic_dialog_node_output_response_type_text_model_json['delimiter'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_text_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeText by calling from_dict on the json representation dialog_node_output_generic_dialog_node_output_response_type_text_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeText.from_dict(dialog_node_output_generic_dialog_node_output_response_type_text_model_json) @@ -10304,6 +10807,88 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_text_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_text_model_json +class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined(): + """ + Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined + """ + + def test_dialog_node_output_generic_dialog_node_output_response_type_user_defined_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined model + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json = {} + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['response_type'] = 'user_defined' + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {} + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined.from_dict(dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json) + assert dialog_node_output_generic_dialog_node_output_response_type_user_defined_model != False + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_dict = DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined.from_dict(dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json).__dict__ + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model2 = DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined(**dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_generic_dialog_node_output_response_type_user_defined_model == dialog_node_output_generic_dialog_node_output_response_type_user_defined_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_user_defined_model.to_dict() + assert dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer + """ + + def test_runtime_response_generic_runtime_response_type_channel_transfer_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model['target'] = channel_transfer_target_model + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer model + runtime_response_generic_runtime_response_type_channel_transfer_model_json = {} + runtime_response_generic_runtime_response_type_channel_transfer_model_json['response_type'] = 'channel_transfer' + runtime_response_generic_runtime_response_type_channel_transfer_model_json['message_to_user'] = 'testString' + runtime_response_generic_runtime_response_type_channel_transfer_model_json['transfer_info'] = channel_transfer_info_model + runtime_response_generic_runtime_response_type_channel_transfer_model_json['channels'] = [response_generic_channel_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeChannelTransfer by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_channel_transfer_model = RuntimeResponseGenericRuntimeResponseTypeChannelTransfer.from_dict(runtime_response_generic_runtime_response_type_channel_transfer_model_json) + assert runtime_response_generic_runtime_response_type_channel_transfer_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeChannelTransfer by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_channel_transfer_model_dict = RuntimeResponseGenericRuntimeResponseTypeChannelTransfer.from_dict(runtime_response_generic_runtime_response_type_channel_transfer_model_json).__dict__ + runtime_response_generic_runtime_response_type_channel_transfer_model2 = RuntimeResponseGenericRuntimeResponseTypeChannelTransfer(**runtime_response_generic_runtime_response_type_channel_transfer_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_channel_transfer_model == runtime_response_generic_runtime_response_type_channel_transfer_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_channel_transfer_model_json2 = runtime_response_generic_runtime_response_type_channel_transfer_model.to_dict() + assert runtime_response_generic_runtime_response_type_channel_transfer_model_json2 == runtime_response_generic_runtime_response_type_channel_transfer_model_json + class TestRuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent @@ -10322,6 +10907,9 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent model runtime_response_generic_runtime_response_type_connect_to_agent_model_json = {} runtime_response_generic_runtime_response_type_connect_to_agent_model_json['response_type'] = 'connect_to_agent' @@ -10331,6 +10919,7 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json['transfer_info'] = dialog_node_output_connect_to_agent_transfer_info_model runtime_response_generic_runtime_response_type_connect_to_agent_model_json['topic'] = 'testString' runtime_response_generic_runtime_response_type_connect_to_agent_model_json['dialog_node'] = 'testString' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeConnectToAgent by calling from_dict on the json representation runtime_response_generic_runtime_response_type_connect_to_agent_model = RuntimeResponseGenericRuntimeResponseTypeConnectToAgent.from_dict(runtime_response_generic_runtime_response_type_connect_to_agent_model_json) @@ -10357,12 +10946,18 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeImage """ + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeImage model runtime_response_generic_runtime_response_type_image_model_json = {} runtime_response_generic_runtime_response_type_image_model_json['response_type'] = 'image' runtime_response_generic_runtime_response_type_image_model_json['source'] = 'testString' runtime_response_generic_runtime_response_type_image_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_image_model_json['description'] = 'testString' + runtime_response_generic_runtime_response_type_image_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeImage by calling from_dict on the json representation runtime_response_generic_runtime_response_type_image_model = RuntimeResponseGenericRuntimeResponseTypeImage.from_dict(runtime_response_generic_runtime_response_type_image_model_json) @@ -10462,6 +11057,9 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeOption model runtime_response_generic_runtime_response_type_option_model_json = {} runtime_response_generic_runtime_response_type_option_model_json['response_type'] = 'option' @@ -10469,6 +11067,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_response_generic_runtime_response_type_option_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_option_model_json['preference'] = 'dropdown' runtime_response_generic_runtime_response_type_option_model_json['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_runtime_response_type_option_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeOption by calling from_dict on the json representation runtime_response_generic_runtime_response_type_option_model = RuntimeResponseGenericRuntimeResponseTypeOption.from_dict(runtime_response_generic_runtime_response_type_option_model_json) @@ -10495,11 +11094,17 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypePause """ + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypePause model runtime_response_generic_runtime_response_type_pause_model_json = {} runtime_response_generic_runtime_response_type_pause_model_json['response_type'] = 'pause' runtime_response_generic_runtime_response_type_pause_model_json['time'] = 38 runtime_response_generic_runtime_response_type_pause_model_json['typing'] = True + runtime_response_generic_runtime_response_type_pause_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypePause by calling from_dict on the json representation runtime_response_generic_runtime_response_type_pause_model = RuntimeResponseGenericRuntimeResponseTypePause.from_dict(runtime_response_generic_runtime_response_type_pause_model_json) @@ -10601,11 +11206,15 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization dialog_suggestion_model['output'] = {} dialog_suggestion_model['dialog_node'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSuggestion model runtime_response_generic_runtime_response_type_suggestion_model_json = {} runtime_response_generic_runtime_response_type_suggestion_model_json['response_type'] = 'suggestion' runtime_response_generic_runtime_response_type_suggestion_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_suggestion_model_json['suggestions'] = [dialog_suggestion_model] + runtime_response_generic_runtime_response_type_suggestion_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeSuggestion by calling from_dict on the json representation runtime_response_generic_runtime_response_type_suggestion_model = RuntimeResponseGenericRuntimeResponseTypeSuggestion.from_dict(runtime_response_generic_runtime_response_type_suggestion_model_json) @@ -10632,10 +11241,16 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeText """ + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeText model runtime_response_generic_runtime_response_type_text_model_json = {} runtime_response_generic_runtime_response_type_text_model_json['response_type'] = 'text' runtime_response_generic_runtime_response_type_text_model_json['text'] = 'testString' + runtime_response_generic_runtime_response_type_text_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeText by calling from_dict on the json representation runtime_response_generic_runtime_response_type_text_model = RuntimeResponseGenericRuntimeResponseTypeText.from_dict(runtime_response_generic_runtime_response_type_text_model_json) @@ -10652,6 +11267,42 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) runtime_response_generic_runtime_response_type_text_model_json2 = runtime_response_generic_runtime_response_type_text_model.to_dict() assert runtime_response_generic_runtime_response_type_text_model_json2 == runtime_response_generic_runtime_response_type_text_model_json +class TestRuntimeResponseGenericRuntimeResponseTypeUserDefined(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeUserDefined + """ + + def test_runtime_response_generic_runtime_response_type_user_defined_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeUserDefined + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model + runtime_response_generic_runtime_response_type_user_defined_model_json = {} + runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {} + runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_user_defined_model = RuntimeResponseGenericRuntimeResponseTypeUserDefined.from_dict(runtime_response_generic_runtime_response_type_user_defined_model_json) + assert runtime_response_generic_runtime_response_type_user_defined_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_user_defined_model_dict = RuntimeResponseGenericRuntimeResponseTypeUserDefined.from_dict(runtime_response_generic_runtime_response_type_user_defined_model_json).__dict__ + runtime_response_generic_runtime_response_type_user_defined_model2 = RuntimeResponseGenericRuntimeResponseTypeUserDefined(**runtime_response_generic_runtime_response_type_user_defined_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_user_defined_model == runtime_response_generic_runtime_response_type_user_defined_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_user_defined_model_json2 = runtime_response_generic_runtime_response_type_user_defined_model.to_dict() + assert runtime_response_generic_runtime_response_type_user_defined_model_json2 == runtime_response_generic_runtime_response_type_user_defined_model_json + # endregion ############################################################################## From d33caba954e764e4b512e4fce62750c2fd9b8cf1 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 19 May 2021 14:10:39 -0400 Subject: [PATCH 315/455] feat(assistantv2): generation release changes --- ibm_watson/assistant_v2.py | 1268 +++++++++++++++++++++++++++++--- test/unit/test_assistant_v2.py | 543 ++++++++++++-- 2 files changed, 1666 insertions(+), 145 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 611202159..1f0a52c87 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2019, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201221-115123 +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -56,7 +56,7 @@ def __init__( Construct a new client for the Assistant service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2020-04-01`. + Specify dates in YYYY-MM-DD format. The current version is `2020-09-24`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md @@ -184,6 +184,7 @@ def message(self, *, input: 'MessageInput' = None, context: 'MessageContext' = None, + user_id: str = None, **kwargs) -> DetailedResponse: """ Send user input to assistant (stateful). @@ -207,6 +208,16 @@ def message(self, assistant on a per-session basis. **Note:** The total size of the context data stored for a stateful session cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `MessageResponse` object @@ -228,7 +239,7 @@ def message(self, params = {'version': self.version} - data = {'input': input, 'context': context} + data = {'input': input, 'context': context, 'user_id': user_id} data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -256,6 +267,7 @@ def message_stateless(self, *, input: 'MessageInputStateless' = None, context: 'MessageContextStateless' = None, + user_id: str = None, **kwargs) -> DetailedResponse: """ Send user input to assistant (stateless). @@ -278,6 +290,16 @@ def message_stateless(self, previous response. **Note:** The total size of the context data for a stateless session cannot exceed 250KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `MessageResponseStateless` object @@ -297,7 +319,7 @@ def message_stateless(self, params = {'version': self.version} - data = {'input': input, 'context': context} + data = {'input': input, 'context': context, 'user_id': user_id} data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -335,7 +357,7 @@ def bulk_classify(self, information about the intents and entities recognized in each input. This method is useful for testing and comparing the performance of different skills or skill versions. - This method is available only with Premium plans. + This method is available only with Enterprise with Data Isolation plans. :param str skill_id: Unique identifier of the skill. To find the skill ID in the Watson Assistant user interface, open the skill settings and click @@ -398,7 +420,7 @@ def list_logs(self, List log events for an assistant. List the events from the log of an assistant. - This method is available only with Premium plans. + This method requires Manager access, and is available only with Enterprise plans. :param str assistant_id: Unique identifier of the assistant. To find the assistant ID in the Watson Assistant user interface, open the assistant @@ -467,8 +489,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: with a request that passes data. For more information about personal data and customer IDs, see [Information 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**. + **Note:** This operation is intended only for deleting data associated with a + single specific customer, not for deleting data associated with multiple customers + or for any other purpose. For more information, see [Labeling and deleting data in + Watson + Assistant](https://cloud.ibm.com/docs/assistant?topic=assistant-information-security#information-security-gdpr-wa). :param str customer_id: The customer ID for which all data is to be deleted. @@ -824,23 +849,217 @@ def __ne__(self, other: 'CaptureGroup') -> bool: return not self == other +class ChannelTransferInfo(): + """ + Information used by an integration to transfer the conversation to a different + channel. + + :attr ChannelTransferTarget target: An object specifying target channels + available for the transfer. Each property of this object represents an available + transfer target. Currently, the only supported property is **chat**, + representing the web chat integration. + """ + + def __init__(self, target: 'ChannelTransferTarget') -> None: + """ + Initialize a ChannelTransferInfo object. + + :param ChannelTransferTarget target: An object specifying target channels + available for the transfer. Each property of this object represents an + available transfer target. Currently, the only supported property is + **chat**, representing the web chat integration. + """ + self.target = target + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': + """Initialize a ChannelTransferInfo object from a json dictionary.""" + args = {} + if 'target' in _dict: + args['target'] = ChannelTransferTarget.from_dict( + _dict.get('target')) + else: + raise ValueError( + 'Required property \'target\' not present in ChannelTransferInfo JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ChannelTransferInfo 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, 'target') and self.target is not None: + _dict['target'] = self.target.to_dict() + 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 ChannelTransferInfo object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ChannelTransferInfo') -> 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: 'ChannelTransferInfo') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ChannelTransferTarget(): + """ + An object specifying target channels available for the transfer. Each property of this + object represents an available transfer target. Currently, the only supported property + is **chat**, representing the web chat integration. + + :attr ChannelTransferTargetChat chat: (optional) Information for transferring to + the web chat integration. + """ + + def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: + """ + Initialize a ChannelTransferTarget object. + + :param ChannelTransferTargetChat chat: (optional) Information for + transferring to the web chat integration. + """ + self.chat = chat + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': + """Initialize a ChannelTransferTarget object from a json dictionary.""" + args = {} + if 'chat' in _dict: + args['chat'] = ChannelTransferTargetChat.from_dict( + _dict.get('chat')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ChannelTransferTarget 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, 'chat') and self.chat is not None: + _dict['chat'] = self.chat.to_dict() + 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 ChannelTransferTarget object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ChannelTransferTarget') -> 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: 'ChannelTransferTarget') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ChannelTransferTargetChat(): + """ + Information for transferring to the web chat integration. + + :attr str url: (optional) The URL of the target web chat. + """ + + def __init__(self, *, url: str = None) -> None: + """ + Initialize a ChannelTransferTargetChat object. + + :param str url: (optional) The URL of the target web chat. + """ + self.url = url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': + """Initialize a ChannelTransferTargetChat object from a json dictionary.""" + args = {} + if 'url' in _dict: + args['url'] = _dict.get('url') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ChannelTransferTargetChat 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, 'url') and self.url is not None: + _dict['url'] = self.url + 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 ChannelTransferTargetChat object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ChannelTransferTargetChat') -> 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: 'ChannelTransferTargetChat') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class DialogLogMessage(): """ Dialog log message details. :attr str level: The severity of the log message. :attr str message: The text of the log message. + :attr str code: A code that indicates the category to which the error message + belongs. + :attr LogMessageSource source: (optional) An object that identifies the dialog + element that generated the error message. """ - def __init__(self, level: str, message: str) -> None: + def __init__(self, + level: str, + message: str, + code: str, + *, + source: 'LogMessageSource' = None) -> None: """ Initialize a DialogLogMessage object. :param str level: The severity of the log message. :param str message: The text of the log message. + :param str code: A code that indicates the category to which the error + message belongs. + :param LogMessageSource source: (optional) An object that identifies the + dialog element that generated the error message. """ self.level = level self.message = message + self.code = code + self.source = source @classmethod def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': @@ -858,6 +1077,14 @@ def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': raise ValueError( 'Required property \'message\' not present in DialogLogMessage JSON' ) + if 'code' in _dict: + args['code'] = _dict.get('code') + else: + raise ValueError( + 'Required property \'code\' not present in DialogLogMessage JSON' + ) + if 'source' in _dict: + args['source'] = LogMessageSource.from_dict(_dict.get('source')) return cls(**args) @classmethod @@ -872,6 +1099,10 @@ def to_dict(self) -> Dict: _dict['level'] = self.level if hasattr(self, 'message') and self.message is not None: _dict['message'] = self.message + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source.to_dict() return _dict def _to_dict(self): @@ -1677,6 +1908,66 @@ def __ne__(self, other: 'LogCollection') -> bool: return not self == other +class LogMessageSource(): + """ + An object that identifies the dialog element that generated the error message. + + """ + + def __init__(self) -> None: + """ + Initialize a LogMessageSource object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSource': + """Initialize a LogMessageSource object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = ( + "Cannot convert dictionary into an instance of base class 'LogMessageSource'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a LogMessageSource object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['dialog_node'] = 'LogMessageSourceDialogNode' + mapping['action'] = 'LogMessageSourceAction' + mapping['step'] = 'LogMessageSourceStep' + mapping['handler'] = 'LogMessageSourceHandler' + disc_value = _dict.get('type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'type\' not found in LogMessageSource JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + class LogPagination(): """ The pagination data for the returned objects. @@ -1970,9 +2261,14 @@ class MessageContextGlobalSystem(): zone to correctly resolve relative time references. :attr str user_id: (optional) A string value that identifies the user who is interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For Plus and Premium - plans, this user ID is used to identify unique users for billing purposes. This - string cannot contain carriage return, newline, or tab characters. + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root of + the message body. If **user_id** is specified in both locations in a message + request, the value specified at the root is used. :attr int turn_count: (optional) A counter that is automatically incremented 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 @@ -2010,9 +2306,13 @@ def __init__(self, :param str user_id: (optional) A string value that identifies the user who is interacting with the assistant. The client must provide a unique identifier for each individual end user who accesses the application. For - Plus and Premium plans, this user ID is used to identify unique users for - billing purposes. This string cannot contain carriage return, newline, or - tab characters. + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root + of the message body. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. :param int turn_count: (optional) A counter that is automatically incremented 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 @@ -3236,12 +3536,23 @@ class MessageRequest(): per-session basis. **Note:** The total size of the context data stored for a stateful session cannot exceed 100KB. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. If **user_id** is specified in both locations, the value + specified at the root is used. """ def __init__(self, *, input: 'MessageInput' = None, - context: 'MessageContext' = None) -> None: + context: 'MessageContext' = None, + user_id: str = None) -> None: """ Initialize a MessageRequest object. @@ -3253,9 +3564,20 @@ def __init__(self, assistant on a per-session basis. **Note:** The total size of the context data stored for a stateful session cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. """ self.input = input self.context = context + self.user_id = user_id @classmethod def from_dict(cls, _dict: Dict) -> 'MessageRequest': @@ -3265,6 +3587,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageRequest': args['input'] = MessageInput.from_dict(_dict.get('input')) if 'context' in _dict: args['context'] = MessageContext.from_dict(_dict.get('context')) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') return cls(**args) @classmethod @@ -3279,6 +3603,8 @@ def to_dict(self) -> Dict: _dict['input'] = self.input.to_dict() if hasattr(self, 'context') and self.context is not None: _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -3312,10 +3638,20 @@ class MessageResponse(): **Note:** The context is included in message responses only if **return_context**=`true` in the message request. Full context is always included in logs. + :attr str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ def __init__(self, output: 'MessageOutput', + user_id: str, *, context: 'MessageContext' = None) -> None: """ @@ -3323,6 +3659,15 @@ def __init__(self, :param MessageOutput output: Assistant output to be rendered or processed by the client. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. :param MessageContext context: (optional) Context data for the conversation. You can use this property to access context variables. The context is stored by the assistant on a per-session basis. @@ -3332,6 +3677,7 @@ def __init__(self, """ self.output = output self.context = context + self.user_id = user_id @classmethod def from_dict(cls, _dict: Dict) -> 'MessageResponse': @@ -3345,6 +3691,12 @@ def from_dict(cls, _dict: Dict) -> 'MessageResponse': ) if 'context' in _dict: args['context'] = MessageContext.from_dict(_dict.get('context')) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') + else: + raise ValueError( + 'Required property \'user_id\' not present in MessageResponse JSON' + ) return cls(**args) @classmethod @@ -3359,6 +3711,8 @@ def to_dict(self) -> Dict: _dict['output'] = self.output.to_dict() if hasattr(self, 'context') and self.context is not None: _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -3390,10 +3744,22 @@ class MessageResponseStateless(): can use this property to access context variables. The context is not stored by the assistant; to maintain session state, include the context from the response in the next message. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ - def __init__(self, output: 'MessageOutput', - context: 'MessageContextStateless') -> None: + def __init__(self, + output: 'MessageOutput', + context: 'MessageContextStateless', + *, + user_id: str = None) -> None: """ Initialize a MessageResponseStateless object. @@ -3403,9 +3769,19 @@ def __init__(self, output: 'MessageOutput', You can use this property to access context variables. The context is not stored by the assistant; to maintain session state, include the context from the response in the next message. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. """ self.output = output self.context = context + self.user_id = user_id @classmethod def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': @@ -3424,6 +3800,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': raise ValueError( 'Required property \'context\' not present in MessageResponseStateless JSON' ) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') return cls(**args) @classmethod @@ -3438,6 +3816,8 @@ def to_dict(self) -> Dict: _dict['output'] = self.output.to_dict() if hasattr(self, 'context') and self.context is not None: _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -3459,6 +3839,61 @@ def __ne__(self, other: 'MessageResponseStateless') -> bool: return not self == other +class ResponseGenericChannel(): + """ + ResponseGenericChannel. + + :attr str channel: (optional) A channel for which the response is intended. + """ + + def __init__(self, *, channel: str = None) -> None: + """ + Initialize a ResponseGenericChannel object. + + :param str channel: (optional) A channel for which the response is + intended. + """ + self.channel = channel + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': + """Initialize a ResponseGenericChannel object from a json dictionary.""" + args = {} + if 'channel' in _dict: + args['channel'] = _dict.get('channel') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericChannel 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, 'channel') and self.channel is not None: + _dict['channel'] = self.channel + 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 ResponseGenericChannel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericChannel') -> 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: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuntimeEntity(): """ The entity value that was recognized in the user input. @@ -4223,7 +4658,9 @@ def __init__(self) -> None: 'RuntimeResponseGenericRuntimeResponseTypeOption', 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeSearch' + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' ])) raise Exception(msg) @@ -4243,7 +4680,9 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': 'RuntimeResponseGenericRuntimeResponseTypeOption', 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeSearch' + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' ])) raise Exception(msg) @@ -4255,6 +4694,8 @@ def _from_dict(cls, _dict: Dict): @classmethod def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping = {} + mapping[ + 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' mapping[ 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' @@ -4264,6 +4705,8 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + mapping[ + 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' disc_value = _dict.get('response_type') if disc_value is None: raise ValueError( @@ -4286,7 +4729,7 @@ class SearchResult(): :attr str id: The unique identifier of the document in the Discovery service collection. This property is included in responses from search skills, which are available - only to Plus or Premium plan users. + only to Plus or Enterprise plan users. :attr SearchResultMetadata result_metadata: An object containing search result metadata from the Discovery service. :attr str body: (optional) A description of the search result. This is taken @@ -4316,7 +4759,7 @@ def __init__(self, :param str id: The unique identifier of the document in the Discovery service collection. This property is included in responses from search skills, which are - available only to Plus or Premium plan users. + available only to Plus or Enterprise plan users. :param SearchResultMetadata result_metadata: An object containing search result metadata from the Discovery service. :param str body: (optional) A description of the search result. This is @@ -4510,9 +4953,8 @@ class SearchResultMetadata(): """ An object containing search result metadata from the Discovery service. - :attr float confidence: (optional) The confidence score for the given result. - For more information about how the confidence is calculated, see the Discovery - service [documentation](../discovery#query-your-collection). + :attr float confidence: (optional) The confidence score for the given result, as + returned by the Discovery service. :attr float score: (optional) An unbounded measure of the relevance of a particular result, dependent on the query and matching document. A higher score indicates a greater match to the query parameters. @@ -4526,8 +4968,7 @@ def __init__(self, Initialize a SearchResultMetadata object. :param float confidence: (optional) The confidence score for the given - result. For more information about how the confidence is calculated, see - the Discovery service [documentation](../discovery#query-your-collection). + result, as returned by the Discovery service. :param float score: (optional) An unbounded measure of the relevance of a particular result, dependent on the query and matching document. A higher score indicates a greater match to the query parameters. @@ -4636,15 +5077,469 @@ def __ne__(self, other: 'SessionResponse') -> bool: return not self == other -class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( - RuntimeResponseGeneric): +class LogMessageSourceAction(LogMessageSource): """ - An object that describes a response with response type `connect_to_agent`. + An object that identifies the dialog element that generated the error message. - :attr str response_type: The type of response returned by the dialog node. The - specified response type must be supported by the client application or channel. - :attr str message_to_human_agent: (optional) A message to be sent to the human - agent who will be taking over the conversation. + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str action: The unique identifier of the action that generated the error + message. + """ + + def __init__(self, type: str, action: str) -> None: + """ + Initialize a LogMessageSourceAction object. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + """ + # pylint: disable=super-init-not-called + self.type = type + self.action = action + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': + """Initialize a LogMessageSourceAction object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceAction JSON' + ) + if 'action' in _dict: + args['action'] = _dict.get('action') + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceAction JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogMessageSourceAction 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 + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + 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 LogMessageSourceAction object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogMessageSourceAction') -> 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: 'LogMessageSourceAction') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogMessageSourceDialogNode(LogMessageSource): + """ + An object that identifies the dialog element that generated the error message. + + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str dialog_node: The unique identifier of the dialog node that generated + the error message. + """ + + def __init__(self, type: str, dialog_node: str) -> None: + """ + Initialize a LogMessageSourceDialogNode object. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str dialog_node: The unique identifier of the dialog node that + generated the error message. + """ + # pylint: disable=super-init-not-called + self.type = type + self.dialog_node = dialog_node + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': + """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' + ) + if 'dialog_node' in _dict: + args['dialog_node'] = _dict.get('dialog_node') + else: + raise ValueError( + 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogMessageSourceDialogNode 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 + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node + 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 LogMessageSourceDialogNode object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogMessageSourceDialogNode') -> 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: 'LogMessageSourceDialogNode') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogMessageSourceHandler(LogMessageSource): + """ + An object that identifies the dialog element that generated the error message. + + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str action: The unique identifier of the action that generated the error + message. + :attr str step: (optional) The unique identifier of the step that generated the + error message. + :attr str handler: The unique identifier of the handler that generated the error + message. + """ + + def __init__(self, + type: str, + action: str, + handler: str, + *, + step: str = None) -> None: + """ + Initialize a LogMessageSourceHandler object. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str handler: The unique identifier of the handler that generated the + error message. + :param str step: (optional) The unique identifier of the step that + generated the error message. + """ + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step + self.handler = handler + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': + """Initialize a LogMessageSourceHandler object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceHandler JSON' + ) + if 'action' in _dict: + args['action'] = _dict.get('action') + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceHandler JSON' + ) + if 'step' in _dict: + args['step'] = _dict.get('step') + if 'handler' in _dict: + args['handler'] = _dict.get('handler') + else: + raise ValueError( + 'Required property \'handler\' not present in LogMessageSourceHandler JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogMessageSourceHandler 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 + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'handler') and self.handler is not None: + _dict['handler'] = self.handler + 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 LogMessageSourceHandler object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogMessageSourceHandler') -> 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: 'LogMessageSourceHandler') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogMessageSourceStep(LogMessageSource): + """ + An object that identifies the dialog element that generated the error message. + + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str action: The unique identifier of the action that generated the error + message. + :attr str step: The unique identifier of the step that generated the error + message. + """ + + def __init__(self, type: str, action: str, step: str) -> None: + """ + Initialize a LogMessageSourceStep object. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str step: The unique identifier of the step that generated the error + message. + """ + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': + """Initialize a LogMessageSourceStep object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceStep JSON' + ) + if 'action' in _dict: + args['action'] = _dict.get('action') + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceStep JSON' + ) + if 'step' in _dict: + args['step'] = _dict.get('step') + else: + raise ValueError( + 'Required property \'step\' not present in LogMessageSourceStep JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogMessageSourceStep 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 + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + 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 LogMessageSourceStep object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogMessageSourceStep') -> 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: 'LogMessageSourceStep') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( + RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeChannelTransfer. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str message_to_user: The message to display to the user when initiating a + channel transfer. + :attr ChannelTransferInfo transfer_info: Information used by an integration to + transfer the conversation to a different channel. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + """ + + def __init__(self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: List['ResponseGenericChannel'] = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str message_to_user: The message to display to the user when + initiating a channel transfer. + :param ChannelTransferInfo transfer_info: Information used by an + integration to transfer the conversation to a different channel. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.message_to_user = message_to_user + self.transfer_info = transfer_info + self.channels = channels + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' + ) + if 'message_to_user' in _dict: + args['message_to_user'] = _dict.get('message_to_user') + else: + raise ValueError( + 'Required property \'message_to_user\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' + ) + if 'transfer_info' in _dict: + args['transfer_info'] = ChannelTransferInfo.from_dict( + _dict.get('transfer_info')) + else: + raise ValueError( + 'Required property \'transfer_info\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' + ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, + 'message_to_user') and self.message_to_user is not None: + _dict['message_to_user'] = self.message_to_user + if hasattr(self, 'transfer_info') and self.transfer_info is not None: + _dict['transfer_info'] = self.transfer_info.to_dict() + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + 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 RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + ) -> 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: 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( + RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeConnectToAgent. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str message_to_human_agent: (optional) A message to be sent to the human + agent who will be taking over the conversation. :attr AgentAvailabilityMessage agent_available: (optional) An optional message to be displayed to the user to indicate that the conversation will be transferred to the next available agent. @@ -4657,6 +5552,10 @@ class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( :attr str topic: (optional) A label identifying the topic of the conversation, derived from the **title** property of the relevant node or the **topic** property of the dialog node response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ def __init__( @@ -4667,7 +5566,8 @@ def __init__( agent_available: 'AgentAvailabilityMessage' = None, agent_unavailable: 'AgentAvailabilityMessage' = None, transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, - topic: str = None) -> None: + topic: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object. @@ -4688,6 +5588,10 @@ def __init__( :param str topic: (optional) A label identifying the topic of the conversation, derived from the **title** property of the relevant node or the **topic** property of the dialog node response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type @@ -4696,6 +5600,7 @@ def __init__( self.agent_unavailable = agent_unavailable self.transfer_info = transfer_info self.topic = topic + self.channels = channels @classmethod def from_dict( @@ -4723,6 +5628,11 @@ def from_dict( _dict.get('transfer_info')) if 'topic' in _dict: args['topic'] = _dict.get('topic') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -4748,6 +5658,8 @@ def to_dict(self) -> Dict: _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'topic') and self.topic is not None: _dict['topic'] = self.topic + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -4772,23 +5684,20 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - CONNECT_TO_AGENT = 'connect_to_agent' - class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): """ - An object that describes a response with response type `image`. + RuntimeResponseGenericRuntimeResponseTypeImage. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. :attr str source: The URL of the image. :attr str title: (optional) The title to show before the response. :attr str description: (optional) The description to show with the the response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ def __init__(self, @@ -4796,7 +5705,8 @@ def __init__(self, source: str, *, title: str = None, - description: str = None) -> None: + description: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. @@ -4807,12 +5717,17 @@ def __init__(self, :param str title: (optional) The title to show before the response. :param str description: (optional) The description to show with the the response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type self.source = source self.title = title self.description = description + self.channels = channels @classmethod def from_dict( @@ -4836,6 +5751,11 @@ def from_dict( args['title'] = _dict.get('title') if 'description' in _dict: args['description'] = _dict.get('description') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -4854,6 +5774,8 @@ def to_dict(self) -> Dict: _dict['title'] = self.title if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -4876,17 +5798,10 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - IMAGE = 'image' - class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): """ - An object that describes a response with response type `option`. + RuntimeResponseGenericRuntimeResponseTypeOption. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. @@ -4895,6 +5810,10 @@ class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): :attr str preference: (optional) The preferred type of control to display. :attr List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ def __init__(self, @@ -4903,7 +5822,8 @@ def __init__(self, options: List['DialogNodeOutputOptionsElement'], *, description: str = None, - preference: str = None) -> None: + preference: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object. @@ -4917,6 +5837,10 @@ def __init__(self, :param str description: (optional) The description to show with the the response. :param str preference: (optional) The preferred type of control to display. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type @@ -4924,6 +5848,7 @@ def __init__(self, self.description = description self.preference = preference self.options = options + self.channels = channels @classmethod def from_dict( @@ -4956,6 +5881,11 @@ def from_dict( raise ValueError( 'Required property \'options\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -4976,6 +5906,8 @@ def to_dict(self) -> Dict: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: _dict['options'] = [x.to_dict() for x in self.options] + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -5000,13 +5932,6 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - OPTION = 'option' - class PreferenceEnum(str, Enum): """ The preferred type of control to display. @@ -5017,20 +5942,25 @@ class PreferenceEnum(str, Enum): class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): """ - An object that describes a response with response type `pause`. + RuntimeResponseGenericRuntimeResponseTypePause. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. :attr int time: How long to pause, in milliseconds. :attr bool typing: (optional) Whether to send a "user is typing" event during the pause. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ def __init__(self, response_type: str, time: int, *, - typing: bool = None) -> None: + typing: bool = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypePause object. @@ -5040,11 +5970,16 @@ def __init__(self, :param int time: How long to pause, in milliseconds. :param bool typing: (optional) Whether to send a "user is typing" event during the pause. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type self.time = time self.typing = typing + self.channels = channels @classmethod def from_dict( @@ -5066,6 +6001,11 @@ def from_dict( ) if 'typing' in _dict: args['typing'] = _dict.get('typing') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -5082,6 +6022,8 @@ def to_dict(self) -> Dict: _dict['time'] = self.time if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -5104,17 +6046,10 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - PAUSE = 'pause' - class RuntimeResponseGenericRuntimeResponseTypeSearch(RuntimeResponseGeneric): """ - An object that describes a response with response type `search`. + RuntimeResponseGenericRuntimeResponseTypeSearch. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. @@ -5124,11 +6059,19 @@ class RuntimeResponseGenericRuntimeResponseTypeSearch(RuntimeResponseGeneric): search results to be displayed in the initial response to the user. :attr List[SearchResult] additional_results: An array of objects that contains additional search results that can be displayed to the user upon request. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ - def __init__(self, response_type: str, header: str, + def __init__(self, + response_type: str, + header: str, primary_results: List['SearchResult'], - additional_results: List['SearchResult']) -> None: + additional_results: List['SearchResult'], + *, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSearch object. @@ -5143,12 +6086,17 @@ def __init__(self, response_type: str, header: str, :param List[SearchResult] additional_results: An array of objects that contains additional search results that can be displayed to the user upon request. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type self.header = header self.primary_results = primary_results self.additional_results = additional_results + self.channels = channels @classmethod def from_dict( @@ -5185,6 +6133,11 @@ def from_dict( raise ValueError( 'Required property \'additional_results\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -5210,6 +6163,8 @@ def to_dict(self) -> Dict: _dict['additional_results'] = [ x.to_dict() for x in self.additional_results ] + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -5234,28 +6189,29 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - SEARCH = 'search' - class RuntimeResponseGenericRuntimeResponseTypeSuggestion( RuntimeResponseGeneric): """ - An object that describes a response with response type `suggestion`. + RuntimeResponseGenericRuntimeResponseTypeSuggestion. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. :attr str title: The title or introductory text to show before the response. :attr List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ - def __init__(self, response_type: str, title: str, - suggestions: List['DialogSuggestion']) -> None: + def __init__(self, + response_type: str, + title: str, + suggestions: List['DialogSuggestion'], + *, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object. @@ -5266,11 +6222,16 @@ def __init__(self, response_type: str, title: str, response. :param List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type self.title = title self.suggestions = suggestions + self.channels = channels @classmethod def from_dict( @@ -5298,6 +6259,11 @@ def from_dict( raise ValueError( 'Required property \'suggestions\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -5314,6 +6280,8 @@ def to_dict(self) -> Dict: _dict['title'] = self.title if hasattr(self, 'suggestions') and self.suggestions is not None: _dict['suggestions'] = [x.to_dict() for x in self.suggestions] + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -5338,24 +6306,25 @@ def __ne__( """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): - """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. - """ - SUGGESTION = 'suggestion' - class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): """ - An object that describes a response with response type `text`. + RuntimeResponseGenericRuntimeResponseTypeText. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. :attr str text: The text of the response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ - def __init__(self, response_type: str, text: str) -> None: + def __init__(self, + response_type: str, + text: str, + *, + channels: List['ResponseGenericChannel'] = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeText object. @@ -5363,10 +6332,15 @@ def __init__(self, response_type: str, text: str) -> None: The specified response type must be supported by the client application or channel. :param str text: The text of the response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type self.text = text + self.channels = channels @classmethod def from_dict( @@ -5386,6 +6360,11 @@ def from_dict( raise ValueError( 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] return cls(**args) @classmethod @@ -5400,6 +6379,8 @@ def to_dict(self) -> Dict: _dict['response_type'] = self.response_type if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] return _dict def _to_dict(self): @@ -5422,9 +6403,104 @@ def __ne__(self, """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ResponseTypeEnum(str, Enum): + +class RuntimeResponseGenericRuntimeResponseTypeUserDefined( + RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeUserDefined. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr dict user_defined: An object containing any properties for the + user-defined response type. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + """ + + def __init__(self, + response_type: str, + user_defined: dict, + *, + channels: List['ResponseGenericChannel'] = None) -> None: """ - The type of response returned by the dialog node. The specified response type must - be supported by the client application or channel. + Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param dict user_defined: An object containing any properties for the + user-defined response type. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ - TEXT = 'text' + # pylint: disable=super-init-not-called + self.response_type = response_type + self.user_defined = user_defined + self.channels = channels + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeUserDefined': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' + ) + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + else: + raise ValueError( + 'Required property \'user_defined\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' + ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + 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 RuntimeResponseGenericRuntimeResponseTypeUserDefined object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + ) -> 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: 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index a2ab09b5e..2f5958c65 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2018, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -29,13 +29,13 @@ version = 'testString' -service = AssistantV2( +_service = AssistantV2( authenticator=NoAuthAuthenticator(), version=version ) -base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: Sessions @@ -62,7 +62,7 @@ def test_create_session_all_params(self): create_session() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions') + url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions') mock_response = '{"session_id": "session_id"}' responses.add(responses.POST, url, @@ -74,7 +74,7 @@ def test_create_session_all_params(self): assistant_id = 'testString' # Invoke method - response = service.create_session( + response = _service.create_session( assistant_id, headers={} ) @@ -90,7 +90,7 @@ def test_create_session_value_error(self): test_create_session_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions') + url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions') mock_response = '{"session_id": "session_id"}' responses.add(responses.POST, url, @@ -108,7 +108,7 @@ def test_create_session_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_session(**req_copy) + _service.create_session(**req_copy) @@ -132,7 +132,7 @@ def test_delete_session_all_params(self): delete_session() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions/testString') + url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString') responses.add(responses.DELETE, url, status=200) @@ -142,7 +142,7 @@ def test_delete_session_all_params(self): session_id = 'testString' # Invoke method - response = service.delete_session( + response = _service.delete_session( assistant_id, session_id, headers={} @@ -159,7 +159,7 @@ def test_delete_session_value_error(self): test_delete_session_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions/testString') + url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString') responses.add(responses.DELETE, url, status=200) @@ -176,7 +176,7 @@ def test_delete_session_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_session(**req_copy) + _service.delete_session(**req_copy) @@ -210,8 +210,8 @@ def test_message_all_params(self): message() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' + url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -333,13 +333,15 @@ def test_message_all_params(self): session_id = 'testString' input = message_input_model context = message_context_model + user_id = 'testString' # Invoke method - response = service.message( + response = _service.message( assistant_id, session_id, input=input, context=context, + user_id=user_id, headers={} ) @@ -350,6 +352,7 @@ def test_message_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['input'] == message_input_model assert req_body['context'] == message_context_model + assert req_body['user_id'] == 'testString' @responses.activate @@ -358,8 +361,8 @@ def test_message_required_params(self): test_message_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' + url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -371,7 +374,7 @@ def test_message_required_params(self): session_id = 'testString' # Invoke method - response = service.message( + response = _service.message( assistant_id, session_id, headers={} @@ -388,8 +391,8 @@ def test_message_value_error(self): test_message_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' + url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -408,7 +411,7 @@ def test_message_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.message(**req_copy) + _service.message(**req_copy) @@ -432,8 +435,8 @@ def test_message_stateless_all_params(self): message_stateless() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' + url = self.preprocess_url(_base_url + '/v2/assistants/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -553,12 +556,14 @@ def test_message_stateless_all_params(self): assistant_id = 'testString' input = message_input_stateless_model context = message_context_stateless_model + user_id = 'testString' # Invoke method - response = service.message_stateless( + response = _service.message_stateless( assistant_id, input=input, context=context, + user_id=user_id, headers={} ) @@ -569,6 +574,7 @@ def test_message_stateless_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['input'] == message_input_stateless_model assert req_body['context'] == message_context_stateless_model + assert req_body['user_id'] == 'testString' @responses.activate @@ -577,8 +583,8 @@ def test_message_stateless_required_params(self): test_message_stateless_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' + url = self.preprocess_url(_base_url + '/v2/assistants/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -589,7 +595,7 @@ def test_message_stateless_required_params(self): assistant_id = 'testString' # Invoke method - response = service.message_stateless( + response = _service.message_stateless( assistant_id, headers={} ) @@ -605,8 +611,8 @@ def test_message_stateless_value_error(self): test_message_stateless_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}' + url = self.preprocess_url(_base_url + '/v2/assistants/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -623,7 +629,7 @@ def test_message_stateless_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.message_stateless(**req_copy) + _service.message_stateless(**req_copy) @@ -657,7 +663,7 @@ def test_bulk_classify_all_params(self): bulk_classify() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') + url = self.preprocess_url(_base_url + '/v2/skills/testString/workspace/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, @@ -674,7 +680,7 @@ def test_bulk_classify_all_params(self): input = [bulk_classify_utterance_model] # Invoke method - response = service.bulk_classify( + response = _service.bulk_classify( skill_id, input=input, headers={} @@ -694,7 +700,7 @@ def test_bulk_classify_required_params(self): test_bulk_classify_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') + url = self.preprocess_url(_base_url + '/v2/skills/testString/workspace/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, @@ -706,7 +712,7 @@ def test_bulk_classify_required_params(self): skill_id = 'testString' # Invoke method - response = service.bulk_classify( + response = _service.bulk_classify( skill_id, headers={} ) @@ -722,7 +728,7 @@ def test_bulk_classify_value_error(self): test_bulk_classify_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/skills/testString/workspace/bulk_classify') + url = self.preprocess_url(_base_url + '/v2/skills/testString/workspace/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, @@ -740,7 +746,7 @@ def test_bulk_classify_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.bulk_classify(**req_copy) + _service.bulk_classify(**req_copy) @@ -774,8 +780,8 @@ def test_list_logs_all_params(self): list_logs() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -790,7 +796,7 @@ def test_list_logs_all_params(self): cursor = 'testString' # Invoke method - response = service.list_logs( + response = _service.list_logs( assistant_id, sort=sort, filter=filter, @@ -817,8 +823,8 @@ def test_list_logs_required_params(self): test_list_logs_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -829,7 +835,7 @@ def test_list_logs_required_params(self): assistant_id = 'testString' # Invoke method - response = service.list_logs( + response = _service.list_logs( assistant_id, headers={} ) @@ -845,8 +851,8 @@ def test_list_logs_value_error(self): test_list_logs_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message"}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = self.preprocess_url(_base_url + '/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -863,7 +869,7 @@ def test_list_logs_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_logs(**req_copy) + _service.list_logs(**req_copy) @@ -897,7 +903,7 @@ def test_delete_user_data_all_params(self): delete_user_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/user_data') + url = self.preprocess_url(_base_url + '/v2/user_data') responses.add(responses.DELETE, url, status=202) @@ -906,7 +912,7 @@ def test_delete_user_data_all_params(self): customer_id = 'testString' # Invoke method - response = service.delete_user_data( + response = _service.delete_user_data( customer_id, headers={} ) @@ -926,7 +932,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/user_data') + url = self.preprocess_url(_base_url + '/v2/user_data') responses.add(responses.DELETE, url, status=202) @@ -941,7 +947,7 @@ def test_delete_user_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_user_data(**req_copy) + _service.delete_user_data(**req_copy) @@ -1226,6 +1232,106 @@ def test_capture_group_serialization(self): capture_group_model_json2 = capture_group_model.to_dict() assert capture_group_model_json2 == capture_group_model_json +class TestChannelTransferInfo(): + """ + Test Class for ChannelTransferInfo + """ + + def test_channel_transfer_info_serialization(self): + """ + Test serialization/deserialization for ChannelTransferInfo + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a json representation of a ChannelTransferInfo model + channel_transfer_info_model_json = {} + channel_transfer_info_model_json['target'] = channel_transfer_target_model + + # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation + channel_transfer_info_model = ChannelTransferInfo.from_dict(channel_transfer_info_model_json) + assert channel_transfer_info_model != False + + # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation + channel_transfer_info_model_dict = ChannelTransferInfo.from_dict(channel_transfer_info_model_json).__dict__ + channel_transfer_info_model2 = ChannelTransferInfo(**channel_transfer_info_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_info_model == channel_transfer_info_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() + assert channel_transfer_info_model_json2 == channel_transfer_info_model_json + +class TestChannelTransferTarget(): + """ + Test Class for ChannelTransferTarget + """ + + def test_channel_transfer_target_serialization(self): + """ + Test serialization/deserialization for ChannelTransferTarget + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a json representation of a ChannelTransferTarget model + channel_transfer_target_model_json = {} + channel_transfer_target_model_json['chat'] = channel_transfer_target_chat_model + + # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation + channel_transfer_target_model = ChannelTransferTarget.from_dict(channel_transfer_target_model_json) + assert channel_transfer_target_model != False + + # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation + channel_transfer_target_model_dict = ChannelTransferTarget.from_dict(channel_transfer_target_model_json).__dict__ + channel_transfer_target_model2 = ChannelTransferTarget(**channel_transfer_target_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_target_model == channel_transfer_target_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() + assert channel_transfer_target_model_json2 == channel_transfer_target_model_json + +class TestChannelTransferTargetChat(): + """ + Test Class for ChannelTransferTargetChat + """ + + def test_channel_transfer_target_chat_serialization(self): + """ + Test serialization/deserialization for ChannelTransferTargetChat + """ + + # Construct a json representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model_json = {} + channel_transfer_target_chat_model_json['url'] = 'testString' + + # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation + channel_transfer_target_chat_model = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json) + assert channel_transfer_target_chat_model != False + + # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation + channel_transfer_target_chat_model_dict = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json).__dict__ + channel_transfer_target_chat_model2 = ChannelTransferTargetChat(**channel_transfer_target_chat_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_target_chat_model == channel_transfer_target_chat_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() + assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json + class TestDialogLogMessage(): """ Test Class for DialogLogMessage @@ -1236,10 +1342,18 @@ def test_dialog_log_message_serialization(self): Test serialization/deserialization for DialogLogMessage """ + # Construct dict forms of any model objects needed in order to build this model. + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + # Construct a json representation of a DialogLogMessage model dialog_log_message_model_json = {} dialog_log_message_model_json['level'] = 'info' dialog_log_message_model_json['message'] = 'testString' + dialog_log_message_model_json['code'] = 'testString' + dialog_log_message_model_json['source'] = log_message_source_model # Construct a model instance of DialogLogMessage by calling from_dict on the json representation dialog_log_message_model = DialogLogMessage.from_dict(dialog_log_message_model_json) @@ -1890,6 +2004,7 @@ def test_log_serialization(self): message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['context'] = message_context_model + message_request_model['user_id'] = 'testString' dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model @@ -1898,12 +2013,16 @@ def test_log_serialization(self): dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption runtime_response_generic_model['response_type'] = 'option' runtime_response_generic_model['title'] = 'testString' runtime_response_generic_model['description'] = 'testString' runtime_response_generic_model['preference'] = 'dropdown' runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['channels'] = [response_generic_channel_model] dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -1917,9 +2036,15 @@ def test_log_serialization(self): dialog_nodes_visited_model['title'] = 'testString' dialog_nodes_visited_model['conditions'] = 'testString' + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] @@ -1944,6 +2069,7 @@ def test_log_serialization(self): message_response_model = {} # MessageResponse message_response_model['output'] = message_output_model message_response_model['context'] = message_context_model + message_response_model['user_id'] = 'testString' # Construct a json representation of a Log model log_model_json = {} @@ -2086,6 +2212,7 @@ def test_log_collection_serialization(self): message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['context'] = message_context_model + message_request_model['user_id'] = 'testString' dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model @@ -2094,12 +2221,16 @@ def test_log_collection_serialization(self): dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption runtime_response_generic_model['response_type'] = 'option' runtime_response_generic_model['title'] = 'testString' runtime_response_generic_model['description'] = 'testString' runtime_response_generic_model['preference'] = 'dropdown' runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['channels'] = [response_generic_channel_model] dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -2113,9 +2244,15 @@ def test_log_collection_serialization(self): dialog_nodes_visited_model['title'] = 'testString' dialog_nodes_visited_model['conditions'] = 'testString' + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] @@ -2140,6 +2277,7 @@ def test_log_collection_serialization(self): message_response_model = {} # MessageResponse message_response_model['output'] = message_output_model message_response_model['context'] = message_context_model + message_response_model['user_id'] = 'testString' log_model = {} # Log log_model['log_id'] = 'testString' @@ -2892,12 +3030,16 @@ def test_message_output_serialization(self): dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption runtime_response_generic_model['response_type'] = 'option' runtime_response_generic_model['title'] = 'testString' runtime_response_generic_model['description'] = 'testString' runtime_response_generic_model['preference'] = 'dropdown' runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['channels'] = [response_generic_channel_model] dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -2911,9 +3053,15 @@ def test_message_output_serialization(self): dialog_nodes_visited_model['title'] = 'testString' dialog_nodes_visited_model['conditions'] = 'testString' + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] @@ -2968,9 +3116,15 @@ def test_message_output_debug_serialization(self): dialog_nodes_visited_model['title'] = 'testString' dialog_nodes_visited_model['conditions'] = 'testString' + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model # Construct a json representation of a MessageOutputDebug model message_output_debug_model_json = {} @@ -3138,6 +3292,7 @@ def test_message_request_serialization(self): message_request_model_json = {} message_request_model_json['input'] = message_input_model message_request_model_json['context'] = message_context_model + message_request_model_json['user_id'] = 'testString' # Construct a model instance of MessageRequest by calling from_dict on the json representation message_request_model = MessageRequest.from_dict(message_request_model_json) @@ -3247,12 +3402,16 @@ def test_message_response_serialization(self): dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption runtime_response_generic_model['response_type'] = 'option' runtime_response_generic_model['title'] = 'testString' runtime_response_generic_model['description'] = 'testString' runtime_response_generic_model['preference'] = 'dropdown' runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['channels'] = [response_generic_channel_model] dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -3266,9 +3425,15 @@ def test_message_response_serialization(self): dialog_nodes_visited_model['title'] = 'testString' dialog_nodes_visited_model['conditions'] = 'testString' + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] @@ -3317,6 +3482,7 @@ def test_message_response_serialization(self): message_response_model_json = {} message_response_model_json['output'] = message_output_model message_response_model_json['context'] = message_context_model + message_response_model_json['user_id'] = 'testString' # Construct a model instance of MessageResponse by calling from_dict on the json representation message_response_model = MessageResponse.from_dict(message_response_model_json) @@ -3426,12 +3592,16 @@ def test_message_response_stateless_serialization(self): dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption runtime_response_generic_model['response_type'] = 'option' runtime_response_generic_model['title'] = 'testString' runtime_response_generic_model['description'] = 'testString' runtime_response_generic_model['preference'] = 'dropdown' runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['channels'] = [response_generic_channel_model] dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -3445,9 +3615,15 @@ def test_message_response_stateless_serialization(self): dialog_nodes_visited_model['title'] = 'testString' dialog_nodes_visited_model['conditions'] = 'testString' + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] @@ -3496,6 +3672,7 @@ def test_message_response_stateless_serialization(self): message_response_stateless_model_json = {} message_response_stateless_model_json['output'] = message_output_model message_response_stateless_model_json['context'] = message_context_stateless_model + message_response_stateless_model_json['user_id'] = 'testString' # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation message_response_stateless_model = MessageResponseStateless.from_dict(message_response_stateless_model_json) @@ -3512,6 +3689,35 @@ def test_message_response_stateless_serialization(self): message_response_stateless_model_json2 = message_response_stateless_model.to_dict() assert message_response_stateless_model_json2 == message_response_stateless_model_json +class TestResponseGenericChannel(): + """ + Test Class for ResponseGenericChannel + """ + + def test_response_generic_channel_serialization(self): + """ + Test serialization/deserialization for ResponseGenericChannel + """ + + # Construct a json representation of a ResponseGenericChannel model + response_generic_channel_model_json = {} + response_generic_channel_model_json['channel'] = 'testString' + + # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation + response_generic_channel_model = ResponseGenericChannel.from_dict(response_generic_channel_model_json) + assert response_generic_channel_model != False + + # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation + response_generic_channel_model_dict = ResponseGenericChannel.from_dict(response_generic_channel_model_json).__dict__ + response_generic_channel_model2 = ResponseGenericChannel(**response_generic_channel_model_dict) + + # Verify the model instances are equivalent + assert response_generic_channel_model == response_generic_channel_model2 + + # Convert model instance back to dict and verify no loss of data + response_generic_channel_model_json2 = response_generic_channel_model.to_dict() + assert response_generic_channel_model_json2 == response_generic_channel_model_json + class TestRuntimeEntity(): """ Test Class for RuntimeEntity @@ -3870,6 +4076,175 @@ def test_session_response_serialization(self): session_response_model_json2 = session_response_model.to_dict() assert session_response_model_json2 == session_response_model_json +class TestLogMessageSourceAction(): + """ + Test Class for LogMessageSourceAction + """ + + def test_log_message_source_action_serialization(self): + """ + Test serialization/deserialization for LogMessageSourceAction + """ + + # Construct a json representation of a LogMessageSourceAction model + log_message_source_action_model_json = {} + log_message_source_action_model_json['type'] = 'action' + log_message_source_action_model_json['action'] = 'testString' + + # Construct a model instance of LogMessageSourceAction by calling from_dict on the json representation + log_message_source_action_model = LogMessageSourceAction.from_dict(log_message_source_action_model_json) + assert log_message_source_action_model != False + + # Construct a model instance of LogMessageSourceAction by calling from_dict on the json representation + log_message_source_action_model_dict = LogMessageSourceAction.from_dict(log_message_source_action_model_json).__dict__ + log_message_source_action_model2 = LogMessageSourceAction(**log_message_source_action_model_dict) + + # Verify the model instances are equivalent + assert log_message_source_action_model == log_message_source_action_model2 + + # Convert model instance back to dict and verify no loss of data + log_message_source_action_model_json2 = log_message_source_action_model.to_dict() + assert log_message_source_action_model_json2 == log_message_source_action_model_json + +class TestLogMessageSourceDialogNode(): + """ + Test Class for LogMessageSourceDialogNode + """ + + def test_log_message_source_dialog_node_serialization(self): + """ + Test serialization/deserialization for LogMessageSourceDialogNode + """ + + # Construct a json representation of a LogMessageSourceDialogNode model + log_message_source_dialog_node_model_json = {} + log_message_source_dialog_node_model_json['type'] = 'dialog_node' + log_message_source_dialog_node_model_json['dialog_node'] = 'testString' + + # Construct a model instance of LogMessageSourceDialogNode by calling from_dict on the json representation + log_message_source_dialog_node_model = LogMessageSourceDialogNode.from_dict(log_message_source_dialog_node_model_json) + assert log_message_source_dialog_node_model != False + + # Construct a model instance of LogMessageSourceDialogNode by calling from_dict on the json representation + log_message_source_dialog_node_model_dict = LogMessageSourceDialogNode.from_dict(log_message_source_dialog_node_model_json).__dict__ + log_message_source_dialog_node_model2 = LogMessageSourceDialogNode(**log_message_source_dialog_node_model_dict) + + # Verify the model instances are equivalent + assert log_message_source_dialog_node_model == log_message_source_dialog_node_model2 + + # Convert model instance back to dict and verify no loss of data + log_message_source_dialog_node_model_json2 = log_message_source_dialog_node_model.to_dict() + assert log_message_source_dialog_node_model_json2 == log_message_source_dialog_node_model_json + +class TestLogMessageSourceHandler(): + """ + Test Class for LogMessageSourceHandler + """ + + def test_log_message_source_handler_serialization(self): + """ + Test serialization/deserialization for LogMessageSourceHandler + """ + + # Construct a json representation of a LogMessageSourceHandler model + log_message_source_handler_model_json = {} + log_message_source_handler_model_json['type'] = 'handler' + log_message_source_handler_model_json['action'] = 'testString' + log_message_source_handler_model_json['step'] = 'testString' + log_message_source_handler_model_json['handler'] = 'testString' + + # Construct a model instance of LogMessageSourceHandler by calling from_dict on the json representation + log_message_source_handler_model = LogMessageSourceHandler.from_dict(log_message_source_handler_model_json) + assert log_message_source_handler_model != False + + # Construct a model instance of LogMessageSourceHandler by calling from_dict on the json representation + log_message_source_handler_model_dict = LogMessageSourceHandler.from_dict(log_message_source_handler_model_json).__dict__ + log_message_source_handler_model2 = LogMessageSourceHandler(**log_message_source_handler_model_dict) + + # Verify the model instances are equivalent + assert log_message_source_handler_model == log_message_source_handler_model2 + + # Convert model instance back to dict and verify no loss of data + log_message_source_handler_model_json2 = log_message_source_handler_model.to_dict() + assert log_message_source_handler_model_json2 == log_message_source_handler_model_json + +class TestLogMessageSourceStep(): + """ + Test Class for LogMessageSourceStep + """ + + def test_log_message_source_step_serialization(self): + """ + Test serialization/deserialization for LogMessageSourceStep + """ + + # Construct a json representation of a LogMessageSourceStep model + log_message_source_step_model_json = {} + log_message_source_step_model_json['type'] = 'step' + log_message_source_step_model_json['action'] = 'testString' + log_message_source_step_model_json['step'] = 'testString' + + # Construct a model instance of LogMessageSourceStep by calling from_dict on the json representation + log_message_source_step_model = LogMessageSourceStep.from_dict(log_message_source_step_model_json) + assert log_message_source_step_model != False + + # Construct a model instance of LogMessageSourceStep by calling from_dict on the json representation + log_message_source_step_model_dict = LogMessageSourceStep.from_dict(log_message_source_step_model_json).__dict__ + log_message_source_step_model2 = LogMessageSourceStep(**log_message_source_step_model_dict) + + # Verify the model instances are equivalent + assert log_message_source_step_model == log_message_source_step_model2 + + # Convert model instance back to dict and verify no loss of data + log_message_source_step_model_json2 = log_message_source_step_model.to_dict() + assert log_message_source_step_model_json2 == log_message_source_step_model_json + +class TestRuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer + """ + + def test_runtime_response_generic_runtime_response_type_channel_transfer_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model['target'] = channel_transfer_target_model + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer model + runtime_response_generic_runtime_response_type_channel_transfer_model_json = {} + runtime_response_generic_runtime_response_type_channel_transfer_model_json['response_type'] = 'channel_transfer' + runtime_response_generic_runtime_response_type_channel_transfer_model_json['message_to_user'] = 'testString' + runtime_response_generic_runtime_response_type_channel_transfer_model_json['transfer_info'] = channel_transfer_info_model + runtime_response_generic_runtime_response_type_channel_transfer_model_json['channels'] = [response_generic_channel_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeChannelTransfer by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_channel_transfer_model = RuntimeResponseGenericRuntimeResponseTypeChannelTransfer.from_dict(runtime_response_generic_runtime_response_type_channel_transfer_model_json) + assert runtime_response_generic_runtime_response_type_channel_transfer_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeChannelTransfer by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_channel_transfer_model_dict = RuntimeResponseGenericRuntimeResponseTypeChannelTransfer.from_dict(runtime_response_generic_runtime_response_type_channel_transfer_model_json).__dict__ + runtime_response_generic_runtime_response_type_channel_transfer_model2 = RuntimeResponseGenericRuntimeResponseTypeChannelTransfer(**runtime_response_generic_runtime_response_type_channel_transfer_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_channel_transfer_model == runtime_response_generic_runtime_response_type_channel_transfer_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_channel_transfer_model_json2 = runtime_response_generic_runtime_response_type_channel_transfer_model.to_dict() + assert runtime_response_generic_runtime_response_type_channel_transfer_model_json2 == runtime_response_generic_runtime_response_type_channel_transfer_model_json + class TestRuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent @@ -3888,6 +4263,9 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent model runtime_response_generic_runtime_response_type_connect_to_agent_model_json = {} runtime_response_generic_runtime_response_type_connect_to_agent_model_json['response_type'] = 'connect_to_agent' @@ -3896,6 +4274,7 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json['agent_unavailable'] = agent_availability_message_model runtime_response_generic_runtime_response_type_connect_to_agent_model_json['transfer_info'] = dialog_node_output_connect_to_agent_transfer_info_model runtime_response_generic_runtime_response_type_connect_to_agent_model_json['topic'] = 'testString' + runtime_response_generic_runtime_response_type_connect_to_agent_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeConnectToAgent by calling from_dict on the json representation runtime_response_generic_runtime_response_type_connect_to_agent_model = RuntimeResponseGenericRuntimeResponseTypeConnectToAgent.from_dict(runtime_response_generic_runtime_response_type_connect_to_agent_model_json) @@ -3922,12 +4301,18 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeImage """ + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeImage model runtime_response_generic_runtime_response_type_image_model_json = {} runtime_response_generic_runtime_response_type_image_model_json['response_type'] = 'image' runtime_response_generic_runtime_response_type_image_model_json['source'] = 'testString' runtime_response_generic_runtime_response_type_image_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_image_model_json['description'] = 'testString' + runtime_response_generic_runtime_response_type_image_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeImage by calling from_dict on the json representation runtime_response_generic_runtime_response_type_image_model = RuntimeResponseGenericRuntimeResponseTypeImage.from_dict(runtime_response_generic_runtime_response_type_image_model_json) @@ -4037,6 +4422,9 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeOption model runtime_response_generic_runtime_response_type_option_model_json = {} runtime_response_generic_runtime_response_type_option_model_json['response_type'] = 'option' @@ -4044,6 +4432,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_response_generic_runtime_response_type_option_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_option_model_json['preference'] = 'dropdown' runtime_response_generic_runtime_response_type_option_model_json['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_runtime_response_type_option_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeOption by calling from_dict on the json representation runtime_response_generic_runtime_response_type_option_model = RuntimeResponseGenericRuntimeResponseTypeOption.from_dict(runtime_response_generic_runtime_response_type_option_model_json) @@ -4070,11 +4459,17 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypePause """ + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypePause model runtime_response_generic_runtime_response_type_pause_model_json = {} runtime_response_generic_runtime_response_type_pause_model_json['response_type'] = 'pause' runtime_response_generic_runtime_response_type_pause_model_json['time'] = 38 runtime_response_generic_runtime_response_type_pause_model_json['typing'] = True + runtime_response_generic_runtime_response_type_pause_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypePause by calling from_dict on the json representation runtime_response_generic_runtime_response_type_pause_model = RuntimeResponseGenericRuntimeResponseTypePause.from_dict(runtime_response_generic_runtime_response_type_pause_model_json) @@ -4121,12 +4516,16 @@ def test_runtime_response_generic_runtime_response_type_search_serialization(sel search_result_model['url'] = 'testString' search_result_model['highlight'] = search_result_highlight_model + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSearch model runtime_response_generic_runtime_response_type_search_model_json = {} runtime_response_generic_runtime_response_type_search_model_json['response_type'] = 'search' runtime_response_generic_runtime_response_type_search_model_json['header'] = 'testString' runtime_response_generic_runtime_response_type_search_model_json['primary_results'] = [search_result_model] runtime_response_generic_runtime_response_type_search_model_json['additional_results'] = [search_result_model] + runtime_response_generic_runtime_response_type_search_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeSearch by calling from_dict on the json representation runtime_response_generic_runtime_response_type_search_model = RuntimeResponseGenericRuntimeResponseTypeSearch.from_dict(runtime_response_generic_runtime_response_type_search_model_json) @@ -4237,11 +4636,15 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization dialog_suggestion_model['value'] = dialog_suggestion_value_model dialog_suggestion_model['output'] = {} + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSuggestion model runtime_response_generic_runtime_response_type_suggestion_model_json = {} runtime_response_generic_runtime_response_type_suggestion_model_json['response_type'] = 'suggestion' runtime_response_generic_runtime_response_type_suggestion_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_suggestion_model_json['suggestions'] = [dialog_suggestion_model] + runtime_response_generic_runtime_response_type_suggestion_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeSuggestion by calling from_dict on the json representation runtime_response_generic_runtime_response_type_suggestion_model = RuntimeResponseGenericRuntimeResponseTypeSuggestion.from_dict(runtime_response_generic_runtime_response_type_suggestion_model_json) @@ -4268,10 +4671,16 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeText """ + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeText model runtime_response_generic_runtime_response_type_text_model_json = {} runtime_response_generic_runtime_response_type_text_model_json['response_type'] = 'text' runtime_response_generic_runtime_response_type_text_model_json['text'] = 'testString' + runtime_response_generic_runtime_response_type_text_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeText by calling from_dict on the json representation runtime_response_generic_runtime_response_type_text_model = RuntimeResponseGenericRuntimeResponseTypeText.from_dict(runtime_response_generic_runtime_response_type_text_model_json) @@ -4288,6 +4697,42 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) runtime_response_generic_runtime_response_type_text_model_json2 = runtime_response_generic_runtime_response_type_text_model.to_dict() assert runtime_response_generic_runtime_response_type_text_model_json2 == runtime_response_generic_runtime_response_type_text_model_json +class TestRuntimeResponseGenericRuntimeResponseTypeUserDefined(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeUserDefined + """ + + def test_runtime_response_generic_runtime_response_type_user_defined_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeUserDefined + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model + runtime_response_generic_runtime_response_type_user_defined_model_json = {} + runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {} + runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_user_defined_model = RuntimeResponseGenericRuntimeResponseTypeUserDefined.from_dict(runtime_response_generic_runtime_response_type_user_defined_model_json) + assert runtime_response_generic_runtime_response_type_user_defined_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_user_defined_model_dict = RuntimeResponseGenericRuntimeResponseTypeUserDefined.from_dict(runtime_response_generic_runtime_response_type_user_defined_model_json).__dict__ + runtime_response_generic_runtime_response_type_user_defined_model2 = RuntimeResponseGenericRuntimeResponseTypeUserDefined(**runtime_response_generic_runtime_response_type_user_defined_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_user_defined_model == runtime_response_generic_runtime_response_type_user_defined_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_user_defined_model_json2 = runtime_response_generic_runtime_response_type_user_defined_model.to_dict() + assert runtime_response_generic_runtime_response_type_user_defined_model_json2 == runtime_response_generic_runtime_response_type_user_defined_model_json + # endregion ############################################################################## From 132066afabf4a671cf8409f5f82d8d0f576feae6 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 19 May 2021 14:29:37 -0400 Subject: [PATCH 316/455] refactor(cc,pi,tests): no significant changes --- ibm_watson/compare_comply_v1.py | 15 +- ibm_watson/personality_insights_v3.py | 24 +- test/unit/test_assistant_v1.py | 2 +- test/unit/test_compare_comply_v1.py | 227 ++--- test/unit/test_discovery_v1.py | 810 +++++++++--------- test/unit/test_language_translator_v3.py | 151 ++-- .../test_natural_language_classifier_v1.py | 67 +- test/unit/test_personality_insights_v3.py | 20 +- test/unit/test_tone_analyzer_v3.py | 32 +- test/unit/test_visual_recognition_v3.py | 123 +-- test/unit/test_visual_recognition_v4.py | 267 +++--- 11 files changed, 877 insertions(+), 861 deletions(-) diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 5320f9de7..6ecc8d374 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2019, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,10 +14,17 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 """ -IBM Watson™ Compare and Comply analyzes governing documents to provide details about -critical aspects of the documents. +IBM Watson™ Compare and Comply is discontinued. Existing instances are supported +until 30 November 2021, but as of 1 December 2020, you can't create instances. Any +instance that exists on 30 November 2021 will be deleted. Consider migrating to Watson +Discovery Premium on IBM Cloud for your Compare and Comply use cases. To start the +migration process, visit +[https://ibm.biz/contact-wdc-premium](https://ibm.biz/contact-wdc-premium). +{: deprecated} +Compare and Comply analyzes governing documents to provide details about critical aspects +of the documents. """ from datetime import datetime diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index 39261113f..f049a5fcf 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2016, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,17 +14,19 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 """ -IBM® will begin sunsetting IBM Watson™ Personality Insights on 1 December 2020. -For a period of one year from this date, you will still be able to use Watson Personality -Insights. However, as of 1 December 2021, the offering will no longer be -available.

As an alternative, we encourage you to consider migrating to IBM -Watson™ Natural Language Understanding, a service on IBM Cloud® that uses deep -learning to extract data and insights from text such as keywords, categories, sentiment, -emotion, and syntax to provide insights for your business or industry. For more -information, see [About Natural Language -Understanding](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-about). +IBM Watson™ Personality Insights is discontinued. Existing instances are supported +until 1 December 2021, but as of 1 December 2020, you cannot create new instances. Any +instance that exists on 1 December 2021 will be deleted.

No direct replacement +exists for Personality Insights. However, you can consider using [IBM Watson™ +Natural Language +Understanding](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-about) +on IBM Cloud® as part of a replacement analytic workflow for your Personality Insights +use cases. You can use Natural Language Understanding to extract data and insights from +text, such as keywords, categories, sentiment, emotion, and syntax. For more information +about the personality models in Personality Insights, see [The science behind the +service](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-science). {: deprecated} The IBM Watson Personality Insights service enables applications to derive insights from social media, enterprise data, or other digital communications. The service uses diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index a95476083..37db94d36 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2021. +# (C) Copyright IBM Corp. 2018, 2021. # # 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/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index bfee84b7a..57a6378b3 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2018, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect import io import json @@ -32,13 +33,13 @@ version = 'testString' -service = CompareComplyV1( +_service = CompareComplyV1( authenticator=NoAuthAuthenticator(), version=version ) -base_url = 'https://api.us-south.compare-comply.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.compare-comply.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: HTMLConversion @@ -65,7 +66,7 @@ def test_convert_to_html_all_params(self): convert_to_html() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/html_conversion') + url = self.preprocess_url(_base_url + '/v1/html_conversion') mock_response = '{"num_pages": "num_pages", "author": "author", "publication_date": "publication_date", "title": "title", "html": "html"}' responses.add(responses.POST, url, @@ -79,7 +80,7 @@ def test_convert_to_html_all_params(self): model = 'contracts' # Invoke method - response = service.convert_to_html( + response = _service.convert_to_html( file, file_content_type=file_content_type, model=model, @@ -101,7 +102,7 @@ def test_convert_to_html_required_params(self): test_convert_to_html_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/html_conversion') + url = self.preprocess_url(_base_url + '/v1/html_conversion') mock_response = '{"num_pages": "num_pages", "author": "author", "publication_date": "publication_date", "title": "title", "html": "html"}' responses.add(responses.POST, url, @@ -113,7 +114,7 @@ def test_convert_to_html_required_params(self): file = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = service.convert_to_html( + response = _service.convert_to_html( file, headers={} ) @@ -129,7 +130,7 @@ def test_convert_to_html_value_error(self): test_convert_to_html_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/html_conversion') + url = self.preprocess_url(_base_url + '/v1/html_conversion') mock_response = '{"num_pages": "num_pages", "author": "author", "publication_date": "publication_date", "title": "title", "html": "html"}' responses.add(responses.POST, url, @@ -147,7 +148,7 @@ def test_convert_to_html_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.convert_to_html(**req_copy) + _service.convert_to_html(**req_copy) @@ -181,7 +182,7 @@ def test_classify_elements_all_params(self): classify_elements() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/element_classification') + url = self.preprocess_url(_base_url + '/v1/element_classification') mock_response = '{"document": {"title": "title", "html": "html", "hash": "hash", "label": "label"}, "model_id": "model_id", "model_version": "model_version", "elements": [{"location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "effective_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_amounts": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "termination_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_types": [{"confidence_level": "High", "text": "text", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "payment_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_currencies": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}], "document_structure": {"section_titles": [{"text": "text", "location": {"begin": 5, "end": 3}, "level": 5, "element_locations": [{"begin": 5, "end": 3}]}], "leading_sentences": [{"text": "text", "location": {"begin": 5, "end": 3}, "element_locations": [{"begin": 5, "end": 3}]}], "paragraphs": [{"location": {"begin": 5, "end": 3}}]}, "parties": [{"party": "party", "role": "role", "importance": "Primary", "addresses": [{"text": "text", "location": {"begin": 5, "end": 3}}], "contacts": [{"name": "name", "role": "role"}], "mentions": [{"text": "text", "location": {"begin": 5, "end": 3}}]}]}' responses.add(responses.POST, url, @@ -195,7 +196,7 @@ def test_classify_elements_all_params(self): model = 'contracts' # Invoke method - response = service.classify_elements( + response = _service.classify_elements( file, file_content_type=file_content_type, model=model, @@ -217,7 +218,7 @@ def test_classify_elements_required_params(self): test_classify_elements_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/element_classification') + url = self.preprocess_url(_base_url + '/v1/element_classification') mock_response = '{"document": {"title": "title", "html": "html", "hash": "hash", "label": "label"}, "model_id": "model_id", "model_version": "model_version", "elements": [{"location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "effective_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_amounts": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "termination_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_types": [{"confidence_level": "High", "text": "text", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "payment_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_currencies": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}], "document_structure": {"section_titles": [{"text": "text", "location": {"begin": 5, "end": 3}, "level": 5, "element_locations": [{"begin": 5, "end": 3}]}], "leading_sentences": [{"text": "text", "location": {"begin": 5, "end": 3}, "element_locations": [{"begin": 5, "end": 3}]}], "paragraphs": [{"location": {"begin": 5, "end": 3}}]}, "parties": [{"party": "party", "role": "role", "importance": "Primary", "addresses": [{"text": "text", "location": {"begin": 5, "end": 3}}], "contacts": [{"name": "name", "role": "role"}], "mentions": [{"text": "text", "location": {"begin": 5, "end": 3}}]}]}' responses.add(responses.POST, url, @@ -229,7 +230,7 @@ def test_classify_elements_required_params(self): file = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = service.classify_elements( + response = _service.classify_elements( file, headers={} ) @@ -245,7 +246,7 @@ def test_classify_elements_value_error(self): test_classify_elements_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/element_classification') + url = self.preprocess_url(_base_url + '/v1/element_classification') mock_response = '{"document": {"title": "title", "html": "html", "hash": "hash", "label": "label"}, "model_id": "model_id", "model_version": "model_version", "elements": [{"location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "effective_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_amounts": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "termination_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_types": [{"confidence_level": "High", "text": "text", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "payment_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_currencies": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}], "document_structure": {"section_titles": [{"text": "text", "location": {"begin": 5, "end": 3}, "level": 5, "element_locations": [{"begin": 5, "end": 3}]}], "leading_sentences": [{"text": "text", "location": {"begin": 5, "end": 3}, "element_locations": [{"begin": 5, "end": 3}]}], "paragraphs": [{"location": {"begin": 5, "end": 3}}]}, "parties": [{"party": "party", "role": "role", "importance": "Primary", "addresses": [{"text": "text", "location": {"begin": 5, "end": 3}}], "contacts": [{"name": "name", "role": "role"}], "mentions": [{"text": "text", "location": {"begin": 5, "end": 3}}]}]}' responses.add(responses.POST, url, @@ -263,7 +264,7 @@ def test_classify_elements_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.classify_elements(**req_copy) + _service.classify_elements(**req_copy) @@ -297,7 +298,7 @@ def test_extract_tables_all_params(self): extract_tables() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/tables') + url = self.preprocess_url(_base_url + '/v1/tables') mock_response = '{"document": {"html": "html", "title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}]}' responses.add(responses.POST, url, @@ -311,7 +312,7 @@ def test_extract_tables_all_params(self): model = 'contracts' # Invoke method - response = service.extract_tables( + response = _service.extract_tables( file, file_content_type=file_content_type, model=model, @@ -333,7 +334,7 @@ def test_extract_tables_required_params(self): test_extract_tables_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/tables') + url = self.preprocess_url(_base_url + '/v1/tables') mock_response = '{"document": {"html": "html", "title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}]}' responses.add(responses.POST, url, @@ -345,7 +346,7 @@ def test_extract_tables_required_params(self): file = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = service.extract_tables( + response = _service.extract_tables( file, headers={} ) @@ -361,7 +362,7 @@ def test_extract_tables_value_error(self): test_extract_tables_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/tables') + url = self.preprocess_url(_base_url + '/v1/tables') mock_response = '{"document": {"html": "html", "title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}]}' responses.add(responses.POST, url, @@ -379,7 +380,7 @@ def test_extract_tables_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.extract_tables(**req_copy) + _service.extract_tables(**req_copy) @@ -413,7 +414,7 @@ def test_compare_documents_all_params(self): compare_documents() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/comparison') + url = self.preprocess_url(_base_url + '/v1/comparison') mock_response = '{"model_id": "model_id", "model_version": "model_version", "documents": [{"title": "title", "html": "html", "hash": "hash", "label": "label"}], "aligned_elements": [{"element_pair": [{"document_label": "document_label", "text": "text", "location": {"begin": 5, "end": 3}, "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "identical_text": true, "provenance_ids": ["provenance_ids"], "significant_elements": true}], "unaligned_elements": [{"document_label": "document_label", "location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}]}' responses.add(responses.POST, url, @@ -431,7 +432,7 @@ def test_compare_documents_all_params(self): model = 'contracts' # Invoke method - response = service.compare_documents( + response = _service.compare_documents( file_1, file_2, file_1_content_type=file_1_content_type, @@ -459,7 +460,7 @@ def test_compare_documents_required_params(self): test_compare_documents_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/comparison') + url = self.preprocess_url(_base_url + '/v1/comparison') mock_response = '{"model_id": "model_id", "model_version": "model_version", "documents": [{"title": "title", "html": "html", "hash": "hash", "label": "label"}], "aligned_elements": [{"element_pair": [{"document_label": "document_label", "text": "text", "location": {"begin": 5, "end": 3}, "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "identical_text": true, "provenance_ids": ["provenance_ids"], "significant_elements": true}], "unaligned_elements": [{"document_label": "document_label", "location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}]}' responses.add(responses.POST, url, @@ -472,7 +473,7 @@ def test_compare_documents_required_params(self): file_2 = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = service.compare_documents( + response = _service.compare_documents( file_1, file_2, headers={} @@ -489,7 +490,7 @@ def test_compare_documents_value_error(self): test_compare_documents_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/comparison') + url = self.preprocess_url(_base_url + '/v1/comparison') mock_response = '{"model_id": "model_id", "model_version": "model_version", "documents": [{"title": "title", "html": "html", "hash": "hash", "label": "label"}], "aligned_elements": [{"element_pair": [{"document_label": "document_label", "text": "text", "location": {"begin": 5, "end": 3}, "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "identical_text": true, "provenance_ids": ["provenance_ids"], "significant_elements": true}], "unaligned_elements": [{"document_label": "document_label", "location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}]}' responses.add(responses.POST, url, @@ -509,7 +510,7 @@ def test_compare_documents_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.compare_documents(**req_copy) + _service.compare_documents(**req_copy) @@ -543,8 +544,8 @@ def test_add_feedback_all_params(self): add_feedback() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/feedback') - mock_response = '{"feedback_id": "feedback_id", "user_id": "user_id", "comment": "comment", "created": "2019-01-01T12:00:00", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' + url = self.preprocess_url(_base_url + '/v1/feedback') + mock_response = '{"feedback_id": "feedback_id", "user_id": "user_id", "comment": "comment", "created": "2019-01-01T12:00:00.000Z", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' responses.add(responses.POST, url, body=mock_response, @@ -605,7 +606,7 @@ def test_add_feedback_all_params(self): comment = 'testString' # Invoke method - response = service.add_feedback( + response = _service.add_feedback( feedback_data, user_id=user_id, comment=comment, @@ -628,8 +629,8 @@ def test_add_feedback_value_error(self): test_add_feedback_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/feedback') - mock_response = '{"feedback_id": "feedback_id", "user_id": "user_id", "comment": "comment", "created": "2019-01-01T12:00:00", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' + url = self.preprocess_url(_base_url + '/v1/feedback') + mock_response = '{"feedback_id": "feedback_id", "user_id": "user_id", "comment": "comment", "created": "2019-01-01T12:00:00.000Z", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' responses.add(responses.POST, url, body=mock_response, @@ -696,7 +697,7 @@ def test_add_feedback_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_feedback(**req_copy) + _service.add_feedback(**req_copy) @@ -720,8 +721,8 @@ def test_list_feedback_all_params(self): list_feedback() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/feedback') - mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' + url = self.preprocess_url(_base_url + '/v1/feedback') + mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -745,7 +746,7 @@ def test_list_feedback_all_params(self): include_total = True # Invoke method - response = service.list_feedback( + response = _service.list_feedback( feedback_type=feedback_type, document_title=document_title, model_id=model_id, @@ -791,8 +792,8 @@ def test_list_feedback_required_params(self): test_list_feedback_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/feedback') - mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' + url = self.preprocess_url(_base_url + '/v1/feedback') + mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -800,7 +801,7 @@ def test_list_feedback_required_params(self): status=200) # Invoke method - response = service.list_feedback() + response = _service.list_feedback() # Check for correct operation @@ -814,8 +815,8 @@ def test_list_feedback_value_error(self): test_list_feedback_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/feedback') - mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' + url = self.preprocess_url(_base_url + '/v1/feedback') + mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -828,7 +829,7 @@ def test_list_feedback_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_feedback(**req_copy) + _service.list_feedback(**req_copy) @@ -852,8 +853,8 @@ def test_get_feedback_all_params(self): get_feedback() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/feedback/testString') - mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' + url = self.preprocess_url(_base_url + '/v1/feedback/testString') + mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' responses.add(responses.GET, url, body=mock_response, @@ -865,7 +866,7 @@ def test_get_feedback_all_params(self): model = 'contracts' # Invoke method - response = service.get_feedback( + response = _service.get_feedback( feedback_id, model=model, headers={} @@ -886,8 +887,8 @@ def test_get_feedback_required_params(self): test_get_feedback_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/feedback/testString') - mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' + url = self.preprocess_url(_base_url + '/v1/feedback/testString') + mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' responses.add(responses.GET, url, body=mock_response, @@ -898,7 +899,7 @@ def test_get_feedback_required_params(self): feedback_id = 'testString' # Invoke method - response = service.get_feedback( + response = _service.get_feedback( feedback_id, headers={} ) @@ -914,8 +915,8 @@ def test_get_feedback_value_error(self): test_get_feedback_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/feedback/testString') - mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' + url = self.preprocess_url(_base_url + '/v1/feedback/testString') + mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' responses.add(responses.GET, url, body=mock_response, @@ -932,7 +933,7 @@ def test_get_feedback_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_feedback(**req_copy) + _service.get_feedback(**req_copy) @@ -956,7 +957,7 @@ def test_delete_feedback_all_params(self): delete_feedback() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/feedback/testString') + url = self.preprocess_url(_base_url + '/v1/feedback/testString') mock_response = '{"status": 6, "message": "message"}' responses.add(responses.DELETE, url, @@ -969,7 +970,7 @@ def test_delete_feedback_all_params(self): model = 'contracts' # Invoke method - response = service.delete_feedback( + response = _service.delete_feedback( feedback_id, model=model, headers={} @@ -990,7 +991,7 @@ def test_delete_feedback_required_params(self): test_delete_feedback_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/feedback/testString') + url = self.preprocess_url(_base_url + '/v1/feedback/testString') mock_response = '{"status": 6, "message": "message"}' responses.add(responses.DELETE, url, @@ -1002,7 +1003,7 @@ def test_delete_feedback_required_params(self): feedback_id = 'testString' # Invoke method - response = service.delete_feedback( + response = _service.delete_feedback( feedback_id, headers={} ) @@ -1018,7 +1019,7 @@ def test_delete_feedback_value_error(self): test_delete_feedback_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/feedback/testString') + url = self.preprocess_url(_base_url + '/v1/feedback/testString') mock_response = '{"status": 6, "message": "message"}' responses.add(responses.DELETE, url, @@ -1036,7 +1037,7 @@ def test_delete_feedback_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_feedback(**req_copy) + _service.delete_feedback(**req_copy) @@ -1070,8 +1071,8 @@ def test_create_batch_all_params(self): create_batch() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/batches') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/batches') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1089,7 +1090,7 @@ def test_create_batch_all_params(self): model = 'contracts' # Invoke method - response = service.create_batch( + response = _service.create_batch( function, input_credentials_file, input_bucket_location, @@ -1117,8 +1118,8 @@ def test_create_batch_required_params(self): test_create_batch_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/batches') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/batches') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1135,7 +1136,7 @@ def test_create_batch_required_params(self): output_bucket_name = 'testString' # Invoke method - response = service.create_batch( + response = _service.create_batch( function, input_credentials_file, input_bucket_location, @@ -1161,8 +1162,8 @@ def test_create_batch_value_error(self): test_create_batch_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/batches') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/batches') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1191,7 +1192,7 @@ def test_create_batch_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_batch(**req_copy) + _service.create_batch(**req_copy) @@ -1215,8 +1216,8 @@ def test_list_batches_all_params(self): list_batches() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/batches') - mock_response = '{"batches": [{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/batches') + mock_response = '{"batches": [{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1224,7 +1225,7 @@ def test_list_batches_all_params(self): status=200) # Invoke method - response = service.list_batches() + response = _service.list_batches() # Check for correct operation @@ -1238,8 +1239,8 @@ def test_list_batches_value_error(self): test_list_batches_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/batches') - mock_response = '{"batches": [{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v1/batches') + mock_response = '{"batches": [{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1252,7 +1253,7 @@ def test_list_batches_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_batches(**req_copy) + _service.list_batches(**req_copy) @@ -1276,8 +1277,8 @@ def test_get_batch_all_params(self): get_batch() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/batches/testString') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/batches/testString') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1288,7 +1289,7 @@ def test_get_batch_all_params(self): batch_id = 'testString' # Invoke method - response = service.get_batch( + response = _service.get_batch( batch_id, headers={} ) @@ -1304,8 +1305,8 @@ def test_get_batch_value_error(self): test_get_batch_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/batches/testString') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/batches/testString') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1322,7 +1323,7 @@ def test_get_batch_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_batch(**req_copy) + _service.get_batch(**req_copy) @@ -1346,8 +1347,8 @@ def test_update_batch_all_params(self): update_batch() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/batches/testString') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/batches/testString') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1360,7 +1361,7 @@ def test_update_batch_all_params(self): model = 'contracts' # Invoke method - response = service.update_batch( + response = _service.update_batch( batch_id, action, model=model, @@ -1383,8 +1384,8 @@ def test_update_batch_required_params(self): test_update_batch_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/batches/testString') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/batches/testString') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1396,7 +1397,7 @@ def test_update_batch_required_params(self): action = 'rescan' # Invoke method - response = service.update_batch( + response = _service.update_batch( batch_id, action, headers={} @@ -1417,8 +1418,8 @@ def test_update_batch_value_error(self): test_update_batch_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/batches/testString') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v1/batches/testString') + mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1437,7 +1438,7 @@ def test_update_batch_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_batch(**req_copy) + _service.update_batch(**req_copy) @@ -1613,8 +1614,8 @@ def test_batch_status_serialization(self): batch_status_model_json['batch_id'] = 'testString' batch_status_model_json['document_counts'] = doc_counts_model batch_status_model_json['status'] = 'testString' - batch_status_model_json['created'] = '2020-01-28T18:40:40.123456Z' - batch_status_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + batch_status_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + batch_status_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of BatchStatus by calling from_dict on the json representation batch_status_model = BatchStatus.from_dict(batch_status_model_json) @@ -1658,8 +1659,8 @@ def test_batches_serialization(self): batch_status_model['batch_id'] = 'testString' batch_status_model['document_counts'] = doc_counts_model batch_status_model['status'] = 'testString' - batch_status_model['created'] = '2020-01-28T18:40:40.123456Z' - batch_status_model['updated'] = '2020-01-28T18:40:40.123456Z' + batch_status_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + batch_status_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a json representation of a Batches model batches_model_json = {} @@ -1821,7 +1822,7 @@ def test_classify_return_serialization(self): type_label_model = {} # TypeLabel type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] + type_label_model['provenance_ids'] = ['Nlu0ogWAEGms4vjhhzpMv3iXhm8b8fBqMBNtT/bXH8JI=', 'Pqjd5I+s/Fdpx2NbIwCRMtyPLV8n1Hq+wINPGAr/PNtcRCSdxR9P7RLf1/eXPKQYI'] type_label_model['modification'] = 'added' category_model = {} # Category @@ -1942,12 +1943,12 @@ def test_classify_return_serialization(self): body_cells_model['row_index_end'] = 1 body_cells_model['column_index_begin'] = 0 body_cells_model['column_index_end'] = 0 - body_cells_model['row_header_ids'] = ['testString'] - body_cells_model['row_header_texts'] = ['testString'] - body_cells_model['row_header_texts_normalized'] = ['testString'] - body_cells_model['column_header_ids'] = ['testString'] - body_cells_model['column_header_texts'] = ['testString'] - body_cells_model['column_header_texts_normalized'] = ['testString'] + body_cells_model['row_header_ids'] = [] + body_cells_model['row_header_texts'] = [] + body_cells_model['row_header_texts_normalized'] = [] + body_cells_model['column_header_ids'] = ['colHeader-23489-23496'] + body_cells_model['column_header_texts'] = ['Res Ref'] + body_cells_model['column_header_texts_normalized'] = ['Res Ref'] body_cells_model['attributes'] = [attribute_model] contexts_model = {} # Contexts @@ -2139,7 +2140,7 @@ def test_compare_return_serialization(self): aligned_element_model = {} # AlignedElement aligned_element_model['element_pair'] = [element_pair_model] aligned_element_model['identical_text'] = True - aligned_element_model['provenance_ids'] = ['testString'] + aligned_element_model['provenance_ids'] = ['1mSG/96z1wY4De35LAExJzhCo2t0DfvbYnTl+vbavjY='] aligned_element_model['significant_elements'] = True unaligned_element_model = {} # UnalignedElement @@ -2938,12 +2939,12 @@ def test_feedback_list_serialization(self): type_label_model = {} # TypeLabel type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] + type_label_model['provenance_ids'] = ['85f5981a-ba91-44f5-9efa-0bd22e64b7bc', 'ce0480a1-5ef1-4c3e-9861-3743b5610795'] type_label_model['modification'] = 'unchanged' category_model = {} # Category category_model['label'] = 'Responsibilities' - category_model['provenance_ids'] = ['testString'] + category_model['provenance_ids'] = [] category_model['modification'] = 'unchanged' original_labels_out_model = {} # OriginalLabelsOut @@ -2974,7 +2975,7 @@ def test_feedback_list_serialization(self): get_feedback_model = {} # GetFeedback get_feedback_model['feedback_id'] = '9730b437-cb86-4d40-9a84-ff6948bb3dd1' - get_feedback_model['created'] = '2020-01-28T18:40:40.123456Z' + get_feedback_model['created'] = datetime_to_string(string_to_datetime("2018-07-03T10:16:05-0500")) get_feedback_model['comment'] = 'testString' get_feedback_model['feedback_data'] = feedback_data_output_model @@ -3062,7 +3063,7 @@ def test_feedback_return_serialization(self): feedback_return_model_json['feedback_id'] = 'testString' feedback_return_model_json['user_id'] = 'testString' feedback_return_model_json['comment'] = 'testString' - feedback_return_model_json['created'] = '2020-01-28T18:40:40.123456Z' + feedback_return_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) feedback_return_model_json['feedback_data'] = feedback_data_output_model # Construct a model instance of FeedbackReturn by calling from_dict on the json representation @@ -3106,12 +3107,12 @@ def test_get_feedback_serialization(self): type_label_model = {} # TypeLabel type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] + type_label_model['provenance_ids'] = ['85f5981a-ba91-44f5-9efa-0bd22e64b7bc', 'ce0480a1-5ef1-4c3e-9861-3743b5610795'] type_label_model['modification'] = 'unchanged' category_model = {} # Category category_model['label'] = 'obligation' - category_model['provenance_ids'] = ['testString'] + category_model['provenance_ids'] = ['85f5981a-ba91-44f5-9efa-0bd22e64b7bc', 'ce0480a1-5ef1-4c3e-9861-3743b5610795'] category_model['modification'] = 'removed' original_labels_out_model = {} # OriginalLabelsOut @@ -3143,7 +3144,7 @@ def test_get_feedback_serialization(self): # Construct a json representation of a GetFeedback model get_feedback_model_json = {} get_feedback_model_json['feedback_id'] = 'testString' - get_feedback_model_json['created'] = '2020-01-28T18:40:40.123456Z' + get_feedback_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) get_feedback_model_json['comment'] = 'testString' get_feedback_model_json['feedback_data'] = feedback_data_output_model @@ -3959,12 +3960,12 @@ def test_table_return_serialization(self): body_cells_model['row_index_end'] = 2 body_cells_model['column_index_begin'] = 1 body_cells_model['column_index_end'] = 1 - body_cells_model['row_header_ids'] = ['testString'] - body_cells_model['row_header_texts'] = ['testString'] - body_cells_model['row_header_texts_normalized'] = ['testString'] - body_cells_model['column_header_ids'] = ['testString'] - body_cells_model['column_header_texts'] = ['testString'] - body_cells_model['column_header_texts_normalized'] = ['testString'] + body_cells_model['row_header_ids'] = ['rowHeader-2244-2262'] + body_cells_model['row_header_texts'] = ['Statutory tax rate'] + body_cells_model['row_header_texts_normalized'] = ['Statutory tax rate'] + body_cells_model['column_header_ids'] = ['colHeader-1050-1082', 'colHeader-1544-1548'] + body_cells_model['column_header_texts'] = ['Three months ended September 30, ', '2005'] + body_cells_model['column_header_texts_normalized'] = ['Three months ended September 30, ', 'Year 1'] body_cells_model['attributes'] = [attribute_model] contexts_model = {} # Contexts diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 601726d0f..27d6361d2 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2016, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,6 +19,8 @@ from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import date_to_string, string_to_date +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect import io import json @@ -32,13 +34,13 @@ version = 'testString' -service = DiscoveryV1( +_service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version=version ) -base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: Environments @@ -65,8 +67,8 @@ def test_create_environment_all_params(self): create_environment() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' + url = self.preprocess_url(_base_url + '/v1/environments') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.POST, url, body=mock_response, @@ -79,7 +81,7 @@ def test_create_environment_all_params(self): size = 'LT' # Invoke method - response = service.create_environment( + response = _service.create_environment( name, description=description, size=size, @@ -102,8 +104,8 @@ def test_create_environment_value_error(self): test_create_environment_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' + url = self.preprocess_url(_base_url + '/v1/environments') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.POST, url, body=mock_response, @@ -122,7 +124,7 @@ def test_create_environment_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_environment(**req_copy) + _service.create_environment(**req_copy) @@ -146,8 +148,8 @@ def test_list_environments_all_params(self): list_environments() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments') - mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' + url = self.preprocess_url(_base_url + '/v1/environments') + mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' responses.add(responses.GET, url, body=mock_response, @@ -158,7 +160,7 @@ def test_list_environments_all_params(self): name = 'testString' # Invoke method - response = service.list_environments( + response = _service.list_environments( name=name, headers={} ) @@ -178,8 +180,8 @@ def test_list_environments_required_params(self): test_list_environments_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments') - mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' + url = self.preprocess_url(_base_url + '/v1/environments') + mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' responses.add(responses.GET, url, body=mock_response, @@ -187,7 +189,7 @@ def test_list_environments_required_params(self): status=200) # Invoke method - response = service.list_environments() + response = _service.list_environments() # Check for correct operation @@ -201,8 +203,8 @@ def test_list_environments_value_error(self): test_list_environments_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments') - mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' + url = self.preprocess_url(_base_url + '/v1/environments') + mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' responses.add(responses.GET, url, body=mock_response, @@ -215,7 +217,7 @@ def test_list_environments_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_environments(**req_copy) + _service.list_environments(**req_copy) @@ -239,8 +241,8 @@ def test_get_environment_all_params(self): get_environment() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.GET, url, body=mock_response, @@ -251,7 +253,7 @@ def test_get_environment_all_params(self): environment_id = 'testString' # Invoke method - response = service.get_environment( + response = _service.get_environment( environment_id, headers={} ) @@ -267,8 +269,8 @@ def test_get_environment_value_error(self): test_get_environment_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.GET, url, body=mock_response, @@ -285,7 +287,7 @@ def test_get_environment_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_environment(**req_copy) + _service.get_environment(**req_copy) @@ -309,8 +311,8 @@ def test_update_environment_all_params(self): update_environment() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.PUT, url, body=mock_response, @@ -324,7 +326,7 @@ def test_update_environment_all_params(self): size = 'S' # Invoke method - response = service.update_environment( + response = _service.update_environment( environment_id, name=name, description=description, @@ -348,8 +350,8 @@ def test_update_environment_value_error(self): test_update_environment_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString') + mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.PUT, url, body=mock_response, @@ -369,7 +371,7 @@ def test_update_environment_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_environment(**req_copy) + _service.update_environment(**req_copy) @@ -393,7 +395,7 @@ def test_delete_environment_all_params(self): delete_environment() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -405,7 +407,7 @@ def test_delete_environment_all_params(self): environment_id = 'testString' # Invoke method - response = service.delete_environment( + response = _service.delete_environment( environment_id, headers={} ) @@ -421,7 +423,7 @@ def test_delete_environment_value_error(self): test_delete_environment_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -439,7 +441,7 @@ def test_delete_environment_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_environment(**req_copy) + _service.delete_environment(**req_copy) @@ -463,7 +465,7 @@ def test_list_fields_all_params(self): list_fields() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/fields') + url = self.preprocess_url(_base_url + '/v1/environments/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' responses.add(responses.GET, url, @@ -476,7 +478,7 @@ def test_list_fields_all_params(self): collection_ids = ['testString'] # Invoke method - response = service.list_fields( + response = _service.list_fields( environment_id, collection_ids, headers={} @@ -497,7 +499,7 @@ def test_list_fields_value_error(self): test_list_fields_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/fields') + url = self.preprocess_url(_base_url + '/v1/environments/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' responses.add(responses.GET, url, @@ -517,7 +519,7 @@ def test_list_fields_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_fields(**req_copy) + _service.list_fields(**req_copy) @@ -551,8 +553,8 @@ def test_create_configuration_all_params(self): create_configuration() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.POST, url, body=mock_response, @@ -755,7 +757,7 @@ def test_create_configuration_all_params(self): source = source_model # Invoke method - response = service.create_configuration( + response = _service.create_configuration( environment_id, name, description=description, @@ -785,8 +787,8 @@ def test_create_configuration_value_error(self): test_create_configuration_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.POST, url, body=mock_response, @@ -996,7 +998,7 @@ def test_create_configuration_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_configuration(**req_copy) + _service.create_configuration(**req_copy) @@ -1020,8 +1022,8 @@ def test_list_configurations_all_params(self): list_configurations() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1033,7 +1035,7 @@ def test_list_configurations_all_params(self): name = 'testString' # Invoke method - response = service.list_configurations( + response = _service.list_configurations( environment_id, name=name, headers={} @@ -1054,8 +1056,8 @@ def test_list_configurations_required_params(self): test_list_configurations_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1066,7 +1068,7 @@ def test_list_configurations_required_params(self): environment_id = 'testString' # Invoke method - response = service.list_configurations( + response = _service.list_configurations( environment_id, headers={} ) @@ -1082,8 +1084,8 @@ def test_list_configurations_value_error(self): test_list_configurations_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1100,7 +1102,7 @@ def test_list_configurations_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_configurations(**req_copy) + _service.list_configurations(**req_copy) @@ -1124,8 +1126,8 @@ def test_get_configuration_all_params(self): get_configuration() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.GET, url, body=mock_response, @@ -1137,7 +1139,7 @@ def test_get_configuration_all_params(self): configuration_id = 'testString' # Invoke method - response = service.get_configuration( + response = _service.get_configuration( environment_id, configuration_id, headers={} @@ -1154,8 +1156,8 @@ def test_get_configuration_value_error(self): test_get_configuration_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.GET, url, body=mock_response, @@ -1174,7 +1176,7 @@ def test_get_configuration_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_configuration(**req_copy) + _service.get_configuration(**req_copy) @@ -1198,8 +1200,8 @@ def test_update_configuration_all_params(self): update_configuration() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.PUT, url, body=mock_response, @@ -1403,7 +1405,7 @@ def test_update_configuration_all_params(self): source = source_model # Invoke method - response = service.update_configuration( + response = _service.update_configuration( environment_id, configuration_id, name, @@ -1434,8 +1436,8 @@ def test_update_configuration_value_error(self): test_update_configuration_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.PUT, url, body=mock_response, @@ -1647,7 +1649,7 @@ def test_update_configuration_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_configuration(**req_copy) + _service.update_configuration(**req_copy) @@ -1671,8 +1673,8 @@ def test_delete_configuration_all_params(self): delete_configuration() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.DELETE, url, body=mock_response, @@ -1684,7 +1686,7 @@ def test_delete_configuration_all_params(self): configuration_id = 'testString' # Invoke method - response = service.delete_configuration( + response = _service.delete_configuration( environment_id, configuration_id, headers={} @@ -1701,8 +1703,8 @@ def test_delete_configuration_value_error(self): test_delete_configuration_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.DELETE, url, body=mock_response, @@ -1721,7 +1723,7 @@ def test_delete_configuration_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_configuration(**req_copy) + _service.delete_configuration(**req_copy) @@ -1755,8 +1757,8 @@ def test_create_collection_all_params(self): create_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.POST, url, body=mock_response, @@ -1771,7 +1773,7 @@ def test_create_collection_all_params(self): language = 'en' # Invoke method - response = service.create_collection( + response = _service.create_collection( environment_id, name, description=description, @@ -1797,8 +1799,8 @@ def test_create_collection_value_error(self): test_create_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.POST, url, body=mock_response, @@ -1820,7 +1822,7 @@ def test_create_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_collection(**req_copy) + _service.create_collection(**req_copy) @@ -1844,8 +1846,8 @@ def test_list_collections_all_params(self): list_collections() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1857,7 +1859,7 @@ def test_list_collections_all_params(self): name = 'testString' # Invoke method - response = service.list_collections( + response = _service.list_collections( environment_id, name=name, headers={} @@ -1878,8 +1880,8 @@ def test_list_collections_required_params(self): test_list_collections_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1890,7 +1892,7 @@ def test_list_collections_required_params(self): environment_id = 'testString' # Invoke method - response = service.list_collections( + response = _service.list_collections( environment_id, headers={} ) @@ -1906,8 +1908,8 @@ def test_list_collections_value_error(self): test_list_collections_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1924,7 +1926,7 @@ def test_list_collections_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_collections(**req_copy) + _service.list_collections(**req_copy) @@ -1948,8 +1950,8 @@ def test_get_collection_all_params(self): get_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.GET, url, body=mock_response, @@ -1961,7 +1963,7 @@ def test_get_collection_all_params(self): collection_id = 'testString' # Invoke method - response = service.get_collection( + response = _service.get_collection( environment_id, collection_id, headers={} @@ -1978,8 +1980,8 @@ def test_get_collection_value_error(self): test_get_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.GET, url, body=mock_response, @@ -1998,7 +2000,7 @@ def test_get_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_collection(**req_copy) + _service.get_collection(**req_copy) @@ -2022,8 +2024,8 @@ def test_update_collection_all_params(self): update_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.PUT, url, body=mock_response, @@ -2038,7 +2040,7 @@ def test_update_collection_all_params(self): configuration_id = 'testString' # Invoke method - response = service.update_collection( + response = _service.update_collection( environment_id, collection_id, name, @@ -2063,8 +2065,8 @@ def test_update_collection_value_error(self): test_update_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00", "data_updated": "2019-01-01T12:00:00"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.PUT, url, body=mock_response, @@ -2087,7 +2089,7 @@ def test_update_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_collection(**req_copy) + _service.update_collection(**req_copy) @@ -2111,7 +2113,7 @@ def test_delete_collection_all_params(self): delete_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -2124,7 +2126,7 @@ def test_delete_collection_all_params(self): collection_id = 'testString' # Invoke method - response = service.delete_collection( + response = _service.delete_collection( environment_id, collection_id, headers={} @@ -2141,7 +2143,7 @@ def test_delete_collection_value_error(self): test_delete_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -2161,7 +2163,7 @@ def test_delete_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_collection(**req_copy) + _service.delete_collection(**req_copy) @@ -2185,7 +2187,7 @@ def test_list_collection_fields_all_params(self): list_collection_fields() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/fields') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' responses.add(responses.GET, url, @@ -2198,7 +2200,7 @@ def test_list_collection_fields_all_params(self): collection_id = 'testString' # Invoke method - response = service.list_collection_fields( + response = _service.list_collection_fields( environment_id, collection_id, headers={} @@ -2215,7 +2217,7 @@ def test_list_collection_fields_value_error(self): test_list_collection_fields_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/fields') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' responses.add(responses.GET, url, @@ -2235,7 +2237,7 @@ def test_list_collection_fields_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_collection_fields(**req_copy) + _service.list_collection_fields(**req_copy) @@ -2269,7 +2271,7 @@ def test_list_expansions_all_params(self): list_expansions() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.GET, url, @@ -2282,7 +2284,7 @@ def test_list_expansions_all_params(self): collection_id = 'testString' # Invoke method - response = service.list_expansions( + response = _service.list_expansions( environment_id, collection_id, headers={} @@ -2299,7 +2301,7 @@ def test_list_expansions_value_error(self): test_list_expansions_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.GET, url, @@ -2319,7 +2321,7 @@ def test_list_expansions_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_expansions(**req_copy) + _service.list_expansions(**req_copy) @@ -2343,7 +2345,7 @@ def test_create_expansions_all_params(self): create_expansions() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.POST, url, @@ -2362,7 +2364,7 @@ def test_create_expansions_all_params(self): expansions = [expansion_model] # Invoke method - response = service.create_expansions( + response = _service.create_expansions( environment_id, collection_id, expansions, @@ -2383,7 +2385,7 @@ def test_create_expansions_value_error(self): test_create_expansions_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.POST, url, @@ -2410,7 +2412,7 @@ def test_create_expansions_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_expansions(**req_copy) + _service.create_expansions(**req_copy) @@ -2434,7 +2436,7 @@ def test_delete_expansions_all_params(self): delete_expansions() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') responses.add(responses.DELETE, url, status=204) @@ -2444,7 +2446,7 @@ def test_delete_expansions_all_params(self): collection_id = 'testString' # Invoke method - response = service.delete_expansions( + response = _service.delete_expansions( environment_id, collection_id, headers={} @@ -2461,7 +2463,7 @@ def test_delete_expansions_value_error(self): test_delete_expansions_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/expansions') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') responses.add(responses.DELETE, url, status=204) @@ -2478,7 +2480,7 @@ def test_delete_expansions_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_expansions(**req_copy) + _service.delete_expansions(**req_copy) @@ -2502,7 +2504,7 @@ def test_get_tokenization_dictionary_status_all_params(self): get_tokenization_dictionary_status() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.GET, url, @@ -2515,7 +2517,7 @@ def test_get_tokenization_dictionary_status_all_params(self): collection_id = 'testString' # Invoke method - response = service.get_tokenization_dictionary_status( + response = _service.get_tokenization_dictionary_status( environment_id, collection_id, headers={} @@ -2532,7 +2534,7 @@ def test_get_tokenization_dictionary_status_value_error(self): test_get_tokenization_dictionary_status_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.GET, url, @@ -2552,7 +2554,7 @@ def test_get_tokenization_dictionary_status_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_tokenization_dictionary_status(**req_copy) + _service.get_tokenization_dictionary_status(**req_copy) @@ -2576,7 +2578,7 @@ def test_create_tokenization_dictionary_all_params(self): create_tokenization_dictionary() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2597,7 +2599,7 @@ def test_create_tokenization_dictionary_all_params(self): tokenization_rules = [token_dict_rule_model] # Invoke method - response = service.create_tokenization_dictionary( + response = _service.create_tokenization_dictionary( environment_id, collection_id, tokenization_rules=tokenization_rules, @@ -2618,7 +2620,7 @@ def test_create_tokenization_dictionary_required_params(self): test_create_tokenization_dictionary_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2631,7 +2633,7 @@ def test_create_tokenization_dictionary_required_params(self): collection_id = 'testString' # Invoke method - response = service.create_tokenization_dictionary( + response = _service.create_tokenization_dictionary( environment_id, collection_id, headers={} @@ -2648,7 +2650,7 @@ def test_create_tokenization_dictionary_value_error(self): test_create_tokenization_dictionary_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2668,7 +2670,7 @@ def test_create_tokenization_dictionary_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_tokenization_dictionary(**req_copy) + _service.create_tokenization_dictionary(**req_copy) @@ -2692,7 +2694,7 @@ def test_delete_tokenization_dictionary_all_params(self): delete_tokenization_dictionary() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') responses.add(responses.DELETE, url, status=200) @@ -2702,7 +2704,7 @@ def test_delete_tokenization_dictionary_all_params(self): collection_id = 'testString' # Invoke method - response = service.delete_tokenization_dictionary( + response = _service.delete_tokenization_dictionary( environment_id, collection_id, headers={} @@ -2719,7 +2721,7 @@ def test_delete_tokenization_dictionary_value_error(self): test_delete_tokenization_dictionary_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') responses.add(responses.DELETE, url, status=200) @@ -2736,7 +2738,7 @@ def test_delete_tokenization_dictionary_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_tokenization_dictionary(**req_copy) + _service.delete_tokenization_dictionary(**req_copy) @@ -2760,7 +2762,7 @@ def test_get_stopword_list_status_all_params(self): get_stopword_list_status() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.GET, url, @@ -2773,7 +2775,7 @@ def test_get_stopword_list_status_all_params(self): collection_id = 'testString' # Invoke method - response = service.get_stopword_list_status( + response = _service.get_stopword_list_status( environment_id, collection_id, headers={} @@ -2790,7 +2792,7 @@ def test_get_stopword_list_status_value_error(self): test_get_stopword_list_status_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.GET, url, @@ -2810,7 +2812,7 @@ def test_get_stopword_list_status_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_stopword_list_status(**req_copy) + _service.get_stopword_list_status(**req_copy) @@ -2834,7 +2836,7 @@ def test_create_stopword_list_all_params(self): create_stopword_list() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2849,7 +2851,7 @@ def test_create_stopword_list_all_params(self): stopword_filename = 'testString' # Invoke method - response = service.create_stopword_list( + response = _service.create_stopword_list( environment_id, collection_id, stopword_file, @@ -2868,7 +2870,7 @@ def test_create_stopword_list_required_params(self): test_create_stopword_list_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2883,7 +2885,7 @@ def test_create_stopword_list_required_params(self): stopword_filename = 'testString' # Invoke method - response = service.create_stopword_list( + response = _service.create_stopword_list( environment_id, collection_id, stopword_file, @@ -2902,7 +2904,7 @@ def test_create_stopword_list_value_error(self): test_create_stopword_list_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2925,7 +2927,7 @@ def test_create_stopword_list_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_stopword_list(**req_copy) + _service.create_stopword_list(**req_copy) @@ -2949,7 +2951,7 @@ def test_delete_stopword_list_all_params(self): delete_stopword_list() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') responses.add(responses.DELETE, url, status=200) @@ -2959,7 +2961,7 @@ def test_delete_stopword_list_all_params(self): collection_id = 'testString' # Invoke method - response = service.delete_stopword_list( + response = _service.delete_stopword_list( environment_id, collection_id, headers={} @@ -2976,7 +2978,7 @@ def test_delete_stopword_list_value_error(self): test_delete_stopword_list_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') responses.add(responses.DELETE, url, status=200) @@ -2993,7 +2995,7 @@ def test_delete_stopword_list_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_stopword_list(**req_copy) + _service.delete_stopword_list(**req_copy) @@ -3027,8 +3029,8 @@ def test_add_document_all_params(self): add_document() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3044,7 +3046,7 @@ def test_add_document_all_params(self): metadata = 'testString' # Invoke method - response = service.add_document( + response = _service.add_document( environment_id, collection_id, file=file, @@ -3065,8 +3067,8 @@ def test_add_document_required_params(self): test_add_document_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3078,7 +3080,7 @@ def test_add_document_required_params(self): collection_id = 'testString' # Invoke method - response = service.add_document( + response = _service.add_document( environment_id, collection_id, headers={} @@ -3095,8 +3097,8 @@ def test_add_document_value_error(self): test_add_document_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3115,7 +3117,7 @@ def test_add_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_document(**req_copy) + _service.add_document(**req_copy) @@ -3139,8 +3141,8 @@ def test_get_document_status_all_params(self): get_document_status() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3153,7 +3155,7 @@ def test_get_document_status_all_params(self): document_id = 'testString' # Invoke method - response = service.get_document_status( + response = _service.get_document_status( environment_id, collection_id, document_id, @@ -3171,8 +3173,8 @@ def test_get_document_status_value_error(self): test_get_document_status_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3193,7 +3195,7 @@ def test_get_document_status_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_document_status(**req_copy) + _service.get_document_status(**req_copy) @@ -3217,8 +3219,8 @@ def test_update_document_all_params(self): update_document() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3235,7 +3237,7 @@ def test_update_document_all_params(self): metadata = 'testString' # Invoke method - response = service.update_document( + response = _service.update_document( environment_id, collection_id, document_id, @@ -3257,8 +3259,8 @@ def test_update_document_required_params(self): test_update_document_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3271,7 +3273,7 @@ def test_update_document_required_params(self): document_id = 'testString' # Invoke method - response = service.update_document( + response = _service.update_document( environment_id, collection_id, document_id, @@ -3289,8 +3291,8 @@ def test_update_document_value_error(self): test_update_document_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3311,7 +3313,7 @@ def test_update_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_document(**req_copy) + _service.update_document(**req_copy) @@ -3335,7 +3337,7 @@ def test_delete_document_all_params(self): delete_document() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -3349,7 +3351,7 @@ def test_delete_document_all_params(self): document_id = 'testString' # Invoke method - response = service.delete_document( + response = _service.delete_document( environment_id, collection_id, document_id, @@ -3367,7 +3369,7 @@ def test_delete_document_value_error(self): test_delete_document_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/documents/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -3389,7 +3391,7 @@ def test_delete_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_document(**req_copy) + _service.delete_document(**req_copy) @@ -3423,7 +3425,7 @@ def test_query_all_params(self): query() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/query') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, @@ -3457,7 +3459,7 @@ def test_query_all_params(self): x_watson_logging_opt_out = True # Invoke method - response = service.query( + response = _service.query( environment_id, collection_id, filter=filter, @@ -3517,7 +3519,7 @@ def test_query_required_params(self): test_query_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/query') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, @@ -3530,7 +3532,7 @@ def test_query_required_params(self): collection_id = 'testString' # Invoke method - response = service.query( + response = _service.query( environment_id, collection_id, headers={} @@ -3547,7 +3549,7 @@ def test_query_value_error(self): test_query_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/query') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, @@ -3567,7 +3569,7 @@ def test_query_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.query(**req_copy) + _service.query(**req_copy) @@ -3591,8 +3593,8 @@ def test_query_notices_all_params(self): query_notices() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3621,7 +3623,7 @@ def test_query_notices_all_params(self): similar_fields = ['testString'] # Invoke method - response = service.query_notices( + response = _service.query_notices( environment_id, collection_id, filter=filter, @@ -3675,8 +3677,8 @@ def test_query_notices_required_params(self): test_query_notices_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3688,7 +3690,7 @@ def test_query_notices_required_params(self): collection_id = 'testString' # Invoke method - response = service.query_notices( + response = _service.query_notices( environment_id, collection_id, headers={} @@ -3705,8 +3707,8 @@ def test_query_notices_value_error(self): test_query_notices_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3725,7 +3727,7 @@ def test_query_notices_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.query_notices(**req_copy) + _service.query_notices(**req_copy) @@ -3749,7 +3751,7 @@ def test_federated_query_all_params(self): federated_query() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/query') + url = self.preprocess_url(_base_url + '/v1/environments/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, @@ -3782,7 +3784,7 @@ def test_federated_query_all_params(self): x_watson_logging_opt_out = True # Invoke method - response = service.federated_query( + response = _service.federated_query( environment_id, collection_ids, filter=filter, @@ -3841,7 +3843,7 @@ def test_federated_query_required_params(self): test_federated_query_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/query') + url = self.preprocess_url(_base_url + '/v1/environments/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, @@ -3873,7 +3875,7 @@ def test_federated_query_required_params(self): bias = 'testString' # Invoke method - response = service.federated_query( + response = _service.federated_query( environment_id, collection_ids, filter=filter, @@ -3931,7 +3933,7 @@ def test_federated_query_value_error(self): test_federated_query_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/query') + url = self.preprocess_url(_base_url + '/v1/environments/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, @@ -3970,7 +3972,7 @@ def test_federated_query_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.federated_query(**req_copy) + _service.federated_query(**req_copy) @@ -3994,8 +3996,8 @@ def test_federated_query_notices_all_params(self): federated_query_notices() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4020,7 +4022,7 @@ def test_federated_query_notices_all_params(self): similar_fields = ['testString'] # Invoke method - response = service.federated_query_notices( + response = _service.federated_query_notices( environment_id, collection_ids, filter=filter, @@ -4067,8 +4069,8 @@ def test_federated_query_notices_required_params(self): test_federated_query_notices_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4080,7 +4082,7 @@ def test_federated_query_notices_required_params(self): collection_ids = ['testString'] # Invoke method - response = service.federated_query_notices( + response = _service.federated_query_notices( environment_id, collection_ids, headers={} @@ -4101,8 +4103,8 @@ def test_federated_query_notices_value_error(self): test_federated_query_notices_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = self.preprocess_url(_base_url + '/v1/environments/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4121,7 +4123,7 @@ def test_federated_query_notices_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.federated_query_notices(**req_copy) + _service.federated_query_notices(**req_copy) @@ -4145,7 +4147,7 @@ def test_get_autocompletion_all_params(self): get_autocompletion() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/autocompletion') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -4161,7 +4163,7 @@ def test_get_autocompletion_all_params(self): count = 38 # Invoke method - response = service.get_autocompletion( + response = _service.get_autocompletion( environment_id, collection_id, prefix, @@ -4187,7 +4189,7 @@ def test_get_autocompletion_required_params(self): test_get_autocompletion_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/autocompletion') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -4201,7 +4203,7 @@ def test_get_autocompletion_required_params(self): prefix = 'testString' # Invoke method - response = service.get_autocompletion( + response = _service.get_autocompletion( environment_id, collection_id, prefix, @@ -4223,7 +4225,7 @@ def test_get_autocompletion_value_error(self): test_get_autocompletion_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/autocompletion') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -4245,7 +4247,7 @@ def test_get_autocompletion_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_autocompletion(**req_copy) + _service.get_autocompletion(**req_copy) @@ -4279,7 +4281,7 @@ def test_list_training_data_all_params(self): list_training_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' responses.add(responses.GET, url, @@ -4292,7 +4294,7 @@ def test_list_training_data_all_params(self): collection_id = 'testString' # Invoke method - response = service.list_training_data( + response = _service.list_training_data( environment_id, collection_id, headers={} @@ -4309,7 +4311,7 @@ def test_list_training_data_value_error(self): test_list_training_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' responses.add(responses.GET, url, @@ -4329,7 +4331,7 @@ def test_list_training_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_training_data(**req_copy) + _service.list_training_data(**req_copy) @@ -4353,7 +4355,7 @@ def test_add_training_data_all_params(self): add_training_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.POST, url, @@ -4375,7 +4377,7 @@ def test_add_training_data_all_params(self): examples = [training_example_model] # Invoke method - response = service.add_training_data( + response = _service.add_training_data( environment_id, collection_id, natural_language_query=natural_language_query, @@ -4400,7 +4402,7 @@ def test_add_training_data_value_error(self): test_add_training_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.POST, url, @@ -4429,7 +4431,7 @@ def test_add_training_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_training_data(**req_copy) + _service.add_training_data(**req_copy) @@ -4453,7 +4455,7 @@ def test_delete_all_training_data_all_params(self): delete_all_training_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') responses.add(responses.DELETE, url, status=204) @@ -4463,7 +4465,7 @@ def test_delete_all_training_data_all_params(self): collection_id = 'testString' # Invoke method - response = service.delete_all_training_data( + response = _service.delete_all_training_data( environment_id, collection_id, headers={} @@ -4480,7 +4482,7 @@ def test_delete_all_training_data_value_error(self): test_delete_all_training_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') responses.add(responses.DELETE, url, status=204) @@ -4497,7 +4499,7 @@ def test_delete_all_training_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_all_training_data(**req_copy) + _service.delete_all_training_data(**req_copy) @@ -4521,7 +4523,7 @@ def test_get_training_data_all_params(self): get_training_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.GET, url, @@ -4535,7 +4537,7 @@ def test_get_training_data_all_params(self): query_id = 'testString' # Invoke method - response = service.get_training_data( + response = _service.get_training_data( environment_id, collection_id, query_id, @@ -4553,7 +4555,7 @@ def test_get_training_data_value_error(self): test_get_training_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.GET, url, @@ -4575,7 +4577,7 @@ def test_get_training_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_training_data(**req_copy) + _service.get_training_data(**req_copy) @@ -4599,7 +4601,7 @@ def test_delete_training_data_all_params(self): delete_training_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString') responses.add(responses.DELETE, url, status=204) @@ -4610,7 +4612,7 @@ def test_delete_training_data_all_params(self): query_id = 'testString' # Invoke method - response = service.delete_training_data( + response = _service.delete_training_data( environment_id, collection_id, query_id, @@ -4628,7 +4630,7 @@ def test_delete_training_data_value_error(self): test_delete_training_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString') responses.add(responses.DELETE, url, status=204) @@ -4647,7 +4649,7 @@ def test_delete_training_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_training_data(**req_copy) + _service.delete_training_data(**req_copy) @@ -4671,7 +4673,7 @@ def test_list_training_examples_all_params(self): list_training_examples() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.GET, url, @@ -4685,7 +4687,7 @@ def test_list_training_examples_all_params(self): query_id = 'testString' # Invoke method - response = service.list_training_examples( + response = _service.list_training_examples( environment_id, collection_id, query_id, @@ -4703,7 +4705,7 @@ def test_list_training_examples_value_error(self): test_list_training_examples_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.GET, url, @@ -4725,7 +4727,7 @@ def test_list_training_examples_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_training_examples(**req_copy) + _service.list_training_examples(**req_copy) @@ -4749,7 +4751,7 @@ def test_create_training_example_all_params(self): create_training_example() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.POST, url, @@ -4766,7 +4768,7 @@ def test_create_training_example_all_params(self): relevance = 38 # Invoke method - response = service.create_training_example( + response = _service.create_training_example( environment_id, collection_id, query_id, @@ -4792,7 +4794,7 @@ def test_create_training_example_value_error(self): test_create_training_example_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.POST, url, @@ -4817,7 +4819,7 @@ def test_create_training_example_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_training_example(**req_copy) + _service.create_training_example(**req_copy) @@ -4841,7 +4843,7 @@ def test_delete_training_example_all_params(self): delete_training_example() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') responses.add(responses.DELETE, url, status=204) @@ -4853,7 +4855,7 @@ def test_delete_training_example_all_params(self): example_id = 'testString' # Invoke method - response = service.delete_training_example( + response = _service.delete_training_example( environment_id, collection_id, query_id, @@ -4872,7 +4874,7 @@ def test_delete_training_example_value_error(self): test_delete_training_example_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') responses.add(responses.DELETE, url, status=204) @@ -4893,7 +4895,7 @@ def test_delete_training_example_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_training_example(**req_copy) + _service.delete_training_example(**req_copy) @@ -4917,7 +4919,7 @@ def test_update_training_example_all_params(self): update_training_example() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.PUT, url, @@ -4934,7 +4936,7 @@ def test_update_training_example_all_params(self): relevance = 38 # Invoke method - response = service.update_training_example( + response = _service.update_training_example( environment_id, collection_id, query_id, @@ -4959,7 +4961,7 @@ def test_update_training_example_value_error(self): test_update_training_example_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.PUT, url, @@ -4985,7 +4987,7 @@ def test_update_training_example_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_training_example(**req_copy) + _service.update_training_example(**req_copy) @@ -5009,7 +5011,7 @@ def test_get_training_example_all_params(self): get_training_example() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.GET, url, @@ -5024,7 +5026,7 @@ def test_get_training_example_all_params(self): example_id = 'testString' # Invoke method - response = service.get_training_example( + response = _service.get_training_example( environment_id, collection_id, query_id, @@ -5043,7 +5045,7 @@ def test_get_training_example_value_error(self): test_get_training_example_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.GET, url, @@ -5067,7 +5069,7 @@ def test_get_training_example_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_training_example(**req_copy) + _service.get_training_example(**req_copy) @@ -5101,7 +5103,7 @@ def test_delete_user_data_all_params(self): delete_user_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/user_data') + url = self.preprocess_url(_base_url + '/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -5110,7 +5112,7 @@ def test_delete_user_data_all_params(self): customer_id = 'testString' # Invoke method - response = service.delete_user_data( + response = _service.delete_user_data( customer_id, headers={} ) @@ -5130,7 +5132,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/user_data') + url = self.preprocess_url(_base_url + '/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -5145,7 +5147,7 @@ def test_delete_user_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_user_data(**req_copy) + _service.delete_user_data(**req_copy) @@ -5179,8 +5181,8 @@ def test_create_event_all_params(self): create_event() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/events') - mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' + url = self.preprocess_url(_base_url + '/v1/events') + mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' responses.add(responses.POST, url, body=mock_response, @@ -5191,7 +5193,7 @@ def test_create_event_all_params(self): event_data_model = {} event_data_model['environment_id'] = 'testString' event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + event_data_model['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) event_data_model['display_rank'] = 38 event_data_model['collection_id'] = 'testString' event_data_model['document_id'] = 'testString' @@ -5201,7 +5203,7 @@ def test_create_event_all_params(self): data = event_data_model # Invoke method - response = service.create_event( + response = _service.create_event( type, data, headers={} @@ -5222,8 +5224,8 @@ def test_create_event_value_error(self): test_create_event_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/events') - mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' + url = self.preprocess_url(_base_url + '/v1/events') + mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' responses.add(responses.POST, url, body=mock_response, @@ -5234,7 +5236,7 @@ def test_create_event_value_error(self): event_data_model = {} event_data_model['environment_id'] = 'testString' event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + event_data_model['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) event_data_model['display_rank'] = 38 event_data_model['collection_id'] = 'testString' event_data_model['document_id'] = 'testString' @@ -5251,7 +5253,7 @@ def test_create_event_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_event(**req_copy) + _service.create_event(**req_copy) @@ -5275,8 +5277,8 @@ def test_query_log_all_params(self): query_log() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/logs') - mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00", "client_timestamp": "2019-01-01T12:00:00", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' + url = self.preprocess_url(_base_url + '/v1/logs') + mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' responses.add(responses.GET, url, body=mock_response, @@ -5291,7 +5293,7 @@ def test_query_log_all_params(self): sort = ['testString'] # Invoke method - response = service.query_log( + response = _service.query_log( filter=filter, query=query, count=count, @@ -5319,8 +5321,8 @@ def test_query_log_required_params(self): test_query_log_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/logs') - mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00", "client_timestamp": "2019-01-01T12:00:00", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' + url = self.preprocess_url(_base_url + '/v1/logs') + mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' responses.add(responses.GET, url, body=mock_response, @@ -5328,7 +5330,7 @@ def test_query_log_required_params(self): status=200) # Invoke method - response = service.query_log() + response = _service.query_log() # Check for correct operation @@ -5342,8 +5344,8 @@ def test_query_log_value_error(self): test_query_log_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/logs') - mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00", "client_timestamp": "2019-01-01T12:00:00", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' + url = self.preprocess_url(_base_url + '/v1/logs') + mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' responses.add(responses.GET, url, body=mock_response, @@ -5356,7 +5358,7 @@ def test_query_log_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.query_log(**req_copy) + _service.query_log(**req_copy) @@ -5380,8 +5382,8 @@ def test_get_metrics_query_all_params(self): get_metrics_query() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5389,12 +5391,12 @@ def test_get_metrics_query_all_params(self): status=200) # Set up parameter values - start_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) - end_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + start_time = string_to_datetime('2019-01-01T12:00:00.000Z') + end_time = string_to_datetime('2019-01-01T12:00:00.000Z') result_type = 'document' # Invoke method - response = service.get_metrics_query( + response = _service.get_metrics_query( start_time=start_time, end_time=end_time, result_type=result_type, @@ -5416,8 +5418,8 @@ def test_get_metrics_query_required_params(self): test_get_metrics_query_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5425,7 +5427,7 @@ def test_get_metrics_query_required_params(self): status=200) # Invoke method - response = service.get_metrics_query() + response = _service.get_metrics_query() # Check for correct operation @@ -5439,8 +5441,8 @@ def test_get_metrics_query_value_error(self): test_get_metrics_query_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5453,7 +5455,7 @@ def test_get_metrics_query_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_metrics_query(**req_copy) + _service.get_metrics_query(**req_copy) @@ -5477,8 +5479,8 @@ def test_get_metrics_query_event_all_params(self): get_metrics_query_event() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_event') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_event') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5486,12 +5488,12 @@ def test_get_metrics_query_event_all_params(self): status=200) # Set up parameter values - start_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) - end_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + start_time = string_to_datetime('2019-01-01T12:00:00.000Z') + end_time = string_to_datetime('2019-01-01T12:00:00.000Z') result_type = 'document' # Invoke method - response = service.get_metrics_query_event( + response = _service.get_metrics_query_event( start_time=start_time, end_time=end_time, result_type=result_type, @@ -5513,8 +5515,8 @@ def test_get_metrics_query_event_required_params(self): test_get_metrics_query_event_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_event') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_event') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5522,7 +5524,7 @@ def test_get_metrics_query_event_required_params(self): status=200) # Invoke method - response = service.get_metrics_query_event() + response = _service.get_metrics_query_event() # Check for correct operation @@ -5536,8 +5538,8 @@ def test_get_metrics_query_event_value_error(self): test_get_metrics_query_event_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_event') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_event') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5550,7 +5552,7 @@ def test_get_metrics_query_event_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_metrics_query_event(**req_copy) + _service.get_metrics_query_event(**req_copy) @@ -5574,8 +5576,8 @@ def test_get_metrics_query_no_results_all_params(self): get_metrics_query_no_results() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_no_search_results') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_no_search_results') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5583,12 +5585,12 @@ def test_get_metrics_query_no_results_all_params(self): status=200) # Set up parameter values - start_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) - end_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + start_time = string_to_datetime('2019-01-01T12:00:00.000Z') + end_time = string_to_datetime('2019-01-01T12:00:00.000Z') result_type = 'document' # Invoke method - response = service.get_metrics_query_no_results( + response = _service.get_metrics_query_no_results( start_time=start_time, end_time=end_time, result_type=result_type, @@ -5610,8 +5612,8 @@ def test_get_metrics_query_no_results_required_params(self): test_get_metrics_query_no_results_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_no_search_results') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_no_search_results') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5619,7 +5621,7 @@ def test_get_metrics_query_no_results_required_params(self): status=200) # Invoke method - response = service.get_metrics_query_no_results() + response = _service.get_metrics_query_no_results() # Check for correct operation @@ -5633,8 +5635,8 @@ def test_get_metrics_query_no_results_value_error(self): test_get_metrics_query_no_results_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/number_of_queries_with_no_search_results') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_no_search_results') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5647,7 +5649,7 @@ def test_get_metrics_query_no_results_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_metrics_query_no_results(**req_copy) + _service.get_metrics_query_no_results(**req_copy) @@ -5671,8 +5673,8 @@ def test_get_metrics_event_rate_all_params(self): get_metrics_event_rate() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/event_rate') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/event_rate') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5680,12 +5682,12 @@ def test_get_metrics_event_rate_all_params(self): status=200) # Set up parameter values - start_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) - end_time = datetime.fromtimestamp(1580236840.123456, timezone.utc) + start_time = string_to_datetime('2019-01-01T12:00:00.000Z') + end_time = string_to_datetime('2019-01-01T12:00:00.000Z') result_type = 'document' # Invoke method - response = service.get_metrics_event_rate( + response = _service.get_metrics_event_rate( start_time=start_time, end_time=end_time, result_type=result_type, @@ -5707,8 +5709,8 @@ def test_get_metrics_event_rate_required_params(self): test_get_metrics_event_rate_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/event_rate') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/event_rate') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5716,7 +5718,7 @@ def test_get_metrics_event_rate_required_params(self): status=200) # Invoke method - response = service.get_metrics_event_rate() + response = _service.get_metrics_event_rate() # Check for correct operation @@ -5730,8 +5732,8 @@ def test_get_metrics_event_rate_value_error(self): test_get_metrics_event_rate_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/event_rate') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' + url = self.preprocess_url(_base_url + '/v1/metrics/event_rate') + mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -5744,7 +5746,7 @@ def test_get_metrics_event_rate_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_metrics_event_rate(**req_copy) + _service.get_metrics_event_rate(**req_copy) @@ -5768,7 +5770,7 @@ def test_get_metrics_query_token_event_all_params(self): get_metrics_query_token_event() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/top_query_tokens_with_event_rate') + url = self.preprocess_url(_base_url + '/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5780,7 +5782,7 @@ def test_get_metrics_query_token_event_all_params(self): count = 38 # Invoke method - response = service.get_metrics_query_token_event( + response = _service.get_metrics_query_token_event( count=count, headers={} ) @@ -5800,7 +5802,7 @@ def test_get_metrics_query_token_event_required_params(self): test_get_metrics_query_token_event_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/top_query_tokens_with_event_rate') + url = self.preprocess_url(_base_url + '/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5809,7 +5811,7 @@ def test_get_metrics_query_token_event_required_params(self): status=200) # Invoke method - response = service.get_metrics_query_token_event() + response = _service.get_metrics_query_token_event() # Check for correct operation @@ -5823,7 +5825,7 @@ def test_get_metrics_query_token_event_value_error(self): test_get_metrics_query_token_event_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/metrics/top_query_tokens_with_event_rate') + url = self.preprocess_url(_base_url + '/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5837,7 +5839,7 @@ def test_get_metrics_query_token_event_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_metrics_query_token_event(**req_copy) + _service.get_metrics_query_token_event(**req_copy) @@ -5871,7 +5873,7 @@ def test_list_credentials_all_params(self): list_credentials() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/credentials') + url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}]}' responses.add(responses.GET, url, @@ -5883,7 +5885,7 @@ def test_list_credentials_all_params(self): environment_id = 'testString' # Invoke method - response = service.list_credentials( + response = _service.list_credentials( environment_id, headers={} ) @@ -5899,7 +5901,7 @@ def test_list_credentials_value_error(self): test_list_credentials_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/credentials') + url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}]}' responses.add(responses.GET, url, @@ -5917,7 +5919,7 @@ def test_list_credentials_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_credentials(**req_copy) + _service.list_credentials(**req_copy) @@ -5941,7 +5943,7 @@ def test_create_credentials_all_params(self): create_credentials() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/credentials') + url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' responses.add(responses.POST, url, @@ -5978,7 +5980,7 @@ def test_create_credentials_all_params(self): status = 'connected' # Invoke method - response = service.create_credentials( + response = _service.create_credentials( environment_id, source_type=source_type, credential_details=credential_details, @@ -6002,7 +6004,7 @@ def test_create_credentials_value_error(self): test_create_credentials_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/credentials') + url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' responses.add(responses.POST, url, @@ -6045,7 +6047,7 @@ def test_create_credentials_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_credentials(**req_copy) + _service.create_credentials(**req_copy) @@ -6069,7 +6071,7 @@ def test_get_credentials_all_params(self): get_credentials() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' responses.add(responses.GET, url, @@ -6082,7 +6084,7 @@ def test_get_credentials_all_params(self): credential_id = 'testString' # Invoke method - response = service.get_credentials( + response = _service.get_credentials( environment_id, credential_id, headers={} @@ -6099,7 +6101,7 @@ def test_get_credentials_value_error(self): test_get_credentials_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' responses.add(responses.GET, url, @@ -6119,7 +6121,7 @@ def test_get_credentials_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_credentials(**req_copy) + _service.get_credentials(**req_copy) @@ -6143,7 +6145,7 @@ def test_update_credentials_all_params(self): update_credentials() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' responses.add(responses.PUT, url, @@ -6181,7 +6183,7 @@ def test_update_credentials_all_params(self): status = 'connected' # Invoke method - response = service.update_credentials( + response = _service.update_credentials( environment_id, credential_id, source_type=source_type, @@ -6206,7 +6208,7 @@ def test_update_credentials_value_error(self): test_update_credentials_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' responses.add(responses.PUT, url, @@ -6251,7 +6253,7 @@ def test_update_credentials_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_credentials(**req_copy) + _service.update_credentials(**req_copy) @@ -6275,7 +6277,7 @@ def test_delete_credentials_all_params(self): delete_credentials() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -6288,7 +6290,7 @@ def test_delete_credentials_all_params(self): credential_id = 'testString' # Invoke method - response = service.delete_credentials( + response = _service.delete_credentials( environment_id, credential_id, headers={} @@ -6305,7 +6307,7 @@ def test_delete_credentials_value_error(self): test_delete_credentials_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/credentials/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -6325,7 +6327,7 @@ def test_delete_credentials_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_credentials(**req_copy) + _service.delete_credentials(**req_copy) @@ -6359,7 +6361,7 @@ def test_list_gateways_all_params(self): list_gateways() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/gateways') + url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways') mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' responses.add(responses.GET, url, @@ -6371,7 +6373,7 @@ def test_list_gateways_all_params(self): environment_id = 'testString' # Invoke method - response = service.list_gateways( + response = _service.list_gateways( environment_id, headers={} ) @@ -6387,7 +6389,7 @@ def test_list_gateways_value_error(self): test_list_gateways_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/gateways') + url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways') mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' responses.add(responses.GET, url, @@ -6405,7 +6407,7 @@ def test_list_gateways_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_gateways(**req_copy) + _service.list_gateways(**req_copy) @@ -6429,7 +6431,7 @@ def test_create_gateway_all_params(self): create_gateway() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/gateways') + url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' responses.add(responses.POST, url, @@ -6442,7 +6444,7 @@ def test_create_gateway_all_params(self): name = 'testString' # Invoke method - response = service.create_gateway( + response = _service.create_gateway( environment_id, name=name, headers={} @@ -6462,7 +6464,7 @@ def test_create_gateway_required_params(self): test_create_gateway_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/gateways') + url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' responses.add(responses.POST, url, @@ -6474,7 +6476,7 @@ def test_create_gateway_required_params(self): environment_id = 'testString' # Invoke method - response = service.create_gateway( + response = _service.create_gateway( environment_id, headers={} ) @@ -6490,7 +6492,7 @@ def test_create_gateway_value_error(self): test_create_gateway_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/gateways') + url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' responses.add(responses.POST, url, @@ -6508,7 +6510,7 @@ def test_create_gateway_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_gateway(**req_copy) + _service.create_gateway(**req_copy) @@ -6532,7 +6534,7 @@ def test_get_gateway_all_params(self): get_gateway() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/gateways/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' responses.add(responses.GET, url, @@ -6545,7 +6547,7 @@ def test_get_gateway_all_params(self): gateway_id = 'testString' # Invoke method - response = service.get_gateway( + response = _service.get_gateway( environment_id, gateway_id, headers={} @@ -6562,7 +6564,7 @@ def test_get_gateway_value_error(self): test_get_gateway_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/gateways/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' responses.add(responses.GET, url, @@ -6582,7 +6584,7 @@ def test_get_gateway_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_gateway(**req_copy) + _service.get_gateway(**req_copy) @@ -6606,7 +6608,7 @@ def test_delete_gateway_all_params(self): delete_gateway() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/gateways/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "status": "status"}' responses.add(responses.DELETE, url, @@ -6619,7 +6621,7 @@ def test_delete_gateway_all_params(self): gateway_id = 'testString' # Invoke method - response = service.delete_gateway( + response = _service.delete_gateway( environment_id, gateway_id, headers={} @@ -6636,7 +6638,7 @@ def test_delete_gateway_value_error(self): test_delete_gateway_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/environments/testString/gateways/testString') + url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "status": "status"}' responses.add(responses.DELETE, url, @@ -6656,7 +6658,7 @@ def test_delete_gateway_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_gateway(**req_copy) + _service.delete_gateway(**req_copy) @@ -6729,12 +6731,12 @@ def test_collection_serialization(self): training_status_model['minimum_examples_added'] = False training_status_model['sufficient_label_diversity'] = False training_status_model['notices'] = 0 - training_status_model['successfully_trained'] = '2020-01-28T18:40:40.123456Z' - training_status_model['data_updated'] = '2020-01-28T18:40:40.123456Z' + training_status_model['successfully_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_status_model['data_updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) source_status_model = {} # SourceStatus source_status_model['status'] = 'complete' - source_status_model['next_crawl'] = '2020-01-28T18:40:40.123456Z' + source_status_model['next_crawl'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) collection_crawl_status_model = {} # CollectionCrawlStatus collection_crawl_status_model['source_crawl'] = source_status_model @@ -6755,8 +6757,8 @@ def test_collection_serialization(self): collection_model_json['collection_id'] = 'testString' collection_model_json['name'] = 'testString' collection_model_json['description'] = 'testString' - collection_model_json['created'] = '2020-01-28T18:40:40.123456Z' - collection_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + collection_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + collection_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) collection_model_json['status'] = 'active' collection_model_json['configuration_id'] = 'testString' collection_model_json['language'] = 'testString' @@ -6795,7 +6797,7 @@ def test_collection_crawl_status_serialization(self): source_status_model = {} # SourceStatus source_status_model['status'] = 'running' - source_status_model['next_crawl'] = '2020-01-28T18:40:40.123456Z' + source_status_model['next_crawl'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a json representation of a CollectionCrawlStatus model collection_crawl_status_model_json = {} @@ -6946,7 +6948,7 @@ def test_configuration_serialization(self): html_settings_model = {} # HtmlSettings html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] + html_settings_model['exclude_tags_keep_content'] = ['span'] html_settings_model['keep_content'] = x_path_patterns_model html_settings_model['exclude_content'] = x_path_patterns_model html_settings_model['keep_tag_attributes'] = ['testString'] @@ -6955,7 +6957,7 @@ def test_configuration_serialization(self): segment_settings_model = {} # SegmentSettings segment_settings_model['enabled'] = True segment_settings_model['selector_tags'] = ['testString'] - segment_settings_model['annotated_fields'] = ['testString'] + segment_settings_model['annotated_fields'] = ['custom-field-1', 'custom-field-2'] normalization_operation_model = {} # NormalizationOperation normalization_operation_model['operation'] = 'move' @@ -6986,11 +6988,11 @@ def test_configuration_serialization(self): nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] + nlu_enrichment_sentiment_model['targets'] = ['IBM', 'Watson'] nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] + nlu_enrichment_emotion_model['targets'] = ['IBM', 'Watson'] nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles nlu_enrichment_semantic_roles_model['entities'] = True @@ -7077,8 +7079,8 @@ def test_configuration_serialization(self): configuration_model_json = {} configuration_model_json['configuration_id'] = 'testString' configuration_model_json['name'] = 'testString' - configuration_model_json['created'] = '2020-01-28T18:40:40.123456Z' - configuration_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + configuration_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + configuration_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) configuration_model_json['description'] = 'testString' configuration_model_json['conversions'] = conversions_model configuration_model_json['enrichments'] = [enrichment_model] @@ -7197,7 +7199,7 @@ def test_create_event_response_serialization(self): event_data_model = {} # EventData event_data_model['environment_id'] = 'testString' event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + event_data_model['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) event_data_model['display_rank'] = 38 event_data_model['collection_id'] = 'testString' event_data_model['document_id'] = 'testString' @@ -7427,7 +7429,7 @@ def test_delete_configuration_response_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'configuration_in_use' - notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['created'] = datetime_to_string(string_to_datetime("2016-09-28T12:34:00.000Z")) notice_model['document_id'] = 'testString' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -7589,7 +7591,7 @@ def test_document_accepted_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) notice_model['document_id'] = 'testString' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -7663,7 +7665,7 @@ def test_document_status_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'index_342' - notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) notice_model['document_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -7890,15 +7892,15 @@ def test_environment_serialization(self): search_status_model['scope'] = 'testString' search_status_model['status'] = 'NO_DATA' search_status_model['status_description'] = 'testString' - search_status_model['last_trained'] = '2020-01-28' + search_status_model['last_trained'] = "2019-01-01" # Construct a json representation of a Environment model environment_model_json = {} environment_model_json['environment_id'] = 'testString' environment_model_json['name'] = 'testString' environment_model_json['description'] = 'testString' - environment_model_json['created'] = '2020-01-28T18:40:40.123456Z' - environment_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + environment_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + environment_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) environment_model_json['status'] = 'active' environment_model_json['read_only'] = True environment_model_json['size'] = 'LT' @@ -7965,7 +7967,7 @@ def test_event_data_serialization(self): event_data_model_json = {} event_data_model_json['environment_id'] = 'testString' event_data_model_json['session_token'] = 'testString' - event_data_model_json['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + event_data_model_json['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) event_data_model_json['display_rank'] = 38 event_data_model_json['collection_id'] = 'testString' event_data_model_json['document_id'] = 'testString' @@ -8364,12 +8366,12 @@ def test_list_collections_response_serialization(self): training_status_model['minimum_examples_added'] = True training_status_model['sufficient_label_diversity'] = True training_status_model['notices'] = 38 - training_status_model['successfully_trained'] = '2020-01-28T18:40:40.123456Z' - training_status_model['data_updated'] = '2020-01-28T18:40:40.123456Z' + training_status_model['successfully_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_status_model['data_updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) source_status_model = {} # SourceStatus source_status_model['status'] = 'running' - source_status_model['next_crawl'] = '2020-01-28T18:40:40.123456Z' + source_status_model['next_crawl'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) collection_crawl_status_model = {} # CollectionCrawlStatus collection_crawl_status_model['source_crawl'] = source_status_model @@ -8389,8 +8391,8 @@ def test_list_collections_response_serialization(self): collection_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' collection_model['name'] = 'example' collection_model['description'] = 'this is a demo collection' - collection_model['created'] = '2020-01-28T18:40:40.123456Z' - collection_model['updated'] = '2020-01-28T18:40:40.123456Z' + collection_model['created'] = datetime_to_string(string_to_datetime("2015-08-24T18:42:25.324Z")) + collection_model['updated'] = datetime_to_string(string_to_datetime("2015-08-24T18:42:25.324Z")) collection_model['status'] = 'active' collection_model['configuration_id'] = '6963be41-2dea-4f79-8f52-127c63c479b0' collection_model['language'] = 'en' @@ -8591,8 +8593,8 @@ def test_list_configurations_response_serialization(self): configuration_model = {} # Configuration configuration_model['configuration_id'] = 'testString' configuration_model['name'] = 'testString' - configuration_model['created'] = '2020-01-28T18:40:40.123456Z' - configuration_model['updated'] = '2020-01-28T18:40:40.123456Z' + configuration_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + configuration_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) configuration_model['description'] = 'testString' configuration_model['conversions'] = conversions_model configuration_model['enrichments'] = [enrichment_model] @@ -8651,14 +8653,14 @@ def test_list_environments_response_serialization(self): search_status_model['scope'] = 'testString' search_status_model['status'] = 'NO_DATA' search_status_model['status_description'] = 'testString' - search_status_model['last_trained'] = '2020-01-28' + search_status_model['last_trained'] = "2019-01-01" environment_model = {} # Environment environment_model['environment_id'] = 'ecbda78e-fb06-40b1-a43f-a039fac0adc6' environment_model['name'] = 'byod_environment' environment_model['description'] = 'Private Data Environment' - environment_model['created'] = '2020-01-28T18:40:40.123456Z' - environment_model['updated'] = '2020-01-28T18:40:40.123456Z' + environment_model['created'] = datetime_to_string(string_to_datetime("2017-07-14T12:54:40.985Z")) + environment_model['updated'] = datetime_to_string(string_to_datetime("2017-07-14T12:54:40.985Z")) environment_model['status'] = 'active' environment_model['read_only'] = False environment_model['size'] = 'LT' @@ -8714,8 +8716,8 @@ def test_log_query_response_serialization(self): log_query_response_result_model['document_type'] = 'query' log_query_response_result_model['natural_language_query'] = 'testString' log_query_response_result_model['document_results'] = log_query_response_result_documents_model - log_query_response_result_model['created_timestamp'] = '2020-01-28T18:40:40.123456Z' - log_query_response_result_model['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + log_query_response_result_model['created_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + log_query_response_result_model['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) log_query_response_result_model['query_id'] = 'testString' log_query_response_result_model['session_token'] = 'testString' log_query_response_result_model['collection_id'] = 'testString' @@ -8774,8 +8776,8 @@ def test_log_query_response_result_serialization(self): log_query_response_result_model_json['document_type'] = 'query' log_query_response_result_model_json['natural_language_query'] = 'testString' log_query_response_result_model_json['document_results'] = log_query_response_result_documents_model - log_query_response_result_model_json['created_timestamp'] = '2020-01-28T18:40:40.123456Z' - log_query_response_result_model_json['client_timestamp'] = '2020-01-28T18:40:40.123456Z' + log_query_response_result_model_json['created_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + log_query_response_result_model_json['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) log_query_response_result_model_json['query_id'] = 'testString' log_query_response_result_model_json['session_token'] = 'testString' log_query_response_result_model_json['collection_id'] = 'testString' @@ -8884,7 +8886,7 @@ def test_metric_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. metric_aggregation_result_model = {} # MetricAggregationResult - metric_aggregation_result_model['key_as_string'] = '2020-01-28T18:40:40.123456Z' + metric_aggregation_result_model['key_as_string'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) metric_aggregation_result_model['key'] = 26 metric_aggregation_result_model['matching_results'] = 38 metric_aggregation_result_model['event_rate'] = 72.5 @@ -8922,7 +8924,7 @@ def test_metric_aggregation_result_serialization(self): # Construct a json representation of a MetricAggregationResult model metric_aggregation_result_model_json = {} - metric_aggregation_result_model_json['key_as_string'] = '2020-01-28T18:40:40.123456Z' + metric_aggregation_result_model_json['key_as_string'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) metric_aggregation_result_model_json['key'] = 26 metric_aggregation_result_model_json['matching_results'] = 38 metric_aggregation_result_model_json['event_rate'] = 72.5 @@ -8955,7 +8957,7 @@ def test_metric_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. metric_aggregation_result_model = {} # MetricAggregationResult - metric_aggregation_result_model['key_as_string'] = '2020-01-28T18:40:40.123456Z' + metric_aggregation_result_model['key_as_string'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) metric_aggregation_result_model['key'] = 26 metric_aggregation_result_model['matching_results'] = 38 metric_aggregation_result_model['event_rate'] = 72.5 @@ -9422,7 +9424,7 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} notice_model_json['notice_id'] = 'testString' - notice_model_json['created'] = '2020-01-28T18:40:40.123456Z' + notice_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) notice_model_json['document_id'] = 'testString' notice_model_json['query_id'] = 'testString' notice_model_json['severity'] = 'warning' @@ -9573,7 +9575,7 @@ def test_query_notices_response_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'xpath_not_found' - notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['created'] = datetime_to_string(string_to_datetime("2016-09-20T17:26:17.000Z")) notice_model['document_id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -9647,7 +9649,7 @@ def test_query_notices_result_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) notice_model['document_id'] = 'testString' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -9964,7 +9966,7 @@ def test_search_status_serialization(self): search_status_model_json['scope'] = 'testString' search_status_model_json['status'] = 'NO_DATA' search_status_model_json['status_description'] = 'testString' - search_status_model_json['last_trained'] = '2020-01-28' + search_status_model_json['last_trained'] = "2019-01-01" # Construct a model instance of SearchStatus by calling from_dict on the json representation search_status_model = SearchStatus.from_dict(search_status_model_json) @@ -10350,7 +10352,7 @@ def test_source_status_serialization(self): # Construct a json representation of a SourceStatus model source_status_model_json = {} source_status_model_json['status'] = 'running' - source_status_model_json['next_crawl'] = '2020-01-28T18:40:40.123456Z' + source_status_model_json['next_crawl'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of SourceStatus by calling from_dict on the json representation source_status_model = SourceStatus.from_dict(source_status_model_json) @@ -10641,8 +10643,8 @@ def test_training_status_serialization(self): training_status_model_json['minimum_examples_added'] = True training_status_model_json['sufficient_label_diversity'] = True training_status_model_json['notices'] = 38 - training_status_model_json['successfully_trained'] = '2020-01-28T18:40:40.123456Z' - training_status_model_json['data_updated'] = '2020-01-28T18:40:40.123456Z' + training_status_model_json['successfully_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_status_model_json['data_updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of TrainingStatus by calling from_dict on the json representation training_status_model = TrainingStatus.from_dict(training_status_model_json) diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index ab79534bc..6b198cb12 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2018, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect import io import json @@ -32,13 +33,13 @@ version = 'testString' -service = LanguageTranslatorV3( +_service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version=version ) -base_url = 'https://api.us-south.language-translator.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.language-translator.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: Languages @@ -65,7 +66,7 @@ def test_list_languages_all_params(self): list_languages() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/languages') + url = self.preprocess_url(_base_url + '/v3/languages') mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' responses.add(responses.GET, url, @@ -74,7 +75,7 @@ def test_list_languages_all_params(self): status=200) # Invoke method - response = service.list_languages() + response = _service.list_languages() # Check for correct operation @@ -88,7 +89,7 @@ def test_list_languages_value_error(self): test_list_languages_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/languages') + url = self.preprocess_url(_base_url + '/v3/languages') mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' responses.add(responses.GET, url, @@ -102,7 +103,7 @@ def test_list_languages_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_languages(**req_copy) + _service.list_languages(**req_copy) @@ -136,7 +137,7 @@ def test_translate_all_params(self): translate() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/translate') + url = self.preprocess_url(_base_url + '/v3/translate') mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' responses.add(responses.POST, url, @@ -151,7 +152,7 @@ def test_translate_all_params(self): target = 'testString' # Invoke method - response = service.translate( + response = _service.translate( text, model_id=model_id, source=source, @@ -176,7 +177,7 @@ def test_translate_value_error(self): test_translate_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/translate') + url = self.preprocess_url(_base_url + '/v3/translate') mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' responses.add(responses.POST, url, @@ -197,7 +198,7 @@ def test_translate_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.translate(**req_copy) + _service.translate(**req_copy) @@ -231,7 +232,7 @@ def test_list_identifiable_languages_all_params(self): list_identifiable_languages() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/identifiable_languages') + url = self.preprocess_url(_base_url + '/v3/identifiable_languages') mock_response = '{"languages": [{"language": "language", "name": "name"}]}' responses.add(responses.GET, url, @@ -240,7 +241,7 @@ def test_list_identifiable_languages_all_params(self): status=200) # Invoke method - response = service.list_identifiable_languages() + response = _service.list_identifiable_languages() # Check for correct operation @@ -254,7 +255,7 @@ def test_list_identifiable_languages_value_error(self): test_list_identifiable_languages_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/identifiable_languages') + url = self.preprocess_url(_base_url + '/v3/identifiable_languages') mock_response = '{"languages": [{"language": "language", "name": "name"}]}' responses.add(responses.GET, url, @@ -268,7 +269,7 @@ def test_list_identifiable_languages_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_identifiable_languages(**req_copy) + _service.list_identifiable_languages(**req_copy) @@ -292,7 +293,7 @@ def test_identify_all_params(self): identify() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/identify') + url = self.preprocess_url(_base_url + '/v3/identify') mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' responses.add(responses.POST, url, @@ -304,7 +305,7 @@ def test_identify_all_params(self): text = 'testString' # Invoke method - response = service.identify( + response = _service.identify( text, headers={} ) @@ -322,7 +323,7 @@ def test_identify_value_error(self): test_identify_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/identify') + url = self.preprocess_url(_base_url + '/v3/identify') mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' responses.add(responses.POST, url, @@ -340,7 +341,7 @@ def test_identify_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.identify(**req_copy) + _service.identify(**req_copy) @@ -374,7 +375,7 @@ def test_list_models_all_params(self): list_models() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/models') + url = self.preprocess_url(_base_url + '/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' responses.add(responses.GET, url, @@ -388,7 +389,7 @@ def test_list_models_all_params(self): default = True # Invoke method - response = service.list_models( + response = _service.list_models( source=source, target=target, default=default, @@ -412,7 +413,7 @@ def test_list_models_required_params(self): test_list_models_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/models') + url = self.preprocess_url(_base_url + '/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' responses.add(responses.GET, url, @@ -421,7 +422,7 @@ def test_list_models_required_params(self): status=200) # Invoke method - response = service.list_models() + response = _service.list_models() # Check for correct operation @@ -435,7 +436,7 @@ def test_list_models_value_error(self): test_list_models_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/models') + url = self.preprocess_url(_base_url + '/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' responses.add(responses.GET, url, @@ -449,7 +450,7 @@ def test_list_models_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_models(**req_copy) + _service.list_models(**req_copy) @@ -473,7 +474,7 @@ def test_create_model_all_params(self): create_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/models') + url = self.preprocess_url(_base_url + '/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.POST, url, @@ -488,7 +489,7 @@ def test_create_model_all_params(self): name = 'testString' # Invoke method - response = service.create_model( + response = _service.create_model( base_model_id, forced_glossary=forced_glossary, parallel_corpus=parallel_corpus, @@ -512,7 +513,7 @@ def test_create_model_required_params(self): test_create_model_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/models') + url = self.preprocess_url(_base_url + '/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.POST, url, @@ -524,7 +525,7 @@ def test_create_model_required_params(self): base_model_id = 'testString' # Invoke method - response = service.create_model( + response = _service.create_model( base_model_id, headers={} ) @@ -544,7 +545,7 @@ def test_create_model_value_error(self): test_create_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/models') + url = self.preprocess_url(_base_url + '/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.POST, url, @@ -562,7 +563,7 @@ def test_create_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_model(**req_copy) + _service.create_model(**req_copy) @@ -586,7 +587,7 @@ def test_delete_model_all_params(self): delete_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/models/testString') + url = self.preprocess_url(_base_url + '/v3/models/testString') mock_response = '{"status": "status"}' responses.add(responses.DELETE, url, @@ -598,7 +599,7 @@ def test_delete_model_all_params(self): model_id = 'testString' # Invoke method - response = service.delete_model( + response = _service.delete_model( model_id, headers={} ) @@ -614,7 +615,7 @@ def test_delete_model_value_error(self): test_delete_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/models/testString') + url = self.preprocess_url(_base_url + '/v3/models/testString') mock_response = '{"status": "status"}' responses.add(responses.DELETE, url, @@ -632,7 +633,7 @@ def test_delete_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_model(**req_copy) + _service.delete_model(**req_copy) @@ -656,7 +657,7 @@ def test_get_model_all_params(self): get_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/models/testString') + url = self.preprocess_url(_base_url + '/v3/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.GET, url, @@ -668,7 +669,7 @@ def test_get_model_all_params(self): model_id = 'testString' # Invoke method - response = service.get_model( + response = _service.get_model( model_id, headers={} ) @@ -684,7 +685,7 @@ def test_get_model_value_error(self): test_get_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/models/testString') + url = self.preprocess_url(_base_url + '/v3/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.GET, url, @@ -702,7 +703,7 @@ def test_get_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_model(**req_copy) + _service.get_model(**req_copy) @@ -736,8 +737,8 @@ def test_list_documents_all_params(self): list_documents() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents') - mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}]}' + url = self.preprocess_url(_base_url + '/v3/documents') + mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' responses.add(responses.GET, url, body=mock_response, @@ -745,7 +746,7 @@ def test_list_documents_all_params(self): status=200) # Invoke method - response = service.list_documents() + response = _service.list_documents() # Check for correct operation @@ -759,8 +760,8 @@ def test_list_documents_value_error(self): test_list_documents_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents') - mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}]}' + url = self.preprocess_url(_base_url + '/v3/documents') + mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' responses.add(responses.GET, url, body=mock_response, @@ -773,7 +774,7 @@ def test_list_documents_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_documents(**req_copy) + _service.list_documents(**req_copy) @@ -797,8 +798,8 @@ def test_translate_document_all_params(self): translate_document() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}' + url = self.preprocess_url(_base_url + '/v3/documents') + mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' responses.add(responses.POST, url, body=mock_response, @@ -815,7 +816,7 @@ def test_translate_document_all_params(self): document_id = 'testString' # Invoke method - response = service.translate_document( + response = _service.translate_document( file, filename=filename, file_content_type=file_content_type, @@ -837,8 +838,8 @@ def test_translate_document_required_params(self): test_translate_document_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}' + url = self.preprocess_url(_base_url + '/v3/documents') + mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' responses.add(responses.POST, url, body=mock_response, @@ -850,7 +851,7 @@ def test_translate_document_required_params(self): filename = 'testString' # Invoke method - response = service.translate_document( + response = _service.translate_document( file, filename=filename, headers={} @@ -867,8 +868,8 @@ def test_translate_document_value_error(self): test_translate_document_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}' + url = self.preprocess_url(_base_url + '/v3/documents') + mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' responses.add(responses.POST, url, body=mock_response, @@ -886,7 +887,7 @@ def test_translate_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.translate_document(**req_copy) + _service.translate_document(**req_copy) @@ -910,8 +911,8 @@ def test_get_document_status_all_params(self): get_document_status() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents/testString') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}' + url = self.preprocess_url(_base_url + '/v3/documents/testString') + mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' responses.add(responses.GET, url, body=mock_response, @@ -922,7 +923,7 @@ def test_get_document_status_all_params(self): document_id = 'testString' # Invoke method - response = service.get_document_status( + response = _service.get_document_status( document_id, headers={} ) @@ -938,8 +939,8 @@ def test_get_document_status_value_error(self): test_get_document_status_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents/testString') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00", "completed": "2019-01-01T12:00:00", "word_count": 10, "character_count": 15}' + url = self.preprocess_url(_base_url + '/v3/documents/testString') + mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' responses.add(responses.GET, url, body=mock_response, @@ -956,7 +957,7 @@ def test_get_document_status_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_document_status(**req_copy) + _service.get_document_status(**req_copy) @@ -980,7 +981,7 @@ def test_delete_document_all_params(self): delete_document() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents/testString') + url = self.preprocess_url(_base_url + '/v3/documents/testString') responses.add(responses.DELETE, url, status=204) @@ -989,7 +990,7 @@ def test_delete_document_all_params(self): document_id = 'testString' # Invoke method - response = service.delete_document( + response = _service.delete_document( document_id, headers={} ) @@ -1005,7 +1006,7 @@ def test_delete_document_value_error(self): test_delete_document_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents/testString') + url = self.preprocess_url(_base_url + '/v3/documents/testString') responses.add(responses.DELETE, url, status=204) @@ -1020,7 +1021,7 @@ def test_delete_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_document(**req_copy) + _service.delete_document(**req_copy) @@ -1044,7 +1045,7 @@ def test_get_translated_document_all_params(self): get_translated_document() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents/testString/translated_document') + url = self.preprocess_url(_base_url + '/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -1057,7 +1058,7 @@ def test_get_translated_document_all_params(self): accept = 'application/powerpoint' # Invoke method - response = service.get_translated_document( + response = _service.get_translated_document( document_id, accept=accept, headers={} @@ -1074,7 +1075,7 @@ def test_get_translated_document_required_params(self): test_get_translated_document_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents/testString/translated_document') + url = self.preprocess_url(_base_url + '/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -1086,7 +1087,7 @@ def test_get_translated_document_required_params(self): document_id = 'testString' # Invoke method - response = service.get_translated_document( + response = _service.get_translated_document( document_id, headers={} ) @@ -1102,7 +1103,7 @@ def test_get_translated_document_value_error(self): test_get_translated_document_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/documents/testString/translated_document') + url = self.preprocess_url(_base_url + '/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -1120,7 +1121,7 @@ def test_get_translated_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_translated_document(**req_copy) + _service.get_translated_document(**req_copy) @@ -1184,8 +1185,8 @@ def test_document_list_serialization(self): document_status_model['source'] = 'testString' document_status_model['detected_language_confidence'] = 0 document_status_model['target'] = 'testString' - document_status_model['created'] = '2020-01-28T18:40:40.123456Z' - document_status_model['completed'] = '2020-01-28T18:40:40.123456Z' + document_status_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + document_status_model['completed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) document_status_model['word_count'] = 38 document_status_model['character_count'] = 38 @@ -1228,8 +1229,8 @@ def test_document_status_serialization(self): document_status_model_json['source'] = 'testString' document_status_model_json['detected_language_confidence'] = 0 document_status_model_json['target'] = 'testString' - document_status_model_json['created'] = '2020-01-28T18:40:40.123456Z' - document_status_model_json['completed'] = '2020-01-28T18:40:40.123456Z' + document_status_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + document_status_model_json['completed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) document_status_model_json['word_count'] = 38 document_status_model_json['character_count'] = 38 diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index d68cb260f..eeaec42aa 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2015, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect import io import json @@ -30,12 +31,12 @@ from ibm_watson.natural_language_classifier_v1 import * -service = NaturalLanguageClassifierV1( +_service = NaturalLanguageClassifierV1( authenticator=NoAuthAuthenticator() ) -base_url = 'https://api.us-south.natural-language-classifier.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.natural-language-classifier.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: ClassifyText @@ -62,7 +63,7 @@ def test_classify_all_params(self): classify() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/classifiers/testString/classify') + url = self.preprocess_url(_base_url + '/v1/classifiers/testString/classify') mock_response = '{"classifier_id": "classifier_id", "url": "url", "text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}' responses.add(responses.POST, url, @@ -75,7 +76,7 @@ def test_classify_all_params(self): text = 'testString' # Invoke method - response = service.classify( + response = _service.classify( classifier_id, text, headers={} @@ -95,7 +96,7 @@ def test_classify_value_error(self): test_classify_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/classifiers/testString/classify') + url = self.preprocess_url(_base_url + '/v1/classifiers/testString/classify') mock_response = '{"classifier_id": "classifier_id", "url": "url", "text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}' responses.add(responses.POST, url, @@ -115,7 +116,7 @@ def test_classify_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.classify(**req_copy) + _service.classify(**req_copy) @@ -139,7 +140,7 @@ def test_classify_collection_all_params(self): classify_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/classifiers/testString/classify_collection') + url = self.preprocess_url(_base_url + '/v1/classifiers/testString/classify_collection') mock_response = '{"classifier_id": "classifier_id", "url": "url", "collection": [{"text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}]}' responses.add(responses.POST, url, @@ -156,7 +157,7 @@ def test_classify_collection_all_params(self): collection = [classify_input_model] # Invoke method - response = service.classify_collection( + response = _service.classify_collection( classifier_id, collection, headers={} @@ -176,7 +177,7 @@ def test_classify_collection_value_error(self): test_classify_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/classifiers/testString/classify_collection') + url = self.preprocess_url(_base_url + '/v1/classifiers/testString/classify_collection') mock_response = '{"classifier_id": "classifier_id", "url": "url", "collection": [{"text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}]}' responses.add(responses.POST, url, @@ -200,7 +201,7 @@ def test_classify_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.classify_collection(**req_copy) + _service.classify_collection(**req_copy) @@ -234,8 +235,8 @@ def test_create_classifier_all_params(self): create_classifier() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/classifiers') - mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00", "status_description": "status_description", "language": "language"}' + url = self.preprocess_url(_base_url + '/v1/classifiers') + mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00.000Z", "status_description": "status_description", "language": "language"}' responses.add(responses.POST, url, body=mock_response, @@ -247,7 +248,7 @@ def test_create_classifier_all_params(self): training_data = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = service.create_classifier( + response = _service.create_classifier( training_metadata, training_data, headers={} @@ -264,8 +265,8 @@ def test_create_classifier_value_error(self): test_create_classifier_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/classifiers') - mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00", "status_description": "status_description", "language": "language"}' + url = self.preprocess_url(_base_url + '/v1/classifiers') + mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00.000Z", "status_description": "status_description", "language": "language"}' responses.add(responses.POST, url, body=mock_response, @@ -284,7 +285,7 @@ def test_create_classifier_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_classifier(**req_copy) + _service.create_classifier(**req_copy) @@ -308,8 +309,8 @@ def test_list_classifiers_all_params(self): list_classifiers() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/classifiers') - mock_response = '{"classifiers": [{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00", "status_description": "status_description", "language": "language"}]}' + url = self.preprocess_url(_base_url + '/v1/classifiers') + mock_response = '{"classifiers": [{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00.000Z", "status_description": "status_description", "language": "language"}]}' responses.add(responses.GET, url, body=mock_response, @@ -317,7 +318,7 @@ def test_list_classifiers_all_params(self): status=200) # Invoke method - response = service.list_classifiers() + response = _service.list_classifiers() # Check for correct operation @@ -345,8 +346,8 @@ def test_get_classifier_all_params(self): get_classifier() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/classifiers/testString') - mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00", "status_description": "status_description", "language": "language"}' + url = self.preprocess_url(_base_url + '/v1/classifiers/testString') + mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00.000Z", "status_description": "status_description", "language": "language"}' responses.add(responses.GET, url, body=mock_response, @@ -357,7 +358,7 @@ def test_get_classifier_all_params(self): classifier_id = 'testString' # Invoke method - response = service.get_classifier( + response = _service.get_classifier( classifier_id, headers={} ) @@ -373,8 +374,8 @@ def test_get_classifier_value_error(self): test_get_classifier_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/classifiers/testString') - mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00", "status_description": "status_description", "language": "language"}' + url = self.preprocess_url(_base_url + '/v1/classifiers/testString') + mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00.000Z", "status_description": "status_description", "language": "language"}' responses.add(responses.GET, url, body=mock_response, @@ -391,7 +392,7 @@ def test_get_classifier_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_classifier(**req_copy) + _service.get_classifier(**req_copy) @@ -415,7 +416,7 @@ def test_delete_classifier_all_params(self): delete_classifier() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/classifiers/testString') + url = self.preprocess_url(_base_url + '/v1/classifiers/testString') responses.add(responses.DELETE, url, status=200) @@ -424,7 +425,7 @@ def test_delete_classifier_all_params(self): classifier_id = 'testString' # Invoke method - response = service.delete_classifier( + response = _service.delete_classifier( classifier_id, headers={} ) @@ -440,7 +441,7 @@ def test_delete_classifier_value_error(self): test_delete_classifier_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/classifiers/testString') + url = self.preprocess_url(_base_url + '/v1/classifiers/testString') responses.add(responses.DELETE, url, status=200) @@ -455,7 +456,7 @@ def test_delete_classifier_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_classifier(**req_copy) + _service.delete_classifier(**req_copy) @@ -596,7 +597,7 @@ def test_classifier_serialization(self): classifier_model_json['url'] = 'testString' classifier_model_json['status'] = 'Non Existent' classifier_model_json['classifier_id'] = 'testString' - classifier_model_json['created'] = '2020-01-28T18:40:40.123456Z' + classifier_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) classifier_model_json['status_description'] = 'testString' classifier_model_json['language'] = 'testString' @@ -632,7 +633,7 @@ def test_classifier_list_serialization(self): classifier_model['url'] = 'testString' classifier_model['status'] = 'Non Existent' classifier_model['classifier_id'] = 'testString' - classifier_model['created'] = '2020-01-28T18:40:40.123456Z' + classifier_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) classifier_model['status_description'] = 'testString' classifier_model['language'] = 'testString' diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index 5b052a010..d005d1fc3 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2018, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -29,13 +29,13 @@ version = 'testString' -service = PersonalityInsightsV3( +_service = PersonalityInsightsV3( authenticator=NoAuthAuthenticator(), version=version ) -base_url = 'https://api.us-south.personality-insights.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.personality-insights.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: Methods @@ -62,7 +62,7 @@ def test_profile_all_params(self): profile() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/profile') + url = self.preprocess_url(_base_url + '/v3/profile') mock_response = '{"processed_language": "ar", "word_count": 10, "word_count_message": "word_count_message", "personality": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "needs": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "values": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "behavior": [{"trait_id": "trait_id", "name": "name", "category": "category", "percentage": 10}], "consumption_preferences": [{"consumption_preference_category_id": "consumption_preference_category_id", "name": "name", "consumption_preferences": [{"consumption_preference_id": "consumption_preference_id", "name": "name", "score": 0.0}]}], "warnings": [{"warning_id": "WORD_COUNT_MESSAGE", "message": "message"}]}' responses.add(responses.POST, url, @@ -97,7 +97,7 @@ def test_profile_all_params(self): consumption_preferences = True # Invoke method - response = service.profile( + response = _service.profile( content, accept, content_type=content_type, @@ -127,7 +127,7 @@ def test_profile_required_params(self): test_profile_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/profile') + url = self.preprocess_url(_base_url + '/v3/profile') mock_response = '{"processed_language": "ar", "word_count": 10, "word_count_message": "word_count_message", "personality": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "needs": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "values": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "behavior": [{"trait_id": "trait_id", "name": "name", "category": "category", "percentage": 10}], "consumption_preferences": [{"consumption_preference_category_id": "consumption_preference_category_id", "name": "name", "consumption_preferences": [{"consumption_preference_id": "consumption_preference_id", "name": "name", "score": 0.0}]}], "warnings": [{"warning_id": "WORD_COUNT_MESSAGE", "message": "message"}]}' responses.add(responses.POST, url, @@ -156,7 +156,7 @@ def test_profile_required_params(self): accept = 'application/json' # Invoke method - response = service.profile( + response = _service.profile( content, accept, headers={} @@ -174,7 +174,7 @@ def test_profile_value_error(self): test_profile_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/profile') + url = self.preprocess_url(_base_url + '/v3/profile') mock_response = '{"processed_language": "ar", "word_count": 10, "word_count_message": "word_count_message", "personality": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "needs": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "values": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "behavior": [{"trait_id": "trait_id", "name": "name", "category": "category", "percentage": 10}], "consumption_preferences": [{"consumption_preference_category_id": "consumption_preference_category_id", "name": "name", "consumption_preferences": [{"consumption_preference_id": "consumption_preference_id", "name": "name", "score": 0.0}]}], "warnings": [{"warning_id": "WORD_COUNT_MESSAGE", "message": "message"}]}' responses.add(responses.POST, url, @@ -210,7 +210,7 @@ def test_profile_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.profile(**req_copy) + _service.profile(**req_copy) diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index 6f5f5843b..cb398a571 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2018, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -29,13 +29,13 @@ version = 'testString' -service = ToneAnalyzerV3( +_service = ToneAnalyzerV3( authenticator=NoAuthAuthenticator(), version=version ) -base_url = 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: Methods @@ -62,7 +62,7 @@ def test_tone_all_params(self): tone() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/tone') + url = self.preprocess_url(_base_url + '/v3/tone') mock_response = '{"document_tone": {"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "warning": "warning"}, "sentences_tone": [{"sentence_id": 11, "text": "text", "tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "input_from": 10, "input_to": 8}]}' responses.add(responses.POST, url, @@ -83,7 +83,7 @@ def test_tone_all_params(self): accept_language = 'ar' # Invoke method - response = service.tone( + response = _service.tone( tone_input, content_type=content_type, sentences=sentences, @@ -110,7 +110,7 @@ def test_tone_required_params(self): test_tone_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/tone') + url = self.preprocess_url(_base_url + '/v3/tone') mock_response = '{"document_tone": {"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "warning": "warning"}, "sentences_tone": [{"sentence_id": 11, "text": "text", "tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "input_from": 10, "input_to": 8}]}' responses.add(responses.POST, url, @@ -126,7 +126,7 @@ def test_tone_required_params(self): tone_input = tone_input_model # Invoke method - response = service.tone( + response = _service.tone( tone_input, headers={} ) @@ -143,7 +143,7 @@ def test_tone_value_error(self): test_tone_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/tone') + url = self.preprocess_url(_base_url + '/v3/tone') mock_response = '{"document_tone": {"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "warning": "warning"}, "sentences_tone": [{"sentence_id": 11, "text": "text", "tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "input_from": 10, "input_to": 8}]}' responses.add(responses.POST, url, @@ -165,7 +165,7 @@ def test_tone_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.tone(**req_copy) + _service.tone(**req_copy) @@ -189,7 +189,7 @@ def test_tone_chat_all_params(self): tone_chat() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/tone_chat') + url = self.preprocess_url(_base_url + '/v3/tone_chat') mock_response = '{"utterances_tone": [{"utterance_id": 12, "utterance_text": "utterance_text", "tones": [{"score": 5, "tone_id": "excited", "tone_name": "tone_name"}], "error": "error"}], "warning": "warning"}' responses.add(responses.POST, url, @@ -208,7 +208,7 @@ def test_tone_chat_all_params(self): accept_language = 'ar' # Invoke method - response = service.tone_chat( + response = _service.tone_chat( utterances, content_language=content_language, accept_language=accept_language, @@ -229,7 +229,7 @@ def test_tone_chat_required_params(self): test_tone_chat_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/tone_chat') + url = self.preprocess_url(_base_url + '/v3/tone_chat') mock_response = '{"utterances_tone": [{"utterance_id": 12, "utterance_text": "utterance_text", "tones": [{"score": 5, "tone_id": "excited", "tone_name": "tone_name"}], "error": "error"}], "warning": "warning"}' responses.add(responses.POST, url, @@ -246,7 +246,7 @@ def test_tone_chat_required_params(self): utterances = [utterance_model] # Invoke method - response = service.tone_chat( + response = _service.tone_chat( utterances, headers={} ) @@ -265,7 +265,7 @@ def test_tone_chat_value_error(self): test_tone_chat_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/tone_chat') + url = self.preprocess_url(_base_url + '/v3/tone_chat') mock_response = '{"utterances_tone": [{"utterance_id": 12, "utterance_text": "utterance_text", "tones": [{"score": 5, "tone_id": "excited", "tone_name": "tone_name"}], "error": "error"}], "warning": "warning"}' responses.add(responses.POST, url, @@ -288,7 +288,7 @@ def test_tone_chat_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.tone_chat(**req_copy) + _service.tone_chat(**req_copy) diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index 5ebc9de48..ae9e5f132 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2020. +# (C) Copyright IBM Corp. 2016, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect import io import json @@ -32,13 +33,13 @@ version = 'testString' -service = VisualRecognitionV3( +_service = VisualRecognitionV3( authenticator=NoAuthAuthenticator(), version=version ) -base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: General @@ -65,7 +66,7 @@ def test_classify_all_params(self): classify() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classify') + url = self.preprocess_url(_base_url + '/v3/classify') mock_response = '{"custom_classes": 14, "images_processed": 16, "images": [{"source_url": "source_url", "resolved_url": "resolved_url", "image": "image", "error": {"code": 4, "description": "description", "error_id": "error_id"}, "classifiers": [{"name": "name", "classifier_id": "classifier_id", "classes": [{"class": "class_", "score": 0, "type_hierarchy": "type_hierarchy"}]}]}], "warnings": [{"warning_id": "warning_id", "description": "description"}]}' responses.add(responses.POST, url, @@ -84,7 +85,7 @@ def test_classify_all_params(self): accept_language = 'en' # Invoke method - response = service.classify( + response = _service.classify( images_file=images_file, images_filename=images_filename, images_file_content_type=images_file_content_type, @@ -107,7 +108,7 @@ def test_classify_required_params(self): test_classify_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classify') + url = self.preprocess_url(_base_url + '/v3/classify') mock_response = '{"custom_classes": 14, "images_processed": 16, "images": [{"source_url": "source_url", "resolved_url": "resolved_url", "image": "image", "error": {"code": 4, "description": "description", "error_id": "error_id"}, "classifiers": [{"name": "name", "classifier_id": "classifier_id", "classes": [{"class": "class_", "score": 0, "type_hierarchy": "type_hierarchy"}]}]}], "warnings": [{"warning_id": "warning_id", "description": "description"}]}' responses.add(responses.POST, url, @@ -116,7 +117,7 @@ def test_classify_required_params(self): status=200) # Invoke method - response = service.classify() + response = _service.classify() # Check for correct operation @@ -130,7 +131,7 @@ def test_classify_value_error(self): test_classify_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classify') + url = self.preprocess_url(_base_url + '/v3/classify') mock_response = '{"custom_classes": 14, "images_processed": 16, "images": [{"source_url": "source_url", "resolved_url": "resolved_url", "image": "image", "error": {"code": 4, "description": "description", "error_id": "error_id"}, "classifiers": [{"name": "name", "classifier_id": "classifier_id", "classes": [{"class": "class_", "score": 0, "type_hierarchy": "type_hierarchy"}]}]}], "warnings": [{"warning_id": "warning_id", "description": "description"}]}' responses.add(responses.POST, url, @@ -144,7 +145,7 @@ def test_classify_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.classify(**req_copy) + _service.classify(**req_copy) @@ -178,8 +179,8 @@ def test_create_classifier_all_params(self): create_classifier() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v3/classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -193,7 +194,7 @@ def test_create_classifier_all_params(self): negative_examples_filename = 'testString' # Invoke method - response = service.create_classifier( + response = _service.create_classifier( name, positive_examples, negative_examples=negative_examples, @@ -212,8 +213,8 @@ def test_create_classifier_required_params(self): test_create_classifier_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v3/classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -225,7 +226,7 @@ def test_create_classifier_required_params(self): positive_examples = { 'key': io.BytesIO(b'This is a mock file.').getvalue() } # Invoke method - response = service.create_classifier( + response = _service.create_classifier( name, positive_examples, headers={} @@ -242,8 +243,8 @@ def test_create_classifier_value_error(self): test_create_classifier_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v3/classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -262,7 +263,7 @@ def test_create_classifier_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_classifier(**req_copy) + _service.create_classifier(**req_copy) @@ -286,8 +287,8 @@ def test_list_classifiers_all_params(self): list_classifiers() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers') - mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v3/classifiers') + mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -298,7 +299,7 @@ def test_list_classifiers_all_params(self): verbose = True # Invoke method - response = service.list_classifiers( + response = _service.list_classifiers( verbose=verbose, headers={} ) @@ -318,8 +319,8 @@ def test_list_classifiers_required_params(self): test_list_classifiers_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers') - mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v3/classifiers') + mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -327,7 +328,7 @@ def test_list_classifiers_required_params(self): status=200) # Invoke method - response = service.list_classifiers() + response = _service.list_classifiers() # Check for correct operation @@ -341,8 +342,8 @@ def test_list_classifiers_value_error(self): test_list_classifiers_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers') - mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v3/classifiers') + mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -355,7 +356,7 @@ def test_list_classifiers_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_classifiers(**req_copy) + _service.list_classifiers(**req_copy) @@ -379,8 +380,8 @@ def test_get_classifier_all_params(self): get_classifier() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers/testString') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v3/classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -391,7 +392,7 @@ def test_get_classifier_all_params(self): classifier_id = 'testString' # Invoke method - response = service.get_classifier( + response = _service.get_classifier( classifier_id, headers={} ) @@ -407,8 +408,8 @@ def test_get_classifier_value_error(self): test_get_classifier_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers/testString') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v3/classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -425,7 +426,7 @@ def test_get_classifier_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_classifier(**req_copy) + _service.get_classifier(**req_copy) @@ -449,8 +450,8 @@ def test_update_classifier_all_params(self): update_classifier() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers/testString') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v3/classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -464,7 +465,7 @@ def test_update_classifier_all_params(self): negative_examples_filename = 'testString' # Invoke method - response = service.update_classifier( + response = _service.update_classifier( classifier_id, positive_examples=positive_examples, negative_examples=negative_examples, @@ -483,8 +484,8 @@ def test_update_classifier_required_params(self): test_update_classifier_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers/testString') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v3/classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -495,7 +496,7 @@ def test_update_classifier_required_params(self): classifier_id = 'testString' # Invoke method - response = service.update_classifier( + response = _service.update_classifier( classifier_id, headers={} ) @@ -511,8 +512,8 @@ def test_update_classifier_value_error(self): test_update_classifier_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers/testString') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}' + url = self.preprocess_url(_base_url + '/v3/classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -529,7 +530,7 @@ def test_update_classifier_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_classifier(**req_copy) + _service.update_classifier(**req_copy) @@ -553,7 +554,7 @@ def test_delete_classifier_all_params(self): delete_classifier() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers/testString') + url = self.preprocess_url(_base_url + '/v3/classifiers/testString') responses.add(responses.DELETE, url, status=200) @@ -562,7 +563,7 @@ def test_delete_classifier_all_params(self): classifier_id = 'testString' # Invoke method - response = service.delete_classifier( + response = _service.delete_classifier( classifier_id, headers={} ) @@ -578,7 +579,7 @@ def test_delete_classifier_value_error(self): test_delete_classifier_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers/testString') + url = self.preprocess_url(_base_url + '/v3/classifiers/testString') responses.add(responses.DELETE, url, status=200) @@ -593,7 +594,7 @@ def test_delete_classifier_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_classifier(**req_copy) + _service.delete_classifier(**req_copy) @@ -627,7 +628,7 @@ def test_get_core_ml_model_all_params(self): get_core_ml_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers/testString/core_ml_model') + url = self.preprocess_url(_base_url + '/v3/classifiers/testString/core_ml_model') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -639,7 +640,7 @@ def test_get_core_ml_model_all_params(self): classifier_id = 'testString' # Invoke method - response = service.get_core_ml_model( + response = _service.get_core_ml_model( classifier_id, headers={} ) @@ -655,7 +656,7 @@ def test_get_core_ml_model_value_error(self): test_get_core_ml_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/classifiers/testString/core_ml_model') + url = self.preprocess_url(_base_url + '/v3/classifiers/testString/core_ml_model') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -673,7 +674,7 @@ def test_get_core_ml_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_core_ml_model(**req_copy) + _service.get_core_ml_model(**req_copy) @@ -707,7 +708,7 @@ def test_delete_user_data_all_params(self): delete_user_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/user_data') + url = self.preprocess_url(_base_url + '/v3/user_data') responses.add(responses.DELETE, url, status=202) @@ -716,7 +717,7 @@ def test_delete_user_data_all_params(self): customer_id = 'testString' # Invoke method - response = service.delete_user_data( + response = _service.delete_user_data( customer_id, headers={} ) @@ -736,7 +737,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v3/user_data') + url = self.preprocess_url(_base_url + '/v3/user_data') responses.add(responses.DELETE, url, status=202) @@ -751,7 +752,7 @@ def test_delete_user_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_user_data(**req_copy) + _service.delete_user_data(**req_copy) @@ -958,10 +959,10 @@ def test_classifier_serialization(self): classifier_model_json['status'] = 'ready' classifier_model_json['core_ml_enabled'] = True classifier_model_json['explanation'] = 'testString' - classifier_model_json['created'] = '2020-01-28T18:40:40.123456Z' + classifier_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) classifier_model_json['classes'] = [class_model] - classifier_model_json['retrained'] = '2020-01-28T18:40:40.123456Z' - classifier_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + classifier_model_json['retrained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifier_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of Classifier by calling from_dict on the json representation classifier_model = Classifier.from_dict(classifier_model_json) @@ -1038,10 +1039,10 @@ def test_classifiers_serialization(self): classifier_model['status'] = 'ready' classifier_model['core_ml_enabled'] = True classifier_model['explanation'] = 'testString' - classifier_model['created'] = '2020-01-28T18:40:40.123456Z' + classifier_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) classifier_model['classes'] = [class_model] - classifier_model['retrained'] = '2020-01-28T18:40:40.123456Z' - classifier_model['updated'] = '2020-01-28T18:40:40.123456Z' + classifier_model['retrained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifier_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a json representation of a Classifiers model classifiers_model_json = {} diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index a3e28a064..f6d177cce 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2019, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,7 +19,8 @@ from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator -from ibm_cloud_sdk_core.utils import date_to_string +from ibm_cloud_sdk_core.utils import date_to_string, string_to_date +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect import io import json @@ -33,13 +34,13 @@ version = 'testString' -service = VisualRecognitionV4( +_service = VisualRecognitionV4( authenticator=NoAuthAuthenticator(), version=version ) -base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: Analysis @@ -66,7 +67,7 @@ def test_analyze_all_params(self): analyze() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/analyze') + url = self.preprocess_url(_base_url + '/v4/analyze') mock_response = '{"images": [{"source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "objects": {"collections": [{"collection_id": "collection_id", "objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}, "score": 5}]}]}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}]}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' responses.add(responses.POST, url, @@ -88,7 +89,7 @@ def test_analyze_all_params(self): threshold = 0.15 # Invoke method - response = service.analyze( + response = _service.analyze( collection_ids, features, images_file=images_file, @@ -108,7 +109,7 @@ def test_analyze_required_params(self): test_analyze_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/analyze') + url = self.preprocess_url(_base_url + '/v4/analyze') mock_response = '{"images": [{"source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "objects": {"collections": [{"collection_id": "collection_id", "objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}, "score": 5}]}]}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}]}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' responses.add(responses.POST, url, @@ -121,7 +122,7 @@ def test_analyze_required_params(self): features = ['objects'] # Invoke method - response = service.analyze( + response = _service.analyze( collection_ids, features, headers={} @@ -138,7 +139,7 @@ def test_analyze_value_error(self): test_analyze_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/analyze') + url = self.preprocess_url(_base_url + '/v4/analyze') mock_response = '{"images": [{"source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "objects": {"collections": [{"collection_id": "collection_id", "objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}, "score": 5}]}]}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}]}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' responses.add(responses.POST, url, @@ -158,7 +159,7 @@ def test_analyze_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.analyze(**req_copy) + _service.analyze(**req_copy) @@ -192,8 +193,8 @@ def test_create_collection_all_params(self): create_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + url = self.preprocess_url(_base_url + '/v4/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' responses.add(responses.POST, url, body=mock_response, @@ -219,7 +220,7 @@ def test_create_collection_all_params(self): training_status = training_status_model # Invoke method - response = service.create_collection( + response = _service.create_collection( name=name, description=description, training_status=training_status, @@ -242,8 +243,8 @@ def test_create_collection_value_error(self): test_create_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + url = self.preprocess_url(_base_url + '/v4/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' responses.add(responses.POST, url, body=mock_response, @@ -274,7 +275,7 @@ def test_create_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_collection(**req_copy) + _service.create_collection(**req_copy) @@ -298,8 +299,8 @@ def test_list_collections_all_params(self): list_collections() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}]}' + url = self.preprocess_url(_base_url + '/v4/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -307,7 +308,7 @@ def test_list_collections_all_params(self): status=200) # Invoke method - response = service.list_collections() + response = _service.list_collections() # Check for correct operation @@ -321,8 +322,8 @@ def test_list_collections_value_error(self): test_list_collections_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}]}' + url = self.preprocess_url(_base_url + '/v4/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -335,7 +336,7 @@ def test_list_collections_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_collections(**req_copy) + _service.list_collections(**req_copy) @@ -359,8 +360,8 @@ def test_get_collection_all_params(self): get_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + url = self.preprocess_url(_base_url + '/v4/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' responses.add(responses.GET, url, body=mock_response, @@ -371,7 +372,7 @@ def test_get_collection_all_params(self): collection_id = 'testString' # Invoke method - response = service.get_collection( + response = _service.get_collection( collection_id, headers={} ) @@ -387,8 +388,8 @@ def test_get_collection_value_error(self): test_get_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + url = self.preprocess_url(_base_url + '/v4/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' responses.add(responses.GET, url, body=mock_response, @@ -405,7 +406,7 @@ def test_get_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_collection(**req_copy) + _service.get_collection(**req_copy) @@ -429,8 +430,8 @@ def test_update_collection_all_params(self): update_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + url = self.preprocess_url(_base_url + '/v4/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' responses.add(responses.POST, url, body=mock_response, @@ -457,7 +458,7 @@ def test_update_collection_all_params(self): training_status = training_status_model # Invoke method - response = service.update_collection( + response = _service.update_collection( collection_id, name=name, description=description, @@ -481,8 +482,8 @@ def test_update_collection_required_params(self): test_update_collection_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + url = self.preprocess_url(_base_url + '/v4/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' responses.add(responses.POST, url, body=mock_response, @@ -493,7 +494,7 @@ def test_update_collection_required_params(self): collection_id = 'testString' # Invoke method - response = service.update_collection( + response = _service.update_collection( collection_id, headers={} ) @@ -509,8 +510,8 @@ def test_update_collection_value_error(self): test_update_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + url = self.preprocess_url(_base_url + '/v4/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' responses.add(responses.POST, url, body=mock_response, @@ -527,7 +528,7 @@ def test_update_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_collection(**req_copy) + _service.update_collection(**req_copy) @@ -551,7 +552,7 @@ def test_delete_collection_all_params(self): delete_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString') + url = self.preprocess_url(_base_url + '/v4/collections/testString') responses.add(responses.DELETE, url, status=200) @@ -560,7 +561,7 @@ def test_delete_collection_all_params(self): collection_id = 'testString' # Invoke method - response = service.delete_collection( + response = _service.delete_collection( collection_id, headers={} ) @@ -576,7 +577,7 @@ def test_delete_collection_value_error(self): test_delete_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString') + url = self.preprocess_url(_base_url + '/v4/collections/testString') responses.add(responses.DELETE, url, status=200) @@ -591,7 +592,7 @@ def test_delete_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_collection(**req_copy) + _service.delete_collection(**req_copy) @@ -615,7 +616,7 @@ def test_get_model_file_all_params(self): get_model_file() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/model') + url = self.preprocess_url(_base_url + '/v4/collections/testString/model') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -629,7 +630,7 @@ def test_get_model_file_all_params(self): model_format = 'rscnn' # Invoke method - response = service.get_model_file( + response = _service.get_model_file( collection_id, feature, model_format, @@ -652,7 +653,7 @@ def test_get_model_file_value_error(self): test_get_model_file_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/model') + url = self.preprocess_url(_base_url + '/v4/collections/testString/model') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -674,7 +675,7 @@ def test_get_model_file_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_model_file(**req_copy) + _service.get_model_file(**req_copy) @@ -708,8 +709,8 @@ def test_add_images_all_params(self): add_images() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images') - mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00", "created": "2019-01-01T12:00:00", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' + url = self.preprocess_url(_base_url + '/v4/collections/testString/images') + mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z", "created": "2019-01-01T12:00:00.000Z", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' responses.add(responses.POST, url, body=mock_response, @@ -726,10 +727,10 @@ def test_add_images_all_params(self): collection_id = 'testString' images_file = [file_with_metadata_model] image_url = ['testString'] - training_data = 'testString' + training_data = '{"objects":[{"object":"2018-Fit","location":{"left":33,"top":8,"width":760,"height":419}}]}' # Invoke method - response = service.add_images( + response = _service.add_images( collection_id, images_file=images_file, image_url=image_url, @@ -748,8 +749,8 @@ def test_add_images_required_params(self): test_add_images_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images') - mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00", "created": "2019-01-01T12:00:00", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' + url = self.preprocess_url(_base_url + '/v4/collections/testString/images') + mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z", "created": "2019-01-01T12:00:00.000Z", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' responses.add(responses.POST, url, body=mock_response, @@ -760,7 +761,7 @@ def test_add_images_required_params(self): collection_id = 'testString' # Invoke method - response = service.add_images( + response = _service.add_images( collection_id, headers={} ) @@ -776,8 +777,8 @@ def test_add_images_value_error(self): test_add_images_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images') - mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00", "created": "2019-01-01T12:00:00", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' + url = self.preprocess_url(_base_url + '/v4/collections/testString/images') + mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z", "created": "2019-01-01T12:00:00.000Z", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' responses.add(responses.POST, url, body=mock_response, @@ -794,7 +795,7 @@ def test_add_images_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_images(**req_copy) + _service.add_images(**req_copy) @@ -818,8 +819,8 @@ def test_list_images_all_params(self): list_images() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images') - mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v4/collections/testString/images') + mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -830,7 +831,7 @@ def test_list_images_all_params(self): collection_id = 'testString' # Invoke method - response = service.list_images( + response = _service.list_images( collection_id, headers={} ) @@ -846,8 +847,8 @@ def test_list_images_value_error(self): test_list_images_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images') - mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v4/collections/testString/images') + mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -864,7 +865,7 @@ def test_list_images_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_images(**req_copy) + _service.list_images(**req_copy) @@ -888,8 +889,8 @@ def test_get_image_details_all_params(self): get_image_details() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString') - mock_response = '{"image_id": "image_id", "updated": "2019-01-01T12:00:00", "created": "2019-01-01T12:00:00", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}' + url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString') + mock_response = '{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z", "created": "2019-01-01T12:00:00.000Z", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}' responses.add(responses.GET, url, body=mock_response, @@ -901,7 +902,7 @@ def test_get_image_details_all_params(self): image_id = 'testString' # Invoke method - response = service.get_image_details( + response = _service.get_image_details( collection_id, image_id, headers={} @@ -918,8 +919,8 @@ def test_get_image_details_value_error(self): test_get_image_details_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString') - mock_response = '{"image_id": "image_id", "updated": "2019-01-01T12:00:00", "created": "2019-01-01T12:00:00", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}' + url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString') + mock_response = '{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z", "created": "2019-01-01T12:00:00.000Z", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}' responses.add(responses.GET, url, body=mock_response, @@ -938,7 +939,7 @@ def test_get_image_details_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_image_details(**req_copy) + _service.get_image_details(**req_copy) @@ -962,7 +963,7 @@ def test_delete_image_all_params(self): delete_image() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString') + url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString') responses.add(responses.DELETE, url, status=200) @@ -972,7 +973,7 @@ def test_delete_image_all_params(self): image_id = 'testString' # Invoke method - response = service.delete_image( + response = _service.delete_image( collection_id, image_id, headers={} @@ -989,7 +990,7 @@ def test_delete_image_value_error(self): test_delete_image_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString') + url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString') responses.add(responses.DELETE, url, status=200) @@ -1006,7 +1007,7 @@ def test_delete_image_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_image(**req_copy) + _service.delete_image(**req_copy) @@ -1030,7 +1031,7 @@ def test_get_jpeg_image_all_params(self): get_jpeg_image() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString/jpeg') + url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString/jpeg') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -1044,7 +1045,7 @@ def test_get_jpeg_image_all_params(self): size = 'full' # Invoke method - response = service.get_jpeg_image( + response = _service.get_jpeg_image( collection_id, image_id, size=size, @@ -1066,7 +1067,7 @@ def test_get_jpeg_image_required_params(self): test_get_jpeg_image_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString/jpeg') + url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString/jpeg') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -1079,7 +1080,7 @@ def test_get_jpeg_image_required_params(self): image_id = 'testString' # Invoke method - response = service.get_jpeg_image( + response = _service.get_jpeg_image( collection_id, image_id, headers={} @@ -1096,7 +1097,7 @@ def test_get_jpeg_image_value_error(self): test_get_jpeg_image_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString/jpeg') + url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString/jpeg') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -1116,7 +1117,7 @@ def test_get_jpeg_image_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_jpeg_image(**req_copy) + _service.get_jpeg_image(**req_copy) @@ -1150,7 +1151,7 @@ def test_list_object_metadata_all_params(self): list_object_metadata() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/objects') + url = self.preprocess_url(_base_url + '/v4/collections/testString/objects') mock_response = '{"object_count": 12, "objects": [{"object": "object", "count": 5}]}' responses.add(responses.GET, url, @@ -1162,7 +1163,7 @@ def test_list_object_metadata_all_params(self): collection_id = 'testString' # Invoke method - response = service.list_object_metadata( + response = _service.list_object_metadata( collection_id, headers={} ) @@ -1178,7 +1179,7 @@ def test_list_object_metadata_value_error(self): test_list_object_metadata_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/objects') + url = self.preprocess_url(_base_url + '/v4/collections/testString/objects') mock_response = '{"object_count": 12, "objects": [{"object": "object", "count": 5}]}' responses.add(responses.GET, url, @@ -1196,7 +1197,7 @@ def test_list_object_metadata_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_object_metadata(**req_copy) + _service.list_object_metadata(**req_copy) @@ -1220,7 +1221,7 @@ def test_update_object_metadata_all_params(self): update_object_metadata() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') + url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') mock_response = '{"object": "object", "count": 5}' responses.add(responses.POST, url, @@ -1234,7 +1235,7 @@ def test_update_object_metadata_all_params(self): new_object = 'testString' # Invoke method - response = service.update_object_metadata( + response = _service.update_object_metadata( collection_id, object, new_object, @@ -1255,7 +1256,7 @@ def test_update_object_metadata_value_error(self): test_update_object_metadata_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') + url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') mock_response = '{"object": "object", "count": 5}' responses.add(responses.POST, url, @@ -1277,7 +1278,7 @@ def test_update_object_metadata_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_object_metadata(**req_copy) + _service.update_object_metadata(**req_copy) @@ -1301,7 +1302,7 @@ def test_get_object_metadata_all_params(self): get_object_metadata() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') + url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') mock_response = '{"object": "object", "count": 5}' responses.add(responses.GET, url, @@ -1314,7 +1315,7 @@ def test_get_object_metadata_all_params(self): object = 'testString' # Invoke method - response = service.get_object_metadata( + response = _service.get_object_metadata( collection_id, object, headers={} @@ -1331,7 +1332,7 @@ def test_get_object_metadata_value_error(self): test_get_object_metadata_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') + url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') mock_response = '{"object": "object", "count": 5}' responses.add(responses.GET, url, @@ -1351,7 +1352,7 @@ def test_get_object_metadata_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_object_metadata(**req_copy) + _service.get_object_metadata(**req_copy) @@ -1375,7 +1376,7 @@ def test_delete_object_all_params(self): delete_object() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') + url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') responses.add(responses.DELETE, url, status=200) @@ -1385,7 +1386,7 @@ def test_delete_object_all_params(self): object = 'testString' # Invoke method - response = service.delete_object( + response = _service.delete_object( collection_id, object, headers={} @@ -1402,7 +1403,7 @@ def test_delete_object_value_error(self): test_delete_object_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/objects/testString') + url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') responses.add(responses.DELETE, url, status=200) @@ -1419,7 +1420,7 @@ def test_delete_object_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_object(**req_copy) + _service.delete_object(**req_copy) @@ -1453,8 +1454,8 @@ def test_train_all_params(self): train() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/train') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + url = self.preprocess_url(_base_url + '/v4/collections/testString/train') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' responses.add(responses.POST, url, body=mock_response, @@ -1465,7 +1466,7 @@ def test_train_all_params(self): collection_id = 'testString' # Invoke method - response = service.train( + response = _service.train( collection_id, headers={} ) @@ -1481,8 +1482,8 @@ def test_train_value_error(self): test_train_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/train') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' + url = self.preprocess_url(_base_url + '/v4/collections/testString/train') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' responses.add(responses.POST, url, body=mock_response, @@ -1499,7 +1500,7 @@ def test_train_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.train(**req_copy) + _service.train(**req_copy) @@ -1523,7 +1524,7 @@ def test_add_image_training_data_all_params(self): add_image_training_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString/training_data') + url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString/training_data') mock_response = '{"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}' responses.add(responses.POST, url, @@ -1549,7 +1550,7 @@ def test_add_image_training_data_all_params(self): objects = [training_data_object_model] # Invoke method - response = service.add_image_training_data( + response = _service.add_image_training_data( collection_id, image_id, objects=objects, @@ -1570,7 +1571,7 @@ def test_add_image_training_data_value_error(self): test_add_image_training_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/collections/testString/images/testString/training_data') + url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString/training_data') mock_response = '{"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}' responses.add(responses.POST, url, @@ -1603,7 +1604,7 @@ def test_add_image_training_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_image_training_data(**req_copy) + _service.add_image_training_data(**req_copy) @@ -1627,8 +1628,8 @@ def test_get_training_usage_all_params(self): get_training_usage() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/training_usage') - mock_response = '{"start_time": "2019-01-01T12:00:00", "end_time": "2019-01-01T12:00:00", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00", "status": "failed", "image_count": 11}]}' + url = self.preprocess_url(_base_url + '/v4/training_usage') + mock_response = '{"start_time": "2019-01-01T12:00:00.000Z", "end_time": "2019-01-01T12:00:00.000Z", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00.000Z", "status": "failed", "image_count": 11}]}' responses.add(responses.GET, url, body=mock_response, @@ -1636,11 +1637,11 @@ def test_get_training_usage_all_params(self): status=200) # Set up parameter values - start_time = date.fromtimestamp(1580236840.123456) - end_time = date.fromtimestamp(1580236840.123456) + start_time = string_to_date('2019-01-01') + end_time = string_to_date('2019-01-01') # Invoke method - response = service.get_training_usage( + response = _service.get_training_usage( start_time=start_time, end_time=end_time, headers={} @@ -1662,8 +1663,8 @@ def test_get_training_usage_required_params(self): test_get_training_usage_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/training_usage') - mock_response = '{"start_time": "2019-01-01T12:00:00", "end_time": "2019-01-01T12:00:00", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00", "status": "failed", "image_count": 11}]}' + url = self.preprocess_url(_base_url + '/v4/training_usage') + mock_response = '{"start_time": "2019-01-01T12:00:00.000Z", "end_time": "2019-01-01T12:00:00.000Z", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00.000Z", "status": "failed", "image_count": 11}]}' responses.add(responses.GET, url, body=mock_response, @@ -1671,7 +1672,7 @@ def test_get_training_usage_required_params(self): status=200) # Invoke method - response = service.get_training_usage() + response = _service.get_training_usage() # Check for correct operation @@ -1685,8 +1686,8 @@ def test_get_training_usage_value_error(self): test_get_training_usage_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/training_usage') - mock_response = '{"start_time": "2019-01-01T12:00:00", "end_time": "2019-01-01T12:00:00", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00", "status": "failed", "image_count": 11}]}' + url = self.preprocess_url(_base_url + '/v4/training_usage') + mock_response = '{"start_time": "2019-01-01T12:00:00.000Z", "end_time": "2019-01-01T12:00:00.000Z", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00.000Z", "status": "failed", "image_count": 11}]}' responses.add(responses.GET, url, body=mock_response, @@ -1699,7 +1700,7 @@ def test_get_training_usage_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_training_usage(**req_copy) + _service.get_training_usage(**req_copy) @@ -1733,7 +1734,7 @@ def test_delete_user_data_all_params(self): delete_user_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/user_data') + url = self.preprocess_url(_base_url + '/v4/user_data') responses.add(responses.DELETE, url, status=202) @@ -1742,7 +1743,7 @@ def test_delete_user_data_all_params(self): customer_id = 'testString' # Invoke method - response = service.delete_user_data( + response = _service.delete_user_data( customer_id, headers={} ) @@ -1762,7 +1763,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v4/user_data') + url = self.preprocess_url(_base_url + '/v4/user_data') responses.add(responses.DELETE, url, status=202) @@ -1777,7 +1778,7 @@ def test_delete_user_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_user_data(**req_copy) + _service.delete_user_data(**req_copy) @@ -1902,8 +1903,8 @@ def test_collection_serialization(self): collection_model_json['collection_id'] = 'testString' collection_model_json['name'] = 'testString' collection_model_json['description'] = 'testString' - collection_model_json['created'] = '2020-01-28T18:40:40.123456Z' - collection_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + collection_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + collection_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) collection_model_json['image_count'] = 38 collection_model_json['training_status'] = collection_training_status_model @@ -2031,8 +2032,8 @@ def test_collections_list_serialization(self): collection_model['collection_id'] = 'testString' collection_model['name'] = 'testString' collection_model['description'] = 'testString' - collection_model['created'] = '2020-01-28T18:40:40.123456Z' - collection_model['updated'] = '2020-01-28T18:40:40.123456Z' + collection_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + collection_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) collection_model['image_count'] = 38 collection_model['training_status'] = collection_training_status_model @@ -2291,8 +2292,8 @@ def test_image_details_serialization(self): # Construct a json representation of a ImageDetails model image_details_model_json = {} image_details_model_json['image_id'] = 'testString' - image_details_model_json['updated'] = '2020-01-28T18:40:40.123456Z' - image_details_model_json['created'] = '2020-01-28T18:40:40.123456Z' + image_details_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + image_details_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) image_details_model_json['source'] = image_source_model image_details_model_json['dimensions'] = image_dimensions_model image_details_model_json['errors'] = [error_model] @@ -2361,8 +2362,8 @@ def test_image_details_list_serialization(self): image_details_model = {} # ImageDetails image_details_model['image_id'] = 'testString' - image_details_model['updated'] = '2020-01-28T18:40:40.123456Z' - image_details_model['created'] = '2020-01-28T18:40:40.123456Z' + image_details_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + image_details_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) image_details_model['source'] = image_source_model image_details_model['dimensions'] = image_dimensions_model image_details_model['errors'] = [error_model] @@ -2470,7 +2471,7 @@ def test_image_summary_serialization(self): # Construct a json representation of a ImageSummary model image_summary_model_json = {} image_summary_model_json['image_id'] = 'testString' - image_summary_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + image_summary_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of ImageSummary by calling from_dict on the json representation image_summary_model = ImageSummary.from_dict(image_summary_model_json) @@ -2501,7 +2502,7 @@ def test_image_summary_list_serialization(self): image_summary_model = {} # ImageSummary image_summary_model['image_id'] = 'testString' - image_summary_model['updated'] = '2020-01-28T18:40:40.123456Z' + image_summary_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a json representation of a ImageSummaryList model image_summary_list_model_json = {} @@ -2818,7 +2819,7 @@ def test_training_event_serialization(self): training_event_model_json = {} training_event_model_json['type'] = 'objects' training_event_model_json['collection_id'] = 'testString' - training_event_model_json['completion_time'] = '2020-01-28T18:40:40.123456Z' + training_event_model_json['completion_time'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) training_event_model_json['status'] = 'failed' training_event_model_json['image_count'] = 38 @@ -2852,14 +2853,14 @@ def test_training_events_serialization(self): training_event_model = {} # TrainingEvent training_event_model['type'] = 'objects' training_event_model['collection_id'] = 'testString' - training_event_model['completion_time'] = '2020-01-28T18:40:40.123456Z' + training_event_model['completion_time'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) training_event_model['status'] = 'failed' training_event_model['image_count'] = 38 # Construct a json representation of a TrainingEvents model training_events_model_json = {} - training_events_model_json['start_time'] = '2020-01-28T18:40:40.123456Z' - training_events_model_json['end_time'] = '2020-01-28T18:40:40.123456Z' + training_events_model_json['start_time'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_events_model_json['end_time'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) training_events_model_json['completed_events'] = 38 training_events_model_json['trained_images'] = 38 training_events_model_json['events'] = [training_event_model] From 0ea3ac0ce1024138097e1777f8ecde5b45eaa92d Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 19 May 2021 16:45:56 -0400 Subject: [PATCH 317/455] feat(discov2): generation release changes --- ibm_watson/discovery_v2.py | 327 ++++++++++++++++- test/unit/test_discovery_v2.py | 627 +++++++++++++++++++++++---------- 2 files changed, 763 insertions(+), 191 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 093b27a19..c17756c7c 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2019, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201210-124536 +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 """ IBM Watson™ Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive @@ -539,6 +539,81 @@ def get_autocompletion(self, response = self.send(request) return response + def query_collection_notices(self, + project_id: str, + collection_id: str, + *, + filter: str = None, + query: str = None, + natural_language_query: str = None, + count: int = None, + offset: int = None, + **kwargs) -> DetailedResponse: + """ + Query collection notices. + + Finds collection-level notices (errors and warnings) that are generated when + documents are ingested. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str collection_id: The ID of the collection. + :param str filter: (optional) A cacheable query that excludes documents + that don't mention the query content. Filter searches are better for + metadata-type searches and for assessing the concepts in the data set. + :param str query: (optional) A query search returns all documents in your + data set with full enrichments and full text, but with the most relevant + documents listed first. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by utilizing training data and natural language + understanding. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is **10000**. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. The maximum for + the **count** and **offset** values together in any one query is **10000**. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query_collection_notices') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'filter': filter, + 'query': query, + 'natural_language_query': natural_language_query, + 'count': count, + 'offset': offset + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/notices'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + def query_notices(self, project_id: str, *, @@ -549,11 +624,10 @@ def query_notices(self, offset: int = None, **kwargs) -> DetailedResponse: """ - Query system notices. + Query project notices. - Queries for notices (errors or warnings) that might have been generated by the - system. Notices are generated when ingesting documents and performing relevance - training. + Finds project-level notices (errors and warnings). Currently, project-level + notices are generated by relevancy training. :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. @@ -1234,6 +1308,50 @@ def update_training_query(self, response = self.send(request) return response + def delete_training_query(self, project_id: str, query_id: str, + **kwargs) -> DetailedResponse: + """ + Delete a training data query. + + Removes details from a training data query, including the query string and all + examples. + + :param str project_id: The ID of the project. This information can be found + from the deploy page of the Discovery administrative tooling. + :param str query_id: The ID of the query used for training. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if query_id is None: + raise ValueError('query_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_training_query') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + ######################### # analyze ######################### @@ -1374,7 +1492,8 @@ def create_enrichment(self, :param str project_id: The ID of the project. This information can be found from the deploy page of the Discovery administrative tooling. - :param CreateEnrichment enrichment: + :param CreateEnrichment enrichment: Information about a specific + enrichment. :param BinaryIO file: (optional) The enrichment file to upload. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -4762,6 +4881,26 @@ class QueryLargePassages(): `100`. :attr int characters: (optional) The approximate number of characters that any one passage will have. + :attr bool find_answers: (optional) When true, `answer` objects are returned as + part of each passage in the query results. The primary difference between an + `answer` and a `passage` is that the length of a passage is defined by the + query, where the length of an `answer` is calculated by Discovery based on how + much text is needed to answer the question./n/nThis parameter is ignored if + passages are not enabled for the query, or no **natural_language_query** is + specified./n/nIf the **find_answers** parameter is set to `true` and + **per_document** parameter is also set to `true`, then the document search + results and the passage search results within each document are reordered using + the answer confidences. The goal of this reordering is to do as much as possible + to make sure that the first answer of the first passage of the first document is + the best answer. Similarly, if the **find_answers** parameter is set to `true` + and **per_document** parameter is set to `false`, then the passage search + results are reordered in decreasing order of the highest confidence answer for + each document and passage./n/nThe **find_answers** parameter is **beta** + functionality available only on managed instances and should not be used in a + production environment. This parameter is not available on installed instances + of Discovery. + :attr int max_answers_per_passage: (optional) The number of `answer` objects to + return per passage if the **find_answers** parmeter is specified as `true`. """ def __init__(self, @@ -4771,7 +4910,9 @@ def __init__(self, max_per_document: int = None, fields: List[str] = None, count: int = None, - characters: int = None) -> None: + characters: int = None, + find_answers: bool = None, + max_answers_per_passage: int = None) -> None: """ Initialize a QueryLargePassages object. @@ -4789,6 +4930,28 @@ def __init__(self, maximum is `100`. :param int characters: (optional) The approximate number of characters that any one passage will have. + :param bool find_answers: (optional) When true, `answer` objects are + returned as part of each passage in the query results. The primary + difference between an `answer` and a `passage` is that the length of a + passage is defined by the query, where the length of an `answer` is + calculated by Discovery based on how much text is needed to answer the + question./n/nThis parameter is ignored if passages are not enabled for the + query, or no **natural_language_query** is specified./n/nIf the + **find_answers** parameter is set to `true` and **per_document** parameter + is also set to `true`, then the document search results and the passage + search results within each document are reordered using the answer + confidences. The goal of this reordering is to do as much as possible to + make sure that the first answer of the first passage of the first document + is the best answer. Similarly, if the **find_answers** parameter is set to + `true` and **per_document** parameter is set to `false`, then the passage + search results are reordered in decreasing order of the highest confidence + answer for each document and passage./n/nThe **find_answers** parameter is + **beta** functionality available only on managed instances and should not + be used in a production environment. This parameter is not available on + installed instances of Discovery. + :param int max_answers_per_passage: (optional) The number of `answer` + objects to return per passage if the **find_answers** parmeter is specified + as `true`. """ self.enabled = enabled self.per_document = per_document @@ -4796,6 +4959,8 @@ def __init__(self, self.fields = fields self.count = count self.characters = characters + self.find_answers = find_answers + self.max_answers_per_passage = max_answers_per_passage @classmethod def from_dict(cls, _dict: Dict) -> 'QueryLargePassages': @@ -4813,6 +4978,11 @@ def from_dict(cls, _dict: Dict) -> 'QueryLargePassages': args['count'] = _dict.get('count') if 'characters' in _dict: args['characters'] = _dict.get('characters') + if 'find_answers' in _dict: + args['find_answers'] = _dict.get('find_answers') + if 'max_answers_per_passage' in _dict: + args['max_answers_per_passage'] = _dict.get( + 'max_answers_per_passage') return cls(**args) @classmethod @@ -4836,6 +5006,11 @@ def to_dict(self) -> Dict: _dict['count'] = self.count if hasattr(self, 'characters') and self.characters is not None: _dict['characters'] = self.characters + if hasattr(self, 'find_answers') and self.find_answers is not None: + _dict['find_answers'] = self.find_answers + if hasattr(self, 'max_answers_per_passage' + ) and self.max_answers_per_passage is not None: + _dict['max_answers_per_passage'] = self.max_answers_per_passage return _dict def _to_dict(self): @@ -5212,6 +5387,10 @@ class QueryResponsePassage(): extracted passage in the originating field. :attr str field: (optional) The label of the field from which the passage has been extracted. + :attr float confidence: (optional) An estimate of the probability that the + passage is relevant. + :attr List[ResultPassageAnswer] answers: (optional) An array of extracted + answers to the specified query. """ def __init__(self, @@ -5222,7 +5401,9 @@ def __init__(self, collection_id: str = None, start_offset: int = None, end_offset: int = None, - field: str = None) -> None: + field: str = None, + confidence: float = None, + answers: List['ResultPassageAnswer'] = None) -> None: """ Initialize a QueryResponsePassage object. @@ -5239,6 +5420,10 @@ def __init__(self, extracted passage in the originating field. :param str field: (optional) The label of the field from which the passage has been extracted. + :param float confidence: (optional) An estimate of the probability that the + passage is relevant. + :param List[ResultPassageAnswer] answers: (optional) An array of extracted + answers to the specified query. """ self.passage_text = passage_text self.passage_score = passage_score @@ -5247,6 +5432,8 @@ def __init__(self, self.start_offset = start_offset self.end_offset = end_offset self.field = field + self.confidence = confidence + self.answers = answers @classmethod def from_dict(cls, _dict: Dict) -> 'QueryResponsePassage': @@ -5266,6 +5453,12 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponsePassage': args['end_offset'] = _dict.get('end_offset') if 'field' in _dict: args['field'] = _dict.get('field') + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + if 'answers' in _dict: + args['answers'] = [ + ResultPassageAnswer.from_dict(x) for x in _dict.get('answers') + ] return cls(**args) @classmethod @@ -5290,6 +5483,10 @@ def to_dict(self) -> Dict: _dict['end_offset'] = self.end_offset if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'answers') and self.answers is not None: + _dict['answers'] = [x.to_dict() for x in self.answers] return _dict def _to_dict(self): @@ -5536,6 +5733,10 @@ class QueryResultPassage(): extracted passage in the originating field. :attr str field: (optional) The label of the field from which the passage has been extracted. + :attr float confidence: (optional) Estimate of the probability that the passage + is relevant. + :attr List[ResultPassageAnswer] answers: (optional) An arry of extracted answers + to the specified query. """ def __init__(self, @@ -5543,7 +5744,9 @@ def __init__(self, passage_text: str = None, start_offset: int = None, end_offset: int = None, - field: str = None) -> None: + field: str = None, + confidence: float = None, + answers: List['ResultPassageAnswer'] = None) -> None: """ Initialize a QueryResultPassage object. @@ -5554,11 +5757,17 @@ def __init__(self, extracted passage in the originating field. :param str field: (optional) The label of the field from which the passage has been extracted. + :param float confidence: (optional) Estimate of the probability that the + passage is relevant. + :param List[ResultPassageAnswer] answers: (optional) An arry of extracted + answers to the specified query. """ self.passage_text = passage_text self.start_offset = start_offset self.end_offset = end_offset self.field = field + self.confidence = confidence + self.answers = answers @classmethod def from_dict(cls, _dict: Dict) -> 'QueryResultPassage': @@ -5572,6 +5781,12 @@ def from_dict(cls, _dict: Dict) -> 'QueryResultPassage': args['end_offset'] = _dict.get('end_offset') if 'field' in _dict: args['field'] = _dict.get('field') + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + if 'answers' in _dict: + args['answers'] = [ + ResultPassageAnswer.from_dict(x) for x in _dict.get('answers') + ] return cls(**args) @classmethod @@ -5590,6 +5805,10 @@ def to_dict(self) -> Dict: _dict['end_offset'] = self.end_offset if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'answers') and self.answers is not None: + _dict['answers'] = [x.to_dict() for x in self.answers] return _dict def _to_dict(self): @@ -6068,6 +6287,94 @@ def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: return not self == other +class ResultPassageAnswer(): + """ + Object containing a potential answer to the specified query. + + :attr str answer_text: (optional) Answer text for the specified query as + identified by Discovery. + :attr int start_offset: (optional) The position of the first character of the + extracted answer in the originating field. + :attr int end_offset: (optional) The position of the last character of the + extracted answer in the originating field. + :attr float confidence: (optional) An estimate of the probability that the + answer is relevant. + """ + + def __init__(self, + *, + answer_text: str = None, + start_offset: int = None, + end_offset: int = None, + confidence: float = None) -> None: + """ + Initialize a ResultPassageAnswer object. + + :param str answer_text: (optional) Answer text for the specified query as + identified by Discovery. + :param int start_offset: (optional) The position of the first character of + the extracted answer in the originating field. + :param int end_offset: (optional) The position of the last character of the + extracted answer in the originating field. + :param float confidence: (optional) An estimate of the probability that the + answer is relevant. + """ + self.answer_text = answer_text + self.start_offset = start_offset + self.end_offset = end_offset + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResultPassageAnswer': + """Initialize a ResultPassageAnswer object from a json dictionary.""" + args = {} + if 'answer_text' in _dict: + args['answer_text'] = _dict.get('answer_text') + if 'start_offset' in _dict: + args['start_offset'] = _dict.get('start_offset') + if 'end_offset' in _dict: + args['end_offset'] = _dict.get('end_offset') + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResultPassageAnswer 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, 'answer_text') and self.answer_text is not None: + _dict['answer_text'] = self.answer_text + if hasattr(self, 'start_offset') and self.start_offset is not None: + _dict['start_offset'] = self.start_offset + if hasattr(self, 'end_offset') and self.end_offset is not None: + _dict['end_offset'] = self.end_offset + 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 ResultPassageAnswer object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResultPassageAnswer') -> 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: 'ResultPassageAnswer') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RetrievalDetails(): """ An object contain retrieval type information. diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index a773e75f4..c2861b6d2 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect import io import json @@ -32,13 +33,13 @@ version = 'testString' -service = DiscoveryV2( +_service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version=version ) -base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: Collections @@ -65,7 +66,7 @@ def test_list_collections_all_params(self): list_collections() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' responses.add(responses.GET, url, @@ -77,7 +78,7 @@ def test_list_collections_all_params(self): project_id = 'testString' # Invoke method - response = service.list_collections( + response = _service.list_collections( project_id, headers={} ) @@ -93,7 +94,7 @@ def test_list_collections_value_error(self): test_list_collections_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' responses.add(responses.GET, url, @@ -111,7 +112,7 @@ def test_list_collections_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_collections(**req_copy) + _service.list_collections(**req_copy) @@ -135,8 +136,8 @@ def test_create_collection_all_params(self): create_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.POST, url, body=mock_response, @@ -156,7 +157,7 @@ def test_create_collection_all_params(self): enrichments = [collection_enrichment_model] # Invoke method - response = service.create_collection( + response = _service.create_collection( project_id, name, description=description, @@ -182,8 +183,8 @@ def test_create_collection_value_error(self): test_create_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.POST, url, body=mock_response, @@ -210,7 +211,7 @@ def test_create_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_collection(**req_copy) + _service.create_collection(**req_copy) @@ -234,8 +235,8 @@ def test_get_collection_all_params(self): get_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.GET, url, body=mock_response, @@ -247,7 +248,7 @@ def test_get_collection_all_params(self): collection_id = 'testString' # Invoke method - response = service.get_collection( + response = _service.get_collection( project_id, collection_id, headers={} @@ -264,8 +265,8 @@ def test_get_collection_value_error(self): test_get_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.GET, url, body=mock_response, @@ -284,7 +285,7 @@ def test_get_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_collection(**req_copy) + _service.get_collection(**req_copy) @@ -308,8 +309,8 @@ def test_update_collection_all_params(self): update_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.POST, url, body=mock_response, @@ -329,7 +330,7 @@ def test_update_collection_all_params(self): enrichments = [collection_enrichment_model] # Invoke method - response = service.update_collection( + response = _service.update_collection( project_id, collection_id, name=name, @@ -354,8 +355,8 @@ def test_update_collection_value_error(self): test_update_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.POST, url, body=mock_response, @@ -382,7 +383,7 @@ def test_update_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_collection(**req_copy) + _service.update_collection(**req_copy) @@ -406,7 +407,7 @@ def test_delete_collection_all_params(self): delete_collection() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') responses.add(responses.DELETE, url, status=204) @@ -416,7 +417,7 @@ def test_delete_collection_all_params(self): collection_id = 'testString' # Invoke method - response = service.delete_collection( + response = _service.delete_collection( project_id, collection_id, headers={} @@ -433,7 +434,7 @@ def test_delete_collection_value_error(self): test_delete_collection_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') responses.add(responses.DELETE, url, status=204) @@ -450,7 +451,7 @@ def test_delete_collection_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_collection(**req_copy) + _service.delete_collection(**req_copy) @@ -484,8 +485,8 @@ def test_query_all_params(self): query() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/query') + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -510,6 +511,8 @@ def test_query_all_params(self): query_large_passages_model['fields'] = ['testString'] query_large_passages_model['count'] = 100 query_large_passages_model['characters'] = 50 + query_large_passages_model['find_answers'] = True + query_large_passages_model['max_answers_per_passage'] = 38 # Set up parameter values project_id = 'testString' @@ -529,7 +532,7 @@ def test_query_all_params(self): passages = query_large_passages_model # Invoke method - response = service.query( + response = _service.query( project_id, collection_ids=collection_ids, filter=filter, @@ -575,8 +578,8 @@ def test_query_required_params(self): test_query_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/query') + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -587,7 +590,7 @@ def test_query_required_params(self): project_id = 'testString' # Invoke method - response = service.query( + response = _service.query( project_id, headers={} ) @@ -603,8 +606,8 @@ def test_query_value_error(self): test_query_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/query') + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -621,7 +624,7 @@ def test_query_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.query(**req_copy) + _service.query(**req_copy) @@ -645,7 +648,7 @@ def test_get_autocompletion_all_params(self): get_autocompletion() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/autocompletion') + url = self.preprocess_url(_base_url + '/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -661,7 +664,7 @@ def test_get_autocompletion_all_params(self): count = 38 # Invoke method - response = service.get_autocompletion( + response = _service.get_autocompletion( project_id, prefix, collection_ids=collection_ids, @@ -688,7 +691,7 @@ def test_get_autocompletion_required_params(self): test_get_autocompletion_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/autocompletion') + url = self.preprocess_url(_base_url + '/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -701,7 +704,7 @@ def test_get_autocompletion_required_params(self): prefix = 'testString' # Invoke method - response = service.get_autocompletion( + response = _service.get_autocompletion( project_id, prefix, headers={} @@ -722,7 +725,7 @@ def test_get_autocompletion_value_error(self): test_get_autocompletion_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/autocompletion') + url = self.preprocess_url(_base_url + '/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -742,7 +745,129 @@ def test_get_autocompletion_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_autocompletion(**req_copy) + _service.get_autocompletion(**req_copy) + + + +class TestQueryCollectionNotices(): + """ + Test Class for query_collection_notices + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_query_collection_notices_all_params(self): + """ + query_collection_notices() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + filter = 'testString' + query = 'testString' + natural_language_query = 'testString' + count = 38 + offset = 38 + + # Invoke method + response = _service.query_collection_notices( + project_id, + collection_id, + filter=filter, + query=query, + natural_language_query=natural_language_query, + count=count, + offset=offset, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'filter={}'.format(filter) in query_string + assert 'query={}'.format(query) in query_string + assert 'natural_language_query={}'.format(natural_language_query) in query_string + assert 'count={}'.format(count) in query_string + assert 'offset={}'.format(offset) in query_string + + + @responses.activate + def test_query_collection_notices_required_params(self): + """ + test_query_collection_notices_required_params() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = _service.query_collection_notices( + project_id, + collection_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_query_collection_notices_value_error(self): + """ + test_query_collection_notices_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.query_collection_notices(**req_copy) @@ -766,8 +891,8 @@ def test_query_notices_all_params(self): query_notices() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/notices') - mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/notices') + mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, body=mock_response, @@ -783,7 +908,7 @@ def test_query_notices_all_params(self): offset = 38 # Invoke method - response = service.query_notices( + response = _service.query_notices( project_id, filter=filter, query=query, @@ -812,8 +937,8 @@ def test_query_notices_required_params(self): test_query_notices_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/notices') - mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/notices') + mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, body=mock_response, @@ -824,7 +949,7 @@ def test_query_notices_required_params(self): project_id = 'testString' # Invoke method - response = service.query_notices( + response = _service.query_notices( project_id, headers={} ) @@ -840,8 +965,8 @@ def test_query_notices_value_error(self): test_query_notices_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/notices') - mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/notices') + mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, body=mock_response, @@ -858,7 +983,7 @@ def test_query_notices_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.query_notices(**req_copy) + _service.query_notices(**req_copy) @@ -882,7 +1007,7 @@ def test_list_fields_all_params(self): list_fields() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/fields') + url = self.preprocess_url(_base_url + '/v2/projects/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' responses.add(responses.GET, url, @@ -895,7 +1020,7 @@ def test_list_fields_all_params(self): collection_ids = ['testString'] # Invoke method - response = service.list_fields( + response = _service.list_fields( project_id, collection_ids=collection_ids, headers={} @@ -916,7 +1041,7 @@ def test_list_fields_required_params(self): test_list_fields_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/fields') + url = self.preprocess_url(_base_url + '/v2/projects/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' responses.add(responses.GET, url, @@ -928,7 +1053,7 @@ def test_list_fields_required_params(self): project_id = 'testString' # Invoke method - response = service.list_fields( + response = _service.list_fields( project_id, headers={} ) @@ -944,7 +1069,7 @@ def test_list_fields_value_error(self): test_list_fields_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/fields') + url = self.preprocess_url(_base_url + '/v2/projects/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' responses.add(responses.GET, url, @@ -962,7 +1087,7 @@ def test_list_fields_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_fields(**req_copy) + _service.list_fields(**req_copy) @@ -996,7 +1121,7 @@ def test_get_component_settings_all_params(self): get_component_settings() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/component_settings') + url = self.preprocess_url(_base_url + '/v2/projects/testString/component_settings') mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' responses.add(responses.GET, url, @@ -1008,7 +1133,7 @@ def test_get_component_settings_all_params(self): project_id = 'testString' # Invoke method - response = service.get_component_settings( + response = _service.get_component_settings( project_id, headers={} ) @@ -1024,7 +1149,7 @@ def test_get_component_settings_value_error(self): test_get_component_settings_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/component_settings') + url = self.preprocess_url(_base_url + '/v2/projects/testString/component_settings') mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' responses.add(responses.GET, url, @@ -1042,7 +1167,7 @@ def test_get_component_settings_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_component_settings(**req_copy) + _service.get_component_settings(**req_copy) @@ -1076,7 +1201,7 @@ def test_add_document_all_params(self): add_document() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing"}' responses.add(responses.POST, url, @@ -1094,7 +1219,7 @@ def test_add_document_all_params(self): x_watson_discovery_force = True # Invoke method - response = service.add_document( + response = _service.add_document( project_id, collection_id, file=file, @@ -1116,7 +1241,7 @@ def test_add_document_required_params(self): test_add_document_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing"}' responses.add(responses.POST, url, @@ -1129,7 +1254,7 @@ def test_add_document_required_params(self): collection_id = 'testString' # Invoke method - response = service.add_document( + response = _service.add_document( project_id, collection_id, headers={} @@ -1146,7 +1271,7 @@ def test_add_document_value_error(self): test_add_document_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing"}' responses.add(responses.POST, url, @@ -1166,7 +1291,7 @@ def test_add_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_document(**req_copy) + _service.add_document(**req_copy) @@ -1190,7 +1315,7 @@ def test_update_document_all_params(self): update_document() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing"}' responses.add(responses.POST, url, @@ -1209,7 +1334,7 @@ def test_update_document_all_params(self): x_watson_discovery_force = True # Invoke method - response = service.update_document( + response = _service.update_document( project_id, collection_id, document_id, @@ -1232,7 +1357,7 @@ def test_update_document_required_params(self): test_update_document_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing"}' responses.add(responses.POST, url, @@ -1246,7 +1371,7 @@ def test_update_document_required_params(self): document_id = 'testString' # Invoke method - response = service.update_document( + response = _service.update_document( project_id, collection_id, document_id, @@ -1264,7 +1389,7 @@ def test_update_document_value_error(self): test_update_document_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing"}' responses.add(responses.POST, url, @@ -1286,7 +1411,7 @@ def test_update_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_document(**req_copy) + _service.update_document(**req_copy) @@ -1310,7 +1435,7 @@ def test_delete_document_all_params(self): delete_document() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -1325,7 +1450,7 @@ def test_delete_document_all_params(self): x_watson_discovery_force = True # Invoke method - response = service.delete_document( + response = _service.delete_document( project_id, collection_id, document_id, @@ -1344,7 +1469,7 @@ def test_delete_document_required_params(self): test_delete_document_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -1358,7 +1483,7 @@ def test_delete_document_required_params(self): document_id = 'testString' # Invoke method - response = service.delete_document( + response = _service.delete_document( project_id, collection_id, document_id, @@ -1376,7 +1501,7 @@ def test_delete_document_value_error(self): test_delete_document_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/documents/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -1398,7 +1523,7 @@ def test_delete_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_document(**req_copy) + _service.delete_document(**req_copy) @@ -1432,8 +1557,8 @@ def test_list_training_queries_all_params(self): list_training_queries() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') - mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -1444,7 +1569,7 @@ def test_list_training_queries_all_params(self): project_id = 'testString' # Invoke method - response = service.list_training_queries( + response = _service.list_training_queries( project_id, headers={} ) @@ -1460,8 +1585,8 @@ def test_list_training_queries_value_error(self): test_list_training_queries_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') - mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -1478,7 +1603,7 @@ def test_list_training_queries_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_training_queries(**req_copy) + _service.list_training_queries(**req_copy) @@ -1502,7 +1627,7 @@ def test_delete_training_queries_all_params(self): delete_training_queries() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') responses.add(responses.DELETE, url, status=204) @@ -1511,7 +1636,7 @@ def test_delete_training_queries_all_params(self): project_id = 'testString' # Invoke method - response = service.delete_training_queries( + response = _service.delete_training_queries( project_id, headers={} ) @@ -1527,7 +1652,7 @@ def test_delete_training_queries_value_error(self): test_delete_training_queries_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') responses.add(responses.DELETE, url, status=204) @@ -1542,7 +1667,7 @@ def test_delete_training_queries_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_training_queries(**req_copy) + _service.delete_training_queries(**req_copy) @@ -1566,8 +1691,8 @@ def test_create_training_query_all_params(self): create_training_query() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -1587,7 +1712,7 @@ def test_create_training_query_all_params(self): filter = 'testString' # Invoke method - response = service.create_training_query( + response = _service.create_training_query( project_id, natural_language_query, examples, @@ -1611,8 +1736,8 @@ def test_create_training_query_value_error(self): test_create_training_query_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -1640,7 +1765,7 @@ def test_create_training_query_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_training_query(**req_copy) + _service.create_training_query(**req_copy) @@ -1664,8 +1789,8 @@ def test_get_training_query_all_params(self): get_training_query() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1677,7 +1802,7 @@ def test_get_training_query_all_params(self): query_id = 'testString' # Invoke method - response = service.get_training_query( + response = _service.get_training_query( project_id, query_id, headers={} @@ -1694,8 +1819,8 @@ def test_get_training_query_value_error(self): test_get_training_query_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1714,7 +1839,7 @@ def test_get_training_query_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_training_query(**req_copy) + _service.get_training_query(**req_copy) @@ -1738,8 +1863,8 @@ def test_update_training_query_all_params(self): update_training_query() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -1760,7 +1885,7 @@ def test_update_training_query_all_params(self): filter = 'testString' # Invoke method - response = service.update_training_query( + response = _service.update_training_query( project_id, query_id, natural_language_query, @@ -1785,8 +1910,8 @@ def test_update_training_query_value_error(self): test_update_training_query_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00", "updated": "2019-01-01T12:00:00"}]}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -1816,7 +1941,75 @@ def test_update_training_query_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_training_query(**req_copy) + _service.update_training_query(**req_copy) + + + +class TestDeleteTrainingQuery(): + """ + Test Class for delete_training_query + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_training_query_all_params(self): + """ + delete_training_query() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + + # Invoke method + response = _service.delete_training_query( + project_id, + query_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + + @responses.activate + def test_delete_training_query_value_error(self): + """ + test_delete_training_query_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "query_id": query_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_training_query(**req_copy) @@ -1850,8 +2043,8 @@ def test_analyze_document_all_params(self): analyze_document() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' responses.add(responses.POST, url, body=mock_response, @@ -1867,7 +2060,7 @@ def test_analyze_document_all_params(self): metadata = 'testString' # Invoke method - response = service.analyze_document( + response = _service.analyze_document( project_id, collection_id, file=file, @@ -1888,8 +2081,8 @@ def test_analyze_document_required_params(self): test_analyze_document_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' responses.add(responses.POST, url, body=mock_response, @@ -1901,7 +2094,7 @@ def test_analyze_document_required_params(self): collection_id = 'testString' # Invoke method - response = service.analyze_document( + response = _service.analyze_document( project_id, collection_id, headers={} @@ -1918,8 +2111,8 @@ def test_analyze_document_value_error(self): test_analyze_document_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' + url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' responses.add(responses.POST, url, body=mock_response, @@ -1938,7 +2131,7 @@ def test_analyze_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.analyze_document(**req_copy) + _service.analyze_document(**req_copy) @@ -1972,7 +2165,7 @@ def test_list_enrichments_all_params(self): list_enrichments() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments') + url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}]}' responses.add(responses.GET, url, @@ -1984,7 +2177,7 @@ def test_list_enrichments_all_params(self): project_id = 'testString' # Invoke method - response = service.list_enrichments( + response = _service.list_enrichments( project_id, headers={} ) @@ -2000,7 +2193,7 @@ def test_list_enrichments_value_error(self): test_list_enrichments_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments') + url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}]}' responses.add(responses.GET, url, @@ -2018,7 +2211,7 @@ def test_list_enrichments_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_enrichments(**req_copy) + _service.list_enrichments(**req_copy) @@ -2042,7 +2235,7 @@ def test_create_enrichment_all_params(self): create_enrichment() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments') + url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' responses.add(responses.POST, url, @@ -2070,7 +2263,7 @@ def test_create_enrichment_all_params(self): file = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = service.create_enrichment( + response = _service.create_enrichment( project_id, enrichment, file=file, @@ -2088,7 +2281,7 @@ def test_create_enrichment_required_params(self): test_create_enrichment_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments') + url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' responses.add(responses.POST, url, @@ -2115,7 +2308,7 @@ def test_create_enrichment_required_params(self): enrichment = create_enrichment_model # Invoke method - response = service.create_enrichment( + response = _service.create_enrichment( project_id, enrichment, headers={} @@ -2132,7 +2325,7 @@ def test_create_enrichment_value_error(self): test_create_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments') + url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' responses.add(responses.POST, url, @@ -2166,7 +2359,7 @@ def test_create_enrichment_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_enrichment(**req_copy) + _service.create_enrichment(**req_copy) @@ -2190,7 +2383,7 @@ def test_get_enrichment_all_params(self): get_enrichment() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' responses.add(responses.GET, url, @@ -2203,7 +2396,7 @@ def test_get_enrichment_all_params(self): enrichment_id = 'testString' # Invoke method - response = service.get_enrichment( + response = _service.get_enrichment( project_id, enrichment_id, headers={} @@ -2220,7 +2413,7 @@ def test_get_enrichment_value_error(self): test_get_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' responses.add(responses.GET, url, @@ -2240,7 +2433,7 @@ def test_get_enrichment_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_enrichment(**req_copy) + _service.get_enrichment(**req_copy) @@ -2264,7 +2457,7 @@ def test_update_enrichment_all_params(self): update_enrichment() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' responses.add(responses.POST, url, @@ -2279,7 +2472,7 @@ def test_update_enrichment_all_params(self): description = 'testString' # Invoke method - response = service.update_enrichment( + response = _service.update_enrichment( project_id, enrichment_id, name, @@ -2302,7 +2495,7 @@ def test_update_enrichment_value_error(self): test_update_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' responses.add(responses.POST, url, @@ -2325,7 +2518,7 @@ def test_update_enrichment_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_enrichment(**req_copy) + _service.update_enrichment(**req_copy) @@ -2349,7 +2542,7 @@ def test_delete_enrichment_all_params(self): delete_enrichment() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') responses.add(responses.DELETE, url, status=204) @@ -2359,7 +2552,7 @@ def test_delete_enrichment_all_params(self): enrichment_id = 'testString' # Invoke method - response = service.delete_enrichment( + response = _service.delete_enrichment( project_id, enrichment_id, headers={} @@ -2376,7 +2569,7 @@ def test_delete_enrichment_value_error(self): test_delete_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString/enrichments/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') responses.add(responses.DELETE, url, status=204) @@ -2393,7 +2586,7 @@ def test_delete_enrichment_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_enrichment(**req_copy) + _service.delete_enrichment(**req_copy) @@ -2427,7 +2620,7 @@ def test_list_projects_all_params(self): list_projects() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects') + url = self.preprocess_url(_base_url + '/v2/projects') mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' responses.add(responses.GET, url, @@ -2436,7 +2629,7 @@ def test_list_projects_all_params(self): status=200) # Invoke method - response = service.list_projects() + response = _service.list_projects() # Check for correct operation @@ -2450,7 +2643,7 @@ def test_list_projects_value_error(self): test_list_projects_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects') + url = self.preprocess_url(_base_url + '/v2/projects') mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' responses.add(responses.GET, url, @@ -2464,7 +2657,7 @@ def test_list_projects_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_projects(**req_copy) + _service.list_projects(**req_copy) @@ -2488,7 +2681,7 @@ def test_create_project_all_params(self): create_project() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects') + url = self.preprocess_url(_base_url + '/v2/projects') mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.POST, url, @@ -2535,7 +2728,7 @@ def test_create_project_all_params(self): default_query_parameters = default_query_params_model # Invoke method - response = service.create_project( + response = _service.create_project( name, type, default_query_parameters=default_query_parameters, @@ -2558,7 +2751,7 @@ def test_create_project_value_error(self): test_create_project_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects') + url = self.preprocess_url(_base_url + '/v2/projects') mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.POST, url, @@ -2612,7 +2805,7 @@ def test_create_project_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_project(**req_copy) + _service.create_project(**req_copy) @@ -2636,7 +2829,7 @@ def test_get_project_all_params(self): get_project() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString') mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.GET, url, @@ -2648,7 +2841,7 @@ def test_get_project_all_params(self): project_id = 'testString' # Invoke method - response = service.get_project( + response = _service.get_project( project_id, headers={} ) @@ -2664,7 +2857,7 @@ def test_get_project_value_error(self): test_get_project_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString') mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.GET, url, @@ -2682,7 +2875,7 @@ def test_get_project_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_project(**req_copy) + _service.get_project(**req_copy) @@ -2706,7 +2899,7 @@ def test_update_project_all_params(self): update_project() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString') mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.POST, url, @@ -2719,7 +2912,7 @@ def test_update_project_all_params(self): name = 'testString' # Invoke method - response = service.update_project( + response = _service.update_project( project_id, name=name, headers={} @@ -2739,7 +2932,7 @@ def test_update_project_required_params(self): test_update_project_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString') mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.POST, url, @@ -2751,7 +2944,7 @@ def test_update_project_required_params(self): project_id = 'testString' # Invoke method - response = service.update_project( + response = _service.update_project( project_id, headers={} ) @@ -2767,7 +2960,7 @@ def test_update_project_value_error(self): test_update_project_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString') mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.POST, url, @@ -2785,7 +2978,7 @@ def test_update_project_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_project(**req_copy) + _service.update_project(**req_copy) @@ -2809,7 +3002,7 @@ def test_delete_project_all_params(self): delete_project() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString') responses.add(responses.DELETE, url, status=204) @@ -2818,7 +3011,7 @@ def test_delete_project_all_params(self): project_id = 'testString' # Invoke method - response = service.delete_project( + response = _service.delete_project( project_id, headers={} ) @@ -2834,7 +3027,7 @@ def test_delete_project_value_error(self): test_delete_project_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/projects/testString') + url = self.preprocess_url(_base_url + '/v2/projects/testString') responses.add(responses.DELETE, url, status=204) @@ -2849,7 +3042,7 @@ def test_delete_project_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_project(**req_copy) + _service.delete_project(**req_copy) @@ -2883,7 +3076,7 @@ def test_delete_user_data_all_params(self): delete_user_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/user_data') + url = self.preprocess_url(_base_url + '/v2/user_data') responses.add(responses.DELETE, url, status=200) @@ -2892,7 +3085,7 @@ def test_delete_user_data_all_params(self): customer_id = 'testString' # Invoke method - response = service.delete_user_data( + response = _service.delete_user_data( customer_id, headers={} ) @@ -2912,7 +3105,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v2/user_data') + url = self.preprocess_url(_base_url + '/v2/user_data') responses.add(responses.DELETE, url, status=200) @@ -2927,7 +3120,7 @@ def test_delete_user_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_user_data(**req_copy) + _service.delete_user_data(**req_copy) @@ -2955,7 +3148,7 @@ def test_analyzed_document_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) notice_model['document_id'] = 'testString' notice_model['collection_id'] = 'testString' notice_model['query_id'] = 'testString' @@ -3068,7 +3261,7 @@ def test_collection_details_serialization(self): collection_details_model_json['collection_id'] = 'testString' collection_details_model_json['name'] = 'testString' collection_details_model_json['description'] = 'testString' - collection_details_model_json['created'] = '2020-01-28T18:40:40.123456Z' + collection_details_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) collection_details_model_json['language'] = 'testString' collection_details_model_json['enrichments'] = [collection_enrichment_model] @@ -3898,7 +4091,7 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} notice_model_json['notice_id'] = 'testString' - notice_model_json['created'] = '2020-01-28T18:40:40.123456Z' + notice_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) notice_model_json['document_id'] = 'testString' notice_model_json['collection_id'] = 'testString' notice_model_json['query_id'] = 'testString' @@ -4206,6 +4399,8 @@ def test_query_large_passages_serialization(self): query_large_passages_model_json['fields'] = ['testString'] query_large_passages_model_json['count'] = 100 query_large_passages_model_json['characters'] = 50 + query_large_passages_model_json['find_answers'] = True + query_large_passages_model_json['max_answers_per_passage'] = 38 # Construct a model instance of QueryLargePassages by calling from_dict on the json representation query_large_passages_model = QueryLargePassages.from_dict(query_large_passages_model_json) @@ -4296,7 +4491,7 @@ def test_query_notices_response_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = '2020-01-28T18:40:40.123456Z' + notice_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) notice_model['document_id'] = 'testString' notice_model['collection_id'] = 'testString' notice_model['query_id'] = 'testString' @@ -4341,11 +4536,19 @@ def test_query_response_serialization(self): query_result_metadata_model['collection_id'] = 'testString' query_result_metadata_model['confidence'] = 72.5 + result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model['answer_text'] = 'testString' + result_passage_answer_model['start_offset'] = 38 + result_passage_answer_model['end_offset'] = 38 + result_passage_answer_model['confidence'] = 0 + query_result_passage_model = {} # QueryResultPassage query_result_passage_model['passage_text'] = 'testString' query_result_passage_model['start_offset'] = 38 query_result_passage_model['end_offset'] = 38 query_result_passage_model['field'] = 'testString' + query_result_passage_model['confidence'] = 0 + query_result_passage_model['answers'] = [result_passage_answer_model] query_result_model = {} # QueryResult query_result_model['document_id'] = 'testString' @@ -4483,6 +4686,8 @@ def test_query_response_serialization(self): query_response_passage_model['start_offset'] = 38 query_response_passage_model['end_offset'] = 38 query_response_passage_model['field'] = 'testString' + query_response_passage_model['confidence'] = 0 + query_response_passage_model['answers'] = [result_passage_answer_model] # Construct a json representation of a QueryResponse model query_response_model_json = {} @@ -4520,6 +4725,14 @@ def test_query_response_passage_serialization(self): Test serialization/deserialization for QueryResponsePassage """ + # Construct dict forms of any model objects needed in order to build this model. + + result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model['answer_text'] = 'testString' + result_passage_answer_model['start_offset'] = 38 + result_passage_answer_model['end_offset'] = 38 + result_passage_answer_model['confidence'] = 0 + # Construct a json representation of a QueryResponsePassage model query_response_passage_model_json = {} query_response_passage_model_json['passage_text'] = 'testString' @@ -4529,6 +4742,8 @@ def test_query_response_passage_serialization(self): query_response_passage_model_json['start_offset'] = 38 query_response_passage_model_json['end_offset'] = 38 query_response_passage_model_json['field'] = 'testString' + query_response_passage_model_json['confidence'] = 0 + query_response_passage_model_json['answers'] = [result_passage_answer_model] # Construct a model instance of QueryResponsePassage by calling from_dict on the json representation query_response_passage_model = QueryResponsePassage.from_dict(query_response_passage_model_json) @@ -4562,11 +4777,19 @@ def test_query_result_serialization(self): query_result_metadata_model['collection_id'] = 'testString' query_result_metadata_model['confidence'] = 72.5 + result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model['answer_text'] = 'testString' + result_passage_answer_model['start_offset'] = 38 + result_passage_answer_model['end_offset'] = 38 + result_passage_answer_model['confidence'] = 0 + query_result_passage_model = {} # QueryResultPassage query_result_passage_model['passage_text'] = 'testString' query_result_passage_model['start_offset'] = 38 query_result_passage_model['end_offset'] = 38 query_result_passage_model['field'] = 'testString' + query_result_passage_model['confidence'] = 0 + query_result_passage_model['answers'] = [result_passage_answer_model] # Construct a json representation of a QueryResult model query_result_model_json = {} @@ -4632,12 +4855,22 @@ def test_query_result_passage_serialization(self): Test serialization/deserialization for QueryResultPassage """ + # Construct dict forms of any model objects needed in order to build this model. + + result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model['answer_text'] = 'testString' + result_passage_answer_model['start_offset'] = 38 + result_passage_answer_model['end_offset'] = 38 + result_passage_answer_model['confidence'] = 0 + # Construct a json representation of a QueryResultPassage model query_result_passage_model_json = {} query_result_passage_model_json['passage_text'] = 'testString' query_result_passage_model_json['start_offset'] = 38 query_result_passage_model_json['end_offset'] = 38 query_result_passage_model_json['field'] = 'testString' + query_result_passage_model_json['confidence'] = 0 + query_result_passage_model_json['answers'] = [result_passage_answer_model] # Construct a model instance of QueryResultPassage by calling from_dict on the json representation query_result_passage_model = QueryResultPassage.from_dict(query_result_passage_model_json) @@ -4931,6 +5164,38 @@ def test_query_top_hits_aggregation_result_serialization(self): query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json +class TestResultPassageAnswer(): + """ + Test Class for ResultPassageAnswer + """ + + def test_result_passage_answer_serialization(self): + """ + Test serialization/deserialization for ResultPassageAnswer + """ + + # Construct a json representation of a ResultPassageAnswer model + result_passage_answer_model_json = {} + result_passage_answer_model_json['answer_text'] = 'testString' + result_passage_answer_model_json['start_offset'] = 38 + result_passage_answer_model_json['end_offset'] = 38 + result_passage_answer_model_json['confidence'] = 0 + + # Construct a model instance of ResultPassageAnswer by calling from_dict on the json representation + result_passage_answer_model = ResultPassageAnswer.from_dict(result_passage_answer_model_json) + assert result_passage_answer_model != False + + # Construct a model instance of ResultPassageAnswer by calling from_dict on the json representation + result_passage_answer_model_dict = ResultPassageAnswer.from_dict(result_passage_answer_model_json).__dict__ + result_passage_answer_model2 = ResultPassageAnswer(**result_passage_answer_model_dict) + + # Verify the model instances are equivalent + assert result_passage_answer_model == result_passage_answer_model2 + + # Convert model instance back to dict and verify no loss of data + result_passage_answer_model_json2 = result_passage_answer_model.to_dict() + assert result_passage_answer_model_json2 == result_passage_answer_model_json + class TestRetrievalDetails(): """ Test Class for RetrievalDetails @@ -5649,8 +5914,8 @@ def test_training_example_serialization(self): training_example_model_json['document_id'] = 'testString' training_example_model_json['collection_id'] = 'testString' training_example_model_json['relevance'] = 38 - training_example_model_json['created'] = '2020-01-28T18:40:40.123456Z' - training_example_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + training_example_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_example_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of TrainingExample by calling from_dict on the json representation training_example_model = TrainingExample.from_dict(training_example_model_json) @@ -5683,16 +5948,16 @@ def test_training_query_serialization(self): training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_example_model['created'] = '2020-01-28T18:40:40.123456Z' - training_example_model['updated'] = '2020-01-28T18:40:40.123456Z' + training_example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a json representation of a TrainingQuery model training_query_model_json = {} training_query_model_json['query_id'] = 'testString' training_query_model_json['natural_language_query'] = 'testString' training_query_model_json['filter'] = 'testString' - training_query_model_json['created'] = '2020-01-28T18:40:40.123456Z' - training_query_model_json['updated'] = '2020-01-28T18:40:40.123456Z' + training_query_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_query_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) training_query_model_json['examples'] = [training_example_model] # Construct a model instance of TrainingQuery by calling from_dict on the json representation @@ -5726,15 +5991,15 @@ def test_training_query_set_serialization(self): training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_example_model['created'] = '2020-01-28T18:40:40.123456Z' - training_example_model['updated'] = '2020-01-28T18:40:40.123456Z' + training_example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) training_query_model = {} # TrainingQuery training_query_model['query_id'] = 'testString' training_query_model['natural_language_query'] = 'testString' training_query_model['filter'] = 'testString' - training_query_model['created'] = '2020-01-28T18:40:40.123456Z' - training_query_model['updated'] = '2020-01-28T18:40:40.123456Z' + training_query_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_query_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) training_query_model['examples'] = [training_example_model] # Construct a json representation of a TrainingQuerySet model From 06008553bdae0d2c0768d41a1d1878523e5bd810 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 20 May 2021 12:47:08 -0400 Subject: [PATCH 318/455] feat(stt-tts): generation release changes --- ibm_watson/speech_to_text_v1.py | 407 ++++-- ibm_watson/speech_to_text_v1_adapter.py | 403 +++--- ibm_watson/text_to_speech_v1.py | 1523 +++++++++++++++++++- resources/tts_audio.wav | Bin 0 -> 75726 bytes test/integration/test_text_to_speech_v1.py | 29 + test/unit/test_speech_to_text_v1.py | 383 ++--- test/unit/test_text_to_speech_v1.py | 1123 +++++++++++++-- 7 files changed, 3231 insertions(+), 637 deletions(-) create mode 100644 resources/tts_audio.wav diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 97716c530..b29557c08 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2015, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,14 +14,19 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's speech-recognition capabilities to produce transcripts of spoken audio. The service can transcribe speech from various languages and audio formats. In addition to basic transcription, the service can produce detailed information about many different aspects -of the audio. For most languages, the service supports two sampling rates, broadband and -narrowband. It returns all JSON response content in the UTF-8 character set. +of the audio. It returns all JSON response content in the UTF-8 character set. +The service supports two types of models: previous-generation models that include the +terms `Broadband` and `Narrowband` in their names, and beta next-generation models that +include the terms `Multimedia` and `Telephony` in their names. Broadband and multimedia +models have minimum sampling rates of 16 kHz. Narrowband and telephony models have minimum +sampling rates of 8 kHz. The beta next-generation models currently support fewer languages +and features, but they offer high throughput and greater transcription accuracy. For speech recognition, the service supports synchronous and asynchronous HTTP Representational State Transfer (REST) interfaces. It also supports a WebSocket interface that provides a full-duplex, low-latency communication channel: Clients send requests and @@ -32,8 +37,9 @@ language model customization, the service also supports grammars. A grammar is a formal language specification that lets you restrict the phrases that the service can recognize. Language model customization and acoustic model customization are generally available for -production use with all language models that are generally available. Grammars are beta -functionality for all language models that support language model customization. +production use with all previous-generation models that are generally available. Grammars +are beta functionality for all previous-generation models that support language model +customization. Next-generation models do not support customization at this time. """ from enum import Enum @@ -89,8 +95,8 @@ def list_models(self, **kwargs) -> DetailedResponse: information includes the name of the model and its minimum sampling rate in Hertz, among other things. The ordering of the list of models can change from call to call; do not rely on an alphabetized or static list of models. - **See also:** [Languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). + **See also:** [Listing + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -120,11 +126,12 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: Gets information for a single specified language model that is available for use 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/speech-to-text?topic=speech-to-text-models#models). + **See also:** [Listing + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list). :param str model_id: The identifier of the model in the form of its name - from the output of the **Get a model** method. + from the output of the **Get a model** method. (**Note:** The model + `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SpeechModel` object @@ -182,6 +189,7 @@ def recognize(self, split_transcript_at_phrase_end: bool = None, speech_detector_sensitivity: float = None, background_audio_suppression: float = None, + low_latency: bool = None, **kwargs) -> DetailedResponse: """ Recognize audio. @@ -240,8 +248,33 @@ def recognize(self, required rate, the service down-samples the audio to the appropriate rate. If the sampling rate of the audio is lower than the minimum required rate, the request fails. - **See also:** [Audio - formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). + **See also:** [Supported audio + formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats). + ### Next-generation models + **Note:** The next-generation language models are beta functionality. They + support a limited number of languages and features at this time. The supported + languages, models, and features will increase with future releases. + The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 kHz) + models for many languages. Next-generation models have higher throughput than the + service's previous generation of `Broadband` and `Narrowband` models. When you use + next-generation models, the service can return transcriptions more quickly and + also provide noticeably better transcription accuracy. + You specify a next-generation model by using the `model` query parameter, as you + do a previous-generation model. Next-generation models support the same request + headers as previous-generation models, but they support only the following + additional query parameters: + * `background_audio_suppression` + * `inactivity_timeout` + * `profanity_filter` + * `redaction` + * `smart_formatting` + * `speaker_labels` + * `speech_detector_sensitivity` + * `timestamps` + Many next-generation models also support the beta `low_latency` parameter, which + is not available with previous-generation models. + **See also:** [Next-generation languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). ### 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. @@ -261,15 +294,19 @@ def recognize(self, For more information about specifying an audio format, see **Audio formats (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/speech-to-text?topic=speech-to-text-models#models). + for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is + deprecated; use `ar-MS_BroadbandModel` instead.) See [Languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) + and [Next-generation languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). :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/speech-to-text?topic=speech-to-text-input#custom-input). + model. By default, no custom language model is used. See [Using a custom + language model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse). **Note:** Use this parameter instead of the deprecated `customization_id` parameter. :param str acoustic_customization_id: (optional) The customization ID @@ -277,15 +314,17 @@ def recognize(self, request. The base model of the specified custom acoustic 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 acoustic model is used. See [Custom - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#custom-input). + model. By default, no custom acoustic model is used. See [Using a custom + acoustic model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acousticUse). :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/speech-to-text?topic=speech-to-text-input#version). + the parameter is used with or without a custom model. See [Making speech + recognition requests with upgraded custom + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade-use#custom-upgrade-use-recognition). :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 @@ -300,8 +339,8 @@ def recognize(self, Use caution when setting the weight: a higher value can improve the 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/speech-to-text?topic=speech-to-text-input#custom-input). + See [Using customization + weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). :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 @@ -319,39 +358,39 @@ def recognize(self, effective length for double-byte languages might be shorter. Keywords are case-insensitive. See [Keyword - spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#keyword_spotting). + spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#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/speech-to-text?topic=speech-to-text-output#keyword_spotting). + spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#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/speech-to-text?topic=speech-to-text-output#max_alternatives). + alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#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/speech-to-text?topic=speech-to-text-output#word_alternatives). + alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#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/speech-to-text?topic=speech-to-text-output#word_confidence). + confidence](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#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/speech-to-text?topic=speech-to-text-output#word_timestamps). + timestamps](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#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/speech-to-text?topic=speech-to-text-output#profanity_filter). + `false` to return results with no censoring. Applies to US English and + Japanese transcription only. See [Profanity + filtering](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#profanity-filtering). :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 @@ -360,17 +399,20 @@ 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/speech-to-text?topic=speech-to-text-output#smart_formatting). + formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#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. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - **Note:** Applies to US English, Australian English, German, Japanese, - Korean, and Spanish (both broadband and narrowband models) and UK English - (narrowband model) transcription only. - See [Speaker - labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#speaker_labels). + * For previous-generation models, can be used for US English, Australian + English, German, Japanese, Korean, and Spanish (both broadband and + narrowband models) and UK English (narrowband model) transcription only. + * For next-generation models, can be used for English (Australian, UK, and + US), German, and Spanish transcription only. + Restrictions and limitations apply to the use of speaker labels for both + types of models. See [Speaker + labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-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 @@ -381,7 +423,8 @@ 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/speech-to-text?topic=speech-to-text-input#grammars-input). + [Using a grammar for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUse). :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` @@ -395,13 +438,13 @@ def recognize(self, be `1`). **Note:** Applies to US English, Japanese, and Korean transcription only. See [Numeric - redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#redaction). + redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#numeric-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/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 @@ -416,7 +459,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/speech-to-text?topic=speech-to-text-output#silence_time). + time](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#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 @@ -426,7 +469,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/speech-to-text?topic=speech-to-text-output#split_transcript). + end](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#split-transcript). :param float speech_detector_sensitivity: (optional) The sensitivity of speech activity detection that the service is to perform. Use the parameter to suppress word insertions from music, coughing, and other non-speech @@ -438,8 +481,8 @@ def recognize(self, * 0.5 (the default) provides a reasonable compromise for the level of sensitivity. * 1.0 suppresses no audio (speech detection sensitivity is disabled). - The values increase on a monotonic curve. See [Speech Activity - Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). + The values increase on a monotonic curve. See [Speech detector + sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity). :param float background_audio_suppression: (optional) The level to which the service is to suppress background audio based on its volume to prevent it from being transcribed as speech. Use the parameter to suppress side @@ -449,8 +492,24 @@ def recognize(self, is disabled). * 0.5 provides a reasonable level of audio suppression for general usage. * 1.0 suppresses all audio (no audio is transcribed). - The values increase on a monotonic curve. See [Speech Activity - Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). + The values increase on a monotonic curve. See [Background audio + suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression). + :param bool low_latency: (optional) If `true` for next-generation + `Multimedia` and `Telephony` models that support low latency, directs the + service to produce results even more quickly than it usually does. + Next-generation models produce transcription results faster than + previous-generation models. The `low_latency` parameter causes the models + to produce results even more quickly, though the results might be less + accurate when the parameter is used. + **Note:** The parameter is beta functionality. It is not available for + previous-generation `Broadband` and `Narrowband` models. It is available + only for some next-generation models. + * For a list of next-generation models that support low latency, see + [Supported language + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported) + for next-generation models. + * For more information about the `low_latency` parameter, see [Low + latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SpeechRecognitionResults` object @@ -487,7 +546,8 @@ def recognize(self, 'end_of_phrase_silence_time': end_of_phrase_silence_time, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, - 'background_audio_suppression': background_audio_suppression + 'background_audio_suppression': background_audio_suppression, + 'low_latency': low_latency } data = audio @@ -659,6 +719,7 @@ def create_job(self, split_transcript_at_phrase_end: bool = None, speech_detector_sensitivity: float = None, background_audio_suppression: float = None, + low_latency: bool = None, **kwargs) -> DetailedResponse: """ Create a job. @@ -743,16 +804,44 @@ def create_job(self, required rate, the service down-samples the audio to the appropriate rate. If the sampling rate of the audio is lower than the minimum required rate, the request fails. - **See also:** [Audio - formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). + **See also:** [Supported audio + formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats). + ### Next-generation models + **Note:** The next-generation language models are beta functionality. They + support a limited number of languages and features at this time. The supported + languages, models, and features will increase with future releases. + The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 kHz) + models for many languages. Next-generation models have higher throughput than the + service's previous generation of `Broadband` and `Narrowband` models. When you use + next-generation models, the service can return transcriptions more quickly and + also provide noticeably better transcription accuracy. + You specify a next-generation model by using the `model` query parameter, as you + do a previous-generation model. Next-generation models support the same request + headers as previous-generation models, but they support only the following + additional query parameters: + * `background_audio_suppression` + * `inactivity_timeout` + * `profanity_filter` + * `redaction` + * `smart_formatting` + * `speaker_labels` + * `speech_detector_sensitivity` + * `timestamps` + Many next-generation models also support the beta `low_latency` parameter, which + is not available with previous-generation models. + **See also:** [Next-generation languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). :param BinaryIO audio: The audio to transcribe. :param str content_type: (optional) The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (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/speech-to-text?topic=speech-to-text-models#models). + for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is + deprecated; use `ar-MS_BroadbandModel` instead.) See [Languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) + and [Next-generation languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). :param str callback_url: (optional) A URL to which callback notifications are to be sent. The URL must already be successfully allowlisted by using the **Register a callback** method. You can include the same callback URL @@ -794,8 +883,9 @@ def create_job(self, 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/speech-to-text?topic=speech-to-text-input#custom-input). + model. By default, no custom language model is used. See [Using a custom + language model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse). **Note:** Use this parameter instead of the deprecated `customization_id` parameter. :param str acoustic_customization_id: (optional) The customization ID @@ -803,15 +893,17 @@ def create_job(self, request. The base model of the specified custom acoustic 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 acoustic model is used. See [Custom - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#custom-input). + model. By default, no custom acoustic model is used. See [Using a custom + acoustic model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acousticUse). :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/speech-to-text?topic=speech-to-text-input#version). + the parameter is used with or without a custom model. See [Making speech + recognition requests with upgraded custom + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade-use#custom-upgrade-use-recognition). :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 @@ -826,8 +918,8 @@ def create_job(self, Use caution when setting the weight: a higher value can improve the 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/speech-to-text?topic=speech-to-text-input#custom-input). + See [Using customization + weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). :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 @@ -845,39 +937,39 @@ def create_job(self, effective length for double-byte languages might be shorter. Keywords are case-insensitive. See [Keyword - spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#keyword_spotting). + spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#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/speech-to-text?topic=speech-to-text-output#keyword_spotting). + spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#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/speech-to-text?topic=speech-to-text-output#max_alternatives). + alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#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/speech-to-text?topic=speech-to-text-output#word_alternatives). + alternatives](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#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/speech-to-text?topic=speech-to-text-output#word_confidence). + confidence](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#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/speech-to-text?topic=speech-to-text-output#word_timestamps). + timestamps](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-metadata#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/speech-to-text?topic=speech-to-text-output#profanity_filter). + `false` to return results with no censoring. Applies to US English and + Japanese transcription only. See [Profanity + filtering](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#profanity-filtering). :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 @@ -886,17 +978,20 @@ 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/speech-to-text?topic=speech-to-text-output#smart_formatting). + formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#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. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - **Note:** Applies to US English, Australian English, German, Japanese, - Korean, and Spanish (both broadband and narrowband models) and UK English - (narrowband model) transcription only. - See [Speaker - labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#speaker_labels). + * For previous-generation models, can be used for US English, Australian + English, German, Japanese, Korean, and Spanish (both broadband and + narrowband models) and UK English (narrowband model) transcription only. + * For next-generation models, can be used for English (Australian, UK, and + US), German, and Spanish transcription only. + Restrictions and limitations apply to the use of speaker labels for both + types of models. See [Speaker + labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-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 @@ -907,7 +1002,8 @@ 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/speech-to-text?topic=speech-to-text-input#grammars-input). + [Using a grammar for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUse). :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` @@ -921,7 +1017,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/speech-to-text?topic=speech-to-text-output#redaction). + redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#numeric-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 @@ -929,7 +1025,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/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 @@ -943,13 +1039,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/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/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 @@ -964,7 +1060,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/speech-to-text?topic=speech-to-text-output#silence_time). + time](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#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 @@ -974,7 +1070,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/speech-to-text?topic=speech-to-text-output#split_transcript). + end](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#split-transcript). :param float speech_detector_sensitivity: (optional) The sensitivity of speech activity detection that the service is to perform. Use the parameter to suppress word insertions from music, coughing, and other non-speech @@ -986,8 +1082,8 @@ def create_job(self, * 0.5 (the default) provides a reasonable compromise for the level of sensitivity. * 1.0 suppresses no audio (speech detection sensitivity is disabled). - The values increase on a monotonic curve. See [Speech Activity - Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). + The values increase on a monotonic curve. See [Speech detector + sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity). :param float background_audio_suppression: (optional) The level to which the service is to suppress background audio based on its volume to prevent it from being transcribed as speech. Use the parameter to suppress side @@ -997,8 +1093,24 @@ def create_job(self, is disabled). * 0.5 provides a reasonable level of audio suppression for general usage. * 1.0 suppresses all audio (no audio is transcribed). - The values increase on a monotonic curve. See [Speech Activity - Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). + The values increase on a monotonic curve. See [Background audio + suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression). + :param bool low_latency: (optional) If `true` for next-generation + `Multimedia` and `Telephony` models that support low latency, directs the + service to produce results even more quickly than it usually does. + Next-generation models produce transcription results faster than + previous-generation models. The `low_latency` parameter causes the models + to produce results even more quickly, though the results might be less + accurate when the parameter is used. + **Note:** The parameter is beta functionality. It is not available for + previous-generation `Broadband` and `Narrowband` models. It is available + only for some next-generation models. + * For a list of next-generation models that support low latency, see + [Supported language + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported) + for next-generation models. + * For more information about the `low_latency` parameter, see [Low + latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `RecognitionJob` object @@ -1041,7 +1153,8 @@ def create_job(self, 'end_of_phrase_silence_time': end_of_phrase_silence_time, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, - 'background_audio_suppression': background_audio_suppression + 'background_audio_suppression': background_audio_suppression, + 'low_latency': low_latency } data = audio @@ -1299,7 +1412,8 @@ def list_language_models(self, :param str language: (optional) The identifier of the language for which custom language or custom acoustic models are to be returned. Omit the parameter to see all custom language or custom acoustic models that are - owned by the requesting credentials. + owned by the requesting credentials. (**Note:** The identifier `ar-AR` is + deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). @@ -1477,6 +1591,8 @@ def train_language_model(self, The value that you assign is used for all recognition requests that use the model. You can override it for any recognition request by specifying a customization weight for that request. + See [Using customization + weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object @@ -1577,7 +1693,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/speech-to-text?topic=speech-to-text-customUpgrade#upgradeLanguage). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-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 @@ -2587,7 +2703,8 @@ def create_acoustic_model(self, `Mobile custom model` or `Noisy car custom model`. :param str base_model_name: The name of the base language model that is to be customized by the new custom acoustic model. The new custom model can be - used only with the base model that it customizes. + used only with the base model that it customizes. (**Note:** The model + `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) To determine whether a base model supports acoustic model customization, refer to [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). @@ -2649,7 +2766,8 @@ def list_acoustic_models(self, :param str language: (optional) The identifier of the language for which custom language or custom acoustic models are to be returned. Omit the parameter to see all custom language or custom acoustic models that are - owned by the requesting credentials. + owned by the requesting credentials. (**Note:** The identifier `ar-AR` is + deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). @@ -2949,7 +3067,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/speech-to-text?topic=speech-to-text-customUpgrade#upgradeAcoustic). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-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 @@ -2967,7 +3085,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/speech-to-text?topic=speech-to-text-customUpgrade#upgradeAcoustic). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-acoustic). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3123,8 +3241,8 @@ def add_audio(self, minimum required rate, the service down-samples the audio to the appropriate rate. 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/speech-to-text?topic=speech-to-text-audio-formats#audio-formats). + **See also:** [Supported audio + formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-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 @@ -3409,18 +3527,26 @@ class GetModelEnums: class ModelId(str, Enum): """ The identifier of the model in the form of its name from the output of the **Get a - model** method. + model** method. (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use + `ar-MS_BroadbandModel` instead.). """ AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' + AR_MS_TELEPHONY = 'ar-MS_Telephony' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + DE_DE_TELEPHONY = 'de-DE_Telephony' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' + EN_AU_TELEPHONY = 'en-AU_Telephony' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' + EN_GB_TELEPHONY = 'en-GB_Telephony' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' + EN_US_MULTIMEDIA = 'en-US_Multimedia' EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' + EN_US_TELEPHONY = 'en-US_Telephony' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' @@ -3429,16 +3555,20 @@ class ModelId(str, Enum): ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' + ES_ES_TELEPHONY = 'es-ES_Telephony' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' + FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + FR_FR_TELEPHONY = 'fr-FR_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' @@ -3447,6 +3577,7 @@ class ModelId(str, Enum): NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' + PT_BR_TELEPHONY = 'pt-BR_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' @@ -3480,20 +3611,30 @@ class ContentType(str, Enum): class Model(str, Enum): """ - The identifier of the model that is to be used for the recognition request. See - [Languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). + The identifier of the model that is to be used for the recognition request. + (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use + `ar-MS_BroadbandModel` instead.) See [Languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) and + [Next-generation languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). """ AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' + AR_MS_TELEPHONY = 'ar-MS_Telephony' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + DE_DE_TELEPHONY = 'de-DE_Telephony' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' + EN_AU_TELEPHONY = 'en-AU_Telephony' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' + EN_GB_TELEPHONY = 'en-GB_Telephony' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' + EN_US_MULTIMEDIA = 'en-US_Multimedia' EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' + EN_US_TELEPHONY = 'en-US_Telephony' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' @@ -3502,16 +3643,20 @@ class Model(str, Enum): ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' + ES_ES_TELEPHONY = 'es-ES_Telephony' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' + FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + FR_FR_TELEPHONY = 'fr-FR_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' @@ -3520,6 +3665,7 @@ class Model(str, Enum): NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' + PT_BR_TELEPHONY = 'pt-BR_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' @@ -3553,20 +3699,30 @@ class ContentType(str, Enum): class Model(str, Enum): """ - The identifier of the model that is to be used for the recognition request. See - [Languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models#models). + The identifier of the model that is to be used for the recognition request. + (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use + `ar-MS_BroadbandModel` instead.) See [Languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) and + [Next-generation languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). """ AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' + AR_MS_TELEPHONY = 'ar-MS_Telephony' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' + DE_DE_TELEPHONY = 'de-DE_Telephony' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' + EN_AU_TELEPHONY = 'en-AU_Telephony' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' + EN_GB_TELEPHONY = 'en-GB_Telephony' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' + EN_US_MULTIMEDIA = 'en-US_Multimedia' EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' + EN_US_TELEPHONY = 'en-US_Telephony' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' @@ -3575,16 +3731,20 @@ class Model(str, Enum): ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' + ES_ES_TELEPHONY = 'es-ES_Telephony' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' + FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' + FR_FR_TELEPHONY = 'fr-FR_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' @@ -3593,6 +3753,7 @@ class Model(str, Enum): NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' + PT_BR_TELEPHONY = 'pt-BR_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' @@ -3631,12 +3792,14 @@ class Language(str, Enum): """ The identifier of the language for which custom language or custom acoustic models are to be returned. Omit the parameter to see all custom language or custom - acoustic models that are owned by the requesting credentials. + acoustic models that are owned by the requesting credentials. (**Note:** The + identifier `ar-AR` is deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). """ AR_AR = 'ar-AR' + AR_MS = 'ar-MS' DE_DE = 'de-DE' EN_AU = 'en-AU' EN_GB = 'en-GB' @@ -3735,12 +3898,14 @@ class Language(str, Enum): """ The identifier of the language for which custom language or custom acoustic models are to be returned. Omit the parameter to see all custom language or custom - acoustic models that are owned by the requesting credentials. + acoustic models that are owned by the requesting credentials. (**Note:** The + identifier `ar-AR` is deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). """ AR_AR = 'ar-AR' + AR_MS = 'ar-MS' DE_DE = 'de-DE' EN_AU = 'en-AU' EN_GB = 'en-GB' @@ -6888,8 +7053,10 @@ class SpeechRecognitionAlternative(): :attr str transcript: A transcription of the audio. :attr float confidence: (optional) A score that indicates the service's - confidence in the transcript in the range of 0.0 to 1.0. A confidence score is - returned only for the best alternative and only with results marked as final. + confidence in the transcript in the range of 0.0 to 1.0. For speech recognition + with previous-generation models, a confidence score is returned only for the + best alternative and only with results marked as final. For speech recognition + with next-generation models, a confidence score is never returned. :attr List[str] timestamps: (optional) Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds, for example: @@ -6913,9 +7080,11 @@ def __init__(self, :param str transcript: A transcription of the audio. :param float confidence: (optional) A score that indicates the service's - confidence in the transcript in the range of 0.0 to 1.0. A confidence score - is returned only for the best alternative and only with results marked as - final. + confidence in the transcript in the range of 0.0 to 1.0. For speech + recognition with previous-generation models, a confidence score is returned + only for the best alternative and only with results marked as final. For + speech recognition with next-generation models, a confidence score is never + returned. :param List[str] timestamps: (optional) Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds, for @@ -7338,10 +7507,17 @@ class SupportedFeatures(): supported only for US English, Australian English, German, Japanese, Korean, and Spanish (both broadband and narrowband models) and UK English (narrowband model only). Speaker labels are not supported for any other models. + :attr bool low_latency: (optional) Indicates whether the `low_latency` parameter + can be used with a next-generation language model. The field is returned only + for next-generation models. Previous-generation models do not support the + `low_latency` parameter. """ - def __init__(self, custom_language_model: bool, - speaker_labels: bool) -> None: + def __init__(self, + custom_language_model: bool, + speaker_labels: bool, + *, + low_latency: bool = None) -> None: """ Initialize a SupportedFeatures object. @@ -7355,9 +7531,14 @@ def __init__(self, custom_language_model: bool, Korean, and Spanish (both broadband and narrowband models) and UK English (narrowband model only). Speaker labels are not supported for any other models. + :param bool low_latency: (optional) Indicates whether the `low_latency` + parameter can be used with a next-generation language model. The field is + returned only for next-generation models. Previous-generation models do not + support the `low_latency` parameter. """ self.custom_language_model = custom_language_model self.speaker_labels = speaker_labels + self.low_latency = low_latency @classmethod def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': @@ -7375,6 +7556,8 @@ def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': raise ValueError( 'Required property \'speaker_labels\' not present in SupportedFeatures JSON' ) + if 'low_latency' in _dict: + args['low_latency'] = _dict.get('low_latency') return cls(**args) @classmethod @@ -7390,6 +7573,8 @@ def to_dict(self) -> Dict: _dict['custom_language_model'] = self.custom_language_model if hasattr(self, 'speaker_labels') and self.speaker_labels is not None: _dict['speaker_labels'] = self.speaker_labels + if hasattr(self, 'low_latency') and self.low_latency is not None: + _dict['low_latency'] = self.low_latency return _dict def _to_dict(self): diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 7cf5087f3..e9119ff72 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2018, 2020. +# (C) Copyright IBM Corp. 2018, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -55,202 +55,238 @@ def recognize_using_websocket(self, split_transcript_at_phrase_end=None, speech_detector_sensitivity=None, background_audio_suppression=None, + low_latency=None, **kwargs): """ Sends audio for speech recognition using web sockets. + :param AudioSource audio: The audio to transcribe in the format specified by the - `Content-Type` header. + `Content-Type` header. :param str content_type: The type of the input: audio/basic, audio/flac, - audio/l16, audio/mp3, audio/mpeg, audio/mulaw, audio/ogg, audio/ogg;codecs=opus, - audio/ogg;codecs=vorbis, audio/wav, audio/webm, audio/webm;codecs=opus, or - audio/webm;codecs=vorbis. + audio/l16, audio/mp3, audio/mpeg, audio/mulaw, audio/ogg, audio/ogg;codecs=opus, + audio/ogg;codecs=vorbis, audio/wav, audio/webm, audio/webm;codecs=opus, or + audio/webm;codecs=vorbis. :param RecognizeCallback recognize_callback: The callback method for the websocket. - :param str model: The identifier of the model that is to be used for the - recognition request or, for the **Create a session** method, with the new session. - :param str language_customization_id: 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 service credentials created 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/speech-to-text?topic=speech-to-text-input#custom). - **Note:** Use this parameter instead of the deprecated `customization_id` - parameter. - :param str acoustic_customization_id: The customization ID (GUID) of a custom - acoustic model that is to be used with the recognition request or, for the - **Create a session** method, with the new session. The base model of the specified - custom acoustic model must match the model specified with the `model` parameter. - You must make the request with service credentials created for the instance of the - service that owns the custom model. By default, no custom acoustic model is used. - :param float customization_weight: If you specify the customization ID (GUID) of a - custom language model with the recognition request or, for sessions, with the - **Create a session** method, the customization weight tells the service how much - weight to give to words from the custom language model compared to those from the - base model for the current request. - Specify a value between 0.0 and 1.0. Unless a different customization weight was - specified for the custom model when it was trained, the default value is 0.3. A - customization weight that you specify overrides a weight that was specified when - the custom model was trained. - The default value yields the best performance in general. Assign a higher value if - your audio makes frequent use of OOV words from the custom model. Use caution when - setting the weight: a higher value can improve the accuracy of phrases from the - custom model's domain, but it can negatively affect performance on non-domain - phrases. - :param str base_model_version: The version of the specified base model that is to - be used with recognition request or, for the **Create a session** method, with the - new session. 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. For more - information, see [Base model - version](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#version). - :param int inactivity_timeout: The time in seconds after which, if only silence - (no speech) is detected in submitted audio, the connection is closed with a 400 - error. Useful for stopping audio submission from a live microphone when a user - simply walks away. Use `-1` for infinity. + :param str model: (optional) The identifier of the model that is to be used + for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is + deprecated; use `ar-MS_BroadbandModel` instead.) See [Languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) + and [Next-generation languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). + :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 [Using a custom + language model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse). + **Note:** Use this parameter instead of the deprecated `customization_id` + parameter. + :param str acoustic_customization_id: (optional) The customization ID + (GUID) of a custom acoustic model that is to be used with the recognition + request. The base model of the specified custom acoustic 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 acoustic model is used. See [Using a custom + acoustic model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acousticUse). + :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 [Making speech + recognition requests with upgraded custom + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade-use#custom-upgrade-use-recognition). + :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 + to words from the custom language model compared to those from the base + model for the current request. + Specify a value between 0.0 and 1.0. Unless a different customization + weight was specified for the custom model when it was trained, the default + value is 0.3. A customization weight that you specify overrides a weight + that was specified when the custom model was trained. + The default value yields the best performance in general. Assign a higher + value if your audio makes frequent use of OOV words from the custom model. + Use caution when setting the weight: a higher value can improve the + accuracy of phrases from the custom model's domain, but it can negatively + affect performance on non-domain phrases. + See [Using customization + weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). + :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/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. - Omit the parameter or specify an empty array if you do not need to spot - keywords. - You can spot a maximum of 1000 keywords with a single request. A single - keyword can have a maximum length of 1024 characters, though the maximum - effective length for double-byte languages might be shorter. Keywords are - case-insensitive. - See [Keyword - spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#keyword_spotting). - :param float keywords_threshold: 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 and 1 - inclusive. No keyword spotting is performed if you omit the parameter. If you - specify a threshold, you must also specify one or more keywords. - :param int max_alternatives: The maximum number of alternative transcripts to be - returned. By default, a single transcription is returned. - :param float word_alternatives_threshold: 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 and 1 - inclusive. No alternative words are computed if you omit the parameter. - :param bool word_confidence: If `true`, a confidence measure in the range of 0 to - 1 is returned for each word. By default, no word confidence measures are returned. - :param bool timestamps: If `true`, time alignment is returned for each word. By - default, no timestamps are returned. - :param bool profanity_filter: If `true` (the default), 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. - :param bool smart_formatting: If `true`, converts dates, times, series of digits - and numbers, phone numbers, currency values, and internet addresses into more - readable, conventional representations in the final transcript of a recognition - request. For US English, also converts certain keyword strings to punctuation - symbols. By default, no smart formatting is performed. Applies to US English and - Spanish transcription only. + 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. + Omit the parameter or specify an empty array if you do not need to spot + keywords. + You can spot a maximum of 1000 keywords with a single request. A single + keyword can have a maximum length of 1024 characters, though the maximum + effective length for double-byte languages might be shorter. Keywords are + case-insensitive. + See [Keyword + spotting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-spotting#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/speech-to-text?topic=speech-to-text-spotting#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/speech-to-text?topic=speech-to-text-metadata#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/speech-to-text?topic=speech-to-text-spotting#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/speech-to-text?topic=speech-to-text-metadata#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/speech-to-text?topic=speech-to-text-metadata#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 and + Japanese transcription only. See [Profanity + filtering](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#profanity-filtering). + :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 + the final transcript of a recognition request. For US English, the service + also converts certain keyword strings to punctuation symbols. By default, + the service performs no smart formatting. + **Note:** Applies to US English, Japanese, and Spanish transcription only. + See [Smart + formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#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. - Setting `speaker_labels` to `true` forces the `timestamps` parameter to be - `true`, regardless of whether you specify `false` for the parameter. - **Note:** Applies to US English, German, Japanese, Korean, and Spanish - (both broadband and narrowband models) and UK English (narrowband model) - transcription only. To determine whether a language model supports speaker - labels, you can also 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/speech-to-text?topic=speech-to-text-output#speaker_labels). + labels that identify which words were spoken by which participants in a + multi-person exchange. By default, the service returns no speaker labels. + Setting `speaker_labels` to `true` forces the `timestamps` parameter to be + `true`, regardless of whether you specify `false` for the parameter. + * For previous-generation models, can be used for US English, Australian + English, German, Japanese, Korean, and Spanish (both broadband and + narrowband models) and UK English (narrowband model) transcription only. + * For next-generation models, can be used for English (Australian, UK, and + US), German, and Spanish transcription only. + Restrictions and limitations apply to the use of speaker labels for both + types of models. See [Speaker + labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. - :param str customization_id: **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 request. Do not specify both parameters with a - request. - :param str grammar_name: The name of a grammar that is to be used with the - recognition request. If you specify a grammar, you must also use the - `language_customization_id` parameter to specify the name of the 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/speech-to-text?topic=speech-to-text-output). - :param bool redaction: 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` character. It is intended - to redact sensitive numeric data, such as credit card numbers. By default, the - service performs no redaction. - When you enable redaction, the service automatically enables smart formatting, - regardless of whether you explicitly disable that feature. To ensure maximum - security, the service also disables keyword spotting (ignores the `keywords` and - `keywords_threshold` parameters) and returns only a single final transcript - (forces the `max_alternatives` parameter to be `1`). - **Note:** Applies to US English, Japanese, and Korean transcription only. - See [Numeric - redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-output#redaction). - :param bool processing_metrics: 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 `processing_metrics_interval` parameter. It also - returns processing metrics for transcription events, for example, for final and - interim results. By default, the service returns no processing metrics. - :param float processing_metrics_interval: 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 is set to `true`. - The parameter accepts a minimum value of 0.1 seconds. The level of precision is - not restricted, so you can specify values such as 0.25 and 0.125. - The service does not impose a maximum value. If you want to receive processing - metrics only for transcription events instead of at periodic intervals, set the - value to a large number. If the value is larger than the duration of the audio, - the service returns processing metrics only for transcription events. - :param bool audio_metrics: 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. + :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 + request. Do not specify both parameters with a request. + :param str grammar_name: (optional) The name of a grammar that is to be + used with the recognition request. If you specify a grammar, you must also + use the `language_customization_id` parameter to specify the name of the + 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 + [Using a grammar for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUse). + :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` + character. It is intended to redact sensitive numeric data, such as credit + card numbers. By default, the service performs no redaction. + When you enable redaction, the service automatically enables smart + formatting, regardless of whether you explicitly disable that feature. To + ensure maximum security, the service also disables keyword spotting + (ignores the `keywords` and `keywords_threshold` parameters) and returns + only a single final transcript (forces the `max_alternatives` parameter to + be `1`). + **Note:** Applies to US English, Japanese, and Korean transcription only. + See [Numeric + redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#numeric-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/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 - silence before it reaches the end of the audio stream, its response can - include multiple final results. Silence indicates a point at which the - speaker pauses between spoken words or phrases. - Specify a value for the pause interval in the range of 0.0 to 120.0. - * A value greater than 0 specifies the interval that the service is to use - for speech recognition. - * A value of 0 indicates that the service is to use the default interval. - It is equivalent to omitting the parameter. - 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/speech-to-text?topic=speech-to-text-output#silence_time). + the duration of the pause interval at which the service splits a transcript + into multiple final results. If the service detects pauses or extended + silence before it reaches the end of the audio stream, its response can + include multiple final results. Silence indicates a point at which the + speaker pauses between spoken words or phrases. + Specify a value for the pause interval in the range of 0.0 to 120.0. + * A value greater than 0 specifies the interval that the service is to use + for speech recognition. + * A value of 0 indicates that the service is to use the default interval. + It is equivalent to omitting the parameter. + 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/speech-to-text?topic=speech-to-text-parsing#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 - meaningful phrases such as sentences. The service bases its understanding - of semantic features on the base language model that you use with a - request. Custom language models and grammars can also influence how and - 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/speech-to-text?topic=speech-to-text-output#split_transcript). + the service to split the transcript into multiple final results based on + semantic features of the input, for example, at the conclusion of + meaningful phrases such as sentences. The service bases its understanding + of semantic features on the base language model that you use with a + request. Custom language models and grammars can also influence how and + 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/speech-to-text?topic=speech-to-text-parsing#split-transcript). :param float speech_detector_sensitivity: (optional) The sensitivity of - speech activity detection that the service is to perform. Use the parameter - to suppress word insertions from music, coughing, and other non-speech - events. The service biases the audio it passes for speech recognition by - evaluating the input audio against prior models of speech and non-speech - activity. - Specify a value between 0.0 and 1.0: - * 0.0 suppresses all audio (no speech is transcribed). - * 0.5 (the default) provides a reasonable compromise for the level of - sensitivity. - * 1.0 suppresses no audio (speech detection sensitivity is disabled). - The values increase on a monotonic curve. See [Speech Activity - Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). + speech activity detection that the service is to perform. Use the parameter + to suppress word insertions from music, coughing, and other non-speech + events. The service biases the audio it passes for speech recognition by + evaluating the input audio against prior models of speech and non-speech + activity. + Specify a value between 0.0 and 1.0: + * 0.0 suppresses all audio (no speech is transcribed). + * 0.5 (the default) provides a reasonable compromise for the level of + sensitivity. + * 1.0 suppresses no audio (speech detection sensitivity is disabled). + The values increase on a monotonic curve. See [Speech detector + sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity). :param float background_audio_suppression: (optional) The level to which - the service is to suppress background audio based on its volume to prevent - it from being transcribed as speech. Use the parameter to suppress side - conversations or background noise. - Specify a value in the range of 0.0 to 1.0: - * 0.0 (the default) provides no suppression (background audio suppression - is disabled). - * 0.5 provides a reasonable level of audio suppression for general usage. - * 1.0 suppresses all audio (no audio is transcribed). - The values increase on a monotonic curve. See [Speech Activity - Detection](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-input#detection). + the service is to suppress background audio based on its volume to prevent + it from being transcribed as speech. Use the parameter to suppress side + conversations or background noise. + Specify a value in the range of 0.0 to 1.0: + * 0.0 (the default) provides no suppression (background audio suppression + is disabled). + * 0.5 provides a reasonable level of audio suppression for general usage. + * 1.0 suppresses all audio (no audio is transcribed). + The values increase on a monotonic curve. See [Background audio + suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression). + :param bool low_latency: (optional) If `true` for next-generation + `Multimedia` and `Telephony` models that support low latency, directs the + service to produce results even more quickly than it usually does. + Next-generation models produce transcription results faster than + previous-generation models. The `low_latency` parameter causes the models + to produce results even more quickly, though the results might be less + accurate when the parameter is used. + **Note:** The parameter is beta functionality. It is not available for + previous-generation `Broadband` and `Narrowband` models. It is available + only for some next-generation models. + * For a list of next-generation models that support low latency, see + [Supported language + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported) + for next-generation models. + * For more information about the `low_latency` parameter, see [Low + latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). :param dict headers: A `dict` containing the request headers :return: A `dict` containing the `SpeechRecognitionResults` response. :rtype: dict @@ -316,7 +352,8 @@ def recognize_using_websocket(self, 'end_of_phrase_silence_time': end_of_phrase_silence_time, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, - 'background_audio_suppression': background_audio_suppression + 'background_audio_suppression': background_audio_suppression, + 'low_latency': low_latency } options = {k: v for k, v in options.items() if v is not None} request['options'] = options diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 3834a376d..9c8c78ad9 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2015, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, @@ -30,12 +30,16 @@ that, when combined, sound like the word. A phonetic translation is based on the SSML phoneme format for representing a word. You can specify a phonetic translation in standard International Phonetic Alphabet (IPA) representation or in the proprietary IBM Symbolic -Phonetic Representation (SPR). The Arabic, Chinese, Dutch, and Korean languages support -only IPA. +Phonetic Representation (SPR). The Arabic, Chinese, Dutch, Australian English, and Korean +languages support only IPA. +The service also offers a Tune by Example feature that lets you define custom prompts. You +can also define speaker models to improve the quality of your custom prompts. The service +support custom prompts only for US English custom models and voices. """ from enum import Enum -from typing import Dict, List +from os.path import basename +from typing import BinaryIO, Dict, List import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -127,8 +131,31 @@ def get_voice(self, voices** method. **See also:** [Listing a specific 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. + ### Important voice updates + The service's voices underwent significant change on 2 December 2020. + * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural + instead of concatenative. + * The `ar-AR_OmarVoice` voice is deprecated. Use `ar-MS_OmarVoice` voice instead. + * The `ar-AR` language identifier cannot be used to create a custom model. Use the + `ar-MS` identifier instead. + * The standard concatenative voices for the following languages are now + deprecated: Brazilian Portuguese, United Kingdom and United States English, + French, German, Italian, Japanese, and Spanish (all dialects). + * The features expressive SSML, voice transformation SSML, and use of the `volume` + attribute of the `` element are deprecated and are not supported with any + of the service's neural voices. + * All of the service's voices are now customizable and generally available (GA) + for production use. + The deprecated voices and features will continue to function for at least one year + but might be removed at a future date. You are encouraged to migrate to the + equivalent neural voices at your earliest convenience. For more information about + all voice updates, see the [2 December 2020 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) + in the release notes. + + :param str voice: The voice for which information is to be returned. For + more information about specifying a voice, see **Important voice updates** + in the method description. :param str customization_id: (optional) The customization ID (GUID) of a custom model for which information is to be returned. You must make the request with credentials for the instance of the service that owns the @@ -230,6 +257,27 @@ def synthesize(self, For more information about specifying an audio format, including additional details about some of the formats, see [Audio formats](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-audioFormats#audioFormats). + ### Important voice updates + The service's voices underwent significant change on 2 December 2020. + * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural + instead of concatenative. + * The `ar-AR_OmarVoice` voice is deprecated. Use `ar-MS_OmarVoice` voice instead. + * The `ar-AR` language identifier cannot be used to create a custom model. Use the + `ar-MS` identifier instead. + * The standard concatenative voices for the following languages are now + deprecated: Brazilian Portuguese, United Kingdom and United States English, + French, German, Italian, Japanese, and Spanish (all dialects). + * The features expressive SSML, voice transformation SSML, and use of the `volume` + attribute of the `` element are deprecated and are not supported with any + of the service's neural voices. + * All of the service's voices are now customizable and generally available (GA) + for production use. + The deprecated voices and features will continue to function for at least one year + but might be removed at a future date. You are encouraged to migrate to the + equivalent neural voices at your earliest convenience. For more information about + all voice updates, see the [2 December 2020 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) + in the release notes. ### 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 @@ -243,7 +291,9 @@ def synthesize(self, audio. You can use the `Accept` header or the `accept` parameter to specify the audio format. For more information about specifying an audio format, see **Audio formats (accept types)** in the method description. - :param str voice: (optional) The voice to use for synthesis. + :param str voice: (optional) The voice to use for synthesis. For more + information about specifying a voice, see **Important voice updates** in + the method description. :param str customization_id: (optional) The customization ID (GUID) of a custom model to use for the synthesis. If a custom model is specified, it works only if it matches the language of the indicated voice. You must make @@ -303,15 +353,38 @@ def get_pronunciation(self, for a specific custom model to see the translation for that model. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). + ### Important voice updates + The service's voices underwent significant change on 2 December 2020. + * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural + instead of concatenative. + * The `ar-AR_OmarVoice` voice is deprecated. Use `ar-MS_OmarVoice` voice instead. + * The `ar-AR` language identifier cannot be used to create a custom model. Use the + `ar-MS` identifier instead. + * The standard concatenative voices for the following languages are now + deprecated: Brazilian Portuguese, United Kingdom and United States English, + French, German, Italian, Japanese, and Spanish (all dialects). + * The features expressive SSML, voice transformation SSML, and use of the `volume` + attribute of the `` element are deprecated and are not supported with any + of the service's neural voices. + * All of the service's voices are now customizable and generally available (GA) + for production use. + The deprecated voices and features will continue to function for at least one year + but might be removed at a future date. You are encouraged to migrate to the + equivalent neural voices at your earliest convenience. For more information about + all voice updates, see the [2 December 2020 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) + in the release notes. :param str text: The word for which the pronunciation is requested. :param str voice: (optional) A voice that specifies the language in which the pronunciation is to be returned. All voices for the same language (for - example, `en-US`) return the same translation. + example, `en-US`) return the same translation. For more information about + specifying a voice, see **Important voice updates** in the method + description. :param str format: (optional) The phoneme format in which to return the - pronunciation. The Arabic, Chinese, Dutch, and Korean languages support - only IPA. Omit the parameter to obtain the pronunciation in the default - format. + pronunciation. The Arabic, Chinese, Dutch, Australian English, and Korean + languages support only IPA. Omit the parameter to obtain the pronunciation + in the default format. :param str customization_id: (optional) The customization ID (GUID) of a custom model for which the pronunciation is to be returned. The language of a specified custom model must match the language of the specified voice. If @@ -372,13 +445,35 @@ def create_custom_model(self, used to create it. **See also:** [Creating a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). + ### Important voice updates + The service's voices underwent significant change on 2 December 2020. + * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural + instead of concatenative. + * The `ar-AR_OmarVoice` voice is deprecated. Use `ar-MS_OmarVoice` voice instead. + * The `ar-AR` language identifier cannot be used to create a custom model. Use the + `ar-MS` identifier instead. + * The standard concatenative voices for the following languages are now + deprecated: Brazilian Portuguese, United Kingdom and United States English, + French, German, Italian, Japanese, and Spanish (all dialects). + * The features expressive SSML, voice transformation SSML, and use of the `volume` + attribute of the `` element are deprecated and are not supported with any + of the service's neural voices. + * All of the service's voices are now customizable and generally available (GA) + for production use. + The deprecated voices and features will continue to function for at least one year + but might be removed at a future date. You are encouraged to migrate to the + equivalent neural voices at your earliest convenience. For more information about + all voice updates, see the [2 December 2020 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) + in the release notes. :param str name: The name of the new custom model. :param str language: (optional) The language of the new custom model. You create a custom model for a specific language, not for a specific voice. A - custom model can be used with any voice, standard or neural, for its - specified language. Omit the parameter to use the the default language, - `en-US`. + custom model can be used with any voice for its specified language. Omit + the parameter to use the the default language, `en-US`. **Note:** The + `ar-AR` language identifier cannot be used to create a custom model. Use + the `ar-MS` identifier instead. :param str description: (optional) A description of the new custom model. Specifying a description is recommended. :param dict headers: A `dict` containing the request headers @@ -421,8 +516,8 @@ def list_custom_models(self, Lists metadata such as the name and description for all custom models that are owned by an instance of the service. Specify a language to list the custom models - for that language only. To see the words in addition to the metadata for a - specific custom model, use the **List a custom model** method. You must use + for that language only. To see the words and prompts in addition to the metadata + for a specific custom model, use the **Get a custom model** method. You must use credentials for the instance of the service that owns a model to list information about it. **See also:** [Querying all custom @@ -542,8 +637,9 @@ def get_custom_model(self, customization_id: str, Gets all information about a specified custom model. In addition to metadata such as the name and description of the custom model, the output includes the words and - their translations as defined in the model. To see just the metadata for a model, - use the **List custom models** method. + their translations that are defined for the model, as well as any prompts that are + defined for the model. To see just the metadata for a model, use the **List custom + models** method. **See also:** [Querying a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsQuery). @@ -778,9 +874,9 @@ def add_word(self, :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR - translation. The Arabic, Chinese, Dutch, and Korean languages support only - IPA. A sounds-like is one or more words that, when combined, sound like the - word. + translation. The Arabic, Chinese, Dutch, Australian English, and Korean + languages support only IPA. A sounds-like is one or more words that, when + combined, sound like the word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -914,6 +1010,536 @@ def delete_word(self, customization_id: str, word: str, response = self.send(request) return response + ######################### + # Custom prompts + ######################### + + def list_custom_prompts(self, customization_id: str, + **kwargs) -> DetailedResponse: + """ + List custom prompts. + + Lists information about all custom prompts that are defined for a custom model. + The information includes the prompt ID, prompt text, status, and optional speaker + ID for each prompt of the custom model. You must use credentials for the instance + of the service that owns the custom model. The same information about all of the + prompts for a custom model is also provided by the **Get a custom model** method. + That method provides complete details about a specified custom model, including + its language, owner, custom words, and more. + **Beta:** Custom prompts are beta functionality that is supported only for use + with US English custom models and voices. + **See also:** [Listing custom + prompts](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-custom-prompts#tbe-custom-prompts-list). + + :param str customization_id: The customization ID (GUID) of the custom + model. You must make the request with credentials for the instance of the + service that owns the custom model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Prompts` object + """ + + if customization_id is None: + raise ValueError('customization_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_custom_prompts') + headers.update(sdk_headers) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id'] + path_param_values = self.encode_path_vars(customization_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/prompts'.format( + **path_param_dict) + request = self.prepare_request(method='GET', url=url, headers=headers) + + response = self.send(request) + return response + + def add_custom_prompt(self, + customization_id: str, + prompt_id: str, + metadata: 'PromptMetadata', + file: BinaryIO, + *, + filename: str = None, + **kwargs) -> DetailedResponse: + """ + Add a custom prompt. + + Adds a custom prompt to a custom model. A prompt is defined by the text that is to + be spoken, the audio for that text, a unique user-specified ID for the prompt, and + an optional speaker ID. The information is used to generate prosodic data that is + not visible to the user. This data is used by the service to produce the + synthesized audio upon request. You must use credentials for the instance of the + service that owns a custom model to add a prompt to it. You can add a maximum of + 1000 custom prompts to a single custom model. + You are recommended to assign meaningful values for prompt IDs. For example, use + `goodbye` to identify a prompt that speaks a farewell message. Prompt IDs must be + unique within a given custom model. You cannot define two prompts with the same + name for the same custom model. If you provide the ID of an existing prompt, the + previously uploaded prompt is replaced by the new information. The existing prompt + is reprocessed by using the new text and audio and, if provided, new speaker + model, and the prosody data associated with the prompt is updated. + The quality of a prompt is undefined if the language of a prompt does not match + the language of its custom model. This is consistent with any text or SSML that is + specified for a speech synthesis request. The service makes a best-effort attempt + to render the specified text for the prompt; it does not validate that the + language of the text matches the language of the model. + Adding a prompt is an asynchronous operation. Although it accepts less audio than + speaker enrollment, the service must align the audio with the provided text. The + time that it takes to process a prompt depends on the prompt itself. The + processing time for a reasonably sized prompt generally matches the length of the + audio (for example, it takes 20 seconds to process a 20-second prompt). + For shorter prompts, you can wait for a reasonable amount of time and then check + the status of the prompt with the **Get a custom prompt** method. For longer + prompts, consider using that method to poll the service every few seconds to + determine when the prompt becomes available. No prompt can be used for speech + synthesis if it is in the `processing` or `failed` state. Only prompts that are in + the `available` state can be used for speech synthesis. + When it processes a request, the service attempts to align the text and the audio + that are provided for the prompt. The text that is passed with a prompt must match + the spoken audio as closely as possible. Optimally, the text and audio match + exactly. The service does its best to align the specified text with the audio, and + it can often compensate for mismatches between the two. But if the service cannot + effectively align the text and the audio, possibly because the magnitude of + mismatches between the two is too great, processing of the prompt fails. + ### Evaluating a prompt + Always listen to and evaluate a prompt to determine its quality before using it + in production. To evaluate a prompt, include only the single prompt in a speech + synthesis request by using the following SSML extension, in this case for a prompt + whose ID is `goodbye`: + `` + In some cases, you might need to rerecord and resubmit a prompt as many as five + times to address the following possible problems: + * The service might fail to detect a mismatch between the prompt’s text and audio. + The longer the prompt, the greater the chance for misalignment between its text + and audio. Therefore, multiple shorter prompts are preferable to a single long + prompt. + * The text of a prompt might include a word that the service does not recognize. + In this case, you can create a custom word and pronunciation pair to tell the + service how to pronounce the word. You must then re-create the prompt. + * The quality of the input audio might be insufficient or the service’s processing + of the audio might fail to detect the intended prosody. Submitting new audio for + the prompt can correct these issues. + If a prompt that is created without a speaker ID does not adequately reflect the + intended prosody, enrolling the speaker and providing a speaker ID for the prompt + is one recommended means of potentially improving the quality of the prompt. This + is especially important for shorter prompts such as "good-bye" or "thank you," + where less audio data makes it more difficult to match the prosody of the speaker. + **Beta:** Custom prompts are beta functionality that is supported only for use + with US English custom models and voices. + **See also:** + * [Add a custom + prompt](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-create#tbe-create-add-prompt) + * [Evaluate a custom + prompt](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-create#tbe-create-evaluate-prompt) + * [Rules for creating custom + prompts](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-rules#tbe-rules-prompts). + + :param str customization_id: The customization ID (GUID) of the custom + model. You must make the request with credentials for the instance of the + service that owns the custom model. + :param str prompt_id: The identifier of the prompt that is to be added to + the custom model: + * Include a maximum of 49 characters in the ID. + * Include only alphanumeric characters and `_` (underscores) in the ID. + * Do not include XML sensitive characters (double quotes, single quotes, + ampersands, angle brackets, and slashes) in the ID. + * To add a new prompt, the ID must be unique for the specified custom + model. Otherwise, the new information for the prompt overwrites the + existing prompt that has that ID. + :param PromptMetadata metadata: Information about the prompt that is to be + added to a custom model. The following example of a `PromptMetadata` object + includes both the required prompt text and an optional speaker model ID: + `{ "prompt_text": "Thank you and good-bye!", "speaker_id": + "823068b2-ed4e-11ea-b6e0-7b6456aa95cc" }`. + :param BinaryIO file: An audio file that speaks the text of the prompt with + intonation and prosody that matches how you would like the prompt to be + spoken. + * The prompt audio must be in WAV format and must have a minimum sampling + rate of 16 kHz. The service accepts audio with higher sampling rates. The + service transcodes all audio to 16 kHz before processing it. + * The length of the prompt audio is limited to 30 seconds. + :param str filename: (optional) The filename for file. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Prompt` object + """ + + if customization_id is None: + raise ValueError('customization_id must be provided') + if prompt_id is None: + raise ValueError('prompt_id must be provided') + if metadata is None: + raise ValueError('metadata must be provided') + if file is None: + raise ValueError('file must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_custom_prompt') + headers.update(sdk_headers) + + form_data = [] + form_data.append( + ('metadata', (None, json.dumps(metadata), 'application/json'))) + if not filename and hasattr(file, 'name'): + filename = basename(file.name) + if not filename: + raise ValueError('filename must be provided') + form_data.append(('file', (filename, file, 'audio/wav'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'prompt_id'] + path_param_values = self.encode_path_vars(customization_id, prompt_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + files=form_data) + + response = self.send(request) + return response + + def get_custom_prompt(self, customization_id: str, prompt_id: str, + **kwargs) -> DetailedResponse: + """ + Get a custom prompt. + + Gets information about a specified custom prompt for a specified custom model. The + information includes the prompt ID, prompt text, status, and optional speaker ID + for each prompt of the custom model. You must use credentials for the instance of + the service that owns the custom model. + **Beta:** Custom prompts are beta functionality that is supported only for use + with US English custom models and voices. + **See also:** [Listing custom + prompts](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-custom-prompts#tbe-custom-prompts-list). + + :param str customization_id: The customization ID (GUID) of the custom + model. You must make the request with credentials for the instance of the + service that owns the custom model. + :param str prompt_id: The identifier (name) of the prompt. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Prompt` object + """ + + if customization_id is None: + raise ValueError('customization_id must be provided') + if prompt_id is None: + raise ValueError('prompt_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_custom_prompt') + headers.update(sdk_headers) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['customization_id', 'prompt_id'] + path_param_values = self.encode_path_vars(customization_id, prompt_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', url=url, headers=headers) + + response = self.send(request) + return response + + def delete_custom_prompt(self, customization_id: str, prompt_id: str, + **kwargs) -> DetailedResponse: + """ + Delete a custom prompt. + + Deletes an existing custom prompt from a custom model. The service deletes the + prompt with the specified ID. You must use credentials for the instance of the + service that owns the custom model from which the prompt is to be deleted. + **Caution:** Deleting a custom prompt elicits a 400 response code from synthesis + requests that attempt to use the prompt. Make sure that you do not attempt to use + a deleted prompt in a production application. + **Beta:** Custom prompts are beta functionality that is supported only for use + with US English custom models and voices. + **See also:** [Deleting a custom + prompt](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-custom-prompts#tbe-custom-prompts-delete). + + :param str customization_id: The customization ID (GUID) of the custom + model. You must make the request with credentials for the instance of the + service that owns the custom model. + :param str prompt_id: The identifier (name) of the prompt that is to be + deleted. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if customization_id is None: + raise ValueError('customization_id must be provided') + if prompt_id is None: + raise ValueError('prompt_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_custom_prompt') + headers.update(sdk_headers) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['customization_id', 'prompt_id'] + path_param_values = self.encode_path_vars(customization_id, prompt_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( + **path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers) + + response = self.send(request) + return response + + ######################### + # Speaker models + ######################### + + def list_speaker_models(self, **kwargs) -> DetailedResponse: + """ + List speaker models. + + Lists information about all speaker models that are defined for a service + instance. The information includes the speaker ID and speaker name of each defined + speaker. You must use credentials for the instance of a service to list its + speakers. + **Beta:** Speaker models and the custom prompts with which they are used are beta + functionality that is supported only for use with US English custom models and + voices. + **See also:** [Listing speaker + models](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-speaker-models#tbe-speaker-models-list). + + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Speakers` object + """ + + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_speaker_models') + headers.update(sdk_headers) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/v1/speakers' + request = self.prepare_request(method='GET', url=url, headers=headers) + + response = self.send(request) + return response + + def create_speaker_model(self, speaker_name: str, audio: BinaryIO, + **kwargs) -> DetailedResponse: + """ + Create a speaker model. + + Creates a new speaker model, which is an optional enrollment token for users who + are to add prompts to custom models. A speaker model contains information about a + user's voice. The service extracts this information from a WAV audio sample that + you pass as the body of the request. Associating a speaker model with a prompt is + optional, but the information that is extracted from the speaker model helps the + service learn about the speaker's voice. + A speaker model can make an appreciable difference in the quality of prompts, + especially short prompts with relatively little audio, that are associated with + that speaker. A speaker model can help the service produce a prompt with more + confidence; the lack of a speaker model can potentially compromise the quality of + a prompt. + The gender of the speaker who creates a speaker model does not need to match the + gender of a voice that is used with prompts that are associated with that speaker + model. For example, a speaker model that is created by a male speaker can be + associated with prompts that are spoken by female voices. + You create a speaker model for a given instance of the service. The new speaker + model is owned by the service instance whose credentials are used to create it. + That same speaker can then be used to create prompts for all custom models within + that service instance. No language is associated with a speaker model, but each + custom model has a single specified language. You can add prompts only to US + English models. + You specify a name for the speaker when you create it. The name must be unique + among all speaker names for the owning service instance. To re-create a speaker + model for an existing speaker name, you must first delete the existing speaker + model that has that name. + Speaker enrollment is a synchronous operation. Although it accepts more audio data + than a prompt, the process of adding a speaker is very fast. The service simply + extracts information about the speaker’s voice from the audio. Unlike prompts, + speaker models neither need nor accept a transcription of the audio. When the call + returns, the audio is fully processed and the speaker enrollment is complete. + The service returns a speaker ID with the request. A speaker ID is globally unique + identifier (GUID) that you use to identify the speaker in subsequent requests to + the service. + **Beta:** Speaker models and the custom prompts with which they are used are beta + functionality that is supported only for use with US English custom models and + voices. + **See also:** + * [Create a speaker + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-create#tbe-create-speaker-model) + * [Rules for creating speaker + models](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-rules#tbe-rules-speakers). + + :param str speaker_name: The name of the speaker that is to be added to the + service instance. + * Include a maximum of 49 characters in the name. + * Include only alphanumeric characters and `_` (underscores) in the name. + * Do not include XML sensitive characters (double quotes, single quotes, + ampersands, angle brackets, and slashes) in the name. + * Do not use the name of an existing speaker that is already defined for + the service instance. + :param BinaryIO audio: An enrollment audio file that contains a sample of + the speaker’s voice. + * The enrollment audio must be in WAV format and must have a minimum + sampling rate of 16 kHz. The service accepts audio with higher sampling + rates. It transcodes all audio to 16 kHz before processing it. + * The length of the enrollment audio is limited to 1 minute. Speaking one + or two paragraphs of text that include five to ten sentences is + recommended. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SpeakerModel` object + """ + + if speaker_name is None: + raise ValueError('speaker_name must be provided') + if audio is None: + raise ValueError('audio must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_speaker_model') + headers.update(sdk_headers) + + params = {'speaker_name': speaker_name} + + data = audio + headers['content-type'] = 'audio/wav' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/v1/speakers' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request) + return response + + def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: + """ + Get a speaker model. + + Gets information about all prompts that are defined by a specified speaker for all + custom models that are owned by a service instance. The information is grouped by + the customization IDs of the custom models. For each custom model, the information + lists information about each prompt that is defined for that custom model by the + speaker. You must use credentials for the instance of the service that owns a + speaker model to list its prompts. + **Beta:** Speaker models and the custom prompts with which they are used are beta + functionality that is supported only for use with US English custom models and + voices. + **See also:** [Listing the custom prompts for a speaker + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-speaker-models#tbe-speaker-models-list-prompts). + + :param str speaker_id: The speaker ID (GUID) of the speaker model. You must + make the request with service credentials for the instance of the service + that owns the speaker model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SpeakerCustomModels` object + """ + + if speaker_id is None: + raise ValueError('speaker_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_speaker_model') + headers.update(sdk_headers) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['speaker_id'] + path_param_values = self.encode_path_vars(speaker_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/speakers/{speaker_id}'.format(**path_param_dict) + request = self.prepare_request(method='GET', url=url, headers=headers) + + response = self.send(request) + return response + + def delete_speaker_model(self, speaker_id: str, + **kwargs) -> DetailedResponse: + """ + Delete a speaker model. + + Deletes an existing speaker model from the service instance. The service deletes + the enrolled speaker with the specified speaker ID. You must use credentials for + the instance of the service that owns a speaker model to delete the speaker. + Any prompts that are associated with the deleted speaker are not affected by the + speaker's deletion. The prosodic data that defines the quality of a prompt is + established when the prompt is created. A prompt is static and remains unaffected + by deletion of its associated speaker. However, the prompt cannot be resubmitted + or updated with its original speaker once that speaker is deleted. + **Beta:** Speaker models and the custom prompts with which they are used are beta + functionality that is supported only for use with US English custom models and + voices. + **See also:** [Deleting a speaker + model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-speaker-models#tbe-speaker-models-delete). + + :param str speaker_id: The speaker ID (GUID) of the speaker model. You must + make the request with service credentials for the instance of the service + that owns the speaker model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if speaker_id is None: + raise ValueError('speaker_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_speaker_model') + headers.update(sdk_headers) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + + path_param_keys = ['speaker_id'] + path_param_values = self.encode_path_vars(speaker_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/speakers/{speaker_id}'.format(**path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers) + + response = self.send(request) + return response + ######################### # User data ######################### @@ -973,14 +1599,18 @@ class GetVoiceEnums: class Voice(str, Enum): """ - The voice for which information is to be returned. + The voice for which information is to be returned. For more information about + specifying a voice, see **Important voice updates** in the method description. """ AR_AR_OMARVOICE = 'ar-AR_OmarVoice' + AR_MS_OMARVOICE = 'ar-MS_OmarVoice' DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' + EN_AU_CRAIGVOICE = 'en-AU-CraigVoice' + EN_AU_MADISONVOICE = 'en-AU-MadisonVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' @@ -1003,6 +1633,7 @@ class Voice(str, Enum): ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' @@ -1010,6 +1641,8 @@ class Voice(str, Enum): IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' + KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' + KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' @@ -1049,14 +1682,18 @@ class Accept(str, Enum): class Voice(str, Enum): """ - The voice to use for synthesis. + The voice to use for synthesis. For more information about specifying a voice, see + **Important voice updates** in the method description. """ AR_AR_OMARVOICE = 'ar-AR_OmarVoice' + AR_MS_OMARVOICE = 'ar-MS_OmarVoice' DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' + EN_AU_CRAIGVOICE = 'en-AU-CraigVoice' + EN_AU_MADISONVOICE = 'en-AU-MadisonVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' @@ -1079,6 +1716,7 @@ class Voice(str, Enum): ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' @@ -1086,6 +1724,8 @@ class Voice(str, Enum): IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' + KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' + KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' @@ -1106,14 +1746,18 @@ class Voice(str, Enum): """ A voice that specifies the language in which the pronunciation is to be returned. All voices for the same language (for example, `en-US`) return the same - translation. + translation. For more information about specifying a voice, see **Important voice + updates** in the method description. """ AR_AR_OMARVOICE = 'ar-AR_OmarVoice' + AR_MS_OMARVOICE = 'ar-MS_OmarVoice' DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' + EN_AU_CRAIGVOICE = 'en-AU-CraigVoice' + EN_AU_MADISONVOICE = 'en-AU-MadisonVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' @@ -1136,6 +1780,7 @@ class Voice(str, Enum): ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' + FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' @@ -1143,6 +1788,8 @@ class Voice(str, Enum): IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' + KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' + KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' @@ -1156,8 +1803,8 @@ class Voice(str, Enum): class Format(str, Enum): """ The phoneme format in which to return the pronunciation. The Arabic, Chinese, - Dutch, and Korean languages support only IPA. Omit the parameter to obtain the - pronunciation in the default format. + Dutch, Australian English, and Korean languages support only IPA. Omit the + parameter to obtain the pronunciation in the default format. """ IBM = 'ibm' IPA = 'ipa' @@ -1174,12 +1821,15 @@ class Language(str, Enum): are to be returned. Omit the parameter to see all custom models that are owned by the requester. """ + AR_MS = 'ar-MS' DE_DE = 'de-DE' + EN_AU = 'en-AU' EN_GB = 'en-GB' EN_US = 'en-US' ES_ES = 'es-ES' ES_LA = 'es-LA' ES_US = 'es-US' + FR_CA = 'fr-CA' FR_FR = 'fr-FR' IT_IT = 'it-IT' JA_JP = 'ja-JP' @@ -1218,9 +1868,12 @@ class CustomModel(): :attr List[Word] words: (optional) An array of `Word` objects that lists the words and their translations from the custom model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The - array is empty if the custom model contains no words. This field is returned - only by the **Get a voice** method and only when you specify the customization - ID of a custom model. + array is empty if no words are defined for the custom model. This field is + returned only by the **Get a custom model** method. + :attr List[Prompt] prompts: (optional) An array of `Prompt` objects that + provides information about the prompts that are defined for the specified custom + model. The array is empty if no prompts are defined for the custom model. This + field is returned only by the **Get a custom model** method. """ def __init__(self, @@ -1232,7 +1885,8 @@ def __init__(self, created: str = None, last_modified: str = None, description: str = None, - words: List['Word'] = None) -> None: + words: List['Word'] = None, + prompts: List['Prompt'] = None) -> None: """ Initialize a CustomModel object. @@ -1256,9 +1910,13 @@ def __init__(self, :param List[Word] words: (optional) An array of `Word` objects that lists the words and their translations from the custom model. The words are listed in alphabetical order, with uppercase letters listed before - lowercase letters. The array is empty if the custom model contains no - words. This field is returned only by the **Get a voice** method and only - when you specify the customization ID of a custom model. + lowercase letters. The array is empty if no words are defined for the + custom model. This field is returned only by the **Get a custom model** + method. + :param List[Prompt] prompts: (optional) An array of `Prompt` objects that + provides information about the prompts that are defined for the specified + custom model. The array is empty if no prompts are defined for the custom + model. This field is returned only by the **Get a custom model** method. """ self.customization_id = customization_id self.name = name @@ -1268,6 +1926,7 @@ def __init__(self, self.last_modified = last_modified self.description = description self.words = words + self.prompts = prompts @classmethod def from_dict(cls, _dict: Dict) -> 'CustomModel': @@ -1293,6 +1952,10 @@ def from_dict(cls, _dict: Dict) -> 'CustomModel': args['description'] = _dict.get('description') if 'words' in _dict: args['words'] = [Word.from_dict(x) for x in _dict.get('words')] + if 'prompts' in _dict: + args['prompts'] = [ + Prompt.from_dict(x) for x in _dict.get('prompts') + ] return cls(**args) @classmethod @@ -1320,6 +1983,8 @@ def to_dict(self) -> Dict: _dict['description'] = self.description if hasattr(self, 'words') and self.words is not None: _dict['words'] = [x.to_dict() for x in self.words] + if hasattr(self, 'prompts') and self.prompts is not None: + _dict['prompts'] = [x.to_dict() for x in self.prompts] return _dict def _to_dict(self): @@ -1407,47 +2072,102 @@ def __ne__(self, other: 'CustomModels') -> bool: return not self == other -class Pronunciation(): +class Prompt(): """ - The pronunciation of the specified text. - - :attr str pronunciation: The pronunciation of the specified text in the - requested voice and format. If a custom model is specified, the pronunciation - also reflects that custom model. + Information about a custom prompt. + + :attr str prompt: The user-specified text of the prompt. + :attr str prompt_id: The user-specified identifier (name) of the prompt. + :attr str status: The status of the prompt: + * `processing`: The service received the request to add the prompt and is + analyzing the validity of the prompt. + * `available`: The service successfully validated the prompt, which is now ready + for use in a speech synthesis request. + * `failed`: The service's validation of the prompt failed. The status of the + prompt includes an `error` field that describes the reason for the failure. + :attr str error: (optional) If the status of the prompt is `failed`, an error + message that describes the reason for the failure. The field is omitted if no + error occurred. + :attr str speaker_id: (optional) The speaker ID (GUID) of the speaker for which + the prompt was defined. The field is omitted if no speaker ID was specified. """ - def __init__(self, pronunciation: str) -> None: - """ - Initialize a Pronunciation object. - - :param str pronunciation: The pronunciation of the specified text in the - requested voice and format. If a custom model is specified, the - pronunciation also reflects that custom model. - """ - self.pronunciation = pronunciation + def __init__(self, + prompt: str, + prompt_id: str, + status: str, + *, + error: str = None, + speaker_id: str = None) -> None: + """ + Initialize a Prompt object. + + :param str prompt: The user-specified text of the prompt. + :param str prompt_id: The user-specified identifier (name) of the prompt. + :param str status: The status of the prompt: + * `processing`: The service received the request to add the prompt and is + analyzing the validity of the prompt. + * `available`: The service successfully validated the prompt, which is now + ready for use in a speech synthesis request. + * `failed`: The service's validation of the prompt failed. The status of + the prompt includes an `error` field that describes the reason for the + failure. + :param str error: (optional) If the status of the prompt is `failed`, an + error message that describes the reason for the failure. The field is + omitted if no error occurred. + :param str speaker_id: (optional) The speaker ID (GUID) of the speaker for + which the prompt was defined. The field is omitted if no speaker ID was + specified. + """ + self.prompt = prompt + self.prompt_id = prompt_id + self.status = status + self.error = error + self.speaker_id = speaker_id @classmethod - def from_dict(cls, _dict: Dict) -> 'Pronunciation': - """Initialize a Pronunciation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Prompt': + """Initialize a Prompt object from a json dictionary.""" args = {} - if 'pronunciation' in _dict: - args['pronunciation'] = _dict.get('pronunciation') + if 'prompt' in _dict: + args['prompt'] = _dict.get('prompt') else: raise ValueError( - 'Required property \'pronunciation\' not present in Pronunciation JSON' - ) + 'Required property \'prompt\' not present in Prompt JSON') + if 'prompt_id' in _dict: + args['prompt_id'] = _dict.get('prompt_id') + else: + raise ValueError( + 'Required property \'prompt_id\' not present in Prompt JSON') + if 'status' in _dict: + args['status'] = _dict.get('status') + else: + raise ValueError( + 'Required property \'status\' not present in Prompt JSON') + if 'error' in _dict: + args['error'] = _dict.get('error') + if 'speaker_id' in _dict: + args['speaker_id'] = _dict.get('speaker_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Pronunciation object from a json dictionary.""" + """Initialize a Prompt 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, 'pronunciation') and self.pronunciation is not None: - _dict['pronunciation'] = self.pronunciation + if hasattr(self, 'prompt') and self.prompt is not None: + _dict['prompt'] = self.prompt + if hasattr(self, 'prompt_id') and self.prompt_id is not None: + _dict['prompt_id'] = self.prompt_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + if hasattr(self, 'error') and self.error is not None: + _dict['error'] = self.error + if hasattr(self, 'speaker_id') and self.speaker_id is not None: + _dict['speaker_id'] = self.speaker_id return _dict def _to_dict(self): @@ -1455,16 +2175,666 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Pronunciation object.""" + """Return a `str` version of this Prompt object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Pronunciation') -> bool: + def __eq__(self, other: 'Prompt') -> 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: 'Pronunciation') -> bool: + def __ne__(self, other: 'Prompt') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class PromptMetadata(): + """ + Information about the prompt that is to be added to a custom model. The following + example of a `PromptMetadata` object includes both the required prompt text and an + optional speaker model ID: + `{ "prompt_text": "Thank you and good-bye!", "speaker_id": + "823068b2-ed4e-11ea-b6e0-7b6456aa95cc" }`. + + :attr str prompt_text: The required written text of the spoken prompt. The + length of a prompt's text is limited to a few sentences. Speaking one or two + sentences of text is the recommended limit. A prompt cannot contain more than + 1000 characters of text. Escape any XML control characters (double quotes, + single quotes, ampersands, angle brackets, and slashes) that appear in the text + of the prompt. + :attr str speaker_id: (optional) The optional speaker ID (GUID) of a previously + defined speaker model that is to be associated with the prompt. + """ + + def __init__(self, prompt_text: str, *, speaker_id: str = None) -> None: + """ + Initialize a PromptMetadata object. + + :param str prompt_text: The required written text of the spoken prompt. The + length of a prompt's text is limited to a few sentences. Speaking one or + two sentences of text is the recommended limit. A prompt cannot contain + more than 1000 characters of text. Escape any XML control characters + (double quotes, single quotes, ampersands, angle brackets, and slashes) + that appear in the text of the prompt. + :param str speaker_id: (optional) The optional speaker ID (GUID) of a + previously defined speaker model that is to be associated with the prompt. + """ + self.prompt_text = prompt_text + self.speaker_id = speaker_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'PromptMetadata': + """Initialize a PromptMetadata object from a json dictionary.""" + args = {} + if 'prompt_text' in _dict: + args['prompt_text'] = _dict.get('prompt_text') + else: + raise ValueError( + 'Required property \'prompt_text\' not present in PromptMetadata JSON' + ) + if 'speaker_id' in _dict: + args['speaker_id'] = _dict.get('speaker_id') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a PromptMetadata 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, 'prompt_text') and self.prompt_text is not None: + _dict['prompt_text'] = self.prompt_text + if hasattr(self, 'speaker_id') and self.speaker_id is not None: + _dict['speaker_id'] = self.speaker_id + 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 PromptMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'PromptMetadata') -> 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: 'PromptMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Prompts(): + """ + Information about the custom prompts that are defined for a custom model. + + :attr List[Prompt] prompts: An array of `Prompt` objects that provides + information about the prompts that are defined for the specified custom model. + The array is empty if no prompts are defined for the custom model. + """ + + def __init__(self, prompts: List['Prompt']) -> None: + """ + Initialize a Prompts object. + + :param List[Prompt] prompts: An array of `Prompt` objects that provides + information about the prompts that are defined for the specified custom + model. The array is empty if no prompts are defined for the custom model. + """ + self.prompts = prompts + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Prompts': + """Initialize a Prompts object from a json dictionary.""" + args = {} + if 'prompts' in _dict: + args['prompts'] = [ + Prompt.from_dict(x) for x in _dict.get('prompts') + ] + else: + raise ValueError( + 'Required property \'prompts\' not present in Prompts JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Prompts 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, 'prompts') and self.prompts is not None: + _dict['prompts'] = [x.to_dict() for x in self.prompts] + 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 Prompts object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Prompts') -> 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: 'Prompts') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Pronunciation(): + """ + The pronunciation of the specified text. + + :attr str pronunciation: The pronunciation of the specified text in the + requested voice and format. If a custom model is specified, the pronunciation + also reflects that custom model. + """ + + def __init__(self, pronunciation: str) -> None: + """ + Initialize a Pronunciation object. + + :param str pronunciation: The pronunciation of the specified text in the + requested voice and format. If a custom model is specified, the + pronunciation also reflects that custom model. + """ + self.pronunciation = pronunciation + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Pronunciation': + """Initialize a Pronunciation object from a json dictionary.""" + args = {} + if 'pronunciation' in _dict: + args['pronunciation'] = _dict.get('pronunciation') + else: + raise ValueError( + 'Required property \'pronunciation\' not present in Pronunciation JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Pronunciation 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, 'pronunciation') and self.pronunciation is not None: + _dict['pronunciation'] = self.pronunciation + 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 Pronunciation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Pronunciation') -> 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: 'Pronunciation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Speaker(): + """ + Information about a speaker model. + + :attr str speaker_id: The speaker ID (GUID) of the speaker. + :attr str name: The user-defined name of the speaker. + """ + + def __init__(self, speaker_id: str, name: str) -> None: + """ + Initialize a Speaker object. + + :param str speaker_id: The speaker ID (GUID) of the speaker. + :param str name: The user-defined name of the speaker. + """ + self.speaker_id = speaker_id + self.name = name + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Speaker': + """Initialize a Speaker object from a json dictionary.""" + args = {} + if 'speaker_id' in _dict: + args['speaker_id'] = _dict.get('speaker_id') + else: + raise ValueError( + 'Required property \'speaker_id\' not present in Speaker JSON') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in Speaker JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Speaker 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, 'speaker_id') and self.speaker_id is not None: + _dict['speaker_id'] = self.speaker_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + 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 Speaker object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Speaker') -> 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: 'Speaker') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SpeakerCustomModel(): + """ + A custom models for which the speaker has defined prompts. + + :attr str customization_id: The customization ID (GUID) of a custom model for + which the speaker has defined one or more prompts. + :attr List[SpeakerPrompt] prompts: An array of `SpeakerPrompt` objects that + provides information about each prompt that the user has defined for the custom + model. + """ + + def __init__(self, customization_id: str, + prompts: List['SpeakerPrompt']) -> None: + """ + Initialize a SpeakerCustomModel object. + + :param str customization_id: The customization ID (GUID) of a custom model + for which the speaker has defined one or more prompts. + :param List[SpeakerPrompt] prompts: An array of `SpeakerPrompt` objects + that provides information about each prompt that the user has defined for + the custom model. + """ + self.customization_id = customization_id + self.prompts = prompts + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModel': + """Initialize a SpeakerCustomModel object from a json dictionary.""" + args = {} + if 'customization_id' in _dict: + args['customization_id'] = _dict.get('customization_id') + else: + raise ValueError( + 'Required property \'customization_id\' not present in SpeakerCustomModel JSON' + ) + if 'prompts' in _dict: + args['prompts'] = [ + SpeakerPrompt.from_dict(x) for x in _dict.get('prompts') + ] + else: + raise ValueError( + 'Required property \'prompts\' not present in SpeakerCustomModel JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeakerCustomModel 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, + 'customization_id') and self.customization_id is not None: + _dict['customization_id'] = self.customization_id + if hasattr(self, 'prompts') and self.prompts is not None: + _dict['prompts'] = [x.to_dict() for x in self.prompts] + 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 SpeakerCustomModel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SpeakerCustomModel') -> 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: 'SpeakerCustomModel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SpeakerCustomModels(): + """ + Custom models for which the speaker has defined prompts. + + :attr List[SpeakerCustomModel] customizations: An array of `SpeakerCustomModel` + objects. Each object provides information about the prompts that are defined for + a specified speaker in the custom models that are owned by a specified service + instance. The array is empty if no prompts are defined for the speaker. + """ + + def __init__(self, customizations: List['SpeakerCustomModel']) -> None: + """ + Initialize a SpeakerCustomModels object. + + :param List[SpeakerCustomModel] customizations: An array of + `SpeakerCustomModel` objects. Each object provides information about the + prompts that are defined for a specified speaker in the custom models that + are owned by a specified service instance. The array is empty if no prompts + are defined for the speaker. + """ + self.customizations = customizations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModels': + """Initialize a SpeakerCustomModels object from a json dictionary.""" + args = {} + if 'customizations' in _dict: + args['customizations'] = [ + SpeakerCustomModel.from_dict(x) + for x in _dict.get('customizations') + ] + else: + raise ValueError( + 'Required property \'customizations\' not present in SpeakerCustomModels JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeakerCustomModels 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, 'customizations') and self.customizations is not None: + _dict['customizations'] = [x.to_dict() for x in self.customizations] + 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 SpeakerCustomModels object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SpeakerCustomModels') -> 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: 'SpeakerCustomModels') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SpeakerModel(): + """ + The speaker ID of the speaker model. + + :attr str speaker_id: The speaker ID (GUID) of the speaker model. + """ + + def __init__(self, speaker_id: str) -> None: + """ + Initialize a SpeakerModel object. + + :param str speaker_id: The speaker ID (GUID) of the speaker model. + """ + self.speaker_id = speaker_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SpeakerModel': + """Initialize a SpeakerModel object from a json dictionary.""" + args = {} + if 'speaker_id' in _dict: + args['speaker_id'] = _dict.get('speaker_id') + else: + raise ValueError( + 'Required property \'speaker_id\' not present in SpeakerModel JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeakerModel 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, 'speaker_id') and self.speaker_id is not None: + _dict['speaker_id'] = self.speaker_id + 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 SpeakerModel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SpeakerModel') -> 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: 'SpeakerModel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SpeakerPrompt(): + """ + A prompt that a speaker has defined for a custom model. + + :attr str prompt: The user-specified text of the prompt. + :attr str prompt_id: The user-specified identifier (name) of the prompt. + :attr str status: The status of the prompt: + * `processing`: The service received the request to add the prompt and is + analyzing the validity of the prompt. + * `available`: The service successfully validated the prompt, which is now ready + for use in a speech synthesis request. + * `failed`: The service's validation of the prompt failed. The status of the + prompt includes an `error` field that describes the reason for the failure. + :attr str error: (optional) If the status of the prompt is `failed`, an error + message that describes the reason for the failure. The field is omitted if no + error occurred. + """ + + def __init__(self, + prompt: str, + prompt_id: str, + status: str, + *, + error: str = None) -> None: + """ + Initialize a SpeakerPrompt object. + + :param str prompt: The user-specified text of the prompt. + :param str prompt_id: The user-specified identifier (name) of the prompt. + :param str status: The status of the prompt: + * `processing`: The service received the request to add the prompt and is + analyzing the validity of the prompt. + * `available`: The service successfully validated the prompt, which is now + ready for use in a speech synthesis request. + * `failed`: The service's validation of the prompt failed. The status of + the prompt includes an `error` field that describes the reason for the + failure. + :param str error: (optional) If the status of the prompt is `failed`, an + error message that describes the reason for the failure. The field is + omitted if no error occurred. + """ + self.prompt = prompt + self.prompt_id = prompt_id + self.status = status + self.error = error + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SpeakerPrompt': + """Initialize a SpeakerPrompt object from a json dictionary.""" + args = {} + if 'prompt' in _dict: + args['prompt'] = _dict.get('prompt') + else: + raise ValueError( + 'Required property \'prompt\' not present in SpeakerPrompt JSON' + ) + if 'prompt_id' in _dict: + args['prompt_id'] = _dict.get('prompt_id') + else: + raise ValueError( + 'Required property \'prompt_id\' not present in SpeakerPrompt JSON' + ) + if 'status' in _dict: + args['status'] = _dict.get('status') + else: + raise ValueError( + 'Required property \'status\' not present in SpeakerPrompt JSON' + ) + if 'error' in _dict: + args['error'] = _dict.get('error') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SpeakerPrompt 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, 'prompt') and self.prompt is not None: + _dict['prompt'] = self.prompt + if hasattr(self, 'prompt_id') and self.prompt_id is not None: + _dict['prompt_id'] = self.prompt_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + if hasattr(self, 'error') and self.error is not None: + _dict['error'] = self.error + 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 SpeakerPrompt object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SpeakerPrompt') -> 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: 'SpeakerPrompt') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Speakers(): + """ + Information about all speaker models for the service instance. + + :attr List[Speaker] speakers: An array of `Speaker` objects that provides + information about the speakers for the service instance. The array is empty if + the service instance has no speakers. + """ + + def __init__(self, speakers: List['Speaker']) -> None: + """ + Initialize a Speakers object. + + :param List[Speaker] speakers: An array of `Speaker` objects that provides + information about the speakers for the service instance. The array is empty + if the service instance has no speakers. + """ + self.speakers = speakers + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Speakers': + """Initialize a Speakers object from a json dictionary.""" + args = {} + if 'speakers' in _dict: + args['speakers'] = [ + Speaker.from_dict(x) for x in _dict.get('speakers') + ] + else: + raise ValueError( + 'Required property \'speakers\' not present in Speakers JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Speakers 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, 'speakers') and self.speakers is not None: + _dict['speakers'] = [x.to_dict() for x in self.speakers] + 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 Speakers object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Speakers') -> 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: 'Speakers') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1477,7 +2847,8 @@ class SupportedFeatures(): `false`, the voice cannot be customized. (Same as `customizable`.). :attr bool voice_transformation: If `true`, the voice can be transformed by using the SSML <voice-transformation> element; if `false`, the voice - cannot be transformed. + cannot be transformed. The feature was available only for the now-deprecated + standard voices. You cannot use the feature with neural voices. """ def __init__(self, custom_pronunciation: bool, @@ -1489,7 +2860,9 @@ def __init__(self, custom_pronunciation: bool, if `false`, the voice cannot be customized. (Same as `customizable`.). :param bool voice_transformation: If `true`, the voice can be transformed by using the SSML <voice-transformation> element; if `false`, the - voice cannot be transformed. + voice cannot be transformed. The feature was available only for the + now-deprecated standard voices. You cannot use the feature with neural + voices. """ self.custom_pronunciation = custom_pronunciation self.voice_transformation = voice_transformation @@ -1554,8 +2927,9 @@ class Translation(): :attr str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR translation. The - Arabic, Chinese, Dutch, and Korean languages support only IPA. A sounds-like is - one or more words that, when combined, sound like the word. + Arabic, Chinese, Dutch, Australian English, and Korean languages support only + IPA. A sounds-like is one or more words that, when combined, sound like the + word. :attr str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of @@ -1571,9 +2945,9 @@ def __init__(self, translation: str, *, part_of_speech: str = None) -> None: :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR - translation. The Arabic, Chinese, Dutch, and Korean languages support only - IPA. A sounds-like is one or more words that, when combined, sound like the - word. + translation. The Arabic, Chinese, Dutch, Australian English, and Korean + languages support only IPA. A sounds-like is one or more words that, when + combined, sound like the word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -1876,9 +3250,9 @@ class Word(): :attr str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. The Arabic, Chinese, - Dutch, and Korean languages support only IPA. A sounds-like translation consists - of one or more words that, when combined, sound like the word. The maximum - length of a translation is 499 characters. + Dutch, Australian English, and Korean languages support only IPA. A sounds-like + translation consists of one or more words that, when combined, sound like the + word. The maximum length of a translation is 499 characters. :attr str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of @@ -1900,9 +3274,10 @@ def __init__(self, :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. The - Arabic, Chinese, Dutch, and Korean languages support only IPA. A - sounds-like translation consists of one or more words that, when combined, - sound like the word. The maximum length of a translation is 499 characters. + Arabic, Chinese, Dutch, Australian English, and Korean languages support + only IPA. A sounds-like translation consists of one or more words that, + when combined, sound like the word. The maximum length of a translation is + 499 characters. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single diff --git a/resources/tts_audio.wav b/resources/tts_audio.wav new file mode 100644 index 0000000000000000000000000000000000000000..ba4760649ea3a46afb64ad02ef3f10adce8d24d3 GIT binary patch literal 75726 zcmeFZXM7V!7d|?>>eaF=_g=tM(>o#b9w77{5_&?1P(z16fCNGdB@jvop_fn-AoSjC znz4<$CEMy<+TFR2c<+1v_kO*fU-UDURy#B2Jm)!QX4ms<{~let-pyplkPd^pOqe<+ zMMnr>@LJXmZx$265*_K?W5B>TeC*MuYu_FNx(?LheeW;lPH5ILt7)^WMhzR1abM2) zav6I0-@pGM@IM6phrs_3_#XoQL*Rc1{Qp6KQbPXUKcPNCpa1iZe*E{}_o3haIXATS zVE#Yv|8wL&tC`S>=Krit{?9j|_04~N{@>sJ=iL9a`R}>^9VzrXbd3G@3Vr&|drCPP zqym-TTb6LtPgx=%Dk3E!B2X!j6B!W`ALVhJqaxy`0r(_*^y|Mqg+^rmA0I-WLf?c& z2ptdo3w;W`WB%`!|F!PF*8k_XfL8ypp2DL4So_~L0>=N32Ndr@{j=yT)L-bI0>8x{ zk19yWQY(%yB%HWlt(j`z4TYDL=+lL7qv2H&iNGtCG$8r(D_WE6Bn?SRl0|RQO!5Os zVOY|JoTrEAee|-CyrqPmC#TTcMcRsHkqWB9IL`$e?N5v8b<&ycC#`{2Z~7f=!u(8r z1CEb`f5|*jM1LR&R8Mx1P8d%|t_U8|gWMnrvV~3}J?SXIlMJ$ySx1-9*hT3RjdWxQ;Ye`))g6tJ~k&V7LX~h=NlSF9rRz}8eKzf(owVoqrQdROXyYl8BM@z3z<%*kiGOWeL@?u>*x@o zA(eCrT`Sd*9j~Mo#tLOw$3@Z$XK{f4150M~^!>AfCghS+Q z_~G%RK-BG2jhO368BHhlkDL;~1UVSNg4JrACnf=SQvsyj&{|A5`IX!zpVBzy9hpeB zlDYIAB2x}zu96Homee8R(dT+vjoz-%0w7XJAJ7PlP$%&ez zl7qA}c}0C->1?`~jHBTsli5ypkR$XJ`0_95MwU_sISSU+Bz?(B;-E{&6hwSKJiJf7 zhNX|GPxzN$AL%97 z+KT)Pj=Uhp=~i-vyr2xz4DafbRz%4RrG1E;62?YfBT~f}ZwLLIOrV=!@g2I7_yr%W z59B%!voI8~8b@1`SyV=b1NlfqbT=~WC|J4x*1RQOBUpM8#1tD`+nH z89sMGCJw+TH%L3ul}rHZe}&gFRG8oBM8v8tIRQ^2f$d>wvlodm1E_|6! zqeyLJTn^QMYg15*F4D!Y_5(8X6Xfk(I+rX1PyO^Y9gP07h?abXtT+Ok3ds_Ttp)C> z7U!8!@zo>_u@;eOq%Ue` zCixDn^<*FY7xPCG+!*;2@k>Qzy99QAj(%r>^-D+?j{Ji9up9lf1tOo}`zv%OxKtBW zbU1B8BIsmbIT9AOLtQr0nK&9i#jA;#SA)n_p_ab~#x+qlvT1wR`73<~jAfWBo0D7Q zI^BUvb%aKfn`9V0NYYVv+L89iyGLl7i}#tZO-vHO)%KV%>mf7u!={^v-!;rCnV9GP z2DVPx1(|E7!{Gk|WPBC!@&ai>Q&1BcV;)!puf_t|Z;`D(A(qdPK@2fth8_wIv`4OH zqXIq#KUjD+3)ugF-*+(bM$EluFoSjm%f2EzQ9m{#t|ySe^Dz&r$mc+R7Aog1x*3*y zj?c}IIU|7jFwzlOkVQ_?NX!bI5z7tW+AF$_oI^gXqr;IMh4c@mG5Xtu`m_*HE~H0^ zRcK9Skh6$L3P!v}yJ2NA9A`8}#@)kgXaI+081ocHQW6W+XltnfC~IMR3H_3eCduH{ zJk)6!IfP2-qJA)DGI+NE=rjkGk1;EhlXIjgP`HYkH-UC#o+G~XNiE>`EA35{%u)Cf zz)aDF&Y%}Cvn8WG|48c7=X5D*Z7OWJhXLB>8tye83UKsN&`pm(Swc37fC&Xl3f zjY1V|&a6l6`;L4;-DEQ2{|Hg+29|C^Ob^n3V0Aibz)m`qv<7DyA-k?&RT4|$v1+YC zhI>EGx+&oF2h2P9;A9cvA_CXNV1f_h8>t7}6=OsnGA$ms6=A)3kSstieK7O)qnluL z0bawv+heHB+v)GfhOMYl2heLn(jGHXB4)Jam^VvM*Z-jlz}2Q?8hC3*?MR2;4^U^i zVOCFqm2c=n#QP6g2#=4UVh;nBt1$ajVcegA|0JL{2yG^!l6oO`l8L)b}x2S|?Q8&IuHH|`+o&(b3 zu-aiTUwwjE&y1Q~n+zhCVdo9h6o%A8#9dhHZU^ofoOKC&e}HIBMJ?@x^+*DpgE{CV z*!C~D$QKTPT9l`_a%Fr4<8*A{ZsJl;4Gc_a+2)-aG$hDiOS0}MPse=&~ z)0dd9+`#;p@Cz7pAB^~%%8~PJF%JzOy|DglLz6IfeTF(YP52!CZp2J|3~_&hjCllH zMX1Wh>1Cp2`eNoYqcRFu>77J{`xCV$2`k_W7_|XCjQQ#rX27*zV;6X^1S_NdsEF_3 zZ9~*f)En9y{47Q8crlBlVFmXidgd@@AzeqYcEa5CGmid6rlML5!?n&c^z$9?lVasD z5!TP5$IzDs`L_Vvxr|x$6ZF;)Ys)R*=xyZOBCL_U!1M=jv=7Gj;JP9UvsW535o?V< za0XWA80Q|vdIXG^2Sit(g7ifN-b1Cx&`b0Ys_z0EJA{h+HD>%vc-IhCoW(4Zg_>%` zIn!X#F0gGsSqCiUqZf`ABg!K&gKtBv*iO%&lJCMge=w@~YkD}xQNekiVKW}t@F zLyj&$wMe70z~U=J&(r_{&oJMg0@v^1Dkcgu|2$;43A~VCjE+RkuuMLx)?nI>)}qUR zY!j-WUZGS-q$Xhn#&N-mUZ@UT$Ro@{QlPVnbYM23Wk*KB>|`>SMa&P(=S&+moQYwU zGCpPvvx*F7-Y|EV*-QuK1}P`~nDdxN^1(7IxT&JKd=fv3Kg37#E4dN;Y@sHuW%di} zgz=~&$kbrBi7af91buepi-I zI@`F}QrEVms(0DWig)%^!CutFW%E1PPvwQGPnCj9A)7CKC0i&{N>t1uu1jE-C)YLB zHPC+Ca@|_PBjFT$l<=dVCg+&zY#Zql`547nd9jpH6f1iv5+v&|N12&NY%lfz<7c9n zu0nNSk+-|+H|HPjdcH#6OqZ*2ZOM1#yfzcG3Q% zJE4=v3j*8Bw&FzvZHfcN_olbS{qn4ZwQO1Z0J@JGz}FNRm8D_Rbpyke>RLqn5%Dl= zi{cWi5ZZE%z!dLY$6(9xN{eZ2HtG+3B zN@|M!VQMkWnG#$9OeWbvXRbwHpf|zU+0od2#1nLAs$He&#X~C=yG61OhR@?aOE{kx z$hg~JN{eUBy4GgmI_OKo+l22`^bannl6`pit}t(6iMF)#{h6Fbxr(ZQf1&UdpH0(b zN3n$|obEp1=^IosJ~odD zXFE#UC_gAJ$cHKiXgX_JD2K>r%5I9sFhzn!s6jUi-*B^n?*hYp!(Bf)4mgNofNiNc z&iJJ0hk}ZdY}Z4@@|f=u`Gkqd7iz6)w(S#d%ciyK#;Fb43_HUAmDco4Ha2^o{rcOy ztkPA*lizfGQSZIhaw<@RpTQquzff({w~js*)h6;`^!B(Vv2DVe$_I*mri%h&9eVS? z%9CY{itm+vs9x+ycN}*N@zp2I#k0kuC5;q2Rfm<^6uVSowaMDE%InfqqAtu6Iu}>z zc3~HPoLk5h1iE|N_SW`+j$ZbD)ve2x=l9CpQylJADO8aUViigAGZGrz_~cIK)t@}6 z(;^`!dRp9VgH}4hEvxu6zx4HwZwKYExjkQe^?3KIZRL$z1^yjEXUPNgPZ8^4?#G^p z{W4)j^2Ee1A~$K)%VI>UxZTdt=3x2g!jXBgg>Q}5swP#d?ArswSd+L=DpFn6>a=pz z4P^)I%`^N=N2FCb_cZKt%t)o5G&RMQkZYWO8o04ZQ zOY!!RZ8FFbPNpQ)O>4Qb)9NnLHWTYfQ&%UF_~YTd#O0p%CRIWC+grJ7^8&9oKUw-P zCA($uJB!AX9ULeUsm~Y=$4-fT6mqLQpmhNmH)a_ zU-8n^)mGwf#@Iz>=?Fy~l}kBXB@IiCm>fCCAn5YdXB7LSo!HlW^I)^UIA4LgxATVG zY#U;|R-JA#m$u1Icy<33Q`*h9Rra}Vb2LevReyP#o?WkY-Oy%m{rn6eH9o0JM3p$* z_pI7cygmOx-s{}N>;VrKJ^1d$pLxT|FPIhXxqOOjkiKC?<+9{>!J5syFHHrK# z!VqSWe9mof?W+E|M4Nvz&sH$?L!F`~#-;WhUT5$;QzdJnN>ha?e^D*b6-WA`7ezIU zc%f^hZKjwZ$`K^Nw?4Di?Y-gq#>cp~+Be&_Su(5Um)k$Ic~|h76iBLf1a~MB4Xfgr z3|+&vZ8JOVYTvi{KXpgdSeJ4jwj!*ySms?(xu(Qj{Hpj?-qsiGA54AtWA?OsQ7JKX zv##_%kZ#qrF&v0$ozOMyK&mc&O|&h>5?!tH%fAsP)9cPv6)%g97ws!LURYAR&e+H@ z&3V+{gFa&oqI6a(X|CQKJ~-k~#Get342KL~>)UC{rQ?~UTu1*o?^gGE`wdGY+b{N= z*4C9LiiP*BbAQcWUiRA7JJ?E+6s}AfTCZ_yro+$e`nLF~;pMu9n%5KchIr+B%6V!! zj@bH}ca?2;zaq!<@^*HcSL@y$&7WM-xvIZ=JY}S2#R}b{=sB?mqL@f+v?sbw)Zd0< z`Y3gCQBJU?@2-2Pb*u5ya4W}_lrN5|E8RyZlu2y9f+wP zz05FDU#-cJ_Yij>S=>n95YJ-Q9>*x#@#^~(=SwP!P8U8eT2sEj65(4y#>oBQili2` zYi9-PpR89}=U}Zp8OEgcv1j$4sNRUL;@(_*;Dlp+rLSauk*MhN!gqO{a+~DOE*Wlm zZq_*``?t|DQM`1#;9m0;fHsOwb(E^r@6FG)Mu64^v~U1b-=G3jE7 zQL`vOnX>WP(t{y$c-lP4~WZ|L*$Q^|L40UlQ~SE^nR-BP< zlJAvompv7mnL$_|Kf(R6ZNlHd%ijCWQC4H+7Nf%StWs*(=osj`Cft)O*IYN$j*W@q zV@+{$$DlOjwCS#ky?@?(Me~@hA8eSdnq-l_iCNyglek1l_ZV*o1Wkw1p4}F zdsz1o_YL>Ap1a-#fxX-uK3}MTm12+#VLD@W{6Q+0O_1894P@yulXy9qz*T!wooY*V zWqwr$%W&Ie$6-$w?l)0}x@W}ZsKwEXVnlI0;v2_%W1mJ{&>srx8P-G>9X3m87yU>h zd6WMi*Y6gYsb2YkvS($NE0$FFjqR#=>n4ZUIn7+OdFwou(fZkrzW- zDSl)^@3=A1E`ufFPQ+7vl&+WhjO-uL6|5wuU|wYOmmMfOT{^m$FZ`=`dPSVM zk^QCfvS(0mGQGld6X!}N%Rf_?loK?2!Y1gB>8f>K>l)~qXuBwnN_@n{7Y5|MpFJ&I z!yPLf70#ZXHC~n97udreC9Rq3%trPr(I=A860d|xnn<3A?lL}7gGAE|?x|;{(`Dad z>t>x{ec=eY%)vv8996tA7{`*3f_@PX$D3~^cUEmj!J#0(yb8$b3QmU1A#B5kcHCfe89ivSPJEsk({IV^Q7oxqSHh13F z!Sjjx8<)>{(Y?eo+#BOR7)TY&xWq^zTuEoskACg0IMe5C&l z?ju#=u7Ma=EPZh&Vt{*}BiGuY+Gm<>DysU?+T4EIG0#&^*e|`UexX}rXb}5H;+xcQ zsd-6%CXS0wja?eKJA6ghI`w4P6>^X(3mywL^If+8P?cv~Z5&=cq}ci)qIhlj*OlGP za{E3H4HgR-0!@_T9 z%9R~uP1r0!%6%Rz^ZnwSVfL4AEAV2)s8HQofAJexh%t8Ykcj@8lzMCCv=Eu9@$U7BCNLhy3|Q# z3Y_q>aNM`Y`m6Ep(nrOYKjgj}`KsWxGe5UfY09fEaqROa36IER(K1Q6q>gACJ6`fy zeqC9lOi|a;O*b@*bm^#yRkHHwlDQ-&xGwlGcq^F5o#J!Jcy|yDm$7oDp71nq-22YG-hJJ3(YwyO$D8Tx=BajmZfjunn5G&v zm7C0oj^6HKf0QUWY<=8MDLYfQr5&iTrPjdA=_!q3eG&C_Z?u1C&ZtrpMdDNBcm7&% zg8!N0gK=SDoxCse)cMQb^?BPnzocC6c;cxO=tiGQ2Wf9=H)xJ&rfGgtFH&_;-_+g< z)9McDz6qZkF(~4w_O)~ZEycRGud9P)c~uAV9IMaT&~d`^uYYKuV{j5b19v<2khV+? ztCcpEzmVn0*2@pe^|D&x7oXSNN&8|qteiE*nUi=);i`coGsY&3KW9}w0- zqfqXZ#fg)7&i&N-++5SVs`7IA;v&BIeAPeBmA)VS9%iFvtG+mDYh0rwdGfr39&zoW zI)`Ve{uT3r##iQ?_xICU>|64wZy(%6rzouNMX`+kQ z{iZo8-y}&8%@x}C?${nyBo!!gFBXlkhI{foEB&)2uVYEps#fXEduH9M6IQ=uw5?)8U)M{}d*~~3;PqTbeF~5+@{p{_oceOt(DywhYX^gks;I}BI>#j#MiTgUW zEc3^DtLt~E|FCvs4P)X{eL(&zP4ynDK2tKjw8Ge;s+nnl@%!pBo6Ggq-QLyHwZPk- z|Cx=F)l;!yPxQrx`w_=`nzQt4_G;`*gIg_IZ-2#?&mv4*^K+F8rLn?=dKLT%7BqZN({=5x-C(UW1q(ehMT&*sDe+C(;6WpPpaH~XJw=KNA}#;;H{jl7;Xv2KG7H3w}QrS2cyYHZEZ zsi_&&33;-{&c&5~nnznEmkoK_@LAFQE;l~CYQDbzX@1_)GLdDJuswEkz2$WmC+&&( zH6z#{rOpPumMxKe9qEbuja8dF6&}jJky|gj-IIjJo|k>zzo=N@Gs(|J3Num;7*jdi^tAkHRXeUItVu$@B!A+-jPRzjIv?!Tu8p$p!1Uwkvs2qf;%>3|VyUZW zSzgpD{`sFz=RS1Zx%%kv`;5wZwo_KUcedg|qB?VV(qnxeLt4#FO+L>YteqfwpgtLS zUOB+tJ-_?wGjI04`tezpr}wja75q|u+j=q3S$ZMtXWe+6$uK`TP?O0Rob+kpkc_`- zeUmEEhe<5-U_h{y8_!q7SJtm=S@qsFFt~wjO|}I42FB6jqM@Rm>|@p;v#Q>z{#AS? zJ16ZXD&S6gO`fJf$}J1L@~-j^r@xUK!BOsBjvt&|T&d1*yV3Tqs|TkQ-4!hewlKdb z8d0RN^e5ZGzK^Vmj82%C73^y2U*4sv);WEFmW|k@8_)h^jVS%Tw6yY=d57_ff=MqM zJX-N&^;=W{mk%ajnbeQ9y=tyjVjEa=)K9Flpo;t8b5zi^ToKF z!S9ORD+)}-AF6m?u{cO9L>Cyye&!+^+&?hz{xZK=#J@qX=^YOgeRFpqUS z_SF|gFx^E{#WTf4WMOc!udyfE+sQlLTj5Izwj||jJJ!aDocYG##VyO5dQ_^8u}r)% zc3N8FW^C8*I}dHZMQv7y6&~#g?I6)1*UqXpRX_OynN#Qm7HgAsm zo^OS;eq36rHfEbbAvvwVW9Pi>J}rJu_;wti~$xffzZS=YMWI@2?QKR~Z> zf4Iu3ADF4DL*Nc~fWIL07xz&Q)$W(ip||{N0`{QKFZMq39^#vdwbFAe8;jNqvIsM)w7F;YnSzXte?d}vDDjpM765-OUk&87q zxO%y%maW|ViF>*&yZW5%xNki3TpUmT@R>a%_)7e> zdWOO$-XQKJjZ_p!3WAs1jeSG7Ny7f%I8Tlz%WvXV3rg|_yO(Li?B+kkJX|IDLXyp& z@o)1?@T&cty^B5j9EsMUrt{_hSXlBxS1WQrc!EAMS=6|8J4?%nna85PiWncWJAS$T zdv3c)h81hEQC#%CPJUSux_(DJu?1^ zs~`21;p_0dvLxR{b5_+^>t1I+dzZ>J6}`>RJq46yThVmR6l^b2DL1LRDRdH_I6|^j zW|q}vPkY+it*+kwaIUF$m}`Y+k-rcAnsGuXr?-fm-^dMQbmBLX_L5mbG;a{5a}NJ> zcPGzi?=;(ivSX#S-0kG^^&Rz(!m17T(uOy^+iFIGij-3kRQ-v{pm8Z0aZ4>Z<%3H0 z7aL18#k*fmdTx7}lYh|S@-^oh((7z5?c%r*Nzt)uBNSm`U3hGE%%7UsxbtwGU*w-= zzfwBwUEW(!k*{KJ6&|n*38uy6%mD|d%7oC#I#Pj(zfn&m7>}k}1ouq-UpC{KpGWa04&L8O(J3n*S z9VL$MooBdCnz>OcqUXgVCyuFIx7q7POv=virs^Nm4oyIoL#v&Y#-3$;O8zJwG<$?Wtqhl>h$C zz5MMJ8tZu*arW{T(Dt$m%D$RfntxOmRf9A;;@+o_WL3-s&2p_zcR@E{14|V_qqS1 zP1r?jnk-$biJlT|*2YSHVK%5AN1cmER?QSqW;c69XySC2U(D;3mt5Mk@-pt)J$2Ug zToZ0ex5!>7GNnx=ta3zTMe^O`!3hrx2XqhhUc*?OO1#G1&a%>-Nt5VCkE`mOInVnh z7#@&%9QJWGvF|rx68q(L@f6Wq>8Em!db?tcIGX7$%x7-1N0@2CuL9v^-frF<-Y&Rj z+0Omg?eZQF9Q zzEU|+(N--F-=t5}nY8WY{UzDLOHWPfkL8Ce?pJ(OezUT!HP*Gq_jj<6KTi&ex=HWI z4$1FoeNl<=P2((4I}AI+uZKU=zfiOz3w*oWO@rTYPdJrpuXBRi+Hc## zT~~eU2xa=n`pR!9*J?It_o`ClW7#Y^nbr{RX1-+42#ayQqBziwZ|b+ZI@({`vvL2Z zKQ{|3V1zG4Hzh~eQ*;}=I%Mr=?e5QFV>FTaRr*HQ+3=i9WRy&M+{JrGgE369woc!y zU76PSDdE$#UDdqGFK!~73e0zGwskOnsJv*bEYRlt@TU4hbfw453p?l>#>*%ab+wHn zPHKB9(i9FA6LBf*PS|MmIfYTumhWa?QM#efQ1Z0sc1fi%%G$-(fm_Z?$Yl0Y**STo zI8z=THZ3wIE;Ihu_?q#Z<2A9PbvcrKRP68OzUGs-$2zi{6P?BGJl8naN!KX*A?rW3 z9^SXKTJ(@zEAF6tqLV~9b;sn#L@jv(_lSPUI!SNtSYSzDWAJrwmVdbSfIY%7$X({? z>UVnQ`^NGz_MPaZs4=-7xZpczukVz2j|Oi`C#pLcnnhK|cF(v|`-|Fd9 zv93ThOS42dN;OW@Dmd7F2lL6KilY@9EBaQpv6s1)1upR}=9XlF^q#~oJ*E-qo<#49 zPLKUPZfjh1()on^i2dS!`3hl_-|Ks4cUYQR4qKKv%A5G^MNDIG0K(h5ZNa?-g`y| zJ+zfLU(!ufE12Zj@2VTDEj}yXuU!;Y67bXG--|N6oD)&pds^J;E~*>L$E54Am{weWm{;{I9U@HN6yO z$r@2}y4wGPldC>iHmvB|;>>by#Z?or9rVv-K9e3)yi=Z3J=W$##2DoI#Sy$A5PLjv zZo=)TA-YYP)^dhP;oo>3TPjS)Oh1|1*pE8xHj%l&{M=g8InI08w>9`gC}k^@(YkL9 zHDaDbTvSUGyX3z~)0qm~Tif9}=>EYg4^#*2-X*RIM<=@t*F8(@j~okK9lWu=Q{L&G zD=r#bAlno6QvXH7tf)mv-D~e}tZ4Q{R)chVY_q6Ik()IgNv7kt(NG>+HnntInX`0D z!I4+~Y-@f>)j+%5y2RYc`AF0{A};2SsNPX&G0Cxaqs;pLdQpVs~B3 z*fPGjxNL!Wpp7#>tFG^O!igA${ZUd+xlxxKX^UcF)Ukt-YNuo*E{%_lj*Ljv&XSE_ z_68<<<~v`QuN$4l7z=A@T9t2{U_5CSJDYot;I2b5&6Vy|SA>l+jE>x=(`x4^y^3Gu z93$Z({k?*xxpqOdH`5X88tavKW;qP@wYK`USf|^4#Orboa4vD}_D6^V%GqI$bXNV5 zxY&&LSz(RN)LEZ0Eava1#OS4w*OaG%!|hH>oUOU}i1E|X^##(mO>;WDSzElO@=evW zsvG9+!I8@DVP^dfgDG-i42kX(xjAZR)Exau<#oc~uNg^RqvKRnBh%XIe=8qWZ8tSC zKD2an_4Ac;%Scml9cBtNJy=T|B$1?9_3RMH`Q0?F0G-9JcX}F{{$@YntvGcHN;wvu6 zd)70^&3adR-Z=`aQ_b@%QC6vSnptVP?i_%O;%w)9 zYj@2!o;);eqyCt(iFl2#j&+FfVQKw}YU7gP{;w@hx;!p_*VWk0R92p8oaoev`fBfm z4>b5=NWz%p`pF#=1F`E2^TM9Wr!u4XFZq_9KxJXY5d2-UY32IzO%=ZyW2&dx175cv zVr-&w>JyRAqbEi_iQbqvE~Qz@z{D-FQw@r+?drwy#mr#8$@!mKS3hV>3_tiPnIsZNk~l_W@F#eQPrwg<|*a(4rl z!SU95(R$gEZ`p4>YCci@#N6C6($T};n7yQIulqS-Mq*UmjHc=qe>S;Y|8UJVX};tm zG4r(wwvV@u?f1%U<-?0-71YX2eeucD<}cN``--M~(0=Gy-q%^ibX3jI*N&PU*DCp3 z^4H0pluc=E64Ue^*+RA-vsb9}+_&h>UCh_2FICR1m}op<>}6_Db<=X*^E>yH-73GR z`6hC2?6btS$xRbe!oN_Pzh>-HzOX4=$6!o58M-c2ea;9FD6_GuNo7@oVO) z)Hbo-g>O^0QY*z4|6uFj$`RG6rpx7xOWKuIls_%k82yzU9QwcoB9ZJ>jo0^z-XH&a z^1}47$rln@#oURogul|1tLjKH7_8GgkDX_%gDuUgMw`AheyCVz+-f>%zTzOh&Dq+OUVN}DvRW<-{_@qgQ+1WoT1OG1GLTWGw9;_}BA|{g>(_lc;3z z`=4Gpv$wwK_x9r3zHb`j{ZUbF>FjGvx+z`y^w@=oHxs^3d7YM*b|8M0Zku|ba-{qj zdndTtbJwxXR$kT0m|Jnq=rd+iUNV>2xBBYwV`+a;BUP7(gHh>V{qX4X@k?V{MkVVf zYgeh3iHDLId=$4ZaL?V^!Qgr@&UD_iwd!@{HOowUPw!Q}2GL0}WMRtlsw$;Yu|nES zc|*NGJyLO1!pN$n7V&1fJ1{%Y*|)&6#r3Owux+5ZLAArAsR*xJZ$0jDaDGuO_43HM zsiSL6t$(-v%i3>hH?CnxbVPlp9VertG2hwW+r8GdxN1zfw3z#lRp5HR;%&RvPhT&4 zzq7cO$>^BEPY`ca&y9Q%-zq&jZDPutq_eSIBPH6$^4_9Mb|teTSm-so#(C;`Ry*4} zN-dAAe^~Zg+Bxz(z4%FjlD#4AtNdDbIzkye%+ODNN}H|ds0J z_yU8yV?7a``}V$ew>82s$9c?o-@A-o${Hk3q$RQ`sx|6rd1t9cGECHh{g#2qP4#>$1^ARl%1n%5%+iMk@RO7hch>)n^Kx2G>CF(W{G># zI)0zGo#&8anDu?-XH^X=FB|_TcNUTlvI1%0gwn6d$5%eJ{^aws<;u^(w-~NPOX5C> zONc3p@M(`J?Xq{`nxcu!P3$F8V*lV0?D~4fb@X|i;f_4pY}=R4G>_8vbC6>yfdk_2K zf)YAhbXVF|_DEJ+c2PD})?f61nMbCRxx!ekd2pYvR&ZR<8>r$=a|4BEP%HG2M5y>M zO~g3EM1w9`8Cx1N#GuwrQEn0cMA~z|`)~OgxW+nUwh^}W_L5PJyc5QbI+Mh6w#Zf-gEl-tTR4@3mA z1C7aS$#dCY*+JQQH6J!Ca!c$tasHTy$j;%dG}TI<6Vk$e{J(^ z4;`#q;~D4I2UCK-1?vQU40wVmLJ{?lx01*5fyzgUU5dJjSCUQQDrUOCV71uVamTsc zd&L{=uN_cv40SWDq}L?t#e3OX%rTY>&ZsR_sjp3Pmym?v{bB;bP?|& zCVsfEMp#2Cpq>gl#G)M6UWddK?C1V z*u)+WO@F-~Fq7ll*qB9n(*QyJ(_Zwv(7jc8QIWq2ha@#^NKACGs+vST2%J zmL10&`<3{tXa_r+QL^*c5sa7a2ew9$c zALGt&i}`55O|zL;ajy6~7CW|uVca0JXyV)LpC4?^A7eU5w#pBxZ5pgAv=;R}<#@$p z`BX`U=pK{I%pgPf;^4txZg5|qov)9t%-=lt(BIeJl6xua6V7wV+>2mazL8KE?9TCA zI#1|8z6qbn&%tc?iN8VMlOPQ`IS+S=W?`u~%Z1 zKT~`wZ!C+HFOWZzE@J0kuke1nK48asDRya=3Tk>rxWxD4V!89&Q2s9er!We7p^+pg zJQv0a?}gL6pEGlVa3y;zXbOJCo#4I|jtDWtz@~~0Nt(zdiUo>3iq47xnO>p<=Xlyh zDB|OwB6MO0v4Qyk`-^XbJ$|lna9;3(-{QaLukYU!{FV#yi~0E&bpt;G_e08pn}XMa zMZs{60NGTbuiz4D<9gOgH`4EfFkJu75+=gdF;GnOWinWfT`9gMj*(c!YAKZ&WoKoR zWo{|*Ri=_wiH@-UFngF>RI-3@jkj~7xURwk?5~axY6*?8&;OzD18*1dg{R!npn-eI zSM#H|E?fcUA!zo$3Oo#62p;nf^gj*s4=xV23Kns0?jU!FJH}P; zP@NGG(}bzdVCica8uhp!!i$53DLxp!O?-v!ZI4^>ke`ViQT z7vAv$`7Qhoel+e+9AR#;<*ZEfDPmO0wiGpG?80LqjhtlWV^_>OSkz8bF6t*v6qmC5 zv4edlc9}OO1LzI97Q6C)#vb!p%wLRwEu-O3gB3t2@S4vM<_T5M8SJ5Z;OjJK5?4_J z_H|bwk4JE7{ur<3yYV&oyFwl29TU&q7fD1*MPXutxGTF7ng=&_j8~$sAxwML&75E| z88iBQ!DsOexO3dqU{0_<+KQO&jE%X))L=xU1-0`=?l{+)tKdZZV}1}?dq@#>U0j7) zU?Dvy7=@F9T4*Hn$DaBavV*B)yMirh(O;ri(KpN?(h7Dc*`DMt{B1{rUD-#lTY3)m zVgHV^7ek}h3_IiR^EHI2&;%rsFQM8jgW_iwc2sYm1;XD#C+zbOK}%v029f#9C(wVK zB$JtQz#NKCD5+BE6yc?COb`UKFkEO(jliWdG$!dxXXYq&gWqE=GS$pbtUEH8edHlY zW5$s!(CBujcZGU_j~~JB;S2a)LS5{E?TX##0#v!NP}q&6mxZ@b6nsHn2n=S~lUW()#hJQ0tlJ%vkIJ>%lyN zI%%ZvJ->`^3dCv&O~8Bu`HBt^gU77P+|$H6fl6pf5ZGbU@R^o5S7KeQY5p@y187tw1%d#D9&LhA4S(*Fb|B2KA5}HS-8P0qv>?dl!zQVw>q1=sx-~TbW+WWoStTKmj!x z8jD$i7I%&3@qKuiVB|LlRZw!MLOM%k3p5NW<`cFByBrF(TBMTHWgbF((4X1GtR@ek zW4_L8VTM5CF%n9(K~SuuqxwuiES}SW7(EQF4dYpy=QGhRAXo^q6TMd)UHeue9p-csI-WS2_ zPoXN2ieDv@T}H*I;TTMt%Wx%1_W{SJ8&_u<$eelWwDb!_z`2 ztd>D@bQZSf3WK0I83Wbwd}v*Ap@wlm0ooFoeFWN`XsAQvsGc^`k?D#mU5#i?#<$Jz zY5{~Yp)RQlO;0zx>Vhlx(a%1*0vtRHY%amFc<50-1u}l*#5-`~Ccb+PRz8L5{4&%f zR?Iz*aAXHmJO4m8bC;T+~Ub>MRB}O7T4peVZTSDRH(OeT6KnfM*u8%7fa?35%qdO%3QT`J+#Iv{d2DP#=-# zEfor!S>RF>^64C6_XFbj5I)+`{tZSCKs93n#!lp885CK$rj8qAwq#jD7&{F}FP~P4}t#!aE z2@sMYcC|2C8piq@nc5%xa)BR3Kqd+;c;s{fP;Y|hor4N`8LHs>kE+}nXd^?N4n03W z0;K%Vu7#rILhl}E6FVURPDCVvvh35KS}e%Y$b|pnMA1qen)h zf)iR`6WZ;36c*|6%#4QcTLD&ubktJV-WhXkEF!0Yy092FB!A4>6vWR8TwWtakFY9H zLX+x%#`ItK-3GRZVPO+6)DL8ffJ;6qO9uGZ02l~(Cc{xw^+))|i1S-R8`>7$m|(pd z=LQkSH1tu3{CNRB1W{3=Ne7@9gBtY^t*nS(GAii^jAexNH-Tdi*5TO7*Q*f#$lxvyrx+!drhAp9|vAA)z z7wu}GpS5_dL;+%x4=lrgf&$v;YQ%xV6AZe;yEb5e3K>^`{4T?BC$dw5|5^Mf&|fmF z&4>MOQQ3H?=u&Y^1wHXwFeLy#!Vrff;Sp{UT0An$D9`ljewSa*YBV0#&4O-T~D52O> zWDNx)eQ0gP`;h0^@IwTAT=3}*;%kPLS%_{M^sGS3NX)=G*dv1HRfteqc%T4B?a&%B z;IauUeu8=NFf28|;%ekcGgP$BK*EIllcH5QEDq^_-C(O8{fgm90zQRTx!_dXxuVz6GQ65uwmAFBmL>RSMLM6ma?zjQId-pnX8D4Yc@UFak84 zu!)1Up{LUr;DH-RD8b=Ah+-HR6UrzDdi@t%jD@nZJ?5Ass8WAJ21S4$_2BV!DE zTcDEkLImI8bsjV8Ta42NxseJUg*SJZ9v^U_po@ zWr(Q>*2IHv31Fogh;rcN{g3vy!f3HL^9eqQfNUm^t%1)zAbSzVLNj<27?uEaya_LY zxF}Eq;!tU&;EMvay9{xv#uF+U!Q0Tx9*4?g!b925Nx+^EvwdJ(XpNE!KQj^2bj+7wh=CH{c)`~s#5f#? z!~$oUs)IE_CcIDr zHwtTc^cjF1ZmbwAA2TAR@PnTnLX0K(Pkegw}8&4)DNI2~H@0W#|cI1QlBb zt4q;K32>2Pj0D(hLZ1#qzY@NyF=}XJE&2#O4~oHW78vPZZ|Erpp&3GkPZro+31$_* zCo?e7!l%TKJT~H-P)tj~u$u7C0DnSgi(st*$FnhV=xGuuuqgE8GBv!di8zbli5YfT zU|lGpL0qB4z`qa=L-_b%uM<9rKBDCW!Xk_rkGRId>pB=S0E>NKz60Jch>8>b*kG*| z=Y;qq#~B>Pw%{E0qgC>cyw3kPq6%Y~(LeJMQv!P_RuCLGs6sUlT_J_$FFkw@y{f_S z%8y7GFnSz3)5E{o$VV+AOt6Y7|2VI@(T4&k_z?wy-&RC9`(usMp;f4*6i*U*i~gU$ zEW!w*Y|mR9 zeuY_d;D?~H5UWG5MMBGXoQS`*GCmfA0wVjw<6AKTf;LB@B_DW9tPRl+60=&tjRbHk zA9C^*@8sjp2hbCPnI#^gJbEFkP7W=rm@ft+iNHH#z9aA%k%s_&NHlIkdwz^N7cfkw78gIuEYtc#>ci=0hI5m^BH1Q)r*qR~B>_ z@N^zpbfX8dav{El#5Qi&7#Uox2-=OHp3FXt{zC8!v7cnsEo1EE@jQ#M6DllaoC3o! zS5Ew-LC;<2k=P19=#XLid9;-U8f5S;3L|IBB*2XSg@JYrpAzp#aN+{^zpYGyBxrFA zz9*Kt5Z|ZZUlo!2*WL16^Gjloj#%cv0Nc>w03K?*K%r=d84fu({s2pfrKyPG*NPfqLHc94+=rh3& zH9>-iMtd;F#F`SDM*1VYkmx27Ef8Jz;8~*YWV|G69#W=X`Os5hF@k7;*gOqX5RXWt zlvqIGjdZk1ddo-0WcF;B9};(G zVRnhF)*%}tRv?iKu|LGVXwVx9zY}^bpywT)Ct6G-oQ#a{L;(Fp@Qb`v8S_d!1Bt2$ zVk@zcWDbm=$pLvJS|OM5g+gv9h_OcC36i-A;yWisLvn)#&`Nk_K&w`?MlutmM`9hw zypoJs5IwUP4T)K7Wly=GZ9#A>4}C`?o+TEH#BE}k)D!y_ihhWVCD!i~{%6K_#MT_qJuJ?E(T2`k|wPbgEPdUvdDZ8e@oVPJmxK=O#dRm8^Tdy z^@w$d#=i=l(ZQ)w%qNL^HOM{Dc483%ph*W0jo>heLy0XRkrIg}S&W0&L1LSUZV-th z_L96$-qXrj@PJ#y(vfI@pwNbZYa}zoqF*P*LOvyV6*AUPjNb!lNi0aL4v|e_Pf3=R z@Xv%kh+Y#tkA+|Pi1&%46HBg@#dd{dl0hRvAbT6cR}=Usqq<@ktCUZ~vAn^@B z>~i8c1*0YN7=T<69XFNPSujR}!TY zN&VjwvG^tjl-TgE4HQ_RS_)5=>!YKS)l8@SDUd#99(-{{ij#z!eg| zk_aFd?U5NHt5uQ(BN=%S?GOr7&_bj<0GUgG_Uw*CJc5sOdyBVLsUBz7R56Wu0pBcYhsT;it{yicM~6W%A0Ea4Ne4@nP zKzugondrKRXZ~k{$ZkLwWbS{yhiHofPmtJ$c!vL3vr^FDgU=>*io_FyPZU}uBP4c# z#0Es#3D3xgi8mryG~z*sjFKpw=n%<33K$Io>qX?3_~jsYLa=p-CemeNlo1J;@D^F6 zlem_wrz{vbi3Lj0rv|FXn$QB7j6q8zr)dVY#5R(3bUe67G>Oa&kykQ{QSe_%ndE)| z$B2ggZ&mp}OR0f7!~*1j+r)>E2#d%a(O=T02fvXq8!%UdHWwsIE7KQ3C-E;tD#<($ zogr4Av`9EaMyz07$!`HjX9?(0p^0W_Cy^d99}31p)V-%# zvA!f)CYeti|1ZJZuw|aIBD^@sd=jf4#OK7Dlc?|mqV5tr8G_%*tdq^Bt9f-K{Kc(kt12Zl9-#&=0&??^`jx1 z7lywHssfK^NOYNuStqN?JoHqAAL7AC#w!!O+aQJU&`Og1i$LpInWu{^(|sb5WJXHy z8Sw{XrbImF0_R9lkh%St5SHPBCK8n zxa2|$)$lZtgCL}X%rx->WW{2`Y!gpRRw!n8cn4OpkMVpGM*9l0nTSjd@qae-{=aM` zS+RaXE78b!HU=LF#i6iXF7SdvPQMa3C*XUsM@ZI39ISJ4nWcY*e9~)31o6JaLKI_^ zA>ajx2T5d0A|Dd77l5P0#*@`4+0`R*OJYc}ii<{n#8c+rM?!pAtL!}i?-XE6WdD|| zK8o>Eh~NKb&xp4otEM81FdVu|tP6?h$y$Qs`N%$CC?an=_(^skNX#6M^#qAKNK{2+ zTPf2j9{&;_LSieD1^S;{5UWqD8KFG@OJ9s}6L09ov+0m374y{!KFAKaBsTLSo+CS} zCOkuIFY$^>*_w!~8wrAJ7V;%t=tKhOHR10#_^$uJQ4+OR1bxJcNs##5GF}o*C7ekD zRm3L}KS|;V7e-8Q;z`zwWSQP!EhK_xWK?7?k%7#)z!PF=h;1diTO>Ll`IQhnL!{jW zZHU6>NuY!5=4F5@B+e#SB2}@*CBBWUl!+%}KrONE#2(Z}kHlt@IEcg%Bu?WYU)7OE zuMXaM%cu{<$jAzrNCN3S6aR+c{S@^52K|r>6N%?TAtip~F788uR9Kjn$as=pZkdG+g?>arnhUWuBM}Z+WyF-_ z$`$nWq>Kw>{aw8*n?`o3DuEZduo7gR3(>0$bK^h`ob1q&EI5%VD_S9$H?p%xvgB3q zJBbMt@Y0K3h9_coNJlv2o@iNZjDql(%;N)$h3vm4;j_B< zAygHYwMO>h?T{rBPY@n{#GI2{Rw^_uxs3N&knMbMf#^dNxJEKWWZhjEJSF*Xf}u*{ zR1%N4!5^|eSb#T3L>B>lXaybfLDKUussixBjM$#67zm$;3@T;sdGR-~Xa+o;inf!` zw+n5MSdY*}ctAW4v0()3)()K_>p@~U$j%kn8zXj~$a)DzmJNQAom8@C84IdY5M@5Y zC0C0cVs_|thT)1Y619c15b%pBI`YGS!@=DXX5ZYp`XkKnI#syZHZ6GZdq;_ zbu=slSwqB@$uP0m6~HMs#`nK9qY3;b_PrQ-N_2o^yNFE2W4s=4h4@agXRe}k8G73q zKNax=$-SgO^6x_%Nj~C3nYAD*GICC%3G&X-kaaTuB>E@kS0bT_AFylo7%h=8#z9*u zVu!Ff{tW{~UW|jp4P-}zD3yzdve#6Q}M?8v-K8eRF0)NR# z7h?HDaO^(pX&$&iq&ynBM^1oL!48cb<0qpf>vkD?WhtPHtno=y;X_XXJS@p+lNB>r zwN?Rz96ZuJ?0e(_Gq(wThzz(f4w8*0J8(n?lrrB`h?aBVQ;CnXfhw{dHGvc490=K= z&cPcbgF$RG$zK`DGLI(YuE|*rlB*{9O|m}x4;g4+%VH!XpB9UqwmN7-1vft6Cku3v zf601?#GW6Z=a13)XTS-*iBq@Ba7thZ{C7OgN&l!%0OIUwOQI$Ed_1nU}v`tP={*(%Xk@1x^306)l)dtXofV`0|oc6 z|3p08Q|xLUgB+fwY6E|@Cs1S0q8gz#)fi_0y*Oc5LY<(iFt>3FNvb|U`$a2{(}(lb zBt?|Vso~mtg%Y-xq~-pU{lZn3-9R2en!Uw$)Soihf_@Zj3emB@?Ww{Wnxi3)DWaL%E`j6;3ct-@}F{B$`nRP zE%jqKo7zh~>xs-;_333sCAY(JtHPps0~=hbS-H}bq)&E>ovgc%$D_G&) z;`^o4Q_woMQ+~^m9YQar$m)!0S?)x&I;pXhOc9D4nfv>jWv}x;QH7GLz?D$?Q*awI z+UNE%q38zx<<^ zElc_gRI@kI0?HX`hw-u1XIet-5;_Dfh_jFeILTM!j8q5tgs?>%sYGh$)wAkdsu${e z6jV6B6`OhomL4sg?4DTiXThrMS$X?|)5A7ZZ_#LAeYVMDzBa;?9Drn=3EP_qX$%_v|nE&1rTwkk^$b7x039J;6)MZwT2pF? zwpeMdKBOczn*CZ`?>}1d(7C9jorm>)EZJK4dBGV^jRBdal3;0EPg4UOvWxp9yC8>A9!-!^<-SjHS=-cJolfN%- zcJcc_7F#joUgWljefB)Vb5zz#R5$Ie*fEe1XrY{Dy{40dQ+1CVp>!A-2eG^D*_qwG1lnNWuC7A^+RL|6GIp+Z2VZX*(5lJ;hXQ zN$QNMY4Mkh3Eqd98E^Z(e)PJ}+nlt_?9*-_U|Xz?$Ci408lB3X2EyA*ARg_H(L=v6 zwWKDA-*|s>_AI!WU(+>6d}){-wl=C>#C*G8{F0+_Pmf*cEldhD7N)85S;3(2jp=>z zkHRRiwK|;^*ehHUev;v!@qu9oBS>q#-jY_HRPh3(bN_MK^eyeB@>0Gg{Ut2+7nXJ} zYLt65dv4(^;jwLBxtX;qHJsMqV4eLa>KhOrW&cxcT+%$d`bS^d@lRW`R~2k19_Rem z*`l<4;ITf>Iyt7We7EXXQU_M;o6y6&+TS8)+xr!7?z~O6ZAV+*yy}zC-QM3ho!(F833H!Oz8bd9zZg;*<9Ers#LnwMv>iPIgOqQdeb@p2Tf1{a`(9 z6-@0ogT6$X5X|@A_CE>S6I#fN)$;Ic&v2L25%nu+wa@MxmwPySZqY=!Y3QvAf7Uuv zw_cqtwZznI)kdcjJ8p`9=e&6{?&XHJSXX|=h~dS%ze44t57&YH#5cAzX_`pbvrr`VYH2-M+wb+Q~iu|QoD=WJ>pbG zJ|eA^TcM_+pEOnaq+a1R+A_m>hu3thFrJ|-vNgEJ*VQ}6Be)lN4E`fxf|cWQ{2P-q%N} zt@WZ0ahkEv@}u1r+9!NtgdDysl((mtM{umRJf*0~alsZ+OVz1y`V!RNOruKa-{^7rbES^*MvLW+nq%#K>~k!A_(VNMwEI#^ ze{*IQ*LNLq-wRw-zGHS93XMv}G1tP}ysXlKIl@Nk%A__ma_jO9&euO!*PJ>n z5( ze;{=5{pe}rndTYm)%<@*A{AwY;W=|CZ^^k(#Kh*x0#`>I|M5r6x(^ zg=^x!Dvvt2Z!BvqX~uVqQLQBSeUfLGyJ6|&(qiv)@wonsTWGvy@Y3zXjjqz1TG@As zMCrNh>%a*7c50 zp$#J{MfZ#AmQW+!7?o~o$Td?Z2^V~CORY|+aAfgu_js`}UD5cH<&E{C^}MB-`4=N& zsLYk1cCG=U$q~4zVUto$)B=@*(?m^qNd?&d_(6uVd=_h_2djP|)hCpsIZIsCy?w=_ z`b2KL!O!6wudu76sNjdfexCmNO8cs~nH9!VpHt^jgT4(SYj#P#V5=k7b{@$7J>yp9 z_c_z^CgqjS{WoWA{!Jr$2vt?e(sACF$V>O+6MRo8Rqdh}!)5iFK3h$paIP zMsE%qVUMybGYq8%4ylj!T2|2V8f{4#%X>DIwErX7gmjYHl90 zL8pO7qy&x7@BWl9CDE>8M|;tb+WWD0_6iTJPosW-=$ER2_ZsNj1cZ1I`hmeRwX z?ZRfN*mNY+6SFSmNY%=9PByqve{8BbrA26W`kwb%zLLHx?Zvyr??%6$^zlJ<4Od5D z3}xrn8WtP28TJ|XnWxzHhx82pDdLZCDWtru6#mbk{N?GMU-a?Ko35{;-*ryEm%qd_ zP^rQ9vFTwuqg%(1O5Bk6U;L#QCbD*DdD~Q@iTM#|dPd(j?qwwlfV?uibd&e@U|XdI zUD+_f5@$bcUu)ZBSz$V9*u)*6AFH9#v0&fe8=;51Uu}b2!%&>f?25Xem0E;yQmEzs z$1~IO-n+@)Be2|`>84bftq@rv3Ka%m}iMgl9wjBVh)6x9N${1;^{vqUfU@* z5}kqS{-!>MZ*jrB@a^%>!awe zf&Tgnjq^!LZ*f|nz<1Es$G<$VIJhzx5$Nu{UixpT<~yt8@M|0^qhb@LmTO*RaO(A1 zr&4cMa>w^UK?LPv$ZavZnW zERBr09Lt^NGWb<|fbJm=@P1L;BrhvV$_UG}V_{s)J6=)v(IJ1u{FJmkB_g?Q{IIAl zp~oz3xd`oom=#omH--9Q8*#ljRB9+sM#^Ec6fHkgy6Pc}i@RX_U|wXYXl`h@&TQ60 z)jo20X^yy2JS5#y0{TAIWH`bPViu|Ig}?p7d{?~NJ>5$~oNQ^x?hQUHT~rvK8=pNhdvETIg8j}to_=COW`ylc z)UCuy<-*D>NE#B?D6$z=sb5nQ#VOwJN+!EHmA?1>9kj~B)oOYnb(pElmFGM2zjGVe zZ`@d@T zwsrc@!nXc3T1UR8d5TrEJFx-(VL5LZYYsP7=9FutJ?4nPBrqmq6c5^G}-f7Dh_R`SU$loIygimq|wB9z~GtDzJ zr1uLEu9sOOX63EDSu%YeV6V`104>II>tt)+4N?;$_Ot}Pc+?N;sW4XQM9 z)oWV)Wx^(FTls-=arTpsZQs9pbL#c&Hy_jf&RS5c`QK@4`4Dp@^K#?ghA&M%>!Xmz zVb{Xug%&!t+yAq!G#z70l`6ivg?Z^O-rangmo_ldQE;$yq3A?HvvpkO@l{bnD7KR$!&m1d6(_LE#>mKIs6ZNK6jX{&b*^1 z;O3elYPA-w)R6?-mGM3FcE5C8xu$)OD!ch=U-@ycoj1)T6qPUTQz`_%q|Mf=k#&+6 zRoPlotTVW7)mnL#-^IVQ{jH8JeVEH< zf%(M$Y56wfO!(-?^^vBCGa+{@N4dFbChqM?$awYkv)9452^s#v-~2iHThrvw`_aZk ze@bTg8|5w~G>qWP7xd0z_khcPA`lzg71-&I^oImq3(u5?)FQSe*Pbn)_tP(#f4EwP zs)nW9d3uf}%6U=+dA|~;{i9Xajw%D>Y-xk+mOCp;<==&6zL=8zg?$Q^6gTkM^xl^C zkpmKctuVgYqncalG_G^BMzab#qAD5Z3cZSJW?%T!`(wh#jE@7;Q?tVIkGWb0!qg)A z1KW`Og5H42lTqvrQ1=&wry%^j|IBp55VN_xFFKnKI88-u3~q z&vehxDdO*_&N1a;{V~N+Tf#P4zv1Un{naOORouChEB-2&5RIJmk0^`67a=BXj{A=K zvZ;J|iUphH?N?u*jt6_ zVc!;awW7PmraC3{JoTE@DX6v~c|hn^s;|3oj{igb_k+@kK89qz&)$+3SLAb5^ex3& zE)=&;?PNBx^$iOx-jF3x8{_WB7sU(=TWTt&cMtsGI+Wim`)AL7+55ax#*+ zzT-m3mJr#o!11}G9FV|stVZBdjA8bm8ud0RNw;fvq?3VH-n!lwzEI(?d{IlM!k7ol zpKM1y4N(L^lUz-$RP#{B?NhdB5^gK2L>X`dq=JBjCg$Dvp_?l65 zE0jyUQRnBnt82fjv7+)<$+jrkGE3{{tLL0ha5#T~Cz_Y%gp-+1oifIBEm+gEh70KQY-;`h>AU=^%W zzEh+07W7(n2mg;@q2Vq!jB)FqX~pV&tvT=(La9dz9~@93=MBx8l~uLihW8%jx2MDj z<@Qx>SM_$4uPYrXcRgWp)G^1O#vSwoWs)$^Kh5)5Nm9}J-1eD$KOOscIell&y5c^* z`#>oU7$?}+&=29`qVl85#Vm-r5mv{R!k<^42cDHyD^4s}nRh6!TfwN}-KDGib>(~1 zDgK1{JUm5Vh&8lj$Vz)J>wD8jLv6kR$8%}y3U(56iTVL3rWNEF(j_TM9w~Q}w@8Y3 zLHtbGDX&y_>P_f<^cmdfxJ`3wH>s)Y27U$Kk@-ii;2mAKEc+3TiFWd?qDt(1+{$vM zN+lJ$l<$y~5&I&tXV`mtdCMF_9#c;5Ajbp;diFaf7nqSnshzbtyJCKQr_~!Oj??~S zh8x1o`Id&Z3HGy&8zJc-(_!l~4DIMo(s18l*WSX{`9llN7j-H*>-|%R*BY?j82ehR zwtKceZB|>Bx#QymOh;(sR?Jvs)F&C9Q&=sU7ICtj^}KPuVEk zD{~euaHThxsFI{Dv)NE2uFQ?dT;peic7U`nGReAyO=Ikn@O{SKLm~j*GdC5 z+(W@_;x}?JOpHEFSt?Z&4+We0H@Qza=N3IGzUq0Q)H0_;WhPB6zca-hSAbiHu2|Mv zA2_y#{~bw3J`Wjh@@UU}3yLOY4@w{UX;jA3oEt@bJ#z)Cx)(Qu_SS1?7t|x#&-4yM zvVDF;L5wT*QPh1$Jpa9PzVx?(W4SN#>J>+No(1ET3EF9`gW63_kgiLY)Y*{OPWGK) zha-bgcO$&&eOihg8Y?d+_tGu=)k4sDa_0(AIl!>$C z8vC*JwRCY%&=ZIiV#T_`c>i_xTvtuka!;Z>)ld``l8{&~FXcwUgy`*I(U6@T;WeY~ zMAe9BX?>m?j@ne^*wEqy72r?WOfSwSq6TTE>ZvW)W$TMG>Ee zt+gLA#~8Y@v*|BUf0dzMqG~fU+4XEXJwQ7z#``b0kCguE=@smz7BkBYX5&OIlsYK) z5rzjFh}#uZpfM|`5%Lb-8rN+^U%La{7{$>zE+V-wu~y9FkSgX9Ll<+ykkip861ycY zh+iL8#8nM`Rx~=ReR_|KzB!)?>z5w(9`)Vxmb$+xtyU_#V**{247R(iW285(RpQU_ zXCn)&JYy0gy_4J#z75Dsg)pDf=anP=g|43pj^tk`zUI5B9W$|^6C%EiNDFmhJ@S*G zF`vw5^4AQ>#!^EEgNYXy)PT!3gJ1dTc?#U;yfuR(@`J%t z5~I>}^^an-x32SYVRz?D|1tWsqfy+_u2l!w67X}M~<@=+S1eAhS^l17UdKYzD zyDWDOe(AaIn&|r6b5ybzyrHSF@$s9Z=Z9=E#qfs>P3$|Oy~#xtj+JW^d(paGd*E&7 zyjRr8b-;5ga7ge3irv1#!Ys$9x*z|^7+Y}FyI#9u)a-%Kd!aoXr!3`-|8SkTL;M$} z2G;8K3ijES%iJVok~ge4GJjY8Y3Egc8|@Z%(Rkf(lTlSwnkrw{Zy0Jg4n?et>K<|1 z{gW%dO?(Bzdp1mOBlhr3b60YA_XYw_rA&1ecKUu*cgj_z%DCxeuzFBC zq5ZDh5Zd}u+}+(>1Hb4$T24pojcppcIiin!h$+Q*-4Y(|i7S_ql2S2lx8oYKTbSap zx>tE$1gFS7lpnV7MB%`82NyVue5pZ-gh+8xlAq-cwd#N3*%=myQ8zR1w-KovB^y@7#K3 zthymEvGix>wvq#Z7&_OwBSMbK58rRQZdk*;Ft!N|O(?9GRwb;$h3FloNlI^jb>HjY z_i8`-EcLIH;(n96_S1+D&C^fj9(1Momq>9yL#qPZ;~~OKpxk%m+nKjm*V~rZHdwn@ zrkH~!yUAh5VxshboF*~KTCE-JW9~BxsJ+VPg3&+OXAH(DO_;oo6ehg%QbVf`Fm4k(@o!EnXV&R>*Ul~kUxJ=wzHQeMe__)sOeC9CImvyp! zHWmm%o3xkmpJIkEM9h$WQ+RE!_M`Su4JwtDba{hPPpeE_rW-Ix^la>%>{07d6`4EqU9Fz%5)KN>r5kD{70EVb1Jnog zsJuchQpeCGYysDW`<}Utvn<*AQEDrFgZ@a_bf>aNj+Oh##aN9rQ5WLA)*EtrG0%U{ zli+^j=_)j)CK-RXEH|A;-XlY)!Ys0SBUi^yi60d;)6v~L#T0Ej5LOylK4On;6SrGy zt;|wV)x*j&ag1+)b6Vb~Y-cW4+`RPr(pt{x1?}?B6@Fi`%GW~lt5zn4GjK=QPW;#A zMfS=e;~b;ym+Xr|T7-QHo#nV~osVO}q1*tPrK0KG?5~J_b6_25>lil zN)L6A(n{RmJ6TfMnO?F@c+B=kHu?qgLVO$$lqKeWqbetw6Y54a3^`}p?Km8f7kf9} z8$H=ki{A)5m%o?=+%kHz)W~zP@OjRM?1y;`oTcusJ@cG5a|dLF=H?eu-b(%@$b?M` zzLekTG3*AcSRD3=w#{azv7;p_bXQcpn30h~LoQf;Hx4rFFibb`R^HYG_a?lP=L)P8 zR8y$>+G=s9{~u^pj%Zc>RB9-Dq^rV#;1r>Od=7VlzoNSX11y}W#(vJ$WUk{Z2yhOl zT1*0KXaAtT(^J$F@@d(i9@32ZP*p;fwY_J!Tk^eA=JWl`G5jF;f;ZVehH4nHC)OQv zE2N%rI9K2F(LqISjmn6q5PHKp)U?RRnb%obo7->~kS*yDi1)AaZgp2Htz42_d?NpO zc2#8Ej(Rfves_AIEq{k|lkk#0!F|CD!A-*|y^ybCUS@w7HY}oi=vMP;F2MD)#D+c% z%X3_|#F}OrzUKNeqnYyja8q4V9&=9i1l?k|-ijGdb&+cZ*9V3OZ;^ldLO2{8gITMf zBx{>-mL(Ipol(kiwHbAbS;#hLdH}B}lA2Bz(zmFai06{jLiM^<4){L;a0DZTUOtnz zWv~PFh3SlG4rK)j@I3joB{Ql))MwUDK(kt8xrRFl*G2CNJ!AdB{K#~`wAwt(ddeDa z@=znhJl{m0>hBmFhA2JByUsPWkSRRiQgJiV6nB?=Yjzxp*lMDcy3z+v70>2ih*nI$ zX1f@^Gy5%b%|Sz=@h9t{u;-CYB6^0nZG-Kz9rx{Xt+UOCO!tjDc|X&PDbGb2`f#Fp zCUC@iD9{nU@s%<(SlJuty%7q;cMl{L4D70E%sVqO0UdmQ&G1ZXS!fc=) zAiMko2z3T#5W~YFUsj{E7y2{$IJ1jR*KWw)Nd?Lb2I!fF#nd$MH(@1p#M(T}VPDMt zs@iD5GBM(O@l4M!!R)sp7-HeQ%80?^@{U;l2}? zE-eUt>uQ+$K6jQoQhUfWQEU4)m0JBPl?%A_zAmkCMP|v8X&BDbXLp(phinb$X0aP4 z8_(Emq1}K@o?@DAF0!09-$Wj3tFgq~$n*x;+?8U6@}7D_T~mG#76!+NF>-w=5qO{r zJimHkee(l7#Lid?S;f{tN;n`_r-HcoW+4@=C9AR8HJqeqYdB>1if_SQ0?Jxfwl<&3 zH{=>qKg->P_P}Ll*w(nGavRkYak)c&!rigFHw|EVYfzvS?Y+iFXv|}AA+Mr+zzb&t2q=QSkF_txL@Itl2gGjX_V)A?#0agg*AdXxM}o7 z>9LYNf%obby{;;#9&VmZv$Zh{pc2?g_KndqV|s;+v(~lN4S5yTICPzDuH{FIWWH?Z z#+;@`vPs6;#@@_T`CV|Jz{nGo^0E=P!*2D~_tgqS3B84Nf#trTz7ByugsI3Ib(I&% zh4LyTO&vhBWM6XKxiic|dLZ+N?ai+-)HXgf%;ul6e=$42pWzH}-?X3AWHB^qH?^s@j%&}KB{mD-@J~5ZW{3lt9?3W!qt=IX(%sB3y>6CSdnwAapKa*MR8YE0 zZ}l0bL|X^rui8k-pl#q=Sq7UE4F|bY{t?%Q*-nW}UDGX#!MI!hAUTxgR3|2vx}|ki zmq<1JX{Ci8PL8D8soUHI`2&is_{XSk<)Cl8ySlHHFkToEU9(GS@WQyxi)rZL%J;tqUm$y=Tuc_TnD$6)eBn4p@frb*bKJx{|B51ukQ5oW#WQ!=1-ofqO`u!GOCxgdiaR2x;EMrW_)d21C-bE)*bd?wkk#=JxIg3OYA6oPo*or;`sVn z&jnAa@VO=`QdwwU>ntIi(8ZI{{9Z|oVq zkauz)*ss_ztclylwdXc6lc_I(D>ICmLv7U`s{Q09Vq>wpvX1i6J+!XEbN_s41$)XI zB==j&VOkHvWqX5=Z>^ePEuUd1G%d3{v;JUnTE-f_rEln!nS8DSC+bh-JK}!fZeW!E zMW7W*fnWJQIrkQZmtGVXYgMF0?xD`sL(#pHyDkwp)K;yqCYrH_)*FP=N4<5)kVrwB}45+tz*513-ZMDu&Y97>f&iVLL$atHaQ z)LL=|=XvfGk1Vd>{Z5WmKlsNNUnt;9n~VS8jOJY7>tIJQQrV~-q-XG_j57b6u0c)b z=GbDwD}}YURyWuTsg~}JmLbjUKUl_@SYwRgEgx;T%->{BQ`NN!>JXLJ!nF^|3h8aI zMqp2%NN6o@!+FGexDlm|uv^}wc2#vbRh}-NM~-bEJs7vDb*JkCg>fXai|=n3!=*rb z(wIW_J@8XoGhOKfsypmQUEpf&*M}feXOz2$9-)mqO>fEcM7iGzpXmRn%`_deL~_59 zo4M$JEO$cwwXZVyI2*shc*649E{2?Qk!if;89x+v@{AQa3NwP6g0WIv zrAP=VU7lZ9u)+J4@~>R%xlnkj@R8dgZjv`kH${W=2XL%YrLI(OQ-QU__=uXPjpEYn zQ4xiq?X9e-vN_at%6`l~#@^koTd$d_@Di)>yG{K~ZMjFiNa?-4uk3cfD==qlq(%qYGXygvu&w!YHi%psBu*dH@S&S4WNLw zV!z~Cah(u>E(P*zC3+j`xTot5eJReT4N{jW?d0jwY`LLUpSq|ulbYfdjyv=u(*#p_ zCR0vPzGPonr-yiLeN4I7xBn4$)B3Hw?2ByeO;?#Z)B@&+VVUtW)}Tg<sEA zy$DHgBw04$*z^+13j3Cj<{^ITGGlpuh@m(3(wCY}ai{1$)EUH$YqUJzcz&l27Z3P< z^4Ai#Dn;^N!CJoZzNdko#GtfXUM)Yv92^vXmTzhttx|LJHrf#Fq&}JUFelg)b|RgP zx|Ap;9c#=bOeQKSrcjx{`{r>=>Pgy7>(o^3k?fOeQ;+y<##_uqi4P_!eUPzyYe{5U z%9WKV>^;jn+X!8%h@jtJxxnYM#C7K%1cuOy$)NQtw9M&CHa-uRJa+eCn@S) z?I$tW)2SrUXI5tGYvj|ubMAw_3*vaiq!dUVX`$Q$^VwN>ihI$9b0(&Su4+KkG*mOs zH&-I4i<-r>q?;?vf)xYL zv0rjbjuLAJ{J!)4fkB@TDGiV=i={#fu@X)|BmvL!j@AO$oXzMT={xi`<_bHSOXbF~ zxlBIOfIW)+u~l3aPBY>}KF-v?q_5&6!AI>^`HVPLdZ8B63)sxZap!N(OgAY^Th1jD>uvVHD0MPB0}JS~6~}ftIabM6_{Py(r!e zP8LeU`O<6ghHyFfGB7<55O?} zVt(bDGtHD^;z#8#W}~5zVJ5o@n6a0bZb0+?%Glf3onOn0pf@o4xSITF_7*T+=jm6~ zxyn+t3J_-JsX4)D|AycOWxqB+9uTl>UeU6zgue+27@7341RdvUbb5S(hKFVlLe zf2u&uqz^JZnJUaPrX}~3ziGH@_{`ui=!RcRbIoa{<;K;9Y(ui?hN%eh6U7~1TXAQ( zE9^m>YD)$d>K1*xc1tlRGZe3~QnAYq#gXDpv76+Rn&KSeJaM7$04IjVDhVp5BueeY zz0z9M4a~DlWcWL2)2VaJ@4(c~z)JrR_kb@3zdmv+`2#q?eTP5B?q+(jCvZB~&aS6k zYdf_?`Vj2-iP{xKmQv(AWe2c#E2;D3%{a%>7AIWi06TZ5z8cj6JZ%Ol_Y}sl}XoTmz_}XEU<@|`1w$}5k@PicG4-CBL^Dh` zrZ3Zr>A=iqim=j5W?wMdn7vFf<6v(x?U_>g0ezcZPbUDoxhZO5-lC4Bzg|@@MFmI) zpu$(wz6DLAv>*_;t=f2edQdy3@u)Rf2PA5rHWHZX9e}v|9}t3pMMf>A8M+bt!+BK8 zgrhwPxN*bu>UukUBG6D91I@XSJ_h)~(ZAC_(>`hzH4iA? z9q8epDII&y3#h5UW~vV!jW5IXJ%+OlSF~^S=D;9DC8zcsP{8M+60Q<;OYZ?>=+639 z)axXn7DxtC@z1~_Jdaw)p=iZHtwp6w7xdd7HE;)kyj&MltwC+hVN?rd0aH2>w*DBf zuWzCvX_P)02ybstk8=n=F3Lzh1#0+M>M6#k(|^+UQQH$s=~OzMPDj$Q)MnHQZ3cey z4p4d>SjEGDYrGHmgCq5!sQ1}})*I+m^nTEw%|Nbhq<2KM&}yv04uC_qLBU+`=Oi*W zhW;zCu0FOT6xamzA*!Jq$a#6O=eHVnOr%pIQK_^St@^1RsQMX<>Y&Hq(EYB zoW?U!=Mla2!)eROsCRpZda|i{BIdgkIOhjZ1$7eK z8|p-*S{8WL9R8y%>dy$SN)zy}C(tCjfIIEbY9pYZ{|Jd&2&~HSsK#mzeoqH-_6VFM zevV46ig>ai-uoRG@$-QUnFjvgW_V^ zFj%6gkQ0K**$35(^Dw(NfQ&v2EiM7q?2yS>;N^12Ri-|QnuKvKg;nwEHBrZR404x- z|1|?L=3GdLq|Zi0SvK&-&*A^WsI3^ijuB+*eZYg^;0M9)O2wE*fe*DIIcXSAOIYEl zsC?W7Y~4ygwQdVeUdLQm!PhYA05lmlYC>vrQH{0?ytxZa$cH`K1XS}sKnX$n^FqVY zprv(T58neFAOh|5!uefN(<))^Tfx>-=({;|eHgU;6P~exZ{5I)zo8!tKC6szW}_v7 z>_;l}UO+zxVnQZ(`xJGNr1F|z+K{SXKW07+x!wk-EDT3|9>Jh!21(6D#oq<|VeyTH zdI(LqiVDdj{GZsXbkq#CM=L(?^$qGB+oB$DK58BRLGDxrAM4;d3cWXlED}5;7QYjO z4}ug(qo>!P$VS~kD+KYfF7^>_fD^d)2k)A}&AZ6ElX^fJ^pM(ff)Dx@Rec2gj^Im@ zDnsm4K-OcZ8{leXaH$74<3cN$uxhm+*;eq6;AHtBHKgLY26Yv`k*fLjnAwW(Bu?17 zJD^R*tpaUPzig-O!kSn?DZ#t2LFePZ^F_8ZMg*97&kr(RoVC`~%@4gEb@NdjzE@b;XM)Vunysftb^@aKpirCMU zz^DHV+B8$&3z}9?dm*D;;49|nv>(BBocuDwyWQbf%Kf_#5E0y+{&f2ED1dqV3sQA2be z)kEKiC}2LGos9_lKJ^GIGYYc!B|g1{S*-~#vPjE7{fne61TMdw>IG!^2*fW5@bW2o z9NiLcuEQ7z;^sW+6u8_UT2u|PbR6dc+^|sXp*yv;&dg54Yb#I@x(J@}31npm@bRCa zF7qCh1bY63-T6ryMWZSclIjFDe+;B%HN4GJtvfxCs;TAE>-F2(4SEH<*iG~u%REy% zQ=^$Y*~j4YzLv_|)PV3!4b*1Qr!)(yI+p3BbW5E0`T;V%l?sP+^?;R_f+%DN-B3FR z3HU?%jqa$8r)tnP*p}(^kJ<_FmDAUN>%el+uT$#~g&aXvCx%W%l<_zHRBHy!>_Mf$ zp6;VUwT-wD;Gh!5#^__P7kZLx9Sksv^$XC~A^Ltg7Ix6id<|Xu z6899`pf+nw=p*`iEuNXA6ya8n;aYvVK>LTPqkpGQqhDz6sGv53zJ<5y(WkXF(EQ2h z^9$^}RmZ+t2|ZTp2~YBcUP$lItorY?MXwB9U87G052|4ACmp)^tM)B@U#oG#maBsNPkQh&2Qsv~jxwO3otUeuEG*O(0} zBEM1kD(ws{sG_!uu8K@)WdJwr(<{;wR7ttdzgEQ6L)m9(JHdI z4EF#XqONFv(Pt4gCQuu&i)W?2qJ!E@?0AOK|4_X(GwpzlSdU%5>*xpfHE0XzqW~Rk zMVG*SFV*iOUW(I=bRuj?8sap8%GR3GFM!g_P_6aN^cgjk{+3z*sq2HNqd*$~uO2|m zxm9aQTlE*PI=^7;K2EL3j?~K0ZmLAdM+WGQjukB|)NEJ-f{xyk>ZNtSy&NxKXRP`a zNZni5LYiKVwcR|(;|uDb_6qB^ZipPGX&>o9RId6GKKi1588>Ithb{XFbe_UpTvecb zz)HcGg4z~PB2r$Brx#IkwZ-~y=+zr)gx*b$rv2J{{QZ;O9(L}z_5%0DxS@?k=;c#= zCY^!(p>OqR(CnkMi2F?bqX~+1I5PM}kmp^%ImX@z>`fQKq)LLycb`M)>%c&7` zb1eXS{Exl|QKgM)hmqW%y1@Q5hfN?iz15`Mh@Sq0CAkTGEPyRu3u{e7o>$SaT9*DZ z}x*j!CYe4PO%h6SE zhs|X8a!;9`I1Z1x5LMr+=w6Vh57ahTu?u*=8J-nj-S_Ar(9!+y_%5JgSEXjb&dx`K z^EIq_E)W6I^v9t6U+gFB(9MvK(^&hQhL^d8ede7yN25*t@{CbbzAhG(>S#s9MmQa`X_$W)z~i zg@}I%8iHL9*U#Y|qYnB@jojOGPTi_*M~&n=tSv974m`0G>zq7z_|K?ixc90ycbt8Q zyQX@wuecf9H{2)I&ZtZ)W+JnO>5e>D9JO1kgp=H&+FlFCeUCp&oun-iEnAc?6t6r? z-YYjzPN+MuKHLkhvIOg<&*&Mr;b|Z9nE8fj%gkam?BvvEUQ#vbMfA^zey>9BI^oZD zZ4>S+dW1X3Y7+1TSs_J;#yPbA> z;d1F!L==_SJJ_(H#uhZTNbqfy%$tK+J)QeDZ75} zbJiF5iMQ;t_gb@N&Aju@tUcjyJ?*II*?4ktpz!&Q_MTpxo>y^x#XZ@3QoDLDq<)k6 zA$PG@@*eL`?nHN_Q?$G6+4e^J7uEEC7`_v{8-5-gENz~Vtc<=4chFl5{u>XdGtrIq zWNU#k<8{#`@!##kov-Y7tv%w(=<#5ua9G@C<((JoOOl~sx33y)^$C04UaU?|vlQ(= zD)bSnyVgO@0_RM7N$lw~+H2Nqr`?KzNyVw98?BvkN2vSvRsQmUcS|RD>6-8B_OAND zc_&(v?C2d*F{7d`bEK=co7&6lJ)BdLY0AMokpCn&-&$rL5smM=w*8^@`T5P(?9`c7 zHotez)V|*bci8*t3`SO+(E7dmQv0~~B>#-kR!8d6id`yqOGnA9@au5EnjpUX3HLr_ z_V-GDj;4f_;ZyWZMIoZeQ^7xBmTYwrGDyE97rEN8#%xZbJmul7Ifx$3Q! zb*{8G%NCDFs?}L;LA*R(8y^&X5bO{P^}q7p4b}yBM%D4N(W~Ks(M|HPMPa|O>fE-% zz0G^cYjK7-KiL0vmZ}1I3-?#+ae0hWtgQ2vaMluk(ZCgbYx5P!)tSF!Z?=~9&+A;! z-{789H>+_`)kV(f;UP(7`o7BP)h|{4CihwTi1e0XzK(G&i+=ErFNNVQ-ul#{df zHm==R>RaM%QL(RmP|t2H_qW|qs8^4(Z1kdkUbMHjG_|kQR$5qWOa75d*S%KrL+YN` z3g1kor)K9KR#(8?RB2al&59Svd!8qLt;M-Qp5~qKw4hnN@m5*qI}eIeSs$(rzl|=8 z4;0?r!|qii{paLm`TwhBVMj<$BKfB)l4bGXaYM3P{`F(4Ir)1uUJQ_@_~;1PsY}I< z{VTp#Y_716Q}1@$8-%$JQeUDoozvaP?tr~kNaDLgKk<*K)qgd=e4xE> zOnkQ2?Hy%>g}8U8!k6}6svoWWE;BT~CAi!vRGeOOd2X>-#7olSs!pz&lm5ZlJ9nbB`}9ZeQ4baq-qnU*(y0z3L|)>B@&Uc+-;!{XN|^#hfY*?~W>Z7j#T2 z%uSzBy;tt<@%P2AOS>hToTJ=1se3YGa$jUxoH_CNao)Kho2h&yJ6ze_yWI2beZ}`b zYd@EIFE!nrk~|sg6U~axQGdFRB(2HvPYucKQ86g`XQ)Q&J?9>`!@4{AcW`8QjJ(!A zoW<6%c!&6D?dIRBW7sh30x<`5ai#jm1@SOhqpf5YM_RvAwbi%QoAS2<$yoK^+C^;J zTsxy&$)57okE>ROH+tpd37eDSRA(@^biLU8ue_O=KIf;>gT1#5EVC-BSJ(Dt4hT;z zyd2(`ZmNE+;>gtf_7~3OnJcoh({r5TrMErKmZ>21wD-BaCYX>vwC|MSJN93*J9^vY zk8JJSys=Q@U70$m^kheUXS4r;_r7~x!S1@LZ?*kOdQCf6-%6N`tR)6uYXK>T+`I1RBnzxrSMOyx$>0Skrgj_lf2(#8gd_| z`t9wK!BOlF_+BzRy*9Hbb~>M2`*O=1|F@M>D+m1UmKAH?>1<8T%x>W<%!9^@v(xjEouVDAOnOPh_?n}uYBJkdv;BFR^RueJ+O-_zUK?NF zpF9xvFD_meU+Vtqo@uS{4=cP>+$s9TJxd*b-*-My54t|_{u}LM>^f(s)G_HBQ@1jjZ4+J{o*q3MeWhr#!+PGn%>I+}nR|e`Sw8Px z>n?GhbEkVFogrfM_7KKWcSLc)$A&kFss6BdO8?Bh7ybIw303nm>x=hw+~4_>m2P@@ zBFF3O}Cx7k0Va1uzCg%^{L-r))t4}X|RNS(3S@^i?sIs^wdwnv# z_;5*Y!OVD7Z|8oSp5`23wZ%I}yT?CSuX#tOZ*)h*$Cp+N?2_NB^q=T>_ZjE+>igVT zP_{9AMln~1{i*9XS!Ff$iyZ4c`$6{x_bKlH?;2-fTpyhf-sa@IleNE|PNoE}`swiT z_GossoMrnWe^`Ez%^veL6t z_trhycvj5>Z$^|3{t_LlxNS*cM%Op(z5RFC)fE$*QpZO>ZNG9(_q^)&N1RYUBj3F4 z^cFw4Y|w+vd*yx&S44}m+tgoI`C(-BZ!TP#KBDp8jlZPwea)@?9Yg$sQodf_JCL~k z3jOiw-UJTKewRj2gkDtt@(?hUT1RZWb3D3 zPOwzHLK}i3OV9ZelS93SQoFe$l1=_u!5`vX-PhCCrML2eWT$wPy6>$JJ5gne?~ZDM zz5M;dSbsMKL8!OC3&~#}E!VlbFP(|$&|B`f%5UD1`lENPeRjNM{E?!v)8i+?{lf3V zg8xK*T~Bjg7|hN(b#p5|4zKMV+;gGbJou8a`wTld_ha~OxH0puy47`GW?xNSjb>SI zxRJ9tc(r#z+pDd=?Rz76E<4mcyE|O<&QBXV56NYQoL=`Ee_iVzIuEoTtiQbBkLk;T zDbZOKKQ;O_YvT5<*L#k#y!w3xWwUn{n%ie}&dKj;U6{(GBKL*lvGAATFU6gs8O}D@ z%PTfjURJp_U1QA(o(j_TTY95VL*?7)-^CXX?A&{F@d9hTn@{!+p7Fm4H${Vk1B=s2 zLz45o!!ymPg|;2f3b&8b?w&eddUX1ew`z4 zP3nNS)cSW^uda+W_7Z2Yv&sF$3A9T;w&vLt)|2t#@CN_<;Mi!gIM`={g9?ZDP40iX zG~L-kou+rFI49m&nfO!EgN9_rd_QDv#mM-(Xj5vRs<`^D^m*0^!Q|kL=)CaDLS0w5 zc}d&L{RhQYdZ$HGdQMr}v~i!pBQ?W^d{#BQ6m$&D|B(4!CxLcP9UqQz237r3_fTf< z(wkkoHBYSu6Kk8xoOgJfD*LP&T$^VzCh93xyif@a8(lx4)yEYl;y{k72{4w*7 z)OS`Q{P|KWkd`|l`?wwqIrJHL;Q z3}1+Qt@X|{?>DKZ(x=%>d*ZqFUG9O_y3)T3N$KTiPn~a@9L^}@du9)) zcVpGHjT5U*w`vAv6wl1;-n@L&@q=e(M~geZHanquQstJ;T>pl`y5g_ow?o%1)G zx&G$vq0WTdROg+ZbJp#!@!^56a^c_^^+(xr^E;P5OU1SC)(lRsj-IzCR!pmJs_cy3 z?|QTIuHqxL2U5Cq&uO!NIZi{(5J^U#p8*MI-Sk z%IVHao$I}!j+FZMQVw6UTUek-gTYT$xG3W;knTx@#5%EKV96TIM?s;&n!6ol>=`?9Xgv=pWP~P zOW*k`QxgW=Gwd$Kkeh`-K1@{kr5>E8H7&0=!8yquliIAj_d9MbnH??v6f$UyDm*7o_Ui#ud8df&-)sWHJ}(YVxM)hDKw z7jExZ+wqvcpEoR1VO=_~tb32{{RS3>_u83^pPruzyceA_+_~=6=_f1a)f`_pz3Q;+ zKfOiPtI1n>|IieBy#0PMrPQ2%zi(6jlf}NmUZoZOn7B{%uV2S;@IjPy@62qWlMeUf z)_Q-nZnA&lEc3Q@@3vOO3&OSW_n{v&mtGyP3pW;T2)~HcF(f%JjQrn)!<{43Bhnk~ zsg~{CkXu|iG;^0dGJZF1a%xjsr|X?*(YeI~3Qq*R;VxlC>8HH!KN($^Jm~M;H_&@) z>9Xv5^;_1@&z&7z=~r4Ss}39b&tbPW+>rV-S>oKBnU_7sIXrl}AnzGW3R9()-f?ZI zmUG&&`4^q}nf-0I|J1hLo~@l{8&(W@JGUvG86KMMu3cXHOzK$weE(o~S=H|1b=|?TGrl_nke0a|V9ud#|uI7^*7t`@JjD$7k+Kx6A6io2tuHW+zpoD(|k`JvYi- z7Ou!2k^jiwBe}*tD>|m|b>CHb(~Mu(wsd%~Ptqwl|ByPwIYn$wTk1CzcUAP}w#q!2 zI^MlUoQPP$=tBK>X#9bHVDXB9s|Nn8F6!rp?ZFS>!SOBeV`AE#vfi{8xdW;D^sbGa z(&N)3y(jHf)y=H1kMiF1erG+Xy4!~fOZ+{;U34z(9ltSn(O(tTM~8;1N)Hs~gb#Sf z)@-Q%u3|TPwEWYU%2NkFGc?sOAu~x??M3di^i1!haO;65`xX|~sJHeJg$3=SH(arC zS>IEs18NrKIt#bAwzp4=|Jrcn(9XIutw&4a?Ge?N*N2%qgE@r_@mUr5sw(gI18ZAX zwC_~dPVe(tWw#bb^xfIFqSzMy*A3IhWj@W!&J4~>%buk-$P}E@ylieo)!6EnQagqn z14j(3DE$&u=*-Ur{_^6bI@f(z;ef)QgX`=!(s$>sO`q&uBc`gtotNIf;-boBxw})1 z*2lr;+F@&>P0^hAtMHm|yI_JUSB@U&A2>BU!o4=LI5j$%>n~O1@-gW+vz=Z(euUOw zqFt?59sf42wI_Ltylb6PgG&lc1FCh7E{-pZwh8{Bir+26J>zr2u(YP|Myc9;y>e3H zMKyP%&Incn2c}yZ_ZU8>c~wPka%K2{by4b$)cf%vg{gga=BEqGEGg=Ye9P*Vi9H`A zODp!R9A^EbH}Py5xVGY!rVWjwG8aXEP9|hps$a++oYn(X$ODc&Bc`rIM)VfLL9}H}_QTyv*O-t>Xv$ zdy5N7M+g6io{VowK8P<0z9`(%Z|5J@3GM?jJ7rece+qy0#nX5bGO5fnsb;Ux19ridBy~ zHGLgA)x0?UdBdL@@5{cY_~+rw?`!^D*^)d_Tdk-gRM*`=&EG z8d0px$Hg^4M{=06ck21f((Fyy7t*hI3sfI=y>~)-NNz^%*i3A%438^*Quw7bTYTEA z^;i!Gd_I^J%If^J3~y_ZF*BT;sc5MK+VIPA#;qh&pu!!j0}%hw z%H-hS=fYnKr5le`BK{}ozE8jX@8X7&ONO3WzVsF)01PWo~_@m z`U3Zhc(%Q7W_@mb>TOjjUSfajUGLr*U7ugm*EMjl-yI#1>=s`Yj4%DYxRZZiJl0*G z-cIkcc`>!zYf}~W8L4#ozRaiD$=QMzTDwPo3IczAuzy$^)u>DQ@aPx+@ZuRd=RPG` z=p2_`oF4CeVm%gL5cgY?yrG$YWgbXv>nw=Jg~tV-gkzF*)_<%^qNOiqihjn3D*EjIbP_-k~6{pj$CurWN#w@Nks*YSy||EqYqBAdS3>9IaY zJ(v4O^-)zv=SHXNyv<^hezDGu4k^7`R2_4)M{-;+Cx1fsgFS!Aue07v-<~-?=`L*5 ze|oS_YFM>bnQ^}kcMgBHukyBZw~SW#PX(jw&Gy;WMWxm9fZGN;BvbXqmp0`{Cd)SO zZcX+^rmxQA(nqIvOZ_FaK(#`3&Y7x2{J>l49Ay11{I7qvPDj2K&rr^KMf9KWreKlk zwwjb7SgV~hHg%)Ry}pd6+1EL)JKf$&5*QQbbPlC1ni1a@^{W!>Kj9h5ex9rtp-R=q zmnnyKfnG2@&zb4&0Z5gX=E`DqU29HO?aUq|NihWYnuD6w~H4z+vu#|Ys#9P9!(1ORi^(3`;BCNv?w^b zG&1N8o{rD4Znv6M(fSAL37v4rThG~>Q=8J)rn|lE-JE-)JHg$?yMx8wlmeeP<5ei>rKArSkEN& z@oK$;G7Qg%s^S$=XPq>{GV&QRU9Ak7p)&$*uFP8#;fqe@-5b-`2ZkT9kdb zUFSTSqg!MhPm8_?SA-B~o-@4kF<+Lf^QqsHPE=YFPdoQ-sYWvnQ zRahLYT-KO)Z8A6hPC2q!$={`g--cH7RXo-@*S<+Ldix{~*)LhwyRSH(yCt!?H#qa1 z>y$NqT6nut*S{4%9V=@eg*taw5kC~IRK@3k%0f?4<=!o-uiBuy+>qR=`m)z#9k-SI zit#(~`|*bO=J<|yqjJ`Zl2=vlcYHjM+-$w3in5XRZ0ic;2iC}vexusMTkT6!3H_tNV4bD*871Ii4zhYo0P!U&og6i(lzH&vfg_WKDdO^}6`eL-d}9 zh0$`=iJfBqD>)`<&}yBp%=^XaFMg-8yt@j;ZmIm)GUe5Fwm0f*+>Umu>PB}H*V=3U z$3D?slpG$Pq%7Ns*4QMI?5UGOe^8ceYpu)aNrx)IPO_TyF06|b-#sjg)@gsGGo;hS zhuo7~rAX;8)ip1S;&4v%S~N#B4fV;m`1+_ZUJ>7%+^aWTKVee-_KZQo=cuQj+P9JpEU88@=`o%ibepCB%TjlTQ z8t}6!Z17HNuZ$Y^VT|1{;Tqi_lxh@(SA{NmR0(0 z2UU=qpls*)szv+0Tp6-DsnCjyQ=Qy4@)aX_TVuIn#~kY#WiGE$rP=?fu4$2~?=Dwv zvP(~yjDSN=MaVqm{i} zs;ZMclFjiIs_=Rh&Io4NHi?~h^?G~yONRlC{FMVD4i)|(08ts~#DwZx$ePFjT7q=$9-heh!$l%9h zy(&XH;;f`_hxPB|8LjFG>i9fg-z}8=nVF1Lj{jZN$<9)J*4?UptWw7JcGcT_qAbbh zsy%zeTA*z1*<$t^Rja#Dy#FVvZu_rR>|tw;r1OfZ5_XifovQg?ul(z1>C>6Yw2YM& zT&Iydp8TMCj{Eep(^V}rMYSVoeda7xP0f^U9i+;qv@+q_s@wH|s!@(qUCg1{^>h^a zST(orsk&|tRklr(EML|;;d@n$_!o`-Bx%Dds*d|n~=e53d6Z?Es^)3ZiT->l9A70RuT zR(^aJX~;0uC9G4Hd!(w~wv(0Z)D>@u-SG9~>AHqK7O$(GtWm$;UUF>JZ@Y9KTUVN1 z4nM0RuT?bw)QIk`9ek;3_BLvL+cl=&NXO1mrBovS`?9j}TWhovqz$XIujx(Mse6sq z_2V>p`rOi`hptM)G{P}@`ec1}ZSsij-6N^e2j+dP_-CrwqfJl5&`zGNyHlBHx>#D84PAl;RNb(#ETwjh zjSeP_(t>BDYu&1Bpvwn+12+9{*$AYf&^vG$Kj7+B= zTPs7wUrsZp3yZI@Ptec0BtgBvMfay~&>HFHCjF*D^}=uHxovu%XhC<vOD} z=_g1JXL^4j6S@#rNFH?jrkhiur_w8`R;##L=z-22)zX$~&7f2Bp|c2`vgpS}=g=R@ zpX$)})J6}{-B`D@BsxTrH~pNE0=;xc>8Gs5H_Ed9qUTfn{Hta`kBDl?dAM|dZXV5& z>{!iYleDNyxFUdihdjfYN;9U2Gy!s!S~cdAwTe3f<#UApOsO*f(KRZqc~V|{j# zp4+4yNarDXwAqr%SjmH2`6kW2N|HjmEq$79hjbXE6BK>3=oLuMY zp9!U+8S%F8zc?-EYh86t?u%Rp42GI zH$rRHD5=rot{{2RLuZ7(`&G|crrks5({5P=It8b-b6WH~x-@PhnU2)w=pR9dL(Vq z2htBC;`dSpduH`;-YNTfpvuEAu`&g@c znQmj-s?vChp3b#&728Jhrq0Nh7L3=mU+ekb=^k{Gqu*Yvd(f+gPJDEAp^pze`8s6_ zHfbg4bxcPXI=gf2=CX#Mqh0z-=NdW_)1xaVi4K>vs2QeLVOIN`4pMYE!+P^IJe5zac$3)zgI$DYk00sCsUb9O(5-hq5lsuu2+^ zrDfl^dR|8Jqst^66S3e$>Bl)zPh#fu9Hf&v zJUUh!C3`fAh7&eMHO?=w0?(&duwh@97Gkj)>dXR@AjE2XO>oo_6S z0vpgP9XC%k_3rdiL!;PFLp2Y2z4b~*IPpLSBzju*mFu|aA4z{w4Ok;$q;y6`7c%-8 zT~O(_ONT!C-{Obp#>gjX%d6BXdyVH~>}UmD8mWM%vtz$3K&56})M&UL9q%HI zo4$VZwsti?dZg3g93A3QbSR>GBD<5`-E>aoXRJM=XSdLQ*wN1l(&d%XIr{O?naiv= zo`&9ygC$pbO*ZN)bT_Ae=~G9CZu}cPY(rUpx|h;~2MOD%am(=MoLP~qJ_V+VHG6a-uNejMNga|eUIP2ruIJ#_ z=s$_>&~r1R=Ym`4e2vv&uaD5^(|Qv9De+2l{-RsvfJQ*)?oeaH{?eD6u9EaMrBflYaGl!M$)LR}iwmqYjw}l(%%!o|s))?z+ z=1X78;ra>^iZDH83!oUUN**c|XHx`p3qmrUrZ%39Dzl@7jinni!g#<>C8SHPiKs-g$Iaq$4`o&pt%o=z@(M1rgD!l&+$jiJ?E^gQ~U|Ew9|OR(fA?H_tC(qkMnL;p^^w=R`rStGg`gK5|!;4Q2Tx7~kw(8rjr<@A7L=h3l?Zqme5phmhcv%AnW(+M!t6R@L5+SZdDJps9I)>qt> zj*WCX<+qg@FIEbiz{s)O{G3kr%(F*Qr7Is^FOp>GxyK#`Wz!Lt4z3yf%No*?H>FR~ z5gJ{fBQ9r}=qqh$zLuWKSMnU4ZGIjLtI-);Q4}v2|c2 zPgkLnpx-*}Dr^j12&|39distIwT!J>D`0jDR@>-fP@WsTwy`sb^p@^=d~bRav!Ad; zbmOemJy<^wLZWNX%#_AYM@u|Yg`Ph|Kcgcc+QNJoH7iOlV5}v*Pmve+zC$B28bE*6 zD#?_SSf)oQ{k`c_8%qM6dKMNFYsh##JvFTvVuNzJ2J4JnW2M0&L=H%mKCr9?JxJ*u z?`mxHw`Cph1z1Zon!bSSAI@>n?G#(Z9st2JQ$~z+LO;Dh_?A~|*u5gsF> z-!i>))A}i0YfYEbzVh51?M-?(o0UPg7%5M|%2rCNxEm-8w9I~>_i}$3U4kV-NeVB< zUIy`UK8w?1APJ;H$IGmKTc?>Kc}|=43-4iDu{`uT$LcreNp<=c9pYq}xeK_HuE(9a z3w_SPBFw@s<1P9+CmKDmC02<2%YLEfb<6KT}^48KU@kVq!rUN<_6g$Ma-~otz@XYKqY&tuf_>#HM-<22TY^tPTv&9l55HyYu&(SY=1C`Fbi^u4&+GwX zld!t%Z#vo{S*#8y44uW-dYV^{<_==Ss_`jeFYFBcx$*0!Z$0ZxCs?oy=L+#W^eg7h z*jO+XBL;=g+mbtCwdkeF(^xgo7+Omlfuv3BOqL=LBj`CB6 z>UzcsmIVXA3DJ+ZsVp0iG=8H}&j)jY5o$F?Y%RUULF4o=E|&EG|BcnbM&tcisd~)< zw872=B~(bC(Y)@muJUZgNf$~y1^Q06Yp@{84(B-8-^axXBdl| zlFh~58>!)w@%Y@2KCak0?uG3mqQEzswQ1Ch(V0QzF|g};%g;1e65Gt_Xe8OFF-Q6u z{l)5oSwS%wU16*p^Ug{V%$N~@9{7ZMZj{%Ld*YjrB8*H?za!rCrCIn3b_;eE&yJ@` z=~LJ%dEE#+SPe$vAQcWz4mttM< zim@;~u^_x3NQ2RXgP0S$7yJ;*LLqO1l<+LbANGRvs@0VsKcZHwE^!0a2YJxVHKnIJ z`u`Ap1+D^dV{_ms*mc-AI^wb;(O0ZZuf_oa2Eh`ulr&z$4jEK#EGkh3(K7KBV?$4j zMXS`$@SX;pwd%fbLnans1z9QjTIcmlFgUiMzr43WomjyUnl0mPk|gksXf+H7z3o9n zSp85dz)!h5JBLW9x-2(-i$7-HV^!&uY=x`vOigr)%Ii z@q~_60ZHP^y7ffZEMjWL%39M)w@?4pYJAKE3&Yw~Nrnw&?Ws}JN(=>GRii6l@QA0d zci=Sa7LkR)<*Y6mX_x}y4SYqX=3#6jEE#wYuZ_QE*Ml74eULSt2no^`7re|)fomx0 zsg5*&@nPF?x(EH8Lw%;XERC%8?M7WoE%_DkBV zDw5cspXapqx-<`L9rI?qNRXHb-^Xcs;sK=mSf{8iG2o zp6qjYD#nM$MgL8#+)$P{HUngbUFBa+`+5wK4{6p^d~ld=f3iw&C%~MbN9BnS-;jGa%zctJ|Y1 zz!&5J%#Mep#V#P}N<9Y+HF7k(T&cW1=zgTpF!GYV#+KG=OtCUbu$y$8CqAs!6X~bS z-iGyIwnTNjy`itHyR%knv00J;1+&u@(OYdorB>p1Oc=5QPe7u4u7OYpgPreAR$b9LN4Lb;z0yBk8Bz`uS z083!-ud&@=641tAU5l2(4Umgjt?^C#u(Hva)u(0R)+W$HW!wg#V>9T*4sIdahZjPN z!DR;DCep|8Wgo|U&A)uq*4IQ~M)&$Po4WE9;6@@(>_|x(2g8C^fi1DXjJ!wtIMj1t zw6KRnz@PwwUS0XZu#Amtts=IL{0A%|2oY`o%_kzk@@>{iVxi!y)aqGxAEr-(Zx|DI zB+|~7Jql49xCc*!)%7JSd<9H=vpxq#hp|Av3erk=1lW801=s;}jE%;64QK`Vk2Qgz zV=m}0+6u3N$3xmge8ewUE^IbDGAspn2aRJ-p>r_3#3$@N>_mf}fwmf70?*j4XYi~x zjSl~eA5Ck9opbfdP>K-i$HfE7*ywsj-Ng#1HTXO(s`uD=Q2- zBp+#ZZmlE(gV?BNVPDCglE1}Q!^xp5mR6%A`C~uOEIc(CD{LguIFiAZ5gWJ3CNgq< zhp&R0h;>aUF0)ym1BYPG9LbHZoAkt5{hxL3(e=!QUC21_tR1=w%v_af5jJRcj0W74 zD(j}X29L;mvFlhn;w&;r^}3hA*NhJjzCm|{QOcI*$b1b;!5ZO*SZAynNYP+__6z(Y zY$VSmR#_u0p%MYjjU^3N|Blpi!B%8#&~)MvEF=6qtN~FAcBxmNY|vP-D|kG3L3{vc zGOyo(($RCGUSsKoNgv>Zv0je68QOvm^(8Nm3U}|+cie;jgNQ-k@D@#)vtbPCwZE~e z*aIws*@Xs&__8KdT3Pgsk#E+W(PiX7o)Hd(l{cIQs2;ljZpW^HnXu$=>lOOCOV8jM zxJHmKPlD0YJM?v5q9^1;&dk@>F!}Y$(1Tv^y)YJ;A}b4;c=&`LYy{ebsjZy79Ym_4up zRv*L&@7=GlHp*W#NK3ej;cT$QeR{5?j5)C<(La_DE`-dH(MPZyc#o)uC^fG;p`UOl z@OJ13IRf+mq>POKc^SS1OB|N%5?+gJT(_i$-0)gvZ)2H>;@Anq>BOTZ`wjL$n~1mZ z{gqnbK3xIJYa&8yu%-RLUH}bZ8(9b9JUlvHtD>Aa#@~S%(LaM%zy<8ZqOz}`ODZOK z9<>1MUhEu|8HTOFwo&WB9*5b2eZ}*kF<9SbeaewFhV>@Dz6q`dC}tpxrC zejh!=6L|XU5RI16;q_oED&ht{S!;Uung8U*b#6ce!smu zOAvlaR?1anLrQwbeTej7sfc`;3;PKV!rBKV9+o%q}mcY4Y@U1D+C-GW{8&}cIQrJB8Nj5Y_jqe8IQbIh#ZD(0Fq#N& z%KF1!AOVnrBQ0Z;NC*2!P8g(TPlvx-6ktbR0X;Q;#&PlvzAm!mD#*B~L*4jTuGGj^7Y4)-A^i1oq_z#OU`QrDq{u_VPVXFr2f z*%w4oNB~Vm!{O0cV|*If9&m^whGvjP42O*+hB*flfIzUTruxBTxX6yB^>qAbkF)_# z#HjhMzib7#1F;mgg{ShjsBw~qM>6cT2F=crW{`_**S;jHW8ygwA^sgkHm4_d=q|*5 zSQ{f%WDdUo2V(LWgEe261?*S5=7OnIisl{K5`MTBSceJBKBOJ z?n3;8m4neBMg?z?S28>~XcM*}rybs^yO6g8ub^wx?|?zlS`nh}qAYifMwOQ~f&sAS zuuDi34~Ru0W}(W0dNpho`v&ybs-J)!;Zv~IcoJeTqG>!TD_~GK$SWt*Z;$}Y#|VuP z|5MOCN|F^`k0%p15r;%&$>GV#NuoL6ax#itnhW=VOUJ5^R~e>%jd$l7yft=~{Q*+I z4)*KXp&A2d4?h7CW@Xu_)JcM5@c;NP&VDVr) zT}d2FgA_m~2CFkl)&PA$QpCa_NA``$zhPy_*up7d87hR}nzWuEM%Ip4AM}Q2$M-W5 z&@mnr%)yLf{U6?iJQOIMuLeslU>Nk4h=i}$(fCQKBn>l+M?msqNzklbJqu4w7Myqm zwt-dRYwRMnl^vd!?tw$V#Ap>he?WI2&o)@sg5u$5$VZzjDlt4*f{Yb2HP)QDfN6;J z(MS`uQB?z~CKADO!(Ewr3bJr8pR73^1iM8vhV3zVJdh_=0iRV@)&Q71{&Z?J84dmg zZjt(=-ZFaOCorpcS2%n$q*EGzhsM5vjLCANbwkVRY2pktfcTH>WvDxmYa!|<_QA7} zd!X(YONng+OOtN_%OGX4CT+SWJTdGZ*#hduisffxi(qZR<9rfbLc*XuVlb)$+skXi zZe^!%5B@a~>bmkOpc6!I#Mf9>;_<;+L9Ah&evb6Ozwm*u251SMnrcAS3lC(nYSaiA zz5tdG*^r$eKF2B&`xDJEChR?4k#$)w_Mh#JudFc(?`mSkSU9qcCK z&F}y)TjVV8nynf$zK3c+c507ePHLI3pU94!KYkP}jtAuV_#Ut&@jWa?q&05U_pE0u z%LjVqdgk0)UU|ld9KaOd?2P&^N-V*`Jn14Mjq*u)|rV%E=~QzXk3CR0Uj6yBMrf!%<`g|9`% zX3w)n!Fe#V$O2S}Hv=o-BVa;VP3FTYu;%O$@aI;P+>%fN6~I#12|#U8a*(+63&6WgVi?tHon5uE+dXI>@{{D-8R~c zwT9V8V&oD{d|))1c@aAh(=c1^Gep;suhS`<@+zT?)S$4x@YHxC!*>vE!K;AISVJRG zRvjh@DT7_v4IoIcG+NBAz{8s;1~!bCoHfIafz?1_tPj49$`tl>l*26N(4z(HQHcnQIjz4A%W%P4MXKCoszpRWWa= zuRm2qf1v98?aDtNsb_wz&vN#mUf01tVwv$CaCl_2sKy>DIdrSOmv>=f_c$Z*t*#rY z-&9LtYb1@48cBns%Sxi_@YI$1{TN+=59t#-=;*A8rKq`1tG`}%hPOm7$CPWV@$FxV zXBkyKCAD6Xg%L((X<^r4iXihkqtv2%kJHl(4g>LF;aj!##59}%>d>>+X$-aE6b9=_ zz0xd3xlT`P&>0U`Z_#d-Nz`iWTTAMnX_T8aPF52uZtBMHSlC2Mt8HsE_>ZCbJf}OTT_y%am#GOEq8aff z*3o(bJLdbce5v~WOnS?H8>vr#=!0?`$V_dGd8pQm%*_VLrA~6hHpAP2GVmAZEiqh& z)}>!hwR8roN7_6|Yflas%r`-I8L21zDET)_LRcCyQBC4R)!$U_3Fky2G3^-bs$Vs- zMvb;j>su+=^yqBXM%`t!ot72LH2rZS)&*so?)0Oh%IqxA82-2ttb&Y**z*i zj4$Kl4}Oezrcxs$i^Ma~=z`?K$(wOnFESNQDPgLTrSOWN@tNnyO^HdgnJ zB$aQp2Vj{8OH%BJpCtJ}bL>>_fnBrPd>viXP-Dfx5=__49q|~F|PSXhCDn8a+sx>=KRk0Fe z?3klpwtLu|Dy_k{dSXdWtk)A+$xWL7_xih1yW&vIl+$LLWj#PWLv?a(sTFWKv}uTRXq;pg==+Z~gKZ?eqV8kz z6cswpNwo&pv_qp9r4g)FB{#m1xD~dqS5MwTnm`2s9*@&koD$9*i1Vt0a>D{EVRs$M2XH)Q$L~*ON>uV*G!zDX>>?e`{Cq2fNqdm~g zubS_#vO2Yz3t2V1cDuBwO*%DB(m^xX`D=9dTFJ6Xy4;}?giVqRUU++r7u;_c4cKI| znA_-SYc+?TG;*TKF=cDtUe=gi*<#p0bel}xXkE)Gy9PaPgLIb+1Lr@$XCt+8i9YpX zd1j-esqlO-06*xz3jKDn=KiflN36m*J@z#=2>G(}iO%pZRHU`)PFTdWG-j~$x z?gmzQl%z@4#MV8~j-RzVCu+S*l1_!@+N#-7M>AaW;~aviLo#Qd@Co266PKL9U5bseg+nvEG;mV`X$Y|M(a9ES8>*a{u5*xM`|8L>EvKZ?HfG}zsFfP zn1`>m1Bn65sT(3o^6RY8R?<)Es#>&qoOs+@Pl7Wh?#DvFN)d$++nOkqoFq1-D19f> zpO(I_k(_ecGvFCeHoP9c+fut2-WHE(R)HvRljg&fhC?PFLY&ngt=w3CCM*Cr`A3Zz zIe-+=7P5szm(VLqHBeXiqnc8?_Xi)qJJ$fSgk!4?=}FXV2hRK)cu( z)}AT{d^2pCVPdJ40sRr{fHl#Ejvexq8AFW+ zd>XY3RQQ>AgskuyNt<&jCE0MSv85FRPwV5l3nvobqXzU0>Zc8|HW@OQMkLILsW+e+ zfb0wP0r0ONe(I>Ht;0`ll2ltXTF^FGW6llmJy|!-!(koC?2XsTfQdn}M452yL{n6~ zU<=@B+jJTn&eVkYpigO1&&as)XCLL z=J2W1526JyGH}=A2YrnkY2desWVsG4pzfPdVw>SHh)>{y%;`CNAbcxvy5T6`%Pc(+ zJH>7yt~Wai`vi_9c1El5F6cAWM_9j3J(ZY(GwEOZI~Z=2&0d;%4&b{ zPKDKy2JxOb)4pE6H7rcGu7UX>P6a&}mKvUgeSqD88Hdv%3ZV9kT28VD)K-I54L`=e z1`Q6qve0Ok|UmRPV;^M_l)x4~YL-4FGtVdYiCmY1~a*69gwu<+kROISfzBBD;>LvSwZ z3onL5v5i0IQ^RG`@keCEVD({!$l1bbqpifnyxjq0Y`ATh4ZINCrm644s*vjgHFoLl zX2xXR&6%KKk`#y^{+JpX6OB_N05=V1O5O{0)12inRrBx}tTwqwqyfk8%er8@$zY;4 zAa^LzoJOj}N z`6jXr)bqh3!l7abu>~-#tOjh;czvF_OppRN3*Mbi;6JfJz0F!6J@kyvz*FLxiRk$r4WU94?IfE<6lhp!BSW(-l74LfScn?5z-s1`x6zz z*^~VP@p8Tjjl-vzEFjjDJOy<~)UzNn-W9>~cm|9lEJcUzME;h&M>U4wO~DB~54}dC zksX-80=d% zP*_(gl-Nt`8N4bHAC`$(lJUnPqG{kl&;!ylr}a6Rg6AgJfG)M@T4ETqiCsZW8k+CP zDzTEBYA`jd%$7)i^@E#Z%%*a~)FPpiyeWYvv%(-jQ+-Cp5({n4PV!q;$!I;R1z*eh z@ijIC1Z?Vl86hVHsPZDaLDfRPRv%0R6M>~fQ}Jok0kikf9cIkxGX}JdN=;%{7-BpX z`xuK!wAG{g5l6!qqgT{F5pA+_`pY|j>OZPEU|J3KW=CS-V34qeuwLLcqDS&l%#Yjz z62&(Vu^<=LpF2|@X!85)PTo^v5Esve$z$zJ#WZ>YB0wYXyfD(Ba^g&wOWyfF#urU6 zK6#AhKx{>p&!8-xj8>9;FsDA?iQp=+8@#o^WJU0tFfQx>a1uBMy-W)iQXS44L>N2X z0=tD}GANRq0{F#bQ}A8j0y09>25^oMT!}nDV(d=C0x~PIU_`;4x{iBbgRm!5_f%_j z;2E*L_-pJeXQn`zL>b@~W`bvjlOa#R{sO@hU&C}`9kDd*Wp)Hr9;T`W@6RkuodOvN zvcpMuH^q6!7&}edd6FMytVSXd0`^s&JB@6@g_#50T?Ajgj4< zZ_Krfh|^x(+WAPCl_R#rc7qzosW4VnhIo{DS8G<_2lD17m%#gqz|y9^5O0QVVrlTl z#Alqp98?~IF4Ww}8KLV`W#D;AK_NX=o5{A zb%_Or=vkatMt*SIT%mvTNjwqKN2+)b=7crJx?}OMtE_}s19~q~k5XM;drpW@QNalg z&XK`2l40o3&*0GEL$Euhb`BjUKSLHB&Z1u9BHpMLD^jKVP*sdO07jg1V{yMxKAn~u-kYrGzsg^ z`7b;xnK3G~sn!}9maEXN={_-Kv}Racx5uVXgpCiQ8%*%f5H(kZ^jDZA?Cm; zFjFimn4Z(LCL3vDMw8#eJHmCEhz1XU1!Ske2%*1NWjr@5CYr*t$uy<34?zM%n^c{! zYFHQ06nqBrVm8Pa42@^NSF;yj>#@PuDNgyoVuAvQec74hoh(Ta)WV#|B!S$>!Q)%k z=~L`5o{p~sL$W(TJ|IDMDbbDL(7=6E1(H+Z8Q?WoIw}f4G31wEzp=vj79;>OVUhMO0OkM}YBx4WOD8#D^5|CBE)R9u@lnW(5(GqXc=v$D4P?uw&UV@UcYp zAVjb%IZ~JrYG$zZP5M1p2F}J)B<|=5! z!bt_94)8nriT?t1BA>zh2_O_gO{mSASxg(0yz+~lKsRcFgkcHyd*dh zX<{R=clb5-D0|K5;Qvlxb!xBkJ~Z|SnRNCMzLZ)_P!Pxhjta(uS}O9vXaun*kpb(< zzF_Y*YCP1Tg28#uLB7negFV1ISbF}YO4V2lRuSCDT-h7ExdYj;bI^S5&-jr&Ctf(8 zMl=LIsS{s|Wq~E2o{6&#{1p2F3x$MOX{3RbHfNW>?bu^102#d@Vm>*~Nd$}lWMYT`&7&y3jok|V!A}uY z!ok8eV^LUrBw=h2egaOAm>(7jh5*)ylLH3LW2Zp=^%^Z~Cb)@+11rY-!3yjW6PdA6 zShfGf44^}>9{V5E0+WLz;CawSb{BY`2nNqMLO+4g0QX^Guv6?8wHe?*G#pC%kxLuB?`M(;1O795We7_zX@FQzL@)13`dM$p~%GOa^N|lPjYx z3tLRx3=uk>1y6#$n(=b_6-#fdAG?>mfaJifpg|&NY>vq^pcCv{FbFlDXcs$!+#=`4 zHs}ddloA<`*CA4e%Qa|)7_~w&p<0;wEn*II02~81V4_PZh440DV0;qH0=zrA1!iU+ zf% 0 + prompt = self.text_to_speech.get_custom_prompt(customization_id, prompt_id).get_result() + assert prompt["prompt_id"] == prompt_id + self.text_to_speech.delete_custom_prompt(customization_id, prompt_id) + + def test_speaker_models(self): + speaker_name = "Angelo" + + with open("resources/tts_audio.wav", "rb") as audio_file: + speaker_id = self.text_to_speech.create_speaker_model( + speaker_name, audio_file + ).get_result()["speaker_id"] + speaker_models = self.text_to_speech.list_speaker_models().get_result() + assert len(speaker_models) > 0 + speaker_model = self.text_to_speech.get_speaker_model(speaker_id).get_result() + self.text_to_speech.delete_speaker_model(speaker_id) + def test_synthesize_using_websocket(self): file = 'tongue_twister.wav' diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 2ef2a470d..986c01e6b 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2015, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -30,12 +30,12 @@ from ibm_watson.speech_to_text_v1 import * -service = SpeechToTextV1( +_service = SpeechToTextV1( authenticator=NoAuthAuthenticator() ) -base_url = 'https://api.us-south.speech-to-text.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.speech-to-text.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: Models @@ -62,8 +62,8 @@ def test_list_models_all_params(self): list_models() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/models') - mock_response = '{"models": [{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true}, "description": "description"}]}' + url = self.preprocess_url(_base_url + '/v1/models') + mock_response = '{"models": [{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}]}' responses.add(responses.GET, url, body=mock_response, @@ -71,7 +71,7 @@ def test_list_models_all_params(self): status=200) # Invoke method - response = service.list_models() + response = _service.list_models() # Check for correct operation @@ -99,8 +99,8 @@ def test_get_model_all_params(self): get_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/models/ar-AR_BroadbandModel') - mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true}, "description": "description"}' + url = self.preprocess_url(_base_url + '/v1/models/ar-AR_BroadbandModel') + mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' responses.add(responses.GET, url, body=mock_response, @@ -111,7 +111,7 @@ def test_get_model_all_params(self): model_id = 'ar-AR_BroadbandModel' # Invoke method - response = service.get_model( + response = _service.get_model( model_id, headers={} ) @@ -127,8 +127,8 @@ def test_get_model_value_error(self): test_get_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/models/ar-AR_BroadbandModel') - mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true}, "description": "description"}' + url = self.preprocess_url(_base_url + '/v1/models/ar-AR_BroadbandModel') + mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' responses.add(responses.GET, url, body=mock_response, @@ -145,7 +145,7 @@ def test_get_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_model(**req_copy) + _service.get_model(**req_copy) @@ -179,7 +179,7 @@ def test_recognize_all_params(self): recognize() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/recognize') + url = self.preprocess_url(_base_url + '/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -213,9 +213,10 @@ def test_recognize_all_params(self): split_transcript_at_phrase_end = True speech_detector_sensitivity = 72.5 background_audio_suppression = 72.5 + low_latency = True # Invoke method - response = service.recognize( + response = _service.recognize( audio, content_type=content_type, model=model, @@ -241,6 +242,7 @@ def test_recognize_all_params(self): split_transcript_at_phrase_end=split_transcript_at_phrase_end, speech_detector_sensitivity=speech_detector_sensitivity, background_audio_suppression=background_audio_suppression, + low_latency=low_latency, headers={} ) @@ -273,6 +275,7 @@ def test_recognize_all_params(self): assert 'split_transcript_at_phrase_end={}'.format('true' if split_transcript_at_phrase_end else 'false') in query_string assert 'speech_detector_sensitivity={}'.format(speech_detector_sensitivity) in query_string assert 'background_audio_suppression={}'.format(background_audio_suppression) in query_string + assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string # Validate body params @@ -282,7 +285,7 @@ def test_recognize_required_params(self): test_recognize_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/recognize') + url = self.preprocess_url(_base_url + '/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -294,7 +297,7 @@ def test_recognize_required_params(self): audio = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = service.recognize( + response = _service.recognize( audio, headers={} ) @@ -311,7 +314,7 @@ def test_recognize_value_error(self): test_recognize_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/recognize') + url = self.preprocess_url(_base_url + '/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -329,7 +332,7 @@ def test_recognize_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.recognize(**req_copy) + _service.recognize(**req_copy) @@ -363,7 +366,7 @@ def test_register_callback_all_params(self): register_callback() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/register_callback') + url = self.preprocess_url(_base_url + '/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' responses.add(responses.POST, url, @@ -376,7 +379,7 @@ def test_register_callback_all_params(self): user_secret = 'testString' # Invoke method - response = service.register_callback( + response = _service.register_callback( callback_url, user_secret=user_secret, headers={} @@ -398,7 +401,7 @@ def test_register_callback_required_params(self): test_register_callback_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/register_callback') + url = self.preprocess_url(_base_url + '/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' responses.add(responses.POST, url, @@ -410,7 +413,7 @@ def test_register_callback_required_params(self): callback_url = 'testString' # Invoke method - response = service.register_callback( + response = _service.register_callback( callback_url, headers={} ) @@ -430,7 +433,7 @@ def test_register_callback_value_error(self): test_register_callback_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/register_callback') + url = self.preprocess_url(_base_url + '/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' responses.add(responses.POST, url, @@ -448,7 +451,7 @@ def test_register_callback_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.register_callback(**req_copy) + _service.register_callback(**req_copy) @@ -472,7 +475,7 @@ def test_unregister_callback_all_params(self): unregister_callback() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/unregister_callback') + url = self.preprocess_url(_base_url + '/v1/unregister_callback') responses.add(responses.POST, url, status=200) @@ -481,7 +484,7 @@ def test_unregister_callback_all_params(self): callback_url = 'testString' # Invoke method - response = service.unregister_callback( + response = _service.unregister_callback( callback_url, headers={} ) @@ -501,7 +504,7 @@ def test_unregister_callback_value_error(self): test_unregister_callback_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/unregister_callback') + url = self.preprocess_url(_base_url + '/v1/unregister_callback') responses.add(responses.POST, url, status=200) @@ -516,7 +519,7 @@ def test_unregister_callback_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.unregister_callback(**req_copy) + _service.unregister_callback(**req_copy) @@ -540,7 +543,7 @@ def test_create_job_all_params(self): create_job() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/recognitions') + url = self.preprocess_url(_base_url + '/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -580,9 +583,10 @@ def test_create_job_all_params(self): split_transcript_at_phrase_end = True speech_detector_sensitivity = 72.5 background_audio_suppression = 72.5 + low_latency = True # Invoke method - response = service.create_job( + response = _service.create_job( audio, content_type=content_type, model=model, @@ -614,6 +618,7 @@ def test_create_job_all_params(self): split_transcript_at_phrase_end=split_transcript_at_phrase_end, speech_detector_sensitivity=speech_detector_sensitivity, background_audio_suppression=background_audio_suppression, + low_latency=low_latency, headers={} ) @@ -652,6 +657,7 @@ def test_create_job_all_params(self): assert 'split_transcript_at_phrase_end={}'.format('true' if split_transcript_at_phrase_end else 'false') in query_string assert 'speech_detector_sensitivity={}'.format(speech_detector_sensitivity) in query_string assert 'background_audio_suppression={}'.format(background_audio_suppression) in query_string + assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string # Validate body params @@ -661,7 +667,7 @@ def test_create_job_required_params(self): test_create_job_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/recognitions') + url = self.preprocess_url(_base_url + '/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -673,7 +679,7 @@ def test_create_job_required_params(self): audio = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = service.create_job( + response = _service.create_job( audio, headers={} ) @@ -690,7 +696,7 @@ def test_create_job_value_error(self): test_create_job_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/recognitions') + url = self.preprocess_url(_base_url + '/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -708,7 +714,7 @@ def test_create_job_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_job(**req_copy) + _service.create_job(**req_copy) @@ -732,7 +738,7 @@ def test_check_jobs_all_params(self): check_jobs() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/recognitions') + url = self.preprocess_url(_base_url + '/v1/recognitions') mock_response = '{"recognitions": [{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}]}' responses.add(responses.GET, url, @@ -741,7 +747,7 @@ def test_check_jobs_all_params(self): status=200) # Invoke method - response = service.check_jobs() + response = _service.check_jobs() # Check for correct operation @@ -769,7 +775,7 @@ def test_check_job_all_params(self): check_job() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/recognitions/testString') + url = self.preprocess_url(_base_url + '/v1/recognitions/testString') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' responses.add(responses.GET, url, @@ -781,7 +787,7 @@ def test_check_job_all_params(self): id = 'testString' # Invoke method - response = service.check_job( + response = _service.check_job( id, headers={} ) @@ -797,7 +803,7 @@ def test_check_job_value_error(self): test_check_job_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/recognitions/testString') + url = self.preprocess_url(_base_url + '/v1/recognitions/testString') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' responses.add(responses.GET, url, @@ -815,7 +821,7 @@ def test_check_job_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.check_job(**req_copy) + _service.check_job(**req_copy) @@ -839,7 +845,7 @@ def test_delete_job_all_params(self): delete_job() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/recognitions/testString') + url = self.preprocess_url(_base_url + '/v1/recognitions/testString') responses.add(responses.DELETE, url, status=204) @@ -848,7 +854,7 @@ def test_delete_job_all_params(self): id = 'testString' # Invoke method - response = service.delete_job( + response = _service.delete_job( id, headers={} ) @@ -864,7 +870,7 @@ def test_delete_job_value_error(self): test_delete_job_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/recognitions/testString') + url = self.preprocess_url(_base_url + '/v1/recognitions/testString') responses.add(responses.DELETE, url, status=204) @@ -879,7 +885,7 @@ def test_delete_job_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_job(**req_copy) + _service.delete_job(**req_copy) @@ -913,7 +919,7 @@ def test_create_language_model_all_params(self): create_language_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations') + url = self.preprocess_url(_base_url + '/v1/customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' responses.add(responses.POST, url, @@ -928,7 +934,7 @@ def test_create_language_model_all_params(self): description = 'testString' # Invoke method - response = service.create_language_model( + response = _service.create_language_model( name, base_model_name, dialect=dialect, @@ -953,7 +959,7 @@ def test_create_language_model_value_error(self): test_create_language_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations') + url = self.preprocess_url(_base_url + '/v1/customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' responses.add(responses.POST, url, @@ -975,7 +981,7 @@ def test_create_language_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_language_model(**req_copy) + _service.create_language_model(**req_copy) @@ -999,7 +1005,7 @@ def test_list_language_models_all_params(self): list_language_models() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations') + url = self.preprocess_url(_base_url + '/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}]}' responses.add(responses.GET, url, @@ -1011,7 +1017,7 @@ def test_list_language_models_all_params(self): language = 'ar-AR' # Invoke method - response = service.list_language_models( + response = _service.list_language_models( language=language, headers={} ) @@ -1031,7 +1037,7 @@ def test_list_language_models_required_params(self): test_list_language_models_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations') + url = self.preprocess_url(_base_url + '/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}]}' responses.add(responses.GET, url, @@ -1040,7 +1046,7 @@ def test_list_language_models_required_params(self): status=200) # Invoke method - response = service.list_language_models() + response = _service.list_language_models() # Check for correct operation @@ -1068,7 +1074,7 @@ def test_get_language_model_all_params(self): get_language_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' responses.add(responses.GET, url, @@ -1080,7 +1086,7 @@ def test_get_language_model_all_params(self): customization_id = 'testString' # Invoke method - response = service.get_language_model( + response = _service.get_language_model( customization_id, headers={} ) @@ -1096,7 +1102,7 @@ def test_get_language_model_value_error(self): test_get_language_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' responses.add(responses.GET, url, @@ -1114,7 +1120,7 @@ def test_get_language_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_language_model(**req_copy) + _service.get_language_model(**req_copy) @@ -1138,7 +1144,7 @@ def test_delete_language_model_all_params(self): delete_language_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString') responses.add(responses.DELETE, url, status=200) @@ -1147,7 +1153,7 @@ def test_delete_language_model_all_params(self): customization_id = 'testString' # Invoke method - response = service.delete_language_model( + response = _service.delete_language_model( customization_id, headers={} ) @@ -1163,7 +1169,7 @@ def test_delete_language_model_value_error(self): test_delete_language_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString') responses.add(responses.DELETE, url, status=200) @@ -1178,7 +1184,7 @@ def test_delete_language_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_language_model(**req_copy) + _service.delete_language_model(**req_copy) @@ -1202,7 +1208,7 @@ def test_train_language_model_all_params(self): train_language_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/train') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -1216,7 +1222,7 @@ def test_train_language_model_all_params(self): customization_weight = 72.5 # Invoke method - response = service.train_language_model( + response = _service.train_language_model( customization_id, word_type_to_add=word_type_to_add, customization_weight=customization_weight, @@ -1239,7 +1245,7 @@ def test_train_language_model_required_params(self): test_train_language_model_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/train') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -1251,7 +1257,7 @@ def test_train_language_model_required_params(self): customization_id = 'testString' # Invoke method - response = service.train_language_model( + response = _service.train_language_model( customization_id, headers={} ) @@ -1267,7 +1273,7 @@ def test_train_language_model_value_error(self): test_train_language_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/train') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -1285,7 +1291,7 @@ def test_train_language_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.train_language_model(**req_copy) + _service.train_language_model(**req_copy) @@ -1309,7 +1315,7 @@ def test_reset_language_model_all_params(self): reset_language_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/reset') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/reset') responses.add(responses.POST, url, status=200) @@ -1318,7 +1324,7 @@ def test_reset_language_model_all_params(self): customization_id = 'testString' # Invoke method - response = service.reset_language_model( + response = _service.reset_language_model( customization_id, headers={} ) @@ -1334,7 +1340,7 @@ def test_reset_language_model_value_error(self): test_reset_language_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/reset') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/reset') responses.add(responses.POST, url, status=200) @@ -1349,7 +1355,7 @@ def test_reset_language_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.reset_language_model(**req_copy) + _service.reset_language_model(**req_copy) @@ -1373,7 +1379,7 @@ def test_upgrade_language_model_all_params(self): upgrade_language_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/upgrade_model') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/upgrade_model') responses.add(responses.POST, url, status=200) @@ -1382,7 +1388,7 @@ def test_upgrade_language_model_all_params(self): customization_id = 'testString' # Invoke method - response = service.upgrade_language_model( + response = _service.upgrade_language_model( customization_id, headers={} ) @@ -1398,7 +1404,7 @@ def test_upgrade_language_model_value_error(self): test_upgrade_language_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/upgrade_model') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/upgrade_model') responses.add(responses.POST, url, status=200) @@ -1413,7 +1419,7 @@ def test_upgrade_language_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.upgrade_language_model(**req_copy) + _service.upgrade_language_model(**req_copy) @@ -1447,7 +1453,7 @@ def test_list_corpora_all_params(self): list_corpora() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora') mock_response = '{"corpora": [{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' responses.add(responses.GET, url, @@ -1459,7 +1465,7 @@ def test_list_corpora_all_params(self): customization_id = 'testString' # Invoke method - response = service.list_corpora( + response = _service.list_corpora( customization_id, headers={} ) @@ -1475,7 +1481,7 @@ def test_list_corpora_value_error(self): test_list_corpora_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora') mock_response = '{"corpora": [{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' responses.add(responses.GET, url, @@ -1493,7 +1499,7 @@ def test_list_corpora_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_corpora(**req_copy) + _service.list_corpora(**req_copy) @@ -1517,7 +1523,7 @@ def test_add_corpus_all_params(self): add_corpus() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') responses.add(responses.POST, url, status=201) @@ -1529,7 +1535,7 @@ def test_add_corpus_all_params(self): allow_overwrite = True # Invoke method - response = service.add_corpus( + response = _service.add_corpus( customization_id, corpus_name, corpus_file, @@ -1552,7 +1558,7 @@ def test_add_corpus_required_params(self): test_add_corpus_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') responses.add(responses.POST, url, status=201) @@ -1563,7 +1569,7 @@ def test_add_corpus_required_params(self): corpus_file = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = service.add_corpus( + response = _service.add_corpus( customization_id, corpus_name, corpus_file, @@ -1581,7 +1587,7 @@ def test_add_corpus_value_error(self): test_add_corpus_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') responses.add(responses.POST, url, status=201) @@ -1600,7 +1606,7 @@ def test_add_corpus_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_corpus(**req_copy) + _service.add_corpus(**req_copy) @@ -1624,7 +1630,7 @@ def test_get_corpus_all_params(self): get_corpus() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') mock_response = '{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' responses.add(responses.GET, url, @@ -1637,7 +1643,7 @@ def test_get_corpus_all_params(self): corpus_name = 'testString' # Invoke method - response = service.get_corpus( + response = _service.get_corpus( customization_id, corpus_name, headers={} @@ -1654,7 +1660,7 @@ def test_get_corpus_value_error(self): test_get_corpus_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') mock_response = '{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' responses.add(responses.GET, url, @@ -1674,7 +1680,7 @@ def test_get_corpus_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_corpus(**req_copy) + _service.get_corpus(**req_copy) @@ -1698,7 +1704,7 @@ def test_delete_corpus_all_params(self): delete_corpus() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') responses.add(responses.DELETE, url, status=200) @@ -1708,7 +1714,7 @@ def test_delete_corpus_all_params(self): corpus_name = 'testString' # Invoke method - response = service.delete_corpus( + response = _service.delete_corpus( customization_id, corpus_name, headers={} @@ -1725,7 +1731,7 @@ def test_delete_corpus_value_error(self): test_delete_corpus_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/corpora/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') responses.add(responses.DELETE, url, status=200) @@ -1742,7 +1748,7 @@ def test_delete_corpus_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_corpus(**req_copy) + _service.delete_corpus(**req_copy) @@ -1776,7 +1782,7 @@ def test_list_words_all_params(self): list_words() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' responses.add(responses.GET, url, @@ -1790,7 +1796,7 @@ def test_list_words_all_params(self): sort = 'alphabetical' # Invoke method - response = service.list_words( + response = _service.list_words( customization_id, word_type=word_type, sort=sort, @@ -1813,7 +1819,7 @@ def test_list_words_required_params(self): test_list_words_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' responses.add(responses.GET, url, @@ -1825,7 +1831,7 @@ def test_list_words_required_params(self): customization_id = 'testString' # Invoke method - response = service.list_words( + response = _service.list_words( customization_id, headers={} ) @@ -1841,7 +1847,7 @@ def test_list_words_value_error(self): test_list_words_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' responses.add(responses.GET, url, @@ -1859,7 +1865,7 @@ def test_list_words_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_words(**req_copy) + _service.list_words(**req_copy) @@ -1883,7 +1889,7 @@ def test_add_words_all_params(self): add_words() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') responses.add(responses.POST, url, status=201) @@ -1899,7 +1905,7 @@ def test_add_words_all_params(self): words = [custom_word_model] # Invoke method - response = service.add_words( + response = _service.add_words( customization_id, words, headers={} @@ -1919,7 +1925,7 @@ def test_add_words_value_error(self): test_add_words_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') responses.add(responses.POST, url, status=201) @@ -1942,7 +1948,7 @@ def test_add_words_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_words(**req_copy) + _service.add_words(**req_copy) @@ -1966,7 +1972,7 @@ def test_add_word_all_params(self): add_word() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') responses.add(responses.PUT, url, status=201) @@ -1979,7 +1985,7 @@ def test_add_word_all_params(self): display_as = 'testString' # Invoke method - response = service.add_word( + response = _service.add_word( customization_id, word_name, word=word, @@ -2004,7 +2010,7 @@ def test_add_word_value_error(self): test_add_word_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') responses.add(responses.PUT, url, status=201) @@ -2024,7 +2030,7 @@ def test_add_word_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_word(**req_copy) + _service.add_word(**req_copy) @@ -2048,7 +2054,7 @@ def test_get_word_all_params(self): get_word() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' responses.add(responses.GET, url, @@ -2061,7 +2067,7 @@ def test_get_word_all_params(self): word_name = 'testString' # Invoke method - response = service.get_word( + response = _service.get_word( customization_id, word_name, headers={} @@ -2078,7 +2084,7 @@ def test_get_word_value_error(self): test_get_word_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' responses.add(responses.GET, url, @@ -2098,7 +2104,7 @@ def test_get_word_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_word(**req_copy) + _service.get_word(**req_copy) @@ -2122,7 +2128,7 @@ def test_delete_word_all_params(self): delete_word() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') responses.add(responses.DELETE, url, status=200) @@ -2132,7 +2138,7 @@ def test_delete_word_all_params(self): word_name = 'testString' # Invoke method - response = service.delete_word( + response = _service.delete_word( customization_id, word_name, headers={} @@ -2149,7 +2155,7 @@ def test_delete_word_value_error(self): test_delete_word_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') responses.add(responses.DELETE, url, status=200) @@ -2166,7 +2172,7 @@ def test_delete_word_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_word(**req_copy) + _service.delete_word(**req_copy) @@ -2200,7 +2206,7 @@ def test_list_grammars_all_params(self): list_grammars() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars') mock_response = '{"grammars": [{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' responses.add(responses.GET, url, @@ -2212,7 +2218,7 @@ def test_list_grammars_all_params(self): customization_id = 'testString' # Invoke method - response = service.list_grammars( + response = _service.list_grammars( customization_id, headers={} ) @@ -2228,7 +2234,7 @@ def test_list_grammars_value_error(self): test_list_grammars_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars') mock_response = '{"grammars": [{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' responses.add(responses.GET, url, @@ -2246,7 +2252,7 @@ def test_list_grammars_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_grammars(**req_copy) + _service.list_grammars(**req_copy) @@ -2270,7 +2276,7 @@ def test_add_grammar_all_params(self): add_grammar() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') responses.add(responses.POST, url, status=201) @@ -2283,7 +2289,7 @@ def test_add_grammar_all_params(self): allow_overwrite = True # Invoke method - response = service.add_grammar( + response = _service.add_grammar( customization_id, grammar_name, grammar_file, @@ -2308,7 +2314,7 @@ def test_add_grammar_required_params(self): test_add_grammar_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') responses.add(responses.POST, url, status=201) @@ -2320,7 +2326,7 @@ def test_add_grammar_required_params(self): content_type = 'application/srgs' # Invoke method - response = service.add_grammar( + response = _service.add_grammar( customization_id, grammar_name, grammar_file, @@ -2340,7 +2346,7 @@ def test_add_grammar_value_error(self): test_add_grammar_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') responses.add(responses.POST, url, status=201) @@ -2361,7 +2367,7 @@ def test_add_grammar_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_grammar(**req_copy) + _service.add_grammar(**req_copy) @@ -2385,7 +2391,7 @@ def test_get_grammar_all_params(self): get_grammar() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') mock_response = '{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' responses.add(responses.GET, url, @@ -2398,7 +2404,7 @@ def test_get_grammar_all_params(self): grammar_name = 'testString' # Invoke method - response = service.get_grammar( + response = _service.get_grammar( customization_id, grammar_name, headers={} @@ -2415,7 +2421,7 @@ def test_get_grammar_value_error(self): test_get_grammar_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') mock_response = '{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' responses.add(responses.GET, url, @@ -2435,7 +2441,7 @@ def test_get_grammar_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_grammar(**req_copy) + _service.get_grammar(**req_copy) @@ -2459,7 +2465,7 @@ def test_delete_grammar_all_params(self): delete_grammar() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') responses.add(responses.DELETE, url, status=200) @@ -2469,7 +2475,7 @@ def test_delete_grammar_all_params(self): grammar_name = 'testString' # Invoke method - response = service.delete_grammar( + response = _service.delete_grammar( customization_id, grammar_name, headers={} @@ -2486,7 +2492,7 @@ def test_delete_grammar_value_error(self): test_delete_grammar_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/grammars/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') responses.add(responses.DELETE, url, status=200) @@ -2503,7 +2509,7 @@ def test_delete_grammar_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_grammar(**req_copy) + _service.delete_grammar(**req_copy) @@ -2537,7 +2543,7 @@ def test_create_acoustic_model_all_params(self): create_acoustic_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' responses.add(responses.POST, url, @@ -2551,7 +2557,7 @@ def test_create_acoustic_model_all_params(self): description = 'testString' # Invoke method - response = service.create_acoustic_model( + response = _service.create_acoustic_model( name, base_model_name, description=description, @@ -2574,7 +2580,7 @@ def test_create_acoustic_model_value_error(self): test_create_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' responses.add(responses.POST, url, @@ -2595,7 +2601,7 @@ def test_create_acoustic_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_acoustic_model(**req_copy) + _service.create_acoustic_model(**req_copy) @@ -2619,7 +2625,7 @@ def test_list_acoustic_models_all_params(self): list_acoustic_models() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}]}' responses.add(responses.GET, url, @@ -2631,7 +2637,7 @@ def test_list_acoustic_models_all_params(self): language = 'ar-AR' # Invoke method - response = service.list_acoustic_models( + response = _service.list_acoustic_models( language=language, headers={} ) @@ -2651,7 +2657,7 @@ def test_list_acoustic_models_required_params(self): test_list_acoustic_models_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}]}' responses.add(responses.GET, url, @@ -2660,7 +2666,7 @@ def test_list_acoustic_models_required_params(self): status=200) # Invoke method - response = service.list_acoustic_models() + response = _service.list_acoustic_models() # Check for correct operation @@ -2688,7 +2694,7 @@ def test_get_acoustic_model_all_params(self): get_acoustic_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' responses.add(responses.GET, url, @@ -2700,7 +2706,7 @@ def test_get_acoustic_model_all_params(self): customization_id = 'testString' # Invoke method - response = service.get_acoustic_model( + response = _service.get_acoustic_model( customization_id, headers={} ) @@ -2716,7 +2722,7 @@ def test_get_acoustic_model_value_error(self): test_get_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' responses.add(responses.GET, url, @@ -2734,7 +2740,7 @@ def test_get_acoustic_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_acoustic_model(**req_copy) + _service.get_acoustic_model(**req_copy) @@ -2758,7 +2764,7 @@ def test_delete_acoustic_model_all_params(self): delete_acoustic_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString') responses.add(responses.DELETE, url, status=200) @@ -2767,7 +2773,7 @@ def test_delete_acoustic_model_all_params(self): customization_id = 'testString' # Invoke method - response = service.delete_acoustic_model( + response = _service.delete_acoustic_model( customization_id, headers={} ) @@ -2783,7 +2789,7 @@ def test_delete_acoustic_model_value_error(self): test_delete_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString') responses.add(responses.DELETE, url, status=200) @@ -2798,7 +2804,7 @@ def test_delete_acoustic_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_acoustic_model(**req_copy) + _service.delete_acoustic_model(**req_copy) @@ -2822,7 +2828,7 @@ def test_train_acoustic_model_all_params(self): train_acoustic_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/train') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -2835,7 +2841,7 @@ def test_train_acoustic_model_all_params(self): custom_language_model_id = 'testString' # Invoke method - response = service.train_acoustic_model( + response = _service.train_acoustic_model( customization_id, custom_language_model_id=custom_language_model_id, headers={} @@ -2856,7 +2862,7 @@ def test_train_acoustic_model_required_params(self): test_train_acoustic_model_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/train') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -2868,7 +2874,7 @@ def test_train_acoustic_model_required_params(self): customization_id = 'testString' # Invoke method - response = service.train_acoustic_model( + response = _service.train_acoustic_model( customization_id, headers={} ) @@ -2884,7 +2890,7 @@ def test_train_acoustic_model_value_error(self): test_train_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/train') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -2902,7 +2908,7 @@ def test_train_acoustic_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.train_acoustic_model(**req_copy) + _service.train_acoustic_model(**req_copy) @@ -2926,7 +2932,7 @@ def test_reset_acoustic_model_all_params(self): reset_acoustic_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/reset') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/reset') responses.add(responses.POST, url, status=200) @@ -2935,7 +2941,7 @@ def test_reset_acoustic_model_all_params(self): customization_id = 'testString' # Invoke method - response = service.reset_acoustic_model( + response = _service.reset_acoustic_model( customization_id, headers={} ) @@ -2951,7 +2957,7 @@ def test_reset_acoustic_model_value_error(self): test_reset_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/reset') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/reset') responses.add(responses.POST, url, status=200) @@ -2966,7 +2972,7 @@ def test_reset_acoustic_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.reset_acoustic_model(**req_copy) + _service.reset_acoustic_model(**req_copy) @@ -2990,7 +2996,7 @@ def test_upgrade_acoustic_model_all_params(self): upgrade_acoustic_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/upgrade_model') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/upgrade_model') responses.add(responses.POST, url, status=200) @@ -3001,7 +3007,7 @@ def test_upgrade_acoustic_model_all_params(self): force = True # Invoke method - response = service.upgrade_acoustic_model( + response = _service.upgrade_acoustic_model( customization_id, custom_language_model_id=custom_language_model_id, force=force, @@ -3024,7 +3030,7 @@ def test_upgrade_acoustic_model_required_params(self): test_upgrade_acoustic_model_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/upgrade_model') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/upgrade_model') responses.add(responses.POST, url, status=200) @@ -3033,7 +3039,7 @@ def test_upgrade_acoustic_model_required_params(self): customization_id = 'testString' # Invoke method - response = service.upgrade_acoustic_model( + response = _service.upgrade_acoustic_model( customization_id, headers={} ) @@ -3049,7 +3055,7 @@ def test_upgrade_acoustic_model_value_error(self): test_upgrade_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/upgrade_model') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/upgrade_model') responses.add(responses.POST, url, status=200) @@ -3064,7 +3070,7 @@ def test_upgrade_acoustic_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.upgrade_acoustic_model(**req_copy) + _service.upgrade_acoustic_model(**req_copy) @@ -3098,7 +3104,7 @@ def test_list_audio_all_params(self): list_audio() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio') mock_response = '{"total_minutes_of_audio": 22, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' responses.add(responses.GET, url, @@ -3110,7 +3116,7 @@ def test_list_audio_all_params(self): customization_id = 'testString' # Invoke method - response = service.list_audio( + response = _service.list_audio( customization_id, headers={} ) @@ -3126,7 +3132,7 @@ def test_list_audio_value_error(self): test_list_audio_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio') mock_response = '{"total_minutes_of_audio": 22, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' responses.add(responses.GET, url, @@ -3144,7 +3150,7 @@ def test_list_audio_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_audio(**req_copy) + _service.list_audio(**req_copy) @@ -3168,7 +3174,7 @@ def test_add_audio_all_params(self): add_audio() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') responses.add(responses.POST, url, status=201) @@ -3182,7 +3188,7 @@ def test_add_audio_all_params(self): allow_overwrite = True # Invoke method - response = service.add_audio( + response = _service.add_audio( customization_id, audio_name, audio_resource, @@ -3208,7 +3214,7 @@ def test_add_audio_required_params(self): test_add_audio_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') responses.add(responses.POST, url, status=201) @@ -3219,7 +3225,7 @@ def test_add_audio_required_params(self): audio_resource = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = service.add_audio( + response = _service.add_audio( customization_id, audio_name, audio_resource, @@ -3238,7 +3244,7 @@ def test_add_audio_value_error(self): test_add_audio_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') responses.add(responses.POST, url, status=201) @@ -3257,7 +3263,7 @@ def test_add_audio_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_audio(**req_copy) + _service.add_audio(**req_copy) @@ -3281,7 +3287,7 @@ def test_get_audio_all_params(self): get_audio() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') mock_response = '{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok", "container": {"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' responses.add(responses.GET, url, @@ -3294,7 +3300,7 @@ def test_get_audio_all_params(self): audio_name = 'testString' # Invoke method - response = service.get_audio( + response = _service.get_audio( customization_id, audio_name, headers={} @@ -3311,7 +3317,7 @@ def test_get_audio_value_error(self): test_get_audio_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') mock_response = '{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok", "container": {"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' responses.add(responses.GET, url, @@ -3331,7 +3337,7 @@ def test_get_audio_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_audio(**req_copy) + _service.get_audio(**req_copy) @@ -3355,7 +3361,7 @@ def test_delete_audio_all_params(self): delete_audio() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') responses.add(responses.DELETE, url, status=200) @@ -3365,7 +3371,7 @@ def test_delete_audio_all_params(self): audio_name = 'testString' # Invoke method - response = service.delete_audio( + response = _service.delete_audio( customization_id, audio_name, headers={} @@ -3382,7 +3388,7 @@ def test_delete_audio_value_error(self): test_delete_audio_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') responses.add(responses.DELETE, url, status=200) @@ -3399,7 +3405,7 @@ def test_delete_audio_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_audio(**req_copy) + _service.delete_audio(**req_copy) @@ -3433,7 +3439,7 @@ def test_delete_user_data_all_params(self): delete_user_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/user_data') + url = self.preprocess_url(_base_url + '/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -3442,7 +3448,7 @@ def test_delete_user_data_all_params(self): customer_id = 'testString' # Invoke method - response = service.delete_user_data( + response = _service.delete_user_data( customer_id, headers={} ) @@ -3462,7 +3468,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/user_data') + url = self.preprocess_url(_base_url + '/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -3477,7 +3483,7 @@ def test_delete_user_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_user_data(**req_copy) + _service.delete_user_data(**req_copy) @@ -4531,6 +4537,7 @@ def test_speech_model_serialization(self): supported_features_model = {} # SupportedFeatures supported_features_model['custom_language_model'] = True supported_features_model['speaker_labels'] = True + supported_features_model['low_latency'] = True # Construct a json representation of a SpeechModel model speech_model_model_json = {} @@ -4571,6 +4578,7 @@ def test_speech_models_serialization(self): supported_features_model = {} # SupportedFeatures supported_features_model['custom_language_model'] = True supported_features_model['speaker_labels'] = True + supported_features_model['low_latency'] = True speech_model_model = {} # SpeechModel speech_model_model['name'] = 'testString' @@ -4803,6 +4811,7 @@ def test_supported_features_serialization(self): supported_features_model_json = {} supported_features_model_json['custom_language_model'] = True supported_features_model_json['speaker_labels'] = True + supported_features_model_json['low_latency'] = True # Construct a model instance of SupportedFeatures by calling from_dict on the json representation supported_features_model = SupportedFeatures.from_dict(supported_features_model_json) diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index ddb5a74d0..4af54f88f 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,21 +19,23 @@ from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator import inspect +import io import json import pytest import re import requests import responses +import tempfile import urllib from ibm_watson.text_to_speech_v1 import * -service = TextToSpeechV1( +_service = TextToSpeechV1( authenticator=NoAuthAuthenticator() ) -base_url = 'https://api.us-south.text-to-speech.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.text-to-speech.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: Voices @@ -60,8 +62,8 @@ def test_list_voices_all_params(self): list_voices() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/voices') - mock_response = '{"voices": [{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}}]}' + url = self.preprocess_url(_base_url + '/v1/voices') + mock_response = '{"voices": [{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}]}' responses.add(responses.GET, url, body=mock_response, @@ -69,7 +71,7 @@ def test_list_voices_all_params(self): status=200) # Invoke method - response = service.list_voices() + response = _service.list_voices() # Check for correct operation @@ -97,8 +99,8 @@ def test_get_voice_all_params(self): get_voice() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/voices/ar-AR_OmarVoice') - mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}}' + url = self.preprocess_url(_base_url + '/v1/voices/ar-AR_OmarVoice') + mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, body=mock_response, @@ -110,7 +112,7 @@ def test_get_voice_all_params(self): customization_id = 'testString' # Invoke method - response = service.get_voice( + response = _service.get_voice( voice, customization_id=customization_id, headers={} @@ -131,8 +133,8 @@ def test_get_voice_required_params(self): test_get_voice_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/voices/ar-AR_OmarVoice') - mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}}' + url = self.preprocess_url(_base_url + '/v1/voices/ar-AR_OmarVoice') + mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, body=mock_response, @@ -143,7 +145,7 @@ def test_get_voice_required_params(self): voice = 'ar-AR_OmarVoice' # Invoke method - response = service.get_voice( + response = _service.get_voice( voice, headers={} ) @@ -159,8 +161,8 @@ def test_get_voice_value_error(self): test_get_voice_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/voices/ar-AR_OmarVoice') - mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}}' + url = self.preprocess_url(_base_url + '/v1/voices/ar-AR_OmarVoice') + mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, body=mock_response, @@ -177,7 +179,7 @@ def test_get_voice_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_voice(**req_copy) + _service.get_voice(**req_copy) @@ -211,7 +213,7 @@ def test_synthesize_all_params(self): synthesize() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/synthesize') + url = self.preprocess_url(_base_url + '/v1/synthesize') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, @@ -226,7 +228,7 @@ def test_synthesize_all_params(self): customization_id = 'testString' # Invoke method - response = service.synthesize( + response = _service.synthesize( text, accept=accept, voice=voice, @@ -253,7 +255,7 @@ def test_synthesize_required_params(self): test_synthesize_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/synthesize') + url = self.preprocess_url(_base_url + '/v1/synthesize') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, @@ -265,7 +267,7 @@ def test_synthesize_required_params(self): text = 'testString' # Invoke method - response = service.synthesize( + response = _service.synthesize( text, headers={} ) @@ -284,7 +286,7 @@ def test_synthesize_value_error(self): test_synthesize_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/synthesize') + url = self.preprocess_url(_base_url + '/v1/synthesize') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, @@ -302,7 +304,7 @@ def test_synthesize_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.synthesize(**req_copy) + _service.synthesize(**req_copy) @@ -336,7 +338,7 @@ def test_get_pronunciation_all_params(self): get_pronunciation() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/pronunciation') + url = self.preprocess_url(_base_url + '/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' responses.add(responses.GET, url, @@ -351,7 +353,7 @@ def test_get_pronunciation_all_params(self): customization_id = 'testString' # Invoke method - response = service.get_pronunciation( + response = _service.get_pronunciation( text, voice=voice, format=format, @@ -377,7 +379,7 @@ def test_get_pronunciation_required_params(self): test_get_pronunciation_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/pronunciation') + url = self.preprocess_url(_base_url + '/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' responses.add(responses.GET, url, @@ -389,7 +391,7 @@ def test_get_pronunciation_required_params(self): text = 'testString' # Invoke method - response = service.get_pronunciation( + response = _service.get_pronunciation( text, headers={} ) @@ -409,7 +411,7 @@ def test_get_pronunciation_value_error(self): test_get_pronunciation_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/pronunciation') + url = self.preprocess_url(_base_url + '/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' responses.add(responses.GET, url, @@ -427,7 +429,7 @@ def test_get_pronunciation_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_pronunciation(**req_copy) + _service.get_pronunciation(**req_copy) @@ -461,8 +463,8 @@ def test_create_custom_model_all_params(self): create_custom_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations') - mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' + url = self.preprocess_url(_base_url + '/v1/customizations') + mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' responses.add(responses.POST, url, body=mock_response, @@ -471,11 +473,11 @@ def test_create_custom_model_all_params(self): # Set up parameter values name = 'testString' - language = 'de-DE' + language = 'ar-MS' description = 'testString' # Invoke method - response = service.create_custom_model( + response = _service.create_custom_model( name, language=language, description=description, @@ -488,7 +490,7 @@ def test_create_custom_model_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' - assert req_body['language'] == 'de-DE' + assert req_body['language'] == 'ar-MS' assert req_body['description'] == 'testString' @@ -498,8 +500,8 @@ def test_create_custom_model_value_error(self): test_create_custom_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations') - mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' + url = self.preprocess_url(_base_url + '/v1/customizations') + mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' responses.add(responses.POST, url, body=mock_response, @@ -508,7 +510,7 @@ def test_create_custom_model_value_error(self): # Set up parameter values name = 'testString' - language = 'de-DE' + language = 'ar-MS' description = 'testString' # Pass in all but one required param and check for a ValueError @@ -518,7 +520,7 @@ def test_create_custom_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.create_custom_model(**req_copy) + _service.create_custom_model(**req_copy) @@ -542,8 +544,8 @@ def test_list_custom_models_all_params(self): list_custom_models() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations') - mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}]}' + url = self.preprocess_url(_base_url + '/v1/customizations') + mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -551,10 +553,10 @@ def test_list_custom_models_all_params(self): status=200) # Set up parameter values - language = 'de-DE' + language = 'ar-MS' # Invoke method - response = service.list_custom_models( + response = _service.list_custom_models( language=language, headers={} ) @@ -574,8 +576,8 @@ def test_list_custom_models_required_params(self): test_list_custom_models_required_params() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations') - mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}]}' + url = self.preprocess_url(_base_url + '/v1/customizations') + mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -583,7 +585,7 @@ def test_list_custom_models_required_params(self): status=200) # Invoke method - response = service.list_custom_models() + response = _service.list_custom_models() # Check for correct operation @@ -611,7 +613,7 @@ def test_update_custom_model_all_params(self): update_custom_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString') responses.add(responses.POST, url, status=200) @@ -629,7 +631,7 @@ def test_update_custom_model_all_params(self): words = [word_model] # Invoke method - response = service.update_custom_model( + response = _service.update_custom_model( customization_id, name=name, description=description, @@ -653,7 +655,7 @@ def test_update_custom_model_value_error(self): test_update_custom_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString') responses.add(responses.POST, url, status=200) @@ -677,7 +679,7 @@ def test_update_custom_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.update_custom_model(**req_copy) + _service.update_custom_model(**req_copy) @@ -701,8 +703,8 @@ def test_get_custom_model_all_params(self): get_custom_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString') - mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' + url = self.preprocess_url(_base_url + '/v1/customizations/testString') + mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' responses.add(responses.GET, url, body=mock_response, @@ -713,7 +715,7 @@ def test_get_custom_model_all_params(self): customization_id = 'testString' # Invoke method - response = service.get_custom_model( + response = _service.get_custom_model( customization_id, headers={} ) @@ -729,8 +731,8 @@ def test_get_custom_model_value_error(self): test_get_custom_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString') - mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' + url = self.preprocess_url(_base_url + '/v1/customizations/testString') + mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' responses.add(responses.GET, url, body=mock_response, @@ -747,7 +749,7 @@ def test_get_custom_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_custom_model(**req_copy) + _service.get_custom_model(**req_copy) @@ -771,7 +773,7 @@ def test_delete_custom_model_all_params(self): delete_custom_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString') responses.add(responses.DELETE, url, status=204) @@ -780,7 +782,7 @@ def test_delete_custom_model_all_params(self): customization_id = 'testString' # Invoke method - response = service.delete_custom_model( + response = _service.delete_custom_model( customization_id, headers={} ) @@ -796,7 +798,7 @@ def test_delete_custom_model_value_error(self): test_delete_custom_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString') responses.add(responses.DELETE, url, status=204) @@ -811,7 +813,7 @@ def test_delete_custom_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_custom_model(**req_copy) + _service.delete_custom_model(**req_copy) @@ -845,7 +847,7 @@ def test_add_words_all_params(self): add_words() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') responses.add(responses.POST, url, status=200) @@ -861,7 +863,7 @@ def test_add_words_all_params(self): words = [word_model] # Invoke method - response = service.add_words( + response = _service.add_words( customization_id, words, headers={} @@ -881,7 +883,7 @@ def test_add_words_value_error(self): test_add_words_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') responses.add(responses.POST, url, status=200) @@ -904,7 +906,7 @@ def test_add_words_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_words(**req_copy) + _service.add_words(**req_copy) @@ -928,7 +930,7 @@ def test_list_words_all_params(self): list_words() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' responses.add(responses.GET, url, @@ -940,7 +942,7 @@ def test_list_words_all_params(self): customization_id = 'testString' # Invoke method - response = service.list_words( + response = _service.list_words( customization_id, headers={} ) @@ -956,7 +958,7 @@ def test_list_words_value_error(self): test_list_words_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' responses.add(responses.GET, url, @@ -974,7 +976,7 @@ def test_list_words_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_words(**req_copy) + _service.list_words(**req_copy) @@ -998,7 +1000,7 @@ def test_add_word_all_params(self): add_word() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') responses.add(responses.PUT, url, status=200) @@ -1010,7 +1012,7 @@ def test_add_word_all_params(self): part_of_speech = 'Dosi' # Invoke method - response = service.add_word( + response = _service.add_word( customization_id, word, translation, @@ -1033,7 +1035,7 @@ def test_add_word_value_error(self): test_add_word_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') responses.add(responses.PUT, url, status=200) @@ -1053,7 +1055,7 @@ def test_add_word_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.add_word(**req_copy) + _service.add_word(**req_copy) @@ -1077,7 +1079,7 @@ def test_get_word_all_params(self): get_word() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') mock_response = '{"translation": "translation", "part_of_speech": "Dosi"}' responses.add(responses.GET, url, @@ -1090,7 +1092,7 @@ def test_get_word_all_params(self): word = 'testString' # Invoke method - response = service.get_word( + response = _service.get_word( customization_id, word, headers={} @@ -1107,7 +1109,7 @@ def test_get_word_value_error(self): test_get_word_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') mock_response = '{"translation": "translation", "part_of_speech": "Dosi"}' responses.add(responses.GET, url, @@ -1127,7 +1129,7 @@ def test_get_word_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.get_word(**req_copy) + _service.get_word(**req_copy) @@ -1151,7 +1153,7 @@ def test_delete_word_all_params(self): delete_word() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') responses.add(responses.DELETE, url, status=204) @@ -1161,7 +1163,7 @@ def test_delete_word_all_params(self): word = 'testString' # Invoke method - response = service.delete_word( + response = _service.delete_word( customization_id, word, headers={} @@ -1178,7 +1180,7 @@ def test_delete_word_value_error(self): test_delete_word_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/customizations/testString/words/testString') + url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') responses.add(responses.DELETE, url, status=204) @@ -1195,7 +1197,7 @@ def test_delete_word_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_word(**req_copy) + _service.delete_word(**req_copy) @@ -1204,6 +1206,625 @@ def test_delete_word_value_error(self): # End of Service: CustomWords ############################################################################## +############################################################################## +# Start of Service: CustomPrompts +############################################################################## +# region + +class TestListCustomPrompts(): + """ + Test Class for list_custom_prompts + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_custom_prompts_all_params(self): + """ + list_custom_prompts() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts') + mock_response = '{"prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Invoke method + response = _service.list_custom_prompts( + customization_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_list_custom_prompts_value_error(self): + """ + test_list_custom_prompts_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts') + mock_response = '{"prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_custom_prompts(**req_copy) + + + +class TestAddCustomPrompt(): + """ + Test Class for add_custom_prompt + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_add_custom_prompt_all_params(self): + """ + add_custom_prompt() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a PromptMetadata model + prompt_metadata_model = {} + prompt_metadata_model['prompt_text'] = 'testString' + prompt_metadata_model['speaker_id'] = 'testString' + + # Set up parameter values + customization_id = 'testString' + prompt_id = 'testString' + metadata = prompt_metadata_model + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + + # Invoke method + response = _service.add_custom_prompt( + customization_id, + prompt_id, + metadata, + file, + filename=filename, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + + @responses.activate + def test_add_custom_prompt_required_params(self): + """ + test_add_custom_prompt_required_params() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a PromptMetadata model + prompt_metadata_model = {} + prompt_metadata_model['prompt_text'] = 'testString' + prompt_metadata_model['speaker_id'] = 'testString' + + # Set up parameter values + customization_id = 'testString' + prompt_id = 'testString' + metadata = prompt_metadata_model + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + + # Invoke method + response = _service.add_custom_prompt( + customization_id, + prompt_id, + metadata, + file, + filename=filename, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + + @responses.activate + def test_add_custom_prompt_value_error(self): + """ + test_add_custom_prompt_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a PromptMetadata model + prompt_metadata_model = {} + prompt_metadata_model['prompt_text'] = 'testString' + prompt_metadata_model['speaker_id'] = 'testString' + + # Set up parameter values + customization_id = 'testString' + prompt_id = 'testString' + metadata = prompt_metadata_model + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "prompt_id": prompt_id, + "metadata": metadata, + "file": file, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.add_custom_prompt(**req_copy) + + + +class TestGetCustomPrompt(): + """ + Test Class for get_custom_prompt + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_custom_prompt_all_params(self): + """ + get_custom_prompt() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + prompt_id = 'testString' + + # Invoke method + response = _service.get_custom_prompt( + customization_id, + prompt_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_get_custom_prompt_value_error(self): + """ + test_get_custom_prompt_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + customization_id = 'testString' + prompt_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "prompt_id": prompt_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_custom_prompt(**req_copy) + + + +class TestDeleteCustomPrompt(): + """ + Test Class for delete_custom_prompt + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_custom_prompt_all_params(self): + """ + delete_custom_prompt() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + customization_id = 'testString' + prompt_id = 'testString' + + # Invoke method + response = _service.delete_custom_prompt( + customization_id, + prompt_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + + @responses.activate + def test_delete_custom_prompt_value_error(self): + """ + test_delete_custom_prompt_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + customization_id = 'testString' + prompt_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "customization_id": customization_id, + "prompt_id": prompt_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_custom_prompt(**req_copy) + + + +# endregion +############################################################################## +# End of Service: CustomPrompts +############################################################################## + +############################################################################## +# Start of Service: SpeakerModels +############################################################################## +# region + +class TestListSpeakerModels(): + """ + Test Class for list_speaker_models + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_speaker_models_all_params(self): + """ + list_speaker_models() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/speakers') + mock_response = '{"speakers": [{"speaker_id": "speaker_id", "name": "name"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = _service.list_speaker_models() + + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + +class TestCreateSpeakerModel(): + """ + Test Class for create_speaker_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_speaker_model_all_params(self): + """ + create_speaker_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/speakers') + mock_response = '{"speaker_id": "speaker_id"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + speaker_name = 'testString' + audio = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = _service.create_speaker_model( + speaker_name, + audio, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'speaker_name={}'.format(speaker_name) in query_string + # Validate body params + assert responses.calls[0].request.body == audio + + + @responses.activate + def test_create_speaker_model_value_error(self): + """ + test_create_speaker_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/speakers') + mock_response = '{"speaker_id": "speaker_id"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + speaker_name = 'testString' + audio = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "speaker_name": speaker_name, + "audio": audio, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_speaker_model(**req_copy) + + + +class TestGetSpeakerModel(): + """ + Test Class for get_speaker_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_speaker_model_all_params(self): + """ + get_speaker_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/speakers/testString') + mock_response = '{"customizations": [{"customization_id": "customization_id", "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + speaker_id = 'testString' + + # Invoke method + response = _service.get_speaker_model( + speaker_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_get_speaker_model_value_error(self): + """ + test_get_speaker_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/speakers/testString') + mock_response = '{"customizations": [{"customization_id": "customization_id", "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + speaker_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "speaker_id": speaker_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_speaker_model(**req_copy) + + + +class TestDeleteSpeakerModel(): + """ + Test Class for delete_speaker_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_speaker_model_all_params(self): + """ + delete_speaker_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/speakers/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + speaker_id = 'testString' + + # Invoke method + response = _service.delete_speaker_model( + speaker_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + + @responses.activate + def test_delete_speaker_model_value_error(self): + """ + test_delete_speaker_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/speakers/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + speaker_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "speaker_id": speaker_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_speaker_model(**req_copy) + + + +# endregion +############################################################################## +# End of Service: SpeakerModels +############################################################################## + ############################################################################## # Start of Service: UserData ############################################################################## @@ -1229,7 +1850,7 @@ def test_delete_user_data_all_params(self): delete_user_data() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/user_data') + url = self.preprocess_url(_base_url + '/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -1238,7 +1859,7 @@ def test_delete_user_data_all_params(self): customer_id = 'testString' # Invoke method - response = service.delete_user_data( + response = _service.delete_user_data( customer_id, headers={} ) @@ -1258,7 +1879,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/user_data') + url = self.preprocess_url(_base_url + '/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -1273,7 +1894,7 @@ def test_delete_user_data_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_user_data(**req_copy) + _service.delete_user_data(**req_copy) @@ -1304,6 +1925,13 @@ def test_custom_model_serialization(self): word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' + prompt_model = {} # Prompt + prompt_model['prompt'] = 'testString' + prompt_model['prompt_id'] = 'testString' + prompt_model['status'] = 'testString' + prompt_model['error'] = 'testString' + prompt_model['speaker_id'] = 'testString' + # Construct a json representation of a CustomModel model custom_model_model_json = {} custom_model_model_json['customization_id'] = 'testString' @@ -1314,6 +1942,7 @@ def test_custom_model_serialization(self): custom_model_model_json['last_modified'] = 'testString' custom_model_model_json['description'] = 'testString' custom_model_model_json['words'] = [word_model] + custom_model_model_json['prompts'] = [prompt_model] # Construct a model instance of CustomModel by calling from_dict on the json representation custom_model_model = CustomModel.from_dict(custom_model_model_json) @@ -1347,6 +1976,13 @@ def test_custom_models_serialization(self): word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' + prompt_model = {} # Prompt + prompt_model['prompt'] = 'testString' + prompt_model['prompt_id'] = 'testString' + prompt_model['status'] = 'testString' + prompt_model['error'] = 'testString' + prompt_model['speaker_id'] = 'testString' + custom_model_model = {} # CustomModel custom_model_model['customization_id'] = 'testString' custom_model_model['name'] = 'testString' @@ -1356,6 +1992,7 @@ def test_custom_models_serialization(self): custom_model_model['last_modified'] = 'testString' custom_model_model['description'] = 'testString' custom_model_model['words'] = [word_model] + custom_model_model['prompts'] = [prompt_model] # Construct a json representation of a CustomModels model custom_models_model_json = {} @@ -1376,6 +2013,107 @@ def test_custom_models_serialization(self): custom_models_model_json2 = custom_models_model.to_dict() assert custom_models_model_json2 == custom_models_model_json +class TestPrompt(): + """ + Test Class for Prompt + """ + + def test_prompt_serialization(self): + """ + Test serialization/deserialization for Prompt + """ + + # Construct a json representation of a Prompt model + prompt_model_json = {} + prompt_model_json['prompt'] = 'testString' + prompt_model_json['prompt_id'] = 'testString' + prompt_model_json['status'] = 'testString' + prompt_model_json['error'] = 'testString' + prompt_model_json['speaker_id'] = 'testString' + + # Construct a model instance of Prompt by calling from_dict on the json representation + prompt_model = Prompt.from_dict(prompt_model_json) + assert prompt_model != False + + # Construct a model instance of Prompt by calling from_dict on the json representation + prompt_model_dict = Prompt.from_dict(prompt_model_json).__dict__ + prompt_model2 = Prompt(**prompt_model_dict) + + # Verify the model instances are equivalent + assert prompt_model == prompt_model2 + + # Convert model instance back to dict and verify no loss of data + prompt_model_json2 = prompt_model.to_dict() + assert prompt_model_json2 == prompt_model_json + +class TestPromptMetadata(): + """ + Test Class for PromptMetadata + """ + + def test_prompt_metadata_serialization(self): + """ + Test serialization/deserialization for PromptMetadata + """ + + # Construct a json representation of a PromptMetadata model + prompt_metadata_model_json = {} + prompt_metadata_model_json['prompt_text'] = 'testString' + prompt_metadata_model_json['speaker_id'] = 'testString' + + # Construct a model instance of PromptMetadata by calling from_dict on the json representation + prompt_metadata_model = PromptMetadata.from_dict(prompt_metadata_model_json) + assert prompt_metadata_model != False + + # Construct a model instance of PromptMetadata by calling from_dict on the json representation + prompt_metadata_model_dict = PromptMetadata.from_dict(prompt_metadata_model_json).__dict__ + prompt_metadata_model2 = PromptMetadata(**prompt_metadata_model_dict) + + # Verify the model instances are equivalent + assert prompt_metadata_model == prompt_metadata_model2 + + # Convert model instance back to dict and verify no loss of data + prompt_metadata_model_json2 = prompt_metadata_model.to_dict() + assert prompt_metadata_model_json2 == prompt_metadata_model_json + +class TestPrompts(): + """ + Test Class for Prompts + """ + + def test_prompts_serialization(self): + """ + Test serialization/deserialization for Prompts + """ + + # Construct dict forms of any model objects needed in order to build this model. + + prompt_model = {} # Prompt + prompt_model['prompt'] = 'testString' + prompt_model['prompt_id'] = 'testString' + prompt_model['status'] = 'testString' + prompt_model['error'] = 'testString' + prompt_model['speaker_id'] = 'testString' + + # Construct a json representation of a Prompts model + prompts_model_json = {} + prompts_model_json['prompts'] = [prompt_model] + + # Construct a model instance of Prompts by calling from_dict on the json representation + prompts_model = Prompts.from_dict(prompts_model_json) + assert prompts_model != False + + # Construct a model instance of Prompts by calling from_dict on the json representation + prompts_model_dict = Prompts.from_dict(prompts_model_json).__dict__ + prompts_model2 = Prompts(**prompts_model_dict) + + # Verify the model instances are equivalent + assert prompts_model == prompts_model2 + + # Convert model instance back to dict and verify no loss of data + prompts_model_json2 = prompts_model.to_dict() + assert prompts_model_json2 == prompts_model_json + class TestPronunciation(): """ Test Class for Pronunciation @@ -1405,6 +2143,211 @@ def test_pronunciation_serialization(self): pronunciation_model_json2 = pronunciation_model.to_dict() assert pronunciation_model_json2 == pronunciation_model_json +class TestSpeaker(): + """ + Test Class for Speaker + """ + + def test_speaker_serialization(self): + """ + Test serialization/deserialization for Speaker + """ + + # Construct a json representation of a Speaker model + speaker_model_json = {} + speaker_model_json['speaker_id'] = 'testString' + speaker_model_json['name'] = 'testString' + + # Construct a model instance of Speaker by calling from_dict on the json representation + speaker_model = Speaker.from_dict(speaker_model_json) + assert speaker_model != False + + # Construct a model instance of Speaker by calling from_dict on the json representation + speaker_model_dict = Speaker.from_dict(speaker_model_json).__dict__ + speaker_model2 = Speaker(**speaker_model_dict) + + # Verify the model instances are equivalent + assert speaker_model == speaker_model2 + + # Convert model instance back to dict and verify no loss of data + speaker_model_json2 = speaker_model.to_dict() + assert speaker_model_json2 == speaker_model_json + +class TestSpeakerCustomModel(): + """ + Test Class for SpeakerCustomModel + """ + + def test_speaker_custom_model_serialization(self): + """ + Test serialization/deserialization for SpeakerCustomModel + """ + + # Construct dict forms of any model objects needed in order to build this model. + + speaker_prompt_model = {} # SpeakerPrompt + speaker_prompt_model['prompt'] = 'testString' + speaker_prompt_model['prompt_id'] = 'testString' + speaker_prompt_model['status'] = 'testString' + speaker_prompt_model['error'] = 'testString' + + # Construct a json representation of a SpeakerCustomModel model + speaker_custom_model_model_json = {} + speaker_custom_model_model_json['customization_id'] = 'testString' + speaker_custom_model_model_json['prompts'] = [speaker_prompt_model] + + # Construct a model instance of SpeakerCustomModel by calling from_dict on the json representation + speaker_custom_model_model = SpeakerCustomModel.from_dict(speaker_custom_model_model_json) + assert speaker_custom_model_model != False + + # Construct a model instance of SpeakerCustomModel by calling from_dict on the json representation + speaker_custom_model_model_dict = SpeakerCustomModel.from_dict(speaker_custom_model_model_json).__dict__ + speaker_custom_model_model2 = SpeakerCustomModel(**speaker_custom_model_model_dict) + + # Verify the model instances are equivalent + assert speaker_custom_model_model == speaker_custom_model_model2 + + # Convert model instance back to dict and verify no loss of data + speaker_custom_model_model_json2 = speaker_custom_model_model.to_dict() + assert speaker_custom_model_model_json2 == speaker_custom_model_model_json + +class TestSpeakerCustomModels(): + """ + Test Class for SpeakerCustomModels + """ + + def test_speaker_custom_models_serialization(self): + """ + Test serialization/deserialization for SpeakerCustomModels + """ + + # Construct dict forms of any model objects needed in order to build this model. + + speaker_prompt_model = {} # SpeakerPrompt + speaker_prompt_model['prompt'] = 'testString' + speaker_prompt_model['prompt_id'] = 'testString' + speaker_prompt_model['status'] = 'testString' + speaker_prompt_model['error'] = 'testString' + + speaker_custom_model_model = {} # SpeakerCustomModel + speaker_custom_model_model['customization_id'] = 'testString' + speaker_custom_model_model['prompts'] = [speaker_prompt_model] + + # Construct a json representation of a SpeakerCustomModels model + speaker_custom_models_model_json = {} + speaker_custom_models_model_json['customizations'] = [speaker_custom_model_model] + + # Construct a model instance of SpeakerCustomModels by calling from_dict on the json representation + speaker_custom_models_model = SpeakerCustomModels.from_dict(speaker_custom_models_model_json) + assert speaker_custom_models_model != False + + # Construct a model instance of SpeakerCustomModels by calling from_dict on the json representation + speaker_custom_models_model_dict = SpeakerCustomModels.from_dict(speaker_custom_models_model_json).__dict__ + speaker_custom_models_model2 = SpeakerCustomModels(**speaker_custom_models_model_dict) + + # Verify the model instances are equivalent + assert speaker_custom_models_model == speaker_custom_models_model2 + + # Convert model instance back to dict and verify no loss of data + speaker_custom_models_model_json2 = speaker_custom_models_model.to_dict() + assert speaker_custom_models_model_json2 == speaker_custom_models_model_json + +class TestSpeakerModel(): + """ + Test Class for SpeakerModel + """ + + def test_speaker_model_serialization(self): + """ + Test serialization/deserialization for SpeakerModel + """ + + # Construct a json representation of a SpeakerModel model + speaker_model_model_json = {} + speaker_model_model_json['speaker_id'] = 'testString' + + # Construct a model instance of SpeakerModel by calling from_dict on the json representation + speaker_model_model = SpeakerModel.from_dict(speaker_model_model_json) + assert speaker_model_model != False + + # Construct a model instance of SpeakerModel by calling from_dict on the json representation + speaker_model_model_dict = SpeakerModel.from_dict(speaker_model_model_json).__dict__ + speaker_model_model2 = SpeakerModel(**speaker_model_model_dict) + + # Verify the model instances are equivalent + assert speaker_model_model == speaker_model_model2 + + # Convert model instance back to dict and verify no loss of data + speaker_model_model_json2 = speaker_model_model.to_dict() + assert speaker_model_model_json2 == speaker_model_model_json + +class TestSpeakerPrompt(): + """ + Test Class for SpeakerPrompt + """ + + def test_speaker_prompt_serialization(self): + """ + Test serialization/deserialization for SpeakerPrompt + """ + + # Construct a json representation of a SpeakerPrompt model + speaker_prompt_model_json = {} + speaker_prompt_model_json['prompt'] = 'testString' + speaker_prompt_model_json['prompt_id'] = 'testString' + speaker_prompt_model_json['status'] = 'testString' + speaker_prompt_model_json['error'] = 'testString' + + # Construct a model instance of SpeakerPrompt by calling from_dict on the json representation + speaker_prompt_model = SpeakerPrompt.from_dict(speaker_prompt_model_json) + assert speaker_prompt_model != False + + # Construct a model instance of SpeakerPrompt by calling from_dict on the json representation + speaker_prompt_model_dict = SpeakerPrompt.from_dict(speaker_prompt_model_json).__dict__ + speaker_prompt_model2 = SpeakerPrompt(**speaker_prompt_model_dict) + + # Verify the model instances are equivalent + assert speaker_prompt_model == speaker_prompt_model2 + + # Convert model instance back to dict and verify no loss of data + speaker_prompt_model_json2 = speaker_prompt_model.to_dict() + assert speaker_prompt_model_json2 == speaker_prompt_model_json + +class TestSpeakers(): + """ + Test Class for Speakers + """ + + def test_speakers_serialization(self): + """ + Test serialization/deserialization for Speakers + """ + + # Construct dict forms of any model objects needed in order to build this model. + + speaker_model = {} # Speaker + speaker_model['speaker_id'] = 'testString' + speaker_model['name'] = 'testString' + + # Construct a json representation of a Speakers model + speakers_model_json = {} + speakers_model_json['speakers'] = [speaker_model] + + # Construct a model instance of Speakers by calling from_dict on the json representation + speakers_model = Speakers.from_dict(speakers_model_json) + assert speakers_model != False + + # Construct a model instance of Speakers by calling from_dict on the json representation + speakers_model_dict = Speakers.from_dict(speakers_model_json).__dict__ + speakers_model2 = Speakers(**speakers_model_dict) + + # Verify the model instances are equivalent + assert speakers_model == speakers_model2 + + # Convert model instance back to dict and verify no loss of data + speakers_model_json2 = speakers_model.to_dict() + assert speakers_model_json2 == speakers_model_json + class TestSupportedFeatures(): """ Test Class for SupportedFeatures @@ -1486,6 +2429,13 @@ def test_voice_serialization(self): word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' + prompt_model = {} # Prompt + prompt_model['prompt'] = 'testString' + prompt_model['prompt_id'] = 'testString' + prompt_model['status'] = 'testString' + prompt_model['error'] = 'testString' + prompt_model['speaker_id'] = 'testString' + custom_model_model = {} # CustomModel custom_model_model['customization_id'] = 'testString' custom_model_model['name'] = 'testString' @@ -1495,6 +2445,7 @@ def test_voice_serialization(self): custom_model_model['last_modified'] = 'testString' custom_model_model['description'] = 'testString' custom_model_model['words'] = [word_model] + custom_model_model['prompts'] = [prompt_model] # Construct a json representation of a Voice model voice_model_json = {} @@ -1543,6 +2494,13 @@ def test_voices_serialization(self): word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' + prompt_model = {} # Prompt + prompt_model['prompt'] = 'testString' + prompt_model['prompt_id'] = 'testString' + prompt_model['status'] = 'testString' + prompt_model['error'] = 'testString' + prompt_model['speaker_id'] = 'testString' + custom_model_model = {} # CustomModel custom_model_model['customization_id'] = 'testString' custom_model_model['name'] = 'testString' @@ -1552,6 +2510,7 @@ def test_voices_serialization(self): custom_model_model['last_modified'] = 'testString' custom_model_model['description'] = 'testString' custom_model_model['words'] = [word_model] + custom_model_model['prompts'] = [prompt_model] voice_model = {} # Voice voice_model['url'] = 'testString' From e5e71b655bc3d7477fd4244df28651fa91a82cd4 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 20 May 2021 14:35:42 -0400 Subject: [PATCH 319/455] feat(nlu): generation release changes --- .../natural_language_understanding_v1.py | 2943 ++++++++++++++--- .../test_natural_language_understanding_v1.py | 2091 +++++++++++- 2 files changed, 4534 insertions(+), 500 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index a48bae47e..e3108e0a5 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2019, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you @@ -28,7 +28,7 @@ from datetime import datetime from enum import Enum -from typing import Dict, List +from typing import BinaryIO, Dict, List import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -59,7 +59,7 @@ def __init__( Construct a new client for the Natural Language Understanding service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2020-08-01`. + Specify dates in YYYY-MM-DD format. The current version is `2021-03-25`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md @@ -98,6 +98,7 @@ def analyze(self, Analyzes text, HTML, or a public webpage for the following features: - Categories + - Classifications - Concepts - Emotion - Entities @@ -260,186 +261,1617 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: response = self.send(request) return response + ######################### + # Manage sentiment models + ######################### + + def create_sentiment_model(self, + language: str, + training_data: BinaryIO, + *, + name: str = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + **kwargs) -> DetailedResponse: + """ + Create sentiment model. + + (Beta) Creates a custom sentiment model by uploading training data and associated + metadata. The model begins the training and deploying process and is ready to use + when the `status` is `available`. + + :param str language: The 2-letter language code of this model. + :param BinaryIO training_data: Training data in CSV format. For more + information, see [Sentiment training data + requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-custom-sentiment#sentiment-training-data-requirements). + :param str name: (optional) An optional name for the model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio + workspace that deployed this model to Natural Language Understanding. + :param str version_description: (optional) The description of the version. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object + """ + + if language is None: + raise ValueError('language must be provided') + if training_data is None: + raise ValueError('training_data must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_sentiment_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + form_data.append(('language', (None, language, 'text/plain'))) + form_data.append(('training_data', (None, training_data, 'text/csv'))) + if name: + form_data.append(('name', (None, name, 'text/plain'))) + if description: + form_data.append(('description', (None, description, 'text/plain'))) + if model_version: + form_data.append( + ('model_version', (None, model_version, 'text/plain'))) + if workspace_id: + form_data.append( + ('workspace_id', (None, workspace_id, 'text/plain'))) + if version_description: + form_data.append(('version_description', (None, version_description, + 'text/plain'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/v1/models/sentiment' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request) + return response + + def list_sentiment_models(self, **kwargs) -> DetailedResponse: + """ + List sentiment models. + + (Beta) Returns all custom sentiment models associated with this service instance. + + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ListSentimentModelsResponse` object + """ + + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_sentiment_models') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/v1/models/sentiment' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def get_sentiment_model(self, model_id: str, **kwargs) -> DetailedResponse: + """ + Get sentiment model details. + + (Beta) Returns the status of the sentiment model with the given model ID. + + :param str model_id: ID of the model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object + """ + + if model_id is None: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_sentiment_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def update_sentiment_model(self, + model_id: str, + language: str, + training_data: BinaryIO, + *, + name: str = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + **kwargs) -> DetailedResponse: + """ + Update sentiment model. + + (Beta) Overwrites the training data associated with this custom sentiment model + and retrains the model. The new model replaces the current deployment. + + :param str model_id: ID of the model. + :param str language: The 2-letter language code of this model. + :param BinaryIO training_data: Training data in CSV format. For more + information, see [Sentiment training data + requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-custom-sentiment#sentiment-training-data-requirements). + :param str name: (optional) An optional name for the model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio + workspace that deployed this model to Natural Language Understanding. + :param str version_description: (optional) The description of the version. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object + """ + + if model_id is None: + raise ValueError('model_id must be provided') + if language is None: + raise ValueError('language must be provided') + if training_data is None: + raise ValueError('training_data must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_sentiment_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + form_data.append(('language', (None, language, 'text/plain'))) + form_data.append(('training_data', (None, training_data, 'text/csv'))) + if name: + form_data.append(('name', (None, name, 'text/plain'))) + if description: + form_data.append(('description', (None, description, 'text/plain'))) + if model_version: + form_data.append( + ('model_version', (None, model_version, 'text/plain'))) + if workspace_id: + form_data.append( + ('workspace_id', (None, workspace_id, 'text/plain'))) + if version_description: + form_data.append(('version_description', (None, version_description, + 'text/plain'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request) + return response + + def delete_sentiment_model(self, model_id: str, + **kwargs) -> DetailedResponse: + """ + Delete sentiment model. + + (Beta) Un-deploys the custom sentiment model with the given model ID and deletes + all associated customer data, including any training data or binary artifacts. + + :param str model_id: ID of the model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object + """ + + if model_id is None: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_sentiment_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + ######################### + # Manage categories models + ######################### + + def create_categories_model(self, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: str = None, + name: str = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + **kwargs) -> DetailedResponse: + """ + Create categories model. + + (Beta) Creates a custom categories model by uploading training data and associated + metadata. The model begins the training and deploying process and is ready to use + when the `status` is `available`. + + :param str language: The 2-letter language code of this model. + :param BinaryIO training_data: Training data in JSON format. For more + information, see [Categories training data + requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories##categories-training-data-requirements). + :param str training_data_content_type: (optional) The content type of + training_data. + :param str name: (optional) An optional name for the model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio + workspace that deployed this model to Natural Language Understanding. + :param str version_description: (optional) The description of the version. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object + """ + + if language is None: + raise ValueError('language must be provided') + if training_data is None: + raise ValueError('training_data must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_categories_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + form_data.append(('language', (None, language, 'text/plain'))) + form_data.append(('training_data', + (None, training_data, training_data_content_type or + 'application/octet-stream'))) + if name: + form_data.append(('name', (None, name, 'text/plain'))) + if description: + form_data.append(('description', (None, description, 'text/plain'))) + if model_version: + form_data.append( + ('model_version', (None, model_version, 'text/plain'))) + if workspace_id: + form_data.append( + ('workspace_id', (None, workspace_id, 'text/plain'))) + if version_description: + form_data.append(('version_description', (None, version_description, + 'text/plain'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/v1/models/categories' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request) + return response + + def list_categories_models(self, **kwargs) -> DetailedResponse: + """ + List categories models. + + (Beta) Returns all custom categories models associated with this service instance. + + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ListCategoriesModelsResponse` object + """ + + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_categories_models') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/v1/models/categories' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: + """ + Get categories model details. + + (Beta) Returns the status of the categories model with the given model ID. + + :param str model_id: ID of the model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object + """ + + if model_id is None: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_categories_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/models/categories/{model_id}'.format(**path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def update_categories_model(self, + model_id: str, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: str = None, + name: str = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + **kwargs) -> DetailedResponse: + """ + Update categories model. + + (Beta) Overwrites the training data associated with this custom categories model + and retrains the model. The new model replaces the current deployment. + + :param str model_id: ID of the model. + :param str language: The 2-letter language code of this model. + :param BinaryIO training_data: Training data in JSON format. For more + information, see [Categories training data + requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories##categories-training-data-requirements). + :param str training_data_content_type: (optional) The content type of + training_data. + :param str name: (optional) An optional name for the model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio + workspace that deployed this model to Natural Language Understanding. + :param str version_description: (optional) The description of the version. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object + """ + + if model_id is None: + raise ValueError('model_id must be provided') + if language is None: + raise ValueError('language must be provided') + if training_data is None: + raise ValueError('training_data must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_categories_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + form_data.append(('language', (None, language, 'text/plain'))) + form_data.append(('training_data', + (None, training_data, training_data_content_type or + 'application/octet-stream'))) + if name: + form_data.append(('name', (None, name, 'text/plain'))) + if description: + form_data.append(('description', (None, description, 'text/plain'))) + if model_version: + form_data.append( + ('model_version', (None, model_version, 'text/plain'))) + if workspace_id: + form_data.append( + ('workspace_id', (None, workspace_id, 'text/plain'))) + if version_description: + form_data.append(('version_description', (None, version_description, + 'text/plain'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/models/categories/{model_id}'.format(**path_param_dict) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request) + return response + + def delete_categories_model(self, model_id: str, + **kwargs) -> DetailedResponse: + """ + Delete categories model. + + (Beta) Un-deploys the custom categories model with the given model ID and deletes + all associated customer data, including any training data or binary artifacts. + + :param str model_id: ID of the model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object + """ + + if model_id is None: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_categories_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/models/categories/{model_id}'.format(**path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + ######################### + # Manage classifications models + ######################### + + def create_classifications_model(self, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: str = None, + name: str = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + **kwargs) -> DetailedResponse: + """ + Create classifications model. + + (Beta) Creates a custom classifications model by uploading training data and + associated metadata. The model begins the training and deploying process and is + ready to use when the `status` is `available`. + + :param str language: The 2-letter language code of this model. + :param BinaryIO training_data: Training data in JSON format. For more + information, see [Classifications training data + requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-classifications#classification-training-data-requirements). + :param str training_data_content_type: (optional) The content type of + training_data. + :param str name: (optional) An optional name for the model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio + workspace that deployed this model to Natural Language Understanding. + :param str version_description: (optional) The description of the version. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object + """ + + if language is None: + raise ValueError('language must be provided') + if training_data is None: + raise ValueError('training_data must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_classifications_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + form_data.append(('language', (None, language, 'text/plain'))) + form_data.append(('training_data', + (None, training_data, training_data_content_type or + 'application/octet-stream'))) + if name: + form_data.append(('name', (None, name, 'text/plain'))) + if description: + form_data.append(('description', (None, description, 'text/plain'))) + if model_version: + form_data.append( + ('model_version', (None, model_version, 'text/plain'))) + if workspace_id: + form_data.append( + ('workspace_id', (None, workspace_id, 'text/plain'))) + if version_description: + form_data.append(('version_description', (None, version_description, + 'text/plain'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/v1/models/classifications' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request) + return response + + def list_classifications_models(self, **kwargs) -> DetailedResponse: + """ + List classifications models. + + (Beta) Returns all custom classifications models associated with this service + instance. + + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ListClassificationsModelsResponse` object + """ + + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_classifications_models') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + url = '/v1/models/classifications' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def get_classifications_model(self, model_id: str, + **kwargs) -> DetailedResponse: + """ + Get classifications model details. + + (Beta) Returns the status of the classifications model with the given model ID. + + :param str model_id: ID of the model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object + """ + + if model_id is None: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_classifications_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + def update_classifications_model(self, + model_id: str, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: str = None, + name: str = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + **kwargs) -> DetailedResponse: + """ + Update classifications model. + + (Beta) Overwrites the training data associated with this custom classifications + model and retrains the model. The new model replaces the current deployment. + + :param str model_id: ID of the model. + :param str language: The 2-letter language code of this model. + :param BinaryIO training_data: Training data in JSON format. For more + information, see [Classifications training data + requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-classifications#classification-training-data-requirements). + :param str training_data_content_type: (optional) The content type of + training_data. + :param str name: (optional) An optional name for the model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio + workspace that deployed this model to Natural Language Understanding. + :param str version_description: (optional) The description of the version. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object + """ + + if model_id is None: + raise ValueError('model_id must be provided') + if language is None: + raise ValueError('language must be provided') + if training_data is None: + raise ValueError('training_data must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_classifications_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + form_data.append(('language', (None, language, 'text/plain'))) + form_data.append(('training_data', + (None, training_data, training_data_content_type or + 'application/octet-stream'))) + if name: + form_data.append(('name', (None, name, 'text/plain'))) + if description: + form_data.append(('description', (None, description, 'text/plain'))) + if model_version: + form_data.append( + ('model_version', (None, model_version, 'text/plain'))) + if workspace_id: + form_data.append( + ('workspace_id', (None, workspace_id, 'text/plain'))) + if version_description: + form_data.append(('version_description', (None, version_description, + 'text/plain'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) + request = self.prepare_request(method='PUT', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request) + return response + + def delete_classifications_model(self, model_id: str, + **kwargs) -> DetailedResponse: + """ + Delete classifications model. + + (Beta) Un-deploys the custom classifications model with the given model ID and + deletes all associated customer data, including any training data or binary + artifacts. + + :param str model_id: ID of the model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object + """ + + if model_id is None: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_classifications_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + headers['Accept'] = 'application/json' + + path_param_keys = ['model_id'] + path_param_values = self.encode_path_vars(model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request) + return response + + +class CreateCategoriesModelEnums: + """ + Enums for create_categories_model parameters. + """ + + class TrainingDataContentType(str, Enum): + """ + The content type of training_data. + """ + JSON = 'json' + APPLICATION_JSON = 'application/json' + + +class UpdateCategoriesModelEnums: + """ + Enums for update_categories_model parameters. + """ + + class TrainingDataContentType(str, Enum): + """ + The content type of training_data. + """ + JSON = 'json' + APPLICATION_JSON = 'application/json' + + +class CreateClassificationsModelEnums: + """ + Enums for create_classifications_model parameters. + """ + + class TrainingDataContentType(str, Enum): + """ + The content type of training_data. + """ + JSON = 'json' + APPLICATION_JSON = 'application/json' + + +class UpdateClassificationsModelEnums: + """ + Enums for update_classifications_model parameters. + """ + + class TrainingDataContentType(str, Enum): + """ + The content type of training_data. + """ + JSON = 'json' + APPLICATION_JSON = 'application/json' + + +############################################################################## +# Models +############################################################################## + + +class AnalysisResults(): + """ + Results of the analysis, organized by feature. + + :attr str language: (optional) Language used to analyze the text. + :attr str analyzed_text: (optional) Text that was used in the analysis. + :attr str retrieved_url: (optional) URL of the webpage that was analyzed. + :attr AnalysisResultsUsage usage: (optional) API usage information for the + request. + :attr List[ConceptsResult] concepts: (optional) The general concepts referenced + or alluded to in the analyzed text. + :attr List[EntitiesResult] entities: (optional) The entities detected in the + analyzed text. + :attr List[KeywordsResult] keywords: (optional) The keywords from the analyzed + text. + :attr List[CategoriesResult] categories: (optional) The categories that the + service assigned to the analyzed text. + :attr List[ClassificationsResult] classifications: (optional) The + classifications assigned to the analyzed text. + :attr EmotionResult emotion: (optional) The anger, disgust, fear, joy, or + sadness conveyed by the content. + :attr FeaturesResultsMetadata metadata: (optional) Webpage metadata, such as the + author and the title of the page. + :attr List[RelationsResult] relations: (optional) The relationships between + entities in the content. + :attr List[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into + `subject`, `action`, and `object` form. + :attr SentimentResult sentiment: (optional) The sentiment of the content. + :attr SyntaxResult syntax: (optional) Tokens and sentences returned from syntax + analysis. + """ + + def __init__(self, + *, + language: str = None, + analyzed_text: str = None, + retrieved_url: str = None, + usage: 'AnalysisResultsUsage' = None, + concepts: List['ConceptsResult'] = None, + entities: List['EntitiesResult'] = None, + keywords: List['KeywordsResult'] = None, + categories: List['CategoriesResult'] = None, + classifications: List['ClassificationsResult'] = None, + emotion: 'EmotionResult' = None, + metadata: 'FeaturesResultsMetadata' = None, + relations: List['RelationsResult'] = None, + semantic_roles: List['SemanticRolesResult'] = None, + sentiment: 'SentimentResult' = None, + syntax: 'SyntaxResult' = None) -> None: + """ + Initialize a AnalysisResults object. + + :param str language: (optional) Language used to analyze the text. + :param str analyzed_text: (optional) Text that was used in the analysis. + :param str retrieved_url: (optional) URL of the webpage that was analyzed. + :param AnalysisResultsUsage usage: (optional) API usage information for the + request. + :param List[ConceptsResult] concepts: (optional) The general concepts + referenced or alluded to in the analyzed text. + :param List[EntitiesResult] entities: (optional) The entities detected in + the analyzed text. + :param List[KeywordsResult] keywords: (optional) The keywords from the + analyzed text. + :param List[CategoriesResult] categories: (optional) The categories that + the service assigned to the analyzed text. + :param List[ClassificationsResult] classifications: (optional) The + classifications assigned to the analyzed text. + :param EmotionResult emotion: (optional) The anger, disgust, fear, joy, or + sadness conveyed by the content. + :param FeaturesResultsMetadata metadata: (optional) Webpage metadata, such + as the author and the title of the page. + :param List[RelationsResult] relations: (optional) The relationships + between entities in the content. + :param List[SemanticRolesResult] semantic_roles: (optional) Sentences + parsed into `subject`, `action`, and `object` form. + :param SentimentResult sentiment: (optional) The sentiment of the content. + :param SyntaxResult syntax: (optional) Tokens and sentences returned from + syntax analysis. + """ + self.language = language + self.analyzed_text = analyzed_text + self.retrieved_url = retrieved_url + self.usage = usage + self.concepts = concepts + self.entities = entities + self.keywords = keywords + self.categories = categories + self.classifications = classifications + self.emotion = emotion + self.metadata = metadata + self.relations = relations + self.semantic_roles = semantic_roles + self.sentiment = sentiment + self.syntax = syntax + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AnalysisResults': + """Initialize a AnalysisResults object from a json dictionary.""" + args = {} + if 'language' in _dict: + args['language'] = _dict.get('language') + if 'analyzed_text' in _dict: + args['analyzed_text'] = _dict.get('analyzed_text') + if 'retrieved_url' in _dict: + args['retrieved_url'] = _dict.get('retrieved_url') + if 'usage' in _dict: + args['usage'] = AnalysisResultsUsage.from_dict(_dict.get('usage')) + if 'concepts' in _dict: + args['concepts'] = [ + ConceptsResult.from_dict(x) for x in _dict.get('concepts') + ] + if 'entities' in _dict: + args['entities'] = [ + EntitiesResult.from_dict(x) for x in _dict.get('entities') + ] + if 'keywords' in _dict: + args['keywords'] = [ + KeywordsResult.from_dict(x) for x in _dict.get('keywords') + ] + if 'categories' in _dict: + args['categories'] = [ + CategoriesResult.from_dict(x) for x in _dict.get('categories') + ] + if 'classifications' in _dict: + args['classifications'] = [ + ClassificationsResult.from_dict(x) + for x in _dict.get('classifications') + ] + if 'emotion' in _dict: + args['emotion'] = EmotionResult.from_dict(_dict.get('emotion')) + if 'metadata' in _dict: + args['metadata'] = FeaturesResultsMetadata.from_dict( + _dict.get('metadata')) + if 'relations' in _dict: + args['relations'] = [ + RelationsResult.from_dict(x) for x in _dict.get('relations') + ] + if 'semantic_roles' in _dict: + args['semantic_roles'] = [ + SemanticRolesResult.from_dict(x) + for x in _dict.get('semantic_roles') + ] + if 'sentiment' in _dict: + args['sentiment'] = SentimentResult.from_dict( + _dict.get('sentiment')) + if 'syntax' in _dict: + args['syntax'] = SyntaxResult.from_dict(_dict.get('syntax')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalysisResults 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, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'analyzed_text') and self.analyzed_text is not None: + _dict['analyzed_text'] = self.analyzed_text + if hasattr(self, 'retrieved_url') and self.retrieved_url is not None: + _dict['retrieved_url'] = self.retrieved_url + if hasattr(self, 'usage') and self.usage is not None: + _dict['usage'] = self.usage.to_dict() + if hasattr(self, 'concepts') and self.concepts is not None: + _dict['concepts'] = [x.to_dict() for x in self.concepts] + if hasattr(self, 'entities') and self.entities is not None: + _dict['entities'] = [x.to_dict() for x in self.entities] + if hasattr(self, 'keywords') and self.keywords is not None: + _dict['keywords'] = [x.to_dict() for x in self.keywords] + if hasattr(self, 'categories') and self.categories is not None: + _dict['categories'] = [x.to_dict() for x in self.categories] + if hasattr(self, + 'classifications') and self.classifications is not None: + _dict['classifications'] = [ + x.to_dict() for x in self.classifications + ] + if hasattr(self, 'emotion') and self.emotion is not None: + _dict['emotion'] = self.emotion.to_dict() + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata.to_dict() + if hasattr(self, 'relations') and self.relations is not None: + _dict['relations'] = [x.to_dict() for x in self.relations] + if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: + _dict['semantic_roles'] = [x.to_dict() for x in self.semantic_roles] + if hasattr(self, 'sentiment') and self.sentiment is not None: + _dict['sentiment'] = self.sentiment.to_dict() + if hasattr(self, 'syntax') and self.syntax is not None: + _dict['syntax'] = self.syntax.to_dict() + 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 AnalysisResults object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AnalysisResults') -> 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: 'AnalysisResults') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AnalysisResultsUsage(): + """ + API usage information for the request. + + :attr int features: (optional) Number of features used in the API call. + :attr int text_characters: (optional) Number of text characters processed. + :attr int text_units: (optional) Number of 10,000-character units processed. + """ + + def __init__(self, + *, + features: int = None, + text_characters: int = None, + text_units: int = None) -> None: + """ + Initialize a AnalysisResultsUsage object. + + :param int features: (optional) Number of features used in the API call. + :param int text_characters: (optional) Number of text characters processed. + :param int text_units: (optional) Number of 10,000-character units + processed. + """ + self.features = features + self.text_characters = text_characters + self.text_units = text_units + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AnalysisResultsUsage': + """Initialize a AnalysisResultsUsage object from a json dictionary.""" + args = {} + if 'features' in _dict: + args['features'] = _dict.get('features') + if 'text_characters' in _dict: + args['text_characters'] = _dict.get('text_characters') + if 'text_units' in _dict: + args['text_units'] = _dict.get('text_units') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalysisResultsUsage 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, 'features') and self.features is not None: + _dict['features'] = self.features + if hasattr(self, + 'text_characters') and self.text_characters is not None: + _dict['text_characters'] = self.text_characters + if hasattr(self, 'text_units') and self.text_units is not None: + _dict['text_units'] = self.text_units + 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 AnalysisResultsUsage object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AnalysisResultsUsage') -> 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: 'AnalysisResultsUsage') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Author(): + """ + The author of the analyzed content. + + :attr str name: (optional) Name of the author. + """ + + def __init__(self, *, name: str = None) -> None: + """ + Initialize a Author object. + + :param str name: (optional) Name of the author. + """ + self.name = name + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Author': + """Initialize a Author object from a json dictionary.""" + args = {} + if 'name' in _dict: + args['name'] = _dict.get('name') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Author 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, 'name') and self.name is not None: + _dict['name'] = self.name + 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 Author object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Author') -> 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: 'Author') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CategoriesModel(): + """ + Categories model. + + :attr str name: (optional) An optional name for the model. + :attr dict user_metadata: (optional) An optional map of metadata key-value pairs + to store with this model. + :attr str language: The 2-letter language code of this model. + :attr str description: (optional) An optional description of the model. + :attr str model_version: (optional) An optional version string. + :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + that deployed this model to Natural Language Understanding. + :attr str version_description: (optional) The description of the version. + :attr List[str] features: (optional) The service features that are supported by + the custom model. + :attr str status: When the status is `available`, the model is ready to use. + :attr str model_id: Unique model ID. + :attr datetime created: dateTime indicating when the model was created. + :attr List[Notice] notices: (optional) + :attr datetime last_trained: (optional) dateTime of last successful model + training. + :attr datetime last_deployed: (optional) dateTime of last successful model + deployment. + """ + + def __init__(self, + language: str, + status: str, + model_id: str, + created: datetime, + *, + name: str = None, + user_metadata: dict = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + features: List[str] = None, + notices: List['Notice'] = None, + last_trained: datetime = None, + last_deployed: datetime = None) -> None: + """ + Initialize a CategoriesModel object. + + :param str language: The 2-letter language code of this model. + :param str status: When the status is `available`, the model is ready to + use. + :param str model_id: Unique model ID. + :param datetime created: dateTime indicating when the model was created. + :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio + workspace that deployed this model to Natural Language Understanding. + :param str version_description: (optional) The description of the version. + :param List[str] features: (optional) The service features that are + supported by the custom model. + :param List[Notice] notices: (optional) + :param datetime last_trained: (optional) dateTime of last successful model + training. + :param datetime last_deployed: (optional) dateTime of last successful model + deployment. + """ + self.name = name + self.user_metadata = user_metadata + self.language = language + self.description = description + self.model_version = model_version + self.workspace_id = workspace_id + self.version_description = version_description + self.features = features + self.status = status + self.model_id = model_id + self.created = created + self.notices = notices + self.last_trained = last_trained + self.last_deployed = last_deployed + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CategoriesModel': + """Initialize a CategoriesModel object from a json dictionary.""" + args = {} + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'user_metadata' in _dict: + args['user_metadata'] = _dict.get('user_metadata') + if 'language' in _dict: + args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in CategoriesModel JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'model_version' in _dict: + args['model_version'] = _dict.get('model_version') + if 'workspace_id' in _dict: + args['workspace_id'] = _dict.get('workspace_id') + if 'version_description' in _dict: + args['version_description'] = _dict.get('version_description') + if 'features' in _dict: + args['features'] = _dict.get('features') + if 'status' in _dict: + args['status'] = _dict.get('status') + else: + raise ValueError( + 'Required property \'status\' not present in CategoriesModel JSON' + ) + if 'model_id' in _dict: + args['model_id'] = _dict.get('model_id') + else: + raise ValueError( + 'Required property \'model_id\' not present in CategoriesModel JSON' + ) + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + else: + raise ValueError( + 'Required property \'created\' not present in CategoriesModel JSON' + ) + if 'notices' in _dict: + args['notices'] = [ + Notice.from_dict(x) for x in _dict.get('notices') + ] + if 'last_trained' in _dict: + args['last_trained'] = string_to_datetime(_dict.get('last_trained')) + if 'last_deployed' in _dict: + args['last_deployed'] = string_to_datetime( + _dict.get('last_deployed')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoriesModel 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'user_metadata') and self.user_metadata is not None: + _dict['user_metadata'] = self.user_metadata + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'model_version') and self.model_version is not None: + _dict['model_version'] = self.model_version + if hasattr(self, 'workspace_id') and self.workspace_id is not None: + _dict['workspace_id'] = self.workspace_id + if hasattr( + self, + 'version_description') and self.version_description is not None: + _dict['version_description'] = self.version_description + if hasattr(self, 'features') and self.features is not None: + _dict['features'] = self.features + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + if hasattr(self, 'model_id') and self.model_id is not None: + _dict['model_id'] = self.model_id + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'notices') and self.notices is not None: + _dict['notices'] = [x.to_dict() for x in self.notices] + if hasattr(self, 'last_trained') and self.last_trained is not None: + _dict['last_trained'] = datetime_to_string(self.last_trained) + if hasattr(self, 'last_deployed') and self.last_deployed is not None: + _dict['last_deployed'] = datetime_to_string(self.last_deployed) + 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 CategoriesModel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CategoriesModel') -> 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: 'CategoriesModel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + When the status is `available`, the model is ready to use. + """ + STARTING = 'starting' + TRAINING = 'training' + DEPLOYING = 'deploying' + AVAILABLE = 'available' + ERROR = 'error' + DELETED = 'deleted' + + +class CategoriesModelList(): + """ + List of categories models. + + :attr List[CategoriesModel] models: (optional) The categories models. + """ + + def __init__(self, *, models: List['CategoriesModel'] = None) -> None: + """ + Initialize a CategoriesModelList object. + + :param List[CategoriesModel] models: (optional) The categories models. + """ + self.models = models + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CategoriesModelList': + """Initialize a CategoriesModelList object from a json dictionary.""" + args = {} + if 'models' in _dict: + args['models'] = [ + CategoriesModel.from_dict(x) for x in _dict.get('models') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CategoriesModelList 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, 'models') and self.models is not None: + _dict['models'] = [x.to_dict() for x in self.models] + 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 CategoriesModelList object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CategoriesModelList') -> 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: 'CategoriesModelList') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CategoriesOptions(): + """ + Returns a five-level taxonomy of the content. The top three categories are returned. + Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, + Portuguese, Spanish. + + :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) (Beta) Enter a [custom + model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the standard categories model. **This is available only for + English categories.**. + """ + + def __init__(self, + *, + explanation: bool = None, + limit: int = None, + model: str = None) -> None: + """ + Initialize a CategoriesOptions object. + + :param bool explanation: (optional) Set this to `true` to return + explanations for each categorization. **This is available only for English + categories.**. + :param int limit: (optional) Maximum number of categories to return. + :param str model: (optional) (Beta) Enter a [custom + model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the standard categories model. **This is available only for + English categories.**. + """ + 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 = {} + if 'explanation' in _dict: + 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 + def _from_dict(cls, _dict): + """Initialize a CategoriesOptions 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, 'explanation') and self.explanation is not None: + _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 -############################################################################## -# Models -############################################################################## + 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 CategoriesOptions object.""" + return json.dumps(self.to_dict(), indent=2) -class AnalysisResults(): + def __eq__(self, other: 'CategoriesOptions') -> 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: 'CategoriesOptions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CategoriesRelevantText(): """ - Results of the analysis, organized by feature. + Relevant text that contributed to the categorization. - :attr str language: (optional) Language used to analyze the text. - :attr str analyzed_text: (optional) Text that was used in the analysis. - :attr str retrieved_url: (optional) URL of the webpage that was analyzed. - :attr AnalysisResultsUsage usage: (optional) API usage information for the - request. - :attr List[ConceptsResult] concepts: (optional) The general concepts referenced - or alluded to in the analyzed text. - :attr List[EntitiesResult] entities: (optional) The entities detected in the - analyzed text. - :attr List[KeywordsResult] keywords: (optional) The keywords from the analyzed - text. - :attr List[CategoriesResult] categories: (optional) The categories that the - service assigned to the analyzed text. - :attr EmotionResult emotion: (optional) The anger, disgust, fear, joy, or - sadness conveyed by the content. - :attr FeaturesResultsMetadata metadata: (optional) Webpage metadata, such as the - author and the title of the page. - :attr List[RelationsResult] relations: (optional) The relationships between - entities in the content. - :attr List[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into - `subject`, `action`, and `object` form. - :attr SentimentResult sentiment: (optional) The sentiment of the content. - :attr SyntaxResult syntax: (optional) Tokens and sentences returned from syntax - analysis. + :attr str text: (optional) Text from the analyzed source that supports the + categorization. """ - def __init__(self, - *, - language: str = None, - analyzed_text: str = None, - retrieved_url: str = None, - usage: 'AnalysisResultsUsage' = None, - concepts: List['ConceptsResult'] = None, - entities: List['EntitiesResult'] = None, - keywords: List['KeywordsResult'] = None, - categories: List['CategoriesResult'] = None, - emotion: 'EmotionResult' = None, - metadata: 'FeaturesResultsMetadata' = None, - relations: List['RelationsResult'] = None, - semantic_roles: List['SemanticRolesResult'] = None, - sentiment: 'SentimentResult' = None, - syntax: 'SyntaxResult' = None) -> None: + def __init__(self, *, text: str = None) -> None: """ - Initialize a AnalysisResults object. + Initialize a CategoriesRelevantText object. - :param str language: (optional) Language used to analyze the text. - :param str analyzed_text: (optional) Text that was used in the analysis. - :param str retrieved_url: (optional) URL of the webpage that was analyzed. - :param AnalysisResultsUsage usage: (optional) API usage information for the - request. - :param List[ConceptsResult] concepts: (optional) The general concepts - referenced or alluded to in the analyzed text. - :param List[EntitiesResult] entities: (optional) The entities detected in - the analyzed text. - :param List[KeywordsResult] keywords: (optional) The keywords from the - analyzed text. - :param List[CategoriesResult] categories: (optional) The categories that - the service assigned to the analyzed text. - :param EmotionResult emotion: (optional) The anger, disgust, fear, joy, or - sadness conveyed by the content. - :param FeaturesResultsMetadata metadata: (optional) Webpage metadata, such - as the author and the title of the page. - :param List[RelationsResult] relations: (optional) The relationships - between entities in the content. - :param List[SemanticRolesResult] semantic_roles: (optional) Sentences - parsed into `subject`, `action`, and `object` form. - :param SentimentResult sentiment: (optional) The sentiment of the content. - :param SyntaxResult syntax: (optional) Tokens and sentences returned from - syntax analysis. + :param str text: (optional) Text from the analyzed source that supports the + categorization. """ - self.language = language - self.analyzed_text = analyzed_text - self.retrieved_url = retrieved_url - self.usage = usage - self.concepts = concepts - self.entities = entities - self.keywords = keywords - self.categories = categories - self.emotion = emotion - self.metadata = metadata - self.relations = relations - self.semantic_roles = semantic_roles - self.sentiment = sentiment - self.syntax = syntax + self.text = text @classmethod - def from_dict(cls, _dict: Dict) -> 'AnalysisResults': - """Initialize a AnalysisResults object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CategoriesRelevantText': + """Initialize a CategoriesRelevantText object from a json dictionary.""" args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'analyzed_text' in _dict: - args['analyzed_text'] = _dict.get('analyzed_text') - if 'retrieved_url' in _dict: - args['retrieved_url'] = _dict.get('retrieved_url') - if 'usage' in _dict: - args['usage'] = AnalysisResultsUsage.from_dict(_dict.get('usage')) - if 'concepts' in _dict: - args['concepts'] = [ - ConceptsResult.from_dict(x) for x in _dict.get('concepts') - ] - if 'entities' in _dict: - args['entities'] = [ - EntitiesResult.from_dict(x) for x in _dict.get('entities') - ] - if 'keywords' in _dict: - args['keywords'] = [ - KeywordsResult.from_dict(x) for x in _dict.get('keywords') - ] - if 'categories' in _dict: - args['categories'] = [ - CategoriesResult.from_dict(x) for x in _dict.get('categories') - ] - if 'emotion' in _dict: - args['emotion'] = EmotionResult.from_dict(_dict.get('emotion')) - if 'metadata' in _dict: - args['metadata'] = FeaturesResultsMetadata.from_dict( - _dict.get('metadata')) - if 'relations' in _dict: - args['relations'] = [ - RelationsResult.from_dict(x) for x in _dict.get('relations') - ] - if 'semantic_roles' in _dict: - args['semantic_roles'] = [ - SemanticRolesResult.from_dict(x) - for x in _dict.get('semantic_roles') - ] - if 'sentiment' in _dict: - args['sentiment'] = SentimentResult.from_dict( - _dict.get('sentiment')) - if 'syntax' in _dict: - args['syntax'] = SyntaxResult.from_dict(_dict.get('syntax')) + if 'text' in _dict: + args['text'] = _dict.get('text') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a AnalysisResults object from a json dictionary.""" + """Initialize a CategoriesRelevantText 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, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'analyzed_text') and self.analyzed_text is not None: - _dict['analyzed_text'] = self.analyzed_text - if hasattr(self, 'retrieved_url') and self.retrieved_url is not None: - _dict['retrieved_url'] = self.retrieved_url - if hasattr(self, 'usage') and self.usage is not None: - _dict['usage'] = self.usage.to_dict() - if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = [x.to_dict() for x in self.concepts] - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x.to_dict() for x in self.keywords] - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x.to_dict() for x in self.categories] - if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata.to_dict() - if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = [x.to_dict() for x in self.relations] - if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = [x.to_dict() for x in self.semantic_roles] - if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() - if hasattr(self, 'syntax') and self.syntax is not None: - _dict['syntax'] = self.syntax.to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text return _dict def _to_dict(self): @@ -447,73 +1879,81 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this AnalysisResults object.""" + """Return a `str` version of this CategoriesRelevantText object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'AnalysisResults') -> bool: + def __eq__(self, other: 'CategoriesRelevantText') -> 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: 'AnalysisResults') -> bool: + def __ne__(self, other: 'CategoriesRelevantText') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class AnalysisResultsUsage(): +class CategoriesResult(): """ - API usage information for the request. + A categorization of the analyzed text. - :attr int features: (optional) Number of features used in the API call. - :attr int text_characters: (optional) Number of text characters processed. - :attr int text_units: (optional) Number of 10,000-character units processed. + :attr str label: (optional) The path to the category through the 5-level + taxonomy hierarchy. For more information about the categories, see [Categories + hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). + :attr float score: (optional) Confidence score for the category classification. + Higher values indicate greater confidence. + :attr CategoriesResultExplanation explanation: (optional) Information that helps + to explain what contributed to the categories result. """ def __init__(self, *, - features: int = None, - text_characters: int = None, - text_units: int = None) -> None: + label: str = None, + score: float = None, + explanation: 'CategoriesResultExplanation' = None) -> None: """ - Initialize a AnalysisResultsUsage object. + Initialize a CategoriesResult object. - :param int features: (optional) Number of features used in the API call. - :param int text_characters: (optional) Number of text characters processed. - :param int text_units: (optional) Number of 10,000-character units - processed. + :param str label: (optional) The path to the category through the 5-level + taxonomy hierarchy. For more information about the categories, see + [Categories + hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). + :param float score: (optional) Confidence score for the category + classification. Higher values indicate greater confidence. + :param CategoriesResultExplanation explanation: (optional) Information that + helps to explain what contributed to the categories result. """ - self.features = features - self.text_characters = text_characters - self.text_units = text_units + self.label = label + self.score = score + self.explanation = explanation @classmethod - def from_dict(cls, _dict: Dict) -> 'AnalysisResultsUsage': - """Initialize a AnalysisResultsUsage object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CategoriesResult': + """Initialize a CategoriesResult object from a json dictionary.""" args = {} - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'text_characters' in _dict: - args['text_characters'] = _dict.get('text_characters') - if 'text_units' in _dict: - args['text_units'] = _dict.get('text_units') + if 'label' in _dict: + args['label'] = _dict.get('label') + if 'score' in _dict: + args['score'] = _dict.get('score') + if 'explanation' in _dict: + args['explanation'] = CategoriesResultExplanation.from_dict( + _dict.get('explanation')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a AnalysisResultsUsage object from a json dictionary.""" + """Initialize a CategoriesResult 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, 'features') and self.features is not None: - _dict['features'] = self.features - if hasattr(self, - 'text_characters') and self.text_characters is not None: - _dict['text_characters'] = self.text_characters - if hasattr(self, 'text_units') and self.text_units is not None: - _dict['text_units'] = self.text_units + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score + if hasattr(self, 'explanation') and self.explanation is not None: + _dict['explanation'] = self.explanation.to_dict() return _dict def _to_dict(self): @@ -521,53 +1961,64 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this AnalysisResultsUsage object.""" + """Return a `str` version of this CategoriesResult object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'AnalysisResultsUsage') -> bool: + def __eq__(self, other: 'CategoriesResult') -> 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: 'AnalysisResultsUsage') -> bool: + def __ne__(self, other: 'CategoriesResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Author(): +class CategoriesResultExplanation(): """ - The author of the analyzed content. + Information that helps to explain what contributed to the categories result. - :attr str name: (optional) Name of the author. + :attr List[CategoriesRelevantText] relevant_text: (optional) An array of + relevant text from the source that contributed to the categorization. The sorted + array begins with the phrase that contributed most significantly to the result, + followed by phrases that were less and less impactful. """ - def __init__(self, *, name: str = None) -> None: + def __init__(self, + *, + relevant_text: List['CategoriesRelevantText'] = None) -> None: """ - Initialize a Author object. + Initialize a CategoriesResultExplanation object. - :param str name: (optional) Name of the author. + :param List[CategoriesRelevantText] relevant_text: (optional) An array of + relevant text from the source that contributed to the categorization. The + sorted array begins with the phrase that contributed most significantly to + the result, followed by phrases that were less and less impactful. """ - self.name = name + self.relevant_text = relevant_text @classmethod - def from_dict(cls, _dict: Dict) -> 'Author': - """Initialize a Author object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CategoriesResultExplanation': + """Initialize a CategoriesResultExplanation object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if 'relevant_text' in _dict: + args['relevant_text'] = [ + CategoriesRelevantText.from_dict(x) + for x in _dict.get('relevant_text') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Author object from a json dictionary.""" + """Initialize a CategoriesResultExplanation 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, 'name') and self.name is not None: - _dict['name'] = self.name + if hasattr(self, 'relevant_text') and self.relevant_text is not None: + _dict['relevant_text'] = [x.to_dict() for x in self.relevant_text] return _dict def _to_dict(self): @@ -575,90 +2026,191 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Author object.""" + """Return a `str` version of this CategoriesResultExplanation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Author') -> bool: + def __eq__(self, other: 'CategoriesResultExplanation') -> 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: 'Author') -> bool: + def __ne__(self, other: 'CategoriesResultExplanation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class CategoriesOptions(): +class ClassificationsModel(): """ - Returns a five-level taxonomy of the content. The top three categories are returned. - Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, - Portuguese, Spanish. - - :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) Enter a [custom - model](https://cloud.ibm.com/docs/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. + Classifications model. + + :attr str name: (optional) An optional name for the model. + :attr dict user_metadata: (optional) An optional map of metadata key-value pairs + to store with this model. + :attr str language: The 2-letter language code of this model. + :attr str description: (optional) An optional description of the model. + :attr str model_version: (optional) An optional version string. + :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + that deployed this model to Natural Language Understanding. + :attr str version_description: (optional) The description of the version. + :attr List[str] features: (optional) The service features that are supported by + the custom model. + :attr str status: When the status is `available`, the model is ready to use. + :attr str model_id: Unique model ID. + :attr datetime created: dateTime indicating when the model was created. + :attr List[Notice] notices: (optional) + :attr datetime last_trained: (optional) dateTime of last successful model + training. + :attr datetime last_deployed: (optional) dateTime of last successful model + deployment. """ def __init__(self, + language: str, + status: str, + model_id: str, + created: datetime, *, - explanation: bool = None, - limit: int = None, - model: str = None) -> None: + name: str = None, + user_metadata: dict = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + features: List[str] = None, + notices: List['Notice'] = None, + last_trained: datetime = None, + last_deployed: datetime = None) -> None: """ - Initialize a CategoriesOptions object. - - :param bool explanation: (optional) Set this to `true` to return - explanations for each categorization. **This is available only for English - categories.**. - :param int limit: (optional) Maximum number of categories to return. - :param str model: (optional) Enter a [custom - model](https://cloud.ibm.com/docs/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. + Initialize a ClassificationsModel object. + + :param str language: The 2-letter language code of this model. + :param str status: When the status is `available`, the model is ready to + use. + :param str model_id: Unique model ID. + :param datetime created: dateTime indicating when the model was created. + :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio + workspace that deployed this model to Natural Language Understanding. + :param str version_description: (optional) The description of the version. + :param List[str] features: (optional) The service features that are + supported by the custom model. + :param List[Notice] notices: (optional) + :param datetime last_trained: (optional) dateTime of last successful model + training. + :param datetime last_deployed: (optional) dateTime of last successful model + deployment. """ - self.explanation = explanation - self.limit = limit - self.model = model + self.name = name + self.user_metadata = user_metadata + self.language = language + self.description = description + self.model_version = model_version + self.workspace_id = workspace_id + self.version_description = version_description + self.features = features + self.status = status + self.model_id = model_id + self.created = created + self.notices = notices + self.last_trained = last_trained + self.last_deployed = last_deployed @classmethod - def from_dict(cls, _dict: Dict) -> 'CategoriesOptions': - """Initialize a CategoriesOptions object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ClassificationsModel': + """Initialize a ClassificationsModel object from a json dictionary.""" args = {} - if 'explanation' in _dict: - args['explanation'] = _dict.get('explanation') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'model' in _dict: - args['model'] = _dict.get('model') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'user_metadata' in _dict: + args['user_metadata'] = _dict.get('user_metadata') + if 'language' in _dict: + args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in ClassificationsModel JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'model_version' in _dict: + args['model_version'] = _dict.get('model_version') + if 'workspace_id' in _dict: + args['workspace_id'] = _dict.get('workspace_id') + if 'version_description' in _dict: + args['version_description'] = _dict.get('version_description') + if 'features' in _dict: + args['features'] = _dict.get('features') + if 'status' in _dict: + args['status'] = _dict.get('status') + else: + raise ValueError( + 'Required property \'status\' not present in ClassificationsModel JSON' + ) + if 'model_id' in _dict: + args['model_id'] = _dict.get('model_id') + else: + raise ValueError( + 'Required property \'model_id\' not present in ClassificationsModel JSON' + ) + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + else: + raise ValueError( + 'Required property \'created\' not present in ClassificationsModel JSON' + ) + if 'notices' in _dict: + args['notices'] = [ + Notice.from_dict(x) for x in _dict.get('notices') + ] + if 'last_trained' in _dict: + args['last_trained'] = string_to_datetime(_dict.get('last_trained')) + if 'last_deployed' in _dict: + args['last_deployed'] = string_to_datetime( + _dict.get('last_deployed')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CategoriesOptions object from a json dictionary.""" + """Initialize a ClassificationsModel 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, 'explanation') and self.explanation is not None: - _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 + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'user_metadata') and self.user_metadata is not None: + _dict['user_metadata'] = self.user_metadata + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'model_version') and self.model_version is not None: + _dict['model_version'] = self.model_version + if hasattr(self, 'workspace_id') and self.workspace_id is not None: + _dict['workspace_id'] = self.workspace_id + if hasattr( + self, + 'version_description') and self.version_description is not None: + _dict['version_description'] = self.version_description + if hasattr(self, 'features') and self.features is not None: + _dict['features'] = self.features + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + if hasattr(self, 'model_id') and self.model_id is not None: + _dict['model_id'] = self.model_id + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'notices') and self.notices is not None: + _dict['notices'] = [x.to_dict() for x in self.notices] + if hasattr(self, 'last_trained') and self.last_trained is not None: + _dict['last_trained'] = datetime_to_string(self.last_trained) + if hasattr(self, 'last_deployed') and self.last_deployed is not None: + _dict['last_deployed'] = datetime_to_string(self.last_deployed) return _dict def _to_dict(self): @@ -666,55 +2218,67 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CategoriesOptions object.""" + """Return a `str` version of this ClassificationsModel object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CategoriesOptions') -> bool: + def __eq__(self, other: 'ClassificationsModel') -> 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: 'CategoriesOptions') -> bool: + def __ne__(self, other: 'ClassificationsModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + When the status is `available`, the model is ready to use. + """ + STARTING = 'starting' + TRAINING = 'training' + DEPLOYING = 'deploying' + AVAILABLE = 'available' + ERROR = 'error' + DELETED = 'deleted' + -class CategoriesRelevantText(): +class ClassificationsModelList(): """ - Relevant text that contributed to the categorization. + List of classifications models. - :attr str text: (optional) Text from the analyzed source that supports the - categorization. + :attr List[ClassificationsModel] models: (optional) The classifications models. """ - def __init__(self, *, text: str = None) -> None: + def __init__(self, *, models: List['ClassificationsModel'] = None) -> None: """ - Initialize a CategoriesRelevantText object. + Initialize a ClassificationsModelList object. - :param str text: (optional) Text from the analyzed source that supports the - categorization. + :param List[ClassificationsModel] models: (optional) The classifications + models. """ - self.text = text + self.models = models @classmethod - def from_dict(cls, _dict: Dict) -> 'CategoriesRelevantText': - """Initialize a CategoriesRelevantText object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ClassificationsModelList': + """Initialize a ClassificationsModelList object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if 'models' in _dict: + args['models'] = [ + ClassificationsModel.from_dict(x) for x in _dict.get('models') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CategoriesRelevantText object from a json dictionary.""" + """Initialize a ClassificationsModelList 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, 'text') and self.text is not None: - _dict['text'] = self.text + if hasattr(self, 'models') and self.models is not None: + _dict['models'] = [x.to_dict() for x in self.models] return _dict def _to_dict(self): @@ -722,81 +2286,58 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CategoriesRelevantText object.""" + """Return a `str` version of this ClassificationsModelList object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CategoriesRelevantText') -> bool: + def __eq__(self, other: 'ClassificationsModelList') -> 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: 'CategoriesRelevantText') -> bool: + def __ne__(self, other: 'ClassificationsModelList') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class CategoriesResult(): +class ClassificationsOptions(): """ - A categorization of the analyzed text. + Returns text classifications for the content. + Supported languages: English only. - :attr str label: (optional) The path to the category through the 5-level - taxonomy hierarchy. For more information about the categories, see [Categories - hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). - :attr float score: (optional) Confidence score for the category classification. - Higher values indicate greater confidence. - :attr CategoriesResultExplanation explanation: (optional) Information that helps - to explain what contributed to the categories result. + :attr str model: (optional) (Beta) Enter a [custom + model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) + ID of the classification model to be used. """ - def __init__(self, - *, - label: str = None, - score: float = None, - explanation: 'CategoriesResultExplanation' = None) -> None: + def __init__(self, *, model: str = None) -> None: """ - Initialize a CategoriesResult object. + Initialize a ClassificationsOptions object. - :param str label: (optional) The path to the category through the 5-level - taxonomy hierarchy. For more information about the categories, see - [Categories - hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). - :param float score: (optional) Confidence score for the category - classification. Higher values indicate greater confidence. - :param CategoriesResultExplanation explanation: (optional) Information that - helps to explain what contributed to the categories result. + :param str model: (optional) (Beta) Enter a [custom + model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) + ID of the classification model to be used. """ - self.label = label - self.score = score - self.explanation = explanation + self.model = model @classmethod - def from_dict(cls, _dict: Dict) -> 'CategoriesResult': - """Initialize a CategoriesResult object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ClassificationsOptions': + """Initialize a ClassificationsOptions object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'score' in _dict: - args['score'] = _dict.get('score') - if 'explanation' in _dict: - args['explanation'] = CategoriesResultExplanation.from_dict( - _dict.get('explanation')) + if 'model' in _dict: + args['model'] = _dict.get('model') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CategoriesResult object from a json dictionary.""" + """Initialize a ClassificationsOptions 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, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score - if hasattr(self, 'explanation') and self.explanation is not None: - _dict['explanation'] = self.explanation.to_dict() + if hasattr(self, 'model') and self.model is not None: + _dict['model'] = self.model return _dict def _to_dict(self): @@ -804,64 +2345,65 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CategoriesResult object.""" + """Return a `str` version of this ClassificationsOptions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CategoriesResult') -> bool: + def __eq__(self, other: 'ClassificationsOptions') -> 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: 'CategoriesResult') -> bool: + def __ne__(self, other: 'ClassificationsOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class CategoriesResultExplanation(): +class ClassificationsResult(): """ - Information that helps to explain what contributed to the categories result. + A classification of the analyzed text. - :attr List[CategoriesRelevantText] relevant_text: (optional) An array of - relevant text from the source that contributed to the categorization. The sorted - array begins with the phrase that contributed most significantly to the result, - followed by phrases that were less and less impactful. + :attr str class_name: (optional) Classification assigned to the text. + :attr float confidence: (optional) Confidence score for the classification. + Higher values indicate greater confidence. """ def __init__(self, *, - relevant_text: List['CategoriesRelevantText'] = None) -> None: + class_name: str = None, + confidence: float = None) -> None: """ - Initialize a CategoriesResultExplanation object. + Initialize a ClassificationsResult object. - :param List[CategoriesRelevantText] relevant_text: (optional) An array of - relevant text from the source that contributed to the categorization. The - sorted array begins with the phrase that contributed most significantly to - the result, followed by phrases that were less and less impactful. + :param str class_name: (optional) Classification assigned to the text. + :param float confidence: (optional) Confidence score for the + classification. Higher values indicate greater confidence. """ - self.relevant_text = relevant_text + self.class_name = class_name + self.confidence = confidence @classmethod - def from_dict(cls, _dict: Dict) -> 'CategoriesResultExplanation': - """Initialize a CategoriesResultExplanation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ClassificationsResult': + """Initialize a ClassificationsResult object from a json dictionary.""" args = {} - if 'relevant_text' in _dict: - args['relevant_text'] = [ - CategoriesRelevantText.from_dict(x) - for x in _dict.get('relevant_text') - ] + if 'class_name' in _dict: + args['class_name'] = _dict.get('class_name') + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CategoriesResultExplanation object from a json dictionary.""" + """Initialize a ClassificationsResult 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, 'relevant_text') and self.relevant_text is not None: - _dict['relevant_text'] = [x.to_dict() for x in self.relevant_text] + if hasattr(self, 'class_name') and self.class_name is not None: + _dict['class_name'] = self.class_name + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence return _dict def _to_dict(self): @@ -869,16 +2411,16 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CategoriesResultExplanation object.""" + """Return a `str` version of this ClassificationsResult object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CategoriesResultExplanation') -> bool: + def __eq__(self, other: 'ClassificationsResult') -> 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: 'CategoriesResultExplanation') -> bool: + def __ne__(self, other: 'ClassificationsResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -1896,6 +3438,13 @@ class Features(): """ Analysis features and options. + :attr CategoriesOptions categories: (optional) Returns a five-level taxonomy of + the content. The top three categories are returned. + Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, + Portuguese, Spanish. + :attr ClassificationsOptions classifications: (optional) Returns text + classifications for the content. + Supported languages: English only. :attr ConceptsOptions concepts: (optional) Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. @@ -1917,9 +3466,9 @@ class Features(): content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :attr object metadata: (optional) Returns information from the document, - including author name, title, RSS/ATOM feeds, prominent page image, and - publication date. Supports URL and HTML input types only. + :attr MetadataOptions metadata: (optional) Returns information from the + document, including author name, title, RSS/ATOM feeds, prominent page image, + and publication date. Supports URL and HTML input types only. :attr RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". For @@ -1937,29 +3486,37 @@ class Features(): `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :attr CategoriesOptions categories: (optional) Returns a five-level taxonomy of - the content. The top three categories are returned. - Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, - Portuguese, Spanish. + :attr SummarizationOptions summarization: (optional) (Experimental) Returns a + summary of content. + Supported languages: English only. :attr SyntaxOptions syntax: (optional) Returns tokens and sentences from the input text. """ def __init__(self, *, + categories: 'CategoriesOptions' = None, + classifications: 'ClassificationsOptions' = None, concepts: 'ConceptsOptions' = None, emotion: 'EmotionOptions' = None, entities: 'EntitiesOptions' = None, keywords: 'KeywordsOptions' = None, - metadata: object = None, + metadata: 'MetadataOptions' = None, relations: 'RelationsOptions' = None, semantic_roles: 'SemanticRolesOptions' = None, sentiment: 'SentimentOptions' = None, - categories: 'CategoriesOptions' = None, + summarization: 'SummarizationOptions' = None, syntax: 'SyntaxOptions' = None) -> None: """ Initialize a Features object. + :param CategoriesOptions categories: (optional) Returns a five-level + taxonomy of the content. The top three categories are returned. + Supported languages: Arabic, English, French, German, Italian, Japanese, + Korean, Portuguese, Spanish. + :param ClassificationsOptions classifications: (optional) Returns text + classifications for the content. + Supported languages: English only. :param ConceptsOptions concepts: (optional) Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. @@ -1982,9 +3539,9 @@ def __init__(self, the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :param object metadata: (optional) Returns information from the document, - including author name, title, RSS/ATOM feeds, prominent page image, and - publication date. Supports URL and HTML input types only. + :param MetadataOptions metadata: (optional) Returns information from the + document, including author name, title, RSS/ATOM feeds, prominent page + image, and publication date. Supports URL and HTML input types only. :param RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert @@ -2002,13 +3559,14 @@ def __init__(self, and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :param CategoriesOptions categories: (optional) Returns a five-level - taxonomy of the content. The top three categories are returned. - Supported languages: Arabic, English, French, German, Italian, Japanese, - Korean, Portuguese, Spanish. + :param SummarizationOptions summarization: (optional) (Experimental) + Returns a summary of content. + Supported languages: English only. :param SyntaxOptions syntax: (optional) Returns tokens and sentences from the input text. """ + self.categories = categories + self.classifications = classifications self.concepts = concepts self.emotion = emotion self.entities = entities @@ -2017,13 +3575,19 @@ def __init__(self, self.relations = relations self.semantic_roles = semantic_roles self.sentiment = sentiment - self.categories = categories + self.summarization = summarization self.syntax = syntax @classmethod def from_dict(cls, _dict: Dict) -> 'Features': """Initialize a Features object from a json dictionary.""" args = {} + if 'categories' in _dict: + args['categories'] = CategoriesOptions.from_dict( + _dict.get('categories')) + if 'classifications' in _dict: + args['classifications'] = ClassificationsOptions.from_dict( + _dict.get('classifications')) if 'concepts' in _dict: args['concepts'] = ConceptsOptions.from_dict(_dict.get('concepts')) if 'emotion' in _dict: @@ -2033,7 +3597,7 @@ def from_dict(cls, _dict: Dict) -> 'Features': if 'keywords' in _dict: args['keywords'] = KeywordsOptions.from_dict(_dict.get('keywords')) if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') + args['metadata'] = MetadataOptions.from_dict(_dict.get('metadata')) if 'relations' in _dict: args['relations'] = RelationsOptions.from_dict( _dict.get('relations')) @@ -2043,9 +3607,9 @@ def from_dict(cls, _dict: Dict) -> 'Features': if 'sentiment' in _dict: args['sentiment'] = SentimentOptions.from_dict( _dict.get('sentiment')) - if 'categories' in _dict: - args['categories'] = CategoriesOptions.from_dict( - _dict.get('categories')) + if 'summarization' in _dict: + args['summarization'] = SummarizationOptions.from_dict( + _dict.get('summarization')) if 'syntax' in _dict: args['syntax'] = SyntaxOptions.from_dict(_dict.get('syntax')) return cls(**args) @@ -2058,6 +3622,11 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} + if hasattr(self, 'categories') and self.categories is not None: + _dict['categories'] = self.categories.to_dict() + if hasattr(self, + 'classifications') and self.classifications is not None: + _dict['classifications'] = self.classifications.to_dict() if hasattr(self, 'concepts') and self.concepts is not None: _dict['concepts'] = self.concepts.to_dict() if hasattr(self, 'emotion') and self.emotion is not None: @@ -2067,15 +3636,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'keywords') and self.keywords is not None: _dict['keywords'] = self.keywords.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata + _dict['metadata'] = self.metadata.to_dict() if hasattr(self, 'relations') and self.relations is not None: _dict['relations'] = self.relations.to_dict() if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: _dict['semantic_roles'] = self.semantic_roles.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: _dict['sentiment'] = self.sentiment.to_dict() - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = self.categories.to_dict() + if hasattr(self, 'summarization') and self.summarization is not None: + _dict['summarization'] = self.summarization.to_dict() if hasattr(self, 'syntax') and self.syntax is not None: _dict['syntax'] = self.syntax.to_dict() return _dict @@ -2384,22 +3953,247 @@ def from_dict(cls, _dict: Dict) -> 'KeywordsResult': @classmethod def _from_dict(cls, _dict): - """Initialize a KeywordsResult object from a json dictionary.""" + """Initialize a KeywordsResult 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, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'relevance') and self.relevance is not None: + _dict['relevance'] = self.relevance + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'emotion') and self.emotion is not None: + _dict['emotion'] = self.emotion.to_dict() + if hasattr(self, 'sentiment') and self.sentiment is not None: + _dict['sentiment'] = self.sentiment.to_dict() + 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 KeywordsResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'KeywordsResult') -> 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: 'KeywordsResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ListCategoriesModelsResponse(): + """ + ListCategoriesModelsResponse. + + :attr List[CategoriesModelList] models: (optional) + """ + + def __init__(self, *, models: List['CategoriesModelList'] = None) -> None: + """ + Initialize a ListCategoriesModelsResponse object. + + :param List[CategoriesModelList] models: (optional) + """ + self.models = models + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListCategoriesModelsResponse': + """Initialize a ListCategoriesModelsResponse object from a json dictionary.""" + args = {} + if 'models' in _dict: + args['models'] = [ + CategoriesModelList.from_dict(x) for x in _dict.get('models') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListCategoriesModelsResponse 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, 'models') and self.models is not None: + _dict['models'] = [x.to_dict() for x in self.models] + 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 ListCategoriesModelsResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListCategoriesModelsResponse') -> 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: 'ListCategoriesModelsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ListClassificationsModelsResponse(): + """ + ListClassificationsModelsResponse. + + :attr List[ClassificationsModelList] models: (optional) + """ + + def __init__(self, + *, + models: List['ClassificationsModelList'] = None) -> None: + """ + Initialize a ListClassificationsModelsResponse object. + + :param List[ClassificationsModelList] models: (optional) + """ + self.models = models + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListClassificationsModelsResponse': + """Initialize a ListClassificationsModelsResponse object from a json dictionary.""" + args = {} + if 'models' in _dict: + args['models'] = [ + ClassificationsModelList.from_dict(x) + for x in _dict.get('models') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListClassificationsModelsResponse 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, 'models') and self.models is not None: + _dict['models'] = [x.to_dict() for x in self.models] + 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 ListClassificationsModelsResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListClassificationsModelsResponse') -> 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: 'ListClassificationsModelsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ListModelsResults(): + """ + Custom models that are available for entities and relations. + + :attr List[Model] models: (optional) An array of available models. + """ + + def __init__(self, *, models: List['Model'] = None) -> None: + """ + Initialize a ListModelsResults object. + + :param List[Model] models: (optional) An array of available models. + """ + self.models = models + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListModelsResults': + """Initialize a ListModelsResults object from a json dictionary.""" + args = {} + if 'models' in _dict: + args['models'] = [Model.from_dict(x) for x in _dict.get('models')] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListModelsResults 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, 'models') and self.models is not None: + _dict['models'] = [x.to_dict() for x in self.models] + 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 ListModelsResults object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListModelsResults') -> 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: 'ListModelsResults') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ListSentimentModelsResponse(): + """ + ListSentimentModelsResponse. + + :attr List[SentimentModel] models: (optional) + """ + + def __init__(self, *, models: List['SentimentModel'] = None) -> None: + """ + Initialize a ListSentimentModelsResponse object. + + :param List[SentimentModel] models: (optional) + """ + self.models = models + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListSentimentModelsResponse': + """Initialize a ListSentimentModelsResponse object from a json dictionary.""" + args = {} + if 'models' in _dict: + args['models'] = [ + SentimentModel.from_dict(x) for x in _dict.get('models') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListSentimentModelsResponse 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, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'relevance') and self.relevance is not None: - _dict['relevance'] = self.relevance - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() - if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if hasattr(self, 'models') and self.models is not None: + _dict['models'] = [x.to_dict() for x in self.models] return _dict def _to_dict(self): @@ -2407,70 +4201,62 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this KeywordsResult object.""" + """Return a `str` version of this ListSentimentModelsResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'KeywordsResult') -> bool: + def __eq__(self, other: 'ListSentimentModelsResponse') -> 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: 'KeywordsResult') -> bool: + def __ne__(self, other: 'ListSentimentModelsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ListModelsResults(): +class MetadataOptions(): """ - Custom models that are available for entities and relations. + Returns information from the document, including author name, title, RSS/ATOM feeds, + prominent page image, and publication date. Supports URL and HTML input types only. - :attr List[Model] models: (optional) An array of available models. """ - def __init__(self, *, models: List['Model'] = None) -> None: + def __init__(self) -> None: """ - Initialize a ListModelsResults object. + Initialize a MetadataOptions object. - :param List[Model] models: (optional) An array of available models. """ - self.models = models @classmethod - def from_dict(cls, _dict: Dict) -> 'ListModelsResults': - """Initialize a ListModelsResults object from a json dictionary.""" - args = {} - if 'models' in _dict: - args['models'] = [Model.from_dict(x) for x in _dict.get('models')] - return cls(**args) + def from_dict(cls, _dict: Dict) -> 'MetadataOptions': + """Initialize a MetadataOptions object from a json dictionary.""" + return cls(**_dict) @classmethod def _from_dict(cls, _dict): - """Initialize a ListModelsResults object from a json dictionary.""" + """Initialize a MetadataOptions 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, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] - return _dict + return vars(self) 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 ListModelsResults object.""" + """Return a `str` version of this MetadataOptions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ListModelsResults') -> bool: + def __eq__(self, other: 'MetadataOptions') -> 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: 'ListModelsResults') -> bool: + def __ne__(self, other: 'MetadataOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2620,6 +4406,60 @@ class StatusEnum(str, Enum): DELETED = 'deleted' +class Notice(): + """ + A list of messages describing model training issues when model status is `error`. + + :attr str message: (optional) Describes deficiencies or inconsistencies in + training data. + """ + + def __init__(self, *, message: str = None) -> None: + """ + Initialize a Notice object. + + """ + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Notice': + """Initialize a Notice object from a json dictionary.""" + args = {} + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Notice 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, 'message') and getattr(self, 'message') is not None: + _dict['message'] = getattr(self, 'message') + 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 Notice object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Notice') -> 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: 'Notice') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RelationArgument(): """ RelationArgument. @@ -3535,6 +5375,196 @@ def __ne__(self, other: 'SentenceResult') -> bool: return not self == other +class SentimentModel(): + """ + SentimentModel. + + :attr List[str] features: (optional) The service features that are supported by + the custom model. + :attr str status: (optional) When the status is `available`, the model is ready + to use. + :attr str model_id: (optional) Unique model ID. + :attr datetime created: (optional) dateTime indicating when the model was + created. + :attr datetime last_trained: (optional) dateTime of last successful model + training. + :attr datetime last_deployed: (optional) dateTime of last successful model + deployment. + :attr str name: (optional) A name for the model. + :attr dict user_metadata: (optional) An optional map of metadata key-value pairs + to store with this model. + :attr str language: (optional) The 2-letter language code of this model. + :attr str description: (optional) An optional description of the model. + :attr str model_version: (optional) An optional version string. + :attr List[Notice] notices: (optional) + :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + that deployed this model to Natural Language Understanding. + :attr str version_description: (optional) The description of the version. + """ + + def __init__(self, + *, + features: List[str] = None, + status: str = None, + model_id: str = None, + created: datetime = None, + last_trained: datetime = None, + last_deployed: datetime = None, + name: str = None, + user_metadata: dict = None, + language: str = None, + description: str = None, + model_version: str = None, + notices: List['Notice'] = None, + workspace_id: str = None, + version_description: str = None) -> None: + """ + Initialize a SentimentModel object. + + :param List[str] features: (optional) The service features that are + supported by the custom model. + :param str status: (optional) When the status is `available`, the model is + ready to use. + :param str model_id: (optional) Unique model ID. + :param datetime created: (optional) dateTime indicating when the model was + created. + :param datetime last_trained: (optional) dateTime of last successful model + training. + :param datetime last_deployed: (optional) dateTime of last successful model + deployment. + :param str name: (optional) A name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. + :param str language: (optional) The 2-letter language code of this model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param List[Notice] notices: (optional) + :param str workspace_id: (optional) ID of the Watson Knowledge Studio + workspace that deployed this model to Natural Language Understanding. + :param str version_description: (optional) The description of the version. + """ + self.features = features + self.status = status + self.model_id = model_id + self.created = created + self.last_trained = last_trained + self.last_deployed = last_deployed + self.name = name + self.user_metadata = user_metadata + self.language = language + self.description = description + self.model_version = model_version + self.notices = notices + self.workspace_id = workspace_id + self.version_description = version_description + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SentimentModel': + """Initialize a SentimentModel object from a json dictionary.""" + args = {} + if 'features' in _dict: + args['features'] = _dict.get('features') + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'model_id' in _dict: + args['model_id'] = _dict.get('model_id') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'last_trained' in _dict: + args['last_trained'] = string_to_datetime(_dict.get('last_trained')) + if 'last_deployed' in _dict: + args['last_deployed'] = string_to_datetime( + _dict.get('last_deployed')) + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'user_metadata' in _dict: + args['user_metadata'] = _dict.get('user_metadata') + if 'language' in _dict: + args['language'] = _dict.get('language') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'model_version' in _dict: + args['model_version'] = _dict.get('model_version') + if 'notices' in _dict: + args['notices'] = [ + Notice.from_dict(x) for x in _dict.get('notices') + ] + if 'workspace_id' in _dict: + args['workspace_id'] = _dict.get('workspace_id') + if 'version_description' in _dict: + args['version_description'] = _dict.get('version_description') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SentimentModel 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, 'features') and self.features is not None: + _dict['features'] = self.features + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + if hasattr(self, 'model_id') and self.model_id is not None: + _dict['model_id'] = self.model_id + if hasattr(self, 'created') and self.created is not None: + _dict['created'] = datetime_to_string(self.created) + if hasattr(self, 'last_trained') and self.last_trained is not None: + _dict['last_trained'] = datetime_to_string(self.last_trained) + if hasattr(self, 'last_deployed') and self.last_deployed is not None: + _dict['last_deployed'] = datetime_to_string(self.last_deployed) + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'user_metadata') and self.user_metadata is not None: + _dict['user_metadata'] = self.user_metadata + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'model_version') and self.model_version is not None: + _dict['model_version'] = self.model_version + if hasattr(self, 'notices') and self.notices is not None: + _dict['notices'] = [x.to_dict() for x in self.notices] + if hasattr(self, 'workspace_id') and self.workspace_id is not None: + _dict['workspace_id'] = self.workspace_id + if hasattr( + self, + 'version_description') and self.version_description is not None: + _dict['version_description'] = self.version_description + 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 SentimentModel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SentimentModel') -> 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: 'SentimentModel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + When the status is `available`, the model is ready to use. + """ + STARTING = 'starting' + TRAINING = 'training' + DEPLOYING = 'deploying' + AVAILABLE = 'available' + ERROR = 'error' + DELETED = 'deleted' + + class SentimentOptions(): """ Analyzes the general sentiment of your content or the sentiment toward specific target @@ -3547,12 +5577,18 @@ class SentimentOptions(): sentiment results. :attr List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. + :attr str model: (optional) (Beta) Enter a [custom + model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the standard sentiment model for all sentiment analysis + operations in the request, including targeted sentiment for entities and + keywords. """ def __init__(self, *, document: bool = None, - targets: List[str] = None) -> None: + targets: List[str] = None, + model: str = None) -> None: """ Initialize a SentimentOptions object. @@ -3560,9 +5596,15 @@ def __init__(self, sentiment results. :param List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. + :param str model: (optional) (Beta) Enter a [custom + model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) + ID to override the standard sentiment model for all sentiment analysis + operations in the request, including targeted sentiment for entities and + keywords. """ self.document = document self.targets = targets + self.model = model @classmethod def from_dict(cls, _dict: Dict) -> 'SentimentOptions': @@ -3572,6 +5614,8 @@ def from_dict(cls, _dict: Dict) -> 'SentimentOptions': args['document'] = _dict.get('document') if 'targets' in _dict: args['targets'] = _dict.get('targets') + if 'model' in _dict: + args['model'] = _dict.get('model') return cls(**args) @classmethod @@ -3586,6 +5630,8 @@ def to_dict(self) -> Dict: _dict['document'] = self.document if hasattr(self, 'targets') and self.targets is not None: _dict['targets'] = self.targets + if hasattr(self, 'model') and self.model is not None: + _dict['model'] = self.model return _dict def _to_dict(self): @@ -3679,6 +5725,61 @@ def __ne__(self, other: 'SentimentResult') -> bool: return not self == other +class SummarizationOptions(): + """ + (Experimental) Returns a summary of content. + Supported languages: English only. + + :attr int limit: (optional) Maximum number of summary sentences to return. + """ + + def __init__(self, *, limit: int = None) -> None: + """ + Initialize a SummarizationOptions object. + + :param int limit: (optional) Maximum number of summary sentences to return. + """ + self.limit = limit + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SummarizationOptions': + """Initialize a SummarizationOptions object from a json dictionary.""" + args = {} + if 'limit' in _dict: + args['limit'] = _dict.get('limit') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SummarizationOptions 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, 'limit') and self.limit is not None: + _dict['limit'] = self.limit + 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 SummarizationOptions object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SummarizationOptions') -> 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: 'SummarizationOptions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class SyntaxOptions(): """ Returns tokens and sentences from the input text. diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 60a362251..c3394421b 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2020. +# (C) Copyright IBM Corp. 2019, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -19,24 +19,27 @@ from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect +import io import json import pytest import re import requests import responses +import tempfile import urllib from ibm_watson.natural_language_understanding_v1 import * version = 'testString' -service = NaturalLanguageUnderstandingV1( +_service = NaturalLanguageUnderstandingV1( authenticator=NoAuthAuthenticator(), version=version ) -base_url = 'https://api.us-south.natural-language-understanding.watson.cloud.ibm.com' -service.set_service_url(base_url) +_base_url = 'https://api.us-south.natural-language-understanding.watson.cloud.ibm.com' +_service.set_service_url(_base_url) ############################################################################## # Start of Service: Analyze @@ -63,14 +66,24 @@ def test_analyze_all_params(self): analyze() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/analyze') - mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' + url = self.preprocess_url(_base_url + '/v1/analyze') + mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "classifications": [{"class_name": "class_name", "confidence": 10}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a CategoriesOptions model + categories_options_model = {} + categories_options_model['explanation'] = True + categories_options_model['limit'] = 10 + categories_options_model['model'] = 'testString' + + # Construct a dict representation of a ClassificationsOptions model + classifications_options_model = {} + classifications_options_model['model'] = 'testString' + # Construct a dict representation of a ConceptsOptions model concepts_options_model = {} concepts_options_model['limit'] = 50 @@ -94,6 +107,9 @@ def test_analyze_all_params(self): keywords_options_model['sentiment'] = True keywords_options_model['emotion'] = True + # Construct a dict representation of a MetadataOptions model + metadata_options_model = {} + # Construct a dict representation of a RelationsOptions model relations_options_model = {} relations_options_model['model'] = 'testString' @@ -108,12 +124,11 @@ def test_analyze_all_params(self): sentiment_options_model = {} sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] + sentiment_options_model['model'] = 'testString' - # Construct a dict representation of a CategoriesOptions model - categories_options_model = {} - categories_options_model['explanation'] = True - categories_options_model['limit'] = 10 - categories_options_model['model'] = 'testString' + # Construct a dict representation of a SummarizationOptions model + summarization_options_model = {} + summarization_options_model['limit'] = 10 # Construct a dict representation of a SyntaxOptionsTokens model syntax_options_tokens_model = {} @@ -127,15 +142,17 @@ def test_analyze_all_params(self): # Construct a dict representation of a Features model features_model = {} + features_model['categories'] = categories_options_model + features_model['classifications'] = classifications_options_model features_model['concepts'] = concepts_options_model features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = { 'foo': 'bar' } + features_model['metadata'] = metadata_options_model features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model - features_model['categories'] = categories_options_model + features_model['summarization'] = summarization_options_model features_model['syntax'] = syntax_options_model # Set up parameter values @@ -151,7 +168,7 @@ def test_analyze_all_params(self): limit_text_characters = 38 # Invoke method - response = service.analyze( + response = _service.analyze( features, text=text, html=html, @@ -188,14 +205,24 @@ def test_analyze_value_error(self): test_analyze_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/analyze') - mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' + url = self.preprocess_url(_base_url + '/v1/analyze') + mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "classifications": [{"class_name": "class_name", "confidence": 10}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a CategoriesOptions model + categories_options_model = {} + categories_options_model['explanation'] = True + categories_options_model['limit'] = 10 + categories_options_model['model'] = 'testString' + + # Construct a dict representation of a ClassificationsOptions model + classifications_options_model = {} + classifications_options_model['model'] = 'testString' + # Construct a dict representation of a ConceptsOptions model concepts_options_model = {} concepts_options_model['limit'] = 50 @@ -219,6 +246,9 @@ def test_analyze_value_error(self): keywords_options_model['sentiment'] = True keywords_options_model['emotion'] = True + # Construct a dict representation of a MetadataOptions model + metadata_options_model = {} + # Construct a dict representation of a RelationsOptions model relations_options_model = {} relations_options_model['model'] = 'testString' @@ -233,12 +263,11 @@ def test_analyze_value_error(self): sentiment_options_model = {} sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] + sentiment_options_model['model'] = 'testString' - # Construct a dict representation of a CategoriesOptions model - categories_options_model = {} - categories_options_model['explanation'] = True - categories_options_model['limit'] = 10 - categories_options_model['model'] = 'testString' + # Construct a dict representation of a SummarizationOptions model + summarization_options_model = {} + summarization_options_model['limit'] = 10 # Construct a dict representation of a SyntaxOptionsTokens model syntax_options_tokens_model = {} @@ -252,53 +281,1337 @@ def test_analyze_value_error(self): # Construct a dict representation of a Features model features_model = {} + features_model['categories'] = categories_options_model + features_model['classifications'] = classifications_options_model features_model['concepts'] = concepts_options_model features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = { 'foo': 'bar' } + features_model['metadata'] = metadata_options_model features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model - features_model['categories'] = categories_options_model + features_model['summarization'] = summarization_options_model features_model['syntax'] = syntax_options_model # Set up parameter values - features = features_model - text = 'testString' - html = 'testString' - url = 'testString' - clean = True - xpath = 'testString' - fallback_to_raw = True - return_analyzed_text = True - language = 'testString' - limit_text_characters = 38 + features = features_model + text = 'testString' + html = 'testString' + url = 'testString' + clean = True + xpath = 'testString' + fallback_to_raw = True + return_analyzed_text = True + language = 'testString' + limit_text_characters = 38 + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "features": features, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.analyze(**req_copy) + + + +# endregion +############################################################################## +# End of Service: Analyze +############################################################################## + +############################################################################## +# Start of Service: ManageModels +############################################################################## +# region + +class TestListModels(): + """ + Test Class for list_models + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_models_all_params(self): + """ + list_models() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models') + mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00.000Z"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = _service.list_models() + + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_list_models_value_error(self): + """ + test_list_models_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models') + mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00.000Z"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_models(**req_copy) + + + +class TestDeleteModel(): + """ + Test Class for delete_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_model_all_params(self): + """ + delete_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/testString') + mock_response = '{"deleted": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Invoke method + response = _service.delete_model( + model_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_delete_model_value_error(self): + """ + test_delete_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/testString') + mock_response = '{"deleted": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_model(**req_copy) + + + +# endregion +############################################################################## +# End of Service: ManageModels +############################################################################## + +############################################################################## +# Start of Service: ManageSentimentModels +############################################################################## +# region + +class TestCreateSentimentModel(): + """ + Test Class for create_sentiment_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_sentiment_model_all_params(self): + """ + create_sentiment_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment') + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + name = 'testString' + description = 'testString' + model_version = 'testString' + workspace_id = 'testString' + version_description = 'testString' + + # Invoke method + response = _service.create_sentiment_model( + language, + training_data, + name=name, + description=description, + model_version=model_version, + workspace_id=workspace_id, + version_description=version_description, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + + @responses.activate + def test_create_sentiment_model_required_params(self): + """ + test_create_sentiment_model_required_params() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment') + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = _service.create_sentiment_model( + language, + training_data, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + + @responses.activate + def test_create_sentiment_model_value_error(self): + """ + test_create_sentiment_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment') + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "language": language, + "training_data": training_data, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_sentiment_model(**req_copy) + + + +class TestListSentimentModels(): + """ + Test Class for list_sentiment_models + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_sentiment_models_all_params(self): + """ + list_sentiment_models() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment') + mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = _service.list_sentiment_models() + + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_list_sentiment_models_value_error(self): + """ + test_list_sentiment_models_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment') + mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_sentiment_models(**req_copy) + + + +class TestGetSentimentModel(): + """ + Test Class for get_sentiment_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_sentiment_model_all_params(self): + """ + get_sentiment_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Invoke method + response = _service.get_sentiment_model( + model_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_get_sentiment_model_value_error(self): + """ + test_get_sentiment_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_sentiment_model(**req_copy) + + + +class TestUpdateSentimentModel(): + """ + Test Class for update_sentiment_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_sentiment_model_all_params(self): + """ + update_sentiment_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + name = 'testString' + description = 'testString' + model_version = 'testString' + workspace_id = 'testString' + version_description = 'testString' + + # Invoke method + response = _service.update_sentiment_model( + model_id, + language, + training_data, + name=name, + description=description, + model_version=model_version, + workspace_id=workspace_id, + version_description=version_description, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_update_sentiment_model_required_params(self): + """ + test_update_sentiment_model_required_params() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = _service.update_sentiment_model( + model_id, + language, + training_data, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_update_sentiment_model_value_error(self): + """ + test_update_sentiment_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "model_id": model_id, + "language": language, + "training_data": training_data, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_sentiment_model(**req_copy) + + + +class TestDeleteSentimentModel(): + """ + Test Class for delete_sentiment_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_sentiment_model_all_params(self): + """ + delete_sentiment_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + mock_response = '{"deleted": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Invoke method + response = _service.delete_sentiment_model( + model_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_delete_sentiment_model_value_error(self): + """ + test_delete_sentiment_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + mock_response = '{"deleted": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_sentiment_model(**req_copy) + + + +# endregion +############################################################################## +# End of Service: ManageSentimentModels +############################################################################## + +############################################################################## +# Start of Service: ManageCategoriesModels +############################################################################## +# region + +class TestCreateCategoriesModel(): + """ + Test Class for create_categories_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_categories_model_all_params(self): + """ + create_categories_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'json' + name = 'testString' + description = 'testString' + model_version = 'testString' + workspace_id = 'testString' + version_description = 'testString' + + # Invoke method + response = _service.create_categories_model( + language, + training_data, + training_data_content_type=training_data_content_type, + name=name, + description=description, + model_version=model_version, + workspace_id=workspace_id, + version_description=version_description, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + + @responses.activate + def test_create_categories_model_required_params(self): + """ + test_create_categories_model_required_params() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = _service.create_categories_model( + language, + training_data, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + + @responses.activate + def test_create_categories_model_value_error(self): + """ + test_create_categories_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "language": language, + "training_data": training_data, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_categories_model(**req_copy) + + + +class TestListCategoriesModels(): + """ + Test Class for list_categories_models + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_categories_models_all_params(self): + """ + list_categories_models() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories') + mock_response = '{"models": [{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = _service.list_categories_models() + + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_list_categories_models_value_error(self): + """ + test_list_categories_models_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories') + mock_response = '{"models": [{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_categories_models(**req_copy) + + + +class TestGetCategoriesModel(): + """ + Test Class for get_categories_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_categories_model_all_params(self): + """ + get_categories_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Invoke method + response = _service.get_categories_model( + model_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_get_categories_model_value_error(self): + """ + test_get_categories_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_categories_model(**req_copy) + + + +class TestUpdateCategoriesModel(): + """ + Test Class for update_categories_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_update_categories_model_all_params(self): + """ + update_categories_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'json' + name = 'testString' + description = 'testString' + model_version = 'testString' + workspace_id = 'testString' + version_description = 'testString' + + # Invoke method + response = _service.update_categories_model( + model_id, + language, + training_data, + training_data_content_type=training_data_content_type, + name=name, + description=description, + model_version=model_version, + workspace_id=workspace_id, + version_description=version_description, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_update_categories_model_required_params(self): + """ + test_update_categories_model_required_params() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = _service.update_categories_model( + model_id, + language, + training_data, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_update_categories_model_value_error(self): + """ + test_update_categories_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "model_id": model_id, + "language": language, + "training_data": training_data, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_categories_model(**req_copy) + + + +class TestDeleteCategoriesModel(): + """ + Test Class for delete_categories_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_delete_categories_model_all_params(self): + """ + delete_categories_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + mock_response = '{"deleted": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Invoke method + response = _service.delete_categories_model( + model_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_delete_categories_model_value_error(self): + """ + test_delete_categories_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + mock_response = '{"deleted": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_categories_model(**req_copy) + + + +# endregion +############################################################################## +# End of Service: ManageCategoriesModels +############################################################################## + +############################################################################## +# Start of Service: ManageClassificationsModels +############################################################################## +# region + +class TestCreateClassificationsModel(): + """ + Test Class for create_classifications_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_create_classifications_model_all_params(self): + """ + create_classifications_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/classifications') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'json' + name = 'testString' + description = 'testString' + model_version = 'testString' + workspace_id = 'testString' + version_description = 'testString' + + # Invoke method + response = _service.create_classifications_model( + language, + training_data, + training_data_content_type=training_data_content_type, + name=name, + description=description, + model_version=model_version, + workspace_id=workspace_id, + version_description=version_description, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + + @responses.activate + def test_create_classifications_model_required_params(self): + """ + test_create_classifications_model_required_params() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/classifications') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = _service.create_classifications_model( + language, + training_data, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + + @responses.activate + def test_create_classifications_model_value_error(self): + """ + test_create_classifications_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/classifications') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "language": language, + "training_data": training_data, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_classifications_model(**req_copy) + + + +class TestListClassificationsModels(): + """ + Test Class for list_classifications_models + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_list_classifications_models_all_params(self): + """ + list_classifications_models() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/classifications') + mock_response = '{"models": [{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = _service.list_classifications_models() + + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_list_classifications_models_value_error(self): + """ + test_list_classifications_models_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/classifications') + mock_response = '{"models": [{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_classifications_models(**req_copy) + + + +class TestGetClassificationsModel(): + """ + Test Class for get_classifications_model + """ + + def preprocess_url(self, request_url: str): + """ + Preprocess the request URL to ensure the mock response will be found. + """ + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + @responses.activate + def test_get_classifications_model_all_params(self): + """ + get_classifications_model() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + + # Invoke method + response = _service.get_classifications_model( + model_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_get_classifications_model_value_error(self): + """ + test_get_classifications_model_value_error() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { - "features": features, + "model_id": model_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.analyze(**req_copy) - + _service.get_classifications_model(**req_copy) -# endregion -############################################################################## -# End of Service: Analyze -############################################################################## - -############################################################################## -# Start of Service: ManageModels -############################################################################## -# region -class TestListModels(): +class TestUpdateClassificationsModel(): """ - Test Class for list_models + Test Class for update_classifications_model """ def preprocess_url(self, request_url: str): @@ -311,22 +1624,75 @@ def preprocess_url(self, request_url: str): return re.compile(request_url.rstrip('/') + '/+') @responses.activate - def test_list_models_all_params(self): + def test_update_classifications_model_all_params(self): """ - list_models() + update_classifications_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/models') - mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00"}]}' - responses.add(responses.GET, + url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) + # Set up parameter values + model_id = 'testString' + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'json' + name = 'testString' + description = 'testString' + model_version = 'testString' + workspace_id = 'testString' + version_description = 'testString' + # Invoke method - response = service.list_models() + response = _service.update_classifications_model( + model_id, + language, + training_data, + training_data_content_type=training_data_content_type, + name=name, + description=description, + model_version=model_version, + workspace_id=workspace_id, + version_description=version_description, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + + @responses.activate + def test_update_classifications_model_required_params(self): + """ + test_update_classifications_model_required_params() + """ + # Set up mock + url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + model_id = 'testString' + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + # Invoke method + response = _service.update_classifications_model( + model_id, + language, + training_data, + headers={} + ) # Check for correct operation assert len(responses.calls) == 1 @@ -334,32 +1700,40 @@ def test_list_models_all_params(self): @responses.activate - def test_list_models_value_error(self): + def test_update_classifications_model_value_error(self): """ - test_list_models_value_error() + test_update_classifications_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/models') - mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00"}]}' - responses.add(responses.GET, + url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.PUT, url, body=mock_response, content_type='application/json', status=200) + # Set up parameter values + model_id = 'testString' + language = 'testString' + training_data = io.BytesIO(b'This is a mock file.').getvalue() + # Pass in all but one required param and check for a ValueError req_param_dict = { + "model_id": model_id, + "language": language, + "training_data": training_data, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.list_models(**req_copy) + _service.update_classifications_model(**req_copy) -class TestDeleteModel(): +class TestDeleteClassificationsModel(): """ - Test Class for delete_model + Test Class for delete_classifications_model """ def preprocess_url(self, request_url: str): @@ -372,12 +1746,12 @@ def preprocess_url(self, request_url: str): return re.compile(request_url.rstrip('/') + '/+') @responses.activate - def test_delete_model_all_params(self): + def test_delete_classifications_model_all_params(self): """ - delete_model() + delete_classifications_model() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/models/testString') + url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') mock_response = '{"deleted": "deleted"}' responses.add(responses.DELETE, url, @@ -389,7 +1763,7 @@ def test_delete_model_all_params(self): model_id = 'testString' # Invoke method - response = service.delete_model( + response = _service.delete_classifications_model( model_id, headers={} ) @@ -400,12 +1774,12 @@ def test_delete_model_all_params(self): @responses.activate - def test_delete_model_value_error(self): + def test_delete_classifications_model_value_error(self): """ - test_delete_model_value_error() + test_delete_classifications_model_value_error() """ # Set up mock - url = self.preprocess_url(base_url + '/v1/models/testString') + url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') mock_response = '{"deleted": "deleted"}' responses.add(responses.DELETE, url, @@ -423,13 +1797,13 @@ def test_delete_model_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - service.delete_model(**req_copy) + _service.delete_classifications_model(**req_copy) # endregion ############################################################################## -# End of Service: ManageModels +# End of Service: ManageClassificationsModels ############################################################################## @@ -508,6 +1882,10 @@ def test_analysis_results_serialization(self): categories_result_model['score'] = 0.594296 categories_result_model['explanation'] = categories_result_explanation_model + classifications_result_model = {} # ClassificationsResult + classifications_result_model['class_name'] = 'temperature' + classifications_result_model['confidence'] = 0.562519 + document_emotion_results_model = {} # DocumentEmotionResults document_emotion_results_model['emotion'] = emotion_scores_model @@ -538,7 +1916,7 @@ def test_analysis_results_serialization(self): relation_argument_model = {} # RelationArgument relation_argument_model['entities'] = [relation_entity_model] - relation_argument_model['location'] = [38] + relation_argument_model['location'] = [22, 32] relation_argument_model['text'] = 'Best Actor' relations_result_model = {} # RelationsResult @@ -614,6 +1992,7 @@ def test_analysis_results_serialization(self): analysis_results_model_json['entities'] = [entities_result_model] analysis_results_model_json['keywords'] = [keywords_result_model] analysis_results_model_json['categories'] = [categories_result_model] + analysis_results_model_json['classifications'] = [classifications_result_model] analysis_results_model_json['emotion'] = emotion_result_model analysis_results_model_json['metadata'] = features_results_metadata_model analysis_results_model_json['relations'] = [relations_result_model] @@ -696,6 +2075,103 @@ def test_author_serialization(self): author_model_json2 = author_model.to_dict() assert author_model_json2 == author_model_json +class TestCategoriesModel(): + """ + Test Class for CategoriesModel + """ + + def test_categories_model_serialization(self): + """ + Test serialization/deserialization for CategoriesModel + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + + # Construct a json representation of a CategoriesModel model + categories_model_model_json = {} + categories_model_model_json['name'] = 'testString' + categories_model_model_json['user_metadata'] = {} + categories_model_model_json['language'] = 'testString' + categories_model_model_json['description'] = 'testString' + categories_model_model_json['model_version'] = 'testString' + categories_model_model_json['workspace_id'] = 'testString' + categories_model_model_json['version_description'] = 'testString' + categories_model_model_json['features'] = ['testString'] + categories_model_model_json['status'] = 'starting' + categories_model_model_json['model_id'] = 'testString' + categories_model_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + categories_model_model_json['notices'] = [notice_model] + categories_model_model_json['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + categories_model_model_json['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + + # Construct a model instance of CategoriesModel by calling from_dict on the json representation + categories_model_model = CategoriesModel.from_dict(categories_model_model_json) + assert categories_model_model != False + + # Construct a model instance of CategoriesModel by calling from_dict on the json representation + categories_model_model_dict = CategoriesModel.from_dict(categories_model_model_json).__dict__ + categories_model_model2 = CategoriesModel(**categories_model_model_dict) + + # Verify the model instances are equivalent + assert categories_model_model == categories_model_model2 + + # Convert model instance back to dict and verify no loss of data + categories_model_model_json2 = categories_model_model.to_dict() + assert categories_model_model_json2 == categories_model_model_json + +class TestCategoriesModelList(): + """ + Test Class for CategoriesModelList + """ + + def test_categories_model_list_serialization(self): + """ + Test serialization/deserialization for CategoriesModelList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + + categories_model_model = {} # CategoriesModel + categories_model_model['name'] = 'testString' + categories_model_model['user_metadata'] = {} + categories_model_model['language'] = 'testString' + categories_model_model['description'] = 'testString' + categories_model_model['model_version'] = 'testString' + categories_model_model['workspace_id'] = 'testString' + categories_model_model['version_description'] = 'testString' + categories_model_model['features'] = ['testString'] + categories_model_model['status'] = 'starting' + categories_model_model['model_id'] = 'testString' + categories_model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + categories_model_model['notices'] = [notice_model] + categories_model_model['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + categories_model_model['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + + # Construct a json representation of a CategoriesModelList model + categories_model_list_model_json = {} + categories_model_list_model_json['models'] = [categories_model_model] + + # Construct a model instance of CategoriesModelList by calling from_dict on the json representation + categories_model_list_model = CategoriesModelList.from_dict(categories_model_list_model_json) + assert categories_model_list_model != False + + # Construct a model instance of CategoriesModelList by calling from_dict on the json representation + categories_model_list_model_dict = CategoriesModelList.from_dict(categories_model_list_model_json).__dict__ + categories_model_list_model2 = CategoriesModelList(**categories_model_list_model_dict) + + # Verify the model instances are equivalent + assert categories_model_list_model == categories_model_list_model2 + + # Convert model instance back to dict and verify no loss of data + categories_model_list_model_json2 = categories_model_list_model.to_dict() + assert categories_model_list_model_json2 == categories_model_list_model_json + class TestCategoriesOptions(): """ Test Class for CategoriesOptions @@ -829,6 +2305,162 @@ def test_categories_result_explanation_serialization(self): categories_result_explanation_model_json2 = categories_result_explanation_model.to_dict() assert categories_result_explanation_model_json2 == categories_result_explanation_model_json +class TestClassificationsModel(): + """ + Test Class for ClassificationsModel + """ + + def test_classifications_model_serialization(self): + """ + Test serialization/deserialization for ClassificationsModel + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + + # Construct a json representation of a ClassificationsModel model + classifications_model_model_json = {} + classifications_model_model_json['name'] = 'testString' + classifications_model_model_json['user_metadata'] = {} + classifications_model_model_json['language'] = 'testString' + classifications_model_model_json['description'] = 'testString' + classifications_model_model_json['model_version'] = 'testString' + classifications_model_model_json['workspace_id'] = 'testString' + classifications_model_model_json['version_description'] = 'testString' + classifications_model_model_json['features'] = ['testString'] + classifications_model_model_json['status'] = 'starting' + classifications_model_model_json['model_id'] = 'testString' + classifications_model_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifications_model_model_json['notices'] = [notice_model] + classifications_model_model_json['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifications_model_model_json['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + + # Construct a model instance of ClassificationsModel by calling from_dict on the json representation + classifications_model_model = ClassificationsModel.from_dict(classifications_model_model_json) + assert classifications_model_model != False + + # Construct a model instance of ClassificationsModel by calling from_dict on the json representation + classifications_model_model_dict = ClassificationsModel.from_dict(classifications_model_model_json).__dict__ + classifications_model_model2 = ClassificationsModel(**classifications_model_model_dict) + + # Verify the model instances are equivalent + assert classifications_model_model == classifications_model_model2 + + # Convert model instance back to dict and verify no loss of data + classifications_model_model_json2 = classifications_model_model.to_dict() + assert classifications_model_model_json2 == classifications_model_model_json + +class TestClassificationsModelList(): + """ + Test Class for ClassificationsModelList + """ + + def test_classifications_model_list_serialization(self): + """ + Test serialization/deserialization for ClassificationsModelList + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + + classifications_model_model = {} # ClassificationsModel + classifications_model_model['name'] = 'testString' + classifications_model_model['user_metadata'] = {} + classifications_model_model['language'] = 'testString' + classifications_model_model['description'] = 'testString' + classifications_model_model['model_version'] = 'testString' + classifications_model_model['workspace_id'] = 'testString' + classifications_model_model['version_description'] = 'testString' + classifications_model_model['features'] = ['testString'] + classifications_model_model['status'] = 'starting' + classifications_model_model['model_id'] = 'testString' + classifications_model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifications_model_model['notices'] = [notice_model] + classifications_model_model['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifications_model_model['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + + # Construct a json representation of a ClassificationsModelList model + classifications_model_list_model_json = {} + classifications_model_list_model_json['models'] = [classifications_model_model] + + # Construct a model instance of ClassificationsModelList by calling from_dict on the json representation + classifications_model_list_model = ClassificationsModelList.from_dict(classifications_model_list_model_json) + assert classifications_model_list_model != False + + # Construct a model instance of ClassificationsModelList by calling from_dict on the json representation + classifications_model_list_model_dict = ClassificationsModelList.from_dict(classifications_model_list_model_json).__dict__ + classifications_model_list_model2 = ClassificationsModelList(**classifications_model_list_model_dict) + + # Verify the model instances are equivalent + assert classifications_model_list_model == classifications_model_list_model2 + + # Convert model instance back to dict and verify no loss of data + classifications_model_list_model_json2 = classifications_model_list_model.to_dict() + assert classifications_model_list_model_json2 == classifications_model_list_model_json + +class TestClassificationsOptions(): + """ + Test Class for ClassificationsOptions + """ + + def test_classifications_options_serialization(self): + """ + Test serialization/deserialization for ClassificationsOptions + """ + + # Construct a json representation of a ClassificationsOptions model + classifications_options_model_json = {} + classifications_options_model_json['model'] = 'testString' + + # Construct a model instance of ClassificationsOptions by calling from_dict on the json representation + classifications_options_model = ClassificationsOptions.from_dict(classifications_options_model_json) + assert classifications_options_model != False + + # Construct a model instance of ClassificationsOptions by calling from_dict on the json representation + classifications_options_model_dict = ClassificationsOptions.from_dict(classifications_options_model_json).__dict__ + classifications_options_model2 = ClassificationsOptions(**classifications_options_model_dict) + + # Verify the model instances are equivalent + assert classifications_options_model == classifications_options_model2 + + # Convert model instance back to dict and verify no loss of data + classifications_options_model_json2 = classifications_options_model.to_dict() + assert classifications_options_model_json2 == classifications_options_model_json + +class TestClassificationsResult(): + """ + Test Class for ClassificationsResult + """ + + def test_classifications_result_serialization(self): + """ + Test serialization/deserialization for ClassificationsResult + """ + + # Construct a json representation of a ClassificationsResult model + classifications_result_model_json = {} + classifications_result_model_json['class_name'] = 'testString' + classifications_result_model_json['confidence'] = 72.5 + + # Construct a model instance of ClassificationsResult by calling from_dict on the json representation + classifications_result_model = ClassificationsResult.from_dict(classifications_result_model_json) + assert classifications_result_model != False + + # Construct a model instance of ClassificationsResult by calling from_dict on the json representation + classifications_result_model_dict = ClassificationsResult.from_dict(classifications_result_model_json).__dict__ + classifications_result_model2 = ClassificationsResult(**classifications_result_model_dict) + + # Verify the model instances are equivalent + assert classifications_result_model == classifications_result_model2 + + # Convert model instance back to dict and verify no loss of data + classifications_result_model_json2 = classifications_result_model.to_dict() + assert classifications_result_model_json2 == classifications_result_model_json + class TestConceptsOptions(): """ Test Class for ConceptsOptions @@ -1290,6 +2922,14 @@ def test_features_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + categories_options_model = {} # CategoriesOptions + categories_options_model['explanation'] = True + categories_options_model['limit'] = 10 + categories_options_model['model'] = 'testString' + + classifications_options_model = {} # ClassificationsOptions + classifications_options_model['model'] = 'testString' + concepts_options_model = {} # ConceptsOptions concepts_options_model['limit'] = 50 @@ -1309,6 +2949,8 @@ def test_features_serialization(self): keywords_options_model['sentiment'] = True keywords_options_model['emotion'] = True + metadata_options_model = {} # MetadataOptions + relations_options_model = {} # RelationsOptions relations_options_model['model'] = 'testString' @@ -1320,11 +2962,10 @@ def test_features_serialization(self): sentiment_options_model = {} # SentimentOptions sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] + sentiment_options_model['model'] = 'testString' - categories_options_model = {} # CategoriesOptions - categories_options_model['explanation'] = True - categories_options_model['limit'] = 10 - categories_options_model['model'] = 'testString' + summarization_options_model = {} # SummarizationOptions + summarization_options_model['limit'] = 10 syntax_options_tokens_model = {} # SyntaxOptionsTokens syntax_options_tokens_model['lemma'] = True @@ -1336,15 +2977,17 @@ def test_features_serialization(self): # Construct a json representation of a Features model features_model_json = {} + features_model_json['categories'] = categories_options_model + features_model_json['classifications'] = classifications_options_model features_model_json['concepts'] = concepts_options_model features_model_json['emotion'] = emotion_options_model features_model_json['entities'] = entities_options_model features_model_json['keywords'] = keywords_options_model - features_model_json['metadata'] = { 'foo': 'bar' } + features_model_json['metadata'] = metadata_options_model features_model_json['relations'] = relations_options_model features_model_json['semantic_roles'] = semantic_roles_options_model features_model_json['sentiment'] = sentiment_options_model - features_model_json['categories'] = categories_options_model + features_model_json['summarization'] = summarization_options_model features_model_json['syntax'] = syntax_options_model # Construct a model instance of Features by calling from_dict on the json representation @@ -1508,6 +3151,112 @@ def test_keywords_result_serialization(self): keywords_result_model_json2 = keywords_result_model.to_dict() assert keywords_result_model_json2 == keywords_result_model_json +class TestListCategoriesModelsResponse(): + """ + Test Class for ListCategoriesModelsResponse + """ + + def test_list_categories_models_response_serialization(self): + """ + Test serialization/deserialization for ListCategoriesModelsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + + categories_model_model = {} # CategoriesModel + categories_model_model['name'] = 'testString' + categories_model_model['user_metadata'] = {} + categories_model_model['language'] = 'testString' + categories_model_model['description'] = 'testString' + categories_model_model['model_version'] = 'testString' + categories_model_model['workspace_id'] = 'testString' + categories_model_model['version_description'] = 'testString' + categories_model_model['features'] = ['testString'] + categories_model_model['status'] = 'starting' + categories_model_model['model_id'] = 'testString' + categories_model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + categories_model_model['notices'] = [notice_model] + categories_model_model['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + categories_model_model['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + + categories_model_list_model = {} # CategoriesModelList + categories_model_list_model['models'] = [categories_model_model] + + # Construct a json representation of a ListCategoriesModelsResponse model + list_categories_models_response_model_json = {} + list_categories_models_response_model_json['models'] = [categories_model_list_model] + + # Construct a model instance of ListCategoriesModelsResponse by calling from_dict on the json representation + list_categories_models_response_model = ListCategoriesModelsResponse.from_dict(list_categories_models_response_model_json) + assert list_categories_models_response_model != False + + # Construct a model instance of ListCategoriesModelsResponse by calling from_dict on the json representation + list_categories_models_response_model_dict = ListCategoriesModelsResponse.from_dict(list_categories_models_response_model_json).__dict__ + list_categories_models_response_model2 = ListCategoriesModelsResponse(**list_categories_models_response_model_dict) + + # Verify the model instances are equivalent + assert list_categories_models_response_model == list_categories_models_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_categories_models_response_model_json2 = list_categories_models_response_model.to_dict() + assert list_categories_models_response_model_json2 == list_categories_models_response_model_json + +class TestListClassificationsModelsResponse(): + """ + Test Class for ListClassificationsModelsResponse + """ + + def test_list_classifications_models_response_serialization(self): + """ + Test serialization/deserialization for ListClassificationsModelsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + + classifications_model_model = {} # ClassificationsModel + classifications_model_model['name'] = 'testString' + classifications_model_model['user_metadata'] = {} + classifications_model_model['language'] = 'testString' + classifications_model_model['description'] = 'testString' + classifications_model_model['model_version'] = 'testString' + classifications_model_model['workspace_id'] = 'testString' + classifications_model_model['version_description'] = 'testString' + classifications_model_model['features'] = ['testString'] + classifications_model_model['status'] = 'starting' + classifications_model_model['model_id'] = 'testString' + classifications_model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifications_model_model['notices'] = [notice_model] + classifications_model_model['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifications_model_model['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + + classifications_model_list_model = {} # ClassificationsModelList + classifications_model_list_model['models'] = [classifications_model_model] + + # Construct a json representation of a ListClassificationsModelsResponse model + list_classifications_models_response_model_json = {} + list_classifications_models_response_model_json['models'] = [classifications_model_list_model] + + # Construct a model instance of ListClassificationsModelsResponse by calling from_dict on the json representation + list_classifications_models_response_model = ListClassificationsModelsResponse.from_dict(list_classifications_models_response_model_json) + assert list_classifications_models_response_model != False + + # Construct a model instance of ListClassificationsModelsResponse by calling from_dict on the json representation + list_classifications_models_response_model_dict = ListClassificationsModelsResponse.from_dict(list_classifications_models_response_model_json).__dict__ + list_classifications_models_response_model2 = ListClassificationsModelsResponse(**list_classifications_models_response_model_dict) + + # Verify the model instances are equivalent + assert list_classifications_models_response_model == list_classifications_models_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_classifications_models_response_model_json2 = list_classifications_models_response_model.to_dict() + assert list_classifications_models_response_model_json2 == list_classifications_models_response_model_json + class TestListModelsResults(): """ Test Class for ListModelsResults @@ -1529,7 +3278,7 @@ def test_list_models_results_serialization(self): model_model['model_version'] = 'testString' model_model['version'] = 'testString' model_model['version_description'] = 'testString' - model_model['created'] = '2020-01-28T18:40:40.123456Z' + model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a json representation of a ListModelsResults model list_models_results_model_json = {} @@ -1550,6 +3299,84 @@ def test_list_models_results_serialization(self): list_models_results_model_json2 = list_models_results_model.to_dict() assert list_models_results_model_json2 == list_models_results_model_json +class TestListSentimentModelsResponse(): + """ + Test Class for ListSentimentModelsResponse + """ + + def test_list_sentiment_models_response_serialization(self): + """ + Test serialization/deserialization for ListSentimentModelsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + + sentiment_model_model = {} # SentimentModel + sentiment_model_model['features'] = ['testString'] + sentiment_model_model['status'] = 'starting' + sentiment_model_model['model_id'] = 'testString' + sentiment_model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + sentiment_model_model['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + sentiment_model_model['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + sentiment_model_model['name'] = 'testString' + sentiment_model_model['user_metadata'] = {} + sentiment_model_model['language'] = 'testString' + sentiment_model_model['description'] = 'testString' + sentiment_model_model['model_version'] = 'testString' + sentiment_model_model['notices'] = [notice_model] + sentiment_model_model['workspace_id'] = 'testString' + sentiment_model_model['version_description'] = 'testString' + + # Construct a json representation of a ListSentimentModelsResponse model + list_sentiment_models_response_model_json = {} + list_sentiment_models_response_model_json['models'] = [sentiment_model_model] + + # Construct a model instance of ListSentimentModelsResponse by calling from_dict on the json representation + list_sentiment_models_response_model = ListSentimentModelsResponse.from_dict(list_sentiment_models_response_model_json) + assert list_sentiment_models_response_model != False + + # Construct a model instance of ListSentimentModelsResponse by calling from_dict on the json representation + list_sentiment_models_response_model_dict = ListSentimentModelsResponse.from_dict(list_sentiment_models_response_model_json).__dict__ + list_sentiment_models_response_model2 = ListSentimentModelsResponse(**list_sentiment_models_response_model_dict) + + # Verify the model instances are equivalent + assert list_sentiment_models_response_model == list_sentiment_models_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_sentiment_models_response_model_json2 = list_sentiment_models_response_model.to_dict() + assert list_sentiment_models_response_model_json2 == list_sentiment_models_response_model_json + +class TestMetadataOptions(): + """ + Test Class for MetadataOptions + """ + + def test_metadata_options_serialization(self): + """ + Test serialization/deserialization for MetadataOptions + """ + + # Construct a json representation of a MetadataOptions model + metadata_options_model_json = {} + + # Construct a model instance of MetadataOptions by calling from_dict on the json representation + metadata_options_model = MetadataOptions.from_dict(metadata_options_model_json) + assert metadata_options_model != False + + # Construct a model instance of MetadataOptions by calling from_dict on the json representation + metadata_options_model_dict = MetadataOptions.from_dict(metadata_options_model_json).__dict__ + metadata_options_model2 = MetadataOptions(**metadata_options_model_dict) + + # Verify the model instances are equivalent + assert metadata_options_model == metadata_options_model2 + + # Convert model instance back to dict and verify no loss of data + metadata_options_model_json2 = metadata_options_model.to_dict() + assert metadata_options_model_json2 == metadata_options_model_json + class TestModel(): """ Test Class for Model @@ -1570,7 +3397,7 @@ def test_model_serialization(self): model_model_json['model_version'] = 'testString' model_model_json['version'] = 'testString' model_model_json['version_description'] = 'testString' - model_model_json['created'] = '2020-01-28T18:40:40.123456Z' + model_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) # Construct a model instance of Model by calling from_dict on the json representation model_model = Model.from_dict(model_model_json) @@ -1587,6 +3414,35 @@ def test_model_serialization(self): model_model_json2 = model_model.to_dict() assert model_model_json2 == model_model_json +class TestNotice(): + """ + Test Class for Notice + """ + + def test_notice_serialization(self): + """ + Test serialization/deserialization for Notice + """ + + # Construct a json representation of a Notice model + notice_model_json = {} + notice_model_json['message'] = 'testString' + + # Construct a model instance of Notice by calling from_dict on the json representation + notice_model = Notice.from_dict(notice_model_json) + assert notice_model != False + + # Construct a model instance of Notice by calling from_dict on the json representation + notice_model_dict = Notice.from_dict(notice_model_json).__dict__ + notice_model2 = Notice(**notice_model_dict) + + # Verify the model instances are equivalent + assert notice_model == notice_model2 + + # Convert model instance back to dict and verify no loss of data + notice_model_json2 = notice_model.to_dict() + assert notice_model_json2 == notice_model_json + class TestRelationArgument(): """ Test Class for RelationArgument @@ -2047,6 +3903,53 @@ def test_sentence_result_serialization(self): sentence_result_model_json2 = sentence_result_model.to_dict() assert sentence_result_model_json2 == sentence_result_model_json +class TestSentimentModel(): + """ + Test Class for SentimentModel + """ + + def test_sentiment_model_serialization(self): + """ + Test serialization/deserialization for SentimentModel + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + + # Construct a json representation of a SentimentModel model + sentiment_model_model_json = {} + sentiment_model_model_json['features'] = ['testString'] + sentiment_model_model_json['status'] = 'starting' + sentiment_model_model_json['model_id'] = 'testString' + sentiment_model_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + sentiment_model_model_json['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + sentiment_model_model_json['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + sentiment_model_model_json['name'] = 'testString' + sentiment_model_model_json['user_metadata'] = {} + sentiment_model_model_json['language'] = 'testString' + sentiment_model_model_json['description'] = 'testString' + sentiment_model_model_json['model_version'] = 'testString' + sentiment_model_model_json['notices'] = [notice_model] + sentiment_model_model_json['workspace_id'] = 'testString' + sentiment_model_model_json['version_description'] = 'testString' + + # Construct a model instance of SentimentModel by calling from_dict on the json representation + sentiment_model_model = SentimentModel.from_dict(sentiment_model_model_json) + assert sentiment_model_model != False + + # Construct a model instance of SentimentModel by calling from_dict on the json representation + sentiment_model_model_dict = SentimentModel.from_dict(sentiment_model_model_json).__dict__ + sentiment_model_model2 = SentimentModel(**sentiment_model_model_dict) + + # Verify the model instances are equivalent + assert sentiment_model_model == sentiment_model_model2 + + # Convert model instance back to dict and verify no loss of data + sentiment_model_model_json2 = sentiment_model_model.to_dict() + assert sentiment_model_model_json2 == sentiment_model_model_json + class TestSentimentOptions(): """ Test Class for SentimentOptions @@ -2061,6 +3964,7 @@ def test_sentiment_options_serialization(self): sentiment_options_model_json = {} sentiment_options_model_json['document'] = True sentiment_options_model_json['targets'] = ['testString'] + sentiment_options_model_json['model'] = 'testString' # Construct a model instance of SentimentOptions by calling from_dict on the json representation sentiment_options_model = SentimentOptions.from_dict(sentiment_options_model_json) @@ -2117,6 +4021,35 @@ def test_sentiment_result_serialization(self): sentiment_result_model_json2 = sentiment_result_model.to_dict() assert sentiment_result_model_json2 == sentiment_result_model_json +class TestSummarizationOptions(): + """ + Test Class for SummarizationOptions + """ + + def test_summarization_options_serialization(self): + """ + Test serialization/deserialization for SummarizationOptions + """ + + # Construct a json representation of a SummarizationOptions model + summarization_options_model_json = {} + summarization_options_model_json['limit'] = 10 + + # Construct a model instance of SummarizationOptions by calling from_dict on the json representation + summarization_options_model = SummarizationOptions.from_dict(summarization_options_model_json) + assert summarization_options_model != False + + # Construct a model instance of SummarizationOptions by calling from_dict on the json representation + summarization_options_model_dict = SummarizationOptions.from_dict(summarization_options_model_json).__dict__ + summarization_options_model2 = SummarizationOptions(**summarization_options_model_dict) + + # Verify the model instances are equivalent + assert summarization_options_model == summarization_options_model2 + + # Convert model instance back to dict and verify no loss of data + summarization_options_model_json2 = summarization_options_model.to_dict() + assert summarization_options_model_json2 == summarization_options_model_json + class TestSyntaxOptions(): """ Test Class for SyntaxOptions From 900bd79bbeb7a28b82aa47d2e3345837f62fc306 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 20 May 2021 14:56:16 -0400 Subject: [PATCH 320/455] fix(lt): fix character encoding for non latin langs --- ibm_watson/language_translator_v3.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 9a069d4dc..d5b9b184d 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -174,7 +174,7 @@ def translate(self, 'target': target } data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) + data = json.dumps(data, ensure_ascii=False).encode('utf-8') headers['content-type'] = 'application/json' if 'headers' in kwargs: From 323a2da304750e3d3c2a951582c21f29ed8dffe6 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 24 May 2021 17:43:54 -0400 Subject: [PATCH 321/455] build(requirements): faster dependency resolution and core upgrade --- requirements-dev.txt | 22 +++++++++++----------- requirements.txt | 2 +- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/requirements-dev.txt b/requirements-dev.txt index c872f2b75..5a99832ef 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,21 +1,21 @@ # test dependencies -pytest>=2.8.2 -responses>=0.10.6 -python_dotenv>=0.1.5;python_version!='3.2' -pylint>=1.4.4 -tox>=2.9.1 -pytest-rerunfailures>=3.1 -ibm_cloud_sdk_core==3.3.6 +pytest==6.2.4 +responses==0.13.3 +python_dotenv==0.17.1;python_version!='3.2' +pylint==2.8.2 +tox==3.23.0 +pytest-rerunfailures==9.1.1 +ibm_cloud_sdk_core>=3.3.6, == 3.* # code coverage -coverage<5 +coverage>=4, <5 codecov>=1.6.3 pytest-cov>=2.2.1 # documentation -recommonmark>=0.2.0 -Sphinx>=1.3.1 -bumpversion>=0.5.3 +recommonmark==0.7.1 +Sphinx==3.5.2 +bumpversion==0.6.0 # Web sockets websocket-client==0.48.0 diff --git a/requirements.txt b/requirements.txt index cb4fc4a4e..154be79f7 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 -ibm_cloud_sdk_core==3.3.6 +ibm_cloud_sdk_core>=3.3.6, == 3.* From c09022f8841104262351447ac5dccba6ef159805 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 24 May 2021 17:55:14 -0400 Subject: [PATCH 322/455] fix(nlu): remove ListCategoriesModelsResponse --- .../natural_language_understanding_v1.py | 58 +------------------ .../test_natural_language_understanding_v1.py | 57 +----------------- 2 files changed, 3 insertions(+), 112 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index e3108e0a5..6202f7797 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -623,7 +623,7 @@ def list_categories_models(self, **kwargs) -> DetailedResponse: :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListCategoriesModelsResponse` object + :rtype: DetailedResponse with `dict` result representing a `CategoriesModelList` object """ headers = {} @@ -3990,62 +3990,6 @@ def __ne__(self, other: 'KeywordsResult') -> bool: return not self == other -class ListCategoriesModelsResponse(): - """ - ListCategoriesModelsResponse. - - :attr List[CategoriesModelList] models: (optional) - """ - - def __init__(self, *, models: List['CategoriesModelList'] = None) -> None: - """ - Initialize a ListCategoriesModelsResponse object. - - :param List[CategoriesModelList] models: (optional) - """ - self.models = models - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListCategoriesModelsResponse': - """Initialize a ListCategoriesModelsResponse object from a json dictionary.""" - args = {} - if 'models' in _dict: - args['models'] = [ - CategoriesModelList.from_dict(x) for x in _dict.get('models') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListCategoriesModelsResponse 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, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] - 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 ListCategoriesModelsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListCategoriesModelsResponse') -> 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: 'ListCategoriesModelsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ListClassificationsModelsResponse(): """ ListClassificationsModelsResponse. diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index c3394421b..1d24b9748 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -1050,7 +1050,7 @@ def test_list_categories_models_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/models/categories') - mock_response = '{"models": [{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1073,7 +1073,7 @@ def test_list_categories_models_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/models/categories') - mock_response = '{"models": [{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3151,59 +3151,6 @@ def test_keywords_result_serialization(self): keywords_result_model_json2 = keywords_result_model.to_dict() assert keywords_result_model_json2 == keywords_result_model_json -class TestListCategoriesModelsResponse(): - """ - Test Class for ListCategoriesModelsResponse - """ - - def test_list_categories_models_response_serialization(self): - """ - Test serialization/deserialization for ListCategoriesModelsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' - - categories_model_model = {} # CategoriesModel - categories_model_model['name'] = 'testString' - categories_model_model['user_metadata'] = {} - categories_model_model['language'] = 'testString' - categories_model_model['description'] = 'testString' - categories_model_model['model_version'] = 'testString' - categories_model_model['workspace_id'] = 'testString' - categories_model_model['version_description'] = 'testString' - categories_model_model['features'] = ['testString'] - categories_model_model['status'] = 'starting' - categories_model_model['model_id'] = 'testString' - categories_model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - categories_model_model['notices'] = [notice_model] - categories_model_model['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - categories_model_model['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - - categories_model_list_model = {} # CategoriesModelList - categories_model_list_model['models'] = [categories_model_model] - - # Construct a json representation of a ListCategoriesModelsResponse model - list_categories_models_response_model_json = {} - list_categories_models_response_model_json['models'] = [categories_model_list_model] - - # Construct a model instance of ListCategoriesModelsResponse by calling from_dict on the json representation - list_categories_models_response_model = ListCategoriesModelsResponse.from_dict(list_categories_models_response_model_json) - assert list_categories_models_response_model != False - - # Construct a model instance of ListCategoriesModelsResponse by calling from_dict on the json representation - list_categories_models_response_model_dict = ListCategoriesModelsResponse.from_dict(list_categories_models_response_model_json).__dict__ - list_categories_models_response_model2 = ListCategoriesModelsResponse(**list_categories_models_response_model_dict) - - # Verify the model instances are equivalent - assert list_categories_models_response_model == list_categories_models_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_categories_models_response_model_json2 = list_categories_models_response_model.to_dict() - assert list_categories_models_response_model_json2 == list_categories_models_response_model_json - class TestListClassificationsModelsResponse(): """ Test Class for ListClassificationsModelsResponse From 15653d61222ed339346134dd28273790147d79df Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 2 Jun 2021 14:28:38 -0400 Subject: [PATCH 323/455] ci(travis): remove python 3.5 testing and add verbose tox output --- .travis.yml | 3 +-- setup.py | 2 +- tox.ini | 4 ++-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index aad9df38c..1fb579b22 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,5 @@ language: python python: -- 3.5 - 3.6 - 3.7 - 3.8 @@ -16,7 +15,7 @@ before_script: - pip3 install --editable . script: - pip3 install -U python-dotenv -- tox +- tox -vv before_deploy: - pip3 install bumpversion pypandoc - sudo apt-get update diff --git a/setup.py b/setup.py index 272147bb6..3c0510ce0 100644 --- a/setup.py +++ b/setup.py @@ -64,7 +64,7 @@ def run_tests(self): version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core>=3.3.6'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core>=3.3.6, == 3.*'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='IBM Watson', diff --git a/tox.ini b/tox.ini index f8e4d5efd..17cd0047a 100644 --- a/tox.ini +++ b/tox.ini @@ -1,8 +1,8 @@ [tox] -envlist = lint, py35, py36, py37 +envlist = lint, py36, py37, py38 [testenv:lint] -basepython = python3.7 +basepython = python3.8 deps = pylint commands = pylint ibm_watson test examples From cd1dadfc98d1d8120674a6e796bed01577b79329 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 2 Jun 2021 14:48:40 -0400 Subject: [PATCH 324/455] ci(.env): update credentials --- .env.enc | Bin 1840 -> 1888 bytes tox.ini | 1 + 2 files changed, 1 insertion(+) diff --git a/.env.enc b/.env.enc index ccff317bca9a941e6ed4397440483ae562200127..80fb09046b8d297832c15c50c42f081dcde97392 100644 GIT binary patch literal 1888 zcmV-m2cP)Du#4Y+x+@zzR)+WL`W#1PIH6wec%{G@CH&W*e5&`I_lmmneX(*PU!&;H z4RW+aMz-WO?jd*{A$&<=McQE3AI|+lS*U^j;-a|dZ>y{6&}j`5;_H}kPOb|z9hHT~ zIdoiaj=hsetuY@n+hiPIs}o?u6SvNqMZrHL zO7hik4>)Qe4M9mNZ9BM3OBY^bI%o+_?2gYrsug5d(>|{~Dqt$PyNom&Yqu=!eBP<) z1mP6YhQ#jAlMqpz>~v0H!KrNlQ<+?rK+dM%;}>f*Oc(F$tN3 zQA%!jSLP1H_g$7HwEl^vV+73rGAycS{5`HAYv?>cZkrcSqW&gv!X8{GActN7apLu_ z0UFT$Q4F9j{q{ZXaA=x?*r5S($CGarbAF>~ndfjSu0)O|lUM3c!bD(|ogHDJB(#lZ!RyIRf$tcTTM=q1o0TAH)$@j?Q$%1Dr@nY%>E~L-&Pz&8WwzP= z-4wNJ=xTE*`$xp)VzL66RA>)2VWP9l@q_st@=N}nm=k9&W69|F?YME3!)C1=L)w$? z^RB3N;cJHp;=Ijh*iPBPb_cmfs6x{Ov|&Ht>FY3AL--jnaG475W@ z&dhl!7$#7%7fFgd-7quGSnjy4sTm(jk z{+71@YySm?i9RR0@>tFeMp!%lwRN7xayc~QBl^lHRK*gM{oR}1bwH; zGPTE!u1xBhxvzQ5!kOkWL>{y2$n<9Nh4KGTHnAU5=k1h`BeQU*Ul9ErK2jH$XWM3T z#MA$af_Rb1V8(&G`%5(KB$h#9+tyQScv~bHhm5&uUZ{EZ&ycpstjWX;uhO%2@9rnq z`%+_As5|m4CIN8Z$q{8ZxUwbXap%I#^S8b#v~%dXZ`kl`Lm30V^`{$XeFuanp%tz! z2YZJQCI~NPtP1ot6tP#L--#271Mn_(W}3;#cT^tKGMDIkCMeuqeyEj(*ut*j$_Q6# z4F-VRmbY?y&oX(HKH5%?~yi}L1d9SY%=L!nZKA%a-9FK;}OA!DU3o9J)RBKh7{ z_T#bJNV!qL`PARLQE1fEMYaU+v&@F9=@m6KZvGmRQyZW1aqpv0@Q<5fj+bG*%X|j> zaHX5he9MEABlW+X{OO_p5PmaCt9`lC<}>J-x)y(BM0S|~ylTx@6Wz-VT>g5;kbzKJ zhs>>cQ_iXoin8hL!@NR%8sMHs8fTXw83IUF>+Z;QR|wk&qc$P7L$M8e9p^`CL3xJD z0ugq0-hf_v7u(WGgU* ztZY4fb+ZS^cJ2rYok7s9B+W~<@IS@{^NJiTt}`b6`BsManUGT&PjTf z^II97jgU|V3vmOIB6?~=K87wi)dO>HywD*0nfse#ZeBHU&s^fV9=CNt?LIoAlL3e( aY?zx-A|}sM3wOj$c(CN;w%qITk?GV>UBk!# literal 1840 zcmV-02haGORQQ-Vd!QK;?YHFc;kFDvhQqOpSdDrC!Y00B_uBr0fZ%NRd7RBttnr$> zdvkKk8FQPGwICK_xLTfSd}Hp9ax8osXqG(M-WB#JCYB>aL8cd&9MbV}q;6$}=t)mz z$*#i@1oL)zti+BTgmpQVsrcpY`Hh|>8Yf+0;sTInWkb$T9n8wGKCcumHMry6d;fIH zjvt5lx*RM4;6Vc5`?{=EXu#1~4r0l#v(#|t5CAe2ZSWbbk@zDrBCJ`d@+26&Z91x}> zN8*oASNCZWHdglN*~LG89QQ#Ss4>D_F&{eMnvOFGC=_uaEP=L8=VRF2=UIstTj2G$IkG^7pO&i3!;Pz!M#_T{JI-&j4?90oZ z#N7~hnn{HL{tZglUR#Gn4Hcj(>cXlh+}NyIe$4Gm^8^a3%<{BZoE1=_LJHR<-{(a5H8p4i<8$VghNrFm`& zL*1L8J)Jmju5cMD9?_<69FA&j4|$?0^wVRFt6uRAaxL@_!T3Ajx|;D#uTQJlR8Aqk zN)#14vAPTq1}vt0CbR4ku!)EWJE&(f=U^c47!-X}vsSV3@A}FcQU}x#21~aW8O>^` zKKjLGLXb^h$4CCmC`<3=Mkmz%m>_h(Nz!yx4DMpk*odp1spMGvVNpL5sUCVvV+U_5 zzf!0&8`lRy|B0~!2d;dX-wv=*N(Ah1YC;fnGfC9=9x|Hgup0nmNV>IJ#1w)f3=}XR zHm~+gF)@S|4y5|m)WzZ3DDzgZv{w=y`auw z$^);KJ)04>R2JiB=N;JLjv*sSZ?M9YBd%m;+}$;O;` zyY`8RI@9n)Oxux!5}om#o016Z1<>Xgk|9YVAw~8m4>tb+yh>4_h)pZzqMqMO9J(e$ zXJ)ajW@3WmlmJ~WII+UO8}lGHCTm@^_n7o6!GUT0mo=O>e;LxZv8W}N?^aRPZQRdr!i@TEdrR(+x=Vemu zp*mwIGg#ZSjisj!0yPP%FpE;e4oSbeF(w*vdrz%WrcUOu{Guv8dG(tPdhL?`A!J+1 z>_{z6C)Hv*;0aZA(>F=GID2MrU%sv4+HNgXG6{EaY(1(AQ97ZmC;pVOQ`QqBBoRh$ zVUPhEK30hr{A*i>f3rsM0tH6-#_7rGb^Hafxerjd9k{YJ>Y^o%PnJ0~kOr8&fm-Nj zoTKlc@J%ydUJd4QCN34u^zzn)M}UDV^TTJDBe@u`FP zO=T8C(pwX1UJIf%Of$Nm(j^?V!aJ^egEHBm@r|B-14z#n?;S@ojiQxNnzz_H7uIYw zgM9_ShWUd(-6J@!YC`~UJ3f93@xv5}5`vdl*g+S)U><;uoiAa;V&jNC8cpf&n0f=y zLqXH-F7R>!o}A!M=E7oXx$|9QM{+WG}+0RT?E=n*dMPmu9Mp zCF28o9ST(SLm!C2T7ib#z2&hl$4@Hu*~waYNMWazUS#RzXl^B*>Mo#t8d(u25n=&0 z(FJ`&L#+;C*pM` Date: Fri, 4 Jun 2021 12:47:30 -0400 Subject: [PATCH 325/455] fix(tts): remove extraneous filename param --- ibm_watson/text_to_speech_v1.py | 17 ++--------- test/unit/test_text_to_speech_v1.py | 44 ----------------------------- 2 files changed, 3 insertions(+), 58 deletions(-) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 9c8c78ad9..fb0716e77 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -38,7 +38,6 @@ """ from enum import Enum -from os.path import basename from typing import BinaryIO, Dict, List import json @@ -1061,13 +1060,8 @@ def list_custom_prompts(self, customization_id: str, response = self.send(request) return response - def add_custom_prompt(self, - customization_id: str, - prompt_id: str, - metadata: 'PromptMetadata', - file: BinaryIO, - *, - filename: str = None, + def add_custom_prompt(self, customization_id: str, prompt_id: str, + metadata: 'PromptMetadata', file: BinaryIO, **kwargs) -> DetailedResponse: """ Add a custom prompt. @@ -1166,7 +1160,6 @@ def add_custom_prompt(self, rate of 16 kHz. The service accepts audio with higher sampling rates. The service transcodes all audio to 16 kHz before processing it. * The length of the prompt audio is limited to 30 seconds. - :param str filename: (optional) The filename for file. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Prompt` object @@ -1189,11 +1182,7 @@ def add_custom_prompt(self, form_data = [] form_data.append( ('metadata', (None, json.dumps(metadata), 'application/json'))) - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, 'audio/wav'))) + form_data.append(('file', (None, file, 'audio/wav'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 4af54f88f..7414852a4 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1319,7 +1319,6 @@ def test_add_custom_prompt_all_params(self): prompt_id = 'testString' metadata = prompt_metadata_model file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' # Invoke method response = _service.add_custom_prompt( @@ -1327,48 +1326,6 @@ def test_add_custom_prompt_all_params(self): prompt_id, metadata, file, - filename=filename, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - - - @responses.activate - def test_add_custom_prompt_required_params(self): - """ - test_add_custom_prompt_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') - mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) - - # Construct a dict representation of a PromptMetadata model - prompt_metadata_model = {} - prompt_metadata_model['prompt_text'] = 'testString' - prompt_metadata_model['speaker_id'] = 'testString' - - # Set up parameter values - customization_id = 'testString' - prompt_id = 'testString' - metadata = prompt_metadata_model - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - - # Invoke method - response = _service.add_custom_prompt( - customization_id, - prompt_id, - metadata, - file, - filename=filename, headers={} ) @@ -1401,7 +1358,6 @@ def test_add_custom_prompt_value_error(self): prompt_id = 'testString' metadata = prompt_metadata_model file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { From 1bb8b22a5ac7f044e98686e133f3fb8512dda9a8 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 4 Jun 2021 12:48:16 -0400 Subject: [PATCH 326/455] ci(tox): fix slow dependency resolution --- appveyor.yml | 27 +++++++-------------------- tox.ini | 6 ++---- 2 files changed, 9 insertions(+), 24 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 17727297f..4402872df 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,33 +1,20 @@ environment: - matrix: - - - PYTHON: "C:\\Python35" - - PYTHON: "C:\\Python36-x64" + - TOXENV: py36 + - TOXENV: py37 + - TOXENV: py38 install: - # Install Python (from the official .msi of https://python.org) and pip when - # not already installed. - - ps: if (-not(Test-Path($env:PYTHON))) { & appveyor\install.ps1 } - - # Prepend newly installed Python to the PATH of this build - - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%" - - - "python -m pip install --upgrade pip" - - - "pip install --editable ." - - - "pip install -r requirements-dev.txt" + # Install Tox + - pip install tox==3.23.0 build: off test_script: - - - ps: py.test --reruns 3 --cov=ibm_watson + - tox deploy: off matrix: - fast_finish: true - + fast_finish: true \ No newline at end of file diff --git a/tox.ini b/tox.ini index 4748d89a3..380546688 100644 --- a/tox.ini +++ b/tox.ini @@ -8,12 +8,10 @@ commands = pylint ibm_watson test examples [testenv] passenv = TOXENV CI TRAVIS* +deps = -r{toxinidir}/requirements.txt +commands_pre= pip install -r{toxinidir}/requirements-dev.txt commands = py.test --reruns 3 --cov=ibm_watson codecov -e TOXENV -deps = - -r{toxinidir}/requirements.txt - -r{toxinidir}/requirements-dev.txt - --upgrade pip==20.3.3 usedevelop = True exclude = .venv,.git,.tox,docs From 2280dbbd3ad3d5375599d6e2294073518c38447f Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Tue, 8 Jun 2021 15:05:22 -0400 Subject: [PATCH 327/455] ci(tox-appveyor): remove tox and appveyor --- .travis.yml | 5 ++--- appveyor.yml | 20 -------------------- requirements-dev.txt | 1 - tox.ini | 17 ----------------- 4 files changed, 2 insertions(+), 41 deletions(-) delete mode 100644 appveyor.yml delete mode 100644 tox.ini diff --git a/.travis.yml b/.travis.yml index 1fb579b22..e484d4197 100644 --- a/.travis.yml +++ b/.travis.yml @@ -7,15 +7,14 @@ cache: pip before_install: - '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && openssl aes-256-cbc -K $encrypted_3c84dcdc6bbe_key -iv $encrypted_3c84dcdc6bbe_iv -in .env.enc -out .env -d || true' - npm install npm@latest -g -install: -- pip3 install tox-travis before_script: - pip3 install -r requirements.txt - pip3 install -r requirements-dev.txt - pip3 install --editable . script: - pip3 install -U python-dotenv -- tox -vv +- py.test --reruns 3 --cov=ibm_watson +- codecov before_deploy: - pip3 install bumpversion pypandoc - sudo apt-get update diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 4402872df..000000000 --- a/appveyor.yml +++ /dev/null @@ -1,20 +0,0 @@ -environment: - matrix: - - TOXENV: py36 - - TOXENV: py37 - - TOXENV: py38 - -install: - - # Install Tox - - pip install tox==3.23.0 - -build: off - -test_script: - - tox - -deploy: off - -matrix: - fast_finish: true \ No newline at end of file diff --git a/requirements-dev.txt b/requirements-dev.txt index 5a99832ef..c313940fa 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -3,7 +3,6 @@ pytest==6.2.4 responses==0.13.3 python_dotenv==0.17.1;python_version!='3.2' pylint==2.8.2 -tox==3.23.0 pytest-rerunfailures==9.1.1 ibm_cloud_sdk_core>=3.3.6, == 3.* diff --git a/tox.ini b/tox.ini deleted file mode 100644 index 380546688..000000000 --- a/tox.ini +++ /dev/null @@ -1,17 +0,0 @@ -[tox] -envlist = lint, py36, py37, py38 - -[testenv:lint] -basepython = python3.8 -deps = pylint -commands = pylint ibm_watson test examples - -[testenv] -passenv = TOXENV CI TRAVIS* -deps = -r{toxinidir}/requirements.txt -commands_pre= pip install -r{toxinidir}/requirements-dev.txt -commands = - py.test --reruns 3 --cov=ibm_watson - codecov -e TOXENV -usedevelop = True -exclude = .venv,.git,.tox,docs From 49b65312546c8d53dd4f9e6f133dd60418d30f74 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 9 Jun 2021 09:51:48 -0400 Subject: [PATCH 328/455] refactor(readme/nlu): text change and param reorder --- README.md | 2 +- .../natural_language_understanding_v1.py | 32 +++++++------- .../test_natural_language_understanding_v1.py | 42 +++++++++---------- 3 files changed, 38 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index 381e4b659..125aefa2a 100755 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ Python client library to quickly get started with the various [Watson APIs][wdc]
-## ANNOUNCEMENTS! +## Announcements ### Updating endpoint URLs from watsonplatform.net Watson API endpoint URLs at watsonplatform.net are changing and will not work after 26 May 2021. Update your calls to use the newer endpoint URLs. For more information, see https://cloud.ibm.com/docs/watson?topic=watson-endpoint-change. diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 6202f7797..9840166cf 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2021. +# (C) Copyright IBM Corp. 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -3438,10 +3438,6 @@ class Features(): """ Analysis features and options. - :attr CategoriesOptions categories: (optional) Returns a five-level taxonomy of - the content. The top three categories are returned. - Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, - Portuguese, Spanish. :attr ClassificationsOptions classifications: (optional) Returns text classifications for the content. Supported languages: English only. @@ -3489,13 +3485,16 @@ class Features(): :attr SummarizationOptions summarization: (optional) (Experimental) Returns a summary of content. Supported languages: English only. + :attr CategoriesOptions categories: (optional) Returns a five-level taxonomy of + the content. The top three categories are returned. + Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, + Portuguese, Spanish. :attr SyntaxOptions syntax: (optional) Returns tokens and sentences from the input text. """ def __init__(self, *, - categories: 'CategoriesOptions' = None, classifications: 'ClassificationsOptions' = None, concepts: 'ConceptsOptions' = None, emotion: 'EmotionOptions' = None, @@ -3506,14 +3505,11 @@ def __init__(self, semantic_roles: 'SemanticRolesOptions' = None, sentiment: 'SentimentOptions' = None, summarization: 'SummarizationOptions' = None, + categories: 'CategoriesOptions' = None, syntax: 'SyntaxOptions' = None) -> None: """ Initialize a Features object. - :param CategoriesOptions categories: (optional) Returns a five-level - taxonomy of the content. The top three categories are returned. - Supported languages: Arabic, English, French, German, Italian, Japanese, - Korean, Portuguese, Spanish. :param ClassificationsOptions classifications: (optional) Returns text classifications for the content. Supported languages: English only. @@ -3562,10 +3558,13 @@ def __init__(self, :param SummarizationOptions summarization: (optional) (Experimental) Returns a summary of content. Supported languages: English only. + :param CategoriesOptions categories: (optional) Returns a five-level + taxonomy of the content. The top three categories are returned. + Supported languages: Arabic, English, French, German, Italian, Japanese, + Korean, Portuguese, Spanish. :param SyntaxOptions syntax: (optional) Returns tokens and sentences from the input text. """ - self.categories = categories self.classifications = classifications self.concepts = concepts self.emotion = emotion @@ -3576,15 +3575,13 @@ def __init__(self, self.semantic_roles = semantic_roles self.sentiment = sentiment self.summarization = summarization + self.categories = categories self.syntax = syntax @classmethod def from_dict(cls, _dict: Dict) -> 'Features': """Initialize a Features object from a json dictionary.""" args = {} - if 'categories' in _dict: - args['categories'] = CategoriesOptions.from_dict( - _dict.get('categories')) if 'classifications' in _dict: args['classifications'] = ClassificationsOptions.from_dict( _dict.get('classifications')) @@ -3610,6 +3607,9 @@ def from_dict(cls, _dict: Dict) -> 'Features': if 'summarization' in _dict: args['summarization'] = SummarizationOptions.from_dict( _dict.get('summarization')) + if 'categories' in _dict: + args['categories'] = CategoriesOptions.from_dict( + _dict.get('categories')) if 'syntax' in _dict: args['syntax'] = SyntaxOptions.from_dict(_dict.get('syntax')) return cls(**args) @@ -3622,8 +3622,6 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = self.categories.to_dict() if hasattr(self, 'classifications') and self.classifications is not None: _dict['classifications'] = self.classifications.to_dict() @@ -3645,6 +3643,8 @@ def to_dict(self) -> Dict: _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'summarization') and self.summarization is not None: _dict['summarization'] = self.summarization.to_dict() + if hasattr(self, 'categories') and self.categories is not None: + _dict['categories'] = self.categories.to_dict() if hasattr(self, 'syntax') and self.syntax is not None: _dict['syntax'] = self.syntax.to_dict() return _dict diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 1d24b9748..83e5a3da8 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2021. +# (C) Copyright IBM Corp. 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -74,12 +74,6 @@ def test_analyze_all_params(self): content_type='application/json', status=200) - # Construct a dict representation of a CategoriesOptions model - categories_options_model = {} - categories_options_model['explanation'] = True - categories_options_model['limit'] = 10 - categories_options_model['model'] = 'testString' - # Construct a dict representation of a ClassificationsOptions model classifications_options_model = {} classifications_options_model['model'] = 'testString' @@ -130,6 +124,12 @@ def test_analyze_all_params(self): summarization_options_model = {} summarization_options_model['limit'] = 10 + # Construct a dict representation of a CategoriesOptions model + categories_options_model = {} + categories_options_model['explanation'] = True + categories_options_model['limit'] = 10 + categories_options_model['model'] = 'testString' + # Construct a dict representation of a SyntaxOptionsTokens model syntax_options_tokens_model = {} syntax_options_tokens_model['lemma'] = True @@ -142,7 +142,6 @@ def test_analyze_all_params(self): # Construct a dict representation of a Features model features_model = {} - features_model['categories'] = categories_options_model features_model['classifications'] = classifications_options_model features_model['concepts'] = concepts_options_model features_model['emotion'] = emotion_options_model @@ -153,6 +152,7 @@ def test_analyze_all_params(self): features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model features_model['summarization'] = summarization_options_model + features_model['categories'] = categories_options_model features_model['syntax'] = syntax_options_model # Set up parameter values @@ -213,12 +213,6 @@ def test_analyze_value_error(self): content_type='application/json', status=200) - # Construct a dict representation of a CategoriesOptions model - categories_options_model = {} - categories_options_model['explanation'] = True - categories_options_model['limit'] = 10 - categories_options_model['model'] = 'testString' - # Construct a dict representation of a ClassificationsOptions model classifications_options_model = {} classifications_options_model['model'] = 'testString' @@ -269,6 +263,12 @@ def test_analyze_value_error(self): summarization_options_model = {} summarization_options_model['limit'] = 10 + # Construct a dict representation of a CategoriesOptions model + categories_options_model = {} + categories_options_model['explanation'] = True + categories_options_model['limit'] = 10 + categories_options_model['model'] = 'testString' + # Construct a dict representation of a SyntaxOptionsTokens model syntax_options_tokens_model = {} syntax_options_tokens_model['lemma'] = True @@ -281,7 +281,6 @@ def test_analyze_value_error(self): # Construct a dict representation of a Features model features_model = {} - features_model['categories'] = categories_options_model features_model['classifications'] = classifications_options_model features_model['concepts'] = concepts_options_model features_model['emotion'] = emotion_options_model @@ -292,6 +291,7 @@ def test_analyze_value_error(self): features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model features_model['summarization'] = summarization_options_model + features_model['categories'] = categories_options_model features_model['syntax'] = syntax_options_model # Set up parameter values @@ -2922,11 +2922,6 @@ def test_features_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - categories_options_model = {} # CategoriesOptions - categories_options_model['explanation'] = True - categories_options_model['limit'] = 10 - categories_options_model['model'] = 'testString' - classifications_options_model = {} # ClassificationsOptions classifications_options_model['model'] = 'testString' @@ -2967,6 +2962,11 @@ def test_features_serialization(self): summarization_options_model = {} # SummarizationOptions summarization_options_model['limit'] = 10 + categories_options_model = {} # CategoriesOptions + categories_options_model['explanation'] = True + categories_options_model['limit'] = 10 + categories_options_model['model'] = 'testString' + syntax_options_tokens_model = {} # SyntaxOptionsTokens syntax_options_tokens_model['lemma'] = True syntax_options_tokens_model['part_of_speech'] = True @@ -2977,7 +2977,6 @@ def test_features_serialization(self): # Construct a json representation of a Features model features_model_json = {} - features_model_json['categories'] = categories_options_model features_model_json['classifications'] = classifications_options_model features_model_json['concepts'] = concepts_options_model features_model_json['emotion'] = emotion_options_model @@ -2988,6 +2987,7 @@ def test_features_serialization(self): features_model_json['semantic_roles'] = semantic_roles_options_model features_model_json['sentiment'] = sentiment_options_model features_model_json['summarization'] = summarization_options_model + features_model_json['categories'] = categories_options_model features_model_json['syntax'] = syntax_options_model # Construct a model instance of Features by calling from_dict on the json representation From 7c928e767fe42f6d6cf002693cf6af9d2c20aa3d Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 9 Jun 2021 09:56:00 -0400 Subject: [PATCH 329/455] refactor(nlu): copyright change --- test/unit/test_natural_language_understanding_v1.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 83e5a3da8..cfc055173 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2021. +# (C) Copyright IBM Corp. 2019, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. From 0fe491d7b450f1ccc81cc563ddedc87a63b4f687 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 10 Jun 2021 13:25:30 -0400 Subject: [PATCH 330/455] ci(travis): remove integration tests from travis --- .travis.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index e484d4197..6164feabb 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,8 +13,6 @@ before_script: - pip3 install --editable . script: - pip3 install -U python-dotenv -- py.test --reruns 3 --cov=ibm_watson -- codecov before_deploy: - pip3 install bumpversion pypandoc - sudo apt-get update From e3cc28ce88c211fbd4dc43838c715f94eaf38c0e Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 10 Jun 2021 18:18:45 +0000 Subject: [PATCH 331/455] =?UTF-8?q?Bump=20version:=205.1.0=20=E2=86=92=205?= =?UTF-8?q?.2.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 14256294d..9630647a6 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.1.0 +current_version = 5.2.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index a5e451313..f279ec922 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '5.1.0' +__version__ = '5.2.0' diff --git a/setup.py b/setup.py index 3c0510ce0..1469c0d6b 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '5.1.0' +__version__ = '5.2.0' if sys.argv[-1] == 'publish': From 38c8e723498d3b33fe7b70c897637e8070ed1fd1 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 10 Jun 2021 18:18:45 +0000 Subject: [PATCH 332/455] chore(release): 5.2.0 release notes # [5.2.0](https://github.com/watson-developer-cloud/python-sdk/compare/v5.1.0...v5.2.0) (2021-06-10) ### Bug Fixes * **compare-comply:** add deprecation notice for CC ([d006937](https://github.com/watson-developer-cloud/python-sdk/commit/d0069376dcd1e23076c12130feeea1b20010de06)) * **lt:** fix character encoding for non latin langs ([900bd79](https://github.com/watson-developer-cloud/python-sdk/commit/900bd79bbeb7a28b82aa47d2e3345837f62fc306)) * **nlu:** remove ListCategoriesModelsResponse ([c09022f](https://github.com/watson-developer-cloud/python-sdk/commit/c09022f8841104262351447ac5dccba6ef159805)) * **tts:** remove extraneous filename param ([d6f9c5d](https://github.com/watson-developer-cloud/python-sdk/commit/d6f9c5d4b75bf303f363dfac68180351d7bcbc26)) ### Features * **assistantv1:** generation release changes ([ac146a1](https://github.com/watson-developer-cloud/python-sdk/commit/ac146a1efc5e148a636b17540399898c74222a29)) * **assistantv2:** generation release changes ([d33caba](https://github.com/watson-developer-cloud/python-sdk/commit/d33caba954e764e4b512e4fce62750c2fd9b8cf1)) * **discov2:** generation release changes ([0ea3ac0](https://github.com/watson-developer-cloud/python-sdk/commit/0ea3ac0ce1024138097e1777f8ecde5b45eaa92d)) * **nlu:** generation release changes ([e5e71b6](https://github.com/watson-developer-cloud/python-sdk/commit/e5e71b655bc3d7477fd4244df28651fa91a82cd4)) * **stt-tts:** generation release changes ([0600855](https://github.com/watson-developer-cloud/python-sdk/commit/06008553bdae0d2c0768d41a1d1878523e5bd810)) --- CHANGELOG.md | 19 ++++ package-lock.json | 274 +++++++++++++++++++++++----------------------- 2 files changed, 159 insertions(+), 134 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 608995fe1..b11af880f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,22 @@ +# [5.2.0](https://github.com/watson-developer-cloud/python-sdk/compare/v5.1.0...v5.2.0) (2021-06-10) + + +### Bug Fixes + +* **compare-comply:** add deprecation notice for CC ([d006937](https://github.com/watson-developer-cloud/python-sdk/commit/d0069376dcd1e23076c12130feeea1b20010de06)) +* **lt:** fix character encoding for non latin langs ([900bd79](https://github.com/watson-developer-cloud/python-sdk/commit/900bd79bbeb7a28b82aa47d2e3345837f62fc306)) +* **nlu:** remove ListCategoriesModelsResponse ([c09022f](https://github.com/watson-developer-cloud/python-sdk/commit/c09022f8841104262351447ac5dccba6ef159805)) +* **tts:** remove extraneous filename param ([d6f9c5d](https://github.com/watson-developer-cloud/python-sdk/commit/d6f9c5d4b75bf303f363dfac68180351d7bcbc26)) + + +### Features + +* **assistantv1:** generation release changes ([ac146a1](https://github.com/watson-developer-cloud/python-sdk/commit/ac146a1efc5e148a636b17540399898c74222a29)) +* **assistantv2:** generation release changes ([d33caba](https://github.com/watson-developer-cloud/python-sdk/commit/d33caba954e764e4b512e4fce62750c2fd9b8cf1)) +* **discov2:** generation release changes ([0ea3ac0](https://github.com/watson-developer-cloud/python-sdk/commit/0ea3ac0ce1024138097e1777f8ecde5b45eaa92d)) +* **nlu:** generation release changes ([e5e71b6](https://github.com/watson-developer-cloud/python-sdk/commit/e5e71b655bc3d7477fd4244df28651fa91a82cd4)) +* **stt-tts:** generation release changes ([0600855](https://github.com/watson-developer-cloud/python-sdk/commit/06008553bdae0d2c0768d41a1d1878523e5bd810)) + # [5.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v5.0.2...v5.1.0) (2021-01-12) diff --git a/package-lock.json b/package-lock.json index d0b743bd0..073021c0e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -3,162 +3,160 @@ "lockfileVersion": 1, "dependencies": { "@babel/code-frame": { - "version": "7.12.11", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.12.11.tgz", - "integrity": "sha512-Zt1yodBx1UcyiePMSkWnU4hPqhwq7hGi2nFL1LeA3EUl+q2LQx16MISgJ0+z7dnmgvP9QtIleuETGOiOH1RcIw==", + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.14.5.tgz", + "integrity": "sha512-9pzDqyc6OLDaqe+zbACgFkb6fKMNG6CObKpnYXChRsvYGyEdc7CA2BaqeOM+vOtCS5ndmJicPJhKAwYRI6UfFw==", "requires": { - "@babel/highlight": "^7.10.4" + "@babel/highlight": "^7.14.5" } }, "@babel/helper-validator-identifier": { - "version": "7.12.11", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.12.11.tgz", - "integrity": "sha512-np/lG3uARFybkoHokJUmf1QfEvRVCPbmQeUQpKow5cQ3xWrV9i3rUHodKDJPQfTVX61qKi+UdYk8kik84n7XOw==" + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.5.tgz", + "integrity": "sha512-5lsetuxCLilmVGyiLEfoHBRX8UCFD+1m2x3Rj97WrW3V7H3u4RWRXA4evMjImCsin2J2YT0QaVDGf+z8ondbAg==" }, "@babel/highlight": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.10.4.tgz", - "integrity": "sha512-i6rgnR/YgPEQzZZnbTHHuZdlE8qyoBNalD6F+q4vAFlcMEcqmkoG+mPqJYJCo63qPf74+Y1UZsl3l6f7/RIkmA==", + "version": "7.14.5", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.14.5.tgz", + "integrity": "sha512-qf9u2WFWVV0MppaL877j2dBtQIDgmidgjGk5VIMw3OadXvYaXn66U1BFlH2t4+t3i+8PhedppRv+i40ABzd+gg==", "requires": { - "@babel/helper-validator-identifier": "^7.10.4", + "@babel/helper-validator-identifier": "^7.14.5", "chalk": "^2.0.0", "js-tokens": "^4.0.0" } }, "@nodelib/fs.scandir": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.4.tgz", - "integrity": "sha512-33g3pMJk3bg5nXbL/+CY6I2eJDzZAni49PfJnL5fghPTggPvBd/pFNSgJsdAgWptuFu7qq/ERvOYFlhvsLTCKA==", + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", "requires": { - "@nodelib/fs.stat": "2.0.4", + "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "@nodelib/fs.stat": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.4.tgz", - "integrity": "sha512-IYlHJA0clt2+Vg7bccq+TzRdJvv19c2INqBSsoOLp1je7xjtr7J26+WXR72MCdvU9q1qTzIWDfhMf+DRvQJK4Q==" + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==" }, "@nodelib/fs.walk": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.6.tgz", - "integrity": "sha512-8Broas6vTtW4GIXTAHDoE32hnN2M5ykgCpWGbuXHQ15vEMqr23pB76e/GZcYsZCHALv50ktd24qhEyKr6wBtow==", + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.7.tgz", + "integrity": "sha512-BTIhocbPBSrRmHxOAJFtR18oLhxTtAFDAvL8hY1S3iU8k+E60W/YFs4jrixGzQjMpF4qPXxIQHcjVD9dz1C2QA==", "requires": { - "@nodelib/fs.scandir": "2.1.4", + "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "@octokit/auth-token": { - "version": "2.4.4", - "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.4.tgz", - "integrity": "sha512-LNfGu3Ro9uFAYh10MUZVaT7X2CnNm2C8IDQmabx+3DygYIQjs9FwzFAHN/0t6mu5HEPhxcb1XOuxdpY82vCg2Q==", + "version": "2.4.5", + "resolved": "https://registry.npmjs.org/@octokit/auth-token/-/auth-token-2.4.5.tgz", + "integrity": "sha512-BpGYsPgJt05M7/L/5FoE1PiAbdxXFZkX/3kDYcsvd1v6UhlnE5e96dTDr0ezX/EFwciQxf3cNV0loipsURU+WA==", "requires": { - "@octokit/types": "^6.0.0" + "@octokit/types": "^6.0.3" } }, "@octokit/core": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.2.4.tgz", - "integrity": "sha512-d9dTsqdePBqOn7aGkyRFe7pQpCXdibSJ5SFnrTr0axevObZrpz3qkWm7t/NjYv5a66z6vhfteriaq4FRz3e0Qg==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/@octokit/core/-/core-3.4.0.tgz", + "integrity": "sha512-6/vlKPP8NF17cgYXqucdshWqmMZGXkuvtcrWCgU5NOI0Pl2GjlmZyWgBMrU8zJ3v2MJlM6++CiB45VKYmhiWWg==", "requires": { "@octokit/auth-token": "^2.4.4", "@octokit/graphql": "^4.5.8", "@octokit/request": "^5.4.12", + "@octokit/request-error": "^2.0.5", "@octokit/types": "^6.0.3", - "before-after-hook": "^2.1.0", + "before-after-hook": "^2.2.0", "universal-user-agent": "^6.0.0" } }, "@octokit/endpoint": { - "version": "6.0.10", - "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.10.tgz", - "integrity": "sha512-9+Xef8nT7OKZglfkOMm7IL6VwxXUQyR7DUSU0LH/F7VNqs8vyd7es5pTfz9E7DwUIx7R3pGscxu1EBhYljyu7Q==", + "version": "6.0.11", + "resolved": "https://registry.npmjs.org/@octokit/endpoint/-/endpoint-6.0.11.tgz", + "integrity": "sha512-fUIPpx+pZyoLW4GCs3yMnlj2LfoXTWDUVPTC4V3MUEKZm48W+XYpeWSZCv+vYF1ZABUm2CqnDVf1sFtIYrj7KQ==", "requires": { - "@octokit/types": "^6.0.0", + "@octokit/types": "^6.0.3", "is-plain-object": "^5.0.0", "universal-user-agent": "^6.0.0" } }, "@octokit/graphql": { - "version": "4.5.8", - "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.5.8.tgz", - "integrity": "sha512-WnCtNXWOrupfPJgXe+vSmprZJUr0VIu14G58PMlkWGj3cH+KLZEfKMmbUQ6C3Wwx6fdhzVW1CD5RTnBdUHxhhA==", + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/@octokit/graphql/-/graphql-4.6.2.tgz", + "integrity": "sha512-WmsIR1OzOr/3IqfG9JIczI8gMJUMzzyx5j0XXQ4YihHtKlQc+u35VpVoOXhlKAlaBntvry1WpAzPl/a+s3n89Q==", "requires": { "@octokit/request": "^5.3.0", - "@octokit/types": "^6.0.0", + "@octokit/types": "^6.0.3", "universal-user-agent": "^6.0.0" } }, "@octokit/openapi-types": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-2.2.0.tgz", - "integrity": "sha512-274lNUDonw10kT8wHg8fCcUc1ZjZHbWv0/TbAwb0ojhBQqZYc1cQ/4yqTVTtPMDeZ//g7xVEYe/s3vURkRghPg==" + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-7.3.0.tgz", + "integrity": "sha512-o00X2FCLiEeXZkm1Ab5nvPUdVOlrpediwWZkpizUJ/xtZQsJ4FiQ2RB/dJEmb0Nk+NIz7zyDePcSCu/Y/0M3Ew==" }, "@octokit/plugin-paginate-rest": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.7.0.tgz", - "integrity": "sha512-+zARyncLjt9b0FjqPAbJo4ss7HOlBi1nprq+cPlw5vu2+qjy7WvlXhtXFdRHQbSL1Pt+bfAKaLADEkkvg8sP8w==", + "version": "2.13.3", + "resolved": "https://registry.npmjs.org/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.13.3.tgz", + "integrity": "sha512-46lptzM9lTeSmIBt/sVP/FLSTPGx6DCzAdSX3PfeJ3mTf4h9sGC26WpaQzMEq/Z44cOcmx8VsOhO+uEgE3cjYg==", "requires": { - "@octokit/types": "^6.0.1" + "@octokit/types": "^6.11.0" } }, "@octokit/plugin-request-log": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-1.0.2.tgz", - "integrity": "sha512-oTJSNAmBqyDR41uSMunLQKMX0jmEXbwD1fpz8FG27lScV3RhtGfBa1/BBLym+PxcC16IBlF7KH9vP1BUYxA+Eg==" + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-1.0.3.tgz", + "integrity": "sha512-4RFU4li238jMJAzLgAwkBAw+4Loile5haQMQr+uhFq27BmyJXcXSKvoQKqh0agsZEiUlW6iSv3FAgvmGkur7OQ==" }, "@octokit/plugin-rest-endpoint-methods": { - "version": "4.4.1", - "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-4.4.1.tgz", - "integrity": "sha512-+v5PcvrUcDeFXf8hv1gnNvNLdm4C0+2EiuWt9EatjjUmfriM1pTMM+r4j1lLHxeBQ9bVDmbywb11e3KjuavieA==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.3.1.tgz", + "integrity": "sha512-3B2iguGmkh6bQQaVOtCsS0gixrz8Lg0v4JuXPqBcFqLKuJtxAUf3K88RxMEf/naDOI73spD+goJ/o7Ie7Cvdjg==", "requires": { - "@octokit/types": "^6.1.0", + "@octokit/types": "^6.16.2", "deprecation": "^2.3.1" } }, "@octokit/request": { - "version": "5.4.12", - "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.4.12.tgz", - "integrity": "sha512-MvWYdxengUWTGFpfpefBBpVmmEYfkwMoxonIB3sUGp5rhdgwjXL1ejo6JbgzG/QD9B/NYt/9cJX1pxXeSIUCkg==", + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.5.0.tgz", + "integrity": "sha512-jxbMLQdQ3heFMZUaTLSCqcKs2oAHEYh7SnLLXyxbZmlULExZ/RXai7QUWWFKowcGGPlCZuKTZg0gSKHWrfYEoQ==", "requires": { "@octokit/endpoint": "^6.0.1", "@octokit/request-error": "^2.0.0", - "@octokit/types": "^6.0.3", - "deprecation": "^2.0.0", + "@octokit/types": "^6.16.1", "is-plain-object": "^5.0.0", "node-fetch": "^2.6.1", - "once": "^1.4.0", "universal-user-agent": "^6.0.0" } }, "@octokit/request-error": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.4.tgz", - "integrity": "sha512-LjkSiTbsxIErBiRh5wSZvpZqT4t0/c9+4dOe0PII+6jXR+oj/h66s7E4a/MghV7iT8W9ffoQ5Skoxzs96+gBPA==", + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@octokit/request-error/-/request-error-2.0.5.tgz", + "integrity": "sha512-T/2wcCFyM7SkXzNoyVNWjyVlUwBvW3igM3Btr/eKYiPmucXTtkxt2RBsf6gn3LTzaLSLTQtNmvg+dGsOxQrjZg==", "requires": { - "@octokit/types": "^6.0.0", + "@octokit/types": "^6.0.3", "deprecation": "^2.0.0", "once": "^1.4.0" } }, "@octokit/rest": { - "version": "18.0.12", - "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-18.0.12.tgz", - "integrity": "sha512-hNRCZfKPpeaIjOVuNJzkEL6zacfZlBPV8vw8ReNeyUkVvbuCvvrrx8K8Gw2eyHHsmd4dPlAxIXIZ9oHhJfkJpw==", + "version": "18.5.6", + "resolved": "https://registry.npmjs.org/@octokit/rest/-/rest-18.5.6.tgz", + "integrity": "sha512-8HdG6ZjQdZytU6tCt8BQ2XLC7EJ5m4RrbyU/EARSkAM1/HP3ceOzMG/9atEfe17EDMer3IVdHWLedz2wDi73YQ==", "requires": { "@octokit/core": "^3.2.3", "@octokit/plugin-paginate-rest": "^2.6.2", "@octokit/plugin-request-log": "^1.0.2", - "@octokit/plugin-rest-endpoint-methods": "4.4.1" + "@octokit/plugin-rest-endpoint-methods": "5.3.1" } }, "@octokit/types": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.2.1.tgz", - "integrity": "sha512-jHs9OECOiZxuEzxMZcXmqrEO8GYraHF+UzNVH2ACYh8e/Y7YoT+hUf9ldvVd6zIvWv4p3NdxbQ0xx3ku5BnSiA==", + "version": "6.16.2", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.16.2.tgz", + "integrity": "sha512-wWPSynU4oLy3i4KGyk+J1BLwRKyoeW2TwRHgwbDz17WtVFzSK2GOErGliruIx8c+MaYtHSYTx36DSmLNoNbtgA==", "requires": { - "@octokit/openapi-types": "^2.2.0", - "@types/node": ">= 8" + "@octokit/openapi-types": "^7.2.3" } }, "@semantic-release/changelog": { @@ -206,9 +204,9 @@ } }, "@semantic-release/github": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-7.2.0.tgz", - "integrity": "sha512-tMRnWiiWb43whRHvbDGXq4DGEbKRi56glDpXDJZit4PIiwDPX7Kx3QzmwRtDOcG+8lcpGjpdPabYZ9NBxoI2mw==", + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/@semantic-release/github/-/github-7.2.3.tgz", + "integrity": "sha512-lWjIVDLal+EQBzy697ayUNN8MoBpp+jYIyW2luOdqn5XBH4d9bQGfTnjuLyzARZBHejqh932HVjiH/j4+R7VHw==", "requires": { "@octokit/rest": "^18.0.0", "@semantic-release/error": "^2.2.0", @@ -216,7 +214,7 @@ "bottleneck": "^2.18.1", "debug": "^4.0.0", "dir-glob": "^3.0.0", - "fs-extra": "^9.0.0", + "fs-extra": "^10.0.0", "globby": "^11.0.0", "http-proxy-agent": "^4.0.0", "https-proxy-agent": "^5.0.0", @@ -226,6 +224,18 @@ "p-filter": "^2.0.0", "p-retry": "^4.0.0", "url-join": "^4.0.0" + }, + "dependencies": { + "fs-extra": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.0.0.tgz", + "integrity": "sha512-C5owb14u9eJwizKGdchcDUQeFtlSHHthBk8pbX9Vc1PFZrLombudjDnNns88aYslCyF6IY5SUw3Roz6xShcEIQ==", + "requires": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + } + } } }, "@tootallnate/once": { @@ -233,11 +243,6 @@ "resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-1.1.2.tgz", "integrity": "sha512-RbzJvlNzmRq5c3O09UipeuXno4tA1FE6ikOjxZK0tuxVv3412l64l5t1W5pj4+rJq9vpkm/kwiR07aZXnsKPxw==" }, - "@types/node": { - "version": "14.14.20", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.14.20.tgz", - "integrity": "sha512-Y93R97Ouif9JEOWPIUyU+eyIdyRqQR0I8Ez1dzku4hDx34NWh4HbtIc3WNzwB1Y9ULvNGeu5B8h8bVL5cAk4/A==" - }, "@types/retry": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz", @@ -279,9 +284,9 @@ "integrity": "sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==" }, "before-after-hook": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.1.0.tgz", - "integrity": "sha512-IWIbu7pMqyw3EAJHzzHbWa85b6oud/yfKYg5rqB5hNE8CeMi3nX+2C2sj0HswfblST86hpVEOAb9x34NZd6P7A==" + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.2.tgz", + "integrity": "sha512-3pZEU3NT5BFUo/AD5ERPWOgQOCZITni6iavr5AUw5AUwQjMlI0kzu5btnyD39AF0gUEsDPwJT+oY1ORBJijPjQ==" }, "bottleneck": { "version": "2.19.5", @@ -393,9 +398,9 @@ } }, "fast-glob": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.4.tgz", - "integrity": "sha512-kr/Oo6PX51265qeuCYsyGypiO5uJFgBS0jksyG7FUeCyQzNwYnzrNIMR1NXfkZXsMYXYLRAHgISHBz8gQcxKHQ==", + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.2.5.tgz", + "integrity": "sha512-2DtFcgT68wiTTiwZ2hNdJfcHNke9XOfnwmBRWXhmeKM8rF0TGwmC/Qto3S7RoZKp5cilZbxzO5iTNTQsJ+EeDg==", "requires": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", @@ -406,9 +411,9 @@ } }, "fastq": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.10.0.tgz", - "integrity": "sha512-NL2Qc5L3iQEsyYzweq7qfgy5OtXCmGzGvhElGEd/SoFWEMOEczNh5s5ocaF01HDetxz+p8ecjNPA6cZxxIHmzA==", + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.11.0.tgz", + "integrity": "sha512-7Eczs8gIPDrVzT+EksYBcupqMyxSHXXrHOLRRxU2/DicV8789MRBRR8+Hc2uWzUupOs4YS4JzBmBxjjCVBxD/g==", "requires": { "reusify": "^1.0.4" } @@ -422,14 +427,14 @@ } }, "fs-extra": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.0.1.tgz", - "integrity": "sha512-h2iAoN838FqAFJY2/qVpzFXy+EBxfVE220PalAqQLDVsFOHLJrZvut5puAbCdNv6WJk+B8ihI+k0c7JK5erwqQ==", + "version": "9.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz", + "integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==", "requires": { "at-least-node": "^1.0.0", "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", - "universalify": "^1.0.0" + "universalify": "^2.0.0" } }, "get-stream": { @@ -441,17 +446,17 @@ } }, "glob-parent": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.1.tgz", - "integrity": "sha512-FnI+VGOpnlGHWZxthPGR+QhR78fuiK0sNLkHQv+bL9fQi57lNNdquIbna/WrfROrolq8GK5Ek6BiMwqL/voRYQ==", + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "requires": { "is-glob": "^4.0.1" } }, "globby": { - "version": "11.0.2", - "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.2.tgz", - "integrity": "sha512-2ZThXDvvV8fYFRVIxnrMQBipZQDr7MxKAmQK1vujaj9/7eF0efG7BPUKJ7jP7G5SLF37xKDXvO4S/KKLj/Z0og==", + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/globby/-/globby-11.0.3.tgz", + "integrity": "sha512-ffdmosjA807y7+lA1NM0jELARVmYul/715xiILEjo3hBLPTcirgQNnXECn5g3mtR8TOLCVbkfua1Hpen25/Xcg==", "requires": { "array-union": "^2.1.0", "dir-glob": "^3.0.1", @@ -462,9 +467,9 @@ } }, "graceful-fs": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz", - "integrity": "sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw==" + "version": "4.2.6", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.6.tgz", + "integrity": "sha512-nTnJ528pbqxYanhpDYsi4Rd8MAeaBA67+RZ10CM1m3bTAVFEDcd5AuA4a6W5YkGZ1iNXHzZz8T6TBKLeBuNriQ==" }, "has-flag": { "version": "3.0.0", @@ -572,13 +577,6 @@ "requires": { "graceful-fs": "^4.1.6", "universalify": "^2.0.0" - }, - "dependencies": { - "universalify": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", - "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==" - } } }, "lines-and-columns": { @@ -587,9 +585,9 @@ "integrity": "sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA=" }, "lodash": { - "version": "4.17.20", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz", - "integrity": "sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA==" + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" }, "lodash.capitalize": { "version": "4.2.1", @@ -627,18 +625,18 @@ "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==" }, "micromatch": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.2.tgz", - "integrity": "sha512-y7FpHSbMUMoyPbYUSzO6PaZ6FyRnQOpHuKwbo1G+Knck95XVU4QAiKdGEnj5wwoS7PlOgthX/09u5iFJ+aYf5Q==", + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.4.tgz", + "integrity": "sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg==", "requires": { "braces": "^3.0.1", - "picomatch": "^2.0.5" + "picomatch": "^2.2.3" } }, "mime": { - "version": "2.4.7", - "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.7.tgz", - "integrity": "sha512-dhNd1uA2u397uQk3Nv5LM4lm93WYDUXFn3Fu291FJerns4jyTudqhIWe4W04YLy7Uk1tm1Ore04NpjRvQp/NPA==" + "version": "2.5.2", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.5.2.tgz", + "integrity": "sha512-tqkh47FzKeCPD2PUiPB6pkbMzsCasjxAfC62/Wap5qrUWcb+sFasXUC5I3gYM5iBM8v/Qpn4UK0x+j0iHyFPDg==" }, "mimic-fn": { "version": "2.1.0", @@ -698,18 +696,18 @@ "integrity": "sha512-2USApvnsutq8uoxZBGbbWM0JIYLiEMJ9RlaN7fAzVNb9OZN0SHjjTTfIcb667XynS5Y1VhwDJVDa72TnPzAYWw==" }, "p-retry": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.2.0.tgz", - "integrity": "sha512-jPH38/MRh263KKcq0wBNOGFJbm+U6784RilTmHjB/HM9kH9V8WlCpVUcdOmip9cjXOh6MxZ5yk1z2SjDUJfWmA==", + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.5.0.tgz", + "integrity": "sha512-5Hwh4aVQSu6BEP+w2zKlVXtFAaYQe1qWuVADSgoeVlLjwe/Q/AMSoRR4MDeaAfu8llT+YNbEijWu/YF3m6avkg==", "requires": { "@types/retry": "^0.12.0", "retry": "^0.12.0" } }, "parse-json": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.1.0.tgz", - "integrity": "sha512-+mi/lmVVNKFNVyLXV31ERiy2CY5E1/F6QtJFEzoChPRwwngMNXRDQ9GJ5WdE2Z2P4AujsOi0/+2qHID68KwfIQ==", + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", "requires": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", @@ -728,9 +726,9 @@ "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==" }, "picomatch": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.2.2.tgz", - "integrity": "sha512-q0M/9eZHzmr0AulXyPwNfZjtwZ/RBZlbN3K3CErVrk50T2ASYI7Bye0EvekFY3IP1Nt2DHu0re+V2ZHIpMkuWg==" + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.0.tgz", + "integrity": "sha512-lY1Q/PiJGC2zOv/z391WOTD+Z02bCgsFfvxoXXf6h7kv9o+WmsmzYqrAwY63sNgOxE4xEdq0WyUnXfKeBrSvYw==" }, "pump": { "version": "3.0.0", @@ -741,6 +739,11 @@ "once": "^1.3.1" } }, + "queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==" + }, "retry": { "version": "0.12.0", "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", @@ -752,9 +755,12 @@ "integrity": "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==" }, "run-parallel": { - "version": "1.1.10", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.1.10.tgz", - "integrity": "sha512-zb/1OuZ6flOlH6tQyMPUrE3x3Ulxjlo9WIVXR4yVYi4H9UXQaeIsPbLn2R3O3vQCnDKkAl2qHiuocKKX4Tz/Sw==" + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "requires": { + "queue-microtask": "^1.2.2" + } }, "shebang-command": { "version": "2.0.0", @@ -806,9 +812,9 @@ "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" }, "universalify": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-1.0.0.tgz", - "integrity": "sha512-rb6X1W158d7pRQBg5gkR8uPaSfiids68LTJQYOtEUhoJUWBdaQHsuT/EUduxXYxcrt4r5PJ4fuHW1MHT6p0qug==" + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.0.tgz", + "integrity": "sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ==" }, "url-join": { "version": "4.0.1", From 07b40c19271969a6a586f9efbb122063487baa5c Mon Sep 17 00:00:00 2001 From: Michael G Mosca Date: Tue, 15 Jun 2021 16:06:24 -0400 Subject: [PATCH 333/455] ci: fix fix --- .github/workflows/deploy.yml | 8 -------- 1 file changed, 8 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index f8691ef31..c91f23daf 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -66,11 +66,3 @@ jobs: run: npx semantic-release --dry-run - name: Build binary wheel and a source tarball run: python setup.py sdist - - name: Publish a Python distribution to PyPI # must have built dist before - if: github.event.workflow_run.conclusion == 'success' && github.event_name == 'push' && startsWith(github.ref, 'refs/tags') - uses: pypa/gh-action-pypi-publish@master - with: - password: ${{ secrets.PYPI_PASSWORD }} - user: watson-devex - repository_url: https://upload.pypi.org/legacy - verbose: false \ No newline at end of file From b9b7d8a7a48aeaf412b3aee5c0b0e133e52ad2d1 Mon Sep 17 00:00:00 2001 From: Michael G Mosca Date: Mon, 21 Jun 2021 17:34:34 -0400 Subject: [PATCH 334/455] ci(gha): Switch CI from Travis to GHA (#791) * ci: revisit GHA * ci(gha): ready CI for production release * ci(gha): add windows testing with legacy resolver * ci(gha): remove python 3.6/3.7 for windows Co-authored-by: Angelo Paparazzi --- .bumpversion.cfg | 6 ++--- .github/workflows/build-test.yml | 45 ++++++++++++++++++++++---------- .github/workflows/deploy.yml | 13 ++++----- .releaserc | 6 +++++ .travis.yml | 45 -------------------------------- setup.cfg | 2 ++ setup.py | 3 --- 7 files changed, 47 insertions(+), 73 deletions(-) delete mode 100644 .travis.yml create mode 100644 setup.cfg diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 9630647a6..77db58b09 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -6,6 +6,6 @@ commit = True search = __version__ = '{current_version}' replace = __version__ = '{new_version}' -[bumpversion:file:setup.py] -search = __version__ = '{current_version}' -replace = __version__ = '{new_version}' +[bumpversion:file:setup.cfg] +search = version = '{current_version}' +replace = version = '{new_version}' diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 657f5dd09..57d158c75 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -17,12 +17,17 @@ on: jobs: build_test: - name: Build and Test on Python ${{ matrix.python-version }} and ${{ matrix.os }} + name: Build on Python ${{ matrix.python-version }} using ${{ matrix.os }} runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ['3.5', '3.6', '3.7', '3.8'] - os: [ubuntu-latest] + python-version: ['3.6', '3.7', '3.8'] + os: [ubuntu-latest, windows-latest] + exclude: + - os: windows-latest + python-version: '3.6' + - os: windows-latest + python-version: '3.7' steps: - uses: actions/checkout@v2 @@ -30,23 +35,35 @@ jobs: uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - - name: Install dependencies + - name: Install dependencies (ubuntu) + if: matrix.os == 'ubuntu-latest' run: | pip3 install -r requirements.txt - pip3 install -r requirements-dev.txt --use-deprecated=legacy-resolver + pip3 install -r requirements-dev.txt pip3 install --editable . - - name: Execute Python unit tests for code coverage - if: matrix.python-version == '3.5' + - name: Install dependencies (windows) + if: matrix.os == 'windows-latest' + run: | + pip3 install -r requirements.txt --use-deprecated=legacy-resolver + pip3 install -r requirements-dev.txt --use-deprecated=legacy-resolver + pip3 install --editable . --use-deprecated=legacy-resolver + - name: Execute Python 3.6/3.7 unit tests + if: matrix.python-version != '3.8' + run: | + pip3 install -U python-dotenv + py.test test/unit + - name: Execute Python 3.8 unit tests (windows) + if: matrix.os == 'windows-latest' run: | pip3 install -U python-dotenv - py.test --reruns 3 --cov=ibm_watson + py.test test/unit --reruns 3 + - name: Execute Python 3.8 unit tests (ubuntu) + if: matrix.python-version == '3.8' && matrix.os == 'ubuntu-latest' + run: | + pip3 install -U python-dotenv + py.test test/unit --reruns 3 --cov=ibm_watson - name: Upload coverage to Codecov - if: matrix.python-version == '3.5' + if: matrix.python-version == '3.8' && matrix.os == 'ubuntu-latest' uses: codecov/codecov-action@v1 with: name: py${{ matrix.python-version }}-${{ matrix.os }} - - name: Execute Python unit tests - if: matrix.python-version != '3.5' - run: | - pip3 install -U python-dotenv - py.test diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index c91f23daf..a07d45afe 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -12,7 +12,6 @@ on: branches: [ master ] types: - completed - # Allows you to run this workflow manually from the Actions tab workflow_dispatch: @@ -34,11 +33,6 @@ jobs: uses: actions/setup-node@v1 with: node-version: 12 - - name: Install dependencies - run: | - pip3 install -r requirements.txt - pip3 install -r requirements-dev.txt --use-deprecated=legacy-resolver - pip3 install --editable . - name: Install Semantic Release dependencies run: | sudo apt-get install bumpversion @@ -49,8 +43,10 @@ jobs: npm install -g @semantic-release/github npm install -g @semantic-release/commit-analyzer npm install -g @semantic-release/release-notes-generator + npm install -g semantic-release-pypi + pip3 install setuptools wheel twine - name: Publish js docs - if: github.event.workflow_run.conclusion == 'success' && startsWith(github.ref, 'refs/tags') + if: ${{ github.event.workflow_run.conclusion == 'success' }} env: GH_TOKEN: ${{ secrets.GH_TOKEN }} GHA_BRANCH: ${{ github.ref }} # non PR only need to get last part @@ -63,6 +59,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN }} - run: npx semantic-release --dry-run + PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }} + run: npx semantic-release #--dry-run --branches 9388_gha Uncomment for testxing purposes - name: Build binary wheel and a source tarball run: python setup.py sdist diff --git a/.releaserc b/.releaserc index 4ee525055..3db0690e8 100644 --- a/.releaserc +++ b/.releaserc @@ -16,6 +16,12 @@ "message": "chore(release): ${nextRelease.version} release notes\n\n${nextRelease.notes}" } ], + [ + "semantic-release-pypi", + { + "repoUrl": "https://upload.pypi.org/legacy" + } + ], "@semantic-release/github" ] } diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 6164feabb..000000000 --- a/.travis.yml +++ /dev/null @@ -1,45 +0,0 @@ -language: python -python: -- 3.6 -- 3.7 -- 3.8 -cache: pip -before_install: -- '[ "${TRAVIS_PULL_REQUEST}" = "false" ] && openssl aes-256-cbc -K $encrypted_3c84dcdc6bbe_key -iv $encrypted_3c84dcdc6bbe_iv -in .env.enc -out .env -d || true' -- npm install npm@latest -g -before_script: -- pip3 install -r requirements.txt -- pip3 install -r requirements-dev.txt -- pip3 install --editable . -script: -- pip3 install -U python-dotenv -before_deploy: -- pip3 install bumpversion pypandoc -- sudo apt-get update -- sudo apt-get install pandoc -- nvm install 12 -- npm install @semantic-release/changelog -- npm install @semantic-release/exec -- npm install @semantic-release/git -- npm install @semantic-release/github -deploy: -- provider: script - script: docs/publish.sh - skip_cleanup: true - on: - python: 3.8 - tags: true -- provider: script - script: npx semantic-release - skip_cleanup: true - on: - python: 3.8 - branch: master -- provider: pypi - user: watson-devex - password: "$PYPI_PASSWORD" - repository: https://upload.pypi.org/legacy - skip_cleanup: true - on: - python: 3.8 - tags: true diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 000000000..29e579727 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[metadata] +version = 5.2.0 \ No newline at end of file diff --git a/setup.py b/setup.py index 1469c0d6b..5c615d5bb 100644 --- a/setup.py +++ b/setup.py @@ -18,8 +18,6 @@ import os import sys -__version__ = '5.2.0' - if sys.argv[-1] == 'publish': # test server @@ -61,7 +59,6 @@ def run_tests(self): setup(name='ibm-watson', - version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core>=3.3.6, == 3.*'], From e151e8271f4ddc2d0217beec8e84896e0e44539f Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Tue, 22 Jun 2021 09:57:06 -0400 Subject: [PATCH 335/455] fix(tts): remove origin header from websocket request --- ibm_watson/websocket/synthesize_listener.py | 1 + requirements-dev.txt | 2 +- requirements.txt | 2 +- test/integration/test_text_to_speech_v1.py | 35 +++++++++++++++++++++ 4 files changed, 38 insertions(+), 2 deletions(-) diff --git a/ibm_watson/websocket/synthesize_listener.py b/ibm_watson/websocket/synthesize_listener.py index e6fcec22c..ed57d3547 100644 --- a/ibm_watson/websocket/synthesize_listener.py +++ b/ibm_watson/websocket/synthesize_listener.py @@ -57,6 +57,7 @@ def __init__(self, self.ws_client.run_forever(http_proxy_host=self.http_proxy_host, http_proxy_port=self.http_proxy_port, + suppress_origin=True, sslopt={'cert_reqs': ssl.CERT_NONE} if self.verify is not None else None) diff --git a/requirements-dev.txt b/requirements-dev.txt index c313940fa..086cfe4e8 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -17,4 +17,4 @@ Sphinx==3.5.2 bumpversion==0.6.0 # Web sockets -websocket-client==0.48.0 +websocket-client==1.1.0 diff --git a/requirements.txt b/requirements.txt index 154be79f7..7df31b85a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 -websocket-client==0.48.0 +websocket-client==1.1.0 ibm_cloud_sdk_core>=3.3.6, == 3.* diff --git a/test/integration/test_text_to_speech_v1.py b/test/integration/test_text_to_speech_v1.py index f2b0d6221..41fab2fe5 100644 --- a/test/integration/test_text_to_speech_v1.py +++ b/test/integration/test_text_to_speech_v1.py @@ -133,3 +133,38 @@ def on_close(self): assert test_callback.fd is not None assert os.stat(file).st_size > 0 os.remove(file) + + # This is test will only be meaningful so long as en-AU_CraigVoice is a Neural type voice model + # Check this url for all Neutral type voice models: https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#languageVoices + def test_synthesize_using_websocket_neural(self): + file = 'tongue_twister.wav' + + class MySynthesizeCallback(SynthesizeCallback): + + def __init__(self): + SynthesizeCallback.__init__(self) + self.fd = None + self.error = None + + def on_connected(self): + self.fd = open(file, 'ab') + + def on_error(self, error): + self.error = error + + def on_audio_stream(self, audio_stream): + self.fd.write(audio_stream) + + 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-AU_CraigVoice') + assert test_callback.error is None + assert test_callback.fd is not None + assert os.stat(file).st_size > 0 + os.remove(file) From 9fa9d6c51dc3100ff12b896ff00d05350000ce44 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 28 Jun 2021 12:17:25 -0400 Subject: [PATCH 336/455] Switch deploy configuration methods (#794) * ci(gha): change deploy configs to test pypa publish gha * chore(setup.py): upload readme correctly * ci(deploy): update deploy config for production --- .bumpversion.cfg | 6 ++-- .github/workflows/deploy.yml | 12 +++++--- .releaserc | 6 ---- pyproject.toml | 3 ++ setup.cfg | 2 -- setup.py | 60 ++++++++---------------------------- 6 files changed, 27 insertions(+), 62 deletions(-) create mode 100644 pyproject.toml delete mode 100644 setup.cfg diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 77db58b09..9630647a6 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -6,6 +6,6 @@ commit = True search = __version__ = '{current_version}' replace = __version__ = '{new_version}' -[bumpversion:file:setup.cfg] -search = version = '{current_version}' -replace = version = '{new_version}' +[bumpversion:file:setup.py] +search = __version__ = '{current_version}' +replace = __version__ = '{new_version}' diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index a07d45afe..a8ca95413 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -43,8 +43,6 @@ jobs: npm install -g @semantic-release/github npm install -g @semantic-release/commit-analyzer npm install -g @semantic-release/release-notes-generator - npm install -g semantic-release-pypi - pip3 install setuptools wheel twine - name: Publish js docs if: ${{ github.event.workflow_run.conclusion == 'success' }} env: @@ -59,7 +57,13 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN }} - PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }} run: npx semantic-release #--dry-run --branches 9388_gha Uncomment for testxing purposes - name: Build binary wheel and a source tarball - run: python setup.py sdist + run: | + pip3 install setuptools wheel twine build + python -m build --sdist --outdir dist/ + - name: Publish distribution to Test PyPI + uses: pypa/gh-action-pypi-publish@v1.4.2 # Try to update version tag every release + with: + password: ${{ secrets.PYPI_TOKEN }} + repository_url: https://upload.pypi.org/legacy/ # This must be changed if testing deploys to test.pypi.org \ No newline at end of file diff --git a/.releaserc b/.releaserc index 3db0690e8..4ee525055 100644 --- a/.releaserc +++ b/.releaserc @@ -16,12 +16,6 @@ "message": "chore(release): ${nextRelease.version} release notes\n\n${nextRelease.notes}" } ], - [ - "semantic-release-pypi", - { - "repoUrl": "https://upload.pypi.org/legacy" - } - ], "@semantic-release/github" ] } diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000..07de284aa --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["setuptools", "wheel"] +build-backend = "setuptools.build_meta" \ No newline at end of file diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 29e579727..000000000 --- a/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[metadata] -version = 5.2.0 \ No newline at end of file diff --git a/setup.py b/setup.py index 5c615d5bb..f9034f9c2 100644 --- a/setup.py +++ b/setup.py @@ -14,61 +14,27 @@ # limitations under the License. from setuptools import setup -from setuptools.command.test import test as TestCommand -import os -import sys +from os import path +__version__ = '5.2.0' -if sys.argv[-1] == 'publish': - # test server - os.system('python setup.py register -r pypitest') - os.system('python setup.py sdist upload -r pypitest') - - # production server - os.system('python setup.py register -r pypi') - os.system('python setup.py sdist upload -r pypi') - sys.exit() - -# Convert README.md to README.rst for pypi -try: - from pypandoc import convert_file - - def read_md(f): - return convert_file(f, 'rst') - - # read_md = lambda f: convert(f, 'rst') -except: - print('warning: pypandoc module not found, ' - 'could not convert Markdown to RST') - - def read_md(f): - return open(f, 'rb').read().decode(encoding='utf-8') - # read_md = lambda f: open(f, 'rb').read().decode(encoding='utf-8') - - -class PyTest(TestCommand): - def finalize_options(self): - TestCommand.finalize_options(self) - self.test_args = ['--strict', '--verbose', '--tb=long', 'test'] - self.test_suite = True - - def run_tests(self): - import pytest - errcode = pytest.main(self.test_args) - sys.exit(errcode) - +# read contents of README file +this_directory = path.abspath(path.dirname(__file__)) +with open(path.join(this_directory, 'README.md'), encoding='utf-8') as file: + readme_file = file.read() setup(name='ibm-watson', + version=__version__, description='Client library to use the IBM Watson Services', + packages=['ibm_watson'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==1.1.0', 'ibm_cloud_sdk_core>=3.3.6, == 3.*'], + tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures'], license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core>=3.3.6, == 3.*'], - tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], - cmdclass={'test': PyTest}, author='IBM Watson', author_email='watdevex@us.ibm.com', - long_description=read_md('README.md'), + long_description=readme_file, + long_description_content_type='text/markdown', url='https://github.com/watson-developer-cloud/python-sdk', - packages=['ibm_watson'], include_package_data=True, keywords='language, vision, question and answer' + ' tone_analyzer, natural language classifier,' + @@ -81,7 +47,7 @@ def run_tests(self): 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', - 'Development Status :: 4 - Beta', + 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', From e513db271fae73c338b2f769009832c0e9bff850 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Mon, 28 Jun 2021 16:26:17 +0000 Subject: [PATCH 337/455] =?UTF-8?q?Bump=20version:=205.2.0=20=E2=86=92=205?= =?UTF-8?q?.2.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 9630647a6..ad22cb851 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.2.0 +current_version = 5.2.1 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index f279ec922..4dc2ef264 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '5.2.0' +__version__ = '5.2.1' diff --git a/setup.py b/setup.py index f9034f9c2..d8d42ea59 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '5.2.0' +__version__ = '5.2.1' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From a23a745fc569aaef0da645cb793baf6dfad22a70 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Mon, 28 Jun 2021 16:26:17 +0000 Subject: [PATCH 338/455] chore(release): 5.2.1 release notes ## [5.2.1](https://github.com/watson-developer-cloud/python-sdk/compare/v5.2.0...v5.2.1) (2021-06-28) ### Bug Fixes * **tts:** remove origin header from websocket request ([e151e82](https://github.com/watson-developer-cloud/python-sdk/commit/e151e8271f4ddc2d0217beec8e84896e0e44539f)) --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b11af880f..2f86b1ef8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [5.2.1](https://github.com/watson-developer-cloud/python-sdk/compare/v5.2.0...v5.2.1) (2021-06-28) + + +### Bug Fixes + +* **tts:** remove origin header from websocket request ([e151e82](https://github.com/watson-developer-cloud/python-sdk/commit/e151e8271f4ddc2d0217beec8e84896e0e44539f)) + # [5.2.0](https://github.com/watson-developer-cloud/python-sdk/compare/v5.1.0...v5.2.0) (2021-06-10) From 264807d7eb3287bbca56328496a477e042a9b2ca Mon Sep 17 00:00:00 2001 From: gabe-l-hart Date: Tue, 6 Jul 2021 11:13:39 -0600 Subject: [PATCH 339/455] fix: robustify the STT streaming results handling (#768) * fix: robustify the STT streaming results handling In the STT recognize_listener, the clause that handles 'results' or 'speaker_labels' was prone to index errors when the 'results' object returned by the service was empty. This can happen, so this change makes that logic safe to empty (or otherwise malformed) results. * Remove buggy extra call to on_hypothesis Co-authored-by: Mamoon Raja Co-authored-by: Angelo Paparazzi --- ibm_watson/websocket/recognize_listener.py | 27 ++++++++++++---------- 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index 3931a2529..21679760f 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -194,18 +194,21 @@ def on_data(self, ws, message, message_type, fin): # if in streaming elif 'results' in json_object or 'speaker_labels' in json_object: - hypothesis = '' - if 'results' in json_object: - hypothesis = json_object['results'][0]['alternatives'][0][ - 'transcript'] - b_final = (json_object['results'][0]['final'] is True) - transcripts = self.extract_transcripts( - json_object['results'][0]['alternatives']) - - if b_final: - self.callback.on_transcription(transcripts) - - self.callback.on_hypothesis(hypothesis) + # If results are present, extract the hypothesis and, if finalized, the full + # set of transcriptions and send them to the appropriate callbacks. + results = json_object.get('results') + if results: + b_final = (results[0].get('final') is True) + alternatives = results[0].get('alternatives') + if alternatives: + hypothesis = alternatives[0].get('transcript') + transcripts = self.extract_transcripts(alternatives) + if b_final: + self.callback.on_transcription(transcripts) + if hypothesis: + self.callback.on_hypothesis(hypothesis) + + # Always call the on_data callback if 'results' or 'speaker_labels' are present self.callback.on_data(json_object) def on_error(self, ws, error): From 09a379a6a66e8c98ae65b8fe5df28ea08de2c3d2 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 6 Jul 2021 17:25:52 +0000 Subject: [PATCH 340/455] =?UTF-8?q?Bump=20version:=205.2.1=20=E2=86=92=205?= =?UTF-8?q?.2.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index ad22cb851..2ab670222 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.2.1 +current_version = 5.2.2 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 4dc2ef264..7478af2c5 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '5.2.1' +__version__ = '5.2.2' diff --git a/setup.py b/setup.py index d8d42ea59..f3d671422 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '5.2.1' +__version__ = '5.2.2' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From 1eca9a163aceff8ff8e8dde5dbe85461324f72bf Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 6 Jul 2021 17:25:52 +0000 Subject: [PATCH 341/455] chore(release): 5.2.2 release notes ## [5.2.2](https://github.com/watson-developer-cloud/python-sdk/compare/v5.2.1...v5.2.2) (2021-07-06) ### Bug Fixes * robustify the STT streaming results handling ([#768](https://github.com/watson-developer-cloud/python-sdk/issues/768)) ([264807d](https://github.com/watson-developer-cloud/python-sdk/commit/264807d7eb3287bbca56328496a477e042a9b2ca)) --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f86b1ef8..248fa0ceb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## [5.2.2](https://github.com/watson-developer-cloud/python-sdk/compare/v5.2.1...v5.2.2) (2021-07-06) + + +### Bug Fixes + +* robustify the STT streaming results handling ([#768](https://github.com/watson-developer-cloud/python-sdk/issues/768)) ([264807d](https://github.com/watson-developer-cloud/python-sdk/commit/264807d7eb3287bbca56328496a477e042a9b2ca)) + ## [5.2.1](https://github.com/watson-developer-cloud/python-sdk/compare/v5.2.0...v5.2.1) (2021-06-28) From 18c1ddb214370a78ab11d5bf61ece1a9fd949a96 Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Mon, 26 Jul 2021 09:29:03 -0500 Subject: [PATCH 342/455] Update README.md --- README.md | 38 -------------------------------------- 1 file changed, 38 deletions(-) diff --git a/README.md b/README.md index 125aefa2a..2c399692a 100755 --- a/README.md +++ b/README.md @@ -11,41 +11,6 @@ Python client library to quickly get started with the various [Watson APIs][wdc] services. -
- Table of Contents - - * [Before you begin](#before-you-begin) - * [Installation](#installation) - * [Examples](#examples) - * [Discovery v2 only on CP4D](#discovery-v2-only-on-cp4d) - * [Running in IBM Cloud](#running-in-ibm-cloud) - * [Authentication](#authentication) - * [Getting credentials](#getting-credentials) - * [IAM](#iam) - * [Username and password](#username-and-password) - * [No Authentication](#no-authentication) - * [Python version](#python-version) - * [Changes for v1.0](#changes-for-v10) - * [Changes for v2.0](#changes-for-v20) - * [Changes for v3.0](#changes-for-v30) - * [Changes for v4.0](#changes-for-v40) - * [Migration](#migration) - * [Configuring the http client](#configuring-the-http-client-supported-from-v110) - * [Disable SSL certificate verification](#disable-ssl-certificate-verification) - * [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) - * [Dependencies](#dependencies) - * [License](#license) - * [Contributing](#contributing) - * [Featured Projects](#featured-projects) - -
- ## Announcements ### Updating endpoint URLs from watsonplatform.net Watson API endpoint URLs at watsonplatform.net are changing and will not work after 26 May 2021. Update your calls to use the newer endpoint URLs. For more information, see https://cloud.ibm.com/docs/watson?topic=watson-endpoint-change. @@ -104,9 +69,6 @@ For more details see [#405](https://github.com/watson-developer-cloud/python-sdk The [examples][examples] folder has basic and advanced examples. The examples within each service assume that you already have [service credentials](#getting-credentials). -## Discovery v2 only on CP4D -Discovery v2 is only available on Cloud Pak for Data. - ## Running in IBM Cloud If you run your app in IBM Cloud, the SDK gets credentials from the [`VCAP_SERVICES`][vcap_services] environment variable. From 67389b36495ab696a97e8f598e863d96aa97e418 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 19 Jul 2021 17:50:20 -0400 Subject: [PATCH 343/455] ci(release): change release commit messages to include skip c_i --- .bumpversion.cfg | 1 + .releaserc | 6 ------ 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 2ab670222..c28f36b6c 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,6 +1,7 @@ [bumpversion] current_version = 5.2.2 commit = True +message = Bump version: {current_version} → {new_version} [skip ci] [bumpversion:file:ibm_watson/version.py] search = __version__ = '{current_version}' diff --git a/.releaserc b/.releaserc index 4ee525055..1de8456e5 100644 --- a/.releaserc +++ b/.releaserc @@ -10,12 +10,6 @@ "prepareCmd": "bumpversion --allow-dirty --current-version ${lastRelease.version} --new-version ${nextRelease.version} patch" } ], - [ - "@semantic-release/git", - { - "message": "chore(release): ${nextRelease.version} release notes\n\n${nextRelease.notes}" - } - ], "@semantic-release/github" ] } From 204793ba128c6349890ff74ca499a05485e2e46a Mon Sep 17 00:00:00 2001 From: Ajiemar Santiago Date: Thu, 12 Aug 2021 11:20:28 -0500 Subject: [PATCH 344/455] docs: [skip ci] add nlc deprecation notice (#797) * docs: [skip ci] add nlc deprecation notice * docs: [skip ci] add space Co-authored-by: Watson Github Bot --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 2c399692a..1a9f3d543 100755 --- a/README.md +++ b/README.md @@ -12,6 +12,11 @@ Python client library to quickly get started with the various [Watson APIs][wdc] services. ## Announcements +### Natural Language Classifier deprecation +On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. + +As an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud that uses deep learning to extract data and insights from text such as keywords, categories, sentiment, emotion, and syntax, along with advanced multi-label text classification capabilities, to provide even richer insights for your business or industry. For more information, see [Migrating to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating). + ### Updating endpoint URLs from watsonplatform.net Watson API endpoint URLs at watsonplatform.net are changing and will not work after 26 May 2021. Update your calls to use the newer endpoint URLs. For more information, see https://cloud.ibm.com/docs/watson?topic=watson-endpoint-change. From 09149290dac7574c21d149861f13c8bc8ec06bcd Mon Sep 17 00:00:00 2001 From: Michael G Mosca Date: Wed, 25 Aug 2021 14:02:07 -0400 Subject: [PATCH 345/455] ci: fix --- .github/workflows/deploy.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index a8ca95413..268186eb5 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -63,6 +63,7 @@ jobs: pip3 install setuptools wheel twine build python -m build --sdist --outdir dist/ - name: Publish distribution to Test PyPI + continue-on-error: true uses: pypa/gh-action-pypi-publish@v1.4.2 # Try to update version tag every release with: password: ${{ secrets.PYPI_TOKEN }} From d1ec209484320c2a61c735721148a66f58e6f7b1 Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Wed, 18 Aug 2021 09:06:43 -0500 Subject: [PATCH 346/455] fix(nlc): add deprecation warning add deprecation warning to NLC constructor fix #9624 --- ibm_watson/natural_language_classifier_v1.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 16144ce72..c7675bd7b 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -84,6 +84,15 @@ def classify(self, classifier_id: str, text: str, :rtype: DetailedResponse with `dict` result representing a `Classification` object """ + print( + """ + On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. + The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. + Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. + For more information, see https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating + """ + ) + if classifier_id is None: raise ValueError('classifier_id must be provided') if text is None: From 3658ee856c3ddba77a64589631b4605ae3c8c86c Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Thu, 26 Aug 2021 09:55:51 -0500 Subject: [PATCH 347/455] fix(nlc): move deprecation warning move deprecation warning to within initalizer block --- ibm_watson/natural_language_classifier_v1.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index c7675bd7b..ed42033ff 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -45,6 +45,15 @@ class NaturalLanguageClassifierV1(BaseService): DEFAULT_SERVICE_URL = 'https://api.us-south.natural-language-classifier.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'natural_language_classifier' + print( + """ + On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. + The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. + Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. + For more information, see https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating + """ + ) + def __init__( self, authenticator: Authenticator = None, @@ -84,15 +93,6 @@ def classify(self, classifier_id: str, text: str, :rtype: DetailedResponse with `dict` result representing a `Classification` object """ - print( - """ - On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. - The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. - Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. - For more information, see https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating - """ - ) - if classifier_id is None: raise ValueError('classifier_id must be provided') if text is None: From 09a6dd4d7b26664cb92d8652f8d54ca96d9404a9 Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Thu, 26 Aug 2021 11:24:16 -0500 Subject: [PATCH 348/455] fix(nlc): move deprecation warning move deprecation warning within initalizer block --- ibm_watson/natural_language_classifier_v1.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index ed42033ff..4049ac1f9 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -45,15 +45,6 @@ class NaturalLanguageClassifierV1(BaseService): DEFAULT_SERVICE_URL = 'https://api.us-south.natural-language-classifier.watson.cloud.ibm.com' DEFAULT_SERVICE_NAME = 'natural_language_classifier' - print( - """ - On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. - The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. - Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. - For more information, see https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating - """ - ) - def __init__( self, authenticator: Authenticator = None, @@ -65,7 +56,15 @@ def __init__( :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - """ + """ + print( + """ + On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. + The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. + Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. + For more information, see https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating + """ + ) if not authenticator: authenticator = get_authenticator_from_environment(service_name) BaseService.__init__(self, From 04c5d2cae8b12c35df01b127d8d4051e6f5ae986 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 26 Aug 2021 17:33:07 +0000 Subject: [PATCH 349/455] =?UTF-8?q?Bump=20version:=205.2.2=20=E2=86=92=205?= =?UTF-8?q?.2.3=20[skip=20ci]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index c28f36b6c..08f707c39 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.2.2 +current_version = 5.2.3 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 7478af2c5..f9bc7375f 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '5.2.2' +__version__ = '5.2.3' diff --git a/setup.py b/setup.py index f3d671422..2c060053c 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '5.2.2' +__version__ = '5.2.3' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From 7810317ffde8bf3490da627a036a5586984de579 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 9 Sep 2021 15:46:07 -0400 Subject: [PATCH 350/455] chore(examples): update urls --- examples/assistant_v1.py | 2 +- examples/assistant_v2.py | 2 +- examples/compare_comply_v1.py | 2 +- examples/discovery_v1.py | 2 +- examples/language_translator_v3.py | 2 +- examples/natural_language_classifier_v1.py | 2 +- examples/natural_language_understanding_v1.py | 2 +- examples/speaker_text_to_speech.py | 2 +- examples/speech_to_text_v1.py | 2 +- examples/text_to_speech_v1.py | 2 +- examples/tone_analyzer_v3.py | 2 +- examples/visual_recognition_v3.py | 2 +- examples/visual_recognition_v4.py | 2 +- 13 files changed, 13 insertions(+), 13 deletions(-) diff --git a/examples/assistant_v1.py b/examples/assistant_v1.py index 77d49191e..2316e2d38 100644 --- a/examples/assistant_v1.py +++ b/examples/assistant_v1.py @@ -13,7 +13,7 @@ # Authentication via external config like VCAP_SERVICES assistant = AssistantV1(version='2018-07-10') -assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') +assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') ######################### # Workspaces diff --git a/examples/assistant_v2.py b/examples/assistant_v2.py index 90cd62728..af28a1c69 100644 --- a/examples/assistant_v2.py +++ b/examples/assistant_v2.py @@ -6,7 +6,7 @@ assistant = AssistantV2( version='2018-09-20', authenticator=authenticator) -assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') +assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') ######################### # Sessions diff --git a/examples/compare_comply_v1.py b/examples/compare_comply_v1.py index 81867d0c0..63e339860 100644 --- a/examples/compare_comply_v1.py +++ b/examples/compare_comply_v1.py @@ -8,7 +8,7 @@ compare_comply = CompareComplyV1( version='2018-03-23', authenticator=authenticator) -compare_comply.set_service_url('https://gateway.watsonplatform.net/compare-comply/api') +compare_comply.set_service_url('https://api.us-south.compare-comply.watson.cloud.ibm.com') print('Convert to HTML') contract = os.path.abspath('resources/contract_A.pdf') diff --git a/examples/discovery_v1.py b/examples/discovery_v1.py index 1bf1dad4d..4f32acf22 100644 --- a/examples/discovery_v1.py +++ b/examples/discovery_v1.py @@ -6,7 +6,7 @@ discovery = DiscoveryV1( version='2018-08-01', authenticator=authenticator) -discovery.set_service_url('https://gateway.watsonplatform.net/discovery/api') +discovery.set_service_url('https://api.us-south.discovery.watson.cloud.ibm.com') environments = discovery.list_environments().get_result() print(json.dumps(environments, indent=2)) diff --git a/examples/language_translator_v3.py b/examples/language_translator_v3.py index 12feb0b1d..da7aecf8f 100644 --- a/examples/language_translator_v3.py +++ b/examples/language_translator_v3.py @@ -7,7 +7,7 @@ language_translator = LanguageTranslatorV3( version='2018-05-01', authenticator=authenticator) -language_translator.set_service_url('https://gateway.watsonplatform.net/language-translator/api') +language_translator.set_service_url('https://api.us-south.language-translator.watson.cloud.ibm.com') ## Translate translation = language_translator.translate( diff --git a/examples/natural_language_classifier_v1.py b/examples/natural_language_classifier_v1.py index 3cf93c1f4..62457e509 100644 --- a/examples/natural_language_classifier_v1.py +++ b/examples/natural_language_classifier_v1.py @@ -6,7 +6,7 @@ authenticator = IAMAuthenticator('your_api_key') service = NaturalLanguageClassifierV1(authenticator=authenticator) -service.set_service_url('https://gateway.watsonplatform.net/natural-language-classifier/api') +service.set_service_url('https://api.us-south.natural-language-classifier.watson.cloud.ibm.com') classifiers = service.list_classifiers().get_result() print(json.dumps(classifiers, indent=2)) diff --git a/examples/natural_language_understanding_v1.py b/examples/natural_language_understanding_v1.py index 87449a6d2..570e74821 100644 --- a/examples/natural_language_understanding_v1.py +++ b/examples/natural_language_understanding_v1.py @@ -13,7 +13,7 @@ # Authentication via external config like VCAP_SERVICES service = NaturalLanguageUnderstandingV1( version='2018-03-16') -service.set_service_url('https://gateway.watsonplatform.net/natural-language-understanding/api') +service.set_service_url('https://api.us-south.natural-language-understanding.watson.cloud.ibm.com') response = service.analyze( text='Bruce Banner is the Hulk and Bruce Wayne is BATMAN! ' diff --git a/examples/speaker_text_to_speech.py b/examples/speaker_text_to_speech.py index 9faf6fb98..a75495dc0 100644 --- a/examples/speaker_text_to_speech.py +++ b/examples/speaker_text_to_speech.py @@ -12,7 +12,7 @@ authenticator = IAMAuthenticator('your_api_key') service = TextToSpeechV1(authenticator=authenticator) -service.set_service_url('https://stream.watsonplatform.net/speech-to-text/api') +service.set_service_url('https://api.us-south.speech-to-text.watson.cloud.ibm.com') class Play(object): """ diff --git a/examples/speech_to_text_v1.py b/examples/speech_to_text_v1.py index 083e7d961..e0b60a33b 100644 --- a/examples/speech_to_text_v1.py +++ b/examples/speech_to_text_v1.py @@ -7,7 +7,7 @@ authenticator = IAMAuthenticator('your_api_key') service = SpeechToTextV1(authenticator=authenticator) -service.set_service_url('https://stream.watsonplatform.net/speech-to-text/api') +service.set_service_url('https://api.us-south.speech-to-text.watson.cloud.ibm.com') models = service.list_models().get_result() print(json.dumps(models, indent=2)) diff --git a/examples/text_to_speech_v1.py b/examples/text_to_speech_v1.py index 22c28ec21..0571592df 100644 --- a/examples/text_to_speech_v1.py +++ b/examples/text_to_speech_v1.py @@ -7,7 +7,7 @@ authenticator = IAMAuthenticator('your_api_key') service = TextToSpeechV1(authenticator=authenticator) -service.set_service_url('https://stream.watsonplatform.net/text-to-speech/api') +service.set_service_url('https://api.us-south.text-to-speech.watson.cloud.ibm.com') voices = service.list_voices().get_result() print(json.dumps(voices, indent=2)) diff --git a/examples/tone_analyzer_v3.py b/examples/tone_analyzer_v3.py index bcd32adfd..db4833180 100755 --- a/examples/tone_analyzer_v3.py +++ b/examples/tone_analyzer_v3.py @@ -14,7 +14,7 @@ # Authentication via external config like VCAP_SERVICES service = ToneAnalyzerV3(version='2017-09-21') -service.set_service_url('https://gateway.watsonplatform.net/tone-analyzer/api') +service.set_service_url('https://api.us-south.tone-analyzer.watson.cloud.ibm.com') print("\ntone_chat() example 1:\n") utterances = [{ diff --git a/examples/visual_recognition_v3.py b/examples/visual_recognition_v3.py index 775edba73..01ddeb7b8 100644 --- a/examples/visual_recognition_v3.py +++ b/examples/visual_recognition_v3.py @@ -11,7 +11,7 @@ service = VisualRecognitionV3( '2018-03-19', authenticator=authenticator) -service.set_service_url('https://gateway.watsonplatform.net/visual-recognition/api') +service.set_service_url('https://api.us-south.visual-recognition.watson.cloud.ibm.com') # with open(abspath('resources/cars.zip'), 'rb') as cars, \ # open(abspath('resources/trucks.zip'), 'rb') as trucks: diff --git a/examples/visual_recognition_v4.py b/examples/visual_recognition_v4.py index 66c76aa03..5febf8986 100644 --- a/examples/visual_recognition_v4.py +++ b/examples/visual_recognition_v4.py @@ -9,7 +9,7 @@ service = VisualRecognitionV4( '2018-03-19', authenticator=authenticator) -service.set_service_url('https://gateway.watsonplatform.net/visual-recognition/api') +service.set_service_url('https://api.us-south.visual-recognition.watson.cloud.ibm.com') # create a classifier my_collection = service.create_collection( From c437e920e8c57f94aa29105a811462fcd5f32950 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 9 Sep 2021 15:47:26 -0400 Subject: [PATCH 351/455] test(unit/integration): update tests --- test/integration/test_discovery_v1.py | 3 +- test/unit/test_assistant_v1.py | 966 ++++++++++-------- test/unit/test_assistant_v2.py | 389 ++++--- test/unit/test_compare_comply_v1.py | 162 +-- test/unit/test_discovery_v1.py | 672 +++++++----- test/unit/test_discovery_v2.py | 312 +++--- test/unit/test_language_translator_v3.py | 62 +- .../test_natural_language_classifier_v1.py | 30 +- .../test_natural_language_understanding_v1.py | 335 +++--- test/unit/test_personality_insights_v3.py | 60 +- test/unit/test_speech_to_text_v1.py | 206 ++-- test/unit/test_text_to_speech_v1.py | 96 +- test/unit/test_tone_analyzer_v3.py | 28 +- test/unit/test_visual_recognition_v3.py | 46 +- test/unit/test_visual_recognition_v4.py | 126 ++- 15 files changed, 2079 insertions(+), 1414 deletions(-) diff --git a/test/integration/test_discovery_v1.py b/test/integration/test_discovery_v1.py index 6d842bd08..32428e00c 100644 --- a/test/integration/test_discovery_v1.py +++ b/test/integration/test_discovery_v1.py @@ -134,8 +134,7 @@ def test_queries(self): query_results = self.discovery.query( self.environment_id, self.collection_id, - filter='extracted_metadata.sha1::9181d244*', - return_fields='extracted_metadata.sha1').get_result() + filter='extracted_metadata.sha1::9181d244*').get_result() assert query_results is not None @pytest.mark.skip( diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 37db94d36..c2314b635 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -53,6 +53,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -65,7 +67,7 @@ def test_message_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -75,9 +77,9 @@ def test_message_all_params(self): # Construct a dict representation of a MessageInput model message_input_model = {} message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False + message_input_model['foo'] = 'testString' # Construct a dict representation of a RuntimeIntent model runtime_intent_model = {} @@ -149,7 +151,7 @@ def test_message_all_params(self): context_model['conversation_id'] = 'testString' context_model['system'] = {} context_model['metadata'] = message_context_metadata_model - context_model['foo'] = { 'foo': 'bar' } + context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeVisitedDetails model dialog_node_visited_details_model = {} @@ -200,18 +202,18 @@ def test_message_all_params(self): output_data_model['log_messages'] = [log_message_model] output_data_model['text'] = ['testString'] output_data_model['generic'] = [runtime_response_generic_model] - output_data_model['foo'] = { 'foo': 'bar' } + output_data_model['foo'] = 'testString' # Set up parameter values workspace_id = 'testString' input = message_input_model intents = [runtime_intent_model] entities = [runtime_entity_model] - alternate_intents = True + alternate_intents = False context = context_model output = output_data_model user_id = 'testString' - nodes_visited_details = True + nodes_visited_details = False # Invoke method response = _service.message( @@ -239,7 +241,7 @@ def test_message_all_params(self): assert req_body['input'] == message_input_model assert req_body['intents'] == [runtime_intent_model] assert req_body['entities'] == [runtime_entity_model] - assert req_body['alternate_intents'] == True + assert req_body['alternate_intents'] == False assert req_body['context'] == context_model assert req_body['output'] == output_data_model assert req_body['user_id'] == 'testString' @@ -252,7 +254,7 @@ def test_message_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -280,7 +282,7 @@ def test_message_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -320,6 +322,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -332,7 +336,7 @@ def test_bulk_classify_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -369,7 +373,7 @@ def test_bulk_classify_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -397,7 +401,7 @@ def test_bulk_classify_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -437,6 +441,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -449,7 +455,7 @@ def test_list_workspaces_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -458,10 +464,10 @@ def test_list_workspaces_all_params(self): # Set up parameter values page_limit = 38 - include_count = True + include_count = False sort = 'name' cursor = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.list_workspaces( @@ -493,7 +499,7 @@ def test_list_workspaces_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -516,7 +522,7 @@ def test_list_workspaces_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -542,6 +548,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -554,7 +562,7 @@ def test_create_workspace_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -593,12 +601,12 @@ def test_create_workspace_all_params(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model dialog_node_next_step_model = {} @@ -634,7 +642,7 @@ def test_create_workspace_all_params(self): dialog_node_model['digress_out'] = 'allow_returning' dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' - dialog_node_model['disambiguation_opt_out'] = True + dialog_node_model['disambiguation_opt_out'] = False # Construct a dict representation of a Counterexample model counterexample_model = {} @@ -648,7 +656,7 @@ def test_create_workspace_all_params(self): workspace_system_settings_disambiguation_model = {} workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' - workspace_system_settings_disambiguation_model['enabled'] = True + workspace_system_settings_disambiguation_model['enabled'] = False workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' workspace_system_settings_disambiguation_model['randomize'] = True workspace_system_settings_disambiguation_model['max_suggestions'] = 1 @@ -656,19 +664,19 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a WorkspaceSystemSettingsSystemEntities model workspace_system_settings_system_entities_model = {} - workspace_system_settings_system_entities_model['enabled'] = True + workspace_system_settings_system_entities_model['enabled'] = False # Construct a dict representation of a WorkspaceSystemSettingsOffTopic model workspace_system_settings_off_topic_model = {} - workspace_system_settings_off_topic_model['enabled'] = True + workspace_system_settings_off_topic_model['enabled'] = False # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model workspace_system_settings_model['human_agent_assist'] = {} - workspace_system_settings_model['spelling_suggestions'] = True - workspace_system_settings_model['spelling_auto_correct'] = True + workspace_system_settings_model['spelling_suggestions'] = False + workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model @@ -722,12 +730,12 @@ def test_create_workspace_all_params(self): dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] metadata = {} - learning_opt_out = True + learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] intents = [create_intent_model] entities = [create_entity_model] - include_audit = True + include_audit = False # Invoke method response = _service.create_workspace( @@ -761,7 +769,7 @@ def test_create_workspace_all_params(self): assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] assert req_body['metadata'] == {} - assert req_body['learning_opt_out'] == True + assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] assert req_body['intents'] == [create_intent_model] @@ -775,7 +783,7 @@ def test_create_workspace_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -798,7 +806,7 @@ def test_create_workspace_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -824,6 +832,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -836,7 +846,7 @@ def test_get_workspace_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -845,8 +855,8 @@ def test_get_workspace_all_params(self): # Set up parameter values workspace_id = 'testString' - export = True - include_audit = True + export = False + include_audit = False sort = 'stable' # Invoke method @@ -876,7 +886,7 @@ def test_get_workspace_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -904,7 +914,7 @@ def test_get_workspace_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -934,6 +944,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -946,7 +958,7 @@ def test_update_workspace_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -985,12 +997,12 @@ def test_update_workspace_all_params(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model dialog_node_next_step_model = {} @@ -1026,7 +1038,7 @@ def test_update_workspace_all_params(self): dialog_node_model['digress_out'] = 'allow_returning' dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' - dialog_node_model['disambiguation_opt_out'] = True + dialog_node_model['disambiguation_opt_out'] = False # Construct a dict representation of a Counterexample model counterexample_model = {} @@ -1040,7 +1052,7 @@ def test_update_workspace_all_params(self): workspace_system_settings_disambiguation_model = {} workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' - workspace_system_settings_disambiguation_model['enabled'] = True + workspace_system_settings_disambiguation_model['enabled'] = False workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' workspace_system_settings_disambiguation_model['randomize'] = True workspace_system_settings_disambiguation_model['max_suggestions'] = 1 @@ -1048,19 +1060,19 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a WorkspaceSystemSettingsSystemEntities model workspace_system_settings_system_entities_model = {} - workspace_system_settings_system_entities_model['enabled'] = True + workspace_system_settings_system_entities_model['enabled'] = False # Construct a dict representation of a WorkspaceSystemSettingsOffTopic model workspace_system_settings_off_topic_model = {} - workspace_system_settings_off_topic_model['enabled'] = True + workspace_system_settings_off_topic_model['enabled'] = False # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model workspace_system_settings_model['human_agent_assist'] = {} - workspace_system_settings_model['spelling_suggestions'] = True - workspace_system_settings_model['spelling_auto_correct'] = True + workspace_system_settings_model['spelling_suggestions'] = False + workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model @@ -1115,13 +1127,13 @@ def test_update_workspace_all_params(self): dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] metadata = {} - learning_opt_out = True + learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] intents = [create_intent_model] entities = [create_entity_model] - append = True - include_audit = True + append = False + include_audit = False # Invoke method response = _service.update_workspace( @@ -1158,7 +1170,7 @@ def test_update_workspace_all_params(self): assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] assert req_body['metadata'] == {} - assert req_body['learning_opt_out'] == True + assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] assert req_body['intents'] == [create_intent_model] @@ -1172,7 +1184,7 @@ def test_update_workspace_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -1200,7 +1212,7 @@ def test_update_workspace_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "learning_opt_out": true, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": {"anyKey": "anyValue"}}, "spelling_suggestions": true, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -1230,6 +1242,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1304,6 +1318,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1325,12 +1341,12 @@ def test_list_intents_all_params(self): # Set up parameter values workspace_id = 'testString' - export = True + export = False page_limit = 38 - include_count = True + include_count = False sort = 'intent' cursor = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.list_intents( @@ -1423,6 +1439,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1457,7 +1475,7 @@ def test_create_intent_all_params(self): intent = 'testString' description = 'testString' examples = [example_model] - include_audit = True + include_audit = False # Invoke method response = _service.create_intent( @@ -1583,6 +1601,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1605,8 +1625,8 @@ def test_get_intent_all_params(self): # Set up parameter values workspace_id = 'testString' intent = 'testString' - export = True - include_audit = True + export = False + include_audit = False # Invoke method response = _service.get_intent( @@ -1696,6 +1716,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1731,8 +1753,8 @@ def test_update_intent_all_params(self): new_intent = 'testString' new_description = 'testString' new_examples = [example_model] - append = True - include_audit = True + append = False + include_audit = False # Invoke method response = _service.update_intent( @@ -1864,6 +1886,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1942,6 +1966,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1965,10 +1991,10 @@ def test_list_examples_all_params(self): workspace_id = 'testString' intent = 'testString' page_limit = 38 - include_count = True + include_count = False sort = 'text' cursor = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.list_examples( @@ -2064,6 +2090,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2093,7 +2121,7 @@ def test_create_example_all_params(self): intent = 'testString' text = 'testString' mentions = [mention_model] - include_audit = True + include_audit = False # Invoke method response = _service.create_example( @@ -2208,6 +2236,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2231,7 +2261,7 @@ def test_get_example_all_params(self): workspace_id = 'testString' intent = 'testString' text = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.get_example( @@ -2324,6 +2354,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2354,7 +2386,7 @@ def test_update_example_all_params(self): text = 'testString' new_text = 'testString' new_mentions = [mention_model] - include_audit = True + include_audit = False # Invoke method response = _service.update_example( @@ -2473,6 +2505,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2555,6 +2589,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2577,10 +2613,10 @@ def test_list_counterexamples_all_params(self): # Set up parameter values workspace_id = 'testString' page_limit = 38 - include_count = True + include_count = False sort = 'text' cursor = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.list_counterexamples( @@ -2671,6 +2707,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2693,7 +2731,7 @@ def test_create_counterexample_all_params(self): # Set up parameter values workspace_id = 'testString' text = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.create_counterexample( @@ -2787,6 +2825,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2809,7 +2849,7 @@ def test_get_counterexample_all_params(self): # Set up parameter values workspace_id = 'testString' text = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.get_counterexample( @@ -2897,6 +2937,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2920,7 +2962,7 @@ def test_update_counterexample_all_params(self): workspace_id = 'testString' text = 'testString' new_text = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.update_counterexample( @@ -3018,6 +3060,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3096,6 +3140,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3108,7 +3154,7 @@ def test_list_entities_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3117,12 +3163,12 @@ def test_list_entities_all_params(self): # Set up parameter values workspace_id = 'testString' - export = True + export = False page_limit = 38 - include_count = True + include_count = False sort = 'entity' cursor = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.list_entities( @@ -3157,7 +3203,7 @@ def test_list_entities_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3185,7 +3231,7 @@ def test_list_entities_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3215,6 +3261,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3227,7 +3275,7 @@ def test_create_entity_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3249,7 +3297,7 @@ def test_create_entity_all_params(self): metadata = {} fuzzy_match = True values = [create_value_model] - include_audit = True + include_audit = False # Invoke method response = _service.create_entity( @@ -3286,7 +3334,7 @@ def test_create_entity_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3339,7 +3387,7 @@ def test_create_entity_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3383,6 +3431,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3395,7 +3445,7 @@ def test_get_entity_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3405,8 +3455,8 @@ def test_get_entity_all_params(self): # Set up parameter values workspace_id = 'testString' entity = 'testString' - export = True - include_audit = True + export = False + include_audit = False # Invoke method response = _service.get_entity( @@ -3434,7 +3484,7 @@ def test_get_entity_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3464,7 +3514,7 @@ def test_get_entity_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -3496,6 +3546,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3508,7 +3560,7 @@ def test_update_entity_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3531,8 +3583,8 @@ def test_update_entity_all_params(self): new_metadata = {} new_fuzzy_match = True new_values = [create_value_model] - append = True - include_audit = True + append = False + include_audit = False # Invoke method response = _service.update_entity( @@ -3572,7 +3624,7 @@ def test_update_entity_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3627,7 +3679,7 @@ def test_update_entity_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -3672,6 +3724,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3750,6 +3804,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3772,8 +3828,8 @@ def test_list_mentions_all_params(self): # Set up parameter values workspace_id = 'testString' entity = 'testString' - export = True - include_audit = True + export = False + include_audit = False # Invoke method response = _service.list_mentions( @@ -3873,6 +3929,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3885,7 +3943,7 @@ def test_list_values_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3895,12 +3953,12 @@ def test_list_values_all_params(self): # Set up parameter values workspace_id = 'testString' entity = 'testString' - export = True + export = False page_limit = 38 - include_count = True + include_count = False sort = 'value' cursor = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.list_values( @@ -3936,7 +3994,7 @@ def test_list_values_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3966,7 +4024,7 @@ def test_list_values_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -3998,6 +4056,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4010,7 +4070,7 @@ def test_create_value_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4025,7 +4085,7 @@ def test_create_value_all_params(self): type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] - include_audit = True + include_audit = False # Invoke method response = _service.create_value( @@ -4063,7 +4123,7 @@ def test_create_value_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4110,7 +4170,7 @@ def test_create_value_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4148,6 +4208,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4160,7 +4222,7 @@ def test_get_value_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4171,8 +4233,8 @@ def test_get_value_all_params(self): workspace_id = 'testString' entity = 'testString' value = 'testString' - export = True - include_audit = True + export = False + include_audit = False # Invoke method response = _service.get_value( @@ -4201,7 +4263,7 @@ def test_get_value_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4233,7 +4295,7 @@ def test_get_value_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -4267,6 +4329,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4279,7 +4343,7 @@ def test_update_value_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4295,8 +4359,8 @@ def test_update_value_all_params(self): new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] - append = True - include_audit = True + append = False + include_audit = False # Invoke method response = _service.update_value( @@ -4337,7 +4401,7 @@ def test_update_value_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4386,7 +4450,7 @@ def test_update_value_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -4425,6 +4489,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4507,6 +4573,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4531,10 +4599,10 @@ def test_list_synonyms_all_params(self): entity = 'testString' value = 'testString' page_limit = 38 - include_count = True + include_count = False sort = 'synonym' cursor = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.list_synonyms( @@ -4635,6 +4703,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4659,7 +4729,7 @@ def test_create_synonym_all_params(self): entity = 'testString' value = 'testString' synonym = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.create_synonym( @@ -4763,6 +4833,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4787,7 +4859,7 @@ def test_get_synonym_all_params(self): entity = 'testString' value = 'testString' synonym = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.get_synonym( @@ -4885,6 +4957,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4910,7 +4984,7 @@ def test_update_synonym_all_params(self): value = 'testString' synonym = 'testString' new_synonym = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.update_synonym( @@ -5018,6 +5092,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5104,6 +5180,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5116,7 +5194,7 @@ def test_list_dialog_nodes_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5126,10 +5204,10 @@ def test_list_dialog_nodes_all_params(self): # Set up parameter values workspace_id = 'testString' page_limit = 38 - include_count = True + include_count = False sort = 'dialog_node' cursor = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.list_dialog_nodes( @@ -5162,7 +5240,7 @@ def test_list_dialog_nodes_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5190,7 +5268,7 @@ def test_list_dialog_nodes_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5220,6 +5298,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5232,7 +5312,7 @@ def test_create_dialog_node_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -5271,12 +5351,12 @@ def test_create_dialog_node_all_params(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model dialog_node_next_step_model = {} @@ -5312,8 +5392,8 @@ def test_create_dialog_node_all_params(self): digress_out = 'allow_returning' digress_out_slots = 'not_allowed' user_label = 'testString' - disambiguation_opt_out = True - include_audit = True + disambiguation_opt_out = False + include_audit = False # Invoke method response = _service.create_dialog_node( @@ -5368,7 +5448,7 @@ def test_create_dialog_node_all_params(self): assert req_body['digress_out'] == 'allow_returning' assert req_body['digress_out_slots'] == 'not_allowed' assert req_body['user_label'] == 'testString' - assert req_body['disambiguation_opt_out'] == True + assert req_body['disambiguation_opt_out'] == False @responses.activate @@ -5378,7 +5458,7 @@ def test_create_dialog_node_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -5417,12 +5497,12 @@ def test_create_dialog_node_required_params(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model dialog_node_next_step_model = {} @@ -5458,7 +5538,7 @@ def test_create_dialog_node_required_params(self): digress_out = 'allow_returning' digress_out_slots = 'not_allowed' user_label = 'testString' - disambiguation_opt_out = True + disambiguation_opt_out = False # Invoke method response = _service.create_dialog_node( @@ -5508,7 +5588,7 @@ def test_create_dialog_node_required_params(self): assert req_body['digress_out'] == 'allow_returning' assert req_body['digress_out_slots'] == 'not_allowed' assert req_body['user_label'] == 'testString' - assert req_body['disambiguation_opt_out'] == True + assert req_body['disambiguation_opt_out'] == False @responses.activate @@ -5518,7 +5598,7 @@ def test_create_dialog_node_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -5557,12 +5637,12 @@ def test_create_dialog_node_value_error(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model dialog_node_next_step_model = {} @@ -5598,7 +5678,7 @@ def test_create_dialog_node_value_error(self): digress_out = 'allow_returning' digress_out_slots = 'not_allowed' user_label = 'testString' - disambiguation_opt_out = True + disambiguation_opt_out = False # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -5621,6 +5701,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5633,7 +5715,7 @@ def test_get_dialog_node_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5643,7 +5725,7 @@ def test_get_dialog_node_all_params(self): # Set up parameter values workspace_id = 'testString' dialog_node = 'testString' - include_audit = True + include_audit = False # Invoke method response = _service.get_dialog_node( @@ -5669,7 +5751,7 @@ def test_get_dialog_node_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5699,7 +5781,7 @@ def test_get_dialog_node_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5731,6 +5813,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5743,7 +5827,7 @@ def test_update_dialog_node_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -5782,12 +5866,12 @@ def test_update_dialog_node_all_params(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model dialog_node_next_step_model = {} @@ -5824,8 +5908,8 @@ def test_update_dialog_node_all_params(self): new_digress_out = 'allow_returning' new_digress_out_slots = 'not_allowed' new_user_label = 'testString' - new_disambiguation_opt_out = True - include_audit = True + new_disambiguation_opt_out = False + include_audit = False # Invoke method response = _service.update_dialog_node( @@ -5881,7 +5965,7 @@ def test_update_dialog_node_all_params(self): assert req_body['digress_out'] == 'allow_returning' assert req_body['digress_out_slots'] == 'not_allowed' assert req_body['user_label'] == 'testString' - assert req_body['disambiguation_opt_out'] == True + assert req_body['disambiguation_opt_out'] == False @responses.activate @@ -5891,7 +5975,7 @@ def test_update_dialog_node_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -5930,12 +6014,12 @@ def test_update_dialog_node_required_params(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model dialog_node_next_step_model = {} @@ -5972,7 +6056,7 @@ def test_update_dialog_node_required_params(self): new_digress_out = 'allow_returning' new_digress_out_slots = 'not_allowed' new_user_label = 'testString' - new_disambiguation_opt_out = True + new_disambiguation_opt_out = False # Invoke method response = _service.update_dialog_node( @@ -6023,7 +6107,7 @@ def test_update_dialog_node_required_params(self): assert req_body['digress_out'] == 'allow_returning' assert req_body['digress_out_slots'] == 'not_allowed' assert req_body['user_label'] == 'testString' - assert req_body['disambiguation_opt_out'] == True + assert req_body['disambiguation_opt_out'] == False @responses.activate @@ -6033,7 +6117,7 @@ def test_update_dialog_node_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}, "modifiers": {"overwrite": false}}, "context": {"integrations": {"mapKey": {"mapKey": {"anyKey": "anyValue"}}}}, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": true, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -6072,12 +6156,12 @@ def test_update_dialog_node_value_error(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model dialog_node_next_step_model = {} @@ -6114,7 +6198,7 @@ def test_update_dialog_node_value_error(self): new_digress_out = 'allow_returning' new_digress_out_slots = 'not_allowed' new_user_label = 'testString' - new_disambiguation_opt_out = True + new_disambiguation_opt_out = False # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -6137,6 +6221,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6215,6 +6301,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6227,7 +6315,7 @@ def test_list_logs_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6270,7 +6358,7 @@ def test_list_logs_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6298,7 +6386,7 @@ def test_list_logs_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6328,6 +6416,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6340,7 +6430,7 @@ def test_list_all_logs_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6381,7 +6471,7 @@ def test_list_all_logs_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6413,7 +6503,7 @@ def test_list_all_logs_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": {"anyKey": "anyValue"}}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": true, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6453,6 +6543,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6522,7 +6614,7 @@ def test_delete_user_data_value_error(self): # Start of Model Tests ############################################################################## # region -class TestAgentAvailabilityMessage(): +class TestModel_AgentAvailabilityMessage(): """ Test Class for AgentAvailabilityMessage """ @@ -6551,7 +6643,7 @@ def test_agent_availability_message_serialization(self): agent_availability_message_model_json2 = agent_availability_message_model.to_dict() assert agent_availability_message_model_json2 == agent_availability_message_model_json -class TestBulkClassifyOutput(): +class TestModel_BulkClassifyOutput(): """ Test Class for BulkClassifyOutput """ @@ -6641,7 +6733,7 @@ def test_bulk_classify_output_serialization(self): bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() assert bulk_classify_output_model_json2 == bulk_classify_output_model_json -class TestBulkClassifyResponse(): +class TestModel_BulkClassifyResponse(): """ Test Class for BulkClassifyResponse """ @@ -6734,7 +6826,7 @@ def test_bulk_classify_response_serialization(self): bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() assert bulk_classify_response_model_json2 == bulk_classify_response_model_json -class TestBulkClassifyUtterance(): +class TestModel_BulkClassifyUtterance(): """ Test Class for BulkClassifyUtterance """ @@ -6763,7 +6855,7 @@ def test_bulk_classify_utterance_serialization(self): bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json -class TestCaptureGroup(): +class TestModel_CaptureGroup(): """ Test Class for CaptureGroup """ @@ -6793,7 +6885,7 @@ def test_capture_group_serialization(self): capture_group_model_json2 = capture_group_model.to_dict() assert capture_group_model_json2 == capture_group_model_json -class TestChannelTransferInfo(): +class TestModel_ChannelTransferInfo(): """ Test Class for ChannelTransferInfo """ @@ -6830,7 +6922,7 @@ def test_channel_transfer_info_serialization(self): channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() assert channel_transfer_info_model_json2 == channel_transfer_info_model_json -class TestChannelTransferTarget(): +class TestModel_ChannelTransferTarget(): """ Test Class for ChannelTransferTarget """ @@ -6864,7 +6956,7 @@ def test_channel_transfer_target_serialization(self): channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() assert channel_transfer_target_model_json2 == channel_transfer_target_model_json -class TestChannelTransferTargetChat(): +class TestModel_ChannelTransferTargetChat(): """ Test Class for ChannelTransferTargetChat """ @@ -6893,7 +6985,7 @@ def test_channel_transfer_target_chat_serialization(self): channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json -class TestContext(): +class TestModel_Context(): """ Test Class for Context """ @@ -6914,7 +7006,7 @@ def test_context_serialization(self): context_model_json['conversation_id'] = 'testString' context_model_json['system'] = {} context_model_json['metadata'] = message_context_metadata_model - context_model_json['foo'] = { 'foo': 'bar' } + context_model_json['foo'] = 'testString' # Construct a model instance of Context by calling from_dict on the json representation context_model = Context.from_dict(context_model_json) @@ -6931,7 +7023,17 @@ def test_context_serialization(self): context_model_json2 = context_model.to_dict() assert context_model_json2 == context_model_json -class TestCounterexample(): + # Test get_properties and set_properties methods. + context_model.set_properties({}) + actual_dict = context_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': 'testString'} + context_model.set_properties(expected_dict) + actual_dict = context_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_Counterexample(): """ Test Class for Counterexample """ @@ -6944,8 +7046,8 @@ def test_counterexample_serialization(self): # Construct a json representation of a Counterexample model counterexample_model_json = {} counterexample_model_json['text'] = 'testString' - counterexample_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - counterexample_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + counterexample_model_json['created'] = "2019-01-01T12:00:00Z" + counterexample_model_json['updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of Counterexample by calling from_dict on the json representation counterexample_model = Counterexample.from_dict(counterexample_model_json) @@ -6962,7 +7064,7 @@ def test_counterexample_serialization(self): counterexample_model_json2 = counterexample_model.to_dict() assert counterexample_model_json2 == counterexample_model_json -class TestCounterexampleCollection(): +class TestModel_CounterexampleCollection(): """ Test Class for CounterexampleCollection """ @@ -6976,8 +7078,8 @@ def test_counterexample_collection_serialization(self): counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - counterexample_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + counterexample_model['created'] = "2019-01-01T12:00:00Z" + counterexample_model['updated'] = "2019-01-01T12:00:00Z" pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -7007,7 +7109,7 @@ def test_counterexample_collection_serialization(self): counterexample_collection_model_json2 = counterexample_collection_model.to_dict() assert counterexample_collection_model_json2 == counterexample_collection_model_json -class TestCreateEntity(): +class TestModel_CreateEntity(): """ Test Class for CreateEntity """ @@ -7025,8 +7127,8 @@ def test_create_entity_serialization(self): create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] - create_value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - create_value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + create_value_model['created'] = "2019-01-01T12:00:00Z" + create_value_model['updated'] = "2019-01-01T12:00:00Z" # Construct a json representation of a CreateEntity model create_entity_model_json = {} @@ -7034,8 +7136,8 @@ def test_create_entity_serialization(self): create_entity_model_json['description'] = 'testString' create_entity_model_json['metadata'] = {} create_entity_model_json['fuzzy_match'] = True - create_entity_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - create_entity_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + create_entity_model_json['created'] = "2019-01-01T12:00:00Z" + create_entity_model_json['updated'] = "2019-01-01T12:00:00Z" create_entity_model_json['values'] = [create_value_model] # Construct a model instance of CreateEntity by calling from_dict on the json representation @@ -7053,7 +7155,7 @@ def test_create_entity_serialization(self): create_entity_model_json2 = create_entity_model.to_dict() assert create_entity_model_json2 == create_entity_model_json -class TestCreateIntent(): +class TestModel_CreateIntent(): """ Test Class for CreateIntent """ @@ -7072,15 +7174,15 @@ def test_create_intent_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['created'] = "2019-01-01T12:00:00Z" + example_model['updated'] = "2019-01-01T12:00:00Z" # Construct a json representation of a CreateIntent model create_intent_model_json = {} create_intent_model_json['intent'] = 'testString' create_intent_model_json['description'] = 'testString' - create_intent_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - create_intent_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + create_intent_model_json['created'] = "2019-01-01T12:00:00Z" + create_intent_model_json['updated'] = "2019-01-01T12:00:00Z" create_intent_model_json['examples'] = [example_model] # Construct a model instance of CreateIntent by calling from_dict on the json representation @@ -7098,7 +7200,7 @@ def test_create_intent_serialization(self): create_intent_model_json2 = create_intent_model.to_dict() assert create_intent_model_json2 == create_intent_model_json -class TestCreateValue(): +class TestModel_CreateValue(): """ Test Class for CreateValue """ @@ -7115,8 +7217,8 @@ def test_create_value_serialization(self): create_value_model_json['type'] = 'synonyms' create_value_model_json['synonyms'] = ['testString'] create_value_model_json['patterns'] = ['testString'] - create_value_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - create_value_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + create_value_model_json['created'] = "2019-01-01T12:00:00Z" + create_value_model_json['updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of CreateValue by calling from_dict on the json representation create_value_model = CreateValue.from_dict(create_value_model_json) @@ -7133,7 +7235,7 @@ def test_create_value_serialization(self): create_value_model_json2 = create_value_model.to_dict() assert create_value_model_json2 == create_value_model_json -class TestDialogNode(): +class TestModel_DialogNode(): """ Test Class for DialogNode """ @@ -7170,11 +7272,11 @@ def test_dialog_node_serialization(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' @@ -7208,10 +7310,10 @@ def test_dialog_node_serialization(self): dialog_node_model_json['digress_out'] = 'allow_returning' dialog_node_model_json['digress_out_slots'] = 'not_allowed' dialog_node_model_json['user_label'] = 'testString' - dialog_node_model_json['disambiguation_opt_out'] = True + dialog_node_model_json['disambiguation_opt_out'] = False dialog_node_model_json['disabled'] = True - dialog_node_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - dialog_node_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + dialog_node_model_json['created'] = "2019-01-01T12:00:00Z" + dialog_node_model_json['updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of DialogNode by calling from_dict on the json representation dialog_node_model = DialogNode.from_dict(dialog_node_model_json) @@ -7228,7 +7330,7 @@ def test_dialog_node_serialization(self): dialog_node_model_json2 = dialog_node_model.to_dict() assert dialog_node_model_json2 == dialog_node_model_json -class TestDialogNodeAction(): +class TestModel_DialogNodeAction(): """ Test Class for DialogNodeAction """ @@ -7261,7 +7363,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json2 = dialog_node_action_model.to_dict() assert dialog_node_action_model_json2 == dialog_node_action_model_json -class TestDialogNodeCollection(): +class TestModel_DialogNodeCollection(): """ Test Class for DialogNodeCollection """ @@ -7298,11 +7400,11 @@ def test_dialog_node_collection_serialization(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' @@ -7335,10 +7437,10 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['digress_out'] = 'allow_returning' dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' - dialog_node_model['disambiguation_opt_out'] = True + dialog_node_model['disambiguation_opt_out'] = False dialog_node_model['disabled'] = True - dialog_node_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - dialog_node_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + dialog_node_model['created'] = "2019-01-01T12:00:00Z" + dialog_node_model['updated'] = "2019-01-01T12:00:00Z" pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -7368,7 +7470,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_collection_model_json2 = dialog_node_collection_model.to_dict() assert dialog_node_collection_model_json2 == dialog_node_collection_model_json -class TestDialogNodeContext(): +class TestModel_DialogNodeContext(): """ Test Class for DialogNodeContext """ @@ -7381,7 +7483,7 @@ def test_dialog_node_context_serialization(self): # Construct a json representation of a DialogNodeContext model dialog_node_context_model_json = {} dialog_node_context_model_json['integrations'] = {} - dialog_node_context_model_json['foo'] = { 'foo': 'bar' } + dialog_node_context_model_json['foo'] = 'testString' # Construct a model instance of DialogNodeContext by calling from_dict on the json representation dialog_node_context_model = DialogNodeContext.from_dict(dialog_node_context_model_json) @@ -7398,7 +7500,17 @@ def test_dialog_node_context_serialization(self): dialog_node_context_model_json2 = dialog_node_context_model.to_dict() assert dialog_node_context_model_json2 == dialog_node_context_model_json -class TestDialogNodeNextStep(): + # Test get_properties and set_properties methods. + dialog_node_context_model.set_properties({}) + actual_dict = dialog_node_context_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': 'testString'} + dialog_node_context_model.set_properties(expected_dict) + actual_dict = dialog_node_context_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_DialogNodeNextStep(): """ Test Class for DialogNodeNextStep """ @@ -7429,7 +7541,7 @@ def test_dialog_node_next_step_serialization(self): dialog_node_next_step_model_json2 = dialog_node_next_step_model.to_dict() assert dialog_node_next_step_model_json2 == dialog_node_next_step_model_json -class TestDialogNodeOutput(): +class TestModel_DialogNodeOutput(): """ Test Class for DialogNodeOutput """ @@ -7467,7 +7579,7 @@ def test_dialog_node_output_serialization(self): dialog_node_output_model_json['generic'] = [dialog_node_output_generic_model] dialog_node_output_model_json['integrations'] = {} dialog_node_output_model_json['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model_json['foo'] = { 'foo': 'bar' } + dialog_node_output_model_json['foo'] = 'testString' # Construct a model instance of DialogNodeOutput by calling from_dict on the json representation dialog_node_output_model = DialogNodeOutput.from_dict(dialog_node_output_model_json) @@ -7484,7 +7596,17 @@ def test_dialog_node_output_serialization(self): dialog_node_output_model_json2 = dialog_node_output_model.to_dict() assert dialog_node_output_model_json2 == dialog_node_output_model_json -class TestDialogNodeOutputConnectToAgentTransferInfo(): + # Test get_properties and set_properties methods. + dialog_node_output_model.set_properties({}) + actual_dict = dialog_node_output_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': 'testString'} + dialog_node_output_model.set_properties(expected_dict) + actual_dict = dialog_node_output_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_DialogNodeOutputConnectToAgentTransferInfo(): """ Test Class for DialogNodeOutputConnectToAgentTransferInfo """ @@ -7513,7 +7635,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json -class TestDialogNodeOutputModifiers(): +class TestModel_DialogNodeOutputModifiers(): """ Test Class for DialogNodeOutputModifiers """ @@ -7542,7 +7664,7 @@ def test_dialog_node_output_modifiers_serialization(self): dialog_node_output_modifiers_model_json2 = dialog_node_output_modifiers_model.to_dict() assert dialog_node_output_modifiers_model_json2 == dialog_node_output_modifiers_model_json -class TestDialogNodeOutputOptionsElement(): +class TestModel_DialogNodeOutputOptionsElement(): """ Test Class for DialogNodeOutputOptionsElement """ @@ -7556,11 +7678,11 @@ def test_dialog_node_output_options_element_serialization(self): message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -7641,7 +7763,7 @@ def test_dialog_node_output_options_element_serialization(self): dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json -class TestDialogNodeOutputOptionsElementValue(): +class TestModel_DialogNodeOutputOptionsElementValue(): """ Test Class for DialogNodeOutputOptionsElementValue """ @@ -7655,11 +7777,11 @@ def test_dialog_node_output_options_element_value_serialization(self): message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -7736,7 +7858,7 @@ def test_dialog_node_output_options_element_value_serialization(self): dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json -class TestDialogNodeOutputTextValuesElement(): +class TestModel_DialogNodeOutputTextValuesElement(): """ Test Class for DialogNodeOutputTextValuesElement """ @@ -7765,7 +7887,7 @@ def test_dialog_node_output_text_values_element_serialization(self): dialog_node_output_text_values_element_model_json2 = dialog_node_output_text_values_element_model.to_dict() assert dialog_node_output_text_values_element_model_json2 == dialog_node_output_text_values_element_model_json -class TestDialogNodeVisitedDetails(): +class TestModel_DialogNodeVisitedDetails(): """ Test Class for DialogNodeVisitedDetails """ @@ -7796,7 +7918,7 @@ def test_dialog_node_visited_details_serialization(self): dialog_node_visited_details_model_json2 = dialog_node_visited_details_model.to_dict() assert dialog_node_visited_details_model_json2 == dialog_node_visited_details_model_json -class TestDialogSuggestion(): +class TestModel_DialogSuggestion(): """ Test Class for DialogSuggestion """ @@ -7810,11 +7932,11 @@ def test_dialog_suggestion_serialization(self): message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -7897,7 +8019,7 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() assert dialog_suggestion_model_json2 == dialog_suggestion_model_json -class TestDialogSuggestionValue(): +class TestModel_DialogSuggestionValue(): """ Test Class for DialogSuggestionValue """ @@ -7911,11 +8033,11 @@ def test_dialog_suggestion_value_serialization(self): message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -7992,7 +8114,7 @@ def test_dialog_suggestion_value_serialization(self): dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json -class TestEntity(): +class TestModel_Entity(): """ Test Class for Entity """ @@ -8010,8 +8132,8 @@ def test_entity_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model['created'] = "2019-01-01T12:00:00Z" + value_model['updated'] = "2019-01-01T12:00:00Z" # Construct a json representation of a Entity model entity_model_json = {} @@ -8019,8 +8141,8 @@ def test_entity_serialization(self): entity_model_json['description'] = 'testString' entity_model_json['metadata'] = {} entity_model_json['fuzzy_match'] = True - entity_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - entity_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + entity_model_json['created'] = "2019-01-01T12:00:00Z" + entity_model_json['updated'] = "2019-01-01T12:00:00Z" entity_model_json['values'] = [value_model] # Construct a model instance of Entity by calling from_dict on the json representation @@ -8038,7 +8160,7 @@ def test_entity_serialization(self): entity_model_json2 = entity_model.to_dict() assert entity_model_json2 == entity_model_json -class TestEntityCollection(): +class TestModel_EntityCollection(): """ Test Class for EntityCollection """ @@ -8056,16 +8178,16 @@ def test_entity_collection_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model['created'] = "2019-01-01T12:00:00Z" + value_model['updated'] = "2019-01-01T12:00:00Z" entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' entity_model['metadata'] = {} entity_model['fuzzy_match'] = True - entity_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - entity_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + entity_model['created'] = "2019-01-01T12:00:00Z" + entity_model['updated'] = "2019-01-01T12:00:00Z" entity_model['values'] = [value_model] pagination_model = {} # Pagination @@ -8096,7 +8218,7 @@ def test_entity_collection_serialization(self): entity_collection_model_json2 = entity_collection_model.to_dict() assert entity_collection_model_json2 == entity_collection_model_json -class TestEntityMention(): +class TestModel_EntityMention(): """ Test Class for EntityMention """ @@ -8127,7 +8249,7 @@ def test_entity_mention_serialization(self): entity_mention_model_json2 = entity_mention_model.to_dict() assert entity_mention_model_json2 == entity_mention_model_json -class TestEntityMentionCollection(): +class TestModel_EntityMentionCollection(): """ Test Class for EntityMentionCollection """ @@ -8172,7 +8294,7 @@ def test_entity_mention_collection_serialization(self): entity_mention_collection_model_json2 = entity_mention_collection_model.to_dict() assert entity_mention_collection_model_json2 == entity_mention_collection_model_json -class TestExample(): +class TestModel_Example(): """ Test Class for Example """ @@ -8192,8 +8314,8 @@ def test_example_serialization(self): example_model_json = {} example_model_json['text'] = 'testString' example_model_json['mentions'] = [mention_model] - example_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - example_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model_json['created'] = "2019-01-01T12:00:00Z" + example_model_json['updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of Example by calling from_dict on the json representation example_model = Example.from_dict(example_model_json) @@ -8210,7 +8332,7 @@ def test_example_serialization(self): example_model_json2 = example_model.to_dict() assert example_model_json2 == example_model_json -class TestExampleCollection(): +class TestModel_ExampleCollection(): """ Test Class for ExampleCollection """ @@ -8229,8 +8351,8 @@ def test_example_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['created'] = "2019-01-01T12:00:00Z" + example_model['updated'] = "2019-01-01T12:00:00Z" pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -8260,7 +8382,7 @@ def test_example_collection_serialization(self): example_collection_model_json2 = example_collection_model.to_dict() assert example_collection_model_json2 == example_collection_model_json -class TestIntent(): +class TestModel_Intent(): """ Test Class for Intent """ @@ -8279,15 +8401,15 @@ def test_intent_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['created'] = "2019-01-01T12:00:00Z" + example_model['updated'] = "2019-01-01T12:00:00Z" # Construct a json representation of a Intent model intent_model_json = {} intent_model_json['intent'] = 'testString' intent_model_json['description'] = 'testString' - intent_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - intent_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + intent_model_json['created'] = "2019-01-01T12:00:00Z" + intent_model_json['updated'] = "2019-01-01T12:00:00Z" intent_model_json['examples'] = [example_model] # Construct a model instance of Intent by calling from_dict on the json representation @@ -8305,7 +8427,7 @@ def test_intent_serialization(self): intent_model_json2 = intent_model.to_dict() assert intent_model_json2 == intent_model_json -class TestIntentCollection(): +class TestModel_IntentCollection(): """ Test Class for IntentCollection """ @@ -8324,14 +8446,14 @@ def test_intent_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['created'] = "2019-01-01T12:00:00Z" + example_model['updated'] = "2019-01-01T12:00:00Z" intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - intent_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + intent_model['created'] = "2019-01-01T12:00:00Z" + intent_model['updated'] = "2019-01-01T12:00:00Z" intent_model['examples'] = [example_model] pagination_model = {} # Pagination @@ -8362,7 +8484,7 @@ def test_intent_collection_serialization(self): intent_collection_model_json2 = intent_collection_model.to_dict() assert intent_collection_model_json2 == intent_collection_model_json -class TestLog(): +class TestModel_Log(): """ Test Class for Log """ @@ -8376,11 +8498,11 @@ def test_log_serialization(self): message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -8444,7 +8566,7 @@ def test_log_serialization(self): context_model['conversation_id'] = 'testString' context_model['system'] = {} context_model['metadata'] = message_context_metadata_model - context_model['foo'] = { 'foo': 'bar' } + context_model['foo'] = 'testString' dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' @@ -8487,7 +8609,7 @@ def test_log_serialization(self): output_data_model['log_messages'] = [log_message_model] output_data_model['text'] = ['testString'] output_data_model['generic'] = [runtime_response_generic_model] - output_data_model['foo'] = { 'foo': 'bar' } + output_data_model['foo'] = 'testString' dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -8500,7 +8622,7 @@ def test_log_serialization(self): message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] message_request_model['entities'] = [runtime_entity_model] - message_request_model['alternate_intents'] = True + message_request_model['alternate_intents'] = False message_request_model['context'] = context_model message_request_model['output'] = output_data_model message_request_model['actions'] = [dialog_node_action_model] @@ -8510,7 +8632,7 @@ def test_log_serialization(self): message_response_model['input'] = message_input_model message_response_model['intents'] = [runtime_intent_model] message_response_model['entities'] = [runtime_entity_model] - message_response_model['alternate_intents'] = True + message_response_model['alternate_intents'] = False message_response_model['context'] = context_model message_response_model['output'] = output_data_model message_response_model['actions'] = [dialog_node_action_model] @@ -8541,7 +8663,7 @@ def test_log_serialization(self): log_model_json2 = log_model.to_dict() assert log_model_json2 == log_model_json -class TestLogCollection(): +class TestModel_LogCollection(): """ Test Class for LogCollection """ @@ -8555,11 +8677,11 @@ def test_log_collection_serialization(self): message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -8623,7 +8745,7 @@ def test_log_collection_serialization(self): context_model['conversation_id'] = 'testString' context_model['system'] = {} context_model['metadata'] = message_context_metadata_model - context_model['foo'] = { 'foo': 'bar' } + context_model['foo'] = 'testString' dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' @@ -8666,7 +8788,7 @@ def test_log_collection_serialization(self): output_data_model['log_messages'] = [log_message_model] output_data_model['text'] = ['testString'] output_data_model['generic'] = [runtime_response_generic_model] - output_data_model['foo'] = { 'foo': 'bar' } + output_data_model['foo'] = 'testString' dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -8679,7 +8801,7 @@ def test_log_collection_serialization(self): message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] message_request_model['entities'] = [runtime_entity_model] - message_request_model['alternate_intents'] = True + message_request_model['alternate_intents'] = False message_request_model['context'] = context_model message_request_model['output'] = output_data_model message_request_model['actions'] = [dialog_node_action_model] @@ -8689,7 +8811,7 @@ def test_log_collection_serialization(self): message_response_model['input'] = message_input_model message_response_model['intents'] = [runtime_intent_model] message_response_model['entities'] = [runtime_entity_model] - message_response_model['alternate_intents'] = True + message_response_model['alternate_intents'] = False message_response_model['context'] = context_model message_response_model['output'] = output_data_model message_response_model['actions'] = [dialog_node_action_model] @@ -8729,7 +8851,7 @@ def test_log_collection_serialization(self): log_collection_model_json2 = log_collection_model.to_dict() assert log_collection_model_json2 == log_collection_model_json -class TestLogMessage(): +class TestModel_LogMessage(): """ Test Class for LogMessage """ @@ -8767,7 +8889,7 @@ def test_log_message_serialization(self): log_message_model_json2 = log_message_model.to_dict() assert log_message_model_json2 == log_message_model_json -class TestLogMessageSource(): +class TestModel_LogMessageSource(): """ Test Class for LogMessageSource """ @@ -8797,7 +8919,7 @@ def test_log_message_source_serialization(self): log_message_source_model_json2 = log_message_source_model.to_dict() assert log_message_source_model_json2 == log_message_source_model_json -class TestLogPagination(): +class TestModel_LogPagination(): """ Test Class for LogPagination """ @@ -8828,7 +8950,7 @@ def test_log_pagination_serialization(self): log_pagination_model_json2 = log_pagination_model.to_dict() assert log_pagination_model_json2 == log_pagination_model_json -class TestMention(): +class TestModel_Mention(): """ Test Class for Mention """ @@ -8858,7 +8980,7 @@ def test_mention_serialization(self): mention_model_json2 = mention_model.to_dict() assert mention_model_json2 == mention_model_json -class TestMessageContextMetadata(): +class TestModel_MessageContextMetadata(): """ Test Class for MessageContextMetadata """ @@ -8888,7 +9010,7 @@ def test_message_context_metadata_serialization(self): message_context_metadata_model_json2 = message_context_metadata_model.to_dict() assert message_context_metadata_model_json2 == message_context_metadata_model_json -class TestMessageInput(): +class TestModel_MessageInput(): """ Test Class for MessageInput """ @@ -8901,11 +9023,11 @@ def test_message_input_serialization(self): # Construct a json representation of a MessageInput model message_input_model_json = {} message_input_model_json['text'] = 'testString' - message_input_model_json['spelling_suggestions'] = True - message_input_model_json['spelling_auto_correct'] = True + message_input_model_json['spelling_suggestions'] = False + message_input_model_json['spelling_auto_correct'] = False message_input_model_json['suggested_text'] = 'testString' message_input_model_json['original_text'] = 'testString' - message_input_model_json['foo'] = { 'foo': 'bar' } + message_input_model_json['foo'] = 'testString' # Construct a model instance of MessageInput by calling from_dict on the json representation message_input_model = MessageInput.from_dict(message_input_model_json) @@ -8922,7 +9044,17 @@ def test_message_input_serialization(self): message_input_model_json2 = message_input_model.to_dict() assert message_input_model_json2 == message_input_model_json -class TestMessageRequest(): + # Test get_properties and set_properties methods. + message_input_model.set_properties({}) + actual_dict = message_input_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': 'testString'} + message_input_model.set_properties(expected_dict) + actual_dict = message_input_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_MessageRequest(): """ Test Class for MessageRequest """ @@ -8936,11 +9068,11 @@ def test_message_request_serialization(self): message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -9004,7 +9136,7 @@ def test_message_request_serialization(self): context_model['conversation_id'] = 'testString' context_model['system'] = {} context_model['metadata'] = message_context_metadata_model - context_model['foo'] = { 'foo': 'bar' } + context_model['foo'] = 'testString' dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' @@ -9047,7 +9179,7 @@ def test_message_request_serialization(self): output_data_model['log_messages'] = [log_message_model] output_data_model['text'] = ['testString'] output_data_model['generic'] = [runtime_response_generic_model] - output_data_model['foo'] = { 'foo': 'bar' } + output_data_model['foo'] = 'testString' dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -9061,7 +9193,7 @@ def test_message_request_serialization(self): message_request_model_json['input'] = message_input_model message_request_model_json['intents'] = [runtime_intent_model] message_request_model_json['entities'] = [runtime_entity_model] - message_request_model_json['alternate_intents'] = True + message_request_model_json['alternate_intents'] = False message_request_model_json['context'] = context_model message_request_model_json['output'] = output_data_model message_request_model_json['actions'] = [dialog_node_action_model] @@ -9082,7 +9214,7 @@ def test_message_request_serialization(self): message_request_model_json2 = message_request_model.to_dict() assert message_request_model_json2 == message_request_model_json -class TestMessageResponse(): +class TestModel_MessageResponse(): """ Test Class for MessageResponse """ @@ -9096,11 +9228,11 @@ def test_message_response_serialization(self): message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -9164,7 +9296,7 @@ def test_message_response_serialization(self): context_model['conversation_id'] = 'testString' context_model['system'] = {} context_model['metadata'] = message_context_metadata_model - context_model['foo'] = { 'foo': 'bar' } + context_model['foo'] = 'testString' dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' @@ -9207,7 +9339,7 @@ def test_message_response_serialization(self): output_data_model['log_messages'] = [log_message_model] output_data_model['text'] = ['testString'] output_data_model['generic'] = [runtime_response_generic_model] - output_data_model['foo'] = { 'foo': 'bar' } + output_data_model['foo'] = 'testString' dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -9221,7 +9353,7 @@ def test_message_response_serialization(self): message_response_model_json['input'] = message_input_model message_response_model_json['intents'] = [runtime_intent_model] message_response_model_json['entities'] = [runtime_entity_model] - message_response_model_json['alternate_intents'] = True + message_response_model_json['alternate_intents'] = False message_response_model_json['context'] = context_model message_response_model_json['output'] = output_data_model message_response_model_json['actions'] = [dialog_node_action_model] @@ -9242,7 +9374,7 @@ def test_message_response_serialization(self): message_response_model_json2 = message_response_model.to_dict() assert message_response_model_json2 == message_response_model_json -class TestOutputData(): +class TestModel_OutputData(): """ Test Class for OutputData """ @@ -9271,11 +9403,11 @@ def test_output_data_serialization(self): message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -9358,7 +9490,7 @@ def test_output_data_serialization(self): output_data_model_json['log_messages'] = [log_message_model] output_data_model_json['text'] = ['testString'] output_data_model_json['generic'] = [runtime_response_generic_model] - output_data_model_json['foo'] = { 'foo': 'bar' } + output_data_model_json['foo'] = 'testString' # Construct a model instance of OutputData by calling from_dict on the json representation output_data_model = OutputData.from_dict(output_data_model_json) @@ -9375,7 +9507,17 @@ def test_output_data_serialization(self): output_data_model_json2 = output_data_model.to_dict() assert output_data_model_json2 == output_data_model_json -class TestPagination(): + # Test get_properties and set_properties methods. + output_data_model.set_properties({}) + actual_dict = output_data_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': 'testString'} + output_data_model.set_properties(expected_dict) + actual_dict = output_data_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_Pagination(): """ Test Class for Pagination """ @@ -9409,7 +9551,7 @@ def test_pagination_serialization(self): pagination_model_json2 = pagination_model.to_dict() assert pagination_model_json2 == pagination_model_json -class TestResponseGenericChannel(): +class TestModel_ResponseGenericChannel(): """ Test Class for ResponseGenericChannel """ @@ -9438,7 +9580,7 @@ def test_response_generic_channel_serialization(self): response_generic_channel_model_json2 = response_generic_channel_model.to_dict() assert response_generic_channel_model_json2 == response_generic_channel_model_json -class TestRuntimeEntity(): +class TestModel_RuntimeEntity(): """ Test Class for RuntimeEntity """ @@ -9516,7 +9658,7 @@ def test_runtime_entity_serialization(self): runtime_entity_model_json2 = runtime_entity_model.to_dict() assert runtime_entity_model_json2 == runtime_entity_model_json -class TestRuntimeEntityAlternative(): +class TestModel_RuntimeEntityAlternative(): """ Test Class for RuntimeEntityAlternative """ @@ -9546,7 +9688,7 @@ def test_runtime_entity_alternative_serialization(self): runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json -class TestRuntimeEntityInterpretation(): +class TestModel_RuntimeEntityInterpretation(): """ Test Class for RuntimeEntityInterpretation """ @@ -9600,7 +9742,7 @@ def test_runtime_entity_interpretation_serialization(self): runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json -class TestRuntimeEntityRole(): +class TestModel_RuntimeEntityRole(): """ Test Class for RuntimeEntityRole """ @@ -9629,7 +9771,7 @@ def test_runtime_entity_role_serialization(self): runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() assert runtime_entity_role_model_json2 == runtime_entity_role_model_json -class TestRuntimeIntent(): +class TestModel_RuntimeIntent(): """ Test Class for RuntimeIntent """ @@ -9659,7 +9801,7 @@ def test_runtime_intent_serialization(self): runtime_intent_model_json2 = runtime_intent_model.to_dict() assert runtime_intent_model_json2 == runtime_intent_model_json -class TestSynonym(): +class TestModel_Synonym(): """ Test Class for Synonym """ @@ -9672,8 +9814,8 @@ def test_synonym_serialization(self): # Construct a json representation of a Synonym model synonym_model_json = {} synonym_model_json['synonym'] = 'testString' - synonym_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - synonym_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + synonym_model_json['created'] = "2019-01-01T12:00:00Z" + synonym_model_json['updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of Synonym by calling from_dict on the json representation synonym_model = Synonym.from_dict(synonym_model_json) @@ -9690,7 +9832,7 @@ def test_synonym_serialization(self): synonym_model_json2 = synonym_model.to_dict() assert synonym_model_json2 == synonym_model_json -class TestSynonymCollection(): +class TestModel_SynonymCollection(): """ Test Class for SynonymCollection """ @@ -9704,8 +9846,8 @@ def test_synonym_collection_serialization(self): synonym_model = {} # Synonym synonym_model['synonym'] = 'testString' - synonym_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - synonym_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + synonym_model['created'] = "2019-01-01T12:00:00Z" + synonym_model['updated'] = "2019-01-01T12:00:00Z" pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -9735,7 +9877,7 @@ def test_synonym_collection_serialization(self): synonym_collection_model_json2 = synonym_collection_model.to_dict() assert synonym_collection_model_json2 == synonym_collection_model_json -class TestValue(): +class TestModel_Value(): """ Test Class for Value """ @@ -9752,8 +9894,8 @@ def test_value_serialization(self): value_model_json['type'] = 'synonyms' value_model_json['synonyms'] = ['testString'] value_model_json['patterns'] = ['testString'] - value_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - value_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model_json['created'] = "2019-01-01T12:00:00Z" + value_model_json['updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of Value by calling from_dict on the json representation value_model = Value.from_dict(value_model_json) @@ -9770,7 +9912,7 @@ def test_value_serialization(self): value_model_json2 = value_model.to_dict() assert value_model_json2 == value_model_json -class TestValueCollection(): +class TestModel_ValueCollection(): """ Test Class for ValueCollection """ @@ -9788,8 +9930,8 @@ def test_value_collection_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model['created'] = "2019-01-01T12:00:00Z" + value_model['updated'] = "2019-01-01T12:00:00Z" pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -9819,7 +9961,7 @@ def test_value_collection_serialization(self): value_collection_model_json2 = value_collection_model.to_dict() assert value_collection_model_json2 == value_collection_model_json -class TestWebhook(): +class TestModel_Webhook(): """ Test Class for Webhook """ @@ -9856,7 +9998,7 @@ def test_webhook_serialization(self): webhook_model_json2 = webhook_model.to_dict() assert webhook_model_json2 == webhook_model_json -class TestWebhookHeader(): +class TestModel_WebhookHeader(): """ Test Class for WebhookHeader """ @@ -9886,7 +10028,7 @@ def test_webhook_header_serialization(self): webhook_header_model_json2 = webhook_header_model.to_dict() assert webhook_header_model_json2 == webhook_header_model_json -class TestWorkspace(): +class TestModel_Workspace(): """ Test Class for Workspace """ @@ -9923,11 +10065,11 @@ def test_workspace_serialization(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' @@ -9960,15 +10102,15 @@ def test_workspace_serialization(self): dialog_node_model['digress_out'] = 'allow_returning' dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' - dialog_node_model['disambiguation_opt_out'] = True + dialog_node_model['disambiguation_opt_out'] = False dialog_node_model['disabled'] = True - dialog_node_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - dialog_node_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + dialog_node_model['created'] = "2019-01-01T12:00:00Z" + dialog_node_model['updated'] = "2019-01-01T12:00:00Z" counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - counterexample_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + counterexample_model['created'] = "2019-01-01T12:00:00Z" + counterexample_model['updated'] = "2019-01-01T12:00:00Z" workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True @@ -9976,24 +10118,24 @@ def test_workspace_serialization(self): workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' - workspace_system_settings_disambiguation_model['enabled'] = True + workspace_system_settings_disambiguation_model['enabled'] = False workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' workspace_system_settings_disambiguation_model['randomize'] = True workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities - workspace_system_settings_system_entities_model['enabled'] = True + workspace_system_settings_system_entities_model['enabled'] = False workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic - workspace_system_settings_off_topic_model['enabled'] = True + workspace_system_settings_off_topic_model['enabled'] = False workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model workspace_system_settings_model['human_agent_assist'] = {} - workspace_system_settings_model['spelling_suggestions'] = True - workspace_system_settings_model['spelling_auto_correct'] = True + workspace_system_settings_model['spelling_suggestions'] = False + workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model @@ -10013,14 +10155,14 @@ def test_workspace_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['created'] = "2019-01-01T12:00:00Z" + example_model['updated'] = "2019-01-01T12:00:00Z" intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - intent_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + intent_model['created'] = "2019-01-01T12:00:00Z" + intent_model['updated'] = "2019-01-01T12:00:00Z" intent_model['examples'] = [example_model] value_model = {} # Value @@ -10029,16 +10171,16 @@ def test_workspace_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model['created'] = "2019-01-01T12:00:00Z" + value_model['updated'] = "2019-01-01T12:00:00Z" entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' entity_model['metadata'] = {} entity_model['fuzzy_match'] = True - entity_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - entity_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + entity_model['created'] = "2019-01-01T12:00:00Z" + entity_model['updated'] = "2019-01-01T12:00:00Z" entity_model['values'] = [value_model] # Construct a json representation of a Workspace model @@ -10049,10 +10191,10 @@ def test_workspace_serialization(self): workspace_model_json['workspace_id'] = 'testString' workspace_model_json['dialog_nodes'] = [dialog_node_model] workspace_model_json['counterexamples'] = [counterexample_model] - workspace_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - workspace_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + workspace_model_json['created'] = "2019-01-01T12:00:00Z" + workspace_model_json['updated'] = "2019-01-01T12:00:00Z" workspace_model_json['metadata'] = {} - workspace_model_json['learning_opt_out'] = True + workspace_model_json['learning_opt_out'] = False workspace_model_json['system_settings'] = workspace_system_settings_model workspace_model_json['status'] = 'Non Existent' workspace_model_json['webhooks'] = [webhook_model] @@ -10074,7 +10216,7 @@ def test_workspace_serialization(self): workspace_model_json2 = workspace_model.to_dict() assert workspace_model_json2 == workspace_model_json -class TestWorkspaceCollection(): +class TestModel_WorkspaceCollection(): """ Test Class for WorkspaceCollection """ @@ -10111,11 +10253,11 @@ def test_workspace_collection_serialization(self): dialog_node_output_model['generic'] = [dialog_node_output_generic_model] dialog_node_output_model['integrations'] = {} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model - dialog_node_output_model['foo'] = { 'foo': 'bar' } + dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext dialog_node_context_model['integrations'] = {} - dialog_node_context_model['foo'] = { 'foo': 'bar' } + dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' @@ -10148,15 +10290,15 @@ def test_workspace_collection_serialization(self): dialog_node_model['digress_out'] = 'allow_returning' dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' - dialog_node_model['disambiguation_opt_out'] = True + dialog_node_model['disambiguation_opt_out'] = False dialog_node_model['disabled'] = True - dialog_node_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - dialog_node_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + dialog_node_model['created'] = "2019-01-01T12:00:00Z" + dialog_node_model['updated'] = "2019-01-01T12:00:00Z" counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - counterexample_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + counterexample_model['created'] = "2019-01-01T12:00:00Z" + counterexample_model['updated'] = "2019-01-01T12:00:00Z" workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True @@ -10164,24 +10306,24 @@ def test_workspace_collection_serialization(self): workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' - workspace_system_settings_disambiguation_model['enabled'] = True + workspace_system_settings_disambiguation_model['enabled'] = False workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' workspace_system_settings_disambiguation_model['randomize'] = True workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities - workspace_system_settings_system_entities_model['enabled'] = True + workspace_system_settings_system_entities_model['enabled'] = False workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic - workspace_system_settings_off_topic_model['enabled'] = True + workspace_system_settings_off_topic_model['enabled'] = False workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model workspace_system_settings_model['human_agent_assist'] = {} - workspace_system_settings_model['spelling_suggestions'] = True - workspace_system_settings_model['spelling_auto_correct'] = True + workspace_system_settings_model['spelling_suggestions'] = False + workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model @@ -10201,14 +10343,14 @@ def test_workspace_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + example_model['created'] = "2019-01-01T12:00:00Z" + example_model['updated'] = "2019-01-01T12:00:00Z" intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - intent_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + intent_model['created'] = "2019-01-01T12:00:00Z" + intent_model['updated'] = "2019-01-01T12:00:00Z" intent_model['examples'] = [example_model] value_model = {} # Value @@ -10217,16 +10359,16 @@ def test_workspace_collection_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - value_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + value_model['created'] = "2019-01-01T12:00:00Z" + value_model['updated'] = "2019-01-01T12:00:00Z" entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' entity_model['metadata'] = {} entity_model['fuzzy_match'] = True - entity_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - entity_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + entity_model['created'] = "2019-01-01T12:00:00Z" + entity_model['updated'] = "2019-01-01T12:00:00Z" entity_model['values'] = [value_model] workspace_model = {} # Workspace @@ -10236,10 +10378,10 @@ def test_workspace_collection_serialization(self): workspace_model['workspace_id'] = 'testString' workspace_model['dialog_nodes'] = [dialog_node_model] workspace_model['counterexamples'] = [counterexample_model] - workspace_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - workspace_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + workspace_model['created'] = "2019-01-01T12:00:00Z" + workspace_model['updated'] = "2019-01-01T12:00:00Z" workspace_model['metadata'] = {} - workspace_model['learning_opt_out'] = True + workspace_model['learning_opt_out'] = False workspace_model['system_settings'] = workspace_system_settings_model workspace_model['status'] = 'Non Existent' workspace_model['webhooks'] = [webhook_model] @@ -10274,7 +10416,7 @@ def test_workspace_collection_serialization(self): workspace_collection_model_json2 = workspace_collection_model.to_dict() assert workspace_collection_model_json2 == workspace_collection_model_json -class TestWorkspaceSystemSettings(): +class TestModel_WorkspaceSystemSettings(): """ Test Class for WorkspaceSystemSettings """ @@ -10292,25 +10434,25 @@ def test_workspace_system_settings_serialization(self): workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' - workspace_system_settings_disambiguation_model['enabled'] = True + workspace_system_settings_disambiguation_model['enabled'] = False workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' workspace_system_settings_disambiguation_model['randomize'] = True workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities - workspace_system_settings_system_entities_model['enabled'] = True + workspace_system_settings_system_entities_model['enabled'] = False workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic - workspace_system_settings_off_topic_model['enabled'] = True + workspace_system_settings_off_topic_model['enabled'] = False # Construct a json representation of a WorkspaceSystemSettings model workspace_system_settings_model_json = {} workspace_system_settings_model_json['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model_json['disambiguation'] = workspace_system_settings_disambiguation_model workspace_system_settings_model_json['human_agent_assist'] = {} - workspace_system_settings_model_json['spelling_suggestions'] = True - workspace_system_settings_model_json['spelling_auto_correct'] = True + workspace_system_settings_model_json['spelling_suggestions'] = False + workspace_system_settings_model_json['spelling_auto_correct'] = False workspace_system_settings_model_json['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model_json['off_topic'] = workspace_system_settings_off_topic_model @@ -10329,7 +10471,7 @@ def test_workspace_system_settings_serialization(self): workspace_system_settings_model_json2 = workspace_system_settings_model.to_dict() assert workspace_system_settings_model_json2 == workspace_system_settings_model_json -class TestWorkspaceSystemSettingsDisambiguation(): +class TestModel_WorkspaceSystemSettingsDisambiguation(): """ Test Class for WorkspaceSystemSettingsDisambiguation """ @@ -10343,7 +10485,7 @@ def test_workspace_system_settings_disambiguation_serialization(self): workspace_system_settings_disambiguation_model_json = {} workspace_system_settings_disambiguation_model_json['prompt'] = 'testString' workspace_system_settings_disambiguation_model_json['none_of_the_above_prompt'] = 'testString' - workspace_system_settings_disambiguation_model_json['enabled'] = True + workspace_system_settings_disambiguation_model_json['enabled'] = False workspace_system_settings_disambiguation_model_json['sensitivity'] = 'auto' workspace_system_settings_disambiguation_model_json['randomize'] = True workspace_system_settings_disambiguation_model_json['max_suggestions'] = 1 @@ -10364,7 +10506,7 @@ def test_workspace_system_settings_disambiguation_serialization(self): workspace_system_settings_disambiguation_model_json2 = workspace_system_settings_disambiguation_model.to_dict() assert workspace_system_settings_disambiguation_model_json2 == workspace_system_settings_disambiguation_model_json -class TestWorkspaceSystemSettingsOffTopic(): +class TestModel_WorkspaceSystemSettingsOffTopic(): """ Test Class for WorkspaceSystemSettingsOffTopic """ @@ -10376,7 +10518,7 @@ def test_workspace_system_settings_off_topic_serialization(self): # Construct a json representation of a WorkspaceSystemSettingsOffTopic model workspace_system_settings_off_topic_model_json = {} - workspace_system_settings_off_topic_model_json['enabled'] = True + workspace_system_settings_off_topic_model_json['enabled'] = False # Construct a model instance of WorkspaceSystemSettingsOffTopic by calling from_dict on the json representation workspace_system_settings_off_topic_model = WorkspaceSystemSettingsOffTopic.from_dict(workspace_system_settings_off_topic_model_json) @@ -10393,7 +10535,7 @@ def test_workspace_system_settings_off_topic_serialization(self): workspace_system_settings_off_topic_model_json2 = workspace_system_settings_off_topic_model.to_dict() assert workspace_system_settings_off_topic_model_json2 == workspace_system_settings_off_topic_model_json -class TestWorkspaceSystemSettingsSystemEntities(): +class TestModel_WorkspaceSystemSettingsSystemEntities(): """ Test Class for WorkspaceSystemSettingsSystemEntities """ @@ -10405,7 +10547,7 @@ def test_workspace_system_settings_system_entities_serialization(self): # Construct a json representation of a WorkspaceSystemSettingsSystemEntities model workspace_system_settings_system_entities_model_json = {} - workspace_system_settings_system_entities_model_json['enabled'] = True + workspace_system_settings_system_entities_model_json['enabled'] = False # Construct a model instance of WorkspaceSystemSettingsSystemEntities by calling from_dict on the json representation workspace_system_settings_system_entities_model = WorkspaceSystemSettingsSystemEntities.from_dict(workspace_system_settings_system_entities_model_json) @@ -10422,7 +10564,7 @@ def test_workspace_system_settings_system_entities_serialization(self): workspace_system_settings_system_entities_model_json2 = workspace_system_settings_system_entities_model.to_dict() assert workspace_system_settings_system_entities_model_json2 == workspace_system_settings_system_entities_model_json -class TestWorkspaceSystemSettingsTooling(): +class TestModel_WorkspaceSystemSettingsTooling(): """ Test Class for WorkspaceSystemSettingsTooling """ @@ -10451,7 +10593,7 @@ def test_workspace_system_settings_tooling_serialization(self): workspace_system_settings_tooling_model_json2 = workspace_system_settings_tooling_model.to_dict() assert workspace_system_settings_tooling_model_json2 == workspace_system_settings_tooling_model_json -class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer(): +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer(): """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer """ @@ -10497,7 +10639,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_channel_tra dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json -class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent(): +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent(): """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent """ @@ -10542,7 +10684,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json -class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeImage(): +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeImage(): """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeImage """ @@ -10564,6 +10706,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_image_seria dialog_node_output_generic_dialog_node_output_response_type_image_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_image_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_image_model_json['channels'] = [response_generic_channel_model] + dialog_node_output_generic_dialog_node_output_response_type_image_model_json['alt_text'] = 'testString' # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeImage by calling from_dict on the json representation dialog_node_output_generic_dialog_node_output_response_type_image_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeImage.from_dict(dialog_node_output_generic_dialog_node_output_response_type_image_model_json) @@ -10580,7 +10723,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_image_seria dialog_node_output_generic_dialog_node_output_response_type_image_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_image_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_image_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_image_model_json -class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeOption(): +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeOption(): """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeOption """ @@ -10594,11 +10737,11 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -10690,7 +10833,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri dialog_node_output_generic_dialog_node_output_response_type_option_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_option_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_option_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_option_model_json -class TestDialogNodeOutputGenericDialogNodeOutputResponseTypePause(): +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypePause(): """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypePause """ @@ -10727,7 +10870,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_pause_seria dialog_node_output_generic_dialog_node_output_response_type_pause_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_pause_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_pause_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_pause_model_json -class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill(): +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill(): """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill """ @@ -10748,7 +10891,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_search_skil dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['query'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['query_type'] = 'natural_language' dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['filter'] = 'testString' - dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['discovery_version'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['discovery_version'] = '2018-12-03' dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill by calling from_dict on the json representation @@ -10766,7 +10909,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_search_skil dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_search_skill_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json -class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeText(): +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeText(): """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeText """ @@ -10789,7 +10932,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial dialog_node_output_generic_dialog_node_output_response_type_text_model_json['response_type'] = 'text' dialog_node_output_generic_dialog_node_output_response_type_text_model_json['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_dialog_node_output_response_type_text_model_json['selection_policy'] = 'sequential' - dialog_node_output_generic_dialog_node_output_response_type_text_model_json['delimiter'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_text_model_json['delimiter'] = '\n' dialog_node_output_generic_dialog_node_output_response_type_text_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeText by calling from_dict on the json representation @@ -10807,7 +10950,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_text_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_text_model_json -class TestDialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined(): +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined(): """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined """ @@ -10843,7 +10986,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_user_define dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_user_defined_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer """ @@ -10889,7 +11032,7 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali runtime_response_generic_runtime_response_type_channel_transfer_model_json2 = runtime_response_generic_runtime_response_type_channel_transfer_model.to_dict() assert runtime_response_generic_runtime_response_type_channel_transfer_model_json2 == runtime_response_generic_runtime_response_type_channel_transfer_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent """ @@ -10936,7 +11079,7 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeImage(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeImage """ @@ -10958,6 +11101,7 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self runtime_response_generic_runtime_response_type_image_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_image_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_image_model_json['channels'] = [response_generic_channel_model] + runtime_response_generic_runtime_response_type_image_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeImage by calling from_dict on the json representation runtime_response_generic_runtime_response_type_image_model = RuntimeResponseGenericRuntimeResponseTypeImage.from_dict(runtime_response_generic_runtime_response_type_image_model_json) @@ -10974,7 +11118,7 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self runtime_response_generic_runtime_response_type_image_model_json2 = runtime_response_generic_runtime_response_type_image_model.to_dict() assert runtime_response_generic_runtime_response_type_image_model_json2 == runtime_response_generic_runtime_response_type_image_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeOption(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeOption """ @@ -10988,11 +11132,11 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -11084,7 +11228,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_response_generic_runtime_response_type_option_model_json2 = runtime_response_generic_runtime_response_type_option_model.to_dict() assert runtime_response_generic_runtime_response_type_option_model_json2 == runtime_response_generic_runtime_response_type_option_model_json -class TestRuntimeResponseGenericRuntimeResponseTypePause(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypePause(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypePause """ @@ -11121,7 +11265,7 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self runtime_response_generic_runtime_response_type_pause_model_json2 = runtime_response_generic_runtime_response_type_pause_model.to_dict() assert runtime_response_generic_runtime_response_type_pause_model_json2 == runtime_response_generic_runtime_response_type_pause_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeSuggestion(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeSuggestion """ @@ -11135,11 +11279,11 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_model = {} # MessageInput message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = True - message_input_model['spelling_auto_correct'] = True + message_input_model['spelling_suggestions'] = False + message_input_model['spelling_auto_correct'] = False message_input_model['suggested_text'] = 'testString' message_input_model['original_text'] = 'testString' - message_input_model['foo'] = { 'foo': 'bar' } + message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -11231,7 +11375,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_response_generic_runtime_response_type_suggestion_model_json2 = runtime_response_generic_runtime_response_type_suggestion_model.to_dict() assert runtime_response_generic_runtime_response_type_suggestion_model_json2 == runtime_response_generic_runtime_response_type_suggestion_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeText(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeText(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeText """ @@ -11267,7 +11411,7 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) runtime_response_generic_runtime_response_type_text_model_json2 = runtime_response_generic_runtime_response_type_text_model.to_dict() assert runtime_response_generic_runtime_response_type_text_model_json2 == runtime_response_generic_runtime_response_type_text_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeUserDefined(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeUserDefined """ diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 2f5958c65..886337542 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -51,6 +51,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -121,6 +123,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -199,6 +203,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -211,7 +217,7 @@ def test_message_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -285,12 +291,12 @@ def test_message_all_params(self): # Construct a dict representation of a MessageInputOptions model message_input_options_model = {} - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False # Construct a dict representation of a MessageInput model message_input_model = {} @@ -308,6 +314,8 @@ def test_message_all_params(self): message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' # Construct a dict representation of a MessageContextGlobal model message_context_global_model = {} @@ -316,7 +324,7 @@ def test_message_all_params(self): # Construct a dict representation of a MessageContextSkillSystem model message_context_skill_system_model = {} message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = { 'foo': 'bar' } + message_context_skill_system_model['foo'] = 'testString' # Construct a dict representation of a MessageContextSkill model message_context_skill_model = {} @@ -362,7 +370,7 @@ def test_message_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -392,7 +400,7 @@ def test_message_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -424,6 +432,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -436,7 +446,7 @@ def test_message_stateless_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -510,10 +520,10 @@ def test_message_stateless_all_params(self): # Construct a dict representation of a MessageInputOptionsStateless model message_input_options_stateless_model = {} - message_input_options_stateless_model['restart'] = True - message_input_options_stateless_model['alternate_intents'] = True + message_input_options_stateless_model['restart'] = False + message_input_options_stateless_model['alternate_intents'] = False message_input_options_stateless_model['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model['debug'] = True + message_input_options_stateless_model['debug'] = False # Construct a dict representation of a MessageInputStateless model message_input_stateless_model = {} @@ -531,6 +541,8 @@ def test_message_stateless_all_params(self): message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' # Construct a dict representation of a MessageContextGlobalStateless model message_context_global_stateless_model = {} @@ -540,7 +552,7 @@ def test_message_stateless_all_params(self): # Construct a dict representation of a MessageContextSkillSystem model message_context_skill_system_model = {} message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = { 'foo': 'bar' } + message_context_skill_system_model['foo'] = 'testString' # Construct a dict representation of a MessageContextSkill model message_context_skill_model = {} @@ -584,7 +596,7 @@ def test_message_stateless_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -612,7 +624,7 @@ def test_message_stateless_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -652,6 +664,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -664,7 +678,7 @@ def test_bulk_classify_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -701,7 +715,7 @@ def test_bulk_classify_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -729,7 +743,7 @@ def test_bulk_classify_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -769,6 +783,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -781,7 +797,7 @@ def test_list_logs_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -824,7 +840,7 @@ def test_list_logs_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -852,7 +868,7 @@ def test_list_logs_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": true, "export": true}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": {"anyKey": "anyValue"}}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": {"anyKey": "anyValue"}}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": {"anyKey": "anyValue"}}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -892,6 +908,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -961,7 +979,7 @@ def test_delete_user_data_value_error(self): # Start of Model Tests ############################################################################## # region -class TestAgentAvailabilityMessage(): +class TestModel_AgentAvailabilityMessage(): """ Test Class for AgentAvailabilityMessage """ @@ -990,7 +1008,7 @@ def test_agent_availability_message_serialization(self): agent_availability_message_model_json2 = agent_availability_message_model.to_dict() assert agent_availability_message_model_json2 == agent_availability_message_model_json -class TestBulkClassifyOutput(): +class TestModel_BulkClassifyOutput(): """ Test Class for BulkClassifyOutput """ @@ -1080,7 +1098,7 @@ def test_bulk_classify_output_serialization(self): bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() assert bulk_classify_output_model_json2 == bulk_classify_output_model_json -class TestBulkClassifyResponse(): +class TestModel_BulkClassifyResponse(): """ Test Class for BulkClassifyResponse """ @@ -1173,7 +1191,7 @@ def test_bulk_classify_response_serialization(self): bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() assert bulk_classify_response_model_json2 == bulk_classify_response_model_json -class TestBulkClassifyUtterance(): +class TestModel_BulkClassifyUtterance(): """ Test Class for BulkClassifyUtterance """ @@ -1202,7 +1220,7 @@ def test_bulk_classify_utterance_serialization(self): bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json -class TestCaptureGroup(): +class TestModel_CaptureGroup(): """ Test Class for CaptureGroup """ @@ -1232,7 +1250,7 @@ def test_capture_group_serialization(self): capture_group_model_json2 = capture_group_model.to_dict() assert capture_group_model_json2 == capture_group_model_json -class TestChannelTransferInfo(): +class TestModel_ChannelTransferInfo(): """ Test Class for ChannelTransferInfo """ @@ -1269,7 +1287,7 @@ def test_channel_transfer_info_serialization(self): channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() assert channel_transfer_info_model_json2 == channel_transfer_info_model_json -class TestChannelTransferTarget(): +class TestModel_ChannelTransferTarget(): """ Test Class for ChannelTransferTarget """ @@ -1303,7 +1321,7 @@ def test_channel_transfer_target_serialization(self): channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() assert channel_transfer_target_model_json2 == channel_transfer_target_model_json -class TestChannelTransferTargetChat(): +class TestModel_ChannelTransferTargetChat(): """ Test Class for ChannelTransferTargetChat """ @@ -1332,7 +1350,7 @@ def test_channel_transfer_target_chat_serialization(self): channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json -class TestDialogLogMessage(): +class TestModel_DialogLogMessage(): """ Test Class for DialogLogMessage """ @@ -1370,7 +1388,7 @@ def test_dialog_log_message_serialization(self): dialog_log_message_model_json2 = dialog_log_message_model.to_dict() assert dialog_log_message_model_json2 == dialog_log_message_model_json -class TestDialogNodeAction(): +class TestModel_DialogNodeAction(): """ Test Class for DialogNodeAction """ @@ -1403,7 +1421,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json2 = dialog_node_action_model.to_dict() assert dialog_node_action_model_json2 == dialog_node_action_model_json -class TestDialogNodeOutputConnectToAgentTransferInfo(): +class TestModel_DialogNodeOutputConnectToAgentTransferInfo(): """ Test Class for DialogNodeOutputConnectToAgentTransferInfo """ @@ -1432,7 +1450,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json -class TestDialogNodeOutputOptionsElement(): +class TestModel_DialogNodeOutputOptionsElement(): """ Test Class for DialogNodeOutputOptionsElement """ @@ -1503,12 +1521,12 @@ def test_dialog_node_output_options_element_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' @@ -1541,7 +1559,7 @@ def test_dialog_node_output_options_element_serialization(self): dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json -class TestDialogNodeOutputOptionsElementValue(): +class TestModel_DialogNodeOutputOptionsElementValue(): """ Test Class for DialogNodeOutputOptionsElementValue """ @@ -1612,12 +1630,12 @@ def test_dialog_node_output_options_element_value_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' @@ -1646,7 +1664,7 @@ def test_dialog_node_output_options_element_value_serialization(self): dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json -class TestDialogNodesVisited(): +class TestModel_DialogNodesVisited(): """ Test Class for DialogNodesVisited """ @@ -1677,7 +1695,7 @@ def test_dialog_nodes_visited_serialization(self): dialog_nodes_visited_model_json2 = dialog_nodes_visited_model.to_dict() assert dialog_nodes_visited_model_json2 == dialog_nodes_visited_model_json -class TestDialogSuggestion(): +class TestModel_DialogSuggestion(): """ Test Class for DialogSuggestion """ @@ -1748,12 +1766,12 @@ def test_dialog_suggestion_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' @@ -1787,7 +1805,7 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() assert dialog_suggestion_model_json2 == dialog_suggestion_model_json -class TestDialogSuggestionValue(): +class TestModel_DialogSuggestionValue(): """ Test Class for DialogSuggestionValue """ @@ -1858,12 +1876,12 @@ def test_dialog_suggestion_value_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' @@ -1892,7 +1910,7 @@ def test_dialog_suggestion_value_serialization(self): dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json -class TestLog(): +class TestModel_Log(): """ Test Class for Log """ @@ -1963,12 +1981,12 @@ def test_log_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' @@ -1984,6 +2002,8 @@ def test_log_serialization(self): message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model @@ -1991,7 +2011,7 @@ def test_log_serialization(self): message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = { 'foo': 'bar' } + message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill message_context_skill_model['user_defined'] = {} @@ -2100,7 +2120,7 @@ def test_log_serialization(self): log_model_json2 = log_model.to_dict() assert log_model_json2 == log_model_json -class TestLogCollection(): +class TestModel_LogCollection(): """ Test Class for LogCollection """ @@ -2171,12 +2191,12 @@ def test_log_collection_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' @@ -2192,6 +2212,8 @@ def test_log_collection_serialization(self): message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model @@ -2199,7 +2221,7 @@ def test_log_collection_serialization(self): message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = { 'foo': 'bar' } + message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill message_context_skill_model['user_defined'] = {} @@ -2317,7 +2339,7 @@ def test_log_collection_serialization(self): log_collection_model_json2 = log_collection_model.to_dict() assert log_collection_model_json2 == log_collection_model_json -class TestLogPagination(): +class TestModel_LogPagination(): """ Test Class for LogPagination """ @@ -2348,7 +2370,7 @@ def test_log_pagination_serialization(self): log_pagination_model_json2 = log_pagination_model.to_dict() assert log_pagination_model_json2 == log_pagination_model_json -class TestMessageContext(): +class TestModel_MessageContext(): """ Test Class for MessageContext """ @@ -2366,6 +2388,8 @@ def test_message_context_serialization(self): message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model @@ -2373,7 +2397,7 @@ def test_message_context_serialization(self): message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = { 'foo': 'bar' } + message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill message_context_skill_model['user_defined'] = {} @@ -2399,7 +2423,7 @@ def test_message_context_serialization(self): message_context_model_json2 = message_context_model.to_dict() assert message_context_model_json2 == message_context_model_json -class TestMessageContextGlobal(): +class TestModel_MessageContextGlobal(): """ Test Class for MessageContextGlobal """ @@ -2417,6 +2441,8 @@ def test_message_context_global_serialization(self): message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' # Construct a json representation of a MessageContextGlobal model message_context_global_model_json = {} @@ -2438,7 +2464,7 @@ def test_message_context_global_serialization(self): message_context_global_model_json2 = message_context_global_model.to_dict() assert message_context_global_model_json2 == message_context_global_model_json -class TestMessageContextGlobalStateless(): +class TestModel_MessageContextGlobalStateless(): """ Test Class for MessageContextGlobalStateless """ @@ -2456,6 +2482,8 @@ def test_message_context_global_stateless_serialization(self): message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' # Construct a json representation of a MessageContextGlobalStateless model message_context_global_stateless_model_json = {} @@ -2477,7 +2505,7 @@ def test_message_context_global_stateless_serialization(self): message_context_global_stateless_model_json2 = message_context_global_stateless_model.to_dict() assert message_context_global_stateless_model_json2 == message_context_global_stateless_model_json -class TestMessageContextGlobalSystem(): +class TestModel_MessageContextGlobalSystem(): """ Test Class for MessageContextGlobalSystem """ @@ -2494,6 +2522,8 @@ def test_message_context_global_system_serialization(self): message_context_global_system_model_json['turn_count'] = 38 message_context_global_system_model_json['locale'] = 'en-us' message_context_global_system_model_json['reference_time'] = 'testString' + message_context_global_system_model_json['session_start_time'] = 'testString' + message_context_global_system_model_json['state'] = 'testString' # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) @@ -2510,7 +2540,7 @@ def test_message_context_global_system_serialization(self): message_context_global_system_model_json2 = message_context_global_system_model.to_dict() assert message_context_global_system_model_json2 == message_context_global_system_model_json -class TestMessageContextSkill(): +class TestModel_MessageContextSkill(): """ Test Class for MessageContextSkill """ @@ -2524,7 +2554,7 @@ def test_message_context_skill_serialization(self): message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = { 'foo': 'bar' } + message_context_skill_system_model['foo'] = 'testString' # Construct a json representation of a MessageContextSkill model message_context_skill_model_json = {} @@ -2546,7 +2576,7 @@ def test_message_context_skill_serialization(self): message_context_skill_model_json2 = message_context_skill_model.to_dict() assert message_context_skill_model_json2 == message_context_skill_model_json -class TestMessageContextSkillSystem(): +class TestModel_MessageContextSkillSystem(): """ Test Class for MessageContextSkillSystem """ @@ -2559,7 +2589,7 @@ def test_message_context_skill_system_serialization(self): # Construct a json representation of a MessageContextSkillSystem model message_context_skill_system_model_json = {} message_context_skill_system_model_json['state'] = 'testString' - message_context_skill_system_model_json['foo'] = { 'foo': 'bar' } + message_context_skill_system_model_json['foo'] = 'testString' # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) @@ -2576,7 +2606,17 @@ def test_message_context_skill_system_serialization(self): message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() assert message_context_skill_system_model_json2 == message_context_skill_system_model_json -class TestMessageContextStateless(): + # Test get_properties and set_properties methods. + message_context_skill_system_model.set_properties({}) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': 'testString'} + message_context_skill_system_model.set_properties(expected_dict) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_MessageContextStateless(): """ Test Class for MessageContextStateless """ @@ -2594,6 +2634,8 @@ def test_message_context_stateless_serialization(self): message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' message_context_global_stateless_model = {} # MessageContextGlobalStateless message_context_global_stateless_model['system'] = message_context_global_system_model @@ -2601,7 +2643,7 @@ def test_message_context_stateless_serialization(self): message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = { 'foo': 'bar' } + message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill message_context_skill_model['user_defined'] = {} @@ -2627,7 +2669,7 @@ def test_message_context_stateless_serialization(self): message_context_stateless_model_json2 = message_context_stateless_model.to_dict() assert message_context_stateless_model_json2 == message_context_stateless_model_json -class TestMessageInput(): +class TestModel_MessageInput(): """ Test Class for MessageInput """ @@ -2698,12 +2740,12 @@ def test_message_input_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False # Construct a json representation of a MessageInput model message_input_model_json = {} @@ -2729,7 +2771,7 @@ def test_message_input_serialization(self): message_input_model_json2 = message_input_model.to_dict() assert message_input_model_json2 == message_input_model_json -class TestMessageInputOptions(): +class TestModel_MessageInputOptions(): """ Test Class for MessageInputOptions """ @@ -2747,12 +2789,12 @@ def test_message_input_options_serialization(self): # Construct a json representation of a MessageInputOptions model message_input_options_model_json = {} - message_input_options_model_json['restart'] = True - message_input_options_model_json['alternate_intents'] = True + message_input_options_model_json['restart'] = False + message_input_options_model_json['alternate_intents'] = False message_input_options_model_json['spelling'] = message_input_options_spelling_model - message_input_options_model_json['debug'] = True - message_input_options_model_json['return_context'] = True - message_input_options_model_json['export'] = True + message_input_options_model_json['debug'] = False + message_input_options_model_json['return_context'] = False + message_input_options_model_json['export'] = False # Construct a model instance of MessageInputOptions by calling from_dict on the json representation message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) @@ -2769,7 +2811,7 @@ def test_message_input_options_serialization(self): message_input_options_model_json2 = message_input_options_model.to_dict() assert message_input_options_model_json2 == message_input_options_model_json -class TestMessageInputOptionsSpelling(): +class TestModel_MessageInputOptionsSpelling(): """ Test Class for MessageInputOptionsSpelling """ @@ -2799,7 +2841,7 @@ def test_message_input_options_spelling_serialization(self): message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json -class TestMessageInputOptionsStateless(): +class TestModel_MessageInputOptionsStateless(): """ Test Class for MessageInputOptionsStateless """ @@ -2817,10 +2859,10 @@ def test_message_input_options_stateless_serialization(self): # Construct a json representation of a MessageInputOptionsStateless model message_input_options_stateless_model_json = {} - message_input_options_stateless_model_json['restart'] = True - message_input_options_stateless_model_json['alternate_intents'] = True + message_input_options_stateless_model_json['restart'] = False + message_input_options_stateless_model_json['alternate_intents'] = False message_input_options_stateless_model_json['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model_json['debug'] = True + message_input_options_stateless_model_json['debug'] = False # Construct a model instance of MessageInputOptionsStateless by calling from_dict on the json representation message_input_options_stateless_model = MessageInputOptionsStateless.from_dict(message_input_options_stateless_model_json) @@ -2837,7 +2879,7 @@ def test_message_input_options_stateless_serialization(self): message_input_options_stateless_model_json2 = message_input_options_stateless_model.to_dict() assert message_input_options_stateless_model_json2 == message_input_options_stateless_model_json -class TestMessageInputStateless(): +class TestModel_MessageInputStateless(): """ Test Class for MessageInputStateless """ @@ -2908,10 +2950,10 @@ def test_message_input_stateless_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_stateless_model = {} # MessageInputOptionsStateless - message_input_options_stateless_model['restart'] = True - message_input_options_stateless_model['alternate_intents'] = True + message_input_options_stateless_model['restart'] = False + message_input_options_stateless_model['alternate_intents'] = False message_input_options_stateless_model['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model['debug'] = True + message_input_options_stateless_model['debug'] = False # Construct a json representation of a MessageInputStateless model message_input_stateless_model_json = {} @@ -2937,7 +2979,7 @@ def test_message_input_stateless_serialization(self): message_input_stateless_model_json2 = message_input_stateless_model.to_dict() assert message_input_stateless_model_json2 == message_input_stateless_model_json -class TestMessageOutput(): +class TestModel_MessageOutput(): """ Test Class for MessageOutput """ @@ -3008,12 +3050,12 @@ def test_message_output_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' @@ -3099,7 +3141,7 @@ def test_message_output_serialization(self): message_output_model_json2 = message_output_model.to_dict() assert message_output_model_json2 == message_output_model_json -class TestMessageOutputDebug(): +class TestModel_MessageOutputDebug(): """ Test Class for MessageOutputDebug """ @@ -3148,7 +3190,7 @@ def test_message_output_debug_serialization(self): message_output_debug_model_json2 = message_output_debug_model.to_dict() assert message_output_debug_model_json2 == message_output_debug_model_json -class TestMessageOutputSpelling(): +class TestModel_MessageOutputSpelling(): """ Test Class for MessageOutputSpelling """ @@ -3179,7 +3221,7 @@ def test_message_output_spelling_serialization(self): message_output_spelling_model_json2 = message_output_spelling_model.to_dict() assert message_output_spelling_model_json2 == message_output_spelling_model_json -class TestMessageRequest(): +class TestModel_MessageRequest(): """ Test Class for MessageRequest """ @@ -3250,10 +3292,10 @@ def test_message_request_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True + message_input_options_model['debug'] = False message_input_options_model['return_context'] = True message_input_options_model['export'] = True @@ -3271,6 +3313,8 @@ def test_message_request_serialization(self): message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model @@ -3278,7 +3322,7 @@ def test_message_request_serialization(self): message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = { 'foo': 'bar' } + message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill message_context_skill_model['user_defined'] = {} @@ -3309,7 +3353,7 @@ def test_message_request_serialization(self): message_request_model_json2 = message_request_model.to_dict() assert message_request_model_json2 == message_request_model_json -class TestMessageResponse(): +class TestModel_MessageResponse(): """ Test Class for MessageResponse """ @@ -3380,12 +3424,12 @@ def test_message_response_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' @@ -3461,6 +3505,8 @@ def test_message_response_serialization(self): message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model @@ -3468,7 +3514,7 @@ def test_message_response_serialization(self): message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = { 'foo': 'bar' } + message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill message_context_skill_model['user_defined'] = {} @@ -3499,7 +3545,7 @@ def test_message_response_serialization(self): message_response_model_json2 = message_response_model.to_dict() assert message_response_model_json2 == message_response_model_json -class TestMessageResponseStateless(): +class TestModel_MessageResponseStateless(): """ Test Class for MessageResponseStateless """ @@ -3570,12 +3616,12 @@ def test_message_response_stateless_serialization(self): message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' @@ -3651,6 +3697,8 @@ def test_message_response_stateless_serialization(self): message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' message_context_global_stateless_model = {} # MessageContextGlobalStateless message_context_global_stateless_model['system'] = message_context_global_system_model @@ -3658,7 +3706,7 @@ def test_message_response_stateless_serialization(self): message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = { 'foo': 'bar' } + message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill message_context_skill_model['user_defined'] = {} @@ -3689,7 +3737,7 @@ def test_message_response_stateless_serialization(self): message_response_stateless_model_json2 = message_response_stateless_model.to_dict() assert message_response_stateless_model_json2 == message_response_stateless_model_json -class TestResponseGenericChannel(): +class TestModel_ResponseGenericChannel(): """ Test Class for ResponseGenericChannel """ @@ -3718,7 +3766,7 @@ def test_response_generic_channel_serialization(self): response_generic_channel_model_json2 = response_generic_channel_model.to_dict() assert response_generic_channel_model_json2 == response_generic_channel_model_json -class TestRuntimeEntity(): +class TestModel_RuntimeEntity(): """ Test Class for RuntimeEntity """ @@ -3796,7 +3844,7 @@ def test_runtime_entity_serialization(self): runtime_entity_model_json2 = runtime_entity_model.to_dict() assert runtime_entity_model_json2 == runtime_entity_model_json -class TestRuntimeEntityAlternative(): +class TestModel_RuntimeEntityAlternative(): """ Test Class for RuntimeEntityAlternative """ @@ -3826,7 +3874,7 @@ def test_runtime_entity_alternative_serialization(self): runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json -class TestRuntimeEntityInterpretation(): +class TestModel_RuntimeEntityInterpretation(): """ Test Class for RuntimeEntityInterpretation """ @@ -3880,7 +3928,7 @@ def test_runtime_entity_interpretation_serialization(self): runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json -class TestRuntimeEntityRole(): +class TestModel_RuntimeEntityRole(): """ Test Class for RuntimeEntityRole """ @@ -3909,7 +3957,7 @@ def test_runtime_entity_role_serialization(self): runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() assert runtime_entity_role_model_json2 == runtime_entity_role_model_json -class TestRuntimeIntent(): +class TestModel_RuntimeIntent(): """ Test Class for RuntimeIntent """ @@ -3939,7 +3987,7 @@ def test_runtime_intent_serialization(self): runtime_intent_model_json2 = runtime_intent_model.to_dict() assert runtime_intent_model_json2 == runtime_intent_model_json -class TestSearchResult(): +class TestModel_SearchResult(): """ Test Class for SearchResult """ @@ -3985,7 +4033,7 @@ def test_search_result_serialization(self): search_result_model_json2 = search_result_model.to_dict() assert search_result_model_json2 == search_result_model_json -class TestSearchResultHighlight(): +class TestModel_SearchResultHighlight(): """ Test Class for SearchResultHighlight """ @@ -4017,7 +4065,17 @@ def test_search_result_highlight_serialization(self): search_result_highlight_model_json2 = search_result_highlight_model.to_dict() assert search_result_highlight_model_json2 == search_result_highlight_model_json -class TestSearchResultMetadata(): + # Test get_properties and set_properties methods. + search_result_highlight_model.set_properties({}) + actual_dict = search_result_highlight_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': ['testString']} + search_result_highlight_model.set_properties(expected_dict) + actual_dict = search_result_highlight_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_SearchResultMetadata(): """ Test Class for SearchResultMetadata """ @@ -4047,7 +4105,7 @@ def test_search_result_metadata_serialization(self): search_result_metadata_model_json2 = search_result_metadata_model.to_dict() assert search_result_metadata_model_json2 == search_result_metadata_model_json -class TestSessionResponse(): +class TestModel_SessionResponse(): """ Test Class for SessionResponse """ @@ -4076,7 +4134,7 @@ def test_session_response_serialization(self): session_response_model_json2 = session_response_model.to_dict() assert session_response_model_json2 == session_response_model_json -class TestLogMessageSourceAction(): +class TestModel_LogMessageSourceAction(): """ Test Class for LogMessageSourceAction """ @@ -4106,7 +4164,7 @@ def test_log_message_source_action_serialization(self): log_message_source_action_model_json2 = log_message_source_action_model.to_dict() assert log_message_source_action_model_json2 == log_message_source_action_model_json -class TestLogMessageSourceDialogNode(): +class TestModel_LogMessageSourceDialogNode(): """ Test Class for LogMessageSourceDialogNode """ @@ -4136,7 +4194,7 @@ def test_log_message_source_dialog_node_serialization(self): log_message_source_dialog_node_model_json2 = log_message_source_dialog_node_model.to_dict() assert log_message_source_dialog_node_model_json2 == log_message_source_dialog_node_model_json -class TestLogMessageSourceHandler(): +class TestModel_LogMessageSourceHandler(): """ Test Class for LogMessageSourceHandler """ @@ -4168,7 +4226,7 @@ def test_log_message_source_handler_serialization(self): log_message_source_handler_model_json2 = log_message_source_handler_model.to_dict() assert log_message_source_handler_model_json2 == log_message_source_handler_model_json -class TestLogMessageSourceStep(): +class TestModel_LogMessageSourceStep(): """ Test Class for LogMessageSourceStep """ @@ -4199,7 +4257,7 @@ def test_log_message_source_step_serialization(self): log_message_source_step_model_json2 = log_message_source_step_model.to_dict() assert log_message_source_step_model_json2 == log_message_source_step_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer """ @@ -4245,7 +4303,7 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali runtime_response_generic_runtime_response_type_channel_transfer_model_json2 = runtime_response_generic_runtime_response_type_channel_transfer_model.to_dict() assert runtime_response_generic_runtime_response_type_channel_transfer_model_json2 == runtime_response_generic_runtime_response_type_channel_transfer_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent """ @@ -4291,7 +4349,7 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeImage(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeImage """ @@ -4313,6 +4371,7 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self runtime_response_generic_runtime_response_type_image_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_image_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_image_model_json['channels'] = [response_generic_channel_model] + runtime_response_generic_runtime_response_type_image_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeImage by calling from_dict on the json representation runtime_response_generic_runtime_response_type_image_model = RuntimeResponseGenericRuntimeResponseTypeImage.from_dict(runtime_response_generic_runtime_response_type_image_model_json) @@ -4329,7 +4388,7 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self runtime_response_generic_runtime_response_type_image_model_json2 = runtime_response_generic_runtime_response_type_image_model.to_dict() assert runtime_response_generic_runtime_response_type_image_model_json2 == runtime_response_generic_runtime_response_type_image_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeOption(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeOption """ @@ -4400,12 +4459,12 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' @@ -4449,7 +4508,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_response_generic_runtime_response_type_option_model_json2 = runtime_response_generic_runtime_response_type_option_model.to_dict() assert runtime_response_generic_runtime_response_type_option_model_json2 == runtime_response_generic_runtime_response_type_option_model_json -class TestRuntimeResponseGenericRuntimeResponseTypePause(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypePause(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypePause """ @@ -4486,7 +4545,7 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self runtime_response_generic_runtime_response_type_pause_model_json2 = runtime_response_generic_runtime_response_type_pause_model.to_dict() assert runtime_response_generic_runtime_response_type_pause_model_json2 == runtime_response_generic_runtime_response_type_pause_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeSearch(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeSearch(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeSearch """ @@ -4542,7 +4601,7 @@ def test_runtime_response_generic_runtime_response_type_search_serialization(sel runtime_response_generic_runtime_response_type_search_model_json2 = runtime_response_generic_runtime_response_type_search_model.to_dict() assert runtime_response_generic_runtime_response_type_search_model_json2 == runtime_response_generic_runtime_response_type_search_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeSuggestion(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeSuggestion """ @@ -4613,12 +4672,12 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_options_spelling_model['auto_correct'] = True message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = True - message_input_options_model['alternate_intents'] = True + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = True - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' @@ -4661,7 +4720,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_response_generic_runtime_response_type_suggestion_model_json2 = runtime_response_generic_runtime_response_type_suggestion_model.to_dict() assert runtime_response_generic_runtime_response_type_suggestion_model_json2 == runtime_response_generic_runtime_response_type_suggestion_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeText(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeText(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeText """ @@ -4697,7 +4756,7 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) runtime_response_generic_runtime_response_type_text_model_json2 = runtime_response_generic_runtime_response_type_text_model.to_dict() assert runtime_response_generic_runtime_response_type_text_model_json2 == runtime_response_generic_runtime_response_type_text_model_json -class TestRuntimeResponseGenericRuntimeResponseTypeUserDefined(): +class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeUserDefined """ diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py index 57a6378b3..72c554bae 100644 --- a/test/unit/test_compare_comply_v1.py +++ b/test/unit/test_compare_comply_v1.py @@ -55,6 +55,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -171,6 +173,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -287,6 +291,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -403,6 +409,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -427,8 +435,8 @@ def test_compare_documents_all_params(self): file_2 = io.BytesIO(b'This is a mock file.').getvalue() file_1_content_type = 'application/pdf' file_2_content_type = 'application/pdf' - file_1_label = 'testString' - file_2_label = 'testString' + file_1_label = 'file_1' + file_2_label = 'file_2' model = 'contracts' # Invoke method @@ -533,6 +541,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -710,6 +720,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -842,6 +854,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -946,6 +960,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1060,6 +1076,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1205,6 +1223,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1266,6 +1286,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1336,6 +1358,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1452,7 +1476,7 @@ def test_update_batch_value_error(self): # Start of Model Tests ############################################################################## # region -class TestAddress(): +class TestModel_Address(): """ Test Class for Address """ @@ -1488,7 +1512,7 @@ def test_address_serialization(self): address_model_json2 = address_model.to_dict() assert address_model_json2 == address_model_json -class TestAlignedElement(): +class TestModel_AlignedElement(): """ Test Class for AlignedElement """ @@ -1549,7 +1573,7 @@ def test_aligned_element_serialization(self): aligned_element_model_json2 = aligned_element_model.to_dict() assert aligned_element_model_json2 == aligned_element_model_json -class TestAttribute(): +class TestModel_Attribute(): """ Test Class for Attribute """ @@ -1586,7 +1610,7 @@ def test_attribute_serialization(self): attribute_model_json2 = attribute_model.to_dict() assert attribute_model_json2 == attribute_model_json -class TestBatchStatus(): +class TestModel_BatchStatus(): """ Test Class for BatchStatus """ @@ -1614,8 +1638,8 @@ def test_batch_status_serialization(self): batch_status_model_json['batch_id'] = 'testString' batch_status_model_json['document_counts'] = doc_counts_model batch_status_model_json['status'] = 'testString' - batch_status_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - batch_status_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + batch_status_model_json['created'] = "2019-01-01T12:00:00Z" + batch_status_model_json['updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of BatchStatus by calling from_dict on the json representation batch_status_model = BatchStatus.from_dict(batch_status_model_json) @@ -1632,7 +1656,7 @@ def test_batch_status_serialization(self): batch_status_model_json2 = batch_status_model.to_dict() assert batch_status_model_json2 == batch_status_model_json -class TestBatches(): +class TestModel_Batches(): """ Test Class for Batches """ @@ -1659,8 +1683,8 @@ def test_batches_serialization(self): batch_status_model['batch_id'] = 'testString' batch_status_model['document_counts'] = doc_counts_model batch_status_model['status'] = 'testString' - batch_status_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - batch_status_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + batch_status_model['created'] = "2019-01-01T12:00:00Z" + batch_status_model['updated'] = "2019-01-01T12:00:00Z" # Construct a json representation of a Batches model batches_model_json = {} @@ -1681,7 +1705,7 @@ def test_batches_serialization(self): batches_model_json2 = batches_model.to_dict() assert batches_model_json2 == batches_model_json -class TestBodyCells(): +class TestModel_BodyCells(): """ Test Class for BodyCells """ @@ -1734,7 +1758,7 @@ def test_body_cells_serialization(self): body_cells_model_json2 = body_cells_model.to_dict() assert body_cells_model_json2 == body_cells_model_json -class TestCategory(): +class TestModel_Category(): """ Test Class for Category """ @@ -1765,7 +1789,7 @@ def test_category_serialization(self): category_model_json2 = category_model.to_dict() assert category_model_json2 == category_model_json -class TestCategoryComparison(): +class TestModel_CategoryComparison(): """ Test Class for CategoryComparison """ @@ -1794,7 +1818,7 @@ def test_category_comparison_serialization(self): category_comparison_model_json2 = category_comparison_model.to_dict() assert category_comparison_model_json2 == category_comparison_model_json -class TestClassifyReturn(): +class TestModel_ClassifyReturn(): """ Test Class for ClassifyReturn """ @@ -2056,7 +2080,7 @@ def test_classify_return_serialization(self): classify_return_model_json2 = classify_return_model.to_dict() assert classify_return_model_json2 == classify_return_model_json -class TestColumnHeaders(): +class TestModel_ColumnHeaders(): """ Test Class for ColumnHeaders """ @@ -2092,7 +2116,7 @@ def test_column_headers_serialization(self): column_headers_model_json2 = column_headers_model.to_dict() assert column_headers_model_json2 == column_headers_model_json -class TestCompareReturn(): +class TestModel_CompareReturn(): """ Test Class for CompareReturn """ @@ -2174,7 +2198,7 @@ def test_compare_return_serialization(self): compare_return_model_json2 = compare_return_model.to_dict() assert compare_return_model_json2 == compare_return_model_json -class TestContact(): +class TestModel_Contact(): """ Test Class for Contact """ @@ -2204,7 +2228,7 @@ def test_contact_serialization(self): contact_model_json2 = contact_model.to_dict() assert contact_model_json2 == contact_model_json -class TestContexts(): +class TestModel_Contexts(): """ Test Class for Contexts """ @@ -2240,7 +2264,7 @@ def test_contexts_serialization(self): contexts_model_json2 = contexts_model.to_dict() assert contexts_model_json2 == contexts_model_json -class TestContractAmts(): +class TestModel_ContractAmts(): """ Test Class for ContractAmts """ @@ -2285,7 +2309,7 @@ def test_contract_amts_serialization(self): contract_amts_model_json2 = contract_amts_model.to_dict() assert contract_amts_model_json2 == contract_amts_model_json -class TestContractCurrencies(): +class TestModel_ContractCurrencies(): """ Test Class for ContractCurrencies """ @@ -2324,7 +2348,7 @@ def test_contract_currencies_serialization(self): contract_currencies_model_json2 = contract_currencies_model.to_dict() assert contract_currencies_model_json2 == contract_currencies_model_json -class TestContractTerms(): +class TestModel_ContractTerms(): """ Test Class for ContractTerms """ @@ -2369,7 +2393,7 @@ def test_contract_terms_serialization(self): contract_terms_model_json2 = contract_terms_model.to_dict() assert contract_terms_model_json2 == contract_terms_model_json -class TestContractTypes(): +class TestModel_ContractTypes(): """ Test Class for ContractTypes """ @@ -2407,7 +2431,7 @@ def test_contract_types_serialization(self): contract_types_model_json2 = contract_types_model.to_dict() assert contract_types_model_json2 == contract_types_model_json -class TestDocCounts(): +class TestModel_DocCounts(): """ Test Class for DocCounts """ @@ -2439,7 +2463,7 @@ def test_doc_counts_serialization(self): doc_counts_model_json2 = doc_counts_model.to_dict() assert doc_counts_model_json2 == doc_counts_model_json -class TestDocInfo(): +class TestModel_DocInfo(): """ Test Class for DocInfo """ @@ -2470,7 +2494,7 @@ def test_doc_info_serialization(self): doc_info_model_json2 = doc_info_model.to_dict() assert doc_info_model_json2 == doc_info_model_json -class TestDocStructure(): +class TestModel_DocStructure(): """ Test Class for DocStructure """ @@ -2525,7 +2549,7 @@ def test_doc_structure_serialization(self): doc_structure_model_json2 = doc_structure_model.to_dict() assert doc_structure_model_json2 == doc_structure_model_json -class TestDocument(): +class TestModel_Document(): """ Test Class for Document """ @@ -2557,7 +2581,7 @@ def test_document_serialization(self): document_model_json2 = document_model.to_dict() assert document_model_json2 == document_model_json -class TestEffectiveDates(): +class TestModel_EffectiveDates(): """ Test Class for EffectiveDates """ @@ -2596,7 +2620,7 @@ def test_effective_dates_serialization(self): effective_dates_model_json2 = effective_dates_model.to_dict() assert effective_dates_model_json2 == effective_dates_model_json -class TestElement(): +class TestModel_Element(): """ Test Class for Element """ @@ -2654,7 +2678,7 @@ def test_element_serialization(self): element_model_json2 = element_model.to_dict() assert element_model_json2 == element_model_json -class TestElementLocations(): +class TestModel_ElementLocations(): """ Test Class for ElementLocations """ @@ -2684,7 +2708,7 @@ def test_element_locations_serialization(self): element_locations_model_json2 = element_locations_model.to_dict() assert element_locations_model_json2 == element_locations_model_json -class TestElementPair(): +class TestModel_ElementPair(): """ Test Class for ElementPair """ @@ -2739,7 +2763,7 @@ def test_element_pair_serialization(self): element_pair_model_json2 = element_pair_model.to_dict() assert element_pair_model_json2 == element_pair_model_json -class TestFeedbackDataInput(): +class TestModel_FeedbackDataInput(): """ Test Class for FeedbackDataInput """ @@ -2807,7 +2831,7 @@ def test_feedback_data_input_serialization(self): feedback_data_input_model_json2 = feedback_data_input_model.to_dict() assert feedback_data_input_model_json2 == feedback_data_input_model_json -class TestFeedbackDataOutput(): +class TestModel_FeedbackDataOutput(): """ Test Class for FeedbackDataOutput """ @@ -2883,7 +2907,7 @@ def test_feedback_data_output_serialization(self): feedback_data_output_model_json2 = feedback_data_output_model.to_dict() assert feedback_data_output_model_json2 == feedback_data_output_model_json -class TestFeedbackDeleted(): +class TestModel_FeedbackDeleted(): """ Test Class for FeedbackDeleted """ @@ -2913,7 +2937,7 @@ def test_feedback_deleted_serialization(self): feedback_deleted_model_json2 = feedback_deleted_model.to_dict() assert feedback_deleted_model_json2 == feedback_deleted_model_json -class TestFeedbackList(): +class TestModel_FeedbackList(): """ Test Class for FeedbackList """ @@ -2975,7 +2999,7 @@ def test_feedback_list_serialization(self): get_feedback_model = {} # GetFeedback get_feedback_model['feedback_id'] = '9730b437-cb86-4d40-9a84-ff6948bb3dd1' - get_feedback_model['created'] = datetime_to_string(string_to_datetime("2018-07-03T10:16:05-0500")) + get_feedback_model['created'] = "2018-07-03T15:16:05Z" get_feedback_model['comment'] = 'testString' get_feedback_model['feedback_data'] = feedback_data_output_model @@ -2998,7 +3022,7 @@ def test_feedback_list_serialization(self): feedback_list_model_json2 = feedback_list_model.to_dict() assert feedback_list_model_json2 == feedback_list_model_json -class TestFeedbackReturn(): +class TestModel_FeedbackReturn(): """ Test Class for FeedbackReturn """ @@ -3063,7 +3087,7 @@ def test_feedback_return_serialization(self): feedback_return_model_json['feedback_id'] = 'testString' feedback_return_model_json['user_id'] = 'testString' feedback_return_model_json['comment'] = 'testString' - feedback_return_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + feedback_return_model_json['created'] = "2019-01-01T12:00:00Z" feedback_return_model_json['feedback_data'] = feedback_data_output_model # Construct a model instance of FeedbackReturn by calling from_dict on the json representation @@ -3081,7 +3105,7 @@ def test_feedback_return_serialization(self): feedback_return_model_json2 = feedback_return_model.to_dict() assert feedback_return_model_json2 == feedback_return_model_json -class TestGetFeedback(): +class TestModel_GetFeedback(): """ Test Class for GetFeedback """ @@ -3144,7 +3168,7 @@ def test_get_feedback_serialization(self): # Construct a json representation of a GetFeedback model get_feedback_model_json = {} get_feedback_model_json['feedback_id'] = 'testString' - get_feedback_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + get_feedback_model_json['created'] = "2019-01-01T12:00:00Z" get_feedback_model_json['comment'] = 'testString' get_feedback_model_json['feedback_data'] = feedback_data_output_model @@ -3163,7 +3187,7 @@ def test_get_feedback_serialization(self): get_feedback_model_json2 = get_feedback_model.to_dict() assert get_feedback_model_json2 == get_feedback_model_json -class TestHTMLReturn(): +class TestModel_HTMLReturn(): """ Test Class for HTMLReturn """ @@ -3196,7 +3220,7 @@ def test_html_return_serialization(self): html_return_model_json2 = html_return_model.to_dict() assert html_return_model_json2 == html_return_model_json -class TestInterpretation(): +class TestModel_Interpretation(): """ Test Class for Interpretation """ @@ -3227,7 +3251,7 @@ def test_interpretation_serialization(self): interpretation_model_json2 = interpretation_model.to_dict() assert interpretation_model_json2 == interpretation_model_json -class TestKey(): +class TestModel_Key(): """ Test Class for Key """ @@ -3264,7 +3288,7 @@ def test_key_serialization(self): key_model_json2 = key_model.to_dict() assert key_model_json2 == key_model_json -class TestKeyValuePair(): +class TestModel_KeyValuePair(): """ Test Class for KeyValuePair """ @@ -3310,7 +3334,7 @@ def test_key_value_pair_serialization(self): key_value_pair_model_json2 = key_value_pair_model.to_dict() assert key_value_pair_model_json2 == key_value_pair_model_json -class TestLabel(): +class TestModel_Label(): """ Test Class for Label """ @@ -3340,7 +3364,7 @@ def test_label_serialization(self): label_model_json2 = label_model.to_dict() assert label_model_json2 == label_model_json -class TestLeadingSentence(): +class TestModel_LeadingSentence(): """ Test Class for LeadingSentence """ @@ -3381,7 +3405,7 @@ def test_leading_sentence_serialization(self): leading_sentence_model_json2 = leading_sentence_model.to_dict() assert leading_sentence_model_json2 == leading_sentence_model_json -class TestLocation(): +class TestModel_Location(): """ Test Class for Location """ @@ -3411,7 +3435,7 @@ def test_location_serialization(self): location_model_json2 = location_model.to_dict() assert location_model_json2 == location_model_json -class TestMention(): +class TestModel_Mention(): """ Test Class for Mention """ @@ -3447,7 +3471,7 @@ def test_mention_serialization(self): mention_model_json2 = mention_model.to_dict() assert mention_model_json2 == mention_model_json -class TestOriginalLabelsIn(): +class TestModel_OriginalLabelsIn(): """ Test Class for OriginalLabelsIn """ @@ -3493,7 +3517,7 @@ def test_original_labels_in_serialization(self): original_labels_in_model_json2 = original_labels_in_model.to_dict() assert original_labels_in_model_json2 == original_labels_in_model_json -class TestOriginalLabelsOut(): +class TestModel_OriginalLabelsOut(): """ Test Class for OriginalLabelsOut """ @@ -3539,7 +3563,7 @@ def test_original_labels_out_serialization(self): original_labels_out_model_json2 = original_labels_out_model.to_dict() assert original_labels_out_model_json2 == original_labels_out_model_json -class TestPagination(): +class TestModel_Pagination(): """ Test Class for Pagination """ @@ -3572,7 +3596,7 @@ def test_pagination_serialization(self): pagination_model_json2 = pagination_model.to_dict() assert pagination_model_json2 == pagination_model_json -class TestParagraphs(): +class TestModel_Paragraphs(): """ Test Class for Paragraphs """ @@ -3607,7 +3631,7 @@ def test_paragraphs_serialization(self): paragraphs_model_json2 = paragraphs_model.to_dict() assert paragraphs_model_json2 == paragraphs_model_json -class TestParties(): +class TestModel_Parties(): """ Test Class for Parties """ @@ -3659,7 +3683,7 @@ def test_parties_serialization(self): parties_model_json2 = parties_model.to_dict() assert parties_model_json2 == parties_model_json -class TestPaymentTerms(): +class TestModel_PaymentTerms(): """ Test Class for PaymentTerms """ @@ -3704,7 +3728,7 @@ def test_payment_terms_serialization(self): payment_terms_model_json2 = payment_terms_model.to_dict() assert payment_terms_model_json2 == payment_terms_model_json -class TestRowHeaders(): +class TestModel_RowHeaders(): """ Test Class for RowHeaders """ @@ -3746,7 +3770,7 @@ def test_row_headers_serialization(self): row_headers_model_json2 = row_headers_model.to_dict() assert row_headers_model_json2 == row_headers_model_json -class TestSectionTitle(): +class TestModel_SectionTitle(): """ Test Class for SectionTitle """ @@ -3782,7 +3806,7 @@ def test_section_title_serialization(self): section_title_model_json2 = section_title_model.to_dict() assert section_title_model_json2 == section_title_model_json -class TestSectionTitles(): +class TestModel_SectionTitles(): """ Test Class for SectionTitles """ @@ -3824,7 +3848,7 @@ def test_section_titles_serialization(self): section_titles_model_json2 = section_titles_model.to_dict() assert section_titles_model_json2 == section_titles_model_json -class TestShortDoc(): +class TestModel_ShortDoc(): """ Test Class for ShortDoc """ @@ -3854,7 +3878,7 @@ def test_short_doc_serialization(self): short_doc_model_json2 = short_doc_model.to_dict() assert short_doc_model_json2 == short_doc_model_json -class TestTableHeaders(): +class TestModel_TableHeaders(): """ Test Class for TableHeaders """ @@ -3889,7 +3913,7 @@ def test_table_headers_serialization(self): table_headers_model_json2 = table_headers_model.to_dict() assert table_headers_model_json2 == table_headers_model_json -class TestTableReturn(): +class TestModel_TableReturn(): """ Test Class for TableReturn """ @@ -4020,7 +4044,7 @@ def test_table_return_serialization(self): table_return_model_json2 = table_return_model.to_dict() assert table_return_model_json2 == table_return_model_json -class TestTableTitle(): +class TestModel_TableTitle(): """ Test Class for TableTitle """ @@ -4056,7 +4080,7 @@ def test_table_title_serialization(self): table_title_model_json2 = table_title_model.to_dict() assert table_title_model_json2 == table_title_model_json -class TestTables(): +class TestModel_Tables(): """ Test Class for Tables """ @@ -4176,7 +4200,7 @@ def test_tables_serialization(self): tables_model_json2 = tables_model.to_dict() assert tables_model_json2 == tables_model_json -class TestTerminationDates(): +class TestModel_TerminationDates(): """ Test Class for TerminationDates """ @@ -4215,7 +4239,7 @@ def test_termination_dates_serialization(self): termination_dates_model_json2 = termination_dates_model.to_dict() assert termination_dates_model_json2 == termination_dates_model_json -class TestTypeLabel(): +class TestModel_TypeLabel(): """ Test Class for TypeLabel """ @@ -4252,7 +4276,7 @@ def test_type_label_serialization(self): type_label_model_json2 = type_label_model.to_dict() assert type_label_model_json2 == type_label_model_json -class TestTypeLabelComparison(): +class TestModel_TypeLabelComparison(): """ Test Class for TypeLabelComparison """ @@ -4287,7 +4311,7 @@ def test_type_label_comparison_serialization(self): type_label_comparison_model_json2 = type_label_comparison_model.to_dict() assert type_label_comparison_model_json2 == type_label_comparison_model_json -class TestUnalignedElement(): +class TestModel_UnalignedElement(): """ Test Class for UnalignedElement """ @@ -4342,7 +4366,7 @@ def test_unaligned_element_serialization(self): unaligned_element_model_json2 = unaligned_element_model.to_dict() assert unaligned_element_model_json2 == unaligned_element_model_json -class TestUpdatedLabelsIn(): +class TestModel_UpdatedLabelsIn(): """ Test Class for UpdatedLabelsIn """ @@ -4388,7 +4412,7 @@ def test_updated_labels_in_serialization(self): updated_labels_in_model_json2 = updated_labels_in_model.to_dict() assert updated_labels_in_model_json2 == updated_labels_in_model_json -class TestUpdatedLabelsOut(): +class TestModel_UpdatedLabelsOut(): """ Test Class for UpdatedLabelsOut """ @@ -4434,7 +4458,7 @@ def test_updated_labels_out_serialization(self): updated_labels_out_model_json2 = updated_labels_out_model.to_dict() assert updated_labels_out_model_json2 == updated_labels_out_model_json -class TestValue(): +class TestModel_Value(): """ Test Class for Value """ diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 27d6361d2..19746cfae 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -56,6 +56,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -137,6 +139,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -230,6 +234,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -300,6 +306,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -384,6 +392,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -454,6 +464,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -542,6 +554,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -554,7 +568,7 @@ def test_create_configuration_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.POST, url, body=mock_response, @@ -607,8 +621,8 @@ def test_create_configuration_all_params(self): # Construct a dict representation of a SegmentSettings model segment_settings_model = {} - segment_settings_model['enabled'] = True - segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['enabled'] = False + segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['testString'] # Construct a dict representation of a NormalizationOperation model @@ -688,15 +702,15 @@ def test_create_configuration_all_params(self): enrichment_model['description'] = 'testString' enrichment_model['destination_field'] = 'testString' enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = True + enrichment_model['overwrite'] = False enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = True + enrichment_model['ignore_downstream_errors'] = False enrichment_model['options'] = enrichment_options_model # Construct a dict representation of a SourceSchedule model source_schedule_model = {} source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'testString' + source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'daily' # Construct a dict representation of a SourceOptionsFolder model @@ -719,11 +733,11 @@ def test_create_configuration_all_params(self): source_options_web_crawl_model = {} source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'gentle' - source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['crawl_speed'] = 'normal' + source_options_web_crawl_model['allow_untrusted_certificate'] = False source_options_web_crawl_model['maximum_hops'] = 38 source_options_web_crawl_model['request_timeout'] = 38 - source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] # Construct a dict representation of a SourceOptionsBuckets model @@ -788,7 +802,7 @@ def test_create_configuration_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.POST, url, body=mock_response, @@ -841,8 +855,8 @@ def test_create_configuration_value_error(self): # Construct a dict representation of a SegmentSettings model segment_settings_model = {} - segment_settings_model['enabled'] = True - segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['enabled'] = False + segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['testString'] # Construct a dict representation of a NormalizationOperation model @@ -922,15 +936,15 @@ def test_create_configuration_value_error(self): enrichment_model['description'] = 'testString' enrichment_model['destination_field'] = 'testString' enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = True + enrichment_model['overwrite'] = False enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = True + enrichment_model['ignore_downstream_errors'] = False enrichment_model['options'] = enrichment_options_model # Construct a dict representation of a SourceSchedule model source_schedule_model = {} source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'testString' + source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'daily' # Construct a dict representation of a SourceOptionsFolder model @@ -953,11 +967,11 @@ def test_create_configuration_value_error(self): source_options_web_crawl_model = {} source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'gentle' - source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['crawl_speed'] = 'normal' + source_options_web_crawl_model['allow_untrusted_certificate'] = False source_options_web_crawl_model['maximum_hops'] = 38 source_options_web_crawl_model['request_timeout'] = 38 - source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] # Construct a dict representation of a SourceOptionsBuckets model @@ -1011,6 +1025,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1023,7 +1039,7 @@ def test_list_configurations_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1057,7 +1073,7 @@ def test_list_configurations_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1085,7 +1101,7 @@ def test_list_configurations_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1115,6 +1131,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1127,7 +1145,7 @@ def test_get_configuration_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.GET, url, body=mock_response, @@ -1157,7 +1175,7 @@ def test_get_configuration_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.GET, url, body=mock_response, @@ -1189,6 +1207,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1201,7 +1221,7 @@ def test_update_configuration_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.PUT, url, body=mock_response, @@ -1254,8 +1274,8 @@ def test_update_configuration_all_params(self): # Construct a dict representation of a SegmentSettings model segment_settings_model = {} - segment_settings_model['enabled'] = True - segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['enabled'] = False + segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['testString'] # Construct a dict representation of a NormalizationOperation model @@ -1335,15 +1355,15 @@ def test_update_configuration_all_params(self): enrichment_model['description'] = 'testString' enrichment_model['destination_field'] = 'testString' enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = True + enrichment_model['overwrite'] = False enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = True + enrichment_model['ignore_downstream_errors'] = False enrichment_model['options'] = enrichment_options_model # Construct a dict representation of a SourceSchedule model source_schedule_model = {} source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'testString' + source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'daily' # Construct a dict representation of a SourceOptionsFolder model @@ -1366,11 +1386,11 @@ def test_update_configuration_all_params(self): source_options_web_crawl_model = {} source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'gentle' - source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['crawl_speed'] = 'normal' + source_options_web_crawl_model['allow_untrusted_certificate'] = False source_options_web_crawl_model['maximum_hops'] = 38 source_options_web_crawl_model['request_timeout'] = 38 - source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] # Construct a dict representation of a SourceOptionsBuckets model @@ -1437,7 +1457,7 @@ def test_update_configuration_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": true, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": {"anyKey": "anyValue"}}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": false, "time_zone": "time_zone", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": false, "crawl_speed": "gentle", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.PUT, url, body=mock_response, @@ -1490,8 +1510,8 @@ def test_update_configuration_value_error(self): # Construct a dict representation of a SegmentSettings model segment_settings_model = {} - segment_settings_model['enabled'] = True - segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['enabled'] = False + segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['testString'] # Construct a dict representation of a NormalizationOperation model @@ -1571,15 +1591,15 @@ def test_update_configuration_value_error(self): enrichment_model['description'] = 'testString' enrichment_model['destination_field'] = 'testString' enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = True + enrichment_model['overwrite'] = False enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = True + enrichment_model['ignore_downstream_errors'] = False enrichment_model['options'] = enrichment_options_model # Construct a dict representation of a SourceSchedule model source_schedule_model = {} source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'testString' + source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'daily' # Construct a dict representation of a SourceOptionsFolder model @@ -1602,11 +1622,11 @@ def test_update_configuration_value_error(self): source_options_web_crawl_model = {} source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'gentle' - source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['crawl_speed'] = 'normal' + source_options_web_crawl_model['allow_untrusted_certificate'] = False source_options_web_crawl_model['maximum_hops'] = 38 source_options_web_crawl_model['request_timeout'] = 38 - source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] # Construct a dict representation of a SourceOptionsBuckets model @@ -1662,6 +1682,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1746,6 +1768,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1758,7 +1782,7 @@ def test_create_collection_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.POST, url, body=mock_response, @@ -1800,7 +1824,7 @@ def test_create_collection_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.POST, url, body=mock_response, @@ -1835,6 +1859,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1847,7 +1873,7 @@ def test_list_collections_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1881,7 +1907,7 @@ def test_list_collections_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1909,7 +1935,7 @@ def test_list_collections_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1939,6 +1965,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1951,7 +1979,7 @@ def test_get_collection_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.GET, url, body=mock_response, @@ -1981,7 +2009,7 @@ def test_get_collection_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.GET, url, body=mock_response, @@ -2013,6 +2041,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2025,7 +2055,7 @@ def test_update_collection_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.PUT, url, body=mock_response, @@ -2066,7 +2096,7 @@ def test_update_collection_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": false, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.PUT, url, body=mock_response, @@ -2102,6 +2132,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2176,6 +2208,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2260,6 +2294,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2334,6 +2370,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2425,6 +2463,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2493,6 +2533,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2567,6 +2609,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2683,6 +2727,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2751,6 +2797,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2825,6 +2873,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2940,6 +2990,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3018,6 +3070,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3130,6 +3184,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3208,6 +3264,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3326,6 +3384,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3414,6 +3474,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3426,7 +3488,7 @@ def test_query_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3445,18 +3507,18 @@ def test_query_all_params(self): return_ = 'testString' offset = 38 sort = 'testString' - highlight = True + highlight = False passages_fields = 'testString' passages_count = 100 passages_characters = 50 - deduplicate = True + deduplicate = False deduplicate_field = 'testString' - similar = True + similar = False similar_document_ids = 'testString' similar_fields = 'testString' bias = 'testString' - spelling_suggestions = True - x_watson_logging_opt_out = True + spelling_suggestions = False + x_watson_logging_opt_out = False # Invoke method response = _service.query( @@ -3500,17 +3562,17 @@ def test_query_all_params(self): assert req_body['return'] == 'testString' assert req_body['offset'] == 38 assert req_body['sort'] == 'testString' - assert req_body['highlight'] == True + assert req_body['highlight'] == False assert req_body['passages.fields'] == 'testString' assert req_body['passages.count'] == 100 assert req_body['passages.characters'] == 50 - assert req_body['deduplicate'] == True + assert req_body['deduplicate'] == False assert req_body['deduplicate.field'] == 'testString' - assert req_body['similar'] == True + assert req_body['similar'] == False assert req_body['similar.document_ids'] == 'testString' assert req_body['similar.fields'] == 'testString' assert req_body['bias'] == 'testString' - assert req_body['spelling_suggestions'] == True + assert req_body['spelling_suggestions'] == False @responses.activate @@ -3520,7 +3582,7 @@ def test_query_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3550,7 +3612,7 @@ def test_query_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3582,6 +3644,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3594,7 +3658,7 @@ def test_query_notices_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3613,12 +3677,12 @@ def test_query_notices_all_params(self): return_ = ['testString'] offset = 38 sort = ['testString'] - highlight = True + highlight = False passages_fields = ['testString'] passages_count = 100 passages_characters = 50 deduplicate_field = 'testString' - similar = True + similar = False similar_document_ids = ['testString'] similar_fields = ['testString'] @@ -3678,7 +3742,7 @@ def test_query_notices_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3708,7 +3772,7 @@ def test_query_notices_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3740,6 +3804,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3752,7 +3818,7 @@ def test_federated_query_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3771,17 +3837,17 @@ def test_federated_query_all_params(self): return_ = 'testString' offset = 38 sort = 'testString' - highlight = True + highlight = False passages_fields = 'testString' passages_count = 100 passages_characters = 50 - deduplicate = True + deduplicate = False deduplicate_field = 'testString' - similar = True + similar = False similar_document_ids = 'testString' similar_fields = 'testString' bias = 'testString' - x_watson_logging_opt_out = True + x_watson_logging_opt_out = False # Invoke method response = _service.federated_query( @@ -3825,13 +3891,13 @@ def test_federated_query_all_params(self): assert req_body['return'] == 'testString' assert req_body['offset'] == 38 assert req_body['sort'] == 'testString' - assert req_body['highlight'] == True + assert req_body['highlight'] == False assert req_body['passages.fields'] == 'testString' assert req_body['passages.count'] == 100 assert req_body['passages.characters'] == 50 - assert req_body['deduplicate'] == True + assert req_body['deduplicate'] == False assert req_body['deduplicate.field'] == 'testString' - assert req_body['similar'] == True + assert req_body['similar'] == False assert req_body['similar.document_ids'] == 'testString' assert req_body['similar.fields'] == 'testString' assert req_body['bias'] == 'testString' @@ -3844,7 +3910,7 @@ def test_federated_query_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3863,13 +3929,13 @@ def test_federated_query_required_params(self): return_ = 'testString' offset = 38 sort = 'testString' - highlight = True + highlight = False passages_fields = 'testString' passages_count = 100 passages_characters = 50 - deduplicate = True + deduplicate = False deduplicate_field = 'testString' - similar = True + similar = False similar_document_ids = 'testString' similar_fields = 'testString' bias = 'testString' @@ -3915,13 +3981,13 @@ def test_federated_query_required_params(self): assert req_body['return'] == 'testString' assert req_body['offset'] == 38 assert req_body['sort'] == 'testString' - assert req_body['highlight'] == True + assert req_body['highlight'] == False assert req_body['passages.fields'] == 'testString' assert req_body['passages.count'] == 100 assert req_body['passages.characters'] == 50 - assert req_body['deduplicate'] == True + assert req_body['deduplicate'] == False assert req_body['deduplicate.field'] == 'testString' - assert req_body['similar'] == True + assert req_body['similar'] == False assert req_body['similar.document_ids'] == 'testString' assert req_body['similar.fields'] == 'testString' assert req_body['bias'] == 'testString' @@ -3934,7 +4000,7 @@ def test_federated_query_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3953,13 +4019,13 @@ def test_federated_query_value_error(self): return_ = 'testString' offset = 38 sort = 'testString' - highlight = True + highlight = False passages_fields = 'testString' passages_count = 100 passages_characters = 50 - deduplicate = True + deduplicate = False deduplicate_field = 'testString' - similar = True + similar = False similar_document_ids = 'testString' similar_fields = 'testString' bias = 'testString' @@ -3985,6 +4051,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3997,7 +4065,7 @@ def test_federated_query_notices_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4015,9 +4083,9 @@ def test_federated_query_notices_all_params(self): return_ = ['testString'] offset = 38 sort = ['testString'] - highlight = True + highlight = False deduplicate_field = 'testString' - similar = True + similar = False similar_document_ids = ['testString'] similar_fields = ['testString'] @@ -4070,7 +4138,7 @@ def test_federated_query_notices_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4104,7 +4172,7 @@ def test_federated_query_notices_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4136,6 +4204,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4270,6 +4340,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4344,6 +4416,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4444,6 +4518,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4512,6 +4588,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4590,6 +4668,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4662,6 +4742,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4740,6 +4822,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4832,6 +4916,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -4908,6 +4994,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5000,6 +5088,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5092,6 +5182,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5170,6 +5262,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5193,7 +5287,7 @@ def test_create_event_all_params(self): event_data_model = {} event_data_model['environment_id'] = 'testString' event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + event_data_model['client_timestamp'] = "2019-01-01T12:00:00Z" event_data_model['display_rank'] = 38 event_data_model['collection_id'] = 'testString' event_data_model['document_id'] = 'testString' @@ -5236,7 +5330,7 @@ def test_create_event_value_error(self): event_data_model = {} event_data_model['environment_id'] = 'testString' event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + event_data_model['client_timestamp'] = "2019-01-01T12:00:00Z" event_data_model['display_rank'] = 38 event_data_model['collection_id'] = 'testString' event_data_model['document_id'] = 'testString' @@ -5266,6 +5360,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5371,6 +5467,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5468,6 +5566,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5565,6 +5665,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5662,6 +5764,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5759,6 +5863,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5862,6 +5968,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -5932,6 +6040,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6060,6 +6170,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6134,6 +6246,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6266,6 +6380,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6350,6 +6466,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6420,6 +6538,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6523,6 +6643,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6597,6 +6719,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -6672,7 +6796,7 @@ def test_delete_gateway_value_error(self): # Start of Model Tests ############################################################################## # region -class TestAggregationResult(): +class TestModel_AggregationResult(): """ Test Class for AggregationResult """ @@ -6702,7 +6826,7 @@ def test_aggregation_result_serialization(self): aggregation_result_model_json2 = aggregation_result_model.to_dict() assert aggregation_result_model_json2 == aggregation_result_model_json -class TestCollection(): +class TestModel_Collection(): """ Test Class for Collection """ @@ -6731,12 +6855,12 @@ def test_collection_serialization(self): training_status_model['minimum_examples_added'] = False training_status_model['sufficient_label_diversity'] = False training_status_model['notices'] = 0 - training_status_model['successfully_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - training_status_model['data_updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_status_model['successfully_trained'] = "2019-01-01T12:00:00Z" + training_status_model['data_updated'] = "2019-01-01T12:00:00Z" source_status_model = {} # SourceStatus source_status_model['status'] = 'complete' - source_status_model['next_crawl'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + source_status_model['next_crawl'] = "2019-01-01T12:00:00Z" collection_crawl_status_model = {} # CollectionCrawlStatus collection_crawl_status_model['source_crawl'] = source_status_model @@ -6757,8 +6881,8 @@ def test_collection_serialization(self): collection_model_json['collection_id'] = 'testString' collection_model_json['name'] = 'testString' collection_model_json['description'] = 'testString' - collection_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - collection_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + collection_model_json['created'] = "2019-01-01T12:00:00Z" + collection_model_json['updated'] = "2019-01-01T12:00:00Z" collection_model_json['status'] = 'active' collection_model_json['configuration_id'] = 'testString' collection_model_json['language'] = 'testString' @@ -6783,7 +6907,7 @@ def test_collection_serialization(self): collection_model_json2 = collection_model.to_dict() assert collection_model_json2 == collection_model_json -class TestCollectionCrawlStatus(): +class TestModel_CollectionCrawlStatus(): """ Test Class for CollectionCrawlStatus """ @@ -6797,7 +6921,7 @@ def test_collection_crawl_status_serialization(self): source_status_model = {} # SourceStatus source_status_model['status'] = 'running' - source_status_model['next_crawl'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + source_status_model['next_crawl'] = "2019-01-01T12:00:00Z" # Construct a json representation of a CollectionCrawlStatus model collection_crawl_status_model_json = {} @@ -6818,7 +6942,7 @@ def test_collection_crawl_status_serialization(self): collection_crawl_status_model_json2 = collection_crawl_status_model.to_dict() assert collection_crawl_status_model_json2 == collection_crawl_status_model_json -class TestCollectionDiskUsage(): +class TestModel_CollectionDiskUsage(): """ Test Class for CollectionDiskUsage """ @@ -6847,7 +6971,7 @@ def test_collection_disk_usage_serialization(self): collection_disk_usage_model_json2 = collection_disk_usage_model.to_dict() assert collection_disk_usage_model_json2 == collection_disk_usage_model_json -class TestCollectionUsage(): +class TestModel_CollectionUsage(): """ Test Class for CollectionUsage """ @@ -6877,7 +7001,7 @@ def test_collection_usage_serialization(self): collection_usage_model_json2 = collection_usage_model.to_dict() assert collection_usage_model_json2 == collection_usage_model_json -class TestCompletions(): +class TestModel_Completions(): """ Test Class for Completions """ @@ -6906,7 +7030,7 @@ def test_completions_serialization(self): completions_model_json2 = completions_model.to_dict() assert completions_model_json2 == completions_model_json -class TestConfiguration(): +class TestModel_Configuration(): """ Test Class for Configuration """ @@ -6956,7 +7080,7 @@ def test_configuration_serialization(self): segment_settings_model = {} # SegmentSettings segment_settings_model['enabled'] = True - segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['custom-field-1', 'custom-field-2'] normalization_operation_model = {} # NormalizationOperation @@ -7024,9 +7148,9 @@ def test_configuration_serialization(self): enrichment_model['description'] = 'testString' enrichment_model['destination_field'] = 'enriched_title' enrichment_model['source_field'] = 'title' - enrichment_model['overwrite'] = True + enrichment_model['overwrite'] = False enrichment_model['enrichment'] = 'natural_language_understanding' - enrichment_model['ignore_downstream_errors'] = True + enrichment_model['ignore_downstream_errors'] = False enrichment_model['options'] = enrichment_options_model source_schedule_model = {} # SourceSchedule @@ -7050,11 +7174,11 @@ def test_configuration_serialization(self): source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'gentle' - source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['crawl_speed'] = 'normal' + source_options_web_crawl_model['allow_untrusted_certificate'] = False source_options_web_crawl_model['maximum_hops'] = 38 source_options_web_crawl_model['request_timeout'] = 38 - source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] source_options_buckets_model = {} # SourceOptionsBuckets @@ -7079,8 +7203,8 @@ def test_configuration_serialization(self): configuration_model_json = {} configuration_model_json['configuration_id'] = 'testString' configuration_model_json['name'] = 'testString' - configuration_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - configuration_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + configuration_model_json['created'] = "2019-01-01T12:00:00Z" + configuration_model_json['updated'] = "2019-01-01T12:00:00Z" configuration_model_json['description'] = 'testString' configuration_model_json['conversions'] = conversions_model configuration_model_json['enrichments'] = [enrichment_model] @@ -7102,7 +7226,7 @@ def test_configuration_serialization(self): configuration_model_json2 = configuration_model.to_dict() assert configuration_model_json2 == configuration_model_json -class TestConversions(): +class TestModel_Conversions(): """ Test Class for Conversions """ @@ -7151,8 +7275,8 @@ def test_conversions_serialization(self): html_settings_model['exclude_tag_attributes'] = ['testString'] segment_settings_model = {} # SegmentSettings - segment_settings_model['enabled'] = True - segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['enabled'] = False + segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['testString'] normalization_operation_model = {} # NormalizationOperation @@ -7184,7 +7308,7 @@ def test_conversions_serialization(self): conversions_model_json2 = conversions_model.to_dict() assert conversions_model_json2 == conversions_model_json -class TestCreateEventResponse(): +class TestModel_CreateEventResponse(): """ Test Class for CreateEventResponse """ @@ -7199,7 +7323,7 @@ def test_create_event_response_serialization(self): event_data_model = {} # EventData event_data_model['environment_id'] = 'testString' event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + event_data_model['client_timestamp'] = "2019-01-01T12:00:00Z" event_data_model['display_rank'] = 38 event_data_model['collection_id'] = 'testString' event_data_model['document_id'] = 'testString' @@ -7225,7 +7349,7 @@ def test_create_event_response_serialization(self): create_event_response_model_json2 = create_event_response_model.to_dict() assert create_event_response_model_json2 == create_event_response_model_json -class TestCredentialDetails(): +class TestModel_CredentialDetails(): """ Test Class for CredentialDetails """ @@ -7272,7 +7396,7 @@ def test_credential_details_serialization(self): credential_details_model_json2 = credential_details_model.to_dict() assert credential_details_model_json2 == credential_details_model_json -class TestCredentials(): +class TestModel_Credentials(): """ Test Class for Credentials """ @@ -7327,7 +7451,7 @@ def test_credentials_serialization(self): credentials_model_json2 = credentials_model.to_dict() assert credentials_model_json2 == credentials_model_json -class TestCredentialsList(): +class TestModel_CredentialsList(): """ Test Class for CredentialsList """ @@ -7385,7 +7509,7 @@ def test_credentials_list_serialization(self): credentials_list_model_json2 = credentials_list_model.to_dict() assert credentials_list_model_json2 == credentials_list_model_json -class TestDeleteCollectionResponse(): +class TestModel_DeleteCollectionResponse(): """ Test Class for DeleteCollectionResponse """ @@ -7415,7 +7539,7 @@ def test_delete_collection_response_serialization(self): delete_collection_response_model_json2 = delete_collection_response_model.to_dict() assert delete_collection_response_model_json2 == delete_collection_response_model_json -class TestDeleteConfigurationResponse(): +class TestModel_DeleteConfigurationResponse(): """ Test Class for DeleteConfigurationResponse """ @@ -7429,7 +7553,7 @@ def test_delete_configuration_response_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'configuration_in_use' - notice_model['created'] = datetime_to_string(string_to_datetime("2016-09-28T12:34:00.000Z")) + notice_model['created'] = "2016-09-28T12:34:00Z" notice_model['document_id'] = 'testString' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -7457,7 +7581,7 @@ def test_delete_configuration_response_serialization(self): delete_configuration_response_model_json2 = delete_configuration_response_model.to_dict() assert delete_configuration_response_model_json2 == delete_configuration_response_model_json -class TestDeleteCredentials(): +class TestModel_DeleteCredentials(): """ Test Class for DeleteCredentials """ @@ -7487,7 +7611,7 @@ def test_delete_credentials_serialization(self): delete_credentials_model_json2 = delete_credentials_model.to_dict() assert delete_credentials_model_json2 == delete_credentials_model_json -class TestDeleteDocumentResponse(): +class TestModel_DeleteDocumentResponse(): """ Test Class for DeleteDocumentResponse """ @@ -7517,7 +7641,7 @@ def test_delete_document_response_serialization(self): delete_document_response_model_json2 = delete_document_response_model.to_dict() assert delete_document_response_model_json2 == delete_document_response_model_json -class TestDeleteEnvironmentResponse(): +class TestModel_DeleteEnvironmentResponse(): """ Test Class for DeleteEnvironmentResponse """ @@ -7547,7 +7671,7 @@ def test_delete_environment_response_serialization(self): delete_environment_response_model_json2 = delete_environment_response_model.to_dict() assert delete_environment_response_model_json2 == delete_environment_response_model_json -class TestDiskUsage(): +class TestModel_DiskUsage(): """ Test Class for DiskUsage """ @@ -7577,7 +7701,7 @@ def test_disk_usage_serialization(self): disk_usage_model_json2 = disk_usage_model.to_dict() assert disk_usage_model_json2 == disk_usage_model_json -class TestDocumentAccepted(): +class TestModel_DocumentAccepted(): """ Test Class for DocumentAccepted """ @@ -7591,7 +7715,7 @@ def test_document_accepted_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + notice_model['created'] = "2019-01-01T12:00:00Z" notice_model['document_id'] = 'testString' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -7619,7 +7743,7 @@ def test_document_accepted_serialization(self): document_accepted_model_json2 = document_accepted_model.to_dict() assert document_accepted_model_json2 == document_accepted_model_json -class TestDocumentCounts(): +class TestModel_DocumentCounts(): """ Test Class for DocumentCounts """ @@ -7651,7 +7775,7 @@ def test_document_counts_serialization(self): document_counts_model_json2 = document_counts_model.to_dict() assert document_counts_model_json2 == document_counts_model_json -class TestDocumentStatus(): +class TestModel_DocumentStatus(): """ Test Class for DocumentStatus """ @@ -7665,7 +7789,7 @@ def test_document_status_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'index_342' - notice_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + notice_model['created'] = "2019-01-01T12:00:00Z" notice_model['document_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -7698,7 +7822,7 @@ def test_document_status_serialization(self): document_status_model_json2 = document_status_model.to_dict() assert document_status_model_json2 == document_status_model_json -class TestEnrichment(): +class TestModel_Enrichment(): """ Test Class for Enrichment """ @@ -7763,9 +7887,9 @@ def test_enrichment_serialization(self): enrichment_model_json['description'] = 'testString' enrichment_model_json['destination_field'] = 'testString' enrichment_model_json['source_field'] = 'testString' - enrichment_model_json['overwrite'] = True + enrichment_model_json['overwrite'] = False enrichment_model_json['enrichment'] = 'testString' - enrichment_model_json['ignore_downstream_errors'] = True + enrichment_model_json['ignore_downstream_errors'] = False enrichment_model_json['options'] = enrichment_options_model # Construct a model instance of Enrichment by calling from_dict on the json representation @@ -7783,7 +7907,7 @@ def test_enrichment_serialization(self): enrichment_model_json2 = enrichment_model.to_dict() assert enrichment_model_json2 == enrichment_model_json -class TestEnrichmentOptions(): +class TestModel_EnrichmentOptions(): """ Test Class for EnrichmentOptions """ @@ -7859,7 +7983,7 @@ def test_enrichment_options_serialization(self): enrichment_options_model_json2 = enrichment_options_model.to_dict() assert enrichment_options_model_json2 == enrichment_options_model_json -class TestEnvironment(): +class TestModel_Environment(): """ Test Class for Environment """ @@ -7899,8 +8023,8 @@ def test_environment_serialization(self): environment_model_json['environment_id'] = 'testString' environment_model_json['name'] = 'testString' environment_model_json['description'] = 'testString' - environment_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - environment_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + environment_model_json['created'] = "2019-01-01T12:00:00Z" + environment_model_json['updated'] = "2019-01-01T12:00:00Z" environment_model_json['status'] = 'active' environment_model_json['read_only'] = True environment_model_json['size'] = 'LT' @@ -7923,7 +8047,7 @@ def test_environment_serialization(self): environment_model_json2 = environment_model.to_dict() assert environment_model_json2 == environment_model_json -class TestEnvironmentDocuments(): +class TestModel_EnvironmentDocuments(): """ Test Class for EnvironmentDocuments """ @@ -7953,7 +8077,7 @@ def test_environment_documents_serialization(self): environment_documents_model_json2 = environment_documents_model.to_dict() assert environment_documents_model_json2 == environment_documents_model_json -class TestEventData(): +class TestModel_EventData(): """ Test Class for EventData """ @@ -7967,7 +8091,7 @@ def test_event_data_serialization(self): event_data_model_json = {} event_data_model_json['environment_id'] = 'testString' event_data_model_json['session_token'] = 'testString' - event_data_model_json['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + event_data_model_json['client_timestamp'] = "2019-01-01T12:00:00Z" event_data_model_json['display_rank'] = 38 event_data_model_json['collection_id'] = 'testString' event_data_model_json['document_id'] = 'testString' @@ -7988,7 +8112,7 @@ def test_event_data_serialization(self): event_data_model_json2 = event_data_model.to_dict() assert event_data_model_json2 == event_data_model_json -class TestExpansion(): +class TestModel_Expansion(): """ Test Class for Expansion """ @@ -8018,7 +8142,7 @@ def test_expansion_serialization(self): expansion_model_json2 = expansion_model.to_dict() assert expansion_model_json2 == expansion_model_json -class TestExpansions(): +class TestModel_Expansions(): """ Test Class for Expansions """ @@ -8053,7 +8177,7 @@ def test_expansions_serialization(self): expansions_model_json2 = expansions_model.to_dict() assert expansions_model_json2 == expansions_model_json -class TestField(): +class TestModel_Field(): """ Test Class for Field """ @@ -8083,7 +8207,7 @@ def test_field_serialization(self): field_model_json2 = field_model.to_dict() assert field_model_json2 == field_model_json -class TestFontSetting(): +class TestModel_FontSetting(): """ Test Class for FontSetting """ @@ -8117,7 +8241,7 @@ def test_font_setting_serialization(self): font_setting_model_json2 = font_setting_model.to_dict() assert font_setting_model_json2 == font_setting_model_json -class TestGateway(): +class TestModel_Gateway(): """ Test Class for Gateway """ @@ -8150,7 +8274,7 @@ def test_gateway_serialization(self): gateway_model_json2 = gateway_model.to_dict() assert gateway_model_json2 == gateway_model_json -class TestGatewayDelete(): +class TestModel_GatewayDelete(): """ Test Class for GatewayDelete """ @@ -8180,7 +8304,7 @@ def test_gateway_delete_serialization(self): gateway_delete_model_json2 = gateway_delete_model.to_dict() assert gateway_delete_model_json2 == gateway_delete_model_json -class TestGatewayList(): +class TestModel_GatewayList(): """ Test Class for GatewayList """ @@ -8218,7 +8342,7 @@ def test_gateway_list_serialization(self): gateway_list_model_json2 = gateway_list_model.to_dict() assert gateway_list_model_json2 == gateway_list_model_json -class TestHtmlSettings(): +class TestModel_HtmlSettings(): """ Test Class for HtmlSettings """ @@ -8257,7 +8381,7 @@ def test_html_settings_serialization(self): html_settings_model_json2 = html_settings_model.to_dict() assert html_settings_model_json2 == html_settings_model_json -class TestIndexCapacity(): +class TestModel_IndexCapacity(): """ Test Class for IndexCapacity """ @@ -8302,7 +8426,7 @@ def test_index_capacity_serialization(self): index_capacity_model_json2 = index_capacity_model.to_dict() assert index_capacity_model_json2 == index_capacity_model_json -class TestListCollectionFieldsResponse(): +class TestModel_ListCollectionFieldsResponse(): """ Test Class for ListCollectionFieldsResponse """ @@ -8337,7 +8461,7 @@ def test_list_collection_fields_response_serialization(self): list_collection_fields_response_model_json2 = list_collection_fields_response_model.to_dict() assert list_collection_fields_response_model_json2 == list_collection_fields_response_model_json -class TestListCollectionsResponse(): +class TestModel_ListCollectionsResponse(): """ Test Class for ListCollectionsResponse """ @@ -8366,12 +8490,12 @@ def test_list_collections_response_serialization(self): training_status_model['minimum_examples_added'] = True training_status_model['sufficient_label_diversity'] = True training_status_model['notices'] = 38 - training_status_model['successfully_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - training_status_model['data_updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_status_model['successfully_trained'] = "2019-01-01T12:00:00Z" + training_status_model['data_updated'] = "2019-01-01T12:00:00Z" source_status_model = {} # SourceStatus source_status_model['status'] = 'running' - source_status_model['next_crawl'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + source_status_model['next_crawl'] = "2019-01-01T12:00:00Z" collection_crawl_status_model = {} # CollectionCrawlStatus collection_crawl_status_model['source_crawl'] = source_status_model @@ -8391,8 +8515,8 @@ def test_list_collections_response_serialization(self): collection_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' collection_model['name'] = 'example' collection_model['description'] = 'this is a demo collection' - collection_model['created'] = datetime_to_string(string_to_datetime("2015-08-24T18:42:25.324Z")) - collection_model['updated'] = datetime_to_string(string_to_datetime("2015-08-24T18:42:25.324Z")) + collection_model['created'] = "2015-08-24T18:42:25.324000Z" + collection_model['updated'] = "2015-08-24T18:42:25.324000Z" collection_model['status'] = 'active' collection_model['configuration_id'] = '6963be41-2dea-4f79-8f52-127c63c479b0' collection_model['language'] = 'en' @@ -8421,7 +8545,7 @@ def test_list_collections_response_serialization(self): list_collections_response_model_json2 = list_collections_response_model.to_dict() assert list_collections_response_model_json2 == list_collections_response_model_json -class TestListConfigurationsResponse(): +class TestModel_ListConfigurationsResponse(): """ Test Class for ListConfigurationsResponse """ @@ -8470,8 +8594,8 @@ def test_list_configurations_response_serialization(self): html_settings_model['exclude_tag_attributes'] = ['testString'] segment_settings_model = {} # SegmentSettings - segment_settings_model['enabled'] = True - segment_settings_model['selector_tags'] = ['testString'] + segment_settings_model['enabled'] = False + segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['testString'] normalization_operation_model = {} # NormalizationOperation @@ -8539,14 +8663,14 @@ def test_list_configurations_response_serialization(self): enrichment_model['description'] = 'testString' enrichment_model['destination_field'] = 'testString' enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = True + enrichment_model['overwrite'] = False enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = True + enrichment_model['ignore_downstream_errors'] = False enrichment_model['options'] = enrichment_options_model source_schedule_model = {} # SourceSchedule source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'testString' + source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'daily' source_options_folder_model = {} # SourceOptionsFolder @@ -8565,11 +8689,11 @@ def test_list_configurations_response_serialization(self): source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'gentle' - source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['crawl_speed'] = 'normal' + source_options_web_crawl_model['allow_untrusted_certificate'] = False source_options_web_crawl_model['maximum_hops'] = 38 source_options_web_crawl_model['request_timeout'] = 38 - source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] source_options_buckets_model = {} # SourceOptionsBuckets @@ -8593,8 +8717,8 @@ def test_list_configurations_response_serialization(self): configuration_model = {} # Configuration configuration_model['configuration_id'] = 'testString' configuration_model['name'] = 'testString' - configuration_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - configuration_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + configuration_model['created'] = "2019-01-01T12:00:00Z" + configuration_model['updated'] = "2019-01-01T12:00:00Z" configuration_model['description'] = 'testString' configuration_model['conversions'] = conversions_model configuration_model['enrichments'] = [enrichment_model] @@ -8620,7 +8744,7 @@ def test_list_configurations_response_serialization(self): list_configurations_response_model_json2 = list_configurations_response_model.to_dict() assert list_configurations_response_model_json2 == list_configurations_response_model_json -class TestListEnvironmentsResponse(): +class TestModel_ListEnvironmentsResponse(): """ Test Class for ListEnvironmentsResponse """ @@ -8659,8 +8783,8 @@ def test_list_environments_response_serialization(self): environment_model['environment_id'] = 'ecbda78e-fb06-40b1-a43f-a039fac0adc6' environment_model['name'] = 'byod_environment' environment_model['description'] = 'Private Data Environment' - environment_model['created'] = datetime_to_string(string_to_datetime("2017-07-14T12:54:40.985Z")) - environment_model['updated'] = datetime_to_string(string_to_datetime("2017-07-14T12:54:40.985Z")) + environment_model['created'] = "2017-07-14T12:54:40.985000Z" + environment_model['updated'] = "2017-07-14T12:54:40.985000Z" environment_model['status'] = 'active' environment_model['read_only'] = False environment_model['size'] = 'LT' @@ -8687,7 +8811,7 @@ def test_list_environments_response_serialization(self): list_environments_response_model_json2 = list_environments_response_model.to_dict() assert list_environments_response_model_json2 == list_environments_response_model_json -class TestLogQueryResponse(): +class TestModel_LogQueryResponse(): """ Test Class for LogQueryResponse """ @@ -8716,8 +8840,8 @@ def test_log_query_response_serialization(self): log_query_response_result_model['document_type'] = 'query' log_query_response_result_model['natural_language_query'] = 'testString' log_query_response_result_model['document_results'] = log_query_response_result_documents_model - log_query_response_result_model['created_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - log_query_response_result_model['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + log_query_response_result_model['created_timestamp'] = "2019-01-01T12:00:00Z" + log_query_response_result_model['client_timestamp'] = "2019-01-01T12:00:00Z" log_query_response_result_model['query_id'] = 'testString' log_query_response_result_model['session_token'] = 'testString' log_query_response_result_model['collection_id'] = 'testString' @@ -8746,7 +8870,7 @@ def test_log_query_response_serialization(self): log_query_response_model_json2 = log_query_response_model.to_dict() assert log_query_response_model_json2 == log_query_response_model_json -class TestLogQueryResponseResult(): +class TestModel_LogQueryResponseResult(): """ Test Class for LogQueryResponseResult """ @@ -8776,8 +8900,8 @@ def test_log_query_response_result_serialization(self): log_query_response_result_model_json['document_type'] = 'query' log_query_response_result_model_json['natural_language_query'] = 'testString' log_query_response_result_model_json['document_results'] = log_query_response_result_documents_model - log_query_response_result_model_json['created_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - log_query_response_result_model_json['client_timestamp'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + log_query_response_result_model_json['created_timestamp'] = "2019-01-01T12:00:00Z" + log_query_response_result_model_json['client_timestamp'] = "2019-01-01T12:00:00Z" log_query_response_result_model_json['query_id'] = 'testString' log_query_response_result_model_json['session_token'] = 'testString' log_query_response_result_model_json['collection_id'] = 'testString' @@ -8801,7 +8925,7 @@ def test_log_query_response_result_serialization(self): log_query_response_result_model_json2 = log_query_response_result_model.to_dict() assert log_query_response_result_model_json2 == log_query_response_result_model_json -class TestLogQueryResponseResultDocuments(): +class TestModel_LogQueryResponseResultDocuments(): """ Test Class for LogQueryResponseResultDocuments """ @@ -8840,7 +8964,7 @@ def test_log_query_response_result_documents_serialization(self): log_query_response_result_documents_model_json2 = log_query_response_result_documents_model.to_dict() assert log_query_response_result_documents_model_json2 == log_query_response_result_documents_model_json -class TestLogQueryResponseResultDocumentsResult(): +class TestModel_LogQueryResponseResultDocumentsResult(): """ Test Class for LogQueryResponseResultDocumentsResult """ @@ -8873,7 +8997,7 @@ def test_log_query_response_result_documents_result_serialization(self): log_query_response_result_documents_result_model_json2 = log_query_response_result_documents_result_model.to_dict() assert log_query_response_result_documents_result_model_json2 == log_query_response_result_documents_result_model_json -class TestMetricAggregation(): +class TestModel_MetricAggregation(): """ Test Class for MetricAggregation """ @@ -8886,7 +9010,7 @@ def test_metric_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. metric_aggregation_result_model = {} # MetricAggregationResult - metric_aggregation_result_model['key_as_string'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + metric_aggregation_result_model['key_as_string'] = "2019-01-01T12:00:00Z" metric_aggregation_result_model['key'] = 26 metric_aggregation_result_model['matching_results'] = 38 metric_aggregation_result_model['event_rate'] = 72.5 @@ -8912,7 +9036,7 @@ def test_metric_aggregation_serialization(self): metric_aggregation_model_json2 = metric_aggregation_model.to_dict() assert metric_aggregation_model_json2 == metric_aggregation_model_json -class TestMetricAggregationResult(): +class TestModel_MetricAggregationResult(): """ Test Class for MetricAggregationResult """ @@ -8924,7 +9048,7 @@ def test_metric_aggregation_result_serialization(self): # Construct a json representation of a MetricAggregationResult model metric_aggregation_result_model_json = {} - metric_aggregation_result_model_json['key_as_string'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + metric_aggregation_result_model_json['key_as_string'] = "2019-01-01T12:00:00Z" metric_aggregation_result_model_json['key'] = 26 metric_aggregation_result_model_json['matching_results'] = 38 metric_aggregation_result_model_json['event_rate'] = 72.5 @@ -8944,7 +9068,7 @@ def test_metric_aggregation_result_serialization(self): metric_aggregation_result_model_json2 = metric_aggregation_result_model.to_dict() assert metric_aggregation_result_model_json2 == metric_aggregation_result_model_json -class TestMetricResponse(): +class TestModel_MetricResponse(): """ Test Class for MetricResponse """ @@ -8957,7 +9081,7 @@ def test_metric_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. metric_aggregation_result_model = {} # MetricAggregationResult - metric_aggregation_result_model['key_as_string'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + metric_aggregation_result_model['key_as_string'] = "2019-01-01T12:00:00Z" metric_aggregation_result_model['key'] = 26 metric_aggregation_result_model['matching_results'] = 38 metric_aggregation_result_model['event_rate'] = 72.5 @@ -8986,7 +9110,7 @@ def test_metric_response_serialization(self): metric_response_model_json2 = metric_response_model.to_dict() assert metric_response_model_json2 == metric_response_model_json -class TestMetricTokenAggregation(): +class TestModel_MetricTokenAggregation(): """ Test Class for MetricTokenAggregation """ @@ -9023,7 +9147,7 @@ def test_metric_token_aggregation_serialization(self): metric_token_aggregation_model_json2 = metric_token_aggregation_model.to_dict() assert metric_token_aggregation_model_json2 == metric_token_aggregation_model_json -class TestMetricTokenAggregationResult(): +class TestModel_MetricTokenAggregationResult(): """ Test Class for MetricTokenAggregationResult """ @@ -9054,7 +9178,7 @@ def test_metric_token_aggregation_result_serialization(self): metric_token_aggregation_result_model_json2 = metric_token_aggregation_result_model.to_dict() assert metric_token_aggregation_result_model_json2 == metric_token_aggregation_result_model_json -class TestMetricTokenResponse(): +class TestModel_MetricTokenResponse(): """ Test Class for MetricTokenResponse """ @@ -9094,7 +9218,7 @@ def test_metric_token_response_serialization(self): metric_token_response_model_json2 = metric_token_response_model.to_dict() assert metric_token_response_model_json2 == metric_token_response_model_json -class TestNluEnrichmentConcepts(): +class TestModel_NluEnrichmentConcepts(): """ Test Class for NluEnrichmentConcepts """ @@ -9123,7 +9247,7 @@ def test_nlu_enrichment_concepts_serialization(self): nlu_enrichment_concepts_model_json2 = nlu_enrichment_concepts_model.to_dict() assert nlu_enrichment_concepts_model_json2 == nlu_enrichment_concepts_model_json -class TestNluEnrichmentEmotion(): +class TestModel_NluEnrichmentEmotion(): """ Test Class for NluEnrichmentEmotion """ @@ -9153,7 +9277,7 @@ def test_nlu_enrichment_emotion_serialization(self): nlu_enrichment_emotion_model_json2 = nlu_enrichment_emotion_model.to_dict() assert nlu_enrichment_emotion_model_json2 == nlu_enrichment_emotion_model_json -class TestNluEnrichmentEntities(): +class TestModel_NluEnrichmentEntities(): """ Test Class for NluEnrichmentEntities """ @@ -9188,7 +9312,7 @@ def test_nlu_enrichment_entities_serialization(self): nlu_enrichment_entities_model_json2 = nlu_enrichment_entities_model.to_dict() assert nlu_enrichment_entities_model_json2 == nlu_enrichment_entities_model_json -class TestNluEnrichmentFeatures(): +class TestModel_NluEnrichmentFeatures(): """ Test Class for NluEnrichmentFeatures """ @@ -9259,7 +9383,7 @@ def test_nlu_enrichment_features_serialization(self): nlu_enrichment_features_model_json2 = nlu_enrichment_features_model.to_dict() assert nlu_enrichment_features_model_json2 == nlu_enrichment_features_model_json -class TestNluEnrichmentKeywords(): +class TestModel_NluEnrichmentKeywords(): """ Test Class for NluEnrichmentKeywords """ @@ -9290,7 +9414,7 @@ def test_nlu_enrichment_keywords_serialization(self): nlu_enrichment_keywords_model_json2 = nlu_enrichment_keywords_model.to_dict() assert nlu_enrichment_keywords_model_json2 == nlu_enrichment_keywords_model_json -class TestNluEnrichmentRelations(): +class TestModel_NluEnrichmentRelations(): """ Test Class for NluEnrichmentRelations """ @@ -9319,7 +9443,7 @@ def test_nlu_enrichment_relations_serialization(self): nlu_enrichment_relations_model_json2 = nlu_enrichment_relations_model.to_dict() assert nlu_enrichment_relations_model_json2 == nlu_enrichment_relations_model_json -class TestNluEnrichmentSemanticRoles(): +class TestModel_NluEnrichmentSemanticRoles(): """ Test Class for NluEnrichmentSemanticRoles """ @@ -9350,7 +9474,7 @@ def test_nlu_enrichment_semantic_roles_serialization(self): nlu_enrichment_semantic_roles_model_json2 = nlu_enrichment_semantic_roles_model.to_dict() assert nlu_enrichment_semantic_roles_model_json2 == nlu_enrichment_semantic_roles_model_json -class TestNluEnrichmentSentiment(): +class TestModel_NluEnrichmentSentiment(): """ Test Class for NluEnrichmentSentiment """ @@ -9380,7 +9504,7 @@ def test_nlu_enrichment_sentiment_serialization(self): nlu_enrichment_sentiment_model_json2 = nlu_enrichment_sentiment_model.to_dict() assert nlu_enrichment_sentiment_model_json2 == nlu_enrichment_sentiment_model_json -class TestNormalizationOperation(): +class TestModel_NormalizationOperation(): """ Test Class for NormalizationOperation """ @@ -9411,7 +9535,7 @@ def test_normalization_operation_serialization(self): normalization_operation_model_json2 = normalization_operation_model.to_dict() assert normalization_operation_model_json2 == normalization_operation_model_json -class TestNotice(): +class TestModel_Notice(): """ Test Class for Notice """ @@ -9424,7 +9548,7 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} notice_model_json['notice_id'] = 'testString' - notice_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + notice_model_json['created'] = "2019-01-01T12:00:00Z" notice_model_json['document_id'] = 'testString' notice_model_json['query_id'] = 'testString' notice_model_json['severity'] = 'warning' @@ -9446,7 +9570,7 @@ def test_notice_serialization(self): notice_model_json2 = notice_model.to_dict() assert notice_model_json2 == notice_model_json -class TestPdfHeadingDetection(): +class TestModel_PdfHeadingDetection(): """ Test Class for PdfHeadingDetection """ @@ -9485,7 +9609,7 @@ def test_pdf_heading_detection_serialization(self): pdf_heading_detection_model_json2 = pdf_heading_detection_model.to_dict() assert pdf_heading_detection_model_json2 == pdf_heading_detection_model_json -class TestPdfSettings(): +class TestModel_PdfSettings(): """ Test Class for PdfSettings """ @@ -9527,7 +9651,7 @@ def test_pdf_settings_serialization(self): pdf_settings_model_json2 = pdf_settings_model.to_dict() assert pdf_settings_model_json2 == pdf_settings_model_json -class TestQueryAggregation(): +class TestModel_QueryAggregation(): """ Test Class for QueryAggregation """ @@ -9557,7 +9681,7 @@ def test_query_aggregation_serialization(self): query_aggregation_model_json2 = query_aggregation_model.to_dict() assert query_aggregation_model_json2 == query_aggregation_model_json -class TestQueryNoticesResponse(): +class TestModel_QueryNoticesResponse(): """ Test Class for QueryNoticesResponse """ @@ -9575,7 +9699,7 @@ def test_query_notices_response_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'xpath_not_found' - notice_model['created'] = datetime_to_string(string_to_datetime("2016-09-20T17:26:17.000Z")) + notice_model['created'] = "2016-09-20T17:26:17Z" notice_model['document_id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -9592,7 +9716,7 @@ def test_query_notices_response_serialization(self): query_notices_result_model['file_type'] = 'html' query_notices_result_model['sha1'] = 'de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3' query_notices_result_model['notices'] = [notice_model] - query_notices_result_model['foo'] = { 'foo': 'bar' } + query_notices_result_model['score'] = { 'foo': 'bar' } query_aggregation_model = {} # Histogram query_aggregation_model['type'] = 'histogram' @@ -9631,7 +9755,7 @@ def test_query_notices_response_serialization(self): query_notices_response_model_json2 = query_notices_response_model.to_dict() assert query_notices_response_model_json2 == query_notices_response_model_json -class TestQueryNoticesResult(): +class TestModel_QueryNoticesResult(): """ Test Class for QueryNoticesResult """ @@ -9649,7 +9773,7 @@ def test_query_notices_result_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + notice_model['created'] = "2019-01-01T12:00:00Z" notice_model['document_id'] = 'testString' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -9684,7 +9808,17 @@ def test_query_notices_result_serialization(self): query_notices_result_model_json2 = query_notices_result_model.to_dict() assert query_notices_result_model_json2 == query_notices_result_model_json -class TestQueryPassages(): + # Test get_properties and set_properties methods. + query_notices_result_model.set_properties({}) + actual_dict = query_notices_result_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': { 'foo': 'bar' }} + query_notices_result_model.set_properties(expected_dict) + actual_dict = query_notices_result_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_QueryPassages(): """ Test Class for QueryPassages """ @@ -9718,7 +9852,7 @@ def test_query_passages_serialization(self): query_passages_model_json2 = query_passages_model.to_dict() assert query_passages_model_json2 == query_passages_model_json -class TestQueryResponse(): +class TestModel_QueryResponse(): """ Test Class for QueryResponse """ @@ -9739,7 +9873,7 @@ def test_query_response_serialization(self): query_result_model['metadata'] = {} query_result_model['collection_id'] = 'testString' query_result_model['result_metadata'] = query_result_metadata_model - query_result_model['foo'] = { 'foo': 'bar' } + query_result_model['score'] = { 'foo': 'bar' } query_aggregation_model = {} # Histogram query_aggregation_model['type'] = 'histogram' @@ -9784,7 +9918,7 @@ def test_query_response_serialization(self): query_response_model_json2 = query_response_model.to_dict() assert query_response_model_json2 == query_response_model_json -class TestQueryResult(): +class TestModel_QueryResult(): """ Test Class for QueryResult """ @@ -9823,7 +9957,17 @@ def test_query_result_serialization(self): query_result_model_json2 = query_result_model.to_dict() assert query_result_model_json2 == query_result_model_json -class TestQueryResultMetadata(): + # Test get_properties and set_properties methods. + query_result_model.set_properties({}) + actual_dict = query_result_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': { 'foo': 'bar' }} + query_result_model.set_properties(expected_dict) + actual_dict = query_result_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_QueryResultMetadata(): """ Test Class for QueryResultMetadata """ @@ -9853,7 +9997,7 @@ def test_query_result_metadata_serialization(self): query_result_metadata_model_json2 = query_result_metadata_model.to_dict() assert query_result_metadata_model_json2 == query_result_metadata_model_json -class TestRetrievalDetails(): +class TestModel_RetrievalDetails(): """ Test Class for RetrievalDetails """ @@ -9882,7 +10026,7 @@ def test_retrieval_details_serialization(self): retrieval_details_model_json2 = retrieval_details_model.to_dict() assert retrieval_details_model_json2 == retrieval_details_model_json -class TestSduStatus(): +class TestModel_SduStatus(): """ Test Class for SduStatus """ @@ -9921,7 +10065,7 @@ def test_sdu_status_serialization(self): sdu_status_model_json2 = sdu_status_model.to_dict() assert sdu_status_model_json2 == sdu_status_model_json -class TestSduStatusCustomFields(): +class TestModel_SduStatusCustomFields(): """ Test Class for SduStatusCustomFields """ @@ -9951,7 +10095,7 @@ def test_sdu_status_custom_fields_serialization(self): sdu_status_custom_fields_model_json2 = sdu_status_custom_fields_model.to_dict() assert sdu_status_custom_fields_model_json2 == sdu_status_custom_fields_model_json -class TestSearchStatus(): +class TestModel_SearchStatus(): """ Test Class for SearchStatus """ @@ -9983,7 +10127,7 @@ def test_search_status_serialization(self): search_status_model_json2 = search_status_model.to_dict() assert search_status_model_json2 == search_status_model_json -class TestSegmentSettings(): +class TestModel_SegmentSettings(): """ Test Class for SegmentSettings """ @@ -9995,8 +10139,8 @@ def test_segment_settings_serialization(self): # Construct a json representation of a SegmentSettings model segment_settings_model_json = {} - segment_settings_model_json['enabled'] = True - segment_settings_model_json['selector_tags'] = ['testString'] + segment_settings_model_json['enabled'] = False + segment_settings_model_json['selector_tags'] = ['h1', 'h2'] segment_settings_model_json['annotated_fields'] = ['testString'] # Construct a model instance of SegmentSettings by calling from_dict on the json representation @@ -10014,7 +10158,7 @@ def test_segment_settings_serialization(self): segment_settings_model_json2 = segment_settings_model.to_dict() assert segment_settings_model_json2 == segment_settings_model_json -class TestSource(): +class TestModel_Source(): """ Test Class for Source """ @@ -10028,7 +10172,7 @@ def test_source_serialization(self): source_schedule_model = {} # SourceSchedule source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'testString' + source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'daily' source_options_folder_model = {} # SourceOptionsFolder @@ -10047,11 +10191,11 @@ def test_source_serialization(self): source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'gentle' - source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['crawl_speed'] = 'normal' + source_options_web_crawl_model['allow_untrusted_certificate'] = False source_options_web_crawl_model['maximum_hops'] = 38 source_options_web_crawl_model['request_timeout'] = 38 - source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] source_options_buckets_model = {} # SourceOptionsBuckets @@ -10088,7 +10232,7 @@ def test_source_serialization(self): source_model_json2 = source_model.to_dict() assert source_model_json2 == source_model_json -class TestSourceOptions(): +class TestModel_SourceOptions(): """ Test Class for SourceOptions """ @@ -10116,11 +10260,11 @@ def test_source_options_serialization(self): source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'gentle' - source_options_web_crawl_model['allow_untrusted_certificate'] = True + source_options_web_crawl_model['crawl_speed'] = 'normal' + source_options_web_crawl_model['allow_untrusted_certificate'] = False source_options_web_crawl_model['maximum_hops'] = 38 source_options_web_crawl_model['request_timeout'] = 38 - source_options_web_crawl_model['override_robots_txt'] = True + source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] source_options_buckets_model = {} # SourceOptionsBuckets @@ -10151,7 +10295,7 @@ def test_source_options_serialization(self): source_options_model_json2 = source_options_model.to_dict() assert source_options_model_json2 == source_options_model_json -class TestSourceOptionsBuckets(): +class TestModel_SourceOptionsBuckets(): """ Test Class for SourceOptionsBuckets """ @@ -10181,7 +10325,7 @@ def test_source_options_buckets_serialization(self): source_options_buckets_model_json2 = source_options_buckets_model.to_dict() assert source_options_buckets_model_json2 == source_options_buckets_model_json -class TestSourceOptionsFolder(): +class TestModel_SourceOptionsFolder(): """ Test Class for SourceOptionsFolder """ @@ -10212,7 +10356,7 @@ def test_source_options_folder_serialization(self): source_options_folder_model_json2 = source_options_folder_model.to_dict() assert source_options_folder_model_json2 == source_options_folder_model_json -class TestSourceOptionsObject(): +class TestModel_SourceOptionsObject(): """ Test Class for SourceOptionsObject """ @@ -10242,7 +10386,7 @@ def test_source_options_object_serialization(self): source_options_object_model_json2 = source_options_object_model.to_dict() assert source_options_object_model_json2 == source_options_object_model_json -class TestSourceOptionsSiteColl(): +class TestModel_SourceOptionsSiteColl(): """ Test Class for SourceOptionsSiteColl """ @@ -10272,7 +10416,7 @@ def test_source_options_site_coll_serialization(self): source_options_site_coll_model_json2 = source_options_site_coll_model.to_dict() assert source_options_site_coll_model_json2 == source_options_site_coll_model_json -class TestSourceOptionsWebCrawl(): +class TestModel_SourceOptionsWebCrawl(): """ Test Class for SourceOptionsWebCrawl """ @@ -10286,11 +10430,11 @@ def test_source_options_web_crawl_serialization(self): source_options_web_crawl_model_json = {} source_options_web_crawl_model_json['url'] = 'testString' source_options_web_crawl_model_json['limit_to_starting_hosts'] = True - source_options_web_crawl_model_json['crawl_speed'] = 'gentle' - source_options_web_crawl_model_json['allow_untrusted_certificate'] = True + source_options_web_crawl_model_json['crawl_speed'] = 'normal' + source_options_web_crawl_model_json['allow_untrusted_certificate'] = False source_options_web_crawl_model_json['maximum_hops'] = 38 source_options_web_crawl_model_json['request_timeout'] = 38 - source_options_web_crawl_model_json['override_robots_txt'] = True + source_options_web_crawl_model_json['override_robots_txt'] = False source_options_web_crawl_model_json['blacklist'] = ['testString'] # Construct a model instance of SourceOptionsWebCrawl by calling from_dict on the json representation @@ -10308,7 +10452,7 @@ def test_source_options_web_crawl_serialization(self): source_options_web_crawl_model_json2 = source_options_web_crawl_model.to_dict() assert source_options_web_crawl_model_json2 == source_options_web_crawl_model_json -class TestSourceSchedule(): +class TestModel_SourceSchedule(): """ Test Class for SourceSchedule """ @@ -10321,7 +10465,7 @@ def test_source_schedule_serialization(self): # Construct a json representation of a SourceSchedule model source_schedule_model_json = {} source_schedule_model_json['enabled'] = True - source_schedule_model_json['time_zone'] = 'testString' + source_schedule_model_json['time_zone'] = 'America/New_York' source_schedule_model_json['frequency'] = 'daily' # Construct a model instance of SourceSchedule by calling from_dict on the json representation @@ -10339,7 +10483,7 @@ def test_source_schedule_serialization(self): source_schedule_model_json2 = source_schedule_model.to_dict() assert source_schedule_model_json2 == source_schedule_model_json -class TestSourceStatus(): +class TestModel_SourceStatus(): """ Test Class for SourceStatus """ @@ -10352,7 +10496,7 @@ def test_source_status_serialization(self): # Construct a json representation of a SourceStatus model source_status_model_json = {} source_status_model_json['status'] = 'running' - source_status_model_json['next_crawl'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + source_status_model_json['next_crawl'] = "2019-01-01T12:00:00Z" # Construct a model instance of SourceStatus by calling from_dict on the json representation source_status_model = SourceStatus.from_dict(source_status_model_json) @@ -10369,7 +10513,7 @@ def test_source_status_serialization(self): source_status_model_json2 = source_status_model.to_dict() assert source_status_model_json2 == source_status_model_json -class TestTokenDictRule(): +class TestModel_TokenDictRule(): """ Test Class for TokenDictRule """ @@ -10401,7 +10545,7 @@ def test_token_dict_rule_serialization(self): token_dict_rule_model_json2 = token_dict_rule_model.to_dict() assert token_dict_rule_model_json2 == token_dict_rule_model_json -class TestTokenDictStatusResponse(): +class TestModel_TokenDictStatusResponse(): """ Test Class for TokenDictStatusResponse """ @@ -10431,7 +10575,7 @@ def test_token_dict_status_response_serialization(self): token_dict_status_response_model_json2 = token_dict_status_response_model.to_dict() assert token_dict_status_response_model_json2 == token_dict_status_response_model_json -class TestTopHitsResults(): +class TestModel_TopHitsResults(): """ Test Class for TopHitsResults """ @@ -10474,7 +10618,7 @@ def test_top_hits_results_serialization(self): top_hits_results_model_json2 = top_hits_results_model.to_dict() assert top_hits_results_model_json2 == top_hits_results_model_json -class TestTrainingDataSet(): +class TestModel_TrainingDataSet(): """ Test Class for TrainingDataSet """ @@ -10518,7 +10662,7 @@ def test_training_data_set_serialization(self): training_data_set_model_json2 = training_data_set_model.to_dict() assert training_data_set_model_json2 == training_data_set_model_json -class TestTrainingExample(): +class TestModel_TrainingExample(): """ Test Class for TrainingExample """ @@ -10549,7 +10693,7 @@ def test_training_example_serialization(self): training_example_model_json2 = training_example_model.to_dict() assert training_example_model_json2 == training_example_model_json -class TestTrainingExampleList(): +class TestModel_TrainingExampleList(): """ Test Class for TrainingExampleList """ @@ -10585,7 +10729,7 @@ def test_training_example_list_serialization(self): training_example_list_model_json2 = training_example_list_model.to_dict() assert training_example_list_model_json2 == training_example_list_model_json -class TestTrainingQuery(): +class TestModel_TrainingQuery(): """ Test Class for TrainingQuery """ @@ -10624,7 +10768,7 @@ def test_training_query_serialization(self): training_query_model_json2 = training_query_model.to_dict() assert training_query_model_json2 == training_query_model_json -class TestTrainingStatus(): +class TestModel_TrainingStatus(): """ Test Class for TrainingStatus """ @@ -10643,8 +10787,8 @@ def test_training_status_serialization(self): training_status_model_json['minimum_examples_added'] = True training_status_model_json['sufficient_label_diversity'] = True training_status_model_json['notices'] = 38 - training_status_model_json['successfully_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - training_status_model_json['data_updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_status_model_json['successfully_trained'] = "2019-01-01T12:00:00Z" + training_status_model_json['data_updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of TrainingStatus by calling from_dict on the json representation training_status_model = TrainingStatus.from_dict(training_status_model_json) @@ -10661,7 +10805,7 @@ def test_training_status_serialization(self): training_status_model_json2 = training_status_model.to_dict() assert training_status_model_json2 == training_status_model_json -class TestWordHeadingDetection(): +class TestModel_WordHeadingDetection(): """ Test Class for WordHeadingDetection """ @@ -10705,7 +10849,7 @@ def test_word_heading_detection_serialization(self): word_heading_detection_model_json2 = word_heading_detection_model.to_dict() assert word_heading_detection_model_json2 == word_heading_detection_model_json -class TestWordSettings(): +class TestModel_WordSettings(): """ Test Class for WordSettings """ @@ -10752,7 +10896,7 @@ def test_word_settings_serialization(self): word_settings_model_json2 = word_settings_model.to_dict() assert word_settings_model_json2 == word_settings_model_json -class TestWordStyle(): +class TestModel_WordStyle(): """ Test Class for WordStyle """ @@ -10782,7 +10926,7 @@ def test_word_style_serialization(self): word_style_model_json2 = word_style_model.to_dict() assert word_style_model_json2 == word_style_model_json -class TestXPathPatterns(): +class TestModel_XPathPatterns(): """ Test Class for XPathPatterns """ @@ -10811,7 +10955,7 @@ def test_x_path_patterns_serialization(self): x_path_patterns_model_json2 = x_path_patterns_model.to_dict() assert x_path_patterns_model_json2 == x_path_patterns_model_json -class TestCalculation(): +class TestModel_Calculation(): """ Test Class for Calculation """ @@ -10843,7 +10987,7 @@ def test_calculation_serialization(self): calculation_model_json2 = calculation_model.to_dict() assert calculation_model_json2 == calculation_model_json -class TestFilter(): +class TestModel_Filter(): """ Test Class for Filter """ @@ -10874,7 +11018,7 @@ def test_filter_serialization(self): filter_model_json2 = filter_model.to_dict() assert filter_model_json2 == filter_model_json -class TestHistogram(): +class TestModel_Histogram(): """ Test Class for Histogram """ @@ -10906,7 +11050,7 @@ def test_histogram_serialization(self): histogram_model_json2 = histogram_model.to_dict() assert histogram_model_json2 == histogram_model_json -class TestNested(): +class TestModel_Nested(): """ Test Class for Nested """ @@ -10937,7 +11081,7 @@ def test_nested_serialization(self): nested_model_json2 = nested_model.to_dict() assert nested_model_json2 == nested_model_json -class TestTerm(): +class TestModel_Term(): """ Test Class for Term """ @@ -10969,7 +11113,7 @@ def test_term_serialization(self): term_model_json2 = term_model.to_dict() assert term_model_json2 == term_model_json -class TestTimeslice(): +class TestModel_Timeslice(): """ Test Class for Timeslice """ @@ -11002,7 +11146,7 @@ def test_timeslice_serialization(self): timeslice_model_json2 = timeslice_model.to_dict() assert timeslice_model_json2 == timeslice_model_json -class TestTopHits(): +class TestModel_TopHits(): """ Test Class for TopHits """ diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index c2861b6d2..500d6a127 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -55,6 +55,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -125,6 +127,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -137,7 +141,7 @@ def test_create_collection_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.POST, url, body=mock_response, @@ -153,7 +157,7 @@ def test_create_collection_all_params(self): project_id = 'testString' name = 'testString' description = 'testString' - language = 'testString' + language = 'en' enrichments = [collection_enrichment_model] # Invoke method @@ -173,7 +177,7 @@ def test_create_collection_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['language'] == 'testString' + assert req_body['language'] == 'en' assert req_body['enrichments'] == [collection_enrichment_model] @@ -184,7 +188,7 @@ def test_create_collection_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.POST, url, body=mock_response, @@ -200,7 +204,7 @@ def test_create_collection_value_error(self): project_id = 'testString' name = 'testString' description = 'testString' - language = 'testString' + language = 'en' enrichments = [collection_enrichment_model] # Pass in all but one required param and check for a ValueError @@ -224,6 +228,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -236,7 +242,7 @@ def test_get_collection_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.GET, url, body=mock_response, @@ -266,7 +272,7 @@ def test_get_collection_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.GET, url, body=mock_response, @@ -298,6 +304,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -310,7 +318,7 @@ def test_update_collection_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.POST, url, body=mock_response, @@ -356,7 +364,7 @@ def test_update_collection_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "language", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' responses.add(responses.POST, url, body=mock_response, @@ -396,6 +404,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -474,6 +484,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -486,7 +498,7 @@ def test_query_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -509,9 +521,9 @@ def test_query_all_params(self): query_large_passages_model['per_document'] = True query_large_passages_model['max_per_document'] = 38 query_large_passages_model['fields'] = ['testString'] - query_large_passages_model['count'] = 100 + query_large_passages_model['count'] = 400 query_large_passages_model['characters'] = 50 - query_large_passages_model['find_answers'] = True + query_large_passages_model['find_answers'] = False query_large_passages_model['max_answers_per_passage'] = 38 # Set up parameter values @@ -579,7 +591,7 @@ def test_query_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -607,7 +619,7 @@ def test_query_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": {"anyKey": "anyValue"}}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -637,6 +649,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -758,6 +772,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -880,6 +896,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -996,6 +1014,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1110,6 +1130,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1190,6 +1212,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1216,7 +1240,7 @@ def test_add_document_all_params(self): filename = 'testString' file_content_type = 'application/json' metadata = 'testString' - x_watson_discovery_force = True + x_watson_discovery_force = False # Invoke method response = _service.add_document( @@ -1304,6 +1328,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1331,7 +1357,7 @@ def test_update_document_all_params(self): filename = 'testString' file_content_type = 'application/json' metadata = 'testString' - x_watson_discovery_force = True + x_watson_discovery_force = False # Invoke method response = _service.update_document( @@ -1424,6 +1450,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1447,7 +1475,7 @@ def test_delete_document_all_params(self): project_id = 'testString' collection_id = 'testString' document_id = 'testString' - x_watson_discovery_force = True + x_watson_discovery_force = False # Invoke method response = _service.delete_document( @@ -1546,6 +1574,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1616,6 +1646,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1680,6 +1712,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1778,6 +1812,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1852,6 +1888,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1954,6 +1992,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2032,6 +2072,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2044,7 +2086,7 @@ def test_analyze_document_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' responses.add(responses.POST, url, body=mock_response, @@ -2082,7 +2124,7 @@ def test_analyze_document_required_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' responses.add(responses.POST, url, body=mock_response, @@ -2112,7 +2154,7 @@ def test_analyze_document_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": {"anyKey": "anyValue"}}}}' + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' responses.add(responses.POST, url, body=mock_response, @@ -2154,6 +2196,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2224,6 +2268,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2372,6 +2418,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2446,6 +2494,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2531,6 +2581,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2609,6 +2661,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2670,6 +2724,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2818,6 +2874,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2888,6 +2946,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2991,6 +3051,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3065,6 +3127,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3134,7 +3198,7 @@ def test_delete_user_data_value_error(self): # Start of Model Tests ############################################################################## # region -class TestAnalyzedDocument(): +class TestModel_AnalyzedDocument(): """ Test Class for AnalyzedDocument """ @@ -3148,7 +3212,7 @@ def test_analyzed_document_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + notice_model['created'] = "2019-01-01T12:00:00Z" notice_model['document_id'] = 'testString' notice_model['collection_id'] = 'testString' notice_model['query_id'] = 'testString' @@ -3180,7 +3244,7 @@ def test_analyzed_document_serialization(self): analyzed_document_model_json2 = analyzed_document_model.to_dict() assert analyzed_document_model_json2 == analyzed_document_model_json -class TestAnalyzedResult(): +class TestModel_AnalyzedResult(): """ Test Class for AnalyzedResult """ @@ -3210,7 +3274,17 @@ def test_analyzed_result_serialization(self): analyzed_result_model_json2 = analyzed_result_model.to_dict() assert analyzed_result_model_json2 == analyzed_result_model_json -class TestCollection(): + # Test get_properties and set_properties methods. + analyzed_result_model.set_properties({}) + actual_dict = analyzed_result_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': { 'foo': 'bar' }} + analyzed_result_model.set_properties(expected_dict) + actual_dict = analyzed_result_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_Collection(): """ Test Class for Collection """ @@ -3240,7 +3314,7 @@ def test_collection_serialization(self): collection_model_json2 = collection_model.to_dict() assert collection_model_json2 == collection_model_json -class TestCollectionDetails(): +class TestModel_CollectionDetails(): """ Test Class for CollectionDetails """ @@ -3261,8 +3335,8 @@ def test_collection_details_serialization(self): collection_details_model_json['collection_id'] = 'testString' collection_details_model_json['name'] = 'testString' collection_details_model_json['description'] = 'testString' - collection_details_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - collection_details_model_json['language'] = 'testString' + collection_details_model_json['created'] = "2019-01-01T12:00:00Z" + collection_details_model_json['language'] = 'en' collection_details_model_json['enrichments'] = [collection_enrichment_model] # Construct a model instance of CollectionDetails by calling from_dict on the json representation @@ -3280,7 +3354,7 @@ def test_collection_details_serialization(self): collection_details_model_json2 = collection_details_model.to_dict() assert collection_details_model_json2 == collection_details_model_json -class TestCollectionEnrichment(): +class TestModel_CollectionEnrichment(): """ Test Class for CollectionEnrichment """ @@ -3310,7 +3384,7 @@ def test_collection_enrichment_serialization(self): collection_enrichment_model_json2 = collection_enrichment_model.to_dict() assert collection_enrichment_model_json2 == collection_enrichment_model_json -class TestCompletions(): +class TestModel_Completions(): """ Test Class for Completions """ @@ -3339,7 +3413,7 @@ def test_completions_serialization(self): completions_model_json2 = completions_model.to_dict() assert completions_model_json2 == completions_model_json -class TestComponentSettingsAggregation(): +class TestModel_ComponentSettingsAggregation(): """ Test Class for ComponentSettingsAggregation """ @@ -3371,7 +3445,7 @@ def test_component_settings_aggregation_serialization(self): component_settings_aggregation_model_json2 = component_settings_aggregation_model.to_dict() assert component_settings_aggregation_model_json2 == component_settings_aggregation_model_json -class TestComponentSettingsFieldsShown(): +class TestModel_ComponentSettingsFieldsShown(): """ Test Class for ComponentSettingsFieldsShown """ @@ -3410,7 +3484,7 @@ def test_component_settings_fields_shown_serialization(self): component_settings_fields_shown_model_json2 = component_settings_fields_shown_model.to_dict() assert component_settings_fields_shown_model_json2 == component_settings_fields_shown_model_json -class TestComponentSettingsFieldsShownBody(): +class TestModel_ComponentSettingsFieldsShownBody(): """ Test Class for ComponentSettingsFieldsShownBody """ @@ -3440,7 +3514,7 @@ def test_component_settings_fields_shown_body_serialization(self): component_settings_fields_shown_body_model_json2 = component_settings_fields_shown_body_model.to_dict() assert component_settings_fields_shown_body_model_json2 == component_settings_fields_shown_body_model_json -class TestComponentSettingsFieldsShownTitle(): +class TestModel_ComponentSettingsFieldsShownTitle(): """ Test Class for ComponentSettingsFieldsShownTitle """ @@ -3469,7 +3543,7 @@ def test_component_settings_fields_shown_title_serialization(self): component_settings_fields_shown_title_model_json2 = component_settings_fields_shown_title_model.to_dict() assert component_settings_fields_shown_title_model_json2 == component_settings_fields_shown_title_model_json -class TestComponentSettingsResponse(): +class TestModel_ComponentSettingsResponse(): """ Test Class for ComponentSettingsResponse """ @@ -3521,7 +3595,7 @@ def test_component_settings_response_serialization(self): component_settings_response_model_json2 = component_settings_response_model.to_dict() assert component_settings_response_model_json2 == component_settings_response_model_json -class TestCreateEnrichment(): +class TestModel_CreateEnrichment(): """ Test Class for CreateEnrichment """ @@ -3561,7 +3635,7 @@ def test_create_enrichment_serialization(self): create_enrichment_model_json2 = create_enrichment_model.to_dict() assert create_enrichment_model_json2 == create_enrichment_model_json -class TestDefaultQueryParams(): +class TestModel_DefaultQueryParams(): """ Test Class for DefaultQueryParams """ @@ -3618,7 +3692,7 @@ def test_default_query_params_serialization(self): default_query_params_model_json2 = default_query_params_model.to_dict() assert default_query_params_model_json2 == default_query_params_model_json -class TestDefaultQueryParamsPassages(): +class TestModel_DefaultQueryParamsPassages(): """ Test Class for DefaultQueryParamsPassages """ @@ -3652,7 +3726,7 @@ def test_default_query_params_passages_serialization(self): default_query_params_passages_model_json2 = default_query_params_passages_model.to_dict() assert default_query_params_passages_model_json2 == default_query_params_passages_model_json -class TestDefaultQueryParamsSuggestedRefinements(): +class TestModel_DefaultQueryParamsSuggestedRefinements(): """ Test Class for DefaultQueryParamsSuggestedRefinements """ @@ -3682,7 +3756,7 @@ def test_default_query_params_suggested_refinements_serialization(self): default_query_params_suggested_refinements_model_json2 = default_query_params_suggested_refinements_model.to_dict() assert default_query_params_suggested_refinements_model_json2 == default_query_params_suggested_refinements_model_json -class TestDefaultQueryParamsTableResults(): +class TestModel_DefaultQueryParamsTableResults(): """ Test Class for DefaultQueryParamsTableResults """ @@ -3713,7 +3787,7 @@ def test_default_query_params_table_results_serialization(self): default_query_params_table_results_model_json2 = default_query_params_table_results_model.to_dict() assert default_query_params_table_results_model_json2 == default_query_params_table_results_model_json -class TestDeleteDocumentResponse(): +class TestModel_DeleteDocumentResponse(): """ Test Class for DeleteDocumentResponse """ @@ -3743,7 +3817,7 @@ def test_delete_document_response_serialization(self): delete_document_response_model_json2 = delete_document_response_model.to_dict() assert delete_document_response_model_json2 == delete_document_response_model_json -class TestDocumentAccepted(): +class TestModel_DocumentAccepted(): """ Test Class for DocumentAccepted """ @@ -3773,7 +3847,7 @@ def test_document_accepted_serialization(self): document_accepted_model_json2 = document_accepted_model.to_dict() assert document_accepted_model_json2 == document_accepted_model_json -class TestDocumentAttribute(): +class TestModel_DocumentAttribute(): """ Test Class for DocumentAttribute """ @@ -3810,7 +3884,7 @@ def test_document_attribute_serialization(self): document_attribute_model_json2 = document_attribute_model.to_dict() assert document_attribute_model_json2 == document_attribute_model_json -class TestEnrichment(): +class TestModel_Enrichment(): """ Test Class for Enrichment """ @@ -3851,7 +3925,7 @@ def test_enrichment_serialization(self): enrichment_model_json2 = enrichment_model.to_dict() assert enrichment_model_json2 == enrichment_model_json -class TestEnrichmentOptions(): +class TestModel_EnrichmentOptions(): """ Test Class for EnrichmentOptions """ @@ -3883,7 +3957,7 @@ def test_enrichment_options_serialization(self): enrichment_options_model_json2 = enrichment_options_model.to_dict() assert enrichment_options_model_json2 == enrichment_options_model_json -class TestEnrichments(): +class TestModel_Enrichments(): """ Test Class for Enrichments """ @@ -3927,7 +4001,7 @@ def test_enrichments_serialization(self): enrichments_model_json2 = enrichments_model.to_dict() assert enrichments_model_json2 == enrichments_model_json -class TestField(): +class TestModel_Field(): """ Test Class for Field """ @@ -3958,7 +4032,7 @@ def test_field_serialization(self): field_model_json2 = field_model.to_dict() assert field_model_json2 == field_model_json -class TestListCollectionsResponse(): +class TestModel_ListCollectionsResponse(): """ Test Class for ListCollectionsResponse """ @@ -3993,7 +4067,7 @@ def test_list_collections_response_serialization(self): list_collections_response_model_json2 = list_collections_response_model.to_dict() assert list_collections_response_model_json2 == list_collections_response_model_json -class TestListFieldsResponse(): +class TestModel_ListFieldsResponse(): """ Test Class for ListFieldsResponse """ @@ -4029,7 +4103,7 @@ def test_list_fields_response_serialization(self): list_fields_response_model_json2 = list_fields_response_model.to_dict() assert list_fields_response_model_json2 == list_fields_response_model_json -class TestListProjectsResponse(): +class TestModel_ListProjectsResponse(): """ Test Class for ListProjectsResponse """ @@ -4078,7 +4152,7 @@ def test_list_projects_response_serialization(self): list_projects_response_model_json2 = list_projects_response_model.to_dict() assert list_projects_response_model_json2 == list_projects_response_model_json -class TestNotice(): +class TestModel_Notice(): """ Test Class for Notice """ @@ -4091,7 +4165,7 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} notice_model_json['notice_id'] = 'testString' - notice_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + notice_model_json['created'] = "2019-01-01T12:00:00Z" notice_model_json['document_id'] = 'testString' notice_model_json['collection_id'] = 'testString' notice_model_json['query_id'] = 'testString' @@ -4114,7 +4188,7 @@ def test_notice_serialization(self): notice_model_json2 = notice_model.to_dict() assert notice_model_json2 == notice_model_json -class TestProjectDetails(): +class TestModel_ProjectDetails(): """ Test Class for ProjectDetails """ @@ -4190,7 +4264,7 @@ def test_project_details_serialization(self): project_details_model_json2 = project_details_model.to_dict() assert project_details_model_json2 == project_details_model_json -class TestProjectListDetails(): +class TestModel_ProjectListDetails(): """ Test Class for ProjectListDetails """ @@ -4236,7 +4310,7 @@ def test_project_list_details_serialization(self): project_list_details_model_json2 = project_list_details_model.to_dict() assert project_list_details_model_json2 == project_list_details_model_json -class TestProjectListDetailsRelevancyTrainingStatus(): +class TestModel_ProjectListDetailsRelevancyTrainingStatus(): """ Test Class for ProjectListDetailsRelevancyTrainingStatus """ @@ -4273,7 +4347,7 @@ def test_project_list_details_relevancy_training_status_serialization(self): project_list_details_relevancy_training_status_model_json2 = project_list_details_relevancy_training_status_model.to_dict() assert project_list_details_relevancy_training_status_model_json2 == project_list_details_relevancy_training_status_model_json -class TestQueryAggregation(): +class TestModel_QueryAggregation(): """ Test Class for QueryAggregation """ @@ -4302,7 +4376,7 @@ def test_query_aggregation_serialization(self): query_aggregation_model_json2 = query_aggregation_model.to_dict() assert query_aggregation_model_json2 == query_aggregation_model_json -class TestQueryGroupByAggregationResult(): +class TestModel_QueryGroupByAggregationResult(): """ Test Class for QueryGroupByAggregationResult """ @@ -4343,7 +4417,7 @@ def test_query_group_by_aggregation_result_serialization(self): query_group_by_aggregation_result_model_json2 = query_group_by_aggregation_result_model.to_dict() assert query_group_by_aggregation_result_model_json2 == query_group_by_aggregation_result_model_json -class TestQueryHistogramAggregationResult(): +class TestModel_QueryHistogramAggregationResult(): """ Test Class for QueryHistogramAggregationResult """ @@ -4381,7 +4455,7 @@ def test_query_histogram_aggregation_result_serialization(self): query_histogram_aggregation_result_model_json2 = query_histogram_aggregation_result_model.to_dict() assert query_histogram_aggregation_result_model_json2 == query_histogram_aggregation_result_model_json -class TestQueryLargePassages(): +class TestModel_QueryLargePassages(): """ Test Class for QueryLargePassages """ @@ -4397,9 +4471,9 @@ def test_query_large_passages_serialization(self): query_large_passages_model_json['per_document'] = True query_large_passages_model_json['max_per_document'] = 38 query_large_passages_model_json['fields'] = ['testString'] - query_large_passages_model_json['count'] = 100 + query_large_passages_model_json['count'] = 400 query_large_passages_model_json['characters'] = 50 - query_large_passages_model_json['find_answers'] = True + query_large_passages_model_json['find_answers'] = False query_large_passages_model_json['max_answers_per_passage'] = 38 # Construct a model instance of QueryLargePassages by calling from_dict on the json representation @@ -4417,7 +4491,7 @@ def test_query_large_passages_serialization(self): query_large_passages_model_json2 = query_large_passages_model.to_dict() assert query_large_passages_model_json2 == query_large_passages_model_json -class TestQueryLargeSuggestedRefinements(): +class TestModel_QueryLargeSuggestedRefinements(): """ Test Class for QueryLargeSuggestedRefinements """ @@ -4447,7 +4521,7 @@ def test_query_large_suggested_refinements_serialization(self): query_large_suggested_refinements_model_json2 = query_large_suggested_refinements_model.to_dict() assert query_large_suggested_refinements_model_json2 == query_large_suggested_refinements_model_json -class TestQueryLargeTableResults(): +class TestModel_QueryLargeTableResults(): """ Test Class for QueryLargeTableResults """ @@ -4477,7 +4551,7 @@ def test_query_large_table_results_serialization(self): query_large_table_results_model_json2 = query_large_table_results_model.to_dict() assert query_large_table_results_model_json2 == query_large_table_results_model_json -class TestQueryNoticesResponse(): +class TestModel_QueryNoticesResponse(): """ Test Class for QueryNoticesResponse """ @@ -4491,7 +4565,7 @@ def test_query_notices_response_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + notice_model['created'] = "2019-01-01T12:00:00Z" notice_model['document_id'] = 'testString' notice_model['collection_id'] = 'testString' notice_model['query_id'] = 'testString' @@ -4519,7 +4593,7 @@ def test_query_notices_response_serialization(self): query_notices_response_model_json2 = query_notices_response_model.to_dict() assert query_notices_response_model_json2 == query_notices_response_model_json -class TestQueryResponse(): +class TestModel_QueryResponse(): """ Test Class for QueryResponse """ @@ -4555,7 +4629,7 @@ def test_query_response_serialization(self): query_result_model['metadata'] = {} query_result_model['result_metadata'] = query_result_metadata_model query_result_model['document_passages'] = [query_result_passage_model] - query_result_model['foo'] = { 'foo': 'bar' } + query_result_model['id'] = { 'foo': 'bar' } query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' @@ -4715,7 +4789,7 @@ def test_query_response_serialization(self): query_response_model_json2 = query_response_model.to_dict() assert query_response_model_json2 == query_response_model_json -class TestQueryResponsePassage(): +class TestModel_QueryResponsePassage(): """ Test Class for QueryResponsePassage """ @@ -4760,7 +4834,7 @@ def test_query_response_passage_serialization(self): query_response_passage_model_json2 = query_response_passage_model.to_dict() assert query_response_passage_model_json2 == query_response_passage_model_json -class TestQueryResult(): +class TestModel_QueryResult(): """ Test Class for QueryResult """ @@ -4814,7 +4888,17 @@ def test_query_result_serialization(self): query_result_model_json2 = query_result_model.to_dict() assert query_result_model_json2 == query_result_model_json -class TestQueryResultMetadata(): + # Test get_properties and set_properties methods. + query_result_model.set_properties({}) + actual_dict = query_result_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': { 'foo': 'bar' }} + query_result_model.set_properties(expected_dict) + actual_dict = query_result_model.get_properties() + assert actual_dict == expected_dict + +class TestModel_QueryResultMetadata(): """ Test Class for QueryResultMetadata """ @@ -4845,7 +4929,7 @@ def test_query_result_metadata_serialization(self): query_result_metadata_model_json2 = query_result_metadata_model.to_dict() assert query_result_metadata_model_json2 == query_result_metadata_model_json -class TestQueryResultPassage(): +class TestModel_QueryResultPassage(): """ Test Class for QueryResultPassage """ @@ -4887,7 +4971,7 @@ def test_query_result_passage_serialization(self): query_result_passage_model_json2 = query_result_passage_model.to_dict() assert query_result_passage_model_json2 == query_result_passage_model_json -class TestQuerySuggestedRefinement(): +class TestModel_QuerySuggestedRefinement(): """ Test Class for QuerySuggestedRefinement """ @@ -4916,7 +5000,7 @@ def test_query_suggested_refinement_serialization(self): query_suggested_refinement_model_json2 = query_suggested_refinement_model.to_dict() assert query_suggested_refinement_model_json2 == query_suggested_refinement_model_json -class TestQueryTableResult(): +class TestModel_QueryTableResult(): """ Test Class for QueryTableResult """ @@ -5054,7 +5138,7 @@ def test_query_table_result_serialization(self): query_table_result_model_json2 = query_table_result_model.to_dict() assert query_table_result_model_json2 == query_table_result_model_json -class TestQueryTermAggregationResult(): +class TestModel_QueryTermAggregationResult(): """ Test Class for QueryTermAggregationResult """ @@ -5095,7 +5179,7 @@ def test_query_term_aggregation_result_serialization(self): query_term_aggregation_result_model_json2 = query_term_aggregation_result_model.to_dict() assert query_term_aggregation_result_model_json2 == query_term_aggregation_result_model_json -class TestQueryTimesliceAggregationResult(): +class TestModel_QueryTimesliceAggregationResult(): """ Test Class for QueryTimesliceAggregationResult """ @@ -5134,7 +5218,7 @@ def test_query_timeslice_aggregation_result_serialization(self): query_timeslice_aggregation_result_model_json2 = query_timeslice_aggregation_result_model.to_dict() assert query_timeslice_aggregation_result_model_json2 == query_timeslice_aggregation_result_model_json -class TestQueryTopHitsAggregationResult(): +class TestModel_QueryTopHitsAggregationResult(): """ Test Class for QueryTopHitsAggregationResult """ @@ -5164,7 +5248,7 @@ def test_query_top_hits_aggregation_result_serialization(self): query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json -class TestResultPassageAnswer(): +class TestModel_ResultPassageAnswer(): """ Test Class for ResultPassageAnswer """ @@ -5196,7 +5280,7 @@ def test_result_passage_answer_serialization(self): result_passage_answer_model_json2 = result_passage_answer_model.to_dict() assert result_passage_answer_model_json2 == result_passage_answer_model_json -class TestRetrievalDetails(): +class TestModel_RetrievalDetails(): """ Test Class for RetrievalDetails """ @@ -5225,7 +5309,7 @@ def test_retrieval_details_serialization(self): retrieval_details_model_json2 = retrieval_details_model.to_dict() assert retrieval_details_model_json2 == retrieval_details_model_json -class TestTableBodyCells(): +class TestModel_TableBodyCells(): """ Test Class for TableBodyCells """ @@ -5296,7 +5380,7 @@ def test_table_body_cells_serialization(self): table_body_cells_model_json2 = table_body_cells_model.to_dict() assert table_body_cells_model_json2 == table_body_cells_model_json -class TestTableCellKey(): +class TestModel_TableCellKey(): """ Test Class for TableCellKey """ @@ -5333,7 +5417,7 @@ def test_table_cell_key_serialization(self): table_cell_key_model_json2 = table_cell_key_model.to_dict() assert table_cell_key_model_json2 == table_cell_key_model_json -class TestTableCellValues(): +class TestModel_TableCellValues(): """ Test Class for TableCellValues """ @@ -5370,7 +5454,7 @@ def test_table_cell_values_serialization(self): table_cell_values_model_json2 = table_cell_values_model.to_dict() assert table_cell_values_model_json2 == table_cell_values_model_json -class TestTableColumnHeaderIds(): +class TestModel_TableColumnHeaderIds(): """ Test Class for TableColumnHeaderIds """ @@ -5399,7 +5483,7 @@ def test_table_column_header_ids_serialization(self): table_column_header_ids_model_json2 = table_column_header_ids_model.to_dict() assert table_column_header_ids_model_json2 == table_column_header_ids_model_json -class TestTableColumnHeaderTexts(): +class TestModel_TableColumnHeaderTexts(): """ Test Class for TableColumnHeaderTexts """ @@ -5428,7 +5512,7 @@ def test_table_column_header_texts_serialization(self): table_column_header_texts_model_json2 = table_column_header_texts_model.to_dict() assert table_column_header_texts_model_json2 == table_column_header_texts_model_json -class TestTableColumnHeaderTextsNormalized(): +class TestModel_TableColumnHeaderTextsNormalized(): """ Test Class for TableColumnHeaderTextsNormalized """ @@ -5457,7 +5541,7 @@ def test_table_column_header_texts_normalized_serialization(self): table_column_header_texts_normalized_model_json2 = table_column_header_texts_normalized_model.to_dict() assert table_column_header_texts_normalized_model_json2 == table_column_header_texts_normalized_model_json -class TestTableColumnHeaders(): +class TestModel_TableColumnHeaders(): """ Test Class for TableColumnHeaders """ @@ -5493,7 +5577,7 @@ def test_table_column_headers_serialization(self): table_column_headers_model_json2 = table_column_headers_model.to_dict() assert table_column_headers_model_json2 == table_column_headers_model_json -class TestTableElementLocation(): +class TestModel_TableElementLocation(): """ Test Class for TableElementLocation """ @@ -5523,7 +5607,7 @@ def test_table_element_location_serialization(self): table_element_location_model_json2 = table_element_location_model.to_dict() assert table_element_location_model_json2 == table_element_location_model_json -class TestTableHeaders(): +class TestModel_TableHeaders(): """ Test Class for TableHeaders """ @@ -5558,7 +5642,7 @@ def test_table_headers_serialization(self): table_headers_model_json2 = table_headers_model.to_dict() assert table_headers_model_json2 == table_headers_model_json -class TestTableKeyValuePairs(): +class TestModel_TableKeyValuePairs(): """ Test Class for TableKeyValuePairs """ @@ -5604,7 +5688,7 @@ def test_table_key_value_pairs_serialization(self): table_key_value_pairs_model_json2 = table_key_value_pairs_model.to_dict() assert table_key_value_pairs_model_json2 == table_key_value_pairs_model_json -class TestTableResultTable(): +class TestModel_TableResultTable(): """ Test Class for TableResultTable """ @@ -5734,7 +5818,7 @@ def test_table_result_table_serialization(self): table_result_table_model_json2 = table_result_table_model.to_dict() assert table_result_table_model_json2 == table_result_table_model_json -class TestTableRowHeaderIds(): +class TestModel_TableRowHeaderIds(): """ Test Class for TableRowHeaderIds """ @@ -5763,7 +5847,7 @@ def test_table_row_header_ids_serialization(self): table_row_header_ids_model_json2 = table_row_header_ids_model.to_dict() assert table_row_header_ids_model_json2 == table_row_header_ids_model_json -class TestTableRowHeaderTexts(): +class TestModel_TableRowHeaderTexts(): """ Test Class for TableRowHeaderTexts """ @@ -5792,7 +5876,7 @@ def test_table_row_header_texts_serialization(self): table_row_header_texts_model_json2 = table_row_header_texts_model.to_dict() assert table_row_header_texts_model_json2 == table_row_header_texts_model_json -class TestTableRowHeaderTextsNormalized(): +class TestModel_TableRowHeaderTextsNormalized(): """ Test Class for TableRowHeaderTextsNormalized """ @@ -5821,7 +5905,7 @@ def test_table_row_header_texts_normalized_serialization(self): table_row_header_texts_normalized_model_json2 = table_row_header_texts_normalized_model.to_dict() assert table_row_header_texts_normalized_model_json2 == table_row_header_texts_normalized_model_json -class TestTableRowHeaders(): +class TestModel_TableRowHeaders(): """ Test Class for TableRowHeaders """ @@ -5863,7 +5947,7 @@ def test_table_row_headers_serialization(self): table_row_headers_model_json2 = table_row_headers_model.to_dict() assert table_row_headers_model_json2 == table_row_headers_model_json -class TestTableTextLocation(): +class TestModel_TableTextLocation(): """ Test Class for TableTextLocation """ @@ -5899,7 +5983,7 @@ def test_table_text_location_serialization(self): table_text_location_model_json2 = table_text_location_model.to_dict() assert table_text_location_model_json2 == table_text_location_model_json -class TestTrainingExample(): +class TestModel_TrainingExample(): """ Test Class for TrainingExample """ @@ -5914,8 +5998,8 @@ def test_training_example_serialization(self): training_example_model_json['document_id'] = 'testString' training_example_model_json['collection_id'] = 'testString' training_example_model_json['relevance'] = 38 - training_example_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - training_example_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_example_model_json['created'] = "2019-01-01T12:00:00Z" + training_example_model_json['updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of TrainingExample by calling from_dict on the json representation training_example_model = TrainingExample.from_dict(training_example_model_json) @@ -5932,7 +6016,7 @@ def test_training_example_serialization(self): training_example_model_json2 = training_example_model.to_dict() assert training_example_model_json2 == training_example_model_json -class TestTrainingQuery(): +class TestModel_TrainingQuery(): """ Test Class for TrainingQuery """ @@ -5948,16 +6032,16 @@ def test_training_query_serialization(self): training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - training_example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_example_model['created'] = "2019-01-01T12:00:00Z" + training_example_model['updated'] = "2019-01-01T12:00:00Z" # Construct a json representation of a TrainingQuery model training_query_model_json = {} training_query_model_json['query_id'] = 'testString' training_query_model_json['natural_language_query'] = 'testString' training_query_model_json['filter'] = 'testString' - training_query_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - training_query_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_query_model_json['created'] = "2019-01-01T12:00:00Z" + training_query_model_json['updated'] = "2019-01-01T12:00:00Z" training_query_model_json['examples'] = [training_example_model] # Construct a model instance of TrainingQuery by calling from_dict on the json representation @@ -5975,7 +6059,7 @@ def test_training_query_serialization(self): training_query_model_json2 = training_query_model.to_dict() assert training_query_model_json2 == training_query_model_json -class TestTrainingQuerySet(): +class TestModel_TrainingQuerySet(): """ Test Class for TrainingQuerySet """ @@ -5991,15 +6075,15 @@ def test_training_query_set_serialization(self): training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_example_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - training_example_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_example_model['created'] = "2019-01-01T12:00:00Z" + training_example_model['updated'] = "2019-01-01T12:00:00Z" training_query_model = {} # TrainingQuery training_query_model['query_id'] = 'testString' training_query_model['natural_language_query'] = 'testString' training_query_model['filter'] = 'testString' - training_query_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - training_query_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_query_model['created'] = "2019-01-01T12:00:00Z" + training_query_model['updated'] = "2019-01-01T12:00:00Z" training_query_model['examples'] = [training_example_model] # Construct a json representation of a TrainingQuerySet model @@ -6021,7 +6105,7 @@ def test_training_query_set_serialization(self): training_query_set_model_json2 = training_query_set_model.to_dict() assert training_query_set_model_json2 == training_query_set_model_json -class TestQueryCalculationAggregation(): +class TestModel_QueryCalculationAggregation(): """ Test Class for QueryCalculationAggregation """ @@ -6052,7 +6136,7 @@ def test_query_calculation_aggregation_serialization(self): query_calculation_aggregation_model_json2 = query_calculation_aggregation_model.to_dict() assert query_calculation_aggregation_model_json2 == query_calculation_aggregation_model_json -class TestQueryFilterAggregation(): +class TestModel_QueryFilterAggregation(): """ Test Class for QueryFilterAggregation """ @@ -6083,7 +6167,7 @@ def test_query_filter_aggregation_serialization(self): query_filter_aggregation_model_json2 = query_filter_aggregation_model.to_dict() assert query_filter_aggregation_model_json2 == query_filter_aggregation_model_json -class TestQueryGroupByAggregation(): +class TestModel_QueryGroupByAggregation(): """ Test Class for QueryGroupByAggregation """ @@ -6112,7 +6196,7 @@ def test_query_group_by_aggregation_serialization(self): query_group_by_aggregation_model_json2 = query_group_by_aggregation_model.to_dict() assert query_group_by_aggregation_model_json2 == query_group_by_aggregation_model_json -class TestQueryHistogramAggregation(): +class TestModel_QueryHistogramAggregation(): """ Test Class for QueryHistogramAggregation """ @@ -6144,7 +6228,7 @@ def test_query_histogram_aggregation_serialization(self): query_histogram_aggregation_model_json2 = query_histogram_aggregation_model.to_dict() assert query_histogram_aggregation_model_json2 == query_histogram_aggregation_model_json -class TestQueryNestedAggregation(): +class TestModel_QueryNestedAggregation(): """ Test Class for QueryNestedAggregation """ @@ -6175,7 +6259,7 @@ def test_query_nested_aggregation_serialization(self): query_nested_aggregation_model_json2 = query_nested_aggregation_model.to_dict() assert query_nested_aggregation_model_json2 == query_nested_aggregation_model_json -class TestQueryTermAggregation(): +class TestModel_QueryTermAggregation(): """ Test Class for QueryTermAggregation """ @@ -6207,7 +6291,7 @@ def test_query_term_aggregation_serialization(self): query_term_aggregation_model_json2 = query_term_aggregation_model.to_dict() assert query_term_aggregation_model_json2 == query_term_aggregation_model_json -class TestQueryTimesliceAggregation(): +class TestModel_QueryTimesliceAggregation(): """ Test Class for QueryTimesliceAggregation """ @@ -6239,7 +6323,7 @@ def test_query_timeslice_aggregation_serialization(self): query_timeslice_aggregation_model_json2 = query_timeslice_aggregation_model.to_dict() assert query_timeslice_aggregation_model_json2 == query_timeslice_aggregation_model_json -class TestQueryTopHitsAggregation(): +class TestModel_QueryTopHitsAggregation(): """ Test Class for QueryTopHitsAggregation """ diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 6b198cb12..2f39f5139 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -31,7 +31,7 @@ import urllib from ibm_watson.language_translator_v3 import * -version = 'testString' +version = '2018-05-01' _service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), @@ -55,6 +55,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -126,6 +128,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -221,6 +225,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -282,6 +288,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -364,6 +372,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -463,6 +473,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -576,6 +588,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -646,6 +660,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -726,6 +742,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -787,6 +805,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -900,6 +920,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -970,6 +992,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1034,6 +1058,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1135,7 +1161,7 @@ def test_get_translated_document_value_error(self): # Start of Model Tests ############################################################################## # region -class TestDeleteModelResult(): +class TestModel_DeleteModelResult(): """ Test Class for DeleteModelResult """ @@ -1164,7 +1190,7 @@ def test_delete_model_result_serialization(self): delete_model_result_model_json2 = delete_model_result_model.to_dict() assert delete_model_result_model_json2 == delete_model_result_model_json -class TestDocumentList(): +class TestModel_DocumentList(): """ Test Class for DocumentList """ @@ -1185,8 +1211,8 @@ def test_document_list_serialization(self): document_status_model['source'] = 'testString' document_status_model['detected_language_confidence'] = 0 document_status_model['target'] = 'testString' - document_status_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - document_status_model['completed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + document_status_model['created'] = "2019-01-01T12:00:00Z" + document_status_model['completed'] = "2019-01-01T12:00:00Z" document_status_model['word_count'] = 38 document_status_model['character_count'] = 38 @@ -1209,7 +1235,7 @@ def test_document_list_serialization(self): document_list_model_json2 = document_list_model.to_dict() assert document_list_model_json2 == document_list_model_json -class TestDocumentStatus(): +class TestModel_DocumentStatus(): """ Test Class for DocumentStatus """ @@ -1229,8 +1255,8 @@ def test_document_status_serialization(self): document_status_model_json['source'] = 'testString' document_status_model_json['detected_language_confidence'] = 0 document_status_model_json['target'] = 'testString' - document_status_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - document_status_model_json['completed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + document_status_model_json['created'] = "2019-01-01T12:00:00Z" + document_status_model_json['completed'] = "2019-01-01T12:00:00Z" document_status_model_json['word_count'] = 38 document_status_model_json['character_count'] = 38 @@ -1249,7 +1275,7 @@ def test_document_status_serialization(self): document_status_model_json2 = document_status_model.to_dict() assert document_status_model_json2 == document_status_model_json -class TestIdentifiableLanguage(): +class TestModel_IdentifiableLanguage(): """ Test Class for IdentifiableLanguage """ @@ -1279,7 +1305,7 @@ def test_identifiable_language_serialization(self): identifiable_language_model_json2 = identifiable_language_model.to_dict() assert identifiable_language_model_json2 == identifiable_language_model_json -class TestIdentifiableLanguages(): +class TestModel_IdentifiableLanguages(): """ Test Class for IdentifiableLanguages """ @@ -1314,7 +1340,7 @@ def test_identifiable_languages_serialization(self): identifiable_languages_model_json2 = identifiable_languages_model.to_dict() assert identifiable_languages_model_json2 == identifiable_languages_model_json -class TestIdentifiedLanguage(): +class TestModel_IdentifiedLanguage(): """ Test Class for IdentifiedLanguage """ @@ -1344,7 +1370,7 @@ def test_identified_language_serialization(self): identified_language_model_json2 = identified_language_model.to_dict() assert identified_language_model_json2 == identified_language_model_json -class TestIdentifiedLanguages(): +class TestModel_IdentifiedLanguages(): """ Test Class for IdentifiedLanguages """ @@ -1379,7 +1405,7 @@ def test_identified_languages_serialization(self): identified_languages_model_json2 = identified_languages_model.to_dict() assert identified_languages_model_json2 == identified_languages_model_json -class TestLanguage(): +class TestModel_Language(): """ Test Class for Language """ @@ -1416,7 +1442,7 @@ def test_language_serialization(self): language_model_json2 = language_model.to_dict() assert language_model_json2 == language_model_json -class TestLanguages(): +class TestModel_Languages(): """ Test Class for Languages """ @@ -1458,7 +1484,7 @@ def test_languages_serialization(self): languages_model_json2 = languages_model.to_dict() assert languages_model_json2 == languages_model_json -class TestTranslation(): +class TestModel_Translation(): """ Test Class for Translation """ @@ -1487,7 +1513,7 @@ def test_translation_serialization(self): translation_model_json2 = translation_model.to_dict() assert translation_model_json2 == translation_model_json -class TestTranslationModel(): +class TestModel_TranslationModel(): """ Test Class for TranslationModel """ @@ -1525,7 +1551,7 @@ def test_translation_model_serialization(self): translation_model_model_json2 = translation_model_model.to_dict() assert translation_model_model_json2 == translation_model_model_json -class TestTranslationModels(): +class TestModel_TranslationModels(): """ Test Class for TranslationModels """ @@ -1568,7 +1594,7 @@ def test_translation_models_serialization(self): translation_models_model_json2 = translation_models_model.to_dict() assert translation_models_model_json2 == translation_models_model_json -class TestTranslationResult(): +class TestModel_TranslationResult(): """ Test Class for TranslationResult """ diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py index eeaec42aa..37d61b978 100644 --- a/test/unit/test_natural_language_classifier_v1.py +++ b/test/unit/test_natural_language_classifier_v1.py @@ -52,6 +52,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -129,6 +131,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -224,6 +228,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -298,6 +304,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -335,6 +343,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -405,6 +415,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -470,7 +482,7 @@ def test_delete_classifier_value_error(self): # Start of Model Tests ############################################################################## # region -class TestClassification(): +class TestModel_Classification(): """ Test Class for Classification """ @@ -509,7 +521,7 @@ def test_classification_serialization(self): classification_model_json2 = classification_model.to_dict() assert classification_model_json2 == classification_model_json -class TestClassificationCollection(): +class TestModel_ClassificationCollection(): """ Test Class for ClassificationCollection """ @@ -551,7 +563,7 @@ def test_classification_collection_serialization(self): classification_collection_model_json2 = classification_collection_model.to_dict() assert classification_collection_model_json2 == classification_collection_model_json -class TestClassifiedClass(): +class TestModel_ClassifiedClass(): """ Test Class for ClassifiedClass """ @@ -581,7 +593,7 @@ def test_classified_class_serialization(self): classified_class_model_json2 = classified_class_model.to_dict() assert classified_class_model_json2 == classified_class_model_json -class TestClassifier(): +class TestModel_Classifier(): """ Test Class for Classifier """ @@ -597,7 +609,7 @@ def test_classifier_serialization(self): classifier_model_json['url'] = 'testString' classifier_model_json['status'] = 'Non Existent' classifier_model_json['classifier_id'] = 'testString' - classifier_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifier_model_json['created'] = "2019-01-01T12:00:00Z" classifier_model_json['status_description'] = 'testString' classifier_model_json['language'] = 'testString' @@ -616,7 +628,7 @@ def test_classifier_serialization(self): classifier_model_json2 = classifier_model.to_dict() assert classifier_model_json2 == classifier_model_json -class TestClassifierList(): +class TestModel_ClassifierList(): """ Test Class for ClassifierList """ @@ -633,7 +645,7 @@ def test_classifier_list_serialization(self): classifier_model['url'] = 'testString' classifier_model['status'] = 'Non Existent' classifier_model['classifier_id'] = 'testString' - classifier_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifier_model['created'] = "2019-01-01T12:00:00Z" classifier_model['status_description'] = 'testString' classifier_model['language'] = 'testString' @@ -656,7 +668,7 @@ def test_classifier_list_serialization(self): classifier_list_model_json2 = classifier_list_model.to_dict() assert classifier_list_model_json2 == classifier_list_model_json -class TestClassifyInput(): +class TestModel_ClassifyInput(): """ Test Class for ClassifyInput """ @@ -685,7 +697,7 @@ def test_classify_input_serialization(self): classify_input_model_json2 = classify_input_model.to_dict() assert classify_input_model_json2 == classify_input_model_json -class TestCollectionItem(): +class TestModel_CollectionItem(): """ Test Class for CollectionItem """ diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index cfc055173..d5bb4e7dc 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -55,6 +55,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -90,16 +92,16 @@ def test_analyze_all_params(self): # Construct a dict representation of a EntitiesOptions model entities_options_model = {} entities_options_model['limit'] = 250 - entities_options_model['mentions'] = True + entities_options_model['mentions'] = False entities_options_model['model'] = 'testString' - entities_options_model['sentiment'] = True - entities_options_model['emotion'] = True + entities_options_model['sentiment'] = False + entities_options_model['emotion'] = False # Construct a dict representation of a KeywordsOptions model keywords_options_model = {} keywords_options_model['limit'] = 250 - keywords_options_model['sentiment'] = True - keywords_options_model['emotion'] = True + keywords_options_model['sentiment'] = False + keywords_options_model['emotion'] = False # Construct a dict representation of a MetadataOptions model metadata_options_model = {} @@ -111,8 +113,8 @@ def test_analyze_all_params(self): # Construct a dict representation of a SemanticRolesOptions model semantic_roles_options_model = {} semantic_roles_options_model['limit'] = 38 - semantic_roles_options_model['keywords'] = True - semantic_roles_options_model['entities'] = True + semantic_roles_options_model['keywords'] = False + semantic_roles_options_model['entities'] = False # Construct a dict representation of a SentimentOptions model sentiment_options_model = {} @@ -126,7 +128,7 @@ def test_analyze_all_params(self): # Construct a dict representation of a CategoriesOptions model categories_options_model = {} - categories_options_model['explanation'] = True + categories_options_model['explanation'] = False categories_options_model['limit'] = 10 categories_options_model['model'] = 'testString' @@ -163,7 +165,7 @@ def test_analyze_all_params(self): clean = True xpath = 'testString' fallback_to_raw = True - return_analyzed_text = True + return_analyzed_text = False language = 'testString' limit_text_characters = 38 @@ -194,7 +196,7 @@ def test_analyze_all_params(self): assert req_body['clean'] == True assert req_body['xpath'] == 'testString' assert req_body['fallback_to_raw'] == True - assert req_body['return_analyzed_text'] == True + assert req_body['return_analyzed_text'] == False assert req_body['language'] == 'testString' assert req_body['limit_text_characters'] == 38 @@ -229,16 +231,16 @@ def test_analyze_value_error(self): # Construct a dict representation of a EntitiesOptions model entities_options_model = {} entities_options_model['limit'] = 250 - entities_options_model['mentions'] = True + entities_options_model['mentions'] = False entities_options_model['model'] = 'testString' - entities_options_model['sentiment'] = True - entities_options_model['emotion'] = True + entities_options_model['sentiment'] = False + entities_options_model['emotion'] = False # Construct a dict representation of a KeywordsOptions model keywords_options_model = {} keywords_options_model['limit'] = 250 - keywords_options_model['sentiment'] = True - keywords_options_model['emotion'] = True + keywords_options_model['sentiment'] = False + keywords_options_model['emotion'] = False # Construct a dict representation of a MetadataOptions model metadata_options_model = {} @@ -250,8 +252,8 @@ def test_analyze_value_error(self): # Construct a dict representation of a SemanticRolesOptions model semantic_roles_options_model = {} semantic_roles_options_model['limit'] = 38 - semantic_roles_options_model['keywords'] = True - semantic_roles_options_model['entities'] = True + semantic_roles_options_model['keywords'] = False + semantic_roles_options_model['entities'] = False # Construct a dict representation of a SentimentOptions model sentiment_options_model = {} @@ -265,7 +267,7 @@ def test_analyze_value_error(self): # Construct a dict representation of a CategoriesOptions model categories_options_model = {} - categories_options_model['explanation'] = True + categories_options_model['explanation'] = False categories_options_model['limit'] = 10 categories_options_model['model'] = 'testString' @@ -302,7 +304,7 @@ def test_analyze_value_error(self): clean = True xpath = 'testString' fallback_to_raw = True - return_analyzed_text = True + return_analyzed_text = False language = 'testString' limit_text_characters = 38 @@ -336,6 +338,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -397,6 +401,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -477,6 +483,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -591,6 +599,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -652,6 +662,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -722,6 +734,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -842,6 +856,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -922,6 +938,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1038,6 +1056,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1099,6 +1119,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1169,6 +1191,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1291,6 +1315,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1371,6 +1397,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1487,6 +1515,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1499,7 +1529,7 @@ def test_list_classifications_models_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/models/classifications') - mock_response = '{"models": [{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1522,7 +1552,7 @@ def test_list_classifications_models_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/models/classifications') - mock_response = '{"models": [{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1548,6 +1578,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1618,6 +1650,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1740,6 +1774,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1811,7 +1847,7 @@ def test_delete_classifications_model_value_error(self): # Start of Model Tests ############################################################################## # region -class TestAnalysisResults(): +class TestModel_AnalysisResults(): """ Test Class for AnalysisResults """ @@ -1878,7 +1914,7 @@ def test_analysis_results_serialization(self): categories_result_explanation_model['relevant_text'] = [categories_relevant_text_model] categories_result_model = {} # CategoriesResult - categories_result_model['label'] = '/technology and computing/software' + categories_result_model['label'] = '/technology and computing/computing/computer software and applications' categories_result_model['score'] = 0.594296 categories_result_model['explanation'] = categories_result_explanation_model @@ -2015,7 +2051,7 @@ def test_analysis_results_serialization(self): analysis_results_model_json2 = analysis_results_model.to_dict() assert analysis_results_model_json2 == analysis_results_model_json -class TestAnalysisResultsUsage(): +class TestModel_AnalysisResultsUsage(): """ Test Class for AnalysisResultsUsage """ @@ -2046,7 +2082,7 @@ def test_analysis_results_usage_serialization(self): analysis_results_usage_model_json2 = analysis_results_usage_model.to_dict() assert analysis_results_usage_model_json2 == analysis_results_usage_model_json -class TestAuthor(): +class TestModel_Author(): """ Test Class for Author """ @@ -2075,7 +2111,7 @@ def test_author_serialization(self): author_model_json2 = author_model.to_dict() assert author_model_json2 == author_model_json -class TestCategoriesModel(): +class TestModel_CategoriesModel(): """ Test Class for CategoriesModel """ @@ -2088,7 +2124,7 @@ def test_categories_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' # Construct a json representation of a CategoriesModel model categories_model_model_json = {} @@ -2102,10 +2138,10 @@ def test_categories_model_serialization(self): categories_model_model_json['features'] = ['testString'] categories_model_model_json['status'] = 'starting' categories_model_model_json['model_id'] = 'testString' - categories_model_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + categories_model_model_json['created'] = "2019-01-01T12:00:00Z" categories_model_model_json['notices'] = [notice_model] - categories_model_model_json['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - categories_model_model_json['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + categories_model_model_json['last_trained'] = "2019-01-01T12:00:00Z" + categories_model_model_json['last_deployed'] = "2019-01-01T12:00:00Z" # Construct a model instance of CategoriesModel by calling from_dict on the json representation categories_model_model = CategoriesModel.from_dict(categories_model_model_json) @@ -2122,7 +2158,7 @@ def test_categories_model_serialization(self): categories_model_model_json2 = categories_model_model.to_dict() assert categories_model_model_json2 == categories_model_model_json -class TestCategoriesModelList(): +class TestModel_CategoriesModelList(): """ Test Class for CategoriesModelList """ @@ -2135,7 +2171,7 @@ def test_categories_model_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' categories_model_model = {} # CategoriesModel categories_model_model['name'] = 'testString' @@ -2148,10 +2184,10 @@ def test_categories_model_list_serialization(self): categories_model_model['features'] = ['testString'] categories_model_model['status'] = 'starting' categories_model_model['model_id'] = 'testString' - categories_model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + categories_model_model['created'] = "2019-01-01T12:00:00Z" categories_model_model['notices'] = [notice_model] - categories_model_model['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - categories_model_model['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + categories_model_model['last_trained'] = "2019-01-01T12:00:00Z" + categories_model_model['last_deployed'] = "2019-01-01T12:00:00Z" # Construct a json representation of a CategoriesModelList model categories_model_list_model_json = {} @@ -2172,7 +2208,7 @@ def test_categories_model_list_serialization(self): categories_model_list_model_json2 = categories_model_list_model.to_dict() assert categories_model_list_model_json2 == categories_model_list_model_json -class TestCategoriesOptions(): +class TestModel_CategoriesOptions(): """ Test Class for CategoriesOptions """ @@ -2184,7 +2220,7 @@ def test_categories_options_serialization(self): # Construct a json representation of a CategoriesOptions model categories_options_model_json = {} - categories_options_model_json['explanation'] = True + categories_options_model_json['explanation'] = False categories_options_model_json['limit'] = 10 categories_options_model_json['model'] = 'testString' @@ -2203,7 +2239,7 @@ def test_categories_options_serialization(self): categories_options_model_json2 = categories_options_model.to_dict() assert categories_options_model_json2 == categories_options_model_json -class TestCategoriesRelevantText(): +class TestModel_CategoriesRelevantText(): """ Test Class for CategoriesRelevantText """ @@ -2232,7 +2268,7 @@ def test_categories_relevant_text_serialization(self): categories_relevant_text_model_json2 = categories_relevant_text_model.to_dict() assert categories_relevant_text_model_json2 == categories_relevant_text_model_json -class TestCategoriesResult(): +class TestModel_CategoriesResult(): """ Test Class for CategoriesResult """ @@ -2271,7 +2307,7 @@ def test_categories_result_serialization(self): categories_result_model_json2 = categories_result_model.to_dict() assert categories_result_model_json2 == categories_result_model_json -class TestCategoriesResultExplanation(): +class TestModel_CategoriesResultExplanation(): """ Test Class for CategoriesResultExplanation """ @@ -2305,7 +2341,7 @@ def test_categories_result_explanation_serialization(self): categories_result_explanation_model_json2 = categories_result_explanation_model.to_dict() assert categories_result_explanation_model_json2 == categories_result_explanation_model_json -class TestClassificationsModel(): +class TestModel_ClassificationsModel(): """ Test Class for ClassificationsModel """ @@ -2318,7 +2354,7 @@ def test_classifications_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' # Construct a json representation of a ClassificationsModel model classifications_model_model_json = {} @@ -2332,10 +2368,10 @@ def test_classifications_model_serialization(self): classifications_model_model_json['features'] = ['testString'] classifications_model_model_json['status'] = 'starting' classifications_model_model_json['model_id'] = 'testString' - classifications_model_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifications_model_model_json['created'] = "2019-01-01T12:00:00Z" classifications_model_model_json['notices'] = [notice_model] - classifications_model_model_json['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - classifications_model_model_json['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifications_model_model_json['last_trained'] = "2019-01-01T12:00:00Z" + classifications_model_model_json['last_deployed'] = "2019-01-01T12:00:00Z" # Construct a model instance of ClassificationsModel by calling from_dict on the json representation classifications_model_model = ClassificationsModel.from_dict(classifications_model_model_json) @@ -2352,7 +2388,7 @@ def test_classifications_model_serialization(self): classifications_model_model_json2 = classifications_model_model.to_dict() assert classifications_model_model_json2 == classifications_model_model_json -class TestClassificationsModelList(): +class TestModel_ClassificationsModelList(): """ Test Class for ClassificationsModelList """ @@ -2365,7 +2401,7 @@ def test_classifications_model_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' classifications_model_model = {} # ClassificationsModel classifications_model_model['name'] = 'testString' @@ -2378,10 +2414,10 @@ def test_classifications_model_list_serialization(self): classifications_model_model['features'] = ['testString'] classifications_model_model['status'] = 'starting' classifications_model_model['model_id'] = 'testString' - classifications_model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifications_model_model['created'] = "2019-01-01T12:00:00Z" classifications_model_model['notices'] = [notice_model] - classifications_model_model['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - classifications_model_model['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifications_model_model['last_trained'] = "2019-01-01T12:00:00Z" + classifications_model_model['last_deployed'] = "2019-01-01T12:00:00Z" # Construct a json representation of a ClassificationsModelList model classifications_model_list_model_json = {} @@ -2402,7 +2438,7 @@ def test_classifications_model_list_serialization(self): classifications_model_list_model_json2 = classifications_model_list_model.to_dict() assert classifications_model_list_model_json2 == classifications_model_list_model_json -class TestClassificationsOptions(): +class TestModel_ClassificationsOptions(): """ Test Class for ClassificationsOptions """ @@ -2431,7 +2467,7 @@ def test_classifications_options_serialization(self): classifications_options_model_json2 = classifications_options_model.to_dict() assert classifications_options_model_json2 == classifications_options_model_json -class TestClassificationsResult(): +class TestModel_ClassificationsResult(): """ Test Class for ClassificationsResult """ @@ -2461,7 +2497,7 @@ def test_classifications_result_serialization(self): classifications_result_model_json2 = classifications_result_model.to_dict() assert classifications_result_model_json2 == classifications_result_model_json -class TestConceptsOptions(): +class TestModel_ConceptsOptions(): """ Test Class for ConceptsOptions """ @@ -2490,7 +2526,7 @@ def test_concepts_options_serialization(self): concepts_options_model_json2 = concepts_options_model.to_dict() assert concepts_options_model_json2 == concepts_options_model_json -class TestConceptsResult(): +class TestModel_ConceptsResult(): """ Test Class for ConceptsResult """ @@ -2521,7 +2557,7 @@ def test_concepts_result_serialization(self): concepts_result_model_json2 = concepts_result_model.to_dict() assert concepts_result_model_json2 == concepts_result_model_json -class TestDeleteModelResults(): +class TestModel_DeleteModelResults(): """ Test Class for DeleteModelResults """ @@ -2550,7 +2586,7 @@ def test_delete_model_results_serialization(self): delete_model_results_model_json2 = delete_model_results_model.to_dict() assert delete_model_results_model_json2 == delete_model_results_model_json -class TestDisambiguationResult(): +class TestModel_DisambiguationResult(): """ Test Class for DisambiguationResult """ @@ -2581,7 +2617,7 @@ def test_disambiguation_result_serialization(self): disambiguation_result_model_json2 = disambiguation_result_model.to_dict() assert disambiguation_result_model_json2 == disambiguation_result_model_json -class TestDocumentEmotionResults(): +class TestModel_DocumentEmotionResults(): """ Test Class for DocumentEmotionResults """ @@ -2619,7 +2655,7 @@ def test_document_emotion_results_serialization(self): document_emotion_results_model_json2 = document_emotion_results_model.to_dict() assert document_emotion_results_model_json2 == document_emotion_results_model_json -class TestDocumentSentimentResults(): +class TestModel_DocumentSentimentResults(): """ Test Class for DocumentSentimentResults """ @@ -2649,7 +2685,7 @@ def test_document_sentiment_results_serialization(self): document_sentiment_results_model_json2 = document_sentiment_results_model.to_dict() assert document_sentiment_results_model_json2 == document_sentiment_results_model_json -class TestEmotionOptions(): +class TestModel_EmotionOptions(): """ Test Class for EmotionOptions """ @@ -2679,7 +2715,7 @@ def test_emotion_options_serialization(self): emotion_options_model_json2 = emotion_options_model.to_dict() assert emotion_options_model_json2 == emotion_options_model_json -class TestEmotionResult(): +class TestModel_EmotionResult(): """ Test Class for EmotionResult """ @@ -2725,7 +2761,7 @@ def test_emotion_result_serialization(self): emotion_result_model_json2 = emotion_result_model.to_dict() assert emotion_result_model_json2 == emotion_result_model_json -class TestEmotionScores(): +class TestModel_EmotionScores(): """ Test Class for EmotionScores """ @@ -2758,7 +2794,7 @@ def test_emotion_scores_serialization(self): emotion_scores_model_json2 = emotion_scores_model.to_dict() assert emotion_scores_model_json2 == emotion_scores_model_json -class TestEntitiesOptions(): +class TestModel_EntitiesOptions(): """ Test Class for EntitiesOptions """ @@ -2771,10 +2807,10 @@ def test_entities_options_serialization(self): # Construct a json representation of a EntitiesOptions model entities_options_model_json = {} entities_options_model_json['limit'] = 250 - entities_options_model_json['mentions'] = True + entities_options_model_json['mentions'] = False entities_options_model_json['model'] = 'testString' - entities_options_model_json['sentiment'] = True - entities_options_model_json['emotion'] = True + entities_options_model_json['sentiment'] = False + entities_options_model_json['emotion'] = False # Construct a model instance of EntitiesOptions by calling from_dict on the json representation entities_options_model = EntitiesOptions.from_dict(entities_options_model_json) @@ -2791,7 +2827,7 @@ def test_entities_options_serialization(self): entities_options_model_json2 = entities_options_model.to_dict() assert entities_options_model_json2 == entities_options_model_json -class TestEntitiesResult(): +class TestModel_EntitiesResult(): """ Test Class for EntitiesResult """ @@ -2850,7 +2886,7 @@ def test_entities_result_serialization(self): entities_result_model_json2 = entities_result_model.to_dict() assert entities_result_model_json2 == entities_result_model_json -class TestEntityMention(): +class TestModel_EntityMention(): """ Test Class for EntityMention """ @@ -2881,7 +2917,7 @@ def test_entity_mention_serialization(self): entity_mention_model_json2 = entity_mention_model.to_dict() assert entity_mention_model_json2 == entity_mention_model_json -class TestFeatureSentimentResults(): +class TestModel_FeatureSentimentResults(): """ Test Class for FeatureSentimentResults """ @@ -2910,7 +2946,7 @@ def test_feature_sentiment_results_serialization(self): feature_sentiment_results_model_json2 = feature_sentiment_results_model.to_dict() assert feature_sentiment_results_model_json2 == feature_sentiment_results_model_json -class TestFeatures(): +class TestModel_Features(): """ Test Class for Features """ @@ -2934,15 +2970,15 @@ def test_features_serialization(self): entities_options_model = {} # EntitiesOptions entities_options_model['limit'] = 250 - entities_options_model['mentions'] = True + entities_options_model['mentions'] = False entities_options_model['model'] = 'testString' - entities_options_model['sentiment'] = True - entities_options_model['emotion'] = True + entities_options_model['sentiment'] = False + entities_options_model['emotion'] = False keywords_options_model = {} # KeywordsOptions keywords_options_model['limit'] = 250 - keywords_options_model['sentiment'] = True - keywords_options_model['emotion'] = True + keywords_options_model['sentiment'] = False + keywords_options_model['emotion'] = False metadata_options_model = {} # MetadataOptions @@ -2951,8 +2987,8 @@ def test_features_serialization(self): semantic_roles_options_model = {} # SemanticRolesOptions semantic_roles_options_model['limit'] = 38 - semantic_roles_options_model['keywords'] = True - semantic_roles_options_model['entities'] = True + semantic_roles_options_model['keywords'] = False + semantic_roles_options_model['entities'] = False sentiment_options_model = {} # SentimentOptions sentiment_options_model['document'] = True @@ -2963,7 +2999,7 @@ def test_features_serialization(self): summarization_options_model['limit'] = 10 categories_options_model = {} # CategoriesOptions - categories_options_model['explanation'] = True + categories_options_model['explanation'] = False categories_options_model['limit'] = 10 categories_options_model['model'] = 'testString' @@ -3005,7 +3041,7 @@ def test_features_serialization(self): features_model_json2 = features_model.to_dict() assert features_model_json2 == features_model_json -class TestFeaturesResultsMetadata(): +class TestModel_FeaturesResultsMetadata(): """ Test Class for FeaturesResultsMetadata """ @@ -3046,7 +3082,7 @@ def test_features_results_metadata_serialization(self): features_results_metadata_model_json2 = features_results_metadata_model.to_dict() assert features_results_metadata_model_json2 == features_results_metadata_model_json -class TestFeed(): +class TestModel_Feed(): """ Test Class for Feed """ @@ -3075,7 +3111,7 @@ def test_feed_serialization(self): feed_model_json2 = feed_model.to_dict() assert feed_model_json2 == feed_model_json -class TestKeywordsOptions(): +class TestModel_KeywordsOptions(): """ Test Class for KeywordsOptions """ @@ -3088,8 +3124,8 @@ def test_keywords_options_serialization(self): # Construct a json representation of a KeywordsOptions model keywords_options_model_json = {} keywords_options_model_json['limit'] = 250 - keywords_options_model_json['sentiment'] = True - keywords_options_model_json['emotion'] = True + keywords_options_model_json['sentiment'] = False + keywords_options_model_json['emotion'] = False # Construct a model instance of KeywordsOptions by calling from_dict on the json representation keywords_options_model = KeywordsOptions.from_dict(keywords_options_model_json) @@ -3106,7 +3142,7 @@ def test_keywords_options_serialization(self): keywords_options_model_json2 = keywords_options_model.to_dict() assert keywords_options_model_json2 == keywords_options_model_json -class TestKeywordsResult(): +class TestModel_KeywordsResult(): """ Test Class for KeywordsResult """ @@ -3151,60 +3187,7 @@ def test_keywords_result_serialization(self): keywords_result_model_json2 = keywords_result_model.to_dict() assert keywords_result_model_json2 == keywords_result_model_json -class TestListClassificationsModelsResponse(): - """ - Test Class for ListClassificationsModelsResponse - """ - - def test_list_classifications_models_response_serialization(self): - """ - Test serialization/deserialization for ListClassificationsModelsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' - - classifications_model_model = {} # ClassificationsModel - classifications_model_model['name'] = 'testString' - classifications_model_model['user_metadata'] = {} - classifications_model_model['language'] = 'testString' - classifications_model_model['description'] = 'testString' - classifications_model_model['model_version'] = 'testString' - classifications_model_model['workspace_id'] = 'testString' - classifications_model_model['version_description'] = 'testString' - classifications_model_model['features'] = ['testString'] - classifications_model_model['status'] = 'starting' - classifications_model_model['model_id'] = 'testString' - classifications_model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - classifications_model_model['notices'] = [notice_model] - classifications_model_model['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - classifications_model_model['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - - classifications_model_list_model = {} # ClassificationsModelList - classifications_model_list_model['models'] = [classifications_model_model] - - # Construct a json representation of a ListClassificationsModelsResponse model - list_classifications_models_response_model_json = {} - list_classifications_models_response_model_json['models'] = [classifications_model_list_model] - - # Construct a model instance of ListClassificationsModelsResponse by calling from_dict on the json representation - list_classifications_models_response_model = ListClassificationsModelsResponse.from_dict(list_classifications_models_response_model_json) - assert list_classifications_models_response_model != False - - # Construct a model instance of ListClassificationsModelsResponse by calling from_dict on the json representation - list_classifications_models_response_model_dict = ListClassificationsModelsResponse.from_dict(list_classifications_models_response_model_json).__dict__ - list_classifications_models_response_model2 = ListClassificationsModelsResponse(**list_classifications_models_response_model_dict) - - # Verify the model instances are equivalent - assert list_classifications_models_response_model == list_classifications_models_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_classifications_models_response_model_json2 = list_classifications_models_response_model.to_dict() - assert list_classifications_models_response_model_json2 == list_classifications_models_response_model_json - -class TestListModelsResults(): +class TestModel_ListModelsResults(): """ Test Class for ListModelsResults """ @@ -3225,7 +3208,7 @@ def test_list_models_results_serialization(self): model_model['model_version'] = 'testString' model_model['version'] = 'testString' model_model['version_description'] = 'testString' - model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + model_model['created'] = "2019-01-01T12:00:00Z" # Construct a json representation of a ListModelsResults model list_models_results_model_json = {} @@ -3246,7 +3229,7 @@ def test_list_models_results_serialization(self): list_models_results_model_json2 = list_models_results_model.to_dict() assert list_models_results_model_json2 == list_models_results_model_json -class TestListSentimentModelsResponse(): +class TestModel_ListSentimentModelsResponse(): """ Test Class for ListSentimentModelsResponse """ @@ -3259,15 +3242,15 @@ def test_list_sentiment_models_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' sentiment_model_model = {} # SentimentModel sentiment_model_model['features'] = ['testString'] sentiment_model_model['status'] = 'starting' sentiment_model_model['model_id'] = 'testString' - sentiment_model_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - sentiment_model_model['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - sentiment_model_model['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + sentiment_model_model['created'] = "2019-01-01T12:00:00Z" + sentiment_model_model['last_trained'] = "2019-01-01T12:00:00Z" + sentiment_model_model['last_deployed'] = "2019-01-01T12:00:00Z" sentiment_model_model['name'] = 'testString' sentiment_model_model['user_metadata'] = {} sentiment_model_model['language'] = 'testString' @@ -3296,7 +3279,7 @@ def test_list_sentiment_models_response_serialization(self): list_sentiment_models_response_model_json2 = list_sentiment_models_response_model.to_dict() assert list_sentiment_models_response_model_json2 == list_sentiment_models_response_model_json -class TestMetadataOptions(): +class TestModel_MetadataOptions(): """ Test Class for MetadataOptions """ @@ -3324,7 +3307,7 @@ def test_metadata_options_serialization(self): metadata_options_model_json2 = metadata_options_model.to_dict() assert metadata_options_model_json2 == metadata_options_model_json -class TestModel(): +class TestModel_Model(): """ Test Class for Model """ @@ -3344,7 +3327,7 @@ def test_model_serialization(self): model_model_json['model_version'] = 'testString' model_model_json['version'] = 'testString' model_model_json['version_description'] = 'testString' - model_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + model_model_json['created'] = "2019-01-01T12:00:00Z" # Construct a model instance of Model by calling from_dict on the json representation model_model = Model.from_dict(model_model_json) @@ -3361,7 +3344,7 @@ def test_model_serialization(self): model_model_json2 = model_model.to_dict() assert model_model_json2 == model_model_json -class TestNotice(): +class TestModel_Notice(): """ Test Class for Notice """ @@ -3390,7 +3373,7 @@ def test_notice_serialization(self): notice_model_json2 = notice_model.to_dict() assert notice_model_json2 == notice_model_json -class TestRelationArgument(): +class TestModel_RelationArgument(): """ Test Class for RelationArgument """ @@ -3427,7 +3410,7 @@ def test_relation_argument_serialization(self): relation_argument_model_json2 = relation_argument_model.to_dict() assert relation_argument_model_json2 == relation_argument_model_json -class TestRelationEntity(): +class TestModel_RelationEntity(): """ Test Class for RelationEntity """ @@ -3457,7 +3440,7 @@ def test_relation_entity_serialization(self): relation_entity_model_json2 = relation_entity_model.to_dict() assert relation_entity_model_json2 == relation_entity_model_json -class TestRelationsOptions(): +class TestModel_RelationsOptions(): """ Test Class for RelationsOptions """ @@ -3486,7 +3469,7 @@ def test_relations_options_serialization(self): relations_options_model_json2 = relations_options_model.to_dict() assert relations_options_model_json2 == relations_options_model_json -class TestRelationsResult(): +class TestModel_RelationsResult(): """ Test Class for RelationsResult """ @@ -3529,7 +3512,7 @@ def test_relations_result_serialization(self): relations_result_model_json2 = relations_result_model.to_dict() assert relations_result_model_json2 == relations_result_model_json -class TestSemanticRolesEntity(): +class TestModel_SemanticRolesEntity(): """ Test Class for SemanticRolesEntity """ @@ -3559,7 +3542,7 @@ def test_semantic_roles_entity_serialization(self): semantic_roles_entity_model_json2 = semantic_roles_entity_model.to_dict() assert semantic_roles_entity_model_json2 == semantic_roles_entity_model_json -class TestSemanticRolesKeyword(): +class TestModel_SemanticRolesKeyword(): """ Test Class for SemanticRolesKeyword """ @@ -3588,7 +3571,7 @@ def test_semantic_roles_keyword_serialization(self): semantic_roles_keyword_model_json2 = semantic_roles_keyword_model.to_dict() assert semantic_roles_keyword_model_json2 == semantic_roles_keyword_model_json -class TestSemanticRolesOptions(): +class TestModel_SemanticRolesOptions(): """ Test Class for SemanticRolesOptions """ @@ -3601,8 +3584,8 @@ def test_semantic_roles_options_serialization(self): # Construct a json representation of a SemanticRolesOptions model semantic_roles_options_model_json = {} semantic_roles_options_model_json['limit'] = 38 - semantic_roles_options_model_json['keywords'] = True - semantic_roles_options_model_json['entities'] = True + semantic_roles_options_model_json['keywords'] = False + semantic_roles_options_model_json['entities'] = False # Construct a model instance of SemanticRolesOptions by calling from_dict on the json representation semantic_roles_options_model = SemanticRolesOptions.from_dict(semantic_roles_options_model_json) @@ -3619,7 +3602,7 @@ def test_semantic_roles_options_serialization(self): semantic_roles_options_model_json2 = semantic_roles_options_model.to_dict() assert semantic_roles_options_model_json2 == semantic_roles_options_model_json -class TestSemanticRolesResult(): +class TestModel_SemanticRolesResult(): """ Test Class for SemanticRolesResult """ @@ -3678,7 +3661,7 @@ def test_semantic_roles_result_serialization(self): semantic_roles_result_model_json2 = semantic_roles_result_model.to_dict() assert semantic_roles_result_model_json2 == semantic_roles_result_model_json -class TestSemanticRolesResultAction(): +class TestModel_SemanticRolesResultAction(): """ Test Class for SemanticRolesResultAction """ @@ -3715,7 +3698,7 @@ def test_semantic_roles_result_action_serialization(self): semantic_roles_result_action_model_json2 = semantic_roles_result_action_model.to_dict() assert semantic_roles_result_action_model_json2 == semantic_roles_result_action_model_json -class TestSemanticRolesResultObject(): +class TestModel_SemanticRolesResultObject(): """ Test Class for SemanticRolesResultObject """ @@ -3750,7 +3733,7 @@ def test_semantic_roles_result_object_serialization(self): semantic_roles_result_object_model_json2 = semantic_roles_result_object_model.to_dict() assert semantic_roles_result_object_model_json2 == semantic_roles_result_object_model_json -class TestSemanticRolesResultSubject(): +class TestModel_SemanticRolesResultSubject(): """ Test Class for SemanticRolesResultSubject """ @@ -3790,7 +3773,7 @@ def test_semantic_roles_result_subject_serialization(self): semantic_roles_result_subject_model_json2 = semantic_roles_result_subject_model.to_dict() assert semantic_roles_result_subject_model_json2 == semantic_roles_result_subject_model_json -class TestSemanticRolesVerb(): +class TestModel_SemanticRolesVerb(): """ Test Class for SemanticRolesVerb """ @@ -3820,7 +3803,7 @@ def test_semantic_roles_verb_serialization(self): semantic_roles_verb_model_json2 = semantic_roles_verb_model.to_dict() assert semantic_roles_verb_model_json2 == semantic_roles_verb_model_json -class TestSentenceResult(): +class TestModel_SentenceResult(): """ Test Class for SentenceResult """ @@ -3850,7 +3833,7 @@ def test_sentence_result_serialization(self): sentence_result_model_json2 = sentence_result_model.to_dict() assert sentence_result_model_json2 == sentence_result_model_json -class TestSentimentModel(): +class TestModel_SentimentModel(): """ Test Class for SentimentModel """ @@ -3863,16 +3846,16 @@ def test_sentiment_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Not enough examples for class \'foo\'. 4 were given but 5 are required.' + notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' # Construct a json representation of a SentimentModel model sentiment_model_model_json = {} sentiment_model_model_json['features'] = ['testString'] sentiment_model_model_json['status'] = 'starting' sentiment_model_model_json['model_id'] = 'testString' - sentiment_model_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - sentiment_model_model_json['last_trained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - sentiment_model_model_json['last_deployed'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + sentiment_model_model_json['created'] = "2019-01-01T12:00:00Z" + sentiment_model_model_json['last_trained'] = "2019-01-01T12:00:00Z" + sentiment_model_model_json['last_deployed'] = "2019-01-01T12:00:00Z" sentiment_model_model_json['name'] = 'testString' sentiment_model_model_json['user_metadata'] = {} sentiment_model_model_json['language'] = 'testString' @@ -3897,7 +3880,7 @@ def test_sentiment_model_serialization(self): sentiment_model_model_json2 = sentiment_model_model.to_dict() assert sentiment_model_model_json2 == sentiment_model_model_json -class TestSentimentOptions(): +class TestModel_SentimentOptions(): """ Test Class for SentimentOptions """ @@ -3928,7 +3911,7 @@ def test_sentiment_options_serialization(self): sentiment_options_model_json2 = sentiment_options_model.to_dict() assert sentiment_options_model_json2 == sentiment_options_model_json -class TestSentimentResult(): +class TestModel_SentimentResult(): """ Test Class for SentimentResult """ @@ -3968,7 +3951,7 @@ def test_sentiment_result_serialization(self): sentiment_result_model_json2 = sentiment_result_model.to_dict() assert sentiment_result_model_json2 == sentiment_result_model_json -class TestSummarizationOptions(): +class TestModel_SummarizationOptions(): """ Test Class for SummarizationOptions """ @@ -3997,7 +3980,7 @@ def test_summarization_options_serialization(self): summarization_options_model_json2 = summarization_options_model.to_dict() assert summarization_options_model_json2 == summarization_options_model_json -class TestSyntaxOptions(): +class TestModel_SyntaxOptions(): """ Test Class for SyntaxOptions """ @@ -4033,7 +4016,7 @@ def test_syntax_options_serialization(self): syntax_options_model_json2 = syntax_options_model.to_dict() assert syntax_options_model_json2 == syntax_options_model_json -class TestSyntaxOptionsTokens(): +class TestModel_SyntaxOptionsTokens(): """ Test Class for SyntaxOptionsTokens """ @@ -4063,7 +4046,7 @@ def test_syntax_options_tokens_serialization(self): syntax_options_tokens_model_json2 = syntax_options_tokens_model.to_dict() assert syntax_options_tokens_model_json2 == syntax_options_tokens_model_json -class TestSyntaxResult(): +class TestModel_SyntaxResult(): """ Test Class for SyntaxResult """ @@ -4105,7 +4088,7 @@ def test_syntax_result_serialization(self): syntax_result_model_json2 = syntax_result_model.to_dict() assert syntax_result_model_json2 == syntax_result_model_json -class TestTargetedEmotionResults(): +class TestModel_TargetedEmotionResults(): """ Test Class for TargetedEmotionResults """ @@ -4144,7 +4127,7 @@ def test_targeted_emotion_results_serialization(self): targeted_emotion_results_model_json2 = targeted_emotion_results_model.to_dict() assert targeted_emotion_results_model_json2 == targeted_emotion_results_model_json -class TestTargetedSentimentResults(): +class TestModel_TargetedSentimentResults(): """ Test Class for TargetedSentimentResults """ @@ -4174,7 +4157,7 @@ def test_targeted_sentiment_results_serialization(self): targeted_sentiment_results_model_json2 = targeted_sentiment_results_model.to_dict() assert targeted_sentiment_results_model_json2 == targeted_sentiment_results_model_json -class TestTokenResult(): +class TestModel_TokenResult(): """ Test Class for TokenResult """ diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py index d005d1fc3..787ea51e0 100755 --- a/test/unit/test_personality_insights_v3.py +++ b/test/unit/test_personality_insights_v3.py @@ -51,6 +51,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -77,10 +79,10 @@ def test_profile_all_params(self): content_item_model['created'] = 26 content_item_model['updated'] = 26 content_item_model['contenttype'] = 'text/plain' - content_item_model['language'] = 'ar' + content_item_model['language'] = 'en' content_item_model['parentid'] = 'testString' - content_item_model['reply'] = True - content_item_model['forward'] = True + content_item_model['reply'] = False + content_item_model['forward'] = False # Construct a dict representation of a Content model content_model = {} @@ -89,12 +91,12 @@ def test_profile_all_params(self): # Set up parameter values content = content_model accept = 'application/json' - content_type = 'application/json' - content_language = 'ar' - accept_language = 'ar' - raw_scores = True - csv_headers = True - consumption_preferences = True + content_type = 'text/plain' + content_language = 'en' + accept_language = 'en' + raw_scores = False + csv_headers = False + consumption_preferences = False # Invoke method response = _service.profile( @@ -142,10 +144,10 @@ def test_profile_required_params(self): content_item_model['created'] = 26 content_item_model['updated'] = 26 content_item_model['contenttype'] = 'text/plain' - content_item_model['language'] = 'ar' + content_item_model['language'] = 'en' content_item_model['parentid'] = 'testString' - content_item_model['reply'] = True - content_item_model['forward'] = True + content_item_model['reply'] = False + content_item_model['forward'] = False # Construct a dict representation of a Content model content_model = {} @@ -189,10 +191,10 @@ def test_profile_value_error(self): content_item_model['created'] = 26 content_item_model['updated'] = 26 content_item_model['contenttype'] = 'text/plain' - content_item_model['language'] = 'ar' + content_item_model['language'] = 'en' content_item_model['parentid'] = 'testString' - content_item_model['reply'] = True - content_item_model['forward'] = True + content_item_model['reply'] = False + content_item_model['forward'] = False # Construct a dict representation of a Content model content_model = {} @@ -224,7 +226,7 @@ def test_profile_value_error(self): # Start of Model Tests ############################################################################## # region -class TestBehavior(): +class TestModel_Behavior(): """ Test Class for Behavior """ @@ -256,7 +258,7 @@ def test_behavior_serialization(self): behavior_model_json2 = behavior_model.to_dict() assert behavior_model_json2 == behavior_model_json -class TestConsumptionPreferences(): +class TestModel_ConsumptionPreferences(): """ Test Class for ConsumptionPreferences """ @@ -287,7 +289,7 @@ def test_consumption_preferences_serialization(self): consumption_preferences_model_json2 = consumption_preferences_model.to_dict() assert consumption_preferences_model_json2 == consumption_preferences_model_json -class TestConsumptionPreferencesCategory(): +class TestModel_ConsumptionPreferencesCategory(): """ Test Class for ConsumptionPreferencesCategory """ @@ -325,7 +327,7 @@ def test_consumption_preferences_category_serialization(self): consumption_preferences_category_model_json2 = consumption_preferences_category_model.to_dict() assert consumption_preferences_category_model_json2 == consumption_preferences_category_model_json -class TestContent(): +class TestModel_Content(): """ Test Class for Content """ @@ -343,10 +345,10 @@ def test_content_serialization(self): content_item_model['created'] = 26 content_item_model['updated'] = 26 content_item_model['contenttype'] = 'text/plain' - content_item_model['language'] = 'ar' + content_item_model['language'] = 'en' content_item_model['parentid'] = 'testString' - content_item_model['reply'] = True - content_item_model['forward'] = True + content_item_model['reply'] = False + content_item_model['forward'] = False # Construct a json representation of a Content model content_model_json = {} @@ -367,7 +369,7 @@ def test_content_serialization(self): content_model_json2 = content_model.to_dict() assert content_model_json2 == content_model_json -class TestContentItem(): +class TestModel_ContentItem(): """ Test Class for ContentItem """ @@ -384,10 +386,10 @@ def test_content_item_serialization(self): content_item_model_json['created'] = 26 content_item_model_json['updated'] = 26 content_item_model_json['contenttype'] = 'text/plain' - content_item_model_json['language'] = 'ar' + content_item_model_json['language'] = 'en' content_item_model_json['parentid'] = 'testString' - content_item_model_json['reply'] = True - content_item_model_json['forward'] = True + content_item_model_json['reply'] = False + content_item_model_json['forward'] = False # Construct a model instance of ContentItem by calling from_dict on the json representation content_item_model = ContentItem.from_dict(content_item_model_json) @@ -404,7 +406,7 @@ def test_content_item_serialization(self): content_item_model_json2 = content_item_model.to_dict() assert content_item_model_json2 == content_item_model_json -class TestProfile(): +class TestModel_Profile(): """ Test Class for Profile """ @@ -471,7 +473,7 @@ def test_profile_serialization(self): profile_model_json2 = profile_model.to_dict() assert profile_model_json2 == profile_model_json -class TestTrait(): +class TestModel_Trait(): """ Test Class for Trait """ @@ -505,7 +507,7 @@ def test_trait_serialization(self): trait_model_json2 = trait_model.to_dict() assert trait_model_json2 == trait_model_json -class TestWarning(): +class TestModel_Warning(): """ Test Class for Warning """ diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 986c01e6b..18934165a 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -51,6 +51,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -88,6 +90,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -168,6 +172,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -190,7 +196,7 @@ def test_recognize_all_params(self): # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() content_type = 'application/octet-stream' - model = 'ar-AR_BroadbandModel' + model = 'en-US_BroadbandModel' language_customization_id = 'testString' acoustic_customization_id = 'testString' base_model_version = 'testString' @@ -200,20 +206,20 @@ def test_recognize_all_params(self): keywords_threshold = 72.5 max_alternatives = 38 word_alternatives_threshold = 72.5 - word_confidence = True - timestamps = True + word_confidence = False + timestamps = False profanity_filter = True - smart_formatting = True - speaker_labels = True + smart_formatting = False + speaker_labels = False customization_id = 'testString' grammar_name = 'testString' - redaction = True - audio_metrics = True + redaction = False + audio_metrics = False end_of_phrase_silence_time = 72.5 - split_transcript_at_phrase_end = True + split_transcript_at_phrase_end = False speech_detector_sensitivity = 72.5 background_audio_suppression = 72.5 - low_latency = True + low_latency = False # Invoke method response = _service.recognize( @@ -355,6 +361,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -464,6 +472,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -532,6 +542,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -554,7 +566,7 @@ def test_create_job_all_params(self): # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() content_type = 'application/octet-stream' - model = 'ar-AR_BroadbandModel' + model = 'en-US_BroadbandModel' callback_url = 'testString' events = 'recognitions.started' user_token = 'testString' @@ -568,22 +580,22 @@ def test_create_job_all_params(self): keywords_threshold = 72.5 max_alternatives = 38 word_alternatives_threshold = 72.5 - word_confidence = True - timestamps = True + word_confidence = False + timestamps = False profanity_filter = True - smart_formatting = True - speaker_labels = True + smart_formatting = False + speaker_labels = False customization_id = 'testString' grammar_name = 'testString' - redaction = True - processing_metrics = True + redaction = False + processing_metrics = False processing_metrics_interval = 72.5 - audio_metrics = True + audio_metrics = False end_of_phrase_silence_time = 72.5 - split_transcript_at_phrase_end = True + split_transcript_at_phrase_end = False speech_detector_sensitivity = 72.5 background_audio_suppression = 72.5 - low_latency = True + low_latency = False # Invoke method response = _service.create_job( @@ -727,6 +739,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -764,6 +778,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -834,6 +850,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -908,6 +926,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -929,7 +949,7 @@ def test_create_language_model_all_params(self): # Set up parameter values name = 'testString' - base_model_name = 'de-DE_BroadbandModel' + base_model_name = 'ar-MS_Telephony' dialect = 'testString' description = 'testString' @@ -948,7 +968,7 @@ def test_create_language_model_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' - assert req_body['base_model_name'] == 'de-DE_BroadbandModel' + assert req_body['base_model_name'] == 'ar-MS_Telephony' assert req_body['dialect'] == 'testString' assert req_body['description'] == 'testString' @@ -969,7 +989,7 @@ def test_create_language_model_value_error(self): # Set up parameter values name = 'testString' - base_model_name = 'de-DE_BroadbandModel' + base_model_name = 'ar-MS_Telephony' dialect = 'testString' description = 'testString' @@ -994,6 +1014,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1063,6 +1085,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1133,6 +1157,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1197,6 +1223,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1304,6 +1332,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1368,6 +1398,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1442,6 +1474,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1512,6 +1546,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1532,7 +1568,7 @@ def test_add_corpus_all_params(self): customization_id = 'testString' corpus_name = 'testString' corpus_file = io.BytesIO(b'This is a mock file.').getvalue() - allow_overwrite = True + allow_overwrite = False # Invoke method response = _service.add_corpus( @@ -1619,6 +1655,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1693,6 +1731,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1771,6 +1811,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1878,6 +1920,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1961,6 +2005,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2043,6 +2089,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2117,6 +2165,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2195,6 +2245,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2265,6 +2317,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2286,7 +2340,7 @@ def test_add_grammar_all_params(self): grammar_name = 'testString' grammar_file = 'testString' content_type = 'application/srgs' - allow_overwrite = True + allow_overwrite = False # Invoke method response = _service.add_grammar( @@ -2380,6 +2434,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2454,6 +2510,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2532,6 +2590,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2614,6 +2674,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2683,6 +2745,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2753,6 +2817,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2817,6 +2883,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2921,6 +2989,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -2985,6 +3055,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3004,7 +3076,7 @@ def test_upgrade_acoustic_model_all_params(self): # Set up parameter values customization_id = 'testString' custom_language_model_id = 'testString' - force = True + force = False # Invoke method response = _service.upgrade_acoustic_model( @@ -3093,6 +3165,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3163,6 +3237,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3185,7 +3261,7 @@ def test_add_audio_all_params(self): audio_resource = io.BytesIO(b'This is a mock file.').getvalue() content_type = 'application/zip' contained_content_type = 'audio/alaw' - allow_overwrite = True + allow_overwrite = False # Invoke method response = _service.add_audio( @@ -3276,6 +3352,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3350,6 +3428,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3428,6 +3508,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -3497,7 +3579,7 @@ def test_delete_user_data_value_error(self): # Start of Model Tests ############################################################################## # region -class TestAcousticModel(): +class TestModel_AcousticModel(): """ Test Class for AcousticModel """ @@ -3537,7 +3619,7 @@ def test_acoustic_model_serialization(self): acoustic_model_model_json2 = acoustic_model_model.to_dict() assert acoustic_model_model_json2 == acoustic_model_model_json -class TestAcousticModels(): +class TestModel_AcousticModels(): """ Test Class for AcousticModels """ @@ -3582,7 +3664,7 @@ def test_acoustic_models_serialization(self): acoustic_models_model_json2 = acoustic_models_model.to_dict() assert acoustic_models_model_json2 == acoustic_models_model_json -class TestAudioDetails(): +class TestModel_AudioDetails(): """ Test Class for AudioDetails """ @@ -3614,7 +3696,7 @@ def test_audio_details_serialization(self): audio_details_model_json2 = audio_details_model.to_dict() assert audio_details_model_json2 == audio_details_model_json -class TestAudioListing(): +class TestModel_AudioListing(): """ Test Class for AudioListing """ @@ -3662,7 +3744,7 @@ def test_audio_listing_serialization(self): audio_listing_model_json2 = audio_listing_model.to_dict() assert audio_listing_model_json2 == audio_listing_model_json -class TestAudioMetrics(): +class TestModel_AudioMetrics(): """ Test Class for AudioMetrics """ @@ -3710,7 +3792,7 @@ def test_audio_metrics_serialization(self): audio_metrics_model_json2 = audio_metrics_model.to_dict() assert audio_metrics_model_json2 == audio_metrics_model_json -class TestAudioMetricsDetails(): +class TestModel_AudioMetricsDetails(): """ Test Class for AudioMetricsDetails """ @@ -3754,7 +3836,7 @@ def test_audio_metrics_details_serialization(self): audio_metrics_details_model_json2 = audio_metrics_details_model.to_dict() assert audio_metrics_details_model_json2 == audio_metrics_details_model_json -class TestAudioMetricsHistogramBin(): +class TestModel_AudioMetricsHistogramBin(): """ Test Class for AudioMetricsHistogramBin """ @@ -3785,7 +3867,7 @@ def test_audio_metrics_histogram_bin_serialization(self): audio_metrics_histogram_bin_model_json2 = audio_metrics_histogram_bin_model.to_dict() assert audio_metrics_histogram_bin_model_json2 == audio_metrics_histogram_bin_model_json -class TestAudioResource(): +class TestModel_AudioResource(): """ Test Class for AudioResource """ @@ -3825,7 +3907,7 @@ def test_audio_resource_serialization(self): audio_resource_model_json2 = audio_resource_model.to_dict() assert audio_resource_model_json2 == audio_resource_model_json -class TestAudioResources(): +class TestModel_AudioResources(): """ Test Class for AudioResources """ @@ -3869,7 +3951,7 @@ def test_audio_resources_serialization(self): audio_resources_model_json2 = audio_resources_model.to_dict() assert audio_resources_model_json2 == audio_resources_model_json -class TestCorpora(): +class TestModel_Corpora(): """ Test Class for Corpora """ @@ -3907,7 +3989,7 @@ def test_corpora_serialization(self): corpora_model_json2 = corpora_model.to_dict() assert corpora_model_json2 == corpora_model_json -class TestCorpus(): +class TestModel_Corpus(): """ Test Class for Corpus """ @@ -3940,7 +4022,7 @@ def test_corpus_serialization(self): corpus_model_json2 = corpus_model.to_dict() assert corpus_model_json2 == corpus_model_json -class TestCustomWord(): +class TestModel_CustomWord(): """ Test Class for CustomWord """ @@ -3971,7 +4053,7 @@ def test_custom_word_serialization(self): custom_word_model_json2 = custom_word_model.to_dict() assert custom_word_model_json2 == custom_word_model_json -class TestGrammar(): +class TestModel_Grammar(): """ Test Class for Grammar """ @@ -4003,7 +4085,7 @@ def test_grammar_serialization(self): grammar_model_json2 = grammar_model.to_dict() assert grammar_model_json2 == grammar_model_json -class TestGrammars(): +class TestModel_Grammars(): """ Test Class for Grammars """ @@ -4040,7 +4122,7 @@ def test_grammars_serialization(self): grammars_model_json2 = grammars_model.to_dict() assert grammars_model_json2 == grammars_model_json -class TestKeywordResult(): +class TestModel_KeywordResult(): """ Test Class for KeywordResult """ @@ -4072,7 +4154,7 @@ def test_keyword_result_serialization(self): keyword_result_model_json2 = keyword_result_model.to_dict() assert keyword_result_model_json2 == keyword_result_model_json -class TestLanguageModel(): +class TestModel_LanguageModel(): """ Test Class for LanguageModel """ @@ -4114,7 +4196,7 @@ def test_language_model_serialization(self): language_model_model_json2 = language_model_model.to_dict() assert language_model_model_json2 == language_model_model_json -class TestLanguageModels(): +class TestModel_LanguageModels(): """ Test Class for LanguageModels """ @@ -4161,7 +4243,7 @@ def test_language_models_serialization(self): language_models_model_json2 = language_models_model.to_dict() assert language_models_model_json2 == language_models_model_json -class TestProcessedAudio(): +class TestModel_ProcessedAudio(): """ Test Class for ProcessedAudio """ @@ -4193,7 +4275,7 @@ def test_processed_audio_serialization(self): processed_audio_model_json2 = processed_audio_model.to_dict() assert processed_audio_model_json2 == processed_audio_model_json -class TestProcessingMetrics(): +class TestModel_ProcessingMetrics(): """ Test Class for ProcessingMetrics """ @@ -4232,7 +4314,7 @@ def test_processing_metrics_serialization(self): processing_metrics_model_json2 = processing_metrics_model.to_dict() assert processing_metrics_model_json2 == processing_metrics_model_json -class TestRecognitionJob(): +class TestModel_RecognitionJob(): """ Test Class for RecognitionJob """ @@ -4344,7 +4426,7 @@ def test_recognition_job_serialization(self): recognition_job_model_json2 = recognition_job_model.to_dict() assert recognition_job_model_json2 == recognition_job_model_json -class TestRecognitionJobs(): +class TestModel_RecognitionJobs(): """ Test Class for RecognitionJobs """ @@ -4459,7 +4541,7 @@ def test_recognition_jobs_serialization(self): recognition_jobs_model_json2 = recognition_jobs_model.to_dict() assert recognition_jobs_model_json2 == recognition_jobs_model_json -class TestRegisterStatus(): +class TestModel_RegisterStatus(): """ Test Class for RegisterStatus """ @@ -4489,7 +4571,7 @@ def test_register_status_serialization(self): register_status_model_json2 = register_status_model.to_dict() assert register_status_model_json2 == register_status_model_json -class TestSpeakerLabelsResult(): +class TestModel_SpeakerLabelsResult(): """ Test Class for SpeakerLabelsResult """ @@ -4522,7 +4604,7 @@ def test_speaker_labels_result_serialization(self): speaker_labels_result_model_json2 = speaker_labels_result_model.to_dict() assert speaker_labels_result_model_json2 == speaker_labels_result_model_json -class TestSpeechModel(): +class TestModel_SpeechModel(): """ Test Class for SpeechModel """ @@ -4563,7 +4645,7 @@ def test_speech_model_serialization(self): speech_model_model_json2 = speech_model_model.to_dict() assert speech_model_model_json2 == speech_model_model_json -class TestSpeechModels(): +class TestModel_SpeechModels(): """ Test Class for SpeechModels """ @@ -4607,7 +4689,7 @@ def test_speech_models_serialization(self): speech_models_model_json2 = speech_models_model.to_dict() assert speech_models_model_json2 == speech_models_model_json -class TestSpeechRecognitionAlternative(): +class TestModel_SpeechRecognitionAlternative(): """ Test Class for SpeechRecognitionAlternative """ @@ -4639,7 +4721,7 @@ def test_speech_recognition_alternative_serialization(self): speech_recognition_alternative_model_json2 = speech_recognition_alternative_model.to_dict() assert speech_recognition_alternative_model_json2 == speech_recognition_alternative_model_json -class TestSpeechRecognitionResult(): +class TestModel_SpeechRecognitionResult(): """ Test Class for SpeechRecognitionResult """ @@ -4695,7 +4777,7 @@ def test_speech_recognition_result_serialization(self): speech_recognition_result_model_json2 = speech_recognition_result_model.to_dict() assert speech_recognition_result_model_json2 == speech_recognition_result_model_json -class TestSpeechRecognitionResults(): +class TestModel_SpeechRecognitionResults(): """ Test Class for SpeechRecognitionResults """ @@ -4797,7 +4879,7 @@ def test_speech_recognition_results_serialization(self): speech_recognition_results_model_json2 = speech_recognition_results_model.to_dict() assert speech_recognition_results_model_json2 == speech_recognition_results_model_json -class TestSupportedFeatures(): +class TestModel_SupportedFeatures(): """ Test Class for SupportedFeatures """ @@ -4828,7 +4910,7 @@ def test_supported_features_serialization(self): supported_features_model_json2 = supported_features_model.to_dict() assert supported_features_model_json2 == supported_features_model_json -class TestTrainingResponse(): +class TestModel_TrainingResponse(): """ Test Class for TrainingResponse """ @@ -4863,7 +4945,7 @@ def test_training_response_serialization(self): training_response_model_json2 = training_response_model.to_dict() assert training_response_model_json2 == training_response_model_json -class TestTrainingWarning(): +class TestModel_TrainingWarning(): """ Test Class for TrainingWarning """ @@ -4893,7 +4975,7 @@ def test_training_warning_serialization(self): training_warning_model_json2 = training_warning_model.to_dict() assert training_warning_model_json2 == training_warning_model_json -class TestWord(): +class TestModel_Word(): """ Test Class for Word """ @@ -4932,7 +5014,7 @@ def test_word_serialization(self): word_model_json2 = word_model.to_dict() assert word_model_json2 == word_model_json -class TestWordAlternativeResult(): +class TestModel_WordAlternativeResult(): """ Test Class for WordAlternativeResult """ @@ -4962,7 +5044,7 @@ def test_word_alternative_result_serialization(self): word_alternative_result_model_json2 = word_alternative_result_model.to_dict() assert word_alternative_result_model_json2 == word_alternative_result_model_json -class TestWordAlternativeResults(): +class TestModel_WordAlternativeResults(): """ Test Class for WordAlternativeResults """ @@ -4999,7 +5081,7 @@ def test_word_alternative_results_serialization(self): word_alternative_results_model_json2 = word_alternative_results_model.to_dict() assert word_alternative_results_model_json2 == word_alternative_results_model_json -class TestWordError(): +class TestModel_WordError(): """ Test Class for WordError """ @@ -5028,7 +5110,7 @@ def test_word_error_serialization(self): word_error_model_json2 = word_error_model.to_dict() assert word_error_model_json2 == word_error_model_json -class TestWords(): +class TestModel_Words(): """ Test Class for Words """ diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 7414852a4..c8119130d 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -51,6 +51,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -88,6 +90,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -202,6 +206,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -223,8 +229,8 @@ def test_synthesize_all_params(self): # Set up parameter values text = 'testString' - accept = 'audio/basic' - voice = 'ar-AR_OmarVoice' + accept = 'audio/ogg;codecs=opus' + voice = 'en-US_MichaelV3Voice' customization_id = 'testString' # Invoke method @@ -327,6 +333,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -348,8 +356,8 @@ def test_get_pronunciation_all_params(self): # Set up parameter values text = 'testString' - voice = 'ar-AR_OmarVoice' - format = 'ibm' + voice = 'en-US_MichaelV3Voice' + format = 'ipa' customization_id = 'testString' # Invoke method @@ -452,6 +460,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -473,7 +483,7 @@ def test_create_custom_model_all_params(self): # Set up parameter values name = 'testString' - language = 'ar-MS' + language = 'en-US' description = 'testString' # Invoke method @@ -490,7 +500,7 @@ def test_create_custom_model_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' - assert req_body['language'] == 'ar-MS' + assert req_body['language'] == 'en-US' assert req_body['description'] == 'testString' @@ -510,7 +520,7 @@ def test_create_custom_model_value_error(self): # Set up parameter values name = 'testString' - language = 'ar-MS' + language = 'en-US' description = 'testString' # Pass in all but one required param and check for a ValueError @@ -533,6 +543,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -602,6 +614,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -692,6 +706,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -762,6 +778,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -836,6 +854,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -919,6 +939,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -989,6 +1011,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1068,6 +1092,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1142,6 +1168,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1220,6 +1248,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1290,6 +1320,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1382,6 +1414,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1456,6 +1490,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1534,6 +1570,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1571,6 +1609,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1651,6 +1691,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1721,6 +1763,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1795,6 +1839,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1864,7 +1910,7 @@ def test_delete_user_data_value_error(self): # Start of Model Tests ############################################################################## # region -class TestCustomModel(): +class TestModel_CustomModel(): """ Test Class for CustomModel """ @@ -1915,7 +1961,7 @@ def test_custom_model_serialization(self): custom_model_model_json2 = custom_model_model.to_dict() assert custom_model_model_json2 == custom_model_model_json -class TestCustomModels(): +class TestModel_CustomModels(): """ Test Class for CustomModels """ @@ -1969,7 +2015,7 @@ def test_custom_models_serialization(self): custom_models_model_json2 = custom_models_model.to_dict() assert custom_models_model_json2 == custom_models_model_json -class TestPrompt(): +class TestModel_Prompt(): """ Test Class for Prompt """ @@ -2002,7 +2048,7 @@ def test_prompt_serialization(self): prompt_model_json2 = prompt_model.to_dict() assert prompt_model_json2 == prompt_model_json -class TestPromptMetadata(): +class TestModel_PromptMetadata(): """ Test Class for PromptMetadata """ @@ -2032,7 +2078,7 @@ def test_prompt_metadata_serialization(self): prompt_metadata_model_json2 = prompt_metadata_model.to_dict() assert prompt_metadata_model_json2 == prompt_metadata_model_json -class TestPrompts(): +class TestModel_Prompts(): """ Test Class for Prompts """ @@ -2070,7 +2116,7 @@ def test_prompts_serialization(self): prompts_model_json2 = prompts_model.to_dict() assert prompts_model_json2 == prompts_model_json -class TestPronunciation(): +class TestModel_Pronunciation(): """ Test Class for Pronunciation """ @@ -2099,7 +2145,7 @@ def test_pronunciation_serialization(self): pronunciation_model_json2 = pronunciation_model.to_dict() assert pronunciation_model_json2 == pronunciation_model_json -class TestSpeaker(): +class TestModel_Speaker(): """ Test Class for Speaker """ @@ -2129,7 +2175,7 @@ def test_speaker_serialization(self): speaker_model_json2 = speaker_model.to_dict() assert speaker_model_json2 == speaker_model_json -class TestSpeakerCustomModel(): +class TestModel_SpeakerCustomModel(): """ Test Class for SpeakerCustomModel """ @@ -2167,7 +2213,7 @@ def test_speaker_custom_model_serialization(self): speaker_custom_model_model_json2 = speaker_custom_model_model.to_dict() assert speaker_custom_model_model_json2 == speaker_custom_model_model_json -class TestSpeakerCustomModels(): +class TestModel_SpeakerCustomModels(): """ Test Class for SpeakerCustomModels """ @@ -2208,7 +2254,7 @@ def test_speaker_custom_models_serialization(self): speaker_custom_models_model_json2 = speaker_custom_models_model.to_dict() assert speaker_custom_models_model_json2 == speaker_custom_models_model_json -class TestSpeakerModel(): +class TestModel_SpeakerModel(): """ Test Class for SpeakerModel """ @@ -2237,7 +2283,7 @@ def test_speaker_model_serialization(self): speaker_model_model_json2 = speaker_model_model.to_dict() assert speaker_model_model_json2 == speaker_model_model_json -class TestSpeakerPrompt(): +class TestModel_SpeakerPrompt(): """ Test Class for SpeakerPrompt """ @@ -2269,7 +2315,7 @@ def test_speaker_prompt_serialization(self): speaker_prompt_model_json2 = speaker_prompt_model.to_dict() assert speaker_prompt_model_json2 == speaker_prompt_model_json -class TestSpeakers(): +class TestModel_Speakers(): """ Test Class for Speakers """ @@ -2304,7 +2350,7 @@ def test_speakers_serialization(self): speakers_model_json2 = speakers_model.to_dict() assert speakers_model_json2 == speakers_model_json -class TestSupportedFeatures(): +class TestModel_SupportedFeatures(): """ Test Class for SupportedFeatures """ @@ -2334,7 +2380,7 @@ def test_supported_features_serialization(self): supported_features_model_json2 = supported_features_model.to_dict() assert supported_features_model_json2 == supported_features_model_json -class TestTranslation(): +class TestModel_Translation(): """ Test Class for Translation """ @@ -2364,7 +2410,7 @@ def test_translation_serialization(self): translation_model_json2 = translation_model.to_dict() assert translation_model_json2 == translation_model_json -class TestVoice(): +class TestModel_Voice(): """ Test Class for Voice """ @@ -2429,7 +2475,7 @@ def test_voice_serialization(self): voice_model_json2 = voice_model.to_dict() assert voice_model_json2 == voice_model_json -class TestVoices(): +class TestModel_Voices(): """ Test Class for Voices """ @@ -2497,7 +2543,7 @@ def test_voices_serialization(self): voices_model_json2 = voices_model.to_dict() assert voices_model_json2 == voices_model_json -class TestWord(): +class TestModel_Word(): """ Test Class for Word """ @@ -2528,7 +2574,7 @@ def test_word_serialization(self): word_model_json2 = word_model.to_dict() assert word_model_json2 == word_model_json -class TestWords(): +class TestModel_Words(): """ Test Class for Words """ diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py index cb398a571..1a97b5441 100755 --- a/test/unit/test_tone_analyzer_v3.py +++ b/test/unit/test_tone_analyzer_v3.py @@ -51,6 +51,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -80,7 +82,7 @@ def test_tone_all_params(self): sentences = True tones = ['emotion'] content_language = 'en' - accept_language = 'ar' + accept_language = 'en' # Invoke method response = _service.tone( @@ -178,6 +180,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -205,7 +209,7 @@ def test_tone_chat_all_params(self): # Set up parameter values utterances = [utterance_model] content_language = 'en' - accept_language = 'ar' + accept_language = 'en' # Invoke method response = _service.tone_chat( @@ -302,7 +306,7 @@ def test_tone_chat_value_error(self): # Start of Model Tests ############################################################################## # region -class TestDocumentAnalysis(): +class TestModel_DocumentAnalysis(): """ Test Class for DocumentAnalysis """ @@ -345,7 +349,7 @@ def test_document_analysis_serialization(self): document_analysis_model_json2 = document_analysis_model.to_dict() assert document_analysis_model_json2 == document_analysis_model_json -class TestSentenceAnalysis(): +class TestModel_SentenceAnalysis(): """ Test Class for SentenceAnalysis """ @@ -391,7 +395,7 @@ def test_sentence_analysis_serialization(self): sentence_analysis_model_json2 = sentence_analysis_model.to_dict() assert sentence_analysis_model_json2 == sentence_analysis_model_json -class TestToneAnalysis(): +class TestModel_ToneAnalysis(): """ Test Class for ToneAnalysis """ @@ -446,7 +450,7 @@ def test_tone_analysis_serialization(self): tone_analysis_model_json2 = tone_analysis_model.to_dict() assert tone_analysis_model_json2 == tone_analysis_model_json -class TestToneCategory(): +class TestModel_ToneCategory(): """ Test Class for ToneCategory """ @@ -484,7 +488,7 @@ def test_tone_category_serialization(self): tone_category_model_json2 = tone_category_model.to_dict() assert tone_category_model_json2 == tone_category_model_json -class TestToneChatScore(): +class TestModel_ToneChatScore(): """ Test Class for ToneChatScore """ @@ -515,7 +519,7 @@ def test_tone_chat_score_serialization(self): tone_chat_score_model_json2 = tone_chat_score_model.to_dict() assert tone_chat_score_model_json2 == tone_chat_score_model_json -class TestToneInput(): +class TestModel_ToneInput(): """ Test Class for ToneInput """ @@ -544,7 +548,7 @@ def test_tone_input_serialization(self): tone_input_model_json2 = tone_input_model.to_dict() assert tone_input_model_json2 == tone_input_model_json -class TestToneScore(): +class TestModel_ToneScore(): """ Test Class for ToneScore """ @@ -575,7 +579,7 @@ def test_tone_score_serialization(self): tone_score_model_json2 = tone_score_model.to_dict() assert tone_score_model_json2 == tone_score_model_json -class TestUtterance(): +class TestModel_Utterance(): """ Test Class for Utterance """ @@ -605,7 +609,7 @@ def test_utterance_serialization(self): utterance_model_json2 = utterance_model.to_dict() assert utterance_model_json2 == utterance_model_json -class TestUtteranceAnalyses(): +class TestModel_UtteranceAnalyses(): """ Test Class for UtteranceAnalyses """ @@ -648,7 +652,7 @@ def test_utterance_analyses_serialization(self): utterance_analyses_model_json2 = utterance_analyses_model.to_dict() assert utterance_analyses_model_json2 == utterance_analyses_model_json -class TestUtteranceAnalysis(): +class TestModel_UtteranceAnalysis(): """ Test Class for UtteranceAnalysis """ diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py index ae9e5f132..327eb930d 100644 --- a/test/unit/test_visual_recognition_v3.py +++ b/test/unit/test_visual_recognition_v3.py @@ -55,6 +55,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -168,6 +170,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -276,6 +280,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -369,6 +375,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -439,6 +447,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -543,6 +553,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -617,6 +629,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -697,6 +711,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -766,7 +782,7 @@ def test_delete_user_data_value_error(self): # Start of Model Tests ############################################################################## # region -class TestClass(): +class TestModel_Class(): """ Test Class for Class """ @@ -795,7 +811,7 @@ def test_class_serialization(self): class_model_json2 = class_model.to_dict() assert class_model_json2 == class_model_json -class TestClassResult(): +class TestModel_ClassResult(): """ Test Class for ClassResult """ @@ -826,7 +842,7 @@ def test_class_result_serialization(self): class_result_model_json2 = class_result_model.to_dict() assert class_result_model_json2 == class_result_model_json -class TestClassifiedImage(): +class TestModel_ClassifiedImage(): """ Test Class for ClassifiedImage """ @@ -876,7 +892,7 @@ def test_classified_image_serialization(self): classified_image_model_json2 = classified_image_model.to_dict() assert classified_image_model_json2 == classified_image_model_json -class TestClassifiedImages(): +class TestModel_ClassifiedImages(): """ Test Class for ClassifiedImages """ @@ -936,7 +952,7 @@ def test_classified_images_serialization(self): classified_images_model_json2 = classified_images_model.to_dict() assert classified_images_model_json2 == classified_images_model_json -class TestClassifier(): +class TestModel_Classifier(): """ Test Class for Classifier """ @@ -959,10 +975,10 @@ def test_classifier_serialization(self): classifier_model_json['status'] = 'ready' classifier_model_json['core_ml_enabled'] = True classifier_model_json['explanation'] = 'testString' - classifier_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifier_model_json['created'] = "2019-01-01T12:00:00Z" classifier_model_json['classes'] = [class_model] - classifier_model_json['retrained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - classifier_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifier_model_json['retrained'] = "2019-01-01T12:00:00Z" + classifier_model_json['updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of Classifier by calling from_dict on the json representation classifier_model = Classifier.from_dict(classifier_model_json) @@ -979,7 +995,7 @@ def test_classifier_serialization(self): classifier_model_json2 = classifier_model.to_dict() assert classifier_model_json2 == classifier_model_json -class TestClassifierResult(): +class TestModel_ClassifierResult(): """ Test Class for ClassifierResult """ @@ -1017,7 +1033,7 @@ def test_classifier_result_serialization(self): classifier_result_model_json2 = classifier_result_model.to_dict() assert classifier_result_model_json2 == classifier_result_model_json -class TestClassifiers(): +class TestModel_Classifiers(): """ Test Class for Classifiers """ @@ -1039,10 +1055,10 @@ def test_classifiers_serialization(self): classifier_model['status'] = 'ready' classifier_model['core_ml_enabled'] = True classifier_model['explanation'] = 'testString' - classifier_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifier_model['created'] = "2019-01-01T12:00:00Z" classifier_model['classes'] = [class_model] - classifier_model['retrained'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - classifier_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + classifier_model['retrained'] = "2019-01-01T12:00:00Z" + classifier_model['updated'] = "2019-01-01T12:00:00Z" # Construct a json representation of a Classifiers model classifiers_model_json = {} @@ -1063,7 +1079,7 @@ def test_classifiers_serialization(self): classifiers_model_json2 = classifiers_model.to_dict() assert classifiers_model_json2 == classifiers_model_json -class TestErrorInfo(): +class TestModel_ErrorInfo(): """ Test Class for ErrorInfo """ @@ -1094,7 +1110,7 @@ def test_error_info_serialization(self): error_info_model_json2 = error_info_model.to_dict() assert error_info_model_json2 == error_info_model_json -class TestWarningInfo(): +class TestModel_WarningInfo(): """ Test Class for WarningInfo """ diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index f6d177cce..d1875fdc5 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -56,6 +56,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -182,6 +184,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -288,6 +292,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -349,6 +355,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -419,6 +427,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -541,6 +551,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -605,6 +617,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -698,6 +712,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -808,6 +824,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -878,6 +896,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -952,6 +972,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1020,6 +1042,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1140,6 +1164,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1210,6 +1236,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1291,6 +1319,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1365,6 +1395,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1443,6 +1475,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1513,6 +1547,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1617,6 +1653,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1723,6 +1761,8 @@ def preprocess_url(self, request_url: str): """ Preprocess the request URL to ensure the mock response will be found. """ + request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded + request_url = urllib.parse.quote(request_url, safe=':/') if re.fullmatch('.*/+', request_url) is None: return request_url else: @@ -1792,7 +1832,7 @@ def test_delete_user_data_value_error(self): # Start of Model Tests ############################################################################## # region -class TestAnalyzeResponse(): +class TestModel_AnalyzeResponse(): """ Test Class for AnalyzeResponse """ @@ -1875,7 +1915,7 @@ def test_analyze_response_serialization(self): analyze_response_model_json2 = analyze_response_model.to_dict() assert analyze_response_model_json2 == analyze_response_model_json -class TestCollection(): +class TestModel_Collection(): """ Test Class for Collection """ @@ -1903,8 +1943,8 @@ def test_collection_serialization(self): collection_model_json['collection_id'] = 'testString' collection_model_json['name'] = 'testString' collection_model_json['description'] = 'testString' - collection_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - collection_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + collection_model_json['created'] = "2019-01-01T12:00:00Z" + collection_model_json['updated'] = "2019-01-01T12:00:00Z" collection_model_json['image_count'] = 38 collection_model_json['training_status'] = collection_training_status_model @@ -1923,7 +1963,7 @@ def test_collection_serialization(self): collection_model_json2 = collection_model.to_dict() assert collection_model_json2 == collection_model_json -class TestCollectionObjects(): +class TestModel_CollectionObjects(): """ Test Class for CollectionObjects """ @@ -1966,7 +2006,7 @@ def test_collection_objects_serialization(self): collection_objects_model_json2 = collection_objects_model.to_dict() assert collection_objects_model_json2 == collection_objects_model_json -class TestCollectionTrainingStatus(): +class TestModel_CollectionTrainingStatus(): """ Test Class for CollectionTrainingStatus """ @@ -2005,7 +2045,7 @@ def test_collection_training_status_serialization(self): collection_training_status_model_json2 = collection_training_status_model.to_dict() assert collection_training_status_model_json2 == collection_training_status_model_json -class TestCollectionsList(): +class TestModel_CollectionsList(): """ Test Class for CollectionsList """ @@ -2032,8 +2072,8 @@ def test_collections_list_serialization(self): collection_model['collection_id'] = 'testString' collection_model['name'] = 'testString' collection_model['description'] = 'testString' - collection_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - collection_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + collection_model['created'] = "2019-01-01T12:00:00Z" + collection_model['updated'] = "2019-01-01T12:00:00Z" collection_model['image_count'] = 38 collection_model['training_status'] = collection_training_status_model @@ -2056,7 +2096,7 @@ def test_collections_list_serialization(self): collections_list_model_json2 = collections_list_model.to_dict() assert collections_list_model_json2 == collections_list_model_json -class TestDetectedObjects(): +class TestModel_DetectedObjects(): """ Test Class for DetectedObjects """ @@ -2102,7 +2142,7 @@ def test_detected_objects_serialization(self): detected_objects_model_json2 = detected_objects_model.to_dict() assert detected_objects_model_json2 == detected_objects_model_json -class TestError(): +class TestModel_Error(): """ Test Class for Error """ @@ -2140,7 +2180,7 @@ def test_error_serialization(self): error_model_json2 = error_model.to_dict() assert error_model_json2 == error_model_json -class TestErrorTarget(): +class TestModel_ErrorTarget(): """ Test Class for ErrorTarget """ @@ -2170,7 +2210,7 @@ def test_error_target_serialization(self): error_target_model_json2 = error_target_model.to_dict() assert error_target_model_json2 == error_target_model_json -class TestImage(): +class TestModel_Image(): """ Test Class for Image """ @@ -2243,7 +2283,7 @@ def test_image_serialization(self): image_model_json2 = image_model.to_dict() assert image_model_json2 == image_model_json -class TestImageDetails(): +class TestModel_ImageDetails(): """ Test Class for ImageDetails """ @@ -2292,8 +2332,8 @@ def test_image_details_serialization(self): # Construct a json representation of a ImageDetails model image_details_model_json = {} image_details_model_json['image_id'] = 'testString' - image_details_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - image_details_model_json['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + image_details_model_json['updated'] = "2019-01-01T12:00:00Z" + image_details_model_json['created'] = "2019-01-01T12:00:00Z" image_details_model_json['source'] = image_source_model image_details_model_json['dimensions'] = image_dimensions_model image_details_model_json['errors'] = [error_model] @@ -2314,7 +2354,7 @@ def test_image_details_serialization(self): image_details_model_json2 = image_details_model.to_dict() assert image_details_model_json2 == image_details_model_json -class TestImageDetailsList(): +class TestModel_ImageDetailsList(): """ Test Class for ImageDetailsList """ @@ -2362,8 +2402,8 @@ def test_image_details_list_serialization(self): image_details_model = {} # ImageDetails image_details_model['image_id'] = 'testString' - image_details_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - image_details_model['created'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + image_details_model['updated'] = "2019-01-01T12:00:00Z" + image_details_model['created'] = "2019-01-01T12:00:00Z" image_details_model['source'] = image_source_model image_details_model['dimensions'] = image_dimensions_model image_details_model['errors'] = [error_model] @@ -2395,7 +2435,7 @@ def test_image_details_list_serialization(self): image_details_list_model_json2 = image_details_list_model.to_dict() assert image_details_list_model_json2 == image_details_list_model_json -class TestImageDimensions(): +class TestModel_ImageDimensions(): """ Test Class for ImageDimensions """ @@ -2425,7 +2465,7 @@ def test_image_dimensions_serialization(self): image_dimensions_model_json2 = image_dimensions_model.to_dict() assert image_dimensions_model_json2 == image_dimensions_model_json -class TestImageSource(): +class TestModel_ImageSource(): """ Test Class for ImageSource """ @@ -2458,7 +2498,7 @@ def test_image_source_serialization(self): image_source_model_json2 = image_source_model.to_dict() assert image_source_model_json2 == image_source_model_json -class TestImageSummary(): +class TestModel_ImageSummary(): """ Test Class for ImageSummary """ @@ -2471,7 +2511,7 @@ def test_image_summary_serialization(self): # Construct a json representation of a ImageSummary model image_summary_model_json = {} image_summary_model_json['image_id'] = 'testString' - image_summary_model_json['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + image_summary_model_json['updated'] = "2019-01-01T12:00:00Z" # Construct a model instance of ImageSummary by calling from_dict on the json representation image_summary_model = ImageSummary.from_dict(image_summary_model_json) @@ -2488,7 +2528,7 @@ def test_image_summary_serialization(self): image_summary_model_json2 = image_summary_model.to_dict() assert image_summary_model_json2 == image_summary_model_json -class TestImageSummaryList(): +class TestModel_ImageSummaryList(): """ Test Class for ImageSummaryList """ @@ -2502,7 +2542,7 @@ def test_image_summary_list_serialization(self): image_summary_model = {} # ImageSummary image_summary_model['image_id'] = 'testString' - image_summary_model['updated'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + image_summary_model['updated'] = "2019-01-01T12:00:00Z" # Construct a json representation of a ImageSummaryList model image_summary_list_model_json = {} @@ -2523,7 +2563,7 @@ def test_image_summary_list_serialization(self): image_summary_list_model_json2 = image_summary_list_model.to_dict() assert image_summary_list_model_json2 == image_summary_list_model_json -class TestLocation(): +class TestModel_Location(): """ Test Class for Location """ @@ -2555,7 +2595,7 @@ def test_location_serialization(self): location_model_json2 = location_model.to_dict() assert location_model_json2 == location_model_json -class TestObjectDetail(): +class TestModel_ObjectDetail(): """ Test Class for ObjectDetail """ @@ -2594,7 +2634,7 @@ def test_object_detail_serialization(self): object_detail_model_json2 = object_detail_model.to_dict() assert object_detail_model_json2 == object_detail_model_json -class TestObjectDetailLocation(): +class TestModel_ObjectDetailLocation(): """ Test Class for ObjectDetailLocation """ @@ -2626,7 +2666,7 @@ def test_object_detail_location_serialization(self): object_detail_location_model_json2 = object_detail_location_model.to_dict() assert object_detail_location_model_json2 == object_detail_location_model_json -class TestObjectMetadata(): +class TestModel_ObjectMetadata(): """ Test Class for ObjectMetadata """ @@ -2656,7 +2696,7 @@ def test_object_metadata_serialization(self): object_metadata_model_json2 = object_metadata_model.to_dict() assert object_metadata_model_json2 == object_metadata_model_json -class TestObjectMetadataList(): +class TestModel_ObjectMetadataList(): """ Test Class for ObjectMetadataList """ @@ -2692,7 +2732,7 @@ def test_object_metadata_list_serialization(self): object_metadata_list_model_json2 = object_metadata_list_model.to_dict() assert object_metadata_list_model_json2 == object_metadata_list_model_json -class TestObjectTrainingStatus(): +class TestModel_ObjectTrainingStatus(): """ Test Class for ObjectTrainingStatus """ @@ -2726,7 +2766,7 @@ def test_object_training_status_serialization(self): object_training_status_model_json2 = object_training_status_model.to_dict() assert object_training_status_model_json2 == object_training_status_model_json -class TestTrainingDataObject(): +class TestModel_TrainingDataObject(): """ Test Class for TrainingDataObject """ @@ -2764,7 +2804,7 @@ def test_training_data_object_serialization(self): training_data_object_model_json2 = training_data_object_model.to_dict() assert training_data_object_model_json2 == training_data_object_model_json -class TestTrainingDataObjects(): +class TestModel_TrainingDataObjects(): """ Test Class for TrainingDataObjects """ @@ -2805,7 +2845,7 @@ def test_training_data_objects_serialization(self): training_data_objects_model_json2 = training_data_objects_model.to_dict() assert training_data_objects_model_json2 == training_data_objects_model_json -class TestTrainingEvent(): +class TestModel_TrainingEvent(): """ Test Class for TrainingEvent """ @@ -2819,7 +2859,7 @@ def test_training_event_serialization(self): training_event_model_json = {} training_event_model_json['type'] = 'objects' training_event_model_json['collection_id'] = 'testString' - training_event_model_json['completion_time'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_event_model_json['completion_time'] = "2019-01-01T12:00:00Z" training_event_model_json['status'] = 'failed' training_event_model_json['image_count'] = 38 @@ -2838,7 +2878,7 @@ def test_training_event_serialization(self): training_event_model_json2 = training_event_model.to_dict() assert training_event_model_json2 == training_event_model_json -class TestTrainingEvents(): +class TestModel_TrainingEvents(): """ Test Class for TrainingEvents """ @@ -2853,14 +2893,14 @@ def test_training_events_serialization(self): training_event_model = {} # TrainingEvent training_event_model['type'] = 'objects' training_event_model['collection_id'] = 'testString' - training_event_model['completion_time'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_event_model['completion_time'] = "2019-01-01T12:00:00Z" training_event_model['status'] = 'failed' training_event_model['image_count'] = 38 # Construct a json representation of a TrainingEvents model training_events_model_json = {} - training_events_model_json['start_time'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) - training_events_model_json['end_time'] = datetime_to_string(string_to_datetime("2019-01-01T12:00:00.000Z")) + training_events_model_json['start_time'] = "2019-01-01T12:00:00Z" + training_events_model_json['end_time'] = "2019-01-01T12:00:00Z" training_events_model_json['completed_events'] = 38 training_events_model_json['trained_images'] = 38 training_events_model_json['events'] = [training_event_model] @@ -2880,7 +2920,7 @@ def test_training_events_serialization(self): training_events_model_json2 = training_events_model.to_dict() assert training_events_model_json2 == training_events_model_json -class TestTrainingStatus(): +class TestModel_TrainingStatus(): """ Test Class for TrainingStatus """ @@ -2919,7 +2959,7 @@ def test_training_status_serialization(self): training_status_model_json2 = training_status_model.to_dict() assert training_status_model_json2 == training_status_model_json -class TestUpdateObjectMetadata(): +class TestModel_UpdateObjectMetadata(): """ Test Class for UpdateObjectMetadata """ @@ -2949,7 +2989,7 @@ def test_update_object_metadata_serialization(self): update_object_metadata_model_json2 = update_object_metadata_model.to_dict() assert update_object_metadata_model_json2 == update_object_metadata_model_json -class TestWarning(): +class TestModel_Warning(): """ Test Class for Warning """ @@ -2980,7 +3020,7 @@ def test_warning_serialization(self): warning_model_json2 = warning_model.to_dict() assert warning_model_json2 == warning_model_json -class TestFileWithMetadata(): +class TestModel_FileWithMetadata(): """ Test Class for FileWithMetadata """ From 1b05e1b3169b8c904fd17c3834d4e61779fa511c Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 9 Sep 2021 15:48:26 -0400 Subject: [PATCH 352/455] fix(wss): fix on_transcription parsing issue including tests --- ibm_watson/websocket/recognize_listener.py | 27 ++++--- resources/speech_with_pause.wav | Bin 0 -> 360398 bytes test/integration/test_speech_to_text_v1.py | 87 +++++++++++++++++++-- 3 files changed, 100 insertions(+), 14 deletions(-) create mode 100644 resources/speech_with_pause.wav diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index 21679760f..9847e9192 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -198,15 +198,24 @@ def on_data(self, ws, message, message_type, fin): # set of transcriptions and send them to the appropriate callbacks. results = json_object.get('results') if results: - b_final = (results[0].get('final') is True) - alternatives = results[0].get('alternatives') - if alternatives: - hypothesis = alternatives[0].get('transcript') - transcripts = self.extract_transcripts(alternatives) - if b_final: - self.callback.on_transcription(transcripts) - if hypothesis: - self.callback.on_hypothesis(hypothesis) + if (self.options.get('interim_results') is True): + b_final = (results[0].get('final') is True) + alternatives = results[0].get('alternatives') + if alternatives: + hypothesis = alternatives[0].get('transcript') + transcripts = self.extract_transcripts(alternatives) + if b_final: + self.callback.on_transcription(transcripts) + if hypothesis: + self.callback.on_hypothesis(hypothesis) + else: + final_transcript = [] + for result in results: + transcript = self.extract_transcripts( + result.get('alternatives')) + final_transcript.append(transcript) + + self.callback.on_transcription(final_transcript) # Always call the on_data callback if 'results' or 'speaker_labels' are present self.callback.on_data(json_object) diff --git a/resources/speech_with_pause.wav b/resources/speech_with_pause.wav new file mode 100644 index 0000000000000000000000000000000000000000..783426cb598d2e6abbed337e21db0cff35176049 GIT binary patch literal 360398 zcmYJ62mDXf|Hm(pl@bXdWEHYE*_4sWs7OgEEkcQm5JHNmh@=wIL?w|>v?N7FW=pon zio*RrpXc!VyN}P;XWV=CdC%ATecCi{*6gdnnUh-@-rV%w?vEDDl_W_9t|sp$$*5a1 zBpH)jNvq~<+g--@&09CSp?TY8?Jneft1ge-TdijKDpkr?s#r1U+U3zMLnvi%`dHc{ z?Ug>BKA8?nho@uGvFXHgTKY=*a{5|2BYiWSmo841q)XF9{QpJzS^8o6Uiwx#HGMW6 z%2Q8p4NsrrnHRaH^2{`zd@&uz@6Vl%Lj zEBz-ulV+m-N7G&Dmh}5{CHJl7w=L=R^iY~1$(&rA6iiAbWs`Erl}X9uvgCr~RJxbD zx23sA)qJjyR7t8O^^(R(gXEf|MpBu(u1NAG z*^~2<)9K0dM4G1AlEU0uEvcSV<*8!HrOEls%qdDeLhDYaS-8I#cT}Z>=E+UT9m$=^ zZCve>R(x)nG~sH*t9jBUxg}}G-`kRVlI}@=u1Avl_^uhxmP{_9)RUpLr_${7sT?)d z;i-;Ex1@LSaPk08-AGHT($BKAG8Zi=!#(wqy0pAb(vq@oNxD#C*W@mq>B!y9X;V|m zugCAT!s|*}dtP#azWqln)sy>^k;$}VQL;Fhp7csCNmiwQra6+Gtc+FZm+5!uF=lEy zSoBAVO8>C@=nqv!yOq` zBomT87+wQZZe7rgxf;dFqzVJ#$6+K5J)ST7w$uCr>96lR?x{moY4z ze3q6^Td;Btq%D$$jB6?SUL~oW989~VU6}v=jNyN*vKnJ14SU1|>Hn zYgxq;(+%mj=`Cp+)?8LfzK>BYm~2bm<<2?mfNkkFjCeW5@g%FaecGSZ`XSFfoGwcX zFuoJhj;!p{th0IPsPxlxUs{Ogt0aSye#z~$a$qt(d7Lq>%KE8CpH{M0x~G-Xf6n}U zrbOB_Et_7RUeCJU#VTKw9!^U!CoQ=D_T*VcraSAgQj#ZGnvPE&NFPl{rw^sKvj1i< zn%^^87qNoIB=eIWl3$a}$vnosC98cs{TxA`YNZv^M)a&j+BWUYGrMTpt;q|?!em{t zB6%-)C3%n;zmVQ;WGDTUe#M@g!rolStp3W*I-ZtJ`cUf1a?_$)S@V_nE*CxjJ)KYcXEAS|()te= zfi=wgYSzvk`f(sV59)C;-OpHLXFru&rWO09G*t8mrRSiX*^>jb@k081HS>2v z(j)1~+_z^%KF>9b)jgQ?If?fZSmXCWdAdP?1}0A>ud=RsL1Fr^g2zCY?&UQi8N%A^ z7izqN8gGIA+z)MgG5LVi`ytfjJ6738tjUGRf@CJ;j^#Bq8O~jIQ@Vd2;OX9Bhdz`H zpu9oJ6UmcMgr})<1n-6N7i;OA99@Z&J@< z>U)_rJ(b@EQu6)W_aOZo48(<}6&H*I*5vLB}x4+dIo zEe~X3X<5N9VDs zb295!@?8^V&S^W!mm>D2ts@zq=NLJqulMNZo4m6hkEVB~t>GvgnT6rh=q!8y zb@+t#%;m24x!$G+3mN6*jK+tI&?mI?73y;~hSSdO)G~lk9mG8LrtS&!W1OSM)TeCwA7Nu@ooSmkL0fDVYNIN?wu9n z!G%HA{1#69H7mtAn!{^SSRqrXVH&L%#*^<-*PHZqC6eK4?p{JKe&EwGetC^iAJ1G2 zWej>VQXN?*cT@ATjQUd6zy^5vKKRZ~c+3VQ%KzZnr=WI6po(XZ(@sKTrTQBwaV;Eh zHKn>@zD<8*wSO4+!)LT_KJVtTO220OR&wX@G-udZm%ySTUvGwDwSgnmg5s3ts!Qq8 z&3lngJ0U6G!@Ewrp5V!kkV8J>`i9r*(B>B@`3WduFKF-G+;tc28^Eg?aZTkl z4k>I>GKKq}O`hTXOS~HoA9yo)BbkxRLdN+NJ~W5xecr#%^=0yX@@=vz*_s?pjv!lo znJhtOTAh3j2N@547{YkmOWPiX;`gBq%dUIeICT`L#THu^~s$^z)hYE z{AEn?9Aohup9jJrhVlD2KD|QiAMtk>Wj+ujm8S5CyQ%95IMO)k9Zf%`QQic~8OKv{ zpzeV?_vZhHxoa{bGo3nTCU5b6INx=Lv)u=OR!ew@zmM?$^~~6{K^N)3s6Ed8AJeya z$=gVIFH`a(aGQ2qt>F*#nHx2imdsOEdM%ghLoXf-yrvQoRtcn|Lhy=uth-xi_btp_ zE1s$rB%+JaLr)=tp82ko?6y z*uef<0hM}-YZ-fHJ3ApwFXN87$aFPW=S>2~%a3GvJ}dZSkU@7)?t4(0anO(fP}H&P z+wI7p*|~BeMP)%oTMcho%ii0!BFR(8rN(FQQd)^h?=Q8F{i8El0~?XI5af z7iHX}8~M0S2U@X;-p+$&y#)P}CoY6~ErEZ%$#-hmuR-e;!A;eV*HMR@c?s=b1U32` zTE3M3e}h&W;dO%RZ|KEpepvwJe~n(w;Q1xUxf^(?QNI(o%;RZac+Ioa_yIKMSH@~3 zHM~cS!{8+Mz*RcKuhgqLGn!A)mW9-OD$T>LFAnuM2F?0{k|)AL`olw>g=&8Wh5Uq3 zdX;aVfF4&%uM8SV`?Le4+y^JSmv3+7|AExX`bm|*|G|+*v8l-j6wyLG|(w0GX z=mcj_Lg`1zPxIV(W^WRu&SCtPGfq<8uNbAr(3zUSn=7W3(kis10bIHcnpAsu^lgmC zL)u6;gsVl83c(FwFLLM&lqhk3y{f_U!D(uo658y}OegU4%Vw z5+1gmwXuYCv6g#Jvj+2`2Q`G!b`ElPKkk2=cQ-=0o1UfP^(n11YcMA}=r6eA=CFEm zB8A?`ZkL91V`tW5Kj-J3GjN@)tiCmjm^PZDtbmE(<$#0_$!P>wg)&ImoP+WOP~w?M_?M zP0V#Q=HX)Kj8>~0p#|l!Jhgxuv}7h~^F&@o{s8^^kur8dI}Xy5BdkNmH!tliz&w_q zloE`PEyxzG%#?W)x_gvo_wzbTf24JV=tW)T?gr$5Hq7(g@Q&{Akj|`?PJCaHKIRY9 zI1_S1c3%ImOLlPWrkq36e2kJ#QC7yVa+E7FKu<4*-&CaKH&LRRX)kE=1FX=y0{3W& zB#{@MvyVC0!u;*wsch6!EKsUU=(v9dI(?8;+Yo*>4DL58c^CdYl=gLC%x>a!BidHi zpnLY9^lq%2E`095Xw`%3lxK!)`(=zo6-v1=^zB|+a4VdzF(Z97S9RXCV(dGz%A3JM ztFrbA($9Yx*;8oOms3Vbc1|;X?-+P(b;`?6|1vS6|8Y;ky$2YL-K?4Yy!Nn8_cJO- z7^mOppCh%4PZ`*^|4`~aKK};w_yO9keRMbb{{lwC-EkrFl^IJ+f|jY(B`@_{!kk{h ziqFKAgLlraGn<|JoJ(cSxK}UZ?i`Hj-<0|_Jn~(xd2oTxS)s?UkK|?NYGW-)uiU{2 zJ4~y^UfR5y*8y7RditC4vQq06jA3=gsW$Vd4YV%fRfzE{NGp|R?NMfG%uk8spa7Lw zONHT-j>qq;(9OJ*iBBR~D6N)*FKZ92$5orM3v#ccca+&b#VBN<#|5diG&5I<`wMav zVf>5o{wh{eMQW(P4Ap|>)#YkHn`#AmcOJIoJ=C|J5&etoZYI zx!QB`q_(qsjBE*>cD>vjB(b~MN$uIYjp%tr#!^df6?##b&sWnT=QUv*wSs4(4VN;$ zQWs^XreWXTz^c;5gzs8YdM(CJyO#E@OR2RyWjCOn8v_-o$ygVomG<%?+EtX# zb@`<``)4eY(yPeVW1zPWuv;23qNM{ptIYd$wE9u#@x##axRWaJo1<2M*{u(ixP^W8 zAp5yH`>6x%sX*z4xGty0D`|HPYO2Avt};2Jc71KW+R*Fse--*&mRA+pTaQtw%=;3I z!wIO_Pw-u>7gGD}jJI@rGym^K?%KgDsDqsdbnFo8)}5r~?=QYT$;@P9t}-&7Sy|gk zkdEzf?)sJTeqv?Bk~dM_VOE=7hs$VX87^m987~ui>I9`7VFzAJf2z~wW})5H>09x$ zeUV#gy}z9KKA+Vg1ypNPH*|mNvDnKy^~DUd>XNYX3ec(y%=KaF{|Roi5`GmuA)DB* zYx!mwJM|0X?GM?v?;s0)!uutBvy9(1umZi*Nq>YxeagPp%JCkrxx8i}7ruy2|7O_p zpCDbVfx;~3zAuoLzCd2_zIj3V{EE?ap_j2uFY=38jcQKOg*7N8~4%ST`#vmKL zI?M?EMBC<5%0jNsC~-9{UP}$?_+N8SkJw4n4xE|EA>U9 z>=C5mvBCDUoHAYSN-mq||4N?xC|FTmL~|L6T%s?p4>ps>gUx3c-#&#_GZFpcb>{u; zV2OE?vL+!f>oEVcs1o}&i`$Zq#vNIk0Uep<$4Uw;z91YpZ9tfr?IL&591=gd7W>bMB4Aq)tA?B z%GWA4gWk*yWAirmJWu=kQA#(gKkY*6tfd?Md*W=rrtr)Z`uAMuF@CUwG9llx2oGT+b z4sX%QMa<`No?XYYzp|P$vPL6K&dZ+A3Uz=TF4Z~7-d1ZY6{vanvs5GxG~^U_X%E`R z-imbVC@WYlsfV!+bgvQ40cTi^rw9jd_- zNtE0P9eL_5_`*G0w;?57OWV~MDnYyJaBpk4MrZiN z1HAm(o$DUzx`Vs#2$GeOZGEJxT0El!Qk~E3;2#el%{>UOd6erB{(p#X?qLM(q`q#n z+F$foJcB+l290HG&|IEJ$9Rl;wWK$P+f)pkup~WkgzF>AcBa3B(4n40a`aLc=|QV{ zVpmZc8^kyL8KvQrq^;={ELU&hYj}^pucI4{giq?5?1HSQZS7`wcpJv89V21?deGW_ zXj1(c+lP@r?TJ?Z;k4B2ML6tqt~aquyobf+O{CXZSh8LV^}NL|FJt?9K3JC?hY#x& z(QbDqE$>WeQA?Y`6EnH@bxNCp-D)f|>KHsv`4jm38WQnG!SA~mU&;H}#@^=MskHw^ z`ecvZ!I$zOcfHOtLuqTbFt*x<9%F4hO)K8un#TX*8Kr(0bcM2^Zf7UiOf-!uI@#xMN#I|<~Bc;UBjP+TcwQ@84aW+OUF3*Lwk74u&g|X|& zlMjYfr5*7uuDcmwN4x_ge?28AEht;+{jR~9t-=aYZpw@|ZZp*NCn%>9!hYn|6L9U! zaR019l2QUtzEdj8&)O&-_GwMlU=3F9)$H56@VV3MB4!W1&-8=4Zkeo`=$n!rn0g`@&GJ!BEJaT#xYTjxFR7D6ig=yP@b>M|wh$pXBb* zT*IKa@|2sQ+4a)uX}R=@v`|_kEzSFu(AYlsKp?!~&&2uq8$mjA!%rS-AH)TQ<&aE79rcyn9}M{N2So4g6TzR&NL5K zfwVZ^)#cu{aJdI*lh=dvrxTW`mONLNr|ME>BWi3w8}4DOp5oF&^elhHzc_00&=-)I z#_{fP_}WAC-|@YZC%Q9g!x^<#;azXRAr`>pzJ#YNWo3wnd5!0uWd@!Iv!$1847^?6 z%s^)D5uO*hqi5p>7j8A@tjw?=$aQ*x-U|GD67^^g ze2ZrnBSW|zzYFq#vYc|C{v7>W@6fIf`1~<3{G_eHJ-`E^-C3a}i$U*ok%7*|pf!6`hR4i@R|1TOc4ZnN{ff`i@*&k@l;EG zy%*a02vl|mRBr&6-i=3~O7}w%?}G+C3~lVgcaK4b_0@Lg3AO$Dv`gI}Kkd4NK9-|~ zR{U}w_YZ>FkAhPShgRw#7yyMG!vET_2Esl1^UiWQL&;jw-b$2Ij9yiz{hi<-L!qKm zq0D+DCcxc>1nZYP?_qd>Wef?WKgpd>P?&I~?}=Qkw+sr@t5G7WArjXR&C<(By*cf1UrSd=VJzQBXBJXy;Bi}|}US(9u_ ze#ft}0)NUR?t3u&twZ; znor?H@}?Ik=V@vmM?2oaa=#2@%x17LJGk%XfO(Nq^$-0Y#$9?zX5j&v#`~w}t>ZGB z_qOL5USqh%QR+lmGo4nw4(A(1&mIkT4yMh|QO2v3GMj5ABc%Ul3}p>wWFBI6+A<$a zkVmfN)tq&7C*yoh=8%_<57$eSKZP3PgOeFaEu0g0C%$4lJsQG{-p0J>Dbru39)2^g zmPjM5`P+tayRsf0XWWPJa`knmemyn4dGgj6J1&xmUhUptkWuIcZ*&N<*S=$jk1Imx2F86)l>cUA9nPQP=ZgP1=>vA+rP8t zj|7eD5IcJl+RZ%Z!ZawL{#rf5FY!rwF&%0#o8MmJo96-@eKJV-uRww3Q{qxy3!y}M zfoE{{bpC4dpN-_NRIl_tHIy_1YV{G%%;DZQppp7@K0u$^0;SmvjrjxJQ4jC?JgJ`Z z7Bo^>UmEvmXt^})YkIN-8n=L7r$Wj5VyEu}*XszUY907Ub99Wmp~)lQeXr80H)z9i zQ0l?(&0+NJW!fljoEUhpoMIGodo=W1PBD(_1%7>%9=}SvC&RY~!Ef5aUuwY5>cFkq z!jm7NEXPT&g8h7jyWgO;*Ln96qxdx3;3-DRS|33(Ye(Cvr)AP&aOx}gzZ$%%H5~0e zxKO;h;9I#Fj#v|pUMelYt1R#9@!XAYx{lo0BX}jcQkooV0QFC!&e^ndJgw5rVaVc@-2r&kAlT^D}d zmJ!vr(k5{BHnc!*QxAI6i@Iz}H~cxRd9oU)zp^~1u33W?H>MZY^Qy`AIHyQT5fOL3dY=R}WmxO8N|5{0$o6&q#7x*$>(Ven#$F7uJ`4 z8Z9xa!|#8>1&_kh4#Eqg{rhh?qSE0pbj3{AGPIp!Lk>;hpBaKhPb-)wa}3cNXosS9r~EZ@OLop2SMxl1i4*J zNz9R&O+V<&<4}DOr}y)#{A37pXEfC6WvJjBeCZ$acNU+X<$FEUcOiM-2F19Kr}|Lp z=%8WD47$gQP}m93`7zL5dFNw1(Vr5Zfga9*TYSy69J)WB5+_r~IG!HNUA?Hi3*~kU z*KKgy-jr?I`ttm6XtR`C8Y)E=fu^6}F7Cc5j7{`@)ra3}3suk5cP%>iL0UMB`p41! zX9G7AE2s8w3)Hbb6i_SO)lkW1(B3=fljyeIwB~v!YAK|Z9L!cmW-2$MU75SuaaT9S z>OSu2#50YVnd*V^Mjw^9g~9Z`Cp^6abzB2SuR!??q1rdl+S+_BgX~cdtwTS_dCa|- zK7Hz1(reR)Yms-frz+)Kz@=@!0Q0OLq9*m#gre7{EzP+apw}u_6%T(e=RUnj7ld}7 zVzs&6^zBwcwh%3N54{_}3J_hP9<9ISUdBUThniSDS}c<78eZBKn(|5OeidqM0&lsE zerwn5%S=pQUPULoi}v_2TIDN@aUaH~H9ZhzU7s2|!q2oTJP=k+XXfNy#!qXvJg^O8 zB=_k?iT&Zia_iB|({NU-Yt)rGkd~_N-^rZn&$)@GZsK|QXKTh(9@;j1Bktfnc=}M* z$;7j5dkd-H1=c_>>c5HJ$^S%emSEf(^V}V@@2)UYbr|2v8S$LKmg8t&!)oeCd$m`{ zgY^krkG-QY{cFWXg95jlFTnlKY}kz31Sa}kfB&Ab#ep#<|N_WJT51M6M+7pk%q8YQkm>hmQ$ zdkx%r2@<{5MQyNa(K@w69e`(VhCY3XmhugB>kp{Y5j4?#(6b-lm2W^{pF*=70bh6> z3OJV%7r{k8M0eF=&_0xmiL4yIl53AmW|JRkVTX!z{FAO+ltF4-7u zvIX3vE!T}`hb<_%75t?g{N;99GJw9wv9&F}#ATGjFiNn*;j~q~@^+q7C%u+(Zsv0j zYSkjErmiJ+G&N79?=!ik)9dkkBfoiyUmed$d_RwQTa8?`9a(D&wgYvnUDyYH37Vj? znAhiLdCbr7BDvCH#!jtHOy5H0dlmdhOyCOE!G>>xcv`bzY-tfdwE7}3A! z_0BL)U(ri(D1u*4DNA#&tN7T!{yA?X39LqTqe-{9LN=!(XY>d3ow=_d+_XKN2`|0 zT*4>qT}mG3p?RMQJ{(a9d7voLmy%pX;Y|hLI2XeC^e|gSUZ{>1Y@<)ao3()M>gkU5 zxQ=KpHIZAy;>#^X^6PcULMf%;JPn}HBLC!>?Vy-7`0i@vO+2#^H?^RT(md_ORrsW4 zBd-$Wa!=4^J3y(W^S4q;@4zX>23bSBZV2CqGVBVK?g3wVf^S504~KVXFI7js1%4qi zMGLKneC_591HIPv*af-f(X%?>O!(M)aI~4oJfaK-1>R*V?uWMxf*TE@er1zB@RXi# z1#Q{g_$#{o0eD##I8|rpct=_vG4I-{Z=(%u88y-3QO*%peg}7o2bV8)4xH$A?r9io z9c3ADy`r@k3vu?^K;?nTEftunV$7NN61}pQbIJL0W63PY=Q50HWyZ1+d_*gV9K8nI zNQ9q~$HhV3D8kc~7W@+Ib_NYf+MZi(=HEKl>!RW;Z)<1J|Fd z{FFUdh+j+7stVMhj3TEiP3wy>zha(TfjL-FSy@kK*i~L9Sta^sk5hti4dPPdX_;9; zVrlgC|Hled0?N*c6%*)s%n)8;ZH@#fTg0zxKYFn*;6A;q;saghddtN-WM<{(qdktO zczTf;qIHbHNO(pcW05f8j;#J@C91;o+0nXy=g*^l{l5PN6w7Izw1vvx+ zdtI1XsxtD;f^HviGdJ>HU$zpU@ibxwl=v$#Q&ss}nUPbjYsE^ropr0w89r5I183nN*?4Hae`v|&9f2R+DIj~<&Al&QzQDLoUd+&p|TB0>3E zS*8*F6A5-fSewOYUt@l4$0}DwtWBvkxT>*ks?avq*o9%NMU3b*GwQ8jSijd$QXziL z7<}U!psH$IA3>{?X7mOh+isO^$1Lc4=dYDhbzAg2e8$0 ze*M`|HdsV2e77Kc8!f+YbHAR;vB(-v1gS@V!6V2-1CU;{cfS}ois*l%3BILO3y|BM z=YHcRMk38kr3LzCjUAXxJCyH+Bik5lF$f9f8Sa?FbK7WpCT2T7yXFEgV81iw&Vm-4 zWkE_<4KM$R*JiE_aJ5y;juPn->Q*L*SO>>kkBtcW_5A&rF6ub#jDH=) zX!XLH&<**n5B&Lg%2~*2(ht8b$X>=0%;MYk898V4z0kfF7@HAT6!gjuz$4QS`L#Dz z3*$YWU>;^s%6IhL-u=w@h!a>wxvO~hCA}1V@D=52c~F{P#iwPA{kuVKo<%*b`1P#2 zKUwqomor1lj0xBt*4YpI`V}>-rVdxK2q*ncJ6X|Qn<)2lW@I{T8A-p48h(Y9^fkX} zt3SayKMs{U&2{Q5l~yj?KZ{&&jl=2)sRe~AFyi8z3mWG@S?z_iUm4+iajd|Gurs{bHq_zOF7^3yi%J8i+=*2$N<$&Y1tWghIlFw zqf(4hP$`iRY6K8Kh>J5MOXUOn*UpHT@MB9 zz|{#l+z^^v9tu_(h|8H=$SR zn^h^f92BxL?`rXVGy2sC%37XUi-wv-sh{(E=&Q&DH_ix8JHvcr44#-{(4PZbBBk`k zWPvZnUm_naKpjnJyRmFtka_Oo(te=NzboJA^KSqh7cqGSGmx8k*2X0!RBx*sT9lI! zm~z-sv`pzBTaa?a0_jsa!VJpe=|^E@gm%fxC*}&>B#i|BW^^W4$Wzcva|RY}UzBi4%FwB!uO-lnf)I5O{W-c7*I z@Jx_=qXp`wP_DA5{tA%+!?BNud3Xjt%ezFwd`A@VretIC6F!y|*yiTr+0o0hg5TyN z3(vq?qCaFJev=RI(0qY6W>G*3Ou?@96sx!wGK&6|(R|YCsJE*>-$lEk_7iO^Jy_>Y zA+Ouor?`gGdM$t5S^MtD!B}ZVhTlZNYva={)rJ+P4K3P6t1=4BS%EEC-^v`?UX*^C z^Abr=lTj60SdCGQR<_HSFV|X(g^UuKJ0hZBl`FND1c_Qr3;-s%sgsDS}t)wV^co!AxKS-* z`n>fBt)T7e=!5$HCf+ZmRB;vK;bLMdva*P^Pvhz~X>WM9` z9agbA_-jg}Mbm=mW%!8l;WH|VSEUk&ji%Vk+EC;D)cy$181=6_AdW)6*em>1V(cHV zfxReGi-&9BX~wEQ@>O@*-tFwuLy^af^}2_aHVS^Cl6b&M;Nhx9ORM1#tA>k z@Il$)-l5$4@eH-657lXBxwHazHN;wY19#kvea^_@ev~{c$UMr25wS9w7K{ir_F?24 z)vomSR-U^K8)Hp8Ty+?shS&v-a2mkKm}}+n(BeCpnRa1@Ix{~5DQ6V3@4U}v#`PYF zepS9*%8r=NN?gpl&%Uv+p9y1!~A9PEjEkw$zJ*r!YX;On%(`v+3i(jN0 z4WWa2k?(-EMm${)ID$Uu$=KxQVUhnNTpxq}nvK7EEY#I#MLpotv2V=cuDAI68uWcS z{+k)RUI{P#|Ni;`&wrWx2xr)W=lxJ}oEXZ3$!`4pTlsbcd|(;=obQqiaF2~}ku}`8 z7O(#I_<24F{($jtoWWdL_NUU0<=neBIZURIzw!JVjcH8Y9PVDibG!KERFYE5zT^+; z+(3z|LiFZZ%HNv&LM!$pJNe}skZiN@2MvNZ>Vq+Q)d_&K5J)=t)x2(NZ9C-Ygusq5Aou{$lE5rh%5!;hL!n$7&E{5b*&u`CVUv z_LxF}V-)AT5^^rMiI;Lusle^@q$xj|)5aJ9F#*|;sf^)}+lb5**?ATBUjgqa3s*Gi z!Zj&A;@Y$Pxe=Vx)mrZCeflo7ddQ)x(=xH6EtxlS=qPWCSkZ^0Yj zS$nEdi}J1BG;L{S*-={8kJB~COAj#m$`jE}*B7}%?~&FBaiGm;o$`HW>JXtBu|1+H zjI7d|qkT~RtlTeGRTk79s%J9u} zU@l^Ob8{I>qIT?9Yq87EcY1NOmi~oQtF_DUbaR0~|o|9Zl;d;GyK#t{0wG5qrWg-|*z{`z&kphUI! z4g6{bs#)mSBcR3)L2G+JxkZdW9;mXhbz|Wf=AU{haA7&b(@<48Nkp>GMCK4NG8?`t z{>@leV>HE?42747PuFMk7+gg@*aQCcFfU^|jnCAFBzoW`sQjaFYa?^b4G^_@txEGK zTmO`vs#gNyL+Rylo{zji^q=vwo#84S_}d+hFp+2MsnlHAL|erx^h5i;*!+kjG@q6z zmzl^Gw%<$)AMo5)jJUZ4L>8FuN{xLd^Qz6s_>g0K(xb78(fx=glsiPAenyR2PUg~! zcPUjAymF6u7d{TZizNJ&`7`!Ko&H}|l2$#lBj~^R3~uxl^Wuz)fnUKlVi!dYzDNIG zWL(EE7f;cHq44$ojKs*m)u&LG)(B%qjH|T1dGvY)vduW|9>OzYgKYT@zZjvS59kA0 zr^GXdl_3X|BN~Gy;zrcWm>?634!rp}o)-J6Sj!*KNo)+VG#Q*E3*LzZ!ov5uqXk8f% zer;q>8jhbnL~ffM|s%31^W*s&$s8 zWm&M*NDGXTEJd5O_*7=Tj55v28a7gS8&q~X^mrfZ=|A$BuO zRx3fubEJ=J4>PT|Rn$j4sW9P4{@<2fLt1f3Y?*A+O5Q)LZ3nIcet^ z_>pmUVt-E&SE=vN(KFWXV#eqwzeW4ad5nv(#b&<~1#v5FX->b(G6V8cqiT%SP`0QA zU)DOOT`NY26rt|pa5weSU)fnkm1U%UHSjY~yaVjrBkU~^$=ZGNejjF+X*rDE9@nz| z&M4PhPFu9#7SbEd`kTm)o{Zqx@= zEl6edOV6x(LE3Vf`PSQE9N-Sda0e|>LNEd`=9DxJY7^rt(nuRu4pzw_YBv&2G`#xv zBIxrHF0lejpyv8C-r)5K-^VDt9h9(xr`GXVzBC`&J{?{rI%H9JRvduwSe7X^L4Kn( zKuq2@{HBI&t3)n*68gK8a+bkk^oGbGjiC^~A}>ZSu=#{UV;9K|957PC^PWYGV*`g<5b#PDbR1Sbz_?w28a}@7E_Y z8g6<&7{#`r6q}>B#`p@o4TF#xhR{ZBCB~e|Hsvg*w_BJ?`H-@ov9b17Y{PdvZO)S)>GhxNbR|=Fy#6j@ zKfPbk6ofR))biKOD!F%X~5jd-nRh5{G%r&l0Pi|T0pg!_zsIv&q z8a=;{arle2Yk?L$QI>v|fUd+i)isQxSeNhEyE`fAB3dS0y_^Drp`?Luc;hyN})^D!$PDHlWdHtIrSB$(kKlHf-Z4&)057*9VWVm)gy}Vi#wXvHI zMCzn;QJC4N#aM_Rl;(=a>kN0i0Xk&-T@`ww^;18&5{I0!G%w@w^(|b(NSgapn?n!y zt(vZg2$7YyLCu;o)^bJdn&J)Qt2ya`$Q=2F*%f0x1*5<8Uo;F7NVJ%Xnp3ZI6dVf? zZ-u#B9qNy@;o)83^`np_UIJzR|0oT!OSSo*O;|6E7(L@a)aOJ$h)pm{sygSbwAI|K zX0f;<$OaKz@(6N?*6C4P=6~u&nWArvFB36em;T+1w9=Cv8&&ZXc7x}Fb$lYS%~&Lx zUeNiD+|w4Ws=leES4^e+qcPVtTzdQ+$F_`qMEeh>EMwos(=THOCL`5oS=WzbS$fyo z&?6E5Rhd(Bx9km+Nz0KDsCk&{D;Yb-tPpGR0%-SP)`}5lhxy$dCel@WhccgdVlx;x z%dQ&NWc0;p*;RvE!s^`?_`E#yFgwDW6vk#72kcxil$i67>%mgGJ_^@d1FbSz%DjCOp_^tpo{jD>kA5zpb>C6aHt2uM zP^^w?%=cGkY3q-)&K@j)3afF7gw&!f{%;hzkk(xFu6Jqm5}qwTP%YwOBRSJ@i}NA?{5XESBinh%0FqqoNjM zOqkhFtjiIKp6@SMG4f3HyYKkcF;#bq+3n2SEb>nDsVh?ph1}YR&$YB)EZ@iQemTE5 z#u@Z%Dc^5re2+7du8%|XY$f+OhUO|%tNxT8Nwtrm=ZSvPkEv8HqRtFoqEhs{8m(on zyco;u|{Dy*yDXnPVQIc08RtIhRM2(EODJIz#} z%(RsM*HV%*CuY+XE!OWmR)u~mbNMLay9dqZQc;uW>C7l#W&`6H%x$$l(CFNhSRGn(15{LcuIEYwnKFD4dYmEP4UF$|B>!POy2_1e zjcff^TI}UKYFUYYBXU3~>vu+7T}7+W`XFf>VZC2`wlDG;>21_U&Ad?>Zf157`>PIf zA^kr=z2Zhi0+<=RDD$EmE03xHeT|;*m`6qnX#HT(G&-Ool;0TV4!oD=HRgWv?8+(g zGT%9Z)VqrnZ%zR7Gn=0{O)p_|n?aA|dVSC{d%`<9!AaDz&BiAM9}Hi(ABx==%9;zV z?LKw&{|k~-Ny012LS}Q+uV*G5b$sOrbMIAREtIC0W|p&lTFXgI2wE7a(uUVedQcJ>d<$d*7Jw~GGoz<&a zmNvPAM7inT?uO)W=UIvFO4hL&nVD-XJL*Mk-^xb+mDl>_rT_mbBLD?~O>Qtn|xK%So9P z!knn}$2{~`a-RqS^KHlcrlKC?4B``Vu!=HLqg3HEy@+VuJhV(7v3Zz^GT!Ess1^2w zmUp$rmaI{&BVtslbB|doEFoqu%gOVFnX78dp1ulkE+Pfn2B}IZ(beLv5<6;4invC# z;!=!NR^*6dLGswcxR|w0xm-lClB_FUEQU7egN(6wIaj!pTsr;>)F@h)f8!pho>mV> zR64Vd@r!m)qXnecQ8qBXzarMI*tUb67?*^b*>75myZ9KG* z&}x#4;blJrYGgK{Xa`phokI;VKk$TLog4zc?#0yuyKhfQH1EkkIQU>{(r#^x_gJ{O zIddm)jpvi!yomH6cb)hDt^J>m*zg1VkIrWh%uJ?I>Et5qmP zTxqLd4RL*nLe|sdUD}P*G}KBevPO%sFO-nQeuzod=Hglu_oU>NhxJ;9dyS91ku@*I z%Y0SZais-jMw0@?J$Qy^w=+M=LHbVg`-*VX)~w&OO;Y)q>8=^ayZ zs@e)|GMU)V@-y>wnep4a6lS=$-!UuiDfX1w=kM@M;|a{1pNVJ8m}(@xct26D+Ih4F zo6*eC)AyupO36T-D(cGOm81`9kkxosgnDz*mSfD8mg?v?5bJz`dZo5nX|}LSwYN!$ zq&OEc8b&FZnNQ1f@z7g$y!a?{rxt)3%hT23O7JNsmhJtNWh90@mvr+SLUG6Vwa!y;=;1gYmr&n-lU&$2f2iF*c@y2u>k*Tv(}P%HLse`F0~)~ zT8!V68q6f8EwvgH()?>zvO3IZB}KIEZ1h7rf-6qC9J7Pe3Tw6&>%zDidv+9d>8j1dB_8rd#i57YhdX7+GdZ3*^+iD)J0$d{d zucU+;p%2$lN5qNU1^4VknO%`=j88Mh@G5$D3AHP!9SUpvD1C`D;q2?rH11F-L;PRN zPG{ynExvLISA?S9+nSe}v@=J%p6fy+ta3DDE3j%J-nV)6fy6 z-8XsV%GMmZ|iN!m;yyN3-Fti zVTO(``D?!YSzK?xhm0A2jn5wjKD3NhuBX3dhT2JAcX92Y1~Y7^7peD(|J}pxOc+yh z4o7`1MreqIl}78+{hM7Yo-%9LQ|_jiiO$#}qgu_RSR|~5?96Y>HLPCbUf0^Bjqnf@ z#uCgvD@9cXG~a zU5B-wi{70VWJP7sY^-%XI?-h?iZO~@+;UUsW=)WJ+u5`Hr~ht%E7 zW|79n=qSCa#VAKvUH`HAlqG68%|{zVZmRja(@RjswP<(ugeaW5X}NpmT$EB4#y@6x z)o-j!?F{6iOg*y3eR+vuE=0@ap(5uI)WS$B@u`DEbiMRJ40iNrEAgm<=-pEmkD7v9 zITJH#6s575G16c+t5S(R`nElpLCL}Vi&_nB)p7n;I>}Cn=4ZZ~J(G`?8D;ek6mM(L z0Hh*fHMLJ{q5K1s)(84ok9MjP78NY)}mCO|>og{qpVWIJnDsdN|b#JZX(aSpnH z@hxH%%nmM{_S}rw&|b5O7~8DWtwyjg$k)b5crucipF|`MLBby#bO$p&scV=s*C<%+ zgi7CLO%ju$rBaz&)Pg8jC35qU_{#_I%4m04AL#fmP)T z1C>Se0qkZ(mQ$v@!~F63-u_^0q&}__d83{`rFm_0W=Y*f32KIVQp6;i)AukVDmT#< zC1u^rsOu53E=!W8>krWeVmqSkO?}`f^KITTJ-|^@R!cMTN(-O1X64ZwP+XDyN)}lI zebXzf<|j}4gV!$lVtzy#!y3|(lOms-^SbJviC&s>cEAt(xw$pP1RHP%)w=}kn)7~?P%H5gXuYU z--mnk)ta-*hajG($k#F9q}uWd>SBIe9;VxCtyUkRv{h_-}X_zyKHE1U{4SAM=X z232dQtvDA|t`E`cB$wyiN#U*zwA^TsnozoYv{H#MX6N%Rt@iSW)2s>kv{}{l>&w^d zX)b7(ywZ4K?PW%rWWp!+C-ZE^RU_YxsXIam=3majrTUmV>r~? z^-3uTC{LMNUAwL}-O`M7Ry-D3+TG>m4*&10?X)C!G(r-Lxkt4{6%Kv3C+fMLm}Z`r z+tHWITz?M|Ko2g@QM?C9K)uZf94~WI8WCokR||NqrJB>aD{_Om*UaN)Rvj~^iaLt+ zU{8?ICuo$5*~j$eO~RKarg$D%Qs#k8o(nR1GWR@6eXSTt@kjbYTO((5rUos^kB4&2 z)7p<(p2D*@4Se=AJf7xNn+|4sDqg}#)bk|w7=>=DdUAQXk21BnM`MmS^OhLpR)>93 zf{|BZF{`$j?)!yUdGnr%Vit4!Q1Ip&I~4P>Iwl?Hxo69nQ%q~K)^)wr;?rC5T^r;g z{K0jM|-X^hgg8PFVwD;JdD)N#SE+I=V#~myXXOBDWzZS648Pz zk~rE!^>ORDQf6>v$2EE(b1bck@oZwS)U~gn4f=u2lcVKFJCe2uGb|~EiPCM#9oKW8 zc;C{Ls`RJCqC~IsqW#@Zr`YFet}(N?R-*i@C^1@1d0K3~NHELL5^j&OK||%pNa2DpxiZ=3Dl$eyr6<7M?!gi7cM35^arQON`MlGm81I z#-hQ_gnk$ctRc2IP5EHB4SM6LI>Kn9mKJ8RqQ%+OUQkp$N zdD70!^ix#OD$4tY*9uBA7mMQ|+G-6g^Xv`t3#jF2tumTWOghZV-Ss>& z(b;;a&B7k3zw(iCyCdYdn-50WZyP1*g||Fougt$UgUhHT5xH}i%X5;mIHU!%EXJGd zr~SXsBTwy{#|Ro%F2?z5YK=H5WsoQviRoH_WTS`H)#2KRc}|s*l#rC5wQ+k!o7NU3 zF0Bp9TVL_Z+pJvkw~b(DJc-3d&%Rl|&DQpP7z25FF-pfAQ#XhFCk&{T0uB87|q(V`(v zCPrAOk?JAUvt&KS33-WKHLF}a)k01#lE$pudT)$V(C=q_MT{>I=@jEr%&%>}WzUz4 zC(qOgRPn+XmsdK1qwOB0%=eUS=%xZ91Gk+;j z=rfBJW9{vtYLzzC1e5~J+b1S2o>8C|Pm7}w68fk9!E+~PsmUxDy&~^34_R|Kc+9b) zok$OLf|TNk0Os-4ccUj++GFhG59~hWH?8aHv{6!0H_IK`ZSFB=U7v;4>TBRFB2Vpw zmIiTTqS)+-=Tq-y1mqcNqA`~280F@orCKMn(-~EI0pp@%t%l~=JI+AKu*O8HizC%5 zb3Of$ryFsswJ6$>^}ZNW@A+ri5M13cH?RI?QQ2LBRArtKqv>y9&6tbLOgUz`74L2S zTcwgmf{bD8yXWYQz!E-yZ{vwO^%z@EY*IGY;$MY!dE$_{{LF=F9y#OkucsdEATcj| z-yn&_-01E2O)F7LUajbfeok|ym~&2l_|;*Jnny%$qUT!ZJ3hde7~4~VT@x|2twSwM z83T8kzL+T8M@x+n-L4^btNMlZw)olXj#??SEsCo&e#WzF-Fj+~=zMKv(bpkoEXw#PYk4V2Ng>KJj>;xi zGUJz0wwYbDRsRxnXt}J?lelyBAwAyuSoAktKuyN3t37DV^K#93c7f-uyKl5!Xk8Ff zEyi36rHBysjlKVe-=jsqQbnw&Umk&u8=GW|zPJ|UEH!c|hB>vwn@JUn=v!F>{a_h=^1RYdNk%D8GOxin^_h5b>-s92peG<(N6`)gZx`ZP=4< zl{&-(YX9>ZjYRz*i0n4RhqVNg-3(NAL!yjpgj}`di7akN6!1gH+aj}-HexPAW6)xR z^8hdbMwpp3|9WDB%>+0ADcaL3yAvyRJtfrR)q8tAP)K? zB|RH-g%23Tm5jJ^taZ%Oe~kHxv01JXM|nP%GN9u-k4wqVcr4}H^^EX7)~J4#4A7JV z%;I|1kP-QwE%Xz!znj&nPA0|B|K|BQ{{9)ydveadP>y`is8Z~kOW7e=S^p84BR@8t zL*IrwOxY=BJ&_X{3#zT%d=KW)5XWl7j`%mTL?w8zjdS~zHtAo~Qg|7^d*+rr!I+?! zuf(&#^av>dDtVcAL_beFPgh@#G*ldN%>3cGr&-x)S`^GCrcETG)naCPsfBXBsF#wo zQg4eqR4LH7ODUiyc$cLYdcw>~*8#hNnYA9`|4wjI5y$oOQv=TBNoK~bniJ-3 zG<44^kC}1@z+wBqSJmPzr5C)_ytiiKjrq{~!i(jd=Gl!=#iF@HG3psn%l8x(eO_iG zk5S5=*%G;D7x=H}YSGN+&c(3z=B5)ven)6g*YJFMWC;E1VmL%vh}?D*D)PS(Kq9-u zri-OA^G-zI8AaAQ@OgWtC(n2pqoZTy*B1P4+>bu`n1N6f_g(aA6m}6~)juF=dmdI2 zPqptu31Z{4-H5qvM4RlFG0n~RPGq>Krd#OMU5ukA%*Sl}=0ons^(b|B_}??i6F1UJ zr43_-ji@v7*vpJPo(vc>3u%qSX05kL|bGKon<7x8k=v^t+vV#$jstyo6DV88LIfx5U`!1<~TaG05}UaYbA223_9Jw#FSVXgy3oRx)>7$aQ zQetN6`JHlY$4V&dU(j2TCJ~ou#J$)TecSqKV@?TCRT0Z8!YD?jD`T23QQK4jRz^e$ z+6wiVi)f{Kiu75E{Qr0qv*ehOK)G7$nY>+YFUC;~LyxwYF7MHT>zcDoMi)j6)qJ38 z)G;%%5|fs^bK0XkPz-^Q(PmuV3pddYco7-cy-+8578GjEG$&WWph2YKKv?wcHNjh^o_3Q0nQqOlg96f}u>45g^Rq_Pydy5s%q{wsQYey{uvfCqoWJkGitXB_925{$ieB{kVEw#m?wADZ)M$87cn2^L8U5Sg)#9Q)Alo{3)M^ z;1w^a-lLqYmo7!t@|@4B*l(iYt_qTph-K?l^3e|{#!P8UjaNw}o-V7uP1K7hdC$0u zF|_KNTB)Qg#;z5j{CK*LzTAtToLb1wqs>i*sXS z!4c-n(>1Fx>Si-FCy4oVV-^)N+r?87L{^%uRq4#uniUeoYl!HfKQv--CX@Gs7Z<|iXw8YbLW2+pkF?zZ_}(B>S4wmM8u}HI&CADG9UU8kI?#` z!rImXDZJ}oLqy00a`jL7P$5y>SsPaZ8Yvk{Vq=c(#_(YA68J=X@I z?Iz~?6FF-JGN0BGpjFUyawV7fexqh+7CZCB$kVL#99Gl3*)bQc>qnerVV;Y*Yn9Km zJn9c?K#BThiiOdYdK*1&?lS$snUS|+4tP1Yx`Pxo#)X>i(bxy^mzGfg+HH)m*x;CD z!JMoj=*<=A`jxJm2{mGm#i6=?)bL%q5g)94tiMPLqFx{+cxOZ|m7Cv03&s5WN_+Jg zqmrx;u}j)8L_vs+i4p(eS~8-+xc7EIcf_9TqD7gwTdP;ZsKn@MHFz}?W3#mm$GvTC z95a#Eq1Gm>`73!&>K}7qn@7_%pm)?<9(rfwWoy~r=1uYRxc%%wSB3eC%`+G?Js2F!#w9EA&5e-#*~ThSYg#JQ1Ct3gk-qDZs!^?TB?>(pG$+0IH8qMM>t zXv@?K#pG#=)XJrfW)!{lDfxlXk6z+Z#8Li1`{EV-_F9QWK#C(Umu6$uiPmiGnab_0 z_@oS8i&bX?O$KINj79XG%cqnnV>E8WIGoF$X*`MYl3561kN(z6&mIq3DkPsN3(v(JKGo0WGc-oRcVx35`R z#=_a(hO?S~UWdu~j zEYCJJN(-4*5a(_u*Is5-i@9q^jYZ3mI4?0z5zAm)v^tI!w{xfnB?I$!x|&L}&Y~6_ z^MS}6BAQhyqQ^n~)cmAss$x6MYY`EhMh~lxnYmHwY6cI_({9CjF>jS8ooMlnC!?4( z^Ce<~N0X_<46nV>4Asx&VV$6;>eyaUuQwj23%`5X=m;*)h|`|kg_YQVePm3u=hS(w z+`ZHz=Ab)zT02(gHMB!Ks(5d$&lk}H^K5%>%!<{XRjkZ%?$n?HjD%6(F@LOiV2q%+ zj%UOy%1ffBULSjm8}Ph&?K|d_(A#OG=LW`JT)P%(am3{qOC!;YlNSpg&xfr|&Bk2l zugJ#C%In3D8E@h4R1;K}xs?5@XT!WUBFD5R{TWu4-cV&T@#W?y(p&l)<-{C5+Biiqoua)`$t0V3w>jIp00e>x)7G(mbP8EB4{I<-`7GcoJ3 z@%wGK$CD(D4>jV?EJ0&$)M4jdYGaDlwW0d_CcEE3}EG<0FhjOs1 z+)4mW<5po-4Qe{y6*WwkV0-{@tMbYjp{c%3jIptWMvs~)KB70wRi{1U3+7R4 zk}-W+0rcL;;m!Oaw#DqXB9NEz%U<@aE6r#vSA{a$Zu-2DE23XK_s3|*_jpEaJbHqZ zntr8?=15pFigZwIG)-Iy=W*txJcRJ@)GIPyh%8H1UDAS94v9Edu%{?P} zT=dQN%%@Q{<|Wp`p-p0B$b$1C--wR%Yy%^UJgMDQ8>1jiHzMLs##Rf75kC62L;@*= z#LR%64)r=^n~P8@k9@?H6j3#1$rA%(rXNcXNn@_xX*?z3$y47yr5C?2ml4}xhDD`P zb7F|=a&$cVAZ8CYV}N>=F%R+x^+Gj!?NOpl9KGnFP=|0XMJ4O=G3TGCPIY}VxU~pc zpAnMf+0o)8%+sS^P3x*0P#ed;P-U&5=lsn2O)g+pRSz`J$ZaokeyG2D#SCpmVYfiu zHTTQ8li!T?*Vfz|$-}&wM%0*F+nifki=%E`mv7BI+XZRlL3HSQkbqk7lr&z=QhMz9 zZ)RHY6d$83)WbwIXxY9NX+sG}i+n5YF>}6WqYvTl?bz)-S5ME07Q^b)ZFIX?Nj)<} zox=EIb!PdNo*4ZJo^U5tKm>p`|CnpVv+U}Im+>9uA=4{tw1HZvUV5eY6F~+kKuPi& zxsOqbF=j<+LcO>Ey_Y7N5nL~`c!}t@H&3`&9&PGMhQ*=k*@Lx74K~__^yM2nS{yE6 z6uG%luj5hzEe}u8Pof<~9F6v8V>RRz=JFFE>Mt=nm%6`vNNGuwvH5kRLKnhmKPxk-t$8VhsbPy;if2)3@wN{0w%Ir1|IEqsFLxQoVZ^*E zS!B4@mg2k$a)){CjDr-f5@U>F-nXkm8Lo^gxKnPH5k2@oSg+d6l-6Pf!>Ap`lM&Bh z*tPW;4dD2jO)7fU)jY*?DSMf1Q0$RyFfLR?yB2DrS46xjiz%^)V<^CQY88(sNsA;@ zyN0^p)vjbas`#wb)nYuhOs?AuUfYLd<}oJgM#Z5c^+xl85Ii zGU}fHtEa0Wt3~AP<HXiLt3wk-L%@DBvRc+Vv*CJZNoF-ayw9t#^pM|94 z={!aW8Fgf|y=Ty^g}=nojVMqXHjdkvIQQp4xR_e;k8paU7_<+W&EE(S&p9?{s*yz> z1PM$W?JCAV&TRg@^O(((d@^EERO(vVEFw{fL<#V3TKhH6#P}gK`+1bPhFP#~ac|}w zj&Uu!8F6DiW5&-bptaI}tx-{Kbv+ri?mp4(CU#MoN3@R;y_$#8j=ZIR(T2Xi%4b9Z~h2b=PP;_Ws~h;G`(vLV`YW`(VXsA zSG=q3Z)#u1v-9Boo?_(L(Hog(V+NGUqZZ=+&&AzZjI_sVeNOnzxC8l372cU^QanYR zJyCX1-p)ilYQRQ;o@SjY@97yb4pG`7)=7+^`&8{b`p1lYk2xuoGNVo74CAzwnK#pv zCs%1hRnt`_uuNmTVrIp)^xKnh#4ed(K<|dF&_1dzBF@qHare6TK%=faSH%pm(V{8G zlm==^_LN&&u27u?pceGh;%%`NCQdHVW`l6L5u4QR{)T+hEnyny4v6^SLAZ<~*RoYgs zmJd1SF)yncS-HR`JPStObv*Y)JzzgA)}CLKdtwe;5eW5I-6dHAMm6b=Q1>;eN?UZa z$BJw#MVWdj^${r1=?T_0Dh@nK_G%V;crqhB)K_IZnW#Wx)1+5w=n)U)snGwhB8)LL zvb6!cL>z&q4w(nFJ!9tSLB+Tu`dZ8lph_ z?h5z8At;L(NsY`~3RRW%NK?<*zm+x2<0CZ@H>lm)+*8rRrk-F7gV`kX2pi=sy0;0^ zv-ycV8OPba5sqz!9<62OJu%0k=Ti2^e)tS=KAv*v3C4}sMdoOVnGChDX{9i>ygoB2 zr#H&WGeBKiB0;3v=C4(zuLC6$g`+pjcIk<74xFJFfqfP2R^p5Kh|TAuAQX*g1121|zo&^>EMz4p| zM*F;)wwd>hwlMpgR%v4=ly&uu7=dAYg&y6F+$qjLq^K*+vDTX_@0NaQwKzygF)}os z6d3K-B2l!YMSWVE`7c~b=0_x){EJ!e%!Ogu;>gqB1V7x6Jcq-X8rv?pyhhcn?>lSo}PEIzqeD#h1Y=-$9c3gw?OU z>F!WM@DypY(-}cztdA1cF?OOkULq1%=~cgtm-rIVGupS@SIXIP94%nV=ju6Ts){F_ zo5jX`qD{F-kkO=go_1;mQ>mI%Uh1vSrZ#&9hV4F6k?Cm0#4W2{xQnP@lkj7mL5@ni#I(Uob8j1uh; zPcfcCS=te`IT}BtWyh1rjed1cxEH1MyJ)>pt)6ThbH02+kKd;>V}s068qZu%LlIkL zTlHd@Ez}&-B3P{X6KXKl)_65DN-hg?yp`3UEky}6`XroVxkt=Rp+!>Lidc5@6zye= zM4yLLQJb&+3i+3qPxBcR<Xav%BOOT2Hj7Yx^!uo1*-u&%|>T|35>O`E|5QtMlr26T7bM zLq4f5G=JF7_23WY+4bb(yRi9mg`b$~Kb{4vg(K#s^L$0Knww`YMs0eAtd?;{-Pk5& zORY(sjU%E&E@LcD%ypw3qCEUgBx?gGgfdgK4w<)De5MwwP672Hmy&{9NssMo3v~N< zzT>q#sdS|LDUv@^KqaW{n9nQbe^H9|3}r2Kp6S>tM7VULf5yu;r&dpZwC&O+^&(~5 zc(R0e%L|yriagyOOlVL1dY*;X7vEpM;QcetwVC-vJm^uml?8~(-U#UqEkEY&N0+iVchlQjFWjbOS4v$L#}2V^@|vb-7@r5eMPj9F-Z}D zay9kTr%Z9EjTldB@th(fgB{(N3&>S}c^C~XKh>$hh--Cz(Sz|^s{*W7k*@IsBYi<4 zfz(aK1((k_4H-XPm3l8@yrX?Y zf7=eI^;&3%QI?*_s|Pz~sFj|JLC;TX%hED)e7Ww7_Llhn6I2tumnDwdEQ`D^48T4)%PvA+yQZ5l7UY;xv zv&o6HQnOcTQ>NGNu#R_1Sn4KX=ZtDtNu46-b|D*irnr_eEs0sMKFZh4k7YDy)C|q! zpl?$-Bi?03ki*m=k5Eg{GGIi8cCHohs%ZZ)tAVmv%=;PRmz2%abpGW2Rq(Y1a3XC& zuQLPsr}X+nFOR5IPo;>bM;L*sgr%)VE;cvl9A+C4uNX7Mnw`aY_?&y^@SNT zJ0svjMu7wAOax0)P8YbHh?M*IJcyX_ao~kK=kN)x|D)*|;N(c3cDu)3CmY+geX(sD z7hi1K&Lz3nwrzWDjeFYt)tmkP>ECX4cV?RP7M^;l3QbU60Suy@V6TsYbw_g+?!ty9 z6{0>P2(?0$;`x37nn8R7GAj9X;yWS3vlW=0{{Z7;0!-lR3twa581w$HKi32IWG!rH z`toUzwU=b6AO76ue7+9inV?RJ$m2%V z66NSoO$(Z?bQu0e{w?Y%O>Aop+7Cr$|3iZi2OLRRzBIgspHWPS5Gd3u z9kD6%tM^=Bn~+z45CoLBMpHWTCwL*|g8^1oN!TyST%eBhXm%X3O@sbFB1G0NU$5j( z|3UG8J(BmCmnzg-1KIiE@Ez5wpzmnL&seZ^sOvAvF4YIEhcsq>uP|iYP%Z~uV>`Gq zR9n##?oSQ)dl)=Xgf*eQ-T7Hk6fq)XB@^zY5v~uhTF~cuf`5S~=c0<1R&dX1!1)&k z9YTW)Al?x2-_e8;^yJap_ph)Ty&y3*uwnn30gLWD;zpt<^%tz-JFp@V8ya=-K@+^t z>@L*92VuOZ+jkOZ6og(Q-G;0LV$PvDOEky*B6zGQXMO_Sji#J`hvT7XCx}h+1mrk> z0@glQFK8|p>Oy`Qj`tka2Z}|I%|d89ir?}XS4iW%hW#Q>81*dN^M~oZAG}^PyXz9H zDipz>*bimC^SiyEPaux_*FVyo-&Ys)Sw!mqDB(iUibWqu6w4$dyWLJ(;)Gu%7G$jF~yiRNxZ!}CQsV}#q~_q9f-r}{_p zq1;aXoDGycL;4=|_&?G-3M<~aDVrZ28LMSXku2B@7UwMhFbQGL9s?$PQQq&U$*=5xE z8CgbzdLuqyz6C-2I-~aHjh?kE3Ax0@WBZS4E zqoS3HPqU;Z{ z|GDsK)XNC*nvjM=F%R;9kWNGls{H;{sAm=GcZt}Bs4G62oqO^Br51S_XhS`=QC2hp zt`y;JXqLMZt^q|$sCy*p5tiR^3P~NRTS1u;gnuH&DXPsuM@D%dgn}cxin@59D?pij zAJB`VKw}I6ZO{ueCCX(ZR*V^Z6(r-Y{=}wxAzQ!UPlW=iJ;;wx zZ^BV?KvoKXj;aKj25FISxW}lI2f}Dk1rY~+5@M4g6dz?!5tfK@tH`rQ+7``mL_O$H zHz9<6BO8sb;XO$H|0ZRiTn&2qD3U^PAc_R@F-g?Xy#@HP`7y^}&_^9XimHGlqF%sA zUmygt5NOx@UNxQJf7FWxbzDW*5~>?Vl8O4iBWw{xk*I48vPcMDM^$Yo*NwUyquQ~? z@H#?ZQI`>cP#zp{w+g{IwFUh=^A7_N%{rX|wrCXG z|F$5xsKycDf@ta}nk7WzGu*2Iz?Pf{=Q0mA)JI?(?6onR2dWm0 zgmXq%YyJPf7pT$?*&>uTZ3a=waQNI3s0Z8*y_ir<;86H%BY3JsVKwFVnM4c@<Tu4_T z&4qe+u^=~S23Y++5{u>oAr1#Zo00UR`4=dEf%FcFpV2c$-U8x5BHN8vCWsY}SSKjn zM|~&lpeImuYkpN!E_f-W;d=ACA&dhXI|eK}suD#u7tPW`U9He`HBjOz0`lII&_XyQjBQ2jl?F(g{(Y-*}Lw>hnlr2O| zxJs~R)WZ^S*z-Gt{;yxuUm*SYy-ZrebF2W@ilP=2x99iW%K|AyK0M+fpv*`ExbLX@ zRDby17OoP-WoT9dx(mohM|^t36Ggr>V$dU`0pX7bam=4ZhdMB!OeA6}|A3#+To{y< zM!o{-yVVi&Ne{StDC2^>p0;paRsQG}@sIER5Uw9pWg(XJF|f?2cQEo+QSCRXq`C$^ zGRm}~+%RI$qe+;k*CeWm-}VqBv-J73VOobybZM3e9(!#L8G8P#|ZU8Oc_*PgfjAo=ZP|~h_O^0 zt_3kpnu25_KYBQ5_XWUDN3*Sl!Cwo3CP(Z>gkGa8#Q!=;T0s8u=N6(_BghUQZ@nMn znOedML|ws~{n6G904r$>$3T;{P`@F>Ye7tJl<~;{%Zz;0e5~awJV(T4cmU52%|Dn4 zUCYo^+_m7bqKQq2;rQ{7El-2<4}-nrv#5*06)Nx~-hz*ed~MWe99f;KuwK@IbdJ&n zX#GH5hk&%A>A|Qg!xmTz`{6hbKrZrU-y&W!n!JN%0-@E4wmaaE!gH{JW<`CU z8^PTu1QHMjubqH1S_8*H-5VCd&lf@JJz7D~H>2P=E&ypjRRZhb`(pTQJ@ocN-2%~k z^Jx%iRfK1npR>3FUJi;4u7l0}4)Sh+XVeii{4ChRfAE=ouR*CtbWuGW zLOl?chp+?0_&_{elvzbxanOo<1)5WiXmDb8=HMH8Wp}rsWVCxQ2ISizH2fY6*=&-M#QwX^Fjvyb%Kj{bSMUSO{ z9BqKTw%3Yl(OP-fQ!A|*obwd8hLvz;D7NIZl3@4hz$cc#Jz50M`5JZ|y9!V0IMkTz zg{LaBR4U-T@UD1cycu2-kHvL32^$MPmByX82``1$g?(1X zo8x`)Dfm)+BfbgWjPJvj;luH<_&j_zJ`w*1UjeUmf%lYvqrUj_oX=vHu+LZkBk&@y z@4xWw_!xW~-Vu({9)2s0N8r)81d{j>dj>r-&tSLVD$YQEhwIS$axO^gxIZ3E54ewQ z;cA!unV5GGyN8_y9DE{p#t{&A|A2LQ7Gwvpwo&fqDOiv-u>NL%JT!!7Q%MWc3W2q& zqg92cx*FE^K9ILZAP2Lw4w|BFQ+uh+)sm_ezIv&X)kW%h^>4MET3fB8>eNq4l7gvT z<(J}C6y=4oM>(jhR=Ox1lz~bq<(K?QzAX2XOUV^wgZx`^$s^@?@*Y{0+bHD}t5Q{| ztR%=M&orqadIoUi9BE4D9@GG$p6ACL*%9M1No(#CHGaXDyd3! z^@M8BdV*~W!0Imn`eQNJtO2m%+JZNP7(ytXs0;Vx2Ij}w;d}9~coAYVArl?R+hkFy z2epPup$IygN}xVchp4_(bt;Kvv6ZMkZOm-&=k=evmVi8f7NCCNNk4ND_ECKUiR*=x{AURv{6ZkQF z8@>P^36fC_x8S)TGmk+Aj(`pt3fc_u8M=Witiw)Wcd>`?3er%E;k7oPWe|rK)nSx? zC?^X%g(a{`BegX3j(R}dr5;tUt9R8W>PIz2l~h)9XyF>I#lveI)u6IeF)F*|s`3YE zr8HKWApHaX?~u+)ccd%QX=#fzLTWBmlFU+^_(pst9uOypEk%oXUsx#A5#I3K`JB+E zP{Ggy?sU))920ozZ|e8?zQUH_bNM^^XZe@=C;4l`-&XqczTMu|UbknAhxH`7_qrRo zquf>8?cD3!1wC<|JnvY4A!utcS9mN>$4*k&`VZEfVJ%}e6n;~DU#axcUrSdiRit?P z!dWq+BPuz^SZR|%Kbg@}H}DGDdbzTAI#esz$bZ(m&a=Z^#685F={9>`_%Z`ELc0V; zR+WibC(zoPwIb?ld677qFBdw?J>@=!?h5_nUfMRI2s2mz!o=8qI!c655#u9EMKy}b zh^!hJ8F4+VgloGa$EH~{(+|T+-Ano>p~J$Jc48zyi<=l^gT;fJgH<6J@hmiz$Aq!M zRpGL*Sg0gy)*{N`)v&JGDD@xZ zwER=TrEX$^ut!)f>=fL>G*J=PNV3#Go*-|MFUhhzU8$s&)mmb!@jRkEb%;)83_4u@ zQa{f?8;2S%7)7Jgq%--9Cyniln&E)KW|*YEr+d#HWZKcM$x6gAtc7M)iz@5o_Hsv9 z-_PX2${gjDA}FzH6Scp(MU7JwFs%=3gRcWpiF1-_Piuc8@qFHJQ zvN%neDGiajO1-2}(k3ZMYA+v_Q{|#c3FRB;ou5)wX@U4rC@QSwEAt;i!$Qu`du}8r z2k!(Y1$Ds}ft>+cV5+~OKhxLUCwgOi<$OhaeSG_U+kJogM*52T4tv{sD|tz8y2s^h z;O*|6@7>^?>TThT_EKKX^U$-zGskn@WA!F`@A$8CAH}iQ5caL5VtB2B{-SeAUN3d8 zifG;vuT6XmC99_kcUcckeGX7 zrdV2QVWc{6!AQ<&>GqH>Iw6No@lW$P`S*hT(JYmiQa+2M_fma5AF*F1GNIr{qy{OUsK-??^-YKndj;5iS*oX zZ*w1Zk8$&PNAf!5eaM}XJ1}>6?&RFHxu;(K+evw7@Nqz~``W<`2$lQTqy>F5IK&%c5n9?k&6}wpfA1QT7P8E64H4 zcGvQsskh+?t5C57#OR7qj*za4K5>sURc@^KlufYaCqO(csuXC|p5lg3)xb>8{hThD z-P5R)UrB|M*QaEqshMkXn|tE|HTX)>cV!%AAa~GVx`10^B z;TOUJu7<9O&e4uh_D#0;*2>l|mh+bD7SU48TFQFa^4q-5bjPq($1>x{1Z<|-U7jSq z<2Q!xaILr^u+AHXHuKHJhVl?~KDLHfO?74x*dF>fhIXd==5p2!HoJY6eYpLxZNIgW z<%FrC@tyv(&cn`R3$aPe1!g7FhpE97WpE~)&Y*wO`)LQ=p6W-IBA#JGHJ9p@3&?Aw zT2dLQy>wWz$qVHo;2GUkA8HcTiP%RbP?1b=HiMm_yQ15!i_~>x2Qpph+EhWZB+(R~ zioMb*XlK!zk(lw<2hI8V2I_1@Td8E{0_c6KQ7dr!-5ALhgY3tI=X;V@krKrh^lLsXaNVcRn(`II_ z%j+NfPpQGSvKNgB6}wiJuehOdjY{RpjVNVA@TIIw1!hq4UI{RJv$kcWz?^6n; zCuMzcV_c4$P9_@`*;_><#zYs2D_o$6zHn;6&(ZxO@|>@1bu5vlLx#ut82uJq3TtGW zF|+B1)NraZHIO<$Rim%bZn_B5kTEjT=-t#b@+W>%E38C{8@N-xcX`I_W9dCoo248~ znVohZ^Lg$n-~3R0c^Y<;B$(rDj_#1YxFN;x*qCSPXL(}%ZCh`@XYXyFXX|gRVX0wW zW~yZxVd6{~=EBw@n*GnG0MyNe!=9+UH z7sd}4u8FboA*F%l#_kd8s0z$BHc6-HpBvg4_Ze>+*BE6(1H*WIdtDB*h^|L=oU9$0tusvNwbI_C4otnDav-H?YINGKv~B6V zGUjLQ&bpXo%9@(_HG|D~k={PzdS-0yXWt>QGWFRaM_n#{sDfPWK&?u(d)4q&Vu6Zs zJ93%*t??G?qTOT?b()FN-O>*=zA=tAJ~SlgcF-SiS*a!(LbC%QpU=0~Zx5CaRS`yt z-^7LDR(^G`iSJ0>-K=Wqw^E9v2r0$Vt=ZK*)3_tb61t(esH=AL%h+B;@`{`J-yMm#L32290-3war`1pUo@GuT5@vatrkP*}L=xvIhP` ztss{cJ_bwqTIF@mdY#54rzAc~c%CpI>95qHnVWOXzE)fzafIU5#^N@j2~m~E!6)FY z@hx~wVi?I$hnOY0VTL!x3#N8vz2%0bmo?Vbz@FfE>`Dw*BhN>FjG0`ZcYzTx&!Y}T zymn2tOXj|Yt;|oswZ=uI>x1`tb$Ti}OXBWF^r>AK7;Hbqz8aKM;o`f5IIX=trwU0@ktPBv!fH?g&7 zn$)n0TDlUU?2wnsiSjmOo(jD-v2FNh!a~j=myvbICqzNQj01a9O;buL^JNYq2SuDA z#tY?ym3$q(8-I{*CrlO}OBIzh>PsyiKK&CvjazZZNI)WDjVy{Ygt$;O?s#Cdf1>ZX z_k`Et+vcn07yKsz<$`^J)q~dqIsOdaJ?~;qO?QR7k-4LDhGyT&a%J_*{FyN|BRRcY z`iry?X@8~VrZ!6Lm}*HoofeTkH9bCkNyhz*))}Wk({)HqOtvKTijVyL^XHo%XMR-u zwKe`$>ZH6v!dJSAb8Mkt+3VHc)mdG4LG9JmUY2`M^nBDp`+37;`aRsU&BP??AluF0 zFxf4?t@UlKtxe4<3{}{AWV+T>nIn$mXY%WXETN^CCQcG>@7)M0X-Pl|D znx+KHc6+RAeE5HnxzT|FD`QU;YFfB#;Q@t8#vUth1d_*`i?`RX9yIkaw9~C-*3!M{ zJ#-o7HPfAa%}&?V)KAje^sOK!$)VR#&xv@fzZRwblncs9QkE10(fw@Mr2JNnszWtk zFyeQJBh+DLk*>Vqim^3F-F)j)>m=(=%W`vZ(@?{HT?~7TUP|31$B`4sUF0h=mfAvD z=t=YnI-0IQ6(imFQLL`EODQ4aQZaF!fC(Ew&Pe`rsBtKT+sXCiI&derArONl3;#$J z6ka`z)g~s9C8_>YJ?aA~5x4OA*b?=YoFf{AF`?2N9u)n3{MG#3{7d}H{D1q`_$T^5 z`2yZ2o`&uNx#e?iWp&MLk}*2{WSW}VJ2f+9T+03AzmlIPl};j)`Xud3`kXW=`9R9A z)Ol%K+C^|0ex(1G?n}FtIxXc}lALfoJ}my9_$Eok)3Lm2yoVC)$+3B5J67LXw_Af5 z^|seoQ(<~>V@yrQJws1=3=v7BlLgogMz6K2t6*fKn4bkY7WgYVF?_fEw6PNN1M4N@ z!e_1~$A(VwUxm`*d0{sHj2jvlQNK+WyiN z6aFd8=vrm_*N8Jqv3Bwu;WpneZ-wok#vF&iVB zgiW!}GAHW~F#E^>_;an3`d%(6)fZZXCIzX0>?`U!=PlRA2OeYQ#Vsg8@zpRRjh zgRP7;#k|OrV~Euo zSUtUpTt<8WOzsfiy8{4AJ_)GaKl0K4}c5(P0REU<|y-m$z>|DgV|~9M7AHqE;ZPuY$Mjs6lQevZ}L8I8^45I(?aSD zwV;})j8JCERi)cPI6si{2G04{`(Ar@djsB!zEl3AfjdDz7sZzljN%G$nuv*Agg(5F zYZBb$FYRN!4Lu*-WjuAfjeR=*Pyh13i@?^v4!`W(?iu3F&OMxSA^UI^o@LBBk@+~I zQATQdqx4;A$5O@Q4Ipp*67>n2;vW8{^((%*u(*U6Oa)6Bg*eC&&RTnsU?om`;pD{YNy_c1u0^^ISSNhp#NHQ4bM+ zvnF#FNAK|VQ43?L7o=lr#BMA&Gp0&pFV|*UU-JpWSlv^`Pq$)@vBmVb!DJ|_KfvP5 z66yo-2D_!!QJ%UdhcDb%*NM53LG6tlCJIqk zsV~$!N=Nsg5788J6A+JA`kTgNGYrH9wD?fq@HEI&=(3`x4-;MEVK7gOKJaB?&ek3Yr=YI7Bf{9bem zqlHGoQXxX5rG|1JrG}cP{sTF^Rv?)q;K>IdmzD%L?J&S$s{>Lp3FGnGWIMQDciHp0 zzx4g}={g^q&cx9{su)#*tW0#rXJH4l->R&n$j7BY;$Y!CAI+Z&O$qe~Z3}hfn+Rs{ zu{c|5A_pKIi&56fo27!{d_Iw@AH3ur>RawD1K7nc?<3!Gzdo=ja4#?^aMRxsN;(ea z9?Z_poD2S%FZDwzn|3+1b!w&50;%s)bSZI3x}^USQxl%X2jaf{e*Me!d&%z>znlIp z`1{wdrN2GDBY%5;Uj6a)d*2_qKikKBPYTOg?2l7R8PA3nD}1ulkn%!#vMgV0RDs8? zZ>D{89(Go}qSnLv(vo4ky=!EhLTif8FP&6&S~)}6n381*`y;#Bcj*rj+vJC#@nH3z zb1(QNQk>ETD^A$RL8O7Wqm@zyh~qx`ivmbMQa@7bc5%!mBwxf*AVJTzkYQXiEbzSt5 zzKyYrd7h<f!YIU&XcxQ4pJ(r!WZwVe=eM`J`to?@Lo%5rs zd6?vy2~xGv`3XoV3+<=vD;*!5A=iztLE#Y*T_Y?J2gC93reVWf!<{`GRqbx;I?H2| z&oDt>PuGF1%%oF$$zxzG_CwxaHss1~Lw3!Cr9k#KTkWD=Q(Q`Wd6ASW{wH1(z2b6d zg4|4Ts<|rkVZ$=;+r$*GtRAuuMN^%~NFoX!h&_R9&^4_lVCeDqT0qaO?O7pONd#*0imLBh7X0ZxL3jNfkJ^>{zLu^{#9T@Z~3u6 zkw92rum6~DgxBtQnAbUXV)lYeG5vd5i?ljvMbcJ*oXt)-mf}uXlrkrINRlUEe|+8e zthoIkSqVR;{I*s>$DAy3 zr+7rM_<~Eq$6G$LDa3s>N9rQ|Qf8AI3?|3YsCR`P7oS$o%mA+L_Yyx0pg?m}Zqqg{=N-?)rI=?g`$ufiI!@ z(i3I4wgBb*)E3ghkUr4e`_6sAz0mW_o9pivsv`YV>l0uG6XrNm3Da}qbYpd6E8`vGM&n#VKYat; z4`wWFrIr&Uo&hlEL_7qL<-r58clVj7E{SoI9-x1 zOShwWx)!@dcUj-YaK_Nn7-2ePs%buCzH9DkNwY4uPjNJMa?aka4X#-(vul*|i=&a_ zCLkj%?IGKKTT9ymYg6kJi)4;BJu==iT+{E>4P?tgwBMWBNq&M1Mp^s>u&;hW4sfJ; zK`8*J+bB5%sH_*{ttDV?3#8@JQ>lv_lus+Q)UIj^b)>poT?LsXw=!L6t87wmwWT^$ z9isM7XRA|Gi`q{)BNvg=r6Tew`5U0s1t7PyTsfi4P}1ZPa&@_~94;S|K8d_gUMRs= z4vpm220sUG2C4^l2Y&_Yb3+0DiQ;Ai2L&ql-QG2xa_)P%C399}ziIR|^Y66+&LVm{O8lY}o9m82zAdhmxDh zcB?N5aN9R$E@_ zr&3L{*5c`4Tc6)E-8;lzgc|__xR%%gq9M70Sb;53%8J*x;{L{-{dw-(jNJEmmpr6@ zPOuuEA=Xj)YjyFtL=;(#q{uxGv#2-;d8XB5Ce?=7%AV3~)YmX9HFPsX8EP8F7`_+= z8}p3oOpVQV%Ido)AtG2o<&j^=3KU5PX#-mhH0lIHq;aLuZJcAOV*X;D zZ6U2At@Ge3+}hi6(kz*#n+BS8nj8>Sm$WRl+_A`(G|LJLZJAk3S$O}8Lvyj`Y207$-$X@mb30njCtW%KZx(qVa z1hSRGl&|vNav}LCGXwZSX%wmwkbQ4Ey+nq|0TUm?3M5?&J?%u_m*E5ehm3m?CYs7 zhdvuV#eS^%vGnH&KNcsp&UE-@NXw~x#!*(6b)B&=GfbPvr+UfUA6a-#BTq4|tTK`g znpcNK73fyvRPnOK^mxCCr_}`4P8yyfHiGnlZjkKCrl2+durtE z${Ce&D0hYXytiY345bL`)g|VD*v7wIsI6IZGFteCuY&+c}{eI&Xb7eq0`q@&g)vZS? zig}(YdU5c zX%dWMjTwekhFm>u7;oSVLyeSaCg5i~0KNNSWQ}JH^9@CSs@TQw){tkoYuI2IVxSED z^(S;0;OT#4hB80t2J}(L4BsJ(lK&7Pd=EYiVv0Aw$?2#)R|kQ|KUJx(G*^zob+!V| z%XG-=hXbqN0a*P0+B9{y!a;^@o!kMk+MVQH@>qG6+*6K}Q=~ZQhjc?aAT5*z0lxcC zEFdlvlK3Y4tI&uL&mH1ca2sG-$&KS$b4|HAfcJh2E)NQU!h!k_RU~=yJe<3!`*z+y z$R`ZUtCAPWm2!!^)49cRhvbyX_GT8%ERk_0?Lcbr)SfA0lFuaFP5hG3B%x1ytvE|u z$+!W(7yR1(^Vjz(-IEMQMChnb74qK`1ovbmk% z5woJ&#B?h#t3c-h@iE<^*GCj^d90(2li081YV3^qMxBTiA@4D}4bRQ2E!HmC8dz@| zhq31gQF$nIG)dosQ6{Re{yq3hyUrM8ATc^1=dD0Su9Vg>$RZf~%2P|r0A z&F5!=$Gcl>2KTnQd`3Q~B&zGNZNy~iD!qcyvov7Daa1>w$5VkV@ErS!*9A?8v2*l! z#&~mctHIX6Hrdw7w#2&9^42`V{N8-ovekOnrrLGRo6Z)lXjc>G0tf5pZGUNdV!I30 z@Qy9Q9%FxNTWgE8-Lwv~-nTTjke0dTY|}y0JktfF=qJxU&hWXq~j@>ECM>Z0`Umnj~~KU0zZYr9zagtj;+)%$c(*&d_V=| z1LUZ3^F(|_52&imftTZM0nzMuY8J!x;|X>VDfskVe1M0cS2V-Be> zcf?yW&yxEyH^sfyzlp!4TqXi+J@XR#E|({KPGo9iFoF)B;G}HTOfB`_*xhVLox^a- zw9vZ6u_bJ8#JI>~P(rI`%HVft+(x)b%NDmT>}}g z3g#)Mn?{#$sNtC2tsAHd*J3kMnTUa3M5Y`G~gj#}^pT@rlMTRzV zCAg`<(SaWR1)$NUdy9L2d3JcldFpv2_bK3M49}aBJ0_=Q_D{gC__T|uM^fGZqR}RK zX!6YDCGgcES)cqgX+ctWQq{x`3ID~fjf?+f{n_KY;oJSMkG^gGc{ZU#dP*)Hm?V@| zHmfg`dtyN@!#ly+S%U9amumVzQ_8){K8lk ze3|~nj^-NHX7)(uTvtxm#BetJdzc~oXt)+JGU`ZF`KU&bqrxq&A@+}!ccxThtSQYj z*V5Vc%^vN1>omH)IBPkR>?WJVvd}nB*N*N&oYxjAm0>k5ly@ng)%{pYVmZlDL&*>L zE^Ug^OKK+^4ejMBa-Lvz@FirF9|S)KgFzQpoy*_~@x6sUVtomdR{#&Hp0Y}rqCAs} z$ycNcQbie4!qo{{CA>fRnU>j6`uc`FhFxIa*6Sr-YXeuNQtbyivsEh`%GdMKRHfqqj#FkDe2CIr3pda=0N}7uML7;XLA; z?40UccTK$gjh71d^| z(STFf)jH}}@a>zaG3q(RFE;|ey|8pb>?alzRY4I5krWAFXv`EU3nBgnf0lp2|Kf`a zw}ipsE71t7ju((wEd~VwSEOdr3vr|v1N!Wo@Lcc;6#!Gq5erLB$nd`ucZdzen?gO| z7T=P$^1;yO(4kQ4&>rqlkPP+hx>DVw|rxKHs2X8O;MGiRz=BCtE28lo{ESK z@8-JU_-!v~$L(9~n;penyTU$%Z;2=#IU@30#Gdert{l758fCKRD>DLFhI-1KXChieWQOkx-xj_#yf9O~-xUp*~als_9A}<&peLIw1Ci*ihiogH-U}z?*kn%~EN z=Z!));fc^iyaO$_ib^%5%2GwChGdaGh*+(-ROWs%Y3cA^Bt>otgGWLvtI?u>DP zWwC9Ky|=^S>;hUV2zv0O!{e|z1CCD)+_~9laGiHu2s<3UF``&xnaEcW-2sj77cPY@ z3~L$IG%Vd!%H?uCw^z4KwkW0yqro`IP}x8lzUv?92kSrUdgu2{MS6#~P?T z6YbJ(>9X8gnXJ5%-%Izzw?Z=52cFvnd7D(OJFMQG{5jqs92R1 zoWC5LJ!t!AJqg*Ut#ECNj7^Op!z{yVD6?dBHyAtJi@bq1#RT=4vQ<6`lCV{54tV%S z;M)xXf9nz-7fR%w2loWd`cr*fd=b$2o$$r@O8c7mhWSSO`udvtT)yAl%idMqzrAC< z>%2DK6W?5ap}>Vep)8tlux2~G@L@YMm|ae(Ks=bg8^KNPqMD8D4kk|rs0 zwQBetVj&qut)`ApZK&nsS>i8<3KvptW*H#x1I$Y-+pL|zr~cd4#5UZ<*c&(oIe$Cv zI;%SOI3gW)?Cb2u?Cl+Gol9I#!}f(skRSRLz5!6tE@53<<(-^;zs+jxWWHzYXQ-g> zqO+0)U8(JH`8jl&h2EuS%SA?BN-zFy!m+{fS+&+Q5(^3I#!c?1D1khZ)T1=g# zzEIPF89NyMCW2j!RC7Q&);)goNJw5okyLuoo5|Q z91R?u9mO2S?H2oH+alW!TXXv)doMd>-)*aGTVk!^_8ctQLluzvesYqe_X7P*$xK%68T=ZgRXcX((LH!j!_ysU!$J^n=h5y)!t zzCFGxzM}p*{-3^%zRTVw-qOHrEaKe@-q#b)U~fa;5P!|U^*|lK(6WR5xG!8-s8Xmz zs8FbS$Q1g>C2=)EJ43zr@j?xV^NUGGBu*+NX92=WO0m*7X#?oP?&3yay)aKCWghY} ztXvkf@OeN16U8~AUVI@`7te^rMK3Rhu7=`6?fH@XmCzCHZE#v}K@j7HaO1gx+`=Fe z%nKw#Zh{XOKyP*oe1!9l2oS+0!I^#3e!YGp zyyu?5VRRd27>a`LDC)oHSLz-5ZMxyQ5xSwe>beJP8`cC{5w<+*WzI4^7%#n@u1sfA zzbFG_vcCYLbr>RuC~_c@4wzTfFZoB@a;jr-oZ2OEAjK2+E0pS>8$ky-HzXR;|i=nC! zH(oHj2UO&Tv9hTJoYoiPS>xZvPlhDDPTxzH$^K>^vaQ(r%mAhUFyH=SDl=>7y}*AD zk`{`GW|zJ2L}2)xhYI&STBJHbZYxE>lh2iYN^7MEi4@Q9JAjdNl4}*35E>JD5h~4B z3T+NDfztjI|FqyrZYCE9V!`@=X>7)w=If)ht32`aXNmb*hKCx_mgUg;{={p`6mJ|7L~)4UCL8= zxp#iU|!RosD)IBi~)x9Z1O8LhFQ(lVI%2xgoBt&R%QwT4m+2A zOx%R}mjgsN?P4}khw-+++NzHAA>M&qd`nu$gG3Cm39pP7$FJiDh-4xTmw~g51Iu=% zS{iD(-e_&0%48hg2>4<1fcs04Z}9O@IiO&(i63M*^`4Ni(@<%afU#sv`UU-f8bZ#5 zOw$LVA#jEkGP~Ko*mQabWhB=Tr^x>FLAoWdaVL;rw1=TU?z=I0R9~>nMRc?DWAv-o zZ&Vy{gxEt(VY&hjvIa=>5atf`5I>`J#g3En*nRrGy7y$NdQJ{g*W>R%zp_*@ycRG? z+sY#V|Hy=Dlk3V|<*eFJ`v#e{RJoc|Ky(4Z@sHFK5V;v*JMOf9bYM1rM!uwk$>W6( zcP3~E#S3}TBZwd_2_r!(6cfq`?fGA!!TeF76U0?tML&Ngw3eSGjZH zgVo|{ePxflQr;nV1lCH9G7_vo0p*D@OM8xAAu19!+=i9ahJ!x&u2#W#?38v3xSJo9 z)!4squV<*erCmZL$%(b6{NyTam_!M0gbC_f;xe#x=SrLS#bObSCf|||wRS>N?igQA z^^$Msd$>Wm%IQKarQg_MvIenDaq!2uK4J_u7g+vHl<9m${;>QP(UPuBPLg?UDle)z z)L15s7%eXiO$^nPuMy+vXT&h2tH27al@nAC{UP=Oz7?3z8?`4)dE*Vek=miANw<|C zag^2RR+F`1RM!J_Jat#U#?YQQj2%~IVegnb#xllXOaYu%tKx}N6Lvbi7`rNeRyL4_ zbh*0Tva1DcRL8P)m?=~{;u2nt+)Llm4KW+04hA(Dm4}%sc8XQ6G>F7rqXEguCI4 zegMX{246&!BuQe8HeMO6ti%$b=3yG~PLAPUg!YNURUS7IkK_?N_$=anB}(lpb;%>tZDI&SbcfU)z@&Q# z+1XPvrCijk#BN+scS{^_pD$k9ta3-uIeyI7%-=A$|>)3M3?S}s?Zr^QkAnEtq1n9A+tf2kxjjryn!5Z;G& zNd53q^b!hszDWB8K^{tOWo_(S;y7^TYp5rw@rDul9b_x@p41-hO;vib?jQCE`9-^^ zc-17*sWNjFHTUvjZKBL7;f2*UZ7NA+q5VD#r|D~O#+Upv!w}~WWvlOdr z#YMU?tD`?-2!)Tpi_#nEDTG6vDlU+M_ycw>dyOCzLAa#EQEuHQwjbG0yR3}UbYy#G zwQeoDofx8=mR_rmspI-oT@`YPT10z91;CJl9dAlE9;F$zuJjpurn3S& z;1jh2s)UcxenT-+N8N1vUwOC^NuJj4G1b$zBaX@gOYqqBT z0_0d`$Wh9_*mQCTc?)|fzY`zGkFj^e3H-cDi)o?fVsC8&5lK$LVx&jG#(~cKG*!YA zu`l9Nf1LMuP?4aIm^xD25=;t|;YZ0;v_xejpW&P7`^Zg`k7;pgqVU4s+FzEptCz4a z^&kFC;1m}vT~}{vhasz7oWCg9p>EW!l~e{p^~_t4we4hktfxpqt#VYSGi)JW<)u|#XEG}eZb4e2CmFFsA_ zC%4ot5x>YIWLtc@T3&si{R>sL<*_TOO_`?r)UM)nh(Y*kB^4sP^YVSd49zB<$@3u! z#MGNa8}fsCMrae7CXB#pFtezhY8p>*2C*AeM*o?ZARgi}xi#_*Y98Flb5bmSjXNhv z1kD_!s}Z?kT=0ajirA>j)t9DENQ=1)sTDKWgc~~Jm-*|#>ynktG>z7k!Yj%L#9`Vy zCR2Z!IYIQrnyBxzQgjYvVvACj@yqIY$of~OdoT{F3??akwBF=r<_fclD6PiJiCRzU z60@AHjDLiT^l(ifePHM6;x*K%@;9X!UJ>-xZ+wo{2KHH>>_`h#II&ZGqSVHYk`?J( z!13t${^S7nmdTGGYPNA8$)KX)o}h&uL9n72nMqVK-Bg)q%n? z@djR&eMI-faIqUVJXBnLNSA<-u&3k$+=#$xVLX1CE=_OIK5)Z4ocEJ(A5Wq!#71sP z-aXGu;Wi#m{*)zerMz$c7K)v85r@Rto(sA0fkSFZsy^N}bU1Hho-<@7-Y|)H0=FP{ zVQzbYWd<5X(US1aGuv}pm`knEO{cz!=X`Dac4ZZ_M&FcPEKLg33?0YP*n#>X)N1(` zKUQ+#6`5>y1^o`2AP<)TC1V!pv)Bn_6|n8V6Jj{X{QksM;TXS9bL&&BH;vD=ok3k- ztnAl^IqsXsVmpG9{ZEABbZu)u_VD&}w8!5rO(9|2>A3W`o`AAaHAJwtgPHt|X zkhl)tLAM~A%Fj5Ke;~KV$5P+%N>WGA!hb8V#B-vU)?VDmrG#>n9mH>Zo>E)r%HNb* z5wl1i_Ew1(!{m8*1?mxKYpe21N>kU9I5i&Mqm5R7$T!rwWMdjq*VHY1n3^f)X^UyU z?lDsmTPPKlH)HQ;v#vZnMeD2#!JbpIfD<>17=^XLw^9tllSbSRS?j4-F8P>VNIJA% z(qA&r`sm8+PU^h21#r?i>O68jLotW&za{Wl=fgZThX9;R@s0QqB@~3)PsjUvw3X&~!=XJx0E%Fs{f}Bh2GMG*E=%vzF zZkxE19%iwdJCSesbAcFXw(goe&a_Okg?!v6wY>4Et%)H?6+&B}#X@bvCSw`qgYuAf zNKv?rak6D8TB{?Clk4HBbZh1~K2eGg9?1U^dzfN$iZX-i#Zl@QY87R}t*qLgKf&BINds2=o+AXfa@@WN>gr2w>5%s>d&wlL;*kmBw{pc)mLW|@E*!mwIMl) zJ)@gXpVU?<4tyZlne0UEqNWnVv6Im6;xXQqYRq2msb=R@h>U;kC z%(DyYGu>5Refpjb%x(3caz}s5*-dNsAB~OLXZYE!|L2Ge2~=CW7Hn{A?%QTrg7Y5eVBSoJz{+4{}TJKRPUkvt9I6hkrjMtPB9iE zdoqb`Va_5(U_ptvMnAvZJ1?66X9p%UvG8c5We3!BVu`2p%^|GZ!)y$3si z_p+t5fuY(Vulf)3j62V`6%yMv{%% zeePtRrpE!myg$l-IaRsFq+1|&wnY$Edn$yP@Fn+LXwS5w1D`yL;1Y^kr zYX|!(VU;osNVU7dG{s;=GT3Ic(>)ASe0X5)@n1Jk{|xWVwErW=dI$@cr!FKkaWAVcw7yknbTzs}u|8iq>J-^5f~ zU)u)~6S4)oT5&PnHrDc;o7LkNOp^h*dIAF&+kQ1d8ja!e;Y9 zuCG>KI-iLy{H%RJy_i}9?W-jiBtJTm~31wFYU zYUSWtc|O^OY{n%fU9tqb;aY#?zlv{3Pqm`_P7XuN6(h7^I~$uY1@IHC#TDXblBarE zb)^==jAIKp5BF6|4W%l7Flm@Pn#HDQM?z2J=gb!2mGFjKRL7wvGTKbfY$|=@PX6b8WleAE|Y5ap(<{T|U+ABHLQq1rCbFx@H8H@-tlBzJ%#P?i9y=&;O zZ$_{TtWZ5+y)i_N4O9$43&lL#`~wXSob&CGW)r8Sn)y5ZDR2i;@MXA>=+r9AZ1=U! zbIX^-^X^%W-gHv_g?w4RWIg7zne(+`!Lm|)rnEWIR>HK!_(_?d7)Gji(7MpFnd`3K zRxcZK#m3fy=C$lUYPd3pEVPJL3H`ZU5bvJk+gigdi@5XjkmfRS`0*xHc*#DYR!ljX znUCC4VUc))cN_iG>)I&B%y$y|@s;TurHI;sR_Dy(TXwv%RK!%?3Eio$)9avU;PY z^FGnV#^~+UE_fAxW5rZrp6d1JE+d)DV}Kd5~D^|BW5Sr4p()Ex)-;4FkYq( zL{_73b|tCJ_Yvy~cgY#BX2Qr3p_pZ=S>WT0S#&Y8PS|Sx&78qEGY+XOv}$CODaTUX zbd!0ftXFDLD?i&DVH!>TRsU8FtDTHPe7IPa?Vxr;PPu{JfbVQ-z@62GhDrn`$q&ge z(ct?U_v9y1Evy0uJA}NX4b(=;0KE@-oO76CbcrI%ceRG}D07BQq#cwF@?^EFQ4-bD zWU@&=tL#*#(D!62_nA#+M!+`M)bccuog|#(PmzICM1;4RG!oGH&T#PkpIhnk_7@mex0@#Y8;t%~s5mh*ir z!%R-LjsAz?(B89;O?^xu?pI^I+C;5s+~hZ#2J_Y77j)Am8sS_y(|chIeI<=jp3{ROhgurm=y5T`d%fG zNwBe9)OW%ELj5$%HDJE(wcb}gCdFwt*pEUi7h{aj$}7bb6FtKA=Wa5W^r7lJC0oyA zEAsb{8|kBU(Y6@Hgfrp=E`o{HRi(XNpZiM~z*m3=`4wXFt+-p<-+9DISlztCb5KmB2!jxyKLmq^h1+wIgMiO^`&tghwJ3==?%e9wG zE~p$=v}id+TBYp($7dg9^#oT)B08k5p&9iyMZ$S0K@ z+BPE*bHIz3T52Jwq4EXM(RXnim#Jq1 z#$3+wm^@STkWZRTt>SpgC9a1uIdDG28h)`ia*l^JMv9kCP_M8T*~$)dy7Gs-P|xNz z3CoG0eNY~&$uy5m6L{W1W6&G9S}`+2Oz1&oCo9fiL2#MT-twQ_XL_pD^+yIi>xWHm zZ0$`w^q9cQzzn)Zyk;G5ZcTIji~P@&$6SQ{lI_DFLEH?P$BG( z83>c{n#>`O5i@kw4>A*xm2@&2gDw4!mHVQ{*~W64998RvS}KLvO{N~EY5WLUD|99J zfKIl2vu`(FG}?sXf)n)e=8ewt)~%$nye3dj=`CbBhB}tw>;qcw#MT{lIQgE{58}XPa!EV7p>kOi`tjaC({~M<>f* zeW(9mAc+>Xl(F|Tg&DKu809ach|pcU$6X?GjN#~OOgDZd;amm>YprFY4)cR?4gOz0 zez!hU9;z&-^H~R9i!IQXs4ul&nJ}(1*Mvz`I)={6RY`BLhj^4NraR>C(gU?2X=7?* zn#Syqgy2j$oZQ8=Ht5*k$-pV)Bm2J!?jO9QWc%++V@YY#A#-njx;9YSE1#!}_`Rkk zB4x6an{sdZGgn<0!KaZ~bhH*`49C3w6Lz>!SbwIqG-|N%$eb-PnxS{|4but}rvrE! znXTmPysthJmEtxhC z`y}|OpkHv6VYaPuJmpj5lKvsVQ`$}bfc2CWRh^*MKTc{uKA7v+DvOusVx^AqE6r!$ z^Dnp)jDfz`(G1V`s7 zJO3{?j$EWCkcAjR`idV-OV|?X0lBT-gk2+67yn_(C<~?P+5qH|eimccFQ}Q_k;hY& zPcyyZTIl^@%Ll8`q^)q68(~z@B-O9qHkts1HzjbLN7QRrVeql(N~alN&Jz$={ZSfDEtXEoXX z=AMVn`_{?ZxTn@S*0$^&X<@LclE|z#FSXQRdn?7H7^M)?&(y-knwuL>!JAp8?j!9j zYiud}5T$J3pd8K4F|)QGO$YUy;52EJF;3`Wz9E(;)0NxOTKxsnlH0;pL=K@HJ!3Ru z#-S2o2B~ZW`G?-pcA!SJjx+Orvh|skbdPoxzIS`BKHrI-$ksO+>L>N%#xJ1ZrLaZC z)$Ao@uQXicNS?4zR7sjjke|54hVjd}6XXy2N~=$Mfz~&a%xBjzJM_N#K3bA2<74=) z%rey5TN_=;4)!eWvkBGq$K*e{T|K6CWw!EN%sa$z`q5v_|4z#=ZFRBE^UR!r6}cIq zYGQ^v!P%buJuovbEx4JTV7u!GiR0uexpfPs>dP&KTurRM(+dTsbBjw>afx%e{VEqO z`wCtL9#Y1%-(0}+^hR)0XcfJ{RpiTRsBicELb#Lp+=^dzOHR^NDt*O5vp z7?QSMpJogIeKF3s%#lipBS zykM&=tKthCyiq&{d(@QARWvf1%3z)u(2btyS68X3i zVgz%R=_?6n71a%ZE)U@<@g>+y<1yupTGXzOq?-ugH}G}2{>EpeyzJ8^vSu+3Io>4w zy!1qh(w{K5xNgF5j?f~gl3!GR$3ERJR5yw#ze^|NZDf|Yj_CoDEUyi8ldh9v)}!{{ zgu6;7|E|C}{SPtD(pwmyR`tgQ+tKslH_HxT2t6Tf2-a8jl1Cy4PwW8IBA-`EGSyAb zO+Pb@!Bb08>heF^E?MH(m9p1gTW-nSvq+Xx+%Dy6u(#5l;D8pMjQIx>(KDR=lI{31$bX=nKVEOHlZm4i0?|+}Gam7fcHU(ReAxDpAIL z_A=}~rIk<_x@I&WrAc*=3$AO$)T{bQb~T?xo@w3D3AKuPAmR3zuR`W4gM+E^d6Ffb zGL_+{>dS)BK`Z?xTsI{MPsk!=c3_FLh`C|Tv~#AK^6lI*1)AQ_{;wxsJ|WqM&L#<$X}@-pQx(@?m~w_uj4wLr3% z%Us}g39q@{bP%lWRP8o$Uo%j7PcsT>EtHMg1|y1H$+K*6t*pY+(C?%F#U_K-^Kn7-z+*qH_ZsL+iRZQ%5#7w1)CEOQgvR+L2NxjP) z6+-+%W0z7~X+Y;A=kS_qYLwCLt9{^k?dC#!Q??_x8#UGU^a)qQ>=mcdc7e71F;muedmV z7EbEg>OlP;CW}pGQ^{ne3cW?YfeSkdl<3dKMKXw+MEt5GKi7+M|B1)M@@y0BU&Q;D zNngHzT|_cKGi_(wWLWk9W^#Mew%|Iwg{R#QG08%<15;67sqWYJlJdMN#0jUFbLb>zAcTDUitRuYsRc@e;VsD!&iGz$AN>{ZB?aN-}K!l{l^fyLNzJ!p)tOs|X7V?{W zgl}9uqq7=IQ}_y|yZmA1u6jn!qlGYY)kbW|M(Mreddge6nOh}Xp2sIQ9rD#lFbf$y=O*~r#op_7So^4353bmE$HE`?UGmGWwjU%ce5k=NC ztk^xhL7t6c3YbISs-9qWkyWGs^KVnBpNhth%t>~T@Pz+}Xzgf7kcSwJ(b;{4pR8(r zf8dPXQ21{88=hn*>3}lKXwE(0_A-ya+AM|Y^H^gVJe-vb)+L#2Jki#vb9L32#g5>I zb5qe3a5Z#9uF5Plg)9U3zm?@a^tfo_OoQ#1@}NtCHT)LUCd{&o6e`nSLG)Y3JY@yK z(`J|mIzrxIZvD7^NIkAsBH#F9LR~hbbwq#netj%gAl?>gGKb~$A+tJ=>=41&DwBheN;U~Mapq0jQuSzNs@v2;S`lQ3W{JHxkA4B1t8Mylex{id|E8xx zQlPE+v+&Tm#1zXElFOkd;VIY7++EmVoc-UVy4u88&d%n3V{<{0{EvRZ1k5E`)M&zZ z*c4KPj#X|U@;=3dkPly??~`51MjBvOf=?J{oYrsay^Oy=Slvuiaseda0@50_$|R*8 z{fqVR-H|Q&pazxg`mgLezAN|IIH;}0sqhls*G^V3s_Xl-F?2Y2LJYc2??~SpZgwD- zNd#jE_=cZocSa*G$R+Ss=Q1CSCdLwGDA@)Lz2C_IqpLnjUrPUEzQZDJFrw)m%(ad( zB0wC5Y8r?pTWBN1q75-eJ(!tAwlZFNRv!fz`X6jNwi#1Oe*tS}7**NspfbhN1k9eq zfCctrk^8@Lyog}l}N zm1oLR=qo-?3~<}%7I_!C4YtC1yyVUsnp#&4XwQw`$Sb0-@Hjw&km{t&RPN;Gy(IDzR&r1z>7#B0JGx zw9n{B8|!v@hIs~hn_-m3B*auEiXF_phPXsoI)cjdma!SN)fPl#(rFZ?Sht`{;|}wY zNki^cW*po#_93mKJ=3D-P!cVq@KeZJifKxHsj-y2V0qTg{09p3dLxVMX6t~mGmqIy z_vjtyXT!<07K(G%Xe^k)e!T+;q1)qEu)gQA9Qh#&jV=nZ>v}ZIN+$%P!@9BMs;Wt%5$&*vOXR8*t|sNjJ2E z^fs)-chF)c!Ezl%FX8jOc{L#`dvpblem1&Pj(w|`VPH?v5pL4iyf}RW!Q*9qPR}Tb_6t8gDMkO67i8? zYzO^&n7)`f%eBOAd_yz9?;dW|SrL%u`DfM@38 zIp@-cV7RWp>5)q78l^z|ziVuz2WS?)G63sLHoQ2c1p23Lr5`{({GaN^M!d>z06M?X zV`wc9v$uh^eu}oCYe5dUK@FxcTaFOSg&x<2>kp{}t&Oc<^8bnK?I+OFw}I$e94ve@ zEbLJ-n4QTqqZh!n$khq@aTg#Ddz0BrkHUw!ZfqbWSn%CJ@F>R^sD_n91Rm52;dQrS zvOw=HjIVTqM$mZZL(GAOP90*!{zEShovn8P5qAK2#kNPU$OXL*eFdiEY4Va>!ft$^ z{{Z^xa^o|dLkD7|4+Nd0GddK$g1Fg+df;7H(1kqMC{3T~OE96D01E$L*s9gWUFJ_R zfmu$ym|WeCd%Xhc9cPe9*@^RLH~Nf56Du=?-q2UjUl~8?$Sx%nV5y!kC&0tc#ia5J zoNVdLNY0J^-UaY>$Lc-lR%SkUbJfu+{3Cl4ySgT{13XYcC~aJzeW5tI4XjB4f3+<7 zrnXWj4lwcXERq-%SJaC+t{nOg@BaB!Yd7tkpqiB%AC}F zK9KxZVQ=JMfBnRC!Ma^zG=Sgn8+hnX@cDWm8tlXU>(4Bs3Ho0&25Z}8ET{eGZfXLx zHUgeUD*nHVZZ*bWt-hotIt^#cR@|+L^j}Qg4q)bhUq25Xe<^wo(=@N>IuL7o^qYPK zeuzjM=*f*Gaaf&JD4x8)y}1WPh9*#lnvScN4L_|J=;U8fotwt2H~h3b)Fz%o8Kp2Z zipr7#@{nA?wcCPBqR047-_ycSo9K*~Yc0Ck|EH{0%=nG|gj`{D?9#eW^5}uS_RaV` zX|xKIDZU#Y;A!PBM~n@$B%b@9^fJEp3@w4@@|-D2HZtps6Y#9+VV_@R%8@#l8Tt&Z znv>|7AAnrfY3Q9KK?h|Je%A`{mIPc~2TmB7KEOn{!4x6aLEk@V)PS$`-k1n2lHK6; zZ(`oz(H-CW4NQ`k^ccP}1!_9q5f%MU>*mS-D~NtK27^@44ADglnaTW(*kCpKsBbcE zB4O&k7PA4XxG$bjL#8}fo4>%)Eg`9hsa``j?Jm~eFx>aL%xk7ODT`B1AWNa_bpRSb zWuWB|GFn2@WDL|aZX28M8umg9q6t3##MsU3CKW)ts7$^Yr|E3^x3QUN2qM8+tjJ2t zY&`F`(7>sH{8(i~0YjmIQwjcg7o4OsnJsvgvy6dE2g0%zwi@|_sf+qhpC}AHod5m3 zNnjKmg8E82luR~ZpR9&W-o+&1nv8<>#-F&S?@tXcA^|}LnhpOa%ou)rwHd|mWXxJ8A=$n zpuJKHx*A`N9PHTh@VUpLdYDFcVp6Q6(GvF4X*>hf_$*yR-_Y*3{v`~FDl`herw{hk zRr(1&M^orZRl;<}cp5_&(6X=;Q;khf(r8DY!1e{j6!q z3wTb4p@Fp+sx3BL4GZ~%SNs`2v7B*&9ovtz`+sc+H&jL*k;h~cX+bKH-eeE{znwHA zUSdPMu!6*6W^x%wIn(g@rtDUBHF|qTg9Lk?J;t_RZ=f!iOvbZ3_l5mN-hr98h3QJ3 zp;CB&?8a{{i=AR2L&-;+TsHO@_MVNcg1Ot01U zv7=Yuu3Ury%P-^}k+DiILKCG6*6LT12E~+OBo`!$*RZG)aPGxI!DS}a)FD{?C0H4M z;r0`l<`VO6u2<;wpELiPFFr0*d@u;PStK*Qb zohp3@6@)rS)uoZ4@!({{f&p|Sus0ABSnhx78|GW!3;0I+cleuuYxWbS>-HA3C}<4L zfRP0;1v~RU=IzPL%~LTA`8dy>e<{DVZwzQAo0Y5j2j&h}SsZ3sfa&j>VoULNF(fuK zO)(WVC!23trdjV=2V=7AxMiSaxMhdsxuvLelhp%72H8Fb)VOF*l=oln(y+eaO~N~b z-Sd=nUvkcOOt!bRp~_}Hg5LWQm^UkInk=?Q9km}gNqzVy{BvFq7JClXu$E9&C_~ra#Os%aE>WR0-4Dr4=Tr4bB6~|*% ze5bfWTqjNz4WX6r26_*Dg{(n?D1V#Q}A1E3Da2JZj)08OksUGIZUIg_!Mpt|#e@G3nQkzSZC8 zMQH>)lZ{#~6eD8QcIrIb``^?e=)pLv9L9WLqVhr6g2~w(@)G&ATtSIcrpWiCUnMyd zAF@c5r2@=y#|3%J%{v1J{Pp|^zFodKAjQ`7)dndRJWpT4f>F?gh|JgXCgqLD9h>tc zyLt9ya8#OP*35`Wubk#hU6?X8vFNpjYH7)9& z$axV1!yAUlo__8l&MJ-@wvpBti(wieF6J+@T}fA_h_OlUp!wBdTDsOv2> zo}si<4?|VtD0t96;j|QSA~yJ+-;7M@->|76(8R-upQ%i~kY$+n)nH-DaD%ukZUY}7 zj1&@uY;d)=SteWKtk0|$tks9p39tV5%iYXT?{?1}?w38AmlyA&e$sa4lWNmw(vanunjRQKbbhlPMrLaIF)X~ zx@@3f)Jcq&^<_8^nUy{&Zgh-_e4O1)hRW zP#t-mS0nFD?u^{n+=$%6Iq}(vAo{<}_$lLdx+C46`Y`28atM6&dnp~$*JORoE$!PD zEUm=q^Wim5BDY8zwg%UT?=QR%$C(RT4}isX%09qe!nWAb)qDVxg(JkOLIpmSZ!Rnq z|1>=|{cb*Md0~6%cmWpMDCa##8%Gm|#ZlQFkLlO(=3}7ZO5!7A<8Kol{`5Y*h4w|+ z1M)^4%%(+4cSF-dbHP)aE5*o5<)AOcl~0_m8v z2UApCr8d%i={OjSQ`DX6c+7M5(T?dXCa%{prASHkD6$N*#HyyLrn4rm`G$F>g|Wt1 zV?oaEWF2npZ*^IhSz;|eS(;f|TiRRZS@JFGt-skc+j#pOdv(WgN4WDxr|4YaknP*; zhwX;FucN=?nVr~UY}-J>J8k)5PB9fSJr*^wk*SR7fanqr2?vGmLRqmJc4cc!EUplX zn~s_Gn~Iq_p~^O0I43+5dJD&Rj-QRW*x_tEPT%!V|7rpr-C^j8t;PxVBmCj3*cB&? z1bBFV!RuL$s&+ppmc3>&kl|blDpfalQt6;}?l&g=zX#hH-pN1s=mLInI=qWbpbX#C zkL#*Fk51X zxHpC5Wa+CECykfhh3baxKuw}`@NFRE&+&aLNX9IBk?SIqH`y!; ztV?X7y^1{tbT+rGuXV2Fxw(vapeY9v0*g&n^B?9o^IA)?^-ueCM^|S>R2<*n8N|cf+ua%p~9MDIHD5pN0_!7B7e z_A)1$)?w$RiA%+%VnwmNxJq0r_D7%cdtr$%0Tben@z-18Z+90Pi6&7O8iw+{)|2hb)@2>+ zD^$GRk{lwzijEiWP3K!2e9KDvhKq%Ve7@(>jrDLf}Vs{SQwPT z-l9XK4nAL??}Hk^G%cXc1p8tSDs)TbEUBOLG1NVj2f|p#;HSXv&??#PI|b%Na{iqB z%)BajV{&ii)XO=Ut!35A8kRXJV{rPwv?ZzcQnch^$(|%RL67eiUpIbne8+^xiJ8ew z(~e~n$zF(YiQ0Zoa8c-;6syFekEA8Dl}+PQ#L4CvmMH6H%(Gv%wgdgjWm#h`VP0km zH@z1N#15vDCf(H9{MEd{($M&$-@&5>dshfGBWt(-Tt%7|oY}Q#vp2P1r>gen!?GV7p)a-BUE3mK5*c#YgfbulV zS{3BN04yDE?O@$)&9&CBjkfK#y|<;5tTLBLLlg{2G17?aN9Rcob~y6J z+0c8~i~hrS5<=ahCE_;@>u(TZrV}_v|I`c6K|B-t)(O5JRtQuKeGN)yn zPmfIBmR2EceQHX|Pbsrt&q^enNbHnoO{58(63Zm5Nj{YNB|Sd#0r-~X@^2Lk^JfNz zgkIGDpM70lV=vf^miIcPvL@t{N9=f3a(AywQ5 zvffv7FUu>-FW60wt$Ef8w%={tY=vwGa5laN0d}QjilvDq-@MY?0TT&Z&2R8(9UvQe zE%hzCEne#&>pt)_Gp$8zO~5VgV_OUIN{a0mY~N?_VY}hC#91ON9nEJFvnQL${xj=kW@P4X8Pn6RrsbyolsZ0T zb@I8Sr-`2v0`Vi`>%@1DFNn`c7?i}PoKKyXUMcfvmKR*Q!TBwHKL>sa)s#!AZS|{& z2of+wutGdwI&VH|S!Jzdi-BL<1SAp*{GEf=d)B46sza>%vCg*JUfaId@@&!e_4Xc) zC}+BJr_1SH?EcA9;MwA>5_T-?YnU3A8rDDTq1WTB>2b53;Fp_|p+^2#(^%;$S@ z*HJaPco%zvhe7&S0)Abm(7I41DOxTJs_tv`fp%ZNg!&dw=7BI# zM;IbrHpN(OS}WK)IuQd~r0jgQut8_u^Xi+M_O4Wsr-&kp{tX0aY8`b-& zNvo-?(hRK$7}oRkZr~4W)f06mv{XAF4_kpsx(^DfhBjW?t-91Lps6nfFYza7MCfU- zO7L<(0i$h$FSDRgL45wb{NDMm@|<}qpzwAsXLrtsoD66(?L(BgGqYOe!3L_Xq@Ezb5B zD=*UC%bsQ*4NasT&R5RHt_;^H_izvA?dzTH9p~);X5bD`UOT&~Yd2`d&7A=-ol9B| zn}0I(5~gwoLCsuGyXt+ktsuJ;LG-y3QA9@QbZ9}SVTgoIfQq{YDlRk_3%13|(1TDl zX^!+j3Q2DHvvf!rj2%itxuFn9KZ8RWcrvlrueGI>Qkv9AzJng}De3@Rc`xc#wVCy# zA@_zaAx4{`%ylh;t&411TM|e!0U07u)u76!4LE*gRoZxghS3B&E9`^ILE;i8?2TxD5PPYWj zBN11$Hmwm~3SU9k|C#H??nX|o4d^+M#%!pqPJ^%hL0hj?(VnXtz)3%*o`sI(2;`#n zsJhw?3Wb?kwBAtv0};S?bW<971maCyFG+tvg=Qr@voWaVHv4~--gdM&&BS;4^h)^J z4tkm%N8KX}nglJOrMw)`!~|mmGUV5x!M)I^YXoQBlfz_SsrKSe%Ct}ai_a> zx|X}{yEIo>_uuY|Zoj(@>_%bldav&76ZSN$YWVcQcks^yYo39Bdnk|_Xdb*0EFPK}dLQ~hnva-bH@K8X;OVVJZ8}rirvE|@ zQ#a0=QOqBxz#rt!@mGcG;x{Oo^s^qZh3ti)wl&l}!?V-7JZxlmw+I(VqvfMUMxBjP zqoNCi7y1^pHmX+CM{xHpMubI73{MEF7xs@g#Z$+#+ReCUx`=D4GYb*=1tr7LT|_8nps9Kt>ce-r>f8i&J@nm@k&)hk``%hVsX;dbR%e>RBj3fy zdk~422Zbpwlo(1y-m8uDkMvQhC@++K@^J8ys;a#}oa=-vX+w1wEZ{-d!8>X)vOp!^ zx5a?WAC0UCJZb8>t6u2e?q7@8kU1nKz$7+@EDrF_c^B#`p*@>b^kkas$_Z0>Z}zTw$9 zSrb7f9+s(REXv4ApPgPj{dk%qZA$7#=t`_h4okk6G$-lLq>D)tk_V=AO`QgIUDwRp zSuJvoR@-#iBMU0XjZkjQdRCM9Sm`yg~6!c z0Wi;A`ln;X{R&>zIR7U9ZNKJkk98Lo920yLtN_y6uFzN5#J@3H3X+Ue2C;@DPf}zs zitnmFV*a2FB8}0Mfg<=><^jn^*HTe*><@q*#1~5=+g^LXQQTF+UBy$`D~7!cTNGX< zVtqtP#LtmSB2yzPN0p6w5Lq|!Ohgx~y<6c8!Uu;zoy1e!v(26DD(R}{8~`QaNc$06 z8(S9i1TvAc_L=vX`ydXxZR&tH?0*q!CE*`Fi;Lm5vK-r+Ttv>cvN4eEzzO@SwjcDk zzm$-?8vaB!UPCij^S7bbAuUv08Y5l6lt>ZzN9gE0LAUR2C8$(`S33=AE3efESghZm z@jC}A>^pilo9jbhCHw0Gpyj#`=W9tih%SN(z((x9IMfKjj5Qq&CC;@qpoP$XAb*O#lcCbzGO`vt)A~`^T+W)1Q#9{l{s>D=aEPBw)9T(ZuTDV?(}ZJ`+Fb@wgOdl&HS%y0SM@Y;*Kv8AH|*VPpP)FoQ@p~TVfUljpN)Q}@=A(yA#@hh z%5s4#{u)1=fP%sBTOuI8gAhfCFu2Clp->FGb zyaUbaCRmZh!0zlXS5g$^g?b5jyw!AyF`e0uUX%&^E1{z4FLS)*7uzf2ytlYCpUNz+5V;I?3&V8dW#WcNP>?m|&j3p5Qbf*N>KXm%(sG(k$1YM?6c zPOhR%0m1Msh=vj1Y&HauxFwXQmw>VHv$jF|q?vGIG(hUcf62Qxa)gu-tc3MFc5>mam7xj!m%yx7q4umdd3{+4Y z*0Hvi_M*-b{zEESW6dk2h54J5{B|~xee?l zvK2Xz)ASbBUB21??CWS{vs@2^^rO;3X@oRHS}HvQ>9#j`%THuRsRu=+nILRFRm_
)-JEwqxxL1BbVZ{7LGJsJ9P1 zz@<pSgwKgplfzTnrSHuAmM!E}E9l~% z8k{e6S1M|5WG3E`i`)vKyUA_YY|XNjN0p0rO~Xms$yL;4bw#<#x|+CFy9D=YcWY0i z_l0*(Sc&i>;bkMXMU;x%6B!xxSJcy}>V?)6$|@9Fcue7`g_{??SBNQ;7P&aW6yDpr zz`fV`(C)DPZLygziKC&Zw4MzoD~&Rk7`~()SN4G~@Db!+S<*Ie;o~+`|s2~UCJ}k^BjEoect=tyWWG|f4q~tU7!Mx?3w0K+<&+qxvIO?!K00K)Uf|*>t&s6 z8E*d7R76yGKPP|#-h#|w?iq#Aqn?3N&Y{1+9LHZ;dw5zR6iF&*#WY!sga7s&B-d_Q zN3F1SL+yce@Kw35Y*Sh*NuXrLLD!{@QXQ+dGAdYpWdhFL>WGZH>)HB5nnH&{17$N) z82u_C^oH$aLm;UxhOX=vu7C@2pc!#<;CCjnn=!v)W9Ohhpg*IbCejqWKmSwaiKcg; z7kfk-r?r3uT!j7cM6QHc{o_y!&_h3mh6is28o?6$?ca?I-(pnO|H>Sh)y zRcKd~JL-qXcTf>o=eg^8;&_CqN!XH++n*O~Kmyd|FV$ zKO(R`cspbR@3w~aTJHgB+kDKo%@%Hn&rB!HlPyl`OzRhGX~d{AY#VLcY!_?=wnos# z$+Zu65a(`0@2Rfc?p_|hXR!BE$;IQRzgOYA;*|uOl@@bu;^B~h&t6w_+A$D{*4Az^MT$^ zPu0eN$hk)aFBOE~8L)ZnP{XN%x53Iv<)rc)O!cm6g1SU232&|h`faMBw=x>)DErW* z_Z9tOHAsIl3H>C)@K{LBqB|v(BoaSrg+197>^(M@4d;G=Uf>X}7uN}@fE6(lwUced zW|HaXC>g_iK=15)JQoSQAT!lZs2{CHjjSu^$#X(QLKpr=s|sETOb8SST=Vzw>%Nsf zt8W(kzghWdc`v&f99AT~$b#rM z(GR1iL_4GZD6*yS&O(QyZbY7sSRLLYtfcoNa%L`PFZ)_+JT&M(K$~|uw}my3F|C2! zxDK5+-_T=qk$%Rt0M1DjlnNlE_6to3?hB+L-retWLOb$&eo1ItHP1`SJ(_zsH#2v5 zo-;ocnyvv~<-p9~XXGxID$mtya4JP)S-+q&vLpMQ{R2~`m-&H0CX`j<#KxxErZ(nJ z=08A9erjD|`^_HZ2soZQPq`Mro^#&A-uhuj!sM`@aQ?OlFBEO&r|mk z*JEd%qp4$x{U6(U>k*6JJjEPt-fAjtI*q!2aq*+DPUt066H?KAQk37#*|}br^vXgf z%OP|M&8M&Rn)+=h5Z8t6`=mZn3)BY4<=xdpy(zLVXV5=C32}nQXbisbDpYLmV%^Td zM-^Z{Ek-)LxyR@p1UnO5F-gX6ScSdN#WV<=1+_TvBe*8~3O zV-pEW99UL&Vjv98XF26lXDq11Hlw>n7NV58z){ zgU0d9X`5S~flm(OJ zTgWZe&JRb<#bF)=MU=|+It~Xs+3E0Kcen%YA3eW#YIq8J9G(K?k%qfP_Zifpqg^kZ zi=366iH?ho9ganyGjv2HuDzp(X$y(0xqq(uEnb-u3pWnI3>_L)=)ppQ` zH3Za2x6t0ma(GZ*s6fjj&pQYcJV}^3j6}!uJM@)zMz+oXDf%vQAcHVV&<&OQXSxNs z=v}D5u0(hE38pwI8aKeAn93%xzeDdp;-dK)xOz@L$bIJ?qCPj7Yme^o0`?tyA2u(E z^@4nG7<;Y@zY_cIKK~GFaUI_dEa~}N2HTWfNiIVXIgY*r<+!-kUp=Xqm7(%`skfAZ z3_lJ2FYEAcU}WHjK)`}UNEVU`#_8rtsWa1RrLRrzlfF1DBh_p^VyLS7q#mSH$}36FiZ_Zxq8yZFbcr~?xWBu_{e|F`^0@r-=!{-{fQqy3(iT5j5Uj-g?{>9dCPnJm~x(S zW;!dlRPM%}tpkwqjWdsj8%_cjgLw6 zVWtE5p9z**N0J2-#f@{uryo*-kTXY;ABoyTCN^nOFe*~uH*lBJmar4M$iY-``UTyK z>*j9ZRpf8w-v9=p2S3hR0<=O;?s@bagQ&-3W%2}33>c~gV0-@fmsydV44ifqFgz~; z|N5G#2~3_3-E^H;C3tANLf?YV0ylv*OL*I((z%P*2an4`c~dceuH=n-b^=Fm#$6en zC#76_oTRgxBNMZ~2DU5KTGkZ>@A6yb=UaAIdRgLmi}HHpP0gE=H#To|-o3p1Jb&J^ zyrFqa?%CXVxhr$YJbT{6{0r8Zjz{jZ{>*UsctciCOonD_ecpOte$>1$*UXy*C-C}$ z6+)r-n53gDOP;FCQ;t;qP&HL&t50f{Xjkff>DwD`nItLF)QzeCq^eUZrhGJUjo)-@ zHH}m$iqf*}lBwd4K!fCq#*3>-bkbweEa@|86KQ?PV-ZJa<-MS@NgcG?moxeCu`zx0 zbhu5(7MSZV?W4VQ5b=+>-?*E5^xitYP5#dTf6x^=7AE1Kup`V3HxG>nZil+x7{AG{ zMGqo@W5R@xCh{iwF#eUXC-aFDR4MKl-W+~6fkt>iSV^=6o&dDCs(65SoVc|(Rm@`B z8-_2yad8j$a~fntsM<~#UG0U>w?Z@AX{KkzL02@iJ>_aNPn{y{CH`XUzgLoad}nA8aM4hr|3 zDUzBF?$j&JXSis8V{RlC#XH7IM>8Ug!dpTnct`ZZq~S$ib)bDf9JqxmYVv>dE%DXy zIpEVmd)s?fV)v2bq@6V#bL?+z3prW~KuXwef zC$}&uO*Tug(RvXpd}8JV{}+q|E(Q9+UE`hqjQ=6rHFEp}oKCX>je|3S>w;t8s5LOK z$A8AR(|f@4#of}acMoyb^z`uF@+}LT4iV9QsAu0LFF`ByHT{RX1SsIcK+wSno;!s* zp9>#XxUa9_&&G3gO7ukhMe;@ZO7=v4PjOl~2M#GW)H+QQO>2!xb3mO?6;st#mQirz zU!*@I8p#ZCA)v}?i&w)@wlu9MgB1l=Bgt7z=*UxK zGaz6}(R1lc`ZiwJ9OK&;nuLCGW9~ri3LuvKTph0vPYUgr$G`+`1iCtnYXMef1w9o$ z%y2}YZ&2gm#&8U$`xv1`NA3eZb3HO}A!aOaE>yfn>`YVv1n4Vx2(JoxF;Tr1sD_P4 zTYoNezSDf4y}P`9yn62o&s@KM1G#-rDYp(a@oA|xleKzNQ$DuttLtW-7+&^v4frjH+tn+9O$ZNlVZ3HvWou~u>kHZwnxzkpWxh|_lu+@wOBf6-Ib z5%Uf~0ihB(l$?i-_9WCPg{bvvA*#&-9;+dJkxt`o;L^PMKnNPq|7_=W;S$`_bUQe; zJf%*dHY|p@%PqX#L60gMpM5#9@jYbYj+i`jXPYzC6LsUwW4)p~kWWUS<5(Z67jl8+ zFf^z^*V{Gl3%)^*eGPs0y$!urJn5bV?l-Q&t_jZTj$+8VJ?$CDyx(mvZSQP3HVJ;^ zw5_zYM=sXc_Mjh5Dd>~`#WKwDC$Bduz)!h%av$d2&pncRBKJ)0!rY;`yK+0^Z9^4k zu&29TdecH{V^`Q}^u%9cb7^?V;Y42_2 z1Lb^FQ=jFuY#|&PJ90adN0ZgTCB7E5Mz&y!)-URX3Qaw@iw}*?i;N4`Lq6W=@9*pF zz3Lg@DGC?fJa@L+>#pEglP;qiC|dI{fM-x2?gz~xmykIh;Z852>lt1uCD?(LA0s4#I$N;eaA#}=fNIjm5k3iEm0OzC@Q$Eo!K0fvUjx0MORk4flVe@wz zE>oSt(a`)*EI2Os4IM~B|2Rw^jNa|I_D9@R-36|DuA{Eyu5K>Mb_0 zSV+rSi#I>V+QqTVz0}W(%ukF1BYF~d5pM>sFLw#_3L@-6hJv6$wl%Zl!&oS|80{J&UI6*X9JV(+)>cpPAJ0{X8@-@IIrYklo zRLZf+hsvbVr97u>t$d)Uu6QONE_cbs%ZkZ#vXZiDvNTz~bgQ(Gbfx4SP^pWBWdz6` z+_KyiU>JP`gJ%}_JM~e;+#n~DYH|sd?d#D&q;aky6H72v39==?YM%!j`)1(Xe|400%}caqI}&xd z*M)~< zJq~-OYw-tAxqBM+2MvKfzBr!38}2iRfF{ov58*xFt>(MvOZr^C^S=8&6V9M2Fgp+p z>Jlc zk1T2W`=h z{;P8E0QvzLh=Ez)scwWKz#+U&p&l&4=@0(sH_V(xz;01Qm?I!cf`K+1%*uy^2Gg1M zWFb@)XQ)4vm{tMna0sj;C_0esNCkP9SVGJt)Xk%yA{{Ys7(56wl7F+q znYCag#?To}jRt^#m=_rmsTT2~zpE9tVxJkszUc*A?pFG}$i%z63h!bM$Fs!!m)q(( z<{Ia!fPQ4Rv#-+#u2~~TzWu5FrhTDZX`gKSfu4l4&MbJAPh%(7+|t2P(-O|Rowqe_ zLf&w6!s&T?a~tNChu5t$FPOjB_Qv_aTRZeRRw}uK+(i%O`shW}A_81>=m%BC4)P|$ zA&PL137g7xsG91chDWAb<|F3ErfSA!`or2SnAz^v4A6Gh&DM*Ii%kd3udA1v(%P+o;?04(=RY8-AJ~B*+u~65SFH zm$)R8rCOO+mM=f0r~=o?zf@;bWq<`-r>?F30IbC%^iCdSALTVT$Cm*Hu#uvu!X|$x zKL#YA16+dA(of>K*Z~^_MfknIAxh_3>F<~bf5vQh16`Uv1SP5+q=P69?T<$|eJ=JV z5PAVN0akEFFtMj&I#LTg^Evhe`;ldUTB(5FUknGI8rZ1xLsaa>83&GCE=LbedIPX} zv*G8umJE`O5o`BRM-g);QVOVyvBVZ)7?_fKi95jbHzUuIMW|`W-bLV%;j@{e+Z+t3WAMaC7Jt|v1+S$>)p6}iLrc>eQ(4n{1FavdRcl(SN2w{zZ%qqb9fQua$$T%RP3r5E zO!H~eC}U8+O4n06Qgc>470AFrn#Y|d?hCI;DcU<883= z!u(RgTA~b~xbH|#NcYLcV*-d-v@)ces47quQj^%b4O7Wg=agfBW6V$rfQK%N+qDKP)l$osbsxmOZHykUTj*V zbZB{?LtuMwM&y3t0I{CeNBmyCS6y4TQ~ybC(+$(+s2`}xs)VZLs{QH|tzQ>24UBW)%1DMf*_gSdup z1pg|xH$9EwL4B$rp3+iOeNs;BPyS|p#~;8cMHo5>5A(_Xs{S}ISVw);ecQ2zEavHs ziF_p&>m*%WTwh)N-5=c=PaDrZPmZUAce?kdce1akzh_`g@P3FJDIP5zGslU9EAgE< z$Bs=_h0;YCIB-p&*KpVHj__TAE}|3S-;%hLlFJnW#{9^(5w ziFS!x;9%0@`EYrE9D4^;Sr=dsMnI!-IWj~VFno=1ew%}ZD`$V<6yIW8Ol6$dPi&>+ z8T4KXFyQ!PTb#UAP#ofrQ;~f$psbP44rUW@lw1eI))1WQE(}z(n5&6Fi5SjfHOwn3 z$HqrjNA88)AtuNM3jDu(rF@St32f=*c<!*#*=!QrugupP86E?5OV zZavGlykU95ykEI*av$aH%&nGtI7gY&D|^Eq&Yw?No&GG&?vi`ia?)DT`NU%kybmpc zpXh=}oA8$4DgPbJ86EE19)W*iXkP3qOHlc|ZlWB?2w7Nm3AiJbbR8yo4#_8JJ-I~@ zQKe`jx*dic#;8$m`f40(q>Oukn`>ccXSi(WXKZ5XY;Kz(N}Z8?C7%$v$wn-}R7zZo_l~<_&11u( zJ>YhDBiK7Y`X2%fUeP1==sadj1|%M<`?-6MyOTTSI^vq^TJ5^-k^-X;aWC`K@J7A& zeEaS8LYhrj9D$+Al)3@8r^B#1KlIt3EdDKU$;SP(jL+j z(ri+5)csYDlqG?Zj>v1s$6;@hFR3V*BYqAh$Y5+we)CoQhP;v7&ET_X!7JyJCy9>G z-I&hdgM}4AtrOT7>Ko}2od*12+i>Tg#vk$Ybgy>>T?;)L|Bz66>?>0O+@w4% z#jnmkg!*O|eF_ytIqE&-rzi2M2?~S*#Y@5FxhOr2t?2}CdGAYG%S7P5Whwkh4IJek zYT9VGX!mM|!fSnyrj44bI;Q9kXMusmx-kf#Z84( z`Bk|ysZ_Eoy0;6QEDjHyOYKmM9dDN6SEQe0pR<h5|nWo`62s0?5K2!NQ@Dz^dxPlf(A#pvcEa$LQ~9@7VR28!V-CpgLE?lkp>o z*~}bvKfGa<62;I#UWPl|FOmd~`2^LIuFkE-Ys7CY=nN+#Em)UaNpno2yGSZYXi1LP zCe}*^VCLRl`dd0c_F6{DL$X)0WwN5Oo6-@|a#ER8DJ?B+Ass7SAe|!}iAmxQNk8xb zUx|JRZ2|$d$~SmRdDFl-zsP$G&*=VO+uP|cU_qaT?vWE1W*OLPF3b<(@GL*bHe>HG zTqYw?CEhKz2i&ZCk&EDIRft}WHi+#8FV&8yIS=f~HTc@jNP~zV;)J$|JkmC@7d)AA za9Ca+U4dy=spwbuAQz8Nk#IO3)`t2fmeAOS;M0!W= z;s4kY&4Xs9EcPneE&3RLcS$%L+7cQSniRScQiTVG4~HLw&%+Jc6KaM${y1RAK6#z5 zvMo7BOikMd?9y#S83NIw-~D5Gh%g;H>eeSy{N7Df8sphXZ|#9J*eegf(Au#vMlZ6 z-4YIw9F-MOL=-IeB6qmjQxn(MQ_xlmad%v;Di z&5Q7+@{0;g!p5SR;!~1WP;Xc*mjKalQc<8NsT``js8oZK6;Sn1A636ne*iyWt-6c4 zf?BG!t3Igipwro`>Wd6MTS>u>UZfZ$&jhwGRa#flLp({e6fyHYpW+XOJ9T63b=m}V z+7n~}IKC{D53{gKI}yJJADxcTSCKi97MSKe3$FlzITQZgM}w7v&jbGidITy3BL4eO zOBo8y9HF1}>HW?82mK`iCjzB{+kv}o242HDum|^G7QH8QHxvog0fSHwSr{R}H;hKd z#vaCGK+D_*;`(Z$9&>`>v+aTUm=29Q3HzK`2=7%Js)nZS}3g3wGug&aam* zFIZ;1WFO|5>%A0M8+J#B$EU_y#r}%$f}^};TwCpO8)Ln0*SSyn%SYd^Nw_PP#`V7= znJykJY{2i%<j{+NIi2+Tz+*K-cZlXtY9I8GU=hd85v( zNO_ymJ9T=hEVWKbE%O^AVNmEQYZj_FN|E9UxKCZdGHIbIhKWcW^(55;MMv32@lL@i z?mcoHv;#YUwLcvwlYcO~n3UWF4_0m51=rM#fuFwXn4y02SUsh^!@QHc-Mj+tD9lr{ zFu^+N?1|SD=Pu_bXF1mv7vma$Y+lFn!*j&D!nf4FG%znXCDa=XCm|+7&R8&Bn>h_N zKn{6~GIE<~Nbpy1dWZ>44}T0RFo$l53Cx(t(8##R zrpOOym^_G1jHO}z@eka;mqSyi1TZ?opo(w+8g5c-7Y_mNRskDC1@zZCqnoP9j)O`? zN#yTI@n-S1@qRe3|3mdUCUy)w*$!bMbT-h&ANAhxoN}LZ-F12#6&=&;Pi$pui-6s~ zpZ~++&wG=*J?BaGu53D|P;OBR*E+$W^i1)$3e|`_i`c`Kpv-^Hz0#3lyHy~zCT$a4 z9Dn`DL1q*A1*-a+#3V2W?M2@O3;73u#*pzF2}+4pOPa~gDSxZ;w2k!|!z9BzLn8y< z;L$tv#SMoH+l{wPS>|MlF^x#CpKeUwoVF&_XZ9F*2Cc4~X0K|g@{OXOqQByz!l!r# zH9i8|un)0ju})D=WKXDAaJv7pw}D6G4m;(} z4vw$(v39=wneB*eHC}gZI{eya-|uMPJniIx&AQFC(ly;R&vnI>h8g2(&m(VX|IR>K z=vKIO^fEBw+t8ma=aeGfQ)9Sac|`?nu|xSF`k(liI76~m(iuDMdvb+xri#=|(mv4r z)bBPFG7d40HV!m4L0x><(8iFj@2-D|Q}`1VNMUV?wuH8}ww1PyR<1pv38{msx2PDK z%GI)Ol7r%ZM6-pn1>^a%c-w%qDWEE0c2j{o56!hH*cO*g)?#Zi)e`AIOcKDZ)DEu+ zl?;V~e}evC#n4Plkk5u*gmOY}5c9`|x`*nA(nF$9JoqVi9W0aVpdvIJr|xigNThkR z8We#(#CxFkQG#py4Uub5qI5!$Fae!92_4&9Fh9qEu_S`#>k#PFZAhL+Z?gw;{k~93 ztcSe#64=d#@y#&;Jc`oD;&AibZH`O$)G1fA+Hy$yL!lbZp>YB7i>31_)7BUwqlkqW)O*v!wpTVJZ zsmrUrfN3^Y-c4Q))gV_s7kr=6k|m;E0vC50WgxB z?FD;yl5)2yUtLUFMVF$t>6aOP8xjVwQE5yVJ{mS-541_|(lyX+)-swkKsS`q)YY`t zRMq?fFMp?MzjC>vja-WwIErmv8_{&(PQe$bxOL=B#yTPJk&q73`$-z>E|{MturCgup+;x6wP=)6kuCZgdp3 zAGVe)@LSB5VR?6Q%jRy#5$0^lcK(TGW&OVX>)p?hKTrSM@~dW+J$s0yv2Bn`E48cWfLpohoLvr2blGV zU`y8qopn~|aA1vZj%T0C$NW`lZlYt2IKe%%IrJ;Nn~!Pvz(+&IA4&RE}A#aP7XF>E*dW!Mb{ z;1Jz2R2myFp_!nzsG6weD-S7N$~`h#RzliavP67AWQCGPF@c$%0CFWlm8IrldYlOy z|6iCC9)ULH2q-PTVgiXmiT3ehv5J@zzlpvB&arB2N$fi~neF4P;uXN(e+<^hV0^te z(EJNy4`RikkZ>s;i}%7TN6Cy~-Y`wzq)`Q`mKoSCug6Am9`rl!Lp4*Ed<2aD63iMm zvaeCUw1zV09_(P|A>O@b>##GK4T%f!EL3nQ(N2*Y;o{+yP)l18lm{1sh11D@3CR4S zn48Q*x4ObP&oSNJ+g99~lYiPWKd)16=^RydV9k4khQ$5WWyi zfF{BZQ4#3s+!j^_s;`i=jyy|wPE!&{z{=+KsNa~BCn+UUHkrGc)6MnGF7v~bL#db3 zuBNxjSd{U1#;)`gY1-5==CelHFh(cW8gXA3)k)PNRc+urXDL+jQqn^rH@_iw9a)ak zo6TSb0IORqF(I)v(IzoJ-Z^$5vLVzcVDQ0`$+g9C+U`Yc>u2j}Yh~+Y>usw8{7-pX zHCun%6`L6Gt(~K&Gvxg3I_>`3Q{b8J4SRe0a(pZOeFBq%k3w}KdC~pxZj2fHgMDOm z`ZsqG-!3RG>LP9=iAa_}Cuy=QAX_URqgbu{pemy2rTs^@LqFc&HgrPter>cF6{eP^ zVWwWDbkhlA3F92YExk-X4*7MwwvD!;)~i{ev8Wa5QYy9brF@NSl5~`$m-uf{IiZh# z1rvm;*v$>0qQDD0AooKpdLQ8gHEAA^2R$TnLZSbsW-y9aric?fp}XWVw8z;3B%d2BgfkY!Kx zL;|kp8P-L1;%yV`7W#yTg)apX!B&1If3mt(oReEtEPs zrNF$^yvob~lb@D0FP$vZyRfE6#UjzdWeT6o_>}fD<$>vvAqqyY3f0aQC?tH<9MbVv0M zvC(dABFtya-BJ>Go-)!JrU}y)rru3?WBzE07`r0k5kpVQtXQ}h}%Fv(C`-f04?kBoZrxdP>`p|6sjrJj4DCF@rj&8 zOye|7reQA^z((X{GzZ(@JK-MTe7p-5@1|aGM_@lHxkBFi?sl#Rjx_rus|+XSGcxOj zoZ;Cc{&dX}{eJ!P#E+5RJAAwQb>r8cUu%D#{8N-A)<3L4s9IV4VjqrB~Ee$~7_ zInA>r*_xc{dF=}7I!<{cK}TdjqFj;#^y5kL8d!V(0BezlJH+M95%d>VmK{~l>ayBP zx~KX{hK+`u2A^TE@o!TLbN`fksa?~bW|S)2xX9Zg*+rHWIbC=vq#Ku~HA+pIou(Fu z51mX`O=@$7d7o*Iv4vr>PNZp}+#pMeZ-9^amgnUT26}ftkRx5;zOs;W5zdN{=+*G* z-~oRTUmiI3#oS9>*-pKa@3?N8ZtYvpH-Do=Zh4sZDz6&QJY({s`SS~m);(4Uc95NI zBW0jsH=ePRX2R;Ut1^b5D!Toq(bVuxRe08EC+y{5md~!4y6Yjf5@m z2yn3XlklJ;+CkxMFqKI?hmL9zaTg9ioNVl#&w`WbfevsFRC;~Dlo}t;h@XxXifsTd zI1tVSCvJE^=_hJppdr6v*nu=dz3#_Ej2H-K|$o7xz!0Fls4vsjf2Zro7l zf>P2mk_D0;k}RnAWJ4LD7q2{A+rB5iGBpz4V-LaBHb?q}SD@lp3@zLhzEejr?Km};X2`33pCI`S7q>08#+%w;gIi01w)H*oN;bY;|#htN%sO{%Q%OmgF zBmM|K%EJ{nipj{Mun~xWPr-h{v|z>H=3vp#_t2T}_(_&;wi|;MPuio z3pNlF%VM#3EEJC>9)q1FVz0sTy&aS~jxhnIA5{L;$(q8;=`BOdOq|3!wqfgBS(8DL2TfHqiLqMBRh>DzZ2as<;n&kScb}FJv7-@0{8KP z(-6KE^OC(Vf9i;dz)awmW}}Yj2wf*LX3_QV^Ao@>X*dI+H!%dLzenT@stBB4N^lo) zuW>(dEzmqp!{qoLuQ-1@-vDht160SGf~PVC+INP;p4Ex&;;<@6=Vp1Fy$;9== zBgFH>3&exO#l-JL<3$3|K4Eoe=gt=t6}-adD8Y{h9>kFAWNOV`c;B5emx*9{?#o!h^m&Kcpl#qUlm^oZI>s|I50y^s4;ZY6p3%~ zjfey(P=e&dRZ!I&0oHH;lal9&y3A2V0W9lf;Ad1xJ@9;SU=mn(sg(kza5M1KTBzl( z=t)uHh? ziIuQ>!r~{y$JEChYJiCT8cI=c?Ps(el;W(hYVifo2Caa}kAc|( zPm>31C!l_MbG~v~;~keKSCZdJ12ByPfeu(k?V>JGZzww@r>oL^fx^89=8c|Pi`$Po zl{*9Mt2FLAdJ3(e4}+6^0XX06=5Mq2zBDUU}7C%Wk9$lF)5cM zwm>uTNo*E)*kz#tuLy{bcMc_&aN3i@_jUirvz+*sEAJVs$0# zDo+DjFbtdfX3TwHP9L+FQ$SJoGq5htfMTCbo`K^}HkpKu{Cx1!R>QNB!+XJ72Da%P zK`r4n;cp>Nq!XF(O(oKbii=u^#)>vW>o5TQ`&4m?SR!^pS#zUkl&GPo1pX8UdP6UT zJA^%iq;RXC3>1gD@e{m5P-~8HuW}baVP3?&2UK!VItSVpO>q(@kbbbg`S4h)$+1C` zt9`N%cxW!xj$PVs_7%JYc4DsE9nK*V*1`OSmYNN7H$4<@JN!5C-OQeaO71(>3S?GV zvL)tlhv7yLO{PPGz8T`daQGIChu_60AO<_*2`$4(0iK%1m6md3co9(5e*`C!vCtw4 z;@nPz>zD}I3@?$ZXEF`3_k9MGXW7I{#8Crw&VA9NscmViM)wC1UmhF2V9An(5qP)UK`$nGv@nG73wjtMOJ7#QuZ^+08`l#EbYibaI@yHI@Yx-Ed4CFBC5iR$wV8H}ml92V=jn z`MH3zw+q@R*P+1^0itRM^zxW^M<_sr6Ae-EeEp9BoP{UnbFvo)&f9p}DY7;A6KBDm zkb?)Z7j9TkfuYObe7xl^S+HJOVt-a48&+SBD|Hoj zcqY{Xto!R^U+9hPhyJhyTI{Xi_7Z~%`%`egmVgiD$DFAGumioJ+MkJO!N2M!y-_9a zgd)H%=+z-D!DrBdpMOfc#y;@^vefa!&BV`y9BPb{m?J+~yR- zb`6yaq}&XsROrbZu&$;M)ro(dkygS-hebYboy-L;#Rr8mKI)-P=*(Z^d2R_E^lPyx zv8u5|^cB!4E2G1r^`mm^0QLjXUJOEsUchnjEAM{*KVSX2j z>EiX{qro^30q<>xMzEim2}J5-VDY;`yGn}8c^RHBy}{-XQ^UZdY)N0Gi{jjU;b!nU z@J8{b^A^F|;}Y)|PXT@Dnfyz9JCxoP05MdP#BeE7<&FfQk9c%){*Y67EqremveQZj5I` zHDr0LKeSfmu^-X1(2tuE?G7h}mOv{^jUJ8Ku~At9M-MahZzB**C%}<%2u|SA_*qmB ze`Bs)6uf%|PGu*-fT@ic&|&x?v2fz4fLfp*oM=u$L%lRHm3T>*@RTpXZ0aOB^&@c4 z*+6cBs3RJMs;FJVegLv#KS(5y#+h)0e1)XeS1u=qV=?lg=rK5NW7= zZbCnzA3U@eI0M~ck3ya95?p}tP`AiYw;7=cri9)E%R1Q{sG;D8?F8%fGguxP`Y*aAJ(ONXAEM9T z`PqkB;U9WBJ%JuTx1!6^VmgaDh?>F-H<(3m5sVO5i8(|I@Dy|4#WNjw%?55p(d0F3 z**%D`H83GLh`z8Gl;7{fSH}k;GN|Hq#O7_7hqpuB?*{5*DbOM-ezvJnRZH<2muP!~n2dDEP+T0s?9lVrOaO)h9_kGU;1RDeymD z5yf$3zmlbaY(59w0~u2PVt2OE9|xbbx;7U#G(RIs*SqjCYhQ#NR$)_|weCUm}e(C94(ouqLI4R{Yj z;%U%AI)PnD&sb~BwA55lMEKArDZGbf_1U#(`mC-KT$&zreISSvqH25z6>%de4IPLbun+M(?8IjK z7+wc)MOHyUaWNbP=Kuq|0u%ZNtRG%%J)uwW06N;`Ic-qsOoYqRR`APS!s#i&Q3LqylA2|&Sj1A;2JVk4O$DBZ-_r$4_L4E!p&RsvEHF)2p zaQY(PTU>&FRBv#_USP}F3A!m%(hf}gga0z?KGf%}pdiX%r?3NhLgk^LCxOD1263Va z(}`ICpE)0NgPNkUnFV#U_3SR7@2()~G+nfOMY(-q1VQ^5mhj-fn z%pw``&MPofrqUPaUvw0;4hwEOfxb+`EseTzJiI}EgT>quelxRp!|`KrXdb-a?&Hn{ zE4UN4A+*g!z_}j69W&AQ@qBSng^$3Ua1-}|M%@Tpep`4}THpXu5&Mtk*na#Cm!dJ) zz`cQ1bT3pyC2#^`P;I{sCD|dUg?xB==D_2kL`({#p*w2B{zVz9g6C>6aMSOw&7h>Tnf6TpkmQ%Xe^YeM}G%)%hBaNEd1WKHl}obaE#gF59j zyuvns>oNlzt8VaxD}}E02j?a@gj3+zR~X#aSK!sG#s4}CRZBE8*UNp1zrWK`o~KrqU1%UZG+gi>-Se6Gj-!_>3+)6A?v_M_)D}D+d0=>}JC7=bj8@iW0Vok8wD-|mPEx2m2 zNu{@9Z?_lmK2H9r>Zd(8n`_9$h&6+O`mRA1Cq<+Sr}Q$;#YoIf zv_w8U=hj1mvp=GL6SzCoh3jZ7)Ezo_34TF_-h~=*4x+?VoYuL}&Rzqq#LndI|6co0 zhh0P_eh+U}8jhqb@UM(T3>*vJmG=MrTQ%@+)j{{ymeUKrHyn;EJT4onu4FEupWw48P*p1qJs}OesT9y0$^eqMGdkISwU8+M58d!74x#q7;t49j zX@w`?1T@r)cuuzv-%;PRMeff8x-|*)nDTH|_?zm3DZ?I27znxsJR0`U4`>(71D`I4 zc=!^^LZ|8D^e%cW_?8Rl1@vsZ#v>;eq20J2lh9uTfR|l@cwYy;!~r;q>>(!N#HGNs z?Fyo9Q|Q8FqT?|`3u`Ri{c9+ocEP0DhPrHNVhEG~OF?7b3unIPKq#Dmr`9o?rxW;g z9_Mm@d>yKX$?=guR`mp~Zv=jIApSV+!QQV%Vj$w@RcNtB5_%|pbwpo%nz4ewDby2qbi~rCT!!-sUF5zc?5@&Z}45tfm6;W#KCuP zM|leG!vyc-nfgv*ktgSkz z{#-aW+mjO!YwBR`QVDmz30zx8K$(3BPT2w|k9EXkAO+Q*js1gHE)>UtxPuy0VCDY% z^9|wm)HgX2=W;o^#Y?D@KB21#BndQn0$kM?=Ey#{W^v%*TNr1q78I$ffa_>L|M0JO z;w4m(Gm!UdBGUSBMXn+%Zh?yYQk=X^c&$aYAB)ph88e{(&enV8E@rT+nMJ6J)-by; zw>^d3z)j{U^BQVZkC{8nJ>~`TnaP7cl@6NTwNWRI!oRi;r}+(Pg%rHsxnNO#!87&=mvB*_8uSmq?*vgl0y^g4Se8xz!l^%VrVN;L;k>hnTEVzMirj< z-?iOO9-1wltwf8^w!>XtuIE)jX52rAN=>~mic_M;o$@} z9ESb!7gR_sQ5~IxZ?y=O5&WT%U2X83Y5~=pHHdPzsn=jMTd4rWV7`}ur>X=h^)hrR zeCB^Y&!~(JBKIwZN?BvX5h;|(f>3Ms;jTt80aKy}tBI*V zZ@3swhtuCSOf{~c68qPGvpak&)c6}>ux~1}eb|NI&7H-k|BBQ56KCKiesvV5YdB6- z6P%6-VAh>yKVVX;L0^-B37iHFlma*=J5dQdXJ4Q`dG_CrukrKicwYpi()3XE_UAL|^a}e}^X)2X#*xG}1<*LcN6f$aCc3=eVv9$=A?V`wX`E zXYvR60g48v(f!RQXOWZsKf@FSw>^X@=O)y>b%``034Z2d_?ON?Zm6T{(@v>r2w=ZR3FDl+Re+_A#APRmgr+i-2G;FOQXeD@))0Fx|?3CMUv zy6gWjM;jBfQSF6^TBrv0;!}QuQlpdfL#06gE=)PZ|3R3dti);Dh}^pX^}|ZcVHO}K zOvm^0(O*u+Ssexizs_Ly7olj%j%)K6jQrc^l9%FnE(v|fuZW_{Q4J0URl<<@Ta#e1}PdJ1If7 zt%8VFgkwe*Qw>?9D=N6!P!?;1%-ak3wl(UBWr(<+I5hsh`pETV2@&DLXU^h$M}@`0 zORyPSM2BIrwgj3MN69!f2+nF-P&rNGR-jFAh1rJ6yffbSc%naejGxeDU*Ob-bHfnm z417kX;=oQYihTelF(xiUT^Ebj14cp*4y`-ZEM5%y4Xe=yFN^A<2cmWUQ#3V#AGADL zHd-a7WuB8|_!os^MLh%ysnq1&gaY&3)iEu5k7!1{$M$Fw%_sMxvl@lks2q`r9W9R- zj9MDgYMk+<$XJcZ8*~#m#!0wl`ZTc`nd}2+EHZg-Qh%)IV?nE0g6QP>Z zfGo`U$*hU-BiBNc!<(ZQ<8`25eG`blz41J-z_LTSpxe*$8v>hxi^DG9a$=EAV9_*+ zosMe25gU#Th%mAuUJ`MpKJx>JrE|e`fmb1UOafh=^PCRE%VYs_5O}hU@fnF>$=y^F zej}knSYLRXJCPiNzjGi#vDY|f$=lEoK1*F8hM~tCLe!#`aOdy`@$2#~(=W+xLVQBc2q&^ZlLpNUF%{$>(5W4P;+JndMt@ zD!R>EOeS=WzembPtH6u(J^K|pAA^AHt&%iwW-t|^S>PXNBL|`d@q)w?MEWj zJ22w60SA}`Bz*sPesmxBLM0Pd83kttqmPP!8)u^Lw;cbLXGNl7eWNNl1O z;2d8{^1yxVoh+F=0RCZ9HY;8^niBsBjBlUhak4XaAbo}G3`Bo7puhfR`J9S~yISH4 zl*G$&HWG5qDW*GH3!fzw&V?s9cZmsP1~rGUv2~ec%p^=|B5;>G1Yhh;cy7)m2V%aY zL7jS)trf*|Tfc={239VWSXFTnhc9UZ^M{EMJ(#A!%Q#inopu`O8;&xLQm5V&A9 zWtZZdlqJVe^@!%lROVakS$qLA5Z7l6DzQWG3hzR+O*W3#h&GJ%WYRd9s2uKN+Pf{; zl^KV~`2m>Vo$(KB1~HgifXO)~i)?4+XW~-gAEpFnBy^E~a}8V{`HWLD>0vJ5S zN=wL!oK>j4ZWA}?7np>$=6~kGKN~eb3Qp5^&QNG|4n|%41X*Sevc%YbUGI{EkP{lA zM@S}jVp~*!eGa~Bd-R-lna$Xq3GwdS$Ql1j!gn2$`L>u-wuIMuNm55TITtXOYsAbz z-wBpFBg9=tCQB0AQGvVB?ZOcoaVyR~^0sjQI7QDc} zk@u*@&|Trv5i%7>mfwi_Es`F_!~VO0IY)Gc_VQ5p=zhf{$G~}y>cY<6;XI=*VsrGA zVmbH094d+_&J&!GHf)^plyuNS-v8+SL?og&2^~m7NhTZ&Mrx6p?RQ({(cxfmn7#Kt3y3-kW-kPN{xUf zTT^N|W>6k5NOmN@FeSn3Aiyc+4^?z!4k~Ay zqJ4>)aIt9!?j4=1hMH(3yOIf`b1BE1WbMiSL8nGcB$8#2oen2sU^F)Ze)B5R5MI^g zI3J+zHJ8(ps0W3Ext!;yzZqz#ClK$yqgq)GpMpDISKxx0YZYv5TA}KZqSKtosRZ}NDwyG{B8yU1ayK!8^AVhsL-^{y z`eJ2pCQ5T^pxYkKS%SKt40a4_iAuyp%%`PzuTq?`RQ4Nlo;{PCfc*2Xb3t#+-X^jW zncBdccTcQhcA~2sh-lFkS$OTgXA^T03v(A&;WzH&M@-?SCzfDql7YC^99`%~_!B&5 zN`sx<8lA-usNtSrizWG}&>C=R1JA%E+TnW7PKHt4onaH2p^Z%sp`{YTt+cwF}z2~0a!54SIN2Jn!FJcqhIhYf@-Zw!RULAd94bXTV zFI&x&b23_#J?Rjm<*~Avbp93S;=)7os8J8V!Wh6;%Y)ygj#Q^Fz-|A-KC1_rX(itF ze%WR^!R+LuL#XgS3sskGp#r(iOuZMcH-@f!KlSfPYT+?t^&`}0nV}ZMb6K>a%Yv2& zG6O$ItXvJ<2PsjCtxpN|(%I<=&2SBif?!=j74;E5K!_^&0jJh|IQ@;Oa=-I854i8L zP!amL|A??SIzCr$Jf}f%a>EpQ(Q)*gI(YDh&_kTeEW(XrNoV>$J^Q! zZxY+nYtlld9|ORzE$1wI%UvkVYkGy#?KbM{d?=f>W!o-rZ~o?4_>XH{i7V41^o*Em z#QPe{_ZULY(f_y7)DR}vuR?z^bu%yxsw>+}t(nF|ZU~)4vUE<`9n8n|I>5=fo-W&s zgG(#oeIS+PZP^dHhYYU$Dt>Njb_bidUKi0ZJ;1c+4cB)nRrje-2*0nf%o$p7-QIxQ z2@#8DcxN-Ro_#c;Q<<+P23v9EhtL^Va5nD8By<9s&;_zjvV6qP1@QM>!TR(^t)Mo! za3XP@O!i+Nvhp5sGC94%T)rPO#BZUuvV-Vi1?gqB(OH(3KV>^KkBZpDJU}F`WI4@5 z!v}mCieQ3ToYz&0tJR!WIE+}>11@JF3P;C?noe|z|ME8=>$eqi> zT21@xqbmjR`LaM|>AWhzhZAEUy9Cn^Z**kh9(3!I>uel(t(_#2mXu- z@oXk2H`)7mgZI(e*$Rqi6nA6;kc#66m{n|+4`7#fk!*VauEKsM zm|1EQF~K010~<;y@0f_(A#yGd*T5`V5A%EqfZo5OYbmMBYqg#1Ix7#v! z5*%Dh=?LdY1@teY|2ig7{hMA$JlBvd%Kaii@f>?1< z$q(b|ykibFPhL^}l2={jcih=fbK4%O&-r-Zg1tiw&H7K z=u@8{>gIA@7L!HEE|63AadNcey1ZkCvW5Bl8M1m3Q?2U1cV;hnhj)1vXURM~f8*II zoZ#QwU`jiVkF1GpSKe#8&>XtTKY2w1cv2g44O+_P@CsV;RoCfDR`KgZwo1>~0M};{ z5=&ms;?v`d7#d5qGjsl2AR}#IDxFHC?Is4AFyRZ(M^{C?=?EDM6%}x2h4Ijy$9H?l zlRuM<+Tl<+GQ?A&xCOO-1lfNHf2!aPUSQ7qF1VMu$r^I@A*Lg#T+>oS?+GR|XV~)Q zK%X%Q1^95H`7tv&)~@fIX?k6>r33 zbrG*)7WX>K@9{EuDd9JIpf*?JZOFs>)05ScxcgwtnEwrCV%3$o4ROh-RFFO3#o$d| zX&Rbst2wz+h?z!c4kYnvOLJD#C7ZZ-^(}Y;1X$N+@mqV#{`ML3z;n_^CPo$}&?EW2 zHF=&+Fey6Aen-c3s)=^NV(!r_PMu!7zFTtk zekJEwVP**9*e~rzLG3ttYOzGk7jndAPJrXw(?0y$1n$TlV&Eh-czIb@?!Y%$9&mqS z$fY;fW?kom%If^0E^~oSgyKDfeXc*q^;ZS3SU2{h_GC1aF&S6C2@y>_@XOMg`=j zi2cE2(njR7dgShH%+eFU0PJCgx`@qjA!heg;Sr2v%Uu)2;cI;L3O471neW$Tu4Sg{ zD2V6wAacrXnU~sV40}5xzVO8r26n{9sFMDZyW~~b>~-MJK6AxOg4^`Up36QmH9ODQ z)sr*1f-IV8^Dpv`hTL6~ELDj*WHo2Vc>caRdyYKhx(&R(Wn8_!oC0NJGP3RprgO8I z^8DiCGcoy*^CN+H%<^TfOe{xJ>q4I=qWdv9n?iOu!A}->4Y}pn5@cp zx{}@1dG7Uf?$mCc{*y$_9De-_erhOZXcNxRot%bo^5VSf(r|jh$Zl(RjgvXaYqR$= za1u5o4rX#*<)@0i6*|aMJcJp1TjJpAZ%x$dyx+D&S6{Ap4xX8+bkQSuSF<=@*O4oG z@?KN;=`)Gz0X!E$`WwuYi6)7TBZBAY7*}Z=-Ri$Y>tm)#-^eM8h}H;B(nPZM2vn(U z!52Jn)0p0M;nx-H+BY%Nv<3^1#meyPPr$MDHLvd>+L*bxp52LoqEtJ#;rS1wAIuSY z%Ow9PS)(``(|nvza(1f)=sQDXm#(}QB~!C<)J%1`_j6>+`Rq?L&FAbt!Fy@QcN1j} zHmv_qBb;OAc7#l}k?dd#-rzgmVn2I}=lBKHZ51+1eeUE)VtF@swWsW~zJwle4KA|T z>PRg^ea5MJmv?lON$*BfI~wA2dq+CW?%?B*5 zt31(@xIeXIek$;bbLX?ctX{4@_h>%vE1i>miA>Gb_c8T@Mp1@s zby-D8^p{^S-@V13E(4wSk+Y={=Td&Y>vPVbU2ORFbN)Xe3f~ZsXL!Hcc}2~+e#NWY8_i=oiQE z?gd_X2Trdop;4jQWHo^~gPHr;niJ{-=k8DTG}$@vDv;ya5M}L%wFX34Ce>ptB5nvz zP!i~?NS=U-Y?BUg*M{(KT9XAPa8}A?X0|((xp!GkOP4s$c5@o`B<5BVCwZB7Z{s=Y z$)39lQQMcyF^H<{{_l4`lq`0e$-`1A-m&Dr$>iy_XlNB<`&|rNg`Dk=fqDL4IF)Rq zE;>Y2lm^Z^3yai`Sp0+6u~K%4d$yUK#w22A4ky$g{;mgEZ5>fPnW!krYb!15%+Jos z3Q=@4&w1W0JWo4#7LurTPIHbM*bH{zvnJg}MS8j>e3ap-jU`tfVnT6(om}hRwbTkG z?0bIKVzs%e3Dn@zd9FV5w0~r)^f&MJD3!qvnVs)xk*85(c=;(eslnm2kxRak!zK^~ zNG6acPV+ivac>4t8BYXTrwH8u|B?hEvmSZsIQOR(SMV)$XioVbAP8zP5ss7Rkq61T zXW6M_WxJ~M&Ch>VbC5t!cb3z4D=|5PXT1d<9XLNH(=o5-r=8?o z+$EE`IP=1&_Uck^+FTHb~nAqOH1h0HV_kw!PG1ucDhifbwGcpRImZdb%#Z ztH%au2Cw!Q@fHe3)757o;eyn+J?Rw(v9Ze9%6B8idvZqC3i-%yRjH4PQGqStiku=wxM51@n(vx7Xx z{_MFTn^J~e{A*@Jj}!+%|IJf0RA>}7_QB7oc7KA8InGq@7h9BMCZsvp0F_ouQJmy^ z90R!!#TI>#ayKab73@mpC>O9%k7H-j7j|_KPUkA@SyB}S@H9P{Id0-(jq-@{GzhiX z>{^bpMSrc#4dykUkc~ZOB?11OAPNf9Wm^dwa2L2KyapS#79?p=;T7M#DVm?Z*iJoQ z`_f#IpSmNG9Oxn^dcib>D=M*(Nuq{*1I9;bGspNFoMvaz-I`k7!vz7b4j?72=-PqCa}^ZAUOHBwyfg}* z@5A;4y9E!LmiC(VT6mu&+tjEP3HE?(m_3{0f};?xb`Y8IcNe)wJsS=0dDSDNsBwX2qm_5T@ zCbv)vEa@wuEU#j&YM1J)>bpuM`a#0YP!&`?0vi%1c-iKsftYPiXaAC?ZY(n~2O0Y( zIr|noZ-KrfsSHM^jc4 zQfJo~QI%_;S)%!g_g*?NX3>?@bs!ogT?2hC)wX|cL=-7399pVLs>P!$!&O#MdOc7N$c>n`I1*i`c`%sIUntC}JF$A)P( z`R^gMgPFSTCMW&@PVqgm8}#$D0eGgnf$@PVf$!iqoiJDGqMLElJKH-9RCGZ!A|3E~wtB{Tnt05fAMTItckTqY z(NonknYb$MU5Bn-HZXS`iM&F-?7l=W`*B{G_c|EPa$E!>aC8U8Rl)enWA^$50BqApzD0(YsIdYNIN;fKLw%xUam+>Gm01Jef6 zTAY(h;U)Of*c-;}I{gUUJnbsYa`k@kplY_zL`i{(9_;nt-%`K8c$oObeJ9bfS&hqD zIj&TqXS}zGuY$iMyxG%14ZUwYcp?exw=bz$iJQgyFc4mg?`RLx#pPmiv7*4uanFE;ERNd5MLePUDW`MBDmhIL2!%jP{vq1Mcj}{>@x0?&s5c%m2*x73!;Z#M z#@B|CC;(o=J8rt}fwmSpcviJeT~zF$+9xC_>!N~}T`?0?_>1&;<>>3esj`bPe|X3q z;37Qwg{VeOBU^R?jUJD8P<~hsZ@@EUf~RmRx+=~yA2`6*`~wr{0#(x~&cU?6K5+2` z0;%BIRuO-r{PR#!aiMxQ3%C0^@WuR64d&JBsg#Z}huF^VdQe}zWlmmMdIE;zvA>o7 zr*Af~dJP^h)4pCjqzP>?Hiv{~ zDbc8lj!mwTEG8dIYMJygu}R|lgpCPf6BZ=YN$inSExBk)N@}f)iq@YtKYDt1ybJvM zC2#19yq5B=a6@daX`r2~yQN=h2pQHJ+n5fT_M6t2mYZgoW}9x9-kP?X2Abv&N1aSL zOkU$jyeAS2Zj?&oc=A**b};^JOgGj=i9N9-Mif(cW)Tb$GoF_4Z!h_ zlx_s?hmOn6%kL;|DrX5LU>yWh<;7NTTmFPK)=L}+his3Sh#KQpxQKs=mB~zksKZY# z7wne-;C25I--|WXx7BSmNt&zLbGnWCHt5c8#tnLkX})Q*X`QL7$z|M*yZCcMCBsbp zRoySGMcY9$UAgWfGdAt9e zUkeIpUf=>;!E#b3^il~l-5#CSPEI`XJ64~< zWUS~O=6dAp;r!%i;`qm2(mvI8-&zL^@Mf9YG8$%l!2#x5+VQl3Y00TuQpctiO5K|> zKBZR*nh(j@lRqX6O!}EPF!51B#e}Ev7w~>cA=g0}uuqmf zmiCqu^HK9+l>h6RWAKNvm@DJbdll~#mpR7L!LrqoZfP0TEi7nxV7Y4PV>xQRV>)G= zX2`F9g_2==&;gSKweqNZzN~F1H%N?!{`;`*%Xtrb%J96EaYwqV;mULx9_MaPU9^@O z`&;2C)Ef3kLD?7C0(l-b*gqA~bQb%Sm+{$F3ytA{OvZt>HTBmXl}pt|93jqvV;iQ< zuP&%=uU?L4-eYwO&2vq8?J?~TT~YmA{TxFR;|F6)({ob~^D*;D^FQYOR1~jFjd@~H z4MrUQy6DDg4`~EVYZQMi__rEVdxiFR{LKVa5f8&;nxZiim#kW|grXVq%I&yK6(+xa zQ`V&d+$x+Et_b@<3U`NvGg+CS=t0D`mR~1F?hO6G6k;@Z=D02Pu4)%IH>pXFu z>L}Pgf%Epn{S*)Pbhi#=xLTfuo?f2*C_7GrIopwQHXA;>3XdJ9vB&NgXt}H;QU|)_ z?p>~dt|~aak8@UZCOIbI1o#S_jTZJyye0mz&9nV!D`E?w@jumC0zJ*enZ+{ip?m!% zy$kxvbJ7Z??MyA7`Y5F)ijEtT2PTJ-PT>bwIca-hOybvsKDbl9h;NkeE#Xk2GWl`J z;k3mWAFQh#P2B0;SAm4k0Y!Gza}n!_zaESD@gyn9yQRF0vtHW8_dEL>=VMk@8 zi@mFTk^PCi0vaTPolRZM+#@^}yk1}KKz(U^aARn;tS&s;EeaL=#dh3Bzra0vs!XRp z=*ao1P_+fwR$oj)6XBtHjHZ<)AnfY&HSJ)lAUlk@vaUed2Q~#}{v)Ib-^2$##DcQtav32k?eZyEz+PQczZ-G&0 z_rCJp$M^n=SHuNuI%lB@{m!BOeR!pwfhBneJoW=-_bM7uxgKx7n=LM%F8t^)ioT@@5{qxW_yDYV5Hq#O8!FzVU4yJ(L z*=e;1y=QLgfdeO(W`P`D^ILs(gRg}zo9~yE-t*}9IlX48!}=&%tn=-MLFPxV zuRqo1PNMuWOpA5Ie188)P>yoCzFOW##AUeWo_nIZIa8EMoX)LK960ID1RoiLZf*x$ zq`P|l^7Qt!^EBoR%je1Ck$FzI+u~~(AW~(n_s)IJXy+-%QuK_L*<73H1i;9DOq!5!@Cr{CW7Xh*FW+BU2)7;8`&${6|>7u#FbE1^-ENX`Gj9 zn+KvUztya?ROF)%XZcynW6Lkg3(GyrP0K+`e@m3*rFpd3iPM?S*v&W<$M2oG<=TOo z-0ID$Xkm`xzU+_Caj8Mzrf-`0qU;5oEx2sPQRmh; z)nCNxs(bX>5z5|*$84^jv7_tDCZs(0jEQjbVqhT@QS4+c^rvz)y7p^e+<)N=--k*= z8&ENqgP)}!OvJJNXTD~>Crm!t(t{2mvps;(!Ob#8U;b#`<59WNaJI_fws*_Wea{@4~~J7ukJ zZI;FE}z~%Bi7o(KFqn>J;*mfDknRsn51g2Ij{TI@XB<~@;Yo~ zcuUUnRS`nO7`%PfSSFgMnYtJY8EWXyG4u0jmAb!lR^42ERfEy!GwwB2MDuDBRcZUM zb77irb@+FjAy-nLrdaw}&NBrvnndGWeGi>eGgJLjRYlmQu*%AXR^jmU+_%=d#B;@6 z&i&f8+qDmm)x4Z4c|E5*qo^!xzKwL2-oQ~Qf;sN);8!pTFTf++WrtsuImmG-FG>)V z0-Ju%LDn!`ZNwFP?W+mH@j&2!bUv6I>Lzz7#tL@SBSmdz-C+F~!y;pElh?EfFQZC4 zPfyHa&F4+0jsF?^`W*Vkx>?#Qns7~b^+8cBc2d0*<_nckaCk`_`v}k7hf2S)I*xu9 zgxso)Dyym#OxyW%S6({#TlDZjg%5%qO9NvD36J%W?Dc3adrUctwhL6_4|YL0H&XlatP z6K>EiSm|Bi4?kdMIgV|MJJf*v?P)6T2#`Gr`C~Rp5wdL{tXA_qR#L-056q!j{RVI7 zFF;GZq!9;vNsGnofDO{9}NE=WgSOvRkgw&a-cP{8f&jN=76F~r1 zf%S3QKf~YDpWW}`T3_|;Lh)b@9Lr`rGxdB0eL3jQ!+g>7ToUhkJDyz`o&{(=-*Pu~ zC*wF!$93LW3N5VBIE44NEA4k|tx>u^iT;(r+Begh@mI!r>Vc+d&r%nszE16zmM48u z#sKR?`&H*SPfNc~x+c4+oFhKdSatUewM^~II!h-@tR>St&U_HXw4R1ydK<1jZ`FCY zhfCq2c2ZB&oYv;l-!tqqwYNM7YaFpHa(mR+Y`$!k>~1_-s%C2%)i5$9;%u1S(%p2< zVAVxyd#JCe^g>6)HCdU^MX6^XhyRuLv?sw`&wYyLuBxl4Yn{vP>gaa5H+sr@UweD_ z?!mLo3&T0fFRHiiEz|uh-RI?apv;$*z^|R-Q=wx8nTW z0~@96p?R{`^0LZRLV_y4y1b@>wvsLfT~I%R-%!(7-q_sO4}XqZhT(>ihST~o`scc- zD81UXKegAj3$!D&1GJ5`HMNzs8tqNZF3n6$AqU*|ZT{+al0^WzajB%bD^w9!FJRG99Gm z{mQQRC5V-8?BH`zksJm?Sy+-u9|G@S93`Wg6OLa(SJ*=viS(D`S}k0zNOr*a*#Vp3 zLTr-;OF5(mM6?CwM>YRP*e%Ur|LRcP`0fpP4NS))agHm815SJ2X!7iKc6igo0wWRbx~^Gw4&*{%xN~!`Oq!;+XQ>c zy9$4*|J4q_RXoge&UD^X+ccS;yPE!_HeFp#+yU~tn&M9sKmV0gk~dK7Q8rPvQ18%c z4U`Ah&mftHDYqu5IkBd>YrAbGmjl87BxmE z?;2000+#du|1JL@R4fLQF9w4K$ObB-cc@6{0lHD?QgNw9puWGdPe9FbgKL^|jANr+ z&$;p1Rt0zUD~^lKAFfhxObYs!2V}v%Xg^n1OjPa?_Nms2J=AIH{%n0@+8Av`ZCNHk zKQ+hkT3D_btZA!hq8WgCR&H%C?Imqv-7j6|-(A&FgUr~|c-5GIX7mr^6P$Q5ai(dl zZ?22e;su~qidI1@G=no!l#S+R@X--WlD;WgM?iT~=0!86~&S7)Dl=@}_*;a-6Nf*$4joG@EgMoDp z#L-0d)7iiPd}i0Yf*N50JM6t+=7OLWH?RR}D?g2!W)H;%_D}B>Z@~{Q1BawkECl-fT|IJUJrI$r$fU`fT}8qAwhq=NdgIv#RYpr;3R8qDOhO&Z zGlvkPd5PBSY;*duC%jC>(ZoOBe-2i^9w(;pOcV~YnY@KMkrxK>8C*mbpu7BmI@kl- zzpd}Nx2M;~)+0L^C&gXCExG<;MmX5L3+BGzTd4Uc z)=;%odSzFF(UK|92lWRP9MqQ5xR6|NS-7n(pg(D{hFysiv!Bfo7X3MTPxP*wb#jc) z)++LQSTFMy!zpcZb#YY=WpnxS&?nHUlR&C84%LuNlV4M07y77%h;`J0W|QV0%@j=@ z%@lm2`;mvoD)z}f2a8Ir{Zqa1C~Wt4PGR;j%pPYyU?1v;b=JpEbGWyYKSr_!Pvh9t zP8oxu;3>9z_h1`bkWYcFq77PM!wo>0{tBCs0s%Fs_5VT_DmdpM&xW34u(|yF8wRrQmsidRlFkHQk<3D4a%g&{*mz6@}PX*$s6S>jQ;p+=|Qlz zY>)hx;-zvPO!nHUqN?4(0p%n`MfrnJZ15X zAqZ!j{8~ckQ63PAsfO^;MCC_c?=F6Qr4{w$O=Y$D9=)Yw@Qwm#TzzFyd?nBnZ13gZ zj8Ggbh6MQng;F^fb*jm1{zoY`lYwr~C(e`>;G2`ciT=<#m9wmm_n5aR`Ew2(LyQ!V zj-j^F6J*0o5SL5Y!Znb_1lG}$o%cSW7aQ!p?W#}rU%=IjsX(~{Nv8Nn7ICvIYgQLJd|Q~C;fy(kzzaqU4zxHWD(7JF}7M_WGIG;6fAyj5qNM7Pxm zt=%{2MbqEou4qo(m!e1=mD(b$X2wNptV8Gi!&gIk9dgOBC19gh5*ZF!CdIon4UiY}dVU-s2e zkr4wen~X`iU7Dk!Mr9OEqk2&teYPp0q&}&guWxQlG)=b54to-|565h)*=%~LAFh2N zib7|(Gq^d>!?(dx$!&GYowFRh9U~q09J`$-T({j}-laafKfhD}gvd$o&iQ2$r?8v- zN|-d?pXzPqneY1Om~S6rJ7=A5&0#BPpX{iMDz(XfUK%bFl>?c>Ez%a!XXqOmh8nUN zqV?CcT{JJme5%FD9*Xg738%2HUMZiiII7H{x*`rmmHU)FuW>Z4OARgSEi;*Q>}KM- z$2h>yLf=Z4Pb+Ggt5=9yQROHqT!c6K8m9JEwCQG|?RXl7T^`UNe=$FMf;a6Wa3d{Y z)wX1!a0rBjgE~4U>m~Qd2gBKoRMuk_;f1R)1*X_$@K+MrJ10Sb z%m<})8m7itYK)WMs}BAD|4);303T8a{Mkpc_e*9E??58W0+*x+&4V%Ug1Y4w${#=c zi>cHOvndVtxxGJ_aBcN&!9VW;wdx$)oJOG5RnBX{(Qc1tk*6OUJ^_5j4pihE?wfdq zIo#RtaLdmuEX(U|4HNNFu5r$q?4ZnO@J86D*{awk+Q!*lTc=n*TdUfhS&i21nbk7K zWgJXTODmD~53U~N(ywF`xBh8g>dNK&Lz)&kB0q;y-5@l21~c`HmM4Z92CaSzK96<1 zuRK3ITHiOnB)yc46%?8}`UH~!=aSPo8b)8vwLW*F+^%S2&VAXO5&gqXnfBdin$SqqO7)$SJIEAtkE}J^wW`uGdgWg9 z)E}g(p;xlSinW4MEUzuEw;N`go|vcNhn8+unEx{tG(_tvXjY0k)g`4~`3b$j{mMr| zCox04S=&jUWGHEhG%sM=@xv5havG-S&uEk3;T{w6Dlf|4gR1w#{8$ZsnUC45-`f@)xgKb+SC~darpldbZ)Zcb`pG zZZyv}cvql8_uhNhTf%$aGs=^QkL?PV#HG&Dw4#o(Of!uRouf3KXi4@p_BQr+ zwhXHcbjVaZG_C0aGG=Esv;FH>41 z3;(LVs_W~{83Ly4VdjXjkrktQM53IQrt9K|3))Kj1=C=bHUs!&mHI@_hl8Qt0OBu0dcYKO7pRFS=@HdhiNJHbR|ldzG?_VMy1zr*%a0L+~T&SM=4AHAqHv-9Nm;4n7__nRNR%vs9OLN8UUm`@$A9;-P> zy<9`HTm4Cl;5Arq*}CTtVF!G)_F`U!h0JYqHKpexv{Ek!GQGgGte&TP(^ z4nJz#D*Gzj4z)JPnuuS!+Zsg%Z({3bn`&EYJ7deR)v`~rU$y6S%tq%vud@{xs*8AO zm3NJI{rlSqaKF2(=ZvSh*Wo?mo9>T8;pe{86A8x)v zM8l%G@KqSBN>hy$gW_bhS3O;0)GpSBv-!!-sAL(bX9y?RPrO8gR0rVHBPx zj{2gCSD(+GAVPjoJB|m(`xXvh4R{V~$a8nuLVS^>$z_RI1_8(Yh}R4=?_2VHIDQV=zP@#tzQkUOB{XPaQeQJ)FTO~ zkeHN3l{HXoZh?wn2e1l-nD^aQELQx<)A*EWM_YQzoN`g_l%>!&>f|OSaV6ySZgfE%J^@cUctDhrz+P#WW>1bHcN~Iiyv%o?qB7&tS(~hN*@fFUh&+NEJijb|PLg z>rw95?1{w3ROw!cW7~Fo1CKaj92=;V7cqkvOO1Rgb6{rq%z~K}GvoN(;>;8H!GFwr zk$ETcYUaNn^I@P*;C{9Sjol0dlVMz;D~diSWlu!$v5{&Eii6=|MHJq4iYoPVFs6qze`)jT zUgaJ%?z> zjb7$s*lb5RQ&)p5&vI_+&Md1my?0LLM~0vkocB}C^P^yuc9Y>xkqskJ(jLWENpP(u z!y?EJ>tPm?frBs(PY{`(s5~8PJ!*ju=m4{`JDb|6@Cs+6(!PX!?iO!Z^$)dmY+LrBN2nxdW%(Oi=6wSQjE6L28?W^yD459vaZA z|MEP?awfb2A>9U@!Jlm4mZ5Lfkvb`sS!YB1x5uI?xSd(WCI5B*4ODDbqkGocU)t|O zac>`Z)wXzaq<}9R>aEDe`6ZZO>EGmb;GI>e|3e^|7;y^Mj+mBZLoY zZE~{R7H_lK3gIsQ!d}cV&GFn(-Fe)Ziz(a}JVox}?oh(}**n`;ko|Wi2*qETI3Y+o~G`Ub+EF@Lh=5iMp9YZ)aU@ zoVU7be`&gDuB!F8`CM1kM4@|-kW+XAx_L4x--YOBo`H8>&YkQ)c4-OTy#|`h#Zl)? z0s+uU9)OcEh?&wWSTil)EG4n;xD6Zg5~%i5XrLa3N&FqgVnq~E55d+b2`6b284Mi) zc?8Ox#o&QN!%HgwPo*Yj=Nx8NlDr}B{WR$RRBGqkeB|N^6hot{HJYp|l?UnS5|u7= zy}r`pT~uy^8Sp2ZyXf-hD-&<)*CS!%?_I1;qr6ZD!! zqYqt5QSdjuJ3o#=1L+@k^K-M5s;)8t?n_P$Q+#K)HxK@FYieK(Iz~Im_03@8fUA6{z8I1ib7$Ui$A4r~5!l9OBpQ{Ihjshx{11a6dDts~qYmTMcz1i6d*q%A?lJBd_e0__!gYeG;F%-N z@z~zkZnnP#k8{v=*7nO*(|!moqDgfBG0u6;|D4%y_`cvWyC=Dop6#AGpe&a9itzMQ zWDk=X(17}mI+tdsW}D`Y=7T1kN}{N?srE1J3hg6pP+L^jRkv7oM7JNT|6fFHj84#fVlumt z3_DjlNLw4zg^PT(q@JU;s27P!aTAjyIk<$$LOZ4cnP|VQQnsT`JH<3Vm*Nf2(?Ymy z{b8&OhqE#m_DTi0Tz(#IS7n(B-uyo9SugHd2`bMzXeAV&5{QJeBNEejVFUMu$#j^? zC`(hm3oOmSU{oi-BI`)aS`|i8JN|Dw6+vn6*J<)9sG40@Bq=0jRdS`B{q$AE9+Vtr zvsqZhtYY79^_nl}MC!oY8`=_pem7Dkyrf{^mboxV3)!07iK?q2hD@yAoh3g zGqO}2w!qiw4|A*>45e?>uvx65Ww4Nj@;Y1a+B0|pr&7r(gLkQ!|HjRE7B%oD?$9|- z@AGho9x1wEvC4!1-@5+=RBOBUYJ^1%dX@S+HzxIHZ`W_iN>EHOLHRzPG1AC z84dZad4mDe50_B``*{M&1YVPy_5PjA@T|C~=Vl+($KwGPG1Ohq{miw*)x%|RopiQ! zesMH#tg|Oj@m{l5vEI)doLL~#oLMBZP3EG^gv{R7RO@t`!amooAqRhQ)CSR$i;Z+n z_i=YUTpva<$=vOW^iO2xS_oA7iGY?ZRe=wbm2U&ds#qAHmdiDg9h~4?ZQem5LSlGz!Ack4+ z5c;ZJFpiUns`m1tY)PGP=AID^YhlebCkLg${+vxul^2Z?4@}oI?!zxQo?m!3>(G&? zLI?E=R>y6W6+BW|FoNfpY&AjM;~H%A9DI-A@ck~r^s5XT{E0j_OqIQ;*hS$|(TJ?t zf;{@CvOBozJv>uCl-b#5Oa+B_Q+Po&70>4#uFVp3(EG8oYYGdXgb*qC(Oo>IoQPst zj8db_gbkC3?r|C@%U?VTcTj(yjyA1Eah<-X7-)*w^nKZxd!)i>&QhrRKi=O-San%! z!ZWBXcZbndnb@g7R9D8wvOe)soD6EBKm0``AEUz?z8Ab;SjzrO#uuY>O{ zJ_46LB|YohG8EmeI@Nf8rLqrj*mlsfO(FNH?fvk3ZRU9G=;VBY>+w=*1|@Odn#_9y zPrRCJ^}@Z&(e%3FtAyfv(EnH9b|9NHM7l~(TZOtY2^Ex^=zr`)C1nIPRVh>zPlJmo zrtF2=h*Q}@*o^DLKrjGfMXNYYovDt~9Mj~~j@I7RM(f7vuIhridip8)t@@K}PZsFg z>b3d{aHb5pgLo~ewP)Cn71m^`&#LFD+o+4Gwd$AR4snLqNh}PS`iN?rs){OIID(#h zcHstGrJTy!uu`fqJ@TOX@JpTngDy-_j6bQQ$kKVtL^*LBbGldbG)CDuvWrBaB2 zYjuRmwGm9{TyVgm6nfZy#dz(tU~rY=`|IHQy@mI`61-7Es$@Oex%WIttJ&LiXNp%D zRD_-B!f9q3E177_gag_Jj%6v{rvje&F6zCS=zYdh-CqDPv6;^-EWg6nFL( zA6NL3fBE%1f4ZOge;s;Ii%~dlL!8GDYhDz31y14OIKT`?TlNgI56a35xuwEL^uDUAf$M(P*FzIX1mhKj)N>3~cyd<`IflfI=9sC`HlEX8V zx_7xdulqPYdUu>1oj)B@9R(bB?IYpxh1=cK3<0*U6YbaSG347z4j=oina*R*_s%dd zKxe1U^rRq7&D+rbhmv`eQ3=6 zl2Gwq$+oB~yD=j!Iq|9iVwyNW{Zd_5vtQ%Y)YJ~qPS>v0Zqshp?uPkyOuLug?Sc_F zRvV|yt^J}orJ1g&rBP^ZgW2u|!XgEH#XMLB1;lvOQPo&De=gyguozE(JfLA75(nd9 zq6o@oc0-0K5G-*SR^&?>P9q z3t*DmWd@L+J3gQO{ykMU@G5uAR55QnBkB6ybKjVz@k$Ph<|384dT925` zPvsf_&G3uP?h&dT7pSWb(&5dal5H!mPM4pHYBosM@8-F2P>;Wd<8^}9GM)Gx$SWJo zM_1+#c~E(Iiz>l3vhh@Eq*iR?o5JvqV^7foEtM_w**4UO8WZzf`O0y0qSN_YNJTUh zhI$+HVhaD(Xm|-<`zYM{t$eSoaH4nextG~nmKM`OCMBIwj>$`pcc1!rE@xLP6T$?Z zjScw3)B)2I3VaV-5A3AUMF$Z__W+yRbNIHz`33(`aO-~W6t5iAb+~6IJLUVXsYGms zbGx&a^SPtD;|=b{uWWI)7uLzvKdnuy-K__#VYaMFVT}E#{i*#6pL>Yvp*vn(GdsC zZRt_zGtg7C9Gd$&uqi9 zx6B@v%^mSqSfXi$VXN*Yj_-SQMGYF$4|C(Nvf+)wTZf%9-!=ZNFQ(;=s>TYpl{b|U z=+dtfo(hksR9{flSriFer)N}`MWor(I$!+L{E=v&>U>?i8$93L?c8R!5wG7b>{Mbv zN%sT!u?D>39dER^x92Xq^IZHJ8G5%heE0o}rJATp-jlDRPW(ov6s}mnBLi;IfXD&%91(SjHqiib#F zFb2KxeCS8i{-Lr_1LYGI!?tOnIE=z{Dj4F~a9SUrYfy(;^bS>jbuwsurefd8#%eYe zRnYjWPCoO<=CT2}rii7pyp3PN2jxfR5KoyylMQl1qilq6Qz@3$Cp=e(rJoa>cs4!;jbpYGW&PXVCS+ zb=oz{)y7rG3e**6{lu+s6{ioA3mcG8<(c&oE?!(vGJ-Pnn)l z67HgynvfQkdD33XvmsDYhC{BZiYTgPDT;=U`MZ18IwQ!*9bN0ak-^!@-I_Yaonbp7 zA4DCB8XGw%{GqwNaj3qO?!ER64&5oHMPY9u{)t+dO`h#QSkjbf{0U;ambRWczp9Gzj{F`I^mlX<1vq_vqR6w63^I)l^p4aXg?cA$ zNn-*P19zAUP5}w3v9PSalrPYCdz%T8`xv_v> z9q1)RhThALDP{;Bl|sEoZB-|zN2>3O4aAGYUrtp;)o8rr>WM$aX=I-e($I zTAB}f%msIMa=?W8$Ccpr&>%S3vzh6xL6hSZ`Y?k+PuX1jK@EMHecwFL6-yOUl(lf- zNfz!4{W+yxpJ@&gC1F)A7f*^$MUA>5E~+`zO7?tzi)F;m@ZkJB z_c6kG=5ROYEGja^&BY|J6;s~vbjmU48q4M7WaUEzgXPc-e#*=>igVfQujT(6{-XvL zo(gc$46w{9{^ld^_U7^)Axi6eYQSEc>e=B*LizeAXh;hVQNzKZkE8~TMl0YS?^5t$ z72(TQUGw3+FB;_bb6(<1u3qi*NL4H7bm_=nvtr?Eb92~IVCydajF8$ zMf<5nDndxASx{3N&eFNPhO;z!b zvYEVisK3-1b%2A+`|<`R;Gs7q5F2>rFX>+n4(I}Gfohd~BctfGDcjP0MAMD;82Et|Mh zy1Q{OErxM|*J4vNg6-%B6wkEe?H_1NRF*%Y8axsTP!Uf@qRgC+7(BBiq-x@G4 z+kzv1CD+ph9$@2KPu4s%oE*239;YIGdN$c$@O3H5ufl4TO{Ed<;Eb8f&i)tGNIT}c z)!0U6ZSl3__Y0~N{!J<#dS`It9jI!lQmW43R%%x^P%cqi;wr?*rcL7wHs3a9f}1@f2-MN;&zdS_l481VxHRx{Ll=P zTTU?VS_|{CCmq*qCQ+Y#4Vcu{@Q(3Za>u$qx_Y_3IA=NYurDj+_+j5`x7qU8)>>Wg zBZs6%rfo_IPkxlBOAIAwk~*Zsr;oNz_H2>{D+JM|j?l!2yA>USXS`LM=dBqTMKVX) zuDSLG@G#T%wG4<_n&WHEdO5#jYZuYMJV9Sx(-xnjL+VDld&bjY&7vM=|1U?c9C6uh zh3_txjf9HYx16F z<2HQHpTj@Nr}bT7iuaE*qjMdLEelkrow=z#P)iCbUyR<_!<<%WT8&&pM zah7_PhW<}CTrV0r83r3PhOYWqy1(#;e=1H^)e&+k&59=I@w8@7k(XbOvKd=Kw6lt>+f zTl6h_93#Z3s)wj(*Hx~-S-1>3(G{5IZlxRAMg<&CH{6iv$YhjSD&Xz#gzC0_=ppW7 z*KjR54Wm4f2)&8Rb5C%#E2I+C`V*K3zC$}}GKx-J!S{xPTB=6wEfbgoBce6i?w)LA z;+btFz^5C^bnqW$Wd$WA^~6zBUS)aN{z6Wi-t=nVv7bOLb zzF)$u#F8nKGDbP3c#i~UC_jmRp{bHnj8lx1CU}}Ux?7Fxdw_ek_=DHajo5LL0!~8<`HyZkjsq@Dx zx`E3&qrIWOV7PC1t-q{&DE_VNA?qYv@O}2YV+V4~J;O85TO8bS4t(C;g1^oHMOOjN zXdCZh_^K{=q!;j+nCf{AemDv9(adqgW)Kkfy zR;__aTt@Sr?O}24TTN9>D|HKTkm|TlmM*Og_3Us}P&Gk(!=_QDel5<%xN4&66*#nV z%KC~v@+GoQ%m5_NHW%5$Ml-(|4}+-^mP)hlZADMlBJ`07@L{^I z3+%djgTw1WUfztl$1FTt%78xDLNE3iJbhW818t!>xJo|uvy&eZ4mkU+7b+_!%2&X%tP>cAkE_=|NxC1}q`0Nh zXkX|RrWNLPmi(3i<}JpXC@R?1{ZM2HuHX4kx^wYGl z>NH`qVx25cC~t5zD5kU02(UvLq1UoG_^5tG&#kKbPg%u~7(5c_>2C!Vq_VdtPM;>K zv~&LLff4X|Hv|ha#dYBnTY=e8esoPQGb`Q4pM_9CuZ|kr0eZdw8M7!3x7qRKdm~1x z>#GN<$EcgBlbJhz#;dfv>KXfpj!d1G(3#d({Y$k_UF^?Cc5#c!L9F@|Ur@a_$m&zY z4<&{gQwh9h2co0DZ^E3Q1oPMw_Lh~IPf6;GBr3tJ{=6Rcb+TCwaIC941;-I)^U{$)*<^d`!;()`w-h; zYh>oc^be^OQgSDG;@|%|^6T!e+wskkzNS{Su67L%Op=>av((cxDs@xkhTwj02gmY^ zwAACN9nx#r&U>cI($qfFzNp2~`*M%T-8Z^Vwp?MK^<&j}gwp8aR#Yw5-Zb@ze3J8Z zo|pLo`OJB%Mi-A-V2;;j3Nu0WxqmaYjuV*#!jX;#!7~L+67`cWpe0Cpp~zm zr>y&!>$0nzI}bJdNpEN04_|e5d0X+M8BE=mMx>_0OX3^3a=Df{S2&d}musPCuP;nm z0Ha~Da-ZO!V(Y1VA%7P-E#33~1xFUm0DnITriJpy|42Fu@Fvo>3rEHx6HmRgMOw5t zeE8z-i@Uqa;w+21ySsaFcb8(tDfPx>l1ws@|Lp!(FO~&%fi{!(edL_`Q03)0%DbxL z>dopcDy#Cl{5g|DwIll?%j+1io7B)xnaOfa@h3Z7#i(iZNtK=5tJElF$#UpsR0gp| zdJa0hzoCTr8&9T7JVfG?jD$m{SjvFlVv^*GPl_r;*29I|RoDifcoj@4h6tU4Ekdos zjdAzqh$e%bd00FYZr;W4C_Y0cxeA-Y|6%qvA3pSmWQEi%?SQ0@LEv+hr`Av$RSo&g zEl^P}|4-F_9n&+1^fuHA4A@B`@*LTmI*u)jk@jL5{hEA4Oavh;7xNS*G6!3a>hMXX zVZYH7ejf?uRUc3RWPq%%2(uwYu$FKDbOoEg&>xFD-Dhy?XA4bmzn_QSCI_|UkYF~P z>Wczz{d)gklQ;>HmDUyN z#msf9xU^_g_#9q=w7?F3rvGZ7YOq~c1ghK{P#tP2rYSR_5$m9MEOXE-wFHxJ;;jyuH%J8r28YkKp}Wql#nuD(1-6(|5=o#0X?!otK0q$E3pv1-TCTo5koA5uEv7hfgouQ#g9$e9DChXb{CQo(^^t#s|jxC-R$6gKY(;V=-n`8qB6zgL6~`wP+FlncoH$SDLT3x1pys zD$xeevK)1_bWL@=bYwQZ@^ZepIMWu^A7acb(vnD&&dtL=7 z(I(;veV>_2A0}3aS_rwGLC#!jv_)dga18J+4jm+?v+;&Du{#nrCyEkeF++4}Wohby zxFtN(OGSSX&E$e6H`?j}UdBZmQ`BQ*n~7%P$9M<-Au$s#>BaIQoM1oI zQ5r#&p*$yRPkAMeBbmX3z-M1O?@rH0&q?n~pTa*Z@KNX<`WXHhNk_iHt*|^)5Lm~T z^qzE2ax#uL_D7BnuJax{-!M1Aa-6XiZ2gT;Ywr|G}?3-nZR9E_gN) zEA37>nCJ4}3bC?*;+gC#{RE`03Gl+iL*bc#nNU-*3atXGqqlN9+e@`nRbMrq?W^?2 zd&w@-9jUg^Zucg}pb{KS22d@QrB~25=-2o*9lDzhl!H{00-m63Ow@hQ&78qxUIE== zNAws*Y)kT>H1~_TVdvBU&W75eK9Lb{b{9c)Q43n7A)yiBZIMh-miU@vA^Q0wf`^vN zAYG2##s=&ISe$%yk!`s|GD+H(NJG|r7i9Gopm!Qfy#iOUCvg|bnOTw__*@D_?~sR3 z3d){4*nIDnaFVLf(-ec@Iz-%C)Fx6X922St{(=XY;=kcmJR`_4{j&w@FJ#OA#`W~fU4M36pSp&A(Of5*r1O;Aye_iW_Ox&zQneSl`_ zhkF+{!Bg9N&ntMH-eulxo*tahZ3Brz=jd<0WLs+cX{%*lWG~@(;`pC)2DGmMN1P+q zrn2UlWX0nPyB9nx*j)67d6-@9F$niWAIR;p(u#?46ManDG5n4{=C<2U+xFToyK3{3 zBlYOtDzC9syeY9kiBSnXV?OC<_5{6Cx)NLebwr}cz;kTgi!aq^{3;`t^iGK z9#oQNp*oujCqZ3k%9dgt=jK29R(h*?qPYR?y6&6qL{DkoB>yj=VYr>>oOl_&`ZvX$ zMSH`yf?3!FOyFsL0)NTBN)U$wBByi<^^mD3KL>?ZSJ^%K6B(3tg@0%V7^aKFS0$|o zBSkR3W%Cr*z&$Xtuh<5tHr~mb$}Z70C=My5KJ3{hKzFj7>_L@=bK>6}+CsR>O|rML zPO|09Vh{y)5tXDl;tbrG@t8rChwfSjC3^s5g(5g{#*vrElVm(uEbT1WEP5W+g)YN6 z_%5(W_!K-9z9o7j*-a!!5P(DxpJ4xkifVx6F0JT6T{g?f#+iQS!!m?GUE*@Vw_ZDd|} zQRr~+2lDS;A{kl% zede?9F8}$!za9E(|9t+pSLdnd9^m|8|6-e9J8%2TKGreGx!ASXJpc}XtJpfFx+Bhi z9144Z^%L&giXf$qG;cL0TfCM5*3#gucTPLutndM2@u9;ZlEZ`3x`4>iOa zy6V=bn8upKQnL`PWX00JJ1|D3*Q2t{D}?0)jibP(O)TeI($-85-Ng-c&ccA_|IUaKwCZpCfPji7T;U{+hCNa zxwIa2jERyjlQ)%Dll7%rkrSm(5H0pX$JbP{TUwW_L?_5D%3X?Y%6aTMwmevy9~H~x zb!Bo?paqyU)Xc-n{1ct3GD6t*e;#I)|Dcc6WP*Q z(*4lRoWlZM~#-sAn8k-_3!Tb?4t# z#J0w^&Gyw+$9}~A-oDPx+Bez6wno++mhzUb;0y|;rKTj)15j047R!tG6crZsEo2L4 z7i8rx&d<%CTe!&Nw$lo%fIQtF#cEm@Be%! zeKI~4yUtp^n%-wz3HK6bRY#n?nr)UfY$>*Mwx-%*?HTqQd!~I8SZdV+-~d>?oiL((}LNUCz%fY-j$*ZsdOO%R(9A0mO5njPzb) zr7*(x+}+OE33qxOuCCt|SxiS%hm0HJ$|cTBO0Aw*Bo%`8-1H8hD| zoN_gFO!*}hewTYxCNpVX>_Pn()k?(`==b#sT1D%6Mb(J=k-(P7O6-*2iMm-MWwp2NK zDP5VaNF5{YNGP!v&ZXK&82lvh5v%FFau*xW^w2vD_lz%%wT%ixQ(ak&os}ye%H{H6 zS!wxc`QM6p%2#Y@br($|?QQK(?RKqBTS0S0RfNv{2jhotun-#Or>M{j@TWJR8qzhH z94Nr=zyo=Z5{Pu^K=HE3^-x;SC_D+&5C#QHggucXVhboEucSRu@l_Wuia0=D=>sLu zTXaD`z|0s5=W0B5PkYe`_4+TXrVRW{JWjoP;uVq+QVHnPXK*HZ;Wnr!Y7tqAP4L+8 zsE9?hQj#tGK`bGE;A0dygCM2t@aMZj8NpLR1bd+KfwIUakHuz+!6b5Kq!f}QuYz>= zDWLXG@uj0H-U7DeQE1@yxJz&^xka8>?{e=;??W&J4|>*e)!Zwbx9q95LW>s^=|`rM zrq8CP=AikmrIz)awY_bvt+K7NwXEf|$yO9o*dl*nuKjmrc1-rJUkiUR*(ZK)%iCVG z&nmdm_@<#JVk>cnJSokHYz^dd59}Ase}D|km`O*#n--BWPc$uJrX(7ZQ7>hv()fc>owaKf-KeRO>k(b}2b>8Lg9}0xkmETY8|sqcN}_OhLFkDv z!hhU*+I`V6!gkAY#T;Y4YpP~mWLau^cg z<`EXLZK>m~dzLR0coupWNx<*=3ES)k;HEW1|FaaXu3DjvVRxjOL_rQ?)XL53)w&;s zPEnarYobmY>l>=+T$kGz#^Cd0!!!(&r(mZ>ExkZpwj>kMkrGqS$$>b4;`@#e^k5Qi-4!SDn%6~>^0 zjg6Fs9_1#KZB<2sB2nSBcs`%{FJQv54Z4X7zPbEb|E|D8!5`#8C!iLa2i5Q;Xx!#v zCMZCUy$MxaKGc_6knuGn+zQE>6UA#J`*2nc$E_X2R7gaYz%FRCWQusP=mxZKH!!CO zhgV|;bp|KvI^;s$#3cW$XkTP%I5BioXcQp*Mt*?L=6&LIcst_s%k#N>pFm*M`068B z`kH&BOXb{S?`CUgon;{{`^|04mCY^9qs$A}56_)fSjE!b*~6PEjEw}~&Y2aNDJ1yjxt7~5nlBZXHO;hU zyDA3~B~kL@+SAdl_z#JV5}(G6h)UAlR=lM?LsdJIidB@@)U@da%A$G#6K;#NWv)Qo5#aNlg+v#MU>wRDG6Zl8p2Zu}0Jz z3N{}ShTA|-{u>HM7c>#g!!v@qKyTk3F5kJ(eiNVPNjzCw%zZ7htzO$GM_=a|=TYY} zWCnC_<~hWUPsj@hS?*ab;)Afhvv#o$bKZA1_b%e61pNQA9_qVDCHtN2en0%wgfr;RevI--CkvLby%nu)u*t*Vot6`_uE*Qx1CZ zJ-$(VCBNOjBLLbY$SFI5MesHhW7Av>O7up81#H0Ufog(F@B}sRw6+zs7N^4{x?K7N zGpeJ|`M<#az6bKrQqeh$MF!Q1h#Gy_3^4(%>29b}k09yfBoLY3Vpdjya&c*B(KMTHFzaIEf<;$xtG2gjgS$TwMpk3jq6Hq|$HZ@#UIOx6Y zOt!`rS1-uTt5YB`wX*m2)(U&cA|<1HY}^ptFWPE6uN$J`WTmL9NDyhxY*6md8lx=< zb4p6m!e#fBJ)JtElrw2`LZ8^PQL_!}^{4e}lz|2cw~A;yZkd`{CuOD18T4&SoeU`+{`dA(R#H`LelgF2a#zt!WXP*P33N z?wb2rKij_A$2g8VjyR@a0uW>GX6vtU0LpsJ^4hXJ>=ZUP)C- z-B7bao1lMaC>>QI`f7A;^k@8YTy$*orKrTHsYbtHpJ9-}Xqc|QsFUi(Xf*hZ@C^nnx({zhzJLO=f~SGkfjxoR$g;2D|A9%$ zTE2i^;vXN_g(q-e_+F$)bWhv^l!+0@R_O`C#0}^zhl2{x51zrzP&JJbFO)2ib|f;0 z!$fUjw6vKdUo<_E6b``Yy%YPBKEirzRO*4MwmR4$cvZL_Smv+G-|!}Q#=E~eM>^8& zV{K~NN9zJmOzf8Tmcy2YsExXsTt#aO(+l?HUC;TEJ@A*|r~1d&?~i}H{dFuSzQA34 z+q&Ob!}Eu)zOSUG$a&IM#(cbx%S*{k$*r58QvATSf~ykv5J@K{(#vEGK$q;uJSN9W zM~Rn#OFLG2m}(&Jt}3g~iO!FogJEo(sOyesyqm_=)I) zWG_*LstVe<7VeKI#zOmOhN%Qy{T|s+m0~hwCJS^)e zd&P_ZA$Jb8|fP zyzxH2FPp#Y9}>uc9z(;;n+y?2AyFfhJ0x!V>xbL&@CvAr2CIrt; zO;EzKk#kiaUSSccsM4rr(%|&H2M5D<$xW~_Cc}L;1wICcWSlgL$Rsv_c3w!$qg`|d zW;Gli$C+hJTZUxz(~W47eo5UxHiVWQOh2X@GOw8yvK_L|AWS}$ZIjiJJ!9%Jt7s2c zrys~+&<1A_m!M!Dht!4ysBW*o5iG-fw-x)()|fYE!{0s*3GO+frOv&j)lUwAPKi+>VGcZt#JG1L0NML zYMRqRf84%(z%U&fOo2ORdAK6nOLEM^8^B$Wg*>{-ksPE04uD5T4@X%#93*>@3DyKk zpdhGc>!E?xK>?bC?7{;`AwGtr;$4`ue+N}^3;aGDRI2-+r6_@&OkCt89G6eAeeMTR znOK+szNrm6Jpw!E(U|GJ21`c!pAue;l^92hkIJLwc|jDO|tcxT+vN4Q=#Ocx(EiN|^=^i4APpazCscRz)m7kW905|ED0Cj1;H01vM7{z{WCmkC*b)idW$>h5 zhnCC*Ced-YpQ?bB{tTRo;~@1Ehf3ilzlM&v4V=l3;ryqOZ*D_wrhwZnlcBb%4dPExI1%rnMsR{BV;5flTJe)`7StlG(Fdes=Bh!$-$|TX z2f@>54Mv3-K9V2smn=nQ>S75m86$lyRTF81l6VQndnKp~F5+C<4ZmSn(oLEnjfclK zmne^&Zbz~?*%W-6TJWG%0c~s%`H&>3dQ@MkKh>NvQ29uKTLjla8SL1i@L%-C)3_B0 zOAE!IUo+&(kh=ZPLNbRbXS%3U&V*BwIJcd*d&7xuzpqwh7#f zKcMcK0_WGi%#t_o(-wv+gJI&03`atDYiys3#1ib{wnAyP6MWL;$Z0)|cmKbM(0!2I zdtKB6&Z5?Ew{?Vb67(983t#7LAS8Un*WUi0y2c#t3b*ZBoU&JODprbIfhy-3SkGa+ zikHAf&xF&l5uCa=Kr|dlAWW3&9F$ih0d+WL-8w ze(xnX%97!Tr{N<03m&sX{0Vu;w;qS|;g#^MH3SFXG3a~sao1 z#|QcbwqXMGJdho*1QLW+$jh*TF}@ZYxq28gfK;bOcf zbz-(V3b*)gqB?d0PO>+3n<@qM)E$~-Ix}05UK3`@f~D|>tck3eOeYI4nap-(B+~+p z$^S9wOgv7k9Qr+Kza#j+YQYOIi&9dX@HB46ENwshi3P~$Tms^4Pxxf(Ai1Uxsj}U` z1UZX+!@r8I9k?r7V(TwJYq|`6)b`=Q_}cG9`tV0MKFyekvk8!%} z#f|bcG(TJl|M$P%jdV;~O5j=9jdao{@XWTr&DRN>FC%n@d(fLU#w1`cJZfLzqgjaj z#T62fWHt0>Dc~3#6E~5#C0C@Q2_v}^2~L?f%WFd4C?m#7U*Sm{g{osdHYexFiBt|% z0je@B^^2GTvT-YLDWAa`*$&yqrBEe2fyQA86z^)WRAh)u!s&V)4qabpQMhxYpC|+# z>^V4gp5kxXJ~AaN;Kq3i>ZlL-?Z0pq=E7Be9p3PRP~u(`rU@!&Yky!5?FQAEg8rlr zJh%OY2_V(X#INoIp{A^G97N|i$cjh>|Es*u?LF-M$Gg#c4BO>d`1gn2r{0UmFlh`u z)pIV#T?7_bA1CM7y z4$U96$#U=@~ggYiLPzgKI9zsvBj}nm85D1u&>zavEL;y$pEN*-O{_ZD87g^{t zd*}X_xB1jF9Nkj^w~4d5Q{1gweVwBnYwfFS5ldThoGHEdMPapqius!SBl)cgN0skAsq$6z-;hb4$F7Q z&d`l9d95cqAWvp#%@ExPL+j{vv6(T`qgO{AGj7n&(VjzY2nBLnEp17COT$y6IHqIl z!&rMP7h5%!i+XKXrmL^!6mr>7svcp%SF{jweyf<5)FiT?us=^ah(6N6;$e}Iq1?bx zexG+A*Tmh!_1QVx*}!?vIo6d1MpG~D8E5p=0!eZ%cK{hGJzYngKfxpWWWR1#fkbxQ z`N(BKerSyE9v=;dgBFQ_yF-I;b8G^wa5~P05|R&+Q_{=CJ@O7!OjnT&luuMFRo-RK zsfMVlAhm3?_7HM!y66VsnP4-!JkB2Duq zoLpDoo^v4o_lEl>Silb*(T=0`j`ouFcJ{yQ&FnvH9c&Y=)h#zosl^=&d*)~4Zpyj+ z`(d^uyLxuh-_f~-f-M%FWj$;ol|faB9f9=Bpwh;kQ~%Uv>#rL3Mh}a97yCYDY4k7SBmG?MYIPYE zjU2$Um{%;-3+Gqu~=c6^f2*6d9mt+DOcYClX^`T3{Z?{yn(OH)R(5YxLvyfb#HdaL%RGLZyYNp&3whqsl9AjuAt zN0?}4FRiD`Al2(C)H0Wl4%@MhtykHr3$Bg0-YTr_D<4M4sDg%}0CUB*) z;M3cT=Vufc5MH4VI)oq4N9i#Ed4WksG7`I&LOI(HG?CBJlEh*pid-P8Q>UqTdNOEE zS+tiXL0ZVBPs0Z(p;u95kmb;sRKb;tl?)UN8f1sQLQ?EzY~kW1-Nd6X&qoCxqJuXB zo&8E|(POXl~)H0(ZVQ?{4mroc_Oi zX7~72@~7v!_WP}GW4@>U{E*!?uUXMoOObP(_o`n9-rLN;L;i1XzI%*w1Zc+BK;G`a z4fTBw+z*eDJRq+#x8(+96dPezs^%jLv#vTxGf-PzZ!rvuIu!jdrfck$nAqs{#uED5 zn*FK{>H6*Zx%y(=YHe$EH>F;-ko+JX8g3@+;}3e5d%Ah9 zd-{4+zR$?GHldpy%b)UXMry%w(6Xnx7C1jU20F6s)9hXC6YK}3eX|(j~vqk(U>P-Uhl<+wk6y1P-JVNYTgu z19Aa6s#frK#s#gyBWUY3BF$}sa0fiIYQf9Fv7tEhQR5f^a^*x)xl)@6CN=&yeUECz2292Fa_u& z8Vt|Y4^;fcIOR?V6iC7?0~h>GXaEep6l4dS;7&jhYIBZv@{Y~W+_kg!vW>A$v9y5a zb8k`o!k78u^JeDu$ZeU|xuALR5ldM|RW6f16Wj@x;D)d?q!6n3OZwh(yz7?hvwN&( zn=dACI2Z^M$Uc#S*cC~V`{1DxeI3?;7>Jez->&&TKZb!V+>@K84g`joHyA!-g_4cM5(VD zaulxe;{r{BzeBYnqmZ*&Lb{T8NM4{8(JE#tBat1KRg?cA7i5p2RvIrKsFjJ9mVQd zzw$Ls;HQd5xZU?+Lf4;Oh9u(KaA6LV@_6k|Vy-8aOb4+d0;T3Q)bzVByV(%o!H;G{ zmr>h)4nKyLxqWzS=rnrycA$z5!ghZXy7Ri|@Y0}*vVz9j0eyK{5P)`rsWS?S)8^Q+ zKEzIt!hCogdebz_7-xlV;+{GO9dUC|uyey#;DBy``B6{FT#$Q4V|Ozl@(@$m)}e%; zA2W}eaMrE?Tj^ijqZYKL!QiZq@=xZwKv&$`vzvSAu8R8lA7uX2cjh1ku$-N?1ua?T z>!v?U`%Qbz3#{uLEjixzUQmjbNn1eK^%vQXSS$gPBHSXl8mVt@0yTrjLn|Wh#cQQb z;yl#?vmuc@R^b70^gXl^UsasCtTs*eOE(5na-~6`_h{OwHYgS{O~^%(N}`hCH^B|T zB&2xBBXf|u^G$M7dJuWbXNbzukD^;4I?%?ebqDNkEitAQMKMKDMaPTI7mqiYOpDAT zEpgU*)`8Ze)|1FAv|F#+de}GHzuMb@w0hoYaYb=!Q7to`49^H~{(j-CiuE@Ld=Ykq z+C+Ye`bsWBy)MO!xPyGF;y6^o168bgzIvy+zuK+3r~0CbS1(Yz)pa#vHNP|mwL^4T zeWCt=VVLoXF=G5Ps#DZe<9o7Zt#RO@YkN~DBnS3pS1x`{GsO(Saox_RqnN}a?XwRR(NJ+nfsV}nl^yv@zXJZYry|6 zI7C#9*hw{}_fqr7vP3&cJJG%{6^aPsgZ9v(2qQKjlkW=ohI#;6*9kD^YRe|dqUFsL z*~+jgQTtTa&G5o_FG>|XHfp`$q4t_;iNZ@?CcNU2kp)nfUI`8jT?h}tM3aI0e=fO< zx=QUK`$&(7E{Apo9{OC|C#T;QZ*63GV}58B%ue%rv)Z!O;gLR#?fvtwU zn#1In>eRR_E-hEz6Z9m4Yx2yK>B;pJc^)BGnDq?ywD1msMsq|UI`}nILUc%CC%#af znZ~l~GM&7uye0UJlq{AxMc+l0FrA4YA>1c>0P@W(oSJXOmlMGqL<54T3)*H|1-)m;D zt>j7cJLzlD-(en!7>9&JctuD|bL)w6#eYh>!KYMAY?O`_r$z1sef|P3$*pzHv|Fr3 z>kl}~{5oF`4#?Ifj@;d!IzeK8^L{|KrK8 z0DZn?XdzT&q_737>RfOvdLT{b4LbHJ{9|9b?{^-*1S-YJTT(w+&=QQVO$0a*w`(o>4@8wwP%JQ`L zp9>xk9U-=3GyP1?%c~&+b^U>OI-0uWWqOnBn#47P=F_R4wG=r35n0>@(aka?t(AD6@U?!ByO zDz;0$OUr`_vP*JH)G_QA4*7q2HQZ(AQ)n&~)^tl}^JvrZ;zvczi%f+Z3+EKREbLLF zD6Ve0YOZQs29-pjv%BkrJHY9@=g=?tL8Y;KcOZx7w5Nqf?`a8c{Sa?I-(DU}W+5TG zR>Vq|lAq~JFkh}Jud-=izVu+XB4N%WA0~f-WUs4W8h*k#*-lm{yC9#YsHF5LkFw=Z z@2*xgSDghRrnGVm?w@!#Tz)YNm>A|E-GSZ+KS@P+U1IUfsH6`-VwnYk^;pS55L@SC z?za`pN;&k>Y!fMbBQY9Jd#o>3&Gc%yf=*)^Juw;;X?)J3WqO5_mj za-DMh?W*Kji)X}YKWPuxIY+VUsfXj+23w0}5Z~x#$d6L7iR@eDdF4E%LorfOMKMA_ z;ztwN8mb+tD=LY4o0?N6B6;|QrY2@z$@(vbH&IVw4#dq(XjWook|*g>QlAo@_@6QT zjOVp3_D{KwN+fLJDWbdB`5ca9V<(pn<>55RM=+$V;{Nc??Fc>ztl}#H-W+k(a(uMi zvF=4Jo`qWceBtkcvITeZ59Ke(zny=-ph3~GVzK#ei{IMGehmp87u~zL6p#h;J^w?Z zVGq1dia;nH=egsl>%H%t9dq8bVf#ZXl# zWU(8OLYob`rBi+hy8mwSs`7sFPx9`H2Z}V%T01J6!<9bgC_6=^wYWY zUHCK$2no?rdJ*00Y`Bv?gL1qblkQH)g3SZ3Z4HKRKl~trR)ekWdls0AA>3}QF;RU{mMw`TtfVXp35SgB>gQ(lq88|B5U|Q zl7}V;t1%O7h5YLYd?PURUEq)}hO^y*+2$GVD=>>5p#IPIwDv6JHoNB!yrrG_P;reSz92LIQ(mXMiFr}^ z1YG*^qGrVlO*!VV){w1(qbFv+f@`Cj*ixuM8D-0T_Po#^xNzXC!~ z2qU#Y8bwy5(_~)xXyq8>RAi~fsNbsn>Tl{<>S*;7)hbm7m5W`3cgJ((VdXWXtAAI% zfmZ67@+%Solx#9vnk~mhK|eJ{c|x%hXNeDqR4vIQLN85`bQB*&TJOJ^2{d|0O?V&D zBHMrtI~wYMJe-{U!z;l7KLmc=5%BCzfgE`rNj>AR*U)1>ML==T7(Y&gzj6k;<4d5X zb^_P2xkM(p2u8>TaB>GDtE4tqC1XNW;Mw>XyoD;aGhDyDFqex%@A3%jBN=>G8n8P( zzAwHl;CIgVKJu7AK4RT9TkG1Utp?i$|xRC ze4_Y~>7XUaUc+_AGt-|Q8ZOF`Od%4%zL<&q<|S!w@YO$~4>?ORU2j~^89LJsvKsQg^Q~VvCk-G&voJ(_y78GwYy*0PAzOt2ZR7N_=IM))_I9CJYrQE<>YI2-)oNyF7 zMmr6z>#nKpt+;#6`nvc%fh)na;jyBjk|9K6N}#vPlHliE&HklIR!>06b+q~+{E=-` zGSy>tF58%`jlOpi5+S>@mDv((EL)as!%k;6vX@vZD_8ww2eF%!(-o=md(0R*n!1jS zQ$0yn@p-W1ve3WkBbSf~+z7AtiBQ)N8M+1kb`AJ?gV2$D0@LMRwz~-%>`!0}))N?P z=%*kpln(GnwL5~jq#^hvco^Nuhj2VP;w=15!$Wg}yO8DDA8AnOU})?FZ(ujbL;1o< zFdu#gMg&aQK#Kf}crAa;H^FD{?E+7GoF{{maAT2~RKeBRInJ@czRkAF`q5IuvKBM9 zA10@XGrc!mFl{saX)>A`nB1mzmYTK=j@It#-md=E!HwZ~Y?Z4*5m_4h@HWs@NU`ZI zNlYQ_R1+pi_CPj89`RpOp4^^zXgSwBpxw?uvUj17& zS@oN($qrGjP~3rTu!5{Cqo-r2djBzk&VkY*5_c7u;QK!S0?=$sHfBVIq919D9(4=o zlh=_JVF*3MT*Qq``Qg|VjS?vdz#)4gWSQsSKLh_azs^F{WSCoO{{)YbZyd5V+C+`f;A?_2r)XiLDoO2!P z?9XiFZTqdYtOb^pma3Lw^EPved9SIRX|`#Q*L3aVWWHK>NI#N~nc*%%C6r}f4HufvKHMR9id`x0uG~t` z9dCxO8FYVJ_<7j1uJWDt?n27a9=8&NxP`8fu9YqdyCUpOy$yU@c)>p&422irEus#R zfb=lg1nh~<^5cpn$UQF2)<7+t#Qs#yPKfcA+{0@*(=Wgo-<_|8?Vge^$@c|aFAr>o z9e#0OY~XvKqR;}=!;)Y}7J?&l0!b0OK#^=6_~swwf6J46W8Wh0U2FmmbB(zB?#Avc z*Cd>t*HK-z0_*XfW4@!5j_>U+@6#~OP@ zrAK#&eh_unIMDD?*GTJDXR2xDN#%%CDcQ91aS zDick}Dby;uGgOEb!Jn>*#FdBgJ?OuV$&yj&)MdWWf789_Y0y&iV@k>h`B(XBMP=nJ z%FwLbZXTumLP8QBhbE96ZJ>igOhJ&6f)oS~-vsaC6Lpqd1d z);L*PW(55eMAdcF-=I}?p?ae$-;E@vE>srT3uMCK;IrLE`llB9j=hpWP^7dG&lJ@M zRi+|Xb^ZKS=xlF*TSkBfxzeLRXEof{neXWz85k|}3dV!FC4ikyKsPuUJB8{X27G|; z^&wam9{x2b6&3t9{L_%f+Y$WF*?9d)@kq&2DMOZ_DncdO46p1U`C`;Aji8)(4GQ^3 zMh(rZiy93^{u~f!ZG?@e1zLVp>N1ifo`7S%3lj}mR=}*oT<0>FF?XmmXlw}F37?T% z`T}&iyPz!I1_>@3wBx3DSN(>r?jk0bWuUIPikYN0VgUWPxhRPD+!GK&1K8`O3AF=l z{44pOZw+*vEqo2}>L>Y{`qtq!Z@|xoqN12j^mhW2=^y`4sPnzZ7pTX-@OAtz3HL7Y z?l&P*aR(+4bHH|+fIP(oj<$~0NVJ{n_~>ZoJnOWhev+c1TI#&zT;<~2FFa;n>p*UB zbHt1(_e8v|HHnMTK2kmUV7FwZbTF}!yhq)p2jesThv|*?L=t9pQl7^zfe*7 z8h!Xar~np;(xBn`12nN{RNZCJIlU3GK_dBsSNJ^0YI^Fpuj&V8 z{e4-!Oe#-<^SrLyA{&J#r3$l^j-hu_F?jtcauSg#4MO|=0%@OFP`Vuq{ROJ`dgy)M zBJbjCXeqKD8=)TX1Vy3h$e);tE<+jG6m)>ounbfHBbYwX{9E54-#k14)qUmQXBgxA z;OoiX;r)CmWF$|8qIbT(x8HzliivzW|H{|gcgh>%T>-{#J4~OdL1Po;I_T_(JlK4P z*`asVbq>QTABUvDzDOLbioWpdjbOeb??*x56cNUW1Bdzctlb);h)NuwJ&EweNK-b#8IJb?f0=FX7AeP32#} zw?c!3bP}oLc}UN_?aS~L`?~Y@p~ZUxW?hk>4~;{<>{HAa`jHLjFf&HJS@B3osZ!LW z=8C4a_Ah9H{?x{4cWAQIf~tmU1)HO6i)`&7{ysdZvZ46?%m*^8&B`WU>uWQJN@0dkyNuJ|v!ap^$tFHO3)qGFBkrZZZhQ?T~U( z3+WI0kxSiG_#+_mKk&`p6mYV{)0QnNj)Px4?HY< z29v#$aLW5VTaiW5j$4j%-R{&oD>_=>PXA_YW_@842<#Gny5%28*P~@k| zSIKpXJBroH+3b2%o_dwr6Z*?y~mcevpbgQYad$+Oy4j~`RzXip?t zv=emd&*CTG&DhZIB}CMf5_WP5+n92lr%CRSR~Fl2V>kOjoEC)8sbUNxaqu+qt2U*9H_A3h(fL?CpXG0pw^!!pM(55Oe%mWe-`;*&;CoD zJ1yA=7tDA}o@Zb}_!Oj%T{!>mhYy8@2V;doe=+i4OZhs3Fcjiuaa!DH2i&XObKLWg zU6Jc9%T40;A!lGex15`R+WiMUyA7_#PKzUCM?kGjX02kGXf8BuGz~G0G_5sVGnwJi zUT)4Yx3Lsjep>&u_jX=$|Id4$Z!Vk(orxHcAkq|hBUP{;3q#@F6-iDPr3Z+mWE;@y zR>2cCh55*ghLS+5V3oDmxgcCk(pJ?+4CkX7#_Wqd6W1udW&GQ?;@A~2SE4cuuXQQf z6Y9~b1#GTzj&cNg`_al;N~_|u;%`NNMJ?oN&c|f_s;sH(3aX(Y^jNAJS%&xtJ#Ug| z0r&^E0#K~`c?z`2RMcy`_{t!Ry+UT# z8t$Mw^TnNG+tePnGs0Dv(}sCbg5Af;#LS z*e=z`@2Dz&B1bR^+}|%yK(z-s@GCgU2FlWd)j*Ddahs+9`JZU4qNLfiMj86BtcvT z=`6*bV|`$G1qEh()5c;&@r9x(Md?NPh35(n7P<-_7bThma|c_oI;m`W~={3BWcEqPV=8HN)Cd7Ioz9i~4qspxelu>IA;wNvy{jP0X6 zF}>r4$4e7r2{Yqo;Qa0yJ;QiOpQ_8$JX6cLy}Avw0-e=$p*7O073!esj%v6n zLG=jpvU|#8WefB@BH2&+5LFR#zCv*s(ctiXFgQyGV*IW6@4lBlx33|pQ>DK@Xq#XB zDS<)gRdLNN5;RKDm0TBk_c@whImSduyBTXl!5tj)&kwSJQ zXOa`a`p*JY_ntHkI-q6nNL-9Og=a82)Hiro5YU&4|6{x_^3U-P@izsFT z+;P4fWGQWiqk5fttgAi<3LzV7D{Jj&*<+43?*cz3qj-FAo#NWXXNzx{##k2EG98WF z$33~e+kTDk43os|LIu=B=Rxr)2uy@3i-l)sYSracq49KQp@ zOUd|hie*|BI)&{b4>22k%zF^?c9cG+|I(diA9-f;$ak4UK3{ok?(NAdS gq}w$ z$@`h49U?mI9K7%beL}lavF;8%Mf#JqaFqO^+ElDDJ+sMfc!kAnHgR$L-S^4APry<) z6U$s}YT^gDuVb6NLp{T;j@|Yrcz+)!#{T}0;FD1A*IGKmSmQeXG=C((i3`NFh`;{p zuiv$jN>C|qmTN3lJv;qD&yi1h&K=|a;?6^@j9SJcqauC&Mi9^2+uQdp0&iS)av4(U z!z|&p`#ziedIe+)x*S|Av@$U}M%WfCYd)c0$uHg(xGx~uKM&bzTl_YW%XW|`iz$9% z{piZ=SAf2oOW}XvNMbXH+3y(e%fF@nPJHx1zJ@K@I+F^O&!{D}#9Tq;G7s^jE8S1< z@W1p7#|pU2EG!?(0pcq$_Zzfh+GSR4v(`?#M{lU!@;Lo9b`r%`k}RGEWVKWv3Sp1z zC{j|prMI4n%Bj_L5aZ0)q&%`E*>ZMV0yv?w@4lqE;%x{al@Y^B@TTJpuZihc4n-BPwvCH4{h4xUrZe-EpagB~c=+%M^R@X0fh zOy{%aK$%$_5UH@W^rix79qv6K8qk~aFcDf-Ixu|^J?LXHQO{58#YAeKMccaj_>fgp zjC`Y5`nbiBd9;Vz-cEkOemi}u`@X}zQ`zS;`EQwtA)G?iZZB(Rx=W_TCNj@bk%+=0 z_~&1faq|}WSct(;(llmwV*dQ8nRl6WAL9JxnC2)+|Il0Z4ffG=8Y)YjP#x>W0P5CH zBI4$KVoYLm;*-R0iD5~N*ogyF+P==`UXnmRT8YFMVXtoQVjp9li?6jIHAt6GSyLoO z(^2fNqzXxCuptE`AufmidZ^k zuEXBdjy_5~`O8i(#v8hLnpEMSWw238L-c1IP0bR#MpM(hLcbDkxpB2tkZZs zS}RDMb|-#>v!;!xwV|H<)XhsEi#NNYowui7JdtW=l3pZ55QXw9c_i6q3+XgDoQ_TT zsl)!4tCOo56&%XYlVuDU=1*Ly++*FTJ!d_A$k@|lth^>pYTKwJT9&-Vu~grl;PZv~ z93#i9zTYsvl|<^Sz}_?v> z_a*mC&XjzfE`_g%A{UA4==qlYx0&!e!AJ=AR({Vx&Cc^^c;yqm|62d6?yukRtBL4z z#+{B^L?m{HxR!B4}Vj>{K6059Q>_{K!x-bncTyL!@<O5`Ca$xLgZCUz?{IUK|h1m1UCzb2n`NP6`mnQwv=g7 zeMmJYb$sefX;P&*ojOPAuBm3E+?V1_c$)B*VFyAZLf6AXWAG4U4?ckH;9KB;!21D3 z14ct>&-gyawq1$X(s7nmQ~^9moW&iwrabk0Kz_*NYDC|y-{fz{5lz&bd>;Hb$-9$Z zCugv?!uorR*v>fY8Sjyia}jSc$8m-_x*qnr8g`(^)Ry1ps)D4j#?#D@#tQ1gY?t|n zYp98?Ht$vq_MGbn>f7PSO^4Vfr?z6~uh2JTEGoTrM?r$OSp%=rNhi?u) z9KIoZaCo`!(C{x|H?Rcl3R@pGCu~SqyRe2~4Z@m)wFqk*Rwpcq{Eg3{3q!+0$DsS? zC+_=KVC}#;_^vJy7derN=2?j8dq91iMEKYe>gXOb`oIw#jB1N#ED`oT)HrG7{t9og zV%4lnEa4Gqstk6tBNwcrqn0DTBO{UTMfv+5huu-jxt1y{)8S@qh{@N;c%JMzPG6M> zqbj_1f$`F)N~OsLNHWW*B)LsXjo!IKzfYu7ZF-=dwP@sO41{8J=XVx*lYJ&i<+~-p zA}v|SEQz%GST7MXmzVs2d3qBx#QRiUE2`b5ujNg84W7g|bpg9%3G#C3qe3?oCmEhY zsds7xXHU6yQ_FJ|wYBQeP3HtvFf`{bJXQ|u)fwztk_!+4Rs|ZpG_h%7;l%8T5s5hy zOY?XC#AS)E601-M`P3&ifXCa=pMp zy#-#i2FvtywE5ih(82RXbYP(Ni#X-4)S}Hmc4}YNYX-0%h17UX^dt^`JL~q2&Im2= zpq`~~cTb}leO2`v2AI!?@euIO6FD zlpS%8BzGng6-we=Khd;k(udw~3koscH41NWN3sY1LJpcoSA+Sk;pANSP)njKdCa?z zbbi=3*?ZV4;%`Vn2S64MxhE1E^c4Fc=uZL1aK|l2q;sn?Gj;YO+^eZ%zQU7=9?GF) zi@VKn_%k|?Q|+fUq?+F)a>{FyL7zZ|h}*Kznj1~Dmd`1l+`iL%KaxXujyR>W{-py} zU|kIgOc^MN%p!)1>B4ykL4NI;7=OgnH>y zsdRFjyy8vh9(DNc6*=_7fQGbmd_P5}fvO@7-K+sI>aoNM^`;A8BAqsd8j<9=Z}Qah zIPmrNCsX*PYbv!HHqx=?40Jt#YIH5_S?%`Zmw5WNA(M2Z|5@hbkYryZ&&8wE_3dUBvn4S$??QiUV z!!b@dJGp$p=H8yHXdAQ4vgG#c2fs36%W6S|(9+h8R*P*Aak9;P9%4It=-boJ?l*~? zhw%Z40UZPH1l9;T8B`#6S+G60HrCK1M1S8Rn_x%Cl#tdTxkEk@M^iEQ4RMKi>EJUX zuoCf|d$6kf@SlL6{4c*~-|W8qs1M}Ehj@;<2P>%y(vNPDg~cj*h0aAj*n>a(m**dP z!-UaSewTZpdy;!RpJ~*HSmoa6&9Ux79%DKB)3tDqAwuGdJ13PUHiB8{$#cAb4`>d( zKl@XSpePk=63~x#YU%V@_^sPp_CN_~p@(OWmzKL7$z2UbQPuUSiI+*@c^&ZE-{{L z`DA?+lH3RDW^{_$zM1J?d)|LyK-EA;;F_Sa!O_88LtONW$q}|MEKm5#a3j24iUnk} z`lYOrazx7YDR-ybg3m50r8~vC6va}+gbxW%9eygTTbLO-H`G70U&w{vw84FXt_PL~ zTpeHy_{;wRF&iDJBY)2JootV;^y#qaowZX`9h)Y9n?208__*xU_R8ToOKjVBXphyk zj2a5ps7}+y5rv;7gCo=t;4tkUs9EzLIT&l8J;&_#se+i<(bO>$pH5ciH0sy%p-NI4 z_dR!Ya@Kr|Ze+KXFxQz@s@&ZohvaXt`JD*TBB`#pMvDPcD-!)XS6@ox?{XqI=keK0 z4C{V6hE1i~K~DV(djCYQKNWqz=3_B>!IQp_OZ$s1@~McC?&k3$AFZJ~9{w9hRWd<0 zDQRDZ7j9p2NxBh6v7?O=pZ*^5I}Pziv+<`@Ovr@JZ~PJosS--?|B{5*grdI}|JD)* z;)SoAw1a-y!|Br5-Tu=)#t}d)M{cY+g@ENS_`2blZWP3x6D^O5f9agFfo!hBe#8DXi!+^uoYn^!ybe^4|^1LC+re`9|}7j zb~fxt*ivMdq|nKsPGV;t1vmC$WR{>yfj#IAzdfLAz&Zbl{wMuv_`RePYfj&*KD~Vc zsAW^eb{O2)V##FL0G&HdH^Bd>TC_-hhp*jd?R|)Lo5Ko4dL;duJCU`#!_~%>+V$Ca z$$1dHdLO^hgd8ylYpgS?vzBoe0Dv9tDT~X`c%5q z6~t%w+<6f#cMJJoJ;+zEI}Q?YTiEdpNpqCFF1r^(tcp&F?@?NHOOQX9m|~vhXWo2}wy+iwb0KtvAb2O*bD^d>#`GF$n)j4Pv85 zShCS~qrUC9%}Sr=(NwhxB9G&(Z))jINPdJx6pN57;UU`~4@3a@=AKJ8e~8LIV+@ig+}K^}PnoGiu?Qv@2Y z))nP?Lw~R0q#u6Iqc7p7hxq$mHa;GRMIBwE90=R^h|0(1-Jle8eB>| znRq(!E_ER)5Ji58jLQ7@|CW=dU7xxuX^4sV=4ginsJZJQRg$jIQRjxID}Ab-nrmfq zB(~9T@_c#^s$k}&PyAxE_p)^KUFVz8ZKhUCiFklXL;`*f zE`XQ!Nk~CDzN`)1NJWE6p`VB&tq@`h`4s##I5zlY@YUcI!8L+ogL(%g1WpLd5=hTm zB+G&UZ~f<>-QLa%0XYD2zXv$+Yb7$ZlVk3PIm2t)>wNlCQxnVIFW*qNa8-M z{3{|C>KhsrjQfKLR?kiHyPIQaJVRbmWmi`0BjK)eL^{k?qtJC=eXQ?$ilx9o#Q?TJYB3Q{?AI^SMCo>s~4l9OSbm zcwle=VpZqh1$q=XIxr&eLO`#8z<{0pmHlJz6}Wvzv43O99s0*s%ytS-!5MU{r^uSR zz8nk9Icf;LAxi2al`mg`MGntQsMSA61FwnAYXH}~NPcR2U_OP@;rK-Cjst&4ZmI*; z!&flYITI`TNP6Q|cIG0#C@a@BfPM|8Z%Hq_CjFcXozI<3*xO?6!PJ(S4F&v*V;Ob6 zvZI;(@U$Q@{VICFKqJEVNPUQ>@RQQu<5A-cUF7G|A$7H<4aY`LT66`Sig-?A9&~&% zGRqq*(3+<-HO1z6hGXeI?k?^=20V3e%^}h-%Dvs~z+U9zxr5!PygMU)h~abW(p$brJ0_r%lopg2+%fZ>G9F5CA;DURamQ%wdJsM zw_dRN&}n%9-Qivke>IG%Y7xGD=|lh8Hx)douit2V@JsN-U-SFrm%+cNe+jTDrK*MR z_kozJZyaB#JAMsI_b~DZ)5AR8Q%P`zZ#!z;tc6Zqpu21YeP>S)t=7_-nu=ayu)p3V zC#XDC*-lbVu?+RakBUC{7ar3QtiJR|o*P76oul-W@uOnIM%H8sRIESMNwZYcv!lxs0XAyMy*;v<1x*o@4N3QD{f%SPgzhl6IM8|7K3FkRyL#nkrB!_qt-M;MP zkQF65F`Kgs75T#Oe$}K_{x$0OT_vk*hU0@{5_Y@&E~`70JK9yBzTgGWtRvy5GhH?C zI^3lS$UdysO^FYx<-FsZ27ij77gjC!=4#@BV_m;o?WuNt%QF@#u3}4fQbpun`YjHj zj@nb>6&|!QqAr@yZ1_VKU^cz*A%p)eebJktKOLrLK@Pn#c7!PM>&9UBvD$3(;d_eJ zDA`)wcHY(jnPe%se4(uOE#Kw7V}0lNp7%}79-Q=x#^=x+kHS(quk`g@PYgj`s9#CH zPrf7R#C*bMna_GE=Y97veeC=m;N#=7z?P2e&gNLJW60{PPZY{#^u^y)A*)S1SPVMc z1bU|xqE58R{!d8AxUPWSAieZ6bn)7pa+`6Yre_uxr~;v(0z#2e&x0j zjWozJpQo1u1BSSx$S|&n7393T5Hi6_YT32NrV~gOSQpoSuExY@uY%^DrMK&Hx^8@S z<-=b@UIHEz8-B1C^i6sK_S6Sgb{QqfAZUriIf(p$SfaqX8efee=3RUz@68KD-p-{4 z=_d0H)xq3yyQoBkst44r>xNe=R4a=QW)4w#Wvv_N0AAX9fVC@6_oc4H?G*Jn=kt>o z?czQ=sNd0)Dj!{a%K5r{M`OutL4A*2z8UHMRLA#>Z*?rXy1&8C8h-o8^F$aNTxEdiGtW z8t^XaaejcCm7?eH2Vj1dx7uo;yCYGY1Cc1(xN^FWQn_+Fm{=GousFN*-0kBjOtpb! zo>}z2ErXo+fZXvO9y>j%CP5V|l4WznbKaw)k6bidR24`~7J7PW=F~vSDS?zT8MvBD zJ;QNSWNbkGPEj(=FJN0cfyLk!we>#Z0qbnGq8eT*V!6xVU4DwSpcVb;JHRgw;cf4( zMH2hbOTVbSCVS|C)S)bwwP?KuJ)81bM(Ib;HO^4GZ=5!X&NRKOoA4#?!pFItm;@>f zTF+Vw*_PR!(sRDI?H-!xWy=*yWox+YBel(D`c&}QZ%a+jw^`P0czkMcWwh-%)h+uF zlj>^==Vu9I!p2b3K~yCawq4YJeNBy2gQxpix>+7u3J}FG3k~f)alNmEiBIY(Ui4ty zqMxNMNGCB#K1D(dCDOMjGaE-H^)EBlIOVZW6Ql{ynZv9{Z9h$}HD0;LkfpTOwbVV_ zlZ&jV@>FjuM0K5S$R8`HO*P4#75hel=K;N>w?HN7dg0Cjt{M1E(_){R@9D`7t;KS5 z-~Ab0|G*8`@oY18!RH;sZI+@2p9UVj^8}cIa%;}GKTskKZ&Oc zqQ>7C*;w3UrL&9ra;h0m&C<)}L-|;&(w1sN!~<${4W^^+dKpenf`@o}vuH1{^u(|a zKSh45cdxWu(3|FZQ}o3vdN8rBo%9H@`!4GBEq5&u^dF73%%x{}32)Ex5bOja*}13e z!F_x*nsudRIn~!wkoC93`kFd90c4?mAYb&po|$aq#@6B1>hPUnmM=t$OtieV6u0KI zwzrhi2htyHu$HJb(W~ib5!!cg1)pJcvPTY4StSS?Y#ZUC^FWB)Y4(ERZ326`AQ|3< zZ|?+xea!X7YxwR)C{YbKzK00cW~`bY>$?_xG9C4`8)9ot#NTnBnCSV&PdI#KG^!p@ ztlVHrwC9EKnBD~IsNwkD(~Zot3hvpSYG|PAsK}s+kF4D;PbGSEgc?1~4^qeCxr8pP z4~?%L>G2p9WezF@zXA_tiBkAxU*PkffY0F?6krbB;V+X<*&j=ZpGZUP<=19iY6d5W z1=>uya8?qFsnS_NPQ!Nnmv}F#VTHRw2fCUv+O(S&G-RdAjZN6B((^?7>zYN)*Zq>T))b^~`zb z%YrzCj#vRxoBxsDk%xSqV(_2F=v<3D2i#TQ63ysf{mxkl$+reoLQ)yUJU?Cc$+#ax zyv$fvS$7I}cL^#2YwoAS{T^}Nca`$wwjTy>#TRc>pq?A-d@^MdI)SF{%@G&h$XG{88ORWw2WGU z*hKA$NNWJ{(>2Qw{K<`|=UZI=No?pO%Mj}O_))3xGuH2{noDHS>VaE7>FdxycT@9c zs5mAEvQMYw2K+C%wT)23^;q^o$*hkOvpI(1U9L{w-s41M~jk?tmuGOa7U2STEn5JFq#*-Y!Y>pFMd4=j{ zweiD;YRgn?5ViW6(Ct9Tw^W-{m4lVlXNP!?UG@v{MAL{em`1GTX|jO-qk8HRyx|As z2QeAz^;WS`_A&jj+-{{_Xm8?EdQh|2S5`HT825}Vbmh!V*QBm;KQ&OlP@yCr+OWTD zP94@Q=5O@sCPrC20N1hW42QQ=rH^(pz4+$QXZW639REr*Qf5_bDSfeMWivaGE&7=r zOwG)|Z0kufDhAR!I#!#ajlxQ?fqlzL&Q+1xCuHLm^0^2D+N+8))cBug#>!EeraQz> zGZUJ`661s1sNK}Qic|6g-1Vn1*lZ)?sTmzWeW1PO6go8qQblwdmWV{^s%J4r839Oc z8KKVG(d}}GSTo8fM+Cq)&mtp?nm>J^i@_q$OhNWf756^RL-U?^3)dPU%A46eq0|!& zr#ebCIN3xjRIR1Q_yCP_dD2m5=sTA8hvqS;&Pt+5TFM{PDSZPLB^v|eU2z9WF;Xl; zA{&4Qr97QEG^F7oR5UL~wn;nL3Hx&^V}eoB+$~e#BYr{T@L^nGokkEi~6Tde?ZeQCC$ZeDkILOyDotk6G+q2z<)lg-3aEuPGqy!skZNlq|_ z0eO=(Q%`3pq(2~bA`SK3mWWzNgt6LCt(_<=2LXvQWKAtM(TVT$6k2&1O|Efs^S1oT zvsOUA%4^f9=9~m~fWn!k*i%g}WT0tsAv^FZ4pXE7iCy~Kn+GpaR_EOo&1gDya z8C0mPt8JF)%>RtD=4i2#o^ttyGlQL6{Yz0+r3lQm^jdf1}AD%jVkt^x=1P{_`cKhPWYcO| zo?EY44a*a~B3*1MiT2ta{TKO=A=VfAPO`-{^pnN#wuZ!oKGYlP7ey=R-)M1$9XNrn z{|eQVFPdwxM3vQY!aJ&xCwh}CrN!nJxtji}=isd#sKzQRXr2KC;MW-=Bk@8# zMR!^T?cEOEjfUS3g-`FHc3XQQt7by=RK0Ek8n+Kx@|w!ZpUpm0M!t_E(g6$Nd2_Y- z(yU2!uJv>PxIx{fN9G{8MU17x(?@eOwVM0Mv080?BeiTU(cfW?@s>X7D`au40`aiX z@+=X1O^xGbEio58bBz`v;*9=Sj?)+yQoBe3L1r_Z zr~?JeNbkB-mQQjOU3k_S6NTL}$)~7qJ6oJawR?1hf6Y?*1=~Y3)fnqR;iT{JC{KW> zYmM?9?EB1`L2GE1McyhQd+V)jWqi`w8tGQqknEJ9#uE`~ZAQ$*9?MmE&t2Yi!Y$2J zdMc_Eue98gYdvYG+NvAxWU%E9z3r(pYR0&~IC z1@p%juWLs2jw}}JVaN_0+8((-2Gp+DPvUq|Fc?@nk+*oGj z1L||p0lAhKZ|+5pIO3r*mpFxmsfhMUHZ&(A6PNQmGWEe7?Ugs^Xq}13)VZ>T z=Ej@*Ruqxzv5B=aI-B95H`V!7Mb9 z`u2v-2;-&Lg-5Enw%go7F2HYRb@vKmiI}R}wF|PN(c3-LmCIe*I3?#0i~2^EH`2Qg zxJJ6|o=MWGzhy4h}PSJ*k@Xj_3PRX$tqtI4p)#1--<#!dt+eGEwNjQMAv}bJT!4DakQc>I ztsBJ)aFhx3qiO8}ZJZ;5kCv=41D5GfGckZD5%sG8*Mwsh$0S=y*Xb zBCA91EXTQ>4&uVyh0N^QA-%pnTC_07c}h}cyO7b09%3z^qa}o99`WQc-kF)G<=a5p zCC?)}C%B`G&GMHv6luPY-bhaJ*jdFmqq#QJ+Kou3v6jX1f_pB#V+MIVqKK`r?BoZ#0b}|KKp!&_*Bui87W;(#~}A5If%M?LAD@E zPg%(GgsyRO&86B4OSrYRK1{}WCVK80{$!e=Z|h^Vwz8~|i)wBs%(2=GdY8=9gn5oE zXv%eld99C)TCJ|_Sz&p0zecimMm-G4H`>)Syy_?zFHNtVv8D#!t8RJXW9-rp= z1|y^EwA1dHs$I4A#v?S}I$A3#1<^)J%$*{yrKa_UrLtZ^Y{GWmQnb=bSWeLqs*zlY z-uOs9)}k%dY%Od}E$8G&&wZlF8=A%R!nSrkjcva)xACtljB03CjR|@|pOrqZEc@gc z_rK1zuCYd4Z5SHSCB20>W0b)n{MggdY%Gp~^Rs}<^;pAtfSuv=w*61$GJg^cp3gij zuOi3g)mF$$*kE+@lUv4G*&7e-X05!)Wv23ca&2+Dj0Dk=xPuP*JsD}7z$Q@27%ER_ zDJ(Cjk+xP2GqPZbtzl+Ea*H7=*eO!T=~Q#ei|kTgD??VsQf!6(q8ZVJEAUgTN3Tpn z*Mm1?tQVpi-*zeq9HTn-8sn1KX?aHv>IK>*b0;>_FFf@Ja_a)}+E?pewfdr^sZk@@ zX7n{@iW&Me%P0#Hn|2Q!`4m~hN#NVfY z*~oRh#3pG+65CJDg}m%xIjs$H{XpW0y1@T(Y9+B#G}g{ae{+|ogD1+UMV7D+ncv$j zPld-2o`>#!hA9{6-z?FVX*%7Wu+jWumZXBz94J9P`1t_29C@7Opbl&b=+I$#A76z4 zVx44Q2Ur@h#uGiy-1|K(%q^mY*julAipeG9?$xx6(N~Eq)V)9AUc_}7 z#Re@zkJ8+7qFLDZ;qf<@W9hMDS(yjVFNo$nSk`9jQ?zvSdoxVr6Z$r0C%63_XX|P6 zWf3a4RFb9`NEf|hmWFy-IMz6GqYOY}Dob6#&*-;x==PnDi1cG3jjjX#i?!7vt%$*% zF&|m?Ih^w#eua5jaXMZ$m1EK4R%rK+5+iInC{B1_z2FkHF`^%a|lzlp{>jV&gdxGa`y zN!mtlHMEKJ>bWTA;pfSzC5qPKp|`Wv6f8e2(XmTVcXJ_{d1?4g0s8kOVjHR}=9_-T zOV2@bwU*biMW;8C%w|-DlCNMl{zZyihn4%NtY}6ME0xF04}b57UG6G6M6&V0*k|68 zd9=KGh+al3BO1|XWGuX=6}cdZ^fE~%S7eo03)@2mB!DgYRWyyuSet6eO~es)BXj5* zm1IwA52&eqj&2sCi~W zJ;e|vc!Xs?KU;Un6PMZ};n#hTCPKJySOaxdg>r+kLZ>lo7WC2YwL z%$%|_&#Oi!sP(|)S!(IFp=*^dy-plhU^ikjyJI+vWwNWbO6w~!$*%MjH<4@eV40XG zuA+_Sk;~-+C}J0?jAW#$)O-4Z?W1q~OKfA&)H6Fud~sv++EFr-h$MdP8+~=_(4)`A zzNfZ$Ra{_IuIdJiHI#>!mgeY}YOdWM-b!OFR;`vG?F9=b|TV?CCPc8q*KZ(2^g z{{op?PBD}47W!gEtWOSVeLab|xk%AmuEL7j44QmZ8)UIsi&`dWe@hcNriXb_rq!D2 zO^_qE>tjR>tOX~HvdDBP=qlXHQeGb?mLtU#FpG*z$gO)caz@C!EJJ+I4YF_FV$rxl zt);{4$Rc#JEW~p@q)X^A>ICG*?j3;!{SoWrJS;j*smtLsUYMG&usXA})?&BW*~mat z#3GrVJj!TvtOWeydCZl@74on)%F4tRbkqKlr;YUZ?u*G3*aoe7St!#kqM)*3hd3b; zwDQ>9zOt&9jo)ZQSENH+(UxdYqK@hD1k!J0iY$ia*ORpv!RUXRc!WGJjgvA#8%QmQ zxth}~X*@)eDNEEowYBM3^hs+@HdZ<;DY?zJaw+v$s_V5hEAZ0IG>u8SsGtVCu5#DP^72F(RVGo_-^F(%ySR$^fzCKTxeLoEu*yj=4LFz z=iMvK^7>tCPFq{cW|7t`O)NCW5}S|~57%6B`jXLR{}xTmNKXs*7C2g4a%SoR zhyR+l@h|*EmRMWa0h^RfpNtmq4*yX@<2n*Y4K#$w*!m|>Irym&EO$`XawYbSV!&j5 zVsC#K733>%5*uM&agW|EF-B`L)Dq-FIv}6Y8fZn4N%H{bo3J_9kr~EAt1@A+3=-$% z9jas&1!{w^8TyEc^l$Bkwfd=+gKAIT#bG&)Zf#p-lvYX4qBjI~bTIQPHqHq|q*c@c z^+H%*9^tv{E7L-^Q$urFLpeUs!|x?Fsx4o#}YpmA&YOJzx*^dLQu*RN=XtBAzkhS9rkBLVbd<#`J+NrNAdOL@%b<6nFXW;iQyg=s^-{*Bed&uBODB7 z9@7@$+3b!bP?wqIF8YO))Yfau;4@$0SfA;0m<33)5I1mu6|4&1Pb-FT=Cf9W4EPw) zQ#Qk&8YzE>Y{Xt3)@F%<(guaSZH^RQv}^hvsN!^4!i+P9W7!PUT9c*TL_a9Tny;|$ zzcedpZ}p6p2fTkCRkI$NMZ{k17TKQpv|y>C5sR4JM3nwf<=ksQVmmcNMjF+j-Cwnj zT-96~E2{wgCuAWkdoSUZ^+YM6*!}`bEkI5oeG{~Hx6DSwYB{pqvJmr)45XD5`Q&vx zl9lKg*BAfBMY1|NvW~39op>h)(R1uK7E}{ip#xsX;>06l1k*kUojz%w zfT(U}1or<%$Y71|>Xl_D=Mp)bPj-_>WEH$H0a$~pnop>aUmiX?9#2a}da#bwb+xP)%nS0ScC*v51aY{G8Bck6*9@U^ zP<3uF`4A|5fTJkC0t6Ayvhj>ifLL_{RX_M zfV2{QHlKW+Krxp&{1jVQjjnjt9^er^2QHPTXIW~lJB0uPM zDB^ckY%KMWY63BR#1q*Luf`%|zD#ucu7f8u6do~vG1kIo+=yL#!Y3P2PiwUAzGx

Team, I know that times are tough!

Product sales have been disappointing for the past three quarters.

We have a competitive product, but we need to do a better job of selling it!

" -} diff --git a/resources/tone-example.json b/resources/tone-example.json deleted file mode 100755 index c3cc7f90c..000000000 --- a/resources/tone-example.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "text": "Team, I know that times are tough! Product sales have been disappointing for the past three quarters. We have a competitive product, but we need to do a better job of selling it!" -} diff --git a/resources/tone-v3-expect1.json b/resources/tone-v3-expect1.json deleted file mode 100644 index e41cf8529..000000000 --- a/resources/tone-v3-expect1.json +++ /dev/null @@ -1,8680 +0,0 @@ -{ - "document_tone": { - "tone_categories": [ - { - "tones": [ - { - "score": 0.971214, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.546126, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.543228, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.072227, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.057439, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.53, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.003, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.55, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.241, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.513, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.467, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.749, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - "sentences_tone": [ - { - "sentence_id": 0, - "text": "Call me Ishmael.", - "input_from": 0, - "input_to": 16, - "tone_categories": [] - }, - { - "sentence_id": 1, - "text": "Some years ago-never mind how long precisely-having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world.", - "input_from": 17, - "input_to": 224, - "tone_categories": [ - { - "tones": [ - { - "score": 0.170393, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.350151, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.201739, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.114688, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.469036, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.114, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.728, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.406, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.166, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.284, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.375, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.92, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 2, - "text": "It is a way I have of driving off the spleen and regulating the circulation.", - "input_from": 225, - "input_to": 301, - "tone_categories": [ - { - "tones": [ - { - "score": 0.335625, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.263686, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.429728, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.20467, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.139387, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.628, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.755, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.253, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.461, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.312, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 3, - "text": "Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off-then, I account it high time to get to sea as soon as I can.", - "input_from": 302, - "input_to": 795, - "tone_categories": [ - { - "tones": [ - { - "score": 0.53187, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.50254, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.36085, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.037935, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.158363, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.203, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.008, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.318, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.7, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.444, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.51, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.81, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 4, - "text": "This is my substitute for pistol and ball.", - "input_from": 796, - "input_to": 838, - "tone_categories": [ - { - "tones": [ - { - "score": 0.175965, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.290521, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.215051, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.302646, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.259432, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.569, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.571, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.446, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.56, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.81, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 5, - "text": "With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship.", - "input_from": 839, - "input_to": 932, - "tone_categories": [ - { - "tones": [ - { - "score": 0.183406, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.518299, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.150604, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.168203, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.307349, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.346, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.888, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.706, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.795, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.107, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 6, - "text": "There is nothing surprising in this.", - "input_from": 933, - "input_to": 969, - "tone_categories": [ - { - "tones": [ - { - "score": 0.202684, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.331177, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.335063, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.249111, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.433038, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.35, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.044, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.795, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.935, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.739, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 7, - "text": "If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me.", - "input_from": 970, - "input_to": 1107, - "tone_categories": [ - { - "tones": [ - { - "score": 0.263035, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.203018, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.108853, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.135628, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.430709, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.605, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.176, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.315, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.041, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.721, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.707, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.953, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 8, - "text": "There now is your insular city of the Manhattoes, belted round by wharves as Indian isles by coral reefs-commerce surrounds it with her surf.", - "input_from": 1108, - "input_to": 1249, - "tone_categories": [ - { - "tones": [ - { - "score": 0.208645, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.505883, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.139235, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.123256, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.209934, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.591, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.655, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.587, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.5, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.115, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 9, - "text": "Right and left, the streets take you waterward.", - "input_from": 1250, - "input_to": 1297, - "tone_categories": [ - { - "tones": [ - { - "score": 0.296232, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.248731, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.249263, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.315715, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.234019, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.249, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.813, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.832, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.817, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.017, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 10, - "text": "Its extreme downtown is the battery, where that noble mole is washed by waves, and cooled by breezes, which a few hours previous were out of sight of land.", - "input_from": 1298, - "input_to": 1453, - "tone_categories": [ - { - "tones": [ - { - "score": 0.373581, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.556262, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.197002, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.108432, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.158906, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.778, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.484, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.311, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.301, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.261, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 11, - "text": "Look at the crowds of water-gazers there.", - "input_from": 1454, - "input_to": 1495, - "tone_categories": [ - { - "tones": [ - { - "score": 0.098702, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.639292, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.2851, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.124082, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.294147, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.929, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.224, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.337, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.221, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.192, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 12, - "text": "Circumambulate the city of a dreamy Sabbath afternoon.", - "input_from": 1496, - "input_to": 1550, - "tone_categories": [ - { - "tones": [ - { - "score": 0.169689, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.206569, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.181326, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.247856, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.395501, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.975, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.932, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.388, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.137, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.18, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 13, - "text": "Go from Corlears Hook to Coenties Slip, and from thence, by Whitehall, northward.", - "input_from": 1551, - "input_to": 1632, - "tone_categories": [ - { - "tones": [ - { - "score": 0.207906, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.371378, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.280693, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.102245, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.416521, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.93, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.571, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.265, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.234, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.305, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 14, - "text": "What do you see?-Posted like silent sentinels all around the town, stand thousands upon thousands of mortal men fixed in ocean reveries.", - "input_from": 1633, - "input_to": 1769, - "tone_categories": [ - { - "tones": [ - { - "score": 0.262753, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.696676, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.194555, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.15851, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.270896, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.082, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.351, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.201, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.722, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.628, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.347, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 15, - "text": "Some leaning against the spiles; some seated upon the pier-heads; some looking over the bulwarks of ships from China; some high aloft in the rigging, as if striving to get a still better seaward peep.", - "input_from": 1770, - "input_to": 1970, - "tone_categories": [ - { - "tones": [ - { - "score": 0.382868, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.489318, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.205163, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.118944, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.425947, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.135, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.767, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.954, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.691, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.157, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.226, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.243, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 16, - "text": "But these are all landsmen; of week days pent up in lath and plaster-tied to counters, nailed to benches, clinched to desks.", - "input_from": 1971, - "input_to": 2095, - "tone_categories": [ - { - "tones": [ - { - "score": 0.109781, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.348402, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.100454, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.439683, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.396121, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.493, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.871, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.405, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.274, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.258, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.671, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 17, - "text": "How then is this?", - "input_from": 2096, - "input_to": 2113, - "tone_categories": [ - { - "tones": [ - { - "score": 0.289338, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.487263, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.184789, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.060132, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.370277, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.847, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.31, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.132, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.157, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.335, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.954, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 18, - "text": "Are the green fields gone?", - "input_from": 2114, - "input_to": 2140, - "tone_categories": [ - { - "tones": [ - { - "score": 0.150856, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.364911, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.294397, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.153937, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.284773, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.418, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.897, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.157, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.342, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.102, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 19, - "text": "What do they here?", - "input_from": 2141, - "input_to": 2159, - "tone_categories": [ - { - "tones": [ - { - "score": 0.298403, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.484869, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.244632, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.119957, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.282312, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.06, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.19, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.93, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.985, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.261, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 20, - "text": "But look! here come more crowds, pacing straight for the water, and seemingly bound for a dive.", - "input_from": 2160, - "input_to": 2255, - "tone_categories": [ - { - "tones": [ - { - "score": 0.081729, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.366571, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.179309, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.336148, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.33228, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.459, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.38, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.891, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.286, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.371, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.222, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.528, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 21, - "text": "Strange!", - "input_from": 2256, - "input_to": 2264, - "tone_categories": [] - }, - { - "sentence_id": 22, - "text": "Nothing will content them but the extremest limit of the land; loitering under the shady lee of yonder warehouses will not suffice.", - "input_from": 2265, - "input_to": 2396, - "tone_categories": [ - { - "tones": [ - { - "score": 0.214428, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.400577, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.44209, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.079106, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.253806, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.721, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.202, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.274, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.214, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.671, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 23, - "text": "No.", - "input_from": 2397, - "input_to": 2400, - "tone_categories": [] - }, - { - "sentence_id": 24, - "text": "They must get just as nigh the water as they possibly can without falling in.", - "input_from": 2401, - "input_to": 2478, - "tone_categories": [ - { - "tones": [ - { - "score": 0.149916, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.438289, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.309294, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.103366, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.428773, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.451, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.556, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.076, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.546, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.511, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.826, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 25, - "text": "And there they stand-miles of them-leagues.", - "input_from": 2479, - "input_to": 2522, - "tone_categories": [ - { - "tones": [ - { - "score": 0.195838, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.609443, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.237532, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.218651, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.238227, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.498, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.201, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.812, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.902, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.23, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 26, - "text": "Inlanders all, they come from lanes and alleys, streets and avenues-north, east, south, and west.", - "input_from": 2523, - "input_to": 2620, - "tone_categories": [ - { - "tones": [ - { - "score": 0.20581, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.242848, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.156057, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.317132, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.284507, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.72, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.566, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.565, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.72, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.818, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.111, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 27, - "text": "Yet here they all unite.", - "input_from": 2621, - "input_to": 2645, - "tone_categories": [ - { - "tones": [ - { - "score": 0.221384, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.169253, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.151174, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.250741, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.430384, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.987, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.277, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.267, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.932, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.954, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.287, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 28, - "text": "Tell me, does the magnetic virtue of the needles of the compasses of all those ships attract them thither?", - "input_from": 2646, - "input_to": 2752, - "tone_categories": [ - { - "tones": [ - { - "score": 0.225617, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.571378, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.290246, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.164151, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.183171, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.597, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.465, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.524, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.823, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.429, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.364, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 29, - "text": "Once more.", - "input_from": 2753, - "input_to": 2763, - "tone_categories": [] - }, - { - "sentence_id": 30, - "text": "Say you are in the country; in some high land of lakes.", - "input_from": 2764, - "input_to": 2819, - "tone_categories": [ - { - "tones": [ - { - "score": 0.141122, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.421809, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.361904, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.202674, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.359623, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.614, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.603, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.387, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.919, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.785, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.035, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 31, - "text": "Take almost any path you please, and ten to one it carries you down in a dale, and leaves you there by a pool in the stream.", - "input_from": 2820, - "input_to": 2944, - "tone_categories": [ - { - "tones": [ - { - "score": 0.279927, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.343172, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.36336, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.149495, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.305648, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.733, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.412, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.649, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.748, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.876, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.03, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 32, - "text": "There is magic in it.", - "input_from": 2945, - "input_to": 2966, - "tone_categories": [ - { - "tones": [ - { - "score": 0.151178, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.362646, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.405931, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.202287, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.323321, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.58, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.153, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.393, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.743, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.511, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 33, - "text": "Let the most absent-minded of men be plunged in his deepest reveries-stand that man on his legs, set his feet a-going, and he will infallibly lead you to water, if water there be in all that region.", - "input_from": 2967, - "input_to": 3165, - "tone_categories": [ - { - "tones": [ - { - "score": 0.073153, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.722682, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.45649, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.065335, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.408581, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.114, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.255, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.459, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.229, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.9, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.784, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.309, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 34, - "text": "Should you ever be athirst in the great American desert, try this experiment, if your caravan happen to be supplied with a metaphysical professor.", - "input_from": 3166, - "input_to": 3312, - "tone_categories": [ - { - "tones": [ - { - "score": 0.252295, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.52585, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.234371, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.112877, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.175748, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.275, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.199, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.661, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.392, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.591, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.412, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.389, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 35, - "text": "Yes, as every one knows, meditation and water are wedded for ever.", - "input_from": 3313, - "input_to": 3379, - "tone_categories": [ - { - "tones": [ - { - "score": 0.174186, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.248523, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.148391, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.25751, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.475705, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.675, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.786, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.749, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.316, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.261, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.133, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.636, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 36, - "text": "But here is an artist.", - "input_from": 3380, - "input_to": 3402, - "tone_categories": [ - { - "tones": [ - { - "score": 0.188722, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.138485, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.171406, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.293563, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.528097, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.615, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.03, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.393, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.552, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.844, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 37, - "text": "He desires to paint you the dreamiest, shadiest, quietest, most enchanting bit of romantic landscape in all the valley of the Saco.", - "input_from": 3403, - "input_to": 3534, - "tone_categories": [ - { - "tones": [ - { - "score": 0.115039, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.136932, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.228761, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.323535, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.433443, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.493, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.735, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.761, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.804, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.545, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.136, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 38, - "text": "What is the chief element he employs?", - "input_from": 3535, - "input_to": 3572, - "tone_categories": [ - { - "tones": [ - { - "score": 0.398249, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.351877, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.410105, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.088988, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.129349, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.372, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.519, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.351, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.423, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.278, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 39, - "text": "There stand his trees, each with a hollow trunk, as if a hermit and a crucifix were within; and here sleeps his meadow, and there sleep his cattle; and up from yonder cottage goes a sleepy smoke.", - "input_from": 3573, - "input_to": 3768, - "tone_categories": [ - { - "tones": [ - { - "score": 0.265136, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.796105, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.075884, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.126968, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.210043, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.114, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.601, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.518, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.753, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.872, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.214, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 40, - "text": "Deep into distant woodlands winds a mazy way, reaching to overlapping spurs of mountains bathed in their hill-side blue.", - "input_from": 3769, - "input_to": 3889, - "tone_categories": [ - { - "tones": [ - { - "score": 0.118054, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.375256, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.54878, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.12193, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.235122, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.773, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.711, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.6, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.578, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.185, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 41, - "text": "But though the picture lies thus tranced, and though this pine-tree shakes down its sighs like leaves upon this shepherd's head, yet all were vain, unless the shepherd's eye were fixed upon the magic stream before him.", - "input_from": 3890, - "input_to": 4108, - "tone_categories": [ - { - "tones": [ - { - "score": 0.441053, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.262616, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.138243, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.023707, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.530394, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.273, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.11, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.43, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.166, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.771, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.595, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.739, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 42, - "text": "Go visit the Prairies in June, when for scores on scores of miles you wade knee-deep among Tiger-lilies-what is the one charm wanting?-Water-there is not a drop of water there!", - "input_from": 4109, - "input_to": 4285, - "tone_categories": [ - { - "tones": [ - { - "score": 0.37904, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.175941, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.260338, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.402414, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.162226, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.528, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.558, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.567, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.67, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.148, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 43, - "text": "Were Niagara but a cataract of sand, would you travel your thousand miles to see it?", - "input_from": 4286, - "input_to": 4370, - "tone_categories": [ - { - "tones": [ - { - "score": 0.033412, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.429261, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.434537, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.380345, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.262543, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.139, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.067, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.756, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.768, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.568, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 44, - "text": "Why did the poor poet of Tennessee, upon suddenly receiving two handfuls of silver, deliberate whether to buy him a coat, which he sadly needed, or invest his money in a pedestrian trip to Rockaway Beach?", - "input_from": 4371, - "input_to": 4575, - "tone_categories": [ - { - "tones": [ - { - "score": 0.267462, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.61645, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.060459, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.083649, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.46912, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.019, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.065, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.641, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.446, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.433, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.277, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.39, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 45, - "text": "Why is almost every robust healthy boy with a robust healthy soul in him, at some time or other crazy to go to sea?", - "input_from": 4576, - "input_to": 4691, - "tone_categories": [ - { - "tones": [ - { - "score": 0.222434, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.151632, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.146582, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.199168, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.371779, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.614, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.671, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.173, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.692, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.379, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.772, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 46, - "text": "Why upon your first voyage as a passenger, did you yourself feel such a mystical vibration, when first told that you and your ship were now out of sight of land?", - "input_from": 4692, - "input_to": 4853, - "tone_categories": [ - { - "tones": [ - { - "score": 0.289226, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.403452, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.388116, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.148897, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.177373, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.099, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.175, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.446, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.872, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.875, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.031, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 47, - "text": "Why did the old Persians hold the sea holy?", - "input_from": 4854, - "input_to": 4897, - "tone_categories": [ - { - "tones": [ - { - "score": 0.156871, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.440361, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.372559, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.076162, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.261716, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.531, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.286, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.138, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.128, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.879, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 48, - "text": "Why did the Greeks give it a separate deity, and own brother of Jove?", - "input_from": 4898, - "input_to": 4967, - "tone_categories": [ - { - "tones": [ - { - "score": 0.372514, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.425748, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.326713, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.097709, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.306402, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.652, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.508, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.517, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.384, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.498, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 49, - "text": "Surely all this is not without meaning.", - "input_from": 4968, - "input_to": 5007, - "tone_categories": [ - { - "tones": [ - { - "score": 0.237539, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.227237, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.376581, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.069574, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.540447, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.886, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.997, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.401, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.001, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.832, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.376, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.992, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 50, - "text": "And still deeper the meaning of that story of Narcissus, who because he could not grasp the tormenting, mild image he saw in the fountain, plunged into it and was drowned.", - "input_from": 5008, - "input_to": 5179, - "tone_categories": [ - { - "tones": [ - { - "score": 0.079256, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.671545, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.535755, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.023619, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.420106, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.732, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.449, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.708, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.133, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.591, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.445, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.739, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 51, - "text": "But that same image, we ourselves see in all rivers and oceans.", - "input_from": 5180, - "input_to": 5243, - "tone_categories": [ - { - "tones": [ - { - "score": 0.066081, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.227092, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.2573, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.269542, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.654919, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.786, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.128, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.016, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.935, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.954, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.961, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 52, - "text": "It is the image of the ungraspable phantom of life; and this is the key to it all.", - "input_from": 5244, - "input_to": 5326, - "tone_categories": [ - { - "tones": [ - { - "score": 0.046707, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.140698, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.645008, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.165148, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.333413, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.6, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.956, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.789, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.367, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.193, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.238, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 53, - "text": "Now, when I say that I am in the habit of going to sea whenever I begin to grow hazy about the eyes, and begin to be over conscious of my lungs, I do not mean to have it inferred that I ever go to sea as a passenger.", - "input_from": 5327, - "input_to": 5543, - "tone_categories": [ - { - "tones": [ - { - "score": 0.405999, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.206239, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.216264, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.299023, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.319107, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.275, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.196, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.281, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.405, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.476, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.52, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.853, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 54, - "text": "For to go as a passenger you must needs have a purse, and a purse is but a rag unless you have something in it.", - "input_from": 5544, - "input_to": 5655, - "tone_categories": [ - { - "tones": [ - { - "score": 0.242366, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.313293, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.391356, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.202589, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.276341, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.053, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.442, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.16, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.627, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.465, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.598, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 55, - "text": "Besides, passengers get sea-sick-grow quarrelsome-don't sleep of nights-do not enjoy themselves much, as a general thing;-no, I never go as a passenger; nor, though I am something of a salt, do I ever go to sea as a Commodore, or a Captain, or a Cook.", - "input_from": 5656, - "input_to": 5907, - "tone_categories": [ - { - "tones": [ - { - "score": 0.393608, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.510843, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.296177, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.071568, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.302687, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.066, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.772, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.436, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.229, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.349, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.313, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.826, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 56, - "text": "I abandon the glory and distinction of such offices to those who like them.", - "input_from": 5908, - "input_to": 5983, - "tone_categories": [ - { - "tones": [ - { - "score": 0.179585, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.479747, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.424013, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.246049, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.1726, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.289, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.153, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.276, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.762, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.847, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.888, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 57, - "text": "For my part, I abominate all honourable respectable toils, trials, and tribulations of every kind whatsoever.", - "input_from": 5984, - "input_to": 6093, - "tone_categories": [ - { - "tones": [ - { - "score": 0.357501, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.34783, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.29798, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.095727, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.332466, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.847, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.352, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.402, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.368, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.441, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.932, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 58, - "text": "It is quite as much as I can do to take care of myself, without taking care of ships, barques, brigs, schooners, and what not.", - "input_from": 6094, - "input_to": 6220, - "tone_categories": [ - { - "tones": [ - { - "score": 0.311786, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.246754, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.205102, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.310913, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.413132, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.223, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.179, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.352, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.507, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.909, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 59, - "text": "And as for going as cook,-though I confess there is considerable glory in that, a cook being a sort of officer on ship-board-yet, somehow, I never fancied broiling fowls;-though once broiled, judiciously buttered, and judgmatically salted and peppered, there is no one who will speak more respectfully, not to say reverentially, of a broiled fowl than I will.", - "input_from": 6221, - "input_to": 6580, - "tone_categories": [ - { - "tones": [ - { - "score": 0.366891, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.435328, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.256416, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.037071, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.473926, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.487, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.25, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.564, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.453, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.73, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 60, - "text": "It is out of the idolatrous dotings of the old Egyptians upon broiled ibis and roasted river horse, that you see the mummies of those creatures in their huge bake-houses the pyramids.", - "input_from": 6581, - "input_to": 6764, - "tone_categories": [ - { - "tones": [ - { - "score": 0.068849, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.670484, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.565229, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.072999, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.194397, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.713, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.521, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.694, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.546, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.136, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 61, - "text": "No, when I go to sea, I go as a simple sailor, right before the mast, plumb down into the forecastle, aloft there to the royal mast-head.", - "input_from": 6765, - "input_to": 6902, - "tone_categories": [ - { - "tones": [ - { - "score": 0.202455, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.368053, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.487951, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.116903, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.240054, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.63, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.761, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.23, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.425, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.493, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 62, - "text": "True, they rather order me about some, and make me jump from spar to spar, like a grasshopper in a May meadow.", - "input_from": 6903, - "input_to": 7013, - "tone_categories": [ - { - "tones": [ - { - "score": 0.114608, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.180568, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.127396, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.552524, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.21591, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.913, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.392, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.35, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.573, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.659, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.814, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 63, - "text": "And at first, this sort of thing is unpleasant enough.", - "input_from": 7014, - "input_to": 7068, - "tone_categories": [ - { - "tones": [ - { - "score": 0.172106, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.323635, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.405992, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.168903, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.287174, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.715, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.885, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.218, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.059, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.19, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.894, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 64, - "text": "It touches one's sense of honour, particularly if you come of an old established family in the land, the Van Rensselaers, or Randolphs, or Hardicanutes.", - "input_from": 7069, - "input_to": 7221, - "tone_categories": [ - { - "tones": [ - { - "score": 0.245789, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.355261, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.290643, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.112017, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.277867, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.866, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.571, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.495, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.291, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.557, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.608, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.671, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 65, - "text": "And more than all, if just previous to putting your hand into the tar-pot, you have been lording it as a country schoolmaster, making the tallest boys stand in awe of you.", - "input_from": 7222, - "input_to": 7393, - "tone_categories": [ - { - "tones": [ - { - "score": 0.107358, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.727051, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.242276, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.116783, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.176322, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.155, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.08, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.612, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.35, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.806, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.569, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.213, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 66, - "text": "The transition is a keen one, I assure you, from a schoolmaster to a sailor, and requires a strong decoction of Seneca and the Stoics to enable you to grin and bear it.", - "input_from": 7394, - "input_to": 7562, - "tone_categories": [ - { - "tones": [ - { - "score": 0.381463, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.493127, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.524356, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.061184, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.233586, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.155, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.298, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.583, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.916, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.746, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.729, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.109, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 67, - "text": "But even this wears off in time.", - "input_from": 7563, - "input_to": 7595, - "tone_categories": [ - { - "tones": [ - { - "score": 0.15969, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.501692, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.184826, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.114453, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.347395, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.841, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.603, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.01, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.297, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.847, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.97, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 68, - "text": "What of it, if some old hunks of a sea-captain orders me to get a broom and sweep down the decks?", - "input_from": 7596, - "input_to": 7693, - "tone_categories": [ - { - "tones": [ - { - "score": 0.349233, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.150259, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.448867, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.14003, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.233611, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.364, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.284, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.791, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.498, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.153, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.275, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.685, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 69, - "text": "What does that indignity amount to, weighed, I mean, in the scales of the New Testament?", - "input_from": 7694, - "input_to": 7782, - "tone_categories": [ - { - "tones": [ - { - "score": 0.114981, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.341251, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.232329, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.372385, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.282898, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.815, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.571, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.329, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.18, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.68, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 70, - "text": "Do you think the archangel Gabriel thinks anything the less of me, because I promptly and respectfully obey that old hunks in that particular instance?", - "input_from": 7783, - "input_to": 7934, - "tone_categories": [ - { - "tones": [ - { - "score": 0.117679, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.425065, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.606104, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.040868, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.459945, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.821, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.196, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.326, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.266, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.39, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.412, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.846, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 71, - "text": "Who ain't a slave?", - "input_from": 7935, - "input_to": 7953, - "tone_categories": [ - { - "tones": [ - { - "score": 0.243072, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.332116, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.450842, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.11269, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.202439, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.9, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.932, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.606, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.194, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.061, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 72, - "text": "Tell me that.", - "input_from": 7954, - "input_to": 7967, - "tone_categories": [] - }, - { - "sentence_id": 73, - "text": "Well, then, however the old sea-captains may order me about-however they may thump and punch me about, I have the satisfaction of knowing that it is all right; that everybody else is one way or other served in much the same way-either in a physical or metaphysical point of view, that is; and so the universal thump is passed round, and all hands should rub each other's shoulder-blades, and be content.", - "input_from": 7968, - "input_to": 8371, - "tone_categories": [ - { - "tones": [ - { - "score": 0.600225, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.188614, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.342122, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.051428, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.309914, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.296, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.005, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.566, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.261, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.455, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.372, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.792, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 74, - "text": "Again, I always go to sea as a sailor, because they make a point of paying me for my trouble, whereas they never pay passengers a single penny that I ever heard of.", - "input_from": 8372, - "input_to": 8536, - "tone_categories": [ - { - "tones": [ - { - "score": 0.399134, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.426051, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.191353, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.133474, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.336895, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.69, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.659, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.195, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.23, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.499, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.371, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.895, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 75, - "text": "On the contrary, passengers themselves must pay.", - "input_from": 8537, - "input_to": 8585, - "tone_categories": [ - { - "tones": [ - { - "score": 0.176823, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.441884, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.245443, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.135024, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.265692, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.984, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.723, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.242, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.433, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.501, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.655, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.155, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 76, - "text": "And there is all the difference in the world between paying and being paid.", - "input_from": 8586, - "input_to": 8661, - "tone_categories": [ - { - "tones": [ - { - "score": 0.20078, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.215978, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.097787, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.302586, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.483807, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.723, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.967, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.475, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.14, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.392, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.224, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 77, - "text": "The act of paying is perhaps the most uncomfortable infliction that the two orchard thieves entailed upon us.", - "input_from": 8662, - "input_to": 8771, - "tone_categories": [ - { - "tones": [ - { - "score": 0.272819, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.637609, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.45609, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.038838, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.143311, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.346, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.667, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.494, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.286, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.288, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.525, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 78, - "text": "But BEING PAID,-what will compare with it?", - "input_from": 8772, - "input_to": 8814, - "tone_categories": [ - { - "tones": [ - { - "score": 0.129291, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.168215, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.505291, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.172874, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.445413, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.978, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.525, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.027, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.07, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.214, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.957, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 79, - "text": "The urbane activity with which a man receives money is really marvellous, considering that we so earnestly believe money to be the root of all earthly ills, and that on no account can a monied man enter heaven.", - "input_from": 8815, - "input_to": 9025, - "tone_categories": [ - { - "tones": [ - { - "score": 0.258157, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.362913, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.209787, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.224406, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.206747, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.623, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.284, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.637, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.265, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.563, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 80, - "text": "Ah! how cheerfully we consign ourselves to perdition!", - "input_from": 9026, - "input_to": 9079, - "tone_categories": [ - { - "tones": [ - { - "score": 0.326175, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.279526, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.280562, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.081405, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.159875, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.031, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.18, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.959, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.979, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.862, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 81, - "text": "Finally, I always go to sea as a sailor, because of the wholesome exercise and pure air of the fore-castle deck.", - "input_from": 9080, - "input_to": 9192, - "tone_categories": [ - { - "tones": [ - { - "score": 0.10393, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.110797, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.194602, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.691458, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.203747, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.563, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.543, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.775, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.663, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.283, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.19, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.655, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 82, - "text": "For as in this world, head winds are far more prevalent than winds from astern (that is, if you never violate the Pythagorean maxim), so for the most part the Commodore on the quarter-deck gets his atmosphere at second hand from the sailors on the forecastle.", - "input_from": 9193, - "input_to": 9452, - "tone_categories": [ - { - "tones": [ - { - "score": 0.190926, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.563901, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.379399, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.039081, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.386472, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.066, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.167, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.835, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.569, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.551, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.391, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.166, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 83, - "text": "He thinks he breathes it first; but not so.", - "input_from": 9453, - "input_to": 9496, - "tone_categories": [ - { - "tones": [ - { - "score": 0.146976, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.264925, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.429378, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.140581, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.474616, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.779, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.032, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.035, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.763, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.927, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.925, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 84, - "text": "In much the same way do the commonalty lead their leaders in many other things, at the same time that the leaders little suspect it.", - "input_from": 9497, - "input_to": 9629, - "tone_categories": [ - { - "tones": [ - { - "score": 0.223986, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.530082, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.343833, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.063121, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.278164, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.257, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.571, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.899, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.752, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.411, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.255, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.23, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 85, - "text": "But wherefore it was that after having repeatedly smelt the sea as a merchant sailor, I should now take it into my head to go on a whaling voyage; this the invisible police officer of the Fates, who has the constant surveillance of me, and secretly dogs me, and influences me in some unaccountable way-he can better answer than any one else.", - "input_from": 9630, - "input_to": 9971, - "tone_categories": [ - { - "tones": [ - { - "score": 0.421184, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.707532, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.530845, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.014768, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.092379, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.688, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.008, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.506, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.429, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.239, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.422, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.808, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 86, - "text": "And, doubtless, my going on this whaling voyage, formed part of the grand programme of Providence that was drawn up a long time ago.", - "input_from": 9972, - "input_to": 10104, - "tone_categories": [ - { - "tones": [ - { - "score": 0.259643, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.433288, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.221091, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.234673, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.23225, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.199, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.509, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.569, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.443, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.581, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.565, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 87, - "text": "It came in as a sort of brief interlude and solo between more extensive performances.", - "input_from": 10105, - "input_to": 10190, - "tone_categories": [ - { - "tones": [ - { - "score": 0.220237, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.488841, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.346516, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.32806, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.174339, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.451, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.922, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.534, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.24, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.432, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.536, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 88, - "text": "I take it that this part of the bill must have run something like this:\n\"GRAND CONTESTED ELECTION FOR THE PRESIDENCY OF THE UNITED STATES.", - "input_from": 10191, - "input_to": 10329, - "tone_categories": [ - { - "tones": [ - { - "score": 0.118164, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.52867, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.454139, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.167206, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.198501, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.065, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.374, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.345, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.446, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.536, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.739, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 89, - "text": "\"WHALING VOYAGE BY ONE ISHMAEL.", - "input_from": 10330, - "input_to": 10361, - "tone_categories": [ - { - "tones": [ - { - "score": 0.242882, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.212707, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.251869, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.217312, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.219939, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.912, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.571, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.035, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.119, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.401, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 90, - "text": "\"BLOODY BATTLE IN AFFGHANISTAN.\"", - "input_from": 10362, - "input_to": 10394, - "tone_categories": [ - { - "tones": [ - { - "score": 0.467411, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.387246, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.297422, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.040942, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.214117, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.981, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.571, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.89, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.743, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.401, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 91, - "text": "Though I cannot tell why it was exactly that those stage managers, the Fates, put me down for this shabby part of a whaling voyage, when others were set down for magnificent parts in high tragedies, and short and easy parts in genteel comedies, and jolly parts in farces-though I cannot tell why this was exactly; yet, now that I recall all the circumstances, I think I can see a little into the springs and motives which being cunningly presented to me under various disguises, induced me to set about performing the part I did, besides cajoling me into the delusion that it was a choice resulting from my own unbiased freewill and discriminating judgment.", - "input_from": 10395, - "input_to": 11052, - "tone_categories": [ - { - "tones": [ - { - "score": 0.530573, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.305188, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.287743, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.049307, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.240543, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.255, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.167, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.438, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.321, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.433, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.506, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.827, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 92, - "text": "Chief among these motives was the overwhelming idea of the great whale himself.", - "input_from": 11053, - "input_to": 11132, - "tone_categories": [ - { - "tones": [ - { - "score": 0.07347, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.348998, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.403245, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.326948, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.136145, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.768, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.22, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.265, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.218, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.833, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 93, - "text": "Such a portentous and mysterious monster roused all my curiosity.", - "input_from": 11133, - "input_to": 11198, - "tone_categories": [ - { - "tones": [ - { - "score": 0.287072, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.045712, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.428996, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.280744, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.139453, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.879, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.669, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.556, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.409, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.235, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.78, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 94, - "text": "Then the wild and distant seas where he rolled his island bulk; the undeliverable, nameless perils of the whale; these, with all the attending marvels of a thousand Patagonian sights and sounds, helped to sway me to my wish.", - "input_from": 11199, - "input_to": 11423, - "tone_categories": [ - { - "tones": [ - { - "score": 0.201321, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.413132, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.328442, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.040351, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.432223, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.014, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.235, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.601, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.517, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.566, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.531, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.385, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 95, - "text": "With other men, perhaps, such things would not have been inducements; but as for me, I am tormented with an everlasting itch for things remote.", - "input_from": 11424, - "input_to": 11567, - "tone_categories": [ - { - "tones": [ - { - "score": 0.47654, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.418817, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.133762, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.08858, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.419193, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.257, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0.196, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.447, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.057, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.497, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.378, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.956, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 96, - "text": "I love to sail forbidden seas, and land on barbarous coasts.", - "input_from": 11568, - "input_to": 11628, - "tone_categories": [ - { - "tones": [ - { - "score": 0.099477, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.164791, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.149077, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.425919, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.384697, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.232, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.295, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.829, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.739, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.876, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 97, - "text": "Not ignoring what is good, I am quick to perceive a horror, and could still be social with it-would they let me-since it is but well to be on friendly terms with all the inmates of the place one lodges in.", - "input_from": 11629, - "input_to": 11834, - "tone_categories": [ - { - "tones": [ - { - "score": 0.267446, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.220281, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.345987, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.061857, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.226209, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.591, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.184, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.514, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.39, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.825, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - }, - { - "sentence_id": 98, - "text": "By reason of these things, then, the whaling voyage was welcome; the great flood-gates of the wonder-world swung open, and in the wild conceits that swayed me to my purpose, two and two there floated into my inmost soul, endless processions of the whale, and, mid most of them all, one grand hooded phantom, like a snow hill in the air.", - "input_from": 11835, - "input_to": 12171, - "tone_categories": [ - { - "tones": [ - { - "score": 0.096855, - "tone_id": "anger", - "tone_name": "Anger" - }, - { - "score": 0.111949, - "tone_id": "disgust", - "tone_name": "Disgust" - }, - { - "score": 0.630888, - "tone_id": "fear", - "tone_name": "Fear" - }, - { - "score": 0.172567, - "tone_id": "joy", - "tone_name": "Joy" - }, - { - "score": 0.180281, - "tone_id": "sadness", - "tone_name": "Sadness" - } - ], - "category_id": "emotion_tone", - "category_name": "Emotion Tone" - }, - { - "tones": [ - { - "score": 0.275, - "tone_id": "analytical", - "tone_name": "Analytical" - }, - { - "score": 0.031, - "tone_id": "confident", - "tone_name": "Confident" - }, - { - "score": 0, - "tone_id": "tentative", - "tone_name": "Tentative" - } - ], - "category_id": "language_tone", - "category_name": "Language Tone" - }, - { - "tones": [ - { - "score": 0.711, - "tone_id": "openness_big5", - "tone_name": "Openness" - }, - { - "score": 0.498, - "tone_id": "conscientiousness_big5", - "tone_name": "Conscientiousness" - }, - { - "score": 0.427, - "tone_id": "extraversion_big5", - "tone_name": "Extraversion" - }, - { - "score": 0.432, - "tone_id": "agreeableness_big5", - "tone_name": "Agreeableness" - }, - { - "score": 0.662, - "tone_id": "emotional_range_big5", - "tone_name": "Emotional Range" - } - ], - "category_id": "social_tone", - "category_name": "Social Tone" - } - ] - } - ] -} \ No newline at end of file diff --git a/resources/tone-v3-expect2.json b/resources/tone-v3-expect2.json deleted file mode 100644 index bbd93ad1d..000000000 --- a/resources/tone-v3-expect2.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "utterances_tone": [ - { - "utterance_id": 0, - "utterance_text": "I am very happy", - "tones": [ - { - "score": 0.875529, - "tone_id": "polite", - "tone_name": "polite" - }, - { - "score": 0.838693, - "tone_id": "satisfied", - "tone_name": "satisfied" - }, - { - "score": 0.844135, - "tone_id": "sympathetic", - "tone_name": "sympathetic" - }, - { - "score": 0.916255, - "tone_id": "excited", - "tone_name": "excited" - } - ] - } - ] -} diff --git a/test/integration/test_compare_comply_v1.py b/test/integration/test_compare_comply_v1.py deleted file mode 100644 index c0e6e5150..000000000 --- a/test/integration/test_compare_comply_v1.py +++ /dev/null @@ -1,160 +0,0 @@ -# coding: utf-8 -import pytest -import ibm_watson -import os -from os.path import abspath -from unittest import TestCase -from ibm_watson.compare_comply_v1 import TableReturn - - -@pytest.mark.skipif(os.getenv('COMPARE_COMPLY_APIKEY') is None, - reason='requires COMPARE_COMPLY_APIKEY') -class IntegrationTestCompareComplyV1(TestCase): - compare_comply = None - - @classmethod - def setup_class(cls): - 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' - }) - - def test_convert_to_html(self): - contract = abspath('resources/contract_A.pdf') - with open(contract, 'rb') as file: - result = self.compare_comply.convert_to_html(file).get_result() - assert result is not None - - 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() - assert result is not None - - def test_extract_tables(self): - table = abspath('resources/table_test.png') - with open(table, 'rb') as file: - result = self.compare_comply.extract_tables(file).get_result() - TableReturn._from_dict(result) - assert result is not None - - 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() - - assert result is not None - - @pytest.mark.skip(reason="Temporarily skip") - def test_feedback(self): - feedback_data = { - 'feedback_type': - 'element_classification', - 'document': { - 'hash': '', - 'title': 'doc title' - }, - '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.', - 'original_labels': { - 'types': [{ - 'label': { - 'nature': 'Obligation', - 'party': 'IBM' - }, - 'provenance_ids': [ - '85f5981a-ba91-44f5-9efa-0bd22e64b7bc', - 'ce0480a1-5ef1-4c3e-9861-3743b5610795' - ] - }, { - 'label': { - 'nature': 'End User', - 'party': 'Exclusion' - }, - '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' - } - }], - 'categories': [{ - 'label': 'Responsibilities' - }, { - 'label': 'Audits' - }] - } - } - - add_feedback = self.compare_comply.add_feedback( - 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() - 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() - assert delete_feedback is not None - - @pytest.mark.skip(reason="Temporarily skip") - def test_batches(self): - list_batches = self.compare_comply.list_batches().get_result() - assert list_batches is not None - - 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', - 'compare-comply-integration-test-bucket-input', - output_credentials_file, 'us-south', - 'compare-comply-integration-test-bucket-output').get_result() - - assert create_batch is not None - assert create_batch['batch_id'] is not None - batch_id = create_batch['batch_id'] - - get_batch = self.compare_comply.get_batch(batch_id) - assert get_batch is not None - - update_batch = self.compare_comply.update_batch(batch_id, 'rescan') - assert update_batch is not None diff --git a/test/integration/test_examples.py b/test/integration/test_examples.py index 008902a1e..aafcbf83a 100644 --- a/test/integration/test_examples.py +++ b/test/integration/test_examples.py @@ -9,10 +9,7 @@ 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'] # examples path. /examples examples_path = join(dirname(__file__), '../../', 'examples', '*.py') diff --git a/test/integration/test_natural_language_classifier_v1.py b/test/integration/test_natural_language_classifier_v1.py deleted file mode 100644 index 76729011a..000000000 --- a/test/integration/test_natural_language_classifier_v1.py +++ /dev/null @@ -1,67 +0,0 @@ -# coding: utf-8 -from unittest import TestCase -import os -import ibm_watson -import pytest -import json -import time - -FIVE_SECONDS = 5 - - -@pytest.mark.skipif(os.getenv('NATURAL_LANGUAGE_CLASSIFIER_APIKEY') is None, - reason='requires NATURAL_LANGUAGE_CLASSIFIER_APIKEY') -class TestNaturalLanguageClassifierV1(TestCase): - - def setUp(self): - 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: - metadata = json.dumps({'name': 'my-classifier', 'language': 'en'}) - classifier = self.natural_language_classifier.create_classifier( - training_data=training_data, - training_metadata=metadata, - ).get_result() - self.classifier_id = classifier['classifier_id'] - - 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() - 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() - iterations += 1 - if status['status'] != 'Available': - time.sleep(FIVE_SECONDS) - - 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() - assert classes is not None - - 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_personality_insights_v3.py b/test/integration/test_personality_insights_v3.py deleted file mode 100644 index fb04be696..000000000 --- a/test/integration/test_personality_insights_v3.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding: utf-8 -from unittest import TestCase -import os -import ibm_watson -import pytest -import json -import time -from os.path import join - -@pytest.mark.skipif(os.getenv('PERSONALITY_INSIGHTS_APIKEY') is None, - reason='requires PERSONALITY_INSIGHTS_APIKEY') -class TestPersonalityInsightsV3(TestCase): - - def setUp(self): - self.personality_insights = ibm_watson.PersonalityInsightsV3(version='2017-10-13') - self.personality_insights.set_default_headers({ - 'X-Watson-Learning-Opt-Out': '1', - 'X-Watson-Test': '1' - }) - - def test_profile1(self): - with open(join(os.getcwd(), 'resources/personality-v3.json')) as \ - profile_json: - profile = self.personality_insights.profile( - profile_json.read(), - 'application/json', - raw_scores=True, - consumption_preferences=True).get_result() - assert profile is not None diff --git a/test/integration/test_tone_analyzer_v3.py b/test/integration/test_tone_analyzer_v3.py deleted file mode 100644 index d4b03103b..000000000 --- a/test/integration/test_tone_analyzer_v3.py +++ /dev/null @@ -1,60 +0,0 @@ -# coding: utf-8 -from unittest import TestCase -import os -import ibm_watson -import pytest -import json -import time -from os.path import join -from ibm_watson.tone_analyzer_v3 import ToneInput - -@pytest.mark.skipif(os.getenv('TONE_ANALYZER_APIKEY') is None, - reason='requires PTONE_ANALYZER_APIKEY') -class TestToneAnalyzerV3(TestCase): - - def setUp(self): - self.tone_analyzer = ibm_watson.ToneAnalyzerV3(version='2017-09-21') - self.tone_analyzer.set_default_headers({ - 'X-Watson-Learning-Opt-Out': '1', - 'X-Watson-Test': '1' - }) - - def test_tone_chat(self): - utterances = [{ - 'text': 'I am very happy.', - 'user': 'glenn' - }, { - 'text': 'It is a good day.', - 'user': 'glenn' - }] - tone_chat = self.tone_analyzer.tone_chat(utterances).get_result() - assert tone_chat is not None - - def test_tone1(self): - tone = self.tone_analyzer.tone(tone_input='I am very happy. It is a good day.', content_type="text/plain").get_result() - assert tone is not None - - def test_tone2(self): - with open(join(os.getcwd(), 'resources/tone-example.json')) as tone_json: - tone = self.tone_analyzer.tone(json.load(tone_json)['text'], content_type="text/plain").get_result() - assert tone is not None - - def test_tone3(self): - with open(join(os.getcwd(), 'resources/tone-example.json')) as tone_json: - tone = self.tone_analyzer.tone(tone_input=json.load(tone_json)['text'], content_type='text/plain', sentences=True).get_result() - assert tone is not None - - def test_tone4(self): - with open(join(os.getcwd(), 'resources/tone-example.json')) as tone_json: - tone = self.tone_analyzer.tone(tone_input=json.load(tone_json), content_type='application/json').get_result() - assert tone is not None - - def test_tone5(self): - with open(join(os.getcwd(), 'resources/tone-example-html.json')) as tone_html: - tone = self.tone_analyzer.tone(json.load(tone_html)['text'],content_type='text/html').get_result() - assert tone is not None - - def test_tone6(self): - tone_input = ToneInput('I am very happy. It is a good day.') - tone = self.tone_analyzer.tone(tone_input=tone_input, content_type="application/json").get_result() - assert tone is not None \ No newline at end of file diff --git a/test/integration/test_visual_recognition_v3.py b/test/integration/test_visual_recognition_v3.py deleted file mode 100644 index a71054596..000000000 --- a/test/integration/test_visual_recognition_v3.py +++ /dev/null @@ -1,59 +0,0 @@ -# coding: utf-8 -import pytest -import ibm_watson -import os -from os.path import abspath -from unittest import TestCase - - -@pytest.mark.skipif(os.getenv('VISUAL_RECOGNITION_APIKEY') is None, - reason='requires VISUAL_RECOGNITION_APIKEY') -class IntegrationTestVisualRecognitionV3(TestCase): - visual_recognition = None - classifier_id = None - - @classmethod - 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' - }) - cls.classifier_id = 'sdk-classifier-do-not-delete_1118105040' - - def test_classify(self): - dog_path = abspath('resources/dog.jpg') - with open(dog_path, 'rb') as image_file: - dog_results = self.visual_recognition.classify( - images_file=image_file, - threshold='0.1', - classifier_ids=['default']).get_result() - assert dog_results is not None - - @pytest.mark.skip(reason="Time consuming") - def test_custom_classifier(self): - with open(abspath('resources/cars.zip'), 'rb') as cars, \ - open(abspath('resources/trucks.zip'), 'rb') as trucks: - classifier = self.visual_recognition.create_classifier( - 'CarsVsTrucks', - positive_examples={ - 'cars': cars - }, - negative_examples=trucks, - ).get_result() - - assert classifier is not None - - classifier_id = classifier['classifier_id'] - 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() - - @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() - assert core_ml_model.ok diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py deleted file mode 100644 index 97d9e8e53..000000000 --- a/test/integration/test_visual_recognition_v4.py +++ /dev/null @@ -1,164 +0,0 @@ -# coding: utf-8 -import pytest -import ibm_watson -import os -import json -from unittest import TestCase -from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata, TrainingDataObject, Location - - -@pytest.mark.skipif(os.getenv('VISUAL_RECOGNITION_APIKEY') is None, - reason='requires VISUAL_RECOGNITION_APIKEY') -class IntegrationTestVisualRecognitionV3(TestCase): - visual_recognition = None - - @classmethod - 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' - }) - - def test_01_colllections(self): - collection = self.visual_recognition.create_collection( - 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() - assert my_collection is not None - assert my_collection.get('name') == 'my_collection' - - updated_collection = self.visual_recognition.update_collection( - collection_id=collection_id, - description='new description').get_result() - assert updated_collection is not None - - 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() - 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" - ], - ).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() - assert list_images is not None - - 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() - 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') - 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: - analyze_images = self.visual_recognition.analyze( - collection_ids=['a06f7036-0529-49ee-bdf6-82ddec276923'], - features=[AnalyzeEnums.Features.OBJECTS.value], - images_file=[ - 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() - assert analyze_images is not None - print(json.dumps(analyze_images, indent=2)) - - 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() - 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: - add_images_result = self.visual_recognition.add_images( - collection_id, - images_file=[FileWithMetadata(giraffe_info)], - ).get_result() - assert add_images_result is not None - image_id = add_images_result.get('images')[0].get('image_id') - assert image_id is not None - - # add image training data - training_data = self.visual_recognition.add_image_training_data( - collection_id, - image_id, - objects=[ - TrainingDataObject(object='giraffe training data', - location=Location(64, 270, 755, 784)) - ]).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() - 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 c2314b635..696a08a7b 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2021. +# (C) Copyright IBM Corp. 2018, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -34,11 +34,38 @@ _service = AssistantV1( authenticator=NoAuthAuthenticator(), version=version - ) +) _base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' _service.set_service_url(_base_url) + +def preprocess_url(operation_path: str): + """ + Returns the request url associated with the specified operation path. + This will be base_url concatenated with a quoted version of operation_path. + The returned request URL is used to register the mock response so it needs + to match the request URL that is formed by the requests library. + """ + # First, unquote the path since it might have some quoted/escaped characters in it + # due to how the generator inserts the operation paths into the unit test code. + operation_path = urllib.parse.unquote(operation_path) + + # Next, quote the path using urllib so that we approximate what will + # happen during request processing. + operation_path = urllib.parse.quote(operation_path, safe='/') + + # Finally, form the request URL from the base URL and operation path. + request_url = _base_url + operation_path + + # If the request url does NOT end with a /, then just return it as-is. + # Otherwise, return a regular expression that matches one or more trailing /. + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + ############################################################################## # Start of Service: Message ############################################################################## @@ -49,25 +76,14 @@ class TestMessage(): Test Class for message """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_message_all_params(self): """ message() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + url = preprocess_url('/v1/workspaces/testString/message') + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -135,7 +151,6 @@ def test_message_all_params(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -200,7 +215,6 @@ def test_message_all_params(self): output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] - output_data_model['text'] = ['testString'] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' @@ -246,6 +260,14 @@ def test_message_all_params(self): assert req_body['output'] == output_data_model assert req_body['user_id'] == 'testString' + def test_message_all_params_with_retries(self): + # Enable retries and run test_message_all_params. + _service.enable_retries() + self.test_message_all_params() + + # Disable retries and run test_message_all_params. + _service.disable_retries() + self.test_message_all_params() @responses.activate def test_message_required_params(self): @@ -253,8 +275,8 @@ def test_message_required_params(self): test_message_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + url = preprocess_url('/v1/workspaces/testString/message') + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -274,6 +296,14 @@ def test_message_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_message_required_params_with_retries(self): + # Enable retries and run test_message_required_params. + _service.enable_retries() + self.test_message_required_params() + + # Disable retries and run test_message_required_params. + _service.disable_retries() + self.test_message_required_params() @responses.activate def test_message_value_error(self): @@ -281,8 +311,8 @@ def test_message_value_error(self): test_message_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + url = preprocess_url('/v1/workspaces/testString/message') + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -302,6 +332,14 @@ def test_message_value_error(self): _service.message(**req_copy) + def test_message_value_error_with_retries(self): + # Enable retries and run test_message_value_error. + _service.enable_retries() + self.test_message_value_error() + + # Disable retries and run test_message_value_error. + _service.disable_retries() + self.test_message_value_error() # endregion ############################################################################## @@ -318,25 +356,14 @@ class TestBulkClassify(): Test Class for bulk_classify """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_bulk_classify_all_params(self): """ bulk_classify() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + url = preprocess_url('/v1/workspaces/testString/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -365,6 +392,14 @@ def test_bulk_classify_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['input'] == [bulk_classify_utterance_model] + def test_bulk_classify_all_params_with_retries(self): + # Enable retries and run test_bulk_classify_all_params. + _service.enable_retries() + self.test_bulk_classify_all_params() + + # Disable retries and run test_bulk_classify_all_params. + _service.disable_retries() + self.test_bulk_classify_all_params() @responses.activate def test_bulk_classify_required_params(self): @@ -372,8 +407,8 @@ def test_bulk_classify_required_params(self): test_bulk_classify_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + url = preprocess_url('/v1/workspaces/testString/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -393,6 +428,14 @@ def test_bulk_classify_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_bulk_classify_required_params_with_retries(self): + # Enable retries and run test_bulk_classify_required_params. + _service.enable_retries() + self.test_bulk_classify_required_params() + + # Disable retries and run test_bulk_classify_required_params. + _service.disable_retries() + self.test_bulk_classify_required_params() @responses.activate def test_bulk_classify_value_error(self): @@ -400,8 +443,8 @@ def test_bulk_classify_value_error(self): test_bulk_classify_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + url = preprocess_url('/v1/workspaces/testString/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -421,6 +464,14 @@ def test_bulk_classify_value_error(self): _service.bulk_classify(**req_copy) + def test_bulk_classify_value_error_with_retries(self): + # Enable retries and run test_bulk_classify_value_error. + _service.enable_retries() + self.test_bulk_classify_value_error() + + # Disable retries and run test_bulk_classify_value_error. + _service.disable_retries() + self.test_bulk_classify_value_error() # endregion ############################################################################## @@ -437,25 +488,14 @@ class TestListWorkspaces(): Test Class for list_workspaces """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_workspaces_all_params(self): """ list_workspaces() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/workspaces') + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -491,6 +531,14 @@ def test_list_workspaces_all_params(self): assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_list_workspaces_all_params_with_retries(self): + # Enable retries and run test_list_workspaces_all_params. + _service.enable_retries() + self.test_list_workspaces_all_params() + + # Disable retries and run test_list_workspaces_all_params. + _service.disable_retries() + self.test_list_workspaces_all_params() @responses.activate def test_list_workspaces_required_params(self): @@ -498,8 +546,8 @@ def test_list_workspaces_required_params(self): test_list_workspaces_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/workspaces') + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -514,6 +562,14 @@ def test_list_workspaces_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_workspaces_required_params_with_retries(self): + # Enable retries and run test_list_workspaces_required_params. + _service.enable_retries() + self.test_list_workspaces_required_params() + + # Disable retries and run test_list_workspaces_required_params. + _service.disable_retries() + self.test_list_workspaces_required_params() @responses.activate def test_list_workspaces_value_error(self): @@ -521,8 +577,8 @@ def test_list_workspaces_value_error(self): test_list_workspaces_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/workspaces') + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -538,59 +594,47 @@ def test_list_workspaces_value_error(self): _service.list_workspaces(**req_copy) + def test_list_workspaces_value_error_with_retries(self): + # Enable retries and run test_list_workspaces_value_error. + _service.enable_retries() + self.test_list_workspaces_value_error() + + # Disable retries and run test_list_workspaces_value_error. + _service.disable_retries() + self.test_list_workspaces_value_error() class TestCreateWorkspace(): """ Test Class for create_workspace """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_workspace_all_params(self): """ create_workspace() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a ChannelTransferTargetChat model - channel_transfer_target_chat_model = {} - channel_transfer_target_chat_model['url'] = 'testString' - - # Construct a dict representation of a ChannelTransferTarget model - channel_transfer_target_model = {} - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - # Construct a dict representation of a ChannelTransferInfo model - channel_transfer_info_model = {} - channel_transfer_info_model['target'] = channel_transfer_target_model - # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -679,6 +723,7 @@ def test_create_workspace_all_params(self): workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['foo'] = 'testString' # Construct a dict representation of a WebhookHeader model webhook_header_model = {} @@ -775,6 +820,14 @@ def test_create_workspace_all_params(self): assert req_body['intents'] == [create_intent_model] assert req_body['entities'] == [create_entity_model] + def test_create_workspace_all_params_with_retries(self): + # Enable retries and run test_create_workspace_all_params. + _service.enable_retries() + self.test_create_workspace_all_params() + + # Disable retries and run test_create_workspace_all_params. + _service.disable_retries() + self.test_create_workspace_all_params() @responses.activate def test_create_workspace_required_params(self): @@ -782,8 +835,8 @@ def test_create_workspace_required_params(self): test_create_workspace_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -798,6 +851,14 @@ def test_create_workspace_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_workspace_required_params_with_retries(self): + # Enable retries and run test_create_workspace_required_params. + _service.enable_retries() + self.test_create_workspace_required_params() + + # Disable retries and run test_create_workspace_required_params. + _service.disable_retries() + self.test_create_workspace_required_params() @responses.activate def test_create_workspace_value_error(self): @@ -805,8 +866,8 @@ def test_create_workspace_value_error(self): test_create_workspace_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -822,31 +883,28 @@ def test_create_workspace_value_error(self): _service.create_workspace(**req_copy) + def test_create_workspace_value_error_with_retries(self): + # Enable retries and run test_create_workspace_value_error. + _service.enable_retries() + self.test_create_workspace_value_error() + + # Disable retries and run test_create_workspace_value_error. + _service.disable_retries() + self.test_create_workspace_value_error() class TestGetWorkspace(): """ Test Class for get_workspace """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_workspace_all_params(self): """ get_workspace() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -878,6 +936,14 @@ def test_get_workspace_all_params(self): assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string assert 'sort={}'.format(sort) in query_string + def test_get_workspace_all_params_with_retries(self): + # Enable retries and run test_get_workspace_all_params. + _service.enable_retries() + self.test_get_workspace_all_params() + + # Disable retries and run test_get_workspace_all_params. + _service.disable_retries() + self.test_get_workspace_all_params() @responses.activate def test_get_workspace_required_params(self): @@ -885,8 +951,8 @@ def test_get_workspace_required_params(self): test_get_workspace_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -906,6 +972,14 @@ def test_get_workspace_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_workspace_required_params_with_retries(self): + # Enable retries and run test_get_workspace_required_params. + _service.enable_retries() + self.test_get_workspace_required_params() + + # Disable retries and run test_get_workspace_required_params. + _service.disable_retries() + self.test_get_workspace_required_params() @responses.activate def test_get_workspace_value_error(self): @@ -913,8 +987,8 @@ def test_get_workspace_value_error(self): test_get_workspace_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.GET, url, body=mock_response, @@ -934,59 +1008,47 @@ def test_get_workspace_value_error(self): _service.get_workspace(**req_copy) + def test_get_workspace_value_error_with_retries(self): + # Enable retries and run test_get_workspace_value_error. + _service.enable_retries() + self.test_get_workspace_value_error() + + # Disable retries and run test_get_workspace_value_error. + _service.disable_retries() + self.test_get_workspace_value_error() class TestUpdateWorkspace(): """ Test Class for update_workspace """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_workspace_all_params(self): """ update_workspace() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) - # Construct a dict representation of a ChannelTransferTargetChat model - channel_transfer_target_chat_model = {} - channel_transfer_target_chat_model['url'] = 'testString' - - # Construct a dict representation of a ChannelTransferTarget model - channel_transfer_target_model = {} - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - # Construct a dict representation of a ChannelTransferInfo model - channel_transfer_info_model = {} - channel_transfer_info_model['target'] = channel_transfer_target_model - # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -1075,6 +1137,7 @@ def test_update_workspace_all_params(self): workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['foo'] = 'testString' # Construct a dict representation of a WebhookHeader model webhook_header_model = {} @@ -1176,6 +1239,14 @@ def test_update_workspace_all_params(self): assert req_body['intents'] == [create_intent_model] assert req_body['entities'] == [create_entity_model] + def test_update_workspace_all_params_with_retries(self): + # Enable retries and run test_update_workspace_all_params. + _service.enable_retries() + self.test_update_workspace_all_params() + + # Disable retries and run test_update_workspace_all_params. + _service.disable_retries() + self.test_update_workspace_all_params() @responses.activate def test_update_workspace_required_params(self): @@ -1183,8 +1254,8 @@ def test_update_workspace_required_params(self): test_update_workspace_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -1204,6 +1275,14 @@ def test_update_workspace_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_update_workspace_required_params_with_retries(self): + # Enable retries and run test_update_workspace_required_params. + _service.enable_retries() + self.test_update_workspace_required_params() + + # Disable retries and run test_update_workspace_required_params. + _service.disable_retries() + self.test_update_workspace_required_params() @responses.activate def test_update_workspace_value_error(self): @@ -1211,8 +1290,8 @@ def test_update_workspace_value_error(self): test_update_workspace_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -1232,30 +1311,27 @@ def test_update_workspace_value_error(self): _service.update_workspace(**req_copy) + def test_update_workspace_value_error_with_retries(self): + # Enable retries and run test_update_workspace_value_error. + _service.enable_retries() + self.test_update_workspace_value_error() + + # Disable retries and run test_update_workspace_value_error. + _service.disable_retries() + self.test_update_workspace_value_error() class TestDeleteWorkspace(): """ Test Class for delete_workspace """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_workspace_all_params(self): """ delete_workspace() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString') + url = preprocess_url('/v1/workspaces/testString') responses.add(responses.DELETE, url, status=200) @@ -1273,6 +1349,14 @@ def test_delete_workspace_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_workspace_all_params_with_retries(self): + # Enable retries and run test_delete_workspace_all_params. + _service.enable_retries() + self.test_delete_workspace_all_params() + + # Disable retries and run test_delete_workspace_all_params. + _service.disable_retries() + self.test_delete_workspace_all_params() @responses.activate def test_delete_workspace_value_error(self): @@ -1280,7 +1364,7 @@ def test_delete_workspace_value_error(self): test_delete_workspace_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString') + url = preprocess_url('/v1/workspaces/testString') responses.add(responses.DELETE, url, status=200) @@ -1298,6 +1382,14 @@ def test_delete_workspace_value_error(self): _service.delete_workspace(**req_copy) + def test_delete_workspace_value_error_with_retries(self): + # Enable retries and run test_delete_workspace_value_error. + _service.enable_retries() + self.test_delete_workspace_value_error() + + # Disable retries and run test_delete_workspace_value_error. + _service.disable_retries() + self.test_delete_workspace_value_error() # endregion ############################################################################## @@ -1314,24 +1406,13 @@ class TestListIntents(): Test Class for list_intents """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_intents_all_params(self): """ list_intents() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -1373,6 +1454,14 @@ def test_list_intents_all_params(self): assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_list_intents_all_params_with_retries(self): + # Enable retries and run test_list_intents_all_params. + _service.enable_retries() + self.test_list_intents_all_params() + + # Disable retries and run test_list_intents_all_params. + _service.disable_retries() + self.test_list_intents_all_params() @responses.activate def test_list_intents_required_params(self): @@ -1380,7 +1469,7 @@ def test_list_intents_required_params(self): test_list_intents_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -1401,6 +1490,14 @@ def test_list_intents_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_intents_required_params_with_retries(self): + # Enable retries and run test_list_intents_required_params. + _service.enable_retries() + self.test_list_intents_required_params() + + # Disable retries and run test_list_intents_required_params. + _service.disable_retries() + self.test_list_intents_required_params() @responses.activate def test_list_intents_value_error(self): @@ -1408,7 +1505,7 @@ def test_list_intents_value_error(self): test_list_intents_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -1429,30 +1526,27 @@ def test_list_intents_value_error(self): _service.list_intents(**req_copy) + def test_list_intents_value_error_with_retries(self): + # Enable retries and run test_list_intents_value_error. + _service.enable_retries() + self.test_list_intents_value_error() + + # Disable retries and run test_list_intents_value_error. + _service.disable_retries() + self.test_list_intents_value_error() class TestCreateIntent(): """ Test Class for create_intent """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_intent_all_params(self): """ create_intent() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -1500,6 +1594,14 @@ def test_create_intent_all_params(self): assert req_body['description'] == 'testString' assert req_body['examples'] == [example_model] + def test_create_intent_all_params_with_retries(self): + # Enable retries and run test_create_intent_all_params. + _service.enable_retries() + self.test_create_intent_all_params() + + # Disable retries and run test_create_intent_all_params. + _service.disable_retries() + self.test_create_intent_all_params() @responses.activate def test_create_intent_required_params(self): @@ -1507,7 +1609,7 @@ def test_create_intent_required_params(self): test_create_intent_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -1549,6 +1651,14 @@ def test_create_intent_required_params(self): assert req_body['description'] == 'testString' assert req_body['examples'] == [example_model] + def test_create_intent_required_params_with_retries(self): + # Enable retries and run test_create_intent_required_params. + _service.enable_retries() + self.test_create_intent_required_params() + + # Disable retries and run test_create_intent_required_params. + _service.disable_retries() + self.test_create_intent_required_params() @responses.activate def test_create_intent_value_error(self): @@ -1556,7 +1666,7 @@ def test_create_intent_value_error(self): test_create_intent_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents') + url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -1591,30 +1701,27 @@ def test_create_intent_value_error(self): _service.create_intent(**req_copy) + def test_create_intent_value_error_with_retries(self): + # Enable retries and run test_create_intent_value_error. + _service.enable_retries() + self.test_create_intent_value_error() + + # Disable retries and run test_create_intent_value_error. + _service.disable_retries() + self.test_create_intent_value_error() class TestGetIntent(): """ Test Class for get_intent """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_intent_all_params(self): """ get_intent() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -1646,6 +1753,14 @@ def test_get_intent_all_params(self): assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_get_intent_all_params_with_retries(self): + # Enable retries and run test_get_intent_all_params. + _service.enable_retries() + self.test_get_intent_all_params() + + # Disable retries and run test_get_intent_all_params. + _service.disable_retries() + self.test_get_intent_all_params() @responses.activate def test_get_intent_required_params(self): @@ -1653,7 +1768,7 @@ def test_get_intent_required_params(self): test_get_intent_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -1676,6 +1791,14 @@ def test_get_intent_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_intent_required_params_with_retries(self): + # Enable retries and run test_get_intent_required_params. + _service.enable_retries() + self.test_get_intent_required_params() + + # Disable retries and run test_get_intent_required_params. + _service.disable_retries() + self.test_get_intent_required_params() @responses.activate def test_get_intent_value_error(self): @@ -1683,7 +1806,7 @@ def test_get_intent_value_error(self): test_get_intent_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -1706,30 +1829,27 @@ def test_get_intent_value_error(self): _service.get_intent(**req_copy) + def test_get_intent_value_error_with_retries(self): + # Enable retries and run test_get_intent_value_error. + _service.enable_retries() + self.test_get_intent_value_error() + + # Disable retries and run test_get_intent_value_error. + _service.disable_retries() + self.test_get_intent_value_error() class TestUpdateIntent(): """ Test Class for update_intent """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_intent_all_params(self): """ update_intent() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -1782,6 +1902,14 @@ def test_update_intent_all_params(self): assert req_body['description'] == 'testString' assert req_body['examples'] == [example_model] + def test_update_intent_all_params_with_retries(self): + # Enable retries and run test_update_intent_all_params. + _service.enable_retries() + self.test_update_intent_all_params() + + # Disable retries and run test_update_intent_all_params. + _service.disable_retries() + self.test_update_intent_all_params() @responses.activate def test_update_intent_required_params(self): @@ -1789,7 +1917,7 @@ def test_update_intent_required_params(self): test_update_intent_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -1833,6 +1961,14 @@ def test_update_intent_required_params(self): assert req_body['description'] == 'testString' assert req_body['examples'] == [example_model] + def test_update_intent_required_params_with_retries(self): + # Enable retries and run test_update_intent_required_params. + _service.enable_retries() + self.test_update_intent_required_params() + + # Disable retries and run test_update_intent_required_params. + _service.disable_retries() + self.test_update_intent_required_params() @responses.activate def test_update_intent_value_error(self): @@ -1840,7 +1976,7 @@ def test_update_intent_value_error(self): test_update_intent_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -1876,30 +2012,27 @@ def test_update_intent_value_error(self): _service.update_intent(**req_copy) + def test_update_intent_value_error_with_retries(self): + # Enable retries and run test_update_intent_value_error. + _service.enable_retries() + self.test_update_intent_value_error() + + # Disable retries and run test_update_intent_value_error. + _service.disable_retries() + self.test_update_intent_value_error() class TestDeleteIntent(): """ Test Class for delete_intent """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_intent_all_params(self): """ delete_intent() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString') responses.add(responses.DELETE, url, status=200) @@ -1919,6 +2052,14 @@ def test_delete_intent_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_intent_all_params_with_retries(self): + # Enable retries and run test_delete_intent_all_params. + _service.enable_retries() + self.test_delete_intent_all_params() + + # Disable retries and run test_delete_intent_all_params. + _service.disable_retries() + self.test_delete_intent_all_params() @responses.activate def test_delete_intent_value_error(self): @@ -1926,7 +2067,7 @@ def test_delete_intent_value_error(self): test_delete_intent_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString') responses.add(responses.DELETE, url, status=200) @@ -1946,6 +2087,14 @@ def test_delete_intent_value_error(self): _service.delete_intent(**req_copy) + def test_delete_intent_value_error_with_retries(self): + # Enable retries and run test_delete_intent_value_error. + _service.enable_retries() + self.test_delete_intent_value_error() + + # Disable retries and run test_delete_intent_value_error. + _service.disable_retries() + self.test_delete_intent_value_error() # endregion ############################################################################## @@ -1962,24 +2111,13 @@ class TestListExamples(): Test Class for list_examples """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_examples_all_params(self): """ list_examples() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -2020,6 +2158,14 @@ def test_list_examples_all_params(self): assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_list_examples_all_params_with_retries(self): + # Enable retries and run test_list_examples_all_params. + _service.enable_retries() + self.test_list_examples_all_params() + + # Disable retries and run test_list_examples_all_params. + _service.disable_retries() + self.test_list_examples_all_params() @responses.activate def test_list_examples_required_params(self): @@ -2027,7 +2173,7 @@ def test_list_examples_required_params(self): test_list_examples_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -2050,6 +2196,14 @@ def test_list_examples_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_examples_required_params_with_retries(self): + # Enable retries and run test_list_examples_required_params. + _service.enable_retries() + self.test_list_examples_required_params() + + # Disable retries and run test_list_examples_required_params. + _service.disable_retries() + self.test_list_examples_required_params() @responses.activate def test_list_examples_value_error(self): @@ -2057,7 +2211,7 @@ def test_list_examples_value_error(self): test_list_examples_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -2080,30 +2234,27 @@ def test_list_examples_value_error(self): _service.list_examples(**req_copy) + def test_list_examples_value_error_with_retries(self): + # Enable retries and run test_list_examples_value_error. + _service.enable_retries() + self.test_list_examples_value_error() + + # Disable retries and run test_list_examples_value_error. + _service.disable_retries() + self.test_list_examples_value_error() class TestCreateExample(): """ Test Class for create_example """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_example_all_params(self): """ create_example() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -2145,6 +2296,14 @@ def test_create_example_all_params(self): assert req_body['text'] == 'testString' assert req_body['mentions'] == [mention_model] + def test_create_example_all_params_with_retries(self): + # Enable retries and run test_create_example_all_params. + _service.enable_retries() + self.test_create_example_all_params() + + # Disable retries and run test_create_example_all_params. + _service.disable_retries() + self.test_create_example_all_params() @responses.activate def test_create_example_required_params(self): @@ -2152,7 +2311,7 @@ def test_create_example_required_params(self): test_create_example_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -2188,6 +2347,14 @@ def test_create_example_required_params(self): assert req_body['text'] == 'testString' assert req_body['mentions'] == [mention_model] + def test_create_example_required_params_with_retries(self): + # Enable retries and run test_create_example_required_params. + _service.enable_retries() + self.test_create_example_required_params() + + # Disable retries and run test_create_example_required_params. + _service.disable_retries() + self.test_create_example_required_params() @responses.activate def test_create_example_value_error(self): @@ -2195,7 +2362,7 @@ def test_create_example_value_error(self): test_create_example_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -2226,30 +2393,27 @@ def test_create_example_value_error(self): _service.create_example(**req_copy) + def test_create_example_value_error_with_retries(self): + # Enable retries and run test_create_example_value_error. + _service.enable_retries() + self.test_create_example_value_error() + + # Disable retries and run test_create_example_value_error. + _service.disable_retries() + self.test_create_example_value_error() class TestGetExample(): """ Test Class for get_example """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_example_all_params(self): """ get_example() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -2280,6 +2444,14 @@ def test_get_example_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_get_example_all_params_with_retries(self): + # Enable retries and run test_get_example_all_params. + _service.enable_retries() + self.test_get_example_all_params() + + # Disable retries and run test_get_example_all_params. + _service.disable_retries() + self.test_get_example_all_params() @responses.activate def test_get_example_required_params(self): @@ -2287,7 +2459,7 @@ def test_get_example_required_params(self): test_get_example_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -2312,6 +2484,14 @@ def test_get_example_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_example_required_params_with_retries(self): + # Enable retries and run test_get_example_required_params. + _service.enable_retries() + self.test_get_example_required_params() + + # Disable retries and run test_get_example_required_params. + _service.disable_retries() + self.test_get_example_required_params() @responses.activate def test_get_example_value_error(self): @@ -2319,7 +2499,7 @@ def test_get_example_value_error(self): test_get_example_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -2344,30 +2524,27 @@ def test_get_example_value_error(self): _service.get_example(**req_copy) + def test_get_example_value_error_with_retries(self): + # Enable retries and run test_get_example_value_error. + _service.enable_retries() + self.test_get_example_value_error() + + # Disable retries and run test_get_example_value_error. + _service.disable_retries() + self.test_get_example_value_error() class TestUpdateExample(): """ Test Class for update_example """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_example_all_params(self): """ update_example() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -2411,6 +2588,14 @@ def test_update_example_all_params(self): assert req_body['text'] == 'testString' assert req_body['mentions'] == [mention_model] + def test_update_example_all_params_with_retries(self): + # Enable retries and run test_update_example_all_params. + _service.enable_retries() + self.test_update_example_all_params() + + # Disable retries and run test_update_example_all_params. + _service.disable_retries() + self.test_update_example_all_params() @responses.activate def test_update_example_required_params(self): @@ -2418,7 +2603,7 @@ def test_update_example_required_params(self): test_update_example_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -2456,6 +2641,14 @@ def test_update_example_required_params(self): assert req_body['text'] == 'testString' assert req_body['mentions'] == [mention_model] + def test_update_example_required_params_with_retries(self): + # Enable retries and run test_update_example_required_params. + _service.enable_retries() + self.test_update_example_required_params() + + # Disable retries and run test_update_example_required_params. + _service.disable_retries() + self.test_update_example_required_params() @responses.activate def test_update_example_value_error(self): @@ -2463,7 +2656,7 @@ def test_update_example_value_error(self): test_update_example_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -2495,30 +2688,27 @@ def test_update_example_value_error(self): _service.update_example(**req_copy) + def test_update_example_value_error_with_retries(self): + # Enable retries and run test_update_example_value_error. + _service.enable_retries() + self.test_update_example_value_error() + + # Disable retries and run test_update_example_value_error. + _service.disable_retries() + self.test_update_example_value_error() class TestDeleteExample(): """ Test Class for delete_example """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_example_all_params(self): """ delete_example() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') responses.add(responses.DELETE, url, status=200) @@ -2540,6 +2730,14 @@ def test_delete_example_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_example_all_params_with_retries(self): + # Enable retries and run test_delete_example_all_params. + _service.enable_retries() + self.test_delete_example_all_params() + + # Disable retries and run test_delete_example_all_params. + _service.disable_retries() + self.test_delete_example_all_params() @responses.activate def test_delete_example_value_error(self): @@ -2547,7 +2745,7 @@ def test_delete_example_value_error(self): test_delete_example_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/intents/testString/examples/testString') + url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') responses.add(responses.DELETE, url, status=200) @@ -2569,6 +2767,14 @@ def test_delete_example_value_error(self): _service.delete_example(**req_copy) + def test_delete_example_value_error_with_retries(self): + # Enable retries and run test_delete_example_value_error. + _service.enable_retries() + self.test_delete_example_value_error() + + # Disable retries and run test_delete_example_value_error. + _service.disable_retries() + self.test_delete_example_value_error() # endregion ############################################################################## @@ -2585,24 +2791,13 @@ class TestListCounterexamples(): Test Class for list_counterexamples """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_counterexamples_all_params(self): """ list_counterexamples() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -2641,6 +2836,14 @@ def test_list_counterexamples_all_params(self): assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_list_counterexamples_all_params_with_retries(self): + # Enable retries and run test_list_counterexamples_all_params. + _service.enable_retries() + self.test_list_counterexamples_all_params() + + # Disable retries and run test_list_counterexamples_all_params. + _service.disable_retries() + self.test_list_counterexamples_all_params() @responses.activate def test_list_counterexamples_required_params(self): @@ -2648,7 +2851,7 @@ def test_list_counterexamples_required_params(self): test_list_counterexamples_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -2669,6 +2872,14 @@ def test_list_counterexamples_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_counterexamples_required_params_with_retries(self): + # Enable retries and run test_list_counterexamples_required_params. + _service.enable_retries() + self.test_list_counterexamples_required_params() + + # Disable retries and run test_list_counterexamples_required_params. + _service.disable_retries() + self.test_list_counterexamples_required_params() @responses.activate def test_list_counterexamples_value_error(self): @@ -2676,7 +2887,7 @@ def test_list_counterexamples_value_error(self): test_list_counterexamples_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -2697,30 +2908,27 @@ def test_list_counterexamples_value_error(self): _service.list_counterexamples(**req_copy) + def test_list_counterexamples_value_error_with_retries(self): + # Enable retries and run test_list_counterexamples_value_error. + _service.enable_retries() + self.test_list_counterexamples_value_error() + + # Disable retries and run test_list_counterexamples_value_error. + _service.disable_retries() + self.test_list_counterexamples_value_error() class TestCreateCounterexample(): """ Test Class for create_counterexample """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_counterexample_all_params(self): """ create_counterexample() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -2752,6 +2960,14 @@ def test_create_counterexample_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['text'] == 'testString' + def test_create_counterexample_all_params_with_retries(self): + # Enable retries and run test_create_counterexample_all_params. + _service.enable_retries() + self.test_create_counterexample_all_params() + + # Disable retries and run test_create_counterexample_all_params. + _service.disable_retries() + self.test_create_counterexample_all_params() @responses.activate def test_create_counterexample_required_params(self): @@ -2759,7 +2975,7 @@ def test_create_counterexample_required_params(self): test_create_counterexample_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -2785,6 +3001,14 @@ def test_create_counterexample_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['text'] == 'testString' + def test_create_counterexample_required_params_with_retries(self): + # Enable retries and run test_create_counterexample_required_params. + _service.enable_retries() + self.test_create_counterexample_required_params() + + # Disable retries and run test_create_counterexample_required_params. + _service.disable_retries() + self.test_create_counterexample_required_params() @responses.activate def test_create_counterexample_value_error(self): @@ -2792,7 +3016,7 @@ def test_create_counterexample_value_error(self): test_create_counterexample_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples') + url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -2815,30 +3039,27 @@ def test_create_counterexample_value_error(self): _service.create_counterexample(**req_copy) + def test_create_counterexample_value_error_with_retries(self): + # Enable retries and run test_create_counterexample_value_error. + _service.enable_retries() + self.test_create_counterexample_value_error() + + # Disable retries and run test_create_counterexample_value_error. + _service.disable_retries() + self.test_create_counterexample_value_error() class TestGetCounterexample(): """ Test Class for get_counterexample """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_counterexample_all_params(self): """ get_counterexample() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -2867,6 +3088,14 @@ def test_get_counterexample_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_get_counterexample_all_params_with_retries(self): + # Enable retries and run test_get_counterexample_all_params. + _service.enable_retries() + self.test_get_counterexample_all_params() + + # Disable retries and run test_get_counterexample_all_params. + _service.disable_retries() + self.test_get_counterexample_all_params() @responses.activate def test_get_counterexample_required_params(self): @@ -2874,7 +3103,7 @@ def test_get_counterexample_required_params(self): test_get_counterexample_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -2897,6 +3126,14 @@ def test_get_counterexample_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_counterexample_required_params_with_retries(self): + # Enable retries and run test_get_counterexample_required_params. + _service.enable_retries() + self.test_get_counterexample_required_params() + + # Disable retries and run test_get_counterexample_required_params. + _service.disable_retries() + self.test_get_counterexample_required_params() @responses.activate def test_get_counterexample_value_error(self): @@ -2904,7 +3141,7 @@ def test_get_counterexample_value_error(self): test_get_counterexample_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -2927,30 +3164,27 @@ def test_get_counterexample_value_error(self): _service.get_counterexample(**req_copy) + def test_get_counterexample_value_error_with_retries(self): + # Enable retries and run test_get_counterexample_value_error. + _service.enable_retries() + self.test_get_counterexample_value_error() + + # Disable retries and run test_get_counterexample_value_error. + _service.disable_retries() + self.test_get_counterexample_value_error() class TestUpdateCounterexample(): """ Test Class for update_counterexample """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_counterexample_all_params(self): """ update_counterexample() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -2984,6 +3218,14 @@ def test_update_counterexample_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['text'] == 'testString' + def test_update_counterexample_all_params_with_retries(self): + # Enable retries and run test_update_counterexample_all_params. + _service.enable_retries() + self.test_update_counterexample_all_params() + + # Disable retries and run test_update_counterexample_all_params. + _service.disable_retries() + self.test_update_counterexample_all_params() @responses.activate def test_update_counterexample_required_params(self): @@ -2991,7 +3233,7 @@ def test_update_counterexample_required_params(self): test_update_counterexample_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -3019,6 +3261,14 @@ def test_update_counterexample_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['text'] == 'testString' + def test_update_counterexample_required_params_with_retries(self): + # Enable retries and run test_update_counterexample_required_params. + _service.enable_retries() + self.test_update_counterexample_required_params() + + # Disable retries and run test_update_counterexample_required_params. + _service.disable_retries() + self.test_update_counterexample_required_params() @responses.activate def test_update_counterexample_value_error(self): @@ -3026,7 +3276,7 @@ def test_update_counterexample_value_error(self): test_update_counterexample_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -3050,30 +3300,27 @@ def test_update_counterexample_value_error(self): _service.update_counterexample(**req_copy) + def test_update_counterexample_value_error_with_retries(self): + # Enable retries and run test_update_counterexample_value_error. + _service.enable_retries() + self.test_update_counterexample_value_error() + + # Disable retries and run test_update_counterexample_value_error. + _service.disable_retries() + self.test_update_counterexample_value_error() class TestDeleteCounterexample(): """ Test Class for delete_counterexample """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_counterexample_all_params(self): """ delete_counterexample() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') responses.add(responses.DELETE, url, status=200) @@ -3093,6 +3340,14 @@ def test_delete_counterexample_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_counterexample_all_params_with_retries(self): + # Enable retries and run test_delete_counterexample_all_params. + _service.enable_retries() + self.test_delete_counterexample_all_params() + + # Disable retries and run test_delete_counterexample_all_params. + _service.disable_retries() + self.test_delete_counterexample_all_params() @responses.activate def test_delete_counterexample_value_error(self): @@ -3100,7 +3355,7 @@ def test_delete_counterexample_value_error(self): test_delete_counterexample_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/counterexamples/testString') + url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') responses.add(responses.DELETE, url, status=200) @@ -3120,6 +3375,14 @@ def test_delete_counterexample_value_error(self): _service.delete_counterexample(**req_copy) + def test_delete_counterexample_value_error_with_retries(self): + # Enable retries and run test_delete_counterexample_value_error. + _service.enable_retries() + self.test_delete_counterexample_value_error() + + # Disable retries and run test_delete_counterexample_value_error. + _service.disable_retries() + self.test_delete_counterexample_value_error() # endregion ############################################################################## @@ -3136,24 +3399,13 @@ class TestListEntities(): Test Class for list_entities """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_entities_all_params(self): """ list_entities() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -3195,6 +3447,14 @@ def test_list_entities_all_params(self): assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_list_entities_all_params_with_retries(self): + # Enable retries and run test_list_entities_all_params. + _service.enable_retries() + self.test_list_entities_all_params() + + # Disable retries and run test_list_entities_all_params. + _service.disable_retries() + self.test_list_entities_all_params() @responses.activate def test_list_entities_required_params(self): @@ -3202,7 +3462,7 @@ def test_list_entities_required_params(self): test_list_entities_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -3223,6 +3483,14 @@ def test_list_entities_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_entities_required_params_with_retries(self): + # Enable retries and run test_list_entities_required_params. + _service.enable_retries() + self.test_list_entities_required_params() + + # Disable retries and run test_list_entities_required_params. + _service.disable_retries() + self.test_list_entities_required_params() @responses.activate def test_list_entities_value_error(self): @@ -3230,7 +3498,7 @@ def test_list_entities_value_error(self): test_list_entities_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -3251,30 +3519,27 @@ def test_list_entities_value_error(self): _service.list_entities(**req_copy) + def test_list_entities_value_error_with_retries(self): + # Enable retries and run test_list_entities_value_error. + _service.enable_retries() + self.test_list_entities_value_error() + + # Disable retries and run test_list_entities_value_error. + _service.disable_retries() + self.test_list_entities_value_error() class TestCreateEntity(): """ Test Class for create_entity """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_entity_all_params(self): """ create_entity() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -3326,6 +3591,14 @@ def test_create_entity_all_params(self): assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] + def test_create_entity_all_params_with_retries(self): + # Enable retries and run test_create_entity_all_params. + _service.enable_retries() + self.test_create_entity_all_params() + + # Disable retries and run test_create_entity_all_params. + _service.disable_retries() + self.test_create_entity_all_params() @responses.activate def test_create_entity_required_params(self): @@ -3333,7 +3606,7 @@ def test_create_entity_required_params(self): test_create_entity_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -3379,6 +3652,14 @@ def test_create_entity_required_params(self): assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] + def test_create_entity_required_params_with_retries(self): + # Enable retries and run test_create_entity_required_params. + _service.enable_retries() + self.test_create_entity_required_params() + + # Disable retries and run test_create_entity_required_params. + _service.disable_retries() + self.test_create_entity_required_params() @responses.activate def test_create_entity_value_error(self): @@ -3386,7 +3667,7 @@ def test_create_entity_value_error(self): test_create_entity_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities') + url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -3421,30 +3702,27 @@ def test_create_entity_value_error(self): _service.create_entity(**req_copy) + def test_create_entity_value_error_with_retries(self): + # Enable retries and run test_create_entity_value_error. + _service.enable_retries() + self.test_create_entity_value_error() + + # Disable retries and run test_create_entity_value_error. + _service.disable_retries() + self.test_create_entity_value_error() class TestGetEntity(): """ Test Class for get_entity """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_entity_all_params(self): """ get_entity() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -3476,6 +3754,14 @@ def test_get_entity_all_params(self): assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_get_entity_all_params_with_retries(self): + # Enable retries and run test_get_entity_all_params. + _service.enable_retries() + self.test_get_entity_all_params() + + # Disable retries and run test_get_entity_all_params. + _service.disable_retries() + self.test_get_entity_all_params() @responses.activate def test_get_entity_required_params(self): @@ -3483,7 +3769,7 @@ def test_get_entity_required_params(self): test_get_entity_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -3506,6 +3792,14 @@ def test_get_entity_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_entity_required_params_with_retries(self): + # Enable retries and run test_get_entity_required_params. + _service.enable_retries() + self.test_get_entity_required_params() + + # Disable retries and run test_get_entity_required_params. + _service.disable_retries() + self.test_get_entity_required_params() @responses.activate def test_get_entity_value_error(self): @@ -3513,7 +3807,7 @@ def test_get_entity_value_error(self): test_get_entity_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -3536,30 +3830,27 @@ def test_get_entity_value_error(self): _service.get_entity(**req_copy) + def test_get_entity_value_error_with_retries(self): + # Enable retries and run test_get_entity_value_error. + _service.enable_retries() + self.test_get_entity_value_error() + + # Disable retries and run test_get_entity_value_error. + _service.disable_retries() + self.test_get_entity_value_error() class TestUpdateEntity(): """ Test Class for update_entity """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_entity_all_params(self): """ update_entity() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -3616,6 +3907,14 @@ def test_update_entity_all_params(self): assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] + def test_update_entity_all_params_with_retries(self): + # Enable retries and run test_update_entity_all_params. + _service.enable_retries() + self.test_update_entity_all_params() + + # Disable retries and run test_update_entity_all_params. + _service.disable_retries() + self.test_update_entity_all_params() @responses.activate def test_update_entity_required_params(self): @@ -3623,7 +3922,7 @@ def test_update_entity_required_params(self): test_update_entity_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -3671,6 +3970,14 @@ def test_update_entity_required_params(self): assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] + def test_update_entity_required_params_with_retries(self): + # Enable retries and run test_update_entity_required_params. + _service.enable_retries() + self.test_update_entity_required_params() + + # Disable retries and run test_update_entity_required_params. + _service.disable_retries() + self.test_update_entity_required_params() @responses.activate def test_update_entity_value_error(self): @@ -3678,7 +3985,7 @@ def test_update_entity_value_error(self): test_update_entity_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -3714,30 +4021,27 @@ def test_update_entity_value_error(self): _service.update_entity(**req_copy) + def test_update_entity_value_error_with_retries(self): + # Enable retries and run test_update_entity_value_error. + _service.enable_retries() + self.test_update_entity_value_error() + + # Disable retries and run test_update_entity_value_error. + _service.disable_retries() + self.test_update_entity_value_error() class TestDeleteEntity(): """ Test Class for delete_entity """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_entity_all_params(self): """ delete_entity() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString') responses.add(responses.DELETE, url, status=200) @@ -3757,6 +4061,14 @@ def test_delete_entity_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_entity_all_params_with_retries(self): + # Enable retries and run test_delete_entity_all_params. + _service.enable_retries() + self.test_delete_entity_all_params() + + # Disable retries and run test_delete_entity_all_params. + _service.disable_retries() + self.test_delete_entity_all_params() @responses.activate def test_delete_entity_value_error(self): @@ -3764,7 +4076,7 @@ def test_delete_entity_value_error(self): test_delete_entity_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString') responses.add(responses.DELETE, url, status=200) @@ -3784,6 +4096,14 @@ def test_delete_entity_value_error(self): _service.delete_entity(**req_copy) + def test_delete_entity_value_error_with_retries(self): + # Enable retries and run test_delete_entity_value_error. + _service.enable_retries() + self.test_delete_entity_value_error() + + # Disable retries and run test_delete_entity_value_error. + _service.disable_retries() + self.test_delete_entity_value_error() # endregion ############################################################################## @@ -3800,24 +4120,13 @@ class TestListMentions(): Test Class for list_mentions """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_mentions_all_params(self): """ list_mentions() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/mentions') + url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -3849,6 +4158,14 @@ def test_list_mentions_all_params(self): assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_list_mentions_all_params_with_retries(self): + # Enable retries and run test_list_mentions_all_params. + _service.enable_retries() + self.test_list_mentions_all_params() + + # Disable retries and run test_list_mentions_all_params. + _service.disable_retries() + self.test_list_mentions_all_params() @responses.activate def test_list_mentions_required_params(self): @@ -3856,7 +4173,7 @@ def test_list_mentions_required_params(self): test_list_mentions_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/mentions') + url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -3879,6 +4196,14 @@ def test_list_mentions_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_mentions_required_params_with_retries(self): + # Enable retries and run test_list_mentions_required_params. + _service.enable_retries() + self.test_list_mentions_required_params() + + # Disable retries and run test_list_mentions_required_params. + _service.disable_retries() + self.test_list_mentions_required_params() @responses.activate def test_list_mentions_value_error(self): @@ -3886,7 +4211,7 @@ def test_list_mentions_value_error(self): test_list_mentions_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/mentions') + url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -3909,6 +4234,14 @@ def test_list_mentions_value_error(self): _service.list_mentions(**req_copy) + def test_list_mentions_value_error_with_retries(self): + # Enable retries and run test_list_mentions_value_error. + _service.enable_retries() + self.test_list_mentions_value_error() + + # Disable retries and run test_list_mentions_value_error. + _service.disable_retries() + self.test_list_mentions_value_error() # endregion ############################################################################## @@ -3925,24 +4258,13 @@ class TestListValues(): Test Class for list_values """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_values_all_params(self): """ list_values() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -3986,6 +4308,14 @@ def test_list_values_all_params(self): assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_list_values_all_params_with_retries(self): + # Enable retries and run test_list_values_all_params. + _service.enable_retries() + self.test_list_values_all_params() + + # Disable retries and run test_list_values_all_params. + _service.disable_retries() + self.test_list_values_all_params() @responses.activate def test_list_values_required_params(self): @@ -3993,7 +4323,7 @@ def test_list_values_required_params(self): test_list_values_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -4016,6 +4346,14 @@ def test_list_values_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_values_required_params_with_retries(self): + # Enable retries and run test_list_values_required_params. + _service.enable_retries() + self.test_list_values_required_params() + + # Disable retries and run test_list_values_required_params. + _service.disable_retries() + self.test_list_values_required_params() @responses.activate def test_list_values_value_error(self): @@ -4023,7 +4361,7 @@ def test_list_values_value_error(self): test_list_values_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -4046,30 +4384,27 @@ def test_list_values_value_error(self): _service.list_values(**req_copy) + def test_list_values_value_error_with_retries(self): + # Enable retries and run test_list_values_value_error. + _service.enable_retries() + self.test_list_values_value_error() + + # Disable retries and run test_list_values_value_error. + _service.disable_retries() + self.test_list_values_value_error() class TestCreateValue(): """ Test Class for create_value """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_value_all_params(self): """ create_value() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -4115,6 +4450,14 @@ def test_create_value_all_params(self): assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] + def test_create_value_all_params_with_retries(self): + # Enable retries and run test_create_value_all_params. + _service.enable_retries() + self.test_create_value_all_params() + + # Disable retries and run test_create_value_all_params. + _service.disable_retries() + self.test_create_value_all_params() @responses.activate def test_create_value_required_params(self): @@ -4122,7 +4465,7 @@ def test_create_value_required_params(self): test_create_value_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -4162,6 +4505,14 @@ def test_create_value_required_params(self): assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] + def test_create_value_required_params_with_retries(self): + # Enable retries and run test_create_value_required_params. + _service.enable_retries() + self.test_create_value_required_params() + + # Disable retries and run test_create_value_required_params. + _service.disable_retries() + self.test_create_value_required_params() @responses.activate def test_create_value_value_error(self): @@ -4169,7 +4520,7 @@ def test_create_value_value_error(self): test_create_value_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -4198,30 +4549,27 @@ def test_create_value_value_error(self): _service.create_value(**req_copy) + def test_create_value_value_error_with_retries(self): + # Enable retries and run test_create_value_value_error. + _service.enable_retries() + self.test_create_value_value_error() + + # Disable retries and run test_create_value_value_error. + _service.disable_retries() + self.test_create_value_value_error() class TestGetValue(): """ Test Class for get_value """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_value_all_params(self): """ get_value() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -4255,6 +4603,14 @@ def test_get_value_all_params(self): assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_get_value_all_params_with_retries(self): + # Enable retries and run test_get_value_all_params. + _service.enable_retries() + self.test_get_value_all_params() + + # Disable retries and run test_get_value_all_params. + _service.disable_retries() + self.test_get_value_all_params() @responses.activate def test_get_value_required_params(self): @@ -4262,7 +4618,7 @@ def test_get_value_required_params(self): test_get_value_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -4287,6 +4643,14 @@ def test_get_value_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_value_required_params_with_retries(self): + # Enable retries and run test_get_value_required_params. + _service.enable_retries() + self.test_get_value_required_params() + + # Disable retries and run test_get_value_required_params. + _service.disable_retries() + self.test_get_value_required_params() @responses.activate def test_get_value_value_error(self): @@ -4294,7 +4658,7 @@ def test_get_value_value_error(self): test_get_value_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -4319,30 +4683,27 @@ def test_get_value_value_error(self): _service.get_value(**req_copy) + def test_get_value_value_error_with_retries(self): + # Enable retries and run test_get_value_value_error. + _service.enable_retries() + self.test_get_value_value_error() + + # Disable retries and run test_get_value_value_error. + _service.disable_retries() + self.test_get_value_value_error() class TestUpdateValue(): """ Test Class for update_value """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_value_all_params(self): """ update_value() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -4393,6 +4754,14 @@ def test_update_value_all_params(self): assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] + def test_update_value_all_params_with_retries(self): + # Enable retries and run test_update_value_all_params. + _service.enable_retries() + self.test_update_value_all_params() + + # Disable retries and run test_update_value_all_params. + _service.disable_retries() + self.test_update_value_all_params() @responses.activate def test_update_value_required_params(self): @@ -4400,7 +4769,7 @@ def test_update_value_required_params(self): test_update_value_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -4442,6 +4811,14 @@ def test_update_value_required_params(self): assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] + def test_update_value_required_params_with_retries(self): + # Enable retries and run test_update_value_required_params. + _service.enable_retries() + self.test_update_value_required_params() + + # Disable retries and run test_update_value_required_params. + _service.disable_retries() + self.test_update_value_required_params() @responses.activate def test_update_value_value_error(self): @@ -4449,7 +4826,7 @@ def test_update_value_value_error(self): test_update_value_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -4479,30 +4856,27 @@ def test_update_value_value_error(self): _service.update_value(**req_copy) + def test_update_value_value_error_with_retries(self): + # Enable retries and run test_update_value_value_error. + _service.enable_retries() + self.test_update_value_value_error() + + # Disable retries and run test_update_value_value_error. + _service.disable_retries() + self.test_update_value_value_error() class TestDeleteValue(): """ Test Class for delete_value """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_value_all_params(self): """ delete_value() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') responses.add(responses.DELETE, url, status=200) @@ -4524,6 +4898,14 @@ def test_delete_value_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_value_all_params_with_retries(self): + # Enable retries and run test_delete_value_all_params. + _service.enable_retries() + self.test_delete_value_all_params() + + # Disable retries and run test_delete_value_all_params. + _service.disable_retries() + self.test_delete_value_all_params() @responses.activate def test_delete_value_value_error(self): @@ -4531,7 +4913,7 @@ def test_delete_value_value_error(self): test_delete_value_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') responses.add(responses.DELETE, url, status=200) @@ -4553,6 +4935,14 @@ def test_delete_value_value_error(self): _service.delete_value(**req_copy) + def test_delete_value_value_error_with_retries(self): + # Enable retries and run test_delete_value_value_error. + _service.enable_retries() + self.test_delete_value_value_error() + + # Disable retries and run test_delete_value_value_error. + _service.disable_retries() + self.test_delete_value_value_error() # endregion ############################################################################## @@ -4569,24 +4959,13 @@ class TestListSynonyms(): Test Class for list_synonyms """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_synonyms_all_params(self): """ list_synonyms() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -4629,6 +5008,14 @@ def test_list_synonyms_all_params(self): assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_list_synonyms_all_params_with_retries(self): + # Enable retries and run test_list_synonyms_all_params. + _service.enable_retries() + self.test_list_synonyms_all_params() + + # Disable retries and run test_list_synonyms_all_params. + _service.disable_retries() + self.test_list_synonyms_all_params() @responses.activate def test_list_synonyms_required_params(self): @@ -4636,7 +5023,7 @@ def test_list_synonyms_required_params(self): test_list_synonyms_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -4661,6 +5048,14 @@ def test_list_synonyms_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_synonyms_required_params_with_retries(self): + # Enable retries and run test_list_synonyms_required_params. + _service.enable_retries() + self.test_list_synonyms_required_params() + + # Disable retries and run test_list_synonyms_required_params. + _service.disable_retries() + self.test_list_synonyms_required_params() @responses.activate def test_list_synonyms_value_error(self): @@ -4668,7 +5063,7 @@ def test_list_synonyms_value_error(self): test_list_synonyms_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, @@ -4693,30 +5088,27 @@ def test_list_synonyms_value_error(self): _service.list_synonyms(**req_copy) + def test_list_synonyms_value_error_with_retries(self): + # Enable retries and run test_list_synonyms_value_error. + _service.enable_retries() + self.test_list_synonyms_value_error() + + # Disable retries and run test_list_synonyms_value_error. + _service.disable_retries() + self.test_list_synonyms_value_error() class TestCreateSynonym(): """ Test Class for create_synonym """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_synonym_all_params(self): """ create_synonym() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -4752,6 +5144,14 @@ def test_create_synonym_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['synonym'] == 'testString' + def test_create_synonym_all_params_with_retries(self): + # Enable retries and run test_create_synonym_all_params. + _service.enable_retries() + self.test_create_synonym_all_params() + + # Disable retries and run test_create_synonym_all_params. + _service.disable_retries() + self.test_create_synonym_all_params() @responses.activate def test_create_synonym_required_params(self): @@ -4759,7 +5159,7 @@ def test_create_synonym_required_params(self): test_create_synonym_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -4789,6 +5189,14 @@ def test_create_synonym_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['synonym'] == 'testString' + def test_create_synonym_required_params_with_retries(self): + # Enable retries and run test_create_synonym_required_params. + _service.enable_retries() + self.test_create_synonym_required_params() + + # Disable retries and run test_create_synonym_required_params. + _service.disable_retries() + self.test_create_synonym_required_params() @responses.activate def test_create_synonym_value_error(self): @@ -4796,7 +5204,7 @@ def test_create_synonym_value_error(self): test_create_synonym_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -4823,30 +5231,27 @@ def test_create_synonym_value_error(self): _service.create_synonym(**req_copy) + def test_create_synonym_value_error_with_retries(self): + # Enable retries and run test_create_synonym_value_error. + _service.enable_retries() + self.test_create_synonym_value_error() + + # Disable retries and run test_create_synonym_value_error. + _service.disable_retries() + self.test_create_synonym_value_error() class TestGetSynonym(): """ Test Class for get_synonym """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_synonym_all_params(self): """ get_synonym() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -4879,6 +5284,14 @@ def test_get_synonym_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_get_synonym_all_params_with_retries(self): + # Enable retries and run test_get_synonym_all_params. + _service.enable_retries() + self.test_get_synonym_all_params() + + # Disable retries and run test_get_synonym_all_params. + _service.disable_retries() + self.test_get_synonym_all_params() @responses.activate def test_get_synonym_required_params(self): @@ -4886,7 +5299,7 @@ def test_get_synonym_required_params(self): test_get_synonym_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -4913,6 +5326,14 @@ def test_get_synonym_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_synonym_required_params_with_retries(self): + # Enable retries and run test_get_synonym_required_params. + _service.enable_retries() + self.test_get_synonym_required_params() + + # Disable retries and run test_get_synonym_required_params. + _service.disable_retries() + self.test_get_synonym_required_params() @responses.activate def test_get_synonym_value_error(self): @@ -4920,7 +5341,7 @@ def test_get_synonym_value_error(self): test_get_synonym_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -4947,30 +5368,27 @@ def test_get_synonym_value_error(self): _service.get_synonym(**req_copy) + def test_get_synonym_value_error_with_retries(self): + # Enable retries and run test_get_synonym_value_error. + _service.enable_retries() + self.test_get_synonym_value_error() + + # Disable retries and run test_get_synonym_value_error. + _service.disable_retries() + self.test_get_synonym_value_error() class TestUpdateSynonym(): """ Test Class for update_synonym """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_synonym_all_params(self): """ update_synonym() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -5008,6 +5426,14 @@ def test_update_synonym_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['synonym'] == 'testString' + def test_update_synonym_all_params_with_retries(self): + # Enable retries and run test_update_synonym_all_params. + _service.enable_retries() + self.test_update_synonym_all_params() + + # Disable retries and run test_update_synonym_all_params. + _service.disable_retries() + self.test_update_synonym_all_params() @responses.activate def test_update_synonym_required_params(self): @@ -5015,7 +5441,7 @@ def test_update_synonym_required_params(self): test_update_synonym_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -5047,6 +5473,14 @@ def test_update_synonym_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['synonym'] == 'testString' + def test_update_synonym_required_params_with_retries(self): + # Enable retries and run test_update_synonym_required_params. + _service.enable_retries() + self.test_update_synonym_required_params() + + # Disable retries and run test_update_synonym_required_params. + _service.disable_retries() + self.test_update_synonym_required_params() @responses.activate def test_update_synonym_value_error(self): @@ -5054,7 +5488,7 @@ def test_update_synonym_value_error(self): test_update_synonym_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -5082,30 +5516,27 @@ def test_update_synonym_value_error(self): _service.update_synonym(**req_copy) + def test_update_synonym_value_error_with_retries(self): + # Enable retries and run test_update_synonym_value_error. + _service.enable_retries() + self.test_update_synonym_value_error() + + # Disable retries and run test_update_synonym_value_error. + _service.disable_retries() + self.test_update_synonym_value_error() class TestDeleteSynonym(): """ Test Class for delete_synonym """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_synonym_all_params(self): """ delete_synonym() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') responses.add(responses.DELETE, url, status=200) @@ -5129,6 +5560,14 @@ def test_delete_synonym_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_synonym_all_params_with_retries(self): + # Enable retries and run test_delete_synonym_all_params. + _service.enable_retries() + self.test_delete_synonym_all_params() + + # Disable retries and run test_delete_synonym_all_params. + _service.disable_retries() + self.test_delete_synonym_all_params() @responses.activate def test_delete_synonym_value_error(self): @@ -5136,7 +5575,7 @@ def test_delete_synonym_value_error(self): test_delete_synonym_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') + url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') responses.add(responses.DELETE, url, status=200) @@ -5160,6 +5599,14 @@ def test_delete_synonym_value_error(self): _service.delete_synonym(**req_copy) + def test_delete_synonym_value_error_with_retries(self): + # Enable retries and run test_delete_synonym_value_error. + _service.enable_retries() + self.test_delete_synonym_value_error() + + # Disable retries and run test_delete_synonym_value_error. + _service.disable_retries() + self.test_delete_synonym_value_error() # endregion ############################################################################## @@ -5176,25 +5623,14 @@ class TestListDialogNodes(): Test Class for list_dialog_nodes """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_dialog_nodes_all_params(self): """ list_dialog_nodes() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5232,6 +5668,14 @@ def test_list_dialog_nodes_all_params(self): assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_list_dialog_nodes_all_params_with_retries(self): + # Enable retries and run test_list_dialog_nodes_all_params. + _service.enable_retries() + self.test_list_dialog_nodes_all_params() + + # Disable retries and run test_list_dialog_nodes_all_params. + _service.disable_retries() + self.test_list_dialog_nodes_all_params() @responses.activate def test_list_dialog_nodes_required_params(self): @@ -5239,8 +5683,8 @@ def test_list_dialog_nodes_required_params(self): test_list_dialog_nodes_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5260,6 +5704,14 @@ def test_list_dialog_nodes_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_dialog_nodes_required_params_with_retries(self): + # Enable retries and run test_list_dialog_nodes_required_params. + _service.enable_retries() + self.test_list_dialog_nodes_required_params() + + # Disable retries and run test_list_dialog_nodes_required_params. + _service.disable_retries() + self.test_list_dialog_nodes_required_params() @responses.activate def test_list_dialog_nodes_value_error(self): @@ -5267,8 +5719,8 @@ def test_list_dialog_nodes_value_error(self): test_list_dialog_nodes_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5288,59 +5740,47 @@ def test_list_dialog_nodes_value_error(self): _service.list_dialog_nodes(**req_copy) + def test_list_dialog_nodes_value_error_with_retries(self): + # Enable retries and run test_list_dialog_nodes_value_error. + _service.enable_retries() + self.test_list_dialog_nodes_value_error() + + # Disable retries and run test_list_dialog_nodes_value_error. + _service.disable_retries() + self.test_list_dialog_nodes_value_error() class TestCreateDialogNode(): """ Test Class for create_dialog_node """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_dialog_node_all_params(self): """ create_dialog_node() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a ChannelTransferTargetChat model - channel_transfer_target_chat_model = {} - channel_transfer_target_chat_model['url'] = 'testString' - - # Construct a dict representation of a ChannelTransferTarget model - channel_transfer_target_model = {} - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - # Construct a dict representation of a ChannelTransferInfo model - channel_transfer_info_model = {} - channel_transfer_info_model['target'] = channel_transfer_target_model - # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5450,6 +5890,14 @@ def test_create_dialog_node_all_params(self): assert req_body['user_label'] == 'testString' assert req_body['disambiguation_opt_out'] == False + def test_create_dialog_node_all_params_with_retries(self): + # Enable retries and run test_create_dialog_node_all_params. + _service.enable_retries() + self.test_create_dialog_node_all_params() + + # Disable retries and run test_create_dialog_node_all_params. + _service.disable_retries() + self.test_create_dialog_node_all_params() @responses.activate def test_create_dialog_node_required_params(self): @@ -5457,36 +5905,27 @@ def test_create_dialog_node_required_params(self): test_create_dialog_node_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a ChannelTransferTargetChat model - channel_transfer_target_chat_model = {} - channel_transfer_target_chat_model['url'] = 'testString' - - # Construct a dict representation of a ChannelTransferTarget model - channel_transfer_target_model = {} - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - # Construct a dict representation of a ChannelTransferInfo model - channel_transfer_info_model = {} - channel_transfer_info_model['target'] = channel_transfer_target_model - # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5590,6 +6029,14 @@ def test_create_dialog_node_required_params(self): assert req_body['user_label'] == 'testString' assert req_body['disambiguation_opt_out'] == False + def test_create_dialog_node_required_params_with_retries(self): + # Enable retries and run test_create_dialog_node_required_params. + _service.enable_retries() + self.test_create_dialog_node_required_params() + + # Disable retries and run test_create_dialog_node_required_params. + _service.disable_retries() + self.test_create_dialog_node_required_params() @responses.activate def test_create_dialog_node_value_error(self): @@ -5597,36 +6044,27 @@ def test_create_dialog_node_value_error(self): test_create_dialog_node_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a ChannelTransferTargetChat model - channel_transfer_target_chat_model = {} - channel_transfer_target_chat_model['url'] = 'testString' - - # Construct a dict representation of a ChannelTransferTarget model - channel_transfer_target_model = {} - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - # Construct a dict representation of a ChannelTransferInfo model - channel_transfer_info_model = {} - channel_transfer_info_model['target'] = channel_transfer_target_model - # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5691,31 +6129,28 @@ def test_create_dialog_node_value_error(self): _service.create_dialog_node(**req_copy) + def test_create_dialog_node_value_error_with_retries(self): + # Enable retries and run test_create_dialog_node_value_error. + _service.enable_retries() + self.test_create_dialog_node_value_error() + + # Disable retries and run test_create_dialog_node_value_error. + _service.disable_retries() + self.test_create_dialog_node_value_error() class TestGetDialogNode(): """ Test Class for get_dialog_node """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_dialog_node_all_params(self): """ get_dialog_node() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5743,6 +6178,14 @@ def test_get_dialog_node_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_get_dialog_node_all_params_with_retries(self): + # Enable retries and run test_get_dialog_node_all_params. + _service.enable_retries() + self.test_get_dialog_node_all_params() + + # Disable retries and run test_get_dialog_node_all_params. + _service.disable_retries() + self.test_get_dialog_node_all_params() @responses.activate def test_get_dialog_node_required_params(self): @@ -5750,8 +6193,8 @@ def test_get_dialog_node_required_params(self): test_get_dialog_node_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5773,6 +6216,14 @@ def test_get_dialog_node_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_dialog_node_required_params_with_retries(self): + # Enable retries and run test_get_dialog_node_required_params. + _service.enable_retries() + self.test_get_dialog_node_required_params() + + # Disable retries and run test_get_dialog_node_required_params. + _service.disable_retries() + self.test_get_dialog_node_required_params() @responses.activate def test_get_dialog_node_value_error(self): @@ -5780,8 +6231,8 @@ def test_get_dialog_node_value_error(self): test_get_dialog_node_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5803,59 +6254,47 @@ def test_get_dialog_node_value_error(self): _service.get_dialog_node(**req_copy) + def test_get_dialog_node_value_error_with_retries(self): + # Enable retries and run test_get_dialog_node_value_error. + _service.enable_retries() + self.test_get_dialog_node_value_error() + + # Disable retries and run test_get_dialog_node_value_error. + _service.disable_retries() + self.test_get_dialog_node_value_error() class TestUpdateDialogNode(): """ Test Class for update_dialog_node """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_dialog_node_all_params(self): """ update_dialog_node() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) - # Construct a dict representation of a ChannelTransferTargetChat model - channel_transfer_target_chat_model = {} - channel_transfer_target_chat_model['url'] = 'testString' - - # Construct a dict representation of a ChannelTransferTarget model - channel_transfer_target_model = {} - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - # Construct a dict representation of a ChannelTransferInfo model - channel_transfer_info_model = {} - channel_transfer_info_model['target'] = channel_transfer_target_model - # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -5967,6 +6406,14 @@ def test_update_dialog_node_all_params(self): assert req_body['user_label'] == 'testString' assert req_body['disambiguation_opt_out'] == False + def test_update_dialog_node_all_params_with_retries(self): + # Enable retries and run test_update_dialog_node_all_params. + _service.enable_retries() + self.test_update_dialog_node_all_params() + + # Disable retries and run test_update_dialog_node_all_params. + _service.disable_retries() + self.test_update_dialog_node_all_params() @responses.activate def test_update_dialog_node_required_params(self): @@ -5974,36 +6421,27 @@ def test_update_dialog_node_required_params(self): test_update_dialog_node_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) - # Construct a dict representation of a ChannelTransferTargetChat model - channel_transfer_target_chat_model = {} - channel_transfer_target_chat_model['url'] = 'testString' - - # Construct a dict representation of a ChannelTransferTarget model - channel_transfer_target_model = {} - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - # Construct a dict representation of a ChannelTransferInfo model - channel_transfer_info_model = {} - channel_transfer_info_model['target'] = channel_transfer_target_model - # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6109,6 +6547,14 @@ def test_update_dialog_node_required_params(self): assert req_body['user_label'] == 'testString' assert req_body['disambiguation_opt_out'] == False + def test_update_dialog_node_required_params_with_retries(self): + # Enable retries and run test_update_dialog_node_required_params. + _service.enable_retries() + self.test_update_dialog_node_required_params() + + # Disable retries and run test_update_dialog_node_required_params. + _service.disable_retries() + self.test_update_dialog_node_required_params() @responses.activate def test_update_dialog_node_value_error(self): @@ -6116,36 +6562,27 @@ def test_update_dialog_node_value_error(self): test_update_dialog_node_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "channel_transfer", "message_to_user": "message_to_user", "transfer_info": {"target": {"chat": {"url": "url"}}}, "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) - # Construct a dict representation of a ChannelTransferTargetChat model - channel_transfer_target_chat_model = {} - channel_transfer_target_chat_model['url'] = 'testString' - - # Construct a dict representation of a ChannelTransferTarget model - channel_transfer_target_model = {} - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - # Construct a dict representation of a ChannelTransferInfo model - channel_transfer_info_model = {} - channel_transfer_info_model['target'] = channel_transfer_target_model - # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6211,30 +6648,27 @@ def test_update_dialog_node_value_error(self): _service.update_dialog_node(**req_copy) + def test_update_dialog_node_value_error_with_retries(self): + # Enable retries and run test_update_dialog_node_value_error. + _service.enable_retries() + self.test_update_dialog_node_value_error() + + # Disable retries and run test_update_dialog_node_value_error. + _service.disable_retries() + self.test_update_dialog_node_value_error() class TestDeleteDialogNode(): """ Test Class for delete_dialog_node """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_dialog_node_all_params(self): """ delete_dialog_node() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') + url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') responses.add(responses.DELETE, url, status=200) @@ -6254,6 +6688,14 @@ def test_delete_dialog_node_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_dialog_node_all_params_with_retries(self): + # Enable retries and run test_delete_dialog_node_all_params. + _service.enable_retries() + self.test_delete_dialog_node_all_params() + + # Disable retries and run test_delete_dialog_node_all_params. + _service.disable_retries() + self.test_delete_dialog_node_all_params() @responses.activate def test_delete_dialog_node_value_error(self): @@ -6261,7 +6703,7 @@ def test_delete_dialog_node_value_error(self): test_delete_dialog_node_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/dialog_nodes/testString') + url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') responses.add(responses.DELETE, url, status=200) @@ -6281,6 +6723,14 @@ def test_delete_dialog_node_value_error(self): _service.delete_dialog_node(**req_copy) + def test_delete_dialog_node_value_error_with_retries(self): + # Enable retries and run test_delete_dialog_node_value_error. + _service.enable_retries() + self.test_delete_dialog_node_value_error() + + # Disable retries and run test_delete_dialog_node_value_error. + _service.disable_retries() + self.test_delete_dialog_node_value_error() # endregion ############################################################################## @@ -6297,25 +6747,14 @@ class TestListLogs(): Test Class for list_logs """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_logs_all_params(self): """ list_logs() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/workspaces/testString/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6350,6 +6789,14 @@ def test_list_logs_all_params(self): assert 'page_limit={}'.format(page_limit) in query_string assert 'cursor={}'.format(cursor) in query_string + def test_list_logs_all_params_with_retries(self): + # Enable retries and run test_list_logs_all_params. + _service.enable_retries() + self.test_list_logs_all_params() + + # Disable retries and run test_list_logs_all_params. + _service.disable_retries() + self.test_list_logs_all_params() @responses.activate def test_list_logs_required_params(self): @@ -6357,8 +6804,8 @@ def test_list_logs_required_params(self): test_list_logs_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/workspaces/testString/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6378,6 +6825,14 @@ def test_list_logs_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_logs_required_params_with_retries(self): + # Enable retries and run test_list_logs_required_params. + _service.enable_retries() + self.test_list_logs_required_params() + + # Disable retries and run test_list_logs_required_params. + _service.disable_retries() + self.test_list_logs_required_params() @responses.activate def test_list_logs_value_error(self): @@ -6385,8 +6840,8 @@ def test_list_logs_value_error(self): test_list_logs_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/workspaces/testString/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6406,31 +6861,28 @@ def test_list_logs_value_error(self): _service.list_logs(**req_copy) + def test_list_logs_value_error_with_retries(self): + # Enable retries and run test_list_logs_value_error. + _service.enable_retries() + self.test_list_logs_value_error() + + # Disable retries and run test_list_logs_value_error. + _service.disable_retries() + self.test_list_logs_value_error() class TestListAllLogs(): """ Test Class for list_all_logs """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_all_logs_all_params(self): """ list_all_logs() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6463,6 +6915,14 @@ def test_list_all_logs_all_params(self): assert 'page_limit={}'.format(page_limit) in query_string assert 'cursor={}'.format(cursor) in query_string + def test_list_all_logs_all_params_with_retries(self): + # Enable retries and run test_list_all_logs_all_params. + _service.enable_retries() + self.test_list_all_logs_all_params() + + # Disable retries and run test_list_all_logs_all_params. + _service.disable_retries() + self.test_list_all_logs_all_params() @responses.activate def test_list_all_logs_required_params(self): @@ -6470,8 +6930,8 @@ def test_list_all_logs_required_params(self): test_list_all_logs_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6495,6 +6955,14 @@ def test_list_all_logs_required_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string + def test_list_all_logs_required_params_with_retries(self): + # Enable retries and run test_list_all_logs_required_params. + _service.enable_retries() + self.test_list_all_logs_required_params() + + # Disable retries and run test_list_all_logs_required_params. + _service.disable_retries() + self.test_list_all_logs_required_params() @responses.activate def test_list_all_logs_value_error(self): @@ -6502,8 +6970,8 @@ def test_list_all_logs_value_error(self): test_list_all_logs_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "text": ["text"], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v1/logs') + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6523,6 +6991,14 @@ def test_list_all_logs_value_error(self): _service.list_all_logs(**req_copy) + def test_list_all_logs_value_error_with_retries(self): + # Enable retries and run test_list_all_logs_value_error. + _service.enable_retries() + self.test_list_all_logs_value_error() + + # Disable retries and run test_list_all_logs_value_error. + _service.disable_retries() + self.test_list_all_logs_value_error() # endregion ############################################################################## @@ -6539,24 +7015,13 @@ class TestDeleteUserData(): Test Class for delete_user_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_user_data_all_params(self): """ delete_user_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/user_data') + url = preprocess_url('/v1/user_data') responses.add(responses.DELETE, url, status=202) @@ -6578,6 +7043,14 @@ def test_delete_user_data_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string + def test_delete_user_data_all_params_with_retries(self): + # Enable retries and run test_delete_user_data_all_params. + _service.enable_retries() + self.test_delete_user_data_all_params() + + # Disable retries and run test_delete_user_data_all_params. + _service.disable_retries() + self.test_delete_user_data_all_params() @responses.activate def test_delete_user_data_value_error(self): @@ -6585,7 +7058,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/user_data') + url = preprocess_url('/v1/user_data') responses.add(responses.DELETE, url, status=202) @@ -6603,6 +7076,14 @@ def test_delete_user_data_value_error(self): _service.delete_user_data(**req_copy) + def test_delete_user_data_value_error_with_retries(self): + # Enable retries and run test_delete_user_data_value_error. + _service.enable_retries() + self.test_delete_user_data_value_error() + + # Disable retries and run test_delete_user_data_value_error. + _service.disable_retries() + self.test_delete_user_data_value_error() # endregion ############################################################################## @@ -6702,7 +7183,6 @@ def test_bulk_classify_output_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -6792,7 +7272,6 @@ def test_bulk_classify_response_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -7046,8 +7525,8 @@ def test_counterexample_serialization(self): # Construct a json representation of a Counterexample model counterexample_model_json = {} counterexample_model_json['text'] = 'testString' - counterexample_model_json['created'] = "2019-01-01T12:00:00Z" - counterexample_model_json['updated'] = "2019-01-01T12:00:00Z" + counterexample_model_json['created'] = '2019-01-01T12:00:00Z' + counterexample_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Counterexample by calling from_dict on the json representation counterexample_model = Counterexample.from_dict(counterexample_model_json) @@ -7078,8 +7557,8 @@ def test_counterexample_collection_serialization(self): counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = "2019-01-01T12:00:00Z" - counterexample_model['updated'] = "2019-01-01T12:00:00Z" + counterexample_model['created'] = '2019-01-01T12:00:00Z' + counterexample_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -7127,8 +7606,8 @@ def test_create_entity_serialization(self): create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] - create_value_model['created'] = "2019-01-01T12:00:00Z" - create_value_model['updated'] = "2019-01-01T12:00:00Z" + create_value_model['created'] = '2019-01-01T12:00:00Z' + create_value_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a CreateEntity model create_entity_model_json = {} @@ -7136,8 +7615,8 @@ def test_create_entity_serialization(self): create_entity_model_json['description'] = 'testString' create_entity_model_json['metadata'] = {} create_entity_model_json['fuzzy_match'] = True - create_entity_model_json['created'] = "2019-01-01T12:00:00Z" - create_entity_model_json['updated'] = "2019-01-01T12:00:00Z" + create_entity_model_json['created'] = '2019-01-01T12:00:00Z' + create_entity_model_json['updated'] = '2019-01-01T12:00:00Z' create_entity_model_json['values'] = [create_value_model] # Construct a model instance of CreateEntity by calling from_dict on the json representation @@ -7174,15 +7653,15 @@ def test_create_intent_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = "2019-01-01T12:00:00Z" - example_model['updated'] = "2019-01-01T12:00:00Z" + example_model['created'] = '2019-01-01T12:00:00Z' + example_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a CreateIntent model create_intent_model_json = {} create_intent_model_json['intent'] = 'testString' create_intent_model_json['description'] = 'testString' - create_intent_model_json['created'] = "2019-01-01T12:00:00Z" - create_intent_model_json['updated'] = "2019-01-01T12:00:00Z" + create_intent_model_json['created'] = '2019-01-01T12:00:00Z' + create_intent_model_json['updated'] = '2019-01-01T12:00:00Z' create_intent_model_json['examples'] = [example_model] # Construct a model instance of CreateIntent by calling from_dict on the json representation @@ -7217,8 +7696,8 @@ def test_create_value_serialization(self): create_value_model_json['type'] = 'synonyms' create_value_model_json['synonyms'] = ['testString'] create_value_model_json['patterns'] = ['testString'] - create_value_model_json['created'] = "2019-01-01T12:00:00Z" - create_value_model_json['updated'] = "2019-01-01T12:00:00Z" + create_value_model_json['created'] = '2019-01-01T12:00:00Z' + create_value_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of CreateValue by calling from_dict on the json representation create_value_model = CreateValue.from_dict(create_value_model_json) @@ -7247,23 +7726,17 @@ def test_dialog_node_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat - channel_transfer_target_chat_model['url'] = 'testString' - - channel_transfer_target_model = {} # ChannelTransferTarget - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - channel_transfer_info_model = {} # ChannelTransferInfo - channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -7312,8 +7785,8 @@ def test_dialog_node_serialization(self): dialog_node_model_json['user_label'] = 'testString' dialog_node_model_json['disambiguation_opt_out'] = False dialog_node_model_json['disabled'] = True - dialog_node_model_json['created'] = "2019-01-01T12:00:00Z" - dialog_node_model_json['updated'] = "2019-01-01T12:00:00Z" + dialog_node_model_json['created'] = '2019-01-01T12:00:00Z' + dialog_node_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of DialogNode by calling from_dict on the json representation dialog_node_model = DialogNode.from_dict(dialog_node_model_json) @@ -7375,23 +7848,17 @@ def test_dialog_node_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat - channel_transfer_target_chat_model['url'] = 'testString' - - channel_transfer_target_model = {} # ChannelTransferTarget - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - channel_transfer_info_model = {} # ChannelTransferInfo - channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -7439,8 +7906,8 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False dialog_node_model['disabled'] = True - dialog_node_model['created'] = "2019-01-01T12:00:00Z" - dialog_node_model['updated'] = "2019-01-01T12:00:00Z" + dialog_node_model['created'] = '2019-01-01T12:00:00Z' + dialog_node_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -7553,23 +8020,17 @@ def test_dialog_node_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat - channel_transfer_target_chat_model['url'] = 'testString' - - channel_transfer_target_model = {} # ChannelTransferTarget - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - channel_transfer_info_model = {} # ChannelTransferInfo - channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -7732,7 +8193,6 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -7831,7 +8291,6 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -7986,7 +8445,6 @@ def test_dialog_suggestion_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -8087,7 +8545,6 @@ def test_dialog_suggestion_value_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -8132,8 +8589,8 @@ def test_entity_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = "2019-01-01T12:00:00Z" - value_model['updated'] = "2019-01-01T12:00:00Z" + value_model['created'] = '2019-01-01T12:00:00Z' + value_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a Entity model entity_model_json = {} @@ -8141,8 +8598,8 @@ def test_entity_serialization(self): entity_model_json['description'] = 'testString' entity_model_json['metadata'] = {} entity_model_json['fuzzy_match'] = True - entity_model_json['created'] = "2019-01-01T12:00:00Z" - entity_model_json['updated'] = "2019-01-01T12:00:00Z" + entity_model_json['created'] = '2019-01-01T12:00:00Z' + entity_model_json['updated'] = '2019-01-01T12:00:00Z' entity_model_json['values'] = [value_model] # Construct a model instance of Entity by calling from_dict on the json representation @@ -8178,16 +8635,16 @@ def test_entity_collection_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = "2019-01-01T12:00:00Z" - value_model['updated'] = "2019-01-01T12:00:00Z" + value_model['created'] = '2019-01-01T12:00:00Z' + value_model['updated'] = '2019-01-01T12:00:00Z' entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' entity_model['metadata'] = {} entity_model['fuzzy_match'] = True - entity_model['created'] = "2019-01-01T12:00:00Z" - entity_model['updated'] = "2019-01-01T12:00:00Z" + entity_model['created'] = '2019-01-01T12:00:00Z' + entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] pagination_model = {} # Pagination @@ -8314,8 +8771,8 @@ def test_example_serialization(self): example_model_json = {} example_model_json['text'] = 'testString' example_model_json['mentions'] = [mention_model] - example_model_json['created'] = "2019-01-01T12:00:00Z" - example_model_json['updated'] = "2019-01-01T12:00:00Z" + example_model_json['created'] = '2019-01-01T12:00:00Z' + example_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Example by calling from_dict on the json representation example_model = Example.from_dict(example_model_json) @@ -8351,8 +8808,8 @@ def test_example_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = "2019-01-01T12:00:00Z" - example_model['updated'] = "2019-01-01T12:00:00Z" + example_model['created'] = '2019-01-01T12:00:00Z' + example_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -8401,15 +8858,15 @@ def test_intent_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = "2019-01-01T12:00:00Z" - example_model['updated'] = "2019-01-01T12:00:00Z" + example_model['created'] = '2019-01-01T12:00:00Z' + example_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a Intent model intent_model_json = {} intent_model_json['intent'] = 'testString' intent_model_json['description'] = 'testString' - intent_model_json['created'] = "2019-01-01T12:00:00Z" - intent_model_json['updated'] = "2019-01-01T12:00:00Z" + intent_model_json['created'] = '2019-01-01T12:00:00Z' + intent_model_json['updated'] = '2019-01-01T12:00:00Z' intent_model_json['examples'] = [example_model] # Construct a model instance of Intent by calling from_dict on the json representation @@ -8446,14 +8903,14 @@ def test_intent_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = "2019-01-01T12:00:00Z" - example_model['updated'] = "2019-01-01T12:00:00Z" + example_model['created'] = '2019-01-01T12:00:00Z' + example_model['updated'] = '2019-01-01T12:00:00Z' intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = "2019-01-01T12:00:00Z" - intent_model['updated'] = "2019-01-01T12:00:00Z" + intent_model['created'] = '2019-01-01T12:00:00Z' + intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] pagination_model = {} # Pagination @@ -8552,7 +9009,6 @@ def test_log_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -8607,7 +9063,6 @@ def test_log_serialization(self): output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] - output_data_model['text'] = ['testString'] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' @@ -8731,7 +9186,6 @@ def test_log_collection_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -8786,7 +9240,6 @@ def test_log_collection_serialization(self): output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] - output_data_model['text'] = ['testString'] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' @@ -9122,7 +9575,6 @@ def test_message_request_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -9177,7 +9629,6 @@ def test_message_request_serialization(self): output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] - output_data_model['text'] = ['testString'] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' @@ -9282,7 +9733,6 @@ def test_message_response_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -9337,7 +9787,6 @@ def test_message_response_serialization(self): output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] - output_data_model['text'] = ['testString'] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' @@ -9457,7 +9906,6 @@ def test_output_data_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -9488,7 +9936,6 @@ def test_output_data_serialization(self): output_data_model_json['nodes_visited'] = ['testString'] output_data_model_json['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model_json['log_messages'] = [log_message_model] - output_data_model_json['text'] = ['testString'] output_data_model_json['generic'] = [runtime_response_generic_model] output_data_model_json['foo'] = 'testString' @@ -9637,7 +10084,6 @@ def test_runtime_entity_serialization(self): runtime_entity_model_json['location'] = [38] runtime_entity_model_json['value'] = 'testString' runtime_entity_model_json['confidence'] = 72.5 - runtime_entity_model_json['metadata'] = {} runtime_entity_model_json['groups'] = [capture_group_model] runtime_entity_model_json['interpretation'] = runtime_entity_interpretation_model runtime_entity_model_json['alternatives'] = [runtime_entity_alternative_model] @@ -9814,8 +10260,8 @@ def test_synonym_serialization(self): # Construct a json representation of a Synonym model synonym_model_json = {} synonym_model_json['synonym'] = 'testString' - synonym_model_json['created'] = "2019-01-01T12:00:00Z" - synonym_model_json['updated'] = "2019-01-01T12:00:00Z" + synonym_model_json['created'] = '2019-01-01T12:00:00Z' + synonym_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Synonym by calling from_dict on the json representation synonym_model = Synonym.from_dict(synonym_model_json) @@ -9846,8 +10292,8 @@ def test_synonym_collection_serialization(self): synonym_model = {} # Synonym synonym_model['synonym'] = 'testString' - synonym_model['created'] = "2019-01-01T12:00:00Z" - synonym_model['updated'] = "2019-01-01T12:00:00Z" + synonym_model['created'] = '2019-01-01T12:00:00Z' + synonym_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -9894,8 +10340,8 @@ def test_value_serialization(self): value_model_json['type'] = 'synonyms' value_model_json['synonyms'] = ['testString'] value_model_json['patterns'] = ['testString'] - value_model_json['created'] = "2019-01-01T12:00:00Z" - value_model_json['updated'] = "2019-01-01T12:00:00Z" + value_model_json['created'] = '2019-01-01T12:00:00Z' + value_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Value by calling from_dict on the json representation value_model = Value.from_dict(value_model_json) @@ -9930,8 +10376,8 @@ def test_value_collection_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = "2019-01-01T12:00:00Z" - value_model['updated'] = "2019-01-01T12:00:00Z" + value_model['created'] = '2019-01-01T12:00:00Z' + value_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -10040,23 +10486,17 @@ def test_workspace_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat - channel_transfer_target_chat_model['url'] = 'testString' - - channel_transfer_target_model = {} # ChannelTransferTarget - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - channel_transfer_info_model = {} # ChannelTransferInfo - channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -10104,13 +10544,13 @@ def test_workspace_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False dialog_node_model['disabled'] = True - dialog_node_model['created'] = "2019-01-01T12:00:00Z" - dialog_node_model['updated'] = "2019-01-01T12:00:00Z" + dialog_node_model['created'] = '2019-01-01T12:00:00Z' + dialog_node_model['updated'] = '2019-01-01T12:00:00Z' counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = "2019-01-01T12:00:00Z" - counterexample_model['updated'] = "2019-01-01T12:00:00Z" + counterexample_model['created'] = '2019-01-01T12:00:00Z' + counterexample_model['updated'] = '2019-01-01T12:00:00Z' workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True @@ -10138,6 +10578,7 @@ def test_workspace_serialization(self): workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['foo'] = 'testString' webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' @@ -10155,14 +10596,14 @@ def test_workspace_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = "2019-01-01T12:00:00Z" - example_model['updated'] = "2019-01-01T12:00:00Z" + example_model['created'] = '2019-01-01T12:00:00Z' + example_model['updated'] = '2019-01-01T12:00:00Z' intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = "2019-01-01T12:00:00Z" - intent_model['updated'] = "2019-01-01T12:00:00Z" + intent_model['created'] = '2019-01-01T12:00:00Z' + intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] value_model = {} # Value @@ -10171,16 +10612,16 @@ def test_workspace_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = "2019-01-01T12:00:00Z" - value_model['updated'] = "2019-01-01T12:00:00Z" + value_model['created'] = '2019-01-01T12:00:00Z' + value_model['updated'] = '2019-01-01T12:00:00Z' entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' entity_model['metadata'] = {} entity_model['fuzzy_match'] = True - entity_model['created'] = "2019-01-01T12:00:00Z" - entity_model['updated'] = "2019-01-01T12:00:00Z" + entity_model['created'] = '2019-01-01T12:00:00Z' + entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] # Construct a json representation of a Workspace model @@ -10191,8 +10632,8 @@ def test_workspace_serialization(self): workspace_model_json['workspace_id'] = 'testString' workspace_model_json['dialog_nodes'] = [dialog_node_model] workspace_model_json['counterexamples'] = [counterexample_model] - workspace_model_json['created'] = "2019-01-01T12:00:00Z" - workspace_model_json['updated'] = "2019-01-01T12:00:00Z" + workspace_model_json['created'] = '2019-01-01T12:00:00Z' + workspace_model_json['updated'] = '2019-01-01T12:00:00Z' workspace_model_json['metadata'] = {} workspace_model_json['learning_opt_out'] = False workspace_model_json['system_settings'] = workspace_system_settings_model @@ -10228,23 +10669,17 @@ def test_workspace_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat - channel_transfer_target_chat_model['url'] = 'testString' - - channel_transfer_target_model = {} # ChannelTransferTarget - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - - channel_transfer_info_model = {} # ChannelTransferInfo - channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer - dialog_node_output_generic_model['response_type'] = 'channel_transfer' - dialog_node_output_generic_model['message_to_user'] = 'testString' - dialog_node_output_generic_model['transfer_info'] = channel_transfer_info_model + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -10292,13 +10727,13 @@ def test_workspace_collection_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False dialog_node_model['disabled'] = True - dialog_node_model['created'] = "2019-01-01T12:00:00Z" - dialog_node_model['updated'] = "2019-01-01T12:00:00Z" + dialog_node_model['created'] = '2019-01-01T12:00:00Z' + dialog_node_model['updated'] = '2019-01-01T12:00:00Z' counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = "2019-01-01T12:00:00Z" - counterexample_model['updated'] = "2019-01-01T12:00:00Z" + counterexample_model['created'] = '2019-01-01T12:00:00Z' + counterexample_model['updated'] = '2019-01-01T12:00:00Z' workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True @@ -10326,6 +10761,7 @@ def test_workspace_collection_serialization(self): workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['foo'] = 'testString' webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' @@ -10343,14 +10779,14 @@ def test_workspace_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = "2019-01-01T12:00:00Z" - example_model['updated'] = "2019-01-01T12:00:00Z" + example_model['created'] = '2019-01-01T12:00:00Z' + example_model['updated'] = '2019-01-01T12:00:00Z' intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = "2019-01-01T12:00:00Z" - intent_model['updated'] = "2019-01-01T12:00:00Z" + intent_model['created'] = '2019-01-01T12:00:00Z' + intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] value_model = {} # Value @@ -10359,16 +10795,16 @@ def test_workspace_collection_serialization(self): value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = "2019-01-01T12:00:00Z" - value_model['updated'] = "2019-01-01T12:00:00Z" + value_model['created'] = '2019-01-01T12:00:00Z' + value_model['updated'] = '2019-01-01T12:00:00Z' entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' entity_model['metadata'] = {} entity_model['fuzzy_match'] = True - entity_model['created'] = "2019-01-01T12:00:00Z" - entity_model['updated'] = "2019-01-01T12:00:00Z" + entity_model['created'] = '2019-01-01T12:00:00Z' + entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] workspace_model = {} # Workspace @@ -10378,8 +10814,8 @@ def test_workspace_collection_serialization(self): workspace_model['workspace_id'] = 'testString' workspace_model['dialog_nodes'] = [dialog_node_model] workspace_model['counterexamples'] = [counterexample_model] - workspace_model['created'] = "2019-01-01T12:00:00Z" - workspace_model['updated'] = "2019-01-01T12:00:00Z" + workspace_model['created'] = '2019-01-01T12:00:00Z' + workspace_model['updated'] = '2019-01-01T12:00:00Z' workspace_model['metadata'] = {} workspace_model['learning_opt_out'] = False workspace_model['system_settings'] = workspace_system_settings_model @@ -10455,6 +10891,7 @@ def test_workspace_system_settings_serialization(self): workspace_system_settings_model_json['spelling_auto_correct'] = False workspace_system_settings_model_json['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model_json['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model_json['foo'] = 'testString' # Construct a model instance of WorkspaceSystemSettings by calling from_dict on the json representation workspace_system_settings_model = WorkspaceSystemSettings.from_dict(workspace_system_settings_model_json) @@ -10471,6 +10908,16 @@ def test_workspace_system_settings_serialization(self): workspace_system_settings_model_json2 = workspace_system_settings_model.to_dict() assert workspace_system_settings_model_json2 == workspace_system_settings_model_json + # Test get_properties and set_properties methods. + workspace_system_settings_model.set_properties({}) + actual_dict = workspace_system_settings_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': 'testString'} + workspace_system_settings_model.set_properties(expected_dict) + actual_dict = workspace_system_settings_model.get_properties() + assert actual_dict == expected_dict + class TestModel_WorkspaceSystemSettingsDisambiguation(): """ Test Class for WorkspaceSystemSettingsDisambiguation @@ -10593,6 +11040,46 @@ def test_workspace_system_settings_tooling_serialization(self): workspace_system_settings_tooling_model_json2 = workspace_system_settings_tooling_model.to_dict() assert workspace_system_settings_tooling_model_json2 == workspace_system_settings_tooling_model_json +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio(): + """ + Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio + """ + + def test_dialog_node_output_generic_dialog_node_output_response_type_audio_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json = {} + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['response_type'] = 'audio' + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['source'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['title'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['description'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channels'] = [response_generic_channel_model] + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['alt_text'] = 'testString' + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_audio_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio.from_dict(dialog_node_output_generic_dialog_node_output_response_type_audio_model_json) + assert dialog_node_output_generic_dialog_node_output_response_type_audio_model != False + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_audio_model_dict = DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio.from_dict(dialog_node_output_generic_dialog_node_output_response_type_audio_model_json).__dict__ + dialog_node_output_generic_dialog_node_output_response_type_audio_model2 = DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio(**dialog_node_output_generic_dialog_node_output_response_type_audio_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_generic_dialog_node_output_response_type_audio_model == dialog_node_output_generic_dialog_node_output_response_type_audio_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_audio_model.to_dict() + assert dialog_node_output_generic_dialog_node_output_response_type_audio_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_audio_model_json + class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer(): """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer @@ -10684,6 +11171,45 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe(): + """ + Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe + """ + + def test_dialog_node_output_generic_dialog_node_output_response_type_iframe_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe model + dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json = {} + dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json['response_type'] = 'iframe' + dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json['source'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json['title'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json['description'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json['image_url'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json['channels'] = [response_generic_channel_model] + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_iframe_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe.from_dict(dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json) + assert dialog_node_output_generic_dialog_node_output_response_type_iframe_model != False + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_iframe_model_dict = DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe.from_dict(dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json).__dict__ + dialog_node_output_generic_dialog_node_output_response_type_iframe_model2 = DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe(**dialog_node_output_generic_dialog_node_output_response_type_iframe_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_generic_dialog_node_output_response_type_iframe_model == dialog_node_output_generic_dialog_node_output_response_type_iframe_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_iframe_model.to_dict() + assert dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json + class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeImage(): """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeImage @@ -10791,7 +11317,6 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -10986,6 +11511,86 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_user_define dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_user_defined_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo(): + """ + Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo + """ + + def test_dialog_node_output_generic_dialog_node_output_response_type_video_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo model + dialog_node_output_generic_dialog_node_output_response_type_video_model_json = {} + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['response_type'] = 'video' + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['source'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['title'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['description'] = 'testString' + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channels'] = [response_generic_channel_model] + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['alt_text'] = 'testString' + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_video_model = DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo.from_dict(dialog_node_output_generic_dialog_node_output_response_type_video_model_json) + assert dialog_node_output_generic_dialog_node_output_response_type_video_model != False + + # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo by calling from_dict on the json representation + dialog_node_output_generic_dialog_node_output_response_type_video_model_dict = DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo.from_dict(dialog_node_output_generic_dialog_node_output_response_type_video_model_json).__dict__ + dialog_node_output_generic_dialog_node_output_response_type_video_model2 = DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo(**dialog_node_output_generic_dialog_node_output_response_type_video_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_generic_dialog_node_output_response_type_video_model == dialog_node_output_generic_dialog_node_output_response_type_video_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_generic_dialog_node_output_response_type_video_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_video_model.to_dict() + assert dialog_node_output_generic_dialog_node_output_response_type_video_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_video_model_json + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeAudio + """ + + def test_runtime_response_generic_runtime_response_type_audio_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeAudio + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeAudio model + runtime_response_generic_runtime_response_type_audio_model_json = {} + runtime_response_generic_runtime_response_type_audio_model_json['response_type'] = 'audio' + runtime_response_generic_runtime_response_type_audio_model_json['source'] = 'testString' + runtime_response_generic_runtime_response_type_audio_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_audio_model_json['description'] = 'testString' + runtime_response_generic_runtime_response_type_audio_model_json['channels'] = [response_generic_channel_model] + runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_audio_model_json['alt_text'] = 'testString' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_audio_model = RuntimeResponseGenericRuntimeResponseTypeAudio.from_dict(runtime_response_generic_runtime_response_type_audio_model_json) + assert runtime_response_generic_runtime_response_type_audio_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_audio_model_dict = RuntimeResponseGenericRuntimeResponseTypeAudio.from_dict(runtime_response_generic_runtime_response_type_audio_model_json).__dict__ + runtime_response_generic_runtime_response_type_audio_model2 = RuntimeResponseGenericRuntimeResponseTypeAudio(**runtime_response_generic_runtime_response_type_audio_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_audio_model == runtime_response_generic_runtime_response_type_audio_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_audio_model_json2 = runtime_response_generic_runtime_response_type_audio_model.to_dict() + assert runtime_response_generic_runtime_response_type_audio_model_json2 == runtime_response_generic_runtime_response_type_audio_model_json + class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer @@ -11079,6 +11684,45 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json +class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeIframe + """ + + def test_runtime_response_generic_runtime_response_type_iframe_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeIframe + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeIframe model + runtime_response_generic_runtime_response_type_iframe_model_json = {} + runtime_response_generic_runtime_response_type_iframe_model_json['response_type'] = 'iframe' + runtime_response_generic_runtime_response_type_iframe_model_json['source'] = 'testString' + runtime_response_generic_runtime_response_type_iframe_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_iframe_model_json['description'] = 'testString' + runtime_response_generic_runtime_response_type_iframe_model_json['image_url'] = 'testString' + runtime_response_generic_runtime_response_type_iframe_model_json['channels'] = [response_generic_channel_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeIframe by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_iframe_model = RuntimeResponseGenericRuntimeResponseTypeIframe.from_dict(runtime_response_generic_runtime_response_type_iframe_model_json) + assert runtime_response_generic_runtime_response_type_iframe_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeIframe by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_iframe_model_dict = RuntimeResponseGenericRuntimeResponseTypeIframe.from_dict(runtime_response_generic_runtime_response_type_iframe_model_json).__dict__ + runtime_response_generic_runtime_response_type_iframe_model2 = RuntimeResponseGenericRuntimeResponseTypeIframe(**runtime_response_generic_runtime_response_type_iframe_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_iframe_model == runtime_response_generic_runtime_response_type_iframe_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_iframe_model_json2 = runtime_response_generic_runtime_response_type_iframe_model.to_dict() + assert runtime_response_generic_runtime_response_type_iframe_model_json2 == runtime_response_generic_runtime_response_type_iframe_model_json + class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeImage @@ -11186,7 +11830,6 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -11333,7 +11976,6 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -11447,6 +12089,46 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati runtime_response_generic_runtime_response_type_user_defined_model_json2 = runtime_response_generic_runtime_response_type_user_defined_model.to_dict() assert runtime_response_generic_runtime_response_type_user_defined_model_json2 == runtime_response_generic_runtime_response_type_user_defined_model_json +class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeVideo + """ + + def test_runtime_response_generic_runtime_response_type_video_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeVideo + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'chat' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeVideo model + runtime_response_generic_runtime_response_type_video_model_json = {} + runtime_response_generic_runtime_response_type_video_model_json['response_type'] = 'video' + runtime_response_generic_runtime_response_type_video_model_json['source'] = 'testString' + runtime_response_generic_runtime_response_type_video_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_video_model_json['description'] = 'testString' + runtime_response_generic_runtime_response_type_video_model_json['channels'] = [response_generic_channel_model] + runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_video_model_json['alt_text'] = 'testString' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_video_model = RuntimeResponseGenericRuntimeResponseTypeVideo.from_dict(runtime_response_generic_runtime_response_type_video_model_json) + assert runtime_response_generic_runtime_response_type_video_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_video_model_dict = RuntimeResponseGenericRuntimeResponseTypeVideo.from_dict(runtime_response_generic_runtime_response_type_video_model_json).__dict__ + runtime_response_generic_runtime_response_type_video_model2 = RuntimeResponseGenericRuntimeResponseTypeVideo(**runtime_response_generic_runtime_response_type_video_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_video_model == runtime_response_generic_runtime_response_type_video_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_video_model_json2 = runtime_response_generic_runtime_response_type_video_model.to_dict() + assert runtime_response_generic_runtime_response_type_video_model_json2 == runtime_response_generic_runtime_response_type_video_model_json + # endregion ############################################################################## diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 1ba9a3ee1..2542016ee 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2021. +# (C) Copyright IBM Corp. 2018, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -32,11 +32,38 @@ _service = AssistantV2( authenticator=NoAuthAuthenticator(), version=version - ) +) _base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' _service.set_service_url(_base_url) + +def preprocess_url(operation_path: str): + """ + Returns the request url associated with the specified operation path. + This will be base_url concatenated with a quoted version of operation_path. + The returned request URL is used to register the mock response so it needs + to match the request URL that is formed by the requests library. + """ + # First, unquote the path since it might have some quoted/escaped characters in it + # due to how the generator inserts the operation paths into the unit test code. + operation_path = urllib.parse.unquote(operation_path) + + # Next, quote the path using urllib so that we approximate what will + # happen during request processing. + operation_path = urllib.parse.quote(operation_path, safe='/') + + # Finally, form the request URL from the base URL and operation path. + request_url = _base_url + operation_path + + # If the request url does NOT end with a /, then just return it as-is. + # Otherwise, return a regular expression that matches one or more trailing /. + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + ############################################################################## # Start of Service: Sessions ############################################################################## @@ -47,24 +74,13 @@ class TestCreateSession(): Test Class for create_session """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_session_all_params(self): """ create_session() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions') + url = preprocess_url('/v2/assistants/testString/sessions') mock_response = '{"session_id": "session_id"}' responses.add(responses.POST, url, @@ -85,6 +101,14 @@ def test_create_session_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_session_all_params_with_retries(self): + # Enable retries and run test_create_session_all_params. + _service.enable_retries() + self.test_create_session_all_params() + + # Disable retries and run test_create_session_all_params. + _service.disable_retries() + self.test_create_session_all_params() @responses.activate def test_create_session_value_error(self): @@ -92,7 +116,7 @@ def test_create_session_value_error(self): test_create_session_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions') + url = preprocess_url('/v2/assistants/testString/sessions') mock_response = '{"session_id": "session_id"}' responses.add(responses.POST, url, @@ -113,30 +137,27 @@ def test_create_session_value_error(self): _service.create_session(**req_copy) + def test_create_session_value_error_with_retries(self): + # Enable retries and run test_create_session_value_error. + _service.enable_retries() + self.test_create_session_value_error() + + # Disable retries and run test_create_session_value_error. + _service.disable_retries() + self.test_create_session_value_error() class TestDeleteSession(): """ Test Class for delete_session """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_session_all_params(self): """ delete_session() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString') + url = preprocess_url('/v2/assistants/testString/sessions/testString') responses.add(responses.DELETE, url, status=200) @@ -156,6 +177,14 @@ def test_delete_session_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_session_all_params_with_retries(self): + # Enable retries and run test_delete_session_all_params. + _service.enable_retries() + self.test_delete_session_all_params() + + # Disable retries and run test_delete_session_all_params. + _service.disable_retries() + self.test_delete_session_all_params() @responses.activate def test_delete_session_value_error(self): @@ -163,7 +192,7 @@ def test_delete_session_value_error(self): test_delete_session_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString') + url = preprocess_url('/v2/assistants/testString/sessions/testString') responses.add(responses.DELETE, url, status=200) @@ -183,6 +212,14 @@ def test_delete_session_value_error(self): _service.delete_session(**req_copy) + def test_delete_session_value_error_with_retries(self): + # Enable retries and run test_delete_session_value_error. + _service.enable_retries() + self.test_delete_session_value_error() + + # Disable retries and run test_delete_session_value_error. + _service.disable_retries() + self.test_delete_session_value_error() # endregion ############################################################################## @@ -199,25 +236,14 @@ class TestMessage(): Test Class for message """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_message_all_params(self): """ message() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + url = preprocess_url('/v2/assistants/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -278,12 +304,16 @@ def test_message_all_params(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + # Construct a dict representation of a MessageInputAttachment model + message_input_attachment_model = {} + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + # Construct a dict representation of a MessageInputOptionsSpelling model message_input_options_spelling_model = {} message_input_options_spelling_model['suggestions'] = True @@ -305,6 +335,7 @@ def test_message_all_params(self): message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model # Construct a dict representation of a MessageContextGlobalSystem model @@ -316,6 +347,7 @@ def test_message_all_params(self): message_context_global_system_model['reference_time'] = 'testString' message_context_global_system_model['session_start_time'] = 'testString' message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True # Construct a dict representation of a MessageContextGlobal model message_context_global_model = {} @@ -335,6 +367,7 @@ def test_message_all_params(self): message_context_model = {} message_context_model['global'] = message_context_global_model message_context_model['skills'] = {} + message_context_model['integrations'] = { 'foo': 'bar' } # Set up parameter values assistant_id = 'testString' @@ -362,6 +395,14 @@ def test_message_all_params(self): assert req_body['context'] == message_context_model assert req_body['user_id'] == 'testString' + def test_message_all_params_with_retries(self): + # Enable retries and run test_message_all_params. + _service.enable_retries() + self.test_message_all_params() + + # Disable retries and run test_message_all_params. + _service.disable_retries() + self.test_message_all_params() @responses.activate def test_message_required_params(self): @@ -369,8 +410,8 @@ def test_message_required_params(self): test_message_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + url = preprocess_url('/v2/assistants/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -392,6 +433,14 @@ def test_message_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_message_required_params_with_retries(self): + # Enable retries and run test_message_required_params. + _service.enable_retries() + self.test_message_required_params() + + # Disable retries and run test_message_required_params. + _service.disable_retries() + self.test_message_required_params() @responses.activate def test_message_value_error(self): @@ -399,8 +448,8 @@ def test_message_value_error(self): test_message_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + url = preprocess_url('/v2/assistants/testString/sessions/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -422,31 +471,28 @@ def test_message_value_error(self): _service.message(**req_copy) + def test_message_value_error_with_retries(self): + # Enable retries and run test_message_value_error. + _service.enable_retries() + self.test_message_value_error() + + # Disable retries and run test_message_value_error. + _service.disable_retries() + self.test_message_value_error() class TestMessageStateless(): """ Test Class for message_stateless """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_message_stateless_all_params(self): """ message_stateless() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + url = preprocess_url('/v2/assistants/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -507,12 +553,16 @@ def test_message_stateless_all_params(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + # Construct a dict representation of a MessageInputAttachment model + message_input_attachment_model = {} + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + # Construct a dict representation of a MessageInputOptionsSpelling model message_input_options_spelling_model = {} message_input_options_spelling_model['suggestions'] = True @@ -532,6 +582,7 @@ def test_message_stateless_all_params(self): message_input_stateless_model['intents'] = [runtime_intent_model] message_input_stateless_model['entities'] = [runtime_entity_model] message_input_stateless_model['suggestion_id'] = 'testString' + message_input_stateless_model['attachments'] = [message_input_attachment_model] message_input_stateless_model['options'] = message_input_options_stateless_model # Construct a dict representation of a MessageContextGlobalSystem model @@ -543,6 +594,7 @@ def test_message_stateless_all_params(self): message_context_global_system_model['reference_time'] = 'testString' message_context_global_system_model['session_start_time'] = 'testString' message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True # Construct a dict representation of a MessageContextGlobalStateless model message_context_global_stateless_model = {} @@ -563,6 +615,7 @@ def test_message_stateless_all_params(self): message_context_stateless_model = {} message_context_stateless_model['global'] = message_context_global_stateless_model message_context_stateless_model['skills'] = {} + message_context_stateless_model['integrations'] = { 'foo': 'bar' } # Set up parameter values assistant_id = 'testString' @@ -588,6 +641,14 @@ def test_message_stateless_all_params(self): assert req_body['context'] == message_context_stateless_model assert req_body['user_id'] == 'testString' + def test_message_stateless_all_params_with_retries(self): + # Enable retries and run test_message_stateless_all_params. + _service.enable_retries() + self.test_message_stateless_all_params() + + # Disable retries and run test_message_stateless_all_params. + _service.disable_retries() + self.test_message_stateless_all_params() @responses.activate def test_message_stateless_required_params(self): @@ -595,8 +656,8 @@ def test_message_stateless_required_params(self): test_message_stateless_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + url = preprocess_url('/v2/assistants/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -616,6 +677,14 @@ def test_message_stateless_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_message_stateless_required_params_with_retries(self): + # Enable retries and run test_message_stateless_required_params. + _service.enable_retries() + self.test_message_stateless_required_params() + + # Disable retries and run test_message_stateless_required_params. + _service.disable_retries() + self.test_message_stateless_required_params() @responses.activate def test_message_stateless_value_error(self): @@ -623,8 +692,8 @@ def test_message_stateless_value_error(self): test_message_stateless_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}' + url = preprocess_url('/v2/assistants/testString/message') + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -644,6 +713,14 @@ def test_message_stateless_value_error(self): _service.message_stateless(**req_copy) + def test_message_stateless_value_error_with_retries(self): + # Enable retries and run test_message_stateless_value_error. + _service.enable_retries() + self.test_message_stateless_value_error() + + # Disable retries and run test_message_stateless_value_error. + _service.disable_retries() + self.test_message_stateless_value_error() # endregion ############################################################################## @@ -660,25 +737,14 @@ class TestBulkClassify(): Test Class for bulk_classify """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_bulk_classify_all_params(self): """ bulk_classify() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -707,6 +773,14 @@ def test_bulk_classify_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['input'] == [bulk_classify_utterance_model] + def test_bulk_classify_all_params_with_retries(self): + # Enable retries and run test_bulk_classify_all_params. + _service.enable_retries() + self.test_bulk_classify_all_params() + + # Disable retries and run test_bulk_classify_all_params. + _service.disable_retries() + self.test_bulk_classify_all_params() @responses.activate def test_bulk_classify_required_params(self): @@ -714,8 +788,8 @@ def test_bulk_classify_required_params(self): test_bulk_classify_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -735,6 +809,14 @@ def test_bulk_classify_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_bulk_classify_required_params_with_retries(self): + # Enable retries and run test_bulk_classify_required_params. + _service.enable_retries() + self.test_bulk_classify_required_params() + + # Disable retries and run test_bulk_classify_required_params. + _service.disable_retries() + self.test_bulk_classify_required_params() @responses.activate def test_bulk_classify_value_error(self): @@ -742,8 +824,8 @@ def test_bulk_classify_value_error(self): test_bulk_classify_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -763,6 +845,14 @@ def test_bulk_classify_value_error(self): _service.bulk_classify(**req_copy) + def test_bulk_classify_value_error_with_retries(self): + # Enable retries and run test_bulk_classify_value_error. + _service.enable_retries() + self.test_bulk_classify_value_error() + + # Disable retries and run test_bulk_classify_value_error. + _service.disable_retries() + self.test_bulk_classify_value_error() # endregion ############################################################################## @@ -779,25 +869,14 @@ class TestListLogs(): Test Class for list_logs """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_logs_all_params(self): """ list_logs() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -832,6 +911,14 @@ def test_list_logs_all_params(self): assert 'page_limit={}'.format(page_limit) in query_string assert 'cursor={}'.format(cursor) in query_string + def test_list_logs_all_params_with_retries(self): + # Enable retries and run test_list_logs_all_params. + _service.enable_retries() + self.test_list_logs_all_params() + + # Disable retries and run test_list_logs_all_params. + _service.disable_retries() + self.test_list_logs_all_params() @responses.activate def test_list_logs_required_params(self): @@ -839,8 +926,8 @@ def test_list_logs_required_params(self): test_list_logs_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -860,6 +947,14 @@ def test_list_logs_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_logs_required_params_with_retries(self): + # Enable retries and run test_list_logs_required_params. + _service.enable_retries() + self.test_list_logs_required_params() + + # Disable retries and run test_list_logs_required_params. + _service.disable_retries() + self.test_list_logs_required_params() @responses.activate def test_list_logs_value_error(self): @@ -867,8 +962,8 @@ def test_list_logs_value_error(self): test_list_logs_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "metadata": {"mapKey": "anyValue"}, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state"}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -888,6 +983,14 @@ def test_list_logs_value_error(self): _service.list_logs(**req_copy) + def test_list_logs_value_error_with_retries(self): + # Enable retries and run test_list_logs_value_error. + _service.enable_retries() + self.test_list_logs_value_error() + + # Disable retries and run test_list_logs_value_error. + _service.disable_retries() + self.test_list_logs_value_error() # endregion ############################################################################## @@ -904,24 +1007,13 @@ class TestDeleteUserData(): Test Class for delete_user_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_user_data_all_params(self): """ delete_user_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/user_data') + url = preprocess_url('/v2/user_data') responses.add(responses.DELETE, url, status=202) @@ -943,6 +1035,14 @@ def test_delete_user_data_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string + def test_delete_user_data_all_params_with_retries(self): + # Enable retries and run test_delete_user_data_all_params. + _service.enable_retries() + self.test_delete_user_data_all_params() + + # Disable retries and run test_delete_user_data_all_params. + _service.disable_retries() + self.test_delete_user_data_all_params() @responses.activate def test_delete_user_data_value_error(self): @@ -950,7 +1050,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/user_data') + url = preprocess_url('/v2/user_data') responses.add(responses.DELETE, url, status=202) @@ -968,6 +1068,14 @@ def test_delete_user_data_value_error(self): _service.delete_user_data(**req_copy) + def test_delete_user_data_value_error_with_retries(self): + # Enable retries and run test_delete_user_data_value_error. + _service.enable_retries() + self.test_delete_user_data_value_error() + + # Disable retries and run test_delete_user_data_value_error. + _service.disable_retries() + self.test_delete_user_data_value_error() # endregion ############################################################################## @@ -1067,7 +1175,6 @@ def test_bulk_classify_output_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -1157,7 +1264,6 @@ def test_bulk_classify_response_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] @@ -1510,12 +1616,15 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -1534,6 +1643,7 @@ def test_dialog_node_output_options_element_serialization(self): message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue @@ -1619,12 +1729,15 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -1643,6 +1756,7 @@ def test_dialog_node_output_options_element_value_serialization(self): message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model # Construct a json representation of a DialogNodeOutputOptionsElementValue model @@ -1664,36 +1778,36 @@ def test_dialog_node_output_options_element_value_serialization(self): dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json -class TestModel_DialogNodesVisited(): +class TestModel_DialogNodeVisited(): """ - Test Class for DialogNodesVisited + Test Class for DialogNodeVisited """ - def test_dialog_nodes_visited_serialization(self): + def test_dialog_node_visited_serialization(self): """ - Test serialization/deserialization for DialogNodesVisited + Test serialization/deserialization for DialogNodeVisited """ - # Construct a json representation of a DialogNodesVisited model - dialog_nodes_visited_model_json = {} - dialog_nodes_visited_model_json['dialog_node'] = 'testString' - dialog_nodes_visited_model_json['title'] = 'testString' - dialog_nodes_visited_model_json['conditions'] = 'testString' + # Construct a json representation of a DialogNodeVisited model + dialog_node_visited_model_json = {} + dialog_node_visited_model_json['dialog_node'] = 'testString' + dialog_node_visited_model_json['title'] = 'testString' + dialog_node_visited_model_json['conditions'] = 'testString' - # Construct a model instance of DialogNodesVisited by calling from_dict on the json representation - dialog_nodes_visited_model = DialogNodesVisited.from_dict(dialog_nodes_visited_model_json) - assert dialog_nodes_visited_model != False + # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation + dialog_node_visited_model = DialogNodeVisited.from_dict(dialog_node_visited_model_json) + assert dialog_node_visited_model != False - # Construct a model instance of DialogNodesVisited by calling from_dict on the json representation - dialog_nodes_visited_model_dict = DialogNodesVisited.from_dict(dialog_nodes_visited_model_json).__dict__ - dialog_nodes_visited_model2 = DialogNodesVisited(**dialog_nodes_visited_model_dict) + # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation + dialog_node_visited_model_dict = DialogNodeVisited.from_dict(dialog_node_visited_model_json).__dict__ + dialog_node_visited_model2 = DialogNodeVisited(**dialog_node_visited_model_dict) # Verify the model instances are equivalent - assert dialog_nodes_visited_model == dialog_nodes_visited_model2 + assert dialog_node_visited_model == dialog_node_visited_model2 # Convert model instance back to dict and verify no loss of data - dialog_nodes_visited_model_json2 = dialog_nodes_visited_model.to_dict() - assert dialog_nodes_visited_model_json2 == dialog_nodes_visited_model_json + dialog_node_visited_model_json2 = dialog_node_visited_model.to_dict() + assert dialog_node_visited_model_json2 == dialog_node_visited_model_json class TestModel_DialogSuggestion(): """ @@ -1755,12 +1869,15 @@ def test_dialog_suggestion_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -1779,6 +1896,7 @@ def test_dialog_suggestion_serialization(self): message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model dialog_suggestion_value_model = {} # DialogSuggestionValue @@ -1865,12 +1983,15 @@ def test_dialog_suggestion_value_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -1889,6 +2010,7 @@ def test_dialog_suggestion_value_serialization(self): message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model # Construct a json representation of a DialogSuggestionValue model @@ -1970,12 +2092,15 @@ def test_log_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -1994,6 +2119,7 @@ def test_log_serialization(self): message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model message_context_global_system_model = {} # MessageContextGlobalSystem @@ -2004,6 +2130,7 @@ def test_log_serialization(self): message_context_global_system_model['reference_time'] = 'testString' message_context_global_system_model['session_start_time'] = 'testString' message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model @@ -2020,6 +2147,7 @@ def test_log_serialization(self): message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = {} + message_context_model['integrations'] = { 'foo': 'bar' } message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model @@ -2051,10 +2179,10 @@ def test_log_serialization(self): dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_nodes_visited_model = {} # DialogNodesVisited - dialog_nodes_visited_model['dialog_node'] = 'testString' - dialog_nodes_visited_model['title'] = 'testString' - dialog_nodes_visited_model['conditions'] = 'testString' + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' @@ -2067,7 +2195,7 @@ def test_log_serialization(self): dialog_log_message_model['source'] = log_message_source_model message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' @@ -2180,12 +2308,15 @@ def test_log_collection_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -2204,6 +2335,7 @@ def test_log_collection_serialization(self): message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model message_context_global_system_model = {} # MessageContextGlobalSystem @@ -2214,6 +2346,7 @@ def test_log_collection_serialization(self): message_context_global_system_model['reference_time'] = 'testString' message_context_global_system_model['session_start_time'] = 'testString' message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model @@ -2230,6 +2363,7 @@ def test_log_collection_serialization(self): message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = {} + message_context_model['integrations'] = { 'foo': 'bar' } message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model @@ -2261,10 +2395,10 @@ def test_log_collection_serialization(self): dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_nodes_visited_model = {} # DialogNodesVisited - dialog_nodes_visited_model['dialog_node'] = 'testString' - dialog_nodes_visited_model['title'] = 'testString' - dialog_nodes_visited_model['conditions'] = 'testString' + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' @@ -2277,7 +2411,7 @@ def test_log_collection_serialization(self): dialog_log_message_model['source'] = log_message_source_model message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' @@ -2390,6 +2524,7 @@ def test_message_context_serialization(self): message_context_global_system_model['reference_time'] = 'testString' message_context_global_system_model['session_start_time'] = 'testString' message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model @@ -2407,6 +2542,7 @@ def test_message_context_serialization(self): message_context_model_json = {} message_context_model_json['global'] = message_context_global_model message_context_model_json['skills'] = {} + message_context_model_json['integrations'] = { 'foo': 'bar' } # Construct a model instance of MessageContext by calling from_dict on the json representation message_context_model = MessageContext.from_dict(message_context_model_json) @@ -2443,6 +2579,7 @@ def test_message_context_global_serialization(self): message_context_global_system_model['reference_time'] = 'testString' message_context_global_system_model['session_start_time'] = 'testString' message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True # Construct a json representation of a MessageContextGlobal model message_context_global_model_json = {} @@ -2484,6 +2621,7 @@ def test_message_context_global_stateless_serialization(self): message_context_global_system_model['reference_time'] = 'testString' message_context_global_system_model['session_start_time'] = 'testString' message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True # Construct a json representation of a MessageContextGlobalStateless model message_context_global_stateless_model_json = {} @@ -2524,6 +2662,7 @@ def test_message_context_global_system_serialization(self): message_context_global_system_model_json['reference_time'] = 'testString' message_context_global_system_model_json['session_start_time'] = 'testString' message_context_global_system_model_json['state'] = 'testString' + message_context_global_system_model_json['skip_user_input'] = True # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) @@ -2636,6 +2775,7 @@ def test_message_context_stateless_serialization(self): message_context_global_system_model['reference_time'] = 'testString' message_context_global_system_model['session_start_time'] = 'testString' message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True message_context_global_stateless_model = {} # MessageContextGlobalStateless message_context_global_stateless_model['system'] = message_context_global_system_model @@ -2653,6 +2793,7 @@ def test_message_context_stateless_serialization(self): message_context_stateless_model_json = {} message_context_stateless_model_json['global'] = message_context_global_stateless_model message_context_stateless_model_json['skills'] = {} + message_context_stateless_model_json['integrations'] = { 'foo': 'bar' } # Construct a model instance of MessageContextStateless by calling from_dict on the json representation message_context_stateless_model = MessageContextStateless.from_dict(message_context_stateless_model_json) @@ -2729,12 +2870,15 @@ def test_message_input_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -2754,6 +2898,7 @@ def test_message_input_serialization(self): message_input_model_json['intents'] = [runtime_intent_model] message_input_model_json['entities'] = [runtime_entity_model] message_input_model_json['suggestion_id'] = 'testString' + message_input_model_json['attachments'] = [message_input_attachment_model] message_input_model_json['options'] = message_input_options_model # Construct a model instance of MessageInput by calling from_dict on the json representation @@ -2771,6 +2916,36 @@ def test_message_input_serialization(self): message_input_model_json2 = message_input_model.to_dict() assert message_input_model_json2 == message_input_model_json +class TestModel_MessageInputAttachment(): + """ + Test Class for MessageInputAttachment + """ + + def test_message_input_attachment_serialization(self): + """ + Test serialization/deserialization for MessageInputAttachment + """ + + # Construct a json representation of a MessageInputAttachment model + message_input_attachment_model_json = {} + message_input_attachment_model_json['url'] = 'testString' + message_input_attachment_model_json['media_type'] = 'testString' + + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) + assert message_input_attachment_model != False + + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ + message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) + + # Verify the model instances are equivalent + assert message_input_attachment_model == message_input_attachment_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_attachment_model_json2 = message_input_attachment_model.to_dict() + assert message_input_attachment_model_json2 == message_input_attachment_model_json + class TestModel_MessageInputOptions(): """ Test Class for MessageInputOptions @@ -2939,12 +3114,15 @@ def test_message_input_stateless_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -2962,6 +3140,7 @@ def test_message_input_stateless_serialization(self): message_input_stateless_model_json['intents'] = [runtime_intent_model] message_input_stateless_model_json['entities'] = [runtime_entity_model] message_input_stateless_model_json['suggestion_id'] = 'testString' + message_input_stateless_model_json['attachments'] = [message_input_attachment_model] message_input_stateless_model_json['options'] = message_input_options_stateless_model # Construct a model instance of MessageInputStateless by calling from_dict on the json representation @@ -3039,12 +3218,15 @@ def test_message_output_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -3063,6 +3245,7 @@ def test_message_output_serialization(self): message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue @@ -3090,10 +3273,10 @@ def test_message_output_serialization(self): dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_nodes_visited_model = {} # DialogNodesVisited - dialog_nodes_visited_model['dialog_node'] = 'testString' - dialog_nodes_visited_model['title'] = 'testString' - dialog_nodes_visited_model['conditions'] = 'testString' + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' @@ -3106,7 +3289,7 @@ def test_message_output_serialization(self): dialog_log_message_model['source'] = log_message_source_model message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' @@ -3153,10 +3336,10 @@ def test_message_output_debug_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_nodes_visited_model = {} # DialogNodesVisited - dialog_nodes_visited_model['dialog_node'] = 'testString' - dialog_nodes_visited_model['title'] = 'testString' - dialog_nodes_visited_model['conditions'] = 'testString' + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' @@ -3170,7 +3353,7 @@ def test_message_output_debug_serialization(self): # Construct a json representation of a MessageOutputDebug model message_output_debug_model_json = {} - message_output_debug_model_json['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model_json['log_messages'] = [dialog_log_message_model] message_output_debug_model_json['branch_exited'] = True message_output_debug_model_json['branch_exited_reason'] = 'completed' @@ -3281,12 +3464,15 @@ def test_message_request_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -3305,6 +3491,7 @@ def test_message_request_serialization(self): message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model message_context_global_system_model = {} # MessageContextGlobalSystem @@ -3315,6 +3502,7 @@ def test_message_request_serialization(self): message_context_global_system_model['reference_time'] = 'testString' message_context_global_system_model['session_start_time'] = 'testString' message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model @@ -3331,6 +3519,7 @@ def test_message_request_serialization(self): message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = {} + message_context_model['integrations'] = { 'foo': 'bar' } # Construct a json representation of a MessageRequest model message_request_model_json = {} @@ -3413,12 +3602,15 @@ def test_message_response_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -3437,6 +3629,7 @@ def test_message_response_serialization(self): message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue @@ -3464,10 +3657,10 @@ def test_message_response_serialization(self): dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_nodes_visited_model = {} # DialogNodesVisited - dialog_nodes_visited_model['dialog_node'] = 'testString' - dialog_nodes_visited_model['title'] = 'testString' - dialog_nodes_visited_model['conditions'] = 'testString' + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' @@ -3480,7 +3673,7 @@ def test_message_response_serialization(self): dialog_log_message_model['source'] = log_message_source_model message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' @@ -3507,6 +3700,7 @@ def test_message_response_serialization(self): message_context_global_system_model['reference_time'] = 'testString' message_context_global_system_model['session_start_time'] = 'testString' message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model @@ -3523,6 +3717,7 @@ def test_message_response_serialization(self): message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = {} + message_context_model['integrations'] = { 'foo': 'bar' } # Construct a json representation of a MessageResponse model message_response_model_json = {} @@ -3605,12 +3800,15 @@ def test_message_response_stateless_serialization(self): runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -3629,6 +3827,7 @@ def test_message_response_stateless_serialization(self): message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue @@ -3656,10 +3855,10 @@ def test_message_response_stateless_serialization(self): dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_nodes_visited_model = {} # DialogNodesVisited - dialog_nodes_visited_model['dialog_node'] = 'testString' - dialog_nodes_visited_model['title'] = 'testString' - dialog_nodes_visited_model['conditions'] = 'testString' + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' @@ -3672,7 +3871,7 @@ def test_message_response_stateless_serialization(self): dialog_log_message_model['source'] = log_message_source_model message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_nodes_visited_model] + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' @@ -3699,6 +3898,7 @@ def test_message_response_stateless_serialization(self): message_context_global_system_model['reference_time'] = 'testString' message_context_global_system_model['session_start_time'] = 'testString' message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True message_context_global_stateless_model = {} # MessageContextGlobalStateless message_context_global_stateless_model['system'] = message_context_global_system_model @@ -3715,6 +3915,7 @@ def test_message_response_stateless_serialization(self): message_context_stateless_model = {} # MessageContextStateless message_context_stateless_model['global'] = message_context_global_stateless_model message_context_stateless_model['skills'] = {} + message_context_stateless_model['integrations'] = { 'foo': 'bar' } # Construct a json representation of a MessageResponseStateless model message_response_stateless_model_json = {} @@ -3823,7 +4024,6 @@ def test_runtime_entity_serialization(self): runtime_entity_model_json['location'] = [38] runtime_entity_model_json['value'] = 'testString' runtime_entity_model_json['confidence'] = 72.5 - runtime_entity_model_json['metadata'] = {} runtime_entity_model_json['groups'] = [capture_group_model] runtime_entity_model_json['interpretation'] = runtime_entity_interpretation_model runtime_entity_model_json['alternatives'] = [runtime_entity_alternative_model] @@ -4292,6 +4492,46 @@ def test_log_message_source_step_serialization(self): log_message_source_step_model_json2 = log_message_source_step_model.to_dict() assert log_message_source_step_model_json2 == log_message_source_step_model_json +class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeAudio + """ + + def test_runtime_response_generic_runtime_response_type_audio_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeAudio + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeAudio model + runtime_response_generic_runtime_response_type_audio_model_json = {} + runtime_response_generic_runtime_response_type_audio_model_json['response_type'] = 'audio' + runtime_response_generic_runtime_response_type_audio_model_json['source'] = 'testString' + runtime_response_generic_runtime_response_type_audio_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_audio_model_json['description'] = 'testString' + runtime_response_generic_runtime_response_type_audio_model_json['channels'] = [response_generic_channel_model] + runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_audio_model_json['alt_text'] = 'testString' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_audio_model = RuntimeResponseGenericRuntimeResponseTypeAudio.from_dict(runtime_response_generic_runtime_response_type_audio_model_json) + assert runtime_response_generic_runtime_response_type_audio_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_audio_model_dict = RuntimeResponseGenericRuntimeResponseTypeAudio.from_dict(runtime_response_generic_runtime_response_type_audio_model_json).__dict__ + runtime_response_generic_runtime_response_type_audio_model2 = RuntimeResponseGenericRuntimeResponseTypeAudio(**runtime_response_generic_runtime_response_type_audio_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_audio_model == runtime_response_generic_runtime_response_type_audio_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_audio_model_json2 = runtime_response_generic_runtime_response_type_audio_model.to_dict() + assert runtime_response_generic_runtime_response_type_audio_model_json2 == runtime_response_generic_runtime_response_type_audio_model_json + class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer @@ -4384,6 +4624,45 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json +class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeIframe + """ + + def test_runtime_response_generic_runtime_response_type_iframe_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeIframe + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeIframe model + runtime_response_generic_runtime_response_type_iframe_model_json = {} + runtime_response_generic_runtime_response_type_iframe_model_json['response_type'] = 'iframe' + runtime_response_generic_runtime_response_type_iframe_model_json['source'] = 'testString' + runtime_response_generic_runtime_response_type_iframe_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_iframe_model_json['description'] = 'testString' + runtime_response_generic_runtime_response_type_iframe_model_json['image_url'] = 'testString' + runtime_response_generic_runtime_response_type_iframe_model_json['channels'] = [response_generic_channel_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeIframe by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_iframe_model = RuntimeResponseGenericRuntimeResponseTypeIframe.from_dict(runtime_response_generic_runtime_response_type_iframe_model_json) + assert runtime_response_generic_runtime_response_type_iframe_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeIframe by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_iframe_model_dict = RuntimeResponseGenericRuntimeResponseTypeIframe.from_dict(runtime_response_generic_runtime_response_type_iframe_model_json).__dict__ + runtime_response_generic_runtime_response_type_iframe_model2 = RuntimeResponseGenericRuntimeResponseTypeIframe(**runtime_response_generic_runtime_response_type_iframe_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_iframe_model == runtime_response_generic_runtime_response_type_iframe_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_iframe_model_json2 = runtime_response_generic_runtime_response_type_iframe_model.to_dict() + assert runtime_response_generic_runtime_response_type_iframe_model_json2 == runtime_response_generic_runtime_response_type_iframe_model_json + class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeImage @@ -4483,12 +4762,15 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -4507,6 +4789,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue @@ -4701,12 +4984,15 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['metadata'] = {} runtime_entity_model['groups'] = [capture_group_model] runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -4725,6 +5011,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_model['intents'] = [runtime_intent_model] message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] message_input_model['options'] = message_input_options_model dialog_suggestion_value_model = {} # DialogSuggestionValue @@ -4832,6 +5119,46 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati runtime_response_generic_runtime_response_type_user_defined_model_json2 = runtime_response_generic_runtime_response_type_user_defined_model.to_dict() assert runtime_response_generic_runtime_response_type_user_defined_model_json2 == runtime_response_generic_runtime_response_type_user_defined_model_json +class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeVideo + """ + + def test_runtime_response_generic_runtime_response_type_video_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeVideo + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeVideo model + runtime_response_generic_runtime_response_type_video_model_json = {} + runtime_response_generic_runtime_response_type_video_model_json['response_type'] = 'video' + runtime_response_generic_runtime_response_type_video_model_json['source'] = 'testString' + runtime_response_generic_runtime_response_type_video_model_json['title'] = 'testString' + runtime_response_generic_runtime_response_type_video_model_json['description'] = 'testString' + runtime_response_generic_runtime_response_type_video_model_json['channels'] = [response_generic_channel_model] + runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_video_model_json['alt_text'] = 'testString' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_video_model = RuntimeResponseGenericRuntimeResponseTypeVideo.from_dict(runtime_response_generic_runtime_response_type_video_model_json) + assert runtime_response_generic_runtime_response_type_video_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_video_model_dict = RuntimeResponseGenericRuntimeResponseTypeVideo.from_dict(runtime_response_generic_runtime_response_type_video_model_json).__dict__ + runtime_response_generic_runtime_response_type_video_model2 = RuntimeResponseGenericRuntimeResponseTypeVideo(**runtime_response_generic_runtime_response_type_video_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_video_model == runtime_response_generic_runtime_response_type_video_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_video_model_json2 = runtime_response_generic_runtime_response_type_video_model.to_dict() + assert runtime_response_generic_runtime_response_type_video_model_json2 == runtime_response_generic_runtime_response_type_video_model_json + # endregion ############################################################################## diff --git a/test/unit/test_compare_comply_v1.py b/test/unit/test_compare_comply_v1.py deleted file mode 100644 index 72c554bae..000000000 --- a/test/unit/test_compare_comply_v1.py +++ /dev/null @@ -1,4502 +0,0 @@ -# -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2021. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Unit Tests for CompareComplyV1 -""" - -from datetime import datetime, timezone -from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime -import inspect -import io -import json -import pytest -import re -import requests -import responses -import tempfile -import urllib -from ibm_watson.compare_comply_v1 import * - -version = 'testString' - -_service = CompareComplyV1( - authenticator=NoAuthAuthenticator(), - version=version - ) - -_base_url = 'https://api.us-south.compare-comply.watson.cloud.ibm.com' -_service.set_service_url(_base_url) - -############################################################################## -# Start of Service: HTMLConversion -############################################################################## -# region - -class TestConvertToHtml(): - """ - Test Class for convert_to_html - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_convert_to_html_all_params(self): - """ - convert_to_html() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/html_conversion') - mock_response = '{"num_pages": "num_pages", "author": "author", "publication_date": "publication_date", "title": "title", "html": "html"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - file_content_type = 'application/pdf' - model = 'contracts' - - # Invoke method - response = _service.convert_to_html( - file, - file_content_type=file_content_type, - model=model, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'model={}'.format(model) in query_string - - - @responses.activate - def test_convert_to_html_required_params(self): - """ - test_convert_to_html_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/html_conversion') - mock_response = '{"num_pages": "num_pages", "author": "author", "publication_date": "publication_date", "title": "title", "html": "html"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - - # Invoke method - response = _service.convert_to_html( - file, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_convert_to_html_value_error(self): - """ - test_convert_to_html_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/html_conversion') - mock_response = '{"num_pages": "num_pages", "author": "author", "publication_date": "publication_date", "title": "title", "html": "html"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "file": file, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.convert_to_html(**req_copy) - - - -# endregion -############################################################################## -# End of Service: HTMLConversion -############################################################################## - -############################################################################## -# Start of Service: ElementClassification -############################################################################## -# region - -class TestClassifyElements(): - """ - Test Class for classify_elements - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_classify_elements_all_params(self): - """ - classify_elements() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/element_classification') - mock_response = '{"document": {"title": "title", "html": "html", "hash": "hash", "label": "label"}, "model_id": "model_id", "model_version": "model_version", "elements": [{"location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "effective_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_amounts": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "termination_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_types": [{"confidence_level": "High", "text": "text", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "payment_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_currencies": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}], "document_structure": {"section_titles": [{"text": "text", "location": {"begin": 5, "end": 3}, "level": 5, "element_locations": [{"begin": 5, "end": 3}]}], "leading_sentences": [{"text": "text", "location": {"begin": 5, "end": 3}, "element_locations": [{"begin": 5, "end": 3}]}], "paragraphs": [{"location": {"begin": 5, "end": 3}}]}, "parties": [{"party": "party", "role": "role", "importance": "Primary", "addresses": [{"text": "text", "location": {"begin": 5, "end": 3}}], "contacts": [{"name": "name", "role": "role"}], "mentions": [{"text": "text", "location": {"begin": 5, "end": 3}}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - file_content_type = 'application/pdf' - model = 'contracts' - - # Invoke method - response = _service.classify_elements( - file, - file_content_type=file_content_type, - model=model, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'model={}'.format(model) in query_string - - - @responses.activate - def test_classify_elements_required_params(self): - """ - test_classify_elements_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/element_classification') - mock_response = '{"document": {"title": "title", "html": "html", "hash": "hash", "label": "label"}, "model_id": "model_id", "model_version": "model_version", "elements": [{"location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "effective_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_amounts": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "termination_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_types": [{"confidence_level": "High", "text": "text", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "payment_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_currencies": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}], "document_structure": {"section_titles": [{"text": "text", "location": {"begin": 5, "end": 3}, "level": 5, "element_locations": [{"begin": 5, "end": 3}]}], "leading_sentences": [{"text": "text", "location": {"begin": 5, "end": 3}, "element_locations": [{"begin": 5, "end": 3}]}], "paragraphs": [{"location": {"begin": 5, "end": 3}}]}, "parties": [{"party": "party", "role": "role", "importance": "Primary", "addresses": [{"text": "text", "location": {"begin": 5, "end": 3}}], "contacts": [{"name": "name", "role": "role"}], "mentions": [{"text": "text", "location": {"begin": 5, "end": 3}}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - - # Invoke method - response = _service.classify_elements( - file, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_classify_elements_value_error(self): - """ - test_classify_elements_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/element_classification') - mock_response = '{"document": {"title": "title", "html": "html", "hash": "hash", "label": "label"}, "model_id": "model_id", "model_version": "model_version", "elements": [{"location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "effective_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_amounts": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "termination_dates": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_types": [{"confidence_level": "High", "text": "text", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "payment_terms": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "interpretation": {"value": "value", "numeric_value": 13, "unit": "unit"}, "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "contract_currencies": [{"confidence_level": "High", "text": "text", "text_normalized": "text_normalized", "provenance_ids": ["provenance_ids"], "location": {"begin": 5, "end": 3}}], "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}], "document_structure": {"section_titles": [{"text": "text", "location": {"begin": 5, "end": 3}, "level": 5, "element_locations": [{"begin": 5, "end": 3}]}], "leading_sentences": [{"text": "text", "location": {"begin": 5, "end": 3}, "element_locations": [{"begin": 5, "end": 3}]}], "paragraphs": [{"location": {"begin": 5, "end": 3}}]}, "parties": [{"party": "party", "role": "role", "importance": "Primary", "addresses": [{"text": "text", "location": {"begin": 5, "end": 3}}], "contacts": [{"name": "name", "role": "role"}], "mentions": [{"text": "text", "location": {"begin": 5, "end": 3}}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "file": file, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.classify_elements(**req_copy) - - - -# endregion -############################################################################## -# End of Service: ElementClassification -############################################################################## - -############################################################################## -# Start of Service: Tables -############################################################################## -# region - -class TestExtractTables(): - """ - Test Class for extract_tables - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_extract_tables_all_params(self): - """ - extract_tables() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/tables') - mock_response = '{"document": {"html": "html", "title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - file_content_type = 'application/pdf' - model = 'contracts' - - # Invoke method - response = _service.extract_tables( - file, - file_content_type=file_content_type, - model=model, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'model={}'.format(model) in query_string - - - @responses.activate - def test_extract_tables_required_params(self): - """ - test_extract_tables_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/tables') - mock_response = '{"document": {"html": "html", "title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - - # Invoke method - response = _service.extract_tables( - file, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_extract_tables_value_error(self): - """ - test_extract_tables_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/tables') - mock_response = '{"document": {"html": "html", "title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "tables": [{"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"location": {"begin": 5, "end": 3}, "text": "text"}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "file": file, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.extract_tables(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Tables -############################################################################## - -############################################################################## -# Start of Service: Comparison -############################################################################## -# region - -class TestCompareDocuments(): - """ - Test Class for compare_documents - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_compare_documents_all_params(self): - """ - compare_documents() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/comparison') - mock_response = '{"model_id": "model_id", "model_version": "model_version", "documents": [{"title": "title", "html": "html", "hash": "hash", "label": "label"}], "aligned_elements": [{"element_pair": [{"document_label": "document_label", "text": "text", "location": {"begin": 5, "end": 3}, "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "identical_text": true, "provenance_ids": ["provenance_ids"], "significant_elements": true}], "unaligned_elements": [{"document_label": "document_label", "location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file_1 = io.BytesIO(b'This is a mock file.').getvalue() - file_2 = io.BytesIO(b'This is a mock file.').getvalue() - file_1_content_type = 'application/pdf' - file_2_content_type = 'application/pdf' - file_1_label = 'file_1' - file_2_label = 'file_2' - model = 'contracts' - - # Invoke method - response = _service.compare_documents( - file_1, - file_2, - file_1_content_type=file_1_content_type, - file_2_content_type=file_2_content_type, - file_1_label=file_1_label, - file_2_label=file_2_label, - model=model, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'file_1_label={}'.format(file_1_label) in query_string - assert 'file_2_label={}'.format(file_2_label) in query_string - assert 'model={}'.format(model) in query_string - - - @responses.activate - def test_compare_documents_required_params(self): - """ - test_compare_documents_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/comparison') - mock_response = '{"model_id": "model_id", "model_version": "model_version", "documents": [{"title": "title", "html": "html", "hash": "hash", "label": "label"}], "aligned_elements": [{"element_pair": [{"document_label": "document_label", "text": "text", "location": {"begin": 5, "end": 3}, "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "identical_text": true, "provenance_ids": ["provenance_ids"], "significant_elements": true}], "unaligned_elements": [{"document_label": "document_label", "location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file_1 = io.BytesIO(b'This is a mock file.').getvalue() - file_2 = io.BytesIO(b'This is a mock file.').getvalue() - - # Invoke method - response = _service.compare_documents( - file_1, - file_2, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_compare_documents_value_error(self): - """ - test_compare_documents_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/comparison') - mock_response = '{"model_id": "model_id", "model_version": "model_version", "documents": [{"title": "title", "html": "html", "hash": "hash", "label": "label"}], "aligned_elements": [{"element_pair": [{"document_label": "document_label", "text": "text", "location": {"begin": 5, "end": 3}, "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}], "identical_text": true, "provenance_ids": ["provenance_ids"], "significant_elements": true}], "unaligned_elements": [{"document_label": "document_label", "location": {"begin": 5, "end": 3}, "text": "text", "types": [{"label": {"nature": "nature", "party": "party"}}], "categories": [{"label": "Amendments"}], "attributes": [{"type": "Currency", "text": "text", "location": {"begin": 5, "end": 3}}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - file_1 = io.BytesIO(b'This is a mock file.').getvalue() - file_2 = io.BytesIO(b'This is a mock file.').getvalue() - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "file_1": file_1, - "file_2": file_2, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.compare_documents(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Comparison -############################################################################## - -############################################################################## -# Start of Service: Feedback -############################################################################## -# region - -class TestAddFeedback(): - """ - Test Class for add_feedback - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_add_feedback_all_params(self): - """ - add_feedback() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/feedback') - mock_response = '{"feedback_id": "feedback_id", "user_id": "user_id", "comment": "comment", "created": "2019-01-01T12:00:00.000Z", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ShortDoc model - short_doc_model = {} - short_doc_model['title'] = 'testString' - short_doc_model['hash'] = 'testString' - - # Construct a dict representation of a Location model - location_model = {} - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a dict representation of a Label model - label_model = {} - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - # Construct a dict representation of a TypeLabel model - type_label_model = {} - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] - type_label_model['modification'] = 'added' - - # Construct a dict representation of a Category model - category_model = {} - category_model['label'] = 'Amendments' - category_model['provenance_ids'] = ['testString'] - category_model['modification'] = 'added' - - # Construct a dict representation of a OriginalLabelsIn model - original_labels_in_model = {} - original_labels_in_model['types'] = [type_label_model] - original_labels_in_model['categories'] = [category_model] - - # Construct a dict representation of a UpdatedLabelsIn model - updated_labels_in_model = {} - updated_labels_in_model['types'] = [type_label_model] - updated_labels_in_model['categories'] = [category_model] - - # Construct a dict representation of a FeedbackDataInput model - feedback_data_input_model = {} - feedback_data_input_model['feedback_type'] = 'testString' - feedback_data_input_model['document'] = short_doc_model - feedback_data_input_model['model_id'] = 'testString' - feedback_data_input_model['model_version'] = 'testString' - feedback_data_input_model['location'] = location_model - feedback_data_input_model['text'] = 'testString' - feedback_data_input_model['original_labels'] = original_labels_in_model - feedback_data_input_model['updated_labels'] = updated_labels_in_model - - # Set up parameter values - feedback_data = feedback_data_input_model - user_id = 'testString' - comment = 'testString' - - # Invoke method - response = _service.add_feedback( - feedback_data, - user_id=user_id, - comment=comment, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['feedback_data'] == feedback_data_input_model - assert req_body['user_id'] == 'testString' - assert req_body['comment'] == 'testString' - - - @responses.activate - def test_add_feedback_value_error(self): - """ - test_add_feedback_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/feedback') - mock_response = '{"feedback_id": "feedback_id", "user_id": "user_id", "comment": "comment", "created": "2019-01-01T12:00:00.000Z", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ShortDoc model - short_doc_model = {} - short_doc_model['title'] = 'testString' - short_doc_model['hash'] = 'testString' - - # Construct a dict representation of a Location model - location_model = {} - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a dict representation of a Label model - label_model = {} - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - # Construct a dict representation of a TypeLabel model - type_label_model = {} - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] - type_label_model['modification'] = 'added' - - # Construct a dict representation of a Category model - category_model = {} - category_model['label'] = 'Amendments' - category_model['provenance_ids'] = ['testString'] - category_model['modification'] = 'added' - - # Construct a dict representation of a OriginalLabelsIn model - original_labels_in_model = {} - original_labels_in_model['types'] = [type_label_model] - original_labels_in_model['categories'] = [category_model] - - # Construct a dict representation of a UpdatedLabelsIn model - updated_labels_in_model = {} - updated_labels_in_model['types'] = [type_label_model] - updated_labels_in_model['categories'] = [category_model] - - # Construct a dict representation of a FeedbackDataInput model - feedback_data_input_model = {} - feedback_data_input_model['feedback_type'] = 'testString' - feedback_data_input_model['document'] = short_doc_model - feedback_data_input_model['model_id'] = 'testString' - feedback_data_input_model['model_version'] = 'testString' - feedback_data_input_model['location'] = location_model - feedback_data_input_model['text'] = 'testString' - feedback_data_input_model['original_labels'] = original_labels_in_model - feedback_data_input_model['updated_labels'] = updated_labels_in_model - - # Set up parameter values - feedback_data = feedback_data_input_model - user_id = 'testString' - comment = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "feedback_data": feedback_data, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.add_feedback(**req_copy) - - - -class TestListFeedback(): - """ - Test Class for list_feedback - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_list_feedback_all_params(self): - """ - list_feedback() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/feedback') - mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - feedback_type = 'testString' - document_title = 'testString' - model_id = 'testString' - model_version = 'testString' - category_removed = 'testString' - category_added = 'testString' - category_not_changed = 'testString' - type_removed = 'testString' - type_added = 'testString' - type_not_changed = 'testString' - page_limit = 100 - cursor = 'testString' - sort = 'testString' - include_total = True - - # Invoke method - response = _service.list_feedback( - feedback_type=feedback_type, - document_title=document_title, - model_id=model_id, - model_version=model_version, - category_removed=category_removed, - category_added=category_added, - category_not_changed=category_not_changed, - type_removed=type_removed, - type_added=type_added, - type_not_changed=type_not_changed, - page_limit=page_limit, - cursor=cursor, - sort=sort, - include_total=include_total, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'feedback_type={}'.format(feedback_type) in query_string - assert 'document_title={}'.format(document_title) in query_string - assert 'model_id={}'.format(model_id) in query_string - assert 'model_version={}'.format(model_version) in query_string - assert 'category_removed={}'.format(category_removed) in query_string - assert 'category_added={}'.format(category_added) in query_string - assert 'category_not_changed={}'.format(category_not_changed) in query_string - assert 'type_removed={}'.format(type_removed) in query_string - assert 'type_added={}'.format(type_added) in query_string - assert 'type_not_changed={}'.format(type_not_changed) in query_string - assert 'page_limit={}'.format(page_limit) in query_string - assert 'cursor={}'.format(cursor) in query_string - assert 'sort={}'.format(sort) in query_string - assert 'include_total={}'.format('true' if include_total else 'false') in query_string - - - @responses.activate - def test_list_feedback_required_params(self): - """ - test_list_feedback_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/feedback') - mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Invoke method - response = _service.list_feedback() - - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_list_feedback_value_error(self): - """ - test_list_feedback_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/feedback') - mock_response = '{"feedback": [{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_feedback(**req_copy) - - - -class TestGetFeedback(): - """ - Test Class for get_feedback - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_get_feedback_all_params(self): - """ - get_feedback() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/feedback/testString') - mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - feedback_id = 'testString' - model = 'contracts' - - # Invoke method - response = _service.get_feedback( - feedback_id, - model=model, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'model={}'.format(model) in query_string - - - @responses.activate - def test_get_feedback_required_params(self): - """ - test_get_feedback_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/feedback/testString') - mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - feedback_id = 'testString' - - # Invoke method - response = _service.get_feedback( - feedback_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_get_feedback_value_error(self): - """ - test_get_feedback_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/feedback/testString') - mock_response = '{"feedback_id": "feedback_id", "created": "2019-01-01T12:00:00.000Z", "comment": "comment", "feedback_data": {"feedback_type": "feedback_type", "document": {"title": "title", "hash": "hash"}, "model_id": "model_id", "model_version": "model_version", "location": {"begin": 5, "end": 3}, "text": "text", "original_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "updated_labels": {"types": [{"label": {"nature": "nature", "party": "party"}, "provenance_ids": ["provenance_ids"], "modification": "added"}], "categories": [{"label": "Amendments", "provenance_ids": ["provenance_ids"], "modification": "added"}]}, "pagination": {"refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor", "refresh_url": "refresh_url", "next_url": "next_url", "total": 5}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - feedback_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "feedback_id": feedback_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_feedback(**req_copy) - - - -class TestDeleteFeedback(): - """ - Test Class for delete_feedback - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_delete_feedback_all_params(self): - """ - delete_feedback() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/feedback/testString') - mock_response = '{"status": 6, "message": "message"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - feedback_id = 'testString' - model = 'contracts' - - # Invoke method - response = _service.delete_feedback( - feedback_id, - model=model, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'model={}'.format(model) in query_string - - - @responses.activate - def test_delete_feedback_required_params(self): - """ - test_delete_feedback_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/feedback/testString') - mock_response = '{"status": 6, "message": "message"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - feedback_id = 'testString' - - # Invoke method - response = _service.delete_feedback( - feedback_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_delete_feedback_value_error(self): - """ - test_delete_feedback_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/feedback/testString') - mock_response = '{"status": 6, "message": "message"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - feedback_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "feedback_id": feedback_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_feedback(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Feedback -############################################################################## - -############################################################################## -# Start of Service: Batches -############################################################################## -# region - -class TestCreateBatch(): - """ - Test Class for create_batch - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_create_batch_all_params(self): - """ - create_batch() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/batches') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - function = 'html_conversion' - input_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() - input_bucket_location = 'testString' - input_bucket_name = 'testString' - output_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() - output_bucket_location = 'testString' - output_bucket_name = 'testString' - model = 'contracts' - - # Invoke method - response = _service.create_batch( - function, - input_credentials_file, - input_bucket_location, - input_bucket_name, - output_credentials_file, - output_bucket_location, - output_bucket_name, - model=model, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'function={}'.format(function) in query_string - assert 'model={}'.format(model) in query_string - - - @responses.activate - def test_create_batch_required_params(self): - """ - test_create_batch_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/batches') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - function = 'html_conversion' - input_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() - input_bucket_location = 'testString' - input_bucket_name = 'testString' - output_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() - output_bucket_location = 'testString' - output_bucket_name = 'testString' - - # Invoke method - response = _service.create_batch( - function, - input_credentials_file, - input_bucket_location, - input_bucket_name, - output_credentials_file, - output_bucket_location, - output_bucket_name, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'function={}'.format(function) in query_string - - - @responses.activate - def test_create_batch_value_error(self): - """ - test_create_batch_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/batches') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - function = 'html_conversion' - input_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() - input_bucket_location = 'testString' - input_bucket_name = 'testString' - output_credentials_file = io.BytesIO(b'This is a mock file.').getvalue() - output_bucket_location = 'testString' - output_bucket_name = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "function": function, - "input_credentials_file": input_credentials_file, - "input_bucket_location": input_bucket_location, - "input_bucket_name": input_bucket_name, - "output_credentials_file": output_credentials_file, - "output_bucket_location": output_bucket_location, - "output_bucket_name": output_bucket_name, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_batch(**req_copy) - - - -class TestListBatches(): - """ - Test Class for list_batches - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_list_batches_all_params(self): - """ - list_batches() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/batches') - mock_response = '{"batches": [{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Invoke method - response = _service.list_batches() - - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_list_batches_value_error(self): - """ - test_list_batches_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/batches') - mock_response = '{"batches": [{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_batches(**req_copy) - - - -class TestGetBatch(): - """ - Test Class for get_batch - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_get_batch_all_params(self): - """ - get_batch() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/batches/testString') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - batch_id = 'testString' - - # Invoke method - response = _service.get_batch( - batch_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_get_batch_value_error(self): - """ - test_get_batch_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/batches/testString') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - batch_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "batch_id": batch_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_batch(**req_copy) - - - -class TestUpdateBatch(): - """ - Test Class for update_batch - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_update_batch_all_params(self): - """ - update_batch() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/batches/testString') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - batch_id = 'testString' - action = 'rescan' - model = 'contracts' - - # Invoke method - response = _service.update_batch( - batch_id, - action, - model=model, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'action={}'.format(action) in query_string - assert 'model={}'.format(model) in query_string - - - @responses.activate - def test_update_batch_required_params(self): - """ - test_update_batch_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/batches/testString') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - batch_id = 'testString' - action = 'rescan' - - # Invoke method - response = _service.update_batch( - batch_id, - action, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'action={}'.format(action) in query_string - - - @responses.activate - def test_update_batch_value_error(self): - """ - test_update_batch_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/batches/testString') - mock_response = '{"function": "element_classification", "input_bucket_location": "input_bucket_location", "input_bucket_name": "input_bucket_name", "output_bucket_location": "output_bucket_location", "output_bucket_name": "output_bucket_name", "batch_id": "batch_id", "document_counts": {"total": 5, "pending": 7, "successful": 10, "failed": 6}, "status": "status", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - batch_id = 'testString' - action = 'rescan' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "batch_id": batch_id, - "action": action, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_batch(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Batches -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region -class TestModel_Address(): - """ - Test Class for Address - """ - - def test_address_serialization(self): - """ - Test serialization/deserialization for Address - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a Address model - address_model_json = {} - address_model_json['text'] = 'testString' - address_model_json['location'] = location_model - - # Construct a model instance of Address by calling from_dict on the json representation - address_model = Address.from_dict(address_model_json) - assert address_model != False - - # Construct a model instance of Address by calling from_dict on the json representation - address_model_dict = Address.from_dict(address_model_json).__dict__ - address_model2 = Address(**address_model_dict) - - # Verify the model instances are equivalent - assert address_model == address_model2 - - # Convert model instance back to dict and verify no loss of data - address_model_json2 = address_model.to_dict() - assert address_model_json2 == address_model_json - -class TestModel_AlignedElement(): - """ - Test Class for AlignedElement - """ - - def test_aligned_element_serialization(self): - """ - Test serialization/deserialization for AlignedElement - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - type_label_comparison_model = {} # TypeLabelComparison - type_label_comparison_model['label'] = label_model - - category_comparison_model = {} # CategoryComparison - category_comparison_model['label'] = 'Amendments' - - attribute_model = {} # Attribute - attribute_model['type'] = 'Currency' - attribute_model['text'] = 'testString' - attribute_model['location'] = location_model - - element_pair_model = {} # ElementPair - element_pair_model['document_label'] = 'testString' - element_pair_model['text'] = 'testString' - element_pair_model['location'] = location_model - element_pair_model['types'] = [type_label_comparison_model] - element_pair_model['categories'] = [category_comparison_model] - element_pair_model['attributes'] = [attribute_model] - - # Construct a json representation of a AlignedElement model - aligned_element_model_json = {} - aligned_element_model_json['element_pair'] = [element_pair_model] - aligned_element_model_json['identical_text'] = True - aligned_element_model_json['provenance_ids'] = ['testString'] - aligned_element_model_json['significant_elements'] = True - - # Construct a model instance of AlignedElement by calling from_dict on the json representation - aligned_element_model = AlignedElement.from_dict(aligned_element_model_json) - assert aligned_element_model != False - - # Construct a model instance of AlignedElement by calling from_dict on the json representation - aligned_element_model_dict = AlignedElement.from_dict(aligned_element_model_json).__dict__ - aligned_element_model2 = AlignedElement(**aligned_element_model_dict) - - # Verify the model instances are equivalent - assert aligned_element_model == aligned_element_model2 - - # Convert model instance back to dict and verify no loss of data - aligned_element_model_json2 = aligned_element_model.to_dict() - assert aligned_element_model_json2 == aligned_element_model_json - -class TestModel_Attribute(): - """ - Test Class for Attribute - """ - - def test_attribute_serialization(self): - """ - Test serialization/deserialization for Attribute - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a Attribute model - attribute_model_json = {} - attribute_model_json['type'] = 'Currency' - attribute_model_json['text'] = 'testString' - attribute_model_json['location'] = location_model - - # Construct a model instance of Attribute by calling from_dict on the json representation - attribute_model = Attribute.from_dict(attribute_model_json) - assert attribute_model != False - - # Construct a model instance of Attribute by calling from_dict on the json representation - attribute_model_dict = Attribute.from_dict(attribute_model_json).__dict__ - attribute_model2 = Attribute(**attribute_model_dict) - - # Verify the model instances are equivalent - assert attribute_model == attribute_model2 - - # Convert model instance back to dict and verify no loss of data - attribute_model_json2 = attribute_model.to_dict() - assert attribute_model_json2 == attribute_model_json - -class TestModel_BatchStatus(): - """ - Test Class for BatchStatus - """ - - def test_batch_status_serialization(self): - """ - Test serialization/deserialization for BatchStatus - """ - - # Construct dict forms of any model objects needed in order to build this model. - - doc_counts_model = {} # DocCounts - doc_counts_model['total'] = 38 - doc_counts_model['pending'] = 38 - doc_counts_model['successful'] = 38 - doc_counts_model['failed'] = 38 - - # Construct a json representation of a BatchStatus model - batch_status_model_json = {} - batch_status_model_json['function'] = 'element_classification' - batch_status_model_json['input_bucket_location'] = 'testString' - batch_status_model_json['input_bucket_name'] = 'testString' - batch_status_model_json['output_bucket_location'] = 'testString' - batch_status_model_json['output_bucket_name'] = 'testString' - batch_status_model_json['batch_id'] = 'testString' - batch_status_model_json['document_counts'] = doc_counts_model - batch_status_model_json['status'] = 'testString' - batch_status_model_json['created'] = "2019-01-01T12:00:00Z" - batch_status_model_json['updated'] = "2019-01-01T12:00:00Z" - - # Construct a model instance of BatchStatus by calling from_dict on the json representation - batch_status_model = BatchStatus.from_dict(batch_status_model_json) - assert batch_status_model != False - - # Construct a model instance of BatchStatus by calling from_dict on the json representation - batch_status_model_dict = BatchStatus.from_dict(batch_status_model_json).__dict__ - batch_status_model2 = BatchStatus(**batch_status_model_dict) - - # Verify the model instances are equivalent - assert batch_status_model == batch_status_model2 - - # Convert model instance back to dict and verify no loss of data - batch_status_model_json2 = batch_status_model.to_dict() - assert batch_status_model_json2 == batch_status_model_json - -class TestModel_Batches(): - """ - Test Class for Batches - """ - - def test_batches_serialization(self): - """ - Test serialization/deserialization for Batches - """ - - # Construct dict forms of any model objects needed in order to build this model. - - doc_counts_model = {} # DocCounts - doc_counts_model['total'] = 38 - doc_counts_model['pending'] = 38 - doc_counts_model['successful'] = 38 - doc_counts_model['failed'] = 38 - - batch_status_model = {} # BatchStatus - batch_status_model['function'] = 'element_classification' - batch_status_model['input_bucket_location'] = 'testString' - batch_status_model['input_bucket_name'] = 'testString' - batch_status_model['output_bucket_location'] = 'testString' - batch_status_model['output_bucket_name'] = 'testString' - batch_status_model['batch_id'] = 'testString' - batch_status_model['document_counts'] = doc_counts_model - batch_status_model['status'] = 'testString' - batch_status_model['created'] = "2019-01-01T12:00:00Z" - batch_status_model['updated'] = "2019-01-01T12:00:00Z" - - # Construct a json representation of a Batches model - batches_model_json = {} - batches_model_json['batches'] = [batch_status_model] - - # Construct a model instance of Batches by calling from_dict on the json representation - batches_model = Batches.from_dict(batches_model_json) - assert batches_model != False - - # Construct a model instance of Batches by calling from_dict on the json representation - batches_model_dict = Batches.from_dict(batches_model_json).__dict__ - batches_model2 = Batches(**batches_model_dict) - - # Verify the model instances are equivalent - assert batches_model == batches_model2 - - # Convert model instance back to dict and verify no loss of data - batches_model_json2 = batches_model.to_dict() - assert batches_model_json2 == batches_model_json - -class TestModel_BodyCells(): - """ - Test Class for BodyCells - """ - - def test_body_cells_serialization(self): - """ - Test serialization/deserialization for BodyCells - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - attribute_model = {} # Attribute - attribute_model['type'] = 'Currency' - attribute_model['text'] = 'testString' - attribute_model['location'] = location_model - - # Construct a json representation of a BodyCells model - body_cells_model_json = {} - body_cells_model_json['cell_id'] = 'testString' - body_cells_model_json['location'] = location_model - body_cells_model_json['text'] = 'testString' - body_cells_model_json['row_index_begin'] = 26 - body_cells_model_json['row_index_end'] = 26 - body_cells_model_json['column_index_begin'] = 26 - body_cells_model_json['column_index_end'] = 26 - body_cells_model_json['row_header_ids'] = ['testString'] - body_cells_model_json['row_header_texts'] = ['testString'] - body_cells_model_json['row_header_texts_normalized'] = ['testString'] - body_cells_model_json['column_header_ids'] = ['testString'] - body_cells_model_json['column_header_texts'] = ['testString'] - body_cells_model_json['column_header_texts_normalized'] = ['testString'] - body_cells_model_json['attributes'] = [attribute_model] - - # Construct a model instance of BodyCells by calling from_dict on the json representation - body_cells_model = BodyCells.from_dict(body_cells_model_json) - assert body_cells_model != False - - # Construct a model instance of BodyCells by calling from_dict on the json representation - body_cells_model_dict = BodyCells.from_dict(body_cells_model_json).__dict__ - body_cells_model2 = BodyCells(**body_cells_model_dict) - - # Verify the model instances are equivalent - assert body_cells_model == body_cells_model2 - - # Convert model instance back to dict and verify no loss of data - body_cells_model_json2 = body_cells_model.to_dict() - assert body_cells_model_json2 == body_cells_model_json - -class TestModel_Category(): - """ - Test Class for Category - """ - - def test_category_serialization(self): - """ - Test serialization/deserialization for Category - """ - - # Construct a json representation of a Category model - category_model_json = {} - category_model_json['label'] = 'Amendments' - category_model_json['provenance_ids'] = ['testString'] - category_model_json['modification'] = 'added' - - # Construct a model instance of Category by calling from_dict on the json representation - category_model = Category.from_dict(category_model_json) - assert category_model != False - - # Construct a model instance of Category by calling from_dict on the json representation - category_model_dict = Category.from_dict(category_model_json).__dict__ - category_model2 = Category(**category_model_dict) - - # Verify the model instances are equivalent - assert category_model == category_model2 - - # Convert model instance back to dict and verify no loss of data - category_model_json2 = category_model.to_dict() - assert category_model_json2 == category_model_json - -class TestModel_CategoryComparison(): - """ - Test Class for CategoryComparison - """ - - def test_category_comparison_serialization(self): - """ - Test serialization/deserialization for CategoryComparison - """ - - # Construct a json representation of a CategoryComparison model - category_comparison_model_json = {} - category_comparison_model_json['label'] = 'Amendments' - - # Construct a model instance of CategoryComparison by calling from_dict on the json representation - category_comparison_model = CategoryComparison.from_dict(category_comparison_model_json) - assert category_comparison_model != False - - # Construct a model instance of CategoryComparison by calling from_dict on the json representation - category_comparison_model_dict = CategoryComparison.from_dict(category_comparison_model_json).__dict__ - category_comparison_model2 = CategoryComparison(**category_comparison_model_dict) - - # Verify the model instances are equivalent - assert category_comparison_model == category_comparison_model2 - - # Convert model instance back to dict and verify no loss of data - category_comparison_model_json2 = category_comparison_model.to_dict() - assert category_comparison_model_json2 == category_comparison_model_json - -class TestModel_ClassifyReturn(): - """ - Test Class for ClassifyReturn - """ - - def test_classify_return_serialization(self): - """ - Test serialization/deserialization for ClassifyReturn - """ - - # Construct dict forms of any model objects needed in order to build this model. - - document_model = {} # Document - document_model['title'] = 'IBM DC QDRO Guidelines' - document_model['html'] = '\n\n ...' - document_model['hash'] = '91edc2ff254d29f7a4922635ad47276a' - document_model['label'] = 'testString' - - location_model = {} # Location - location_model['begin'] = 6958 - location_model['end'] = 7171 - - label_model = {} # Label - label_model['nature'] = 'Obligation' - label_model['party'] = 'You' - - type_label_model = {} # TypeLabel - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['Nlu0ogWAEGms4vjhhzpMv3iXhm8b8fBqMBNtT/bXH8JI=', 'Pqjd5I+s/Fdpx2NbIwCRMtyPLV8n1Hq+wINPGAr/PNtcRCSdxR9P7RLf1/eXPKQYI'] - type_label_model['modification'] = 'added' - - category_model = {} # Category - category_model['label'] = 'Amendments' - category_model['provenance_ids'] = ['testString'] - category_model['modification'] = 'added' - - attribute_model = {} # Attribute - attribute_model['type'] = 'Currency' - attribute_model['text'] = 'testString' - attribute_model['location'] = location_model - - element_model = {} # Element - element_model['location'] = location_model - element_model['text'] = 'In the following sections, you will find the Plan\'s processing guidelines for determining the qualification of an order and some discussion of plan features and issues that should be considered in drafting a QDRO.' - element_model['types'] = [type_label_model] - element_model['categories'] = [category_model] - element_model['attributes'] = [attribute_model] - - effective_dates_model = {} # EffectiveDates - effective_dates_model['confidence_level'] = 'High' - effective_dates_model['text'] = 'testString' - effective_dates_model['text_normalized'] = 'testString' - effective_dates_model['provenance_ids'] = ['testString'] - effective_dates_model['location'] = location_model - - interpretation_model = {} # Interpretation - interpretation_model['value'] = 'testString' - interpretation_model['numeric_value'] = 72.5 - interpretation_model['unit'] = 'testString' - - contract_amts_model = {} # ContractAmts - contract_amts_model['confidence_level'] = 'High' - contract_amts_model['text'] = 'testString' - contract_amts_model['text_normalized'] = 'testString' - contract_amts_model['interpretation'] = interpretation_model - contract_amts_model['provenance_ids'] = ['testString'] - contract_amts_model['location'] = location_model - - termination_dates_model = {} # TerminationDates - termination_dates_model['confidence_level'] = 'High' - termination_dates_model['text'] = 'testString' - termination_dates_model['text_normalized'] = 'testString' - termination_dates_model['provenance_ids'] = ['testString'] - termination_dates_model['location'] = location_model - - contract_types_model = {} # ContractTypes - contract_types_model['confidence_level'] = 'High' - contract_types_model['text'] = 'testString' - contract_types_model['provenance_ids'] = ['testString'] - contract_types_model['location'] = location_model - - contract_terms_model = {} # ContractTerms - contract_terms_model['confidence_level'] = 'High' - contract_terms_model['text'] = 'testString' - contract_terms_model['text_normalized'] = 'testString' - contract_terms_model['interpretation'] = interpretation_model - contract_terms_model['provenance_ids'] = ['testString'] - contract_terms_model['location'] = location_model - - payment_terms_model = {} # PaymentTerms - payment_terms_model['confidence_level'] = 'High' - payment_terms_model['text'] = 'testString' - payment_terms_model['text_normalized'] = 'testString' - payment_terms_model['interpretation'] = interpretation_model - payment_terms_model['provenance_ids'] = ['testString'] - payment_terms_model['location'] = location_model - - contract_currencies_model = {} # ContractCurrencies - contract_currencies_model['confidence_level'] = 'High' - contract_currencies_model['text'] = 'testString' - contract_currencies_model['text_normalized'] = 'testString' - contract_currencies_model['provenance_ids'] = ['testString'] - contract_currencies_model['location'] = location_model - - section_title_model = {} # SectionTitle - section_title_model['text'] = 'Buyer will pay Supplier certain amounts for the Developed Works and other Services and Deliverables as described below: ' - section_title_model['location'] = location_model - - table_title_model = {} # TableTitle - table_title_model['location'] = location_model - table_title_model['text'] = 'Roles and responsibilities' - - table_headers_model = {} # TableHeaders - table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = { 'foo': 'bar' } - table_headers_model['text'] = 'testString' - table_headers_model['row_index_begin'] = 26 - table_headers_model['row_index_end'] = 26 - table_headers_model['column_index_begin'] = 26 - table_headers_model['column_index_end'] = 26 - - row_headers_model = {} # RowHeaders - row_headers_model['cell_id'] = 'testString' - row_headers_model['location'] = location_model - row_headers_model['text'] = 'testString' - row_headers_model['text_normalized'] = 'testString' - row_headers_model['row_index_begin'] = 26 - row_headers_model['row_index_end'] = 26 - row_headers_model['column_index_begin'] = 26 - row_headers_model['column_index_end'] = 26 - - column_headers_model = {} # ColumnHeaders - column_headers_model['cell_id'] = 'colHeader-23489-23496' - column_headers_model['location'] = { 'foo': 'bar' } - column_headers_model['text'] = 'Res Ref' - column_headers_model['text_normalized'] = 'Res Ref' - column_headers_model['row_index_begin'] = 0 - column_headers_model['row_index_end'] = 0 - column_headers_model['column_index_begin'] = 0 - column_headers_model['column_index_end'] = 0 - - body_cells_model = {} # BodyCells - body_cells_model['cell_id'] = 'bodyCell-24768-24777' - body_cells_model['location'] = location_model - body_cells_model['text'] = 'RBS-RES01' - body_cells_model['row_index_begin'] = 1 - body_cells_model['row_index_end'] = 1 - body_cells_model['column_index_begin'] = 0 - body_cells_model['column_index_end'] = 0 - body_cells_model['row_header_ids'] = [] - body_cells_model['row_header_texts'] = [] - body_cells_model['row_header_texts_normalized'] = [] - body_cells_model['column_header_ids'] = ['colHeader-23489-23496'] - body_cells_model['column_header_texts'] = ['Res Ref'] - body_cells_model['column_header_texts_normalized'] = ['Res Ref'] - body_cells_model['attributes'] = [attribute_model] - - contexts_model = {} # Contexts - contexts_model['text'] = 'testString' - contexts_model['location'] = location_model - - key_model = {} # Key - key_model['cell_id'] = 'testString' - key_model['location'] = location_model - key_model['text'] = 'testString' - - value_model = {} # Value - value_model['cell_id'] = 'testString' - value_model['location'] = location_model - value_model['text'] = 'testString' - - key_value_pair_model = {} # KeyValuePair - key_value_pair_model['key'] = key_model - key_value_pair_model['value'] = [value_model] - - tables_model = {} # Tables - tables_model['location'] = location_model - tables_model['text'] = 'Res Ref Role Type Estimated Days Rate (per da y) Estimated Total RBS-RES01 CRM Developer 1 (Junior Technical Consultant) 55 £600 £33,000 RBS-RES02 CRM Developer 2 (Junior Technical Consultant) 77 £600 £46,200 RBS-RES03 Specialist Tester (Test Lead) 65 £550 £35,750 Totals £114,950 ' - tables_model['section_title'] = section_title_model - tables_model['title'] = table_title_model - tables_model['table_headers'] = [table_headers_model] - tables_model['row_headers'] = [row_headers_model] - tables_model['column_headers'] = [column_headers_model] - tables_model['body_cells'] = [body_cells_model] - tables_model['contexts'] = [contexts_model] - tables_model['key_value_pairs'] = [key_value_pair_model] - - element_locations_model = {} # ElementLocations - element_locations_model['begin'] = 4174 - element_locations_model['end'] = 4277 - - section_titles_model = {} # SectionTitles - section_titles_model['text'] = '1.0 Scope of Work Summary' - section_titles_model['location'] = location_model - section_titles_model['level'] = 1 - section_titles_model['element_locations'] = [element_locations_model] - - leading_sentence_model = {} # LeadingSentence - leading_sentence_model['text'] = 'testString' - leading_sentence_model['location'] = location_model - leading_sentence_model['element_locations'] = [element_locations_model] - - paragraphs_model = {} # Paragraphs - paragraphs_model['location'] = location_model - - doc_structure_model = {} # DocStructure - doc_structure_model['section_titles'] = [section_titles_model] - doc_structure_model['leading_sentences'] = [leading_sentence_model] - doc_structure_model['paragraphs'] = [paragraphs_model] - - address_model = {} # Address - address_model['text'] = 'testString' - address_model['location'] = location_model - - contact_model = {} # Contact - contact_model['name'] = 'testString' - contact_model['role'] = 'testString' - - mention_model = {} # Mention - mention_model['text'] = 'testString' - mention_model['location'] = location_model - - parties_model = {} # Parties - parties_model['party'] = 'IBM' - parties_model['role'] = 'Unknown' - parties_model['importance'] = 'Primary' - parties_model['addresses'] = [address_model] - parties_model['contacts'] = [contact_model] - parties_model['mentions'] = [mention_model] - - # Construct a json representation of a ClassifyReturn model - classify_return_model_json = {} - classify_return_model_json['document'] = document_model - classify_return_model_json['model_id'] = 'testString' - classify_return_model_json['model_version'] = 'testString' - classify_return_model_json['elements'] = [element_model] - classify_return_model_json['effective_dates'] = [effective_dates_model] - classify_return_model_json['contract_amounts'] = [contract_amts_model] - classify_return_model_json['termination_dates'] = [termination_dates_model] - classify_return_model_json['contract_types'] = [contract_types_model] - classify_return_model_json['contract_terms'] = [contract_terms_model] - classify_return_model_json['payment_terms'] = [payment_terms_model] - classify_return_model_json['contract_currencies'] = [contract_currencies_model] - classify_return_model_json['tables'] = [tables_model] - classify_return_model_json['document_structure'] = doc_structure_model - classify_return_model_json['parties'] = [parties_model] - - # Construct a model instance of ClassifyReturn by calling from_dict on the json representation - classify_return_model = ClassifyReturn.from_dict(classify_return_model_json) - assert classify_return_model != False - - # Construct a model instance of ClassifyReturn by calling from_dict on the json representation - classify_return_model_dict = ClassifyReturn.from_dict(classify_return_model_json).__dict__ - classify_return_model2 = ClassifyReturn(**classify_return_model_dict) - - # Verify the model instances are equivalent - assert classify_return_model == classify_return_model2 - - # Convert model instance back to dict and verify no loss of data - classify_return_model_json2 = classify_return_model.to_dict() - assert classify_return_model_json2 == classify_return_model_json - -class TestModel_ColumnHeaders(): - """ - Test Class for ColumnHeaders - """ - - def test_column_headers_serialization(self): - """ - Test serialization/deserialization for ColumnHeaders - """ - - # Construct a json representation of a ColumnHeaders model - column_headers_model_json = {} - column_headers_model_json['cell_id'] = 'testString' - column_headers_model_json['location'] = { 'foo': 'bar' } - column_headers_model_json['text'] = 'testString' - column_headers_model_json['text_normalized'] = 'testString' - column_headers_model_json['row_index_begin'] = 26 - column_headers_model_json['row_index_end'] = 26 - column_headers_model_json['column_index_begin'] = 26 - column_headers_model_json['column_index_end'] = 26 - - # Construct a model instance of ColumnHeaders by calling from_dict on the json representation - column_headers_model = ColumnHeaders.from_dict(column_headers_model_json) - assert column_headers_model != False - - # Construct a model instance of ColumnHeaders by calling from_dict on the json representation - column_headers_model_dict = ColumnHeaders.from_dict(column_headers_model_json).__dict__ - column_headers_model2 = ColumnHeaders(**column_headers_model_dict) - - # Verify the model instances are equivalent - assert column_headers_model == column_headers_model2 - - # Convert model instance back to dict and verify no loss of data - column_headers_model_json2 = column_headers_model.to_dict() - assert column_headers_model_json2 == column_headers_model_json - -class TestModel_CompareReturn(): - """ - Test Class for CompareReturn - """ - - def test_compare_return_serialization(self): - """ - Test serialization/deserialization for CompareReturn - """ - - # Construct dict forms of any model objects needed in order to build this model. - - document_model = {} # Document - document_model['title'] = '31235_000156459017003570_kodk-ex1013_296.pdf' - document_model['html'] = '...' - document_model['hash'] = '0d9589556c16fca21c64ce9c8b10d065' - document_model['label'] = 'file_1' - - location_model = {} # Location - location_model['begin'] = 5690 - location_model['end'] = 5865 - - label_model = {} # Label - label_model['nature'] = 'Exclusion' - label_model['party'] = 'You' - - type_label_comparison_model = {} # TypeLabelComparison - type_label_comparison_model['label'] = label_model - - category_comparison_model = {} # CategoryComparison - category_comparison_model['label'] = 'Amendments' - - attribute_model = {} # Attribute - attribute_model['type'] = 'Currency' - attribute_model['text'] = 'testString' - attribute_model['location'] = location_model - - element_pair_model = {} # ElementPair - element_pair_model['document_label'] = 'file_1' - element_pair_model['text'] = 'You will not have the rights of a Ishki shareholder with respect to the shares issued to you in payment of your RSUs until the shares are actually issued and delivered to you.' - element_pair_model['location'] = location_model - element_pair_model['types'] = [type_label_comparison_model] - element_pair_model['categories'] = [category_comparison_model] - element_pair_model['attributes'] = [attribute_model] - - aligned_element_model = {} # AlignedElement - aligned_element_model['element_pair'] = [element_pair_model] - aligned_element_model['identical_text'] = True - aligned_element_model['provenance_ids'] = ['1mSG/96z1wY4De35LAExJzhCo2t0DfvbYnTl+vbavjY='] - aligned_element_model['significant_elements'] = True - - unaligned_element_model = {} # UnalignedElement - unaligned_element_model['document_label'] = 'file_1' - unaligned_element_model['location'] = location_model - unaligned_element_model['text'] = 'The RSUs (at the time of vesting or otherwise) will be includible as compensation for pension.' - unaligned_element_model['types'] = [type_label_comparison_model] - unaligned_element_model['categories'] = [category_comparison_model] - unaligned_element_model['attributes'] = [attribute_model] - - # Construct a json representation of a CompareReturn model - compare_return_model_json = {} - compare_return_model_json['model_id'] = 'testString' - compare_return_model_json['model_version'] = 'testString' - compare_return_model_json['documents'] = [document_model] - compare_return_model_json['aligned_elements'] = [aligned_element_model] - compare_return_model_json['unaligned_elements'] = [unaligned_element_model] - - # Construct a model instance of CompareReturn by calling from_dict on the json representation - compare_return_model = CompareReturn.from_dict(compare_return_model_json) - assert compare_return_model != False - - # Construct a model instance of CompareReturn by calling from_dict on the json representation - compare_return_model_dict = CompareReturn.from_dict(compare_return_model_json).__dict__ - compare_return_model2 = CompareReturn(**compare_return_model_dict) - - # Verify the model instances are equivalent - assert compare_return_model == compare_return_model2 - - # Convert model instance back to dict and verify no loss of data - compare_return_model_json2 = compare_return_model.to_dict() - assert compare_return_model_json2 == compare_return_model_json - -class TestModel_Contact(): - """ - Test Class for Contact - """ - - def test_contact_serialization(self): - """ - Test serialization/deserialization for Contact - """ - - # Construct a json representation of a Contact model - contact_model_json = {} - contact_model_json['name'] = 'testString' - contact_model_json['role'] = 'testString' - - # Construct a model instance of Contact by calling from_dict on the json representation - contact_model = Contact.from_dict(contact_model_json) - assert contact_model != False - - # Construct a model instance of Contact by calling from_dict on the json representation - contact_model_dict = Contact.from_dict(contact_model_json).__dict__ - contact_model2 = Contact(**contact_model_dict) - - # Verify the model instances are equivalent - assert contact_model == contact_model2 - - # Convert model instance back to dict and verify no loss of data - contact_model_json2 = contact_model.to_dict() - assert contact_model_json2 == contact_model_json - -class TestModel_Contexts(): - """ - Test Class for Contexts - """ - - def test_contexts_serialization(self): - """ - Test serialization/deserialization for Contexts - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a Contexts model - contexts_model_json = {} - contexts_model_json['text'] = 'testString' - contexts_model_json['location'] = location_model - - # Construct a model instance of Contexts by calling from_dict on the json representation - contexts_model = Contexts.from_dict(contexts_model_json) - assert contexts_model != False - - # Construct a model instance of Contexts by calling from_dict on the json representation - contexts_model_dict = Contexts.from_dict(contexts_model_json).__dict__ - contexts_model2 = Contexts(**contexts_model_dict) - - # Verify the model instances are equivalent - assert contexts_model == contexts_model2 - - # Convert model instance back to dict and verify no loss of data - contexts_model_json2 = contexts_model.to_dict() - assert contexts_model_json2 == contexts_model_json - -class TestModel_ContractAmts(): - """ - Test Class for ContractAmts - """ - - def test_contract_amts_serialization(self): - """ - Test serialization/deserialization for ContractAmts - """ - - # Construct dict forms of any model objects needed in order to build this model. - - interpretation_model = {} # Interpretation - interpretation_model['value'] = 'testString' - interpretation_model['numeric_value'] = 72.5 - interpretation_model['unit'] = 'testString' - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a ContractAmts model - contract_amts_model_json = {} - contract_amts_model_json['confidence_level'] = 'High' - contract_amts_model_json['text'] = 'testString' - contract_amts_model_json['text_normalized'] = 'testString' - contract_amts_model_json['interpretation'] = interpretation_model - contract_amts_model_json['provenance_ids'] = ['testString'] - contract_amts_model_json['location'] = location_model - - # Construct a model instance of ContractAmts by calling from_dict on the json representation - contract_amts_model = ContractAmts.from_dict(contract_amts_model_json) - assert contract_amts_model != False - - # Construct a model instance of ContractAmts by calling from_dict on the json representation - contract_amts_model_dict = ContractAmts.from_dict(contract_amts_model_json).__dict__ - contract_amts_model2 = ContractAmts(**contract_amts_model_dict) - - # Verify the model instances are equivalent - assert contract_amts_model == contract_amts_model2 - - # Convert model instance back to dict and verify no loss of data - contract_amts_model_json2 = contract_amts_model.to_dict() - assert contract_amts_model_json2 == contract_amts_model_json - -class TestModel_ContractCurrencies(): - """ - Test Class for ContractCurrencies - """ - - def test_contract_currencies_serialization(self): - """ - Test serialization/deserialization for ContractCurrencies - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a ContractCurrencies model - contract_currencies_model_json = {} - contract_currencies_model_json['confidence_level'] = 'High' - contract_currencies_model_json['text'] = 'testString' - contract_currencies_model_json['text_normalized'] = 'testString' - contract_currencies_model_json['provenance_ids'] = ['testString'] - contract_currencies_model_json['location'] = location_model - - # Construct a model instance of ContractCurrencies by calling from_dict on the json representation - contract_currencies_model = ContractCurrencies.from_dict(contract_currencies_model_json) - assert contract_currencies_model != False - - # Construct a model instance of ContractCurrencies by calling from_dict on the json representation - contract_currencies_model_dict = ContractCurrencies.from_dict(contract_currencies_model_json).__dict__ - contract_currencies_model2 = ContractCurrencies(**contract_currencies_model_dict) - - # Verify the model instances are equivalent - assert contract_currencies_model == contract_currencies_model2 - - # Convert model instance back to dict and verify no loss of data - contract_currencies_model_json2 = contract_currencies_model.to_dict() - assert contract_currencies_model_json2 == contract_currencies_model_json - -class TestModel_ContractTerms(): - """ - Test Class for ContractTerms - """ - - def test_contract_terms_serialization(self): - """ - Test serialization/deserialization for ContractTerms - """ - - # Construct dict forms of any model objects needed in order to build this model. - - interpretation_model = {} # Interpretation - interpretation_model['value'] = 'testString' - interpretation_model['numeric_value'] = 72.5 - interpretation_model['unit'] = 'testString' - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a ContractTerms model - contract_terms_model_json = {} - contract_terms_model_json['confidence_level'] = 'High' - contract_terms_model_json['text'] = 'testString' - contract_terms_model_json['text_normalized'] = 'testString' - contract_terms_model_json['interpretation'] = interpretation_model - contract_terms_model_json['provenance_ids'] = ['testString'] - contract_terms_model_json['location'] = location_model - - # Construct a model instance of ContractTerms by calling from_dict on the json representation - contract_terms_model = ContractTerms.from_dict(contract_terms_model_json) - assert contract_terms_model != False - - # Construct a model instance of ContractTerms by calling from_dict on the json representation - contract_terms_model_dict = ContractTerms.from_dict(contract_terms_model_json).__dict__ - contract_terms_model2 = ContractTerms(**contract_terms_model_dict) - - # Verify the model instances are equivalent - assert contract_terms_model == contract_terms_model2 - - # Convert model instance back to dict and verify no loss of data - contract_terms_model_json2 = contract_terms_model.to_dict() - assert contract_terms_model_json2 == contract_terms_model_json - -class TestModel_ContractTypes(): - """ - Test Class for ContractTypes - """ - - def test_contract_types_serialization(self): - """ - Test serialization/deserialization for ContractTypes - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a ContractTypes model - contract_types_model_json = {} - contract_types_model_json['confidence_level'] = 'High' - contract_types_model_json['text'] = 'testString' - contract_types_model_json['provenance_ids'] = ['testString'] - contract_types_model_json['location'] = location_model - - # Construct a model instance of ContractTypes by calling from_dict on the json representation - contract_types_model = ContractTypes.from_dict(contract_types_model_json) - assert contract_types_model != False - - # Construct a model instance of ContractTypes by calling from_dict on the json representation - contract_types_model_dict = ContractTypes.from_dict(contract_types_model_json).__dict__ - contract_types_model2 = ContractTypes(**contract_types_model_dict) - - # Verify the model instances are equivalent - assert contract_types_model == contract_types_model2 - - # Convert model instance back to dict and verify no loss of data - contract_types_model_json2 = contract_types_model.to_dict() - assert contract_types_model_json2 == contract_types_model_json - -class TestModel_DocCounts(): - """ - Test Class for DocCounts - """ - - def test_doc_counts_serialization(self): - """ - Test serialization/deserialization for DocCounts - """ - - # Construct a json representation of a DocCounts model - doc_counts_model_json = {} - doc_counts_model_json['total'] = 38 - doc_counts_model_json['pending'] = 38 - doc_counts_model_json['successful'] = 38 - doc_counts_model_json['failed'] = 38 - - # Construct a model instance of DocCounts by calling from_dict on the json representation - doc_counts_model = DocCounts.from_dict(doc_counts_model_json) - assert doc_counts_model != False - - # Construct a model instance of DocCounts by calling from_dict on the json representation - doc_counts_model_dict = DocCounts.from_dict(doc_counts_model_json).__dict__ - doc_counts_model2 = DocCounts(**doc_counts_model_dict) - - # Verify the model instances are equivalent - assert doc_counts_model == doc_counts_model2 - - # Convert model instance back to dict and verify no loss of data - doc_counts_model_json2 = doc_counts_model.to_dict() - assert doc_counts_model_json2 == doc_counts_model_json - -class TestModel_DocInfo(): - """ - Test Class for DocInfo - """ - - def test_doc_info_serialization(self): - """ - Test serialization/deserialization for DocInfo - """ - - # Construct a json representation of a DocInfo model - doc_info_model_json = {} - doc_info_model_json['html'] = 'testString' - doc_info_model_json['title'] = 'testString' - doc_info_model_json['hash'] = 'testString' - - # Construct a model instance of DocInfo by calling from_dict on the json representation - doc_info_model = DocInfo.from_dict(doc_info_model_json) - assert doc_info_model != False - - # Construct a model instance of DocInfo by calling from_dict on the json representation - doc_info_model_dict = DocInfo.from_dict(doc_info_model_json).__dict__ - doc_info_model2 = DocInfo(**doc_info_model_dict) - - # Verify the model instances are equivalent - assert doc_info_model == doc_info_model2 - - # Convert model instance back to dict and verify no loss of data - doc_info_model_json2 = doc_info_model.to_dict() - assert doc_info_model_json2 == doc_info_model_json - -class TestModel_DocStructure(): - """ - Test Class for DocStructure - """ - - def test_doc_structure_serialization(self): - """ - Test serialization/deserialization for DocStructure - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - element_locations_model = {} # ElementLocations - element_locations_model['begin'] = 38 - element_locations_model['end'] = 38 - - section_titles_model = {} # SectionTitles - section_titles_model['text'] = 'testString' - section_titles_model['location'] = location_model - section_titles_model['level'] = 38 - section_titles_model['element_locations'] = [element_locations_model] - - leading_sentence_model = {} # LeadingSentence - leading_sentence_model['text'] = 'testString' - leading_sentence_model['location'] = location_model - leading_sentence_model['element_locations'] = [element_locations_model] - - paragraphs_model = {} # Paragraphs - paragraphs_model['location'] = location_model - - # Construct a json representation of a DocStructure model - doc_structure_model_json = {} - doc_structure_model_json['section_titles'] = [section_titles_model] - doc_structure_model_json['leading_sentences'] = [leading_sentence_model] - doc_structure_model_json['paragraphs'] = [paragraphs_model] - - # Construct a model instance of DocStructure by calling from_dict on the json representation - doc_structure_model = DocStructure.from_dict(doc_structure_model_json) - assert doc_structure_model != False - - # Construct a model instance of DocStructure by calling from_dict on the json representation - doc_structure_model_dict = DocStructure.from_dict(doc_structure_model_json).__dict__ - doc_structure_model2 = DocStructure(**doc_structure_model_dict) - - # Verify the model instances are equivalent - assert doc_structure_model == doc_structure_model2 - - # Convert model instance back to dict and verify no loss of data - doc_structure_model_json2 = doc_structure_model.to_dict() - assert doc_structure_model_json2 == doc_structure_model_json - -class TestModel_Document(): - """ - Test Class for Document - """ - - def test_document_serialization(self): - """ - Test serialization/deserialization for Document - """ - - # Construct a json representation of a Document model - document_model_json = {} - document_model_json['title'] = 'testString' - document_model_json['html'] = 'testString' - document_model_json['hash'] = 'testString' - document_model_json['label'] = 'testString' - - # Construct a model instance of Document by calling from_dict on the json representation - document_model = Document.from_dict(document_model_json) - assert document_model != False - - # Construct a model instance of Document by calling from_dict on the json representation - document_model_dict = Document.from_dict(document_model_json).__dict__ - document_model2 = Document(**document_model_dict) - - # Verify the model instances are equivalent - assert document_model == document_model2 - - # Convert model instance back to dict and verify no loss of data - document_model_json2 = document_model.to_dict() - assert document_model_json2 == document_model_json - -class TestModel_EffectiveDates(): - """ - Test Class for EffectiveDates - """ - - def test_effective_dates_serialization(self): - """ - Test serialization/deserialization for EffectiveDates - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a EffectiveDates model - effective_dates_model_json = {} - effective_dates_model_json['confidence_level'] = 'High' - effective_dates_model_json['text'] = 'testString' - effective_dates_model_json['text_normalized'] = 'testString' - effective_dates_model_json['provenance_ids'] = ['testString'] - effective_dates_model_json['location'] = location_model - - # Construct a model instance of EffectiveDates by calling from_dict on the json representation - effective_dates_model = EffectiveDates.from_dict(effective_dates_model_json) - assert effective_dates_model != False - - # Construct a model instance of EffectiveDates by calling from_dict on the json representation - effective_dates_model_dict = EffectiveDates.from_dict(effective_dates_model_json).__dict__ - effective_dates_model2 = EffectiveDates(**effective_dates_model_dict) - - # Verify the model instances are equivalent - assert effective_dates_model == effective_dates_model2 - - # Convert model instance back to dict and verify no loss of data - effective_dates_model_json2 = effective_dates_model.to_dict() - assert effective_dates_model_json2 == effective_dates_model_json - -class TestModel_Element(): - """ - Test Class for Element - """ - - def test_element_serialization(self): - """ - Test serialization/deserialization for Element - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - type_label_model = {} # TypeLabel - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] - type_label_model['modification'] = 'added' - - category_model = {} # Category - category_model['label'] = 'Amendments' - category_model['provenance_ids'] = ['testString'] - category_model['modification'] = 'added' - - attribute_model = {} # Attribute - attribute_model['type'] = 'Currency' - attribute_model['text'] = 'testString' - attribute_model['location'] = location_model - - # Construct a json representation of a Element model - element_model_json = {} - element_model_json['location'] = location_model - element_model_json['text'] = 'testString' - element_model_json['types'] = [type_label_model] - element_model_json['categories'] = [category_model] - element_model_json['attributes'] = [attribute_model] - - # Construct a model instance of Element by calling from_dict on the json representation - element_model = Element.from_dict(element_model_json) - assert element_model != False - - # Construct a model instance of Element by calling from_dict on the json representation - element_model_dict = Element.from_dict(element_model_json).__dict__ - element_model2 = Element(**element_model_dict) - - # Verify the model instances are equivalent - assert element_model == element_model2 - - # Convert model instance back to dict and verify no loss of data - element_model_json2 = element_model.to_dict() - assert element_model_json2 == element_model_json - -class TestModel_ElementLocations(): - """ - Test Class for ElementLocations - """ - - def test_element_locations_serialization(self): - """ - Test serialization/deserialization for ElementLocations - """ - - # Construct a json representation of a ElementLocations model - element_locations_model_json = {} - element_locations_model_json['begin'] = 38 - element_locations_model_json['end'] = 38 - - # Construct a model instance of ElementLocations by calling from_dict on the json representation - element_locations_model = ElementLocations.from_dict(element_locations_model_json) - assert element_locations_model != False - - # Construct a model instance of ElementLocations by calling from_dict on the json representation - element_locations_model_dict = ElementLocations.from_dict(element_locations_model_json).__dict__ - element_locations_model2 = ElementLocations(**element_locations_model_dict) - - # Verify the model instances are equivalent - assert element_locations_model == element_locations_model2 - - # Convert model instance back to dict and verify no loss of data - element_locations_model_json2 = element_locations_model.to_dict() - assert element_locations_model_json2 == element_locations_model_json - -class TestModel_ElementPair(): - """ - Test Class for ElementPair - """ - - def test_element_pair_serialization(self): - """ - Test serialization/deserialization for ElementPair - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - type_label_comparison_model = {} # TypeLabelComparison - type_label_comparison_model['label'] = label_model - - category_comparison_model = {} # CategoryComparison - category_comparison_model['label'] = 'Amendments' - - attribute_model = {} # Attribute - attribute_model['type'] = 'Currency' - attribute_model['text'] = 'testString' - attribute_model['location'] = location_model - - # Construct a json representation of a ElementPair model - element_pair_model_json = {} - element_pair_model_json['document_label'] = 'testString' - element_pair_model_json['text'] = 'testString' - element_pair_model_json['location'] = location_model - element_pair_model_json['types'] = [type_label_comparison_model] - element_pair_model_json['categories'] = [category_comparison_model] - element_pair_model_json['attributes'] = [attribute_model] - - # Construct a model instance of ElementPair by calling from_dict on the json representation - element_pair_model = ElementPair.from_dict(element_pair_model_json) - assert element_pair_model != False - - # Construct a model instance of ElementPair by calling from_dict on the json representation - element_pair_model_dict = ElementPair.from_dict(element_pair_model_json).__dict__ - element_pair_model2 = ElementPair(**element_pair_model_dict) - - # Verify the model instances are equivalent - assert element_pair_model == element_pair_model2 - - # Convert model instance back to dict and verify no loss of data - element_pair_model_json2 = element_pair_model.to_dict() - assert element_pair_model_json2 == element_pair_model_json - -class TestModel_FeedbackDataInput(): - """ - Test Class for FeedbackDataInput - """ - - def test_feedback_data_input_serialization(self): - """ - Test serialization/deserialization for FeedbackDataInput - """ - - # Construct dict forms of any model objects needed in order to build this model. - - short_doc_model = {} # ShortDoc - short_doc_model['title'] = 'testString' - short_doc_model['hash'] = 'testString' - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - type_label_model = {} # TypeLabel - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] - type_label_model['modification'] = 'added' - - category_model = {} # Category - category_model['label'] = 'Amendments' - category_model['provenance_ids'] = ['testString'] - category_model['modification'] = 'added' - - original_labels_in_model = {} # OriginalLabelsIn - original_labels_in_model['types'] = [type_label_model] - original_labels_in_model['categories'] = [category_model] - - updated_labels_in_model = {} # UpdatedLabelsIn - updated_labels_in_model['types'] = [type_label_model] - updated_labels_in_model['categories'] = [category_model] - - # Construct a json representation of a FeedbackDataInput model - feedback_data_input_model_json = {} - feedback_data_input_model_json['feedback_type'] = 'testString' - feedback_data_input_model_json['document'] = short_doc_model - feedback_data_input_model_json['model_id'] = 'testString' - feedback_data_input_model_json['model_version'] = 'testString' - feedback_data_input_model_json['location'] = location_model - feedback_data_input_model_json['text'] = 'testString' - feedback_data_input_model_json['original_labels'] = original_labels_in_model - feedback_data_input_model_json['updated_labels'] = updated_labels_in_model - - # Construct a model instance of FeedbackDataInput by calling from_dict on the json representation - feedback_data_input_model = FeedbackDataInput.from_dict(feedback_data_input_model_json) - assert feedback_data_input_model != False - - # Construct a model instance of FeedbackDataInput by calling from_dict on the json representation - feedback_data_input_model_dict = FeedbackDataInput.from_dict(feedback_data_input_model_json).__dict__ - feedback_data_input_model2 = FeedbackDataInput(**feedback_data_input_model_dict) - - # Verify the model instances are equivalent - assert feedback_data_input_model == feedback_data_input_model2 - - # Convert model instance back to dict and verify no loss of data - feedback_data_input_model_json2 = feedback_data_input_model.to_dict() - assert feedback_data_input_model_json2 == feedback_data_input_model_json - -class TestModel_FeedbackDataOutput(): - """ - Test Class for FeedbackDataOutput - """ - - def test_feedback_data_output_serialization(self): - """ - Test serialization/deserialization for FeedbackDataOutput - """ - - # Construct dict forms of any model objects needed in order to build this model. - - short_doc_model = {} # ShortDoc - short_doc_model['title'] = 'testString' - short_doc_model['hash'] = 'testString' - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - type_label_model = {} # TypeLabel - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] - type_label_model['modification'] = 'added' - - category_model = {} # Category - category_model['label'] = 'Amendments' - category_model['provenance_ids'] = ['testString'] - category_model['modification'] = 'added' - - original_labels_out_model = {} # OriginalLabelsOut - original_labels_out_model['types'] = [type_label_model] - original_labels_out_model['categories'] = [category_model] - - updated_labels_out_model = {} # UpdatedLabelsOut - updated_labels_out_model['types'] = [type_label_model] - updated_labels_out_model['categories'] = [category_model] - - pagination_model = {} # Pagination - pagination_model['refresh_cursor'] = 'testString' - pagination_model['next_cursor'] = 'testString' - pagination_model['refresh_url'] = 'testString' - pagination_model['next_url'] = 'testString' - pagination_model['total'] = 26 - - # Construct a json representation of a FeedbackDataOutput model - feedback_data_output_model_json = {} - feedback_data_output_model_json['feedback_type'] = 'testString' - feedback_data_output_model_json['document'] = short_doc_model - feedback_data_output_model_json['model_id'] = 'testString' - feedback_data_output_model_json['model_version'] = 'testString' - feedback_data_output_model_json['location'] = location_model - feedback_data_output_model_json['text'] = 'testString' - feedback_data_output_model_json['original_labels'] = original_labels_out_model - feedback_data_output_model_json['updated_labels'] = updated_labels_out_model - feedback_data_output_model_json['pagination'] = pagination_model - - # Construct a model instance of FeedbackDataOutput by calling from_dict on the json representation - feedback_data_output_model = FeedbackDataOutput.from_dict(feedback_data_output_model_json) - assert feedback_data_output_model != False - - # Construct a model instance of FeedbackDataOutput by calling from_dict on the json representation - feedback_data_output_model_dict = FeedbackDataOutput.from_dict(feedback_data_output_model_json).__dict__ - feedback_data_output_model2 = FeedbackDataOutput(**feedback_data_output_model_dict) - - # Verify the model instances are equivalent - assert feedback_data_output_model == feedback_data_output_model2 - - # Convert model instance back to dict and verify no loss of data - feedback_data_output_model_json2 = feedback_data_output_model.to_dict() - assert feedback_data_output_model_json2 == feedback_data_output_model_json - -class TestModel_FeedbackDeleted(): - """ - Test Class for FeedbackDeleted - """ - - def test_feedback_deleted_serialization(self): - """ - Test serialization/deserialization for FeedbackDeleted - """ - - # Construct a json representation of a FeedbackDeleted model - feedback_deleted_model_json = {} - feedback_deleted_model_json['status'] = 38 - feedback_deleted_model_json['message'] = 'testString' - - # Construct a model instance of FeedbackDeleted by calling from_dict on the json representation - feedback_deleted_model = FeedbackDeleted.from_dict(feedback_deleted_model_json) - assert feedback_deleted_model != False - - # Construct a model instance of FeedbackDeleted by calling from_dict on the json representation - feedback_deleted_model_dict = FeedbackDeleted.from_dict(feedback_deleted_model_json).__dict__ - feedback_deleted_model2 = FeedbackDeleted(**feedback_deleted_model_dict) - - # Verify the model instances are equivalent - assert feedback_deleted_model == feedback_deleted_model2 - - # Convert model instance back to dict and verify no loss of data - feedback_deleted_model_json2 = feedback_deleted_model.to_dict() - assert feedback_deleted_model_json2 == feedback_deleted_model_json - -class TestModel_FeedbackList(): - """ - Test Class for FeedbackList - """ - - def test_feedback_list_serialization(self): - """ - Test serialization/deserialization for FeedbackList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - short_doc_model = {} # ShortDoc - short_doc_model['title'] = 'Legal Approval SOW' - short_doc_model['hash'] = 'dcd82f59c6bb1a289a514b611d531191' - - location_model = {} # Location - location_model['begin'] = 214 - location_model['end'] = 237 - - label_model = {} # Label - label_model['nature'] = 'Obligation' - label_model['party'] = 'IBM' - - type_label_model = {} # TypeLabel - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['85f5981a-ba91-44f5-9efa-0bd22e64b7bc', 'ce0480a1-5ef1-4c3e-9861-3743b5610795'] - type_label_model['modification'] = 'unchanged' - - category_model = {} # Category - category_model['label'] = 'Responsibilities' - category_model['provenance_ids'] = [] - category_model['modification'] = 'unchanged' - - original_labels_out_model = {} # OriginalLabelsOut - original_labels_out_model['types'] = [type_label_model] - original_labels_out_model['categories'] = [category_model] - - updated_labels_out_model = {} # UpdatedLabelsOut - updated_labels_out_model['types'] = [type_label_model] - updated_labels_out_model['categories'] = [category_model] - - pagination_model = {} # Pagination - pagination_model['refresh_cursor'] = 'testString' - pagination_model['next_cursor'] = 'testString' - pagination_model['refresh_url'] = 'testString' - pagination_model['next_url'] = 'testString' - pagination_model['total'] = 26 - - feedback_data_output_model = {} # FeedbackDataOutput - feedback_data_output_model['feedback_type'] = 'element_classification' - feedback_data_output_model['document'] = short_doc_model - feedback_data_output_model['model_id'] = 'contracts' - feedback_data_output_model['model_version'] = '10.00' - feedback_data_output_model['location'] = location_model - feedback_data_output_model['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.' - feedback_data_output_model['original_labels'] = original_labels_out_model - feedback_data_output_model['updated_labels'] = updated_labels_out_model - feedback_data_output_model['pagination'] = pagination_model - - get_feedback_model = {} # GetFeedback - get_feedback_model['feedback_id'] = '9730b437-cb86-4d40-9a84-ff6948bb3dd1' - get_feedback_model['created'] = "2018-07-03T15:16:05Z" - get_feedback_model['comment'] = 'testString' - get_feedback_model['feedback_data'] = feedback_data_output_model - - # Construct a json representation of a FeedbackList model - feedback_list_model_json = {} - feedback_list_model_json['feedback'] = [get_feedback_model] - - # Construct a model instance of FeedbackList by calling from_dict on the json representation - feedback_list_model = FeedbackList.from_dict(feedback_list_model_json) - assert feedback_list_model != False - - # Construct a model instance of FeedbackList by calling from_dict on the json representation - feedback_list_model_dict = FeedbackList.from_dict(feedback_list_model_json).__dict__ - feedback_list_model2 = FeedbackList(**feedback_list_model_dict) - - # Verify the model instances are equivalent - assert feedback_list_model == feedback_list_model2 - - # Convert model instance back to dict and verify no loss of data - feedback_list_model_json2 = feedback_list_model.to_dict() - assert feedback_list_model_json2 == feedback_list_model_json - -class TestModel_FeedbackReturn(): - """ - Test Class for FeedbackReturn - """ - - def test_feedback_return_serialization(self): - """ - Test serialization/deserialization for FeedbackReturn - """ - - # Construct dict forms of any model objects needed in order to build this model. - - short_doc_model = {} # ShortDoc - short_doc_model['title'] = 'testString' - short_doc_model['hash'] = 'testString' - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - type_label_model = {} # TypeLabel - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] - type_label_model['modification'] = 'added' - - category_model = {} # Category - category_model['label'] = 'Amendments' - category_model['provenance_ids'] = ['testString'] - category_model['modification'] = 'added' - - original_labels_out_model = {} # OriginalLabelsOut - original_labels_out_model['types'] = [type_label_model] - original_labels_out_model['categories'] = [category_model] - - updated_labels_out_model = {} # UpdatedLabelsOut - updated_labels_out_model['types'] = [type_label_model] - updated_labels_out_model['categories'] = [category_model] - - pagination_model = {} # Pagination - pagination_model['refresh_cursor'] = 'testString' - pagination_model['next_cursor'] = 'testString' - pagination_model['refresh_url'] = 'testString' - pagination_model['next_url'] = 'testString' - pagination_model['total'] = 26 - - feedback_data_output_model = {} # FeedbackDataOutput - feedback_data_output_model['feedback_type'] = 'testString' - feedback_data_output_model['document'] = short_doc_model - feedback_data_output_model['model_id'] = 'testString' - feedback_data_output_model['model_version'] = 'testString' - feedback_data_output_model['location'] = location_model - feedback_data_output_model['text'] = 'testString' - feedback_data_output_model['original_labels'] = original_labels_out_model - feedback_data_output_model['updated_labels'] = updated_labels_out_model - feedback_data_output_model['pagination'] = pagination_model - - # Construct a json representation of a FeedbackReturn model - feedback_return_model_json = {} - feedback_return_model_json['feedback_id'] = 'testString' - feedback_return_model_json['user_id'] = 'testString' - feedback_return_model_json['comment'] = 'testString' - feedback_return_model_json['created'] = "2019-01-01T12:00:00Z" - feedback_return_model_json['feedback_data'] = feedback_data_output_model - - # Construct a model instance of FeedbackReturn by calling from_dict on the json representation - feedback_return_model = FeedbackReturn.from_dict(feedback_return_model_json) - assert feedback_return_model != False - - # Construct a model instance of FeedbackReturn by calling from_dict on the json representation - feedback_return_model_dict = FeedbackReturn.from_dict(feedback_return_model_json).__dict__ - feedback_return_model2 = FeedbackReturn(**feedback_return_model_dict) - - # Verify the model instances are equivalent - assert feedback_return_model == feedback_return_model2 - - # Convert model instance back to dict and verify no loss of data - feedback_return_model_json2 = feedback_return_model.to_dict() - assert feedback_return_model_json2 == feedback_return_model_json - -class TestModel_GetFeedback(): - """ - Test Class for GetFeedback - """ - - def test_get_feedback_serialization(self): - """ - Test serialization/deserialization for GetFeedback - """ - - # Construct dict forms of any model objects needed in order to build this model. - - short_doc_model = {} # ShortDoc - short_doc_model['title'] = 'Legal Approval SOW' - short_doc_model['hash'] = '4492935afd3673e04082591d163ad68b' - - location_model = {} # Location - location_model['begin'] = 214 - location_model['end'] = 237 - - label_model = {} # Label - label_model['nature'] = 'Obligation' - label_model['party'] = 'IBM' - - type_label_model = {} # TypeLabel - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['85f5981a-ba91-44f5-9efa-0bd22e64b7bc', 'ce0480a1-5ef1-4c3e-9861-3743b5610795'] - type_label_model['modification'] = 'unchanged' - - category_model = {} # Category - category_model['label'] = 'obligation' - category_model['provenance_ids'] = ['85f5981a-ba91-44f5-9efa-0bd22e64b7bc', 'ce0480a1-5ef1-4c3e-9861-3743b5610795'] - category_model['modification'] = 'removed' - - original_labels_out_model = {} # OriginalLabelsOut - original_labels_out_model['types'] = [type_label_model] - original_labels_out_model['categories'] = [category_model] - - updated_labels_out_model = {} # UpdatedLabelsOut - updated_labels_out_model['types'] = [type_label_model] - updated_labels_out_model['categories'] = [category_model] - - pagination_model = {} # Pagination - pagination_model['refresh_cursor'] = 'testString' - pagination_model['next_cursor'] = 'testString' - pagination_model['refresh_url'] = 'testString' - pagination_model['next_url'] = 'testString' - pagination_model['total'] = 26 - - feedback_data_output_model = {} # FeedbackDataOutput - feedback_data_output_model['feedback_type'] = 'element_classification' - feedback_data_output_model['document'] = short_doc_model - feedback_data_output_model['model_id'] = 'contracts' - feedback_data_output_model['model_version'] = '10.00' - feedback_data_output_model['location'] = location_model - feedback_data_output_model['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.' - feedback_data_output_model['original_labels'] = original_labels_out_model - feedback_data_output_model['updated_labels'] = updated_labels_out_model - feedback_data_output_model['pagination'] = pagination_model - - # Construct a json representation of a GetFeedback model - get_feedback_model_json = {} - get_feedback_model_json['feedback_id'] = 'testString' - get_feedback_model_json['created'] = "2019-01-01T12:00:00Z" - get_feedback_model_json['comment'] = 'testString' - get_feedback_model_json['feedback_data'] = feedback_data_output_model - - # Construct a model instance of GetFeedback by calling from_dict on the json representation - get_feedback_model = GetFeedback.from_dict(get_feedback_model_json) - assert get_feedback_model != False - - # Construct a model instance of GetFeedback by calling from_dict on the json representation - get_feedback_model_dict = GetFeedback.from_dict(get_feedback_model_json).__dict__ - get_feedback_model2 = GetFeedback(**get_feedback_model_dict) - - # Verify the model instances are equivalent - assert get_feedback_model == get_feedback_model2 - - # Convert model instance back to dict and verify no loss of data - get_feedback_model_json2 = get_feedback_model.to_dict() - assert get_feedback_model_json2 == get_feedback_model_json - -class TestModel_HTMLReturn(): - """ - Test Class for HTMLReturn - """ - - def test_html_return_serialization(self): - """ - Test serialization/deserialization for HTMLReturn - """ - - # Construct a json representation of a HTMLReturn model - html_return_model_json = {} - html_return_model_json['num_pages'] = 'testString' - html_return_model_json['author'] = 'testString' - html_return_model_json['publication_date'] = 'testString' - html_return_model_json['title'] = 'testString' - html_return_model_json['html'] = 'testString' - - # Construct a model instance of HTMLReturn by calling from_dict on the json representation - html_return_model = HTMLReturn.from_dict(html_return_model_json) - assert html_return_model != False - - # Construct a model instance of HTMLReturn by calling from_dict on the json representation - html_return_model_dict = HTMLReturn.from_dict(html_return_model_json).__dict__ - html_return_model2 = HTMLReturn(**html_return_model_dict) - - # Verify the model instances are equivalent - assert html_return_model == html_return_model2 - - # Convert model instance back to dict and verify no loss of data - html_return_model_json2 = html_return_model.to_dict() - assert html_return_model_json2 == html_return_model_json - -class TestModel_Interpretation(): - """ - Test Class for Interpretation - """ - - def test_interpretation_serialization(self): - """ - Test serialization/deserialization for Interpretation - """ - - # Construct a json representation of a Interpretation model - interpretation_model_json = {} - interpretation_model_json['value'] = 'testString' - interpretation_model_json['numeric_value'] = 72.5 - interpretation_model_json['unit'] = 'testString' - - # Construct a model instance of Interpretation by calling from_dict on the json representation - interpretation_model = Interpretation.from_dict(interpretation_model_json) - assert interpretation_model != False - - # Construct a model instance of Interpretation by calling from_dict on the json representation - interpretation_model_dict = Interpretation.from_dict(interpretation_model_json).__dict__ - interpretation_model2 = Interpretation(**interpretation_model_dict) - - # Verify the model instances are equivalent - assert interpretation_model == interpretation_model2 - - # Convert model instance back to dict and verify no loss of data - interpretation_model_json2 = interpretation_model.to_dict() - assert interpretation_model_json2 == interpretation_model_json - -class TestModel_Key(): - """ - Test Class for Key - """ - - def test_key_serialization(self): - """ - Test serialization/deserialization for Key - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a Key model - key_model_json = {} - key_model_json['cell_id'] = 'testString' - key_model_json['location'] = location_model - key_model_json['text'] = 'testString' - - # Construct a model instance of Key by calling from_dict on the json representation - key_model = Key.from_dict(key_model_json) - assert key_model != False - - # Construct a model instance of Key by calling from_dict on the json representation - key_model_dict = Key.from_dict(key_model_json).__dict__ - key_model2 = Key(**key_model_dict) - - # Verify the model instances are equivalent - assert key_model == key_model2 - - # Convert model instance back to dict and verify no loss of data - key_model_json2 = key_model.to_dict() - assert key_model_json2 == key_model_json - -class TestModel_KeyValuePair(): - """ - Test Class for KeyValuePair - """ - - def test_key_value_pair_serialization(self): - """ - Test serialization/deserialization for KeyValuePair - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - key_model = {} # Key - key_model['cell_id'] = 'testString' - key_model['location'] = location_model - key_model['text'] = 'testString' - - value_model = {} # Value - value_model['cell_id'] = 'testString' - value_model['location'] = location_model - value_model['text'] = 'testString' - - # Construct a json representation of a KeyValuePair model - key_value_pair_model_json = {} - key_value_pair_model_json['key'] = key_model - key_value_pair_model_json['value'] = [value_model] - - # Construct a model instance of KeyValuePair by calling from_dict on the json representation - key_value_pair_model = KeyValuePair.from_dict(key_value_pair_model_json) - assert key_value_pair_model != False - - # Construct a model instance of KeyValuePair by calling from_dict on the json representation - key_value_pair_model_dict = KeyValuePair.from_dict(key_value_pair_model_json).__dict__ - key_value_pair_model2 = KeyValuePair(**key_value_pair_model_dict) - - # Verify the model instances are equivalent - assert key_value_pair_model == key_value_pair_model2 - - # Convert model instance back to dict and verify no loss of data - key_value_pair_model_json2 = key_value_pair_model.to_dict() - assert key_value_pair_model_json2 == key_value_pair_model_json - -class TestModel_Label(): - """ - Test Class for Label - """ - - def test_label_serialization(self): - """ - Test serialization/deserialization for Label - """ - - # Construct a json representation of a Label model - label_model_json = {} - label_model_json['nature'] = 'testString' - label_model_json['party'] = 'testString' - - # Construct a model instance of Label by calling from_dict on the json representation - label_model = Label.from_dict(label_model_json) - assert label_model != False - - # Construct a model instance of Label by calling from_dict on the json representation - label_model_dict = Label.from_dict(label_model_json).__dict__ - label_model2 = Label(**label_model_dict) - - # Verify the model instances are equivalent - assert label_model == label_model2 - - # Convert model instance back to dict and verify no loss of data - label_model_json2 = label_model.to_dict() - assert label_model_json2 == label_model_json - -class TestModel_LeadingSentence(): - """ - Test Class for LeadingSentence - """ - - def test_leading_sentence_serialization(self): - """ - Test serialization/deserialization for LeadingSentence - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - element_locations_model = {} # ElementLocations - element_locations_model['begin'] = 38 - element_locations_model['end'] = 38 - - # Construct a json representation of a LeadingSentence model - leading_sentence_model_json = {} - leading_sentence_model_json['text'] = 'testString' - leading_sentence_model_json['location'] = location_model - leading_sentence_model_json['element_locations'] = [element_locations_model] - - # Construct a model instance of LeadingSentence by calling from_dict on the json representation - leading_sentence_model = LeadingSentence.from_dict(leading_sentence_model_json) - assert leading_sentence_model != False - - # Construct a model instance of LeadingSentence by calling from_dict on the json representation - leading_sentence_model_dict = LeadingSentence.from_dict(leading_sentence_model_json).__dict__ - leading_sentence_model2 = LeadingSentence(**leading_sentence_model_dict) - - # Verify the model instances are equivalent - assert leading_sentence_model == leading_sentence_model2 - - # Convert model instance back to dict and verify no loss of data - leading_sentence_model_json2 = leading_sentence_model.to_dict() - assert leading_sentence_model_json2 == leading_sentence_model_json - -class TestModel_Location(): - """ - Test Class for Location - """ - - def test_location_serialization(self): - """ - Test serialization/deserialization for Location - """ - - # Construct a json representation of a Location model - location_model_json = {} - location_model_json['begin'] = 26 - location_model_json['end'] = 26 - - # Construct a model instance of Location by calling from_dict on the json representation - location_model = Location.from_dict(location_model_json) - assert location_model != False - - # Construct a model instance of Location by calling from_dict on the json representation - location_model_dict = Location.from_dict(location_model_json).__dict__ - location_model2 = Location(**location_model_dict) - - # Verify the model instances are equivalent - assert location_model == location_model2 - - # Convert model instance back to dict and verify no loss of data - location_model_json2 = location_model.to_dict() - assert location_model_json2 == location_model_json - -class TestModel_Mention(): - """ - Test Class for Mention - """ - - def test_mention_serialization(self): - """ - Test serialization/deserialization for Mention - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a Mention model - mention_model_json = {} - mention_model_json['text'] = 'testString' - mention_model_json['location'] = location_model - - # Construct a model instance of Mention by calling from_dict on the json representation - mention_model = Mention.from_dict(mention_model_json) - assert mention_model != False - - # Construct a model instance of Mention by calling from_dict on the json representation - mention_model_dict = Mention.from_dict(mention_model_json).__dict__ - mention_model2 = Mention(**mention_model_dict) - - # Verify the model instances are equivalent - assert mention_model == mention_model2 - - # Convert model instance back to dict and verify no loss of data - mention_model_json2 = mention_model.to_dict() - assert mention_model_json2 == mention_model_json - -class TestModel_OriginalLabelsIn(): - """ - Test Class for OriginalLabelsIn - """ - - def test_original_labels_in_serialization(self): - """ - Test serialization/deserialization for OriginalLabelsIn - """ - - # Construct dict forms of any model objects needed in order to build this model. - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - type_label_model = {} # TypeLabel - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] - type_label_model['modification'] = 'added' - - category_model = {} # Category - category_model['label'] = 'Amendments' - category_model['provenance_ids'] = ['testString'] - category_model['modification'] = 'added' - - # Construct a json representation of a OriginalLabelsIn model - original_labels_in_model_json = {} - original_labels_in_model_json['types'] = [type_label_model] - original_labels_in_model_json['categories'] = [category_model] - - # Construct a model instance of OriginalLabelsIn by calling from_dict on the json representation - original_labels_in_model = OriginalLabelsIn.from_dict(original_labels_in_model_json) - assert original_labels_in_model != False - - # Construct a model instance of OriginalLabelsIn by calling from_dict on the json representation - original_labels_in_model_dict = OriginalLabelsIn.from_dict(original_labels_in_model_json).__dict__ - original_labels_in_model2 = OriginalLabelsIn(**original_labels_in_model_dict) - - # Verify the model instances are equivalent - assert original_labels_in_model == original_labels_in_model2 - - # Convert model instance back to dict and verify no loss of data - original_labels_in_model_json2 = original_labels_in_model.to_dict() - assert original_labels_in_model_json2 == original_labels_in_model_json - -class TestModel_OriginalLabelsOut(): - """ - Test Class for OriginalLabelsOut - """ - - def test_original_labels_out_serialization(self): - """ - Test serialization/deserialization for OriginalLabelsOut - """ - - # Construct dict forms of any model objects needed in order to build this model. - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - type_label_model = {} # TypeLabel - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] - type_label_model['modification'] = 'added' - - category_model = {} # Category - category_model['label'] = 'Amendments' - category_model['provenance_ids'] = ['testString'] - category_model['modification'] = 'added' - - # Construct a json representation of a OriginalLabelsOut model - original_labels_out_model_json = {} - original_labels_out_model_json['types'] = [type_label_model] - original_labels_out_model_json['categories'] = [category_model] - - # Construct a model instance of OriginalLabelsOut by calling from_dict on the json representation - original_labels_out_model = OriginalLabelsOut.from_dict(original_labels_out_model_json) - assert original_labels_out_model != False - - # Construct a model instance of OriginalLabelsOut by calling from_dict on the json representation - original_labels_out_model_dict = OriginalLabelsOut.from_dict(original_labels_out_model_json).__dict__ - original_labels_out_model2 = OriginalLabelsOut(**original_labels_out_model_dict) - - # Verify the model instances are equivalent - assert original_labels_out_model == original_labels_out_model2 - - # Convert model instance back to dict and verify no loss of data - original_labels_out_model_json2 = original_labels_out_model.to_dict() - assert original_labels_out_model_json2 == original_labels_out_model_json - -class TestModel_Pagination(): - """ - Test Class for Pagination - """ - - def test_pagination_serialization(self): - """ - Test serialization/deserialization for Pagination - """ - - # Construct a json representation of a Pagination model - pagination_model_json = {} - pagination_model_json['refresh_cursor'] = 'testString' - pagination_model_json['next_cursor'] = 'testString' - pagination_model_json['refresh_url'] = 'testString' - pagination_model_json['next_url'] = 'testString' - pagination_model_json['total'] = 26 - - # Construct a model instance of Pagination by calling from_dict on the json representation - pagination_model = Pagination.from_dict(pagination_model_json) - assert pagination_model != False - - # Construct a model instance of Pagination by calling from_dict on the json representation - pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ - pagination_model2 = Pagination(**pagination_model_dict) - - # Verify the model instances are equivalent - assert pagination_model == pagination_model2 - - # Convert model instance back to dict and verify no loss of data - pagination_model_json2 = pagination_model.to_dict() - assert pagination_model_json2 == pagination_model_json - -class TestModel_Paragraphs(): - """ - Test Class for Paragraphs - """ - - def test_paragraphs_serialization(self): - """ - Test serialization/deserialization for Paragraphs - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a Paragraphs model - paragraphs_model_json = {} - paragraphs_model_json['location'] = location_model - - # Construct a model instance of Paragraphs by calling from_dict on the json representation - paragraphs_model = Paragraphs.from_dict(paragraphs_model_json) - assert paragraphs_model != False - - # Construct a model instance of Paragraphs by calling from_dict on the json representation - paragraphs_model_dict = Paragraphs.from_dict(paragraphs_model_json).__dict__ - paragraphs_model2 = Paragraphs(**paragraphs_model_dict) - - # Verify the model instances are equivalent - assert paragraphs_model == paragraphs_model2 - - # Convert model instance back to dict and verify no loss of data - paragraphs_model_json2 = paragraphs_model.to_dict() - assert paragraphs_model_json2 == paragraphs_model_json - -class TestModel_Parties(): - """ - Test Class for Parties - """ - - def test_parties_serialization(self): - """ - Test serialization/deserialization for Parties - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - address_model = {} # Address - address_model['text'] = 'testString' - address_model['location'] = location_model - - contact_model = {} # Contact - contact_model['name'] = 'testString' - contact_model['role'] = 'testString' - - mention_model = {} # Mention - mention_model['text'] = 'testString' - mention_model['location'] = location_model - - # Construct a json representation of a Parties model - parties_model_json = {} - parties_model_json['party'] = 'testString' - parties_model_json['role'] = 'testString' - parties_model_json['importance'] = 'Primary' - parties_model_json['addresses'] = [address_model] - parties_model_json['contacts'] = [contact_model] - parties_model_json['mentions'] = [mention_model] - - # Construct a model instance of Parties by calling from_dict on the json representation - parties_model = Parties.from_dict(parties_model_json) - assert parties_model != False - - # Construct a model instance of Parties by calling from_dict on the json representation - parties_model_dict = Parties.from_dict(parties_model_json).__dict__ - parties_model2 = Parties(**parties_model_dict) - - # Verify the model instances are equivalent - assert parties_model == parties_model2 - - # Convert model instance back to dict and verify no loss of data - parties_model_json2 = parties_model.to_dict() - assert parties_model_json2 == parties_model_json - -class TestModel_PaymentTerms(): - """ - Test Class for PaymentTerms - """ - - def test_payment_terms_serialization(self): - """ - Test serialization/deserialization for PaymentTerms - """ - - # Construct dict forms of any model objects needed in order to build this model. - - interpretation_model = {} # Interpretation - interpretation_model['value'] = 'testString' - interpretation_model['numeric_value'] = 72.5 - interpretation_model['unit'] = 'testString' - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a PaymentTerms model - payment_terms_model_json = {} - payment_terms_model_json['confidence_level'] = 'High' - payment_terms_model_json['text'] = 'testString' - payment_terms_model_json['text_normalized'] = 'testString' - payment_terms_model_json['interpretation'] = interpretation_model - payment_terms_model_json['provenance_ids'] = ['testString'] - payment_terms_model_json['location'] = location_model - - # Construct a model instance of PaymentTerms by calling from_dict on the json representation - payment_terms_model = PaymentTerms.from_dict(payment_terms_model_json) - assert payment_terms_model != False - - # Construct a model instance of PaymentTerms by calling from_dict on the json representation - payment_terms_model_dict = PaymentTerms.from_dict(payment_terms_model_json).__dict__ - payment_terms_model2 = PaymentTerms(**payment_terms_model_dict) - - # Verify the model instances are equivalent - assert payment_terms_model == payment_terms_model2 - - # Convert model instance back to dict and verify no loss of data - payment_terms_model_json2 = payment_terms_model.to_dict() - assert payment_terms_model_json2 == payment_terms_model_json - -class TestModel_RowHeaders(): - """ - Test Class for RowHeaders - """ - - def test_row_headers_serialization(self): - """ - Test serialization/deserialization for RowHeaders - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a RowHeaders model - row_headers_model_json = {} - row_headers_model_json['cell_id'] = 'testString' - row_headers_model_json['location'] = location_model - row_headers_model_json['text'] = 'testString' - row_headers_model_json['text_normalized'] = 'testString' - row_headers_model_json['row_index_begin'] = 26 - row_headers_model_json['row_index_end'] = 26 - row_headers_model_json['column_index_begin'] = 26 - row_headers_model_json['column_index_end'] = 26 - - # Construct a model instance of RowHeaders by calling from_dict on the json representation - row_headers_model = RowHeaders.from_dict(row_headers_model_json) - assert row_headers_model != False - - # Construct a model instance of RowHeaders by calling from_dict on the json representation - row_headers_model_dict = RowHeaders.from_dict(row_headers_model_json).__dict__ - row_headers_model2 = RowHeaders(**row_headers_model_dict) - - # Verify the model instances are equivalent - assert row_headers_model == row_headers_model2 - - # Convert model instance back to dict and verify no loss of data - row_headers_model_json2 = row_headers_model.to_dict() - assert row_headers_model_json2 == row_headers_model_json - -class TestModel_SectionTitle(): - """ - Test Class for SectionTitle - """ - - def test_section_title_serialization(self): - """ - Test serialization/deserialization for SectionTitle - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a SectionTitle model - section_title_model_json = {} - section_title_model_json['text'] = 'testString' - section_title_model_json['location'] = location_model - - # Construct a model instance of SectionTitle by calling from_dict on the json representation - section_title_model = SectionTitle.from_dict(section_title_model_json) - assert section_title_model != False - - # Construct a model instance of SectionTitle by calling from_dict on the json representation - section_title_model_dict = SectionTitle.from_dict(section_title_model_json).__dict__ - section_title_model2 = SectionTitle(**section_title_model_dict) - - # Verify the model instances are equivalent - assert section_title_model == section_title_model2 - - # Convert model instance back to dict and verify no loss of data - section_title_model_json2 = section_title_model.to_dict() - assert section_title_model_json2 == section_title_model_json - -class TestModel_SectionTitles(): - """ - Test Class for SectionTitles - """ - - def test_section_titles_serialization(self): - """ - Test serialization/deserialization for SectionTitles - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - element_locations_model = {} # ElementLocations - element_locations_model['begin'] = 38 - element_locations_model['end'] = 38 - - # Construct a json representation of a SectionTitles model - section_titles_model_json = {} - section_titles_model_json['text'] = 'testString' - section_titles_model_json['location'] = location_model - section_titles_model_json['level'] = 38 - section_titles_model_json['element_locations'] = [element_locations_model] - - # Construct a model instance of SectionTitles by calling from_dict on the json representation - section_titles_model = SectionTitles.from_dict(section_titles_model_json) - assert section_titles_model != False - - # Construct a model instance of SectionTitles by calling from_dict on the json representation - section_titles_model_dict = SectionTitles.from_dict(section_titles_model_json).__dict__ - section_titles_model2 = SectionTitles(**section_titles_model_dict) - - # Verify the model instances are equivalent - assert section_titles_model == section_titles_model2 - - # Convert model instance back to dict and verify no loss of data - section_titles_model_json2 = section_titles_model.to_dict() - assert section_titles_model_json2 == section_titles_model_json - -class TestModel_ShortDoc(): - """ - Test Class for ShortDoc - """ - - def test_short_doc_serialization(self): - """ - Test serialization/deserialization for ShortDoc - """ - - # Construct a json representation of a ShortDoc model - short_doc_model_json = {} - short_doc_model_json['title'] = 'testString' - short_doc_model_json['hash'] = 'testString' - - # Construct a model instance of ShortDoc by calling from_dict on the json representation - short_doc_model = ShortDoc.from_dict(short_doc_model_json) - assert short_doc_model != False - - # Construct a model instance of ShortDoc by calling from_dict on the json representation - short_doc_model_dict = ShortDoc.from_dict(short_doc_model_json).__dict__ - short_doc_model2 = ShortDoc(**short_doc_model_dict) - - # Verify the model instances are equivalent - assert short_doc_model == short_doc_model2 - - # Convert model instance back to dict and verify no loss of data - short_doc_model_json2 = short_doc_model.to_dict() - assert short_doc_model_json2 == short_doc_model_json - -class TestModel_TableHeaders(): - """ - Test Class for TableHeaders - """ - - def test_table_headers_serialization(self): - """ - Test serialization/deserialization for TableHeaders - """ - - # Construct a json representation of a TableHeaders model - table_headers_model_json = {} - table_headers_model_json['cell_id'] = 'testString' - table_headers_model_json['location'] = { 'foo': 'bar' } - table_headers_model_json['text'] = 'testString' - table_headers_model_json['row_index_begin'] = 26 - table_headers_model_json['row_index_end'] = 26 - table_headers_model_json['column_index_begin'] = 26 - table_headers_model_json['column_index_end'] = 26 - - # Construct a model instance of TableHeaders by calling from_dict on the json representation - table_headers_model = TableHeaders.from_dict(table_headers_model_json) - assert table_headers_model != False - - # Construct a model instance of TableHeaders by calling from_dict on the json representation - table_headers_model_dict = TableHeaders.from_dict(table_headers_model_json).__dict__ - table_headers_model2 = TableHeaders(**table_headers_model_dict) - - # Verify the model instances are equivalent - assert table_headers_model == table_headers_model2 - - # Convert model instance back to dict and verify no loss of data - table_headers_model_json2 = table_headers_model.to_dict() - assert table_headers_model_json2 == table_headers_model_json - -class TestModel_TableReturn(): - """ - Test Class for TableReturn - """ - - def test_table_return_serialization(self): - """ - Test serialization/deserialization for TableReturn - """ - - # Construct dict forms of any model objects needed in order to build this model. - - doc_info_model = {} # DocInfo - doc_info_model['html'] = 'testString' - doc_info_model['title'] = 'testString' - doc_info_model['hash'] = 'testString' - - location_model = {} # Location - location_model['begin'] = 872 - location_model['end'] = 5879 - - section_title_model = {} # SectionTitle - section_title_model['text'] = 'testString' - section_title_model['location'] = location_model - - table_title_model = {} # TableTitle - table_title_model['location'] = location_model - table_title_model['text'] = 'testString' - - table_headers_model = {} # TableHeaders - table_headers_model['cell_id'] = 'tableHeader-872-873' - table_headers_model['location'] = { 'foo': 'bar' } - table_headers_model['text'] = 'testString' - table_headers_model['row_index_begin'] = 0 - table_headers_model['row_index_end'] = 0 - table_headers_model['column_index_begin'] = 0 - table_headers_model['column_index_end'] = 0 - - row_headers_model = {} # RowHeaders - row_headers_model['cell_id'] = 'rowHeader-2244-2262' - row_headers_model['location'] = location_model - row_headers_model['text'] = 'Statutory tax rate' - row_headers_model['text_normalized'] = 'Statutory tax rate' - row_headers_model['row_index_begin'] = 2 - row_headers_model['row_index_end'] = 2 - row_headers_model['column_index_begin'] = 0 - row_headers_model['column_index_end'] = 0 - - column_headers_model = {} # ColumnHeaders - column_headers_model['cell_id'] = 'colHeader-1050-1082' - column_headers_model['location'] = { 'foo': 'bar' } - column_headers_model['text'] = 'Three months ended September 30,' - column_headers_model['text_normalized'] = 'Three months ended September 30,' - column_headers_model['row_index_begin'] = 0 - column_headers_model['row_index_end'] = 0 - column_headers_model['column_index_begin'] = 1 - column_headers_model['column_index_end'] = 2 - - attribute_model = {} # Attribute - attribute_model['type'] = 'Currency' - attribute_model['text'] = 'testString' - attribute_model['location'] = location_model - - body_cells_model = {} # BodyCells - body_cells_model['cell_id'] = 'bodyCell-2450-2455' - body_cells_model['location'] = location_model - body_cells_model['text'] = '35.0%' - body_cells_model['row_index_begin'] = 2 - body_cells_model['row_index_end'] = 2 - body_cells_model['column_index_begin'] = 1 - body_cells_model['column_index_end'] = 1 - body_cells_model['row_header_ids'] = ['rowHeader-2244-2262'] - body_cells_model['row_header_texts'] = ['Statutory tax rate'] - body_cells_model['row_header_texts_normalized'] = ['Statutory tax rate'] - body_cells_model['column_header_ids'] = ['colHeader-1050-1082', 'colHeader-1544-1548'] - body_cells_model['column_header_texts'] = ['Three months ended September 30, ', '2005'] - body_cells_model['column_header_texts_normalized'] = ['Three months ended September 30, ', 'Year 1'] - body_cells_model['attributes'] = [attribute_model] - - contexts_model = {} # Contexts - contexts_model['text'] = 'testString' - contexts_model['location'] = location_model - - key_model = {} # Key - key_model['cell_id'] = 'testString' - key_model['location'] = location_model - key_model['text'] = 'testString' - - value_model = {} # Value - value_model['cell_id'] = 'testString' - value_model['location'] = location_model - value_model['text'] = 'testString' - - key_value_pair_model = {} # KeyValuePair - key_value_pair_model['key'] = key_model - key_value_pair_model['value'] = [value_model] - - tables_model = {} # Tables - tables_model['location'] = location_model - tables_model['text'] = '...' - tables_model['section_title'] = section_title_model - tables_model['title'] = table_title_model - tables_model['table_headers'] = [table_headers_model] - tables_model['row_headers'] = [row_headers_model] - tables_model['column_headers'] = [column_headers_model] - tables_model['body_cells'] = [body_cells_model] - tables_model['contexts'] = [contexts_model] - tables_model['key_value_pairs'] = [key_value_pair_model] - - # Construct a json representation of a TableReturn model - table_return_model_json = {} - table_return_model_json['document'] = doc_info_model - table_return_model_json['model_id'] = 'testString' - table_return_model_json['model_version'] = 'testString' - table_return_model_json['tables'] = [tables_model] - - # Construct a model instance of TableReturn by calling from_dict on the json representation - table_return_model = TableReturn.from_dict(table_return_model_json) - assert table_return_model != False - - # Construct a model instance of TableReturn by calling from_dict on the json representation - table_return_model_dict = TableReturn.from_dict(table_return_model_json).__dict__ - table_return_model2 = TableReturn(**table_return_model_dict) - - # Verify the model instances are equivalent - assert table_return_model == table_return_model2 - - # Convert model instance back to dict and verify no loss of data - table_return_model_json2 = table_return_model.to_dict() - assert table_return_model_json2 == table_return_model_json - -class TestModel_TableTitle(): - """ - Test Class for TableTitle - """ - - def test_table_title_serialization(self): - """ - Test serialization/deserialization for TableTitle - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a TableTitle model - table_title_model_json = {} - table_title_model_json['location'] = location_model - table_title_model_json['text'] = 'testString' - - # Construct a model instance of TableTitle by calling from_dict on the json representation - table_title_model = TableTitle.from_dict(table_title_model_json) - assert table_title_model != False - - # Construct a model instance of TableTitle by calling from_dict on the json representation - table_title_model_dict = TableTitle.from_dict(table_title_model_json).__dict__ - table_title_model2 = TableTitle(**table_title_model_dict) - - # Verify the model instances are equivalent - assert table_title_model == table_title_model2 - - # Convert model instance back to dict and verify no loss of data - table_title_model_json2 = table_title_model.to_dict() - assert table_title_model_json2 == table_title_model_json - -class TestModel_Tables(): - """ - Test Class for Tables - """ - - def test_tables_serialization(self): - """ - Test serialization/deserialization for Tables - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - section_title_model = {} # SectionTitle - section_title_model['text'] = 'testString' - section_title_model['location'] = location_model - - table_title_model = {} # TableTitle - table_title_model['location'] = location_model - table_title_model['text'] = 'testString' - - table_headers_model = {} # TableHeaders - table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = { 'foo': 'bar' } - table_headers_model['text'] = 'testString' - table_headers_model['row_index_begin'] = 26 - table_headers_model['row_index_end'] = 26 - table_headers_model['column_index_begin'] = 26 - table_headers_model['column_index_end'] = 26 - - row_headers_model = {} # RowHeaders - row_headers_model['cell_id'] = 'testString' - row_headers_model['location'] = location_model - row_headers_model['text'] = 'testString' - row_headers_model['text_normalized'] = 'testString' - row_headers_model['row_index_begin'] = 26 - row_headers_model['row_index_end'] = 26 - row_headers_model['column_index_begin'] = 26 - row_headers_model['column_index_end'] = 26 - - column_headers_model = {} # ColumnHeaders - column_headers_model['cell_id'] = 'testString' - column_headers_model['location'] = { 'foo': 'bar' } - column_headers_model['text'] = 'testString' - column_headers_model['text_normalized'] = 'testString' - column_headers_model['row_index_begin'] = 26 - column_headers_model['row_index_end'] = 26 - column_headers_model['column_index_begin'] = 26 - column_headers_model['column_index_end'] = 26 - - attribute_model = {} # Attribute - attribute_model['type'] = 'Currency' - attribute_model['text'] = 'testString' - attribute_model['location'] = location_model - - body_cells_model = {} # BodyCells - body_cells_model['cell_id'] = 'testString' - body_cells_model['location'] = location_model - body_cells_model['text'] = 'testString' - body_cells_model['row_index_begin'] = 26 - body_cells_model['row_index_end'] = 26 - body_cells_model['column_index_begin'] = 26 - body_cells_model['column_index_end'] = 26 - body_cells_model['row_header_ids'] = ['testString'] - body_cells_model['row_header_texts'] = ['testString'] - body_cells_model['row_header_texts_normalized'] = ['testString'] - body_cells_model['column_header_ids'] = ['testString'] - body_cells_model['column_header_texts'] = ['testString'] - body_cells_model['column_header_texts_normalized'] = ['testString'] - body_cells_model['attributes'] = [attribute_model] - - contexts_model = {} # Contexts - contexts_model['text'] = 'testString' - contexts_model['location'] = location_model - - key_model = {} # Key - key_model['cell_id'] = 'testString' - key_model['location'] = location_model - key_model['text'] = 'testString' - - value_model = {} # Value - value_model['cell_id'] = 'testString' - value_model['location'] = location_model - value_model['text'] = 'testString' - - key_value_pair_model = {} # KeyValuePair - key_value_pair_model['key'] = key_model - key_value_pair_model['value'] = [value_model] - - # Construct a json representation of a Tables model - tables_model_json = {} - tables_model_json['location'] = location_model - tables_model_json['text'] = 'testString' - tables_model_json['section_title'] = section_title_model - tables_model_json['title'] = table_title_model - tables_model_json['table_headers'] = [table_headers_model] - tables_model_json['row_headers'] = [row_headers_model] - tables_model_json['column_headers'] = [column_headers_model] - tables_model_json['body_cells'] = [body_cells_model] - tables_model_json['contexts'] = [contexts_model] - tables_model_json['key_value_pairs'] = [key_value_pair_model] - - # Construct a model instance of Tables by calling from_dict on the json representation - tables_model = Tables.from_dict(tables_model_json) - assert tables_model != False - - # Construct a model instance of Tables by calling from_dict on the json representation - tables_model_dict = Tables.from_dict(tables_model_json).__dict__ - tables_model2 = Tables(**tables_model_dict) - - # Verify the model instances are equivalent - assert tables_model == tables_model2 - - # Convert model instance back to dict and verify no loss of data - tables_model_json2 = tables_model.to_dict() - assert tables_model_json2 == tables_model_json - -class TestModel_TerminationDates(): - """ - Test Class for TerminationDates - """ - - def test_termination_dates_serialization(self): - """ - Test serialization/deserialization for TerminationDates - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a TerminationDates model - termination_dates_model_json = {} - termination_dates_model_json['confidence_level'] = 'High' - termination_dates_model_json['text'] = 'testString' - termination_dates_model_json['text_normalized'] = 'testString' - termination_dates_model_json['provenance_ids'] = ['testString'] - termination_dates_model_json['location'] = location_model - - # Construct a model instance of TerminationDates by calling from_dict on the json representation - termination_dates_model = TerminationDates.from_dict(termination_dates_model_json) - assert termination_dates_model != False - - # Construct a model instance of TerminationDates by calling from_dict on the json representation - termination_dates_model_dict = TerminationDates.from_dict(termination_dates_model_json).__dict__ - termination_dates_model2 = TerminationDates(**termination_dates_model_dict) - - # Verify the model instances are equivalent - assert termination_dates_model == termination_dates_model2 - - # Convert model instance back to dict and verify no loss of data - termination_dates_model_json2 = termination_dates_model.to_dict() - assert termination_dates_model_json2 == termination_dates_model_json - -class TestModel_TypeLabel(): - """ - Test Class for TypeLabel - """ - - def test_type_label_serialization(self): - """ - Test serialization/deserialization for TypeLabel - """ - - # Construct dict forms of any model objects needed in order to build this model. - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - # Construct a json representation of a TypeLabel model - type_label_model_json = {} - type_label_model_json['label'] = label_model - type_label_model_json['provenance_ids'] = ['testString'] - type_label_model_json['modification'] = 'added' - - # Construct a model instance of TypeLabel by calling from_dict on the json representation - type_label_model = TypeLabel.from_dict(type_label_model_json) - assert type_label_model != False - - # Construct a model instance of TypeLabel by calling from_dict on the json representation - type_label_model_dict = TypeLabel.from_dict(type_label_model_json).__dict__ - type_label_model2 = TypeLabel(**type_label_model_dict) - - # Verify the model instances are equivalent - assert type_label_model == type_label_model2 - - # Convert model instance back to dict and verify no loss of data - type_label_model_json2 = type_label_model.to_dict() - assert type_label_model_json2 == type_label_model_json - -class TestModel_TypeLabelComparison(): - """ - Test Class for TypeLabelComparison - """ - - def test_type_label_comparison_serialization(self): - """ - Test serialization/deserialization for TypeLabelComparison - """ - - # Construct dict forms of any model objects needed in order to build this model. - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - # Construct a json representation of a TypeLabelComparison model - type_label_comparison_model_json = {} - type_label_comparison_model_json['label'] = label_model - - # Construct a model instance of TypeLabelComparison by calling from_dict on the json representation - type_label_comparison_model = TypeLabelComparison.from_dict(type_label_comparison_model_json) - assert type_label_comparison_model != False - - # Construct a model instance of TypeLabelComparison by calling from_dict on the json representation - type_label_comparison_model_dict = TypeLabelComparison.from_dict(type_label_comparison_model_json).__dict__ - type_label_comparison_model2 = TypeLabelComparison(**type_label_comparison_model_dict) - - # Verify the model instances are equivalent - assert type_label_comparison_model == type_label_comparison_model2 - - # Convert model instance back to dict and verify no loss of data - type_label_comparison_model_json2 = type_label_comparison_model.to_dict() - assert type_label_comparison_model_json2 == type_label_comparison_model_json - -class TestModel_UnalignedElement(): - """ - Test Class for UnalignedElement - """ - - def test_unaligned_element_serialization(self): - """ - Test serialization/deserialization for UnalignedElement - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - type_label_comparison_model = {} # TypeLabelComparison - type_label_comparison_model['label'] = label_model - - category_comparison_model = {} # CategoryComparison - category_comparison_model['label'] = 'Amendments' - - attribute_model = {} # Attribute - attribute_model['type'] = 'Currency' - attribute_model['text'] = 'testString' - attribute_model['location'] = location_model - - # Construct a json representation of a UnalignedElement model - unaligned_element_model_json = {} - unaligned_element_model_json['document_label'] = 'testString' - unaligned_element_model_json['location'] = location_model - unaligned_element_model_json['text'] = 'testString' - unaligned_element_model_json['types'] = [type_label_comparison_model] - unaligned_element_model_json['categories'] = [category_comparison_model] - unaligned_element_model_json['attributes'] = [attribute_model] - - # Construct a model instance of UnalignedElement by calling from_dict on the json representation - unaligned_element_model = UnalignedElement.from_dict(unaligned_element_model_json) - assert unaligned_element_model != False - - # Construct a model instance of UnalignedElement by calling from_dict on the json representation - unaligned_element_model_dict = UnalignedElement.from_dict(unaligned_element_model_json).__dict__ - unaligned_element_model2 = UnalignedElement(**unaligned_element_model_dict) - - # Verify the model instances are equivalent - assert unaligned_element_model == unaligned_element_model2 - - # Convert model instance back to dict and verify no loss of data - unaligned_element_model_json2 = unaligned_element_model.to_dict() - assert unaligned_element_model_json2 == unaligned_element_model_json - -class TestModel_UpdatedLabelsIn(): - """ - Test Class for UpdatedLabelsIn - """ - - def test_updated_labels_in_serialization(self): - """ - Test serialization/deserialization for UpdatedLabelsIn - """ - - # Construct dict forms of any model objects needed in order to build this model. - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - type_label_model = {} # TypeLabel - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] - type_label_model['modification'] = 'added' - - category_model = {} # Category - category_model['label'] = 'Amendments' - category_model['provenance_ids'] = ['testString'] - category_model['modification'] = 'added' - - # Construct a json representation of a UpdatedLabelsIn model - updated_labels_in_model_json = {} - updated_labels_in_model_json['types'] = [type_label_model] - updated_labels_in_model_json['categories'] = [category_model] - - # Construct a model instance of UpdatedLabelsIn by calling from_dict on the json representation - updated_labels_in_model = UpdatedLabelsIn.from_dict(updated_labels_in_model_json) - assert updated_labels_in_model != False - - # Construct a model instance of UpdatedLabelsIn by calling from_dict on the json representation - updated_labels_in_model_dict = UpdatedLabelsIn.from_dict(updated_labels_in_model_json).__dict__ - updated_labels_in_model2 = UpdatedLabelsIn(**updated_labels_in_model_dict) - - # Verify the model instances are equivalent - assert updated_labels_in_model == updated_labels_in_model2 - - # Convert model instance back to dict and verify no loss of data - updated_labels_in_model_json2 = updated_labels_in_model.to_dict() - assert updated_labels_in_model_json2 == updated_labels_in_model_json - -class TestModel_UpdatedLabelsOut(): - """ - Test Class for UpdatedLabelsOut - """ - - def test_updated_labels_out_serialization(self): - """ - Test serialization/deserialization for UpdatedLabelsOut - """ - - # Construct dict forms of any model objects needed in order to build this model. - - label_model = {} # Label - label_model['nature'] = 'testString' - label_model['party'] = 'testString' - - type_label_model = {} # TypeLabel - type_label_model['label'] = label_model - type_label_model['provenance_ids'] = ['testString'] - type_label_model['modification'] = 'added' - - category_model = {} # Category - category_model['label'] = 'Amendments' - category_model['provenance_ids'] = ['testString'] - category_model['modification'] = 'added' - - # Construct a json representation of a UpdatedLabelsOut model - updated_labels_out_model_json = {} - updated_labels_out_model_json['types'] = [type_label_model] - updated_labels_out_model_json['categories'] = [category_model] - - # Construct a model instance of UpdatedLabelsOut by calling from_dict on the json representation - updated_labels_out_model = UpdatedLabelsOut.from_dict(updated_labels_out_model_json) - assert updated_labels_out_model != False - - # Construct a model instance of UpdatedLabelsOut by calling from_dict on the json representation - updated_labels_out_model_dict = UpdatedLabelsOut.from_dict(updated_labels_out_model_json).__dict__ - updated_labels_out_model2 = UpdatedLabelsOut(**updated_labels_out_model_dict) - - # Verify the model instances are equivalent - assert updated_labels_out_model == updated_labels_out_model2 - - # Convert model instance back to dict and verify no loss of data - updated_labels_out_model_json2 = updated_labels_out_model.to_dict() - assert updated_labels_out_model_json2 == updated_labels_out_model_json - -class TestModel_Value(): - """ - Test Class for Value - """ - - def test_value_serialization(self): - """ - Test serialization/deserialization for Value - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['begin'] = 26 - location_model['end'] = 26 - - # Construct a json representation of a Value model - value_model_json = {} - value_model_json['cell_id'] = 'testString' - value_model_json['location'] = location_model - value_model_json['text'] = 'testString' - - # Construct a model instance of Value by calling from_dict on the json representation - value_model = Value.from_dict(value_model_json) - assert value_model != False - - # Construct a model instance of Value by calling from_dict on the json representation - value_model_dict = Value.from_dict(value_model_json).__dict__ - value_model2 = Value(**value_model_dict) - - # Verify the model instances are equivalent - assert value_model == value_model2 - - # Convert model instance back to dict and verify no loss of data - value_model_json2 = value_model.to_dict() - assert value_model_json2 == value_model_json - - -# endregion -############################################################################## -# End of Model Tests -############################################################################## diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 96f2d9cb5..1b6b9efb5 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2021. +# (C) Copyright IBM Corp. 2016, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -37,11 +37,38 @@ _service = DiscoveryV1( authenticator=NoAuthAuthenticator(), version=version - ) +) _base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' _service.set_service_url(_base_url) + +def preprocess_url(operation_path: str): + """ + Returns the request url associated with the specified operation path. + This will be base_url concatenated with a quoted version of operation_path. + The returned request URL is used to register the mock response so it needs + to match the request URL that is formed by the requests library. + """ + # First, unquote the path since it might have some quoted/escaped characters in it + # due to how the generator inserts the operation paths into the unit test code. + operation_path = urllib.parse.unquote(operation_path) + + # Next, quote the path using urllib so that we approximate what will + # happen during request processing. + operation_path = urllib.parse.quote(operation_path, safe='/') + + # Finally, form the request URL from the base URL and operation path. + request_url = _base_url + operation_path + + # If the request url does NOT end with a /, then just return it as-is. + # Otherwise, return a regular expression that matches one or more trailing /. + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + ############################################################################## # Start of Service: Environments ############################################################################## @@ -52,24 +79,13 @@ class TestCreateEnvironment(): Test Class for create_environment """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_environment_all_params(self): """ create_environment() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments') + url = preprocess_url('/v1/environments') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.POST, url, @@ -99,6 +115,14 @@ def test_create_environment_all_params(self): assert req_body['description'] == 'testString' assert req_body['size'] == 'LT' + def test_create_environment_all_params_with_retries(self): + # Enable retries and run test_create_environment_all_params. + _service.enable_retries() + self.test_create_environment_all_params() + + # Disable retries and run test_create_environment_all_params. + _service.disable_retries() + self.test_create_environment_all_params() @responses.activate def test_create_environment_value_error(self): @@ -106,7 +130,7 @@ def test_create_environment_value_error(self): test_create_environment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments') + url = preprocess_url('/v1/environments') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.POST, url, @@ -129,30 +153,27 @@ def test_create_environment_value_error(self): _service.create_environment(**req_copy) + def test_create_environment_value_error_with_retries(self): + # Enable retries and run test_create_environment_value_error. + _service.enable_retries() + self.test_create_environment_value_error() + + # Disable retries and run test_create_environment_value_error. + _service.disable_retries() + self.test_create_environment_value_error() class TestListEnvironments(): """ Test Class for list_environments """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_environments_all_params(self): """ list_environments() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments') + url = preprocess_url('/v1/environments') mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' responses.add(responses.GET, url, @@ -177,6 +198,14 @@ def test_list_environments_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'name={}'.format(name) in query_string + def test_list_environments_all_params_with_retries(self): + # Enable retries and run test_list_environments_all_params. + _service.enable_retries() + self.test_list_environments_all_params() + + # Disable retries and run test_list_environments_all_params. + _service.disable_retries() + self.test_list_environments_all_params() @responses.activate def test_list_environments_required_params(self): @@ -184,7 +213,7 @@ def test_list_environments_required_params(self): test_list_environments_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments') + url = preprocess_url('/v1/environments') mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' responses.add(responses.GET, url, @@ -200,6 +229,14 @@ def test_list_environments_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_environments_required_params_with_retries(self): + # Enable retries and run test_list_environments_required_params. + _service.enable_retries() + self.test_list_environments_required_params() + + # Disable retries and run test_list_environments_required_params. + _service.disable_retries() + self.test_list_environments_required_params() @responses.activate def test_list_environments_value_error(self): @@ -207,7 +244,7 @@ def test_list_environments_value_error(self): test_list_environments_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments') + url = preprocess_url('/v1/environments') mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' responses.add(responses.GET, url, @@ -224,30 +261,27 @@ def test_list_environments_value_error(self): _service.list_environments(**req_copy) + def test_list_environments_value_error_with_retries(self): + # Enable retries and run test_list_environments_value_error. + _service.enable_retries() + self.test_list_environments_value_error() + + # Disable retries and run test_list_environments_value_error. + _service.disable_retries() + self.test_list_environments_value_error() class TestGetEnvironment(): """ Test Class for get_environment """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_environment_all_params(self): """ get_environment() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString') + url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.GET, url, @@ -268,6 +302,14 @@ def test_get_environment_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_environment_all_params_with_retries(self): + # Enable retries and run test_get_environment_all_params. + _service.enable_retries() + self.test_get_environment_all_params() + + # Disable retries and run test_get_environment_all_params. + _service.disable_retries() + self.test_get_environment_all_params() @responses.activate def test_get_environment_value_error(self): @@ -275,7 +317,7 @@ def test_get_environment_value_error(self): test_get_environment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString') + url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.GET, url, @@ -296,30 +338,27 @@ def test_get_environment_value_error(self): _service.get_environment(**req_copy) + def test_get_environment_value_error_with_retries(self): + # Enable retries and run test_get_environment_value_error. + _service.enable_retries() + self.test_get_environment_value_error() + + # Disable retries and run test_get_environment_value_error. + _service.disable_retries() + self.test_get_environment_value_error() class TestUpdateEnvironment(): """ Test Class for update_environment """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_environment_all_params(self): """ update_environment() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString') + url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.PUT, url, @@ -351,6 +390,14 @@ def test_update_environment_all_params(self): assert req_body['description'] == 'testString' assert req_body['size'] == 'S' + def test_update_environment_all_params_with_retries(self): + # Enable retries and run test_update_environment_all_params. + _service.enable_retries() + self.test_update_environment_all_params() + + # Disable retries and run test_update_environment_all_params. + _service.disable_retries() + self.test_update_environment_all_params() @responses.activate def test_update_environment_value_error(self): @@ -358,7 +405,7 @@ def test_update_environment_value_error(self): test_update_environment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString') + url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' responses.add(responses.PUT, url, @@ -382,30 +429,27 @@ def test_update_environment_value_error(self): _service.update_environment(**req_copy) + def test_update_environment_value_error_with_retries(self): + # Enable retries and run test_update_environment_value_error. + _service.enable_retries() + self.test_update_environment_value_error() + + # Disable retries and run test_update_environment_value_error. + _service.disable_retries() + self.test_update_environment_value_error() class TestDeleteEnvironment(): """ Test Class for delete_environment """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_environment_all_params(self): """ delete_environment() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString') + url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -426,6 +470,14 @@ def test_delete_environment_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_environment_all_params_with_retries(self): + # Enable retries and run test_delete_environment_all_params. + _service.enable_retries() + self.test_delete_environment_all_params() + + # Disable retries and run test_delete_environment_all_params. + _service.disable_retries() + self.test_delete_environment_all_params() @responses.activate def test_delete_environment_value_error(self): @@ -433,7 +485,7 @@ def test_delete_environment_value_error(self): test_delete_environment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString') + url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -454,30 +506,27 @@ def test_delete_environment_value_error(self): _service.delete_environment(**req_copy) + def test_delete_environment_value_error_with_retries(self): + # Enable retries and run test_delete_environment_value_error. + _service.enable_retries() + self.test_delete_environment_value_error() + + # Disable retries and run test_delete_environment_value_error. + _service.disable_retries() + self.test_delete_environment_value_error() class TestListFields(): """ Test Class for list_fields """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_fields_all_params(self): """ list_fields() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/fields') + url = preprocess_url('/v1/environments/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' responses.add(responses.GET, url, @@ -504,6 +553,14 @@ def test_list_fields_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string + def test_list_fields_all_params_with_retries(self): + # Enable retries and run test_list_fields_all_params. + _service.enable_retries() + self.test_list_fields_all_params() + + # Disable retries and run test_list_fields_all_params. + _service.disable_retries() + self.test_list_fields_all_params() @responses.activate def test_list_fields_value_error(self): @@ -511,7 +568,7 @@ def test_list_fields_value_error(self): test_list_fields_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/fields') + url = preprocess_url('/v1/environments/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' responses.add(responses.GET, url, @@ -534,6 +591,14 @@ def test_list_fields_value_error(self): _service.list_fields(**req_copy) + def test_list_fields_value_error_with_retries(self): + # Enable retries and run test_list_fields_value_error. + _service.enable_retries() + self.test_list_fields_value_error() + + # Disable retries and run test_list_fields_value_error. + _service.disable_retries() + self.test_list_fields_value_error() # endregion ############################################################################## @@ -550,24 +615,13 @@ class TestCreateConfiguration(): Test Class for create_configuration """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_configuration_all_params(self): """ create_configuration() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') + url = preprocess_url('/v1/environments/testString/configurations') mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.POST, url, @@ -794,6 +848,14 @@ def test_create_configuration_all_params(self): assert req_body['normalizations'] == [normalization_operation_model] assert req_body['source'] == source_model + def test_create_configuration_all_params_with_retries(self): + # Enable retries and run test_create_configuration_all_params. + _service.enable_retries() + self.test_create_configuration_all_params() + + # Disable retries and run test_create_configuration_all_params. + _service.disable_retries() + self.test_create_configuration_all_params() @responses.activate def test_create_configuration_value_error(self): @@ -801,7 +863,7 @@ def test_create_configuration_value_error(self): test_create_configuration_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') + url = preprocess_url('/v1/environments/testString/configurations') mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.POST, url, @@ -1015,30 +1077,27 @@ def test_create_configuration_value_error(self): _service.create_configuration(**req_copy) + def test_create_configuration_value_error_with_retries(self): + # Enable retries and run test_create_configuration_value_error. + _service.enable_retries() + self.test_create_configuration_value_error() + + # Disable retries and run test_create_configuration_value_error. + _service.disable_retries() + self.test_create_configuration_value_error() class TestListConfigurations(): """ Test Class for list_configurations """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_configurations_all_params(self): """ list_configurations() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') + url = preprocess_url('/v1/environments/testString/configurations') mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, @@ -1065,6 +1124,14 @@ def test_list_configurations_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'name={}'.format(name) in query_string + def test_list_configurations_all_params_with_retries(self): + # Enable retries and run test_list_configurations_all_params. + _service.enable_retries() + self.test_list_configurations_all_params() + + # Disable retries and run test_list_configurations_all_params. + _service.disable_retries() + self.test_list_configurations_all_params() @responses.activate def test_list_configurations_required_params(self): @@ -1072,7 +1139,7 @@ def test_list_configurations_required_params(self): test_list_configurations_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') + url = preprocess_url('/v1/environments/testString/configurations') mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, @@ -1093,6 +1160,14 @@ def test_list_configurations_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_configurations_required_params_with_retries(self): + # Enable retries and run test_list_configurations_required_params. + _service.enable_retries() + self.test_list_configurations_required_params() + + # Disable retries and run test_list_configurations_required_params. + _service.disable_retries() + self.test_list_configurations_required_params() @responses.activate def test_list_configurations_value_error(self): @@ -1100,7 +1175,7 @@ def test_list_configurations_value_error(self): test_list_configurations_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations') + url = preprocess_url('/v1/environments/testString/configurations') mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, @@ -1121,30 +1196,27 @@ def test_list_configurations_value_error(self): _service.list_configurations(**req_copy) + def test_list_configurations_value_error_with_retries(self): + # Enable retries and run test_list_configurations_value_error. + _service.enable_retries() + self.test_list_configurations_value_error() + + # Disable retries and run test_list_configurations_value_error. + _service.disable_retries() + self.test_list_configurations_value_error() class TestGetConfiguration(): """ Test Class for get_configuration """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_configuration_all_params(self): """ get_configuration() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + url = preprocess_url('/v1/environments/testString/configurations/testString') mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.GET, url, @@ -1167,6 +1239,14 @@ def test_get_configuration_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_configuration_all_params_with_retries(self): + # Enable retries and run test_get_configuration_all_params. + _service.enable_retries() + self.test_get_configuration_all_params() + + # Disable retries and run test_get_configuration_all_params. + _service.disable_retries() + self.test_get_configuration_all_params() @responses.activate def test_get_configuration_value_error(self): @@ -1174,7 +1254,7 @@ def test_get_configuration_value_error(self): test_get_configuration_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + url = preprocess_url('/v1/environments/testString/configurations/testString') mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.GET, url, @@ -1197,30 +1277,27 @@ def test_get_configuration_value_error(self): _service.get_configuration(**req_copy) + def test_get_configuration_value_error_with_retries(self): + # Enable retries and run test_get_configuration_value_error. + _service.enable_retries() + self.test_get_configuration_value_error() + + # Disable retries and run test_get_configuration_value_error. + _service.disable_retries() + self.test_get_configuration_value_error() class TestUpdateConfiguration(): """ Test Class for update_configuration """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_configuration_all_params(self): """ update_configuration() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + url = preprocess_url('/v1/environments/testString/configurations/testString') mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.PUT, url, @@ -1449,6 +1526,14 @@ def test_update_configuration_all_params(self): assert req_body['normalizations'] == [normalization_operation_model] assert req_body['source'] == source_model + def test_update_configuration_all_params_with_retries(self): + # Enable retries and run test_update_configuration_all_params. + _service.enable_retries() + self.test_update_configuration_all_params() + + # Disable retries and run test_update_configuration_all_params. + _service.disable_retries() + self.test_update_configuration_all_params() @responses.activate def test_update_configuration_value_error(self): @@ -1456,7 +1541,7 @@ def test_update_configuration_value_error(self): test_update_configuration_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + url = preprocess_url('/v1/environments/testString/configurations/testString') mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.PUT, url, @@ -1672,30 +1757,27 @@ def test_update_configuration_value_error(self): _service.update_configuration(**req_copy) + def test_update_configuration_value_error_with_retries(self): + # Enable retries and run test_update_configuration_value_error. + _service.enable_retries() + self.test_update_configuration_value_error() + + # Disable retries and run test_update_configuration_value_error. + _service.disable_retries() + self.test_update_configuration_value_error() class TestDeleteConfiguration(): """ Test Class for delete_configuration """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_configuration_all_params(self): """ delete_configuration() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + url = preprocess_url('/v1/environments/testString/configurations/testString') mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.DELETE, url, @@ -1718,6 +1800,14 @@ def test_delete_configuration_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_configuration_all_params_with_retries(self): + # Enable retries and run test_delete_configuration_all_params. + _service.enable_retries() + self.test_delete_configuration_all_params() + + # Disable retries and run test_delete_configuration_all_params. + _service.disable_retries() + self.test_delete_configuration_all_params() @responses.activate def test_delete_configuration_value_error(self): @@ -1725,7 +1815,7 @@ def test_delete_configuration_value_error(self): test_delete_configuration_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/configurations/testString') + url = preprocess_url('/v1/environments/testString/configurations/testString') mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.DELETE, url, @@ -1748,6 +1838,14 @@ def test_delete_configuration_value_error(self): _service.delete_configuration(**req_copy) + def test_delete_configuration_value_error_with_retries(self): + # Enable retries and run test_delete_configuration_value_error. + _service.enable_retries() + self.test_delete_configuration_value_error() + + # Disable retries and run test_delete_configuration_value_error. + _service.disable_retries() + self.test_delete_configuration_value_error() # endregion ############################################################################## @@ -1764,24 +1862,13 @@ class TestCreateCollection(): Test Class for create_collection """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_collection_all_params(self): """ create_collection() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') + url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.POST, url, @@ -1816,6 +1903,14 @@ def test_create_collection_all_params(self): assert req_body['configuration_id'] == 'testString' assert req_body['language'] == 'en' + def test_create_collection_all_params_with_retries(self): + # Enable retries and run test_create_collection_all_params. + _service.enable_retries() + self.test_create_collection_all_params() + + # Disable retries and run test_create_collection_all_params. + _service.disable_retries() + self.test_create_collection_all_params() @responses.activate def test_create_collection_value_error(self): @@ -1823,7 +1918,7 @@ def test_create_collection_value_error(self): test_create_collection_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') + url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.POST, url, @@ -1849,30 +1944,27 @@ def test_create_collection_value_error(self): _service.create_collection(**req_copy) + def test_create_collection_value_error_with_retries(self): + # Enable retries and run test_create_collection_value_error. + _service.enable_retries() + self.test_create_collection_value_error() + + # Disable retries and run test_create_collection_value_error. + _service.disable_retries() + self.test_create_collection_value_error() class TestListCollections(): """ Test Class for list_collections """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_collections_all_params(self): """ list_collections() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') + url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' responses.add(responses.GET, url, @@ -1899,6 +1991,14 @@ def test_list_collections_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'name={}'.format(name) in query_string + def test_list_collections_all_params_with_retries(self): + # Enable retries and run test_list_collections_all_params. + _service.enable_retries() + self.test_list_collections_all_params() + + # Disable retries and run test_list_collections_all_params. + _service.disable_retries() + self.test_list_collections_all_params() @responses.activate def test_list_collections_required_params(self): @@ -1906,7 +2006,7 @@ def test_list_collections_required_params(self): test_list_collections_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') + url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' responses.add(responses.GET, url, @@ -1927,6 +2027,14 @@ def test_list_collections_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_collections_required_params_with_retries(self): + # Enable retries and run test_list_collections_required_params. + _service.enable_retries() + self.test_list_collections_required_params() + + # Disable retries and run test_list_collections_required_params. + _service.disable_retries() + self.test_list_collections_required_params() @responses.activate def test_list_collections_value_error(self): @@ -1934,7 +2042,7 @@ def test_list_collections_value_error(self): test_list_collections_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections') + url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' responses.add(responses.GET, url, @@ -1955,30 +2063,27 @@ def test_list_collections_value_error(self): _service.list_collections(**req_copy) + def test_list_collections_value_error_with_retries(self): + # Enable retries and run test_list_collections_value_error. + _service.enable_retries() + self.test_list_collections_value_error() + + # Disable retries and run test_list_collections_value_error. + _service.disable_retries() + self.test_list_collections_value_error() class TestGetCollection(): """ Test Class for get_collection """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_collection_all_params(self): """ get_collection() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') + url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.GET, url, @@ -2001,6 +2106,14 @@ def test_get_collection_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_collection_all_params_with_retries(self): + # Enable retries and run test_get_collection_all_params. + _service.enable_retries() + self.test_get_collection_all_params() + + # Disable retries and run test_get_collection_all_params. + _service.disable_retries() + self.test_get_collection_all_params() @responses.activate def test_get_collection_value_error(self): @@ -2008,7 +2121,7 @@ def test_get_collection_value_error(self): test_get_collection_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') + url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.GET, url, @@ -2031,30 +2144,27 @@ def test_get_collection_value_error(self): _service.get_collection(**req_copy) + def test_get_collection_value_error_with_retries(self): + # Enable retries and run test_get_collection_value_error. + _service.enable_retries() + self.test_get_collection_value_error() + + # Disable retries and run test_get_collection_value_error. + _service.disable_retries() + self.test_get_collection_value_error() class TestUpdateCollection(): """ Test Class for update_collection """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_collection_all_params(self): """ update_collection() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') + url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.PUT, url, @@ -2088,6 +2198,14 @@ def test_update_collection_all_params(self): assert req_body['description'] == 'testString' assert req_body['configuration_id'] == 'testString' + def test_update_collection_all_params_with_retries(self): + # Enable retries and run test_update_collection_all_params. + _service.enable_retries() + self.test_update_collection_all_params() + + # Disable retries and run test_update_collection_all_params. + _service.disable_retries() + self.test_update_collection_all_params() @responses.activate def test_update_collection_value_error(self): @@ -2095,7 +2213,7 @@ def test_update_collection_value_error(self): test_update_collection_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') + url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' responses.add(responses.PUT, url, @@ -2122,30 +2240,27 @@ def test_update_collection_value_error(self): _service.update_collection(**req_copy) + def test_update_collection_value_error_with_retries(self): + # Enable retries and run test_update_collection_value_error. + _service.enable_retries() + self.test_update_collection_value_error() + + # Disable retries and run test_update_collection_value_error. + _service.disable_retries() + self.test_update_collection_value_error() class TestDeleteCollection(): """ Test Class for delete_collection """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_collection_all_params(self): """ delete_collection() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') + url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -2168,6 +2283,14 @@ def test_delete_collection_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_collection_all_params_with_retries(self): + # Enable retries and run test_delete_collection_all_params. + _service.enable_retries() + self.test_delete_collection_all_params() + + # Disable retries and run test_delete_collection_all_params. + _service.disable_retries() + self.test_delete_collection_all_params() @responses.activate def test_delete_collection_value_error(self): @@ -2175,7 +2298,7 @@ def test_delete_collection_value_error(self): test_delete_collection_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString') + url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -2198,30 +2321,27 @@ def test_delete_collection_value_error(self): _service.delete_collection(**req_copy) + def test_delete_collection_value_error_with_retries(self): + # Enable retries and run test_delete_collection_value_error. + _service.enable_retries() + self.test_delete_collection_value_error() + + # Disable retries and run test_delete_collection_value_error. + _service.disable_retries() + self.test_delete_collection_value_error() class TestListCollectionFields(): """ Test Class for list_collection_fields """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_collection_fields_all_params(self): """ list_collection_fields() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/fields') + url = preprocess_url('/v1/environments/testString/collections/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' responses.add(responses.GET, url, @@ -2244,6 +2364,14 @@ def test_list_collection_fields_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_collection_fields_all_params_with_retries(self): + # Enable retries and run test_list_collection_fields_all_params. + _service.enable_retries() + self.test_list_collection_fields_all_params() + + # Disable retries and run test_list_collection_fields_all_params. + _service.disable_retries() + self.test_list_collection_fields_all_params() @responses.activate def test_list_collection_fields_value_error(self): @@ -2251,7 +2379,7 @@ def test_list_collection_fields_value_error(self): test_list_collection_fields_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/fields') + url = preprocess_url('/v1/environments/testString/collections/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' responses.add(responses.GET, url, @@ -2274,6 +2402,14 @@ def test_list_collection_fields_value_error(self): _service.list_collection_fields(**req_copy) + def test_list_collection_fields_value_error_with_retries(self): + # Enable retries and run test_list_collection_fields_value_error. + _service.enable_retries() + self.test_list_collection_fields_value_error() + + # Disable retries and run test_list_collection_fields_value_error. + _service.disable_retries() + self.test_list_collection_fields_value_error() # endregion ############################################################################## @@ -2290,24 +2426,13 @@ class TestListExpansions(): Test Class for list_expansions """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_expansions_all_params(self): """ list_expansions() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') + url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.GET, url, @@ -2330,6 +2455,14 @@ def test_list_expansions_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_expansions_all_params_with_retries(self): + # Enable retries and run test_list_expansions_all_params. + _service.enable_retries() + self.test_list_expansions_all_params() + + # Disable retries and run test_list_expansions_all_params. + _service.disable_retries() + self.test_list_expansions_all_params() @responses.activate def test_list_expansions_value_error(self): @@ -2337,7 +2470,7 @@ def test_list_expansions_value_error(self): test_list_expansions_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') + url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.GET, url, @@ -2360,30 +2493,27 @@ def test_list_expansions_value_error(self): _service.list_expansions(**req_copy) + def test_list_expansions_value_error_with_retries(self): + # Enable retries and run test_list_expansions_value_error. + _service.enable_retries() + self.test_list_expansions_value_error() + + # Disable retries and run test_list_expansions_value_error. + _service.disable_retries() + self.test_list_expansions_value_error() class TestCreateExpansions(): """ Test Class for create_expansions """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_expansions_all_params(self): """ create_expansions() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') + url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.POST, url, @@ -2416,6 +2546,14 @@ def test_create_expansions_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['expansions'] == [expansion_model] + def test_create_expansions_all_params_with_retries(self): + # Enable retries and run test_create_expansions_all_params. + _service.enable_retries() + self.test_create_expansions_all_params() + + # Disable retries and run test_create_expansions_all_params. + _service.disable_retries() + self.test_create_expansions_all_params() @responses.activate def test_create_expansions_value_error(self): @@ -2423,7 +2561,7 @@ def test_create_expansions_value_error(self): test_create_expansions_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') + url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.POST, url, @@ -2453,30 +2591,27 @@ def test_create_expansions_value_error(self): _service.create_expansions(**req_copy) + def test_create_expansions_value_error_with_retries(self): + # Enable retries and run test_create_expansions_value_error. + _service.enable_retries() + self.test_create_expansions_value_error() + + # Disable retries and run test_create_expansions_value_error. + _service.disable_retries() + self.test_create_expansions_value_error() class TestDeleteExpansions(): """ Test Class for delete_expansions """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_expansions_all_params(self): """ delete_expansions() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') + url = preprocess_url('/v1/environments/testString/collections/testString/expansions') responses.add(responses.DELETE, url, status=204) @@ -2496,6 +2631,14 @@ def test_delete_expansions_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_expansions_all_params_with_retries(self): + # Enable retries and run test_delete_expansions_all_params. + _service.enable_retries() + self.test_delete_expansions_all_params() + + # Disable retries and run test_delete_expansions_all_params. + _service.disable_retries() + self.test_delete_expansions_all_params() @responses.activate def test_delete_expansions_value_error(self): @@ -2503,7 +2646,7 @@ def test_delete_expansions_value_error(self): test_delete_expansions_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/expansions') + url = preprocess_url('/v1/environments/testString/collections/testString/expansions') responses.add(responses.DELETE, url, status=204) @@ -2523,30 +2666,27 @@ def test_delete_expansions_value_error(self): _service.delete_expansions(**req_copy) + def test_delete_expansions_value_error_with_retries(self): + # Enable retries and run test_delete_expansions_value_error. + _service.enable_retries() + self.test_delete_expansions_value_error() + + # Disable retries and run test_delete_expansions_value_error. + _service.disable_retries() + self.test_delete_expansions_value_error() class TestGetTokenizationDictionaryStatus(): """ Test Class for get_tokenization_dictionary_status """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_tokenization_dictionary_status_all_params(self): """ get_tokenization_dictionary_status() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.GET, url, @@ -2569,6 +2709,14 @@ def test_get_tokenization_dictionary_status_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_tokenization_dictionary_status_all_params_with_retries(self): + # Enable retries and run test_get_tokenization_dictionary_status_all_params. + _service.enable_retries() + self.test_get_tokenization_dictionary_status_all_params() + + # Disable retries and run test_get_tokenization_dictionary_status_all_params. + _service.disable_retries() + self.test_get_tokenization_dictionary_status_all_params() @responses.activate def test_get_tokenization_dictionary_status_value_error(self): @@ -2576,7 +2724,7 @@ def test_get_tokenization_dictionary_status_value_error(self): test_get_tokenization_dictionary_status_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.GET, url, @@ -2599,30 +2747,27 @@ def test_get_tokenization_dictionary_status_value_error(self): _service.get_tokenization_dictionary_status(**req_copy) + def test_get_tokenization_dictionary_status_value_error_with_retries(self): + # Enable retries and run test_get_tokenization_dictionary_status_value_error. + _service.enable_retries() + self.test_get_tokenization_dictionary_status_value_error() + + # Disable retries and run test_get_tokenization_dictionary_status_value_error. + _service.disable_retries() + self.test_get_tokenization_dictionary_status_value_error() class TestCreateTokenizationDictionary(): """ Test Class for create_tokenization_dictionary """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_tokenization_dictionary_all_params(self): """ create_tokenization_dictionary() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2657,6 +2802,14 @@ def test_create_tokenization_dictionary_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['tokenization_rules'] == [token_dict_rule_model] + def test_create_tokenization_dictionary_all_params_with_retries(self): + # Enable retries and run test_create_tokenization_dictionary_all_params. + _service.enable_retries() + self.test_create_tokenization_dictionary_all_params() + + # Disable retries and run test_create_tokenization_dictionary_all_params. + _service.disable_retries() + self.test_create_tokenization_dictionary_all_params() @responses.activate def test_create_tokenization_dictionary_required_params(self): @@ -2664,7 +2817,7 @@ def test_create_tokenization_dictionary_required_params(self): test_create_tokenization_dictionary_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2687,6 +2840,14 @@ def test_create_tokenization_dictionary_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 202 + def test_create_tokenization_dictionary_required_params_with_retries(self): + # Enable retries and run test_create_tokenization_dictionary_required_params. + _service.enable_retries() + self.test_create_tokenization_dictionary_required_params() + + # Disable retries and run test_create_tokenization_dictionary_required_params. + _service.disable_retries() + self.test_create_tokenization_dictionary_required_params() @responses.activate def test_create_tokenization_dictionary_value_error(self): @@ -2694,7 +2855,7 @@ def test_create_tokenization_dictionary_value_error(self): test_create_tokenization_dictionary_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2717,30 +2878,27 @@ def test_create_tokenization_dictionary_value_error(self): _service.create_tokenization_dictionary(**req_copy) + def test_create_tokenization_dictionary_value_error_with_retries(self): + # Enable retries and run test_create_tokenization_dictionary_value_error. + _service.enable_retries() + self.test_create_tokenization_dictionary_value_error() + + # Disable retries and run test_create_tokenization_dictionary_value_error. + _service.disable_retries() + self.test_create_tokenization_dictionary_value_error() class TestDeleteTokenizationDictionary(): """ Test Class for delete_tokenization_dictionary """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_tokenization_dictionary_all_params(self): """ delete_tokenization_dictionary() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') responses.add(responses.DELETE, url, status=200) @@ -2760,6 +2918,14 @@ def test_delete_tokenization_dictionary_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_tokenization_dictionary_all_params_with_retries(self): + # Enable retries and run test_delete_tokenization_dictionary_all_params. + _service.enable_retries() + self.test_delete_tokenization_dictionary_all_params() + + # Disable retries and run test_delete_tokenization_dictionary_all_params. + _service.disable_retries() + self.test_delete_tokenization_dictionary_all_params() @responses.activate def test_delete_tokenization_dictionary_value_error(self): @@ -2767,7 +2933,7 @@ def test_delete_tokenization_dictionary_value_error(self): test_delete_tokenization_dictionary_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') responses.add(responses.DELETE, url, status=200) @@ -2787,30 +2953,27 @@ def test_delete_tokenization_dictionary_value_error(self): _service.delete_tokenization_dictionary(**req_copy) + def test_delete_tokenization_dictionary_value_error_with_retries(self): + # Enable retries and run test_delete_tokenization_dictionary_value_error. + _service.enable_retries() + self.test_delete_tokenization_dictionary_value_error() + + # Disable retries and run test_delete_tokenization_dictionary_value_error. + _service.disable_retries() + self.test_delete_tokenization_dictionary_value_error() class TestGetStopwordListStatus(): """ Test Class for get_stopword_list_status """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_stopword_list_status_all_params(self): """ get_stopword_list_status() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.GET, url, @@ -2833,6 +2996,14 @@ def test_get_stopword_list_status_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_stopword_list_status_all_params_with_retries(self): + # Enable retries and run test_get_stopword_list_status_all_params. + _service.enable_retries() + self.test_get_stopword_list_status_all_params() + + # Disable retries and run test_get_stopword_list_status_all_params. + _service.disable_retries() + self.test_get_stopword_list_status_all_params() @responses.activate def test_get_stopword_list_status_value_error(self): @@ -2840,7 +3011,7 @@ def test_get_stopword_list_status_value_error(self): test_get_stopword_list_status_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.GET, url, @@ -2863,30 +3034,27 @@ def test_get_stopword_list_status_value_error(self): _service.get_stopword_list_status(**req_copy) + def test_get_stopword_list_status_value_error_with_retries(self): + # Enable retries and run test_get_stopword_list_status_value_error. + _service.enable_retries() + self.test_get_stopword_list_status_value_error() + + # Disable retries and run test_get_stopword_list_status_value_error. + _service.disable_retries() + self.test_get_stopword_list_status_value_error() class TestCreateStopwordList(): """ Test Class for create_stopword_list """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_stopword_list_all_params(self): """ create_stopword_list() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2913,6 +3081,14 @@ def test_create_stopword_list_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_create_stopword_list_all_params_with_retries(self): + # Enable retries and run test_create_stopword_list_all_params. + _service.enable_retries() + self.test_create_stopword_list_all_params() + + # Disable retries and run test_create_stopword_list_all_params. + _service.disable_retries() + self.test_create_stopword_list_all_params() @responses.activate def test_create_stopword_list_required_params(self): @@ -2920,7 +3096,7 @@ def test_create_stopword_list_required_params(self): test_create_stopword_list_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2947,6 +3123,14 @@ def test_create_stopword_list_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_create_stopword_list_required_params_with_retries(self): + # Enable retries and run test_create_stopword_list_required_params. + _service.enable_retries() + self.test_create_stopword_list_required_params() + + # Disable retries and run test_create_stopword_list_required_params. + _service.disable_retries() + self.test_create_stopword_list_required_params() @responses.activate def test_create_stopword_list_value_error(self): @@ -2954,7 +3138,7 @@ def test_create_stopword_list_value_error(self): test_create_stopword_list_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' responses.add(responses.POST, url, @@ -2980,30 +3164,27 @@ def test_create_stopword_list_value_error(self): _service.create_stopword_list(**req_copy) + def test_create_stopword_list_value_error_with_retries(self): + # Enable retries and run test_create_stopword_list_value_error. + _service.enable_retries() + self.test_create_stopword_list_value_error() + + # Disable retries and run test_create_stopword_list_value_error. + _service.disable_retries() + self.test_create_stopword_list_value_error() class TestDeleteStopwordList(): """ Test Class for delete_stopword_list """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_stopword_list_all_params(self): """ delete_stopword_list() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') responses.add(responses.DELETE, url, status=200) @@ -3023,6 +3204,14 @@ def test_delete_stopword_list_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_stopword_list_all_params_with_retries(self): + # Enable retries and run test_delete_stopword_list_all_params. + _service.enable_retries() + self.test_delete_stopword_list_all_params() + + # Disable retries and run test_delete_stopword_list_all_params. + _service.disable_retries() + self.test_delete_stopword_list_all_params() @responses.activate def test_delete_stopword_list_value_error(self): @@ -3030,7 +3219,7 @@ def test_delete_stopword_list_value_error(self): test_delete_stopword_list_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/word_lists/stopwords') + url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') responses.add(responses.DELETE, url, status=200) @@ -3050,6 +3239,14 @@ def test_delete_stopword_list_value_error(self): _service.delete_stopword_list(**req_copy) + def test_delete_stopword_list_value_error_with_retries(self): + # Enable retries and run test_delete_stopword_list_value_error. + _service.enable_retries() + self.test_delete_stopword_list_value_error() + + # Disable retries and run test_delete_stopword_list_value_error. + _service.disable_retries() + self.test_delete_stopword_list_value_error() # endregion ############################################################################## @@ -3066,24 +3263,13 @@ class TestAddDocument(): Test Class for add_document """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_add_document_all_params(self): """ add_document() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents') + url = preprocess_url('/v1/environments/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, @@ -3114,6 +3300,14 @@ def test_add_document_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 202 + def test_add_document_all_params_with_retries(self): + # Enable retries and run test_add_document_all_params. + _service.enable_retries() + self.test_add_document_all_params() + + # Disable retries and run test_add_document_all_params. + _service.disable_retries() + self.test_add_document_all_params() @responses.activate def test_add_document_required_params(self): @@ -3121,7 +3315,7 @@ def test_add_document_required_params(self): test_add_document_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents') + url = preprocess_url('/v1/environments/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, @@ -3144,6 +3338,14 @@ def test_add_document_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 202 + def test_add_document_required_params_with_retries(self): + # Enable retries and run test_add_document_required_params. + _service.enable_retries() + self.test_add_document_required_params() + + # Disable retries and run test_add_document_required_params. + _service.disable_retries() + self.test_add_document_required_params() @responses.activate def test_add_document_value_error(self): @@ -3151,7 +3353,7 @@ def test_add_document_value_error(self): test_add_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents') + url = preprocess_url('/v1/environments/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, @@ -3174,30 +3376,27 @@ def test_add_document_value_error(self): _service.add_document(**req_copy) + def test_add_document_value_error_with_retries(self): + # Enable retries and run test_add_document_value_error. + _service.enable_retries() + self.test_add_document_value_error() + + # Disable retries and run test_add_document_value_error. + _service.disable_retries() + self.test_add_document_value_error() class TestGetDocumentStatus(): """ Test Class for get_document_status """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_document_status_all_params(self): """ get_document_status() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -3222,6 +3421,14 @@ def test_get_document_status_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_document_status_all_params_with_retries(self): + # Enable retries and run test_get_document_status_all_params. + _service.enable_retries() + self.test_get_document_status_all_params() + + # Disable retries and run test_get_document_status_all_params. + _service.disable_retries() + self.test_get_document_status_all_params() @responses.activate def test_get_document_status_value_error(self): @@ -3229,7 +3436,7 @@ def test_get_document_status_value_error(self): test_get_document_status_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -3254,30 +3461,27 @@ def test_get_document_status_value_error(self): _service.get_document_status(**req_copy) + def test_get_document_status_value_error_with_retries(self): + # Enable retries and run test_get_document_status_value_error. + _service.enable_retries() + self.test_get_document_status_value_error() + + # Disable retries and run test_get_document_status_value_error. + _service.disable_retries() + self.test_get_document_status_value_error() class TestUpdateDocument(): """ Test Class for update_document """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_document_all_params(self): """ update_document() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, @@ -3310,6 +3514,14 @@ def test_update_document_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 202 + def test_update_document_all_params_with_retries(self): + # Enable retries and run test_update_document_all_params. + _service.enable_retries() + self.test_update_document_all_params() + + # Disable retries and run test_update_document_all_params. + _service.disable_retries() + self.test_update_document_all_params() @responses.activate def test_update_document_required_params(self): @@ -3317,7 +3529,7 @@ def test_update_document_required_params(self): test_update_document_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, @@ -3342,6 +3554,14 @@ def test_update_document_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 202 + def test_update_document_required_params_with_retries(self): + # Enable retries and run test_update_document_required_params. + _service.enable_retries() + self.test_update_document_required_params() + + # Disable retries and run test_update_document_required_params. + _service.disable_retries() + self.test_update_document_required_params() @responses.activate def test_update_document_value_error(self): @@ -3349,7 +3569,7 @@ def test_update_document_value_error(self): test_update_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.POST, url, @@ -3374,30 +3594,27 @@ def test_update_document_value_error(self): _service.update_document(**req_copy) + def test_update_document_value_error_with_retries(self): + # Enable retries and run test_update_document_value_error. + _service.enable_retries() + self.test_update_document_value_error() + + # Disable retries and run test_update_document_value_error. + _service.disable_retries() + self.test_update_document_value_error() class TestDeleteDocument(): """ Test Class for delete_document """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_document_all_params(self): """ delete_document() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -3422,6 +3639,14 @@ def test_delete_document_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_document_all_params_with_retries(self): + # Enable retries and run test_delete_document_all_params. + _service.enable_retries() + self.test_delete_document_all_params() + + # Disable retries and run test_delete_document_all_params. + _service.disable_retries() + self.test_delete_document_all_params() @responses.activate def test_delete_document_value_error(self): @@ -3429,7 +3654,7 @@ def test_delete_document_value_error(self): test_delete_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/documents/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -3454,6 +3679,14 @@ def test_delete_document_value_error(self): _service.delete_document(**req_copy) + def test_delete_document_value_error_with_retries(self): + # Enable retries and run test_delete_document_value_error. + _service.enable_retries() + self.test_delete_document_value_error() + + # Disable retries and run test_delete_document_value_error. + _service.disable_retries() + self.test_delete_document_value_error() # endregion ############################################################################## @@ -3470,25 +3703,14 @@ class TestQuery(): Test Class for query """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_query_all_params(self): """ query() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + url = preprocess_url('/v1/environments/testString/collections/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3574,6 +3796,14 @@ def test_query_all_params(self): assert req_body['bias'] == 'testString' assert req_body['spelling_suggestions'] == False + def test_query_all_params_with_retries(self): + # Enable retries and run test_query_all_params. + _service.enable_retries() + self.test_query_all_params() + + # Disable retries and run test_query_all_params. + _service.disable_retries() + self.test_query_all_params() @responses.activate def test_query_required_params(self): @@ -3581,8 +3811,8 @@ def test_query_required_params(self): test_query_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + url = preprocess_url('/v1/environments/testString/collections/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3604,6 +3834,14 @@ def test_query_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_query_required_params_with_retries(self): + # Enable retries and run test_query_required_params. + _service.enable_retries() + self.test_query_required_params() + + # Disable retries and run test_query_required_params. + _service.disable_retries() + self.test_query_required_params() @responses.activate def test_query_value_error(self): @@ -3611,8 +3849,8 @@ def test_query_value_error(self): test_query_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + url = preprocess_url('/v1/environments/testString/collections/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3634,31 +3872,28 @@ def test_query_value_error(self): _service.query(**req_copy) + def test_query_value_error_with_retries(self): + # Enable retries and run test_query_value_error. + _service.enable_retries() + self.test_query_value_error() + + # Disable retries and run test_query_value_error. + _service.disable_retries() + self.test_query_value_error() class TestQueryNotices(): """ Test Class for query_notices """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_query_notices_all_params(self): """ query_notices() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = preprocess_url('/v1/environments/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3734,6 +3969,14 @@ def test_query_notices_all_params(self): assert 'similar.document_ids={}'.format(','.join(similar_document_ids)) in query_string assert 'similar.fields={}'.format(','.join(similar_fields)) in query_string + def test_query_notices_all_params_with_retries(self): + # Enable retries and run test_query_notices_all_params. + _service.enable_retries() + self.test_query_notices_all_params() + + # Disable retries and run test_query_notices_all_params. + _service.disable_retries() + self.test_query_notices_all_params() @responses.activate def test_query_notices_required_params(self): @@ -3741,8 +3984,8 @@ def test_query_notices_required_params(self): test_query_notices_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = preprocess_url('/v1/environments/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3764,6 +4007,14 @@ def test_query_notices_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_query_notices_required_params_with_retries(self): + # Enable retries and run test_query_notices_required_params. + _service.enable_retries() + self.test_query_notices_required_params() + + # Disable retries and run test_query_notices_required_params. + _service.disable_retries() + self.test_query_notices_required_params() @responses.activate def test_query_notices_value_error(self): @@ -3771,8 +4022,8 @@ def test_query_notices_value_error(self): test_query_notices_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = preprocess_url('/v1/environments/testString/collections/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3794,31 +4045,28 @@ def test_query_notices_value_error(self): _service.query_notices(**req_copy) + def test_query_notices_value_error_with_retries(self): + # Enable retries and run test_query_notices_value_error. + _service.enable_retries() + self.test_query_notices_value_error() + + # Disable retries and run test_query_notices_value_error. + _service.disable_retries() + self.test_query_notices_value_error() class TestFederatedQuery(): """ Test Class for federated_query """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_federated_query_all_params(self): """ federated_query() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + url = preprocess_url('/v1/environments/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3902,6 +4150,14 @@ def test_federated_query_all_params(self): assert req_body['similar.fields'] == 'testString' assert req_body['bias'] == 'testString' + def test_federated_query_all_params_with_retries(self): + # Enable retries and run test_federated_query_all_params. + _service.enable_retries() + self.test_federated_query_all_params() + + # Disable retries and run test_federated_query_all_params. + _service.disable_retries() + self.test_federated_query_all_params() @responses.activate def test_federated_query_required_params(self): @@ -3909,8 +4165,8 @@ def test_federated_query_required_params(self): test_federated_query_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + url = preprocess_url('/v1/environments/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3992,6 +4248,14 @@ def test_federated_query_required_params(self): assert req_body['similar.fields'] == 'testString' assert req_body['bias'] == 'testString' + def test_federated_query_required_params_with_retries(self): + # Enable retries and run test_federated_query_required_params. + _service.enable_retries() + self.test_federated_query_required_params() + + # Disable retries and run test_federated_query_required_params. + _service.disable_retries() + self.test_federated_query_required_params() @responses.activate def test_federated_query_value_error(self): @@ -3999,8 +4263,8 @@ def test_federated_query_value_error(self): test_federated_query_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + url = preprocess_url('/v1/environments/testString/query') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -4041,31 +4305,28 @@ def test_federated_query_value_error(self): _service.federated_query(**req_copy) + def test_federated_query_value_error_with_retries(self): + # Enable retries and run test_federated_query_value_error. + _service.enable_retries() + self.test_federated_query_value_error() + + # Disable retries and run test_federated_query_value_error. + _service.disable_retries() + self.test_federated_query_value_error() class TestFederatedQueryNotices(): """ Test Class for federated_query_notices """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_federated_query_notices_all_params(self): """ federated_query_notices() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = preprocess_url('/v1/environments/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4130,6 +4391,14 @@ def test_federated_query_notices_all_params(self): assert 'similar.document_ids={}'.format(','.join(similar_document_ids)) in query_string assert 'similar.fields={}'.format(','.join(similar_fields)) in query_string + def test_federated_query_notices_all_params_with_retries(self): + # Enable retries and run test_federated_query_notices_all_params. + _service.enable_retries() + self.test_federated_query_notices_all_params() + + # Disable retries and run test_federated_query_notices_all_params. + _service.disable_retries() + self.test_federated_query_notices_all_params() @responses.activate def test_federated_query_notices_required_params(self): @@ -4137,8 +4406,8 @@ def test_federated_query_notices_required_params(self): test_federated_query_notices_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = preprocess_url('/v1/environments/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4164,6 +4433,14 @@ def test_federated_query_notices_required_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string + def test_federated_query_notices_required_params_with_retries(self): + # Enable retries and run test_federated_query_notices_required_params. + _service.enable_retries() + self.test_federated_query_notices_required_params() + + # Disable retries and run test_federated_query_notices_required_params. + _service.disable_retries() + self.test_federated_query_notices_required_params() @responses.activate def test_federated_query_notices_value_error(self): @@ -4171,8 +4448,8 @@ def test_federated_query_notices_value_error(self): test_federated_query_notices_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "histogram", "matching_results": 16, "field": "field", "interval": 8}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + url = preprocess_url('/v1/environments/testString/notices') + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4194,30 +4471,27 @@ def test_federated_query_notices_value_error(self): _service.federated_query_notices(**req_copy) + def test_federated_query_notices_value_error_with_retries(self): + # Enable retries and run test_federated_query_notices_value_error. + _service.enable_retries() + self.test_federated_query_notices_value_error() + + # Disable retries and run test_federated_query_notices_value_error. + _service.disable_retries() + self.test_federated_query_notices_value_error() class TestGetAutocompletion(): """ Test Class for get_autocompletion """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_autocompletion_all_params(self): """ get_autocompletion() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/autocompletion') + url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -4252,6 +4526,14 @@ def test_get_autocompletion_all_params(self): assert 'field={}'.format(field) in query_string assert 'count={}'.format(count) in query_string + def test_get_autocompletion_all_params_with_retries(self): + # Enable retries and run test_get_autocompletion_all_params. + _service.enable_retries() + self.test_get_autocompletion_all_params() + + # Disable retries and run test_get_autocompletion_all_params. + _service.disable_retries() + self.test_get_autocompletion_all_params() @responses.activate def test_get_autocompletion_required_params(self): @@ -4259,7 +4541,7 @@ def test_get_autocompletion_required_params(self): test_get_autocompletion_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/autocompletion') + url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -4288,6 +4570,14 @@ def test_get_autocompletion_required_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'prefix={}'.format(prefix) in query_string + def test_get_autocompletion_required_params_with_retries(self): + # Enable retries and run test_get_autocompletion_required_params. + _service.enable_retries() + self.test_get_autocompletion_required_params() + + # Disable retries and run test_get_autocompletion_required_params. + _service.disable_retries() + self.test_get_autocompletion_required_params() @responses.activate def test_get_autocompletion_value_error(self): @@ -4295,7 +4585,7 @@ def test_get_autocompletion_value_error(self): test_get_autocompletion_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/autocompletion') + url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -4320,6 +4610,14 @@ def test_get_autocompletion_value_error(self): _service.get_autocompletion(**req_copy) + def test_get_autocompletion_value_error_with_retries(self): + # Enable retries and run test_get_autocompletion_value_error. + _service.enable_retries() + self.test_get_autocompletion_value_error() + + # Disable retries and run test_get_autocompletion_value_error. + _service.disable_retries() + self.test_get_autocompletion_value_error() # endregion ############################################################################## @@ -4336,24 +4634,13 @@ class TestListTrainingData(): Test Class for list_training_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_training_data_all_params(self): """ list_training_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' responses.add(responses.GET, url, @@ -4376,6 +4663,14 @@ def test_list_training_data_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_training_data_all_params_with_retries(self): + # Enable retries and run test_list_training_data_all_params. + _service.enable_retries() + self.test_list_training_data_all_params() + + # Disable retries and run test_list_training_data_all_params. + _service.disable_retries() + self.test_list_training_data_all_params() @responses.activate def test_list_training_data_value_error(self): @@ -4383,7 +4678,7 @@ def test_list_training_data_value_error(self): test_list_training_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' responses.add(responses.GET, url, @@ -4406,30 +4701,27 @@ def test_list_training_data_value_error(self): _service.list_training_data(**req_copy) + def test_list_training_data_value_error_with_retries(self): + # Enable retries and run test_list_training_data_value_error. + _service.enable_retries() + self.test_list_training_data_value_error() + + # Disable retries and run test_list_training_data_value_error. + _service.disable_retries() + self.test_list_training_data_value_error() class TestAddTrainingData(): """ Test Class for add_training_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_add_training_data_all_params(self): """ add_training_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.POST, url, @@ -4469,6 +4761,14 @@ def test_add_training_data_all_params(self): assert req_body['filter'] == 'testString' assert req_body['examples'] == [training_example_model] + def test_add_training_data_all_params_with_retries(self): + # Enable retries and run test_add_training_data_all_params. + _service.enable_retries() + self.test_add_training_data_all_params() + + # Disable retries and run test_add_training_data_all_params. + _service.disable_retries() + self.test_add_training_data_all_params() @responses.activate def test_add_training_data_value_error(self): @@ -4476,7 +4776,7 @@ def test_add_training_data_value_error(self): test_add_training_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.POST, url, @@ -4508,30 +4808,27 @@ def test_add_training_data_value_error(self): _service.add_training_data(**req_copy) + def test_add_training_data_value_error_with_retries(self): + # Enable retries and run test_add_training_data_value_error. + _service.enable_retries() + self.test_add_training_data_value_error() + + # Disable retries and run test_add_training_data_value_error. + _service.disable_retries() + self.test_add_training_data_value_error() class TestDeleteAllTrainingData(): """ Test Class for delete_all_training_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_all_training_data_all_params(self): """ delete_all_training_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data') responses.add(responses.DELETE, url, status=204) @@ -4551,6 +4848,14 @@ def test_delete_all_training_data_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_all_training_data_all_params_with_retries(self): + # Enable retries and run test_delete_all_training_data_all_params. + _service.enable_retries() + self.test_delete_all_training_data_all_params() + + # Disable retries and run test_delete_all_training_data_all_params. + _service.disable_retries() + self.test_delete_all_training_data_all_params() @responses.activate def test_delete_all_training_data_value_error(self): @@ -4558,7 +4863,7 @@ def test_delete_all_training_data_value_error(self): test_delete_all_training_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data') responses.add(responses.DELETE, url, status=204) @@ -4578,30 +4883,27 @@ def test_delete_all_training_data_value_error(self): _service.delete_all_training_data(**req_copy) + def test_delete_all_training_data_value_error_with_retries(self): + # Enable retries and run test_delete_all_training_data_value_error. + _service.enable_retries() + self.test_delete_all_training_data_value_error() + + # Disable retries and run test_delete_all_training_data_value_error. + _service.disable_retries() + self.test_delete_all_training_data_value_error() class TestGetTrainingData(): """ Test Class for get_training_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_training_data_all_params(self): """ get_training_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.GET, url, @@ -4626,6 +4928,14 @@ def test_get_training_data_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_training_data_all_params_with_retries(self): + # Enable retries and run test_get_training_data_all_params. + _service.enable_retries() + self.test_get_training_data_all_params() + + # Disable retries and run test_get_training_data_all_params. + _service.disable_retries() + self.test_get_training_data_all_params() @responses.activate def test_get_training_data_value_error(self): @@ -4633,7 +4943,7 @@ def test_get_training_data_value_error(self): test_get_training_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.GET, url, @@ -4658,30 +4968,27 @@ def test_get_training_data_value_error(self): _service.get_training_data(**req_copy) + def test_get_training_data_value_error_with_retries(self): + # Enable retries and run test_get_training_data_value_error. + _service.enable_retries() + self.test_get_training_data_value_error() + + # Disable retries and run test_get_training_data_value_error. + _service.disable_retries() + self.test_get_training_data_value_error() class TestDeleteTrainingData(): """ Test Class for delete_training_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_training_data_all_params(self): """ delete_training_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') responses.add(responses.DELETE, url, status=204) @@ -4703,6 +5010,14 @@ def test_delete_training_data_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_training_data_all_params_with_retries(self): + # Enable retries and run test_delete_training_data_all_params. + _service.enable_retries() + self.test_delete_training_data_all_params() + + # Disable retries and run test_delete_training_data_all_params. + _service.disable_retries() + self.test_delete_training_data_all_params() @responses.activate def test_delete_training_data_value_error(self): @@ -4710,7 +5025,7 @@ def test_delete_training_data_value_error(self): test_delete_training_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') responses.add(responses.DELETE, url, status=204) @@ -4732,30 +5047,27 @@ def test_delete_training_data_value_error(self): _service.delete_training_data(**req_copy) + def test_delete_training_data_value_error_with_retries(self): + # Enable retries and run test_delete_training_data_value_error. + _service.enable_retries() + self.test_delete_training_data_value_error() + + # Disable retries and run test_delete_training_data_value_error. + _service.disable_retries() + self.test_delete_training_data_value_error() class TestListTrainingExamples(): """ Test Class for list_training_examples """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_training_examples_all_params(self): """ list_training_examples() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.GET, url, @@ -4780,6 +5092,14 @@ def test_list_training_examples_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_training_examples_all_params_with_retries(self): + # Enable retries and run test_list_training_examples_all_params. + _service.enable_retries() + self.test_list_training_examples_all_params() + + # Disable retries and run test_list_training_examples_all_params. + _service.disable_retries() + self.test_list_training_examples_all_params() @responses.activate def test_list_training_examples_value_error(self): @@ -4787,7 +5107,7 @@ def test_list_training_examples_value_error(self): test_list_training_examples_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' responses.add(responses.GET, url, @@ -4812,30 +5132,27 @@ def test_list_training_examples_value_error(self): _service.list_training_examples(**req_copy) + def test_list_training_examples_value_error_with_retries(self): + # Enable retries and run test_list_training_examples_value_error. + _service.enable_retries() + self.test_list_training_examples_value_error() + + # Disable retries and run test_list_training_examples_value_error. + _service.disable_retries() + self.test_list_training_examples_value_error() class TestCreateTrainingExample(): """ Test Class for create_training_example """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_training_example_all_params(self): """ create_training_example() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.POST, url, @@ -4871,6 +5188,14 @@ def test_create_training_example_all_params(self): assert req_body['cross_reference'] == 'testString' assert req_body['relevance'] == 38 + def test_create_training_example_all_params_with_retries(self): + # Enable retries and run test_create_training_example_all_params. + _service.enable_retries() + self.test_create_training_example_all_params() + + # Disable retries and run test_create_training_example_all_params. + _service.disable_retries() + self.test_create_training_example_all_params() @responses.activate def test_create_training_example_value_error(self): @@ -4878,7 +5203,7 @@ def test_create_training_example_value_error(self): test_create_training_example_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.POST, url, @@ -4906,30 +5231,27 @@ def test_create_training_example_value_error(self): _service.create_training_example(**req_copy) + def test_create_training_example_value_error_with_retries(self): + # Enable retries and run test_create_training_example_value_error. + _service.enable_retries() + self.test_create_training_example_value_error() + + # Disable retries and run test_create_training_example_value_error. + _service.disable_retries() + self.test_create_training_example_value_error() class TestDeleteTrainingExample(): """ Test Class for delete_training_example """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_training_example_all_params(self): """ delete_training_example() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') responses.add(responses.DELETE, url, status=204) @@ -4953,6 +5275,14 @@ def test_delete_training_example_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_training_example_all_params_with_retries(self): + # Enable retries and run test_delete_training_example_all_params. + _service.enable_retries() + self.test_delete_training_example_all_params() + + # Disable retries and run test_delete_training_example_all_params. + _service.disable_retries() + self.test_delete_training_example_all_params() @responses.activate def test_delete_training_example_value_error(self): @@ -4960,7 +5290,7 @@ def test_delete_training_example_value_error(self): test_delete_training_example_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') responses.add(responses.DELETE, url, status=204) @@ -4984,30 +5314,27 @@ def test_delete_training_example_value_error(self): _service.delete_training_example(**req_copy) + def test_delete_training_example_value_error_with_retries(self): + # Enable retries and run test_delete_training_example_value_error. + _service.enable_retries() + self.test_delete_training_example_value_error() + + # Disable retries and run test_delete_training_example_value_error. + _service.disable_retries() + self.test_delete_training_example_value_error() class TestUpdateTrainingExample(): """ Test Class for update_training_example """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_training_example_all_params(self): """ update_training_example() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.PUT, url, @@ -5042,6 +5369,14 @@ def test_update_training_example_all_params(self): assert req_body['cross_reference'] == 'testString' assert req_body['relevance'] == 38 + def test_update_training_example_all_params_with_retries(self): + # Enable retries and run test_update_training_example_all_params. + _service.enable_retries() + self.test_update_training_example_all_params() + + # Disable retries and run test_update_training_example_all_params. + _service.disable_retries() + self.test_update_training_example_all_params() @responses.activate def test_update_training_example_value_error(self): @@ -5049,7 +5384,7 @@ def test_update_training_example_value_error(self): test_update_training_example_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.PUT, url, @@ -5078,30 +5413,27 @@ def test_update_training_example_value_error(self): _service.update_training_example(**req_copy) + def test_update_training_example_value_error_with_retries(self): + # Enable retries and run test_update_training_example_value_error. + _service.enable_retries() + self.test_update_training_example_value_error() + + # Disable retries and run test_update_training_example_value_error. + _service.disable_retries() + self.test_update_training_example_value_error() class TestGetTrainingExample(): """ Test Class for get_training_example """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_training_example_all_params(self): """ get_training_example() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.GET, url, @@ -5128,6 +5460,14 @@ def test_get_training_example_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_training_example_all_params_with_retries(self): + # Enable retries and run test_get_training_example_all_params. + _service.enable_retries() + self.test_get_training_example_all_params() + + # Disable retries and run test_get_training_example_all_params. + _service.disable_retries() + self.test_get_training_example_all_params() @responses.activate def test_get_training_example_value_error(self): @@ -5135,7 +5475,7 @@ def test_get_training_example_value_error(self): test_get_training_example_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/collections/testString/training_data/testString/examples/testString') + url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' responses.add(responses.GET, url, @@ -5162,6 +5502,14 @@ def test_get_training_example_value_error(self): _service.get_training_example(**req_copy) + def test_get_training_example_value_error_with_retries(self): + # Enable retries and run test_get_training_example_value_error. + _service.enable_retries() + self.test_get_training_example_value_error() + + # Disable retries and run test_get_training_example_value_error. + _service.disable_retries() + self.test_get_training_example_value_error() # endregion ############################################################################## @@ -5178,24 +5526,13 @@ class TestDeleteUserData(): Test Class for delete_user_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_user_data_all_params(self): """ delete_user_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/user_data') + url = preprocess_url('/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -5217,6 +5554,14 @@ def test_delete_user_data_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string + def test_delete_user_data_all_params_with_retries(self): + # Enable retries and run test_delete_user_data_all_params. + _service.enable_retries() + self.test_delete_user_data_all_params() + + # Disable retries and run test_delete_user_data_all_params. + _service.disable_retries() + self.test_delete_user_data_all_params() @responses.activate def test_delete_user_data_value_error(self): @@ -5224,7 +5569,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/user_data') + url = preprocess_url('/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -5242,6 +5587,14 @@ def test_delete_user_data_value_error(self): _service.delete_user_data(**req_copy) + def test_delete_user_data_value_error_with_retries(self): + # Enable retries and run test_delete_user_data_value_error. + _service.enable_retries() + self.test_delete_user_data_value_error() + + # Disable retries and run test_delete_user_data_value_error. + _service.disable_retries() + self.test_delete_user_data_value_error() # endregion ############################################################################## @@ -5258,24 +5611,13 @@ class TestCreateEvent(): Test Class for create_event """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_event_all_params(self): """ create_event() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/events') + url = preprocess_url('/v1/events') mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' responses.add(responses.POST, url, @@ -5287,7 +5629,7 @@ def test_create_event_all_params(self): event_data_model = {} event_data_model['environment_id'] = 'testString' event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = "2019-01-01T12:00:00Z" + event_data_model['client_timestamp'] = '2019-01-01T12:00:00Z' event_data_model['display_rank'] = 38 event_data_model['collection_id'] = 'testString' event_data_model['document_id'] = 'testString' @@ -5311,6 +5653,14 @@ def test_create_event_all_params(self): assert req_body['type'] == 'click' assert req_body['data'] == event_data_model + def test_create_event_all_params_with_retries(self): + # Enable retries and run test_create_event_all_params. + _service.enable_retries() + self.test_create_event_all_params() + + # Disable retries and run test_create_event_all_params. + _service.disable_retries() + self.test_create_event_all_params() @responses.activate def test_create_event_value_error(self): @@ -5318,7 +5668,7 @@ def test_create_event_value_error(self): test_create_event_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/events') + url = preprocess_url('/v1/events') mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' responses.add(responses.POST, url, @@ -5330,7 +5680,7 @@ def test_create_event_value_error(self): event_data_model = {} event_data_model['environment_id'] = 'testString' event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = "2019-01-01T12:00:00Z" + event_data_model['client_timestamp'] = '2019-01-01T12:00:00Z' event_data_model['display_rank'] = 38 event_data_model['collection_id'] = 'testString' event_data_model['document_id'] = 'testString' @@ -5350,30 +5700,27 @@ def test_create_event_value_error(self): _service.create_event(**req_copy) + def test_create_event_value_error_with_retries(self): + # Enable retries and run test_create_event_value_error. + _service.enable_retries() + self.test_create_event_value_error() + + # Disable retries and run test_create_event_value_error. + _service.disable_retries() + self.test_create_event_value_error() class TestQueryLog(): """ Test Class for query_log """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_query_log_all_params(self): """ query_log() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/logs') + url = preprocess_url('/v1/logs') mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' responses.add(responses.GET, url, @@ -5410,6 +5757,14 @@ def test_query_log_all_params(self): assert 'offset={}'.format(offset) in query_string assert 'sort={}'.format(','.join(sort)) in query_string + def test_query_log_all_params_with_retries(self): + # Enable retries and run test_query_log_all_params. + _service.enable_retries() + self.test_query_log_all_params() + + # Disable retries and run test_query_log_all_params. + _service.disable_retries() + self.test_query_log_all_params() @responses.activate def test_query_log_required_params(self): @@ -5417,7 +5772,7 @@ def test_query_log_required_params(self): test_query_log_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/logs') + url = preprocess_url('/v1/logs') mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' responses.add(responses.GET, url, @@ -5433,6 +5788,14 @@ def test_query_log_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_query_log_required_params_with_retries(self): + # Enable retries and run test_query_log_required_params. + _service.enable_retries() + self.test_query_log_required_params() + + # Disable retries and run test_query_log_required_params. + _service.disable_retries() + self.test_query_log_required_params() @responses.activate def test_query_log_value_error(self): @@ -5440,7 +5803,7 @@ def test_query_log_value_error(self): test_query_log_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/logs') + url = preprocess_url('/v1/logs') mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' responses.add(responses.GET, url, @@ -5457,30 +5820,27 @@ def test_query_log_value_error(self): _service.query_log(**req_copy) + def test_query_log_value_error_with_retries(self): + # Enable retries and run test_query_log_value_error. + _service.enable_retries() + self.test_query_log_value_error() + + # Disable retries and run test_query_log_value_error. + _service.disable_retries() + self.test_query_log_value_error() class TestGetMetricsQuery(): """ Test Class for get_metrics_query """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_metrics_query_all_params(self): """ get_metrics_query() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries') + url = preprocess_url('/v1/metrics/number_of_queries') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5509,6 +5869,14 @@ def test_get_metrics_query_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string + def test_get_metrics_query_all_params_with_retries(self): + # Enable retries and run test_get_metrics_query_all_params. + _service.enable_retries() + self.test_get_metrics_query_all_params() + + # Disable retries and run test_get_metrics_query_all_params. + _service.disable_retries() + self.test_get_metrics_query_all_params() @responses.activate def test_get_metrics_query_required_params(self): @@ -5516,7 +5884,7 @@ def test_get_metrics_query_required_params(self): test_get_metrics_query_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries') + url = preprocess_url('/v1/metrics/number_of_queries') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5532,6 +5900,14 @@ def test_get_metrics_query_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_metrics_query_required_params_with_retries(self): + # Enable retries and run test_get_metrics_query_required_params. + _service.enable_retries() + self.test_get_metrics_query_required_params() + + # Disable retries and run test_get_metrics_query_required_params. + _service.disable_retries() + self.test_get_metrics_query_required_params() @responses.activate def test_get_metrics_query_value_error(self): @@ -5539,7 +5915,7 @@ def test_get_metrics_query_value_error(self): test_get_metrics_query_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries') + url = preprocess_url('/v1/metrics/number_of_queries') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5556,30 +5932,27 @@ def test_get_metrics_query_value_error(self): _service.get_metrics_query(**req_copy) + def test_get_metrics_query_value_error_with_retries(self): + # Enable retries and run test_get_metrics_query_value_error. + _service.enable_retries() + self.test_get_metrics_query_value_error() + + # Disable retries and run test_get_metrics_query_value_error. + _service.disable_retries() + self.test_get_metrics_query_value_error() class TestGetMetricsQueryEvent(): """ Test Class for get_metrics_query_event """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_metrics_query_event_all_params(self): """ get_metrics_query_event() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_event') + url = preprocess_url('/v1/metrics/number_of_queries_with_event') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5608,6 +5981,14 @@ def test_get_metrics_query_event_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string + def test_get_metrics_query_event_all_params_with_retries(self): + # Enable retries and run test_get_metrics_query_event_all_params. + _service.enable_retries() + self.test_get_metrics_query_event_all_params() + + # Disable retries and run test_get_metrics_query_event_all_params. + _service.disable_retries() + self.test_get_metrics_query_event_all_params() @responses.activate def test_get_metrics_query_event_required_params(self): @@ -5615,7 +5996,7 @@ def test_get_metrics_query_event_required_params(self): test_get_metrics_query_event_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_event') + url = preprocess_url('/v1/metrics/number_of_queries_with_event') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5631,6 +6012,14 @@ def test_get_metrics_query_event_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_metrics_query_event_required_params_with_retries(self): + # Enable retries and run test_get_metrics_query_event_required_params. + _service.enable_retries() + self.test_get_metrics_query_event_required_params() + + # Disable retries and run test_get_metrics_query_event_required_params. + _service.disable_retries() + self.test_get_metrics_query_event_required_params() @responses.activate def test_get_metrics_query_event_value_error(self): @@ -5638,7 +6027,7 @@ def test_get_metrics_query_event_value_error(self): test_get_metrics_query_event_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_event') + url = preprocess_url('/v1/metrics/number_of_queries_with_event') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5655,30 +6044,27 @@ def test_get_metrics_query_event_value_error(self): _service.get_metrics_query_event(**req_copy) + def test_get_metrics_query_event_value_error_with_retries(self): + # Enable retries and run test_get_metrics_query_event_value_error. + _service.enable_retries() + self.test_get_metrics_query_event_value_error() + + # Disable retries and run test_get_metrics_query_event_value_error. + _service.disable_retries() + self.test_get_metrics_query_event_value_error() class TestGetMetricsQueryNoResults(): """ Test Class for get_metrics_query_no_results """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_metrics_query_no_results_all_params(self): """ get_metrics_query_no_results() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_no_search_results') + url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5707,6 +6093,14 @@ def test_get_metrics_query_no_results_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string + def test_get_metrics_query_no_results_all_params_with_retries(self): + # Enable retries and run test_get_metrics_query_no_results_all_params. + _service.enable_retries() + self.test_get_metrics_query_no_results_all_params() + + # Disable retries and run test_get_metrics_query_no_results_all_params. + _service.disable_retries() + self.test_get_metrics_query_no_results_all_params() @responses.activate def test_get_metrics_query_no_results_required_params(self): @@ -5714,7 +6108,7 @@ def test_get_metrics_query_no_results_required_params(self): test_get_metrics_query_no_results_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_no_search_results') + url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5730,6 +6124,14 @@ def test_get_metrics_query_no_results_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_metrics_query_no_results_required_params_with_retries(self): + # Enable retries and run test_get_metrics_query_no_results_required_params. + _service.enable_retries() + self.test_get_metrics_query_no_results_required_params() + + # Disable retries and run test_get_metrics_query_no_results_required_params. + _service.disable_retries() + self.test_get_metrics_query_no_results_required_params() @responses.activate def test_get_metrics_query_no_results_value_error(self): @@ -5737,7 +6139,7 @@ def test_get_metrics_query_no_results_value_error(self): test_get_metrics_query_no_results_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/number_of_queries_with_no_search_results') + url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5754,30 +6156,27 @@ def test_get_metrics_query_no_results_value_error(self): _service.get_metrics_query_no_results(**req_copy) + def test_get_metrics_query_no_results_value_error_with_retries(self): + # Enable retries and run test_get_metrics_query_no_results_value_error. + _service.enable_retries() + self.test_get_metrics_query_no_results_value_error() + + # Disable retries and run test_get_metrics_query_no_results_value_error. + _service.disable_retries() + self.test_get_metrics_query_no_results_value_error() class TestGetMetricsEventRate(): """ Test Class for get_metrics_event_rate """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_metrics_event_rate_all_params(self): """ get_metrics_event_rate() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/event_rate') + url = preprocess_url('/v1/metrics/event_rate') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5806,6 +6205,14 @@ def test_get_metrics_event_rate_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string + def test_get_metrics_event_rate_all_params_with_retries(self): + # Enable retries and run test_get_metrics_event_rate_all_params. + _service.enable_retries() + self.test_get_metrics_event_rate_all_params() + + # Disable retries and run test_get_metrics_event_rate_all_params. + _service.disable_retries() + self.test_get_metrics_event_rate_all_params() @responses.activate def test_get_metrics_event_rate_required_params(self): @@ -5813,7 +6220,7 @@ def test_get_metrics_event_rate_required_params(self): test_get_metrics_event_rate_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/event_rate') + url = preprocess_url('/v1/metrics/event_rate') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5829,6 +6236,14 @@ def test_get_metrics_event_rate_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_metrics_event_rate_required_params_with_retries(self): + # Enable retries and run test_get_metrics_event_rate_required_params. + _service.enable_retries() + self.test_get_metrics_event_rate_required_params() + + # Disable retries and run test_get_metrics_event_rate_required_params. + _service.disable_retries() + self.test_get_metrics_event_rate_required_params() @responses.activate def test_get_metrics_event_rate_value_error(self): @@ -5836,7 +6251,7 @@ def test_get_metrics_event_rate_value_error(self): test_get_metrics_event_rate_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/event_rate') + url = preprocess_url('/v1/metrics/event_rate') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5853,30 +6268,27 @@ def test_get_metrics_event_rate_value_error(self): _service.get_metrics_event_rate(**req_copy) + def test_get_metrics_event_rate_value_error_with_retries(self): + # Enable retries and run test_get_metrics_event_rate_value_error. + _service.enable_retries() + self.test_get_metrics_event_rate_value_error() + + # Disable retries and run test_get_metrics_event_rate_value_error. + _service.disable_retries() + self.test_get_metrics_event_rate_value_error() class TestGetMetricsQueryTokenEvent(): """ Test Class for get_metrics_query_token_event """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_metrics_query_token_event_all_params(self): """ get_metrics_query_token_event() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/top_query_tokens_with_event_rate') + url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5901,6 +6313,14 @@ def test_get_metrics_query_token_event_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'count={}'.format(count) in query_string + def test_get_metrics_query_token_event_all_params_with_retries(self): + # Enable retries and run test_get_metrics_query_token_event_all_params. + _service.enable_retries() + self.test_get_metrics_query_token_event_all_params() + + # Disable retries and run test_get_metrics_query_token_event_all_params. + _service.disable_retries() + self.test_get_metrics_query_token_event_all_params() @responses.activate def test_get_metrics_query_token_event_required_params(self): @@ -5908,7 +6328,7 @@ def test_get_metrics_query_token_event_required_params(self): test_get_metrics_query_token_event_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/top_query_tokens_with_event_rate') + url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5924,6 +6344,14 @@ def test_get_metrics_query_token_event_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_metrics_query_token_event_required_params_with_retries(self): + # Enable retries and run test_get_metrics_query_token_event_required_params. + _service.enable_retries() + self.test_get_metrics_query_token_event_required_params() + + # Disable retries and run test_get_metrics_query_token_event_required_params. + _service.disable_retries() + self.test_get_metrics_query_token_event_required_params() @responses.activate def test_get_metrics_query_token_event_value_error(self): @@ -5931,7 +6359,7 @@ def test_get_metrics_query_token_event_value_error(self): test_get_metrics_query_token_event_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/metrics/top_query_tokens_with_event_rate') + url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' responses.add(responses.GET, url, @@ -5948,6 +6376,14 @@ def test_get_metrics_query_token_event_value_error(self): _service.get_metrics_query_token_event(**req_copy) + def test_get_metrics_query_token_event_value_error_with_retries(self): + # Enable retries and run test_get_metrics_query_token_event_value_error. + _service.enable_retries() + self.test_get_metrics_query_token_event_value_error() + + # Disable retries and run test_get_metrics_query_token_event_value_error. + _service.disable_retries() + self.test_get_metrics_query_token_event_value_error() # endregion ############################################################################## @@ -5964,24 +6400,13 @@ class TestListCredentials(): Test Class for list_credentials """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_credentials_all_params(self): """ list_credentials() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') + url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' responses.add(responses.GET, url, @@ -6002,6 +6427,14 @@ def test_list_credentials_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_credentials_all_params_with_retries(self): + # Enable retries and run test_list_credentials_all_params. + _service.enable_retries() + self.test_list_credentials_all_params() + + # Disable retries and run test_list_credentials_all_params. + _service.disable_retries() + self.test_list_credentials_all_params() @responses.activate def test_list_credentials_value_error(self): @@ -6009,7 +6442,7 @@ def test_list_credentials_value_error(self): test_list_credentials_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') + url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' responses.add(responses.GET, url, @@ -6030,30 +6463,27 @@ def test_list_credentials_value_error(self): _service.list_credentials(**req_copy) + def test_list_credentials_value_error_with_retries(self): + # Enable retries and run test_list_credentials_value_error. + _service.enable_retries() + self.test_list_credentials_value_error() + + # Disable retries and run test_list_credentials_value_error. + _service.disable_retries() + self.test_list_credentials_value_error() class TestCreateCredentials(): """ Test Class for create_credentials """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_credentials_all_params(self): """ create_credentials() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') + url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.POST, url, @@ -6112,6 +6542,14 @@ def test_create_credentials_all_params(self): assert req_body['credential_details'] == credential_details_model assert req_body['status'] == status_details_model + def test_create_credentials_all_params_with_retries(self): + # Enable retries and run test_create_credentials_all_params. + _service.enable_retries() + self.test_create_credentials_all_params() + + # Disable retries and run test_create_credentials_all_params. + _service.disable_retries() + self.test_create_credentials_all_params() @responses.activate def test_create_credentials_value_error(self): @@ -6119,7 +6557,7 @@ def test_create_credentials_value_error(self): test_create_credentials_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') + url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.POST, url, @@ -6170,30 +6608,27 @@ def test_create_credentials_value_error(self): _service.create_credentials(**req_copy) + def test_create_credentials_value_error_with_retries(self): + # Enable retries and run test_create_credentials_value_error. + _service.enable_retries() + self.test_create_credentials_value_error() + + # Disable retries and run test_create_credentials_value_error. + _service.disable_retries() + self.test_create_credentials_value_error() class TestGetCredentials(): """ Test Class for get_credentials """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_credentials_all_params(self): """ get_credentials() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') + url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.GET, url, @@ -6216,6 +6651,14 @@ def test_get_credentials_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_credentials_all_params_with_retries(self): + # Enable retries and run test_get_credentials_all_params. + _service.enable_retries() + self.test_get_credentials_all_params() + + # Disable retries and run test_get_credentials_all_params. + _service.disable_retries() + self.test_get_credentials_all_params() @responses.activate def test_get_credentials_value_error(self): @@ -6223,7 +6666,7 @@ def test_get_credentials_value_error(self): test_get_credentials_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') + url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.GET, url, @@ -6246,30 +6689,27 @@ def test_get_credentials_value_error(self): _service.get_credentials(**req_copy) + def test_get_credentials_value_error_with_retries(self): + # Enable retries and run test_get_credentials_value_error. + _service.enable_retries() + self.test_get_credentials_value_error() + + # Disable retries and run test_get_credentials_value_error. + _service.disable_retries() + self.test_get_credentials_value_error() class TestUpdateCredentials(): """ Test Class for update_credentials """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_credentials_all_params(self): """ update_credentials() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') + url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.PUT, url, @@ -6330,6 +6770,14 @@ def test_update_credentials_all_params(self): assert req_body['credential_details'] == credential_details_model assert req_body['status'] == status_details_model + def test_update_credentials_all_params_with_retries(self): + # Enable retries and run test_update_credentials_all_params. + _service.enable_retries() + self.test_update_credentials_all_params() + + # Disable retries and run test_update_credentials_all_params. + _service.disable_retries() + self.test_update_credentials_all_params() @responses.activate def test_update_credentials_value_error(self): @@ -6337,7 +6785,7 @@ def test_update_credentials_value_error(self): test_update_credentials_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') + url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.PUT, url, @@ -6390,30 +6838,27 @@ def test_update_credentials_value_error(self): _service.update_credentials(**req_copy) + def test_update_credentials_value_error_with_retries(self): + # Enable retries and run test_update_credentials_value_error. + _service.enable_retries() + self.test_update_credentials_value_error() + + # Disable retries and run test_update_credentials_value_error. + _service.disable_retries() + self.test_update_credentials_value_error() class TestDeleteCredentials(): """ Test Class for delete_credentials """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_credentials_all_params(self): """ delete_credentials() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') + url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -6436,6 +6881,14 @@ def test_delete_credentials_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_credentials_all_params_with_retries(self): + # Enable retries and run test_delete_credentials_all_params. + _service.enable_retries() + self.test_delete_credentials_all_params() + + # Disable retries and run test_delete_credentials_all_params. + _service.disable_retries() + self.test_delete_credentials_all_params() @responses.activate def test_delete_credentials_value_error(self): @@ -6443,7 +6896,7 @@ def test_delete_credentials_value_error(self): test_delete_credentials_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') + url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "status": "deleted"}' responses.add(responses.DELETE, url, @@ -6466,6 +6919,14 @@ def test_delete_credentials_value_error(self): _service.delete_credentials(**req_copy) + def test_delete_credentials_value_error_with_retries(self): + # Enable retries and run test_delete_credentials_value_error. + _service.enable_retries() + self.test_delete_credentials_value_error() + + # Disable retries and run test_delete_credentials_value_error. + _service.disable_retries() + self.test_delete_credentials_value_error() # endregion ############################################################################## @@ -6482,24 +6943,13 @@ class TestListGateways(): Test Class for list_gateways """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_gateways_all_params(self): """ list_gateways() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways') + url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' responses.add(responses.GET, url, @@ -6520,6 +6970,14 @@ def test_list_gateways_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_gateways_all_params_with_retries(self): + # Enable retries and run test_list_gateways_all_params. + _service.enable_retries() + self.test_list_gateways_all_params() + + # Disable retries and run test_list_gateways_all_params. + _service.disable_retries() + self.test_list_gateways_all_params() @responses.activate def test_list_gateways_value_error(self): @@ -6527,7 +6985,7 @@ def test_list_gateways_value_error(self): test_list_gateways_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways') + url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' responses.add(responses.GET, url, @@ -6548,30 +7006,27 @@ def test_list_gateways_value_error(self): _service.list_gateways(**req_copy) + def test_list_gateways_value_error_with_retries(self): + # Enable retries and run test_list_gateways_value_error. + _service.enable_retries() + self.test_list_gateways_value_error() + + # Disable retries and run test_list_gateways_value_error. + _service.disable_retries() + self.test_list_gateways_value_error() class TestCreateGateway(): """ Test Class for create_gateway """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_gateway_all_params(self): """ create_gateway() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways') + url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' responses.add(responses.POST, url, @@ -6597,6 +7052,14 @@ def test_create_gateway_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' + def test_create_gateway_all_params_with_retries(self): + # Enable retries and run test_create_gateway_all_params. + _service.enable_retries() + self.test_create_gateway_all_params() + + # Disable retries and run test_create_gateway_all_params. + _service.disable_retries() + self.test_create_gateway_all_params() @responses.activate def test_create_gateway_required_params(self): @@ -6604,7 +7067,7 @@ def test_create_gateway_required_params(self): test_create_gateway_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways') + url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' responses.add(responses.POST, url, @@ -6625,6 +7088,14 @@ def test_create_gateway_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_create_gateway_required_params_with_retries(self): + # Enable retries and run test_create_gateway_required_params. + _service.enable_retries() + self.test_create_gateway_required_params() + + # Disable retries and run test_create_gateway_required_params. + _service.disable_retries() + self.test_create_gateway_required_params() @responses.activate def test_create_gateway_value_error(self): @@ -6632,7 +7103,7 @@ def test_create_gateway_value_error(self): test_create_gateway_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways') + url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' responses.add(responses.POST, url, @@ -6653,30 +7124,27 @@ def test_create_gateway_value_error(self): _service.create_gateway(**req_copy) + def test_create_gateway_value_error_with_retries(self): + # Enable retries and run test_create_gateway_value_error. + _service.enable_retries() + self.test_create_gateway_value_error() + + # Disable retries and run test_create_gateway_value_error. + _service.disable_retries() + self.test_create_gateway_value_error() class TestGetGateway(): """ Test Class for get_gateway """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_gateway_all_params(self): """ get_gateway() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways/testString') + url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' responses.add(responses.GET, url, @@ -6699,6 +7167,14 @@ def test_get_gateway_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_gateway_all_params_with_retries(self): + # Enable retries and run test_get_gateway_all_params. + _service.enable_retries() + self.test_get_gateway_all_params() + + # Disable retries and run test_get_gateway_all_params. + _service.disable_retries() + self.test_get_gateway_all_params() @responses.activate def test_get_gateway_value_error(self): @@ -6706,7 +7182,7 @@ def test_get_gateway_value_error(self): test_get_gateway_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways/testString') + url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' responses.add(responses.GET, url, @@ -6729,30 +7205,27 @@ def test_get_gateway_value_error(self): _service.get_gateway(**req_copy) + def test_get_gateway_value_error_with_retries(self): + # Enable retries and run test_get_gateway_value_error. + _service.enable_retries() + self.test_get_gateway_value_error() + + # Disable retries and run test_get_gateway_value_error. + _service.disable_retries() + self.test_get_gateway_value_error() class TestDeleteGateway(): """ Test Class for delete_gateway """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_gateway_all_params(self): """ delete_gateway() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways/testString') + url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "status": "status"}' responses.add(responses.DELETE, url, @@ -6775,6 +7248,14 @@ def test_delete_gateway_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_gateway_all_params_with_retries(self): + # Enable retries and run test_delete_gateway_all_params. + _service.enable_retries() + self.test_delete_gateway_all_params() + + # Disable retries and run test_delete_gateway_all_params. + _service.disable_retries() + self.test_delete_gateway_all_params() @responses.activate def test_delete_gateway_value_error(self): @@ -6782,7 +7263,7 @@ def test_delete_gateway_value_error(self): test_delete_gateway_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/environments/testString/gateways/testString') + url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "status": "status"}' responses.add(responses.DELETE, url, @@ -6805,6 +7286,14 @@ def test_delete_gateway_value_error(self): _service.delete_gateway(**req_copy) + def test_delete_gateway_value_error_with_retries(self): + # Enable retries and run test_delete_gateway_value_error. + _service.enable_retries() + self.test_delete_gateway_value_error() + + # Disable retries and run test_delete_gateway_value_error. + _service.disable_retries() + self.test_delete_gateway_value_error() # endregion ############################################################################## @@ -6816,36 +7305,6 @@ def test_delete_gateway_value_error(self): # Start of Model Tests ############################################################################## # region -class TestModel_AggregationResult(): - """ - Test Class for AggregationResult - """ - - def test_aggregation_result_serialization(self): - """ - Test serialization/deserialization for AggregationResult - """ - - # Construct a json representation of a AggregationResult model - aggregation_result_model_json = {} - aggregation_result_model_json['key'] = 'testString' - aggregation_result_model_json['matching_results'] = 38 - - # Construct a model instance of AggregationResult by calling from_dict on the json representation - aggregation_result_model = AggregationResult.from_dict(aggregation_result_model_json) - assert aggregation_result_model != False - - # Construct a model instance of AggregationResult by calling from_dict on the json representation - aggregation_result_model_dict = AggregationResult.from_dict(aggregation_result_model_json).__dict__ - aggregation_result_model2 = AggregationResult(**aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert aggregation_result_model == aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - aggregation_result_model_json2 = aggregation_result_model.to_dict() - assert aggregation_result_model_json2 == aggregation_result_model_json - class TestModel_Collection(): """ Test Class for Collection @@ -6875,12 +7334,12 @@ def test_collection_serialization(self): training_status_model['minimum_examples_added'] = False training_status_model['sufficient_label_diversity'] = False training_status_model['notices'] = 0 - training_status_model['successfully_trained'] = "2019-01-01T12:00:00Z" - training_status_model['data_updated'] = "2019-01-01T12:00:00Z" + training_status_model['successfully_trained'] = '2019-01-01T12:00:00Z' + training_status_model['data_updated'] = '2019-01-01T12:00:00Z' source_status_model = {} # SourceStatus source_status_model['status'] = 'complete' - source_status_model['next_crawl'] = "2019-01-01T12:00:00Z" + source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' collection_crawl_status_model = {} # CollectionCrawlStatus collection_crawl_status_model['source_crawl'] = source_status_model @@ -6901,8 +7360,8 @@ def test_collection_serialization(self): collection_model_json['collection_id'] = 'testString' collection_model_json['name'] = 'testString' collection_model_json['description'] = 'testString' - collection_model_json['created'] = "2019-01-01T12:00:00Z" - collection_model_json['updated'] = "2019-01-01T12:00:00Z" + collection_model_json['created'] = '2019-01-01T12:00:00Z' + collection_model_json['updated'] = '2019-01-01T12:00:00Z' collection_model_json['status'] = 'active' collection_model_json['configuration_id'] = 'testString' collection_model_json['language'] = 'testString' @@ -6941,7 +7400,7 @@ def test_collection_crawl_status_serialization(self): source_status_model = {} # SourceStatus source_status_model['status'] = 'running' - source_status_model['next_crawl'] = "2019-01-01T12:00:00Z" + source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' # Construct a json representation of a CollectionCrawlStatus model collection_crawl_status_model_json = {} @@ -7223,8 +7682,8 @@ def test_configuration_serialization(self): configuration_model_json = {} configuration_model_json['configuration_id'] = 'testString' configuration_model_json['name'] = 'testString' - configuration_model_json['created'] = "2019-01-01T12:00:00Z" - configuration_model_json['updated'] = "2019-01-01T12:00:00Z" + configuration_model_json['created'] = '2019-01-01T12:00:00Z' + configuration_model_json['updated'] = '2019-01-01T12:00:00Z' configuration_model_json['description'] = 'testString' configuration_model_json['conversions'] = conversions_model configuration_model_json['enrichments'] = [enrichment_model] @@ -7343,7 +7802,7 @@ def test_create_event_response_serialization(self): event_data_model = {} # EventData event_data_model['environment_id'] = 'testString' event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = "2019-01-01T12:00:00Z" + event_data_model['client_timestamp'] = '2019-01-01T12:00:00Z' event_data_model['display_rank'] = 38 event_data_model['collection_id'] = 'testString' event_data_model['document_id'] = 'testString' @@ -7581,7 +8040,7 @@ def test_delete_configuration_response_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'configuration_in_use' - notice_model['created'] = "2016-09-28T12:34:00Z" + notice_model['created'] = '2016-09-28T12:34:00Z' notice_model['document_id'] = 'testString' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -7743,7 +8202,7 @@ def test_document_accepted_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = "2019-01-01T12:00:00Z" + notice_model['created'] = '2019-01-01T12:00:00Z' notice_model['document_id'] = 'testString' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -7817,7 +8276,7 @@ def test_document_status_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'index_342' - notice_model['created'] = "2019-01-01T12:00:00Z" + notice_model['created'] = '2019-01-01T12:00:00Z' notice_model['document_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -8044,15 +8503,15 @@ def test_environment_serialization(self): search_status_model['scope'] = 'testString' search_status_model['status'] = 'NO_DATA' search_status_model['status_description'] = 'testString' - search_status_model['last_trained'] = "2019-01-01" + search_status_model['last_trained'] = '2019-01-01' # Construct a json representation of a Environment model environment_model_json = {} environment_model_json['environment_id'] = 'testString' environment_model_json['name'] = 'testString' environment_model_json['description'] = 'testString' - environment_model_json['created'] = "2019-01-01T12:00:00Z" - environment_model_json['updated'] = "2019-01-01T12:00:00Z" + environment_model_json['created'] = '2019-01-01T12:00:00Z' + environment_model_json['updated'] = '2019-01-01T12:00:00Z' environment_model_json['status'] = 'active' environment_model_json['read_only'] = True environment_model_json['size'] = 'LT' @@ -8119,7 +8578,7 @@ def test_event_data_serialization(self): event_data_model_json = {} event_data_model_json['environment_id'] = 'testString' event_data_model_json['session_token'] = 'testString' - event_data_model_json['client_timestamp'] = "2019-01-01T12:00:00Z" + event_data_model_json['client_timestamp'] = '2019-01-01T12:00:00Z' event_data_model_json['display_rank'] = 38 event_data_model_json['collection_id'] = 'testString' event_data_model_json['document_id'] = 'testString' @@ -8518,12 +8977,12 @@ def test_list_collections_response_serialization(self): training_status_model['minimum_examples_added'] = True training_status_model['sufficient_label_diversity'] = True training_status_model['notices'] = 38 - training_status_model['successfully_trained'] = "2019-01-01T12:00:00Z" - training_status_model['data_updated'] = "2019-01-01T12:00:00Z" + training_status_model['successfully_trained'] = '2019-01-01T12:00:00Z' + training_status_model['data_updated'] = '2019-01-01T12:00:00Z' source_status_model = {} # SourceStatus source_status_model['status'] = 'running' - source_status_model['next_crawl'] = "2019-01-01T12:00:00Z" + source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' collection_crawl_status_model = {} # CollectionCrawlStatus collection_crawl_status_model['source_crawl'] = source_status_model @@ -8543,8 +9002,8 @@ def test_list_collections_response_serialization(self): collection_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' collection_model['name'] = 'example' collection_model['description'] = 'this is a demo collection' - collection_model['created'] = "2015-08-24T18:42:25.324000Z" - collection_model['updated'] = "2015-08-24T18:42:25.324000Z" + collection_model['created'] = '2015-08-24T18:42:25.324000Z' + collection_model['updated'] = '2015-08-24T18:42:25.324000Z' collection_model['status'] = 'active' collection_model['configuration_id'] = '6963be41-2dea-4f79-8f52-127c63c479b0' collection_model['language'] = 'en' @@ -8745,8 +9204,8 @@ def test_list_configurations_response_serialization(self): configuration_model = {} # Configuration configuration_model['configuration_id'] = 'testString' configuration_model['name'] = 'testString' - configuration_model['created'] = "2019-01-01T12:00:00Z" - configuration_model['updated'] = "2019-01-01T12:00:00Z" + configuration_model['created'] = '2019-01-01T12:00:00Z' + configuration_model['updated'] = '2019-01-01T12:00:00Z' configuration_model['description'] = 'testString' configuration_model['conversions'] = conversions_model configuration_model['enrichments'] = [enrichment_model] @@ -8805,14 +9264,14 @@ def test_list_environments_response_serialization(self): search_status_model['scope'] = 'testString' search_status_model['status'] = 'NO_DATA' search_status_model['status_description'] = 'testString' - search_status_model['last_trained'] = "2019-01-01" + search_status_model['last_trained'] = '2019-01-01' environment_model = {} # Environment environment_model['environment_id'] = 'ecbda78e-fb06-40b1-a43f-a039fac0adc6' environment_model['name'] = 'byod_environment' environment_model['description'] = 'Private Data Environment' - environment_model['created'] = "2017-07-14T12:54:40.985000Z" - environment_model['updated'] = "2017-07-14T12:54:40.985000Z" + environment_model['created'] = '2017-07-14T12:54:40.985000Z' + environment_model['updated'] = '2017-07-14T12:54:40.985000Z' environment_model['status'] = 'active' environment_model['read_only'] = False environment_model['size'] = 'LT' @@ -8868,8 +9327,8 @@ def test_log_query_response_serialization(self): log_query_response_result_model['document_type'] = 'query' log_query_response_result_model['natural_language_query'] = 'testString' log_query_response_result_model['document_results'] = log_query_response_result_documents_model - log_query_response_result_model['created_timestamp'] = "2019-01-01T12:00:00Z" - log_query_response_result_model['client_timestamp'] = "2019-01-01T12:00:00Z" + log_query_response_result_model['created_timestamp'] = '2019-01-01T12:00:00Z' + log_query_response_result_model['client_timestamp'] = '2019-01-01T12:00:00Z' log_query_response_result_model['query_id'] = 'testString' log_query_response_result_model['session_token'] = 'testString' log_query_response_result_model['collection_id'] = 'testString' @@ -8928,8 +9387,8 @@ def test_log_query_response_result_serialization(self): log_query_response_result_model_json['document_type'] = 'query' log_query_response_result_model_json['natural_language_query'] = 'testString' log_query_response_result_model_json['document_results'] = log_query_response_result_documents_model - log_query_response_result_model_json['created_timestamp'] = "2019-01-01T12:00:00Z" - log_query_response_result_model_json['client_timestamp'] = "2019-01-01T12:00:00Z" + log_query_response_result_model_json['created_timestamp'] = '2019-01-01T12:00:00Z' + log_query_response_result_model_json['client_timestamp'] = '2019-01-01T12:00:00Z' log_query_response_result_model_json['query_id'] = 'testString' log_query_response_result_model_json['session_token'] = 'testString' log_query_response_result_model_json['collection_id'] = 'testString' @@ -9038,7 +9497,7 @@ def test_metric_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. metric_aggregation_result_model = {} # MetricAggregationResult - metric_aggregation_result_model['key_as_string'] = "2019-01-01T12:00:00Z" + metric_aggregation_result_model['key_as_string'] = '2019-01-01T12:00:00Z' metric_aggregation_result_model['key'] = 26 metric_aggregation_result_model['matching_results'] = 38 metric_aggregation_result_model['event_rate'] = 72.5 @@ -9076,7 +9535,7 @@ def test_metric_aggregation_result_serialization(self): # Construct a json representation of a MetricAggregationResult model metric_aggregation_result_model_json = {} - metric_aggregation_result_model_json['key_as_string'] = "2019-01-01T12:00:00Z" + metric_aggregation_result_model_json['key_as_string'] = '2019-01-01T12:00:00Z' metric_aggregation_result_model_json['key'] = 26 metric_aggregation_result_model_json['matching_results'] = 38 metric_aggregation_result_model_json['event_rate'] = 72.5 @@ -9109,7 +9568,7 @@ def test_metric_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. metric_aggregation_result_model = {} # MetricAggregationResult - metric_aggregation_result_model['key_as_string'] = "2019-01-01T12:00:00Z" + metric_aggregation_result_model['key_as_string'] = '2019-01-01T12:00:00Z' metric_aggregation_result_model['key'] = 26 metric_aggregation_result_model['matching_results'] = 38 metric_aggregation_result_model['event_rate'] = 72.5 @@ -9576,7 +10035,7 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} notice_model_json['notice_id'] = 'testString' - notice_model_json['created'] = "2019-01-01T12:00:00Z" + notice_model_json['created'] = '2019-01-01T12:00:00Z' notice_model_json['document_id'] = 'testString' notice_model_json['query_id'] = 'testString' notice_model_json['severity'] = 'warning' @@ -9692,7 +10151,6 @@ def test_query_aggregation_serialization(self): # Construct a json representation of a QueryAggregation model query_aggregation_model_json = {} query_aggregation_model_json['type'] = 'testString' - query_aggregation_model_json['matching_results'] = 38 # Construct a model instance of QueryAggregation by calling from_dict on the json representation query_aggregation_model = QueryAggregation.from_dict(query_aggregation_model_json) @@ -9709,6 +10167,44 @@ def test_query_aggregation_serialization(self): query_aggregation_model_json2 = query_aggregation_model.to_dict() assert query_aggregation_model_json2 == query_aggregation_model_json +class TestModel_QueryHistogramAggregationResult(): + """ + Test Class for QueryHistogramAggregationResult + """ + + def test_query_histogram_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryHistogramAggregationResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model['type'] = 'filter' + query_aggregation_model['match'] = 'testString' + query_aggregation_model['matching_results'] = 26 + + # Construct a json representation of a QueryHistogramAggregationResult model + query_histogram_aggregation_result_model_json = {} + query_histogram_aggregation_result_model_json['key'] = 26 + query_histogram_aggregation_result_model_json['matching_results'] = 38 + query_histogram_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + + # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation + query_histogram_aggregation_result_model = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json) + assert query_histogram_aggregation_result_model != False + + # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation + query_histogram_aggregation_result_model_dict = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json).__dict__ + query_histogram_aggregation_result_model2 = QueryHistogramAggregationResult(**query_histogram_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_histogram_aggregation_result_model == query_histogram_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_histogram_aggregation_result_model_json2 = query_histogram_aggregation_result_model.to_dict() + assert query_histogram_aggregation_result_model_json2 == query_histogram_aggregation_result_model_json + class TestModel_QueryNoticesResponse(): """ Test Class for QueryNoticesResponse @@ -9727,7 +10223,7 @@ def test_query_notices_response_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'xpath_not_found' - notice_model['created'] = "2016-09-20T17:26:17Z" + notice_model['created'] = '2016-09-20T17:26:17Z' notice_model['document_id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -9746,11 +10242,10 @@ def test_query_notices_response_serialization(self): query_notices_result_model['notices'] = [notice_model] query_notices_result_model['score'] = { 'foo': 'bar' } - query_aggregation_model = {} # Histogram - query_aggregation_model['type'] = 'histogram' - query_aggregation_model['matching_results'] = 38 - query_aggregation_model['field'] = 'testString' - query_aggregation_model['interval'] = 38 + query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model['type'] = 'filter' + query_aggregation_model['match'] = 'testString' + query_aggregation_model['matching_results'] = 26 query_passages_model = {} # QueryPassages query_passages_model['document_id'] = 'testString' @@ -9801,7 +10296,7 @@ def test_query_notices_result_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = "2019-01-01T12:00:00Z" + notice_model['created'] = '2019-01-01T12:00:00Z' notice_model['document_id'] = 'testString' notice_model['query_id'] = 'testString' notice_model['severity'] = 'warning' @@ -9903,11 +10398,10 @@ def test_query_response_serialization(self): query_result_model['result_metadata'] = query_result_metadata_model query_result_model['score'] = { 'foo': 'bar' } - query_aggregation_model = {} # Histogram - query_aggregation_model['type'] = 'histogram' - query_aggregation_model['matching_results'] = 38 - query_aggregation_model['field'] = 'testString' - query_aggregation_model['interval'] = 38 + query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model['type'] = 'filter' + query_aggregation_model['match'] = 'testString' + query_aggregation_model['matching_results'] = 26 query_passages_model = {} # QueryPassages query_passages_model['document_id'] = 'testString' @@ -10025,6 +10519,116 @@ def test_query_result_metadata_serialization(self): query_result_metadata_model_json2 = query_result_metadata_model.to_dict() assert query_result_metadata_model_json2 == query_result_metadata_model_json +class TestModel_QueryTermAggregationResult(): + """ + Test Class for QueryTermAggregationResult + """ + + def test_query_term_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryTermAggregationResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model['type'] = 'filter' + query_aggregation_model['match'] = 'testString' + query_aggregation_model['matching_results'] = 26 + + # Construct a json representation of a QueryTermAggregationResult model + query_term_aggregation_result_model_json = {} + query_term_aggregation_result_model_json['key'] = 'testString' + query_term_aggregation_result_model_json['matching_results'] = 38 + query_term_aggregation_result_model_json['relevancy'] = 72.5 + query_term_aggregation_result_model_json['total_matching_documents'] = 38 + query_term_aggregation_result_model_json['estimated_matching_documents'] = 38 + query_term_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + + # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation + query_term_aggregation_result_model = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json) + assert query_term_aggregation_result_model != False + + # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation + query_term_aggregation_result_model_dict = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json).__dict__ + query_term_aggregation_result_model2 = QueryTermAggregationResult(**query_term_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_term_aggregation_result_model == query_term_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_term_aggregation_result_model_json2 = query_term_aggregation_result_model.to_dict() + assert query_term_aggregation_result_model_json2 == query_term_aggregation_result_model_json + +class TestModel_QueryTimesliceAggregationResult(): + """ + Test Class for QueryTimesliceAggregationResult + """ + + def test_query_timeslice_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryTimesliceAggregationResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model['type'] = 'filter' + query_aggregation_model['match'] = 'testString' + query_aggregation_model['matching_results'] = 26 + + # Construct a json representation of a QueryTimesliceAggregationResult model + query_timeslice_aggregation_result_model_json = {} + query_timeslice_aggregation_result_model_json['key_as_string'] = 'testString' + query_timeslice_aggregation_result_model_json['key'] = 26 + query_timeslice_aggregation_result_model_json['matching_results'] = 26 + query_timeslice_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + + # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation + query_timeslice_aggregation_result_model = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json) + assert query_timeslice_aggregation_result_model != False + + # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation + query_timeslice_aggregation_result_model_dict = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json).__dict__ + query_timeslice_aggregation_result_model2 = QueryTimesliceAggregationResult(**query_timeslice_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_timeslice_aggregation_result_model == query_timeslice_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_timeslice_aggregation_result_model_json2 = query_timeslice_aggregation_result_model.to_dict() + assert query_timeslice_aggregation_result_model_json2 == query_timeslice_aggregation_result_model_json + +class TestModel_QueryTopHitsAggregationResult(): + """ + Test Class for QueryTopHitsAggregationResult + """ + + def test_query_top_hits_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryTopHitsAggregationResult + """ + + # Construct a json representation of a QueryTopHitsAggregationResult model + query_top_hits_aggregation_result_model_json = {} + query_top_hits_aggregation_result_model_json['matching_results'] = 38 + query_top_hits_aggregation_result_model_json['hits'] = [{}] + + # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation + query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) + assert query_top_hits_aggregation_result_model != False + + # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation + query_top_hits_aggregation_result_model_dict = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json).__dict__ + query_top_hits_aggregation_result_model2 = QueryTopHitsAggregationResult(**query_top_hits_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_top_hits_aggregation_result_model == query_top_hits_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() + assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json + class TestModel_RetrievalDetails(): """ Test Class for RetrievalDetails @@ -10138,7 +10742,7 @@ def test_search_status_serialization(self): search_status_model_json['scope'] = 'testString' search_status_model_json['status'] = 'NO_DATA' search_status_model_json['status_description'] = 'testString' - search_status_model_json['last_trained'] = "2019-01-01" + search_status_model_json['last_trained'] = '2019-01-01' # Construct a model instance of SearchStatus by calling from_dict on the json representation search_status_model = SearchStatus.from_dict(search_status_model_json) @@ -10524,7 +11128,7 @@ def test_source_status_serialization(self): # Construct a json representation of a SourceStatus model source_status_model_json = {} source_status_model_json['status'] = 'running' - source_status_model_json['next_crawl'] = "2019-01-01T12:00:00Z" + source_status_model_json['next_crawl'] = '2019-01-01T12:00:00Z' # Construct a model instance of SourceStatus by calling from_dict on the json representation source_status_model = SourceStatus.from_dict(source_status_model_json) @@ -10633,49 +11237,6 @@ def test_token_dict_status_response_serialization(self): token_dict_status_response_model_json2 = token_dict_status_response_model.to_dict() assert token_dict_status_response_model_json2 == token_dict_status_response_model_json -class TestModel_TopHitsResults(): - """ - Test Class for TopHitsResults - """ - - def test_top_hits_results_serialization(self): - """ - Test serialization/deserialization for TopHitsResults - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_result_metadata_model = {} # QueryResultMetadata - query_result_metadata_model['score'] = 72.5 - query_result_metadata_model['confidence'] = 72.5 - - query_result_model = {} # QueryResult - query_result_model['id'] = 'testString' - query_result_model['metadata'] = {} - query_result_model['collection_id'] = 'testString' - query_result_model['result_metadata'] = query_result_metadata_model - query_result_model['foo'] = { 'foo': 'bar' } - - # Construct a json representation of a TopHitsResults model - top_hits_results_model_json = {} - top_hits_results_model_json['matching_results'] = 38 - top_hits_results_model_json['hits'] = [query_result_model] - - # Construct a model instance of TopHitsResults by calling from_dict on the json representation - top_hits_results_model = TopHitsResults.from_dict(top_hits_results_model_json) - assert top_hits_results_model != False - - # Construct a model instance of TopHitsResults by calling from_dict on the json representation - top_hits_results_model_dict = TopHitsResults.from_dict(top_hits_results_model_json).__dict__ - top_hits_results_model2 = TopHitsResults(**top_hits_results_model_dict) - - # Verify the model instances are equivalent - assert top_hits_results_model == top_hits_results_model2 - - # Convert model instance back to dict and verify no loss of data - top_hits_results_model_json2 = top_hits_results_model.to_dict() - assert top_hits_results_model_json2 == top_hits_results_model_json - class TestModel_TrainingDataSet(): """ Test Class for TrainingDataSet @@ -10845,8 +11406,8 @@ def test_training_status_serialization(self): training_status_model_json['minimum_examples_added'] = True training_status_model_json['sufficient_label_diversity'] = True training_status_model_json['notices'] = 38 - training_status_model_json['successfully_trained'] = "2019-01-01T12:00:00Z" - training_status_model_json['data_updated'] = "2019-01-01T12:00:00Z" + training_status_model_json['successfully_trained'] = '2019-01-01T12:00:00Z' + training_status_model_json['data_updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of TrainingStatus by calling from_dict on the json representation training_status_model = TrainingStatus.from_dict(training_status_model_json) @@ -11013,245 +11574,232 @@ def test_x_path_patterns_serialization(self): x_path_patterns_model_json2 = x_path_patterns_model.to_dict() assert x_path_patterns_model_json2 == x_path_patterns_model_json -class TestModel_Calculation(): +class TestModel_QueryCalculationAggregation(): """ - Test Class for Calculation + Test Class for QueryCalculationAggregation """ - def test_calculation_serialization(self): + def test_query_calculation_aggregation_serialization(self): """ - Test serialization/deserialization for Calculation + Test serialization/deserialization for QueryCalculationAggregation """ - # Construct a json representation of a Calculation model - calculation_model_json = {} - calculation_model_json['type'] = 'unique_count' - calculation_model_json['matching_results'] = 38 - calculation_model_json['field'] = 'testString' - calculation_model_json['value'] = 72.5 + # Construct a json representation of a QueryCalculationAggregation model + query_calculation_aggregation_model_json = {} + query_calculation_aggregation_model_json['type'] = 'unique_count' + query_calculation_aggregation_model_json['field'] = 'testString' + query_calculation_aggregation_model_json['value'] = 72.5 - # Construct a model instance of Calculation by calling from_dict on the json representation - calculation_model = Calculation.from_dict(calculation_model_json) - assert calculation_model != False + # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation + query_calculation_aggregation_model = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json) + assert query_calculation_aggregation_model != False - # Construct a model instance of Calculation by calling from_dict on the json representation - calculation_model_dict = Calculation.from_dict(calculation_model_json).__dict__ - calculation_model2 = Calculation(**calculation_model_dict) + # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation + query_calculation_aggregation_model_dict = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json).__dict__ + query_calculation_aggregation_model2 = QueryCalculationAggregation(**query_calculation_aggregation_model_dict) # Verify the model instances are equivalent - assert calculation_model == calculation_model2 + assert query_calculation_aggregation_model == query_calculation_aggregation_model2 # Convert model instance back to dict and verify no loss of data - calculation_model_json2 = calculation_model.to_dict() - assert calculation_model_json2 == calculation_model_json + query_calculation_aggregation_model_json2 = query_calculation_aggregation_model.to_dict() + assert query_calculation_aggregation_model_json2 == query_calculation_aggregation_model_json -class TestModel_Filter(): +class TestModel_QueryFilterAggregation(): """ - Test Class for Filter + Test Class for QueryFilterAggregation """ - def test_filter_serialization(self): + def test_query_filter_aggregation_serialization(self): """ - Test serialization/deserialization for Filter + Test serialization/deserialization for QueryFilterAggregation """ - # Construct a json representation of a Filter model - filter_model_json = {} - filter_model_json['type'] = 'filter' - filter_model_json['matching_results'] = 38 - filter_model_json['match'] = 'testString' + # Construct a json representation of a QueryFilterAggregation model + query_filter_aggregation_model_json = {} + query_filter_aggregation_model_json['type'] = 'filter' + query_filter_aggregation_model_json['match'] = 'testString' + query_filter_aggregation_model_json['matching_results'] = 26 - # Construct a model instance of Filter by calling from_dict on the json representation - filter_model = Filter.from_dict(filter_model_json) - assert filter_model != False + # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation + query_filter_aggregation_model = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json) + assert query_filter_aggregation_model != False - # Construct a model instance of Filter by calling from_dict on the json representation - filter_model_dict = Filter.from_dict(filter_model_json).__dict__ - filter_model2 = Filter(**filter_model_dict) + # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation + query_filter_aggregation_model_dict = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json).__dict__ + query_filter_aggregation_model2 = QueryFilterAggregation(**query_filter_aggregation_model_dict) # Verify the model instances are equivalent - assert filter_model == filter_model2 + assert query_filter_aggregation_model == query_filter_aggregation_model2 # Convert model instance back to dict and verify no loss of data - filter_model_json2 = filter_model.to_dict() - assert filter_model_json2 == filter_model_json + query_filter_aggregation_model_json2 = query_filter_aggregation_model.to_dict() + assert query_filter_aggregation_model_json2 == query_filter_aggregation_model_json -class TestModel_Histogram(): +class TestModel_QueryHistogramAggregation(): """ - Test Class for Histogram + Test Class for QueryHistogramAggregation """ - def test_histogram_serialization(self): + def test_query_histogram_aggregation_serialization(self): """ - Test serialization/deserialization for Histogram + Test serialization/deserialization for QueryHistogramAggregation """ - # Construct a json representation of a Histogram model - histogram_model_json = {} - histogram_model_json['type'] = 'histogram' - histogram_model_json['matching_results'] = 38 - histogram_model_json['field'] = 'testString' - histogram_model_json['interval'] = 38 + # Construct a json representation of a QueryHistogramAggregation model + query_histogram_aggregation_model_json = {} + query_histogram_aggregation_model_json['type'] = 'histogram' + query_histogram_aggregation_model_json['field'] = 'testString' + query_histogram_aggregation_model_json['interval'] = 38 + query_histogram_aggregation_model_json['name'] = 'testString' - # Construct a model instance of Histogram by calling from_dict on the json representation - histogram_model = Histogram.from_dict(histogram_model_json) - assert histogram_model != False + # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation + query_histogram_aggregation_model = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json) + assert query_histogram_aggregation_model != False - # Construct a model instance of Histogram by calling from_dict on the json representation - histogram_model_dict = Histogram.from_dict(histogram_model_json).__dict__ - histogram_model2 = Histogram(**histogram_model_dict) + # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation + query_histogram_aggregation_model_dict = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json).__dict__ + query_histogram_aggregation_model2 = QueryHistogramAggregation(**query_histogram_aggregation_model_dict) # Verify the model instances are equivalent - assert histogram_model == histogram_model2 + assert query_histogram_aggregation_model == query_histogram_aggregation_model2 # Convert model instance back to dict and verify no loss of data - histogram_model_json2 = histogram_model.to_dict() - assert histogram_model_json2 == histogram_model_json + query_histogram_aggregation_model_json2 = query_histogram_aggregation_model.to_dict() + assert query_histogram_aggregation_model_json2 == query_histogram_aggregation_model_json -class TestModel_Nested(): +class TestModel_QueryNestedAggregation(): """ - Test Class for Nested + Test Class for QueryNestedAggregation """ - def test_nested_serialization(self): + def test_query_nested_aggregation_serialization(self): """ - Test serialization/deserialization for Nested + Test serialization/deserialization for QueryNestedAggregation """ - # Construct a json representation of a Nested model - nested_model_json = {} - nested_model_json['type'] = 'nested' - nested_model_json['matching_results'] = 38 - nested_model_json['path'] = 'testString' + # Construct a json representation of a QueryNestedAggregation model + query_nested_aggregation_model_json = {} + query_nested_aggregation_model_json['type'] = 'nested' + query_nested_aggregation_model_json['path'] = 'testString' + query_nested_aggregation_model_json['matching_results'] = 26 - # Construct a model instance of Nested by calling from_dict on the json representation - nested_model = Nested.from_dict(nested_model_json) - assert nested_model != False + # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation + query_nested_aggregation_model = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json) + assert query_nested_aggregation_model != False - # Construct a model instance of Nested by calling from_dict on the json representation - nested_model_dict = Nested.from_dict(nested_model_json).__dict__ - nested_model2 = Nested(**nested_model_dict) + # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation + query_nested_aggregation_model_dict = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json).__dict__ + query_nested_aggregation_model2 = QueryNestedAggregation(**query_nested_aggregation_model_dict) # Verify the model instances are equivalent - assert nested_model == nested_model2 + assert query_nested_aggregation_model == query_nested_aggregation_model2 # Convert model instance back to dict and verify no loss of data - nested_model_json2 = nested_model.to_dict() - assert nested_model_json2 == nested_model_json + query_nested_aggregation_model_json2 = query_nested_aggregation_model.to_dict() + assert query_nested_aggregation_model_json2 == query_nested_aggregation_model_json -class TestModel_Term(): +class TestModel_QueryTermAggregation(): """ - Test Class for Term + Test Class for QueryTermAggregation """ - def test_term_serialization(self): + def test_query_term_aggregation_serialization(self): """ - Test serialization/deserialization for Term + Test serialization/deserialization for QueryTermAggregation """ - # Construct a json representation of a Term model - term_model_json = {} - term_model_json['type'] = 'term' - term_model_json['matching_results'] = 38 - term_model_json['field'] = 'testString' - term_model_json['count'] = 38 + # Construct a json representation of a QueryTermAggregation model + query_term_aggregation_model_json = {} + query_term_aggregation_model_json['type'] = 'term' + query_term_aggregation_model_json['field'] = 'testString' + query_term_aggregation_model_json['count'] = 38 + query_term_aggregation_model_json['name'] = 'testString' - # Construct a model instance of Term by calling from_dict on the json representation - term_model = Term.from_dict(term_model_json) - assert term_model != False + # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation + query_term_aggregation_model = QueryTermAggregation.from_dict(query_term_aggregation_model_json) + assert query_term_aggregation_model != False - # Construct a model instance of Term by calling from_dict on the json representation - term_model_dict = Term.from_dict(term_model_json).__dict__ - term_model2 = Term(**term_model_dict) + # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation + query_term_aggregation_model_dict = QueryTermAggregation.from_dict(query_term_aggregation_model_json).__dict__ + query_term_aggregation_model2 = QueryTermAggregation(**query_term_aggregation_model_dict) # Verify the model instances are equivalent - assert term_model == term_model2 + assert query_term_aggregation_model == query_term_aggregation_model2 # Convert model instance back to dict and verify no loss of data - term_model_json2 = term_model.to_dict() - assert term_model_json2 == term_model_json + query_term_aggregation_model_json2 = query_term_aggregation_model.to_dict() + assert query_term_aggregation_model_json2 == query_term_aggregation_model_json -class TestModel_Timeslice(): +class TestModel_QueryTimesliceAggregation(): """ - Test Class for Timeslice + Test Class for QueryTimesliceAggregation """ - def test_timeslice_serialization(self): + def test_query_timeslice_aggregation_serialization(self): """ - Test serialization/deserialization for Timeslice + Test serialization/deserialization for QueryTimesliceAggregation """ - # Construct a json representation of a Timeslice model - timeslice_model_json = {} - timeslice_model_json['type'] = 'timeslice' - timeslice_model_json['matching_results'] = 38 - timeslice_model_json['field'] = 'testString' - timeslice_model_json['interval'] = 'testString' - timeslice_model_json['anomaly'] = True + # Construct a json representation of a QueryTimesliceAggregation model + query_timeslice_aggregation_model_json = {} + query_timeslice_aggregation_model_json['type'] = 'timeslice' + query_timeslice_aggregation_model_json['field'] = 'testString' + query_timeslice_aggregation_model_json['interval'] = 'testString' + query_timeslice_aggregation_model_json['name'] = 'testString' - # Construct a model instance of Timeslice by calling from_dict on the json representation - timeslice_model = Timeslice.from_dict(timeslice_model_json) - assert timeslice_model != False + # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation + query_timeslice_aggregation_model = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json) + assert query_timeslice_aggregation_model != False - # Construct a model instance of Timeslice by calling from_dict on the json representation - timeslice_model_dict = Timeslice.from_dict(timeslice_model_json).__dict__ - timeslice_model2 = Timeslice(**timeslice_model_dict) + # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation + query_timeslice_aggregation_model_dict = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json).__dict__ + query_timeslice_aggregation_model2 = QueryTimesliceAggregation(**query_timeslice_aggregation_model_dict) # Verify the model instances are equivalent - assert timeslice_model == timeslice_model2 + assert query_timeslice_aggregation_model == query_timeslice_aggregation_model2 # Convert model instance back to dict and verify no loss of data - timeslice_model_json2 = timeslice_model.to_dict() - assert timeslice_model_json2 == timeslice_model_json + query_timeslice_aggregation_model_json2 = query_timeslice_aggregation_model.to_dict() + assert query_timeslice_aggregation_model_json2 == query_timeslice_aggregation_model_json -class TestModel_TopHits(): +class TestModel_QueryTopHitsAggregation(): """ - Test Class for TopHits + Test Class for QueryTopHitsAggregation """ - def test_top_hits_serialization(self): + def test_query_top_hits_aggregation_serialization(self): """ - Test serialization/deserialization for TopHits + Test serialization/deserialization for QueryTopHitsAggregation """ # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata - query_result_metadata_model['score'] = 72.5 - query_result_metadata_model['confidence'] = 72.5 - - query_result_model = {} # QueryResult - query_result_model['id'] = 'testString' - query_result_model['metadata'] = {} - query_result_model['collection_id'] = 'testString' - query_result_model['result_metadata'] = query_result_metadata_model - query_result_model['foo'] = { 'foo': 'bar' } - - top_hits_results_model = {} # TopHitsResults - top_hits_results_model['matching_results'] = 38 - top_hits_results_model['hits'] = [query_result_model] + query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult + query_top_hits_aggregation_result_model['matching_results'] = 38 + query_top_hits_aggregation_result_model['hits'] = [{}] - # Construct a json representation of a TopHits model - top_hits_model_json = {} - top_hits_model_json['type'] = 'top_hits' - top_hits_model_json['matching_results'] = 38 - top_hits_model_json['size'] = 38 - top_hits_model_json['hits'] = top_hits_results_model + # Construct a json representation of a QueryTopHitsAggregation model + query_top_hits_aggregation_model_json = {} + query_top_hits_aggregation_model_json['type'] = 'top_hits' + query_top_hits_aggregation_model_json['size'] = 38 + query_top_hits_aggregation_model_json['name'] = 'testString' + query_top_hits_aggregation_model_json['hits'] = query_top_hits_aggregation_result_model - # Construct a model instance of TopHits by calling from_dict on the json representation - top_hits_model = TopHits.from_dict(top_hits_model_json) - assert top_hits_model != False + # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation + query_top_hits_aggregation_model = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json) + assert query_top_hits_aggregation_model != False - # Construct a model instance of TopHits by calling from_dict on the json representation - top_hits_model_dict = TopHits.from_dict(top_hits_model_json).__dict__ - top_hits_model2 = TopHits(**top_hits_model_dict) + # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation + query_top_hits_aggregation_model_dict = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json).__dict__ + query_top_hits_aggregation_model2 = QueryTopHitsAggregation(**query_top_hits_aggregation_model_dict) # Verify the model instances are equivalent - assert top_hits_model == top_hits_model2 + assert query_top_hits_aggregation_model == query_top_hits_aggregation_model2 # Convert model instance back to dict and verify no loss of data - top_hits_model_json2 = top_hits_model.to_dict() - assert top_hits_model_json2 == top_hits_model_json + query_top_hits_aggregation_model_json2 = query_top_hits_aggregation_model.to_dict() + assert query_top_hits_aggregation_model_json2 == query_top_hits_aggregation_model_json # endregion diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 2f39f5139..f0ed3cb4d 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2021. +# (C) Copyright IBM Corp. 2018, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -36,11 +36,38 @@ _service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), version=version - ) +) _base_url = 'https://api.us-south.language-translator.watson.cloud.ibm.com' _service.set_service_url(_base_url) + +def preprocess_url(operation_path: str): + """ + Returns the request url associated with the specified operation path. + This will be base_url concatenated with a quoted version of operation_path. + The returned request URL is used to register the mock response so it needs + to match the request URL that is formed by the requests library. + """ + # First, unquote the path since it might have some quoted/escaped characters in it + # due to how the generator inserts the operation paths into the unit test code. + operation_path = urllib.parse.unquote(operation_path) + + # Next, quote the path using urllib so that we approximate what will + # happen during request processing. + operation_path = urllib.parse.quote(operation_path, safe='/') + + # Finally, form the request URL from the base URL and operation path. + request_url = _base_url + operation_path + + # If the request url does NOT end with a /, then just return it as-is. + # Otherwise, return a regular expression that matches one or more trailing /. + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + ############################################################################## # Start of Service: Languages ############################################################################## @@ -51,24 +78,13 @@ class TestListLanguages(): Test Class for list_languages """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_languages_all_params(self): """ list_languages() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/languages') + url = preprocess_url('/v3/languages') mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' responses.add(responses.GET, url, @@ -84,6 +100,14 @@ def test_list_languages_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_languages_all_params_with_retries(self): + # Enable retries and run test_list_languages_all_params. + _service.enable_retries() + self.test_list_languages_all_params() + + # Disable retries and run test_list_languages_all_params. + _service.disable_retries() + self.test_list_languages_all_params() @responses.activate def test_list_languages_value_error(self): @@ -91,7 +115,7 @@ def test_list_languages_value_error(self): test_list_languages_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/languages') + url = preprocess_url('/v3/languages') mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' responses.add(responses.GET, url, @@ -108,6 +132,14 @@ def test_list_languages_value_error(self): _service.list_languages(**req_copy) + def test_list_languages_value_error_with_retries(self): + # Enable retries and run test_list_languages_value_error. + _service.enable_retries() + self.test_list_languages_value_error() + + # Disable retries and run test_list_languages_value_error. + _service.disable_retries() + self.test_list_languages_value_error() # endregion ############################################################################## @@ -124,24 +156,13 @@ class TestTranslate(): Test Class for translate """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_translate_all_params(self): """ translate() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/translate') + url = preprocess_url('/v3/translate') mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' responses.add(responses.POST, url, @@ -174,6 +195,14 @@ def test_translate_all_params(self): assert req_body['source'] == 'testString' assert req_body['target'] == 'testString' + def test_translate_all_params_with_retries(self): + # Enable retries and run test_translate_all_params. + _service.enable_retries() + self.test_translate_all_params() + + # Disable retries and run test_translate_all_params. + _service.disable_retries() + self.test_translate_all_params() @responses.activate def test_translate_value_error(self): @@ -181,7 +210,7 @@ def test_translate_value_error(self): test_translate_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/translate') + url = preprocess_url('/v3/translate') mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' responses.add(responses.POST, url, @@ -205,6 +234,14 @@ def test_translate_value_error(self): _service.translate(**req_copy) + def test_translate_value_error_with_retries(self): + # Enable retries and run test_translate_value_error. + _service.enable_retries() + self.test_translate_value_error() + + # Disable retries and run test_translate_value_error. + _service.disable_retries() + self.test_translate_value_error() # endregion ############################################################################## @@ -221,24 +258,13 @@ class TestListIdentifiableLanguages(): Test Class for list_identifiable_languages """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_identifiable_languages_all_params(self): """ list_identifiable_languages() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/identifiable_languages') + url = preprocess_url('/v3/identifiable_languages') mock_response = '{"languages": [{"language": "language", "name": "name"}]}' responses.add(responses.GET, url, @@ -254,6 +280,14 @@ def test_list_identifiable_languages_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_identifiable_languages_all_params_with_retries(self): + # Enable retries and run test_list_identifiable_languages_all_params. + _service.enable_retries() + self.test_list_identifiable_languages_all_params() + + # Disable retries and run test_list_identifiable_languages_all_params. + _service.disable_retries() + self.test_list_identifiable_languages_all_params() @responses.activate def test_list_identifiable_languages_value_error(self): @@ -261,7 +295,7 @@ def test_list_identifiable_languages_value_error(self): test_list_identifiable_languages_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/identifiable_languages') + url = preprocess_url('/v3/identifiable_languages') mock_response = '{"languages": [{"language": "language", "name": "name"}]}' responses.add(responses.GET, url, @@ -278,30 +312,27 @@ def test_list_identifiable_languages_value_error(self): _service.list_identifiable_languages(**req_copy) + def test_list_identifiable_languages_value_error_with_retries(self): + # Enable retries and run test_list_identifiable_languages_value_error. + _service.enable_retries() + self.test_list_identifiable_languages_value_error() + + # Disable retries and run test_list_identifiable_languages_value_error. + _service.disable_retries() + self.test_list_identifiable_languages_value_error() class TestIdentify(): """ Test Class for identify """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_identify_all_params(self): """ identify() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/identify') + url = preprocess_url('/v3/identify') mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' responses.add(responses.POST, url, @@ -324,6 +355,14 @@ def test_identify_all_params(self): # Validate body params assert str(responses.calls[0].request.body, 'utf-8') == text + def test_identify_all_params_with_retries(self): + # Enable retries and run test_identify_all_params. + _service.enable_retries() + self.test_identify_all_params() + + # Disable retries and run test_identify_all_params. + _service.disable_retries() + self.test_identify_all_params() @responses.activate def test_identify_value_error(self): @@ -331,7 +370,7 @@ def test_identify_value_error(self): test_identify_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/identify') + url = preprocess_url('/v3/identify') mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' responses.add(responses.POST, url, @@ -352,6 +391,14 @@ def test_identify_value_error(self): _service.identify(**req_copy) + def test_identify_value_error_with_retries(self): + # Enable retries and run test_identify_value_error. + _service.enable_retries() + self.test_identify_value_error() + + # Disable retries and run test_identify_value_error. + _service.disable_retries() + self.test_identify_value_error() # endregion ############################################################################## @@ -368,24 +415,13 @@ class TestListModels(): Test Class for list_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_models_all_params(self): """ list_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/models') + url = preprocess_url('/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' responses.add(responses.GET, url, @@ -416,6 +452,14 @@ def test_list_models_all_params(self): assert 'target={}'.format(target) in query_string assert 'default={}'.format('true' if default else 'false') in query_string + def test_list_models_all_params_with_retries(self): + # Enable retries and run test_list_models_all_params. + _service.enable_retries() + self.test_list_models_all_params() + + # Disable retries and run test_list_models_all_params. + _service.disable_retries() + self.test_list_models_all_params() @responses.activate def test_list_models_required_params(self): @@ -423,7 +467,7 @@ def test_list_models_required_params(self): test_list_models_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/models') + url = preprocess_url('/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' responses.add(responses.GET, url, @@ -439,6 +483,14 @@ def test_list_models_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_models_required_params_with_retries(self): + # Enable retries and run test_list_models_required_params. + _service.enable_retries() + self.test_list_models_required_params() + + # Disable retries and run test_list_models_required_params. + _service.disable_retries() + self.test_list_models_required_params() @responses.activate def test_list_models_value_error(self): @@ -446,7 +498,7 @@ def test_list_models_value_error(self): test_list_models_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/models') + url = preprocess_url('/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' responses.add(responses.GET, url, @@ -463,30 +515,27 @@ def test_list_models_value_error(self): _service.list_models(**req_copy) + def test_list_models_value_error_with_retries(self): + # Enable retries and run test_list_models_value_error. + _service.enable_retries() + self.test_list_models_value_error() + + # Disable retries and run test_list_models_value_error. + _service.disable_retries() + self.test_list_models_value_error() class TestCreateModel(): """ Test Class for create_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_model_all_params(self): """ create_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/models') + url = preprocess_url('/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.POST, url, @@ -518,6 +567,14 @@ def test_create_model_all_params(self): assert 'base_model_id={}'.format(base_model_id) in query_string assert 'name={}'.format(name) in query_string + def test_create_model_all_params_with_retries(self): + # Enable retries and run test_create_model_all_params. + _service.enable_retries() + self.test_create_model_all_params() + + # Disable retries and run test_create_model_all_params. + _service.disable_retries() + self.test_create_model_all_params() @responses.activate def test_create_model_required_params(self): @@ -525,7 +582,7 @@ def test_create_model_required_params(self): test_create_model_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/models') + url = preprocess_url('/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.POST, url, @@ -550,6 +607,14 @@ def test_create_model_required_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'base_model_id={}'.format(base_model_id) in query_string + def test_create_model_required_params_with_retries(self): + # Enable retries and run test_create_model_required_params. + _service.enable_retries() + self.test_create_model_required_params() + + # Disable retries and run test_create_model_required_params. + _service.disable_retries() + self.test_create_model_required_params() @responses.activate def test_create_model_value_error(self): @@ -557,7 +622,7 @@ def test_create_model_value_error(self): test_create_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/models') + url = preprocess_url('/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.POST, url, @@ -578,30 +643,27 @@ def test_create_model_value_error(self): _service.create_model(**req_copy) + def test_create_model_value_error_with_retries(self): + # Enable retries and run test_create_model_value_error. + _service.enable_retries() + self.test_create_model_value_error() + + # Disable retries and run test_create_model_value_error. + _service.disable_retries() + self.test_create_model_value_error() class TestDeleteModel(): """ Test Class for delete_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_model_all_params(self): """ delete_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/models/testString') + url = preprocess_url('/v3/models/testString') mock_response = '{"status": "status"}' responses.add(responses.DELETE, url, @@ -622,6 +684,14 @@ def test_delete_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_model_all_params_with_retries(self): + # Enable retries and run test_delete_model_all_params. + _service.enable_retries() + self.test_delete_model_all_params() + + # Disable retries and run test_delete_model_all_params. + _service.disable_retries() + self.test_delete_model_all_params() @responses.activate def test_delete_model_value_error(self): @@ -629,7 +699,7 @@ def test_delete_model_value_error(self): test_delete_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/models/testString') + url = preprocess_url('/v3/models/testString') mock_response = '{"status": "status"}' responses.add(responses.DELETE, url, @@ -650,30 +720,27 @@ def test_delete_model_value_error(self): _service.delete_model(**req_copy) + def test_delete_model_value_error_with_retries(self): + # Enable retries and run test_delete_model_value_error. + _service.enable_retries() + self.test_delete_model_value_error() + + # Disable retries and run test_delete_model_value_error. + _service.disable_retries() + self.test_delete_model_value_error() class TestGetModel(): """ Test Class for get_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_model_all_params(self): """ get_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/models/testString') + url = preprocess_url('/v3/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.GET, url, @@ -694,6 +761,14 @@ def test_get_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_model_all_params_with_retries(self): + # Enable retries and run test_get_model_all_params. + _service.enable_retries() + self.test_get_model_all_params() + + # Disable retries and run test_get_model_all_params. + _service.disable_retries() + self.test_get_model_all_params() @responses.activate def test_get_model_value_error(self): @@ -701,7 +776,7 @@ def test_get_model_value_error(self): test_get_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/models/testString') + url = preprocess_url('/v3/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' responses.add(responses.GET, url, @@ -722,6 +797,14 @@ def test_get_model_value_error(self): _service.get_model(**req_copy) + def test_get_model_value_error_with_retries(self): + # Enable retries and run test_get_model_value_error. + _service.enable_retries() + self.test_get_model_value_error() + + # Disable retries and run test_get_model_value_error. + _service.disable_retries() + self.test_get_model_value_error() # endregion ############################################################################## @@ -738,24 +821,13 @@ class TestListDocuments(): Test Class for list_documents """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_documents_all_params(self): """ list_documents() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents') + url = preprocess_url('/v3/documents') mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' responses.add(responses.GET, url, @@ -771,6 +843,14 @@ def test_list_documents_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_documents_all_params_with_retries(self): + # Enable retries and run test_list_documents_all_params. + _service.enable_retries() + self.test_list_documents_all_params() + + # Disable retries and run test_list_documents_all_params. + _service.disable_retries() + self.test_list_documents_all_params() @responses.activate def test_list_documents_value_error(self): @@ -778,7 +858,7 @@ def test_list_documents_value_error(self): test_list_documents_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents') + url = preprocess_url('/v3/documents') mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' responses.add(responses.GET, url, @@ -795,30 +875,27 @@ def test_list_documents_value_error(self): _service.list_documents(**req_copy) + def test_list_documents_value_error_with_retries(self): + # Enable retries and run test_list_documents_value_error. + _service.enable_retries() + self.test_list_documents_value_error() + + # Disable retries and run test_list_documents_value_error. + _service.disable_retries() + self.test_list_documents_value_error() class TestTranslateDocument(): """ Test Class for translate_document """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_translate_document_all_params(self): """ translate_document() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents') + url = preprocess_url('/v3/documents') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' responses.add(responses.POST, url, @@ -851,6 +928,14 @@ def test_translate_document_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 202 + def test_translate_document_all_params_with_retries(self): + # Enable retries and run test_translate_document_all_params. + _service.enable_retries() + self.test_translate_document_all_params() + + # Disable retries and run test_translate_document_all_params. + _service.disable_retries() + self.test_translate_document_all_params() @responses.activate def test_translate_document_required_params(self): @@ -858,7 +943,7 @@ def test_translate_document_required_params(self): test_translate_document_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents') + url = preprocess_url('/v3/documents') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' responses.add(responses.POST, url, @@ -881,6 +966,14 @@ def test_translate_document_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 202 + def test_translate_document_required_params_with_retries(self): + # Enable retries and run test_translate_document_required_params. + _service.enable_retries() + self.test_translate_document_required_params() + + # Disable retries and run test_translate_document_required_params. + _service.disable_retries() + self.test_translate_document_required_params() @responses.activate def test_translate_document_value_error(self): @@ -888,7 +981,7 @@ def test_translate_document_value_error(self): test_translate_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents') + url = preprocess_url('/v3/documents') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' responses.add(responses.POST, url, @@ -910,30 +1003,27 @@ def test_translate_document_value_error(self): _service.translate_document(**req_copy) + def test_translate_document_value_error_with_retries(self): + # Enable retries and run test_translate_document_value_error. + _service.enable_retries() + self.test_translate_document_value_error() + + # Disable retries and run test_translate_document_value_error. + _service.disable_retries() + self.test_translate_document_value_error() class TestGetDocumentStatus(): """ Test Class for get_document_status """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_document_status_all_params(self): """ get_document_status() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents/testString') + url = preprocess_url('/v3/documents/testString') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' responses.add(responses.GET, url, @@ -954,6 +1044,14 @@ def test_get_document_status_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_document_status_all_params_with_retries(self): + # Enable retries and run test_get_document_status_all_params. + _service.enable_retries() + self.test_get_document_status_all_params() + + # Disable retries and run test_get_document_status_all_params. + _service.disable_retries() + self.test_get_document_status_all_params() @responses.activate def test_get_document_status_value_error(self): @@ -961,7 +1059,7 @@ def test_get_document_status_value_error(self): test_get_document_status_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents/testString') + url = preprocess_url('/v3/documents/testString') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' responses.add(responses.GET, url, @@ -982,30 +1080,27 @@ def test_get_document_status_value_error(self): _service.get_document_status(**req_copy) + def test_get_document_status_value_error_with_retries(self): + # Enable retries and run test_get_document_status_value_error. + _service.enable_retries() + self.test_get_document_status_value_error() + + # Disable retries and run test_get_document_status_value_error. + _service.disable_retries() + self.test_get_document_status_value_error() class TestDeleteDocument(): """ Test Class for delete_document """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_document_all_params(self): """ delete_document() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents/testString') + url = preprocess_url('/v3/documents/testString') responses.add(responses.DELETE, url, status=204) @@ -1023,6 +1118,14 @@ def test_delete_document_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_document_all_params_with_retries(self): + # Enable retries and run test_delete_document_all_params. + _service.enable_retries() + self.test_delete_document_all_params() + + # Disable retries and run test_delete_document_all_params. + _service.disable_retries() + self.test_delete_document_all_params() @responses.activate def test_delete_document_value_error(self): @@ -1030,7 +1133,7 @@ def test_delete_document_value_error(self): test_delete_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents/testString') + url = preprocess_url('/v3/documents/testString') responses.add(responses.DELETE, url, status=204) @@ -1048,30 +1151,27 @@ def test_delete_document_value_error(self): _service.delete_document(**req_copy) + def test_delete_document_value_error_with_retries(self): + # Enable retries and run test_delete_document_value_error. + _service.enable_retries() + self.test_delete_document_value_error() + + # Disable retries and run test_delete_document_value_error. + _service.disable_retries() + self.test_delete_document_value_error() class TestGetTranslatedDocument(): """ Test Class for get_translated_document """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_translated_document_all_params(self): """ get_translated_document() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents/testString/translated_document') + url = preprocess_url('/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -1094,6 +1194,14 @@ def test_get_translated_document_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_translated_document_all_params_with_retries(self): + # Enable retries and run test_get_translated_document_all_params. + _service.enable_retries() + self.test_get_translated_document_all_params() + + # Disable retries and run test_get_translated_document_all_params. + _service.disable_retries() + self.test_get_translated_document_all_params() @responses.activate def test_get_translated_document_required_params(self): @@ -1101,7 +1209,7 @@ def test_get_translated_document_required_params(self): test_get_translated_document_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents/testString/translated_document') + url = preprocess_url('/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -1122,6 +1230,14 @@ def test_get_translated_document_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_translated_document_required_params_with_retries(self): + # Enable retries and run test_get_translated_document_required_params. + _service.enable_retries() + self.test_get_translated_document_required_params() + + # Disable retries and run test_get_translated_document_required_params. + _service.disable_retries() + self.test_get_translated_document_required_params() @responses.activate def test_get_translated_document_value_error(self): @@ -1129,7 +1245,7 @@ def test_get_translated_document_value_error(self): test_get_translated_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v3/documents/testString/translated_document') + url = preprocess_url('/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' responses.add(responses.GET, url, @@ -1150,6 +1266,14 @@ def test_get_translated_document_value_error(self): _service.get_translated_document(**req_copy) + def test_get_translated_document_value_error_with_retries(self): + # Enable retries and run test_get_translated_document_value_error. + _service.enable_retries() + self.test_get_translated_document_value_error() + + # Disable retries and run test_get_translated_document_value_error. + _service.disable_retries() + self.test_get_translated_document_value_error() # endregion ############################################################################## @@ -1211,8 +1335,8 @@ def test_document_list_serialization(self): document_status_model['source'] = 'testString' document_status_model['detected_language_confidence'] = 0 document_status_model['target'] = 'testString' - document_status_model['created'] = "2019-01-01T12:00:00Z" - document_status_model['completed'] = "2019-01-01T12:00:00Z" + document_status_model['created'] = '2019-01-01T12:00:00Z' + document_status_model['completed'] = '2019-01-01T12:00:00Z' document_status_model['word_count'] = 38 document_status_model['character_count'] = 38 @@ -1255,8 +1379,8 @@ def test_document_status_serialization(self): document_status_model_json['source'] = 'testString' document_status_model_json['detected_language_confidence'] = 0 document_status_model_json['target'] = 'testString' - document_status_model_json['created'] = "2019-01-01T12:00:00Z" - document_status_model_json['completed'] = "2019-01-01T12:00:00Z" + document_status_model_json['created'] = '2019-01-01T12:00:00Z' + document_status_model_json['completed'] = '2019-01-01T12:00:00Z' document_status_model_json['word_count'] = 38 document_status_model_json['character_count'] = 38 diff --git a/test/unit/test_natural_language_classifier_v1.py b/test/unit/test_natural_language_classifier_v1.py deleted file mode 100644 index 37d61b978..000000000 --- a/test/unit/test_natural_language_classifier_v1.py +++ /dev/null @@ -1,741 +0,0 @@ -# -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2021. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Unit Tests for NaturalLanguageClassifierV1 -""" - -from datetime import datetime, timezone -from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime -import inspect -import io -import json -import pytest -import re -import responses -import tempfile -import urllib -from ibm_watson.natural_language_classifier_v1 import * - - -_service = NaturalLanguageClassifierV1( - authenticator=NoAuthAuthenticator() - ) - -_base_url = 'https://api.us-south.natural-language-classifier.watson.cloud.ibm.com' -_service.set_service_url(_base_url) - -############################################################################## -# Start of Service: ClassifyText -############################################################################## -# region - -class TestClassify(): - """ - Test Class for classify - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_classify_all_params(self): - """ - classify() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/classifiers/testString/classify') - mock_response = '{"classifier_id": "classifier_id", "url": "url", "text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - classifier_id = 'testString' - text = 'testString' - - # Invoke method - response = _service.classify( - classifier_id, - text, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['text'] == 'testString' - - - @responses.activate - def test_classify_value_error(self): - """ - test_classify_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/classifiers/testString/classify') - mock_response = '{"classifier_id": "classifier_id", "url": "url", "text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - classifier_id = 'testString' - text = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "classifier_id": classifier_id, - "text": text, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.classify(**req_copy) - - - -class TestClassifyCollection(): - """ - Test Class for classify_collection - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_classify_collection_all_params(self): - """ - classify_collection() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/classifiers/testString/classify_collection') - mock_response = '{"classifier_id": "classifier_id", "url": "url", "collection": [{"text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ClassifyInput model - classify_input_model = {} - classify_input_model['text'] = 'How hot will it be today?' - - # Set up parameter values - classifier_id = 'testString' - collection = [classify_input_model] - - # Invoke method - response = _service.classify_collection( - classifier_id, - collection, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['collection'] == [classify_input_model] - - - @responses.activate - def test_classify_collection_value_error(self): - """ - test_classify_collection_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/classifiers/testString/classify_collection') - mock_response = '{"classifier_id": "classifier_id", "url": "url", "collection": [{"text": "text", "top_class": "top_class", "classes": [{"confidence": 10, "class_name": "class_name"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ClassifyInput model - classify_input_model = {} - classify_input_model['text'] = 'How hot will it be today?' - - # Set up parameter values - classifier_id = 'testString' - collection = [classify_input_model] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "classifier_id": classifier_id, - "collection": collection, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.classify_collection(**req_copy) - - - -# endregion -############################################################################## -# End of Service: ClassifyText -############################################################################## - -############################################################################## -# Start of Service: ManageClassifiers -############################################################################## -# region - -class TestCreateClassifier(): - """ - Test Class for create_classifier - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_create_classifier_all_params(self): - """ - create_classifier() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/classifiers') - mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00.000Z", "status_description": "status_description", "language": "language"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - training_metadata = io.BytesIO(b'This is a mock file.').getvalue() - training_data = io.BytesIO(b'This is a mock file.').getvalue() - - # Invoke method - response = _service.create_classifier( - training_metadata, - training_data, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_create_classifier_value_error(self): - """ - test_create_classifier_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/classifiers') - mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00.000Z", "status_description": "status_description", "language": "language"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - training_metadata = io.BytesIO(b'This is a mock file.').getvalue() - training_data = io.BytesIO(b'This is a mock file.').getvalue() - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "training_metadata": training_metadata, - "training_data": training_data, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_classifier(**req_copy) - - - -class TestListClassifiers(): - """ - Test Class for list_classifiers - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_list_classifiers_all_params(self): - """ - list_classifiers() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/classifiers') - mock_response = '{"classifiers": [{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00.000Z", "status_description": "status_description", "language": "language"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Invoke method - response = _service.list_classifiers() - - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - -class TestGetClassifier(): - """ - Test Class for get_classifier - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_get_classifier_all_params(self): - """ - get_classifier() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/classifiers/testString') - mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00.000Z", "status_description": "status_description", "language": "language"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Invoke method - response = _service.get_classifier( - classifier_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_get_classifier_value_error(self): - """ - test_get_classifier_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/classifiers/testString') - mock_response = '{"name": "name", "url": "url", "status": "Non Existent", "classifier_id": "classifier_id", "created": "2019-01-01T12:00:00.000Z", "status_description": "status_description", "language": "language"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "classifier_id": classifier_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_classifier(**req_copy) - - - -class TestDeleteClassifier(): - """ - Test Class for delete_classifier - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_delete_classifier_all_params(self): - """ - delete_classifier() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/classifiers/testString') - responses.add(responses.DELETE, - url, - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Invoke method - response = _service.delete_classifier( - classifier_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_delete_classifier_value_error(self): - """ - test_delete_classifier_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v1/classifiers/testString') - responses.add(responses.DELETE, - url, - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "classifier_id": classifier_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_classifier(**req_copy) - - - -# endregion -############################################################################## -# End of Service: ManageClassifiers -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region -class TestModel_Classification(): - """ - Test Class for Classification - """ - - def test_classification_serialization(self): - """ - Test serialization/deserialization for Classification - """ - - # Construct dict forms of any model objects needed in order to build this model. - - classified_class_model = {} # ClassifiedClass - classified_class_model['confidence'] = 72.5 - classified_class_model['class_name'] = 'testString' - - # Construct a json representation of a Classification model - classification_model_json = {} - classification_model_json['classifier_id'] = 'testString' - classification_model_json['url'] = 'testString' - classification_model_json['text'] = 'testString' - classification_model_json['top_class'] = 'testString' - classification_model_json['classes'] = [classified_class_model] - - # Construct a model instance of Classification by calling from_dict on the json representation - classification_model = Classification.from_dict(classification_model_json) - assert classification_model != False - - # Construct a model instance of Classification by calling from_dict on the json representation - classification_model_dict = Classification.from_dict(classification_model_json).__dict__ - classification_model2 = Classification(**classification_model_dict) - - # Verify the model instances are equivalent - assert classification_model == classification_model2 - - # Convert model instance back to dict and verify no loss of data - classification_model_json2 = classification_model.to_dict() - assert classification_model_json2 == classification_model_json - -class TestModel_ClassificationCollection(): - """ - Test Class for ClassificationCollection - """ - - def test_classification_collection_serialization(self): - """ - Test serialization/deserialization for ClassificationCollection - """ - - # Construct dict forms of any model objects needed in order to build this model. - - classified_class_model = {} # ClassifiedClass - classified_class_model['confidence'] = 72.5 - classified_class_model['class_name'] = 'testString' - - collection_item_model = {} # CollectionItem - collection_item_model['text'] = 'testString' - collection_item_model['top_class'] = 'testString' - collection_item_model['classes'] = [classified_class_model] - - # Construct a json representation of a ClassificationCollection model - classification_collection_model_json = {} - classification_collection_model_json['classifier_id'] = 'testString' - classification_collection_model_json['url'] = 'testString' - classification_collection_model_json['collection'] = [collection_item_model] - - # Construct a model instance of ClassificationCollection by calling from_dict on the json representation - classification_collection_model = ClassificationCollection.from_dict(classification_collection_model_json) - assert classification_collection_model != False - - # Construct a model instance of ClassificationCollection by calling from_dict on the json representation - classification_collection_model_dict = ClassificationCollection.from_dict(classification_collection_model_json).__dict__ - classification_collection_model2 = ClassificationCollection(**classification_collection_model_dict) - - # Verify the model instances are equivalent - assert classification_collection_model == classification_collection_model2 - - # Convert model instance back to dict and verify no loss of data - classification_collection_model_json2 = classification_collection_model.to_dict() - assert classification_collection_model_json2 == classification_collection_model_json - -class TestModel_ClassifiedClass(): - """ - Test Class for ClassifiedClass - """ - - def test_classified_class_serialization(self): - """ - Test serialization/deserialization for ClassifiedClass - """ - - # Construct a json representation of a ClassifiedClass model - classified_class_model_json = {} - classified_class_model_json['confidence'] = 72.5 - classified_class_model_json['class_name'] = 'testString' - - # Construct a model instance of ClassifiedClass by calling from_dict on the json representation - classified_class_model = ClassifiedClass.from_dict(classified_class_model_json) - assert classified_class_model != False - - # Construct a model instance of ClassifiedClass by calling from_dict on the json representation - classified_class_model_dict = ClassifiedClass.from_dict(classified_class_model_json).__dict__ - classified_class_model2 = ClassifiedClass(**classified_class_model_dict) - - # Verify the model instances are equivalent - assert classified_class_model == classified_class_model2 - - # Convert model instance back to dict and verify no loss of data - classified_class_model_json2 = classified_class_model.to_dict() - assert classified_class_model_json2 == classified_class_model_json - -class TestModel_Classifier(): - """ - Test Class for Classifier - """ - - def test_classifier_serialization(self): - """ - Test serialization/deserialization for Classifier - """ - - # Construct a json representation of a Classifier model - classifier_model_json = {} - classifier_model_json['name'] = 'testString' - classifier_model_json['url'] = 'testString' - classifier_model_json['status'] = 'Non Existent' - classifier_model_json['classifier_id'] = 'testString' - classifier_model_json['created'] = "2019-01-01T12:00:00Z" - classifier_model_json['status_description'] = 'testString' - classifier_model_json['language'] = 'testString' - - # Construct a model instance of Classifier by calling from_dict on the json representation - classifier_model = Classifier.from_dict(classifier_model_json) - assert classifier_model != False - - # Construct a model instance of Classifier by calling from_dict on the json representation - classifier_model_dict = Classifier.from_dict(classifier_model_json).__dict__ - classifier_model2 = Classifier(**classifier_model_dict) - - # Verify the model instances are equivalent - assert classifier_model == classifier_model2 - - # Convert model instance back to dict and verify no loss of data - classifier_model_json2 = classifier_model.to_dict() - assert classifier_model_json2 == classifier_model_json - -class TestModel_ClassifierList(): - """ - Test Class for ClassifierList - """ - - def test_classifier_list_serialization(self): - """ - Test serialization/deserialization for ClassifierList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - classifier_model = {} # Classifier - classifier_model['name'] = 'testString' - classifier_model['url'] = 'testString' - classifier_model['status'] = 'Non Existent' - classifier_model['classifier_id'] = 'testString' - classifier_model['created'] = "2019-01-01T12:00:00Z" - classifier_model['status_description'] = 'testString' - classifier_model['language'] = 'testString' - - # Construct a json representation of a ClassifierList model - classifier_list_model_json = {} - classifier_list_model_json['classifiers'] = [classifier_model] - - # Construct a model instance of ClassifierList by calling from_dict on the json representation - classifier_list_model = ClassifierList.from_dict(classifier_list_model_json) - assert classifier_list_model != False - - # Construct a model instance of ClassifierList by calling from_dict on the json representation - classifier_list_model_dict = ClassifierList.from_dict(classifier_list_model_json).__dict__ - classifier_list_model2 = ClassifierList(**classifier_list_model_dict) - - # Verify the model instances are equivalent - assert classifier_list_model == classifier_list_model2 - - # Convert model instance back to dict and verify no loss of data - classifier_list_model_json2 = classifier_list_model.to_dict() - assert classifier_list_model_json2 == classifier_list_model_json - -class TestModel_ClassifyInput(): - """ - Test Class for ClassifyInput - """ - - def test_classify_input_serialization(self): - """ - Test serialization/deserialization for ClassifyInput - """ - - # Construct a json representation of a ClassifyInput model - classify_input_model_json = {} - classify_input_model_json['text'] = 'testString' - - # Construct a model instance of ClassifyInput by calling from_dict on the json representation - classify_input_model = ClassifyInput.from_dict(classify_input_model_json) - assert classify_input_model != False - - # Construct a model instance of ClassifyInput by calling from_dict on the json representation - classify_input_model_dict = ClassifyInput.from_dict(classify_input_model_json).__dict__ - classify_input_model2 = ClassifyInput(**classify_input_model_dict) - - # Verify the model instances are equivalent - assert classify_input_model == classify_input_model2 - - # Convert model instance back to dict and verify no loss of data - classify_input_model_json2 = classify_input_model.to_dict() - assert classify_input_model_json2 == classify_input_model_json - -class TestModel_CollectionItem(): - """ - Test Class for CollectionItem - """ - - def test_collection_item_serialization(self): - """ - Test serialization/deserialization for CollectionItem - """ - - # Construct dict forms of any model objects needed in order to build this model. - - classified_class_model = {} # ClassifiedClass - classified_class_model['confidence'] = 72.5 - classified_class_model['class_name'] = 'testString' - - # Construct a json representation of a CollectionItem model - collection_item_model_json = {} - collection_item_model_json['text'] = 'testString' - collection_item_model_json['top_class'] = 'testString' - collection_item_model_json['classes'] = [classified_class_model] - - # Construct a model instance of CollectionItem by calling from_dict on the json representation - collection_item_model = CollectionItem.from_dict(collection_item_model_json) - assert collection_item_model != False - - # Construct a model instance of CollectionItem by calling from_dict on the json representation - collection_item_model_dict = CollectionItem.from_dict(collection_item_model_json).__dict__ - collection_item_model2 = CollectionItem(**collection_item_model_dict) - - # Verify the model instances are equivalent - assert collection_item_model == collection_item_model2 - - # Convert model instance back to dict and verify no loss of data - collection_item_model_json2 = collection_item_model.to_dict() - assert collection_item_model_json2 == collection_item_model_json - - -# endregion -############################################################################## -# End of Model Tests -############################################################################## diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index d5bb4e7dc..b00e2f23a 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2021. +# (C) Copyright IBM Corp. 2019, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -36,11 +36,38 @@ _service = NaturalLanguageUnderstandingV1( authenticator=NoAuthAuthenticator(), version=version - ) +) _base_url = 'https://api.us-south.natural-language-understanding.watson.cloud.ibm.com' _service.set_service_url(_base_url) + +def preprocess_url(operation_path: str): + """ + Returns the request url associated with the specified operation path. + This will be base_url concatenated with a quoted version of operation_path. + The returned request URL is used to register the mock response so it needs + to match the request URL that is formed by the requests library. + """ + # First, unquote the path since it might have some quoted/escaped characters in it + # due to how the generator inserts the operation paths into the unit test code. + operation_path = urllib.parse.unquote(operation_path) + + # Next, quote the path using urllib so that we approximate what will + # happen during request processing. + operation_path = urllib.parse.quote(operation_path, safe='/') + + # Finally, form the request URL from the base URL and operation path. + request_url = _base_url + operation_path + + # If the request url does NOT end with a /, then just return it as-is. + # Otherwise, return a regular expression that matches one or more trailing /. + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + ############################################################################## # Start of Service: Analyze ############################################################################## @@ -51,24 +78,13 @@ class TestAnalyze(): Test Class for analyze """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_analyze_all_params(self): """ analyze() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/analyze') + url = preprocess_url('/v1/analyze') mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "classifications": [{"class_name": "class_name", "confidence": 10}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' responses.add(responses.POST, url, @@ -103,9 +119,6 @@ def test_analyze_all_params(self): keywords_options_model['sentiment'] = False keywords_options_model['emotion'] = False - # Construct a dict representation of a MetadataOptions model - metadata_options_model = {} - # Construct a dict representation of a RelationsOptions model relations_options_model = {} relations_options_model['model'] = 'testString' @@ -149,7 +162,7 @@ def test_analyze_all_params(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = metadata_options_model + features_model['metadata'] = {} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -200,6 +213,14 @@ def test_analyze_all_params(self): assert req_body['language'] == 'testString' assert req_body['limit_text_characters'] == 38 + def test_analyze_all_params_with_retries(self): + # Enable retries and run test_analyze_all_params. + _service.enable_retries() + self.test_analyze_all_params() + + # Disable retries and run test_analyze_all_params. + _service.disable_retries() + self.test_analyze_all_params() @responses.activate def test_analyze_value_error(self): @@ -207,7 +228,7 @@ def test_analyze_value_error(self): test_analyze_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/analyze') + url = preprocess_url('/v1/analyze') mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "classifications": [{"class_name": "class_name", "confidence": 10}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' responses.add(responses.POST, url, @@ -242,9 +263,6 @@ def test_analyze_value_error(self): keywords_options_model['sentiment'] = False keywords_options_model['emotion'] = False - # Construct a dict representation of a MetadataOptions model - metadata_options_model = {} - # Construct a dict representation of a RelationsOptions model relations_options_model = {} relations_options_model['model'] = 'testString' @@ -288,7 +306,7 @@ def test_analyze_value_error(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = metadata_options_model + features_model['metadata'] = {} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -318,6 +336,14 @@ def test_analyze_value_error(self): _service.analyze(**req_copy) + def test_analyze_value_error_with_retries(self): + # Enable retries and run test_analyze_value_error. + _service.enable_retries() + self.test_analyze_value_error() + + # Disable retries and run test_analyze_value_error. + _service.disable_retries() + self.test_analyze_value_error() # endregion ############################################################################## @@ -334,24 +360,13 @@ class TestListModels(): Test Class for list_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_models_all_params(self): """ list_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models') + url = preprocess_url('/v1/models') mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -367,6 +382,14 @@ def test_list_models_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_models_all_params_with_retries(self): + # Enable retries and run test_list_models_all_params. + _service.enable_retries() + self.test_list_models_all_params() + + # Disable retries and run test_list_models_all_params. + _service.disable_retries() + self.test_list_models_all_params() @responses.activate def test_list_models_value_error(self): @@ -374,7 +397,7 @@ def test_list_models_value_error(self): test_list_models_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models') + url = preprocess_url('/v1/models') mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -391,30 +414,27 @@ def test_list_models_value_error(self): _service.list_models(**req_copy) + def test_list_models_value_error_with_retries(self): + # Enable retries and run test_list_models_value_error. + _service.enable_retries() + self.test_list_models_value_error() + + # Disable retries and run test_list_models_value_error. + _service.disable_retries() + self.test_list_models_value_error() class TestDeleteModel(): """ Test Class for delete_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_model_all_params(self): """ delete_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/testString') + url = preprocess_url('/v1/models/testString') mock_response = '{"deleted": "deleted"}' responses.add(responses.DELETE, url, @@ -435,6 +455,14 @@ def test_delete_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_model_all_params_with_retries(self): + # Enable retries and run test_delete_model_all_params. + _service.enable_retries() + self.test_delete_model_all_params() + + # Disable retries and run test_delete_model_all_params. + _service.disable_retries() + self.test_delete_model_all_params() @responses.activate def test_delete_model_value_error(self): @@ -442,7 +470,7 @@ def test_delete_model_value_error(self): test_delete_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/testString') + url = preprocess_url('/v1/models/testString') mock_response = '{"deleted": "deleted"}' responses.add(responses.DELETE, url, @@ -463,6 +491,14 @@ def test_delete_model_value_error(self): _service.delete_model(**req_copy) + def test_delete_model_value_error_with_retries(self): + # Enable retries and run test_delete_model_value_error. + _service.enable_retries() + self.test_delete_model_value_error() + + # Disable retries and run test_delete_model_value_error. + _service.disable_retries() + self.test_delete_model_value_error() # endregion ############################################################################## @@ -479,24 +515,13 @@ class TestCreateSentimentModel(): Test Class for create_sentiment_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_sentiment_model_all_params(self): """ create_sentiment_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment') + url = preprocess_url('/v1/models/sentiment') mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.POST, url, @@ -529,6 +554,14 @@ def test_create_sentiment_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_sentiment_model_all_params_with_retries(self): + # Enable retries and run test_create_sentiment_model_all_params. + _service.enable_retries() + self.test_create_sentiment_model_all_params() + + # Disable retries and run test_create_sentiment_model_all_params. + _service.disable_retries() + self.test_create_sentiment_model_all_params() @responses.activate def test_create_sentiment_model_required_params(self): @@ -536,7 +569,7 @@ def test_create_sentiment_model_required_params(self): test_create_sentiment_model_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment') + url = preprocess_url('/v1/models/sentiment') mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.POST, url, @@ -559,6 +592,14 @@ def test_create_sentiment_model_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_sentiment_model_required_params_with_retries(self): + # Enable retries and run test_create_sentiment_model_required_params. + _service.enable_retries() + self.test_create_sentiment_model_required_params() + + # Disable retries and run test_create_sentiment_model_required_params. + _service.disable_retries() + self.test_create_sentiment_model_required_params() @responses.activate def test_create_sentiment_model_value_error(self): @@ -566,7 +607,7 @@ def test_create_sentiment_model_value_error(self): test_create_sentiment_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment') + url = preprocess_url('/v1/models/sentiment') mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.POST, url, @@ -589,30 +630,27 @@ def test_create_sentiment_model_value_error(self): _service.create_sentiment_model(**req_copy) + def test_create_sentiment_model_value_error_with_retries(self): + # Enable retries and run test_create_sentiment_model_value_error. + _service.enable_retries() + self.test_create_sentiment_model_value_error() + + # Disable retries and run test_create_sentiment_model_value_error. + _service.disable_retries() + self.test_create_sentiment_model_value_error() class TestListSentimentModels(): """ Test Class for list_sentiment_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_sentiment_models_all_params(self): """ list_sentiment_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment') + url = preprocess_url('/v1/models/sentiment') mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' responses.add(responses.GET, url, @@ -628,6 +666,14 @@ def test_list_sentiment_models_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_sentiment_models_all_params_with_retries(self): + # Enable retries and run test_list_sentiment_models_all_params. + _service.enable_retries() + self.test_list_sentiment_models_all_params() + + # Disable retries and run test_list_sentiment_models_all_params. + _service.disable_retries() + self.test_list_sentiment_models_all_params() @responses.activate def test_list_sentiment_models_value_error(self): @@ -635,7 +681,7 @@ def test_list_sentiment_models_value_error(self): test_list_sentiment_models_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment') + url = preprocess_url('/v1/models/sentiment') mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' responses.add(responses.GET, url, @@ -652,30 +698,27 @@ def test_list_sentiment_models_value_error(self): _service.list_sentiment_models(**req_copy) + def test_list_sentiment_models_value_error_with_retries(self): + # Enable retries and run test_list_sentiment_models_value_error. + _service.enable_retries() + self.test_list_sentiment_models_value_error() + + # Disable retries and run test_list_sentiment_models_value_error. + _service.disable_retries() + self.test_list_sentiment_models_value_error() class TestGetSentimentModel(): """ Test Class for get_sentiment_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_sentiment_model_all_params(self): """ get_sentiment_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + url = preprocess_url('/v1/models/sentiment/testString') mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.GET, url, @@ -696,6 +739,14 @@ def test_get_sentiment_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_sentiment_model_all_params_with_retries(self): + # Enable retries and run test_get_sentiment_model_all_params. + _service.enable_retries() + self.test_get_sentiment_model_all_params() + + # Disable retries and run test_get_sentiment_model_all_params. + _service.disable_retries() + self.test_get_sentiment_model_all_params() @responses.activate def test_get_sentiment_model_value_error(self): @@ -703,7 +754,7 @@ def test_get_sentiment_model_value_error(self): test_get_sentiment_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + url = preprocess_url('/v1/models/sentiment/testString') mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.GET, url, @@ -724,30 +775,27 @@ def test_get_sentiment_model_value_error(self): _service.get_sentiment_model(**req_copy) + def test_get_sentiment_model_value_error_with_retries(self): + # Enable retries and run test_get_sentiment_model_value_error. + _service.enable_retries() + self.test_get_sentiment_model_value_error() + + # Disable retries and run test_get_sentiment_model_value_error. + _service.disable_retries() + self.test_get_sentiment_model_value_error() class TestUpdateSentimentModel(): """ Test Class for update_sentiment_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_sentiment_model_all_params(self): """ update_sentiment_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + url = preprocess_url('/v1/models/sentiment/testString') mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.PUT, url, @@ -782,6 +830,14 @@ def test_update_sentiment_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_update_sentiment_model_all_params_with_retries(self): + # Enable retries and run test_update_sentiment_model_all_params. + _service.enable_retries() + self.test_update_sentiment_model_all_params() + + # Disable retries and run test_update_sentiment_model_all_params. + _service.disable_retries() + self.test_update_sentiment_model_all_params() @responses.activate def test_update_sentiment_model_required_params(self): @@ -789,7 +845,7 @@ def test_update_sentiment_model_required_params(self): test_update_sentiment_model_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + url = preprocess_url('/v1/models/sentiment/testString') mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.PUT, url, @@ -814,6 +870,14 @@ def test_update_sentiment_model_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_update_sentiment_model_required_params_with_retries(self): + # Enable retries and run test_update_sentiment_model_required_params. + _service.enable_retries() + self.test_update_sentiment_model_required_params() + + # Disable retries and run test_update_sentiment_model_required_params. + _service.disable_retries() + self.test_update_sentiment_model_required_params() @responses.activate def test_update_sentiment_model_value_error(self): @@ -821,7 +885,7 @@ def test_update_sentiment_model_value_error(self): test_update_sentiment_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + url = preprocess_url('/v1/models/sentiment/testString') mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.PUT, url, @@ -846,30 +910,27 @@ def test_update_sentiment_model_value_error(self): _service.update_sentiment_model(**req_copy) + def test_update_sentiment_model_value_error_with_retries(self): + # Enable retries and run test_update_sentiment_model_value_error. + _service.enable_retries() + self.test_update_sentiment_model_value_error() + + # Disable retries and run test_update_sentiment_model_value_error. + _service.disable_retries() + self.test_update_sentiment_model_value_error() class TestDeleteSentimentModel(): """ Test Class for delete_sentiment_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_sentiment_model_all_params(self): """ delete_sentiment_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + url = preprocess_url('/v1/models/sentiment/testString') mock_response = '{"deleted": "deleted"}' responses.add(responses.DELETE, url, @@ -890,6 +951,14 @@ def test_delete_sentiment_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_sentiment_model_all_params_with_retries(self): + # Enable retries and run test_delete_sentiment_model_all_params. + _service.enable_retries() + self.test_delete_sentiment_model_all_params() + + # Disable retries and run test_delete_sentiment_model_all_params. + _service.disable_retries() + self.test_delete_sentiment_model_all_params() @responses.activate def test_delete_sentiment_model_value_error(self): @@ -897,7 +966,7 @@ def test_delete_sentiment_model_value_error(self): test_delete_sentiment_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/sentiment/testString') + url = preprocess_url('/v1/models/sentiment/testString') mock_response = '{"deleted": "deleted"}' responses.add(responses.DELETE, url, @@ -918,6 +987,14 @@ def test_delete_sentiment_model_value_error(self): _service.delete_sentiment_model(**req_copy) + def test_delete_sentiment_model_value_error_with_retries(self): + # Enable retries and run test_delete_sentiment_model_value_error. + _service.enable_retries() + self.test_delete_sentiment_model_value_error() + + # Disable retries and run test_delete_sentiment_model_value_error. + _service.disable_retries() + self.test_delete_sentiment_model_value_error() # endregion ############################################################################## @@ -934,24 +1011,13 @@ class TestCreateCategoriesModel(): Test Class for create_categories_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_categories_model_all_params(self): """ create_categories_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories') + url = preprocess_url('/v1/models/categories') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -986,6 +1052,14 @@ def test_create_categories_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_categories_model_all_params_with_retries(self): + # Enable retries and run test_create_categories_model_all_params. + _service.enable_retries() + self.test_create_categories_model_all_params() + + # Disable retries and run test_create_categories_model_all_params. + _service.disable_retries() + self.test_create_categories_model_all_params() @responses.activate def test_create_categories_model_required_params(self): @@ -993,7 +1067,7 @@ def test_create_categories_model_required_params(self): test_create_categories_model_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories') + url = preprocess_url('/v1/models/categories') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -1016,6 +1090,14 @@ def test_create_categories_model_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_categories_model_required_params_with_retries(self): + # Enable retries and run test_create_categories_model_required_params. + _service.enable_retries() + self.test_create_categories_model_required_params() + + # Disable retries and run test_create_categories_model_required_params. + _service.disable_retries() + self.test_create_categories_model_required_params() @responses.activate def test_create_categories_model_value_error(self): @@ -1023,7 +1105,7 @@ def test_create_categories_model_value_error(self): test_create_categories_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories') + url = preprocess_url('/v1/models/categories') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -1046,30 +1128,27 @@ def test_create_categories_model_value_error(self): _service.create_categories_model(**req_copy) + def test_create_categories_model_value_error_with_retries(self): + # Enable retries and run test_create_categories_model_value_error. + _service.enable_retries() + self.test_create_categories_model_value_error() + + # Disable retries and run test_create_categories_model_value_error. + _service.disable_retries() + self.test_create_categories_model_value_error() class TestListCategoriesModels(): """ Test Class for list_categories_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_categories_models_all_params(self): """ list_categories_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories') + url = preprocess_url('/v1/models/categories') mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -1085,6 +1164,14 @@ def test_list_categories_models_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_categories_models_all_params_with_retries(self): + # Enable retries and run test_list_categories_models_all_params. + _service.enable_retries() + self.test_list_categories_models_all_params() + + # Disable retries and run test_list_categories_models_all_params. + _service.disable_retries() + self.test_list_categories_models_all_params() @responses.activate def test_list_categories_models_value_error(self): @@ -1092,7 +1179,7 @@ def test_list_categories_models_value_error(self): test_list_categories_models_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories') + url = preprocess_url('/v1/models/categories') mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -1109,30 +1196,27 @@ def test_list_categories_models_value_error(self): _service.list_categories_models(**req_copy) + def test_list_categories_models_value_error_with_retries(self): + # Enable retries and run test_list_categories_models_value_error. + _service.enable_retries() + self.test_list_categories_models_value_error() + + # Disable retries and run test_list_categories_models_value_error. + _service.disable_retries() + self.test_list_categories_models_value_error() class TestGetCategoriesModel(): """ Test Class for get_categories_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_categories_model_all_params(self): """ get_categories_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + url = preprocess_url('/v1/models/categories/testString') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -1153,6 +1237,14 @@ def test_get_categories_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_categories_model_all_params_with_retries(self): + # Enable retries and run test_get_categories_model_all_params. + _service.enable_retries() + self.test_get_categories_model_all_params() + + # Disable retries and run test_get_categories_model_all_params. + _service.disable_retries() + self.test_get_categories_model_all_params() @responses.activate def test_get_categories_model_value_error(self): @@ -1160,7 +1252,7 @@ def test_get_categories_model_value_error(self): test_get_categories_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + url = preprocess_url('/v1/models/categories/testString') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -1181,30 +1273,27 @@ def test_get_categories_model_value_error(self): _service.get_categories_model(**req_copy) + def test_get_categories_model_value_error_with_retries(self): + # Enable retries and run test_get_categories_model_value_error. + _service.enable_retries() + self.test_get_categories_model_value_error() + + # Disable retries and run test_get_categories_model_value_error. + _service.disable_retries() + self.test_get_categories_model_value_error() class TestUpdateCategoriesModel(): """ Test Class for update_categories_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_categories_model_all_params(self): """ update_categories_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + url = preprocess_url('/v1/models/categories/testString') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, @@ -1241,6 +1330,14 @@ def test_update_categories_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_update_categories_model_all_params_with_retries(self): + # Enable retries and run test_update_categories_model_all_params. + _service.enable_retries() + self.test_update_categories_model_all_params() + + # Disable retries and run test_update_categories_model_all_params. + _service.disable_retries() + self.test_update_categories_model_all_params() @responses.activate def test_update_categories_model_required_params(self): @@ -1248,7 +1345,7 @@ def test_update_categories_model_required_params(self): test_update_categories_model_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + url = preprocess_url('/v1/models/categories/testString') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, @@ -1273,6 +1370,14 @@ def test_update_categories_model_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_update_categories_model_required_params_with_retries(self): + # Enable retries and run test_update_categories_model_required_params. + _service.enable_retries() + self.test_update_categories_model_required_params() + + # Disable retries and run test_update_categories_model_required_params. + _service.disable_retries() + self.test_update_categories_model_required_params() @responses.activate def test_update_categories_model_value_error(self): @@ -1280,7 +1385,7 @@ def test_update_categories_model_value_error(self): test_update_categories_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + url = preprocess_url('/v1/models/categories/testString') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, @@ -1305,30 +1410,27 @@ def test_update_categories_model_value_error(self): _service.update_categories_model(**req_copy) + def test_update_categories_model_value_error_with_retries(self): + # Enable retries and run test_update_categories_model_value_error. + _service.enable_retries() + self.test_update_categories_model_value_error() + + # Disable retries and run test_update_categories_model_value_error. + _service.disable_retries() + self.test_update_categories_model_value_error() class TestDeleteCategoriesModel(): """ Test Class for delete_categories_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_categories_model_all_params(self): """ delete_categories_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + url = preprocess_url('/v1/models/categories/testString') mock_response = '{"deleted": "deleted"}' responses.add(responses.DELETE, url, @@ -1349,6 +1451,14 @@ def test_delete_categories_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_categories_model_all_params_with_retries(self): + # Enable retries and run test_delete_categories_model_all_params. + _service.enable_retries() + self.test_delete_categories_model_all_params() + + # Disable retries and run test_delete_categories_model_all_params. + _service.disable_retries() + self.test_delete_categories_model_all_params() @responses.activate def test_delete_categories_model_value_error(self): @@ -1356,7 +1466,7 @@ def test_delete_categories_model_value_error(self): test_delete_categories_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/categories/testString') + url = preprocess_url('/v1/models/categories/testString') mock_response = '{"deleted": "deleted"}' responses.add(responses.DELETE, url, @@ -1377,6 +1487,14 @@ def test_delete_categories_model_value_error(self): _service.delete_categories_model(**req_copy) + def test_delete_categories_model_value_error_with_retries(self): + # Enable retries and run test_delete_categories_model_value_error. + _service.enable_retries() + self.test_delete_categories_model_value_error() + + # Disable retries and run test_delete_categories_model_value_error. + _service.disable_retries() + self.test_delete_categories_model_value_error() # endregion ############################################################################## @@ -1393,24 +1511,13 @@ class TestCreateClassificationsModel(): Test Class for create_classifications_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_classifications_model_all_params(self): """ create_classifications_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications') + url = preprocess_url('/v1/models/classifications') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -1445,6 +1552,14 @@ def test_create_classifications_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_classifications_model_all_params_with_retries(self): + # Enable retries and run test_create_classifications_model_all_params. + _service.enable_retries() + self.test_create_classifications_model_all_params() + + # Disable retries and run test_create_classifications_model_all_params. + _service.disable_retries() + self.test_create_classifications_model_all_params() @responses.activate def test_create_classifications_model_required_params(self): @@ -1452,7 +1567,7 @@ def test_create_classifications_model_required_params(self): test_create_classifications_model_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications') + url = preprocess_url('/v1/models/classifications') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -1475,6 +1590,14 @@ def test_create_classifications_model_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_classifications_model_required_params_with_retries(self): + # Enable retries and run test_create_classifications_model_required_params. + _service.enable_retries() + self.test_create_classifications_model_required_params() + + # Disable retries and run test_create_classifications_model_required_params. + _service.disable_retries() + self.test_create_classifications_model_required_params() @responses.activate def test_create_classifications_model_value_error(self): @@ -1482,7 +1605,7 @@ def test_create_classifications_model_value_error(self): test_create_classifications_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications') + url = preprocess_url('/v1/models/classifications') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, @@ -1505,30 +1628,27 @@ def test_create_classifications_model_value_error(self): _service.create_classifications_model(**req_copy) + def test_create_classifications_model_value_error_with_retries(self): + # Enable retries and run test_create_classifications_model_value_error. + _service.enable_retries() + self.test_create_classifications_model_value_error() + + # Disable retries and run test_create_classifications_model_value_error. + _service.disable_retries() + self.test_create_classifications_model_value_error() class TestListClassificationsModels(): """ Test Class for list_classifications_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_classifications_models_all_params(self): """ list_classifications_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications') + url = preprocess_url('/v1/models/classifications') mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -1544,6 +1664,14 @@ def test_list_classifications_models_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_classifications_models_all_params_with_retries(self): + # Enable retries and run test_list_classifications_models_all_params. + _service.enable_retries() + self.test_list_classifications_models_all_params() + + # Disable retries and run test_list_classifications_models_all_params. + _service.disable_retries() + self.test_list_classifications_models_all_params() @responses.activate def test_list_classifications_models_value_error(self): @@ -1551,7 +1679,7 @@ def test_list_classifications_models_value_error(self): test_list_classifications_models_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications') + url = preprocess_url('/v1/models/classifications') mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, @@ -1568,30 +1696,27 @@ def test_list_classifications_models_value_error(self): _service.list_classifications_models(**req_copy) + def test_list_classifications_models_value_error_with_retries(self): + # Enable retries and run test_list_classifications_models_value_error. + _service.enable_retries() + self.test_list_classifications_models_value_error() + + # Disable retries and run test_list_classifications_models_value_error. + _service.disable_retries() + self.test_list_classifications_models_value_error() class TestGetClassificationsModel(): """ Test Class for get_classifications_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_classifications_model_all_params(self): """ get_classifications_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + url = preprocess_url('/v1/models/classifications/testString') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -1612,6 +1737,14 @@ def test_get_classifications_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_classifications_model_all_params_with_retries(self): + # Enable retries and run test_get_classifications_model_all_params. + _service.enable_retries() + self.test_get_classifications_model_all_params() + + # Disable retries and run test_get_classifications_model_all_params. + _service.disable_retries() + self.test_get_classifications_model_all_params() @responses.activate def test_get_classifications_model_value_error(self): @@ -1619,7 +1752,7 @@ def test_get_classifications_model_value_error(self): test_get_classifications_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + url = preprocess_url('/v1/models/classifications/testString') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, @@ -1640,30 +1773,27 @@ def test_get_classifications_model_value_error(self): _service.get_classifications_model(**req_copy) + def test_get_classifications_model_value_error_with_retries(self): + # Enable retries and run test_get_classifications_model_value_error. + _service.enable_retries() + self.test_get_classifications_model_value_error() + + # Disable retries and run test_get_classifications_model_value_error. + _service.disable_retries() + self.test_get_classifications_model_value_error() class TestUpdateClassificationsModel(): """ Test Class for update_classifications_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_classifications_model_all_params(self): """ update_classifications_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + url = preprocess_url('/v1/models/classifications/testString') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, @@ -1700,6 +1830,14 @@ def test_update_classifications_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_update_classifications_model_all_params_with_retries(self): + # Enable retries and run test_update_classifications_model_all_params. + _service.enable_retries() + self.test_update_classifications_model_all_params() + + # Disable retries and run test_update_classifications_model_all_params. + _service.disable_retries() + self.test_update_classifications_model_all_params() @responses.activate def test_update_classifications_model_required_params(self): @@ -1707,7 +1845,7 @@ def test_update_classifications_model_required_params(self): test_update_classifications_model_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + url = preprocess_url('/v1/models/classifications/testString') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, @@ -1732,6 +1870,14 @@ def test_update_classifications_model_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_update_classifications_model_required_params_with_retries(self): + # Enable retries and run test_update_classifications_model_required_params. + _service.enable_retries() + self.test_update_classifications_model_required_params() + + # Disable retries and run test_update_classifications_model_required_params. + _service.disable_retries() + self.test_update_classifications_model_required_params() @responses.activate def test_update_classifications_model_value_error(self): @@ -1739,7 +1885,7 @@ def test_update_classifications_model_value_error(self): test_update_classifications_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + url = preprocess_url('/v1/models/classifications/testString') mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, @@ -1764,30 +1910,27 @@ def test_update_classifications_model_value_error(self): _service.update_classifications_model(**req_copy) + def test_update_classifications_model_value_error_with_retries(self): + # Enable retries and run test_update_classifications_model_value_error. + _service.enable_retries() + self.test_update_classifications_model_value_error() + + # Disable retries and run test_update_classifications_model_value_error. + _service.disable_retries() + self.test_update_classifications_model_value_error() class TestDeleteClassificationsModel(): """ Test Class for delete_classifications_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_classifications_model_all_params(self): """ delete_classifications_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + url = preprocess_url('/v1/models/classifications/testString') mock_response = '{"deleted": "deleted"}' responses.add(responses.DELETE, url, @@ -1808,6 +1951,14 @@ def test_delete_classifications_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_classifications_model_all_params_with_retries(self): + # Enable retries and run test_delete_classifications_model_all_params. + _service.enable_retries() + self.test_delete_classifications_model_all_params() + + # Disable retries and run test_delete_classifications_model_all_params. + _service.disable_retries() + self.test_delete_classifications_model_all_params() @responses.activate def test_delete_classifications_model_value_error(self): @@ -1815,7 +1966,7 @@ def test_delete_classifications_model_value_error(self): test_delete_classifications_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/classifications/testString') + url = preprocess_url('/v1/models/classifications/testString') mock_response = '{"deleted": "deleted"}' responses.add(responses.DELETE, url, @@ -1836,6 +1987,14 @@ def test_delete_classifications_model_value_error(self): _service.delete_classifications_model(**req_copy) + def test_delete_classifications_model_value_error_with_retries(self): + # Enable retries and run test_delete_classifications_model_value_error. + _service.enable_retries() + self.test_delete_classifications_model_value_error() + + # Disable retries and run test_delete_classifications_model_value_error. + _service.disable_retries() + self.test_delete_classifications_model_value_error() # endregion ############################################################################## @@ -2138,10 +2297,10 @@ def test_categories_model_serialization(self): categories_model_model_json['features'] = ['testString'] categories_model_model_json['status'] = 'starting' categories_model_model_json['model_id'] = 'testString' - categories_model_model_json['created'] = "2019-01-01T12:00:00Z" + categories_model_model_json['created'] = '2019-01-01T12:00:00Z' categories_model_model_json['notices'] = [notice_model] - categories_model_model_json['last_trained'] = "2019-01-01T12:00:00Z" - categories_model_model_json['last_deployed'] = "2019-01-01T12:00:00Z" + categories_model_model_json['last_trained'] = '2019-01-01T12:00:00Z' + categories_model_model_json['last_deployed'] = '2019-01-01T12:00:00Z' # Construct a model instance of CategoriesModel by calling from_dict on the json representation categories_model_model = CategoriesModel.from_dict(categories_model_model_json) @@ -2184,10 +2343,10 @@ def test_categories_model_list_serialization(self): categories_model_model['features'] = ['testString'] categories_model_model['status'] = 'starting' categories_model_model['model_id'] = 'testString' - categories_model_model['created'] = "2019-01-01T12:00:00Z" + categories_model_model['created'] = '2019-01-01T12:00:00Z' categories_model_model['notices'] = [notice_model] - categories_model_model['last_trained'] = "2019-01-01T12:00:00Z" - categories_model_model['last_deployed'] = "2019-01-01T12:00:00Z" + categories_model_model['last_trained'] = '2019-01-01T12:00:00Z' + categories_model_model['last_deployed'] = '2019-01-01T12:00:00Z' # Construct a json representation of a CategoriesModelList model categories_model_list_model_json = {} @@ -2368,10 +2527,10 @@ def test_classifications_model_serialization(self): classifications_model_model_json['features'] = ['testString'] classifications_model_model_json['status'] = 'starting' classifications_model_model_json['model_id'] = 'testString' - classifications_model_model_json['created'] = "2019-01-01T12:00:00Z" + classifications_model_model_json['created'] = '2019-01-01T12:00:00Z' classifications_model_model_json['notices'] = [notice_model] - classifications_model_model_json['last_trained'] = "2019-01-01T12:00:00Z" - classifications_model_model_json['last_deployed'] = "2019-01-01T12:00:00Z" + classifications_model_model_json['last_trained'] = '2019-01-01T12:00:00Z' + classifications_model_model_json['last_deployed'] = '2019-01-01T12:00:00Z' # Construct a model instance of ClassificationsModel by calling from_dict on the json representation classifications_model_model = ClassificationsModel.from_dict(classifications_model_model_json) @@ -2414,10 +2573,10 @@ def test_classifications_model_list_serialization(self): classifications_model_model['features'] = ['testString'] classifications_model_model['status'] = 'starting' classifications_model_model['model_id'] = 'testString' - classifications_model_model['created'] = "2019-01-01T12:00:00Z" + classifications_model_model['created'] = '2019-01-01T12:00:00Z' classifications_model_model['notices'] = [notice_model] - classifications_model_model['last_trained'] = "2019-01-01T12:00:00Z" - classifications_model_model['last_deployed'] = "2019-01-01T12:00:00Z" + classifications_model_model['last_trained'] = '2019-01-01T12:00:00Z' + classifications_model_model['last_deployed'] = '2019-01-01T12:00:00Z' # Construct a json representation of a ClassificationsModelList model classifications_model_list_model_json = {} @@ -2980,8 +3139,6 @@ def test_features_serialization(self): keywords_options_model['sentiment'] = False keywords_options_model['emotion'] = False - metadata_options_model = {} # MetadataOptions - relations_options_model = {} # RelationsOptions relations_options_model['model'] = 'testString' @@ -3018,7 +3175,7 @@ def test_features_serialization(self): features_model_json['emotion'] = emotion_options_model features_model_json['entities'] = entities_options_model features_model_json['keywords'] = keywords_options_model - features_model_json['metadata'] = metadata_options_model + features_model_json['metadata'] = {} features_model_json['relations'] = relations_options_model features_model_json['semantic_roles'] = semantic_roles_options_model features_model_json['sentiment'] = sentiment_options_model @@ -3208,7 +3365,7 @@ def test_list_models_results_serialization(self): model_model['model_version'] = 'testString' model_model['version'] = 'testString' model_model['version_description'] = 'testString' - model_model['created'] = "2019-01-01T12:00:00Z" + model_model['created'] = '2019-01-01T12:00:00Z' # Construct a json representation of a ListModelsResults model list_models_results_model_json = {} @@ -3248,9 +3405,9 @@ def test_list_sentiment_models_response_serialization(self): sentiment_model_model['features'] = ['testString'] sentiment_model_model['status'] = 'starting' sentiment_model_model['model_id'] = 'testString' - sentiment_model_model['created'] = "2019-01-01T12:00:00Z" - sentiment_model_model['last_trained'] = "2019-01-01T12:00:00Z" - sentiment_model_model['last_deployed'] = "2019-01-01T12:00:00Z" + sentiment_model_model['created'] = '2019-01-01T12:00:00Z' + sentiment_model_model['last_trained'] = '2019-01-01T12:00:00Z' + sentiment_model_model['last_deployed'] = '2019-01-01T12:00:00Z' sentiment_model_model['name'] = 'testString' sentiment_model_model['user_metadata'] = {} sentiment_model_model['language'] = 'testString' @@ -3279,34 +3436,6 @@ def test_list_sentiment_models_response_serialization(self): list_sentiment_models_response_model_json2 = list_sentiment_models_response_model.to_dict() assert list_sentiment_models_response_model_json2 == list_sentiment_models_response_model_json -class TestModel_MetadataOptions(): - """ - Test Class for MetadataOptions - """ - - def test_metadata_options_serialization(self): - """ - Test serialization/deserialization for MetadataOptions - """ - - # Construct a json representation of a MetadataOptions model - metadata_options_model_json = {} - - # Construct a model instance of MetadataOptions by calling from_dict on the json representation - metadata_options_model = MetadataOptions.from_dict(metadata_options_model_json) - assert metadata_options_model != False - - # Construct a model instance of MetadataOptions by calling from_dict on the json representation - metadata_options_model_dict = MetadataOptions.from_dict(metadata_options_model_json).__dict__ - metadata_options_model2 = MetadataOptions(**metadata_options_model_dict) - - # Verify the model instances are equivalent - assert metadata_options_model == metadata_options_model2 - - # Convert model instance back to dict and verify no loss of data - metadata_options_model_json2 = metadata_options_model.to_dict() - assert metadata_options_model_json2 == metadata_options_model_json - class TestModel_Model(): """ Test Class for Model @@ -3327,7 +3456,7 @@ def test_model_serialization(self): model_model_json['model_version'] = 'testString' model_model_json['version'] = 'testString' model_model_json['version_description'] = 'testString' - model_model_json['created'] = "2019-01-01T12:00:00Z" + model_model_json['created'] = '2019-01-01T12:00:00Z' # Construct a model instance of Model by calling from_dict on the json representation model_model = Model.from_dict(model_model_json) @@ -3853,9 +3982,9 @@ def test_sentiment_model_serialization(self): sentiment_model_model_json['features'] = ['testString'] sentiment_model_model_json['status'] = 'starting' sentiment_model_model_json['model_id'] = 'testString' - sentiment_model_model_json['created'] = "2019-01-01T12:00:00Z" - sentiment_model_model_json['last_trained'] = "2019-01-01T12:00:00Z" - sentiment_model_model_json['last_deployed'] = "2019-01-01T12:00:00Z" + sentiment_model_model_json['created'] = '2019-01-01T12:00:00Z' + sentiment_model_model_json['last_trained'] = '2019-01-01T12:00:00Z' + sentiment_model_model_json['last_deployed'] = '2019-01-01T12:00:00Z' sentiment_model_model_json['name'] = 'testString' sentiment_model_model_json['user_metadata'] = {} sentiment_model_model_json['language'] = 'testString' diff --git a/test/unit/test_personality_insights_v3.py b/test/unit/test_personality_insights_v3.py deleted file mode 100755 index 787ea51e0..000000000 --- a/test/unit/test_personality_insights_v3.py +++ /dev/null @@ -1,544 +0,0 @@ -# -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2021. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Unit Tests for PersonalityInsightsV3 -""" - -from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator -import inspect -import json -import pytest -import re -import requests -import responses -import urllib -from ibm_watson.personality_insights_v3 import * - -version = 'testString' - -_service = PersonalityInsightsV3( - authenticator=NoAuthAuthenticator(), - version=version - ) - -_base_url = 'https://api.us-south.personality-insights.watson.cloud.ibm.com' -_service.set_service_url(_base_url) - -############################################################################## -# Start of Service: Methods -############################################################################## -# region - -class TestProfile(): - """ - Test Class for profile - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_profile_all_params(self): - """ - profile() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/profile') - mock_response = '{"processed_language": "ar", "word_count": 10, "word_count_message": "word_count_message", "personality": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "needs": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "values": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "behavior": [{"trait_id": "trait_id", "name": "name", "category": "category", "percentage": 10}], "consumption_preferences": [{"consumption_preference_category_id": "consumption_preference_category_id", "name": "name", "consumption_preferences": [{"consumption_preference_id": "consumption_preference_id", "name": "name", "score": 0.0}]}], "warnings": [{"warning_id": "WORD_COUNT_MESSAGE", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ContentItem model - content_item_model = {} - content_item_model['content'] = 'testString' - content_item_model['id'] = 'testString' - content_item_model['created'] = 26 - content_item_model['updated'] = 26 - content_item_model['contenttype'] = 'text/plain' - content_item_model['language'] = 'en' - content_item_model['parentid'] = 'testString' - content_item_model['reply'] = False - content_item_model['forward'] = False - - # Construct a dict representation of a Content model - content_model = {} - content_model['contentItems'] = [content_item_model] - - # Set up parameter values - content = content_model - accept = 'application/json' - content_type = 'text/plain' - content_language = 'en' - accept_language = 'en' - raw_scores = False - csv_headers = False - consumption_preferences = False - - # Invoke method - response = _service.profile( - content, - accept, - content_type=content_type, - content_language=content_language, - accept_language=accept_language, - raw_scores=raw_scores, - csv_headers=csv_headers, - consumption_preferences=consumption_preferences, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'raw_scores={}'.format('true' if raw_scores else 'false') in query_string - assert 'csv_headers={}'.format('true' if csv_headers else 'false') in query_string - assert 'consumption_preferences={}'.format('true' if consumption_preferences else 'false') in query_string - # Validate body params - - - @responses.activate - def test_profile_required_params(self): - """ - test_profile_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/profile') - mock_response = '{"processed_language": "ar", "word_count": 10, "word_count_message": "word_count_message", "personality": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "needs": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "values": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "behavior": [{"trait_id": "trait_id", "name": "name", "category": "category", "percentage": 10}], "consumption_preferences": [{"consumption_preference_category_id": "consumption_preference_category_id", "name": "name", "consumption_preferences": [{"consumption_preference_id": "consumption_preference_id", "name": "name", "score": 0.0}]}], "warnings": [{"warning_id": "WORD_COUNT_MESSAGE", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ContentItem model - content_item_model = {} - content_item_model['content'] = 'testString' - content_item_model['id'] = 'testString' - content_item_model['created'] = 26 - content_item_model['updated'] = 26 - content_item_model['contenttype'] = 'text/plain' - content_item_model['language'] = 'en' - content_item_model['parentid'] = 'testString' - content_item_model['reply'] = False - content_item_model['forward'] = False - - # Construct a dict representation of a Content model - content_model = {} - content_model['contentItems'] = [content_item_model] - - # Set up parameter values - content = content_model - accept = 'application/json' - - # Invoke method - response = _service.profile( - content, - accept, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - - - @responses.activate - def test_profile_value_error(self): - """ - test_profile_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/profile') - mock_response = '{"processed_language": "ar", "word_count": 10, "word_count_message": "word_count_message", "personality": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "needs": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "values": [{"trait_id": "trait_id", "name": "name", "category": "personality", "percentile": 10, "raw_score": 9, "significant": false}], "behavior": [{"trait_id": "trait_id", "name": "name", "category": "category", "percentage": 10}], "consumption_preferences": [{"consumption_preference_category_id": "consumption_preference_category_id", "name": "name", "consumption_preferences": [{"consumption_preference_id": "consumption_preference_id", "name": "name", "score": 0.0}]}], "warnings": [{"warning_id": "WORD_COUNT_MESSAGE", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ContentItem model - content_item_model = {} - content_item_model['content'] = 'testString' - content_item_model['id'] = 'testString' - content_item_model['created'] = 26 - content_item_model['updated'] = 26 - content_item_model['contenttype'] = 'text/plain' - content_item_model['language'] = 'en' - content_item_model['parentid'] = 'testString' - content_item_model['reply'] = False - content_item_model['forward'] = False - - # Construct a dict representation of a Content model - content_model = {} - content_model['contentItems'] = [content_item_model] - - # Set up parameter values - content = content_model - accept = 'application/json' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "content": content, - "accept": accept, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.profile(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Methods -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region -class TestModel_Behavior(): - """ - Test Class for Behavior - """ - - def test_behavior_serialization(self): - """ - Test serialization/deserialization for Behavior - """ - - # Construct a json representation of a Behavior model - behavior_model_json = {} - behavior_model_json['trait_id'] = 'testString' - behavior_model_json['name'] = 'testString' - behavior_model_json['category'] = 'testString' - behavior_model_json['percentage'] = 72.5 - - # Construct a model instance of Behavior by calling from_dict on the json representation - behavior_model = Behavior.from_dict(behavior_model_json) - assert behavior_model != False - - # Construct a model instance of Behavior by calling from_dict on the json representation - behavior_model_dict = Behavior.from_dict(behavior_model_json).__dict__ - behavior_model2 = Behavior(**behavior_model_dict) - - # Verify the model instances are equivalent - assert behavior_model == behavior_model2 - - # Convert model instance back to dict and verify no loss of data - behavior_model_json2 = behavior_model.to_dict() - assert behavior_model_json2 == behavior_model_json - -class TestModel_ConsumptionPreferences(): - """ - Test Class for ConsumptionPreferences - """ - - def test_consumption_preferences_serialization(self): - """ - Test serialization/deserialization for ConsumptionPreferences - """ - - # Construct a json representation of a ConsumptionPreferences model - consumption_preferences_model_json = {} - consumption_preferences_model_json['consumption_preference_id'] = 'testString' - consumption_preferences_model_json['name'] = 'testString' - consumption_preferences_model_json['score'] = 0.0 - - # Construct a model instance of ConsumptionPreferences by calling from_dict on the json representation - consumption_preferences_model = ConsumptionPreferences.from_dict(consumption_preferences_model_json) - assert consumption_preferences_model != False - - # Construct a model instance of ConsumptionPreferences by calling from_dict on the json representation - consumption_preferences_model_dict = ConsumptionPreferences.from_dict(consumption_preferences_model_json).__dict__ - consumption_preferences_model2 = ConsumptionPreferences(**consumption_preferences_model_dict) - - # Verify the model instances are equivalent - assert consumption_preferences_model == consumption_preferences_model2 - - # Convert model instance back to dict and verify no loss of data - consumption_preferences_model_json2 = consumption_preferences_model.to_dict() - assert consumption_preferences_model_json2 == consumption_preferences_model_json - -class TestModel_ConsumptionPreferencesCategory(): - """ - Test Class for ConsumptionPreferencesCategory - """ - - def test_consumption_preferences_category_serialization(self): - """ - Test serialization/deserialization for ConsumptionPreferencesCategory - """ - - # Construct dict forms of any model objects needed in order to build this model. - - consumption_preferences_model = {} # ConsumptionPreferences - consumption_preferences_model['consumption_preference_id'] = 'testString' - consumption_preferences_model['name'] = 'testString' - consumption_preferences_model['score'] = 0.0 - - # Construct a json representation of a ConsumptionPreferencesCategory model - consumption_preferences_category_model_json = {} - consumption_preferences_category_model_json['consumption_preference_category_id'] = 'testString' - consumption_preferences_category_model_json['name'] = 'testString' - consumption_preferences_category_model_json['consumption_preferences'] = [consumption_preferences_model] - - # Construct a model instance of ConsumptionPreferencesCategory by calling from_dict on the json representation - consumption_preferences_category_model = ConsumptionPreferencesCategory.from_dict(consumption_preferences_category_model_json) - assert consumption_preferences_category_model != False - - # Construct a model instance of ConsumptionPreferencesCategory by calling from_dict on the json representation - consumption_preferences_category_model_dict = ConsumptionPreferencesCategory.from_dict(consumption_preferences_category_model_json).__dict__ - consumption_preferences_category_model2 = ConsumptionPreferencesCategory(**consumption_preferences_category_model_dict) - - # Verify the model instances are equivalent - assert consumption_preferences_category_model == consumption_preferences_category_model2 - - # Convert model instance back to dict and verify no loss of data - consumption_preferences_category_model_json2 = consumption_preferences_category_model.to_dict() - assert consumption_preferences_category_model_json2 == consumption_preferences_category_model_json - -class TestModel_Content(): - """ - Test Class for Content - """ - - def test_content_serialization(self): - """ - Test serialization/deserialization for Content - """ - - # Construct dict forms of any model objects needed in order to build this model. - - content_item_model = {} # ContentItem - content_item_model['content'] = 'testString' - content_item_model['id'] = 'testString' - content_item_model['created'] = 26 - content_item_model['updated'] = 26 - content_item_model['contenttype'] = 'text/plain' - content_item_model['language'] = 'en' - content_item_model['parentid'] = 'testString' - content_item_model['reply'] = False - content_item_model['forward'] = False - - # Construct a json representation of a Content model - content_model_json = {} - content_model_json['contentItems'] = [content_item_model] - - # Construct a model instance of Content by calling from_dict on the json representation - content_model = Content.from_dict(content_model_json) - assert content_model != False - - # Construct a model instance of Content by calling from_dict on the json representation - content_model_dict = Content.from_dict(content_model_json).__dict__ - content_model2 = Content(**content_model_dict) - - # Verify the model instances are equivalent - assert content_model == content_model2 - - # Convert model instance back to dict and verify no loss of data - content_model_json2 = content_model.to_dict() - assert content_model_json2 == content_model_json - -class TestModel_ContentItem(): - """ - Test Class for ContentItem - """ - - def test_content_item_serialization(self): - """ - Test serialization/deserialization for ContentItem - """ - - # Construct a json representation of a ContentItem model - content_item_model_json = {} - content_item_model_json['content'] = 'testString' - content_item_model_json['id'] = 'testString' - content_item_model_json['created'] = 26 - content_item_model_json['updated'] = 26 - content_item_model_json['contenttype'] = 'text/plain' - content_item_model_json['language'] = 'en' - content_item_model_json['parentid'] = 'testString' - content_item_model_json['reply'] = False - content_item_model_json['forward'] = False - - # Construct a model instance of ContentItem by calling from_dict on the json representation - content_item_model = ContentItem.from_dict(content_item_model_json) - assert content_item_model != False - - # Construct a model instance of ContentItem by calling from_dict on the json representation - content_item_model_dict = ContentItem.from_dict(content_item_model_json).__dict__ - content_item_model2 = ContentItem(**content_item_model_dict) - - # Verify the model instances are equivalent - assert content_item_model == content_item_model2 - - # Convert model instance back to dict and verify no loss of data - content_item_model_json2 = content_item_model.to_dict() - assert content_item_model_json2 == content_item_model_json - -class TestModel_Profile(): - """ - Test Class for Profile - """ - - def test_profile_serialization(self): - """ - Test serialization/deserialization for Profile - """ - - # Construct dict forms of any model objects needed in order to build this model. - - trait_model = {} # Trait - trait_model['trait_id'] = 'big5_openness' - trait_model['name'] = 'Openness' - trait_model['category'] = 'personality' - trait_model['percentile'] = 0.8011555009553 - trait_model['raw_score'] = 0.77565404255038 - trait_model['significant'] = True - - behavior_model = {} # Behavior - behavior_model['trait_id'] = 'behavior_sunday' - behavior_model['name'] = 'Sunday' - behavior_model['category'] = 'behavior' - behavior_model['percentage'] = 0.21392532795156 - - consumption_preferences_model = {} # ConsumptionPreferences - consumption_preferences_model['consumption_preference_id'] = 'consumption_preferences_automobile_ownership_cost' - consumption_preferences_model['name'] = 'Likely to be sensitive to ownership cost when buying automobiles' - consumption_preferences_model['score'] = 0 - - consumption_preferences_category_model = {} # ConsumptionPreferencesCategory - consumption_preferences_category_model['consumption_preference_category_id'] = 'consumption_preferences_shopping' - consumption_preferences_category_model['name'] = 'Purchasing Preferences' - consumption_preferences_category_model['consumption_preferences'] = [consumption_preferences_model] - - warning_model = {} # Warning - warning_model['warning_id'] = 'WORD_COUNT_MESSAGE' - warning_model['message'] = 'testString' - - # Construct a json representation of a Profile model - profile_model_json = {} - profile_model_json['processed_language'] = 'ar' - profile_model_json['word_count'] = 38 - profile_model_json['word_count_message'] = 'testString' - profile_model_json['personality'] = [trait_model] - profile_model_json['needs'] = [trait_model] - profile_model_json['values'] = [trait_model] - profile_model_json['behavior'] = [behavior_model] - profile_model_json['consumption_preferences'] = [consumption_preferences_category_model] - profile_model_json['warnings'] = [warning_model] - - # Construct a model instance of Profile by calling from_dict on the json representation - profile_model = Profile.from_dict(profile_model_json) - assert profile_model != False - - # Construct a model instance of Profile by calling from_dict on the json representation - profile_model_dict = Profile.from_dict(profile_model_json).__dict__ - profile_model2 = Profile(**profile_model_dict) - - # Verify the model instances are equivalent - assert profile_model == profile_model2 - - # Convert model instance back to dict and verify no loss of data - profile_model_json2 = profile_model.to_dict() - assert profile_model_json2 == profile_model_json - -class TestModel_Trait(): - """ - Test Class for Trait - """ - - def test_trait_serialization(self): - """ - Test serialization/deserialization for Trait - """ - - # Construct a json representation of a Trait model - trait_model_json = {} - trait_model_json['trait_id'] = 'testString' - trait_model_json['name'] = 'testString' - trait_model_json['category'] = 'personality' - trait_model_json['percentile'] = 72.5 - trait_model_json['raw_score'] = 72.5 - trait_model_json['significant'] = True - - # Construct a model instance of Trait by calling from_dict on the json representation - trait_model = Trait.from_dict(trait_model_json) - assert trait_model != False - - # Construct a model instance of Trait by calling from_dict on the json representation - trait_model_dict = Trait.from_dict(trait_model_json).__dict__ - trait_model2 = Trait(**trait_model_dict) - - # Verify the model instances are equivalent - assert trait_model == trait_model2 - - # Convert model instance back to dict and verify no loss of data - trait_model_json2 = trait_model.to_dict() - assert trait_model_json2 == trait_model_json - -class TestModel_Warning(): - """ - Test Class for Warning - """ - - def test_warning_serialization(self): - """ - Test serialization/deserialization for Warning - """ - - # Construct a json representation of a Warning model - warning_model_json = {} - warning_model_json['warning_id'] = 'WORD_COUNT_MESSAGE' - warning_model_json['message'] = 'testString' - - # Construct a model instance of Warning by calling from_dict on the json representation - warning_model = Warning.from_dict(warning_model_json) - assert warning_model != False - - # Construct a model instance of Warning by calling from_dict on the json representation - warning_model_dict = Warning.from_dict(warning_model_json).__dict__ - warning_model2 = Warning(**warning_model_dict) - - # Verify the model instances are equivalent - assert warning_model == warning_model2 - - # Convert model instance back to dict and verify no loss of data - warning_model_json2 = warning_model.to_dict() - assert warning_model_json2 == warning_model_json - - -# endregion -############################################################################## -# End of Model Tests -############################################################################## diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 18934165a..ee6bc39b0 100755 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2021. +# (C) Copyright IBM Corp. 2015, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -32,11 +32,38 @@ _service = SpeechToTextV1( authenticator=NoAuthAuthenticator() - ) +) _base_url = 'https://api.us-south.speech-to-text.watson.cloud.ibm.com' _service.set_service_url(_base_url) + +def preprocess_url(operation_path: str): + """ + Returns the request url associated with the specified operation path. + This will be base_url concatenated with a quoted version of operation_path. + The returned request URL is used to register the mock response so it needs + to match the request URL that is formed by the requests library. + """ + # First, unquote the path since it might have some quoted/escaped characters in it + # due to how the generator inserts the operation paths into the unit test code. + operation_path = urllib.parse.unquote(operation_path) + + # Next, quote the path using urllib so that we approximate what will + # happen during request processing. + operation_path = urllib.parse.quote(operation_path, safe='/') + + # Finally, form the request URL from the base URL and operation path. + request_url = _base_url + operation_path + + # If the request url does NOT end with a /, then just return it as-is. + # Otherwise, return a regular expression that matches one or more trailing /. + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + ############################################################################## # Start of Service: Models ############################################################################## @@ -47,25 +74,14 @@ class TestListModels(): Test Class for list_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_models_all_params(self): """ list_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models') - mock_response = '{"models": [{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}]}' + url = preprocess_url('/v1/models') + mock_response = '{"models": [{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}]}' responses.add(responses.GET, url, body=mock_response, @@ -80,31 +96,28 @@ def test_list_models_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_models_all_params_with_retries(self): + # Enable retries and run test_list_models_all_params. + _service.enable_retries() + self.test_list_models_all_params() + + # Disable retries and run test_list_models_all_params. + _service.disable_retries() + self.test_list_models_all_params() class TestGetModel(): """ Test Class for get_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_model_all_params(self): """ get_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/ar-AR_BroadbandModel') - mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' + url = preprocess_url('/v1/models/ar-AR_BroadbandModel') + mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' responses.add(responses.GET, url, body=mock_response, @@ -124,6 +137,14 @@ def test_get_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_model_all_params_with_retries(self): + # Enable retries and run test_get_model_all_params. + _service.enable_retries() + self.test_get_model_all_params() + + # Disable retries and run test_get_model_all_params. + _service.disable_retries() + self.test_get_model_all_params() @responses.activate def test_get_model_value_error(self): @@ -131,8 +152,8 @@ def test_get_model_value_error(self): test_get_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/models/ar-AR_BroadbandModel') - mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' + url = preprocess_url('/v1/models/ar-AR_BroadbandModel') + mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' responses.add(responses.GET, url, body=mock_response, @@ -152,6 +173,14 @@ def test_get_model_value_error(self): _service.get_model(**req_copy) + def test_get_model_value_error_with_retries(self): + # Enable retries and run test_get_model_value_error. + _service.enable_retries() + self.test_get_model_value_error() + + # Disable retries and run test_get_model_value_error. + _service.disable_retries() + self.test_get_model_value_error() # endregion ############################################################################## @@ -168,24 +197,13 @@ class TestRecognize(): Test Class for recognize """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_recognize_all_params(self): """ recognize() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/recognize') + url = preprocess_url('/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -284,6 +302,14 @@ def test_recognize_all_params(self): assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string # Validate body params + def test_recognize_all_params_with_retries(self): + # Enable retries and run test_recognize_all_params. + _service.enable_retries() + self.test_recognize_all_params() + + # Disable retries and run test_recognize_all_params. + _service.disable_retries() + self.test_recognize_all_params() @responses.activate def test_recognize_required_params(self): @@ -291,7 +317,7 @@ def test_recognize_required_params(self): test_recognize_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/recognize') + url = preprocess_url('/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -313,6 +339,14 @@ def test_recognize_required_params(self): assert response.status_code == 200 # Validate body params + def test_recognize_required_params_with_retries(self): + # Enable retries and run test_recognize_required_params. + _service.enable_retries() + self.test_recognize_required_params() + + # Disable retries and run test_recognize_required_params. + _service.disable_retries() + self.test_recognize_required_params() @responses.activate def test_recognize_value_error(self): @@ -320,7 +354,7 @@ def test_recognize_value_error(self): test_recognize_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/recognize') + url = preprocess_url('/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -341,6 +375,14 @@ def test_recognize_value_error(self): _service.recognize(**req_copy) + def test_recognize_value_error_with_retries(self): + # Enable retries and run test_recognize_value_error. + _service.enable_retries() + self.test_recognize_value_error() + + # Disable retries and run test_recognize_value_error. + _service.disable_retries() + self.test_recognize_value_error() # endregion ############################################################################## @@ -357,24 +399,13 @@ class TestRegisterCallback(): Test Class for register_callback """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_register_callback_all_params(self): """ register_callback() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/register_callback') + url = preprocess_url('/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' responses.add(responses.POST, url, @@ -402,6 +433,14 @@ def test_register_callback_all_params(self): assert 'callback_url={}'.format(callback_url) in query_string assert 'user_secret={}'.format(user_secret) in query_string + def test_register_callback_all_params_with_retries(self): + # Enable retries and run test_register_callback_all_params. + _service.enable_retries() + self.test_register_callback_all_params() + + # Disable retries and run test_register_callback_all_params. + _service.disable_retries() + self.test_register_callback_all_params() @responses.activate def test_register_callback_required_params(self): @@ -409,7 +448,7 @@ def test_register_callback_required_params(self): test_register_callback_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/register_callback') + url = preprocess_url('/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' responses.add(responses.POST, url, @@ -434,6 +473,14 @@ def test_register_callback_required_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'callback_url={}'.format(callback_url) in query_string + def test_register_callback_required_params_with_retries(self): + # Enable retries and run test_register_callback_required_params. + _service.enable_retries() + self.test_register_callback_required_params() + + # Disable retries and run test_register_callback_required_params. + _service.disable_retries() + self.test_register_callback_required_params() @responses.activate def test_register_callback_value_error(self): @@ -441,7 +488,7 @@ def test_register_callback_value_error(self): test_register_callback_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/register_callback') + url = preprocess_url('/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' responses.add(responses.POST, url, @@ -462,30 +509,27 @@ def test_register_callback_value_error(self): _service.register_callback(**req_copy) + def test_register_callback_value_error_with_retries(self): + # Enable retries and run test_register_callback_value_error. + _service.enable_retries() + self.test_register_callback_value_error() + + # Disable retries and run test_register_callback_value_error. + _service.disable_retries() + self.test_register_callback_value_error() class TestUnregisterCallback(): """ Test Class for unregister_callback """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_unregister_callback_all_params(self): """ unregister_callback() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/unregister_callback') + url = preprocess_url('/v1/unregister_callback') responses.add(responses.POST, url, status=200) @@ -507,6 +551,14 @@ def test_unregister_callback_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'callback_url={}'.format(callback_url) in query_string + def test_unregister_callback_all_params_with_retries(self): + # Enable retries and run test_unregister_callback_all_params. + _service.enable_retries() + self.test_unregister_callback_all_params() + + # Disable retries and run test_unregister_callback_all_params. + _service.disable_retries() + self.test_unregister_callback_all_params() @responses.activate def test_unregister_callback_value_error(self): @@ -514,7 +566,7 @@ def test_unregister_callback_value_error(self): test_unregister_callback_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/unregister_callback') + url = preprocess_url('/v1/unregister_callback') responses.add(responses.POST, url, status=200) @@ -532,30 +584,27 @@ def test_unregister_callback_value_error(self): _service.unregister_callback(**req_copy) + def test_unregister_callback_value_error_with_retries(self): + # Enable retries and run test_unregister_callback_value_error. + _service.enable_retries() + self.test_unregister_callback_value_error() + + # Disable retries and run test_unregister_callback_value_error. + _service.disable_retries() + self.test_unregister_callback_value_error() class TestCreateJob(): """ Test Class for create_job """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_job_all_params(self): """ create_job() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/recognitions') + url = preprocess_url('/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -672,6 +721,14 @@ def test_create_job_all_params(self): assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string # Validate body params + def test_create_job_all_params_with_retries(self): + # Enable retries and run test_create_job_all_params. + _service.enable_retries() + self.test_create_job_all_params() + + # Disable retries and run test_create_job_all_params. + _service.disable_retries() + self.test_create_job_all_params() @responses.activate def test_create_job_required_params(self): @@ -679,7 +736,7 @@ def test_create_job_required_params(self): test_create_job_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/recognitions') + url = preprocess_url('/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -701,6 +758,14 @@ def test_create_job_required_params(self): assert response.status_code == 201 # Validate body params + def test_create_job_required_params_with_retries(self): + # Enable retries and run test_create_job_required_params. + _service.enable_retries() + self.test_create_job_required_params() + + # Disable retries and run test_create_job_required_params. + _service.disable_retries() + self.test_create_job_required_params() @responses.activate def test_create_job_value_error(self): @@ -708,7 +773,7 @@ def test_create_job_value_error(self): test_create_job_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/recognitions') + url = preprocess_url('/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' responses.add(responses.POST, url, @@ -729,30 +794,27 @@ def test_create_job_value_error(self): _service.create_job(**req_copy) + def test_create_job_value_error_with_retries(self): + # Enable retries and run test_create_job_value_error. + _service.enable_retries() + self.test_create_job_value_error() + + # Disable retries and run test_create_job_value_error. + _service.disable_retries() + self.test_create_job_value_error() class TestCheckJobs(): """ Test Class for check_jobs """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_check_jobs_all_params(self): """ check_jobs() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/recognitions') + url = preprocess_url('/v1/recognitions') mock_response = '{"recognitions": [{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}]}' responses.add(responses.GET, url, @@ -768,30 +830,27 @@ def test_check_jobs_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_check_jobs_all_params_with_retries(self): + # Enable retries and run test_check_jobs_all_params. + _service.enable_retries() + self.test_check_jobs_all_params() + + # Disable retries and run test_check_jobs_all_params. + _service.disable_retries() + self.test_check_jobs_all_params() class TestCheckJob(): """ Test Class for check_job """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_check_job_all_params(self): """ check_job() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/recognitions/testString') + url = preprocess_url('/v1/recognitions/testString') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' responses.add(responses.GET, url, @@ -812,6 +871,14 @@ def test_check_job_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_check_job_all_params_with_retries(self): + # Enable retries and run test_check_job_all_params. + _service.enable_retries() + self.test_check_job_all_params() + + # Disable retries and run test_check_job_all_params. + _service.disable_retries() + self.test_check_job_all_params() @responses.activate def test_check_job_value_error(self): @@ -819,7 +886,7 @@ def test_check_job_value_error(self): test_check_job_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/recognitions/testString') + url = preprocess_url('/v1/recognitions/testString') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' responses.add(responses.GET, url, @@ -840,30 +907,27 @@ def test_check_job_value_error(self): _service.check_job(**req_copy) + def test_check_job_value_error_with_retries(self): + # Enable retries and run test_check_job_value_error. + _service.enable_retries() + self.test_check_job_value_error() + + # Disable retries and run test_check_job_value_error. + _service.disable_retries() + self.test_check_job_value_error() class TestDeleteJob(): """ Test Class for delete_job """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_job_all_params(self): """ delete_job() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/recognitions/testString') + url = preprocess_url('/v1/recognitions/testString') responses.add(responses.DELETE, url, status=204) @@ -881,6 +945,14 @@ def test_delete_job_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_job_all_params_with_retries(self): + # Enable retries and run test_delete_job_all_params. + _service.enable_retries() + self.test_delete_job_all_params() + + # Disable retries and run test_delete_job_all_params. + _service.disable_retries() + self.test_delete_job_all_params() @responses.activate def test_delete_job_value_error(self): @@ -888,7 +960,7 @@ def test_delete_job_value_error(self): test_delete_job_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/recognitions/testString') + url = preprocess_url('/v1/recognitions/testString') responses.add(responses.DELETE, url, status=204) @@ -906,6 +978,14 @@ def test_delete_job_value_error(self): _service.delete_job(**req_copy) + def test_delete_job_value_error_with_retries(self): + # Enable retries and run test_delete_job_value_error. + _service.enable_retries() + self.test_delete_job_value_error() + + # Disable retries and run test_delete_job_value_error. + _service.disable_retries() + self.test_delete_job_value_error() # endregion ############################################################################## @@ -922,24 +1002,13 @@ class TestCreateLanguageModel(): Test Class for create_language_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_language_model_all_params(self): """ create_language_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations') + url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' responses.add(responses.POST, url, @@ -972,6 +1041,14 @@ def test_create_language_model_all_params(self): assert req_body['dialect'] == 'testString' assert req_body['description'] == 'testString' + def test_create_language_model_all_params_with_retries(self): + # Enable retries and run test_create_language_model_all_params. + _service.enable_retries() + self.test_create_language_model_all_params() + + # Disable retries and run test_create_language_model_all_params. + _service.disable_retries() + self.test_create_language_model_all_params() @responses.activate def test_create_language_model_value_error(self): @@ -979,7 +1056,7 @@ def test_create_language_model_value_error(self): test_create_language_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations') + url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' responses.add(responses.POST, url, @@ -1004,30 +1081,27 @@ def test_create_language_model_value_error(self): _service.create_language_model(**req_copy) + def test_create_language_model_value_error_with_retries(self): + # Enable retries and run test_create_language_model_value_error. + _service.enable_retries() + self.test_create_language_model_value_error() + + # Disable retries and run test_create_language_model_value_error. + _service.disable_retries() + self.test_create_language_model_value_error() class TestListLanguageModels(): """ Test Class for list_language_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_language_models_all_params(self): """ list_language_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations') + url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}]}' responses.add(responses.GET, url, @@ -1052,6 +1126,14 @@ def test_list_language_models_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'language={}'.format(language) in query_string + def test_list_language_models_all_params_with_retries(self): + # Enable retries and run test_list_language_models_all_params. + _service.enable_retries() + self.test_list_language_models_all_params() + + # Disable retries and run test_list_language_models_all_params. + _service.disable_retries() + self.test_list_language_models_all_params() @responses.activate def test_list_language_models_required_params(self): @@ -1059,7 +1141,7 @@ def test_list_language_models_required_params(self): test_list_language_models_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations') + url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}]}' responses.add(responses.GET, url, @@ -1075,30 +1157,27 @@ def test_list_language_models_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_language_models_required_params_with_retries(self): + # Enable retries and run test_list_language_models_required_params. + _service.enable_retries() + self.test_list_language_models_required_params() + + # Disable retries and run test_list_language_models_required_params. + _service.disable_retries() + self.test_list_language_models_required_params() class TestGetLanguageModel(): """ Test Class for get_language_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_language_model_all_params(self): """ get_language_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString') + url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' responses.add(responses.GET, url, @@ -1119,6 +1198,14 @@ def test_get_language_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_language_model_all_params_with_retries(self): + # Enable retries and run test_get_language_model_all_params. + _service.enable_retries() + self.test_get_language_model_all_params() + + # Disable retries and run test_get_language_model_all_params. + _service.disable_retries() + self.test_get_language_model_all_params() @responses.activate def test_get_language_model_value_error(self): @@ -1126,7 +1213,7 @@ def test_get_language_model_value_error(self): test_get_language_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString') + url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' responses.add(responses.GET, url, @@ -1147,30 +1234,27 @@ def test_get_language_model_value_error(self): _service.get_language_model(**req_copy) + def test_get_language_model_value_error_with_retries(self): + # Enable retries and run test_get_language_model_value_error. + _service.enable_retries() + self.test_get_language_model_value_error() + + # Disable retries and run test_get_language_model_value_error. + _service.disable_retries() + self.test_get_language_model_value_error() class TestDeleteLanguageModel(): """ Test Class for delete_language_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_language_model_all_params(self): """ delete_language_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString') + url = preprocess_url('/v1/customizations/testString') responses.add(responses.DELETE, url, status=200) @@ -1188,6 +1272,14 @@ def test_delete_language_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_language_model_all_params_with_retries(self): + # Enable retries and run test_delete_language_model_all_params. + _service.enable_retries() + self.test_delete_language_model_all_params() + + # Disable retries and run test_delete_language_model_all_params. + _service.disable_retries() + self.test_delete_language_model_all_params() @responses.activate def test_delete_language_model_value_error(self): @@ -1195,7 +1287,7 @@ def test_delete_language_model_value_error(self): test_delete_language_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString') + url = preprocess_url('/v1/customizations/testString') responses.add(responses.DELETE, url, status=200) @@ -1213,30 +1305,27 @@ def test_delete_language_model_value_error(self): _service.delete_language_model(**req_copy) + def test_delete_language_model_value_error_with_retries(self): + # Enable retries and run test_delete_language_model_value_error. + _service.enable_retries() + self.test_delete_language_model_value_error() + + # Disable retries and run test_delete_language_model_value_error. + _service.disable_retries() + self.test_delete_language_model_value_error() class TestTrainLanguageModel(): """ Test Class for train_language_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_train_language_model_all_params(self): """ train_language_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/train') + url = preprocess_url('/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -1266,6 +1355,14 @@ def test_train_language_model_all_params(self): assert 'word_type_to_add={}'.format(word_type_to_add) in query_string assert 'customization_weight={}'.format(customization_weight) in query_string + def test_train_language_model_all_params_with_retries(self): + # Enable retries and run test_train_language_model_all_params. + _service.enable_retries() + self.test_train_language_model_all_params() + + # Disable retries and run test_train_language_model_all_params. + _service.disable_retries() + self.test_train_language_model_all_params() @responses.activate def test_train_language_model_required_params(self): @@ -1273,7 +1370,7 @@ def test_train_language_model_required_params(self): test_train_language_model_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/train') + url = preprocess_url('/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -1294,6 +1391,14 @@ def test_train_language_model_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_train_language_model_required_params_with_retries(self): + # Enable retries and run test_train_language_model_required_params. + _service.enable_retries() + self.test_train_language_model_required_params() + + # Disable retries and run test_train_language_model_required_params. + _service.disable_retries() + self.test_train_language_model_required_params() @responses.activate def test_train_language_model_value_error(self): @@ -1301,7 +1406,7 @@ def test_train_language_model_value_error(self): test_train_language_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/train') + url = preprocess_url('/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -1322,30 +1427,27 @@ def test_train_language_model_value_error(self): _service.train_language_model(**req_copy) + def test_train_language_model_value_error_with_retries(self): + # Enable retries and run test_train_language_model_value_error. + _service.enable_retries() + self.test_train_language_model_value_error() + + # Disable retries and run test_train_language_model_value_error. + _service.disable_retries() + self.test_train_language_model_value_error() class TestResetLanguageModel(): """ Test Class for reset_language_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_reset_language_model_all_params(self): """ reset_language_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/reset') + url = preprocess_url('/v1/customizations/testString/reset') responses.add(responses.POST, url, status=200) @@ -1363,6 +1465,14 @@ def test_reset_language_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_reset_language_model_all_params_with_retries(self): + # Enable retries and run test_reset_language_model_all_params. + _service.enable_retries() + self.test_reset_language_model_all_params() + + # Disable retries and run test_reset_language_model_all_params. + _service.disable_retries() + self.test_reset_language_model_all_params() @responses.activate def test_reset_language_model_value_error(self): @@ -1370,7 +1480,7 @@ def test_reset_language_model_value_error(self): test_reset_language_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/reset') + url = preprocess_url('/v1/customizations/testString/reset') responses.add(responses.POST, url, status=200) @@ -1388,30 +1498,27 @@ def test_reset_language_model_value_error(self): _service.reset_language_model(**req_copy) + def test_reset_language_model_value_error_with_retries(self): + # Enable retries and run test_reset_language_model_value_error. + _service.enable_retries() + self.test_reset_language_model_value_error() + + # Disable retries and run test_reset_language_model_value_error. + _service.disable_retries() + self.test_reset_language_model_value_error() class TestUpgradeLanguageModel(): """ Test Class for upgrade_language_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_upgrade_language_model_all_params(self): """ upgrade_language_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/upgrade_model') + url = preprocess_url('/v1/customizations/testString/upgrade_model') responses.add(responses.POST, url, status=200) @@ -1429,6 +1536,14 @@ def test_upgrade_language_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_upgrade_language_model_all_params_with_retries(self): + # Enable retries and run test_upgrade_language_model_all_params. + _service.enable_retries() + self.test_upgrade_language_model_all_params() + + # Disable retries and run test_upgrade_language_model_all_params. + _service.disable_retries() + self.test_upgrade_language_model_all_params() @responses.activate def test_upgrade_language_model_value_error(self): @@ -1436,7 +1551,7 @@ def test_upgrade_language_model_value_error(self): test_upgrade_language_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/upgrade_model') + url = preprocess_url('/v1/customizations/testString/upgrade_model') responses.add(responses.POST, url, status=200) @@ -1454,6 +1569,14 @@ def test_upgrade_language_model_value_error(self): _service.upgrade_language_model(**req_copy) + def test_upgrade_language_model_value_error_with_retries(self): + # Enable retries and run test_upgrade_language_model_value_error. + _service.enable_retries() + self.test_upgrade_language_model_value_error() + + # Disable retries and run test_upgrade_language_model_value_error. + _service.disable_retries() + self.test_upgrade_language_model_value_error() # endregion ############################################################################## @@ -1470,24 +1593,13 @@ class TestListCorpora(): Test Class for list_corpora """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_corpora_all_params(self): """ list_corpora() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora') + url = preprocess_url('/v1/customizations/testString/corpora') mock_response = '{"corpora": [{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' responses.add(responses.GET, url, @@ -1508,6 +1620,14 @@ def test_list_corpora_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_corpora_all_params_with_retries(self): + # Enable retries and run test_list_corpora_all_params. + _service.enable_retries() + self.test_list_corpora_all_params() + + # Disable retries and run test_list_corpora_all_params. + _service.disable_retries() + self.test_list_corpora_all_params() @responses.activate def test_list_corpora_value_error(self): @@ -1515,7 +1635,7 @@ def test_list_corpora_value_error(self): test_list_corpora_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora') + url = preprocess_url('/v1/customizations/testString/corpora') mock_response = '{"corpora": [{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' responses.add(responses.GET, url, @@ -1536,30 +1656,27 @@ def test_list_corpora_value_error(self): _service.list_corpora(**req_copy) + def test_list_corpora_value_error_with_retries(self): + # Enable retries and run test_list_corpora_value_error. + _service.enable_retries() + self.test_list_corpora_value_error() + + # Disable retries and run test_list_corpora_value_error. + _service.disable_retries() + self.test_list_corpora_value_error() class TestAddCorpus(): """ Test Class for add_corpus """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_add_corpus_all_params(self): """ add_corpus() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') + url = preprocess_url('/v1/customizations/testString/corpora/testString') responses.add(responses.POST, url, status=201) @@ -1587,6 +1704,14 @@ def test_add_corpus_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string + def test_add_corpus_all_params_with_retries(self): + # Enable retries and run test_add_corpus_all_params. + _service.enable_retries() + self.test_add_corpus_all_params() + + # Disable retries and run test_add_corpus_all_params. + _service.disable_retries() + self.test_add_corpus_all_params() @responses.activate def test_add_corpus_required_params(self): @@ -1594,7 +1719,7 @@ def test_add_corpus_required_params(self): test_add_corpus_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') + url = preprocess_url('/v1/customizations/testString/corpora/testString') responses.add(responses.POST, url, status=201) @@ -1616,6 +1741,14 @@ def test_add_corpus_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_add_corpus_required_params_with_retries(self): + # Enable retries and run test_add_corpus_required_params. + _service.enable_retries() + self.test_add_corpus_required_params() + + # Disable retries and run test_add_corpus_required_params. + _service.disable_retries() + self.test_add_corpus_required_params() @responses.activate def test_add_corpus_value_error(self): @@ -1623,7 +1756,7 @@ def test_add_corpus_value_error(self): test_add_corpus_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') + url = preprocess_url('/v1/customizations/testString/corpora/testString') responses.add(responses.POST, url, status=201) @@ -1645,30 +1778,27 @@ def test_add_corpus_value_error(self): _service.add_corpus(**req_copy) + def test_add_corpus_value_error_with_retries(self): + # Enable retries and run test_add_corpus_value_error. + _service.enable_retries() + self.test_add_corpus_value_error() + + # Disable retries and run test_add_corpus_value_error. + _service.disable_retries() + self.test_add_corpus_value_error() class TestGetCorpus(): """ Test Class for get_corpus """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_corpus_all_params(self): """ get_corpus() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') + url = preprocess_url('/v1/customizations/testString/corpora/testString') mock_response = '{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' responses.add(responses.GET, url, @@ -1691,6 +1821,14 @@ def test_get_corpus_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_corpus_all_params_with_retries(self): + # Enable retries and run test_get_corpus_all_params. + _service.enable_retries() + self.test_get_corpus_all_params() + + # Disable retries and run test_get_corpus_all_params. + _service.disable_retries() + self.test_get_corpus_all_params() @responses.activate def test_get_corpus_value_error(self): @@ -1698,7 +1836,7 @@ def test_get_corpus_value_error(self): test_get_corpus_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') + url = preprocess_url('/v1/customizations/testString/corpora/testString') mock_response = '{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' responses.add(responses.GET, url, @@ -1721,30 +1859,27 @@ def test_get_corpus_value_error(self): _service.get_corpus(**req_copy) + def test_get_corpus_value_error_with_retries(self): + # Enable retries and run test_get_corpus_value_error. + _service.enable_retries() + self.test_get_corpus_value_error() + + # Disable retries and run test_get_corpus_value_error. + _service.disable_retries() + self.test_get_corpus_value_error() class TestDeleteCorpus(): """ Test Class for delete_corpus """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_corpus_all_params(self): """ delete_corpus() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') + url = preprocess_url('/v1/customizations/testString/corpora/testString') responses.add(responses.DELETE, url, status=200) @@ -1764,6 +1899,14 @@ def test_delete_corpus_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_corpus_all_params_with_retries(self): + # Enable retries and run test_delete_corpus_all_params. + _service.enable_retries() + self.test_delete_corpus_all_params() + + # Disable retries and run test_delete_corpus_all_params. + _service.disable_retries() + self.test_delete_corpus_all_params() @responses.activate def test_delete_corpus_value_error(self): @@ -1771,7 +1914,7 @@ def test_delete_corpus_value_error(self): test_delete_corpus_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/corpora/testString') + url = preprocess_url('/v1/customizations/testString/corpora/testString') responses.add(responses.DELETE, url, status=200) @@ -1791,6 +1934,14 @@ def test_delete_corpus_value_error(self): _service.delete_corpus(**req_copy) + def test_delete_corpus_value_error_with_retries(self): + # Enable retries and run test_delete_corpus_value_error. + _service.enable_retries() + self.test_delete_corpus_value_error() + + # Disable retries and run test_delete_corpus_value_error. + _service.disable_retries() + self.test_delete_corpus_value_error() # endregion ############################################################################## @@ -1807,24 +1958,13 @@ class TestListWords(): Test Class for list_words """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_words_all_params(self): """ list_words() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') + url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' responses.add(responses.GET, url, @@ -1854,6 +1994,14 @@ def test_list_words_all_params(self): assert 'word_type={}'.format(word_type) in query_string assert 'sort={}'.format(sort) in query_string + def test_list_words_all_params_with_retries(self): + # Enable retries and run test_list_words_all_params. + _service.enable_retries() + self.test_list_words_all_params() + + # Disable retries and run test_list_words_all_params. + _service.disable_retries() + self.test_list_words_all_params() @responses.activate def test_list_words_required_params(self): @@ -1861,7 +2009,7 @@ def test_list_words_required_params(self): test_list_words_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') + url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' responses.add(responses.GET, url, @@ -1882,6 +2030,14 @@ def test_list_words_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_words_required_params_with_retries(self): + # Enable retries and run test_list_words_required_params. + _service.enable_retries() + self.test_list_words_required_params() + + # Disable retries and run test_list_words_required_params. + _service.disable_retries() + self.test_list_words_required_params() @responses.activate def test_list_words_value_error(self): @@ -1889,7 +2045,7 @@ def test_list_words_value_error(self): test_list_words_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') + url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' responses.add(responses.GET, url, @@ -1910,30 +2066,27 @@ def test_list_words_value_error(self): _service.list_words(**req_copy) + def test_list_words_value_error_with_retries(self): + # Enable retries and run test_list_words_value_error. + _service.enable_retries() + self.test_list_words_value_error() + + # Disable retries and run test_list_words_value_error. + _service.disable_retries() + self.test_list_words_value_error() class TestAddWords(): """ Test Class for add_words """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_add_words_all_params(self): """ add_words() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') + url = preprocess_url('/v1/customizations/testString/words') responses.add(responses.POST, url, status=201) @@ -1962,6 +2115,14 @@ def test_add_words_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['words'] == [custom_word_model] + def test_add_words_all_params_with_retries(self): + # Enable retries and run test_add_words_all_params. + _service.enable_retries() + self.test_add_words_all_params() + + # Disable retries and run test_add_words_all_params. + _service.disable_retries() + self.test_add_words_all_params() @responses.activate def test_add_words_value_error(self): @@ -1969,7 +2130,7 @@ def test_add_words_value_error(self): test_add_words_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') + url = preprocess_url('/v1/customizations/testString/words') responses.add(responses.POST, url, status=201) @@ -1995,30 +2156,27 @@ def test_add_words_value_error(self): _service.add_words(**req_copy) + def test_add_words_value_error_with_retries(self): + # Enable retries and run test_add_words_value_error. + _service.enable_retries() + self.test_add_words_value_error() + + # Disable retries and run test_add_words_value_error. + _service.disable_retries() + self.test_add_words_value_error() class TestAddWord(): """ Test Class for add_word """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_add_word_all_params(self): """ add_word() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') responses.add(responses.PUT, url, status=201) @@ -2049,6 +2207,14 @@ def test_add_word_all_params(self): assert req_body['sounds_like'] == ['testString'] assert req_body['display_as'] == 'testString' + def test_add_word_all_params_with_retries(self): + # Enable retries and run test_add_word_all_params. + _service.enable_retries() + self.test_add_word_all_params() + + # Disable retries and run test_add_word_all_params. + _service.disable_retries() + self.test_add_word_all_params() @responses.activate def test_add_word_value_error(self): @@ -2056,7 +2222,7 @@ def test_add_word_value_error(self): test_add_word_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') responses.add(responses.PUT, url, status=201) @@ -2079,30 +2245,27 @@ def test_add_word_value_error(self): _service.add_word(**req_copy) + def test_add_word_value_error_with_retries(self): + # Enable retries and run test_add_word_value_error. + _service.enable_retries() + self.test_add_word_value_error() + + # Disable retries and run test_add_word_value_error. + _service.disable_retries() + self.test_add_word_value_error() class TestGetWord(): """ Test Class for get_word """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_word_all_params(self): """ get_word() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' responses.add(responses.GET, url, @@ -2125,6 +2288,14 @@ def test_get_word_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_word_all_params_with_retries(self): + # Enable retries and run test_get_word_all_params. + _service.enable_retries() + self.test_get_word_all_params() + + # Disable retries and run test_get_word_all_params. + _service.disable_retries() + self.test_get_word_all_params() @responses.activate def test_get_word_value_error(self): @@ -2132,7 +2303,7 @@ def test_get_word_value_error(self): test_get_word_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' responses.add(responses.GET, url, @@ -2155,30 +2326,27 @@ def test_get_word_value_error(self): _service.get_word(**req_copy) + def test_get_word_value_error_with_retries(self): + # Enable retries and run test_get_word_value_error. + _service.enable_retries() + self.test_get_word_value_error() + + # Disable retries and run test_get_word_value_error. + _service.disable_retries() + self.test_get_word_value_error() class TestDeleteWord(): """ Test Class for delete_word """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_word_all_params(self): """ delete_word() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') responses.add(responses.DELETE, url, status=200) @@ -2198,6 +2366,14 @@ def test_delete_word_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_word_all_params_with_retries(self): + # Enable retries and run test_delete_word_all_params. + _service.enable_retries() + self.test_delete_word_all_params() + + # Disable retries and run test_delete_word_all_params. + _service.disable_retries() + self.test_delete_word_all_params() @responses.activate def test_delete_word_value_error(self): @@ -2205,7 +2381,7 @@ def test_delete_word_value_error(self): test_delete_word_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') responses.add(responses.DELETE, url, status=200) @@ -2225,6 +2401,14 @@ def test_delete_word_value_error(self): _service.delete_word(**req_copy) + def test_delete_word_value_error_with_retries(self): + # Enable retries and run test_delete_word_value_error. + _service.enable_retries() + self.test_delete_word_value_error() + + # Disable retries and run test_delete_word_value_error. + _service.disable_retries() + self.test_delete_word_value_error() # endregion ############################################################################## @@ -2241,24 +2425,13 @@ class TestListGrammars(): Test Class for list_grammars """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_grammars_all_params(self): """ list_grammars() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars') + url = preprocess_url('/v1/customizations/testString/grammars') mock_response = '{"grammars": [{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' responses.add(responses.GET, url, @@ -2279,6 +2452,14 @@ def test_list_grammars_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_grammars_all_params_with_retries(self): + # Enable retries and run test_list_grammars_all_params. + _service.enable_retries() + self.test_list_grammars_all_params() + + # Disable retries and run test_list_grammars_all_params. + _service.disable_retries() + self.test_list_grammars_all_params() @responses.activate def test_list_grammars_value_error(self): @@ -2286,7 +2467,7 @@ def test_list_grammars_value_error(self): test_list_grammars_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars') + url = preprocess_url('/v1/customizations/testString/grammars') mock_response = '{"grammars": [{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' responses.add(responses.GET, url, @@ -2307,30 +2488,27 @@ def test_list_grammars_value_error(self): _service.list_grammars(**req_copy) + def test_list_grammars_value_error_with_retries(self): + # Enable retries and run test_list_grammars_value_error. + _service.enable_retries() + self.test_list_grammars_value_error() + + # Disable retries and run test_list_grammars_value_error. + _service.disable_retries() + self.test_list_grammars_value_error() class TestAddGrammar(): """ Test Class for add_grammar """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_add_grammar_all_params(self): """ add_grammar() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') + url = preprocess_url('/v1/customizations/testString/grammars/testString') responses.add(responses.POST, url, status=201) @@ -2338,7 +2516,7 @@ def test_add_grammar_all_params(self): # Set up parameter values customization_id = 'testString' grammar_name = 'testString' - grammar_file = 'testString' + grammar_file = io.BytesIO(b'This is a mock file.').getvalue() content_type = 'application/srgs' allow_overwrite = False @@ -2361,6 +2539,14 @@ def test_add_grammar_all_params(self): assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string # Validate body params + def test_add_grammar_all_params_with_retries(self): + # Enable retries and run test_add_grammar_all_params. + _service.enable_retries() + self.test_add_grammar_all_params() + + # Disable retries and run test_add_grammar_all_params. + _service.disable_retries() + self.test_add_grammar_all_params() @responses.activate def test_add_grammar_required_params(self): @@ -2368,7 +2554,7 @@ def test_add_grammar_required_params(self): test_add_grammar_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') + url = preprocess_url('/v1/customizations/testString/grammars/testString') responses.add(responses.POST, url, status=201) @@ -2376,7 +2562,7 @@ def test_add_grammar_required_params(self): # Set up parameter values customization_id = 'testString' grammar_name = 'testString' - grammar_file = 'testString' + grammar_file = io.BytesIO(b'This is a mock file.').getvalue() content_type = 'application/srgs' # Invoke method @@ -2393,6 +2579,14 @@ def test_add_grammar_required_params(self): assert response.status_code == 201 # Validate body params + def test_add_grammar_required_params_with_retries(self): + # Enable retries and run test_add_grammar_required_params. + _service.enable_retries() + self.test_add_grammar_required_params() + + # Disable retries and run test_add_grammar_required_params. + _service.disable_retries() + self.test_add_grammar_required_params() @responses.activate def test_add_grammar_value_error(self): @@ -2400,7 +2594,7 @@ def test_add_grammar_value_error(self): test_add_grammar_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') + url = preprocess_url('/v1/customizations/testString/grammars/testString') responses.add(responses.POST, url, status=201) @@ -2408,7 +2602,7 @@ def test_add_grammar_value_error(self): # Set up parameter values customization_id = 'testString' grammar_name = 'testString' - grammar_file = 'testString' + grammar_file = io.BytesIO(b'This is a mock file.').getvalue() content_type = 'application/srgs' # Pass in all but one required param and check for a ValueError @@ -2424,30 +2618,27 @@ def test_add_grammar_value_error(self): _service.add_grammar(**req_copy) + def test_add_grammar_value_error_with_retries(self): + # Enable retries and run test_add_grammar_value_error. + _service.enable_retries() + self.test_add_grammar_value_error() + + # Disable retries and run test_add_grammar_value_error. + _service.disable_retries() + self.test_add_grammar_value_error() class TestGetGrammar(): """ Test Class for get_grammar """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_grammar_all_params(self): """ get_grammar() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') + url = preprocess_url('/v1/customizations/testString/grammars/testString') mock_response = '{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' responses.add(responses.GET, url, @@ -2470,6 +2661,14 @@ def test_get_grammar_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_grammar_all_params_with_retries(self): + # Enable retries and run test_get_grammar_all_params. + _service.enable_retries() + self.test_get_grammar_all_params() + + # Disable retries and run test_get_grammar_all_params. + _service.disable_retries() + self.test_get_grammar_all_params() @responses.activate def test_get_grammar_value_error(self): @@ -2477,7 +2676,7 @@ def test_get_grammar_value_error(self): test_get_grammar_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') + url = preprocess_url('/v1/customizations/testString/grammars/testString') mock_response = '{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' responses.add(responses.GET, url, @@ -2500,30 +2699,27 @@ def test_get_grammar_value_error(self): _service.get_grammar(**req_copy) + def test_get_grammar_value_error_with_retries(self): + # Enable retries and run test_get_grammar_value_error. + _service.enable_retries() + self.test_get_grammar_value_error() + + # Disable retries and run test_get_grammar_value_error. + _service.disable_retries() + self.test_get_grammar_value_error() class TestDeleteGrammar(): """ Test Class for delete_grammar """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_grammar_all_params(self): """ delete_grammar() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') + url = preprocess_url('/v1/customizations/testString/grammars/testString') responses.add(responses.DELETE, url, status=200) @@ -2543,6 +2739,14 @@ def test_delete_grammar_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_grammar_all_params_with_retries(self): + # Enable retries and run test_delete_grammar_all_params. + _service.enable_retries() + self.test_delete_grammar_all_params() + + # Disable retries and run test_delete_grammar_all_params. + _service.disable_retries() + self.test_delete_grammar_all_params() @responses.activate def test_delete_grammar_value_error(self): @@ -2550,7 +2754,7 @@ def test_delete_grammar_value_error(self): test_delete_grammar_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/grammars/testString') + url = preprocess_url('/v1/customizations/testString/grammars/testString') responses.add(responses.DELETE, url, status=200) @@ -2570,6 +2774,14 @@ def test_delete_grammar_value_error(self): _service.delete_grammar(**req_copy) + def test_delete_grammar_value_error_with_retries(self): + # Enable retries and run test_delete_grammar_value_error. + _service.enable_retries() + self.test_delete_grammar_value_error() + + # Disable retries and run test_delete_grammar_value_error. + _service.disable_retries() + self.test_delete_grammar_value_error() # endregion ############################################################################## @@ -2586,24 +2798,13 @@ class TestCreateAcousticModel(): Test Class for create_acoustic_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_acoustic_model_all_params(self): """ create_acoustic_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations') + url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' responses.add(responses.POST, url, @@ -2633,6 +2834,14 @@ def test_create_acoustic_model_all_params(self): assert req_body['base_model_name'] == 'ar-AR_BroadbandModel' assert req_body['description'] == 'testString' + def test_create_acoustic_model_all_params_with_retries(self): + # Enable retries and run test_create_acoustic_model_all_params. + _service.enable_retries() + self.test_create_acoustic_model_all_params() + + # Disable retries and run test_create_acoustic_model_all_params. + _service.disable_retries() + self.test_create_acoustic_model_all_params() @responses.activate def test_create_acoustic_model_value_error(self): @@ -2640,7 +2849,7 @@ def test_create_acoustic_model_value_error(self): test_create_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations') + url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' responses.add(responses.POST, url, @@ -2664,30 +2873,27 @@ def test_create_acoustic_model_value_error(self): _service.create_acoustic_model(**req_copy) + def test_create_acoustic_model_value_error_with_retries(self): + # Enable retries and run test_create_acoustic_model_value_error. + _service.enable_retries() + self.test_create_acoustic_model_value_error() + + # Disable retries and run test_create_acoustic_model_value_error. + _service.disable_retries() + self.test_create_acoustic_model_value_error() class TestListAcousticModels(): """ Test Class for list_acoustic_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_acoustic_models_all_params(self): """ list_acoustic_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations') + url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}]}' responses.add(responses.GET, url, @@ -2712,6 +2918,14 @@ def test_list_acoustic_models_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'language={}'.format(language) in query_string + def test_list_acoustic_models_all_params_with_retries(self): + # Enable retries and run test_list_acoustic_models_all_params. + _service.enable_retries() + self.test_list_acoustic_models_all_params() + + # Disable retries and run test_list_acoustic_models_all_params. + _service.disable_retries() + self.test_list_acoustic_models_all_params() @responses.activate def test_list_acoustic_models_required_params(self): @@ -2719,7 +2933,7 @@ def test_list_acoustic_models_required_params(self): test_list_acoustic_models_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations') + url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}]}' responses.add(responses.GET, url, @@ -2735,30 +2949,27 @@ def test_list_acoustic_models_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_acoustic_models_required_params_with_retries(self): + # Enable retries and run test_list_acoustic_models_required_params. + _service.enable_retries() + self.test_list_acoustic_models_required_params() + + # Disable retries and run test_list_acoustic_models_required_params. + _service.disable_retries() + self.test_list_acoustic_models_required_params() class TestGetAcousticModel(): """ Test Class for get_acoustic_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_acoustic_model_all_params(self): """ get_acoustic_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString') + url = preprocess_url('/v1/acoustic_customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' responses.add(responses.GET, url, @@ -2779,6 +2990,14 @@ def test_get_acoustic_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_acoustic_model_all_params_with_retries(self): + # Enable retries and run test_get_acoustic_model_all_params. + _service.enable_retries() + self.test_get_acoustic_model_all_params() + + # Disable retries and run test_get_acoustic_model_all_params. + _service.disable_retries() + self.test_get_acoustic_model_all_params() @responses.activate def test_get_acoustic_model_value_error(self): @@ -2786,7 +3005,7 @@ def test_get_acoustic_model_value_error(self): test_get_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString') + url = preprocess_url('/v1/acoustic_customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' responses.add(responses.GET, url, @@ -2807,30 +3026,27 @@ def test_get_acoustic_model_value_error(self): _service.get_acoustic_model(**req_copy) + def test_get_acoustic_model_value_error_with_retries(self): + # Enable retries and run test_get_acoustic_model_value_error. + _service.enable_retries() + self.test_get_acoustic_model_value_error() + + # Disable retries and run test_get_acoustic_model_value_error. + _service.disable_retries() + self.test_get_acoustic_model_value_error() class TestDeleteAcousticModel(): """ Test Class for delete_acoustic_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_acoustic_model_all_params(self): """ delete_acoustic_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString') + url = preprocess_url('/v1/acoustic_customizations/testString') responses.add(responses.DELETE, url, status=200) @@ -2848,6 +3064,14 @@ def test_delete_acoustic_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_acoustic_model_all_params_with_retries(self): + # Enable retries and run test_delete_acoustic_model_all_params. + _service.enable_retries() + self.test_delete_acoustic_model_all_params() + + # Disable retries and run test_delete_acoustic_model_all_params. + _service.disable_retries() + self.test_delete_acoustic_model_all_params() @responses.activate def test_delete_acoustic_model_value_error(self): @@ -2855,7 +3079,7 @@ def test_delete_acoustic_model_value_error(self): test_delete_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString') + url = preprocess_url('/v1/acoustic_customizations/testString') responses.add(responses.DELETE, url, status=200) @@ -2873,30 +3097,27 @@ def test_delete_acoustic_model_value_error(self): _service.delete_acoustic_model(**req_copy) + def test_delete_acoustic_model_value_error_with_retries(self): + # Enable retries and run test_delete_acoustic_model_value_error. + _service.enable_retries() + self.test_delete_acoustic_model_value_error() + + # Disable retries and run test_delete_acoustic_model_value_error. + _service.disable_retries() + self.test_delete_acoustic_model_value_error() class TestTrainAcousticModel(): """ Test Class for train_acoustic_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_train_acoustic_model_all_params(self): """ train_acoustic_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/train') + url = preprocess_url('/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -2923,6 +3144,14 @@ def test_train_acoustic_model_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'custom_language_model_id={}'.format(custom_language_model_id) in query_string + def test_train_acoustic_model_all_params_with_retries(self): + # Enable retries and run test_train_acoustic_model_all_params. + _service.enable_retries() + self.test_train_acoustic_model_all_params() + + # Disable retries and run test_train_acoustic_model_all_params. + _service.disable_retries() + self.test_train_acoustic_model_all_params() @responses.activate def test_train_acoustic_model_required_params(self): @@ -2930,7 +3159,7 @@ def test_train_acoustic_model_required_params(self): test_train_acoustic_model_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/train') + url = preprocess_url('/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -2951,6 +3180,14 @@ def test_train_acoustic_model_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_train_acoustic_model_required_params_with_retries(self): + # Enable retries and run test_train_acoustic_model_required_params. + _service.enable_retries() + self.test_train_acoustic_model_required_params() + + # Disable retries and run test_train_acoustic_model_required_params. + _service.disable_retries() + self.test_train_acoustic_model_required_params() @responses.activate def test_train_acoustic_model_value_error(self): @@ -2958,7 +3195,7 @@ def test_train_acoustic_model_value_error(self): test_train_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/train') + url = preprocess_url('/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' responses.add(responses.POST, url, @@ -2979,30 +3216,27 @@ def test_train_acoustic_model_value_error(self): _service.train_acoustic_model(**req_copy) + def test_train_acoustic_model_value_error_with_retries(self): + # Enable retries and run test_train_acoustic_model_value_error. + _service.enable_retries() + self.test_train_acoustic_model_value_error() + + # Disable retries and run test_train_acoustic_model_value_error. + _service.disable_retries() + self.test_train_acoustic_model_value_error() class TestResetAcousticModel(): """ Test Class for reset_acoustic_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_reset_acoustic_model_all_params(self): """ reset_acoustic_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/reset') + url = preprocess_url('/v1/acoustic_customizations/testString/reset') responses.add(responses.POST, url, status=200) @@ -3020,6 +3254,14 @@ def test_reset_acoustic_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_reset_acoustic_model_all_params_with_retries(self): + # Enable retries and run test_reset_acoustic_model_all_params. + _service.enable_retries() + self.test_reset_acoustic_model_all_params() + + # Disable retries and run test_reset_acoustic_model_all_params. + _service.disable_retries() + self.test_reset_acoustic_model_all_params() @responses.activate def test_reset_acoustic_model_value_error(self): @@ -3027,7 +3269,7 @@ def test_reset_acoustic_model_value_error(self): test_reset_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/reset') + url = preprocess_url('/v1/acoustic_customizations/testString/reset') responses.add(responses.POST, url, status=200) @@ -3045,30 +3287,27 @@ def test_reset_acoustic_model_value_error(self): _service.reset_acoustic_model(**req_copy) + def test_reset_acoustic_model_value_error_with_retries(self): + # Enable retries and run test_reset_acoustic_model_value_error. + _service.enable_retries() + self.test_reset_acoustic_model_value_error() + + # Disable retries and run test_reset_acoustic_model_value_error. + _service.disable_retries() + self.test_reset_acoustic_model_value_error() class TestUpgradeAcousticModel(): """ Test Class for upgrade_acoustic_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_upgrade_acoustic_model_all_params(self): """ upgrade_acoustic_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/upgrade_model') + url = preprocess_url('/v1/acoustic_customizations/testString/upgrade_model') responses.add(responses.POST, url, status=200) @@ -3095,6 +3334,14 @@ def test_upgrade_acoustic_model_all_params(self): assert 'custom_language_model_id={}'.format(custom_language_model_id) in query_string assert 'force={}'.format('true' if force else 'false') in query_string + def test_upgrade_acoustic_model_all_params_with_retries(self): + # Enable retries and run test_upgrade_acoustic_model_all_params. + _service.enable_retries() + self.test_upgrade_acoustic_model_all_params() + + # Disable retries and run test_upgrade_acoustic_model_all_params. + _service.disable_retries() + self.test_upgrade_acoustic_model_all_params() @responses.activate def test_upgrade_acoustic_model_required_params(self): @@ -3102,7 +3349,7 @@ def test_upgrade_acoustic_model_required_params(self): test_upgrade_acoustic_model_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/upgrade_model') + url = preprocess_url('/v1/acoustic_customizations/testString/upgrade_model') responses.add(responses.POST, url, status=200) @@ -3120,6 +3367,14 @@ def test_upgrade_acoustic_model_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_upgrade_acoustic_model_required_params_with_retries(self): + # Enable retries and run test_upgrade_acoustic_model_required_params. + _service.enable_retries() + self.test_upgrade_acoustic_model_required_params() + + # Disable retries and run test_upgrade_acoustic_model_required_params. + _service.disable_retries() + self.test_upgrade_acoustic_model_required_params() @responses.activate def test_upgrade_acoustic_model_value_error(self): @@ -3127,7 +3382,7 @@ def test_upgrade_acoustic_model_value_error(self): test_upgrade_acoustic_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/upgrade_model') + url = preprocess_url('/v1/acoustic_customizations/testString/upgrade_model') responses.add(responses.POST, url, status=200) @@ -3145,6 +3400,14 @@ def test_upgrade_acoustic_model_value_error(self): _service.upgrade_acoustic_model(**req_copy) + def test_upgrade_acoustic_model_value_error_with_retries(self): + # Enable retries and run test_upgrade_acoustic_model_value_error. + _service.enable_retries() + self.test_upgrade_acoustic_model_value_error() + + # Disable retries and run test_upgrade_acoustic_model_value_error. + _service.disable_retries() + self.test_upgrade_acoustic_model_value_error() # endregion ############################################################################## @@ -3161,24 +3424,13 @@ class TestListAudio(): Test Class for list_audio """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_audio_all_params(self): """ list_audio() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio') + url = preprocess_url('/v1/acoustic_customizations/testString/audio') mock_response = '{"total_minutes_of_audio": 22, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' responses.add(responses.GET, url, @@ -3199,6 +3451,14 @@ def test_list_audio_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_audio_all_params_with_retries(self): + # Enable retries and run test_list_audio_all_params. + _service.enable_retries() + self.test_list_audio_all_params() + + # Disable retries and run test_list_audio_all_params. + _service.disable_retries() + self.test_list_audio_all_params() @responses.activate def test_list_audio_value_error(self): @@ -3206,7 +3466,7 @@ def test_list_audio_value_error(self): test_list_audio_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio') + url = preprocess_url('/v1/acoustic_customizations/testString/audio') mock_response = '{"total_minutes_of_audio": 22, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' responses.add(responses.GET, url, @@ -3227,30 +3487,27 @@ def test_list_audio_value_error(self): _service.list_audio(**req_copy) + def test_list_audio_value_error_with_retries(self): + # Enable retries and run test_list_audio_value_error. + _service.enable_retries() + self.test_list_audio_value_error() + + # Disable retries and run test_list_audio_value_error. + _service.disable_retries() + self.test_list_audio_value_error() class TestAddAudio(): """ Test Class for add_audio """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_add_audio_all_params(self): """ add_audio() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') responses.add(responses.POST, url, status=201) @@ -3283,6 +3540,14 @@ def test_add_audio_all_params(self): assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string # Validate body params + def test_add_audio_all_params_with_retries(self): + # Enable retries and run test_add_audio_all_params. + _service.enable_retries() + self.test_add_audio_all_params() + + # Disable retries and run test_add_audio_all_params. + _service.disable_retries() + self.test_add_audio_all_params() @responses.activate def test_add_audio_required_params(self): @@ -3290,7 +3555,7 @@ def test_add_audio_required_params(self): test_add_audio_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') responses.add(responses.POST, url, status=201) @@ -3313,6 +3578,14 @@ def test_add_audio_required_params(self): assert response.status_code == 201 # Validate body params + def test_add_audio_required_params_with_retries(self): + # Enable retries and run test_add_audio_required_params. + _service.enable_retries() + self.test_add_audio_required_params() + + # Disable retries and run test_add_audio_required_params. + _service.disable_retries() + self.test_add_audio_required_params() @responses.activate def test_add_audio_value_error(self): @@ -3320,7 +3593,7 @@ def test_add_audio_value_error(self): test_add_audio_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') responses.add(responses.POST, url, status=201) @@ -3342,30 +3615,27 @@ def test_add_audio_value_error(self): _service.add_audio(**req_copy) + def test_add_audio_value_error_with_retries(self): + # Enable retries and run test_add_audio_value_error. + _service.enable_retries() + self.test_add_audio_value_error() + + # Disable retries and run test_add_audio_value_error. + _service.disable_retries() + self.test_add_audio_value_error() class TestGetAudio(): """ Test Class for get_audio """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_audio_all_params(self): """ get_audio() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') mock_response = '{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok", "container": {"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' responses.add(responses.GET, url, @@ -3388,6 +3658,14 @@ def test_get_audio_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_audio_all_params_with_retries(self): + # Enable retries and run test_get_audio_all_params. + _service.enable_retries() + self.test_get_audio_all_params() + + # Disable retries and run test_get_audio_all_params. + _service.disable_retries() + self.test_get_audio_all_params() @responses.activate def test_get_audio_value_error(self): @@ -3395,7 +3673,7 @@ def test_get_audio_value_error(self): test_get_audio_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') mock_response = '{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok", "container": {"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' responses.add(responses.GET, url, @@ -3418,30 +3696,27 @@ def test_get_audio_value_error(self): _service.get_audio(**req_copy) + def test_get_audio_value_error_with_retries(self): + # Enable retries and run test_get_audio_value_error. + _service.enable_retries() + self.test_get_audio_value_error() + + # Disable retries and run test_get_audio_value_error. + _service.disable_retries() + self.test_get_audio_value_error() class TestDeleteAudio(): """ Test Class for delete_audio """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_audio_all_params(self): """ delete_audio() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') responses.add(responses.DELETE, url, status=200) @@ -3461,6 +3736,14 @@ def test_delete_audio_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_delete_audio_all_params_with_retries(self): + # Enable retries and run test_delete_audio_all_params. + _service.enable_retries() + self.test_delete_audio_all_params() + + # Disable retries and run test_delete_audio_all_params. + _service.disable_retries() + self.test_delete_audio_all_params() @responses.activate def test_delete_audio_value_error(self): @@ -3468,7 +3751,7 @@ def test_delete_audio_value_error(self): test_delete_audio_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/acoustic_customizations/testString/audio/testString') + url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') responses.add(responses.DELETE, url, status=200) @@ -3488,6 +3771,14 @@ def test_delete_audio_value_error(self): _service.delete_audio(**req_copy) + def test_delete_audio_value_error_with_retries(self): + # Enable retries and run test_delete_audio_value_error. + _service.enable_retries() + self.test_delete_audio_value_error() + + # Disable retries and run test_delete_audio_value_error. + _service.disable_retries() + self.test_delete_audio_value_error() # endregion ############################################################################## @@ -3504,24 +3795,13 @@ class TestDeleteUserData(): Test Class for delete_user_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_user_data_all_params(self): """ delete_user_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/user_data') + url = preprocess_url('/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -3543,6 +3823,14 @@ def test_delete_user_data_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string + def test_delete_user_data_all_params_with_retries(self): + # Enable retries and run test_delete_user_data_all_params. + _service.enable_retries() + self.test_delete_user_data_all_params() + + # Disable retries and run test_delete_user_data_all_params. + _service.disable_retries() + self.test_delete_user_data_all_params() @responses.activate def test_delete_user_data_value_error(self): @@ -3550,7 +3838,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/user_data') + url = preprocess_url('/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -3568,6 +3856,14 @@ def test_delete_user_data_value_error(self): _service.delete_user_data(**req_copy) + def test_delete_user_data_value_error_with_retries(self): + # Enable retries and run test_delete_user_data_value_error. + _service.enable_retries() + self.test_delete_user_data_value_error() + + # Disable retries and run test_delete_user_data_value_error. + _service.disable_retries() + self.test_delete_user_data_value_error() # endregion ############################################################################## @@ -4618,6 +4914,7 @@ def test_speech_model_serialization(self): supported_features_model = {} # SupportedFeatures supported_features_model['custom_language_model'] = True + supported_features_model['custom_acoustic_model'] = True supported_features_model['speaker_labels'] = True supported_features_model['low_latency'] = True @@ -4659,6 +4956,7 @@ def test_speech_models_serialization(self): supported_features_model = {} # SupportedFeatures supported_features_model['custom_language_model'] = True + supported_features_model['custom_acoustic_model'] = True supported_features_model['speaker_labels'] = True supported_features_model['low_latency'] = True @@ -4892,6 +5190,7 @@ def test_supported_features_serialization(self): # Construct a json representation of a SupportedFeatures model supported_features_model_json = {} supported_features_model_json['custom_language_model'] = True + supported_features_model_json['custom_acoustic_model'] = True supported_features_model_json['speaker_labels'] = True supported_features_model_json['low_latency'] = True diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index c8119130d..25ab220d2 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2021. +# (C) Copyright IBM Corp. 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -32,11 +32,38 @@ _service = TextToSpeechV1( authenticator=NoAuthAuthenticator() - ) +) _base_url = 'https://api.us-south.text-to-speech.watson.cloud.ibm.com' _service.set_service_url(_base_url) + +def preprocess_url(operation_path: str): + """ + Returns the request url associated with the specified operation path. + This will be base_url concatenated with a quoted version of operation_path. + The returned request URL is used to register the mock response so it needs + to match the request URL that is formed by the requests library. + """ + # First, unquote the path since it might have some quoted/escaped characters in it + # due to how the generator inserts the operation paths into the unit test code. + operation_path = urllib.parse.unquote(operation_path) + + # Next, quote the path using urllib so that we approximate what will + # happen during request processing. + operation_path = urllib.parse.quote(operation_path, safe='/') + + # Finally, form the request URL from the base URL and operation path. + request_url = _base_url + operation_path + + # If the request url does NOT end with a /, then just return it as-is. + # Otherwise, return a regular expression that matches one or more trailing /. + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + ############################################################################## # Start of Service: Voices ############################################################################## @@ -47,24 +74,13 @@ class TestListVoices(): Test Class for list_voices """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_voices_all_params(self): """ list_voices() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/voices') + url = preprocess_url('/v1/voices') mock_response = '{"voices": [{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}]}' responses.add(responses.GET, url, @@ -80,30 +96,27 @@ def test_list_voices_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_voices_all_params_with_retries(self): + # Enable retries and run test_list_voices_all_params. + _service.enable_retries() + self.test_list_voices_all_params() + + # Disable retries and run test_list_voices_all_params. + _service.disable_retries() + self.test_list_voices_all_params() class TestGetVoice(): """ Test Class for get_voice """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_voice_all_params(self): """ get_voice() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/voices/ar-AR_OmarVoice') + url = preprocess_url('/v1/voices/ar-AR_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, @@ -130,6 +143,14 @@ def test_get_voice_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'customization_id={}'.format(customization_id) in query_string + def test_get_voice_all_params_with_retries(self): + # Enable retries and run test_get_voice_all_params. + _service.enable_retries() + self.test_get_voice_all_params() + + # Disable retries and run test_get_voice_all_params. + _service.disable_retries() + self.test_get_voice_all_params() @responses.activate def test_get_voice_required_params(self): @@ -137,7 +158,7 @@ def test_get_voice_required_params(self): test_get_voice_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/voices/ar-AR_OmarVoice') + url = preprocess_url('/v1/voices/ar-AR_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, @@ -158,6 +179,14 @@ def test_get_voice_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_voice_required_params_with_retries(self): + # Enable retries and run test_get_voice_required_params. + _service.enable_retries() + self.test_get_voice_required_params() + + # Disable retries and run test_get_voice_required_params. + _service.disable_retries() + self.test_get_voice_required_params() @responses.activate def test_get_voice_value_error(self): @@ -165,7 +194,7 @@ def test_get_voice_value_error(self): test_get_voice_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/voices/ar-AR_OmarVoice') + url = preprocess_url('/v1/voices/ar-AR_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, @@ -186,6 +215,14 @@ def test_get_voice_value_error(self): _service.get_voice(**req_copy) + def test_get_voice_value_error_with_retries(self): + # Enable retries and run test_get_voice_value_error. + _service.enable_retries() + self.test_get_voice_value_error() + + # Disable retries and run test_get_voice_value_error. + _service.disable_retries() + self.test_get_voice_value_error() # endregion ############################################################################## @@ -202,24 +239,13 @@ class TestSynthesize(): Test Class for synthesize """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_synthesize_all_params(self): """ synthesize() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/synthesize') + url = preprocess_url('/v1/synthesize') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, @@ -254,6 +280,14 @@ def test_synthesize_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['text'] == 'testString' + def test_synthesize_all_params_with_retries(self): + # Enable retries and run test_synthesize_all_params. + _service.enable_retries() + self.test_synthesize_all_params() + + # Disable retries and run test_synthesize_all_params. + _service.disable_retries() + self.test_synthesize_all_params() @responses.activate def test_synthesize_required_params(self): @@ -261,7 +295,7 @@ def test_synthesize_required_params(self): test_synthesize_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/synthesize') + url = preprocess_url('/v1/synthesize') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, @@ -285,6 +319,14 @@ def test_synthesize_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['text'] == 'testString' + def test_synthesize_required_params_with_retries(self): + # Enable retries and run test_synthesize_required_params. + _service.enable_retries() + self.test_synthesize_required_params() + + # Disable retries and run test_synthesize_required_params. + _service.disable_retries() + self.test_synthesize_required_params() @responses.activate def test_synthesize_value_error(self): @@ -292,7 +334,7 @@ def test_synthesize_value_error(self): test_synthesize_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/synthesize') + url = preprocess_url('/v1/synthesize') mock_response = 'This is a mock binary response.' responses.add(responses.POST, url, @@ -313,6 +355,14 @@ def test_synthesize_value_error(self): _service.synthesize(**req_copy) + def test_synthesize_value_error_with_retries(self): + # Enable retries and run test_synthesize_value_error. + _service.enable_retries() + self.test_synthesize_value_error() + + # Disable retries and run test_synthesize_value_error. + _service.disable_retries() + self.test_synthesize_value_error() # endregion ############################################################################## @@ -329,24 +379,13 @@ class TestGetPronunciation(): Test Class for get_pronunciation """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_pronunciation_all_params(self): """ get_pronunciation() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/pronunciation') + url = preprocess_url('/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' responses.add(responses.GET, url, @@ -380,6 +419,14 @@ def test_get_pronunciation_all_params(self): assert 'format={}'.format(format) in query_string assert 'customization_id={}'.format(customization_id) in query_string + def test_get_pronunciation_all_params_with_retries(self): + # Enable retries and run test_get_pronunciation_all_params. + _service.enable_retries() + self.test_get_pronunciation_all_params() + + # Disable retries and run test_get_pronunciation_all_params. + _service.disable_retries() + self.test_get_pronunciation_all_params() @responses.activate def test_get_pronunciation_required_params(self): @@ -387,7 +434,7 @@ def test_get_pronunciation_required_params(self): test_get_pronunciation_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/pronunciation') + url = preprocess_url('/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' responses.add(responses.GET, url, @@ -412,6 +459,14 @@ def test_get_pronunciation_required_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'text={}'.format(text) in query_string + def test_get_pronunciation_required_params_with_retries(self): + # Enable retries and run test_get_pronunciation_required_params. + _service.enable_retries() + self.test_get_pronunciation_required_params() + + # Disable retries and run test_get_pronunciation_required_params. + _service.disable_retries() + self.test_get_pronunciation_required_params() @responses.activate def test_get_pronunciation_value_error(self): @@ -419,7 +474,7 @@ def test_get_pronunciation_value_error(self): test_get_pronunciation_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/pronunciation') + url = preprocess_url('/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' responses.add(responses.GET, url, @@ -440,6 +495,14 @@ def test_get_pronunciation_value_error(self): _service.get_pronunciation(**req_copy) + def test_get_pronunciation_value_error_with_retries(self): + # Enable retries and run test_get_pronunciation_value_error. + _service.enable_retries() + self.test_get_pronunciation_value_error() + + # Disable retries and run test_get_pronunciation_value_error. + _service.disable_retries() + self.test_get_pronunciation_value_error() # endregion ############################################################################## @@ -456,24 +519,13 @@ class TestCreateCustomModel(): Test Class for create_custom_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_custom_model_all_params(self): """ create_custom_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations') + url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' responses.add(responses.POST, url, @@ -503,6 +555,14 @@ def test_create_custom_model_all_params(self): assert req_body['language'] == 'en-US' assert req_body['description'] == 'testString' + def test_create_custom_model_all_params_with_retries(self): + # Enable retries and run test_create_custom_model_all_params. + _service.enable_retries() + self.test_create_custom_model_all_params() + + # Disable retries and run test_create_custom_model_all_params. + _service.disable_retries() + self.test_create_custom_model_all_params() @responses.activate def test_create_custom_model_value_error(self): @@ -510,7 +570,7 @@ def test_create_custom_model_value_error(self): test_create_custom_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations') + url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' responses.add(responses.POST, url, @@ -533,30 +593,27 @@ def test_create_custom_model_value_error(self): _service.create_custom_model(**req_copy) + def test_create_custom_model_value_error_with_retries(self): + # Enable retries and run test_create_custom_model_value_error. + _service.enable_retries() + self.test_create_custom_model_value_error() + + # Disable retries and run test_create_custom_model_value_error. + _service.disable_retries() + self.test_create_custom_model_value_error() class TestListCustomModels(): """ Test Class for list_custom_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_custom_models_all_params(self): """ list_custom_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations') + url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}]}' responses.add(responses.GET, url, @@ -581,6 +638,14 @@ def test_list_custom_models_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'language={}'.format(language) in query_string + def test_list_custom_models_all_params_with_retries(self): + # Enable retries and run test_list_custom_models_all_params. + _service.enable_retries() + self.test_list_custom_models_all_params() + + # Disable retries and run test_list_custom_models_all_params. + _service.disable_retries() + self.test_list_custom_models_all_params() @responses.activate def test_list_custom_models_required_params(self): @@ -588,7 +653,7 @@ def test_list_custom_models_required_params(self): test_list_custom_models_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations') + url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}]}' responses.add(responses.GET, url, @@ -604,30 +669,27 @@ def test_list_custom_models_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_custom_models_required_params_with_retries(self): + # Enable retries and run test_list_custom_models_required_params. + _service.enable_retries() + self.test_list_custom_models_required_params() + + # Disable retries and run test_list_custom_models_required_params. + _service.disable_retries() + self.test_list_custom_models_required_params() class TestUpdateCustomModel(): """ Test Class for update_custom_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_update_custom_model_all_params(self): """ update_custom_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString') + url = preprocess_url('/v1/customizations/testString') responses.add(responses.POST, url, status=200) @@ -662,6 +724,14 @@ def test_update_custom_model_all_params(self): assert req_body['description'] == 'testString' assert req_body['words'] == [word_model] + def test_update_custom_model_all_params_with_retries(self): + # Enable retries and run test_update_custom_model_all_params. + _service.enable_retries() + self.test_update_custom_model_all_params() + + # Disable retries and run test_update_custom_model_all_params. + _service.disable_retries() + self.test_update_custom_model_all_params() @responses.activate def test_update_custom_model_value_error(self): @@ -669,7 +739,7 @@ def test_update_custom_model_value_error(self): test_update_custom_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString') + url = preprocess_url('/v1/customizations/testString') responses.add(responses.POST, url, status=200) @@ -696,30 +766,27 @@ def test_update_custom_model_value_error(self): _service.update_custom_model(**req_copy) + def test_update_custom_model_value_error_with_retries(self): + # Enable retries and run test_update_custom_model_value_error. + _service.enable_retries() + self.test_update_custom_model_value_error() + + # Disable retries and run test_update_custom_model_value_error. + _service.disable_retries() + self.test_update_custom_model_value_error() class TestGetCustomModel(): """ Test Class for get_custom_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_custom_model_all_params(self): """ get_custom_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString') + url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' responses.add(responses.GET, url, @@ -740,6 +807,14 @@ def test_get_custom_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_custom_model_all_params_with_retries(self): + # Enable retries and run test_get_custom_model_all_params. + _service.enable_retries() + self.test_get_custom_model_all_params() + + # Disable retries and run test_get_custom_model_all_params. + _service.disable_retries() + self.test_get_custom_model_all_params() @responses.activate def test_get_custom_model_value_error(self): @@ -747,7 +822,7 @@ def test_get_custom_model_value_error(self): test_get_custom_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString') + url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' responses.add(responses.GET, url, @@ -768,30 +843,27 @@ def test_get_custom_model_value_error(self): _service.get_custom_model(**req_copy) + def test_get_custom_model_value_error_with_retries(self): + # Enable retries and run test_get_custom_model_value_error. + _service.enable_retries() + self.test_get_custom_model_value_error() + + # Disable retries and run test_get_custom_model_value_error. + _service.disable_retries() + self.test_get_custom_model_value_error() class TestDeleteCustomModel(): """ Test Class for delete_custom_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_custom_model_all_params(self): """ delete_custom_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString') + url = preprocess_url('/v1/customizations/testString') responses.add(responses.DELETE, url, status=204) @@ -809,6 +881,14 @@ def test_delete_custom_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_custom_model_all_params_with_retries(self): + # Enable retries and run test_delete_custom_model_all_params. + _service.enable_retries() + self.test_delete_custom_model_all_params() + + # Disable retries and run test_delete_custom_model_all_params. + _service.disable_retries() + self.test_delete_custom_model_all_params() @responses.activate def test_delete_custom_model_value_error(self): @@ -816,7 +896,7 @@ def test_delete_custom_model_value_error(self): test_delete_custom_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString') + url = preprocess_url('/v1/customizations/testString') responses.add(responses.DELETE, url, status=204) @@ -834,6 +914,14 @@ def test_delete_custom_model_value_error(self): _service.delete_custom_model(**req_copy) + def test_delete_custom_model_value_error_with_retries(self): + # Enable retries and run test_delete_custom_model_value_error. + _service.enable_retries() + self.test_delete_custom_model_value_error() + + # Disable retries and run test_delete_custom_model_value_error. + _service.disable_retries() + self.test_delete_custom_model_value_error() # endregion ############################################################################## @@ -850,24 +938,13 @@ class TestAddWords(): Test Class for add_words """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_add_words_all_params(self): """ add_words() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') + url = preprocess_url('/v1/customizations/testString/words') responses.add(responses.POST, url, status=200) @@ -896,6 +973,14 @@ def test_add_words_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['words'] == [word_model] + def test_add_words_all_params_with_retries(self): + # Enable retries and run test_add_words_all_params. + _service.enable_retries() + self.test_add_words_all_params() + + # Disable retries and run test_add_words_all_params. + _service.disable_retries() + self.test_add_words_all_params() @responses.activate def test_add_words_value_error(self): @@ -903,7 +988,7 @@ def test_add_words_value_error(self): test_add_words_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') + url = preprocess_url('/v1/customizations/testString/words') responses.add(responses.POST, url, status=200) @@ -929,30 +1014,27 @@ def test_add_words_value_error(self): _service.add_words(**req_copy) + def test_add_words_value_error_with_retries(self): + # Enable retries and run test_add_words_value_error. + _service.enable_retries() + self.test_add_words_value_error() + + # Disable retries and run test_add_words_value_error. + _service.disable_retries() + self.test_add_words_value_error() class TestListWords(): """ Test Class for list_words """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_words_all_params(self): """ list_words() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') + url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' responses.add(responses.GET, url, @@ -973,6 +1055,14 @@ def test_list_words_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_words_all_params_with_retries(self): + # Enable retries and run test_list_words_all_params. + _service.enable_retries() + self.test_list_words_all_params() + + # Disable retries and run test_list_words_all_params. + _service.disable_retries() + self.test_list_words_all_params() @responses.activate def test_list_words_value_error(self): @@ -980,7 +1070,7 @@ def test_list_words_value_error(self): test_list_words_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words') + url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' responses.add(responses.GET, url, @@ -1001,30 +1091,27 @@ def test_list_words_value_error(self): _service.list_words(**req_copy) + def test_list_words_value_error_with_retries(self): + # Enable retries and run test_list_words_value_error. + _service.enable_retries() + self.test_list_words_value_error() + + # Disable retries and run test_list_words_value_error. + _service.disable_retries() + self.test_list_words_value_error() class TestAddWord(): """ Test Class for add_word """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_add_word_all_params(self): """ add_word() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') responses.add(responses.PUT, url, status=200) @@ -1052,6 +1139,14 @@ def test_add_word_all_params(self): assert req_body['translation'] == 'testString' assert req_body['part_of_speech'] == 'Dosi' + def test_add_word_all_params_with_retries(self): + # Enable retries and run test_add_word_all_params. + _service.enable_retries() + self.test_add_word_all_params() + + # Disable retries and run test_add_word_all_params. + _service.disable_retries() + self.test_add_word_all_params() @responses.activate def test_add_word_value_error(self): @@ -1059,7 +1154,7 @@ def test_add_word_value_error(self): test_add_word_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') responses.add(responses.PUT, url, status=200) @@ -1082,30 +1177,27 @@ def test_add_word_value_error(self): _service.add_word(**req_copy) + def test_add_word_value_error_with_retries(self): + # Enable retries and run test_add_word_value_error. + _service.enable_retries() + self.test_add_word_value_error() + + # Disable retries and run test_add_word_value_error. + _service.disable_retries() + self.test_add_word_value_error() class TestGetWord(): """ Test Class for get_word """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_word_all_params(self): """ get_word() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') mock_response = '{"translation": "translation", "part_of_speech": "Dosi"}' responses.add(responses.GET, url, @@ -1128,6 +1220,14 @@ def test_get_word_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_word_all_params_with_retries(self): + # Enable retries and run test_get_word_all_params. + _service.enable_retries() + self.test_get_word_all_params() + + # Disable retries and run test_get_word_all_params. + _service.disable_retries() + self.test_get_word_all_params() @responses.activate def test_get_word_value_error(self): @@ -1135,7 +1235,7 @@ def test_get_word_value_error(self): test_get_word_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') mock_response = '{"translation": "translation", "part_of_speech": "Dosi"}' responses.add(responses.GET, url, @@ -1158,30 +1258,27 @@ def test_get_word_value_error(self): _service.get_word(**req_copy) + def test_get_word_value_error_with_retries(self): + # Enable retries and run test_get_word_value_error. + _service.enable_retries() + self.test_get_word_value_error() + + # Disable retries and run test_get_word_value_error. + _service.disable_retries() + self.test_get_word_value_error() class TestDeleteWord(): """ Test Class for delete_word """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_word_all_params(self): """ delete_word() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') responses.add(responses.DELETE, url, status=204) @@ -1201,6 +1298,14 @@ def test_delete_word_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_word_all_params_with_retries(self): + # Enable retries and run test_delete_word_all_params. + _service.enable_retries() + self.test_delete_word_all_params() + + # Disable retries and run test_delete_word_all_params. + _service.disable_retries() + self.test_delete_word_all_params() @responses.activate def test_delete_word_value_error(self): @@ -1208,7 +1313,7 @@ def test_delete_word_value_error(self): test_delete_word_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/words/testString') + url = preprocess_url('/v1/customizations/testString/words/testString') responses.add(responses.DELETE, url, status=204) @@ -1228,6 +1333,14 @@ def test_delete_word_value_error(self): _service.delete_word(**req_copy) + def test_delete_word_value_error_with_retries(self): + # Enable retries and run test_delete_word_value_error. + _service.enable_retries() + self.test_delete_word_value_error() + + # Disable retries and run test_delete_word_value_error. + _service.disable_retries() + self.test_delete_word_value_error() # endregion ############################################################################## @@ -1244,24 +1357,13 @@ class TestListCustomPrompts(): Test Class for list_custom_prompts """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_custom_prompts_all_params(self): """ list_custom_prompts() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts') + url = preprocess_url('/v1/customizations/testString/prompts') mock_response = '{"prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' responses.add(responses.GET, url, @@ -1282,6 +1384,14 @@ def test_list_custom_prompts_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_custom_prompts_all_params_with_retries(self): + # Enable retries and run test_list_custom_prompts_all_params. + _service.enable_retries() + self.test_list_custom_prompts_all_params() + + # Disable retries and run test_list_custom_prompts_all_params. + _service.disable_retries() + self.test_list_custom_prompts_all_params() @responses.activate def test_list_custom_prompts_value_error(self): @@ -1289,7 +1399,7 @@ def test_list_custom_prompts_value_error(self): test_list_custom_prompts_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts') + url = preprocess_url('/v1/customizations/testString/prompts') mock_response = '{"prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' responses.add(responses.GET, url, @@ -1310,30 +1420,27 @@ def test_list_custom_prompts_value_error(self): _service.list_custom_prompts(**req_copy) + def test_list_custom_prompts_value_error_with_retries(self): + # Enable retries and run test_list_custom_prompts_value_error. + _service.enable_retries() + self.test_list_custom_prompts_value_error() + + # Disable retries and run test_list_custom_prompts_value_error. + _service.disable_retries() + self.test_list_custom_prompts_value_error() class TestAddCustomPrompt(): """ Test Class for add_custom_prompt """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_add_custom_prompt_all_params(self): """ add_custom_prompt() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' responses.add(responses.POST, url, @@ -1365,6 +1472,14 @@ def test_add_custom_prompt_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_add_custom_prompt_all_params_with_retries(self): + # Enable retries and run test_add_custom_prompt_all_params. + _service.enable_retries() + self.test_add_custom_prompt_all_params() + + # Disable retries and run test_add_custom_prompt_all_params. + _service.disable_retries() + self.test_add_custom_prompt_all_params() @responses.activate def test_add_custom_prompt_value_error(self): @@ -1372,7 +1487,7 @@ def test_add_custom_prompt_value_error(self): test_add_custom_prompt_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' responses.add(responses.POST, url, @@ -1404,30 +1519,27 @@ def test_add_custom_prompt_value_error(self): _service.add_custom_prompt(**req_copy) + def test_add_custom_prompt_value_error_with_retries(self): + # Enable retries and run test_add_custom_prompt_value_error. + _service.enable_retries() + self.test_add_custom_prompt_value_error() + + # Disable retries and run test_add_custom_prompt_value_error. + _service.disable_retries() + self.test_add_custom_prompt_value_error() class TestGetCustomPrompt(): """ Test Class for get_custom_prompt """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_custom_prompt_all_params(self): """ get_custom_prompt() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' responses.add(responses.GET, url, @@ -1450,6 +1562,14 @@ def test_get_custom_prompt_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_custom_prompt_all_params_with_retries(self): + # Enable retries and run test_get_custom_prompt_all_params. + _service.enable_retries() + self.test_get_custom_prompt_all_params() + + # Disable retries and run test_get_custom_prompt_all_params. + _service.disable_retries() + self.test_get_custom_prompt_all_params() @responses.activate def test_get_custom_prompt_value_error(self): @@ -1457,7 +1577,7 @@ def test_get_custom_prompt_value_error(self): test_get_custom_prompt_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' responses.add(responses.GET, url, @@ -1480,30 +1600,27 @@ def test_get_custom_prompt_value_error(self): _service.get_custom_prompt(**req_copy) + def test_get_custom_prompt_value_error_with_retries(self): + # Enable retries and run test_get_custom_prompt_value_error. + _service.enable_retries() + self.test_get_custom_prompt_value_error() + + # Disable retries and run test_get_custom_prompt_value_error. + _service.disable_retries() + self.test_get_custom_prompt_value_error() class TestDeleteCustomPrompt(): """ Test Class for delete_custom_prompt """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_custom_prompt_all_params(self): """ delete_custom_prompt() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + url = preprocess_url('/v1/customizations/testString/prompts/testString') responses.add(responses.DELETE, url, status=204) @@ -1523,6 +1640,14 @@ def test_delete_custom_prompt_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_custom_prompt_all_params_with_retries(self): + # Enable retries and run test_delete_custom_prompt_all_params. + _service.enable_retries() + self.test_delete_custom_prompt_all_params() + + # Disable retries and run test_delete_custom_prompt_all_params. + _service.disable_retries() + self.test_delete_custom_prompt_all_params() @responses.activate def test_delete_custom_prompt_value_error(self): @@ -1530,7 +1655,7 @@ def test_delete_custom_prompt_value_error(self): test_delete_custom_prompt_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/customizations/testString/prompts/testString') + url = preprocess_url('/v1/customizations/testString/prompts/testString') responses.add(responses.DELETE, url, status=204) @@ -1550,6 +1675,14 @@ def test_delete_custom_prompt_value_error(self): _service.delete_custom_prompt(**req_copy) + def test_delete_custom_prompt_value_error_with_retries(self): + # Enable retries and run test_delete_custom_prompt_value_error. + _service.enable_retries() + self.test_delete_custom_prompt_value_error() + + # Disable retries and run test_delete_custom_prompt_value_error. + _service.disable_retries() + self.test_delete_custom_prompt_value_error() # endregion ############################################################################## @@ -1566,24 +1699,13 @@ class TestListSpeakerModels(): Test Class for list_speaker_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_list_speaker_models_all_params(self): """ list_speaker_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/speakers') + url = preprocess_url('/v1/speakers') mock_response = '{"speakers": [{"speaker_id": "speaker_id", "name": "name"}]}' responses.add(responses.GET, url, @@ -1599,30 +1721,27 @@ def test_list_speaker_models_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_speaker_models_all_params_with_retries(self): + # Enable retries and run test_list_speaker_models_all_params. + _service.enable_retries() + self.test_list_speaker_models_all_params() + + # Disable retries and run test_list_speaker_models_all_params. + _service.disable_retries() + self.test_list_speaker_models_all_params() class TestCreateSpeakerModel(): """ Test Class for create_speaker_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_create_speaker_model_all_params(self): """ create_speaker_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/speakers') + url = preprocess_url('/v1/speakers') mock_response = '{"speaker_id": "speaker_id"}' responses.add(responses.POST, url, @@ -1651,6 +1770,14 @@ def test_create_speaker_model_all_params(self): # Validate body params assert responses.calls[0].request.body == audio + def test_create_speaker_model_all_params_with_retries(self): + # Enable retries and run test_create_speaker_model_all_params. + _service.enable_retries() + self.test_create_speaker_model_all_params() + + # Disable retries and run test_create_speaker_model_all_params. + _service.disable_retries() + self.test_create_speaker_model_all_params() @responses.activate def test_create_speaker_model_value_error(self): @@ -1658,7 +1785,7 @@ def test_create_speaker_model_value_error(self): test_create_speaker_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/speakers') + url = preprocess_url('/v1/speakers') mock_response = '{"speaker_id": "speaker_id"}' responses.add(responses.POST, url, @@ -1681,30 +1808,27 @@ def test_create_speaker_model_value_error(self): _service.create_speaker_model(**req_copy) + def test_create_speaker_model_value_error_with_retries(self): + # Enable retries and run test_create_speaker_model_value_error. + _service.enable_retries() + self.test_create_speaker_model_value_error() + + # Disable retries and run test_create_speaker_model_value_error. + _service.disable_retries() + self.test_create_speaker_model_value_error() class TestGetSpeakerModel(): """ Test Class for get_speaker_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_speaker_model_all_params(self): """ get_speaker_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/speakers/testString') + url = preprocess_url('/v1/speakers/testString') mock_response = '{"customizations": [{"customization_id": "customization_id", "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error"}]}]}' responses.add(responses.GET, url, @@ -1725,6 +1849,14 @@ def test_get_speaker_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_speaker_model_all_params_with_retries(self): + # Enable retries and run test_get_speaker_model_all_params. + _service.enable_retries() + self.test_get_speaker_model_all_params() + + # Disable retries and run test_get_speaker_model_all_params. + _service.disable_retries() + self.test_get_speaker_model_all_params() @responses.activate def test_get_speaker_model_value_error(self): @@ -1732,7 +1864,7 @@ def test_get_speaker_model_value_error(self): test_get_speaker_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/speakers/testString') + url = preprocess_url('/v1/speakers/testString') mock_response = '{"customizations": [{"customization_id": "customization_id", "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error"}]}]}' responses.add(responses.GET, url, @@ -1753,30 +1885,27 @@ def test_get_speaker_model_value_error(self): _service.get_speaker_model(**req_copy) + def test_get_speaker_model_value_error_with_retries(self): + # Enable retries and run test_get_speaker_model_value_error. + _service.enable_retries() + self.test_get_speaker_model_value_error() + + # Disable retries and run test_get_speaker_model_value_error. + _service.disable_retries() + self.test_get_speaker_model_value_error() class TestDeleteSpeakerModel(): """ Test Class for delete_speaker_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_speaker_model_all_params(self): """ delete_speaker_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/speakers/testString') + url = preprocess_url('/v1/speakers/testString') responses.add(responses.DELETE, url, status=204) @@ -1794,6 +1923,14 @@ def test_delete_speaker_model_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_speaker_model_all_params_with_retries(self): + # Enable retries and run test_delete_speaker_model_all_params. + _service.enable_retries() + self.test_delete_speaker_model_all_params() + + # Disable retries and run test_delete_speaker_model_all_params. + _service.disable_retries() + self.test_delete_speaker_model_all_params() @responses.activate def test_delete_speaker_model_value_error(self): @@ -1801,7 +1938,7 @@ def test_delete_speaker_model_value_error(self): test_delete_speaker_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/speakers/testString') + url = preprocess_url('/v1/speakers/testString') responses.add(responses.DELETE, url, status=204) @@ -1819,6 +1956,14 @@ def test_delete_speaker_model_value_error(self): _service.delete_speaker_model(**req_copy) + def test_delete_speaker_model_value_error_with_retries(self): + # Enable retries and run test_delete_speaker_model_value_error. + _service.enable_retries() + self.test_delete_speaker_model_value_error() + + # Disable retries and run test_delete_speaker_model_value_error. + _service.disable_retries() + self.test_delete_speaker_model_value_error() # endregion ############################################################################## @@ -1835,24 +1980,13 @@ class TestDeleteUserData(): Test Class for delete_user_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_user_data_all_params(self): """ delete_user_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/user_data') + url = preprocess_url('/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -1874,6 +2008,14 @@ def test_delete_user_data_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string + def test_delete_user_data_all_params_with_retries(self): + # Enable retries and run test_delete_user_data_all_params. + _service.enable_retries() + self.test_delete_user_data_all_params() + + # Disable retries and run test_delete_user_data_all_params. + _service.disable_retries() + self.test_delete_user_data_all_params() @responses.activate def test_delete_user_data_value_error(self): @@ -1881,7 +2023,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v1/user_data') + url = preprocess_url('/v1/user_data') responses.add(responses.DELETE, url, status=200) @@ -1899,6 +2041,14 @@ def test_delete_user_data_value_error(self): _service.delete_user_data(**req_copy) + def test_delete_user_data_value_error_with_retries(self): + # Enable retries and run test_delete_user_data_value_error. + _service.enable_retries() + self.test_delete_user_data_value_error() + + # Disable retries and run test_delete_user_data_value_error. + _service.disable_retries() + self.test_delete_user_data_value_error() # endregion ############################################################################## diff --git a/test/unit/test_tone_analyzer_v3.py b/test/unit/test_tone_analyzer_v3.py deleted file mode 100755 index 1a97b5441..000000000 --- a/test/unit/test_tone_analyzer_v3.py +++ /dev/null @@ -1,698 +0,0 @@ -# -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2021. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Unit Tests for ToneAnalyzerV3 -""" - -from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator -import inspect -import json -import pytest -import re -import requests -import responses -import urllib -from ibm_watson.tone_analyzer_v3 import * - -version = 'testString' - -_service = ToneAnalyzerV3( - authenticator=NoAuthAuthenticator(), - version=version - ) - -_base_url = 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com' -_service.set_service_url(_base_url) - -############################################################################## -# Start of Service: Methods -############################################################################## -# region - -class TestTone(): - """ - Test Class for tone - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_tone_all_params(self): - """ - tone() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/tone') - mock_response = '{"document_tone": {"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "warning": "warning"}, "sentences_tone": [{"sentence_id": 11, "text": "text", "tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "input_from": 10, "input_to": 8}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ToneInput model - tone_input_model = {} - tone_input_model['text'] = 'testString' - - # Set up parameter values - tone_input = tone_input_model - content_type = 'application/json' - sentences = True - tones = ['emotion'] - content_language = 'en' - accept_language = 'en' - - # Invoke method - response = _service.tone( - tone_input, - content_type=content_type, - sentences=sentences, - tones=tones, - content_language=content_language, - accept_language=accept_language, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'sentences={}'.format('true' if sentences else 'false') in query_string - assert 'tones={}'.format(','.join(tones)) in query_string - # Validate body params - - - @responses.activate - def test_tone_required_params(self): - """ - test_tone_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/tone') - mock_response = '{"document_tone": {"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "warning": "warning"}, "sentences_tone": [{"sentence_id": 11, "text": "text", "tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "input_from": 10, "input_to": 8}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ToneInput model - tone_input_model = {} - tone_input_model['text'] = 'testString' - - # Set up parameter values - tone_input = tone_input_model - - # Invoke method - response = _service.tone( - tone_input, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - - - @responses.activate - def test_tone_value_error(self): - """ - test_tone_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/tone') - mock_response = '{"document_tone": {"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "warning": "warning"}, "sentences_tone": [{"sentence_id": 11, "text": "text", "tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "tone_categories": [{"tones": [{"score": 5, "tone_id": "tone_id", "tone_name": "tone_name"}], "category_id": "category_id", "category_name": "category_name"}], "input_from": 10, "input_to": 8}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ToneInput model - tone_input_model = {} - tone_input_model['text'] = 'testString' - - # Set up parameter values - tone_input = tone_input_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "tone_input": tone_input, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.tone(**req_copy) - - - -class TestToneChat(): - """ - Test Class for tone_chat - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_tone_chat_all_params(self): - """ - tone_chat() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/tone_chat') - mock_response = '{"utterances_tone": [{"utterance_id": 12, "utterance_text": "utterance_text", "tones": [{"score": 5, "tone_id": "excited", "tone_name": "tone_name"}], "error": "error"}], "warning": "warning"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a Utterance model - utterance_model = {} - utterance_model['text'] = 'testString' - utterance_model['user'] = 'testString' - - # Set up parameter values - utterances = [utterance_model] - content_language = 'en' - accept_language = 'en' - - # Invoke method - response = _service.tone_chat( - utterances, - content_language=content_language, - accept_language=accept_language, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['utterances'] == [utterance_model] - - - @responses.activate - def test_tone_chat_required_params(self): - """ - test_tone_chat_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/tone_chat') - mock_response = '{"utterances_tone": [{"utterance_id": 12, "utterance_text": "utterance_text", "tones": [{"score": 5, "tone_id": "excited", "tone_name": "tone_name"}], "error": "error"}], "warning": "warning"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a Utterance model - utterance_model = {} - utterance_model['text'] = 'testString' - utterance_model['user'] = 'testString' - - # Set up parameter values - utterances = [utterance_model] - - # Invoke method - response = _service.tone_chat( - utterances, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['utterances'] == [utterance_model] - - - @responses.activate - def test_tone_chat_value_error(self): - """ - test_tone_chat_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/tone_chat') - mock_response = '{"utterances_tone": [{"utterance_id": 12, "utterance_text": "utterance_text", "tones": [{"score": 5, "tone_id": "excited", "tone_name": "tone_name"}], "error": "error"}], "warning": "warning"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a Utterance model - utterance_model = {} - utterance_model['text'] = 'testString' - utterance_model['user'] = 'testString' - - # Set up parameter values - utterances = [utterance_model] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "utterances": utterances, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.tone_chat(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Methods -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region -class TestModel_DocumentAnalysis(): - """ - Test Class for DocumentAnalysis - """ - - def test_document_analysis_serialization(self): - """ - Test serialization/deserialization for DocumentAnalysis - """ - - # Construct dict forms of any model objects needed in order to build this model. - - tone_score_model = {} # ToneScore - tone_score_model['score'] = 72.5 - tone_score_model['tone_id'] = 'testString' - tone_score_model['tone_name'] = 'testString' - - tone_category_model = {} # ToneCategory - tone_category_model['tones'] = [tone_score_model] - tone_category_model['category_id'] = 'testString' - tone_category_model['category_name'] = 'testString' - - # Construct a json representation of a DocumentAnalysis model - document_analysis_model_json = {} - document_analysis_model_json['tones'] = [tone_score_model] - document_analysis_model_json['tone_categories'] = [tone_category_model] - document_analysis_model_json['warning'] = 'testString' - - # Construct a model instance of DocumentAnalysis by calling from_dict on the json representation - document_analysis_model = DocumentAnalysis.from_dict(document_analysis_model_json) - assert document_analysis_model != False - - # Construct a model instance of DocumentAnalysis by calling from_dict on the json representation - document_analysis_model_dict = DocumentAnalysis.from_dict(document_analysis_model_json).__dict__ - document_analysis_model2 = DocumentAnalysis(**document_analysis_model_dict) - - # Verify the model instances are equivalent - assert document_analysis_model == document_analysis_model2 - - # Convert model instance back to dict and verify no loss of data - document_analysis_model_json2 = document_analysis_model.to_dict() - assert document_analysis_model_json2 == document_analysis_model_json - -class TestModel_SentenceAnalysis(): - """ - Test Class for SentenceAnalysis - """ - - def test_sentence_analysis_serialization(self): - """ - Test serialization/deserialization for SentenceAnalysis - """ - - # Construct dict forms of any model objects needed in order to build this model. - - tone_score_model = {} # ToneScore - tone_score_model['score'] = 72.5 - tone_score_model['tone_id'] = 'testString' - tone_score_model['tone_name'] = 'testString' - - tone_category_model = {} # ToneCategory - tone_category_model['tones'] = [tone_score_model] - tone_category_model['category_id'] = 'testString' - tone_category_model['category_name'] = 'testString' - - # Construct a json representation of a SentenceAnalysis model - sentence_analysis_model_json = {} - sentence_analysis_model_json['sentence_id'] = 38 - sentence_analysis_model_json['text'] = 'testString' - sentence_analysis_model_json['tones'] = [tone_score_model] - sentence_analysis_model_json['tone_categories'] = [tone_category_model] - sentence_analysis_model_json['input_from'] = 38 - sentence_analysis_model_json['input_to'] = 38 - - # Construct a model instance of SentenceAnalysis by calling from_dict on the json representation - sentence_analysis_model = SentenceAnalysis.from_dict(sentence_analysis_model_json) - assert sentence_analysis_model != False - - # Construct a model instance of SentenceAnalysis by calling from_dict on the json representation - sentence_analysis_model_dict = SentenceAnalysis.from_dict(sentence_analysis_model_json).__dict__ - sentence_analysis_model2 = SentenceAnalysis(**sentence_analysis_model_dict) - - # Verify the model instances are equivalent - assert sentence_analysis_model == sentence_analysis_model2 - - # Convert model instance back to dict and verify no loss of data - sentence_analysis_model_json2 = sentence_analysis_model.to_dict() - assert sentence_analysis_model_json2 == sentence_analysis_model_json - -class TestModel_ToneAnalysis(): - """ - Test Class for ToneAnalysis - """ - - def test_tone_analysis_serialization(self): - """ - Test serialization/deserialization for ToneAnalysis - """ - - # Construct dict forms of any model objects needed in order to build this model. - - tone_score_model = {} # ToneScore - tone_score_model['score'] = 72.5 - tone_score_model['tone_id'] = 'testString' - tone_score_model['tone_name'] = 'testString' - - tone_category_model = {} # ToneCategory - tone_category_model['tones'] = [tone_score_model] - tone_category_model['category_id'] = 'testString' - tone_category_model['category_name'] = 'testString' - - document_analysis_model = {} # DocumentAnalysis - document_analysis_model['tones'] = [tone_score_model] - document_analysis_model['tone_categories'] = [tone_category_model] - document_analysis_model['warning'] = 'testString' - - sentence_analysis_model = {} # SentenceAnalysis - sentence_analysis_model['sentence_id'] = 38 - sentence_analysis_model['text'] = 'testString' - sentence_analysis_model['tones'] = [tone_score_model] - sentence_analysis_model['tone_categories'] = [tone_category_model] - sentence_analysis_model['input_from'] = 38 - sentence_analysis_model['input_to'] = 38 - - # Construct a json representation of a ToneAnalysis model - tone_analysis_model_json = {} - tone_analysis_model_json['document_tone'] = document_analysis_model - tone_analysis_model_json['sentences_tone'] = [sentence_analysis_model] - - # Construct a model instance of ToneAnalysis by calling from_dict on the json representation - tone_analysis_model = ToneAnalysis.from_dict(tone_analysis_model_json) - assert tone_analysis_model != False - - # Construct a model instance of ToneAnalysis by calling from_dict on the json representation - tone_analysis_model_dict = ToneAnalysis.from_dict(tone_analysis_model_json).__dict__ - tone_analysis_model2 = ToneAnalysis(**tone_analysis_model_dict) - - # Verify the model instances are equivalent - assert tone_analysis_model == tone_analysis_model2 - - # Convert model instance back to dict and verify no loss of data - tone_analysis_model_json2 = tone_analysis_model.to_dict() - assert tone_analysis_model_json2 == tone_analysis_model_json - -class TestModel_ToneCategory(): - """ - Test Class for ToneCategory - """ - - def test_tone_category_serialization(self): - """ - Test serialization/deserialization for ToneCategory - """ - - # Construct dict forms of any model objects needed in order to build this model. - - tone_score_model = {} # ToneScore - tone_score_model['score'] = 72.5 - tone_score_model['tone_id'] = 'testString' - tone_score_model['tone_name'] = 'testString' - - # Construct a json representation of a ToneCategory model - tone_category_model_json = {} - tone_category_model_json['tones'] = [tone_score_model] - tone_category_model_json['category_id'] = 'testString' - tone_category_model_json['category_name'] = 'testString' - - # Construct a model instance of ToneCategory by calling from_dict on the json representation - tone_category_model = ToneCategory.from_dict(tone_category_model_json) - assert tone_category_model != False - - # Construct a model instance of ToneCategory by calling from_dict on the json representation - tone_category_model_dict = ToneCategory.from_dict(tone_category_model_json).__dict__ - tone_category_model2 = ToneCategory(**tone_category_model_dict) - - # Verify the model instances are equivalent - assert tone_category_model == tone_category_model2 - - # Convert model instance back to dict and verify no loss of data - tone_category_model_json2 = tone_category_model.to_dict() - assert tone_category_model_json2 == tone_category_model_json - -class TestModel_ToneChatScore(): - """ - Test Class for ToneChatScore - """ - - def test_tone_chat_score_serialization(self): - """ - Test serialization/deserialization for ToneChatScore - """ - - # Construct a json representation of a ToneChatScore model - tone_chat_score_model_json = {} - tone_chat_score_model_json['score'] = 72.5 - tone_chat_score_model_json['tone_id'] = 'excited' - tone_chat_score_model_json['tone_name'] = 'testString' - - # Construct a model instance of ToneChatScore by calling from_dict on the json representation - tone_chat_score_model = ToneChatScore.from_dict(tone_chat_score_model_json) - assert tone_chat_score_model != False - - # Construct a model instance of ToneChatScore by calling from_dict on the json representation - tone_chat_score_model_dict = ToneChatScore.from_dict(tone_chat_score_model_json).__dict__ - tone_chat_score_model2 = ToneChatScore(**tone_chat_score_model_dict) - - # Verify the model instances are equivalent - assert tone_chat_score_model == tone_chat_score_model2 - - # Convert model instance back to dict and verify no loss of data - tone_chat_score_model_json2 = tone_chat_score_model.to_dict() - assert tone_chat_score_model_json2 == tone_chat_score_model_json - -class TestModel_ToneInput(): - """ - Test Class for ToneInput - """ - - def test_tone_input_serialization(self): - """ - Test serialization/deserialization for ToneInput - """ - - # Construct a json representation of a ToneInput model - tone_input_model_json = {} - tone_input_model_json['text'] = 'testString' - - # Construct a model instance of ToneInput by calling from_dict on the json representation - tone_input_model = ToneInput.from_dict(tone_input_model_json) - assert tone_input_model != False - - # Construct a model instance of ToneInput by calling from_dict on the json representation - tone_input_model_dict = ToneInput.from_dict(tone_input_model_json).__dict__ - tone_input_model2 = ToneInput(**tone_input_model_dict) - - # Verify the model instances are equivalent - assert tone_input_model == tone_input_model2 - - # Convert model instance back to dict and verify no loss of data - tone_input_model_json2 = tone_input_model.to_dict() - assert tone_input_model_json2 == tone_input_model_json - -class TestModel_ToneScore(): - """ - Test Class for ToneScore - """ - - def test_tone_score_serialization(self): - """ - Test serialization/deserialization for ToneScore - """ - - # Construct a json representation of a ToneScore model - tone_score_model_json = {} - tone_score_model_json['score'] = 72.5 - tone_score_model_json['tone_id'] = 'testString' - tone_score_model_json['tone_name'] = 'testString' - - # Construct a model instance of ToneScore by calling from_dict on the json representation - tone_score_model = ToneScore.from_dict(tone_score_model_json) - assert tone_score_model != False - - # Construct a model instance of ToneScore by calling from_dict on the json representation - tone_score_model_dict = ToneScore.from_dict(tone_score_model_json).__dict__ - tone_score_model2 = ToneScore(**tone_score_model_dict) - - # Verify the model instances are equivalent - assert tone_score_model == tone_score_model2 - - # Convert model instance back to dict and verify no loss of data - tone_score_model_json2 = tone_score_model.to_dict() - assert tone_score_model_json2 == tone_score_model_json - -class TestModel_Utterance(): - """ - Test Class for Utterance - """ - - def test_utterance_serialization(self): - """ - Test serialization/deserialization for Utterance - """ - - # Construct a json representation of a Utterance model - utterance_model_json = {} - utterance_model_json['text'] = 'testString' - utterance_model_json['user'] = 'testString' - - # Construct a model instance of Utterance by calling from_dict on the json representation - utterance_model = Utterance.from_dict(utterance_model_json) - assert utterance_model != False - - # Construct a model instance of Utterance by calling from_dict on the json representation - utterance_model_dict = Utterance.from_dict(utterance_model_json).__dict__ - utterance_model2 = Utterance(**utterance_model_dict) - - # Verify the model instances are equivalent - assert utterance_model == utterance_model2 - - # Convert model instance back to dict and verify no loss of data - utterance_model_json2 = utterance_model.to_dict() - assert utterance_model_json2 == utterance_model_json - -class TestModel_UtteranceAnalyses(): - """ - Test Class for UtteranceAnalyses - """ - - def test_utterance_analyses_serialization(self): - """ - Test serialization/deserialization for UtteranceAnalyses - """ - - # Construct dict forms of any model objects needed in order to build this model. - - tone_chat_score_model = {} # ToneChatScore - tone_chat_score_model['score'] = 72.5 - tone_chat_score_model['tone_id'] = 'excited' - tone_chat_score_model['tone_name'] = 'testString' - - utterance_analysis_model = {} # UtteranceAnalysis - utterance_analysis_model['utterance_id'] = 38 - utterance_analysis_model['utterance_text'] = 'testString' - utterance_analysis_model['tones'] = [tone_chat_score_model] - utterance_analysis_model['error'] = 'testString' - - # Construct a json representation of a UtteranceAnalyses model - utterance_analyses_model_json = {} - utterance_analyses_model_json['utterances_tone'] = [utterance_analysis_model] - utterance_analyses_model_json['warning'] = 'testString' - - # Construct a model instance of UtteranceAnalyses by calling from_dict on the json representation - utterance_analyses_model = UtteranceAnalyses.from_dict(utterance_analyses_model_json) - assert utterance_analyses_model != False - - # Construct a model instance of UtteranceAnalyses by calling from_dict on the json representation - utterance_analyses_model_dict = UtteranceAnalyses.from_dict(utterance_analyses_model_json).__dict__ - utterance_analyses_model2 = UtteranceAnalyses(**utterance_analyses_model_dict) - - # Verify the model instances are equivalent - assert utterance_analyses_model == utterance_analyses_model2 - - # Convert model instance back to dict and verify no loss of data - utterance_analyses_model_json2 = utterance_analyses_model.to_dict() - assert utterance_analyses_model_json2 == utterance_analyses_model_json - -class TestModel_UtteranceAnalysis(): - """ - Test Class for UtteranceAnalysis - """ - - def test_utterance_analysis_serialization(self): - """ - Test serialization/deserialization for UtteranceAnalysis - """ - - # Construct dict forms of any model objects needed in order to build this model. - - tone_chat_score_model = {} # ToneChatScore - tone_chat_score_model['score'] = 72.5 - tone_chat_score_model['tone_id'] = 'excited' - tone_chat_score_model['tone_name'] = 'testString' - - # Construct a json representation of a UtteranceAnalysis model - utterance_analysis_model_json = {} - utterance_analysis_model_json['utterance_id'] = 38 - utterance_analysis_model_json['utterance_text'] = 'testString' - utterance_analysis_model_json['tones'] = [tone_chat_score_model] - utterance_analysis_model_json['error'] = 'testString' - - # Construct a model instance of UtteranceAnalysis by calling from_dict on the json representation - utterance_analysis_model = UtteranceAnalysis.from_dict(utterance_analysis_model_json) - assert utterance_analysis_model != False - - # Construct a model instance of UtteranceAnalysis by calling from_dict on the json representation - utterance_analysis_model_dict = UtteranceAnalysis.from_dict(utterance_analysis_model_json).__dict__ - utterance_analysis_model2 = UtteranceAnalysis(**utterance_analysis_model_dict) - - # Verify the model instances are equivalent - assert utterance_analysis_model == utterance_analysis_model2 - - # Convert model instance back to dict and verify no loss of data - utterance_analysis_model_json2 = utterance_analysis_model.to_dict() - assert utterance_analysis_model_json2 == utterance_analysis_model_json - - -# endregion -############################################################################## -# End of Model Tests -############################################################################## diff --git a/test/unit/test_visual_recognition_v3.py b/test/unit/test_visual_recognition_v3.py deleted file mode 100644 index 327eb930d..000000000 --- a/test/unit/test_visual_recognition_v3.py +++ /dev/null @@ -1,1147 +0,0 @@ -# -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2021. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Unit Tests for VisualRecognitionV3 -""" - -from datetime import datetime, timezone -from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime -import inspect -import io -import json -import pytest -import re -import requests -import responses -import tempfile -import urllib -from ibm_watson.visual_recognition_v3 import * - -version = 'testString' - -_service = VisualRecognitionV3( - authenticator=NoAuthAuthenticator(), - version=version - ) - -_base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' -_service.set_service_url(_base_url) - -############################################################################## -# Start of Service: General -############################################################################## -# region - -class TestClassify(): - """ - Test Class for classify - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_classify_all_params(self): - """ - classify() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classify') - mock_response = '{"custom_classes": 14, "images_processed": 16, "images": [{"source_url": "source_url", "resolved_url": "resolved_url", "image": "image", "error": {"code": 4, "description": "description", "error_id": "error_id"}, "classifiers": [{"name": "name", "classifier_id": "classifier_id", "classes": [{"class": "class_", "score": 0, "type_hierarchy": "type_hierarchy"}]}]}], "warnings": [{"warning_id": "warning_id", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - images_file = io.BytesIO(b'This is a mock file.').getvalue() - images_filename = 'testString' - images_file_content_type = 'testString' - url = 'testString' - threshold = 72.5 - owners = ['testString'] - classifier_ids = ['testString'] - accept_language = 'en' - - # Invoke method - response = _service.classify( - images_file=images_file, - images_filename=images_filename, - images_file_content_type=images_file_content_type, - url=url, - threshold=threshold, - owners=owners, - classifier_ids=classifier_ids, - accept_language=accept_language, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_classify_required_params(self): - """ - test_classify_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classify') - mock_response = '{"custom_classes": 14, "images_processed": 16, "images": [{"source_url": "source_url", "resolved_url": "resolved_url", "image": "image", "error": {"code": 4, "description": "description", "error_id": "error_id"}, "classifiers": [{"name": "name", "classifier_id": "classifier_id", "classes": [{"class": "class_", "score": 0, "type_hierarchy": "type_hierarchy"}]}]}], "warnings": [{"warning_id": "warning_id", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Invoke method - response = _service.classify() - - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_classify_value_error(self): - """ - test_classify_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classify') - mock_response = '{"custom_classes": 14, "images_processed": 16, "images": [{"source_url": "source_url", "resolved_url": "resolved_url", "image": "image", "error": {"code": 4, "description": "description", "error_id": "error_id"}, "classifiers": [{"name": "name", "classifier_id": "classifier_id", "classes": [{"class": "class_", "score": 0, "type_hierarchy": "type_hierarchy"}]}]}], "warnings": [{"warning_id": "warning_id", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.classify(**req_copy) - - - -# endregion -############################################################################## -# End of Service: General -############################################################################## - -############################################################################## -# Start of Service: Custom -############################################################################## -# region - -class TestCreateClassifier(): - """ - Test Class for create_classifier - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_create_classifier_all_params(self): - """ - create_classifier() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - name = 'testString' - positive_examples = { 'key': io.BytesIO(b'This is a mock file.').getvalue() } - negative_examples = io.BytesIO(b'This is a mock file.').getvalue() - negative_examples_filename = 'testString' - - # Invoke method - response = _service.create_classifier( - name, - positive_examples, - negative_examples=negative_examples, - negative_examples_filename=negative_examples_filename, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_create_classifier_required_params(self): - """ - test_create_classifier_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - name = 'testString' - positive_examples = { 'key': io.BytesIO(b'This is a mock file.').getvalue() } - - # Invoke method - response = _service.create_classifier( - name, - positive_examples, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_create_classifier_value_error(self): - """ - test_create_classifier_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - name = 'testString' - positive_examples = { 'key': io.BytesIO(b'This is a mock file.').getvalue() } - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "name": name, - "positive_examples": positive_examples, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_classifier(**req_copy) - - - -class TestListClassifiers(): - """ - Test Class for list_classifiers - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_list_classifiers_all_params(self): - """ - list_classifiers() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers') - mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - verbose = True - - # Invoke method - response = _service.list_classifiers( - verbose=verbose, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'verbose={}'.format('true' if verbose else 'false') in query_string - - - @responses.activate - def test_list_classifiers_required_params(self): - """ - test_list_classifiers_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers') - mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Invoke method - response = _service.list_classifiers() - - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_list_classifiers_value_error(self): - """ - test_list_classifiers_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers') - mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_classifiers(**req_copy) - - - -class TestGetClassifier(): - """ - Test Class for get_classifier - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_get_classifier_all_params(self): - """ - get_classifier() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers/testString') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Invoke method - response = _service.get_classifier( - classifier_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_get_classifier_value_error(self): - """ - test_get_classifier_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers/testString') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "classifier_id": classifier_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_classifier(**req_copy) - - - -class TestUpdateClassifier(): - """ - Test Class for update_classifier - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_update_classifier_all_params(self): - """ - update_classifier() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers/testString') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - classifier_id = 'testString' - positive_examples = { 'key': io.BytesIO(b'This is a mock file.').getvalue() } - negative_examples = io.BytesIO(b'This is a mock file.').getvalue() - negative_examples_filename = 'testString' - - # Invoke method - response = _service.update_classifier( - classifier_id, - positive_examples=positive_examples, - negative_examples=negative_examples, - negative_examples_filename=negative_examples_filename, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_update_classifier_required_params(self): - """ - test_update_classifier_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers/testString') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Invoke method - response = _service.update_classifier( - classifier_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_update_classifier_value_error(self): - """ - test_update_classifier_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers/testString') - mock_response = '{"classifier_id": "classifier_id", "name": "name", "owner": "owner", "status": "ready", "core_ml_enabled": false, "explanation": "explanation", "created": "2019-01-01T12:00:00.000Z", "classes": [{"class": "class_"}], "retrained": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "classifier_id": classifier_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_classifier(**req_copy) - - - -class TestDeleteClassifier(): - """ - Test Class for delete_classifier - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_delete_classifier_all_params(self): - """ - delete_classifier() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers/testString') - responses.add(responses.DELETE, - url, - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Invoke method - response = _service.delete_classifier( - classifier_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_delete_classifier_value_error(self): - """ - test_delete_classifier_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers/testString') - responses.add(responses.DELETE, - url, - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "classifier_id": classifier_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_classifier(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Custom -############################################################################## - -############################################################################## -# Start of Service: CoreML -############################################################################## -# region - -class TestGetCoreMlModel(): - """ - Test Class for get_core_ml_model - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_get_core_ml_model_all_params(self): - """ - get_core_ml_model() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers/testString/core_ml_model') - mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/octet-stream', - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Invoke method - response = _service.get_core_ml_model( - classifier_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_get_core_ml_model_value_error(self): - """ - test_get_core_ml_model_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/classifiers/testString/core_ml_model') - mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/octet-stream', - status=200) - - # Set up parameter values - classifier_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "classifier_id": classifier_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_core_ml_model(**req_copy) - - - -# endregion -############################################################################## -# End of Service: CoreML -############################################################################## - -############################################################################## -# Start of Service: UserData -############################################################################## -# region - -class TestDeleteUserData(): - """ - Test Class for delete_user_data - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_delete_user_data_all_params(self): - """ - delete_user_data() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/user_data') - responses.add(responses.DELETE, - url, - status=202) - - # Set up parameter values - customer_id = 'testString' - - # Invoke method - response = _service.delete_user_data( - customer_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'customer_id={}'.format(customer_id) in query_string - - - @responses.activate - def test_delete_user_data_value_error(self): - """ - test_delete_user_data_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v3/user_data') - responses.add(responses.DELETE, - url, - status=202) - - # Set up parameter values - customer_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "customer_id": customer_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_user_data(**req_copy) - - - -# endregion -############################################################################## -# End of Service: UserData -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region -class TestModel_Class(): - """ - Test Class for Class - """ - - def test_class_serialization(self): - """ - Test serialization/deserialization for Class - """ - - # Construct a json representation of a Class model - class_model_json = {} - class_model_json['class'] = 'testString' - - # Construct a model instance of Class by calling from_dict on the json representation - class_model = Class.from_dict(class_model_json) - assert class_model != False - - # Construct a model instance of Class by calling from_dict on the json representation - class_model_dict = Class.from_dict(class_model_json).__dict__ - class_model2 = Class(**class_model_dict) - - # Verify the model instances are equivalent - assert class_model == class_model2 - - # Convert model instance back to dict and verify no loss of data - class_model_json2 = class_model.to_dict() - assert class_model_json2 == class_model_json - -class TestModel_ClassResult(): - """ - Test Class for ClassResult - """ - - def test_class_result_serialization(self): - """ - Test serialization/deserialization for ClassResult - """ - - # Construct a json representation of a ClassResult model - class_result_model_json = {} - class_result_model_json['class'] = 'testString' - class_result_model_json['score'] = 0 - class_result_model_json['type_hierarchy'] = 'testString' - - # Construct a model instance of ClassResult by calling from_dict on the json representation - class_result_model = ClassResult.from_dict(class_result_model_json) - assert class_result_model != False - - # Construct a model instance of ClassResult by calling from_dict on the json representation - class_result_model_dict = ClassResult.from_dict(class_result_model_json).__dict__ - class_result_model2 = ClassResult(**class_result_model_dict) - - # Verify the model instances are equivalent - assert class_result_model == class_result_model2 - - # Convert model instance back to dict and verify no loss of data - class_result_model_json2 = class_result_model.to_dict() - assert class_result_model_json2 == class_result_model_json - -class TestModel_ClassifiedImage(): - """ - Test Class for ClassifiedImage - """ - - def test_classified_image_serialization(self): - """ - Test serialization/deserialization for ClassifiedImage - """ - - # Construct dict forms of any model objects needed in order to build this model. - - error_info_model = {} # ErrorInfo - error_info_model['code'] = 38 - error_info_model['description'] = 'testString' - error_info_model['error_id'] = 'testString' - - class_result_model = {} # ClassResult - class_result_model['class'] = 'testString' - class_result_model['score'] = 0 - class_result_model['type_hierarchy'] = 'testString' - - classifier_result_model = {} # ClassifierResult - classifier_result_model['name'] = 'testString' - classifier_result_model['classifier_id'] = 'testString' - classifier_result_model['classes'] = [class_result_model] - - # Construct a json representation of a ClassifiedImage model - classified_image_model_json = {} - classified_image_model_json['source_url'] = 'testString' - classified_image_model_json['resolved_url'] = 'testString' - classified_image_model_json['image'] = 'testString' - classified_image_model_json['error'] = error_info_model - classified_image_model_json['classifiers'] = [classifier_result_model] - - # Construct a model instance of ClassifiedImage by calling from_dict on the json representation - classified_image_model = ClassifiedImage.from_dict(classified_image_model_json) - assert classified_image_model != False - - # Construct a model instance of ClassifiedImage by calling from_dict on the json representation - classified_image_model_dict = ClassifiedImage.from_dict(classified_image_model_json).__dict__ - classified_image_model2 = ClassifiedImage(**classified_image_model_dict) - - # Verify the model instances are equivalent - assert classified_image_model == classified_image_model2 - - # Convert model instance back to dict and verify no loss of data - classified_image_model_json2 = classified_image_model.to_dict() - assert classified_image_model_json2 == classified_image_model_json - -class TestModel_ClassifiedImages(): - """ - Test Class for ClassifiedImages - """ - - def test_classified_images_serialization(self): - """ - Test serialization/deserialization for ClassifiedImages - """ - - # Construct dict forms of any model objects needed in order to build this model. - - error_info_model = {} # ErrorInfo - error_info_model['code'] = 38 - error_info_model['description'] = 'testString' - error_info_model['error_id'] = 'testString' - - class_result_model = {} # ClassResult - class_result_model['class'] = 'testString' - class_result_model['score'] = 0 - class_result_model['type_hierarchy'] = 'testString' - - classifier_result_model = {} # ClassifierResult - classifier_result_model['name'] = 'testString' - classifier_result_model['classifier_id'] = 'testString' - classifier_result_model['classes'] = [class_result_model] - - classified_image_model = {} # ClassifiedImage - classified_image_model['source_url'] = 'testString' - classified_image_model['resolved_url'] = 'testString' - classified_image_model['image'] = 'testString' - classified_image_model['error'] = error_info_model - classified_image_model['classifiers'] = [classifier_result_model] - - warning_info_model = {} # WarningInfo - warning_info_model['warning_id'] = 'testString' - warning_info_model['description'] = 'testString' - - # Construct a json representation of a ClassifiedImages model - classified_images_model_json = {} - classified_images_model_json['custom_classes'] = 38 - classified_images_model_json['images_processed'] = 38 - classified_images_model_json['images'] = [classified_image_model] - classified_images_model_json['warnings'] = [warning_info_model] - - # Construct a model instance of ClassifiedImages by calling from_dict on the json representation - classified_images_model = ClassifiedImages.from_dict(classified_images_model_json) - assert classified_images_model != False - - # Construct a model instance of ClassifiedImages by calling from_dict on the json representation - classified_images_model_dict = ClassifiedImages.from_dict(classified_images_model_json).__dict__ - classified_images_model2 = ClassifiedImages(**classified_images_model_dict) - - # Verify the model instances are equivalent - assert classified_images_model == classified_images_model2 - - # Convert model instance back to dict and verify no loss of data - classified_images_model_json2 = classified_images_model.to_dict() - assert classified_images_model_json2 == classified_images_model_json - -class TestModel_Classifier(): - """ - Test Class for Classifier - """ - - def test_classifier_serialization(self): - """ - Test serialization/deserialization for Classifier - """ - - # Construct dict forms of any model objects needed in order to build this model. - - class_model = {} # Class - class_model['class'] = 'testString' - - # Construct a json representation of a Classifier model - classifier_model_json = {} - classifier_model_json['classifier_id'] = 'testString' - classifier_model_json['name'] = 'testString' - classifier_model_json['owner'] = 'testString' - classifier_model_json['status'] = 'ready' - classifier_model_json['core_ml_enabled'] = True - classifier_model_json['explanation'] = 'testString' - classifier_model_json['created'] = "2019-01-01T12:00:00Z" - classifier_model_json['classes'] = [class_model] - classifier_model_json['retrained'] = "2019-01-01T12:00:00Z" - classifier_model_json['updated'] = "2019-01-01T12:00:00Z" - - # Construct a model instance of Classifier by calling from_dict on the json representation - classifier_model = Classifier.from_dict(classifier_model_json) - assert classifier_model != False - - # Construct a model instance of Classifier by calling from_dict on the json representation - classifier_model_dict = Classifier.from_dict(classifier_model_json).__dict__ - classifier_model2 = Classifier(**classifier_model_dict) - - # Verify the model instances are equivalent - assert classifier_model == classifier_model2 - - # Convert model instance back to dict and verify no loss of data - classifier_model_json2 = classifier_model.to_dict() - assert classifier_model_json2 == classifier_model_json - -class TestModel_ClassifierResult(): - """ - Test Class for ClassifierResult - """ - - def test_classifier_result_serialization(self): - """ - Test serialization/deserialization for ClassifierResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - class_result_model = {} # ClassResult - class_result_model['class'] = 'testString' - class_result_model['score'] = 0 - class_result_model['type_hierarchy'] = 'testString' - - # Construct a json representation of a ClassifierResult model - classifier_result_model_json = {} - classifier_result_model_json['name'] = 'testString' - classifier_result_model_json['classifier_id'] = 'testString' - classifier_result_model_json['classes'] = [class_result_model] - - # Construct a model instance of ClassifierResult by calling from_dict on the json representation - classifier_result_model = ClassifierResult.from_dict(classifier_result_model_json) - assert classifier_result_model != False - - # Construct a model instance of ClassifierResult by calling from_dict on the json representation - classifier_result_model_dict = ClassifierResult.from_dict(classifier_result_model_json).__dict__ - classifier_result_model2 = ClassifierResult(**classifier_result_model_dict) - - # Verify the model instances are equivalent - assert classifier_result_model == classifier_result_model2 - - # Convert model instance back to dict and verify no loss of data - classifier_result_model_json2 = classifier_result_model.to_dict() - assert classifier_result_model_json2 == classifier_result_model_json - -class TestModel_Classifiers(): - """ - Test Class for Classifiers - """ - - def test_classifiers_serialization(self): - """ - Test serialization/deserialization for Classifiers - """ - - # Construct dict forms of any model objects needed in order to build this model. - - class_model = {} # Class - class_model['class'] = 'testString' - - classifier_model = {} # Classifier - classifier_model['classifier_id'] = 'testString' - classifier_model['name'] = 'testString' - classifier_model['owner'] = 'testString' - classifier_model['status'] = 'ready' - classifier_model['core_ml_enabled'] = True - classifier_model['explanation'] = 'testString' - classifier_model['created'] = "2019-01-01T12:00:00Z" - classifier_model['classes'] = [class_model] - classifier_model['retrained'] = "2019-01-01T12:00:00Z" - classifier_model['updated'] = "2019-01-01T12:00:00Z" - - # Construct a json representation of a Classifiers model - classifiers_model_json = {} - classifiers_model_json['classifiers'] = [classifier_model] - - # Construct a model instance of Classifiers by calling from_dict on the json representation - classifiers_model = Classifiers.from_dict(classifiers_model_json) - assert classifiers_model != False - - # Construct a model instance of Classifiers by calling from_dict on the json representation - classifiers_model_dict = Classifiers.from_dict(classifiers_model_json).__dict__ - classifiers_model2 = Classifiers(**classifiers_model_dict) - - # Verify the model instances are equivalent - assert classifiers_model == classifiers_model2 - - # Convert model instance back to dict and verify no loss of data - classifiers_model_json2 = classifiers_model.to_dict() - assert classifiers_model_json2 == classifiers_model_json - -class TestModel_ErrorInfo(): - """ - Test Class for ErrorInfo - """ - - def test_error_info_serialization(self): - """ - Test serialization/deserialization for ErrorInfo - """ - - # Construct a json representation of a ErrorInfo model - error_info_model_json = {} - error_info_model_json['code'] = 38 - error_info_model_json['description'] = 'testString' - error_info_model_json['error_id'] = 'testString' - - # Construct a model instance of ErrorInfo by calling from_dict on the json representation - error_info_model = ErrorInfo.from_dict(error_info_model_json) - assert error_info_model != False - - # Construct a model instance of ErrorInfo by calling from_dict on the json representation - error_info_model_dict = ErrorInfo.from_dict(error_info_model_json).__dict__ - error_info_model2 = ErrorInfo(**error_info_model_dict) - - # Verify the model instances are equivalent - assert error_info_model == error_info_model2 - - # Convert model instance back to dict and verify no loss of data - error_info_model_json2 = error_info_model.to_dict() - assert error_info_model_json2 == error_info_model_json - -class TestModel_WarningInfo(): - """ - Test Class for WarningInfo - """ - - def test_warning_info_serialization(self): - """ - Test serialization/deserialization for WarningInfo - """ - - # Construct a json representation of a WarningInfo model - warning_info_model_json = {} - warning_info_model_json['warning_id'] = 'testString' - warning_info_model_json['description'] = 'testString' - - # Construct a model instance of WarningInfo by calling from_dict on the json representation - warning_info_model = WarningInfo.from_dict(warning_info_model_json) - assert warning_info_model != False - - # Construct a model instance of WarningInfo by calling from_dict on the json representation - warning_info_model_dict = WarningInfo.from_dict(warning_info_model_json).__dict__ - warning_info_model2 = WarningInfo(**warning_info_model_dict) - - # Verify the model instances are equivalent - assert warning_info_model == warning_info_model2 - - # Convert model instance back to dict and verify no loss of data - warning_info_model_json2 = warning_info_model.to_dict() - assert warning_info_model_json2 == warning_info_model_json - - -# endregion -############################################################################## -# End of Model Tests -############################################################################## diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py deleted file mode 100644 index d1875fdc5..000000000 --- a/test/unit/test_visual_recognition_v4.py +++ /dev/null @@ -1,3058 +0,0 @@ -# -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2021. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Unit Tests for VisualRecognitionV4 -""" - -from datetime import datetime, timezone -from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator -from ibm_cloud_sdk_core.utils import date_to_string, string_to_date -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime -import inspect -import io -import json -import pytest -import re -import requests -import responses -import tempfile -import urllib -from ibm_watson.visual_recognition_v4 import * - -version = 'testString' - -_service = VisualRecognitionV4( - authenticator=NoAuthAuthenticator(), - version=version - ) - -_base_url = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' -_service.set_service_url(_base_url) - -############################################################################## -# Start of Service: Analysis -############################################################################## -# region - -class TestAnalyze(): - """ - Test Class for analyze - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_analyze_all_params(self): - """ - analyze() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/analyze') - mock_response = '{"images": [{"source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "objects": {"collections": [{"collection_id": "collection_id", "objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}, "score": 5}]}]}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}]}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a FileWithMetadata model - file_with_metadata_model = {} - file_with_metadata_model['data'] = io.BytesIO(b'This is a mock file.').getvalue() - file_with_metadata_model['filename'] = 'testString' - file_with_metadata_model['content_type'] = 'testString' - - # Set up parameter values - collection_ids = ['testString'] - features = ['objects'] - images_file = [file_with_metadata_model] - image_url = ['testString'] - threshold = 0.15 - - # Invoke method - response = _service.analyze( - collection_ids, - features, - images_file=images_file, - image_url=image_url, - threshold=threshold, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_analyze_required_params(self): - """ - test_analyze_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/analyze') - mock_response = '{"images": [{"source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "objects": {"collections": [{"collection_id": "collection_id", "objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}, "score": 5}]}]}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}]}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_ids = ['testString'] - features = ['objects'] - - # Invoke method - response = _service.analyze( - collection_ids, - features, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_analyze_value_error(self): - """ - test_analyze_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/analyze') - mock_response = '{"images": [{"source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "objects": {"collections": [{"collection_id": "collection_id", "objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}, "score": 5}]}]}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}]}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_ids = ['testString'] - features = ['objects'] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_ids": collection_ids, - "features": features, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.analyze(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Analysis -############################################################################## - -############################################################################## -# Start of Service: Collections -############################################################################## -# region - -class TestCreateCollection(): - """ - Test Class for create_collection - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_create_collection_all_params(self): - """ - create_collection() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ObjectTrainingStatus model - object_training_status_model = {} - object_training_status_model['ready'] = True - object_training_status_model['in_progress'] = True - object_training_status_model['data_changed'] = True - object_training_status_model['latest_failed'] = True - object_training_status_model['rscnn_ready'] = True - object_training_status_model['description'] = 'testString' - - # Construct a dict representation of a TrainingStatus model - training_status_model = {} - training_status_model['objects'] = object_training_status_model - - # Set up parameter values - name = 'testString' - description = 'testString' - training_status = training_status_model - - # Invoke method - response = _service.create_collection( - name=name, - description=description, - training_status=training_status, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['training_status'] == training_status_model - - - @responses.activate - def test_create_collection_value_error(self): - """ - test_create_collection_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ObjectTrainingStatus model - object_training_status_model = {} - object_training_status_model['ready'] = True - object_training_status_model['in_progress'] = True - object_training_status_model['data_changed'] = True - object_training_status_model['latest_failed'] = True - object_training_status_model['rscnn_ready'] = True - object_training_status_model['description'] = 'testString' - - # Construct a dict representation of a TrainingStatus model - training_status_model = {} - training_status_model['objects'] = object_training_status_model - - # Set up parameter values - name = 'testString' - description = 'testString' - training_status = training_status_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_collection(**req_copy) - - - -class TestListCollections(): - """ - Test Class for list_collections - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_list_collections_all_params(self): - """ - list_collections() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Invoke method - response = _service.list_collections() - - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_list_collections_value_error(self): - """ - test_list_collections_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_collections(**req_copy) - - - -class TestGetCollection(): - """ - Test Class for get_collection - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_get_collection_all_params(self): - """ - get_collection() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Invoke method - response = _service.get_collection( - collection_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_get_collection_value_error(self): - """ - test_get_collection_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_collection(**req_copy) - - - -class TestUpdateCollection(): - """ - Test Class for update_collection - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_update_collection_all_params(self): - """ - update_collection() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a ObjectTrainingStatus model - object_training_status_model = {} - object_training_status_model['ready'] = True - object_training_status_model['in_progress'] = True - object_training_status_model['data_changed'] = True - object_training_status_model['latest_failed'] = True - object_training_status_model['rscnn_ready'] = True - object_training_status_model['description'] = 'testString' - - # Construct a dict representation of a TrainingStatus model - training_status_model = {} - training_status_model['objects'] = object_training_status_model - - # Set up parameter values - collection_id = 'testString' - name = 'testString' - description = 'testString' - training_status = training_status_model - - # Invoke method - response = _service.update_collection( - collection_id, - name=name, - description=description, - training_status=training_status, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['training_status'] == training_status_model - - - @responses.activate - def test_update_collection_required_params(self): - """ - test_update_collection_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Invoke method - response = _service.update_collection( - collection_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_update_collection_value_error(self): - """ - test_update_collection_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_collection(**req_copy) - - - -class TestDeleteCollection(): - """ - Test Class for delete_collection - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_delete_collection_all_params(self): - """ - delete_collection() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString') - responses.add(responses.DELETE, - url, - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Invoke method - response = _service.delete_collection( - collection_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_delete_collection_value_error(self): - """ - test_delete_collection_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString') - responses.add(responses.DELETE, - url, - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_collection(**req_copy) - - - -class TestGetModelFile(): - """ - Test Class for get_model_file - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_get_model_file_all_params(self): - """ - get_model_file() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/model') - mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/octet-stream', - status=200) - - # Set up parameter values - collection_id = 'testString' - feature = 'objects' - model_format = 'rscnn' - - # Invoke method - response = _service.get_model_file( - collection_id, - feature, - model_format, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'feature={}'.format(feature) in query_string - assert 'model_format={}'.format(model_format) in query_string - - - @responses.activate - def test_get_model_file_value_error(self): - """ - test_get_model_file_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/model') - mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/octet-stream', - status=200) - - # Set up parameter values - collection_id = 'testString' - feature = 'objects' - model_format = 'rscnn' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - "feature": feature, - "model_format": model_format, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_model_file(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Collections -############################################################################## - -############################################################################## -# Start of Service: Images -############################################################################## -# region - -class TestAddImages(): - """ - Test Class for add_images - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_add_images_all_params(self): - """ - add_images() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images') - mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z", "created": "2019-01-01T12:00:00.000Z", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a FileWithMetadata model - file_with_metadata_model = {} - file_with_metadata_model['data'] = io.BytesIO(b'This is a mock file.').getvalue() - file_with_metadata_model['filename'] = 'testString' - file_with_metadata_model['content_type'] = 'testString' - - # Set up parameter values - collection_id = 'testString' - images_file = [file_with_metadata_model] - image_url = ['testString'] - training_data = '{"objects":[{"object":"2018-Fit","location":{"left":33,"top":8,"width":760,"height":419}}]}' - - # Invoke method - response = _service.add_images( - collection_id, - images_file=images_file, - image_url=image_url, - training_data=training_data, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_add_images_required_params(self): - """ - test_add_images_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images') - mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z", "created": "2019-01-01T12:00:00.000Z", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Invoke method - response = _service.add_images( - collection_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_add_images_value_error(self): - """ - test_add_images_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images') - mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z", "created": "2019-01-01T12:00:00.000Z", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}], "warnings": [{"code": "invalid_field", "message": "message", "more_info": "more_info"}], "trace": "trace"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.add_images(**req_copy) - - - -class TestListImages(): - """ - Test Class for list_images - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_list_images_all_params(self): - """ - list_images() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images') - mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Invoke method - response = _service.list_images( - collection_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_list_images_value_error(self): - """ - test_list_images_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images') - mock_response = '{"images": [{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_images(**req_copy) - - - -class TestGetImageDetails(): - """ - Test Class for get_image_details - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_get_image_details_all_params(self): - """ - get_image_details() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString') - mock_response = '{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z", "created": "2019-01-01T12:00:00.000Z", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - image_id = 'testString' - - # Invoke method - response = _service.get_image_details( - collection_id, - image_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_get_image_details_value_error(self): - """ - test_get_image_details_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString') - mock_response = '{"image_id": "image_id", "updated": "2019-01-01T12:00:00.000Z", "created": "2019-01-01T12:00:00.000Z", "source": {"type": "file", "filename": "filename", "archive_filename": "archive_filename", "source_url": "source_url", "resolved_url": "resolved_url"}, "dimensions": {"height": 6, "width": 5}, "errors": [{"code": "invalid_field", "message": "message", "more_info": "more_info", "target": {"type": "field", "name": "name"}}], "training_data": {"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - image_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - "image_id": image_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_image_details(**req_copy) - - - -class TestDeleteImage(): - """ - Test Class for delete_image - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_delete_image_all_params(self): - """ - delete_image() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString') - responses.add(responses.DELETE, - url, - status=200) - - # Set up parameter values - collection_id = 'testString' - image_id = 'testString' - - # Invoke method - response = _service.delete_image( - collection_id, - image_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_delete_image_value_error(self): - """ - test_delete_image_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString') - responses.add(responses.DELETE, - url, - status=200) - - # Set up parameter values - collection_id = 'testString' - image_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - "image_id": image_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_image(**req_copy) - - - -class TestGetJpegImage(): - """ - Test Class for get_jpeg_image - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_get_jpeg_image_all_params(self): - """ - get_jpeg_image() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString/jpeg') - mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='image/jpeg', - status=200) - - # Set up parameter values - collection_id = 'testString' - image_id = 'testString' - size = 'full' - - # Invoke method - response = _service.get_jpeg_image( - collection_id, - image_id, - size=size, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'size={}'.format(size) in query_string - - - @responses.activate - def test_get_jpeg_image_required_params(self): - """ - test_get_jpeg_image_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString/jpeg') - mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='image/jpeg', - status=200) - - # Set up parameter values - collection_id = 'testString' - image_id = 'testString' - - # Invoke method - response = _service.get_jpeg_image( - collection_id, - image_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_get_jpeg_image_value_error(self): - """ - test_get_jpeg_image_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString/jpeg') - mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='image/jpeg', - status=200) - - # Set up parameter values - collection_id = 'testString' - image_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - "image_id": image_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_jpeg_image(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Images -############################################################################## - -############################################################################## -# Start of Service: Objects -############################################################################## -# region - -class TestListObjectMetadata(): - """ - Test Class for list_object_metadata - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_list_object_metadata_all_params(self): - """ - list_object_metadata() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/objects') - mock_response = '{"object_count": 12, "objects": [{"object": "object", "count": 5}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Invoke method - response = _service.list_object_metadata( - collection_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_list_object_metadata_value_error(self): - """ - test_list_object_metadata_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/objects') - mock_response = '{"object_count": 12, "objects": [{"object": "object", "count": 5}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_object_metadata(**req_copy) - - - -class TestUpdateObjectMetadata(): - """ - Test Class for update_object_metadata - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_update_object_metadata_all_params(self): - """ - update_object_metadata() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') - mock_response = '{"object": "object", "count": 5}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - object = 'testString' - new_object = 'testString' - - # Invoke method - response = _service.update_object_metadata( - collection_id, - object, - new_object, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['object'] == 'testString' - - - @responses.activate - def test_update_object_metadata_value_error(self): - """ - test_update_object_metadata_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') - mock_response = '{"object": "object", "count": 5}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - object = 'testString' - new_object = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - "object": object, - "new_object": new_object, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_object_metadata(**req_copy) - - - -class TestGetObjectMetadata(): - """ - Test Class for get_object_metadata - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_get_object_metadata_all_params(self): - """ - get_object_metadata() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') - mock_response = '{"object": "object", "count": 5}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - object = 'testString' - - # Invoke method - response = _service.get_object_metadata( - collection_id, - object, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_get_object_metadata_value_error(self): - """ - test_get_object_metadata_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') - mock_response = '{"object": "object", "count": 5}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - collection_id = 'testString' - object = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - "object": object, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_object_metadata(**req_copy) - - - -class TestDeleteObject(): - """ - Test Class for delete_object - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_delete_object_all_params(self): - """ - delete_object() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') - responses.add(responses.DELETE, - url, - status=200) - - # Set up parameter values - collection_id = 'testString' - object = 'testString' - - # Invoke method - response = _service.delete_object( - collection_id, - object, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_delete_object_value_error(self): - """ - test_delete_object_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/objects/testString') - responses.add(responses.DELETE, - url, - status=200) - - # Set up parameter values - collection_id = 'testString' - object = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - "object": object, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_object(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Objects -############################################################################## - -############################################################################## -# Start of Service: Training -############################################################################## -# region - -class TestTrain(): - """ - Test Class for train - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_train_all_params(self): - """ - train() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/train') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) - - # Set up parameter values - collection_id = 'testString' - - # Invoke method - response = _service.train( - collection_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - - @responses.activate - def test_train_value_error(self): - """ - test_train_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/train') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "image_count": 11, "training_status": {"objects": {"ready": false, "in_progress": false, "data_changed": true, "latest_failed": false, "rscnn_ready": false, "description": "description"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) - - # Set up parameter values - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.train(**req_copy) - - - -class TestAddImageTrainingData(): - """ - Test Class for add_image_training_data - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_add_image_training_data_all_params(self): - """ - add_image_training_data() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString/training_data') - mock_response = '{"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a Location model - location_model = {} - location_model['top'] = 38 - location_model['left'] = 38 - location_model['width'] = 38 - location_model['height'] = 38 - - # Construct a dict representation of a TrainingDataObject model - training_data_object_model = {} - training_data_object_model['object'] = 'testString' - training_data_object_model['location'] = location_model - - # Set up parameter values - collection_id = 'testString' - image_id = 'testString' - objects = [training_data_object_model] - - # Invoke method - response = _service.add_image_training_data( - collection_id, - image_id, - objects=objects, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['objects'] == [training_data_object_model] - - - @responses.activate - def test_add_image_training_data_value_error(self): - """ - test_add_image_training_data_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/collections/testString/images/testString/training_data') - mock_response = '{"objects": [{"object": "object", "location": {"top": 3, "left": 4, "width": 5, "height": 6}}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a Location model - location_model = {} - location_model['top'] = 38 - location_model['left'] = 38 - location_model['width'] = 38 - location_model['height'] = 38 - - # Construct a dict representation of a TrainingDataObject model - training_data_object_model = {} - training_data_object_model['object'] = 'testString' - training_data_object_model['location'] = location_model - - # Set up parameter values - collection_id = 'testString' - image_id = 'testString' - objects = [training_data_object_model] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "collection_id": collection_id, - "image_id": image_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.add_image_training_data(**req_copy) - - - -class TestGetTrainingUsage(): - """ - Test Class for get_training_usage - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_get_training_usage_all_params(self): - """ - get_training_usage() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/training_usage') - mock_response = '{"start_time": "2019-01-01T12:00:00.000Z", "end_time": "2019-01-01T12:00:00.000Z", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00.000Z", "status": "failed", "image_count": 11}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - start_time = string_to_date('2019-01-01') - end_time = string_to_date('2019-01-01') - - # Invoke method - response = _service.get_training_usage( - start_time=start_time, - end_time=end_time, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'start_time={}'.format(date_to_string(start_time)) in query_string - assert 'end_time={}'.format(date_to_string(end_time)) in query_string - - - @responses.activate - def test_get_training_usage_required_params(self): - """ - test_get_training_usage_required_params() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/training_usage') - mock_response = '{"start_time": "2019-01-01T12:00:00.000Z", "end_time": "2019-01-01T12:00:00.000Z", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00.000Z", "status": "failed", "image_count": 11}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Invoke method - response = _service.get_training_usage() - - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - - @responses.activate - def test_get_training_usage_value_error(self): - """ - test_get_training_usage_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/training_usage') - mock_response = '{"start_time": "2019-01-01T12:00:00.000Z", "end_time": "2019-01-01T12:00:00.000Z", "completed_events": 16, "trained_images": 14, "events": [{"type": "objects", "collection_id": "collection_id", "completion_time": "2019-01-01T12:00:00.000Z", "status": "failed", "image_count": 11}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_training_usage(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Training -############################################################################## - -############################################################################## -# Start of Service: UserData -############################################################################## -# region - -class TestDeleteUserData(): - """ - Test Class for delete_user_data - """ - - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - - @responses.activate - def test_delete_user_data_all_params(self): - """ - delete_user_data() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/user_data') - responses.add(responses.DELETE, - url, - status=202) - - # Set up parameter values - customer_id = 'testString' - - # Invoke method - response = _service.delete_user_data( - customer_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'customer_id={}'.format(customer_id) in query_string - - - @responses.activate - def test_delete_user_data_value_error(self): - """ - test_delete_user_data_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v4/user_data') - responses.add(responses.DELETE, - url, - status=202) - - # Set up parameter values - customer_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "customer_id": customer_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_user_data(**req_copy) - - - -# endregion -############################################################################## -# End of Service: UserData -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region -class TestModel_AnalyzeResponse(): - """ - Test Class for AnalyzeResponse - """ - - def test_analyze_response_serialization(self): - """ - Test serialization/deserialization for AnalyzeResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - image_source_model = {} # ImageSource - image_source_model['type'] = 'file' - image_source_model['filename'] = 'testString' - image_source_model['archive_filename'] = 'testString' - image_source_model['source_url'] = 'testString' - image_source_model['resolved_url'] = 'testString' - - image_dimensions_model = {} # ImageDimensions - image_dimensions_model['height'] = 38 - image_dimensions_model['width'] = 38 - - object_detail_location_model = {} # ObjectDetailLocation - object_detail_location_model['top'] = 38 - object_detail_location_model['left'] = 38 - object_detail_location_model['width'] = 38 - object_detail_location_model['height'] = 38 - - object_detail_model = {} # ObjectDetail - object_detail_model['object'] = 'testString' - object_detail_model['location'] = object_detail_location_model - object_detail_model['score'] = 72.5 - - collection_objects_model = {} # CollectionObjects - collection_objects_model['collection_id'] = 'testString' - collection_objects_model['objects'] = [object_detail_model] - - detected_objects_model = {} # DetectedObjects - detected_objects_model['collections'] = [collection_objects_model] - - error_target_model = {} # ErrorTarget - error_target_model['type'] = 'field' - error_target_model['name'] = 'testString' - - error_model = {} # Error - error_model['code'] = 'invalid_field' - error_model['message'] = 'testString' - error_model['more_info'] = 'testString' - error_model['target'] = error_target_model - - image_model = {} # Image - image_model['source'] = image_source_model - image_model['dimensions'] = image_dimensions_model - image_model['objects'] = detected_objects_model - image_model['errors'] = [error_model] - - warning_model = {} # Warning - warning_model['code'] = 'invalid_field' - warning_model['message'] = 'testString' - warning_model['more_info'] = 'testString' - - # Construct a json representation of a AnalyzeResponse model - analyze_response_model_json = {} - analyze_response_model_json['images'] = [image_model] - analyze_response_model_json['warnings'] = [warning_model] - analyze_response_model_json['trace'] = 'testString' - - # Construct a model instance of AnalyzeResponse by calling from_dict on the json representation - analyze_response_model = AnalyzeResponse.from_dict(analyze_response_model_json) - assert analyze_response_model != False - - # Construct a model instance of AnalyzeResponse by calling from_dict on the json representation - analyze_response_model_dict = AnalyzeResponse.from_dict(analyze_response_model_json).__dict__ - analyze_response_model2 = AnalyzeResponse(**analyze_response_model_dict) - - # Verify the model instances are equivalent - assert analyze_response_model == analyze_response_model2 - - # Convert model instance back to dict and verify no loss of data - analyze_response_model_json2 = analyze_response_model.to_dict() - assert analyze_response_model_json2 == analyze_response_model_json - -class TestModel_Collection(): - """ - Test Class for Collection - """ - - def test_collection_serialization(self): - """ - Test serialization/deserialization for Collection - """ - - # Construct dict forms of any model objects needed in order to build this model. - - object_training_status_model = {} # ObjectTrainingStatus - object_training_status_model['ready'] = True - object_training_status_model['in_progress'] = True - object_training_status_model['data_changed'] = True - object_training_status_model['latest_failed'] = True - object_training_status_model['rscnn_ready'] = True - object_training_status_model['description'] = 'testString' - - collection_training_status_model = {} # CollectionTrainingStatus - collection_training_status_model['objects'] = object_training_status_model - - # Construct a json representation of a Collection model - collection_model_json = {} - collection_model_json['collection_id'] = 'testString' - collection_model_json['name'] = 'testString' - collection_model_json['description'] = 'testString' - collection_model_json['created'] = "2019-01-01T12:00:00Z" - collection_model_json['updated'] = "2019-01-01T12:00:00Z" - collection_model_json['image_count'] = 38 - collection_model_json['training_status'] = collection_training_status_model - - # Construct a model instance of Collection by calling from_dict on the json representation - collection_model = Collection.from_dict(collection_model_json) - assert collection_model != False - - # Construct a model instance of Collection by calling from_dict on the json representation - collection_model_dict = Collection.from_dict(collection_model_json).__dict__ - collection_model2 = Collection(**collection_model_dict) - - # Verify the model instances are equivalent - assert collection_model == collection_model2 - - # Convert model instance back to dict and verify no loss of data - collection_model_json2 = collection_model.to_dict() - assert collection_model_json2 == collection_model_json - -class TestModel_CollectionObjects(): - """ - Test Class for CollectionObjects - """ - - def test_collection_objects_serialization(self): - """ - Test serialization/deserialization for CollectionObjects - """ - - # Construct dict forms of any model objects needed in order to build this model. - - object_detail_location_model = {} # ObjectDetailLocation - object_detail_location_model['top'] = 38 - object_detail_location_model['left'] = 38 - object_detail_location_model['width'] = 38 - object_detail_location_model['height'] = 38 - - object_detail_model = {} # ObjectDetail - object_detail_model['object'] = 'testString' - object_detail_model['location'] = object_detail_location_model - object_detail_model['score'] = 72.5 - - # Construct a json representation of a CollectionObjects model - collection_objects_model_json = {} - collection_objects_model_json['collection_id'] = 'testString' - collection_objects_model_json['objects'] = [object_detail_model] - - # Construct a model instance of CollectionObjects by calling from_dict on the json representation - collection_objects_model = CollectionObjects.from_dict(collection_objects_model_json) - assert collection_objects_model != False - - # Construct a model instance of CollectionObjects by calling from_dict on the json representation - collection_objects_model_dict = CollectionObjects.from_dict(collection_objects_model_json).__dict__ - collection_objects_model2 = CollectionObjects(**collection_objects_model_dict) - - # Verify the model instances are equivalent - assert collection_objects_model == collection_objects_model2 - - # Convert model instance back to dict and verify no loss of data - collection_objects_model_json2 = collection_objects_model.to_dict() - assert collection_objects_model_json2 == collection_objects_model_json - -class TestModel_CollectionTrainingStatus(): - """ - Test Class for CollectionTrainingStatus - """ - - def test_collection_training_status_serialization(self): - """ - Test serialization/deserialization for CollectionTrainingStatus - """ - - # Construct dict forms of any model objects needed in order to build this model. - - object_training_status_model = {} # ObjectTrainingStatus - object_training_status_model['ready'] = True - object_training_status_model['in_progress'] = True - object_training_status_model['data_changed'] = True - object_training_status_model['latest_failed'] = True - object_training_status_model['rscnn_ready'] = True - object_training_status_model['description'] = 'testString' - - # Construct a json representation of a CollectionTrainingStatus model - collection_training_status_model_json = {} - collection_training_status_model_json['objects'] = object_training_status_model - - # Construct a model instance of CollectionTrainingStatus by calling from_dict on the json representation - collection_training_status_model = CollectionTrainingStatus.from_dict(collection_training_status_model_json) - assert collection_training_status_model != False - - # Construct a model instance of CollectionTrainingStatus by calling from_dict on the json representation - collection_training_status_model_dict = CollectionTrainingStatus.from_dict(collection_training_status_model_json).__dict__ - collection_training_status_model2 = CollectionTrainingStatus(**collection_training_status_model_dict) - - # Verify the model instances are equivalent - assert collection_training_status_model == collection_training_status_model2 - - # Convert model instance back to dict and verify no loss of data - collection_training_status_model_json2 = collection_training_status_model.to_dict() - assert collection_training_status_model_json2 == collection_training_status_model_json - -class TestModel_CollectionsList(): - """ - Test Class for CollectionsList - """ - - def test_collections_list_serialization(self): - """ - Test serialization/deserialization for CollectionsList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - object_training_status_model = {} # ObjectTrainingStatus - object_training_status_model['ready'] = True - object_training_status_model['in_progress'] = True - object_training_status_model['data_changed'] = True - object_training_status_model['latest_failed'] = True - object_training_status_model['rscnn_ready'] = True - object_training_status_model['description'] = 'testString' - - collection_training_status_model = {} # CollectionTrainingStatus - collection_training_status_model['objects'] = object_training_status_model - - collection_model = {} # Collection - collection_model['collection_id'] = 'testString' - collection_model['name'] = 'testString' - collection_model['description'] = 'testString' - collection_model['created'] = "2019-01-01T12:00:00Z" - collection_model['updated'] = "2019-01-01T12:00:00Z" - collection_model['image_count'] = 38 - collection_model['training_status'] = collection_training_status_model - - # Construct a json representation of a CollectionsList model - collections_list_model_json = {} - collections_list_model_json['collections'] = [collection_model] - - # Construct a model instance of CollectionsList by calling from_dict on the json representation - collections_list_model = CollectionsList.from_dict(collections_list_model_json) - assert collections_list_model != False - - # Construct a model instance of CollectionsList by calling from_dict on the json representation - collections_list_model_dict = CollectionsList.from_dict(collections_list_model_json).__dict__ - collections_list_model2 = CollectionsList(**collections_list_model_dict) - - # Verify the model instances are equivalent - assert collections_list_model == collections_list_model2 - - # Convert model instance back to dict and verify no loss of data - collections_list_model_json2 = collections_list_model.to_dict() - assert collections_list_model_json2 == collections_list_model_json - -class TestModel_DetectedObjects(): - """ - Test Class for DetectedObjects - """ - - def test_detected_objects_serialization(self): - """ - Test serialization/deserialization for DetectedObjects - """ - - # Construct dict forms of any model objects needed in order to build this model. - - object_detail_location_model = {} # ObjectDetailLocation - object_detail_location_model['top'] = 38 - object_detail_location_model['left'] = 38 - object_detail_location_model['width'] = 38 - object_detail_location_model['height'] = 38 - - object_detail_model = {} # ObjectDetail - object_detail_model['object'] = 'testString' - object_detail_model['location'] = object_detail_location_model - object_detail_model['score'] = 72.5 - - collection_objects_model = {} # CollectionObjects - collection_objects_model['collection_id'] = 'testString' - collection_objects_model['objects'] = [object_detail_model] - - # Construct a json representation of a DetectedObjects model - detected_objects_model_json = {} - detected_objects_model_json['collections'] = [collection_objects_model] - - # Construct a model instance of DetectedObjects by calling from_dict on the json representation - detected_objects_model = DetectedObjects.from_dict(detected_objects_model_json) - assert detected_objects_model != False - - # Construct a model instance of DetectedObjects by calling from_dict on the json representation - detected_objects_model_dict = DetectedObjects.from_dict(detected_objects_model_json).__dict__ - detected_objects_model2 = DetectedObjects(**detected_objects_model_dict) - - # Verify the model instances are equivalent - assert detected_objects_model == detected_objects_model2 - - # Convert model instance back to dict and verify no loss of data - detected_objects_model_json2 = detected_objects_model.to_dict() - assert detected_objects_model_json2 == detected_objects_model_json - -class TestModel_Error(): - """ - Test Class for Error - """ - - def test_error_serialization(self): - """ - Test serialization/deserialization for Error - """ - - # Construct dict forms of any model objects needed in order to build this model. - - error_target_model = {} # ErrorTarget - error_target_model['type'] = 'parameter' - error_target_model['name'] = 'version' - - # Construct a json representation of a Error model - error_model_json = {} - error_model_json['code'] = 'invalid_field' - error_model_json['message'] = 'testString' - error_model_json['more_info'] = 'testString' - error_model_json['target'] = error_target_model - - # Construct a model instance of Error by calling from_dict on the json representation - error_model = Error.from_dict(error_model_json) - assert error_model != False - - # Construct a model instance of Error by calling from_dict on the json representation - error_model_dict = Error.from_dict(error_model_json).__dict__ - error_model2 = Error(**error_model_dict) - - # Verify the model instances are equivalent - assert error_model == error_model2 - - # Convert model instance back to dict and verify no loss of data - error_model_json2 = error_model.to_dict() - assert error_model_json2 == error_model_json - -class TestModel_ErrorTarget(): - """ - Test Class for ErrorTarget - """ - - def test_error_target_serialization(self): - """ - Test serialization/deserialization for ErrorTarget - """ - - # Construct a json representation of a ErrorTarget model - error_target_model_json = {} - error_target_model_json['type'] = 'field' - error_target_model_json['name'] = 'testString' - - # Construct a model instance of ErrorTarget by calling from_dict on the json representation - error_target_model = ErrorTarget.from_dict(error_target_model_json) - assert error_target_model != False - - # Construct a model instance of ErrorTarget by calling from_dict on the json representation - error_target_model_dict = ErrorTarget.from_dict(error_target_model_json).__dict__ - error_target_model2 = ErrorTarget(**error_target_model_dict) - - # Verify the model instances are equivalent - assert error_target_model == error_target_model2 - - # Convert model instance back to dict and verify no loss of data - error_target_model_json2 = error_target_model.to_dict() - assert error_target_model_json2 == error_target_model_json - -class TestModel_Image(): - """ - Test Class for Image - """ - - def test_image_serialization(self): - """ - Test serialization/deserialization for Image - """ - - # Construct dict forms of any model objects needed in order to build this model. - - image_source_model = {} # ImageSource - image_source_model['type'] = 'file' - image_source_model['filename'] = 'testString' - image_source_model['archive_filename'] = 'testString' - image_source_model['source_url'] = 'testString' - image_source_model['resolved_url'] = 'testString' - - image_dimensions_model = {} # ImageDimensions - image_dimensions_model['height'] = 38 - image_dimensions_model['width'] = 38 - - object_detail_location_model = {} # ObjectDetailLocation - object_detail_location_model['top'] = 38 - object_detail_location_model['left'] = 38 - object_detail_location_model['width'] = 38 - object_detail_location_model['height'] = 38 - - object_detail_model = {} # ObjectDetail - object_detail_model['object'] = 'testString' - object_detail_model['location'] = object_detail_location_model - object_detail_model['score'] = 72.5 - - collection_objects_model = {} # CollectionObjects - collection_objects_model['collection_id'] = 'testString' - collection_objects_model['objects'] = [object_detail_model] - - detected_objects_model = {} # DetectedObjects - detected_objects_model['collections'] = [collection_objects_model] - - error_target_model = {} # ErrorTarget - error_target_model['type'] = 'field' - error_target_model['name'] = 'testString' - - error_model = {} # Error - error_model['code'] = 'invalid_field' - error_model['message'] = 'testString' - error_model['more_info'] = 'testString' - error_model['target'] = error_target_model - - # Construct a json representation of a Image model - image_model_json = {} - image_model_json['source'] = image_source_model - image_model_json['dimensions'] = image_dimensions_model - image_model_json['objects'] = detected_objects_model - image_model_json['errors'] = [error_model] - - # Construct a model instance of Image by calling from_dict on the json representation - image_model = Image.from_dict(image_model_json) - assert image_model != False - - # Construct a model instance of Image by calling from_dict on the json representation - image_model_dict = Image.from_dict(image_model_json).__dict__ - image_model2 = Image(**image_model_dict) - - # Verify the model instances are equivalent - assert image_model == image_model2 - - # Convert model instance back to dict and verify no loss of data - image_model_json2 = image_model.to_dict() - assert image_model_json2 == image_model_json - -class TestModel_ImageDetails(): - """ - Test Class for ImageDetails - """ - - def test_image_details_serialization(self): - """ - Test serialization/deserialization for ImageDetails - """ - - # Construct dict forms of any model objects needed in order to build this model. - - image_source_model = {} # ImageSource - image_source_model['type'] = 'file' - image_source_model['filename'] = 'testString' - image_source_model['archive_filename'] = 'testString' - image_source_model['source_url'] = 'testString' - image_source_model['resolved_url'] = 'testString' - - image_dimensions_model = {} # ImageDimensions - image_dimensions_model['height'] = 38 - image_dimensions_model['width'] = 38 - - error_target_model = {} # ErrorTarget - error_target_model['type'] = 'field' - error_target_model['name'] = 'testString' - - error_model = {} # Error - error_model['code'] = 'invalid_field' - error_model['message'] = 'testString' - error_model['more_info'] = 'testString' - error_model['target'] = error_target_model - - location_model = {} # Location - location_model['top'] = 38 - location_model['left'] = 38 - location_model['width'] = 38 - location_model['height'] = 38 - - training_data_object_model = {} # TrainingDataObject - training_data_object_model['object'] = 'testString' - training_data_object_model['location'] = location_model - - training_data_objects_model = {} # TrainingDataObjects - training_data_objects_model['objects'] = [training_data_object_model] - - # Construct a json representation of a ImageDetails model - image_details_model_json = {} - image_details_model_json['image_id'] = 'testString' - image_details_model_json['updated'] = "2019-01-01T12:00:00Z" - image_details_model_json['created'] = "2019-01-01T12:00:00Z" - image_details_model_json['source'] = image_source_model - image_details_model_json['dimensions'] = image_dimensions_model - image_details_model_json['errors'] = [error_model] - image_details_model_json['training_data'] = training_data_objects_model - - # Construct a model instance of ImageDetails by calling from_dict on the json representation - image_details_model = ImageDetails.from_dict(image_details_model_json) - assert image_details_model != False - - # Construct a model instance of ImageDetails by calling from_dict on the json representation - image_details_model_dict = ImageDetails.from_dict(image_details_model_json).__dict__ - image_details_model2 = ImageDetails(**image_details_model_dict) - - # Verify the model instances are equivalent - assert image_details_model == image_details_model2 - - # Convert model instance back to dict and verify no loss of data - image_details_model_json2 = image_details_model.to_dict() - assert image_details_model_json2 == image_details_model_json - -class TestModel_ImageDetailsList(): - """ - Test Class for ImageDetailsList - """ - - def test_image_details_list_serialization(self): - """ - Test serialization/deserialization for ImageDetailsList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - image_source_model = {} # ImageSource - image_source_model['type'] = 'file' - image_source_model['filename'] = 'testString' - image_source_model['archive_filename'] = 'testString' - image_source_model['source_url'] = 'testString' - image_source_model['resolved_url'] = 'testString' - - image_dimensions_model = {} # ImageDimensions - image_dimensions_model['height'] = 38 - image_dimensions_model['width'] = 38 - - error_target_model = {} # ErrorTarget - error_target_model['type'] = 'field' - error_target_model['name'] = 'testString' - - error_model = {} # Error - error_model['code'] = 'invalid_field' - error_model['message'] = 'testString' - error_model['more_info'] = 'testString' - error_model['target'] = error_target_model - - location_model = {} # Location - location_model['top'] = 38 - location_model['left'] = 38 - location_model['width'] = 38 - location_model['height'] = 38 - - training_data_object_model = {} # TrainingDataObject - training_data_object_model['object'] = 'testString' - training_data_object_model['location'] = location_model - - training_data_objects_model = {} # TrainingDataObjects - training_data_objects_model['objects'] = [training_data_object_model] - - image_details_model = {} # ImageDetails - image_details_model['image_id'] = 'testString' - image_details_model['updated'] = "2019-01-01T12:00:00Z" - image_details_model['created'] = "2019-01-01T12:00:00Z" - image_details_model['source'] = image_source_model - image_details_model['dimensions'] = image_dimensions_model - image_details_model['errors'] = [error_model] - image_details_model['training_data'] = training_data_objects_model - - warning_model = {} # Warning - warning_model['code'] = 'invalid_field' - warning_model['message'] = 'testString' - warning_model['more_info'] = 'testString' - - # Construct a json representation of a ImageDetailsList model - image_details_list_model_json = {} - image_details_list_model_json['images'] = [image_details_model] - image_details_list_model_json['warnings'] = [warning_model] - image_details_list_model_json['trace'] = 'testString' - - # Construct a model instance of ImageDetailsList by calling from_dict on the json representation - image_details_list_model = ImageDetailsList.from_dict(image_details_list_model_json) - assert image_details_list_model != False - - # Construct a model instance of ImageDetailsList by calling from_dict on the json representation - image_details_list_model_dict = ImageDetailsList.from_dict(image_details_list_model_json).__dict__ - image_details_list_model2 = ImageDetailsList(**image_details_list_model_dict) - - # Verify the model instances are equivalent - assert image_details_list_model == image_details_list_model2 - - # Convert model instance back to dict and verify no loss of data - image_details_list_model_json2 = image_details_list_model.to_dict() - assert image_details_list_model_json2 == image_details_list_model_json - -class TestModel_ImageDimensions(): - """ - Test Class for ImageDimensions - """ - - def test_image_dimensions_serialization(self): - """ - Test serialization/deserialization for ImageDimensions - """ - - # Construct a json representation of a ImageDimensions model - image_dimensions_model_json = {} - image_dimensions_model_json['height'] = 38 - image_dimensions_model_json['width'] = 38 - - # Construct a model instance of ImageDimensions by calling from_dict on the json representation - image_dimensions_model = ImageDimensions.from_dict(image_dimensions_model_json) - assert image_dimensions_model != False - - # Construct a model instance of ImageDimensions by calling from_dict on the json representation - image_dimensions_model_dict = ImageDimensions.from_dict(image_dimensions_model_json).__dict__ - image_dimensions_model2 = ImageDimensions(**image_dimensions_model_dict) - - # Verify the model instances are equivalent - assert image_dimensions_model == image_dimensions_model2 - - # Convert model instance back to dict and verify no loss of data - image_dimensions_model_json2 = image_dimensions_model.to_dict() - assert image_dimensions_model_json2 == image_dimensions_model_json - -class TestModel_ImageSource(): - """ - Test Class for ImageSource - """ - - def test_image_source_serialization(self): - """ - Test serialization/deserialization for ImageSource - """ - - # Construct a json representation of a ImageSource model - image_source_model_json = {} - image_source_model_json['type'] = 'file' - image_source_model_json['filename'] = 'testString' - image_source_model_json['archive_filename'] = 'testString' - image_source_model_json['source_url'] = 'testString' - image_source_model_json['resolved_url'] = 'testString' - - # Construct a model instance of ImageSource by calling from_dict on the json representation - image_source_model = ImageSource.from_dict(image_source_model_json) - assert image_source_model != False - - # Construct a model instance of ImageSource by calling from_dict on the json representation - image_source_model_dict = ImageSource.from_dict(image_source_model_json).__dict__ - image_source_model2 = ImageSource(**image_source_model_dict) - - # Verify the model instances are equivalent - assert image_source_model == image_source_model2 - - # Convert model instance back to dict and verify no loss of data - image_source_model_json2 = image_source_model.to_dict() - assert image_source_model_json2 == image_source_model_json - -class TestModel_ImageSummary(): - """ - Test Class for ImageSummary - """ - - def test_image_summary_serialization(self): - """ - Test serialization/deserialization for ImageSummary - """ - - # Construct a json representation of a ImageSummary model - image_summary_model_json = {} - image_summary_model_json['image_id'] = 'testString' - image_summary_model_json['updated'] = "2019-01-01T12:00:00Z" - - # Construct a model instance of ImageSummary by calling from_dict on the json representation - image_summary_model = ImageSummary.from_dict(image_summary_model_json) - assert image_summary_model != False - - # Construct a model instance of ImageSummary by calling from_dict on the json representation - image_summary_model_dict = ImageSummary.from_dict(image_summary_model_json).__dict__ - image_summary_model2 = ImageSummary(**image_summary_model_dict) - - # Verify the model instances are equivalent - assert image_summary_model == image_summary_model2 - - # Convert model instance back to dict and verify no loss of data - image_summary_model_json2 = image_summary_model.to_dict() - assert image_summary_model_json2 == image_summary_model_json - -class TestModel_ImageSummaryList(): - """ - Test Class for ImageSummaryList - """ - - def test_image_summary_list_serialization(self): - """ - Test serialization/deserialization for ImageSummaryList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - image_summary_model = {} # ImageSummary - image_summary_model['image_id'] = 'testString' - image_summary_model['updated'] = "2019-01-01T12:00:00Z" - - # Construct a json representation of a ImageSummaryList model - image_summary_list_model_json = {} - image_summary_list_model_json['images'] = [image_summary_model] - - # Construct a model instance of ImageSummaryList by calling from_dict on the json representation - image_summary_list_model = ImageSummaryList.from_dict(image_summary_list_model_json) - assert image_summary_list_model != False - - # Construct a model instance of ImageSummaryList by calling from_dict on the json representation - image_summary_list_model_dict = ImageSummaryList.from_dict(image_summary_list_model_json).__dict__ - image_summary_list_model2 = ImageSummaryList(**image_summary_list_model_dict) - - # Verify the model instances are equivalent - assert image_summary_list_model == image_summary_list_model2 - - # Convert model instance back to dict and verify no loss of data - image_summary_list_model_json2 = image_summary_list_model.to_dict() - assert image_summary_list_model_json2 == image_summary_list_model_json - -class TestModel_Location(): - """ - Test Class for Location - """ - - def test_location_serialization(self): - """ - Test serialization/deserialization for Location - """ - - # Construct a json representation of a Location model - location_model_json = {} - location_model_json['top'] = 38 - location_model_json['left'] = 38 - location_model_json['width'] = 38 - location_model_json['height'] = 38 - - # Construct a model instance of Location by calling from_dict on the json representation - location_model = Location.from_dict(location_model_json) - assert location_model != False - - # Construct a model instance of Location by calling from_dict on the json representation - location_model_dict = Location.from_dict(location_model_json).__dict__ - location_model2 = Location(**location_model_dict) - - # Verify the model instances are equivalent - assert location_model == location_model2 - - # Convert model instance back to dict and verify no loss of data - location_model_json2 = location_model.to_dict() - assert location_model_json2 == location_model_json - -class TestModel_ObjectDetail(): - """ - Test Class for ObjectDetail - """ - - def test_object_detail_serialization(self): - """ - Test serialization/deserialization for ObjectDetail - """ - - # Construct dict forms of any model objects needed in order to build this model. - - object_detail_location_model = {} # ObjectDetailLocation - object_detail_location_model['top'] = 38 - object_detail_location_model['left'] = 38 - object_detail_location_model['width'] = 38 - object_detail_location_model['height'] = 38 - - # Construct a json representation of a ObjectDetail model - object_detail_model_json = {} - object_detail_model_json['object'] = 'testString' - object_detail_model_json['location'] = object_detail_location_model - object_detail_model_json['score'] = 72.5 - - # Construct a model instance of ObjectDetail by calling from_dict on the json representation - object_detail_model = ObjectDetail.from_dict(object_detail_model_json) - assert object_detail_model != False - - # Construct a model instance of ObjectDetail by calling from_dict on the json representation - object_detail_model_dict = ObjectDetail.from_dict(object_detail_model_json).__dict__ - object_detail_model2 = ObjectDetail(**object_detail_model_dict) - - # Verify the model instances are equivalent - assert object_detail_model == object_detail_model2 - - # Convert model instance back to dict and verify no loss of data - object_detail_model_json2 = object_detail_model.to_dict() - assert object_detail_model_json2 == object_detail_model_json - -class TestModel_ObjectDetailLocation(): - """ - Test Class for ObjectDetailLocation - """ - - def test_object_detail_location_serialization(self): - """ - Test serialization/deserialization for ObjectDetailLocation - """ - - # Construct a json representation of a ObjectDetailLocation model - object_detail_location_model_json = {} - object_detail_location_model_json['top'] = 38 - object_detail_location_model_json['left'] = 38 - object_detail_location_model_json['width'] = 38 - object_detail_location_model_json['height'] = 38 - - # Construct a model instance of ObjectDetailLocation by calling from_dict on the json representation - object_detail_location_model = ObjectDetailLocation.from_dict(object_detail_location_model_json) - assert object_detail_location_model != False - - # Construct a model instance of ObjectDetailLocation by calling from_dict on the json representation - object_detail_location_model_dict = ObjectDetailLocation.from_dict(object_detail_location_model_json).__dict__ - object_detail_location_model2 = ObjectDetailLocation(**object_detail_location_model_dict) - - # Verify the model instances are equivalent - assert object_detail_location_model == object_detail_location_model2 - - # Convert model instance back to dict and verify no loss of data - object_detail_location_model_json2 = object_detail_location_model.to_dict() - assert object_detail_location_model_json2 == object_detail_location_model_json - -class TestModel_ObjectMetadata(): - """ - Test Class for ObjectMetadata - """ - - def test_object_metadata_serialization(self): - """ - Test serialization/deserialization for ObjectMetadata - """ - - # Construct a json representation of a ObjectMetadata model - object_metadata_model_json = {} - object_metadata_model_json['object'] = 'testString' - object_metadata_model_json['count'] = 38 - - # Construct a model instance of ObjectMetadata by calling from_dict on the json representation - object_metadata_model = ObjectMetadata.from_dict(object_metadata_model_json) - assert object_metadata_model != False - - # Construct a model instance of ObjectMetadata by calling from_dict on the json representation - object_metadata_model_dict = ObjectMetadata.from_dict(object_metadata_model_json).__dict__ - object_metadata_model2 = ObjectMetadata(**object_metadata_model_dict) - - # Verify the model instances are equivalent - assert object_metadata_model == object_metadata_model2 - - # Convert model instance back to dict and verify no loss of data - object_metadata_model_json2 = object_metadata_model.to_dict() - assert object_metadata_model_json2 == object_metadata_model_json - -class TestModel_ObjectMetadataList(): - """ - Test Class for ObjectMetadataList - """ - - def test_object_metadata_list_serialization(self): - """ - Test serialization/deserialization for ObjectMetadataList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - object_metadata_model = {} # ObjectMetadata - object_metadata_model['object'] = 'testString' - object_metadata_model['count'] = 38 - - # Construct a json representation of a ObjectMetadataList model - object_metadata_list_model_json = {} - object_metadata_list_model_json['object_count'] = 38 - object_metadata_list_model_json['objects'] = [object_metadata_model] - - # Construct a model instance of ObjectMetadataList by calling from_dict on the json representation - object_metadata_list_model = ObjectMetadataList.from_dict(object_metadata_list_model_json) - assert object_metadata_list_model != False - - # Construct a model instance of ObjectMetadataList by calling from_dict on the json representation - object_metadata_list_model_dict = ObjectMetadataList.from_dict(object_metadata_list_model_json).__dict__ - object_metadata_list_model2 = ObjectMetadataList(**object_metadata_list_model_dict) - - # Verify the model instances are equivalent - assert object_metadata_list_model == object_metadata_list_model2 - - # Convert model instance back to dict and verify no loss of data - object_metadata_list_model_json2 = object_metadata_list_model.to_dict() - assert object_metadata_list_model_json2 == object_metadata_list_model_json - -class TestModel_ObjectTrainingStatus(): - """ - Test Class for ObjectTrainingStatus - """ - - def test_object_training_status_serialization(self): - """ - Test serialization/deserialization for ObjectTrainingStatus - """ - - # Construct a json representation of a ObjectTrainingStatus model - object_training_status_model_json = {} - object_training_status_model_json['ready'] = True - object_training_status_model_json['in_progress'] = True - object_training_status_model_json['data_changed'] = True - object_training_status_model_json['latest_failed'] = True - object_training_status_model_json['rscnn_ready'] = True - object_training_status_model_json['description'] = 'testString' - - # Construct a model instance of ObjectTrainingStatus by calling from_dict on the json representation - object_training_status_model = ObjectTrainingStatus.from_dict(object_training_status_model_json) - assert object_training_status_model != False - - # Construct a model instance of ObjectTrainingStatus by calling from_dict on the json representation - object_training_status_model_dict = ObjectTrainingStatus.from_dict(object_training_status_model_json).__dict__ - object_training_status_model2 = ObjectTrainingStatus(**object_training_status_model_dict) - - # Verify the model instances are equivalent - assert object_training_status_model == object_training_status_model2 - - # Convert model instance back to dict and verify no loss of data - object_training_status_model_json2 = object_training_status_model.to_dict() - assert object_training_status_model_json2 == object_training_status_model_json - -class TestModel_TrainingDataObject(): - """ - Test Class for TrainingDataObject - """ - - def test_training_data_object_serialization(self): - """ - Test serialization/deserialization for TrainingDataObject - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['top'] = 38 - location_model['left'] = 38 - location_model['width'] = 38 - location_model['height'] = 38 - - # Construct a json representation of a TrainingDataObject model - training_data_object_model_json = {} - training_data_object_model_json['object'] = 'testString' - training_data_object_model_json['location'] = location_model - - # Construct a model instance of TrainingDataObject by calling from_dict on the json representation - training_data_object_model = TrainingDataObject.from_dict(training_data_object_model_json) - assert training_data_object_model != False - - # Construct a model instance of TrainingDataObject by calling from_dict on the json representation - training_data_object_model_dict = TrainingDataObject.from_dict(training_data_object_model_json).__dict__ - training_data_object_model2 = TrainingDataObject(**training_data_object_model_dict) - - # Verify the model instances are equivalent - assert training_data_object_model == training_data_object_model2 - - # Convert model instance back to dict and verify no loss of data - training_data_object_model_json2 = training_data_object_model.to_dict() - assert training_data_object_model_json2 == training_data_object_model_json - -class TestModel_TrainingDataObjects(): - """ - Test Class for TrainingDataObjects - """ - - def test_training_data_objects_serialization(self): - """ - Test serialization/deserialization for TrainingDataObjects - """ - - # Construct dict forms of any model objects needed in order to build this model. - - location_model = {} # Location - location_model['top'] = 38 - location_model['left'] = 38 - location_model['width'] = 38 - location_model['height'] = 38 - - training_data_object_model = {} # TrainingDataObject - training_data_object_model['object'] = 'testString' - training_data_object_model['location'] = location_model - - # Construct a json representation of a TrainingDataObjects model - training_data_objects_model_json = {} - training_data_objects_model_json['objects'] = [training_data_object_model] - - # Construct a model instance of TrainingDataObjects by calling from_dict on the json representation - training_data_objects_model = TrainingDataObjects.from_dict(training_data_objects_model_json) - assert training_data_objects_model != False - - # Construct a model instance of TrainingDataObjects by calling from_dict on the json representation - training_data_objects_model_dict = TrainingDataObjects.from_dict(training_data_objects_model_json).__dict__ - training_data_objects_model2 = TrainingDataObjects(**training_data_objects_model_dict) - - # Verify the model instances are equivalent - assert training_data_objects_model == training_data_objects_model2 - - # Convert model instance back to dict and verify no loss of data - training_data_objects_model_json2 = training_data_objects_model.to_dict() - assert training_data_objects_model_json2 == training_data_objects_model_json - -class TestModel_TrainingEvent(): - """ - Test Class for TrainingEvent - """ - - def test_training_event_serialization(self): - """ - Test serialization/deserialization for TrainingEvent - """ - - # Construct a json representation of a TrainingEvent model - training_event_model_json = {} - training_event_model_json['type'] = 'objects' - training_event_model_json['collection_id'] = 'testString' - training_event_model_json['completion_time'] = "2019-01-01T12:00:00Z" - training_event_model_json['status'] = 'failed' - training_event_model_json['image_count'] = 38 - - # Construct a model instance of TrainingEvent by calling from_dict on the json representation - training_event_model = TrainingEvent.from_dict(training_event_model_json) - assert training_event_model != False - - # Construct a model instance of TrainingEvent by calling from_dict on the json representation - training_event_model_dict = TrainingEvent.from_dict(training_event_model_json).__dict__ - training_event_model2 = TrainingEvent(**training_event_model_dict) - - # Verify the model instances are equivalent - assert training_event_model == training_event_model2 - - # Convert model instance back to dict and verify no loss of data - training_event_model_json2 = training_event_model.to_dict() - assert training_event_model_json2 == training_event_model_json - -class TestModel_TrainingEvents(): - """ - Test Class for TrainingEvents - """ - - def test_training_events_serialization(self): - """ - Test serialization/deserialization for TrainingEvents - """ - - # Construct dict forms of any model objects needed in order to build this model. - - training_event_model = {} # TrainingEvent - training_event_model['type'] = 'objects' - training_event_model['collection_id'] = 'testString' - training_event_model['completion_time'] = "2019-01-01T12:00:00Z" - training_event_model['status'] = 'failed' - training_event_model['image_count'] = 38 - - # Construct a json representation of a TrainingEvents model - training_events_model_json = {} - training_events_model_json['start_time'] = "2019-01-01T12:00:00Z" - training_events_model_json['end_time'] = "2019-01-01T12:00:00Z" - training_events_model_json['completed_events'] = 38 - training_events_model_json['trained_images'] = 38 - training_events_model_json['events'] = [training_event_model] - - # Construct a model instance of TrainingEvents by calling from_dict on the json representation - training_events_model = TrainingEvents.from_dict(training_events_model_json) - assert training_events_model != False - - # Construct a model instance of TrainingEvents by calling from_dict on the json representation - training_events_model_dict = TrainingEvents.from_dict(training_events_model_json).__dict__ - training_events_model2 = TrainingEvents(**training_events_model_dict) - - # Verify the model instances are equivalent - assert training_events_model == training_events_model2 - - # Convert model instance back to dict and verify no loss of data - training_events_model_json2 = training_events_model.to_dict() - assert training_events_model_json2 == training_events_model_json - -class TestModel_TrainingStatus(): - """ - Test Class for TrainingStatus - """ - - def test_training_status_serialization(self): - """ - Test serialization/deserialization for TrainingStatus - """ - - # Construct dict forms of any model objects needed in order to build this model. - - object_training_status_model = {} # ObjectTrainingStatus - object_training_status_model['ready'] = True - object_training_status_model['in_progress'] = True - object_training_status_model['data_changed'] = True - object_training_status_model['latest_failed'] = True - object_training_status_model['rscnn_ready'] = True - object_training_status_model['description'] = 'testString' - - # Construct a json representation of a TrainingStatus model - training_status_model_json = {} - training_status_model_json['objects'] = object_training_status_model - - # Construct a model instance of TrainingStatus by calling from_dict on the json representation - training_status_model = TrainingStatus.from_dict(training_status_model_json) - assert training_status_model != False - - # Construct a model instance of TrainingStatus by calling from_dict on the json representation - training_status_model_dict = TrainingStatus.from_dict(training_status_model_json).__dict__ - training_status_model2 = TrainingStatus(**training_status_model_dict) - - # Verify the model instances are equivalent - assert training_status_model == training_status_model2 - - # Convert model instance back to dict and verify no loss of data - training_status_model_json2 = training_status_model.to_dict() - assert training_status_model_json2 == training_status_model_json - -class TestModel_UpdateObjectMetadata(): - """ - Test Class for UpdateObjectMetadata - """ - - def test_update_object_metadata_serialization(self): - """ - Test serialization/deserialization for UpdateObjectMetadata - """ - - # Construct a json representation of a UpdateObjectMetadata model - update_object_metadata_model_json = {} - update_object_metadata_model_json['object'] = 'testString' - update_object_metadata_model_json['count'] = 38 - - # Construct a model instance of UpdateObjectMetadata by calling from_dict on the json representation - update_object_metadata_model = UpdateObjectMetadata.from_dict(update_object_metadata_model_json) - assert update_object_metadata_model != False - - # Construct a model instance of UpdateObjectMetadata by calling from_dict on the json representation - update_object_metadata_model_dict = UpdateObjectMetadata.from_dict(update_object_metadata_model_json).__dict__ - update_object_metadata_model2 = UpdateObjectMetadata(**update_object_metadata_model_dict) - - # Verify the model instances are equivalent - assert update_object_metadata_model == update_object_metadata_model2 - - # Convert model instance back to dict and verify no loss of data - update_object_metadata_model_json2 = update_object_metadata_model.to_dict() - assert update_object_metadata_model_json2 == update_object_metadata_model_json - -class TestModel_Warning(): - """ - Test Class for Warning - """ - - def test_warning_serialization(self): - """ - Test serialization/deserialization for Warning - """ - - # Construct a json representation of a Warning model - warning_model_json = {} - warning_model_json['code'] = 'invalid_field' - warning_model_json['message'] = 'testString' - warning_model_json['more_info'] = 'testString' - - # Construct a model instance of Warning by calling from_dict on the json representation - warning_model = Warning.from_dict(warning_model_json) - assert warning_model != False - - # Construct a model instance of Warning by calling from_dict on the json representation - warning_model_dict = Warning.from_dict(warning_model_json).__dict__ - warning_model2 = Warning(**warning_model_dict) - - # Verify the model instances are equivalent - assert warning_model == warning_model2 - - # Convert model instance back to dict and verify no loss of data - warning_model_json2 = warning_model.to_dict() - assert warning_model_json2 == warning_model_json - -class TestModel_FileWithMetadata(): - """ - Test Class for FileWithMetadata - """ - - def test_file_with_metadata_serialization(self): - """ - Test serialization/deserialization for FileWithMetadata - """ - - # Construct a json representation of a FileWithMetadata model - file_with_metadata_model_json = {} - file_with_metadata_model_json['data'] = io.BytesIO(b'This is a mock file.').getvalue() - file_with_metadata_model_json['filename'] = 'testString' - file_with_metadata_model_json['content_type'] = 'testString' - - # Construct a model instance of FileWithMetadata by calling from_dict on the json representation - file_with_metadata_model = FileWithMetadata.from_dict(file_with_metadata_model_json) - assert file_with_metadata_model != False - - # Construct a model instance of FileWithMetadata by calling from_dict on the json representation - file_with_metadata_model_dict = FileWithMetadata.from_dict(file_with_metadata_model_json).__dict__ - file_with_metadata_model2 = FileWithMetadata(**file_with_metadata_model_dict) - - # Verify the model instances are equivalent - assert file_with_metadata_model == file_with_metadata_model2 - - # Convert model instance back to dict and verify no loss of data - file_with_metadata_model_json2 = file_with_metadata_model.to_dict() - assert file_with_metadata_model_json2 == file_with_metadata_model_json - - -# endregion -############################################################################## -# End of Model Tests -############################################################################## From fbcebd088c205070e9bae22821b2a2e8920a07c5 Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Wed, 10 Aug 2022 09:13:25 -0500 Subject: [PATCH 368/455] feat(assistant-v1): update models and add new methods New methods are createWorkspaceAsync, updateWorkspaceAsync, exportWorkspaceAsync --- ibm_watson/assistant_v1.py | 653 ++++++++++++++- test/unit/test_assistant_v1.py | 1402 +++++++++++++++++++++++++------- 2 files changed, 1737 insertions(+), 318 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index bbdb45f5b..ee13305c3 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -48,7 +48,7 @@ class AssistantV1(BaseService): """The Assistant V1 service.""" DEFAULT_SERVICE_URL = 'https://api.us-south.assistant.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'assistant' + DEFAULT_SERVICE_NAME = 'conversation' def __init__( self, @@ -176,6 +176,7 @@ def message(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -235,6 +236,7 @@ def bulk_classify(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -303,6 +305,7 @@ def list_workspaces(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/workspaces' @@ -334,6 +337,8 @@ def create_workspace(self, Create a workspace based on component objects. You must provide workspace components defining the content of the new workspace. + **Note:** The new workspace data cannot be larger than 1.5 MB. For larger + requests, use the **Create workspace asynchronously** method. :param str name: (optional) The name of the workspace. This string cannot contain carriage return, newline, or tab characters. @@ -402,6 +407,7 @@ def create_workspace(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/workspaces' @@ -459,6 +465,7 @@ def get_workspace(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -495,6 +502,8 @@ def update_workspace(self, Update an existing workspace with new or modified data. You must provide component objects defining the content of the updated workspace. + **Note:** The new workspace data cannot be larger than 1.5 MB. For larger + requests, use the **Update workspace asynchronously** method. :param str workspace_id: Unique identifier of the workspace. :param str name: (optional) The name of the workspace. This string cannot @@ -579,6 +588,7 @@ def update_workspace(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -618,6 +628,7 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -632,6 +643,294 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response + def create_workspace_async( + self, + *, + name: str = None, + description: str = None, + language: str = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, + metadata: dict = None, + learning_opt_out: bool = None, + system_settings: 'WorkspaceSystemSettings' = None, + webhooks: List['Webhook'] = None, + intents: List['CreateIntent'] = None, + entities: List['CreateEntity'] = None, + **kwargs) -> DetailedResponse: + """ + Create workspace asynchronously. + + Create a workspace asynchronously based on component objects. You must provide + workspace components defining the content of the new workspace. + A successful call to this method only initiates asynchronous creation of the + workspace. The new workspace is not available until processing completes. To check + the status of the asynchronous operation, use the **Export workspace + asynchronously** method. + + :param str name: (optional) The name of the workspace. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the workspace. This + string cannot contain carriage return, newline, or tab characters. + :param str language: (optional) The language of the workspace. + :param List[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. + :param List[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. + :param dict metadata: (optional) Any metadata related to the workspace. + :param bool learning_opt_out: (optional) Whether training data from the + workspace (including artifacts such as intents and entities) can be used by + IBM for general service improvements. `true` indicates that workspace + training data is not to be used. + :param WorkspaceSystemSettings system_settings: (optional) Global settings + for the workspace. + :param List[Webhook] webhooks: (optional) + :param List[CreateIntent] intents: (optional) An array of objects defining + the intents for the workspace. + :param List[CreateEntity] entities: (optional) An array of objects + describing the entities for the workspace. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Workspace` object + """ + + if dialog_nodes is not None: + dialog_nodes = [convert_model(x) for x in dialog_nodes] + if counterexamples is not None: + counterexamples = [convert_model(x) for x in counterexamples] + if system_settings is not None: + system_settings = convert_model(system_settings) + if webhooks is not None: + webhooks = [convert_model(x) for x in webhooks] + if intents is not None: + intents = [convert_model(x) for x in intents] + if entities is not None: + entities = [convert_model(x) for x in entities] + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_workspace_async') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'name': name, + 'description': description, + 'language': language, + 'dialog_nodes': dialog_nodes, + 'counterexamples': counterexamples, + 'metadata': metadata, + 'learning_opt_out': learning_opt_out, + 'system_settings': system_settings, + 'webhooks': webhooks, + 'intents': intents, + 'entities': entities + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v1/workspaces_async' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def update_workspace_async( + self, + workspace_id: str, + *, + name: str = None, + description: str = None, + language: str = None, + dialog_nodes: List['DialogNode'] = None, + counterexamples: List['Counterexample'] = None, + metadata: dict = None, + learning_opt_out: bool = None, + system_settings: 'WorkspaceSystemSettings' = None, + webhooks: List['Webhook'] = None, + intents: List['CreateIntent'] = None, + entities: List['CreateEntity'] = None, + append: bool = None, + **kwargs) -> DetailedResponse: + """ + Update workspace asynchronously. + + Update an existing workspace asynchronously with new or modified data. You must + provide component objects defining the content of the updated workspace. + A successful call to this method only initiates an asynchronous update of the + workspace. The updated workspace is not available until processing completes. To + check the status of the asynchronous operation, use the **Export workspace + asynchronously** method. + + :param str workspace_id: Unique identifier of the workspace. + :param str name: (optional) The name of the workspace. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the workspace. This + string cannot contain carriage return, newline, or tab characters. + :param str language: (optional) The language of the workspace. + :param List[DialogNode] dialog_nodes: (optional) An array of objects + describing the dialog nodes in the workspace. + :param List[Counterexample] counterexamples: (optional) An array of objects + defining input examples that have been marked as irrelevant input. + :param dict metadata: (optional) Any metadata related to the workspace. + :param bool learning_opt_out: (optional) Whether training data from the + workspace (including artifacts such as intents and entities) can be used by + IBM for general service improvements. `true` indicates that workspace + training data is not to be used. + :param WorkspaceSystemSettings system_settings: (optional) Global settings + for the workspace. + :param List[Webhook] webhooks: (optional) + :param List[CreateIntent] intents: (optional) An array of objects defining + the intents for the workspace. + :param List[CreateEntity] entities: (optional) An array of objects + describing the entities for the workspace. + :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 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 dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Workspace` object + """ + + if workspace_id is None: + raise ValueError('workspace_id must be provided') + if dialog_nodes is not None: + dialog_nodes = [convert_model(x) for x in dialog_nodes] + if counterexamples is not None: + counterexamples = [convert_model(x) for x in counterexamples] + if system_settings is not None: + system_settings = convert_model(system_settings) + if webhooks is not None: + webhooks = [convert_model(x) for x in webhooks] + if intents is not None: + intents = [convert_model(x) for x in intents] + if entities is not None: + entities = [convert_model(x) for x in entities] + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_workspace_async') + headers.update(sdk_headers) + + params = {'version': self.version, 'append': append} + + data = { + 'name': name, + 'description': description, + 'language': language, + 'dialog_nodes': dialog_nodes, + 'counterexamples': counterexamples, + 'metadata': metadata, + 'learning_opt_out': learning_opt_out, + 'system_settings': system_settings, + 'webhooks': webhooks, + 'intents': intents, + 'entities': entities + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces_async/{workspace_id}'.format(**path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def export_workspace_async(self, + workspace_id: str, + *, + include_audit: bool = None, + sort: str = None, + verbose: bool = None, + **kwargs) -> DetailedResponse: + """ + Export workspace asynchronously. + + Export the entire workspace asynchronously, including all workspace content. + A successful call to this method only initiates an asynchronous export. The + exported JSON data is not available until processing completes. After the initial + request is submitted, you can continue to poll by calling the same request again + and checking the value of the **status** property. When processing has completed, + the request returns the exported JSON data. Remember that the usual rate limits + apply. + + :param str workspace_id: Unique identifier of the workspace. + :param bool include_audit: (optional) Whether to include the audit + properties (`created` and `updated` timestamps) in the response. + :param str sort: (optional) Indicates how the returned workspace data will + be sorted. Specify `sort=stable` to sort all workspace objects by unique + identifier, in ascending alphabetical order. + :param bool verbose: (optional) Whether the response should include the + `counts` property, which indicates how many of each component (such as + intents and entities) the workspace contains. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Workspace` object + """ + + if workspace_id is None: + raise ValueError('workspace_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='export_workspace_async') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'include_audit': include_audit, + 'sort': sort, + 'verbose': verbose + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['workspace_id'] + path_param_values = self.encode_path_vars(workspace_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v1/workspaces_async/{workspace_id}/export'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + ######################### # Intents ######################### @@ -694,6 +993,7 @@ def list_intents(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -765,6 +1065,7 @@ def create_intent(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -823,6 +1124,7 @@ def get_intent(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -912,6 +1214,7 @@ def update_intent(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -956,6 +1259,7 @@ def delete_intent(self, workspace_id: str, intent: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -1032,6 +1336,7 @@ def list_examples(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -1100,6 +1405,7 @@ def create_example(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent'] @@ -1154,6 +1460,7 @@ def get_example(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent', 'text'] @@ -1224,6 +1531,7 @@ def update_example(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent', 'text'] @@ -1271,6 +1579,7 @@ def delete_example(self, workspace_id: str, intent: str, text: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'intent', 'text'] @@ -1343,6 +1652,7 @@ def list_counterexamples(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -1403,6 +1713,7 @@ def create_counterexample(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -1455,6 +1766,7 @@ def get_counterexample(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'text'] @@ -1516,6 +1828,7 @@ def update_counterexample(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'text'] @@ -1562,6 +1875,7 @@ def delete_counterexample(self, workspace_id: str, text: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'text'] @@ -1639,6 +1953,7 @@ def list_entities(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -1719,6 +2034,7 @@ def create_entity(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -1777,6 +2093,7 @@ def get_entity(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -1873,6 +2190,7 @@ def update_entity(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -1917,6 +2235,7 @@ def delete_entity(self, workspace_id: str, entity: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -1980,6 +2299,7 @@ def list_mentions(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -2061,6 +2381,7 @@ def list_values(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -2147,6 +2468,7 @@ def create_value(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity'] @@ -2210,6 +2532,7 @@ def get_value(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2315,6 +2638,7 @@ def update_value(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2362,6 +2686,7 @@ def delete_value(self, workspace_id: str, entity: str, value: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2441,6 +2766,7 @@ def list_synonyms(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2509,6 +2835,7 @@ def create_synonym(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value'] @@ -2567,6 +2894,7 @@ def get_synonym(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] @@ -2638,6 +2966,7 @@ def update_synonym(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] @@ -2689,6 +3018,7 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'entity', 'value', 'synonym'] @@ -2761,6 +3091,7 @@ def list_dialog_nodes(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -2912,6 +3243,7 @@ def create_dialog_node(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -2963,6 +3295,7 @@ def get_dialog_node(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'dialog_node'] @@ -3119,6 +3452,7 @@ def update_dialog_node(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'dialog_node'] @@ -3164,6 +3498,7 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id', 'dialog_node'] @@ -3196,6 +3531,10 @@ def list_logs(self, List the events from the log of a specific workspace. This method requires Manager access. + **Note:** If you use the **cursor** parameter to retrieve results one page at a + time, subsequent requests must be no more than 5 minutes apart. Any returned value + for the **cursor** parameter becomes invalid after 5 minutes. For more information + about using pagination, see [Pagination](#pagination). :param str workspace_id: Unique identifier of the workspace. :param str sort: (optional) How to sort the returned log events. You can @@ -3231,6 +3570,7 @@ def list_logs(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['workspace_id'] @@ -3256,6 +3596,10 @@ def list_all_logs(self, List log events in all workspaces. List the events from the logs of all workspaces in the service instance. + **Note:** If you use the **cursor** parameter to retrieve results one page at a + time, subsequent requests must be no more than 5 minutes apart. Any returned value + for the **cursor** parameter becomes invalid after 5 minutes. For more information + about using pagination, see [Pagination](#pagination). :param str filter: A cacheable parameter that limits the results to those matching the specified filter. You must specify a filter query that @@ -3295,6 +3639,7 @@ def list_all_logs(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/logs' @@ -3345,6 +3690,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/user_data' @@ -3385,6 +3731,19 @@ class Sort(str, Enum): STABLE = 'stable' +class ExportWorkspaceAsyncEnums: + """ + Enums for export_workspace_async parameters. + """ + + class Sort(str, Enum): + """ + Indicates how the returned workspace data will be sorted. Specify `sort=stable` to + sort all workspace objects by unique identifier, in ascending alphabetical order. + """ + STABLE = 'stable' + + class ListIntentsEnums: """ Enums for list_intents parameters. @@ -8988,17 +9347,20 @@ class RuntimeIntent(): An intent identified in the user input. :attr str intent: The name of the recognized intent. - :attr float confidence: A decimal percentage that represents Watson's confidence - in the intent. + :attr float confidence: (optional) A decimal percentage that represents Watson's + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. """ - def __init__(self, intent: str, confidence: float) -> None: + def __init__(self, intent: str, *, confidence: float = None) -> None: """ Initialize a RuntimeIntent object. :param str intent: The name of the recognized intent. - :param float confidence: A decimal percentage that represents Watson's - confidence in the intent. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the intent. If you are specifying an intent as part + of a request, but you do not have a calculated confidence value, specify + `1`. """ self.intent = intent self.confidence = confidence @@ -9015,10 +9377,6 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': ) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') - else: - raise ValueError( - 'Required property \'confidence\' not present in RuntimeIntent JSON' - ) return cls(**args) @classmethod @@ -9143,6 +9501,61 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) +class StatusError(): + """ + An object describing an error that occurred during processing of an asynchronous + operation. + + :attr str message: (optional) The text of the error message. + """ + + def __init__(self, *, message: str = None) -> None: + """ + Initialize a StatusError object. + + :param str message: (optional) The text of the error message. + """ + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatusError': + """Initialize a StatusError object from a json dictionary.""" + args = {} + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatusError 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, 'message') and self.message is not None: + _dict['message'] = self.message + 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 StatusError object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatusError') -> 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: 'StatusError') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Synonym(): """ Synonym. @@ -9681,11 +10094,27 @@ class Workspace(): improvements. `true` indicates that workspace training data is not to be used. :attr WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. - :attr str status: (optional) The current status of the workspace. + :attr str status: (optional) The current status of the workspace: + - **Available**: The workspace is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. Returned only by + the **Export workspace asynchronously** method. + - **Non Existent**: The workspace does not exist. + - **Processing**: An asynchronous operation has not yet completed. Returned + only by the **Export workspace asynchronously** method. + - **Training**: The workspace is training based on new data such as intents or + examples. + :attr List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. :attr List[Webhook] webhooks: (optional) :attr List[Intent] intents: (optional) An array of intents. :attr List[Entity] entities: (optional) An array of objects describing the entities for the workspace. + :attr WorkspaceCounts counts: (optional) An object containing properties that + indicate how many intents, entities, and dialog nodes are defined in the + workspace. This property is included only in responses from the **Export + workspace asynchronously** method, and only when the **verbose** query parameter + is set to `true`. """ def __init__(self, @@ -9702,9 +10131,11 @@ def __init__(self, metadata: dict = None, system_settings: 'WorkspaceSystemSettings' = None, status: str = None, + status_errors: List['StatusError'] = None, webhooks: List['Webhook'] = None, intents: List['Intent'] = None, - entities: List['Entity'] = None) -> None: + entities: List['Entity'] = None, + counts: 'WorkspaceCounts' = None) -> None: """ Initialize a Workspace object. @@ -9728,6 +10159,11 @@ def __init__(self, :param List[Intent] intents: (optional) An array of intents. :param List[Entity] entities: (optional) An array of objects describing the entities for the workspace. + :param WorkspaceCounts counts: (optional) An object containing properties + that indicate how many intents, entities, and dialog nodes are defined in + the workspace. This property is included only in responses from the + **Export workspace asynchronously** method, and only when the **verbose** + query parameter is set to `true`. """ self.name = name self.description = description @@ -9741,9 +10177,11 @@ def __init__(self, self.learning_opt_out = learning_opt_out self.system_settings = system_settings self.status = status + self.status_errors = status_errors self.webhooks = webhooks self.intents = intents self.entities = entities + self.counts = counts @classmethod def from_dict(cls, _dict: Dict) -> 'Workspace': @@ -9789,6 +10227,10 @@ def from_dict(cls, _dict: Dict) -> 'Workspace': _dict.get('system_settings')) if 'status' in _dict: args['status'] = _dict.get('status') + if 'status_errors' in _dict: + args['status_errors'] = [ + StatusError.from_dict(x) for x in _dict.get('status_errors') + ] if 'webhooks' in _dict: args['webhooks'] = [ Webhook.from_dict(x) for x in _dict.get('webhooks') @@ -9801,6 +10243,8 @@ def from_dict(cls, _dict: Dict) -> 'Workspace': args['entities'] = [ Entity.from_dict(x) for x in _dict.get('entities') ] + if 'counts' in _dict: + args['counts'] = WorkspaceCounts.from_dict(_dict.get('counts')) return cls(**args) @classmethod @@ -9841,12 +10285,19 @@ def to_dict(self) -> Dict: _dict['system_settings'] = self.system_settings.to_dict() if hasattr(self, 'status') and getattr(self, 'status') is not None: _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + _dict['status_errors'] = [ + x.to_dict() for x in getattr(self, 'status_errors') + ] if hasattr(self, 'webhooks') and self.webhooks is not None: _dict['webhooks'] = [x.to_dict() for x in self.webhooks] if hasattr(self, 'intents') and self.intents is not None: _dict['intents'] = [x.to_dict() for x in self.intents] if hasattr(self, 'entities') and self.entities is not None: _dict['entities'] = [x.to_dict() for x in self.entities] + if hasattr(self, 'counts') and self.counts is not None: + _dict['counts'] = self.counts.to_dict() return _dict def _to_dict(self): @@ -9869,12 +10320,22 @@ def __ne__(self, other: 'Workspace') -> bool: class StatusEnum(str, Enum): """ - The current status of the workspace. + The current status of the workspace: + - **Available**: The workspace is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. Returned only by the + **Export workspace asynchronously** method. + - **Non Existent**: The workspace does not exist. + - **Processing**: An asynchronous operation has not yet completed. Returned only + by the **Export workspace asynchronously** method. + - **Training**: The workspace is training based on new data such as intents or + examples. """ + AVAILABLE = 'Available' + FAILED = 'Failed' NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' TRAINING = 'Training' - FAILED = 'Failed' - AVAILABLE = 'Available' UNAVAILABLE = 'Unavailable' @@ -9952,6 +10413,83 @@ def __ne__(self, other: 'WorkspaceCollection') -> bool: return not self == other +class WorkspaceCounts(): + """ + An object containing properties that indicate how many intents, entities, and dialog + nodes are defined in the workspace. This property is included only in responses from + the **Export workspace asynchronously** method, and only when the **verbose** query + parameter is set to `true`. + + :attr int intent: (optional) The number of intents defined in the workspace. + :attr int entity: (optional) The number of entities defined in the workspace. + :attr int node: (optional) The number of nodes defined in the workspace. + """ + + def __init__(self, + *, + intent: int = None, + entity: int = None, + node: int = None) -> None: + """ + Initialize a WorkspaceCounts object. + + :param int intent: (optional) The number of intents defined in the + workspace. + :param int entity: (optional) The number of entities defined in the + workspace. + :param int node: (optional) The number of nodes defined in the workspace. + """ + self.intent = intent + self.entity = entity + self.node = node + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WorkspaceCounts': + """Initialize a WorkspaceCounts object from a json dictionary.""" + args = {} + if 'intent' in _dict: + args['intent'] = _dict.get('intent') + if 'entity' in _dict: + args['entity'] = _dict.get('entity') + if 'node' in _dict: + args['node'] = _dict.get('node') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceCounts 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, 'intent') and self.intent is not None: + _dict['intent'] = self.intent + if hasattr(self, 'entity') and self.entity is not None: + _dict['entity'] = self.entity + if hasattr(self, 'node') and self.node is not None: + _dict['node'] = self.node + 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 WorkspaceCounts object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'WorkspaceCounts') -> 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: 'WorkspaceCounts') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class WorkspaceSystemSettings(): """ Global settings for the workspace. @@ -9973,13 +10511,15 @@ class WorkspaceSystemSettings(): Workspace settings related to the behavior of system entities. :attr WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings related to detection of irrelevant input. + :attr WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings related to + the version of the training algorithms currently used by the skill. """ # The set of defined properties for the class _properties = frozenset([ 'tooling', 'disambiguation', 'human_agent_assist', 'spelling_suggestions', 'spelling_auto_correct', 'system_entities', - 'off_topic' + 'off_topic', 'nlp' ]) def __init__( @@ -9992,6 +10532,7 @@ def __init__( spelling_auto_correct: bool = None, system_entities: 'WorkspaceSystemSettingsSystemEntities' = None, off_topic: 'WorkspaceSystemSettingsOffTopic' = None, + nlp: 'WorkspaceSystemSettingsNlp' = None, **kwargs) -> None: """ Initialize a WorkspaceSystemSettings object. @@ -10014,6 +10555,9 @@ def __init__( Workspace settings related to the behavior of system entities. :param WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings related to detection of irrelevant input. + :param WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings + related to the version of the training algorithms currently used by the + skill. :param **kwargs: (optional) Any additional properties. """ self.tooling = tooling @@ -10023,6 +10567,7 @@ def __init__( self.spelling_auto_correct = spelling_auto_correct self.system_entities = system_entities self.off_topic = off_topic + self.nlp = nlp for _key, _value in kwargs.items(): setattr(self, _key, _value) @@ -10050,6 +10595,8 @@ def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': if 'off_topic' in _dict: args['off_topic'] = WorkspaceSystemSettingsOffTopic.from_dict( _dict.get('off_topic')) + if 'nlp' in _dict: + args['nlp'] = WorkspaceSystemSettingsNlp.from_dict(_dict.get('nlp')) args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -10081,6 +10628,8 @@ def to_dict(self) -> Dict: _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() + if hasattr(self, 'nlp') and self.nlp is not None: + _dict['nlp'] = self.nlp.to_dict() for _key in [ k for k in vars(self).keys() if k not in WorkspaceSystemSettings._properties @@ -10270,6 +10819,76 @@ class SensitivityEnum(str, Enum): LOW = 'low' +class WorkspaceSystemSettingsNlp(): + """ + Workspace settings related to the version of the training algorithms currently used by + the skill. + + :attr str model: (optional) The policy the skill follows for selecting the + algorithm version to use: + - `baseline`: the latest mature version + - `beta`: the latest beta version. + """ + + def __init__(self, *, model: str = None) -> None: + """ + Initialize a WorkspaceSystemSettingsNlp object. + + :param str model: (optional) The policy the skill follows for selecting the + algorithm version to use: + - `baseline`: the latest mature version + - `beta`: the latest beta version. + """ + self.model = model + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsNlp': + """Initialize a WorkspaceSystemSettingsNlp object from a json dictionary.""" + args = {} + if 'model' in _dict: + args['model'] = _dict.get('model') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WorkspaceSystemSettingsNlp 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, 'model') and self.model is not None: + _dict['model'] = self.model + 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 WorkspaceSystemSettingsNlp object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'WorkspaceSystemSettingsNlp') -> 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: 'WorkspaceSystemSettingsNlp') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ModelEnum(str, Enum): + """ + The policy the skill follows for selecting the algorithm version to use: + - `baseline`: the latest mature version + - `beta`: the latest beta version. + """ + BASELINE = 'baseline' + BETA = 'beta' + + class WorkspaceSystemSettingsOffTopic(): """ Workspace settings related to detection of irrelevant input. diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 696a08a7b..0d3e7a0c7 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2022. +# (C) Copyright IBM Corp. 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -164,7 +164,7 @@ def test_message_all_params(self): # Construct a dict representation of a Context model context_model = {} context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'key1': 'testString'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -331,7 +331,6 @@ def test_message_value_error(self): with pytest.raises(ValueError): _service.message(**req_copy) - def test_message_value_error_with_retries(self): # Enable retries and run test_message_value_error. _service.enable_retries() @@ -463,7 +462,6 @@ def test_bulk_classify_value_error(self): with pytest.raises(ValueError): _service.bulk_classify(**req_copy) - def test_bulk_classify_value_error_with_retries(self): # Enable retries and run test_bulk_classify_value_error. _service.enable_retries() @@ -495,7 +493,7 @@ def test_list_workspaces_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -547,7 +545,7 @@ def test_list_workspaces_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -578,7 +576,7 @@ def test_list_workspaces_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -593,7 +591,6 @@ def test_list_workspaces_value_error(self): with pytest.raises(ValueError): _service.list_workspaces(**req_copy) - def test_list_workspaces_value_error_with_retries(self): # Enable retries and run test_list_workspaces_value_error. _service.enable_retries() @@ -615,7 +612,7 @@ def test_create_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -633,7 +630,7 @@ def test_create_workspace_all_params(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model @@ -643,13 +640,13 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -662,7 +659,7 @@ def test_create_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -675,7 +672,7 @@ def test_create_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'key1': 'testString'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -714,15 +711,20 @@ def test_create_workspace_all_params(self): workspace_system_settings_off_topic_model = {} workspace_system_settings_off_topic_model['enabled'] = False + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'baseline' + # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' # Construct a dict representation of a WebhookHeader model @@ -755,7 +757,7 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'key1': 'testString'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -764,7 +766,7 @@ def test_create_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {} + create_entity_model['metadata'] = {'key1': 'testString'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -774,7 +776,7 @@ def test_create_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {} + metadata = {'key1': 'testString'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -813,7 +815,7 @@ def test_create_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -836,7 +838,7 @@ def test_create_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -867,7 +869,7 @@ def test_create_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -882,7 +884,6 @@ def test_create_workspace_value_error(self): with pytest.raises(ValueError): _service.create_workspace(**req_copy) - def test_create_workspace_value_error_with_retries(self): # Enable retries and run test_create_workspace_value_error. _service.enable_retries() @@ -904,7 +905,7 @@ def test_get_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -936,105 +937,768 @@ def test_get_workspace_all_params(self): assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string assert 'sort={}'.format(sort) in query_string - def test_get_workspace_all_params_with_retries(self): - # Enable retries and run test_get_workspace_all_params. + def test_get_workspace_all_params_with_retries(self): + # Enable retries and run test_get_workspace_all_params. + _service.enable_retries() + self.test_get_workspace_all_params() + + # Disable retries and run test_get_workspace_all_params. + _service.disable_retries() + self.test_get_workspace_all_params() + + @responses.activate + def test_get_workspace_required_params(self): + """ + test_get_workspace_required_params() + """ + # Set up mock + url = preprocess_url('/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = _service.get_workspace( + workspace_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_workspace_required_params_with_retries(self): + # Enable retries and run test_get_workspace_required_params. + _service.enable_retries() + self.test_get_workspace_required_params() + + # Disable retries and run test_get_workspace_required_params. + _service.disable_retries() + self.test_get_workspace_required_params() + + @responses.activate + def test_get_workspace_value_error(self): + """ + test_get_workspace_value_error() + """ + # Set up mock + url = preprocess_url('/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_workspace(**req_copy) + + def test_get_workspace_value_error_with_retries(self): + # Enable retries and run test_get_workspace_value_error. + _service.enable_retries() + self.test_get_workspace_value_error() + + # Disable retries and run test_get_workspace_value_error. + _service.disable_retries() + self.test_get_workspace_value_error() + +class TestUpdateWorkspace(): + """ + Test Class for update_workspace + """ + + @responses.activate + def test_update_workspace_all_params(self): + """ + update_workspace() + """ + # Set up mock + url = preprocess_url('/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} + dialog_node_output_generic_model['alt_text'] = 'testString' + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Construct a dict representation of a DialogNode model + dialog_node_model = {} + dialog_node_model['dialog_node'] = 'testString' + dialog_node_model['description'] = 'testString' + dialog_node_model['conditions'] = 'testString' + dialog_node_model['parent'] = 'testString' + dialog_node_model['previous_sibling'] = 'testString' + dialog_node_model['output'] = dialog_node_output_model + dialog_node_model['context'] = dialog_node_context_model + dialog_node_model['metadata'] = {'key1': 'testString'} + dialog_node_model['next_step'] = dialog_node_next_step_model + dialog_node_model['title'] = 'testString' + dialog_node_model['type'] = 'standard' + dialog_node_model['event_name'] = 'focus' + dialog_node_model['variable'] = 'testString' + dialog_node_model['actions'] = [dialog_node_action_model] + dialog_node_model['digress_in'] = 'not_available' + dialog_node_model['digress_out'] = 'allow_returning' + dialog_node_model['digress_out_slots'] = 'not_allowed' + dialog_node_model['user_label'] = 'testString' + dialog_node_model['disambiguation_opt_out'] = False + + # Construct a dict representation of a Counterexample model + counterexample_model = {} + counterexample_model['text'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsTooling model + workspace_system_settings_tooling_model = {} + workspace_system_settings_tooling_model['store_generic_responses'] = True + + # Construct a dict representation of a WorkspaceSystemSettingsDisambiguation model + workspace_system_settings_disambiguation_model = {} + workspace_system_settings_disambiguation_model['prompt'] = 'testString' + workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model['enabled'] = False + workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model['randomize'] = True + workspace_system_settings_disambiguation_model['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsSystemEntities model + workspace_system_settings_system_entities_model = {} + workspace_system_settings_system_entities_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsOffTopic model + workspace_system_settings_off_topic_model = {} + workspace_system_settings_off_topic_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'baseline' + + # Construct a dict representation of a WorkspaceSystemSettings model + workspace_system_settings_model = {} + workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model + workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model + workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} + workspace_system_settings_model['spelling_suggestions'] = False + workspace_system_settings_model['spelling_auto_correct'] = False + workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model + workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model + workspace_system_settings_model['foo'] = 'testString' + + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + # Construct a dict representation of a Webhook model + webhook_model = {} + webhook_model['url'] = 'testString' + webhook_model['name'] = 'testString' + webhook_model['headers'] = [webhook_header_model] + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Construct a dict representation of a CreateIntent model + create_intent_model = {} + create_intent_model['intent'] = 'testString' + create_intent_model['description'] = 'testString' + create_intent_model['examples'] = [example_model] + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Construct a dict representation of a CreateEntity model + create_entity_model = {} + create_entity_model['entity'] = 'testString' + create_entity_model['description'] = 'testString' + create_entity_model['metadata'] = {'key1': 'testString'} + create_entity_model['fuzzy_match'] = True + create_entity_model['values'] = [create_value_model] + + # Set up parameter values + workspace_id = 'testString' + name = 'testString' + description = 'testString' + language = 'testString' + dialog_nodes = [dialog_node_model] + counterexamples = [counterexample_model] + metadata = {'key1': 'testString'} + learning_opt_out = False + system_settings = workspace_system_settings_model + webhooks = [webhook_model] + intents = [create_intent_model] + entities = [create_entity_model] + append = False + include_audit = False + + # Invoke method + response = _service.update_workspace( + workspace_id, + name=name, + description=description, + language=language, + dialog_nodes=dialog_nodes, + counterexamples=counterexamples, + metadata=metadata, + learning_opt_out=learning_opt_out, + system_settings=system_settings, + webhooks=webhooks, + intents=intents, + entities=entities, + append=append, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'append={}'.format('true' if append else 'false') in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['language'] == 'testString' + assert req_body['dialog_nodes'] == [dialog_node_model] + assert req_body['counterexamples'] == [counterexample_model] + assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['learning_opt_out'] == False + assert req_body['system_settings'] == workspace_system_settings_model + assert req_body['webhooks'] == [webhook_model] + assert req_body['intents'] == [create_intent_model] + assert req_body['entities'] == [create_entity_model] + + def test_update_workspace_all_params_with_retries(self): + # Enable retries and run test_update_workspace_all_params. + _service.enable_retries() + self.test_update_workspace_all_params() + + # Disable retries and run test_update_workspace_all_params. + _service.disable_retries() + self.test_update_workspace_all_params() + + @responses.activate + def test_update_workspace_required_params(self): + """ + test_update_workspace_required_params() + """ + # Set up mock + url = preprocess_url('/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = _service.update_workspace( + workspace_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_update_workspace_required_params_with_retries(self): + # Enable retries and run test_update_workspace_required_params. + _service.enable_retries() + self.test_update_workspace_required_params() + + # Disable retries and run test_update_workspace_required_params. + _service.disable_retries() + self.test_update_workspace_required_params() + + @responses.activate + def test_update_workspace_value_error(self): + """ + test_update_workspace_value_error() + """ + # Set up mock + url = preprocess_url('/v1/workspaces/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_workspace(**req_copy) + + def test_update_workspace_value_error_with_retries(self): + # Enable retries and run test_update_workspace_value_error. + _service.enable_retries() + self.test_update_workspace_value_error() + + # Disable retries and run test_update_workspace_value_error. + _service.disable_retries() + self.test_update_workspace_value_error() + +class TestDeleteWorkspace(): + """ + Test Class for delete_workspace + """ + + @responses.activate + def test_delete_workspace_all_params(self): + """ + delete_workspace() + """ + # Set up mock + url = preprocess_url('/v1/workspaces/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = _service.delete_workspace( + workspace_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_delete_workspace_all_params_with_retries(self): + # Enable retries and run test_delete_workspace_all_params. + _service.enable_retries() + self.test_delete_workspace_all_params() + + # Disable retries and run test_delete_workspace_all_params. + _service.disable_retries() + self.test_delete_workspace_all_params() + + @responses.activate + def test_delete_workspace_value_error(self): + """ + test_delete_workspace_value_error() + """ + # Set up mock + url = preprocess_url('/v1/workspaces/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "workspace_id": workspace_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_workspace(**req_copy) + + def test_delete_workspace_value_error_with_retries(self): + # Enable retries and run test_delete_workspace_value_error. + _service.enable_retries() + self.test_delete_workspace_value_error() + + # Disable retries and run test_delete_workspace_value_error. + _service.disable_retries() + self.test_delete_workspace_value_error() + +class TestCreateWorkspaceAsync(): + """ + Test Class for create_workspace_async + """ + + @responses.activate + def test_create_workspace_async_all_params(self): + """ + create_workspace_async() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a ResponseGenericChannel model + response_generic_channel_model = {} + response_generic_channel_model['channel'] = 'chat' + + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + dialog_node_output_generic_model = {} + dialog_node_output_generic_model['response_type'] = 'audio' + dialog_node_output_generic_model['source'] = 'testString' + dialog_node_output_generic_model['title'] = 'testString' + dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['channels'] = [response_generic_channel_model] + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} + dialog_node_output_generic_model['alt_text'] = 'testString' + + # Construct a dict representation of a DialogNodeOutputModifiers model + dialog_node_output_modifiers_model = {} + dialog_node_output_modifiers_model['overwrite'] = True + + # Construct a dict representation of a DialogNodeOutput model + dialog_node_output_model = {} + dialog_node_output_model['generic'] = [dialog_node_output_generic_model] + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model + dialog_node_output_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeContext model + dialog_node_context_model = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['foo'] = 'testString' + + # Construct a dict representation of a DialogNodeNextStep model + dialog_node_next_step_model = {} + dialog_node_next_step_model['behavior'] = 'get_user_input' + dialog_node_next_step_model['dialog_node'] = 'testString' + dialog_node_next_step_model['selector'] = 'condition' + + # Construct a dict representation of a DialogNodeAction model + dialog_node_action_model = {} + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + # Construct a dict representation of a DialogNode model + dialog_node_model = {} + dialog_node_model['dialog_node'] = 'testString' + dialog_node_model['description'] = 'testString' + dialog_node_model['conditions'] = 'testString' + dialog_node_model['parent'] = 'testString' + dialog_node_model['previous_sibling'] = 'testString' + dialog_node_model['output'] = dialog_node_output_model + dialog_node_model['context'] = dialog_node_context_model + dialog_node_model['metadata'] = {'key1': 'testString'} + dialog_node_model['next_step'] = dialog_node_next_step_model + dialog_node_model['title'] = 'testString' + dialog_node_model['type'] = 'standard' + dialog_node_model['event_name'] = 'focus' + dialog_node_model['variable'] = 'testString' + dialog_node_model['actions'] = [dialog_node_action_model] + dialog_node_model['digress_in'] = 'not_available' + dialog_node_model['digress_out'] = 'allow_returning' + dialog_node_model['digress_out_slots'] = 'not_allowed' + dialog_node_model['user_label'] = 'testString' + dialog_node_model['disambiguation_opt_out'] = False + + # Construct a dict representation of a Counterexample model + counterexample_model = {} + counterexample_model['text'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsTooling model + workspace_system_settings_tooling_model = {} + workspace_system_settings_tooling_model['store_generic_responses'] = True + + # Construct a dict representation of a WorkspaceSystemSettingsDisambiguation model + workspace_system_settings_disambiguation_model = {} + workspace_system_settings_disambiguation_model['prompt'] = 'testString' + workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' + workspace_system_settings_disambiguation_model['enabled'] = False + workspace_system_settings_disambiguation_model['sensitivity'] = 'auto' + workspace_system_settings_disambiguation_model['randomize'] = True + workspace_system_settings_disambiguation_model['max_suggestions'] = 1 + workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' + + # Construct a dict representation of a WorkspaceSystemSettingsSystemEntities model + workspace_system_settings_system_entities_model = {} + workspace_system_settings_system_entities_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsOffTopic model + workspace_system_settings_off_topic_model = {} + workspace_system_settings_off_topic_model['enabled'] = False + + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'baseline' + + # Construct a dict representation of a WorkspaceSystemSettings model + workspace_system_settings_model = {} + workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model + workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model + workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} + workspace_system_settings_model['spelling_suggestions'] = False + workspace_system_settings_model['spelling_auto_correct'] = False + workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model + workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model + workspace_system_settings_model['foo'] = 'testString' + + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + + # Construct a dict representation of a Webhook model + webhook_model = {} + webhook_model['url'] = 'testString' + webhook_model['name'] = 'testString' + webhook_model['headers'] = [webhook_header_model] + + # Construct a dict representation of a Mention model + mention_model = {} + mention_model['entity'] = 'testString' + mention_model['location'] = [38] + + # Construct a dict representation of a Example model + example_model = {} + example_model['text'] = 'testString' + example_model['mentions'] = [mention_model] + + # Construct a dict representation of a CreateIntent model + create_intent_model = {} + create_intent_model['intent'] = 'testString' + create_intent_model['description'] = 'testString' + create_intent_model['examples'] = [example_model] + + # Construct a dict representation of a CreateValue model + create_value_model = {} + create_value_model['value'] = 'testString' + create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['type'] = 'synonyms' + create_value_model['synonyms'] = ['testString'] + create_value_model['patterns'] = ['testString'] + + # Construct a dict representation of a CreateEntity model + create_entity_model = {} + create_entity_model['entity'] = 'testString' + create_entity_model['description'] = 'testString' + create_entity_model['metadata'] = {'key1': 'testString'} + create_entity_model['fuzzy_match'] = True + create_entity_model['values'] = [create_value_model] + + # Set up parameter values + name = 'testString' + description = 'testString' + language = 'testString' + dialog_nodes = [dialog_node_model] + counterexamples = [counterexample_model] + metadata = {'key1': 'testString'} + learning_opt_out = False + system_settings = workspace_system_settings_model + webhooks = [webhook_model] + intents = [create_intent_model] + entities = [create_entity_model] + + # Invoke method + response = _service.create_workspace_async( + name=name, + description=description, + language=language, + dialog_nodes=dialog_nodes, + counterexamples=counterexamples, + metadata=metadata, + learning_opt_out=learning_opt_out, + system_settings=system_settings, + webhooks=webhooks, + intents=intents, + entities=entities, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['language'] == 'testString' + assert req_body['dialog_nodes'] == [dialog_node_model] + assert req_body['counterexamples'] == [counterexample_model] + assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['learning_opt_out'] == False + assert req_body['system_settings'] == workspace_system_settings_model + assert req_body['webhooks'] == [webhook_model] + assert req_body['intents'] == [create_intent_model] + assert req_body['entities'] == [create_entity_model] + + def test_create_workspace_async_all_params_with_retries(self): + # Enable retries and run test_create_workspace_async_all_params. _service.enable_retries() - self.test_get_workspace_all_params() + self.test_create_workspace_async_all_params() - # Disable retries and run test_get_workspace_all_params. + # Disable retries and run test_create_workspace_async_all_params. _service.disable_retries() - self.test_get_workspace_all_params() + self.test_create_workspace_async_all_params() @responses.activate - def test_get_workspace_required_params(self): + def test_create_workspace_async_required_params(self): """ - test_get_workspace_required_params() + test_create_workspace_async_required_params() """ # Set up mock - url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.GET, + url = preprocess_url('/v1/workspaces_async') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) - - # Set up parameter values - workspace_id = 'testString' + status=202) # Invoke method - response = _service.get_workspace( - workspace_id, - headers={} - ) + response = _service.create_workspace_async() + # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 202 - def test_get_workspace_required_params_with_retries(self): - # Enable retries and run test_get_workspace_required_params. + def test_create_workspace_async_required_params_with_retries(self): + # Enable retries and run test_create_workspace_async_required_params. _service.enable_retries() - self.test_get_workspace_required_params() + self.test_create_workspace_async_required_params() - # Disable retries and run test_get_workspace_required_params. + # Disable retries and run test_create_workspace_async_required_params. _service.disable_retries() - self.test_get_workspace_required_params() + self.test_create_workspace_async_required_params() @responses.activate - def test_get_workspace_value_error(self): + def test_create_workspace_async_value_error(self): """ - test_get_workspace_value_error() + test_create_workspace_async_value_error() """ # Set up mock - url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.GET, + url = preprocess_url('/v1/workspaces_async') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) - - # Set up parameter values - workspace_id = 'testString' + status=202) # Pass in all but one required param and check for a ValueError req_param_dict = { - "workspace_id": workspace_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_workspace(**req_copy) - + _service.create_workspace_async(**req_copy) - def test_get_workspace_value_error_with_retries(self): - # Enable retries and run test_get_workspace_value_error. + def test_create_workspace_async_value_error_with_retries(self): + # Enable retries and run test_create_workspace_async_value_error. _service.enable_retries() - self.test_get_workspace_value_error() + self.test_create_workspace_async_value_error() - # Disable retries and run test_get_workspace_value_error. + # Disable retries and run test_create_workspace_async_value_error. _service.disable_retries() - self.test_get_workspace_value_error() + self.test_create_workspace_async_value_error() -class TestUpdateWorkspace(): +class TestUpdateWorkspaceAsync(): """ - Test Class for update_workspace + Test Class for update_workspace_async """ @responses.activate - def test_update_workspace_all_params(self): + def test_update_workspace_async_all_params(self): """ - update_workspace() + update_workspace_async() """ # Set up mock - url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces_async/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=202) # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} @@ -1047,7 +1711,7 @@ def test_update_workspace_all_params(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model @@ -1057,13 +1721,13 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1076,7 +1740,7 @@ def test_update_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1089,7 +1753,7 @@ def test_update_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'key1': 'testString'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1128,15 +1792,20 @@ def test_update_workspace_all_params(self): workspace_system_settings_off_topic_model = {} workspace_system_settings_off_topic_model['enabled'] = False + # Construct a dict representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model = {} + workspace_system_settings_nlp_model['model'] = 'baseline' + # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' # Construct a dict representation of a WebhookHeader model @@ -1169,7 +1838,7 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'key1': 'testString'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1178,7 +1847,7 @@ def test_update_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {} + create_entity_model['metadata'] = {'key1': 'testString'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1189,17 +1858,16 @@ def test_update_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {} + metadata = {'key1': 'testString'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] intents = [create_intent_model] entities = [create_entity_model] append = False - include_audit = False # Invoke method - response = _service.update_workspace( + response = _service.update_workspace_async( workspace_id, name=name, description=description, @@ -1213,18 +1881,16 @@ def test_update_workspace_all_params(self): intents=intents, entities=entities, append=append, - include_audit=include_audit, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 202 # Validate query params query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string - assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' @@ -1232,71 +1898,71 @@ def test_update_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] assert req_body['intents'] == [create_intent_model] assert req_body['entities'] == [create_entity_model] - def test_update_workspace_all_params_with_retries(self): - # Enable retries and run test_update_workspace_all_params. + def test_update_workspace_async_all_params_with_retries(self): + # Enable retries and run test_update_workspace_async_all_params. _service.enable_retries() - self.test_update_workspace_all_params() + self.test_update_workspace_async_all_params() - # Disable retries and run test_update_workspace_all_params. + # Disable retries and run test_update_workspace_async_all_params. _service.disable_retries() - self.test_update_workspace_all_params() + self.test_update_workspace_async_all_params() @responses.activate - def test_update_workspace_required_params(self): + def test_update_workspace_async_required_params(self): """ - test_update_workspace_required_params() + test_update_workspace_async_required_params() """ # Set up mock - url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces_async/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=202) # Set up parameter values workspace_id = 'testString' # Invoke method - response = _service.update_workspace( + response = _service.update_workspace_async( workspace_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 202 - def test_update_workspace_required_params_with_retries(self): - # Enable retries and run test_update_workspace_required_params. + def test_update_workspace_async_required_params_with_retries(self): + # Enable retries and run test_update_workspace_async_required_params. _service.enable_retries() - self.test_update_workspace_required_params() + self.test_update_workspace_async_required_params() - # Disable retries and run test_update_workspace_required_params. + # Disable retries and run test_update_workspace_async_required_params. _service.disable_retries() - self.test_update_workspace_required_params() + self.test_update_workspace_async_required_params() @responses.activate - def test_update_workspace_value_error(self): + def test_update_workspace_async_value_error(self): """ - test_update_workspace_value_error() + test_update_workspace_async_value_error() """ # Set up mock - url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}}, "status": "Non Existent", "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + url = preprocess_url('/v1/workspaces_async/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=202) # Set up parameter values workspace_id = 'testString' @@ -1308,65 +1974,118 @@ def test_update_workspace_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_workspace(**req_copy) - + _service.update_workspace_async(**req_copy) - def test_update_workspace_value_error_with_retries(self): - # Enable retries and run test_update_workspace_value_error. + def test_update_workspace_async_value_error_with_retries(self): + # Enable retries and run test_update_workspace_async_value_error. _service.enable_retries() - self.test_update_workspace_value_error() + self.test_update_workspace_async_value_error() - # Disable retries and run test_update_workspace_value_error. + # Disable retries and run test_update_workspace_async_value_error. _service.disable_retries() - self.test_update_workspace_value_error() + self.test_update_workspace_async_value_error() -class TestDeleteWorkspace(): +class TestExportWorkspaceAsync(): """ - Test Class for delete_workspace + Test Class for export_workspace_async """ @responses.activate - def test_delete_workspace_all_params(self): + def test_export_workspace_async_all_params(self): """ - delete_workspace() + export_workspace_async() """ # Set up mock - url = preprocess_url('/v1/workspaces/testString') - responses.add(responses.DELETE, + url = preprocess_url('/v1/workspaces_async/testString/export') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.GET, url, + body=mock_response, + content_type='application/json', status=200) # Set up parameter values workspace_id = 'testString' + include_audit = False + sort = 'stable' + verbose = False # Invoke method - response = _service.delete_workspace( + response = _service.export_workspace_async( workspace_id, + include_audit=include_audit, + sort=sort, + verbose=verbose, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'verbose={}'.format('true' if verbose else 'false') in query_string - def test_delete_workspace_all_params_with_retries(self): - # Enable retries and run test_delete_workspace_all_params. + def test_export_workspace_async_all_params_with_retries(self): + # Enable retries and run test_export_workspace_async_all_params. _service.enable_retries() - self.test_delete_workspace_all_params() + self.test_export_workspace_async_all_params() - # Disable retries and run test_delete_workspace_all_params. + # Disable retries and run test_export_workspace_async_all_params. _service.disable_retries() - self.test_delete_workspace_all_params() + self.test_export_workspace_async_all_params() @responses.activate - def test_delete_workspace_value_error(self): + def test_export_workspace_async_required_params(self): """ - test_delete_workspace_value_error() + test_export_workspace_async_required_params() """ # Set up mock - url = preprocess_url('/v1/workspaces/testString') - responses.add(responses.DELETE, + url = preprocess_url('/v1/workspaces_async/testString/export') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + workspace_id = 'testString' + + # Invoke method + response = _service.export_workspace_async( + workspace_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_export_workspace_async_required_params_with_retries(self): + # Enable retries and run test_export_workspace_async_required_params. + _service.enable_retries() + self.test_export_workspace_async_required_params() + + # Disable retries and run test_export_workspace_async_required_params. + _service.disable_retries() + self.test_export_workspace_async_required_params() + + @responses.activate + def test_export_workspace_async_value_error(self): + """ + test_export_workspace_async_value_error() + """ + # Set up mock + url = preprocess_url('/v1/workspaces_async/testString/export') + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + responses.add(responses.GET, url, + body=mock_response, + content_type='application/json', status=200) # Set up parameter values @@ -1379,17 +2098,16 @@ def test_delete_workspace_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_workspace(**req_copy) - + _service.export_workspace_async(**req_copy) - def test_delete_workspace_value_error_with_retries(self): - # Enable retries and run test_delete_workspace_value_error. + def test_export_workspace_async_value_error_with_retries(self): + # Enable retries and run test_export_workspace_async_value_error. _service.enable_retries() - self.test_delete_workspace_value_error() + self.test_export_workspace_async_value_error() - # Disable retries and run test_delete_workspace_value_error. + # Disable retries and run test_export_workspace_async_value_error. _service.disable_retries() - self.test_delete_workspace_value_error() + self.test_export_workspace_async_value_error() # endregion ############################################################################## @@ -1525,7 +2243,6 @@ def test_list_intents_value_error(self): with pytest.raises(ValueError): _service.list_intents(**req_copy) - def test_list_intents_value_error_with_retries(self): # Enable retries and run test_list_intents_value_error. _service.enable_retries() @@ -1700,7 +2417,6 @@ def test_create_intent_value_error(self): with pytest.raises(ValueError): _service.create_intent(**req_copy) - def test_create_intent_value_error_with_retries(self): # Enable retries and run test_create_intent_value_error. _service.enable_retries() @@ -1828,7 +2544,6 @@ def test_get_intent_value_error(self): with pytest.raises(ValueError): _service.get_intent(**req_copy) - def test_get_intent_value_error_with_retries(self): # Enable retries and run test_get_intent_value_error. _service.enable_retries() @@ -2011,7 +2726,6 @@ def test_update_intent_value_error(self): with pytest.raises(ValueError): _service.update_intent(**req_copy) - def test_update_intent_value_error_with_retries(self): # Enable retries and run test_update_intent_value_error. _service.enable_retries() @@ -2086,7 +2800,6 @@ def test_delete_intent_value_error(self): with pytest.raises(ValueError): _service.delete_intent(**req_copy) - def test_delete_intent_value_error_with_retries(self): # Enable retries and run test_delete_intent_value_error. _service.enable_retries() @@ -2233,7 +2946,6 @@ def test_list_examples_value_error(self): with pytest.raises(ValueError): _service.list_examples(**req_copy) - def test_list_examples_value_error_with_retries(self): # Enable retries and run test_list_examples_value_error. _service.enable_retries() @@ -2392,7 +3104,6 @@ def test_create_example_value_error(self): with pytest.raises(ValueError): _service.create_example(**req_copy) - def test_create_example_value_error_with_retries(self): # Enable retries and run test_create_example_value_error. _service.enable_retries() @@ -2523,7 +3234,6 @@ def test_get_example_value_error(self): with pytest.raises(ValueError): _service.get_example(**req_copy) - def test_get_example_value_error_with_retries(self): # Enable retries and run test_get_example_value_error. _service.enable_retries() @@ -2687,7 +3397,6 @@ def test_update_example_value_error(self): with pytest.raises(ValueError): _service.update_example(**req_copy) - def test_update_example_value_error_with_retries(self): # Enable retries and run test_update_example_value_error. _service.enable_retries() @@ -2766,7 +3475,6 @@ def test_delete_example_value_error(self): with pytest.raises(ValueError): _service.delete_example(**req_copy) - def test_delete_example_value_error_with_retries(self): # Enable retries and run test_delete_example_value_error. _service.enable_retries() @@ -2907,7 +3615,6 @@ def test_list_counterexamples_value_error(self): with pytest.raises(ValueError): _service.list_counterexamples(**req_copy) - def test_list_counterexamples_value_error_with_retries(self): # Enable retries and run test_list_counterexamples_value_error. _service.enable_retries() @@ -3038,7 +3745,6 @@ def test_create_counterexample_value_error(self): with pytest.raises(ValueError): _service.create_counterexample(**req_copy) - def test_create_counterexample_value_error_with_retries(self): # Enable retries and run test_create_counterexample_value_error. _service.enable_retries() @@ -3163,7 +3869,6 @@ def test_get_counterexample_value_error(self): with pytest.raises(ValueError): _service.get_counterexample(**req_copy) - def test_get_counterexample_value_error_with_retries(self): # Enable retries and run test_get_counterexample_value_error. _service.enable_retries() @@ -3299,7 +4004,6 @@ def test_update_counterexample_value_error(self): with pytest.raises(ValueError): _service.update_counterexample(**req_copy) - def test_update_counterexample_value_error_with_retries(self): # Enable retries and run test_update_counterexample_value_error. _service.enable_retries() @@ -3374,7 +4078,6 @@ def test_delete_counterexample_value_error(self): with pytest.raises(ValueError): _service.delete_counterexample(**req_copy) - def test_delete_counterexample_value_error_with_retries(self): # Enable retries and run test_delete_counterexample_value_error. _service.enable_retries() @@ -3518,7 +4221,6 @@ def test_list_entities_value_error(self): with pytest.raises(ValueError): _service.list_entities(**req_copy) - def test_list_entities_value_error_with_retries(self): # Enable retries and run test_list_entities_value_error. _service.enable_retries() @@ -3550,7 +4252,7 @@ def test_create_entity_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'key1': 'testString'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3559,7 +4261,7 @@ def test_create_entity_all_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {} + metadata = {'key1': 'testString'} fuzzy_match = True values = [create_value_model] include_audit = False @@ -3587,7 +4289,7 @@ def test_create_entity_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3617,7 +4319,7 @@ def test_create_entity_required_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'key1': 'testString'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3626,7 +4328,7 @@ def test_create_entity_required_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {} + metadata = {'key1': 'testString'} fuzzy_match = True values = [create_value_model] @@ -3648,7 +4350,7 @@ def test_create_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3678,7 +4380,7 @@ def test_create_entity_value_error(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'key1': 'testString'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3687,7 +4389,7 @@ def test_create_entity_value_error(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {} + metadata = {'key1': 'testString'} fuzzy_match = True values = [create_value_model] @@ -3701,7 +4403,6 @@ def test_create_entity_value_error(self): with pytest.raises(ValueError): _service.create_entity(**req_copy) - def test_create_entity_value_error_with_retries(self): # Enable retries and run test_create_entity_value_error. _service.enable_retries() @@ -3829,7 +4530,6 @@ def test_get_entity_value_error(self): with pytest.raises(ValueError): _service.get_entity(**req_copy) - def test_get_entity_value_error_with_retries(self): # Enable retries and run test_get_entity_value_error. _service.enable_retries() @@ -3861,7 +4561,7 @@ def test_update_entity_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'key1': 'testString'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3871,7 +4571,7 @@ def test_update_entity_all_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {} + new_metadata = {'key1': 'testString'} new_fuzzy_match = True new_values = [create_value_model] append = False @@ -3903,7 +4603,7 @@ def test_update_entity_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3933,7 +4633,7 @@ def test_update_entity_required_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'key1': 'testString'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -3943,7 +4643,7 @@ def test_update_entity_required_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {} + new_metadata = {'key1': 'testString'} new_fuzzy_match = True new_values = [create_value_model] @@ -3966,7 +4666,7 @@ def test_update_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -3996,7 +4696,7 @@ def test_update_entity_value_error(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'key1': 'testString'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4006,7 +4706,7 @@ def test_update_entity_value_error(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {} + new_metadata = {'key1': 'testString'} new_fuzzy_match = True new_values = [create_value_model] @@ -4020,7 +4720,6 @@ def test_update_entity_value_error(self): with pytest.raises(ValueError): _service.update_entity(**req_copy) - def test_update_entity_value_error_with_retries(self): # Enable retries and run test_update_entity_value_error. _service.enable_retries() @@ -4095,7 +4794,6 @@ def test_delete_entity_value_error(self): with pytest.raises(ValueError): _service.delete_entity(**req_copy) - def test_delete_entity_value_error_with_retries(self): # Enable retries and run test_delete_entity_value_error. _service.enable_retries() @@ -4233,7 +4931,6 @@ def test_list_mentions_value_error(self): with pytest.raises(ValueError): _service.list_mentions(**req_copy) - def test_list_mentions_value_error_with_retries(self): # Enable retries and run test_list_mentions_value_error. _service.enable_retries() @@ -4383,7 +5080,6 @@ def test_list_values_value_error(self): with pytest.raises(ValueError): _service.list_values(**req_copy) - def test_list_values_value_error_with_retries(self): # Enable retries and run test_list_values_value_error. _service.enable_retries() @@ -4416,7 +5112,7 @@ def test_create_value_all_params(self): workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {} + metadata = {'key1': 'testString'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -4445,7 +5141,7 @@ def test_create_value_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4477,7 +5173,7 @@ def test_create_value_required_params(self): workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {} + metadata = {'key1': 'testString'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -4500,7 +5196,7 @@ def test_create_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4532,7 +5228,7 @@ def test_create_value_value_error(self): workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {} + metadata = {'key1': 'testString'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -4548,7 +5244,6 @@ def test_create_value_value_error(self): with pytest.raises(ValueError): _service.create_value(**req_copy) - def test_create_value_value_error_with_retries(self): # Enable retries and run test_create_value_value_error. _service.enable_retries() @@ -4682,7 +5377,6 @@ def test_get_value_value_error(self): with pytest.raises(ValueError): _service.get_value(**req_copy) - def test_get_value_value_error_with_retries(self): # Enable retries and run test_get_value_value_error. _service.enable_retries() @@ -4716,7 +5410,7 @@ def test_update_value_all_params(self): entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {} + new_metadata = {'key1': 'testString'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -4749,7 +5443,7 @@ def test_update_value_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4782,7 +5476,7 @@ def test_update_value_required_params(self): entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {} + new_metadata = {'key1': 'testString'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -4806,7 +5500,7 @@ def test_update_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -4839,7 +5533,7 @@ def test_update_value_value_error(self): entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {} + new_metadata = {'key1': 'testString'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -4855,7 +5549,6 @@ def test_update_value_value_error(self): with pytest.raises(ValueError): _service.update_value(**req_copy) - def test_update_value_value_error_with_retries(self): # Enable retries and run test_update_value_value_error. _service.enable_retries() @@ -4934,7 +5627,6 @@ def test_delete_value_value_error(self): with pytest.raises(ValueError): _service.delete_value(**req_copy) - def test_delete_value_value_error_with_retries(self): # Enable retries and run test_delete_value_value_error. _service.enable_retries() @@ -5087,7 +5779,6 @@ def test_list_synonyms_value_error(self): with pytest.raises(ValueError): _service.list_synonyms(**req_copy) - def test_list_synonyms_value_error_with_retries(self): # Enable retries and run test_list_synonyms_value_error. _service.enable_retries() @@ -5230,7 +5921,6 @@ def test_create_synonym_value_error(self): with pytest.raises(ValueError): _service.create_synonym(**req_copy) - def test_create_synonym_value_error_with_retries(self): # Enable retries and run test_create_synonym_value_error. _service.enable_retries() @@ -5367,7 +6057,6 @@ def test_get_synonym_value_error(self): with pytest.raises(ValueError): _service.get_synonym(**req_copy) - def test_get_synonym_value_error_with_retries(self): # Enable retries and run test_get_synonym_value_error. _service.enable_retries() @@ -5515,7 +6204,6 @@ def test_update_synonym_value_error(self): with pytest.raises(ValueError): _service.update_synonym(**req_copy) - def test_update_synonym_value_error_with_retries(self): # Enable retries and run test_update_synonym_value_error. _service.enable_retries() @@ -5598,7 +6286,6 @@ def test_delete_synonym_value_error(self): with pytest.raises(ValueError): _service.delete_synonym(**req_copy) - def test_delete_synonym_value_error_with_retries(self): # Enable retries and run test_delete_synonym_value_error. _service.enable_retries() @@ -5739,7 +6426,6 @@ def test_list_dialog_nodes_value_error(self): with pytest.raises(ValueError): _service.list_dialog_nodes(**req_copy) - def test_list_dialog_nodes_value_error_with_retries(self): # Enable retries and run test_list_dialog_nodes_value_error. _service.enable_retries() @@ -5779,7 +6465,7 @@ def test_create_dialog_node_all_params(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model @@ -5789,13 +6475,13 @@ def test_create_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -5808,7 +6494,7 @@ def test_create_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -5821,7 +6507,7 @@ def test_create_dialog_node_all_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {} + metadata = {'key1': 'testString'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -5877,7 +6563,7 @@ def test_create_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -5924,7 +6610,7 @@ def test_create_dialog_node_required_params(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model @@ -5934,13 +6620,13 @@ def test_create_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -5953,7 +6639,7 @@ def test_create_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -5966,7 +6652,7 @@ def test_create_dialog_node_required_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {} + metadata = {'key1': 'testString'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6016,7 +6702,7 @@ def test_create_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6063,7 +6749,7 @@ def test_create_dialog_node_value_error(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6073,13 +6759,13 @@ def test_create_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6092,7 +6778,7 @@ def test_create_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6105,7 +6791,7 @@ def test_create_dialog_node_value_error(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {} + metadata = {'key1': 'testString'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6128,7 +6814,6 @@ def test_create_dialog_node_value_error(self): with pytest.raises(ValueError): _service.create_dialog_node(**req_copy) - def test_create_dialog_node_value_error_with_retries(self): # Enable retries and run test_create_dialog_node_value_error. _service.enable_retries() @@ -6253,7 +6938,6 @@ def test_get_dialog_node_value_error(self): with pytest.raises(ValueError): _service.get_dialog_node(**req_copy) - def test_get_dialog_node_value_error_with_retries(self): # Enable retries and run test_get_dialog_node_value_error. _service.enable_retries() @@ -6293,7 +6977,7 @@ def test_update_dialog_node_all_params(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6303,13 +6987,13 @@ def test_update_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6322,7 +7006,7 @@ def test_update_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6336,7 +7020,7 @@ def test_update_dialog_node_all_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {} + new_metadata = {'key1': 'testString'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -6393,7 +7077,7 @@ def test_update_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6440,7 +7124,7 @@ def test_update_dialog_node_required_params(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6450,13 +7134,13 @@ def test_update_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6469,7 +7153,7 @@ def test_update_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6483,7 +7167,7 @@ def test_update_dialog_node_required_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {} + new_metadata = {'key1': 'testString'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -6534,7 +7218,7 @@ def test_update_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {} + assert req_body['metadata'] == {'key1': 'testString'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6581,7 +7265,7 @@ def test_update_dialog_node_value_error(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6591,13 +7275,13 @@ def test_update_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6610,7 +7294,7 @@ def test_update_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6624,7 +7308,7 @@ def test_update_dialog_node_value_error(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {} + new_metadata = {'key1': 'testString'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -6647,7 +7331,6 @@ def test_update_dialog_node_value_error(self): with pytest.raises(ValueError): _service.update_dialog_node(**req_copy) - def test_update_dialog_node_value_error_with_retries(self): # Enable retries and run test_update_dialog_node_value_error. _service.enable_retries() @@ -6722,7 +7405,6 @@ def test_delete_dialog_node_value_error(self): with pytest.raises(ValueError): _service.delete_dialog_node(**req_copy) - def test_delete_dialog_node_value_error_with_retries(self): # Enable retries and run test_delete_dialog_node_value_error. _service.enable_retries() @@ -6860,7 +7542,6 @@ def test_list_logs_value_error(self): with pytest.raises(ValueError): _service.list_logs(**req_copy) - def test_list_logs_value_error_with_retries(self): # Enable retries and run test_list_logs_value_error. _service.enable_retries() @@ -6990,7 +7671,6 @@ def test_list_all_logs_value_error(self): with pytest.raises(ValueError): _service.list_all_logs(**req_copy) - def test_list_all_logs_value_error_with_retries(self): # Enable retries and run test_list_all_logs_value_error. _service.enable_retries() @@ -7075,7 +7755,6 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) - def test_delete_user_data_value_error_with_retries(self): # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() @@ -7483,7 +8162,7 @@ def test_context_serialization(self): # Construct a json representation of a Context model context_model_json = {} context_model_json['conversation_id'] = 'testString' - context_model_json['system'] = {} + context_model_json['system'] = {'key1': 'testString'} context_model_json['metadata'] = message_context_metadata_model context_model_json['foo'] = 'testString' @@ -7602,7 +8281,7 @@ def test_create_entity_serialization(self): create_value_model = {} # CreateValue create_value_model['value'] = 'testString' - create_value_model['metadata'] = {} + create_value_model['metadata'] = {'key1': 'testString'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -7613,7 +8292,7 @@ def test_create_entity_serialization(self): create_entity_model_json = {} create_entity_model_json['entity'] = 'testString' create_entity_model_json['description'] = 'testString' - create_entity_model_json['metadata'] = {} + create_entity_model_json['metadata'] = {'key1': 'testString'} create_entity_model_json['fuzzy_match'] = True create_entity_model_json['created'] = '2019-01-01T12:00:00Z' create_entity_model_json['updated'] = '2019-01-01T12:00:00Z' @@ -7692,7 +8371,7 @@ def test_create_value_serialization(self): # Construct a json representation of a CreateValue model create_value_model_json = {} create_value_model_json['value'] = 'testString' - create_value_model_json['metadata'] = {} + create_value_model_json['metadata'] = {'key1': 'testString'} create_value_model_json['type'] = 'synonyms' create_value_model_json['synonyms'] = ['testString'] create_value_model_json['patterns'] = ['testString'] @@ -7735,7 +8414,7 @@ def test_dialog_node_serialization(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers @@ -7743,12 +8422,12 @@ def test_dialog_node_serialization(self): dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -7759,7 +8438,7 @@ def test_dialog_node_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7772,7 +8451,7 @@ def test_dialog_node_serialization(self): dialog_node_model_json['previous_sibling'] = 'testString' dialog_node_model_json['output'] = dialog_node_output_model dialog_node_model_json['context'] = dialog_node_context_model - dialog_node_model_json['metadata'] = {} + dialog_node_model_json['metadata'] = {'key1': 'testString'} dialog_node_model_json['next_step'] = dialog_node_next_step_model dialog_node_model_json['title'] = 'testString' dialog_node_model_json['type'] = 'standard' @@ -7817,7 +8496,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json = {} dialog_node_action_model_json['name'] = 'testString' dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {} + dialog_node_action_model_json['parameters'] = {'key1': 'testString'} dialog_node_action_model_json['result_variable'] = 'testString' dialog_node_action_model_json['credentials'] = 'testString' @@ -7857,7 +8536,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers @@ -7865,12 +8544,12 @@ def test_dialog_node_collection_serialization(self): dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -7881,7 +8560,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7893,7 +8572,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'key1': 'testString'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -7949,7 +8628,7 @@ def test_dialog_node_context_serialization(self): # Construct a json representation of a DialogNodeContext model dialog_node_context_model_json = {} - dialog_node_context_model_json['integrations'] = {} + dialog_node_context_model_json['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model_json['foo'] = 'testString' # Construct a model instance of DialogNodeContext by calling from_dict on the json representation @@ -8029,7 +8708,7 @@ def test_dialog_node_output_serialization(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers @@ -8038,7 +8717,7 @@ def test_dialog_node_output_serialization(self): # Construct a json representation of a DialogNodeOutput model dialog_node_output_model_json = {} dialog_node_output_model_json['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model_json['integrations'] = {} + dialog_node_output_model_json['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model_json['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model_json['foo'] = 'testString' @@ -8079,7 +8758,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'key1': 'testString'}} # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) @@ -8459,7 +9138,7 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json = {} dialog_suggestion_model_json['label'] = 'testString' dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {} + dialog_suggestion_model_json['output'] = {'key1': 'testString'} dialog_suggestion_model_json['dialog_node'] = 'testString' # Construct a model instance of DialogSuggestion by calling from_dict on the json representation @@ -8585,7 +9264,7 @@ def test_entity_serialization(self): value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'key1': 'testString'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] @@ -8596,7 +9275,7 @@ def test_entity_serialization(self): entity_model_json = {} entity_model_json['entity'] = 'testString' entity_model_json['description'] = 'testString' - entity_model_json['metadata'] = {} + entity_model_json['metadata'] = {'key1': 'testString'} entity_model_json['fuzzy_match'] = True entity_model_json['created'] = '2019-01-01T12:00:00Z' entity_model_json['updated'] = '2019-01-01T12:00:00Z' @@ -8631,7 +9310,7 @@ def test_entity_collection_serialization(self): value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'key1': 'testString'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] @@ -8641,7 +9320,7 @@ def test_entity_collection_serialization(self): entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {} + entity_model['metadata'] = {'key1': 'testString'} entity_model['fuzzy_match'] = True entity_model['created'] = '2019-01-01T12:00:00Z' entity_model['updated'] = '2019-01-01T12:00:00Z' @@ -9020,7 +9699,7 @@ def test_log_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'key1': 'testString'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -9069,7 +9748,7 @@ def test_log_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -9197,7 +9876,7 @@ def test_log_collection_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'key1': 'testString'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -9246,7 +9925,7 @@ def test_log_collection_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -9586,7 +10265,7 @@ def test_message_request_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'key1': 'testString'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -9635,7 +10314,7 @@ def test_message_request_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -9744,7 +10423,7 @@ def test_message_response_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {} + context_model['system'] = {'key1': 'testString'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -9793,7 +10472,7 @@ def test_message_response_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -10247,6 +10926,35 @@ def test_runtime_intent_serialization(self): runtime_intent_model_json2 = runtime_intent_model.to_dict() assert runtime_intent_model_json2 == runtime_intent_model_json +class TestModel_StatusError(): + """ + Test Class for StatusError + """ + + def test_status_error_serialization(self): + """ + Test serialization/deserialization for StatusError + """ + + # Construct a json representation of a StatusError model + status_error_model_json = {} + status_error_model_json['message'] = 'testString' + + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model = StatusError.from_dict(status_error_model_json) + assert status_error_model != False + + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model_dict = StatusError.from_dict(status_error_model_json).__dict__ + status_error_model2 = StatusError(**status_error_model_dict) + + # Verify the model instances are equivalent + assert status_error_model == status_error_model2 + + # Convert model instance back to dict and verify no loss of data + status_error_model_json2 = status_error_model.to_dict() + assert status_error_model_json2 == status_error_model_json + class TestModel_Synonym(): """ Test Class for Synonym @@ -10336,7 +11044,7 @@ def test_value_serialization(self): # Construct a json representation of a Value model value_model_json = {} value_model_json['value'] = 'testString' - value_model_json['metadata'] = {} + value_model_json['metadata'] = {'key1': 'testString'} value_model_json['type'] = 'synonyms' value_model_json['synonyms'] = ['testString'] value_model_json['patterns'] = ['testString'] @@ -10372,7 +11080,7 @@ def test_value_collection_serialization(self): value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'key1': 'testString'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] @@ -10495,7 +11203,7 @@ def test_workspace_serialization(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers @@ -10503,12 +11211,12 @@ def test_workspace_serialization(self): dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -10519,7 +11227,7 @@ def test_workspace_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -10531,7 +11239,7 @@ def test_workspace_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'key1': 'testString'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -10570,16 +11278,23 @@ def test_workspace_serialization(self): workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model['model'] = 'baseline' + workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' + status_error_model = {} # StatusError + status_error_model['message'] = 'testString' + webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' @@ -10608,7 +11323,7 @@ def test_workspace_serialization(self): value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'key1': 'testString'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] @@ -10618,12 +11333,17 @@ def test_workspace_serialization(self): entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {} + entity_model['metadata'] = {'key1': 'testString'} entity_model['fuzzy_match'] = True entity_model['created'] = '2019-01-01T12:00:00Z' entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] + workspace_counts_model = {} # WorkspaceCounts + workspace_counts_model['intent'] = 38 + workspace_counts_model['entity'] = 38 + workspace_counts_model['node'] = 38 + # Construct a json representation of a Workspace model workspace_model_json = {} workspace_model_json['name'] = 'testString' @@ -10634,13 +11354,15 @@ def test_workspace_serialization(self): workspace_model_json['counterexamples'] = [counterexample_model] workspace_model_json['created'] = '2019-01-01T12:00:00Z' workspace_model_json['updated'] = '2019-01-01T12:00:00Z' - workspace_model_json['metadata'] = {} + workspace_model_json['metadata'] = {'key1': 'testString'} workspace_model_json['learning_opt_out'] = False workspace_model_json['system_settings'] = workspace_system_settings_model - workspace_model_json['status'] = 'Non Existent' + workspace_model_json['status'] = 'Available' + workspace_model_json['status_errors'] = [status_error_model] workspace_model_json['webhooks'] = [webhook_model] workspace_model_json['intents'] = [intent_model] workspace_model_json['entities'] = [entity_model] + workspace_model_json['counts'] = workspace_counts_model # Construct a model instance of Workspace by calling from_dict on the json representation workspace_model = Workspace.from_dict(workspace_model_json) @@ -10678,7 +11400,7 @@ def test_workspace_collection_serialization(self): dialog_node_output_generic_model['title'] = 'testString' dialog_node_output_generic_model['description'] = 'testString' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers @@ -10686,12 +11408,12 @@ def test_workspace_collection_serialization(self): dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {} + dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {} + dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -10702,7 +11424,7 @@ def test_workspace_collection_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -10714,7 +11436,7 @@ def test_workspace_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {} + dialog_node_model['metadata'] = {'key1': 'testString'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -10753,16 +11475,23 @@ def test_workspace_collection_serialization(self): workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model['model'] = 'baseline' + workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {} + workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' + status_error_model = {} # StatusError + status_error_model['message'] = 'testString' + webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' @@ -10791,7 +11520,7 @@ def test_workspace_collection_serialization(self): value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {} + value_model['metadata'] = {'key1': 'testString'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] @@ -10801,12 +11530,17 @@ def test_workspace_collection_serialization(self): entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {} + entity_model['metadata'] = {'key1': 'testString'} entity_model['fuzzy_match'] = True entity_model['created'] = '2019-01-01T12:00:00Z' entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] + workspace_counts_model = {} # WorkspaceCounts + workspace_counts_model['intent'] = 38 + workspace_counts_model['entity'] = 38 + workspace_counts_model['node'] = 38 + workspace_model = {} # Workspace workspace_model['name'] = 'testString' workspace_model['description'] = 'testString' @@ -10816,13 +11550,15 @@ def test_workspace_collection_serialization(self): workspace_model['counterexamples'] = [counterexample_model] workspace_model['created'] = '2019-01-01T12:00:00Z' workspace_model['updated'] = '2019-01-01T12:00:00Z' - workspace_model['metadata'] = {} + workspace_model['metadata'] = {'key1': 'testString'} workspace_model['learning_opt_out'] = False workspace_model['system_settings'] = workspace_system_settings_model - workspace_model['status'] = 'Non Existent' + workspace_model['status'] = 'Available' + workspace_model['status_errors'] = [status_error_model] workspace_model['webhooks'] = [webhook_model] workspace_model['intents'] = [intent_model] workspace_model['entities'] = [entity_model] + workspace_model['counts'] = workspace_counts_model pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -10852,6 +11588,37 @@ def test_workspace_collection_serialization(self): workspace_collection_model_json2 = workspace_collection_model.to_dict() assert workspace_collection_model_json2 == workspace_collection_model_json +class TestModel_WorkspaceCounts(): + """ + Test Class for WorkspaceCounts + """ + + def test_workspace_counts_serialization(self): + """ + Test serialization/deserialization for WorkspaceCounts + """ + + # Construct a json representation of a WorkspaceCounts model + workspace_counts_model_json = {} + workspace_counts_model_json['intent'] = 38 + workspace_counts_model_json['entity'] = 38 + workspace_counts_model_json['node'] = 38 + + # Construct a model instance of WorkspaceCounts by calling from_dict on the json representation + workspace_counts_model = WorkspaceCounts.from_dict(workspace_counts_model_json) + assert workspace_counts_model != False + + # Construct a model instance of WorkspaceCounts by calling from_dict on the json representation + workspace_counts_model_dict = WorkspaceCounts.from_dict(workspace_counts_model_json).__dict__ + workspace_counts_model2 = WorkspaceCounts(**workspace_counts_model_dict) + + # Verify the model instances are equivalent + assert workspace_counts_model == workspace_counts_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_counts_model_json2 = workspace_counts_model.to_dict() + assert workspace_counts_model_json2 == workspace_counts_model_json + class TestModel_WorkspaceSystemSettings(): """ Test Class for WorkspaceSystemSettings @@ -10882,15 +11649,19 @@ def test_workspace_system_settings_serialization(self): workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model['model'] = 'baseline' + # Construct a json representation of a WorkspaceSystemSettings model workspace_system_settings_model_json = {} workspace_system_settings_model_json['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model_json['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model_json['human_agent_assist'] = {} + workspace_system_settings_model_json['human_agent_assist'] = {'key1': 'testString'} workspace_system_settings_model_json['spelling_suggestions'] = False workspace_system_settings_model_json['spelling_auto_correct'] = False workspace_system_settings_model_json['system_entities'] = workspace_system_settings_system_entities_model workspace_system_settings_model_json['off_topic'] = workspace_system_settings_off_topic_model + workspace_system_settings_model_json['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model_json['foo'] = 'testString' # Construct a model instance of WorkspaceSystemSettings by calling from_dict on the json representation @@ -10953,6 +11724,35 @@ def test_workspace_system_settings_disambiguation_serialization(self): workspace_system_settings_disambiguation_model_json2 = workspace_system_settings_disambiguation_model.to_dict() assert workspace_system_settings_disambiguation_model_json2 == workspace_system_settings_disambiguation_model_json +class TestModel_WorkspaceSystemSettingsNlp(): + """ + Test Class for WorkspaceSystemSettingsNlp + """ + + def test_workspace_system_settings_nlp_serialization(self): + """ + Test serialization/deserialization for WorkspaceSystemSettingsNlp + """ + + # Construct a json representation of a WorkspaceSystemSettingsNlp model + workspace_system_settings_nlp_model_json = {} + workspace_system_settings_nlp_model_json['model'] = 'baseline' + + # Construct a model instance of WorkspaceSystemSettingsNlp by calling from_dict on the json representation + workspace_system_settings_nlp_model = WorkspaceSystemSettingsNlp.from_dict(workspace_system_settings_nlp_model_json) + assert workspace_system_settings_nlp_model != False + + # Construct a model instance of WorkspaceSystemSettingsNlp by calling from_dict on the json representation + workspace_system_settings_nlp_model_dict = WorkspaceSystemSettingsNlp.from_dict(workspace_system_settings_nlp_model_json).__dict__ + workspace_system_settings_nlp_model2 = WorkspaceSystemSettingsNlp(**workspace_system_settings_nlp_model_dict) + + # Verify the model instances are equivalent + assert workspace_system_settings_nlp_model == workspace_system_settings_nlp_model2 + + # Convert model instance back to dict and verify no loss of data + workspace_system_settings_nlp_model_json2 = workspace_system_settings_nlp_model.to_dict() + assert workspace_system_settings_nlp_model_json2 == workspace_system_settings_nlp_model_json + class TestModel_WorkspaceSystemSettingsOffTopic(): """ Test Class for WorkspaceSystemSettingsOffTopic @@ -11062,7 +11862,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_audio_seria dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channels'] = [response_generic_channel_model] - dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio by calling from_dict on the json representation @@ -11142,7 +11942,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ agent_availability_message_model['message'] = 'testString' dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'key1': 'testString'}} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' @@ -11493,7 +12293,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_user_define # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined model dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['response_type'] = 'user_defined' - dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {} + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {'key1': 'testString'} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined by calling from_dict on the json representation @@ -11533,7 +12333,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_video_seria dialog_node_output_generic_dialog_node_output_response_type_video_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_video_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channels'] = [response_generic_channel_model] - dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channel_options'] = { 'foo': 'bar' } + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channel_options'] = {'foo': 'bar'} dialog_node_output_generic_dialog_node_output_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo by calling from_dict on the json representation @@ -11573,7 +12373,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation @@ -11653,7 +12453,7 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali agent_availability_message_model['message'] = 'testString' dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'key1': 'testString'}} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' @@ -11989,7 +12789,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization dialog_suggestion_model = {} # DialogSuggestion dialog_suggestion_model['label'] = 'testString' dialog_suggestion_model['value'] = dialog_suggestion_value_model - dialog_suggestion_model['output'] = {} + dialog_suggestion_model['output'] = {'key1': 'testString'} dialog_suggestion_model['dialog_node'] = 'testString' response_generic_channel_model = {} # ResponseGenericChannel @@ -12071,7 +12871,7 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model runtime_response_generic_runtime_response_type_user_defined_model_json = {} runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' - runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {} + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'key1': 'testString'} runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation @@ -12111,7 +12911,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self runtime_response_generic_runtime_response_type_video_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation From a1586ec6750e5130493fa8d08ac01d13a36e3715 Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Wed, 10 Aug 2022 09:14:17 -0500 Subject: [PATCH 369/455] feat(assistant-v2): update models and add new methods New methods are listEnvironments, getEnvironments, listReleases, getRelease, deployRelease --- ibm_watson/assistant_v2.py | 7862 ++++++++++++++++++++++---------- test/unit/test_assistant_v2.py | 2257 ++++++++- 2 files changed, 7379 insertions(+), 2740 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index b9413e510..f7318ec4a 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -26,6 +26,7 @@ See: https://cloud.ibm.com/docs/assistant """ +from datetime import datetime from enum import Enum from typing import Dict, List import json @@ -34,7 +35,7 @@ from ibm_cloud_sdk_core import BaseService, DetailedResponse from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import convert_model +from ibm_cloud_sdk_core.utils import convert_model, datetime_to_string, string_to_datetime from .common import get_sdk_headers @@ -47,7 +48,7 @@ class AssistantV2(BaseService): """The Assistant V2 service.""" DEFAULT_SERVICE_URL = 'https://api.us-south.assistant.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'assistant' + DEFAULT_SERVICE_NAME = 'conversation' def __init__( self, @@ -80,7 +81,11 @@ def __init__( # Sessions ######################### - def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: + def create_session(self, + assistant_id: str, + *, + create_session: 'CreateSession' = None, + **kwargs) -> DetailedResponse: """ Create a session. @@ -96,6 +101,7 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: assistants, see the [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 CreateSession create_session: (optional) :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SessionResponse` object @@ -111,8 +117,14 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: params = {'version': self.version} + data = {} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['assistant_id'] @@ -122,7 +134,8 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: request = self.prepare_request(method='POST', url=url, headers=headers, - params=params) + params=params, + data=data) response = self.send(request, **kwargs) return response @@ -162,6 +175,7 @@ def delete_session(self, assistant_id: str, session_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['assistant_id', 'session_id'] @@ -249,6 +263,7 @@ def message(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['assistant_id', 'session_id'] @@ -329,6 +344,7 @@ def message_stateless(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['assistant_id'] @@ -348,10 +364,7 @@ def message_stateless(self, # Bulk classify ######################### - def bulk_classify(self, - skill_id: str, - *, - input: List['BulkClassifyUtterance'] = None, + def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], **kwargs) -> DetailedResponse: """ Identify intents and entities in multiple user utterances. @@ -365,8 +378,8 @@ def bulk_classify(self, :param str skill_id: Unique identifier of the skill. To find the skill ID in the Watson Assistant user interface, open the skill settings and click **API Details**. - :param List[BulkClassifyUtterance] input: (optional) An array of input - utterances to classify. + :param List[BulkClassifyUtterance] input: An array of input utterances to + classify. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object @@ -374,8 +387,9 @@ def bulk_classify(self, if skill_id is None: raise ValueError('skill_id must be provided') - if input is not None: - input = [convert_model(x) for x in input] + if input is None: + raise ValueError('input must be provided') + input = [convert_model(x) for x in input] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', @@ -391,6 +405,7 @@ def bulk_classify(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['skill_id'] @@ -424,6 +439,10 @@ def list_logs(self, List the events from the log of an assistant. This method requires Manager access, and is available only with Enterprise plans. + **Note:** If you use the **cursor** parameter to retrieve results one page at a + time, subsequent requests must be no more than 5 minutes apart. Any returned value + for the **cursor** parameter becomes invalid after 5 minutes. For more information + about using pagination, see [Pagination](#pagination). :param str assistant_id: Unique identifier of the assistant. To find the assistant ID in the Watson Assistant user interface, open the assistant @@ -464,6 +483,7 @@ def list_logs(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['assistant_id'] @@ -517,6 +537,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v2/user_data' @@ -528,6 +549,373 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response + ######################### + # Environments + ######################### + + def list_environments(self, + assistant_id: str, + *, + page_limit: int = None, + include_count: bool = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + List environments. + + List the environments associated with an assistant. + + :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/assistant?topic=assistant-assistant-add#assistant-add-task). + **Note:** Currently, the v2 API does not support creating assistants. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned environments + will be sorted. To reverse the sort order, prefix the value with a minus + sign (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 with `dict` result representing a `EnvironmentCollection` object + """ + + if assistant_id is None: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_environments') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def get_environment(self, + assistant_id: str, + environment_id: str, + *, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + Get environment. + + Get information about an environment. For more information about environments, see + [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). + + :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/assistant?topic=assistant-assistant-add#assistant-add-task). + **Note:** Currently, the v2 API does not support creating assistants. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the Watson Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :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 with `dict` result representing a `Environment` object + """ + + if assistant_id is None: + raise ValueError('assistant_id must be provided') + if environment_id is None: + raise ValueError('environment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_environment') + headers.update(sdk_headers) + + params = {'version': self.version, 'include_audit': include_audit} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + ######################### + # Releases + ######################### + + def list_releases(self, + assistant_id: str, + *, + page_limit: int = None, + include_count: bool = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + List releases. + + List the releases associated with an assistant. (In the Watson Assistant user + interface, a release is called a *version*.). + + :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/assistant?topic=assistant-assistant-add#assistant-add-task). + **Note:** Currently, the v2 API does not support creating assistants. + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned workspaces will + be sorted. To reverse the sort order, prefix the value with a minus sign + (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 with `dict` result representing a `ReleaseCollection` object + """ + + if assistant_id is None: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_releases') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases'.format(**path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def get_release(self, + assistant_id: str, + release: str, + *, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + Get release. + + Get information about a release. + Release data is not available until publishing of the release completes. If + publishing is still in progress, you can continue to poll by calling the same + request again and checking the value of the **status** property. When processing + has completed, the request returns the release data. + + :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/assistant?topic=assistant-assistant-add#assistant-add-task). + **Note:** Currently, the v2 API does not support creating assistants. + :param str release: Unique identifier of the release. + :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 with `dict` result representing a `Release` object + """ + + if assistant_id is None: + raise ValueError('assistant_id must be provided') + if release is None: + raise ValueError('release must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_release') + headers.update(sdk_headers) + + params = {'version': self.version, 'include_audit': include_audit} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases/{release}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def deploy_release(self, + assistant_id: str, + release: str, + environment_id: str, + *, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + Deploy release. + + Update the environment with the content of the release. All snapshots saved as + part of the release become active in the environment. + + :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/assistant?topic=assistant-assistant-add#assistant-add-task). + **Note:** Currently, the v2 API does not support creating assistants. + :param str release: Unique identifier of the release. + :param str environment_id: The environment ID of the environment where the + release is to be deployed. + :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 with `dict` result representing a `Environment` object + """ + + if assistant_id is None: + raise ValueError('assistant_id must be provided') + if release is None: + raise ValueError('release must be provided') + if environment_id is None: + raise ValueError('environment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='deploy_release') + headers.update(sdk_headers) + + params = {'version': self.version, 'include_audit': include_audit} + + data = {'environment_id': environment_id} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases/{release}/deploy'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + +class ListEnvironmentsEnums: + """ + Enums for list_environments parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned environments will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + NAME = 'name' + UPDATED = 'updated' + + +class ListReleasesEnums: + """ + Enums for list_releases parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned workspaces will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + NAME = 'name' + UPDATED = 'updated' + ############################################################################## # Models @@ -1438,9 +1826,9 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: class DialogNodeVisited(): """ An objects containing detailed diagnostic information about a dialog node that was - triggered during processing of the input message. + visited during processing of the input message. - :attr str dialog_node: (optional) A dialog node that was triggered during + :attr str dialog_node: (optional) A dialog node that was visited during processing of the input message. :attr str title: (optional) The title of the dialog node. :attr str conditions: (optional) The conditions that trigger the dialog node. @@ -1454,7 +1842,7 @@ def __init__(self, """ Initialize a DialogNodeVisited object. - :param str dialog_node: (optional) A dialog node that was triggered during + :param str dialog_node: (optional) A dialog node that was visited during processing of the input message. :param str title: (optional) The title of the dialog node. :param str conditions: (optional) The conditions that trigger the dialog @@ -1658,169 +2046,169 @@ def __ne__(self, other: 'DialogSuggestionValue') -> bool: return not self == other -class Log(): - """ - Log. - - :attr str log_id: A unique identifier for the logged event. - :attr MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :attr MessageResponse response: A response from the Watson Assistant service. - :attr str assistant_id: Unique identifier of the assistant. - :attr str session_id: The ID of the session the message was part of. - :attr str skill_id: The unique identifier of the skill that responded to the - message. - :attr str snapshot: The name of the snapshot (dialog skill version) that - responded to the message (for example, `draft`). - :attr str request_timestamp: The timestamp for receipt of the message. - :attr str response_timestamp: The timestamp for the system response to the - message. - :attr str language: The language of the assistant to which the message request - was made. - :attr str customer_id: (optional) The customer ID specified for the message, if - any. +class Environment(): + """ + Environment. + + :attr str name: (optional) The name of the environment. + :attr str description: (optional) The description of the environment. + :attr str language: (optional) The language of the environment. An environment + is always created with the same language as the assistant it is associated with. + :attr str assistant_id: (optional) The assistant ID of the assistant the + environment is associated with. + :attr str environment_id: (optional) The environment ID of the environment. + :attr str environment: (optional) The type of the environment. All environments + other than the `draft` and `live` environments have the type `staging`. + :attr EnvironmentReleaseReference release_reference: (optional) An object + describing the release that is currently deployed in the environment. + :attr EnvironmentOrchestration orchestration: (optional) The search skill + orchestration settings for the environment. + :attr int session_timeout: (optional) The session inactivity timeout setting for + the environment. + :attr List[IntegrationReference] integration_references: (optional) An array of + objects describing the integrations that exist in the environment. + :attr List[SkillReference] skill_references: (optional) An array of objects + describing the skills (such as actions and dialog) that exist in the + environment. + :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. """ def __init__(self, - log_id: str, - request: 'MessageRequest', - response: 'MessageResponse', - assistant_id: str, - session_id: str, - skill_id: str, - snapshot: str, - request_timestamp: str, - response_timestamp: str, - language: str, *, - customer_id: str = None) -> None: - """ - Initialize a Log object. - - :param str log_id: A unique identifier for the logged event. - :param MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :param MessageResponse response: A response from the Watson Assistant - service. - :param str assistant_id: Unique identifier of the assistant. - :param str session_id: The ID of the session the message was part of. - :param str skill_id: The unique identifier of the skill that responded to - the message. - :param str snapshot: The name of the snapshot (dialog skill version) that - responded to the message (for example, `draft`). - :param str request_timestamp: The timestamp for receipt of the message. - :param str response_timestamp: The timestamp for the system response to the - message. - :param str language: The language of the assistant to which the message - request was made. - :param str customer_id: (optional) The customer ID specified for the - message, if any. + name: str = None, + description: str = None, + language: str = None, + assistant_id: str = None, + environment_id: str = None, + environment: str = None, + release_reference: 'EnvironmentReleaseReference' = None, + orchestration: 'EnvironmentOrchestration' = None, + session_timeout: int = None, + integration_references: List['IntegrationReference'] = None, + skill_references: List['SkillReference'] = None, + created: datetime = None, + updated: datetime = None) -> None: + """ + Initialize a Environment object. + + :param str name: (optional) The name of the environment. + :param str description: (optional) The description of the environment. + :param str language: (optional) The language of the environment. An + environment is always created with the same language as the assistant it is + associated with. + :param EnvironmentReleaseReference release_reference: (optional) An object + describing the release that is currently deployed in the environment. + :param EnvironmentOrchestration orchestration: (optional) The search skill + orchestration settings for the environment. + :param int session_timeout: (optional) The session inactivity timeout + setting for the environment. + :param List[IntegrationReference] integration_references: (optional) An + array of objects describing the integrations that exist in the environment. + :param List[SkillReference] skill_references: (optional) An array of + objects describing the skills (such as actions and dialog) that exist in + the environment. """ - self.log_id = log_id - self.request = request - self.response = response - self.assistant_id = assistant_id - self.session_id = session_id - self.skill_id = skill_id - self.snapshot = snapshot - self.request_timestamp = request_timestamp - self.response_timestamp = response_timestamp + self.name = name + self.description = description self.language = language - self.customer_id = customer_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Log': - """Initialize a Log object from a json dictionary.""" + self.assistant_id = assistant_id + self.environment_id = environment_id + self.environment = environment + self.release_reference = release_reference + self.orchestration = orchestration + self.session_timeout = session_timeout + self.integration_references = integration_references + self.skill_references = skill_references + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Environment': + """Initialize a Environment object from a json dictionary.""" args = {} - if 'log_id' in _dict: - args['log_id'] = _dict.get('log_id') - else: - raise ValueError( - 'Required property \'log_id\' not present in Log JSON') - if 'request' in _dict: - args['request'] = MessageRequest.from_dict(_dict.get('request')) - else: - raise ValueError( - 'Required property \'request\' not present in Log JSON') - if 'response' in _dict: - args['response'] = MessageResponse.from_dict(_dict.get('response')) - else: - raise ValueError( - 'Required property \'response\' not present in Log JSON') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - else: - raise ValueError( - 'Required property \'assistant_id\' not present in Log JSON') - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') - else: - raise ValueError( - 'Required property \'session_id\' not present in Log JSON') - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') - else: - raise ValueError( - 'Required property \'skill_id\' not present in Log JSON') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') - else: - raise ValueError( - 'Required property \'snapshot\' not present in Log JSON') - if 'request_timestamp' in _dict: - args['request_timestamp'] = _dict.get('request_timestamp') - else: - raise ValueError( - 'Required property \'request_timestamp\' not present in Log JSON' - ) - if 'response_timestamp' in _dict: - args['response_timestamp'] = _dict.get('response_timestamp') - else: - raise ValueError( - 'Required property \'response_timestamp\' not present in Log JSON' - ) + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') if 'language' in _dict: args['language'] = _dict.get('language') - else: - raise ValueError( - 'Required property \'language\' not present in Log JSON') - if 'customer_id' in _dict: - args['customer_id'] = _dict.get('customer_id') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + if 'environment_id' in _dict: + args['environment_id'] = _dict.get('environment_id') + if 'environment' in _dict: + args['environment'] = _dict.get('environment') + if 'release_reference' in _dict: + args['release_reference'] = EnvironmentReleaseReference.from_dict( + _dict.get('release_reference')) + if 'orchestration' in _dict: + args['orchestration'] = EnvironmentOrchestration.from_dict( + _dict.get('orchestration')) + if 'session_timeout' in _dict: + args['session_timeout'] = _dict.get('session_timeout') + if 'integration_references' in _dict: + args['integration_references'] = [ + IntegrationReference.from_dict(x) + for x in _dict.get('integration_references') + ] + if 'skill_references' in _dict: + args['skill_references'] = [ + SkillReference.from_dict(x) + for x in _dict.get('skill_references') + ] + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Log object from a json dictionary.""" + """Initialize a Environment 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, 'log_id') and self.log_id is not None: - _dict['log_id'] = self.log_id - if hasattr(self, 'request') and self.request is not None: - _dict['request'] = self.request.to_dict() - if hasattr(self, 'response') and self.response is not None: - _dict['response'] = self.response.to_dict() - if hasattr(self, 'assistant_id') and self.assistant_id is not None: - _dict['assistant_id'] = self.assistant_id - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id - if hasattr(self, 'skill_id') and self.skill_id is not None: - _dict['skill_id'] = self.skill_id - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot - if hasattr(self, - 'request_timestamp') and self.request_timestamp is not None: - _dict['request_timestamp'] = self.request_timestamp - if hasattr( - self, - 'response_timestamp') and self.response_timestamp is not None: - _dict['response_timestamp'] = self.response_timestamp + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language - if hasattr(self, 'customer_id') and self.customer_id is not None: - _dict['customer_id'] = self.customer_id + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'environment') and getattr(self, + 'environment') is not None: + _dict['environment'] = getattr(self, 'environment') + if hasattr(self, + 'release_reference') and self.release_reference is not None: + _dict['release_reference'] = self.release_reference.to_dict() + if hasattr(self, 'orchestration') and self.orchestration is not None: + _dict['orchestration'] = self.orchestration.to_dict() + if hasattr(self, + 'session_timeout') and self.session_timeout is not None: + _dict['session_timeout'] = self.session_timeout + if hasattr(self, 'integration_references' + ) and self.integration_references is not None: + _dict['integration_references'] = [ + x.to_dict() for x in self.integration_references + ] + if hasattr(self, + 'skill_references') and self.skill_references is not None: + _dict['skill_references'] = [ + x.to_dict() for x in self.skill_references + ] + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) return _dict def _to_dict(self): @@ -1828,67 +2216,71 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Log object.""" + """Return a `str` version of this Environment object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Log') -> bool: + def __eq__(self, other: 'Environment') -> 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: 'Log') -> bool: + def __ne__(self, other: 'Environment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogCollection(): +class EnvironmentCollection(): """ - LogCollection. + EnvironmentCollection. - :attr List[Log] logs: An array of objects describing log events. - :attr LogPagination pagination: The pagination data for the returned objects. + :attr List[Environment] environments: An array of objects describing the + environments associated with an assistant. + :attr Pagination pagination: The pagination data for the returned objects. """ - def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: + def __init__(self, environments: List['Environment'], + pagination: 'Pagination') -> None: """ - Initialize a LogCollection object. + Initialize a EnvironmentCollection object. - :param List[Log] logs: An array of objects describing log events. - :param LogPagination pagination: The pagination data for the returned - objects. + :param List[Environment] environments: An array of objects describing the + environments associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. """ - self.logs = logs + self.environments = environments self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'LogCollection': - """Initialize a LogCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'EnvironmentCollection': + """Initialize a EnvironmentCollection object from a json dictionary.""" args = {} - if 'logs' in _dict: - args['logs'] = [Log.from_dict(x) for x in _dict.get('logs')] + if 'environments' in _dict: + args['environments'] = [ + Environment.from_dict(x) for x in _dict.get('environments') + ] else: raise ValueError( - 'Required property \'logs\' not present in LogCollection JSON') + 'Required property \'environments\' not present in EnvironmentCollection JSON' + ) if 'pagination' in _dict: - args['pagination'] = LogPagination.from_dict( - _dict.get('pagination')) + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) else: raise ValueError( - 'Required property \'pagination\' not present in LogCollection JSON' + 'Required property \'pagination\' not present in EnvironmentCollection JSON' ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogCollection object from a json dictionary.""" + """Initialize a EnvironmentCollection 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, 'logs') and self.logs is not None: - _dict['logs'] = [x.to_dict() for x in self.logs] + if hasattr(self, 'environments') and self.environments is not None: + _dict['environments'] = [x.to_dict() for x in self.environments] if hasattr(self, 'pagination') and self.pagination is not None: _dict['pagination'] = self.pagination.to_dict() return _dict @@ -1898,134 +2290,134 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogCollection object.""" + """Return a `str` version of this EnvironmentCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogCollection') -> bool: + def __eq__(self, other: 'EnvironmentCollection') -> 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: 'LogCollection') -> bool: + def __ne__(self, other: 'EnvironmentCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSource(): +class EnvironmentOrchestration(): """ - An object that identifies the dialog element that generated the error message. + The search skill orchestration settings for the environment. + :attr bool search_skill_fallback: (optional) Whether assistants deployed to the + environment fall back to a search skill when responding to messages that do not + match any intent. If no search skill is configured for the assistant, this + property is ignored. """ - def __init__(self) -> None: + def __init__(self, *, search_skill_fallback: bool = None) -> None: """ - Initialize a LogMessageSource object. + Initialize a EnvironmentOrchestration object. + :param bool search_skill_fallback: (optional) Whether assistants deployed + to the environment fall back to a search skill when responding to messages + that do not match any intent. If no search skill is configured for the + assistant, this property is ignored. """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) - raise Exception(msg) + self.search_skill_fallback = search_skill_fallback @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSource': - """Initialize a LogMessageSource object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'LogMessageSource'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) - raise Exception(msg) + def from_dict(cls, _dict: Dict) -> 'EnvironmentOrchestration': + """Initialize a EnvironmentOrchestration object from a json dictionary.""" + args = {} + if 'search_skill_fallback' in _dict: + args['search_skill_fallback'] = _dict.get('search_skill_fallback') + return cls(**args) @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a LogMessageSource object from a json dictionary.""" + def _from_dict(cls, _dict): + """Initialize a EnvironmentOrchestration object from a json dictionary.""" return cls.from_dict(_dict) - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['dialog_node'] = 'LogMessageSourceDialogNode' - mapping['action'] = 'LogMessageSourceAction' - mapping['step'] = 'LogMessageSourceStep' - mapping['handler'] = 'LogMessageSourceHandler' - disc_value = _dict.get('type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'type\' not found in LogMessageSource JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'search_skill_fallback' + ) and self.search_skill_fallback is not None: + _dict['search_skill_fallback'] = self.search_skill_fallback + return _dict + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() -class LogPagination(): + def __str__(self) -> str: + """Return a `str` version of this EnvironmentOrchestration object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'EnvironmentOrchestration') -> 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: 'EnvironmentOrchestration') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class EnvironmentReference(): """ - The pagination data for the returned objects. + EnvironmentReference. - :attr str next_url: (optional) The URL that will return the next page of - results, if any. - :attr int matched: (optional) Reserved for future use. - :attr str next_cursor: (optional) A token identifying the next page of results. + :attr str name: (optional) The name of the deployed environment. + :attr str environment_id: (optional) The environment ID of the deployed + environment. + :attr str environment: (optional) The type of the deployed environment. All + environments other than the draft and live environments have the type `staging`. """ def __init__(self, *, - next_url: str = None, - matched: int = None, - next_cursor: str = None) -> None: + name: str = None, + environment_id: str = None, + environment: str = None) -> None: """ - Initialize a LogPagination object. + Initialize a EnvironmentReference object. - :param str next_url: (optional) The URL that will return the next page of - results, if any. - :param int matched: (optional) Reserved for future use. - :param str next_cursor: (optional) A token identifying the next page of - results. + :param str name: (optional) The name of the deployed environment. """ - self.next_url = next_url - self.matched = matched - self.next_cursor = next_cursor + self.name = name + self.environment_id = environment_id + self.environment = environment @classmethod - def from_dict(cls, _dict: Dict) -> 'LogPagination': - """Initialize a LogPagination object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'EnvironmentReference': + """Initialize a EnvironmentReference object from a json dictionary.""" args = {} - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'environment_id' in _dict: + args['environment_id'] = _dict.get('environment_id') + if 'environment' in _dict: + args['environment'] = _dict.get('environment') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogPagination object from a json dictionary.""" + """Initialize a EnvironmentReference 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, 'next_url') and self.next_url is not None: - _dict['next_url'] = self.next_url - if hasattr(self, 'matched') and self.matched is not None: - _dict['matched'] = self.matched - if hasattr(self, 'next_cursor') and self.next_cursor is not None: - _dict['next_cursor'] = self.next_cursor + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'environment') and getattr(self, + 'environment') is not None: + _dict['environment'] = getattr(self, 'environment') return _dict def _to_dict(self): @@ -2033,87 +2425,62 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogPagination object.""" + """Return a `str` version of this EnvironmentReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogPagination') -> bool: + def __eq__(self, other: 'EnvironmentReference') -> 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: 'LogPagination') -> bool: + def __ne__(self, other: 'EnvironmentReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class EnvironmentEnum(str, Enum): + """ + The type of the deployed environment. All environments other than the draft and + live environments have the type `staging`. + """ + DRAFT = 'draft' + LIVE = 'live' + STAGING = 'staging' + -class MessageContext(): +class EnvironmentReleaseReference(): """ - MessageContext. + An object describing the release that is currently deployed in the environment. - :attr MessageContextGlobal global_: (optional) Session context data that is - shared by all skills used by the assistant. - :attr dict skills: (optional) Information specific to particular skills used by - the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. - :attr object integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :attr str release: (optional) The name of the deployed release. """ - def __init__(self, - *, - global_: 'MessageContextGlobal' = None, - skills: dict = None, - integrations: object = None) -> None: + def __init__(self, *, release: str = None) -> None: """ - Initialize a MessageContext object. + Initialize a EnvironmentReleaseReference object. - :param MessageContextGlobal global_: (optional) Session context data that - is shared by all skills used by the assistant. - :param dict skills: (optional) Information specific to particular skills - used by the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. - :param object integrations: (optional) An object containing context data - that is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str release: (optional) The name of the deployed release. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.release = release @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContext': - """Initialize a MessageContext object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'EnvironmentReleaseReference': + """Initialize a EnvironmentReleaseReference object from a json dictionary.""" args = {} - if 'global' in _dict: - args['global_'] = MessageContextGlobal.from_dict( - _dict.get('global')) - if 'skills' in _dict: - args['skills'] = { - k: MessageContextSkill.from_dict(v) - for k, v in _dict.get('skills').items() - } - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if 'release' in _dict: + args['release'] = _dict.get('release') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContext object from a json dictionary.""" + """Initialize a EnvironmentReleaseReference 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, 'global_') and self.global_ is not None: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + if hasattr(self, 'release') and self.release is not None: + _dict['release'] = self.release return _dict def _to_dict(self): @@ -2121,66 +2488,61 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContext object.""" + """Return a `str` version of this EnvironmentReleaseReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContext') -> bool: + def __eq__(self, other: 'EnvironmentReleaseReference') -> 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: 'MessageContext') -> bool: + def __ne__(self, other: 'EnvironmentReleaseReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobal(): +class IntegrationReference(): """ - Session context data that is shared by all skills used by the assistant. + IntegrationReference. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :attr str session_id: (optional) The session ID. + :attr str integration_id: (optional) The integration ID of the integration. + :attr str type: (optional) The type of the integration. """ - def __init__(self, - *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: + def __init__(self, *, integration_id: str = None, type: str = None) -> None: """ - Initialize a MessageContextGlobal object. + Initialize a IntegrationReference object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. + :param str integration_id: (optional) The integration ID of the + integration. + :param str type: (optional) The type of the integration. """ - self.system = system - self.session_id = session_id + self.integration_id = integration_id + self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': - """Initialize a MessageContextGlobal object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'IntegrationReference': + """Initialize a IntegrationReference object from a json dictionary.""" args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if 'integration_id' in _dict: + args['integration_id'] = _dict.get('integration_id') + if 'type' in _dict: + args['type'] = _dict.get('type') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobal object from a json dictionary.""" + """Initialize a IntegrationReference 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, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and getattr(self, - 'session_id') is not None: - _dict['session_id'] = getattr(self, 'session_id') + if hasattr(self, 'integration_id') and self.integration_id is not None: + _dict['integration_id'] = self.integration_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -2188,261 +2550,253 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobal object.""" + """Return a `str` version of this IntegrationReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobal') -> bool: + def __eq__(self, other: 'IntegrationReference') -> 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: 'MessageContextGlobal') -> bool: + def __ne__(self, other: 'IntegrationReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobalStateless(): +class Log(): """ - Session context data that is shared by all skills used by the assistant. + Log. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :attr str session_id: (optional) The unique identifier of the session. + :attr str log_id: A unique identifier for the logged event. + :attr MessageRequest request: A stateful message request formatted for the + Watson Assistant service. + :attr MessageResponse response: A response from the Watson Assistant service. + :attr str assistant_id: Unique identifier of the assistant. + :attr str session_id: The ID of the session the message was part of. + :attr str skill_id: The unique identifier of the skill that responded to the + message. + :attr str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :attr str request_timestamp: The timestamp for receipt of the message. + :attr str response_timestamp: The timestamp for the system response to the + message. + :attr str language: The language of the assistant to which the message request + was made. + :attr str customer_id: (optional) The customer ID specified for the message, if + any. """ def __init__(self, + log_id: str, + request: 'MessageRequest', + response: 'MessageResponse', + assistant_id: str, + session_id: str, + skill_id: str, + snapshot: str, + request_timestamp: str, + response_timestamp: str, + language: str, *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: + customer_id: str = None) -> None: """ - Initialize a MessageContextGlobalStateless object. + Initialize a Log object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param str log_id: A unique identifier for the logged event. + :param MessageRequest request: A stateful message request formatted for the + Watson Assistant service. + :param MessageResponse response: A response from the Watson Assistant + service. + :param str assistant_id: Unique identifier of the assistant. + :param str session_id: The ID of the session the message was part of. + :param str skill_id: The unique identifier of the skill that responded to + the message. + :param str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the + message. + :param str language: The language of the assistant to which the message + request was made. + :param str customer_id: (optional) The customer ID specified for the + message, if any. """ - self.system = system + self.log_id = log_id + self.request = request + self.response = response + self.assistant_id = assistant_id self.session_id = session_id + self.skill_id = skill_id + self.snapshot = snapshot + self.request_timestamp = request_timestamp + self.response_timestamp = response_timestamp + self.language = language + self.customer_id = customer_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Log': + """Initialize a Log object from a json dictionary.""" args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) + if 'log_id' in _dict: + args['log_id'] = _dict.get('log_id') + else: + raise ValueError( + 'Required property \'log_id\' not present in Log JSON') + if 'request' in _dict: + args['request'] = MessageRequest.from_dict(_dict.get('request')) + else: + raise ValueError( + 'Required property \'request\' not present in Log JSON') + if 'response' in _dict: + args['response'] = MessageResponse.from_dict(_dict.get('response')) + else: + raise ValueError( + 'Required property \'response\' not present in Log JSON') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + else: + raise ValueError( + 'Required property \'assistant_id\' not present in Log JSON') if 'session_id' in _dict: args['session_id'] = _dict.get('session_id') + else: + raise ValueError( + 'Required property \'session_id\' not present in Log JSON') + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + else: + raise ValueError( + 'Required property \'skill_id\' not present in Log JSON') + if 'snapshot' in _dict: + args['snapshot'] = _dict.get('snapshot') + else: + raise ValueError( + 'Required property \'snapshot\' not present in Log JSON') + if 'request_timestamp' in _dict: + args['request_timestamp'] = _dict.get('request_timestamp') + else: + raise ValueError( + 'Required property \'request_timestamp\' not present in Log JSON' + ) + if 'response_timestamp' in _dict: + args['response_timestamp'] = _dict.get('response_timestamp') + else: + raise ValueError( + 'Required property \'response_timestamp\' not present in Log JSON' + ) + if 'language' in _dict: + args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in Log JSON') + if 'customer_id' in _dict: + args['customer_id'] = _dict.get('customer_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + """Initialize a Log 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, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() + if hasattr(self, 'log_id') and self.log_id is not None: + _dict['log_id'] = self.log_id + if hasattr(self, 'request') and self.request is not None: + _dict['request'] = self.request.to_dict() + if hasattr(self, 'response') and self.response is not None: + _dict['response'] = self.response.to_dict() + if hasattr(self, 'assistant_id') and self.assistant_id is not None: + _dict['assistant_id'] = self.assistant_id if hasattr(self, 'session_id') and self.session_id is not None: _dict['session_id'] = self.session_id - return _dict - + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + if hasattr(self, + 'request_timestamp') and self.request_timestamp is not None: + _dict['request_timestamp'] = self.request_timestamp + if hasattr( + self, + 'response_timestamp') and self.response_timestamp is not None: + _dict['response_timestamp'] = self.response_timestamp + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'customer_id') and self.customer_id is not None: + _dict['customer_id'] = self.customer_id + 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 MessageContextGlobalStateless object.""" + """Return a `str` version of this Log object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalStateless') -> bool: + def __eq__(self, other: 'Log') -> 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: 'MessageContextGlobalStateless') -> bool: + def __ne__(self, other: 'Log') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobalSystem(): +class LogCollection(): """ - Built-in system properties that apply to all skills used by the assistant. + LogCollection. - :attr str timezone: (optional) The user time zone. The assistant uses the time - zone to correctly resolve relative time references. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root of - the message body. If **user_id** is specified in both locations in a message - request, the value specified at the root is used. - :attr int turn_count: (optional) A counter that is automatically incremented - 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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for the - skill. - :attr str session_start_time: (optional) The time at which the session started. - With the stateful `message` method, the start time is always present, and is set - by the service based on the time the session was created. With the stateless - `message` method, the start time is set by the service in the response to the - first message, and should be returned as part of the context with each - subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for example, - `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :attr str state: (optional) An encoded string that represents the configuration - state of the assistant at the beginning of the conversation. If you are using - the stateless `message` method, save this value and then send it in the context - of the subsequent message request to avoid disruptions if there are - configuration changes during the conversation (such as a change to a skill the - assistant uses). - :attr bool skip_user_input: (optional) For internal use only. + :attr List[Log] logs: An array of objects describing log events. + :attr LogPagination pagination: The pagination data for the returned objects. """ - def __init__(self, - *, - timezone: str = None, - user_id: str = None, - turn_count: int = None, - locale: str = None, - reference_time: str = None, - session_start_time: str = None, - state: str = None, - skip_user_input: bool = None) -> None: + def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: """ - Initialize a MessageContextGlobalSystem object. + Initialize a LogCollection object. - :param str timezone: (optional) The user time zone. The assistant uses the - time zone to correctly resolve relative time references. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root - of the message body. If **user_id** is specified in both locations in a - message request, the value specified at the root is used. - :param int turn_count: (optional) A counter that is automatically - incremented 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). - :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for - the skill. - :param str session_start_time: (optional) The time at which the session - started. With the stateful `message` method, the start time is always - present, and is set by the service based on the time the session was - created. With the stateless `message` method, the start time is set by the - service in the response to the first message, and should be returned as - part of the context with each subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :param str state: (optional) An encoded string that represents the - configuration state of the assistant at the beginning of the conversation. - If you are using the stateless `message` method, save this value and then - send it in the context of the subsequent message request to avoid - disruptions if there are configuration changes during the conversation - (such as a change to a skill the assistant uses). - :param bool skip_user_input: (optional) For internal use only. + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned + objects. """ - self.timezone = timezone - self.user_id = user_id - self.turn_count = turn_count - self.locale = locale - self.reference_time = reference_time - self.session_start_time = session_start_time - self.state = state - self.skip_user_input = skip_user_input + self.logs = logs + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogCollection': + """Initialize a LogCollection object from a json dictionary.""" args = {} - if 'timezone' in _dict: - args['timezone'] = _dict.get('timezone') - if 'user_id' in _dict: - 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') - if 'session_start_time' in _dict: - args['session_start_time'] = _dict.get('session_start_time') - if 'state' in _dict: - args['state'] = _dict.get('state') - if 'skip_user_input' in _dict: - args['skip_user_input'] = _dict.get('skip_user_input') + if 'logs' in _dict: + args['logs'] = [Log.from_dict(x) for x in _dict.get('logs')] + else: + raise ValueError( + 'Required property \'logs\' not present in LogCollection JSON') + if 'pagination' in _dict: + args['pagination'] = LogPagination.from_dict( + _dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in LogCollection JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + """Initialize a LogCollection 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, 'timezone') and self.timezone is not None: - _dict['timezone'] = self.timezone - if hasattr(self, 'user_id') and self.user_id is not None: - _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 - if hasattr( - self, - 'session_start_time') and self.session_start_time is not None: - _dict['session_start_time'] = self.session_start_time - if hasattr(self, 'state') and self.state is not None: - _dict['state'] = self.state - if hasattr(self, - 'skip_user_input') and self.skip_user_input is not None: - _dict['skip_user_input'] = self.skip_user_input + if hasattr(self, 'logs') and self.logs is not None: + _dict['logs'] = [x.to_dict() for x in self.logs] + if hasattr(self, 'pagination') and self.pagination is not None: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -2450,224 +2804,163 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalSystem object.""" + """Return a `str` version of this LogCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalSystem') -> bool: + def __eq__(self, other: 'LogCollection') -> 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: 'MessageContextGlobalSystem') -> bool: + def __ne__(self, other: 'LogCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LocaleEnum(str, 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(): +class LogMessageSource(): """ - Contains information specific to a particular skill used by the assistant. The - property name must be the same as the name of the skill (for example, `main skill`). + An object that identifies the dialog element that generated the error message. - :attr dict user_defined: (optional) Arbitrary variables that can be read and - written by a particular skill. - :attr MessageContextSkillSystem system: (optional) System context data used by - the skill. """ - def __init__(self, - *, - user_defined: dict = None, - system: 'MessageContextSkillSystem' = None) -> None: + def __init__(self) -> None: """ - Initialize a MessageContextSkill object. + Initialize a LogMessageSource object. - :param dict user_defined: (optional) Arbitrary variables that can be read - and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data - used by the skill. """ - self.user_defined = user_defined - self.system = system + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': - """Initialize a MessageContextSkill object from a json dictionary.""" - args = {} - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'system' in _dict: - args['system'] = MessageContextSkillSystem.from_dict( - _dict.get('system')) - return cls(**args) + def from_dict(cls, _dict: Dict) -> 'LogMessageSource': + """Initialize a LogMessageSource object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = ( + "Cannot convert dictionary into an instance of base class 'LogMessageSource'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) @classmethod - def _from_dict(cls, _dict): - """Initialize a MessageContextSkill object from a json dictionary.""" + def _from_dict(cls, _dict: Dict): + """Initialize a LogMessageSource 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, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() - 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 MessageContextSkill object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MessageContextSkill') -> 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: 'MessageContextSkill') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['dialog_node'] = 'LogMessageSourceDialogNode' + mapping['action'] = 'LogMessageSourceAction' + mapping['step'] = 'LogMessageSourceStep' + mapping['handler'] = 'LogMessageSourceHandler' + disc_value = _dict.get('type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'type\' not found in LogMessageSource JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) -class MessageContextSkillSystem(): +class LogPagination(): """ - System context data used by the skill. + The pagination data for the returned objects. - :attr str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context of a - subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. + :attr str next_url: (optional) The URL that will return the next page of + results, if any. + :attr int matched: (optional) Reserved for future use. + :attr str next_cursor: (optional) A token identifying the next page of results. """ - # The set of defined properties for the class - _properties = frozenset(['state']) - - def __init__(self, *, state: str = None, **kwargs) -> None: + def __init__(self, + *, + next_url: str = None, + matched: int = None, + next_cursor: str = None) -> None: """ - Initialize a MessageContextSkillSystem object. + Initialize a LogPagination object. - :param str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context - of a subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. - :param **kwargs: (optional) Any additional properties. + :param str next_url: (optional) The URL that will return the next page of + results, if any. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of + results. """ - self.state = state - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.next_url = next_url + self.matched = matched + self.next_cursor = next_cursor @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogPagination': + """Initialize a LogPagination object from a json dictionary.""" args = {} - if 'state' in _dict: - args['state'] = _dict.get('state') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if 'next_url' in _dict: + args['next_url'] = _dict.get('next_url') + if 'matched' in _dict: + args['matched'] = _dict.get('matched') + if 'next_cursor' in _dict: + args['next_cursor'] = _dict.get('next_cursor') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + """Initialize a LogPagination 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, 'state') and self.state is not None: - _dict['state'] = self.state - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in MessageContextSkillSystem._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillSystem object.""" + """Return a `str` version of this LogPagination object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkillSystem') -> bool: + def __eq__(self, other: 'LogPagination') -> 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: 'MessageContextSkillSystem') -> bool: + def __ne__(self, other: 'LogPagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextStateless(): +class MessageContext(): """ - MessageContextStateless. + MessageContext. - :attr MessageContextGlobalStateless global_: (optional) Session context data - that is shared by all skills used by the assistant. + :attr MessageContextGlobal global_: (optional) Session context data that is + shared by all skills used by the assistant. :attr dict skills: (optional) Information specific to particular skills used by the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. :attr object integrations: (optional) An object containing context data that is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). @@ -2675,18 +2968,16 @@ class MessageContextStateless(): def __init__(self, *, - global_: 'MessageContextGlobalStateless' = None, + global_: 'MessageContextGlobal' = None, skills: dict = None, integrations: object = None) -> None: """ - Initialize a MessageContextStateless object. + Initialize a MessageContext object. - :param MessageContextGlobalStateless global_: (optional) Session context - data that is shared by all skills used by the assistant. + :param MessageContextGlobal global_: (optional) Session context data that + is shared by all skills used by the assistant. :param dict skills: (optional) Information specific to particular skills used by the assistant. - **Note:** Currently, only a single child property is supported, containing - variables that apply to the dialog skill used by the assistant. :param object integrations: (optional) An object containing context data that is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). @@ -2696,11 +2987,11 @@ def __init__(self, self.integrations = integrations @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': - """Initialize a MessageContextStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContext': + """Initialize a MessageContext object from a json dictionary.""" args = {} if 'global' in _dict: - args['global_'] = MessageContextGlobalStateless.from_dict( + args['global_'] = MessageContextGlobal.from_dict( _dict.get('global')) if 'skills' in _dict: args['skills'] = { @@ -2713,7 +3004,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextStateless object from a json dictionary.""" + """Initialize a MessageContext object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -2732,141 +3023,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextStateless object.""" + """Return a `str` version of this MessageContext object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextStateless') -> bool: + def __eq__(self, other: 'MessageContext') -> 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: 'MessageContextStateless') -> bool: + def __ne__(self, other: 'MessageContext') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInput(): +class MessageContextGlobal(): """ - An input object that includes the input text. + Session context data that is shared by all skills used by the assistant. - :attr str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :attr str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :attr str suggestion_id: (optional) For internal use only. - :attr List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be sent - to external services by webhooks. - :attr MessageInputOptions options: (optional) Optional properties that control - how the assistant responds. + :attr MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :attr str session_id: (optional) The session ID. """ def __init__(self, *, - message_type: str = None, - text: str = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - suggestion_id: str = None, - attachments: List['MessageInputAttachment'] = None, - options: 'MessageInputOptions' = None) -> None: + system: 'MessageContextGlobalSystem' = None, + session_id: str = None) -> None: """ - Initialize a MessageInput object. + Initialize a MessageContextGlobal object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be - sent to external services by webhooks. - :param MessageInputOptions options: (optional) Optional properties that - control how the assistant responds. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.options = options + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInput': - """Initialize a MessageInput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': + """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} - if 'message_type' in _dict: - args['message_type'] = _dict.get('message_type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'suggestion_id' in _dict: - args['suggestion_id'] = _dict.get('suggestion_id') - if 'attachments' in _dict: - args['attachments'] = [ - MessageInputAttachment.from_dict(x) - for x in _dict.get('attachments') - ] - if 'options' in _dict: - args['options'] = MessageInputOptions.from_dict( - _dict.get('options')) + if 'system' in _dict: + args['system'] = MessageContextGlobalSystem.from_dict( + _dict.get('system')) + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInput object from a json dictionary.""" + """Initialize a MessageContextGlobal 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, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - _dict['attachments'] = [x.to_dict() for x in self.attachments] - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if hasattr(self, 'system') and self.system is not None: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and getattr(self, + 'session_id') is not None: + _dict['session_id'] = getattr(self, 'session_id') return _dict def _to_dict(self): @@ -2874,78 +3090,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInput object.""" + """Return a `str` version of this MessageContextGlobal object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInput') -> bool: + def __eq__(self, other: 'MessageContextGlobal') -> 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: 'MessageInput') -> bool: + def __ne__(self, other: 'MessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): - """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. - """ - TEXT = 'text' - SEARCH = 'search' - -class MessageInputAttachment(): +class MessageContextGlobalStateless(): """ - A reference to a media file to be sent as an attachment with the message. + Session context data that is shared by all skills used by the assistant. - :attr str url: The URL of the media file. - :attr str media_type: (optional) The media content type (such as a MIME type) of - the attachment. + :attr MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :attr str session_id: (optional) The unique identifier of the session. """ - def __init__(self, url: str, *, media_type: str = None) -> None: + def __init__(self, + *, + system: 'MessageContextGlobalSystem' = None, + session_id: str = None) -> None: """ - Initialize a MessageInputAttachment object. + Initialize a MessageContextGlobalStateless object. - :param str url: The URL of the media file. - :param str media_type: (optional) The media content type (such as a MIME - type) of the attachment. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. """ - self.url = url - self.media_type = media_type + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': - """Initialize a MessageInputAttachment object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': + """Initialize a MessageContextGlobalStateless object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') - else: - raise ValueError( - 'Required property \'url\' not present in MessageInputAttachment JSON' - ) - if 'media_type' in _dict: - args['media_type'] = _dict.get('media_type') + if 'system' in _dict: + args['system'] = MessageContextGlobalSystem.from_dict( + _dict.get('system')) + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputAttachment object from a json dictionary.""" + """Initialize a MessageContextGlobalStateless 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, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'media_type') and self.media_type is not None: - _dict['media_type'] = self.media_type + if hasattr(self, 'system') and self.system is not None: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id return _dict def _to_dict(self): @@ -2953,128 +3157,194 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputAttachment object.""" + """Return a `str` version of this MessageContextGlobalStateless object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputAttachment') -> bool: + def __eq__(self, other: 'MessageContextGlobalStateless') -> 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: 'MessageInputAttachment') -> bool: + def __ne__(self, other: 'MessageContextGlobalStateless') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputOptions(): +class MessageContextGlobalSystem(): """ - Optional properties that control how the assistant responds. + Built-in system properties that apply to all skills used by the assistant. - :attr bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. - :attr bool return_context: (optional) Whether to return session context with the - response. If you specify `true`, the response includes the `context` property. - If you also specify **debug**=`true`, the returned skill context includes the - `system.state` property. - :attr bool export: (optional) Whether to return session context, including full - conversation state. If you specify `true`, the response includes the `context` - property, and the skill context includes the `system.state` property. - **Note:** If **export**=`true`, the context is returned regardless of the value - of **return_context**. + :attr str timezone: (optional) The user time zone. The assistant uses the time + zone to correctly resolve relative time references. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root of + the message body. If **user_id** is specified in both locations in a message + request, the value specified at the root is used. + :attr int turn_count: (optional) A counter that is automatically incremented + 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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for the + skill. + :attr str session_start_time: (optional) The time at which the session started. + With the stateful `message` method, the start time is always present, and is set + by the service based on the time the session was created. With the stateless + `message` method, the start time is set by the service in the response to the + first message, and should be returned as part of the context with each + subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for example, + `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :attr str state: (optional) An encoded string that represents the configuration + state of the assistant at the beginning of the conversation. If you are using + the stateless `message` method, save this value and then send it in the context + of the subsequent message request to avoid disruptions if there are + configuration changes during the conversation (such as a change to a skill the + assistant uses). + :attr bool skip_user_input: (optional) For internal use only. """ def __init__(self, *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None, - return_context: bool = None, - export: bool = None) -> None: + timezone: str = None, + user_id: str = None, + turn_count: int = None, + locale: str = None, + reference_time: str = None, + session_start_time: str = None, + state: str = None, + skip_user_input: bool = None) -> None: """ - Initialize a MessageInputOptions object. + Initialize a MessageContextGlobalSystem object. - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. - :param bool return_context: (optional) Whether to return session context - with the response. If you specify `true`, the response includes the - `context` property. If you also specify **debug**=`true`, the returned - skill context includes the `system.state` property. - :param bool export: (optional) Whether to return session context, including - full conversation state. If you specify `true`, the response includes the - `context` property, and the skill context includes the `system.state` - property. - **Note:** If **export**=`true`, the context is returned regardless of the - value of **return_context**. + :param str timezone: (optional) The user time zone. The assistant uses the + time zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root + of the message body. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. + :param int turn_count: (optional) A counter that is automatically + incremented 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). + :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for + the skill. + :param str session_start_time: (optional) The time at which the session + started. With the stateful `message` method, the start time is always + present, and is set by the service based on the time the session was + created. With the stateless `message` method, the start time is set by the + service in the response to the first message, and should be returned as + part of the context with each subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the + configuration state of the assistant at the beginning of the conversation. + If you are using the stateless `message` method, save this value and then + send it in the context of the subsequent message request to avoid + disruptions if there are configuration changes during the conversation + (such as a change to a skill the assistant uses). + :param bool skip_user_input: (optional) For internal use only. """ - self.restart = restart - self.alternate_intents = alternate_intents - self.spelling = spelling - self.debug = debug - self.return_context = return_context - self.export = export + self.timezone = timezone + self.user_id = user_id + self.turn_count = turn_count + self.locale = locale + self.reference_time = reference_time + self.session_start_time = session_start_time + self.state = state + self.skip_user_input = skip_user_input @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': - """Initialize a MessageInputOptions object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': + """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') - if 'return_context' in _dict: - args['return_context'] = _dict.get('return_context') - if 'export' in _dict: - args['export'] = _dict.get('export') + if 'timezone' in _dict: + args['timezone'] = _dict.get('timezone') + if 'user_id' in _dict: + 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') + if 'session_start_time' in _dict: + args['session_start_time'] = _dict.get('session_start_time') + if 'state' in _dict: + args['state'] = _dict.get('state') + if 'skip_user_input' in _dict: + args['skip_user_input'] = _dict.get('skip_user_input') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptions object from a json dictionary.""" + """Initialize a MessageContextGlobalSystem 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, 'restart') and self.restart is not None: - _dict['restart'] = self.restart + if hasattr(self, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + if hasattr(self, 'user_id') and self.user_id is not None: + _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 + if hasattr( + self, + 'session_start_time') and self.session_start_time is not None: + _dict['session_start_time'] = self.session_start_time + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug - if hasattr(self, 'return_context') and self.return_context is not None: - _dict['return_context'] = self.return_context - if hasattr(self, 'export') and self.export is not None: - _dict['export'] = self.export + 'skip_user_input') and self.skip_user_input is not None: + _dict['skip_user_input'] = self.skip_user_input return _dict def _to_dict(self): @@ -3082,86 +3352,96 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptions object.""" + """Return a `str` version of this MessageContextGlobalSystem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptions') -> bool: + def __eq__(self, other: 'MessageContextGlobalSystem') -> 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: 'MessageInputOptions') -> bool: + def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LocaleEnum(str, 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 MessageInputOptionsSpelling(): +class MessageContextSkill(): """ - Spelling correction options for the message. Any options specified on an individual - message override the settings configured for the skill. + Contains information specific to a particular skill used by the assistant. The + property name must be the same as the name of the skill. + **Note:** The default skill names are `main skill` for the dialog skill (if enabled), + and `actions skill` for the actions skill. - :attr bool suggestions: (optional) Whether to use spelling correction when - processing the input. If spelling correction is used and **auto_correct** is - `true`, any spelling corrections are automatically applied to the user input. If - **auto_correct** is `false`, any suggested corrections are returned in the - **output.spelling** property. - This property overrides the value of the **spelling_suggestions** property in - the workspace settings for the skill. - :attr bool auto_correct: (optional) Whether to use autocorrection when - processing the input. If this property is `true`, any corrections are - automatically applied to the user input, and the original text is returned in - the **output.spelling** property of the message response. This property - overrides the value of the **spelling_auto_correct** property in the workspace - settings for the skill. + :attr dict user_defined: (optional) Arbitrary variables that can be read and + written by a particular skill. + :attr MessageContextSkillSystem system: (optional) System context data used by + the skill. """ def __init__(self, *, - suggestions: bool = None, - auto_correct: bool = None) -> None: + user_defined: dict = None, + system: 'MessageContextSkillSystem' = None) -> None: """ - Initialize a MessageInputOptionsSpelling object. + Initialize a MessageContextSkill object. - :param bool suggestions: (optional) Whether to use spelling correction when - processing the input. If spelling correction is used and **auto_correct** - is `true`, any spelling corrections are automatically applied to the user - input. If **auto_correct** is `false`, any suggested corrections are - returned in the **output.spelling** property. - This property overrides the value of the **spelling_suggestions** property - in the workspace settings for the skill. - :param bool auto_correct: (optional) Whether to use autocorrection when - processing the input. If this property is `true`, any corrections are - automatically applied to the user input, and the original text is returned - in the **output.spelling** property of the message response. This property - overrides the value of the **spelling_auto_correct** property in the - workspace settings for the skill. + :param dict user_defined: (optional) Arbitrary variables that can be read + and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. """ - self.suggestions = suggestions - self.auto_correct = auto_correct + self.user_defined = user_defined + self.system = system @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': - """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': + """Initialize a MessageContextSkill object from a json dictionary.""" args = {} - if 'suggestions' in _dict: - args['suggestions'] = _dict.get('suggestions') - if 'auto_correct' in _dict: - args['auto_correct'] = _dict.get('auto_correct') + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + if 'system' in _dict: + args['system'] = MessageContextSkillSystem.from_dict( + _dict.get('system')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + """Initialize a MessageContextSkill 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, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = self.suggestions - if hasattr(self, 'auto_correct') and self.auto_correct is not None: - _dict['auto_correct'] = self.auto_correct + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + _dict['system'] = self.system.to_dict() return _dict def _to_dict(self): @@ -3169,95 +3449,182 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptionsSpelling object.""" + """Return a `str` version of this MessageContextSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptionsSpelling') -> bool: + def __eq__(self, other: 'MessageContextSkill') -> 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: 'MessageInputOptionsSpelling') -> bool: + def __ne__(self, other: 'MessageContextSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputOptionsStateless(): +class MessageContextSkillSystem(): """ - Optional properties that control how the assistant responds. + System context data used by the skill. - :attr bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :attr str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context of a + subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + """ + + # The set of defined properties for the class + _properties = frozenset(['state']) + + def __init__(self, *, state: str = None, **kwargs) -> None: + """ + Initialize a MessageContextSkillSystem object. + + :param str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context + of a subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + :param **kwargs: (optional) Any additional properties. + """ + self.state = state + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': + """Initialize a MessageContextSkillSystem object from a json dictionary.""" + args = {} + if 'state' in _dict: + args['state'] = _dict.get('state') + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkillSystem 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, 'state') and self.state is not None: + _dict['state'] = self.state + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in MessageContextSkillSystem._properties: + setattr(self, _key, _value) + + def __str__(self) -> str: + """Return a `str` version of this MessageContextSkillSystem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkillSystem') -> 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: 'MessageContextSkillSystem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextStateless(): + """ + MessageContextStateless. + + :attr MessageContextGlobalStateless global_: (optional) Session context data + that is shared by all skills used by the assistant. + :attr dict skills: (optional) Information specific to particular skills used by + the assistant. + :attr object integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ def __init__(self, *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None) -> None: + global_: 'MessageContextGlobalStateless' = None, + skills: dict = None, + integrations: object = None) -> None: """ - Initialize a MessageInputOptionsStateless object. + Initialize a MessageContextStateless object. - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :param MessageContextGlobalStateless global_: (optional) Session context + data that is shared by all skills used by the assistant. + :param dict skills: (optional) Information specific to particular skills + used by the assistant. + :param object integrations: (optional) An object containing context data + that is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - self.restart = restart - self.alternate_intents = alternate_intents - self.spelling = spelling - self.debug = debug + self.global_ = global_ + self.skills = skills + self.integrations = integrations @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': + """Initialize a MessageContextStateless object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') + if 'global' in _dict: + args['global_'] = MessageContextGlobalStateless.from_dict( + _dict.get('global')) + if 'skills' in _dict: + args['skills'] = { + k: MessageContextSkill.from_dict(v) + for k, v in _dict.get('skills').items() + } + if 'integrations' in _dict: + args['integrations'] = _dict.get('integrations') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + """Initialize a MessageContextStateless 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, 'restart') and self.restart is not None: - _dict['restart'] = self.restart - if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug + if hasattr(self, 'global_') and self.global_ is not None: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations return _dict def _to_dict(self): @@ -3265,21 +3632,21 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptionsStateless object.""" + """Return a `str` version of this MessageContextStateless object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptionsStateless') -> bool: + def __eq__(self, other: 'MessageContextStateless') -> 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: 'MessageInputOptionsStateless') -> bool: + def __ne__(self, other: 'MessageContextStateless') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputStateless(): +class MessageInput(): """ An input object that includes the input text. @@ -3302,8 +3669,8 @@ class MessageInputStateless(): multimedia attachments to be sent with the message. **Note:** Attachments are not processed by the assistant itself, but can be sent to external services by webhooks. - :attr MessageInputOptionsStateless options: (optional) Optional properties that - control how the assistant responds. + :attr MessageInputOptions options: (optional) Optional properties that control + how the assistant responds. """ def __init__(self, @@ -3314,9 +3681,9 @@ def __init__(self, entities: List['RuntimeEntity'] = None, suggestion_id: str = None, attachments: List['MessageInputAttachment'] = None, - options: 'MessageInputOptionsStateless' = None) -> None: + options: 'MessageInputOptions' = None) -> None: """ - Initialize a MessageInputStateless object. + Initialize a MessageInput object. :param str message_type: (optional) The type of the message: - `text`: The user input is processed normally by the assistant. @@ -3339,8 +3706,8 @@ def __init__(self, multimedia attachments to be sent with the message. **Note:** Attachments are not processed by the assistant itself, but can be sent to external services by webhooks. - :param MessageInputOptionsStateless options: (optional) Optional properties - that control how the assistant responds. + :param MessageInputOptions options: (optional) Optional properties that + control how the assistant responds. """ self.message_type = message_type self.text = text @@ -3351,8 +3718,8 @@ def __init__(self, self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': - """Initialize a MessageInputStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInput': + """Initialize a MessageInput object from a json dictionary.""" args = {} if 'message_type' in _dict: args['message_type'] = _dict.get('message_type') @@ -3374,13 +3741,13 @@ def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': for x in _dict.get('attachments') ] if 'options' in _dict: - args['options'] = MessageInputOptionsStateless.from_dict( + args['options'] = MessageInputOptions.from_dict( _dict.get('options')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputStateless object from a json dictionary.""" + """Initialize a MessageInput object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -3407,16 +3774,16 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputStateless object.""" + """Return a `str` version of this MessageInput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputStateless') -> bool: + def __eq__(self, other: 'MessageInput') -> 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: 'MessageInputStateless') -> bool: + def __ne__(self, other: 'MessageInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3433,118 +3800,52 @@ class MessageTypeEnum(str, Enum): SEARCH = 'search' -class MessageOutput(): +class MessageInputAttachment(): """ - Assistant output to be rendered or processed by the client. + A reference to a media file to be sent as an attachment with the message. - :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any - channel. It is the responsibility of the client application to implement the - supported response types. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in - the user input, sorted in descending order of confidence. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified - in the user input. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing - any actions requested by the dialog node. - :attr MessageOutputDebug debug: (optional) Additional detailed information about - a message response and how it was generated. - :attr dict user_defined: (optional) An object containing any custom properties - included in the response. This object includes any arbitrary properties defined - in the dialog JSON editor as part of the dialog node output. - :attr MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + :attr str url: The URL of the media file. + :attr str media_type: (optional) The media content type (such as a MIME type) of + the attachment. """ - def __init__(self, - *, - generic: List['RuntimeResponseGeneric'] = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - actions: List['DialogNodeAction'] = None, - debug: 'MessageOutputDebug' = None, - user_defined: dict = None, - spelling: 'MessageOutputSpelling' = None) -> None: + def __init__(self, url: str, *, media_type: str = None) -> None: """ - Initialize a MessageOutput object. + Initialize a MessageInputAttachment object. - :param List[RuntimeResponseGeneric] generic: (optional) Output intended for - any channel. It is the responsibility of the client application to - implement the supported response types. - :param List[RuntimeIntent] intents: (optional) An array of intents - recognized in the user input, sorted in descending order of confidence. - :param List[RuntimeEntity] entities: (optional) An array of entities - identified in the user input. - :param List[DialogNodeAction] actions: (optional) An array of objects - describing any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information - about a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom - properties included in the response. This object includes any arbitrary - properties defined in the dialog JSON editor as part of the dialog node - output. - :param MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + :param str url: The URL of the media file. + :param str media_type: (optional) The media content type (such as a MIME + type) of the attachment. """ - self.generic = generic - self.intents = intents - self.entities = entities - self.actions = actions - self.debug = debug - self.user_defined = user_defined - self.spelling = spelling + self.url = url + self.media_type = media_type @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutput': - """Initialize a MessageOutput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': + """Initialize a MessageInputAttachment object from a json dictionary.""" args = {} - if 'generic' in _dict: - args['generic'] = [ - RuntimeResponseGeneric.from_dict(x) - for x in _dict.get('generic') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') - ] - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') - ] - if 'debug' in _dict: - args['debug'] = MessageOutputDebug.from_dict(_dict.get('debug')) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'spelling' in _dict: - args['spelling'] = MessageOutputSpelling.from_dict( - _dict.get('spelling')) + if 'url' in _dict: + args['url'] = _dict.get('url') + else: + raise ValueError( + 'Required property \'url\' not present in MessageInputAttachment JSON' + ) + if 'media_type' in _dict: + args['media_type'] = _dict.get('media_type') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutput object from a json dictionary.""" + """Initialize a MessageInputAttachment 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, 'generic') and self.generic is not None: - _dict['generic'] = [x.to_dict() for x in self.generic] - if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] - if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'actions') and self.actions is not None: - _dict['actions'] = [x.to_dict() for x in self.actions] - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug.to_dict() - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'media_type') and self.media_type is not None: + _dict['media_type'] = self.media_type return _dict def _to_dict(self): @@ -3552,97 +3853,128 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutput object.""" + """Return a `str` version of this MessageInputAttachment object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutput') -> bool: + def __eq__(self, other: 'MessageInputAttachment') -> 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: 'MessageOutput') -> bool: + def __ne__(self, other: 'MessageInputAttachment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebug(): +class MessageInputOptions(): """ - Additional detailed information about a message response and how it was generated. + Optional properties that control how the assistant responds. - :attr List[DialogNodeVisited] nodes_visited: (optional) An array of objects - containing detailed diagnostic information about dialog nodes that were - triggered during processing of the input message. - :attr List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :attr bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` - by the assistant, the `branch_exited_reason` specifies whether the dialog - completed by itself or got interrupted. + :attr bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :attr bool alternate_intents: (optional) Whether to return more than one intent. + Set to `true` to return all matching intents. + :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :attr bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. + :attr bool return_context: (optional) Whether to return session context with the + response. If you specify `true`, the response includes the `context` property. + If you also specify **debug**=`true`, the returned skill context includes the + `system.state` property. + :attr bool export: (optional) Whether to return session context, including full + conversation state. If you specify `true`, the response includes the `context` + property, and the skill context includes the `system.state` property. + **Note:** If **export**=`true`, the context is returned regardless of the value + of **return_context**. """ def __init__(self, *, - nodes_visited: List['DialogNodeVisited'] = None, - log_messages: List['DialogLogMessage'] = None, - branch_exited: bool = None, - branch_exited_reason: str = None) -> None: + restart: bool = None, + alternate_intents: bool = None, + spelling: 'MessageInputOptionsSpelling' = None, + debug: bool = None, + return_context: bool = None, + export: bool = None) -> None: """ - Initialize a MessageOutputDebug object. + Initialize a MessageInputOptions object. - :param List[DialogNodeVisited] nodes_visited: (optional) An array of - objects containing detailed diagnostic information about dialog nodes that - were triggered during processing of the input message. - :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :param bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :param str branch_exited_reason: (optional) When `branch_exited` is set to - `true` by the assistant, the `branch_exited_reason` specifies whether the - dialog completed by itself or got interrupted. + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. + :param bool return_context: (optional) Whether to return session context + with the response. If you specify `true`, the response includes the + `context` property. If you also specify **debug**=`true`, the returned + skill context includes the `system.state` property. + :param bool export: (optional) Whether to return session context, including + full conversation state. If you specify `true`, the response includes the + `context` property, and the skill context includes the `system.state` + property. + **Note:** If **export**=`true`, the context is returned regardless of the + value of **return_context**. """ - self.nodes_visited = nodes_visited - self.log_messages = log_messages - self.branch_exited = branch_exited - self.branch_exited_reason = branch_exited_reason + self.restart = restart + self.alternate_intents = alternate_intents + self.spelling = spelling + self.debug = debug + self.return_context = return_context + self.export = export @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': - """Initialize a MessageOutputDebug object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': + """Initialize a MessageInputOptions object from a json dictionary.""" args = {} - if 'nodes_visited' in _dict: - args['nodes_visited'] = [ - DialogNodeVisited.from_dict(x) - for x in _dict.get('nodes_visited') - ] - if 'log_messages' in _dict: - args['log_messages'] = [ - DialogLogMessage.from_dict(x) for x in _dict.get('log_messages') - ] - if 'branch_exited' in _dict: - args['branch_exited'] = _dict.get('branch_exited') - if 'branch_exited_reason' in _dict: - args['branch_exited_reason'] = _dict.get('branch_exited_reason') + if 'restart' in _dict: + args['restart'] = _dict.get('restart') + if 'alternate_intents' in _dict: + args['alternate_intents'] = _dict.get('alternate_intents') + if 'spelling' in _dict: + args['spelling'] = MessageInputOptionsSpelling.from_dict( + _dict.get('spelling')) + if 'debug' in _dict: + args['debug'] = _dict.get('debug') + if 'return_context' in _dict: + args['return_context'] = _dict.get('return_context') + if 'export' in _dict: + args['export'] = _dict.get('export') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebug object from a json dictionary.""" + """Initialize a MessageInputOptions 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, 'nodes_visited') and self.nodes_visited is not None: - _dict['nodes_visited'] = [x.to_dict() for x in self.nodes_visited] - if hasattr(self, 'log_messages') and self.log_messages is not None: - _dict['log_messages'] = [x.to_dict() for x in self.log_messages] - if hasattr(self, 'branch_exited') and self.branch_exited is not None: - _dict['branch_exited'] = self.branch_exited - if hasattr(self, 'branch_exited_reason' - ) and self.branch_exited_reason is not None: - _dict['branch_exited_reason'] = self.branch_exited_reason + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'spelling') and self.spelling is not None: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug + if hasattr(self, 'return_context') and self.return_context is not None: + _dict['return_context'] = self.return_context + if hasattr(self, 'export') and self.export is not None: + _dict['export'] = self.export return _dict def _to_dict(self): @@ -3650,90 +3982,86 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebug object.""" + """Return a `str` version of this MessageInputOptions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputDebug') -> bool: + def __eq__(self, other: 'MessageInputOptions') -> 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: 'MessageOutputDebug') -> bool: + def __ne__(self, other: 'MessageInputOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class BranchExitedReasonEnum(str, Enum): - """ - When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` - specifies whether the dialog completed by itself or got interrupted. - """ - COMPLETED = 'completed' - FALLBACK = 'fallback' - -class MessageOutputSpelling(): +class MessageInputOptionsSpelling(): """ - Properties describing any spelling corrections in the user input that was received. + Spelling correction options for the message. Any options specified on an individual + message override the settings configured for the skill. - :attr str text: (optional) The user input text that was used to generate the - response. If spelling autocorrection is enabled, this text reflects any spelling - corrections that were applied. - :attr str original_text: (optional) The original user input text. This property - is returned only if autocorrection is enabled and the user input was corrected. - :attr str suggested_text: (optional) Any suggested corrections of the input - text. This property is returned only if spelling correction is enabled and - autocorrection is disabled. + :attr bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** is + `true`, any spelling corrections are automatically applied to the user input. If + **auto_correct** is `false`, any suggested corrections are returned in the + **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property in + the workspace settings for the skill. + :attr bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned in + the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the workspace + settings for the skill. """ def __init__(self, *, - text: str = None, - original_text: str = None, - suggested_text: str = None) -> None: + suggestions: bool = None, + auto_correct: bool = None) -> None: """ - Initialize a MessageOutputSpelling object. + Initialize a MessageInputOptionsSpelling object. - :param str text: (optional) The user input text that was used to generate - the response. If spelling autocorrection is enabled, this text reflects any - spelling corrections that were applied. - :param str original_text: (optional) The original user input text. This - property is returned only if autocorrection is enabled and the user input - was corrected. - :param str suggested_text: (optional) Any suggested corrections of the - input text. This property is returned only if spelling correction is - enabled and autocorrection is disabled. + :param bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** + is `true`, any spelling corrections are automatically applied to the user + input. If **auto_correct** is `false`, any suggested corrections are + returned in the **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property + in the workspace settings for the skill. + :param bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned + in the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the + workspace settings for the skill. """ - self.text = text - self.original_text = original_text - self.suggested_text = suggested_text + self.suggestions = suggestions + self.auto_correct = auto_correct @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': - """Initialize a MessageOutputSpelling object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': + """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'original_text' in _dict: - args['original_text'] = _dict.get('original_text') - if 'suggested_text' in _dict: - args['suggested_text'] = _dict.get('suggested_text') + if 'suggestions' in _dict: + args['suggestions'] = _dict.get('suggestions') + if 'auto_correct' in _dict: + args['auto_correct'] = _dict.get('auto_correct') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputSpelling object from a json dictionary.""" + """Initialize a MessageInputOptionsSpelling 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'original_text') and self.original_text is not None: - _dict['original_text'] = self.original_text - if hasattr(self, 'suggested_text') and self.suggested_text is not None: - _dict['suggested_text'] = self.suggested_text + if hasattr(self, 'suggestions') and self.suggestions is not None: + _dict['suggestions'] = self.suggestions + if hasattr(self, 'auto_correct') and self.auto_correct is not None: + _dict['auto_correct'] = self.auto_correct return _dict def _to_dict(self): @@ -3741,101 +4069,95 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputSpelling object.""" + """Return a `str` version of this MessageInputOptionsSpelling object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputSpelling') -> bool: + def __eq__(self, other: 'MessageInputOptionsSpelling') -> 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: 'MessageOutputSpelling') -> bool: + def __ne__(self, other: 'MessageInputOptionsSpelling') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageRequest(): +class MessageInputOptionsStateless(): """ - A stateful message request formatted for the Watson Assistant service. + Optional properties that control how the assistant responds. - :attr MessageInput input: (optional) An input object that includes the input - text. - :attr MessageContext context: (optional) Context data for the conversation. You - can use this property to set or modify context variables, which can also be - accessed by dialog nodes. The context is stored by the assistant on a - per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. If **user_id** is specified in both locations, the value - specified at the root is used. + :attr bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :attr bool alternate_intents: (optional) Whether to return more than one intent. + Set to `true` to return all matching intents. + :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :attr bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ def __init__(self, *, - input: 'MessageInput' = None, - context: 'MessageContext' = None, - user_id: str = None) -> None: + restart: bool = None, + alternate_intents: bool = None, + spelling: 'MessageInputOptionsSpelling' = None, + debug: bool = None) -> None: """ - Initialize a MessageRequest object. + Initialize a MessageInputOptionsStateless object. - :param MessageInput input: (optional) An input object that includes the - input text. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to set or modify context variables, - which can also be accessed by dialog nodes. The context is stored by the - assistant on a per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. If **user_id** is specified in both locations, the - value specified at the root is used. + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ - self.input = input - self.context = context - self.user_id = user_id + self.restart = restart + self.alternate_intents = alternate_intents + self.spelling = spelling + self.debug = debug @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageRequest': - """Initialize a MessageRequest object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': + """Initialize a MessageInputOptionsStateless object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if 'restart' in _dict: + args['restart'] = _dict.get('restart') + if 'alternate_intents' in _dict: + args['alternate_intents'] = _dict.get('alternate_intents') + if 'spelling' in _dict: + args['spelling'] = MessageInputOptionsSpelling.from_dict( + _dict.get('spelling')) + if 'debug' in _dict: + args['debug'] = _dict.get('debug') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageRequest object from a json dictionary.""" + """Initialize a MessageInputOptionsStateless 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, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() - if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'spelling') and self.spelling is not None: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug return _dict def _to_dict(self): @@ -3843,107 +4165,141 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageRequest object.""" + """Return a `str` version of this MessageInputOptionsStateless object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageRequest') -> bool: + def __eq__(self, other: 'MessageInputOptionsStateless') -> 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: 'MessageRequest') -> bool: + def __ne__(self, other: 'MessageInputOptionsStateless') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageResponse(): +class MessageInputStateless(): """ - A response from the Watson Assistant service. + An input object that includes the input text. - :attr MessageOutput output: Assistant output to be rendered or processed by the - client. - :attr MessageContext context: (optional) Context data for the conversation. You - can use this property to access context variables. The context is stored by the - assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :attr str user_id: A string value that identifies the user who is interacting - with the assistant. The client must provide a unique identifier for each - individual end user who accesses the application. For user-based plans, this - user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :attr str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or actions skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :attr str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the + user input. Include intents from the previous response to continue using those + intents rather than trying to recognize intents in the new input. + :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :attr str suggestion_id: (optional) For internal use only. + :attr List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. + **Note:** Attachments are not processed by the assistant itself, but can be sent + to external services by webhooks. + :attr MessageInputOptionsStateless options: (optional) Optional properties that + control how the assistant responds. """ def __init__(self, - output: 'MessageOutput', - user_id: str, *, - context: 'MessageContext' = None) -> None: + message_type: str = None, + text: str = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + suggestion_id: str = None, + attachments: List['MessageInputAttachment'] = None, + options: 'MessageInputOptionsStateless' = None) -> None: """ - Initialize a MessageResponse object. + Initialize a MessageInputStateless object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param str user_id: A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier - for each individual end user who accesses the application. For user-based - plans, this user ID is used to identify unique users for billing purposes. - This string cannot contain carriage return, newline, or tab characters. If - no value is specified in the input, **user_id** is automatically set to the - value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to access context variables. The - context is stored by the assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or actions skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. + **Note:** Attachments are not processed by the assistant itself, but can be + sent to external services by webhooks. + :param MessageInputOptionsStateless options: (optional) Optional properties + that control how the assistant responds. """ - self.output = output - self.context = context - self.user_id = user_id + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponse': - """Initialize a MessageResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': + """Initialize a MessageInputStateless object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponse JSON' - ) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - else: - raise ValueError( - 'Required property \'user_id\' not present in MessageResponse JSON' - ) + if 'message_type' in _dict: + args['message_type'] = _dict.get('message_type') + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent.from_dict(x) for x in _dict.get('intents') + ] + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity.from_dict(x) for x in _dict.get('entities') + ] + if 'suggestion_id' in _dict: + args['suggestion_id'] = _dict.get('suggestion_id') + if 'attachments' in _dict: + args['attachments'] = [ + MessageInputAttachment.from_dict(x) + for x in _dict.get('attachments') + ] + if 'options' in _dict: + args['options'] = MessageInputOptionsStateless.from_dict( + _dict.get('options')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageResponse object from a json dictionary.""" + """Initialize a MessageInputStateless 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, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + _dict['intents'] = [x.to_dict() for x in self.intents] + if hasattr(self, 'entities') and self.entities is not None: + _dict['entities'] = [x.to_dict() for x in self.entities] + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + _dict['attachments'] = [x.to_dict() for x in self.attachments] + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -3951,159 +4307,260 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageResponse object.""" + """Return a `str` version of this MessageInputStateless object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageResponse') -> bool: + def __eq__(self, other: 'MessageInputStateless') -> 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: 'MessageResponse') -> bool: + def __ne__(self, other: 'MessageInputStateless') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or actions skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + TEXT = 'text' + SEARCH = 'search' + -class MessageResponseStateless(): +class MessageOutput(): """ - A stateless response from the Watson Assistant service. + Assistant output to be rendered or processed by the client. - :attr MessageOutput output: Assistant output to be rendered or processed by the - client. - :attr MessageContextStateless context: Context data for the conversation. You - can use this property to access context variables. The context is not stored by - the assistant; to maintain session state, include the context from the response - in the next message. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :attr List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :attr List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :attr MessageOutputDebug debug: (optional) Additional detailed information about + a message response and how it was generated. + :attr dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :attr MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ def __init__(self, - output: 'MessageOutput', - context: 'MessageContextStateless', *, - user_id: str = None) -> None: + generic: List['RuntimeResponseGeneric'] = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + actions: List['DialogNodeAction'] = None, + debug: 'MessageOutputDebug' = None, + user_defined: dict = None, + spelling: 'MessageOutputSpelling' = None) -> None: """ - Initialize a MessageResponseStateless object. + Initialize a MessageOutput object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param MessageContextStateless context: Context data for the conversation. - You can use this property to access context variables. The context is not - stored by the assistant; to maintain session state, include the context - from the response in the next message. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ - self.output = output - self.context = context - self.user_id = user_id + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': - """Initialize a MessageResponseStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutput': + """Initialize a MessageOutput object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponseStateless JSON' - ) - if 'context' in _dict: - args['context'] = MessageContextStateless.from_dict( - _dict.get('context')) - else: - raise ValueError( - 'Required property \'context\' not present in MessageResponseStateless JSON' - ) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MessageResponseStateless 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, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + if 'generic' in _dict: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(x) + for x in _dict.get('generic') + ] + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent.from_dict(x) for x in _dict.get('intents') + ] + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity.from_dict(x) for x in _dict.get('entities') + ] + if 'actions' in _dict: + args['actions'] = [ + DialogNodeAction.from_dict(x) for x in _dict.get('actions') + ] + if 'debug' in _dict: + args['debug'] = MessageOutputDebug.from_dict(_dict.get('debug')) + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + if 'spelling' in _dict: + args['spelling'] = MessageOutputSpelling.from_dict( + _dict.get('spelling')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutput 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, 'generic') and self.generic is not None: + _dict['generic'] = [x.to_dict() for x in self.generic] + if hasattr(self, 'intents') and self.intents is not None: + _dict['intents'] = [x.to_dict() for x in self.intents] + if hasattr(self, 'entities') and self.entities is not None: + _dict['entities'] = [x.to_dict() for x in self.entities] + if hasattr(self, 'actions') and self.actions is not None: + _dict['actions'] = [x.to_dict() for x in self.actions] + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + _dict['spelling'] = self.spelling.to_dict() + 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 MessageResponseStateless object.""" + """Return a `str` version of this MessageOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageResponseStateless') -> bool: + def __eq__(self, other: 'MessageOutput') -> 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: 'MessageResponseStateless') -> bool: + def __ne__(self, other: 'MessageOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ResponseGenericChannel(): +class MessageOutputDebug(): """ - ResponseGenericChannel. + Additional detailed information about a message response and how it was generated. - :attr str channel: (optional) A channel for which the response is intended. + :attr List[DialogNodeVisited] nodes_visited: (optional) An array of objects + containing detailed diagnostic information about dialog nodes that were visited + during processing of the input message. + :attr List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :attr bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` + by the assistant, the `branch_exited_reason` specifies whether the dialog + completed by itself or got interrupted. + :attr List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of + objects containing detailed diagnostic information about dialog nodes and + actions that were visited during processing of the input message. + This property is present only if the assistant has an actions skill. """ - def __init__(self, *, channel: str = None) -> None: + def __init__( + self, + *, + nodes_visited: List['DialogNodeVisited'] = None, + log_messages: List['DialogLogMessage'] = None, + branch_exited: bool = None, + branch_exited_reason: str = None, + turn_events: List['MessageOutputDebugTurnEvent'] = None) -> None: """ - Initialize a ResponseGenericChannel object. + Initialize a MessageOutputDebug object. - :param str channel: (optional) A channel for which the response is - intended. + :param List[DialogNodeVisited] nodes_visited: (optional) An array of + objects containing detailed diagnostic information about dialog nodes that + were visited during processing of the input message. + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :param bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the + dialog completed by itself or got interrupted. + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array + of objects containing detailed diagnostic information about dialog nodes + and actions that were visited during processing of the input message. + This property is present only if the assistant has an actions skill. """ - self.channel = channel + self.nodes_visited = nodes_visited + self.log_messages = log_messages + self.branch_exited = branch_exited + self.branch_exited_reason = branch_exited_reason + self.turn_events = turn_events @classmethod - def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': - """Initialize a ResponseGenericChannel object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': + """Initialize a MessageOutputDebug object from a json dictionary.""" args = {} - if 'channel' in _dict: - args['channel'] = _dict.get('channel') + if 'nodes_visited' in _dict: + args['nodes_visited'] = [ + DialogNodeVisited.from_dict(x) + for x in _dict.get('nodes_visited') + ] + if 'log_messages' in _dict: + args['log_messages'] = [ + DialogLogMessage.from_dict(x) for x in _dict.get('log_messages') + ] + if 'branch_exited' in _dict: + args['branch_exited'] = _dict.get('branch_exited') + if 'branch_exited_reason' in _dict: + args['branch_exited_reason'] = _dict.get('branch_exited_reason') + if 'turn_events' in _dict: + args['turn_events'] = [ + MessageOutputDebugTurnEvent.from_dict(x) + for x in _dict.get('turn_events') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ResponseGenericChannel object from a json dictionary.""" + """Initialize a MessageOutputDebug 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, 'channel') and self.channel is not None: - _dict['channel'] = self.channel + if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: + _dict['nodes_visited'] = [x.to_dict() for x in self.nodes_visited] + if hasattr(self, 'log_messages') and self.log_messages is not None: + _dict['log_messages'] = [x.to_dict() for x in self.log_messages] + if hasattr(self, 'branch_exited') and self.branch_exited is not None: + _dict['branch_exited'] = self.branch_exited + if hasattr(self, 'branch_exited_reason' + ) and self.branch_exited_reason is not None: + _dict['branch_exited_reason'] = self.branch_exited_reason + if hasattr(self, 'turn_events') and self.turn_events is not None: + _dict['turn_events'] = [x.to_dict() for x in self.turn_events] return _dict def _to_dict(self): @@ -4111,161 +4568,172 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ResponseGenericChannel object.""" + """Return a `str` version of this MessageOutputDebug object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ResponseGenericChannel') -> bool: + def __eq__(self, other: 'MessageOutputDebug') -> 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: 'ResponseGenericChannel') -> bool: + def __ne__(self, other: 'MessageOutputDebug') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class BranchExitedReasonEnum(str, Enum): + """ + When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` + specifies whether the dialog completed by itself or got interrupted. + """ + COMPLETED = 'completed' + FALLBACK = 'fallback' + -class RuntimeEntity(): +class MessageOutputDebugTurnEvent(): """ - The entity value that was recognized in the user input. + MessageOutputDebugTurnEvent. - :attr str entity: An entity detected in the input. - :attr List[int] location: (optional) An array of zero-based character offsets - that indicate where the detected entity values begin and end in the input text. - :attr str value: The term in the input text that was recognized as an entity - value. - :attr float confidence: (optional) A decimal percentage that represents Watson's - confidence in the recognized 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, - entity: str, - value: str, - *, - location: List[int] = None, - confidence: float = None, - groups: List['CaptureGroup'] = None, - interpretation: 'RuntimeEntityInterpretation' = None, - alternatives: List['RuntimeEntityAlternative'] = None, - role: 'RuntimeEntityRole' = None) -> None: + def __init__(self) -> None: """ - Initialize a RuntimeEntity object. + Initialize a MessageOutputDebugTurnEvent object. - :param str entity: An entity detected in the input. - :param str value: The term in the input text that was recognized as an - entity value. - :param List[int] location: (optional) An array of zero-based character - offsets that indicate where the detected entity values begin and end in the - input text. - :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized 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 - self.value = value - self.confidence = confidence - self.groups = groups - self.interpretation = interpretation - self.alternatives = alternatives - self.role = role + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited' + ])) + raise Exception(msg) @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': - """Initialize a RuntimeEntity object from a json dictionary.""" - args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') - else: + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = ( + "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'action_visited'] = 'MessageOutputDebugTurnEventTurnEventActionVisited' + mapping[ + 'action_finished'] = 'MessageOutputDebugTurnEventTurnEventActionFinished' + mapping[ + 'step_visited'] = 'MessageOutputDebugTurnEventTurnEventStepVisited' + mapping[ + 'step_answered'] = 'MessageOutputDebugTurnEventTurnEventStepAnswered' + mapping[ + 'handler_visited'] = 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + mapping['callout'] = 'MessageOutputDebugTurnEventTurnEventCallout' + mapping['search'] = 'MessageOutputDebugTurnEventTurnEventSearch' + mapping[ + 'node_visited'] = 'MessageOutputDebugTurnEventTurnEventNodeVisited' + disc_value = _dict.get('event') + if disc_value is None: raise ValueError( - 'Required property \'entity\' not present in RuntimeEntity JSON' + 'Discriminator property \'event\' not found in MessageOutputDebugTurnEvent JSON' ) - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'value' in _dict: - args['value'] = _dict.get('value') - else: - raise ValueError( - 'Required property \'value\' not present in RuntimeEntity JSON') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'groups' in _dict: - 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')) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class MessageOutputSpelling(): + """ + Properties describing any spelling corrections in the user input that was received. + + :attr str text: (optional) The user input text that was used to generate the + response. If spelling autocorrection is enabled, this text reflects any spelling + corrections that were applied. + :attr str original_text: (optional) The original user input text. This property + is returned only if autocorrection is enabled and the user input was corrected. + :attr str suggested_text: (optional) Any suggested corrections of the input + text. This property is returned only if spelling correction is enabled and + autocorrection is disabled. + """ + + def __init__(self, + *, + text: str = None, + original_text: str = None, + suggested_text: str = None) -> None: + """ + Initialize a MessageOutputSpelling object. + + :param str text: (optional) The user input text that was used to generate + the response. If spelling autocorrection is enabled, this text reflects any + spelling corrections that were applied. + :param str original_text: (optional) The original user input text. This + property is returned only if autocorrection is enabled and the user input + was corrected. + :param str suggested_text: (optional) Any suggested corrections of the + input text. This property is returned only if spelling correction is + enabled and autocorrection is disabled. + """ + self.text = text + self.original_text = original_text + self.suggested_text = suggested_text + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': + """Initialize a MessageOutputSpelling object from a json dictionary.""" + args = {} + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'original_text' in _dict: + args['original_text'] = _dict.get('original_text') + if 'suggested_text' in _dict: + args['suggested_text'] = _dict.get('suggested_text') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntity object from a json dictionary.""" + """Initialize a MessageOutputSpelling 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, 'entity') and self.entity is not None: - _dict['entity'] = self.entity - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location - 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 - 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() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'original_text') and self.original_text is not None: + _dict['original_text'] = self.original_text + if hasattr(self, 'suggested_text') and self.suggested_text is not None: + _dict['suggested_text'] = self.suggested_text return _dict def _to_dict(self): @@ -4273,64 +4741,101 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntity object.""" + """Return a `str` version of this MessageOutputSpelling object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntity') -> bool: + def __eq__(self, other: 'MessageOutputSpelling') -> 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: 'RuntimeEntity') -> bool: + def __ne__(self, other: 'MessageOutputSpelling') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityAlternative(): +class MessageRequest(): """ - An alternative value for the recognized entity. + A stateful message request formatted for the Watson Assistant service. - :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. + :attr MessageInput input: (optional) An input object that includes the input + text. + :attr MessageContext context: (optional) Context data for the conversation. You + can use this property to set or modify context variables, which can also be + accessed by dialog nodes. The context is stored by the assistant on a + per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. If **user_id** is specified in both locations, the value + specified at the root is used. """ - def __init__(self, *, value: str = None, confidence: float = None) -> None: + def __init__(self, + *, + input: 'MessageInput' = None, + context: 'MessageContext' = None, + user_id: str = None) -> None: """ - Initialize a RuntimeEntityAlternative object. + Initialize a MessageRequest 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. + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. """ - self.value = value - self.confidence = confidence + self.input = input + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageRequest': + """Initialize a MessageRequest object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if 'input' in _dict: + args['input'] = MessageInput.from_dict(_dict.get('input')) + if 'context' in _dict: + args['context'] = MessageContext.from_dict(_dict.get('context')) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + """Initialize a MessageRequest 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 + if hasattr(self, 'input') and self.input is not None: + _dict['input'] = self.input.to_dict() + if hasattr(self, 'context') and self.context is not None: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -4338,298 +4843,1262 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityAlternative object.""" + """Return a `str` version of this MessageRequest object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + def __eq__(self, other: 'MessageRequest') -> 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: + def __ne__(self, other: 'MessageRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityInterpretation(): +class MessageResponse(): """ - RuntimeEntityInterpretation. + A response from the Watson Assistant service. - :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`). + :attr MessageOutput output: Assistant output to be rendered or processed by the + client. + :attr MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :attr str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ def __init__(self, + output: 'MessageOutput', + user_id: str, *, - 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: + context: 'MessageContext' = None) -> None: """ - Initialize a RuntimeEntityInterpretation object. + Initialize a MessageResponse 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`). + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. """ - 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 + self.output = output + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageResponse': + """Initialize a MessageResponse object from a json dictionary.""" args = {} - 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') + if 'output' in _dict: + args['output'] = MessageOutput.from_dict(_dict.get('output')) + else: + raise ValueError( + 'Required property \'output\' not present in MessageResponse JSON' + ) + if 'context' in _dict: + args['context'] = MessageContext.from_dict(_dict.get('context')) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') + else: + raise ValueError( + 'Required property \'user_id\' not present in MessageResponse JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + """Initialize a MessageResponse 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, 'output') and self.output is not None: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + 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 MessageResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageResponse') -> 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: 'MessageResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageResponseStateless(): + """ + A stateless response from the Watson Assistant service. + + :attr MessageOutput output: Assistant output to be rendered or processed by the + client. + :attr MessageContextStateless context: Context data for the conversation. You + can use this property to access context variables. The context is not stored by + the assistant; to maintain session state, include the context from the response + in the next message. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + """ + + def __init__(self, + output: 'MessageOutput', + context: 'MessageContextStateless', + *, + user_id: str = None) -> None: + """ + Initialize a MessageResponseStateless object. + + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param MessageContextStateless context: Context data for the conversation. + You can use this property to access context variables. The context is not + stored by the assistant; to maintain session state, include the context + from the response in the next message. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + """ + self.output = output + self.context = context + self.user_id = user_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': + """Initialize a MessageResponseStateless object from a json dictionary.""" + args = {} + if 'output' in _dict: + args['output'] = MessageOutput.from_dict(_dict.get('output')) + else: + raise ValueError( + 'Required property \'output\' not present in MessageResponseStateless JSON' + ) + if 'context' in _dict: + args['context'] = MessageContextStateless.from_dict( + _dict.get('context')) + else: + raise ValueError( + 'Required property \'context\' not present in MessageResponseStateless JSON' + ) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageResponseStateless 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, 'output') and self.output is not None: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + 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 MessageResponseStateless object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageResponseStateless') -> 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: 'MessageResponseStateless') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Pagination(): + """ + The pagination data for the returned objects. + + :attr str refresh_url: The URL that will return the same page of results. + :attr str next_url: (optional) The URL that will return the next page of + results. + :attr int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the current + page. + :attr int matched: (optional) Reserved for future use. + :attr str refresh_cursor: (optional) A token identifying the current page of + results. + :attr str next_cursor: (optional) A token identifying the next page of results. + """ + + def __init__(self, + refresh_url: str, + *, + next_url: str = None, + total: int = None, + matched: int = None, + refresh_cursor: str = None, + next_cursor: str = None) -> None: + """ + Initialize a Pagination object. + + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the + current page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page + of results. + :param str next_cursor: (optional) A token identifying the next page of + results. + """ + self.refresh_url = refresh_url + self.next_url = next_url + self.total = total + self.matched = matched + self.refresh_cursor = refresh_cursor + self.next_cursor = next_cursor + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Pagination': + """Initialize a Pagination object from a json dictionary.""" + args = {} + if 'refresh_url' in _dict: + args['refresh_url'] = _dict.get('refresh_url') + else: + raise ValueError( + 'Required property \'refresh_url\' not present in Pagination JSON' + ) + if 'next_url' in _dict: + args['next_url'] = _dict.get('next_url') + if 'total' in _dict: + args['total'] = _dict.get('total') + if 'matched' in _dict: + args['matched'] = _dict.get('matched') + if 'refresh_cursor' in _dict: + args['refresh_cursor'] = _dict.get('refresh_cursor') + if 'next_cursor' in _dict: + args['next_cursor'] = _dict.get('next_cursor') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Pagination 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, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'total') and self.total is not None: + _dict['total'] = self.total + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: + _dict['refresh_cursor'] = self.refresh_cursor + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor + 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 Pagination object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Pagination') -> 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: 'Pagination') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Release(): + """ + Release. + + :attr str release: (optional) The name of the release. The name is the version + number (an integer), returned as a string. + :attr str description: (optional) The description of the release. + :attr List[EnvironmentReference] environment_references: (optional) An array of + objects describing the environments where this release has been deployed. + :attr ReleaseContent content: (optional) An object describing the versionable + content objects (such as skill snapshots) that are included in the release. + :attr str status: (optional) The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + :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. + """ + + def __init__(self, + *, + release: str = None, + description: str = None, + environment_references: List['EnvironmentReference'] = None, + content: 'ReleaseContent' = None, + status: str = None, + created: datetime = None, + updated: datetime = None) -> None: + """ + Initialize a Release object. + + :param str release: (optional) The name of the release. The name is the + version number (an integer), returned as a string. + :param str description: (optional) The description of the release. + :param ReleaseContent content: (optional) An object describing the + versionable content objects (such as skill snapshots) that are included in + the release. + :param str status: (optional) The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + """ + self.release = release + self.description = description + self.environment_references = environment_references + self.content = content + self.status = status + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Release': + """Initialize a Release object from a json dictionary.""" + args = {} + if 'release' in _dict: + args['release'] = _dict.get('release') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'environment_references' in _dict: + args['environment_references'] = [ + EnvironmentReference.from_dict(x) + for x in _dict.get('environment_references') + ] + if 'content' in _dict: + args['content'] = ReleaseContent.from_dict(_dict.get('content')) + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Release 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, 'release') and self.release is not None: + _dict['release'] = self.release + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'environment_references') and getattr( + self, 'environment_references') is not None: + _dict['environment_references'] = [ + x.to_dict() for x in getattr(self, 'environment_references') + ] + if hasattr(self, 'content') and self.content is not None: + _dict['content'] = self.content.to_dict() + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + 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 Release object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Release') -> 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: 'Release') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + """ + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class ReleaseCollection(): + """ + ReleaseCollection. + + :attr List[Release] releases: An array of objects describing the releases + associated with an assistant. + :attr Pagination pagination: The pagination data for the returned objects. + """ + + def __init__(self, releases: List['Release'], + pagination: 'Pagination') -> None: + """ + Initialize a ReleaseCollection object. + + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. + """ + self.releases = releases + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': + """Initialize a ReleaseCollection object from a json dictionary.""" + args = {} + if 'releases' in _dict: + args['releases'] = [ + Release.from_dict(x) for x in _dict.get('releases') + ] + else: + raise ValueError( + 'Required property \'releases\' not present in ReleaseCollection JSON' + ) + if 'pagination' in _dict: + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in ReleaseCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseCollection 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, 'releases') and self.releases is not None: + _dict['releases'] = [x.to_dict() for x in self.releases] + if hasattr(self, 'pagination') and self.pagination is not None: + _dict['pagination'] = self.pagination.to_dict() + 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 ReleaseCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseCollection') -> 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: 'ReleaseCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseContent(): + """ + An object describing the versionable content objects (such as skill snapshots) that + are included in the release. + + :attr List[ReleaseSkillReference] skills: (optional) The skill snapshots that + are included in the release. + """ + + def __init__(self, *, skills: List['ReleaseSkillReference'] = None) -> None: + """ + Initialize a ReleaseContent object. + + """ + self.skills = skills + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseContent': + """Initialize a ReleaseContent object from a json dictionary.""" + args = {} + if 'skills' in _dict: + args['skills'] = [ + ReleaseSkillReference.from_dict(x) for x in _dict.get('skills') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseContent 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, 'skills') and getattr(self, 'skills') is not None: + _dict['skills'] = [x.to_dict() for x in getattr(self, 'skills')] + 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 ReleaseContent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseContent') -> 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: 'ReleaseContent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseSkillReference(): + """ + ReleaseSkillReference. + + :attr str skill_id: (optional) The skill ID of the skill. + :attr str type: (optional) The type of the skill. + :attr str snapshot: (optional) The name of the snapshot (skill version) that is + saved as part of the release (for example, `draft` or `1`). + """ + + def __init__(self, + *, + skill_id: str = None, + type: str = None, + snapshot: str = None) -> None: + """ + Initialize a ReleaseSkillReference object. + + :param str skill_id: (optional) The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the snapshot (skill version) + that is saved as part of the release (for example, `draft` or `1`). + """ + self.skill_id = skill_id + self.type = type + self.snapshot = snapshot + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseSkillReference': + """Initialize a ReleaseSkillReference object from a json dictionary.""" + args = {} + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'snapshot' in _dict: + args['snapshot'] = _dict.get('snapshot') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseSkillReference 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, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + 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 ReleaseSkillReference object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseSkillReference') -> 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: 'ReleaseSkillReference') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of the skill. + """ + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + + +class ResponseGenericChannel(): + """ + ResponseGenericChannel. + + :attr str channel: (optional) A channel for which the response is intended. + """ + + def __init__(self, *, channel: str = None) -> None: + """ + Initialize a ResponseGenericChannel object. + + :param str channel: (optional) A channel for which the response is + intended. + """ + self.channel = channel + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': + """Initialize a ResponseGenericChannel object from a json dictionary.""" + args = {} + if 'channel' in _dict: + args['channel'] = _dict.get('channel') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericChannel 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, 'channel') and self.channel is not None: + _dict['channel'] = self.channel + 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 ResponseGenericChannel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericChannel') -> 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: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntity(): + """ + The entity value that was recognized in the user input. + + :attr str entity: An entity detected in the input. + :attr List[int] location: (optional) An array of zero-based character offsets + that indicate where the detected entity values begin and end in the input text. + :attr str value: The term in the input text that was recognized as an entity + value. + :attr float confidence: (optional) A decimal percentage that represents Watson's + confidence in the recognized 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. + :attr str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill (if + enabled) and `actions skill` for the actions skill. + This property is present only if the assistant has both a dialog skill and an + actions skill. + """ + + def __init__(self, + entity: str, + value: str, + *, + location: List[int] = None, + confidence: float = None, + groups: List['CaptureGroup'] = None, + interpretation: 'RuntimeEntityInterpretation' = None, + alternatives: List['RuntimeEntityAlternative'] = None, + role: 'RuntimeEntityRole' = None, + skill: str = None) -> None: + """ + Initialize a RuntimeEntity object. + + :param str entity: An entity detected in the input. + :param str value: The term in the input text that was recognized as an + entity value. + :param List[int] location: (optional) An array of zero-based character + offsets that indicate where the detected entity values begin and end in the + input text. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the recognized 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. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the actions skill. + This property is present only if the assistant has both a dialog skill and + an actions skill. + """ + self.entity = entity + self.location = location + self.value = value + self.confidence = confidence + self.groups = groups + self.interpretation = interpretation + self.alternatives = alternatives + self.role = role + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': + """Initialize a RuntimeEntity object from a json dictionary.""" + args = {} + if 'entity' in _dict: + args['entity'] = _dict.get('entity') + else: + raise ValueError( + 'Required property \'entity\' not present in RuntimeEntity JSON' + ) + if 'location' in _dict: + args['location'] = _dict.get('location') + if 'value' in _dict: + args['value'] = _dict.get('value') + else: + raise ValueError( + 'Required property \'value\' not present in RuntimeEntity JSON') + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + if 'groups' in _dict: + 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')) + if 'skill' in _dict: + args['skill'] = _dict.get('skill') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntity 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, 'entity') and self.entity is not None: + _dict['entity'] = self.entity + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + 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 + 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() + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + 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 RuntimeEntity object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntity') -> 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: 'RuntimeEntity') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + 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 = {} + 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 = {} + 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: @@ -4676,13 +6145,1154 @@ def to_dict(self) -> Dict: 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 + '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(str, 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 = {} + 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(str, 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. + + :attr str intent: The name of the recognized intent. + :attr float confidence: (optional) A decimal percentage that represents Watson's + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. + :attr str skill: (optional) The skill that identified the intent. Currently, the + only possible values are `main skill` for the dialog skill (if enabled) and + `actions skill` for the actions skill. + This property is present only if the assistant has both a dialog skill and an + actions skill. + """ + + def __init__(self, + intent: str, + *, + confidence: float = None, + skill: str = None) -> None: + """ + Initialize a RuntimeIntent object. + + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the intent. If you are specifying an intent as part + of a request, but you do not have a calculated confidence value, specify + `1`. + :param str skill: (optional) The skill that identified the intent. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the actions skill. + This property is present only if the assistant has both a dialog skill and + an actions skill. + """ + self.intent = intent + self.confidence = confidence + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': + """Initialize a RuntimeIntent object from a json dictionary.""" + args = {} + if 'intent' in _dict: + args['intent'] = _dict.get('intent') + else: + raise ValueError( + 'Required property \'intent\' not present in RuntimeIntent JSON' + ) + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + if 'skill' in _dict: + args['skill'] = _dict.get('skill') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeIntent 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, 'intent') and self.intent is not None: + _dict['intent'] = self.intent + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + 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 RuntimeIntent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeIntent') -> 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: 'RuntimeIntent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGeneric(): + """ + RuntimeResponseGeneric. + + """ + + def __init__(self) -> None: + """ + Initialize a RuntimeResponseGeneric object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = ( + "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' + mapping[ + 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + mapping[ + 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' + mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' + mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' + mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' + mapping[ + 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' + mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' + mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + mapping[ + 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class SearchResult(): + """ + SearchResult. + + :attr str id: The unique identifier of the document in the Discovery service + collection. + This property is included in responses from search skills, which are available + only to Plus or Enterprise plan users. + :attr SearchResultMetadata result_metadata: An object containing search result + metadata from the Discovery service. + :attr str body: (optional) A description of the search result. This is taken + from an abstract, summary, or highlight field in the Discovery service response, + as specified in the search skill configuration. + :attr str title: (optional) The title of the search result. This is taken from a + title or name field in the Discovery service response, as specified in the + search skill configuration. + :attr str url: (optional) The URL of the original data object in its native data + source. + :attr SearchResultHighlight highlight: (optional) An object containing segments + of text from search results with query-matching text highlighted using HTML + `` tags. + :attr List[SearchResultAnswer] answers: (optional) An array specifying segments + of text within the result that were identified as direct answers to the search + query. Currently, only the single answer with the highest confidence (if any) is + returned. + **Note:** This property uses the answer finding beta feature, and is available + only if the search skill is connected to a Discovery v2 service instance. + """ + + def __init__(self, + id: str, + result_metadata: 'SearchResultMetadata', + *, + body: str = None, + title: str = None, + url: str = None, + highlight: 'SearchResultHighlight' = None, + answers: List['SearchResultAnswer'] = None) -> None: + """ + Initialize a SearchResult object. + + :param str id: The unique identifier of the document in the Discovery + service collection. + This property is included in responses from search skills, which are + available only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search + result metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is + taken from an abstract, summary, or highlight field in the Discovery + service response, as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken + from a title or name field in the Discovery service response, as specified + in the search skill configuration. + :param str url: (optional) The URL of the original data object in its + native data source. + :param SearchResultHighlight highlight: (optional) An object containing + segments of text from search results with query-matching text highlighted + using HTML `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying + segments of text within the result that were identified as direct answers + to the search query. Currently, only the single answer with the highest + confidence (if any) is returned. + **Note:** This property uses the answer finding beta feature, and is + available only if the search skill is connected to a Discovery v2 service + instance. + """ + self.id = id + self.result_metadata = result_metadata + self.body = body + self.title = title + self.url = url + self.highlight = highlight + self.answers = answers + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResult': + """Initialize a SearchResult object from a json dictionary.""" + args = {} + if 'id' in _dict: + args['id'] = _dict.get('id') + else: + raise ValueError( + 'Required property \'id\' not present in SearchResult JSON') + if 'result_metadata' in _dict: + args['result_metadata'] = SearchResultMetadata.from_dict( + _dict.get('result_metadata')) + else: + raise ValueError( + 'Required property \'result_metadata\' not present in SearchResult JSON' + ) + if 'body' in _dict: + args['body'] = _dict.get('body') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'url' in _dict: + args['url'] = _dict.get('url') + if 'highlight' in _dict: + args['highlight'] = SearchResultHighlight.from_dict( + _dict.get('highlight')) + if 'answers' in _dict: + args['answers'] = [ + SearchResultAnswer.from_dict(x) for x in _dict.get('answers') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResult 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, 'id') and self.id is not None: + _dict['id'] = self.id + if hasattr(self, + 'result_metadata') and self.result_metadata is not None: + _dict['result_metadata'] = self.result_metadata.to_dict() + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight.to_dict() + if hasattr(self, 'answers') and self.answers is not None: + _dict['answers'] = [x.to_dict() for x in self.answers] + 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 SearchResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResult') -> 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: 'SearchResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultAnswer(): + """ + An object specifing a segment of text that was identified as a direct answer to the + search query. + + :attr str text: The text of the answer. + :attr float confidence: The confidence score for the answer, as returned by the + Discovery service. + """ + + def __init__(self, text: str, confidence: float) -> None: + """ + Initialize a SearchResultAnswer object. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned + by the Discovery service. + """ + self.text = text + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': + """Initialize a SearchResultAnswer object from a json dictionary.""" + args = {} + if 'text' in _dict: + args['text'] = _dict.get('text') + else: + raise ValueError( + 'Required property \'text\' not present in SearchResultAnswer JSON' + ) + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + else: + raise ValueError( + 'Required property \'confidence\' not present in SearchResultAnswer JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultAnswer 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, 'text') and self.text is not None: + _dict['text'] = self.text + 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 SearchResultAnswer object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultAnswer') -> 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: 'SearchResultAnswer') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultHighlight(): + """ + An object containing segments of text from search results with query-matching text + highlighted using HTML `` tags. + + :attr List[str] body: (optional) An array of strings containing segments taken + from body text in the search results, with query-matching substrings + highlighted. + :attr List[str] title: (optional) An array of strings containing segments taken + from title text in the search results, with query-matching substrings + highlighted. + :attr List[str] url: (optional) An array of strings containing segments taken + from URLs in the search results, with query-matching substrings highlighted. + """ + + # The set of defined properties for the class + _properties = frozenset(['body', 'title', 'url']) + + def __init__(self, + *, + body: List[str] = None, + title: List[str] = None, + url: List[str] = None, + **kwargs) -> None: + """ + Initialize a SearchResultHighlight object. + + :param List[str] body: (optional) An array of strings containing segments + taken from body text in the search results, with query-matching substrings + highlighted. + :param List[str] title: (optional) An array of strings containing segments + taken from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments + taken from URLs in the search results, with query-matching substrings + highlighted. + :param **kwargs: (optional) Any additional properties. + """ + self.body = body + self.title = title + self.url = url + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': + """Initialize a SearchResultHighlight object from a json dictionary.""" + args = {} + if 'body' in _dict: + args['body'] = _dict.get('body') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'url' in _dict: + args['url'] = _dict.get('url') + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultHighlight 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, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in SearchResultHighlight._properties: + setattr(self, _key, _value) + + def __str__(self) -> str: + """Return a `str` version of this SearchResultHighlight object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultHighlight') -> 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: 'SearchResultHighlight') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultMetadata(): + """ + An object containing search result metadata from the Discovery service. + + :attr float confidence: (optional) The confidence score for the given result, as + returned by the Discovery service. + :attr float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher score + indicates a greater match to the query parameters. + """ + + def __init__(self, + *, + confidence: float = None, + score: float = None) -> None: + """ + Initialize a SearchResultMetadata object. + + :param float confidence: (optional) The confidence score for the given + result, as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher + score indicates a greater match to the query parameters. + """ + self.confidence = confidence + self.score = score + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': + """Initialize a SearchResultMetadata object from a json dictionary.""" + args = {} + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + if 'score' in _dict: + args['score'] = _dict.get('score') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultMetadata 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, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score + 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 SearchResultMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultMetadata') -> 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: 'SearchResultMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SessionResponse(): + """ + SessionResponse. + + :attr str session_id: The session ID. + """ + + def __init__(self, session_id: str) -> None: + """ + Initialize a SessionResponse object. + + :param str session_id: The session ID. + """ + self.session_id = session_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SessionResponse': + """Initialize a SessionResponse object from a json dictionary.""" + args = {} + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') + else: + raise ValueError( + 'Required property \'session_id\' not present in SessionResponse JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SessionResponse 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, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + 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 SessionResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SessionResponse') -> 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: 'SessionResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SkillReference(): + """ + SkillReference. + + :attr str skill_id: (optional) The skill ID of the skill. + :attr str type: (optional) The type of the skill. + :attr bool disabled: (optional) Whether the skill is disabled. A disabled skill + in the draft environment does not handle any messages at run time, and it is not + included in saved releases. + :attr str snapshot: (optional) The name of the snapshot (skill version) that is + saved as part of the release (for example, `draft` or `1`). + :attr str skill_reference: (optional) The type of skill identified by the skill + reference. The possible values are `main skill` (for a dialog skill), `actions + skill`, and `search skill`. + """ + + def __init__(self, + *, + skill_id: str = None, + type: str = None, + disabled: bool = None, + snapshot: str = None, + skill_reference: str = None) -> None: + """ + Initialize a SkillReference object. + + :param str skill_id: (optional) The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param bool disabled: (optional) Whether the skill is disabled. A disabled + skill in the draft environment does not handle any messages at run time, + and it is not included in saved releases. + :param str snapshot: (optional) The name of the snapshot (skill version) + that is saved as part of the release (for example, `draft` or `1`). + :param str skill_reference: (optional) The type of skill identified by the + skill reference. The possible values are `main skill` (for a dialog skill), + `actions skill`, and `search skill`. + """ + self.skill_id = skill_id + self.type = type + self.disabled = disabled + self.snapshot = snapshot + self.skill_reference = skill_reference + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SkillReference': + """Initialize a SkillReference object from a json dictionary.""" + args = {} + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'disabled' in _dict: + args['disabled'] = _dict.get('disabled') + if 'snapshot' in _dict: + args['snapshot'] = _dict.get('snapshot') + if 'skill_reference' in _dict: + args['skill_reference'] = _dict.get('skill_reference') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SkillReference 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, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'disabled') and self.disabled is not None: + _dict['disabled'] = self.disabled + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot 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 + 'skill_reference') and self.skill_reference is not None: + _dict['skill_reference'] = self.skill_reference + 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 SkillReference object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SkillReference') -> 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: 'SkillReference') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of the skill. + """ + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + + +class TurnEventActionSource(): + """ + TurnEventActionSource. + + :attr str type: (optional) The type of turn event. + :attr str action: (optional) An action that was visited during processing of the + message. + :attr str action_title: (optional) The title of the action. + :attr str condition: (optional) The condition that triggered the dialog node. + """ + + def __init__(self, + *, + type: str = None, + action: str = None, + action_title: str = None, + condition: str = None) -> None: + """ + Initialize a TurnEventActionSource object. + + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing + of the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog + node. + """ + self.type = type + self.action = action + self.action_title = action_title + self.condition = condition + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventActionSource': + """Initialize a TurnEventActionSource object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'action' in _dict: + args['action'] = _dict.get('action') + if 'action_title' in _dict: + args['action_title'] = _dict.get('action_title') + if 'condition' in _dict: + args['condition'] = _dict.get('condition') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventActionSource 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 + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'action_title') and self.action_title is not None: + _dict['action_title'] = self.action_title + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition + 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 TurnEventActionSource object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TurnEventActionSource') -> 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: 'TurnEventActionSource') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of turn event. + """ + ACTION = 'action' + + +class TurnEventCalloutCallout(): + """ + TurnEventCalloutCallout. + + :attr str type: (optional) callout type. + :attr dict internal: (optional) For internal use only. + """ + + def __init__(self, *, type: str = None, internal: dict = None) -> None: + """ + Initialize a TurnEventCalloutCallout object. + + :param str type: (optional) callout type. + :param dict internal: (optional) For internal use only. + """ + self.type = type + self.internal = internal + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': + """Initialize a TurnEventCalloutCallout object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'internal' in _dict: + args['internal'] = _dict.get('internal') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventCalloutCallout 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 + if hasattr(self, 'internal') and self.internal is not None: + _dict['internal'] = self.internal + 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 TurnEventCalloutCallout object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TurnEventCalloutCallout') -> 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: 'TurnEventCalloutCallout') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + callout type. + """ + INTEGRATION_INTERACTION = 'integration_interaction' + + +class TurnEventCalloutError(): + """ + TurnEventCalloutError. + + :attr str message: (optional) Any error message returned by a failed call to an + external service. + """ + + def __init__(self, *, message: str = None) -> None: + """ + Initialize a TurnEventCalloutError object. + + :param str message: (optional) Any error message returned by a failed call + to an external service. + """ + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutError': + """Initialize a TurnEventCalloutError object from a json dictionary.""" + args = {} + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventCalloutError 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, 'message') and self.message is not None: + _dict['message'] = self.message + 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 TurnEventCalloutError object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TurnEventCalloutError') -> 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: 'TurnEventCalloutError') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TurnEventNodeSource(): + """ + TurnEventNodeSource. + + :attr str type: (optional) The type of turn event. + :attr str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :attr str title: (optional) The title of the dialog node. + :attr str condition: (optional) The condition that triggered the dialog node. + """ + + def __init__(self, + *, + type: str = None, + dialog_node: str = None, + title: str = None, + condition: str = None) -> None: + """ + Initialize a TurnEventNodeSource object. + + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str condition: (optional) The condition that triggered the dialog + node. + """ + self.type = type + self.dialog_node = dialog_node + self.title = title + self.condition = condition + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventNodeSource': + """Initialize a TurnEventNodeSource object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'dialog_node' in _dict: + args['dialog_node'] = _dict.get('dialog_node') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'condition' in _dict: + args['condition'] = _dict.get('condition') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventNodeSource 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 + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition return _dict def _to_dict(self): @@ -4690,65 +7300,126 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityInterpretation object.""" + """Return a `str` version of this TurnEventNodeSource object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + def __eq__(self, other: 'TurnEventNodeSource') -> 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: + def __ne__(self, other: 'TurnEventNodeSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class GranularityEnum(str, Enum): + class TypeEnum(str, Enum): """ - The precision or duration of a time range specified by a recognized `@sys-time` or - `@sys-date` entity. + The type of turn event. """ - DAY = 'day' - FORTNIGHT = 'fortnight' - HOUR = 'hour' - INSTANT = 'instant' - MINUTE = 'minute' - MONTH = 'month' - QUARTER = 'quarter' - SECOND = 'second' - WEEK = 'week' - WEEKEND = 'weekend' - YEAR = 'year' + DIALOG_NODE = 'dialog_node' -class RuntimeEntityRole(): +class TurnEventSearchError(): """ - 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. + TurnEventSearchError. - :attr str type: (optional) The relationship of the entity to the range. + :attr str message: (optional) Any error message returned by a failed call to a + search skill. """ - def __init__(self, *, type: str = None) -> None: + def __init__(self, *, message: str = None) -> None: """ - Initialize a RuntimeEntityRole object. + Initialize a TurnEventSearchError object. - :param str type: (optional) The relationship of the entity to the range. + :param str message: (optional) Any error message returned by a failed call + to a search skill. + """ + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError': + """Initialize a TurnEventSearchError object from a json dictionary.""" + args = {} + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventSearchError 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, 'message') and self.message is not None: + _dict['message'] = self.message + 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 TurnEventSearchError object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'TurnEventSearchError') -> 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: 'TurnEventSearchError') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogMessageSourceAction(LogMessageSource): + """ + An object that identifies the dialog element that generated the error message. + + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str action: The unique identifier of the action that generated the error + message. + """ + + def __init__(self, type: str, action: str) -> None: + """ + Initialize a LogMessageSourceAction object. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. """ + # pylint: disable=super-init-not-called self.type = type + self.action = action @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': - """Initialize a RuntimeEntityRole object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': + """Initialize a LogMessageSourceAction object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceAction JSON' + ) + if 'action' in _dict: + args['action'] = _dict.get('action') + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceAction JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityRole object from a json dictionary.""" + """Initialize a LogMessageSourceAction object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -4756,6 +7427,8 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action return _dict def _to_dict(self): @@ -4763,81 +7436,73 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityRole object.""" + """Return a `str` version of this LogMessageSourceAction object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityRole') -> bool: + def __eq__(self, other: 'LogMessageSourceAction') -> 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: + def __ne__(self, other: 'LogMessageSourceAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, 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(): +class LogMessageSourceDialogNode(LogMessageSource): """ - An intent identified in the user input. + An object that identifies the dialog element that generated the error message. - :attr str intent: The name of the recognized intent. - :attr float confidence: A decimal percentage that represents Watson's confidence - in the intent. + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str dialog_node: The unique identifier of the dialog node that generated + the error message. """ - def __init__(self, intent: str, confidence: float) -> None: + def __init__(self, type: str, dialog_node: str) -> None: """ - Initialize a RuntimeIntent object. + Initialize a LogMessageSourceDialogNode object. - :param str intent: The name of the recognized intent. - :param float confidence: A decimal percentage that represents Watson's - confidence in the intent. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str dialog_node: The unique identifier of the dialog node that + generated the error message. """ - self.intent = intent - self.confidence = confidence + # pylint: disable=super-init-not-called + self.type = type + self.dialog_node = dialog_node @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': - """Initialize a RuntimeIntent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': + """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if 'type' in _dict: + args['type'] = _dict.get('type') else: raise ValueError( - 'Required property \'intent\' not present in RuntimeIntent JSON' + 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if 'dialog_node' in _dict: + args['dialog_node'] = _dict.get('dialog_node') else: raise ValueError( - 'Required property \'confidence\' not present in RuntimeIntent JSON' + 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeIntent object from a json dictionary.""" + """Initialize a LogMessageSourceDialogNode 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, 'intent') and self.intent is not None: - _dict['intent'] = self.intent - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node return _dict def _to_dict(self): @@ -4845,240 +7510,187 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeIntent object.""" + """Return a `str` version of this LogMessageSourceDialogNode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeIntent') -> bool: + def __eq__(self, other: 'LogMessageSourceDialogNode') -> 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: 'RuntimeIntent') -> bool: + def __ne__(self, other: 'LogMessageSourceDialogNode') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeResponseGeneric(): +class LogMessageSourceHandler(LogMessageSource): """ - RuntimeResponseGeneric. + An object that identifies the dialog element that generated the error message. + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str action: The unique identifier of the action that generated the error + message. + :attr str step: (optional) The unique identifier of the step that generated the + error message. + :attr str handler: The unique identifier of the handler that generated the error + message. """ - def __init__(self) -> None: + def __init__(self, + type: str, + action: str, + handler: str, + *, + step: str = None) -> None: """ - Initialize a RuntimeResponseGeneric object. + Initialize a LogMessageSourceHandler object. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str handler: The unique identifier of the handler that generated the + error message. + :param str step: (optional) The unique identifier of the step that + generated the error message. """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe' - ])) - raise Exception(msg) + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step + self.handler = handler @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe' - ])) - raise Exception(msg) + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': + """Initialize a LogMessageSourceHandler object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceHandler JSON' + ) + if 'action' in _dict: + args['action'] = _dict.get('action') + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceHandler JSON' + ) + if 'step' in _dict: + args['step'] = _dict.get('step') + if 'handler' in _dict: + args['handler'] = _dict.get('handler') + else: + raise ValueError( + 'Required property \'handler\' not present in LogMessageSourceHandler JSON' + ) + return cls(**args) @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + def _from_dict(cls, _dict): + """Initialize a LogMessageSourceHandler object from a json dictionary.""" return cls.from_dict(_dict) - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' - mapping[ - 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' - mapping[ - 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' - mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' - mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' - mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' - mapping[ - 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' - mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' - mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' - mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' - mapping[ - 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' - mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' - disc_value = _dict.get('response_type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) + 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 + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'handler') and self.handler is not None: + _dict['handler'] = self.handler + return _dict + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() -class SearchResult(): + def __str__(self) -> str: + """Return a `str` version of this LogMessageSourceHandler object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogMessageSourceHandler') -> 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: 'LogMessageSourceHandler') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogMessageSourceStep(LogMessageSource): """ - SearchResult. + An object that identifies the dialog element that generated the error message. - :attr str id: The unique identifier of the document in the Discovery service - collection. - This property is included in responses from search skills, which are available - only to Plus or Enterprise plan users. - :attr SearchResultMetadata result_metadata: An object containing search result - metadata from the Discovery service. - :attr str body: (optional) A description of the search result. This is taken - from an abstract, summary, or highlight field in the Discovery service response, - as specified in the search skill configuration. - :attr str title: (optional) The title of the search result. This is taken from a - title or name field in the Discovery service response, as specified in the - search skill configuration. - :attr str url: (optional) The URL of the original data object in its native data - source. - :attr SearchResultHighlight highlight: (optional) An object containing segments - of text from search results with query-matching text highlighted using HTML - `` tags. - :attr List[SearchResultAnswer] answers: (optional) An array specifying segments - of text within the result that were identified as direct answers to the search - query. Currently, only the single answer with the highest confidence (if any) is - returned. - **Note:** This property uses the answer finding beta feature, and is available - only if the search skill is connected to a Discovery v2 service instance. + :attr str type: A string that indicates the type of dialog element that + generated the error message. + :attr str action: The unique identifier of the action that generated the error + message. + :attr str step: The unique identifier of the step that generated the error + message. """ - def __init__(self, - id: str, - result_metadata: 'SearchResultMetadata', - *, - body: str = None, - title: str = None, - url: str = None, - highlight: 'SearchResultHighlight' = None, - answers: List['SearchResultAnswer'] = None) -> None: + def __init__(self, type: str, action: str, step: str) -> None: """ - Initialize a SearchResult object. + Initialize a LogMessageSourceStep object. - :param str id: The unique identifier of the document in the Discovery - service collection. - This property is included in responses from search skills, which are - available only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search - result metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is - taken from an abstract, summary, or highlight field in the Discovery - service response, as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken - from a title or name field in the Discovery service response, as specified - in the search skill configuration. - :param str url: (optional) The URL of the original data object in its - native data source. - :param SearchResultHighlight highlight: (optional) An object containing - segments of text from search results with query-matching text highlighted - using HTML `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying - segments of text within the result that were identified as direct answers - to the search query. Currently, only the single answer with the highest - confidence (if any) is returned. - **Note:** This property uses the answer finding beta feature, and is - available only if the search skill is connected to a Discovery v2 service - instance. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str step: The unique identifier of the step that generated the error + message. """ - self.id = id - self.result_metadata = result_metadata - self.body = body - self.title = title - self.url = url - self.highlight = highlight - self.answers = answers + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResult': - """Initialize a SearchResult object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': + """Initialize a LogMessageSourceStep object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') + if 'type' in _dict: + args['type'] = _dict.get('type') else: raise ValueError( - 'Required property \'id\' not present in SearchResult JSON') - if 'result_metadata' in _dict: - args['result_metadata'] = SearchResultMetadata.from_dict( - _dict.get('result_metadata')) + 'Required property \'type\' not present in LogMessageSourceStep JSON' + ) + if 'action' in _dict: + args['action'] = _dict.get('action') else: raise ValueError( - 'Required property \'result_metadata\' not present in SearchResult JSON' + 'Required property \'action\' not present in LogMessageSourceStep JSON' + ) + if 'step' in _dict: + args['step'] = _dict.get('step') + else: + raise ValueError( + 'Required property \'step\' not present in LogMessageSourceStep JSON' ) - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'highlight' in _dict: - args['highlight'] = SearchResultHighlight.from_dict( - _dict.get('highlight')) - if 'answers' in _dict: - args['answers'] = [ - SearchResultAnswer.from_dict(x) for x in _dict.get('answers') - ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResult object from a json dictionary.""" + """Initialize a LogMessageSourceStep 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, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight.to_dict() - if hasattr(self, 'answers') and self.answers is not None: - _dict['answers'] = [x.to_dict() for x in self.answers] + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step return _dict def _to_dict(self): @@ -5086,71 +7698,108 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResult object.""" + """Return a `str` version of this LogMessageSourceStep object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResult') -> bool: + def __eq__(self, other: 'LogMessageSourceStep') -> 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: 'SearchResult') -> bool: + def __ne__(self, other: 'LogMessageSourceStep') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultAnswer(): +class MessageOutputDebugTurnEventTurnEventActionFinished( + MessageOutputDebugTurnEvent): """ - An object specifing a segment of text that was identified as a direct answer to the - search query. + MessageOutputDebugTurnEventTurnEventActionFinished. - :attr str text: The text of the answer. - :attr float confidence: The confidence score for the answer, as returned by the - Discovery service. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr str action_start_time: (optional) The time when the action started + processing the message. + :attr str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :attr str reason: (optional) The reason the action finished processing. + :attr dict action_variables: (optional) The state of all action variables at the + time the action finished. """ - def __init__(self, text: str, confidence: float) -> None: - """ - Initialize a SearchResultAnswer object. - - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned - by the Discovery service. + def __init__(self, + *, + event: str = None, + source: 'TurnEventActionSource' = None, + action_start_time: str = None, + condition_type: str = None, + reason: str = None, + action_variables: dict = None) -> None: + """ + Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables + at the time the action finished. """ - self.text = text - self.confidence = confidence + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason + self.action_variables = action_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': - """Initialize a SearchResultAnswer object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventActionFinished': + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in SearchResultAnswer JSON' - ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - else: - raise ValueError( - 'Required property \'confidence\' not present in SearchResultAnswer JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'action_start_time' in _dict: + args['action_start_time'] = _dict.get('action_start_time') + if 'condition_type' in _dict: + args['condition_type'] = _dict.get('condition_type') + if 'reason' in _dict: + args['reason'] = _dict.get('reason') + if 'action_variables' in _dict: + args['action_variables'] = _dict.get('action_variables') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultAnswer object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables return _dict def _to_dict(self): @@ -5158,191 +7807,230 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultAnswer object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionFinished object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultAnswer') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> 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: 'SearchResultAnswer') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + class ReasonEnum(str, Enum): + """ + The reason the action finished processing. + """ + ALL_STEPS_DONE = 'all_steps_done' + NO_STEPS_VISITED = 'no_steps_visited' + ENDED_BY_STEP = 'ended_by_step' + CONNECT_TO_AGENT = 'connect_to_agent' + MAX_RETRIES_REACHED = 'max_retries_reached' + FALLBACK = 'fallback' -class SearchResultHighlight(): - """ - An object containing segments of text from search results with query-matching text - highlighted using HTML `` tags. - :attr List[str] body: (optional) An array of strings containing segments taken - from body text in the search results, with query-matching substrings - highlighted. - :attr List[str] title: (optional) An array of strings containing segments taken - from title text in the search results, with query-matching substrings - highlighted. - :attr List[str] url: (optional) An array of strings containing segments taken - from URLs in the search results, with query-matching substrings highlighted. +class MessageOutputDebugTurnEventTurnEventActionVisited( + MessageOutputDebugTurnEvent): """ + MessageOutputDebugTurnEventTurnEventActionVisited. - # The set of defined properties for the class - _properties = frozenset(['body', 'title', 'url']) + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr str action_start_time: (optional) The time when the action started + processing the message. + :attr str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :attr str reason: (optional) The reason the action was visited. + """ def __init__(self, *, - body: List[str] = None, - title: List[str] = None, - url: List[str] = None, - **kwargs) -> None: - """ - Initialize a SearchResultHighlight object. - - :param List[str] body: (optional) An array of strings containing segments - taken from body text in the search results, with query-matching substrings - highlighted. - :param List[str] title: (optional) An array of strings containing segments - taken from title text in the search results, with query-matching substrings - highlighted. - :param List[str] url: (optional) An array of strings containing segments - taken from URLs in the search results, with query-matching substrings - highlighted. - :param **kwargs: (optional) Any additional properties. + event: str = None, + source: 'TurnEventActionSource' = None, + action_start_time: str = None, + condition_type: str = None, + reason: str = None) -> None: + """ + Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action was visited. """ - self.body = body - self.title = title - self.url = url - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': - """Initialize a SearchResultHighlight object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventActionVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" args = {} - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'action_start_time' in _dict: + args['action_start_time'] = _dict.get('action_start_time') + if 'condition_type' in _dict: + args['condition_type'] = _dict.get('condition_type') + if 'reason' in _dict: + args['reason'] = _dict.get('reason') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultHighlight object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited 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, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in SearchResultHighlight._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this SearchResultHighlight object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultHighlight') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> 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: 'SearchResultHighlight') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + class ReasonEnum(str, Enum): + """ + The reason the action was visited. + """ + INTENT = 'intent' + INVOKE_SUBACTION = 'invoke_subaction' + SUBACTION_RETURN = 'subaction_return' + INVOKE_EXTERNAL = 'invoke_external' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + AGENT_REQUESTED = 'agent_requested' + STEP_VALIDATION_FAILED = 'step_validation_failed' + NO_ACTION_MATCHES = 'no_action_matches' + -class SearchResultMetadata(): +class MessageOutputDebugTurnEventTurnEventCallout(MessageOutputDebugTurnEvent): """ - An object containing search result metadata from the Discovery service. + MessageOutputDebugTurnEventTurnEventCallout. - :attr float confidence: (optional) The confidence score for the given result, as - returned by the Discovery service. - :attr float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr TurnEventCalloutCallout callout: (optional) + :attr TurnEventCalloutError error: (optional) """ def __init__(self, *, - confidence: float = None, - score: float = None) -> None: + event: str = None, + source: 'TurnEventActionSource' = None, + callout: 'TurnEventCalloutCallout' = None, + error: 'TurnEventCalloutError' = None) -> None: """ - Initialize a SearchResultMetadata object. + Initialize a MessageOutputDebugTurnEventTurnEventCallout object. - :param float confidence: (optional) The confidence score for the given - result, as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher - score indicates a greater match to the query parameters. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ - self.confidence = confidence - self.score = score + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.callout = callout + self.error = error @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': - """Initialize a SearchResultMetadata object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventCallout': + """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" args = {} - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'score' in _dict: - args['score'] = _dict.get('score') + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'callout' in _dict: + args['callout'] = TurnEventCalloutCallout.from_dict( + _dict.get('callout')) + if 'error' in _dict: + args['error'] = TurnEventCalloutError.from_dict(_dict.get('error')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultMetadata object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventCallout 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, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'callout') and self.callout is not None: + _dict['callout'] = self.callout.to_dict() + if hasattr(self, 'error') and self.error is not None: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -5350,57 +8038,81 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultMetadata object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventCallout object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultMetadata') -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> 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: 'SearchResultMetadata') -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SessionResponse(): +class MessageOutputDebugTurnEventTurnEventHandlerVisited( + MessageOutputDebugTurnEvent): """ - SessionResponse. + MessageOutputDebugTurnEventTurnEventHandlerVisited. - :attr str session_id: The session ID. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr str action_start_time: (optional) The time when the action started + processing the message. """ - def __init__(self, session_id: str) -> None: + def __init__(self, + *, + event: str = None, + source: 'TurnEventActionSource' = None, + action_start_time: str = None) -> None: """ - Initialize a SessionResponse object. + Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object. - :param str session_id: The session ID. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. """ - self.session_id = session_id + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time @classmethod - def from_dict(cls, _dict: Dict) -> 'SessionResponse': - """Initialize a SessionResponse object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventHandlerVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" args = {} - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') - else: - raise ValueError( - 'Required property \'session_id\' not present in SessionResponse JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'action_start_time' in _dict: + args['action_start_time'] = _dict.get('action_start_time') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SessionResponse object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited 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, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time return _dict def _to_dict(self): @@ -5408,73 +8120,79 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SessionResponse object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventHandlerVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SessionResponse') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> 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: 'SessionResponse') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSourceAction(LogMessageSource): +class MessageOutputDebugTurnEventTurnEventNodeVisited( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventNodeVisited. - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str action: The unique identifier of the action that generated the error - message. + :attr str event: (optional) The type of turn event. + :attr TurnEventNodeSource source: (optional) + :attr str reason: (optional) The reason the dialog node was visited. """ - def __init__(self, type: str, action: str) -> None: + def __init__(self, + *, + event: str = None, + source: 'TurnEventNodeSource' = None, + reason: str = None) -> None: """ - Initialize a LogMessageSourceAction object. + Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action + self.event = event + self.source = source + self.reason = reason @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': - """Initialize a LogMessageSourceAction object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventNodeVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceAction JSON' - ) - if 'action' in _dict: - args['action'] = _dict.get('action') - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceAction JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventNodeSource.from_dict(_dict.get('source')) + if 'reason' in _dict: + args['reason'] = _dict.get('reason') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceAction object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited 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 - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason return _dict def _to_dict(self): @@ -5482,73 +8200,89 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceAction object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventNodeVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceAction') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> 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: 'LogMessageSourceAction') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ReasonEnum(str, Enum): + """ + The reason the dialog node was visited. + """ + WELCOME = 'welcome' + BRANCH_START = 'branch_start' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + TOPIC_SWITCH_WITHOUT_RETURN = 'topic_switch_without_return' + JUMP = 'jump' + -class LogMessageSourceDialogNode(LogMessageSource): +class MessageOutputDebugTurnEventTurnEventSearch(MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventSearch. - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str dialog_node: The unique identifier of the dialog node that generated - the error message. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr TurnEventSearchError error: (optional) """ - def __init__(self, type: str, dialog_node: str) -> None: + def __init__(self, + *, + event: str = None, + source: 'TurnEventActionSource' = None, + error: 'TurnEventSearchError' = None) -> None: """ - Initialize a LogMessageSourceDialogNode object. + Initialize a MessageOutputDebugTurnEventTurnEventSearch object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str dialog_node: The unique identifier of the dialog node that - generated the error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventSearchError error: (optional) """ # pylint: disable=super-init-not-called - self.type = type - self.dialog_node = dialog_node + self.event = event + self.source = source + self.error = error @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventSearch': + """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' - ) - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - else: - raise ValueError( - 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'error' in _dict: + args['error'] = TurnEventSearchError.from_dict(_dict.get('error')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventSearch 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 - if hasattr(self, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'error') and self.error is not None: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -5556,100 +8290,103 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceDialogNode object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventSearch object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceDialogNode') -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> 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: 'LogMessageSourceDialogNode') -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSourceHandler(LogMessageSource): +class MessageOutputDebugTurnEventTurnEventStepAnswered( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventStepAnswered. - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str action: The unique identifier of the action that generated the error - message. - :attr str step: (optional) The unique identifier of the step that generated the - error message. - :attr str handler: The unique identifier of the handler that generated the error - message. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :attr str action_start_time: (optional) The time when the action started + processing the message. + :attr bool prompted: (optional) Whether the step was answered in response to a + prompt from the assistant. If this property is `false`, the user provided the + answer without visiting the step. """ def __init__(self, - type: str, - action: str, - handler: str, *, - step: str = None) -> None: - """ - Initialize a LogMessageSourceHandler object. - - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str handler: The unique identifier of the handler that generated the - error message. - :param str step: (optional) The unique identifier of the step that - generated the error message. + event: str = None, + source: 'TurnEventActionSource' = None, + condition_type: str = None, + action_start_time: str = None, + prompted: bool = None) -> None: + """ + Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool prompted: (optional) Whether the step was answered in response + to a prompt from the assistant. If this property is `false`, the user + provided the answer without visiting the step. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step - self.handler = handler + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.prompted = prompted @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': - """Initialize a LogMessageSourceHandler object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepAnswered': + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceHandler JSON' - ) - if 'action' in _dict: - args['action'] = _dict.get('action') - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceHandler JSON' - ) - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'handler' in _dict: - args['handler'] = _dict.get('handler') - else: - raise ValueError( - 'Required property \'handler\' not present in LogMessageSourceHandler JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'condition_type' in _dict: + args['condition_type'] = _dict.get('condition_type') + if 'action_start_time' in _dict: + args['action_start_time'] = _dict.get('action_start_time') + if 'prompted' in _dict: + args['prompted'] = _dict.get('prompted') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceHandler object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered 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 - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step - if hasattr(self, 'handler') and self.handler is not None: - _dict['handler'] = self.handler + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'prompted') and self.prompted is not None: + _dict['prompted'] = self.prompted return _dict def _to_dict(self): @@ -5657,86 +8394,111 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceHandler object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepAnswered object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceHandler') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> 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: 'LogMessageSourceHandler') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' -class LogMessageSourceStep(LogMessageSource): - """ - An object that identifies the dialog element that generated the error message. - :attr str type: A string that indicates the type of dialog element that - generated the error message. - :attr str action: The unique identifier of the action that generated the error - message. - :attr str step: The unique identifier of the step that generated the error - message. +class MessageOutputDebugTurnEventTurnEventStepVisited( + MessageOutputDebugTurnEvent): """ + MessageOutputDebugTurnEventTurnEventStepVisited. - def __init__(self, type: str, action: str, step: str) -> None: - """ - Initialize a LogMessageSourceStep object. + :attr str event: (optional) The type of turn event. + :attr TurnEventActionSource source: (optional) + :attr str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :attr str action_start_time: (optional) The time when the action started + processing the message. + :attr bool has_question: (optional) Whether the step collects a customer + response. + """ - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str step: The unique identifier of the step that generated the error - message. + def __init__(self, + *, + event: str = None, + source: 'TurnEventActionSource' = None, + condition_type: str = None, + action_start_time: str = None, + has_question: bool = None) -> None: + """ + Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object. + + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool has_question: (optional) Whether the step collects a customer + response. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.has_question = has_question @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': - """Initialize a LogMessageSourceStep object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceStep JSON' - ) - if 'action' in _dict: - args['action'] = _dict.get('action') - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceStep JSON' - ) - if 'step' in _dict: - args['step'] = _dict.get('step') - else: - raise ValueError( - 'Required property \'step\' not present in LogMessageSourceStep JSON' - ) + if 'event' in _dict: + args['event'] = _dict.get('event') + if 'source' in _dict: + args['source'] = TurnEventActionSource.from_dict( + _dict.get('source')) + if 'condition_type' in _dict: + args['condition_type'] = _dict.get('condition_type') + if 'action_start_time' in _dict: + args['action_start_time'] = _dict.get('action_start_time') + if 'has_question' in _dict: + args['has_question'] = _dict.get('has_question') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceStep object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited 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 - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'has_question') and self.has_question is not None: + _dict['has_question'] = self.has_question return _dict def _to_dict(self): @@ -5744,19 +8506,31 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceStep object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceStep') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> 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: 'LogMessageSourceStep') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): """ @@ -6165,6 +8939,72 @@ def __ne__( return not self == other +class RuntimeResponseGenericRuntimeResponseTypeDate(RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeDate. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + """ + + def __init__(self, response_type: str) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeDate': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeDate JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeDate 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_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 RuntimeResponseGenericRuntimeResponseTypeDate object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeDate') -> 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: 'RuntimeResponseGenericRuntimeResponseTypeDate') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuntimeResponseGenericRuntimeResponseTypeIframe(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeIframe. diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 2542016ee..7c944b5c3 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2022. +# (C) Copyright IBM Corp. 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,7 +17,9 @@ Unit Tests for AssistantV2 """ +from datetime import datetime, timezone from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator +from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect import json import pytest @@ -100,6 +102,8 @@ def test_create_session_all_params(self): # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) def test_create_session_all_params_with_retries(self): # Enable retries and run test_create_session_all_params. @@ -110,6 +114,42 @@ def test_create_session_all_params_with_retries(self): _service.disable_retries() self.test_create_session_all_params() + @responses.activate + def test_create_session_required_params(self): + """ + test_create_session_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/sessions') + mock_response = '{"session_id": "session_id"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.create_session( + assistant_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + def test_create_session_required_params_with_retries(self): + # Enable retries and run test_create_session_required_params. + _service.enable_retries() + self.test_create_session_required_params() + + # Disable retries and run test_create_session_required_params. + _service.disable_retries() + self.test_create_session_required_params() + @responses.activate def test_create_session_value_error(self): """ @@ -136,7 +176,6 @@ def test_create_session_value_error(self): with pytest.raises(ValueError): _service.create_session(**req_copy) - def test_create_session_value_error_with_retries(self): # Enable retries and run test_create_session_value_error. _service.enable_retries() @@ -211,7 +250,6 @@ def test_delete_session_value_error(self): with pytest.raises(ValueError): _service.delete_session(**req_copy) - def test_delete_session_value_error_with_retries(self): # Enable retries and run test_delete_session_value_error. _service.enable_retries() @@ -243,7 +281,7 @@ def test_message_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -254,6 +292,7 @@ def test_message_all_params(self): runtime_intent_model = {} runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' # Construct a dict representation of a CaptureGroup model capture_group_model = {} @@ -308,6 +347,7 @@ def test_message_all_params(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' # Construct a dict representation of a MessageInputAttachment model message_input_attachment_model = {} @@ -360,14 +400,14 @@ def test_message_all_params(self): # Construct a dict representation of a MessageContextSkill model message_context_skill_model = {} - message_context_skill_model['user_defined'] = {} + message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} message_context_skill_model['system'] = message_context_skill_system_model # Construct a dict representation of a MessageContext model message_context_model = {} message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {} - message_context_model['integrations'] = { 'foo': 'bar' } + message_context_model['skills'] = {'key1': message_context_skill_model} + message_context_model['integrations'] = {'foo': 'bar'} # Set up parameter values assistant_id = 'testString' @@ -411,7 +451,7 @@ def test_message_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -449,7 +489,7 @@ def test_message_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -470,7 +510,6 @@ def test_message_value_error(self): with pytest.raises(ValueError): _service.message(**req_copy) - def test_message_value_error_with_retries(self): # Enable retries and run test_message_value_error. _service.enable_retries() @@ -492,7 +531,7 @@ def test_message_stateless_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -503,6 +542,7 @@ def test_message_stateless_all_params(self): runtime_intent_model = {} runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' # Construct a dict representation of a CaptureGroup model capture_group_model = {} @@ -557,6 +597,7 @@ def test_message_stateless_all_params(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' # Construct a dict representation of a MessageInputAttachment model message_input_attachment_model = {} @@ -608,14 +649,14 @@ def test_message_stateless_all_params(self): # Construct a dict representation of a MessageContextSkill model message_context_skill_model = {} - message_context_skill_model['user_defined'] = {} + message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} message_context_skill_model['system'] = message_context_skill_system_model # Construct a dict representation of a MessageContextStateless model message_context_stateless_model = {} message_context_stateless_model['global'] = message_context_global_stateless_model - message_context_stateless_model['skills'] = {} - message_context_stateless_model['integrations'] = { 'foo': 'bar' } + message_context_stateless_model['skills'] = {'key1': message_context_skill_model} + message_context_stateless_model['integrations'] = {'foo': 'bar'} # Set up parameter values assistant_id = 'testString' @@ -657,7 +698,7 @@ def test_message_stateless_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -693,7 +734,7 @@ def test_message_stateless_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -712,7 +753,6 @@ def test_message_stateless_value_error(self): with pytest.raises(ValueError): _service.message_stateless(**req_copy) - def test_message_stateless_value_error_with_retries(self): # Enable retries and run test_message_stateless_value_error. _service.enable_retries() @@ -744,7 +784,7 @@ def test_bulk_classify_all_params(self): """ # Set up mock url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -762,7 +802,7 @@ def test_bulk_classify_all_params(self): # Invoke method response = _service.bulk_classify( skill_id, - input=input, + input, headers={} ) @@ -782,42 +822,6 @@ def test_bulk_classify_all_params_with_retries(self): _service.disable_retries() self.test_bulk_classify_all_params() - @responses.activate - def test_bulk_classify_required_params(self): - """ - test_bulk_classify_required_params() - """ - # Set up mock - url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - skill_id = 'testString' - - # Invoke method - response = _service.bulk_classify( - skill_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_bulk_classify_required_params_with_retries(self): - # Enable retries and run test_bulk_classify_required_params. - _service.enable_retries() - self.test_bulk_classify_required_params() - - # Disable retries and run test_bulk_classify_required_params. - _service.disable_retries() - self.test_bulk_classify_required_params() - @responses.activate def test_bulk_classify_value_error(self): """ @@ -825,26 +829,31 @@ def test_bulk_classify_value_error(self): """ # Set up mock url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' + # Set up parameter values skill_id = 'testString' + input = [bulk_classify_utterance_model] # Pass in all but one required param and check for a ValueError req_param_dict = { "skill_id": skill_id, + "input": input, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): _service.bulk_classify(**req_copy) - def test_bulk_classify_value_error_with_retries(self): # Enable retries and run test_bulk_classify_value_error. _service.enable_retries() @@ -876,7 +885,7 @@ def test_list_logs_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -927,7 +936,7 @@ def test_list_logs_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -963,7 +972,7 @@ def test_list_logs_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed"}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -982,7 +991,6 @@ def test_list_logs_value_error(self): with pytest.raises(ValueError): _service.list_logs(**req_copy) - def test_list_logs_value_error_with_retries(self): # Enable retries and run test_list_logs_value_error. _service.enable_retries() @@ -1067,7 +1075,6 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) - def test_delete_user_data_value_error_with_retries(self): # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() @@ -1082,143 +1089,809 @@ def test_delete_user_data_value_error_with_retries(self): # End of Service: UserData ############################################################################## - ############################################################################## -# Start of Model Tests +# Start of Service: Environments ############################################################################## # region -class TestModel_AgentAvailabilityMessage(): + +class TestListEnvironments(): """ - Test Class for AgentAvailabilityMessage + Test Class for list_environments """ - def test_agent_availability_message_serialization(self): + @responses.activate + def test_list_environments_all_params(self): """ - Test serialization/deserialization for AgentAvailabilityMessage + list_environments() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct a json representation of a AgentAvailabilityMessage model - agent_availability_message_model_json = {} - agent_availability_message_model_json['message'] = 'testString' - - # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation - agent_availability_message_model = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json) - assert agent_availability_message_model != False + # Set up parameter values + assistant_id = 'testString' + page_limit = 38 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False - # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation - agent_availability_message_model_dict = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json).__dict__ - agent_availability_message_model2 = AgentAvailabilityMessage(**agent_availability_message_model_dict) + # Invoke method + response = _service.list_environments( + assistant_id, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) - # Verify the model instances are equivalent - assert agent_availability_message_model == agent_availability_message_model2 + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - # Convert model instance back to dict and verify no loss of data - agent_availability_message_model_json2 = agent_availability_message_model.to_dict() - assert agent_availability_message_model_json2 == agent_availability_message_model_json + def test_list_environments_all_params_with_retries(self): + # Enable retries and run test_list_environments_all_params. + _service.enable_retries() + self.test_list_environments_all_params() -class TestModel_BulkClassifyOutput(): - """ - Test Class for BulkClassifyOutput - """ + # Disable retries and run test_list_environments_all_params. + _service.disable_retries() + self.test_list_environments_all_params() - def test_bulk_classify_output_serialization(self): + @responses.activate + def test_list_environments_required_params(self): """ - Test serialization/deserialization for BulkClassifyOutput + test_list_environments_required_params() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct dict forms of any model objects needed in order to build this model. - - bulk_classify_utterance_model = {} # BulkClassifyUtterance - bulk_classify_utterance_model['text'] = 'testString' - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Set up parameter values + assistant_id = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Invoke method + response = _service.list_environments( + assistant_id, + headers={} + ) - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model + def test_list_environments_required_params_with_retries(self): + # Enable retries and run test_list_environments_required_params. + _service.enable_retries() + self.test_list_environments_required_params() - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 + # Disable retries and run test_list_environments_required_params. + _service.disable_retries() + self.test_list_environments_required_params() - # Construct a json representation of a BulkClassifyOutput model - bulk_classify_output_model_json = {} - bulk_classify_output_model_json['input'] = bulk_classify_utterance_model - bulk_classify_output_model_json['entities'] = [runtime_entity_model] - bulk_classify_output_model_json['intents'] = [runtime_intent_model] + @responses.activate + def test_list_environments_value_error(self): + """ + test_list_environments_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation - bulk_classify_output_model = BulkClassifyOutput.from_dict(bulk_classify_output_model_json) - assert bulk_classify_output_model != False + # Set up parameter values + assistant_id = 'testString' - # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation - bulk_classify_output_model_dict = BulkClassifyOutput.from_dict(bulk_classify_output_model_json).__dict__ - bulk_classify_output_model2 = BulkClassifyOutput(**bulk_classify_output_model_dict) + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_environments(**req_copy) - # Verify the model instances are equivalent - assert bulk_classify_output_model == bulk_classify_output_model2 + def test_list_environments_value_error_with_retries(self): + # Enable retries and run test_list_environments_value_error. + _service.enable_retries() + self.test_list_environments_value_error() - # Convert model instance back to dict and verify no loss of data - bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() - assert bulk_classify_output_model_json2 == bulk_classify_output_model_json + # Disable retries and run test_list_environments_value_error. + _service.disable_retries() + self.test_list_environments_value_error() -class TestModel_BulkClassifyResponse(): +class TestGetEnvironment(): """ - Test Class for BulkClassifyResponse + Test Class for get_environment """ - def test_bulk_classify_response_serialization(self): + @responses.activate + def test_get_environment_all_params(self): """ - Test serialization/deserialization for BulkClassifyResponse + get_environment() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) - # Construct dict forms of any model objects needed in order to build this model. + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + include_audit = False - bulk_classify_utterance_model = {} # BulkClassifyUtterance - bulk_classify_utterance_model['text'] = 'testString' + # Invoke method + response = _service.get_environment( + assistant_id, + environment_id, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_get_environment_all_params_with_retries(self): + # Enable retries and run test_get_environment_all_params. + _service.enable_retries() + self.test_get_environment_all_params() + + # Disable retries and run test_get_environment_all_params. + _service.disable_retries() + self.test_get_environment_all_params() + + @responses.activate + def test_get_environment_required_params(self): + """ + test_get_environment_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + + # Invoke method + response = _service.get_environment( + assistant_id, + environment_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_environment_required_params_with_retries(self): + # Enable retries and run test_get_environment_required_params. + _service.enable_retries() + self.test_get_environment_required_params() + + # Disable retries and run test_get_environment_required_params. + _service.disable_retries() + self.test_get_environment_required_params() + + @responses.activate + def test_get_environment_value_error(self): + """ + test_get_environment_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_environment(**req_copy) + + def test_get_environment_value_error_with_retries(self): + # Enable retries and run test_get_environment_value_error. + _service.enable_retries() + self.test_get_environment_value_error() + + # Disable retries and run test_get_environment_value_error. + _service.disable_retries() + self.test_get_environment_value_error() + +# endregion +############################################################################## +# End of Service: Environments +############################################################################## + +############################################################################## +# Start of Service: Releases +############################################################################## +# region + +class TestListReleases(): + """ + Test Class for list_releases + """ + + @responses.activate + def test_list_releases_all_params(self): + """ + list_releases() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + page_limit = 38 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False + + # Invoke method + response = _service.list_releases( + assistant_id, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_list_releases_all_params_with_retries(self): + # Enable retries and run test_list_releases_all_params. + _service.enable_retries() + self.test_list_releases_all_params() + + # Disable retries and run test_list_releases_all_params. + _service.disable_retries() + self.test_list_releases_all_params() + + @responses.activate + def test_list_releases_required_params(self): + """ + test_list_releases_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.list_releases( + assistant_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_releases_required_params_with_retries(self): + # Enable retries and run test_list_releases_required_params. + _service.enable_retries() + self.test_list_releases_required_params() + + # Disable retries and run test_list_releases_required_params. + _service.disable_retries() + self.test_list_releases_required_params() + + @responses.activate + def test_list_releases_value_error(self): + """ + test_list_releases_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_releases(**req_copy) + + def test_list_releases_value_error_with_retries(self): + # Enable retries and run test_list_releases_value_error. + _service.enable_retries() + self.test_list_releases_value_error() + + # Disable retries and run test_list_releases_value_error. + _service.disable_retries() + self.test_list_releases_value_error() + +class TestGetRelease(): + """ + Test Class for get_release + """ + + @responses.activate + def test_get_release_all_params(self): + """ + get_release() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + include_audit = False + + # Invoke method + response = _service.get_release( + assistant_id, + release, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_get_release_all_params_with_retries(self): + # Enable retries and run test_get_release_all_params. + _service.enable_retries() + self.test_get_release_all_params() + + # Disable retries and run test_get_release_all_params. + _service.disable_retries() + self.test_get_release_all_params() + + @responses.activate + def test_get_release_required_params(self): + """ + test_get_release_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + + # Invoke method + response = _service.get_release( + assistant_id, + release, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_release_required_params_with_retries(self): + # Enable retries and run test_get_release_required_params. + _service.enable_retries() + self.test_get_release_required_params() + + # Disable retries and run test_get_release_required_params. + _service.disable_retries() + self.test_get_release_required_params() + + @responses.activate + def test_get_release_value_error(self): + """ + test_get_release_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "release": release, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_release(**req_copy) + + def test_get_release_value_error_with_retries(self): + # Enable retries and run test_get_release_value_error. + _service.enable_retries() + self.test_get_release_value_error() + + # Disable retries and run test_get_release_value_error. + _service.disable_retries() + self.test_get_release_value_error() + +class TestDeployRelease(): + """ + Test Class for deploy_release + """ + + @responses.activate + def test_deploy_release_all_params(self): + """ + deploy_release() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' + include_audit = False + + # Invoke method + response = _service.deploy_release( + assistant_id, + release, + environment_id, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['environment_id'] == 'testString' + + def test_deploy_release_all_params_with_retries(self): + # Enable retries and run test_deploy_release_all_params. + _service.enable_retries() + self.test_deploy_release_all_params() + + # Disable retries and run test_deploy_release_all_params. + _service.disable_retries() + self.test_deploy_release_all_params() + + @responses.activate + def test_deploy_release_required_params(self): + """ + test_deploy_release_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' + + # Invoke method + response = _service.deploy_release( + assistant_id, + release, + environment_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['environment_id'] == 'testString' + + def test_deploy_release_required_params_with_retries(self): + # Enable retries and run test_deploy_release_required_params. + _service.enable_retries() + self.test_deploy_release_required_params() + + # Disable retries and run test_deploy_release_required_params. + _service.disable_retries() + self.test_deploy_release_required_params() + + @responses.activate + def test_deploy_release_value_error(self): + """ + test_deploy_release_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "release": release, + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.deploy_release(**req_copy) + + def test_deploy_release_value_error_with_retries(self): + # Enable retries and run test_deploy_release_value_error. + _service.enable_retries() + self.test_deploy_release_value_error() + + # Disable retries and run test_deploy_release_value_error. + _service.disable_retries() + self.test_deploy_release_value_error() + +# endregion +############################################################################## +# End of Service: Releases +############################################################################## + + +############################################################################## +# Start of Model Tests +############################################################################## +# region +class TestModel_AgentAvailabilityMessage(): + """ + Test Class for AgentAvailabilityMessage + """ + + def test_agent_availability_message_serialization(self): + """ + Test serialization/deserialization for AgentAvailabilityMessage + """ + + # Construct a json representation of a AgentAvailabilityMessage model + agent_availability_message_model_json = {} + agent_availability_message_model_json['message'] = 'testString' + + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json) + assert agent_availability_message_model != False + + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model_dict = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json).__dict__ + agent_availability_message_model2 = AgentAvailabilityMessage(**agent_availability_message_model_dict) + + # Verify the model instances are equivalent + assert agent_availability_message_model == agent_availability_message_model2 + + # Convert model instance back to dict and verify no loss of data + agent_availability_message_model_json2 = agent_availability_message_model.to_dict() + assert agent_availability_message_model_json2 == agent_availability_message_model_json + +class TestModel_BulkClassifyOutput(): + """ + Test Class for BulkClassifyOutput + """ + + def test_bulk_classify_output_serialization(self): + """ + Test serialization/deserialization for BulkClassifyOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + # Construct a json representation of a BulkClassifyOutput model + bulk_classify_output_model_json = {} + bulk_classify_output_model_json['input'] = bulk_classify_utterance_model + bulk_classify_output_model_json['entities'] = [runtime_entity_model] + bulk_classify_output_model_json['intents'] = [runtime_intent_model] + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model = BulkClassifyOutput.from_dict(bulk_classify_output_model_json) + assert bulk_classify_output_model != False + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model_dict = BulkClassifyOutput.from_dict(bulk_classify_output_model_json).__dict__ + bulk_classify_output_model2 = BulkClassifyOutput(**bulk_classify_output_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_output_model == bulk_classify_output_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() + assert bulk_classify_output_model_json2 == bulk_classify_output_model_json + +class TestModel_BulkClassifyResponse(): + """ + Test Class for BulkClassifyResponse + """ + + def test_bulk_classify_response_serialization(self): + """ + Test serialization/deserialization for BulkClassifyResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -1268,10 +1941,12 @@ def test_bulk_classify_response_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' bulk_classify_output_model = {} # BulkClassifyOutput bulk_classify_output_model['input'] = bulk_classify_utterance_model @@ -1508,7 +2183,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json = {} dialog_node_action_model_json['name'] = 'testString' dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {} + dialog_node_action_model_json['parameters'] = {'key1': 'testString'} dialog_node_action_model_json['result_variable'] = 'testString' dialog_node_action_model_json['credentials'] = 'testString' @@ -1539,7 +2214,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'key1': 'testString'}} # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) @@ -1571,6 +2246,7 @@ def test_dialog_node_output_options_element_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -1620,6 +2296,7 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -1684,6 +2361,7 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -1733,6 +2411,7 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -1824,6 +2503,7 @@ def test_dialog_suggestion_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -1873,6 +2553,7 @@ def test_dialog_suggestion_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -1906,7 +2587,7 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json = {} dialog_suggestion_model_json['label'] = 'testString' dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {} + dialog_suggestion_model_json['output'] = {'key1': 'testString'} # Construct a model instance of DialogSuggestion by calling from_dict on the json representation dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) @@ -1938,6 +2619,7 @@ def test_dialog_suggestion_value_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -1987,6 +2669,7 @@ def test_dialog_suggestion_value_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -2032,6 +2715,257 @@ def test_dialog_suggestion_value_serialization(self): dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json +class TestModel_Environment(): + """ + Test Class for Environment + """ + + def test_environment_serialization(self): + """ + Test serialization/deserialization for Environment + """ + + # Construct dict forms of any model objects needed in order to build this model. + + environment_release_reference_model = {} # EnvironmentReleaseReference + environment_release_reference_model['release'] = 'testString' + + environment_orchestration_model = {} # EnvironmentOrchestration + environment_orchestration_model['search_skill_fallback'] = True + + integration_reference_model = {} # IntegrationReference + integration_reference_model['integration_id'] = 'testString' + integration_reference_model['type'] = 'testString' + + skill_reference_model = {} # SkillReference + skill_reference_model['skill_id'] = 'testString' + skill_reference_model['type'] = 'dialog' + skill_reference_model['disabled'] = True + skill_reference_model['snapshot'] = 'testString' + skill_reference_model['skill_reference'] = 'testString' + + # Construct a json representation of a Environment model + environment_model_json = {} + environment_model_json['name'] = 'testString' + environment_model_json['description'] = 'testString' + environment_model_json['language'] = 'testString' + environment_model_json['assistant_id'] = 'testString' + environment_model_json['environment_id'] = 'testString' + environment_model_json['environment'] = 'testString' + environment_model_json['release_reference'] = environment_release_reference_model + environment_model_json['orchestration'] = environment_orchestration_model + environment_model_json['session_timeout'] = 38 + environment_model_json['integration_references'] = [integration_reference_model] + environment_model_json['skill_references'] = [skill_reference_model] + environment_model_json['created'] = '2019-01-01T12:00:00Z' + environment_model_json['updated'] = '2019-01-01T12:00:00Z' + + # Construct a model instance of Environment by calling from_dict on the json representation + environment_model = Environment.from_dict(environment_model_json) + assert environment_model != False + + # Construct a model instance of Environment by calling from_dict on the json representation + environment_model_dict = Environment.from_dict(environment_model_json).__dict__ + environment_model2 = Environment(**environment_model_dict) + + # Verify the model instances are equivalent + assert environment_model == environment_model2 + + # Convert model instance back to dict and verify no loss of data + environment_model_json2 = environment_model.to_dict() + assert environment_model_json2 == environment_model_json + +class TestModel_EnvironmentCollection(): + """ + Test Class for EnvironmentCollection + """ + + def test_environment_collection_serialization(self): + """ + Test serialization/deserialization for EnvironmentCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + environment_release_reference_model = {} # EnvironmentReleaseReference + environment_release_reference_model['release'] = 'testString' + + environment_orchestration_model = {} # EnvironmentOrchestration + environment_orchestration_model['search_skill_fallback'] = True + + integration_reference_model = {} # IntegrationReference + integration_reference_model['integration_id'] = 'testString' + integration_reference_model['type'] = 'testString' + + skill_reference_model = {} # SkillReference + skill_reference_model['skill_id'] = 'testString' + skill_reference_model['type'] = 'dialog' + skill_reference_model['disabled'] = True + skill_reference_model['snapshot'] = 'testString' + skill_reference_model['skill_reference'] = 'testString' + + environment_model = {} # Environment + environment_model['name'] = 'testString' + environment_model['description'] = 'testString' + environment_model['language'] = 'testString' + environment_model['assistant_id'] = 'testString' + environment_model['environment_id'] = 'testString' + environment_model['environment'] = 'testString' + environment_model['release_reference'] = environment_release_reference_model + environment_model['orchestration'] = environment_orchestration_model + environment_model['session_timeout'] = 38 + environment_model['integration_references'] = [integration_reference_model] + environment_model['skill_references'] = [skill_reference_model] + environment_model['created'] = '2019-01-01T12:00:00Z' + environment_model['updated'] = '2019-01-01T12:00:00Z' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a EnvironmentCollection model + environment_collection_model_json = {} + environment_collection_model_json['environments'] = [environment_model] + environment_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation + environment_collection_model = EnvironmentCollection.from_dict(environment_collection_model_json) + assert environment_collection_model != False + + # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation + environment_collection_model_dict = EnvironmentCollection.from_dict(environment_collection_model_json).__dict__ + environment_collection_model2 = EnvironmentCollection(**environment_collection_model_dict) + + # Verify the model instances are equivalent + assert environment_collection_model == environment_collection_model2 + + # Convert model instance back to dict and verify no loss of data + environment_collection_model_json2 = environment_collection_model.to_dict() + assert environment_collection_model_json2 == environment_collection_model_json + +class TestModel_EnvironmentOrchestration(): + """ + Test Class for EnvironmentOrchestration + """ + + def test_environment_orchestration_serialization(self): + """ + Test serialization/deserialization for EnvironmentOrchestration + """ + + # Construct a json representation of a EnvironmentOrchestration model + environment_orchestration_model_json = {} + environment_orchestration_model_json['search_skill_fallback'] = True + + # Construct a model instance of EnvironmentOrchestration by calling from_dict on the json representation + environment_orchestration_model = EnvironmentOrchestration.from_dict(environment_orchestration_model_json) + assert environment_orchestration_model != False + + # Construct a model instance of EnvironmentOrchestration by calling from_dict on the json representation + environment_orchestration_model_dict = EnvironmentOrchestration.from_dict(environment_orchestration_model_json).__dict__ + environment_orchestration_model2 = EnvironmentOrchestration(**environment_orchestration_model_dict) + + # Verify the model instances are equivalent + assert environment_orchestration_model == environment_orchestration_model2 + + # Convert model instance back to dict and verify no loss of data + environment_orchestration_model_json2 = environment_orchestration_model.to_dict() + assert environment_orchestration_model_json2 == environment_orchestration_model_json + +class TestModel_EnvironmentReference(): + """ + Test Class for EnvironmentReference + """ + + def test_environment_reference_serialization(self): + """ + Test serialization/deserialization for EnvironmentReference + """ + + # Construct a json representation of a EnvironmentReference model + environment_reference_model_json = {} + environment_reference_model_json['name'] = 'testString' + environment_reference_model_json['environment_id'] = 'testString' + environment_reference_model_json['environment'] = 'draft' + + # Construct a model instance of EnvironmentReference by calling from_dict on the json representation + environment_reference_model = EnvironmentReference.from_dict(environment_reference_model_json) + assert environment_reference_model != False + + # Construct a model instance of EnvironmentReference by calling from_dict on the json representation + environment_reference_model_dict = EnvironmentReference.from_dict(environment_reference_model_json).__dict__ + environment_reference_model2 = EnvironmentReference(**environment_reference_model_dict) + + # Verify the model instances are equivalent + assert environment_reference_model == environment_reference_model2 + + # Convert model instance back to dict and verify no loss of data + environment_reference_model_json2 = environment_reference_model.to_dict() + assert environment_reference_model_json2 == environment_reference_model_json + +class TestModel_EnvironmentReleaseReference(): + """ + Test Class for EnvironmentReleaseReference + """ + + def test_environment_release_reference_serialization(self): + """ + Test serialization/deserialization for EnvironmentReleaseReference + """ + + # Construct a json representation of a EnvironmentReleaseReference model + environment_release_reference_model_json = {} + environment_release_reference_model_json['release'] = 'testString' + + # Construct a model instance of EnvironmentReleaseReference by calling from_dict on the json representation + environment_release_reference_model = EnvironmentReleaseReference.from_dict(environment_release_reference_model_json) + assert environment_release_reference_model != False + + # Construct a model instance of EnvironmentReleaseReference by calling from_dict on the json representation + environment_release_reference_model_dict = EnvironmentReleaseReference.from_dict(environment_release_reference_model_json).__dict__ + environment_release_reference_model2 = EnvironmentReleaseReference(**environment_release_reference_model_dict) + + # Verify the model instances are equivalent + assert environment_release_reference_model == environment_release_reference_model2 + + # Convert model instance back to dict and verify no loss of data + environment_release_reference_model_json2 = environment_release_reference_model.to_dict() + assert environment_release_reference_model_json2 == environment_release_reference_model_json + +class TestModel_IntegrationReference(): + """ + Test Class for IntegrationReference + """ + + def test_integration_reference_serialization(self): + """ + Test serialization/deserialization for IntegrationReference + """ + + # Construct a json representation of a IntegrationReference model + integration_reference_model_json = {} + integration_reference_model_json['integration_id'] = 'testString' + integration_reference_model_json['type'] = 'testString' + + # Construct a model instance of IntegrationReference by calling from_dict on the json representation + integration_reference_model = IntegrationReference.from_dict(integration_reference_model_json) + assert integration_reference_model != False + + # Construct a model instance of IntegrationReference by calling from_dict on the json representation + integration_reference_model_dict = IntegrationReference.from_dict(integration_reference_model_json).__dict__ + integration_reference_model2 = IntegrationReference(**integration_reference_model_dict) + + # Verify the model instances are equivalent + assert integration_reference_model == integration_reference_model2 + + # Convert model instance back to dict and verify no loss of data + integration_reference_model_json2 = integration_reference_model.to_dict() + assert integration_reference_model_json2 == integration_reference_model_json + class TestModel_Log(): """ Test Class for Log @@ -2047,6 +2981,7 @@ def test_log_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -2096,6 +3031,7 @@ def test_log_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -2141,13 +3077,13 @@ def test_log_serialization(self): message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} + message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} message_context_skill_model['system'] = message_context_skill_system_model message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {} - message_context_model['integrations'] = { 'foo': 'bar' } + message_context_model['skills'] = {'key1': message_context_skill_model} + message_context_model['integrations'] = {'foo': 'bar'} message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model @@ -2175,7 +3111,7 @@ def test_log_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -2194,11 +3130,25 @@ def test_log_serialization(self): dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' @@ -2211,7 +3161,7 @@ def test_log_serialization(self): message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {} + message_output_model['user_defined'] = {'key1': 'testString'} message_output_model['spelling'] = message_output_spelling_model message_response_model = {} # MessageResponse @@ -2263,6 +3213,7 @@ def test_log_collection_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -2312,6 +3263,7 @@ def test_log_collection_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -2357,13 +3309,13 @@ def test_log_collection_serialization(self): message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} + message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} message_context_skill_model['system'] = message_context_skill_system_model message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {} - message_context_model['integrations'] = { 'foo': 'bar' } + message_context_model['skills'] = {'key1': message_context_skill_model} + message_context_model['integrations'] = {'foo': 'bar'} message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model @@ -2391,7 +3343,7 @@ def test_log_collection_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -2410,11 +3362,25 @@ def test_log_collection_serialization(self): dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' @@ -2427,7 +3393,7 @@ def test_log_collection_serialization(self): message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {} + message_output_model['user_defined'] = {'key1': 'testString'} message_output_model['spelling'] = message_output_spelling_model message_response_model = {} # MessageResponse @@ -2535,14 +3501,14 @@ def test_message_context_serialization(self): message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} + message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} message_context_skill_model['system'] = message_context_skill_system_model # Construct a json representation of a MessageContext model message_context_model_json = {} message_context_model_json['global'] = message_context_global_model - message_context_model_json['skills'] = {} - message_context_model_json['integrations'] = { 'foo': 'bar' } + message_context_model_json['skills'] = {'key1': message_context_skill_model} + message_context_model_json['integrations'] = {'foo': 'bar'} # Construct a model instance of MessageContext by calling from_dict on the json representation message_context_model = MessageContext.from_dict(message_context_model_json) @@ -2697,7 +3663,7 @@ def test_message_context_skill_serialization(self): # Construct a json representation of a MessageContextSkill model message_context_skill_model_json = {} - message_context_skill_model_json['user_defined'] = {} + message_context_skill_model_json['user_defined'] = {'key1': {'foo': 'bar'}} message_context_skill_model_json['system'] = message_context_skill_system_model # Construct a model instance of MessageContextSkill by calling from_dict on the json representation @@ -2786,14 +3752,14 @@ def test_message_context_stateless_serialization(self): message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} + message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} message_context_skill_model['system'] = message_context_skill_system_model # Construct a json representation of a MessageContextStateless model message_context_stateless_model_json = {} message_context_stateless_model_json['global'] = message_context_global_stateless_model - message_context_stateless_model_json['skills'] = {} - message_context_stateless_model_json['integrations'] = { 'foo': 'bar' } + message_context_stateless_model_json['skills'] = {'key1': message_context_skill_model} + message_context_stateless_model_json['integrations'] = {'foo': 'bar'} # Construct a model instance of MessageContextStateless by calling from_dict on the json representation message_context_stateless_model = MessageContextStateless.from_dict(message_context_stateless_model_json) @@ -2825,6 +3791,7 @@ def test_message_input_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -2874,6 +3841,7 @@ def test_message_input_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -3069,6 +4037,7 @@ def test_message_input_stateless_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3118,6 +4087,7 @@ def test_message_input_stateless_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -3173,6 +4143,7 @@ def test_message_output_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3222,6 +4193,7 @@ def test_message_output_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -3269,7 +4241,7 @@ def test_message_output_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -3288,11 +4260,25 @@ def test_message_output_serialization(self): dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' @@ -3306,7 +4292,7 @@ def test_message_output_serialization(self): message_output_model_json['entities'] = [runtime_entity_model] message_output_model_json['actions'] = [dialog_node_action_model] message_output_model_json['debug'] = message_output_debug_model - message_output_model_json['user_defined'] = {} + message_output_model_json['user_defined'] = {'key1': 'testString'} message_output_model_json['spelling'] = message_output_spelling_model # Construct a model instance of MessageOutput by calling from_dict on the json representation @@ -3351,12 +4337,26 @@ def test_message_output_debug_serialization(self): dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + # Construct a json representation of a MessageOutputDebug model message_output_debug_model_json = {} message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model_json['log_messages'] = [dialog_log_message_model] message_output_debug_model_json['branch_exited'] = True message_output_debug_model_json['branch_exited_reason'] = 'completed' + message_output_debug_model_json['turn_events'] = [message_output_debug_turn_event_model] # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) @@ -3419,6 +4419,7 @@ def test_message_request_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3468,6 +4469,7 @@ def test_message_request_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -3513,13 +4515,13 @@ def test_message_request_serialization(self): message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} + message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} message_context_skill_model['system'] = message_context_skill_system_model message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {} - message_context_model['integrations'] = { 'foo': 'bar' } + message_context_model['skills'] = {'key1': message_context_skill_model} + message_context_model['integrations'] = {'foo': 'bar'} # Construct a json representation of a MessageRequest model message_request_model_json = {} @@ -3557,6 +4559,7 @@ def test_message_response_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3606,6 +4609,7 @@ def test_message_response_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -3653,7 +4657,7 @@ def test_message_response_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -3672,11 +4676,25 @@ def test_message_response_serialization(self): dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' @@ -3689,7 +4707,7 @@ def test_message_response_serialization(self): message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {} + message_output_model['user_defined'] = {'key1': 'testString'} message_output_model['spelling'] = message_output_spelling_model message_context_global_system_model = {} # MessageContextGlobalSystem @@ -3711,13 +4729,13 @@ def test_message_response_serialization(self): message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} + message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} message_context_skill_model['system'] = message_context_skill_system_model message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {} - message_context_model['integrations'] = { 'foo': 'bar' } + message_context_model['skills'] = {'key1': message_context_skill_model} + message_context_model['integrations'] = {'foo': 'bar'} # Construct a json representation of a MessageResponse model message_response_model_json = {} @@ -3755,6 +4773,7 @@ def test_message_response_stateless_serialization(self): runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3804,6 +4823,7 @@ def test_message_response_stateless_serialization(self): runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -3851,7 +4871,7 @@ def test_message_response_stateless_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {} + dialog_node_action_model['parameters'] = {'key1': 'testString'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -3870,11 +4890,25 @@ def test_message_response_stateless_serialization(self): dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' @@ -3887,7 +4921,7 @@ def test_message_response_stateless_serialization(self): message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {} + message_output_model['user_defined'] = {'key1': 'testString'} message_output_model['spelling'] = message_output_spelling_model message_context_global_system_model = {} # MessageContextGlobalSystem @@ -3900,43 +4934,256 @@ def test_message_response_stateless_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_stateless_model = {} # MessageContextGlobalStateless - message_context_global_stateless_model['system'] = message_context_global_system_model - message_context_global_stateless_model['session_id'] = 'testString' + message_context_global_stateless_model = {} # MessageContextGlobalStateless + message_context_global_stateless_model['system'] = message_context_global_system_model + message_context_global_stateless_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_skill_model = {} # MessageContextSkill + message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} + message_context_skill_model['system'] = message_context_skill_system_model + + message_context_stateless_model = {} # MessageContextStateless + message_context_stateless_model['global'] = message_context_global_stateless_model + message_context_stateless_model['skills'] = {'key1': message_context_skill_model} + message_context_stateless_model['integrations'] = {'foo': 'bar'} + + # Construct a json representation of a MessageResponseStateless model + message_response_stateless_model_json = {} + message_response_stateless_model_json['output'] = message_output_model + message_response_stateless_model_json['context'] = message_context_stateless_model + message_response_stateless_model_json['user_id'] = 'testString' + + # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation + message_response_stateless_model = MessageResponseStateless.from_dict(message_response_stateless_model_json) + assert message_response_stateless_model != False + + # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation + message_response_stateless_model_dict = MessageResponseStateless.from_dict(message_response_stateless_model_json).__dict__ + message_response_stateless_model2 = MessageResponseStateless(**message_response_stateless_model_dict) + + # Verify the model instances are equivalent + assert message_response_stateless_model == message_response_stateless_model2 + + # Convert model instance back to dict and verify no loss of data + message_response_stateless_model_json2 = message_response_stateless_model.to_dict() + assert message_response_stateless_model_json2 == message_response_stateless_model_json + +class TestModel_Pagination(): + """ + Test Class for Pagination + """ + + def test_pagination_serialization(self): + """ + Test serialization/deserialization for Pagination + """ + + # Construct a json representation of a Pagination model + pagination_model_json = {} + pagination_model_json['refresh_url'] = 'testString' + pagination_model_json['next_url'] = 'testString' + pagination_model_json['total'] = 38 + pagination_model_json['matched'] = 38 + pagination_model_json['refresh_cursor'] = 'testString' + pagination_model_json['next_cursor'] = 'testString' + + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model = Pagination.from_dict(pagination_model_json) + assert pagination_model != False + + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ + pagination_model2 = Pagination(**pagination_model_dict) + + # Verify the model instances are equivalent + assert pagination_model == pagination_model2 + + # Convert model instance back to dict and verify no loss of data + pagination_model_json2 = pagination_model.to_dict() + assert pagination_model_json2 == pagination_model_json + +class TestModel_Release(): + """ + Test Class for Release + """ + + def test_release_serialization(self): + """ + Test serialization/deserialization for Release + """ + + # Construct dict forms of any model objects needed in order to build this model. + + environment_reference_model = {} # EnvironmentReference + environment_reference_model['name'] = 'testString' + environment_reference_model['environment_id'] = 'testString' + environment_reference_model['environment'] = 'draft' + + release_skill_reference_model = {} # ReleaseSkillReference + release_skill_reference_model['skill_id'] = 'testString' + release_skill_reference_model['type'] = 'dialog' + release_skill_reference_model['snapshot'] = 'testString' + + release_content_model = {} # ReleaseContent + release_content_model['skills'] = [release_skill_reference_model] + + # Construct a json representation of a Release model + release_model_json = {} + release_model_json['release'] = 'testString' + release_model_json['description'] = 'testString' + release_model_json['environment_references'] = [environment_reference_model] + release_model_json['content'] = release_content_model + release_model_json['status'] = 'Available' + release_model_json['created'] = '2019-01-01T12:00:00Z' + release_model_json['updated'] = '2019-01-01T12:00:00Z' + + # Construct a model instance of Release by calling from_dict on the json representation + release_model = Release.from_dict(release_model_json) + assert release_model != False + + # Construct a model instance of Release by calling from_dict on the json representation + release_model_dict = Release.from_dict(release_model_json).__dict__ + release_model2 = Release(**release_model_dict) + + # Verify the model instances are equivalent + assert release_model == release_model2 + + # Convert model instance back to dict and verify no loss of data + release_model_json2 = release_model.to_dict() + assert release_model_json2 == release_model_json + +class TestModel_ReleaseCollection(): + """ + Test Class for ReleaseCollection + """ + + def test_release_collection_serialization(self): + """ + Test serialization/deserialization for ReleaseCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + environment_reference_model = {} # EnvironmentReference + environment_reference_model['name'] = 'testString' + environment_reference_model['environment_id'] = 'testString' + environment_reference_model['environment'] = 'draft' + + release_skill_reference_model = {} # ReleaseSkillReference + release_skill_reference_model['skill_id'] = 'testString' + release_skill_reference_model['type'] = 'dialog' + release_skill_reference_model['snapshot'] = 'testString' + + release_content_model = {} # ReleaseContent + release_content_model['skills'] = [release_skill_reference_model] + + release_model = {} # Release + release_model['release'] = 'testString' + release_model['description'] = 'testString' + release_model['environment_references'] = [environment_reference_model] + release_model['content'] = release_content_model + release_model['status'] = 'Available' + release_model['created'] = '2019-01-01T12:00:00Z' + release_model['updated'] = '2019-01-01T12:00:00Z' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a ReleaseCollection model + release_collection_model_json = {} + release_collection_model_json['releases'] = [release_model] + release_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of ReleaseCollection by calling from_dict on the json representation + release_collection_model = ReleaseCollection.from_dict(release_collection_model_json) + assert release_collection_model != False + + # Construct a model instance of ReleaseCollection by calling from_dict on the json representation + release_collection_model_dict = ReleaseCollection.from_dict(release_collection_model_json).__dict__ + release_collection_model2 = ReleaseCollection(**release_collection_model_dict) + + # Verify the model instances are equivalent + assert release_collection_model == release_collection_model2 + + # Convert model instance back to dict and verify no loss of data + release_collection_model_json2 = release_collection_model.to_dict() + assert release_collection_model_json2 == release_collection_model_json + +class TestModel_ReleaseContent(): + """ + Test Class for ReleaseContent + """ + + def test_release_content_serialization(self): + """ + Test serialization/deserialization for ReleaseContent + """ + + # Construct dict forms of any model objects needed in order to build this model. - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + release_skill_reference_model = {} # ReleaseSkillReference + release_skill_reference_model['skill_id'] = 'testString' + release_skill_reference_model['type'] = 'dialog' + release_skill_reference_model['snapshot'] = 'testString' - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {} - message_context_skill_model['system'] = message_context_skill_system_model + # Construct a json representation of a ReleaseContent model + release_content_model_json = {} + release_content_model_json['skills'] = [release_skill_reference_model] - message_context_stateless_model = {} # MessageContextStateless - message_context_stateless_model['global'] = message_context_global_stateless_model - message_context_stateless_model['skills'] = {} - message_context_stateless_model['integrations'] = { 'foo': 'bar' } + # Construct a model instance of ReleaseContent by calling from_dict on the json representation + release_content_model = ReleaseContent.from_dict(release_content_model_json) + assert release_content_model != False - # Construct a json representation of a MessageResponseStateless model - message_response_stateless_model_json = {} - message_response_stateless_model_json['output'] = message_output_model - message_response_stateless_model_json['context'] = message_context_stateless_model - message_response_stateless_model_json['user_id'] = 'testString' + # Construct a model instance of ReleaseContent by calling from_dict on the json representation + release_content_model_dict = ReleaseContent.from_dict(release_content_model_json).__dict__ + release_content_model2 = ReleaseContent(**release_content_model_dict) - # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation - message_response_stateless_model = MessageResponseStateless.from_dict(message_response_stateless_model_json) - assert message_response_stateless_model != False + # Verify the model instances are equivalent + assert release_content_model == release_content_model2 - # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation - message_response_stateless_model_dict = MessageResponseStateless.from_dict(message_response_stateless_model_json).__dict__ - message_response_stateless_model2 = MessageResponseStateless(**message_response_stateless_model_dict) + # Convert model instance back to dict and verify no loss of data + release_content_model_json2 = release_content_model.to_dict() + assert release_content_model_json2 == release_content_model_json + +class TestModel_ReleaseSkillReference(): + """ + Test Class for ReleaseSkillReference + """ + + def test_release_skill_reference_serialization(self): + """ + Test serialization/deserialization for ReleaseSkillReference + """ + + # Construct a json representation of a ReleaseSkillReference model + release_skill_reference_model_json = {} + release_skill_reference_model_json['skill_id'] = 'testString' + release_skill_reference_model_json['type'] = 'dialog' + release_skill_reference_model_json['snapshot'] = 'testString' + + # Construct a model instance of ReleaseSkillReference by calling from_dict on the json representation + release_skill_reference_model = ReleaseSkillReference.from_dict(release_skill_reference_model_json) + assert release_skill_reference_model != False + + # Construct a model instance of ReleaseSkillReference by calling from_dict on the json representation + release_skill_reference_model_dict = ReleaseSkillReference.from_dict(release_skill_reference_model_json).__dict__ + release_skill_reference_model2 = ReleaseSkillReference(**release_skill_reference_model_dict) # Verify the model instances are equivalent - assert message_response_stateless_model == message_response_stateless_model2 + assert release_skill_reference_model == release_skill_reference_model2 # Convert model instance back to dict and verify no loss of data - message_response_stateless_model_json2 = message_response_stateless_model.to_dict() - assert message_response_stateless_model_json2 == message_response_stateless_model_json + release_skill_reference_model_json2 = release_skill_reference_model.to_dict() + assert release_skill_reference_model_json2 == release_skill_reference_model_json class TestModel_ResponseGenericChannel(): """ @@ -4028,6 +5275,7 @@ def test_runtime_entity_serialization(self): runtime_entity_model_json['interpretation'] = runtime_entity_interpretation_model runtime_entity_model_json['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model_json['role'] = runtime_entity_role_model + runtime_entity_model_json['skill'] = 'testString' # Construct a model instance of RuntimeEntity by calling from_dict on the json representation runtime_entity_model = RuntimeEntity.from_dict(runtime_entity_model_json) @@ -4171,6 +5419,7 @@ def test_runtime_intent_serialization(self): runtime_intent_model_json = {} runtime_intent_model_json['intent'] = 'testString' runtime_intent_model_json['confidence'] = 72.5 + runtime_intent_model_json['skill'] = 'testString' # Construct a model instance of RuntimeIntent by calling from_dict on the json representation runtime_intent_model = RuntimeIntent.from_dict(runtime_intent_model_json) @@ -4369,6 +5618,191 @@ def test_session_response_serialization(self): session_response_model_json2 = session_response_model.to_dict() assert session_response_model_json2 == session_response_model_json +class TestModel_SkillReference(): + """ + Test Class for SkillReference + """ + + def test_skill_reference_serialization(self): + """ + Test serialization/deserialization for SkillReference + """ + + # Construct a json representation of a SkillReference model + skill_reference_model_json = {} + skill_reference_model_json['skill_id'] = 'testString' + skill_reference_model_json['type'] = 'dialog' + skill_reference_model_json['disabled'] = True + skill_reference_model_json['snapshot'] = 'testString' + skill_reference_model_json['skill_reference'] = 'testString' + + # Construct a model instance of SkillReference by calling from_dict on the json representation + skill_reference_model = SkillReference.from_dict(skill_reference_model_json) + assert skill_reference_model != False + + # Construct a model instance of SkillReference by calling from_dict on the json representation + skill_reference_model_dict = SkillReference.from_dict(skill_reference_model_json).__dict__ + skill_reference_model2 = SkillReference(**skill_reference_model_dict) + + # Verify the model instances are equivalent + assert skill_reference_model == skill_reference_model2 + + # Convert model instance back to dict and verify no loss of data + skill_reference_model_json2 = skill_reference_model.to_dict() + assert skill_reference_model_json2 == skill_reference_model_json + +class TestModel_TurnEventActionSource(): + """ + Test Class for TurnEventActionSource + """ + + def test_turn_event_action_source_serialization(self): + """ + Test serialization/deserialization for TurnEventActionSource + """ + + # Construct a json representation of a TurnEventActionSource model + turn_event_action_source_model_json = {} + turn_event_action_source_model_json['type'] = 'action' + turn_event_action_source_model_json['action'] = 'testString' + turn_event_action_source_model_json['action_title'] = 'testString' + turn_event_action_source_model_json['condition'] = 'testString' + + # Construct a model instance of TurnEventActionSource by calling from_dict on the json representation + turn_event_action_source_model = TurnEventActionSource.from_dict(turn_event_action_source_model_json) + assert turn_event_action_source_model != False + + # Construct a model instance of TurnEventActionSource by calling from_dict on the json representation + turn_event_action_source_model_dict = TurnEventActionSource.from_dict(turn_event_action_source_model_json).__dict__ + turn_event_action_source_model2 = TurnEventActionSource(**turn_event_action_source_model_dict) + + # Verify the model instances are equivalent + assert turn_event_action_source_model == turn_event_action_source_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_action_source_model_json2 = turn_event_action_source_model.to_dict() + assert turn_event_action_source_model_json2 == turn_event_action_source_model_json + +class TestModel_TurnEventCalloutCallout(): + """ + Test Class for TurnEventCalloutCallout + """ + + def test_turn_event_callout_callout_serialization(self): + """ + Test serialization/deserialization for TurnEventCalloutCallout + """ + + # Construct a json representation of a TurnEventCalloutCallout model + turn_event_callout_callout_model_json = {} + turn_event_callout_callout_model_json['type'] = 'integration_interaction' + turn_event_callout_callout_model_json['internal'] = {'key1': 'testString'} + + # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation + turn_event_callout_callout_model = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json) + assert turn_event_callout_callout_model != False + + # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation + turn_event_callout_callout_model_dict = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json).__dict__ + turn_event_callout_callout_model2 = TurnEventCalloutCallout(**turn_event_callout_callout_model_dict) + + # Verify the model instances are equivalent + assert turn_event_callout_callout_model == turn_event_callout_callout_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_callout_callout_model_json2 = turn_event_callout_callout_model.to_dict() + assert turn_event_callout_callout_model_json2 == turn_event_callout_callout_model_json + +class TestModel_TurnEventCalloutError(): + """ + Test Class for TurnEventCalloutError + """ + + def test_turn_event_callout_error_serialization(self): + """ + Test serialization/deserialization for TurnEventCalloutError + """ + + # Construct a json representation of a TurnEventCalloutError model + turn_event_callout_error_model_json = {} + turn_event_callout_error_model_json['message'] = 'testString' + + # Construct a model instance of TurnEventCalloutError by calling from_dict on the json representation + turn_event_callout_error_model = TurnEventCalloutError.from_dict(turn_event_callout_error_model_json) + assert turn_event_callout_error_model != False + + # Construct a model instance of TurnEventCalloutError by calling from_dict on the json representation + turn_event_callout_error_model_dict = TurnEventCalloutError.from_dict(turn_event_callout_error_model_json).__dict__ + turn_event_callout_error_model2 = TurnEventCalloutError(**turn_event_callout_error_model_dict) + + # Verify the model instances are equivalent + assert turn_event_callout_error_model == turn_event_callout_error_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_callout_error_model_json2 = turn_event_callout_error_model.to_dict() + assert turn_event_callout_error_model_json2 == turn_event_callout_error_model_json + +class TestModel_TurnEventNodeSource(): + """ + Test Class for TurnEventNodeSource + """ + + def test_turn_event_node_source_serialization(self): + """ + Test serialization/deserialization for TurnEventNodeSource + """ + + # Construct a json representation of a TurnEventNodeSource model + turn_event_node_source_model_json = {} + turn_event_node_source_model_json['type'] = 'dialog_node' + turn_event_node_source_model_json['dialog_node'] = 'testString' + turn_event_node_source_model_json['title'] = 'testString' + turn_event_node_source_model_json['condition'] = 'testString' + + # Construct a model instance of TurnEventNodeSource by calling from_dict on the json representation + turn_event_node_source_model = TurnEventNodeSource.from_dict(turn_event_node_source_model_json) + assert turn_event_node_source_model != False + + # Construct a model instance of TurnEventNodeSource by calling from_dict on the json representation + turn_event_node_source_model_dict = TurnEventNodeSource.from_dict(turn_event_node_source_model_json).__dict__ + turn_event_node_source_model2 = TurnEventNodeSource(**turn_event_node_source_model_dict) + + # Verify the model instances are equivalent + assert turn_event_node_source_model == turn_event_node_source_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_node_source_model_json2 = turn_event_node_source_model.to_dict() + assert turn_event_node_source_model_json2 == turn_event_node_source_model_json + +class TestModel_TurnEventSearchError(): + """ + Test Class for TurnEventSearchError + """ + + def test_turn_event_search_error_serialization(self): + """ + Test serialization/deserialization for TurnEventSearchError + """ + + # Construct a json representation of a TurnEventSearchError model + turn_event_search_error_model_json = {} + turn_event_search_error_model_json['message'] = 'testString' + + # Construct a model instance of TurnEventSearchError by calling from_dict on the json representation + turn_event_search_error_model = TurnEventSearchError.from_dict(turn_event_search_error_model_json) + assert turn_event_search_error_model != False + + # Construct a model instance of TurnEventSearchError by calling from_dict on the json representation + turn_event_search_error_model_dict = TurnEventSearchError.from_dict(turn_event_search_error_model_json).__dict__ + turn_event_search_error_model2 = TurnEventSearchError(**turn_event_search_error_model_dict) + + # Verify the model instances are equivalent + assert turn_event_search_error_model == turn_event_search_error_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_search_error_model_json2 = turn_event_search_error_model.to_dict() + assert turn_event_search_error_model_json2 == turn_event_search_error_model_json + class TestModel_LogMessageSourceAction(): """ Test Class for LogMessageSourceAction @@ -4492,6 +5926,338 @@ def test_log_message_source_step_serialization(self): log_message_source_step_model_json2 = log_message_source_step_model.to_dict() assert log_message_source_step_model_json2 == log_message_source_step_model_json +class TestModel_MessageOutputDebugTurnEventTurnEventActionFinished(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventActionFinished + """ + + def test_message_output_debug_turn_event_turn_event_action_finished_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventActionFinished + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventActionFinished model + message_output_debug_turn_event_turn_event_action_finished_model_json = {} + message_output_debug_turn_event_turn_event_action_finished_model_json['event'] = 'action_finished' + message_output_debug_turn_event_turn_event_action_finished_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_action_finished_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_action_finished_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_action_finished_model_json['reason'] = 'all_steps_done' + message_output_debug_turn_event_turn_event_action_finished_model_json['action_variables'] = {'key1': 'testString'} + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionFinished by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_finished_model = MessageOutputDebugTurnEventTurnEventActionFinished.from_dict(message_output_debug_turn_event_turn_event_action_finished_model_json) + assert message_output_debug_turn_event_turn_event_action_finished_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionFinished by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_finished_model_dict = MessageOutputDebugTurnEventTurnEventActionFinished.from_dict(message_output_debug_turn_event_turn_event_action_finished_model_json).__dict__ + message_output_debug_turn_event_turn_event_action_finished_model2 = MessageOutputDebugTurnEventTurnEventActionFinished(**message_output_debug_turn_event_turn_event_action_finished_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_action_finished_model == message_output_debug_turn_event_turn_event_action_finished_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_action_finished_model_json2 = message_output_debug_turn_event_turn_event_action_finished_model.to_dict() + assert message_output_debug_turn_event_turn_event_action_finished_model_json2 == message_output_debug_turn_event_turn_event_action_finished_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventActionVisited(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventActionVisited + """ + + def test_message_output_debug_turn_event_turn_event_action_visited_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventActionVisited + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventActionVisited model + message_output_debug_turn_event_turn_event_action_visited_model_json = {} + message_output_debug_turn_event_turn_event_action_visited_model_json['event'] = 'action_visited' + message_output_debug_turn_event_turn_event_action_visited_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_action_visited_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_action_visited_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_action_visited_model_json['reason'] = 'intent' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_visited_model = MessageOutputDebugTurnEventTurnEventActionVisited.from_dict(message_output_debug_turn_event_turn_event_action_visited_model_json) + assert message_output_debug_turn_event_turn_event_action_visited_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_visited_model_dict = MessageOutputDebugTurnEventTurnEventActionVisited.from_dict(message_output_debug_turn_event_turn_event_action_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_action_visited_model2 = MessageOutputDebugTurnEventTurnEventActionVisited(**message_output_debug_turn_event_turn_event_action_visited_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_action_visited_model == message_output_debug_turn_event_turn_event_action_visited_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_action_visited_model_json2 = message_output_debug_turn_event_turn_event_action_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_action_visited_model_json2 == message_output_debug_turn_event_turn_event_action_visited_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventCallout(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventCallout + """ + + def test_message_output_debug_turn_event_turn_event_callout_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventCallout + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + turn_event_callout_callout_model = {} # TurnEventCalloutCallout + turn_event_callout_callout_model['type'] = 'integration_interaction' + turn_event_callout_callout_model['internal'] = {'key1': 'testString'} + + turn_event_callout_error_model = {} # TurnEventCalloutError + turn_event_callout_error_model['message'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventCallout model + message_output_debug_turn_event_turn_event_callout_model_json = {} + message_output_debug_turn_event_turn_event_callout_model_json['event'] = 'callout' + message_output_debug_turn_event_turn_event_callout_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_callout_model_json['callout'] = turn_event_callout_callout_model + message_output_debug_turn_event_turn_event_callout_model_json['error'] = turn_event_callout_error_model + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventCallout by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_callout_model = MessageOutputDebugTurnEventTurnEventCallout.from_dict(message_output_debug_turn_event_turn_event_callout_model_json) + assert message_output_debug_turn_event_turn_event_callout_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventCallout by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_callout_model_dict = MessageOutputDebugTurnEventTurnEventCallout.from_dict(message_output_debug_turn_event_turn_event_callout_model_json).__dict__ + message_output_debug_turn_event_turn_event_callout_model2 = MessageOutputDebugTurnEventTurnEventCallout(**message_output_debug_turn_event_turn_event_callout_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_callout_model == message_output_debug_turn_event_turn_event_callout_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_callout_model_json2 = message_output_debug_turn_event_turn_event_callout_model.to_dict() + assert message_output_debug_turn_event_turn_event_callout_model_json2 == message_output_debug_turn_event_turn_event_callout_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventHandlerVisited(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventHandlerVisited + """ + + def test_message_output_debug_turn_event_turn_event_handler_visited_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventHandlerVisited + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventHandlerVisited model + message_output_debug_turn_event_turn_event_handler_visited_model_json = {} + message_output_debug_turn_event_turn_event_handler_visited_model_json['event'] = 'handler_visited' + message_output_debug_turn_event_turn_event_handler_visited_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_handler_visited_model_json['action_start_time'] = 'testString' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventHandlerVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_handler_visited_model = MessageOutputDebugTurnEventTurnEventHandlerVisited.from_dict(message_output_debug_turn_event_turn_event_handler_visited_model_json) + assert message_output_debug_turn_event_turn_event_handler_visited_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventHandlerVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_handler_visited_model_dict = MessageOutputDebugTurnEventTurnEventHandlerVisited.from_dict(message_output_debug_turn_event_turn_event_handler_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_handler_visited_model2 = MessageOutputDebugTurnEventTurnEventHandlerVisited(**message_output_debug_turn_event_turn_event_handler_visited_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_handler_visited_model == message_output_debug_turn_event_turn_event_handler_visited_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_handler_visited_model_json2 = message_output_debug_turn_event_turn_event_handler_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_handler_visited_model_json2 == message_output_debug_turn_event_turn_event_handler_visited_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventNodeVisited(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventNodeVisited + """ + + def test_message_output_debug_turn_event_turn_event_node_visited_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventNodeVisited + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_node_source_model = {} # TurnEventNodeSource + turn_event_node_source_model['type'] = 'dialog_node' + turn_event_node_source_model['dialog_node'] = 'testString' + turn_event_node_source_model['title'] = 'testString' + turn_event_node_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventNodeVisited model + message_output_debug_turn_event_turn_event_node_visited_model_json = {} + message_output_debug_turn_event_turn_event_node_visited_model_json['event'] = 'node_visited' + message_output_debug_turn_event_turn_event_node_visited_model_json['source'] = turn_event_node_source_model + message_output_debug_turn_event_turn_event_node_visited_model_json['reason'] = 'welcome' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventNodeVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_node_visited_model = MessageOutputDebugTurnEventTurnEventNodeVisited.from_dict(message_output_debug_turn_event_turn_event_node_visited_model_json) + assert message_output_debug_turn_event_turn_event_node_visited_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventNodeVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_node_visited_model_dict = MessageOutputDebugTurnEventTurnEventNodeVisited.from_dict(message_output_debug_turn_event_turn_event_node_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_node_visited_model2 = MessageOutputDebugTurnEventTurnEventNodeVisited(**message_output_debug_turn_event_turn_event_node_visited_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_node_visited_model == message_output_debug_turn_event_turn_event_node_visited_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_node_visited_model_json2 = message_output_debug_turn_event_turn_event_node_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_node_visited_model_json2 == message_output_debug_turn_event_turn_event_node_visited_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventSearch(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventSearch + """ + + def test_message_output_debug_turn_event_turn_event_search_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventSearch + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + turn_event_search_error_model = {} # TurnEventSearchError + turn_event_search_error_model['message'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventSearch model + message_output_debug_turn_event_turn_event_search_model_json = {} + message_output_debug_turn_event_turn_event_search_model_json['event'] = 'search' + message_output_debug_turn_event_turn_event_search_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_search_model_json['error'] = turn_event_search_error_model + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventSearch by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_search_model = MessageOutputDebugTurnEventTurnEventSearch.from_dict(message_output_debug_turn_event_turn_event_search_model_json) + assert message_output_debug_turn_event_turn_event_search_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventSearch by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_search_model_dict = MessageOutputDebugTurnEventTurnEventSearch.from_dict(message_output_debug_turn_event_turn_event_search_model_json).__dict__ + message_output_debug_turn_event_turn_event_search_model2 = MessageOutputDebugTurnEventTurnEventSearch(**message_output_debug_turn_event_turn_event_search_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_search_model == message_output_debug_turn_event_turn_event_search_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_search_model_json2 = message_output_debug_turn_event_turn_event_search_model.to_dict() + assert message_output_debug_turn_event_turn_event_search_model_json2 == message_output_debug_turn_event_turn_event_search_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventStepAnswered(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventStepAnswered + """ + + def test_message_output_debug_turn_event_turn_event_step_answered_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventStepAnswered + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventStepAnswered model + message_output_debug_turn_event_turn_event_step_answered_model_json = {} + message_output_debug_turn_event_turn_event_step_answered_model_json['event'] = 'step_answered' + message_output_debug_turn_event_turn_event_step_answered_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_step_answered_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_step_answered_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_step_answered_model_json['prompted'] = True + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepAnswered by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_answered_model = MessageOutputDebugTurnEventTurnEventStepAnswered.from_dict(message_output_debug_turn_event_turn_event_step_answered_model_json) + assert message_output_debug_turn_event_turn_event_step_answered_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepAnswered by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_answered_model_dict = MessageOutputDebugTurnEventTurnEventStepAnswered.from_dict(message_output_debug_turn_event_turn_event_step_answered_model_json).__dict__ + message_output_debug_turn_event_turn_event_step_answered_model2 = MessageOutputDebugTurnEventTurnEventStepAnswered(**message_output_debug_turn_event_turn_event_step_answered_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_step_answered_model == message_output_debug_turn_event_turn_event_step_answered_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_step_answered_model_json2 = message_output_debug_turn_event_turn_event_step_answered_model.to_dict() + assert message_output_debug_turn_event_turn_event_step_answered_model_json2 == message_output_debug_turn_event_turn_event_step_answered_model_json + +class TestModel_MessageOutputDebugTurnEventTurnEventStepVisited(): + """ + Test Class for MessageOutputDebugTurnEventTurnEventStepVisited + """ + + def test_message_output_debug_turn_event_turn_event_step_visited_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventStepVisited + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventStepVisited model + message_output_debug_turn_event_turn_event_step_visited_model_json = {} + message_output_debug_turn_event_turn_event_step_visited_model_json['event'] = 'step_visited' + message_output_debug_turn_event_turn_event_step_visited_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_step_visited_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_step_visited_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_step_visited_model_json['has_question'] = True + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_visited_model = MessageOutputDebugTurnEventTurnEventStepVisited.from_dict(message_output_debug_turn_event_turn_event_step_visited_model_json) + assert message_output_debug_turn_event_turn_event_step_visited_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_visited_model_dict = MessageOutputDebugTurnEventTurnEventStepVisited.from_dict(message_output_debug_turn_event_turn_event_step_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_step_visited_model2 = MessageOutputDebugTurnEventTurnEventStepVisited(**message_output_debug_turn_event_turn_event_step_visited_model_dict) + + # Verify the model instances are equivalent + assert message_output_debug_turn_event_turn_event_step_visited_model == message_output_debug_turn_event_turn_event_step_visited_model2 + + # Convert model instance back to dict and verify no loss of data + message_output_debug_turn_event_turn_event_step_visited_model_json2 = message_output_debug_turn_event_turn_event_step_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_step_visited_model_json2 == message_output_debug_turn_event_turn_event_step_visited_model_json + class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeAudio @@ -4514,7 +6280,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation @@ -4594,7 +6360,7 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali agent_availability_message_model['message'] = 'testString' dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {} + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'key1': 'testString'}} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' @@ -4624,6 +6390,35 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json +class TestModel_RuntimeResponseGenericRuntimeResponseTypeDate(): + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeDate + """ + + def test_runtime_response_generic_runtime_response_type_date_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeDate + """ + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeDate model + runtime_response_generic_runtime_response_type_date_model_json = {} + runtime_response_generic_runtime_response_type_date_model_json['response_type'] = 'date' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeDate by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_date_model = RuntimeResponseGenericRuntimeResponseTypeDate.from_dict(runtime_response_generic_runtime_response_type_date_model_json) + assert runtime_response_generic_runtime_response_type_date_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeDate by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_date_model_dict = RuntimeResponseGenericRuntimeResponseTypeDate.from_dict(runtime_response_generic_runtime_response_type_date_model_json).__dict__ + runtime_response_generic_runtime_response_type_date_model2 = RuntimeResponseGenericRuntimeResponseTypeDate(**runtime_response_generic_runtime_response_type_date_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_date_model == runtime_response_generic_runtime_response_type_date_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_date_model_json2 = runtime_response_generic_runtime_response_type_date_model.to_dict() + assert runtime_response_generic_runtime_response_type_date_model_json2 == runtime_response_generic_runtime_response_type_date_model_json + class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe(): """ Test Class for RuntimeResponseGenericRuntimeResponseTypeIframe @@ -4717,6 +6512,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -4766,6 +6562,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -4939,6 +6736,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -4988,6 +6786,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_model['interpretation'] = runtime_entity_interpretation_model runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -5020,7 +6819,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization dialog_suggestion_model = {} # DialogSuggestion dialog_suggestion_model['label'] = 'testString' dialog_suggestion_model['value'] = dialog_suggestion_value_model - dialog_suggestion_model['output'] = {} + dialog_suggestion_model['output'] = {'key1': 'testString'} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' @@ -5101,7 +6900,7 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model runtime_response_generic_runtime_response_type_user_defined_model_json = {} runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' - runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {} + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'key1': 'testString'} runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation @@ -5141,7 +6940,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self runtime_response_generic_runtime_response_type_video_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = { 'foo': 'bar' } + runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation From dea58c536126d3e4dab29710c5bd5ac2366b7cf2 Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Wed, 10 Aug 2022 09:19:05 -0500 Subject: [PATCH 370/455] refactor(discovery-v1): minor code cleanup --- ibm_watson/discovery_v1.py | 72 ++++++++++++++++++++++- test/unit/test_discovery_v1.py | 104 +++++++-------------------------- 2 files changed, 90 insertions(+), 86 deletions(-) diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 08411eb79..cfd74bf3d 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -14,9 +14,9 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 """ -IBM Watson™ Discovery is a cognitive search and content analytics engine that you +IBM Watson™ Discovery v1 is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive better decision-making. Securely unify structured and unstructured data with pre-enriched content, and use a simplified query language to eliminate the need for manual filtering of @@ -124,6 +124,7 @@ def create_environment(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/environments' @@ -161,6 +162,7 @@ def list_environments(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/environments' @@ -195,6 +197,7 @@ def get_environment(self, environment_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -249,6 +252,7 @@ def update_environment(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -287,6 +291,7 @@ def delete_environment(self, environment_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -334,6 +339,7 @@ def list_fields(self, environment_id: str, collection_ids: List[str], if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -430,6 +436,7 @@ def create_configuration( if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -475,6 +482,7 @@ def list_configurations(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -516,6 +524,7 @@ def get_configuration(self, environment_id: str, configuration_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'configuration_id'] @@ -612,6 +621,7 @@ def update_configuration( if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'configuration_id'] @@ -662,6 +672,7 @@ def delete_configuration(self, environment_id: str, configuration_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'configuration_id'] @@ -729,6 +740,7 @@ def create_collection(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -774,6 +786,7 @@ def list_collections(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -815,6 +828,7 @@ def get_collection(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -877,6 +891,7 @@ def update_collection(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -919,6 +934,7 @@ def delete_collection(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -962,6 +978,7 @@ def list_collection_fields(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1010,6 +1027,7 @@ def list_expansions(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1077,6 +1095,7 @@ def create_expansions(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1122,6 +1141,7 @@ def delete_expansions(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['environment_id', 'collection_id'] path_param_values = self.encode_path_vars(environment_id, collection_id) @@ -1167,6 +1187,7 @@ def get_tokenization_dictionary_status(self, environment_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1227,6 +1248,7 @@ def create_tokenization_dictionary( if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1273,6 +1295,7 @@ def delete_tokenization_dictionary(self, environment_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['environment_id', 'collection_id'] path_param_values = self.encode_path_vars(environment_id, collection_id) @@ -1315,6 +1338,7 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1375,6 +1399,7 @@ def create_stopword_list(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1420,6 +1445,7 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['environment_id', 'collection_id'] path_param_values = self.encode_path_vars(environment_id, collection_id) @@ -1514,6 +1540,7 @@ def add_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -1564,6 +1591,7 @@ def get_document_status(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'document_id'] @@ -1644,6 +1672,7 @@ def update_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'document_id'] @@ -1694,6 +1723,7 @@ def delete_document(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'document_id'] @@ -1868,6 +1898,7 @@ def query(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -2009,6 +2040,7 @@ def query_notices(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -2172,6 +2204,7 @@ def federated_query(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -2297,6 +2330,7 @@ def federated_query_notices(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -2361,6 +2395,7 @@ def get_autocompletion(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -2408,6 +2443,7 @@ def list_training_data(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -2475,6 +2511,7 @@ def add_training_data(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id'] @@ -2519,6 +2556,7 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['environment_id', 'collection_id'] path_param_values = self.encode_path_vars(environment_id, collection_id) @@ -2565,6 +2603,7 @@ def get_training_data(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'query_id'] @@ -2613,6 +2652,7 @@ def delete_training_data(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['environment_id', 'collection_id', 'query_id'] path_param_values = self.encode_path_vars(environment_id, collection_id, @@ -2659,6 +2699,7 @@ def list_training_examples(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'query_id'] @@ -2727,6 +2768,7 @@ def create_training_example(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'collection_id', 'query_id'] @@ -2779,6 +2821,7 @@ def delete_training_example(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = [ 'environment_id', 'collection_id', 'query_id', 'example_id' @@ -2844,6 +2887,7 @@ def update_training_example(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = [ @@ -2898,6 +2942,7 @@ def get_training_example(self, environment_id: str, collection_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = [ @@ -2950,6 +2995,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/user_data' request = self.prepare_request(method='DELETE', @@ -3000,6 +3046,7 @@ def create_event(self, type: str, data: 'EventData', if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/events' @@ -3065,6 +3112,7 @@ def query_log(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/logs' @@ -3114,6 +3162,7 @@ def get_metrics_query(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries' @@ -3164,6 +3213,7 @@ def get_metrics_query_event(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries_with_event' @@ -3214,6 +3264,7 @@ def get_metrics_query_no_results(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries_with_no_search_results' @@ -3264,6 +3315,7 @@ def get_metrics_event_rate(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/metrics/event_rate' @@ -3305,6 +3357,7 @@ def get_metrics_query_token_event(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/metrics/top_query_tokens_with_event_rate' @@ -3347,6 +3400,7 @@ def list_credentials(self, environment_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -3424,6 +3478,7 @@ def create_credentials(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -3471,6 +3526,7 @@ def get_credentials(self, environment_id: str, credential_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'credential_id'] @@ -3552,6 +3608,7 @@ def update_credentials(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'credential_id'] @@ -3597,6 +3654,7 @@ def delete_credentials(self, environment_id: str, credential_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'credential_id'] @@ -3640,6 +3698,7 @@ def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -3689,6 +3748,7 @@ def create_gateway(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id'] @@ -3733,6 +3793,7 @@ def get_gateway(self, environment_id: str, gateway_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'gateway_id'] @@ -3776,6 +3837,7 @@ def delete_gateway(self, environment_id: str, gateway_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['environment_id', 'gateway_id'] @@ -12465,7 +12527,9 @@ class TrainingDataSet(): training data set. :attr str collection_id: (optional) The collection id associated with this training data set. - :attr List[TrainingQuery] queries: (optional) Array of training queries. + :attr List[TrainingQuery] queries: (optional) Array of training queries. At + least 50 queries are required for training to begin. A maximum of 10,000 queries + are returned. """ def __init__(self, @@ -12481,6 +12545,8 @@ def __init__(self, :param str collection_id: (optional) The collection id associated with this training data set. :param List[TrainingQuery] queries: (optional) Array of training queries. + At least 50 queries are required for training to begin. A maximum of 10,000 + queries are returned. """ self.environment_id = environment_id self.collection_id = collection_id diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 1b6b9efb5..a37881797 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -152,7 +152,6 @@ def test_create_environment_value_error(self): with pytest.raises(ValueError): _service.create_environment(**req_copy) - def test_create_environment_value_error_with_retries(self): # Enable retries and run test_create_environment_value_error. _service.enable_retries() @@ -260,7 +259,6 @@ def test_list_environments_value_error(self): with pytest.raises(ValueError): _service.list_environments(**req_copy) - def test_list_environments_value_error_with_retries(self): # Enable retries and run test_list_environments_value_error. _service.enable_retries() @@ -337,7 +335,6 @@ def test_get_environment_value_error(self): with pytest.raises(ValueError): _service.get_environment(**req_copy) - def test_get_environment_value_error_with_retries(self): # Enable retries and run test_get_environment_value_error. _service.enable_retries() @@ -428,7 +425,6 @@ def test_update_environment_value_error(self): with pytest.raises(ValueError): _service.update_environment(**req_copy) - def test_update_environment_value_error_with_retries(self): # Enable retries and run test_update_environment_value_error. _service.enable_retries() @@ -505,7 +501,6 @@ def test_delete_environment_value_error(self): with pytest.raises(ValueError): _service.delete_environment(**req_copy) - def test_delete_environment_value_error_with_retries(self): # Enable retries and run test_delete_environment_value_error. _service.enable_retries() @@ -590,7 +585,6 @@ def test_list_fields_value_error(self): with pytest.raises(ValueError): _service.list_fields(**req_copy) - def test_list_fields_value_error_with_retries(self): # Enable retries and run test_list_fields_value_error. _service.enable_retries() @@ -740,7 +734,7 @@ def test_create_configuration_all_params(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'key1': 'testString'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -982,7 +976,7 @@ def test_create_configuration_value_error(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'key1': 'testString'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1076,7 +1070,6 @@ def test_create_configuration_value_error(self): with pytest.raises(ValueError): _service.create_configuration(**req_copy) - def test_create_configuration_value_error_with_retries(self): # Enable retries and run test_create_configuration_value_error. _service.enable_retries() @@ -1195,7 +1188,6 @@ def test_list_configurations_value_error(self): with pytest.raises(ValueError): _service.list_configurations(**req_copy) - def test_list_configurations_value_error_with_retries(self): # Enable retries and run test_list_configurations_value_error. _service.enable_retries() @@ -1276,7 +1268,6 @@ def test_get_configuration_value_error(self): with pytest.raises(ValueError): _service.get_configuration(**req_copy) - def test_get_configuration_value_error_with_retries(self): # Enable retries and run test_get_configuration_value_error. _service.enable_retries() @@ -1416,7 +1407,7 @@ def test_update_configuration_all_params(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'key1': 'testString'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1660,7 +1651,7 @@ def test_update_configuration_value_error(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'key1': 'testString'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1756,7 +1747,6 @@ def test_update_configuration_value_error(self): with pytest.raises(ValueError): _service.update_configuration(**req_copy) - def test_update_configuration_value_error_with_retries(self): # Enable retries and run test_update_configuration_value_error. _service.enable_retries() @@ -1837,7 +1827,6 @@ def test_delete_configuration_value_error(self): with pytest.raises(ValueError): _service.delete_configuration(**req_copy) - def test_delete_configuration_value_error_with_retries(self): # Enable retries and run test_delete_configuration_value_error. _service.enable_retries() @@ -1943,7 +1932,6 @@ def test_create_collection_value_error(self): with pytest.raises(ValueError): _service.create_collection(**req_copy) - def test_create_collection_value_error_with_retries(self): # Enable retries and run test_create_collection_value_error. _service.enable_retries() @@ -2062,7 +2050,6 @@ def test_list_collections_value_error(self): with pytest.raises(ValueError): _service.list_collections(**req_copy) - def test_list_collections_value_error_with_retries(self): # Enable retries and run test_list_collections_value_error. _service.enable_retries() @@ -2143,7 +2130,6 @@ def test_get_collection_value_error(self): with pytest.raises(ValueError): _service.get_collection(**req_copy) - def test_get_collection_value_error_with_retries(self): # Enable retries and run test_get_collection_value_error. _service.enable_retries() @@ -2239,7 +2225,6 @@ def test_update_collection_value_error(self): with pytest.raises(ValueError): _service.update_collection(**req_copy) - def test_update_collection_value_error_with_retries(self): # Enable retries and run test_update_collection_value_error. _service.enable_retries() @@ -2320,7 +2305,6 @@ def test_delete_collection_value_error(self): with pytest.raises(ValueError): _service.delete_collection(**req_copy) - def test_delete_collection_value_error_with_retries(self): # Enable retries and run test_delete_collection_value_error. _service.enable_retries() @@ -2401,7 +2385,6 @@ def test_list_collection_fields_value_error(self): with pytest.raises(ValueError): _service.list_collection_fields(**req_copy) - def test_list_collection_fields_value_error_with_retries(self): # Enable retries and run test_list_collection_fields_value_error. _service.enable_retries() @@ -2492,7 +2475,6 @@ def test_list_expansions_value_error(self): with pytest.raises(ValueError): _service.list_expansions(**req_copy) - def test_list_expansions_value_error_with_retries(self): # Enable retries and run test_list_expansions_value_error. _service.enable_retries() @@ -2590,7 +2572,6 @@ def test_create_expansions_value_error(self): with pytest.raises(ValueError): _service.create_expansions(**req_copy) - def test_create_expansions_value_error_with_retries(self): # Enable retries and run test_create_expansions_value_error. _service.enable_retries() @@ -2665,7 +2646,6 @@ def test_delete_expansions_value_error(self): with pytest.raises(ValueError): _service.delete_expansions(**req_copy) - def test_delete_expansions_value_error_with_retries(self): # Enable retries and run test_delete_expansions_value_error. _service.enable_retries() @@ -2746,7 +2726,6 @@ def test_get_tokenization_dictionary_status_value_error(self): with pytest.raises(ValueError): _service.get_tokenization_dictionary_status(**req_copy) - def test_get_tokenization_dictionary_status_value_error_with_retries(self): # Enable retries and run test_get_tokenization_dictionary_status_value_error. _service.enable_retries() @@ -2877,7 +2856,6 @@ def test_create_tokenization_dictionary_value_error(self): with pytest.raises(ValueError): _service.create_tokenization_dictionary(**req_copy) - def test_create_tokenization_dictionary_value_error_with_retries(self): # Enable retries and run test_create_tokenization_dictionary_value_error. _service.enable_retries() @@ -2952,7 +2930,6 @@ def test_delete_tokenization_dictionary_value_error(self): with pytest.raises(ValueError): _service.delete_tokenization_dictionary(**req_copy) - def test_delete_tokenization_dictionary_value_error_with_retries(self): # Enable retries and run test_delete_tokenization_dictionary_value_error. _service.enable_retries() @@ -3033,7 +3010,6 @@ def test_get_stopword_list_status_value_error(self): with pytest.raises(ValueError): _service.get_stopword_list_status(**req_copy) - def test_get_stopword_list_status_value_error_with_retries(self): # Enable retries and run test_get_stopword_list_status_value_error. _service.enable_retries() @@ -3163,7 +3139,6 @@ def test_create_stopword_list_value_error(self): with pytest.raises(ValueError): _service.create_stopword_list(**req_copy) - def test_create_stopword_list_value_error_with_retries(self): # Enable retries and run test_create_stopword_list_value_error. _service.enable_retries() @@ -3238,7 +3213,6 @@ def test_delete_stopword_list_value_error(self): with pytest.raises(ValueError): _service.delete_stopword_list(**req_copy) - def test_delete_stopword_list_value_error_with_retries(self): # Enable retries and run test_delete_stopword_list_value_error. _service.enable_retries() @@ -3375,7 +3349,6 @@ def test_add_document_value_error(self): with pytest.raises(ValueError): _service.add_document(**req_copy) - def test_add_document_value_error_with_retries(self): # Enable retries and run test_add_document_value_error. _service.enable_retries() @@ -3460,7 +3433,6 @@ def test_get_document_status_value_error(self): with pytest.raises(ValueError): _service.get_document_status(**req_copy) - def test_get_document_status_value_error_with_retries(self): # Enable retries and run test_get_document_status_value_error. _service.enable_retries() @@ -3593,7 +3565,6 @@ def test_update_document_value_error(self): with pytest.raises(ValueError): _service.update_document(**req_copy) - def test_update_document_value_error_with_retries(self): # Enable retries and run test_update_document_value_error. _service.enable_retries() @@ -3678,7 +3649,6 @@ def test_delete_document_value_error(self): with pytest.raises(ValueError): _service.delete_document(**req_copy) - def test_delete_document_value_error_with_retries(self): # Enable retries and run test_delete_document_value_error. _service.enable_retries() @@ -3871,7 +3841,6 @@ def test_query_value_error(self): with pytest.raises(ValueError): _service.query(**req_copy) - def test_query_value_error_with_retries(self): # Enable retries and run test_query_value_error. _service.enable_retries() @@ -4044,7 +4013,6 @@ def test_query_notices_value_error(self): with pytest.raises(ValueError): _service.query_notices(**req_copy) - def test_query_notices_value_error_with_retries(self): # Enable retries and run test_query_notices_value_error. _service.enable_retries() @@ -4304,7 +4272,6 @@ def test_federated_query_value_error(self): with pytest.raises(ValueError): _service.federated_query(**req_copy) - def test_federated_query_value_error_with_retries(self): # Enable retries and run test_federated_query_value_error. _service.enable_retries() @@ -4470,7 +4437,6 @@ def test_federated_query_notices_value_error(self): with pytest.raises(ValueError): _service.federated_query_notices(**req_copy) - def test_federated_query_notices_value_error_with_retries(self): # Enable retries and run test_federated_query_notices_value_error. _service.enable_retries() @@ -4609,7 +4575,6 @@ def test_get_autocompletion_value_error(self): with pytest.raises(ValueError): _service.get_autocompletion(**req_copy) - def test_get_autocompletion_value_error_with_retries(self): # Enable retries and run test_get_autocompletion_value_error. _service.enable_retries() @@ -4700,7 +4665,6 @@ def test_list_training_data_value_error(self): with pytest.raises(ValueError): _service.list_training_data(**req_copy) - def test_list_training_data_value_error_with_retries(self): # Enable retries and run test_list_training_data_value_error. _service.enable_retries() @@ -4807,7 +4771,6 @@ def test_add_training_data_value_error(self): with pytest.raises(ValueError): _service.add_training_data(**req_copy) - def test_add_training_data_value_error_with_retries(self): # Enable retries and run test_add_training_data_value_error. _service.enable_retries() @@ -4882,7 +4845,6 @@ def test_delete_all_training_data_value_error(self): with pytest.raises(ValueError): _service.delete_all_training_data(**req_copy) - def test_delete_all_training_data_value_error_with_retries(self): # Enable retries and run test_delete_all_training_data_value_error. _service.enable_retries() @@ -4967,7 +4929,6 @@ def test_get_training_data_value_error(self): with pytest.raises(ValueError): _service.get_training_data(**req_copy) - def test_get_training_data_value_error_with_retries(self): # Enable retries and run test_get_training_data_value_error. _service.enable_retries() @@ -5046,7 +5007,6 @@ def test_delete_training_data_value_error(self): with pytest.raises(ValueError): _service.delete_training_data(**req_copy) - def test_delete_training_data_value_error_with_retries(self): # Enable retries and run test_delete_training_data_value_error. _service.enable_retries() @@ -5131,7 +5091,6 @@ def test_list_training_examples_value_error(self): with pytest.raises(ValueError): _service.list_training_examples(**req_copy) - def test_list_training_examples_value_error_with_retries(self): # Enable retries and run test_list_training_examples_value_error. _service.enable_retries() @@ -5230,7 +5189,6 @@ def test_create_training_example_value_error(self): with pytest.raises(ValueError): _service.create_training_example(**req_copy) - def test_create_training_example_value_error_with_retries(self): # Enable retries and run test_create_training_example_value_error. _service.enable_retries() @@ -5313,7 +5271,6 @@ def test_delete_training_example_value_error(self): with pytest.raises(ValueError): _service.delete_training_example(**req_copy) - def test_delete_training_example_value_error_with_retries(self): # Enable retries and run test_delete_training_example_value_error. _service.enable_retries() @@ -5412,7 +5369,6 @@ def test_update_training_example_value_error(self): with pytest.raises(ValueError): _service.update_training_example(**req_copy) - def test_update_training_example_value_error_with_retries(self): # Enable retries and run test_update_training_example_value_error. _service.enable_retries() @@ -5501,7 +5457,6 @@ def test_get_training_example_value_error(self): with pytest.raises(ValueError): _service.get_training_example(**req_copy) - def test_get_training_example_value_error_with_retries(self): # Enable retries and run test_get_training_example_value_error. _service.enable_retries() @@ -5586,7 +5541,6 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) - def test_delete_user_data_value_error_with_retries(self): # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() @@ -5699,7 +5653,6 @@ def test_create_event_value_error(self): with pytest.raises(ValueError): _service.create_event(**req_copy) - def test_create_event_value_error_with_retries(self): # Enable retries and run test_create_event_value_error. _service.enable_retries() @@ -5819,7 +5772,6 @@ def test_query_log_value_error(self): with pytest.raises(ValueError): _service.query_log(**req_copy) - def test_query_log_value_error_with_retries(self): # Enable retries and run test_query_log_value_error. _service.enable_retries() @@ -5931,7 +5883,6 @@ def test_get_metrics_query_value_error(self): with pytest.raises(ValueError): _service.get_metrics_query(**req_copy) - def test_get_metrics_query_value_error_with_retries(self): # Enable retries and run test_get_metrics_query_value_error. _service.enable_retries() @@ -6043,7 +5994,6 @@ def test_get_metrics_query_event_value_error(self): with pytest.raises(ValueError): _service.get_metrics_query_event(**req_copy) - def test_get_metrics_query_event_value_error_with_retries(self): # Enable retries and run test_get_metrics_query_event_value_error. _service.enable_retries() @@ -6155,7 +6105,6 @@ def test_get_metrics_query_no_results_value_error(self): with pytest.raises(ValueError): _service.get_metrics_query_no_results(**req_copy) - def test_get_metrics_query_no_results_value_error_with_retries(self): # Enable retries and run test_get_metrics_query_no_results_value_error. _service.enable_retries() @@ -6267,7 +6216,6 @@ def test_get_metrics_event_rate_value_error(self): with pytest.raises(ValueError): _service.get_metrics_event_rate(**req_copy) - def test_get_metrics_event_rate_value_error_with_retries(self): # Enable retries and run test_get_metrics_event_rate_value_error. _service.enable_retries() @@ -6375,7 +6323,6 @@ def test_get_metrics_query_token_event_value_error(self): with pytest.raises(ValueError): _service.get_metrics_query_token_event(**req_copy) - def test_get_metrics_query_token_event_value_error_with_retries(self): # Enable retries and run test_get_metrics_query_token_event_value_error. _service.enable_retries() @@ -6462,7 +6409,6 @@ def test_list_credentials_value_error(self): with pytest.raises(ValueError): _service.list_credentials(**req_copy) - def test_list_credentials_value_error_with_retries(self): # Enable retries and run test_list_credentials_value_error. _service.enable_retries() @@ -6607,7 +6553,6 @@ def test_create_credentials_value_error(self): with pytest.raises(ValueError): _service.create_credentials(**req_copy) - def test_create_credentials_value_error_with_retries(self): # Enable retries and run test_create_credentials_value_error. _service.enable_retries() @@ -6688,7 +6633,6 @@ def test_get_credentials_value_error(self): with pytest.raises(ValueError): _service.get_credentials(**req_copy) - def test_get_credentials_value_error_with_retries(self): # Enable retries and run test_get_credentials_value_error. _service.enable_retries() @@ -6837,7 +6781,6 @@ def test_update_credentials_value_error(self): with pytest.raises(ValueError): _service.update_credentials(**req_copy) - def test_update_credentials_value_error_with_retries(self): # Enable retries and run test_update_credentials_value_error. _service.enable_retries() @@ -6918,7 +6861,6 @@ def test_delete_credentials_value_error(self): with pytest.raises(ValueError): _service.delete_credentials(**req_copy) - def test_delete_credentials_value_error_with_retries(self): # Enable retries and run test_delete_credentials_value_error. _service.enable_retries() @@ -7005,7 +6947,6 @@ def test_list_gateways_value_error(self): with pytest.raises(ValueError): _service.list_gateways(**req_copy) - def test_list_gateways_value_error_with_retries(self): # Enable retries and run test_list_gateways_value_error. _service.enable_retries() @@ -7123,7 +7064,6 @@ def test_create_gateway_value_error(self): with pytest.raises(ValueError): _service.create_gateway(**req_copy) - def test_create_gateway_value_error_with_retries(self): # Enable retries and run test_create_gateway_value_error. _service.enable_retries() @@ -7204,7 +7144,6 @@ def test_get_gateway_value_error(self): with pytest.raises(ValueError): _service.get_gateway(**req_copy) - def test_get_gateway_value_error_with_retries(self): # Enable retries and run test_get_gateway_value_error. _service.enable_retries() @@ -7285,7 +7224,6 @@ def test_delete_gateway_value_error(self): with pytest.raises(ValueError): _service.delete_gateway(**req_copy) - def test_delete_gateway_value_error_with_retries(self): # Enable retries and run test_delete_gateway_value_error. _service.enable_retries() @@ -7613,7 +7551,7 @@ def test_configuration_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'key1': 'testString'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -8359,7 +8297,7 @@ def test_enrichment_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'key1': 'testString'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -8444,7 +8382,7 @@ def test_enrichment_options_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'key1': 'testString'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -9136,7 +9074,7 @@ def test_list_configurations_response_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} + nlu_enrichment_features_model['categories'] = {'key1': 'testString'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -9850,7 +9788,7 @@ def test_nlu_enrichment_features_serialization(self): nlu_enrichment_features_model_json['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model_json['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model_json['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model_json['categories'] = {} + nlu_enrichment_features_model_json['categories'] = {'key1': 'testString'} nlu_enrichment_features_model_json['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model_json['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model_json['concepts'] = nlu_enrichment_concepts_model @@ -10232,7 +10170,7 @@ def test_query_notices_response_serialization(self): query_notices_result_model = {} # QueryNoticesResult query_notices_result_model['id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' - query_notices_result_model['metadata'] = {} + query_notices_result_model['metadata'] = {'key1': 'testString'} query_notices_result_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' query_notices_result_model['result_metadata'] = query_result_metadata_model query_notices_result_model['code'] = 200 @@ -10240,7 +10178,7 @@ def test_query_notices_response_serialization(self): query_notices_result_model['file_type'] = 'html' query_notices_result_model['sha1'] = 'de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3' query_notices_result_model['notices'] = [notice_model] - query_notices_result_model['score'] = { 'foo': 'bar' } + query_notices_result_model['score'] = {'foo': 'bar'} query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' @@ -10306,7 +10244,7 @@ def test_query_notices_result_serialization(self): # Construct a json representation of a QueryNoticesResult model query_notices_result_model_json = {} query_notices_result_model_json['id'] = 'testString' - query_notices_result_model_json['metadata'] = {} + query_notices_result_model_json['metadata'] = {'key1': 'testString'} query_notices_result_model_json['collection_id'] = 'testString' query_notices_result_model_json['result_metadata'] = query_result_metadata_model query_notices_result_model_json['code'] = 38 @@ -10314,7 +10252,7 @@ def test_query_notices_result_serialization(self): query_notices_result_model_json['file_type'] = 'pdf' query_notices_result_model_json['sha1'] = 'testString' query_notices_result_model_json['notices'] = [notice_model] - query_notices_result_model_json['foo'] = { 'foo': 'bar' } + query_notices_result_model_json['foo'] = {'foo': 'bar'} # Construct a model instance of QueryNoticesResult by calling from_dict on the json representation query_notices_result_model = QueryNoticesResult.from_dict(query_notices_result_model_json) @@ -10336,7 +10274,7 @@ def test_query_notices_result_serialization(self): actual_dict = query_notices_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': { 'foo': 'bar' }} + expected_dict = {'foo': {'foo': 'bar'}} query_notices_result_model.set_properties(expected_dict) actual_dict = query_notices_result_model.get_properties() assert actual_dict == expected_dict @@ -10393,10 +10331,10 @@ def test_query_response_serialization(self): query_result_model = {} # QueryResult query_result_model['id'] = 'watson-generated ID' - query_result_model['metadata'] = {} + query_result_model['metadata'] = {'key1': 'testString'} query_result_model['collection_id'] = 'testString' query_result_model['result_metadata'] = query_result_metadata_model - query_result_model['score'] = { 'foo': 'bar' } + query_result_model['score'] = {'foo': 'bar'} query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' @@ -10459,10 +10397,10 @@ def test_query_result_serialization(self): # Construct a json representation of a QueryResult model query_result_model_json = {} query_result_model_json['id'] = 'testString' - query_result_model_json['metadata'] = {} + query_result_model_json['metadata'] = {'key1': 'testString'} query_result_model_json['collection_id'] = 'testString' query_result_model_json['result_metadata'] = query_result_metadata_model - query_result_model_json['foo'] = { 'foo': 'bar' } + query_result_model_json['foo'] = {'foo': 'bar'} # Construct a model instance of QueryResult by calling from_dict on the json representation query_result_model = QueryResult.from_dict(query_result_model_json) @@ -10484,7 +10422,7 @@ def test_query_result_serialization(self): actual_dict = query_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': { 'foo': 'bar' }} + expected_dict = {'foo': {'foo': 'bar'}} query_result_model.set_properties(expected_dict) actual_dict = query_result_model.get_properties() assert actual_dict == expected_dict @@ -10612,7 +10550,7 @@ def test_query_top_hits_aggregation_result_serialization(self): # Construct a json representation of a QueryTopHitsAggregationResult model query_top_hits_aggregation_result_model_json = {} query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{}] + query_top_hits_aggregation_result_model_json['hits'] = [{'key1': 'testString'}] # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) @@ -11777,7 +11715,7 @@ def test_query_top_hits_aggregation_serialization(self): query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{}] + query_top_hits_aggregation_result_model['hits'] = [{'key1': 'testString'}] # Construct a json representation of a QueryTopHitsAggregation model query_top_hits_aggregation_model_json = {} From 972a1ae6f774a4849ffc6e8fe1a77e04090a7441 Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Wed, 10 Aug 2022 09:22:09 -0500 Subject: [PATCH 371/455] feat(discovery-v2): update models and add several new methods New methods are listDocuments, getDocument, listDocumentClassifiers, createDocumentClassifier, getDocumentClassifier, updateDocumentClassifier, deleteDocumentClassifier, listDocumentClassifierModels, createDocumentClassifierModels, getDocumentClassifierModels, updateDocumentClassifierModels, deleteDocumentClassifierModels,getStopwordList, createStopwordList, deleteStopwordList, listExpansions, createExpansions, deleteExpansions --- ibm_watson/discovery_v2.py | 6725 ++++++++++++++++++++++++-------- test/unit/test_discovery_v2.py | 5268 +++++++++++++++++++------ 2 files changed, 9087 insertions(+), 2906 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 708007d08..5f66ab600 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2021. +# (C) Copyright IBM Corp. 2019, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 +# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 """ IBM Watson™ Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive @@ -64,7 +64,7 @@ def __init__( Specify dates in YYYY-MM-DD format. The current version is `2020-08-30`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md about initializing the authenticator of your choice. """ if version is None: @@ -79,40 +79,34 @@ def __init__( self.configure_service(service_name) ######################### - # Collections + # Projects ######################### - def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: + def list_projects(self, **kwargs) -> DetailedResponse: """ - List collections. + List projects. - Lists existing collections for the specified project. + Lists existing projects for this instance. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object + :rtype: DetailedResponse with `dict` result representing a `ListProjectsResponse` object """ - if project_id is None: - raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_collections') + operation_id='list_projects') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) + url = '/v2/projects' request = self.prepare_request(method='GET', url=url, headers=headers, @@ -121,50 +115,48 @@ def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response - def create_collection(self, - project_id: str, - name: str, - *, - description: str = None, - language: str = None, - enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> DetailedResponse: + def create_project(self, + name: str, + type: str, + *, + default_query_parameters: 'DefaultQueryParams' = None, + **kwargs) -> DetailedResponse: """ - Create a collection. + Create a project. - Create a new collection in the specified project. + Create a new project for this instance. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str name: The name of the collection. - :param str description: (optional) A description of the collection. - :param str language: (optional) The language of the collection. - :param List[CollectionEnrichment] enrichments: (optional) An array of - enrichments that are applied to this collection. + :param str name: The human readable name of this project. + :param str type: The type of project. + The `content_intelligence` type is a *Document Retrieval for Contracts* + project and the `other` type is a *Custom* project. + The `content_mining` and `content_intelligence` types are available with + Premium plan managed deployments and installed deployments only. + :param DefaultQueryParams default_query_parameters: (optional) Default + query parameters for this project. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ - if project_id is None: - raise ValueError('project_id must be provided') if name is None: raise ValueError('name must be provided') - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] + if type is None: + raise ValueError('type must be provided') + if default_query_parameters is not None: + default_query_parameters = convert_model(default_query_parameters) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='create_collection') + operation_id='create_project') headers.update(sdk_headers) params = {'version': self.version} data = { 'name': name, - 'description': description, - 'language': language, - 'enrichments': enrichments + 'type': type, + 'default_query_parameters': default_query_parameters } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -172,12 +164,10 @@ def create_collection(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) + url = '/v2/projects' request = self.prepare_request(method='POST', url=url, headers=headers, @@ -187,42 +177,38 @@ def create_collection(self, response = self.send(request, **kwargs) return response - def get_collection(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def get_project(self, project_id: str, **kwargs) -> DetailedResponse: """ - Get collection. + Get project. - Get details about the specified collection. + Get details on the specified project. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID 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 with `dict` result representing a `CollectionDetails` object + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ if project_id is None: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_collection') + operation_id='get_project') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}'.format( - **path_param_dict) + url = '/v2/projects/{project_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -231,63 +217,48 @@ def get_collection(self, project_id: str, collection_id: str, response = self.send(request, **kwargs) return response - def update_collection(self, - project_id: str, - collection_id: str, - *, - name: str = None, - description: str = None, - enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> DetailedResponse: + def update_project(self, + project_id: str, + *, + name: str = None, + **kwargs) -> DetailedResponse: """ - Update a collection. + Update a project. - Updates the specified collection's name, description, and enrichments. + Update the specified project's name. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. - :param str name: (optional) The name of the collection. - :param str description: (optional) A description of the collection. - :param List[CollectionEnrichment] enrichments: (optional) An array of - enrichments that are applied to this collection. + :param str name: (optional) The new name to give this project. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object + :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ if project_id is None: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_collection') + operation_id='update_project') headers.update(sdk_headers) params = {'version': self.version} - data = { - 'name': name, - 'description': description, - 'enrichments': enrichments - } + data = {'name': name} data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}'.format( - **path_param_dict) + url = '/v2/projects/{project_id}'.format(**path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -297,17 +268,16 @@ def update_collection(self, response = self.send(request, **kwargs) return response - def delete_collection(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: """ - Delete a collection. + Delete a project. - Deletes the specified collection from the project. All documents stored in the - specified collection and not shared is also deleted. + Deletes the specified project. + **Important:** Deleting a project deletes everything that is part of the specified + project, including all collections. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID 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 @@ -315,24 +285,22 @@ def delete_collection(self, project_id: str, collection_id: str, if project_id is None: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_collection') + operation_id='delete_project') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}'.format( - **path_param_dict) + url = '/v2/projects/{project_id}'.format(**path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -341,197 +309,93 @@ def delete_collection(self, project_id: str, collection_id: str, response = self.send(request, **kwargs) return response - ######################### - # Queries - ######################### - - def query(self, - project_id: str, - *, - collection_ids: List[str] = None, - filter: str = None, - query: str = None, - natural_language_query: str = None, - aggregation: str = None, - count: int = None, - return_: List[str] = None, - offset: int = None, - sort: str = None, - highlight: bool = None, - spelling_suggestions: bool = None, - table_results: 'QueryLargeTableResults' = None, - suggested_refinements: 'QueryLargeSuggestedRefinements' = None, - passages: 'QueryLargePassages' = None, - **kwargs) -> DetailedResponse: + def list_fields(self, + project_id: str, + *, + collection_ids: List[str] = None, + **kwargs) -> DetailedResponse: """ - Query a project. + List fields. - By using this method, you can construct queries. For details, see the [Discovery - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-concepts). - The default query parameters are defined by the settings for this project, see the - [Discovery - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-project-defaults) - for an overview of the standard default settings, and see [the Projects API - documentation](#create-project) for details about how to set custom default query - settings. + Gets a list of the unique fields (and their types) stored in the specified + collections. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param List[str] collection_ids: (optional) A comma-separated list of - collection IDs to be queried against. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. Use a query search when you want to find the most - relevant search results. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. - :param List[str] return_: (optional) A list of the fields in the document - hierarchy to return. If this parameter is an empty list, then all fields - are returned. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. - :param str sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. - :param bool highlight: (optional) When `true`, a highlight field is - returned for each result which contains the fields which match the query - with `` tags around the matching query terms. - :param bool spelling_suggestions: (optional) When `true` and the - **natural_language_query** parameter is used, the - **natural_language_query** parameter is spell checked. The most likely - correction is returned in the **suggested_query** field of the response (if - one exists). - :param QueryLargeTableResults table_results: (optional) Configuration for - table retrieval. - :param QueryLargeSuggestedRefinements suggested_refinements: (optional) - Configuration for suggested refinements. Available with Premium plans only. - :param QueryLargePassages passages: (optional) Configuration for passage - retrieval. + :param List[str] collection_ids: (optional) Comma separated list of the + collection IDs. If this parameter is not specified, all collections in the + project are used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object + :rtype: DetailedResponse with `dict` result representing a `ListFieldsResponse` object """ if project_id is None: raise ValueError('project_id must be provided') - if table_results is not None: - table_results = convert_model(table_results) - if suggested_refinements is not None: - suggested_refinements = convert_model(suggested_refinements) - if passages is not None: - passages = convert_model(passages) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='query') + operation_id='list_fields') headers.update(sdk_headers) - params = {'version': self.version} - - data = { - 'collection_ids': collection_ids, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'aggregation': aggregation, - 'count': count, - 'return': return_, - 'offset': offset, - 'sort': sort, - 'highlight': highlight, - 'spelling_suggestions': spelling_suggestions, - 'table_results': table_results, - 'suggested_refinements': suggested_refinements, - 'passages': passages + params = { + 'version': self.version, + 'collection_ids': convert_list(collection_ids) } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/query'.format(**path_param_dict) - request = self.prepare_request(method='POST', + url = '/v2/projects/{project_id}/fields'.format(**path_param_dict) + request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - data=data) + params=params) response = self.send(request, **kwargs) return response - def get_autocompletion(self, - project_id: str, - prefix: str, - *, - collection_ids: List[str] = None, - field: str = None, - count: int = None, - **kwargs) -> DetailedResponse: + ######################### + # Collections + ######################### + + def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: """ - Get Autocomplete Suggestions. + List collections. - Returns completion query suggestions for the specified prefix. + Lists existing collections for the specified project. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str prefix: The prefix to use for autocompletion. For example, the - prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. - :param List[str] collection_ids: (optional) Comma separated list of the - collection IDs. If this parameter is not specified, all collections in the - project are used. - :param str field: (optional) The field in the result documents that - autocompletion suggestions are identified from. - :param int count: (optional) The number of autocompletion suggestions to - return. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Completions` object + :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object """ if project_id is None: raise ValueError('project_id must be provided') - if prefix is None: - raise ValueError('prefix must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_autocompletion') + operation_id='list_collections') headers.update(sdk_headers) - params = { - 'version': self.version, - 'prefix': prefix, - 'collection_ids': convert_list(collection_ids), - 'field': field, - 'count': count - } + params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/autocompletion'.format( - **path_param_dict) + url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -540,143 +404,127 @@ def get_autocompletion(self, response = self.send(request, **kwargs) return response - def query_collection_notices(self, - project_id: str, - collection_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - count: int = None, - offset: int = None, - **kwargs) -> DetailedResponse: + def create_collection(self, + project_id: str, + name: str, + *, + description: str = None, + language: str = None, + enrichments: List['CollectionEnrichment'] = None, + smart_document_understanding: + 'CollectionDetailsSmartDocumentUnderstanding' = None, + **kwargs) -> DetailedResponse: """ - Query collection notices. + Create a collection. - Finds collection-level notices (errors and warnings) that are generated when - documents are ingested. + Create a new collection in the specified project. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. + :param str name: The name of the collection. + :param str description: (optional) A description of the collection. + :param str language: (optional) The language of the collection. For a list + of supported languages, see the [product + documentation](/docs/discovery-data?topic=discovery-data-language-support). + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. To get a list of + enrichments that are available for a project, use the [List + enrichments](#listenrichments) method. + If no enrichments are specified when the collection is created, the default + enrichments for the project type are applied. For more information about + project default settings, see the [product + documentation](/docs/discovery-data?topic=discovery-data-project-defaults). + :param CollectionDetailsSmartDocumentUnderstanding + smart_document_understanding: (optional) An object that describes the Smart + Document Understanding model for a collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ if project_id is None: raise ValueError('project_id must be provided') - if collection_id is None: - raise ValueError('collection_id must be provided') + if name is None: + raise ValueError('name must be provided') + if enrichments is not None: + enrichments = [convert_model(x) for x in enrichments] + if smart_document_understanding is not None: + smart_document_understanding = convert_model( + smart_document_understanding) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='query_collection_notices') + operation_id='create_collection') headers.update(sdk_headers) - params = { - 'version': self.version, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'count': count, - 'offset': offset + params = {'version': self.version} + + data = { + 'name': name, + 'description': description, + 'language': language, + 'enrichments': enrichments, + 'smart_document_understanding': smart_document_understanding } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'collection_id'] - path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}/notices'.format( - **path_param_dict) - request = self.prepare_request(method='GET', + url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) + request = self.prepare_request(method='POST', url=url, headers=headers, - params=params) + params=params, + data=data) response = self.send(request, **kwargs) return response - def query_notices(self, - project_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - count: int = None, - offset: int = None, - **kwargs) -> DetailedResponse: + def get_collection(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - Query project notices. + Get collection. - Finds project-level notices (errors and warnings). Currently, project-level - notices are generated by relevancy training. + Get details about the specified collection. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. + :param str collection_id: The ID 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 with `dict` result representing a `QueryNoticesResponse` object + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ if project_id is None: raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='query_notices') + operation_id='get_collection') headers.update(sdk_headers) - params = { - 'version': self.version, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'count': count, - 'offset': offset - } + params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/notices'.format(**path_param_dict) + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -685,94 +533,111 @@ def query_notices(self, response = self.send(request, **kwargs) return response - def list_fields(self, - project_id: str, - *, - collection_ids: List[str] = None, - **kwargs) -> DetailedResponse: + def update_collection(self, + project_id: str, + collection_id: str, + *, + name: str = None, + description: str = None, + enrichments: List['CollectionEnrichment'] = None, + **kwargs) -> DetailedResponse: """ - List fields. + Update a collection. - Gets a list of the unique fields (and their types) stored in the the specified - collections. + Updates the specified collection's name, description, and enrichments. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param List[str] collection_ids: (optional) Comma separated list of the - collection IDs. If this parameter is not specified, all collections in the - project are used. + :param str collection_id: The ID of the collection. + :param str name: (optional) The new name of the collection. + :param str description: (optional) The new description of the collection. + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListFieldsResponse` object + :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ if project_id is None: raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + if enrichments is not None: + enrichments = [convert_model(x) for x in enrichments] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_fields') + operation_id='update_collection') headers.update(sdk_headers) - params = { - 'version': self.version, - 'collection_ids': convert_list(collection_ids) + params = {'version': self.version} + + data = { + 'name': name, + 'description': description, + 'enrichments': enrichments } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/fields'.format(**path_param_dict) - request = self.prepare_request(method='GET', + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', url=url, headers=headers, - params=params) + params=params, + data=data) response = self.send(request, **kwargs) return response - ######################### - # Component settings - ######################### - - def get_component_settings(self, project_id: str, - **kwargs) -> DetailedResponse: + def delete_collection(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - List component settings. + Delete a collection. - Returns default configuration settings for components. + Deletes the specified collection from the project. All documents stored in the + specified collection and not shared is also deleted. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param str collection_id: The ID 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 with `dict` result representing a `ComponentSettingsResponse` object + :rtype: DetailedResponse """ if project_id is None: raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_component_settings') + operation_id='delete_collection') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/component_settings'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', + request = self.prepare_request(method='DELETE', url=url, headers=headers, params=params) @@ -784,7 +649,107 @@ def get_component_settings(self, project_id: str, # Documents ######################### - def add_document(self, + def list_documents(self, + project_id: str, + collection_id: str, + *, + count: int = None, + status: str = None, + has_notices: bool = None, + is_parent: bool = None, + parent_document_id: str = None, + sha256: str = None, + **kwargs) -> DetailedResponse: + """ + List documents. + + Lists the documents in the specified collection. The list includes only the + document ID of each document and returns information for up to 10,000 documents. + **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and + later installed instances and from Plus and Enterprise plan IBM Cloud-managed + instances. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str collection_id: The ID of the collection. + :param int count: (optional) The maximum number of documents to return. Up + to 1,000 documents are returned by default. The maximum number allowed is + 10,000. + :param str status: (optional) Filters the documents to include only + documents with the specified ingestion status. The options include: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because + of an error. + * `pending`: The document is uploaded, but the ingestion process is not + started. + * `processing`: Ingestion is in progress. + You can specify one status value or add a comma-separated list of more than + one status value. For example, `available,failed`. + :param bool has_notices: (optional) If set to `true`, only documents that + have notices, meaning documents for which warnings or errors were generated + during the ingestion, are returned. If set to `false`, only documents that + don't have notices are returned. If unspecified, no filter based on notices + is applied. + Notice details are not available in the result, but you can use the [Query + collection notices](#querycollectionnotices) method to find details by + adding the parameter `query=notices.document_id:{document-id}`. + :param bool is_parent: (optional) If set to `true`, only parent documents, + meaning documents that were split during the ingestion process and resulted + in two or more child documents, are returned. If set to `false`, only child + documents are returned. If unspecified, no filter based on the parent or + child relationship is applied. + CSV files, for example, are split into separate documents per line and JSON + files are split into separate documents per object. + :param str parent_document_id: (optional) Filters the documents to include + only child documents that were generated when the specified parent document + was processed. + :param str sha256: (optional) Filters the documents to include only + documents with the specified SHA-256 hash. Format the hash as a hexadecimal + string. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ListDocumentsResponse` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_documents') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'count': count, + 'status': status, + 'has_notices': has_notices, + 'is_parent': is_parent, + 'parent_document_id': parent_document_id, + 'sha256': sha256 + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/documents'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def add_document(self, project_id: str, collection_id: str, *, @@ -799,42 +764,48 @@ def add_document(self, Add a document to a collection with optional metadata. Returns immediately after the system has accepted the document for processing. - * The user must provide document content, metadata, or both. If the request is - missing both document content and metadata, it is rejected. + This operation works with a file upload collection. It cannot be used to modify a + collection that crawls an external data source. + * For a list of supported file types, see the [product + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + * You must provide document content, metadata, or both. If the request is missing + both document content and metadata, it is rejected. * You can set the **Content-Type** parameter on the **file** part to indicate the media type of the document. If the **Content-Type** parameter is missing or is one of the generic media types (for example, `application/octet-stream`), then the service attempts to automatically detect the document's media type. - * The following field names are reserved and are filtered out if present after - normalization: `id`, `score`, `highlight`, and any field with the prefix of: `_`, - `+`, or `-` - * Fields with empty name values after normalization are filtered out before - indexing. - * Fields that contain the following characters after normalization are filtered - out before indexing: `#` and `,` - If the document is uploaded to a collection that shares its data with another + * If the document is uploaded to a collection that shares its data with another collection, the **X-Watson-Discovery-Force** header must be set to `true`. - **Note:** You can assign an ID to a document that you add by appending the ID to - the endpoint + * In curl requests only, you can assign an ID to a document that you add by + appending the ID to the endpoint (`/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}`). If a document already exists with the specified ID, it is replaced. - **Note:** This operation works with a file upload collection. It cannot be used to - modify a collection that crawls an external data source. + For more information about how certain file types and field names are handled when + a file is added to a collection, see the [product + documentation](/docs/discovery-data?topic=discovery-data-index-overview#field-name-limits). :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) The content of the document to ingest. For - maximum supported file size limits, see [the + :param BinaryIO file: (optional) When adding a document, the content of the + document to ingest. For maximum supported file size limits, see [the documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + When analyzing a document, the content of the document to analyze but not + ingest. Only the `application/json` content type is supported currently. + For maximum supported file size limits, see [the product + documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. - Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. + :param str metadata: (optional) Add information about the file that you + want to include in the response. + The maximum supported metadata file size is 1 MB. Metadata parts larger + than 1 MB are rejected. + Example: + ``` + { + "filename": "favorites2.json", + "file_type": "json" + }. :param bool x_watson_discovery_force: (optional) When `true`, the uploaded document is added to the collection even if the data for that collection is shared with other collections. @@ -868,6 +839,7 @@ def add_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id', 'collection_id'] @@ -884,6 +856,59 @@ def add_document(self, response = self.send(request, **kwargs) return response + def get_document(self, project_id: str, collection_id: str, + document_id: str, **kwargs) -> DetailedResponse: + """ + Get document details. + + Get details about a specific document, whether the document is added by uploading + a file or by crawling an external data source. + **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and + later installed instances and from Plus and Enterprise plan IBM Cloud-managed + instances. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str collection_id: The ID of the collection. + :param str document_id: The ID of the document. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentDetails` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + if document_id is None: + raise ValueError('document_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id', 'document_id'] + path_param_values = self.encode_path_vars(project_id, collection_id, + document_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + def update_document(self, project_id: str, collection_id: str, @@ -898,33 +923,42 @@ def update_document(self, """ Update a document. - Replace an existing document or add a document with a specified **document_id**. + Replace an existing document or add a document with a specified document ID. Starts ingesting a document with optional metadata. + This operation works with a file upload collection. It cannot be used to modify a + collection that crawls an external data source. If the document is uploaded to a collection that shares its data with another collection, the **X-Watson-Discovery-Force** header must be set to `true`. - **Note:** When uploading a new document with this method it automatically replaces - any document stored with the same **document_id** if it exists. - **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that connects to an external - source such as Microsoft SharePoint. - **Note:** If an uploaded document is segmented, all segments are overwritten, even - if the updated version of the document has fewer segments. + **Notes:** + * Uploading a new document with this method automatically replaces any existing + document stored with the same document ID. + * If an uploaded document is split into child documents during ingestion, all + existing child documents are overwritten, even if the updated version of the + document has fewer child documents. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param BinaryIO file: (optional) The content of the document to ingest. For - maximum supported file size limits, see [the + :param BinaryIO file: (optional) When adding a document, the content of the + document to ingest. For maximum supported file size limits, see [the documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + When analyzing a document, the content of the document to analyze but not + ingest. Only the `application/json` content type is supported currently. + For maximum supported file size limits, see [the product + documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. - Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. + :param str metadata: (optional) Add information about the file that you + want to include in the response. + The maximum supported metadata file size is 1 MB. Metadata parts larger + than 1 MB are rejected. + Example: + ``` + { + "filename": "favorites2.json", + "file_type": "json" + }. :param bool x_watson_discovery_force: (optional) When `true`, the uploaded document is added to the collection even if the data for that collection is shared with other collections. @@ -960,6 +994,7 @@ def update_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id', 'collection_id', 'document_id'] @@ -1024,6 +1059,7 @@ def delete_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id', 'collection_id', 'document_id'] @@ -1041,83 +1077,223 @@ def delete_document(self, return response ######################### - # Training data + # Queries ######################### - def list_training_queries(self, project_id: str, - **kwargs) -> DetailedResponse: + def query(self, + project_id: str, + *, + collection_ids: List[str] = None, + filter: str = None, + query: str = None, + natural_language_query: str = None, + aggregation: str = None, + count: int = None, + return_: List[str] = None, + offset: int = None, + sort: str = None, + highlight: bool = None, + spelling_suggestions: bool = None, + table_results: 'QueryLargeTableResults' = None, + suggested_refinements: 'QueryLargeSuggestedRefinements' = None, + passages: 'QueryLargePassages' = None, + similar: 'QueryLargeSimilar' = None, + **kwargs) -> DetailedResponse: """ - List training queries. + Query a project. - List the training queries for the specified project. + Search your data by submitting queries that are written in natural language or + formatted in the Discovery Query Language. For more information, see the + [Discovery + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-concepts). + The default query parameters differ by project type. For more information about + the project default settings, see the [Discovery + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-defaults). + See [the Projects API documentation](#create-project) for details about how to set + custom default query settings. + The length of the UTF-8 encoding of the POST body cannot exceed 10,000 bytes, + which is roughly equivalent to 10,000 characters in English. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param List[str] collection_ids: (optional) A comma-separated list of + collection IDs to be queried against. + :param str filter: (optional) Searches for documents that match the + Discovery Query Language criteria that is specified as input. Filter calls + are cached and are faster than query calls because the results are not + ordered by relevance. When used with the **aggregation**, **query**, or + **natural_language_query** parameters, the **filter** parameter runs first. + This parameter is useful for limiting results to those that contain + specific metadata values. + :param str query: (optional) A query search that is written in the + Discovery Query Language and returns all matching documents in your data + set with full enrichments and full text, and with the most relevant + documents listed first. Use a query search when you want to find the most + relevant search results. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by using training data and natural language + understanding. + :param str aggregation: (optional) An aggregation search that returns an + exact answer by combining query search with filters. Useful for + applications to build lists, tables, and time series. For more information + about the supported types of aggregations, see the [Discovery + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-aggregations). + :param int count: (optional) Number of results to return. + :param List[str] return_: (optional) A list of the fields in the document + hierarchy to return. You can specify both root-level (`text`) and nested + (`extracted_metadata.filename`) fields. If this parameter is an empty list, + then all fields are returned. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. + :param str sort: (optional) A comma-separated list of fields in the + document to sort on. You can optionally specify a sort direction by + prefixing the field with `-` for descending or `+` for ascending. Ascending + is the default sort direction if no prefix is specified. + :param bool highlight: (optional) When `true`, a highlight field is + returned for each result that contains fields that match the query. The + matching query terms are emphasized with surrounding `` tags. This + parameter is ignored if **passages.enabled** and **passages.per_document** + are `true`, in which case passages are returned for each document instead + of highlights. + :param bool spelling_suggestions: (optional) When `true` and the + **natural_language_query** parameter is used, the + **natural_language_query** parameter is spell checked. The most likely + correction is returned in the **suggested_query** field of the response (if + one exists). + :param QueryLargeTableResults table_results: (optional) Configuration for + table retrieval. + :param QueryLargeSuggestedRefinements suggested_refinements: (optional) + Configuration for suggested refinements. + **Note**: The **suggested_refinements** parameter that identified dynamic + facets from the data is deprecated. + :param QueryLargePassages passages: (optional) Configuration for passage + retrieval. + :param QueryLargeSimilar similar: (optional) Finds results from documents + that are similar to documents of interest. Use this parameter to add a + *More like these* function to your search. You can include this parameter + with or without a **query**, **filter** or **natural_language_query** + parameter. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuerySet` object + :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object """ if project_id is None: raise ValueError('project_id must be provided') + if table_results is not None: + table_results = convert_model(table_results) + if suggested_refinements is not None: + suggested_refinements = convert_model(suggested_refinements) + if passages is not None: + passages = convert_model(passages) + if similar is not None: + similar = convert_model(similar) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_training_queries') + operation_id='query') headers.update(sdk_headers) params = {'version': self.version} + data = { + 'collection_ids': collection_ids, + 'filter': filter, + 'query': query, + 'natural_language_query': natural_language_query, + 'aggregation': aggregation, + 'count': count, + 'return': return_, + 'offset': offset, + 'sort': sort, + 'highlight': highlight, + 'spelling_suggestions': spelling_suggestions, + 'table_results': table_results, + 'suggested_refinements': suggested_refinements, + 'passages': passages, + 'similar': similar + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries'.format( - **path_param_dict) - request = self.prepare_request(method='GET', + url = '/v2/projects/{project_id}/query'.format(**path_param_dict) + request = self.prepare_request(method='POST', url=url, headers=headers, - params=params) + params=params, + data=data) response = self.send(request, **kwargs) return response - def delete_training_queries(self, project_id: str, - **kwargs) -> DetailedResponse: + def get_autocompletion(self, + project_id: str, + prefix: str, + *, + collection_ids: List[str] = None, + field: str = None, + count: int = None, + **kwargs) -> DetailedResponse: """ - Delete training queries. + Get Autocomplete Suggestions. - Removes all training queries for the specified project. + Returns completion query suggestions for the specified prefix. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param str prefix: The prefix to use for autocompletion. For example, the + prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. + :param List[str] collection_ids: (optional) Comma separated list of the + collection IDs. If this parameter is not specified, all collections in the + project are used. + :param str field: (optional) The field in the result documents that + autocompletion suggestions are identified from. + :param int count: (optional) The number of autocompletion suggestions to + return. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Completions` object """ if project_id is None: raise ValueError('project_id must be provided') + if prefix is None: + raise ValueError('prefix must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_training_queries') + operation_id='get_autocompletion') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + 'prefix': prefix, + 'collection_ids': convert_list(collection_ids), + 'field': field, + 'count': count + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' path_param_keys = ['project_id'] path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries'.format( + url = '/v2/projects/{project_id}/autocompletion'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', + request = self.prepare_request(method='GET', url=url, headers=headers, params=params) @@ -1125,110 +1301,157 @@ def delete_training_queries(self, project_id: str, response = self.send(request, **kwargs) return response - def create_training_query(self, - project_id: str, - natural_language_query: str, - examples: List['TrainingExample'], - *, - filter: str = None, - **kwargs) -> DetailedResponse: + def query_collection_notices(self, + project_id: str, + collection_id: str, + *, + filter: str = None, + query: str = None, + natural_language_query: str = None, + count: int = None, + offset: int = None, + **kwargs) -> DetailedResponse: """ - Create training query. + Query collection notices. - Add a query to the training data for this project. The query can contain a filter - and natural language query. + Finds collection-level notices (errors and warnings) that are generated when + documents are ingested. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str natural_language_query: The natural text query for the training - query. - :param List[TrainingExample] examples: Array of training examples. - :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object - """ - - if project_id is None: + :param str collection_id: The ID of the collection. + :param str filter: (optional) Searches for documents that match the + Discovery Query Language criteria that is specified as input. Filter calls + are cached and are faster than query calls because the results are not + ordered by relevance. When used with the `aggregation`, `query`, or + `natural_language_query` parameters, the `filter` parameter runs first. + This parameter is useful for limiting results to those that contain + specific metadata values. + :param str query: (optional) A query search that is written in the + Discovery Query Language and returns all matching documents in your data + set with full enrichments and full text, and with the most relevant + documents listed first. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by using training data and natural language + understanding. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is + **10,000**. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. The maximum for + the **count** and **offset** values together in any one query is **10000**. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object + """ + + if project_id is None: raise ValueError('project_id must be provided') - if natural_language_query is None: - raise ValueError('natural_language_query must be provided') - if examples is None: - raise ValueError('examples must be provided') - examples = [convert_model(x) for x in examples] + if collection_id is None: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='create_training_query') + operation_id='query_collection_notices') headers.update(sdk_headers) - params = {'version': self.version} - - data = { + params = { + 'version': self.version, + 'filter': filter, + 'query': query, 'natural_language_query': natural_language_query, - 'examples': examples, - 'filter': filter + 'count': count, + 'offset': offset } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/notices'.format( **path_param_dict) - request = self.prepare_request(method='POST', + request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - data=data) + params=params) response = self.send(request, **kwargs) return response - def get_training_query(self, project_id: str, query_id: str, - **kwargs) -> DetailedResponse: + def query_notices(self, + project_id: str, + *, + filter: str = None, + query: str = None, + natural_language_query: str = None, + count: int = None, + offset: int = None, + **kwargs) -> DetailedResponse: """ - Get a training data query. + Query project notices. - Get details for a specific training data query, including the query string and all - examples. + Finds project-level notices (errors and warnings). Currently, project-level + notices are generated by relevancy training. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str query_id: The ID of the query used for training. + :param str filter: (optional) Searches for documents that match the + Discovery Query Language criteria that is specified as input. Filter calls + are cached and are faster than query calls because the results are not + ordered by relevance. When used with the `aggregation`, `query`, or + `natural_language_query` parameters, the `filter` parameter runs first. + This parameter is useful for limiting results to those that contain + specific metadata values. + :param str query: (optional) A query search that is written in the + Discovery Query Language and returns all matching documents in your data + set with full enrichments and full text, and with the most relevant + documents listed first. + :param str natural_language_query: (optional) A natural language query that + returns relevant documents by using training data and natural language + understanding. + :param int count: (optional) Number of results to return. The maximum for + the **count** and **offset** values together in any one query is + **10,000**. + :param int offset: (optional) The number of query results to skip at the + beginning. For example, if the total number of results that are returned is + 10 and the offset is 8, it returns the last two results. The maximum for + the **count** and **offset** values together in any one query is **10000**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object + :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ if project_id is None: raise ValueError('project_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_training_query') + operation_id='query_notices') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + 'filter': filter, + 'query': query, + 'natural_language_query': natural_language_query, + 'count': count, + 'offset': offset + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'query_id'] - path_param_values = self.encode_path_vars(project_id, query_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( - **path_param_dict) + url = '/v2/projects/{project_id}/notices'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1237,158 +1460,140 @@ def get_training_query(self, project_id: str, query_id: str, response = self.send(request, **kwargs) return response - def update_training_query(self, - project_id: str, - query_id: str, - natural_language_query: str, - examples: List['TrainingExample'], - *, - filter: str = None, - **kwargs) -> DetailedResponse: + ######################### + # Query modifications + ######################### + + def get_stopword_list(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - Update a training query. + Get a custom stop words list. - Updates an existing training query and it's examples. + Returns the custom stop words list that is used by the collection. For information + about the default stop words lists that are applied to queries, see [the product + documentation](/docs/discovery-data?topic=discovery-data-stopwords). :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str query_id: The ID of the query used for training. - :param str natural_language_query: The natural text query for the training - query. - :param List[TrainingExample] examples: Array of training examples. - :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + :param str collection_id: The ID 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 with `dict` result representing a `TrainingQuery` object + :rtype: DetailedResponse with `dict` result representing a `StopWordList` object """ if project_id is None: raise ValueError('project_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') - if natural_language_query is None: - raise ValueError('natural_language_query must be provided') - if examples is None: - raise ValueError('examples must be provided') - examples = [convert_model(x) for x in examples] + if collection_id is None: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_training_query') + operation_id='get_stopword_list') headers.update(sdk_headers) params = {'version': self.version} - data = { - 'natural_language_query': natural_language_query, - 'examples': examples, - 'filter': filter - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'query_id'] - path_param_values = self.encode_path_vars(project_id, query_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='POST', + request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - data=data) + params=params) response = self.send(request, **kwargs) return response - def delete_training_query(self, project_id: str, query_id: str, - **kwargs) -> DetailedResponse: - """ - Delete a training data query. - - Removes details from a training data query, including the query string and all - examples. + def create_stopword_list(self, + project_id: str, + collection_id: str, + *, + stopwords: List[str] = None, + **kwargs) -> DetailedResponse: + """ + Create a custom stop words list. + + Adds a list of custom stop words. Stop words are words that you want the service + to ignore when they occur in a query because they're not useful in distinguishing + the semantic meaning of the query. The stop words list cannot contain more than 1 + million characters. + A default stop words list is used by all collections. The default list is applied + both at indexing time and at query time. A custom stop words list that you add is + used at query time only. + The custom stop words list replaces the default stop words list. Therefore, if you + want to keep the stop words that were used when the collection was indexed, get + the default stop words list for the language of the collection first and edit it + to create your custom list. For information about the default stop words lists per + language, see [the product + documentation](/docs/discovery-data?topic=discovery-data-stopwords). :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str query_id: The ID of the query used for training. + :param str collection_id: The ID of the collection. + :param List[str] stopwords: (optional) List of stop words. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `StopWordList` object """ if project_id is None: raise ValueError('project_id must be provided') - if query_id is None: - raise ValueError('query_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_training_query') + operation_id='create_stopword_list') headers.update(sdk_headers) params = {'version': self.version} + data = {'stopwords': stopwords} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'query_id'] - path_param_values = self.encode_path_vars(project_id, query_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', + request = self.prepare_request(method='POST', url=url, headers=headers, - params=params) + params=params, + data=data) response = self.send(request, **kwargs) return response - ######################### - # analyze - ######################### - - def analyze_document(self, - project_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - **kwargs) -> DetailedResponse: + def delete_stopword_list(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - Analyze a Document. + Delete a custom stop words list. - Process a document and return it for realtime use. Supports JSON files only. - The document is processed according to the collection's configuration settings but - is not stored in the collection. - **Note:** This method is supported on installed instances of Discovery only. + Deletes a custom stop words list to stop using it in queries against the + collection. After a custom stop words list is deleted, the default stop words list + is used. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) The content of the document to ingest. For - maximum supported file size limits, see [the - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. - Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `AnalyzedDocument` object + :rtype: DetailedResponse """ if project_id is None: @@ -1398,77 +1603,66 @@ def analyze_document(self, headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='analyze_document') + operation_id='delete_stopword_list') headers.update(sdk_headers) params = {'version': self.version} - form_data = [] - if file: - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if metadata: - form_data.append(('metadata', (None, metadata, 'text/plain'))) - if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] path_param_keys = ['project_id', 'collection_id'] path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/collections/{collection_id}/analyze'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='POST', + request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - files=form_data) + params=params) response = self.send(request, **kwargs) return response - ######################### - # enrichments - ######################### - - def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: + def list_expansions(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - List Enrichments. + Get the expansion list. - Lists the enrichments available to this project. The *Part of Speech* and - *Sentiment of Phrases* enrichments might be listed, but are reserved for internal - use only. + Returns the current expansion list for the specified collection. If an expansion + list is not specified, an empty expansions array is returned. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param str collection_id: The ID 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 with `dict` result representing a `Enrichments` object + :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ if project_id is None: raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_enrichments') + operation_id='list_expansions') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) + url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1477,99 +1671,116 @@ def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response - def create_enrichment(self, - project_id: str, - enrichment: 'CreateEnrichment', - *, - file: BinaryIO = None, + def create_expansions(self, project_id: str, collection_id: str, + expansions: List['Expansion'], **kwargs) -> DetailedResponse: """ - Create an enrichment. + Create or update an expansion list. - Create an enrichment for use with the specified project. + Creates or replaces the expansion list for this collection. An expansion list + introduces alternative wording for key terms that are mentioned in your + collection. By identifying synonyms or common misspellings, you expand the scope + of a query beyond exact matches. The maximum number of expanded terms allowed per + collection is 5,000. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param CreateEnrichment enrichment: Information about a specific - enrichment. - :param BinaryIO file: (optional) The enrichment file to upload. + :param str collection_id: The ID of the collection. + :param List[Expansion] expansions: An array of query expansion definitions. + Each object in the **expansions** array represents a term or set of terms + that will be expanded into other terms. Each expansion object can be + configured as `bidirectional` or `unidirectional`. + * **Bidirectional**: Each entry in the `expanded_terms` list expands to + include all expanded terms. For example, a query for `ibm` expands to `ibm + OR international business machines OR big blue`. + * **Unidirectional**: The terms in `input_terms` in the query are replaced + by the terms in `expanded_terms`. For example, a query for the often + misused term `on premise` is converted to `on premises OR on-premises` and + does not contain the original term. If you want an input term to be + included in the query, then repeat the input term in the expanded terms + list. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Enrichment` object + :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ if project_id is None: raise ValueError('project_id must be provided') - if enrichment is None: - raise ValueError('enrichment must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + if expansions is None: + raise ValueError('expansions must be provided') + expansions = [convert_model(x) for x in expansions] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='create_enrichment') + operation_id='create_expansions') headers.update(sdk_headers) params = {'version': self.version} - form_data = [] - form_data.append( - ('enrichment', (None, json.dumps(enrichment), 'application/json'))) - if file: - form_data.append(('file', (None, file, 'application/octet-stream'))) + data = {'expansions': expansions} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) + url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, params=params, - files=form_data) + data=data) response = self.send(request, **kwargs) return response - def get_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> DetailedResponse: + def delete_expansions(self, project_id: str, collection_id: str, + **kwargs) -> DetailedResponse: """ - Get enrichment. + Delete the expansion list. - Get details about a specific enrichment. + Removes the expansion information for this collection. To disable query expansion + for a collection, delete the expansion list. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. + :param str collection_id: The ID 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 with `dict` result representing a `Enrichment` object + :rtype: DetailedResponse """ if project_id is None: raise ValueError('project_id must be provided') - if enrichment_id is None: - raise ValueError('enrichment_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_enrichment') + operation_id='delete_expansions') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] - path_param_keys = ['project_id', 'enrichment_id'] - path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='GET', + request = self.prepare_request(method='DELETE', url=url, headers=headers, params=params) @@ -1577,102 +1788,91 @@ def get_enrichment(self, project_id: str, enrichment_id: str, response = self.send(request, **kwargs) return response - def update_enrichment(self, - project_id: str, - enrichment_id: str, - name: str, - *, - description: str = None, - **kwargs) -> DetailedResponse: + ######################### + # Component settings + ######################### + + def get_component_settings(self, project_id: str, + **kwargs) -> DetailedResponse: """ - Update an enrichment. + List component settings. - Updates an existing enrichment's name and description. + Returns default configuration settings for components. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. - :param str name: A new name for the enrichment. - :param str description: (optional) A new description for the enrichment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Enrichment` object + :rtype: DetailedResponse with `dict` result representing a `ComponentSettingsResponse` object """ if project_id is None: raise ValueError('project_id must be provided') - if enrichment_id is None: - raise ValueError('enrichment_id must be provided') - if name is None: - raise ValueError('name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_enrichment') + operation_id='get_component_settings') headers.update(sdk_headers) params = {'version': self.version} - data = {'name': name, 'description': description} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'enrichment_id'] - path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + url = '/v2/projects/{project_id}/component_settings'.format( **path_param_dict) - request = self.prepare_request(method='POST', + request = self.prepare_request(method='GET', url=url, headers=headers, - params=params, - data=data) + params=params) response = self.send(request, **kwargs) return response - def delete_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> DetailedResponse: + ######################### + # Training data + ######################### + + def list_training_queries(self, project_id: str, + **kwargs) -> DetailedResponse: """ - Delete an enrichment. + List training queries. - Deletes an existing enrichment from the specified project. - **Note:** Only enrichments that have been manually created can be deleted. + List the training queries for the specified project. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `TrainingQuerySet` object """ if project_id is None: raise ValueError('project_id must be provided') - if enrichment_id is None: - raise ValueError('enrichment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_enrichment') + operation_id='list_training_queries') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - path_param_keys = ['project_id', 'enrichment_id'] - path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + url = '/v2/projects/{project_id}/training_data/queries'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', + request = self.prepare_request(method='GET', url=url, headers=headers, params=params) @@ -1680,35 +1880,40 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, response = self.send(request, **kwargs) return response - ######################### - # projects - ######################### - - def list_projects(self, **kwargs) -> DetailedResponse: + def delete_training_queries(self, project_id: str, + **kwargs) -> DetailedResponse: """ - List projects. + Delete training queries. - Lists existing projects for this instance. + Removes all training queries for the specified project. + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListProjectsResponse` object + :rtype: DetailedResponse """ + if project_id is None: + raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_projects') + operation_id='delete_training_queries') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' + del kwargs['headers'] - url = '/v2/projects' - request = self.prepare_request(method='GET', + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries'.format( + **path_param_dict) + request = self.prepare_request(method='DELETE', url=url, headers=headers, params=params) @@ -1716,48 +1921,50 @@ def list_projects(self, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response - def create_project(self, - name: str, - type: str, - *, - default_query_parameters: 'DefaultQueryParams' = None, - **kwargs) -> DetailedResponse: + def create_training_query(self, + project_id: str, + natural_language_query: str, + examples: List['TrainingExample'], + *, + filter: str = None, + **kwargs) -> DetailedResponse: """ - Create a Project. + Create training query. - Create a new project for this instance. + Add a query to the training data for this project. The query can contain a filter + and natural language query. - :param str name: The human readable name of this project. - :param str type: The type of project. - The `content_intelligence` type is a *Document Retrieval for Contracts* - project and the `other` type is a *Custom* project. - The `content_mining` and `content_intelligence` types are available with - Premium plan managed deployments and installed deployments only. - :param DefaultQueryParams default_query_parameters: (optional) Default - query parameters for this project. + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str natural_language_query: The natural text query that is used as + the training query. + :param List[TrainingExample] examples: Array of training examples. + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if name is None: - raise ValueError('name must be provided') - if type is None: - raise ValueError('type must be provided') - if default_query_parameters is not None: - default_query_parameters = convert_model(default_query_parameters) + if project_id is None: + raise ValueError('project_id must be provided') + if natural_language_query is None: + raise ValueError('natural_language_query must be provided') + if examples is None: + raise ValueError('examples must be provided') + examples = [convert_model(x) for x in examples] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='create_project') + operation_id='create_training_query') headers.update(sdk_headers) params = {'version': self.version} data = { - 'name': name, - 'type': type, - 'default_query_parameters': default_query_parameters + 'natural_language_query': natural_language_query, + 'examples': examples, + 'filter': filter } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1765,9 +1972,14 @@ def create_project(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - url = '/v2/projects' + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/training_data/queries'.format( + **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers, @@ -1777,37 +1989,44 @@ def create_project(self, response = self.send(request, **kwargs) return response - def get_project(self, project_id: str, **kwargs) -> DetailedResponse: + def get_training_query(self, project_id: str, query_id: str, + **kwargs) -> DetailedResponse: """ - Get project. + Get a training data query. - Get details on the specified project. + Get details for a specific training data query, including the query string and all + examples. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ if project_id is None: raise ValueError('project_id must be provided') + if query_id is None: + raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_project') + operation_id='get_training_query') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}'.format(**path_param_dict) + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers, @@ -1816,48 +2035,69 @@ def get_project(self, project_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response - def update_project(self, - project_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def update_training_query(self, + project_id: str, + query_id: str, + natural_language_query: str, + examples: List['TrainingExample'], + *, + filter: str = None, + **kwargs) -> DetailedResponse: """ - Update a project. + Update a training query. - Update the specified project's name. + Updates an existing training query and it's examples. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. - :param str name: (optional) The new name to give this project. + :param str query_id: The ID of the query used for training. + :param str natural_language_query: The natural text query that is used as + the training query. + :param List[TrainingExample] examples: Array of training examples. + :param str filter: (optional) The filter used on the collection before the + **natural_language_query** is applied. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object + :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ if project_id is None: raise ValueError('project_id must be provided') + if query_id is None: + raise ValueError('query_id must be provided') + if natural_language_query is None: + raise ValueError('natural_language_query must be provided') + if examples is None: + raise ValueError('examples must be provided') + examples = [convert_model(x) for x in examples] headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_project') + operation_id='update_training_query') headers.update(sdk_headers) params = {'version': self.version} - data = {'name': name} + data = { + 'natural_language_query': natural_language_query, + 'examples': examples, + 'filter': filter + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', url=url, headers=headers, params=params, @@ -1866,16 +2106,17 @@ def update_project(self, response = self.send(request, **kwargs) return response - def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: + def delete_training_query(self, project_id: str, query_id: str, + **kwargs) -> DetailedResponse: """ - Delete a project. + Delete a training data query. - Deletes the specified project. - **Important:** Deleting a project deletes everything that is part of the specified - project, including all collections. + Removes details from a training data query, including the query string and all + examples. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. + :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1883,21 +2124,25 @@ def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: if project_id is None: raise ValueError('project_id must be provided') + if query_id is None: + raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_project') + operation_id='delete_training_query') headers.update(sdk_headers) params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] - path_param_keys = ['project_id'] - path_param_values = self.encode_path_vars(project_id) + path_param_keys = ['project_id', 'query_id'] + path_param_values = self.encode_path_vars(project_id, query_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/projects/{project_id}'.format(**path_param_dict) + url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( + **path_param_dict) request = self.prepare_request(method='DELETE', url=url, headers=headers, @@ -1907,43 +2152,44 @@ def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: return response ######################### - # userData + # Enrichments ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: """ - Delete labeled data. + List enrichments. - Deletes all data associated with a specified customer ID. The method has no effect - if no data is associated with the customer ID. - 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/discovery-data?topic=discovery-data-information-security#information-security). - **Note:** This method is only supported on IBM Cloud instances of Discovery. + Lists the enrichments available to this project. The *Part of Speech* and + *Sentiment of Phrases* enrichments might be listed, but are reserved for internal + use only. - :param str customer_id: The customer ID for which all data is to be - deleted. + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse + :rtype: DetailedResponse with `dict` result representing a `Enrichments` object """ - if customer_id is None: - raise ValueError('customer_id must be provided') + if project_id is None: + raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_user_data') + operation_id='list_enrichments') headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = {'version': self.version} if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - url = '/v2/user_data' - request = self.prepare_request(method='DELETE', + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) + request = self.prepare_request(method='GET', url=url, headers=headers, params=params) @@ -1951,262 +2197,2157 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response + def create_enrichment(self, + project_id: str, + enrichment: 'CreateEnrichment', + *, + file: BinaryIO = None, + **kwargs) -> DetailedResponse: + """ + Create an enrichment. -class AddDocumentEnums: - """ - Enums for add_document parameters. - """ + Create an enrichment for use with the specified project. To apply the enrichment + to a collection in the project, use the [Collections + API](/apidocs/discovery-data#createcollection). - class FileContentType(str, Enum): - """ - The content type of file. + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param CreateEnrichment enrichment: Information about a specific + enrichment. + :param BinaryIO file: (optional) The enrichment file to upload. Expected + file types per enrichment are as follows: + * CSV for `dictionary` + * PEAR for `uima_annotator` and `rule_based` (Explorer) + * ZIP for `watson_knowledge_studio_model` and `rule_based` (Studio Advanced + Rule Editor). + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment is None: + raise ValueError('enrichment must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_enrichment') + headers.update(sdk_headers) -class UpdateDocumentEnums: - """ - Enums for update_document parameters. - """ + params = {'version': self.version} - class FileContentType(str, Enum): - """ - The content type of file. - """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + form_data = [] + form_data.append( + ('enrichment', (None, json.dumps(enrichment), 'application/json'))) + if file: + form_data.append(('file', (None, file, 'application/octet-stream'))) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -class AnalyzeDocumentEnums: - """ - Enums for analyze_document parameters. - """ + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) - class FileContentType(str, Enum): + response = self.send(request, **kwargs) + return response + + def get_enrichment(self, project_id: str, enrichment_id: str, + **kwargs) -> DetailedResponse: """ - The content type of file. + Get enrichment. + + Get details about a specific enrichment. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str enrichment_id: The ID of the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment_id is None: + raise ValueError('enrichment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_enrichment') + headers.update(sdk_headers) -############################################################################## -# Models -############################################################################## + params = {'version': self.version} + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -class AnalyzedDocument(): - """ - An object that contains the converted document and any identified enrichments. + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - :attr List[Notice] notices: (optional) Array of document results that match the - query. - :attr AnalyzedResult result: (optional) Result of the document analysis. - """ + response = self.send(request, **kwargs) + return response - def __init__(self, - *, - notices: List['Notice'] = None, - result: 'AnalyzedResult' = None) -> None: + def update_enrichment(self, + project_id: str, + enrichment_id: str, + name: str, + *, + description: str = None, + **kwargs) -> DetailedResponse: """ - Initialize a AnalyzedDocument object. + Update an enrichment. - :param List[Notice] notices: (optional) Array of document results that - match the query. - :param AnalyzedResult result: (optional) Result of the document analysis. - """ - self.notices = notices - self.result = result + Updates an existing enrichment's name and description. - @classmethod - def from_dict(cls, _dict: Dict) -> 'AnalyzedDocument': - """Initialize a AnalyzedDocument object from a json dictionary.""" - args = {} - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') - ] - if 'result' in _dict: - args['result'] = AnalyzedResult.from_dict(_dict.get('result')) - return cls(**args) + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str enrichment_id: The ID of the enrichment. + :param str name: A new name for the enrichment. + :param str description: (optional) A new description for the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Enrichment` object + """ - @classmethod - def _from_dict(cls, _dict): - """Initialize a AnalyzedDocument object from a json dictionary.""" - return cls.from_dict(_dict) + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment_id is None: + raise ValueError('enrichment_id must be provided') + if name is None: + raise ValueError('name must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_enrichment') + headers.update(sdk_headers) - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] - if hasattr(self, 'result') and self.result is not None: - _dict['result'] = self.result.to_dict() - return _dict + params = {'version': self.version} - def _to_dict(self): - """Return a json dictionary representing this model.""" + data = {'name': name, 'description': description} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def delete_enrichment(self, project_id: str, enrichment_id: str, + **kwargs) -> DetailedResponse: + """ + Delete an enrichment. + + Deletes an existing enrichment from the specified project. + **Note:** Only enrichments that have been manually created can be deleted. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str enrichment_id: The ID of the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if enrichment_id is None: + raise ValueError('enrichment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_enrichment') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + path_param_keys = ['project_id', 'enrichment_id'] + path_param_values = self.encode_path_vars(project_id, enrichment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( + **path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + ######################### + # Document classifiers + ######################### + + def list_document_classifiers(self, project_id: str, + **kwargs) -> DetailedResponse: + """ + List document classifiers. + + Get a list of the document classifiers in a project. Returns only the name and + classifier ID of each document classifier. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifiers` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_document_classifiers') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def create_document_classifier(self, + project_id: str, + training_data: BinaryIO, + classifier: 'CreateDocumentClassifier', + *, + test_data: BinaryIO = None, + **kwargs) -> DetailedResponse: + """ + Create a document classifier. + + Create a document classifier. You can use the API to create a document classifier + in any project type. After you create a document classifier, you can use the + Enrichments API to create a classifier enrichment, and then the Collections API to + apply the enrichment to a collection in the project. + **Note:** This method is supported on installed instances (IBM Cloud Pak for Data) + or IBM Cloud-managed Premium or Enterprise plan instances. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param BinaryIO training_data: The training data CSV file to upload. The + CSV file must have headers. The file must include a field that contains the + text you want to classify and a field that contains the classification + labels that you want to use to classify your data. If you want to specify + multiple values in a single field, use a semicolon as the value separator. + For a sample file, see [the product + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-cm-doc-classifier). + :param CreateDocumentClassifier classifier: An object that manages the + settings and data that is required to train a document classification + model. + :param BinaryIO test_data: (optional) The CSV with test data to upload. The + column values in the test file must be the same as the column values in the + training data file. If no test data is provided, the training data is split + into two separate groups of training and test data. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if training_data is None: + raise ValueError('training_data must be provided') + if classifier is None: + raise ValueError('classifier must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_document_classifier') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + form_data.append(('training_data', (None, training_data, 'text/csv'))) + form_data.append( + ('classifier', (None, json.dumps(classifier), 'application/json'))) + if test_data: + form_data.append(('test_data', (None, test_data, 'text/csv'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id'] + path_param_values = self.encode_path_vars(project_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request, **kwargs) + return response + + def get_document_classifier(self, project_id: str, classifier_id: str, + **kwargs) -> DetailedResponse: + """ + Get a document classifier. + + Get details about a specific document classifier. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if classifier_id is None: + raise ValueError('classifier_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document_classifier') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def update_document_classifier(self, + project_id: str, + classifier_id: str, + classifier: 'UpdateDocumentClassifier', + *, + training_data: BinaryIO = None, + test_data: BinaryIO = None, + **kwargs) -> DetailedResponse: + """ + Update a document classifier. + + Update the document classifier name or description, update the training data, or + add or update the test data. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param UpdateDocumentClassifier classifier: An object that contains a new + name or description for a document classifier, updated training data, or + new or updated test data. + :param BinaryIO training_data: (optional) The training data CSV file to + upload. The CSV file must have headers. The file must include a field that + contains the text you want to classify and a field that contains the + classification labels that you want to use to classify your data. If you + want to specify multiple values in a single column, use a semicolon as the + value separator. For a sample file, see [the product + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-cm-doc-classifier). + :param BinaryIO test_data: (optional) The CSV with test data to upload. The + column values in the test file must be the same as the column values in the + training data file. If no test data is provided, the training data is split + into two separate groups of training and test data. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if classifier_id is None: + raise ValueError('classifier_id must be provided') + if classifier is None: + raise ValueError('classifier must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document_classifier') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + form_data.append( + ('classifier', (None, json.dumps(classifier), 'application/json'))) + if training_data: + form_data.append( + ('training_data', (None, training_data, 'text/csv'))) + if test_data: + form_data.append(('test_data', (None, test_data, 'text/csv'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request, **kwargs) + return response + + def delete_document_classifier(self, project_id: str, classifier_id: str, + **kwargs) -> DetailedResponse: + """ + Delete a document classifier. + + Deletes an existing document classifier from the specified project. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if classifier_id is None: + raise ValueError('classifier_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document_classifier') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( + **path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + ######################### + # Document classifier models + ######################### + + def list_document_classifier_models(self, project_id: str, + classifier_id: str, + **kwargs) -> DetailedResponse: + """ + List document classifier models. + + Get a list of the document classifier models in a project. Returns only the name + and model ID of each document classifier model. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModels` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if classifier_id is None: + raise ValueError('classifier_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_document_classifier_models') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def create_document_classifier_model( + self, + project_id: str, + classifier_id: str, + name: str, + *, + description: str = None, + learning_rate: float = None, + l1_regularization_strengths: List[float] = None, + l2_regularization_strengths: List[float] = None, + training_max_steps: int = None, + improvement_ratio: float = None, + **kwargs) -> DetailedResponse: + """ + Create a document classifier model. + + Create a document classifier model by training a model that uses the data and + classifier settings defined in the specified document classifier. + **Note:** This method is supported on installed intances (IBM Cloud Pak for Data) + or IBM Cloud-managed Premium or Enterprise plan instances. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param str name: The name of the document classifier model. + :param str description: (optional) A description of the document classifier + model. + :param float learning_rate: (optional) A tuning parameter in an + optimization algorithm that determines the step size at each iteration of + the training process. It influences how much of any newly acquired + information overrides the existing information, and therefore is said to + represent the speed at which a machine learning model learns. The default + value is `0.1`. + :param List[float] l1_regularization_strengths: (optional) Avoids + overfitting by shrinking the coefficient of less important features to + zero, which removes some features altogether. You can specify many values + for hyper-parameter optimization. The default value is `[0.000001]`. + :param List[float] l2_regularization_strengths: (optional) A method you can + apply to avoid overfitting your model on the training data. You can specify + many values for hyper-parameter optimization. The default value is + `[0.000001]`. + :param int training_max_steps: (optional) Maximum number of training steps + to complete. This setting is useful if you need the training process to + finish in a specific time frame to fit into an automated process. The + default value is ten million. + :param float improvement_ratio: (optional) Stops the training run early if + the improvement ratio is not met by the time the process reaches a certain + point. The default value is `0.00001`. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if classifier_id is None: + raise ValueError('classifier_id must be provided') + if name is None: + raise ValueError('name must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_document_classifier_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = { + 'name': name, + 'description': description, + 'learning_rate': learning_rate, + 'l1_regularization_strengths': l1_regularization_strengths, + 'l2_regularization_strengths': l2_regularization_strengths, + 'training_max_steps': training_max_steps, + 'improvement_ratio': improvement_ratio + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def get_document_classifier_model(self, project_id: str, classifier_id: str, + model_id: str, + **kwargs) -> DetailedResponse: + """ + Get a document classifier model. + + Get details about a specific document classifier model. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param str model_id: The ID of the classifier model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if classifier_id is None: + raise ValueError('classifier_id must be provided') + if model_id is None: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document_classifier_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id', 'model_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id, + model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def update_document_classifier_model(self, + project_id: str, + classifier_id: str, + model_id: str, + *, + name: str = None, + description: str = None, + **kwargs) -> DetailedResponse: + """ + Update a document classifier model. + + Update the document classifier model name or description. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param str model_id: The ID of the classifier model. + :param str name: (optional) A new name for the enrichment. + :param str description: (optional) A new description for the enrichment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if classifier_id is None: + raise ValueError('classifier_id must be provided') + if model_id is None: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document_classifier_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + data = {'name': name, 'description': description} + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'classifier_id', 'model_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id, + model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def delete_document_classifier_model(self, project_id: str, + classifier_id: str, model_id: str, + **kwargs) -> DetailedResponse: + """ + Delete a document classifier model. + + Deletes an existing document classifier model from the specified project. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str classifier_id: The ID of the classifier. + :param str model_id: The ID of the classifier model. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if classifier_id is None: + raise ValueError('classifier_id must be provided') + if model_id is None: + raise ValueError('model_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document_classifier_model') + headers.update(sdk_headers) + + params = {'version': self.version} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + path_param_keys = ['project_id', 'classifier_id', 'model_id'] + path_param_values = self.encode_path_vars(project_id, classifier_id, + model_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( + **path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + ######################### + # Analyze + ######################### + + def analyze_document(self, + project_id: str, + collection_id: str, + *, + file: BinaryIO = None, + filename: str = None, + file_content_type: str = None, + metadata: str = None, + **kwargs) -> DetailedResponse: + """ + Analyze a Document. + + Process a document and return it for realtime use. Supports JSON files only. + The file is not stored in the collection, but is processed according to the + collection's configuration settings. To get results, enrichments must be applied + to a field in the collection that also exists in the file that you want to + analyze. For example, to analyze text in a `Quote` field, you must apply + enrichments to the `Quote` field in the collection configuration. Then, when you + analyze the file, the text in the `Quote` field is analyzed and results are + written to a field named `enriched_Quote`. + **Note:** This method is supported with Enterprise plan deployments and installed + deployments only. + + :param str project_id: The ID of the project. This information can be found + from the *Integrate and Deploy* page in Discovery. + :param str collection_id: The ID of the collection. + :param BinaryIO file: (optional) When adding a document, the content of the + document to ingest. For maximum supported file size limits, see [the + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + When analyzing a document, the content of the document to analyze but not + ingest. Only the `application/json` content type is supported currently. + For maximum supported file size limits, see [the product + documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). + :param str filename: (optional) The filename for file. + :param str file_content_type: (optional) The content type of file. + :param str metadata: (optional) Add information about the file that you + want to include in the response. + The maximum supported metadata file size is 1 MB. Metadata parts larger + than 1 MB are rejected. + Example: + ``` + { + "filename": "favorites2.json", + "file_type": "json" + }. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `AnalyzedDocument` object + """ + + if project_id is None: + raise ValueError('project_id must be provided') + if collection_id is None: + raise ValueError('collection_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='analyze_document') + headers.update(sdk_headers) + + params = {'version': self.version} + + form_data = [] + if file: + if not filename and hasattr(file, 'name'): + filename = basename(file.name) + if not filename: + raise ValueError('filename must be provided') + form_data.append(('file', (filename, file, file_content_type or + 'application/octet-stream'))) + if metadata: + form_data.append(('metadata', (None, metadata, 'text/plain'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/analyze'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + files=form_data) + + response = self.send(request, **kwargs) + return response + + ######################### + # User data + ######################### + + def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + """ + Delete labeled data. + + Deletes all data associated with a specified customer ID. The method has no effect + if no data is associated with the customer ID. + 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/discovery-data?topic=discovery-data-information-security#information-security). + **Note:** This method is only supported on IBM Cloud instances of Discovery. + + :param str customer_id: The customer ID for which all data is to be + deleted. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if customer_id is None: + raise ValueError('customer_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_user_data') + headers.update(sdk_headers) + + params = {'version': self.version, 'customer_id': customer_id} + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + + url = '/v2/user_data' + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + +class AddDocumentEnums: + """ + Enums for add_document parameters. + """ + + class FileContentType(str, Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +class UpdateDocumentEnums: + """ + Enums for update_document parameters. + """ + + class FileContentType(str, Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +class AnalyzeDocumentEnums: + """ + Enums for analyze_document parameters. + """ + + class FileContentType(str, Enum): + """ + The content type of file. + """ + APPLICATION_JSON = 'application/json' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' + APPLICATION_PDF = 'application/pdf' + TEXT_HTML = 'text/html' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + + +############################################################################## +# Models +############################################################################## + + +class AnalyzedDocument(): + """ + An object that contains the converted document and any identified enrichments. + Root-level fields from the original file are returned also. + + :attr List[Notice] notices: (optional) Array of notices that are triggered when + the files are processed. + :attr AnalyzedResult result: (optional) Result of the document analysis. + """ + + def __init__(self, + *, + notices: List['Notice'] = None, + result: 'AnalyzedResult' = None) -> None: + """ + Initialize a AnalyzedDocument object. + + :param List[Notice] notices: (optional) Array of notices that are triggered + when the files are processed. + :param AnalyzedResult result: (optional) Result of the document analysis. + """ + self.notices = notices + self.result = result + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AnalyzedDocument': + """Initialize a AnalyzedDocument object from a json dictionary.""" + args = {} + if 'notices' in _dict: + args['notices'] = [ + Notice.from_dict(x) for x in _dict.get('notices') + ] + if 'result' in _dict: + args['result'] = AnalyzedResult.from_dict(_dict.get('result')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalyzedDocument 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, 'notices') and self.notices is not None: + _dict['notices'] = [x.to_dict() for x in self.notices] + if hasattr(self, 'result') and self.result is not None: + _dict['result'] = self.result.to_dict() + 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 AnalyzedDocument object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AnalyzedDocument') -> 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: 'AnalyzedDocument') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AnalyzedResult(): + """ + Result of the document analysis. + + :attr dict metadata: (optional) Metadata that was specified with the request. + """ + + # The set of defined properties for the class + _properties = frozenset(['metadata']) + + def __init__(self, *, metadata: dict = None, **kwargs) -> None: + """ + Initialize a AnalyzedResult object. + + :param dict metadata: (optional) Metadata that was specified with the + request. + :param **kwargs: (optional) Any additional properties. + """ + self.metadata = metadata + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': + """Initialize a AnalyzedResult object from a json dictionary.""" + args = {} + if 'metadata' in _dict: + args['metadata'] = _dict.get('metadata') + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AnalyzedResult 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, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + for _key in [ + k for k in vars(self).keys() + if k not in AnalyzedResult._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of AnalyzedResult""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in AnalyzedResult._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of AnalyzedResult""" + for _key in [ + k for k in vars(self).keys() + if k not in AnalyzedResult._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in AnalyzedResult._properties: + setattr(self, _key, _value) + + def __str__(self) -> str: + """Return a `str` version of this AnalyzedResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AnalyzedResult') -> 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: 'AnalyzedResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ClassifierFederatedModel(): + """ + An object with details for creating federated document classifier models. + + :attr str field: Name of the field that contains the values from which multiple + classifier models are defined. For example, you can specify a field that lists + product lines to create a separate model per product line. + """ + + def __init__(self, field: str) -> None: + """ + Initialize a ClassifierFederatedModel object. + + :param str field: Name of the field that contains the values from which + multiple classifier models are defined. For example, you can specify a + field that lists product lines to create a separate model per product line. + """ + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ClassifierFederatedModel': + """Initialize a ClassifierFederatedModel object from a json dictionary.""" + args = {} + if 'field' in _dict: + args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in ClassifierFederatedModel JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifierFederatedModel 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, 'field') and self.field is not None: + _dict['field'] = self.field + 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 ClassifierFederatedModel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ClassifierFederatedModel') -> 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: 'ClassifierFederatedModel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ClassifierModelEvaluation(): + """ + An object that contains information about a trained document classifier model. + + :attr ModelEvaluationMicroAverage micro_average: A micro-average aggregates the + contributions of all classes to compute the average metric. Classes refers to + the classification labels that are specified in the **answer_field**. + :attr ModelEvaluationMacroAverage macro_average: A macro-average computes metric + independently for each class and then takes the average. Class refers to the + classification label that is specified in the **answer_field**. + :attr List[PerClassModelEvaluation] per_class: An array of evaluation metrics, + one set of metrics for each class, where class refers to the classification + label that is specified in the **answer_field**. + """ + + def __init__(self, micro_average: 'ModelEvaluationMicroAverage', + macro_average: 'ModelEvaluationMacroAverage', + per_class: List['PerClassModelEvaluation']) -> None: + """ + Initialize a ClassifierModelEvaluation object. + + :param ModelEvaluationMicroAverage micro_average: A micro-average + aggregates the contributions of all classes to compute the average metric. + Classes refers to the classification labels that are specified in the + **answer_field**. + :param ModelEvaluationMacroAverage macro_average: A macro-average computes + metric independently for each class and then takes the average. Class + refers to the classification label that is specified in the + **answer_field**. + :param List[PerClassModelEvaluation] per_class: An array of evaluation + metrics, one set of metrics for each class, where class refers to the + classification label that is specified in the **answer_field**. + """ + self.micro_average = micro_average + self.macro_average = macro_average + self.per_class = per_class + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ClassifierModelEvaluation': + """Initialize a ClassifierModelEvaluation object from a json dictionary.""" + args = {} + if 'micro_average' in _dict: + args['micro_average'] = ModelEvaluationMicroAverage.from_dict( + _dict.get('micro_average')) + else: + raise ValueError( + 'Required property \'micro_average\' not present in ClassifierModelEvaluation JSON' + ) + if 'macro_average' in _dict: + args['macro_average'] = ModelEvaluationMacroAverage.from_dict( + _dict.get('macro_average')) + else: + raise ValueError( + 'Required property \'macro_average\' not present in ClassifierModelEvaluation JSON' + ) + if 'per_class' in _dict: + args['per_class'] = [ + PerClassModelEvaluation.from_dict(x) + for x in _dict.get('per_class') + ] + else: + raise ValueError( + 'Required property \'per_class\' not present in ClassifierModelEvaluation JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassifierModelEvaluation 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, 'micro_average') and self.micro_average is not None: + _dict['micro_average'] = self.micro_average.to_dict() + if hasattr(self, 'macro_average') and self.macro_average is not None: + _dict['macro_average'] = self.macro_average.to_dict() + if hasattr(self, 'per_class') and self.per_class is not None: + _dict['per_class'] = [x.to_dict() for x in self.per_class] + 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 ClassifierModelEvaluation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ClassifierModelEvaluation') -> 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: 'ClassifierModelEvaluation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Collection(): + """ + A collection for storing documents. + + :attr str collection_id: (optional) The unique identifier of the collection. + :attr str name: (optional) The name of the collection. + """ + + def __init__(self, *, collection_id: str = None, name: str = None) -> None: + """ + Initialize a Collection object. + + :param str name: (optional) The name of the collection. + """ + self.collection_id = collection_id + self.name = name + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Collection': + """Initialize a Collection object from a json dictionary.""" + args = {} + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Collection 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, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + 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 Collection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Collection') -> 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: 'Collection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionDetails(): + """ + A collection for storing documents. + + :attr str collection_id: (optional) The unique identifier of the collection. + :attr str name: The name of the collection. + :attr str description: (optional) A description of the collection. + :attr datetime created: (optional) The date that the collection was created. + :attr str language: (optional) The language of the collection. For a list of + supported languages, see the [product + documentation](/docs/discovery-data?topic=discovery-data-language-support). + :attr List[CollectionEnrichment] enrichments: (optional) An array of enrichments + that are applied to this collection. To get a list of enrichments that are + available for a project, use the [List enrichments](#listenrichments) method. + If no enrichments are specified when the collection is created, the default + enrichments for the project type are applied. For more information about project + default settings, see the [product + documentation](/docs/discovery-data?topic=discovery-data-project-defaults). + :attr CollectionDetailsSmartDocumentUnderstanding smart_document_understanding: + (optional) An object that describes the Smart Document Understanding model for a + collection. + """ + + def __init__( + self, + name: str, + *, + collection_id: str = None, + description: str = None, + created: datetime = None, + language: str = None, + enrichments: List['CollectionEnrichment'] = None, + smart_document_understanding: + 'CollectionDetailsSmartDocumentUnderstanding' = None + ) -> None: + """ + Initialize a CollectionDetails object. + + :param str name: The name of the collection. + :param str description: (optional) A description of the collection. + :param str language: (optional) The language of the collection. For a list + of supported languages, see the [product + documentation](/docs/discovery-data?topic=discovery-data-language-support). + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. To get a list of + enrichments that are available for a project, use the [List + enrichments](#listenrichments) method. + If no enrichments are specified when the collection is created, the default + enrichments for the project type are applied. For more information about + project default settings, see the [product + documentation](/docs/discovery-data?topic=discovery-data-project-defaults). + :param CollectionDetailsSmartDocumentUnderstanding + smart_document_understanding: (optional) An object that describes the Smart + Document Understanding model for a collection. + """ + self.collection_id = collection_id + self.name = name + self.description = description + self.created = created + self.language = language + self.enrichments = enrichments + self.smart_document_understanding = smart_document_understanding + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CollectionDetails': + """Initialize a CollectionDetails object from a json dictionary.""" + args = {} + if 'collection_id' in _dict: + args['collection_id'] = _dict.get('collection_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in CollectionDetails JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'language' in _dict: + args['language'] = _dict.get('language') + if 'enrichments' in _dict: + args['enrichments'] = [ + CollectionEnrichment.from_dict(x) + for x in _dict.get('enrichments') + ] + if 'smart_document_understanding' in _dict: + args[ + 'smart_document_understanding'] = CollectionDetailsSmartDocumentUnderstanding.from_dict( + _dict.get('smart_document_understanding')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionDetails 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, 'collection_id') and getattr( + self, 'collection_id') is not None: + _dict['collection_id'] = getattr(self, 'collection_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'enrichments') and self.enrichments is not None: + _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + if hasattr(self, 'smart_document_understanding' + ) and self.smart_document_understanding is not None: + _dict[ + 'smart_document_understanding'] = self.smart_document_understanding.to_dict( + ) + 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 CollectionDetails object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CollectionDetails') -> 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: 'CollectionDetails') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class CollectionDetailsSmartDocumentUnderstanding(): + """ + An object that describes the Smart Document Understanding model for a collection. + + :attr bool enabled: (optional) When `true`, smart document understanding + conversion is enabled for the collection. + :attr str model: (optional) Specifies the type of Smart Document Understanding + (SDU) model that is enabled for the collection. The following types of models + are supported: + * `custom`: A user-trained model is applied. + * `pre_trained`: A pretrained model is applied. This type of model is applied + automatically to *Document Retrieval for Contracts* projects. + * `text_extraction`: An SDU model that extracts text and metadata from the + content. This model is enabled in collections by default regardless of the types + of documents in the collection (as long as the service plan supports SDU + models). + You can apply user-trained or pretrained models to collections from the + *Identify fields* page of the product user interface. For more information, see + [the product + documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). + """ + + def __init__(self, *, enabled: bool = None, model: str = None) -> None: + """ + Initialize a CollectionDetailsSmartDocumentUnderstanding object. + + :param bool enabled: (optional) When `true`, smart document understanding + conversion is enabled for the collection. + :param str model: (optional) Specifies the type of Smart Document + Understanding (SDU) model that is enabled for the collection. The following + types of models are supported: + * `custom`: A user-trained model is applied. + * `pre_trained`: A pretrained model is applied. This type of model is + applied automatically to *Document Retrieval for Contracts* projects. + * `text_extraction`: An SDU model that extracts text and metadata from the + content. This model is enabled in collections by default regardless of the + types of documents in the collection (as long as the service plan supports + SDU models). + You can apply user-trained or pretrained models to collections from the + *Identify fields* page of the product user interface. For more information, + see [the product + documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). + """ + self.enabled = enabled + self.model = model + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'CollectionDetailsSmartDocumentUnderstanding': + """Initialize a CollectionDetailsSmartDocumentUnderstanding object from a json dictionary.""" + args = {} + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'model' in _dict: + args['model'] = _dict.get('model') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionDetailsSmartDocumentUnderstanding 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 + if hasattr(self, 'model') and self.model is not None: + _dict['model'] = self.model + 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 CollectionDetailsSmartDocumentUnderstanding object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'CollectionDetailsSmartDocumentUnderstanding') -> 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: 'CollectionDetailsSmartDocumentUnderstanding') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ModelEnum(str, Enum): + """ + Specifies the type of Smart Document Understanding (SDU) model that is enabled for + the collection. The following types of models are supported: + * `custom`: A user-trained model is applied. + * `pre_trained`: A pretrained model is applied. This type of model is applied + automatically to *Document Retrieval for Contracts* projects. + * `text_extraction`: An SDU model that extracts text and metadata from the + content. This model is enabled in collections by default regardless of the types + of documents in the collection (as long as the service plan supports SDU models). + You can apply user-trained or pretrained models to collections from the *Identify + fields* page of the product user interface. For more information, see [the product + documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). + """ + CUSTOM = 'custom' + PRE_TRAINED = 'pre_trained' + TEXT_EXTRACTION = 'text_extraction' + + +class CollectionEnrichment(): + """ + An object describing an enrichment for a collection. + + :attr str enrichment_id: (optional) The unique identifier of this enrichment. + For more information about how to determine the ID of an enrichment, see [the + product + documentation](/docs/discovery-data?topic=discovery-data-manage-enrichments#enrichments-ids). + :attr List[str] fields: (optional) An array of field names that the enrichment + is applied to. + If you apply an enrichment to a field from a JSON file, the data is converted to + an array automatically, even if the field contains a single value. + """ + + def __init__(self, + *, + enrichment_id: str = None, + fields: List[str] = None) -> None: + """ + Initialize a CollectionEnrichment object. + + :param str enrichment_id: (optional) The unique identifier of this + enrichment. For more information about how to determine the ID of an + enrichment, see [the product + documentation](/docs/discovery-data?topic=discovery-data-manage-enrichments#enrichments-ids). + :param List[str] fields: (optional) An array of field names that the + enrichment is applied to. + If you apply an enrichment to a field from a JSON file, the data is + converted to an array automatically, even if the field contains a single + value. + """ + self.enrichment_id = enrichment_id + self.fields = fields + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CollectionEnrichment': + """Initialize a CollectionEnrichment object from a json dictionary.""" + args = {} + if 'enrichment_id' in _dict: + args['enrichment_id'] = _dict.get('enrichment_id') + if 'fields' in _dict: + args['fields'] = _dict.get('fields') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CollectionEnrichment 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, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + 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 CollectionEnrichment object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CollectionEnrichment') -> 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: 'CollectionEnrichment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Completions(): + """ + An object that contains an array of autocompletion suggestions. + + :attr List[str] completions: (optional) Array of autocomplete suggestion based + on the provided prefix. + """ + + def __init__(self, *, completions: List[str] = None) -> None: + """ + Initialize a Completions object. + + :param List[str] completions: (optional) Array of autocomplete suggestion + based on the provided prefix. + """ + self.completions = completions + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Completions': + """Initialize a Completions object from a json dictionary.""" + args = {} + if 'completions' in _dict: + args['completions'] = _dict.get('completions') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Completions 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, 'completions') and self.completions is not None: + _dict['completions'] = self.completions + 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 Completions object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Completions') -> 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: 'Completions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ComponentSettingsAggregation(): + """ + Display settings for aggregations. + + :attr str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :attr str label: (optional) User-friendly alias for the aggregation. + :attr bool multiple_selections_allowed: (optional) Whether users is allowed to + select more than one of the aggregation terms. + :attr str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + + def __init__(self, + *, + name: str = None, + label: str = None, + multiple_selections_allowed: bool = None, + visualization_type: str = None) -> None: + """ + Initialize a ComponentSettingsAggregation object. + + :param str name: (optional) Identifier used to map aggregation settings to + aggregation configuration. + :param str label: (optional) User-friendly alias for the aggregation. + :param bool multiple_selections_allowed: (optional) Whether users is + allowed to select more than one of the aggregation terms. + :param str visualization_type: (optional) Type of visualization to use when + rendering the aggregation. + """ + self.name = name + self.label = label + self.multiple_selections_allowed = multiple_selections_allowed + self.visualization_type = visualization_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': + """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + args = {} + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'label' in _dict: + args['label'] = _dict.get('label') + if 'multiple_selections_allowed' in _dict: + args['multiple_selections_allowed'] = _dict.get( + 'multiple_selections_allowed') + if 'visualization_type' in _dict: + args['visualization_type'] = _dict.get('visualization_type') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsAggregation 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'multiple_selections_allowed' + ) and self.multiple_selections_allowed is not None: + _dict[ + 'multiple_selections_allowed'] = self.multiple_selections_allowed + if hasattr( + self, + 'visualization_type') and self.visualization_type is not None: + _dict['visualization_type'] = self.visualization_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 ComponentSettingsAggregation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ComponentSettingsAggregation') -> 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: 'ComponentSettingsAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class VisualizationTypeEnum(str, Enum): + """ + Type of visualization to use when rendering the aggregation. + """ + AUTO = 'auto' + FACET_TABLE = 'facet_table' + WORD_CLOUD = 'word_cloud' + MAP = 'map' + + +class ComponentSettingsFieldsShown(): + """ + Fields shown in the results section of the UI. + + :attr ComponentSettingsFieldsShownBody body: (optional) Body label. + :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + """ + + def __init__(self, + *, + body: 'ComponentSettingsFieldsShownBody' = None, + title: 'ComponentSettingsFieldsShownTitle' = None) -> None: + """ + Initialize a ComponentSettingsFieldsShown object. + + :param ComponentSettingsFieldsShownBody body: (optional) Body label. + :param ComponentSettingsFieldsShownTitle title: (optional) Title label. + """ + self.body = body + self.title = title + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': + """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + args = {} + if 'body' in _dict: + args['body'] = ComponentSettingsFieldsShownBody.from_dict( + _dict.get('body')) + if 'title' in _dict: + args['title'] = ComponentSettingsFieldsShownTitle.from_dict( + _dict.get('title')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShown 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, 'body') and self.body is not None: + _dict['body'] = self.body.to_dict() + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title.to_dict() + 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 AnalyzedDocument object.""" + """Return a `str` version of this ComponentSettingsFieldsShown object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'AnalyzedDocument') -> bool: + def __eq__(self, other: 'ComponentSettingsFieldsShown') -> 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: 'AnalyzedDocument') -> bool: + def __ne__(self, other: 'ComponentSettingsFieldsShown') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class AnalyzedResult(): +class ComponentSettingsFieldsShownBody(): """ - Result of the document analysis. + Body label. - :attr dict metadata: (optional) Metadata of the document. + :attr bool use_passage: (optional) Use the whole passage as the body. + :attr str field: (optional) Use a specific field as the title. """ - # The set of defined properties for the class - _properties = frozenset(['metadata']) - - def __init__(self, *, metadata: dict = None, **kwargs) -> None: + def __init__(self, *, use_passage: bool = None, field: str = None) -> None: """ - Initialize a AnalyzedResult object. + Initialize a ComponentSettingsFieldsShownBody object. - :param dict metadata: (optional) Metadata of the document. - :param **kwargs: (optional) Any additional properties. + :param bool use_passage: (optional) Use the whole passage as the body. + :param str field: (optional) Use a specific field as the title. """ - self.metadata = metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.use_passage = use_passage + self.field = field @classmethod - def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': - """Initialize a AnalyzedResult object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': + """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" args = {} - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if 'use_passage' in _dict: + args['use_passage'] = _dict.get('use_passage') + if 'field' in _dict: + args['field'] = _dict.get('field') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a AnalyzedResult object from a json dictionary.""" + """Initialize a ComponentSettingsFieldsShownBody 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, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties - ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'use_passage') and self.use_passage is not None: + _dict['use_passage'] = self.use_passage + if hasattr(self, 'field') and self.field is not None: + _dict['field'] = self.field return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of AnalyzedResult""" - _dict = {} + def __str__(self) -> str: + """Return a `str` version of this ComponentSettingsFieldsShownBody object.""" + return json.dumps(self.to_dict(), indent=2) - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict + def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> 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 set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of AnalyzedResult""" - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties - ]: - delattr(self, _key) + def __ne__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other - for _key, _value in _dict.items(): - if _key not in AnalyzedResult._properties: - setattr(self, _key, _value) + +class ComponentSettingsFieldsShownTitle(): + """ + Title label. + + :attr str field: (optional) Use a specific field as the title. + """ + + def __init__(self, *, field: str = None) -> None: + """ + Initialize a ComponentSettingsFieldsShownTitle object. + + :param str field: (optional) Use a specific field as the title. + """ + self.field = field + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': + """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + args = {} + if 'field' in _dict: + args['field'] = _dict.get('field') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ComponentSettingsFieldsShownTitle 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, 'field') and self.field is not None: + _dict['field'] = self.field + 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 AnalyzedResult object.""" + """Return a `str` version of this ComponentSettingsFieldsShownTitle object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'AnalyzedResult') -> bool: + def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> 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: 'AnalyzedResult') -> bool: + def __ne__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Collection(): +class ComponentSettingsResponse(): """ - A collection for storing documents. + The default component settings for this project. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: (optional) The name of the collection. + :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the + results section of the UI. + :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. + :attr bool structured_search: (optional) Whether or not structured search is + enabled. + :attr int results_per_page: (optional) Number or results shown per page. + :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of + component setting aggregations. """ - def __init__(self, *, collection_id: str = None, name: str = None) -> None: + def __init__( + self, + *, + fields_shown: 'ComponentSettingsFieldsShown' = None, + autocomplete: bool = None, + structured_search: bool = None, + results_per_page: int = None, + aggregations: List['ComponentSettingsAggregation'] = None) -> None: """ - Initialize a Collection object. + Initialize a ComponentSettingsResponse object. - :param str name: (optional) The name of the collection. + :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown + in the results section of the UI. + :param bool autocomplete: (optional) Whether or not autocomplete is + enabled. + :param bool structured_search: (optional) Whether or not structured search + is enabled. + :param int results_per_page: (optional) Number or results shown per page. + :param List[ComponentSettingsAggregation] aggregations: (optional) a list + of component setting aggregations. """ - self.collection_id = collection_id - self.name = name + self.fields_shown = fields_shown + self.autocomplete = autocomplete + self.structured_search = structured_search + self.results_per_page = results_per_page + self.aggregations = aggregations @classmethod - def from_dict(cls, _dict: Dict) -> 'Collection': - """Initialize a Collection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': + """Initialize a ComponentSettingsResponse object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if 'fields_shown' in _dict: + args['fields_shown'] = ComponentSettingsFieldsShown.from_dict( + _dict.get('fields_shown')) + if 'autocomplete' in _dict: + args['autocomplete'] = _dict.get('autocomplete') + if 'structured_search' in _dict: + args['structured_search'] = _dict.get('structured_search') + if 'results_per_page' in _dict: + args['results_per_page'] = _dict.get('results_per_page') + if 'aggregations' in _dict: + args['aggregations'] = [ + ComponentSettingsAggregation.from_dict(x) + for x in _dict.get('aggregations') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Collection object from a json dictionary.""" + """Initialize a ComponentSettingsResponse 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, 'collection_id') and getattr( - self, 'collection_id') is not None: - _dict['collection_id'] = getattr(self, 'collection_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name + if hasattr(self, 'fields_shown') and self.fields_shown is not None: + _dict['fields_shown'] = self.fields_shown.to_dict() + if hasattr(self, 'autocomplete') and self.autocomplete is not None: + _dict['autocomplete'] = self.autocomplete + if hasattr(self, + 'structured_search') and self.structured_search is not None: + _dict['structured_search'] = self.structured_search + if hasattr(self, + 'results_per_page') and self.results_per_page is not None: + _dict['results_per_page'] = self.results_per_page + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -2214,103 +4355,135 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Collection object.""" + """Return a `str` version of this ComponentSettingsResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Collection') -> bool: + def __eq__(self, other: 'ComponentSettingsResponse') -> 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: 'Collection') -> bool: + def __ne__(self, other: 'ComponentSettingsResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class CollectionDetails(): +class CreateDocumentClassifier(): """ - A collection for storing documents. + An object that manages the settings and data that is required to train a document + classification model. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: The name of the collection. - :attr str description: (optional) A description of the collection. - :attr datetime created: (optional) The date that the collection was created. - :attr str language: (optional) The language of the collection. - :attr List[CollectionEnrichment] enrichments: (optional) An array of enrichments - that are applied to this collection. + :attr str name: A human-readable name of the document classifier. + :attr str description: (optional) A description of the document classifier. + :attr str language: The language of the training data that is associated with + the document classifier. Language is specified by using the ISO 639-1 language + code, such as `en` for English or `ja` for Japanese. + :attr str answer_field: The name of the field from the training and test data + that contains the classification labels. + :attr List[DocumentClassifierEnrichment] enrichments: (optional) An array of + enrichments to apply to the data that is used to train and test the document + classifier. The output from the enrichments is used as features by the + classifier to classify the document content both during training and at run + time. + :attr ClassifierFederatedModel federated_classification: (optional) An object + with details for creating federated document classifier models. """ - def __init__(self, - name: str, - *, - collection_id: str = None, - description: str = None, - created: datetime = None, - language: str = None, - enrichments: List['CollectionEnrichment'] = None) -> None: + def __init__( + self, + name: str, + language: str, + answer_field: str, + *, + description: str = None, + enrichments: List['DocumentClassifierEnrichment'] = None, + federated_classification: 'ClassifierFederatedModel' = None + ) -> None: """ - Initialize a CollectionDetails object. - - :param str name: The name of the collection. - :param str description: (optional) A description of the collection. - :param str language: (optional) The language of the collection. - :param List[CollectionEnrichment] enrichments: (optional) An array of - enrichments that are applied to this collection. + Initialize a CreateDocumentClassifier object. + + :param str name: A human-readable name of the document classifier. + :param str language: The language of the training data that is associated + with the document classifier. Language is specified by using the ISO 639-1 + language code, such as `en` for English or `ja` for Japanese. + :param str answer_field: The name of the field from the training and test + data that contains the classification labels. + :param str description: (optional) A description of the document + classifier. + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array + of enrichments to apply to the data that is used to train and test the + document classifier. The output from the enrichments is used as features by + the classifier to classify the document content both during training and at + run time. + :param ClassifierFederatedModel federated_classification: (optional) An + object with details for creating federated document classifier models. """ - self.collection_id = collection_id self.name = name self.description = description - self.created = created self.language = language + self.answer_field = answer_field self.enrichments = enrichments + self.federated_classification = federated_classification @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionDetails': - """Initialize a CollectionDetails object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CreateDocumentClassifier': + """Initialize a CreateDocumentClassifier object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') if 'name' in _dict: args['name'] = _dict.get('name') else: raise ValueError( - 'Required property \'name\' not present in CollectionDetails JSON' + 'Required property \'name\' not present in CreateDocumentClassifier JSON' ) if 'description' in _dict: args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) if 'language' in _dict: args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in CreateDocumentClassifier JSON' + ) + if 'answer_field' in _dict: + args['answer_field'] = _dict.get('answer_field') + else: + raise ValueError( + 'Required property \'answer_field\' not present in CreateDocumentClassifier JSON' + ) if 'enrichments' in _dict: args['enrichments'] = [ - CollectionEnrichment.from_dict(x) + DocumentClassifierEnrichment.from_dict(x) for x in _dict.get('enrichments') ] + if 'federated_classification' in _dict: + args[ + 'federated_classification'] = ClassifierFederatedModel.from_dict( + _dict.get('federated_classification')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CollectionDetails object from a json dictionary.""" + """Initialize a CreateDocumentClassifier 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, 'collection_id') and getattr( - self, 'collection_id') is not None: - _dict['collection_id'] = getattr(self, 'collection_id') if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language + if hasattr(self, 'answer_field') and self.answer_field is not None: + _dict['answer_field'] = self.answer_field if hasattr(self, 'enrichments') and self.enrichments is not None: _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + if hasattr(self, 'federated_classification' + ) and self.federated_classification is not None: + _dict[ + 'federated_classification'] = self.federated_classification.to_dict( + ) return _dict def _to_dict(self): @@ -2318,71 +4491,120 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CollectionDetails object.""" + """Return a `str` version of this CreateDocumentClassifier object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CollectionDetails') -> bool: + def __eq__(self, other: 'CreateDocumentClassifier') -> 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: 'CollectionDetails') -> bool: + def __ne__(self, other: 'CreateDocumentClassifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class CollectionEnrichment(): +class CreateEnrichment(): """ - An object describing an Enrichment for a collection. + Information about a specific enrichment. - :attr str enrichment_id: (optional) The unique identifier of this enrichment. - :attr List[str] fields: (optional) An array of field names that the enrichment - is applied to. - If you apply an enrichment to a field from a JSON file, the data is converted to - an array automatically, even if the field contains a single value. + :attr str name: (optional) The human readable name for this enrichment. + :attr str description: (optional) The description of this enrichment. + :attr str type: (optional) The type of this enrichment. The following types are + supported: + * `classifier`: Creates a document classifier enrichment from a document + classifier model that you create by using the [Document classifier + API](/apidocs/discovery-data#createdocumentclassifier). **Note**: A text + classifier enrichment can be created only from the product user interface. + * `dictionary`: Creates a custom dictionary enrichment that you define in a CSV + file. + * `regular_expression`: Creates a custom regular expression enrichment from + regex syntax that you specify in the request. + * `rule_based`: Creates an enrichment from an advanced rules model that is + created and exported as a ZIP file from Watson Knowledge Studio. + * `uima_annotator`: Creates an enrichment from a custom UIMA text analysis model + that is defined in a PEAR file created in one of the following ways: + * Watson Explorer Content Analytics Studio. **Note**: Supported in IBM Cloud + Pak for Data instances only. + * Rule-based model that is created in Watson Knowledge Studio. + * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge + Studio machine learning model that is defined in a ZIP file. + :attr EnrichmentOptions options: (optional) An object that contains options for + the current enrichment. Starting with version `2020-08-30`, the enrichment + options are not included in responses from the List Enrichments method. """ def __init__(self, *, - enrichment_id: str = None, - fields: List[str] = None) -> None: + name: str = None, + description: str = None, + type: str = None, + options: 'EnrichmentOptions' = None) -> None: """ - Initialize a CollectionEnrichment object. + Initialize a CreateEnrichment object. - :param str enrichment_id: (optional) The unique identifier of this - enrichment. - :param List[str] fields: (optional) An array of field names that the - enrichment is applied to. - If you apply an enrichment to a field from a JSON file, the data is - converted to an array automatically, even if the field contains a single - value. + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. The following + types are supported: + * `classifier`: Creates a document classifier enrichment from a document + classifier model that you create by using the [Document classifier + API](/apidocs/discovery-data#createdocumentclassifier). **Note**: A text + classifier enrichment can be created only from the product user interface. + * `dictionary`: Creates a custom dictionary enrichment that you define in a + CSV file. + * `regular_expression`: Creates a custom regular expression enrichment from + regex syntax that you specify in the request. + * `rule_based`: Creates an enrichment from an advanced rules model that is + created and exported as a ZIP file from Watson Knowledge Studio. + * `uima_annotator`: Creates an enrichment from a custom UIMA text analysis + model that is defined in a PEAR file created in one of the following ways: + * Watson Explorer Content Analytics Studio. **Note**: Supported in IBM + Cloud Pak for Data instances only. + * Rule-based model that is created in Watson Knowledge Studio. + * `watson_knowledge_studio_model`: Creates an enrichment from a Watson + Knowledge Studio machine learning model that is defined in a ZIP file. + :param EnrichmentOptions options: (optional) An object that contains + options for the current enrichment. Starting with version `2020-08-30`, the + enrichment options are not included in responses from the List Enrichments + method. """ - self.enrichment_id = enrichment_id - self.fields = fields + self.name = name + self.description = description + self.type = type + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionEnrichment': - """Initialize a CollectionEnrichment object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': + """Initialize a CreateEnrichment object from a json dictionary.""" args = {} - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'options' in _dict: + args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CollectionEnrichment object from a json dictionary.""" + """Initialize a CreateEnrichment 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, 'enrichment_id') and self.enrichment_id is not None: - _dict['enrichment_id'] = self.enrichment_id - if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = self.fields + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'options') and self.options is not None: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -2390,55 +4612,187 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CollectionEnrichment object.""" + """Return a `str` version of this CreateEnrichment object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CollectionEnrichment') -> bool: + def __eq__(self, other: 'CreateEnrichment') -> 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: 'CollectionEnrichment') -> bool: + def __ne__(self, other: 'CreateEnrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of this enrichment. The following types are supported: + * `classifier`: Creates a document classifier enrichment from a document + classifier model that you create by using the [Document classifier + API](/apidocs/discovery-data#createdocumentclassifier). **Note**: A text + classifier enrichment can be created only from the product user interface. + * `dictionary`: Creates a custom dictionary enrichment that you define in a CSV + file. + * `regular_expression`: Creates a custom regular expression enrichment from regex + syntax that you specify in the request. + * `rule_based`: Creates an enrichment from an advanced rules model that is created + and exported as a ZIP file from Watson Knowledge Studio. + * `uima_annotator`: Creates an enrichment from a custom UIMA text analysis model + that is defined in a PEAR file created in one of the following ways: + * Watson Explorer Content Analytics Studio. **Note**: Supported in IBM Cloud + Pak for Data instances only. + * Rule-based model that is created in Watson Knowledge Studio. + * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge + Studio machine learning model that is defined in a ZIP file. + """ + CLASSIFIER = 'classifier' + DICTIONARY = 'dictionary' + REGULAR_EXPRESSION = 'regular_expression' + UIMA_ANNOTATOR = 'uima_annotator' + RULE_BASED = 'rule_based' + WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' + -class Completions(): +class DefaultQueryParams(): """ - An object that contains an array of autocompletion suggestions. + Default query parameters for this project. - :attr List[str] completions: (optional) Array of autocomplete suggestion based - on the provided prefix. + :attr List[str] collection_ids: (optional) An array of collection identifiers to + query. If empty or omitted all collections in the project are queried. + :attr DefaultQueryParamsPassages passages: (optional) Default settings + configuration for passage search options. + :attr DefaultQueryParamsTableResults table_results: (optional) Default project + query settings for table results. + :attr str aggregation: (optional) A string representing the default aggregation + query for the project. + :attr DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) + Object that contains suggested refinement settings. + **Note**: The `suggested_refinements` parameter that identified dynamic facets + from the data is deprecated. + :attr bool spelling_suggestions: (optional) When `true`, a spelling suggestions + for the query are returned by default. + :attr bool highlight: (optional) When `true`, highlights for the query are + returned by default. + :attr int count: (optional) The number of document results returned by default. + :attr str sort: (optional) A comma separated list of document fields to sort + results by default. + :attr List[str] return_: (optional) An array of field names to return in + document results if present by default. """ - def __init__(self, *, completions: List[str] = None) -> None: + def __init__(self, + *, + collection_ids: List[str] = None, + passages: 'DefaultQueryParamsPassages' = None, + table_results: 'DefaultQueryParamsTableResults' = None, + aggregation: str = None, + suggested_refinements: + 'DefaultQueryParamsSuggestedRefinements' = None, + spelling_suggestions: bool = None, + highlight: bool = None, + count: int = None, + sort: str = None, + return_: List[str] = None) -> None: """ - Initialize a Completions object. + Initialize a DefaultQueryParams object. - :param List[str] completions: (optional) Array of autocomplete suggestion - based on the provided prefix. + :param List[str] collection_ids: (optional) An array of collection + identifiers to query. If empty or omitted all collections in the project + are queried. + :param DefaultQueryParamsPassages passages: (optional) Default settings + configuration for passage search options. + :param DefaultQueryParamsTableResults table_results: (optional) Default + project query settings for table results. + :param str aggregation: (optional) A string representing the default + aggregation query for the project. + :param DefaultQueryParamsSuggestedRefinements suggested_refinements: + (optional) Object that contains suggested refinement settings. + **Note**: The `suggested_refinements` parameter that identified dynamic + facets from the data is deprecated. + :param bool spelling_suggestions: (optional) When `true`, a spelling + suggestions for the query are returned by default. + :param bool highlight: (optional) When `true`, highlights for the query are + returned by default. + :param int count: (optional) The number of document results returned by + default. + :param str sort: (optional) A comma separated list of document fields to + sort results by default. + :param List[str] return_: (optional) An array of field names to return in + document results if present by default. """ - self.completions = completions + self.collection_ids = collection_ids + self.passages = passages + self.table_results = table_results + self.aggregation = aggregation + self.suggested_refinements = suggested_refinements + self.spelling_suggestions = spelling_suggestions + self.highlight = highlight + self.count = count + self.sort = sort + self.return_ = return_ @classmethod - def from_dict(cls, _dict: Dict) -> 'Completions': - """Initialize a Completions object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParams': + """Initialize a DefaultQueryParams object from a json dictionary.""" args = {} - if 'completions' in _dict: - args['completions'] = _dict.get('completions') + if 'collection_ids' in _dict: + args['collection_ids'] = _dict.get('collection_ids') + if 'passages' in _dict: + args['passages'] = DefaultQueryParamsPassages.from_dict( + _dict.get('passages')) + if 'table_results' in _dict: + args['table_results'] = DefaultQueryParamsTableResults.from_dict( + _dict.get('table_results')) + if 'aggregation' in _dict: + args['aggregation'] = _dict.get('aggregation') + if 'suggested_refinements' in _dict: + args[ + 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements.from_dict( + _dict.get('suggested_refinements')) + if 'spelling_suggestions' in _dict: + args['spelling_suggestions'] = _dict.get('spelling_suggestions') + if 'highlight' in _dict: + args['highlight'] = _dict.get('highlight') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'sort' in _dict: + args['sort'] = _dict.get('sort') + if 'return' in _dict: + args['return_'] = _dict.get('return') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Completions object from a json dictionary.""" + """Initialize a DefaultQueryParams 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, 'completions') and self.completions is not None: - _dict['completions'] = self.completions + if hasattr(self, 'collection_ids') and self.collection_ids is not None: + _dict['collection_ids'] = self.collection_ids + if hasattr(self, 'passages') and self.passages is not None: + _dict['passages'] = self.passages.to_dict() + if hasattr(self, 'table_results') and self.table_results is not None: + _dict['table_results'] = self.table_results.to_dict() + if hasattr(self, 'aggregation') and self.aggregation is not None: + _dict['aggregation'] = self.aggregation + if hasattr(self, 'suggested_refinements' + ) and self.suggested_refinements is not None: + _dict['suggested_refinements'] = self.suggested_refinements.to_dict( + ) + if hasattr(self, 'spelling_suggestions' + ) and self.spelling_suggestions is not None: + _dict['spelling_suggestions'] = self.spelling_suggestions + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'sort') and self.sort is not None: + _dict['sort'] = self.sort + if hasattr(self, 'return_') and self.return_ is not None: + _dict['return'] = self.return_ return _dict def _to_dict(self): @@ -2446,90 +4800,109 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Completions object.""" + """Return a `str` version of this DefaultQueryParams object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Completions') -> bool: + def __eq__(self, other: 'DefaultQueryParams') -> 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: 'Completions') -> bool: + def __ne__(self, other: 'DefaultQueryParams') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsAggregation(): +class DefaultQueryParamsPassages(): """ - Display settings for aggregations. + Default settings configuration for passage search options. - :attr str name: (optional) Identifier used to map aggregation settings to - aggregation configuration. - :attr str label: (optional) User-friendly alias for the aggregation. - :attr bool multiple_selections_allowed: (optional) Whether users is allowed to - select more than one of the aggregation terms. - :attr str visualization_type: (optional) Type of visualization to use when - rendering the aggregation. + :attr bool enabled: (optional) When `true`, a passage search is performed by + default. + :attr int count: (optional) The number of passages to return. + :attr List[str] fields: (optional) An array of field names to perform the + passage search on. + :attr int characters: (optional) The approximate number of characters that each + returned passage will contain. + :attr bool per_document: (optional) When `true` the number of passages that can + be returned from a single document is restricted to the *max_per_document* + value. + :attr int max_per_document: (optional) The default maximum number of passages + that can be taken from a single document as the result of a passage query. """ def __init__(self, *, - name: str = None, - label: str = None, - multiple_selections_allowed: bool = None, - visualization_type: str = None) -> None: + enabled: bool = None, + count: int = None, + fields: List[str] = None, + characters: int = None, + per_document: bool = None, + max_per_document: int = None) -> None: """ - Initialize a ComponentSettingsAggregation object. + Initialize a DefaultQueryParamsPassages object. - :param str name: (optional) Identifier used to map aggregation settings to - aggregation configuration. - :param str label: (optional) User-friendly alias for the aggregation. - :param bool multiple_selections_allowed: (optional) Whether users is - allowed to select more than one of the aggregation terms. - :param str visualization_type: (optional) Type of visualization to use when - rendering the aggregation. + :param bool enabled: (optional) When `true`, a passage search is performed + by default. + :param int count: (optional) The number of passages to return. + :param List[str] fields: (optional) An array of field names to perform the + passage search on. + :param int characters: (optional) The approximate number of characters that + each returned passage will contain. + :param bool per_document: (optional) When `true` the number of passages + that can be returned from a single document is restricted to the + *max_per_document* value. + :param int max_per_document: (optional) The default maximum number of + passages that can be taken from a single document as the result of a + passage query. """ - self.name = name - self.label = label - self.multiple_selections_allowed = multiple_selections_allowed - self.visualization_type = visualization_type + self.enabled = enabled + self.count = count + self.fields = fields + self.characters = characters + self.per_document = per_document + self.max_per_document = max_per_document @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': - """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsPassages': + """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'multiple_selections_allowed' in _dict: - args['multiple_selections_allowed'] = _dict.get( - 'multiple_selections_allowed') - if 'visualization_type' in _dict: - args['visualization_type'] = _dict.get('visualization_type') + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'fields' in _dict: + args['fields'] = _dict.get('fields') + if 'characters' in _dict: + args['characters'] = _dict.get('characters') + if 'per_document' in _dict: + args['per_document'] = _dict.get('per_document') + if 'max_per_document' in _dict: + args['max_per_document'] = _dict.get('max_per_document') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsAggregation object from a json dictionary.""" + """Initialize a DefaultQueryParamsPassages 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'multiple_selections_allowed' - ) and self.multiple_selections_allowed is not None: - _dict[ - 'multiple_selections_allowed'] = self.multiple_selections_allowed - if hasattr( - self, - 'visualization_type') and self.visualization_type is not None: - _dict['visualization_type'] = self.visualization_type + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + if hasattr(self, 'characters') and self.characters is not None: + _dict['characters'] = self.characters + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document + if hasattr(self, + 'max_per_document') and self.max_per_document is not None: + _dict['max_per_document'] = self.max_per_document return _dict def _to_dict(self): @@ -2537,74 +4910,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsAggregation object.""" + """Return a `str` version of this DefaultQueryParamsPassages object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsAggregation') -> bool: + def __eq__(self, other: 'DefaultQueryParamsPassages') -> 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: 'ComponentSettingsAggregation') -> bool: + def __ne__(self, other: 'DefaultQueryParamsPassages') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class VisualizationTypeEnum(str, Enum): - """ - Type of visualization to use when rendering the aggregation. - """ - AUTO = 'auto' - FACET_TABLE = 'facet_table' - WORD_CLOUD = 'word_cloud' - MAP = 'map' - -class ComponentSettingsFieldsShown(): +class DefaultQueryParamsSuggestedRefinements(): """ - Fields shown in the results section of the UI. + Object that contains suggested refinement settings. + **Note**: The `suggested_refinements` parameter that identified dynamic facets from + the data is deprecated. - :attr ComponentSettingsFieldsShownBody body: (optional) Body label. - :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + :attr bool enabled: (optional) When `true`, suggested refinements for the query + are returned by default. + :attr int count: (optional) The number of suggested refinements to return by + default. """ - def __init__(self, - *, - body: 'ComponentSettingsFieldsShownBody' = None, - title: 'ComponentSettingsFieldsShownTitle' = None) -> None: + def __init__(self, *, enabled: bool = None, count: int = None) -> None: """ - Initialize a ComponentSettingsFieldsShown object. + Initialize a DefaultQueryParamsSuggestedRefinements object. - :param ComponentSettingsFieldsShownBody body: (optional) Body label. - :param ComponentSettingsFieldsShownTitle title: (optional) Title label. + :param bool enabled: (optional) When `true`, suggested refinements for the + query are returned by default. + :param int count: (optional) The number of suggested refinements to return + by default. """ - self.body = body - self.title = title + self.enabled = enabled + self.count = count @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': - """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsSuggestedRefinements': + """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" args = {} - if 'body' in _dict: - args['body'] = ComponentSettingsFieldsShownBody.from_dict( - _dict.get('body')) - if 'title' in _dict: - args['title'] = ComponentSettingsFieldsShownTitle.from_dict( - _dict.get('title')) + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" + """Initialize a DefaultQueryParamsSuggestedRefinements 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, 'body') and self.body is not None: - _dict['body'] = self.body.to_dict() - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title.to_dict() + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count return _dict def _to_dict(self): @@ -2612,60 +4977,76 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShown object.""" + """Return a `str` version of this DefaultQueryParamsSuggestedRefinements object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShown') -> bool: + def __eq__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> 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: 'ComponentSettingsFieldsShown') -> bool: + def __ne__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsFieldsShownBody(): +class DefaultQueryParamsTableResults(): """ - Body label. + Default project query settings for table results. - :attr bool use_passage: (optional) Use the whole passage as the body. - :attr str field: (optional) Use a specific field as the title. + :attr bool enabled: (optional) When `true`, a table results for the query are + returned by default. + :attr int count: (optional) The number of table results to return by default. + :attr int per_document: (optional) The number of table results to include in + each result document. """ - def __init__(self, *, use_passage: bool = None, field: str = None) -> None: + def __init__(self, + *, + enabled: bool = None, + count: int = None, + per_document: int = None) -> None: """ - Initialize a ComponentSettingsFieldsShownBody object. + Initialize a DefaultQueryParamsTableResults object. - :param bool use_passage: (optional) Use the whole passage as the body. - :param str field: (optional) Use a specific field as the title. + :param bool enabled: (optional) When `true`, a table results for the query + are returned by default. + :param int count: (optional) The number of table results to return by + default. + :param int per_document: (optional) The number of table results to include + in each result document. """ - self.use_passage = use_passage - self.field = field + self.enabled = enabled + self.count = count + self.per_document = per_document @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': - """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsTableResults': + """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" args = {} - if 'use_passage' in _dict: - args['use_passage'] = _dict.get('use_passage') - if 'field' in _dict: - args['field'] = _dict.get('field') + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'count' in _dict: + args['count'] = _dict.get('count') + if 'per_document' in _dict: + args['per_document'] = _dict.get('per_document') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" + """Initialize a DefaultQueryParamsTableResults 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, 'use_passage') and self.use_passage is not None: - _dict['use_passage'] = self.use_passage - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field + if hasattr(self, 'enabled') and self.enabled is not None: + _dict['enabled'] = self.enabled + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count + if hasattr(self, 'per_document') and self.per_document is not None: + _dict['per_document'] = self.per_document return _dict def _to_dict(self): @@ -2673,53 +5054,62 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShownBody object.""" + """Return a `str` version of this DefaultQueryParamsTableResults object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: + def __eq__(self, other: 'DefaultQueryParamsTableResults') -> 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: 'ComponentSettingsFieldsShownBody') -> bool: + def __ne__(self, other: 'DefaultQueryParamsTableResults') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ComponentSettingsFieldsShownTitle(): +class DeleteDocumentResponse(): """ - Title label. + Information returned when a document is deleted. - :attr str field: (optional) Use a specific field as the title. + :attr str document_id: (optional) The unique identifier of the document. + :attr str status: (optional) Status of the document. A deleted document has the + status deleted. """ - def __init__(self, *, field: str = None) -> None: + def __init__(self, *, document_id: str = None, status: str = None) -> None: """ - Initialize a ComponentSettingsFieldsShownTitle object. + Initialize a DeleteDocumentResponse object. - :param str field: (optional) Use a specific field as the title. + :param str document_id: (optional) The unique identifier of the document. + :param str status: (optional) Status of the document. A deleted document + has the status deleted. """ - self.field = field + self.document_id = document_id + self.status = status @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': - """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': + """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'status' in _dict: + args['status'] = _dict.get('status') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" + """Initialize a DeleteDocumentResponse 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, 'field') and self.field is not None: - _dict['field'] = self.field + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status return _dict def _to_dict(self): @@ -2727,101 +5117,74 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsFieldsShownTitle object.""" + """Return a `str` version of this DeleteDocumentResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: + def __eq__(self, other: 'DeleteDocumentResponse') -> 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: 'ComponentSettingsFieldsShownTitle') -> bool: + def __ne__(self, other: 'DeleteDocumentResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + Status of the document. A deleted document has the status deleted. + """ + DELETED = 'deleted' + -class ComponentSettingsResponse(): +class DocumentAccepted(): """ - The default component settings for this project. + Information returned after an uploaded document is accepted. - :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the - results section of the UI. - :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. - :attr bool structured_search: (optional) Whether or not structured search is - enabled. - :attr int results_per_page: (optional) Number or results shown per page. - :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of - component setting aggregations. + :attr str document_id: (optional) The unique identifier of the ingested + document. + :attr str status: (optional) Status of the document in the ingestion process. A + status of `processing` is returned for documents that are ingested with a + *version* date before `2019-01-01`. The `pending` status is returned for all + others. """ - def __init__( - self, - *, - fields_shown: 'ComponentSettingsFieldsShown' = None, - autocomplete: bool = None, - structured_search: bool = None, - results_per_page: int = None, - aggregations: List['ComponentSettingsAggregation'] = None) -> None: + def __init__(self, *, document_id: str = None, status: str = None) -> None: """ - Initialize a ComponentSettingsResponse object. + Initialize a DocumentAccepted object. - :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown - in the results section of the UI. - :param bool autocomplete: (optional) Whether or not autocomplete is - enabled. - :param bool structured_search: (optional) Whether or not structured search - is enabled. - :param int results_per_page: (optional) Number or results shown per page. - :param List[ComponentSettingsAggregation] aggregations: (optional) a list - of component setting aggregations. + :param str document_id: (optional) The unique identifier of the ingested + document. + :param str status: (optional) Status of the document in the ingestion + process. A status of `processing` is returned for documents that are + ingested with a *version* date before `2019-01-01`. The `pending` status is + returned for all others. """ - self.fields_shown = fields_shown - self.autocomplete = autocomplete - self.structured_search = structured_search - self.results_per_page = results_per_page - self.aggregations = aggregations + self.document_id = document_id + self.status = status @classmethod - def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': - """Initialize a ComponentSettingsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': + """Initialize a DocumentAccepted object from a json dictionary.""" args = {} - if 'fields_shown' in _dict: - args['fields_shown'] = ComponentSettingsFieldsShown.from_dict( - _dict.get('fields_shown')) - if 'autocomplete' in _dict: - args['autocomplete'] = _dict.get('autocomplete') - if 'structured_search' in _dict: - args['structured_search'] = _dict.get('structured_search') - if 'results_per_page' in _dict: - args['results_per_page'] = _dict.get('results_per_page') - if 'aggregations' in _dict: - args['aggregations'] = [ - ComponentSettingsAggregation.from_dict(x) - for x in _dict.get('aggregations') - ] + if 'document_id' in _dict: + args['document_id'] = _dict.get('document_id') + if 'status' in _dict: + args['status'] = _dict.get('status') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ComponentSettingsResponse object from a json dictionary.""" + """Initialize a DocumentAccepted 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, 'fields_shown') and self.fields_shown is not None: - _dict['fields_shown'] = self.fields_shown.to_dict() - if hasattr(self, 'autocomplete') and self.autocomplete is not None: - _dict['autocomplete'] = self.autocomplete - if hasattr(self, - 'structured_search') and self.structured_search is not None: - _dict['structured_search'] = self.structured_search - if hasattr(self, - 'results_per_page') and self.results_per_page is not None: - _dict['results_per_page'] = self.results_per_page - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + if hasattr(self, 'document_id') and self.document_id is not None: + _dict['document_id'] = self.document_id + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status return _dict def _to_dict(self): @@ -2829,84 +5192,85 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ComponentSettingsResponse object.""" + """Return a `str` version of this DocumentAccepted object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ComponentSettingsResponse') -> bool: + def __eq__(self, other: 'DocumentAccepted') -> 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: 'ComponentSettingsResponse') -> bool: + def __ne__(self, other: 'DocumentAccepted') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + Status of the document in the ingestion process. A status of `processing` is + returned for documents that are ingested with a *version* date before + `2019-01-01`. The `pending` status is returned for all others. + """ + PROCESSING = 'processing' + PENDING = 'pending' + -class CreateEnrichment(): +class DocumentAttribute(): """ - Information about a specific enrichment. + List of document attributes. - :attr str name: (optional) The human readable name for this enrichment. - :attr str description: (optional) The description of this enrichment. - :attr str type: (optional) The type of this enrichment. - :attr EnrichmentOptions options: (optional) An object that contains options for - the current enrichment. Starting with version `2020-08-30`, the enrichment - options are not included in responses from the List Enrichments method. + :attr str type: (optional) The type of attribute. + :attr str text: (optional) The text associated with the attribute. + :attr TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. """ def __init__(self, *, - name: str = None, - description: str = None, type: str = None, - options: 'EnrichmentOptions' = None) -> None: + text: str = None, + location: 'TableElementLocation' = None) -> None: """ - Initialize a CreateEnrichment object. + Initialize a DocumentAttribute object. - :param str name: (optional) The human readable name for this enrichment. - :param str description: (optional) The description of this enrichment. - :param str type: (optional) The type of this enrichment. - :param EnrichmentOptions options: (optional) An object that contains - options for the current enrichment. Starting with version `2020-08-30`, the - enrichment options are not included in responses from the List Enrichments - method. + :param str type: (optional) The type of attribute. + :param str text: (optional) The text associated with the attribute. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. """ - self.name = name - self.description = description self.type = type - self.options = options + self.text = text + self.location = location @classmethod - def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': - """Initialize a CreateEnrichment object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': + """Initialize a DocumentAttribute object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') if 'type' in _dict: args['type'] = _dict.get('type') - if 'options' in _dict: - args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'location' in _dict: + args['location'] = TableElementLocation.from_dict( + _dict.get('location')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CreateEnrichment object from a json dictionary.""" + """Initialize a DocumentAttribute 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + _dict['type'] = self.type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -2914,167 +5278,182 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CreateEnrichment object.""" + """Return a `str` version of this DocumentAttribute object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CreateEnrichment') -> bool: + def __eq__(self, other: 'DocumentAttribute') -> 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: 'CreateEnrichment') -> bool: + def __ne__(self, other: 'DocumentAttribute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of this enrichment. - """ - DICTIONARY = 'dictionary' - REGULAR_EXPRESSION = 'regular_expression' - UIMA_ANNOTATOR = 'uima_annotator' - RULE_BASED = 'rule_based' - WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' - - -class DefaultQueryParams(): - """ - Default query parameters for this project. - :attr List[str] collection_ids: (optional) An array of collection identifiers to - query. If empty or omitted all collections in the project are queried. - :attr DefaultQueryParamsPassages passages: (optional) Default settings - configuration for passage search options. - :attr DefaultQueryParamsTableResults table_results: (optional) Default project - query settings for table results. - :attr str aggregation: (optional) A string representing the default aggregation - query for the project. - :attr DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) - Object that contains suggested refinement settings. Available with Premium plans - only. - :attr bool spelling_suggestions: (optional) When `true`, a spelling suggestions - for the query are returned by default. - :attr bool highlight: (optional) When `true`, a highlights for the query are - returned by default. - :attr int count: (optional) The number of document results returned by default. - :attr str sort: (optional) A comma separated list of document fields to sort - results by default. - :attr List[str] return_: (optional) An array of field names to return in - document results if present by default. +class DocumentClassifier(): + """ + Information about a document classifier. + + :attr str classifier_id: (optional) A unique identifier of the document + classifier. + :attr str name: A human-readable name of the document classifier. + :attr str description: (optional) A description of the document classifier. + :attr datetime created: (optional) The date that the document classifier was + created. + :attr str language: (optional) The language of the training data that is + associated with the document classifier. Language is specified by using the ISO + 639-1 language code, such as `en` for English or `ja` for Japanese. + :attr List[DocumentClassifierEnrichment] enrichments: (optional) An array of + enrichments to apply to the data that is used to train and test the document + classifier. The output from the enrichments is used as features by the + classifier to classify the document content both during training and at run + time. + :attr List[str] recognized_fields: (optional) An array of fields that are used + to train the document classifier. The same set of fields must exist in the + training data, the test data, and the documents where the resulting document + classifier enrichment is applied at run time. + :attr str answer_field: (optional) The name of the field from the training and + test data that contains the classification labels. + :attr str training_data_file: (optional) Name of the CSV file with training data + that is used to train the document classifier. + :attr str test_data_file: (optional) Name of the CSV file with data that is used + to test the document classifier. If no test data is provided, a subset of the + training data is used for testing purposes. + :attr ClassifierFederatedModel federated_classification: (optional) An object + with details for creating federated document classifier models. """ - def __init__(self, - *, - collection_ids: List[str] = None, - passages: 'DefaultQueryParamsPassages' = None, - table_results: 'DefaultQueryParamsTableResults' = None, - aggregation: str = None, - suggested_refinements: - 'DefaultQueryParamsSuggestedRefinements' = None, - spelling_suggestions: bool = None, - highlight: bool = None, - count: int = None, - sort: str = None, - return_: List[str] = None) -> None: - """ - Initialize a DefaultQueryParams object. - - :param List[str] collection_ids: (optional) An array of collection - identifiers to query. If empty or omitted all collections in the project - are queried. - :param DefaultQueryParamsPassages passages: (optional) Default settings - configuration for passage search options. - :param DefaultQueryParamsTableResults table_results: (optional) Default - project query settings for table results. - :param str aggregation: (optional) A string representing the default - aggregation query for the project. - :param DefaultQueryParamsSuggestedRefinements suggested_refinements: - (optional) Object that contains suggested refinement settings. Available - with Premium plans only. - :param bool spelling_suggestions: (optional) When `true`, a spelling - suggestions for the query are returned by default. - :param bool highlight: (optional) When `true`, a highlights for the query - are returned by default. - :param int count: (optional) The number of document results returned by - default. - :param str sort: (optional) A comma separated list of document fields to - sort results by default. - :param List[str] return_: (optional) An array of field names to return in - document results if present by default. + def __init__( + self, + name: str, + *, + classifier_id: str = None, + description: str = None, + created: datetime = None, + language: str = None, + enrichments: List['DocumentClassifierEnrichment'] = None, + recognized_fields: List[str] = None, + answer_field: str = None, + training_data_file: str = None, + test_data_file: str = None, + federated_classification: 'ClassifierFederatedModel' = None + ) -> None: """ - self.collection_ids = collection_ids - self.passages = passages - self.table_results = table_results - self.aggregation = aggregation - self.suggested_refinements = suggested_refinements - self.spelling_suggestions = spelling_suggestions - self.highlight = highlight - self.count = count - self.sort = sort - self.return_ = return_ + Initialize a DocumentClassifier object. + + :param str name: A human-readable name of the document classifier. + :param str description: (optional) A description of the document + classifier. + :param str language: (optional) The language of the training data that is + associated with the document classifier. Language is specified by using the + ISO 639-1 language code, such as `en` for English or `ja` for Japanese. + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array + of enrichments to apply to the data that is used to train and test the + document classifier. The output from the enrichments is used as features by + the classifier to classify the document content both during training and at + run time. + :param List[str] recognized_fields: (optional) An array of fields that are + used to train the document classifier. The same set of fields must exist in + the training data, the test data, and the documents where the resulting + document classifier enrichment is applied at run time. + :param str answer_field: (optional) The name of the field from the training + and test data that contains the classification labels. + :param str training_data_file: (optional) Name of the CSV file with + training data that is used to train the document classifier. + :param str test_data_file: (optional) Name of the CSV file with data that + is used to test the document classifier. If no test data is provided, a + subset of the training data is used for testing purposes. + :param ClassifierFederatedModel federated_classification: (optional) An + object with details for creating federated document classifier models. + """ + self.classifier_id = classifier_id + self.name = name + self.description = description + self.created = created + self.language = language + self.enrichments = enrichments + self.recognized_fields = recognized_fields + self.answer_field = answer_field + self.training_data_file = training_data_file + self.test_data_file = test_data_file + self.federated_classification = federated_classification @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParams': - """Initialize a DefaultQueryParams object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifier': + """Initialize a DocumentClassifier object from a json dictionary.""" args = {} - if 'collection_ids' in _dict: - args['collection_ids'] = _dict.get('collection_ids') - if 'passages' in _dict: - args['passages'] = DefaultQueryParamsPassages.from_dict( - _dict.get('passages')) - if 'table_results' in _dict: - args['table_results'] = DefaultQueryParamsTableResults.from_dict( - _dict.get('table_results')) - if 'aggregation' in _dict: - args['aggregation'] = _dict.get('aggregation') - if 'suggested_refinements' in _dict: + if 'classifier_id' in _dict: + args['classifier_id'] = _dict.get('classifier_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in DocumentClassifier JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'language' in _dict: + args['language'] = _dict.get('language') + if 'enrichments' in _dict: + args['enrichments'] = [ + DocumentClassifierEnrichment.from_dict(x) + for x in _dict.get('enrichments') + ] + if 'recognized_fields' in _dict: + args['recognized_fields'] = _dict.get('recognized_fields') + if 'answer_field' in _dict: + args['answer_field'] = _dict.get('answer_field') + if 'training_data_file' in _dict: + args['training_data_file'] = _dict.get('training_data_file') + if 'test_data_file' in _dict: + args['test_data_file'] = _dict.get('test_data_file') + if 'federated_classification' in _dict: args[ - 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements.from_dict( - _dict.get('suggested_refinements')) - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'highlight' in _dict: - args['highlight'] = _dict.get('highlight') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'sort' in _dict: - args['sort'] = _dict.get('sort') - if 'return' in _dict: - args['return_'] = _dict.get('return') + 'federated_classification'] = ClassifierFederatedModel.from_dict( + _dict.get('federated_classification')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParams object from a json dictionary.""" + """Initialize a DocumentClassifier 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, 'collection_ids') and self.collection_ids is not None: - _dict['collection_ids'] = self.collection_ids - if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = self.passages.to_dict() - if hasattr(self, 'table_results') and self.table_results is not None: - _dict['table_results'] = self.table_results.to_dict() - if hasattr(self, 'aggregation') and self.aggregation is not None: - _dict['aggregation'] = self.aggregation - if hasattr(self, 'suggested_refinements' - ) and self.suggested_refinements is not None: - _dict['suggested_refinements'] = self.suggested_refinements.to_dict( - ) - if hasattr(self, 'spelling_suggestions' - ) and self.spelling_suggestions is not None: - _dict['spelling_suggestions'] = self.spelling_suggestions - if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'sort') and self.sort is not None: - _dict['sort'] = self.sort - if hasattr(self, 'return_') and self.return_ is not None: - _dict['return'] = self.return_ + if hasattr(self, 'classifier_id') and getattr( + self, 'classifier_id') is not None: + _dict['classifier_id'] = getattr(self, 'classifier_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'enrichments') and self.enrichments is not None: + _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + if hasattr(self, + 'recognized_fields') and self.recognized_fields is not None: + _dict['recognized_fields'] = self.recognized_fields + if hasattr(self, 'answer_field') and self.answer_field is not None: + _dict['answer_field'] = self.answer_field + if hasattr( + self, + 'training_data_file') and self.training_data_file is not None: + _dict['training_data_file'] = self.training_data_file + if hasattr(self, 'test_data_file') and self.test_data_file is not None: + _dict['test_data_file'] = self.test_data_file + if hasattr(self, 'federated_classification' + ) and self.federated_classification is not None: + _dict[ + 'federated_classification'] = self.federated_classification.to_dict( + ) return _dict def _to_dict(self): @@ -3082,109 +5461,70 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParams object.""" + """Return a `str` version of this DocumentClassifier object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParams') -> bool: + def __eq__(self, other: 'DocumentClassifier') -> 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: 'DefaultQueryParams') -> bool: + def __ne__(self, other: 'DocumentClassifier') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DefaultQueryParamsPassages(): +class DocumentClassifierEnrichment(): """ - Default settings configuration for passage search options. + An object that describes enrichments that are applied to the training and test data + that is used by the document classifier. - :attr bool enabled: (optional) When `true`, a passage search is performed by - default. - :attr int count: (optional) The number of passages to return. - :attr List[str] fields: (optional) An array of field names to perform the - passage search on. - :attr int characters: (optional) The approximate number of characters that each - returned passage will contain. - :attr bool per_document: (optional) When `true` the number of passages that can - be returned from a single document is restricted to the *max_per_document* - value. - :attr int max_per_document: (optional) The default maximum number of passages - that can be taken from a single document as the result of a passage query. + :attr str enrichment_id: A unique identifier of the enrichment. + :attr List[str] fields: An array of field names where the enrichment is applied. """ - def __init__(self, - *, - enabled: bool = None, - count: int = None, - fields: List[str] = None, - characters: int = None, - per_document: bool = None, - max_per_document: int = None) -> None: + def __init__(self, enrichment_id: str, fields: List[str]) -> None: """ - Initialize a DefaultQueryParamsPassages object. + Initialize a DocumentClassifierEnrichment object. - :param bool enabled: (optional) When `true`, a passage search is performed - by default. - :param int count: (optional) The number of passages to return. - :param List[str] fields: (optional) An array of field names to perform the - passage search on. - :param int characters: (optional) The approximate number of characters that - each returned passage will contain. - :param bool per_document: (optional) When `true` the number of passages - that can be returned from a single document is restricted to the - *max_per_document* value. - :param int max_per_document: (optional) The default maximum number of - passages that can be taken from a single document as the result of a - passage query. + :param str enrichment_id: A unique identifier of the enrichment. + :param List[str] fields: An array of field names where the enrichment is + applied. """ - self.enabled = enabled - self.count = count + self.enrichment_id = enrichment_id self.fields = fields - self.characters = characters - self.per_document = per_document - self.max_per_document = max_per_document @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsPassages': - """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifierEnrichment': + """Initialize a DocumentClassifierEnrichment object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if 'enrichment_id' in _dict: + args['enrichment_id'] = _dict.get('enrichment_id') + else: + raise ValueError( + 'Required property \'enrichment_id\' not present in DocumentClassifierEnrichment JSON' + ) if 'fields' in _dict: args['fields'] = _dict.get('fields') - if 'characters' in _dict: - args['characters'] = _dict.get('characters') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') - if 'max_per_document' in _dict: - args['max_per_document'] = _dict.get('max_per_document') + else: + raise ValueError( + 'Required property \'fields\' not present in DocumentClassifierEnrichment JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" + """Initialize a DocumentClassifierEnrichment 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 - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = self.fields - if hasattr(self, 'characters') and self.characters is not None: - _dict['characters'] = self.characters - if hasattr(self, 'per_document') and self.per_document is not None: - _dict['per_document'] = self.per_document - if hasattr(self, - 'max_per_document') and self.max_per_document is not None: - _dict['max_per_document'] = self.max_per_document + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields return _dict def _to_dict(self): @@ -3192,64 +5532,157 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParamsPassages object.""" + """Return a `str` version of this DocumentClassifierEnrichment object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParamsPassages') -> bool: + def __eq__(self, other: 'DocumentClassifierEnrichment') -> 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: 'DefaultQueryParamsPassages') -> bool: + def __ne__(self, other: 'DocumentClassifierEnrichment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DefaultQueryParamsSuggestedRefinements(): - """ - Object that contains suggested refinement settings. Available with Premium plans only. - - :attr bool enabled: (optional) When `true`, suggested refinements for the query - are returned by default. - :attr int count: (optional) The number of suggested refinements to return by - default. +class DocumentClassifierModel(): + """ + Information about a document classifier model. + + :attr str model_id: (optional) A unique identifier of the document classifier + model. + :attr str name: A human-readable name of the document classifier model. + :attr str description: (optional) A description of the document classifier + model. + :attr datetime created: (optional) The date that the document classifier model + was created. + :attr datetime updated: (optional) The date that the document classifier model + was last updated. + :attr str training_data_file: (optional) Name of the CSV file that contains the + training data that is used to train the document classifier model. + :attr str test_data_file: (optional) Name of the CSV file that contains data + that is used to test the document classifier model. If no test data is provided, + a subset of the training data is used for testing purposes. + :attr str status: (optional) The status of the training run. + :attr ClassifierModelEvaluation evaluation: (optional) An object that contains + information about a trained document classifier model. + :attr str enrichment_id: (optional) A unique identifier of the enrichment that + is generated by this document classifier model. + :attr datetime deployed_at: (optional) The date that the document classifier + model was deployed. """ - def __init__(self, *, enabled: bool = None, count: int = None) -> None: - """ - Initialize a DefaultQueryParamsSuggestedRefinements object. - - :param bool enabled: (optional) When `true`, suggested refinements for the - query are returned by default. - :param int count: (optional) The number of suggested refinements to return - by default. - """ - self.enabled = enabled - self.count = count + def __init__(self, + name: str, + *, + model_id: str = None, + description: str = None, + created: datetime = None, + updated: datetime = None, + training_data_file: str = None, + test_data_file: str = None, + status: str = None, + evaluation: 'ClassifierModelEvaluation' = None, + enrichment_id: str = None, + deployed_at: datetime = None) -> None: + """ + Initialize a DocumentClassifierModel object. + + :param str name: A human-readable name of the document classifier model. + :param str description: (optional) A description of the document classifier + model. + :param str training_data_file: (optional) Name of the CSV file that + contains the training data that is used to train the document classifier + model. + :param str test_data_file: (optional) Name of the CSV file that contains + data that is used to test the document classifier model. If no test data is + provided, a subset of the training data is used for testing purposes. + :param str status: (optional) The status of the training run. + :param ClassifierModelEvaluation evaluation: (optional) An object that + contains information about a trained document classifier model. + :param str enrichment_id: (optional) A unique identifier of the enrichment + that is generated by this document classifier model. + """ + self.model_id = model_id + self.name = name + self.description = description + self.created = created + self.updated = updated + self.training_data_file = training_data_file + self.test_data_file = test_data_file + self.status = status + self.evaluation = evaluation + self.enrichment_id = enrichment_id + self.deployed_at = deployed_at @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsSuggestedRefinements': - """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifierModel': + """Initialize a DocumentClassifierModel object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if 'model_id' in _dict: + args['model_id'] = _dict.get('model_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in DocumentClassifierModel JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + if 'training_data_file' in _dict: + args['training_data_file'] = _dict.get('training_data_file') + if 'test_data_file' in _dict: + args['test_data_file'] = _dict.get('test_data_file') + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'evaluation' in _dict: + args['evaluation'] = ClassifierModelEvaluation.from_dict( + _dict.get('evaluation')) + if 'enrichment_id' in _dict: + args['enrichment_id'] = _dict.get('enrichment_id') + if 'deployed_at' in _dict: + args['deployed_at'] = string_to_datetime(_dict.get('deployed_at')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" + """Initialize a DocumentClassifierModel 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 - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count + if hasattr(self, 'model_id') and getattr(self, 'model_id') is not None: + _dict['model_id'] = getattr(self, 'model_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + if hasattr( + self, + 'training_data_file') and self.training_data_file is not None: + _dict['training_data_file'] = self.training_data_file + if hasattr(self, 'test_data_file') and self.test_data_file is not None: + _dict['test_data_file'] = self.test_data_file + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + if hasattr(self, 'evaluation') and self.evaluation is not None: + _dict['evaluation'] = self.evaluation.to_dict() + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + if hasattr(self, 'deployed_at') and getattr(self, + 'deployed_at') is not None: + _dict['deployed_at'] = datetime_to_string( + getattr(self, 'deployed_at')) return _dict def _to_dict(self): @@ -3257,76 +5690,68 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParamsSuggestedRefinements object.""" + """Return a `str` version of this DocumentClassifierModel object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: + def __eq__(self, other: 'DocumentClassifierModel') -> 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: 'DefaultQueryParamsSuggestedRefinements') -> bool: + def __ne__(self, other: 'DocumentClassifierModel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The status of the training run. + """ + TRAINING = 'training' + AVAILABLE = 'available' + FAILED = 'failed' + -class DefaultQueryParamsTableResults(): +class DocumentClassifierModels(): """ - Default project query settings for table results. + An object that contains a list of document classifier model definitions. - :attr bool enabled: (optional) When `true`, a table results for the query are - returned by default. - :attr int count: (optional) The number of table results to return by default. - :attr int per_document: (optional) The number of table results to include in - each result document. + :attr List[DocumentClassifierModel] models: (optional) An array of document + classifier model definitions. """ def __init__(self, *, - enabled: bool = None, - count: int = None, - per_document: int = None) -> None: + models: List['DocumentClassifierModel'] = None) -> None: """ - Initialize a DefaultQueryParamsTableResults object. + Initialize a DocumentClassifierModels object. - :param bool enabled: (optional) When `true`, a table results for the query - are returned by default. - :param int count: (optional) The number of table results to return by - default. - :param int per_document: (optional) The number of table results to include - in each result document. + :param List[DocumentClassifierModel] models: (optional) An array of + document classifier model definitions. """ - self.enabled = enabled - self.count = count - self.per_document = per_document + self.models = models @classmethod - def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsTableResults': - """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifierModels': + """Initialize a DocumentClassifierModels object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') + if 'models' in _dict: + args['models'] = [ + DocumentClassifierModel.from_dict(x) + for x in _dict.get('models') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" + """Initialize a DocumentClassifierModels 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 - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'per_document') and self.per_document is not None: - _dict['per_document'] = self.per_document + if hasattr(self, 'models') and self.models is not None: + _dict['models'] = [x.to_dict() for x in self.models] return _dict def _to_dict(self): @@ -3334,62 +5759,60 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DefaultQueryParamsTableResults object.""" + """Return a `str` version of this DocumentClassifierModels object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DefaultQueryParamsTableResults') -> bool: + def __eq__(self, other: 'DocumentClassifierModels') -> 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: 'DefaultQueryParamsTableResults') -> bool: + def __ne__(self, other: 'DocumentClassifierModels') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DeleteDocumentResponse(): +class DocumentClassifiers(): """ - Information returned when a document is deleted. + An object that contains a list of document classifier definitions. - :attr str document_id: (optional) The unique identifier of the document. - :attr str status: (optional) Status of the document. A deleted document has the - status deleted. + :attr List[DocumentClassifier] classifiers: (optional) An array of document + classifier definitions. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__(self, + *, + classifiers: List['DocumentClassifier'] = None) -> None: """ - Initialize a DeleteDocumentResponse object. + Initialize a DocumentClassifiers object. - :param str document_id: (optional) The unique identifier of the document. - :param str status: (optional) Status of the document. A deleted document - has the status deleted. + :param List[DocumentClassifier] classifiers: (optional) An array of + document classifier definitions. """ - self.document_id = document_id - self.status = status + self.classifiers = classifiers @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': - """Initialize a DeleteDocumentResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentClassifiers': + """Initialize a DocumentClassifiers object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if 'classifiers' in _dict: + args['classifiers'] = [ + DocumentClassifier.from_dict(x) + for x in _dict.get('classifiers') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DeleteDocumentResponse object from a json dictionary.""" + """Initialize a DocumentClassifiers 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, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status + if hasattr(self, 'classifiers') and self.classifiers is not None: + _dict['classifiers'] = [x.to_dict() for x in self.classifiers] return _dict def _to_dict(self): @@ -3397,74 +5820,154 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DeleteDocumentResponse object.""" + """Return a `str` version of this DocumentClassifiers object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DeleteDocumentResponse') -> bool: + def __eq__(self, other: 'DocumentClassifiers') -> 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: 'DeleteDocumentResponse') -> bool: + def __ne__(self, other: 'DocumentClassifiers') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - Status of the document. A deleted document has the status deleted. - """ - DELETED = 'deleted' - -class DocumentAccepted(): +class DocumentDetails(): """ - Information returned after an uploaded document is accepted. + Information about a document. - :attr str document_id: (optional) The unique identifier of the ingested - document. - :attr str status: (optional) Status of the document in the ingestion process. A - status of `processing` is returned for documents that are ingested with a - *version* date before `2019-01-01`. The `pending` status is returned for all - others. + :attr str document_id: (optional) The unique identifier of the document. + :attr datetime created: (optional) Date and time that the document is added to + the collection. For a child document, the date and time when the process that + generates the child document runs. The date-time format is + `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. + :attr datetime updated: (optional) Date and time that the document is finished + being processed and is indexed. This date changes whenever the document is + reprocessed, including for enrichment changes. The date-time format is + `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. + :attr str status: (optional) The status of the ingestion of the document. The + possible values are: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because of an + error. + * `pending`: The document is uploaded, but the ingestion process is not started. + * `processing`: Ingestion is in progress. + :attr List[Notice] notices: (optional) Array of JSON objects for notices, + meaning warning or error messages, that are produced by the document ingestion + process. The array does not include notices that are produced for child + documents that are generated when a document is processed. + :attr DocumentDetailsChildren children: (optional) Information about the child + documents that are generated from a single document during ingestion or other + processing. + :attr str filename: (optional) Name of the original source file (if available). + :attr str file_type: (optional) The type of the original source file, such as + `csv`, `excel`, `html`, `json`, `pdf`, `text`, `word`, and so on. + :attr str sha256: (optional) The SHA-256 hash of the original source file. The + hash is formatted as a hexadecimal string. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: - """ - Initialize a DocumentAccepted object. - - :param str document_id: (optional) The unique identifier of the ingested - document. - :param str status: (optional) Status of the document in the ingestion - process. A status of `processing` is returned for documents that are - ingested with a *version* date before `2019-01-01`. The `pending` status is - returned for all others. + def __init__(self, + *, + document_id: str = None, + created: datetime = None, + updated: datetime = None, + status: str = None, + notices: List['Notice'] = None, + children: 'DocumentDetailsChildren' = None, + filename: str = None, + file_type: str = None, + sha256: str = None) -> None: + """ + Initialize a DocumentDetails object. + + :param str status: (optional) The status of the ingestion of the document. + The possible values are: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because + of an error. + * `pending`: The document is uploaded, but the ingestion process is not + started. + * `processing`: Ingestion is in progress. + :param List[Notice] notices: (optional) Array of JSON objects for notices, + meaning warning or error messages, that are produced by the document + ingestion process. The array does not include notices that are produced for + child documents that are generated when a document is processed. + :param DocumentDetailsChildren children: (optional) Information about the + child documents that are generated from a single document during ingestion + or other processing. + :param str filename: (optional) Name of the original source file (if + available). + :param str file_type: (optional) The type of the original source file, such + as `csv`, `excel`, `html`, `json`, `pdf`, `text`, `word`, and so on. + :param str sha256: (optional) The SHA-256 hash of the original source file. + The hash is formatted as a hexadecimal string. """ self.document_id = document_id + self.created = created + self.updated = updated self.status = status + self.notices = notices + self.children = children + self.filename = filename + self.file_type = file_type + self.sha256 = sha256 @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': - """Initialize a DocumentAccepted object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentDetails': + """Initialize a DocumentDetails object from a json dictionary.""" args = {} if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) if 'status' in _dict: args['status'] = _dict.get('status') + if 'notices' in _dict: + args['notices'] = [ + Notice.from_dict(x) for x in _dict.get('notices') + ] + if 'children' in _dict: + args['children'] = DocumentDetailsChildren.from_dict( + _dict.get('children')) + if 'filename' in _dict: + args['filename'] = _dict.get('filename') + if 'file_type' in _dict: + args['file_type'] = _dict.get('file_type') + if 'sha256' in _dict: + args['sha256'] = _dict.get('sha256') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DocumentAccepted object from a json dictionary.""" + """Initialize a DocumentDetails 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, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id + if hasattr(self, 'document_id') and getattr(self, + 'document_id') is not None: + _dict['document_id'] = getattr(self, 'document_id') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status + if hasattr(self, 'notices') and self.notices is not None: + _dict['notices'] = [x.to_dict() for x in self.notices] + if hasattr(self, 'children') and self.children is not None: + _dict['children'] = self.children.to_dict() + if hasattr(self, 'filename') and self.filename is not None: + _dict['filename'] = self.filename + if hasattr(self, 'file_type') and self.file_type is not None: + _dict['file_type'] = self.file_type + if hasattr(self, 'sha256') and self.sha256 is not None: + _dict['sha256'] = self.sha256 return _dict def _to_dict(self): @@ -3472,85 +5975,80 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DocumentAccepted object.""" + """Return a `str` version of this DocumentDetails object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DocumentAccepted') -> bool: + def __eq__(self, other: 'DocumentDetails') -> 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: 'DocumentAccepted') -> bool: + def __ne__(self, other: 'DocumentDetails') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class StatusEnum(str, Enum): """ - Status of the document in the ingestion process. A status of `processing` is - returned for documents that are ingested with a *version* date before - `2019-01-01`. The `pending` status is returned for all others. + The status of the ingestion of the document. The possible values are: + * `available`: Ingestion is finished and the document is indexed. + * `failed`: Ingestion is finished, but the document is not indexed because of an + error. + * `pending`: The document is uploaded, but the ingestion process is not started. + * `processing`: Ingestion is in progress. """ - PROCESSING = 'processing' + AVAILABLE = 'available' + FAILED = 'failed' PENDING = 'pending' + PROCESSING = 'processing' -class DocumentAttribute(): +class DocumentDetailsChildren(): """ - List of document attributes. + Information about the child documents that are generated from a single document during + ingestion or other processing. - :attr str type: (optional) The type of attribute. - :attr str text: (optional) The text associated with the attribute. - :attr TableElementLocation location: (optional) The numeric location of the - identified element in the document, represented with two integers labeled - `begin` and `end`. + :attr bool have_notices: (optional) Indicates whether the child documents have + any notices. The value is `false` if the document does not have child documents. + :attr int count: (optional) Number of child documents. The value is `0` when + processing of the document doesn't generate any child documents. """ - def __init__(self, - *, - type: str = None, - text: str = None, - location: 'TableElementLocation' = None) -> None: + def __init__(self, *, have_notices: bool = None, count: int = None) -> None: """ - Initialize a DocumentAttribute object. + Initialize a DocumentDetailsChildren object. - :param str type: (optional) The type of attribute. - :param str text: (optional) The text associated with the attribute. - :param TableElementLocation location: (optional) The numeric location of - the identified element in the document, represented with two integers - labeled `begin` and `end`. + :param bool have_notices: (optional) Indicates whether the child documents + have any notices. The value is `false` if the document does not have child + documents. + :param int count: (optional) Number of child documents. The value is `0` + when processing of the document doesn't generate any child documents. """ - self.type = type - self.text = text - self.location = location + self.have_notices = have_notices + self.count = count @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': - """Initialize a DocumentAttribute object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DocumentDetailsChildren': + """Initialize a DocumentDetailsChildren object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) + if 'have_notices' in _dict: + args['have_notices'] = _dict.get('have_notices') + if 'count' in _dict: + args['count'] = _dict.get('count') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DocumentAttribute object from a json dictionary.""" + """Initialize a DocumentDetailsChildren 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 - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if hasattr(self, 'have_notices') and self.have_notices is not None: + _dict['have_notices'] = self.have_notices + if hasattr(self, 'count') and self.count is not None: + _dict['count'] = self.count return _dict def _to_dict(self): @@ -3558,16 +6056,16 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DocumentAttribute object.""" + """Return a `str` version of this DocumentDetailsChildren object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DocumentAttribute') -> bool: + def __eq__(self, other: 'DocumentDetailsChildren') -> 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: 'DocumentAttribute') -> bool: + def __ne__(self, other: 'DocumentDetailsChildren') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -3676,6 +6174,7 @@ class TypeEnum(str, Enum): UIMA_ANNOTATOR = 'uima_annotator' RULE_BASED = 'rule_based' WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' + CLASSIFIER = 'classifier' class EnrichmentOptions(): @@ -3685,17 +6184,35 @@ class EnrichmentOptions(): Enrichments method. :attr List[str] languages: (optional) An array of supported languages for this - enrichment. Required when `type` is `dictionary`. Optional when `type` is - `rule_based`. Not valid when creating any other type of enrichment. + enrichment. When creating an enrichment, only specify a language that is used by + the model or in the dictionary. Required when **type** is `dictionary`. Optional + when **type** is `rule_based`. Not valid when creating any other type of + enrichment. :attr str entity_type: (optional) The name of the entity type. This value is - used as the field name in the index. Required when `type` is `dictionary` or + used as the field name in the index. Required when **type** is `dictionary` or `regular_expression`. Not valid when creating any other type of enrichment. :attr str regular_expression: (optional) The regular expression to apply for - this enrichment. Required when `type` is `regular_expression`. Not valid when + this enrichment. Required when **type** is `regular_expression`. Not valid when creating any other type of enrichment. :attr str result_field: (optional) The name of the result document field that - this enrichment creates. Required when `type` is `rule_based`. Not valid when - creating any other type of enrichment. + this enrichment creates. Required when **type** is `rule_based` or `classifier`. + Not valid when creating any other type of enrichment. + :attr str classifier_id: (optional) A unique identifier of the document + classifier. Required when **type** is `classifier`. Not valid when creating any + other type of enrichment. + :attr str model_id: (optional) A unique identifier of the document classifier + model. Required when **type** is `classifier`. Not valid when creating any other + type of enrichment. + :attr float confidence_threshold: (optional) Specifies a threshold. Only classes + with evaluation confidence scores that are higher than the specified threshold + are included in the output. Optional when **type** is `classifier`. Not valid + when creating any other type of enrichment. + :attr int top_k: (optional) Evaluates only the classes that fall in the top set + of results when ranked by confidence. For example, if set to `5`, then the top + five classes for each document are evaluated. If set to 0, the + **confidence_threshold** is used to determine the predicted classes. Optional + when **type** is `classifier`. Not valid when creating any other type of + enrichment. """ def __init__(self, @@ -3703,28 +6220,54 @@ def __init__(self, languages: List[str] = None, entity_type: str = None, regular_expression: str = None, - result_field: str = None) -> None: + result_field: str = None, + classifier_id: str = None, + model_id: str = None, + confidence_threshold: float = None, + top_k: int = None) -> None: """ Initialize a EnrichmentOptions object. :param List[str] languages: (optional) An array of supported languages for - this enrichment. Required when `type` is `dictionary`. Optional when `type` - is `rule_based`. Not valid when creating any other type of enrichment. + this enrichment. When creating an enrichment, only specify a language that + is used by the model or in the dictionary. Required when **type** is + `dictionary`. Optional when **type** is `rule_based`. Not valid when + creating any other type of enrichment. :param str entity_type: (optional) The name of the entity type. This value - is used as the field name in the index. Required when `type` is + is used as the field name in the index. Required when **type** is `dictionary` or `regular_expression`. Not valid when creating any other type of enrichment. :param str regular_expression: (optional) The regular expression to apply - for this enrichment. Required when `type` is `regular_expression`. Not + for this enrichment. Required when **type** is `regular_expression`. Not valid when creating any other type of enrichment. :param str result_field: (optional) The name of the result document field - that this enrichment creates. Required when `type` is `rule_based`. Not - valid when creating any other type of enrichment. + that this enrichment creates. Required when **type** is `rule_based` or + `classifier`. Not valid when creating any other type of enrichment. + :param str classifier_id: (optional) A unique identifier of the document + classifier. Required when **type** is `classifier`. Not valid when creating + any other type of enrichment. + :param str model_id: (optional) A unique identifier of the document + classifier model. Required when **type** is `classifier`. Not valid when + creating any other type of enrichment. + :param float confidence_threshold: (optional) Specifies a threshold. Only + classes with evaluation confidence scores that are higher than the + specified threshold are included in the output. Optional when **type** is + `classifier`. Not valid when creating any other type of enrichment. + :param int top_k: (optional) Evaluates only the classes that fall in the + top set of results when ranked by confidence. For example, if set to `5`, + then the top five classes for each document are evaluated. If set to 0, the + **confidence_threshold** is used to determine the predicted classes. + Optional when **type** is `classifier`. Not valid when creating any other + type of enrichment. """ self.languages = languages self.entity_type = entity_type self.regular_expression = regular_expression self.result_field = result_field + self.classifier_id = classifier_id + self.model_id = model_id + self.confidence_threshold = confidence_threshold + self.top_k = top_k @classmethod def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': @@ -3738,6 +6281,14 @@ def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': args['regular_expression'] = _dict.get('regular_expression') if 'result_field' in _dict: args['result_field'] = _dict.get('result_field') + if 'classifier_id' in _dict: + args['classifier_id'] = _dict.get('classifier_id') + if 'model_id' in _dict: + args['model_id'] = _dict.get('model_id') + if 'confidence_threshold' in _dict: + args['confidence_threshold'] = _dict.get('confidence_threshold') + if 'top_k' in _dict: + args['top_k'] = _dict.get('top_k') return cls(**args) @classmethod @@ -3758,6 +6309,15 @@ def to_dict(self) -> Dict: _dict['regular_expression'] = self.regular_expression if hasattr(self, 'result_field') and self.result_field is not None: _dict['result_field'] = self.result_field + if hasattr(self, 'classifier_id') and self.classifier_id is not None: + _dict['classifier_id'] = self.classifier_id + if hasattr(self, 'model_id') and self.model_id is not None: + _dict['model_id'] = self.model_id + if hasattr(self, 'confidence_threshold' + ) and self.confidence_threshold is not None: + _dict['confidence_threshold'] = self.confidence_threshold + if hasattr(self, 'top_k') and self.top_k is not None: + _dict['top_k'] = self.top_k return _dict def _to_dict(self): @@ -3837,6 +6397,169 @@ def __ne__(self, other: 'Enrichments') -> bool: return not self == other +class Expansion(): + """ + An expansion definition. Each object respresents one set of expandable strings. For + example, you could have expansions for the word `hot` in one object, and expansions + for the word `cold` in another. Follow these guidelines when you add terms: + * Specify the terms in lowercase. Lowercase terms expand to uppercase. + * Multiword terms are supported only in bidirectional expansions. + * Do not specify a term that is specified in the stop words list for the collection. + + :attr List[str] input_terms: (optional) A list of terms that will be expanded + for this expansion. If specified, only the items in this list are expanded. + :attr List[str] expanded_terms: A list of terms that this expansion will be + expanded to. If specified without **input_terms**, the list also functions as + the input term list. + """ + + def __init__(self, + expanded_terms: List[str], + *, + input_terms: List[str] = None) -> None: + """ + Initialize a Expansion object. + + :param List[str] expanded_terms: A list of terms that this expansion will + be expanded to. If specified without **input_terms**, the list also + functions as the input term list. + :param List[str] input_terms: (optional) A list of terms that will be + expanded for this expansion. If specified, only the items in this list are + expanded. + """ + self.input_terms = input_terms + self.expanded_terms = expanded_terms + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Expansion': + """Initialize a Expansion object from a json dictionary.""" + args = {} + if 'input_terms' in _dict: + args['input_terms'] = _dict.get('input_terms') + if 'expanded_terms' in _dict: + args['expanded_terms'] = _dict.get('expanded_terms') + else: + raise ValueError( + 'Required property \'expanded_terms\' not present in Expansion JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Expansion 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, 'input_terms') and self.input_terms is not None: + _dict['input_terms'] = self.input_terms + if hasattr(self, 'expanded_terms') and self.expanded_terms is not None: + _dict['expanded_terms'] = self.expanded_terms + 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 Expansion object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Expansion') -> 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: 'Expansion') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Expansions(): + """ + The query expansion definitions for the specified collection. + + :attr List[Expansion] expansions: An array of query expansion definitions. + Each object in the **expansions** array represents a term or set of terms that + will be expanded into other terms. Each expansion object can be configured as + `bidirectional` or `unidirectional`. + * **Bidirectional**: Each entry in the `expanded_terms` list expands to include + all expanded terms. For example, a query for `ibm` expands to `ibm OR + international business machines OR big blue`. + * **Unidirectional**: The terms in `input_terms` in the query are replaced by + the terms in `expanded_terms`. For example, a query for the often misused term + `on premise` is converted to `on premises OR on-premises` and does not contain + the original term. If you want an input term to be included in the query, then + repeat the input term in the expanded terms list. + """ + + def __init__(self, expansions: List['Expansion']) -> None: + """ + Initialize a Expansions object. + + :param List[Expansion] expansions: An array of query expansion definitions. + Each object in the **expansions** array represents a term or set of terms + that will be expanded into other terms. Each expansion object can be + configured as `bidirectional` or `unidirectional`. + * **Bidirectional**: Each entry in the `expanded_terms` list expands to + include all expanded terms. For example, a query for `ibm` expands to `ibm + OR international business machines OR big blue`. + * **Unidirectional**: The terms in `input_terms` in the query are replaced + by the terms in `expanded_terms`. For example, a query for the often + misused term `on premise` is converted to `on premises OR on-premises` and + does not contain the original term. If you want an input term to be + included in the query, then repeat the input term in the expanded terms + list. + """ + self.expansions = expansions + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Expansions': + """Initialize a Expansions object from a json dictionary.""" + args = {} + if 'expansions' in _dict: + args['expansions'] = [ + Expansion.from_dict(x) for x in _dict.get('expansions') + ] + else: + raise ValueError( + 'Required property \'expansions\' not present in Expansions JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Expansions 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, 'expansions') and self.expansions is not None: + _dict['expansions'] = [x.to_dict() for x in self.expansions] + 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 Expansions object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Expansions') -> 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: 'Expansions') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Field(): """ Object that contains field details. @@ -3982,47 +6705,271 @@ def __ne__(self, other: 'ListCollectionsResponse') -> bool: return not self == other -class ListFieldsResponse(): +class ListDocumentsResponse(): + """ + Response object that contains an array of documents. + + :attr int matching_results: (optional) The number of matching results for the + document query. + :attr List[DocumentDetails] documents: (optional) An array that lists the + documents in a collection. Only the document ID of each document is returned in + the list. You can use the [Get document](#getdocument) method to get more + information about an individual document. + """ + + def __init__(self, + *, + matching_results: int = None, + documents: List['DocumentDetails'] = None) -> None: + """ + Initialize a ListDocumentsResponse object. + + :param int matching_results: (optional) The number of matching results for + the document query. + :param List[DocumentDetails] documents: (optional) An array that lists the + documents in a collection. Only the document ID of each document is + returned in the list. You can use the [Get document](#getdocument) method + to get more information about an individual document. + """ + self.matching_results = matching_results + self.documents = documents + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListDocumentsResponse': + """Initialize a ListDocumentsResponse object from a json dictionary.""" + args = {} + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + if 'documents' in _dict: + args['documents'] = [ + DocumentDetails.from_dict(x) for x in _dict.get('documents') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListDocumentsResponse 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, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'documents') and self.documents is not None: + _dict['documents'] = [x.to_dict() for x in self.documents] + 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 ListDocumentsResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListDocumentsResponse') -> 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: 'ListDocumentsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ListFieldsResponse(): + """ + The list of fetched fields. + The fields are returned using a fully qualified name format, however, the format + differs slightly from that used by the query operations. + * Fields which contain nested objects are assigned a type of "nested". + * Fields which belong to a nested object are prefixed with `.properties` (for + example, `warnings.properties.severity` means that the `warnings` object has a + property called `severity`). + + :attr List[Field] fields: (optional) An array that contains information about + each field in the collections. + """ + + def __init__(self, *, fields: List['Field'] = None) -> None: + """ + Initialize a ListFieldsResponse object. + + :param List[Field] fields: (optional) An array that contains information + about each field in the collections. + """ + self.fields = fields + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': + """Initialize a ListFieldsResponse object from a json dictionary.""" + args = {} + if 'fields' in _dict: + args['fields'] = [Field.from_dict(x) for x in _dict.get('fields')] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListFieldsResponse 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, 'fields') and self.fields is not None: + _dict['fields'] = [x.to_dict() for x in self.fields] + 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 ListFieldsResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListFieldsResponse') -> 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: 'ListFieldsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ListProjectsResponse(): + """ + A list of projects in this instance. + + :attr List[ProjectListDetails] projects: (optional) An array of project details. + """ + + def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: + """ + Initialize a ListProjectsResponse object. + + :param List[ProjectListDetails] projects: (optional) An array of project + details. + """ + self.projects = projects + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListProjectsResponse': + """Initialize a ListProjectsResponse object from a json dictionary.""" + args = {} + if 'projects' in _dict: + args['projects'] = [ + ProjectListDetails.from_dict(x) for x in _dict.get('projects') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListProjectsResponse 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, 'projects') and self.projects is not None: + _dict['projects'] = [x.to_dict() for x in self.projects] + 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 ListProjectsResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListProjectsResponse') -> 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: 'ListProjectsResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ModelEvaluationMacroAverage(): """ - The list of fetched fields. - The fields are returned using a fully qualified name format, however, the format - differs slightly from that used by the query operations. - * Fields which contain nested objects are assigned a type of "nested". - * Fields which belong to a nested object are prefixed with `.properties` (for - example, `warnings.properties.severity` means that the `warnings` object has a - property called `severity`). + A macro-average computes metric independently for each class and then takes the + average. Class refers to the classification label that is specified in the + **answer_field**. - :attr List[Field] fields: (optional) An array that contains information about - each field in the collections. + :attr float precision: A metric that measures how many of the overall documents + are classified correctly. + :attr float recall: A metric that measures how often documents that should be + classified into certain classes are classified into those classes. + :attr float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a weighted + average of the precision and recall values. An F1 score reaches its best value + at 1 and worst value at 0. """ - def __init__(self, *, fields: List['Field'] = None) -> None: + def __init__(self, precision: float, recall: float, f1: float) -> None: """ - Initialize a ListFieldsResponse object. + Initialize a ModelEvaluationMacroAverage object. - :param List[Field] fields: (optional) An array that contains information - about each field in the collections. + :param float precision: A metric that measures how many of the overall + documents are classified correctly. + :param float recall: A metric that measures how often documents that should + be classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a + weighted average of the precision and recall values. An F1 score reaches + its best value at 1 and worst value at 0. """ - self.fields = fields + self.precision = precision + self.recall = recall + self.f1 = f1 @classmethod - def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': - """Initialize a ListFieldsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ModelEvaluationMacroAverage': + """Initialize a ModelEvaluationMacroAverage object from a json dictionary.""" args = {} - if 'fields' in _dict: - args['fields'] = [Field.from_dict(x) for x in _dict.get('fields')] + if 'precision' in _dict: + args['precision'] = _dict.get('precision') + else: + raise ValueError( + 'Required property \'precision\' not present in ModelEvaluationMacroAverage JSON' + ) + if 'recall' in _dict: + args['recall'] = _dict.get('recall') + else: + raise ValueError( + 'Required property \'recall\' not present in ModelEvaluationMacroAverage JSON' + ) + if 'f1' in _dict: + args['f1'] = _dict.get('f1') + else: + raise ValueError( + 'Required property \'f1\' not present in ModelEvaluationMacroAverage JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ListFieldsResponse object from a json dictionary.""" + """Initialize a ModelEvaluationMacroAverage 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, 'fields') and self.fields is not None: - _dict['fields'] = [x.to_dict() for x in self.fields] + if hasattr(self, 'precision') and self.precision is not None: + _dict['precision'] = self.precision + if hasattr(self, 'recall') and self.recall is not None: + _dict['recall'] = self.recall + if hasattr(self, 'f1') and self.f1 is not None: + _dict['f1'] = self.f1 return _dict def _to_dict(self): @@ -4030,56 +6977,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ListFieldsResponse object.""" + """Return a `str` version of this ModelEvaluationMacroAverage object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ListFieldsResponse') -> bool: + def __eq__(self, other: 'ModelEvaluationMacroAverage') -> 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: 'ListFieldsResponse') -> bool: + def __ne__(self, other: 'ModelEvaluationMacroAverage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ListProjectsResponse(): +class ModelEvaluationMicroAverage(): """ - A list of projects in this instance. + A micro-average aggregates the contributions of all classes to compute the average + metric. Classes refers to the classification labels that are specified in the + **answer_field**. - :attr List[ProjectListDetails] projects: (optional) An array of project details. + :attr float precision: A metric that measures how many of the overall documents + are classified correctly. + :attr float recall: A metric that measures how often documents that should be + classified into certain classes are classified into those classes. + :attr float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a weighted + average of the precision and recall values. An F1 score reaches its best value + at 1 and worst value at 0. """ - def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: + def __init__(self, precision: float, recall: float, f1: float) -> None: """ - Initialize a ListProjectsResponse object. + Initialize a ModelEvaluationMicroAverage object. - :param List[ProjectListDetails] projects: (optional) An array of project - details. + :param float precision: A metric that measures how many of the overall + documents are classified correctly. + :param float recall: A metric that measures how often documents that should + be classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a + weighted average of the precision and recall values. An F1 score reaches + its best value at 1 and worst value at 0. """ - self.projects = projects + self.precision = precision + self.recall = recall + self.f1 = f1 @classmethod - def from_dict(cls, _dict: Dict) -> 'ListProjectsResponse': - """Initialize a ListProjectsResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ModelEvaluationMicroAverage': + """Initialize a ModelEvaluationMicroAverage object from a json dictionary.""" args = {} - if 'projects' in _dict: - args['projects'] = [ - ProjectListDetails.from_dict(x) for x in _dict.get('projects') - ] + if 'precision' in _dict: + args['precision'] = _dict.get('precision') + else: + raise ValueError( + 'Required property \'precision\' not present in ModelEvaluationMicroAverage JSON' + ) + if 'recall' in _dict: + args['recall'] = _dict.get('recall') + else: + raise ValueError( + 'Required property \'recall\' not present in ModelEvaluationMicroAverage JSON' + ) + if 'f1' in _dict: + args['f1'] = _dict.get('f1') + else: + raise ValueError( + 'Required property \'f1\' not present in ModelEvaluationMicroAverage JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ListProjectsResponse object from a json dictionary.""" + """Initialize a ModelEvaluationMicroAverage 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, 'projects') and self.projects is not None: - _dict['projects'] = [x.to_dict() for x in self.projects] + if hasattr(self, 'precision') and self.precision is not None: + _dict['precision'] = self.precision + if hasattr(self, 'recall') and self.recall is not None: + _dict['recall'] = self.recall + if hasattr(self, 'f1') and self.f1 is not None: + _dict['f1'] = self.f1 return _dict def _to_dict(self): @@ -4087,16 +7069,16 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ListProjectsResponse object.""" + """Return a `str` version of this ModelEvaluationMicroAverage object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ListProjectsResponse') -> bool: + def __eq__(self, other: 'ModelEvaluationMicroAverage') -> 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: 'ListProjectsResponse') -> bool: + def __ne__(self, other: 'ModelEvaluationMicroAverage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -4108,7 +7090,8 @@ class Notice(): :attr str notice_id: (optional) Identifies the notice. Many notices might have the same ID. This field exists so that user applications can programmatically identify a notice and take automatic corrective action. Typical notice IDs - include: `index_failed`, `index_failed_too_many_requests`, + include: + `index_failed`, `index_failed_too_many_requests`, `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, `missing_model`, `unsupported_model`, @@ -4118,7 +7101,7 @@ class Notice(): `smart_document_understanding_failed_warning`, `smart_document_understanding_page_error`, `smart_document_understanding_page_warning`. **Note:** This is not a complete - list, other values might be returned. + list. Other values might be returned. :attr datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :attr str document_id: (optional) Unique identifier of the document. @@ -4232,6 +7215,111 @@ class SeverityEnum(str, Enum): ERROR = 'error' +class PerClassModelEvaluation(): + """ + An object that measures the metrics from a training run for each classification label + separately. + + :attr str name: Class name. Each class name is derived from a value in the + **answer_field**. + :attr float precision: A metric that measures how many of the overall documents + are classified correctly. + :attr float recall: A metric that measures how often documents that should be + classified into certain classes are classified into those classes. + :attr float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a weighted + average of the precision and recall values. An F1 score reaches its best value + at 1 and worst value at 0. + """ + + def __init__(self, name: str, precision: float, recall: float, + f1: float) -> None: + """ + Initialize a PerClassModelEvaluation object. + + :param str name: Class name. Each class name is derived from a value in the + **answer_field**. + :param float precision: A metric that measures how many of the overall + documents are classified correctly. + :param float recall: A metric that measures how often documents that should + be classified into certain classes are classified into those classes. + :param float f1: A metric that measures whether the optimal balance between + precision and recall is reached. The F1 score can be interpreted as a + weighted average of the precision and recall values. An F1 score reaches + its best value at 1 and worst value at 0. + """ + self.name = name + self.precision = precision + self.recall = recall + self.f1 = f1 + + @classmethod + def from_dict(cls, _dict: Dict) -> 'PerClassModelEvaluation': + """Initialize a PerClassModelEvaluation object from a json dictionary.""" + args = {} + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in PerClassModelEvaluation JSON' + ) + if 'precision' in _dict: + args['precision'] = _dict.get('precision') + else: + raise ValueError( + 'Required property \'precision\' not present in PerClassModelEvaluation JSON' + ) + if 'recall' in _dict: + args['recall'] = _dict.get('recall') + else: + raise ValueError( + 'Required property \'recall\' not present in PerClassModelEvaluation JSON' + ) + if 'f1' in _dict: + args['f1'] = _dict.get('f1') + else: + raise ValueError( + 'Required property \'f1\' not present in PerClassModelEvaluation JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a PerClassModelEvaluation 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'precision') and self.precision is not None: + _dict['precision'] = self.precision + if hasattr(self, 'recall') and self.recall is not None: + _dict['recall'] = self.recall + if hasattr(self, 'f1') and self.f1 is not None: + _dict['f1'] = self.f1 + 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 PerClassModelEvaluation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'PerClassModelEvaluation') -> 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: 'PerClassModelEvaluation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ProjectDetails(): """ Detailed information about the specified project. @@ -4946,11 +8034,11 @@ class QueryLargePassages(): regardless of the document quality and returns them in a separate `passages` field in the response. :attr int max_per_document: (optional) Maximum number of passages to return per - document in the result. Ignored if `passages.per_document` is `false`. + document in the result. Ignored if **passages.per_document** is `false`. :attr List[str] fields: (optional) A list of fields to extract passages from. If this parameter is an empty list, then all root-level fields are included. :attr int count: (optional) The maximum number of passages to return. Ignored if - `passages.per_document` is `true`. + **passages.per_document** is `true`. :attr int characters: (optional) The approximate number of characters that any one passage will have. :attr bool find_answers: (optional) When true, `answer` objects are returned as @@ -4997,13 +8085,13 @@ def __init__(self, regardless of the document quality and returns them in a separate `passages` field in the response. :param int max_per_document: (optional) Maximum number of passages to - return per document in the result. Ignored if `passages.per_document` is + return per document in the result. Ignored if **passages.per_document** is `false`. :param List[str] fields: (optional) A list of fields to extract passages from. If this parameter is an empty list, then all root-level fields are included. :param int count: (optional) The maximum number of passages to return. - Ignored if `passages.per_document` is `true`. + Ignored if **passages.per_document** is `true`. :param int characters: (optional) The approximate number of characters that any one passage will have. :param bool find_answers: (optional) When true, `answer` objects are @@ -5108,9 +8196,94 @@ def __ne__(self, other: 'QueryLargePassages') -> bool: return not self == other +class QueryLargeSimilar(): + """ + Finds results from documents that are similar to documents of interest. Use this + parameter to add a *More like these* function to your search. You can include this + parameter with or without a **query**, **filter** or **natural_language_query** + parameter. + + :attr bool enabled: (optional) When `true`, includes documents in the query + results that are similar to documents you specify. + :attr List[str] document_ids: (optional) The list of documents of interest. + Required if **enabled** is `true`. + :attr List[str] fields: (optional) Looks for similarities in the specified + subset of fields in the documents. If not specified, all of the document fields + are used. + """ + + def __init__(self, + *, + enabled: bool = None, + document_ids: List[str] = None, + fields: List[str] = None) -> None: + """ + Initialize a QueryLargeSimilar object. + + :param bool enabled: (optional) When `true`, includes documents in the + query results that are similar to documents you specify. + :param List[str] document_ids: (optional) The list of documents of + interest. Required if **enabled** is `true`. + :param List[str] fields: (optional) Looks for similarities in the specified + subset of fields in the documents. If not specified, all of the document + fields are used. + """ + self.enabled = enabled + self.document_ids = document_ids + self.fields = fields + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryLargeSimilar': + """Initialize a QueryLargeSimilar object from a json dictionary.""" + args = {} + if 'enabled' in _dict: + args['enabled'] = _dict.get('enabled') + if 'document_ids' in _dict: + args['document_ids'] = _dict.get('document_ids') + if 'fields' in _dict: + args['fields'] = _dict.get('fields') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryLargeSimilar 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 + if hasattr(self, 'document_ids') and self.document_ids is not None: + _dict['document_ids'] = self.document_ids + if hasattr(self, 'fields') and self.fields is not None: + _dict['fields'] = self.fields + 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 QueryLargeSimilar object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryLargeSimilar') -> 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: 'QueryLargeSimilar') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryLargeSuggestedRefinements(): """ - Configuration for suggested refinements. Available with Premium plans only. + Configuration for suggested refinements. + **Note**: The **suggested_refinements** parameter that identified dynamic facets from + the data is deprecated. :attr bool enabled: (optional) Whether to perform suggested refinements. :attr int count: (optional) Maximum number of suggested refinements texts to be @@ -5316,7 +8489,8 @@ class QueryResponse(): :attr str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) Array of - suggested refinements. + suggested refinements. **Note**: The `suggested_refinements` parameter that + identified dynamic facets from the data is deprecated. :attr List[QueryTableResult] table_results: (optional) Array of table results. :attr List[QueryResponsePassage] passages: (optional) Passages that best match the query from across all of the collections in the project. @@ -5347,7 +8521,8 @@ def __init__(self, :param str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. :param List[QuerySuggestedRefinement] suggested_refinements: (optional) - Array of suggested refinements. + Array of suggested refinements. **Note**: The `suggested_refinements` + parameter that identified dynamic facets from the data is deprecated. :param List[QueryTableResult] table_results: (optional) Array of table results. :param List[QueryResponsePassage] passages: (optional) Passages that best @@ -5454,7 +8629,9 @@ class QueryResponsePassage(): :attr str passage_text: (optional) The content of the extracted passage. :attr float passage_score: (optional) The confidence score of the passage's - analysis. A higher score indicates greater confidence. + analysis. A higher score indicates greater confidence. The score is used to rank + the passages from all documents and is returned only if + **passages.per_document** is `false`. :attr str document_id: (optional) The unique identifier of the ingested document. :attr str collection_id: (optional) The unique identifier of the collection. @@ -5486,7 +8663,9 @@ def __init__(self, :param str passage_text: (optional) The content of the extracted passage. :param float passage_score: (optional) The confidence score of the - passage's analysis. A higher score indicates greater confidence. + passage's analysis. A higher score indicates greater confidence. The score + is used to rank the passages from all documents and is returned only if + **passages.per_document** is `false`. :param str document_id: (optional) The unique identifier of the ingested document. :param str collection_id: (optional) The unique identifier of the @@ -5930,7 +9109,8 @@ def __ne__(self, other: 'QueryResultPassage') -> bool: class QuerySuggestedRefinement(): """ - A suggested additional query term or terms user to filter results. + A suggested additional query term or terms user to filter results. **Note**: The + `suggested_refinements` parameter is deprecated. :attr str text: (optional) The text used to filter. """ @@ -6552,6 +9732,64 @@ class DocumentRetrievalStrategyEnum(str, Enum): RELEVANCY_TRAINING = 'relevancy_training' +class StopWordList(): + """ + List of words to filter out of text that is submitted in queries. + + :attr List[str] stopwords: List of stop words. + """ + + def __init__(self, stopwords: List[str]) -> None: + """ + Initialize a StopWordList object. + + :param List[str] stopwords: List of stop words. + """ + self.stopwords = stopwords + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StopWordList': + """Initialize a StopWordList object from a json dictionary.""" + args = {} + if 'stopwords' in _dict: + args['stopwords'] = _dict.get('stopwords') + else: + raise ValueError( + 'Required property \'stopwords\' not present in StopWordList JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StopWordList 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, 'stopwords') and self.stopwords is not None: + _dict['stopwords'] = self.stopwords + 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 StopWordList object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StopWordList') -> 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: 'StopWordList') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TableBodyCells(): """ Cells that are not table header, column header, or row header cells. @@ -8166,7 +11404,8 @@ class TrainingQuery(): Object that contains training query details. :attr str query_id: (optional) The query ID associated with the training query. - :attr str natural_language_query: The natural text query for the training query. + :attr str natural_language_query: The natural text query that is used as the + training query. :attr str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. :attr datetime created: (optional) The date and time the query was created. @@ -8185,8 +11424,8 @@ def __init__(self, """ Initialize a TrainingQuery object. - :param str natural_language_query: The natural text query for the training - query. + :param str natural_language_query: The natural text query that is used as + the training query. :param List[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. @@ -8272,7 +11511,9 @@ class TrainingQuerySet(): """ Object specifying the training queries contained in the identified training set. - :attr List[TrainingQuery] queries: (optional) Array of training queries. + :attr List[TrainingQuery] queries: (optional) Array of training queries. At + least 50 queries are required for training to begin. A maximum of 10,000 queries + are returned. """ def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: @@ -8280,6 +11521,8 @@ def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: Initialize a TrainingQuerySet object. :param List[TrainingQuery] queries: (optional) Array of training queries. + At least 50 queries are required for training to begin. A maximum of 10,000 + queries are returned. """ self.queries = queries @@ -8324,6 +11567,68 @@ def __ne__(self, other: 'TrainingQuerySet') -> bool: return not self == other +class UpdateDocumentClassifier(): + """ + An object that contains a new name or description for a document classifier, updated + training data, or new or updated test data. + + :attr str name: (optional) A new name for the classifier. + :attr str description: (optional) A new description for the classifier. + """ + + def __init__(self, *, name: str = None, description: str = None) -> None: + """ + Initialize a UpdateDocumentClassifier object. + + :param str name: (optional) A new name for the classifier. + :param str description: (optional) A new description for the classifier. + """ + self.name = name + self.description = description + + @classmethod + def from_dict(cls, _dict: Dict) -> 'UpdateDocumentClassifier': + """Initialize a UpdateDocumentClassifier object from a json dictionary.""" + args = {} + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a UpdateDocumentClassifier 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + 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 UpdateDocumentClassifier object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'UpdateDocumentClassifier') -> 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: 'UpdateDocumentClassifier') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryCalculationAggregation(QueryAggregation): """ Returns a scalar calculation across all documents for the field specified. Possible diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 500d6a127..ecb024af6 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2021. +# (C) Copyright IBM Corp. 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -36,213 +36,277 @@ _service = DiscoveryV2( authenticator=NoAuthAuthenticator(), version=version - ) +) _base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' _service.set_service_url(_base_url) + +def preprocess_url(operation_path: str): + """ + Returns the request url associated with the specified operation path. + This will be base_url concatenated with a quoted version of operation_path. + The returned request URL is used to register the mock response so it needs + to match the request URL that is formed by the requests library. + """ + # First, unquote the path since it might have some quoted/escaped characters in it + # due to how the generator inserts the operation paths into the unit test code. + operation_path = urllib.parse.unquote(operation_path) + + # Next, quote the path using urllib so that we approximate what will + # happen during request processing. + operation_path = urllib.parse.quote(operation_path, safe='/') + + # Finally, form the request URL from the base URL and operation path. + request_url = _base_url + operation_path + + # If the request url does NOT end with a /, then just return it as-is. + # Otherwise, return a regular expression that matches one or more trailing /. + if re.fullmatch('.*/+', request_url) is None: + return request_url + else: + return re.compile(request_url.rstrip('/') + '/+') + + ############################################################################## -# Start of Service: Collections +# Start of Service: Projects ############################################################################## # region -class TestListCollections(): +class TestListProjects(): """ - Test Class for list_collections + Test Class for list_projects """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_list_collections_all_params(self): + def test_list_projects_all_params(self): """ - list_collections() + list_projects() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' + url = preprocess_url('/v2/projects') + mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) - # Set up parameter values - project_id = 'testString' - # Invoke method - response = _service.list_collections( - project_id, - headers={} - ) + response = _service.list_projects() + # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_projects_all_params_with_retries(self): + # Enable retries and run test_list_projects_all_params. + _service.enable_retries() + self.test_list_projects_all_params() + + # Disable retries and run test_list_projects_all_params. + _service.disable_retries() + self.test_list_projects_all_params() @responses.activate - def test_list_collections_value_error(self): + def test_list_projects_value_error(self): """ - test_list_collections_value_error() + test_list_projects_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' + url = preprocess_url('/v2/projects') + mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) - # Set up parameter values - project_id = 'testString' - # Pass in all but one required param and check for a ValueError req_param_dict = { - "project_id": project_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_collections(**req_copy) + _service.list_projects(**req_copy) + def test_list_projects_value_error_with_retries(self): + # Enable retries and run test_list_projects_value_error. + _service.enable_retries() + self.test_list_projects_value_error() + # Disable retries and run test_list_projects_value_error. + _service.disable_retries() + self.test_list_projects_value_error() -class TestCreateCollection(): +class TestCreateProject(): """ - Test Class for create_collection + Test Class for create_project """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_create_collection_all_params(self): + def test_create_project_all_params(self): """ - create_collection() + create_project() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=201) - # Construct a dict representation of a CollectionEnrichment model - collection_enrichment_model = {} - collection_enrichment_model['enrichment_id'] = 'testString' - collection_enrichment_model['fields'] = ['testString'] + # Construct a dict representation of a DefaultQueryParamsPassages model + default_query_params_passages_model = {} + default_query_params_passages_model['enabled'] = True + default_query_params_passages_model['count'] = 38 + default_query_params_passages_model['fields'] = ['testString'] + default_query_params_passages_model['characters'] = 38 + default_query_params_passages_model['per_document'] = True + default_query_params_passages_model['max_per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsTableResults model + default_query_params_table_results_model = {} + default_query_params_table_results_model['enabled'] = True + default_query_params_table_results_model['count'] = 38 + default_query_params_table_results_model['per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model + default_query_params_suggested_refinements_model = {} + default_query_params_suggested_refinements_model['enabled'] = True + default_query_params_suggested_refinements_model['count'] = 38 + + # Construct a dict representation of a DefaultQueryParams model + default_query_params_model = {} + default_query_params_model['collection_ids'] = ['testString'] + default_query_params_model['passages'] = default_query_params_passages_model + default_query_params_model['table_results'] = default_query_params_table_results_model + default_query_params_model['aggregation'] = 'testString' + default_query_params_model['suggested_refinements'] = default_query_params_suggested_refinements_model + default_query_params_model['spelling_suggestions'] = True + default_query_params_model['highlight'] = True + default_query_params_model['count'] = 38 + default_query_params_model['sort'] = 'testString' + default_query_params_model['return'] = ['testString'] # Set up parameter values - project_id = 'testString' name = 'testString' - description = 'testString' - language = 'en' - enrichments = [collection_enrichment_model] + type = 'document_retrieval' + default_query_parameters = default_query_params_model # Invoke method - response = _service.create_collection( - project_id, + response = _service.create_project( name, - description=description, - language=language, - enrichments=enrichments, + type, + default_query_parameters=default_query_parameters, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 201 # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['language'] == 'en' - assert req_body['enrichments'] == [collection_enrichment_model] + assert req_body['type'] == 'document_retrieval' + assert req_body['default_query_parameters'] == default_query_params_model + def test_create_project_all_params_with_retries(self): + # Enable retries and run test_create_project_all_params. + _service.enable_retries() + self.test_create_project_all_params() + + # Disable retries and run test_create_project_all_params. + _service.disable_retries() + self.test_create_project_all_params() @responses.activate - def test_create_collection_value_error(self): + def test_create_project_value_error(self): """ - test_create_collection_value_error() + test_create_project_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=201) - # Construct a dict representation of a CollectionEnrichment model - collection_enrichment_model = {} - collection_enrichment_model['enrichment_id'] = 'testString' - collection_enrichment_model['fields'] = ['testString'] + # Construct a dict representation of a DefaultQueryParamsPassages model + default_query_params_passages_model = {} + default_query_params_passages_model['enabled'] = True + default_query_params_passages_model['count'] = 38 + default_query_params_passages_model['fields'] = ['testString'] + default_query_params_passages_model['characters'] = 38 + default_query_params_passages_model['per_document'] = True + default_query_params_passages_model['max_per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsTableResults model + default_query_params_table_results_model = {} + default_query_params_table_results_model['enabled'] = True + default_query_params_table_results_model['count'] = 38 + default_query_params_table_results_model['per_document'] = 38 + + # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model + default_query_params_suggested_refinements_model = {} + default_query_params_suggested_refinements_model['enabled'] = True + default_query_params_suggested_refinements_model['count'] = 38 + + # Construct a dict representation of a DefaultQueryParams model + default_query_params_model = {} + default_query_params_model['collection_ids'] = ['testString'] + default_query_params_model['passages'] = default_query_params_passages_model + default_query_params_model['table_results'] = default_query_params_table_results_model + default_query_params_model['aggregation'] = 'testString' + default_query_params_model['suggested_refinements'] = default_query_params_suggested_refinements_model + default_query_params_model['spelling_suggestions'] = True + default_query_params_model['highlight'] = True + default_query_params_model['count'] = 38 + default_query_params_model['sort'] = 'testString' + default_query_params_model['return'] = ['testString'] # Set up parameter values - project_id = 'testString' name = 'testString' - description = 'testString' - language = 'en' - enrichments = [collection_enrichment_model] + type = 'document_retrieval' + default_query_parameters = default_query_params_model # Pass in all but one required param and check for a ValueError req_param_dict = { - "project_id": project_id, "name": name, + "type": type, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.create_collection(**req_copy) + _service.create_project(**req_copy) + def test_create_project_value_error_with_retries(self): + # Enable retries and run test_create_project_value_error. + _service.enable_retries() + self.test_create_project_value_error() + # Disable retries and run test_create_project_value_error. + _service.disable_retries() + self.test_create_project_value_error() -class TestGetCollection(): +class TestGetProject(): """ - Test Class for get_collection + Test Class for get_project """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_get_collection_all_params(self): + def test_get_project_all_params(self): """ - get_collection() + get_project() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.GET, url, body=mock_response, @@ -251,12 +315,10 @@ def test_get_collection_all_params(self): # Set up parameter values project_id = 'testString' - collection_id = 'testString' # Invoke method - response = _service.get_collection( + response = _service.get_project( project_id, - collection_id, headers={} ) @@ -264,15 +326,23 @@ def test_get_collection_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_project_all_params_with_retries(self): + # Enable retries and run test_get_project_all_params. + _service.enable_retries() + self.test_get_project_all_params() + + # Disable retries and run test_get_project_all_params. + _service.disable_retries() + self.test_get_project_all_params() @responses.activate - def test_get_collection_value_error(self): + def test_get_project_value_error(self): """ - test_get_collection_value_error() + test_get_project_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.GET, url, body=mock_response, @@ -281,69 +351,52 @@ def test_get_collection_value_error(self): # Set up parameter values project_id = 'testString' - collection_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "collection_id": collection_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_collection(**req_copy) + _service.get_project(**req_copy) + def test_get_project_value_error_with_retries(self): + # Enable retries and run test_get_project_value_error. + _service.enable_retries() + self.test_get_project_value_error() + # Disable retries and run test_get_project_value_error. + _service.disable_retries() + self.test_get_project_value_error() -class TestUpdateCollection(): +class TestUpdateProject(): """ - Test Class for update_collection + Test Class for update_project """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_update_collection_all_params(self): + def test_update_project_all_params(self): """ - update_collection() + update_project() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) - # Construct a dict representation of a CollectionEnrichment model - collection_enrichment_model = {} - collection_enrichment_model['enrichment_id'] = 'testString' - collection_enrichment_model['fields'] = ['testString'] - # Set up parameter values project_id = 'testString' - collection_id = 'testString' name = 'testString' - description = 'testString' - enrichments = [collection_enrichment_model] # Invoke method - response = _service.update_collection( + response = _service.update_project( project_id, - collection_id, name=name, - description=description, - enrichments=enrichments, headers={} ) @@ -353,121 +406,1362 @@ def test_update_collection_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['enrichments'] == [collection_enrichment_model] + def test_update_project_all_params_with_retries(self): + # Enable retries and run test_update_project_all_params. + _service.enable_retries() + self.test_update_project_all_params() + + # Disable retries and run test_update_project_all_params. + _service.disable_retries() + self.test_update_project_all_params() @responses.activate - def test_update_collection_value_error(self): + def test_update_project_required_params(self): """ - test_update_collection_value_error() + test_update_project_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}]}' + url = preprocess_url('/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) - # Construct a dict representation of a CollectionEnrichment model - collection_enrichment_model = {} - collection_enrichment_model['enrichment_id'] = 'testString' - collection_enrichment_model['fields'] = ['testString'] - # Set up parameter values project_id = 'testString' - collection_id = 'testString' - name = 'testString' - description = 'testString' - enrichments = [collection_enrichment_model] - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "project_id": project_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_collection(**req_copy) + # Invoke method + response = _service.update_project( + project_id, + headers={} + ) + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + def test_update_project_required_params_with_retries(self): + # Enable retries and run test_update_project_required_params. + _service.enable_retries() + self.test_update_project_required_params() -class TestDeleteCollection(): + # Disable retries and run test_update_project_required_params. + _service.disable_retries() + self.test_update_project_required_params() + + @responses.activate + def test_update_project_value_error(self): + """ + test_update_project_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString') + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_project(**req_copy) + + def test_update_project_value_error_with_retries(self): + # Enable retries and run test_update_project_value_error. + _service.enable_retries() + self.test_update_project_value_error() + + # Disable retries and run test_update_project_value_error. + _service.disable_retries() + self.test_update_project_value_error() + +class TestDeleteProject(): + """ + Test Class for delete_project + """ + + @responses.activate + def test_delete_project_all_params(self): + """ + delete_project() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = _service.delete_project( + project_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + def test_delete_project_all_params_with_retries(self): + # Enable retries and run test_delete_project_all_params. + _service.enable_retries() + self.test_delete_project_all_params() + + # Disable retries and run test_delete_project_all_params. + _service.disable_retries() + self.test_delete_project_all_params() + + @responses.activate + def test_delete_project_value_error(self): + """ + test_delete_project_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_project(**req_copy) + + def test_delete_project_value_error_with_retries(self): + # Enable retries and run test_delete_project_value_error. + _service.enable_retries() + self.test_delete_project_value_error() + + # Disable retries and run test_delete_project_value_error. + _service.disable_retries() + self.test_delete_project_value_error() + +class TestListFields(): + """ + Test Class for list_fields + """ + + @responses.activate + def test_list_fields_all_params(self): + """ + list_fields() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_ids = ['testString'] + + # Invoke method + response = _service.list_fields( + project_id, + collection_ids=collection_ids, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string + + def test_list_fields_all_params_with_retries(self): + # Enable retries and run test_list_fields_all_params. + _service.enable_retries() + self.test_list_fields_all_params() + + # Disable retries and run test_list_fields_all_params. + _service.disable_retries() + self.test_list_fields_all_params() + + @responses.activate + def test_list_fields_required_params(self): + """ + test_list_fields_required_params() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = _service.list_fields( + project_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_fields_required_params_with_retries(self): + # Enable retries and run test_list_fields_required_params. + _service.enable_retries() + self.test_list_fields_required_params() + + # Disable retries and run test_list_fields_required_params. + _service.disable_retries() + self.test_list_fields_required_params() + + @responses.activate + def test_list_fields_value_error(self): + """ + test_list_fields_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/fields') + mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_fields(**req_copy) + + def test_list_fields_value_error_with_retries(self): + # Enable retries and run test_list_fields_value_error. + _service.enable_retries() + self.test_list_fields_value_error() + + # Disable retries and run test_list_fields_value_error. + _service.disable_retries() + self.test_list_fields_value_error() + +# endregion +############################################################################## +# End of Service: Projects +############################################################################## + +############################################################################## +# Start of Service: Collections +############################################################################## +# region + +class TestListCollections(): + """ + Test Class for list_collections + """ + + @responses.activate + def test_list_collections_all_params(self): + """ + list_collections() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = _service.list_collections( + project_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_collections_all_params_with_retries(self): + # Enable retries and run test_list_collections_all_params. + _service.enable_retries() + self.test_list_collections_all_params() + + # Disable retries and run test_list_collections_all_params. + _service.disable_retries() + self.test_list_collections_all_params() + + @responses.activate + def test_list_collections_value_error(self): + """ + test_list_collections_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections') + mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_collections(**req_copy) + + def test_list_collections_value_error_with_retries(self): + # Enable retries and run test_list_collections_value_error. + _service.enable_retries() + self.test_list_collections_value_error() + + # Disable retries and run test_list_collections_value_error. + _service.disable_retries() + self.test_list_collections_value_error() + +class TestCreateCollection(): + """ + Test Class for create_collection + """ + + @responses.activate + def test_create_collection_all_params(self): + """ + create_collection() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Construct a dict representation of a CollectionDetailsSmartDocumentUnderstanding model + collection_details_smart_document_understanding_model = {} + collection_details_smart_document_understanding_model['enabled'] = True + collection_details_smart_document_understanding_model['model'] = 'custom' + + # Set up parameter values + project_id = 'testString' + name = 'testString' + description = 'testString' + language = 'en' + enrichments = [collection_enrichment_model] + smart_document_understanding = collection_details_smart_document_understanding_model + + # Invoke method + response = _service.create_collection( + project_id, + name, + description=description, + language=language, + enrichments=enrichments, + smart_document_understanding=smart_document_understanding, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['language'] == 'en' + assert req_body['enrichments'] == [collection_enrichment_model] + assert req_body['smart_document_understanding'] == collection_details_smart_document_understanding_model + + def test_create_collection_all_params_with_retries(self): + # Enable retries and run test_create_collection_all_params. + _service.enable_retries() + self.test_create_collection_all_params() + + # Disable retries and run test_create_collection_all_params. + _service.disable_retries() + self.test_create_collection_all_params() + + @responses.activate + def test_create_collection_value_error(self): + """ + test_create_collection_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Construct a dict representation of a CollectionDetailsSmartDocumentUnderstanding model + collection_details_smart_document_understanding_model = {} + collection_details_smart_document_understanding_model['enabled'] = True + collection_details_smart_document_understanding_model['model'] = 'custom' + + # Set up parameter values + project_id = 'testString' + name = 'testString' + description = 'testString' + language = 'en' + enrichments = [collection_enrichment_model] + smart_document_understanding = collection_details_smart_document_understanding_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_collection(**req_copy) + + def test_create_collection_value_error_with_retries(self): + # Enable retries and run test_create_collection_value_error. + _service.enable_retries() + self.test_create_collection_value_error() + + # Disable retries and run test_create_collection_value_error. + _service.disable_retries() + self.test_create_collection_value_error() + +class TestGetCollection(): + """ + Test Class for get_collection + """ + + @responses.activate + def test_get_collection_all_params(self): + """ + get_collection() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = _service.get_collection( + project_id, + collection_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_collection_all_params_with_retries(self): + # Enable retries and run test_get_collection_all_params. + _service.enable_retries() + self.test_get_collection_all_params() + + # Disable retries and run test_get_collection_all_params. + _service.disable_retries() + self.test_get_collection_all_params() + + @responses.activate + def test_get_collection_value_error(self): + """ + test_get_collection_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_collection(**req_copy) + + def test_get_collection_value_error_with_retries(self): + # Enable retries and run test_get_collection_value_error. + _service.enable_retries() + self.test_get_collection_value_error() + + # Disable retries and run test_get_collection_value_error. + _service.disable_retries() + self.test_get_collection_value_error() + +class TestUpdateCollection(): + """ + Test Class for update_collection + """ + + @responses.activate + def test_update_collection_all_params(self): + """ + update_collection() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + name = 'testString' + description = 'testString' + enrichments = [collection_enrichment_model] + + # Invoke method + response = _service.update_collection( + project_id, + collection_id, + name=name, + description=description, + enrichments=enrichments, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['enrichments'] == [collection_enrichment_model] + + def test_update_collection_all_params_with_retries(self): + # Enable retries and run test_update_collection_all_params. + _service.enable_retries() + self.test_update_collection_all_params() + + # Disable retries and run test_update_collection_all_params. + _service.disable_retries() + self.test_update_collection_all_params() + + @responses.activate + def test_update_collection_value_error(self): + """ + test_update_collection_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Construct a dict representation of a CollectionEnrichment model + collection_enrichment_model = {} + collection_enrichment_model['enrichment_id'] = 'testString' + collection_enrichment_model['fields'] = ['testString'] + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + name = 'testString' + description = 'testString' + enrichments = [collection_enrichment_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_collection(**req_copy) + + def test_update_collection_value_error_with_retries(self): + # Enable retries and run test_update_collection_value_error. + _service.enable_retries() + self.test_update_collection_value_error() + + # Disable retries and run test_update_collection_value_error. + _service.disable_retries() + self.test_update_collection_value_error() + +class TestDeleteCollection(): + """ + Test Class for delete_collection + """ + + @responses.activate + def test_delete_collection_all_params(self): + """ + delete_collection() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = _service.delete_collection( + project_id, + collection_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + def test_delete_collection_all_params_with_retries(self): + # Enable retries and run test_delete_collection_all_params. + _service.enable_retries() + self.test_delete_collection_all_params() + + # Disable retries and run test_delete_collection_all_params. + _service.disable_retries() + self.test_delete_collection_all_params() + + @responses.activate + def test_delete_collection_value_error(self): + """ + test_delete_collection_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_collection(**req_copy) + + def test_delete_collection_value_error_with_retries(self): + # Enable retries and run test_delete_collection_value_error. + _service.enable_retries() + self.test_delete_collection_value_error() + + # Disable retries and run test_delete_collection_value_error. + _service.disable_retries() + self.test_delete_collection_value_error() + +# endregion +############################################################################## +# End of Service: Collections +############################################################################## + +############################################################################## +# Start of Service: Documents +############################################################################## +# region + +class TestListDocuments(): + """ + Test Class for list_documents + """ + + @responses.activate + def test_list_documents_all_params(self): + """ + list_documents() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + count = 38 + status = 'testString' + has_notices = True + is_parent = True + parent_document_id = 'testString' + sha256 = 'testString' + + # Invoke method + response = _service.list_documents( + project_id, + collection_id, + count=count, + status=status, + has_notices=has_notices, + is_parent=is_parent, + parent_document_id=parent_document_id, + sha256=sha256, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'count={}'.format(count) in query_string + assert 'status={}'.format(status) in query_string + assert 'has_notices={}'.format('true' if has_notices else 'false') in query_string + assert 'is_parent={}'.format('true' if is_parent else 'false') in query_string + assert 'parent_document_id={}'.format(parent_document_id) in query_string + assert 'sha256={}'.format(sha256) in query_string + + def test_list_documents_all_params_with_retries(self): + # Enable retries and run test_list_documents_all_params. + _service.enable_retries() + self.test_list_documents_all_params() + + # Disable retries and run test_list_documents_all_params. + _service.disable_retries() + self.test_list_documents_all_params() + + @responses.activate + def test_list_documents_required_params(self): + """ + test_list_documents_required_params() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = _service.list_documents( + project_id, + collection_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_documents_required_params_with_retries(self): + # Enable retries and run test_list_documents_required_params. + _service.enable_retries() + self.test_list_documents_required_params() + + # Disable retries and run test_list_documents_required_params. + _service.disable_retries() + self.test_list_documents_required_params() + + @responses.activate + def test_list_documents_value_error(self): + """ + test_list_documents_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_documents(**req_copy) + + def test_list_documents_value_error_with_retries(self): + # Enable retries and run test_list_documents_value_error. + _service.enable_retries() + self.test_list_documents_value_error() + + # Disable retries and run test_list_documents_value_error. + _service.disable_retries() + self.test_list_documents_value_error() + +class TestAddDocument(): + """ + Test Class for add_document + """ + + @responses.activate + def test_add_document_all_params(self): + """ + add_document() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/json' + metadata = 'testString' + x_watson_discovery_force = False + + # Invoke method + response = _service.add_document( + project_id, + collection_id, + file=file, + filename=filename, + file_content_type=file_content_type, + metadata=metadata, + x_watson_discovery_force=x_watson_discovery_force, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_add_document_all_params_with_retries(self): + # Enable retries and run test_add_document_all_params. + _service.enable_retries() + self.test_add_document_all_params() + + # Disable retries and run test_add_document_all_params. + _service.disable_retries() + self.test_add_document_all_params() + + @responses.activate + def test_add_document_required_params(self): + """ + test_add_document_required_params() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = _service.add_document( + project_id, + collection_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_add_document_required_params_with_retries(self): + # Enable retries and run test_add_document_required_params. + _service.enable_retries() + self.test_add_document_required_params() + + # Disable retries and run test_add_document_required_params. + _service.disable_retries() + self.test_add_document_required_params() + + @responses.activate + def test_add_document_value_error(self): + """ + test_add_document_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.add_document(**req_copy) + + def test_add_document_value_error_with_retries(self): + # Enable retries and run test_add_document_value_error. + _service.enable_retries() + self.test_add_document_value_error() + + # Disable retries and run test_add_document_value_error. + _service.disable_retries() + self.test_add_document_value_error() + +class TestGetDocument(): + """ + Test Class for get_document + """ + + @responses.activate + def test_get_document_all_params(self): + """ + get_document() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Invoke method + response = _service.get_document( + project_id, + collection_id, + document_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_document_all_params_with_retries(self): + # Enable retries and run test_get_document_all_params. + _service.enable_retries() + self.test_get_document_all_params() + + # Disable retries and run test_get_document_all_params. + _service.disable_retries() + self.test_get_document_all_params() + + @responses.activate + def test_get_document_value_error(self): + """ + test_get_document_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + "document_id": document_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_document(**req_copy) + + def test_get_document_value_error_with_retries(self): + # Enable retries and run test_get_document_value_error. + _service.enable_retries() + self.test_get_document_value_error() + + # Disable retries and run test_get_document_value_error. + _service.disable_retries() + self.test_get_document_value_error() + +class TestUpdateDocument(): + """ + Test Class for update_document + """ + + @responses.activate + def test_update_document_all_params(self): + """ + update_document() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/json' + metadata = 'testString' + x_watson_discovery_force = False + + # Invoke method + response = _service.update_document( + project_id, + collection_id, + document_id, + file=file, + filename=filename, + file_content_type=file_content_type, + metadata=metadata, + x_watson_discovery_force=x_watson_discovery_force, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_update_document_all_params_with_retries(self): + # Enable retries and run test_update_document_all_params. + _service.enable_retries() + self.test_update_document_all_params() + + # Disable retries and run test_update_document_all_params. + _service.disable_retries() + self.test_update_document_all_params() + + @responses.activate + def test_update_document_required_params(self): + """ + test_update_document_required_params() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Invoke method + response = _service.update_document( + project_id, + collection_id, + document_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_update_document_required_params_with_retries(self): + # Enable retries and run test_update_document_required_params. + _service.enable_retries() + self.test_update_document_required_params() + + # Disable retries and run test_update_document_required_params. + _service.disable_retries() + self.test_update_document_required_params() + + @responses.activate + def test_update_document_value_error(self): + """ + test_update_document_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "processing"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + "document_id": document_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_document(**req_copy) + + def test_update_document_value_error_with_retries(self): + # Enable retries and run test_update_document_value_error. + _service.enable_retries() + self.test_update_document_value_error() + + # Disable retries and run test_update_document_value_error. + _service.disable_retries() + self.test_update_document_value_error() + +class TestDeleteDocument(): """ - Test Class for delete_collection + Test Class for delete_document """ - def preprocess_url(self, request_url: str): + @responses.activate + def test_delete_document_all_params(self): """ - Preprocess the request URL to ensure the mock response will be found. + delete_document() """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "deleted"}' + responses.add(responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + document_id = 'testString' + x_watson_discovery_force = False + + # Invoke method + response = _service.delete_document( + project_id, + collection_id, + document_id, + x_watson_discovery_force=x_watson_discovery_force, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_delete_document_all_params_with_retries(self): + # Enable retries and run test_delete_document_all_params. + _service.enable_retries() + self.test_delete_document_all_params() + + # Disable retries and run test_delete_document_all_params. + _service.disable_retries() + self.test_delete_document_all_params() @responses.activate - def test_delete_collection_all_params(self): + def test_delete_document_required_params(self): """ - delete_collection() + test_delete_document_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "deleted"}' responses.add(responses.DELETE, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' collection_id = 'testString' + document_id = 'testString' # Invoke method - response = _service.delete_collection( + response = _service.delete_document( project_id, collection_id, + document_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 204 + assert response.status_code == 200 + def test_delete_document_required_params_with_retries(self): + # Enable retries and run test_delete_document_required_params. + _service.enable_retries() + self.test_delete_document_required_params() + + # Disable retries and run test_delete_document_required_params. + _service.disable_retries() + self.test_delete_document_required_params() @responses.activate - def test_delete_collection_value_error(self): + def test_delete_document_value_error(self): """ - test_delete_collection_value_error() + test_delete_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString') + url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') + mock_response = '{"document_id": "document_id", "status": "deleted"}' responses.add(responses.DELETE, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' collection_id = 'testString' + document_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, "collection_id": collection_id, + "document_id": document_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_collection(**req_copy) + _service.delete_document(**req_copy) + def test_delete_document_value_error_with_retries(self): + # Enable retries and run test_delete_document_value_error. + _service.enable_retries() + self.test_delete_document_value_error() + # Disable retries and run test_delete_document_value_error. + _service.disable_retries() + self.test_delete_document_value_error() # endregion ############################################################################## -# End of Service: Collections +# End of Service: Documents ############################################################################## ############################################################################## @@ -480,24 +1774,13 @@ class TestQuery(): Test Class for query """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_query_all_params(self): """ query() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/query') + url = preprocess_url('/v2/projects/testString/query') mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, @@ -526,6 +1809,12 @@ def test_query_all_params(self): query_large_passages_model['find_answers'] = False query_large_passages_model['max_answers_per_passage'] = 38 + # Construct a dict representation of a QueryLargeSimilar model + query_large_similar_model = {} + query_large_similar_model['enabled'] = False + query_large_similar_model['document_ids'] = ['testString'] + query_large_similar_model['fields'] = ['testString'] + # Set up parameter values project_id = 'testString' collection_ids = ['testString'] @@ -542,6 +1831,7 @@ def test_query_all_params(self): table_results = query_large_table_results_model suggested_refinements = query_large_suggested_refinements_model passages = query_large_passages_model + similar = query_large_similar_model # Invoke method response = _service.query( @@ -560,6 +1850,7 @@ def test_query_all_params(self): table_results=table_results, suggested_refinements=suggested_refinements, passages=passages, + similar=similar, headers={} ) @@ -582,7 +1873,16 @@ def test_query_all_params(self): assert req_body['table_results'] == query_large_table_results_model assert req_body['suggested_refinements'] == query_large_suggested_refinements_model assert req_body['passages'] == query_large_passages_model + assert req_body['similar'] == query_large_similar_model + def test_query_all_params_with_retries(self): + # Enable retries and run test_query_all_params. + _service.enable_retries() + self.test_query_all_params() + + # Disable retries and run test_query_all_params. + _service.disable_retries() + self.test_query_all_params() @responses.activate def test_query_required_params(self): @@ -590,7 +1890,7 @@ def test_query_required_params(self): test_query_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/query') + url = preprocess_url('/v2/projects/testString/query') mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, @@ -611,6 +1911,14 @@ def test_query_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_query_required_params_with_retries(self): + # Enable retries and run test_query_required_params. + _service.enable_retries() + self.test_query_required_params() + + # Disable retries and run test_query_required_params. + _service.disable_retries() + self.test_query_required_params() @responses.activate def test_query_value_error(self): @@ -618,7 +1926,7 @@ def test_query_value_error(self): test_query_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/query') + url = preprocess_url('/v2/projects/testString/query') mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, @@ -638,31 +1946,27 @@ def test_query_value_error(self): with pytest.raises(ValueError): _service.query(**req_copy) + def test_query_value_error_with_retries(self): + # Enable retries and run test_query_value_error. + _service.enable_retries() + self.test_query_value_error() + # Disable retries and run test_query_value_error. + _service.disable_retries() + self.test_query_value_error() class TestGetAutocompletion(): """ Test Class for get_autocompletion """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_get_autocompletion_all_params(self): """ get_autocompletion() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/autocompletion') + url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -698,6 +2002,14 @@ def test_get_autocompletion_all_params(self): assert 'field={}'.format(field) in query_string assert 'count={}'.format(count) in query_string + def test_get_autocompletion_all_params_with_retries(self): + # Enable retries and run test_get_autocompletion_all_params. + _service.enable_retries() + self.test_get_autocompletion_all_params() + + # Disable retries and run test_get_autocompletion_all_params. + _service.disable_retries() + self.test_get_autocompletion_all_params() @responses.activate def test_get_autocompletion_required_params(self): @@ -705,7 +2017,7 @@ def test_get_autocompletion_required_params(self): test_get_autocompletion_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/autocompletion') + url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -732,6 +2044,14 @@ def test_get_autocompletion_required_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'prefix={}'.format(prefix) in query_string + def test_get_autocompletion_required_params_with_retries(self): + # Enable retries and run test_get_autocompletion_required_params. + _service.enable_retries() + self.test_get_autocompletion_required_params() + + # Disable retries and run test_get_autocompletion_required_params. + _service.disable_retries() + self.test_get_autocompletion_required_params() @responses.activate def test_get_autocompletion_value_error(self): @@ -739,7 +2059,7 @@ def test_get_autocompletion_value_error(self): test_get_autocompletion_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/autocompletion') + url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' responses.add(responses.GET, url, @@ -761,31 +2081,27 @@ def test_get_autocompletion_value_error(self): with pytest.raises(ValueError): _service.get_autocompletion(**req_copy) + def test_get_autocompletion_value_error_with_retries(self): + # Enable retries and run test_get_autocompletion_value_error. + _service.enable_retries() + self.test_get_autocompletion_value_error() + # Disable retries and run test_get_autocompletion_value_error. + _service.disable_retries() + self.test_get_autocompletion_value_error() class TestQueryCollectionNotices(): """ Test Class for query_collection_notices """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_query_collection_notices_all_params(self): """ query_collection_notices() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/notices') + url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -826,6 +2142,14 @@ def test_query_collection_notices_all_params(self): assert 'count={}'.format(count) in query_string assert 'offset={}'.format(offset) in query_string + def test_query_collection_notices_all_params_with_retries(self): + # Enable retries and run test_query_collection_notices_all_params. + _service.enable_retries() + self.test_query_collection_notices_all_params() + + # Disable retries and run test_query_collection_notices_all_params. + _service.disable_retries() + self.test_query_collection_notices_all_params() @responses.activate def test_query_collection_notices_required_params(self): @@ -833,7 +2157,7 @@ def test_query_collection_notices_required_params(self): test_query_collection_notices_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/notices') + url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -856,6 +2180,14 @@ def test_query_collection_notices_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_query_collection_notices_required_params_with_retries(self): + # Enable retries and run test_query_collection_notices_required_params. + _service.enable_retries() + self.test_query_collection_notices_required_params() + + # Disable retries and run test_query_collection_notices_required_params. + _service.disable_retries() + self.test_query_collection_notices_required_params() @responses.activate def test_query_collection_notices_value_error(self): @@ -863,7 +2195,7 @@ def test_query_collection_notices_value_error(self): test_query_collection_notices_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/notices') + url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -885,31 +2217,27 @@ def test_query_collection_notices_value_error(self): with pytest.raises(ValueError): _service.query_collection_notices(**req_copy) + def test_query_collection_notices_value_error_with_retries(self): + # Enable retries and run test_query_collection_notices_value_error. + _service.enable_retries() + self.test_query_collection_notices_value_error() + # Disable retries and run test_query_collection_notices_value_error. + _service.disable_retries() + self.test_query_collection_notices_value_error() class TestQueryNotices(): """ Test Class for query_notices """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_query_notices_all_params(self): """ query_notices() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/notices') + url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -948,6 +2276,14 @@ def test_query_notices_all_params(self): assert 'count={}'.format(count) in query_string assert 'offset={}'.format(offset) in query_string + def test_query_notices_all_params_with_retries(self): + # Enable retries and run test_query_notices_all_params. + _service.enable_retries() + self.test_query_notices_all_params() + + # Disable retries and run test_query_notices_all_params. + _service.disable_retries() + self.test_query_notices_all_params() @responses.activate def test_query_notices_required_params(self): @@ -955,7 +2291,7 @@ def test_query_notices_required_params(self): test_query_notices_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/notices') + url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -976,6 +2312,14 @@ def test_query_notices_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_query_notices_required_params_with_retries(self): + # Enable retries and run test_query_notices_required_params. + _service.enable_retries() + self.test_query_notices_required_params() + + # Disable retries and run test_query_notices_required_params. + _service.disable_retries() + self.test_query_notices_required_params() @responses.activate def test_query_notices_value_error(self): @@ -983,7 +2327,7 @@ def test_query_notices_value_error(self): test_query_notices_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/notices') + url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' responses.add(responses.GET, url, @@ -1003,32 +2347,38 @@ def test_query_notices_value_error(self): with pytest.raises(ValueError): _service.query_notices(**req_copy) + def test_query_notices_value_error_with_retries(self): + # Enable retries and run test_query_notices_value_error. + _service.enable_retries() + self.test_query_notices_value_error() + # Disable retries and run test_query_notices_value_error. + _service.disable_retries() + self.test_query_notices_value_error() -class TestListFields(): +# endregion +############################################################################## +# End of Service: Queries +############################################################################## + +############################################################################## +# Start of Service: QueryModifications +############################################################################## +# region + +class TestGetStopwordList(): """ - Test Class for list_fields + Test Class for get_stopword_list """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_list_fields_all_params(self): + def test_get_stopword_list_all_params(self): """ - list_fields() + get_stopword_list() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + mock_response = '{"stopwords": ["stopwords"]}' responses.add(responses.GET, url, body=mock_response, @@ -1037,32 +2387,36 @@ def test_list_fields_all_params(self): # Set up parameter values project_id = 'testString' - collection_ids = ['testString'] + collection_id = 'testString' # Invoke method - response = _service.list_fields( + response = _service.get_stopword_list( project_id, - collection_ids=collection_ids, + collection_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string + def test_get_stopword_list_all_params_with_retries(self): + # Enable retries and run test_get_stopword_list_all_params. + _service.enable_retries() + self.test_get_stopword_list_all_params() + + # Disable retries and run test_get_stopword_list_all_params. + _service.disable_retries() + self.test_get_stopword_list_all_params() @responses.activate - def test_list_fields_required_params(self): + def test_get_stopword_list_value_error(self): """ - test_list_fields_required_params() + test_get_stopword_list_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + mock_response = '{"stopwords": ["stopwords"]}' responses.add(responses.GET, url, body=mock_response, @@ -1071,27 +2425,41 @@ def test_list_fields_required_params(self): # Set up parameter values project_id = 'testString' + collection_id = 'testString' - # Invoke method - response = _service.list_fields( - project_id, - headers={} - ) + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_stopword_list(**req_copy) - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 + def test_get_stopword_list_value_error_with_retries(self): + # Enable retries and run test_get_stopword_list_value_error. + _service.enable_retries() + self.test_get_stopword_list_value_error() + # Disable retries and run test_get_stopword_list_value_error. + _service.disable_retries() + self.test_get_stopword_list_value_error() + +class TestCreateStopwordList(): + """ + Test Class for create_stopword_list + """ @responses.activate - def test_list_fields_value_error(self): + def test_create_stopword_list_all_params(self): """ - test_list_fields_value_error() + create_stopword_list() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' - responses.add(responses.GET, + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + mock_response = '{"stopwords": ["stopwords"]}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', @@ -1099,53 +2467,42 @@ def test_list_fields_value_error(self): # Set up parameter values project_id = 'testString' + collection_id = 'testString' + stopwords = ['testString'] - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "project_id": project_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_fields(**req_copy) - - - -# endregion -############################################################################## -# End of Service: Queries -############################################################################## + # Invoke method + response = _service.create_stopword_list( + project_id, + collection_id, + stopwords=stopwords, + headers={} + ) -############################################################################## -# Start of Service: ComponentSettings -############################################################################## -# region + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['stopwords'] == ['testString'] -class TestGetComponentSettings(): - """ - Test Class for get_component_settings - """ + def test_create_stopword_list_all_params_with_retries(self): + # Enable retries and run test_create_stopword_list_all_params. + _service.enable_retries() + self.test_create_stopword_list_all_params() - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Disable retries and run test_create_stopword_list_all_params. + _service.disable_retries() + self.test_create_stopword_list_all_params() @responses.activate - def test_get_component_settings_all_params(self): + def test_create_stopword_list_required_params(self): """ - get_component_settings() + test_create_stopword_list_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/component_settings') - mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' - responses.add(responses.GET, + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + mock_response = '{"stopwords": ["stopwords"]}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', @@ -1153,10 +2510,12 @@ def test_get_component_settings_all_params(self): # Set up parameter values project_id = 'testString' + collection_id = 'testString' # Invoke method - response = _service.get_component_settings( + response = _service.create_stopword_list( project_id, + collection_id, headers={} ) @@ -1164,16 +2523,24 @@ def test_get_component_settings_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_create_stopword_list_required_params_with_retries(self): + # Enable retries and run test_create_stopword_list_required_params. + _service.enable_retries() + self.test_create_stopword_list_required_params() + + # Disable retries and run test_create_stopword_list_required_params. + _service.disable_retries() + self.test_create_stopword_list_required_params() @responses.activate - def test_get_component_settings_value_error(self): + def test_create_stopword_list_value_error(self): """ - test_get_component_settings_value_error() + test_create_stopword_list_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/component_settings') - mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' - responses.add(responses.GET, + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + mock_response = '{"stopwords": ["stopwords"]}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', @@ -1181,104 +2548,126 @@ def test_get_component_settings_value_error(self): # Set up parameter values project_id = 'testString' + collection_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "collection_id": collection_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_component_settings(**req_copy) - + _service.create_stopword_list(**req_copy) + def test_create_stopword_list_value_error_with_retries(self): + # Enable retries and run test_create_stopword_list_value_error. + _service.enable_retries() + self.test_create_stopword_list_value_error() -# endregion -############################################################################## -# End of Service: ComponentSettings -############################################################################## - -############################################################################## -# Start of Service: Documents -############################################################################## -# region + # Disable retries and run test_create_stopword_list_value_error. + _service.disable_retries() + self.test_create_stopword_list_value_error() -class TestAddDocument(): +class TestDeleteStopwordList(): """ - Test Class for add_document + Test Class for delete_stopword_list """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_add_document_all_params(self): + def test_delete_stopword_list_all_params(self): """ - add_document() + delete_stopword_list() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + responses.add(responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=202) + status=204) # Set up parameter values project_id = 'testString' collection_id = 'testString' - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/json' - metadata = 'testString' - x_watson_discovery_force = False # Invoke method - response = _service.add_document( + response = _service.delete_stopword_list( project_id, collection_id, - file=file, - filename=filename, - file_content_type=file_content_type, - metadata=metadata, - x_watson_discovery_force=x_watson_discovery_force, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 + assert response.status_code == 204 + + def test_delete_stopword_list_all_params_with_retries(self): + # Enable retries and run test_delete_stopword_list_all_params. + _service.enable_retries() + self.test_delete_stopword_list_all_params() + + # Disable retries and run test_delete_stopword_list_all_params. + _service.disable_retries() + self.test_delete_stopword_list_all_params() + + @responses.activate + def test_delete_stopword_list_value_error(self): + """ + test_delete_stopword_list_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') + responses.add(responses.DELETE, + url, + status=204) + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_stopword_list(**req_copy) + + def test_delete_stopword_list_value_error_with_retries(self): + # Enable retries and run test_delete_stopword_list_value_error. + _service.enable_retries() + self.test_delete_stopword_list_value_error() + + # Disable retries and run test_delete_stopword_list_value_error. + _service.disable_retries() + self.test_delete_stopword_list_value_error() + +class TestListExpansions(): + """ + Test Class for list_expansions + """ @responses.activate - def test_add_document_required_params(self): + def test_list_expansions_all_params(self): """ - test_add_document_required_params() + list_expansions() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' + responses.add(responses.GET, url, body=mock_response, content_type='application/json', - status=202) + status=200) # Set up parameter values project_id = 'testString' collection_id = 'testString' # Invoke method - response = _service.add_document( + response = _service.list_expansions( project_id, collection_id, headers={} @@ -1286,22 +2675,30 @@ def test_add_document_required_params(self): # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 + assert response.status_code == 200 + + def test_list_expansions_all_params_with_retries(self): + # Enable retries and run test_list_expansions_all_params. + _service.enable_retries() + self.test_list_expansions_all_params() + # Disable retries and run test_list_expansions_all_params. + _service.disable_retries() + self.test_list_expansions_all_params() @responses.activate - def test_add_document_value_error(self): + def test_list_expansions_value_error(self): """ - test_add_document_value_error() + test_list_expansions_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' + responses.add(responses.GET, url, body=mock_response, content_type='application/json', - status=202) + status=200) # Set up parameter values project_id = 'testString' @@ -1315,157 +2712,212 @@ def test_add_document_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.add_document(**req_copy) + _service.list_expansions(**req_copy) + def test_list_expansions_value_error_with_retries(self): + # Enable retries and run test_list_expansions_value_error. + _service.enable_retries() + self.test_list_expansions_value_error() + # Disable retries and run test_list_expansions_value_error. + _service.disable_retries() + self.test_list_expansions_value_error() -class TestUpdateDocument(): +class TestCreateExpansions(): """ - Test Class for update_document + Test Class for create_expansions """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_update_document_all_params(self): + def test_create_expansions_all_params(self): """ - update_document() + create_expansions() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing"}' + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=202) + status=200) + + # Construct a dict representation of a Expansion model + expansion_model = {} + expansion_model['input_terms'] = ['testString'] + expansion_model['expanded_terms'] = ['testString'] # Set up parameter values project_id = 'testString' collection_id = 'testString' - document_id = 'testString' - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/json' - metadata = 'testString' - x_watson_discovery_force = False + expansions = [expansion_model] # Invoke method - response = _service.update_document( + response = _service.create_expansions( project_id, collection_id, - document_id, - file=file, - filename=filename, - file_content_type=file_content_type, - metadata=metadata, - x_watson_discovery_force=x_watson_discovery_force, + expansions, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['expansions'] == [expansion_model] + def test_create_expansions_all_params_with_retries(self): + # Enable retries and run test_create_expansions_all_params. + _service.enable_retries() + self.test_create_expansions_all_params() + + # Disable retries and run test_create_expansions_all_params. + _service.disable_retries() + self.test_create_expansions_all_params() @responses.activate - def test_update_document_required_params(self): + def test_create_expansions_value_error(self): """ - test_update_document_required_params() + test_create_expansions_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing"}' + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') + mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=202) + status=200) + + # Construct a dict representation of a Expansion model + expansion_model = {} + expansion_model['input_terms'] = ['testString'] + expansion_model['expanded_terms'] = ['testString'] + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + expansions = [expansion_model] + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + "expansions": expansions, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_expansions(**req_copy) + + def test_create_expansions_value_error_with_retries(self): + # Enable retries and run test_create_expansions_value_error. + _service.enable_retries() + self.test_create_expansions_value_error() + + # Disable retries and run test_create_expansions_value_error. + _service.disable_retries() + self.test_create_expansions_value_error() + +class TestDeleteExpansions(): + """ + Test Class for delete_expansions + """ + + @responses.activate + def test_delete_expansions_all_params(self): + """ + delete_expansions() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') + responses.add(responses.DELETE, + url, + status=204) # Set up parameter values project_id = 'testString' collection_id = 'testString' - document_id = 'testString' # Invoke method - response = _service.update_document( + response = _service.delete_expansions( project_id, collection_id, - document_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 + assert response.status_code == 204 + def test_delete_expansions_all_params_with_retries(self): + # Enable retries and run test_delete_expansions_all_params. + _service.enable_retries() + self.test_delete_expansions_all_params() + + # Disable retries and run test_delete_expansions_all_params. + _service.disable_retries() + self.test_delete_expansions_all_params() @responses.activate - def test_update_document_value_error(self): + def test_delete_expansions_value_error(self): """ - test_update_document_value_error() + test_delete_expansions_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, + url = preprocess_url('/v2/projects/testString/collections/testString/expansions') + responses.add(responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=202) + status=204) # Set up parameter values project_id = 'testString' collection_id = 'testString' - document_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, "collection_id": collection_id, - "document_id": document_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_document(**req_copy) + _service.delete_expansions(**req_copy) + def test_delete_expansions_value_error_with_retries(self): + # Enable retries and run test_delete_expansions_value_error. + _service.enable_retries() + self.test_delete_expansions_value_error() + # Disable retries and run test_delete_expansions_value_error. + _service.disable_retries() + self.test_delete_expansions_value_error() -class TestDeleteDocument(): +# endregion +############################################################################## +# End of Service: QueryModifications +############################################################################## + +############################################################################## +# Start of Service: ComponentSettings +############################################################################## +# region + +class TestGetComponentSettings(): """ - Test Class for delete_document + Test Class for get_component_settings """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_delete_document_all_params(self): + def test_get_component_settings_all_params(self): """ - delete_document() + get_component_settings() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/component_settings') + mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' + responses.add(responses.GET, url, body=mock_response, content_type='application/json', @@ -1473,16 +2925,10 @@ def test_delete_document_all_params(self): # Set up parameter values project_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - x_watson_discovery_force = False # Invoke method - response = _service.delete_document( + response = _service.get_component_settings( project_id, - collection_id, - document_id, - x_watson_discovery_force=x_watson_discovery_force, headers={} ) @@ -1490,16 +2936,74 @@ def test_delete_document_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_component_settings_all_params_with_retries(self): + # Enable retries and run test_get_component_settings_all_params. + _service.enable_retries() + self.test_get_component_settings_all_params() + + # Disable retries and run test_get_component_settings_all_params. + _service.disable_retries() + self.test_get_component_settings_all_params() @responses.activate - def test_delete_document_required_params(self): + def test_get_component_settings_value_error(self): """ - test_delete_document_required_params() + test_get_component_settings_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/component_settings') + mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_component_settings(**req_copy) + + def test_get_component_settings_value_error_with_retries(self): + # Enable retries and run test_get_component_settings_value_error. + _service.enable_retries() + self.test_get_component_settings_value_error() + + # Disable retries and run test_get_component_settings_value_error. + _service.disable_retries() + self.test_get_component_settings_value_error() + +# endregion +############################################################################## +# End of Service: ComponentSettings +############################################################################## + +############################################################################## +# Start of Service: TrainingData +############################################################################## +# region + +class TestListTrainingQueries(): + """ + Test Class for list_training_queries + """ + + @responses.activate + def test_list_training_queries_all_params(self): + """ + list_training_queries() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/training_data/queries') + mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + responses.add(responses.GET, url, body=mock_response, content_type='application/json', @@ -1507,14 +3011,10 @@ def test_delete_document_required_params(self): # Set up parameter values project_id = 'testString' - collection_id = 'testString' - document_id = 'testString' # Invoke method - response = _service.delete_document( + response = _service.list_training_queries( project_id, - collection_id, - document_id, headers={} ) @@ -1522,16 +3022,24 @@ def test_delete_document_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_training_queries_all_params_with_retries(self): + # Enable retries and run test_list_training_queries_all_params. + _service.enable_retries() + self.test_list_training_queries_all_params() + + # Disable retries and run test_list_training_queries_all_params. + _service.disable_retries() + self.test_list_training_queries_all_params() @responses.activate - def test_delete_document_value_error(self): + def test_list_training_queries_value_error(self): """ - test_delete_document_value_error() + test_list_training_queries_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/training_data/queries') + mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' + responses.add(responses.GET, url, body=mock_response, content_type='application/json', @@ -1539,193 +3047,291 @@ def test_delete_document_value_error(self): # Set up parameter values project_id = 'testString' - collection_id = 'testString' - document_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "collection_id": collection_id, - "document_id": document_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_document(**req_copy) + _service.list_training_queries(**req_copy) + def test_list_training_queries_value_error_with_retries(self): + # Enable retries and run test_list_training_queries_value_error. + _service.enable_retries() + self.test_list_training_queries_value_error() + # Disable retries and run test_list_training_queries_value_error. + _service.disable_retries() + self.test_list_training_queries_value_error() -# endregion -############################################################################## -# End of Service: Documents -############################################################################## +class TestDeleteTrainingQueries(): + """ + Test Class for delete_training_queries + """ + + @responses.activate + def test_delete_training_queries_all_params(self): + """ + delete_training_queries() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/training_data/queries') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + + # Invoke method + response = _service.delete_training_queries( + project_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + def test_delete_training_queries_all_params_with_retries(self): + # Enable retries and run test_delete_training_queries_all_params. + _service.enable_retries() + self.test_delete_training_queries_all_params() + + # Disable retries and run test_delete_training_queries_all_params. + _service.disable_retries() + self.test_delete_training_queries_all_params() + + @responses.activate + def test_delete_training_queries_value_error(self): + """ + test_delete_training_queries_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/training_data/queries') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_training_queries(**req_copy) -############################################################################## -# Start of Service: TrainingData -############################################################################## -# region + def test_delete_training_queries_value_error_with_retries(self): + # Enable retries and run test_delete_training_queries_value_error. + _service.enable_retries() + self.test_delete_training_queries_value_error() -class TestListTrainingQueries(): + # Disable retries and run test_delete_training_queries_value_error. + _service.disable_retries() + self.test_delete_training_queries_value_error() + +class TestCreateTrainingQuery(): """ - Test Class for list_training_queries + Test Class for create_training_query """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_list_training_queries_all_params(self): + def test_create_training_query_all_params(self): """ - list_training_queries() + create_training_query() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') - mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.GET, + url = preprocess_url('/v2/projects/testString/training_data/queries') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=201) + + # Construct a dict representation of a TrainingExample model + training_example_model = {} + training_example_model['document_id'] = 'testString' + training_example_model['collection_id'] = 'testString' + training_example_model['relevance'] = 38 # Set up parameter values project_id = 'testString' + natural_language_query = 'testString' + examples = [training_example_model] + filter = 'testString' # Invoke method - response = _service.list_training_queries( + response = _service.create_training_query( project_id, + natural_language_query, + examples, + filter=filter, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 201 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['natural_language_query'] == 'testString' + assert req_body['examples'] == [training_example_model] + assert req_body['filter'] == 'testString' + + def test_create_training_query_all_params_with_retries(self): + # Enable retries and run test_create_training_query_all_params. + _service.enable_retries() + self.test_create_training_query_all_params() + # Disable retries and run test_create_training_query_all_params. + _service.disable_retries() + self.test_create_training_query_all_params() @responses.activate - def test_list_training_queries_value_error(self): + def test_create_training_query_value_error(self): """ - test_list_training_queries_value_error() + test_create_training_query_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') - mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.GET, + url = preprocess_url('/v2/projects/testString/training_data/queries') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=201) + + # Construct a dict representation of a TrainingExample model + training_example_model = {} + training_example_model['document_id'] = 'testString' + training_example_model['collection_id'] = 'testString' + training_example_model['relevance'] = 38 # Set up parameter values project_id = 'testString' + natural_language_query = 'testString' + examples = [training_example_model] + filter = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "natural_language_query": natural_language_query, + "examples": examples, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_training_queries(**req_copy) + _service.create_training_query(**req_copy) + def test_create_training_query_value_error_with_retries(self): + # Enable retries and run test_create_training_query_value_error. + _service.enable_retries() + self.test_create_training_query_value_error() + # Disable retries and run test_create_training_query_value_error. + _service.disable_retries() + self.test_create_training_query_value_error() -class TestDeleteTrainingQueries(): +class TestGetTrainingQuery(): """ - Test Class for delete_training_queries + Test Class for get_training_query """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_delete_training_queries_all_params(self): + def test_get_training_query_all_params(self): """ - delete_training_queries() + get_training_query() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add(responses.GET, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' + query_id = 'testString' # Invoke method - response = _service.delete_training_queries( + response = _service.get_training_query( project_id, + query_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 204 + assert response.status_code == 200 + + def test_get_training_query_all_params_with_retries(self): + # Enable retries and run test_get_training_query_all_params. + _service.enable_retries() + self.test_get_training_query_all_params() + # Disable retries and run test_get_training_query_all_params. + _service.disable_retries() + self.test_get_training_query_all_params() @responses.activate - def test_delete_training_queries_value_error(self): + def test_get_training_query_value_error(self): """ - test_delete_training_queries_value_error() + test_get_training_query_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') + mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + responses.add(responses.GET, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' + query_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "query_id": query_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_training_queries(**req_copy) + _service.get_training_query(**req_copy) + def test_get_training_query_value_error_with_retries(self): + # Enable retries and run test_get_training_query_value_error. + _service.enable_retries() + self.test_get_training_query_value_error() + # Disable retries and run test_get_training_query_value_error. + _service.disable_retries() + self.test_get_training_query_value_error() -class TestCreateTrainingQuery(): +class TestUpdateTrainingQuery(): """ - Test Class for create_training_query + Test Class for update_training_query """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_create_training_query_all_params(self): + def test_update_training_query_all_params(self): """ - create_training_query() + update_training_query() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -1741,13 +3347,15 @@ def test_create_training_query_all_params(self): # Set up parameter values project_id = 'testString' + query_id = 'testString' natural_language_query = 'testString' examples = [training_example_model] filter = 'testString' # Invoke method - response = _service.create_training_query( + response = _service.update_training_query( project_id, + query_id, natural_language_query, examples, filter=filter, @@ -1763,14 +3371,22 @@ def test_create_training_query_all_params(self): assert req_body['examples'] == [training_example_model] assert req_body['filter'] == 'testString' + def test_update_training_query_all_params_with_retries(self): + # Enable retries and run test_update_training_query_all_params. + _service.enable_retries() + self.test_update_training_query_all_params() + + # Disable retries and run test_update_training_query_all_params. + _service.disable_retries() + self.test_update_training_query_all_params() @responses.activate - def test_create_training_query_value_error(self): + def test_update_training_query_value_error(self): """ - test_create_training_query_value_error() + test_update_training_query_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries') + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, @@ -1786,6 +3402,7 @@ def test_create_training_query_value_error(self): # Set up parameter values project_id = 'testString' + query_id = 'testString' natural_language_query = 'testString' examples = [training_example_model] filter = 'testString' @@ -1793,40 +3410,121 @@ def test_create_training_query_value_error(self): # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "query_id": query_id, "natural_language_query": natural_language_query, "examples": examples, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.create_training_query(**req_copy) + _service.update_training_query(**req_copy) + def test_update_training_query_value_error_with_retries(self): + # Enable retries and run test_update_training_query_value_error. + _service.enable_retries() + self.test_update_training_query_value_error() + # Disable retries and run test_update_training_query_value_error. + _service.disable_retries() + self.test_update_training_query_value_error() -class TestGetTrainingQuery(): +class TestDeleteTrainingQuery(): """ - Test Class for get_training_query + Test Class for delete_training_query """ - def preprocess_url(self, request_url: str): + @responses.activate + def test_delete_training_query_all_params(self): """ - Preprocess the request URL to ensure the mock response will be found. + delete_training_query() """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Set up mock + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + + # Invoke method + response = _service.delete_training_query( + project_id, + query_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 204 + + def test_delete_training_query_all_params_with_retries(self): + # Enable retries and run test_delete_training_query_all_params. + _service.enable_retries() + self.test_delete_training_query_all_params() + + # Disable retries and run test_delete_training_query_all_params. + _service.disable_retries() + self.test_delete_training_query_all_params() @responses.activate - def test_get_training_query_all_params(self): + def test_delete_training_query_value_error(self): """ - get_training_query() + test_delete_training_query_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + url = preprocess_url('/v2/projects/testString/training_data/queries/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + query_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "query_id": query_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_training_query(**req_copy) + + def test_delete_training_query_value_error_with_retries(self): + # Enable retries and run test_delete_training_query_value_error. + _service.enable_retries() + self.test_delete_training_query_value_error() + + # Disable retries and run test_delete_training_query_value_error. + _service.disable_retries() + self.test_delete_training_query_value_error() + +# endregion +############################################################################## +# End of Service: TrainingData +############################################################################## + +############################################################################## +# Start of Service: Enrichments +############################################################################## +# region + +class TestListEnrichments(): + """ + Test Class for list_enrichments + """ + + @responses.activate + def test_list_enrichments_all_params(self): + """ + list_enrichments() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/enrichments') + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1835,12 +3533,10 @@ def test_get_training_query_all_params(self): # Set up parameter values project_id = 'testString' - query_id = 'testString' # Invoke method - response = _service.get_training_query( + response = _service.list_enrichments( project_id, - query_id, headers={} ) @@ -1848,15 +3544,23 @@ def test_get_training_query_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_enrichments_all_params_with_retries(self): + # Enable retries and run test_list_enrichments_all_params. + _service.enable_retries() + self.test_list_enrichments_all_params() + + # Disable retries and run test_list_enrichments_all_params. + _service.disable_retries() + self.test_list_enrichments_all_params() @responses.activate - def test_get_training_query_value_error(self): + def test_list_enrichments_value_error(self): """ - test_get_training_query_value_error() + test_list_enrichments_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + url = preprocess_url('/v2/projects/testString/enrichments') + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1865,228 +3569,292 @@ def test_get_training_query_value_error(self): # Set up parameter values project_id = 'testString' - query_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "query_id": query_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_training_query(**req_copy) + _service.list_enrichments(**req_copy) + + def test_list_enrichments_value_error_with_retries(self): + # Enable retries and run test_list_enrichments_value_error. + _service.enable_retries() + self.test_list_enrichments_value_error() + + # Disable retries and run test_list_enrichments_value_error. + _service.disable_retries() + self.test_list_enrichments_value_error() + +class TestCreateEnrichment(): + """ + Test Class for create_enrichment + """ + + @responses.activate + def test_create_enrichment_all_params(self): + """ + create_enrichment() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/enrichments') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 + + # Construct a dict representation of a CreateEnrichment model + create_enrichment_model = {} + create_enrichment_model['name'] = 'testString' + create_enrichment_model['description'] = 'testString' + create_enrichment_model['type'] = 'classifier' + create_enrichment_model['options'] = enrichment_options_model + + # Set up parameter values + project_id = 'testString' + enrichment = create_enrichment_model + file = io.BytesIO(b'This is a mock file.').getvalue() + # Invoke method + response = _service.create_enrichment( + project_id, + enrichment, + file=file, + headers={} + ) + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 -class TestUpdateTrainingQuery(): - """ - Test Class for update_training_query - """ + def test_create_enrichment_all_params_with_retries(self): + # Enable retries and run test_create_enrichment_all_params. + _service.enable_retries() + self.test_create_enrichment_all_params() - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Disable retries and run test_create_enrichment_all_params. + _service.disable_retries() + self.test_create_enrichment_all_params() @responses.activate - def test_update_training_query_all_params(self): + def test_create_enrichment_required_params(self): """ - update_training_query() + test_create_enrichment_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + url = preprocess_url('/v2/projects/testString/enrichments') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a TrainingExample model - training_example_model = {} - training_example_model['document_id'] = 'testString' - training_example_model['collection_id'] = 'testString' - training_example_model['relevance'] = 38 + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 + + # Construct a dict representation of a CreateEnrichment model + create_enrichment_model = {} + create_enrichment_model['name'] = 'testString' + create_enrichment_model['description'] = 'testString' + create_enrichment_model['type'] = 'classifier' + create_enrichment_model['options'] = enrichment_options_model # Set up parameter values project_id = 'testString' - query_id = 'testString' - natural_language_query = 'testString' - examples = [training_example_model] - filter = 'testString' + enrichment = create_enrichment_model # Invoke method - response = _service.update_training_query( + response = _service.create_enrichment( project_id, - query_id, - natural_language_query, - examples, - filter=filter, + enrichment, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['natural_language_query'] == 'testString' - assert req_body['examples'] == [training_example_model] - assert req_body['filter'] == 'testString' + def test_create_enrichment_required_params_with_retries(self): + # Enable retries and run test_create_enrichment_required_params. + _service.enable_retries() + self.test_create_enrichment_required_params() + + # Disable retries and run test_create_enrichment_required_params. + _service.disable_retries() + self.test_create_enrichment_required_params() @responses.activate - def test_update_training_query_value_error(self): + def test_create_enrichment_value_error(self): """ - test_update_training_query_value_error() + test_create_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + url = preprocess_url('/v2/projects/testString/enrichments') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a TrainingExample model - training_example_model = {} - training_example_model['document_id'] = 'testString' - training_example_model['collection_id'] = 'testString' - training_example_model['relevance'] = 38 + # Construct a dict representation of a EnrichmentOptions model + enrichment_options_model = {} + enrichment_options_model['languages'] = ['testString'] + enrichment_options_model['entity_type'] = 'testString' + enrichment_options_model['regular_expression'] = 'testString' + enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 + + # Construct a dict representation of a CreateEnrichment model + create_enrichment_model = {} + create_enrichment_model['name'] = 'testString' + create_enrichment_model['description'] = 'testString' + create_enrichment_model['type'] = 'classifier' + create_enrichment_model['options'] = enrichment_options_model # Set up parameter values project_id = 'testString' - query_id = 'testString' - natural_language_query = 'testString' - examples = [training_example_model] - filter = 'testString' + enrichment = create_enrichment_model # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "query_id": query_id, - "natural_language_query": natural_language_query, - "examples": examples, + "enrichment": enrichment, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_training_query(**req_copy) + _service.create_enrichment(**req_copy) + def test_create_enrichment_value_error_with_retries(self): + # Enable retries and run test_create_enrichment_value_error. + _service.enable_retries() + self.test_create_enrichment_value_error() + # Disable retries and run test_create_enrichment_value_error. + _service.disable_retries() + self.test_create_enrichment_value_error() -class TestDeleteTrainingQuery(): +class TestGetEnrichment(): """ - Test Class for delete_training_query + Test Class for get_enrichment """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_delete_training_query_all_params(self): + def test_get_enrichment_all_params(self): """ - delete_training_query() + get_enrichment() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' + responses.add(responses.GET, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' - query_id = 'testString' + enrichment_id = 'testString' # Invoke method - response = _service.delete_training_query( + response = _service.get_enrichment( project_id, - query_id, + enrichment_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 204 + assert response.status_code == 200 + def test_get_enrichment_all_params_with_retries(self): + # Enable retries and run test_get_enrichment_all_params. + _service.enable_retries() + self.test_get_enrichment_all_params() + + # Disable retries and run test_get_enrichment_all_params. + _service.disable_retries() + self.test_get_enrichment_all_params() @responses.activate - def test_delete_training_query_value_error(self): + def test_get_enrichment_value_error(self): """ - test_delete_training_query_value_error() + test_get_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/training_data/queries/testString') - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' + responses.add(responses.GET, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' - query_id = 'testString' + enrichment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "query_id": query_id, + "enrichment_id": enrichment_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_training_query(**req_copy) - - + _service.get_enrichment(**req_copy) -# endregion -############################################################################## -# End of Service: TrainingData -############################################################################## + def test_get_enrichment_value_error_with_retries(self): + # Enable retries and run test_get_enrichment_value_error. + _service.enable_retries() + self.test_get_enrichment_value_error() -############################################################################## -# Start of Service: Analyze -############################################################################## -# region + # Disable retries and run test_get_enrichment_value_error. + _service.disable_retries() + self.test_get_enrichment_value_error() -class TestAnalyzeDocument(): +class TestUpdateEnrichment(): """ - Test Class for analyze_document + Test Class for update_enrichment """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_analyze_document_all_params(self): + def test_update_enrichment_all_params(self): """ - analyze_document() + update_enrichment() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' + url = preprocess_url('/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' responses.add(responses.POST, url, body=mock_response, @@ -2095,36 +3863,44 @@ def test_analyze_document_all_params(self): # Set up parameter values project_id = 'testString' - collection_id = 'testString' - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/json' - metadata = 'testString' + enrichment_id = 'testString' + name = 'testString' + description = 'testString' # Invoke method - response = _service.analyze_document( + response = _service.update_enrichment( project_id, - collection_id, - file=file, - filename=filename, - file_content_type=file_content_type, - metadata=metadata, + enrichment_id, + name, + description=description, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + + def test_update_enrichment_all_params_with_retries(self): + # Enable retries and run test_update_enrichment_all_params. + _service.enable_retries() + self.test_update_enrichment_all_params() + # Disable retries and run test_update_enrichment_all_params. + _service.disable_retries() + self.test_update_enrichment_all_params() @responses.activate - def test_analyze_document_required_params(self): + def test_update_enrichment_value_error(self): """ - test_analyze_document_required_params() + test_update_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' + url = preprocess_url('/v2/projects/testString/enrichments/testString') + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' responses.add(responses.POST, url, body=mock_response, @@ -2133,84 +3909,127 @@ def test_analyze_document_required_params(self): # Set up parameter values project_id = 'testString' - collection_id = 'testString' + enrichment_id = 'testString' + name = 'testString' + description = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "enrichment_id": enrichment_id, + "name": name, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_enrichment(**req_copy) + + def test_update_enrichment_value_error_with_retries(self): + # Enable retries and run test_update_enrichment_value_error. + _service.enable_retries() + self.test_update_enrichment_value_error() + + # Disable retries and run test_update_enrichment_value_error. + _service.disable_retries() + self.test_update_enrichment_value_error() + +class TestDeleteEnrichment(): + """ + Test Class for delete_enrichment + """ + + @responses.activate + def test_delete_enrichment_all_params(self): + """ + delete_enrichment() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/enrichments/testString') + responses.add(responses.DELETE, + url, + status=204) + + # Set up parameter values + project_id = 'testString' + enrichment_id = 'testString' # Invoke method - response = _service.analyze_document( + response = _service.delete_enrichment( project_id, - collection_id, + enrichment_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 204 + + def test_delete_enrichment_all_params_with_retries(self): + # Enable retries and run test_delete_enrichment_all_params. + _service.enable_retries() + self.test_delete_enrichment_all_params() + # Disable retries and run test_delete_enrichment_all_params. + _service.disable_retries() + self.test_delete_enrichment_all_params() @responses.activate - def test_analyze_document_value_error(self): + def test_delete_enrichment_value_error(self): """ - test_analyze_document_value_error() + test_delete_enrichment_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' - responses.add(responses.POST, + url = preprocess_url('/v2/projects/testString/enrichments/testString') + responses.add(responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=200) + status=204) # Set up parameter values project_id = 'testString' - collection_id = 'testString' + enrichment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "collection_id": collection_id, + "enrichment_id": enrichment_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.analyze_document(**req_copy) + _service.delete_enrichment(**req_copy) + def test_delete_enrichment_value_error_with_retries(self): + # Enable retries and run test_delete_enrichment_value_error. + _service.enable_retries() + self.test_delete_enrichment_value_error() + # Disable retries and run test_delete_enrichment_value_error. + _service.disable_retries() + self.test_delete_enrichment_value_error() # endregion ############################################################################## -# End of Service: Analyze +# End of Service: Enrichments ############################################################################## ############################################################################## -# Start of Service: Enrichments +# Start of Service: DocumentClassifiers ############################################################################## # region -class TestListEnrichments(): +class TestListDocumentClassifiers(): """ - Test Class for list_enrichments + Test Class for list_document_classifiers """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_list_enrichments_all_params(self): + def test_list_document_classifiers_all_params(self): """ - list_enrichments() + list_document_classifiers() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') - mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}]}' + url = preprocess_url('/v2/projects/testString/document_classifiers') + mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}]}' responses.add(responses.GET, url, body=mock_response, @@ -2221,7 +4040,7 @@ def test_list_enrichments_all_params(self): project_id = 'testString' # Invoke method - response = _service.list_enrichments( + response = _service.list_document_classifiers( project_id, headers={} ) @@ -2230,15 +4049,23 @@ def test_list_enrichments_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_document_classifiers_all_params_with_retries(self): + # Enable retries and run test_list_document_classifiers_all_params. + _service.enable_retries() + self.test_list_document_classifiers_all_params() + + # Disable retries and run test_list_document_classifiers_all_params. + _service.disable_retries() + self.test_list_document_classifiers_all_params() @responses.activate - def test_list_enrichments_value_error(self): + def test_list_document_classifiers_value_error(self): """ - test_list_enrichments_value_error() + test_list_document_classifiers_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') - mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}]}' + url = preprocess_url('/v2/projects/testString/document_classifiers') + mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}]}' responses.add(responses.GET, url, body=mock_response, @@ -2255,64 +4082,66 @@ def test_list_enrichments_value_error(self): for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_enrichments(**req_copy) + _service.list_document_classifiers(**req_copy) + def test_list_document_classifiers_value_error_with_retries(self): + # Enable retries and run test_list_document_classifiers_value_error. + _service.enable_retries() + self.test_list_document_classifiers_value_error() + # Disable retries and run test_list_document_classifiers_value_error. + _service.disable_retries() + self.test_list_document_classifiers_value_error() -class TestCreateEnrichment(): +class TestCreateDocumentClassifier(): """ - Test Class for create_enrichment + Test Class for create_document_classifier """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_create_enrichment_all_params(self): + def test_create_document_classifier_all_params(self): """ - create_enrichment() + create_document_classifier() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['languages'] = ['testString'] - enrichment_options_model['entity_type'] = 'testString' - enrichment_options_model['regular_expression'] = 'testString' - enrichment_options_model['result_field'] = 'testString' + # Construct a dict representation of a DocumentClassifierEnrichment model + document_classifier_enrichment_model = {} + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] - # Construct a dict representation of a CreateEnrichment model - create_enrichment_model = {} - create_enrichment_model['name'] = 'testString' - create_enrichment_model['description'] = 'testString' - create_enrichment_model['type'] = 'dictionary' - create_enrichment_model['options'] = enrichment_options_model + # Construct a dict representation of a ClassifierFederatedModel model + classifier_federated_model_model = {} + classifier_federated_model_model['field'] = 'testString' + + # Construct a dict representation of a CreateDocumentClassifier model + create_document_classifier_model = {} + create_document_classifier_model['name'] = 'testString' + create_document_classifier_model['description'] = 'testString' + create_document_classifier_model['language'] = 'en' + create_document_classifier_model['answer_field'] = 'testString' + create_document_classifier_model['enrichments'] = [document_classifier_enrichment_model] + create_document_classifier_model['federated_classification'] = classifier_federated_model_model # Set up parameter values project_id = 'testString' - enrichment = create_enrichment_model - file = io.BytesIO(b'This is a mock file.').getvalue() + training_data = io.BytesIO(b'This is a mock file.').getvalue() + classifier = create_document_classifier_model + test_data = io.BytesIO(b'This is a mock file.').getvalue() # Invoke method - response = _service.create_enrichment( + response = _service.create_document_classifier( project_id, - enrichment, - file=file, + training_data, + classifier, + test_data=test_data, headers={} ) @@ -2320,43 +4149,57 @@ def test_create_enrichment_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_document_classifier_all_params_with_retries(self): + # Enable retries and run test_create_document_classifier_all_params. + _service.enable_retries() + self.test_create_document_classifier_all_params() + + # Disable retries and run test_create_document_classifier_all_params. + _service.disable_retries() + self.test_create_document_classifier_all_params() @responses.activate - def test_create_enrichment_required_params(self): + def test_create_document_classifier_required_params(self): """ - test_create_enrichment_required_params() + test_create_document_classifier_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['languages'] = ['testString'] - enrichment_options_model['entity_type'] = 'testString' - enrichment_options_model['regular_expression'] = 'testString' - enrichment_options_model['result_field'] = 'testString' + # Construct a dict representation of a DocumentClassifierEnrichment model + document_classifier_enrichment_model = {} + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] - # Construct a dict representation of a CreateEnrichment model - create_enrichment_model = {} - create_enrichment_model['name'] = 'testString' - create_enrichment_model['description'] = 'testString' - create_enrichment_model['type'] = 'dictionary' - create_enrichment_model['options'] = enrichment_options_model + # Construct a dict representation of a ClassifierFederatedModel model + classifier_federated_model_model = {} + classifier_federated_model_model['field'] = 'testString' + + # Construct a dict representation of a CreateDocumentClassifier model + create_document_classifier_model = {} + create_document_classifier_model['name'] = 'testString' + create_document_classifier_model['description'] = 'testString' + create_document_classifier_model['language'] = 'en' + create_document_classifier_model['answer_field'] = 'testString' + create_document_classifier_model['enrichments'] = [document_classifier_enrichment_model] + create_document_classifier_model['federated_classification'] = classifier_federated_model_model # Set up parameter values project_id = 'testString' - enrichment = create_enrichment_model + training_data = io.BytesIO(b'This is a mock file.').getvalue() + classifier = create_document_classifier_model # Invoke method - response = _service.create_enrichment( + response = _service.create_document_classifier( project_id, - enrichment, + training_data, + classifier, headers={} ) @@ -2364,75 +4207,85 @@ def test_create_enrichment_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 201 + def test_create_document_classifier_required_params_with_retries(self): + # Enable retries and run test_create_document_classifier_required_params. + _service.enable_retries() + self.test_create_document_classifier_required_params() + + # Disable retries and run test_create_document_classifier_required_params. + _service.disable_retries() + self.test_create_document_classifier_required_params() @responses.activate - def test_create_enrichment_value_error(self): + def test_create_document_classifier_value_error(self): """ - test_create_enrichment_value_error() + test_create_document_classifier_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['languages'] = ['testString'] - enrichment_options_model['entity_type'] = 'testString' - enrichment_options_model['regular_expression'] = 'testString' - enrichment_options_model['result_field'] = 'testString' + # Construct a dict representation of a DocumentClassifierEnrichment model + document_classifier_enrichment_model = {} + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] - # Construct a dict representation of a CreateEnrichment model - create_enrichment_model = {} - create_enrichment_model['name'] = 'testString' - create_enrichment_model['description'] = 'testString' - create_enrichment_model['type'] = 'dictionary' - create_enrichment_model['options'] = enrichment_options_model + # Construct a dict representation of a ClassifierFederatedModel model + classifier_federated_model_model = {} + classifier_federated_model_model['field'] = 'testString' + + # Construct a dict representation of a CreateDocumentClassifier model + create_document_classifier_model = {} + create_document_classifier_model['name'] = 'testString' + create_document_classifier_model['description'] = 'testString' + create_document_classifier_model['language'] = 'en' + create_document_classifier_model['answer_field'] = 'testString' + create_document_classifier_model['enrichments'] = [document_classifier_enrichment_model] + create_document_classifier_model['federated_classification'] = classifier_federated_model_model # Set up parameter values project_id = 'testString' - enrichment = create_enrichment_model + training_data = io.BytesIO(b'This is a mock file.').getvalue() + classifier = create_document_classifier_model # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "enrichment": enrichment, + "training_data": training_data, + "classifier": classifier, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.create_enrichment(**req_copy) + _service.create_document_classifier(**req_copy) + def test_create_document_classifier_value_error_with_retries(self): + # Enable retries and run test_create_document_classifier_value_error. + _service.enable_retries() + self.test_create_document_classifier_value_error() + # Disable retries and run test_create_document_classifier_value_error. + _service.disable_retries() + self.test_create_document_classifier_value_error() -class TestGetEnrichment(): +class TestGetDocumentClassifier(): """ - Test Class for get_enrichment + Test Class for get_document_classifier """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_get_enrichment_all_params(self): + def test_get_document_classifier_all_params(self): """ - get_enrichment() + get_document_classifier() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.GET, url, body=mock_response, @@ -2441,12 +4294,12 @@ def test_get_enrichment_all_params(self): # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' + classifier_id = 'testString' # Invoke method - response = _service.get_enrichment( + response = _service.get_document_classifier( project_id, - enrichment_id, + classifier_id, headers={} ) @@ -2454,15 +4307,23 @@ def test_get_enrichment_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_document_classifier_all_params_with_retries(self): + # Enable retries and run test_get_document_classifier_all_params. + _service.enable_retries() + self.test_get_document_classifier_all_params() + + # Disable retries and run test_get_document_classifier_all_params. + _service.disable_retries() + self.test_get_document_classifier_all_params() @responses.activate - def test_get_enrichment_value_error(self): + def test_get_document_classifier_value_error(self): """ - test_get_enrichment_value_error() + test_get_document_classifier_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.GET, url, body=mock_response, @@ -2471,142 +4332,194 @@ def test_get_enrichment_value_error(self): # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' + classifier_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "enrichment_id": enrichment_id, + "classifier_id": classifier_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_enrichment(**req_copy) + _service.get_document_classifier(**req_copy) + def test_get_document_classifier_value_error_with_retries(self): + # Enable retries and run test_get_document_classifier_value_error. + _service.enable_retries() + self.test_get_document_classifier_value_error() + # Disable retries and run test_get_document_classifier_value_error. + _service.disable_retries() + self.test_get_document_classifier_value_error() -class TestUpdateEnrichment(): +class TestUpdateDocumentClassifier(): """ - Test Class for update_enrichment + Test Class for update_document_classifier """ - def preprocess_url(self, request_url: str): + @responses.activate + def test_update_document_classifier_all_params(self): """ - Preprocess the request URL to ensure the mock response will be found. + update_document_classifier() """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Set up mock + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) + + # Construct a dict representation of a UpdateDocumentClassifier model + update_document_classifier_model = {} + update_document_classifier_model['name'] = 'testString' + update_document_classifier_model['description'] = 'testString' + + # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' + classifier = update_document_classifier_model + training_data = io.BytesIO(b'This is a mock file.').getvalue() + test_data = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = _service.update_document_classifier( + project_id, + classifier_id, + classifier, + training_data=training_data, + test_data=test_data, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 201 + + def test_update_document_classifier_all_params_with_retries(self): + # Enable retries and run test_update_document_classifier_all_params. + _service.enable_retries() + self.test_update_document_classifier_all_params() + + # Disable retries and run test_update_document_classifier_all_params. + _service.disable_retries() + self.test_update_document_classifier_all_params() @responses.activate - def test_update_enrichment_all_params(self): + def test_update_document_classifier_required_params(self): """ - update_enrichment() + test_update_document_classifier_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=201) + + # Construct a dict representation of a UpdateDocumentClassifier model + update_document_classifier_model = {} + update_document_classifier_model['name'] = 'testString' + update_document_classifier_model['description'] = 'testString' # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' - name = 'testString' - description = 'testString' + classifier_id = 'testString' + classifier = update_document_classifier_model # Invoke method - response = _service.update_enrichment( + response = _service.update_document_classifier( project_id, - enrichment_id, - name, - description=description, + classifier_id, + classifier, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' + assert response.status_code == 201 + def test_update_document_classifier_required_params_with_retries(self): + # Enable retries and run test_update_document_classifier_required_params. + _service.enable_retries() + self.test_update_document_classifier_required_params() + + # Disable retries and run test_update_document_classifier_required_params. + _service.disable_retries() + self.test_update_document_classifier_required_params() @responses.activate - def test_update_enrichment_value_error(self): + def test_update_document_classifier_value_error(self): """ - test_update_enrichment_value_error() + test_update_document_classifier_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field"}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') + mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=201) + + # Construct a dict representation of a UpdateDocumentClassifier model + update_document_classifier_model = {} + update_document_classifier_model['name'] = 'testString' + update_document_classifier_model['description'] = 'testString' # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' - name = 'testString' - description = 'testString' + classifier_id = 'testString' + classifier = update_document_classifier_model # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "enrichment_id": enrichment_id, - "name": name, + "classifier_id": classifier_id, + "classifier": classifier, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_enrichment(**req_copy) + _service.update_document_classifier(**req_copy) + def test_update_document_classifier_value_error_with_retries(self): + # Enable retries and run test_update_document_classifier_value_error. + _service.enable_retries() + self.test_update_document_classifier_value_error() + # Disable retries and run test_update_document_classifier_value_error. + _service.disable_retries() + self.test_update_document_classifier_value_error() -class TestDeleteEnrichment(): +class TestDeleteDocumentClassifier(): """ - Test Class for delete_enrichment + Test Class for delete_document_classifier """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_delete_enrichment_all_params(self): + def test_delete_document_classifier_all_params(self): """ - delete_enrichment() + delete_document_classifier() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') responses.add(responses.DELETE, url, status=204) # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' + classifier_id = 'testString' # Invoke method - response = _service.delete_enrichment( + response = _service.delete_document_classifier( project_id, - enrichment_id, + classifier_id, headers={} ) @@ -2614,281 +4527,263 @@ def test_delete_enrichment_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 204 + def test_delete_document_classifier_all_params_with_retries(self): + # Enable retries and run test_delete_document_classifier_all_params. + _service.enable_retries() + self.test_delete_document_classifier_all_params() + + # Disable retries and run test_delete_document_classifier_all_params. + _service.disable_retries() + self.test_delete_document_classifier_all_params() @responses.activate - def test_delete_enrichment_value_error(self): + def test_delete_document_classifier_value_error(self): """ - test_delete_enrichment_value_error() + test_delete_document_classifier_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString/enrichments/testString') + url = preprocess_url('/v2/projects/testString/document_classifiers/testString') responses.add(responses.DELETE, url, status=204) # Set up parameter values project_id = 'testString' - enrichment_id = 'testString' + classifier_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, - "enrichment_id": enrichment_id, + "classifier_id": classifier_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_enrichment(**req_copy) + _service.delete_document_classifier(**req_copy) + def test_delete_document_classifier_value_error_with_retries(self): + # Enable retries and run test_delete_document_classifier_value_error. + _service.enable_retries() + self.test_delete_document_classifier_value_error() + # Disable retries and run test_delete_document_classifier_value_error. + _service.disable_retries() + self.test_delete_document_classifier_value_error() # endregion ############################################################################## -# End of Service: Enrichments +# End of Service: DocumentClassifiers ############################################################################## ############################################################################## -# Start of Service: Projects +# Start of Service: DocumentClassifierModels ############################################################################## # region -class TestListProjects(): +class TestListDocumentClassifierModels(): """ - Test Class for list_projects + Test Class for list_document_classifier_models """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_list_projects_all_params(self): + def test_list_document_classifier_models_all_params(self): """ - list_projects() + list_document_classifier_models() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects') - mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') + mock_response = '{"models": [{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) - # Invoke method - response = _service.list_projects() + # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' + # Invoke method + response = _service.list_document_classifier_models( + project_id, + classifier_id, + headers={} + ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + def test_list_document_classifier_models_all_params_with_retries(self): + # Enable retries and run test_list_document_classifier_models_all_params. + _service.enable_retries() + self.test_list_document_classifier_models_all_params() + + # Disable retries and run test_list_document_classifier_models_all_params. + _service.disable_retries() + self.test_list_document_classifier_models_all_params() @responses.activate - def test_list_projects_value_error(self): + def test_list_document_classifier_models_value_error(self): """ - test_list_projects_value_error() + test_list_document_classifier_models_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects') - mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') + mock_response = '{"models": [{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, content_type='application/json', status=200) + # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' + # Pass in all but one required param and check for a ValueError req_param_dict = { + "project_id": project_id, + "classifier_id": classifier_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_projects(**req_copy) + _service.list_document_classifier_models(**req_copy) + def test_list_document_classifier_models_value_error_with_retries(self): + # Enable retries and run test_list_document_classifier_models_value_error. + _service.enable_retries() + self.test_list_document_classifier_models_value_error() + # Disable retries and run test_list_document_classifier_models_value_error. + _service.disable_retries() + self.test_list_document_classifier_models_value_error() -class TestCreateProject(): +class TestCreateDocumentClassifierModel(): """ - Test Class for create_project + Test Class for create_document_classifier_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_create_project_all_params(self): + def test_create_document_classifier_model_all_params(self): """ - create_project() + create_document_classifier_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) - - # Construct a dict representation of a DefaultQueryParamsPassages model - default_query_params_passages_model = {} - default_query_params_passages_model['enabled'] = True - default_query_params_passages_model['count'] = 38 - default_query_params_passages_model['fields'] = ['testString'] - default_query_params_passages_model['characters'] = 38 - default_query_params_passages_model['per_document'] = True - default_query_params_passages_model['max_per_document'] = 38 - - # Construct a dict representation of a DefaultQueryParamsTableResults model - default_query_params_table_results_model = {} - default_query_params_table_results_model['enabled'] = True - default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 - - # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model - default_query_params_suggested_refinements_model = {} - default_query_params_suggested_refinements_model['enabled'] = True - default_query_params_suggested_refinements_model['count'] = 38 - - # Construct a dict representation of a DefaultQueryParams model - default_query_params_model = {} - default_query_params_model['collection_ids'] = ['testString'] - default_query_params_model['passages'] = default_query_params_passages_model - default_query_params_model['table_results'] = default_query_params_table_results_model - default_query_params_model['aggregation'] = 'testString' - default_query_params_model['suggested_refinements'] = default_query_params_suggested_refinements_model - default_query_params_model['spelling_suggestions'] = True - default_query_params_model['highlight'] = True - default_query_params_model['count'] = 38 - default_query_params_model['sort'] = 'testString' - default_query_params_model['return'] = ['testString'] + status=201) # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' name = 'testString' - type = 'document_retrieval' - default_query_parameters = default_query_params_model + description = 'testString' + learning_rate = 0 + l1_regularization_strengths = [1.0E-6] + l2_regularization_strengths = [1.0E-6] + training_max_steps = 0 + improvement_ratio = 0 # Invoke method - response = _service.create_project( + response = _service.create_document_classifier_model( + project_id, + classifier_id, name, - type, - default_query_parameters=default_query_parameters, + description=description, + learning_rate=learning_rate, + l1_regularization_strengths=l1_regularization_strengths, + l2_regularization_strengths=l2_regularization_strengths, + training_max_steps=training_max_steps, + improvement_ratio=improvement_ratio, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 201 # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['type'] == 'document_retrieval' - assert req_body['default_query_parameters'] == default_query_params_model - - - @responses.activate - def test_create_project_value_error(self): - """ - test_create_project_value_error() - """ - # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Construct a dict representation of a DefaultQueryParamsPassages model - default_query_params_passages_model = {} - default_query_params_passages_model['enabled'] = True - default_query_params_passages_model['count'] = 38 - default_query_params_passages_model['fields'] = ['testString'] - default_query_params_passages_model['characters'] = 38 - default_query_params_passages_model['per_document'] = True - default_query_params_passages_model['max_per_document'] = 38 + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['learning_rate'] == 0 + assert req_body['l1_regularization_strengths'] == [1.0E-6] + assert req_body['l2_regularization_strengths'] == [1.0E-6] + assert req_body['training_max_steps'] == 0 + assert req_body['improvement_ratio'] == 0 - # Construct a dict representation of a DefaultQueryParamsTableResults model - default_query_params_table_results_model = {} - default_query_params_table_results_model['enabled'] = True - default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 + def test_create_document_classifier_model_all_params_with_retries(self): + # Enable retries and run test_create_document_classifier_model_all_params. + _service.enable_retries() + self.test_create_document_classifier_model_all_params() - # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model - default_query_params_suggested_refinements_model = {} - default_query_params_suggested_refinements_model['enabled'] = True - default_query_params_suggested_refinements_model['count'] = 38 + # Disable retries and run test_create_document_classifier_model_all_params. + _service.disable_retries() + self.test_create_document_classifier_model_all_params() - # Construct a dict representation of a DefaultQueryParams model - default_query_params_model = {} - default_query_params_model['collection_ids'] = ['testString'] - default_query_params_model['passages'] = default_query_params_passages_model - default_query_params_model['table_results'] = default_query_params_table_results_model - default_query_params_model['aggregation'] = 'testString' - default_query_params_model['suggested_refinements'] = default_query_params_suggested_refinements_model - default_query_params_model['spelling_suggestions'] = True - default_query_params_model['highlight'] = True - default_query_params_model['count'] = 38 - default_query_params_model['sort'] = 'testString' - default_query_params_model['return'] = ['testString'] + @responses.activate + def test_create_document_classifier_model_value_error(self): + """ + test_create_document_classifier_model_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201) # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' name = 'testString' - type = 'document_retrieval' - default_query_parameters = default_query_params_model + description = 'testString' + learning_rate = 0 + l1_regularization_strengths = [1.0E-6] + l2_regularization_strengths = [1.0E-6] + training_max_steps = 0 + improvement_ratio = 0 # Pass in all but one required param and check for a ValueError req_param_dict = { + "project_id": project_id, + "classifier_id": classifier_id, "name": name, - "type": type, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.create_project(**req_copy) + _service.create_document_classifier_model(**req_copy) + def test_create_document_classifier_model_value_error_with_retries(self): + # Enable retries and run test_create_document_classifier_model_value_error. + _service.enable_retries() + self.test_create_document_classifier_model_value_error() + # Disable retries and run test_create_document_classifier_model_value_error. + _service.disable_retries() + self.test_create_document_classifier_model_value_error() -class TestGetProject(): +class TestGetDocumentClassifierModel(): """ - Test Class for get_project + Test Class for get_document_classifier_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_get_project_all_params(self): + def test_get_document_classifier_model_all_params(self): """ - get_project() + get_document_classifier_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -2897,10 +4792,14 @@ def test_get_project_all_params(self): # Set up parameter values project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' # Invoke method - response = _service.get_project( + response = _service.get_document_classifier_model( project_id, + classifier_id, + model_id, headers={} ) @@ -2908,15 +4807,23 @@ def test_get_project_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 + def test_get_document_classifier_model_all_params_with_retries(self): + # Enable retries and run test_get_document_classifier_model_all_params. + _service.enable_retries() + self.test_get_document_classifier_model_all_params() + + # Disable retries and run test_get_document_classifier_model_all_params. + _service.disable_retries() + self.test_get_document_classifier_model_all_params() @responses.activate - def test_get_project_value_error(self): + def test_get_document_classifier_model_value_error(self): """ - test_get_project_value_error() + test_get_document_classifier_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -2925,192 +4832,340 @@ def test_get_project_value_error(self): # Set up parameter values project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "classifier_id": classifier_id, + "model_id": model_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_project(**req_copy) + _service.get_document_classifier_model(**req_copy) + def test_get_document_classifier_model_value_error_with_retries(self): + # Enable retries and run test_get_document_classifier_model_value_error. + _service.enable_retries() + self.test_get_document_classifier_model_value_error() + # Disable retries and run test_get_document_classifier_model_value_error. + _service.disable_retries() + self.test_get_document_classifier_model_value_error() -class TestUpdateProject(): +class TestUpdateDocumentClassifierModel(): """ - Test Class for update_project + Test Class for update_document_classifier_model """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate - def test_update_project_all_params(self): + def test_update_document_classifier_model_all_params(self): """ - update_project() + update_document_classifier_model() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=201) # Set up parameter values project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' name = 'testString' + description = 'testString' # Invoke method - response = _service.update_project( + response = _service.update_document_classifier_model( project_id, + classifier_id, + model_id, name=name, + description=description, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 201 # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + def test_update_document_classifier_model_all_params_with_retries(self): + # Enable retries and run test_update_document_classifier_model_all_params. + _service.enable_retries() + self.test_update_document_classifier_model_all_params() + + # Disable retries and run test_update_document_classifier_model_all_params. + _service.disable_retries() + self.test_update_document_classifier_model_all_params() @responses.activate - def test_update_project_required_params(self): + def test_update_document_classifier_model_value_error(self): """ - test_update_project_required_params() + test_update_document_classifier_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', - status=200) + status=201) + + # Set up parameter values + project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' + name = 'testString' + description = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "classifier_id": classifier_id, + "model_id": model_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_document_classifier_model(**req_copy) + + def test_update_document_classifier_model_value_error_with_retries(self): + # Enable retries and run test_update_document_classifier_model_value_error. + _service.enable_retries() + self.test_update_document_classifier_model_value_error() + + # Disable retries and run test_update_document_classifier_model_value_error. + _service.disable_retries() + self.test_update_document_classifier_model_value_error() + +class TestDeleteDocumentClassifierModel(): + """ + Test Class for delete_document_classifier_model + """ + + @responses.activate + def test_delete_document_classifier_model_all_params(self): + """ + delete_document_classifier_model() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + responses.add(responses.DELETE, + url, + status=204) # Set up parameter values project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' # Invoke method - response = _service.update_project( + response = _service.delete_document_classifier_model( project_id, + classifier_id, + model_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 204 + + def test_delete_document_classifier_model_all_params_with_retries(self): + # Enable retries and run test_delete_document_classifier_model_all_params. + _service.enable_retries() + self.test_delete_document_classifier_model_all_params() + # Disable retries and run test_delete_document_classifier_model_all_params. + _service.disable_retries() + self.test_delete_document_classifier_model_all_params() @responses.activate - def test_update_project_value_error(self): + def test_delete_document_classifier_model_value_error(self): """ - test_update_project_value_error() + test_delete_document_classifier_model_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, + url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') + responses.add(responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=200) + status=204) # Set up parameter values project_id = 'testString' + classifier_id = 'testString' + model_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "classifier_id": classifier_id, + "model_id": model_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_project(**req_copy) + _service.delete_document_classifier_model(**req_copy) + def test_delete_document_classifier_model_value_error_with_retries(self): + # Enable retries and run test_delete_document_classifier_model_value_error. + _service.enable_retries() + self.test_delete_document_classifier_model_value_error() + # Disable retries and run test_delete_document_classifier_model_value_error. + _service.disable_retries() + self.test_delete_document_classifier_model_value_error() -class TestDeleteProject(): +# endregion +############################################################################## +# End of Service: DocumentClassifierModels +############################################################################## + +############################################################################## +# Start of Service: Analyze +############################################################################## +# region + +class TestAnalyzeDocument(): """ - Test Class for delete_project + Test Class for analyze_document """ - def preprocess_url(self, request_url: str): + @responses.activate + def test_analyze_document_all_params(self): """ - Preprocess the request URL to ensure the mock response will be found. + analyze_document() """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + file_content_type = 'application/json' + metadata = 'testString' + + # Invoke method + response = _service.analyze_document( + project_id, + collection_id, + file=file, + filename=filename, + file_content_type=file_content_type, + metadata=metadata, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_analyze_document_all_params_with_retries(self): + # Enable retries and run test_analyze_document_all_params. + _service.enable_retries() + self.test_analyze_document_all_params() + + # Disable retries and run test_analyze_document_all_params. + _service.disable_retries() + self.test_analyze_document_all_params() @responses.activate - def test_delete_project_all_params(self): + def test_analyze_document_required_params(self): """ - delete_project() + test_analyze_document_required_params() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' + responses.add(responses.POST, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' + collection_id = 'testString' # Invoke method - response = _service.delete_project( + response = _service.analyze_document( project_id, + collection_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 204 + assert response.status_code == 200 + + def test_analyze_document_required_params_with_retries(self): + # Enable retries and run test_analyze_document_required_params. + _service.enable_retries() + self.test_analyze_document_required_params() + # Disable retries and run test_analyze_document_required_params. + _service.disable_retries() + self.test_analyze_document_required_params() @responses.activate - def test_delete_project_value_error(self): + def test_analyze_document_value_error(self): """ - test_delete_project_value_error() + test_analyze_document_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/projects/testString') - responses.add(responses.DELETE, + url = preprocess_url('/v2/projects/testString/collections/testString/analyze') + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' + responses.add(responses.POST, url, - status=204) + body=mock_response, + content_type='application/json', + status=200) # Set up parameter values project_id = 'testString' + collection_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "project_id": project_id, + "collection_id": collection_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_project(**req_copy) + _service.analyze_document(**req_copy) + def test_analyze_document_value_error_with_retries(self): + # Enable retries and run test_analyze_document_value_error. + _service.enable_retries() + self.test_analyze_document_value_error() + # Disable retries and run test_analyze_document_value_error. + _service.disable_retries() + self.test_analyze_document_value_error() # endregion ############################################################################## -# End of Service: Projects +# End of Service: Analyze ############################################################################## ############################################################################## @@ -3123,24 +5178,13 @@ class TestDeleteUserData(): Test Class for delete_user_data """ - def preprocess_url(self, request_url: str): - """ - Preprocess the request URL to ensure the mock response will be found. - """ - request_url = urllib.parse.unquote(request_url) # don't double-encode if already encoded - request_url = urllib.parse.quote(request_url, safe=':/') - if re.fullmatch('.*/+', request_url) is None: - return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') - @responses.activate def test_delete_user_data_all_params(self): """ delete_user_data() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/user_data') + url = preprocess_url('/v2/user_data') responses.add(responses.DELETE, url, status=200) @@ -3162,6 +5206,14 @@ def test_delete_user_data_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string + def test_delete_user_data_all_params_with_retries(self): + # Enable retries and run test_delete_user_data_all_params. + _service.enable_retries() + self.test_delete_user_data_all_params() + + # Disable retries and run test_delete_user_data_all_params. + _service.disable_retries() + self.test_delete_user_data_all_params() @responses.activate def test_delete_user_data_value_error(self): @@ -3169,7 +5221,7 @@ def test_delete_user_data_value_error(self): test_delete_user_data_value_error() """ # Set up mock - url = self.preprocess_url(_base_url + '/v2/user_data') + url = preprocess_url('/v2/user_data') responses.add(responses.DELETE, url, status=200) @@ -3186,7 +5238,14 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) + def test_delete_user_data_value_error_with_retries(self): + # Enable retries and run test_delete_user_data_value_error. + _service.enable_retries() + self.test_delete_user_data_value_error() + # Disable retries and run test_delete_user_data_value_error. + _service.disable_retries() + self.test_delete_user_data_value_error() # endregion ############################################################################## @@ -3212,7 +5271,7 @@ def test_analyzed_document_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = "2019-01-01T12:00:00Z" + notice_model['created'] = '2019-01-01T12:00:00Z' notice_model['document_id'] = 'testString' notice_model['collection_id'] = 'testString' notice_model['query_id'] = 'testString' @@ -3221,8 +5280,8 @@ def test_analyzed_document_serialization(self): notice_model['description'] = 'testString' analyzed_result_model = {} # AnalyzedResult - analyzed_result_model['metadata'] = {} - analyzed_result_model['foo'] = { 'foo': 'bar' } + analyzed_result_model['metadata'] = {'key1': 'testString'} + analyzed_result_model['foo'] = {'foo': 'bar'} # Construct a json representation of a AnalyzedDocument model analyzed_document_model_json = {} @@ -3256,8 +5315,8 @@ def test_analyzed_result_serialization(self): # Construct a json representation of a AnalyzedResult model analyzed_result_model_json = {} - analyzed_result_model_json['metadata'] = {} - analyzed_result_model_json['foo'] = { 'foo': 'bar' } + analyzed_result_model_json['metadata'] = {'key1': 'testString'} + analyzed_result_model_json['foo'] = {'foo': 'bar'} # Construct a model instance of AnalyzedResult by calling from_dict on the json representation analyzed_result_model = AnalyzedResult.from_dict(analyzed_result_model_json) @@ -3279,11 +5338,89 @@ def test_analyzed_result_serialization(self): actual_dict = analyzed_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': { 'foo': 'bar' }} + expected_dict = {'foo': {'foo': 'bar'}} analyzed_result_model.set_properties(expected_dict) actual_dict = analyzed_result_model.get_properties() assert actual_dict == expected_dict +class TestModel_ClassifierFederatedModel(): + """ + Test Class for ClassifierFederatedModel + """ + + def test_classifier_federated_model_serialization(self): + """ + Test serialization/deserialization for ClassifierFederatedModel + """ + + # Construct a json representation of a ClassifierFederatedModel model + classifier_federated_model_model_json = {} + classifier_federated_model_model_json['field'] = 'testString' + + # Construct a model instance of ClassifierFederatedModel by calling from_dict on the json representation + classifier_federated_model_model = ClassifierFederatedModel.from_dict(classifier_federated_model_model_json) + assert classifier_federated_model_model != False + + # Construct a model instance of ClassifierFederatedModel by calling from_dict on the json representation + classifier_federated_model_model_dict = ClassifierFederatedModel.from_dict(classifier_federated_model_model_json).__dict__ + classifier_federated_model_model2 = ClassifierFederatedModel(**classifier_federated_model_model_dict) + + # Verify the model instances are equivalent + assert classifier_federated_model_model == classifier_federated_model_model2 + + # Convert model instance back to dict and verify no loss of data + classifier_federated_model_model_json2 = classifier_federated_model_model.to_dict() + assert classifier_federated_model_model_json2 == classifier_federated_model_model_json + +class TestModel_ClassifierModelEvaluation(): + """ + Test Class for ClassifierModelEvaluation + """ + + def test_classifier_model_evaluation_serialization(self): + """ + Test serialization/deserialization for ClassifierModelEvaluation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model['precision'] = 0 + model_evaluation_micro_average_model['recall'] = 0 + model_evaluation_micro_average_model['f1'] = 0 + + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model['precision'] = 0 + model_evaluation_macro_average_model['recall'] = 0 + model_evaluation_macro_average_model['f1'] = 0 + + per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model['name'] = 'testString' + per_class_model_evaluation_model['precision'] = 0 + per_class_model_evaluation_model['recall'] = 0 + per_class_model_evaluation_model['f1'] = 0 + + # Construct a json representation of a ClassifierModelEvaluation model + classifier_model_evaluation_model_json = {} + classifier_model_evaluation_model_json['micro_average'] = model_evaluation_micro_average_model + classifier_model_evaluation_model_json['macro_average'] = model_evaluation_macro_average_model + classifier_model_evaluation_model_json['per_class'] = [per_class_model_evaluation_model] + + # Construct a model instance of ClassifierModelEvaluation by calling from_dict on the json representation + classifier_model_evaluation_model = ClassifierModelEvaluation.from_dict(classifier_model_evaluation_model_json) + assert classifier_model_evaluation_model != False + + # Construct a model instance of ClassifierModelEvaluation by calling from_dict on the json representation + classifier_model_evaluation_model_dict = ClassifierModelEvaluation.from_dict(classifier_model_evaluation_model_json).__dict__ + classifier_model_evaluation_model2 = ClassifierModelEvaluation(**classifier_model_evaluation_model_dict) + + # Verify the model instances are equivalent + assert classifier_model_evaluation_model == classifier_model_evaluation_model2 + + # Convert model instance back to dict and verify no loss of data + classifier_model_evaluation_model_json2 = classifier_model_evaluation_model.to_dict() + assert classifier_model_evaluation_model_json2 == classifier_model_evaluation_model_json + class TestModel_Collection(): """ Test Class for Collection @@ -3330,29 +5467,64 @@ def test_collection_details_serialization(self): collection_enrichment_model['enrichment_id'] = 'testString' collection_enrichment_model['fields'] = ['testString'] + collection_details_smart_document_understanding_model = {} # CollectionDetailsSmartDocumentUnderstanding + collection_details_smart_document_understanding_model['enabled'] = True + collection_details_smart_document_understanding_model['model'] = 'custom' + # Construct a json representation of a CollectionDetails model collection_details_model_json = {} collection_details_model_json['collection_id'] = 'testString' collection_details_model_json['name'] = 'testString' collection_details_model_json['description'] = 'testString' - collection_details_model_json['created'] = "2019-01-01T12:00:00Z" + collection_details_model_json['created'] = '2019-01-01T12:00:00Z' collection_details_model_json['language'] = 'en' collection_details_model_json['enrichments'] = [collection_enrichment_model] + collection_details_model_json['smart_document_understanding'] = collection_details_smart_document_understanding_model + + # Construct a model instance of CollectionDetails by calling from_dict on the json representation + collection_details_model = CollectionDetails.from_dict(collection_details_model_json) + assert collection_details_model != False + + # Construct a model instance of CollectionDetails by calling from_dict on the json representation + collection_details_model_dict = CollectionDetails.from_dict(collection_details_model_json).__dict__ + collection_details_model2 = CollectionDetails(**collection_details_model_dict) + + # Verify the model instances are equivalent + assert collection_details_model == collection_details_model2 + + # Convert model instance back to dict and verify no loss of data + collection_details_model_json2 = collection_details_model.to_dict() + assert collection_details_model_json2 == collection_details_model_json + +class TestModel_CollectionDetailsSmartDocumentUnderstanding(): + """ + Test Class for CollectionDetailsSmartDocumentUnderstanding + """ + + def test_collection_details_smart_document_understanding_serialization(self): + """ + Test serialization/deserialization for CollectionDetailsSmartDocumentUnderstanding + """ - # Construct a model instance of CollectionDetails by calling from_dict on the json representation - collection_details_model = CollectionDetails.from_dict(collection_details_model_json) - assert collection_details_model != False + # Construct a json representation of a CollectionDetailsSmartDocumentUnderstanding model + collection_details_smart_document_understanding_model_json = {} + collection_details_smart_document_understanding_model_json['enabled'] = True + collection_details_smart_document_understanding_model_json['model'] = 'custom' - # Construct a model instance of CollectionDetails by calling from_dict on the json representation - collection_details_model_dict = CollectionDetails.from_dict(collection_details_model_json).__dict__ - collection_details_model2 = CollectionDetails(**collection_details_model_dict) + # Construct a model instance of CollectionDetailsSmartDocumentUnderstanding by calling from_dict on the json representation + collection_details_smart_document_understanding_model = CollectionDetailsSmartDocumentUnderstanding.from_dict(collection_details_smart_document_understanding_model_json) + assert collection_details_smart_document_understanding_model != False + + # Construct a model instance of CollectionDetailsSmartDocumentUnderstanding by calling from_dict on the json representation + collection_details_smart_document_understanding_model_dict = CollectionDetailsSmartDocumentUnderstanding.from_dict(collection_details_smart_document_understanding_model_json).__dict__ + collection_details_smart_document_understanding_model2 = CollectionDetailsSmartDocumentUnderstanding(**collection_details_smart_document_understanding_model_dict) # Verify the model instances are equivalent - assert collection_details_model == collection_details_model2 + assert collection_details_smart_document_understanding_model == collection_details_smart_document_understanding_model2 # Convert model instance back to dict and verify no loss of data - collection_details_model_json2 = collection_details_model.to_dict() - assert collection_details_model_json2 == collection_details_model_json + collection_details_smart_document_understanding_model_json2 = collection_details_smart_document_understanding_model.to_dict() + assert collection_details_smart_document_understanding_model_json2 == collection_details_smart_document_understanding_model_json class TestModel_CollectionEnrichment(): """ @@ -3595,6 +5767,49 @@ def test_component_settings_response_serialization(self): component_settings_response_model_json2 = component_settings_response_model.to_dict() assert component_settings_response_model_json2 == component_settings_response_model_json +class TestModel_CreateDocumentClassifier(): + """ + Test Class for CreateDocumentClassifier + """ + + def test_create_document_classifier_serialization(self): + """ + Test serialization/deserialization for CreateDocumentClassifier + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] + + classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model['field'] = 'testString' + + # Construct a json representation of a CreateDocumentClassifier model + create_document_classifier_model_json = {} + create_document_classifier_model_json['name'] = 'testString' + create_document_classifier_model_json['description'] = 'testString' + create_document_classifier_model_json['language'] = 'en' + create_document_classifier_model_json['answer_field'] = 'testString' + create_document_classifier_model_json['enrichments'] = [document_classifier_enrichment_model] + create_document_classifier_model_json['federated_classification'] = classifier_federated_model_model + + # Construct a model instance of CreateDocumentClassifier by calling from_dict on the json representation + create_document_classifier_model = CreateDocumentClassifier.from_dict(create_document_classifier_model_json) + assert create_document_classifier_model != False + + # Construct a model instance of CreateDocumentClassifier by calling from_dict on the json representation + create_document_classifier_model_dict = CreateDocumentClassifier.from_dict(create_document_classifier_model_json).__dict__ + create_document_classifier_model2 = CreateDocumentClassifier(**create_document_classifier_model_dict) + + # Verify the model instances are equivalent + assert create_document_classifier_model == create_document_classifier_model2 + + # Convert model instance back to dict and verify no loss of data + create_document_classifier_model_json2 = create_document_classifier_model.to_dict() + assert create_document_classifier_model_json2 == create_document_classifier_model_json + class TestModel_CreateEnrichment(): """ Test Class for CreateEnrichment @@ -3612,12 +5827,16 @@ def test_create_enrichment_serialization(self): enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 # Construct a json representation of a CreateEnrichment model create_enrichment_model_json = {} create_enrichment_model_json['name'] = 'testString' create_enrichment_model_json['description'] = 'testString' - create_enrichment_model_json['type'] = 'dictionary' + create_enrichment_model_json['type'] = 'classifier' create_enrichment_model_json['options'] = enrichment_options_model # Construct a model instance of CreateEnrichment by calling from_dict on the json representation @@ -3884,6 +6103,345 @@ def test_document_attribute_serialization(self): document_attribute_model_json2 = document_attribute_model.to_dict() assert document_attribute_model_json2 == document_attribute_model_json +class TestModel_DocumentClassifier(): + """ + Test Class for DocumentClassifier + """ + + def test_document_classifier_serialization(self): + """ + Test serialization/deserialization for DocumentClassifier + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] + + classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model['field'] = 'testString' + + # Construct a json representation of a DocumentClassifier model + document_classifier_model_json = {} + document_classifier_model_json['classifier_id'] = 'testString' + document_classifier_model_json['name'] = 'testString' + document_classifier_model_json['description'] = 'testString' + document_classifier_model_json['created'] = '2019-01-01T12:00:00Z' + document_classifier_model_json['language'] = 'en' + document_classifier_model_json['enrichments'] = [document_classifier_enrichment_model] + document_classifier_model_json['recognized_fields'] = ['testString'] + document_classifier_model_json['answer_field'] = 'testString' + document_classifier_model_json['training_data_file'] = 'testString' + document_classifier_model_json['test_data_file'] = 'testString' + document_classifier_model_json['federated_classification'] = classifier_federated_model_model + + # Construct a model instance of DocumentClassifier by calling from_dict on the json representation + document_classifier_model = DocumentClassifier.from_dict(document_classifier_model_json) + assert document_classifier_model != False + + # Construct a model instance of DocumentClassifier by calling from_dict on the json representation + document_classifier_model_dict = DocumentClassifier.from_dict(document_classifier_model_json).__dict__ + document_classifier_model2 = DocumentClassifier(**document_classifier_model_dict) + + # Verify the model instances are equivalent + assert document_classifier_model == document_classifier_model2 + + # Convert model instance back to dict and verify no loss of data + document_classifier_model_json2 = document_classifier_model.to_dict() + assert document_classifier_model_json2 == document_classifier_model_json + +class TestModel_DocumentClassifierEnrichment(): + """ + Test Class for DocumentClassifierEnrichment + """ + + def test_document_classifier_enrichment_serialization(self): + """ + Test serialization/deserialization for DocumentClassifierEnrichment + """ + + # Construct a json representation of a DocumentClassifierEnrichment model + document_classifier_enrichment_model_json = {} + document_classifier_enrichment_model_json['enrichment_id'] = 'testString' + document_classifier_enrichment_model_json['fields'] = ['testString'] + + # Construct a model instance of DocumentClassifierEnrichment by calling from_dict on the json representation + document_classifier_enrichment_model = DocumentClassifierEnrichment.from_dict(document_classifier_enrichment_model_json) + assert document_classifier_enrichment_model != False + + # Construct a model instance of DocumentClassifierEnrichment by calling from_dict on the json representation + document_classifier_enrichment_model_dict = DocumentClassifierEnrichment.from_dict(document_classifier_enrichment_model_json).__dict__ + document_classifier_enrichment_model2 = DocumentClassifierEnrichment(**document_classifier_enrichment_model_dict) + + # Verify the model instances are equivalent + assert document_classifier_enrichment_model == document_classifier_enrichment_model2 + + # Convert model instance back to dict and verify no loss of data + document_classifier_enrichment_model_json2 = document_classifier_enrichment_model.to_dict() + assert document_classifier_enrichment_model_json2 == document_classifier_enrichment_model_json + +class TestModel_DocumentClassifierModel(): + """ + Test Class for DocumentClassifierModel + """ + + def test_document_classifier_model_serialization(self): + """ + Test serialization/deserialization for DocumentClassifierModel + """ + + # Construct dict forms of any model objects needed in order to build this model. + + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model['precision'] = 0 + model_evaluation_micro_average_model['recall'] = 0 + model_evaluation_micro_average_model['f1'] = 0 + + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model['precision'] = 0 + model_evaluation_macro_average_model['recall'] = 0 + model_evaluation_macro_average_model['f1'] = 0 + + per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model['name'] = 'testString' + per_class_model_evaluation_model['precision'] = 0 + per_class_model_evaluation_model['recall'] = 0 + per_class_model_evaluation_model['f1'] = 0 + + classifier_model_evaluation_model = {} # ClassifierModelEvaluation + classifier_model_evaluation_model['micro_average'] = model_evaluation_micro_average_model + classifier_model_evaluation_model['macro_average'] = model_evaluation_macro_average_model + classifier_model_evaluation_model['per_class'] = [per_class_model_evaluation_model] + + # Construct a json representation of a DocumentClassifierModel model + document_classifier_model_model_json = {} + document_classifier_model_model_json['model_id'] = 'testString' + document_classifier_model_model_json['name'] = 'testString' + document_classifier_model_model_json['description'] = 'testString' + document_classifier_model_model_json['created'] = '2019-01-01T12:00:00Z' + document_classifier_model_model_json['updated'] = '2019-01-01T12:00:00Z' + document_classifier_model_model_json['training_data_file'] = 'testString' + document_classifier_model_model_json['test_data_file'] = 'testString' + document_classifier_model_model_json['status'] = 'training' + document_classifier_model_model_json['evaluation'] = classifier_model_evaluation_model + document_classifier_model_model_json['enrichment_id'] = 'testString' + document_classifier_model_model_json['deployed_at'] = '2019-01-01T12:00:00Z' + + # Construct a model instance of DocumentClassifierModel by calling from_dict on the json representation + document_classifier_model_model = DocumentClassifierModel.from_dict(document_classifier_model_model_json) + assert document_classifier_model_model != False + + # Construct a model instance of DocumentClassifierModel by calling from_dict on the json representation + document_classifier_model_model_dict = DocumentClassifierModel.from_dict(document_classifier_model_model_json).__dict__ + document_classifier_model_model2 = DocumentClassifierModel(**document_classifier_model_model_dict) + + # Verify the model instances are equivalent + assert document_classifier_model_model == document_classifier_model_model2 + + # Convert model instance back to dict and verify no loss of data + document_classifier_model_model_json2 = document_classifier_model_model.to_dict() + assert document_classifier_model_model_json2 == document_classifier_model_model_json + +class TestModel_DocumentClassifierModels(): + """ + Test Class for DocumentClassifierModels + """ + + def test_document_classifier_models_serialization(self): + """ + Test serialization/deserialization for DocumentClassifierModels + """ + + # Construct dict forms of any model objects needed in order to build this model. + + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model['precision'] = 0 + model_evaluation_micro_average_model['recall'] = 0 + model_evaluation_micro_average_model['f1'] = 0 + + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model['precision'] = 0 + model_evaluation_macro_average_model['recall'] = 0 + model_evaluation_macro_average_model['f1'] = 0 + + per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model['name'] = 'testString' + per_class_model_evaluation_model['precision'] = 0 + per_class_model_evaluation_model['recall'] = 0 + per_class_model_evaluation_model['f1'] = 0 + + classifier_model_evaluation_model = {} # ClassifierModelEvaluation + classifier_model_evaluation_model['micro_average'] = model_evaluation_micro_average_model + classifier_model_evaluation_model['macro_average'] = model_evaluation_macro_average_model + classifier_model_evaluation_model['per_class'] = [per_class_model_evaluation_model] + + document_classifier_model_model = {} # DocumentClassifierModel + document_classifier_model_model['model_id'] = 'testString' + document_classifier_model_model['name'] = 'testString' + document_classifier_model_model['description'] = 'testString' + document_classifier_model_model['created'] = '2019-01-01T12:00:00Z' + document_classifier_model_model['updated'] = '2019-01-01T12:00:00Z' + document_classifier_model_model['training_data_file'] = 'testString' + document_classifier_model_model['test_data_file'] = 'testString' + document_classifier_model_model['status'] = 'training' + document_classifier_model_model['evaluation'] = classifier_model_evaluation_model + document_classifier_model_model['enrichment_id'] = 'testString' + document_classifier_model_model['deployed_at'] = '2019-01-01T12:00:00Z' + + # Construct a json representation of a DocumentClassifierModels model + document_classifier_models_model_json = {} + document_classifier_models_model_json['models'] = [document_classifier_model_model] + + # Construct a model instance of DocumentClassifierModels by calling from_dict on the json representation + document_classifier_models_model = DocumentClassifierModels.from_dict(document_classifier_models_model_json) + assert document_classifier_models_model != False + + # Construct a model instance of DocumentClassifierModels by calling from_dict on the json representation + document_classifier_models_model_dict = DocumentClassifierModels.from_dict(document_classifier_models_model_json).__dict__ + document_classifier_models_model2 = DocumentClassifierModels(**document_classifier_models_model_dict) + + # Verify the model instances are equivalent + assert document_classifier_models_model == document_classifier_models_model2 + + # Convert model instance back to dict and verify no loss of data + document_classifier_models_model_json2 = document_classifier_models_model.to_dict() + assert document_classifier_models_model_json2 == document_classifier_models_model_json + +class TestModel_DocumentClassifiers(): + """ + Test Class for DocumentClassifiers + """ + + def test_document_classifiers_serialization(self): + """ + Test serialization/deserialization for DocumentClassifiers + """ + + # Construct dict forms of any model objects needed in order to build this model. + + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model['enrichment_id'] = 'testString' + document_classifier_enrichment_model['fields'] = ['testString'] + + classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model['field'] = 'testString' + + document_classifier_model = {} # DocumentClassifier + document_classifier_model['classifier_id'] = 'testString' + document_classifier_model['name'] = 'testString' + document_classifier_model['description'] = 'testString' + document_classifier_model['created'] = '2019-01-01T12:00:00Z' + document_classifier_model['language'] = 'en' + document_classifier_model['enrichments'] = [document_classifier_enrichment_model] + document_classifier_model['recognized_fields'] = ['testString'] + document_classifier_model['answer_field'] = 'testString' + document_classifier_model['training_data_file'] = 'testString' + document_classifier_model['test_data_file'] = 'testString' + document_classifier_model['federated_classification'] = classifier_federated_model_model + + # Construct a json representation of a DocumentClassifiers model + document_classifiers_model_json = {} + document_classifiers_model_json['classifiers'] = [document_classifier_model] + + # Construct a model instance of DocumentClassifiers by calling from_dict on the json representation + document_classifiers_model = DocumentClassifiers.from_dict(document_classifiers_model_json) + assert document_classifiers_model != False + + # Construct a model instance of DocumentClassifiers by calling from_dict on the json representation + document_classifiers_model_dict = DocumentClassifiers.from_dict(document_classifiers_model_json).__dict__ + document_classifiers_model2 = DocumentClassifiers(**document_classifiers_model_dict) + + # Verify the model instances are equivalent + assert document_classifiers_model == document_classifiers_model2 + + # Convert model instance back to dict and verify no loss of data + document_classifiers_model_json2 = document_classifiers_model.to_dict() + assert document_classifiers_model_json2 == document_classifiers_model_json + +class TestModel_DocumentDetails(): + """ + Test Class for DocumentDetails + """ + + def test_document_details_serialization(self): + """ + Test serialization/deserialization for DocumentDetails + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['notice_id'] = 'testString' + notice_model['created'] = '2019-01-01T12:00:00Z' + notice_model['document_id'] = 'testString' + notice_model['collection_id'] = 'testString' + notice_model['query_id'] = 'testString' + notice_model['severity'] = 'warning' + notice_model['step'] = 'testString' + notice_model['description'] = 'testString' + + document_details_children_model = {} # DocumentDetailsChildren + document_details_children_model['have_notices'] = True + document_details_children_model['count'] = 38 + + # Construct a json representation of a DocumentDetails model + document_details_model_json = {} + document_details_model_json['document_id'] = 'testString' + document_details_model_json['created'] = '2019-01-01T12:00:00Z' + document_details_model_json['updated'] = '2019-01-01T12:00:00Z' + document_details_model_json['status'] = 'available' + document_details_model_json['notices'] = [notice_model] + document_details_model_json['children'] = document_details_children_model + document_details_model_json['filename'] = 'testString' + document_details_model_json['file_type'] = 'testString' + document_details_model_json['sha256'] = 'testString' + + # Construct a model instance of DocumentDetails by calling from_dict on the json representation + document_details_model = DocumentDetails.from_dict(document_details_model_json) + assert document_details_model != False + + # Construct a model instance of DocumentDetails by calling from_dict on the json representation + document_details_model_dict = DocumentDetails.from_dict(document_details_model_json).__dict__ + document_details_model2 = DocumentDetails(**document_details_model_dict) + + # Verify the model instances are equivalent + assert document_details_model == document_details_model2 + + # Convert model instance back to dict and verify no loss of data + document_details_model_json2 = document_details_model.to_dict() + assert document_details_model_json2 == document_details_model_json + +class TestModel_DocumentDetailsChildren(): + """ + Test Class for DocumentDetailsChildren + """ + + def test_document_details_children_serialization(self): + """ + Test serialization/deserialization for DocumentDetailsChildren + """ + + # Construct a json representation of a DocumentDetailsChildren model + document_details_children_model_json = {} + document_details_children_model_json['have_notices'] = True + document_details_children_model_json['count'] = 38 + + # Construct a model instance of DocumentDetailsChildren by calling from_dict on the json representation + document_details_children_model = DocumentDetailsChildren.from_dict(document_details_children_model_json) + assert document_details_children_model != False + + # Construct a model instance of DocumentDetailsChildren by calling from_dict on the json representation + document_details_children_model_dict = DocumentDetailsChildren.from_dict(document_details_children_model_json).__dict__ + document_details_children_model2 = DocumentDetailsChildren(**document_details_children_model_dict) + + # Verify the model instances are equivalent + assert document_details_children_model == document_details_children_model2 + + # Convert model instance back to dict and verify no loss of data + document_details_children_model_json2 = document_details_children_model.to_dict() + assert document_details_children_model_json2 == document_details_children_model_json + class TestModel_Enrichment(): """ Test Class for Enrichment @@ -3901,6 +6459,10 @@ def test_enrichment_serialization(self): enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 # Construct a json representation of a Enrichment model enrichment_model_json = {} @@ -3941,6 +6503,10 @@ def test_enrichment_options_serialization(self): enrichment_options_model_json['entity_type'] = 'testString' enrichment_options_model_json['regular_expression'] = 'testString' enrichment_options_model_json['result_field'] = 'testString' + enrichment_options_model_json['classifier_id'] = 'testString' + enrichment_options_model_json['model_id'] = 'testString' + enrichment_options_model_json['confidence_threshold'] = 0 + enrichment_options_model_json['top_k'] = 38 # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation enrichment_options_model = EnrichmentOptions.from_dict(enrichment_options_model_json) @@ -3974,6 +6540,10 @@ def test_enrichments_serialization(self): enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' enrichment_options_model['result_field'] = 'testString' + enrichment_options_model['classifier_id'] = 'testString' + enrichment_options_model['model_id'] = 'testString' + enrichment_options_model['confidence_threshold'] = 0 + enrichment_options_model['top_k'] = 38 enrichment_model = {} # Enrichment enrichment_model['enrichment_id'] = 'testString' @@ -4001,6 +6571,71 @@ def test_enrichments_serialization(self): enrichments_model_json2 = enrichments_model.to_dict() assert enrichments_model_json2 == enrichments_model_json +class TestModel_Expansion(): + """ + Test Class for Expansion + """ + + def test_expansion_serialization(self): + """ + Test serialization/deserialization for Expansion + """ + + # Construct a json representation of a Expansion model + expansion_model_json = {} + expansion_model_json['input_terms'] = ['testString'] + expansion_model_json['expanded_terms'] = ['testString'] + + # Construct a model instance of Expansion by calling from_dict on the json representation + expansion_model = Expansion.from_dict(expansion_model_json) + assert expansion_model != False + + # Construct a model instance of Expansion by calling from_dict on the json representation + expansion_model_dict = Expansion.from_dict(expansion_model_json).__dict__ + expansion_model2 = Expansion(**expansion_model_dict) + + # Verify the model instances are equivalent + assert expansion_model == expansion_model2 + + # Convert model instance back to dict and verify no loss of data + expansion_model_json2 = expansion_model.to_dict() + assert expansion_model_json2 == expansion_model_json + +class TestModel_Expansions(): + """ + Test Class for Expansions + """ + + def test_expansions_serialization(self): + """ + Test serialization/deserialization for Expansions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + expansion_model = {} # Expansion + expansion_model['input_terms'] = ['testString'] + expansion_model['expanded_terms'] = ['testString'] + + # Construct a json representation of a Expansions model + expansions_model_json = {} + expansions_model_json['expansions'] = [expansion_model] + + # Construct a model instance of Expansions by calling from_dict on the json representation + expansions_model = Expansions.from_dict(expansions_model_json) + assert expansions_model != False + + # Construct a model instance of Expansions by calling from_dict on the json representation + expansions_model_dict = Expansions.from_dict(expansions_model_json).__dict__ + expansions_model2 = Expansions(**expansions_model_dict) + + # Verify the model instances are equivalent + assert expansions_model == expansions_model2 + + # Convert model instance back to dict and verify no loss of data + expansions_model_json2 = expansions_model.to_dict() + assert expansions_model_json2 == expansions_model_json + class TestModel_Field(): """ Test Class for Field @@ -4067,6 +6702,63 @@ def test_list_collections_response_serialization(self): list_collections_response_model_json2 = list_collections_response_model.to_dict() assert list_collections_response_model_json2 == list_collections_response_model_json +class TestModel_ListDocumentsResponse(): + """ + Test Class for ListDocumentsResponse + """ + + def test_list_documents_response_serialization(self): + """ + Test serialization/deserialization for ListDocumentsResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + notice_model = {} # Notice + notice_model['notice_id'] = 'testString' + notice_model['created'] = '2019-01-01T12:00:00Z' + notice_model['document_id'] = 'testString' + notice_model['collection_id'] = 'testString' + notice_model['query_id'] = 'testString' + notice_model['severity'] = 'warning' + notice_model['step'] = 'testString' + notice_model['description'] = 'testString' + + document_details_children_model = {} # DocumentDetailsChildren + document_details_children_model['have_notices'] = True + document_details_children_model['count'] = 38 + + document_details_model = {} # DocumentDetails + document_details_model['document_id'] = '4ffcfd8052005b99469e632506763bac_0' + document_details_model['created'] = '2019-01-01T12:00:00Z' + document_details_model['updated'] = '2019-01-01T12:00:00Z' + document_details_model['status'] = 'available' + document_details_model['notices'] = [notice_model] + document_details_model['children'] = document_details_children_model + document_details_model['filename'] = 'testString' + document_details_model['file_type'] = 'testString' + document_details_model['sha256'] = 'testString' + + # Construct a json representation of a ListDocumentsResponse model + list_documents_response_model_json = {} + list_documents_response_model_json['matching_results'] = 38 + list_documents_response_model_json['documents'] = [document_details_model] + + # Construct a model instance of ListDocumentsResponse by calling from_dict on the json representation + list_documents_response_model = ListDocumentsResponse.from_dict(list_documents_response_model_json) + assert list_documents_response_model != False + + # Construct a model instance of ListDocumentsResponse by calling from_dict on the json representation + list_documents_response_model_dict = ListDocumentsResponse.from_dict(list_documents_response_model_json).__dict__ + list_documents_response_model2 = ListDocumentsResponse(**list_documents_response_model_dict) + + # Verify the model instances are equivalent + assert list_documents_response_model == list_documents_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_documents_response_model_json2 = list_documents_response_model.to_dict() + assert list_documents_response_model_json2 == list_documents_response_model_json + class TestModel_ListFieldsResponse(): """ Test Class for ListFieldsResponse @@ -4152,6 +6844,68 @@ def test_list_projects_response_serialization(self): list_projects_response_model_json2 = list_projects_response_model.to_dict() assert list_projects_response_model_json2 == list_projects_response_model_json +class TestModel_ModelEvaluationMacroAverage(): + """ + Test Class for ModelEvaluationMacroAverage + """ + + def test_model_evaluation_macro_average_serialization(self): + """ + Test serialization/deserialization for ModelEvaluationMacroAverage + """ + + # Construct a json representation of a ModelEvaluationMacroAverage model + model_evaluation_macro_average_model_json = {} + model_evaluation_macro_average_model_json['precision'] = 0 + model_evaluation_macro_average_model_json['recall'] = 0 + model_evaluation_macro_average_model_json['f1'] = 0 + + # Construct a model instance of ModelEvaluationMacroAverage by calling from_dict on the json representation + model_evaluation_macro_average_model = ModelEvaluationMacroAverage.from_dict(model_evaluation_macro_average_model_json) + assert model_evaluation_macro_average_model != False + + # Construct a model instance of ModelEvaluationMacroAverage by calling from_dict on the json representation + model_evaluation_macro_average_model_dict = ModelEvaluationMacroAverage.from_dict(model_evaluation_macro_average_model_json).__dict__ + model_evaluation_macro_average_model2 = ModelEvaluationMacroAverage(**model_evaluation_macro_average_model_dict) + + # Verify the model instances are equivalent + assert model_evaluation_macro_average_model == model_evaluation_macro_average_model2 + + # Convert model instance back to dict and verify no loss of data + model_evaluation_macro_average_model_json2 = model_evaluation_macro_average_model.to_dict() + assert model_evaluation_macro_average_model_json2 == model_evaluation_macro_average_model_json + +class TestModel_ModelEvaluationMicroAverage(): + """ + Test Class for ModelEvaluationMicroAverage + """ + + def test_model_evaluation_micro_average_serialization(self): + """ + Test serialization/deserialization for ModelEvaluationMicroAverage + """ + + # Construct a json representation of a ModelEvaluationMicroAverage model + model_evaluation_micro_average_model_json = {} + model_evaluation_micro_average_model_json['precision'] = 0 + model_evaluation_micro_average_model_json['recall'] = 0 + model_evaluation_micro_average_model_json['f1'] = 0 + + # Construct a model instance of ModelEvaluationMicroAverage by calling from_dict on the json representation + model_evaluation_micro_average_model = ModelEvaluationMicroAverage.from_dict(model_evaluation_micro_average_model_json) + assert model_evaluation_micro_average_model != False + + # Construct a model instance of ModelEvaluationMicroAverage by calling from_dict on the json representation + model_evaluation_micro_average_model_dict = ModelEvaluationMicroAverage.from_dict(model_evaluation_micro_average_model_json).__dict__ + model_evaluation_micro_average_model2 = ModelEvaluationMicroAverage(**model_evaluation_micro_average_model_dict) + + # Verify the model instances are equivalent + assert model_evaluation_micro_average_model == model_evaluation_micro_average_model2 + + # Convert model instance back to dict and verify no loss of data + model_evaluation_micro_average_model_json2 = model_evaluation_micro_average_model.to_dict() + assert model_evaluation_micro_average_model_json2 == model_evaluation_micro_average_model_json + class TestModel_Notice(): """ Test Class for Notice @@ -4165,7 +6919,7 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} notice_model_json['notice_id'] = 'testString' - notice_model_json['created'] = "2019-01-01T12:00:00Z" + notice_model_json['created'] = '2019-01-01T12:00:00Z' notice_model_json['document_id'] = 'testString' notice_model_json['collection_id'] = 'testString' notice_model_json['query_id'] = 'testString' @@ -4188,6 +6942,38 @@ def test_notice_serialization(self): notice_model_json2 = notice_model.to_dict() assert notice_model_json2 == notice_model_json +class TestModel_PerClassModelEvaluation(): + """ + Test Class for PerClassModelEvaluation + """ + + def test_per_class_model_evaluation_serialization(self): + """ + Test serialization/deserialization for PerClassModelEvaluation + """ + + # Construct a json representation of a PerClassModelEvaluation model + per_class_model_evaluation_model_json = {} + per_class_model_evaluation_model_json['name'] = 'testString' + per_class_model_evaluation_model_json['precision'] = 0 + per_class_model_evaluation_model_json['recall'] = 0 + per_class_model_evaluation_model_json['f1'] = 0 + + # Construct a model instance of PerClassModelEvaluation by calling from_dict on the json representation + per_class_model_evaluation_model = PerClassModelEvaluation.from_dict(per_class_model_evaluation_model_json) + assert per_class_model_evaluation_model != False + + # Construct a model instance of PerClassModelEvaluation by calling from_dict on the json representation + per_class_model_evaluation_model_dict = PerClassModelEvaluation.from_dict(per_class_model_evaluation_model_json).__dict__ + per_class_model_evaluation_model2 = PerClassModelEvaluation(**per_class_model_evaluation_model_dict) + + # Verify the model instances are equivalent + assert per_class_model_evaluation_model == per_class_model_evaluation_model2 + + # Convert model instance back to dict and verify no loss of data + per_class_model_evaluation_model_json2 = per_class_model_evaluation_model.to_dict() + assert per_class_model_evaluation_model_json2 == per_class_model_evaluation_model_json + class TestModel_ProjectDetails(): """ Test Class for ProjectDetails @@ -4491,6 +7277,37 @@ def test_query_large_passages_serialization(self): query_large_passages_model_json2 = query_large_passages_model.to_dict() assert query_large_passages_model_json2 == query_large_passages_model_json +class TestModel_QueryLargeSimilar(): + """ + Test Class for QueryLargeSimilar + """ + + def test_query_large_similar_serialization(self): + """ + Test serialization/deserialization for QueryLargeSimilar + """ + + # Construct a json representation of a QueryLargeSimilar model + query_large_similar_model_json = {} + query_large_similar_model_json['enabled'] = False + query_large_similar_model_json['document_ids'] = ['testString'] + query_large_similar_model_json['fields'] = ['testString'] + + # Construct a model instance of QueryLargeSimilar by calling from_dict on the json representation + query_large_similar_model = QueryLargeSimilar.from_dict(query_large_similar_model_json) + assert query_large_similar_model != False + + # Construct a model instance of QueryLargeSimilar by calling from_dict on the json representation + query_large_similar_model_dict = QueryLargeSimilar.from_dict(query_large_similar_model_json).__dict__ + query_large_similar_model2 = QueryLargeSimilar(**query_large_similar_model_dict) + + # Verify the model instances are equivalent + assert query_large_similar_model == query_large_similar_model2 + + # Convert model instance back to dict and verify no loss of data + query_large_similar_model_json2 = query_large_similar_model.to_dict() + assert query_large_similar_model_json2 == query_large_similar_model_json + class TestModel_QueryLargeSuggestedRefinements(): """ Test Class for QueryLargeSuggestedRefinements @@ -4565,7 +7382,7 @@ def test_query_notices_response_serialization(self): notice_model = {} # Notice notice_model['notice_id'] = 'testString' - notice_model['created'] = "2019-01-01T12:00:00Z" + notice_model['created'] = '2019-01-01T12:00:00Z' notice_model['document_id'] = 'testString' notice_model['collection_id'] = 'testString' notice_model['query_id'] = 'testString' @@ -4626,10 +7443,10 @@ def test_query_response_serialization(self): query_result_model = {} # QueryResult query_result_model['document_id'] = 'testString' - query_result_model['metadata'] = {} + query_result_model['metadata'] = {'key1': 'testString'} query_result_model['result_metadata'] = query_result_metadata_model query_result_model['document_passages'] = [query_result_passage_model] - query_result_model['id'] = { 'foo': 'bar' } + query_result_model['id'] = {'foo': 'bar'} query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' @@ -4652,7 +7469,7 @@ def test_query_response_serialization(self): table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['location'] = {'foo': 'bar'} table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 @@ -4671,7 +7488,7 @@ def test_query_response_serialization(self): table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = { 'foo': 'bar' } + table_column_headers_model['location'] = {'foo': 'bar'} table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -4868,10 +7685,10 @@ def test_query_result_serialization(self): # Construct a json representation of a QueryResult model query_result_model_json = {} query_result_model_json['document_id'] = 'testString' - query_result_model_json['metadata'] = {} + query_result_model_json['metadata'] = {'key1': 'testString'} query_result_model_json['result_metadata'] = query_result_metadata_model query_result_model_json['document_passages'] = [query_result_passage_model] - query_result_model_json['foo'] = { 'foo': 'bar' } + query_result_model_json['foo'] = {'foo': 'bar'} # Construct a model instance of QueryResult by calling from_dict on the json representation query_result_model = QueryResult.from_dict(query_result_model_json) @@ -4893,7 +7710,7 @@ def test_query_result_serialization(self): actual_dict = query_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': { 'foo': 'bar' }} + expected_dict = {'foo': {'foo': 'bar'}} query_result_model.set_properties(expected_dict) actual_dict = query_result_model.get_properties() assert actual_dict == expected_dict @@ -5022,7 +7839,7 @@ def test_query_table_result_serialization(self): table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['location'] = {'foo': 'bar'} table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 @@ -5041,7 +7858,7 @@ def test_query_table_result_serialization(self): table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = { 'foo': 'bar' } + table_column_headers_model['location'] = {'foo': 'bar'} table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -5231,7 +8048,7 @@ def test_query_top_hits_aggregation_result_serialization(self): # Construct a json representation of a QueryTopHitsAggregationResult model query_top_hits_aggregation_result_model_json = {} query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{}] + query_top_hits_aggregation_result_model_json['hits'] = [{'key1': 'testString'}] # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) @@ -5309,6 +8126,35 @@ def test_retrieval_details_serialization(self): retrieval_details_model_json2 = retrieval_details_model.to_dict() assert retrieval_details_model_json2 == retrieval_details_model_json +class TestModel_StopWordList(): + """ + Test Class for StopWordList + """ + + def test_stop_word_list_serialization(self): + """ + Test serialization/deserialization for StopWordList + """ + + # Construct a json representation of a StopWordList model + stop_word_list_model_json = {} + stop_word_list_model_json['stopwords'] = ['testString'] + + # Construct a model instance of StopWordList by calling from_dict on the json representation + stop_word_list_model = StopWordList.from_dict(stop_word_list_model_json) + assert stop_word_list_model != False + + # Construct a model instance of StopWordList by calling from_dict on the json representation + stop_word_list_model_dict = StopWordList.from_dict(stop_word_list_model_json).__dict__ + stop_word_list_model2 = StopWordList(**stop_word_list_model_dict) + + # Verify the model instances are equivalent + assert stop_word_list_model == stop_word_list_model2 + + # Convert model instance back to dict and verify no loss of data + stop_word_list_model_json2 = stop_word_list_model.to_dict() + assert stop_word_list_model_json2 == stop_word_list_model_json + class TestModel_TableBodyCells(): """ Test Class for TableBodyCells @@ -5554,7 +8400,7 @@ def test_table_column_headers_serialization(self): # Construct a json representation of a TableColumnHeaders model table_column_headers_model_json = {} table_column_headers_model_json['cell_id'] = 'testString' - table_column_headers_model_json['location'] = { 'foo': 'bar' } + table_column_headers_model_json['location'] = {'foo': 'bar'} table_column_headers_model_json['text'] = 'testString' table_column_headers_model_json['text_normalized'] = 'testString' table_column_headers_model_json['row_index_begin'] = 26 @@ -5620,7 +8466,7 @@ def test_table_headers_serialization(self): # Construct a json representation of a TableHeaders model table_headers_model_json = {} table_headers_model_json['cell_id'] = 'testString' - table_headers_model_json['location'] = { 'foo': 'bar' } + table_headers_model_json['location'] = {'foo': 'bar'} table_headers_model_json['text'] = 'testString' table_headers_model_json['row_index_begin'] = 26 table_headers_model_json['row_index_end'] = 26 @@ -5710,7 +8556,7 @@ def test_table_result_table_serialization(self): table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = { 'foo': 'bar' } + table_headers_model['location'] = {'foo': 'bar'} table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 @@ -5729,7 +8575,7 @@ def test_table_result_table_serialization(self): table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = { 'foo': 'bar' } + table_column_headers_model['location'] = {'foo': 'bar'} table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -5998,8 +8844,8 @@ def test_training_example_serialization(self): training_example_model_json['document_id'] = 'testString' training_example_model_json['collection_id'] = 'testString' training_example_model_json['relevance'] = 38 - training_example_model_json['created'] = "2019-01-01T12:00:00Z" - training_example_model_json['updated'] = "2019-01-01T12:00:00Z" + training_example_model_json['created'] = '2019-01-01T12:00:00Z' + training_example_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of TrainingExample by calling from_dict on the json representation training_example_model = TrainingExample.from_dict(training_example_model_json) @@ -6032,16 +8878,16 @@ def test_training_query_serialization(self): training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_example_model['created'] = "2019-01-01T12:00:00Z" - training_example_model['updated'] = "2019-01-01T12:00:00Z" + training_example_model['created'] = '2019-01-01T12:00:00Z' + training_example_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a TrainingQuery model training_query_model_json = {} training_query_model_json['query_id'] = 'testString' training_query_model_json['natural_language_query'] = 'testString' training_query_model_json['filter'] = 'testString' - training_query_model_json['created'] = "2019-01-01T12:00:00Z" - training_query_model_json['updated'] = "2019-01-01T12:00:00Z" + training_query_model_json['created'] = '2019-01-01T12:00:00Z' + training_query_model_json['updated'] = '2019-01-01T12:00:00Z' training_query_model_json['examples'] = [training_example_model] # Construct a model instance of TrainingQuery by calling from_dict on the json representation @@ -6075,15 +8921,15 @@ def test_training_query_set_serialization(self): training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_example_model['created'] = "2019-01-01T12:00:00Z" - training_example_model['updated'] = "2019-01-01T12:00:00Z" + training_example_model['created'] = '2019-01-01T12:00:00Z' + training_example_model['updated'] = '2019-01-01T12:00:00Z' training_query_model = {} # TrainingQuery training_query_model['query_id'] = 'testString' training_query_model['natural_language_query'] = 'testString' training_query_model['filter'] = 'testString' - training_query_model['created'] = "2019-01-01T12:00:00Z" - training_query_model['updated'] = "2019-01-01T12:00:00Z" + training_query_model['created'] = '2019-01-01T12:00:00Z' + training_query_model['updated'] = '2019-01-01T12:00:00Z' training_query_model['examples'] = [training_example_model] # Construct a json representation of a TrainingQuerySet model @@ -6105,6 +8951,36 @@ def test_training_query_set_serialization(self): training_query_set_model_json2 = training_query_set_model.to_dict() assert training_query_set_model_json2 == training_query_set_model_json +class TestModel_UpdateDocumentClassifier(): + """ + Test Class for UpdateDocumentClassifier + """ + + def test_update_document_classifier_serialization(self): + """ + Test serialization/deserialization for UpdateDocumentClassifier + """ + + # Construct a json representation of a UpdateDocumentClassifier model + update_document_classifier_model_json = {} + update_document_classifier_model_json['name'] = 'testString' + update_document_classifier_model_json['description'] = 'testString' + + # Construct a model instance of UpdateDocumentClassifier by calling from_dict on the json representation + update_document_classifier_model = UpdateDocumentClassifier.from_dict(update_document_classifier_model_json) + assert update_document_classifier_model != False + + # Construct a model instance of UpdateDocumentClassifier by calling from_dict on the json representation + update_document_classifier_model_dict = UpdateDocumentClassifier.from_dict(update_document_classifier_model_json).__dict__ + update_document_classifier_model2 = UpdateDocumentClassifier(**update_document_classifier_model_dict) + + # Verify the model instances are equivalent + assert update_document_classifier_model == update_document_classifier_model2 + + # Convert model instance back to dict and verify no loss of data + update_document_classifier_model_json2 = update_document_classifier_model.to_dict() + assert update_document_classifier_model_json2 == update_document_classifier_model_json + class TestModel_QueryCalculationAggregation(): """ Test Class for QueryCalculationAggregation @@ -6337,7 +9213,7 @@ def test_query_top_hits_aggregation_serialization(self): query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{}] + query_top_hits_aggregation_result_model['hits'] = [{'key1': 'testString'}] # Construct a json representation of a QueryTopHitsAggregation model query_top_hits_aggregation_model_json = {} From 446f502c1ca4eabce8155eacaf13ab491621cc04 Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Wed, 10 Aug 2022 09:23:25 -0500 Subject: [PATCH 372/455] refactor(lt): minor code cleanup --- ibm_watson/language_translator_v3.py | 69 +++++++++++++++++++++--- test/unit/test_language_translator_v3.py | 17 ++---- 2 files changed, 65 insertions(+), 21 deletions(-) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index d24244403..1985d86b3 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 """ IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM-provided translation models that you can customize based on @@ -107,6 +107,7 @@ def list_languages(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/languages' @@ -182,6 +183,7 @@ def translate(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/translate' @@ -221,6 +223,7 @@ def list_identifiable_languages(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/identifiable_languages' @@ -259,6 +262,7 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/identify' @@ -315,6 +319,7 @@ def list_models(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/models' @@ -330,7 +335,9 @@ def create_model(self, base_model_id: str, *, forced_glossary: BinaryIO = None, + forced_glossary_content_type: str = None, parallel_corpus: BinaryIO = None, + parallel_corpus_content_type: str = None, name: str = None, **kwargs) -> DetailedResponse: """ @@ -409,6 +416,8 @@ def create_model(self, words or short phrases. For more information, see **Supported file formats** in the method description. *With `curl`, use `--form forced_glossary=@{filename}`.*. + :param str forced_glossary_content_type: (optional) The content type of + forced_glossary. :param BinaryIO parallel_corpus: (optional) A file with parallel sentences for the source and target languages. You can upload multiple parallel corpus files in one request by repeating the parameter. All uploaded @@ -420,6 +429,8 @@ def create_model(self, MB. For more information, see **Supported file formats** in the method description. *With `curl`, use `--form parallel_corpus=@{filename}`.*. + :param str parallel_corpus_content_type: (optional) The content type of + parallel_corpus. :param str name: (optional) An optional model name that you can use to identify the model. Valid characters are letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32 @@ -445,14 +456,19 @@ def create_model(self, form_data = [] if forced_glossary: - form_data.append(('forced_glossary', (None, forced_glossary, - 'application/octet-stream'))) + form_data.append( + ('forced_glossary', + (None, forced_glossary, forced_glossary_content_type or + 'application/octet-stream'))) if parallel_corpus: - form_data.append(('parallel_corpus', (None, parallel_corpus, - 'application/octet-stream'))) + form_data.append( + ('parallel_corpus', + (None, parallel_corpus, parallel_corpus_content_type or + 'application/octet-stream'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/models' @@ -489,6 +505,7 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -529,6 +546,7 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -568,6 +586,7 @@ def list_documents(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/documents' @@ -596,14 +615,16 @@ def translate_document(self, `file` parameter, or you can reference a previously submitted document by document ID. The maximum file size for document translation is * 20 MB for service instances on the Standard, Advanced, and Premium plans - * 2 MB for service instances on the Lite plan. + * 2 MB for service instances on the Lite plan + **Note:** When translating a previously submitted document, the target language + must be different from the target language of the original request when the + document was initially submitted. :param BinaryIO file: The contents of the source file to translate. The maximum file size for document translation is 20 MB for service instances on the Standard, Advanced, and Premium plans, and 2 MB for service instances on the Lite plan. For more information, see [Supported file - formats - (Beta)](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). + formats](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str model_id: (optional) The model to use for translation. For @@ -653,6 +674,7 @@ def translate_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v3/documents' @@ -690,6 +712,7 @@ def get_document_status(self, document_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['document_id'] @@ -728,6 +751,7 @@ def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['document_id'] path_param_values = self.encode_path_vars(document_id) @@ -784,6 +808,7 @@ def get_translated_document(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['document_id'] path_param_values = self.encode_path_vars(document_id) @@ -799,6 +824,34 @@ def get_translated_document(self, return response +class CreateModelEnums: + """ + Enums for create_model parameters. + """ + + class ForcedGlossaryContentType(str, Enum): + """ + The content type of forced_glossary. + """ + APPLICATION_X_TMX_XML = 'application/x-tmx+xml' + APPLICATION_XLIFF_XML = 'application/xliff+xml' + TEXT_CSV = 'text/csv' + TEXT_TAB_SEPARATED_VALUES = 'text/tab-separated-values' + APPLICATION_JSON = 'application/json' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + + class ParallelCorpusContentType(str, Enum): + """ + The content type of parallel_corpus. + """ + APPLICATION_X_TMX_XML = 'application/x-tmx+xml' + APPLICATION_XLIFF_XML = 'application/xliff+xml' + TEXT_CSV = 'text/csv' + TEXT_TAB_SEPARATED_VALUES = 'text/tab-separated-values' + APPLICATION_JSON = 'application/json' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + + class TranslateDocumentEnums: """ Enums for translate_document parameters. diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index f0ed3cb4d..cd020c142 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -131,7 +131,6 @@ def test_list_languages_value_error(self): with pytest.raises(ValueError): _service.list_languages(**req_copy) - def test_list_languages_value_error_with_retries(self): # Enable retries and run test_list_languages_value_error. _service.enable_retries() @@ -233,7 +232,6 @@ def test_translate_value_error(self): with pytest.raises(ValueError): _service.translate(**req_copy) - def test_translate_value_error_with_retries(self): # Enable retries and run test_translate_value_error. _service.enable_retries() @@ -311,7 +309,6 @@ def test_list_identifiable_languages_value_error(self): with pytest.raises(ValueError): _service.list_identifiable_languages(**req_copy) - def test_list_identifiable_languages_value_error_with_retries(self): # Enable retries and run test_list_identifiable_languages_value_error. _service.enable_retries() @@ -390,7 +387,6 @@ def test_identify_value_error(self): with pytest.raises(ValueError): _service.identify(**req_copy) - def test_identify_value_error_with_retries(self): # Enable retries and run test_identify_value_error. _service.enable_retries() @@ -514,7 +510,6 @@ def test_list_models_value_error(self): with pytest.raises(ValueError): _service.list_models(**req_copy) - def test_list_models_value_error_with_retries(self): # Enable retries and run test_list_models_value_error. _service.enable_retries() @@ -546,14 +541,18 @@ def test_create_model_all_params(self): # Set up parameter values base_model_id = 'testString' forced_glossary = io.BytesIO(b'This is a mock file.').getvalue() + forced_glossary_content_type = 'application/x-tmx+xml' parallel_corpus = io.BytesIO(b'This is a mock file.').getvalue() + parallel_corpus_content_type = 'application/x-tmx+xml' name = 'testString' # Invoke method response = _service.create_model( base_model_id, forced_glossary=forced_glossary, + forced_glossary_content_type=forced_glossary_content_type, parallel_corpus=parallel_corpus, + parallel_corpus_content_type=parallel_corpus_content_type, name=name, headers={} ) @@ -642,7 +641,6 @@ def test_create_model_value_error(self): with pytest.raises(ValueError): _service.create_model(**req_copy) - def test_create_model_value_error_with_retries(self): # Enable retries and run test_create_model_value_error. _service.enable_retries() @@ -719,7 +717,6 @@ def test_delete_model_value_error(self): with pytest.raises(ValueError): _service.delete_model(**req_copy) - def test_delete_model_value_error_with_retries(self): # Enable retries and run test_delete_model_value_error. _service.enable_retries() @@ -796,7 +793,6 @@ def test_get_model_value_error(self): with pytest.raises(ValueError): _service.get_model(**req_copy) - def test_get_model_value_error_with_retries(self): # Enable retries and run test_get_model_value_error. _service.enable_retries() @@ -874,7 +870,6 @@ def test_list_documents_value_error(self): with pytest.raises(ValueError): _service.list_documents(**req_copy) - def test_list_documents_value_error_with_retries(self): # Enable retries and run test_list_documents_value_error. _service.enable_retries() @@ -1002,7 +997,6 @@ def test_translate_document_value_error(self): with pytest.raises(ValueError): _service.translate_document(**req_copy) - def test_translate_document_value_error_with_retries(self): # Enable retries and run test_translate_document_value_error. _service.enable_retries() @@ -1079,7 +1073,6 @@ def test_get_document_status_value_error(self): with pytest.raises(ValueError): _service.get_document_status(**req_copy) - def test_get_document_status_value_error_with_retries(self): # Enable retries and run test_get_document_status_value_error. _service.enable_retries() @@ -1150,7 +1143,6 @@ def test_delete_document_value_error(self): with pytest.raises(ValueError): _service.delete_document(**req_copy) - def test_delete_document_value_error_with_retries(self): # Enable retries and run test_delete_document_value_error. _service.enable_retries() @@ -1265,7 +1257,6 @@ def test_get_translated_document_value_error(self): with pytest.raises(ValueError): _service.get_translated_document(**req_copy) - def test_get_translated_document_value_error_with_retries(self): # Enable retries and run test_get_translated_document_value_error. _service.enable_retries() From c8e056c8d503656271bde6315b84838771975179 Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Wed, 10 Aug 2022 09:24:29 -0500 Subject: [PATCH 373/455] feat(nlu): add trainingParameters add parameter trainingParameters to createClassificationsModel and updateClassificationsModel --- .../natural_language_understanding_v1.py | 149 +++++++++++++++--- .../test_natural_language_understanding_v1.py | 77 +++++---- 2 files changed, 174 insertions(+), 52 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 0ae9da787..6e64157cc 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you @@ -62,7 +62,7 @@ def __init__( Construct a new client for the Natural Language Understanding service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2021-08-01`. + Specify dates in YYYY-MM-DD format. The current version is `2022-04-07`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md @@ -176,6 +176,7 @@ def analyze(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/analyze' @@ -215,6 +216,7 @@ def list_models(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models' @@ -250,6 +252,7 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -331,6 +334,7 @@ def create_sentiment_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/sentiment' @@ -364,6 +368,7 @@ def list_sentiment_models(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/sentiment' @@ -399,6 +404,7 @@ def get_sentiment_model(self, model_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -479,6 +485,7 @@ def update_sentiment_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -520,6 +527,7 @@ def delete_sentiment_model(self, model_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -606,6 +614,7 @@ def create_categories_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/categories' @@ -639,6 +648,7 @@ def list_categories_models(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/categories' @@ -674,6 +684,7 @@ def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -759,6 +770,7 @@ def update_categories_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -800,6 +812,7 @@ def delete_categories_model(self, model_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -818,17 +831,19 @@ def delete_categories_model(self, model_id: str, # Manage classifications models ######################### - def create_classifications_model(self, - language: str, - training_data: BinaryIO, - *, - training_data_content_type: str = None, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def create_classifications_model( + self, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: str = None, + name: str = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + training_parameters: 'ClassificationsTrainingParameters' = None, + **kwargs) -> DetailedResponse: """ Create classifications model. @@ -848,6 +863,9 @@ def create_classifications_model(self, :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. :param str version_description: (optional) The description of the version. + :param ClassificationsTrainingParameters training_parameters: (optional) + Optional classifications training parameters along with model train + requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object @@ -884,9 +902,14 @@ def create_classifications_model(self, if version_description: form_data.append(('version_description', (None, version_description, 'text/plain'))) + if training_parameters: + form_data.append( + ('training_parameters', (None, json.dumps(training_parameters), + 'application/json'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/classifications' @@ -921,6 +944,7 @@ def list_classifications_models(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models/classifications' @@ -957,6 +981,7 @@ def get_classifications_model(self, model_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -971,18 +996,20 @@ def get_classifications_model(self, model_id: str, response = self.send(request, **kwargs) return response - def update_classifications_model(self, - model_id: str, - language: str, - training_data: BinaryIO, - *, - training_data_content_type: str = None, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def update_classifications_model( + self, + model_id: str, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: str = None, + name: str = None, + description: str = None, + model_version: str = None, + workspace_id: str = None, + version_description: str = None, + training_parameters: 'ClassificationsTrainingParameters' = None, + **kwargs) -> DetailedResponse: """ Update classifications model. @@ -1002,6 +1029,9 @@ def update_classifications_model(self, :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. :param str version_description: (optional) The description of the version. + :param ClassificationsTrainingParameters training_parameters: (optional) + Optional classifications training parameters along with model train + requests. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object @@ -1040,9 +1070,14 @@ def update_classifications_model(self, if version_description: form_data.append(('version_description', (None, version_description, 'text/plain'))) + if training_parameters: + form_data.append( + ('training_parameters', (None, json.dumps(training_parameters), + 'application/json'))) if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -1085,6 +1120,7 @@ def delete_classifications_model(self, model_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -2433,6 +2469,69 @@ def __ne__(self, other: 'ClassificationsResult') -> bool: return not self == other +class ClassificationsTrainingParameters(): + """ + Optional classifications training parameters along with model train requests. + + :attr str model_type: (optional) Model type selector to train either a + single_label or a multi_label classifier. + """ + + def __init__(self, *, model_type: str = None) -> None: + """ + Initialize a ClassificationsTrainingParameters object. + + :param str model_type: (optional) Model type selector to train either a + single_label or a multi_label classifier. + """ + self.model_type = model_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ClassificationsTrainingParameters': + """Initialize a ClassificationsTrainingParameters object from a json dictionary.""" + args = {} + if 'model_type' in _dict: + args['model_type'] = _dict.get('model_type') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClassificationsTrainingParameters 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, 'model_type') and self.model_type is not None: + _dict['model_type'] = self.model_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 ClassificationsTrainingParameters object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ClassificationsTrainingParameters') -> 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: 'ClassificationsTrainingParameters') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ModelTypeEnum(str, Enum): + """ + Model type selector to train either a single_label or a multi_label classifier. + """ + SINGLE_LABEL = 'single_label' + MULTI_LABEL = 'multi_label' + + class ConceptsOptions(): """ Returns high-level concepts in the content. For example, a research paper about deep diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index b00e2f23a..0d6deebda 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -162,7 +162,7 @@ def test_analyze_all_params(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = {} + features_model['metadata'] = {'key1': 'testString'} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -306,7 +306,7 @@ def test_analyze_value_error(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = {} + features_model['metadata'] = {'key1': 'testString'} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -335,7 +335,6 @@ def test_analyze_value_error(self): with pytest.raises(ValueError): _service.analyze(**req_copy) - def test_analyze_value_error_with_retries(self): # Enable retries and run test_analyze_value_error. _service.enable_retries() @@ -413,7 +412,6 @@ def test_list_models_value_error(self): with pytest.raises(ValueError): _service.list_models(**req_copy) - def test_list_models_value_error_with_retries(self): # Enable retries and run test_list_models_value_error. _service.enable_retries() @@ -490,7 +488,6 @@ def test_delete_model_value_error(self): with pytest.raises(ValueError): _service.delete_model(**req_copy) - def test_delete_model_value_error_with_retries(self): # Enable retries and run test_delete_model_value_error. _service.enable_retries() @@ -629,7 +626,6 @@ def test_create_sentiment_model_value_error(self): with pytest.raises(ValueError): _service.create_sentiment_model(**req_copy) - def test_create_sentiment_model_value_error_with_retries(self): # Enable retries and run test_create_sentiment_model_value_error. _service.enable_retries() @@ -697,7 +693,6 @@ def test_list_sentiment_models_value_error(self): with pytest.raises(ValueError): _service.list_sentiment_models(**req_copy) - def test_list_sentiment_models_value_error_with_retries(self): # Enable retries and run test_list_sentiment_models_value_error. _service.enable_retries() @@ -774,7 +769,6 @@ def test_get_sentiment_model_value_error(self): with pytest.raises(ValueError): _service.get_sentiment_model(**req_copy) - def test_get_sentiment_model_value_error_with_retries(self): # Enable retries and run test_get_sentiment_model_value_error. _service.enable_retries() @@ -909,7 +903,6 @@ def test_update_sentiment_model_value_error(self): with pytest.raises(ValueError): _service.update_sentiment_model(**req_copy) - def test_update_sentiment_model_value_error_with_retries(self): # Enable retries and run test_update_sentiment_model_value_error. _service.enable_retries() @@ -986,7 +979,6 @@ def test_delete_sentiment_model_value_error(self): with pytest.raises(ValueError): _service.delete_sentiment_model(**req_copy) - def test_delete_sentiment_model_value_error_with_retries(self): # Enable retries and run test_delete_sentiment_model_value_error. _service.enable_retries() @@ -1127,7 +1119,6 @@ def test_create_categories_model_value_error(self): with pytest.raises(ValueError): _service.create_categories_model(**req_copy) - def test_create_categories_model_value_error_with_retries(self): # Enable retries and run test_create_categories_model_value_error. _service.enable_retries() @@ -1195,7 +1186,6 @@ def test_list_categories_models_value_error(self): with pytest.raises(ValueError): _service.list_categories_models(**req_copy) - def test_list_categories_models_value_error_with_retries(self): # Enable retries and run test_list_categories_models_value_error. _service.enable_retries() @@ -1272,7 +1262,6 @@ def test_get_categories_model_value_error(self): with pytest.raises(ValueError): _service.get_categories_model(**req_copy) - def test_get_categories_model_value_error_with_retries(self): # Enable retries and run test_get_categories_model_value_error. _service.enable_retries() @@ -1409,7 +1398,6 @@ def test_update_categories_model_value_error(self): with pytest.raises(ValueError): _service.update_categories_model(**req_copy) - def test_update_categories_model_value_error_with_retries(self): # Enable retries and run test_update_categories_model_value_error. _service.enable_retries() @@ -1486,7 +1474,6 @@ def test_delete_categories_model_value_error(self): with pytest.raises(ValueError): _service.delete_categories_model(**req_copy) - def test_delete_categories_model_value_error_with_retries(self): # Enable retries and run test_delete_categories_model_value_error. _service.enable_retries() @@ -1525,6 +1512,10 @@ def test_create_classifications_model_all_params(self): content_type='application/json', status=201) + # Construct a dict representation of a ClassificationsTrainingParameters model + classifications_training_parameters_model = {} + classifications_training_parameters_model['model_type'] = 'single_label' + # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() @@ -1534,6 +1525,7 @@ def test_create_classifications_model_all_params(self): model_version = 'testString' workspace_id = 'testString' version_description = 'testString' + training_parameters = classifications_training_parameters_model # Invoke method response = _service.create_classifications_model( @@ -1545,6 +1537,7 @@ def test_create_classifications_model_all_params(self): model_version=model_version, workspace_id=workspace_id, version_description=version_description, + training_parameters=training_parameters, headers={} ) @@ -1627,7 +1620,6 @@ def test_create_classifications_model_value_error(self): with pytest.raises(ValueError): _service.create_classifications_model(**req_copy) - def test_create_classifications_model_value_error_with_retries(self): # Enable retries and run test_create_classifications_model_value_error. _service.enable_retries() @@ -1695,7 +1687,6 @@ def test_list_classifications_models_value_error(self): with pytest.raises(ValueError): _service.list_classifications_models(**req_copy) - def test_list_classifications_models_value_error_with_retries(self): # Enable retries and run test_list_classifications_models_value_error. _service.enable_retries() @@ -1772,7 +1763,6 @@ def test_get_classifications_model_value_error(self): with pytest.raises(ValueError): _service.get_classifications_model(**req_copy) - def test_get_classifications_model_value_error_with_retries(self): # Enable retries and run test_get_classifications_model_value_error. _service.enable_retries() @@ -1801,6 +1791,10 @@ def test_update_classifications_model_all_params(self): content_type='application/json', status=200) + # Construct a dict representation of a ClassificationsTrainingParameters model + classifications_training_parameters_model = {} + classifications_training_parameters_model['model_type'] = 'single_label' + # Set up parameter values model_id = 'testString' language = 'testString' @@ -1811,6 +1805,7 @@ def test_update_classifications_model_all_params(self): model_version = 'testString' workspace_id = 'testString' version_description = 'testString' + training_parameters = classifications_training_parameters_model # Invoke method response = _service.update_classifications_model( @@ -1823,6 +1818,7 @@ def test_update_classifications_model_all_params(self): model_version=model_version, workspace_id=workspace_id, version_description=version_description, + training_parameters=training_parameters, headers={} ) @@ -1909,7 +1905,6 @@ def test_update_classifications_model_value_error(self): with pytest.raises(ValueError): _service.update_classifications_model(**req_copy) - def test_update_classifications_model_value_error_with_retries(self): # Enable retries and run test_update_classifications_model_value_error. _service.enable_retries() @@ -1986,7 +1981,6 @@ def test_delete_classifications_model_value_error(self): with pytest.raises(ValueError): _service.delete_classifications_model(**req_copy) - def test_delete_classifications_model_value_error_with_retries(self): # Enable retries and run test_delete_classifications_model_value_error. _service.enable_retries() @@ -2288,7 +2282,7 @@ def test_categories_model_serialization(self): # Construct a json representation of a CategoriesModel model categories_model_model_json = {} categories_model_model_json['name'] = 'testString' - categories_model_model_json['user_metadata'] = {} + categories_model_model_json['user_metadata'] = {'key1': {'foo': 'bar'}} categories_model_model_json['language'] = 'testString' categories_model_model_json['description'] = 'testString' categories_model_model_json['model_version'] = 'testString' @@ -2334,7 +2328,7 @@ def test_categories_model_list_serialization(self): categories_model_model = {} # CategoriesModel categories_model_model['name'] = 'testString' - categories_model_model['user_metadata'] = {} + categories_model_model['user_metadata'] = {'key1': {'foo': 'bar'}} categories_model_model['language'] = 'testString' categories_model_model['description'] = 'testString' categories_model_model['model_version'] = 'testString' @@ -2518,7 +2512,7 @@ def test_classifications_model_serialization(self): # Construct a json representation of a ClassificationsModel model classifications_model_model_json = {} classifications_model_model_json['name'] = 'testString' - classifications_model_model_json['user_metadata'] = {} + classifications_model_model_json['user_metadata'] = {'key1': {'foo': 'bar'}} classifications_model_model_json['language'] = 'testString' classifications_model_model_json['description'] = 'testString' classifications_model_model_json['model_version'] = 'testString' @@ -2564,7 +2558,7 @@ def test_classifications_model_list_serialization(self): classifications_model_model = {} # ClassificationsModel classifications_model_model['name'] = 'testString' - classifications_model_model['user_metadata'] = {} + classifications_model_model['user_metadata'] = {'key1': {'foo': 'bar'}} classifications_model_model['language'] = 'testString' classifications_model_model['description'] = 'testString' classifications_model_model['model_version'] = 'testString' @@ -2656,6 +2650,35 @@ def test_classifications_result_serialization(self): classifications_result_model_json2 = classifications_result_model.to_dict() assert classifications_result_model_json2 == classifications_result_model_json +class TestModel_ClassificationsTrainingParameters(): + """ + Test Class for ClassificationsTrainingParameters + """ + + def test_classifications_training_parameters_serialization(self): + """ + Test serialization/deserialization for ClassificationsTrainingParameters + """ + + # Construct a json representation of a ClassificationsTrainingParameters model + classifications_training_parameters_model_json = {} + classifications_training_parameters_model_json['model_type'] = 'single_label' + + # Construct a model instance of ClassificationsTrainingParameters by calling from_dict on the json representation + classifications_training_parameters_model = ClassificationsTrainingParameters.from_dict(classifications_training_parameters_model_json) + assert classifications_training_parameters_model != False + + # Construct a model instance of ClassificationsTrainingParameters by calling from_dict on the json representation + classifications_training_parameters_model_dict = ClassificationsTrainingParameters.from_dict(classifications_training_parameters_model_json).__dict__ + classifications_training_parameters_model2 = ClassificationsTrainingParameters(**classifications_training_parameters_model_dict) + + # Verify the model instances are equivalent + assert classifications_training_parameters_model == classifications_training_parameters_model2 + + # Convert model instance back to dict and verify no loss of data + classifications_training_parameters_model_json2 = classifications_training_parameters_model.to_dict() + assert classifications_training_parameters_model_json2 == classifications_training_parameters_model_json + class TestModel_ConceptsOptions(): """ Test Class for ConceptsOptions @@ -3175,7 +3198,7 @@ def test_features_serialization(self): features_model_json['emotion'] = emotion_options_model features_model_json['entities'] = entities_options_model features_model_json['keywords'] = keywords_options_model - features_model_json['metadata'] = {} + features_model_json['metadata'] = {'key1': 'testString'} features_model_json['relations'] = relations_options_model features_model_json['semantic_roles'] = semantic_roles_options_model features_model_json['sentiment'] = sentiment_options_model @@ -3409,7 +3432,7 @@ def test_list_sentiment_models_response_serialization(self): sentiment_model_model['last_trained'] = '2019-01-01T12:00:00Z' sentiment_model_model['last_deployed'] = '2019-01-01T12:00:00Z' sentiment_model_model['name'] = 'testString' - sentiment_model_model['user_metadata'] = {} + sentiment_model_model['user_metadata'] = {'key1': {'foo': 'bar'}} sentiment_model_model['language'] = 'testString' sentiment_model_model['description'] = 'testString' sentiment_model_model['model_version'] = 'testString' @@ -3986,7 +4009,7 @@ def test_sentiment_model_serialization(self): sentiment_model_model_json['last_trained'] = '2019-01-01T12:00:00Z' sentiment_model_model_json['last_deployed'] = '2019-01-01T12:00:00Z' sentiment_model_model_json['name'] = 'testString' - sentiment_model_model_json['user_metadata'] = {} + sentiment_model_model_json['user_metadata'] = {'key1': {'foo': 'bar'}} sentiment_model_model_json['language'] = 'testString' sentiment_model_model_json['description'] = 'testString' sentiment_model_model_json['model_version'] = 'testString' From e40c06c52ec00168d9a5f7f0e174c8a1fef65d21 Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Wed, 10 Aug 2022 09:25:40 -0500 Subject: [PATCH 374/455] feat(stt): update parameters Remove parameter customizationId from createJob and recognize, Add parameter characterInsertionBias to createJob and recognize, Add parameter strict to trainAcousticModel and trainLanguageModel --- ibm_watson/speech_to_text_v1.py | 437 +++++++++++++++++++--------- test/unit/test_speech_to_text_v1.py | 63 +--- 2 files changed, 319 insertions(+), 181 deletions(-) mode change 100755 => 100644 test/unit/test_speech_to_text_v1.py diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index c769fb495..9c4d64014 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's speech-recognition capabilities to produce transcripts of spoken audio. The service can @@ -120,6 +120,7 @@ def list_models(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/models' @@ -157,6 +158,7 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['model_id'] @@ -191,7 +193,6 @@ def recognize(self, profanity_filter: bool = None, smart_formatting: bool = None, speaker_labels: bool = None, - customization_id: str = None, grammar_name: str = None, redaction: bool = None, audio_metrics: bool = None, @@ -200,6 +201,7 @@ def recognize(self, speech_detector_sensitivity: float = None, background_audio_suppression: float = None, low_latency: bool = None, + character_insertion_bias: float = None, **kwargs) -> DetailedResponse: """ Recognize audio. @@ -267,10 +269,18 @@ def recognize(self, use next-generation models, the service can return transcriptions more quickly and also provide noticeably better transcription accuracy. You specify a next-generation model by using the `model` query parameter, as you - do a previous-generation model. Many next-generation models also support the - `low_latency` parameter, which is not available with previous-generation models. - Next-generation models do not support all of the parameters that are available for - use with previous-generation models. + do a previous-generation model. Most next-generation models support the + `low_latency` parameter, and all next-generation models support the + `character_insertion_bias` parameter. These parameters are not available with + previous-generation models. + Next-generation models do not support all of the speech recognition parameters + that are available for use with previous-generation models. Next-generation models + do not support the following parameters: + * `acoustic_customization_id` + * `keywords` and `keywords_threshold` + * `max_alternatives` + * `processing_metrics` and `processing_metrics_interval` + * `word_alternatives_threshold` **Important:** Effective 15 March 2022, previous-generation models for all languages other than Arabic and Japanese are deprecated. The deprecated models remain available until 15 September 2022, when they will be removed from the @@ -302,11 +312,18 @@ def recognize(self, :param str content_type: (optional) The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. - :param str model: (optional) The identifier of the model that is to be used - for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) See [Using a model for - speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + :param str model: (optional) The model to use for speech recognition. If + you omit the `model` parameter, the service uses the US English + `en-US_BroadbandModel` by default. (The model `ar-AR_BroadbandModel` is + deprecated; use `ar-MS_BroadbandModel` instead.) + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_BroadbandModel`, you must either specify a model with the request or + specify a new default model for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [The default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). :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 @@ -424,10 +441,6 @@ def recognize(self, Spanish transcription only. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-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 - request. Do not specify both parameters with a request. :param str grammar_name: (optional) The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the @@ -496,7 +509,9 @@ def recognize(self, * 0.5 (the default) provides a reasonable compromise for the level of sensitivity. * 1.0 suppresses no audio (speech detection sensitivity is disabled). - The values increase on a monotonic curve. + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. The parameter is supported with all next-generation models and with most previous-generation models. See [Speech detector sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) @@ -511,7 +526,9 @@ def recognize(self, is disabled). * 0.5 provides a reasonable level of audio suppression for general usage. * 1.0 suppresses all audio (no audio is transcribed). - The values increase on a monotonic curve. + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. The parameter is supported with all next-generation models and with most previous-generation models. See [Background audio suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression) @@ -525,12 +542,34 @@ def recognize(self, to produce results even more quickly, though the results might be less accurate when the parameter is used. The parameter is not available for previous-generation `Broadband` and - `Narrowband` models. It is available only for some next-generation models. - For a list of next-generation models that support low latency, see + `Narrowband` models. It is available for most next-generation models. + * For a list of next-generation models that support low latency, see [Supported next-generation language models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported). * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). + :param float character_insertion_bias: (optional) For next-generation + `Multimedia` and `Telephony` models, an indication of whether the service + is biased to recognize shorter or longer strings of characters when + developing transcription hypotheses. By default, the service is optimized + for each individual model to balance its recognition of strings of + different lengths. The model-specific bias is equivalent to 0.0. + The value that you specify represents a change from a model's default bias. + The allowable range of values is -1.0 to 1.0. + * Negative values bias the service to favor hypotheses with shorter strings + of characters. + * Positive values bias the service to favor hypotheses with longer strings + of characters. + As the value approaches -1.0 or 1.0, the impact of the parameter becomes + more pronounced. To determine the most effective value for your scenario, + start by setting the value of the parameter to a small increment, such as + -0.1, -0.05, 0.05, or 0.1, and assess how the value impacts the + transcription results. Then experiment with different values as necessary, + adjusting the value by small increments. + The parameter is not available for previous-generation `Broadband` and + `Narrowband` models. + See [Character insertion + bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SpeechRecognitionResults` object @@ -560,7 +599,6 @@ def recognize(self, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, 'speaker_labels': speaker_labels, - 'customization_id': customization_id, 'grammar_name': grammar_name, 'redaction': redaction, 'audio_metrics': audio_metrics, @@ -568,13 +606,15 @@ def recognize(self, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, - 'low_latency': low_latency + 'low_latency': low_latency, + 'character_insertion_bias': character_insertion_bias } data = audio if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/recognize' @@ -657,6 +697,7 @@ def register_callback(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/register_callback' @@ -698,6 +739,7 @@ def unregister_callback(self, callback_url: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/unregister_callback' request = self.prepare_request(method='POST', @@ -731,7 +773,6 @@ def create_job(self, profanity_filter: bool = None, smart_formatting: bool = None, speaker_labels: bool = None, - customization_id: str = None, grammar_name: str = None, redaction: bool = None, processing_metrics: bool = None, @@ -742,6 +783,7 @@ def create_job(self, speech_detector_sensitivity: float = None, background_audio_suppression: float = None, low_latency: bool = None, + character_insertion_bias: float = None, **kwargs) -> DetailedResponse: """ Create a job. @@ -835,10 +877,18 @@ def create_job(self, use next-generation models, the service can return transcriptions more quickly and also provide noticeably better transcription accuracy. You specify a next-generation model by using the `model` query parameter, as you - do a previous-generation model. Many next-generation models also support the - `low_latency` parameter, which is not available with previous-generation models. - Next-generation models do not support all of the parameters that are available for - use with previous-generation models. + do a previous-generation model. Most next-generation models support the + `low_latency` parameter, and all next-generation models support the + `character_insertion_bias` parameter. These parameters are not available with + previous-generation models. + Next-generation models do not support all of the speech recognition parameters + that are available for use with previous-generation models. Next-generation models + do not support the following parameters: + * `acoustic_customization_id` + * `keywords` and `keywords_threshold` + * `max_alternatives` + * `processing_metrics` and `processing_metrics_interval` + * `word_alternatives_threshold` **Important:** Effective 15 March 2022, previous-generation models for all languages other than Arabic and Japanese are deprecated. The deprecated models remain available until 15 September 2022, when they will be removed from the @@ -856,11 +906,18 @@ def create_job(self, :param str content_type: (optional) The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. - :param str model: (optional) The identifier of the model that is to be used - for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) See [Using a model for - speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + :param str model: (optional) The model to use for speech recognition. If + you omit the `model` parameter, the service uses the US English + `en-US_BroadbandModel` by default. (The model `ar-AR_BroadbandModel` is + deprecated; use `ar-MS_BroadbandModel` instead.) + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_BroadbandModel`, you must either specify a model with the request or + specify a new default model for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [The default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). :param str callback_url: (optional) A URL to which callback notifications are to be sent. The URL must already be successfully allowlisted by using the [Register a callback](#registercallback) method. You can include the @@ -1014,10 +1071,6 @@ def create_job(self, Spanish transcription only. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-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 - request. Do not specify both parameters with a request. :param str grammar_name: (optional) The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the @@ -1108,7 +1161,9 @@ def create_job(self, * 0.5 (the default) provides a reasonable compromise for the level of sensitivity. * 1.0 suppresses no audio (speech detection sensitivity is disabled). - The values increase on a monotonic curve. + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. The parameter is supported with all next-generation models and with most previous-generation models. See [Speech detector sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) @@ -1123,7 +1178,9 @@ def create_job(self, is disabled). * 0.5 provides a reasonable level of audio suppression for general usage. * 1.0 suppresses all audio (no audio is transcribed). - The values increase on a monotonic curve. + The values increase on a monotonic curve. Specifying one or two decimal + places of precision (for example, `0.55`) is typically more than + sufficient. The parameter is supported with all next-generation models and with most previous-generation models. See [Background audio suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression) @@ -1137,12 +1194,34 @@ def create_job(self, to produce results even more quickly, though the results might be less accurate when the parameter is used. The parameter is not available for previous-generation `Broadband` and - `Narrowband` models. It is available only for some next-generation models. - For a list of next-generation models that support low latency, see + `Narrowband` models. It is available for most next-generation models. + * For a list of next-generation models that support low latency, see [Supported next-generation language models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported). * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). + :param float character_insertion_bias: (optional) For next-generation + `Multimedia` and `Telephony` models, an indication of whether the service + is biased to recognize shorter or longer strings of characters when + developing transcription hypotheses. By default, the service is optimized + for each individual model to balance its recognition of strings of + different lengths. The model-specific bias is equivalent to 0.0. + The value that you specify represents a change from a model's default bias. + The allowable range of values is -1.0 to 1.0. + * Negative values bias the service to favor hypotheses with shorter strings + of characters. + * Positive values bias the service to favor hypotheses with longer strings + of characters. + As the value approaches -1.0 or 1.0, the impact of the parameter becomes + more pronounced. To determine the most effective value for your scenario, + start by setting the value of the parameter to a small increment, such as + -0.1, -0.05, 0.05, or 0.1, and assess how the value impacts the + transcription results. Then experiment with different values as necessary, + adjusting the value by small increments. + The parameter is not available for previous-generation `Broadband` and + `Narrowband` models. + See [Character insertion + bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `RecognitionJob` object @@ -1176,7 +1255,6 @@ def create_job(self, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, 'speaker_labels': speaker_labels, - 'customization_id': customization_id, 'grammar_name': grammar_name, 'redaction': redaction, 'processing_metrics': processing_metrics, @@ -1186,13 +1264,15 @@ def create_job(self, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, - 'low_latency': low_latency + 'low_latency': low_latency, + 'character_insertion_bias': character_insertion_bias } data = audio if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/recognitions' @@ -1233,6 +1313,7 @@ def check_jobs(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/recognitions' @@ -1276,6 +1357,7 @@ def check_job(self, id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['id'] @@ -1317,6 +1399,7 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['id'] path_param_values = self.encode_path_vars(id) @@ -1423,6 +1506,7 @@ def create_language_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' @@ -1477,6 +1561,7 @@ def list_language_models(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' @@ -1520,6 +1605,7 @@ def get_language_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1565,6 +1651,7 @@ def delete_language_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1583,6 +1670,7 @@ def train_language_model(self, *, word_type_to_add: str = None, customization_weight: float = None, + strict: bool = None, **kwargs) -> DetailedResponse: """ Train a custom language model. @@ -1652,6 +1740,12 @@ def train_language_model(self, customization weight for that request. See [Using customization weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). + :param bool strict: (optional) If `false`, allows training of the custom + language model to proceed as long as the model contains at least one valid + resource. The method returns an array of `TrainingWarning` objects that + lists any invalid resources. By default (`true`), training of a custom + language model fails (status code 400) if the model contains one or more + invalid resources (corpus files, grammar files, or custom words). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object @@ -1667,11 +1761,13 @@ def train_language_model(self, params = { 'word_type_to_add': word_type_to_add, - 'customization_weight': customization_weight + 'customization_weight': customization_weight, + 'strict': strict } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1723,6 +1819,7 @@ def reset_language_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1780,6 +1877,7 @@ def upgrade_language_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1827,6 +1925,7 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1874,7 +1973,8 @@ def add_corpus(self, (OOV) words. After adding a corpus, you must validate the words resource to ensure that each OOV word's definition is complete and valid. You can use the [List custom words](#listwords) method to examine the words resource. You can use other - words method to eliminate typos and modify how words are pronounced as needed. + words method to eliminate typos and modify how words are pronounced and displayed + as needed. To add a corpus file that has the same name as an existing corpus, set the `allow_overwrite` parameter to `true`; otherwise, the request fails. Overwriting an existing corpus causes the service to process the corpus text file and extract @@ -1957,6 +2057,7 @@ def add_corpus(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'corpus_name'] @@ -2009,6 +2110,7 @@ def get_corpus(self, customization_id: str, corpus_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'corpus_name'] @@ -2061,6 +2163,7 @@ def delete_corpus(self, customization_id: str, corpus_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'corpus_name'] @@ -2092,10 +2195,13 @@ def list_words(self, all words from the custom model's words resource, only custom words that were added or modified by the user, or, _for a custom model that is based on a previous-generation model_, only out-of-vocabulary (OOV) words that were extracted - from corpora or are recognized by grammars. You can also indicate the order in - which the service is to return words; by default, the service lists words in - ascending alphabetical order. You must use credentials for the instance of the - service that owns a model to list information about its words. + from corpora or are recognized by grammars. _For a custom model that is based on a + next-generation model_, you can list all words or only those words that were added + directly by a user, which return the same results. + You can also indicate the order in which the service is to return words; by + default, the service lists words 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/speech-to-text?topic=speech-to-text-manageWords#listWords). @@ -2139,6 +2245,7 @@ def list_words(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -2181,16 +2288,15 @@ def add_words(self, customization_id: str, words: List['CustomWord'], transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might indicate that the word `IBM` is to be displayed as `IBM™`. - * The `sounds_like` field, _which can be used only with a custom model that is - based on a previous-generation model_, provides an array of one or more - pronunciations for the word. Use the parameter to specify how the word can be - pronounced by users. Use the parameter for words that are difficult to pronounce, - foreign words, acronyms, and so on. For example, you might specify that the word - `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like - pronunciations for a word. If you omit the `sounds_like` field, the service - attempts to set the field to its pronunciation of the word. It cannot generate a - pronunciation for all words, so you must review the word's definition to ensure - that it is complete and valid. + * The `sounds_like` field provides an array of one or more pronunciations for the + word. Use the parameter to specify how the word can be pronounced by users. Use + the parameter for words that are difficult to pronounce, foreign words, acronyms, + and so on. For example, you might specify that the word `IEEE` can sound like `I + triple E`. You can specify a maximum of five sounds-like pronunciations for a + word. _For a custom model that is based on a previous-generation model_, if you + omit the `sounds_like` field, the service attempts to set the field to its + pronunciation of the word. It cannot generate a pronunciation for all words, so + you must review the word's definition to ensure that it is complete and valid. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error with the input data, it returns a failure code and @@ -2252,6 +2358,7 @@ def add_words(self, customization_id: str, words: List['CustomWord'], if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -2299,16 +2406,15 @@ def add_word(self, transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might indicate that the word `IBM` is to be displayed as `IBM™`. - * The `sounds_like` field, _which can be used only with a custom model that is - based on a previous-generation model_, provides an array of one or more - pronunciations for the word. Use the parameter to specify how the word can be - pronounced by users. Use the parameter for words that are difficult to pronounce, - foreign words, acronyms, and so on. For example, you might specify that the word - `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like - pronunciations for a word. If you omit the `sounds_like` field, the service - attempts to set the field to its pronunciation of the word. It cannot generate a - pronunciation for all words, so you must review the word's definition to ensure - that it is complete and valid. + * The `sounds_like` field provides an array of one or more pronunciations for the + word. Use the parameter to specify how the word can be pronounced by users. Use + the parameter for words that are difficult to pronounce, foreign words, acronyms, + and so on. For example, you might specify that the word `IEEE` can sound like `i + triple e`. You can specify a maximum of five sounds-like pronunciations for a + word. _For custom models that are based on previous-generation models_, if you + omit the `sounds_like` field, the service attempts to set the field to its + pronunciation of the word. It cannot generate a pronunciation for all words, so + you must review the word's definition to ensure that it is complete and valid. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error, it does not add the word to the words resource. Use @@ -2340,26 +2446,26 @@ def add_word(self, custom model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the [Add a custom word](#addword) method. - :param List[str] sounds_like: (optional) _For a custom model that is based - on a previous-generation model_, an array of sounds-like pronunciations for - the custom word. Specify how words that are difficult to pronounce, foreign - words, acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the - parameter to have the service automatically generate a sounds-like - pronunciation for the word. + :param List[str] sounds_like: (optional) As array of sounds-like + pronunciations for the custom word. Specify how words that are difficult to + pronounce, foreign words, acronyms, and so on can be pronounced by users. + * _For custom models that are based on previous-generation models_, for a + word that is not in the service's base vocabulary, omit the parameter to + have the service automatically generate a sounds-like pronunciation for the + word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. - _For a custom model that is based on a next-generation model_, omit this - field. Custom models based on next-generation models do not support the - `sounds_like` field. The service ignores the field. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. + _For custom models that are based on next-generation models_, the service + uses the spelling of the word as the display-as value if you omit the + field. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2386,6 +2492,7 @@ def add_word(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word_name'] @@ -2437,6 +2544,7 @@ def get_word(self, customization_id: str, word_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word_name'] @@ -2489,6 +2597,7 @@ def delete_word(self, customization_id: str, word_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word_name'] @@ -2542,6 +2651,7 @@ def list_grammars(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -2667,6 +2777,7 @@ def add_grammar(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'grammar_name'] @@ -2723,6 +2834,7 @@ def get_grammar(self, customization_id: str, grammar_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'grammar_name'] @@ -2779,6 +2891,7 @@ def delete_grammar(self, customization_id: str, grammar_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'grammar_name'] @@ -2868,6 +2981,7 @@ def create_acoustic_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/acoustic_customizations' @@ -2921,6 +3035,7 @@ def list_acoustic_models(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/acoustic_customizations' @@ -2963,6 +3078,7 @@ def get_acoustic_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3008,6 +3124,7 @@ def delete_acoustic_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3026,6 +3143,7 @@ def train_acoustic_model(self, customization_id: str, *, custom_language_model_id: str = None, + strict: bool = None, **kwargs) -> DetailedResponse: """ Train a custom acoustic model. @@ -3097,6 +3215,12 @@ def train_acoustic_model(self, custom acoustic model, and the custom language model must be fully trained and available. The credentials specified with the request must own both custom models. + :param bool strict: (optional) If `false`, allows training of the custom + acoustic model to proceed as long as the model contains at least one valid + audio resource. The method returns an array of `TrainingWarning` objects + that lists any invalid resources. By default (`true`), training of a custom + acoustic model fails (status code 400) if the model contains one or more + invalid audio resources. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object @@ -3110,10 +3234,14 @@ def train_acoustic_model(self, operation_id='train_acoustic_model') headers.update(sdk_headers) - params = {'custom_language_model_id': custom_language_model_id} + params = { + 'custom_language_model_id': custom_language_model_id, + 'strict': strict + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3166,6 +3294,7 @@ def reset_acoustic_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3251,6 +3380,7 @@ def upgrade_acoustic_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3304,6 +3434,7 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -3485,6 +3616,7 @@ def add_audio(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'audio_name'] @@ -3552,6 +3684,7 @@ def get_audio(self, customization_id: str, audio_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'audio_name'] @@ -3606,6 +3739,7 @@ def delete_audio(self, customization_id: str, audio_name: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'audio_name'] @@ -3662,6 +3796,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/user_data' request = self.prepare_request(method='DELETE', @@ -3732,6 +3867,7 @@ class ModelId(str, Enum): HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' @@ -3745,6 +3881,7 @@ class ModelId(str, Enum): NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' @@ -3781,10 +3918,17 @@ class ContentType(str, Enum): class Model(str, Enum): """ - The identifier of the model that is to be used for the recognition request. - (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use - `ar-MS_BroadbandModel` instead.) See [Using a model for speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + The model to use for speech recognition. If you omit the `model` parameter, the + service uses the US English `en-US_BroadbandModel` by default. (The model + `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_BroadbandModel`, + you must either specify a model with the request or specify a new default model + for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [The default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' @@ -3834,6 +3978,7 @@ class Model(str, Enum): HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' @@ -3847,6 +3992,7 @@ class Model(str, Enum): NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' @@ -3883,10 +4029,17 @@ class ContentType(str, Enum): class Model(str, Enum): """ - The identifier of the model that is to be used for the recognition request. - (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use - `ar-MS_BroadbandModel` instead.) See [Using a model for speech - recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). + The model to use for speech recognition. If you omit the `model` parameter, the + service uses the US English `en-US_BroadbandModel` by default. (The model + `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_BroadbandModel`, + you must either specify a model with the request or specify a new default model + for your installation of the service. + **See also:** + * [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) + * [The default + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' @@ -3936,6 +4089,7 @@ class Model(str, Enum): HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' + IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' @@ -3949,6 +4103,7 @@ class Model(str, Enum): NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' + PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' @@ -5641,26 +5796,24 @@ class CustomWord(): model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the [Add a custom word](#addword) method. - :attr List[str] sounds_like: (optional) _For a custom model that is based on a - previous-generation model_, an array of sounds-like pronunciations for the - custom word. Specify how words that are difficult to pronounce, foreign words, - acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the parameter to - have the service automatically generate a sounds-like pronunciation for the - word. + :attr List[str] sounds_like: (optional) As array of sounds-like pronunciations + for the custom word. Specify how words that are difficult to pronounce, foreign + words, acronyms, and so on can be pronounced by users. + * _For custom models that are based on previous-generation models_, for a word + that is not in the service's base vocabulary, omit the parameter to have the + service automatically generate a sounds-like pronunciation for the word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. - _For a custom model that is based on a next-generation model_, omit this field. - Custom models based on next-generation models do not support the `sounds_like` - field. The service ignores the field. :attr str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. + _For custom models that are based on next-generation models_, the service uses + the spelling of the word as the display-as value if you omit the field. """ def __init__(self, @@ -5676,26 +5829,26 @@ def __init__(self, custom model. Do not include spaces in the word. Use a `-` (dash) or `_` (underscore) to connect the tokens of compound words. Omit this parameter for the [Add a custom word](#addword) method. - :param List[str] sounds_like: (optional) _For a custom model that is based - on a previous-generation model_, an array of sounds-like pronunciations for - the custom word. Specify how words that are difficult to pronounce, foreign - words, acronyms, and so on can be pronounced by users. - * For a word that is not in the service's base vocabulary, omit the - parameter to have the service automatically generate a sounds-like - pronunciation for the word. + :param List[str] sounds_like: (optional) As array of sounds-like + pronunciations for the custom word. Specify how words that are difficult to + pronounce, foreign words, acronyms, and so on can be pronounced by users. + * _For custom models that are based on previous-generation models_, for a + word that is not in the service's base vocabulary, omit the parameter to + have the service automatically generate a sounds-like pronunciation for the + word. * For a word that is in the service's base vocabulary, use the parameter to specify additional pronunciations for the word. You cannot override the default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. - _For a custom model that is based on a next-generation model_, omit this - field. Custom models based on next-generation models do not support the - `sounds_like` field. The service ignores the field. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. + _For custom models that are based on next-generation models_, the service + uses the spelling of the word as the display-as value if you omit the + field. """ self.word = word self.sounds_like = sounds_like @@ -6683,7 +6836,9 @@ class RecognitionJob(): message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds despite the warnings. This field can be returned only by the - [Create a job](#createjob) method. + [Create a job](#createjob) method. (If you use the `character_insertion_bias` + parameter with a previous-generation model, the warning message refers to the + parameter as `lambdaBias`.). """ def __init__(self, @@ -6735,7 +6890,9 @@ def __init__(self, descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds despite the warnings. This field - can be returned only by the [Create a job](#createjob) method. + can be returned only by the [Create a job](#createjob) method. (If you use + the `character_insertion_bias` parameter with a previous-generation model, + the warning message refers to the parameter as `lambdaBias`.). """ self.id = id self.status = status @@ -7624,7 +7781,9 @@ class SpeechRecognitionResults(): * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown arguments:"` or `"Unknown url query arguments:"` followed by a list of the form - `"{invalid_arg_1}, {invalid_arg_2}."` + `"{invalid_arg_1}, {invalid_arg_2}."` (If you use the `character_insertion_bias` + parameter with a previous-generation model, the warning message refers to the + parameter as `lambdaBias`.) * The following warning is returned if the request passes a custom model that is based on an older version of a base model for which an updated version is available: `"Using previous version of base model, because your custom model has @@ -7681,7 +7840,9 @@ def __init__(self, * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown arguments:"` or `"Unknown url query arguments:"` followed by a list of the - form `"{invalid_arg_1}, {invalid_arg_2}."` + form `"{invalid_arg_1}, {invalid_arg_2}."` (If you use the + `character_insertion_bias` parameter with a previous-generation model, the + warning message refers to the parameter as `lambdaBias`.) * The following warning is returned if the request passes a custom model that is based on an older version of a base model for which an updated version is available: `"Using previous version of base model, because your @@ -8053,19 +8214,23 @@ class Word(): :attr str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :attr List[str] sounds_like: _For a custom model that is based on a - previous-generation model_, an array of as many as five pronunciations for the - word. The array can include the sounds-like pronunciation that is automatically - generated by the service if none is provided when the word is added to the - custom model; the service adds this pronunciation when it finishes processing - the word. - _For a custom model that is based on a next-generation model_, this field does - not apply. Custom models based on next-generation models do not support the - `sounds_like` field, which is ignored. + :attr List[str] sounds_like: An array of as many as five pronunciations for the + word. + * _For a custom model that is based on a previous-generation model_, in addition + to sounds-like pronunciations that were added by a user, the array can include a + sounds-like pronunciation that is automatically generated by the service if none + is provided when the word is added to the custom model. + * _For a custom model that is based on a next-generation model_, the array can + include only sounds-like pronunciations that were added by a user. :attr str display_as: The spelling of the word that the service uses to display - the word in a transcript. The field contains an empty string if no display-as - value is provided for the word, in which case the word is displayed as it is - spelled. + the word in a transcript. + * _For a custom model that is based on a previous-generation model_, the field + can contain an empty string if no display-as value is provided for a word that + exists in the service's base vocabulary. In this case, the word is displayed as + it is spelled. + * _For a custom model that is based on a next-generation model_, the service + uses the spelling of the word as the value of the display-as field when the word + is added to the model. :attr int count: _For a custom model that is based on a previous-generation model_, a sum of the number of times the word is found across all corpora and grammars. For example, if the word occurs five times in one corpus and seven @@ -8104,19 +8269,23 @@ def __init__(self, :param str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :param List[str] sounds_like: _For a custom model that is based on a - previous-generation model_, an array of as many as five pronunciations for - the word. The array can include the sounds-like pronunciation that is - automatically generated by the service if none is provided when the word is - added to the custom model; the service adds this pronunciation when it - finishes processing the word. - _For a custom model that is based on a next-generation model_, this field - does not apply. Custom models based on next-generation models do not - support the `sounds_like` field, which is ignored. + :param List[str] sounds_like: An array of as many as five pronunciations + for the word. + * _For a custom model that is based on a previous-generation model_, in + addition to sounds-like pronunciations that were added by a user, the array + can include a sounds-like pronunciation that is automatically generated by + the service if none is provided when the word is added to the custom model. + * _For a custom model that is based on a next-generation model_, the array + can include only sounds-like pronunciations that were added by a user. :param str display_as: The spelling of the word that the service uses to - display the word in a transcript. The field contains an empty string if no - display-as value is provided for the word, in which case the word is - displayed as it is spelled. + display the word in a transcript. + * _For a custom model that is based on a previous-generation model_, the + field can contain an empty string if no display-as value is provided for a + word that exists in the service's base vocabulary. In this case, the word + is displayed as it is spelled. + * _For a custom model that is based on a next-generation model_, the + service uses the spelling of the word as the value of the display-as field + when the word is added to the model. :param int count: _For a custom model that is based on a previous-generation model_, a sum of the number of times the word is found across all corpora and grammars. For example, if the word occurs five times diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py old mode 100755 new mode 100644 index ee6bc39b0..c71e6f2a8 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -172,7 +172,6 @@ def test_get_model_value_error(self): with pytest.raises(ValueError): _service.get_model(**req_copy) - def test_get_model_value_error_with_retries(self): # Enable retries and run test_get_model_value_error. _service.enable_retries() @@ -229,7 +228,6 @@ def test_recognize_all_params(self): profanity_filter = True smart_formatting = False speaker_labels = False - customization_id = 'testString' grammar_name = 'testString' redaction = False audio_metrics = False @@ -238,6 +236,7 @@ def test_recognize_all_params(self): speech_detector_sensitivity = 72.5 background_audio_suppression = 72.5 low_latency = False + character_insertion_bias = 72.5 # Invoke method response = _service.recognize( @@ -258,7 +257,6 @@ def test_recognize_all_params(self): profanity_filter=profanity_filter, smart_formatting=smart_formatting, speaker_labels=speaker_labels, - customization_id=customization_id, grammar_name=grammar_name, redaction=redaction, audio_metrics=audio_metrics, @@ -267,6 +265,7 @@ def test_recognize_all_params(self): speech_detector_sensitivity=speech_detector_sensitivity, background_audio_suppression=background_audio_suppression, low_latency=low_latency, + character_insertion_bias=character_insertion_bias, headers={} ) @@ -291,7 +290,6 @@ def test_recognize_all_params(self): assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string - assert 'customization_id={}'.format(customization_id) in query_string assert 'grammar_name={}'.format(grammar_name) in query_string assert 'redaction={}'.format('true' if redaction else 'false') in query_string assert 'audio_metrics={}'.format('true' if audio_metrics else 'false') in query_string @@ -300,6 +298,7 @@ def test_recognize_all_params(self): assert 'speech_detector_sensitivity={}'.format(speech_detector_sensitivity) in query_string assert 'background_audio_suppression={}'.format(background_audio_suppression) in query_string assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string + assert 'character_insertion_bias={}'.format(character_insertion_bias) in query_string # Validate body params def test_recognize_all_params_with_retries(self): @@ -374,7 +373,6 @@ def test_recognize_value_error(self): with pytest.raises(ValueError): _service.recognize(**req_copy) - def test_recognize_value_error_with_retries(self): # Enable retries and run test_recognize_value_error. _service.enable_retries() @@ -508,7 +506,6 @@ def test_register_callback_value_error(self): with pytest.raises(ValueError): _service.register_callback(**req_copy) - def test_register_callback_value_error_with_retries(self): # Enable retries and run test_register_callback_value_error. _service.enable_retries() @@ -583,7 +580,6 @@ def test_unregister_callback_value_error(self): with pytest.raises(ValueError): _service.unregister_callback(**req_copy) - def test_unregister_callback_value_error_with_retries(self): # Enable retries and run test_unregister_callback_value_error. _service.enable_retries() @@ -634,7 +630,6 @@ def test_create_job_all_params(self): profanity_filter = True smart_formatting = False speaker_labels = False - customization_id = 'testString' grammar_name = 'testString' redaction = False processing_metrics = False @@ -645,6 +640,7 @@ def test_create_job_all_params(self): speech_detector_sensitivity = 72.5 background_audio_suppression = 72.5 low_latency = False + character_insertion_bias = 72.5 # Invoke method response = _service.create_job( @@ -669,7 +665,6 @@ def test_create_job_all_params(self): profanity_filter=profanity_filter, smart_formatting=smart_formatting, speaker_labels=speaker_labels, - customization_id=customization_id, grammar_name=grammar_name, redaction=redaction, processing_metrics=processing_metrics, @@ -680,6 +675,7 @@ def test_create_job_all_params(self): speech_detector_sensitivity=speech_detector_sensitivity, background_audio_suppression=background_audio_suppression, low_latency=low_latency, + character_insertion_bias=character_insertion_bias, headers={} ) @@ -708,7 +704,6 @@ def test_create_job_all_params(self): assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string - assert 'customization_id={}'.format(customization_id) in query_string assert 'grammar_name={}'.format(grammar_name) in query_string assert 'redaction={}'.format('true' if redaction else 'false') in query_string assert 'processing_metrics={}'.format('true' if processing_metrics else 'false') in query_string @@ -719,6 +714,7 @@ def test_create_job_all_params(self): assert 'speech_detector_sensitivity={}'.format(speech_detector_sensitivity) in query_string assert 'background_audio_suppression={}'.format(background_audio_suppression) in query_string assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string + assert 'character_insertion_bias={}'.format(character_insertion_bias) in query_string # Validate body params def test_create_job_all_params_with_retries(self): @@ -793,7 +789,6 @@ def test_create_job_value_error(self): with pytest.raises(ValueError): _service.create_job(**req_copy) - def test_create_job_value_error_with_retries(self): # Enable retries and run test_create_job_value_error. _service.enable_retries() @@ -906,7 +901,6 @@ def test_check_job_value_error(self): with pytest.raises(ValueError): _service.check_job(**req_copy) - def test_check_job_value_error_with_retries(self): # Enable retries and run test_check_job_value_error. _service.enable_retries() @@ -977,7 +971,6 @@ def test_delete_job_value_error(self): with pytest.raises(ValueError): _service.delete_job(**req_copy) - def test_delete_job_value_error_with_retries(self): # Enable retries and run test_delete_job_value_error. _service.enable_retries() @@ -1080,7 +1073,6 @@ def test_create_language_model_value_error(self): with pytest.raises(ValueError): _service.create_language_model(**req_copy) - def test_create_language_model_value_error_with_retries(self): # Enable retries and run test_create_language_model_value_error. _service.enable_retries() @@ -1233,7 +1225,6 @@ def test_get_language_model_value_error(self): with pytest.raises(ValueError): _service.get_language_model(**req_copy) - def test_get_language_model_value_error_with_retries(self): # Enable retries and run test_get_language_model_value_error. _service.enable_retries() @@ -1304,7 +1295,6 @@ def test_delete_language_model_value_error(self): with pytest.raises(ValueError): _service.delete_language_model(**req_copy) - def test_delete_language_model_value_error_with_retries(self): # Enable retries and run test_delete_language_model_value_error. _service.enable_retries() @@ -1337,12 +1327,14 @@ def test_train_language_model_all_params(self): customization_id = 'testString' word_type_to_add = 'all' customization_weight = 72.5 + strict = True # Invoke method response = _service.train_language_model( customization_id, word_type_to_add=word_type_to_add, customization_weight=customization_weight, + strict=strict, headers={} ) @@ -1354,6 +1346,7 @@ def test_train_language_model_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'word_type_to_add={}'.format(word_type_to_add) in query_string assert 'customization_weight={}'.format(customization_weight) in query_string + assert 'strict={}'.format('true' if strict else 'false') in query_string def test_train_language_model_all_params_with_retries(self): # Enable retries and run test_train_language_model_all_params. @@ -1426,7 +1419,6 @@ def test_train_language_model_value_error(self): with pytest.raises(ValueError): _service.train_language_model(**req_copy) - def test_train_language_model_value_error_with_retries(self): # Enable retries and run test_train_language_model_value_error. _service.enable_retries() @@ -1497,7 +1489,6 @@ def test_reset_language_model_value_error(self): with pytest.raises(ValueError): _service.reset_language_model(**req_copy) - def test_reset_language_model_value_error_with_retries(self): # Enable retries and run test_reset_language_model_value_error. _service.enable_retries() @@ -1568,7 +1559,6 @@ def test_upgrade_language_model_value_error(self): with pytest.raises(ValueError): _service.upgrade_language_model(**req_copy) - def test_upgrade_language_model_value_error_with_retries(self): # Enable retries and run test_upgrade_language_model_value_error. _service.enable_retries() @@ -1655,7 +1645,6 @@ def test_list_corpora_value_error(self): with pytest.raises(ValueError): _service.list_corpora(**req_copy) - def test_list_corpora_value_error_with_retries(self): # Enable retries and run test_list_corpora_value_error. _service.enable_retries() @@ -1777,7 +1766,6 @@ def test_add_corpus_value_error(self): with pytest.raises(ValueError): _service.add_corpus(**req_copy) - def test_add_corpus_value_error_with_retries(self): # Enable retries and run test_add_corpus_value_error. _service.enable_retries() @@ -1858,7 +1846,6 @@ def test_get_corpus_value_error(self): with pytest.raises(ValueError): _service.get_corpus(**req_copy) - def test_get_corpus_value_error_with_retries(self): # Enable retries and run test_get_corpus_value_error. _service.enable_retries() @@ -1933,7 +1920,6 @@ def test_delete_corpus_value_error(self): with pytest.raises(ValueError): _service.delete_corpus(**req_copy) - def test_delete_corpus_value_error_with_retries(self): # Enable retries and run test_delete_corpus_value_error. _service.enable_retries() @@ -2065,7 +2051,6 @@ def test_list_words_value_error(self): with pytest.raises(ValueError): _service.list_words(**req_copy) - def test_list_words_value_error_with_retries(self): # Enable retries and run test_list_words_value_error. _service.enable_retries() @@ -2155,7 +2140,6 @@ def test_add_words_value_error(self): with pytest.raises(ValueError): _service.add_words(**req_copy) - def test_add_words_value_error_with_retries(self): # Enable retries and run test_add_words_value_error. _service.enable_retries() @@ -2244,7 +2228,6 @@ def test_add_word_value_error(self): with pytest.raises(ValueError): _service.add_word(**req_copy) - def test_add_word_value_error_with_retries(self): # Enable retries and run test_add_word_value_error. _service.enable_retries() @@ -2325,7 +2308,6 @@ def test_get_word_value_error(self): with pytest.raises(ValueError): _service.get_word(**req_copy) - def test_get_word_value_error_with_retries(self): # Enable retries and run test_get_word_value_error. _service.enable_retries() @@ -2400,7 +2382,6 @@ def test_delete_word_value_error(self): with pytest.raises(ValueError): _service.delete_word(**req_copy) - def test_delete_word_value_error_with_retries(self): # Enable retries and run test_delete_word_value_error. _service.enable_retries() @@ -2487,7 +2468,6 @@ def test_list_grammars_value_error(self): with pytest.raises(ValueError): _service.list_grammars(**req_copy) - def test_list_grammars_value_error_with_retries(self): # Enable retries and run test_list_grammars_value_error. _service.enable_retries() @@ -2617,7 +2597,6 @@ def test_add_grammar_value_error(self): with pytest.raises(ValueError): _service.add_grammar(**req_copy) - def test_add_grammar_value_error_with_retries(self): # Enable retries and run test_add_grammar_value_error. _service.enable_retries() @@ -2698,7 +2677,6 @@ def test_get_grammar_value_error(self): with pytest.raises(ValueError): _service.get_grammar(**req_copy) - def test_get_grammar_value_error_with_retries(self): # Enable retries and run test_get_grammar_value_error. _service.enable_retries() @@ -2773,7 +2751,6 @@ def test_delete_grammar_value_error(self): with pytest.raises(ValueError): _service.delete_grammar(**req_copy) - def test_delete_grammar_value_error_with_retries(self): # Enable retries and run test_delete_grammar_value_error. _service.enable_retries() @@ -2872,7 +2849,6 @@ def test_create_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.create_acoustic_model(**req_copy) - def test_create_acoustic_model_value_error_with_retries(self): # Enable retries and run test_create_acoustic_model_value_error. _service.enable_retries() @@ -3025,7 +3001,6 @@ def test_get_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.get_acoustic_model(**req_copy) - def test_get_acoustic_model_value_error_with_retries(self): # Enable retries and run test_get_acoustic_model_value_error. _service.enable_retries() @@ -3096,7 +3071,6 @@ def test_delete_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.delete_acoustic_model(**req_copy) - def test_delete_acoustic_model_value_error_with_retries(self): # Enable retries and run test_delete_acoustic_model_value_error. _service.enable_retries() @@ -3128,11 +3102,13 @@ def test_train_acoustic_model_all_params(self): # Set up parameter values customization_id = 'testString' custom_language_model_id = 'testString' + strict = True # Invoke method response = _service.train_acoustic_model( customization_id, custom_language_model_id=custom_language_model_id, + strict=strict, headers={} ) @@ -3143,6 +3119,7 @@ def test_train_acoustic_model_all_params(self): query_string = responses.calls[0].request.url.split('?',1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'custom_language_model_id={}'.format(custom_language_model_id) in query_string + assert 'strict={}'.format('true' if strict else 'false') in query_string def test_train_acoustic_model_all_params_with_retries(self): # Enable retries and run test_train_acoustic_model_all_params. @@ -3215,7 +3192,6 @@ def test_train_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.train_acoustic_model(**req_copy) - def test_train_acoustic_model_value_error_with_retries(self): # Enable retries and run test_train_acoustic_model_value_error. _service.enable_retries() @@ -3286,7 +3262,6 @@ def test_reset_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.reset_acoustic_model(**req_copy) - def test_reset_acoustic_model_value_error_with_retries(self): # Enable retries and run test_reset_acoustic_model_value_error. _service.enable_retries() @@ -3399,7 +3374,6 @@ def test_upgrade_acoustic_model_value_error(self): with pytest.raises(ValueError): _service.upgrade_acoustic_model(**req_copy) - def test_upgrade_acoustic_model_value_error_with_retries(self): # Enable retries and run test_upgrade_acoustic_model_value_error. _service.enable_retries() @@ -3486,7 +3460,6 @@ def test_list_audio_value_error(self): with pytest.raises(ValueError): _service.list_audio(**req_copy) - def test_list_audio_value_error_with_retries(self): # Enable retries and run test_list_audio_value_error. _service.enable_retries() @@ -3614,7 +3587,6 @@ def test_add_audio_value_error(self): with pytest.raises(ValueError): _service.add_audio(**req_copy) - def test_add_audio_value_error_with_retries(self): # Enable retries and run test_add_audio_value_error. _service.enable_retries() @@ -3695,7 +3667,6 @@ def test_get_audio_value_error(self): with pytest.raises(ValueError): _service.get_audio(**req_copy) - def test_get_audio_value_error_with_retries(self): # Enable retries and run test_get_audio_value_error. _service.enable_retries() @@ -3770,7 +3741,6 @@ def test_delete_audio_value_error(self): with pytest.raises(ValueError): _service.delete_audio(**req_copy) - def test_delete_audio_value_error_with_retries(self): # Enable retries and run test_delete_audio_value_error. _service.enable_retries() @@ -3855,7 +3825,6 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) - def test_delete_user_data_value_error_with_retries(self): # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() @@ -4646,7 +4615,7 @@ def test_recognition_job_serialization(self): speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] - speech_recognition_result_model['keywords_result'] = {} + speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' @@ -4758,7 +4727,7 @@ def test_recognition_jobs_serialization(self): speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] - speech_recognition_result_model['keywords_result'] = {} + speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' @@ -5056,7 +5025,7 @@ def test_speech_recognition_result_serialization(self): speech_recognition_result_model_json = {} speech_recognition_result_model_json['final'] = True speech_recognition_result_model_json['alternatives'] = [speech_recognition_alternative_model] - speech_recognition_result_model_json['keywords_result'] = {} + speech_recognition_result_model_json['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model_json['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model_json['end_of_utterance'] = 'end_of_data' @@ -5111,7 +5080,7 @@ def test_speech_recognition_results_serialization(self): speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] - speech_recognition_result_model['keywords_result'] = {} + speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' From b300c5527794eee5ab692a51eb858164dddfef93 Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Wed, 10 Aug 2022 09:26:33 -0500 Subject: [PATCH 375/455] feat(tts): add parameters Add parameter spellOutMode to synthesize --- ibm_watson/text_to_speech_v1.py | 261 +++++++++++++++++----------- test/unit/test_text_to_speech_v1.py | 41 ++--- 2 files changed, 171 insertions(+), 131 deletions(-) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 9d5514257..e0bd5f160 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -14,11 +14,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 +# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, -dialects, and voices. The service supports at least one male or female voice, sometimes +dialects, and voices. The service supports at least one male or female voice, sometimes both, for each language. The audio is streamed back to the client with minimal delay. For speech synthesis, the service supports a synchronous HTTP Representational State Transfer (REST) interface and a WebSocket interface. Both interfaces support plain text @@ -35,6 +35,14 @@ The service also offers a Tune by Example feature that lets you define custom prompts. You can also define speaker models to improve the quality of your custom prompts. The service support custom prompts only for US English custom models and voices. +Effective 31 March 2022, all neural voices are deprecated. The deprecated voices remain +available to existing users until 31 March 2023, when they will be removed from the +service and the documentation. The neural voices are supported only for IBM Cloud; they +are not available for IBM Cloud Pak for Data. All enhanced neural voices remain available +to all users. For more information, see the [31 March 2022 service +update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) +in the release notes for {{site.data.keyword.texttospeechshort}} for +{{site.data.keyword.cloud_notm}}.{: deprecated} API Version: 1.0.0 See: https://cloud.ibm.com/docs/text-to-speech @@ -94,6 +102,14 @@ def list_voices(self, **kwargs) -> DetailedResponse: list of voices can change from call to call; do not rely on an alphabetized or static list of voices. To see information about a specific voice, use the [Get a voice](#getvoice). + **Note:** Effective 31 March 2022, all neural voices are deprecated. The + deprecated voices remain available to existing users until 31 March 2023, when + they will be removed from the service and the documentation. The neural voices are + supported only for IBM Cloud; they are not available for IBM Cloud Pak for Data. + All enhanced neural voices remain available to all users. For more information, + see the [31 March 2022 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) + in the release notes. **See also:** [Listing all available voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoices). @@ -110,6 +126,7 @@ def list_voices(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/voices' @@ -133,10 +150,14 @@ def get_voice(self, voices](#listvoices) method. **See also:** [Listing a specific voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoice). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` - voice is deprecated; use the `ar-MS_OmarVoice` voice instead. + **Note:** Effective 31 March 2022, all neural voices are deprecated. The + deprecated voices remain available to existing users until 31 March 2023, when + they will be removed from the service and the documentation. The neural voices are + supported only for IBM Cloud; they are not available for IBM Cloud Pak for Data. + All enhanced neural voices remain available to all users. For more information, + see the [31 March 2022 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) + in the release notes. :param str voice: The voice for which information is to be returned. :param str customization_id: (optional) The customization ID (GUID) of a @@ -161,6 +182,7 @@ def get_voice(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['voice'] @@ -185,6 +207,7 @@ def synthesize(self, accept: str = None, voice: str = None, customization_id: str = None, + spell_out_mode: str = None, **kwargs) -> DetailedResponse: """ Synthesize audio. @@ -197,16 +220,20 @@ def synthesize(self, specify. The service returns the synthesized audio stream as an array of bytes. **See also:** [The HTTP interface](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-usingHTTP#usingHTTP). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` - voice is deprecated; use the `ar-MS_OmarVoice` voice instead. + **Note:** Effective 31 March 2022, all neural voices are deprecated. The + deprecated voices remain available to existing users until 31 March 2023, when + they will be removed from the service and the documentation. The neural voices are + supported only for IBM Cloud; they are not available for IBM Cloud Pak for Data. + All enhanced neural voices remain available to all users. For more information, + see the [31 March 2022 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) + in the release notes. ### 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 - audio. You must specify a sampling rate for the `audio/l16` and `audio/mulaw` - formats. A specified sampling rate must lie in the range of 8 kHz to 192 kHz. Some - formats restrict the sampling rate to certain values, as noted. + audio. You must specify a sampling rate for the `audio/alaw`, `audio/l16`, and + `audio/mulaw` formats. A specified sampling rate must lie in the range of 8 kHz to + 192 kHz. Some formats restrict the sampling rate to certain values, as noted. * For the `audio/l16` format, you can optionally specify the endianness (`endianness`) of the audio: `endianness=big-endian` or `endianness=little-endian`. @@ -214,6 +241,7 @@ def synthesize(self, of the response audio. If you omit an audio format altogether, the service returns the audio in Ogg format with the Opus codec (`audio/ogg;codecs=opus`). The service always returns single-channel audio. + * `audio/alaw` - You must specify the `rate` of the audio. * `audio/basic` - The service returns audio with a sampling rate of 8000 Hz. * `audio/flac` - You can optionally specify the `rate` of the audio. The default sampling rate is 22,050 Hz. @@ -257,25 +285,38 @@ def synthesize(self, audio. You can use the `Accept` header or the `accept` parameter to specify the audio format. For more information about specifying an audio format, see **Audio formats (accept types)** in the method description. - :param str voice: (optional) The voice to use for synthesis. If you omit - the `voice` parameter, the service uses a default voice, which depends on - the version of the service that you are using: - * _For IBM Cloud,_ the service always uses the US English + :param str voice: (optional) The voice to use for speech synthesis. If you + omit the `voice` parameter, the service uses the US English `en-US_MichaelV3Voice` by default. - * _For IBM Cloud Pak for Data,_ the default voice depends on the voices - that you installed. If you installed the _enhanced neural voices_, the - service uses the US English `en-US_MichaelV3Voice` by default; if that - voice is not installed, you must specify a voice. If you installed the - _neural voices_, the service always uses the Australian English - `en-AU_MadisonVoice` by default. - **See also:** See also [Using languages and - voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices). + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_MichaelV3Voice`, you must either specify a voice with the request or + specify a new default voice for your installation of the service. + **See also:** + * [Using languages and + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices) + * [The default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#specify-voice-default). :param str customization_id: (optional) The customization ID (GUID) of a custom model to use for the synthesis. If a custom model is specified, it works only if it matches the language of the indicated voice. You must make the request with credentials for the instance of the service that owns the custom model. Omit the parameter to use the specified voice with no customization. + :param str spell_out_mode: (optional) *For German voices,* indicates how + the service is to spell out strings of individual letters. To indicate the + pace of the spelling, specify one of the following values: + * `default` - The service reads the characters at the rate at which it + synthesizes speech for the request. You can also omit the parameter + entirely to achieve the default behavior. + * `singles` - The service reads the characters one at a time, with a brief + pause between each character. + * `pairs` - The service reads the characters two at a time, with a brief + pause between each pair. + * `triples` - The service reads the characters three at a time, with a + brief pause between each triplet. + The parameter is available only for IBM Cloud. + **See also:** [Specifying how strings are spelled + out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `BinaryIO` result @@ -289,7 +330,11 @@ def synthesize(self, operation_id='synthesize') headers.update(sdk_headers) - params = {'voice': voice, 'customization_id': customization_id} + params = { + 'voice': voice, + 'customization_id': customization_id, + 'spell_out_mode': spell_out_mode + } data = {'text': text} data = {k: v for (k, v) in data.items() if v is not None} @@ -298,6 +343,7 @@ def synthesize(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/synthesize' request = self.prepare_request(method='POST', @@ -327,17 +373,27 @@ def get_pronunciation(self, pronunciation for a specific format. You can also request the pronunciation for a specific voice to see the default translation for the language of that voice or for a specific custom model to see the translation for that model. + **Note:** Effective 31 March 2022, all neural voices are deprecated. The + deprecated voices remain available to existing users until 31 March 2023, when + they will be removed from the service and the documentation. The neural voices are + supported only for IBM Cloud; they are not available for IBM Cloud Pak for Data. + All enhanced neural voices remain available to all users. For more information, + see the [31 March 2022 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) + in the release notes. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` - voice is deprecated; use the `ar-MS_OmarVoice` voice instead. :param str text: The word for which the pronunciation is requested. :param str voice: (optional) A voice that specifies the language in which - the pronunciation is to be returned. All voices for the same language (for - example, `en-US`) return the same translation. + the pronunciation is to be returned. If you omit the `voice` parameter, the + service uses the US English `en-US_MichaelV3Voice` by default. All voices + for the same language (for example, `en-US`) return the same translation. + _For IBM Cloud Pak for Data,_ if you do not install the + `en-US_MichaelV3Voice`, you must either specify a voice with the request or + specify a new default voice for your installation of the service. + **See also:** [The default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#specify-voice-default). :param str format: (optional) The phoneme format in which to return the pronunciation. The Arabic, Chinese, Dutch, Australian English, and Korean languages support only IPA. Omit the parameter to obtain the pronunciation @@ -372,6 +428,7 @@ def get_pronunciation(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/pronunciation' @@ -402,22 +459,20 @@ def create_custom_model(self, used to create it. **See also:** [Creating a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). - **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian - English, Korean, and Swedish languages and voices are supported only for IBM - Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR` language - identifier cannot be used to create a custom model; use the `ar-MS` identifier - instead. + **Note:** Effective 31 March 2022, all neural voices are deprecated. The + deprecated voices remain available to existing users until 31 March 2023, when + they will be removed from the service and the documentation. The neural voices are + supported only for IBM Cloud; they are not available for IBM Cloud Pak for Data. + All enhanced neural voices remain available to all users. For more information, + see the [31 March 2022 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) + in the release notes. :param str name: The name of the new custom model. :param str language: (optional) The language of the new custom model. You create a custom model for a specific language, not for a specific voice. A custom model can be used with any voice for its specified language. Omit the parameter to use the the default language, `en-US`. - **Important:** If you are using the service on IBM Cloud Pak for Data _and_ - you install the neural voices, the `language`parameter is required. You - must specify the language for the custom model in the indicated format (for - example, `en-AU` for Australian English). The request fails if you do not - specify a language. :param str description: (optional) A description of the new custom model. Specifying a description is recommended. :param dict headers: A `dict` containing the request headers @@ -440,6 +495,7 @@ def create_custom_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' @@ -485,6 +541,7 @@ def list_custom_models(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/customizations' @@ -560,6 +617,7 @@ def update_custom_model(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -605,6 +663,7 @@ def get_custom_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -644,6 +703,7 @@ def delete_custom_model(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id'] path_param_values = self.encode_path_vars(customization_id) @@ -722,6 +782,7 @@ def add_words(self, customization_id: str, words: List['Word'], if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -765,6 +826,7 @@ def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -852,6 +914,7 @@ def add_word(self, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id', 'word'] path_param_values = self.encode_path_vars(customization_id, word) @@ -898,6 +961,7 @@ def get_word(self, customization_id: str, word: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'word'] @@ -941,6 +1005,7 @@ def delete_word(self, customization_id: str, word: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id', 'word'] path_param_values = self.encode_path_vars(customization_id, word) @@ -993,6 +1058,7 @@ def list_custom_prompts(self, customization_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id'] @@ -1131,6 +1197,7 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'prompt_id'] @@ -1180,6 +1247,7 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['customization_id', 'prompt_id'] @@ -1229,6 +1297,7 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['customization_id', 'prompt_id'] path_param_values = self.encode_path_vars(customization_id, prompt_id) @@ -1271,6 +1340,7 @@ def list_speaker_models(self, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/speakers' @@ -1362,6 +1432,7 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' url = '/v1/speakers' @@ -1407,6 +1478,7 @@ def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] headers['Accept'] = 'application/json' path_param_keys = ['speaker_id'] @@ -1454,6 +1526,7 @@ def delete_speaker_model(self, speaker_id: str, if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] path_param_keys = ['speaker_id'] path_param_values = self.encode_path_vars(speaker_id) @@ -1507,6 +1580,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if 'headers' in kwargs: headers.update(kwargs.get('headers')) + del kwargs['headers'] url = '/v1/user_data' request = self.prepare_request(method='DELETE', @@ -1527,12 +1601,9 @@ class Voice(str, Enum): """ The voice for which information is to be returned. """ - AR_AR_OMARVOICE = 'ar-AR_OmarVoice' AR_MS_OMARVOICE = 'ar-MS_OmarVoice' CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' - DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' - DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' @@ -1540,33 +1611,22 @@ class Voice(str, Enum): EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' - EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' - EN_US_ALLISONVOICE = 'en-US_AllisonVoice' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' - EN_US_LISAVOICE = 'en-US_LisaVoice' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' - EN_US_MICHAELVOICE = 'en-US_MichaelVoice' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' - ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' - ES_ES_LAURAVOICE = 'es-ES_LauraVoice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' - ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' - ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' - FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' - IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' - JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' @@ -1576,7 +1636,6 @@ class Voice(str, Enum): NL_BE_BRAMVOICE = 'nl-BE_BramVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' - PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' @@ -1596,6 +1655,7 @@ class Accept(str, Enum): specifying an audio format, see **Audio formats (accept types)** in the method description. """ + AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' AUDIO_FLAC = 'audio/flac' AUDIO_L16 = 'audio/l16' @@ -1612,25 +1672,20 @@ class Accept(str, Enum): class Voice(str, Enum): """ - The voice to use for synthesis. If you omit the `voice` parameter, the service - uses a default voice, which depends on the version of the service that you are - using: - * _For IBM Cloud,_ the service always uses the US English `en-US_MichaelV3Voice` - by default. - * _For IBM Cloud Pak for Data,_ the default voice depends on the voices that you - installed. If you installed the _enhanced neural voices_, the service uses the US - English `en-US_MichaelV3Voice` by default; if that voice is not installed, you - must specify a voice. If you installed the _neural voices_, the service always - uses the Australian English `en-AU_MadisonVoice` by default. - **See also:** See also [Using languages and - voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices). - """ - AR_AR_OMARVOICE = 'ar-AR_OmarVoice' + The voice to use for speech synthesis. If you omit the `voice` parameter, the + service uses the US English `en-US_MichaelV3Voice` by default. + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_MichaelV3Voice`, + you must either specify a voice with the request or specify a new default voice + for your installation of the service. + **See also:** + * [Using languages and + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices) + * [The default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#specify-voice-default). + """ AR_MS_OMARVOICE = 'ar-MS_OmarVoice' CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' - DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' - DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' @@ -1638,33 +1693,22 @@ class Voice(str, Enum): EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' - EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' - EN_US_ALLISONVOICE = 'en-US_AllisonVoice' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' - EN_US_LISAVOICE = 'en-US_LisaVoice' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' - EN_US_MICHAELVOICE = 'en-US_MichaelVoice' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' - ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' - ES_ES_LAURAVOICE = 'es-ES_LauraVoice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' - ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' - ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' - FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' - IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' - JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' @@ -1674,13 +1718,35 @@ class Voice(str, Enum): NL_BE_BRAMVOICE = 'nl-BE_BramVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' - PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' + class SpellOutMode(str, Enum): + """ + *For German voices,* indicates how the service is to spell out strings of + individual letters. To indicate the pace of the spelling, specify one of the + following values: + * `default` - The service reads the characters at the rate at which it synthesizes + speech for the request. You can also omit the parameter entirely to achieve the + default behavior. + * `singles` - The service reads the characters one at a time, with a brief pause + between each character. + * `pairs` - The service reads the characters two at a time, with a brief pause + between each pair. + * `triples` - The service reads the characters three at a time, with a brief pause + between each triplet. + The parameter is available only for IBM Cloud. + **See also:** [Specifying how strings are spelled + out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). + """ + DEFAULT = 'default' + SINGLES = 'singles' + PAIRS = 'pairs' + TRIPLES = 'triples' + class GetPronunciationEnums: """ @@ -1690,15 +1756,18 @@ class GetPronunciationEnums: class Voice(str, Enum): """ A voice that specifies the language in which the pronunciation is to be returned. - All voices for the same language (for example, `en-US`) return the same - translation. + If you omit the `voice` parameter, the service uses the US English + `en-US_MichaelV3Voice` by default. All voices for the same language (for example, + `en-US`) return the same translation. + _For IBM Cloud Pak for Data,_ if you do not install the `en-US_MichaelV3Voice`, + you must either specify a voice with the request or specify a new default voice + for your installation of the service. + **See also:** [The default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#specify-voice-default). """ - AR_AR_OMARVOICE = 'ar-AR_OmarVoice' AR_MS_OMARVOICE = 'ar-MS_OmarVoice' CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' - DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' - DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' @@ -1706,33 +1775,22 @@ class Voice(str, Enum): EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' - EN_GB_KATEVOICE = 'en-GB_KateVoice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' - EN_US_ALLISONVOICE = 'en-US_AllisonVoice' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' - EN_US_LISAVOICE = 'en-US_LisaVoice' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' - EN_US_MICHAELVOICE = 'en-US_MichaelVoice' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' - ES_ES_ENRIQUEVOICE = 'es-ES_EnriqueVoice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' - ES_ES_LAURAVOICE = 'es-ES_LauraVoice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' - ES_LA_SOFIAVOICE = 'es-LA_SofiaVoice' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' - ES_US_SOFIAVOICE = 'es-US_SofiaVoice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' FR_FR_NICOLASV3VOICE = 'fr-FR_NicolasV3Voice' - FR_FR_RENEEVOICE = 'fr-FR_ReneeVoice' FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' - IT_IT_FRANCESCAVOICE = 'it-IT_FrancescaVoice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' - JA_JP_EMIVOICE = 'ja-JP_EmiVoice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' @@ -1742,7 +1800,6 @@ class Voice(str, Enum): NL_BE_BRAMVOICE = 'nl-BE_BramVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' - PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 25ab220d2..36af23b08 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -116,7 +116,7 @@ def test_get_voice_all_params(self): get_voice() """ # Set up mock - url = preprocess_url('/v1/voices/ar-AR_OmarVoice') + url = preprocess_url('/v1/voices/ar-MS_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, @@ -125,7 +125,7 @@ def test_get_voice_all_params(self): status=200) # Set up parameter values - voice = 'ar-AR_OmarVoice' + voice = 'ar-MS_OmarVoice' customization_id = 'testString' # Invoke method @@ -158,7 +158,7 @@ def test_get_voice_required_params(self): test_get_voice_required_params() """ # Set up mock - url = preprocess_url('/v1/voices/ar-AR_OmarVoice') + url = preprocess_url('/v1/voices/ar-MS_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, @@ -167,7 +167,7 @@ def test_get_voice_required_params(self): status=200) # Set up parameter values - voice = 'ar-AR_OmarVoice' + voice = 'ar-MS_OmarVoice' # Invoke method response = _service.get_voice( @@ -194,7 +194,7 @@ def test_get_voice_value_error(self): test_get_voice_value_error() """ # Set up mock - url = preprocess_url('/v1/voices/ar-AR_OmarVoice') + url = preprocess_url('/v1/voices/ar-MS_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add(responses.GET, url, @@ -203,7 +203,7 @@ def test_get_voice_value_error(self): status=200) # Set up parameter values - voice = 'ar-AR_OmarVoice' + voice = 'ar-MS_OmarVoice' # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -214,7 +214,6 @@ def test_get_voice_value_error(self): with pytest.raises(ValueError): _service.get_voice(**req_copy) - def test_get_voice_value_error_with_retries(self): # Enable retries and run test_get_voice_value_error. _service.enable_retries() @@ -250,7 +249,7 @@ def test_synthesize_all_params(self): responses.add(responses.POST, url, body=mock_response, - content_type='audio/basic', + content_type='audio/alaw', status=200) # Set up parameter values @@ -258,6 +257,7 @@ def test_synthesize_all_params(self): accept = 'audio/ogg;codecs=opus' voice = 'en-US_MichaelV3Voice' customization_id = 'testString' + spell_out_mode = 'default' # Invoke method response = _service.synthesize( @@ -265,6 +265,7 @@ def test_synthesize_all_params(self): accept=accept, voice=voice, customization_id=customization_id, + spell_out_mode=spell_out_mode, headers={} ) @@ -276,6 +277,7 @@ def test_synthesize_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'voice={}'.format(voice) in query_string assert 'customization_id={}'.format(customization_id) in query_string + assert 'spell_out_mode={}'.format(spell_out_mode) in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['text'] == 'testString' @@ -300,7 +302,7 @@ def test_synthesize_required_params(self): responses.add(responses.POST, url, body=mock_response, - content_type='audio/basic', + content_type='audio/alaw', status=200) # Set up parameter values @@ -339,7 +341,7 @@ def test_synthesize_value_error(self): responses.add(responses.POST, url, body=mock_response, - content_type='audio/basic', + content_type='audio/alaw', status=200) # Set up parameter values @@ -354,7 +356,6 @@ def test_synthesize_value_error(self): with pytest.raises(ValueError): _service.synthesize(**req_copy) - def test_synthesize_value_error_with_retries(self): # Enable retries and run test_synthesize_value_error. _service.enable_retries() @@ -494,7 +495,6 @@ def test_get_pronunciation_value_error(self): with pytest.raises(ValueError): _service.get_pronunciation(**req_copy) - def test_get_pronunciation_value_error_with_retries(self): # Enable retries and run test_get_pronunciation_value_error. _service.enable_retries() @@ -592,7 +592,6 @@ def test_create_custom_model_value_error(self): with pytest.raises(ValueError): _service.create_custom_model(**req_copy) - def test_create_custom_model_value_error_with_retries(self): # Enable retries and run test_create_custom_model_value_error. _service.enable_retries() @@ -765,7 +764,6 @@ def test_update_custom_model_value_error(self): with pytest.raises(ValueError): _service.update_custom_model(**req_copy) - def test_update_custom_model_value_error_with_retries(self): # Enable retries and run test_update_custom_model_value_error. _service.enable_retries() @@ -842,7 +840,6 @@ def test_get_custom_model_value_error(self): with pytest.raises(ValueError): _service.get_custom_model(**req_copy) - def test_get_custom_model_value_error_with_retries(self): # Enable retries and run test_get_custom_model_value_error. _service.enable_retries() @@ -913,7 +910,6 @@ def test_delete_custom_model_value_error(self): with pytest.raises(ValueError): _service.delete_custom_model(**req_copy) - def test_delete_custom_model_value_error_with_retries(self): # Enable retries and run test_delete_custom_model_value_error. _service.enable_retries() @@ -1013,7 +1009,6 @@ def test_add_words_value_error(self): with pytest.raises(ValueError): _service.add_words(**req_copy) - def test_add_words_value_error_with_retries(self): # Enable retries and run test_add_words_value_error. _service.enable_retries() @@ -1090,7 +1085,6 @@ def test_list_words_value_error(self): with pytest.raises(ValueError): _service.list_words(**req_copy) - def test_list_words_value_error_with_retries(self): # Enable retries and run test_list_words_value_error. _service.enable_retries() @@ -1176,7 +1170,6 @@ def test_add_word_value_error(self): with pytest.raises(ValueError): _service.add_word(**req_copy) - def test_add_word_value_error_with_retries(self): # Enable retries and run test_add_word_value_error. _service.enable_retries() @@ -1257,7 +1250,6 @@ def test_get_word_value_error(self): with pytest.raises(ValueError): _service.get_word(**req_copy) - def test_get_word_value_error_with_retries(self): # Enable retries and run test_get_word_value_error. _service.enable_retries() @@ -1332,7 +1324,6 @@ def test_delete_word_value_error(self): with pytest.raises(ValueError): _service.delete_word(**req_copy) - def test_delete_word_value_error_with_retries(self): # Enable retries and run test_delete_word_value_error. _service.enable_retries() @@ -1419,7 +1410,6 @@ def test_list_custom_prompts_value_error(self): with pytest.raises(ValueError): _service.list_custom_prompts(**req_copy) - def test_list_custom_prompts_value_error_with_retries(self): # Enable retries and run test_list_custom_prompts_value_error. _service.enable_retries() @@ -1518,7 +1508,6 @@ def test_add_custom_prompt_value_error(self): with pytest.raises(ValueError): _service.add_custom_prompt(**req_copy) - def test_add_custom_prompt_value_error_with_retries(self): # Enable retries and run test_add_custom_prompt_value_error. _service.enable_retries() @@ -1599,7 +1588,6 @@ def test_get_custom_prompt_value_error(self): with pytest.raises(ValueError): _service.get_custom_prompt(**req_copy) - def test_get_custom_prompt_value_error_with_retries(self): # Enable retries and run test_get_custom_prompt_value_error. _service.enable_retries() @@ -1674,7 +1662,6 @@ def test_delete_custom_prompt_value_error(self): with pytest.raises(ValueError): _service.delete_custom_prompt(**req_copy) - def test_delete_custom_prompt_value_error_with_retries(self): # Enable retries and run test_delete_custom_prompt_value_error. _service.enable_retries() @@ -1807,7 +1794,6 @@ def test_create_speaker_model_value_error(self): with pytest.raises(ValueError): _service.create_speaker_model(**req_copy) - def test_create_speaker_model_value_error_with_retries(self): # Enable retries and run test_create_speaker_model_value_error. _service.enable_retries() @@ -1884,7 +1870,6 @@ def test_get_speaker_model_value_error(self): with pytest.raises(ValueError): _service.get_speaker_model(**req_copy) - def test_get_speaker_model_value_error_with_retries(self): # Enable retries and run test_get_speaker_model_value_error. _service.enable_retries() @@ -1955,7 +1940,6 @@ def test_delete_speaker_model_value_error(self): with pytest.raises(ValueError): _service.delete_speaker_model(**req_copy) - def test_delete_speaker_model_value_error_with_retries(self): # Enable retries and run test_delete_speaker_model_value_error. _service.enable_retries() @@ -2040,7 +2024,6 @@ def test_delete_user_data_value_error(self): with pytest.raises(ValueError): _service.delete_user_data(**req_copy) - def test_delete_user_data_value_error_with_retries(self): # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() From 069bba3194b2cc85a36db60ee01c200f29cbe88b Mon Sep 17 00:00:00 2001 From: Harrison Saylor Date: Wed, 10 Aug 2022 09:29:33 -0500 Subject: [PATCH 376/455] chore(detect-secrets): run detect secrets --- .secrets.baseline | 100 +++++++++++++++++++--------------------------- 1 file changed, 42 insertions(+), 58 deletions(-) diff --git a/.secrets.baseline b/.secrets.baseline index a9c0826d5..bf19efa9e 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "package-lock.json|^.secrets.baseline$", "lines": null }, - "generated_at": "2022-03-21T19:21:18Z", + "generated_at": "2022-08-10T14:28:21Z", "plugins_used": [ { "name": "AWSKeyDetector" @@ -25,9 +25,7 @@ "name": "CloudantDetector" }, { - "name": "Db2Detector" - }, - { + "ghe_instance": "github.ibm.com", "name": "GheDetector" }, { @@ -67,22 +65,12 @@ } ], "results": { - ".github/workflows/deploy.yml": [ - { - "hashed_secret": "51543e129a641c2ece91b32b5bbeaa704dbfe764", - "is_secret": false, - "is_verified": false, - "line_number": 76, - "type": "DB2 Credentials", - "verified_result": null - } - ], "README.md": [ { "hashed_secret": "d9e9019d9eb455a3d72a3bc252c26927bb148a10", "is_secret": false, "is_verified": false, - "line_number": 132, + "line_number": 137, "type": "Secret Keyword", "verified_result": null }, @@ -90,7 +78,7 @@ "hashed_secret": "32e8612d8ca77c7ea8374aa7918db8e5df9252ed", "is_secret": false, "is_verified": false, - "line_number": 174, + "line_number": 181, "type": "Secret Keyword", "verified_result": null }, @@ -98,15 +86,7 @@ "hashed_secret": "186154712b2d5f6791d85b9a0987b98fa231779c", "is_secret": false, "is_verified": false, - "line_number": 228, - "type": "DB2 Credentials", - "verified_result": null - }, - { - "hashed_secret": "186154712b2d5f6791d85b9a0987b98fa231779c", - "is_secret": false, - "is_verified": false, - "line_number": 228, + "line_number": 241, "type": "Secret Keyword", "verified_result": null } @@ -123,34 +103,18 @@ ], "ibm_watson/discovery_v1.py": [ { - "hashed_secret": "3442496b96dd01591a8cd44b1eec1368ab728aba", - "is_secret": false, - "is_verified": false, - "line_number": 4723, - "type": "DB2 Credentials", - "verified_result": null - }, - { - "hashed_secret": "b16c7ac6faff07d7e255da685e52bd66d3bf1575", - "is_secret": false, - "is_verified": false, - "line_number": 4781, - "type": "DB2 Credentials", - "verified_result": null - }, - { - "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "hashed_secret": "e8fc807ce6fbcda13f91c5b64850173873de0cdc", "is_secret": false, "is_verified": false, - "line_number": 4828, - "type": "DB2 Credentials", + "line_number": 5029, + "type": "Secret Keyword", "verified_result": null }, { - "hashed_secret": "e8fc807ce6fbcda13f91c5b64850173873de0cdc", + "hashed_secret": "fdee05598fdd57ff8e9ae29e92c25a04f2c52fa6", "is_secret": false, "is_verified": false, - "line_number": 4967, + "line_number": 5030, "type": "Secret Keyword", "verified_result": null } @@ -171,32 +135,52 @@ "is_secret": false, "is_verified": false, "line_number": 168, - "type": "DB2 Credentials", + "type": "Secret Keyword", + "verified_result": null + } + ], + "test/unit/test_assistant_v1.py": [ + { + "hashed_secret": "d506bd5213c46bd49e16c634754ad70113408252", + "is_secret": false, + "is_verified": false, + "line_number": 7655, + "type": "Secret Keyword", "verified_result": null }, { - "hashed_secret": "b60d121b438a380c343d5ec3c2037564b82ffef3", + "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 168, + "line_number": 11429, "type": "Secret Keyword", "verified_result": null } ], - "test/unit/test_discovery_v1.py": [ + "test/unit/test_assistant_v2.py": [ { - "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "hashed_secret": "d506bd5213c46bd49e16c634754ad70113408252", "is_secret": false, "is_verified": false, - "line_number": 6789, - "type": "DB2 Credentials", + "line_number": 975, + "type": "Secret Keyword", "verified_result": null }, + { + "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", + "is_secret": false, + "is_verified": false, + "line_number": 4876, + "type": "Secret Keyword", + "verified_result": null + } + ], + "test/unit/test_discovery_v1.py": [ { "hashed_secret": "8318df9ecda039deac9868adf1944a29a95c7114", "is_secret": false, "is_verified": false, - "line_number": 6789, + "line_number": 6733, "type": "Secret Keyword", "verified_result": null }, @@ -204,7 +188,7 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 7961, + "line_number": 7899, "type": "Secret Keyword", "verified_result": null }, @@ -212,7 +196,7 @@ "hashed_secret": "b8e758b5ad59a72f146fcf065239d5c7b695a39a", "is_secret": false, "is_verified": false, - "line_number": 10241, + "line_number": 10179, "type": "Hex High Entropy String", "verified_result": null } @@ -222,13 +206,13 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 418, + "line_number": 416, "type": "Secret Keyword", "verified_result": null } ] }, - "version": "0.13.1+ibm.26.dss", + "version": "0.13.1+ibm.50.dss", "word_list": { "file": null, "hash": null From 1b5f1715ad92573bc8fce2e44ba8b6e5efda3780 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 10 Aug 2022 10:48:34 -0500 Subject: [PATCH 377/455] feat(wss): add and remove websocket params --- ibm_watson/speech_to_text_v1_adapter.py | 32 +++++++++++++++++++------ ibm_watson/text_to_speech_adapter_v1.py | 17 +++++++++++++ 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index e9119ff72..cf383347c 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -45,7 +45,6 @@ def recognize_using_websocket(self, speaker_labels=None, http_proxy_host=None, http_proxy_port=None, - customization_id=None, grammar_name=None, redaction=None, processing_metrics=None, @@ -56,6 +55,7 @@ def recognize_using_websocket(self, speech_detector_sensitivity=None, background_audio_suppression=None, low_latency=None, + character_insertion_bias: float = None, **kwargs): """ Sends audio for speech recognition using web sockets. @@ -190,10 +190,6 @@ def recognize_using_websocket(self, labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. - :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 - request. Do not specify both parameters with a request. :param str grammar_name: (optional) The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the @@ -287,6 +283,28 @@ def recognize_using_websocket(self, for next-generation models. * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). + :param float character_insertion_bias: (optional) For next-generation + `Multimedia` and `Telephony` models, an indication of whether the service + is biased to recognize shorter or longer strings of characters when + developing transcription hypotheses. By default, the service is optimized + for each individual model to balance its recognition of strings of + different lengths. The model-specific bias is equivalent to 0.0. + The value that you specify represents a change from a model's default bias. + The allowable range of values is -1.0 to 1.0. + * Negative values bias the service to favor hypotheses with shorter strings + of characters. + * Positive values bias the service to favor hypotheses with longer strings + of characters. + As the value approaches -1.0 or 1.0, the impact of the parameter becomes + more pronounced. To determine the most effective value for your scenario, + start by setting the value of the parameter to a small increment, such as + -0.1, -0.05, 0.05, or 0.1, and assess how the value impacts the + transcription results. Then experiment with different values as necessary, + adjusting the value by small increments. + The parameter is not available for previous-generation `Broadband` and + `Narrowband` models. + See [Character insertion + bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). :param dict headers: A `dict` containing the request headers :return: A `dict` containing the `SpeechRecognitionResults` response. :rtype: dict @@ -321,7 +339,6 @@ def recognize_using_websocket(self, params = { 'model': model, - 'customization_id': customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, 'language_customization_id': language_customization_id @@ -353,7 +370,8 @@ def recognize_using_websocket(self, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, - 'low_latency': low_latency + 'low_latency': low_latency, + 'character_insertion_bias': character_insertion_bias } options = {k: v for k, v in options.items() if v is not None} request['options'] = options diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index c05763a08..08b5190de 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -30,6 +30,7 @@ def synthesize_using_websocket(self, voice=None, timings=None, customization_id=None, + spell_out_mode: str = None, http_proxy_host=None, http_proxy_port=None, **kwargs): @@ -60,6 +61,21 @@ def synthesize_using_websocket(self, If you include a customization ID, you must call the method with the service credentials of the custom model's owner. Omit the parameter to use the specified voice with no customization. For more information, see [Understanding customization] (https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customIntro#customIntro). + :param str spell_out_mode: (optional) *For German voices,* indicates how + the service is to spell out strings of individual letters. To indicate the + pace of the spelling, specify one of the following values: + * `default` - The service reads the characters at the rate at which it + synthesizes speech for the request. You can also omit the parameter + entirely to achieve the default behavior. + * `singles` - The service reads the characters one at a time, with a brief + pause between each character. + * `pairs` - The service reads the characters two at a time, with a brief + pause between each pair. + * `triples` - The service reads the characters three at a time, with a + brief pause between each triplet. + The parameter is available only for IBM Cloud. + **See also:** [Specifying how strings are spelled + out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. :param dict headers: A `dict` containing the request headers @@ -90,6 +106,7 @@ def synthesize_using_websocket(self, params = { 'voice': voice, 'customization_id': customization_id, + 'spell_out_mode': spell_out_mode } params = {k: v for k, v in params.items() if v is not None} url += '/v1/synthesize?{0}'.format(urlencode(params)) From 149bdd280b7ff49ac344fb796993554539474be5 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 10 Aug 2022 10:59:49 -0500 Subject: [PATCH 378/455] refactor(wss): keep original formatting --- ibm_watson/speech_to_text_v1_adapter.py | 2 +- ibm_watson/text_to_speech_adapter_v1.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index cf383347c..5b0fa08d7 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -55,7 +55,7 @@ def recognize_using_websocket(self, speech_detector_sensitivity=None, background_audio_suppression=None, low_latency=None, - character_insertion_bias: float = None, + character_insertion_bias=None, **kwargs): """ Sends audio for speech recognition using web sockets. diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index 08b5190de..229daad33 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -30,7 +30,7 @@ def synthesize_using_websocket(self, voice=None, timings=None, customization_id=None, - spell_out_mode: str = None, + spell_out_mode=None, http_proxy_host=None, http_proxy_port=None, **kwargs): From c9dbbfa11cd8a301dab779e11b3ce429ab508d79 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 10 Aug 2022 11:32:41 -0500 Subject: [PATCH 379/455] chore(assistants): small hand edits --- ibm_watson/assistant_v1.py | 2 +- ibm_watson/assistant_v2.py | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index ee13305c3..939362250 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -48,7 +48,7 @@ class AssistantV1(BaseService): """The Assistant V1 service.""" DEFAULT_SERVICE_URL = 'https://api.us-south.assistant.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'conversation' + DEFAULT_SERVICE_NAME = 'assistant' def __init__( self, diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index f7318ec4a..8e268cf1e 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -48,7 +48,7 @@ class AssistantV2(BaseService): """The Assistant V2 service.""" DEFAULT_SERVICE_URL = 'https://api.us-south.assistant.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'conversation' + DEFAULT_SERVICE_NAME = 'assistant' def __init__( self, @@ -84,7 +84,6 @@ def __init__( def create_session(self, assistant_id: str, *, - create_session: 'CreateSession' = None, **kwargs) -> DetailedResponse: """ Create a session. @@ -101,7 +100,6 @@ def create_session(self, assistants, see the [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 CreateSession create_session: (optional) :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SessionResponse` object From ac82c45c14ddcd0d608496d1193da09d555b6f15 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 10 Aug 2022 11:48:45 -0500 Subject: [PATCH 380/455] fix(assistantv2): use original createSession method signature --- ibm_watson/assistant_v2.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 8e268cf1e..027b9b3af 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -81,10 +81,7 @@ def __init__( # Sessions ######################### - def create_session(self, - assistant_id: str, - *, - **kwargs) -> DetailedResponse: + def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: """ Create a session. From b2c6e4e89bda4d83ef122ed537bbc9ea9c32f3ee Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 10 Aug 2022 13:43:14 -0500 Subject: [PATCH 381/455] build(version): correct version numbers --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 3b4781f21..b500bbee6 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.3.0 +current_version = 6.0.0 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 1d4672ff0..98d739c93 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '5.3.0' +__version__ = '6.0.0' diff --git a/setup.py b/setup.py index 09a62b2a8..cd872b28f 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '5.3.0' +__version__ = '6.0.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From 6d60aa4e257deb4afa6045ad7b1f10f5c9e1d7ae Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 10 Aug 2022 14:34:18 -0500 Subject: [PATCH 382/455] build(version): prep version numbers for semantic release fix --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index b500bbee6..de99fb6cb 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 6.0.0 +current_version = 6.0.1 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 98d739c93..c4b0ef895 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '6.0.0' +__version__ = '6.0.1' diff --git a/setup.py b/setup.py index cd872b28f..f33720748 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '6.0.0' +__version__ = '6.0.1' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From c9ae547b4f14a6e8f58756acee7ba611a270f11d Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 23 Feb 2023 11:46:24 -0600 Subject: [PATCH 383/455] refactor(all): generator only changes --- ibm_watson/assistant_v1.py | 1447 ++++++++++++----- ibm_watson/assistant_v2.py | 909 ++++++++--- ibm_watson/discovery_v1.py | 1213 ++++++++++---- ibm_watson/discovery_v2.py | 1228 +++++++++----- ibm_watson/language_translator_v3.py | 134 +- .../natural_language_understanding_v1.py | 552 +++++-- ibm_watson/speech_to_text_v1.py | 444 +++-- ibm_watson/text_to_speech_v1.py | 203 ++- test/unit/test_assistant_v1.py | 982 ++++------- test/unit/test_assistant_v2.py | 346 +--- test/unit/test_discovery_v1.py | 210 +-- test/unit/test_discovery_v2.py | 185 +-- test/unit/test_language_translator_v3.py | 4 +- .../test_natural_language_understanding_v1.py | 89 +- test/unit/test_speech_to_text_v1.py | 179 +- test/unit/test_text_to_speech_v1.py | 2 +- 16 files changed, 5023 insertions(+), 3104 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 939362250..6f52fcc8a 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -138,7 +138,7 @@ def message(self, :rtype: DetailedResponse with `dict` result representing a `MessageResponse` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if input is not None: input = convert_model(input) @@ -158,7 +158,7 @@ def message(self, params = { 'version': self.version, - 'nodes_visited_details': nodes_visited_details + 'nodes_visited_details': nodes_visited_details, } data = { @@ -168,7 +168,7 @@ def message(self, 'alternate_intents': alternate_intents, 'context': context, 'output': output, - 'user_id': user_id + 'user_id': user_id, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -217,7 +217,7 @@ def bulk_classify(self, :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if input is not None: input = [convert_model(x) for x in input] @@ -227,9 +227,13 @@ def bulk_classify(self, operation_id='bulk_classify') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input} + data = { + 'input': input, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -300,7 +304,7 @@ def list_workspaces(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -386,7 +390,10 @@ def create_workspace(self, operation_id='create_workspace') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'name': name, @@ -399,7 +406,7 @@ def create_workspace(self, 'system_settings': system_settings, 'webhooks': webhooks, 'intents': intents, - 'entities': entities + 'entities': entities, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -448,7 +455,7 @@ def get_workspace(self, :rtype: DetailedResponse with `dict` result representing a `Workspace` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -460,7 +467,7 @@ def get_workspace(self, 'version': self.version, 'export': export, 'include_audit': include_audit, - 'sort': sort + 'sort': sort, } if 'headers' in kwargs: @@ -543,7 +550,7 @@ def update_workspace(self, :rtype: DetailedResponse with `dict` result representing a `Workspace` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if dialog_nodes is not None: dialog_nodes = [convert_model(x) for x in dialog_nodes] @@ -566,7 +573,7 @@ def update_workspace(self, params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { @@ -580,7 +587,7 @@ def update_workspace(self, 'system_settings': system_settings, 'webhooks': webhooks, 'intents': intents, - 'entities': entities + 'entities': entities, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -616,7 +623,7 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -624,7 +631,9 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: operation_id='delete_workspace') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -712,7 +721,9 @@ def create_workspace_async( operation_id='create_workspace_async') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, @@ -725,7 +736,7 @@ def create_workspace_async( 'system_settings': system_settings, 'webhooks': webhooks, 'intents': intents, - 'entities': entities + 'entities': entities, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -809,7 +820,7 @@ def update_workspace_async( :rtype: DetailedResponse with `dict` result representing a `Workspace` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if dialog_nodes is not None: dialog_nodes = [convert_model(x) for x in dialog_nodes] @@ -829,7 +840,10 @@ def update_workspace_async( operation_id='update_workspace_async') headers.update(sdk_headers) - params = {'version': self.version, 'append': append} + params = { + 'version': self.version, + 'append': append, + } data = { 'name': name, @@ -842,7 +856,7 @@ def update_workspace_async( 'system_settings': system_settings, 'webhooks': webhooks, 'intents': intents, - 'entities': entities + 'entities': entities, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -898,7 +912,7 @@ def export_workspace_async(self, :rtype: DetailedResponse with `dict` result representing a `Workspace` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -910,7 +924,7 @@ def export_workspace_async(self, 'version': self.version, 'include_audit': include_audit, 'sort': sort, - 'verbose': verbose + 'verbose': verbose, } if 'headers' in kwargs: @@ -973,7 +987,7 @@ def list_intents(self, :rtype: DetailedResponse with `dict` result representing a `IntentCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -988,7 +1002,7 @@ def list_intents(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -1040,7 +1054,7 @@ def create_intent(self, :rtype: DetailedResponse with `dict` result representing a `Intent` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if intent is None: raise ValueError('intent must be provided') @@ -1052,12 +1066,15 @@ def create_intent(self, operation_id='create_intent') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'intent': intent, 'description': description, - 'examples': examples + 'examples': examples, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1106,9 +1123,9 @@ def get_intent(self, :rtype: DetailedResponse with `dict` result representing a `Intent` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1119,7 +1136,7 @@ def get_intent(self, params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -1185,9 +1202,9 @@ def update_intent(self, :rtype: DetailedResponse with `dict` result representing a `Intent` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') if new_examples is not None: new_examples = [convert_model(x) for x in new_examples] @@ -1200,13 +1217,13 @@ def update_intent(self, params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { 'intent': new_intent, 'description': new_description, - 'examples': new_examples + 'examples': new_examples, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1245,9 +1262,9 @@ def delete_intent(self, workspace_id: str, intent: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1255,7 +1272,9 @@ def delete_intent(self, workspace_id: str, intent: str, operation_id='delete_intent') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1315,9 +1334,9 @@ def list_examples(self, :rtype: DetailedResponse with `dict` result representing a `ExampleCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1331,7 +1350,7 @@ def list_examples(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -1382,9 +1401,9 @@ def create_example(self, :rtype: DetailedResponse with `dict` result representing a `Example` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') if text is None: raise ValueError('text must be provided') @@ -1396,9 +1415,15 @@ def create_example(self, operation_id='create_example') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': text, 'mentions': mentions} + data = { + 'text': text, + 'mentions': mentions, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -1444,11 +1469,11 @@ def get_example(self, :rtype: DetailedResponse with `dict` result representing a `Example` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1456,7 +1481,10 @@ def get_example(self, operation_id='get_example') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1508,11 +1536,11 @@ def update_example(self, :rtype: DetailedResponse with `dict` result representing a `Example` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') - if text is None: + if not text: raise ValueError('text must be provided') if new_mentions is not None: new_mentions = [convert_model(x) for x in new_mentions] @@ -1522,9 +1550,15 @@ def update_example(self, operation_id='update_example') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': new_text, 'mentions': new_mentions} + data = { + 'text': new_text, + 'mentions': new_mentions, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -1563,11 +1597,11 @@ def delete_example(self, workspace_id: str, intent: str, text: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if intent is None: + if not intent: raise ValueError('intent must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1575,7 +1609,9 @@ def delete_example(self, workspace_id: str, intent: str, text: str, operation_id='delete_example') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1633,7 +1669,7 @@ def list_counterexamples(self, :rtype: DetailedResponse with `dict` result representing a `CounterexampleCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1647,7 +1683,7 @@ def list_counterexamples(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -1694,7 +1730,7 @@ def create_counterexample(self, :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if text is None: raise ValueError('text must be provided') @@ -1704,9 +1740,14 @@ def create_counterexample(self, operation_id='create_counterexample') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': text} + data = { + 'text': text, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -1752,9 +1793,9 @@ def get_counterexample(self, :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1762,7 +1803,10 @@ def get_counterexample(self, operation_id='get_counterexample') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1809,9 +1853,9 @@ def update_counterexample(self, :rtype: DetailedResponse with `dict` result representing a `Counterexample` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1819,9 +1863,14 @@ def update_counterexample(self, operation_id='update_counterexample') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'text': new_text} + data = { + 'text': new_text, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -1861,9 +1910,9 @@ def delete_counterexample(self, workspace_id: str, text: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1871,7 +1920,9 @@ def delete_counterexample(self, workspace_id: str, text: str, operation_id='delete_counterexample') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1933,7 +1984,7 @@ def list_entities(self, :rtype: DetailedResponse with `dict` result representing a `EntityCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1948,7 +1999,7 @@ def list_entities(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -2007,7 +2058,7 @@ def create_entity(self, :rtype: DetailedResponse with `dict` result representing a `Entity` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if entity is None: raise ValueError('entity must be provided') @@ -2019,14 +2070,17 @@ def create_entity(self, operation_id='create_entity') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'entity': entity, 'description': description, 'metadata': metadata, 'fuzzy_match': fuzzy_match, - 'values': values + 'values': values, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2075,9 +2129,9 @@ def get_entity(self, :rtype: DetailedResponse with `dict` result representing a `Entity` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2088,7 +2142,7 @@ def get_entity(self, params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -2159,9 +2213,9 @@ def update_entity(self, :rtype: DetailedResponse with `dict` result representing a `Entity` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') if new_values is not None: new_values = [convert_model(x) for x in new_values] @@ -2174,7 +2228,7 @@ def update_entity(self, params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { @@ -2182,7 +2236,7 @@ def update_entity(self, 'description': new_description, 'metadata': new_metadata, 'fuzzy_match': new_fuzzy_match, - 'values': new_values + 'values': new_values, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2221,9 +2275,9 @@ def delete_entity(self, workspace_id: str, entity: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2231,7 +2285,9 @@ def delete_entity(self, workspace_id: str, entity: str, operation_id='delete_entity') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2281,9 +2337,9 @@ def list_mentions(self, :rtype: DetailedResponse with `dict` result representing a `EntityMentionCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2294,7 +2350,7 @@ def list_mentions(self, params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -2359,9 +2415,9 @@ def list_values(self, :rtype: DetailedResponse with `dict` result representing a `ValueCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2376,7 +2432,7 @@ def list_values(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -2441,9 +2497,9 @@ def create_value(self, :rtype: DetailedResponse with `dict` result representing a `Value` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') if value is None: raise ValueError('value must be provided') @@ -2453,14 +2509,17 @@ def create_value(self, operation_id='create_value') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'value': value, 'metadata': metadata, 'type': type, 'synonyms': synonyms, - 'patterns': patterns + 'patterns': patterns, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2512,11 +2571,11 @@ def get_value(self, :rtype: DetailedResponse with `dict` result representing a `Value` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2527,7 +2586,7 @@ def get_value(self, params = { 'version': self.version, 'export': export, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -2607,11 +2666,11 @@ def update_value(self, :rtype: DetailedResponse with `dict` result representing a `Value` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2622,7 +2681,7 @@ def update_value(self, params = { 'version': self.version, 'append': append, - 'include_audit': include_audit + 'include_audit': include_audit, } data = { @@ -2630,7 +2689,7 @@ def update_value(self, 'metadata': new_metadata, 'type': new_type, 'synonyms': new_synonyms, - 'patterns': new_patterns + 'patterns': new_patterns, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2670,11 +2729,11 @@ def delete_value(self, workspace_id: str, entity: str, value: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2682,7 +2741,9 @@ def delete_value(self, workspace_id: str, entity: str, value: str, operation_id='delete_value') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2743,11 +2804,11 @@ def list_synonyms(self, :rtype: DetailedResponse with `dict` result representing a `SynonymCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2761,7 +2822,7 @@ def list_synonyms(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -2812,11 +2873,11 @@ def create_synonym(self, :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') if synonym is None: raise ValueError('synonym must be provided') @@ -2826,9 +2887,14 @@ def create_synonym(self, operation_id='create_synonym') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'synonym': synonym} + data = { + 'synonym': synonym, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -2876,13 +2942,13 @@ def get_synonym(self, :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') - if synonym is None: + if not synonym: raise ValueError('synonym must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2890,7 +2956,10 @@ def get_synonym(self, operation_id='get_synonym') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2943,13 +3012,13 @@ def update_synonym(self, :rtype: DetailedResponse with `dict` result representing a `Synonym` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') - if synonym is None: + if not synonym: raise ValueError('synonym must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2957,9 +3026,14 @@ def update_synonym(self, operation_id='update_synonym') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'synonym': new_synonym} + data = { + 'synonym': new_synonym, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -3000,13 +3074,13 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if entity is None: + if not entity: raise ValueError('entity must be provided') - if value is None: + if not value: raise ValueError('value must be provided') - if synonym is None: + if not synonym: raise ValueError('synonym must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3014,7 +3088,9 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, operation_id='delete_synonym') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3072,7 +3148,7 @@ def list_dialog_nodes(self, :rtype: DetailedResponse with `dict` result representing a `DialogNodeCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3086,7 +3162,7 @@ def list_dialog_nodes(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -3196,7 +3272,7 @@ def create_dialog_node(self, :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') if dialog_node is None: raise ValueError('dialog_node must be provided') @@ -3214,7 +3290,10 @@ def create_dialog_node(self, operation_id='create_dialog_node') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'dialog_node': dialog_node, @@ -3235,7 +3314,7 @@ def create_dialog_node(self, 'digress_out': digress_out, 'digress_out_slots': digress_out_slots, 'user_label': user_label, - 'disambiguation_opt_out': disambiguation_opt_out + 'disambiguation_opt_out': disambiguation_opt_out, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -3281,9 +3360,9 @@ def get_dialog_node(self, :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if dialog_node is None: + if not dialog_node: raise ValueError('dialog_node must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3291,7 +3370,10 @@ def get_dialog_node(self, operation_id='get_dialog_node') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3405,9 +3487,9 @@ def update_dialog_node(self, :rtype: DetailedResponse with `dict` result representing a `DialogNode` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if dialog_node is None: + if not dialog_node: raise ValueError('dialog_node must be provided') if new_output is not None: new_output = convert_model(new_output) @@ -3423,7 +3505,10 @@ def update_dialog_node(self, operation_id='update_dialog_node') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } data = { 'dialog_node': new_dialog_node, @@ -3444,7 +3529,7 @@ def update_dialog_node(self, 'digress_out': new_digress_out, 'digress_out_slots': new_digress_out_slots, 'user_label': new_user_label, - 'disambiguation_opt_out': new_disambiguation_opt_out + 'disambiguation_opt_out': new_disambiguation_opt_out, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -3484,9 +3569,9 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, :rtype: DetailedResponse """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') - if dialog_node is None: + if not dialog_node: raise ValueError('dialog_node must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3494,7 +3579,9 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, operation_id='delete_dialog_node') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3552,7 +3639,7 @@ def list_logs(self, :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ - if workspace_id is None: + if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3565,7 +3652,7 @@ def list_logs(self, 'sort': sort, 'filter': filter, 'page_limit': page_limit, - 'cursor': cursor + 'cursor': cursor, } if 'headers' in kwargs: @@ -3621,7 +3708,7 @@ def list_all_logs(self, :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ - if filter is None: + if not filter: raise ValueError('filter must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3634,7 +3721,7 @@ def list_all_logs(self, 'filter': filter, 'sort': sort, 'page_limit': page_limit, - 'cursor': cursor + 'cursor': cursor, } if 'headers' in kwargs: @@ -3678,7 +3765,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3686,7 +3773,10 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: operation_id='delete_user_data') headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = { + 'version': self.version, + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3940,11 +4030,11 @@ def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] return cls(**args) @@ -3957,11 +4047,26 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list return _dict def _to_dict(self): @@ -4006,7 +4111,7 @@ def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': args = {} if 'output' in _dict: args['output'] = [ - BulkClassifyOutput.from_dict(x) for x in _dict.get('output') + BulkClassifyOutput.from_dict(v) for v in _dict.get('output') ] return cls(**args) @@ -4019,7 +4124,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'output') and self.output is not None: - _dict['output'] = [x.to_dict() for x in self.output] + output_list = [] + for v in self.output: + if isinstance(v, dict): + output_list.append(v) + else: + output_list.append(v.to_dict()) + _dict['output'] = output_list return _dict def _to_dict(self): @@ -4209,7 +4320,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target.to_dict() + if isinstance(self.target, dict): + _dict['target'] = self.target + else: + _dict['target'] = self.target.to_dict() return _dict def _to_dict(self): @@ -4268,7 +4382,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'chat') and self.chat is not None: - _dict['chat'] = self.chat.to_dict() + if isinstance(self.chat, dict): + _dict['chat'] = self.chat + else: + _dict['chat'] = self.chat.to_dict() return _dict def _to_dict(self): @@ -4409,12 +4526,14 @@ def to_dict(self) -> Dict: if hasattr(self, 'system') and self.system is not None: _dict['system'] = self.system if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata.to_dict() + if isinstance(self.metadata, dict): + _dict['metadata'] = self.metadata + else: + _dict['metadata'] = self.metadata.to_dict() for _key in [ k for k in vars(self).keys() if k not in Context._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -4564,8 +4683,8 @@ def from_dict(cls, _dict: Dict) -> 'CounterexampleCollection': args = {} if 'counterexamples' in _dict: args['counterexamples'] = [ - Counterexample.from_dict(x) - for x in _dict.get('counterexamples') + Counterexample.from_dict(v) + for v in _dict.get('counterexamples') ] else: raise ValueError( @@ -4589,11 +4708,18 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'counterexamples') and self.counterexamples is not None: - _dict['counterexamples'] = [ - x.to_dict() for x in self.counterexamples - ] + counterexamples_list = [] + for v in self.counterexamples: + if isinstance(v, dict): + counterexamples_list.append(v) + else: + counterexamples_list.append(v.to_dict()) + _dict['counterexamples'] = counterexamples_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -4692,7 +4818,7 @@ def from_dict(cls, _dict: Dict) -> 'CreateEntity': args['updated'] = string_to_datetime(_dict.get('updated')) if 'values' in _dict: args['values'] = [ - CreateValue.from_dict(x) for x in _dict.get('values') + CreateValue.from_dict(v) for v in _dict.get('values') ] return cls(**args) @@ -4717,7 +4843,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list return _dict def _to_dict(self): @@ -4800,7 +4932,7 @@ def from_dict(cls, _dict: Dict) -> 'CreateIntent': args['updated'] = string_to_datetime(_dict.get('updated')) if 'examples' in _dict: args['examples'] = [ - Example.from_dict(x) for x in _dict.get('examples') + Example.from_dict(v) for v in _dict.get('examples') ] return cls(**args) @@ -4821,7 +4953,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list return _dict def _to_dict(self): @@ -5174,7 +5312,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogNode': args['variable'] = _dict.get('variable') if 'actions' in _dict: args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') + DialogNodeAction.from_dict(v) for v in _dict.get('actions') ] if 'digress_in' in _dict: args['digress_in'] = _dict.get('digress_in') @@ -5214,13 +5352,22 @@ def to_dict(self) -> Dict: 'previous_sibling') and self.previous_sibling is not None: _dict['previous_sibling'] = self.previous_sibling if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'next_step') and self.next_step is not None: - _dict['next_step'] = self.next_step.to_dict() + if isinstance(self.next_step, dict): + _dict['next_step'] = self.next_step + else: + _dict['next_step'] = self.next_step.to_dict() if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'type') and self.type is not None: @@ -5230,7 +5377,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'variable') and self.variable is not None: _dict['variable'] = self.variable if hasattr(self, 'actions') and self.actions is not None: - _dict['actions'] = [x.to_dict() for x in self.actions] + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list if hasattr(self, 'digress_in') and self.digress_in is not None: _dict['digress_in'] = self.digress_in if hasattr(self, 'digress_out') and self.digress_out is not None: @@ -5459,7 +5612,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeCollection': args = {} if 'dialog_nodes' in _dict: args['dialog_nodes'] = [ - DialogNode.from_dict(x) for x in _dict.get('dialog_nodes') + DialogNode.from_dict(v) for v in _dict.get('dialog_nodes') ] else: raise ValueError( @@ -5482,9 +5635,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: - _dict['dialog_nodes'] = [x.to_dict() for x in self.dialog_nodes] + dialog_nodes_list = [] + for v in self.dialog_nodes: + if isinstance(v, dict): + dialog_nodes_list.append(v) + else: + dialog_nodes_list.append(v.to_dict()) + _dict['dialog_nodes'] = dialog_nodes_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -5553,8 +5715,7 @@ def to_dict(self) -> Dict: k for k in vars(self).keys() if k not in DialogNodeContext._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -5806,8 +5967,8 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': args = {} if 'generic' in _dict: args['generic'] = [ - DialogNodeOutputGeneric.from_dict(x) - for x in _dict.get('generic') + DialogNodeOutputGeneric.from_dict(v) + for v in _dict.get('generic') ] if 'integrations' in _dict: args['integrations'] = _dict.get('integrations') @@ -5827,17 +5988,25 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x.to_dict() for x in self.generic] + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations if hasattr(self, 'modifiers') and self.modifiers is not None: - _dict['modifiers'] = self.modifiers.to_dict() + if isinstance(self.modifiers, dict): + _dict['modifiers'] = self.modifiers + else: + _dict['modifiers'] = self.modifiers.to_dict() for _key in [ k for k in vars(self).keys() if k not in DialogNodeOutput._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -6148,7 +6317,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value.to_dict() + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() return _dict def _to_dict(self): @@ -6218,11 +6390,11 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': args['input'] = MessageInput.from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] return cls(**args) @@ -6235,11 +6407,26 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list return _dict def _to_dict(self): @@ -6470,7 +6657,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value.to_dict() + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output if hasattr(self, 'dialog_node') and self.dialog_node is not None: @@ -6536,11 +6726,11 @@ def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': args['input'] = MessageInput.from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] return cls(**args) @@ -6553,11 +6743,26 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list return _dict def _to_dict(self): @@ -6655,7 +6860,7 @@ def from_dict(cls, _dict: Dict) -> 'Entity': if 'updated' in _dict: args['updated'] = string_to_datetime(_dict.get('updated')) if 'values' in _dict: - args['values'] = [Value.from_dict(x) for x in _dict.get('values')] + args['values'] = [Value.from_dict(v) for v in _dict.get('values')] return cls(**args) @classmethod @@ -6679,7 +6884,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list return _dict def _to_dict(self): @@ -6728,7 +6939,7 @@ def from_dict(cls, _dict: Dict) -> 'EntityCollection': args = {} if 'entities' in _dict: args['entities'] = [ - Entity.from_dict(x) for x in _dict.get('entities') + Entity.from_dict(v) for v in _dict.get('entities') ] else: raise ValueError( @@ -6751,9 +6962,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6883,7 +7103,7 @@ def from_dict(cls, _dict: Dict) -> 'EntityMentionCollection': args = {} if 'examples' in _dict: args['examples'] = [ - EntityMention.from_dict(x) for x in _dict.get('examples') + EntityMention.from_dict(v) for v in _dict.get('examples') ] else: raise ValueError( @@ -6906,9 +7126,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6976,7 +7205,7 @@ def from_dict(cls, _dict: Dict) -> 'Example': 'Required property \'text\' not present in Example JSON') if 'mentions' in _dict: args['mentions'] = [ - Mention.from_dict(x) for x in _dict.get('mentions') + Mention.from_dict(v) for v in _dict.get('mentions') ] if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) @@ -6995,7 +7224,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = [x.to_dict() for x in self.mentions] + mentions_list = [] + for v in self.mentions: + if isinstance(v, dict): + mentions_list.append(v) + else: + mentions_list.append(v.to_dict()) + _dict['mentions'] = mentions_list if hasattr(self, 'created') and getattr(self, 'created') is not None: _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'updated') and getattr(self, 'updated') is not None: @@ -7048,7 +7283,7 @@ def from_dict(cls, _dict: Dict) -> 'ExampleCollection': args = {} if 'examples' in _dict: args['examples'] = [ - Example.from_dict(x) for x in _dict.get('examples') + Example.from_dict(v) for v in _dict.get('examples') ] else: raise ValueError( @@ -7071,9 +7306,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -7156,7 +7400,7 @@ def from_dict(cls, _dict: Dict) -> 'Intent': args['updated'] = string_to_datetime(_dict.get('updated')) if 'examples' in _dict: args['examples'] = [ - Example.from_dict(x) for x in _dict.get('examples') + Example.from_dict(v) for v in _dict.get('examples') ] return cls(**args) @@ -7177,7 +7421,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list return _dict def _to_dict(self): @@ -7226,7 +7476,7 @@ def from_dict(cls, _dict: Dict) -> 'IntentCollection': args = {} if 'intents' in _dict: args['intents'] = [ - Intent.from_dict(x) for x in _dict.get('intents') + Intent.from_dict(v) for v in _dict.get('intents') ] else: raise ValueError( @@ -7249,9 +7499,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -7370,9 +7629,15 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'request') and self.request is not None: - _dict['request'] = self.request.to_dict() + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() if hasattr(self, 'response') and self.response is not None: - _dict['response'] = self.response.to_dict() + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() if hasattr(self, 'log_id') and self.log_id is not None: _dict['log_id'] = self.log_id if hasattr(self, @@ -7431,7 +7696,7 @@ def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} if 'logs' in _dict: - args['logs'] = [Log.from_dict(x) for x in _dict.get('logs')] + args['logs'] = [Log.from_dict(v) for v in _dict.get('logs')] else: raise ValueError( 'Required property \'logs\' not present in LogCollection JSON') @@ -7453,9 +7718,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'logs') and self.logs is not None: - _dict['logs'] = [x.to_dict() for x in self.logs] + logs_list = [] + for v in self.logs: + if isinstance(v, dict): + logs_list.append(v) + else: + logs_list.append(v.to_dict()) + _dict['logs'] = logs_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -7548,7 +7822,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'code') and self.code is not None: _dict['code'] = self.code if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() return _dict def _to_dict(self): @@ -7985,8 +8262,7 @@ def to_dict(self) -> Dict: k for k in vars(self).keys() if k not in MessageInput._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -8121,11 +8397,11 @@ def from_dict(cls, _dict: Dict) -> 'MessageRequest': args['input'] = MessageInput.from_dict(_dict.get('input')) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] if 'alternate_intents' in _dict: args['alternate_intents'] = _dict.get('alternate_intents') @@ -8135,7 +8411,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageRequest': args['output'] = OutputData.from_dict(_dict.get('output')) if 'actions' in _dict: args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') + DialogNodeAction.from_dict(v) for v in _dict.get('actions') ] if 'user_id' in _dict: args['user_id'] = _dict.get('user_id') @@ -8150,20 +8426,47 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() if hasattr(self, 'actions') and getattr(self, 'actions') is not None: - _dict['actions'] = [x.to_dict() for x in getattr(self, 'actions')] + actions_list = [] + for v in getattr(self, 'actions'): + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id return _dict @@ -8273,7 +8576,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageResponse': ) if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] else: raise ValueError( @@ -8281,7 +8584,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageResponse': ) if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] else: raise ValueError( @@ -8303,7 +8606,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageResponse': ) if 'actions' in _dict: args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') + DialogNodeAction.from_dict(v) for v in _dict.get('actions') ] if 'user_id' in _dict: args['user_id'] = _dict.get('user_id') @@ -8322,20 +8625,47 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() if hasattr(self, 'actions') and getattr(self, 'actions') is not None: - _dict['actions'] = [x.to_dict() for x in getattr(self, 'actions')] + actions_list = [] + for v in getattr(self, 'actions'): + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id return _dict @@ -8423,12 +8753,12 @@ def from_dict(cls, _dict: Dict) -> 'OutputData': args['nodes_visited'] = _dict.get('nodes_visited') if 'nodes_visited_details' in _dict: args['nodes_visited_details'] = [ - DialogNodeVisitedDetails.from_dict(x) - for x in _dict.get('nodes_visited_details') + DialogNodeVisitedDetails.from_dict(v) + for v in _dict.get('nodes_visited_details') ] if 'log_messages' in _dict: args['log_messages'] = [ - LogMessage.from_dict(x) for x in _dict.get('log_messages') + LogMessage.from_dict(v) for v in _dict.get('log_messages') ] else: raise ValueError( @@ -8436,8 +8766,8 @@ def from_dict(cls, _dict: Dict) -> 'OutputData': ) if 'generic' in _dict: args['generic'] = [ - RuntimeResponseGeneric.from_dict(x) - for x in _dict.get('generic') + RuntimeResponseGeneric.from_dict(v) + for v in _dict.get('generic') ] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) @@ -8455,18 +8785,33 @@ def to_dict(self) -> Dict: _dict['nodes_visited'] = self.nodes_visited if hasattr(self, 'nodes_visited_details' ) and self.nodes_visited_details is not None: - _dict['nodes_visited_details'] = [ - x.to_dict() for x in self.nodes_visited_details - ] + nodes_visited_details_list = [] + for v in self.nodes_visited_details: + if isinstance(v, dict): + nodes_visited_details_list.append(v) + else: + nodes_visited_details_list.append(v.to_dict()) + _dict['nodes_visited_details'] = nodes_visited_details_list if hasattr(self, 'log_messages') and self.log_messages is not None: - _dict['log_messages'] = [x.to_dict() for x in self.log_messages] + log_messages_list = [] + for v in self.log_messages: + if isinstance(v, dict): + log_messages_list.append(v) + else: + log_messages_list.append(v.to_dict()) + _dict['log_messages'] = log_messages_list if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x.to_dict() for x in self.generic] + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list for _key in [ k for k in vars(self).keys() if k not in OutputData._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -8782,15 +9127,15 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': args['confidence'] = _dict.get('confidence') if 'groups' in _dict: args['groups'] = [ - CaptureGroup.from_dict(x) for x in _dict.get('groups') + CaptureGroup.from_dict(v) for v 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') + RuntimeEntityAlternative.from_dict(v) + for v in _dict.get('alternatives') ] if 'role' in _dict: args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) @@ -8813,13 +9158,31 @@ def to_dict(self) -> Dict: if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'groups') and self.groups is not None: - _dict['groups'] = [x.to_dict() for x in self.groups] + groups_list = [] + for v in self.groups: + if isinstance(v, dict): + groups_list.append(v) + else: + groups_list.append(v.to_dict()) + _dict['groups'] = groups_list if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation.to_dict() + if isinstance(self.interpretation, dict): + _dict['interpretation'] = self.interpretation + else: + _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] + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list if hasattr(self, 'role') and self.role is not None: - _dict['role'] = self.role.to_dict() + if isinstance(self.role, dict): + _dict['role'] = self.role + else: + _dict['role'] = self.role.to_dict() return _dict def _to_dict(self): @@ -9661,7 +10024,7 @@ def from_dict(cls, _dict: Dict) -> 'SynonymCollection': args = {} if 'synonyms' in _dict: args['synonyms'] = [ - Synonym.from_dict(x) for x in _dict.get('synonyms') + Synonym.from_dict(v) for v in _dict.get('synonyms') ] else: raise ValueError( @@ -9684,9 +10047,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'synonyms') and self.synonyms is not None: - _dict['synonyms'] = [x.to_dict() for x in self.synonyms] + synonyms_list = [] + for v in self.synonyms: + if isinstance(v, dict): + synonyms_list.append(v) + else: + synonyms_list.append(v.to_dict()) + _dict['synonyms'] = synonyms_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -9870,7 +10242,7 @@ def from_dict(cls, _dict: Dict) -> 'ValueCollection': """Initialize a ValueCollection object from a json dictionary.""" args = {} if 'values' in _dict: - args['values'] = [Value.from_dict(x) for x in _dict.get('values')] + args['values'] = [Value.from_dict(v) for v in _dict.get('values')] else: raise ValueError( 'Required property \'values\' not present in ValueCollection JSON' @@ -9892,9 +10264,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -9965,7 +10346,7 @@ def from_dict(cls, _dict: Dict) -> 'Webhook': 'Required property \'name\' not present in Webhook JSON') if 'headers' in _dict: args['headers_'] = [ - WebhookHeader.from_dict(x) for x in _dict.get('headers') + WebhookHeader.from_dict(v) for v in _dict.get('headers') ] return cls(**args) @@ -9982,7 +10363,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'headers_') and self.headers_ is not None: - _dict['headers'] = [x.to_dict() for x in self.headers_] + headers_list = [] + for v in self.headers_: + if isinstance(v, dict): + headers_list.append(v) + else: + headers_list.append(v.to_dict()) + _dict['headers'] = headers_list return _dict def _to_dict(self): @@ -10159,11 +10546,6 @@ def __init__(self, :param List[Intent] intents: (optional) An array of intents. :param List[Entity] entities: (optional) An array of objects describing the entities for the workspace. - :param WorkspaceCounts counts: (optional) An object containing properties - that indicate how many intents, entities, and dialog nodes are defined in - the workspace. This property is included only in responses from the - **Export workspace asynchronously** method, and only when the **verbose** - query parameter is set to `true`. """ self.name = name self.description = description @@ -10203,12 +10585,12 @@ def from_dict(cls, _dict: Dict) -> 'Workspace': args['workspace_id'] = _dict.get('workspace_id') if 'dialog_nodes' in _dict: args['dialog_nodes'] = [ - DialogNode.from_dict(x) for x in _dict.get('dialog_nodes') + DialogNode.from_dict(v) for v in _dict.get('dialog_nodes') ] if 'counterexamples' in _dict: args['counterexamples'] = [ - Counterexample.from_dict(x) - for x in _dict.get('counterexamples') + Counterexample.from_dict(v) + for v in _dict.get('counterexamples') ] if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) @@ -10229,19 +10611,19 @@ def from_dict(cls, _dict: Dict) -> 'Workspace': args['status'] = _dict.get('status') if 'status_errors' in _dict: args['status_errors'] = [ - StatusError.from_dict(x) for x in _dict.get('status_errors') + StatusError.from_dict(v) for v in _dict.get('status_errors') ] if 'webhooks' in _dict: args['webhooks'] = [ - Webhook.from_dict(x) for x in _dict.get('webhooks') + Webhook.from_dict(v) for v in _dict.get('webhooks') ] if 'intents' in _dict: args['intents'] = [ - Intent.from_dict(x) for x in _dict.get('intents') + Intent.from_dict(v) for v in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - Entity.from_dict(x) for x in _dict.get('entities') + Entity.from_dict(v) for v in _dict.get('entities') ] if 'counts' in _dict: args['counts'] = WorkspaceCounts.from_dict(_dict.get('counts')) @@ -10265,12 +10647,22 @@ def to_dict(self) -> Dict: self, 'workspace_id') is not None: _dict['workspace_id'] = getattr(self, 'workspace_id') if hasattr(self, 'dialog_nodes') and self.dialog_nodes is not None: - _dict['dialog_nodes'] = [x.to_dict() for x in self.dialog_nodes] + dialog_nodes_list = [] + for v in self.dialog_nodes: + if isinstance(v, dict): + dialog_nodes_list.append(v) + else: + dialog_nodes_list.append(v.to_dict()) + _dict['dialog_nodes'] = dialog_nodes_list if hasattr(self, 'counterexamples') and self.counterexamples is not None: - _dict['counterexamples'] = [ - x.to_dict() for x in self.counterexamples - ] + counterexamples_list = [] + for v in self.counterexamples: + if isinstance(v, dict): + counterexamples_list.append(v) + else: + counterexamples_list.append(v.to_dict()) + _dict['counterexamples'] = counterexamples_list if hasattr(self, 'created') and getattr(self, 'created') is not None: _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'updated') and getattr(self, 'updated') is not None: @@ -10282,22 +10674,50 @@ def to_dict(self) -> Dict: _dict['learning_opt_out'] = self.learning_opt_out if hasattr(self, 'system_settings') and self.system_settings is not None: - _dict['system_settings'] = self.system_settings.to_dict() + if isinstance(self.system_settings, dict): + _dict['system_settings'] = self.system_settings + else: + _dict['system_settings'] = self.system_settings.to_dict() if hasattr(self, 'status') and getattr(self, 'status') is not None: _dict['status'] = getattr(self, 'status') if hasattr(self, 'status_errors') and getattr( self, 'status_errors') is not None: - _dict['status_errors'] = [ - x.to_dict() for x in getattr(self, 'status_errors') - ] + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list if hasattr(self, 'webhooks') and self.webhooks is not None: - _dict['webhooks'] = [x.to_dict() for x in self.webhooks] + webhooks_list = [] + for v in self.webhooks: + if isinstance(v, dict): + webhooks_list.append(v) + else: + webhooks_list.append(v.to_dict()) + _dict['webhooks'] = webhooks_list if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] - if hasattr(self, 'counts') and self.counts is not None: - _dict['counts'] = self.counts.to_dict() + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'counts') and getattr(self, 'counts') is not None: + if isinstance(getattr(self, 'counts'), dict): + _dict['counts'] = getattr(self, 'counts') + else: + _dict['counts'] = getattr(self, 'counts').to_dict() return _dict def _to_dict(self): @@ -10366,7 +10786,7 @@ def from_dict(cls, _dict: Dict) -> 'WorkspaceCollection': args = {} if 'workspaces' in _dict: args['workspaces'] = [ - Workspace.from_dict(x) for x in _dict.get('workspaces') + Workspace.from_dict(v) for v in _dict.get('workspaces') ] else: raise ValueError( @@ -10389,9 +10809,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'workspaces') and self.workspaces is not None: - _dict['workspaces'] = [x.to_dict() for x in self.workspaces] + workspaces_list = [] + for v in self.workspaces: + if isinstance(v, dict): + workspaces_list.append(v) + else: + workspaces_list.append(v.to_dict()) + _dict['workspaces'] = workspaces_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -10610,9 +11039,15 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tooling') and self.tooling is not None: - _dict['tooling'] = self.tooling.to_dict() + if isinstance(self.tooling, dict): + _dict['tooling'] = self.tooling + else: + _dict['tooling'] = self.tooling.to_dict() if hasattr(self, 'disambiguation') and self.disambiguation is not None: - _dict['disambiguation'] = self.disambiguation.to_dict() + if isinstance(self.disambiguation, dict): + _dict['disambiguation'] = self.disambiguation + else: + _dict['disambiguation'] = self.disambiguation.to_dict() if hasattr( self, 'human_agent_assist') and self.human_agent_assist is not None: @@ -10625,17 +11060,25 @@ def to_dict(self) -> Dict: _dict['spelling_auto_correct'] = self.spelling_auto_correct if hasattr(self, 'system_entities') and self.system_entities is not None: - _dict['system_entities'] = self.system_entities.to_dict() + if isinstance(self.system_entities, dict): + _dict['system_entities'] = self.system_entities + else: + _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() + if isinstance(self.off_topic, dict): + _dict['off_topic'] = self.off_topic + else: + _dict['off_topic'] = self.off_topic.to_dict() if hasattr(self, 'nlp') and self.nlp is not None: - _dict['nlp'] = self.nlp.to_dict() + if isinstance(self.nlp, dict): + _dict['nlp'] = self.nlp + else: + _dict['nlp'] = self.nlp.to_dict() for _key in [ k for k in vars(self).keys() if k not in WorkspaceSystemSettings._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -11074,7 +11517,7 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio( specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -11086,7 +11529,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio object. @@ -11102,7 +11545,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -11139,8 +11582,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -11165,7 +11608,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -11263,8 +11712,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -11282,9 +11731,18 @@ def to_dict(self) -> Dict: 'message_to_user') and self.message_to_user is not None: _dict['message_to_user'] = self.message_to_user if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11397,8 +11855,8 @@ def from_dict( _dict.get('transfer_info')) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -11417,14 +11875,29 @@ def to_dict(self) -> Dict: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available.to_dict() + if isinstance(self.agent_available, dict): + _dict['agent_available'] = self.agent_available + else: + _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable.to_dict() + if isinstance(self.agent_unavailable, dict): + _dict['agent_unavailable'] = self.agent_unavailable + else: + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11530,8 +12003,8 @@ def from_dict( args['image_url'] = _dict.get('image_url') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -11554,7 +12027,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image_url') and self.image_url is not None: _dict['image_url'] = self.image_url if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11652,8 +12131,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'alt_text' in _dict: args['alt_text'] = _dict.get('alt_text') @@ -11676,7 +12155,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'alt_text') and self.alt_text is not None: _dict['alt_text'] = self.alt_text return _dict @@ -11780,8 +12265,8 @@ def from_dict( args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(x) - for x in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) + for v in _dict.get('options') ] else: raise ValueError( @@ -11789,8 +12274,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -11811,9 +12296,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x.to_dict() for x in self.options] + options_list = [] + for v in self.options: + if isinstance(v, dict): + options_list.append(v) + else: + options_list.append(v.to_dict()) + _dict['options'] = options_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -11908,8 +12405,8 @@ def from_dict( args['typing'] = _dict.get('typing') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -11928,7 +12425,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12047,8 +12550,8 @@ def from_dict( args['discovery_version'] = _dict.get('discovery_version') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12072,7 +12575,13 @@ def to_dict(self) -> Dict: 'discovery_version') and self.discovery_version is not None: _dict['discovery_version'] = self.discovery_version if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12167,8 +12676,8 @@ def from_dict( ) if 'values' in _dict: args['values'] = [ - DialogNodeOutputTextValuesElement.from_dict(x) - for x in _dict.get('values') + DialogNodeOutputTextValuesElement.from_dict(v) + for v in _dict.get('values') ] else: raise ValueError( @@ -12180,8 +12689,8 @@ def from_dict( args['delimiter'] = _dict.get('delimiter') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12196,14 +12705,26 @@ def to_dict(self) -> Dict: if hasattr(self, 'response_type') and self.response_type is not None: _dict['response_type'] = self.response_type if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] + values_list = [] + for v in self.values: + if isinstance(v, dict): + values_list.append(v) + else: + values_list.append(v.to_dict()) + _dict['values'] = values_list if hasattr(self, 'selection_policy') and self.selection_policy is not None: _dict['selection_policy'] = self.selection_policy if hasattr(self, 'delimiter') and self.delimiter is not None: _dict['delimiter'] = self.delimiter if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12293,8 +12814,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12311,7 +12832,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12354,7 +12881,7 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo( specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -12366,7 +12893,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo object. @@ -12382,7 +12909,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -12419,8 +12946,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -12445,7 +12972,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -12490,7 +13023,7 @@ class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -12502,7 +13035,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. @@ -12519,7 +13052,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -12556,8 +13089,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -12582,7 +13115,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -12682,8 +13221,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12701,9 +13240,18 @@ def to_dict(self) -> Dict: 'message_to_user') and self.message_to_user is not None: _dict['message_to_user'] = self.message_to_user if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12838,8 +13386,8 @@ def from_dict( args['dialog_node'] = _dict.get('dialog_node') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12858,18 +13406,33 @@ def to_dict(self) -> Dict: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available.to_dict() + if isinstance(self.agent_available, dict): + _dict['agent_available'] = self.agent_available + else: + _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable.to_dict() + if isinstance(self.agent_unavailable, dict): + _dict['agent_unavailable'] = self.agent_unavailable + else: + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'topic') and self.topic is not None: _dict['topic'] = self.topic if hasattr(self, 'dialog_node') and self.dialog_node is not None: _dict['dialog_node'] = self.dialog_node if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -12973,8 +13536,8 @@ def from_dict( args['image_url'] = _dict.get('image_url') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -12997,7 +13560,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image_url') and self.image_url is not None: _dict['image_url'] = self.image_url if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -13099,8 +13668,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'alt_text' in _dict: args['alt_text'] = _dict.get('alt_text') @@ -13123,7 +13692,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'alt_text') and self.alt_text is not None: _dict['alt_text'] = self.alt_text return _dict @@ -13224,8 +13799,8 @@ def from_dict( args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(x) - for x in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) + for v in _dict.get('options') ] else: raise ValueError( @@ -13233,8 +13808,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -13255,9 +13830,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x.to_dict() for x in self.options] + options_list = [] + for v in self.options: + if isinstance(v, dict): + options_list.append(v) + else: + options_list.append(v.to_dict()) + _dict['options'] = options_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -13353,8 +13940,8 @@ def from_dict( args['typing'] = _dict.get('typing') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -13373,7 +13960,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -13460,7 +14053,7 @@ def from_dict( ) if 'suggestions' in _dict: args['suggestions'] = [ - DialogSuggestion.from_dict(x) for x in _dict.get('suggestions') + DialogSuggestion.from_dict(v) for v in _dict.get('suggestions') ] else: raise ValueError( @@ -13468,8 +14061,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -13486,9 +14079,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x.to_dict() for x in self.suggestions] + suggestions_list = [] + for v in self.suggestions: + if isinstance(v, dict): + suggestions_list.append(v) + else: + suggestions_list.append(v.to_dict()) + _dict['suggestions'] = suggestions_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -13569,8 +14174,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -13587,7 +14192,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -13669,8 +14280,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -13687,7 +14298,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -13727,7 +14344,7 @@ class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -13739,7 +14356,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. @@ -13756,7 +14373,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -13793,8 +14410,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -13819,7 +14436,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 027b9b3af..940eb8bd4 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -97,12 +97,13 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: assistants, see the [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 request_body: (optional) :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SessionResponse` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -110,7 +111,9 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: operation_id='create_session') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = {} data = {k: v for (k, v) in data.items() if v is not None} @@ -156,9 +159,9 @@ def delete_session(self, assistant_id: str, session_id: str, :rtype: DetailedResponse """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') - if session_id is None: + if not session_id: raise ValueError('session_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -166,7 +169,9 @@ def delete_session(self, assistant_id: str, session_id: str, operation_id='delete_session') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -235,9 +240,9 @@ def message(self, :rtype: DetailedResponse with `dict` result representing a `MessageResponse` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') - if session_id is None: + if not session_id: raise ValueError('session_id must be provided') if input is not None: input = convert_model(input) @@ -249,9 +254,15 @@ def message(self, operation_id='message') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input, 'context': context, 'user_id': user_id} + data = { + 'input': input, + 'context': context, + 'user_id': user_id, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -318,7 +329,7 @@ def message_stateless(self, :rtype: DetailedResponse with `dict` result representing a `MessageResponseStateless` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') if input is not None: input = convert_model(input) @@ -330,9 +341,15 @@ def message_stateless(self, operation_id='message_stateless') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input, 'context': context, 'user_id': user_id} + data = { + 'input': input, + 'context': context, + 'user_id': user_id, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -380,7 +397,7 @@ def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object """ - if skill_id is None: + if not skill_id: raise ValueError('skill_id must be provided') if input is None: raise ValueError('input must be provided') @@ -391,9 +408,13 @@ def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], operation_id='bulk_classify') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'input': input} + data = { + 'input': input, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -460,7 +481,7 @@ def list_logs(self, :rtype: DetailedResponse with `dict` result representing a `LogCollection` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -473,7 +494,7 @@ def list_logs(self, 'sort': sort, 'filter': filter, 'page_limit': page_limit, - 'cursor': cursor + 'cursor': cursor, } if 'headers' in kwargs: @@ -520,7 +541,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -528,7 +549,10 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: operation_id='delete_user_data') headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = { + 'version': self.version, + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -586,7 +610,7 @@ def list_environments(self, :rtype: DetailedResponse with `dict` result representing a `EnvironmentCollection` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -600,7 +624,7 @@ def list_environments(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -650,9 +674,9 @@ def get_environment(self, :rtype: DetailedResponse with `dict` result representing a `Environment` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -660,7 +684,10 @@ def get_environment(self, operation_id='get_environment') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -723,7 +750,7 @@ def list_releases(self, :rtype: DetailedResponse with `dict` result representing a `ReleaseCollection` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -737,7 +764,7 @@ def list_releases(self, 'include_count': include_count, 'sort': sort, 'cursor': cursor, - 'include_audit': include_audit + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -786,9 +813,9 @@ def get_release(self, :rtype: DetailedResponse with `dict` result representing a `Release` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') - if release is None: + if not release: raise ValueError('release must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -796,7 +823,10 @@ def get_release(self, operation_id='get_release') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -845,9 +875,9 @@ def deploy_release(self, :rtype: DetailedResponse with `dict` result representing a `Environment` object """ - if assistant_id is None: + if not assistant_id: raise ValueError('assistant_id must be provided') - if release is None: + if not release: raise ValueError('release must be provided') if environment_id is None: raise ValueError('environment_id must be provided') @@ -857,9 +887,14 @@ def deploy_release(self, operation_id='deploy_release') headers.update(sdk_headers) - params = {'version': self.version, 'include_audit': include_audit} + params = { + 'version': self.version, + 'include_audit': include_audit, + } - data = {'environment_id': environment_id} + data = { + 'environment_id': environment_id, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -1010,11 +1045,11 @@ def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] return cls(**args) @@ -1027,11 +1062,26 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list return _dict def _to_dict(self): @@ -1076,7 +1126,7 @@ def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': args = {} if 'output' in _dict: args['output'] = [ - BulkClassifyOutput.from_dict(x) for x in _dict.get('output') + BulkClassifyOutput.from_dict(v) for v in _dict.get('output') ] return cls(**args) @@ -1089,7 +1139,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'output') and self.output is not None: - _dict['output'] = [x.to_dict() for x in self.output] + output_list = [] + for v in self.output: + if isinstance(v, dict): + output_list.append(v) + else: + output_list.append(v.to_dict()) + _dict['output'] = output_list return _dict def _to_dict(self): @@ -1279,7 +1335,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target.to_dict() + if isinstance(self.target, dict): + _dict['target'] = self.target + else: + _dict['target'] = self.target.to_dict() return _dict def _to_dict(self): @@ -1338,7 +1397,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'chat') and self.chat is not None: - _dict['chat'] = self.chat.to_dict() + if isinstance(self.chat, dict): + _dict['chat'] = self.chat + else: + _dict['chat'] = self.chat.to_dict() return _dict def _to_dict(self): @@ -1488,7 +1550,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'code') and self.code is not None: _dict['code'] = self.code if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() return _dict def _to_dict(self): @@ -1739,7 +1804,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value.to_dict() + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() return _dict def _to_dict(self): @@ -1796,7 +1864,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() return _dict def _to_dict(self): @@ -1960,7 +2031,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'label') and self.label is not None: _dict['label'] = self.label if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value.to_dict() + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() if hasattr(self, 'output') and self.output is not None: _dict['output'] = self.output return _dict @@ -2019,7 +2093,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() return _dict def _to_dict(self): @@ -2093,10 +2170,6 @@ def __init__(self, :param str language: (optional) The language of the environment. An environment is always created with the same language as the assistant it is associated with. - :param EnvironmentReleaseReference release_reference: (optional) An object - describing the release that is currently deployed in the environment. - :param EnvironmentOrchestration orchestration: (optional) The search skill - orchestration settings for the environment. :param int session_timeout: (optional) The session inactivity timeout setting for the environment. :param List[IntegrationReference] integration_references: (optional) An @@ -2145,13 +2218,13 @@ def from_dict(cls, _dict: Dict) -> 'Environment': args['session_timeout'] = _dict.get('session_timeout') if 'integration_references' in _dict: args['integration_references'] = [ - IntegrationReference.from_dict(x) - for x in _dict.get('integration_references') + IntegrationReference.from_dict(v) + for v in _dict.get('integration_references') ] if 'skill_references' in _dict: args['skill_references'] = [ - SkillReference.from_dict(x) - for x in _dict.get('skill_references') + SkillReference.from_dict(v) + for v in _dict.get('skill_references') ] if 'created' in _dict: args['created'] = string_to_datetime(_dict.get('created')) @@ -2182,24 +2255,41 @@ def to_dict(self) -> Dict: if hasattr(self, 'environment') and getattr(self, 'environment') is not None: _dict['environment'] = getattr(self, 'environment') - if hasattr(self, - 'release_reference') and self.release_reference is not None: - _dict['release_reference'] = self.release_reference.to_dict() - if hasattr(self, 'orchestration') and self.orchestration is not None: - _dict['orchestration'] = self.orchestration.to_dict() + if hasattr(self, 'release_reference') and getattr( + self, 'release_reference') is not None: + if isinstance(getattr(self, 'release_reference'), dict): + _dict['release_reference'] = getattr(self, 'release_reference') + else: + _dict['release_reference'] = getattr( + self, 'release_reference').to_dict() + if hasattr(self, 'orchestration') and getattr( + self, 'orchestration') is not None: + if isinstance(getattr(self, 'orchestration'), dict): + _dict['orchestration'] = getattr(self, 'orchestration') + else: + _dict['orchestration'] = getattr(self, + 'orchestration').to_dict() if hasattr(self, 'session_timeout') and self.session_timeout is not None: _dict['session_timeout'] = self.session_timeout if hasattr(self, 'integration_references' ) and self.integration_references is not None: - _dict['integration_references'] = [ - x.to_dict() for x in self.integration_references - ] + integration_references_list = [] + for v in self.integration_references: + if isinstance(v, dict): + integration_references_list.append(v) + else: + integration_references_list.append(v.to_dict()) + _dict['integration_references'] = integration_references_list if hasattr(self, 'skill_references') and self.skill_references is not None: - _dict['skill_references'] = [ - x.to_dict() for x in self.skill_references - ] + skill_references_list = [] + for v in self.skill_references: + if isinstance(v, dict): + skill_references_list.append(v) + else: + skill_references_list.append(v.to_dict()) + _dict['skill_references'] = skill_references_list if hasattr(self, 'created') and getattr(self, 'created') is not None: _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'updated') and getattr(self, 'updated') is not None: @@ -2252,7 +2342,7 @@ def from_dict(cls, _dict: Dict) -> 'EnvironmentCollection': args = {} if 'environments' in _dict: args['environments'] = [ - Environment.from_dict(x) for x in _dict.get('environments') + Environment.from_dict(v) for v in _dict.get('environments') ] else: raise ValueError( @@ -2275,9 +2365,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'environments') and self.environments is not None: - _dict['environments'] = [x.to_dict() for x in self.environments] + environments_list = [] + for v in self.environments: + if isinstance(v, dict): + environments_list.append(v) + else: + environments_list.append(v.to_dict()) + _dict['environments'] = environments_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -2700,9 +2799,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'log_id') and self.log_id is not None: _dict['log_id'] = self.log_id if hasattr(self, 'request') and self.request is not None: - _dict['request'] = self.request.to_dict() + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() if hasattr(self, 'response') and self.response is not None: - _dict['response'] = self.response.to_dict() + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() if hasattr(self, 'assistant_id') and self.assistant_id is not None: _dict['assistant_id'] = self.assistant_id if hasattr(self, 'session_id') and self.session_id is not None: @@ -2767,7 +2872,7 @@ def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} if 'logs' in _dict: - args['logs'] = [Log.from_dict(x) for x in _dict.get('logs')] + args['logs'] = [Log.from_dict(v) for v in _dict.get('logs')] else: raise ValueError( 'Required property \'logs\' not present in LogCollection JSON') @@ -2789,9 +2894,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'logs') and self.logs is not None: - _dict['logs'] = [x.to_dict() for x in self.logs] + logs_list = [] + for v in self.logs: + if isinstance(v, dict): + logs_list.append(v) + else: + logs_list.append(v.to_dict()) + _dict['logs'] = logs_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -2956,7 +3070,7 @@ class MessageContext(): shared by all skills used by the assistant. :attr dict skills: (optional) Information specific to particular skills used by the assistant. - :attr object integrations: (optional) An object containing context data that is + :attr dict integrations: (optional) An object containing context data that is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ @@ -2965,7 +3079,7 @@ def __init__(self, *, global_: 'MessageContextGlobal' = None, skills: dict = None, - integrations: object = None) -> None: + integrations: dict = None) -> None: """ Initialize a MessageContext object. @@ -2973,8 +3087,8 @@ def __init__(self, is shared by all skills used by the assistant. :param dict skills: (optional) Information specific to particular skills used by the assistant. - :param object integrations: (optional) An object containing context data - that is specific to particular integrations. For more information, see the + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ self.global_ = global_ @@ -3006,9 +3120,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'global_') and self.global_ is not None: - _dict['global'] = self.global_.to_dict() + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() if hasattr(self, 'skills') and self.skills is not None: - _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} + skills_map = {} + for k, v in self.skills.items(): + if isinstance(v, dict): + skills_map[k] = v + else: + skills_map[k] = v.to_dict() + _dict['skills'] = skills_map if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations return _dict @@ -3074,7 +3197,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() if hasattr(self, 'session_id') and getattr(self, 'session_id') is not None: _dict['session_id'] = getattr(self, 'session_id') @@ -3142,7 +3268,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() if hasattr(self, 'session_id') and self.session_id is not None: _dict['session_id'] = self.session_id return _dict @@ -3436,7 +3565,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'system') and self.system is not None: - _dict['system'] = self.system.to_dict() + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() return _dict def _to_dict(self): @@ -3511,8 +3643,7 @@ def to_dict(self) -> Dict: k for k in vars(self).keys() if k not in MessageContextSkillSystem._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -3565,7 +3696,7 @@ class MessageContextStateless(): that is shared by all skills used by the assistant. :attr dict skills: (optional) Information specific to particular skills used by the assistant. - :attr object integrations: (optional) An object containing context data that is + :attr dict integrations: (optional) An object containing context data that is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ @@ -3574,7 +3705,7 @@ def __init__(self, *, global_: 'MessageContextGlobalStateless' = None, skills: dict = None, - integrations: object = None) -> None: + integrations: dict = None) -> None: """ Initialize a MessageContextStateless object. @@ -3582,8 +3713,8 @@ def __init__(self, data that is shared by all skills used by the assistant. :param dict skills: (optional) Information specific to particular skills used by the assistant. - :param object integrations: (optional) An object containing context data - that is specific to particular integrations. For more information, see the + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ self.global_ = global_ @@ -3615,9 +3746,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'global_') and self.global_ is not None: - _dict['global'] = self.global_.to_dict() + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() if hasattr(self, 'skills') and self.skills is not None: - _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} + skills_map = {} + for k, v in self.skills.items(): + if isinstance(v, dict): + skills_map[k] = v + else: + skills_map[k] = v.to_dict() + _dict['skills'] = skills_map if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations return _dict @@ -3722,18 +3862,18 @@ def from_dict(cls, _dict: Dict) -> 'MessageInput': args['text'] = _dict.get('text') if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] if 'suggestion_id' in _dict: args['suggestion_id'] = _dict.get('suggestion_id') if 'attachments' in _dict: args['attachments'] = [ - MessageInputAttachment.from_dict(x) - for x in _dict.get('attachments') + MessageInputAttachment.from_dict(v) + for v in _dict.get('attachments') ] if 'options' in _dict: args['options'] = MessageInputOptions.from_dict( @@ -3753,15 +3893,36 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: _dict['suggestion_id'] = self.suggestion_id if hasattr(self, 'attachments') and self.attachments is not None: - _dict['attachments'] = [x.to_dict() for x in self.attachments] + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -3963,7 +4124,10 @@ def to_dict(self) -> Dict: 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() if hasattr(self, 'debug') and self.debug is not None: _dict['debug'] = self.debug if hasattr(self, 'return_context') and self.return_context is not None: @@ -4150,7 +4314,10 @@ def to_dict(self) -> Dict: 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() if hasattr(self, 'debug') and self.debug is not None: _dict['debug'] = self.debug return _dict @@ -4255,18 +4422,18 @@ def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': args['text'] = _dict.get('text') if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] if 'suggestion_id' in _dict: args['suggestion_id'] = _dict.get('suggestion_id') if 'attachments' in _dict: args['attachments'] = [ - MessageInputAttachment.from_dict(x) - for x in _dict.get('attachments') + MessageInputAttachment.from_dict(v) + for v in _dict.get('attachments') ] if 'options' in _dict: args['options'] = MessageInputOptionsStateless.from_dict( @@ -4286,15 +4453,36 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: _dict['suggestion_id'] = self.suggestion_id if hasattr(self, 'attachments') and self.attachments is not None: - _dict['attachments'] = [x.to_dict() for x in self.attachments] + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -4394,20 +4582,20 @@ def from_dict(cls, _dict: Dict) -> 'MessageOutput': args = {} if 'generic' in _dict: args['generic'] = [ - RuntimeResponseGeneric.from_dict(x) - for x in _dict.get('generic') + RuntimeResponseGeneric.from_dict(v) + for v in _dict.get('generic') ] if 'intents' in _dict: args['intents'] = [ - RuntimeIntent.from_dict(x) for x in _dict.get('intents') + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] if 'entities' in _dict: args['entities'] = [ - RuntimeEntity.from_dict(x) for x in _dict.get('entities') + RuntimeEntity.from_dict(v) for v in _dict.get('entities') ] if 'actions' in _dict: args['actions'] = [ - DialogNodeAction.from_dict(x) for x in _dict.get('actions') + DialogNodeAction.from_dict(v) for v in _dict.get('actions') ] if 'debug' in _dict: args['debug'] = MessageOutputDebug.from_dict(_dict.get('debug')) @@ -4427,19 +4615,49 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'generic') and self.generic is not None: - _dict['generic'] = [x.to_dict() for x in self.generic] + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list if hasattr(self, 'intents') and self.intents is not None: - _dict['intents'] = [x.to_dict() for x in self.intents] + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'actions') and self.actions is not None: - _dict['actions'] = [x.to_dict() for x in self.actions] + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug.to_dict() + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'spelling') and self.spelling is not None: - _dict['spelling'] = self.spelling.to_dict() + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() return _dict def _to_dict(self): @@ -4519,12 +4737,12 @@ def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': args = {} if 'nodes_visited' in _dict: args['nodes_visited'] = [ - DialogNodeVisited.from_dict(x) - for x in _dict.get('nodes_visited') + DialogNodeVisited.from_dict(v) + for v in _dict.get('nodes_visited') ] if 'log_messages' in _dict: args['log_messages'] = [ - DialogLogMessage.from_dict(x) for x in _dict.get('log_messages') + DialogLogMessage.from_dict(v) for v in _dict.get('log_messages') ] if 'branch_exited' in _dict: args['branch_exited'] = _dict.get('branch_exited') @@ -4532,8 +4750,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': args['branch_exited_reason'] = _dict.get('branch_exited_reason') if 'turn_events' in _dict: args['turn_events'] = [ - MessageOutputDebugTurnEvent.from_dict(x) - for x in _dict.get('turn_events') + MessageOutputDebugTurnEvent.from_dict(v) + for v in _dict.get('turn_events') ] return cls(**args) @@ -4546,16 +4764,34 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: - _dict['nodes_visited'] = [x.to_dict() for x in self.nodes_visited] + nodes_visited_list = [] + for v in self.nodes_visited: + if isinstance(v, dict): + nodes_visited_list.append(v) + else: + nodes_visited_list.append(v.to_dict()) + _dict['nodes_visited'] = nodes_visited_list if hasattr(self, 'log_messages') and self.log_messages is not None: - _dict['log_messages'] = [x.to_dict() for x in self.log_messages] + log_messages_list = [] + for v in self.log_messages: + if isinstance(v, dict): + log_messages_list.append(v) + else: + log_messages_list.append(v.to_dict()) + _dict['log_messages'] = log_messages_list if hasattr(self, 'branch_exited') and self.branch_exited is not None: _dict['branch_exited'] = self.branch_exited if hasattr(self, 'branch_exited_reason' ) and self.branch_exited_reason is not None: _dict['branch_exited_reason'] = self.branch_exited_reason if hasattr(self, 'turn_events') and self.turn_events is not None: - _dict['turn_events'] = [x.to_dict() for x in self.turn_events] + turn_events_list = [] + for v in self.turn_events: + if isinstance(v, dict): + turn_events_list.append(v) + else: + turn_events_list.append(v.to_dict()) + _dict['turn_events'] = turn_events_list return _dict def _to_dict(self): @@ -4826,9 +5062,15 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'input') and self.input is not None: - _dict['input'] = self.input.to_dict() + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id return _dict @@ -4934,9 +5176,15 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id return _dict @@ -5039,9 +5287,15 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output.to_dict() + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() if hasattr(self, 'context') and self.context is not None: - _dict['context'] = self.context.to_dict() + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() if hasattr(self, 'user_id') and self.user_id is not None: _dict['user_id'] = self.user_id return _dict @@ -5209,9 +5463,6 @@ def __init__(self, :param str release: (optional) The name of the release. The name is the version number (an integer), returned as a string. :param str description: (optional) The description of the release. - :param ReleaseContent content: (optional) An object describing the - versionable content objects (such as skill snapshots) that are included in - the release. :param str status: (optional) The current status of the release: - **Available**: The release is available for deployment. - **Failed**: An asynchronous publish operation has failed. @@ -5235,8 +5486,8 @@ def from_dict(cls, _dict: Dict) -> 'Release': args['description'] = _dict.get('description') if 'environment_references' in _dict: args['environment_references'] = [ - EnvironmentReference.from_dict(x) - for x in _dict.get('environment_references') + EnvironmentReference.from_dict(v) + for v in _dict.get('environment_references') ] if 'content' in _dict: args['content'] = ReleaseContent.from_dict(_dict.get('content')) @@ -5262,11 +5513,18 @@ def to_dict(self) -> Dict: _dict['description'] = self.description if hasattr(self, 'environment_references') and getattr( self, 'environment_references') is not None: - _dict['environment_references'] = [ - x.to_dict() for x in getattr(self, 'environment_references') - ] - if hasattr(self, 'content') and self.content is not None: - _dict['content'] = self.content.to_dict() + environment_references_list = [] + for v in getattr(self, 'environment_references'): + if isinstance(v, dict): + environment_references_list.append(v) + else: + environment_references_list.append(v.to_dict()) + _dict['environment_references'] = environment_references_list + if hasattr(self, 'content') and getattr(self, 'content') is not None: + if isinstance(getattr(self, 'content'), dict): + _dict['content'] = getattr(self, 'content') + else: + _dict['content'] = getattr(self, 'content').to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'created') and getattr(self, 'created') is not None: @@ -5332,7 +5590,7 @@ def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': args = {} if 'releases' in _dict: args['releases'] = [ - Release.from_dict(x) for x in _dict.get('releases') + Release.from_dict(v) for v in _dict.get('releases') ] else: raise ValueError( @@ -5355,9 +5613,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'releases') and self.releases is not None: - _dict['releases'] = [x.to_dict() for x in self.releases] + releases_list = [] + for v in self.releases: + if isinstance(v, dict): + releases_list.append(v) + else: + releases_list.append(v.to_dict()) + _dict['releases'] = releases_list if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -5401,7 +5668,7 @@ def from_dict(cls, _dict: Dict) -> 'ReleaseContent': args = {} if 'skills' in _dict: args['skills'] = [ - ReleaseSkillReference.from_dict(x) for x in _dict.get('skills') + ReleaseSkillReference.from_dict(v) for v in _dict.get('skills') ] return cls(**args) @@ -5414,7 +5681,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'skills') and getattr(self, 'skills') is not None: - _dict['skills'] = [x.to_dict() for x in getattr(self, 'skills')] + skills_list = [] + for v in getattr(self, 'skills'): + if isinstance(v, dict): + skills_list.append(v) + else: + skills_list.append(v.to_dict()) + _dict['skills'] = skills_list return _dict def _to_dict(self): @@ -5688,15 +5961,15 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': args['confidence'] = _dict.get('confidence') if 'groups' in _dict: args['groups'] = [ - CaptureGroup.from_dict(x) for x in _dict.get('groups') + CaptureGroup.from_dict(v) for v 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') + RuntimeEntityAlternative.from_dict(v) + for v in _dict.get('alternatives') ] if 'role' in _dict: args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) @@ -5721,13 +5994,31 @@ def to_dict(self) -> Dict: if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'groups') and self.groups is not None: - _dict['groups'] = [x.to_dict() for x in self.groups] + groups_list = [] + for v in self.groups: + if isinstance(v, dict): + groups_list.append(v) + else: + groups_list.append(v.to_dict()) + _dict['groups'] = groups_list if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation.to_dict() + if isinstance(self.interpretation, dict): + _dict['interpretation'] = self.interpretation + else: + _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] + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list if hasattr(self, 'role') and self.role is not None: - _dict['role'] = self.role.to_dict() + if isinstance(self.role, dict): + _dict['role'] = self.role + else: + _dict['role'] = self.role.to_dict() if hasattr(self, 'skill') and self.skill is not None: _dict['skill'] = self.skill return _dict @@ -6537,7 +6828,7 @@ def from_dict(cls, _dict: Dict) -> 'SearchResult': _dict.get('highlight')) if 'answers' in _dict: args['answers'] = [ - SearchResultAnswer.from_dict(x) for x in _dict.get('answers') + SearchResultAnswer.from_dict(v) for v in _dict.get('answers') ] return cls(**args) @@ -6553,7 +6844,10 @@ def to_dict(self) -> Dict: _dict['id'] = self.id if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() if hasattr(self, 'body') and self.body is not None: _dict['body'] = self.body if hasattr(self, 'title') and self.title is not None: @@ -6561,9 +6855,18 @@ def to_dict(self) -> Dict: if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight.to_dict() + if isinstance(self.highlight, dict): + _dict['highlight'] = self.highlight + else: + _dict['highlight'] = self.highlight.to_dict() if hasattr(self, 'answers') and self.answers is not None: - _dict['answers'] = [x.to_dict() for x in self.answers] + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list return _dict def _to_dict(self): @@ -6733,8 +7036,7 @@ def to_dict(self) -> Dict: k for k in vars(self).keys() if k not in SearchResultHighlight._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -7784,7 +8086,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'event') and self.event is not None: _dict['event'] = self.event if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() if hasattr(self, 'action_start_time') and self.action_start_time is not None: _dict['action_start_time'] = self.action_start_time @@ -7908,7 +8213,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'event') and self.event is not None: _dict['event'] = self.event if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() if hasattr(self, 'action_start_time') and self.action_start_time is not None: _dict['action_start_time'] = self.action_start_time @@ -8021,11 +8329,20 @@ def to_dict(self) -> Dict: if hasattr(self, 'event') and self.event is not None: _dict['event'] = self.event if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() if hasattr(self, 'callout') and self.callout is not None: - _dict['callout'] = self.callout.to_dict() + if isinstance(self.callout, dict): + _dict['callout'] = self.callout + else: + _dict['callout'] = self.callout.to_dict() if hasattr(self, 'error') and self.error is not None: - _dict['error'] = self.error.to_dict() + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -8104,7 +8421,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'event') and self.event is not None: _dict['event'] = self.event if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() if hasattr(self, 'action_start_time') and self.action_start_time is not None: _dict['action_start_time'] = self.action_start_time @@ -8185,7 +8505,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'event') and self.event is not None: _dict['event'] = self.event if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() if hasattr(self, 'reason') and self.reason is not None: _dict['reason'] = self.reason return _dict @@ -8275,9 +8598,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'event') and self.event is not None: _dict['event'] = self.event if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() if hasattr(self, 'error') and self.error is not None: - _dict['error'] = self.error.to_dict() + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -8374,7 +8703,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'event') and self.event is not None: _dict['event'] = self.event if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() if hasattr(self, 'condition_type') and self.condition_type is not None: _dict['condition_type'] = self.condition_type if hasattr(self, @@ -8486,7 +8818,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'event') and self.event is not None: _dict['event'] = self.event if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() if hasattr(self, 'condition_type') and self.condition_type is not None: _dict['condition_type'] = self.condition_type if hasattr(self, @@ -8541,7 +8876,7 @@ class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -8553,7 +8888,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. @@ -8570,7 +8905,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ @@ -8607,8 +8942,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -8633,7 +8968,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options @@ -8733,8 +9074,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -8752,9 +9093,18 @@ def to_dict(self) -> Dict: 'message_to_user') and self.message_to_user is not None: _dict['message_to_user'] = self.message_to_user if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -8879,8 +9229,8 @@ def from_dict( args['topic'] = _dict.get('topic') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -8899,16 +9249,31 @@ def to_dict(self) -> Dict: _dict['message_to_human_agent'] = self.message_to_human_agent if hasattr(self, 'agent_available') and self.agent_available is not None: - _dict['agent_available'] = self.agent_available.to_dict() + if isinstance(self.agent_available, dict): + _dict['agent_available'] = self.agent_available + else: + _dict['agent_available'] = self.agent_available.to_dict() if hasattr(self, 'agent_unavailable') and self.agent_unavailable is not None: - _dict['agent_unavailable'] = self.agent_unavailable.to_dict() + if isinstance(self.agent_unavailable, dict): + _dict['agent_unavailable'] = self.agent_unavailable + else: + _dict['agent_unavailable'] = self.agent_unavailable.to_dict() if hasattr(self, 'transfer_info') and self.transfer_info is not None: - _dict['transfer_info'] = self.transfer_info.to_dict() + if isinstance(self.transfer_info, dict): + _dict['transfer_info'] = self.transfer_info + else: + _dict['transfer_info'] = self.transfer_info.to_dict() if hasattr(self, 'topic') and self.topic is not None: _dict['topic'] = self.topic if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -9078,8 +9443,8 @@ def from_dict( args['image_url'] = _dict.get('image_url') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -9102,7 +9467,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image_url') and self.image_url is not None: _dict['image_url'] = self.image_url if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -9202,8 +9573,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'alt_text' in _dict: args['alt_text'] = _dict.get('alt_text') @@ -9226,7 +9597,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'alt_text') and self.alt_text is not None: _dict['alt_text'] = self.alt_text return _dict @@ -9327,8 +9704,8 @@ def from_dict( args['preference'] = _dict.get('preference') if 'options' in _dict: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(x) - for x in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) + for v in _dict.get('options') ] else: raise ValueError( @@ -9336,8 +9713,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -9358,9 +9735,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'preference') and self.preference is not None: _dict['preference'] = self.preference if hasattr(self, 'options') and self.options is not None: - _dict['options'] = [x.to_dict() for x in self.options] + options_list = [] + for v in self.options: + if isinstance(v, dict): + options_list.append(v) + else: + options_list.append(v.to_dict()) + _dict['options'] = options_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -9456,8 +9845,8 @@ def from_dict( args['typing'] = _dict.get('typing') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -9476,7 +9865,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'typing') and self.typing is not None: _dict['typing'] = self.typing if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -9571,7 +9966,7 @@ def from_dict( ) if 'primary_results' in _dict: args['primary_results'] = [ - SearchResult.from_dict(x) for x in _dict.get('primary_results') + SearchResult.from_dict(v) for v in _dict.get('primary_results') ] else: raise ValueError( @@ -9579,8 +9974,8 @@ def from_dict( ) if 'additional_results' in _dict: args['additional_results'] = [ - SearchResult.from_dict(x) - for x in _dict.get('additional_results') + SearchResult.from_dict(v) + for v in _dict.get('additional_results') ] else: raise ValueError( @@ -9588,8 +9983,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -9607,17 +10002,31 @@ def to_dict(self) -> Dict: _dict['header'] = self.header if hasattr(self, 'primary_results') and self.primary_results is not None: - _dict['primary_results'] = [ - x.to_dict() for x in self.primary_results - ] + primary_results_list = [] + for v in self.primary_results: + if isinstance(v, dict): + primary_results_list.append(v) + else: + primary_results_list.append(v.to_dict()) + _dict['primary_results'] = primary_results_list if hasattr( self, 'additional_results') and self.additional_results is not None: - _dict['additional_results'] = [ - x.to_dict() for x in self.additional_results - ] + additional_results_list = [] + for v in self.additional_results: + if isinstance(v, dict): + additional_results_list.append(v) + else: + additional_results_list.append(v.to_dict()) + _dict['additional_results'] = additional_results_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -9706,7 +10115,7 @@ def from_dict( ) if 'suggestions' in _dict: args['suggestions'] = [ - DialogSuggestion.from_dict(x) for x in _dict.get('suggestions') + DialogSuggestion.from_dict(v) for v in _dict.get('suggestions') ] else: raise ValueError( @@ -9714,8 +10123,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -9732,9 +10141,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title if hasattr(self, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = [x.to_dict() for x in self.suggestions] + suggestions_list = [] + for v in self.suggestions: + if isinstance(v, dict): + suggestions_list.append(v) + else: + suggestions_list.append(v.to_dict()) + _dict['suggestions'] = suggestions_list if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -9815,8 +10236,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -9833,7 +10254,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -9915,8 +10342,8 @@ def from_dict( ) if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] return cls(**args) @@ -9933,7 +10360,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_defined') and self.user_defined is not None: _dict['user_defined'] = self.user_defined if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list return _dict def _to_dict(self): @@ -9973,7 +10406,7 @@ class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr object channel_options: (optional) For internal use only. + :attr dict channel_options: (optional) For internal use only. :attr str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -9985,7 +10418,7 @@ def __init__(self, title: str = None, description: str = None, channels: List['ResponseGenericChannel'] = None, - channel_options: object = None, + channel_options: dict = None, alt_text: str = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. @@ -10002,7 +10435,7 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :param object channel_options: (optional) For internal use only. + :param dict channel_options: (optional) For internal use only. :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ @@ -10039,8 +10472,8 @@ def from_dict( args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ - ResponseGenericChannel.from_dict(x) - for x in _dict.get('channels') + ResponseGenericChannel.from_dict(v) + for v in _dict.get('channels') ] if 'channel_options' in _dict: args['channel_options'] = _dict.get('channel_options') @@ -10065,7 +10498,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: - _dict['channels'] = [x.to_dict() for x in self.channels] + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list if hasattr(self, 'channel_options') and self.channel_options is not None: _dict['channel_options'] = self.channel_options diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index cfd74bf3d..259058efc 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ IBM Watson™ Discovery v1 is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive @@ -115,9 +115,15 @@ def create_environment(self, operation_id='create_environment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'name': name, 'description': description, 'size': size} + data = { + 'name': name, + 'description': description, + 'size': size, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -158,7 +164,10 @@ def list_environments(self, operation_id='list_environments') headers.update(sdk_headers) - params = {'version': self.version, 'name': name} + params = { + 'version': self.version, + 'name': name, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -185,7 +194,7 @@ def get_environment(self, environment_id: str, :rtype: DetailedResponse with `dict` result representing a `Environment` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -193,7 +202,9 @@ def get_environment(self, environment_id: str, operation_id='get_environment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -235,7 +246,7 @@ def update_environment(self, :rtype: DetailedResponse with `dict` result representing a `Environment` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -243,9 +254,15 @@ def update_environment(self, operation_id='update_environment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'name': name, 'description': description, 'size': size} + data = { + 'name': name, + 'description': description, + 'size': size, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -279,7 +296,7 @@ def delete_environment(self, environment_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteEnvironmentResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -287,7 +304,9 @@ def delete_environment(self, environment_id: str, operation_id='delete_environment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -322,7 +341,7 @@ def list_fields(self, environment_id: str, collection_ids: List[str], :rtype: DetailedResponse with `dict` result representing a `ListCollectionFieldsResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if collection_ids is None: raise ValueError('collection_ids must be provided') @@ -334,7 +353,7 @@ def list_fields(self, environment_id: str, collection_ids: List[str], params = { 'version': self.version, - 'collection_ids': convert_list(collection_ids) + 'collection_ids': convert_list(collection_ids), } if 'headers' in kwargs: @@ -402,7 +421,7 @@ def create_configuration( :rtype: DetailedResponse with `dict` result representing a `Configuration` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if name is None: raise ValueError('name must be provided') @@ -420,7 +439,9 @@ def create_configuration( operation_id='create_configuration') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, @@ -428,7 +449,7 @@ def create_configuration( 'conversions': conversions, 'enrichments': enrichments, 'normalizations': normalizations, - 'source': source + 'source': source, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -470,7 +491,7 @@ def list_configurations(self, :rtype: DetailedResponse with `dict` result representing a `ListConfigurationsResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -478,7 +499,10 @@ def list_configurations(self, operation_id='list_configurations') headers.update(sdk_headers) - params = {'version': self.version, 'name': name} + params = { + 'version': self.version, + 'name': name, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -510,9 +534,9 @@ def get_configuration(self, environment_id: str, configuration_id: str, :rtype: DetailedResponse with `dict` result representing a `Configuration` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if configuration_id is None: + if not configuration_id: raise ValueError('configuration_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -520,7 +544,9 @@ def get_configuration(self, environment_id: str, configuration_id: str, operation_id='get_configuration') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -585,9 +611,9 @@ def update_configuration( :rtype: DetailedResponse with `dict` result representing a `Configuration` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if configuration_id is None: + if not configuration_id: raise ValueError('configuration_id must be provided') if name is None: raise ValueError('name must be provided') @@ -605,7 +631,9 @@ def update_configuration( operation_id='update_configuration') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, @@ -613,7 +641,7 @@ def update_configuration( 'conversions': conversions, 'enrichments': enrichments, 'normalizations': normalizations, - 'source': source + 'source': source, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -658,9 +686,9 @@ def delete_configuration(self, environment_id: str, configuration_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteConfigurationResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if configuration_id is None: + if not configuration_id: raise ValueError('configuration_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -668,7 +696,9 @@ def delete_configuration(self, environment_id: str, configuration_id: str, operation_id='delete_configuration') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -716,7 +746,7 @@ def create_collection(self, :rtype: DetailedResponse with `dict` result representing a `Collection` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if name is None: raise ValueError('name must be provided') @@ -726,13 +756,15 @@ def create_collection(self, operation_id='create_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, 'description': description, 'configuration_id': configuration_id, - 'language': language + 'language': language, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -774,7 +806,7 @@ def list_collections(self, :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -782,7 +814,10 @@ def list_collections(self, operation_id='list_collections') headers.update(sdk_headers) - params = {'version': self.version, 'name': name} + params = { + 'version': self.version, + 'name': name, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -814,9 +849,9 @@ def get_collection(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `Collection` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -824,7 +859,9 @@ def get_collection(self, environment_id: str, collection_id: str, operation_id='get_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -866,9 +903,9 @@ def update_collection(self, :rtype: DetailedResponse with `dict` result representing a `Collection` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if name is None: raise ValueError('name must be provided') @@ -878,12 +915,14 @@ def update_collection(self, operation_id='update_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, 'description': description, - 'configuration_id': configuration_id + 'configuration_id': configuration_id, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -920,9 +959,9 @@ def delete_collection(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteCollectionResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -930,7 +969,9 @@ def delete_collection(self, environment_id: str, collection_id: str, operation_id='delete_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -964,9 +1005,9 @@ def list_collection_fields(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `ListCollectionFieldsResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -974,7 +1015,9 @@ def list_collection_fields(self, environment_id: str, collection_id: str, operation_id='list_collection_fields') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1013,9 +1056,9 @@ def list_expansions(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1023,7 +1066,9 @@ def list_expansions(self, environment_id: str, collection_id: str, operation_id='list_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1073,9 +1118,9 @@ def create_expansions(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if expansions is None: raise ValueError('expansions must be provided') @@ -1086,9 +1131,13 @@ def create_expansions(self, environment_id: str, collection_id: str, operation_id='create_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'expansions': expansions} + data = { + 'expansions': expansions, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -1127,9 +1176,9 @@ def delete_expansions(self, environment_id: str, collection_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1137,7 +1186,9 @@ def delete_expansions(self, environment_id: str, collection_id: str, operation_id='delete_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1172,9 +1223,9 @@ def get_tokenization_dictionary_status(self, environment_id: str, :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers( @@ -1183,7 +1234,9 @@ def get_tokenization_dictionary_status(self, environment_id: str, operation_id='get_tokenization_dictionary_status') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1226,9 +1279,9 @@ def create_tokenization_dictionary( :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if tokenization_rules is not None: tokenization_rules = [convert_model(x) for x in tokenization_rules] @@ -1239,9 +1292,13 @@ def create_tokenization_dictionary( operation_id='create_tokenization_dictionary') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'tokenization_rules': tokenization_rules} + data = { + 'tokenization_rules': tokenization_rules, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -1280,9 +1337,9 @@ def delete_tokenization_dictionary(self, environment_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers( @@ -1291,7 +1348,9 @@ def delete_tokenization_dictionary(self, environment_id: str, operation_id='delete_tokenization_dictionary') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1324,9 +1383,9 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1334,7 +1393,9 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, operation_id='get_stopword_list_status') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1375,9 +1436,9 @@ def create_stopword_list(self, :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if stopword_file is None: raise ValueError('stopword_file must be provided') @@ -1387,7 +1448,9 @@ def create_stopword_list(self, operation_id='create_stopword_list') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if not stopword_filename and hasattr(stopword_file, 'name'): @@ -1431,9 +1494,9 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1441,7 +1504,9 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, operation_id='delete_stopword_list') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1515,9 +1580,9 @@ def add_document(self, :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1525,7 +1590,9 @@ def add_document(self, operation_id='add_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if file: @@ -1575,11 +1642,11 @@ def get_document_status(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1587,7 +1654,9 @@ def get_document_status(self, environment_id: str, collection_id: str, operation_id='get_document_status') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1645,11 +1714,11 @@ def update_document(self, :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1657,7 +1726,9 @@ def update_document(self, operation_id='update_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if file: @@ -1707,11 +1778,11 @@ def delete_document(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteDocumentResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1719,7 +1790,9 @@ def delete_document(self, environment_id: str, collection_id: str, operation_id='delete_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1858,17 +1931,21 @@ def query(self, :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} + headers = { + 'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'filter': filter, @@ -1890,7 +1967,7 @@ def query(self, 'similar.document_ids': similar_document_ids, 'similar.fields': similar_fields, 'bias': bias, - 'spelling_suggestions': spelling_suggestions + 'spelling_suggestions': spelling_suggestions, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2007,9 +2084,9 @@ def query_notices(self, :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2035,7 +2112,7 @@ def query_notices(self, 'deduplicate.field': deduplicate_field, 'similar': similar, 'similar.document_ids': convert_list(similar_document_ids), - 'similar.fields': convert_list(similar_fields) + 'similar.fields': convert_list(similar_fields), } if 'headers' in kwargs: @@ -2164,17 +2241,21 @@ def federated_query(self, :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if collection_ids is None: raise ValueError('collection_ids must be provided') - headers = {'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out} + headers = { + 'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='federated_query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'collection_ids': collection_ids, @@ -2196,7 +2277,7 @@ def federated_query(self, 'similar': similar, 'similar.document_ids': similar_document_ids, 'similar.fields': similar_fields, - 'bias': bias + 'bias': bias, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2300,7 +2381,7 @@ def federated_query_notices(self, :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if collection_ids is None: raise ValueError('collection_ids must be provided') @@ -2325,7 +2406,7 @@ def federated_query_notices(self, 'deduplicate.field': deduplicate_field, 'similar': similar, 'similar.document_ids': convert_list(similar_document_ids), - 'similar.fields': convert_list(similar_fields) + 'similar.fields': convert_list(similar_fields), } if 'headers' in kwargs: @@ -2374,11 +2455,11 @@ def get_autocompletion(self, :rtype: DetailedResponse with `dict` result representing a `Completions` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if prefix is None: + if not prefix: raise ValueError('prefix must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2390,7 +2471,7 @@ def get_autocompletion(self, 'version': self.version, 'prefix': prefix, 'field': field, - 'count': count + 'count': count, } if 'headers' in kwargs: @@ -2429,9 +2510,9 @@ def list_training_data(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `TrainingDataSet` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2439,7 +2520,9 @@ def list_training_data(self, environment_id: str, collection_id: str, operation_id='list_training_data') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2486,9 +2569,9 @@ def add_training_data(self, :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if examples is not None: examples = [convert_model(x) for x in examples] @@ -2498,12 +2581,14 @@ def add_training_data(self, operation_id='add_training_data') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'natural_language_query': natural_language_query, 'filter': filter, - 'examples': examples + 'examples': examples, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2542,9 +2627,9 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2552,7 +2637,9 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, operation_id='delete_all_training_data') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2587,11 +2674,11 @@ def get_training_data(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2599,7 +2686,9 @@ def get_training_data(self, environment_id: str, collection_id: str, operation_id='get_training_data') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2636,11 +2725,11 @@ def delete_training_data(self, environment_id: str, collection_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2648,7 +2737,9 @@ def delete_training_data(self, environment_id: str, collection_id: str, operation_id='delete_training_data') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2683,11 +2774,11 @@ def list_training_examples(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `TrainingExampleList` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2695,7 +2786,9 @@ def list_training_examples(self, environment_id: str, collection_id: str, operation_id='list_training_examples') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2743,11 +2836,11 @@ def create_training_example(self, :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2755,12 +2848,14 @@ def create_training_example(self, operation_id='create_training_example') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'document_id': document_id, 'cross_reference': cross_reference, - 'relevance': relevance + 'relevance': relevance, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2803,13 +2898,13 @@ def delete_training_example(self, environment_id: str, collection_id: str, :rtype: DetailedResponse """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') - if example_id is None: + if not example_id: raise ValueError('example_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2817,7 +2912,9 @@ def delete_training_example(self, environment_id: str, collection_id: str, operation_id='delete_training_example') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2864,13 +2961,13 @@ def update_training_example(self, :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') - if example_id is None: + if not example_id: raise ValueError('example_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2878,9 +2975,14 @@ def update_training_example(self, operation_id='update_training_example') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'cross_reference': cross_reference, 'relevance': relevance} + data = { + 'cross_reference': cross_reference, + 'relevance': relevance, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -2924,13 +3026,13 @@ def get_training_example(self, environment_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') - if example_id is None: + if not example_id: raise ValueError('example_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2938,7 +3040,9 @@ def get_training_example(self, environment_id: str, collection_id: str, operation_id='get_training_example') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2983,7 +3087,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2991,7 +3095,10 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: operation_id='delete_user_data') headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = { + 'version': self.version, + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3037,9 +3144,14 @@ def create_event(self, type: str, data: 'EventData', operation_id='create_event') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'type': type, 'data': data} + data = { + 'type': type, + 'data': data, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -3107,7 +3219,7 @@ def query_log(self, 'query': query, 'count': count, 'offset': offset, - 'sort': convert_list(sort) + 'sort': convert_list(sort), } if 'headers' in kwargs: @@ -3157,7 +3269,7 @@ def get_metrics_query(self, 'version': self.version, 'start_time': start_time, 'end_time': end_time, - 'result_type': result_type + 'result_type': result_type, } if 'headers' in kwargs: @@ -3208,7 +3320,7 @@ def get_metrics_query_event(self, 'version': self.version, 'start_time': start_time, 'end_time': end_time, - 'result_type': result_type + 'result_type': result_type, } if 'headers' in kwargs: @@ -3259,7 +3371,7 @@ def get_metrics_query_no_results(self, 'version': self.version, 'start_time': start_time, 'end_time': end_time, - 'result_type': result_type + 'result_type': result_type, } if 'headers' in kwargs: @@ -3310,7 +3422,7 @@ def get_metrics_event_rate(self, 'version': self.version, 'start_time': start_time, 'end_time': end_time, - 'result_type': result_type + 'result_type': result_type, } if 'headers' in kwargs: @@ -3353,7 +3465,10 @@ def get_metrics_query_token_event(self, operation_id='get_metrics_query_token_event') headers.update(sdk_headers) - params = {'version': self.version, 'count': count} + params = { + 'version': self.version, + 'count': count, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3388,7 +3503,7 @@ def list_credentials(self, environment_id: str, :rtype: DetailedResponse with `dict` result representing a `CredentialsList` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3396,7 +3511,9 @@ def list_credentials(self, environment_id: str, operation_id='list_credentials') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3453,7 +3570,7 @@ def create_credentials(self, :rtype: DetailedResponse with `dict` result representing a `Credentials` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') if credential_details is not None: credential_details = convert_model(credential_details) @@ -3465,12 +3582,14 @@ def create_credentials(self, operation_id='create_credentials') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'source_type': source_type, 'credential_details': credential_details, - 'status': status + 'status': status, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -3512,9 +3631,9 @@ def get_credentials(self, environment_id: str, credential_id: str, :rtype: DetailedResponse with `dict` result representing a `Credentials` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if credential_id is None: + if not credential_id: raise ValueError('credential_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3522,7 +3641,9 @@ def get_credentials(self, environment_id: str, credential_id: str, operation_id='get_credentials') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3581,9 +3702,9 @@ def update_credentials(self, :rtype: DetailedResponse with `dict` result representing a `Credentials` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if credential_id is None: + if not credential_id: raise ValueError('credential_id must be provided') if credential_details is not None: credential_details = convert_model(credential_details) @@ -3595,12 +3716,14 @@ def update_credentials(self, operation_id='update_credentials') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'source_type': source_type, 'credential_details': credential_details, - 'status': status + 'status': status, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -3640,9 +3763,9 @@ def delete_credentials(self, environment_id: str, credential_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteCredentials` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if credential_id is None: + if not credential_id: raise ValueError('credential_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3650,7 +3773,9 @@ def delete_credentials(self, environment_id: str, credential_id: str, operation_id='delete_credentials') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3686,7 +3811,7 @@ def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `GatewayList` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3694,7 +3819,9 @@ def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: operation_id='list_gateways') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3731,7 +3858,7 @@ def create_gateway(self, :rtype: DetailedResponse with `dict` result representing a `Gateway` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3739,9 +3866,13 @@ def create_gateway(self, operation_id='create_gateway') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'name': name} + data = { + 'name': name, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -3779,9 +3910,9 @@ def get_gateway(self, environment_id: str, gateway_id: str, :rtype: DetailedResponse with `dict` result representing a `Gateway` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if gateway_id is None: + if not gateway_id: raise ValueError('gateway_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3789,7 +3920,9 @@ def get_gateway(self, environment_id: str, gateway_id: str, operation_id='get_gateway') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3823,9 +3956,9 @@ def delete_gateway(self, environment_id: str, gateway_id: str, :rtype: DetailedResponse with `dict` result representing a `GatewayDelete` object """ - if environment_id is None: + if not environment_id: raise ValueError('environment_id must be provided') - if gateway_id is None: + if not gateway_id: raise ValueError('gateway_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3833,7 +3966,9 @@ def delete_gateway(self, environment_id: str, gateway_id: str, operation_id='delete_gateway') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -4083,19 +4218,35 @@ def to_dict(self) -> Dict: _dict['language'] = self.language if hasattr(self, 'document_counts') and self.document_counts is not None: - _dict['document_counts'] = self.document_counts.to_dict() + if isinstance(self.document_counts, dict): + _dict['document_counts'] = self.document_counts + else: + _dict['document_counts'] = self.document_counts.to_dict() if hasattr(self, 'disk_usage') and self.disk_usage is not None: - _dict['disk_usage'] = self.disk_usage.to_dict() + if isinstance(self.disk_usage, dict): + _dict['disk_usage'] = self.disk_usage + else: + _dict['disk_usage'] = self.disk_usage.to_dict() if hasattr(self, 'training_status') and self.training_status is not None: - _dict['training_status'] = self.training_status.to_dict() + if isinstance(self.training_status, dict): + _dict['training_status'] = self.training_status + else: + _dict['training_status'] = self.training_status.to_dict() if hasattr(self, 'crawl_status') and self.crawl_status is not None: - _dict['crawl_status'] = self.crawl_status.to_dict() + if isinstance(self.crawl_status, dict): + _dict['crawl_status'] = self.crawl_status + else: + _dict['crawl_status'] = self.crawl_status.to_dict() if hasattr(self, 'smart_document_understanding' ) and self.smart_document_understanding is not None: - _dict[ - 'smart_document_understanding'] = self.smart_document_understanding.to_dict( - ) + if isinstance(self.smart_document_understanding, dict): + _dict[ + 'smart_document_understanding'] = self.smart_document_understanding + else: + _dict[ + 'smart_document_understanding'] = self.smart_document_understanding.to_dict( + ) return _dict def _to_dict(self): @@ -4160,7 +4311,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'source_crawl') and self.source_crawl is not None: - _dict['source_crawl'] = self.source_crawl.to_dict() + if isinstance(self.source_crawl, dict): + _dict['source_crawl'] = self.source_crawl + else: + _dict['source_crawl'] = self.source_crawl.to_dict() return _dict def _to_dict(self): @@ -4439,12 +4593,12 @@ def from_dict(cls, _dict: Dict) -> 'Configuration': _dict.get('conversions')) if 'enrichments' in _dict: args['enrichments'] = [ - Enrichment.from_dict(x) for x in _dict.get('enrichments') + Enrichment.from_dict(v) for v in _dict.get('enrichments') ] if 'normalizations' in _dict: args['normalizations'] = [ - NormalizationOperation.from_dict(x) - for x in _dict.get('normalizations') + NormalizationOperation.from_dict(v) + for v in _dict.get('normalizations') ] if 'source' in _dict: args['source'] = Source.from_dict(_dict.get('source')) @@ -4470,13 +4624,31 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'conversions') and self.conversions is not None: - _dict['conversions'] = self.conversions.to_dict() + if isinstance(self.conversions, dict): + _dict['conversions'] = self.conversions + else: + _dict['conversions'] = self.conversions.to_dict() if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list if hasattr(self, 'normalizations') and self.normalizations is not None: - _dict['normalizations'] = [x.to_dict() for x in self.normalizations] + normalizations_list = [] + for v in self.normalizations: + if isinstance(v, dict): + normalizations_list.append(v) + else: + normalizations_list.append(v.to_dict()) + _dict['normalizations'] = normalizations_list if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() return _dict def _to_dict(self): @@ -4566,8 +4738,8 @@ def from_dict(cls, _dict: Dict) -> 'Conversions': args['segment'] = SegmentSettings.from_dict(_dict.get('segment')) if 'json_normalizations' in _dict: args['json_normalizations'] = [ - NormalizationOperation.from_dict(x) - for x in _dict.get('json_normalizations') + NormalizationOperation.from_dict(v) + for v in _dict.get('json_normalizations') ] if 'image_text_recognition' in _dict: args['image_text_recognition'] = _dict.get('image_text_recognition') @@ -4582,19 +4754,35 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'pdf') and self.pdf is not None: - _dict['pdf'] = self.pdf.to_dict() + if isinstance(self.pdf, dict): + _dict['pdf'] = self.pdf + else: + _dict['pdf'] = self.pdf.to_dict() if hasattr(self, 'word') and self.word is not None: - _dict['word'] = self.word.to_dict() + if isinstance(self.word, dict): + _dict['word'] = self.word + else: + _dict['word'] = self.word.to_dict() if hasattr(self, 'html') and self.html is not None: - _dict['html'] = self.html.to_dict() + if isinstance(self.html, dict): + _dict['html'] = self.html + else: + _dict['html'] = self.html.to_dict() if hasattr(self, 'segment') and self.segment is not None: - _dict['segment'] = self.segment.to_dict() + if isinstance(self.segment, dict): + _dict['segment'] = self.segment + else: + _dict['segment'] = self.segment.to_dict() if hasattr( self, 'json_normalizations') and self.json_normalizations is not None: - _dict['json_normalizations'] = [ - x.to_dict() for x in self.json_normalizations - ] + json_normalizations_list = [] + for v in self.json_normalizations: + if isinstance(v, dict): + json_normalizations_list.append(v) + else: + json_normalizations_list.append(v.to_dict()) + _dict['json_normalizations'] = json_normalizations_list if hasattr(self, 'image_text_recognition' ) and self.image_text_recognition is not None: _dict['image_text_recognition'] = self.image_text_recognition @@ -4658,7 +4846,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'data') and self.data is not None: - _dict['data'] = self.data.to_dict() + if isinstance(self.data, dict): + _dict['data'] = self.data + else: + _dict['data'] = self.data.to_dict() return _dict def _to_dict(self): @@ -5125,9 +5316,15 @@ def to_dict(self) -> Dict: if hasattr( self, 'credential_details') and self.credential_details is not None: - _dict['credential_details'] = self.credential_details.to_dict() + if isinstance(self.credential_details, dict): + _dict['credential_details'] = self.credential_details + else: + _dict['credential_details'] = self.credential_details.to_dict() if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status.to_dict() + if isinstance(self.status, dict): + _dict['status'] = self.status + else: + _dict['status'] = self.status.to_dict() return _dict def _to_dict(self): @@ -5190,7 +5387,7 @@ def from_dict(cls, _dict: Dict) -> 'CredentialsList': args = {} if 'credentials' in _dict: args['credentials'] = [ - Credentials.from_dict(x) for x in _dict.get('credentials') + Credentials.from_dict(v) for v in _dict.get('credentials') ] return cls(**args) @@ -5203,7 +5400,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credentials') and self.credentials is not None: - _dict['credentials'] = [x.to_dict() for x in self.credentials] + credentials_list = [] + for v in self.credentials: + if isinstance(v, dict): + credentials_list.append(v) + else: + credentials_list.append(v.to_dict()) + _dict['credentials'] = credentials_list return _dict def _to_dict(self): @@ -5351,7 +5554,7 @@ def from_dict(cls, _dict: Dict) -> 'DeleteConfigurationResponse': ) if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] return cls(**args) @@ -5369,7 +5572,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list return _dict def _to_dict(self): @@ -5725,7 +5934,7 @@ def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': args['status'] = _dict.get('status') if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] return cls(**args) @@ -5742,7 +5951,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list return _dict def _to_dict(self): @@ -5920,7 +6135,7 @@ def from_dict(cls, _dict: Dict) -> 'DocumentStatus': args['sha1'] = _dict.get('sha1') if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] return cls(**args) @@ -5950,7 +6165,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'sha1') and self.sha1 is not None: _dict['sha1'] = self.sha1 if hasattr(self, 'notices') and getattr(self, 'notices') is not None: - _dict['notices'] = [x.to_dict() for x in getattr(self, 'notices')] + notices_list = [] + for v in getattr(self, 'notices'): + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list return _dict def _to_dict(self): @@ -6121,7 +6342,10 @@ def to_dict(self) -> Dict: ) and self.ignore_downstream_errors is not None: _dict['ignore_downstream_errors'] = self.ignore_downstream_errors if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -6158,8 +6382,8 @@ class EnrichmentOptions(): (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. - :attr str model: (optional) The element extraction model to use, which can be - `contract` only. The `elements` enrichment is deprecated. + :attr str model: (optional) Deprecated: The element extraction model to use, + which can be `contract` only. The `elements` enrichment is deprecated. """ def __init__(self, @@ -6178,8 +6402,8 @@ def __init__(self, `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. - :param str model: (optional) The element extraction model to use, which can - be `contract` only. The `elements` enrichment is deprecated. + :param str model: (optional) Deprecated: The element extraction model to + use, which can be `contract` only. The `elements` enrichment is deprecated. """ self.features = features self.language = language @@ -6207,7 +6431,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'features') and self.features is not None: - _dict['features'] = self.features.to_dict() + if isinstance(self.features, dict): + _dict['features'] = self.features + else: + _dict['features'] = self.features.to_dict() if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'model') and self.model is not None: @@ -6377,9 +6604,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'requested_size') and self.requested_size is not None: _dict['requested_size'] = self.requested_size if hasattr(self, 'index_capacity') and self.index_capacity is not None: - _dict['index_capacity'] = self.index_capacity.to_dict() + if isinstance(self.index_capacity, dict): + _dict['index_capacity'] = self.index_capacity + else: + _dict['index_capacity'] = self.index_capacity.to_dict() if hasattr(self, 'search_status') and self.search_status is not None: - _dict['search_status'] = self.search_status.to_dict() + if isinstance(self.search_status, dict): + _dict['search_status'] = self.search_status + else: + _dict['search_status'] = self.search_status.to_dict() return _dict def _to_dict(self): @@ -6751,7 +6984,7 @@ def from_dict(cls, _dict: Dict) -> 'Expansions': args = {} if 'expansions' in _dict: args['expansions'] = [ - Expansion.from_dict(x) for x in _dict.get('expansions') + Expansion.from_dict(v) for v in _dict.get('expansions') ] else: raise ValueError( @@ -6768,7 +7001,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'expansions') and self.expansions is not None: - _dict['expansions'] = [x.to_dict() for x in self.expansions] + expansions_list = [] + for v in self.expansions: + if isinstance(v, dict): + expansions_list.append(v) + else: + expansions_list.append(v.to_dict()) + _dict['expansions'] = expansions_list return _dict def _to_dict(self): @@ -7154,7 +7393,7 @@ def from_dict(cls, _dict: Dict) -> 'GatewayList': args = {} if 'gateways' in _dict: args['gateways'] = [ - Gateway.from_dict(x) for x in _dict.get('gateways') + Gateway.from_dict(v) for v in _dict.get('gateways') ] return cls(**args) @@ -7167,7 +7406,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'gateways') and self.gateways is not None: - _dict['gateways'] = [x.to_dict() for x in self.gateways] + gateways_list = [] + for v in self.gateways: + if isinstance(v, dict): + gateways_list.append(v) + else: + gateways_list.append(v.to_dict()) + _dict['gateways'] = gateways_list return _dict def _to_dict(self): @@ -7275,10 +7520,16 @@ def to_dict(self) -> Dict: ) and self.exclude_tags_keep_content is not None: _dict['exclude_tags_keep_content'] = self.exclude_tags_keep_content if hasattr(self, 'keep_content') and self.keep_content is not None: - _dict['keep_content'] = self.keep_content.to_dict() + if isinstance(self.keep_content, dict): + _dict['keep_content'] = self.keep_content + else: + _dict['keep_content'] = self.keep_content.to_dict() if hasattr(self, 'exclude_content') and self.exclude_content is not None: - _dict['exclude_content'] = self.exclude_content.to_dict() + if isinstance(self.exclude_content, dict): + _dict['exclude_content'] = self.exclude_content + else: + _dict['exclude_content'] = self.exclude_content.to_dict() if hasattr( self, 'keep_tag_attributes') and self.keep_tag_attributes is not None: @@ -7361,11 +7612,20 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'documents') and self.documents is not None: - _dict['documents'] = self.documents.to_dict() + if isinstance(self.documents, dict): + _dict['documents'] = self.documents + else: + _dict['documents'] = self.documents.to_dict() if hasattr(self, 'disk_usage') and self.disk_usage is not None: - _dict['disk_usage'] = self.disk_usage.to_dict() + if isinstance(self.disk_usage, dict): + _dict['disk_usage'] = self.disk_usage + else: + _dict['disk_usage'] = self.disk_usage.to_dict() if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = self.collections.to_dict() + if isinstance(self.collections, dict): + _dict['collections'] = self.collections + else: + _dict['collections'] = self.collections.to_dict() return _dict def _to_dict(self): @@ -7418,7 +7678,7 @@ def from_dict(cls, _dict: Dict) -> 'ListCollectionFieldsResponse': """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" args = {} if 'fields' in _dict: - args['fields'] = [Field.from_dict(x) for x in _dict.get('fields')] + args['fields'] = [Field.from_dict(v) for v in _dict.get('fields')] return cls(**args) @classmethod @@ -7430,7 +7690,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = [x.to_dict() for x in self.fields] + fields_list = [] + for v in self.fields: + if isinstance(v, dict): + fields_list.append(v) + else: + fields_list.append(v.to_dict()) + _dict['fields'] = fields_list return _dict def _to_dict(self): @@ -7475,7 +7741,7 @@ def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': args = {} if 'collections' in _dict: args['collections'] = [ - Collection.from_dict(x) for x in _dict.get('collections') + Collection.from_dict(v) for v in _dict.get('collections') ] return cls(**args) @@ -7488,7 +7754,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = [x.to_dict() for x in self.collections] + collections_list = [] + for v in self.collections: + if isinstance(v, dict): + collections_list.append(v) + else: + collections_list.append(v.to_dict()) + _dict['collections'] = collections_list return _dict def _to_dict(self): @@ -7533,7 +7805,7 @@ def from_dict(cls, _dict: Dict) -> 'ListConfigurationsResponse': args = {} if 'configurations' in _dict: args['configurations'] = [ - Configuration.from_dict(x) for x in _dict.get('configurations') + Configuration.from_dict(v) for v in _dict.get('configurations') ] return cls(**args) @@ -7546,7 +7818,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'configurations') and self.configurations is not None: - _dict['configurations'] = [x.to_dict() for x in self.configurations] + configurations_list = [] + for v in self.configurations: + if isinstance(v, dict): + configurations_list.append(v) + else: + configurations_list.append(v.to_dict()) + _dict['configurations'] = configurations_list return _dict def _to_dict(self): @@ -7591,7 +7869,7 @@ def from_dict(cls, _dict: Dict) -> 'ListEnvironmentsResponse': args = {} if 'environments' in _dict: args['environments'] = [ - Environment.from_dict(x) for x in _dict.get('environments') + Environment.from_dict(v) for v in _dict.get('environments') ] return cls(**args) @@ -7604,7 +7882,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'environments') and self.environments is not None: - _dict['environments'] = [x.to_dict() for x in self.environments] + environments_list = [] + for v in self.environments: + if isinstance(v, dict): + environments_list.append(v) + else: + environments_list.append(v.to_dict()) + _dict['environments'] = environments_list return _dict def _to_dict(self): @@ -7657,8 +7941,8 @@ def from_dict(cls, _dict: Dict) -> 'LogQueryResponse': args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - LogQueryResponseResult.from_dict(x) - for x in _dict.get('results') + LogQueryResponseResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -7674,7 +7958,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -7895,7 +8185,10 @@ def to_dict(self) -> Dict: _dict['natural_language_query'] = self.natural_language_query if hasattr(self, 'document_results') and self.document_results is not None: - _dict['document_results'] = self.document_results.to_dict() + if isinstance(self.document_results, dict): + _dict['document_results'] = self.document_results + else: + _dict['document_results'] = self.document_results.to_dict() if hasattr(self, 'created_timestamp') and self.created_timestamp is not None: _dict['created_timestamp'] = datetime_to_string( @@ -7997,8 +8290,8 @@ def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocuments': args = {} if 'results' in _dict: args['results'] = [ - LogQueryResponseResultDocumentsResult.from_dict(x) - for x in _dict.get('results') + LogQueryResponseResultDocumentsResult.from_dict(v) + for v in _dict.get('results') ] if 'count' in _dict: args['count'] = _dict.get('count') @@ -8013,7 +8306,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count return _dict @@ -8177,8 +8476,8 @@ def from_dict(cls, _dict: Dict) -> 'MetricAggregation': args['event_type'] = _dict.get('event_type') if 'results' in _dict: args['results'] = [ - MetricAggregationResult.from_dict(x) - for x in _dict.get('results') + MetricAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -8195,7 +8494,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'event_type') and self.event_type is not None: _dict['event_type'] = self.event_type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8332,8 +8637,8 @@ def from_dict(cls, _dict: Dict) -> 'MetricResponse': args = {} if 'aggregations' in _dict: args['aggregations'] = [ - MetricAggregation.from_dict(x) - for x in _dict.get('aggregations') + MetricAggregation.from_dict(v) + for v in _dict.get('aggregations') ] return cls(**args) @@ -8346,7 +8651,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -8401,8 +8712,8 @@ def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregation': args['event_type'] = _dict.get('event_type') if 'results' in _dict: args['results'] = [ - MetricTokenAggregationResult.from_dict(x) - for x in _dict.get('results') + MetricTokenAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -8417,7 +8728,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'event_type') and self.event_type is not None: _dict['event_type'] = self.event_type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -8543,8 +8860,8 @@ def from_dict(cls, _dict: Dict) -> 'MetricTokenResponse': args = {} if 'aggregations' in _dict: args['aggregations'] = [ - MetricTokenAggregation.from_dict(x) - for x in _dict.get('aggregations') + MetricTokenAggregation.from_dict(v) + for v in _dict.get('aggregations') ] return cls(**args) @@ -8557,7 +8874,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -8926,21 +9249,42 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = self.keywords.to_dict() + if isinstance(self.keywords, dict): + _dict['keywords'] = self.keywords + else: + _dict['keywords'] = self.keywords.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = self.entities.to_dict() + if isinstance(self.entities, dict): + _dict['entities'] = self.entities + else: + _dict['entities'] = self.entities.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'categories') and self.categories is not None: _dict['categories'] = self.categories if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = self.semantic_roles.to_dict() + if isinstance(self.semantic_roles, dict): + _dict['semantic_roles'] = self.semantic_roles + else: + _dict['semantic_roles'] = self.semantic_roles.to_dict() if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = self.relations.to_dict() + if isinstance(self.relations, dict): + _dict['relations'] = self.relations + else: + _dict['relations'] = self.relations.to_dict() if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = self.concepts.to_dict() + if isinstance(self.concepts, dict): + _dict['concepts'] = self.concepts + else: + _dict['concepts'] = self.concepts.to_dict() return _dict def _to_dict(self): @@ -9550,7 +9894,7 @@ def from_dict(cls, _dict: Dict) -> 'PdfHeadingDetection': args = {} if 'fonts' in _dict: args['fonts'] = [ - FontSetting.from_dict(x) for x in _dict.get('fonts') + FontSetting.from_dict(v) for v in _dict.get('fonts') ] return cls(**args) @@ -9563,7 +9907,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fonts') and self.fonts is not None: - _dict['fonts'] = [x.to_dict() for x in self.fonts] + fonts_list = [] + for v in self.fonts: + if isinstance(v, dict): + fonts_list.append(v) + else: + fonts_list.append(v.to_dict()) + _dict['fonts'] = fonts_list return _dict def _to_dict(self): @@ -9620,7 +9970,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'heading') and self.heading is not None: - _dict['heading'] = self.heading.to_dict() + if isinstance(self.heading, dict): + _dict['heading'] = self.heading + else: + _dict['heading'] = self.heading.to_dict() return _dict def _to_dict(self): @@ -9780,7 +10133,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -9798,7 +10151,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -9869,15 +10228,15 @@ def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - QueryNoticesResult.from_dict(x) for x in _dict.get('results') + QueryNoticesResult.from_dict(v) for v in _dict.get('results') ] if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] if 'passages' in _dict: args['passages'] = [ - QueryPassages.from_dict(x) for x in _dict.get('passages') + QueryPassages.from_dict(v) for v in _dict.get('passages') ] if 'duplicates_removed' in _dict: args['duplicates_removed'] = _dict.get('duplicates_removed') @@ -9895,11 +10254,29 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x.to_dict() for x in self.passages] + passages_list = [] + for v in self.passages: + if isinstance(v, dict): + passages_list.append(v) + else: + passages_list.append(v.to_dict()) + _dict['passages'] = passages_list if hasattr( self, 'duplicates_removed') and self.duplicates_removed is not None: @@ -10017,7 +10394,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryNoticesResult': args['sha1'] = _dict.get('sha1') if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) @@ -10039,7 +10416,10 @@ def to_dict(self) -> Dict: _dict['collection_id'] = self.collection_id if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() if hasattr(self, 'code') and self.code is not None: _dict['code'] = self.code if hasattr(self, 'filename') and self.filename is not None: @@ -10049,13 +10429,18 @@ def to_dict(self) -> Dict: if hasattr(self, 'sha1') and self.sha1 is not None: _dict['sha1'] = self.sha1 if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list for _key in [ k for k in vars(self).keys() if k not in QueryNoticesResult._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -10288,15 +10673,15 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponse': args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - QueryResult.from_dict(x) for x in _dict.get('results') + QueryResult.from_dict(v) for v in _dict.get('results') ] if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] if 'passages' in _dict: args['passages'] = [ - QueryPassages.from_dict(x) for x in _dict.get('passages') + QueryPassages.from_dict(v) for v in _dict.get('passages') ] if 'duplicates_removed' in _dict: args['duplicates_removed'] = _dict.get('duplicates_removed') @@ -10321,11 +10706,29 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x.to_dict() for x in self.passages] + passages_list = [] + for v in self.passages: + if isinstance(v, dict): + passages_list.append(v) + else: + passages_list.append(v.to_dict()) + _dict['passages'] = passages_list if hasattr( self, 'duplicates_removed') and self.duplicates_removed is not None: @@ -10334,7 +10737,10 @@ def to_dict(self) -> Dict: _dict['session_token'] = self.session_token if hasattr(self, 'retrieval_details') and self.retrieval_details is not None: - _dict['retrieval_details'] = self.retrieval_details.to_dict() + if isinstance(self.retrieval_details, dict): + _dict['retrieval_details'] = self.retrieval_details + else: + _dict['retrieval_details'] = self.retrieval_details.to_dict() if hasattr(self, 'suggested_query') and self.suggested_query is not None: _dict['suggested_query'] = self.suggested_query @@ -10433,12 +10839,14 @@ def to_dict(self) -> Dict: _dict['collection_id'] = self.collection_id if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() for _key in [ k for k in vars(self).keys() if k not in QueryResult._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -10634,7 +11042,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': 'estimated_matching_documents') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -10661,7 +11069,13 @@ def to_dict(self) -> Dict: _dict[ 'estimated_matching_documents'] = self.estimated_matching_documents if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -10744,7 +11158,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -10764,7 +11178,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -11046,7 +11466,10 @@ def to_dict(self) -> Dict: 'total_documents') and self.total_documents is not None: _dict['total_documents'] = self.total_documents if hasattr(self, 'custom_fields') and self.custom_fields is not None: - _dict['custom_fields'] = self.custom_fields.to_dict() + if isinstance(self.custom_fields, dict): + _dict['custom_fields'] = self.custom_fields + else: + _dict['custom_fields'] = self.custom_fields.to_dict() return _dict def _to_dict(self): @@ -11423,9 +11846,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'credential_id') and self.credential_id is not None: _dict['credential_id'] = self.credential_id if hasattr(self, 'schedule') and self.schedule is not None: - _dict['schedule'] = self.schedule.to_dict() + if isinstance(self.schedule, dict): + _dict['schedule'] = self.schedule + else: + _dict['schedule'] = self.schedule.to_dict() if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -11536,24 +11965,24 @@ def from_dict(cls, _dict: Dict) -> 'SourceOptions': args = {} if 'folders' in _dict: args['folders'] = [ - SourceOptionsFolder.from_dict(x) for x in _dict.get('folders') + SourceOptionsFolder.from_dict(v) for v in _dict.get('folders') ] if 'objects' in _dict: args['objects'] = [ - SourceOptionsObject.from_dict(x) for x in _dict.get('objects') + SourceOptionsObject.from_dict(v) for v in _dict.get('objects') ] if 'site_collections' in _dict: args['site_collections'] = [ - SourceOptionsSiteColl.from_dict(x) - for x in _dict.get('site_collections') + SourceOptionsSiteColl.from_dict(v) + for v in _dict.get('site_collections') ] if 'urls' in _dict: args['urls'] = [ - SourceOptionsWebCrawl.from_dict(x) for x in _dict.get('urls') + SourceOptionsWebCrawl.from_dict(v) for v in _dict.get('urls') ] if 'buckets' in _dict: args['buckets'] = [ - SourceOptionsBuckets.from_dict(x) for x in _dict.get('buckets') + SourceOptionsBuckets.from_dict(v) for v in _dict.get('buckets') ] if 'crawl_all_buckets' in _dict: args['crawl_all_buckets'] = _dict.get('crawl_all_buckets') @@ -11568,18 +11997,46 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'folders') and self.folders is not None: - _dict['folders'] = [x.to_dict() for x in self.folders] + folders_list = [] + for v in self.folders: + if isinstance(v, dict): + folders_list.append(v) + else: + folders_list.append(v.to_dict()) + _dict['folders'] = folders_list if hasattr(self, 'objects') and self.objects is not None: - _dict['objects'] = [x.to_dict() for x in self.objects] + objects_list = [] + for v in self.objects: + if isinstance(v, dict): + objects_list.append(v) + else: + objects_list.append(v.to_dict()) + _dict['objects'] = objects_list if hasattr(self, 'site_collections') and self.site_collections is not None: - _dict['site_collections'] = [ - x.to_dict() for x in self.site_collections - ] + site_collections_list = [] + for v in self.site_collections: + if isinstance(v, dict): + site_collections_list.append(v) + else: + site_collections_list.append(v.to_dict()) + _dict['site_collections'] = site_collections_list if hasattr(self, 'urls') and self.urls is not None: - _dict['urls'] = [x.to_dict() for x in self.urls] + urls_list = [] + for v in self.urls: + if isinstance(v, dict): + urls_list.append(v) + else: + urls_list.append(v.to_dict()) + _dict['urls'] = urls_list if hasattr(self, 'buckets') and self.buckets is not None: - _dict['buckets'] = [x.to_dict() for x in self.buckets] + buckets_list = [] + for v in self.buckets: + if isinstance(v, dict): + buckets_list.append(v) + else: + buckets_list.append(v.to_dict()) + _dict['buckets'] = buckets_list if hasattr(self, 'crawl_all_buckets') and self.crawl_all_buckets is not None: _dict['crawl_all_buckets'] = self.crawl_all_buckets @@ -12562,7 +13019,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingDataSet': args['collection_id'] = _dict.get('collection_id') if 'queries' in _dict: args['queries'] = [ - TrainingQuery.from_dict(x) for x in _dict.get('queries') + TrainingQuery.from_dict(v) for v in _dict.get('queries') ] return cls(**args) @@ -12579,7 +13036,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'collection_id') and self.collection_id is not None: _dict['collection_id'] = self.collection_id if hasattr(self, 'queries') and self.queries is not None: - _dict['queries'] = [x.to_dict() for x in self.queries] + queries_list = [] + for v in self.queries: + if isinstance(v, dict): + queries_list.append(v) + else: + queries_list.append(v.to_dict()) + _dict['queries'] = queries_list return _dict def _to_dict(self): @@ -12700,7 +13163,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingExampleList': args = {} if 'examples' in _dict: args['examples'] = [ - TrainingExample.from_dict(x) for x in _dict.get('examples') + TrainingExample.from_dict(v) for v in _dict.get('examples') ] return cls(**args) @@ -12713,7 +13176,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list return _dict def _to_dict(self): @@ -12782,7 +13251,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingQuery': args['filter'] = _dict.get('filter') if 'examples' in _dict: args['examples'] = [ - TrainingExample.from_dict(x) for x in _dict.get('examples') + TrainingExample.from_dict(v) for v in _dict.get('examples') ] return cls(**args) @@ -12802,7 +13271,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'filter') and self.filter is not None: _dict['filter'] = self.filter if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list return _dict def _to_dict(self): @@ -13001,11 +13476,11 @@ def from_dict(cls, _dict: Dict) -> 'WordHeadingDetection': args = {} if 'fonts' in _dict: args['fonts'] = [ - FontSetting.from_dict(x) for x in _dict.get('fonts') + FontSetting.from_dict(v) for v in _dict.get('fonts') ] if 'styles' in _dict: args['styles'] = [ - WordStyle.from_dict(x) for x in _dict.get('styles') + WordStyle.from_dict(v) for v in _dict.get('styles') ] return cls(**args) @@ -13018,9 +13493,21 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fonts') and self.fonts is not None: - _dict['fonts'] = [x.to_dict() for x in self.fonts] + fonts_list = [] + for v in self.fonts: + if isinstance(v, dict): + fonts_list.append(v) + else: + fonts_list.append(v.to_dict()) + _dict['fonts'] = fonts_list if hasattr(self, 'styles') and self.styles is not None: - _dict['styles'] = [x.to_dict() for x in self.styles] + styles_list = [] + for v in self.styles: + if isinstance(v, dict): + styles_list.append(v) + else: + styles_list.append(v.to_dict()) + _dict['styles'] = styles_list return _dict def _to_dict(self): @@ -13077,7 +13564,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'heading') and self.heading is not None: - _dict['heading'] = self.heading.to_dict() + if isinstance(self.heading, dict): + _dict['heading'] = self.heading + else: + _dict['heading'] = self.heading.to_dict() return _dict def _to_dict(self): @@ -13350,7 +13840,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -13370,7 +13860,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -13458,8 +13954,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryHistogramAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryHistogramAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -13480,7 +13976,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -13561,7 +14063,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -13581,7 +14083,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -13663,8 +14171,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryTermAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryTermAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -13685,7 +14193,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -13773,8 +14287,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryTimesliceAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryTimesliceAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -13795,7 +14309,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -13886,7 +14406,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits.to_dict() + if isinstance(self.hits, dict): + _dict['hits'] = self.hits + else: + _dict['hits'] = self.hits.to_dict() return _dict def _to_dict(self): diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 5f66ab600..8854f1161 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ IBM Watson™ Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive @@ -99,7 +99,9 @@ def list_projects(self, **kwargs) -> DetailedResponse: operation_id='list_projects') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -151,12 +153,14 @@ def create_project(self, operation_id='create_project') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, 'type': type, - 'default_query_parameters': default_query_parameters + 'default_query_parameters': default_query_parameters, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -190,7 +194,7 @@ def get_project(self, project_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -198,7 +202,9 @@ def get_project(self, project_id: str, **kwargs) -> DetailedResponse: operation_id='get_project') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -235,7 +241,7 @@ def update_project(self, :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -243,9 +249,13 @@ def update_project(self, operation_id='update_project') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'name': name} + data = { + 'name': name, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -283,7 +293,7 @@ def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -291,7 +301,9 @@ def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: operation_id='delete_project') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -330,7 +342,7 @@ def list_fields(self, :rtype: DetailedResponse with `dict` result representing a `ListFieldsResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -340,7 +352,7 @@ def list_fields(self, params = { 'version': self.version, - 'collection_ids': convert_list(collection_ids) + 'collection_ids': convert_list(collection_ids), } if 'headers' in kwargs: @@ -377,7 +389,7 @@ def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -385,7 +397,9 @@ def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: operation_id='list_collections') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -411,8 +425,6 @@ def create_collection(self, description: str = None, language: str = None, enrichments: List['CollectionEnrichment'] = None, - smart_document_understanding: - 'CollectionDetailsSmartDocumentUnderstanding' = None, **kwargs) -> DetailedResponse: """ Create a collection. @@ -434,37 +446,32 @@ def create_collection(self, enrichments for the project type are applied. For more information about project default settings, see the [product documentation](/docs/discovery-data?topic=discovery-data-project-defaults). - :param CollectionDetailsSmartDocumentUnderstanding - smart_document_understanding: (optional) An object that describes the Smart - Document Understanding model for a collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') if name is None: raise ValueError('name must be provided') if enrichments is not None: enrichments = [convert_model(x) for x in enrichments] - if smart_document_understanding is not None: - smart_document_understanding = convert_model( - smart_document_understanding) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='create_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, 'description': description, 'language': language, 'enrichments': enrichments, - 'smart_document_understanding': smart_document_understanding } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -503,9 +510,9 @@ def get_collection(self, project_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -513,7 +520,9 @@ def get_collection(self, project_id: str, collection_id: str, operation_id='get_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -558,9 +567,9 @@ def update_collection(self, :rtype: DetailedResponse with `dict` result representing a `CollectionDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if enrichments is not None: enrichments = [convert_model(x) for x in enrichments] @@ -570,12 +579,14 @@ def update_collection(self, operation_id='update_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, 'description': description, - 'enrichments': enrichments + 'enrichments': enrichments, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -616,9 +627,9 @@ def delete_collection(self, project_id: str, collection_id: str, :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -626,7 +637,9 @@ def delete_collection(self, project_id: str, collection_id: str, operation_id='delete_collection') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -711,9 +724,9 @@ def list_documents(self, :rtype: DetailedResponse with `dict` result representing a `ListDocumentsResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -728,7 +741,7 @@ def list_documents(self, 'has_notices': has_notices, 'is_parent': is_parent, 'parent_document_id': parent_document_id, - 'sha256': sha256 + 'sha256': sha256, } if 'headers' in kwargs: @@ -814,17 +827,21 @@ def add_document(self, :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} + headers = { + 'X-Watson-Discovery-Force': x_watson_discovery_force, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='add_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if file: @@ -876,11 +893,11 @@ def get_document(self, project_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `DocumentDetails` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -888,7 +905,9 @@ def get_document(self, project_id: str, collection_id: str, operation_id='get_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -967,19 +986,23 @@ def update_document(self, :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} + headers = { + 'X-Watson-Discovery-Force': x_watson_discovery_force, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='update_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if file: @@ -1043,19 +1066,23 @@ def delete_document(self, :rtype: DetailedResponse with `dict` result representing a `DeleteDocumentResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') - headers = {'X-Watson-Discovery-Force': x_watson_discovery_force} + headers = { + 'X-Watson-Discovery-Force': x_watson_discovery_force, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', operation_id='delete_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1179,7 +1206,7 @@ def query(self, :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') if table_results is not None: table_results = convert_model(table_results) @@ -1195,7 +1222,9 @@ def query(self, operation_id='query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'collection_ids': collection_ids, @@ -1212,7 +1241,7 @@ def query(self, 'table_results': table_results, 'suggested_refinements': suggested_refinements, 'passages': passages, - 'similar': similar + 'similar': similar, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1265,9 +1294,9 @@ def get_autocompletion(self, :rtype: DetailedResponse with `dict` result representing a `Completions` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if prefix is None: + if not prefix: raise ValueError('prefix must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1280,7 +1309,7 @@ def get_autocompletion(self, 'prefix': prefix, 'collection_ids': convert_list(collection_ids), 'field': field, - 'count': count + 'count': count, } if 'headers' in kwargs: @@ -1346,9 +1375,9 @@ def query_collection_notices(self, :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1362,7 +1391,7 @@ def query_collection_notices(self, 'query': query, 'natural_language_query': natural_language_query, 'count': count, - 'offset': offset + 'offset': offset, } if 'headers' in kwargs: @@ -1426,7 +1455,7 @@ def query_notices(self, :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1440,7 +1469,7 @@ def query_notices(self, 'query': query, 'natural_language_query': natural_language_query, 'count': count, - 'offset': offset + 'offset': offset, } if 'headers' in kwargs: @@ -1481,9 +1510,9 @@ def get_stopword_list(self, project_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `StopWordList` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1491,7 +1520,9 @@ def get_stopword_list(self, project_id: str, collection_id: str, operation_id='get_stopword_list') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1543,9 +1574,9 @@ def create_stopword_list(self, :rtype: DetailedResponse with `dict` result representing a `StopWordList` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1553,9 +1584,13 @@ def create_stopword_list(self, operation_id='create_stopword_list') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'stopwords': stopwords} + data = { + 'stopwords': stopwords, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -1596,9 +1631,9 @@ def delete_stopword_list(self, project_id: str, collection_id: str, :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1606,7 +1641,9 @@ def delete_stopword_list(self, project_id: str, collection_id: str, operation_id='delete_stopword_list') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1641,9 +1678,9 @@ def list_expansions(self, project_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1651,7 +1688,9 @@ def list_expansions(self, project_id: str, collection_id: str, operation_id='list_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1704,9 +1743,9 @@ def create_expansions(self, project_id: str, collection_id: str, :rtype: DetailedResponse with `dict` result representing a `Expansions` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') if expansions is None: raise ValueError('expansions must be provided') @@ -1717,9 +1756,13 @@ def create_expansions(self, project_id: str, collection_id: str, operation_id='create_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'expansions': expansions} + data = { + 'expansions': expansions, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -1759,9 +1802,9 @@ def delete_expansions(self, project_id: str, collection_id: str, :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1769,7 +1812,9 @@ def delete_expansions(self, project_id: str, collection_id: str, operation_id='delete_expansions') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1806,7 +1851,7 @@ def get_component_settings(self, project_id: str, :rtype: DetailedResponse with `dict` result representing a `ComponentSettingsResponse` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1814,7 +1859,9 @@ def get_component_settings(self, project_id: str, operation_id='get_component_settings') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1852,7 +1899,7 @@ def list_training_queries(self, project_id: str, :rtype: DetailedResponse with `dict` result representing a `TrainingQuerySet` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1860,7 +1907,9 @@ def list_training_queries(self, project_id: str, operation_id='list_training_queries') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1894,7 +1943,7 @@ def delete_training_queries(self, project_id: str, :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1902,7 +1951,9 @@ def delete_training_queries(self, project_id: str, operation_id='delete_training_queries') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1946,7 +1997,7 @@ def create_training_query(self, :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') if natural_language_query is None: raise ValueError('natural_language_query must be provided') @@ -1959,12 +2010,14 @@ def create_training_query(self, operation_id='create_training_query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'natural_language_query': natural_language_query, 'examples': examples, - 'filter': filter + 'filter': filter, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2005,9 +2058,9 @@ def get_training_query(self, project_id: str, query_id: str, :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2015,7 +2068,9 @@ def get_training_query(self, project_id: str, query_id: str, operation_id='get_training_query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2061,9 +2116,9 @@ def update_training_query(self, :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') if natural_language_query is None: raise ValueError('natural_language_query must be provided') @@ -2076,12 +2131,14 @@ def update_training_query(self, operation_id='update_training_query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'natural_language_query': natural_language_query, 'examples': examples, - 'filter': filter + 'filter': filter, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2122,9 +2179,9 @@ def delete_training_query(self, project_id: str, query_id: str, :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if query_id is None: + if not query_id: raise ValueError('query_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2132,7 +2189,9 @@ def delete_training_query(self, project_id: str, query_id: str, operation_id='delete_training_query') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2170,7 +2229,7 @@ def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `Enrichments` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2178,7 +2237,9 @@ def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: operation_id='list_enrichments') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2225,7 +2286,7 @@ def create_enrichment(self, :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') if enrichment is None: raise ValueError('enrichment must be provided') @@ -2235,7 +2296,9 @@ def create_enrichment(self, operation_id='create_enrichment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append( @@ -2276,9 +2339,9 @@ def get_enrichment(self, project_id: str, enrichment_id: str, :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if enrichment_id is None: + if not enrichment_id: raise ValueError('enrichment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2286,7 +2349,9 @@ def get_enrichment(self, project_id: str, enrichment_id: str, operation_id='get_enrichment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2328,9 +2393,9 @@ def update_enrichment(self, :rtype: DetailedResponse with `dict` result representing a `Enrichment` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if enrichment_id is None: + if not enrichment_id: raise ValueError('enrichment_id must be provided') if name is None: raise ValueError('name must be provided') @@ -2340,9 +2405,14 @@ def update_enrichment(self, operation_id='update_enrichment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'name': name, 'description': description} + data = { + 'name': name, + 'description': description, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -2382,9 +2452,9 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if enrichment_id is None: + if not enrichment_id: raise ValueError('enrichment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2392,7 +2462,9 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, operation_id='delete_enrichment') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2430,7 +2502,7 @@ def list_document_classifiers(self, project_id: str, :rtype: DetailedResponse with `dict` result representing a `DocumentClassifiers` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2438,7 +2510,9 @@ def list_document_classifiers(self, project_id: str, operation_id='list_document_classifiers') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2496,7 +2570,7 @@ def create_document_classifier(self, :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') if training_data is None: raise ValueError('training_data must be provided') @@ -2508,7 +2582,9 @@ def create_document_classifier(self, operation_id='create_document_classifier') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('training_data', (None, training_data, 'text/csv'))) @@ -2551,9 +2627,9 @@ def get_document_classifier(self, project_id: str, classifier_id: str, :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if classifier_id is None: + if not classifier_id: raise ValueError('classifier_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2561,7 +2637,9 @@ def get_document_classifier(self, project_id: str, classifier_id: str, operation_id='get_document_classifier') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2617,9 +2695,9 @@ def update_document_classifier(self, :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if classifier_id is None: + if not classifier_id: raise ValueError('classifier_id must be provided') if classifier is None: raise ValueError('classifier must be provided') @@ -2629,7 +2707,9 @@ def update_document_classifier(self, operation_id='update_document_classifier') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append( @@ -2674,9 +2754,9 @@ def delete_document_classifier(self, project_id: str, classifier_id: str, :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if classifier_id is None: + if not classifier_id: raise ValueError('classifier_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2684,7 +2764,9 @@ def delete_document_classifier(self, project_id: str, classifier_id: str, operation_id='delete_document_classifier') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2724,9 +2806,9 @@ def list_document_classifier_models(self, project_id: str, :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModels` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if classifier_id is None: + if not classifier_id: raise ValueError('classifier_id must be provided') headers = {} sdk_headers = get_sdk_headers( @@ -2735,7 +2817,9 @@ def list_document_classifier_models(self, project_id: str, operation_id='list_document_classifier_models') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2808,9 +2892,9 @@ def create_document_classifier_model( :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if classifier_id is None: + if not classifier_id: raise ValueError('classifier_id must be provided') if name is None: raise ValueError('name must be provided') @@ -2821,7 +2905,9 @@ def create_document_classifier_model( operation_id='create_document_classifier_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'name': name, @@ -2830,7 +2916,7 @@ def create_document_classifier_model( 'l1_regularization_strengths': l1_regularization_strengths, 'l2_regularization_strengths': l2_regularization_strengths, 'training_max_steps': training_max_steps, - 'improvement_ratio': improvement_ratio + 'improvement_ratio': improvement_ratio, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2872,11 +2958,11 @@ def get_document_classifier_model(self, project_id: str, classifier_id: str, :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if classifier_id is None: + if not classifier_id: raise ValueError('classifier_id must be provided') - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers( @@ -2885,7 +2971,9 @@ def get_document_classifier_model(self, project_id: str, classifier_id: str, operation_id='get_document_classifier_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2930,11 +3018,11 @@ def update_document_classifier_model(self, :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if classifier_id is None: + if not classifier_id: raise ValueError('classifier_id must be provided') - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers( @@ -2943,9 +3031,14 @@ def update_document_classifier_model(self, operation_id='update_document_classifier_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } - data = {'name': name, 'description': description} + data = { + 'name': name, + 'description': description, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -2987,11 +3080,11 @@ def delete_document_classifier_model(self, project_id: str, :rtype: DetailedResponse """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if classifier_id is None: + if not classifier_id: raise ValueError('classifier_id must be provided') - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers( @@ -3000,7 +3093,9 @@ def delete_document_classifier_model(self, project_id: str, operation_id='delete_document_classifier_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3074,9 +3169,9 @@ def analyze_document(self, :rtype: DetailedResponse with `dict` result representing a `AnalyzedDocument` object """ - if project_id is None: + if not project_id: raise ValueError('project_id must be provided') - if collection_id is None: + if not collection_id: raise ValueError('collection_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3084,7 +3179,9 @@ def analyze_document(self, operation_id='analyze_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if file: @@ -3139,7 +3236,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3147,7 +3244,10 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: operation_id='delete_user_data') headers.update(sdk_headers) - params = {'version': self.version, 'customer_id': customer_id} + params = { + 'version': self.version, + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3249,7 +3349,7 @@ def from_dict(cls, _dict: Dict) -> 'AnalyzedDocument': args = {} if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] if 'result' in _dict: args['result'] = AnalyzedResult.from_dict(_dict.get('result')) @@ -3264,9 +3364,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list if hasattr(self, 'result') and self.result is not None: - _dict['result'] = self.result.to_dict() + if isinstance(self.result, dict): + _dict['result'] = self.result + else: + _dict['result'] = self.result.to_dict() return _dict def _to_dict(self): @@ -3334,8 +3443,7 @@ def to_dict(self) -> Dict: k for k in vars(self).keys() if k not in AnalyzedResult._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -3499,8 +3607,8 @@ def from_dict(cls, _dict: Dict) -> 'ClassifierModelEvaluation': ) if 'per_class' in _dict: args['per_class'] = [ - PerClassModelEvaluation.from_dict(x) - for x in _dict.get('per_class') + PerClassModelEvaluation.from_dict(v) + for v in _dict.get('per_class') ] else: raise ValueError( @@ -3517,11 +3625,23 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'micro_average') and self.micro_average is not None: - _dict['micro_average'] = self.micro_average.to_dict() + if isinstance(self.micro_average, dict): + _dict['micro_average'] = self.micro_average + else: + _dict['micro_average'] = self.micro_average.to_dict() if hasattr(self, 'macro_average') and self.macro_average is not None: - _dict['macro_average'] = self.macro_average.to_dict() + if isinstance(self.macro_average, dict): + _dict['macro_average'] = self.macro_average + else: + _dict['macro_average'] = self.macro_average.to_dict() if hasattr(self, 'per_class') and self.per_class is not None: - _dict['per_class'] = [x.to_dict() for x in self.per_class] + per_class_list = [] + for v in self.per_class: + if isinstance(v, dict): + per_class_list.append(v) + else: + per_class_list.append(v.to_dict()) + _dict['per_class'] = per_class_list return _dict def _to_dict(self): @@ -3655,9 +3775,6 @@ def __init__( enrichments for the project type are applied. For more information about project default settings, see the [product documentation](/docs/discovery-data?topic=discovery-data-project-defaults). - :param CollectionDetailsSmartDocumentUnderstanding - smart_document_understanding: (optional) An object that describes the Smart - Document Understanding model for a collection. """ self.collection_id = collection_id self.name = name @@ -3687,8 +3804,8 @@ def from_dict(cls, _dict: Dict) -> 'CollectionDetails': args['language'] = _dict.get('language') if 'enrichments' in _dict: args['enrichments'] = [ - CollectionEnrichment.from_dict(x) - for x in _dict.get('enrichments') + CollectionEnrichment.from_dict(v) + for v in _dict.get('enrichments') ] if 'smart_document_understanding' in _dict: args[ @@ -3716,12 +3833,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x.to_dict() for x in self.enrichments] - if hasattr(self, 'smart_document_understanding' - ) and self.smart_document_understanding is not None: - _dict[ - 'smart_document_understanding'] = self.smart_document_understanding.to_dict( - ) + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list + if hasattr(self, 'smart_document_understanding') and getattr( + self, 'smart_document_understanding') is not None: + if isinstance(getattr(self, 'smart_document_understanding'), dict): + _dict['smart_document_understanding'] = getattr( + self, 'smart_document_understanding') + else: + _dict['smart_document_understanding'] = getattr( + self, 'smart_document_understanding').to_dict() return _dict def _to_dict(self): @@ -4128,9 +4254,15 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body.to_dict() + if isinstance(self.body, dict): + _dict['body'] = self.body + else: + _dict['body'] = self.body.to_dict() if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title.to_dict() + if isinstance(self.title, dict): + _dict['title'] = self.title + else: + _dict['title'] = self.title.to_dict() return _dict def _to_dict(self): @@ -4323,8 +4455,8 @@ def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': args['results_per_page'] = _dict.get('results_per_page') if 'aggregations' in _dict: args['aggregations'] = [ - ComponentSettingsAggregation.from_dict(x) - for x in _dict.get('aggregations') + ComponentSettingsAggregation.from_dict(v) + for v in _dict.get('aggregations') ] return cls(**args) @@ -4337,7 +4469,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fields_shown') and self.fields_shown is not None: - _dict['fields_shown'] = self.fields_shown.to_dict() + if isinstance(self.fields_shown, dict): + _dict['fields_shown'] = self.fields_shown + else: + _dict['fields_shown'] = self.fields_shown.to_dict() if hasattr(self, 'autocomplete') and self.autocomplete is not None: _dict['autocomplete'] = self.autocomplete if hasattr(self, @@ -4347,7 +4482,13 @@ def to_dict(self) -> Dict: 'results_per_page') and self.results_per_page is not None: _dict['results_per_page'] = self.results_per_page if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -4452,8 +4593,8 @@ def from_dict(cls, _dict: Dict) -> 'CreateDocumentClassifier': ) if 'enrichments' in _dict: args['enrichments'] = [ - DocumentClassifierEnrichment.from_dict(x) - for x in _dict.get('enrichments') + DocumentClassifierEnrichment.from_dict(v) + for v in _dict.get('enrichments') ] if 'federated_classification' in _dict: args[ @@ -4478,12 +4619,22 @@ def to_dict(self) -> Dict: if hasattr(self, 'answer_field') and self.answer_field is not None: _dict['answer_field'] = self.answer_field if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list if hasattr(self, 'federated_classification' ) and self.federated_classification is not None: - _dict[ - 'federated_classification'] = self.federated_classification.to_dict( - ) + if isinstance(self.federated_classification, dict): + _dict[ + 'federated_classification'] = self.federated_classification + else: + _dict[ + 'federated_classification'] = self.federated_classification.to_dict( + ) return _dict def _to_dict(self): @@ -4604,7 +4755,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -4773,15 +4927,25 @@ def to_dict(self) -> Dict: if hasattr(self, 'collection_ids') and self.collection_ids is not None: _dict['collection_ids'] = self.collection_ids if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = self.passages.to_dict() + if isinstance(self.passages, dict): + _dict['passages'] = self.passages + else: + _dict['passages'] = self.passages.to_dict() if hasattr(self, 'table_results') and self.table_results is not None: - _dict['table_results'] = self.table_results.to_dict() + if isinstance(self.table_results, dict): + _dict['table_results'] = self.table_results + else: + _dict['table_results'] = self.table_results.to_dict() if hasattr(self, 'aggregation') and self.aggregation is not None: _dict['aggregation'] = self.aggregation if hasattr(self, 'suggested_refinements' ) and self.suggested_refinements is not None: - _dict['suggested_refinements'] = self.suggested_refinements.to_dict( - ) + if isinstance(self.suggested_refinements, dict): + _dict['suggested_refinements'] = self.suggested_refinements + else: + _dict[ + 'suggested_refinements'] = self.suggested_refinements.to_dict( + ) if hasattr(self, 'spelling_suggestions' ) and self.spelling_suggestions is not None: _dict['spelling_suggestions'] = self.spelling_suggestions @@ -5270,7 +5434,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -5400,8 +5567,8 @@ def from_dict(cls, _dict: Dict) -> 'DocumentClassifier': args['language'] = _dict.get('language') if 'enrichments' in _dict: args['enrichments'] = [ - DocumentClassifierEnrichment.from_dict(x) - for x in _dict.get('enrichments') + DocumentClassifierEnrichment.from_dict(v) + for v in _dict.get('enrichments') ] if 'recognized_fields' in _dict: args['recognized_fields'] = _dict.get('recognized_fields') @@ -5437,7 +5604,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list if hasattr(self, 'recognized_fields') and self.recognized_fields is not None: _dict['recognized_fields'] = self.recognized_fields @@ -5451,9 +5624,13 @@ def to_dict(self) -> Dict: _dict['test_data_file'] = self.test_data_file if hasattr(self, 'federated_classification' ) and self.federated_classification is not None: - _dict[ - 'federated_classification'] = self.federated_classification.to_dict( - ) + if isinstance(self.federated_classification, dict): + _dict[ + 'federated_classification'] = self.federated_classification + else: + _dict[ + 'federated_classification'] = self.federated_classification.to_dict( + ) return _dict def _to_dict(self): @@ -5676,7 +5853,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'evaluation') and self.evaluation is not None: - _dict['evaluation'] = self.evaluation.to_dict() + if isinstance(self.evaluation, dict): + _dict['evaluation'] = self.evaluation + else: + _dict['evaluation'] = self.evaluation.to_dict() if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: _dict['enrichment_id'] = self.enrichment_id if hasattr(self, 'deployed_at') and getattr(self, @@ -5737,8 +5917,8 @@ def from_dict(cls, _dict: Dict) -> 'DocumentClassifierModels': args = {} if 'models' in _dict: args['models'] = [ - DocumentClassifierModel.from_dict(x) - for x in _dict.get('models') + DocumentClassifierModel.from_dict(v) + for v in _dict.get('models') ] return cls(**args) @@ -5751,7 +5931,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -5798,8 +5984,8 @@ def from_dict(cls, _dict: Dict) -> 'DocumentClassifiers': args = {} if 'classifiers' in _dict: args['classifiers'] = [ - DocumentClassifier.from_dict(x) - for x in _dict.get('classifiers') + DocumentClassifier.from_dict(v) + for v in _dict.get('classifiers') ] return cls(**args) @@ -5812,7 +5998,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'classifiers') and self.classifiers is not None: - _dict['classifiers'] = [x.to_dict() for x in self.classifiers] + classifiers_list = [] + for v in self.classifiers: + if isinstance(v, dict): + classifiers_list.append(v) + else: + classifiers_list.append(v.to_dict()) + _dict['classifiers'] = classifiers_list return _dict def _to_dict(self): @@ -5928,7 +6120,7 @@ def from_dict(cls, _dict: Dict) -> 'DocumentDetails': args['status'] = _dict.get('status') if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] if 'children' in _dict: args['children'] = DocumentDetailsChildren.from_dict( @@ -5959,9 +6151,18 @@ def to_dict(self) -> Dict: if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list if hasattr(self, 'children') and self.children is not None: - _dict['children'] = self.children.to_dict() + if isinstance(self.children, dict): + _dict['children'] = self.children + else: + _dict['children'] = self.children.to_dict() if hasattr(self, 'filename') and self.filename is not None: _dict['filename'] = self.filename if hasattr(self, 'file_type') and self.file_type is not None: @@ -6141,7 +6342,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'options') and self.options is not None: - _dict['options'] = self.options.to_dict() + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -6362,7 +6566,7 @@ def from_dict(cls, _dict: Dict) -> 'Enrichments': args = {} if 'enrichments' in _dict: args['enrichments'] = [ - Enrichment.from_dict(x) for x in _dict.get('enrichments') + Enrichment.from_dict(v) for v in _dict.get('enrichments') ] return cls(**args) @@ -6375,7 +6579,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'enrichments') and self.enrichments is not None: - _dict['enrichments'] = [x.to_dict() for x in self.enrichments] + enrichments_list = [] + for v in self.enrichments: + if isinstance(v, dict): + enrichments_list.append(v) + else: + enrichments_list.append(v.to_dict()) + _dict['enrichments'] = enrichments_list return _dict def _to_dict(self): @@ -6521,7 +6731,7 @@ def from_dict(cls, _dict: Dict) -> 'Expansions': args = {} if 'expansions' in _dict: args['expansions'] = [ - Expansion.from_dict(x) for x in _dict.get('expansions') + Expansion.from_dict(v) for v in _dict.get('expansions') ] else: raise ValueError( @@ -6538,7 +6748,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'expansions') and self.expansions is not None: - _dict['expansions'] = [x.to_dict() for x in self.expansions] + expansions_list = [] + for v in self.expansions: + if isinstance(v, dict): + expansions_list.append(v) + else: + expansions_list.append(v.to_dict()) + _dict['expansions'] = expansions_list return _dict def _to_dict(self): @@ -6670,7 +6886,7 @@ def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': args = {} if 'collections' in _dict: args['collections'] = [ - Collection.from_dict(x) for x in _dict.get('collections') + Collection.from_dict(v) for v in _dict.get('collections') ] return cls(**args) @@ -6683,7 +6899,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'collections') and self.collections is not None: - _dict['collections'] = [x.to_dict() for x in self.collections] + collections_list = [] + for v in self.collections: + if isinstance(v, dict): + collections_list.append(v) + else: + collections_list.append(v.to_dict()) + _dict['collections'] = collections_list return _dict def _to_dict(self): @@ -6742,7 +6964,7 @@ def from_dict(cls, _dict: Dict) -> 'ListDocumentsResponse': args['matching_results'] = _dict.get('matching_results') if 'documents' in _dict: args['documents'] = [ - DocumentDetails.from_dict(x) for x in _dict.get('documents') + DocumentDetails.from_dict(v) for v in _dict.get('documents') ] return cls(**args) @@ -6758,7 +6980,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'documents') and self.documents is not None: - _dict['documents'] = [x.to_dict() for x in self.documents] + documents_list = [] + for v in self.documents: + if isinstance(v, dict): + documents_list.append(v) + else: + documents_list.append(v.to_dict()) + _dict['documents'] = documents_list return _dict def _to_dict(self): @@ -6808,7 +7036,7 @@ def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': """Initialize a ListFieldsResponse object from a json dictionary.""" args = {} if 'fields' in _dict: - args['fields'] = [Field.from_dict(x) for x in _dict.get('fields')] + args['fields'] = [Field.from_dict(v) for v in _dict.get('fields')] return cls(**args) @classmethod @@ -6820,7 +7048,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'fields') and self.fields is not None: - _dict['fields'] = [x.to_dict() for x in self.fields] + fields_list = [] + for v in self.fields: + if isinstance(v, dict): + fields_list.append(v) + else: + fields_list.append(v.to_dict()) + _dict['fields'] = fields_list return _dict def _to_dict(self): @@ -6864,7 +7098,7 @@ def from_dict(cls, _dict: Dict) -> 'ListProjectsResponse': args = {} if 'projects' in _dict: args['projects'] = [ - ProjectListDetails.from_dict(x) for x in _dict.get('projects') + ProjectListDetails.from_dict(v) for v in _dict.get('projects') ] return cls(**args) @@ -6877,7 +7111,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'projects') and self.projects is not None: - _dict['projects'] = [x.to_dict() for x in self.projects] + projects_list = [] + for v in self.projects: + if isinstance(v, dict): + projects_list.append(v) + else: + projects_list.append(v.to_dict()) + _dict['projects'] = projects_list return _dict def _to_dict(self): @@ -7357,8 +7597,6 @@ def __init__(self, project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: - (optional) Relevancy training status information for this project. :param DefaultQueryParams default_query_parameters: (optional) Default query parameters for this project. """ @@ -7405,19 +7643,26 @@ def to_dict(self) -> Dict: _dict['name'] = self.name if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'relevancy_training_status' - ) and self.relevancy_training_status is not None: - _dict[ - 'relevancy_training_status'] = self.relevancy_training_status.to_dict( - ) + if hasattr(self, 'relevancy_training_status') and getattr( + self, 'relevancy_training_status') is not None: + if isinstance(getattr(self, 'relevancy_training_status'), dict): + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status') + else: + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status').to_dict() if hasattr(self, 'collection_count') and getattr( self, 'collection_count') is not None: _dict['collection_count'] = getattr(self, 'collection_count') if hasattr(self, 'default_query_parameters' ) and self.default_query_parameters is not None: - _dict[ - 'default_query_parameters'] = self.default_query_parameters.to_dict( - ) + if isinstance(self.default_query_parameters, dict): + _dict[ + 'default_query_parameters'] = self.default_query_parameters + else: + _dict[ + 'default_query_parameters'] = self.default_query_parameters.to_dict( + ) return _dict def _to_dict(self): @@ -7487,8 +7732,6 @@ def __init__(self, project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: - (optional) Relevancy training status information for this project. """ self.project_id = project_id self.name = name @@ -7529,11 +7772,14 @@ def to_dict(self) -> Dict: _dict['name'] = self.name if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'relevancy_training_status' - ) and self.relevancy_training_status is not None: - _dict[ - 'relevancy_training_status'] = self.relevancy_training_status.to_dict( - ) + if hasattr(self, 'relevancy_training_status') and getattr( + self, 'relevancy_training_status') is not None: + if isinstance(getattr(self, 'relevancy_training_status'), dict): + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status') + else: + _dict['relevancy_training_status'] = getattr( + self, 'relevancy_training_status').to_dict() if hasattr(self, 'collection_count') and getattr( self, 'collection_count') is not None: _dict['collection_count'] = getattr(self, 'collection_count') @@ -7884,7 +8130,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregationResult': 'estimated_matching_documents') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -7911,7 +8157,13 @@ def to_dict(self) -> Dict: _dict[ 'estimated_matching_documents'] = self.estimated_matching_documents if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -7980,7 +8232,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -7998,7 +8250,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -8436,7 +8694,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': args['matching_results'] = _dict.get('matching_results') if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] return cls(**args) @@ -8452,7 +8710,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list return _dict def _to_dict(self): @@ -8488,9 +8752,10 @@ class QueryResponse(): type information. :attr str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. - :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) Array of - suggested refinements. **Note**: The `suggested_refinements` parameter that - identified dynamic facets from the data is deprecated. + :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) + Deprecated: Array of suggested refinements. **Note**: The + `suggested_refinements` parameter that identified dynamic facets from the data + is deprecated. :attr List[QueryTableResult] table_results: (optional) Array of table results. :attr List[QueryResponsePassage] passages: (optional) Passages that best match the query from across all of the collections in the project. @@ -8521,8 +8786,9 @@ def __init__(self, :param str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. :param List[QuerySuggestedRefinement] suggested_refinements: (optional) - Array of suggested refinements. **Note**: The `suggested_refinements` - parameter that identified dynamic facets from the data is deprecated. + Deprecated: Array of suggested refinements. **Note**: The + `suggested_refinements` parameter that identified dynamic facets from the + data is deprecated. :param List[QueryTableResult] table_results: (optional) Array of table results. :param List[QueryResponsePassage] passages: (optional) Passages that best @@ -8545,11 +8811,11 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponse': args['matching_results'] = _dict.get('matching_results') if 'results' in _dict: args['results'] = [ - QueryResult.from_dict(x) for x in _dict.get('results') + QueryResult.from_dict(v) for v in _dict.get('results') ] if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] if 'retrieval_details' in _dict: args['retrieval_details'] = RetrievalDetails.from_dict( @@ -8558,17 +8824,17 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponse': args['suggested_query'] = _dict.get('suggested_query') if 'suggested_refinements' in _dict: args['suggested_refinements'] = [ - QuerySuggestedRefinement.from_dict(x) - for x in _dict.get('suggested_refinements') + QuerySuggestedRefinement.from_dict(v) + for v in _dict.get('suggested_refinements') ] if 'table_results' in _dict: args['table_results'] = [ - QueryTableResult.from_dict(x) - for x in _dict.get('table_results') + QueryTableResult.from_dict(v) + for v in _dict.get('table_results') ] if 'passages' in _dict: args['passages'] = [ - QueryResponsePassage.from_dict(x) for x in _dict.get('passages') + QueryResponsePassage.from_dict(v) for v in _dict.get('passages') ] return cls(**args) @@ -8584,24 +8850,55 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list if hasattr(self, 'retrieval_details') and self.retrieval_details is not None: - _dict['retrieval_details'] = self.retrieval_details.to_dict() + if isinstance(self.retrieval_details, dict): + _dict['retrieval_details'] = self.retrieval_details + else: + _dict['retrieval_details'] = self.retrieval_details.to_dict() if hasattr(self, 'suggested_query') and self.suggested_query is not None: _dict['suggested_query'] = self.suggested_query if hasattr(self, 'suggested_refinements' ) and self.suggested_refinements is not None: - _dict['suggested_refinements'] = [ - x.to_dict() for x in self.suggested_refinements - ] + suggested_refinements_list = [] + for v in self.suggested_refinements: + if isinstance(v, dict): + suggested_refinements_list.append(v) + else: + suggested_refinements_list.append(v.to_dict()) + _dict['suggested_refinements'] = suggested_refinements_list if hasattr(self, 'table_results') and self.table_results is not None: - _dict['table_results'] = [x.to_dict() for x in self.table_results] + table_results_list = [] + for v in self.table_results: + if isinstance(v, dict): + table_results_list.append(v) + else: + table_results_list.append(v.to_dict()) + _dict['table_results'] = table_results_list if hasattr(self, 'passages') and self.passages is not None: - _dict['passages'] = [x.to_dict() for x in self.passages] + passages_list = [] + for v in self.passages: + if isinstance(v, dict): + passages_list.append(v) + else: + passages_list.append(v.to_dict()) + _dict['passages'] = passages_list return _dict def _to_dict(self): @@ -8713,7 +9010,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponsePassage': args['confidence'] = _dict.get('confidence') if 'answers' in _dict: args['answers'] = [ - ResultPassageAnswer.from_dict(x) for x in _dict.get('answers') + ResultPassageAnswer.from_dict(v) for v in _dict.get('answers') ] return cls(**args) @@ -8742,7 +9039,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'answers') and self.answers is not None: - _dict['answers'] = [x.to_dict() for x in self.answers] + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list return _dict def _to_dict(self): @@ -8824,8 +9127,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryResult': ) if 'document_passages' in _dict: args['document_passages'] = [ - QueryResultPassage.from_dict(x) - for x in _dict.get('document_passages') + QueryResultPassage.from_dict(v) + for v in _dict.get('document_passages') ] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) @@ -8845,17 +9148,23 @@ def to_dict(self) -> Dict: _dict['metadata'] = self.metadata if hasattr(self, 'result_metadata') and self.result_metadata is not None: - _dict['result_metadata'] = self.result_metadata.to_dict() + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() if hasattr(self, 'document_passages') and self.document_passages is not None: - _dict['document_passages'] = [ - x.to_dict() for x in self.document_passages - ] + document_passages_list = [] + for v in self.document_passages: + if isinstance(v, dict): + document_passages_list.append(v) + else: + document_passages_list.append(v.to_dict()) + _dict['document_passages'] = document_passages_list for _key in [ k for k in vars(self).keys() if k not in QueryResult._properties ]: - if getattr(self, _key, None) is not None: - _dict[_key] = getattr(self, _key) + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): @@ -9062,7 +9371,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryResultPassage': args['confidence'] = _dict.get('confidence') if 'answers' in _dict: args['answers'] = [ - ResultPassageAnswer.from_dict(x) for x in _dict.get('answers') + ResultPassageAnswer.from_dict(v) for v in _dict.get('answers') ] return cls(**args) @@ -9085,7 +9394,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'answers') and self.answers is not None: - _dict['answers'] = [x.to_dict() for x in self.answers] + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list return _dict def _to_dict(self): @@ -9247,7 +9562,10 @@ def to_dict(self) -> Dict: 'table_html_offset') and self.table_html_offset is not None: _dict['table_html_offset'] = self.table_html_offset if hasattr(self, 'table') and self.table is not None: - _dict['table'] = self.table.to_dict() + if isinstance(self.table, dict): + _dict['table'] = self.table + else: + _dict['table'] = self.table.to_dict() return _dict def _to_dict(self): @@ -9344,7 +9662,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': 'estimated_matching_documents') if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -9371,7 +9689,13 @@ def to_dict(self) -> Dict: _dict[ 'estimated_matching_documents'] = self.estimated_matching_documents if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -9454,7 +9778,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -9474,7 +9798,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -9912,37 +10242,37 @@ def from_dict(cls, _dict: Dict) -> 'TableBodyCells': args['column_index_end'] = _dict.get('column_index_end') if 'row_header_ids' in _dict: args['row_header_ids'] = [ - TableRowHeaderIds.from_dict(x) - for x in _dict.get('row_header_ids') + TableRowHeaderIds.from_dict(v) + for v in _dict.get('row_header_ids') ] if 'row_header_texts' in _dict: args['row_header_texts'] = [ - TableRowHeaderTexts.from_dict(x) - for x in _dict.get('row_header_texts') + TableRowHeaderTexts.from_dict(v) + for v in _dict.get('row_header_texts') ] if 'row_header_texts_normalized' in _dict: args['row_header_texts_normalized'] = [ - TableRowHeaderTextsNormalized.from_dict(x) - for x in _dict.get('row_header_texts_normalized') + TableRowHeaderTextsNormalized.from_dict(v) + for v in _dict.get('row_header_texts_normalized') ] if 'column_header_ids' in _dict: args['column_header_ids'] = [ - TableColumnHeaderIds.from_dict(x) - for x in _dict.get('column_header_ids') + TableColumnHeaderIds.from_dict(v) + for v in _dict.get('column_header_ids') ] if 'column_header_texts' in _dict: args['column_header_texts'] = [ - TableColumnHeaderTexts.from_dict(x) - for x in _dict.get('column_header_texts') + TableColumnHeaderTexts.from_dict(v) + for v in _dict.get('column_header_texts') ] if 'column_header_texts_normalized' in _dict: args['column_header_texts_normalized'] = [ - TableColumnHeaderTextsNormalized.from_dict(x) - for x in _dict.get('column_header_texts_normalized') + TableColumnHeaderTextsNormalized.from_dict(v) + for v in _dict.get('column_header_texts_normalized') ] if 'attributes' in _dict: args['attributes'] = [ - DocumentAttribute.from_dict(x) for x in _dict.get('attributes') + DocumentAttribute.from_dict(v) for v in _dict.get('attributes') ] return cls(**args) @@ -9957,7 +10287,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -9973,35 +10306,69 @@ def to_dict(self) -> Dict: 'column_index_end') and self.column_index_end is not None: _dict['column_index_end'] = self.column_index_end if hasattr(self, 'row_header_ids') and self.row_header_ids is not None: - _dict['row_header_ids'] = [x.to_dict() for x in self.row_header_ids] + row_header_ids_list = [] + for v in self.row_header_ids: + if isinstance(v, dict): + row_header_ids_list.append(v) + else: + row_header_ids_list.append(v.to_dict()) + _dict['row_header_ids'] = row_header_ids_list if hasattr(self, 'row_header_texts') and self.row_header_texts is not None: - _dict['row_header_texts'] = [ - x.to_dict() for x in self.row_header_texts - ] + row_header_texts_list = [] + for v in self.row_header_texts: + if isinstance(v, dict): + row_header_texts_list.append(v) + else: + row_header_texts_list.append(v.to_dict()) + _dict['row_header_texts'] = row_header_texts_list if hasattr(self, 'row_header_texts_normalized' ) and self.row_header_texts_normalized is not None: - _dict['row_header_texts_normalized'] = [ - x.to_dict() for x in self.row_header_texts_normalized - ] + row_header_texts_normalized_list = [] + for v in self.row_header_texts_normalized: + if isinstance(v, dict): + row_header_texts_normalized_list.append(v) + else: + row_header_texts_normalized_list.append(v.to_dict()) + _dict[ + 'row_header_texts_normalized'] = row_header_texts_normalized_list if hasattr(self, 'column_header_ids') and self.column_header_ids is not None: - _dict['column_header_ids'] = [ - x.to_dict() for x in self.column_header_ids - ] + column_header_ids_list = [] + for v in self.column_header_ids: + if isinstance(v, dict): + column_header_ids_list.append(v) + else: + column_header_ids_list.append(v.to_dict()) + _dict['column_header_ids'] = column_header_ids_list if hasattr( self, 'column_header_texts') and self.column_header_texts is not None: - _dict['column_header_texts'] = [ - x.to_dict() for x in self.column_header_texts - ] + column_header_texts_list = [] + for v in self.column_header_texts: + if isinstance(v, dict): + column_header_texts_list.append(v) + else: + column_header_texts_list.append(v.to_dict()) + _dict['column_header_texts'] = column_header_texts_list if hasattr(self, 'column_header_texts_normalized' ) and self.column_header_texts_normalized is not None: - _dict['column_header_texts_normalized'] = [ - x.to_dict() for x in self.column_header_texts_normalized - ] + column_header_texts_normalized_list = [] + for v in self.column_header_texts_normalized: + if isinstance(v, dict): + column_header_texts_normalized_list.append(v) + else: + column_header_texts_normalized_list.append(v.to_dict()) + _dict[ + 'column_header_texts_normalized'] = column_header_texts_normalized_list if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x.to_dict() for x in self.attributes] + attributes_list = [] + for v in self.attributes: + if isinstance(v, dict): + attributes_list.append(v) + else: + attributes_list.append(v.to_dict()) + _dict['attributes'] = attributes_list return _dict def _to_dict(self): @@ -10078,7 +10445,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict @@ -10157,7 +10527,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text return _dict @@ -10355,7 +10728,7 @@ class TableColumnHeaders(): itself, of the current table. :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr object location: (optional) The location of the column header cell in the + :attr dict location: (optional) The location of the column header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :attr str text: (optional) The textual contents of this cell from the input @@ -10376,7 +10749,7 @@ class TableColumnHeaders(): def __init__(self, *, cell_id: str = None, - location: object = None, + location: dict = None, text: str = None, text_normalized: str = None, row_index_begin: int = None, @@ -10388,8 +10761,8 @@ def __init__(self, :param str cell_id: (optional) The unique ID of the cell in the current table. - :param object location: (optional) The location of the column header cell - in the current table as defined by its `begin` and `end` offsets, + :param dict location: (optional) The location of the column header cell in + the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. @@ -10561,7 +10934,7 @@ class TableHeaders(): The contents of the current table's header. :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr object location: (optional) The location of the table header cell in the + :attr dict location: (optional) The location of the table header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :attr str text: (optional) The textual contents of the cell from the input @@ -10579,7 +10952,7 @@ class TableHeaders(): def __init__(self, *, cell_id: str = None, - location: object = None, + location: dict = None, text: str = None, row_index_begin: int = None, row_index_end: int = None, @@ -10590,7 +10963,7 @@ def __init__(self, :param str cell_id: (optional) The unique ID of the cell in the current table. - :param object location: (optional) The location of the table header cell in + :param dict location: (optional) The location of the table header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. :param str text: (optional) The textual contents of the cell from the input @@ -10710,7 +11083,7 @@ def from_dict(cls, _dict: Dict) -> 'TableKeyValuePairs': args['key'] = TableCellKey.from_dict(_dict.get('key')) if 'value' in _dict: args['value'] = [ - TableCellValues.from_dict(x) for x in _dict.get('value') + TableCellValues.from_dict(v) for v in _dict.get('value') ] return cls(**args) @@ -10723,9 +11096,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key.to_dict() + if isinstance(self.key, dict): + _dict['key'] = self.key + else: + _dict['key'] = self.key.to_dict() if hasattr(self, 'value') and self.value is not None: - _dict['value'] = [x.to_dict() for x in self.value] + value_list = [] + for v in self.value: + if isinstance(v, dict): + value_list.append(v) + else: + value_list.append(v.to_dict()) + _dict['value'] = value_list return _dict def _to_dict(self): @@ -10845,29 +11227,29 @@ def from_dict(cls, _dict: Dict) -> 'TableResultTable': args['title'] = TableTextLocation.from_dict(_dict.get('title')) if 'table_headers' in _dict: args['table_headers'] = [ - TableHeaders.from_dict(x) for x in _dict.get('table_headers') + TableHeaders.from_dict(v) for v in _dict.get('table_headers') ] if 'row_headers' in _dict: args['row_headers'] = [ - TableRowHeaders.from_dict(x) for x in _dict.get('row_headers') + TableRowHeaders.from_dict(v) for v in _dict.get('row_headers') ] if 'column_headers' in _dict: args['column_headers'] = [ - TableColumnHeaders.from_dict(x) - for x in _dict.get('column_headers') + TableColumnHeaders.from_dict(v) + for v in _dict.get('column_headers') ] if 'key_value_pairs' in _dict: args['key_value_pairs'] = [ - TableKeyValuePairs.from_dict(x) - for x in _dict.get('key_value_pairs') + TableKeyValuePairs.from_dict(v) + for v in _dict.get('key_value_pairs') ] if 'body_cells' in _dict: args['body_cells'] = [ - TableBodyCells.from_dict(x) for x in _dict.get('body_cells') + TableBodyCells.from_dict(v) for v in _dict.get('body_cells') ] if 'contexts' in _dict: args['contexts'] = [ - TableTextLocation.from_dict(x) for x in _dict.get('contexts') + TableTextLocation.from_dict(v) for v in _dict.get('contexts') ] return cls(**args) @@ -10880,28 +11262,71 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'section_title') and self.section_title is not None: - _dict['section_title'] = self.section_title.to_dict() + if isinstance(self.section_title, dict): + _dict['section_title'] = self.section_title + else: + _dict['section_title'] = self.section_title.to_dict() if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title.to_dict() + if isinstance(self.title, dict): + _dict['title'] = self.title + else: + _dict['title'] = self.title.to_dict() if hasattr(self, 'table_headers') and self.table_headers is not None: - _dict['table_headers'] = [x.to_dict() for x in self.table_headers] + table_headers_list = [] + for v in self.table_headers: + if isinstance(v, dict): + table_headers_list.append(v) + else: + table_headers_list.append(v.to_dict()) + _dict['table_headers'] = table_headers_list if hasattr(self, 'row_headers') and self.row_headers is not None: - _dict['row_headers'] = [x.to_dict() for x in self.row_headers] + row_headers_list = [] + for v in self.row_headers: + if isinstance(v, dict): + row_headers_list.append(v) + else: + row_headers_list.append(v.to_dict()) + _dict['row_headers'] = row_headers_list if hasattr(self, 'column_headers') and self.column_headers is not None: - _dict['column_headers'] = [x.to_dict() for x in self.column_headers] + column_headers_list = [] + for v in self.column_headers: + if isinstance(v, dict): + column_headers_list.append(v) + else: + column_headers_list.append(v.to_dict()) + _dict['column_headers'] = column_headers_list if hasattr(self, 'key_value_pairs') and self.key_value_pairs is not None: - _dict['key_value_pairs'] = [ - x.to_dict() for x in self.key_value_pairs - ] + key_value_pairs_list = [] + for v in self.key_value_pairs: + if isinstance(v, dict): + key_value_pairs_list.append(v) + else: + key_value_pairs_list.append(v.to_dict()) + _dict['key_value_pairs'] = key_value_pairs_list if hasattr(self, 'body_cells') and self.body_cells is not None: - _dict['body_cells'] = [x.to_dict() for x in self.body_cells] + body_cells_list = [] + for v in self.body_cells: + if isinstance(v, dict): + body_cells_list.append(v) + else: + body_cells_list.append(v.to_dict()) + _dict['body_cells'] = body_cells_list if hasattr(self, 'contexts') and self.contexts is not None: - _dict['contexts'] = [x.to_dict() for x in self.contexts] + contexts_list = [] + for v in self.contexts: + if isinstance(v, dict): + contexts_list.append(v) + else: + contexts_list.append(v.to_dict()) + _dict['contexts'] = contexts_list return _dict def _to_dict(self): @@ -11190,7 +11615,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -11276,7 +11704,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() return _dict def _to_dict(self): @@ -11457,7 +11888,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingQuery': args['updated'] = string_to_datetime(_dict.get('updated')) if 'examples' in _dict: args['examples'] = [ - TrainingExample.from_dict(x) for x in _dict.get('examples') + TrainingExample.from_dict(v) for v in _dict.get('examples') ] else: raise ValueError( @@ -11485,7 +11916,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'updated') and getattr(self, 'updated') is not None: _dict['updated'] = datetime_to_string(getattr(self, 'updated')) if hasattr(self, 'examples') and self.examples is not None: - _dict['examples'] = [x.to_dict() for x in self.examples] + examples_list = [] + for v in self.examples: + if isinstance(v, dict): + examples_list.append(v) + else: + examples_list.append(v.to_dict()) + _dict['examples'] = examples_list return _dict def _to_dict(self): @@ -11532,7 +11969,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingQuerySet': args = {} if 'queries' in _dict: args['queries'] = [ - TrainingQuery.from_dict(x) for x in _dict.get('queries') + TrainingQuery.from_dict(v) for v in _dict.get('queries') ] return cls(**args) @@ -11545,7 +11982,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'queries') and self.queries is not None: - _dict['queries'] = [x.to_dict() for x in self.queries] + queries_list = [] + for v in self.queries: + if isinstance(v, dict): + queries_list.append(v) + else: + queries_list.append(v.to_dict()) + _dict['queries'] = queries_list return _dict def _to_dict(self): @@ -11765,7 +12208,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -11785,7 +12228,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -11843,8 +12292,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregation': ) if 'results' in _dict: args['results'] = [ - QueryGroupByAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryGroupByAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -11859,7 +12308,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -11948,8 +12403,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryHistogramAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryHistogramAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -11970,7 +12425,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -12052,7 +12513,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': ) if 'aggregations' in _dict: args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in _dict.get('aggregations') ] return cls(**args) @@ -12072,7 +12533,13 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + aggregations_list = [] + for v in self.aggregations: + if isinstance(v, dict): + aggregations_list.append(v) + else: + aggregations_list.append(v.to_dict()) + _dict['aggregations'] = aggregations_list return _dict def _to_dict(self): @@ -12155,8 +12622,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryTermAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryTermAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -12177,7 +12644,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -12266,8 +12739,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': args['name'] = _dict.get('name') if 'results' in _dict: args['results'] = [ - QueryTimesliceAggregationResult.from_dict(x) - for x in _dict.get('results') + QueryTimesliceAggregationResult.from_dict(v) + for v in _dict.get('results') ] return cls(**args) @@ -12288,7 +12761,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -12380,7 +12859,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits.to_dict() + if isinstance(self.hits, dict): + _dict['hits'] = self.hits + else: + _dict['hits'] = self.hits.to_dict() return _dict def _to_dict(self): diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 1985d86b3..12e7645a3 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM-provided translation models that you can customize based on @@ -103,7 +103,9 @@ def list_languages(self, **kwargs) -> DetailedResponse: operation_id='list_languages') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -169,13 +171,15 @@ def translate(self, operation_id='translate') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'text': text, 'model_id': model_id, 'source': source, - 'target': target + 'target': target, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data, ensure_ascii=False).encode('utf-8') @@ -219,7 +223,9 @@ def list_identifiable_languages(self, **kwargs) -> DetailedResponse: operation_id='list_identifiable_languages') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -247,7 +253,7 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `IdentifiedLanguages` object """ - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -255,7 +261,9 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: operation_id='identify') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = text headers['content-type'] = 'text/plain' @@ -314,7 +322,7 @@ def list_models(self, 'version': self.version, 'source': source, 'target': target, - 'default': default + 'default': default, } if 'headers' in kwargs: @@ -440,7 +448,7 @@ def create_model(self, :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object """ - if base_model_id is None: + if not base_model_id: raise ValueError('base_model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -451,7 +459,7 @@ def create_model(self, params = { 'version': self.version, 'base_model_id': base_model_id, - 'name': name + 'name': name, } form_data = [] @@ -493,7 +501,7 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `DeleteModelResult` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -501,7 +509,9 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: operation_id='delete_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -534,7 +544,7 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -542,7 +552,9 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: operation_id='get_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -582,7 +594,9 @@ def list_documents(self, **kwargs) -> DetailedResponse: operation_id='list_documents') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -654,7 +668,9 @@ def translate_document(self, operation_id='translate_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] if not filename and hasattr(file, 'name'): @@ -700,7 +716,7 @@ def get_document_status(self, document_id: str, :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object """ - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -708,7 +724,9 @@ def get_document_status(self, document_id: str, operation_id='get_document_status') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -739,7 +757,7 @@ def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -747,7 +765,9 @@ def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: operation_id='delete_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -796,15 +816,19 @@ def get_translated_document(self, :rtype: DetailedResponse with `BinaryIO` result """ - if document_id is None: + if not document_id: raise ValueError('document_id must be provided') - headers = {'Accept': accept} + headers = { + 'Accept': accept, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', operation_id='get_translated_document') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1019,7 +1043,7 @@ def from_dict(cls, _dict: Dict) -> 'DocumentList': args = {} if 'documents' in _dict: args['documents'] = [ - DocumentStatus.from_dict(x) for x in _dict.get('documents') + DocumentStatus.from_dict(v) for v in _dict.get('documents') ] else: raise ValueError( @@ -1036,7 +1060,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'documents') and self.documents is not None: - _dict['documents'] = [x.to_dict() for x in self.documents] + documents_list = [] + for v in self.documents: + if isinstance(v, dict): + documents_list.append(v) + else: + documents_list.append(v.to_dict()) + _dict['documents'] = documents_list return _dict def _to_dict(self): @@ -1357,8 +1387,8 @@ def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguages': args = {} if 'languages' in _dict: args['languages'] = [ - IdentifiableLanguage.from_dict(x) - for x in _dict.get('languages') + IdentifiableLanguage.from_dict(v) + for v in _dict.get('languages') ] else: raise ValueError( @@ -1375,7 +1405,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x.to_dict() for x in self.languages] + languages_list = [] + for v in self.languages: + if isinstance(v, dict): + languages_list.append(v) + else: + languages_list.append(v.to_dict()) + _dict['languages'] = languages_list return _dict def _to_dict(self): @@ -1489,7 +1525,7 @@ def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguages': args = {} if 'languages' in _dict: args['languages'] = [ - IdentifiedLanguage.from_dict(x) for x in _dict.get('languages') + IdentifiedLanguage.from_dict(v) for v in _dict.get('languages') ] else: raise ValueError( @@ -1506,7 +1542,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x.to_dict() for x in self.languages] + languages_list = [] + for v in self.languages: + if isinstance(v, dict): + languages_list.append(v) + else: + languages_list.append(v.to_dict()) + _dict['languages'] = languages_list return _dict def _to_dict(self): @@ -1703,7 +1745,7 @@ def from_dict(cls, _dict: Dict) -> 'Languages': args = {} if 'languages' in _dict: args['languages'] = [ - Language.from_dict(x) for x in _dict.get('languages') + Language.from_dict(v) for v in _dict.get('languages') ] else: raise ValueError( @@ -1719,7 +1761,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: - _dict['languages'] = [x.to_dict() for x in self.languages] + languages_list = [] + for v in self.languages: + if isinstance(v, dict): + languages_list.append(v) + else: + languages_list.append(v.to_dict()) + _dict['languages'] = languages_list return _dict def _to_dict(self): @@ -1987,7 +2035,7 @@ def from_dict(cls, _dict: Dict) -> 'TranslationModels': args = {} if 'models' in _dict: args['models'] = [ - TranslationModel.from_dict(x) for x in _dict.get('models') + TranslationModel.from_dict(v) for v in _dict.get('models') ] else: raise ValueError( @@ -2004,7 +2052,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -2093,7 +2147,7 @@ def from_dict(cls, _dict: Dict) -> 'TranslationResult': 'detected_language_confidence') if 'translations' in _dict: args['translations'] = [ - Translation.from_dict(x) for x in _dict.get('translations') + Translation.from_dict(v) for v in _dict.get('translations') ] else: raise ValueError( @@ -2122,7 +2176,13 @@ def to_dict(self) -> Dict: _dict[ 'detected_language_confidence'] = self.detected_language_confidence if hasattr(self, 'translations') and self.translations is not None: - _dict['translations'] = [x.to_dict() for x in self.translations] + translations_list = [] + for v in self.translations: + if isinstance(v, dict): + translations_list.append(v) + else: + translations_list.append(v.to_dict()) + _dict['translations'] = translations_list return _dict def _to_dict(self): diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 6e64157cc..6d0582913 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2017, 2022. +# (C) Copyright IBM Corp. 2017, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you @@ -156,7 +156,9 @@ def analyze(self, operation_id='analyze') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } data = { 'features': features, @@ -168,7 +170,7 @@ def analyze(self, 'fallback_to_raw': fallback_to_raw, 'return_analyzed_text': return_analyzed_text, 'language': language, - 'limit_text_characters': limit_text_characters + 'limit_text_characters': limit_text_characters, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -212,7 +214,9 @@ def list_models(self, **kwargs) -> DetailedResponse: operation_id='list_models') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -240,7 +244,7 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -248,7 +252,9 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: operation_id='delete_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -303,7 +309,7 @@ def create_sentiment_model(self, :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object """ - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') @@ -313,7 +319,9 @@ def create_sentiment_model(self, operation_id='create_sentiment_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -364,7 +372,9 @@ def list_sentiment_models(self, **kwargs) -> DetailedResponse: operation_id='list_sentiment_models') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -392,7 +402,7 @@ def get_sentiment_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -400,7 +410,9 @@ def get_sentiment_model(self, model_id: str, **kwargs) -> DetailedResponse: operation_id='get_sentiment_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -452,9 +464,9 @@ def update_sentiment_model(self, :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') @@ -464,7 +476,9 @@ def update_sentiment_model(self, operation_id='update_sentiment_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -515,7 +529,7 @@ def delete_sentiment_model(self, model_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -523,7 +537,9 @@ def delete_sentiment_model(self, model_id: str, operation_id='delete_sentiment_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -581,7 +597,7 @@ def create_categories_model(self, :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object """ - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') @@ -591,7 +607,9 @@ def create_categories_model(self, operation_id='create_categories_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -644,7 +662,9 @@ def list_categories_models(self, **kwargs) -> DetailedResponse: operation_id='list_categories_models') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -672,7 +692,7 @@ def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -680,7 +700,9 @@ def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: operation_id='get_categories_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -735,9 +757,9 @@ def update_categories_model(self, :rtype: DetailedResponse with `dict` result representing a `CategoriesModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') @@ -747,7 +769,9 @@ def update_categories_model(self, operation_id='update_categories_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -800,7 +824,7 @@ def delete_categories_model(self, model_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -808,7 +832,9 @@ def delete_categories_model(self, model_id: str, operation_id='delete_categories_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -871,7 +897,7 @@ def create_classifications_model( :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object """ - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') @@ -882,7 +908,9 @@ def create_classifications_model( operation_id='create_classifications_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -940,7 +968,9 @@ def list_classifications_models(self, **kwargs) -> DetailedResponse: operation_id='list_classifications_models') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -969,7 +999,7 @@ def get_classifications_model(self, model_id: str, :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -977,7 +1007,9 @@ def get_classifications_model(self, model_id: str, operation_id='get_classifications_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1037,9 +1069,9 @@ def update_classifications_model( :rtype: DetailedResponse with `dict` result representing a `ClassificationsModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') - if language is None: + if not language: raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') @@ -1050,7 +1082,9 @@ def update_classifications_model( operation_id='update_classifications_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } form_data = [] form_data.append(('language', (None, language, 'text/plain'))) @@ -1107,7 +1141,7 @@ def delete_classifications_model(self, model_id: str, :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers( @@ -1116,7 +1150,9 @@ def delete_classifications_model(self, model_id: str, operation_id='delete_classifications_model') headers.update(sdk_headers) - params = {'version': self.version} + params = { + 'version': self.version, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1302,24 +1338,24 @@ def from_dict(cls, _dict: Dict) -> 'AnalysisResults': args['usage'] = AnalysisResultsUsage.from_dict(_dict.get('usage')) if 'concepts' in _dict: args['concepts'] = [ - ConceptsResult.from_dict(x) for x in _dict.get('concepts') + ConceptsResult.from_dict(v) for v in _dict.get('concepts') ] if 'entities' in _dict: args['entities'] = [ - EntitiesResult.from_dict(x) for x in _dict.get('entities') + EntitiesResult.from_dict(v) for v in _dict.get('entities') ] if 'keywords' in _dict: args['keywords'] = [ - KeywordsResult.from_dict(x) for x in _dict.get('keywords') + KeywordsResult.from_dict(v) for v in _dict.get('keywords') ] if 'categories' in _dict: args['categories'] = [ - CategoriesResult.from_dict(x) for x in _dict.get('categories') + CategoriesResult.from_dict(v) for v in _dict.get('categories') ] if 'classifications' in _dict: args['classifications'] = [ - ClassificationsResult.from_dict(x) - for x in _dict.get('classifications') + ClassificationsResult.from_dict(v) + for v in _dict.get('classifications') ] if 'emotion' in _dict: args['emotion'] = EmotionResult.from_dict(_dict.get('emotion')) @@ -1328,12 +1364,12 @@ def from_dict(cls, _dict: Dict) -> 'AnalysisResults': _dict.get('metadata')) if 'relations' in _dict: args['relations'] = [ - RelationsResult.from_dict(x) for x in _dict.get('relations') + RelationsResult.from_dict(v) for v in _dict.get('relations') ] if 'semantic_roles' in _dict: args['semantic_roles'] = [ - SemanticRolesResult.from_dict(x) - for x in _dict.get('semantic_roles') + SemanticRolesResult.from_dict(v) + for v in _dict.get('semantic_roles') ] if 'sentiment' in _dict: args['sentiment'] = SentimentResult.from_dict( @@ -1357,32 +1393,87 @@ def to_dict(self) -> Dict: if hasattr(self, 'retrieved_url') and self.retrieved_url is not None: _dict['retrieved_url'] = self.retrieved_url if hasattr(self, 'usage') and self.usage is not None: - _dict['usage'] = self.usage.to_dict() + if isinstance(self.usage, dict): + _dict['usage'] = self.usage + else: + _dict['usage'] = self.usage.to_dict() if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = [x.to_dict() for x in self.concepts] + concepts_list = [] + for v in self.concepts: + if isinstance(v, dict): + concepts_list.append(v) + else: + concepts_list.append(v.to_dict()) + _dict['concepts'] = concepts_list if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x.to_dict() for x in self.keywords] + keywords_list = [] + for v in self.keywords: + if isinstance(v, dict): + keywords_list.append(v) + else: + keywords_list.append(v.to_dict()) + _dict['keywords'] = keywords_list if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x.to_dict() for x in self.categories] + categories_list = [] + for v in self.categories: + if isinstance(v, dict): + categories_list.append(v) + else: + categories_list.append(v.to_dict()) + _dict['categories'] = categories_list if hasattr(self, 'classifications') and self.classifications is not None: - _dict['classifications'] = [ - x.to_dict() for x in self.classifications - ] + classifications_list = [] + for v in self.classifications: + if isinstance(v, dict): + classifications_list.append(v) + else: + classifications_list.append(v.to_dict()) + _dict['classifications'] = classifications_list if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata.to_dict() + if isinstance(self.metadata, dict): + _dict['metadata'] = self.metadata + else: + _dict['metadata'] = self.metadata.to_dict() if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = [x.to_dict() for x in self.relations] + relations_list = [] + for v in self.relations: + if isinstance(v, dict): + relations_list.append(v) + else: + relations_list.append(v.to_dict()) + _dict['relations'] = relations_list if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = [x.to_dict() for x in self.semantic_roles] + semantic_roles_list = [] + for v in self.semantic_roles: + if isinstance(v, dict): + semantic_roles_list.append(v) + else: + semantic_roles_list.append(v.to_dict()) + _dict['semantic_roles'] = semantic_roles_list if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'syntax') and self.syntax is not None: - _dict['syntax'] = self.syntax.to_dict() + if isinstance(self.syntax, dict): + _dict['syntax'] = self.syntax + else: + _dict['syntax'] = self.syntax.to_dict() return _dict def _to_dict(self): @@ -1656,7 +1747,7 @@ def from_dict(cls, _dict: Dict) -> 'CategoriesModel': ) if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] if 'last_trained' in _dict: args['last_trained'] = string_to_datetime(_dict.get('last_trained')) @@ -1698,7 +1789,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list if hasattr(self, 'last_trained') and self.last_trained is not None: _dict['last_trained'] = datetime_to_string(self.last_trained) if hasattr(self, 'last_deployed') and self.last_deployed is not None: @@ -1756,7 +1853,7 @@ def from_dict(cls, _dict: Dict) -> 'CategoriesModelList': args = {} if 'models' in _dict: args['models'] = [ - CategoriesModel.from_dict(x) for x in _dict.get('models') + CategoriesModel.from_dict(v) for v in _dict.get('models') ] return cls(**args) @@ -1769,7 +1866,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -1991,7 +2094,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'score') and self.score is not None: _dict['score'] = self.score if hasattr(self, 'explanation') and self.explanation is not None: - _dict['explanation'] = self.explanation.to_dict() + if isinstance(self.explanation, dict): + _dict['explanation'] = self.explanation + else: + _dict['explanation'] = self.explanation.to_dict() return _dict def _to_dict(self): @@ -2042,8 +2148,8 @@ def from_dict(cls, _dict: Dict) -> 'CategoriesResultExplanation': args = {} if 'relevant_text' in _dict: args['relevant_text'] = [ - CategoriesRelevantText.from_dict(x) - for x in _dict.get('relevant_text') + CategoriesRelevantText.from_dict(v) + for v in _dict.get('relevant_text') ] return cls(**args) @@ -2056,7 +2162,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'relevant_text') and self.relevant_text is not None: - _dict['relevant_text'] = [x.to_dict() for x in self.relevant_text] + relevant_text_list = [] + for v in self.relevant_text: + if isinstance(v, dict): + relevant_text_list.append(v) + else: + relevant_text_list.append(v.to_dict()) + _dict['relevant_text'] = relevant_text_list return _dict def _to_dict(self): @@ -2202,7 +2314,7 @@ def from_dict(cls, _dict: Dict) -> 'ClassificationsModel': ) if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] if 'last_trained' in _dict: args['last_trained'] = string_to_datetime(_dict.get('last_trained')) @@ -2244,7 +2356,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'created') and self.created is not None: _dict['created'] = datetime_to_string(self.created) if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list if hasattr(self, 'last_trained') and self.last_trained is not None: _dict['last_trained'] = datetime_to_string(self.last_trained) if hasattr(self, 'last_deployed') and self.last_deployed is not None: @@ -2303,7 +2421,7 @@ def from_dict(cls, _dict: Dict) -> 'ClassificationsModelList': args = {} if 'models' in _dict: args['models'] = [ - ClassificationsModel.from_dict(x) for x in _dict.get('models') + ClassificationsModel.from_dict(v) for v in _dict.get('models') ] return cls(**args) @@ -2316,7 +2434,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -2830,7 +2954,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() return _dict def _to_dict(self): @@ -3025,8 +3152,8 @@ def from_dict(cls, _dict: Dict) -> 'EmotionResult': _dict.get('document')) if 'targets' in _dict: args['targets'] = [ - TargetedEmotionResults.from_dict(x) - for x in _dict.get('targets') + TargetedEmotionResults.from_dict(v) + for v in _dict.get('targets') ] return cls(**args) @@ -3039,9 +3166,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document.to_dict() + if isinstance(self.document, dict): + _dict['document'] = self.document + else: + _dict['document'] = self.document.to_dict() if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = [x.to_dict() for x in self.targets] + targets_list = [] + for v in self.targets: + if isinstance(v, dict): + targets_list.append(v) + else: + targets_list.append(v.to_dict()) + _dict['targets'] = targets_list return _dict def _to_dict(self): @@ -3344,7 +3480,7 @@ def from_dict(cls, _dict: Dict) -> 'EntitiesResult': args['confidence'] = _dict.get('confidence') if 'mentions' in _dict: args['mentions'] = [ - EntityMention.from_dict(x) for x in _dict.get('mentions') + EntityMention.from_dict(v) for v in _dict.get('mentions') ] if 'count' in _dict: args['count'] = _dict.get('count') @@ -3375,15 +3511,30 @@ def to_dict(self) -> Dict: if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = [x.to_dict() for x in self.mentions] + mentions_list = [] + for v in self.mentions: + if isinstance(v, dict): + mentions_list.append(v) + else: + mentions_list.append(v.to_dict()) + _dict['mentions'] = mentions_list if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'disambiguation') and self.disambiguation is not None: - _dict['disambiguation'] = self.disambiguation.to_dict() + if isinstance(self.disambiguation, dict): + _dict['disambiguation'] = self.disambiguation + else: + _dict['disambiguation'] = self.disambiguation.to_dict() return _dict def _to_dict(self): @@ -3729,29 +3880,62 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'classifications') and self.classifications is not None: - _dict['classifications'] = self.classifications.to_dict() + if isinstance(self.classifications, dict): + _dict['classifications'] = self.classifications + else: + _dict['classifications'] = self.classifications.to_dict() if hasattr(self, 'concepts') and self.concepts is not None: - _dict['concepts'] = self.concepts.to_dict() + if isinstance(self.concepts, dict): + _dict['concepts'] = self.concepts + else: + _dict['concepts'] = self.concepts.to_dict() if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = self.entities.to_dict() + if isinstance(self.entities, dict): + _dict['entities'] = self.entities + else: + _dict['entities'] = self.entities.to_dict() if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = self.keywords.to_dict() + if isinstance(self.keywords, dict): + _dict['keywords'] = self.keywords + else: + _dict['keywords'] = self.keywords.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata if hasattr(self, 'relations') and self.relations is not None: - _dict['relations'] = self.relations.to_dict() + if isinstance(self.relations, dict): + _dict['relations'] = self.relations + else: + _dict['relations'] = self.relations.to_dict() if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - _dict['semantic_roles'] = self.semantic_roles.to_dict() + if isinstance(self.semantic_roles, dict): + _dict['semantic_roles'] = self.semantic_roles + else: + _dict['semantic_roles'] = self.semantic_roles.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() if hasattr(self, 'summarization') and self.summarization is not None: - _dict['summarization'] = self.summarization.to_dict() + if isinstance(self.summarization, dict): + _dict['summarization'] = self.summarization + else: + _dict['summarization'] = self.summarization.to_dict() if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = self.categories.to_dict() + if isinstance(self.categories, dict): + _dict['categories'] = self.categories + else: + _dict['categories'] = self.categories.to_dict() if hasattr(self, 'syntax') and self.syntax is not None: - _dict['syntax'] = self.syntax.to_dict() + if isinstance(self.syntax, dict): + _dict['syntax'] = self.syntax + else: + _dict['syntax'] = self.syntax.to_dict() return _dict def _to_dict(self): @@ -3814,7 +3998,7 @@ def from_dict(cls, _dict: Dict) -> 'FeaturesResultsMetadata': args = {} if 'authors' in _dict: args['authors'] = [ - Author.from_dict(x) for x in _dict.get('authors') + Author.from_dict(v) for v in _dict.get('authors') ] if 'publication_date' in _dict: args['publication_date'] = _dict.get('publication_date') @@ -3823,7 +4007,7 @@ def from_dict(cls, _dict: Dict) -> 'FeaturesResultsMetadata': if 'image' in _dict: args['image'] = _dict.get('image') if 'feeds' in _dict: - args['feeds'] = [Feed.from_dict(x) for x in _dict.get('feeds')] + args['feeds'] = [Feed.from_dict(v) for v in _dict.get('feeds')] return cls(**args) @classmethod @@ -3835,7 +4019,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'authors') and self.authors is not None: - _dict['authors'] = [x.to_dict() for x in self.authors] + authors_list = [] + for v in self.authors: + if isinstance(v, dict): + authors_list.append(v) + else: + authors_list.append(v.to_dict()) + _dict['authors'] = authors_list if hasattr(self, 'publication_date') and self.publication_date is not None: _dict['publication_date'] = self.publication_date @@ -3844,7 +4034,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'image') and self.image is not None: _dict['image'] = self.image if hasattr(self, 'feeds') and self.feeds is not None: - _dict['feeds'] = [x.to_dict() for x in self.feeds] + feeds_list = [] + for v in self.feeds: + if isinstance(v, dict): + feeds_list.append(v) + else: + feeds_list.append(v.to_dict()) + _dict['feeds'] = feeds_list return _dict def _to_dict(self): @@ -4071,9 +4267,15 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() if hasattr(self, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment.to_dict() + if isinstance(self.sentiment, dict): + _dict['sentiment'] = self.sentiment + else: + _dict['sentiment'] = self.sentiment.to_dict() return _dict def _to_dict(self): @@ -4115,7 +4317,7 @@ def from_dict(cls, _dict: Dict) -> 'ListModelsResults': """Initialize a ListModelsResults object from a json dictionary.""" args = {} if 'models' in _dict: - args['models'] = [Model.from_dict(x) for x in _dict.get('models')] + args['models'] = [Model.from_dict(v) for v in _dict.get('models')] return cls(**args) @classmethod @@ -4127,7 +4329,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -4170,7 +4378,7 @@ def from_dict(cls, _dict: Dict) -> 'ListSentimentModelsResponse': args = {} if 'models' in _dict: args['models'] = [ - SentimentModel.from_dict(x) for x in _dict.get('models') + SentimentModel.from_dict(v) for v in _dict.get('models') ] return cls(**args) @@ -4183,7 +4391,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -4219,7 +4433,7 @@ class Model(): that deployed this model to Natural Language Understanding. :attr str model_version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. - :attr str version: (optional) Deprecated — use `model_version`. + :attr str version: (optional) Deprecated: Deprecated — use `model_version`. :attr str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. :attr datetime created: (optional) A dateTime indicating when the model was @@ -4250,7 +4464,8 @@ def __init__(self, workspace that deployed this model to Natural Language Understanding. :param str model_version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. - :param str version: (optional) Deprecated — use `model_version`. + :param str version: (optional) Deprecated: Deprecated — use + `model_version`. :param str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. :param datetime created: (optional) A dateTime indicating when the model @@ -4438,7 +4653,7 @@ def from_dict(cls, _dict: Dict) -> 'RelationArgument': args = {} if 'entities' in _dict: args['entities'] = [ - RelationEntity.from_dict(x) for x in _dict.get('entities') + RelationEntity.from_dict(v) for v in _dict.get('entities') ] if 'location' in _dict: args['location'] = _dict.get('location') @@ -4455,7 +4670,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'location') and self.location is not None: _dict['location'] = self.location if hasattr(self, 'text') and self.text is not None: @@ -4650,7 +4871,7 @@ def from_dict(cls, _dict: Dict) -> 'RelationsResult': args['type'] = _dict.get('type') if 'arguments' in _dict: args['arguments'] = [ - RelationArgument.from_dict(x) for x in _dict.get('arguments') + RelationArgument.from_dict(v) for v in _dict.get('arguments') ] return cls(**args) @@ -4669,7 +4890,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type if hasattr(self, 'arguments') and self.arguments is not None: - _dict['arguments'] = [x.to_dict() for x in self.arguments] + arguments_list = [] + for v in self.arguments: + if isinstance(v, dict): + arguments_list.append(v) + else: + arguments_list.append(v.to_dict()) + _dict['arguments'] = arguments_list return _dict def _to_dict(self): @@ -4949,11 +5176,20 @@ def to_dict(self) -> Dict: if hasattr(self, 'sentence') and self.sentence is not None: _dict['sentence'] = self.sentence if hasattr(self, 'subject') and self.subject is not None: - _dict['subject'] = self.subject.to_dict() + if isinstance(self.subject, dict): + _dict['subject'] = self.subject + else: + _dict['subject'] = self.subject.to_dict() if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action.to_dict() + if isinstance(self.action, dict): + _dict['action'] = self.action + else: + _dict['action'] = self.action.to_dict() if hasattr(self, 'object') and self.object is not None: - _dict['object'] = self.object.to_dict() + if isinstance(self.object, dict): + _dict['object'] = self.object + else: + _dict['object'] = self.object.to_dict() return _dict def _to_dict(self): @@ -5025,7 +5261,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'normalized') and self.normalized is not None: _dict['normalized'] = self.normalized if hasattr(self, 'verb') and self.verb is not None: - _dict['verb'] = self.verb.to_dict() + if isinstance(self.verb, dict): + _dict['verb'] = self.verb + else: + _dict['verb'] = self.verb.to_dict() return _dict def _to_dict(self): @@ -5078,7 +5317,7 @@ def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultObject': args['text'] = _dict.get('text') if 'keywords' in _dict: args['keywords'] = [ - SemanticRolesKeyword.from_dict(x) for x in _dict.get('keywords') + SemanticRolesKeyword.from_dict(v) for v in _dict.get('keywords') ] return cls(**args) @@ -5093,7 +5332,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x.to_dict() for x in self.keywords] + keywords_list = [] + for v in self.keywords: + if isinstance(v, dict): + keywords_list.append(v) + else: + keywords_list.append(v.to_dict()) + _dict['keywords'] = keywords_list return _dict def _to_dict(self): @@ -5152,11 +5397,11 @@ def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultSubject': args['text'] = _dict.get('text') if 'entities' in _dict: args['entities'] = [ - SemanticRolesEntity.from_dict(x) for x in _dict.get('entities') + SemanticRolesEntity.from_dict(v) for v in _dict.get('entities') ] if 'keywords' in _dict: args['keywords'] = [ - SemanticRolesKeyword.from_dict(x) for x in _dict.get('keywords') + SemanticRolesKeyword.from_dict(v) for v in _dict.get('keywords') ] return cls(**args) @@ -5171,9 +5416,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'entities') and self.entities is not None: - _dict['entities'] = [x.to_dict() for x in self.entities] + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = [x.to_dict() for x in self.keywords] + keywords_list = [] + for v in self.keywords: + if isinstance(v, dict): + keywords_list.append(v) + else: + keywords_list.append(v.to_dict()) + _dict['keywords'] = keywords_list return _dict def _to_dict(self): @@ -5431,7 +5688,7 @@ def from_dict(cls, _dict: Dict) -> 'SentimentModel': args['model_version'] = _dict.get('model_version') if 'notices' in _dict: args['notices'] = [ - Notice.from_dict(x) for x in _dict.get('notices') + Notice.from_dict(v) for v in _dict.get('notices') ] if 'workspace_id' in _dict: args['workspace_id'] = _dict.get('workspace_id') @@ -5470,7 +5727,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'model_version') and self.model_version is not None: _dict['model_version'] = self.model_version if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = [x.to_dict() for x in self.notices] + notices_list = [] + for v in self.notices: + if isinstance(v, dict): + notices_list.append(v) + else: + notices_list.append(v.to_dict()) + _dict['notices'] = notices_list if hasattr(self, 'workspace_id') and self.workspace_id is not None: _dict['workspace_id'] = self.workspace_id if hasattr( @@ -5631,8 +5894,8 @@ def from_dict(cls, _dict: Dict) -> 'SentimentResult': _dict.get('document')) if 'targets' in _dict: args['targets'] = [ - TargetedSentimentResults.from_dict(x) - for x in _dict.get('targets') + TargetedSentimentResults.from_dict(v) + for v in _dict.get('targets') ] return cls(**args) @@ -5645,9 +5908,18 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document.to_dict() + if isinstance(self.document, dict): + _dict['document'] = self.document + else: + _dict['document'] = self.document.to_dict() if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = [x.to_dict() for x in self.targets] + targets_list = [] + for v in self.targets: + if isinstance(v, dict): + targets_list.append(v) + else: + targets_list.append(v.to_dict()) + _dict['targets'] = targets_list return _dict def _to_dict(self): @@ -5766,7 +6038,10 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tokens') and self.tokens is not None: - _dict['tokens'] = self.tokens.to_dict() + if isinstance(self.tokens, dict): + _dict['tokens'] = self.tokens + else: + _dict['tokens'] = self.tokens.to_dict() if hasattr(self, 'sentences') and self.sentences is not None: _dict['sentences'] = self.sentences return _dict @@ -5885,11 +6160,11 @@ def from_dict(cls, _dict: Dict) -> 'SyntaxResult': args = {} if 'tokens' in _dict: args['tokens'] = [ - TokenResult.from_dict(x) for x in _dict.get('tokens') + TokenResult.from_dict(v) for v in _dict.get('tokens') ] if 'sentences' in _dict: args['sentences'] = [ - SentenceResult.from_dict(x) for x in _dict.get('sentences') + SentenceResult.from_dict(v) for v in _dict.get('sentences') ] return cls(**args) @@ -5902,9 +6177,21 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'tokens') and self.tokens is not None: - _dict['tokens'] = [x.to_dict() for x in self.tokens] + tokens_list = [] + for v in self.tokens: + if isinstance(v, dict): + tokens_list.append(v) + else: + tokens_list.append(v.to_dict()) + _dict['tokens'] = tokens_list if hasattr(self, 'sentences') and self.sentences is not None: - _dict['sentences'] = [x.to_dict() for x in self.sentences] + sentences_list = [] + for v in self.sentences: + if isinstance(v, dict): + sentences_list.append(v) + else: + sentences_list.append(v.to_dict()) + _dict['sentences'] = sentences_list return _dict def _to_dict(self): @@ -5969,7 +6256,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion.to_dict() + if isinstance(self.emotion, dict): + _dict['emotion'] = self.emotion + else: + _dict['emotion'] = self.emotion.to_dict() return _dict def _to_dict(self): diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 9c4d64014..21c4aea23 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2022. +# (C) Copyright IBM Corp. 2015, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's speech-recognition capabilities to produce transcripts of spoken audio. The service can @@ -148,7 +148,7 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `SpeechModel` object """ - if model_id is None: + if not model_id: raise ValueError('model_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -577,7 +577,9 @@ def recognize(self, if audio is None: raise ValueError('audio must be provided') - headers = {'Content-Type': content_type} + headers = { + 'Content-Type': content_type, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='recognize') @@ -607,7 +609,7 @@ def recognize(self, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, 'low_latency': low_latency, - 'character_insertion_bias': character_insertion_bias + 'character_insertion_bias': character_insertion_bias, } data = audio @@ -685,7 +687,7 @@ def register_callback(self, :rtype: DetailedResponse with `dict` result representing a `RegisterStatus` object """ - if callback_url is None: + if not callback_url: raise ValueError('callback_url must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -693,7 +695,10 @@ def register_callback(self, operation_id='register_callback') headers.update(sdk_headers) - params = {'callback_url': callback_url, 'user_secret': user_secret} + params = { + 'callback_url': callback_url, + 'user_secret': user_secret, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -727,7 +732,7 @@ def unregister_callback(self, callback_url: str, :rtype: DetailedResponse """ - if callback_url is None: + if not callback_url: raise ValueError('callback_url must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -735,7 +740,9 @@ def unregister_callback(self, callback_url: str, operation_id='unregister_callback') headers.update(sdk_headers) - params = {'callback_url': callback_url} + params = { + 'callback_url': callback_url, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1229,7 +1236,9 @@ def create_job(self, if audio is None: raise ValueError('audio must be provided') - headers = {'Content-Type': content_type} + headers = { + 'Content-Type': content_type, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='create_job') @@ -1265,7 +1274,7 @@ def create_job(self, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, 'low_latency': low_latency, - 'character_insertion_bias': character_insertion_bias + 'character_insertion_bias': character_insertion_bias, } data = audio @@ -1347,7 +1356,7 @@ def check_job(self, id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `RecognitionJob` object """ - if id is None: + if not id: raise ValueError('id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1389,7 +1398,7 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if id is None: + if not id: raise ValueError('id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1498,7 +1507,7 @@ def create_language_model(self, 'name': name, 'base_model_name': base_model_name, 'dialect': dialect, - 'description': description + 'description': description, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -1557,7 +1566,9 @@ def list_language_models(self, operation_id='list_language_models') headers.update(sdk_headers) - params = {'language': language} + params = { + 'language': language, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1595,7 +1606,7 @@ def get_language_model(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `LanguageModel` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1641,7 +1652,7 @@ def delete_language_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1751,7 +1762,7 @@ def train_language_model(self, :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1762,7 +1773,7 @@ def train_language_model(self, params = { 'word_type_to_add': word_type_to_add, 'customization_weight': customization_weight, - 'strict': strict + 'strict': strict, } if 'headers' in kwargs: @@ -1809,7 +1820,7 @@ def reset_language_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1867,7 +1878,7 @@ def upgrade_language_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1915,7 +1926,7 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `Corpora` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2038,9 +2049,9 @@ def add_corpus(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if corpus_name is None: + if not corpus_name: raise ValueError('corpus_name must be provided') if corpus_file is None: raise ValueError('corpus_file must be provided') @@ -2050,7 +2061,9 @@ def add_corpus(self, operation_id='add_corpus') headers.update(sdk_headers) - params = {'allow_overwrite': allow_overwrite} + params = { + 'allow_overwrite': allow_overwrite, + } form_data = [] form_data.append(('corpus_file', (None, corpus_file, 'text/plain'))) @@ -2098,9 +2111,9 @@ def get_corpus(self, customization_id: str, corpus_name: str, :rtype: DetailedResponse with `dict` result representing a `Corpus` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if corpus_name is None: + if not corpus_name: raise ValueError('corpus_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2151,9 +2164,9 @@ def delete_corpus(self, customization_id: str, corpus_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if corpus_name is None: + if not corpus_name: raise ValueError('corpus_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2233,7 +2246,7 @@ def list_words(self, :rtype: DetailedResponse with `dict` result representing a `Words` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2241,7 +2254,10 @@ def list_words(self, operation_id='list_words') headers.update(sdk_headers) - params = {'word_type': word_type, 'sort': sort} + params = { + 'word_type': word_type, + 'sort': sort, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -2340,7 +2356,7 @@ def add_words(self, customization_id: str, words: List['CustomWord'], :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') @@ -2351,7 +2367,9 @@ def add_words(self, customization_id: str, words: List['CustomWord'], operation_id='add_words') headers.update(sdk_headers) - data = {'words': words} + data = { + 'words': words, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -2471,9 +2489,9 @@ def add_word(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word_name is None: + if not word_name: raise ValueError('word_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2484,7 +2502,7 @@ def add_word(self, data = { 'word': word, 'sounds_like': sounds_like, - 'display_as': display_as + 'display_as': display_as, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -2532,9 +2550,9 @@ def get_word(self, customization_id: str, word_name: str, :rtype: DetailedResponse with `dict` result representing a `Word` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word_name is None: + if not word_name: raise ValueError('word_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2585,9 +2603,9 @@ def delete_word(self, customization_id: str, word_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word_name is None: + if not word_name: raise ValueError('word_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2641,7 +2659,7 @@ def list_grammars(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `Grammars` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2757,21 +2775,25 @@ def add_grammar(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if grammar_name is None: + if not grammar_name: raise ValueError('grammar_name must be provided') if grammar_file is None: raise ValueError('grammar_file must be provided') - if content_type is None: + if not content_type: raise ValueError('content_type must be provided') - headers = {'Content-Type': content_type} + headers = { + 'Content-Type': content_type, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='add_grammar') headers.update(sdk_headers) - params = {'allow_overwrite': allow_overwrite} + params = { + 'allow_overwrite': allow_overwrite, + } data = grammar_file @@ -2822,9 +2844,9 @@ def get_grammar(self, customization_id: str, grammar_name: str, :rtype: DetailedResponse with `dict` result representing a `Grammar` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if grammar_name is None: + if not grammar_name: raise ValueError('grammar_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2879,9 +2901,9 @@ def delete_grammar(self, customization_id: str, grammar_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if grammar_name is None: + if not grammar_name: raise ValueError('grammar_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -2973,7 +2995,7 @@ def create_acoustic_model(self, data = { 'name': name, 'base_model_name': base_model_name, - 'description': description + 'description': description, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -3031,7 +3053,9 @@ def list_acoustic_models(self, operation_id='list_acoustic_models') headers.update(sdk_headers) - params = {'language': language} + params = { + 'language': language, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -3068,7 +3092,7 @@ def get_acoustic_model(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `AcousticModel` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3114,7 +3138,7 @@ def delete_acoustic_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3226,7 +3250,7 @@ def train_acoustic_model(self, :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3236,7 +3260,7 @@ def train_acoustic_model(self, params = { 'custom_language_model_id': custom_language_model_id, - 'strict': strict + 'strict': strict, } if 'headers' in kwargs: @@ -3284,7 +3308,7 @@ def reset_acoustic_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3365,7 +3389,7 @@ def upgrade_acoustic_model(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3375,7 +3399,7 @@ def upgrade_acoustic_model(self, params = { 'custom_language_model_id': custom_language_model_id, - 'force': force + 'force': force, } if 'headers' in kwargs: @@ -3424,7 +3448,7 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `AudioResources` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3595,22 +3619,24 @@ def add_audio(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if audio_name is None: + if not audio_name: raise ValueError('audio_name must be provided') if audio_resource is None: raise ValueError('audio_resource must be provided') headers = { 'Content-Type': content_type, - 'Contained-Content-Type': contained_content_type + 'Contained-Content-Type': contained_content_type, } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='add_audio') headers.update(sdk_headers) - params = {'allow_overwrite': allow_overwrite} + params = { + 'allow_overwrite': allow_overwrite, + } data = audio_resource @@ -3672,9 +3698,9 @@ def get_audio(self, customization_id: str, audio_name: str, :rtype: DetailedResponse with `dict` result representing a `AudioListing` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if audio_name is None: + if not audio_name: raise ValueError('audio_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3727,9 +3753,9 @@ def delete_audio(self, customization_id: str, audio_name: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if audio_name is None: + if not audio_name: raise ValueError('audio_name must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3784,7 +3810,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -3792,7 +3818,9 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: operation_id='delete_user_data') headers.update(sdk_headers) - params = {'customer_id': customer_id} + params = { + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -4634,7 +4662,7 @@ def from_dict(cls, _dict: Dict) -> 'AcousticModels': args = {} if 'customizations' in _dict: args['customizations'] = [ - AcousticModel.from_dict(x) for x in _dict.get('customizations') + AcousticModel.from_dict(v) for v in _dict.get('customizations') ] else: raise ValueError( @@ -4651,7 +4679,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -4895,7 +4929,7 @@ def from_dict(cls, _dict: Dict) -> 'AudioListing': args['container'] = AudioResource.from_dict(_dict.get('container')) if 'audio' in _dict: args['audio'] = [ - AudioResource.from_dict(x) for x in _dict.get('audio') + AudioResource.from_dict(v) for v in _dict.get('audio') ] return cls(**args) @@ -4912,13 +4946,25 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'details') and self.details is not None: - _dict['details'] = self.details.to_dict() + if isinstance(self.details, dict): + _dict['details'] = self.details + else: + _dict['details'] = self.details.to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status if hasattr(self, 'container') and self.container is not None: - _dict['container'] = self.container.to_dict() + if isinstance(self.container, dict): + _dict['container'] = self.container + else: + _dict['container'] = self.container.to_dict() if hasattr(self, 'audio') and self.audio is not None: - _dict['audio'] = [x.to_dict() for x in self.audio] + audio_list = [] + for v in self.audio: + if isinstance(v, dict): + audio_list.append(v) + else: + audio_list.append(v.to_dict()) + _dict['audio'] = audio_list return _dict def _to_dict(self): @@ -5017,7 +5063,10 @@ def to_dict(self) -> Dict: 'sampling_interval') and self.sampling_interval is not None: _dict['sampling_interval'] = self.sampling_interval if hasattr(self, 'accumulated') and self.accumulated is not None: - _dict['accumulated'] = self.accumulated.to_dict() + if isinstance(self.accumulated, dict): + _dict['accumulated'] = self.accumulated + else: + _dict['accumulated'] = self.accumulated.to_dict() return _dict def _to_dict(self): @@ -5185,8 +5234,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'direct_current_offset' in _dict: args['direct_current_offset'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('direct_current_offset') + AudioMetricsHistogramBin.from_dict(v) + for v in _dict.get('direct_current_offset') ] else: raise ValueError( @@ -5194,8 +5243,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'clipping_rate' in _dict: args['clipping_rate'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('clipping_rate') + AudioMetricsHistogramBin.from_dict(v) + for v in _dict.get('clipping_rate') ] else: raise ValueError( @@ -5203,8 +5252,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'speech_level' in _dict: args['speech_level'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('speech_level') + AudioMetricsHistogramBin.from_dict(v) + for v in _dict.get('speech_level') ] else: raise ValueError( @@ -5212,8 +5261,8 @@ def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': ) if 'non_speech_level' in _dict: args['non_speech_level'] = [ - AudioMetricsHistogramBin.from_dict(x) - for x in _dict.get('non_speech_level') + AudioMetricsHistogramBin.from_dict(v) + for v in _dict.get('non_speech_level') ] else: raise ValueError( @@ -5244,18 +5293,38 @@ def to_dict(self) -> Dict: _dict['high_frequency_loss'] = self.high_frequency_loss if hasattr(self, 'direct_current_offset' ) and self.direct_current_offset is not None: - _dict['direct_current_offset'] = [ - x.to_dict() for x in self.direct_current_offset - ] + direct_current_offset_list = [] + for v in self.direct_current_offset: + if isinstance(v, dict): + direct_current_offset_list.append(v) + else: + direct_current_offset_list.append(v.to_dict()) + _dict['direct_current_offset'] = direct_current_offset_list if hasattr(self, 'clipping_rate') and self.clipping_rate is not None: - _dict['clipping_rate'] = [x.to_dict() for x in self.clipping_rate] + clipping_rate_list = [] + for v in self.clipping_rate: + if isinstance(v, dict): + clipping_rate_list.append(v) + else: + clipping_rate_list.append(v.to_dict()) + _dict['clipping_rate'] = clipping_rate_list if hasattr(self, 'speech_level') and self.speech_level is not None: - _dict['speech_level'] = [x.to_dict() for x in self.speech_level] + speech_level_list = [] + for v in self.speech_level: + if isinstance(v, dict): + speech_level_list.append(v) + else: + speech_level_list.append(v.to_dict()) + _dict['speech_level'] = speech_level_list if hasattr(self, 'non_speech_level') and self.non_speech_level is not None: - _dict['non_speech_level'] = [ - x.to_dict() for x in self.non_speech_level - ] + non_speech_level_list = [] + for v in self.non_speech_level: + if isinstance(v, dict): + non_speech_level_list.append(v) + else: + non_speech_level_list.append(v.to_dict()) + _dict['non_speech_level'] = non_speech_level_list return _dict def _to_dict(self): @@ -5457,7 +5526,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'name') and self.name is not None: _dict['name'] = self.name if hasattr(self, 'details') and self.details is not None: - _dict['details'] = self.details.to_dict() + if isinstance(self.details, dict): + _dict['details'] = self.details + else: + _dict['details'] = self.details.to_dict() if hasattr(self, 'status') and self.status is not None: _dict['status'] = self.status return _dict @@ -5539,7 +5611,7 @@ def from_dict(cls, _dict: Dict) -> 'AudioResources': ) if 'audio' in _dict: args['audio'] = [ - AudioResource.from_dict(x) for x in _dict.get('audio') + AudioResource.from_dict(v) for v in _dict.get('audio') ] else: raise ValueError( @@ -5559,7 +5631,13 @@ def to_dict(self) -> Dict: ) and self.total_minutes_of_audio is not None: _dict['total_minutes_of_audio'] = self.total_minutes_of_audio if hasattr(self, 'audio') and self.audio is not None: - _dict['audio'] = [x.to_dict() for x in self.audio] + audio_list = [] + for v in self.audio: + if isinstance(v, dict): + audio_list.append(v) + else: + audio_list.append(v.to_dict()) + _dict['audio'] = audio_list return _dict def _to_dict(self): @@ -5606,7 +5684,7 @@ def from_dict(cls, _dict: Dict) -> 'Corpora': args = {} if 'corpora' in _dict: args['corpora'] = [ - Corpus.from_dict(x) for x in _dict.get('corpora') + Corpus.from_dict(v) for v in _dict.get('corpora') ] else: raise ValueError( @@ -5622,7 +5700,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'corpora') and self.corpora is not None: - _dict['corpora'] = [x.to_dict() for x in self.corpora] + corpora_list = [] + for v in self.corpora: + if isinstance(v, dict): + corpora_list.append(v) + else: + corpora_list.append(v.to_dict()) + _dict['corpora'] = corpora_list return _dict def _to_dict(self): @@ -6059,7 +6143,7 @@ def from_dict(cls, _dict: Dict) -> 'Grammars': args = {} if 'grammars' in _dict: args['grammars'] = [ - Grammar.from_dict(x) for x in _dict.get('grammars') + Grammar.from_dict(v) for v in _dict.get('grammars') ] else: raise ValueError( @@ -6075,7 +6159,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'grammars') and self.grammars is not None: - _dict['grammars'] = [x.to_dict() for x in self.grammars] + grammars_list = [] + for v in self.grammars: + if isinstance(v, dict): + grammars_list.append(v) + else: + grammars_list.append(v.to_dict()) + _dict['grammars'] = grammars_list return _dict def _to_dict(self): @@ -6509,7 +6599,7 @@ def from_dict(cls, _dict: Dict) -> 'LanguageModels': args = {} if 'customizations' in _dict: args['customizations'] = [ - LanguageModel.from_dict(x) for x in _dict.get('customizations') + LanguageModel.from_dict(v) for v in _dict.get('customizations') ] else: raise ValueError( @@ -6526,7 +6616,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -6770,7 +6866,10 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'processed_audio') and self.processed_audio is not None: - _dict['processed_audio'] = self.processed_audio.to_dict() + if isinstance(self.processed_audio, dict): + _dict['processed_audio'] = self.processed_audio + else: + _dict['processed_audio'] = self.processed_audio.to_dict() if hasattr(self, 'wall_clock_since_first_byte_received' ) and self.wall_clock_since_first_byte_received is not None: _dict[ @@ -6932,8 +7031,8 @@ def from_dict(cls, _dict: Dict) -> 'RecognitionJob': args['user_token'] = _dict.get('user_token') if 'results' in _dict: args['results'] = [ - SpeechRecognitionResults.from_dict(x) - for x in _dict.get('results') + SpeechRecognitionResults.from_dict(v) + for v in _dict.get('results') ] if 'warnings' in _dict: args['warnings'] = _dict.get('warnings') @@ -6960,7 +7059,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'user_token') and self.user_token is not None: _dict['user_token'] = self.user_token if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings return _dict @@ -7028,7 +7133,7 @@ def from_dict(cls, _dict: Dict) -> 'RecognitionJobs': args = {} if 'recognitions' in _dict: args['recognitions'] = [ - RecognitionJob.from_dict(x) for x in _dict.get('recognitions') + RecognitionJob.from_dict(v) for v in _dict.get('recognitions') ] else: raise ValueError( @@ -7045,7 +7150,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'recognitions') and self.recognitions is not None: - _dict['recognitions'] = [x.to_dict() for x in self.recognitions] + recognitions_list = [] + for v in self.recognitions: + if isinstance(v, dict): + recognitions_list.append(v) + else: + recognitions_list.append(v.to_dict()) + _dict['recognitions'] = recognitions_list return _dict def _to_dict(self): @@ -7374,7 +7485,10 @@ def to_dict(self) -> Dict: if hasattr( self, 'supported_features') and self.supported_features is not None: - _dict['supported_features'] = self.supported_features.to_dict() + if isinstance(self.supported_features, dict): + _dict['supported_features'] = self.supported_features + else: + _dict['supported_features'] = self.supported_features.to_dict() if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description return _dict @@ -7421,7 +7535,7 @@ def from_dict(cls, _dict: Dict) -> 'SpeechModels': args = {} if 'models' in _dict: args['models'] = [ - SpeechModel.from_dict(x) for x in _dict.get('models') + SpeechModel.from_dict(v) for v in _dict.get('models') ] else: raise ValueError( @@ -7437,7 +7551,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] + models_list = [] + for v in self.models: + if isinstance(v, dict): + models_list.append(v) + else: + models_list.append(v.to_dict()) + _dict['models'] = models_list return _dict def _to_dict(self): @@ -7664,8 +7784,8 @@ def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': ) if 'alternatives' in _dict: args['alternatives'] = [ - SpeechRecognitionAlternative.from_dict(x) - for x in _dict.get('alternatives') + SpeechRecognitionAlternative.from_dict(v) + for v in _dict.get('alternatives') ] else: raise ValueError( @@ -7675,8 +7795,8 @@ def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': args['keywords_result'] = _dict.get('keywords_result') if 'word_alternatives' in _dict: args['word_alternatives'] = [ - WordAlternativeResults.from_dict(x) - for x in _dict.get('word_alternatives') + WordAlternativeResults.from_dict(v) + for v in _dict.get('word_alternatives') ] if 'end_of_utterance' in _dict: args['end_of_utterance'] = _dict.get('end_of_utterance') @@ -7693,15 +7813,25 @@ def to_dict(self) -> Dict: if hasattr(self, 'final') and self.final is not None: _dict['final'] = self.final if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x.to_dict() for x in self.alternatives] + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list if hasattr(self, 'keywords_result') and self.keywords_result is not None: _dict['keywords_result'] = self.keywords_result if hasattr(self, 'word_alternatives') and self.word_alternatives is not None: - _dict['word_alternatives'] = [ - x.to_dict() for x in self.word_alternatives - ] + word_alternatives_list = [] + for v in self.word_alternatives: + if isinstance(v, dict): + word_alternatives_list.append(v) + else: + word_alternatives_list.append(v.to_dict()) + _dict['word_alternatives'] = word_alternatives_list if hasattr(self, 'end_of_utterance') and self.end_of_utterance is not None: _dict['end_of_utterance'] = self.end_of_utterance @@ -7865,15 +7995,15 @@ def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResults': args = {} if 'results' in _dict: args['results'] = [ - SpeechRecognitionResult.from_dict(x) - for x in _dict.get('results') + SpeechRecognitionResult.from_dict(v) + for v in _dict.get('results') ] if 'result_index' in _dict: args['result_index'] = _dict.get('result_index') if 'speaker_labels' in _dict: args['speaker_labels'] = [ - SpeakerLabelsResult.from_dict(x) - for x in _dict.get('speaker_labels') + SpeakerLabelsResult.from_dict(v) + for v in _dict.get('speaker_labels') ] if 'processing_metrics' in _dict: args['processing_metrics'] = ProcessingMetrics.from_dict( @@ -7894,17 +8024,35 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list if hasattr(self, 'result_index') and self.result_index is not None: _dict['result_index'] = self.result_index if hasattr(self, 'speaker_labels') and self.speaker_labels is not None: - _dict['speaker_labels'] = [x.to_dict() for x in self.speaker_labels] + speaker_labels_list = [] + for v in self.speaker_labels: + if isinstance(v, dict): + speaker_labels_list.append(v) + else: + speaker_labels_list.append(v.to_dict()) + _dict['speaker_labels'] = speaker_labels_list if hasattr( self, 'processing_metrics') and self.processing_metrics is not None: - _dict['processing_metrics'] = self.processing_metrics.to_dict() + if isinstance(self.processing_metrics, dict): + _dict['processing_metrics'] = self.processing_metrics + else: + _dict['processing_metrics'] = self.processing_metrics.to_dict() if hasattr(self, 'audio_metrics') and self.audio_metrics is not None: - _dict['audio_metrics'] = self.audio_metrics.to_dict() + if isinstance(self.audio_metrics, dict): + _dict['audio_metrics'] = self.audio_metrics + else: + _dict['audio_metrics'] = self.audio_metrics.to_dict() if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings return _dict @@ -8085,7 +8233,7 @@ def from_dict(cls, _dict: Dict) -> 'TrainingResponse': args = {} if 'warnings' in _dict: args['warnings'] = [ - TrainingWarning.from_dict(x) for x in _dict.get('warnings') + TrainingWarning.from_dict(v) for v in _dict.get('warnings') ] return cls(**args) @@ -8098,7 +8246,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x.to_dict() for x in self.warnings] + warnings_list = [] + for v in self.warnings: + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list return _dict def _to_dict(self): @@ -8348,7 +8502,7 @@ def from_dict(cls, _dict: Dict) -> 'Word': raise ValueError( 'Required property \'source\' not present in Word JSON') if 'error' in _dict: - args['error'] = [WordError.from_dict(x) for x in _dict.get('error')] + args['error'] = [WordError.from_dict(v) for v in _dict.get('error')] return cls(**args) @classmethod @@ -8370,7 +8524,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'source') and self.source is not None: _dict['source'] = self.source if hasattr(self, 'error') and self.error is not None: - _dict['error'] = [x.to_dict() for x in self.error] + error_list = [] + for v in self.error: + if isinstance(v, dict): + error_list.append(v) + else: + error_list.append(v.to_dict()) + _dict['error'] = error_list return _dict def _to_dict(self): @@ -8509,8 +8669,8 @@ def from_dict(cls, _dict: Dict) -> 'WordAlternativeResults': ) if 'alternatives' in _dict: args['alternatives'] = [ - WordAlternativeResult.from_dict(x) - for x in _dict.get('alternatives') + WordAlternativeResult.from_dict(v) + for v in _dict.get('alternatives') ] else: raise ValueError( @@ -8531,7 +8691,13 @@ def to_dict(self) -> Dict: if hasattr(self, 'end_time') and self.end_time is not None: _dict['end_time'] = self.end_time if hasattr(self, 'alternatives') and self.alternatives is not None: - _dict['alternatives'] = [x.to_dict() for x in self.alternatives] + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list return _dict def _to_dict(self): @@ -8646,7 +8812,7 @@ def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} if 'words' in _dict: - args['words'] = [Word.from_dict(x) for x in _dict.get('words')] + args['words'] = [Word.from_dict(v) for v in _dict.get('words')] else: raise ValueError( 'Required property \'words\' not present in Words JSON') @@ -8661,7 +8827,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x.to_dict() for x in self.words] + words_list = [] + for v in self.words: + if isinstance(v, dict): + words_list.append(v) + else: + words_list.append(v.to_dict()) + _dict['words'] = words_list return _dict def _to_dict(self): diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index e0bd5f160..4b81c7ab7 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2022. +# (C) Copyright IBM Corp. 2015, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.53.0-9710cac3-20220713-193508 +# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, @@ -170,7 +170,7 @@ def get_voice(self, :rtype: DetailedResponse with `dict` result representing a `Voice` object """ - if voice is None: + if not voice: raise ValueError('voice must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -178,7 +178,9 @@ def get_voice(self, operation_id='get_voice') headers.update(sdk_headers) - params = {'customization_id': customization_id} + params = { + 'customization_id': customization_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -324,7 +326,9 @@ def synthesize(self, if text is None: raise ValueError('text must be provided') - headers = {'Accept': accept} + headers = { + 'Accept': accept, + } sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', operation_id='synthesize') @@ -333,10 +337,12 @@ def synthesize(self, params = { 'voice': voice, 'customization_id': customization_id, - 'spell_out_mode': spell_out_mode + 'spell_out_mode': spell_out_mode, } - data = {'text': text} + data = { + 'text': text, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -411,7 +417,7 @@ def get_pronunciation(self, :rtype: DetailedResponse with `dict` result representing a `Pronunciation` object """ - if text is None: + if not text: raise ValueError('text must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -423,7 +429,7 @@ def get_pronunciation(self, 'text': text, 'voice': voice, 'format': format, - 'customization_id': customization_id + 'customization_id': customization_id, } if 'headers' in kwargs: @@ -488,7 +494,11 @@ def create_custom_model(self, operation_id='create_custom_model') headers.update(sdk_headers) - data = {'name': name, 'language': language, 'description': description} + data = { + 'name': name, + 'language': language, + 'description': description, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -537,7 +547,9 @@ def list_custom_models(self, operation_id='list_custom_models') headers.update(sdk_headers) - params = {'language': language} + params = { + 'language': language, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -600,7 +612,7 @@ def update_custom_model(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') if words is not None: words = [convert_model(x) for x in words] @@ -610,7 +622,11 @@ def update_custom_model(self, operation_id='update_custom_model') headers.update(sdk_headers) - data = {'name': name, 'description': description, 'words': words} + data = { + 'name': name, + 'description': description, + 'words': words, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -653,7 +669,7 @@ def get_custom_model(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `CustomModel` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -693,7 +709,7 @@ def delete_custom_model(self, customization_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -764,7 +780,7 @@ def add_words(self, customization_id: str, words: List['Word'], :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') if words is None: raise ValueError('words must be provided') @@ -775,7 +791,9 @@ def add_words(self, customization_id: str, words: List['Word'], operation_id='add_words') headers.update(sdk_headers) - data = {'words': words} + data = { + 'words': words, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -816,7 +834,7 @@ def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `Words` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -895,9 +913,9 @@ def add_word(self, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word is None: + if not word: raise ValueError('word must be provided') if translation is None: raise ValueError('translation must be provided') @@ -907,7 +925,10 @@ def add_word(self, operation_id='add_word') headers.update(sdk_headers) - data = {'translation': translation, 'part_of_speech': part_of_speech} + data = { + 'translation': translation, + 'part_of_speech': part_of_speech, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -949,9 +970,9 @@ def get_word(self, customization_id: str, word: str, :rtype: DetailedResponse with `dict` result representing a `Translation` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word is None: + if not word: raise ValueError('word must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -993,9 +1014,9 @@ def delete_word(self, customization_id: str, word: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if word is None: + if not word: raise ValueError('word must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1048,7 +1069,7 @@ def list_custom_prompts(self, customization_id: str, :rtype: DetailedResponse with `dict` result representing a `Prompts` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1176,9 +1197,9 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, :rtype: DetailedResponse with `dict` result representing a `Prompt` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if prompt_id is None: + if not prompt_id: raise ValueError('prompt_id must be provided') if metadata is None: raise ValueError('metadata must be provided') @@ -1235,9 +1256,9 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, :rtype: DetailedResponse with `dict` result representing a `Prompt` object """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if prompt_id is None: + if not prompt_id: raise ValueError('prompt_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1285,9 +1306,9 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, :rtype: DetailedResponse """ - if customization_id is None: + if not customization_id: raise ValueError('customization_id must be provided') - if prompt_id is None: + if not prompt_id: raise ValueError('prompt_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1415,7 +1436,7 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, :rtype: DetailedResponse with `dict` result representing a `SpeakerModel` object """ - if speaker_name is None: + if not speaker_name: raise ValueError('speaker_name must be provided') if audio is None: raise ValueError('audio must be provided') @@ -1425,7 +1446,9 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, operation_id='create_speaker_model') headers.update(sdk_headers) - params = {'speaker_name': speaker_name} + params = { + 'speaker_name': speaker_name, + } data = audio headers['content-type'] = 'audio/wav' @@ -1468,7 +1491,7 @@ def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse with `dict` result representing a `SpeakerCustomModels` object """ - if speaker_id is None: + if not speaker_id: raise ValueError('speaker_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1516,7 +1539,7 @@ def delete_speaker_model(self, speaker_id: str, :rtype: DetailedResponse """ - if speaker_id is None: + if not speaker_id: raise ValueError('speaker_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1568,7 +1591,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: :rtype: DetailedResponse """ - if customer_id is None: + if not customer_id: raise ValueError('customer_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, @@ -1576,7 +1599,9 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: operation_id='delete_user_data') headers.update(sdk_headers) - params = {'customer_id': customer_id} + params = { + 'customer_id': customer_id, + } if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -1961,10 +1986,10 @@ def from_dict(cls, _dict: Dict) -> 'CustomModel': if 'description' in _dict: args['description'] = _dict.get('description') if 'words' in _dict: - args['words'] = [Word.from_dict(x) for x in _dict.get('words')] + args['words'] = [Word.from_dict(v) for v in _dict.get('words')] if 'prompts' in _dict: args['prompts'] = [ - Prompt.from_dict(x) for x in _dict.get('prompts') + Prompt.from_dict(v) for v in _dict.get('prompts') ] return cls(**args) @@ -1992,9 +2017,21 @@ def to_dict(self) -> Dict: if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x.to_dict() for x in self.words] + words_list = [] + for v in self.words: + if isinstance(v, dict): + words_list.append(v) + else: + words_list.append(v.to_dict()) + _dict['words'] = words_list if hasattr(self, 'prompts') and self.prompts is not None: - _dict['prompts'] = [x.to_dict() for x in self.prompts] + prompts_list = [] + for v in self.prompts: + if isinstance(v, dict): + prompts_list.append(v) + else: + prompts_list.append(v.to_dict()) + _dict['prompts'] = prompts_list return _dict def _to_dict(self): @@ -2043,7 +2080,7 @@ def from_dict(cls, _dict: Dict) -> 'CustomModels': args = {} if 'customizations' in _dict: args['customizations'] = [ - CustomModel.from_dict(x) for x in _dict.get('customizations') + CustomModel.from_dict(v) for v in _dict.get('customizations') ] else: raise ValueError( @@ -2060,7 +2097,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -2305,7 +2348,7 @@ def from_dict(cls, _dict: Dict) -> 'Prompts': args = {} if 'prompts' in _dict: args['prompts'] = [ - Prompt.from_dict(x) for x in _dict.get('prompts') + Prompt.from_dict(v) for v in _dict.get('prompts') ] else: raise ValueError( @@ -2321,7 +2364,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'prompts') and self.prompts is not None: - _dict['prompts'] = [x.to_dict() for x in self.prompts] + prompts_list = [] + for v in self.prompts: + if isinstance(v, dict): + prompts_list.append(v) + else: + prompts_list.append(v.to_dict()) + _dict['prompts'] = prompts_list return _dict def _to_dict(self): @@ -2509,7 +2558,7 @@ def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModel': ) if 'prompts' in _dict: args['prompts'] = [ - SpeakerPrompt.from_dict(x) for x in _dict.get('prompts') + SpeakerPrompt.from_dict(v) for v in _dict.get('prompts') ] else: raise ValueError( @@ -2529,7 +2578,13 @@ def to_dict(self) -> Dict: 'customization_id') and self.customization_id is not None: _dict['customization_id'] = self.customization_id if hasattr(self, 'prompts') and self.prompts is not None: - _dict['prompts'] = [x.to_dict() for x in self.prompts] + prompts_list = [] + for v in self.prompts: + if isinstance(v, dict): + prompts_list.append(v) + else: + prompts_list.append(v.to_dict()) + _dict['prompts'] = prompts_list return _dict def _to_dict(self): @@ -2579,8 +2634,8 @@ def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModels': args = {} if 'customizations' in _dict: args['customizations'] = [ - SpeakerCustomModel.from_dict(x) - for x in _dict.get('customizations') + SpeakerCustomModel.from_dict(v) + for v in _dict.get('customizations') ] else: raise ValueError( @@ -2597,7 +2652,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'customizations') and self.customizations is not None: - _dict['customizations'] = [x.to_dict() for x in self.customizations] + customizations_list = [] + for v in self.customizations: + if isinstance(v, dict): + customizations_list.append(v) + else: + customizations_list.append(v.to_dict()) + _dict['customizations'] = customizations_list return _dict def _to_dict(self): @@ -2811,7 +2872,7 @@ def from_dict(cls, _dict: Dict) -> 'Speakers': args = {} if 'speakers' in _dict: args['speakers'] = [ - Speaker.from_dict(x) for x in _dict.get('speakers') + Speaker.from_dict(v) for v in _dict.get('speakers') ] else: raise ValueError( @@ -2827,7 +2888,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'speakers') and self.speakers is not None: - _dict['speakers'] = [x.to_dict() for x in self.speakers] + speakers_list = [] + for v in self.speakers: + if isinstance(v, dict): + speakers_list.append(v) + else: + speakers_list.append(v.to_dict()) + _dict['speakers'] = speakers_list return _dict def _to_dict(self): @@ -3172,9 +3239,15 @@ def to_dict(self) -> Dict: if hasattr( self, 'supported_features') and self.supported_features is not None: - _dict['supported_features'] = self.supported_features.to_dict() + if isinstance(self.supported_features, dict): + _dict['supported_features'] = self.supported_features + else: + _dict['supported_features'] = self.supported_features.to_dict() if hasattr(self, 'customization') and self.customization is not None: - _dict['customization'] = self.customization.to_dict() + if isinstance(self.customization, dict): + _dict['customization'] = self.customization + else: + _dict['customization'] = self.customization.to_dict() return _dict def _to_dict(self): @@ -3216,7 +3289,7 @@ def from_dict(cls, _dict: Dict) -> 'Voices': """Initialize a Voices object from a json dictionary.""" args = {} if 'voices' in _dict: - args['voices'] = [Voice.from_dict(x) for x in _dict.get('voices')] + args['voices'] = [Voice.from_dict(v) for v in _dict.get('voices')] else: raise ValueError( 'Required property \'voices\' not present in Voices JSON') @@ -3231,7 +3304,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'voices') and self.voices is not None: - _dict['voices'] = [x.to_dict() for x in self.voices] + voices_list = [] + for v in self.voices: + if isinstance(v, dict): + voices_list.append(v) + else: + voices_list.append(v.to_dict()) + _dict['voices'] = voices_list return _dict def _to_dict(self): @@ -3418,7 +3497,7 @@ def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} if 'words' in _dict: - args['words'] = [Word.from_dict(x) for x in _dict.get('words')] + args['words'] = [Word.from_dict(v) for v in _dict.get('words')] else: raise ValueError( 'Required property \'words\' not present in Words JSON') @@ -3433,7 +3512,13 @@ def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'words') and self.words is not None: - _dict['words'] = [x.to_dict() for x in self.words] + words_list = [] + for v in self.words: + if isinstance(v, dict): + words_list.append(v) + else: + words_list.append(v.to_dict()) + _dict['words'] = words_list return _dict def _to_dict(self): diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 0d3e7a0c7..9870633f7 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ _service = AssistantV1( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' @@ -83,7 +83,7 @@ def test_message_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -164,7 +164,7 @@ def test_message_all_params(self): # Construct a dict representation of a Context model context_model = {} context_model['conversation_id'] = 'testString' - context_model['system'] = {'key1': 'testString'} + context_model['system'] = {'foo': 'bar'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -186,28 +186,14 @@ def test_message_all_params(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - # Construct a dict representation of a DialogNodeOutputOptionsElementValue model - dialog_node_output_options_element_value_model = {} - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - # Construct a dict representation of a DialogNodeOutputOptionsElement model - dialog_node_output_options_element_model = {} - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a RuntimeResponseGenericRuntimeResponseTypeOption model + # Construct a dict representation of a RuntimeResponseGenericRuntimeResponseTypeText model runtime_response_generic_model = {} - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a OutputData model @@ -276,7 +262,7 @@ def test_message_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -312,7 +298,7 @@ def test_message_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/message') - mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' + mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -493,7 +479,7 @@ def test_list_workspaces_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -545,7 +531,7 @@ def test_list_workspaces_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -576,7 +562,7 @@ def test_list_workspaces_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -612,26 +598,28 @@ def test_create_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -640,13 +628,13 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -659,7 +647,7 @@ def test_create_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -672,7 +660,7 @@ def test_create_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'key1': 'testString'} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -719,7 +707,7 @@ def test_create_workspace_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -757,7 +745,7 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -766,7 +754,7 @@ def test_create_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'key1': 'testString'} + create_entity_model['metadata'] = {'foo': 'bar'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -776,7 +764,7 @@ def test_create_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -815,7 +803,7 @@ def test_create_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -838,7 +826,7 @@ def test_create_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -869,7 +857,7 @@ def test_create_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -905,7 +893,7 @@ def test_get_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -953,7 +941,7 @@ def test_get_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -989,7 +977,7 @@ def test_get_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -1029,26 +1017,28 @@ def test_update_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -1057,13 +1047,13 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1076,7 +1066,7 @@ def test_update_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1089,7 +1079,7 @@ def test_update_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'key1': 'testString'} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1136,7 +1126,7 @@ def test_update_workspace_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -1174,7 +1164,7 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1183,7 +1173,7 @@ def test_update_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'key1': 'testString'} + create_entity_model['metadata'] = {'foo': 'bar'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1194,7 +1184,7 @@ def test_update_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -1237,7 +1227,7 @@ def test_update_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -1260,7 +1250,7 @@ def test_update_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1296,7 +1286,7 @@ def test_update_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1406,26 +1396,28 @@ def test_create_workspace_async_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=202) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -1434,13 +1426,13 @@ def test_create_workspace_async_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1453,7 +1445,7 @@ def test_create_workspace_async_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1466,7 +1458,7 @@ def test_create_workspace_async_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'key1': 'testString'} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1513,7 +1505,7 @@ def test_create_workspace_async_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -1551,7 +1543,7 @@ def test_create_workspace_async_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1560,7 +1552,7 @@ def test_create_workspace_async_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'key1': 'testString'} + create_entity_model['metadata'] = {'foo': 'bar'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1570,7 +1562,7 @@ def test_create_workspace_async_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -1603,7 +1595,7 @@ def test_create_workspace_async_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -1626,7 +1618,7 @@ def test_create_workspace_async_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1657,7 +1649,7 @@ def test_create_workspace_async_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1693,26 +1685,28 @@ def test_update_workspace_async_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=202) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -1721,13 +1715,13 @@ def test_update_workspace_async_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1740,7 +1734,7 @@ def test_update_workspace_async_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1753,7 +1747,7 @@ def test_update_workspace_async_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'key1': 'testString'} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1800,7 +1794,7 @@ def test_update_workspace_async_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -1838,7 +1832,7 @@ def test_update_workspace_async_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1847,7 +1841,7 @@ def test_update_workspace_async_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'key1': 'testString'} + create_entity_model['metadata'] = {'foo': 'bar'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1858,7 +1852,7 @@ def test_update_workspace_async_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -1898,7 +1892,7 @@ def test_update_workspace_async_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -1921,7 +1915,7 @@ def test_update_workspace_async_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1957,7 +1951,7 @@ def test_update_workspace_async_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1997,7 +1991,7 @@ def test_export_workspace_async_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -2045,7 +2039,7 @@ def test_export_workspace_async_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -2081,7 +2075,7 @@ def test_export_workspace_async_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"mapKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"mapKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -4109,7 +4103,7 @@ def test_list_entities_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -4166,7 +4160,7 @@ def test_list_entities_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -4202,7 +4196,7 @@ def test_list_entities_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -4242,7 +4236,7 @@ def test_create_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -4252,7 +4246,7 @@ def test_create_entity_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4261,7 +4255,7 @@ def test_create_entity_all_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} fuzzy_match = True values = [create_value_model] include_audit = False @@ -4289,7 +4283,7 @@ def test_create_entity_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4309,7 +4303,7 @@ def test_create_entity_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -4319,7 +4313,7 @@ def test_create_entity_required_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4328,7 +4322,7 @@ def test_create_entity_required_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} fuzzy_match = True values = [create_value_model] @@ -4350,7 +4344,7 @@ def test_create_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4370,7 +4364,7 @@ def test_create_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -4380,7 +4374,7 @@ def test_create_entity_value_error(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4389,7 +4383,7 @@ def test_create_entity_value_error(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} fuzzy_match = True values = [create_value_model] @@ -4424,7 +4418,7 @@ def test_get_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -4471,7 +4465,7 @@ def test_get_entity_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -4509,7 +4503,7 @@ def test_get_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -4551,7 +4545,7 @@ def test_update_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -4561,7 +4555,7 @@ def test_update_entity_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4571,7 +4565,7 @@ def test_update_entity_all_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {'key1': 'testString'} + new_metadata = {'foo': 'bar'} new_fuzzy_match = True new_values = [create_value_model] append = False @@ -4603,7 +4597,7 @@ def test_update_entity_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4623,7 +4617,7 @@ def test_update_entity_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -4633,7 +4627,7 @@ def test_update_entity_required_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4643,7 +4637,7 @@ def test_update_entity_required_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {'key1': 'testString'} + new_metadata = {'foo': 'bar'} new_fuzzy_match = True new_values = [create_value_model] @@ -4666,7 +4660,7 @@ def test_update_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4686,7 +4680,7 @@ def test_update_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - mock_response = '{"entity": "entity", "description": "description", "metadata": {"mapKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.POST, url, body=mock_response, @@ -4696,7 +4690,7 @@ def test_update_entity_value_error(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4706,7 +4700,7 @@ def test_update_entity_value_error(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {'key1': 'testString'} + new_metadata = {'foo': 'bar'} new_fuzzy_match = True new_values = [create_value_model] @@ -4962,7 +4956,7 @@ def test_list_values_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5021,7 +5015,7 @@ def test_list_values_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5059,7 +5053,7 @@ def test_list_values_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"values": [{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -5101,7 +5095,7 @@ def test_create_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -5112,7 +5106,7 @@ def test_create_value_all_params(self): workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -5141,7 +5135,7 @@ def test_create_value_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5162,7 +5156,7 @@ def test_create_value_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -5173,7 +5167,7 @@ def test_create_value_required_params(self): workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -5196,7 +5190,7 @@ def test_create_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5217,7 +5211,7 @@ def test_create_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -5228,7 +5222,7 @@ def test_create_value_value_error(self): workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -5265,7 +5259,7 @@ def test_get_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5314,7 +5308,7 @@ def test_get_value_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5354,7 +5348,7 @@ def test_get_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -5398,7 +5392,7 @@ def test_update_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -5410,7 +5404,7 @@ def test_update_value_all_params(self): entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {'key1': 'testString'} + new_metadata = {'foo': 'bar'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -5443,7 +5437,7 @@ def test_update_value_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5464,7 +5458,7 @@ def test_update_value_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -5476,7 +5470,7 @@ def test_update_value_required_params(self): entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {'key1': 'testString'} + new_metadata = {'foo': 'bar'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -5500,7 +5494,7 @@ def test_update_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5521,7 +5515,7 @@ def test_update_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - mock_response = '{"value": "value", "metadata": {"mapKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -5533,7 +5527,7 @@ def test_update_value_value_error(self): entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {'key1': 'testString'} + new_metadata = {'foo': 'bar'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -6317,7 +6311,7 @@ def test_list_dialog_nodes_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6371,7 +6365,7 @@ def test_list_dialog_nodes_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6407,7 +6401,7 @@ def test_list_dialog_nodes_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -6447,26 +6441,28 @@ def test_create_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6475,13 +6471,13 @@ def test_create_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6494,7 +6490,7 @@ def test_create_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6507,7 +6503,7 @@ def test_create_dialog_node_all_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6563,7 +6559,7 @@ def test_create_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6592,26 +6588,28 @@ def test_create_dialog_node_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6620,13 +6618,13 @@ def test_create_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6639,7 +6637,7 @@ def test_create_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6652,7 +6650,7 @@ def test_create_dialog_node_required_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6702,7 +6700,7 @@ def test_create_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6731,26 +6729,28 @@ def test_create_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=201) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6759,13 +6759,13 @@ def test_create_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6778,7 +6778,7 @@ def test_create_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6791,7 +6791,7 @@ def test_create_dialog_node_value_error(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {'key1': 'testString'} + metadata = {'foo': 'bar'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6835,7 +6835,7 @@ def test_get_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -6879,7 +6879,7 @@ def test_get_dialog_node_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -6917,7 +6917,7 @@ def test_get_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -6959,26 +6959,28 @@ def test_update_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -6987,13 +6989,13 @@ def test_update_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -7006,7 +7008,7 @@ def test_update_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7020,7 +7022,7 @@ def test_update_dialog_node_all_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {'key1': 'testString'} + new_metadata = {'foo': 'bar'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -7077,7 +7079,7 @@ def test_update_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -7106,26 +7108,28 @@ def test_update_dialog_node_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -7134,13 +7138,13 @@ def test_update_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -7153,7 +7157,7 @@ def test_update_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7167,7 +7171,7 @@ def test_update_dialog_node_required_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {'key1': 'testString'} + new_metadata = {'foo': 'bar'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -7218,7 +7222,7 @@ def test_update_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'key1': 'testString'} + assert req_body['metadata'] == {'foo': 'bar'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -7247,26 +7251,28 @@ def test_update_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "audio", "source": "source", "title": "title", "description": "description", "channels": [{"channel": "chat"}], "channel_options": {"anyKey": "anyValue"}, "alt_text": "alt_text"}], "integrations": {"mapKey": {"mapKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"mapKey": "anyValue"}}}, "metadata": {"mapKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a DialogNodeOutputTextValuesElement model + dialog_node_output_text_values_element_model = {} + dialog_node_output_text_values_element_model['text'] = 'testString' + # Construct a dict representation of a ResponseGenericChannel model response_generic_channel_model = {} response_generic_channel_model['channel'] = 'chat' - # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model + # Construct a dict representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model dialog_node_output_generic_model = {} - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' # Construct a dict representation of a DialogNodeOutputModifiers model dialog_node_output_modifiers_model = {} @@ -7275,13 +7281,13 @@ def test_update_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -7294,7 +7300,7 @@ def test_update_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7308,7 +7314,7 @@ def test_update_dialog_node_value_error(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {'key1': 'testString'} + new_metadata = {'foo': 'bar'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -7436,7 +7442,7 @@ def test_list_logs_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -7487,7 +7493,7 @@ def test_list_logs_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -7523,7 +7529,7 @@ def test_list_logs_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -7563,7 +7569,7 @@ def test_list_all_logs_all_params(self): """ # Set up mock url = preprocess_url('/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -7612,7 +7618,7 @@ def test_list_all_logs_required_params(self): """ # Set up mock url = preprocess_url('/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -7652,7 +7658,7 @@ def test_list_all_logs_value_error(self): """ # Set up mock url = preprocess_url('/v1/logs') - mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"mapKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}]}}], "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -8162,7 +8168,7 @@ def test_context_serialization(self): # Construct a json representation of a Context model context_model_json = {} context_model_json['conversation_id'] = 'testString' - context_model_json['system'] = {'key1': 'testString'} + context_model_json['system'] = {'foo': 'bar'} context_model_json['metadata'] = message_context_metadata_model context_model_json['foo'] = 'testString' @@ -8204,8 +8210,6 @@ def test_counterexample_serialization(self): # Construct a json representation of a Counterexample model counterexample_model_json = {} counterexample_model_json['text'] = 'testString' - counterexample_model_json['created'] = '2019-01-01T12:00:00Z' - counterexample_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Counterexample by calling from_dict on the json representation counterexample_model = Counterexample.from_dict(counterexample_model_json) @@ -8236,8 +8240,6 @@ def test_counterexample_collection_serialization(self): counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2019-01-01T12:00:00Z' - counterexample_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -8281,21 +8283,17 @@ def test_create_entity_serialization(self): create_value_model = {} # CreateValue create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'key1': 'testString'} + create_value_model['metadata'] = {'foo': 'bar'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] - create_value_model['created'] = '2019-01-01T12:00:00Z' - create_value_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a CreateEntity model create_entity_model_json = {} create_entity_model_json['entity'] = 'testString' create_entity_model_json['description'] = 'testString' - create_entity_model_json['metadata'] = {'key1': 'testString'} + create_entity_model_json['metadata'] = {'foo': 'bar'} create_entity_model_json['fuzzy_match'] = True - create_entity_model_json['created'] = '2019-01-01T12:00:00Z' - create_entity_model_json['updated'] = '2019-01-01T12:00:00Z' create_entity_model_json['values'] = [create_value_model] # Construct a model instance of CreateEntity by calling from_dict on the json representation @@ -8332,15 +8330,11 @@ def test_create_intent_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a CreateIntent model create_intent_model_json = {} create_intent_model_json['intent'] = 'testString' create_intent_model_json['description'] = 'testString' - create_intent_model_json['created'] = '2019-01-01T12:00:00Z' - create_intent_model_json['updated'] = '2019-01-01T12:00:00Z' create_intent_model_json['examples'] = [example_model] # Construct a model instance of CreateIntent by calling from_dict on the json representation @@ -8371,12 +8365,10 @@ def test_create_value_serialization(self): # Construct a json representation of a CreateValue model create_value_model_json = {} create_value_model_json['value'] = 'testString' - create_value_model_json['metadata'] = {'key1': 'testString'} + create_value_model_json['metadata'] = {'foo': 'bar'} create_value_model_json['type'] = 'synonyms' create_value_model_json['synonyms'] = ['testString'] create_value_model_json['patterns'] = ['testString'] - create_value_model_json['created'] = '2019-01-01T12:00:00Z' - create_value_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of CreateValue by calling from_dict on the json representation create_value_model = CreateValue.from_dict(create_value_model_json) @@ -8405,29 +8397,30 @@ def test_dialog_node_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -8438,7 +8431,7 @@ def test_dialog_node_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -8451,7 +8444,7 @@ def test_dialog_node_serialization(self): dialog_node_model_json['previous_sibling'] = 'testString' dialog_node_model_json['output'] = dialog_node_output_model dialog_node_model_json['context'] = dialog_node_context_model - dialog_node_model_json['metadata'] = {'key1': 'testString'} + dialog_node_model_json['metadata'] = {'foo': 'bar'} dialog_node_model_json['next_step'] = dialog_node_next_step_model dialog_node_model_json['title'] = 'testString' dialog_node_model_json['type'] = 'standard' @@ -8463,9 +8456,6 @@ def test_dialog_node_serialization(self): dialog_node_model_json['digress_out_slots'] = 'not_allowed' dialog_node_model_json['user_label'] = 'testString' dialog_node_model_json['disambiguation_opt_out'] = False - dialog_node_model_json['disabled'] = True - dialog_node_model_json['created'] = '2019-01-01T12:00:00Z' - dialog_node_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of DialogNode by calling from_dict on the json representation dialog_node_model = DialogNode.from_dict(dialog_node_model_json) @@ -8496,7 +8486,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json = {} dialog_node_action_model_json['name'] = 'testString' dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {'key1': 'testString'} + dialog_node_action_model_json['parameters'] = {'foo': 'bar'} dialog_node_action_model_json['result_variable'] = 'testString' dialog_node_action_model_json['credentials'] = 'testString' @@ -8527,29 +8517,30 @@ def test_dialog_node_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -8560,7 +8551,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -8572,7 +8563,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'key1': 'testString'} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -8584,9 +8575,6 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2019-01-01T12:00:00Z' - dialog_node_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -8628,7 +8616,7 @@ def test_dialog_node_context_serialization(self): # Construct a json representation of a DialogNodeContext model dialog_node_context_model_json = {} - dialog_node_context_model_json['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model_json['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model_json['foo'] = 'testString' # Construct a model instance of DialogNodeContext by calling from_dict on the json representation @@ -8699,17 +8687,18 @@ def test_dialog_node_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True @@ -8717,7 +8706,7 @@ def test_dialog_node_output_serialization(self): # Construct a json representation of a DialogNodeOutput model dialog_node_output_model_json = {} dialog_node_output_model_json['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model_json['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model_json['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model_json['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model_json['foo'] = 'testString' @@ -8758,7 +8747,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'key1': 'testString'}} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'foo': 'bar'}} # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) @@ -8820,8 +8809,6 @@ def test_dialog_node_output_options_element_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -8918,8 +8905,6 @@ def test_dialog_node_output_options_element_value_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -9072,8 +9057,6 @@ def test_dialog_suggestion_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -9138,7 +9121,7 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json = {} dialog_suggestion_model_json['label'] = 'testString' dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {'key1': 'testString'} + dialog_suggestion_model_json['output'] = {'foo': 'bar'} dialog_suggestion_model_json['dialog_node'] = 'testString' # Construct a model instance of DialogSuggestion by calling from_dict on the json representation @@ -9172,8 +9155,6 @@ def test_dialog_suggestion_value_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -9264,21 +9245,17 @@ def test_entity_serialization(self): value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'key1': 'testString'} + value_model['metadata'] = {'foo': 'bar'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a Entity model entity_model_json = {} entity_model_json['entity'] = 'testString' entity_model_json['description'] = 'testString' - entity_model_json['metadata'] = {'key1': 'testString'} + entity_model_json['metadata'] = {'foo': 'bar'} entity_model_json['fuzzy_match'] = True - entity_model_json['created'] = '2019-01-01T12:00:00Z' - entity_model_json['updated'] = '2019-01-01T12:00:00Z' entity_model_json['values'] = [value_model] # Construct a model instance of Entity by calling from_dict on the json representation @@ -9310,20 +9287,16 @@ def test_entity_collection_serialization(self): value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'key1': 'testString'} + value_model['metadata'] = {'foo': 'bar'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {'key1': 'testString'} + entity_model['metadata'] = {'foo': 'bar'} entity_model['fuzzy_match'] = True - entity_model['created'] = '2019-01-01T12:00:00Z' - entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] pagination_model = {} # Pagination @@ -9450,8 +9423,6 @@ def test_example_serialization(self): example_model_json = {} example_model_json['text'] = 'testString' example_model_json['mentions'] = [mention_model] - example_model_json['created'] = '2019-01-01T12:00:00Z' - example_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Example by calling from_dict on the json representation example_model = Example.from_dict(example_model_json) @@ -9487,8 +9458,6 @@ def test_example_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -9537,15 +9506,11 @@ def test_intent_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a Intent model intent_model_json = {} intent_model_json['intent'] = 'testString' intent_model_json['description'] = 'testString' - intent_model_json['created'] = '2019-01-01T12:00:00Z' - intent_model_json['updated'] = '2019-01-01T12:00:00Z' intent_model_json['examples'] = [example_model] # Construct a model instance of Intent by calling from_dict on the json representation @@ -9582,14 +9547,10 @@ def test_intent_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2019-01-01T12:00:00Z' - intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] pagination_model = {} # Pagination @@ -9636,8 +9597,6 @@ def test_log_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -9699,7 +9658,7 @@ def test_log_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'key1': 'testString'} + context_model['system'] = {'foo': 'bar'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -9718,24 +9677,12 @@ def test_log_serialization(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData @@ -9745,13 +9692,6 @@ def test_log_serialization(self): output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] @@ -9759,7 +9699,6 @@ def test_log_serialization(self): message_request_model['alternate_intents'] = False message_request_model['context'] = context_model message_request_model['output'] = output_data_model - message_request_model['actions'] = [dialog_node_action_model] message_request_model['user_id'] = 'testString' message_response_model = {} # MessageResponse @@ -9769,7 +9708,6 @@ def test_log_serialization(self): message_response_model['alternate_intents'] = False message_response_model['context'] = context_model message_response_model['output'] = output_data_model - message_response_model['actions'] = [dialog_node_action_model] message_response_model['user_id'] = 'testString' # Construct a json representation of a Log model @@ -9813,8 +9751,6 @@ def test_log_collection_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -9876,7 +9812,7 @@ def test_log_collection_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'key1': 'testString'} + context_model['system'] = {'foo': 'bar'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -9895,24 +9831,12 @@ def test_log_collection_serialization(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData @@ -9922,13 +9846,6 @@ def test_log_collection_serialization(self): output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] @@ -9936,7 +9853,6 @@ def test_log_collection_serialization(self): message_request_model['alternate_intents'] = False message_request_model['context'] = context_model message_request_model['output'] = output_data_model - message_request_model['actions'] = [dialog_node_action_model] message_request_model['user_id'] = 'testString' message_response_model = {} # MessageResponse @@ -9946,7 +9862,6 @@ def test_log_collection_serialization(self): message_response_model['alternate_intents'] = False message_response_model['context'] = context_model message_response_model['output'] = output_data_model - message_response_model['actions'] = [dialog_node_action_model] message_response_model['user_id'] = 'testString' log_model = {} # Log @@ -10157,8 +10072,6 @@ def test_message_input_serialization(self): message_input_model_json['text'] = 'testString' message_input_model_json['spelling_suggestions'] = False message_input_model_json['spelling_auto_correct'] = False - message_input_model_json['suggested_text'] = 'testString' - message_input_model_json['original_text'] = 'testString' message_input_model_json['foo'] = 'testString' # Construct a model instance of MessageInput by calling from_dict on the json representation @@ -10202,8 +10115,6 @@ def test_message_request_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -10265,7 +10176,7 @@ def test_message_request_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'key1': 'testString'} + context_model['system'] = {'foo': 'bar'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -10284,24 +10195,12 @@ def test_message_request_serialization(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData @@ -10311,13 +10210,6 @@ def test_message_request_serialization(self): output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - # Construct a json representation of a MessageRequest model message_request_model_json = {} message_request_model_json['input'] = message_input_model @@ -10326,7 +10218,6 @@ def test_message_request_serialization(self): message_request_model_json['alternate_intents'] = False message_request_model_json['context'] = context_model message_request_model_json['output'] = output_data_model - message_request_model_json['actions'] = [dialog_node_action_model] message_request_model_json['user_id'] = 'testString' # Construct a model instance of MessageRequest by calling from_dict on the json representation @@ -10360,8 +10251,6 @@ def test_message_response_serialization(self): message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -10423,7 +10312,7 @@ def test_message_response_serialization(self): context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'key1': 'testString'} + context_model['system'] = {'foo': 'bar'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -10442,24 +10331,12 @@ def test_message_response_serialization(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] output_data_model = {} # OutputData @@ -10469,13 +10346,6 @@ def test_message_response_serialization(self): output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - # Construct a json representation of a MessageResponse model message_response_model_json = {} message_response_model_json['input'] = message_input_model @@ -10484,7 +10354,6 @@ def test_message_response_serialization(self): message_response_model_json['alternate_intents'] = False message_response_model_json['context'] = context_model message_response_model_json['output'] = output_data_model - message_response_model_json['actions'] = [dialog_node_action_model] message_response_model_json['user_id'] = 'testString' # Construct a model instance of MessageResponse by calling from_dict on the json representation @@ -10529,85 +10398,12 @@ def test_output_data_serialization(self): log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - message_input_model = {} # MessageInput - message_input_model['text'] = 'testString' - message_input_model['spelling_suggestions'] = False - message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' - message_input_model['foo'] = 'testString' - - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' - - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 - - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] - dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] # Construct a json representation of a OutputData model @@ -10968,8 +10764,6 @@ def test_synonym_serialization(self): # Construct a json representation of a Synonym model synonym_model_json = {} synonym_model_json['synonym'] = 'testString' - synonym_model_json['created'] = '2019-01-01T12:00:00Z' - synonym_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Synonym by calling from_dict on the json representation synonym_model = Synonym.from_dict(synonym_model_json) @@ -11000,8 +10794,6 @@ def test_synonym_collection_serialization(self): synonym_model = {} # Synonym synonym_model['synonym'] = 'testString' - synonym_model['created'] = '2019-01-01T12:00:00Z' - synonym_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -11044,12 +10836,10 @@ def test_value_serialization(self): # Construct a json representation of a Value model value_model_json = {} value_model_json['value'] = 'testString' - value_model_json['metadata'] = {'key1': 'testString'} + value_model_json['metadata'] = {'foo': 'bar'} value_model_json['type'] = 'synonyms' value_model_json['synonyms'] = ['testString'] value_model_json['patterns'] = ['testString'] - value_model_json['created'] = '2019-01-01T12:00:00Z' - value_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Value by calling from_dict on the json representation value_model = Value.from_dict(value_model_json) @@ -11080,12 +10870,10 @@ def test_value_collection_serialization(self): value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'key1': 'testString'} + value_model['metadata'] = {'foo': 'bar'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -11194,29 +10982,30 @@ def test_workspace_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -11227,7 +11016,7 @@ def test_workspace_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -11239,7 +11028,7 @@ def test_workspace_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'key1': 'testString'} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -11251,14 +11040,9 @@ def test_workspace_serialization(self): dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2019-01-01T12:00:00Z' - dialog_node_model['updated'] = '2019-01-01T12:00:00Z' counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2019-01-01T12:00:00Z' - counterexample_model['updated'] = '2019-01-01T12:00:00Z' workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True @@ -11284,7 +11068,7 @@ def test_workspace_serialization(self): workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -11292,9 +11076,6 @@ def test_workspace_serialization(self): workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' - status_error_model = {} # StatusError - status_error_model['message'] = 'testString' - webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' @@ -11311,58 +11092,39 @@ def test_workspace_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2019-01-01T12:00:00Z' - intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'key1': 'testString'} + value_model['metadata'] = {'foo': 'bar'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {'key1': 'testString'} + entity_model['metadata'] = {'foo': 'bar'} entity_model['fuzzy_match'] = True - entity_model['created'] = '2019-01-01T12:00:00Z' - entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] - workspace_counts_model = {} # WorkspaceCounts - workspace_counts_model['intent'] = 38 - workspace_counts_model['entity'] = 38 - workspace_counts_model['node'] = 38 - # Construct a json representation of a Workspace model workspace_model_json = {} workspace_model_json['name'] = 'testString' workspace_model_json['description'] = 'testString' workspace_model_json['language'] = 'testString' - workspace_model_json['workspace_id'] = 'testString' workspace_model_json['dialog_nodes'] = [dialog_node_model] workspace_model_json['counterexamples'] = [counterexample_model] - workspace_model_json['created'] = '2019-01-01T12:00:00Z' - workspace_model_json['updated'] = '2019-01-01T12:00:00Z' - workspace_model_json['metadata'] = {'key1': 'testString'} + workspace_model_json['metadata'] = {'foo': 'bar'} workspace_model_json['learning_opt_out'] = False workspace_model_json['system_settings'] = workspace_system_settings_model - workspace_model_json['status'] = 'Available' - workspace_model_json['status_errors'] = [status_error_model] workspace_model_json['webhooks'] = [webhook_model] workspace_model_json['intents'] = [intent_model] workspace_model_json['entities'] = [entity_model] - workspace_model_json['counts'] = workspace_counts_model # Construct a model instance of Workspace by calling from_dict on the json representation workspace_model = Workspace.from_dict(workspace_model_json) @@ -11391,29 +11153,30 @@ def test_workspace_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model['text'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio - dialog_node_output_generic_model['response_type'] = 'audio' - dialog_node_output_generic_model['source'] = 'testString' - dialog_node_output_generic_model['title'] = 'testString' - dialog_node_output_generic_model['description'] = 'testString' + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model['response_type'] = 'text' + dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] + dialog_node_output_generic_model['selection_policy'] = 'sequential' + dialog_node_output_generic_model['delimiter'] = '\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_generic_model['channel_options'] = {'foo': 'bar'} - dialog_node_output_generic_model['alt_text'] = 'testString' dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'key1': 'testString'}} + dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} dialog_node_context_model['foo'] = 'testString' dialog_node_next_step_model = {} # DialogNodeNextStep @@ -11424,7 +11187,7 @@ def test_workspace_collection_serialization(self): dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -11436,7 +11199,7 @@ def test_workspace_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'key1': 'testString'} + dialog_node_model['metadata'] = {'foo': 'bar'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -11448,14 +11211,9 @@ def test_workspace_collection_serialization(self): dialog_node_model['digress_out_slots'] = 'not_allowed' dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - dialog_node_model['disabled'] = True - dialog_node_model['created'] = '2019-01-01T12:00:00Z' - dialog_node_model['updated'] = '2019-01-01T12:00:00Z' counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - counterexample_model['created'] = '2019-01-01T12:00:00Z' - counterexample_model['updated'] = '2019-01-01T12:00:00Z' workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True @@ -11481,7 +11239,7 @@ def test_workspace_collection_serialization(self): workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'key1': 'testString'} + workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -11489,9 +11247,6 @@ def test_workspace_collection_serialization(self): workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' - status_error_model = {} # StatusError - status_error_model['message'] = 'testString' - webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' @@ -11508,57 +11263,38 @@ def test_workspace_collection_serialization(self): example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - example_model['created'] = '2019-01-01T12:00:00Z' - example_model['updated'] = '2019-01-01T12:00:00Z' intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' - intent_model['created'] = '2019-01-01T12:00:00Z' - intent_model['updated'] = '2019-01-01T12:00:00Z' intent_model['examples'] = [example_model] value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'key1': 'testString'} + value_model['metadata'] = {'foo': 'bar'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - value_model['created'] = '2019-01-01T12:00:00Z' - value_model['updated'] = '2019-01-01T12:00:00Z' entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {'key1': 'testString'} + entity_model['metadata'] = {'foo': 'bar'} entity_model['fuzzy_match'] = True - entity_model['created'] = '2019-01-01T12:00:00Z' - entity_model['updated'] = '2019-01-01T12:00:00Z' entity_model['values'] = [value_model] - workspace_counts_model = {} # WorkspaceCounts - workspace_counts_model['intent'] = 38 - workspace_counts_model['entity'] = 38 - workspace_counts_model['node'] = 38 - workspace_model = {} # Workspace workspace_model['name'] = 'testString' workspace_model['description'] = 'testString' workspace_model['language'] = 'testString' - workspace_model['workspace_id'] = 'testString' workspace_model['dialog_nodes'] = [dialog_node_model] workspace_model['counterexamples'] = [counterexample_model] - workspace_model['created'] = '2019-01-01T12:00:00Z' - workspace_model['updated'] = '2019-01-01T12:00:00Z' - workspace_model['metadata'] = {'key1': 'testString'} + workspace_model['metadata'] = {'foo': 'bar'} workspace_model['learning_opt_out'] = False workspace_model['system_settings'] = workspace_system_settings_model - workspace_model['status'] = 'Available' - workspace_model['status_errors'] = [status_error_model] workspace_model['webhooks'] = [webhook_model] workspace_model['intents'] = [intent_model] workspace_model['entities'] = [entity_model] - workspace_model['counts'] = workspace_counts_model pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -11656,7 +11392,7 @@ def test_workspace_system_settings_serialization(self): workspace_system_settings_model_json = {} workspace_system_settings_model_json['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model_json['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model_json['human_agent_assist'] = {'key1': 'testString'} + workspace_system_settings_model_json['human_agent_assist'] = {'foo': 'bar'} workspace_system_settings_model_json['spelling_suggestions'] = False workspace_system_settings_model_json['spelling_auto_correct'] = False workspace_system_settings_model_json['system_entities'] = workspace_system_settings_system_entities_model @@ -11942,7 +11678,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ agent_availability_message_model['message'] = 'testString' dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'key1': 'testString'}} + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' @@ -12065,8 +11801,6 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -12293,7 +12027,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_user_define # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined model dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['response_type'] = 'user_defined' - dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {'key1': 'testString'} + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined by calling from_dict on the json representation @@ -12453,7 +12187,7 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali agent_availability_message_model['message'] = 'testString' dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'key1': 'testString'}} + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' @@ -12578,8 +12312,6 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -12724,8 +12456,6 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False - message_input_model['suggested_text'] = 'testString' - message_input_model['original_text'] = 'testString' message_input_model['foo'] = 'testString' runtime_intent_model = {} # RuntimeIntent @@ -12789,7 +12519,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization dialog_suggestion_model = {} # DialogSuggestion dialog_suggestion_model['label'] = 'testString' dialog_suggestion_model['value'] = dialog_suggestion_value_model - dialog_suggestion_model['output'] = {'key1': 'testString'} + dialog_suggestion_model['output'] = {'foo': 'bar'} dialog_suggestion_model['dialog_node'] = 'testString' response_generic_channel_model = {} # ResponseGenericChannel @@ -12871,7 +12601,7 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model runtime_response_generic_runtime_response_type_user_defined_model_json = {} runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' - runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'key1': 'testString'} + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 7c944b5c3..24a9f8e1a 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -33,7 +33,7 @@ _service = AssistantV2( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.assistant.watson.cloud.ibm.com' @@ -92,10 +92,12 @@ def test_create_session_all_params(self): # Set up parameter values assistant_id = 'testString' + request_body = {'key1': 'testString'} # Invoke method response = _service.create_session( assistant_id, + request_body=request_body, headers={} ) @@ -104,6 +106,7 @@ def test_create_session_all_params(self): assert response.status_code == 201 # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body == request_body def test_create_session_all_params_with_retries(self): # Enable retries and run test_create_session_all_params. @@ -281,7 +284,7 @@ def test_message_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -400,7 +403,7 @@ def test_message_all_params(self): # Construct a dict representation of a MessageContextSkill model message_context_skill_model = {} - message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} + message_context_skill_model['user_defined'] = {'foo': 'bar'} message_context_skill_model['system'] = message_context_skill_system_model # Construct a dict representation of a MessageContext model @@ -451,7 +454,7 @@ def test_message_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -489,7 +492,7 @@ def test_message_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -531,7 +534,7 @@ def test_message_stateless_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -649,7 +652,7 @@ def test_message_stateless_all_params(self): # Construct a dict representation of a MessageContextSkill model message_context_skill_model = {} - message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} + message_context_skill_model['user_defined'] = {'foo': 'bar'} message_context_skill_model['system'] = message_context_skill_system_model # Construct a dict representation of a MessageContextStateless model @@ -698,7 +701,7 @@ def test_message_stateless_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -734,7 +737,7 @@ def test_message_stateless_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -885,7 +888,7 @@ def test_list_logs_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -936,7 +939,7 @@ def test_list_logs_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -972,7 +975,7 @@ def test_list_logs_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "option", "title": "title", "description": "description", "preference": "dropdown", "options": [{"label": "label", "value": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}}], "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"mapKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"mapKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"mapKey": {"anyKey": "anyValue"}}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -2183,7 +2186,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json = {} dialog_node_action_model_json['name'] = 'testString' dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {'key1': 'testString'} + dialog_node_action_model_json['parameters'] = {'foo': 'bar'} dialog_node_action_model_json['result_variable'] = 'testString' dialog_node_action_model_json['credentials'] = 'testString' @@ -2214,7 +2217,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'key1': 'testString'}} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'foo': 'bar'}} # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) @@ -2587,7 +2590,7 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json = {} dialog_suggestion_model_json['label'] = 'testString' dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {'key1': 'testString'} + dialog_suggestion_model_json['output'] = {'foo': 'bar'} # Construct a model instance of DialogSuggestion by calling from_dict on the json representation dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) @@ -2727,12 +2730,6 @@ def test_environment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_release_reference_model = {} # EnvironmentReleaseReference - environment_release_reference_model['release'] = 'testString' - - environment_orchestration_model = {} # EnvironmentOrchestration - environment_orchestration_model['search_skill_fallback'] = True - integration_reference_model = {} # IntegrationReference integration_reference_model['integration_id'] = 'testString' integration_reference_model['type'] = 'testString' @@ -2749,16 +2746,9 @@ def test_environment_serialization(self): environment_model_json['name'] = 'testString' environment_model_json['description'] = 'testString' environment_model_json['language'] = 'testString' - environment_model_json['assistant_id'] = 'testString' - environment_model_json['environment_id'] = 'testString' - environment_model_json['environment'] = 'testString' - environment_model_json['release_reference'] = environment_release_reference_model - environment_model_json['orchestration'] = environment_orchestration_model environment_model_json['session_timeout'] = 38 environment_model_json['integration_references'] = [integration_reference_model] environment_model_json['skill_references'] = [skill_reference_model] - environment_model_json['created'] = '2019-01-01T12:00:00Z' - environment_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Environment by calling from_dict on the json representation environment_model = Environment.from_dict(environment_model_json) @@ -2787,12 +2777,6 @@ def test_environment_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_release_reference_model = {} # EnvironmentReleaseReference - environment_release_reference_model['release'] = 'testString' - - environment_orchestration_model = {} # EnvironmentOrchestration - environment_orchestration_model['search_skill_fallback'] = True - integration_reference_model = {} # IntegrationReference integration_reference_model['integration_id'] = 'testString' integration_reference_model['type'] = 'testString' @@ -2808,16 +2792,9 @@ def test_environment_collection_serialization(self): environment_model['name'] = 'testString' environment_model['description'] = 'testString' environment_model['language'] = 'testString' - environment_model['assistant_id'] = 'testString' - environment_model['environment_id'] = 'testString' - environment_model['environment'] = 'testString' - environment_model['release_reference'] = environment_release_reference_model - environment_model['orchestration'] = environment_orchestration_model environment_model['session_timeout'] = 38 environment_model['integration_references'] = [integration_reference_model] environment_model['skill_references'] = [skill_reference_model] - environment_model['created'] = '2019-01-01T12:00:00Z' - environment_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -2889,8 +2866,6 @@ def test_environment_reference_serialization(self): # Construct a json representation of a EnvironmentReference model environment_reference_model_json = {} environment_reference_model_json['name'] = 'testString' - environment_reference_model_json['environment_id'] = 'testString' - environment_reference_model_json['environment'] = 'draft' # Construct a model instance of EnvironmentReference by calling from_dict on the json representation environment_reference_model = EnvironmentReference.from_dict(environment_reference_model_json) @@ -3070,14 +3045,13 @@ def test_log_serialization(self): message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_global_model['session_id'] = 'testString' message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} + message_context_skill_model['user_defined'] = {'foo': 'bar'} message_context_skill_model['system'] = message_context_skill_system_model message_context_model = {} # MessageContext @@ -3090,28 +3064,18 @@ def test_log_serialization(self): message_request_model['context'] = message_context_model message_request_model['user_id'] = 'testString' - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -3161,7 +3125,7 @@ def test_log_serialization(self): message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'key1': 'testString'} + message_output_model['user_defined'] = {'foo': 'bar'} message_output_model['spelling'] = message_output_spelling_model message_response_model = {} # MessageResponse @@ -3302,14 +3266,13 @@ def test_log_collection_serialization(self): message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_global_model['session_id'] = 'testString' message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} + message_context_skill_model['user_defined'] = {'foo': 'bar'} message_context_skill_model['system'] = message_context_skill_system_model message_context_model = {} # MessageContext @@ -3322,28 +3285,18 @@ def test_log_collection_serialization(self): message_request_model['context'] = message_context_model message_request_model['user_id'] = 'testString' - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -3393,7 +3346,7 @@ def test_log_collection_serialization(self): message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'key1': 'testString'} + message_output_model['user_defined'] = {'foo': 'bar'} message_output_model['spelling'] = message_output_spelling_model message_response_model = {} # MessageResponse @@ -3494,14 +3447,13 @@ def test_message_context_serialization(self): message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_global_model['session_id'] = 'testString' message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} + message_context_skill_model['user_defined'] = {'foo': 'bar'} message_context_skill_model['system'] = message_context_skill_system_model # Construct a json representation of a MessageContext model @@ -3550,7 +3502,6 @@ def test_message_context_global_serialization(self): # Construct a json representation of a MessageContextGlobal model message_context_global_model_json = {} message_context_global_model_json['system'] = message_context_global_system_model - message_context_global_model_json['session_id'] = 'testString' # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) @@ -3663,7 +3614,7 @@ def test_message_context_skill_serialization(self): # Construct a json representation of a MessageContextSkill model message_context_skill_model_json = {} - message_context_skill_model_json['user_defined'] = {'key1': {'foo': 'bar'}} + message_context_skill_model_json['user_defined'] = {'foo': 'bar'} message_context_skill_model_json['system'] = message_context_skill_system_model # Construct a model instance of MessageContextSkill by calling from_dict on the json representation @@ -3752,7 +3703,7 @@ def test_message_context_stateless_serialization(self): message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} + message_context_skill_model['user_defined'] = {'foo': 'bar'} message_context_skill_model['system'] = message_context_skill_system_model # Construct a json representation of a MessageContextStateless model @@ -4140,6 +4091,14 @@ def test_message_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 @@ -4195,53 +4154,10 @@ def test_message_output_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' - - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False - - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model - - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] - runtime_response_generic_model['channels'] = [response_generic_channel_model] - dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -4292,7 +4208,7 @@ def test_message_output_serialization(self): message_output_model_json['entities'] = [runtime_entity_model] message_output_model_json['actions'] = [dialog_node_action_model] message_output_model_json['debug'] = message_output_debug_model - message_output_model_json['user_defined'] = {'key1': 'testString'} + message_output_model_json['user_defined'] = {'foo': 'bar'} message_output_model_json['spelling'] = message_output_spelling_model # Construct a model instance of MessageOutput by calling from_dict on the json representation @@ -4508,14 +4424,13 @@ def test_message_request_serialization(self): message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_global_model['session_id'] = 'testString' message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} + message_context_skill_model['user_defined'] = {'foo': 'bar'} message_context_skill_model['system'] = message_context_skill_system_model message_context_model = {} # MessageContext @@ -4556,6 +4471,14 @@ def test_message_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 @@ -4611,53 +4534,10 @@ def test_message_response_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' - - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False - - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model - - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] - runtime_response_generic_model['channels'] = [response_generic_channel_model] - dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -4707,7 +4587,7 @@ def test_message_response_serialization(self): message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'key1': 'testString'} + message_output_model['user_defined'] = {'foo': 'bar'} message_output_model['spelling'] = message_output_spelling_model message_context_global_system_model = {} # MessageContextGlobalSystem @@ -4722,14 +4602,13 @@ def test_message_response_serialization(self): message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_global_model['session_id'] = 'testString' message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} + message_context_skill_model['user_defined'] = {'foo': 'bar'} message_context_skill_model['system'] = message_context_skill_system_model message_context_model = {} # MessageContext @@ -4770,6 +4649,14 @@ def test_message_response_stateless_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 @@ -4825,53 +4712,10 @@ def test_message_response_stateless_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' - - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False - - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['options'] = message_input_options_model - - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement - dialog_node_output_options_element_model['label'] = 'testString' - dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeOption - runtime_response_generic_model['response_type'] = 'option' - runtime_response_generic_model['title'] = 'testString' - runtime_response_generic_model['description'] = 'testString' - runtime_response_generic_model['preference'] = 'dropdown' - runtime_response_generic_model['options'] = [dialog_node_output_options_element_model] - runtime_response_generic_model['channels'] = [response_generic_channel_model] - dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'key1': 'testString'} + dialog_node_action_model['parameters'] = {'foo': 'bar'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -4921,7 +4765,7 @@ def test_message_response_stateless_serialization(self): message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'key1': 'testString'} + message_output_model['user_defined'] = {'foo': 'bar'} message_output_model['spelling'] = message_output_spelling_model message_context_global_system_model = {} # MessageContextGlobalSystem @@ -4943,7 +4787,7 @@ def test_message_response_stateless_serialization(self): message_context_skill_system_model['foo'] = 'testString' message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'key1': {'foo': 'bar'}} + message_context_skill_model['user_defined'] = {'foo': 'bar'} message_context_skill_model['system'] = message_context_skill_system_model message_context_stateless_model = {} # MessageContextStateless @@ -5016,30 +4860,11 @@ def test_release_serialization(self): Test serialization/deserialization for Release """ - # Construct dict forms of any model objects needed in order to build this model. - - environment_reference_model = {} # EnvironmentReference - environment_reference_model['name'] = 'testString' - environment_reference_model['environment_id'] = 'testString' - environment_reference_model['environment'] = 'draft' - - release_skill_reference_model = {} # ReleaseSkillReference - release_skill_reference_model['skill_id'] = 'testString' - release_skill_reference_model['type'] = 'dialog' - release_skill_reference_model['snapshot'] = 'testString' - - release_content_model = {} # ReleaseContent - release_content_model['skills'] = [release_skill_reference_model] - # Construct a json representation of a Release model release_model_json = {} release_model_json['release'] = 'testString' release_model_json['description'] = 'testString' - release_model_json['environment_references'] = [environment_reference_model] - release_model_json['content'] = release_content_model release_model_json['status'] = 'Available' - release_model_json['created'] = '2019-01-01T12:00:00Z' - release_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of Release by calling from_dict on the json representation release_model = Release.from_dict(release_model_json) @@ -5068,27 +4893,10 @@ def test_release_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_reference_model = {} # EnvironmentReference - environment_reference_model['name'] = 'testString' - environment_reference_model['environment_id'] = 'testString' - environment_reference_model['environment'] = 'draft' - - release_skill_reference_model = {} # ReleaseSkillReference - release_skill_reference_model['skill_id'] = 'testString' - release_skill_reference_model['type'] = 'dialog' - release_skill_reference_model['snapshot'] = 'testString' - - release_content_model = {} # ReleaseContent - release_content_model['skills'] = [release_skill_reference_model] - release_model = {} # Release release_model['release'] = 'testString' release_model['description'] = 'testString' - release_model['environment_references'] = [environment_reference_model] - release_model['content'] = release_content_model release_model['status'] = 'Available' - release_model['created'] = '2019-01-01T12:00:00Z' - release_model['updated'] = '2019-01-01T12:00:00Z' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -5128,16 +4936,8 @@ def test_release_content_serialization(self): Test serialization/deserialization for ReleaseContent """ - # Construct dict forms of any model objects needed in order to build this model. - - release_skill_reference_model = {} # ReleaseSkillReference - release_skill_reference_model['skill_id'] = 'testString' - release_skill_reference_model['type'] = 'dialog' - release_skill_reference_model['snapshot'] = 'testString' - # Construct a json representation of a ReleaseContent model release_content_model_json = {} - release_content_model_json['skills'] = [release_skill_reference_model] # Construct a model instance of ReleaseContent by calling from_dict on the json representation release_content_model = ReleaseContent.from_dict(release_content_model_json) @@ -5696,7 +5496,7 @@ def test_turn_event_callout_callout_serialization(self): # Construct a json representation of a TurnEventCalloutCallout model turn_event_callout_callout_model_json = {} turn_event_callout_callout_model_json['type'] = 'integration_interaction' - turn_event_callout_callout_model_json['internal'] = {'key1': 'testString'} + turn_event_callout_callout_model_json['internal'] = {'foo': 'bar'} # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation turn_event_callout_callout_model = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json) @@ -5951,7 +5751,7 @@ def test_message_output_debug_turn_event_turn_event_action_finished_serializatio message_output_debug_turn_event_turn_event_action_finished_model_json['action_start_time'] = 'testString' message_output_debug_turn_event_turn_event_action_finished_model_json['condition_type'] = 'user_defined' message_output_debug_turn_event_turn_event_action_finished_model_json['reason'] = 'all_steps_done' - message_output_debug_turn_event_turn_event_action_finished_model_json['action_variables'] = {'key1': 'testString'} + message_output_debug_turn_event_turn_event_action_finished_model_json['action_variables'] = {'foo': 'bar'} # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionFinished by calling from_dict on the json representation message_output_debug_turn_event_turn_event_action_finished_model = MessageOutputDebugTurnEventTurnEventActionFinished.from_dict(message_output_debug_turn_event_turn_event_action_finished_model_json) @@ -6029,7 +5829,7 @@ def test_message_output_debug_turn_event_turn_event_callout_serialization(self): turn_event_callout_callout_model = {} # TurnEventCalloutCallout turn_event_callout_callout_model['type'] = 'integration_interaction' - turn_event_callout_callout_model['internal'] = {'key1': 'testString'} + turn_event_callout_callout_model['internal'] = {'foo': 'bar'} turn_event_callout_error_model = {} # TurnEventCalloutError turn_event_callout_error_model['message'] = 'testString' @@ -6360,7 +6160,7 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali agent_availability_message_model['message'] = 'testString' dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'key1': 'testString'}} + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' @@ -6819,7 +6619,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization dialog_suggestion_model = {} # DialogSuggestion dialog_suggestion_model['label'] = 'testString' dialog_suggestion_model['value'] = dialog_suggestion_value_model - dialog_suggestion_model['output'] = {'key1': 'testString'} + dialog_suggestion_model['output'] = {'foo': 'bar'} response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' @@ -6900,7 +6700,7 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model runtime_response_generic_runtime_response_type_user_defined_model_json = {} runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' - runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'key1': 'testString'} + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index a37881797..945c28ba5 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2022. +# (C) Copyright IBM Corp. 2016, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -36,7 +36,7 @@ _service = DiscoveryV1( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' @@ -616,7 +616,7 @@ def test_create_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.POST, url, body=mock_response, @@ -734,7 +734,7 @@ def test_create_configuration_all_params(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'key1': 'testString'} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -858,7 +858,7 @@ def test_create_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.POST, url, body=mock_response, @@ -976,7 +976,7 @@ def test_create_configuration_value_error(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'key1': 'testString'} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1091,7 +1091,7 @@ def test_list_configurations_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1133,7 +1133,7 @@ def test_list_configurations_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1169,7 +1169,7 @@ def test_list_configurations_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' responses.add(responses.GET, url, body=mock_response, @@ -1209,7 +1209,7 @@ def test_get_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.GET, url, body=mock_response, @@ -1247,7 +1247,7 @@ def test_get_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.GET, url, body=mock_response, @@ -1289,7 +1289,7 @@ def test_update_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.PUT, url, body=mock_response, @@ -1407,7 +1407,7 @@ def test_update_configuration_all_params(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'key1': 'testString'} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1533,7 +1533,7 @@ def test_update_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"mapKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' responses.add(responses.PUT, url, body=mock_response, @@ -1651,7 +1651,7 @@ def test_update_configuration_value_error(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'key1': 'testString'} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -3680,7 +3680,7 @@ def test_query_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3782,7 +3782,7 @@ def test_query_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3820,7 +3820,7 @@ def test_query_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -3862,7 +3862,7 @@ def test_query_notices_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3954,7 +3954,7 @@ def test_query_notices_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -3992,7 +3992,7 @@ def test_query_notices_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4034,7 +4034,7 @@ def test_federated_query_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -4134,7 +4134,7 @@ def test_federated_query_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -4232,7 +4232,7 @@ def test_federated_query_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' responses.add(responses.POST, url, body=mock_response, @@ -4293,7 +4293,7 @@ def test_federated_query_notices_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4374,7 +4374,7 @@ def test_federated_query_notices_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -4416,7 +4416,7 @@ def test_federated_query_notices_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"mapKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' + mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' responses.add(responses.GET, url, body=mock_response, @@ -7256,13 +7256,8 @@ def test_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. document_counts_model = {} # DocumentCounts - document_counts_model['available'] = 0 - document_counts_model['processing'] = 0 - document_counts_model['failed'] = 0 - document_counts_model['pending'] = 26 collection_disk_usage_model = {} # CollectionDiskUsage - collection_disk_usage_model['used_bytes'] = 260 training_status_model = {} # TrainingStatus training_status_model['total_examples'] = 0 @@ -7295,12 +7290,8 @@ def test_collection_serialization(self): # Construct a json representation of a Collection model collection_model_json = {} - collection_model_json['collection_id'] = 'testString' collection_model_json['name'] = 'testString' collection_model_json['description'] = 'testString' - collection_model_json['created'] = '2019-01-01T12:00:00Z' - collection_model_json['updated'] = '2019-01-01T12:00:00Z' - collection_model_json['status'] = 'active' collection_model_json['configuration_id'] = 'testString' collection_model_json['language'] = 'testString' collection_model_json['document_counts'] = document_counts_model @@ -7371,7 +7362,6 @@ def test_collection_disk_usage_serialization(self): # Construct a json representation of a CollectionDiskUsage model collection_disk_usage_model_json = {} - collection_disk_usage_model_json['used_bytes'] = 38 # Construct a model instance of CollectionDiskUsage by calling from_dict on the json representation collection_disk_usage_model = CollectionDiskUsage.from_dict(collection_disk_usage_model_json) @@ -7400,8 +7390,6 @@ def test_collection_usage_serialization(self): # Construct a json representation of a CollectionUsage model collection_usage_model_json = {} - collection_usage_model_json['available'] = 38 - collection_usage_model_json['maximum_allowed'] = 38 # Construct a model instance of CollectionUsage by calling from_dict on the json representation collection_usage_model = CollectionUsage.from_dict(collection_usage_model_json) @@ -7551,7 +7539,7 @@ def test_configuration_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'key1': 'testString'} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -7618,10 +7606,7 @@ def test_configuration_serialization(self): # Construct a json representation of a Configuration model configuration_model_json = {} - configuration_model_json['configuration_id'] = 'testString' configuration_model_json['name'] = 'testString' - configuration_model_json['created'] = '2019-01-01T12:00:00Z' - configuration_model_json['updated'] = '2019-01-01T12:00:00Z' configuration_model_json['description'] = 'testString' configuration_model_json['conversions'] = conversions_model configuration_model_json['enrichments'] = [enrichment_model] @@ -7744,7 +7729,6 @@ def test_create_event_response_serialization(self): event_data_model['display_rank'] = 38 event_data_model['collection_id'] = 'testString' event_data_model['document_id'] = 'testString' - event_data_model['query_id'] = 'testString' # Construct a json representation of a CreateEventResponse model create_event_response_model_json = {} @@ -7852,7 +7836,6 @@ def test_credentials_serialization(self): # Construct a json representation of a Credentials model credentials_model_json = {} - credentials_model_json['credential_id'] = 'testString' credentials_model_json['source_type'] = 'box' credentials_model_json['credential_details'] = credential_details_model credentials_model_json['status'] = status_details_model @@ -7910,7 +7893,6 @@ def test_credentials_list_serialization(self): status_details_model['error_message'] = 'testString' credentials_model = {} # Credentials - credentials_model['credential_id'] = '00000d8c-0000-00e8-ba89-0ed5f89f718b' credentials_model['source_type'] = 'salesforce' credentials_model['credential_details'] = credential_details_model credentials_model['status'] = status_details_model @@ -7977,13 +7959,6 @@ def test_delete_configuration_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['notice_id'] = 'configuration_in_use' - notice_model['created'] = '2016-09-28T12:34:00Z' - notice_model['document_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'The configuration was deleted, but it is referenced by one or more collections.' # Construct a json representation of a DeleteConfigurationResponse model delete_configuration_response_model_json = {} @@ -8108,8 +8083,6 @@ def test_disk_usage_serialization(self): # Construct a json representation of a DiskUsage model disk_usage_model_json = {} - disk_usage_model_json['used_bytes'] = 38 - disk_usage_model_json['maximum_allowed_bytes'] = 38 # Construct a model instance of DiskUsage by calling from_dict on the json representation disk_usage_model = DiskUsage.from_dict(disk_usage_model_json) @@ -8139,13 +8112,6 @@ def test_document_accepted_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['notice_id'] = 'testString' - notice_model['created'] = '2019-01-01T12:00:00Z' - notice_model['document_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'testString' # Construct a json representation of a DocumentAccepted model document_accepted_model_json = {} @@ -8180,10 +8146,6 @@ def test_document_counts_serialization(self): # Construct a json representation of a DocumentCounts model document_counts_model_json = {} - document_counts_model_json['available'] = 26 - document_counts_model_json['processing'] = 26 - document_counts_model_json['failed'] = 26 - document_counts_model_json['pending'] = 26 # Construct a model instance of DocumentCounts by calling from_dict on the json representation document_counts_model = DocumentCounts.from_dict(document_counts_model_json) @@ -8210,27 +8172,11 @@ def test_document_status_serialization(self): Test serialization/deserialization for DocumentStatus """ - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - notice_model['notice_id'] = 'index_342' - notice_model['created'] = '2019-01-01T12:00:00Z' - notice_model['document_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'indexing' - notice_model['description'] = 'something bad happened' - # Construct a json representation of a DocumentStatus model document_status_model_json = {} - document_status_model_json['document_id'] = 'testString' - document_status_model_json['configuration_id'] = 'testString' - document_status_model_json['status'] = 'available' - document_status_model_json['status_description'] = 'testString' document_status_model_json['filename'] = 'testString' document_status_model_json['file_type'] = 'pdf' document_status_model_json['sha1'] = 'testString' - document_status_model_json['notices'] = [notice_model] # Construct a model instance of DocumentStatus by calling from_dict on the json representation document_status_model = DocumentStatus.from_dict(document_status_model_json) @@ -8297,7 +8243,7 @@ def test_enrichment_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'key1': 'testString'} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -8382,7 +8328,7 @@ def test_enrichment_options_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'key1': 'testString'} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -8421,16 +8367,10 @@ def test_environment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. environment_documents_model = {} # EnvironmentDocuments - environment_documents_model['available'] = 38 - environment_documents_model['maximum_allowed'] = 1000000 disk_usage_model = {} # DiskUsage - disk_usage_model['used_bytes'] = 0 - disk_usage_model['maximum_allowed_bytes'] = 85899345920 collection_usage_model = {} # CollectionUsage - collection_usage_model['available'] = 1 - collection_usage_model['maximum_allowed'] = 4 index_capacity_model = {} # IndexCapacity index_capacity_model['documents'] = environment_documents_model @@ -8445,13 +8385,8 @@ def test_environment_serialization(self): # Construct a json representation of a Environment model environment_model_json = {} - environment_model_json['environment_id'] = 'testString' environment_model_json['name'] = 'testString' environment_model_json['description'] = 'testString' - environment_model_json['created'] = '2019-01-01T12:00:00Z' - environment_model_json['updated'] = '2019-01-01T12:00:00Z' - environment_model_json['status'] = 'active' - environment_model_json['read_only'] = True environment_model_json['size'] = 'LT' environment_model_json['requested_size'] = 'testString' environment_model_json['index_capacity'] = index_capacity_model @@ -8484,8 +8419,6 @@ def test_environment_documents_serialization(self): # Construct a json representation of a EnvironmentDocuments model environment_documents_model_json = {} - environment_documents_model_json['available'] = 38 - environment_documents_model_json['maximum_allowed'] = 38 # Construct a model instance of EnvironmentDocuments by calling from_dict on the json representation environment_documents_model = EnvironmentDocuments.from_dict(environment_documents_model_json) @@ -8520,7 +8453,6 @@ def test_event_data_serialization(self): event_data_model_json['display_rank'] = 38 event_data_model_json['collection_id'] = 'testString' event_data_model_json['document_id'] = 'testString' - event_data_model_json['query_id'] = 'testString' # Construct a model instance of EventData by calling from_dict on the json representation event_data_model = EventData.from_dict(event_data_model_json) @@ -8614,8 +8546,6 @@ def test_field_serialization(self): # Construct a json representation of a Field model field_model_json = {} - field_model_json['field'] = 'testString' - field_model_json['type'] = 'nested' # Construct a model instance of Field by calling from_dict on the json representation field_model = Field.from_dict(field_model_json) @@ -8819,16 +8749,10 @@ def test_index_capacity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. environment_documents_model = {} # EnvironmentDocuments - environment_documents_model['available'] = 38 - environment_documents_model['maximum_allowed'] = 38 disk_usage_model = {} # DiskUsage - disk_usage_model['used_bytes'] = 38 - disk_usage_model['maximum_allowed_bytes'] = 38 collection_usage_model = {} # CollectionUsage - collection_usage_model['available'] = 38 - collection_usage_model['maximum_allowed'] = 38 # Construct a json representation of a IndexCapacity model index_capacity_model_json = {} @@ -8864,8 +8788,6 @@ def test_list_collection_fields_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. field_model = {} # Field - field_model['field'] = 'warnings' - field_model['type'] = 'nested' # Construct a json representation of a ListCollectionFieldsResponse model list_collection_fields_response_model_json = {} @@ -8899,13 +8821,8 @@ def test_list_collections_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. document_counts_model = {} # DocumentCounts - document_counts_model['available'] = 26 - document_counts_model['processing'] = 26 - document_counts_model['failed'] = 26 - document_counts_model['pending'] = 26 collection_disk_usage_model = {} # CollectionDiskUsage - collection_disk_usage_model['used_bytes'] = 38 training_status_model = {} # TrainingStatus training_status_model['total_examples'] = 38 @@ -8937,12 +8854,8 @@ def test_list_collections_response_serialization(self): sdu_status_model['custom_fields'] = sdu_status_custom_fields_model collection_model = {} # Collection - collection_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' collection_model['name'] = 'example' collection_model['description'] = 'this is a demo collection' - collection_model['created'] = '2015-08-24T18:42:25.324000Z' - collection_model['updated'] = '2015-08-24T18:42:25.324000Z' - collection_model['status'] = 'active' collection_model['configuration_id'] = '6963be41-2dea-4f79-8f52-127c63c479b0' collection_model['language'] = 'en' collection_model['document_counts'] = document_counts_model @@ -9074,7 +8987,7 @@ def test_list_configurations_response_serialization(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'key1': 'testString'} + nlu_enrichment_features_model['categories'] = {'foo': 'bar'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -9140,10 +9053,7 @@ def test_list_configurations_response_serialization(self): source_model['options'] = source_options_model configuration_model = {} # Configuration - configuration_model['configuration_id'] = 'testString' configuration_model['name'] = 'testString' - configuration_model['created'] = '2019-01-01T12:00:00Z' - configuration_model['updated'] = '2019-01-01T12:00:00Z' configuration_model['description'] = 'testString' configuration_model['conversions'] = conversions_model configuration_model['enrichments'] = [enrichment_model] @@ -9182,16 +9092,10 @@ def test_list_environments_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. environment_documents_model = {} # EnvironmentDocuments - environment_documents_model['available'] = 38 - environment_documents_model['maximum_allowed'] = 38 disk_usage_model = {} # DiskUsage - disk_usage_model['used_bytes'] = 38 - disk_usage_model['maximum_allowed_bytes'] = 38 collection_usage_model = {} # CollectionUsage - collection_usage_model['available'] = 38 - collection_usage_model['maximum_allowed'] = 38 index_capacity_model = {} # IndexCapacity index_capacity_model['documents'] = environment_documents_model @@ -9205,13 +9109,8 @@ def test_list_environments_response_serialization(self): search_status_model['last_trained'] = '2019-01-01' environment_model = {} # Environment - environment_model['environment_id'] = 'ecbda78e-fb06-40b1-a43f-a039fac0adc6' environment_model['name'] = 'byod_environment' environment_model['description'] = 'Private Data Environment' - environment_model['created'] = '2017-07-14T12:54:40.985000Z' - environment_model['updated'] = '2017-07-14T12:54:40.985000Z' - environment_model['status'] = 'active' - environment_model['read_only'] = False environment_model['size'] = 'LT' environment_model['requested_size'] = 'testString' environment_model['index_capacity'] = index_capacity_model @@ -9788,7 +9687,7 @@ def test_nlu_enrichment_features_serialization(self): nlu_enrichment_features_model_json['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model_json['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model_json['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model_json['categories'] = {'key1': 'testString'} + nlu_enrichment_features_model_json['categories'] = {'foo': 'bar'} nlu_enrichment_features_model_json['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model_json['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model_json['concepts'] = nlu_enrichment_concepts_model @@ -9972,13 +9871,6 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} - notice_model_json['notice_id'] = 'testString' - notice_model_json['created'] = '2019-01-01T12:00:00Z' - notice_model_json['document_id'] = 'testString' - notice_model_json['query_id'] = 'testString' - notice_model_json['severity'] = 'warning' - notice_model_json['step'] = 'testString' - notice_model_json['description'] = 'testString' # Construct a model instance of Notice by calling from_dict on the json representation notice_model = Notice.from_dict(notice_model_json) @@ -10160,17 +10052,10 @@ def test_query_notices_response_serialization(self): query_result_metadata_model['confidence'] = 72.5 notice_model = {} # Notice - notice_model['notice_id'] = 'xpath_not_found' - notice_model['created'] = '2016-09-20T17:26:17Z' - notice_model['document_id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'html-to-html' - notice_model['description'] = 'The xpath expression "boom" was not found.' query_notices_result_model = {} # QueryNoticesResult query_notices_result_model['id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' - query_notices_result_model['metadata'] = {'key1': 'testString'} + query_notices_result_model['metadata'] = {'foo': 'bar'} query_notices_result_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' query_notices_result_model['result_metadata'] = query_result_metadata_model query_notices_result_model['code'] = 200 @@ -10178,7 +10063,7 @@ def test_query_notices_response_serialization(self): query_notices_result_model['file_type'] = 'html' query_notices_result_model['sha1'] = 'de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3' query_notices_result_model['notices'] = [notice_model] - query_notices_result_model['score'] = {'foo': 'bar'} + query_notices_result_model['score'] = '1' query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' @@ -10233,18 +10118,11 @@ def test_query_notices_result_serialization(self): query_result_metadata_model['confidence'] = 72.5 notice_model = {} # Notice - notice_model['notice_id'] = 'testString' - notice_model['created'] = '2019-01-01T12:00:00Z' - notice_model['document_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'testString' # Construct a json representation of a QueryNoticesResult model query_notices_result_model_json = {} query_notices_result_model_json['id'] = 'testString' - query_notices_result_model_json['metadata'] = {'key1': 'testString'} + query_notices_result_model_json['metadata'] = {'foo': 'bar'} query_notices_result_model_json['collection_id'] = 'testString' query_notices_result_model_json['result_metadata'] = query_result_metadata_model query_notices_result_model_json['code'] = 38 @@ -10252,7 +10130,7 @@ def test_query_notices_result_serialization(self): query_notices_result_model_json['file_type'] = 'pdf' query_notices_result_model_json['sha1'] = 'testString' query_notices_result_model_json['notices'] = [notice_model] - query_notices_result_model_json['foo'] = {'foo': 'bar'} + query_notices_result_model_json['foo'] = 'testString' # Construct a model instance of QueryNoticesResult by calling from_dict on the json representation query_notices_result_model = QueryNoticesResult.from_dict(query_notices_result_model_json) @@ -10274,7 +10152,7 @@ def test_query_notices_result_serialization(self): actual_dict = query_notices_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': {'foo': 'bar'}} + expected_dict = {'foo': 'testString'} query_notices_result_model.set_properties(expected_dict) actual_dict = query_notices_result_model.get_properties() assert actual_dict == expected_dict @@ -10331,10 +10209,10 @@ def test_query_response_serialization(self): query_result_model = {} # QueryResult query_result_model['id'] = 'watson-generated ID' - query_result_model['metadata'] = {'key1': 'testString'} + query_result_model['metadata'] = {'foo': 'bar'} query_result_model['collection_id'] = 'testString' query_result_model['result_metadata'] = query_result_metadata_model - query_result_model['score'] = {'foo': 'bar'} + query_result_model['score'] = '1' query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' @@ -10397,10 +10275,10 @@ def test_query_result_serialization(self): # Construct a json representation of a QueryResult model query_result_model_json = {} query_result_model_json['id'] = 'testString' - query_result_model_json['metadata'] = {'key1': 'testString'} + query_result_model_json['metadata'] = {'foo': 'bar'} query_result_model_json['collection_id'] = 'testString' query_result_model_json['result_metadata'] = query_result_metadata_model - query_result_model_json['foo'] = {'foo': 'bar'} + query_result_model_json['foo'] = 'testString' # Construct a model instance of QueryResult by calling from_dict on the json representation query_result_model = QueryResult.from_dict(query_result_model_json) @@ -10422,7 +10300,7 @@ def test_query_result_serialization(self): actual_dict = query_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': {'foo': 'bar'}} + expected_dict = {'foo': 'testString'} query_result_model.set_properties(expected_dict) actual_dict = query_result_model.get_properties() assert actual_dict == expected_dict @@ -10550,7 +10428,7 @@ def test_query_top_hits_aggregation_result_serialization(self): # Construct a json representation of a QueryTopHitsAggregationResult model query_top_hits_aggregation_result_model_json = {} query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{'key1': 'testString'}] + query_top_hits_aggregation_result_model_json['hits'] = [{'foo': 'bar'}] # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) @@ -11715,7 +11593,7 @@ def test_query_top_hits_aggregation_serialization(self): query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{'key1': 'testString'}] + query_top_hits_aggregation_result_model['hits'] = [{'foo': 'bar'}] # Construct a json representation of a QueryTopHitsAggregation model query_top_hits_aggregation_model_json = {} diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index ecb024af6..c2e80d2b0 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ _service = DiscoveryV2( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' @@ -785,18 +785,12 @@ def test_create_collection_all_params(self): collection_enrichment_model['enrichment_id'] = 'testString' collection_enrichment_model['fields'] = ['testString'] - # Construct a dict representation of a CollectionDetailsSmartDocumentUnderstanding model - collection_details_smart_document_understanding_model = {} - collection_details_smart_document_understanding_model['enabled'] = True - collection_details_smart_document_understanding_model['model'] = 'custom' - # Set up parameter values project_id = 'testString' name = 'testString' description = 'testString' language = 'en' enrichments = [collection_enrichment_model] - smart_document_understanding = collection_details_smart_document_understanding_model # Invoke method response = _service.create_collection( @@ -805,7 +799,6 @@ def test_create_collection_all_params(self): description=description, language=language, enrichments=enrichments, - smart_document_understanding=smart_document_understanding, headers={} ) @@ -818,7 +811,6 @@ def test_create_collection_all_params(self): assert req_body['description'] == 'testString' assert req_body['language'] == 'en' assert req_body['enrichments'] == [collection_enrichment_model] - assert req_body['smart_document_understanding'] == collection_details_smart_document_understanding_model def test_create_collection_all_params_with_retries(self): # Enable retries and run test_create_collection_all_params. @@ -848,18 +840,12 @@ def test_create_collection_value_error(self): collection_enrichment_model['enrichment_id'] = 'testString' collection_enrichment_model['fields'] = ['testString'] - # Construct a dict representation of a CollectionDetailsSmartDocumentUnderstanding model - collection_details_smart_document_understanding_model = {} - collection_details_smart_document_understanding_model['enabled'] = True - collection_details_smart_document_understanding_model['model'] = 'custom' - # Set up parameter values project_id = 'testString' name = 'testString' description = 'testString' language = 'en' enrichments = [collection_enrichment_model] - smart_document_understanding = collection_details_smart_document_understanding_model # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -1781,7 +1767,7 @@ def test_query_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -1891,7 +1877,7 @@ def test_query_required_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -1927,7 +1913,7 @@ def test_query_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"mapKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -5049,7 +5035,7 @@ def test_analyze_document_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' responses.add(responses.POST, url, body=mock_response, @@ -5095,7 +5081,7 @@ def test_analyze_document_required_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' responses.add(responses.POST, url, body=mock_response, @@ -5133,7 +5119,7 @@ def test_analyze_document_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/analyze') - mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"mapKey": "anyValue"}}}' + mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' responses.add(responses.POST, url, body=mock_response, @@ -5270,18 +5256,10 @@ def test_analyzed_document_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['notice_id'] = 'testString' - notice_model['created'] = '2019-01-01T12:00:00Z' - notice_model['document_id'] = 'testString' - notice_model['collection_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'testString' analyzed_result_model = {} # AnalyzedResult - analyzed_result_model['metadata'] = {'key1': 'testString'} - analyzed_result_model['foo'] = {'foo': 'bar'} + analyzed_result_model['metadata'] = {'foo': 'bar'} + analyzed_result_model['foo'] = 'testString' # Construct a json representation of a AnalyzedDocument model analyzed_document_model_json = {} @@ -5315,8 +5293,8 @@ def test_analyzed_result_serialization(self): # Construct a json representation of a AnalyzedResult model analyzed_result_model_json = {} - analyzed_result_model_json['metadata'] = {'key1': 'testString'} - analyzed_result_model_json['foo'] = {'foo': 'bar'} + analyzed_result_model_json['metadata'] = {'foo': 'bar'} + analyzed_result_model_json['foo'] = 'testString' # Construct a model instance of AnalyzedResult by calling from_dict on the json representation analyzed_result_model = AnalyzedResult.from_dict(analyzed_result_model_json) @@ -5338,7 +5316,7 @@ def test_analyzed_result_serialization(self): actual_dict = analyzed_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': {'foo': 'bar'}} + expected_dict = {'foo': 'testString'} analyzed_result_model.set_properties(expected_dict) actual_dict = analyzed_result_model.get_properties() assert actual_dict == expected_dict @@ -5433,7 +5411,6 @@ def test_collection_serialization(self): # Construct a json representation of a Collection model collection_model_json = {} - collection_model_json['collection_id'] = 'testString' collection_model_json['name'] = 'testString' # Construct a model instance of Collection by calling from_dict on the json representation @@ -5467,19 +5444,12 @@ def test_collection_details_serialization(self): collection_enrichment_model['enrichment_id'] = 'testString' collection_enrichment_model['fields'] = ['testString'] - collection_details_smart_document_understanding_model = {} # CollectionDetailsSmartDocumentUnderstanding - collection_details_smart_document_understanding_model['enabled'] = True - collection_details_smart_document_understanding_model['model'] = 'custom' - # Construct a json representation of a CollectionDetails model collection_details_model_json = {} - collection_details_model_json['collection_id'] = 'testString' collection_details_model_json['name'] = 'testString' collection_details_model_json['description'] = 'testString' - collection_details_model_json['created'] = '2019-01-01T12:00:00Z' collection_details_model_json['language'] = 'en' collection_details_model_json['enrichments'] = [collection_enrichment_model] - collection_details_model_json['smart_document_understanding'] = collection_details_smart_document_understanding_model # Construct a model instance of CollectionDetails by calling from_dict on the json representation collection_details_model = CollectionDetails.from_dict(collection_details_model_json) @@ -6124,10 +6094,8 @@ def test_document_classifier_serialization(self): # Construct a json representation of a DocumentClassifier model document_classifier_model_json = {} - document_classifier_model_json['classifier_id'] = 'testString' document_classifier_model_json['name'] = 'testString' document_classifier_model_json['description'] = 'testString' - document_classifier_model_json['created'] = '2019-01-01T12:00:00Z' document_classifier_model_json['language'] = 'en' document_classifier_model_json['enrichments'] = [document_classifier_enrichment_model] document_classifier_model_json['recognized_fields'] = ['testString'] @@ -6216,17 +6184,13 @@ def test_document_classifier_model_serialization(self): # Construct a json representation of a DocumentClassifierModel model document_classifier_model_model_json = {} - document_classifier_model_model_json['model_id'] = 'testString' document_classifier_model_model_json['name'] = 'testString' document_classifier_model_model_json['description'] = 'testString' - document_classifier_model_model_json['created'] = '2019-01-01T12:00:00Z' - document_classifier_model_model_json['updated'] = '2019-01-01T12:00:00Z' document_classifier_model_model_json['training_data_file'] = 'testString' document_classifier_model_model_json['test_data_file'] = 'testString' document_classifier_model_model_json['status'] = 'training' document_classifier_model_model_json['evaluation'] = classifier_model_evaluation_model document_classifier_model_model_json['enrichment_id'] = 'testString' - document_classifier_model_model_json['deployed_at'] = '2019-01-01T12:00:00Z' # Construct a model instance of DocumentClassifierModel by calling from_dict on the json representation document_classifier_model_model = DocumentClassifierModel.from_dict(document_classifier_model_model_json) @@ -6277,17 +6241,13 @@ def test_document_classifier_models_serialization(self): classifier_model_evaluation_model['per_class'] = [per_class_model_evaluation_model] document_classifier_model_model = {} # DocumentClassifierModel - document_classifier_model_model['model_id'] = 'testString' document_classifier_model_model['name'] = 'testString' document_classifier_model_model['description'] = 'testString' - document_classifier_model_model['created'] = '2019-01-01T12:00:00Z' - document_classifier_model_model['updated'] = '2019-01-01T12:00:00Z' document_classifier_model_model['training_data_file'] = 'testString' document_classifier_model_model['test_data_file'] = 'testString' document_classifier_model_model['status'] = 'training' document_classifier_model_model['evaluation'] = classifier_model_evaluation_model document_classifier_model_model['enrichment_id'] = 'testString' - document_classifier_model_model['deployed_at'] = '2019-01-01T12:00:00Z' # Construct a json representation of a DocumentClassifierModels model document_classifier_models_model_json = {} @@ -6328,10 +6288,8 @@ def test_document_classifiers_serialization(self): classifier_federated_model_model['field'] = 'testString' document_classifier_model = {} # DocumentClassifier - document_classifier_model['classifier_id'] = 'testString' document_classifier_model['name'] = 'testString' document_classifier_model['description'] = 'testString' - document_classifier_model['created'] = '2019-01-01T12:00:00Z' document_classifier_model['language'] = 'en' document_classifier_model['enrichments'] = [document_classifier_enrichment_model] document_classifier_model['recognized_fields'] = ['testString'] @@ -6372,14 +6330,6 @@ def test_document_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['notice_id'] = 'testString' - notice_model['created'] = '2019-01-01T12:00:00Z' - notice_model['document_id'] = 'testString' - notice_model['collection_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'testString' document_details_children_model = {} # DocumentDetailsChildren document_details_children_model['have_notices'] = True @@ -6387,9 +6337,6 @@ def test_document_details_serialization(self): # Construct a json representation of a DocumentDetails model document_details_model_json = {} - document_details_model_json['document_id'] = 'testString' - document_details_model_json['created'] = '2019-01-01T12:00:00Z' - document_details_model_json['updated'] = '2019-01-01T12:00:00Z' document_details_model_json['status'] = 'available' document_details_model_json['notices'] = [notice_model] document_details_model_json['children'] = document_details_children_model @@ -6466,7 +6413,6 @@ def test_enrichment_serialization(self): # Construct a json representation of a Enrichment model enrichment_model_json = {} - enrichment_model_json['enrichment_id'] = 'testString' enrichment_model_json['name'] = 'testString' enrichment_model_json['description'] = 'testString' enrichment_model_json['type'] = 'part_of_speech' @@ -6546,7 +6492,6 @@ def test_enrichments_serialization(self): enrichment_options_model['top_k'] = 38 enrichment_model = {} # Enrichment - enrichment_model['enrichment_id'] = 'testString' enrichment_model['name'] = 'testString' enrichment_model['description'] = 'testString' enrichment_model['type'] = 'part_of_speech' @@ -6648,9 +6593,6 @@ def test_field_serialization(self): # Construct a json representation of a Field model field_model_json = {} - field_model_json['field'] = 'testString' - field_model_json['type'] = 'nested' - field_model_json['collection_id'] = 'testString' # Construct a model instance of Field by calling from_dict on the json representation field_model = Field.from_dict(field_model_json) @@ -6680,7 +6622,6 @@ def test_list_collections_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. collection_model = {} # Collection - collection_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' collection_model['name'] = 'example' # Construct a json representation of a ListCollectionsResponse model @@ -6715,23 +6656,12 @@ def test_list_documents_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['notice_id'] = 'testString' - notice_model['created'] = '2019-01-01T12:00:00Z' - notice_model['document_id'] = 'testString' - notice_model['collection_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'testString' document_details_children_model = {} # DocumentDetailsChildren document_details_children_model['have_notices'] = True document_details_children_model['count'] = 38 document_details_model = {} # DocumentDetails - document_details_model['document_id'] = '4ffcfd8052005b99469e632506763bac_0' - document_details_model['created'] = '2019-01-01T12:00:00Z' - document_details_model['updated'] = '2019-01-01T12:00:00Z' document_details_model['status'] = 'available' document_details_model['notices'] = [notice_model] document_details_model['children'] = document_details_children_model @@ -6772,9 +6702,6 @@ def test_list_fields_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. field_model = {} # Field - field_model['field'] = 'testString' - field_model['type'] = 'nested' - field_model['collection_id'] = 'testString' # Construct a json representation of a ListFieldsResponse model list_fields_response_model_json = {} @@ -6807,23 +6734,9 @@ def test_list_projects_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - project_list_details_relevancy_training_status_model = {} # ProjectListDetailsRelevancyTrainingStatus - project_list_details_relevancy_training_status_model['data_updated'] = 'testString' - project_list_details_relevancy_training_status_model['total_examples'] = 38 - project_list_details_relevancy_training_status_model['sufficient_label_diversity'] = True - project_list_details_relevancy_training_status_model['processing'] = True - project_list_details_relevancy_training_status_model['minimum_examples_added'] = True - project_list_details_relevancy_training_status_model['successfully_trained'] = 'testString' - project_list_details_relevancy_training_status_model['available'] = True - project_list_details_relevancy_training_status_model['notices'] = 38 - project_list_details_relevancy_training_status_model['minimum_queries_added'] = True - project_list_details_model = {} # ProjectListDetails - project_list_details_model['project_id'] = 'testString' project_list_details_model['name'] = 'testString' project_list_details_model['type'] = 'document_retrieval' - project_list_details_model['relevancy_training_status'] = project_list_details_relevancy_training_status_model - project_list_details_model['collection_count'] = 38 # Construct a json representation of a ListProjectsResponse model list_projects_response_model_json = {} @@ -6918,14 +6831,6 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} - notice_model_json['notice_id'] = 'testString' - notice_model_json['created'] = '2019-01-01T12:00:00Z' - notice_model_json['document_id'] = 'testString' - notice_model_json['collection_id'] = 'testString' - notice_model_json['query_id'] = 'testString' - notice_model_json['severity'] = 'warning' - notice_model_json['step'] = 'testString' - notice_model_json['description'] = 'testString' # Construct a model instance of Notice by calling from_dict on the json representation notice_model = Notice.from_dict(notice_model_json) @@ -6986,17 +6891,6 @@ def test_project_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - project_list_details_relevancy_training_status_model = {} # ProjectListDetailsRelevancyTrainingStatus - project_list_details_relevancy_training_status_model['data_updated'] = 'testString' - project_list_details_relevancy_training_status_model['total_examples'] = 38 - project_list_details_relevancy_training_status_model['sufficient_label_diversity'] = True - project_list_details_relevancy_training_status_model['processing'] = True - project_list_details_relevancy_training_status_model['minimum_examples_added'] = True - project_list_details_relevancy_training_status_model['successfully_trained'] = 'testString' - project_list_details_relevancy_training_status_model['available'] = True - project_list_details_relevancy_training_status_model['notices'] = 38 - project_list_details_relevancy_training_status_model['minimum_queries_added'] = True - default_query_params_passages_model = {} # DefaultQueryParamsPassages default_query_params_passages_model['enabled'] = True default_query_params_passages_model['count'] = 38 @@ -7028,11 +6922,8 @@ def test_project_details_serialization(self): # Construct a json representation of a ProjectDetails model project_details_model_json = {} - project_details_model_json['project_id'] = 'testString' project_details_model_json['name'] = 'testString' project_details_model_json['type'] = 'document_retrieval' - project_details_model_json['relevancy_training_status'] = project_list_details_relevancy_training_status_model - project_details_model_json['collection_count'] = 38 project_details_model_json['default_query_parameters'] = default_query_params_model # Construct a model instance of ProjectDetails by calling from_dict on the json representation @@ -7060,26 +6951,10 @@ def test_project_list_details_serialization(self): Test serialization/deserialization for ProjectListDetails """ - # Construct dict forms of any model objects needed in order to build this model. - - project_list_details_relevancy_training_status_model = {} # ProjectListDetailsRelevancyTrainingStatus - project_list_details_relevancy_training_status_model['data_updated'] = 'testString' - project_list_details_relevancy_training_status_model['total_examples'] = 38 - project_list_details_relevancy_training_status_model['sufficient_label_diversity'] = True - project_list_details_relevancy_training_status_model['processing'] = True - project_list_details_relevancy_training_status_model['minimum_examples_added'] = True - project_list_details_relevancy_training_status_model['successfully_trained'] = 'testString' - project_list_details_relevancy_training_status_model['available'] = True - project_list_details_relevancy_training_status_model['notices'] = 38 - project_list_details_relevancy_training_status_model['minimum_queries_added'] = True - # Construct a json representation of a ProjectListDetails model project_list_details_model_json = {} - project_list_details_model_json['project_id'] = 'testString' project_list_details_model_json['name'] = 'testString' project_list_details_model_json['type'] = 'document_retrieval' - project_list_details_model_json['relevancy_training_status'] = project_list_details_relevancy_training_status_model - project_list_details_model_json['collection_count'] = 38 # Construct a model instance of ProjectListDetails by calling from_dict on the json representation project_list_details_model = ProjectListDetails.from_dict(project_list_details_model_json) @@ -7381,14 +7256,6 @@ def test_query_notices_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['notice_id'] = 'testString' - notice_model['created'] = '2019-01-01T12:00:00Z' - notice_model['document_id'] = 'testString' - notice_model['collection_id'] = 'testString' - notice_model['query_id'] = 'testString' - notice_model['severity'] = 'warning' - notice_model['step'] = 'testString' - notice_model['description'] = 'testString' # Construct a json representation of a QueryNoticesResponse model query_notices_response_model_json = {} @@ -7443,10 +7310,10 @@ def test_query_response_serialization(self): query_result_model = {} # QueryResult query_result_model['document_id'] = 'testString' - query_result_model['metadata'] = {'key1': 'testString'} + query_result_model['metadata'] = {'foo': 'bar'} query_result_model['result_metadata'] = query_result_metadata_model query_result_model['document_passages'] = [query_result_passage_model] - query_result_model['id'] = {'foo': 'bar'} + query_result_model['id'] = 'watson-generated ID' query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' @@ -7685,10 +7552,10 @@ def test_query_result_serialization(self): # Construct a json representation of a QueryResult model query_result_model_json = {} query_result_model_json['document_id'] = 'testString' - query_result_model_json['metadata'] = {'key1': 'testString'} + query_result_model_json['metadata'] = {'foo': 'bar'} query_result_model_json['result_metadata'] = query_result_metadata_model query_result_model_json['document_passages'] = [query_result_passage_model] - query_result_model_json['foo'] = {'foo': 'bar'} + query_result_model_json['foo'] = 'testString' # Construct a model instance of QueryResult by calling from_dict on the json representation query_result_model = QueryResult.from_dict(query_result_model_json) @@ -7710,7 +7577,7 @@ def test_query_result_serialization(self): actual_dict = query_result_model.get_properties() assert actual_dict == {} - expected_dict = {'foo': {'foo': 'bar'}} + expected_dict = {'foo': 'testString'} query_result_model.set_properties(expected_dict) actual_dict = query_result_model.get_properties() assert actual_dict == expected_dict @@ -8048,7 +7915,7 @@ def test_query_top_hits_aggregation_result_serialization(self): # Construct a json representation of a QueryTopHitsAggregationResult model query_top_hits_aggregation_result_model_json = {} query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{'key1': 'testString'}] + query_top_hits_aggregation_result_model_json['hits'] = [{'foo': 'bar'}] # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) @@ -8844,8 +8711,6 @@ def test_training_example_serialization(self): training_example_model_json['document_id'] = 'testString' training_example_model_json['collection_id'] = 'testString' training_example_model_json['relevance'] = 38 - training_example_model_json['created'] = '2019-01-01T12:00:00Z' - training_example_model_json['updated'] = '2019-01-01T12:00:00Z' # Construct a model instance of TrainingExample by calling from_dict on the json representation training_example_model = TrainingExample.from_dict(training_example_model_json) @@ -8878,16 +8743,11 @@ def test_training_query_serialization(self): training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_example_model['created'] = '2019-01-01T12:00:00Z' - training_example_model['updated'] = '2019-01-01T12:00:00Z' # Construct a json representation of a TrainingQuery model training_query_model_json = {} - training_query_model_json['query_id'] = 'testString' training_query_model_json['natural_language_query'] = 'testString' training_query_model_json['filter'] = 'testString' - training_query_model_json['created'] = '2019-01-01T12:00:00Z' - training_query_model_json['updated'] = '2019-01-01T12:00:00Z' training_query_model_json['examples'] = [training_example_model] # Construct a model instance of TrainingQuery by calling from_dict on the json representation @@ -8921,15 +8781,10 @@ def test_training_query_set_serialization(self): training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_example_model['created'] = '2019-01-01T12:00:00Z' - training_example_model['updated'] = '2019-01-01T12:00:00Z' training_query_model = {} # TrainingQuery - training_query_model['query_id'] = 'testString' training_query_model['natural_language_query'] = 'testString' training_query_model['filter'] = 'testString' - training_query_model['created'] = '2019-01-01T12:00:00Z' - training_query_model['updated'] = '2019-01-01T12:00:00Z' training_query_model['examples'] = [training_example_model] # Construct a json representation of a TrainingQuerySet model @@ -9213,7 +9068,7 @@ def test_query_top_hits_aggregation_serialization(self): query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{'key1': 'testString'}] + query_top_hits_aggregation_result_model['hits'] = [{'foo': 'bar'}] # Construct a json representation of a QueryTopHitsAggregation model query_top_hits_aggregation_model_json = {} diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index cd020c142..2217b442e 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2022. +# (C) Copyright IBM Corp. 2018, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ _service = LanguageTranslatorV3( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.language-translator.watson.cloud.ibm.com' diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 0d6deebda..65aaf89ab 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2022. +# (C) Copyright IBM Corp. 2019, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -35,7 +35,7 @@ _service = NaturalLanguageUnderstandingV1( authenticator=NoAuthAuthenticator(), - version=version + version=version, ) _base_url = 'https://api.us-south.natural-language-understanding.watson.cloud.ibm.com' @@ -162,7 +162,7 @@ def test_analyze_all_params(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = {'key1': 'testString'} + features_model['metadata'] = {'foo': 'bar'} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -306,7 +306,7 @@ def test_analyze_value_error(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = {'key1': 'testString'} + features_model['metadata'] = {'foo': 'bar'} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -519,7 +519,7 @@ def test_create_sentiment_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/sentiment') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.POST, url, body=mock_response, @@ -567,7 +567,7 @@ def test_create_sentiment_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/sentiment') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.POST, url, body=mock_response, @@ -605,7 +605,7 @@ def test_create_sentiment_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/sentiment') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.POST, url, body=mock_response, @@ -647,7 +647,7 @@ def test_list_sentiment_models_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/sentiment') - mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' + mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' responses.add(responses.GET, url, body=mock_response, @@ -678,7 +678,7 @@ def test_list_sentiment_models_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/sentiment') - mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' + mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' responses.add(responses.GET, url, body=mock_response, @@ -714,7 +714,7 @@ def test_get_sentiment_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.GET, url, body=mock_response, @@ -750,7 +750,7 @@ def test_get_sentiment_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.GET, url, body=mock_response, @@ -790,7 +790,7 @@ def test_update_sentiment_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.PUT, url, body=mock_response, @@ -840,7 +840,7 @@ def test_update_sentiment_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.PUT, url, body=mock_response, @@ -880,7 +880,7 @@ def test_update_sentiment_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' + mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' responses.add(responses.PUT, url, body=mock_response, @@ -1010,7 +1010,7 @@ def test_create_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1060,7 +1060,7 @@ def test_create_categories_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1098,7 +1098,7 @@ def test_create_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1140,7 +1140,7 @@ def test_list_categories_models_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1171,7 +1171,7 @@ def test_list_categories_models_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1207,7 +1207,7 @@ def test_get_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1243,7 +1243,7 @@ def test_get_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1283,7 +1283,7 @@ def test_update_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1335,7 +1335,7 @@ def test_update_categories_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1375,7 +1375,7 @@ def test_update_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1505,7 +1505,7 @@ def test_create_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1561,7 +1561,7 @@ def test_create_classifications_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1599,7 +1599,7 @@ def test_create_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.POST, url, body=mock_response, @@ -1641,7 +1641,7 @@ def test_list_classifications_models_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1672,7 +1672,7 @@ def test_list_classifications_models_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' responses.add(responses.GET, url, body=mock_response, @@ -1708,7 +1708,7 @@ def test_get_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1744,7 +1744,7 @@ def test_get_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1784,7 +1784,7 @@ def test_update_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1842,7 +1842,7 @@ def test_update_classifications_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -1882,7 +1882,7 @@ def test_update_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": {"anyKey": "anyValue"}}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' responses.add(responses.PUT, url, body=mock_response, @@ -2277,12 +2277,11 @@ def test_categories_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' # Construct a json representation of a CategoriesModel model categories_model_model_json = {} categories_model_model_json['name'] = 'testString' - categories_model_model_json['user_metadata'] = {'key1': {'foo': 'bar'}} + categories_model_model_json['user_metadata'] = {'key1': 'unknown type: dict'} categories_model_model_json['language'] = 'testString' categories_model_model_json['description'] = 'testString' categories_model_model_json['model_version'] = 'testString' @@ -2324,11 +2323,10 @@ def test_categories_model_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' categories_model_model = {} # CategoriesModel categories_model_model['name'] = 'testString' - categories_model_model['user_metadata'] = {'key1': {'foo': 'bar'}} + categories_model_model['user_metadata'] = {'key1': 'unknown type: dict'} categories_model_model['language'] = 'testString' categories_model_model['description'] = 'testString' categories_model_model['model_version'] = 'testString' @@ -2507,12 +2505,11 @@ def test_classifications_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' # Construct a json representation of a ClassificationsModel model classifications_model_model_json = {} classifications_model_model_json['name'] = 'testString' - classifications_model_model_json['user_metadata'] = {'key1': {'foo': 'bar'}} + classifications_model_model_json['user_metadata'] = {'key1': 'unknown type: dict'} classifications_model_model_json['language'] = 'testString' classifications_model_model_json['description'] = 'testString' classifications_model_model_json['model_version'] = 'testString' @@ -2554,11 +2551,10 @@ def test_classifications_model_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' classifications_model_model = {} # ClassificationsModel classifications_model_model['name'] = 'testString' - classifications_model_model['user_metadata'] = {'key1': {'foo': 'bar'}} + classifications_model_model['user_metadata'] = {'key1': 'unknown type: dict'} classifications_model_model['language'] = 'testString' classifications_model_model['description'] = 'testString' classifications_model_model['model_version'] = 'testString' @@ -3198,7 +3194,7 @@ def test_features_serialization(self): features_model_json['emotion'] = emotion_options_model features_model_json['entities'] = entities_options_model features_model_json['keywords'] = keywords_options_model - features_model_json['metadata'] = {'key1': 'testString'} + features_model_json['metadata'] = {'foo': 'bar'} features_model_json['relations'] = relations_options_model features_model_json['semantic_roles'] = semantic_roles_options_model features_model_json['sentiment'] = sentiment_options_model @@ -3422,7 +3418,6 @@ def test_list_sentiment_models_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' sentiment_model_model = {} # SentimentModel sentiment_model_model['features'] = ['testString'] @@ -3432,7 +3427,7 @@ def test_list_sentiment_models_response_serialization(self): sentiment_model_model['last_trained'] = '2019-01-01T12:00:00Z' sentiment_model_model['last_deployed'] = '2019-01-01T12:00:00Z' sentiment_model_model['name'] = 'testString' - sentiment_model_model['user_metadata'] = {'key1': {'foo': 'bar'}} + sentiment_model_model['user_metadata'] = {'key1': 'unknown type: dict'} sentiment_model_model['language'] = 'testString' sentiment_model_model['description'] = 'testString' sentiment_model_model['model_version'] = 'testString' @@ -3508,7 +3503,6 @@ def test_notice_serialization(self): # Construct a json representation of a Notice model notice_model_json = {} - notice_model_json['message'] = 'testString' # Construct a model instance of Notice by calling from_dict on the json representation notice_model = Notice.from_dict(notice_model_json) @@ -3998,7 +3992,6 @@ def test_sentiment_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. notice_model = {} # Notice - notice_model['message'] = 'Training data validation failed: Too few examples for label insufficient_examples. Minimum of 5 required' # Construct a json representation of a SentimentModel model sentiment_model_model_json = {} @@ -4009,7 +4002,7 @@ def test_sentiment_model_serialization(self): sentiment_model_model_json['last_trained'] = '2019-01-01T12:00:00Z' sentiment_model_model_json['last_deployed'] = '2019-01-01T12:00:00Z' sentiment_model_model_json['name'] = 'testString' - sentiment_model_model_json['user_metadata'] = {'key1': {'foo': 'bar'}} + sentiment_model_model_json['user_metadata'] = {'key1': 'unknown type: dict'} sentiment_model_model_json['language'] = 'testString' sentiment_model_model_json['description'] = 'testString' sentiment_model_model_json['model_version'] = 'testString' diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index c71e6f2a8..135d950c0 100644 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2022. +# (C) Copyright IBM Corp. 2015, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -220,9 +220,9 @@ def test_recognize_all_params(self): customization_weight = 72.5 inactivity_timeout = 38 keywords = ['testString'] - keywords_threshold = 72.5 + keywords_threshold = 36.0 max_alternatives = 38 - word_alternatives_threshold = 72.5 + word_alternatives_threshold = 36.0 word_confidence = False timestamps = False profanity_filter = True @@ -233,10 +233,10 @@ def test_recognize_all_params(self): audio_metrics = False end_of_phrase_silence_time = 72.5 split_transcript_at_phrase_end = False - speech_detector_sensitivity = 72.5 - background_audio_suppression = 72.5 + speech_detector_sensitivity = 36.0 + background_audio_suppression = 36.0 low_latency = False - character_insertion_bias = 72.5 + character_insertion_bias = 36.0 # Invoke method response = _service.recognize( @@ -282,9 +282,7 @@ def test_recognize_all_params(self): assert 'customization_weight={}'.format(customization_weight) in query_string assert 'inactivity_timeout={}'.format(inactivity_timeout) in query_string assert 'keywords={}'.format(','.join(keywords)) in query_string - assert 'keywords_threshold={}'.format(keywords_threshold) in query_string assert 'max_alternatives={}'.format(max_alternatives) in query_string - assert 'word_alternatives_threshold={}'.format(word_alternatives_threshold) in query_string assert 'word_confidence={}'.format('true' if word_confidence else 'false') in query_string assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string @@ -295,10 +293,7 @@ def test_recognize_all_params(self): assert 'audio_metrics={}'.format('true' if audio_metrics else 'false') in query_string assert 'end_of_phrase_silence_time={}'.format(end_of_phrase_silence_time) in query_string assert 'split_transcript_at_phrase_end={}'.format('true' if split_transcript_at_phrase_end else 'false') in query_string - assert 'speech_detector_sensitivity={}'.format(speech_detector_sensitivity) in query_string - assert 'background_audio_suppression={}'.format(background_audio_suppression) in query_string assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string - assert 'character_insertion_bias={}'.format(character_insertion_bias) in query_string # Validate body params def test_recognize_all_params_with_retries(self): @@ -622,9 +617,9 @@ def test_create_job_all_params(self): customization_weight = 72.5 inactivity_timeout = 38 keywords = ['testString'] - keywords_threshold = 72.5 + keywords_threshold = 36.0 max_alternatives = 38 - word_alternatives_threshold = 72.5 + word_alternatives_threshold = 36.0 word_confidence = False timestamps = False profanity_filter = True @@ -633,14 +628,14 @@ def test_create_job_all_params(self): grammar_name = 'testString' redaction = False processing_metrics = False - processing_metrics_interval = 72.5 + processing_metrics_interval = 36.0 audio_metrics = False end_of_phrase_silence_time = 72.5 split_transcript_at_phrase_end = False - speech_detector_sensitivity = 72.5 - background_audio_suppression = 72.5 + speech_detector_sensitivity = 36.0 + background_audio_suppression = 36.0 low_latency = False - character_insertion_bias = 72.5 + character_insertion_bias = 36.0 # Invoke method response = _service.create_job( @@ -696,9 +691,7 @@ def test_create_job_all_params(self): assert 'customization_weight={}'.format(customization_weight) in query_string assert 'inactivity_timeout={}'.format(inactivity_timeout) in query_string assert 'keywords={}'.format(','.join(keywords)) in query_string - assert 'keywords_threshold={}'.format(keywords_threshold) in query_string assert 'max_alternatives={}'.format(max_alternatives) in query_string - assert 'word_alternatives_threshold={}'.format(word_alternatives_threshold) in query_string assert 'word_confidence={}'.format('true' if word_confidence else 'false') in query_string assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string @@ -707,14 +700,10 @@ def test_create_job_all_params(self): assert 'grammar_name={}'.format(grammar_name) in query_string assert 'redaction={}'.format('true' if redaction else 'false') in query_string assert 'processing_metrics={}'.format('true' if processing_metrics else 'false') in query_string - assert 'processing_metrics_interval={}'.format(processing_metrics_interval) in query_string assert 'audio_metrics={}'.format('true' if audio_metrics else 'false') in query_string assert 'end_of_phrase_silence_time={}'.format(end_of_phrase_silence_time) in query_string assert 'split_transcript_at_phrase_end={}'.format('true' if split_transcript_at_phrase_end else 'false') in query_string - assert 'speech_detector_sensitivity={}'.format(speech_detector_sensitivity) in query_string - assert 'background_audio_suppression={}'.format(background_audio_suppression) in query_string assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string - assert 'character_insertion_bias={}'.format(character_insertion_bias) in query_string # Validate body params def test_create_job_all_params_with_retries(self): @@ -4022,16 +4011,16 @@ def test_audio_metrics_serialization(self): # Construct dict forms of any model objects needed in order to build this model. audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin - audio_metrics_histogram_bin_model['begin'] = 72.5 - audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['begin'] = 36.0 + audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True - audio_metrics_details_model['end_time'] = 72.5 - audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 - audio_metrics_details_model['speech_ratio'] = 72.5 - audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['end_time'] = 36.0 + audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 + audio_metrics_details_model['speech_ratio'] = 36.0 + audio_metrics_details_model['high_frequency_loss'] = 36.0 audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] @@ -4039,7 +4028,7 @@ def test_audio_metrics_serialization(self): # Construct a json representation of a AudioMetrics model audio_metrics_model_json = {} - audio_metrics_model_json['sampling_interval'] = 72.5 + audio_metrics_model_json['sampling_interval'] = 36.0 audio_metrics_model_json['accumulated'] = audio_metrics_details_model # Construct a model instance of AudioMetrics by calling from_dict on the json representation @@ -4070,17 +4059,17 @@ def test_audio_metrics_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin - audio_metrics_histogram_bin_model['begin'] = 72.5 - audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['begin'] = 36.0 + audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 # Construct a json representation of a AudioMetricsDetails model audio_metrics_details_model_json = {} audio_metrics_details_model_json['final'] = True - audio_metrics_details_model_json['end_time'] = 72.5 - audio_metrics_details_model_json['signal_to_noise_ratio'] = 72.5 - audio_metrics_details_model_json['speech_ratio'] = 72.5 - audio_metrics_details_model_json['high_frequency_loss'] = 72.5 + audio_metrics_details_model_json['end_time'] = 36.0 + audio_metrics_details_model_json['signal_to_noise_ratio'] = 36.0 + audio_metrics_details_model_json['speech_ratio'] = 36.0 + audio_metrics_details_model_json['high_frequency_loss'] = 36.0 audio_metrics_details_model_json['direct_current_offset'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model_json['clipping_rate'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model_json['speech_level'] = [audio_metrics_histogram_bin_model] @@ -4113,8 +4102,8 @@ def test_audio_metrics_histogram_bin_serialization(self): # Construct a json representation of a AudioMetricsHistogramBin model audio_metrics_histogram_bin_model_json = {} - audio_metrics_histogram_bin_model_json['begin'] = 72.5 - audio_metrics_histogram_bin_model_json['end'] = 72.5 + audio_metrics_histogram_bin_model_json['begin'] = 36.0 + audio_metrics_histogram_bin_model_json['end'] = 36.0 audio_metrics_histogram_bin_model_json['count'] = 38 # Construct a model instance of AudioMetricsHistogramBin by calling from_dict on the json representation @@ -4520,10 +4509,10 @@ def test_processed_audio_serialization(self): # Construct a json representation of a ProcessedAudio model processed_audio_model_json = {} - processed_audio_model_json['received'] = 72.5 - processed_audio_model_json['seen_by_engine'] = 72.5 - processed_audio_model_json['transcription'] = 72.5 - processed_audio_model_json['speaker_labels'] = 72.5 + processed_audio_model_json['received'] = 36.0 + processed_audio_model_json['seen_by_engine'] = 36.0 + processed_audio_model_json['transcription'] = 36.0 + processed_audio_model_json['speaker_labels'] = 36.0 # Construct a model instance of ProcessedAudio by calling from_dict on the json representation processed_audio_model = ProcessedAudio.from_dict(processed_audio_model_json) @@ -4553,15 +4542,15 @@ def test_processing_metrics_serialization(self): # Construct dict forms of any model objects needed in order to build this model. processed_audio_model = {} # ProcessedAudio - processed_audio_model['received'] = 72.5 - processed_audio_model['seen_by_engine'] = 72.5 - processed_audio_model['transcription'] = 72.5 - processed_audio_model['speaker_labels'] = 72.5 + processed_audio_model['received'] = 36.0 + processed_audio_model['seen_by_engine'] = 36.0 + processed_audio_model['transcription'] = 36.0 + processed_audio_model['speaker_labels'] = 36.0 # Construct a json representation of a ProcessingMetrics model processing_metrics_model_json = {} processing_metrics_model_json['processed_audio'] = processed_audio_model - processing_metrics_model_json['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model_json['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model_json['periodic'] = True # Construct a model instance of ProcessingMetrics by calling from_dict on the json representation @@ -4620,41 +4609,41 @@ def test_recognition_job_serialization(self): speech_recognition_result_model['end_of_utterance'] = 'end_of_data' speaker_labels_result_model = {} # SpeakerLabelsResult - speaker_labels_result_model['from'] = 72.5 - speaker_labels_result_model['to'] = 72.5 + speaker_labels_result_model['from'] = 36.0 + speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 - speaker_labels_result_model['confidence'] = 72.5 + speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True processed_audio_model = {} # ProcessedAudio - processed_audio_model['received'] = 72.5 - processed_audio_model['seen_by_engine'] = 72.5 - processed_audio_model['transcription'] = 72.5 - processed_audio_model['speaker_labels'] = 72.5 + processed_audio_model['received'] = 36.0 + processed_audio_model['seen_by_engine'] = 36.0 + processed_audio_model['transcription'] = 36.0 + processed_audio_model['speaker_labels'] = 36.0 processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model - processing_metrics_model['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin - audio_metrics_histogram_bin_model['begin'] = 72.5 - audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['begin'] = 36.0 + audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True - audio_metrics_details_model['end_time'] = 72.5 - audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 - audio_metrics_details_model['speech_ratio'] = 72.5 - audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['end_time'] = 36.0 + audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 + audio_metrics_details_model['speech_ratio'] = 36.0 + audio_metrics_details_model['high_frequency_loss'] = 36.0 audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_model = {} # AudioMetrics - audio_metrics_model['sampling_interval'] = 72.5 + audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model speech_recognition_results_model = {} # SpeechRecognitionResults @@ -4732,41 +4721,41 @@ def test_recognition_jobs_serialization(self): speech_recognition_result_model['end_of_utterance'] = 'end_of_data' speaker_labels_result_model = {} # SpeakerLabelsResult - speaker_labels_result_model['from'] = 72.5 - speaker_labels_result_model['to'] = 72.5 + speaker_labels_result_model['from'] = 36.0 + speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 - speaker_labels_result_model['confidence'] = 72.5 + speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True processed_audio_model = {} # ProcessedAudio - processed_audio_model['received'] = 72.5 - processed_audio_model['seen_by_engine'] = 72.5 - processed_audio_model['transcription'] = 72.5 - processed_audio_model['speaker_labels'] = 72.5 + processed_audio_model['received'] = 36.0 + processed_audio_model['seen_by_engine'] = 36.0 + processed_audio_model['transcription'] = 36.0 + processed_audio_model['speaker_labels'] = 36.0 processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model - processing_metrics_model['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin - audio_metrics_histogram_bin_model['begin'] = 72.5 - audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['begin'] = 36.0 + audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True - audio_metrics_details_model['end_time'] = 72.5 - audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 - audio_metrics_details_model['speech_ratio'] = 72.5 - audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['end_time'] = 36.0 + audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 + audio_metrics_details_model['speech_ratio'] = 36.0 + audio_metrics_details_model['high_frequency_loss'] = 36.0 audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_model = {} # AudioMetrics - audio_metrics_model['sampling_interval'] = 72.5 + audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model speech_recognition_results_model = {} # SpeechRecognitionResults @@ -4848,10 +4837,10 @@ def test_speaker_labels_result_serialization(self): # Construct a json representation of a SpeakerLabelsResult model speaker_labels_result_model_json = {} - speaker_labels_result_model_json['from'] = 72.5 - speaker_labels_result_model_json['to'] = 72.5 + speaker_labels_result_model_json['from'] = 36.0 + speaker_labels_result_model_json['to'] = 36.0 speaker_labels_result_model_json['speaker'] = 38 - speaker_labels_result_model_json['confidence'] = 72.5 + speaker_labels_result_model_json['confidence'] = 36.0 speaker_labels_result_model_json['final'] = True # Construct a model instance of SpeakerLabelsResult by calling from_dict on the json representation @@ -5085,41 +5074,41 @@ def test_speech_recognition_results_serialization(self): speech_recognition_result_model['end_of_utterance'] = 'end_of_data' speaker_labels_result_model = {} # SpeakerLabelsResult - speaker_labels_result_model['from'] = 72.5 - speaker_labels_result_model['to'] = 72.5 + speaker_labels_result_model['from'] = 36.0 + speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 - speaker_labels_result_model['confidence'] = 72.5 + speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True processed_audio_model = {} # ProcessedAudio - processed_audio_model['received'] = 72.5 - processed_audio_model['seen_by_engine'] = 72.5 - processed_audio_model['transcription'] = 72.5 - processed_audio_model['speaker_labels'] = 72.5 + processed_audio_model['received'] = 36.0 + processed_audio_model['seen_by_engine'] = 36.0 + processed_audio_model['transcription'] = 36.0 + processed_audio_model['speaker_labels'] = 36.0 processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model - processing_metrics_model['wall_clock_since_first_byte_received'] = 72.5 + processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin - audio_metrics_histogram_bin_model['begin'] = 72.5 - audio_metrics_histogram_bin_model['end'] = 72.5 + audio_metrics_histogram_bin_model['begin'] = 36.0 + audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True - audio_metrics_details_model['end_time'] = 72.5 - audio_metrics_details_model['signal_to_noise_ratio'] = 72.5 - audio_metrics_details_model['speech_ratio'] = 72.5 - audio_metrics_details_model['high_frequency_loss'] = 72.5 + audio_metrics_details_model['end_time'] = 36.0 + audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 + audio_metrics_details_model['speech_ratio'] = 36.0 + audio_metrics_details_model['high_frequency_loss'] = 36.0 audio_metrics_details_model['direct_current_offset'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['clipping_rate'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_model = {} # AudioMetrics - audio_metrics_model['sampling_interval'] = 72.5 + audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model # Construct a json representation of a SpeechRecognitionResults model diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 36af23b08..15250dfac 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2022. +# (C) Copyright IBM Corp. 2015, 2023. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. From 696b17a8f6def43b6ffe645cc5b941851320a2dd Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 23 Feb 2023 12:01:14 -0600 Subject: [PATCH 384/455] refactor(assistantv1,discov1,lt): comment changes --- ibm_watson/assistant_v1.py | 96 +++++++++++++++++------- ibm_watson/discovery_v1.py | 2 +- ibm_watson/language_translator_v3.py | 64 +++++++++++----- test/unit/test_assistant_v1.py | 58 +++++++------- test/unit/test_language_translator_v3.py | 2 +- 5 files changed, 143 insertions(+), 79 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 6f52fcc8a..ac77027c2 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -4467,6 +4467,8 @@ class Context(): the previous response. :attr str conversation_id: (optional) The unique identifier of the conversation. + The conversation ID cannot contain any of the following characters: `+` `=` `&&` + `||` `>` `<` `!` `(` `)` `{` `}` `[` `]` `^` `"` `~` `*` `?` `:` `\` `/`. :attr dict system: (optional) For internal use only. :attr MessageContextMetadata metadata: (optional) Metadata related to the message. @@ -4485,7 +4487,9 @@ def __init__(self, Initialize a Context object. :param str conversation_id: (optional) The unique identifier of the - conversation. + conversation. The conversation ID cannot contain any of the following + characters: `+` `=` `&&` `||` `>` `<` `!` `(` `)` `{` `}` `[` `]` `^` `"` + `~` `*` `?` `:` `\` `/`. :param dict system: (optional) For internal use only. :param MessageContextMetadata metadata: (optional) Metadata related to the message. @@ -4662,7 +4666,8 @@ class CounterexampleCollection(): :attr List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, counterexamples: List['Counterexample'], @@ -4673,6 +4678,7 @@ def __init__(self, counterexamples: List['Counterexample'], :param List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.counterexamples = counterexamples self.pagination = pagination @@ -5591,7 +5597,8 @@ class DialogNodeCollection(): :attr List[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, dialog_nodes: List['DialogNode'], @@ -5602,6 +5609,7 @@ def __init__(self, dialog_nodes: List['DialogNode'], :param List[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.dialog_nodes = dialog_nodes self.pagination = pagination @@ -6591,6 +6599,9 @@ class DialogSuggestion(): :attr DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. + **Note:** These properties must be included in the request body of the next + message sent to the assistant. Do not modify or remove any of the included + properties. :attr dict output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. :attr str dialog_node: (optional) The unique ID of the dialog node that the @@ -6613,6 +6624,9 @@ def __init__(self, :param DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. + **Note:** These properties must be included in the request body of the + next message sent to the assistant. Do not modify or remove any of the + included properties. :param dict output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. :param str dialog_node: (optional) The unique ID of the dialog node that @@ -6690,6 +6704,8 @@ class DialogSuggestionValue(): """ An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. + **Note:** These properties must be included in the request body of the next message + sent to the assistant. Do not modify or remove any of the included properties. :attr MessageInput input: (optional) An input object that includes the input text. @@ -6918,7 +6934,8 @@ class EntityCollection(): :attr List[Entity] entities: An array of objects describing the entities defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, entities: List['Entity'], @@ -6929,6 +6946,7 @@ def __init__(self, entities: List['Entity'], :param List[Entity] entities: An array of objects describing the entities defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.entities = entities self.pagination = pagination @@ -7082,7 +7100,8 @@ class EntityMentionCollection(): :attr List[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, examples: List['EntityMention'], @@ -7093,6 +7112,7 @@ def __init__(self, examples: List['EntityMention'], :param List[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.examples = examples self.pagination = pagination @@ -7262,7 +7282,8 @@ class ExampleCollection(): :attr List[Example] examples: An array of objects describing the examples defined for the intent. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, examples: List['Example'], @@ -7273,6 +7294,7 @@ def __init__(self, examples: List['Example'], :param List[Example] examples: An array of objects describing the examples defined for the intent. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.examples = examples self.pagination = pagination @@ -7455,7 +7477,8 @@ class IntentCollection(): :attr List[Intent] intents: An array of objects describing the intents defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, intents: List['Intent'], @@ -7466,6 +7489,7 @@ def __init__(self, intents: List['Intent'], :param List[Intent] intents: An array of objects describing the intents defined for the workspace. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.intents = intents self.pagination = pagination @@ -7678,6 +7702,7 @@ class LogCollection(): :attr List[Log] logs: An array of objects describing log events. :attr LogPagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: @@ -7686,7 +7711,8 @@ def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: :param List[Log] logs: An array of objects describing log events. :param LogPagination pagination: The pagination data for the returned - objects. + objects. For more information about using pagination, see + [Pagination](#pagination). """ self.logs = logs self.pagination = pagination @@ -7929,7 +7955,8 @@ class TypeEnum(str, Enum): class LogPagination(): """ - The pagination data for the returned objects. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). :attr str next_url: (optional) The URL that will return the next page of results, if any. @@ -8856,7 +8883,8 @@ def __ne__(self, other: 'OutputData') -> bool: class Pagination(): """ - The pagination data for the returned objects. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). :attr str refresh_url: The URL that will return the same page of results. :attr str next_url: (optional) The URL that will return the next page of @@ -8968,6 +8996,7 @@ class ResponseGenericChannel(): ResponseGenericChannel. :attr str channel: (optional) A channel for which the response is intended. + **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ def __init__(self, *, channel: str = None) -> None: @@ -8976,6 +9005,7 @@ def __init__(self, *, channel: str = None) -> None: :param str channel: (optional) A channel for which the response is intended. + **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ self.channel = channel @@ -9020,6 +9050,7 @@ def __ne__(self, other: 'ResponseGenericChannel') -> bool: class ChannelEnum(str, Enum): """ A channel for which the response is intended. + **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ CHAT = 'chat' FACEBOOK = 'facebook' @@ -10004,7 +10035,8 @@ class SynonymCollection(): SynonymCollection. :attr List[Synonym] synonyms: An array of synonyms. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, synonyms: List['Synonym'], @@ -10014,6 +10046,7 @@ def __init__(self, synonyms: List['Synonym'], :param List[Synonym] synonyms: An array of synonyms. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.synonyms = synonyms self.pagination = pagination @@ -10224,7 +10257,8 @@ class ValueCollection(): ValueCollection. :attr List[Value] values: An array of entity values. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: @@ -10233,6 +10267,7 @@ def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: :param List[Value] values: An array of entity values. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.values = values self.pagination = pagination @@ -10765,7 +10800,8 @@ class WorkspaceCollection(): :attr List[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. - :attr Pagination pagination: The pagination data for the returned objects. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__(self, workspaces: List['Workspace'], @@ -10776,6 +10812,7 @@ def __init__(self, workspaces: List['Workspace'], :param List[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ self.workspaces = workspaces self.pagination = pagination @@ -11268,9 +11305,11 @@ class WorkspaceSystemSettingsNlp(): the skill. :attr str model: (optional) The policy the skill follows for selecting the - algorithm version to use: - - `baseline`: the latest mature version - - `beta`: the latest beta version. + algorithm version to use. For more information, see the + [documentation](/docs/watson-assistant?topic=watson-assistant-algorithm-version). + On IBM Cloud, you can specify `latest`, `previous`, or `beta`. + On IBM Cloud Pak for Data, you can specify either `beta` or the date of the + version you want to use, in `YYYY-MM-DD` format. """ def __init__(self, *, model: str = None) -> None: @@ -11278,9 +11317,11 @@ def __init__(self, *, model: str = None) -> None: Initialize a WorkspaceSystemSettingsNlp object. :param str model: (optional) The policy the skill follows for selecting the - algorithm version to use: - - `baseline`: the latest mature version - - `beta`: the latest beta version. + algorithm version to use. For more information, see the + [documentation](/docs/watson-assistant?topic=watson-assistant-algorithm-version). + On IBM Cloud, you can specify `latest`, `previous`, or `beta`. + On IBM Cloud Pak for Data, you can specify either `beta` or the date of + the version you want to use, in `YYYY-MM-DD` format. """ self.model = model @@ -11322,15 +11363,6 @@ def __ne__(self, other: 'WorkspaceSystemSettingsNlp') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ModelEnum(str, Enum): - """ - The policy the skill follows for selecting the algorithm version to use: - - `baseline`: the latest mature version - - `beta`: the latest beta version. - """ - BASELINE = 'baseline' - BETA = 'beta' - class WorkspaceSystemSettingsOffTopic(): """ @@ -11652,6 +11684,8 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer( :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM Cloud + Pak for Data. :attr str message_to_user: The message to display to the user when initiating a channel transfer. :attr ChannelTransferInfo transfer_info: Information used by an integration to @@ -11672,6 +11706,8 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM + Cloud Pak for Data. :param str message_to_user: The message to display to the user when initiating a channel transfer. :param ChannelTransferInfo transfer_info: Information used by an @@ -13157,6 +13193,8 @@ class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM Cloud + Pak for Data. :attr str message_to_user: The message to display to the user when initiating a channel transfer. :attr ChannelTransferInfo transfer_info: Information used by an integration to @@ -13179,6 +13217,8 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM + Cloud Pak for Data. :param str message_to_user: The message to display to the user when initiating a channel transfer. :param ChannelTransferInfo transfer_info: Information used by an diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 259058efc..28c723130 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -9997,7 +9997,7 @@ def __ne__(self, other: 'PdfSettings') -> bool: class QueryAggregation(): """ - An aggregation produced by Discovery to analyze the input provided. + An aggregation produced by Discovery to analyze the input provided. :attr str type: The type of aggregation command used. For example: term, filter, max, min, etc. diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 12e7645a3..448e78ec8 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -535,8 +535,8 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: Get model details. Gets information about a translation model, including training status for custom - models. Use this API call to poll the status of your customization request. A - successfully completed training has a status of `available`. + models. Use this method to poll the status of your customization request. A + successfully completed training request has a status of `available`. :param str model_id: Model ID of the model to get. :param dict headers: A `dict` containing the request headers @@ -626,18 +626,40 @@ def translate_document(self, Translate document. Submit a document for translation. You can submit the document contents in the - `file` parameter, or you can reference a previously submitted document by document + `file` parameter, or you can specify a previously submitted document by document ID. The maximum file size for document translation is - * 20 MB for service instances on the Standard, Advanced, and Premium plans - * 2 MB for service instances on the Lite plan + * **2 MB** for service instances on the Lite plan + * **20 MB** for service instances on the Standard plan + * **50 MB** for service instances on the Advanced plan + * **150 MB** for service instances on the Premium plan + You can specify the format of the file to be translated in one of two ways: + * By specifying the appropriate file extension for the format. + * By specifying the content type (MIME type) of the format as the `type` of the + `file` parameter. + In some cases, especially for subtitle file formats, you must use either the file + extension or the content type. For more information about all supported file + formats, their file extensions and content types, and how and when to specify the + file extension or content type, see [Supported file + formats](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). **Note:** When translating a previously submitted document, the target language must be different from the target language of the original request when the document was initially submitted. :param BinaryIO file: The contents of the source file to translate. The - maximum file size for document translation is 20 MB for service instances - on the Standard, Advanced, and Premium plans, and 2 MB for service - instances on the Lite plan. For more information, see [Supported file + maximum file size for document translation is + * **2 MB** for service instances on the Lite plan + * **20 MB** for service instances on the Standard plan + * **50 MB** for service instances on the Advanced plan + * **150 MB** for service instances on the Premium plan + You can specify the format of the file to be translated in one of two ways: + * By specifying the appropriate file extension for the format. + * By specifying the content type (MIME type) of the format as the `type` of + the `file` parameter. + In some cases, especially for subtitle file formats, you must use either + the file extension or the content type. + For more information about all supported file formats, their file + extensions and content types, and how and when to specify the file + extension or content type, see [Supported file formats](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -885,22 +907,25 @@ class FileContentType(str, Enum): """ The content type of file. """ - APPLICATION_POWERPOINT = 'application/powerpoint' APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' - APPLICATION_X_RTF = 'application/x-rtf' - APPLICATION_JSON = 'application/json' - APPLICATION_XML = 'application/xml' + APPLICATION_MSWORD = 'application/msword' + APPLICATION_OCTET_STREAM = 'application/octet-stream' + APPLICATION_PDF = 'application/pdf' + APPLICATION_POWERPOINT = 'application/powerpoint' + APPLICATION_RTF = 'application/rtf' + APPLICATION_TTAF_XML = 'application/ttaf+xml' + APPLICATION_TTML_XML = 'application/ttml+xml' + APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' + APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' + APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' APPLICATION_VND_MS_EXCEL = 'application/vnd.ms-excel' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' APPLICATION_VND_MS_POWERPOINT = 'application/vnd.ms-powerpoint' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = 'application/vnd.openxmlformats-officedocument.presentationml.presentation' - APPLICATION_MSWORD = 'application/msword' + APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' - APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' - APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' - APPLICATION_PDF = 'application/pdf' - APPLICATION_RTF = 'application/rtf' + APPLICATION_X_RTF = 'application/x-rtf' + APPLICATION_XHTML_XML = 'application/xhtml+xml' + APPLICATION_XML = 'application/xml' TEXT_HTML = 'text/html' TEXT_JSON = 'text/json' TEXT_PLAIN = 'text/plain' @@ -908,7 +933,6 @@ class FileContentType(str, Enum): TEXT_RTF = 'text/rtf' TEXT_SBV = 'text/sbv' TEXT_SRT = 'text/srt' - TEXT_VTT = 'text/vtt' TEXT_XML = 'text/xml' diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 9870633f7..86aa0933f 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -479,7 +479,7 @@ def test_list_workspaces_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -531,7 +531,7 @@ def test_list_workspaces_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -562,7 +562,7 @@ def test_list_workspaces_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -598,7 +598,7 @@ def test_create_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -701,7 +701,7 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a WorkspaceSystemSettingsNlp model workspace_system_settings_nlp_model = {} - workspace_system_settings_nlp_model['model'] = 'baseline' + workspace_system_settings_nlp_model['model'] = 'testString' # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} @@ -826,7 +826,7 @@ def test_create_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -857,7 +857,7 @@ def test_create_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -893,7 +893,7 @@ def test_get_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -941,7 +941,7 @@ def test_get_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -977,7 +977,7 @@ def test_get_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -1017,7 +1017,7 @@ def test_update_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1120,7 +1120,7 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a WorkspaceSystemSettingsNlp model workspace_system_settings_nlp_model = {} - workspace_system_settings_nlp_model['model'] = 'baseline' + workspace_system_settings_nlp_model['model'] = 'testString' # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} @@ -1250,7 +1250,7 @@ def test_update_workspace_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1286,7 +1286,7 @@ def test_update_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1396,7 +1396,7 @@ def test_create_workspace_async_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1499,7 +1499,7 @@ def test_create_workspace_async_all_params(self): # Construct a dict representation of a WorkspaceSystemSettingsNlp model workspace_system_settings_nlp_model = {} - workspace_system_settings_nlp_model['model'] = 'baseline' + workspace_system_settings_nlp_model['model'] = 'testString' # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} @@ -1618,7 +1618,7 @@ def test_create_workspace_async_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1649,7 +1649,7 @@ def test_create_workspace_async_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1685,7 +1685,7 @@ def test_update_workspace_async_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1788,7 +1788,7 @@ def test_update_workspace_async_all_params(self): # Construct a dict representation of a WorkspaceSystemSettingsNlp model workspace_system_settings_nlp_model = {} - workspace_system_settings_nlp_model['model'] = 'baseline' + workspace_system_settings_nlp_model['model'] = 'testString' # Construct a dict representation of a WorkspaceSystemSettings model workspace_system_settings_model = {} @@ -1915,7 +1915,7 @@ def test_update_workspace_async_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1951,7 +1951,7 @@ def test_update_workspace_async_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.POST, url, body=mock_response, @@ -1991,7 +1991,7 @@ def test_export_workspace_async_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -2039,7 +2039,7 @@ def test_export_workspace_async_required_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -2075,7 +2075,7 @@ def test_export_workspace_async_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') - mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "baseline"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' + mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' responses.add(responses.GET, url, body=mock_response, @@ -11063,7 +11063,7 @@ def test_workspace_serialization(self): workspace_system_settings_off_topic_model['enabled'] = False workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp - workspace_system_settings_nlp_model['model'] = 'baseline' + workspace_system_settings_nlp_model['model'] = 'testString' workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model @@ -11234,7 +11234,7 @@ def test_workspace_collection_serialization(self): workspace_system_settings_off_topic_model['enabled'] = False workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp - workspace_system_settings_nlp_model['model'] = 'baseline' + workspace_system_settings_nlp_model['model'] = 'testString' workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model @@ -11386,7 +11386,7 @@ def test_workspace_system_settings_serialization(self): workspace_system_settings_off_topic_model['enabled'] = False workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp - workspace_system_settings_nlp_model['model'] = 'baseline' + workspace_system_settings_nlp_model['model'] = 'testString' # Construct a json representation of a WorkspaceSystemSettings model workspace_system_settings_model_json = {} @@ -11472,7 +11472,7 @@ def test_workspace_system_settings_nlp_serialization(self): # Construct a json representation of a WorkspaceSystemSettingsNlp model workspace_system_settings_nlp_model_json = {} - workspace_system_settings_nlp_model_json['model'] = 'baseline' + workspace_system_settings_nlp_model_json['model'] = 'testString' # Construct a model instance of WorkspaceSystemSettingsNlp by calling from_dict on the json representation workspace_system_settings_nlp_model = WorkspaceSystemSettingsNlp.from_dict(workspace_system_settings_nlp_model_json) diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index 2217b442e..fdb19dd00 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -901,7 +901,7 @@ def test_translate_document_all_params(self): # Set up parameter values file = io.BytesIO(b'This is a mock file.').getvalue() filename = 'testString' - file_content_type = 'application/powerpoint' + file_content_type = 'application/mspowerpoint' model_id = 'testString' source = 'testString' target = 'testString' From 14fd5f22096ac83e99a5c6092fbead23cf309f45 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 23 Feb 2023 12:11:53 -0600 Subject: [PATCH 385/455] feat(stt): add and remove models --- ibm_watson/speech_to_text_v1.py | 149 +++++++++++++++------------- test/unit/test_speech_to_text_v1.py | 18 ++-- 2 files changed, 88 insertions(+), 79 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 21c4aea23..a16b7c92e 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -17,7 +17,7 @@ # IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's -speech-recognition capabilities to produce transcripts of spoken audio. The service can +speech-recognition capabilities to produce transcripts of spoken audio. The service can transcribe speech from various languages and audio formats. In addition to basic transcription, the service can produce detailed information about many different aspects of the audio. It returns all JSON response content in the UTF-8 character set. @@ -27,9 +27,9 @@ have minimum sampling rates of 16 kHz. Narrowband and telephony models have minimum sampling rates of 8 kHz. The next-generation models offer high throughput and greater transcription accuracy. -Effective 15 March 2022, previous-generation models for all languages other than Arabic -and Japanese are deprecated. The deprecated models remain available until 15 September -2022, when they will be removed from the service and the documentation. You must migrate +Effective **15 March 2022**, previous-generation models for all languages other than +Arabic and Japanese are deprecated. The deprecated models remain available until **31 July +2023**, when they will be removed from the service and the documentation. You must migrate to the equivalent next-generation model by the end of service date. For more information, see [Migrating to next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate).{: @@ -140,9 +140,7 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list#models-list-specific). :param str model_id: The identifier of the model in the form of its name - from the output of the [List models](#listmodels) method. (**Note:** The - model `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` - instead.). + from the output of the [List models](#listmodels) method. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SpeechModel` object @@ -278,12 +276,11 @@ def recognize(self, do not support the following parameters: * `acoustic_customization_id` * `keywords` and `keywords_threshold` - * `max_alternatives` * `processing_metrics` and `processing_metrics_interval` * `word_alternatives_threshold` - **Important:** Effective 15 March 2022, previous-generation models for all + **Important:** Effective **15 March 2022**, previous-generation models for all languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the + remain available until **31 July 2023**, when they will be removed from the service and the documentation. You must migrate to the equivalent next-generation model by the end of service date. For more information, see [Migrating to next-generation @@ -314,15 +311,14 @@ def recognize(self, (content types)** in the method description. :param str model: (optional) The model to use for speech recognition. If you omit the `model` parameter, the service uses the US English - `en-US_BroadbandModel` by default. (The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) + `en-US_BroadbandModel` by default. _For IBM Cloud Pak for Data,_ if you do not install the `en-US_BroadbandModel`, you must either specify a model with the request or specify a new default model for your installation of the service. **See also:** * [Using a model for speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) - * [The default + * [Using the default model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). :param str language_customization_id: (optional) The customization ID (GUID) of a custom language model that is to be used with the recognition @@ -893,12 +889,11 @@ def create_job(self, do not support the following parameters: * `acoustic_customization_id` * `keywords` and `keywords_threshold` - * `max_alternatives` * `processing_metrics` and `processing_metrics_interval` * `word_alternatives_threshold` - **Important:** Effective 15 March 2022, previous-generation models for all + **Important:** Effective **15 March 2022**, previous-generation models for all languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the + remain available until **31 July 2023**, when they will be removed from the service and the documentation. You must migrate to the equivalent next-generation model by the end of service date. For more information, see [Migrating to next-generation @@ -915,15 +910,14 @@ def create_job(self, (content types)** in the method description. :param str model: (optional) The model to use for speech recognition. If you omit the `model` parameter, the service uses the US English - `en-US_BroadbandModel` by default. (The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) + `en-US_BroadbandModel` by default. _For IBM Cloud Pak for Data,_ if you do not install the `en-US_BroadbandModel`, you must either specify a model with the request or specify a new default model for your installation of the service. **See also:** * [Using a model for speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) - * [The default + * [Using the default model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). :param str callback_url: (optional) A URL to which callback notifications are to be sent. The URL must already be successfully allowlisted by using @@ -1443,9 +1437,9 @@ def create_language_model(self, The service returns an error if you attempt to create more than 1024 models. You do not lose any models, but you cannot create any more until your model count is below the limit. - **Important:** Effective 15 March 2022, previous-generation models for all + **Important:** Effective **15 March 2022**, previous-generation models for all languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the + remain available until **31 July 2023**, when they will be removed from the service and the documentation. You must migrate to the equivalent next-generation model by the end of service date. For more information, see [Migrating to next-generation @@ -1457,10 +1451,12 @@ def create_language_model(self, customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :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 - localized name that matches the language of the custom model. Use a name + a localized name that matches the language of the custom model. Use a name that describes the domain of the custom model, such as `Medical custom - model` or `Legal custom model`. + model` or `Legal custom model`. Use a name that is unique among all custom + language models that you own. + Include a maximum of 256 characters in the name. Do not use backslashes, + slashes, colons, equal signs, ampersands, or question marks in the name. :param str base_model_name: The name of the base language model that is to be customized by the new custom language model. The new custom model can be used only with the base model that it customizes. @@ -1485,9 +1481,10 @@ def create_language_model(self, `es-PE` models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) All values that you pass for the `dialect` field are case-insensitive. - :param str description: (optional) A description of the new custom language - model. Use a localized description that matches the language of the custom - model. + :param str description: (optional) A recommended description of the new + custom language model. Use a localized description that matches the + language of the custom model. Include a maximum of 128 characters in the + description. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `LanguageModel` object @@ -1550,8 +1547,7 @@ def list_language_models(self, five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or custom acoustic - models that are owned by the requesting credentials. (**Note:** The - identifier `ar-AR` is deprecated; use `ar-MS` instead.) + models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). @@ -1699,11 +1695,13 @@ def train_language_model(self, indicate that the training process has begun. You can monitor the status of the training by using the [Get a custom language model](#getlanguagemodel) method to poll the model's status. Use a loop to check - the status every 10 seconds. The method returns a `LanguageModel` object that - includes `status` and `progress` fields. A status of `available` means that the - custom model is trained and ready to use. The service cannot accept subsequent - training requests or requests to add new resources until the existing request - completes. + the status every 10 seconds. If you added custom words directly to a custom model + that is based on a next-generation model, allow for some minutes of extra training + time for the model. + The method returns a `LanguageModel` object that includes `status` and `progress` + fields. A status of `available` means that the custom model is trained 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/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language) @@ -2952,9 +2950,9 @@ def create_acoustic_model(self, below the limit. **Note:** Acoustic model customization is supported only for use with previous-generation models. It is not supported for next-generation models. - **Important:** Effective 15 March 2022, previous-generation models for all + **Important:** Effective **15 March 2022**, previous-generation models for all languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until 15 September 2022, when they will be removed from the + remain available until **31 July 2023**, when they will be removed from the service and the documentation. You must migrate to the equivalent next-generation model by the end of service date. For more information, see [Migrating to next-generation @@ -2963,20 +2961,22 @@ def create_acoustic_model(self, 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 - localized name that matches the language of the custom model. Use a name + a localized name that matches the language of the custom model. Use a name that describes the acoustic environment of the custom model, such as - `Mobile custom model` or `Noisy car custom model`. + `Mobile custom model` or `Noisy car custom model`. Use a name that is + unique among all custom acoustic models that you own. + Include a maximum of 256 characters in the name. Do not use backslashes, + slashes, colons, equal signs, ampersands, or question marks in the name. :param str base_model_name: The name of the base language model that is to be customized by the new custom acoustic model. The new custom model can be - used only with the base model that it customizes. (**Note:** The model - `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) + 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/speech-to-text?topic=speech-to-text-custom-support). - :param str description: (optional) A description of the new custom acoustic - model. Use a localized description that matches the language of the custom - model. + :param str description: (optional) A recommended description of the new + custom acoustic model. Use a localized description that matches the + language of the custom model. Include a maximum of 128 characters in the + description. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `AcousticModel` object @@ -3037,8 +3037,7 @@ def list_acoustic_models(self, five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or custom acoustic - models that are owned by the requesting credentials. (**Note:** The - identifier `ar-AR` is deprecated; use `ar-MS` instead.) + models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). @@ -3213,8 +3212,13 @@ def train_acoustic_model(self, Training can fail to start for the following reasons: * The service is currently handling another request for the custom model, such as another training request or a request to add audio resources to the model. - * The custom model contains less than 10 minutes or more than 200 hours of audio - data. + * The custom model contains less than 10 minutes of audio that includes speech, + not silence. + * The custom model contains more than 50 hours of audio (for IBM Cloud) or more + that 200 hours of audio (for IBM Cloud Pak for Data). **Note:** For IBM Cloud, the + maximum hours of audio for a custom acoustic model was reduced from 200 to 50 + hours in August and September 2022. For more information, see [Maximum hours of + audio](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audioResources#audioMaximum). * You passed a custom language model with the `custom_language_model_id` query parameter that is not in the available state. A custom language model must be fully trained and available to be used to train a custom acoustic model. @@ -3496,11 +3500,15 @@ def add_audio(self, You can use this method to add any number of audio resources to a custom model by calling the method once for each audio or archive file. You can add multiple different audio resources at the same time. You must add a minimum of 10 minutes - and a maximum of 200 hours of audio that includes speech, not just silence, to a - custom acoustic model before you can train it. No audio resource, audio- or - archive-type, can be larger than 100 MB. To add an audio resource that has the - same name as an existing audio resource, set the `allow_overwrite` parameter to - `true`; otherwise, the request fails. + of audio that includes speech, not just silence, to a custom acoustic model before + you can train it. No audio resource, audio- or archive-type, can be larger than + 100 MB. To add an audio resource that has the same name as an existing audio + resource, set the `allow_overwrite` parameter to `true`; otherwise, the request + fails. A custom model can contain no more than 50 hours of audio (for IBM Cloud) + or 200 hours of audio (for IBM Cloud Pak for Data). **Note:** For IBM Cloud, the + maximum hours of audio for a custom acoustic model was reduced from 200 to 50 + hours in August and September 2022. For more information, see [Maximum hours of + audio](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audioResources#audioMaximum). The method is asynchronous. It can take several seconds or minutes to complete depending on the duration of the audio and, in the case of an archive file, the total number of audio files being processed. The service returns a 201 response @@ -3844,10 +3852,8 @@ class GetModelEnums: class ModelId(str, Enum): """ The identifier of the model in the form of its name from the output of the [List - models](#listmodels) method. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.). + models](#listmodels) method. """ - AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -3886,6 +3892,7 @@ class ModelId(str, Enum): ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' @@ -3906,12 +3913,14 @@ class ModelId(str, Enum): KO_KR_TELEPHONY = 'ko-KR_Telephony' NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' + SV_SE_TELEPHONY = 'sv-SE_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' ZH_CN_TELEPHONY = 'zh-CN_Telephony' @@ -3947,18 +3956,16 @@ class ContentType(str, Enum): class Model(str, Enum): """ The model to use for speech recognition. If you omit the `model` parameter, the - service uses the US English `en-US_BroadbandModel` by default. (The model - `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) + service uses the US English `en-US_BroadbandModel` by default. _For IBM Cloud Pak for Data,_ if you do not install the `en-US_BroadbandModel`, you must either specify a model with the request or specify a new default model for your installation of the service. **See also:** * [Using a model for speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) - * [The default + * [Using the default model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ - AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -3997,6 +4004,7 @@ class Model(str, Enum): ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' @@ -4017,12 +4025,14 @@ class Model(str, Enum): KO_KR_TELEPHONY = 'ko-KR_Telephony' NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' + SV_SE_TELEPHONY = 'sv-SE_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' ZH_CN_TELEPHONY = 'zh-CN_Telephony' @@ -4058,18 +4068,16 @@ class ContentType(str, Enum): class Model(str, Enum): """ The model to use for speech recognition. If you omit the `model` parameter, the - service uses the US English `en-US_BroadbandModel` by default. (The model - `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) + service uses the US English `en-US_BroadbandModel` by default. _For IBM Cloud Pak for Data,_ if you do not install the `en-US_BroadbandModel`, you must either specify a model with the request or specify a new default model for your installation of the service. **See also:** * [Using a model for speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) - * [The default + * [Using the default model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ - AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -4108,6 +4116,7 @@ class Model(str, Enum): ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' + FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' @@ -4128,12 +4137,14 @@ class Model(str, Enum): KO_KR_TELEPHONY = 'ko-KR_Telephony' NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' + NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' + SV_SE_TELEPHONY = 'sv-SE_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' ZH_CN_TELEPHONY = 'zh-CN_Telephony' @@ -4175,13 +4186,11 @@ class Language(str, Enum): are to be returned. Specify the five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or - custom acoustic models that are owned by the requesting credentials. (**Note:** - The identifier `ar-AR` is deprecated; use `ar-MS` instead.) + custom acoustic models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ - AR_AR = 'ar-AR' AR_MS = 'ar-MS' CS_CZ = 'cs-CZ' DE_DE = 'de-DE' @@ -4206,6 +4215,7 @@ class Language(str, Enum): NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' + SV_SE = 'sv-SE' ZH_CN = 'zh-CN' @@ -4295,13 +4305,11 @@ class Language(str, Enum): are to be returned. Specify the five-character language identifier; for example, specify `en-US` to see all custom language or custom acoustic models that are based on US English models. Omit the parameter to see all custom language or - custom acoustic models that are owned by the requesting credentials. (**Note:** - The identifier `ar-AR` is deprecated; use `ar-MS` instead.) + custom acoustic models that are owned by the requesting credentials. To determine the languages for which customization is available, see [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ - AR_AR = 'ar-AR' AR_MS = 'ar-MS' CS_CZ = 'cs-CZ' DE_DE = 'de-DE' @@ -4326,6 +4334,7 @@ class Language(str, Enum): NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' + SV_SE = 'sv-SE' ZH_CN = 'zh-CN' diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 135d950c0..b2578b8f3 100644 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -116,7 +116,7 @@ def test_get_model_all_params(self): get_model() """ # Set up mock - url = preprocess_url('/v1/models/ar-AR_BroadbandModel') + url = preprocess_url('/v1/models/ar-MS_BroadbandModel') mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' responses.add(responses.GET, url, @@ -125,7 +125,7 @@ def test_get_model_all_params(self): status=200) # Set up parameter values - model_id = 'ar-AR_BroadbandModel' + model_id = 'ar-MS_BroadbandModel' # Invoke method response = _service.get_model( @@ -152,7 +152,7 @@ def test_get_model_value_error(self): test_get_model_value_error() """ # Set up mock - url = preprocess_url('/v1/models/ar-AR_BroadbandModel') + url = preprocess_url('/v1/models/ar-MS_BroadbandModel') mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' responses.add(responses.GET, url, @@ -161,7 +161,7 @@ def test_get_model_value_error(self): status=200) # Set up parameter values - model_id = 'ar-AR_BroadbandModel' + model_id = 'ar-MS_BroadbandModel' # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -1091,7 +1091,7 @@ def test_list_language_models_all_params(self): status=200) # Set up parameter values - language = 'ar-AR' + language = 'ar-MS' # Invoke method response = _service.list_language_models( @@ -2780,7 +2780,7 @@ def test_create_acoustic_model_all_params(self): # Set up parameter values name = 'testString' - base_model_name = 'ar-AR_BroadbandModel' + base_model_name = 'ar-MS_BroadbandModel' description = 'testString' # Invoke method @@ -2797,7 +2797,7 @@ def test_create_acoustic_model_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' - assert req_body['base_model_name'] == 'ar-AR_BroadbandModel' + assert req_body['base_model_name'] == 'ar-MS_BroadbandModel' assert req_body['description'] == 'testString' def test_create_acoustic_model_all_params_with_retries(self): @@ -2825,7 +2825,7 @@ def test_create_acoustic_model_value_error(self): # Set up parameter values name = 'testString' - base_model_name = 'ar-AR_BroadbandModel' + base_model_name = 'ar-MS_BroadbandModel' description = 'testString' # Pass in all but one required param and check for a ValueError @@ -2867,7 +2867,7 @@ def test_list_acoustic_models_all_params(self): status=200) # Set up parameter values - language = 'ar-AR' + language = 'ar-MS' # Invoke method response = _service.list_acoustic_models( From 546796d3db37f4af52a7745a62f24e769094b567 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 23 Feb 2023 12:28:43 -0600 Subject: [PATCH 386/455] feat(tts): add params and add model constants add params ratePercentage and pitchPercentage to synthesize function --- ibm_watson/text_to_speech_adapter_v1.py | 36 +++++- ibm_watson/text_to_speech_v1.py | 152 ++++++++++++++++-------- test/unit/test_text_to_speech_v1.py | 6 + 3 files changed, 142 insertions(+), 52 deletions(-) diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index 229daad33..6734d1ad0 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -31,6 +31,8 @@ def synthesize_using_websocket(self, timings=None, customization_id=None, spell_out_mode=None, + rate_percentage= None, + pitch_percentage= None, http_proxy_host=None, http_proxy_port=None, **kwargs): @@ -76,6 +78,36 @@ def synthesize_using_websocket(self, The parameter is available only for IBM Cloud. **See also:** [Specifying how strings are spelled out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). + :param int rate_percentage: (optional) The percentage change from the + default speaking rate of the voice that is used for speech synthesis. Each + voice has a default speaking rate that is optimized to represent a normal + rate of speech. The parameter accepts an integer that represents the + percentage change from the voice's default rate: + * Specify a signed negative integer to reduce the speaking rate by that + percentage. For example, -10 reduces the rate by ten percent. + * Specify an unsigned or signed positive integer to increase the speaking + rate by that percentage. For example, 10 and +10 increase the rate by ten + percent. + * Specify 0 or omit the parameter to get the default speaking rate for the + voice. + The parameter affects the rate for an entire request. + For more information, see [Modifying the speaking + rate](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-rate-percentage). + :param int pitch_percentage: (optional) The percentage change from the + default speaking pitch of the voice that is used for speech synthesis. Each + voice has a default speaking pitch that is optimized to represent a normal + tone of voice. The parameter accepts an integer that represents the + percentage change from the voice's default tone: + * Specify a signed negative integer to lower the voice's pitch by that + percentage. For example, -5 reduces the tone by five percent. + * Specify an unsigned or signed positive integer to increase the voice's + pitch by that percentage. For example, 5 and +5 increase the tone by five + percent. + * Specify 0 or omit the parameter to get the default speaking pitch for the + voice. + The parameter affects the pitch for an entire request. + For more information, see [Modifying the speaking + pitch](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-pitch-percentage). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. :param dict headers: A `dict` containing the request headers @@ -106,7 +138,9 @@ def synthesize_using_websocket(self, params = { 'voice': voice, 'customization_id': customization_id, - 'spell_out_mode': spell_out_mode + 'spell_out_mode': spell_out_mode, + 'rate_percentage': rate_percentage, + 'pitch_percentage': pitch_percentage } params = {k: v for k, v in params.items() if v is not None} url += '/v1/synthesize?{0}'.format(urlencode(params)) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 4b81c7ab7..d5a028079 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -18,7 +18,7 @@ """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, -dialects, and voices. The service supports at least one male or female voice, sometimes +dialects, and voices. The service supports at least one male or female voice, sometimes both, for each language. The audio is streamed back to the client with minimal delay. For speech synthesis, the service supports a synchronous HTTP Representational State Transfer (REST) interface and a WebSocket interface. Both interfaces support plain text @@ -35,11 +35,10 @@ The service also offers a Tune by Example feature that lets you define custom prompts. You can also define speaker models to improve the quality of your custom prompts. The service support custom prompts only for US English custom models and voices. -Effective 31 March 2022, all neural voices are deprecated. The deprecated voices remain -available to existing users until 31 March 2023, when they will be removed from the -service and the documentation. The neural voices are supported only for IBM Cloud; they -are not available for IBM Cloud Pak for Data. All enhanced neural voices remain available -to all users. For more information, see the [31 March 2022 service +Effective **31 March 2022**, all *neural voices* are deprecated. The deprecated voices +remain available to existing users until 31 March 2023, when they will be removed from the +service and the documentation. *No enhanced neural voices or expressive neural voices are +deprecated.* For more information, see the [31 March 2022 service update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) in the release notes for {{site.data.keyword.texttospeechshort}} for {{site.data.keyword.cloud_notm}}.{: deprecated} @@ -102,16 +101,15 @@ def list_voices(self, **kwargs) -> DetailedResponse: list of voices can change from call to call; do not rely on an alphabetized or static list of voices. To see information about a specific voice, use the [Get a voice](#getvoice). - **Note:** Effective 31 March 2022, all neural voices are deprecated. The + **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. The neural voices are - supported only for IBM Cloud; they are not available for IBM Cloud Pak for Data. - All enhanced neural voices remain available to all users. For more information, - see the [31 March 2022 service + they will be removed from the service and the documentation. *No enhanced neural + voices or expressive neural voices are deprecated.* For more information, see the + [31 March 2022 service update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) in the release notes. - **See also:** [Listing all available - voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoices). + **See also:** [Listing all + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-list#list-all-voices). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -149,13 +147,12 @@ def get_voice(self, specified voice. To list information about all available voices, use the [List voices](#listvoices) method. **See also:** [Listing a specific - voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoice). - **Note:** Effective 31 March 2022, all neural voices are deprecated. The + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-list#list-specific-voice). + **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. The neural voices are - supported only for IBM Cloud; they are not available for IBM Cloud Pak for Data. - All enhanced neural voices remain available to all users. For more information, - see the [31 March 2022 service + they will be removed from the service and the documentation. *No enhanced neural + voices or expressive neural voices are deprecated.* For more information, see the + [31 March 2022 service update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) in the release notes. @@ -210,6 +207,8 @@ def synthesize(self, voice: str = None, customization_id: str = None, spell_out_mode: str = None, + rate_percentage: int = None, + pitch_percentage: int = None, **kwargs) -> DetailedResponse: """ Synthesize audio. @@ -222,12 +221,11 @@ def synthesize(self, specify. The service returns the synthesized audio stream as an array of bytes. **See also:** [The HTTP interface](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-usingHTTP#usingHTTP). - **Note:** Effective 31 March 2022, all neural voices are deprecated. The + **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. The neural voices are - supported only for IBM Cloud; they are not available for IBM Cloud Pak for Data. - All enhanced neural voices remain available to all users. For more information, - see the [31 March 2022 service + they will be removed from the service and the documentation. *No enhanced neural + voices or expressive neural voices are deprecated.* For more information, see the + [31 March 2022 service update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) in the release notes. ### Audio formats (accept types) @@ -274,6 +272,11 @@ def synthesize(self, For more information about specifying an audio format, including additional details about some of the formats, see [Using audio formats](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-audio-formats). + **Note:** By default, the service returns audio in the Ogg audio format with the + Opus codec (`audio/ogg;codecs=opus`). However, the Ogg audio format is not + supported with the Safari browser. If you are using the service with the Safari + browser, you must use the `Accept` request header or the `accept` query parameter + specify a different format in which you want the service to return the audio. ### 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 @@ -294,10 +297,10 @@ def synthesize(self, `en-US_MichaelV3Voice`, you must either specify a voice with the request or specify a new default voice for your installation of the service. **See also:** - * [Using languages and + * [Languages and voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices) - * [The default - voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#specify-voice-default). + * [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). :param str customization_id: (optional) The customization ID (GUID) of a custom model to use for the synthesis. If a custom model is specified, it works only if it matches the language of the indicated voice. You must make @@ -316,9 +319,38 @@ def synthesize(self, pause between each pair. * `triples` - The service reads the characters three at a time, with a brief pause between each triplet. - The parameter is available only for IBM Cloud. - **See also:** [Specifying how strings are spelled + For more information, see [Specifying how strings are spelled out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). + :param int rate_percentage: (optional) The percentage change from the + default speaking rate of the voice that is used for speech synthesis. Each + voice has a default speaking rate that is optimized to represent a normal + rate of speech. The parameter accepts an integer that represents the + percentage change from the voice's default rate: + * Specify a signed negative integer to reduce the speaking rate by that + percentage. For example, -10 reduces the rate by ten percent. + * Specify an unsigned or signed positive integer to increase the speaking + rate by that percentage. For example, 10 and +10 increase the rate by ten + percent. + * Specify 0 or omit the parameter to get the default speaking rate for the + voice. + The parameter affects the rate for an entire request. + For more information, see [Modifying the speaking + rate](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-rate-percentage). + :param int pitch_percentage: (optional) The percentage change from the + default speaking pitch of the voice that is used for speech synthesis. Each + voice has a default speaking pitch that is optimized to represent a normal + tone of voice. The parameter accepts an integer that represents the + percentage change from the voice's default tone: + * Specify a signed negative integer to lower the voice's pitch by that + percentage. For example, -5 reduces the tone by five percent. + * Specify an unsigned or signed positive integer to increase the voice's + pitch by that percentage. For example, 5 and +5 increase the tone by five + percent. + * Specify 0 or omit the parameter to get the default speaking pitch for the + voice. + The parameter affects the pitch for an entire request. + For more information, see [Modifying the speaking + pitch](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-pitch-percentage). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `BinaryIO` result @@ -338,6 +370,8 @@ def synthesize(self, 'voice': voice, 'customization_id': customization_id, 'spell_out_mode': spell_out_mode, + 'rate_percentage': rate_percentage, + 'pitch_percentage': pitch_percentage, } data = { @@ -379,12 +413,11 @@ def get_pronunciation(self, pronunciation for a specific format. You can also request the pronunciation for a specific voice to see the default translation for the language of that voice or for a specific custom model to see the translation for that model. - **Note:** Effective 31 March 2022, all neural voices are deprecated. The + **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. The neural voices are - supported only for IBM Cloud; they are not available for IBM Cloud Pak for Data. - All enhanced neural voices remain available to all users. For more information, - see the [31 March 2022 service + they will be removed from the service and the documentation. *No enhanced neural + voices or expressive neural voices are deprecated.* For more information, see the + [31 March 2022 service update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) in the release notes. **See also:** [Querying a word from a @@ -398,8 +431,8 @@ def get_pronunciation(self, _For IBM Cloud Pak for Data,_ if you do not install the `en-US_MichaelV3Voice`, you must either specify a voice with the request or specify a new default voice for your installation of the service. - **See also:** [The default - voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#specify-voice-default). + **See also:** [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). :param str format: (optional) The phoneme format in which to return the pronunciation. The Arabic, Chinese, Dutch, Australian English, and Korean languages support only IPA. Omit the parameter to obtain the pronunciation @@ -465,22 +498,28 @@ def create_custom_model(self, used to create it. **See also:** [Creating a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). - **Note:** Effective 31 March 2022, all neural voices are deprecated. The + **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. The neural voices are - supported only for IBM Cloud; they are not available for IBM Cloud Pak for Data. - All enhanced neural voices remain available to all users. For more information, - see the [31 March 2022 service + they will be removed from the service and the documentation. *No enhanced neural + voices or expressive neural voices are deprecated.* For more information, see the + [31 March 2022 service update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) in the release notes. - :param str name: The name of the new custom model. + :param str name: The name of the new custom model. Use a localized name + that matches the language of the custom model. Use a name that describes + the purpose of the custom model, such as `Medical custom model` or `Legal + custom model`. Use a name that is unique among all custom models that you + own. + Include a maximum of 256 characters in the name. Do not use backslashes, + slashes, colons, equal signs, ampersands, or question marks in the name. :param str language: (optional) The language of the new custom model. You create a custom model for a specific language, not for a specific voice. A custom model can be used with any voice for its specified language. Omit the parameter to use the the default language, `en-US`. - :param str description: (optional) A description of the new custom model. - Specifying a description is recommended. + :param str description: (optional) A recommended description of the new + custom model. Use a localized description that matches the language of the + custom model. Include a maximum of 128 characters in the description. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `CustomModel` object @@ -1637,11 +1676,15 @@ class Voice(str, Enum): EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' + EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' + EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' + EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' @@ -1703,10 +1746,10 @@ class Voice(str, Enum): you must either specify a voice with the request or specify a new default voice for your installation of the service. **See also:** - * [Using languages and + * [Languages and voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices) - * [The default - voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#specify-voice-default). + * [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). """ AR_MS_OMARVOICE = 'ar-MS_OmarVoice' CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' @@ -1719,11 +1762,15 @@ class Voice(str, Enum): EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' + EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' + EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' + EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' @@ -1763,8 +1810,7 @@ class SpellOutMode(str, Enum): between each pair. * `triples` - The service reads the characters three at a time, with a brief pause between each triplet. - The parameter is available only for IBM Cloud. - **See also:** [Specifying how strings are spelled + For more information, see [Specifying how strings are spelled out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). """ DEFAULT = 'default' @@ -1787,8 +1833,8 @@ class Voice(str, Enum): _For IBM Cloud Pak for Data,_ if you do not install the `en-US_MichaelV3Voice`, you must either specify a voice with the request or specify a new default voice for your installation of the service. - **See also:** [The default - voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#specify-voice-default). + **See also:** [Using the default + voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). """ AR_MS_OMARVOICE = 'ar-MS_OmarVoice' CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' @@ -1801,11 +1847,15 @@ class Voice(str, Enum): EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' + EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' + EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' + EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' + EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 15250dfac..9d3d8c252 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -258,6 +258,8 @@ def test_synthesize_all_params(self): voice = 'en-US_MichaelV3Voice' customization_id = 'testString' spell_out_mode = 'default' + rate_percentage = 38 + pitch_percentage = 38 # Invoke method response = _service.synthesize( @@ -266,6 +268,8 @@ def test_synthesize_all_params(self): voice=voice, customization_id=customization_id, spell_out_mode=spell_out_mode, + rate_percentage=rate_percentage, + pitch_percentage=pitch_percentage, headers={} ) @@ -278,6 +282,8 @@ def test_synthesize_all_params(self): assert 'voice={}'.format(voice) in query_string assert 'customization_id={}'.format(customization_id) in query_string assert 'spell_out_mode={}'.format(spell_out_mode) in query_string + assert 'rate_percentage={}'.format(rate_percentage) in query_string + assert 'pitch_percentage={}'.format(pitch_percentage) in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['text'] == 'testString' From d6e342f7fc34fdc82cf6042f585d3110bd38abfd Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 23 Feb 2023 12:37:02 -0600 Subject: [PATCH 387/455] feat(nlu): remove all sentimentModel functions BREAKING CHANGE: remove all sentimentModel functions and models --- .../natural_language_understanding_v1.py | 546 +--------------- .../test_natural_language_understanding_v1.py | 586 ------------------ 2 files changed, 3 insertions(+), 1129 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 6d0582913..acfe964c1 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -273,291 +273,6 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: response = self.send(request, **kwargs) return response - ######################### - # Manage sentiment models - ######################### - - def create_sentiment_model(self, - language: str, - training_data: BinaryIO, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: - """ - Create sentiment model. - - (Beta) Creates a custom sentiment model by uploading training data and associated - metadata. The model begins the training and deploying process and is ready to use - when the `status` is `available`. - - :param str language: The 2-letter language code of this model. - :param BinaryIO training_data: Training data in CSV format. For more - information, see [Sentiment training data - requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-custom-sentiment#sentiment-training-data-requirements). - :param str name: (optional) An optional name for the model. - :param str description: (optional) An optional description of the model. - :param str model_version: (optional) An optional version string. - :param str workspace_id: (optional) ID of the Watson Knowledge Studio - workspace that deployed this model to Natural Language Understanding. - :param str version_description: (optional) The description of the version. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object - """ - - if not language: - raise ValueError('language must be provided') - if training_data is None: - raise ValueError('training_data must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_sentiment_model') - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - form_data = [] - form_data.append(('language', (None, language, 'text/plain'))) - form_data.append(('training_data', (None, training_data, 'text/csv'))) - if name: - form_data.append(('name', (None, name, 'text/plain'))) - if description: - form_data.append(('description', (None, description, 'text/plain'))) - if model_version: - form_data.append( - ('model_version', (None, model_version, 'text/plain'))) - if workspace_id: - form_data.append( - ('workspace_id', (None, workspace_id, 'text/plain'))) - if version_description: - form_data.append(('version_description', (None, version_description, - 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/models/sentiment' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def list_sentiment_models(self, **kwargs) -> DetailedResponse: - """ - List sentiment models. - - (Beta) Returns all custom sentiment models associated with this service instance. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListSentimentModelsResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_sentiment_models') - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/models/sentiment' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_sentiment_model(self, model_id: str, **kwargs) -> DetailedResponse: - """ - Get sentiment model details. - - (Beta) Returns the status of the sentiment model with the given model ID. - - :param str model_id: ID of the model. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object - """ - - if not model_id: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_sentiment_model') - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_sentiment_model(self, - model_id: str, - language: str, - training_data: BinaryIO, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: - """ - Update sentiment model. - - (Beta) Overwrites the training data associated with this custom sentiment model - and retrains the model. The new model replaces the current deployment. - - :param str model_id: ID of the model. - :param str language: The 2-letter language code of this model. - :param BinaryIO training_data: Training data in CSV format. For more - information, see [Sentiment training data - requirements](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-custom-sentiment#sentiment-training-data-requirements). - :param str name: (optional) An optional name for the model. - :param str description: (optional) An optional description of the model. - :param str model_version: (optional) An optional version string. - :param str workspace_id: (optional) ID of the Watson Knowledge Studio - workspace that deployed this model to Natural Language Understanding. - :param str version_description: (optional) The description of the version. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SentimentModel` object - """ - - if not model_id: - raise ValueError('model_id must be provided') - if not language: - raise ValueError('language must be provided') - if training_data is None: - raise ValueError('training_data must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_sentiment_model') - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - form_data = [] - form_data.append(('language', (None, language, 'text/plain'))) - form_data.append(('training_data', (None, training_data, 'text/csv'))) - if name: - form_data.append(('name', (None, name, 'text/plain'))) - if description: - form_data.append(('description', (None, description, 'text/plain'))) - if model_version: - form_data.append( - ('model_version', (None, model_version, 'text/plain'))) - if workspace_id: - form_data.append( - ('workspace_id', (None, workspace_id, 'text/plain'))) - if version_description: - form_data.append(('version_description', (None, version_description, - 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def delete_sentiment_model(self, model_id: str, - **kwargs) -> DetailedResponse: - """ - Delete sentiment model. - - (Beta) Un-deploys the custom sentiment model with the given model ID and deletes - all associated customer data, including any training data or binary artifacts. - - :param str model_id: ID of the model. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteModelResults` object - """ - - if not model_id: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_sentiment_model') - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/models/sentiment/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - ######################### # Manage categories models ######################### @@ -3742,6 +3457,7 @@ class Features(): :attr SummarizationOptions summarization: (optional) (Experimental) Returns a summary of content. Supported languages: English only. + Supported regions: Dallas region only. :attr CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, @@ -3814,6 +3530,7 @@ def __init__(self, :param SummarizationOptions summarization: (optional) (Experimental) Returns a summary of content. Supported languages: English only. + Supported regions: Dallas region only. :param CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, @@ -4357,68 +4074,6 @@ def __ne__(self, other: 'ListModelsResults') -> bool: return not self == other -class ListSentimentModelsResponse(): - """ - ListSentimentModelsResponse. - - :attr List[SentimentModel] models: (optional) - """ - - def __init__(self, *, models: List['SentimentModel'] = None) -> None: - """ - Initialize a ListSentimentModelsResponse object. - - :param List[SentimentModel] models: (optional) - """ - self.models = models - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListSentimentModelsResponse': - """Initialize a ListSentimentModelsResponse object from a json dictionary.""" - args = {} - if 'models' in _dict: - args['models'] = [ - SentimentModel.from_dict(v) for v in _dict.get('models') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListSentimentModelsResponse 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, 'models') and self.models is not None: - models_list = [] - for v in self.models: - if isinstance(v, dict): - models_list.append(v) - else: - models_list.append(v.to_dict()) - _dict['models'] = models_list - 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 ListSentimentModelsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListSentimentModelsResponse') -> 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: 'ListSentimentModelsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class Model(): """ Model. @@ -5576,202 +5231,6 @@ def __ne__(self, other: 'SentenceResult') -> bool: return not self == other -class SentimentModel(): - """ - SentimentModel. - - :attr List[str] features: (optional) The service features that are supported by - the custom model. - :attr str status: (optional) When the status is `available`, the model is ready - to use. - :attr str model_id: (optional) Unique model ID. - :attr datetime created: (optional) dateTime indicating when the model was - created. - :attr datetime last_trained: (optional) dateTime of last successful model - training. - :attr datetime last_deployed: (optional) dateTime of last successful model - deployment. - :attr str name: (optional) A name for the model. - :attr dict user_metadata: (optional) An optional map of metadata key-value pairs - to store with this model. - :attr str language: (optional) The 2-letter language code of this model. - :attr str description: (optional) An optional description of the model. - :attr str model_version: (optional) An optional version string. - :attr List[Notice] notices: (optional) - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace - that deployed this model to Natural Language Understanding. - :attr str version_description: (optional) The description of the version. - """ - - def __init__(self, - *, - features: List[str] = None, - status: str = None, - model_id: str = None, - created: datetime = None, - last_trained: datetime = None, - last_deployed: datetime = None, - name: str = None, - user_metadata: dict = None, - language: str = None, - description: str = None, - model_version: str = None, - notices: List['Notice'] = None, - workspace_id: str = None, - version_description: str = None) -> None: - """ - Initialize a SentimentModel object. - - :param List[str] features: (optional) The service features that are - supported by the custom model. - :param str status: (optional) When the status is `available`, the model is - ready to use. - :param str model_id: (optional) Unique model ID. - :param datetime created: (optional) dateTime indicating when the model was - created. - :param datetime last_trained: (optional) dateTime of last successful model - training. - :param datetime last_deployed: (optional) dateTime of last successful model - deployment. - :param str name: (optional) A name for the model. - :param dict user_metadata: (optional) An optional map of metadata key-value - pairs to store with this model. - :param str language: (optional) The 2-letter language code of this model. - :param str description: (optional) An optional description of the model. - :param str model_version: (optional) An optional version string. - :param List[Notice] notices: (optional) - :param str workspace_id: (optional) ID of the Watson Knowledge Studio - workspace that deployed this model to Natural Language Understanding. - :param str version_description: (optional) The description of the version. - """ - self.features = features - self.status = status - self.model_id = model_id - self.created = created - self.last_trained = last_trained - self.last_deployed = last_deployed - self.name = name - self.user_metadata = user_metadata - self.language = language - self.description = description - self.model_version = model_version - self.notices = notices - self.workspace_id = workspace_id - self.version_description = version_description - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SentimentModel': - """Initialize a SentimentModel object from a json dictionary.""" - args = {} - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'last_trained' in _dict: - args['last_trained'] = string_to_datetime(_dict.get('last_trained')) - if 'last_deployed' in _dict: - args['last_deployed'] = string_to_datetime( - _dict.get('last_deployed')) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'user_metadata' in _dict: - args['user_metadata'] = _dict.get('user_metadata') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SentimentModel 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, 'features') and self.features is not None: - _dict['features'] = self.features - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'last_trained') and self.last_trained is not None: - _dict['last_trained'] = datetime_to_string(self.last_trained) - if hasattr(self, 'last_deployed') and self.last_deployed is not None: - _dict['last_deployed'] = datetime_to_string(self.last_deployed) - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'user_metadata') and self.user_metadata is not None: - _dict['user_metadata'] = self.user_metadata - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'model_version') and self.model_version is not None: - _dict['model_version'] = self.model_version - if hasattr(self, 'notices') and self.notices is not None: - notices_list = [] - for v in self.notices: - if isinstance(v, dict): - notices_list.append(v) - else: - notices_list.append(v.to_dict()) - _dict['notices'] = notices_list - if hasattr(self, 'workspace_id') and self.workspace_id is not None: - _dict['workspace_id'] = self.workspace_id - if hasattr( - self, - 'version_description') and self.version_description is not None: - _dict['version_description'] = self.version_description - 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 SentimentModel object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SentimentModel') -> 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: 'SentimentModel') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - When the status is `available`, the model is ready to use. - """ - STARTING = 'starting' - TRAINING = 'training' - DEPLOYING = 'deploying' - AVAILABLE = 'available' - ERROR = 'error' - DELETED = 'deleted' - - class SentimentOptions(): """ Analyzes the general sentiment of your content or the sentiment toward specific target @@ -5945,6 +5404,7 @@ class SummarizationOptions(): """ (Experimental) Returns a summary of content. Supported languages: English only. + Supported regions: Dallas region only. :attr int limit: (optional) Maximum number of summary sentences to return. """ diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 65aaf89ab..053bf8c6b 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -502,497 +502,6 @@ def test_delete_model_value_error_with_retries(self): # End of Service: ManageModels ############################################################################## -############################################################################## -# Start of Service: ManageSentimentModels -############################################################################## -# region - -class TestCreateSentimentModel(): - """ - Test Class for create_sentiment_model - """ - - @responses.activate - def test_create_sentiment_model_all_params(self): - """ - create_sentiment_model() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) - - # Set up parameter values - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - name = 'testString' - description = 'testString' - model_version = 'testString' - workspace_id = 'testString' - version_description = 'testString' - - # Invoke method - response = _service.create_sentiment_model( - language, - training_data, - name=name, - description=description, - model_version=model_version, - workspace_id=workspace_id, - version_description=version_description, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - - def test_create_sentiment_model_all_params_with_retries(self): - # Enable retries and run test_create_sentiment_model_all_params. - _service.enable_retries() - self.test_create_sentiment_model_all_params() - - # Disable retries and run test_create_sentiment_model_all_params. - _service.disable_retries() - self.test_create_sentiment_model_all_params() - - @responses.activate - def test_create_sentiment_model_required_params(self): - """ - test_create_sentiment_model_required_params() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) - - # Set up parameter values - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - - # Invoke method - response = _service.create_sentiment_model( - language, - training_data, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - - def test_create_sentiment_model_required_params_with_retries(self): - # Enable retries and run test_create_sentiment_model_required_params. - _service.enable_retries() - self.test_create_sentiment_model_required_params() - - # Disable retries and run test_create_sentiment_model_required_params. - _service.disable_retries() - self.test_create_sentiment_model_required_params() - - @responses.activate - def test_create_sentiment_model_value_error(self): - """ - test_create_sentiment_model_value_error() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) - - # Set up parameter values - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "language": language, - "training_data": training_data, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_sentiment_model(**req_copy) - - def test_create_sentiment_model_value_error_with_retries(self): - # Enable retries and run test_create_sentiment_model_value_error. - _service.enable_retries() - self.test_create_sentiment_model_value_error() - - # Disable retries and run test_create_sentiment_model_value_error. - _service.disable_retries() - self.test_create_sentiment_model_value_error() - -class TestListSentimentModels(): - """ - Test Class for list_sentiment_models - """ - - @responses.activate - def test_list_sentiment_models_all_params(self): - """ - list_sentiment_models() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment') - mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Invoke method - response = _service.list_sentiment_models() - - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_sentiment_models_all_params_with_retries(self): - # Enable retries and run test_list_sentiment_models_all_params. - _service.enable_retries() - self.test_list_sentiment_models_all_params() - - # Disable retries and run test_list_sentiment_models_all_params. - _service.disable_retries() - self.test_list_sentiment_models_all_params() - - @responses.activate - def test_list_sentiment_models_value_error(self): - """ - test_list_sentiment_models_value_error() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment') - mock_response = '{"models": [{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_sentiment_models(**req_copy) - - def test_list_sentiment_models_value_error_with_retries(self): - # Enable retries and run test_list_sentiment_models_value_error. - _service.enable_retries() - self.test_list_sentiment_models_value_error() - - # Disable retries and run test_list_sentiment_models_value_error. - _service.disable_retries() - self.test_list_sentiment_models_value_error() - -class TestGetSentimentModel(): - """ - Test Class for get_sentiment_model - """ - - @responses.activate - def test_get_sentiment_model_all_params(self): - """ - get_sentiment_model() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - - # Invoke method - response = _service.get_sentiment_model( - model_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_sentiment_model_all_params_with_retries(self): - # Enable retries and run test_get_sentiment_model_all_params. - _service.enable_retries() - self.test_get_sentiment_model_all_params() - - # Disable retries and run test_get_sentiment_model_all_params. - _service.disable_retries() - self.test_get_sentiment_model_all_params() - - @responses.activate - def test_get_sentiment_model_value_error(self): - """ - test_get_sentiment_model_value_error() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "model_id": model_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_sentiment_model(**req_copy) - - def test_get_sentiment_model_value_error_with_retries(self): - # Enable retries and run test_get_sentiment_model_value_error. - _service.enable_retries() - self.test_get_sentiment_model_value_error() - - # Disable retries and run test_get_sentiment_model_value_error. - _service.disable_retries() - self.test_get_sentiment_model_value_error() - -class TestUpdateSentimentModel(): - """ - Test Class for update_sentiment_model - """ - - @responses.activate - def test_update_sentiment_model_all_params(self): - """ - update_sentiment_model() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - name = 'testString' - description = 'testString' - model_version = 'testString' - workspace_id = 'testString' - version_description = 'testString' - - # Invoke method - response = _service.update_sentiment_model( - model_id, - language, - training_data, - name=name, - description=description, - model_version=model_version, - workspace_id=workspace_id, - version_description=version_description, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_update_sentiment_model_all_params_with_retries(self): - # Enable retries and run test_update_sentiment_model_all_params. - _service.enable_retries() - self.test_update_sentiment_model_all_params() - - # Disable retries and run test_update_sentiment_model_all_params. - _service.disable_retries() - self.test_update_sentiment_model_all_params() - - @responses.activate - def test_update_sentiment_model_required_params(self): - """ - test_update_sentiment_model_required_params() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - - # Invoke method - response = _service.update_sentiment_model( - model_id, - language, - training_data, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_update_sentiment_model_required_params_with_retries(self): - # Enable retries and run test_update_sentiment_model_required_params. - _service.enable_retries() - self.test_update_sentiment_model_required_params() - - # Disable retries and run test_update_sentiment_model_required_params. - _service.disable_retries() - self.test_update_sentiment_model_required_params() - - @responses.activate - def test_update_sentiment_model_value_error(self): - """ - test_update_sentiment_model_value_error() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z", "name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "notices": [{"message": "message"}], "workspace_id": "workspace_id", "version_description": "version_description"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - language = 'testString' - training_data = io.BytesIO(b'This is a mock file.').getvalue() - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "model_id": model_id, - "language": language, - "training_data": training_data, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_sentiment_model(**req_copy) - - def test_update_sentiment_model_value_error_with_retries(self): - # Enable retries and run test_update_sentiment_model_value_error. - _service.enable_retries() - self.test_update_sentiment_model_value_error() - - # Disable retries and run test_update_sentiment_model_value_error. - _service.disable_retries() - self.test_update_sentiment_model_value_error() - -class TestDeleteSentimentModel(): - """ - Test Class for delete_sentiment_model - """ - - @responses.activate - def test_delete_sentiment_model_all_params(self): - """ - delete_sentiment_model() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - - # Invoke method - response = _service.delete_sentiment_model( - model_id, - headers={} - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_sentiment_model_all_params_with_retries(self): - # Enable retries and run test_delete_sentiment_model_all_params. - _service.enable_retries() - self.test_delete_sentiment_model_all_params() - - # Disable retries and run test_delete_sentiment_model_all_params. - _service.disable_retries() - self.test_delete_sentiment_model_all_params() - - @responses.activate - def test_delete_sentiment_model_value_error(self): - """ - test_delete_sentiment_model_value_error() - """ - # Set up mock - url = preprocess_url('/v1/models/sentiment/testString') - mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) - - # Set up parameter values - model_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "model_id": model_id, - } - for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_sentiment_model(**req_copy) - - def test_delete_sentiment_model_value_error_with_retries(self): - # Enable retries and run test_delete_sentiment_model_value_error. - _service.enable_retries() - self.test_delete_sentiment_model_value_error() - - # Disable retries and run test_delete_sentiment_model_value_error. - _service.disable_retries() - self.test_delete_sentiment_model_value_error() - -# endregion -############################################################################## -# End of Service: ManageSentimentModels -############################################################################## - ############################################################################## # Start of Service: ManageCategoriesModels ############################################################################## @@ -3405,55 +2914,6 @@ def test_list_models_results_serialization(self): list_models_results_model_json2 = list_models_results_model.to_dict() assert list_models_results_model_json2 == list_models_results_model_json -class TestModel_ListSentimentModelsResponse(): - """ - Test Class for ListSentimentModelsResponse - """ - - def test_list_sentiment_models_response_serialization(self): - """ - Test serialization/deserialization for ListSentimentModelsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - - sentiment_model_model = {} # SentimentModel - sentiment_model_model['features'] = ['testString'] - sentiment_model_model['status'] = 'starting' - sentiment_model_model['model_id'] = 'testString' - sentiment_model_model['created'] = '2019-01-01T12:00:00Z' - sentiment_model_model['last_trained'] = '2019-01-01T12:00:00Z' - sentiment_model_model['last_deployed'] = '2019-01-01T12:00:00Z' - sentiment_model_model['name'] = 'testString' - sentiment_model_model['user_metadata'] = {'key1': 'unknown type: dict'} - sentiment_model_model['language'] = 'testString' - sentiment_model_model['description'] = 'testString' - sentiment_model_model['model_version'] = 'testString' - sentiment_model_model['notices'] = [notice_model] - sentiment_model_model['workspace_id'] = 'testString' - sentiment_model_model['version_description'] = 'testString' - - # Construct a json representation of a ListSentimentModelsResponse model - list_sentiment_models_response_model_json = {} - list_sentiment_models_response_model_json['models'] = [sentiment_model_model] - - # Construct a model instance of ListSentimentModelsResponse by calling from_dict on the json representation - list_sentiment_models_response_model = ListSentimentModelsResponse.from_dict(list_sentiment_models_response_model_json) - assert list_sentiment_models_response_model != False - - # Construct a model instance of ListSentimentModelsResponse by calling from_dict on the json representation - list_sentiment_models_response_model_dict = ListSentimentModelsResponse.from_dict(list_sentiment_models_response_model_json).__dict__ - list_sentiment_models_response_model2 = ListSentimentModelsResponse(**list_sentiment_models_response_model_dict) - - # Verify the model instances are equivalent - assert list_sentiment_models_response_model == list_sentiment_models_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_sentiment_models_response_model_json2 = list_sentiment_models_response_model.to_dict() - assert list_sentiment_models_response_model_json2 == list_sentiment_models_response_model_json - class TestModel_Model(): """ Test Class for Model @@ -3979,52 +3439,6 @@ def test_sentence_result_serialization(self): sentence_result_model_json2 = sentence_result_model.to_dict() assert sentence_result_model_json2 == sentence_result_model_json -class TestModel_SentimentModel(): - """ - Test Class for SentimentModel - """ - - def test_sentiment_model_serialization(self): - """ - Test serialization/deserialization for SentimentModel - """ - - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - - # Construct a json representation of a SentimentModel model - sentiment_model_model_json = {} - sentiment_model_model_json['features'] = ['testString'] - sentiment_model_model_json['status'] = 'starting' - sentiment_model_model_json['model_id'] = 'testString' - sentiment_model_model_json['created'] = '2019-01-01T12:00:00Z' - sentiment_model_model_json['last_trained'] = '2019-01-01T12:00:00Z' - sentiment_model_model_json['last_deployed'] = '2019-01-01T12:00:00Z' - sentiment_model_model_json['name'] = 'testString' - sentiment_model_model_json['user_metadata'] = {'key1': 'unknown type: dict'} - sentiment_model_model_json['language'] = 'testString' - sentiment_model_model_json['description'] = 'testString' - sentiment_model_model_json['model_version'] = 'testString' - sentiment_model_model_json['notices'] = [notice_model] - sentiment_model_model_json['workspace_id'] = 'testString' - sentiment_model_model_json['version_description'] = 'testString' - - # Construct a model instance of SentimentModel by calling from_dict on the json representation - sentiment_model_model = SentimentModel.from_dict(sentiment_model_model_json) - assert sentiment_model_model != False - - # Construct a model instance of SentimentModel by calling from_dict on the json representation - sentiment_model_model_dict = SentimentModel.from_dict(sentiment_model_model_json).__dict__ - sentiment_model_model2 = SentimentModel(**sentiment_model_model_dict) - - # Verify the model instances are equivalent - assert sentiment_model_model == sentiment_model_model2 - - # Convert model instance back to dict and verify no loss of data - sentiment_model_model_json2 = sentiment_model_model.to_dict() - assert sentiment_model_model_json2 == sentiment_model_model_json - class TestModel_SentimentOptions(): """ Test Class for SentimentOptions From 41cb1853267528dcedfd49f42710ff28e6885d37 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 23 Feb 2023 12:51:32 -0600 Subject: [PATCH 388/455] feat(discov2): new aggregation types BREAKING CHANGE: confidence property removed BREAKING CHANGE: smartDocumentUnderstanding param removed BREAKING CHANGE: QueryAggregation structure changed --- ibm_watson/discovery_v2.py | 1401 +++++++++++++++++++++----------- test/unit/test_discovery_v2.py | 641 ++++++++++----- 2 files changed, 1364 insertions(+), 678 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 8854f1161..d6af60eb8 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -16,9 +16,9 @@ # IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 """ -IBM Watson™ Discovery is a cognitive search and content analytics engine that you -can add to applications to identify patterns, trends and actionable insights to drive -better decision-making. Securely unify structured and unstructured data with pre-enriched +IBM Watson® Discovery is a cognitive search and content analytics engine that you can +add to applications to identify patterns, trends and actionable insights to drive better +decision-making. Securely unify structured and unstructured data with pre-enriched content, and use a simplified query language to eliminate the need for manual filtering of results. @@ -680,7 +680,7 @@ def list_documents(self, document ID of each document and returns information for up to 10,000 documents. **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and later installed instances and from Plus and Enterprise plan IBM Cloud-managed - instances. + instances. It is not currently available from Premium plan instances. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -777,8 +777,8 @@ def add_document(self, Add a document to a collection with optional metadata. Returns immediately after the system has accepted the document for processing. - This operation works with a file upload collection. It cannot be used to modify a - collection that crawls an external data source. + Use this method to upload a file to the collection. You cannot use this method to + crawl an external data source. * For a list of supported file types, see the [product documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). * You must provide document content, metadata, or both. If the request is missing @@ -802,7 +802,7 @@ def add_document(self, :param str collection_id: The ID of the collection. :param BinaryIO file: (optional) When adding a document, the content of the document to ingest. For maximum supported file size limits, see [the - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). When analyzing a document, the content of the document to analyze but not ingest. Only the `application/json` content type is supported currently. For maximum supported file size limits, see [the product @@ -882,7 +882,7 @@ def get_document(self, project_id: str, collection_id: str, a file or by crawling an external data source. **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and later installed instances and from Plus and Enterprise plan IBM Cloud-managed - instances. + instances. It is not currently available from Premium plan instances. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -944,8 +944,8 @@ def update_document(self, Replace an existing document or add a document with a specified document ID. Starts ingesting a document with optional metadata. - This operation works with a file upload collection. It cannot be used to modify a - collection that crawls an external data source. + Use this method to upload a file to a collection. You cannot use this method to + crawl an external data source. If the document is uploaded to a collection that shares its data with another collection, the **X-Watson-Discovery-Force** header must be set to `true`. **Notes:** @@ -961,7 +961,7 @@ def update_document(self, :param str document_id: The ID of the document. :param BinaryIO file: (optional) When adding a document, the content of the document to ingest. For maximum supported file size limits, see [the - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). When analyzing a document, the content of the document to analyze but not ingest. Only the `application/json` content type is supported currently. For maximum supported file size limits, see [the product @@ -1045,14 +1045,17 @@ def delete_document(self, """ Delete a document. - If the given document ID is invalid, or if the document is not found, then the a - success response is returned (HTTP status code `200`) with the status set to - 'deleted'. - **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that connects to an external - source such as Microsoft SharePoint. - **Note:** Segments of an uploaded document cannot be deleted individually. Delete - all segments by deleting using the `parent_document_id` of a segment result. + Deletes the document with the document ID that you specify from the collection. + Removes uploaded documents from the collection permanently. If you delete a + document that was added by crawling an external data source, the document will be + added again with the next scheduled crawl of the data source. The delete function + removes the document from the collection, not from the external data source. + **Note:** Files such as CSV or JSON files generate subdocuments when they are + added to a collection. If you delete a subdocument, and then repeat the action + that created it, the deleted document is added back in to your collection. To + remove subdocuments that are generated by an uploaded file, delete the original + document instead. You can get the document ID of the original document from the + `parent_document_id` of the subdocument result. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -1132,12 +1135,12 @@ def query(self, Search your data by submitting queries that are written in natural language or formatted in the Discovery Query Language. For more information, see the [Discovery - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-concepts). - The default query parameters differ by project type. For more information about - the project default settings, see the [Discovery - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-defaults). - See [the Projects API documentation](#create-project) for details about how to set - custom default query settings. + documentation](/docs/discovery-data?topic=discovery-data-query-concepts). The + default query parameters differ by project type. For more information about the + project default settings, see the [Discovery + documentation](/docs/discovery-data?topic=discovery-data-query-defaults). See [the + Projects API documentation](#create-project) for details about how to set custom + default query settings. The length of the UTF-8 encoding of the POST body cannot exceed 10,000 bytes, which is roughly equivalent to 10,000 characters in English. @@ -1164,7 +1167,7 @@ def query(self, exact answer by combining query search with filters. Useful for applications to build lists, tables, and time series. For more information about the supported types of aggregations, see the [Discovery - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-query-aggregations). + documentation](/docs/discovery-data?topic=discovery-data-query-aggregations). :param int count: (optional) Number of results to return. :param List[str] return_: (optional) A list of the fields in the document hierarchy to return. You can specify both root-level (`text`) and nested @@ -1558,12 +1561,9 @@ def create_stopword_list(self, A default stop words list is used by all collections. The default list is applied both at indexing time and at query time. A custom stop words list that you add is used at query time only. - The custom stop words list replaces the default stop words list. Therefore, if you - want to keep the stop words that were used when the collection was indexed, get - the default stop words list for the language of the collection first and edit it - to create your custom list. For information about the default stop words lists per - language, see [the product - documentation](/docs/discovery-data?topic=discovery-data-stopwords). + The custom stop words list augments the default stop words list; you cannot remove + stop words. For information about the default stop words lists per language, see + [the product documentation](/docs/discovery-data?topic=discovery-data-stopwords). :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -2557,7 +2557,7 @@ def create_document_classifier(self, labels that you want to use to classify your data. If you want to specify multiple values in a single field, use a semicolon as the value separator. For a sample file, see [the product - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-cm-doc-classifier). + documentation](/docs/discovery-data?topic=discovery-data-cm-doc-classifier). :param CreateDocumentClassifier classifier: An object that manages the settings and data that is required to train a document classification model. @@ -2685,7 +2685,7 @@ def update_document_classifier(self, classification labels that you want to use to classify your data. If you want to specify multiple values in a single column, use a semicolon as the value separator. For a sample file, see [the product - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-cm-doc-classifier). + documentation](/docs/discovery-data?topic=discovery-data-cm-doc-classifier). :param BinaryIO test_data: (optional) The CSV with test data to upload. The column values in the test file must be the same as the column values in the training data file. If no test data is provided, the training data is split @@ -3147,7 +3147,7 @@ def analyze_document(self, :param str collection_id: The ID of the collection. :param BinaryIO file: (optional) When adding a document, the content of the document to ingest. For maximum supported file size limits, see [the - documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). + documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). When analyzing a document, the content of the document to analyze but not ingest. Only the `application/json` content type is supported currently. For maximum supported file size limits, see [the product @@ -3226,7 +3226,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: 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/discovery-data?topic=discovery-data-information-security#information-security). + security](/docs/discovery-data?topic=discovery-data-information-security#information-security). **Note:** This method is only supported on IBM Cloud instances of Discovery. :param str customer_id: The customer ID for which all data is to be @@ -7963,22 +7963,30 @@ def __ne__(self, class QueryAggregation(): """ - An abstract aggregation type produced by Discovery to analyze the input provided. + An object that defines how to aggregate query results. - :attr str type: The type of aggregation command used. Options include: term, - histogram, timeslice, nested, filter, min, max, sum, average, unique_count, and - top_hits. """ - def __init__(self, type: str) -> None: + def __init__(self) -> None: """ Initialize a QueryAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. """ - self.type = type + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'QueryAggregationQueryTermAggregation', + 'QueryAggregationQueryGroupByAggregation', + 'QueryAggregationQueryHistogramAggregation', + 'QueryAggregationQueryTimesliceAggregation', + 'QueryAggregationQueryNestedAggregation', + 'QueryAggregationQueryFilterAggregation', + 'QueryAggregationQueryCalculationAggregation', + 'QueryAggregationQueryTopHitsAggregation', + 'QueryAggregationQueryPairAggregation', + 'QueryAggregationQueryTrendAggregation', + 'QueryAggregationQueryTopicAggregation' + ])) + raise Exception(msg) @classmethod def from_dict(cls, _dict: Dict) -> 'QueryAggregation': @@ -7986,60 +7994,47 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregation': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryAggregation JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): + msg = ( + "Cannot convert dictionary into an instance of base class 'QueryAggregation'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'QueryAggregationQueryTermAggregation', + 'QueryAggregationQueryGroupByAggregation', + 'QueryAggregationQueryHistogramAggregation', + 'QueryAggregationQueryTimesliceAggregation', + 'QueryAggregationQueryNestedAggregation', + 'QueryAggregationQueryFilterAggregation', + 'QueryAggregationQueryCalculationAggregation', + 'QueryAggregationQueryTopHitsAggregation', + 'QueryAggregationQueryPairAggregation', + 'QueryAggregationQueryTrendAggregation', + 'QueryAggregationQueryTopicAggregation' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): """Initialize a QueryAggregation 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 QueryAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryAggregation') -> 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: 'QueryAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - @classmethod def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping = {} - mapping['term'] = 'QueryTermAggregation' - mapping['histogram'] = 'QueryHistogramAggregation' - mapping['timeslice'] = 'QueryTimesliceAggregation' - mapping['nested'] = 'QueryNestedAggregation' - mapping['filter'] = 'QueryFilterAggregation' - mapping['min'] = 'QueryCalculationAggregation' - mapping['max'] = 'QueryCalculationAggregation' - mapping['sum'] = 'QueryCalculationAggregation' - mapping['average'] = 'QueryCalculationAggregation' - mapping['unique_count'] = 'QueryCalculationAggregation' - mapping['top_hits'] = 'QueryTopHitsAggregation' - mapping['group_by'] = 'QueryGroupByAggregation' + mapping['term'] = 'QueryAggregationQueryTermAggregation' + mapping['group_by'] = 'QueryAggregationQueryGroupByAggregation' + mapping['histogram'] = 'QueryAggregationQueryHistogramAggregation' + mapping['timeslice'] = 'QueryAggregationQueryTimesliceAggregation' + mapping['nested'] = 'QueryAggregationQueryNestedAggregation' + mapping['filter'] = 'QueryAggregationQueryFilterAggregation' + mapping['min'] = 'QueryAggregationQueryCalculationAggregation' + mapping['max'] = 'QueryAggregationQueryCalculationAggregation' + mapping['sum'] = 'QueryAggregationQueryCalculationAggregation' + mapping['average'] = 'QueryAggregationQueryCalculationAggregation' + mapping['unique_count'] = 'QueryAggregationQueryCalculationAggregation' + mapping['top_hits'] = 'QueryAggregationQueryTopHitsAggregation' + mapping['pair'] = 'QueryAggregationQueryPairAggregation' + mapping['trend'] = 'QueryAggregationQueryTrendAggregation' + mapping['topic'] = 'QueryAggregationQueryTopicAggregation' disc_value = _dict.get('type') if disc_value is None: raise ValueError( @@ -8057,19 +8052,22 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: class QueryGroupByAggregationResult(): """ - Top value result for the term aggregation. + Result group for the `group_by` aggregation. - :attr str key: Value of the field with a non-zero frequency in the document set. - :attr int matching_results: Number of documents that contain the 'key'. - :attr float relevancy: (optional) The relevancy for this group. - :attr int total_matching_documents: (optional) The number of documents which - have the group as the value of specified field in the whole set of documents in - this collection. Returned only when the `relevancy` parameter is set to `true`. - :attr int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned only - when the `relevancy` parameter is set to `true`. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr str key: The condition that is met by the documents in this group. For + example, `YEARTXT<2000`. + :attr int matching_results: Number of documents that meet the query and + condition. + :attr float relevancy: (optional) The relevancy for this group. Returned only if + `relevancy:true` is specified in the request. + :attr int total_matching_documents: (optional) Number of documents that meet the + condition in the whole set of documents in this collection. Returned only when + `relevancy:true` is specified in the request. + :attr float estimated_matching_results: (optional) The number of documents that + are estimated to match the query and condition. Returned only when + `relevancy:true` is specified in the request. + :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is returned as a subaggregation. """ def __init__(self, @@ -8078,30 +8076,31 @@ def __init__(self, *, relevancy: float = None, total_matching_documents: int = None, - estimated_matching_documents: int = None, - aggregations: List['QueryAggregation'] = None) -> None: + estimated_matching_results: float = None, + aggregations: List[dict] = None) -> None: """ Initialize a QueryGroupByAggregationResult object. - :param str key: Value of the field with a non-zero frequency in the - document set. - :param int matching_results: Number of documents that contain the 'key'. - :param float relevancy: (optional) The relevancy for this group. - :param int total_matching_documents: (optional) The number of documents - which have the group as the value of specified field in the whole set of - documents in this collection. Returned only when the `relevancy` parameter - is set to `true`. - :param int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned - only when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str key: The condition that is met by the documents in this group. + For example, `YEARTXT<2000`. + :param int matching_results: Number of documents that meet the query and + condition. + :param float relevancy: (optional) The relevancy for this group. Returned + only if `relevancy:true` is specified in the request. + :param int total_matching_documents: (optional) Number of documents that + meet the condition in the whole set of documents in this collection. + Returned only when `relevancy:true` is specified in the request. + :param float estimated_matching_results: (optional) The number of documents + that are estimated to match the query and condition. Returned only when + `relevancy:true` is specified in the request. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is returned as a subaggregation. """ self.key = key self.matching_results = matching_results self.relevancy = relevancy self.total_matching_documents = total_matching_documents - self.estimated_matching_documents = estimated_matching_documents + self.estimated_matching_results = estimated_matching_results self.aggregations = aggregations @classmethod @@ -8125,13 +8124,11 @@ def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregationResult': if 'total_matching_documents' in _dict: args['total_matching_documents'] = _dict.get( 'total_matching_documents') - if 'estimated_matching_documents' in _dict: - args['estimated_matching_documents'] = _dict.get( - 'estimated_matching_documents') + if 'estimated_matching_results' in _dict: + args['estimated_matching_results'] = _dict.get( + 'estimated_matching_results') if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod @@ -8152,18 +8149,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'total_matching_documents' ) and self.total_matching_documents is not None: _dict['total_matching_documents'] = self.total_matching_documents - if hasattr(self, 'estimated_matching_documents' - ) and self.estimated_matching_documents is not None: + if hasattr(self, 'estimated_matching_results' + ) and self.estimated_matching_results is not None: _dict[ - 'estimated_matching_documents'] = self.estimated_matching_documents + 'estimated_matching_results'] = self.estimated_matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -8192,23 +8183,23 @@ class QueryHistogramAggregationResult(): :attr int key: The value of the upper bound for the numeric segment. :attr int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is returned as a subaggregation. """ def __init__(self, key: int, matching_results: int, *, - aggregations: List['QueryAggregation'] = None) -> None: + aggregations: List[dict] = None) -> None: """ Initialize a QueryHistogramAggregationResult object. :param int key: The value of the upper bound for the numeric segment. :param int matching_results: Number of documents with the specified key as the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is returned as a subaggregation. """ self.key = key self.matching_results = matching_results @@ -8231,9 +8222,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' ) if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod @@ -8250,13 +8239,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -8293,8 +8276,10 @@ class QueryLargePassages(): field in the response. :attr int max_per_document: (optional) Maximum number of passages to return per document in the result. Ignored if **passages.per_document** is `false`. - :attr List[str] fields: (optional) A list of fields to extract passages from. If - this parameter is an empty list, then all root-level fields are included. + :attr List[str] fields: (optional) A list of fields to extract passages from. By + default, passages are extracted from the `text` and `title` fields only. If you + add this parameter and specify an empty list (`[]`) as its value, then the + service searches all root-level fields for suitable passages. :attr int count: (optional) The maximum number of passages to return. Ignored if **passages.per_document** is `true`. :attr int characters: (optional) The approximate number of characters that any @@ -8346,8 +8331,10 @@ def __init__(self, return per document in the result. Ignored if **passages.per_document** is `false`. :param List[str] fields: (optional) A list of fields to extract passages - from. If this parameter is an empty list, then all root-level fields are - included. + from. By default, passages are extracted from the `text` and `title` fields + only. If you add this parameter and specify an empty list (`[]`) as its + value, then the service searches all root-level fields for suitable + passages. :param int count: (optional) The maximum number of passages to return. Ignored if **passages.per_document** is `true`. :param int characters: (optional) The approximate number of characters that @@ -8738,6 +8725,66 @@ def __ne__(self, other: 'QueryNoticesResponse') -> bool: return not self == other +class QueryPairAggregationResult(): + """ + Result for the `pair` aggregation. + + :attr List[dict] aggregations: (optional) Array of subaggregations of type + `term`, `group_by`, `histogram`, or `timeslice`. Each element of the matrix that + is returned contains a **relevancy** value that is calculated from the + combination of each value from the first and second aggregations. + """ + + def __init__(self, *, aggregations: List[dict] = None) -> None: + """ + Initialize a QueryPairAggregationResult object. + + :param List[dict] aggregations: (optional) Array of subaggregations of type + `term`, `group_by`, `histogram`, or `timeslice`. Each element of the matrix + that is returned contains a **relevancy** value that is calculated from the + combination of each value from the first and second aggregations. + """ + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryPairAggregationResult': + """Initialize a QueryPairAggregationResult object from a json dictionary.""" + args = {} + if 'aggregations' in _dict: + args['aggregations'] = _dict.get('aggregations') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryPairAggregationResult 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, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = self.aggregations + 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 QueryPairAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryPairAggregationResult') -> 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: 'QueryPairAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryResponse(): """ A response that contains the documents and aggregations for the query. @@ -8758,7 +8805,8 @@ class QueryResponse(): is deprecated. :attr List[QueryTableResult] table_results: (optional) Array of table results. :attr List[QueryResponsePassage] passages: (optional) Passages that best match - the query from across all of the collections in the project. + the query from across all of the collections in the project. Returned if + **passages.per_document** is `false`. """ def __init__(self, @@ -8792,7 +8840,8 @@ def __init__(self, :param List[QueryTableResult] table_results: (optional) Array of table results. :param List[QueryResponsePassage] passages: (optional) Passages that best - match the query from across all of the collections in the project. + match the query from across all of the collections in the project. Returned + if **passages.per_document** is `false`. """ self.matching_results = matching_results self.results = results @@ -8938,10 +8987,9 @@ class QueryResponsePassage(): extracted passage in the originating field. :attr str field: (optional) The label of the field from which the passage has been extracted. - :attr float confidence: (optional) An estimate of the probability that the - passage is relevant. :attr List[ResultPassageAnswer] answers: (optional) An array of extracted - answers to the specified query. + answers to the specified query. Returned for natural language queries when + **passages.per_document** is `false`. """ def __init__(self, @@ -8953,7 +9001,6 @@ def __init__(self, start_offset: int = None, end_offset: int = None, field: str = None, - confidence: float = None, answers: List['ResultPassageAnswer'] = None) -> None: """ Initialize a QueryResponsePassage object. @@ -8973,10 +9020,9 @@ def __init__(self, the extracted passage in the originating field. :param str field: (optional) The label of the field from which the passage has been extracted. - :param float confidence: (optional) An estimate of the probability that the - passage is relevant. :param List[ResultPassageAnswer] answers: (optional) An array of extracted - answers to the specified query. + answers to the specified query. Returned for natural language queries when + **passages.per_document** is `false`. """ self.passage_text = passage_text self.passage_score = passage_score @@ -8985,7 +9031,6 @@ def __init__(self, self.start_offset = start_offset self.end_offset = end_offset self.field = field - self.confidence = confidence self.answers = answers @classmethod @@ -9006,8 +9051,6 @@ def from_dict(cls, _dict: Dict) -> 'QueryResponsePassage': args['end_offset'] = _dict.get('end_offset') if 'field' in _dict: args['field'] = _dict.get('field') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') if 'answers' in _dict: args['answers'] = [ ResultPassageAnswer.from_dict(v) for v in _dict.get('answers') @@ -9036,8 +9079,6 @@ def to_dict(self) -> Dict: _dict['end_offset'] = self.end_offset if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence if hasattr(self, 'answers') and self.answers is not None: answers_list = [] for v in self.answers: @@ -9075,7 +9116,8 @@ class QueryResult(): :attr dict metadata: (optional) Metadata of the document. :attr QueryResultMetadata result_metadata: Metadata of a query result. :attr List[QueryResultPassage] document_passages: (optional) Passages from the - document that best matches the query. + document that best matches the query. Returned if **passages.per_document** is + `true`. """ # The set of defined properties for the class @@ -9096,7 +9138,8 @@ def __init__(self, :param QueryResultMetadata result_metadata: Metadata of a query result. :param dict metadata: (optional) Metadata of the document. :param List[QueryResultPassage] document_passages: (optional) Passages from - the document that best matches the query. + the document that best matches the query. Returned if + **passages.per_document** is `true`. :param **kwargs: (optional) Any additional properties. """ self.document_id = document_id @@ -9216,11 +9259,11 @@ class QueryResultMetadata(): :attr str collection_id: The collection id associated with this training data set. :attr float confidence: (optional) The confidence score for the given result. - Calculated based on how relevant the result is estimated to be. confidence can + Calculated based on how relevant the result is estimated to be. The score can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model specified in the `document_retrieval_strategy` field of the result set. This - field is only returned if the **natural_language_query** parameter is specified + field is returned only if the **natural_language_query** parameter is specified in the query. """ @@ -9237,11 +9280,11 @@ def __init__(self, :param str document_retrieval_source: (optional) The document retrieval source that produced this search result. :param float confidence: (optional) The confidence score for the given - result. Calculated based on how relevant the result is estimated to be. - confidence can range from `0.0` to `1.0`. The higher the number, the more + result. Calculated based on how relevant the result is estimated to be. The + score can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model specified in the `document_retrieval_strategy` field of the - result set. This field is only returned if the **natural_language_query** + result set. This field is returned only if the **natural_language_query** parameter is specified in the query. """ self.document_retrieval_source = document_retrieval_source @@ -9319,10 +9362,9 @@ class QueryResultPassage(): extracted passage in the originating field. :attr str field: (optional) The label of the field from which the passage has been extracted. - :attr float confidence: (optional) Estimate of the probability that the passage - is relevant. :attr List[ResultPassageAnswer] answers: (optional) An arry of extracted answers - to the specified query. + to the specified query. Returned for natural language queries when + **passages.per_document** is `true`. """ def __init__(self, @@ -9331,7 +9373,6 @@ def __init__(self, start_offset: int = None, end_offset: int = None, field: str = None, - confidence: float = None, answers: List['ResultPassageAnswer'] = None) -> None: """ Initialize a QueryResultPassage object. @@ -9343,16 +9384,14 @@ def __init__(self, the extracted passage in the originating field. :param str field: (optional) The label of the field from which the passage has been extracted. - :param float confidence: (optional) Estimate of the probability that the - passage is relevant. :param List[ResultPassageAnswer] answers: (optional) An arry of extracted - answers to the specified query. + answers to the specified query. Returned for natural language queries when + **passages.per_document** is `true`. """ self.passage_text = passage_text self.start_offset = start_offset self.end_offset = end_offset self.field = field - self.confidence = confidence self.answers = answers @classmethod @@ -9367,8 +9406,6 @@ def from_dict(cls, _dict: Dict) -> 'QueryResultPassage': args['end_offset'] = _dict.get('end_offset') if 'field' in _dict: args['field'] = _dict.get('field') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') if 'answers' in _dict: args['answers'] = [ ResultPassageAnswer.from_dict(v) for v in _dict.get('answers') @@ -9391,8 +9428,6 @@ def to_dict(self) -> Dict: _dict['end_offset'] = self.end_offset if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence if hasattr(self, 'answers') and self.answers is not None: answers_list = [] for v in self.answers: @@ -9589,19 +9624,21 @@ def __ne__(self, other: 'QueryTableResult') -> bool: class QueryTermAggregationResult(): """ - Top value result for the term aggregation. + Top value result for the `term` aggregation. - :attr str key: Value of the field with a non-zero frequency in the document set. + :attr str key: Value of the field with a nonzero frequency in the document set. :attr int matching_results: Number of documents that contain the 'key'. - :attr float relevancy: (optional) The relevancy for this term. - :attr int total_matching_documents: (optional) The number of documents which - have the term as the value of specified field in the whole set of documents in - this collection. Returned only when the `relevancy` parameter is set to `true`. - :attr int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned only - when the `relevancy` parameter is set to `true`. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr float relevancy: (optional) The relevancy score for this result. Returned + only if `relevancy:true` is specified in the request. + :attr int total_matching_documents: (optional) Number of documents in the + collection that contain the term in the specified field. Returned only when + `relevancy:true` is specified in the request. + :attr float estimated_matching_results: (optional) Number of documents that are + estimated to match the query and also meet the condition. Returned only when + `relevancy:true` is specified in the request. + :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is combined with other aggregations in the request or + is returned as a subaggregation. """ def __init__(self, @@ -9610,30 +9647,31 @@ def __init__(self, *, relevancy: float = None, total_matching_documents: int = None, - estimated_matching_documents: int = None, - aggregations: List['QueryAggregation'] = None) -> None: + estimated_matching_results: float = None, + aggregations: List[dict] = None) -> None: """ Initialize a QueryTermAggregationResult object. - :param str key: Value of the field with a non-zero frequency in the - document set. + :param str key: Value of the field with a nonzero frequency in the document + set. :param int matching_results: Number of documents that contain the 'key'. - :param float relevancy: (optional) The relevancy for this term. - :param int total_matching_documents: (optional) The number of documents - which have the term as the value of specified field in the whole set of - documents in this collection. Returned only when the `relevancy` parameter - is set to `true`. - :param int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned - only when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param float relevancy: (optional) The relevancy score for this result. + Returned only if `relevancy:true` is specified in the request. + :param int total_matching_documents: (optional) Number of documents in the + collection that contain the term in the specified field. Returned only when + `relevancy:true` is specified in the request. + :param float estimated_matching_results: (optional) Number of documents + that are estimated to match the query and also meet the condition. Returned + only when `relevancy:true` is specified in the request. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is combined with other aggregations in + the request or is returned as a subaggregation. """ self.key = key self.matching_results = matching_results self.relevancy = relevancy self.total_matching_documents = total_matching_documents - self.estimated_matching_documents = estimated_matching_documents + self.estimated_matching_results = estimated_matching_results self.aggregations = aggregations @classmethod @@ -9657,13 +9695,11 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': if 'total_matching_documents' in _dict: args['total_matching_documents'] = _dict.get( 'total_matching_documents') - if 'estimated_matching_documents' in _dict: - args['estimated_matching_documents'] = _dict.get( - 'estimated_matching_documents') + if 'estimated_matching_results' in _dict: + args['estimated_matching_results'] = _dict.get( + 'estimated_matching_results') if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod @@ -9684,18 +9720,12 @@ def to_dict(self) -> Dict: if hasattr(self, 'total_matching_documents' ) and self.total_matching_documents is not None: _dict['total_matching_documents'] = self.total_matching_documents - if hasattr(self, 'estimated_matching_documents' - ) and self.estimated_matching_documents is not None: + if hasattr(self, 'estimated_matching_results' + ) and self.estimated_matching_results is not None: _dict[ - 'estimated_matching_documents'] = self.estimated_matching_documents + 'estimated_matching_results'] = self.estimated_matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -9727,8 +9757,8 @@ class QueryTimesliceAggregationResult(): in UNIX milliseconds since epoch. :attr int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + only when this aggregation is returned as a subaggregation. """ def __init__(self, @@ -9736,7 +9766,7 @@ def __init__(self, key: int, matching_results: int, *, - aggregations: List['QueryAggregation'] = None) -> None: + aggregations: List[dict] = None) -> None: """ Initialize a QueryTimesliceAggregationResult object. @@ -9746,8 +9776,8 @@ def __init__(self, interval in UNIX milliseconds since epoch. :param int matching_results: Number of documents with the specified key as the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param List[dict] aggregations: (optional) An array of subaggregations. + Returned only when this aggregation is returned as a subaggregation. """ self.key_as_string = key_as_string self.key = key @@ -9777,9 +9807,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' ) if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod @@ -9798,13 +9826,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -9831,7 +9853,8 @@ class QueryTopHitsAggregationResult(): A query response that contains the matching documents for the preceding aggregations. :attr int matching_results: Number of matching results. - :attr List[dict] hits: (optional) An array of the document results. + :attr List[dict] hits: (optional) An array of the document results in an ordered + list. """ def __init__(self, @@ -9842,7 +9865,8 @@ def __init__(self, Initialize a QueryTopHitsAggregationResult object. :param int matching_results: Number of matching results. - :param List[dict] hits: (optional) An array of the document results. + :param List[dict] hits: (optional) An array of the document results in an + ordered list. """ self.matching_results = matching_results self.hits = hits @@ -9895,6 +9919,126 @@ def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: return not self == other +class QueryTopicAggregationResult(): + """ + Result for the `topic` aggregation. + + :attr List[dict] aggregations: (optional) Array of subaggregations of type + `term` or `group_by` and `timeslice`. Each element of the matrix that is + returned contains a **topic_indicator** that is calculated from the combination + of each aggregation value and segment of time. + """ + + def __init__(self, *, aggregations: List[dict] = None) -> None: + """ + Initialize a QueryTopicAggregationResult object. + + :param List[dict] aggregations: (optional) Array of subaggregations of + type `term` or `group_by` and `timeslice`. Each element of the matrix that + is returned contains a **topic_indicator** that is calculated from the + combination of each aggregation value and segment of time. + """ + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTopicAggregationResult': + """Initialize a QueryTopicAggregationResult object from a json dictionary.""" + args = {} + if 'aggregations' in _dict: + args['aggregations'] = _dict.get('aggregations') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTopicAggregationResult 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, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = self.aggregations + 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 QueryTopicAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryTopicAggregationResult') -> 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: 'QueryTopicAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTrendAggregationResult(): + """ + Result for the `trend` aggregation. + + :attr List[dict] aggregations: (optional) Array of subaggregations of type + `term` or `group_by` and `timeslice`. Each element of the matrix that is + returned contains a **trend_indicator** that is calculated from the combination + of each aggregation value and segment of time. + """ + + def __init__(self, *, aggregations: List[dict] = None) -> None: + """ + Initialize a QueryTrendAggregationResult object. + + :param List[dict] aggregations: (optional) Array of subaggregations of type + `term` or `group_by` and `timeslice`. Each element of the matrix that is + returned contains a **trend_indicator** that is calculated from the + combination of each aggregation value and segment of time. + """ + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTrendAggregationResult': + """Initialize a QueryTrendAggregationResult object from a json dictionary.""" + args = {} + if 'aggregations' in _dict: + args['aggregations'] = _dict.get('aggregations') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTrendAggregationResult 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, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = self.aggregations + 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 QueryTrendAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryTrendAggregationResult') -> 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: 'QueryTrendAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ResultPassageAnswer(): """ Object that contains a potential answer to the specified query. @@ -12072,44 +12216,47 @@ def __ne__(self, other: 'UpdateDocumentClassifier') -> bool: return not self == other -class QueryCalculationAggregation(QueryAggregation): +class QueryAggregationQueryCalculationAggregation(QueryAggregation): """ Returns a scalar calculation across all documents for the field specified. Possible calculations include min, max, sum, average, and unique_count. + :attr str type: (optional) Specifies the calculation type, such as 'average`, + `max`, `min`, `sum`, or `unique_count`. :attr str field: The field to perform the calculation on. :attr float value: (optional) The value of the calculation. """ - def __init__(self, type: str, field: str, *, value: float = None) -> None: + def __init__(self, + field: str, + *, + type: str = None, + value: float = None) -> None: """ - Initialize a QueryCalculationAggregation object. + Initialize a QueryAggregationQueryCalculationAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param str field: The field to perform the calculation on. + :param str type: (optional) Specifies the calculation type, such as + 'average`, `max`, `min`, `sum`, or `unique_count`. :param float value: (optional) The value of the calculation. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': - """Initialize a QueryCalculationAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryCalculationAggregation': + """Initialize a QueryAggregationQueryCalculationAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryCalculationAggregation JSON' - ) if 'field' in _dict: args['field'] = _dict.get('field') else: raise ValueError( - 'Required property \'field\' not present in QueryCalculationAggregation JSON' + 'Required property \'field\' not present in QueryAggregationQueryCalculationAggregation JSON' ) if 'value' in _dict: args['value'] = _dict.get('value') @@ -12117,7 +12264,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': @classmethod def _from_dict(cls, _dict): - """Initialize a QueryCalculationAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryCalculationAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -12136,85 +12283,80 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryCalculationAggregation object.""" + """Return a `str` version of this QueryAggregationQueryCalculationAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryCalculationAggregation') -> bool: + def __eq__(self, + other: 'QueryAggregationQueryCalculationAggregation') -> 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: 'QueryCalculationAggregation') -> bool: + def __ne__(self, + other: 'QueryAggregationQueryCalculationAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryFilterAggregation(QueryAggregation): +class QueryAggregationQueryFilterAggregation(QueryAggregation): """ - A modifier that narrows the document set of the sub-aggregations it precedes. + A modifier that narrows the document set of the subaggregations it precedes. + :attr str type: (optional) Specifies that the aggregation type is `filter`. :attr str match: The filter that is written in Discovery Query Language syntax - and is applied to the documents before sub-aggregations are run. + and is applied to the documents before subaggregations are run. :attr int matching_results: Number of documents that match the filter. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr List[dict] aggregations: (optional) An array of subaggregations. """ def __init__(self, - type: str, match: str, matching_results: int, *, - aggregations: List['QueryAggregation'] = None) -> None: + type: str = None, + aggregations: List[dict] = None) -> None: """ - Initialize a QueryFilterAggregation object. + Initialize a QueryAggregationQueryFilterAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param str match: The filter that is written in Discovery Query Language - syntax and is applied to the documents before sub-aggregations are run. + syntax and is applied to the documents before subaggregations are run. :param int matching_results: Number of documents that match the filter. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str type: (optional) Specifies that the aggregation type is + `filter`. + :param List[dict] aggregations: (optional) An array of subaggregations. """ + # pylint: disable=super-init-not-called self.type = type self.match = match self.matching_results = matching_results self.aggregations = aggregations @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': - """Initialize a QueryFilterAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryFilterAggregation': + """Initialize a QueryAggregationQueryFilterAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryFilterAggregation JSON' - ) if 'match' in _dict: args['match'] = _dict.get('match') else: raise ValueError( - 'Required property \'match\' not present in QueryFilterAggregation JSON' + 'Required property \'match\' not present in QueryAggregationQueryFilterAggregation JSON' ) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') else: raise ValueError( - 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' + 'Required property \'matching_results\' not present in QueryAggregationQueryFilterAggregation JSON' ) if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryFilterAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryFilterAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -12228,13 +12370,7 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list + _dict['aggregations'] = self.aggregations return _dict def _to_dict(self): @@ -12242,54 +12378,52 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryFilterAggregation object.""" + """Return a `str` version of this QueryAggregationQueryFilterAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryFilterAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryFilterAggregation') -> 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: 'QueryFilterAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryFilterAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryGroupByAggregation(QueryAggregation): +class QueryAggregationQueryGroupByAggregation(QueryAggregation): """ - Returns the top values for the field specified. + Separates document results into groups that meet the conditions you specify. - :attr List[QueryGroupByAggregationResult] results: (optional) Array of top - values for the field. + :attr str type: (optional) Specifies that the aggregation type is `group_by`. + :attr List[QueryGroupByAggregationResult] results: (optional) An array of + results. """ def __init__(self, - type: str, *, + type: str = None, results: List['QueryGroupByAggregationResult'] = None) -> None: """ - Initialize a QueryGroupByAggregation object. + Initialize a QueryAggregationQueryGroupByAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param List[QueryGroupByAggregationResult] results: (optional) Array of top - values for the field. + :param str type: (optional) Specifies that the aggregation type is + `group_by`. + :param List[QueryGroupByAggregationResult] results: (optional) An array of + results. """ + # pylint: disable=super-init-not-called self.type = type self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregation': - """Initialize a QueryGroupByAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryGroupByAggregation': + """Initialize a QueryAggregationQueryGroupByAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryGroupByAggregation JSON' - ) if 'results' in _dict: args['results'] = [ QueryGroupByAggregationResult.from_dict(v) @@ -12299,7 +12433,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregation': @classmethod def _from_dict(cls, _dict): - """Initialize a QueryGroupByAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryGroupByAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -12322,55 +12456,56 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryGroupByAggregation object.""" + """Return a `str` version of this QueryAggregationQueryGroupByAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryGroupByAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryGroupByAggregation') -> 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: 'QueryGroupByAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryGroupByAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryHistogramAggregation(QueryAggregation): +class QueryAggregationQueryHistogramAggregation(QueryAggregation): """ Numeric interval segments to categorize documents by using field values from a single numeric field to describe the category. + :attr str type: (optional) Specifies that the aggregation type is `histogram`. :attr str field: The numeric field name used to create the histogram. :attr int interval: The size of the sections that the results are split into. - :attr str name: (optional) Identifier specified in the query request of this - aggregation. + :attr str name: (optional) Identifier that can optionally be specified in the + query request of this aggregation. :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric intervals. """ def __init__( self, - type: str, field: str, interval: int, *, + type: str = None, name: str = None, results: List['QueryHistogramAggregationResult'] = None) -> None: """ - Initialize a QueryHistogramAggregation object. + Initialize a QueryAggregationQueryHistogramAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param str field: The numeric field name used to create the histogram. :param int interval: The size of the sections that the results are split into. - :param str name: (optional) Identifier specified in the query request of - this aggregation. + :param str type: (optional) Specifies that the aggregation type is + `histogram`. + :param str name: (optional) Identifier that can optionally be specified in + the query request of this aggregation. :param List[QueryHistogramAggregationResult] results: (optional) Array of numeric intervals. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.interval = interval @@ -12378,26 +12513,23 @@ def __init__( self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': - """Initialize a QueryHistogramAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryHistogramAggregation': + """Initialize a QueryAggregationQueryHistogramAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryHistogramAggregation JSON' - ) if 'field' in _dict: args['field'] = _dict.get('field') else: raise ValueError( - 'Required property \'field\' not present in QueryHistogramAggregation JSON' + 'Required property \'field\' not present in QueryAggregationQueryHistogramAggregation JSON' ) if 'interval' in _dict: args['interval'] = _dict.get('interval') else: raise ValueError( - 'Required property \'interval\' not present in QueryHistogramAggregation JSON' + 'Required property \'interval\' not present in QueryAggregationQueryHistogramAggregation JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') @@ -12410,7 +12542,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': @classmethod def _from_dict(cls, _dict): - """Initialize a QueryHistogramAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryHistogramAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -12439,87 +12571,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryHistogramAggregation object.""" + """Return a `str` version of this QueryAggregationQueryHistogramAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryHistogramAggregation') -> bool: + def __eq__(self, + other: 'QueryAggregationQueryHistogramAggregation') -> 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: 'QueryHistogramAggregation') -> bool: + def __ne__(self, + other: 'QueryAggregationQueryHistogramAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryNestedAggregation(QueryAggregation): +class QueryAggregationQueryNestedAggregation(QueryAggregation): """ - A restriction that alters the document set that is used for sub-aggregations it - precedes to nested documents found in the field specified. + A restriction that alters the document set that is used by the aggregations that it + precedes. Subsequent aggregations are applied to nested documents from the specified + field. - :attr str path: The path to the document field to scope sub-aggregations to. + :attr str type: (optional) Specifies that the aggregation type is `nested`. + :attr str path: The path to the document field to scope subsequent aggregations + to. :attr int matching_results: Number of nested documents found in the specified field. - :attr List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :attr List[dict] aggregations: (optional) An array of subaggregations. """ def __init__(self, - type: str, path: str, matching_results: int, *, - aggregations: List['QueryAggregation'] = None) -> None: + type: str = None, + aggregations: List[dict] = None) -> None: """ - Initialize a QueryNestedAggregation object. + Initialize a QueryAggregationQueryNestedAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str path: The path to the document field to scope sub-aggregations - to. + :param str path: The path to the document field to scope subsequent + aggregations to. :param int matching_results: Number of nested documents found in the specified field. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. + :param str type: (optional) Specifies that the aggregation type is + `nested`. + :param List[dict] aggregations: (optional) An array of subaggregations. """ + # pylint: disable=super-init-not-called self.type = type self.path = path self.matching_results = matching_results self.aggregations = aggregations @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': - """Initialize a QueryNestedAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryNestedAggregation': + """Initialize a QueryAggregationQueryNestedAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryNestedAggregation JSON' - ) if 'path' in _dict: args['path'] = _dict.get('path') else: raise ValueError( - 'Required property \'path\' not present in QueryNestedAggregation JSON' + 'Required property \'path\' not present in QueryAggregationQueryNestedAggregation JSON' ) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') else: raise ValueError( - 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' + 'Required property \'matching_results\' not present in QueryAggregationQueryNestedAggregation JSON' ) if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') - ] + args['aggregations'] = _dict.get('aggregations') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a QueryNestedAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryNestedAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -12533,13 +12662,134 @@ def to_dict(self) -> Dict: 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: + _dict['aggregations'] = self.aggregations + 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 QueryAggregationQueryNestedAggregation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryAggregationQueryNestedAggregation') -> 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: 'QueryAggregationQueryNestedAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryAggregationQueryPairAggregation(QueryAggregation): + """ + Calculates relevancy values using combinations of document sets from results of the + specified pair of aggregations. + + :attr str type: (optional) Specifies that the aggregation type is `pair`. + :attr str first: (optional) Specifies the first aggregation in the pair. The + aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :attr str second: (optional) Specifies the second aggregation in the pair. The + aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :attr bool show_estimated_matching_results: (optional) Indicates whether to + include estimated matching result information. + :attr bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :attr List[QueryPairAggregationResult] results: (optional) An array of + aggregations. + """ + + def __init__(self, + *, + type: str = None, + first: str = None, + second: str = None, + show_estimated_matching_results: bool = None, + show_total_matching_documents: bool = None, + results: List['QueryPairAggregationResult'] = None) -> None: + """ + Initialize a QueryAggregationQueryPairAggregation object. + + :param str type: (optional) Specifies that the aggregation type is `pair`. + :param str first: (optional) Specifies the first aggregation in the pair. + The aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :param str second: (optional) Specifies the second aggregation in the pair. + The aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` + aggregation type. + :param bool show_estimated_matching_results: (optional) Indicates whether + to include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryPairAggregationResult] results: (optional) An array of + aggregations. + """ + # pylint: disable=super-init-not-called + self.type = type + self.first = first + self.second = second + self.show_estimated_matching_results = show_estimated_matching_results + self.show_total_matching_documents = show_total_matching_documents + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryPairAggregation': + """Initialize a QueryAggregationQueryPairAggregation object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'first' in _dict: + args['first'] = _dict.get('first') + if 'second' in _dict: + args['second'] = _dict.get('second') + if 'show_estimated_matching_results' in _dict: + args['show_estimated_matching_results'] = _dict.get( + 'show_estimated_matching_results') + if 'show_total_matching_documents' in _dict: + args['show_total_matching_documents'] = _dict.get( + 'show_total_matching_documents') + if 'results' in _dict: + args['results'] = [ + QueryPairAggregationResult.from_dict(v) + for v in _dict.get('results') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregationQueryPairAggregation 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 + if hasattr(self, 'first') and self.first is not None: + _dict['first'] = self.first + if hasattr(self, 'second') and self.second is not None: + _dict['second'] = self.second + if hasattr(self, 'show_estimated_matching_results' + ) and self.show_estimated_matching_results is not None: + _dict[ + 'show_estimated_matching_results'] = self.show_estimated_matching_results + if hasattr(self, 'show_total_matching_documents' + ) and self.show_total_matching_documents is not None: + _dict[ + 'show_total_matching_documents'] = self.show_total_matching_documents + if hasattr(self, 'results') and self.results is not None: + results_list = [] + for v in self.results: if isinstance(v, dict): - aggregations_list.append(v) + results_list.append(v) else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list + results_list.append(v.to_dict()) + _dict['results'] = results_list return _dict def _to_dict(self): @@ -12547,53 +12797,56 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryNestedAggregation object.""" + """Return a `str` version of this QueryAggregationQueryPairAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryNestedAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryPairAggregation') -> 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: 'QueryNestedAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryPairAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTermAggregation(QueryAggregation): +class QueryAggregationQueryTermAggregation(QueryAggregation): """ - Returns the top values for the field specified. + Returns results from the field that is specified. - :attr str field: The field in the document used to generate top values from. - :attr int count: (optional) The number of top values returned. + :attr str type: (optional) Specifies that the aggregation type is `term`. + :attr str field: (optional) The field in the document where the values come + from. + :attr int count: (optional) The number of results returned. Not returned if + `relevancy:true` is specified in the request. :attr str name: (optional) Identifier specified in the query request of this - aggregation. - :attr List[QueryTermAggregationResult] results: (optional) Array of top values - for the field. + aggregation. Not returned if `relevancy:true` is specified in the request. + :attr List[QueryTermAggregationResult] results: (optional) An array of results. """ def __init__(self, - type: str, - field: str, *, + type: str = None, + field: str = None, count: int = None, name: str = None, results: List['QueryTermAggregationResult'] = None) -> None: """ - Initialize a QueryTermAggregation object. + Initialize a QueryAggregationQueryTermAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. - :param str field: The field in the document used to generate top values - from. - :param int count: (optional) The number of top values returned. + :param str type: (optional) Specifies that the aggregation type is `term`. + :param str field: (optional) The field in the document where the values + come from. + :param int count: (optional) The number of results returned. Not returned + if `relevancy:true` is specified in the request. :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryTermAggregationResult] results: (optional) Array of top - values for the field. + this aggregation. Not returned if `relevancy:true` is specified in the + request. + :param List[QueryTermAggregationResult] results: (optional) An array of + results. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.count = count @@ -12601,21 +12854,13 @@ def __init__(self, self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': - """Initialize a QueryTermAggregation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTermAggregation': + """Initialize a QueryAggregationQueryTermAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTermAggregation JSON' - ) if 'field' in _dict: args['field'] = _dict.get('field') - else: - raise ValueError( - 'Required property \'field\' not present in QueryTermAggregation JSON' - ) if 'count' in _dict: args['count'] = _dict.get('count') if 'name' in _dict: @@ -12629,7 +12874,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': @classmethod def _from_dict(cls, _dict): - """Initialize a QueryTermAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryTermAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -12658,55 +12903,56 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryTermAggregation object.""" + """Return a `str` version of this QueryAggregationQueryTermAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryTermAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryTermAggregation') -> 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: 'QueryTermAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryTermAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTimesliceAggregation(QueryAggregation): +class QueryAggregationQueryTimesliceAggregation(QueryAggregation): """ A specialized histogram aggregation that uses dates to create interval segments. + :attr str type: (optional) Specifies that the aggregation type is `timeslice`. :attr str field: The date field name used to create the timeslice. :attr str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. - :attr str name: (optional) Identifier specified in the query request of this - aggregation. + :attr str name: (optional) Identifier that can optionally be specified in the + query request of this aggregation. :attr List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ def __init__( self, - type: str, field: str, interval: str, *, + type: str = None, name: str = None, results: List['QueryTimesliceAggregationResult'] = None) -> None: """ - Initialize a QueryTimesliceAggregation object. + Initialize a QueryAggregationQueryTimesliceAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param str field: The date field name used to create the timeslice. :param str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. - :param str name: (optional) Identifier specified in the query request of - this aggregation. + :param str type: (optional) Specifies that the aggregation type is + `timeslice`. + :param str name: (optional) Identifier that can optionally be specified in + the query request of this aggregation. :param List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ + # pylint: disable=super-init-not-called self.type = type self.field = field self.interval = interval @@ -12714,26 +12960,23 @@ def __init__( self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryTimesliceAggregation': + """Initialize a QueryAggregationQueryTimesliceAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTimesliceAggregation JSON' - ) if 'field' in _dict: args['field'] = _dict.get('field') else: raise ValueError( - 'Required property \'field\' not present in QueryTimesliceAggregation JSON' + 'Required property \'field\' not present in QueryAggregationQueryTimesliceAggregation JSON' ) if 'interval' in _dict: args['interval'] = _dict.get('interval') else: raise ValueError( - 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' + 'Required property \'interval\' not present in QueryAggregationQueryTimesliceAggregation JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') @@ -12746,7 +12989,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': @classmethod def _from_dict(cls, _dict): - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryTimesliceAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -12775,67 +13018,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryTimesliceAggregation object.""" + """Return a `str` version of this QueryAggregationQueryTimesliceAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryTimesliceAggregation') -> bool: + def __eq__(self, + other: 'QueryAggregationQueryTimesliceAggregation') -> 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: 'QueryTimesliceAggregation') -> bool: + def __ne__(self, + other: 'QueryAggregationQueryTimesliceAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class QueryTopHitsAggregation(QueryAggregation): +class QueryAggregationQueryTopHitsAggregation(QueryAggregation): """ Returns the top documents ranked by the score of the query. + :attr str type: (optional) Specifies that the aggregation type is `top_hits`. :attr int size: The number of documents to return. :attr str name: (optional) Identifier specified in the query request of this aggregation. - :attr QueryTopHitsAggregationResult hits: (optional) + :attr QueryTopHitsAggregationResult hits: (optional) A query response that + contains the matching documents for the preceding aggregations. """ def __init__(self, - type: str, size: int, *, + type: str = None, name: str = None, hits: 'QueryTopHitsAggregationResult' = None) -> None: """ - Initialize a QueryTopHitsAggregation object. + Initialize a QueryAggregationQueryTopHitsAggregation object. - :param str type: The type of aggregation command used. Options include: - term, histogram, timeslice, nested, filter, min, max, sum, average, - unique_count, and top_hits. :param int size: The number of documents to return. + :param str type: (optional) Specifies that the aggregation type is + `top_hits`. :param str name: (optional) Identifier specified in the query request of this aggregation. - :param QueryTopHitsAggregationResult hits: (optional) + :param QueryTopHitsAggregationResult hits: (optional) A query response that + contains the matching documents for the preceding aggregations. """ + # pylint: disable=super-init-not-called self.type = type self.size = size self.name = name self.hits = hits @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'QueryAggregationQueryTopHitsAggregation': + """Initialize a QueryAggregationQueryTopHitsAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in QueryTopHitsAggregation JSON' - ) if 'size' in _dict: args['size'] = _dict.get('size') else: raise ValueError( - 'Required property \'size\' not present in QueryTopHitsAggregation JSON' + 'Required property \'size\' not present in QueryAggregationQueryTopHitsAggregation JSON' ) if 'name' in _dict: args['name'] = _dict.get('name') @@ -12846,7 +13091,7 @@ def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': @classmethod def _from_dict(cls, _dict): - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" + """Initialize a QueryAggregationQueryTopHitsAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -12870,15 +13115,263 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this QueryTopHitsAggregation object.""" + """Return a `str` version of this QueryAggregationQueryTopHitsAggregation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryAggregationQueryTopHitsAggregation') -> 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: 'QueryAggregationQueryTopHitsAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryAggregationQueryTopicAggregation(QueryAggregation): + """ + Detects how much the frequency of a given facet value deviates from the expected + average for the given time period. This aggregation type does not use data from + previous time periods. It calculates an index by using the averages of frequency + counts of other facet values for the given time period. + + :attr str type: (optional) Specifies that the aggregation type is `topic`. + :attr str facet: (optional) Specifies the `term` or `group_by` aggregation for + the facet that you want to analyze. + :attr str time_segments: (optional) Specifies the `timeslice` aggregation that + defines the time segments. + :attr bool show_estimated_matching_results: (optional) Indicates whether to + include estimated matching result information. + :attr bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :attr List[QueryTopicAggregationResult] results: (optional) An array of + aggregations. + """ + + def __init__(self, + *, + type: str = None, + facet: str = None, + time_segments: str = None, + show_estimated_matching_results: bool = None, + show_total_matching_documents: bool = None, + results: List['QueryTopicAggregationResult'] = None) -> None: + """ + Initialize a QueryAggregationQueryTopicAggregation object. + + :param str type: (optional) Specifies that the aggregation type is `topic`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation + for the facet that you want to analyze. + :param str time_segments: (optional) Specifies the `timeslice` aggregation + that defines the time segments. + :param bool show_estimated_matching_results: (optional) Indicates whether + to include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryTopicAggregationResult] results: (optional) An array of + aggregations. + """ + # pylint: disable=super-init-not-called + self.type = type + self.facet = facet + self.time_segments = time_segments + self.show_estimated_matching_results = show_estimated_matching_results + self.show_total_matching_documents = show_total_matching_documents + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTopicAggregation': + """Initialize a QueryAggregationQueryTopicAggregation object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'facet' in _dict: + args['facet'] = _dict.get('facet') + if 'time_segments' in _dict: + args['time_segments'] = _dict.get('time_segments') + if 'show_estimated_matching_results' in _dict: + args['show_estimated_matching_results'] = _dict.get( + 'show_estimated_matching_results') + if 'show_total_matching_documents' in _dict: + args['show_total_matching_documents'] = _dict.get( + 'show_total_matching_documents') + if 'results' in _dict: + args['results'] = [ + QueryTopicAggregationResult.from_dict(v) + for v in _dict.get('results') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregationQueryTopicAggregation 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 + if hasattr(self, 'facet') and self.facet is not None: + _dict['facet'] = self.facet + if hasattr(self, 'time_segments') and self.time_segments is not None: + _dict['time_segments'] = self.time_segments + if hasattr(self, 'show_estimated_matching_results' + ) and self.show_estimated_matching_results is not None: + _dict[ + 'show_estimated_matching_results'] = self.show_estimated_matching_results + if hasattr(self, 'show_total_matching_documents' + ) and self.show_total_matching_documents is not None: + _dict[ + 'show_total_matching_documents'] = self.show_total_matching_documents + if hasattr(self, 'results') and self.results is not None: + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list + 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 QueryAggregationQueryTopicAggregation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryAggregationQueryTopicAggregation') -> 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: 'QueryAggregationQueryTopicAggregation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryAggregationQueryTrendAggregation(QueryAggregation): + """ + Detects sharp and unexpected changes in the frequency of a facet or facet value over + time based on the past history of frequency changes of the facet value. + + :attr str type: (optional) Specifies that the aggregation type is `trend`. + :attr str facet: (optional) Specifies the `term` or `group_by` aggregation for + the facet that you want to analyze. + :attr str time_segments: (optional) Specifies the `timeslice` aggregation that + defines the time segments. + :attr bool show_estimated_matching_results: (optional) Indicates whether to + include estimated matching result information. + :attr bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :attr List[QueryTrendAggregationResult] results: (optional) An array of + aggregations. + """ + + def __init__(self, + *, + type: str = None, + facet: str = None, + time_segments: str = None, + show_estimated_matching_results: bool = None, + show_total_matching_documents: bool = None, + results: List['QueryTrendAggregationResult'] = None) -> None: + """ + Initialize a QueryAggregationQueryTrendAggregation object. + + :param str type: (optional) Specifies that the aggregation type is `trend`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation + for the facet that you want to analyze. + :param str time_segments: (optional) Specifies the `timeslice` aggregation + that defines the time segments. + :param bool show_estimated_matching_results: (optional) Indicates whether + to include estimated matching result information. + :param bool show_total_matching_documents: (optional) Indicates whether to + include total matching documents information. + :param List[QueryTrendAggregationResult] results: (optional) An array of + aggregations. + """ + # pylint: disable=super-init-not-called + self.type = type + self.facet = facet + self.time_segments = time_segments + self.show_estimated_matching_results = show_estimated_matching_results + self.show_total_matching_documents = show_total_matching_documents + self.results = results + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTrendAggregation': + """Initialize a QueryAggregationQueryTrendAggregation object from a json dictionary.""" + args = {} + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'facet' in _dict: + args['facet'] = _dict.get('facet') + if 'time_segments' in _dict: + args['time_segments'] = _dict.get('time_segments') + if 'show_estimated_matching_results' in _dict: + args['show_estimated_matching_results'] = _dict.get( + 'show_estimated_matching_results') + if 'show_total_matching_documents' in _dict: + args['show_total_matching_documents'] = _dict.get( + 'show_total_matching_documents') + if 'results' in _dict: + args['results'] = [ + QueryTrendAggregationResult.from_dict(v) + for v in _dict.get('results') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryAggregationQueryTrendAggregation 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 + if hasattr(self, 'facet') and self.facet is not None: + _dict['facet'] = self.facet + if hasattr(self, 'time_segments') and self.time_segments is not None: + _dict['time_segments'] = self.time_segments + if hasattr(self, 'show_estimated_matching_results' + ) and self.show_estimated_matching_results is not None: + _dict[ + 'show_estimated_matching_results'] = self.show_estimated_matching_results + if hasattr(self, 'show_total_matching_documents' + ) and self.show_total_matching_documents is not None: + _dict[ + 'show_total_matching_documents'] = self.show_total_matching_documents + if hasattr(self, 'results') and self.results is not None: + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list + 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 QueryAggregationQueryTrendAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'QueryTopHitsAggregation') -> bool: + def __eq__(self, other: 'QueryAggregationQueryTrendAggregation') -> 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: 'QueryTopHitsAggregation') -> bool: + def __ne__(self, other: 'QueryAggregationQueryTrendAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index c2e80d2b0..08c84b145 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1767,7 +1767,7 @@ def test_query_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -1877,7 +1877,7 @@ def test_query_required_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -1913,7 +1913,7 @@ def test_query_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 10}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "confidence": 0, "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add(responses.POST, url, body=mock_response, @@ -7008,35 +7008,6 @@ def test_project_list_details_relevancy_training_status_serialization(self): project_list_details_relevancy_training_status_model_json2 = project_list_details_relevancy_training_status_model.to_dict() assert project_list_details_relevancy_training_status_model_json2 == project_list_details_relevancy_training_status_model_json -class TestModel_QueryAggregation(): - """ - Test Class for QueryAggregation - """ - - def test_query_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryAggregation - """ - - # Construct a json representation of a QueryAggregation model - query_aggregation_model_json = {} - query_aggregation_model_json['type'] = 'testString' - - # Construct a model instance of QueryAggregation by calling from_dict on the json representation - query_aggregation_model = QueryAggregation.from_dict(query_aggregation_model_json) - assert query_aggregation_model != False - - # Construct a copy of the model instance by calling from_dict on the output of to_dict - query_aggregation_model_json2 = query_aggregation_model.to_dict() - query_aggregation_model2 = QueryAggregation.from_dict(query_aggregation_model_json2) - - # Verify the model instances are equivalent - assert query_aggregation_model == query_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_aggregation_model_json2 = query_aggregation_model.to_dict() - assert query_aggregation_model_json2 == query_aggregation_model_json - class TestModel_QueryGroupByAggregationResult(): """ Test Class for QueryGroupByAggregationResult @@ -7047,21 +7018,14 @@ def test_query_group_by_aggregation_result_serialization(self): Test serialization/deserialization for QueryGroupByAggregationResult """ - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - # Construct a json representation of a QueryGroupByAggregationResult model query_group_by_aggregation_result_model_json = {} query_group_by_aggregation_result_model_json['key'] = 'testString' query_group_by_aggregation_result_model_json['matching_results'] = 38 query_group_by_aggregation_result_model_json['relevancy'] = 72.5 query_group_by_aggregation_result_model_json['total_matching_documents'] = 38 - query_group_by_aggregation_result_model_json['estimated_matching_documents'] = 38 - query_group_by_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + query_group_by_aggregation_result_model_json['estimated_matching_results'] = 72.5 + query_group_by_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] # Construct a model instance of QueryGroupByAggregationResult by calling from_dict on the json representation query_group_by_aggregation_result_model = QueryGroupByAggregationResult.from_dict(query_group_by_aggregation_result_model_json) @@ -7088,18 +7052,11 @@ def test_query_histogram_aggregation_result_serialization(self): Test serialization/deserialization for QueryHistogramAggregationResult """ - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - # Construct a json representation of a QueryHistogramAggregationResult model query_histogram_aggregation_result_model_json = {} query_histogram_aggregation_result_model_json['key'] = 26 query_histogram_aggregation_result_model_json['matching_results'] = 38 - query_histogram_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + query_histogram_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation query_histogram_aggregation_result_model = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json) @@ -7277,6 +7234,35 @@ def test_query_notices_response_serialization(self): query_notices_response_model_json2 = query_notices_response_model.to_dict() assert query_notices_response_model_json2 == query_notices_response_model_json +class TestModel_QueryPairAggregationResult(): + """ + Test Class for QueryPairAggregationResult + """ + + def test_query_pair_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryPairAggregationResult + """ + + # Construct a json representation of a QueryPairAggregationResult model + query_pair_aggregation_result_model_json = {} + query_pair_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + + # Construct a model instance of QueryPairAggregationResult by calling from_dict on the json representation + query_pair_aggregation_result_model = QueryPairAggregationResult.from_dict(query_pair_aggregation_result_model_json) + assert query_pair_aggregation_result_model != False + + # Construct a model instance of QueryPairAggregationResult by calling from_dict on the json representation + query_pair_aggregation_result_model_dict = QueryPairAggregationResult.from_dict(query_pair_aggregation_result_model_json).__dict__ + query_pair_aggregation_result_model2 = QueryPairAggregationResult(**query_pair_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_pair_aggregation_result_model == query_pair_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_pair_aggregation_result_model_json2 = query_pair_aggregation_result_model.to_dict() + assert query_pair_aggregation_result_model_json2 == query_pair_aggregation_result_model_json + class TestModel_QueryResponse(): """ Test Class for QueryResponse @@ -7292,7 +7278,7 @@ def test_query_response_serialization(self): query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['document_retrieval_source'] = 'search' query_result_metadata_model['collection_id'] = 'testString' - query_result_metadata_model['confidence'] = 72.5 + query_result_metadata_model['confidence'] = 0 result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' @@ -7305,7 +7291,6 @@ def test_query_response_serialization(self): query_result_passage_model['start_offset'] = 38 query_result_passage_model['end_offset'] = 38 query_result_passage_model['field'] = 'testString' - query_result_passage_model['confidence'] = 0 query_result_passage_model['answers'] = [result_passage_answer_model] query_result_model = {} # QueryResult @@ -7315,10 +7300,20 @@ def test_query_response_serialization(self): query_result_model['document_passages'] = [query_result_passage_model] query_result_model['id'] = 'watson-generated ID' - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 + query_term_aggregation_result_model = {} # QueryTermAggregationResult + query_term_aggregation_result_model['key'] = 'active' + query_term_aggregation_result_model['matching_results'] = 34 + query_term_aggregation_result_model['relevancy'] = 72.5 + query_term_aggregation_result_model['total_matching_documents'] = 38 + query_term_aggregation_result_model['estimated_matching_results'] = 72.5 + query_term_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + query_aggregation_model = {} # QueryAggregationQueryTermAggregation + query_aggregation_model['type'] = 'term' + query_aggregation_model['field'] = 'field' + query_aggregation_model['count'] = 1 + query_aggregation_model['name'] = 'testString' + query_aggregation_model['results'] = [query_term_aggregation_result_model] retrieval_details_model = {} # RetrievalDetails retrieval_details_model['document_retrieval_strategy'] = 'untrained' @@ -7444,7 +7439,6 @@ def test_query_response_serialization(self): query_response_passage_model['start_offset'] = 38 query_response_passage_model['end_offset'] = 38 query_response_passage_model['field'] = 'testString' - query_response_passage_model['confidence'] = 0 query_response_passage_model['answers'] = [result_passage_answer_model] # Construct a json representation of a QueryResponse model @@ -7500,7 +7494,6 @@ def test_query_response_passage_serialization(self): query_response_passage_model_json['start_offset'] = 38 query_response_passage_model_json['end_offset'] = 38 query_response_passage_model_json['field'] = 'testString' - query_response_passage_model_json['confidence'] = 0 query_response_passage_model_json['answers'] = [result_passage_answer_model] # Construct a model instance of QueryResponsePassage by calling from_dict on the json representation @@ -7533,7 +7526,7 @@ def test_query_result_serialization(self): query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['document_retrieval_source'] = 'search' query_result_metadata_model['collection_id'] = 'testString' - query_result_metadata_model['confidence'] = 72.5 + query_result_metadata_model['confidence'] = 0 result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' @@ -7546,7 +7539,6 @@ def test_query_result_serialization(self): query_result_passage_model['start_offset'] = 38 query_result_passage_model['end_offset'] = 38 query_result_passage_model['field'] = 'testString' - query_result_passage_model['confidence'] = 0 query_result_passage_model['answers'] = [result_passage_answer_model] # Construct a json representation of a QueryResult model @@ -7596,7 +7588,7 @@ def test_query_result_metadata_serialization(self): query_result_metadata_model_json = {} query_result_metadata_model_json['document_retrieval_source'] = 'search' query_result_metadata_model_json['collection_id'] = 'testString' - query_result_metadata_model_json['confidence'] = 72.5 + query_result_metadata_model_json['confidence'] = 0 # Construct a model instance of QueryResultMetadata by calling from_dict on the json representation query_result_metadata_model = QueryResultMetadata.from_dict(query_result_metadata_model_json) @@ -7637,7 +7629,6 @@ def test_query_result_passage_serialization(self): query_result_passage_model_json['start_offset'] = 38 query_result_passage_model_json['end_offset'] = 38 query_result_passage_model_json['field'] = 'testString' - query_result_passage_model_json['confidence'] = 0 query_result_passage_model_json['answers'] = [result_passage_answer_model] # Construct a model instance of QueryResultPassage by calling from_dict on the json representation @@ -7832,21 +7823,14 @@ def test_query_term_aggregation_result_serialization(self): Test serialization/deserialization for QueryTermAggregationResult """ - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - # Construct a json representation of a QueryTermAggregationResult model query_term_aggregation_result_model_json = {} query_term_aggregation_result_model_json['key'] = 'testString' query_term_aggregation_result_model_json['matching_results'] = 38 query_term_aggregation_result_model_json['relevancy'] = 72.5 query_term_aggregation_result_model_json['total_matching_documents'] = 38 - query_term_aggregation_result_model_json['estimated_matching_documents'] = 38 - query_term_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + query_term_aggregation_result_model_json['estimated_matching_results'] = 72.5 + query_term_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation query_term_aggregation_result_model = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json) @@ -7873,19 +7857,12 @@ def test_query_timeslice_aggregation_result_serialization(self): Test serialization/deserialization for QueryTimesliceAggregationResult """ - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - # Construct a json representation of a QueryTimesliceAggregationResult model query_timeslice_aggregation_result_model_json = {} query_timeslice_aggregation_result_model_json['key_as_string'] = 'testString' query_timeslice_aggregation_result_model_json['key'] = 26 query_timeslice_aggregation_result_model_json['matching_results'] = 26 - query_timeslice_aggregation_result_model_json['aggregations'] = [query_aggregation_model] + query_timeslice_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation query_timeslice_aggregation_result_model = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json) @@ -7932,6 +7909,64 @@ def test_query_top_hits_aggregation_result_serialization(self): query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json +class TestModel_QueryTopicAggregationResult(): + """ + Test Class for QueryTopicAggregationResult + """ + + def test_query_topic_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryTopicAggregationResult + """ + + # Construct a json representation of a QueryTopicAggregationResult model + query_topic_aggregation_result_model_json = {} + query_topic_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + + # Construct a model instance of QueryTopicAggregationResult by calling from_dict on the json representation + query_topic_aggregation_result_model = QueryTopicAggregationResult.from_dict(query_topic_aggregation_result_model_json) + assert query_topic_aggregation_result_model != False + + # Construct a model instance of QueryTopicAggregationResult by calling from_dict on the json representation + query_topic_aggregation_result_model_dict = QueryTopicAggregationResult.from_dict(query_topic_aggregation_result_model_json).__dict__ + query_topic_aggregation_result_model2 = QueryTopicAggregationResult(**query_topic_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_topic_aggregation_result_model == query_topic_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_topic_aggregation_result_model_json2 = query_topic_aggregation_result_model.to_dict() + assert query_topic_aggregation_result_model_json2 == query_topic_aggregation_result_model_json + +class TestModel_QueryTrendAggregationResult(): + """ + Test Class for QueryTrendAggregationResult + """ + + def test_query_trend_aggregation_result_serialization(self): + """ + Test serialization/deserialization for QueryTrendAggregationResult + """ + + # Construct a json representation of a QueryTrendAggregationResult model + query_trend_aggregation_result_model_json = {} + query_trend_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + + # Construct a model instance of QueryTrendAggregationResult by calling from_dict on the json representation + query_trend_aggregation_result_model = QueryTrendAggregationResult.from_dict(query_trend_aggregation_result_model_json) + assert query_trend_aggregation_result_model != False + + # Construct a model instance of QueryTrendAggregationResult by calling from_dict on the json representation + query_trend_aggregation_result_model_dict = QueryTrendAggregationResult.from_dict(query_trend_aggregation_result_model_json).__dict__ + query_trend_aggregation_result_model2 = QueryTrendAggregationResult(**query_trend_aggregation_result_model_dict) + + # Verify the model instances are equivalent + assert query_trend_aggregation_result_model == query_trend_aggregation_result_model2 + + # Convert model instance back to dict and verify no loss of data + query_trend_aggregation_result_model_json2 = query_trend_aggregation_result_model.to_dict() + assert query_trend_aggregation_result_model_json2 == query_trend_aggregation_result_model_json + class TestModel_ResultPassageAnswer(): """ Test Class for ResultPassageAnswer @@ -8836,232 +8871,312 @@ def test_update_document_classifier_serialization(self): update_document_classifier_model_json2 = update_document_classifier_model.to_dict() assert update_document_classifier_model_json2 == update_document_classifier_model_json -class TestModel_QueryCalculationAggregation(): +class TestModel_QueryAggregationQueryCalculationAggregation(): """ - Test Class for QueryCalculationAggregation + Test Class for QueryAggregationQueryCalculationAggregation """ - def test_query_calculation_aggregation_serialization(self): + def test_query_aggregation_query_calculation_aggregation_serialization(self): """ - Test serialization/deserialization for QueryCalculationAggregation + Test serialization/deserialization for QueryAggregationQueryCalculationAggregation """ - # Construct a json representation of a QueryCalculationAggregation model - query_calculation_aggregation_model_json = {} - query_calculation_aggregation_model_json['type'] = 'unique_count' - query_calculation_aggregation_model_json['field'] = 'testString' - query_calculation_aggregation_model_json['value'] = 72.5 + # Construct a json representation of a QueryAggregationQueryCalculationAggregation model + query_aggregation_query_calculation_aggregation_model_json = {} + query_aggregation_query_calculation_aggregation_model_json['type'] = 'unique_count' + query_aggregation_query_calculation_aggregation_model_json['field'] = 'testString' + query_aggregation_query_calculation_aggregation_model_json['value'] = 72.5 - # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation - query_calculation_aggregation_model = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json) - assert query_calculation_aggregation_model != False + # Construct a model instance of QueryAggregationQueryCalculationAggregation by calling from_dict on the json representation + query_aggregation_query_calculation_aggregation_model = QueryAggregationQueryCalculationAggregation.from_dict(query_aggregation_query_calculation_aggregation_model_json) + assert query_aggregation_query_calculation_aggregation_model != False - # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation - query_calculation_aggregation_model_dict = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json).__dict__ - query_calculation_aggregation_model2 = QueryCalculationAggregation(**query_calculation_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryCalculationAggregation by calling from_dict on the json representation + query_aggregation_query_calculation_aggregation_model_dict = QueryAggregationQueryCalculationAggregation.from_dict(query_aggregation_query_calculation_aggregation_model_json).__dict__ + query_aggregation_query_calculation_aggregation_model2 = QueryAggregationQueryCalculationAggregation(**query_aggregation_query_calculation_aggregation_model_dict) # Verify the model instances are equivalent - assert query_calculation_aggregation_model == query_calculation_aggregation_model2 + assert query_aggregation_query_calculation_aggregation_model == query_aggregation_query_calculation_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_calculation_aggregation_model_json2 = query_calculation_aggregation_model.to_dict() - assert query_calculation_aggregation_model_json2 == query_calculation_aggregation_model_json + query_aggregation_query_calculation_aggregation_model_json2 = query_aggregation_query_calculation_aggregation_model.to_dict() + assert query_aggregation_query_calculation_aggregation_model_json2 == query_aggregation_query_calculation_aggregation_model_json -class TestModel_QueryFilterAggregation(): +class TestModel_QueryAggregationQueryFilterAggregation(): """ - Test Class for QueryFilterAggregation + Test Class for QueryAggregationQueryFilterAggregation """ - def test_query_filter_aggregation_serialization(self): + def test_query_aggregation_query_filter_aggregation_serialization(self): """ - Test serialization/deserialization for QueryFilterAggregation + Test serialization/deserialization for QueryAggregationQueryFilterAggregation """ - # Construct a json representation of a QueryFilterAggregation model - query_filter_aggregation_model_json = {} - query_filter_aggregation_model_json['type'] = 'filter' - query_filter_aggregation_model_json['match'] = 'testString' - query_filter_aggregation_model_json['matching_results'] = 26 + # Construct a json representation of a QueryAggregationQueryFilterAggregation model + query_aggregation_query_filter_aggregation_model_json = {} + query_aggregation_query_filter_aggregation_model_json['type'] = 'filter' + query_aggregation_query_filter_aggregation_model_json['match'] = 'testString' + query_aggregation_query_filter_aggregation_model_json['matching_results'] = 26 + query_aggregation_query_filter_aggregation_model_json['aggregations'] = [{'foo': 'bar'}] - # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation - query_filter_aggregation_model = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json) - assert query_filter_aggregation_model != False + # Construct a model instance of QueryAggregationQueryFilterAggregation by calling from_dict on the json representation + query_aggregation_query_filter_aggregation_model = QueryAggregationQueryFilterAggregation.from_dict(query_aggregation_query_filter_aggregation_model_json) + assert query_aggregation_query_filter_aggregation_model != False - # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation - query_filter_aggregation_model_dict = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json).__dict__ - query_filter_aggregation_model2 = QueryFilterAggregation(**query_filter_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryFilterAggregation by calling from_dict on the json representation + query_aggregation_query_filter_aggregation_model_dict = QueryAggregationQueryFilterAggregation.from_dict(query_aggregation_query_filter_aggregation_model_json).__dict__ + query_aggregation_query_filter_aggregation_model2 = QueryAggregationQueryFilterAggregation(**query_aggregation_query_filter_aggregation_model_dict) # Verify the model instances are equivalent - assert query_filter_aggregation_model == query_filter_aggregation_model2 + assert query_aggregation_query_filter_aggregation_model == query_aggregation_query_filter_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_filter_aggregation_model_json2 = query_filter_aggregation_model.to_dict() - assert query_filter_aggregation_model_json2 == query_filter_aggregation_model_json + query_aggregation_query_filter_aggregation_model_json2 = query_aggregation_query_filter_aggregation_model.to_dict() + assert query_aggregation_query_filter_aggregation_model_json2 == query_aggregation_query_filter_aggregation_model_json -class TestModel_QueryGroupByAggregation(): +class TestModel_QueryAggregationQueryGroupByAggregation(): """ - Test Class for QueryGroupByAggregation + Test Class for QueryAggregationQueryGroupByAggregation """ - def test_query_group_by_aggregation_serialization(self): + def test_query_aggregation_query_group_by_aggregation_serialization(self): """ - Test serialization/deserialization for QueryGroupByAggregation + Test serialization/deserialization for QueryAggregationQueryGroupByAggregation """ - # Construct a json representation of a QueryGroupByAggregation model - query_group_by_aggregation_model_json = {} - query_group_by_aggregation_model_json['type'] = 'group_by' + # Construct dict forms of any model objects needed in order to build this model. + + query_group_by_aggregation_result_model = {} # QueryGroupByAggregationResult + query_group_by_aggregation_result_model['key'] = 'testString' + query_group_by_aggregation_result_model['matching_results'] = 38 + query_group_by_aggregation_result_model['relevancy'] = 72.5 + query_group_by_aggregation_result_model['total_matching_documents'] = 38 + query_group_by_aggregation_result_model['estimated_matching_results'] = 72.5 + query_group_by_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + # Construct a json representation of a QueryAggregationQueryGroupByAggregation model + query_aggregation_query_group_by_aggregation_model_json = {} + query_aggregation_query_group_by_aggregation_model_json['type'] = 'group_by' + query_aggregation_query_group_by_aggregation_model_json['results'] = [query_group_by_aggregation_result_model] - # Construct a model instance of QueryGroupByAggregation by calling from_dict on the json representation - query_group_by_aggregation_model = QueryGroupByAggregation.from_dict(query_group_by_aggregation_model_json) - assert query_group_by_aggregation_model != False + # Construct a model instance of QueryAggregationQueryGroupByAggregation by calling from_dict on the json representation + query_aggregation_query_group_by_aggregation_model = QueryAggregationQueryGroupByAggregation.from_dict(query_aggregation_query_group_by_aggregation_model_json) + assert query_aggregation_query_group_by_aggregation_model != False - # Construct a model instance of QueryGroupByAggregation by calling from_dict on the json representation - query_group_by_aggregation_model_dict = QueryGroupByAggregation.from_dict(query_group_by_aggregation_model_json).__dict__ - query_group_by_aggregation_model2 = QueryGroupByAggregation(**query_group_by_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryGroupByAggregation by calling from_dict on the json representation + query_aggregation_query_group_by_aggregation_model_dict = QueryAggregationQueryGroupByAggregation.from_dict(query_aggregation_query_group_by_aggregation_model_json).__dict__ + query_aggregation_query_group_by_aggregation_model2 = QueryAggregationQueryGroupByAggregation(**query_aggregation_query_group_by_aggregation_model_dict) # Verify the model instances are equivalent - assert query_group_by_aggregation_model == query_group_by_aggregation_model2 + assert query_aggregation_query_group_by_aggregation_model == query_aggregation_query_group_by_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_group_by_aggregation_model_json2 = query_group_by_aggregation_model.to_dict() - assert query_group_by_aggregation_model_json2 == query_group_by_aggregation_model_json + query_aggregation_query_group_by_aggregation_model_json2 = query_aggregation_query_group_by_aggregation_model.to_dict() + assert query_aggregation_query_group_by_aggregation_model_json2 == query_aggregation_query_group_by_aggregation_model_json -class TestModel_QueryHistogramAggregation(): +class TestModel_QueryAggregationQueryHistogramAggregation(): """ - Test Class for QueryHistogramAggregation + Test Class for QueryAggregationQueryHistogramAggregation """ - def test_query_histogram_aggregation_serialization(self): + def test_query_aggregation_query_histogram_aggregation_serialization(self): """ - Test serialization/deserialization for QueryHistogramAggregation + Test serialization/deserialization for QueryAggregationQueryHistogramAggregation """ - # Construct a json representation of a QueryHistogramAggregation model - query_histogram_aggregation_model_json = {} - query_histogram_aggregation_model_json['type'] = 'histogram' - query_histogram_aggregation_model_json['field'] = 'testString' - query_histogram_aggregation_model_json['interval'] = 38 - query_histogram_aggregation_model_json['name'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. + + query_histogram_aggregation_result_model = {} # QueryHistogramAggregationResult + query_histogram_aggregation_result_model['key'] = 26 + query_histogram_aggregation_result_model['matching_results'] = 38 + query_histogram_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] - # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation - query_histogram_aggregation_model = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json) - assert query_histogram_aggregation_model != False + # Construct a json representation of a QueryAggregationQueryHistogramAggregation model + query_aggregation_query_histogram_aggregation_model_json = {} + query_aggregation_query_histogram_aggregation_model_json['type'] = 'histogram' + query_aggregation_query_histogram_aggregation_model_json['field'] = 'testString' + query_aggregation_query_histogram_aggregation_model_json['interval'] = 38 + query_aggregation_query_histogram_aggregation_model_json['name'] = 'testString' + query_aggregation_query_histogram_aggregation_model_json['results'] = [query_histogram_aggregation_result_model] - # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation - query_histogram_aggregation_model_dict = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json).__dict__ - query_histogram_aggregation_model2 = QueryHistogramAggregation(**query_histogram_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryHistogramAggregation by calling from_dict on the json representation + query_aggregation_query_histogram_aggregation_model = QueryAggregationQueryHistogramAggregation.from_dict(query_aggregation_query_histogram_aggregation_model_json) + assert query_aggregation_query_histogram_aggregation_model != False + + # Construct a model instance of QueryAggregationQueryHistogramAggregation by calling from_dict on the json representation + query_aggregation_query_histogram_aggregation_model_dict = QueryAggregationQueryHistogramAggregation.from_dict(query_aggregation_query_histogram_aggregation_model_json).__dict__ + query_aggregation_query_histogram_aggregation_model2 = QueryAggregationQueryHistogramAggregation(**query_aggregation_query_histogram_aggregation_model_dict) # Verify the model instances are equivalent - assert query_histogram_aggregation_model == query_histogram_aggregation_model2 + assert query_aggregation_query_histogram_aggregation_model == query_aggregation_query_histogram_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_histogram_aggregation_model_json2 = query_histogram_aggregation_model.to_dict() - assert query_histogram_aggregation_model_json2 == query_histogram_aggregation_model_json + query_aggregation_query_histogram_aggregation_model_json2 = query_aggregation_query_histogram_aggregation_model.to_dict() + assert query_aggregation_query_histogram_aggregation_model_json2 == query_aggregation_query_histogram_aggregation_model_json -class TestModel_QueryNestedAggregation(): +class TestModel_QueryAggregationQueryNestedAggregation(): """ - Test Class for QueryNestedAggregation + Test Class for QueryAggregationQueryNestedAggregation """ - def test_query_nested_aggregation_serialization(self): + def test_query_aggregation_query_nested_aggregation_serialization(self): """ - Test serialization/deserialization for QueryNestedAggregation + Test serialization/deserialization for QueryAggregationQueryNestedAggregation """ - # Construct a json representation of a QueryNestedAggregation model - query_nested_aggregation_model_json = {} - query_nested_aggregation_model_json['type'] = 'nested' - query_nested_aggregation_model_json['path'] = 'testString' - query_nested_aggregation_model_json['matching_results'] = 26 + # Construct a json representation of a QueryAggregationQueryNestedAggregation model + query_aggregation_query_nested_aggregation_model_json = {} + query_aggregation_query_nested_aggregation_model_json['type'] = 'nested' + query_aggregation_query_nested_aggregation_model_json['path'] = 'testString' + query_aggregation_query_nested_aggregation_model_json['matching_results'] = 26 + query_aggregation_query_nested_aggregation_model_json['aggregations'] = [{'foo': 'bar'}] - # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation - query_nested_aggregation_model = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json) - assert query_nested_aggregation_model != False + # Construct a model instance of QueryAggregationQueryNestedAggregation by calling from_dict on the json representation + query_aggregation_query_nested_aggregation_model = QueryAggregationQueryNestedAggregation.from_dict(query_aggregation_query_nested_aggregation_model_json) + assert query_aggregation_query_nested_aggregation_model != False - # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation - query_nested_aggregation_model_dict = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json).__dict__ - query_nested_aggregation_model2 = QueryNestedAggregation(**query_nested_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryNestedAggregation by calling from_dict on the json representation + query_aggregation_query_nested_aggregation_model_dict = QueryAggregationQueryNestedAggregation.from_dict(query_aggregation_query_nested_aggregation_model_json).__dict__ + query_aggregation_query_nested_aggregation_model2 = QueryAggregationQueryNestedAggregation(**query_aggregation_query_nested_aggregation_model_dict) # Verify the model instances are equivalent - assert query_nested_aggregation_model == query_nested_aggregation_model2 + assert query_aggregation_query_nested_aggregation_model == query_aggregation_query_nested_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_nested_aggregation_model_json2 = query_nested_aggregation_model.to_dict() - assert query_nested_aggregation_model_json2 == query_nested_aggregation_model_json + query_aggregation_query_nested_aggregation_model_json2 = query_aggregation_query_nested_aggregation_model.to_dict() + assert query_aggregation_query_nested_aggregation_model_json2 == query_aggregation_query_nested_aggregation_model_json -class TestModel_QueryTermAggregation(): +class TestModel_QueryAggregationQueryPairAggregation(): """ - Test Class for QueryTermAggregation + Test Class for QueryAggregationQueryPairAggregation """ - def test_query_term_aggregation_serialization(self): + def test_query_aggregation_query_pair_aggregation_serialization(self): """ - Test serialization/deserialization for QueryTermAggregation + Test serialization/deserialization for QueryAggregationQueryPairAggregation """ - # Construct a json representation of a QueryTermAggregation model - query_term_aggregation_model_json = {} - query_term_aggregation_model_json['type'] = 'term' - query_term_aggregation_model_json['field'] = 'testString' - query_term_aggregation_model_json['count'] = 38 - query_term_aggregation_model_json['name'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. + + query_pair_aggregation_result_model = {} # QueryPairAggregationResult + query_pair_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + # Construct a json representation of a QueryAggregationQueryPairAggregation model + query_aggregation_query_pair_aggregation_model_json = {} + query_aggregation_query_pair_aggregation_model_json['type'] = 'pair' + query_aggregation_query_pair_aggregation_model_json['first'] = 'testString' + query_aggregation_query_pair_aggregation_model_json['second'] = 'testString' + query_aggregation_query_pair_aggregation_model_json['show_estimated_matching_results'] = False + query_aggregation_query_pair_aggregation_model_json['show_total_matching_documents'] = False + query_aggregation_query_pair_aggregation_model_json['results'] = [query_pair_aggregation_result_model] + + # Construct a model instance of QueryAggregationQueryPairAggregation by calling from_dict on the json representation + query_aggregation_query_pair_aggregation_model = QueryAggregationQueryPairAggregation.from_dict(query_aggregation_query_pair_aggregation_model_json) + assert query_aggregation_query_pair_aggregation_model != False + + # Construct a model instance of QueryAggregationQueryPairAggregation by calling from_dict on the json representation + query_aggregation_query_pair_aggregation_model_dict = QueryAggregationQueryPairAggregation.from_dict(query_aggregation_query_pair_aggregation_model_json).__dict__ + query_aggregation_query_pair_aggregation_model2 = QueryAggregationQueryPairAggregation(**query_aggregation_query_pair_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_aggregation_query_pair_aggregation_model == query_aggregation_query_pair_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_aggregation_query_pair_aggregation_model_json2 = query_aggregation_query_pair_aggregation_model.to_dict() + assert query_aggregation_query_pair_aggregation_model_json2 == query_aggregation_query_pair_aggregation_model_json - # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation - query_term_aggregation_model = QueryTermAggregation.from_dict(query_term_aggregation_model_json) - assert query_term_aggregation_model != False +class TestModel_QueryAggregationQueryTermAggregation(): + """ + Test Class for QueryAggregationQueryTermAggregation + """ - # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation - query_term_aggregation_model_dict = QueryTermAggregation.from_dict(query_term_aggregation_model_json).__dict__ - query_term_aggregation_model2 = QueryTermAggregation(**query_term_aggregation_model_dict) + def test_query_aggregation_query_term_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryAggregationQueryTermAggregation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_term_aggregation_result_model = {} # QueryTermAggregationResult + query_term_aggregation_result_model['key'] = 'testString' + query_term_aggregation_result_model['matching_results'] = 38 + query_term_aggregation_result_model['relevancy'] = 72.5 + query_term_aggregation_result_model['total_matching_documents'] = 38 + query_term_aggregation_result_model['estimated_matching_results'] = 72.5 + query_term_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + # Construct a json representation of a QueryAggregationQueryTermAggregation model + query_aggregation_query_term_aggregation_model_json = {} + query_aggregation_query_term_aggregation_model_json['type'] = 'term' + query_aggregation_query_term_aggregation_model_json['field'] = 'testString' + query_aggregation_query_term_aggregation_model_json['count'] = 38 + query_aggregation_query_term_aggregation_model_json['name'] = 'testString' + query_aggregation_query_term_aggregation_model_json['results'] = [query_term_aggregation_result_model] + + # Construct a model instance of QueryAggregationQueryTermAggregation by calling from_dict on the json representation + query_aggregation_query_term_aggregation_model = QueryAggregationQueryTermAggregation.from_dict(query_aggregation_query_term_aggregation_model_json) + assert query_aggregation_query_term_aggregation_model != False + + # Construct a model instance of QueryAggregationQueryTermAggregation by calling from_dict on the json representation + query_aggregation_query_term_aggregation_model_dict = QueryAggregationQueryTermAggregation.from_dict(query_aggregation_query_term_aggregation_model_json).__dict__ + query_aggregation_query_term_aggregation_model2 = QueryAggregationQueryTermAggregation(**query_aggregation_query_term_aggregation_model_dict) # Verify the model instances are equivalent - assert query_term_aggregation_model == query_term_aggregation_model2 + assert query_aggregation_query_term_aggregation_model == query_aggregation_query_term_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_term_aggregation_model_json2 = query_term_aggregation_model.to_dict() - assert query_term_aggregation_model_json2 == query_term_aggregation_model_json + query_aggregation_query_term_aggregation_model_json2 = query_aggregation_query_term_aggregation_model.to_dict() + assert query_aggregation_query_term_aggregation_model_json2 == query_aggregation_query_term_aggregation_model_json -class TestModel_QueryTimesliceAggregation(): +class TestModel_QueryAggregationQueryTimesliceAggregation(): """ - Test Class for QueryTimesliceAggregation + Test Class for QueryAggregationQueryTimesliceAggregation """ - def test_query_timeslice_aggregation_serialization(self): + def test_query_aggregation_query_timeslice_aggregation_serialization(self): """ - Test serialization/deserialization for QueryTimesliceAggregation + Test serialization/deserialization for QueryAggregationQueryTimesliceAggregation """ - # Construct a json representation of a QueryTimesliceAggregation model - query_timeslice_aggregation_model_json = {} - query_timeslice_aggregation_model_json['type'] = 'timeslice' - query_timeslice_aggregation_model_json['field'] = 'testString' - query_timeslice_aggregation_model_json['interval'] = 'testString' - query_timeslice_aggregation_model_json['name'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. + + query_timeslice_aggregation_result_model = {} # QueryTimesliceAggregationResult + query_timeslice_aggregation_result_model['key_as_string'] = 'testString' + query_timeslice_aggregation_result_model['key'] = 26 + query_timeslice_aggregation_result_model['matching_results'] = 26 + query_timeslice_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] - # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation - query_timeslice_aggregation_model = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json) - assert query_timeslice_aggregation_model != False + # Construct a json representation of a QueryAggregationQueryTimesliceAggregation model + query_aggregation_query_timeslice_aggregation_model_json = {} + query_aggregation_query_timeslice_aggregation_model_json['type'] = 'timeslice' + query_aggregation_query_timeslice_aggregation_model_json['field'] = 'testString' + query_aggregation_query_timeslice_aggregation_model_json['interval'] = 'testString' + query_aggregation_query_timeslice_aggregation_model_json['name'] = 'testString' + query_aggregation_query_timeslice_aggregation_model_json['results'] = [query_timeslice_aggregation_result_model] - # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation - query_timeslice_aggregation_model_dict = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json).__dict__ - query_timeslice_aggregation_model2 = QueryTimesliceAggregation(**query_timeslice_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryTimesliceAggregation by calling from_dict on the json representation + query_aggregation_query_timeslice_aggregation_model = QueryAggregationQueryTimesliceAggregation.from_dict(query_aggregation_query_timeslice_aggregation_model_json) + assert query_aggregation_query_timeslice_aggregation_model != False + + # Construct a model instance of QueryAggregationQueryTimesliceAggregation by calling from_dict on the json representation + query_aggregation_query_timeslice_aggregation_model_dict = QueryAggregationQueryTimesliceAggregation.from_dict(query_aggregation_query_timeslice_aggregation_model_json).__dict__ + query_aggregation_query_timeslice_aggregation_model2 = QueryAggregationQueryTimesliceAggregation(**query_aggregation_query_timeslice_aggregation_model_dict) # Verify the model instances are equivalent - assert query_timeslice_aggregation_model == query_timeslice_aggregation_model2 + assert query_aggregation_query_timeslice_aggregation_model == query_aggregation_query_timeslice_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_timeslice_aggregation_model_json2 = query_timeslice_aggregation_model.to_dict() - assert query_timeslice_aggregation_model_json2 == query_timeslice_aggregation_model_json + query_aggregation_query_timeslice_aggregation_model_json2 = query_aggregation_query_timeslice_aggregation_model.to_dict() + assert query_aggregation_query_timeslice_aggregation_model_json2 == query_aggregation_query_timeslice_aggregation_model_json -class TestModel_QueryTopHitsAggregation(): +class TestModel_QueryAggregationQueryTopHitsAggregation(): """ - Test Class for QueryTopHitsAggregation + Test Class for QueryAggregationQueryTopHitsAggregation """ - def test_query_top_hits_aggregation_serialization(self): + def test_query_aggregation_query_top_hits_aggregation_serialization(self): """ - Test serialization/deserialization for QueryTopHitsAggregation + Test serialization/deserialization for QueryAggregationQueryTopHitsAggregation """ # Construct dict forms of any model objects needed in order to build this model. @@ -9070,27 +9185,105 @@ def test_query_top_hits_aggregation_serialization(self): query_top_hits_aggregation_result_model['matching_results'] = 38 query_top_hits_aggregation_result_model['hits'] = [{'foo': 'bar'}] - # Construct a json representation of a QueryTopHitsAggregation model - query_top_hits_aggregation_model_json = {} - query_top_hits_aggregation_model_json['type'] = 'top_hits' - query_top_hits_aggregation_model_json['size'] = 38 - query_top_hits_aggregation_model_json['name'] = 'testString' - query_top_hits_aggregation_model_json['hits'] = query_top_hits_aggregation_result_model + # Construct a json representation of a QueryAggregationQueryTopHitsAggregation model + query_aggregation_query_top_hits_aggregation_model_json = {} + query_aggregation_query_top_hits_aggregation_model_json['type'] = 'top_hits' + query_aggregation_query_top_hits_aggregation_model_json['size'] = 38 + query_aggregation_query_top_hits_aggregation_model_json['name'] = 'testString' + query_aggregation_query_top_hits_aggregation_model_json['hits'] = query_top_hits_aggregation_result_model + + # Construct a model instance of QueryAggregationQueryTopHitsAggregation by calling from_dict on the json representation + query_aggregation_query_top_hits_aggregation_model = QueryAggregationQueryTopHitsAggregation.from_dict(query_aggregation_query_top_hits_aggregation_model_json) + assert query_aggregation_query_top_hits_aggregation_model != False + + # Construct a model instance of QueryAggregationQueryTopHitsAggregation by calling from_dict on the json representation + query_aggregation_query_top_hits_aggregation_model_dict = QueryAggregationQueryTopHitsAggregation.from_dict(query_aggregation_query_top_hits_aggregation_model_json).__dict__ + query_aggregation_query_top_hits_aggregation_model2 = QueryAggregationQueryTopHitsAggregation(**query_aggregation_query_top_hits_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_aggregation_query_top_hits_aggregation_model == query_aggregation_query_top_hits_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_aggregation_query_top_hits_aggregation_model_json2 = query_aggregation_query_top_hits_aggregation_model.to_dict() + assert query_aggregation_query_top_hits_aggregation_model_json2 == query_aggregation_query_top_hits_aggregation_model_json + +class TestModel_QueryAggregationQueryTopicAggregation(): + """ + Test Class for QueryAggregationQueryTopicAggregation + """ + + def test_query_aggregation_query_topic_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryAggregationQueryTopicAggregation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_topic_aggregation_result_model = {} # QueryTopicAggregationResult + query_topic_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + # Construct a json representation of a QueryAggregationQueryTopicAggregation model + query_aggregation_query_topic_aggregation_model_json = {} + query_aggregation_query_topic_aggregation_model_json['type'] = 'topic' + query_aggregation_query_topic_aggregation_model_json['facet'] = 'testString' + query_aggregation_query_topic_aggregation_model_json['time_segments'] = 'testString' + query_aggregation_query_topic_aggregation_model_json['show_estimated_matching_results'] = False + query_aggregation_query_topic_aggregation_model_json['show_total_matching_documents'] = False + query_aggregation_query_topic_aggregation_model_json['results'] = [query_topic_aggregation_result_model] + + # Construct a model instance of QueryAggregationQueryTopicAggregation by calling from_dict on the json representation + query_aggregation_query_topic_aggregation_model = QueryAggregationQueryTopicAggregation.from_dict(query_aggregation_query_topic_aggregation_model_json) + assert query_aggregation_query_topic_aggregation_model != False + + # Construct a model instance of QueryAggregationQueryTopicAggregation by calling from_dict on the json representation + query_aggregation_query_topic_aggregation_model_dict = QueryAggregationQueryTopicAggregation.from_dict(query_aggregation_query_topic_aggregation_model_json).__dict__ + query_aggregation_query_topic_aggregation_model2 = QueryAggregationQueryTopicAggregation(**query_aggregation_query_topic_aggregation_model_dict) + + # Verify the model instances are equivalent + assert query_aggregation_query_topic_aggregation_model == query_aggregation_query_topic_aggregation_model2 + + # Convert model instance back to dict and verify no loss of data + query_aggregation_query_topic_aggregation_model_json2 = query_aggregation_query_topic_aggregation_model.to_dict() + assert query_aggregation_query_topic_aggregation_model_json2 == query_aggregation_query_topic_aggregation_model_json + +class TestModel_QueryAggregationQueryTrendAggregation(): + """ + Test Class for QueryAggregationQueryTrendAggregation + """ + + def test_query_aggregation_query_trend_aggregation_serialization(self): + """ + Test serialization/deserialization for QueryAggregationQueryTrendAggregation + """ + + # Construct dict forms of any model objects needed in order to build this model. + + query_trend_aggregation_result_model = {} # QueryTrendAggregationResult + query_trend_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + + # Construct a json representation of a QueryAggregationQueryTrendAggregation model + query_aggregation_query_trend_aggregation_model_json = {} + query_aggregation_query_trend_aggregation_model_json['type'] = 'trend' + query_aggregation_query_trend_aggregation_model_json['facet'] = 'testString' + query_aggregation_query_trend_aggregation_model_json['time_segments'] = 'testString' + query_aggregation_query_trend_aggregation_model_json['show_estimated_matching_results'] = False + query_aggregation_query_trend_aggregation_model_json['show_total_matching_documents'] = False + query_aggregation_query_trend_aggregation_model_json['results'] = [query_trend_aggregation_result_model] - # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation - query_top_hits_aggregation_model = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json) - assert query_top_hits_aggregation_model != False + # Construct a model instance of QueryAggregationQueryTrendAggregation by calling from_dict on the json representation + query_aggregation_query_trend_aggregation_model = QueryAggregationQueryTrendAggregation.from_dict(query_aggregation_query_trend_aggregation_model_json) + assert query_aggregation_query_trend_aggregation_model != False - # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation - query_top_hits_aggregation_model_dict = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json).__dict__ - query_top_hits_aggregation_model2 = QueryTopHitsAggregation(**query_top_hits_aggregation_model_dict) + # Construct a model instance of QueryAggregationQueryTrendAggregation by calling from_dict on the json representation + query_aggregation_query_trend_aggregation_model_dict = QueryAggregationQueryTrendAggregation.from_dict(query_aggregation_query_trend_aggregation_model_json).__dict__ + query_aggregation_query_trend_aggregation_model2 = QueryAggregationQueryTrendAggregation(**query_aggregation_query_trend_aggregation_model_dict) # Verify the model instances are equivalent - assert query_top_hits_aggregation_model == query_top_hits_aggregation_model2 + assert query_aggregation_query_trend_aggregation_model == query_aggregation_query_trend_aggregation_model2 # Convert model instance back to dict and verify no loss of data - query_top_hits_aggregation_model_json2 = query_top_hits_aggregation_model.to_dict() - assert query_top_hits_aggregation_model_json2 == query_top_hits_aggregation_model_json + query_aggregation_query_trend_aggregation_model_json2 = query_aggregation_query_trend_aggregation_model.to_dict() + assert query_aggregation_query_trend_aggregation_model_json2 == query_aggregation_query_trend_aggregation_model_json # endregion From d2d6fbfce304bdb197b665e612022d4c4cc6b5bd Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 23 Feb 2023 14:46:21 -0600 Subject: [PATCH 389/455] feat(assistantv2): add several new functions BREAKING CHANGE: createSession param removed BREAKING CHANGE: removing and changing of classes --- ibm_watson/assistant_v2.py | 10634 +++++++++++++++++++------------ test/unit/test_assistant_v2.py | 2115 +++++- 2 files changed, 8296 insertions(+), 4453 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 940eb8bd4..4ebc50f34 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -77,11 +77,188 @@ def __init__( self.version = version self.configure_service(service_name) + ######################### + # Assistants + ######################### + + def create_assistant(self, + *, + language: str = None, + name: str = None, + description: str = None, + **kwargs) -> DetailedResponse: + """ + Create an assistant. + + Create a new assistant. + This method is available only with Enterprise plans. + + :param str language: (optional) The language of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This + string cannot contain carriage return, newline, or tab characters. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Assistant` object + """ + + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_assistant') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'language': language, + 'name': name, + 'description': description, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/assistants' + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def list_assistants(self, + *, + page_limit: int = None, + include_count: bool = None, + sort: str = None, + cursor: str = None, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + List assistants. + + List the assistants associated with a Watson Assistant service instance. + This method is available only with Enterprise plans. + + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned assistants will + be sorted. To reverse the sort order, prefix the value with a minus sign + (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 with `dict` result representing a `AssistantCollection` object + """ + + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_assistants') + headers.update(sdk_headers) + + params = { + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/assistants' + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + def delete_assistant(self, assistant_id: str, **kwargs) -> DetailedResponse: + """ + Delete assistant. + + Delete an assistant. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_assistant') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}'.format(**path_param_dict) + request = self.prepare_request(method='DELETE', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + ######################### # Sessions ######################### - def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: + def create_session(self, + assistant_id: str, + *, + analytics: 'RequestAnalytics' = None, + **kwargs) -> DetailedResponse: """ Create a session. @@ -91,13 +268,21 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: information, see the [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/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. - :param dict request_body: (optional) + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SessionResponse` object @@ -105,6 +290,8 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: if not assistant_id: raise ValueError('assistant_id must be provided') + if analytics is not None: + analytics = convert_model(analytics) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', @@ -115,7 +302,9 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: 'version': self.version, } - data = {} + data = { + 'analytics': analytics, + } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) headers['content-type'] = 'application/json' @@ -147,12 +336,18 @@ def delete_session(self, assistant_id: str, session_id: str, session inactivity timeout, see the [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/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param str session_id: Unique identifier of the session. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -210,12 +405,18 @@ def message(self, (including context data) stored by Watson Assistant for the duration of the session. - :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/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param str session_id: Unique identifier of the session. :param MessageInput input: (optional) An input object that includes the input text. @@ -299,12 +500,18 @@ def message_stateless(self, Send user input to an assistant and receive a response, with conversation state (including context data) managed by your application. - :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/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param MessageInputStateless input: (optional) An input object that includes the input text. :param MessageContextStateless context: (optional) Context data for the @@ -454,18 +661,25 @@ def list_logs(self, List log events for an assistant. List the events from the log of an assistant. - This method requires Manager access, and is available only with Enterprise plans. + This method requires Manager access, and is available only with Plus and + Enterprise plans. **Note:** If you use the **cursor** parameter to retrieve results one page at a time, subsequent requests must be no more than 5 minutes apart. Any returned value for the **cursor** parameter becomes invalid after 5 minutes. For more information about using pagination, see [Pagination](#pagination). - :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/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :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 (`-`). @@ -585,13 +799,20 @@ def list_environments(self, List environments. List the environments associated with an assistant. - - :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/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param int page_limit: (optional) The number of records to return in each page of results. :param bool include_count: (optional) Whether to include information about @@ -656,13 +877,20 @@ def get_environment(self, Get information about an environment. For more information about environments, see [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). - - :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/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param str environment_id: Unique identifier of the environment. To find the environment ID in the Watson Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -707,10 +935,168 @@ def get_environment(self, response = self.send(request, **kwargs) return response + def update_environment(self, + assistant_id: str, + environment_id: str, + *, + name: str = None, + description: str = None, + session_timeout: int = None, + skill_references: List['EnvironmentSkill'] = None, + **kwargs) -> DetailedResponse: + """ + Update environment. + + Update an environment with new or modified data. For more information about + environments, see + [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the Watson Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param str name: (optional) The name of the environment. + :param str description: (optional) The description of the environment. + :param int session_timeout: (optional) The session inactivity timeout + setting for the environment (in seconds). + :param List[EnvironmentSkill] skill_references: (optional) An array of + objects identifying the skills (such as action and dialog) that exist in + the environment. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Environment` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + if skill_references is not None: + skill_references = [convert_model(x) for x in skill_references] + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_environment') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'name': name, + 'description': description, + 'session_timeout': session_timeout, + 'skill_references': skill_references, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + ######################### # Releases ######################### + def create_release(self, + assistant_id: str, + *, + description: str = None, + **kwargs) -> DetailedResponse: + """ + Create release. + + Create a new release using the current content of the dialog and action skills in + the draft environment. (In the Watson Assistant user interface, a release is + called a *version*.) + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str description: (optional) The description of the release. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Release` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_release') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'description': description, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases'.format(**path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + def list_releases(self, assistant_id: str, *, @@ -724,14 +1110,21 @@ def list_releases(self, List releases. List the releases associated with an assistant. (In the Watson Assistant user - interface, a release is called a *version*.). - - :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/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + interface, a release is called a *version*.) + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param int page_limit: (optional) The number of records to return in each page of results. :param bool include_count: (optional) Whether to include information about @@ -798,13 +1191,20 @@ def get_release(self, publishing is still in progress, you can continue to poll by calling the same request again and checking the value of the **status** property. When processing has completed, the request returns the release data. - - :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/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param str release: Unique identifier of the release. :param bool include_audit: (optional) Whether to include the audit properties (`created` and `updated` timestamps) in the response. @@ -846,59 +1246,47 @@ def get_release(self, response = self.send(request, **kwargs) return response - def deploy_release(self, - assistant_id: str, - release: str, - environment_id: str, - *, - include_audit: bool = None, + def delete_release(self, assistant_id: str, release: str, **kwargs) -> DetailedResponse: """ - Deploy release. - - Update the environment with the content of the release. All snapshots saved as - part of the release become active in the environment. - - :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/assistant?topic=assistant-assistant-add#assistant-add-task). - **Note:** Currently, the v2 API does not support creating assistants. + Delete release. + + Delete a release. (In the Watson Assistant user interface, a release is called a + *version*.) + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. :param str release: Unique identifier of the release. - :param str environment_id: The environment ID of the environment where the - release is to be deployed. - :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 with `dict` result representing a `Environment` object + :rtype: DetailedResponse """ if not assistant_id: raise ValueError('assistant_id must be provided') if not release: raise ValueError('release must be provided') - if environment_id is None: - raise ValueError('environment_id must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='deploy_release') + operation_id='delete_release') headers.update(sdk_headers) params = { 'version': self.version, - 'include_audit': include_audit, } - data = { - 'environment_id': environment_id, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - if 'headers' in kwargs: headers.update(kwargs.get('headers')) del kwargs['headers'] @@ -907,303 +1295,552 @@ def deploy_release(self, path_param_keys = ['assistant_id', 'release'] path_param_values = self.encode_path_vars(assistant_id, release) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/releases/{release}/deploy'.format( + url = '/v2/assistants/{assistant_id}/releases/{release}'.format( **path_param_dict) - request = self.prepare_request(method='POST', + request = self.prepare_request(method='DELETE', url=url, headers=headers, - params=params, - data=data) + params=params) response = self.send(request, **kwargs) return response - -class ListEnvironmentsEnums: - """ - Enums for list_environments parameters. - """ - - class Sort(str, Enum): - """ - The attribute by which returned environments will be sorted. To reverse the sort - order, prefix the value with a minus sign (`-`). + def deploy_release(self, + assistant_id: str, + release: str, + environment_id: str, + *, + include_audit: bool = None, + **kwargs) -> DetailedResponse: """ - NAME = 'name' - UPDATED = 'updated' + Deploy release. + Update the environment with the content of the release. All snapshots saved as + part of the release become active in the environment. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str release: Unique identifier of the release. + :param str environment_id: The environment ID of the environment where the + release is to be deployed. + :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 with `dict` result representing a `Environment` object + """ -class ListReleasesEnums: - """ - Enums for list_releases parameters. - """ + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not release: + raise ValueError('release must be provided') + if environment_id is None: + raise ValueError('environment_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='deploy_release') + headers.update(sdk_headers) - class Sort(str, Enum): - """ - The attribute by which returned workspaces will be sorted. To reverse the sort - order, prefix the value with a minus sign (`-`). - """ - NAME = 'name' - UPDATED = 'updated' + params = { + 'version': self.version, + 'include_audit': include_audit, + } + data = { + 'environment_id': environment_id, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' -############################################################################## -# Models -############################################################################## + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/releases/{release}/deploy'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) -class AgentAvailabilityMessage(): - """ - AgentAvailabilityMessage. + response = self.send(request, **kwargs) + return response - :attr str message: (optional) The text of the message. - """ + ######################### + # Skills + ######################### - def __init__(self, *, message: str = None) -> None: + def get_skill(self, assistant_id: str, skill_id: str, + **kwargs) -> DetailedResponse: """ - Initialize a AgentAvailabilityMessage object. - - :param str message: (optional) The text of the message. + Get skill. + + Get information about a skill. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the Watson Assistant user interface, open the skill settings and click + **API Details**. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Skill` object """ - self.message = message - @classmethod - def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': - """Initialize a AgentAvailabilityMessage object from a json dictionary.""" - args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') - return cls(**args) + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not skill_id: + raise ValueError('skill_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_skill') + headers.update(sdk_headers) - @classmethod - def _from_dict(cls, _dict): - """Initialize a AgentAvailabilityMessage object from a json dictionary.""" - return cls.from_dict(_dict) + params = { + 'version': self.version, + } - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message - return _dict + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + path_param_keys = ['assistant_id', 'skill_id'] + path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - def __str__(self) -> str: - """Return a `str` version of this AgentAvailabilityMessage object.""" - return json.dumps(self.to_dict(), indent=2) + response = self.send(request, **kwargs) + return response - def __eq__(self, other: 'AgentAvailabilityMessage') -> 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 update_skill(self, + assistant_id: str, + skill_id: str, + *, + name: str = None, + description: str = None, + workspace: dict = None, + dialog_settings: dict = None, + search_settings: dict = None, + **kwargs) -> DetailedResponse: + """ + Update skill. + + Update a skill with new or modified data. + **Note:** The update is performed asynchronously; you can see the status of the + update by calling the **Get skill** method and checking the value of the + **status** property. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the Watson Assistant user interface, open the skill settings and click + **API Details**. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param dict search_settings: (optional) A JSON object describing the search + skill configuration. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Skill` object + """ - def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not skill_id: + raise ValueError('skill_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_skill') + headers.update(sdk_headers) + params = { + 'version': self.version, + } -class BulkClassifyOutput(): - """ - BulkClassifyOutput. + data = { + 'name': name, + 'description': description, + 'workspace': workspace, + 'dialog_settings': dialog_settings, + 'search_settings': search_settings, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - :attr BulkClassifyUtterance input: (optional) The user input utterance to - classify. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified - in the utterance. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in - the utterance. - """ + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def __init__(self, - *, - input: 'BulkClassifyUtterance' = None, - entities: List['RuntimeEntity'] = None, - intents: List['RuntimeIntent'] = None) -> None: - """ - Initialize a BulkClassifyOutput object. + path_param_keys = ['assistant_id', 'skill_id'] + path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) - :param BulkClassifyUtterance input: (optional) The user input utterance to - classify. - :param List[RuntimeEntity] entities: (optional) An array of entities - identified in the utterance. - :param List[RuntimeIntent] intents: (optional) An array of intents - recognized in the utterance. + response = self.send(request, **kwargs) + return response + + def export_skills(self, + assistant_id: str, + *, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + Export skills. + + Asynchronously export the action skill and dialog skill (if enabled) for the + assistant. Use this method to save all skill data so that you can import it to a + different assistant using the **Import skills** method. + A successful call to this method only initiates an asynchronous export. The + exported JSON data is not available until processing completes. + After the initial request is submitted, you can poll the status of the operation + by calling the same request again and checking the value of the **status** + property. If an error occurs (indicated by a **status** value of `Failed`), the + `status_description` property provides more information about the error, and the + `status_errors` property contains an array of error messages that caused the + failure. + When processing has completed, the request returns the exported JSON data. + Remember that the usual rate limits apply. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :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 with `dict` result representing a `SkillsExport` object """ - self.input = input - self.entities = entities - self.intents = intents - @classmethod - def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': - """Initialize a BulkClassifyOutput object from a json dictionary.""" - args = {} - if 'input' in _dict: - args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - return cls(**args) + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='export_skills') + headers.update(sdk_headers) - @classmethod - def _from_dict(cls, _dict): - """Initialize a BulkClassifyOutput object from a json dictionary.""" - return cls.from_dict(_dict) + params = { + 'version': self.version, + 'include_audit': include_audit, + } - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'input') and self.input is not None: - if isinstance(self.input, dict): - _dict['input'] = self.input - else: - _dict['input'] = self.input.to_dict() - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - return _dict + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_export'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) - def __str__(self) -> str: - """Return a `str` version of this BulkClassifyOutput object.""" - return json.dumps(self.to_dict(), indent=2) + response = self.send(request, **kwargs) + return response - def __eq__(self, other: 'BulkClassifyOutput') -> 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 import_skills(self, + assistant_id: str, + assistant_skills: List['SkillImport'], + assistant_state: 'AssistantState', + *, + include_audit: bool = None, + **kwargs) -> DetailedResponse: + """ + Import skills. + + Asynchronously import skills into an existing assistant from a previously exported + file. + The request body for this method should contain the response data that was + received from a previous call to the **Export skills** method, without + modification. + A successful call to this method initiates an asynchronous import. The updated + skills belonging to the assistant are not available until processing completes. To + check the status of the asynchronous import operation, use the **Get status of + skills import** method. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param List[SkillImport] assistant_skills: An array of objects describing + the skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. + :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 with `dict` result representing a `SkillsAsyncRequestStatus` object + """ - def __ne__(self, other: 'BulkClassifyOutput') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + if not assistant_id: + raise ValueError('assistant_id must be provided') + if assistant_skills is None: + raise ValueError('assistant_skills must be provided') + if assistant_state is None: + raise ValueError('assistant_state must be provided') + assistant_skills = [convert_model(x) for x in assistant_skills] + assistant_state = convert_model(assistant_state) + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills') + headers.update(sdk_headers) + params = { + 'version': self.version, + 'include_audit': include_audit, + } -class BulkClassifyResponse(): - """ - BulkClassifyResponse. + data = { + 'assistant_skills': assistant_skills, + 'assistant_state': assistant_state, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - :attr List[BulkClassifyOutput] output: (optional) An array of objects that - contain classification information for the submitted input utterances. - """ + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_import'.format( + **path_param_dict) + request = self.prepare_request(method='POST', + url=url, + headers=headers, + params=params, + data=data) + + response = self.send(request, **kwargs) + return response + + def import_skills_status(self, assistant_id: str, + **kwargs) -> DetailedResponse: + """ + Get status of skills import. + + Retrieve the status of an asynchronous import operation previously initiated by + using the **Import skills** method. + This method is available only with Enterprise plans. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the Watson Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object """ - Initialize a BulkClassifyResponse object. - :param List[BulkClassifyOutput] output: (optional) An array of objects that - contain classification information for the submitted input utterances. + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills_status') + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_import/status'.format( + **path_param_dict) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params) + + response = self.send(request, **kwargs) + return response + + +class ListAssistantsEnums: + """ + Enums for list_assistants parameters. + """ + + class Sort(str, Enum): """ - self.output = output + The attribute by which returned assistants will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + NAME = 'name' + UPDATED = 'updated' - @classmethod - def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': - """Initialize a BulkClassifyResponse object from a json dictionary.""" - args = {} - if 'output' in _dict: - args['output'] = [ - BulkClassifyOutput.from_dict(v) for v in _dict.get('output') - ] - return cls(**args) - @classmethod - def _from_dict(cls, _dict): - """Initialize a BulkClassifyResponse object from a json dictionary.""" - return cls.from_dict(_dict) +class ListEnvironmentsEnums: + """ + Enums for list_environments parameters. + """ - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'output') and self.output is not None: - output_list = [] - for v in self.output: - if isinstance(v, dict): - output_list.append(v) - else: - output_list.append(v.to_dict()) - _dict['output'] = output_list - return _dict + class Sort(str, Enum): + """ + The attribute by which returned environments will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + NAME = 'name' + UPDATED = 'updated' - 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 BulkClassifyResponse object.""" - return json.dumps(self.to_dict(), indent=2) +class ListReleasesEnums: + """ + Enums for list_releases parameters. + """ - def __eq__(self, other: 'BulkClassifyResponse') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + class Sort(str, Enum): + """ + The attribute by which returned workspaces will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + NAME = 'name' + UPDATED = 'updated' - def __ne__(self, other: 'BulkClassifyResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + +############################################################################## +# Models +############################################################################## -class BulkClassifyUtterance(): +class AgentAvailabilityMessage(): """ - The user input utterance to classify. + AgentAvailabilityMessage. - :attr str text: The text of the input utterance. + :attr str message: (optional) The text of the message. """ - def __init__(self, text: str) -> None: + def __init__(self, *, message: str = None) -> None: """ - Initialize a BulkClassifyUtterance object. + Initialize a AgentAvailabilityMessage object. - :param str text: The text of the input utterance. + :param str message: (optional) The text of the message. """ - self.text = text + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': - """Initialize a BulkClassifyUtterance object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': + """Initialize a AgentAvailabilityMessage object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in BulkClassifyUtterance JSON' - ) + if 'message' in _dict: + args['message'] = _dict.get('message') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a BulkClassifyUtterance object from a json dictionary.""" + """Initialize a AgentAvailabilityMessage 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, 'text') and self.text is not None: - _dict['text'] = self.text + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -1211,65 +1848,124 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this BulkClassifyUtterance object.""" + """Return a `str` version of this AgentAvailabilityMessage object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'BulkClassifyUtterance') -> bool: + def __eq__(self, other: 'AgentAvailabilityMessage') -> 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: 'BulkClassifyUtterance') -> bool: + def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class CaptureGroup(): +class Assistant(): """ - CaptureGroup. + Assistant. - :attr str group: A recognized capture group for the entity. - :attr List[int] location: (optional) Zero-based character offsets that indicate - where the entity value begins and ends in the input text. + :attr str assistant_id: (optional) The unique identifier of the assistant. + :attr str name: (optional) The name of the assistant. This string cannot contain + carriage return, newline, or tab characters. + :attr str description: (optional) The description of the assistant. This string + cannot contain carriage return, newline, or tab characters. + :attr str language: The language of the assistant. + :attr List[AssistantSkill] assistant_skills: (optional) An array of skill + references identifying the skills associated with the assistant. + :attr List[EnvironmentReference] assistant_environments: (optional) An array of + objects describing the environments defined for the assistant. """ - def __init__(self, group: str, *, location: List[int] = None) -> None: + def __init__( + self, + language: str, + *, + assistant_id: str = None, + name: str = None, + description: str = None, + assistant_skills: List['AssistantSkill'] = None, + assistant_environments: List['EnvironmentReference'] = None + ) -> None: """ - Initialize a CaptureGroup object. + Initialize a Assistant object. - :param str group: A recognized capture group for the entity. - :param List[int] location: (optional) Zero-based character offsets that - indicate where the entity value begins and ends in the input text. + :param str language: The language of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This + string cannot contain carriage return, newline, or tab characters. """ - self.group = group - self.location = location + self.assistant_id = assistant_id + self.name = name + self.description = description + self.language = language + self.assistant_skills = assistant_skills + self.assistant_environments = assistant_environments @classmethod - def from_dict(cls, _dict: Dict) -> 'CaptureGroup': - """Initialize a CaptureGroup object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Assistant': + """Initialize a Assistant object from a json dictionary.""" args = {} - if 'group' in _dict: - args['group'] = _dict.get('group') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'language' in _dict: + args['language'] = _dict.get('language') else: raise ValueError( - 'Required property \'group\' not present in CaptureGroup JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') + 'Required property \'language\' not present in Assistant JSON') + if 'assistant_skills' in _dict: + args['assistant_skills'] = [ + AssistantSkill.from_dict(v) + for v in _dict.get('assistant_skills') + ] + if 'assistant_environments' in _dict: + args['assistant_environments'] = [ + EnvironmentReference.from_dict(v) + for v in _dict.get('assistant_environments') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CaptureGroup object from a json dictionary.""" + """Initialize a Assistant 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, 'group') and self.group is not None: - _dict['group'] = self.group - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'assistant_skills') and getattr( + self, 'assistant_skills') is not None: + assistant_skills_list = [] + for v in getattr(self, 'assistant_skills'): + if isinstance(v, dict): + assistant_skills_list.append(v) + else: + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, 'assistant_environments') and getattr( + self, 'assistant_environments') is not None: + assistant_environments_list = [] + for v in getattr(self, 'assistant_environments'): + if isinstance(v, dict): + assistant_environments_list.append(v) + else: + assistant_environments_list.append(v.to_dict()) + _dict['assistant_environments'] = assistant_environments_list return _dict def _to_dict(self): @@ -1277,68 +1973,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CaptureGroup object.""" + """Return a `str` version of this Assistant object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CaptureGroup') -> bool: + def __eq__(self, other: 'Assistant') -> 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: 'CaptureGroup') -> bool: + def __ne__(self, other: 'Assistant') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ChannelTransferInfo(): +class AssistantCollection(): """ - Information used by an integration to transfer the conversation to a different - channel. + AssistantCollection. - :attr ChannelTransferTarget target: An object specifying target channels - available for the transfer. Each property of this object represents an available - transfer target. Currently, the only supported property is **chat**, - representing the web chat integration. + :attr List[Assistant] assistants: An array of objects describing the assistants + associated with the instance. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, target: 'ChannelTransferTarget') -> None: + def __init__(self, assistants: List['Assistant'], + pagination: 'Pagination') -> None: """ - Initialize a ChannelTransferInfo object. + Initialize a AssistantCollection object. - :param ChannelTransferTarget target: An object specifying target channels - available for the transfer. Each property of this object represents an - available transfer target. Currently, the only supported property is - **chat**, representing the web chat integration. + :param List[Assistant] assistants: An array of objects describing the + assistants associated with the instance. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - self.target = target + self.assistants = assistants + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': - """Initialize a ChannelTransferInfo object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AssistantCollection': + """Initialize a AssistantCollection object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = ChannelTransferTarget.from_dict( - _dict.get('target')) + if 'assistants' in _dict: + args['assistants'] = [ + Assistant.from_dict(v) for v in _dict.get('assistants') + ] else: raise ValueError( - 'Required property \'target\' not present in ChannelTransferInfo JSON' + 'Required property \'assistants\' not present in AssistantCollection JSON' + ) + if 'pagination' in _dict: + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in AssistantCollection JSON' ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ChannelTransferInfo object from a json dictionary.""" + """Initialize a AssistantCollection 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, 'target') and self.target is not None: - if isinstance(self.target, dict): - _dict['target'] = self.target + if hasattr(self, 'assistants') and self.assistants is not None: + assistants_list = [] + for v in self.assistants: + if isinstance(v, dict): + assistants_list.append(v) + else: + assistants_list.append(v.to_dict()) + _dict['assistants'] = assistants_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination else: - _dict['target'] = self.target.to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -1346,61 +2058,64 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ChannelTransferInfo object.""" + """Return a `str` version of this AssistantCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ChannelTransferInfo') -> bool: + def __eq__(self, other: 'AssistantCollection') -> 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: 'ChannelTransferInfo') -> bool: + def __ne__(self, other: 'AssistantCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ChannelTransferTarget(): +class AssistantSkill(): """ - An object specifying target channels available for the transfer. Each property of this - object represents an available transfer target. Currently, the only supported property - is **chat**, representing the web chat integration. + AssistantSkill. - :attr ChannelTransferTargetChat chat: (optional) Information for transferring to - the web chat integration. + :attr str skill_id: The skill ID of the skill. + :attr str type: (optional) The type of the skill. """ - def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: + def __init__(self, skill_id: str, *, type: str = None) -> None: """ - Initialize a ChannelTransferTarget object. + Initialize a AssistantSkill object. - :param ChannelTransferTargetChat chat: (optional) Information for - transferring to the web chat integration. + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. """ - self.chat = chat + self.skill_id = skill_id + self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': - """Initialize a ChannelTransferTarget object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AssistantSkill': + """Initialize a AssistantSkill object from a json dictionary.""" args = {} - if 'chat' in _dict: - args['chat'] = ChannelTransferTargetChat.from_dict( - _dict.get('chat')) + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + else: + raise ValueError( + 'Required property \'skill_id\' not present in AssistantSkill JSON' + ) + if 'type' in _dict: + args['type'] = _dict.get('type') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ChannelTransferTarget object from a json dictionary.""" + """Initialize a AssistantSkill 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, 'chat') and self.chat is not None: - if isinstance(self.chat, dict): - _dict['chat'] = self.chat - else: - _dict['chat'] = self.chat.to_dict() + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -1408,53 +2123,83 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ChannelTransferTarget object.""" + """Return a `str` version of this AssistantSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ChannelTransferTarget') -> bool: + def __eq__(self, other: 'AssistantSkill') -> 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: 'ChannelTransferTarget') -> bool: + def __ne__(self, other: 'AssistantSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of the skill. + """ + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + -class ChannelTransferTargetChat(): +class AssistantState(): """ - Information for transferring to the web chat integration. + Status information about the skills for the assistant. Included in responses only if + **status**=`Available`. - :attr str url: (optional) The URL of the target web chat. + :attr bool action_disabled: Whether the action skill is disabled in the draft + environment. + :attr bool dialog_disabled: Whether the dialog skill is disabled in the draft + environment. """ - def __init__(self, *, url: str = None) -> None: + def __init__(self, action_disabled: bool, dialog_disabled: bool) -> None: """ - Initialize a ChannelTransferTargetChat object. + Initialize a AssistantState object. - :param str url: (optional) The URL of the target web chat. + :param bool action_disabled: Whether the action skill is disabled in the + draft environment. + :param bool dialog_disabled: Whether the dialog skill is disabled in the + draft environment. """ - self.url = url + self.action_disabled = action_disabled + self.dialog_disabled = dialog_disabled @classmethod - def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': - """Initialize a ChannelTransferTargetChat object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AssistantState': + """Initialize a AssistantState object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if 'action_disabled' in _dict: + args['action_disabled'] = _dict.get('action_disabled') + else: + raise ValueError( + 'Required property \'action_disabled\' not present in AssistantState JSON' + ) + if 'dialog_disabled' in _dict: + args['dialog_disabled'] = _dict.get('dialog_disabled') + else: + raise ValueError( + 'Required property \'dialog_disabled\' not present in AssistantState JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ChannelTransferTargetChat object from a json dictionary.""" + """Initialize a AssistantState 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, 'url') and self.url is not None: - _dict['url'] = self.url + if hasattr(self, + 'action_disabled') and self.action_disabled is not None: + _dict['action_disabled'] = self.action_disabled + if hasattr(self, + 'dialog_disabled') and self.dialog_disabled is not None: + _dict['dialog_disabled'] = self.dialog_disabled return _dict def _to_dict(self): @@ -1462,98 +2207,60 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ChannelTransferTargetChat object.""" + """Return a `str` version of this AssistantState object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ChannelTransferTargetChat') -> bool: + def __eq__(self, other: 'AssistantState') -> 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: 'ChannelTransferTargetChat') -> bool: + def __ne__(self, other: 'AssistantState') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogLogMessage(): +class BaseEnvironmentOrchestration(): """ - Dialog log message details. + The search skill orchestration settings for the environment. - :attr str level: The severity of the log message. - :attr str message: The text of the log message. - :attr str code: A code that indicates the category to which the error message - belongs. - :attr LogMessageSource source: (optional) An object that identifies the dialog - element that generated the error message. + :attr bool search_skill_fallback: (optional) Whether assistants deployed to the + environment fall back to a search skill when responding to messages that do not + match any intent. If no search skill is configured for the assistant, this + property is ignored. """ - def __init__(self, - level: str, - message: str, - code: str, - *, - source: 'LogMessageSource' = None) -> None: + def __init__(self, *, search_skill_fallback: bool = None) -> None: """ - Initialize a DialogLogMessage object. + Initialize a BaseEnvironmentOrchestration object. - :param str level: The severity of the log message. - :param str message: The text of the log message. - :param str code: A code that indicates the category to which the error - message belongs. - :param LogMessageSource source: (optional) An object that identifies the - dialog element that generated the error message. + :param bool search_skill_fallback: (optional) Whether assistants deployed + to the environment fall back to a search skill when responding to messages + that do not match any intent. If no search skill is configured for the + assistant, this property is ignored. """ - self.level = level - self.message = message - self.code = code - self.source = source + self.search_skill_fallback = search_skill_fallback @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': - """Initialize a DialogLogMessage object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'BaseEnvironmentOrchestration': + """Initialize a BaseEnvironmentOrchestration object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') - else: - raise ValueError( - 'Required property \'level\' not present in DialogLogMessage JSON' - ) - if 'message' in _dict: - args['message'] = _dict.get('message') - else: - raise ValueError( - 'Required property \'message\' not present in DialogLogMessage JSON' - ) - if 'code' in _dict: - args['code'] = _dict.get('code') - else: - raise ValueError( - 'Required property \'code\' not present in DialogLogMessage JSON' - ) - if 'source' in _dict: - args['source'] = LogMessageSource.from_dict(_dict.get('source')) + if 'search_skill_fallback' in _dict: + args['search_skill_fallback'] = _dict.get('search_skill_fallback') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogLogMessage object from a json dictionary.""" + """Initialize a BaseEnvironmentOrchestration 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, 'level') and self.level is not None: - _dict['level'] = self.level - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message - if hasattr(self, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() + if hasattr(self, 'search_skill_fallback' + ) and self.search_skill_fallback is not None: + _dict['search_skill_fallback'] = self.search_skill_fallback return _dict def _to_dict(self): @@ -1561,110 +2268,53 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogLogMessage object.""" + """Return a `str` version of this BaseEnvironmentOrchestration object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogLogMessage') -> bool: + def __eq__(self, other: 'BaseEnvironmentOrchestration') -> 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: 'DialogLogMessage') -> bool: + def __ne__(self, other: 'BaseEnvironmentOrchestration') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LevelEnum(str, Enum): - """ - The severity of the log message. - """ - INFO = 'info' - ERROR = 'error' - WARN = 'warn' - -class DialogNodeAction(): +class BaseEnvironmentReleaseReference(): """ - DialogNodeAction. + An object describing the release that is currently deployed in the environment. - :attr str name: The name of the action. - :attr str type: (optional) The type of action to invoke. - :attr dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :attr str result_variable: The location in the dialog context where the result - of the action is stored. - :attr str credentials: (optional) The name of the context variable that the - client application will use to pass in credentials for the action. + :attr str release: (optional) The name of the deployed release. """ - def __init__(self, - name: str, - result_variable: str, - *, - type: str = None, - parameters: dict = None, - credentials: str = None) -> None: + def __init__(self, *, release: str = None) -> None: """ - Initialize a DialogNodeAction object. + Initialize a BaseEnvironmentReleaseReference object. - :param str name: The name of the action. - :param str result_variable: The location in the dialog context where the - result of the action is stored. - :param str type: (optional) The type of action to invoke. - :param dict parameters: (optional) A map of key/value pairs to be provided - to the action. - :param str credentials: (optional) The name of the context variable that - the client application will use to pass in credentials for the action. + :param str release: (optional) The name of the deployed release. """ - self.name = name - self.type = type - self.parameters = parameters - self.result_variable = result_variable - self.credentials = credentials + self.release = release @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': - """Initialize a DialogNodeAction object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'BaseEnvironmentReleaseReference': + """Initialize a BaseEnvironmentReleaseReference object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in DialogNodeAction JSON' - ) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'parameters' in _dict: - args['parameters'] = _dict.get('parameters') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') - else: - raise ValueError( - 'Required property \'result_variable\' not present in DialogNodeAction JSON' - ) - if 'credentials' in _dict: - args['credentials'] = _dict.get('credentials') + if 'release' in _dict: + args['release'] = _dict.get('release') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeAction object from a json dictionary.""" + """Initialize a BaseEnvironmentReleaseReference 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'parameters') and self.parameters is not None: - _dict['parameters'] = self.parameters - if hasattr(self, - 'result_variable') and self.result_variable is not None: - _dict['result_variable'] = self.result_variable - if hasattr(self, 'credentials') and self.credentials is not None: - _dict['credentials'] = self.credentials + if hasattr(self, 'release') and self.release is not None: + _dict['release'] = self.release return _dict def _to_dict(self): @@ -1672,63 +2322,96 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeAction object.""" + """Return a `str` version of this BaseEnvironmentReleaseReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeAction') -> bool: + def __eq__(self, other: 'BaseEnvironmentReleaseReference') -> 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: 'DialogNodeAction') -> bool: + def __ne__(self, other: 'BaseEnvironmentReleaseReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of action to invoke. - """ - CLIENT = 'client' - SERVER = 'server' - WEB_ACTION = 'web-action' - CLOUD_FUNCTION = 'cloud-function' - -class DialogNodeOutputConnectToAgentTransferInfo(): +class BulkClassifyOutput(): """ - Routing or other contextual information to be used by target service desk systems. + BulkClassifyOutput. - :attr dict target: (optional) + :attr BulkClassifyUtterance input: (optional) The user input utterance to + classify. + :attr List[RuntimeEntity] entities: (optional) An array of entities identified + in the utterance. + :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + the utterance. """ - def __init__(self, *, target: dict = None) -> None: + def __init__(self, + *, + input: 'BulkClassifyUtterance' = None, + entities: List['RuntimeEntity'] = None, + intents: List['RuntimeIntent'] = None) -> None: """ - Initialize a DialogNodeOutputConnectToAgentTransferInfo object. + Initialize a BulkClassifyOutput object. - :param dict target: (optional) + :param BulkClassifyUtterance input: (optional) The user input utterance to + classify. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the utterance. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the utterance. """ - self.target = target + self.input = input + self.entities = entities + self.intents = intents @classmethod - def from_dict(cls, - _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': - """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': + """Initialize a BulkClassifyOutput object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = _dict.get('target') + if 'input' in _dict: + args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity.from_dict(v) for v in _dict.get('entities') + ] + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent.from_dict(v) for v in _dict.get('intents') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" + """Initialize a BulkClassifyOutput 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, 'target') and self.target is not None: - _dict['target'] = self.target + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list return _dict def _to_dict(self): @@ -1736,78 +2419,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputConnectToAgentTransferInfo object.""" + """Return a `str` version of this BulkClassifyOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: + def __eq__(self, other: 'BulkClassifyOutput') -> 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: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: + def __ne__(self, other: 'BulkClassifyOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogNodeOutputOptionsElement(): +class BulkClassifyResponse(): """ - DialogNodeOutputOptionsElement. + BulkClassifyResponse. - :attr str label: The user-facing label for the option. - :attr DialogNodeOutputOptionsElementValue value: An object defining the message - input to be sent to the assistant if the user selects the corresponding option. + :attr List[BulkClassifyOutput] output: (optional) An array of objects that + contain classification information for the submitted input utterances. """ - def __init__(self, label: str, - value: 'DialogNodeOutputOptionsElementValue') -> None: + def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: """ - Initialize a DialogNodeOutputOptionsElement object. + Initialize a BulkClassifyResponse object. - :param str label: The user-facing label for the option. - :param DialogNodeOutputOptionsElementValue value: An object defining the - message input to be sent to the assistant if the user selects the - corresponding option. + :param List[BulkClassifyOutput] output: (optional) An array of objects that + contain classification information for the submitted input utterances. """ - self.label = label - self.value = value + self.output = output @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': - """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': + """Initialize a BulkClassifyResponse object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - else: - raise ValueError( - 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' - ) - if 'value' in _dict: - args['value'] = DialogNodeOutputOptionsElementValue.from_dict( - _dict.get('value')) - else: - raise ValueError( - 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' - ) + if 'output' in _dict: + args['output'] = [ + BulkClassifyOutput.from_dict(v) for v in _dict.get('output') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" + """Initialize a BulkClassifyResponse 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, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'value') and self.value is not None: - if isinstance(self.value, dict): - _dict['value'] = self.value - else: - _dict['value'] = self.value.to_dict() + if hasattr(self, 'output') and self.output is not None: + output_list = [] + for v in self.output: + if isinstance(v, dict): + output_list.append(v) + else: + output_list.append(v.to_dict()) + _dict['output'] = output_list return _dict def _to_dict(self): @@ -1815,59 +2483,57 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputOptionsElement object.""" + """Return a `str` version of this BulkClassifyResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> bool: + def __eq__(self, other: 'BulkClassifyResponse') -> 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: 'DialogNodeOutputOptionsElement') -> bool: + def __ne__(self, other: 'BulkClassifyResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogNodeOutputOptionsElementValue(): +class BulkClassifyUtterance(): """ - An object defining the message input to be sent to the assistant if the user selects - the corresponding option. + The user input utterance to classify. - :attr MessageInput input: (optional) An input object that includes the input - text. + :attr str text: The text of the input utterance. """ - def __init__(self, *, input: 'MessageInput' = None) -> None: + def __init__(self, text: str) -> None: """ - Initialize a DialogNodeOutputOptionsElementValue object. + Initialize a BulkClassifyUtterance object. - :param MessageInput input: (optional) An input object that includes the - input text. + :param str text: The text of the input utterance. """ - self.input = input + self.text = text @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': - """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" - args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': + """Initialize a BulkClassifyUtterance object from a json dictionary.""" + args = {} + if 'text' in _dict: + args['text'] = _dict.get('text') + else: + raise ValueError( + 'Required property \'text\' not present in BulkClassifyUtterance JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" + """Initialize a BulkClassifyUtterance 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, 'input') and self.input is not None: - if isinstance(self.input, dict): - _dict['input'] = self.input - else: - _dict['input'] = self.input.to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text return _dict def _to_dict(self): @@ -1875,75 +2541,65 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputOptionsElementValue object.""" + """Return a `str` version of this BulkClassifyUtterance object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: + def __eq__(self, other: 'BulkClassifyUtterance') -> 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: 'DialogNodeOutputOptionsElementValue') -> bool: + def __ne__(self, other: 'BulkClassifyUtterance') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogNodeVisited(): +class CaptureGroup(): """ - An objects containing detailed diagnostic information about a dialog node that was - visited during processing of the input message. + CaptureGroup. - :attr str dialog_node: (optional) A dialog node that was visited during - processing of the input message. - :attr str title: (optional) The title of the dialog node. - :attr str conditions: (optional) The conditions that trigger the dialog node. + :attr str group: A recognized capture group for the entity. + :attr List[int] location: (optional) Zero-based character offsets that indicate + where the entity value begins and ends in the input text. """ - def __init__(self, - *, - dialog_node: str = None, - title: str = None, - conditions: str = None) -> None: + def __init__(self, group: str, *, location: List[int] = None) -> None: """ - Initialize a DialogNodeVisited object. + Initialize a CaptureGroup object. - :param str dialog_node: (optional) A dialog node that was visited during - processing of the input message. - :param str title: (optional) The title of the dialog node. - :param str conditions: (optional) The conditions that trigger the dialog - node. + :param str group: A recognized capture group for the entity. + :param List[int] location: (optional) Zero-based character offsets that + indicate where the entity value begins and ends in the input text. """ - self.dialog_node = dialog_node - self.title = title - self.conditions = conditions + self.group = group + self.location = location @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodeVisited': - """Initialize a DialogNodeVisited object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CaptureGroup': + """Initialize a CaptureGroup object from a json dictionary.""" args = {} - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'conditions' in _dict: - args['conditions'] = _dict.get('conditions') + if 'group' in _dict: + args['group'] = _dict.get('group') + else: + raise ValueError( + 'Required property \'group\' not present in CaptureGroup JSON') + if 'location' in _dict: + args['location'] = _dict.get('location') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeVisited object from a json dictionary.""" + """Initialize a CaptureGroup 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, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'conditions') and self.conditions is not None: - _dict['conditions'] = self.conditions + if hasattr(self, 'group') and self.group is not None: + _dict['group'] = self.group + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location return _dict def _to_dict(self): @@ -1951,92 +2607,68 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeVisited object.""" + """Return a `str` version of this CaptureGroup object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodeVisited') -> bool: + def __eq__(self, other: 'CaptureGroup') -> 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: 'DialogNodeVisited') -> bool: + def __ne__(self, other: 'CaptureGroup') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogSuggestion(): +class ChannelTransferInfo(): """ - DialogSuggestion. + Information used by an integration to transfer the conversation to a different + channel. - :attr str label: The user-facing label for the suggestion. This label is taken - from the **title** or **user_label** property of the corresponding dialog node, - depending on the disambiguation options. - :attr DialogSuggestionValue value: An object defining the message input to be - sent to the assistant if the user selects the corresponding disambiguation - option. - :attr dict output: (optional) The dialog output that will be returned from the - Watson Assistant service if the user selects the corresponding option. + :attr ChannelTransferTarget target: An object specifying target channels + available for the transfer. Each property of this object represents an available + transfer target. Currently, the only supported property is **chat**, + representing the web chat integration. """ - def __init__(self, - label: str, - value: 'DialogSuggestionValue', - *, - output: dict = None) -> None: + def __init__(self, target: 'ChannelTransferTarget') -> None: """ - Initialize a DialogSuggestion object. + Initialize a ChannelTransferInfo object. - :param str label: The user-facing label for the suggestion. This label is - taken from the **title** or **user_label** property of the corresponding - dialog node, depending on the disambiguation options. - :param DialogSuggestionValue value: An object defining the message input to - be sent to the assistant if the user selects the corresponding - disambiguation option. - :param dict output: (optional) The dialog output that will be returned from - the Watson Assistant service if the user selects the corresponding option. + :param ChannelTransferTarget target: An object specifying target channels + available for the transfer. Each property of this object represents an + available transfer target. Currently, the only supported property is + **chat**, representing the web chat integration. """ - self.label = label - self.value = value - self.output = output + self.target = target @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': - """Initialize a DialogSuggestion object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': + """Initialize a ChannelTransferInfo object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - else: - raise ValueError( - 'Required property \'label\' not present in DialogSuggestion JSON' - ) - if 'value' in _dict: - args['value'] = DialogSuggestionValue.from_dict(_dict.get('value')) + if 'target' in _dict: + args['target'] = ChannelTransferTarget.from_dict( + _dict.get('target')) else: raise ValueError( - 'Required property \'value\' not present in DialogSuggestion JSON' + 'Required property \'target\' not present in ChannelTransferInfo JSON' ) - if 'output' in _dict: - args['output'] = _dict.get('output') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogSuggestion object from a json dictionary.""" + """Initialize a ChannelTransferInfo 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, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'value') and self.value is not None: - if isinstance(self.value, dict): - _dict['value'] = self.value + if hasattr(self, 'target') and self.target is not None: + if isinstance(self.target, dict): + _dict['target'] = self.target else: - _dict['value'] = self.value.to_dict() - if hasattr(self, 'output') and self.output is not None: - _dict['output'] = self.output + _dict['target'] = self.target.to_dict() return _dict def _to_dict(self): @@ -2044,59 +2676,61 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogSuggestion object.""" + """Return a `str` version of this ChannelTransferInfo object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogSuggestion') -> bool: + def __eq__(self, other: 'ChannelTransferInfo') -> 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: 'DialogSuggestion') -> bool: + def __ne__(self, other: 'ChannelTransferInfo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogSuggestionValue(): +class ChannelTransferTarget(): """ - An object defining the message input to be sent to the assistant if the user selects - the corresponding disambiguation option. + An object specifying target channels available for the transfer. Each property of this + object represents an available transfer target. Currently, the only supported property + is **chat**, representing the web chat integration. - :attr MessageInput input: (optional) An input object that includes the input - text. + :attr ChannelTransferTargetChat chat: (optional) Information for transferring to + the web chat integration. """ - def __init__(self, *, input: 'MessageInput' = None) -> None: + def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: """ - Initialize a DialogSuggestionValue object. + Initialize a ChannelTransferTarget object. - :param MessageInput input: (optional) An input object that includes the - input text. + :param ChannelTransferTargetChat chat: (optional) Information for + transferring to the web chat integration. """ - self.input = input + self.chat = chat @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': - """Initialize a DialogSuggestionValue object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': + """Initialize a ChannelTransferTarget object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if 'chat' in _dict: + args['chat'] = ChannelTransferTargetChat.from_dict( + _dict.get('chat')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogSuggestionValue object from a json dictionary.""" + """Initialize a ChannelTransferTarget 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, 'input') and self.input is not None: - if isinstance(self.input, dict): - _dict['input'] = self.input + if hasattr(self, 'chat') and self.chat is not None: + if isinstance(self.chat, dict): + _dict['chat'] = self.chat else: - _dict['input'] = self.input.to_dict() + _dict['chat'] = self.chat.to_dict() return _dict def _to_dict(self): @@ -2104,196 +2738,53 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogSuggestionValue object.""" + """Return a `str` version of this ChannelTransferTarget object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogSuggestionValue') -> bool: + def __eq__(self, other: 'ChannelTransferTarget') -> 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: 'DialogSuggestionValue') -> bool: + def __ne__(self, other: 'ChannelTransferTarget') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Environment(): +class ChannelTransferTargetChat(): """ - Environment. + Information for transferring to the web chat integration. - :attr str name: (optional) The name of the environment. - :attr str description: (optional) The description of the environment. - :attr str language: (optional) The language of the environment. An environment - is always created with the same language as the assistant it is associated with. - :attr str assistant_id: (optional) The assistant ID of the assistant the - environment is associated with. - :attr str environment_id: (optional) The environment ID of the environment. - :attr str environment: (optional) The type of the environment. All environments - other than the `draft` and `live` environments have the type `staging`. - :attr EnvironmentReleaseReference release_reference: (optional) An object - describing the release that is currently deployed in the environment. - :attr EnvironmentOrchestration orchestration: (optional) The search skill - orchestration settings for the environment. - :attr int session_timeout: (optional) The session inactivity timeout setting for - the environment. - :attr List[IntegrationReference] integration_references: (optional) An array of - objects describing the integrations that exist in the environment. - :attr List[SkillReference] skill_references: (optional) An array of objects - describing the skills (such as actions and dialog) that exist in the - environment. - :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. + :attr str url: (optional) The URL of the target web chat. """ - def __init__(self, - *, - name: str = None, - description: str = None, - language: str = None, - assistant_id: str = None, - environment_id: str = None, - environment: str = None, - release_reference: 'EnvironmentReleaseReference' = None, - orchestration: 'EnvironmentOrchestration' = None, - session_timeout: int = None, - integration_references: List['IntegrationReference'] = None, - skill_references: List['SkillReference'] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__(self, *, url: str = None) -> None: """ - Initialize a Environment object. + Initialize a ChannelTransferTargetChat object. - :param str name: (optional) The name of the environment. - :param str description: (optional) The description of the environment. - :param str language: (optional) The language of the environment. An - environment is always created with the same language as the assistant it is - associated with. - :param int session_timeout: (optional) The session inactivity timeout - setting for the environment. - :param List[IntegrationReference] integration_references: (optional) An - array of objects describing the integrations that exist in the environment. - :param List[SkillReference] skill_references: (optional) An array of - objects describing the skills (such as actions and dialog) that exist in - the environment. + :param str url: (optional) The URL of the target web chat. """ - self.name = name - self.description = description - self.language = language - self.assistant_id = assistant_id - self.environment_id = environment_id - self.environment = environment - self.release_reference = release_reference - self.orchestration = orchestration - self.session_timeout = session_timeout - self.integration_references = integration_references - self.skill_references = skill_references - self.created = created - self.updated = updated + self.url = url @classmethod - def from_dict(cls, _dict: Dict) -> 'Environment': - """Initialize a Environment object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': + """Initialize a ChannelTransferTargetChat object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'environment' in _dict: - args['environment'] = _dict.get('environment') - if 'release_reference' in _dict: - args['release_reference'] = EnvironmentReleaseReference.from_dict( - _dict.get('release_reference')) - if 'orchestration' in _dict: - args['orchestration'] = EnvironmentOrchestration.from_dict( - _dict.get('orchestration')) - if 'session_timeout' in _dict: - args['session_timeout'] = _dict.get('session_timeout') - if 'integration_references' in _dict: - args['integration_references'] = [ - IntegrationReference.from_dict(v) - for v in _dict.get('integration_references') - ] - if 'skill_references' in _dict: - args['skill_references'] = [ - SkillReference.from_dict(v) - for v in _dict.get('skill_references') - ] - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if 'url' in _dict: + args['url'] = _dict.get('url') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Environment object from a json dictionary.""" + """Initialize a ChannelTransferTargetChat 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'environment') and getattr(self, - 'environment') is not None: - _dict['environment'] = getattr(self, 'environment') - if hasattr(self, 'release_reference') and getattr( - self, 'release_reference') is not None: - if isinstance(getattr(self, 'release_reference'), dict): - _dict['release_reference'] = getattr(self, 'release_reference') - else: - _dict['release_reference'] = getattr( - self, 'release_reference').to_dict() - if hasattr(self, 'orchestration') and getattr( - self, 'orchestration') is not None: - if isinstance(getattr(self, 'orchestration'), dict): - _dict['orchestration'] = getattr(self, 'orchestration') - else: - _dict['orchestration'] = getattr(self, - 'orchestration').to_dict() - if hasattr(self, - 'session_timeout') and self.session_timeout is not None: - _dict['session_timeout'] = self.session_timeout - if hasattr(self, 'integration_references' - ) and self.integration_references is not None: - integration_references_list = [] - for v in self.integration_references: - if isinstance(v, dict): - integration_references_list.append(v) - else: - integration_references_list.append(v.to_dict()) - _dict['integration_references'] = integration_references_list - if hasattr(self, - 'skill_references') and self.skill_references is not None: - skill_references_list = [] - for v in self.skill_references: - if isinstance(v, dict): - skill_references_list.append(v) - else: - skill_references_list.append(v.to_dict()) - _dict['skill_references'] = skill_references_list - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url return _dict def _to_dict(self): @@ -2301,82 +2792,98 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Environment object.""" + """Return a `str` version of this ChannelTransferTargetChat object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Environment') -> bool: + def __eq__(self, other: 'ChannelTransferTargetChat') -> 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: 'Environment') -> bool: + def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class EnvironmentCollection(): +class DialogLogMessage(): """ - EnvironmentCollection. + Dialog log message details. - :attr List[Environment] environments: An array of objects describing the - environments associated with an assistant. - :attr Pagination pagination: The pagination data for the returned objects. + :attr str level: The severity of the log message. + :attr str message: The text of the log message. + :attr str code: A code that indicates the category to which the error message + belongs. + :attr LogMessageSource source: (optional) An object that identifies the dialog + element that generated the error message. """ - def __init__(self, environments: List['Environment'], - pagination: 'Pagination') -> None: + def __init__(self, + level: str, + message: str, + code: str, + *, + source: 'LogMessageSource' = None) -> None: """ - Initialize a EnvironmentCollection object. + Initialize a DialogLogMessage object. - :param List[Environment] environments: An array of objects describing the - environments associated with an assistant. - :param Pagination pagination: The pagination data for the returned objects. + :param str level: The severity of the log message. + :param str message: The text of the log message. + :param str code: A code that indicates the category to which the error + message belongs. + :param LogMessageSource source: (optional) An object that identifies the + dialog element that generated the error message. """ - self.environments = environments - self.pagination = pagination + self.level = level + self.message = message + self.code = code + self.source = source @classmethod - def from_dict(cls, _dict: Dict) -> 'EnvironmentCollection': - """Initialize a EnvironmentCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': + """Initialize a DialogLogMessage object from a json dictionary.""" args = {} - if 'environments' in _dict: - args['environments'] = [ - Environment.from_dict(v) for v in _dict.get('environments') - ] + if 'level' in _dict: + args['level'] = _dict.get('level') else: raise ValueError( - 'Required property \'environments\' not present in EnvironmentCollection JSON' + 'Required property \'level\' not present in DialogLogMessage JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if 'message' in _dict: + args['message'] = _dict.get('message') else: raise ValueError( - 'Required property \'pagination\' not present in EnvironmentCollection JSON' + 'Required property \'message\' not present in DialogLogMessage JSON' ) + if 'code' in _dict: + args['code'] = _dict.get('code') + else: + raise ValueError( + 'Required property \'code\' not present in DialogLogMessage JSON' + ) + if 'source' in _dict: + args['source'] = LogMessageSource.from_dict(_dict.get('source')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a EnvironmentCollection object from a json dictionary.""" + """Initialize a DialogLogMessage 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, 'environments') and self.environments is not None: - environments_list = [] - for v in self.environments: - if isinstance(v, dict): - environments_list.append(v) - else: - environments_list.append(v.to_dict()) - _dict['environments'] = environments_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination + if hasattr(self, 'level') and self.level is not None: + _dict['level'] = self.level + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source else: - _dict['pagination'] = self.pagination.to_dict() + _dict['source'] = self.source.to_dict() return _dict def _to_dict(self): @@ -2384,60 +2891,110 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this EnvironmentCollection object.""" + """Return a `str` version of this DialogLogMessage object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'EnvironmentCollection') -> bool: + def __eq__(self, other: 'DialogLogMessage') -> 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: 'EnvironmentCollection') -> bool: + def __ne__(self, other: 'DialogLogMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LevelEnum(str, Enum): + """ + The severity of the log message. + """ + INFO = 'info' + ERROR = 'error' + WARN = 'warn' + -class EnvironmentOrchestration(): +class DialogNodeAction(): """ - The search skill orchestration settings for the environment. + DialogNodeAction. - :attr bool search_skill_fallback: (optional) Whether assistants deployed to the - environment fall back to a search skill when responding to messages that do not - match any intent. If no search skill is configured for the assistant, this - property is ignored. + :attr str name: The name of the action. + :attr str type: (optional) The type of action to invoke. + :attr dict parameters: (optional) A map of key/value pairs to be provided to the + action. + :attr str result_variable: The location in the dialog context where the result + of the action is stored. + :attr str credentials: (optional) The name of the context variable that the + client application will use to pass in credentials for the action. """ - def __init__(self, *, search_skill_fallback: bool = None) -> None: + def __init__(self, + name: str, + result_variable: str, + *, + type: str = None, + parameters: dict = None, + credentials: str = None) -> None: """ - Initialize a EnvironmentOrchestration object. + Initialize a DialogNodeAction object. - :param bool search_skill_fallback: (optional) Whether assistants deployed - to the environment fall back to a search skill when responding to messages - that do not match any intent. If no search skill is configured for the - assistant, this property is ignored. + :param str name: The name of the action. + :param str result_variable: The location in the dialog context where the + result of the action is stored. + :param str type: (optional) The type of action to invoke. + :param dict parameters: (optional) A map of key/value pairs to be provided + to the action. + :param str credentials: (optional) The name of the context variable that + the client application will use to pass in credentials for the action. """ - self.search_skill_fallback = search_skill_fallback + self.name = name + self.type = type + self.parameters = parameters + self.result_variable = result_variable + self.credentials = credentials @classmethod - def from_dict(cls, _dict: Dict) -> 'EnvironmentOrchestration': - """Initialize a EnvironmentOrchestration object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': + """Initialize a DialogNodeAction object from a json dictionary.""" args = {} - if 'search_skill_fallback' in _dict: - args['search_skill_fallback'] = _dict.get('search_skill_fallback') + if 'name' in _dict: + args['name'] = _dict.get('name') + else: + raise ValueError( + 'Required property \'name\' not present in DialogNodeAction JSON' + ) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'parameters' in _dict: + args['parameters'] = _dict.get('parameters') + if 'result_variable' in _dict: + args['result_variable'] = _dict.get('result_variable') + else: + raise ValueError( + 'Required property \'result_variable\' not present in DialogNodeAction JSON' + ) + if 'credentials' in _dict: + args['credentials'] = _dict.get('credentials') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a EnvironmentOrchestration object from a json dictionary.""" + """Initialize a DialogNodeAction 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, 'search_skill_fallback' - ) and self.search_skill_fallback is not None: - _dict['search_skill_fallback'] = self.search_skill_fallback + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'parameters') and self.parameters is not None: + _dict['parameters'] = self.parameters + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable + if hasattr(self, 'credentials') and self.credentials is not None: + _dict['credentials'] = self.credentials return _dict def _to_dict(self): @@ -2445,73 +3002,63 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this EnvironmentOrchestration object.""" + """Return a `str` version of this DialogNodeAction object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'EnvironmentOrchestration') -> bool: + def __eq__(self, other: 'DialogNodeAction') -> 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: 'EnvironmentOrchestration') -> bool: + def __ne__(self, other: 'DialogNodeAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of action to invoke. + """ + CLIENT = 'client' + SERVER = 'server' + WEB_ACTION = 'web-action' + CLOUD_FUNCTION = 'cloud-function' + -class EnvironmentReference(): +class DialogNodeOutputConnectToAgentTransferInfo(): """ - EnvironmentReference. + Routing or other contextual information to be used by target service desk systems. - :attr str name: (optional) The name of the deployed environment. - :attr str environment_id: (optional) The environment ID of the deployed - environment. - :attr str environment: (optional) The type of the deployed environment. All - environments other than the draft and live environments have the type `staging`. + :attr dict target: (optional) """ - def __init__(self, - *, - name: str = None, - environment_id: str = None, - environment: str = None) -> None: + def __init__(self, *, target: dict = None) -> None: """ - Initialize a EnvironmentReference object. + Initialize a DialogNodeOutputConnectToAgentTransferInfo object. - :param str name: (optional) The name of the deployed environment. + :param dict target: (optional) """ - self.name = name - self.environment_id = environment_id - self.environment = environment + self.target = target @classmethod - def from_dict(cls, _dict: Dict) -> 'EnvironmentReference': - """Initialize a EnvironmentReference object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': + """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'environment' in _dict: - args['environment'] = _dict.get('environment') + if 'target' in _dict: + args['target'] = _dict.get('target') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a EnvironmentReference object from a json dictionary.""" + """Initialize a DialogNodeOutputConnectToAgentTransferInfo 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'environment') and getattr(self, - 'environment') is not None: - _dict['environment'] = getattr(self, 'environment') + if hasattr(self, 'target') and self.target is not None: + _dict['target'] = self.target return _dict def _to_dict(self): @@ -2519,62 +3066,78 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this EnvironmentReference object.""" + """Return a `str` version of this DialogNodeOutputConnectToAgentTransferInfo object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'EnvironmentReference') -> bool: + def __eq__(self, + other: 'DialogNodeOutputConnectToAgentTransferInfo') -> 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: 'EnvironmentReference') -> bool: + def __ne__(self, + other: 'DialogNodeOutputConnectToAgentTransferInfo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class EnvironmentEnum(str, Enum): - """ - The type of the deployed environment. All environments other than the draft and - live environments have the type `staging`. - """ - DRAFT = 'draft' - LIVE = 'live' - STAGING = 'staging' - -class EnvironmentReleaseReference(): +class DialogNodeOutputOptionsElement(): """ - An object describing the release that is currently deployed in the environment. + DialogNodeOutputOptionsElement. - :attr str release: (optional) The name of the deployed release. + :attr str label: The user-facing label for the option. + :attr DialogNodeOutputOptionsElementValue value: An object defining the message + input to be sent to the assistant if the user selects the corresponding option. """ - def __init__(self, *, release: str = None) -> None: + def __init__(self, label: str, + value: 'DialogNodeOutputOptionsElementValue') -> None: """ - Initialize a EnvironmentReleaseReference object. + Initialize a DialogNodeOutputOptionsElement object. - :param str release: (optional) The name of the deployed release. + :param str label: The user-facing label for the option. + :param DialogNodeOutputOptionsElementValue value: An object defining the + message input to be sent to the assistant if the user selects the + corresponding option. """ - self.release = release + self.label = label + self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'EnvironmentReleaseReference': - """Initialize a EnvironmentReleaseReference object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': + """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} - if 'release' in _dict: - args['release'] = _dict.get('release') + if 'label' in _dict: + args['label'] = _dict.get('label') + else: + raise ValueError( + 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' + ) + if 'value' in _dict: + args['value'] = DialogNodeOutputOptionsElementValue.from_dict( + _dict.get('value')) + else: + raise ValueError( + 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a EnvironmentReleaseReference object from a json dictionary.""" + """Initialize a DialogNodeOutputOptionsElement 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, 'release') and self.release is not None: - _dict['release'] = self.release + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'value') and self.value is not None: + if isinstance(self.value, dict): + _dict['value'] = self.value + else: + _dict['value'] = self.value.to_dict() return _dict def _to_dict(self): @@ -2582,61 +3145,59 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this EnvironmentReleaseReference object.""" + """Return a `str` version of this DialogNodeOutputOptionsElement object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'EnvironmentReleaseReference') -> bool: + def __eq__(self, other: 'DialogNodeOutputOptionsElement') -> 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: 'EnvironmentReleaseReference') -> bool: + def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class IntegrationReference(): +class DialogNodeOutputOptionsElementValue(): """ - IntegrationReference. + An object defining the message input to be sent to the assistant if the user selects + the corresponding option. - :attr str integration_id: (optional) The integration ID of the integration. - :attr str type: (optional) The type of the integration. + :attr MessageInput input: (optional) An input object that includes the input + text. """ - def __init__(self, *, integration_id: str = None, type: str = None) -> None: + def __init__(self, *, input: 'MessageInput' = None) -> None: """ - Initialize a IntegrationReference object. + Initialize a DialogNodeOutputOptionsElementValue object. - :param str integration_id: (optional) The integration ID of the - integration. - :param str type: (optional) The type of the integration. + :param MessageInput input: (optional) An input object that includes the + input text. """ - self.integration_id = integration_id - self.type = type + self.input = input @classmethod - def from_dict(cls, _dict: Dict) -> 'IntegrationReference': - """Initialize a IntegrationReference object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': + """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} - if 'integration_id' in _dict: - args['integration_id'] = _dict.get('integration_id') - if 'type' in _dict: - args['type'] = _dict.get('type') + if 'input' in _dict: + args['input'] = MessageInput.from_dict(_dict.get('input')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a IntegrationReference object from a json dictionary.""" + """Initialize a DialogNodeOutputOptionsElementValue 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, 'integration_id') and self.integration_id is not None: - _dict['integration_id'] = self.integration_id - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() return _dict def _to_dict(self): @@ -2644,189 +3205,75 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this IntegrationReference object.""" + """Return a `str` version of this DialogNodeOutputOptionsElementValue object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'IntegrationReference') -> bool: + def __eq__(self, other: 'DialogNodeOutputOptionsElementValue') -> 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: 'IntegrationReference') -> bool: + def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Log(): +class DialogNodeVisited(): """ - Log. + An objects containing detailed diagnostic information about a dialog node that was + visited during processing of the input message. - :attr str log_id: A unique identifier for the logged event. - :attr MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :attr MessageResponse response: A response from the Watson Assistant service. - :attr str assistant_id: Unique identifier of the assistant. - :attr str session_id: The ID of the session the message was part of. - :attr str skill_id: The unique identifier of the skill that responded to the - message. - :attr str snapshot: The name of the snapshot (dialog skill version) that - responded to the message (for example, `draft`). - :attr str request_timestamp: The timestamp for receipt of the message. - :attr str response_timestamp: The timestamp for the system response to the - message. - :attr str language: The language of the assistant to which the message request - was made. - :attr str customer_id: (optional) The customer ID specified for the message, if - any. + :attr str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :attr str title: (optional) The title of the dialog node. + :attr str conditions: (optional) The conditions that trigger the dialog node. """ def __init__(self, - log_id: str, - request: 'MessageRequest', - response: 'MessageResponse', - assistant_id: str, - session_id: str, - skill_id: str, - snapshot: str, - request_timestamp: str, - response_timestamp: str, - language: str, *, - customer_id: str = None) -> None: + dialog_node: str = None, + title: str = None, + conditions: str = None) -> None: """ - Initialize a Log object. + Initialize a DialogNodeVisited object. - :param str log_id: A unique identifier for the logged event. - :param MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :param MessageResponse response: A response from the Watson Assistant - service. - :param str assistant_id: Unique identifier of the assistant. - :param str session_id: The ID of the session the message was part of. - :param str skill_id: The unique identifier of the skill that responded to - the message. - :param str snapshot: The name of the snapshot (dialog skill version) that - responded to the message (for example, `draft`). - :param str request_timestamp: The timestamp for receipt of the message. - :param str response_timestamp: The timestamp for the system response to the - message. - :param str language: The language of the assistant to which the message - request was made. - :param str customer_id: (optional) The customer ID specified for the - message, if any. + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str conditions: (optional) The conditions that trigger the dialog + node. """ - self.log_id = log_id - self.request = request - self.response = response - self.assistant_id = assistant_id - self.session_id = session_id - self.skill_id = skill_id - self.snapshot = snapshot - self.request_timestamp = request_timestamp - self.response_timestamp = response_timestamp - self.language = language - self.customer_id = customer_id + self.dialog_node = dialog_node + self.title = title + self.conditions = conditions @classmethod - def from_dict(cls, _dict: Dict) -> 'Log': - """Initialize a Log object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogNodeVisited': + """Initialize a DialogNodeVisited object from a json dictionary.""" args = {} - if 'log_id' in _dict: - args['log_id'] = _dict.get('log_id') - else: - raise ValueError( - 'Required property \'log_id\' not present in Log JSON') - if 'request' in _dict: - args['request'] = MessageRequest.from_dict(_dict.get('request')) - else: - raise ValueError( - 'Required property \'request\' not present in Log JSON') - if 'response' in _dict: - args['response'] = MessageResponse.from_dict(_dict.get('response')) - else: - raise ValueError( - 'Required property \'response\' not present in Log JSON') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - else: - raise ValueError( - 'Required property \'assistant_id\' not present in Log JSON') - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') - else: - raise ValueError( - 'Required property \'session_id\' not present in Log JSON') - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') - else: - raise ValueError( - 'Required property \'skill_id\' not present in Log JSON') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') - else: - raise ValueError( - 'Required property \'snapshot\' not present in Log JSON') - if 'request_timestamp' in _dict: - args['request_timestamp'] = _dict.get('request_timestamp') - else: - raise ValueError( - 'Required property \'request_timestamp\' not present in Log JSON' - ) - if 'response_timestamp' in _dict: - args['response_timestamp'] = _dict.get('response_timestamp') - else: - raise ValueError( - 'Required property \'response_timestamp\' not present in Log JSON' - ) - if 'language' in _dict: - args['language'] = _dict.get('language') - else: - raise ValueError( - 'Required property \'language\' not present in Log JSON') - if 'customer_id' in _dict: - args['customer_id'] = _dict.get('customer_id') + if 'dialog_node' in _dict: + args['dialog_node'] = _dict.get('dialog_node') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'conditions' in _dict: + args['conditions'] = _dict.get('conditions') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Log object from a json dictionary.""" + """Initialize a DialogNodeVisited 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, 'log_id') and self.log_id is not None: - _dict['log_id'] = self.log_id - if hasattr(self, 'request') and self.request is not None: - if isinstance(self.request, dict): - _dict['request'] = self.request - else: - _dict['request'] = self.request.to_dict() - if hasattr(self, 'response') and self.response is not None: - if isinstance(self.response, dict): - _dict['response'] = self.response - else: - _dict['response'] = self.response.to_dict() - if hasattr(self, 'assistant_id') and self.assistant_id is not None: - _dict['assistant_id'] = self.assistant_id - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id - if hasattr(self, 'skill_id') and self.skill_id is not None: - _dict['skill_id'] = self.skill_id - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot - if hasattr(self, - 'request_timestamp') and self.request_timestamp is not None: - _dict['request_timestamp'] = self.request_timestamp - if hasattr( - self, - 'response_timestamp') and self.response_timestamp is not None: - _dict['response_timestamp'] = self.response_timestamp - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'customer_id') and self.customer_id is not None: - _dict['customer_id'] = self.customer_id + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'conditions') and self.conditions is not None: + _dict['conditions'] = self.conditions return _dict def _to_dict(self): @@ -2834,78 +3281,98 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Log object.""" + """Return a `str` version of this DialogNodeVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Log') -> bool: + def __eq__(self, other: 'DialogNodeVisited') -> 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: 'Log') -> bool: + def __ne__(self, other: 'DialogNodeVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogCollection(): +class DialogSuggestion(): """ - LogCollection. + DialogSuggestion. - :attr List[Log] logs: An array of objects describing log events. - :attr LogPagination pagination: The pagination data for the returned objects. + :attr str label: The user-facing label for the suggestion. This label is taken + from the **title** or **user_label** property of the corresponding dialog node, + depending on the disambiguation options. + :attr DialogSuggestionValue value: An object defining the message input to be + sent to the assistant if the user selects the corresponding disambiguation + option. + **Note:** This entire message input object must be included in the request body + of the next message sent to the assistant. Do not modify or remove any of the + included properties. + :attr dict output: (optional) The dialog output that will be returned from the + Watson Assistant service if the user selects the corresponding option. """ - def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: + def __init__(self, + label: str, + value: 'DialogSuggestionValue', + *, + output: dict = None) -> None: """ - Initialize a LogCollection object. + Initialize a DialogSuggestion object. - :param List[Log] logs: An array of objects describing log events. - :param LogPagination pagination: The pagination data for the returned - objects. + :param str label: The user-facing label for the suggestion. This label is + taken from the **title** or **user_label** property of the corresponding + dialog node, depending on the disambiguation options. + :param DialogSuggestionValue value: An object defining the message input to + be sent to the assistant if the user selects the corresponding + disambiguation option. + **Note:** This entire message input object must be included in the request + body of the next message sent to the assistant. Do not modify or remove any + of the included properties. + :param dict output: (optional) The dialog output that will be returned from + the Watson Assistant service if the user selects the corresponding option. """ - self.logs = logs - self.pagination = pagination + self.label = label + self.value = value + self.output = output @classmethod - def from_dict(cls, _dict: Dict) -> 'LogCollection': - """Initialize a LogCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': + """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - if 'logs' in _dict: - args['logs'] = [Log.from_dict(v) for v in _dict.get('logs')] + if 'label' in _dict: + args['label'] = _dict.get('label') else: raise ValueError( - 'Required property \'logs\' not present in LogCollection JSON') - if 'pagination' in _dict: - args['pagination'] = LogPagination.from_dict( - _dict.get('pagination')) + 'Required property \'label\' not present in DialogSuggestion JSON' + ) + if 'value' in _dict: + args['value'] = DialogSuggestionValue.from_dict(_dict.get('value')) else: raise ValueError( - 'Required property \'pagination\' not present in LogCollection JSON' + 'Required property \'value\' not present in DialogSuggestion JSON' ) + if 'output' in _dict: + args['output'] = _dict.get('output') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogCollection object from a json dictionary.""" + """Initialize a DialogSuggestion 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, 'logs') and self.logs is not None: - logs_list = [] - for v in self.logs: - if isinstance(v, dict): - logs_list.append(v) - else: - logs_list.append(v.to_dict()) - _dict['logs'] = logs_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination + if hasattr(self, 'label') and self.label is not None: + _dict['label'] = self.label + if hasattr(self, 'value') and self.value is not None: + if isinstance(self.value, dict): + _dict['value'] = self.value else: - _dict['pagination'] = self.pagination.to_dict() + _dict['value'] = self.value.to_dict() + if hasattr(self, 'output') and self.output is not None: + _dict['output'] = self.output return _dict def _to_dict(self): @@ -2913,134 +3380,62 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogCollection object.""" + """Return a `str` version of this DialogSuggestion object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogCollection') -> bool: + def __eq__(self, other: 'DialogSuggestion') -> 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: 'LogCollection') -> bool: + def __ne__(self, other: 'DialogSuggestion') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSource(): +class DialogSuggestionValue(): """ - An object that identifies the dialog element that generated the error message. + An object defining the message input to be sent to the assistant if the user selects + the corresponding disambiguation option. + **Note:** This entire message input object must be included in the request body of + the next message sent to the assistant. Do not modify or remove any of the included + properties. + :attr MessageInput input: (optional) An input object that includes the input + text. """ - def __init__(self) -> None: + def __init__(self, *, input: 'MessageInput' = None) -> None: """ - Initialize a LogMessageSource object. + Initialize a DialogSuggestionValue object. + :param MessageInput input: (optional) An input object that includes the + input text. """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) - raise Exception(msg) + self.input = input @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSource': - """Initialize a LogMessageSource object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'LogMessageSource'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a LogMessageSource object from a json dictionary.""" - return cls.from_dict(_dict) - - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['dialog_node'] = 'LogMessageSourceDialogNode' - mapping['action'] = 'LogMessageSourceAction' - mapping['step'] = 'LogMessageSourceStep' - mapping['handler'] = 'LogMessageSourceHandler' - disc_value = _dict.get('type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'type\' not found in LogMessageSource JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - - -class LogPagination(): - """ - The pagination data for the returned objects. - - :attr str next_url: (optional) The URL that will return the next page of - results, if any. - :attr int matched: (optional) Reserved for future use. - :attr str next_cursor: (optional) A token identifying the next page of results. - """ - - def __init__(self, - *, - next_url: str = None, - matched: int = None, - next_cursor: str = None) -> None: - """ - Initialize a LogPagination object. - - :param str next_url: (optional) The URL that will return the next page of - results, if any. - :param int matched: (optional) Reserved for future use. - :param str next_cursor: (optional) A token identifying the next page of - results. - """ - self.next_url = next_url - self.matched = matched - self.next_cursor = next_cursor - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogPagination': - """Initialize a LogPagination object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': + """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if 'input' in _dict: + args['input'] = MessageInput.from_dict(_dict.get('input')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogPagination object from a json dictionary.""" + """Initialize a DialogSuggestionValue 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, 'next_url') and self.next_url is not None: - _dict['next_url'] = self.next_url - if hasattr(self, 'matched') and self.matched is not None: - _dict['matched'] = self.matched - if hasattr(self, 'next_cursor') and self.next_cursor is not None: - _dict['next_cursor'] = self.next_cursor + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() return _dict def _to_dict(self): @@ -3048,162 +3443,276 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogPagination object.""" + """Return a `str` version of this DialogSuggestionValue object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogPagination') -> bool: + def __eq__(self, other: 'DialogSuggestionValue') -> 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: 'LogPagination') -> bool: + def __ne__(self, other: 'DialogSuggestionValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContext(): +class Environment(): """ - MessageContext. + Environment. - :attr MessageContextGlobal global_: (optional) Session context data that is - shared by all skills used by the assistant. - :attr dict skills: (optional) Information specific to particular skills used by - the assistant. - :attr dict integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :attr str name: (optional) The name of the environment. + :attr str description: (optional) The description of the environment. + :attr str assistant_id: (optional) The assistant ID of the assistant the + environment is associated with. + :attr str environment_id: (optional) The environment ID of the environment. + :attr str environment: (optional) The type of the environment. All environments + other than the `draft` and `live` environments have the type `staging`. + :attr BaseEnvironmentReleaseReference release_reference: (optional) An object + describing the release that is currently deployed in the environment. + :attr BaseEnvironmentOrchestration orchestration: (optional) The search skill + orchestration settings for the environment. + :attr int session_timeout: The session inactivity timeout setting for the + environment (in seconds). + :attr List[IntegrationReference] integration_references: (optional) An array of + objects describing the integrations that exist in the environment. + :attr List[EnvironmentSkill] skill_references: An array of objects identifying + the skills (such as action and dialog) that exist in the environment. + :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. """ def __init__(self, + session_timeout: int, + skill_references: List['EnvironmentSkill'], *, - global_: 'MessageContextGlobal' = None, - skills: dict = None, - integrations: dict = None) -> None: + name: str = None, + description: str = None, + assistant_id: str = None, + environment_id: str = None, + environment: str = None, + release_reference: 'BaseEnvironmentReleaseReference' = None, + orchestration: 'BaseEnvironmentOrchestration' = None, + integration_references: List['IntegrationReference'] = None, + created: datetime = None, + updated: datetime = None) -> None: """ - Initialize a MessageContext object. + Initialize a Environment object. - :param MessageContextGlobal global_: (optional) Session context data that - is shared by all skills used by the assistant. - :param dict skills: (optional) Information specific to particular skills - used by the assistant. - :param dict integrations: (optional) An object containing context data that - is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param int session_timeout: The session inactivity timeout setting for the + environment (in seconds). + :param List[EnvironmentSkill] skill_references: An array of objects + identifying the skills (such as action and dialog) that exist in the + environment. + :param str name: (optional) The name of the environment. + :param str description: (optional) The description of the environment. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.name = name + self.description = description + self.assistant_id = assistant_id + self.environment_id = environment_id + self.environment = environment + self.release_reference = release_reference + self.orchestration = orchestration + self.session_timeout = session_timeout + self.integration_references = integration_references + self.skill_references = skill_references + self.created = created + self.updated = updated @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContext': - """Initialize a MessageContext object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Environment': + """Initialize a Environment object from a json dictionary.""" args = {} - if 'global' in _dict: - args['global_'] = MessageContextGlobal.from_dict( - _dict.get('global')) - if 'skills' in _dict: - args['skills'] = { - k: MessageContextSkill.from_dict(v) - for k, v in _dict.get('skills').items() - } - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + if 'environment_id' in _dict: + args['environment_id'] = _dict.get('environment_id') + if 'environment' in _dict: + args['environment'] = _dict.get('environment') + if 'release_reference' in _dict: + args[ + 'release_reference'] = BaseEnvironmentReleaseReference.from_dict( + _dict.get('release_reference')) + if 'orchestration' in _dict: + args['orchestration'] = BaseEnvironmentOrchestration.from_dict( + _dict.get('orchestration')) + if 'session_timeout' in _dict: + args['session_timeout'] = _dict.get('session_timeout') + else: + raise ValueError( + 'Required property \'session_timeout\' not present in Environment JSON' + ) + if 'integration_references' in _dict: + args['integration_references'] = [ + IntegrationReference.from_dict(v) + for v in _dict.get('integration_references') + ] + if 'skill_references' in _dict: + args['skill_references'] = [ + EnvironmentSkill.from_dict(v) + for v in _dict.get('skill_references') + ] + else: + raise ValueError( + 'Required property \'skill_references\' not present in Environment JSON' + ) + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContext object from a json dictionary.""" + """Initialize a Environment 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, 'global_') and self.global_ is not None: - if isinstance(self.global_, dict): - _dict['global'] = self.global_ + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'environment') and getattr(self, + 'environment') is not None: + _dict['environment'] = getattr(self, 'environment') + if hasattr(self, 'release_reference') and getattr( + self, 'release_reference') is not None: + if isinstance(getattr(self, 'release_reference'), dict): + _dict['release_reference'] = getattr(self, 'release_reference') else: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - skills_map = {} - for k, v in self.skills.items(): + _dict['release_reference'] = getattr( + self, 'release_reference').to_dict() + if hasattr(self, 'orchestration') and getattr( + self, 'orchestration') is not None: + if isinstance(getattr(self, 'orchestration'), dict): + _dict['orchestration'] = getattr(self, 'orchestration') + else: + _dict['orchestration'] = getattr(self, + 'orchestration').to_dict() + if hasattr(self, + 'session_timeout') and self.session_timeout is not None: + _dict['session_timeout'] = self.session_timeout + if hasattr(self, 'integration_references') and getattr( + self, 'integration_references') is not None: + integration_references_list = [] + for v in getattr(self, 'integration_references'): if isinstance(v, dict): - skills_map[k] = v + integration_references_list.append(v) else: - skills_map[k] = v.to_dict() - _dict['skills'] = skills_map - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations - 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 MessageContext object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MessageContext') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False + integration_references_list.append(v.to_dict()) + _dict['integration_references'] = integration_references_list + if hasattr(self, + 'skill_references') and self.skill_references is not None: + skill_references_list = [] + for v in self.skill_references: + if isinstance(v, dict): + skill_references_list.append(v) + else: + skill_references_list.append(v.to_dict()) + _dict['skill_references'] = skill_references_list + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + 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 Environment object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Environment') -> 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: 'MessageContext') -> bool: + def __ne__(self, other: 'Environment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobal(): +class EnvironmentCollection(): """ - Session context data that is shared by all skills used by the assistant. + EnvironmentCollection. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :attr str session_id: (optional) The session ID. + :attr List[Environment] environments: An array of objects describing the + environments associated with an assistant. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, - *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: + def __init__(self, environments: List['Environment'], + pagination: 'Pagination') -> None: """ - Initialize a MessageContextGlobal object. + Initialize a EnvironmentCollection object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. + :param List[Environment] environments: An array of objects describing the + environments associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - self.system = system - self.session_id = session_id + self.environments = environments + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': - """Initialize a MessageContextGlobal object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'EnvironmentCollection': + """Initialize a EnvironmentCollection object from a json dictionary.""" args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if 'environments' in _dict: + args['environments'] = [ + Environment.from_dict(v) for v in _dict.get('environments') + ] + else: + raise ValueError( + 'Required property \'environments\' not present in EnvironmentCollection JSON' + ) + if 'pagination' in _dict: + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in EnvironmentCollection JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobal object from a json dictionary.""" + """Initialize a EnvironmentCollection 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, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system + if hasattr(self, 'environments') and self.environments is not None: + environments_list = [] + for v in self.environments: + if isinstance(v, dict): + environments_list.append(v) + else: + environments_list.append(v.to_dict()) + _dict['environments'] = environments_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination else: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and getattr(self, - 'session_id') is not None: - _dict['session_id'] = getattr(self, 'session_id') + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -3211,69 +3720,72 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobal object.""" + """Return a `str` version of this EnvironmentCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobal') -> bool: + def __eq__(self, other: 'EnvironmentCollection') -> 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: 'MessageContextGlobal') -> bool: + def __ne__(self, other: 'EnvironmentCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobalStateless(): +class EnvironmentReference(): """ - Session context data that is shared by all skills used by the assistant. + EnvironmentReference. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :attr str session_id: (optional) The unique identifier of the session. + :attr str name: (optional) The name of the environment. + :attr str environment_id: (optional) The unique identifier of the environment. + :attr str environment: (optional) The type of the environment. All environments + other than the draft and live environments have the type `staging`. """ def __init__(self, *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: + name: str = None, + environment_id: str = None, + environment: str = None) -> None: """ - Initialize a MessageContextGlobalStateless object. + Initialize a EnvironmentReference object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param str name: (optional) The name of the environment. """ - self.system = system - self.session_id = session_id + self.name = name + self.environment_id = environment_id + self.environment = environment @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'EnvironmentReference': + """Initialize a EnvironmentReference object from a json dictionary.""" args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'environment_id' in _dict: + args['environment_id'] = _dict.get('environment_id') + if 'environment' in _dict: + args['environment'] = _dict.get('environment') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + """Initialize a EnvironmentReference 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, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system - else: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'environment') and getattr(self, + 'environment') is not None: + _dict['environment'] = getattr(self, 'environment') return _dict def _to_dict(self): @@ -3281,194 +3793,111 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalStateless object.""" + """Return a `str` version of this EnvironmentReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalStateless') -> bool: + def __eq__(self, other: 'EnvironmentReference') -> 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: 'MessageContextGlobalStateless') -> bool: + def __ne__(self, other: 'EnvironmentReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class EnvironmentEnum(str, Enum): + """ + The type of the environment. All environments other than the draft and live + environments have the type `staging`. + """ + DRAFT = 'draft' + LIVE = 'live' + STAGING = 'staging' + -class MessageContextGlobalSystem(): +class EnvironmentSkill(): """ - Built-in system properties that apply to all skills used by the assistant. + EnvironmentSkill. - :attr str timezone: (optional) The user time zone. The assistant uses the time - zone to correctly resolve relative time references. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root of - the message body. If **user_id** is specified in both locations in a message - request, the value specified at the root is used. - :attr int turn_count: (optional) A counter that is automatically incremented - 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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for the - skill. - :attr str session_start_time: (optional) The time at which the session started. - With the stateful `message` method, the start time is always present, and is set - by the service based on the time the session was created. With the stateless - `message` method, the start time is set by the service in the response to the - first message, and should be returned as part of the context with each - subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for example, - `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :attr str state: (optional) An encoded string that represents the configuration - state of the assistant at the beginning of the conversation. If you are using - the stateless `message` method, save this value and then send it in the context - of the subsequent message request to avoid disruptions if there are - configuration changes during the conversation (such as a change to a skill the - assistant uses). - :attr bool skip_user_input: (optional) For internal use only. + :attr str skill_id: The skill ID of the skill. + :attr str type: (optional) The type of the skill. + :attr bool disabled: (optional) Whether the skill is disabled. A disabled skill + in the draft environment does not handle any messages at run time, and it is not + included in saved releases. + :attr str snapshot: (optional) The name of the skill snapshot that is deployed + to the environment (for example, `draft` or `1`). + :attr str skill_reference: (optional) The type of skill identified by the skill + reference. The possible values are `main skill` (for a dialog skill), `actions + skill`, and `search skill`. """ def __init__(self, + skill_id: str, *, - timezone: str = None, - user_id: str = None, - turn_count: int = None, - locale: str = None, - reference_time: str = None, - session_start_time: str = None, - state: str = None, - skip_user_input: bool = None) -> None: + type: str = None, + disabled: bool = None, + snapshot: str = None, + skill_reference: str = None) -> None: """ - Initialize a MessageContextGlobalSystem object. + Initialize a EnvironmentSkill object. - :param str timezone: (optional) The user time zone. The assistant uses the - time zone to correctly resolve relative time references. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root - of the message body. If **user_id** is specified in both locations in a - message request, the value specified at the root is used. - :param int turn_count: (optional) A counter that is automatically - incremented 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). - :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for - the skill. - :param str session_start_time: (optional) The time at which the session - started. With the stateful `message` method, the start time is always - present, and is set by the service based on the time the session was - created. With the stateless `message` method, the start time is set by the - service in the response to the first message, and should be returned as - part of the context with each subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :param str state: (optional) An encoded string that represents the - configuration state of the assistant at the beginning of the conversation. - If you are using the stateless `message` method, save this value and then - send it in the context of the subsequent message request to avoid - disruptions if there are configuration changes during the conversation - (such as a change to a skill the assistant uses). - :param bool skip_user_input: (optional) For internal use only. + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param bool disabled: (optional) Whether the skill is disabled. A disabled + skill in the draft environment does not handle any messages at run time, + and it is not included in saved releases. + :param str snapshot: (optional) The name of the skill snapshot that is + deployed to the environment (for example, `draft` or `1`). + :param str skill_reference: (optional) The type of skill identified by the + skill reference. The possible values are `main skill` (for a dialog skill), + `actions skill`, and `search skill`. """ - self.timezone = timezone - self.user_id = user_id - self.turn_count = turn_count - self.locale = locale - self.reference_time = reference_time - self.session_start_time = session_start_time - self.state = state - self.skip_user_input = skip_user_input + self.skill_id = skill_id + self.type = type + self.disabled = disabled + self.snapshot = snapshot + self.skill_reference = skill_reference @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'EnvironmentSkill': + """Initialize a EnvironmentSkill object from a json dictionary.""" args = {} - if 'timezone' in _dict: - args['timezone'] = _dict.get('timezone') - if 'user_id' in _dict: - 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') - if 'session_start_time' in _dict: - args['session_start_time'] = _dict.get('session_start_time') - if 'state' in _dict: - args['state'] = _dict.get('state') - if 'skip_user_input' in _dict: - args['skip_user_input'] = _dict.get('skip_user_input') + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + else: + raise ValueError( + 'Required property \'skill_id\' not present in EnvironmentSkill JSON' + ) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'disabled' in _dict: + args['disabled'] = _dict.get('disabled') + if 'snapshot' in _dict: + args['snapshot'] = _dict.get('snapshot') + if 'skill_reference' in _dict: + args['skill_reference'] = _dict.get('skill_reference') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + """Initialize a EnvironmentSkill 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, 'timezone') and self.timezone is not None: - _dict['timezone'] = self.timezone - if hasattr(self, 'user_id') and self.user_id is not None: - _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 - if hasattr( - self, - 'session_start_time') and self.session_start_time is not None: - _dict['session_start_time'] = self.session_start_time - if hasattr(self, 'state') and self.state is not None: - _dict['state'] = self.state + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'disabled') and self.disabled is not None: + _dict['disabled'] = self.disabled + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot if hasattr(self, - 'skip_user_input') and self.skip_user_input is not None: - _dict['skip_user_input'] = self.skip_user_input + 'skill_reference') and self.skill_reference is not None: + _dict['skill_reference'] = self.skill_reference return _dict def _to_dict(self): @@ -3476,99 +3905,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalSystem object.""" + """Return a `str` version of this EnvironmentSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalSystem') -> bool: + def __eq__(self, other: 'EnvironmentSkill') -> 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: 'MessageContextGlobalSystem') -> bool: + def __ne__(self, other: 'EnvironmentSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LocaleEnum(str, Enum): + class TypeEnum(str, 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. + The type of 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' + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' -class MessageContextSkill(): +class IntegrationReference(): """ - Contains information specific to a particular skill used by the assistant. The - property name must be the same as the name of the skill. - **Note:** The default skill names are `main skill` for the dialog skill (if enabled), - and `actions skill` for the actions skill. + IntegrationReference. - :attr dict user_defined: (optional) Arbitrary variables that can be read and - written by a particular skill. - :attr MessageContextSkillSystem system: (optional) System context data used by - the skill. + :attr str integration_id: (optional) The integration ID of the integration. + :attr str type: (optional) The type of the integration. """ - def __init__(self, - *, - user_defined: dict = None, - system: 'MessageContextSkillSystem' = None) -> None: + def __init__(self, *, integration_id: str = None, type: str = None) -> None: """ - Initialize a MessageContextSkill object. + Initialize a IntegrationReference object. - :param dict user_defined: (optional) Arbitrary variables that can be read - and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data - used by the skill. + :param str integration_id: (optional) The integration ID of the + integration. + :param str type: (optional) The type of the integration. """ - self.user_defined = user_defined - self.system = system + self.integration_id = integration_id + self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': - """Initialize a MessageContextSkill object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'IntegrationReference': + """Initialize a IntegrationReference object from a json dictionary.""" args = {} - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'system' in _dict: - args['system'] = MessageContextSkillSystem.from_dict( - _dict.get('system')) + if 'integration_id' in _dict: + args['integration_id'] = _dict.get('integration_id') + if 'type' in _dict: + args['type'] = _dict.get('type') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkill object from a json dictionary.""" + """Initialize a IntegrationReference 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, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system - else: - _dict['system'] = self.system.to_dict() + if hasattr(self, 'integration_id') and self.integration_id is not None: + _dict['integration_id'] = self.integration_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -3576,190 +3975,270 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextSkill object.""" + """Return a `str` version of this IntegrationReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkill') -> bool: + def __eq__(self, other: 'IntegrationReference') -> 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: 'MessageContextSkill') -> bool: + def __ne__(self, other: 'IntegrationReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextSkillSystem(): +class Log(): """ - System context data used by the skill. + Log. - :attr str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context of a - subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. + :attr str log_id: A unique identifier for the logged event. + :attr MessageRequest request: A stateful message request formatted for the + Watson Assistant service. + :attr MessageResponse response: A response from the Watson Assistant service. + :attr str assistant_id: Unique identifier of the assistant. + :attr str session_id: The ID of the session the message was part of. + :attr str skill_id: The unique identifier of the skill that responded to the + message. + :attr str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :attr str request_timestamp: The timestamp for receipt of the message. + :attr str response_timestamp: The timestamp for the system response to the + message. + :attr str language: The language of the assistant to which the message request + was made. + :attr str customer_id: (optional) The customer ID specified for the message, if + any. """ - # The set of defined properties for the class - _properties = frozenset(['state']) - - def __init__(self, *, state: str = None, **kwargs) -> None: + def __init__(self, + log_id: str, + request: 'MessageRequest', + response: 'MessageResponse', + assistant_id: str, + session_id: str, + skill_id: str, + snapshot: str, + request_timestamp: str, + response_timestamp: str, + language: str, + *, + customer_id: str = None) -> None: """ - Initialize a MessageContextSkillSystem object. + Initialize a Log object. - :param str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context - of a subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. - :param **kwargs: (optional) Any additional properties. + :param str log_id: A unique identifier for the logged event. + :param MessageRequest request: A stateful message request formatted for the + Watson Assistant service. + :param MessageResponse response: A response from the Watson Assistant + service. + :param str assistant_id: Unique identifier of the assistant. + :param str session_id: The ID of the session the message was part of. + :param str skill_id: The unique identifier of the skill that responded to + the message. + :param str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the + message. + :param str language: The language of the assistant to which the message + request was made. + :param str customer_id: (optional) The customer ID specified for the + message, if any. """ - self.state = state - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.log_id = log_id + self.request = request + self.response = response + self.assistant_id = assistant_id + self.session_id = session_id + self.skill_id = skill_id + self.snapshot = snapshot + self.request_timestamp = request_timestamp + self.response_timestamp = response_timestamp + self.language = language + self.customer_id = customer_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Log': + """Initialize a Log object from a json dictionary.""" args = {} - if 'state' in _dict: - args['state'] = _dict.get('state') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if 'log_id' in _dict: + args['log_id'] = _dict.get('log_id') + else: + raise ValueError( + 'Required property \'log_id\' not present in Log JSON') + if 'request' in _dict: + args['request'] = MessageRequest.from_dict(_dict.get('request')) + else: + raise ValueError( + 'Required property \'request\' not present in Log JSON') + if 'response' in _dict: + args['response'] = MessageResponse.from_dict(_dict.get('response')) + else: + raise ValueError( + 'Required property \'response\' not present in Log JSON') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + else: + raise ValueError( + 'Required property \'assistant_id\' not present in Log JSON') + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') + else: + raise ValueError( + 'Required property \'session_id\' not present in Log JSON') + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + else: + raise ValueError( + 'Required property \'skill_id\' not present in Log JSON') + if 'snapshot' in _dict: + args['snapshot'] = _dict.get('snapshot') + else: + raise ValueError( + 'Required property \'snapshot\' not present in Log JSON') + if 'request_timestamp' in _dict: + args['request_timestamp'] = _dict.get('request_timestamp') + else: + raise ValueError( + 'Required property \'request_timestamp\' not present in Log JSON' + ) + if 'response_timestamp' in _dict: + args['response_timestamp'] = _dict.get('response_timestamp') + else: + raise ValueError( + 'Required property \'response_timestamp\' not present in Log JSON' + ) + if 'language' in _dict: + args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in Log JSON') + if 'customer_id' in _dict: + args['customer_id'] = _dict.get('customer_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + """Initialize a Log 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, 'state') and self.state is not None: - _dict['state'] = self.state - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'log_id') and self.log_id is not None: + _dict['log_id'] = self.log_id + if hasattr(self, 'request') and self.request is not None: + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() + if hasattr(self, 'assistant_id') and self.assistant_id is not None: + _dict['assistant_id'] = self.assistant_id + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + if hasattr(self, + 'request_timestamp') and self.request_timestamp is not None: + _dict['request_timestamp'] = self.request_timestamp + if hasattr( + self, + 'response_timestamp') and self.response_timestamp is not None: + _dict['response_timestamp'] = self.response_timestamp + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'customer_id') and self.customer_id is not None: + _dict['customer_id'] = self.customer_id return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in MessageContextSkillSystem._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillSystem object.""" + """Return a `str` version of this Log object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkillSystem') -> bool: + def __eq__(self, other: 'Log') -> 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: 'MessageContextSkillSystem') -> bool: + def __ne__(self, other: 'Log') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextStateless(): +class LogCollection(): """ - MessageContextStateless. + LogCollection. - :attr MessageContextGlobalStateless global_: (optional) Session context data - that is shared by all skills used by the assistant. - :attr dict skills: (optional) Information specific to particular skills used by - the assistant. - :attr dict integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :attr List[Log] logs: An array of objects describing log events. + :attr LogPagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, - *, - global_: 'MessageContextGlobalStateless' = None, - skills: dict = None, - integrations: dict = None) -> None: + def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: """ - Initialize a MessageContextStateless object. + Initialize a LogCollection object. - :param MessageContextGlobalStateless global_: (optional) Session context - data that is shared by all skills used by the assistant. - :param dict skills: (optional) Information specific to particular skills - used by the assistant. - :param dict integrations: (optional) An object containing context data that - is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned + objects. For more information about using pagination, see + [Pagination](#pagination). """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.logs = logs + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': - """Initialize a MessageContextStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogCollection': + """Initialize a LogCollection object from a json dictionary.""" args = {} - if 'global' in _dict: - args['global_'] = MessageContextGlobalStateless.from_dict( - _dict.get('global')) - if 'skills' in _dict: - args['skills'] = { - k: MessageContextSkill.from_dict(v) - for k, v in _dict.get('skills').items() - } - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if 'logs' in _dict: + args['logs'] = [Log.from_dict(v) for v in _dict.get('logs')] + else: + raise ValueError( + 'Required property \'logs\' not present in LogCollection JSON') + if 'pagination' in _dict: + args['pagination'] = LogPagination.from_dict( + _dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in LogCollection JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextStateless object from a json dictionary.""" + """Initialize a LogCollection 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, 'global_') and self.global_ is not None: - if isinstance(self.global_, dict): - _dict['global'] = self.global_ - else: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - skills_map = {} - for k, v in self.skills.items(): + if hasattr(self, 'logs') and self.logs is not None: + logs_list = [] + for v in self.logs: if isinstance(v, dict): - skills_map[k] = v + logs_list.append(v) else: - skills_map[k] = v.to_dict() - _dict['skills'] = skills_map - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + logs_list.append(v.to_dict()) + _dict['logs'] = logs_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -3767,162 +4246,135 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextStateless object.""" + """Return a `str` version of this LogCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextStateless') -> bool: + def __eq__(self, other: 'LogCollection') -> 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: 'MessageContextStateless') -> bool: + def __ne__(self, other: 'LogCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInput(): +class LogMessageSource(): """ - An input object that includes the input text. + An object that identifies the dialog element that generated the error message. - :attr str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :attr str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :attr str suggestion_id: (optional) For internal use only. - :attr List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be sent - to external services by webhooks. - :attr MessageInputOptions options: (optional) Optional properties that control - how the assistant responds. + """ + + def __init__(self) -> None: + """ + Initialize a LogMessageSource object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSource': + """Initialize a LogMessageSource object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = ( + "Cannot convert dictionary into an instance of base class 'LogMessageSource'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a LogMessageSource object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['dialog_node'] = 'LogMessageSourceDialogNode' + mapping['action'] = 'LogMessageSourceAction' + mapping['step'] = 'LogMessageSourceStep' + mapping['handler'] = 'LogMessageSourceHandler' + disc_value = _dict.get('type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'type\' not found in LogMessageSource JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class LogPagination(): + """ + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). + + :attr str next_url: (optional) The URL that will return the next page of + results, if any. + :attr int matched: (optional) Reserved for future use. + :attr str next_cursor: (optional) A token identifying the next page of results. """ def __init__(self, *, - message_type: str = None, - text: str = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - suggestion_id: str = None, - attachments: List['MessageInputAttachment'] = None, - options: 'MessageInputOptions' = None) -> None: + next_url: str = None, + matched: int = None, + next_cursor: str = None) -> None: """ - Initialize a MessageInput object. + Initialize a LogPagination object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be - sent to external services by webhooks. - :param MessageInputOptions options: (optional) Optional properties that - control how the assistant responds. + :param str next_url: (optional) The URL that will return the next page of + results, if any. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of + results. """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.options = options + self.next_url = next_url + self.matched = matched + self.next_cursor = next_cursor @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInput': - """Initialize a MessageInput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogPagination': + """Initialize a LogPagination object from a json dictionary.""" args = {} - if 'message_type' in _dict: - args['message_type'] = _dict.get('message_type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'suggestion_id' in _dict: - args['suggestion_id'] = _dict.get('suggestion_id') - if 'attachments' in _dict: - args['attachments'] = [ - MessageInputAttachment.from_dict(v) - for v in _dict.get('attachments') - ] - if 'options' in _dict: - args['options'] = MessageInputOptions.from_dict( - _dict.get('options')) + if 'next_url' in _dict: + args['next_url'] = _dict.get('next_url') + if 'matched' in _dict: + args['matched'] = _dict.get('matched') + if 'next_cursor' in _dict: + args['next_cursor'] = _dict.get('next_cursor') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInput object from a json dictionary.""" + """Initialize a LogPagination 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, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - attachments_list = [] - for v in self.attachments: - if isinstance(v, dict): - attachments_list.append(v) - else: - attachments_list.append(v.to_dict()) - _dict['attachments'] = attachments_list - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options - else: - _dict['options'] = self.options.to_dict() + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor return _dict def _to_dict(self): @@ -3930,78 +4382,92 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInput object.""" + """Return a `str` version of this LogPagination object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInput') -> bool: + def __eq__(self, other: 'LogPagination') -> 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: 'MessageInput') -> bool: + def __ne__(self, other: 'LogPagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): - """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. - """ - TEXT = 'text' - SEARCH = 'search' - -class MessageInputAttachment(): +class MessageContext(): """ - A reference to a media file to be sent as an attachment with the message. + MessageContext. - :attr str url: The URL of the media file. - :attr str media_type: (optional) The media content type (such as a MIME type) of - the attachment. + :attr MessageContextGlobal global_: (optional) Session context data that is + shared by all skills used by the assistant. + :attr dict skills: (optional) Information specific to particular skills used by + the assistant. + :attr dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - def __init__(self, url: str, *, media_type: str = None) -> None: + def __init__(self, + *, + global_: 'MessageContextGlobal' = None, + skills: dict = None, + integrations: dict = None) -> None: """ - Initialize a MessageInputAttachment object. + Initialize a MessageContext object. - :param str url: The URL of the media file. - :param str media_type: (optional) The media content type (such as a MIME - type) of the attachment. - """ - self.url = url - self.media_type = media_type + :param MessageContextGlobal global_: (optional) Session context data that + is shared by all skills used by the assistant. + :param dict skills: (optional) Information specific to particular skills + used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + """ + self.global_ = global_ + self.skills = skills + self.integrations = integrations @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': - """Initialize a MessageInputAttachment object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContext': + """Initialize a MessageContext object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') - else: - raise ValueError( - 'Required property \'url\' not present in MessageInputAttachment JSON' - ) - if 'media_type' in _dict: - args['media_type'] = _dict.get('media_type') + if 'global' in _dict: + args['global_'] = MessageContextGlobal.from_dict( + _dict.get('global')) + if 'skills' in _dict: + args['skills'] = { + k: MessageContextSkill.from_dict(v) + for k, v in _dict.get('skills').items() + } + if 'integrations' in _dict: + args['integrations'] = _dict.get('integrations') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputAttachment object from a json dictionary.""" + """Initialize a MessageContext 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, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'media_type') and self.media_type is not None: - _dict['media_type'] = self.media_type + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + skills_map = {} + for k, v in self.skills.items(): + if isinstance(v, dict): + skills_map[k] = v + else: + skills_map[k] = v.to_dict() + _dict['skills'] = skills_map + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations return _dict def _to_dict(self): @@ -4009,131 +4475,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputAttachment object.""" + """Return a `str` version of this MessageContext object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputAttachment') -> bool: + def __eq__(self, other: 'MessageContext') -> 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: 'MessageInputAttachment') -> bool: + def __ne__(self, other: 'MessageContext') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputOptions(): +class MessageContextGlobal(): """ - Optional properties that control how the assistant responds. + Session context data that is shared by all skills used by the assistant. - :attr bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. - :attr bool return_context: (optional) Whether to return session context with the - response. If you specify `true`, the response includes the `context` property. - If you also specify **debug**=`true`, the returned skill context includes the - `system.state` property. - :attr bool export: (optional) Whether to return session context, including full - conversation state. If you specify `true`, the response includes the `context` - property, and the skill context includes the `system.state` property. - **Note:** If **export**=`true`, the context is returned regardless of the value - of **return_context**. + :attr MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :attr str session_id: (optional) The session ID. """ def __init__(self, *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None, - return_context: bool = None, - export: bool = None) -> None: + system: 'MessageContextGlobalSystem' = None, + session_id: str = None) -> None: """ - Initialize a MessageInputOptions object. + Initialize a MessageContextGlobal object. - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. - :param bool return_context: (optional) Whether to return session context - with the response. If you specify `true`, the response includes the - `context` property. If you also specify **debug**=`true`, the returned - skill context includes the `system.state` property. - :param bool export: (optional) Whether to return session context, including - full conversation state. If you specify `true`, the response includes the - `context` property, and the skill context includes the `system.state` - property. - **Note:** If **export**=`true`, the context is returned regardless of the - value of **return_context**. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. """ - self.restart = restart - self.alternate_intents = alternate_intents - self.spelling = spelling - self.debug = debug - self.return_context = return_context - self.export = export + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': - """Initialize a MessageInputOptions object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': + """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') - if 'return_context' in _dict: - args['return_context'] = _dict.get('return_context') - if 'export' in _dict: - args['export'] = _dict.get('export') + if 'system' in _dict: + args['system'] = MessageContextGlobalSystem.from_dict( + _dict.get('system')) + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptions object from a json dictionary.""" + """Initialize a MessageContextGlobal 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, 'restart') and self.restart is not None: - _dict['restart'] = self.restart - if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'spelling') and self.spelling is not None: - if isinstance(self.spelling, dict): - _dict['spelling'] = self.spelling + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system else: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug - if hasattr(self, 'return_context') and self.return_context is not None: - _dict['return_context'] = self.return_context - if hasattr(self, 'export') and self.export is not None: - _dict['export'] = self.export + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and getattr(self, + 'session_id') is not None: + _dict['session_id'] = getattr(self, 'session_id') return _dict def _to_dict(self): @@ -4141,86 +4545,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptions object.""" + """Return a `str` version of this MessageContextGlobal object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptions') -> bool: + def __eq__(self, other: 'MessageContextGlobal') -> 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: 'MessageInputOptions') -> bool: + def __ne__(self, other: 'MessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputOptionsSpelling(): +class MessageContextGlobalStateless(): """ - Spelling correction options for the message. Any options specified on an individual - message override the settings configured for the skill. + Session context data that is shared by all skills used by the assistant. - :attr bool suggestions: (optional) Whether to use spelling correction when - processing the input. If spelling correction is used and **auto_correct** is - `true`, any spelling corrections are automatically applied to the user input. If - **auto_correct** is `false`, any suggested corrections are returned in the - **output.spelling** property. - This property overrides the value of the **spelling_suggestions** property in - the workspace settings for the skill. - :attr bool auto_correct: (optional) Whether to use autocorrection when - processing the input. If this property is `true`, any corrections are - automatically applied to the user input, and the original text is returned in - the **output.spelling** property of the message response. This property - overrides the value of the **spelling_auto_correct** property in the workspace - settings for the skill. + :attr MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :attr str session_id: (optional) The unique identifier of the session. """ def __init__(self, *, - suggestions: bool = None, - auto_correct: bool = None) -> None: + system: 'MessageContextGlobalSystem' = None, + session_id: str = None) -> None: """ - Initialize a MessageInputOptionsSpelling object. + Initialize a MessageContextGlobalStateless object. - :param bool suggestions: (optional) Whether to use spelling correction when - processing the input. If spelling correction is used and **auto_correct** - is `true`, any spelling corrections are automatically applied to the user - input. If **auto_correct** is `false`, any suggested corrections are - returned in the **output.spelling** property. - This property overrides the value of the **spelling_suggestions** property - in the workspace settings for the skill. - :param bool auto_correct: (optional) Whether to use autocorrection when - processing the input. If this property is `true`, any corrections are - automatically applied to the user input, and the original text is returned - in the **output.spelling** property of the message response. This property - overrides the value of the **spelling_auto_correct** property in the - workspace settings for the skill. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. """ - self.suggestions = suggestions - self.auto_correct = auto_correct + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': - """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': + """Initialize a MessageContextGlobalStateless object from a json dictionary.""" args = {} - if 'suggestions' in _dict: - args['suggestions'] = _dict.get('suggestions') - if 'auto_correct' in _dict: - args['auto_correct'] = _dict.get('auto_correct') + if 'system' in _dict: + args['system'] = MessageContextGlobalSystem.from_dict( + _dict.get('system')) + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + """Initialize a MessageContextGlobalStateless 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, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = self.suggestions - if hasattr(self, 'auto_correct') and self.auto_correct is not None: - _dict['auto_correct'] = self.auto_correct + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id return _dict def _to_dict(self): @@ -4228,98 +4615,194 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptionsSpelling object.""" + """Return a `str` version of this MessageContextGlobalStateless object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptionsSpelling') -> bool: + def __eq__(self, other: 'MessageContextGlobalStateless') -> 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: 'MessageInputOptionsSpelling') -> bool: + def __ne__(self, other: 'MessageContextGlobalStateless') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputOptionsStateless(): +class MessageContextGlobalSystem(): """ - Optional properties that control how the assistant responds. + Built-in system properties that apply to all skills used by the assistant. - :attr bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :attr str timezone: (optional) The user time zone. The assistant uses the time + zone to correctly resolve relative time references. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root of + the message body. If **user_id** is specified in both locations in a message + request, the value specified at the root is used. + :attr int turn_count: (optional) A counter that is automatically incremented + 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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for the + skill. + :attr str session_start_time: (optional) The time at which the session started. + With the stateful `message` method, the start time is always present, and is set + by the service based on the time the session was created. With the stateless + `message` method, the start time is set by the service in the response to the + first message, and should be returned as part of the context with each + subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for example, + `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :attr str state: (optional) An encoded string that represents the configuration + state of the assistant at the beginning of the conversation. If you are using + the stateless `message` method, save this value and then send it in the context + of the subsequent message request to avoid disruptions if there are + configuration changes during the conversation (such as a change to a skill the + assistant uses). + :attr bool skip_user_input: (optional) For internal use only. """ def __init__(self, *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None) -> None: + timezone: str = None, + user_id: str = None, + turn_count: int = None, + locale: str = None, + reference_time: str = None, + session_start_time: str = None, + state: str = None, + skip_user_input: bool = None) -> None: """ - Initialize a MessageInputOptionsStateless object. + Initialize a MessageContextGlobalSystem object. - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :param str timezone: (optional) The user time zone. The assistant uses the + time zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root + of the message body. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. + :param int turn_count: (optional) A counter that is automatically + incremented 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). + :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for + the skill. + :param str session_start_time: (optional) The time at which the session + started. With the stateful `message` method, the start time is always + present, and is set by the service based on the time the session was + created. With the stateless `message` method, the start time is set by the + service in the response to the first message, and should be returned as + part of the context with each subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the + configuration state of the assistant at the beginning of the conversation. + If you are using the stateless `message` method, save this value and then + send it in the context of the subsequent message request to avoid + disruptions if there are configuration changes during the conversation + (such as a change to a skill the assistant uses). + :param bool skip_user_input: (optional) For internal use only. """ - self.restart = restart - self.alternate_intents = alternate_intents - self.spelling = spelling - self.debug = debug + self.timezone = timezone + self.user_id = user_id + self.turn_count = turn_count + self.locale = locale + self.reference_time = reference_time + self.session_start_time = session_start_time + self.state = state + self.skip_user_input = skip_user_input @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': + """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') + if 'timezone' in _dict: + args['timezone'] = _dict.get('timezone') + if 'user_id' in _dict: + 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') + if 'session_start_time' in _dict: + args['session_start_time'] = _dict.get('session_start_time') + if 'state' in _dict: + args['state'] = _dict.get('state') + if 'skip_user_input' in _dict: + args['skip_user_input'] = _dict.get('skip_user_input') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + """Initialize a MessageContextGlobalSystem 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, 'restart') and self.restart is not None: - _dict['restart'] = self.restart + if hasattr(self, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + if hasattr(self, 'user_id') and self.user_id is not None: + _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 + if hasattr( + self, + 'session_start_time') and self.session_start_time is not None: + _dict['session_start_time'] = self.session_start_time + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'spelling') and self.spelling is not None: - if isinstance(self.spelling, dict): - _dict['spelling'] = self.spelling - else: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug + 'skip_user_input') and self.skip_user_input is not None: + _dict['skip_user_input'] = self.skip_user_input return _dict def _to_dict(self): @@ -4327,162 +4810,99 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptionsStateless object.""" + """Return a `str` version of this MessageContextGlobalSystem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptionsStateless') -> bool: + def __eq__(self, other: 'MessageContextGlobalSystem') -> 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: 'MessageInputOptionsStateless') -> bool: + def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LocaleEnum(str, 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 MessageInputStateless(): +class MessageContextSkill(): """ - An input object that includes the input text. + Contains information specific to a particular skill used by the assistant. The + property name must be the same as the name of the skill. + **Note:** The default skill names are `main skill` for the dialog skill (if enabled) + and `actions skill` for the action skill. - :attr str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :attr str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :attr str suggestion_id: (optional) For internal use only. - :attr List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be sent - to external services by webhooks. - :attr MessageInputOptionsStateless options: (optional) Optional properties that - control how the assistant responds. + :attr dict user_defined: (optional) Arbitrary variables that can be read and + written by a particular skill. + :attr MessageContextSkillSystem system: (optional) System context data used by + the skill. """ def __init__(self, *, - message_type: str = None, - text: str = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - suggestion_id: str = None, - attachments: List['MessageInputAttachment'] = None, - options: 'MessageInputOptionsStateless' = None) -> None: + user_defined: dict = None, + system: 'MessageContextSkillSystem' = None) -> None: """ - Initialize a MessageInputStateless object. + Initialize a MessageContextSkill object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. - **Note:** Attachments are not processed by the assistant itself, but can be - sent to external services by webhooks. - :param MessageInputOptionsStateless options: (optional) Optional properties - that control how the assistant responds. + :param dict user_defined: (optional) Arbitrary variables that can be read + and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.options = options + self.user_defined = user_defined + self.system = system @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': - """Initialize a MessageInputStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': + """Initialize a MessageContextSkill object from a json dictionary.""" args = {} - if 'message_type' in _dict: - args['message_type'] = _dict.get('message_type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'suggestion_id' in _dict: - args['suggestion_id'] = _dict.get('suggestion_id') - if 'attachments' in _dict: - args['attachments'] = [ - MessageInputAttachment.from_dict(v) - for v in _dict.get('attachments') - ] - if 'options' in _dict: - args['options'] = MessageInputOptionsStateless.from_dict( - _dict.get('options')) + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + if 'system' in _dict: + args['system'] = MessageContextSkillSystem.from_dict( + _dict.get('system')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputStateless object from a json dictionary.""" + """Initialize a MessageContextSkill 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, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - attachments_list = [] - for v in self.attachments: - if isinstance(v, dict): - attachments_list.append(v) - else: - attachments_list.append(v.to_dict()) - _dict['attachments'] = attachments_list - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system else: - _dict['options'] = self.options.to_dict() + _dict['system'] = self.system.to_dict() return _dict def _to_dict(self): @@ -4490,308 +4910,190 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputStateless object.""" + """Return a `str` version of this MessageContextSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputStateless') -> bool: + def __eq__(self, other: 'MessageContextSkill') -> 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: 'MessageInputStateless') -> bool: + def __ne__(self, other: 'MessageContextSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): - """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or actions skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. - """ - TEXT = 'text' - SEARCH = 'search' - -class MessageOutput(): +class MessageContextSkillSystem(): """ - Assistant output to be rendered or processed by the client. + System context data used by the skill. - :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any - channel. It is the responsibility of the client application to implement the - supported response types. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in - the user input, sorted in descending order of confidence. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified - in the user input. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing - any actions requested by the dialog node. - :attr MessageOutputDebug debug: (optional) Additional detailed information about - a message response and how it was generated. - :attr dict user_defined: (optional) An object containing any custom properties - included in the response. This object includes any arbitrary properties defined - in the dialog JSON editor as part of the dialog node output. - :attr MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + :attr str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context of a + subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. """ - def __init__(self, - *, - generic: List['RuntimeResponseGeneric'] = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - actions: List['DialogNodeAction'] = None, - debug: 'MessageOutputDebug' = None, - user_defined: dict = None, - spelling: 'MessageOutputSpelling' = None) -> None: + # The set of defined properties for the class + _properties = frozenset(['state']) + + def __init__(self, *, state: str = None, **kwargs) -> None: """ - Initialize a MessageOutput object. + Initialize a MessageContextSkillSystem object. - :param List[RuntimeResponseGeneric] generic: (optional) Output intended for - any channel. It is the responsibility of the client application to - implement the supported response types. - :param List[RuntimeIntent] intents: (optional) An array of intents - recognized in the user input, sorted in descending order of confidence. - :param List[RuntimeEntity] entities: (optional) An array of entities - identified in the user input. - :param List[DialogNodeAction] actions: (optional) An array of objects - describing any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information - about a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom - properties included in the response. This object includes any arbitrary - properties defined in the dialog JSON editor as part of the dialog node - output. - :param MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + :param str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context + of a subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + :param **kwargs: (optional) Any additional properties. """ - self.generic = generic - self.intents = intents - self.entities = entities - self.actions = actions - self.debug = debug - self.user_defined = user_defined - self.spelling = spelling + self.state = state + for _key, _value in kwargs.items(): + setattr(self, _key, _value) @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutput': - """Initialize a MessageOutput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': + """Initialize a MessageContextSkillSystem object from a json dictionary.""" args = {} - if 'generic' in _dict: - args['generic'] = [ - RuntimeResponseGeneric.from_dict(v) - for v in _dict.get('generic') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(v) for v in _dict.get('actions') - ] - if 'debug' in _dict: - args['debug'] = MessageOutputDebug.from_dict(_dict.get('debug')) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'spelling' in _dict: - args['spelling'] = MessageOutputSpelling.from_dict( - _dict.get('spelling')) + if 'state' in _dict: + args['state'] = _dict.get('state') + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutput object from a json dictionary.""" + """Initialize a MessageContextSkillSystem 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, 'generic') and self.generic is not None: - generic_list = [] - for v in self.generic: - if isinstance(v, dict): - generic_list.append(v) - else: - generic_list.append(v.to_dict()) - _dict['generic'] = generic_list - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'actions') and self.actions is not None: - actions_list = [] - for v in self.actions: - if isinstance(v, dict): - actions_list.append(v) - else: - actions_list.append(v.to_dict()) - _dict['actions'] = actions_list - if hasattr(self, 'debug') and self.debug is not None: - if isinstance(self.debug, dict): - _dict['debug'] = self.debug - else: - _dict['debug'] = self.debug.to_dict() - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'spelling') and self.spelling is not None: - if isinstance(self.spelling, dict): - _dict['spelling'] = self.spelling - else: - _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in MessageContextSkillSystem._properties: + setattr(self, _key, _value) + def __str__(self) -> str: - """Return a `str` version of this MessageOutput object.""" + """Return a `str` version of this MessageContextSkillSystem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutput') -> bool: + def __eq__(self, other: 'MessageContextSkillSystem') -> 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: 'MessageOutput') -> bool: + def __ne__(self, other: 'MessageContextSkillSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebug(): +class MessageContextStateless(): """ - Additional detailed information about a message response and how it was generated. + MessageContextStateless. - :attr List[DialogNodeVisited] nodes_visited: (optional) An array of objects - containing detailed diagnostic information about dialog nodes that were visited - during processing of the input message. - :attr List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :attr bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` - by the assistant, the `branch_exited_reason` specifies whether the dialog - completed by itself or got interrupted. - :attr List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of - objects containing detailed diagnostic information about dialog nodes and - actions that were visited during processing of the input message. - This property is present only if the assistant has an actions skill. + :attr MessageContextGlobalStateless global_: (optional) Session context data + that is shared by all skills used by the assistant. + :attr dict skills: (optional) Information specific to particular skills used by + the assistant. + :attr dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - def __init__( - self, - *, - nodes_visited: List['DialogNodeVisited'] = None, - log_messages: List['DialogLogMessage'] = None, - branch_exited: bool = None, - branch_exited_reason: str = None, - turn_events: List['MessageOutputDebugTurnEvent'] = None) -> None: + def __init__(self, + *, + global_: 'MessageContextGlobalStateless' = None, + skills: dict = None, + integrations: dict = None) -> None: """ - Initialize a MessageOutputDebug object. + Initialize a MessageContextStateless object. - :param List[DialogNodeVisited] nodes_visited: (optional) An array of - objects containing detailed diagnostic information about dialog nodes that - were visited during processing of the input message. - :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :param bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :param str branch_exited_reason: (optional) When `branch_exited` is set to - `true` by the assistant, the `branch_exited_reason` specifies whether the - dialog completed by itself or got interrupted. - :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array - of objects containing detailed diagnostic information about dialog nodes - and actions that were visited during processing of the input message. - This property is present only if the assistant has an actions skill. + :param MessageContextGlobalStateless global_: (optional) Session context + data that is shared by all skills used by the assistant. + :param dict skills: (optional) Information specific to particular skills + used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - self.nodes_visited = nodes_visited - self.log_messages = log_messages - self.branch_exited = branch_exited - self.branch_exited_reason = branch_exited_reason - self.turn_events = turn_events + self.global_ = global_ + self.skills = skills + self.integrations = integrations @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': - """Initialize a MessageOutputDebug object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': + """Initialize a MessageContextStateless object from a json dictionary.""" args = {} - if 'nodes_visited' in _dict: - args['nodes_visited'] = [ - DialogNodeVisited.from_dict(v) - for v in _dict.get('nodes_visited') - ] - if 'log_messages' in _dict: - args['log_messages'] = [ - DialogLogMessage.from_dict(v) for v in _dict.get('log_messages') - ] - if 'branch_exited' in _dict: - args['branch_exited'] = _dict.get('branch_exited') - if 'branch_exited_reason' in _dict: - args['branch_exited_reason'] = _dict.get('branch_exited_reason') - if 'turn_events' in _dict: - args['turn_events'] = [ - MessageOutputDebugTurnEvent.from_dict(v) - for v in _dict.get('turn_events') - ] + if 'global' in _dict: + args['global_'] = MessageContextGlobalStateless.from_dict( + _dict.get('global')) + if 'skills' in _dict: + args['skills'] = { + k: MessageContextSkill.from_dict(v) + for k, v in _dict.get('skills').items() + } + if 'integrations' in _dict: + args['integrations'] = _dict.get('integrations') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebug object from a json dictionary.""" + """Initialize a MessageContextStateless 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, 'nodes_visited') and self.nodes_visited is not None: - nodes_visited_list = [] - for v in self.nodes_visited: - if isinstance(v, dict): - nodes_visited_list.append(v) - else: - nodes_visited_list.append(v.to_dict()) - _dict['nodes_visited'] = nodes_visited_list - if hasattr(self, 'log_messages') and self.log_messages is not None: - log_messages_list = [] - for v in self.log_messages: - if isinstance(v, dict): - log_messages_list.append(v) - else: - log_messages_list.append(v.to_dict()) - _dict['log_messages'] = log_messages_list - if hasattr(self, 'branch_exited') and self.branch_exited is not None: - _dict['branch_exited'] = self.branch_exited - if hasattr(self, 'branch_exited_reason' - ) and self.branch_exited_reason is not None: - _dict['branch_exited_reason'] = self.branch_exited_reason - if hasattr(self, 'turn_events') and self.turn_events is not None: - turn_events_list = [] - for v in self.turn_events: + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + skills_map = {} + for k, v in self.skills.items(): if isinstance(v, dict): - turn_events_list.append(v) + skills_map[k] = v else: - turn_events_list.append(v.to_dict()) - _dict['turn_events'] = turn_events_list + skills_map[k] = v.to_dict() + _dict['skills'] = skills_map + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations return _dict def _to_dict(self): @@ -4799,172 +5101,180 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebug object.""" + """Return a `str` version of this MessageContextStateless object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputDebug') -> bool: + def __eq__(self, other: 'MessageContextStateless') -> 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: 'MessageOutputDebug') -> bool: + def __ne__(self, other: 'MessageContextStateless') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class BranchExitedReasonEnum(str, Enum): - """ - When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` - specifies whether the dialog completed by itself or got interrupted. - """ - COMPLETED = 'completed' - FALLBACK = 'fallback' - -class MessageOutputDebugTurnEvent(): +class MessageInput(): """ - MessageOutputDebugTurnEvent. + An input object that includes the input text. - """ - - def __init__(self) -> None: - """ - Initialize a MessageOutputDebugTurnEvent object. - - """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'MessageOutputDebugTurnEventTurnEventActionVisited', - 'MessageOutputDebugTurnEventTurnEventActionFinished', - 'MessageOutputDebugTurnEventTurnEventStepVisited', - 'MessageOutputDebugTurnEventTurnEventStepAnswered', - 'MessageOutputDebugTurnEventTurnEventHandlerVisited', - 'MessageOutputDebugTurnEventTurnEventCallout', - 'MessageOutputDebugTurnEventTurnEventSearch', - 'MessageOutputDebugTurnEventTurnEventNodeVisited' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': - """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'MessageOutputDebugTurnEventTurnEventActionVisited', - 'MessageOutputDebugTurnEventTurnEventActionFinished', - 'MessageOutputDebugTurnEventTurnEventStepVisited', - 'MessageOutputDebugTurnEventTurnEventStepAnswered', - 'MessageOutputDebugTurnEventTurnEventHandlerVisited', - 'MessageOutputDebugTurnEventTurnEventCallout', - 'MessageOutputDebugTurnEventTurnEventSearch', - 'MessageOutputDebugTurnEventTurnEventNodeVisited' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" - return cls.from_dict(_dict) - - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping[ - 'action_visited'] = 'MessageOutputDebugTurnEventTurnEventActionVisited' - mapping[ - 'action_finished'] = 'MessageOutputDebugTurnEventTurnEventActionFinished' - mapping[ - 'step_visited'] = 'MessageOutputDebugTurnEventTurnEventStepVisited' - mapping[ - 'step_answered'] = 'MessageOutputDebugTurnEventTurnEventStepAnswered' - mapping[ - 'handler_visited'] = 'MessageOutputDebugTurnEventTurnEventHandlerVisited' - mapping['callout'] = 'MessageOutputDebugTurnEventTurnEventCallout' - mapping['search'] = 'MessageOutputDebugTurnEventTurnEventSearch' - mapping[ - 'node_visited'] = 'MessageOutputDebugTurnEventTurnEventNodeVisited' - disc_value = _dict.get('event') - if disc_value is None: - raise ValueError( - 'Discriminator property \'event\' not found in MessageOutputDebugTurnEvent JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - - -class MessageOutputSpelling(): - """ - Properties describing any spelling corrections in the user input that was received. - - :attr str text: (optional) The user input text that was used to generate the - response. If spelling autocorrection is enabled, this text reflects any spelling - corrections that were applied. - :attr str original_text: (optional) The original user input text. This property - is returned only if autocorrection is enabled and the user input was corrected. - :attr str suggested_text: (optional) Any suggested corrections of the input - text. This property is returned only if spelling correction is enabled and - autocorrection is disabled. + :attr str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :attr str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the + user input. Include intents from the previous response to continue using those + intents rather than trying to recognize intents in the new input. + :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :attr str suggestion_id: (optional) For internal use only. + :attr List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :attr RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :attr MessageInputOptions options: (optional) Optional properties that control + how the assistant responds. """ def __init__(self, *, + message_type: str = None, text: str = None, - original_text: str = None, - suggested_text: str = None) -> None: + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + suggestion_id: str = None, + attachments: List['MessageInputAttachment'] = None, + analytics: 'RequestAnalytics' = None, + options: 'MessageInputOptions' = None) -> None: """ - Initialize a MessageOutputSpelling object. + Initialize a MessageInput object. - :param str text: (optional) The user input text that was used to generate - the response. If spelling autocorrection is enabled, this text reflects any - spelling corrections that were applied. - :param str original_text: (optional) The original user input text. This - property is returned only if autocorrection is enabled and the user input - was corrected. - :param str suggested_text: (optional) Any suggested corrections of the - input text. This property is returned only if spelling correction is - enabled and autocorrection is disabled. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param MessageInputOptions options: (optional) Optional properties that + control how the assistant responds. """ + self.message_type = message_type self.text = text - self.original_text = original_text - self.suggested_text = suggested_text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': - """Initialize a MessageOutputSpelling object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInput': + """Initialize a MessageInput object from a json dictionary.""" args = {} + if 'message_type' in _dict: + args['message_type'] = _dict.get('message_type') if 'text' in _dict: args['text'] = _dict.get('text') - if 'original_text' in _dict: - args['original_text'] = _dict.get('original_text') - if 'suggested_text' in _dict: - args['suggested_text'] = _dict.get('suggested_text') + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent.from_dict(v) for v in _dict.get('intents') + ] + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity.from_dict(v) for v in _dict.get('entities') + ] + if 'suggestion_id' in _dict: + args['suggestion_id'] = _dict.get('suggestion_id') + if 'attachments' in _dict: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) + for v in _dict.get('attachments') + ] + if 'analytics' in _dict: + args['analytics'] = RequestAnalytics.from_dict( + _dict.get('analytics')) + if 'options' in _dict: + args['options'] = MessageInputOptions.from_dict( + _dict.get('options')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputSpelling object from a json dictionary.""" + """Initialize a MessageInput 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, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text - if hasattr(self, 'original_text') and self.original_text is not None: - _dict['original_text'] = self.original_text - if hasattr(self, 'suggested_text') and self.suggested_text is not None: - _dict['suggested_text'] = self.suggested_text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -4972,107 +5282,78 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputSpelling object.""" + """Return a `str` version of this MessageInput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputSpelling') -> bool: + def __eq__(self, other: 'MessageInput') -> 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: 'MessageOutputSpelling') -> bool: + def __ne__(self, other: 'MessageInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + TEXT = 'text' + SEARCH = 'search' -class MessageRequest(): + +class MessageInputAttachment(): """ - A stateful message request formatted for the Watson Assistant service. + A reference to a media file to be sent as an attachment with the message. - :attr MessageInput input: (optional) An input object that includes the input - text. - :attr MessageContext context: (optional) Context data for the conversation. You - can use this property to set or modify context variables, which can also be - accessed by dialog nodes. The context is stored by the assistant on a - per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. If **user_id** is specified in both locations, the value - specified at the root is used. + :attr str url: The URL of the media file. + :attr str media_type: (optional) The media content type (such as a MIME type) of + the attachment. """ - def __init__(self, - *, - input: 'MessageInput' = None, - context: 'MessageContext' = None, - user_id: str = None) -> None: + def __init__(self, url: str, *, media_type: str = None) -> None: """ - Initialize a MessageRequest object. + Initialize a MessageInputAttachment object. - :param MessageInput input: (optional) An input object that includes the - input text. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to set or modify context variables, - which can also be accessed by dialog nodes. The context is stored by the - assistant on a per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. If **user_id** is specified in both locations, the - value specified at the root is used. + :param str url: The URL of the media file. + :param str media_type: (optional) The media content type (such as a MIME + type) of the attachment. """ - self.input = input - self.context = context - self.user_id = user_id + self.url = url + self.media_type = media_type @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageRequest': - """Initialize a MessageRequest object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': + """Initialize a MessageInputAttachment object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if 'url' in _dict: + args['url'] = _dict.get('url') + else: + raise ValueError( + 'Required property \'url\' not present in MessageInputAttachment JSON' + ) + if 'media_type' in _dict: + args['media_type'] = _dict.get('media_type') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageRequest object from a json dictionary.""" + """Initialize a MessageInputAttachment 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, 'input') and self.input is not None: - if isinstance(self.input, dict): - _dict['input'] = self.input - else: - _dict['input'] = self.input.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'media_type') and self.media_type is not None: + _dict['media_type'] = self.media_type return _dict def _to_dict(self): @@ -5080,113 +5361,131 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageRequest object.""" + """Return a `str` version of this MessageInputAttachment object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageRequest') -> bool: + def __eq__(self, other: 'MessageInputAttachment') -> 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: 'MessageRequest') -> bool: + def __ne__(self, other: 'MessageInputAttachment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageResponse(): +class MessageInputOptions(): """ - A response from the Watson Assistant service. + Optional properties that control how the assistant responds. - :attr MessageOutput output: Assistant output to be rendered or processed by the - client. - :attr MessageContext context: (optional) Context data for the conversation. You - can use this property to access context variables. The context is stored by the - assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :attr str user_id: A string value that identifies the user who is interacting - with the assistant. The client must provide a unique identifier for each - individual end user who accesses the application. For user-based plans, this - user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :attr bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :attr bool alternate_intents: (optional) Whether to return more than one intent. + Set to `true` to return all matching intents. + :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :attr bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. + :attr bool return_context: (optional) Whether to return session context with the + response. If you specify `true`, the response includes the `context` property. + If you also specify **debug**=`true`, the returned skill context includes the + `system.state` property. + :attr bool export: (optional) Whether to return session context, including full + conversation state. If you specify `true`, the response includes the `context` + property, and the skill context includes the `system.state` property. + **Note:** If **export**=`true`, the context is returned regardless of the value + of **return_context**. """ def __init__(self, - output: 'MessageOutput', - user_id: str, *, - context: 'MessageContext' = None) -> None: + restart: bool = None, + alternate_intents: bool = None, + spelling: 'MessageInputOptionsSpelling' = None, + debug: bool = None, + return_context: bool = None, + export: bool = None) -> None: """ - Initialize a MessageResponse object. + Initialize a MessageInputOptions object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param str user_id: A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier - for each individual end user who accesses the application. For user-based - plans, this user ID is used to identify unique users for billing purposes. - This string cannot contain carriage return, newline, or tab characters. If - no value is specified in the input, **user_id** is automatically set to the - value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to access context variables. The - context is stored by the assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. + :param bool return_context: (optional) Whether to return session context + with the response. If you specify `true`, the response includes the + `context` property. If you also specify **debug**=`true`, the returned + skill context includes the `system.state` property. + :param bool export: (optional) Whether to return session context, including + full conversation state. If you specify `true`, the response includes the + `context` property, and the skill context includes the `system.state` + property. + **Note:** If **export**=`true`, the context is returned regardless of the + value of **return_context**. """ - self.output = output - self.context = context - self.user_id = user_id + self.restart = restart + self.alternate_intents = alternate_intents + self.spelling = spelling + self.debug = debug + self.return_context = return_context + self.export = export @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponse': - """Initialize a MessageResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': + """Initialize a MessageInputOptions object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponse JSON' - ) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - else: - raise ValueError( - 'Required property \'user_id\' not present in MessageResponse JSON' - ) + if 'restart' in _dict: + args['restart'] = _dict.get('restart') + if 'alternate_intents' in _dict: + args['alternate_intents'] = _dict.get('alternate_intents') + if 'spelling' in _dict: + args['spelling'] = MessageInputOptionsSpelling.from_dict( + _dict.get('spelling')) + if 'debug' in _dict: + args['debug'] = _dict.get('debug') + if 'return_context' in _dict: + args['return_context'] = _dict.get('return_context') + if 'export' in _dict: + args['export'] = _dict.get('export') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageResponse object from a json dictionary.""" + """Initialize a MessageInputOptions 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, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug + if hasattr(self, 'return_context') and self.return_context is not None: + _dict['return_context'] = self.return_context + if hasattr(self, 'export') and self.export is not None: + _dict['export'] = self.export return _dict def _to_dict(self): @@ -5194,110 +5493,86 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageResponse object.""" + """Return a `str` version of this MessageInputOptions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageResponse') -> bool: + def __eq__(self, other: 'MessageInputOptions') -> 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: 'MessageResponse') -> bool: + def __ne__(self, other: 'MessageInputOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageResponseStateless(): - """ - A stateless response from the Watson Assistant service. - - :attr MessageOutput output: Assistant output to be rendered or processed by the - client. - :attr MessageContextStateless context: Context data for the conversation. You - can use this property to access context variables. The context is not stored by - the assistant; to maintain session state, include the context from the response - in the next message. - :attr str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. +class MessageInputOptionsSpelling(): """ + Spelling correction options for the message. Any options specified on an individual + message override the settings configured for the skill. - def __init__(self, - output: 'MessageOutput', - context: 'MessageContextStateless', - *, - user_id: str = None) -> None: + :attr bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** is + `true`, any spelling corrections are automatically applied to the user input. If + **auto_correct** is `false`, any suggested corrections are returned in the + **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property in + the workspace settings for the skill. + :attr bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned in + the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the workspace + settings for the skill. + """ + + def __init__(self, + *, + suggestions: bool = None, + auto_correct: bool = None) -> None: """ - Initialize a MessageResponseStateless object. + Initialize a MessageInputOptionsSpelling object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param MessageContextStateless context: Context data for the conversation. - You can use this property to access context variables. The context is not - stored by the assistant; to maintain session state, include the context - from the response in the next message. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. + :param bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** + is `true`, any spelling corrections are automatically applied to the user + input. If **auto_correct** is `false`, any suggested corrections are + returned in the **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property + in the workspace settings for the skill. + :param bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned + in the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the + workspace settings for the skill. """ - self.output = output - self.context = context - self.user_id = user_id + self.suggestions = suggestions + self.auto_correct = auto_correct @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': - """Initialize a MessageResponseStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': + """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponseStateless JSON' - ) - if 'context' in _dict: - args['context'] = MessageContextStateless.from_dict( - _dict.get('context')) - else: - raise ValueError( - 'Required property \'context\' not present in MessageResponseStateless JSON' - ) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if 'suggestions' in _dict: + args['suggestions'] = _dict.get('suggestions') + if 'auto_correct' in _dict: + args['auto_correct'] = _dict.get('auto_correct') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageResponseStateless object from a json dictionary.""" + """Initialize a MessageInputOptionsSpelling 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, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'suggestions') and self.suggestions is not None: + _dict['suggestions'] = self.suggestions + if hasattr(self, 'auto_correct') and self.auto_correct is not None: + _dict['auto_correct'] = self.auto_correct return _dict def _to_dict(self): @@ -5305,108 +5580,98 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageResponseStateless object.""" + """Return a `str` version of this MessageInputOptionsSpelling object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageResponseStateless') -> bool: + def __eq__(self, other: 'MessageInputOptionsSpelling') -> 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: 'MessageResponseStateless') -> bool: + def __ne__(self, other: 'MessageInputOptionsSpelling') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Pagination(): +class MessageInputOptionsStateless(): """ - The pagination data for the returned objects. + Optional properties that control how the assistant responds. - :attr str refresh_url: The URL that will return the same page of results. - :attr str next_url: (optional) The URL that will return the next page of - results. - :attr int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the current - page. - :attr int matched: (optional) Reserved for future use. - :attr str refresh_cursor: (optional) A token identifying the current page of - results. - :attr str next_cursor: (optional) A token identifying the next page of results. + :attr bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :attr bool alternate_intents: (optional) Whether to return more than one intent. + Set to `true` to return all matching intents. + :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :attr bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ def __init__(self, - refresh_url: str, *, - next_url: str = None, - total: int = None, - matched: int = None, - refresh_cursor: str = None, - next_cursor: str = None) -> None: + restart: bool = None, + alternate_intents: bool = None, + spelling: 'MessageInputOptionsSpelling' = None, + debug: bool = None) -> None: """ - Initialize a Pagination object. + Initialize a MessageInputOptionsStateless object. - :param str refresh_url: The URL that will return the same page of results. - :param str next_url: (optional) The URL that will return the next page of - results. - :param int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the - current page. - :param int matched: (optional) Reserved for future use. - :param str refresh_cursor: (optional) A token identifying the current page - of results. - :param str next_cursor: (optional) A token identifying the next page of - results. + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ - self.refresh_url = refresh_url - self.next_url = next_url - self.total = total - self.matched = matched - self.refresh_cursor = refresh_cursor - self.next_cursor = next_cursor + self.restart = restart + self.alternate_intents = alternate_intents + self.spelling = spelling + self.debug = debug @classmethod - def from_dict(cls, _dict: Dict) -> 'Pagination': - """Initialize a Pagination object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': + """Initialize a MessageInputOptionsStateless object from a json dictionary.""" args = {} - if 'refresh_url' in _dict: - args['refresh_url'] = _dict.get('refresh_url') - else: - raise ValueError( - 'Required property \'refresh_url\' not present in Pagination JSON' - ) - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'total' in _dict: - args['total'] = _dict.get('total') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'refresh_cursor' in _dict: - args['refresh_cursor'] = _dict.get('refresh_cursor') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if 'restart' in _dict: + args['restart'] = _dict.get('restart') + if 'alternate_intents' in _dict: + args['alternate_intents'] = _dict.get('alternate_intents') + if 'spelling' in _dict: + args['spelling'] = MessageInputOptionsSpelling.from_dict( + _dict.get('spelling')) + if 'debug' in _dict: + args['debug'] = _dict.get('debug') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Pagination object from a json dictionary.""" + """Initialize a MessageInputOptionsStateless 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, 'refresh_url') and self.refresh_url is not None: - _dict['refresh_url'] = self.refresh_url - if hasattr(self, 'next_url') and self.next_url is not None: - _dict['next_url'] = self.next_url - if hasattr(self, 'total') and self.total is not None: - _dict['total'] = self.total - if hasattr(self, 'matched') and self.matched is not None: - _dict['matched'] = self.matched - if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: - _dict['refresh_cursor'] = self.refresh_cursor - if hasattr(self, 'next_cursor') and self.next_cursor is not None: - _dict['next_cursor'] = self.next_cursor + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug return _dict def _to_dict(self): @@ -5414,123 +5679,180 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Pagination object.""" + """Return a `str` version of this MessageInputOptionsStateless object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Pagination') -> bool: + def __eq__(self, other: 'MessageInputOptionsStateless') -> 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: 'Pagination') -> bool: + def __ne__(self, other: 'MessageInputOptionsStateless') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Release(): - """ - Release. - - :attr str release: (optional) The name of the release. The name is the version - number (an integer), returned as a string. - :attr str description: (optional) The description of the release. - :attr List[EnvironmentReference] environment_references: (optional) An array of - objects describing the environments where this release has been deployed. - :attr ReleaseContent content: (optional) An object describing the versionable - content objects (such as skill snapshots) that are included in the release. - :attr str status: (optional) The current status of the release: - - **Available**: The release is available for deployment. - - **Failed**: An asynchronous publish operation has failed. - - **Processing**: An asynchronous publish operation has not yet completed. - :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. +class MessageInputStateless(): """ + An input object that includes the input text. - def __init__(self, - *, - release: str = None, - description: str = None, - environment_references: List['EnvironmentReference'] = None, - content: 'ReleaseContent' = None, - status: str = None, - created: datetime = None, - updated: datetime = None) -> None: + :attr str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :attr str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the + user input. Include intents from the previous response to continue using those + intents rather than trying to recognize intents in the new input. + :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :attr str suggestion_id: (optional) For internal use only. + :attr List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :attr RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :attr MessageInputOptionsStateless options: (optional) Optional properties that + control how the assistant responds. + """ + + def __init__(self, + *, + message_type: str = None, + text: str = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + suggestion_id: str = None, + attachments: List['MessageInputAttachment'] = None, + analytics: 'RequestAnalytics' = None, + options: 'MessageInputOptionsStateless' = None) -> None: """ - Initialize a Release object. + Initialize a MessageInputStateless object. - :param str release: (optional) The name of the release. The name is the - version number (an integer), returned as a string. - :param str description: (optional) The description of the release. - :param str status: (optional) The current status of the release: - - **Available**: The release is available for deployment. - - **Failed**: An asynchronous publish operation has failed. - - **Processing**: An asynchronous publish operation has not yet completed. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param MessageInputOptionsStateless options: (optional) Optional properties + that control how the assistant responds. """ - self.release = release - self.description = description - self.environment_references = environment_references - self.content = content - self.status = status - self.created = created - self.updated = updated + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'Release': - """Initialize a Release object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': + """Initialize a MessageInputStateless object from a json dictionary.""" args = {} - if 'release' in _dict: - args['release'] = _dict.get('release') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'environment_references' in _dict: - args['environment_references'] = [ - EnvironmentReference.from_dict(v) - for v in _dict.get('environment_references') + if 'message_type' in _dict: + args['message_type'] = _dict.get('message_type') + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent.from_dict(v) for v in _dict.get('intents') ] - if 'content' in _dict: - args['content'] = ReleaseContent.from_dict(_dict.get('content')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity.from_dict(v) for v in _dict.get('entities') + ] + if 'suggestion_id' in _dict: + args['suggestion_id'] = _dict.get('suggestion_id') + if 'attachments' in _dict: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) + for v in _dict.get('attachments') + ] + if 'analytics' in _dict: + args['analytics'] = RequestAnalytics.from_dict( + _dict.get('analytics')) + if 'options' in _dict: + args['options'] = MessageInputOptionsStateless.from_dict( + _dict.get('options')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Release object from a json dictionary.""" + """Initialize a MessageInputStateless 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, 'release') and self.release is not None: - _dict['release'] = self.release - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'environment_references') and getattr( - self, 'environment_references') is not None: - environment_references_list = [] - for v in getattr(self, 'environment_references'): + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: if isinstance(v, dict): - environment_references_list.append(v) + intents_list.append(v) else: - environment_references_list.append(v.to_dict()) - _dict['environment_references'] = environment_references_list - if hasattr(self, 'content') and getattr(self, 'content') is not None: - if isinstance(getattr(self, 'content'), dict): - _dict['content'] = getattr(self, 'content') + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics else: - _dict['content'] = getattr(self, 'content').to_dict() - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -5538,93 +5860,174 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Release object.""" + """Return a `str` version of this MessageInputStateless object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Release') -> bool: + def __eq__(self, other: 'MessageInputStateless') -> 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: 'Release') -> bool: + def __ne__(self, other: 'MessageInputStateless') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): + class MessageTypeEnum(str, Enum): """ - The current status of the release: - - **Available**: The release is available for deployment. - - **Failed**: An asynchronous publish operation has failed. - - **Processing**: An asynchronous publish operation has not yet completed. + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. """ - AVAILABLE = 'Available' - FAILED = 'Failed' - PROCESSING = 'Processing' + TEXT = 'text' + SEARCH = 'search' -class ReleaseCollection(): +class MessageOutput(): """ - ReleaseCollection. + Assistant output to be rendered or processed by the client. - :attr List[Release] releases: An array of objects describing the releases - associated with an assistant. - :attr Pagination pagination: The pagination data for the returned objects. + :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :attr List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :attr List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :attr MessageOutputDebug debug: (optional) Additional detailed information about + a message response and how it was generated. + :attr dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :attr MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ - def __init__(self, releases: List['Release'], - pagination: 'Pagination') -> None: + def __init__(self, + *, + generic: List['RuntimeResponseGeneric'] = None, + intents: List['RuntimeIntent'] = None, + entities: List['RuntimeEntity'] = None, + actions: List['DialogNodeAction'] = None, + debug: 'MessageOutputDebug' = None, + user_defined: dict = None, + spelling: 'MessageOutputSpelling' = None) -> None: """ - Initialize a ReleaseCollection object. + Initialize a MessageOutput object. - :param List[Release] releases: An array of objects describing the releases - associated with an assistant. - :param Pagination pagination: The pagination data for the returned objects. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ - self.releases = releases - self.pagination = pagination + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': - """Initialize a ReleaseCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutput': + """Initialize a MessageOutput object from a json dictionary.""" args = {} - if 'releases' in _dict: - args['releases'] = [ - Release.from_dict(v) for v in _dict.get('releases') - ] - else: - raise ValueError( - 'Required property \'releases\' not present in ReleaseCollection JSON' - ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) - else: - raise ValueError( - 'Required property \'pagination\' not present in ReleaseCollection JSON' - ) + if 'generic' in _dict: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) + for v in _dict.get('generic') + ] + if 'intents' in _dict: + args['intents'] = [ + RuntimeIntent.from_dict(v) for v in _dict.get('intents') + ] + if 'entities' in _dict: + args['entities'] = [ + RuntimeEntity.from_dict(v) for v in _dict.get('entities') + ] + if 'actions' in _dict: + args['actions'] = [ + DialogNodeAction.from_dict(v) for v in _dict.get('actions') + ] + if 'debug' in _dict: + args['debug'] = MessageOutputDebug.from_dict(_dict.get('debug')) + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + if 'spelling' in _dict: + args['spelling'] = MessageOutputSpelling.from_dict( + _dict.get('spelling')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseCollection object from a json dictionary.""" + """Initialize a MessageOutput 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, 'releases') and self.releases is not None: - releases_list = [] - for v in self.releases: + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: if isinstance(v, dict): - releases_list.append(v) + generic_list.append(v) else: - releases_list.append(v.to_dict()) - _dict['releases'] = releases_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug else: - _dict['pagination'] = self.pagination.to_dict() + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() return _dict def _to_dict(self): @@ -5632,62 +6035,133 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseCollection object.""" + """Return a `str` version of this MessageOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseCollection') -> bool: + def __eq__(self, other: 'MessageOutput') -> 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: 'ReleaseCollection') -> bool: + def __ne__(self, other: 'MessageOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ReleaseContent(): +class MessageOutputDebug(): """ - An object describing the versionable content objects (such as skill snapshots) that - are included in the release. + Additional detailed information about a message response and how it was generated. - :attr List[ReleaseSkillReference] skills: (optional) The skill snapshots that - are included in the release. + :attr List[DialogNodeVisited] nodes_visited: (optional) An array of objects + containing detailed diagnostic information about dialog nodes that were visited + during processing of the input message. + :attr List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :attr bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` + by the assistant, the `branch_exited_reason` specifies whether the dialog + completed by itself or got interrupted. + :attr List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of + objects containing detailed diagnostic information about dialog nodes and + actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. """ - def __init__(self, *, skills: List['ReleaseSkillReference'] = None) -> None: + def __init__( + self, + *, + nodes_visited: List['DialogNodeVisited'] = None, + log_messages: List['DialogLogMessage'] = None, + branch_exited: bool = None, + branch_exited_reason: str = None, + turn_events: List['MessageOutputDebugTurnEvent'] = None) -> None: """ - Initialize a ReleaseContent object. + Initialize a MessageOutputDebug object. + :param List[DialogNodeVisited] nodes_visited: (optional) An array of + objects containing detailed diagnostic information about dialog nodes that + were visited during processing of the input message. + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :param bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the + dialog completed by itself or got interrupted. + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array + of objects containing detailed diagnostic information about dialog nodes + and actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. """ - self.skills = skills + self.nodes_visited = nodes_visited + self.log_messages = log_messages + self.branch_exited = branch_exited + self.branch_exited_reason = branch_exited_reason + self.turn_events = turn_events @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseContent': - """Initialize a ReleaseContent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': + """Initialize a MessageOutputDebug object from a json dictionary.""" args = {} - if 'skills' in _dict: - args['skills'] = [ - ReleaseSkillReference.from_dict(v) for v in _dict.get('skills') + if 'nodes_visited' in _dict: + args['nodes_visited'] = [ + DialogNodeVisited.from_dict(v) + for v in _dict.get('nodes_visited') + ] + if 'log_messages' in _dict: + args['log_messages'] = [ + DialogLogMessage.from_dict(v) for v in _dict.get('log_messages') + ] + if 'branch_exited' in _dict: + args['branch_exited'] = _dict.get('branch_exited') + if 'branch_exited_reason' in _dict: + args['branch_exited_reason'] = _dict.get('branch_exited_reason') + if 'turn_events' in _dict: + args['turn_events'] = [ + MessageOutputDebugTurnEvent.from_dict(v) + for v in _dict.get('turn_events') ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseContent object from a json dictionary.""" + """Initialize a MessageOutputDebug 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, 'skills') and getattr(self, 'skills') is not None: - skills_list = [] - for v in getattr(self, 'skills'): + if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: + nodes_visited_list = [] + for v in self.nodes_visited: if isinstance(v, dict): - skills_list.append(v) + nodes_visited_list.append(v) else: - skills_list.append(v.to_dict()) - _dict['skills'] = skills_list + nodes_visited_list.append(v.to_dict()) + _dict['nodes_visited'] = nodes_visited_list + if hasattr(self, 'log_messages') and self.log_messages is not None: + log_messages_list = [] + for v in self.log_messages: + if isinstance(v, dict): + log_messages_list.append(v) + else: + log_messages_list.append(v.to_dict()) + _dict['log_messages'] = log_messages_list + if hasattr(self, 'branch_exited') and self.branch_exited is not None: + _dict['branch_exited'] = self.branch_exited + if hasattr(self, 'branch_exited_reason' + ) and self.branch_exited_reason is not None: + _dict['branch_exited_reason'] = self.branch_exited_reason + if hasattr(self, 'turn_events') and self.turn_events is not None: + turn_events_list = [] + for v in self.turn_events: + if isinstance(v, dict): + turn_events_list.append(v) + else: + turn_events_list.append(v.to_dict()) + _dict['turn_events'] = turn_events_list return _dict def _to_dict(self): @@ -5695,73 +6169,172 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseContent object.""" + """Return a `str` version of this MessageOutputDebug object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseContent') -> bool: + def __eq__(self, other: 'MessageOutputDebug') -> 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: 'ReleaseContent') -> bool: + def __ne__(self, other: 'MessageOutputDebug') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class BranchExitedReasonEnum(str, Enum): + """ + When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` + specifies whether the dialog completed by itself or got interrupted. + """ + COMPLETED = 'completed' + FALLBACK = 'fallback' + -class ReleaseSkillReference(): +class MessageOutputDebugTurnEvent(): """ - ReleaseSkillReference. + MessageOutputDebugTurnEvent. - :attr str skill_id: (optional) The skill ID of the skill. - :attr str type: (optional) The type of the skill. - :attr str snapshot: (optional) The name of the snapshot (skill version) that is - saved as part of the release (for example, `draft` or `1`). """ - def __init__(self, - *, - skill_id: str = None, - type: str = None, - snapshot: str = None) -> None: + def __init__(self) -> None: """ - Initialize a ReleaseSkillReference object. + Initialize a MessageOutputDebugTurnEvent object. - :param str skill_id: (optional) The skill ID of the skill. - :param str type: (optional) The type of the skill. - :param str snapshot: (optional) The name of the snapshot (skill version) - that is saved as part of the release (for example, `draft` or `1`). """ - self.skill_id = skill_id - self.type = type - self.snapshot = snapshot - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseSkillReference': - """Initialize a ReleaseSkillReference object from a json dictionary.""" - args = {} - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') - return cls(**args) + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited' + ])) + raise Exception(msg) @classmethod - def _from_dict(cls, _dict): - """Initialize a ReleaseSkillReference 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, 'skill_id') and self.skill_id is not None: - _dict['skill_id'] = self.skill_id - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = ( + "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'action_visited'] = 'MessageOutputDebugTurnEventTurnEventActionVisited' + mapping[ + 'action_finished'] = 'MessageOutputDebugTurnEventTurnEventActionFinished' + mapping[ + 'step_visited'] = 'MessageOutputDebugTurnEventTurnEventStepVisited' + mapping[ + 'step_answered'] = 'MessageOutputDebugTurnEventTurnEventStepAnswered' + mapping[ + 'handler_visited'] = 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + mapping['callout'] = 'MessageOutputDebugTurnEventTurnEventCallout' + mapping['search'] = 'MessageOutputDebugTurnEventTurnEventSearch' + mapping[ + 'node_visited'] = 'MessageOutputDebugTurnEventTurnEventNodeVisited' + disc_value = _dict.get('event') + if disc_value is None: + raise ValueError( + 'Discriminator property \'event\' not found in MessageOutputDebugTurnEvent JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class MessageOutputSpelling(): + """ + Properties describing any spelling corrections in the user input that was received. + + :attr str text: (optional) The user input text that was used to generate the + response. If spelling autocorrection is enabled, this text reflects any spelling + corrections that were applied. + :attr str original_text: (optional) The original user input text. This property + is returned only if autocorrection is enabled and the user input was corrected. + :attr str suggested_text: (optional) Any suggested corrections of the input + text. This property is returned only if spelling correction is enabled and + autocorrection is disabled. + """ + + def __init__(self, + *, + text: str = None, + original_text: str = None, + suggested_text: str = None) -> None: + """ + Initialize a MessageOutputSpelling object. + + :param str text: (optional) The user input text that was used to generate + the response. If spelling autocorrection is enabled, this text reflects any + spelling corrections that were applied. + :param str original_text: (optional) The original user input text. This + property is returned only if autocorrection is enabled and the user input + was corrected. + :param str suggested_text: (optional) Any suggested corrections of the + input text. This property is returned only if spelling correction is + enabled and autocorrection is disabled. + """ + self.text = text + self.original_text = original_text + self.suggested_text = suggested_text + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': + """Initialize a MessageOutputSpelling object from a json dictionary.""" + args = {} + if 'text' in _dict: + args['text'] = _dict.get('text') + if 'original_text' in _dict: + args['original_text'] = _dict.get('original_text') + if 'suggested_text' in _dict: + args['suggested_text'] = _dict.get('suggested_text') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageOutputSpelling 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, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'original_text') and self.original_text is not None: + _dict['original_text'] = self.original_text + if hasattr(self, 'suggested_text') and self.suggested_text is not None: + _dict['suggested_text'] = self.suggested_text return _dict def _to_dict(self): @@ -5769,62 +6342,107 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseSkillReference object.""" + """Return a `str` version of this MessageOutputSpelling object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseSkillReference') -> bool: + def __eq__(self, other: 'MessageOutputSpelling') -> 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: 'ReleaseSkillReference') -> bool: + def __ne__(self, other: 'MessageOutputSpelling') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of the skill. - """ - DIALOG = 'dialog' - ACTION = 'action' - SEARCH = 'search' - -class ResponseGenericChannel(): +class MessageRequest(): """ - ResponseGenericChannel. + A stateful message request formatted for the Watson Assistant service. - :attr str channel: (optional) A channel for which the response is intended. + :attr MessageInput input: (optional) An input object that includes the input + text. + :attr MessageContext context: (optional) Context data for the conversation. You + can use this property to set or modify context variables, which can also be + accessed by dialog nodes. The context is stored by the assistant on a + per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. If **user_id** is specified in both locations, the value + specified at the root is used. """ - def __init__(self, *, channel: str = None) -> None: + def __init__(self, + *, + input: 'MessageInput' = None, + context: 'MessageContext' = None, + user_id: str = None) -> None: """ - Initialize a ResponseGenericChannel object. + Initialize a MessageRequest object. - :param str channel: (optional) A channel for which the response is - intended. + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. """ - self.channel = channel + self.input = input + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': - """Initialize a ResponseGenericChannel object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageRequest': + """Initialize a MessageRequest object from a json dictionary.""" args = {} - if 'channel' in _dict: - args['channel'] = _dict.get('channel') + if 'input' in _dict: + args['input'] = MessageInput.from_dict(_dict.get('input')) + if 'context' in _dict: + args['context'] = MessageContext.from_dict(_dict.get('context')) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ResponseGenericChannel object from a json dictionary.""" + """Initialize a MessageRequest 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, 'channel') and self.channel is not None: - _dict['channel'] = self.channel + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input + else: + _dict['input'] = self.input.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -5832,195 +6450,113 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ResponseGenericChannel object.""" + """Return a `str` version of this MessageRequest object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ResponseGenericChannel') -> bool: + def __eq__(self, other: 'MessageRequest') -> 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: 'ResponseGenericChannel') -> bool: + def __ne__(self, other: 'MessageRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntity(): +class MessageResponse(): """ - The entity value that was recognized in the user input. + A response from the Watson Assistant service. - :attr str entity: An entity detected in the input. - :attr List[int] location: (optional) An array of zero-based character offsets - that indicate where the detected entity values begin and end in the input text. - :attr str value: The term in the input text that was recognized as an entity - value. - :attr float confidence: (optional) A decimal percentage that represents Watson's - confidence in the recognized 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. - :attr str skill: (optional) The skill that recognized the entity value. - Currently, the only possible values are `main skill` for the dialog skill (if - enabled) and `actions skill` for the actions skill. - This property is present only if the assistant has both a dialog skill and an - actions skill. - """ + :attr MessageOutput output: Assistant output to be rendered or processed by the + client. + :attr MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :attr str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + """ def __init__(self, - entity: str, - value: str, + output: 'MessageOutput', + user_id: str, *, - location: List[int] = None, - confidence: float = None, - groups: List['CaptureGroup'] = None, - interpretation: 'RuntimeEntityInterpretation' = None, - alternatives: List['RuntimeEntityAlternative'] = None, - role: 'RuntimeEntityRole' = None, - skill: str = None) -> None: + context: 'MessageContext' = None) -> None: """ - Initialize a RuntimeEntity object. + Initialize a MessageResponse object. - :param str entity: An entity detected in the input. - :param str value: The term in the input text that was recognized as an - entity value. - :param List[int] location: (optional) An array of zero-based character - offsets that indicate where the detected entity values begin and end in the - input text. - :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized 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. - :param str skill: (optional) The skill that recognized the entity value. - Currently, the only possible values are `main skill` for the dialog skill - (if enabled) and `actions skill` for the actions skill. - This property is present only if the assistant has both a dialog skill and - an actions skill. + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. """ - self.entity = entity - self.location = location - self.value = value - self.confidence = confidence - self.groups = groups - self.interpretation = interpretation - self.alternatives = alternatives - self.role = role - self.skill = skill + self.output = output + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': - """Initialize a RuntimeEntity object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageResponse': + """Initialize a MessageResponse object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if 'output' in _dict: + args['output'] = MessageOutput.from_dict(_dict.get('output')) else: raise ValueError( - 'Required property \'entity\' not present in RuntimeEntity JSON' + 'Required property \'output\' not present in MessageResponse JSON' ) - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'value' in _dict: - args['value'] = _dict.get('value') + if 'context' in _dict: + args['context'] = MessageContext.from_dict(_dict.get('context')) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') else: raise ValueError( - 'Required property \'value\' not present in RuntimeEntity JSON') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'groups' in _dict: - args['groups'] = [ - CaptureGroup.from_dict(v) for v 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(v) - for v in _dict.get('alternatives') - ] - if 'role' in _dict: - args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) - if 'skill' in _dict: - args['skill'] = _dict.get('skill') + 'Required property \'user_id\' not present in MessageResponse JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntity object from a json dictionary.""" + """Initialize a MessageResponse 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, 'entity') and self.entity is not None: - _dict['entity'] = self.entity - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location - 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 - if hasattr(self, 'groups') and self.groups is not None: - groups_list = [] - for v in self.groups: - if isinstance(v, dict): - groups_list.append(v) - else: - groups_list.append(v.to_dict()) - _dict['groups'] = groups_list - if hasattr(self, 'interpretation') and self.interpretation is not None: - if isinstance(self.interpretation, dict): - _dict['interpretation'] = self.interpretation + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output else: - _dict['interpretation'] = self.interpretation.to_dict() - if hasattr(self, 'alternatives') and self.alternatives is not None: - alternatives_list = [] - for v in self.alternatives: - if isinstance(v, dict): - alternatives_list.append(v) - else: - alternatives_list.append(v.to_dict()) - _dict['alternatives'] = alternatives_list - if hasattr(self, 'role') and self.role is not None: - if isinstance(self.role, dict): - _dict['role'] = self.role + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context else: - _dict['role'] = self.role.to_dict() - if hasattr(self, 'skill') and self.skill is not None: - _dict['skill'] = self.skill + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -6028,64 +6564,110 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntity object.""" + """Return a `str` version of this MessageResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntity') -> bool: + def __eq__(self, other: 'MessageResponse') -> 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: 'RuntimeEntity') -> bool: + def __ne__(self, other: 'MessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityAlternative(): +class MessageResponseStateless(): """ - An alternative value for the recognized entity. + A stateless response from the Watson Assistant service. - :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. + :attr MessageOutput output: Assistant output to be rendered or processed by the + client. + :attr MessageContextStateless context: Context data for the conversation. You + can use this property to access context variables. The context is not stored by + the assistant; to maintain session state, include the context from the response + in the next message. + :attr str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ - def __init__(self, *, value: str = None, confidence: float = None) -> None: + def __init__(self, + output: 'MessageOutput', + context: 'MessageContextStateless', + *, + user_id: str = None) -> None: """ - Initialize a RuntimeEntityAlternative object. + Initialize a MessageResponseStateless 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. + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param MessageContextStateless context: Context data for the conversation. + You can use this property to access context variables. The context is not + stored by the assistant; to maintain session state, include the context + from the response in the next message. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. """ - self.value = value - self.confidence = confidence + self.output = output + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': + """Initialize a MessageResponseStateless object from a json dictionary.""" args = {} - 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 + if 'output' in _dict: + args['output'] = MessageOutput.from_dict(_dict.get('output')) + else: + raise ValueError( + 'Required property \'output\' not present in MessageResponseStateless JSON' + ) + if 'context' in _dict: + args['context'] = MessageContextStateless.from_dict( + _dict.get('context')) + else: + raise ValueError( + 'Required property \'context\' not present in MessageResponseStateless JSON' + ) + if 'user_id' in _dict: + args['user_id'] = _dict.get('user_id') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageResponseStateless 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, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -6093,209 +6675,1077 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityAlternative object.""" + """Return a `str` version of this MessageResponseStateless object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + def __eq__(self, other: 'MessageResponseStateless') -> 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: + def __ne__(self, other: 'MessageResponseStateless') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityInterpretation(): +class Pagination(): """ - RuntimeEntityInterpretation. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). - :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`). + :attr str refresh_url: The URL that will return the same page of results. + :attr str next_url: (optional) The URL that will return the next page of + results. + :attr int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the current + page. + :attr int matched: (optional) Reserved for future use. + :attr str refresh_cursor: (optional) A token identifying the current page of + results. + :attr str next_cursor: (optional) A token identifying the next page of results. """ def __init__(self, + refresh_url: str, *, - 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: + next_url: str = None, + total: int = None, + matched: int = None, + refresh_cursor: str = None, + next_cursor: str = None) -> None: """ - Initialize a RuntimeEntityInterpretation object. + Initialize a Pagination 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`). + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the + current page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page + of results. + :param str next_cursor: (optional) A token identifying the next page of + results. """ - 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.refresh_url = refresh_url + self.next_url = next_url + self.total = total + self.matched = matched + self.refresh_cursor = refresh_cursor + self.next_cursor = next_cursor + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Pagination': + """Initialize a Pagination object from a json dictionary.""" + args = {} + if 'refresh_url' in _dict: + args['refresh_url'] = _dict.get('refresh_url') + else: + raise ValueError( + 'Required property \'refresh_url\' not present in Pagination JSON' + ) + if 'next_url' in _dict: + args['next_url'] = _dict.get('next_url') + if 'total' in _dict: + args['total'] = _dict.get('total') + if 'matched' in _dict: + args['matched'] = _dict.get('matched') + if 'refresh_cursor' in _dict: + args['refresh_cursor'] = _dict.get('refresh_cursor') + if 'next_cursor' in _dict: + args['next_cursor'] = _dict.get('next_cursor') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Pagination 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, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'total') and self.total is not None: + _dict['total'] = self.total + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: + _dict['refresh_cursor'] = self.refresh_cursor + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor + 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 Pagination object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Pagination') -> 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: 'Pagination') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Release(): + """ + Release. + + :attr str release: (optional) The name of the release. The name is the version + number (an integer), returned as a string. + :attr str description: (optional) The description of the release. + :attr List[EnvironmentReference] environment_references: (optional) An array of + objects describing the environments where this release has been deployed. + :attr ReleaseContent content: (optional) An object identifying the versionable + content objects (such as skill snapshots) that are included in the release. + :attr str status: (optional) The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + :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. + """ + + def __init__(self, + *, + release: str = None, + description: str = None, + environment_references: List['EnvironmentReference'] = None, + content: 'ReleaseContent' = None, + status: str = None, + created: datetime = None, + updated: datetime = None) -> None: + """ + Initialize a Release object. + + :param str description: (optional) The description of the release. + """ + self.release = release + self.description = description + self.environment_references = environment_references + self.content = content + self.status = status + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Release': + """Initialize a Release object from a json dictionary.""" + args = {} + if 'release' in _dict: + args['release'] = _dict.get('release') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'environment_references' in _dict: + args['environment_references'] = [ + EnvironmentReference.from_dict(v) + for v in _dict.get('environment_references') + ] + if 'content' in _dict: + args['content'] = ReleaseContent.from_dict(_dict.get('content')) + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'created' in _dict: + args['created'] = string_to_datetime(_dict.get('created')) + if 'updated' in _dict: + args['updated'] = string_to_datetime(_dict.get('updated')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Release 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, 'release') and getattr(self, 'release') is not None: + _dict['release'] = getattr(self, 'release') + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'environment_references') and getattr( + self, 'environment_references') is not None: + environment_references_list = [] + for v in getattr(self, 'environment_references'): + if isinstance(v, dict): + environment_references_list.append(v) + else: + environment_references_list.append(v.to_dict()) + _dict['environment_references'] = environment_references_list + if hasattr(self, 'content') and getattr(self, 'content') is not None: + if isinstance(getattr(self, 'content'), dict): + _dict['content'] = getattr(self, 'content') + else: + _dict['content'] = getattr(self, 'content').to_dict() + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + 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 Release object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Release') -> 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: 'Release') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + """ + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class ReleaseCollection(): + """ + ReleaseCollection. + + :attr List[Release] releases: An array of objects describing the releases + associated with an assistant. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). + """ + + def __init__(self, releases: List['Release'], + pagination: 'Pagination') -> None: + """ + Initialize a ReleaseCollection object. + + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + self.releases = releases + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': + """Initialize a ReleaseCollection object from a json dictionary.""" + args = {} + if 'releases' in _dict: + args['releases'] = [ + Release.from_dict(v) for v in _dict.get('releases') + ] + else: + raise ValueError( + 'Required property \'releases\' not present in ReleaseCollection JSON' + ) + if 'pagination' in _dict: + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in ReleaseCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseCollection 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, 'releases') and self.releases is not None: + releases_list = [] + for v in self.releases: + if isinstance(v, dict): + releases_list.append(v) + else: + releases_list.append(v.to_dict()) + _dict['releases'] = releases_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() + 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 ReleaseCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseCollection') -> 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: 'ReleaseCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseContent(): + """ + An object identifying the versionable content objects (such as skill snapshots) that + are included in the release. + + :attr List[ReleaseSkill] skills: (optional) The skill snapshots that are + included in the release. + """ + + def __init__(self, *, skills: List['ReleaseSkill'] = None) -> None: + """ + Initialize a ReleaseContent object. + + """ + self.skills = skills + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseContent': + """Initialize a ReleaseContent object from a json dictionary.""" + args = {} + if 'skills' in _dict: + args['skills'] = [ + ReleaseSkill.from_dict(v) for v in _dict.get('skills') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseContent 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, 'skills') and getattr(self, 'skills') is not None: + skills_list = [] + for v in getattr(self, 'skills'): + if isinstance(v, dict): + skills_list.append(v) + else: + skills_list.append(v.to_dict()) + _dict['skills'] = skills_list + 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 ReleaseContent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseContent') -> 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: 'ReleaseContent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseSkill(): + """ + ReleaseSkill. + + :attr str skill_id: The skill ID of the skill. + :attr str type: (optional) The type of the skill. + :attr str snapshot: (optional) The name of the skill snapshot that is saved as + part of the release (for example, `draft` or `1`). + """ + + def __init__(self, + skill_id: str, + *, + type: str = None, + snapshot: str = None) -> None: + """ + Initialize a ReleaseSkill object. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is + saved as part of the release (for example, `draft` or `1`). + """ + self.skill_id = skill_id + self.type = type + self.snapshot = snapshot + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': + """Initialize a ReleaseSkill object from a json dictionary.""" + args = {} + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + else: + raise ValueError( + 'Required property \'skill_id\' not present in ReleaseSkill JSON' + ) + if 'type' in _dict: + args['type'] = _dict.get('type') + if 'snapshot' in _dict: + args['snapshot'] = _dict.get('snapshot') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseSkill 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, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + 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 ReleaseSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseSkill') -> 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: 'ReleaseSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of the skill. + """ + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + + +class RequestAnalytics(): + """ + An optional object containing analytics data. Currently, this data is used only for + events sent to the Segment extension. + + :attr str browser: (optional) The browser that was used to send the message that + triggered the event. + :attr str device: (optional) The type of device that was used to send the + message that triggered the event. + :attr str page_url: (optional) The URL of the web page that was used to send the + message that triggered the event. + """ + + def __init__(self, + *, + browser: str = None, + device: str = None, + page_url: str = None) -> None: + """ + Initialize a RequestAnalytics object. + + :param str browser: (optional) The browser that was used to send the + message that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to + send the message that triggered the event. + """ + self.browser = browser + self.device = device + self.page_url = page_url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': + """Initialize a RequestAnalytics object from a json dictionary.""" + args = {} + if 'browser' in _dict: + args['browser'] = _dict.get('browser') + if 'device' in _dict: + args['device'] = _dict.get('device') + if 'pageUrl' in _dict: + args['page_url'] = _dict.get('pageUrl') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RequestAnalytics 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, 'browser') and self.browser is not None: + _dict['browser'] = self.browser + if hasattr(self, 'device') and self.device is not None: + _dict['device'] = self.device + if hasattr(self, 'page_url') and self.page_url is not None: + _dict['pageUrl'] = self.page_url + 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 RequestAnalytics object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RequestAnalytics') -> 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: 'RequestAnalytics') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericChannel(): + """ + ResponseGenericChannel. + + :attr str channel: (optional) A channel for which the response is intended. + """ + + def __init__(self, *, channel: str = None) -> None: + """ + Initialize a ResponseGenericChannel object. + + :param str channel: (optional) A channel for which the response is + intended. + """ + self.channel = channel + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': + """Initialize a ResponseGenericChannel object from a json dictionary.""" + args = {} + if 'channel' in _dict: + args['channel'] = _dict.get('channel') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericChannel 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, 'channel') and self.channel is not None: + _dict['channel'] = self.channel + 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 ResponseGenericChannel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericChannel') -> 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: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntity(): + """ + The entity value that was recognized in the user input. + + :attr str entity: An entity detected in the input. + :attr List[int] location: (optional) An array of zero-based character offsets + that indicate where the detected entity values begin and end in the input text. + :attr str value: The term in the input text that was recognized as an entity + value. + :attr float confidence: (optional) A decimal percentage that represents Watson's + confidence in the recognized 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. + :attr str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill (if + enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__(self, + entity: str, + value: str, + *, + location: List[int] = None, + confidence: float = None, + groups: List['CaptureGroup'] = None, + interpretation: 'RuntimeEntityInterpretation' = None, + alternatives: List['RuntimeEntityAlternative'] = None, + role: 'RuntimeEntityRole' = None, + skill: str = None) -> None: + """ + Initialize a RuntimeEntity object. + + :param str entity: An entity detected in the input. + :param str value: The term in the input text that was recognized as an + entity value. + :param List[int] location: (optional) An array of zero-based character + offsets that indicate where the detected entity values begin and end in the + input text. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the recognized 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. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.entity = entity + self.location = location + self.value = value + self.confidence = confidence + self.groups = groups + self.interpretation = interpretation + self.alternatives = alternatives + self.role = role + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': + """Initialize a RuntimeEntity object from a json dictionary.""" + args = {} + if 'entity' in _dict: + args['entity'] = _dict.get('entity') + else: + raise ValueError( + 'Required property \'entity\' not present in RuntimeEntity JSON' + ) + if 'location' in _dict: + args['location'] = _dict.get('location') + if 'value' in _dict: + args['value'] = _dict.get('value') + else: + raise ValueError( + 'Required property \'value\' not present in RuntimeEntity JSON') + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + if 'groups' in _dict: + args['groups'] = [ + CaptureGroup.from_dict(v) for v 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(v) + for v in _dict.get('alternatives') + ] + if 'role' in _dict: + args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) + if 'skill' in _dict: + args['skill'] = _dict.get('skill') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntity 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, 'entity') and self.entity is not None: + _dict['entity'] = self.entity + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + 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 + if hasattr(self, 'groups') and self.groups is not None: + groups_list = [] + for v in self.groups: + if isinstance(v, dict): + groups_list.append(v) + else: + groups_list.append(v.to_dict()) + _dict['groups'] = groups_list + if hasattr(self, 'interpretation') and self.interpretation is not None: + if isinstance(self.interpretation, dict): + _dict['interpretation'] = self.interpretation + else: + _dict['interpretation'] = self.interpretation.to_dict() + if hasattr(self, 'alternatives') and self.alternatives is not None: + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list + if hasattr(self, 'role') and self.role is not None: + if isinstance(self.role, dict): + _dict['role'] = self.role + else: + _dict['role'] = self.role.to_dict() + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + 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 RuntimeEntity object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntity') -> 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: 'RuntimeEntity') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + 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 = {} + 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 @@ -6314,130 +7764,634 @@ def __init__(self, self.timezone = timezone @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': + """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + args = {} + 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(str, 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 = {} + 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(str, 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. + + :attr str intent: The name of the recognized intent. + :attr float confidence: (optional) A decimal percentage that represents Watson's + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. + :attr str skill: (optional) The skill that identified the intent. Currently, the + only possible values are `main skill` for the dialog skill (if enabled) and + `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__(self, + intent: str, + *, + confidence: float = None, + skill: str = None) -> None: + """ + Initialize a RuntimeIntent object. + + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the intent. If you are specifying an intent as part + of a request, but you do not have a calculated confidence value, specify + `1`. + :param str skill: (optional) The skill that identified the intent. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.intent = intent + self.confidence = confidence + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': + """Initialize a RuntimeIntent object from a json dictionary.""" + args = {} + if 'intent' in _dict: + args['intent'] = _dict.get('intent') + else: + raise ValueError( + 'Required property \'intent\' not present in RuntimeIntent JSON' + ) + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + if 'skill' in _dict: + args['skill'] = _dict.get('skill') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeIntent 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, 'intent') and self.intent is not None: + _dict['intent'] = self.intent + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + 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 RuntimeIntent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeIntent') -> 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: 'RuntimeIntent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGeneric(): + """ + RuntimeResponseGeneric. + + """ + + def __init__(self) -> None: + """ + Initialize a RuntimeResponseGeneric object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = ( + "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " + + "The discriminator value should map to a valid subclass: {1}" + ).format(", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' + mapping[ + 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + mapping[ + 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' + mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' + mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' + mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' + mapping[ + 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' + mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' + mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + mapping[ + 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class SearchResult(): + """ + SearchResult. + + :attr str id: The unique identifier of the document in the Discovery service + collection. + This property is included in responses from search skills, which are available + only to Plus or Enterprise plan users. + :attr SearchResultMetadata result_metadata: An object containing search result + metadata from the Discovery service. + :attr str body: (optional) A description of the search result. This is taken + from an abstract, summary, or highlight field in the Discovery service response, + as specified in the search skill configuration. + :attr str title: (optional) The title of the search result. This is taken from a + title or name field in the Discovery service response, as specified in the + search skill configuration. + :attr str url: (optional) The URL of the original data object in its native data + source. + :attr SearchResultHighlight highlight: (optional) An object containing segments + of text from search results with query-matching text highlighted using HTML + `` tags. + :attr List[SearchResultAnswer] answers: (optional) An array specifying segments + of text within the result that were identified as direct answers to the search + query. Currently, only the single answer with the highest confidence (if any) is + returned. + **Notes:** + - This property uses the answer finding beta feature, and is available only if + the search skill is connected to a Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + + def __init__(self, + id: str, + result_metadata: 'SearchResultMetadata', + *, + body: str = None, + title: str = None, + url: str = None, + highlight: 'SearchResultHighlight' = None, + answers: List['SearchResultAnswer'] = None) -> None: + """ + Initialize a SearchResult object. + + :param str id: The unique identifier of the document in the Discovery + service collection. + This property is included in responses from search skills, which are + available only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search + result metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is + taken from an abstract, summary, or highlight field in the Discovery + service response, as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken + from a title or name field in the Discovery service response, as specified + in the search skill configuration. + :param str url: (optional) The URL of the original data object in its + native data source. + :param SearchResultHighlight highlight: (optional) An object containing + segments of text from search results with query-matching text highlighted + using HTML `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying + segments of text within the result that were identified as direct answers + to the search query. Currently, only the single answer with the highest + confidence (if any) is returned. + **Notes:** + - This property uses the answer finding beta feature, and is available + only if the search skill is connected to a Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.id = id + self.result_metadata = result_metadata + self.body = body + self.title = title + self.url = url + self.highlight = highlight + self.answers = answers + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResult': + """Initialize a SearchResult object from a json dictionary.""" + args = {} + if 'id' in _dict: + args['id'] = _dict.get('id') + else: + raise ValueError( + 'Required property \'id\' not present in SearchResult JSON') + if 'result_metadata' in _dict: + args['result_metadata'] = SearchResultMetadata.from_dict( + _dict.get('result_metadata')) + else: + raise ValueError( + 'Required property \'result_metadata\' not present in SearchResult JSON' + ) + if 'body' in _dict: + args['body'] = _dict.get('body') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'url' in _dict: + args['url'] = _dict.get('url') + if 'highlight' in _dict: + args['highlight'] = SearchResultHighlight.from_dict( + _dict.get('highlight')) + if 'answers' in _dict: + args['answers'] = [ + SearchResultAnswer.from_dict(v) for v in _dict.get('answers') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResult 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, 'id') and self.id is not None: + _dict['id'] = self.id + if hasattr(self, + 'result_metadata') and self.result_metadata is not None: + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'highlight') and self.highlight is not None: + if isinstance(self.highlight, dict): + _dict['highlight'] = self.highlight + else: + _dict['highlight'] = self.highlight.to_dict() + if hasattr(self, 'answers') and self.answers is not None: + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list + 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 SearchResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResult') -> 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: 'SearchResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultAnswer(): + """ + An object specifing a segment of text that was identified as a direct answer to the + search query. + + :attr str text: The text of the answer. + :attr float confidence: The confidence score for the answer, as returned by the + Discovery service. + """ + + def __init__(self, text: str, confidence: float) -> None: + """ + Initialize a SearchResultAnswer object. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned + by the Discovery service. + """ + self.text = text + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': + """Initialize a SearchResultAnswer object from a json dictionary.""" args = {} - 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') + if 'text' in _dict: + args['text'] = _dict.get('text') + else: + raise ValueError( + 'Required property \'text\' not present in SearchResultAnswer JSON' + ) + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + else: + raise ValueError( + 'Required property \'confidence\' not present in SearchResultAnswer JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + """Initialize a SearchResultAnswer 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 + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence return _dict def _to_dict(self): @@ -6445,172 +8399,190 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityInterpretation object.""" + """Return a `str` version of this SearchResultAnswer object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + def __eq__(self, other: 'SearchResultAnswer') -> 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: + def __ne__(self, other: 'SearchResultAnswer') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class GranularityEnum(str, 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(): +class SearchResultHighlight(): """ - 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. + An object containing segments of text from search results with query-matching text + highlighted using HTML `` tags. - :attr str type: (optional) The relationship of the entity to the range. + :attr List[str] body: (optional) An array of strings containing segments taken + from body text in the search results, with query-matching substrings + highlighted. + :attr List[str] title: (optional) An array of strings containing segments taken + from title text in the search results, with query-matching substrings + highlighted. + :attr List[str] url: (optional) An array of strings containing segments taken + from URLs in the search results, with query-matching substrings highlighted. """ - def __init__(self, *, type: str = None) -> None: + # The set of defined properties for the class + _properties = frozenset(['body', 'title', 'url']) + + def __init__(self, + *, + body: List[str] = None, + title: List[str] = None, + url: List[str] = None, + **kwargs) -> None: """ - Initialize a RuntimeEntityRole object. + Initialize a SearchResultHighlight object. - :param str type: (optional) The relationship of the entity to the range. + :param List[str] body: (optional) An array of strings containing segments + taken from body text in the search results, with query-matching substrings + highlighted. + :param List[str] title: (optional) An array of strings containing segments + taken from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments + taken from URLs in the search results, with query-matching substrings + highlighted. + :param **kwargs: (optional) Any additional properties. """ - self.type = type + self.body = body + self.title = title + self.url = url + for _key, _value in kwargs.items(): + setattr(self, _key, _value) @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': - """Initialize a RuntimeEntityRole object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': + """Initialize a SearchResultHighlight object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if 'body' in _dict: + args['body'] = _dict.get('body') + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'url' in _dict: + args['url'] = _dict.get('url') + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityRole object from a json dictionary.""" + """Initialize a SearchResultHighlight 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 + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + _dict[_key] = getattr(self, _key) return _dict - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in SearchResultHighlight._properties: + setattr(self, _key, _value) def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityRole object.""" + """Return a `str` version of this SearchResultHighlight object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityRole') -> bool: + def __eq__(self, other: 'SearchResultHighlight') -> 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: + def __ne__(self, other: 'SearchResultHighlight') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, 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(): +class SearchResultMetadata(): """ - An intent identified in the user input. + An object containing search result metadata from the Discovery service. - :attr str intent: The name of the recognized intent. - :attr float confidence: (optional) A decimal percentage that represents Watson's - confidence in the intent. If you are specifying an intent as part of a request, - but you do not have a calculated confidence value, specify `1`. - :attr str skill: (optional) The skill that identified the intent. Currently, the - only possible values are `main skill` for the dialog skill (if enabled) and - `actions skill` for the actions skill. - This property is present only if the assistant has both a dialog skill and an - actions skill. + :attr float confidence: (optional) The confidence score for the given result, as + returned by the Discovery service. + :attr float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher score + indicates a greater match to the query parameters. """ def __init__(self, - intent: str, *, confidence: float = None, - skill: str = None) -> None: + score: float = None) -> None: """ - Initialize a RuntimeIntent object. + Initialize a SearchResultMetadata object. - :param str intent: The name of the recognized intent. - :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the intent. If you are specifying an intent as part - of a request, but you do not have a calculated confidence value, specify - `1`. - :param str skill: (optional) The skill that identified the intent. - Currently, the only possible values are `main skill` for the dialog skill - (if enabled) and `actions skill` for the actions skill. - This property is present only if the assistant has both a dialog skill and - an actions skill. + :param float confidence: (optional) The confidence score for the given + result, as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher + score indicates a greater match to the query parameters. """ - self.intent = intent self.confidence = confidence - self.skill = skill + self.score = score @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': - """Initialize a RuntimeIntent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': + """Initialize a SearchResultMetadata object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') - else: - raise ValueError( - 'Required property \'intent\' not present in RuntimeIntent JSON' - ) if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') - if 'skill' in _dict: - args['skill'] = _dict.get('skill') + if 'score' in _dict: + args['score'] = _dict.get('score') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeIntent object from a json dictionary.""" + """Initialize a SearchResultMetadata 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, 'intent') and self.intent is not None: - _dict['intent'] = self.intent if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence - if hasattr(self, 'skill') and self.skill is not None: - _dict['skill'] = self.skill + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score return _dict def _to_dict(self): @@ -6618,255 +8590,131 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeIntent object.""" + """Return a `str` version of this SearchResultMetadata object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeIntent') -> bool: + def __eq__(self, other: 'SearchResultMetadata') -> 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: 'RuntimeIntent') -> bool: + def __ne__(self, other: 'SearchResultMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeResponseGeneric(): +class SearchSkillWarning(): """ - RuntimeResponseGeneric. + A warning describing an error in the search skill configuration. + :attr str code: (optional) The error code. + :attr str path: (optional) The location of the error in the search skill + configuration object. + :attr str message: (optional) The error message. """ - def __init__(self) -> None: + def __init__(self, + *, + code: str = None, + path: str = None, + message: str = None) -> None: """ - Initialize a RuntimeResponseGeneric object. + Initialize a SearchSkillWarning object. + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) - raise Exception(msg) + self.code = code + self.path = path + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) - raise Exception(msg) + def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': + """Initialize a SearchSkillWarning object from a json dictionary.""" + args = {} + if 'code' in _dict: + args['code'] = _dict.get('code') + if 'path' in _dict: + args['path'] = _dict.get('path') + if 'message' in _dict: + args['message'] = _dict.get('message') + return cls(**args) @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + def _from_dict(cls, _dict): + """Initialize a SearchSkillWarning object from a json dictionary.""" return cls.from_dict(_dict) - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' - mapping[ - 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' - mapping[ - 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' - mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' - mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' - mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' - mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' - mapping[ - 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' - mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' - mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' - mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' - mapping[ - 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' - mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' - disc_value = _dict.get('response_type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + return _dict -class SearchResult(): - """ - SearchResult. + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() - :attr str id: The unique identifier of the document in the Discovery service - collection. - This property is included in responses from search skills, which are available - only to Plus or Enterprise plan users. - :attr SearchResultMetadata result_metadata: An object containing search result - metadata from the Discovery service. - :attr str body: (optional) A description of the search result. This is taken - from an abstract, summary, or highlight field in the Discovery service response, - as specified in the search skill configuration. - :attr str title: (optional) The title of the search result. This is taken from a - title or name field in the Discovery service response, as specified in the - search skill configuration. - :attr str url: (optional) The URL of the original data object in its native data - source. - :attr SearchResultHighlight highlight: (optional) An object containing segments - of text from search results with query-matching text highlighted using HTML - `` tags. - :attr List[SearchResultAnswer] answers: (optional) An array specifying segments - of text within the result that were identified as direct answers to the search - query. Currently, only the single answer with the highest confidence (if any) is - returned. - **Note:** This property uses the answer finding beta feature, and is available - only if the search skill is connected to a Discovery v2 service instance. - """ + def __str__(self) -> str: + """Return a `str` version of this SearchSkillWarning object.""" + return json.dumps(self.to_dict(), indent=2) - def __init__(self, - id: str, - result_metadata: 'SearchResultMetadata', - *, - body: str = None, - title: str = None, - url: str = None, - highlight: 'SearchResultHighlight' = None, - answers: List['SearchResultAnswer'] = None) -> None: - """ - Initialize a SearchResult object. + def __eq__(self, other: 'SearchSkillWarning') -> bool: + """Return `true` when self and other are equal, false otherwise.""" + if not isinstance(other, self.__class__): + return False + return self.__dict__ == other.__dict__ - :param str id: The unique identifier of the document in the Discovery - service collection. - This property is included in responses from search skills, which are - available only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search - result metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is - taken from an abstract, summary, or highlight field in the Discovery - service response, as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken - from a title or name field in the Discovery service response, as specified - in the search skill configuration. - :param str url: (optional) The URL of the original data object in its - native data source. - :param SearchResultHighlight highlight: (optional) An object containing - segments of text from search results with query-matching text highlighted - using HTML `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying - segments of text within the result that were identified as direct answers - to the search query. Currently, only the single answer with the highest - confidence (if any) is returned. - **Note:** This property uses the answer finding beta feature, and is - available only if the search skill is connected to a Discovery v2 service - instance. + def __ne__(self, other: 'SearchSkillWarning') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SessionResponse(): + """ + SessionResponse. + + :attr str session_id: The session ID. + """ + + def __init__(self, session_id: str) -> None: """ - self.id = id - self.result_metadata = result_metadata - self.body = body - self.title = title - self.url = url - self.highlight = highlight - self.answers = answers + Initialize a SessionResponse object. + + :param str session_id: The session ID. + """ + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResult': - """Initialize a SearchResult object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SessionResponse': + """Initialize a SessionResponse object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - else: - raise ValueError( - 'Required property \'id\' not present in SearchResult JSON') - if 'result_metadata' in _dict: - args['result_metadata'] = SearchResultMetadata.from_dict( - _dict.get('result_metadata')) + if 'session_id' in _dict: + args['session_id'] = _dict.get('session_id') else: raise ValueError( - 'Required property \'result_metadata\' not present in SearchResult JSON' + 'Required property \'session_id\' not present in SessionResponse JSON' ) - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'highlight' in _dict: - args['highlight'] = SearchResultHighlight.from_dict( - _dict.get('highlight')) - if 'answers' in _dict: - args['answers'] = [ - SearchResultAnswer.from_dict(v) for v in _dict.get('answers') - ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResult object from a json dictionary.""" + """Initialize a SessionResponse 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, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - if isinstance(self.result_metadata, dict): - _dict['result_metadata'] = self.result_metadata - else: - _dict['result_metadata'] = self.result_metadata.to_dict() - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'highlight') and self.highlight is not None: - if isinstance(self.highlight, dict): - _dict['highlight'] = self.highlight - else: - _dict['highlight'] = self.highlight.to_dict() - if hasattr(self, 'answers') and self.answers is not None: - answers_list = [] - for v in self.answers: - if isinstance(v, dict): - answers_list.append(v) - else: - answers_list.append(v.to_dict()) - _dict['answers'] = answers_list + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id return _dict def _to_dict(self): @@ -6874,71 +8722,229 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResult object.""" + """Return a `str` version of this SessionResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResult') -> bool: + def __eq__(self, other: 'SessionResponse') -> 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: 'SearchResult') -> bool: + def __ne__(self, other: 'SessionResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultAnswer(): +class Skill(): """ - An object specifing a segment of text that was identified as a direct answer to the - search query. + Skill. - :attr str text: The text of the answer. - :attr float confidence: The confidence score for the answer, as returned by the - Discovery service. + :attr str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :attr str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :attr dict workspace: (optional) An object containing the conversational content + of an action or dialog skill. + :attr str skill_id: (optional) The skill ID of the skill. + :attr str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :attr List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :attr str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :attr dict dialog_settings: (optional) For internal use only. + :attr str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :attr str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :attr str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :attr bool valid: (optional) Whether the skill is structurally valid. + :attr str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :attr dict search_settings: (optional) A JSON object describing the search skill + configuration. + :attr List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :attr str language: The language of the skill. + :attr str type: The type of skill. """ - def __init__(self, text: str, confidence: float) -> None: + def __init__(self, + language: str, + type: str, + *, + name: str = None, + description: str = None, + workspace: dict = None, + skill_id: str = None, + status: str = None, + status_errors: List['StatusError'] = None, + status_description: str = None, + dialog_settings: dict = None, + assistant_id: str = None, + workspace_id: str = None, + environment_id: str = None, + valid: bool = None, + next_snapshot_version: str = None, + search_settings: dict = None, + warnings: List['SearchSkillWarning'] = None) -> None: """ - Initialize a SearchResultAnswer object. + Initialize a Skill object. - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned - by the Discovery service. + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param dict search_settings: (optional) A JSON object describing the search + skill configuration. """ - self.text = text - self.confidence = confidence + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': - """Initialize a SearchResultAnswer object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Skill': + """Initialize a Skill object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'workspace' in _dict: + args['workspace'] = _dict.get('workspace') + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'status_errors' in _dict: + args['status_errors'] = [ + StatusError.from_dict(v) for v in _dict.get('status_errors') + ] + if 'status_description' in _dict: + args['status_description'] = _dict.get('status_description') + if 'dialog_settings' in _dict: + args['dialog_settings'] = _dict.get('dialog_settings') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + if 'workspace_id' in _dict: + args['workspace_id'] = _dict.get('workspace_id') + if 'environment_id' in _dict: + args['environment_id'] = _dict.get('environment_id') + if 'valid' in _dict: + args['valid'] = _dict.get('valid') + if 'next_snapshot_version' in _dict: + args['next_snapshot_version'] = _dict.get('next_snapshot_version') + if 'search_settings' in _dict: + args['search_settings'] = _dict.get('search_settings') + if 'warnings' in _dict: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in _dict.get('warnings') + ] + if 'language' in _dict: + args['language'] = _dict.get('language') else: raise ValueError( - 'Required property \'text\' not present in SearchResultAnswer JSON' - ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + 'Required property \'language\' not present in Skill JSON') + if 'type' in _dict: + args['type'] = _dict.get('type') else: raise ValueError( - 'Required property \'confidence\' not present in SearchResultAnswer JSON' - ) + 'Required property \'type\' not present in Skill JSON') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultAnswer object from a json dictionary.""" + """Initialize a Skill 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') + if hasattr(self, + 'search_settings') and self.search_settings is not None: + _dict['search_settings'] = self.search_settings + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -6946,190 +8952,374 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultAnswer object.""" + """Return a `str` version of this Skill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultAnswer') -> bool: + def __eq__(self, other: 'Skill') -> 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: 'SearchResultAnswer') -> bool: + def __ne__(self, other: 'Skill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + """ + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' -class SearchResultHighlight(): - """ - An object containing segments of text from search results with query-matching text - highlighted using HTML `` tags. + class TypeEnum(str, Enum): + """ + The type of skill. + """ + ACTION = 'action' + DIALOG = 'dialog' + SEARCH = 'search' - :attr List[str] body: (optional) An array of strings containing segments taken - from body text in the search results, with query-matching substrings - highlighted. - :attr List[str] title: (optional) An array of strings containing segments taken - from title text in the search results, with query-matching substrings - highlighted. - :attr List[str] url: (optional) An array of strings containing segments taken - from URLs in the search results, with query-matching substrings highlighted. + +class SkillImport(): """ + SkillImport. - # The set of defined properties for the class - _properties = frozenset(['body', 'title', 'url']) + :attr str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :attr str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :attr dict workspace: (optional) An object containing the conversational content + of an action or dialog skill. + :attr str skill_id: (optional) The skill ID of the skill. + :attr str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :attr List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :attr str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :attr dict dialog_settings: (optional) For internal use only. + :attr str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :attr str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :attr str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :attr bool valid: (optional) Whether the skill is structurally valid. + :attr str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :attr dict search_settings: (optional) A JSON object describing the search skill + configuration. + :attr List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :attr str language: The language of the skill. + :attr str type: The type of skill. + """ def __init__(self, + language: str, + type: str, *, - body: List[str] = None, - title: List[str] = None, - url: List[str] = None, - **kwargs) -> None: + name: str = None, + description: str = None, + workspace: dict = None, + skill_id: str = None, + status: str = None, + status_errors: List['StatusError'] = None, + status_description: str = None, + dialog_settings: dict = None, + assistant_id: str = None, + workspace_id: str = None, + environment_id: str = None, + valid: bool = None, + next_snapshot_version: str = None, + search_settings: dict = None, + warnings: List['SearchSkillWarning'] = None) -> None: """ - Initialize a SearchResultHighlight object. + Initialize a SkillImport object. - :param List[str] body: (optional) An array of strings containing segments - taken from body text in the search results, with query-matching substrings - highlighted. - :param List[str] title: (optional) An array of strings containing segments - taken from title text in the search results, with query-matching substrings - highlighted. - :param List[str] url: (optional) An array of strings containing segments - taken from URLs in the search results, with query-matching substrings - highlighted. - :param **kwargs: (optional) Any additional properties. + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param dict search_settings: (optional) A JSON object describing the search + skill configuration. """ - self.body = body - self.title = title - self.url = url - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': - """Initialize a SearchResultHighlight object from a json dictionary.""" - args = {} - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SkillImport': + """Initialize a SkillImport object from a json dictionary.""" + args = {} + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'workspace' in _dict: + args['workspace'] = _dict.get('workspace') + if 'skill_id' in _dict: + args['skill_id'] = _dict.get('skill_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'status_errors' in _dict: + args['status_errors'] = [ + StatusError.from_dict(v) for v in _dict.get('status_errors') + ] + if 'status_description' in _dict: + args['status_description'] = _dict.get('status_description') + if 'dialog_settings' in _dict: + args['dialog_settings'] = _dict.get('dialog_settings') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + if 'workspace_id' in _dict: + args['workspace_id'] = _dict.get('workspace_id') + if 'environment_id' in _dict: + args['environment_id'] = _dict.get('environment_id') + if 'valid' in _dict: + args['valid'] = _dict.get('valid') + if 'next_snapshot_version' in _dict: + args['next_snapshot_version'] = _dict.get('next_snapshot_version') + if 'search_settings' in _dict: + args['search_settings'] = _dict.get('search_settings') + if 'warnings' in _dict: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in _dict.get('warnings') + ] + if 'language' in _dict: + args['language'] = _dict.get('language') + else: + raise ValueError( + 'Required property \'language\' not present in SkillImport JSON' + ) + if 'type' in _dict: + args['type'] = _dict.get('type') + else: + raise ValueError( + 'Required property \'type\' not present in SkillImport JSON') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultHighlight object from a json dictionary.""" + """Initialize a SkillImport 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, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') + if hasattr(self, + 'search_settings') and self.search_settings is not None: + _dict['search_settings'] = self.search_settings + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + 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 get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in SearchResultHighlight._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this SearchResultHighlight object.""" + """Return a `str` version of this SkillImport object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultHighlight') -> bool: + def __eq__(self, other: 'SkillImport') -> 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: 'SearchResultHighlight') -> bool: + def __ne__(self, other: 'SkillImport') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + """ + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' -class SearchResultMetadata(): + class TypeEnum(str, Enum): + """ + The type of skill. + """ + ACTION = 'action' + DIALOG = 'dialog' + SEARCH = 'search' + + +class SkillsAsyncRequestStatus(): """ - An object containing search result metadata from the Discovery service. + SkillsAsyncRequestStatus. - :attr float confidence: (optional) The confidence score for the given result, as - returned by the Discovery service. - :attr float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. + :attr str assistant_id: (optional) The assistant ID of the assistant. + :attr str status: (optional) The current status of the asynchronous operation: + - **Available**: The export is available. + - **Failed**: An asynchronous export operation has failed. See the + **status_errors** property for more information about the cause of the failure. + - **Processing**: An asynchronous export operation has not yet completed. + :attr str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :attr List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. """ def __init__(self, *, - confidence: float = None, - score: float = None) -> None: + assistant_id: str = None, + status: str = None, + status_description: str = None, + status_errors: List['StatusError'] = None) -> None: """ - Initialize a SearchResultMetadata object. + Initialize a SkillsAsyncRequestStatus object. - :param float confidence: (optional) The confidence score for the given - result, as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher - score indicates a greater match to the query parameters. """ - self.confidence = confidence - self.score = score + self.assistant_id = assistant_id + self.status = status + self.status_description = status_description + self.status_errors = status_errors @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': - """Initialize a SearchResultMetadata object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" args = {} - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'score' in _dict: - args['score'] = _dict.get('score') + if 'assistant_id' in _dict: + args['assistant_id'] = _dict.get('assistant_id') + if 'status' in _dict: + args['status'] = _dict.get('status') + if 'status_description' in _dict: + args['status_description'] = _dict.get('status_description') + if 'status_errors' in _dict: + args['status_errors'] = [ + StatusError.from_dict(v) for v in _dict.get('status_errors') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultMetadata object from a json dictionary.""" + """Initialize a SkillsAsyncRequestStatus 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, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list return _dict def _to_dict(self): @@ -7137,57 +9327,100 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultMetadata object.""" + """Return a `str` version of this SkillsAsyncRequestStatus object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultMetadata') -> bool: + def __eq__(self, other: 'SkillsAsyncRequestStatus') -> 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: 'SearchResultMetadata') -> bool: + def __ne__(self, other: 'SkillsAsyncRequestStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The current status of the asynchronous operation: + - **Available**: The export is available. + - **Failed**: An asynchronous export operation has failed. See the + **status_errors** property for more information about the cause of the failure. + - **Processing**: An asynchronous export operation has not yet completed. + """ + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + -class SessionResponse(): +class SkillsExport(): """ - SessionResponse. + SkillsExport. - :attr str session_id: The session ID. + :attr List[Skill] assistant_skills: An array of objects describing the skills + for the assistant. Included in responses only if **status**=`Available`. + :attr AssistantState assistant_state: Status information about the skills for + the assistant. Included in responses only if **status**=`Available`. """ - def __init__(self, session_id: str) -> None: + def __init__(self, assistant_skills: List['Skill'], + assistant_state: 'AssistantState') -> None: """ - Initialize a SessionResponse object. + Initialize a SkillsExport object. - :param str session_id: The session ID. + :param List[Skill] assistant_skills: An array of objects describing the + skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. """ - self.session_id = session_id + self.assistant_skills = assistant_skills + self.assistant_state = assistant_state @classmethod - def from_dict(cls, _dict: Dict) -> 'SessionResponse': - """Initialize a SessionResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillsExport': + """Initialize a SkillsExport object from a json dictionary.""" args = {} - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if 'assistant_skills' in _dict: + args['assistant_skills'] = [ + Skill.from_dict(v) for v in _dict.get('assistant_skills') + ] else: raise ValueError( - 'Required property \'session_id\' not present in SessionResponse JSON' + 'Required property \'assistant_skills\' not present in SkillsExport JSON' + ) + if 'assistant_state' in _dict: + args['assistant_state'] = AssistantState.from_dict( + _dict.get('assistant_state')) + else: + raise ValueError( + 'Required property \'assistant_state\' not present in SkillsExport JSON' ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SessionResponse object from a json dictionary.""" + """Initialize a SkillsExport 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, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, + 'assistant_skills') and self.assistant_skills is not None: + assistant_skills_list = [] + for v in self.assistant_skills: + if isinstance(v, dict): + assistant_skills_list.append(v) + else: + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, + 'assistant_state') and self.assistant_state is not None: + if isinstance(self.assistant_state, dict): + _dict['assistant_state'] = self.assistant_state + else: + _dict['assistant_state'] = self.assistant_state.to_dict() return _dict def _to_dict(self): @@ -7195,98 +9428,54 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SessionResponse object.""" + """Return a `str` version of this SkillsExport object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SessionResponse') -> bool: + def __eq__(self, other: 'SkillsExport') -> 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: 'SessionResponse') -> bool: + def __ne__(self, other: 'SkillsExport') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SkillReference(): +class StatusError(): """ - SkillReference. + An object describing an error that occurred during processing of an asynchronous + operation. - :attr str skill_id: (optional) The skill ID of the skill. - :attr str type: (optional) The type of the skill. - :attr bool disabled: (optional) Whether the skill is disabled. A disabled skill - in the draft environment does not handle any messages at run time, and it is not - included in saved releases. - :attr str snapshot: (optional) The name of the snapshot (skill version) that is - saved as part of the release (for example, `draft` or `1`). - :attr str skill_reference: (optional) The type of skill identified by the skill - reference. The possible values are `main skill` (for a dialog skill), `actions - skill`, and `search skill`. + :attr str message: (optional) The text of the error message. """ - def __init__(self, - *, - skill_id: str = None, - type: str = None, - disabled: bool = None, - snapshot: str = None, - skill_reference: str = None) -> None: + def __init__(self, *, message: str = None) -> None: """ - Initialize a SkillReference object. + Initialize a StatusError object. - :param str skill_id: (optional) The skill ID of the skill. - :param str type: (optional) The type of the skill. - :param bool disabled: (optional) Whether the skill is disabled. A disabled - skill in the draft environment does not handle any messages at run time, - and it is not included in saved releases. - :param str snapshot: (optional) The name of the snapshot (skill version) - that is saved as part of the release (for example, `draft` or `1`). - :param str skill_reference: (optional) The type of skill identified by the - skill reference. The possible values are `main skill` (for a dialog skill), - `actions skill`, and `search skill`. + :param str message: (optional) The text of the error message. """ - self.skill_id = skill_id - self.type = type - self.disabled = disabled - self.snapshot = snapshot - self.skill_reference = skill_reference + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillReference': - """Initialize a SkillReference object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatusError': + """Initialize a StatusError object from a json dictionary.""" args = {} - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'disabled' in _dict: - args['disabled'] = _dict.get('disabled') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') - if 'skill_reference' in _dict: - args['skill_reference'] = _dict.get('skill_reference') + if 'message' in _dict: + args['message'] = _dict.get('message') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillReference object from a json dictionary.""" + """Initialize a StatusError 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, 'skill_id') and self.skill_id is not None: - _dict['skill_id'] = self.skill_id - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'disabled') and self.disabled is not None: - _dict['disabled'] = self.disabled - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot - if hasattr(self, - 'skill_reference') and self.skill_reference is not None: - _dict['skill_reference'] = self.skill_reference + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -7294,27 +9483,19 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillReference object.""" + """Return a `str` version of this StatusError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillReference') -> bool: + def __eq__(self, other: 'StatusError') -> 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: 'SkillReference') -> bool: + def __ne__(self, other: 'StatusError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of the skill. - """ - DIALOG = 'dialog' - ACTION = 'action' - SEARCH = 'search' - class TurnEventActionSource(): """ @@ -7409,19 +9590,30 @@ class TurnEventCalloutCallout(): """ TurnEventCalloutCallout. - :attr str type: (optional) callout type. + :attr str type: (optional) The type of callout. Currently, the only supported + value is `integration_interaction` (for calls to extensions). :attr dict internal: (optional) For internal use only. + :attr str result_variable: (optional) The name of the variable where the callout + result is stored. """ - def __init__(self, *, type: str = None, internal: dict = None) -> None: + def __init__(self, + *, + type: str = None, + internal: dict = None, + result_variable: str = None) -> None: """ Initialize a TurnEventCalloutCallout object. - :param str type: (optional) callout type. + :param str type: (optional) The type of callout. Currently, the only + supported value is `integration_interaction` (for calls to extensions). :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. """ self.type = type self.internal = internal + self.result_variable = result_variable @classmethod def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': @@ -7431,6 +9623,8 @@ def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': args['type'] = _dict.get('type') if 'internal' in _dict: args['internal'] = _dict.get('internal') + if 'result_variable' in _dict: + args['result_variable'] = _dict.get('result_variable') return cls(**args) @classmethod @@ -7445,6 +9639,9 @@ def to_dict(self) -> Dict: _dict['type'] = self.type if hasattr(self, 'internal') and self.internal is not None: _dict['internal'] = self.internal + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable return _dict def _to_dict(self): @@ -7467,7 +9664,8 @@ def __ne__(self, other: 'TurnEventCalloutCallout') -> bool: class TypeEnum(str, Enum): """ - callout type. + The type of callout. Currently, the only supported value is + `integration_interaction` (for calls to extensions). """ INTEGRATION_INTERACTION = 'integration_interaction' @@ -8156,6 +10354,8 @@ class MessageOutputDebugTurnEventTurnEventActionVisited( :attr str condition_type: (optional) The type of condition (if any) that is defined for the action. :attr str reason: (optional) The reason the action was visited. + :attr str result_variable: (optional) The variable where the result of the call + to the action is stored. Included only if **reason**=`subaction_return`. """ def __init__(self, @@ -8164,7 +10364,8 @@ def __init__(self, source: 'TurnEventActionSource' = None, action_start_time: str = None, condition_type: str = None, - reason: str = None) -> None: + reason: str = None, + result_variable: str = None) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. @@ -8175,6 +10376,9 @@ def __init__(self, :param str condition_type: (optional) The type of condition (if any) that is defined for the action. :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the + call to the action is stored. Included only if + **reason**=`subaction_return`. """ # pylint: disable=super-init-not-called self.event = event @@ -8182,6 +10386,7 @@ def __init__(self, self.action_start_time = action_start_time self.condition_type = condition_type self.reason = reason + self.result_variable = result_variable @classmethod def from_dict( @@ -8200,6 +10405,8 @@ def from_dict( args['condition_type'] = _dict.get('condition_type') if 'reason' in _dict: args['reason'] = _dict.get('reason') + if 'result_variable' in _dict: + args['result_variable'] = _dict.get('result_variable') return cls(**args) @classmethod @@ -8224,6 +10431,9 @@ def to_dict(self) -> Dict: _dict['condition_type'] = self.condition_type if hasattr(self, 'reason') and self.reason is not None: _dict['reason'] = self.reason + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable return _dict def _to_dict(self): @@ -9010,6 +11220,8 @@ class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM Cloud + Pak for Data. :attr str message_to_user: The message to display to the user when initiating a channel transfer. :attr ChannelTransferInfo transfer_info: Information used by an integration to @@ -9032,6 +11244,8 @@ def __init__(self, :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. + **Note:** The `channel_transfer` response type is not supported on IBM + Cloud Pak for Data. :param str message_to_user: The message to display to the user when initiating a channel transfer. :param ChannelTransferInfo transfer_info: Information used by an diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 24a9f8e1a..8caf4ccde 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -66,6 +66,286 @@ def preprocess_url(operation_path: str): return re.compile(request_url.rstrip('/') + '/+') +############################################################################## +# Start of Service: Assistants +############################################################################## +# region + +class TestCreateAssistant(): + """ + Test Class for create_assistant + """ + + @responses.activate + def test_create_assistant_all_params(self): + """ + create_assistant() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + language = 'testString' + name = 'testString' + description = 'testString' + + # Invoke method + response = _service.create_assistant( + language=language, + name=name, + description=description, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['language'] == 'testString' + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + + def test_create_assistant_all_params_with_retries(self): + # Enable retries and run test_create_assistant_all_params. + _service.enable_retries() + self.test_create_assistant_all_params() + + # Disable retries and run test_create_assistant_all_params. + _service.disable_retries() + self.test_create_assistant_all_params() + + @responses.activate + def test_create_assistant_required_params(self): + """ + test_create_assistant_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = _service.create_assistant() + + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_create_assistant_required_params_with_retries(self): + # Enable retries and run test_create_assistant_required_params. + _service.enable_retries() + self.test_create_assistant_required_params() + + # Disable retries and run test_create_assistant_required_params. + _service.disable_retries() + self.test_create_assistant_required_params() + + @responses.activate + def test_create_assistant_value_error(self): + """ + test_create_assistant_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_assistant(**req_copy) + + def test_create_assistant_value_error_with_retries(self): + # Enable retries and run test_create_assistant_value_error. + _service.enable_retries() + self.test_create_assistant_value_error() + + # Disable retries and run test_create_assistant_value_error. + _service.disable_retries() + self.test_create_assistant_value_error() + +class TestListAssistants(): + """ + Test Class for list_assistants + """ + + @responses.activate + def test_list_assistants_all_params(self): + """ + list_assistants() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + page_limit = 38 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False + + # Invoke method + response = _service.list_assistants( + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_list_assistants_all_params_with_retries(self): + # Enable retries and run test_list_assistants_all_params. + _service.enable_retries() + self.test_list_assistants_all_params() + + # Disable retries and run test_list_assistants_all_params. + _service.disable_retries() + self.test_list_assistants_all_params() + + @responses.activate + def test_list_assistants_required_params(self): + """ + test_list_assistants_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Invoke method + response = _service.list_assistants() + + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_assistants_required_params_with_retries(self): + # Enable retries and run test_list_assistants_required_params. + _service.enable_retries() + self.test_list_assistants_required_params() + + # Disable retries and run test_list_assistants_required_params. + _service.disable_retries() + self.test_list_assistants_required_params() + +class TestDeleteAssistant(): + """ + Test Class for delete_assistant + """ + + @responses.activate + def test_delete_assistant_all_params(self): + """ + delete_assistant() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.delete_assistant( + assistant_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_delete_assistant_all_params_with_retries(self): + # Enable retries and run test_delete_assistant_all_params. + _service.enable_retries() + self.test_delete_assistant_all_params() + + # Disable retries and run test_delete_assistant_all_params. + _service.disable_retries() + self.test_delete_assistant_all_params() + + @responses.activate + def test_delete_assistant_value_error(self): + """ + test_delete_assistant_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_assistant(**req_copy) + + def test_delete_assistant_value_error_with_retries(self): + # Enable retries and run test_delete_assistant_value_error. + _service.enable_retries() + self.test_delete_assistant_value_error() + + # Disable retries and run test_delete_assistant_value_error. + _service.disable_retries() + self.test_delete_assistant_value_error() + +# endregion +############################################################################## +# End of Service: Assistants +############################################################################## + ############################################################################## # Start of Service: Sessions ############################################################################## @@ -90,14 +370,20 @@ def test_create_session_all_params(self): content_type='application/json', status=201) + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + # Set up parameter values assistant_id = 'testString' - request_body = {'key1': 'testString'} + analytics = request_analytics_model # Invoke method response = _service.create_session( assistant_id, - request_body=request_body, + analytics=analytics, headers={} ) @@ -106,7 +392,7 @@ def test_create_session_all_params(self): assert response.status_code == 201 # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body == request_body + assert req_body['analytics'] == request_analytics_model def test_create_session_all_params_with_retries(self): # Enable retries and run test_create_session_all_params. @@ -284,7 +570,7 @@ def test_message_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -357,6 +643,12 @@ def test_message_all_params(self): message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + # Construct a dict representation of a MessageInputOptionsSpelling model message_input_options_spelling_model = {} message_input_options_spelling_model['suggestions'] = True @@ -379,6 +671,7 @@ def test_message_all_params(self): message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model # Construct a dict representation of a MessageContextGlobalSystem model @@ -454,7 +747,7 @@ def test_message_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -492,7 +785,7 @@ def test_message_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -534,7 +827,7 @@ def test_message_stateless_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -607,6 +900,12 @@ def test_message_stateless_all_params(self): message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + # Construct a dict representation of a MessageInputOptionsSpelling model message_input_options_spelling_model = {} message_input_options_spelling_model['suggestions'] = True @@ -627,6 +926,7 @@ def test_message_stateless_all_params(self): message_input_stateless_model['entities'] = [runtime_entity_model] message_input_stateless_model['suggestion_id'] = 'testString' message_input_stateless_model['attachments'] = [message_input_attachment_model] + message_input_stateless_model['analytics'] = request_analytics_model message_input_stateless_model['options'] = message_input_options_stateless_model # Construct a dict representation of a MessageContextGlobalSystem model @@ -701,7 +1001,7 @@ def test_message_stateless_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -737,7 +1037,7 @@ def test_message_stateless_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -888,7 +1188,7 @@ def test_list_logs_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -939,7 +1239,7 @@ def test_list_logs_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -975,7 +1275,7 @@ def test_list_logs_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -1109,7 +1409,7 @@ def test_list_environments_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/environments') - mock_response = '{"environments": [{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -1163,7 +1463,7 @@ def test_list_environments_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/environments') - mock_response = '{"environments": [{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -1199,7 +1499,7 @@ def test_list_environments_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/environments') - mock_response = '{"environments": [{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -1239,7 +1539,7 @@ def test_get_environment_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1283,7 +1583,7 @@ def test_get_environment_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1321,7 +1621,7 @@ def test_get_environment_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add(responses.GET, url, body=mock_response, @@ -1351,84 +1651,80 @@ def test_get_environment_value_error_with_retries(self): _service.disable_retries() self.test_get_environment_value_error() -# endregion -############################################################################## -# End of Service: Environments -############################################################################## - -############################################################################## -# Start of Service: Releases -############################################################################## -# region - -class TestListReleases(): +class TestUpdateEnvironment(): """ - Test Class for list_releases + Test Class for update_environment """ @responses.activate - def test_list_releases_all_params(self): + def test_update_environment_all_params(self): """ - list_releases() + update_environment() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=200) + # Construct a dict representation of a EnvironmentSkill model + environment_skill_model = {} + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' + # Set up parameter values assistant_id = 'testString' - page_limit = 38 - include_count = False - sort = 'name' - cursor = 'testString' - include_audit = False + environment_id = 'testString' + name = 'testString' + description = 'testString' + session_timeout = 10 + skill_references = [environment_skill_model] # Invoke method - response = _service.list_releases( + response = _service.update_environment( assistant_id, - page_limit=page_limit, - include_count=include_count, - sort=sort, - cursor=cursor, - include_audit=include_audit, + environment_id, + name=name, + description=description, + session_timeout=session_timeout, + skill_references=skill_references, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'page_limit={}'.format(page_limit) in query_string - assert 'include_count={}'.format('true' if include_count else 'false') in query_string - assert 'sort={}'.format(sort) in query_string - assert 'cursor={}'.format(cursor) in query_string - assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['session_timeout'] == 10 + assert req_body['skill_references'] == [environment_skill_model] - def test_list_releases_all_params_with_retries(self): - # Enable retries and run test_list_releases_all_params. + def test_update_environment_all_params_with_retries(self): + # Enable retries and run test_update_environment_all_params. _service.enable_retries() - self.test_list_releases_all_params() + self.test_update_environment_all_params() - # Disable retries and run test_list_releases_all_params. + # Disable retries and run test_update_environment_all_params. _service.disable_retries() - self.test_list_releases_all_params() + self.test_update_environment_all_params() @responses.activate - def test_list_releases_required_params(self): + def test_update_environment_required_params(self): """ - test_list_releases_required_params() + test_update_environment_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, url, body=mock_response, content_type='application/json', @@ -1436,9 +1732,270 @@ def test_list_releases_required_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' # Invoke method - response = _service.list_releases( + response = _service.update_environment( + assistant_id, + environment_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_update_environment_required_params_with_retries(self): + # Enable retries and run test_update_environment_required_params. + _service.enable_retries() + self.test_update_environment_required_params() + + # Disable retries and run test_update_environment_required_params. + _service.disable_retries() + self.test_update_environment_required_params() + + @responses.activate + def test_update_environment_value_error(self): + """ + test_update_environment_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_environment(**req_copy) + + def test_update_environment_value_error_with_retries(self): + # Enable retries and run test_update_environment_value_error. + _service.enable_retries() + self.test_update_environment_value_error() + + # Disable retries and run test_update_environment_value_error. + _service.disable_retries() + self.test_update_environment_value_error() + +# endregion +############################################################################## +# End of Service: Environments +############################################################################## + +############################################################################## +# Start of Service: Releases +############################################################################## +# region + +class TestCreateRelease(): + """ + Test Class for create_release + """ + + @responses.activate + def test_create_release_all_params(self): + """ + create_release() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + assistant_id = 'testString' + description = 'testString' + + # Invoke method + response = _service.create_release( + assistant_id, + description=description, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['description'] == 'testString' + + def test_create_release_all_params_with_retries(self): + # Enable retries and run test_create_release_all_params. + _service.enable_retries() + self.test_create_release_all_params() + + # Disable retries and run test_create_release_all_params. + _service.disable_retries() + self.test_create_release_all_params() + + @responses.activate + def test_create_release_required_params(self): + """ + test_create_release_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.create_release( + assistant_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_create_release_required_params_with_retries(self): + # Enable retries and run test_create_release_required_params. + _service.enable_retries() + self.test_create_release_required_params() + + # Disable retries and run test_create_release_required_params. + _service.disable_retries() + self.test_create_release_required_params() + + @responses.activate + def test_create_release_value_error(self): + """ + test_create_release_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_release(**req_copy) + + def test_create_release_value_error_with_retries(self): + # Enable retries and run test_create_release_value_error. + _service.enable_retries() + self.test_create_release_value_error() + + # Disable retries and run test_create_release_value_error. + _service.disable_retries() + self.test_create_release_value_error() + +class TestListReleases(): + """ + Test Class for list_releases + """ + + @responses.activate + def test_list_releases_all_params(self): + """ + list_releases() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + page_limit = 38 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False + + # Invoke method + response = _service.list_releases( + assistant_id, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_list_releases_all_params_with_retries(self): + # Enable retries and run test_list_releases_all_params. + _service.enable_retries() + self.test_list_releases_all_params() + + # Disable retries and run test_list_releases_all_params. + _service.disable_retries() + self.test_list_releases_all_params() + + @responses.activate + def test_list_releases_required_params(self): + """ + test_list_releases_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.list_releases( assistant_id, headers={} ) @@ -1615,69 +2172,723 @@ def test_get_release_value_error_with_retries(self): _service.disable_retries() self.test_get_release_value_error() -class TestDeployRelease(): +class TestDeleteRelease(): """ - Test Class for deploy_release + Test Class for delete_release """ @responses.activate - def test_deploy_release_all_params(self): + def test_delete_release_all_params(self): """ - deploy_release() + delete_release() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') - mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, + url = preprocess_url('/v2/assistants/testString/releases/testString') + responses.add(responses.DELETE, url, - body=mock_response, - content_type='application/json', status=200) # Set up parameter values assistant_id = 'testString' release = 'testString' - environment_id = 'testString' - include_audit = False # Invoke method - response = _service.deploy_release( + response = _service.delete_release( assistant_id, release, - environment_id, - include_audit=include_audit, headers={} ) - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['environment_id'] == 'testString' + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_delete_release_all_params_with_retries(self): + # Enable retries and run test_delete_release_all_params. + _service.enable_retries() + self.test_delete_release_all_params() + + # Disable retries and run test_delete_release_all_params. + _service.disable_retries() + self.test_delete_release_all_params() + + @responses.activate + def test_delete_release_value_error(self): + """ + test_delete_release_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString') + responses.add(responses.DELETE, + url, + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "release": release, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.delete_release(**req_copy) + + def test_delete_release_value_error_with_retries(self): + # Enable retries and run test_delete_release_value_error. + _service.enable_retries() + self.test_delete_release_value_error() + + # Disable retries and run test_delete_release_value_error. + _service.disable_retries() + self.test_delete_release_value_error() + +class TestDeployRelease(): + """ + Test Class for deploy_release + """ + + @responses.activate + def test_deploy_release_all_params(self): + """ + deploy_release() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' + include_audit = False + + # Invoke method + response = _service.deploy_release( + assistant_id, + release, + environment_id, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['environment_id'] == 'testString' + + def test_deploy_release_all_params_with_retries(self): + # Enable retries and run test_deploy_release_all_params. + _service.enable_retries() + self.test_deploy_release_all_params() + + # Disable retries and run test_deploy_release_all_params. + _service.disable_retries() + self.test_deploy_release_all_params() + + @responses.activate + def test_deploy_release_required_params(self): + """ + test_deploy_release_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' + + # Invoke method + response = _service.deploy_release( + assistant_id, + release, + environment_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['environment_id'] == 'testString' + + def test_deploy_release_required_params_with_retries(self): + # Enable retries and run test_deploy_release_required_params. + _service.enable_retries() + self.test_deploy_release_required_params() + + # Disable retries and run test_deploy_release_required_params. + _service.disable_retries() + self.test_deploy_release_required_params() + + @responses.activate + def test_deploy_release_value_error(self): + """ + test_deploy_release_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "release": release, + "environment_id": environment_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.deploy_release(**req_copy) + + def test_deploy_release_value_error_with_retries(self): + # Enable retries and run test_deploy_release_value_error. + _service.enable_retries() + self.test_deploy_release_value_error() + + # Disable retries and run test_deploy_release_value_error. + _service.disable_retries() + self.test_deploy_release_value_error() + +# endregion +############################################################################## +# End of Service: Releases +############################################################################## + +############################################################################## +# Start of Service: Skills +############################################################################## +# region + +class TestGetSkill(): + """ + Test Class for get_skill + """ + + @responses.activate + def test_get_skill_all_params(self): + """ + get_skill() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + + # Invoke method + response = _service.get_skill( + assistant_id, + skill_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_skill_all_params_with_retries(self): + # Enable retries and run test_get_skill_all_params. + _service.enable_retries() + self.test_get_skill_all_params() + + # Disable retries and run test_get_skill_all_params. + _service.disable_retries() + self.test_get_skill_all_params() + + @responses.activate + def test_get_skill_value_error(self): + """ + test_get_skill_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "skill_id": skill_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_skill(**req_copy) + + def test_get_skill_value_error_with_retries(self): + # Enable retries and run test_get_skill_value_error. + _service.enable_retries() + self.test_get_skill_value_error() + + # Disable retries and run test_get_skill_value_error. + _service.disable_retries() + self.test_get_skill_value_error() + +class TestUpdateSkill(): + """ + Test Class for update_skill + """ + + @responses.activate + def test_update_skill_all_params(self): + """ + update_skill() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + name = 'testString' + description = 'testString' + workspace = {'foo': 'bar'} + dialog_settings = {'foo': 'bar'} + search_settings = {'foo': 'bar'} + + # Invoke method + response = _service.update_skill( + assistant_id, + skill_id, + name=name, + description=description, + workspace=workspace, + dialog_settings=dialog_settings, + search_settings=search_settings, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['workspace'] == {'foo': 'bar'} + assert req_body['dialog_settings'] == {'foo': 'bar'} + assert req_body['search_settings'] == {'foo': 'bar'} + + def test_update_skill_all_params_with_retries(self): + # Enable retries and run test_update_skill_all_params. + _service.enable_retries() + self.test_update_skill_all_params() + + # Disable retries and run test_update_skill_all_params. + _service.disable_retries() + self.test_update_skill_all_params() + + @responses.activate + def test_update_skill_value_error(self): + """ + test_update_skill_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + name = 'testString' + description = 'testString' + workspace = {'foo': 'bar'} + dialog_settings = {'foo': 'bar'} + search_settings = {'foo': 'bar'} + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "skill_id": skill_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_skill(**req_copy) + + def test_update_skill_value_error_with_retries(self): + # Enable retries and run test_update_skill_value_error. + _service.enable_retries() + self.test_update_skill_value_error() + + # Disable retries and run test_update_skill_value_error. + _service.disable_retries() + self.test_update_skill_value_error() + +class TestExportSkills(): + """ + Test Class for export_skills + """ + + @responses.activate + def test_export_skills_all_params(self): + """ + export_skills() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + include_audit = False + + # Invoke method + response = _service.export_skills( + assistant_id, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_export_skills_all_params_with_retries(self): + # Enable retries and run test_export_skills_all_params. + _service.enable_retries() + self.test_export_skills_all_params() + + # Disable retries and run test_export_skills_all_params. + _service.disable_retries() + self.test_export_skills_all_params() + + @responses.activate + def test_export_skills_required_params(self): + """ + test_export_skills_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.export_skills( + assistant_id, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_export_skills_required_params_with_retries(self): + # Enable retries and run test_export_skills_required_params. + _service.enable_retries() + self.test_export_skills_required_params() + + # Disable retries and run test_export_skills_required_params. + _service.disable_retries() + self.test_export_skills_required_params() + + @responses.activate + def test_export_skills_value_error(self): + """ + test_export_skills_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.export_skills(**req_copy) + + def test_export_skills_value_error_with_retries(self): + # Enable retries and run test_export_skills_value_error. + _service.enable_retries() + self.test_export_skills_value_error() + + # Disable retries and run test_export_skills_value_error. + _service.disable_retries() + self.test_export_skills_value_error() + +class TestImportSkills(): + """ + Test Class for import_skills + """ + + @responses.activate + def test_import_skills_all_params(self): + """ + import_skills() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'foo': 'bar'} + skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['search_settings'] = {'foo': 'bar'} + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + include_audit = False + + # Invoke method + response = _service.import_skills( + assistant_id, + assistant_skills, + assistant_state, + include_audit=include_audit, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['assistant_skills'] == [skill_import_model] + assert req_body['assistant_state'] == assistant_state_model + + def test_import_skills_all_params_with_retries(self): + # Enable retries and run test_import_skills_all_params. + _service.enable_retries() + self.test_import_skills_all_params() + + # Disable retries and run test_import_skills_all_params. + _service.disable_retries() + self.test_import_skills_all_params() + + @responses.activate + def test_import_skills_required_params(self): + """ + test_import_skills_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'foo': 'bar'} + skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['search_settings'] = {'foo': 'bar'} + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + + # Invoke method + response = _service.import_skills( + assistant_id, + assistant_skills, + assistant_state, + headers={} + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['assistant_skills'] == [skill_import_model] + assert req_body['assistant_state'] == assistant_state_model + + def test_import_skills_required_params_with_retries(self): + # Enable retries and run test_import_skills_required_params. + _service.enable_retries() + self.test_import_skills_required_params() + + # Disable retries and run test_import_skills_required_params. + _service.disable_retries() + self.test_import_skills_required_params() + + @responses.activate + def test_import_skills_value_error(self): + """ + test_import_skills_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add(responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202) + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'foo': 'bar'} + skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['search_settings'] = {'foo': 'bar'} + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "assistant_skills": assistant_skills, + "assistant_state": assistant_state, + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.import_skills(**req_copy) - def test_deploy_release_all_params_with_retries(self): - # Enable retries and run test_deploy_release_all_params. + def test_import_skills_value_error_with_retries(self): + # Enable retries and run test_import_skills_value_error. _service.enable_retries() - self.test_deploy_release_all_params() + self.test_import_skills_value_error() - # Disable retries and run test_deploy_release_all_params. + # Disable retries and run test_import_skills_value_error. _service.disable_retries() - self.test_deploy_release_all_params() + self.test_import_skills_value_error() + +class TestImportSkillsStatus(): + """ + Test Class for import_skills_status + """ @responses.activate - def test_deploy_release_required_params(self): + def test_import_skills_status_all_params(self): """ - test_deploy_release_required_params() + import_skills_status() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') - mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, + url = preprocess_url('/v2/assistants/testString/skills_import/status') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add(responses.GET, url, body=mock_response, content_type='application/json', @@ -1685,42 +2896,35 @@ def test_deploy_release_required_params(self): # Set up parameter values assistant_id = 'testString' - release = 'testString' - environment_id = 'testString' # Invoke method - response = _service.deploy_release( + response = _service.import_skills_status( assistant_id, - release, - environment_id, headers={} ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['environment_id'] == 'testString' - def test_deploy_release_required_params_with_retries(self): - # Enable retries and run test_deploy_release_required_params. + def test_import_skills_status_all_params_with_retries(self): + # Enable retries and run test_import_skills_status_all_params. _service.enable_retries() - self.test_deploy_release_required_params() + self.test_import_skills_status_all_params() - # Disable retries and run test_deploy_release_required_params. + # Disable retries and run test_import_skills_status_all_params. _service.disable_retries() - self.test_deploy_release_required_params() + self.test_import_skills_status_all_params() @responses.activate - def test_deploy_release_value_error(self): + def test_import_skills_status_value_error(self): """ - test_deploy_release_value_error() + test_import_skills_status_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') - mock_response = '{"name": "name", "description": "description", "language": "language", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 15, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, + url = preprocess_url('/v2/assistants/testString/skills_import/status') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add(responses.GET, url, body=mock_response, content_type='application/json', @@ -1728,32 +2932,28 @@ def test_deploy_release_value_error(self): # Set up parameter values assistant_id = 'testString' - release = 'testString' - environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "release": release, - "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.deploy_release(**req_copy) + _service.import_skills_status(**req_copy) - def test_deploy_release_value_error_with_retries(self): - # Enable retries and run test_deploy_release_value_error. + def test_import_skills_status_value_error_with_retries(self): + # Enable retries and run test_import_skills_status_value_error. _service.enable_retries() - self.test_deploy_release_value_error() + self.test_import_skills_status_value_error() - # Disable retries and run test_deploy_release_value_error. + # Disable retries and run test_import_skills_status_value_error. _service.disable_retries() - self.test_deploy_release_value_error() + self.test_import_skills_status_value_error() # endregion ############################################################################## -# End of Service: Releases +# End of Service: Skills ############################################################################## @@ -1790,6 +2990,200 @@ def test_agent_availability_message_serialization(self): agent_availability_message_model_json2 = agent_availability_message_model.to_dict() assert agent_availability_message_model_json2 == agent_availability_message_model_json +class TestModel_Assistant(): + """ + Test Class for Assistant + """ + + def test_assistant_serialization(self): + """ + Test serialization/deserialization for Assistant + """ + + # Construct a json representation of a Assistant model + assistant_model_json = {} + assistant_model_json['name'] = 'testString' + assistant_model_json['description'] = 'testString' + assistant_model_json['language'] = 'testString' + + # Construct a model instance of Assistant by calling from_dict on the json representation + assistant_model = Assistant.from_dict(assistant_model_json) + assert assistant_model != False + + # Construct a model instance of Assistant by calling from_dict on the json representation + assistant_model_dict = Assistant.from_dict(assistant_model_json).__dict__ + assistant_model2 = Assistant(**assistant_model_dict) + + # Verify the model instances are equivalent + assert assistant_model == assistant_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_model_json2 = assistant_model.to_dict() + assert assistant_model_json2 == assistant_model_json + +class TestModel_AssistantCollection(): + """ + Test Class for AssistantCollection + """ + + def test_assistant_collection_serialization(self): + """ + Test serialization/deserialization for AssistantCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + assistant_model = {} # Assistant + assistant_model['name'] = 'testString' + assistant_model['description'] = 'testString' + assistant_model['language'] = 'testString' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a AssistantCollection model + assistant_collection_model_json = {} + assistant_collection_model_json['assistants'] = [assistant_model] + assistant_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of AssistantCollection by calling from_dict on the json representation + assistant_collection_model = AssistantCollection.from_dict(assistant_collection_model_json) + assert assistant_collection_model != False + + # Construct a model instance of AssistantCollection by calling from_dict on the json representation + assistant_collection_model_dict = AssistantCollection.from_dict(assistant_collection_model_json).__dict__ + assistant_collection_model2 = AssistantCollection(**assistant_collection_model_dict) + + # Verify the model instances are equivalent + assert assistant_collection_model == assistant_collection_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_collection_model_json2 = assistant_collection_model.to_dict() + assert assistant_collection_model_json2 == assistant_collection_model_json + +class TestModel_AssistantSkill(): + """ + Test Class for AssistantSkill + """ + + def test_assistant_skill_serialization(self): + """ + Test serialization/deserialization for AssistantSkill + """ + + # Construct a json representation of a AssistantSkill model + assistant_skill_model_json = {} + assistant_skill_model_json['skill_id'] = 'testString' + assistant_skill_model_json['type'] = 'dialog' + + # Construct a model instance of AssistantSkill by calling from_dict on the json representation + assistant_skill_model = AssistantSkill.from_dict(assistant_skill_model_json) + assert assistant_skill_model != False + + # Construct a model instance of AssistantSkill by calling from_dict on the json representation + assistant_skill_model_dict = AssistantSkill.from_dict(assistant_skill_model_json).__dict__ + assistant_skill_model2 = AssistantSkill(**assistant_skill_model_dict) + + # Verify the model instances are equivalent + assert assistant_skill_model == assistant_skill_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_skill_model_json2 = assistant_skill_model.to_dict() + assert assistant_skill_model_json2 == assistant_skill_model_json + +class TestModel_AssistantState(): + """ + Test Class for AssistantState + """ + + def test_assistant_state_serialization(self): + """ + Test serialization/deserialization for AssistantState + """ + + # Construct a json representation of a AssistantState model + assistant_state_model_json = {} + assistant_state_model_json['action_disabled'] = True + assistant_state_model_json['dialog_disabled'] = True + + # Construct a model instance of AssistantState by calling from_dict on the json representation + assistant_state_model = AssistantState.from_dict(assistant_state_model_json) + assert assistant_state_model != False + + # Construct a model instance of AssistantState by calling from_dict on the json representation + assistant_state_model_dict = AssistantState.from_dict(assistant_state_model_json).__dict__ + assistant_state_model2 = AssistantState(**assistant_state_model_dict) + + # Verify the model instances are equivalent + assert assistant_state_model == assistant_state_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_state_model_json2 = assistant_state_model.to_dict() + assert assistant_state_model_json2 == assistant_state_model_json + +class TestModel_BaseEnvironmentOrchestration(): + """ + Test Class for BaseEnvironmentOrchestration + """ + + def test_base_environment_orchestration_serialization(self): + """ + Test serialization/deserialization for BaseEnvironmentOrchestration + """ + + # Construct a json representation of a BaseEnvironmentOrchestration model + base_environment_orchestration_model_json = {} + base_environment_orchestration_model_json['search_skill_fallback'] = True + + # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation + base_environment_orchestration_model = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json) + assert base_environment_orchestration_model != False + + # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation + base_environment_orchestration_model_dict = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json).__dict__ + base_environment_orchestration_model2 = BaseEnvironmentOrchestration(**base_environment_orchestration_model_dict) + + # Verify the model instances are equivalent + assert base_environment_orchestration_model == base_environment_orchestration_model2 + + # Convert model instance back to dict and verify no loss of data + base_environment_orchestration_model_json2 = base_environment_orchestration_model.to_dict() + assert base_environment_orchestration_model_json2 == base_environment_orchestration_model_json + +class TestModel_BaseEnvironmentReleaseReference(): + """ + Test Class for BaseEnvironmentReleaseReference + """ + + def test_base_environment_release_reference_serialization(self): + """ + Test serialization/deserialization for BaseEnvironmentReleaseReference + """ + + # Construct a json representation of a BaseEnvironmentReleaseReference model + base_environment_release_reference_model_json = {} + base_environment_release_reference_model_json['release'] = 'testString' + + # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation + base_environment_release_reference_model = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json) + assert base_environment_release_reference_model != False + + # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation + base_environment_release_reference_model_dict = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json).__dict__ + base_environment_release_reference_model2 = BaseEnvironmentReleaseReference(**base_environment_release_reference_model_dict) + + # Verify the model instances are equivalent + assert base_environment_release_reference_model == base_environment_release_reference_model2 + + # Convert model instance back to dict and verify no loss of data + base_environment_release_reference_model_json2 = base_environment_release_reference_model.to_dict() + assert base_environment_release_reference_model_json2 == base_environment_release_reference_model_json + class TestModel_BulkClassifyOutput(): """ Test Class for BulkClassifyOutput @@ -2305,6 +3699,11 @@ def test_dialog_node_output_options_element_serialization(self): message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -2324,6 +3723,7 @@ def test_dialog_node_output_options_element_serialization(self): message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue @@ -2420,6 +3820,11 @@ def test_dialog_node_output_options_element_value_serialization(self): message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -2439,6 +3844,7 @@ def test_dialog_node_output_options_element_value_serialization(self): message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model # Construct a json representation of a DialogNodeOutputOptionsElementValue model @@ -2562,6 +3968,11 @@ def test_dialog_suggestion_serialization(self): message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -2581,6 +3992,7 @@ def test_dialog_suggestion_serialization(self): message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model dialog_suggestion_value_model = {} # DialogSuggestionValue @@ -2678,6 +4090,11 @@ def test_dialog_suggestion_value_serialization(self): message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -2697,6 +4114,7 @@ def test_dialog_suggestion_value_serialization(self): message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model # Construct a json representation of a DialogSuggestionValue model @@ -2730,25 +4148,19 @@ def test_environment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - integration_reference_model = {} # IntegrationReference - integration_reference_model['integration_id'] = 'testString' - integration_reference_model['type'] = 'testString' - - skill_reference_model = {} # SkillReference - skill_reference_model['skill_id'] = 'testString' - skill_reference_model['type'] = 'dialog' - skill_reference_model['disabled'] = True - skill_reference_model['snapshot'] = 'testString' - skill_reference_model['skill_reference'] = 'testString' + environment_skill_model = {} # EnvironmentSkill + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' # Construct a json representation of a Environment model environment_model_json = {} environment_model_json['name'] = 'testString' environment_model_json['description'] = 'testString' - environment_model_json['language'] = 'testString' - environment_model_json['session_timeout'] = 38 - environment_model_json['integration_references'] = [integration_reference_model] - environment_model_json['skill_references'] = [skill_reference_model] + environment_model_json['session_timeout'] = 10 + environment_model_json['skill_references'] = [environment_skill_model] # Construct a model instance of Environment by calling from_dict on the json representation environment_model = Environment.from_dict(environment_model_json) @@ -2777,24 +4189,18 @@ def test_environment_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - integration_reference_model = {} # IntegrationReference - integration_reference_model['integration_id'] = 'testString' - integration_reference_model['type'] = 'testString' - - skill_reference_model = {} # SkillReference - skill_reference_model['skill_id'] = 'testString' - skill_reference_model['type'] = 'dialog' - skill_reference_model['disabled'] = True - skill_reference_model['snapshot'] = 'testString' - skill_reference_model['skill_reference'] = 'testString' + environment_skill_model = {} # EnvironmentSkill + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' environment_model = {} # Environment environment_model['name'] = 'testString' environment_model['description'] = 'testString' - environment_model['language'] = 'testString' - environment_model['session_timeout'] = 38 - environment_model['integration_references'] = [integration_reference_model] - environment_model['skill_references'] = [skill_reference_model] + environment_model['session_timeout'] = 10 + environment_model['skill_references'] = [environment_skill_model] pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -2824,35 +4230,6 @@ def test_environment_collection_serialization(self): environment_collection_model_json2 = environment_collection_model.to_dict() assert environment_collection_model_json2 == environment_collection_model_json -class TestModel_EnvironmentOrchestration(): - """ - Test Class for EnvironmentOrchestration - """ - - def test_environment_orchestration_serialization(self): - """ - Test serialization/deserialization for EnvironmentOrchestration - """ - - # Construct a json representation of a EnvironmentOrchestration model - environment_orchestration_model_json = {} - environment_orchestration_model_json['search_skill_fallback'] = True - - # Construct a model instance of EnvironmentOrchestration by calling from_dict on the json representation - environment_orchestration_model = EnvironmentOrchestration.from_dict(environment_orchestration_model_json) - assert environment_orchestration_model != False - - # Construct a model instance of EnvironmentOrchestration by calling from_dict on the json representation - environment_orchestration_model_dict = EnvironmentOrchestration.from_dict(environment_orchestration_model_json).__dict__ - environment_orchestration_model2 = EnvironmentOrchestration(**environment_orchestration_model_dict) - - # Verify the model instances are equivalent - assert environment_orchestration_model == environment_orchestration_model2 - - # Convert model instance back to dict and verify no loss of data - environment_orchestration_model_json2 = environment_orchestration_model.to_dict() - assert environment_orchestration_model_json2 == environment_orchestration_model_json - class TestModel_EnvironmentReference(): """ Test Class for EnvironmentReference @@ -2882,34 +4259,38 @@ def test_environment_reference_serialization(self): environment_reference_model_json2 = environment_reference_model.to_dict() assert environment_reference_model_json2 == environment_reference_model_json -class TestModel_EnvironmentReleaseReference(): +class TestModel_EnvironmentSkill(): """ - Test Class for EnvironmentReleaseReference + Test Class for EnvironmentSkill """ - def test_environment_release_reference_serialization(self): + def test_environment_skill_serialization(self): """ - Test serialization/deserialization for EnvironmentReleaseReference + Test serialization/deserialization for EnvironmentSkill """ - # Construct a json representation of a EnvironmentReleaseReference model - environment_release_reference_model_json = {} - environment_release_reference_model_json['release'] = 'testString' + # Construct a json representation of a EnvironmentSkill model + environment_skill_model_json = {} + environment_skill_model_json['skill_id'] = 'testString' + environment_skill_model_json['type'] = 'dialog' + environment_skill_model_json['disabled'] = True + environment_skill_model_json['snapshot'] = 'testString' + environment_skill_model_json['skill_reference'] = 'testString' - # Construct a model instance of EnvironmentReleaseReference by calling from_dict on the json representation - environment_release_reference_model = EnvironmentReleaseReference.from_dict(environment_release_reference_model_json) - assert environment_release_reference_model != False + # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation + environment_skill_model = EnvironmentSkill.from_dict(environment_skill_model_json) + assert environment_skill_model != False - # Construct a model instance of EnvironmentReleaseReference by calling from_dict on the json representation - environment_release_reference_model_dict = EnvironmentReleaseReference.from_dict(environment_release_reference_model_json).__dict__ - environment_release_reference_model2 = EnvironmentReleaseReference(**environment_release_reference_model_dict) + # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation + environment_skill_model_dict = EnvironmentSkill.from_dict(environment_skill_model_json).__dict__ + environment_skill_model2 = EnvironmentSkill(**environment_skill_model_dict) # Verify the model instances are equivalent - assert environment_release_reference_model == environment_release_reference_model2 + assert environment_skill_model == environment_skill_model2 # Convert model instance back to dict and verify no loss of data - environment_release_reference_model_json2 = environment_release_reference_model.to_dict() - assert environment_release_reference_model_json2 == environment_release_reference_model_json + environment_skill_model_json2 = environment_skill_model.to_dict() + assert environment_skill_model_json2 == environment_skill_model_json class TestModel_IntegrationReference(): """ @@ -3012,6 +4393,11 @@ def test_log_serialization(self): message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -3031,6 +4417,7 @@ def test_log_serialization(self): message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model message_context_global_system_model = {} # MessageContextGlobalSystem @@ -3106,6 +4493,7 @@ def test_log_serialization(self): message_output_debug_turn_event_model['action_start_time'] = 'testString' message_output_debug_turn_event_model['condition_type'] = 'user_defined' message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] @@ -3233,6 +4621,11 @@ def test_log_collection_serialization(self): message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -3252,6 +4645,7 @@ def test_log_collection_serialization(self): message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model message_context_global_system_model = {} # MessageContextGlobalSystem @@ -3327,6 +4721,7 @@ def test_log_collection_serialization(self): message_output_debug_turn_event_model['action_start_time'] = 'testString' message_output_debug_turn_event_model['condition_type'] = 'user_defined' message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] @@ -3798,6 +5193,11 @@ def test_message_input_serialization(self): message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -3818,6 +5218,7 @@ def test_message_input_serialization(self): message_input_model_json['entities'] = [runtime_entity_model] message_input_model_json['suggestion_id'] = 'testString' message_input_model_json['attachments'] = [message_input_attachment_model] + message_input_model_json['analytics'] = request_analytics_model message_input_model_json['options'] = message_input_options_model # Construct a model instance of MessageInput by calling from_dict on the json representation @@ -4044,6 +5445,11 @@ def test_message_input_stateless_serialization(self): message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -4062,6 +5468,7 @@ def test_message_input_stateless_serialization(self): message_input_stateless_model_json['entities'] = [runtime_entity_model] message_input_stateless_model_json['suggestion_id'] = 'testString' message_input_stateless_model_json['attachments'] = [message_input_attachment_model] + message_input_stateless_model_json['analytics'] = request_analytics_model message_input_stateless_model_json['options'] = message_input_options_stateless_model # Construct a model instance of MessageInputStateless by calling from_dict on the json representation @@ -4188,6 +5595,7 @@ def test_message_output_serialization(self): message_output_debug_turn_event_model['action_start_time'] = 'testString' message_output_debug_turn_event_model['condition_type'] = 'user_defined' message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] @@ -4265,6 +5673,7 @@ def test_message_output_debug_serialization(self): message_output_debug_turn_event_model['action_start_time'] = 'testString' message_output_debug_turn_event_model['condition_type'] = 'user_defined' message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' # Construct a json representation of a MessageOutputDebug model message_output_debug_model_json = {} @@ -4391,6 +5800,11 @@ def test_message_request_serialization(self): message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -4410,6 +5824,7 @@ def test_message_request_serialization(self): message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model message_context_global_system_model = {} # MessageContextGlobalSystem @@ -4568,6 +5983,7 @@ def test_message_response_serialization(self): message_output_debug_turn_event_model['action_start_time'] = 'testString' message_output_debug_turn_event_model['condition_type'] = 'user_defined' message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] @@ -4746,6 +6162,7 @@ def test_message_response_stateless_serialization(self): message_output_debug_turn_event_model['action_start_time'] = 'testString' message_output_debug_turn_event_model['condition_type'] = 'user_defined' message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] @@ -4862,9 +6279,7 @@ def test_release_serialization(self): # Construct a json representation of a Release model release_model_json = {} - release_model_json['release'] = 'testString' release_model_json['description'] = 'testString' - release_model_json['status'] = 'Available' # Construct a model instance of Release by calling from_dict on the json representation release_model = Release.from_dict(release_model_json) @@ -4894,9 +6309,7 @@ def test_release_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. release_model = {} # Release - release_model['release'] = 'testString' release_model['description'] = 'testString' - release_model['status'] = 'Available' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -4954,36 +6367,67 @@ def test_release_content_serialization(self): release_content_model_json2 = release_content_model.to_dict() assert release_content_model_json2 == release_content_model_json -class TestModel_ReleaseSkillReference(): +class TestModel_ReleaseSkill(): + """ + Test Class for ReleaseSkill + """ + + def test_release_skill_serialization(self): + """ + Test serialization/deserialization for ReleaseSkill + """ + + # Construct a json representation of a ReleaseSkill model + release_skill_model_json = {} + release_skill_model_json['skill_id'] = 'testString' + release_skill_model_json['type'] = 'dialog' + release_skill_model_json['snapshot'] = 'testString' + + # Construct a model instance of ReleaseSkill by calling from_dict on the json representation + release_skill_model = ReleaseSkill.from_dict(release_skill_model_json) + assert release_skill_model != False + + # Construct a model instance of ReleaseSkill by calling from_dict on the json representation + release_skill_model_dict = ReleaseSkill.from_dict(release_skill_model_json).__dict__ + release_skill_model2 = ReleaseSkill(**release_skill_model_dict) + + # Verify the model instances are equivalent + assert release_skill_model == release_skill_model2 + + # Convert model instance back to dict and verify no loss of data + release_skill_model_json2 = release_skill_model.to_dict() + assert release_skill_model_json2 == release_skill_model_json + +class TestModel_RequestAnalytics(): """ - Test Class for ReleaseSkillReference + Test Class for RequestAnalytics """ - def test_release_skill_reference_serialization(self): + def test_request_analytics_serialization(self): """ - Test serialization/deserialization for ReleaseSkillReference + Test serialization/deserialization for RequestAnalytics """ - # Construct a json representation of a ReleaseSkillReference model - release_skill_reference_model_json = {} - release_skill_reference_model_json['skill_id'] = 'testString' - release_skill_reference_model_json['type'] = 'dialog' - release_skill_reference_model_json['snapshot'] = 'testString' + # Construct a json representation of a RequestAnalytics model + request_analytics_model_json = {} + request_analytics_model_json['browser'] = 'testString' + request_analytics_model_json['device'] = 'testString' + request_analytics_model_json['pageUrl'] = 'testString' - # Construct a model instance of ReleaseSkillReference by calling from_dict on the json representation - release_skill_reference_model = ReleaseSkillReference.from_dict(release_skill_reference_model_json) - assert release_skill_reference_model != False + # Construct a model instance of RequestAnalytics by calling from_dict on the json representation + request_analytics_model = RequestAnalytics.from_dict(request_analytics_model_json) + assert request_analytics_model != False - # Construct a model instance of ReleaseSkillReference by calling from_dict on the json representation - release_skill_reference_model_dict = ReleaseSkillReference.from_dict(release_skill_reference_model_json).__dict__ - release_skill_reference_model2 = ReleaseSkillReference(**release_skill_reference_model_dict) + # Construct a model instance of RequestAnalytics by calling from_dict on the json representation + request_analytics_model_dict = RequestAnalytics.from_dict(request_analytics_model_json).__dict__ + request_analytics_model2 = RequestAnalytics(**request_analytics_model_dict) # Verify the model instances are equivalent - assert release_skill_reference_model == release_skill_reference_model2 + assert request_analytics_model == request_analytics_model2 # Convert model instance back to dict and verify no loss of data - release_skill_reference_model_json2 = release_skill_reference_model.to_dict() - assert release_skill_reference_model_json2 == release_skill_reference_model_json + request_analytics_model_json2 = request_analytics_model.to_dict() + assert request_analytics_model_json2 == request_analytics_model_json class TestModel_ResponseGenericChannel(): """ @@ -5389,6 +6833,37 @@ def test_search_result_metadata_serialization(self): search_result_metadata_model_json2 = search_result_metadata_model.to_dict() assert search_result_metadata_model_json2 == search_result_metadata_model_json +class TestModel_SearchSkillWarning(): + """ + Test Class for SearchSkillWarning + """ + + def test_search_skill_warning_serialization(self): + """ + Test serialization/deserialization for SearchSkillWarning + """ + + # Construct a json representation of a SearchSkillWarning model + search_skill_warning_model_json = {} + search_skill_warning_model_json['code'] = 'testString' + search_skill_warning_model_json['path'] = 'testString' + search_skill_warning_model_json['message'] = 'testString' + + # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation + search_skill_warning_model = SearchSkillWarning.from_dict(search_skill_warning_model_json) + assert search_skill_warning_model != False + + # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation + search_skill_warning_model_dict = SearchSkillWarning.from_dict(search_skill_warning_model_json).__dict__ + search_skill_warning_model2 = SearchSkillWarning(**search_skill_warning_model_dict) + + # Verify the model instances are equivalent + assert search_skill_warning_model == search_skill_warning_model2 + + # Convert model instance back to dict and verify no loss of data + search_skill_warning_model_json2 = search_skill_warning_model.to_dict() + assert search_skill_warning_model_json2 == search_skill_warning_model_json + class TestModel_SessionResponse(): """ Test Class for SessionResponse @@ -5418,38 +6893,177 @@ def test_session_response_serialization(self): session_response_model_json2 = session_response_model.to_dict() assert session_response_model_json2 == session_response_model_json -class TestModel_SkillReference(): +class TestModel_Skill(): + """ + Test Class for Skill + """ + + def test_skill_serialization(self): + """ + Test serialization/deserialization for Skill + """ + + # Construct a json representation of a Skill model + skill_model_json = {} + skill_model_json['name'] = 'testString' + skill_model_json['description'] = 'testString' + skill_model_json['workspace'] = {'foo': 'bar'} + skill_model_json['dialog_settings'] = {'foo': 'bar'} + skill_model_json['search_settings'] = {'foo': 'bar'} + skill_model_json['language'] = 'testString' + skill_model_json['type'] = 'action' + + # Construct a model instance of Skill by calling from_dict on the json representation + skill_model = Skill.from_dict(skill_model_json) + assert skill_model != False + + # Construct a model instance of Skill by calling from_dict on the json representation + skill_model_dict = Skill.from_dict(skill_model_json).__dict__ + skill_model2 = Skill(**skill_model_dict) + + # Verify the model instances are equivalent + assert skill_model == skill_model2 + + # Convert model instance back to dict and verify no loss of data + skill_model_json2 = skill_model.to_dict() + assert skill_model_json2 == skill_model_json + +class TestModel_SkillImport(): + """ + Test Class for SkillImport + """ + + def test_skill_import_serialization(self): + """ + Test serialization/deserialization for SkillImport + """ + + # Construct a json representation of a SkillImport model + skill_import_model_json = {} + skill_import_model_json['name'] = 'testString' + skill_import_model_json['description'] = 'testString' + skill_import_model_json['workspace'] = {'foo': 'bar'} + skill_import_model_json['dialog_settings'] = {'foo': 'bar'} + skill_import_model_json['search_settings'] = {'foo': 'bar'} + skill_import_model_json['language'] = 'testString' + skill_import_model_json['type'] = 'action' + + # Construct a model instance of SkillImport by calling from_dict on the json representation + skill_import_model = SkillImport.from_dict(skill_import_model_json) + assert skill_import_model != False + + # Construct a model instance of SkillImport by calling from_dict on the json representation + skill_import_model_dict = SkillImport.from_dict(skill_import_model_json).__dict__ + skill_import_model2 = SkillImport(**skill_import_model_dict) + + # Verify the model instances are equivalent + assert skill_import_model == skill_import_model2 + + # Convert model instance back to dict and verify no loss of data + skill_import_model_json2 = skill_import_model.to_dict() + assert skill_import_model_json2 == skill_import_model_json + +class TestModel_SkillsAsyncRequestStatus(): """ - Test Class for SkillReference + Test Class for SkillsAsyncRequestStatus """ - def test_skill_reference_serialization(self): + def test_skills_async_request_status_serialization(self): """ - Test serialization/deserialization for SkillReference + Test serialization/deserialization for SkillsAsyncRequestStatus """ - # Construct a json representation of a SkillReference model - skill_reference_model_json = {} - skill_reference_model_json['skill_id'] = 'testString' - skill_reference_model_json['type'] = 'dialog' - skill_reference_model_json['disabled'] = True - skill_reference_model_json['snapshot'] = 'testString' - skill_reference_model_json['skill_reference'] = 'testString' + # Construct a json representation of a SkillsAsyncRequestStatus model + skills_async_request_status_model_json = {} - # Construct a model instance of SkillReference by calling from_dict on the json representation - skill_reference_model = SkillReference.from_dict(skill_reference_model_json) - assert skill_reference_model != False + # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation + skills_async_request_status_model = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json) + assert skills_async_request_status_model != False - # Construct a model instance of SkillReference by calling from_dict on the json representation - skill_reference_model_dict = SkillReference.from_dict(skill_reference_model_json).__dict__ - skill_reference_model2 = SkillReference(**skill_reference_model_dict) + # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation + skills_async_request_status_model_dict = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json).__dict__ + skills_async_request_status_model2 = SkillsAsyncRequestStatus(**skills_async_request_status_model_dict) # Verify the model instances are equivalent - assert skill_reference_model == skill_reference_model2 + assert skills_async_request_status_model == skills_async_request_status_model2 # Convert model instance back to dict and verify no loss of data - skill_reference_model_json2 = skill_reference_model.to_dict() - assert skill_reference_model_json2 == skill_reference_model_json + skills_async_request_status_model_json2 = skills_async_request_status_model.to_dict() + assert skills_async_request_status_model_json2 == skills_async_request_status_model_json + +class TestModel_SkillsExport(): + """ + Test Class for SkillsExport + """ + + def test_skills_export_serialization(self): + """ + Test serialization/deserialization for SkillsExport + """ + + # Construct dict forms of any model objects needed in order to build this model. + + skill_model = {} # Skill + skill_model['name'] = 'testString' + skill_model['description'] = 'testString' + skill_model['workspace'] = {'foo': 'bar'} + skill_model['dialog_settings'] = {'foo': 'bar'} + skill_model['search_settings'] = {'foo': 'bar'} + skill_model['language'] = 'testString' + skill_model['type'] = 'action' + + assistant_state_model = {} # AssistantState + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Construct a json representation of a SkillsExport model + skills_export_model_json = {} + skills_export_model_json['assistant_skills'] = [skill_model] + skills_export_model_json['assistant_state'] = assistant_state_model + + # Construct a model instance of SkillsExport by calling from_dict on the json representation + skills_export_model = SkillsExport.from_dict(skills_export_model_json) + assert skills_export_model != False + + # Construct a model instance of SkillsExport by calling from_dict on the json representation + skills_export_model_dict = SkillsExport.from_dict(skills_export_model_json).__dict__ + skills_export_model2 = SkillsExport(**skills_export_model_dict) + + # Verify the model instances are equivalent + assert skills_export_model == skills_export_model2 + + # Convert model instance back to dict and verify no loss of data + skills_export_model_json2 = skills_export_model.to_dict() + assert skills_export_model_json2 == skills_export_model_json + +class TestModel_StatusError(): + """ + Test Class for StatusError + """ + + def test_status_error_serialization(self): + """ + Test serialization/deserialization for StatusError + """ + + # Construct a json representation of a StatusError model + status_error_model_json = {} + status_error_model_json['message'] = 'testString' + + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model = StatusError.from_dict(status_error_model_json) + assert status_error_model != False + + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model_dict = StatusError.from_dict(status_error_model_json).__dict__ + status_error_model2 = StatusError(**status_error_model_dict) + + # Verify the model instances are equivalent + assert status_error_model == status_error_model2 + + # Convert model instance back to dict and verify no loss of data + status_error_model_json2 = status_error_model.to_dict() + assert status_error_model_json2 == status_error_model_json class TestModel_TurnEventActionSource(): """ @@ -5497,6 +7111,7 @@ def test_turn_event_callout_callout_serialization(self): turn_event_callout_callout_model_json = {} turn_event_callout_callout_model_json['type'] = 'integration_interaction' turn_event_callout_callout_model_json['internal'] = {'foo': 'bar'} + turn_event_callout_callout_model_json['result_variable'] = 'testString' # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation turn_event_callout_callout_model = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json) @@ -5793,6 +7408,7 @@ def test_message_output_debug_turn_event_turn_event_action_visited_serialization message_output_debug_turn_event_turn_event_action_visited_model_json['action_start_time'] = 'testString' message_output_debug_turn_event_turn_event_action_visited_model_json['condition_type'] = 'user_defined' message_output_debug_turn_event_turn_event_action_visited_model_json['reason'] = 'intent' + message_output_debug_turn_event_turn_event_action_visited_model_json['result_variable'] = 'testString' # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionVisited by calling from_dict on the json representation message_output_debug_turn_event_turn_event_action_visited_model = MessageOutputDebugTurnEventTurnEventActionVisited.from_dict(message_output_debug_turn_event_turn_event_action_visited_model_json) @@ -5830,6 +7446,7 @@ def test_message_output_debug_turn_event_turn_event_callout_serialization(self): turn_event_callout_callout_model = {} # TurnEventCalloutCallout turn_event_callout_callout_model['type'] = 'integration_interaction' turn_event_callout_callout_model['internal'] = {'foo': 'bar'} + turn_event_callout_callout_model['result_variable'] = 'testString' turn_event_callout_error_model = {} # TurnEventCalloutError turn_event_callout_error_model['message'] = 'testString' @@ -6368,6 +7985,11 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -6387,6 +8009,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue @@ -6592,6 +8215,11 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -6611,6 +8239,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_model['entities'] = [runtime_entity_model] message_input_model['suggestion_id'] = 'testString' message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model dialog_suggestion_value_model = {} # DialogSuggestionValue From 8b9f6a897e2e9d3fdb43aa0ce1adc8b2a581f4e9 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 2 Mar 2023 10:14:34 -0600 Subject: [PATCH 390/455] feat(stt, tts): add more models --- ibm_watson/speech_to_text_v1.py | 147 ++++++++++++------------ ibm_watson/text_to_speech_adapter_v1.py | 4 +- ibm_watson/text_to_speech_v1.py | 9 ++ 3 files changed, 86 insertions(+), 74 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index a16b7c92e..bd2c5b713 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -27,11 +27,10 @@ have minimum sampling rates of 16 kHz. Narrowband and telephony models have minimum sampling rates of 8 kHz. The next-generation models offer high throughput and greater transcription accuracy. -Effective **15 March 2022**, previous-generation models for all languages other than -Arabic and Japanese are deprecated. The deprecated models remain available until **31 July -2023**, when they will be removed from the service and the documentation. You must migrate -to the equivalent next-generation model by the end of service date. For more information, -see [Migrating to next-generation +Effective **31 July 2023**, all previous-generation models will be removed from the +service and the documentation. Most previous-generation models were deprecated on 15 March +2022. You must migrate to the equivalent next-generation model by 31 July 2023. For more +information, see [Migrating to next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate).{: deprecated} For speech recognition, the service supports synchronous and asynchronous HTTP @@ -278,11 +277,10 @@ def recognize(self, * `keywords` and `keywords_threshold` * `processing_metrics` and `processing_metrics_interval` * `word_alternatives_threshold` - **Important:** Effective **15 March 2022**, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until **31 July 2023**, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent + next-generation model by 31 July 2023. For more information, see [Migrating to next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** @@ -352,14 +350,18 @@ def recognize(self, to words from the custom language model compared to those from the base model for the current request. Specify a value between 0.0 and 1.0. Unless a different customization - weight was specified for the custom model when it was trained, the default - value is 0.3. A customization weight that you specify overrides a weight - that was specified when the custom model was trained. - The default value yields the best performance in general. Assign a higher - value if your audio makes frequent use of OOV words from the custom model. - Use caution when setting the weight: a higher value can improve the - accuracy of phrases from the custom model's domain, but it can negatively - affect performance on non-domain phrases. + weight was specified for the custom model when the model was trained, the + default value is: + * 0.3 for previous-generation models + * 0.2 for most next-generation models + * 0.1 for next-generation English and Japanese models + A customization weight that you specify overrides a weight that was + specified when the custom model was trained. The default value yields the + best performance in general. Assign a higher value if your audio makes + frequent use of OOV words from the custom model. Use caution when setting + the weight: a higher value can improve the accuracy of phrases from the + custom model's domain, but it can negatively affect performance on + non-domain phrases. See [Using customization weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). :param int inactivity_timeout: (optional) The time in seconds after which, @@ -466,12 +468,12 @@ def recognize(self, default, the service returns no audio metrics. See [Audio 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 - silence before it reaches the end of the audio stream, its response can - include multiple final results. Silence indicates a point at which the - speaker pauses between spoken words or phrases. + :param float end_of_phrase_silence_time: (optional) 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 silence + before it reaches the end of the audio stream, its response can include + multiple final results. Silence indicates a point at which the speaker + pauses between spoken words or phrases. Specify a value for the pause interval in the range of 0.0 to 120.0. * A value greater than 0 specifies the interval that the service is to use for speech recognition. @@ -545,13 +547,11 @@ def recognize(self, * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). :param float character_insertion_bias: (optional) For next-generation - `Multimedia` and `Telephony` models, an indication of whether the service - is biased to recognize shorter or longer strings of characters when - developing transcription hypotheses. By default, the service is optimized - for each individual model to balance its recognition of strings of - different lengths. The model-specific bias is equivalent to 0.0. - The value that you specify represents a change from a model's default bias. - The allowable range of values is -1.0 to 1.0. + models, an indication of whether the service is biased to recognize shorter + or longer strings of characters when developing transcription hypotheses. + By default, the service is optimized to produce the best balance of strings + of different lengths. + The default bias is 0.0. The allowable range of values is -1.0 to 1.0. * Negative values bias the service to favor hypotheses with shorter strings of characters. * Positive values bias the service to favor hypotheses with longer strings @@ -562,8 +562,7 @@ def recognize(self, -0.1, -0.05, 0.05, or 0.1, and assess how the value impacts the transcription results. Then experiment with different values as necessary, adjusting the value by small increments. - The parameter is not available for previous-generation `Broadband` and - `Narrowband` models. + The parameter is not available for previous-generation models. See [Character insertion bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). :param dict headers: A `dict` containing the request headers @@ -891,11 +890,10 @@ def create_job(self, * `keywords` and `keywords_threshold` * `processing_metrics` and `processing_metrics_interval` * `word_alternatives_threshold` - **Important:** Effective **15 March 2022**, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until **31 July 2023**, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent + next-generation model by 31 July 2023. For more information, see [Migrating to next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** @@ -987,14 +985,18 @@ def create_job(self, to words from the custom language model compared to those from the base model for the current request. Specify a value between 0.0 and 1.0. Unless a different customization - weight was specified for the custom model when it was trained, the default - value is 0.3. A customization weight that you specify overrides a weight - that was specified when the custom model was trained. - The default value yields the best performance in general. Assign a higher - value if your audio makes frequent use of OOV words from the custom model. - Use caution when setting the weight: a higher value can improve the - accuracy of phrases from the custom model's domain, but it can negatively - affect performance on non-domain phrases. + weight was specified for the custom model when the model was trained, the + default value is: + * 0.3 for previous-generation models + * 0.2 for most next-generation models + * 0.1 for next-generation English and Japanese models + A customization weight that you specify overrides a weight that was + specified when the custom model was trained. The default value yields the + best performance in general. Assign a higher value if your audio makes + frequent use of OOV words from the custom model. Use caution when setting + the weight: a higher value can improve the accuracy of phrases from the + custom model's domain, but it can negatively affect performance on + non-domain phrases. See [Using customization weight](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageUse#weight). :param int inactivity_timeout: (optional) The time in seconds after which, @@ -1123,12 +1125,12 @@ def create_job(self, default, the service returns no audio metrics. See [Audio 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 - silence before it reaches the end of the audio stream, its response can - include multiple final results. Silence indicates a point at which the - speaker pauses between spoken words or phrases. + :param float end_of_phrase_silence_time: (optional) 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 silence + before it reaches the end of the audio stream, its response can include + multiple final results. Silence indicates a point at which the speaker + pauses between spoken words or phrases. Specify a value for the pause interval in the range of 0.0 to 120.0. * A value greater than 0 specifies the interval that the service is to use for speech recognition. @@ -1202,13 +1204,11 @@ def create_job(self, * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). :param float character_insertion_bias: (optional) For next-generation - `Multimedia` and `Telephony` models, an indication of whether the service - is biased to recognize shorter or longer strings of characters when - developing transcription hypotheses. By default, the service is optimized - for each individual model to balance its recognition of strings of - different lengths. The model-specific bias is equivalent to 0.0. - The value that you specify represents a change from a model's default bias. - The allowable range of values is -1.0 to 1.0. + models, an indication of whether the service is biased to recognize shorter + or longer strings of characters when developing transcription hypotheses. + By default, the service is optimized to produce the best balance of strings + of different lengths. + The default bias is 0.0. The allowable range of values is -1.0 to 1.0. * Negative values bias the service to favor hypotheses with shorter strings of characters. * Positive values bias the service to favor hypotheses with longer strings @@ -1219,8 +1219,7 @@ def create_job(self, -0.1, -0.05, 0.05, or 0.1, and assess how the value impacts the transcription results. Then experiment with different values as necessary, adjusting the value by small increments. - The parameter is not available for previous-generation `Broadband` and - `Narrowband` models. + The parameter is not available for previous-generation models. See [Character insertion bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). :param dict headers: A `dict` containing the request headers @@ -1437,11 +1436,10 @@ def create_language_model(self, The service returns an error if you attempt to create more than 1024 models. You do not lose any models, but you cannot create any more until your model count is below the limit. - **Important:** Effective **15 March 2022**, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until **31 July 2023**, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent + next-generation model by 31 July 2023. For more information, see [Migrating to next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** @@ -1738,7 +1736,10 @@ def train_language_model(self, weight for the custom language model. The customization weight tells the service how much weight to give to words from the custom language model compared to those from the base model for speech recognition. Specify a - value between 0.0 and 1.0; the default is 0.3. + value between 0.0 and 1.0. The default value is: + * 0.3 for previous-generation models + * 0.2 for most next-generation models + * 0.1 for next-generation English and Japanese models The default value yields the best performance in general. Assign a higher value if your audio makes frequent use of OOV words from the custom model. Use caution when setting the weight: a higher value can improve the @@ -2950,11 +2951,10 @@ def create_acoustic_model(self, below the limit. **Note:** Acoustic model customization is supported only for use with previous-generation models. It is not supported for next-generation models. - **Important:** Effective **15 March 2022**, previous-generation models for all - languages other than Arabic and Japanese are deprecated. The deprecated models - remain available until **31 July 2023**, when they will be removed from the - service and the documentation. You must migrate to the equivalent next-generation - model by the end of service date. For more information, see [Migrating to + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent + next-generation model by 31 July 2023. For more information, see [Migrating to next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** [Create a custom acoustic @@ -3907,6 +3907,7 @@ class ModelId(str, Enum): JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + JA_JP_TELEPHONY = 'ja-JP_Telephony' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' @@ -4019,6 +4020,7 @@ class Model(str, Enum): JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + JA_JP_TELEPHONY = 'ja-JP_Telephony' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' @@ -4131,6 +4133,7 @@ class Model(str, Enum): JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' + JA_JP_TELEPHONY = 'ja-JP_Telephony' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' diff --git a/ibm_watson/text_to_speech_adapter_v1.py b/ibm_watson/text_to_speech_adapter_v1.py index 6734d1ad0..0cd22fd74 100644 --- a/ibm_watson/text_to_speech_adapter_v1.py +++ b/ibm_watson/text_to_speech_adapter_v1.py @@ -31,8 +31,8 @@ def synthesize_using_websocket(self, timings=None, customization_id=None, spell_out_mode=None, - rate_percentage= None, - pitch_percentage= None, + rate_percentage=None, + pitch_percentage=None, http_proxy_host=None, http_proxy_port=None, **kwargs): diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index d5a028079..a96478e8c 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1671,6 +1671,8 @@ class Voice(str, Enum): DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' + EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' + EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' @@ -1697,6 +1699,7 @@ class Voice(str, Enum): IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' + KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' @@ -1757,6 +1760,8 @@ class Voice(str, Enum): DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' + EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' + EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' @@ -1783,6 +1788,7 @@ class Voice(str, Enum): IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' + KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' @@ -1842,6 +1848,8 @@ class Voice(str, Enum): DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' + EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' + EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' @@ -1868,6 +1876,7 @@ class Voice(str, Enum): IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' + KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' From a84cd6c983d913811b7943e579126e6a1c71781f Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 2 Mar 2023 10:23:57 -0600 Subject: [PATCH 391/455] feat(assistantv2): improved typing --- ibm_watson/assistant_v2.py | 848 ++++++++++++++++++++++++++++++--- test/unit/test_assistant_v2.py | 831 ++++++++++++++++++++++++++++---- 2 files changed, 1522 insertions(+), 157 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 4ebc50f34..6c7017fa1 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -176,6 +176,7 @@ def list_assistants(self, headers.update(sdk_headers) params = { + 'version': self.version, 'page_limit': page_limit, 'include_count': include_count, 'sort': sort, @@ -1456,7 +1457,7 @@ def update_skill(self, description: str = None, workspace: dict = None, dialog_settings: dict = None, - search_settings: dict = None, + search_settings: 'SearchSettings' = None, **kwargs) -> DetailedResponse: """ Update skill. @@ -1489,8 +1490,8 @@ def update_skill(self, :param dict workspace: (optional) An object containing the conversational content of an action or dialog skill. :param dict dialog_settings: (optional) For internal use only. - :param dict search_settings: (optional) A JSON object describing the search - skill configuration. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Skill` object @@ -1500,6 +1501,8 @@ def update_skill(self, raise ValueError('assistant_id must be provided') if not skill_id: raise ValueError('skill_id must be provided') + if search_settings is not None: + search_settings = convert_model(search_settings) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', @@ -4402,8 +4405,8 @@ class MessageContext(): :attr MessageContextGlobal global_: (optional) Session context data that is shared by all skills used by the assistant. - :attr dict skills: (optional) Information specific to particular skills used by - the assistant. + :attr MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. :attr dict integrations: (optional) An object containing context data that is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). @@ -4412,15 +4415,15 @@ class MessageContext(): def __init__(self, *, global_: 'MessageContextGlobal' = None, - skills: dict = None, + skills: 'MessageContextSkills' = None, integrations: dict = None) -> None: """ Initialize a MessageContext object. :param MessageContextGlobal global_: (optional) Session context data that is shared by all skills used by the assistant. - :param dict skills: (optional) Information specific to particular skills - used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. :param dict integrations: (optional) An object containing context data that is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). @@ -4437,10 +4440,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageContext': args['global_'] = MessageContextGlobal.from_dict( _dict.get('global')) if 'skills' in _dict: - args['skills'] = { - k: MessageContextSkill.from_dict(v) - for k, v in _dict.get('skills').items() - } + args['skills'] = MessageContextSkills.from_dict(_dict.get('skills')) if 'integrations' in _dict: args['integrations'] = _dict.get('integrations') return cls(**args) @@ -4459,13 +4459,10 @@ def to_dict(self) -> Dict: else: _dict['global'] = self.global_.to_dict() if hasattr(self, 'skills') and self.skills is not None: - skills_map = {} - for k, v in self.skills.items(): - if isinstance(v, dict): - skills_map[k] = v - else: - skills_map[k] = v.to_dict() - _dict['skills'] = skills_map + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations return _dict @@ -4849,15 +4846,112 @@ class LocaleEnum(str, Enum): ZH_TW = 'zh-tw' -class MessageContextSkill(): +class MessageContextSkillAction(): """ - Contains information specific to a particular skill used by the assistant. The - property name must be the same as the name of the skill. - **Note:** The default skill names are `main skill` for the dialog skill (if enabled) - and `actions skill` for the action skill. + Context variables that are used by the action skill. - :attr dict user_defined: (optional) Arbitrary variables that can be read and - written by a particular skill. + :attr dict user_defined: (optional) An object containing any arbitrary variables + that can be read and written by a particular skill. + :attr MessageContextSkillSystem system: (optional) System context data used by + the skill. + :attr dict action_variables: (optional) An object containing action variables. + Action variables can be accessed only by steps in the same action, and do not + persist after the action ends. + :attr dict skill_variables: (optional) An object containing skill variables. (In + the Watson Assistant user interface, skill variables are called _session + variables_.) Skill variables can be accessed by any action and persist for the + duration of the session. + """ + + def __init__(self, + *, + user_defined: dict = None, + system: 'MessageContextSkillSystem' = None, + action_variables: dict = None, + skill_variables: dict = None) -> None: + """ + Initialize a MessageContextSkillAction object. + + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + :param dict action_variables: (optional) An object containing action + variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. + :param dict skill_variables: (optional) An object containing skill + variables. (In the Watson Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action + and persist for the duration of the session. + """ + self.user_defined = user_defined + self.system = system + self.action_variables = action_variables + self.skill_variables = skill_variables + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillAction': + """Initialize a MessageContextSkillAction object from a json dictionary.""" + args = {} + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + if 'system' in _dict: + args['system'] = MessageContextSkillSystem.from_dict( + _dict.get('system')) + if 'action_variables' in _dict: + args['action_variables'] = _dict.get('action_variables') + if 'skill_variables' in _dict: + args['skill_variables'] = _dict.get('skill_variables') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkillAction 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, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables + if hasattr(self, + 'skill_variables') and self.skill_variables is not None: + _dict['skill_variables'] = self.skill_variables + 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 MessageContextSkillAction object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkillAction') -> 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: 'MessageContextSkillAction') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextSkillDialog(): + """ + Context variables that are used by the dialog skill. + + :attr dict user_defined: (optional) An object containing any arbitrary variables + that can be read and written by a particular skill. :attr MessageContextSkillSystem system: (optional) System context data used by the skill. """ @@ -4867,10 +4961,10 @@ def __init__(self, user_defined: dict = None, system: 'MessageContextSkillSystem' = None) -> None: """ - Initialize a MessageContextSkill object. + Initialize a MessageContextSkillDialog object. - :param dict user_defined: (optional) Arbitrary variables that can be read - and written by a particular skill. + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. :param MessageContextSkillSystem system: (optional) System context data used by the skill. """ @@ -4878,8 +4972,8 @@ def __init__(self, self.system = system @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': - """Initialize a MessageContextSkill object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillDialog': + """Initialize a MessageContextSkillDialog object from a json dictionary.""" args = {} if 'user_defined' in _dict: args['user_defined'] = _dict.get('user_defined') @@ -4890,7 +4984,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextSkill': @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkill object from a json dictionary.""" + """Initialize a MessageContextSkillDialog object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -4910,16 +5004,16 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextSkill object.""" + """Return a `str` version of this MessageContextSkillDialog object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkill') -> bool: + def __eq__(self, other: 'MessageContextSkillDialog') -> 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: 'MessageContextSkill') -> bool: + def __ne__(self, other: 'MessageContextSkillDialog') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -5022,14 +5116,90 @@ def __ne__(self, other: 'MessageContextSkillSystem') -> bool: return not self == other +class MessageContextSkills(): + """ + Context data specific to particular skills used by the assistant. + + :attr MessageContextSkillDialog main_skill: (optional) Context variables that + are used by the dialog skill. + :attr MessageContextSkillAction actions_skill: (optional) Context variables that + are used by the action skill. + """ + + def __init__(self, + *, + main_skill: 'MessageContextSkillDialog' = None, + actions_skill: 'MessageContextSkillAction' = None) -> None: + """ + Initialize a MessageContextSkills object. + + :param MessageContextSkillDialog main_skill: (optional) Context variables + that are used by the dialog skill. + :param MessageContextSkillAction actions_skill: (optional) Context + variables that are used by the action skill. + """ + self.main_skill = main_skill + self.actions_skill = actions_skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': + """Initialize a MessageContextSkills object from a json dictionary.""" + args = {} + if 'main skill' in _dict: + args['main_skill'] = MessageContextSkillDialog.from_dict( + _dict.get('main skill')) + if 'actions skill' in _dict: + args['actions_skill'] = MessageContextSkillAction.from_dict( + _dict.get('actions skill')) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkills 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, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill + else: + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill + else: + _dict['actions skill'] = self.actions_skill.to_dict() + 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 MessageContextSkills object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkills') -> 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: 'MessageContextSkills') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageContextStateless(): """ MessageContextStateless. :attr MessageContextGlobalStateless global_: (optional) Session context data that is shared by all skills used by the assistant. - :attr dict skills: (optional) Information specific to particular skills used by - the assistant. + :attr MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. :attr dict integrations: (optional) An object containing context data that is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). @@ -5038,15 +5208,15 @@ class MessageContextStateless(): def __init__(self, *, global_: 'MessageContextGlobalStateless' = None, - skills: dict = None, + skills: 'MessageContextSkills' = None, integrations: dict = None) -> None: """ Initialize a MessageContextStateless object. :param MessageContextGlobalStateless global_: (optional) Session context data that is shared by all skills used by the assistant. - :param dict skills: (optional) Information specific to particular skills - used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. :param dict integrations: (optional) An object containing context data that is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). @@ -5063,10 +5233,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': args['global_'] = MessageContextGlobalStateless.from_dict( _dict.get('global')) if 'skills' in _dict: - args['skills'] = { - k: MessageContextSkill.from_dict(v) - for k, v in _dict.get('skills').items() - } + args['skills'] = MessageContextSkills.from_dict(_dict.get('skills')) if 'integrations' in _dict: args['integrations'] = _dict.get('integrations') return cls(**args) @@ -5085,13 +5252,10 @@ def to_dict(self) -> Dict: else: _dict['global'] = self.global_.to_dict() if hasattr(self, 'skills') and self.skills is not None: - skills_map = {} - for k, v in self.skills.items(): - if isinstance(v, dict): - skills_map[k] = v - else: - skills_map[k] = v.to_dict() - _dict['skills'] = skills_map + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations return _dict @@ -8203,8 +8367,8 @@ class SearchResult(): query. Currently, only the single answer with the highest confidence (if any) is returned. **Notes:** - - This property uses the answer finding beta feature, and is available only if - the search skill is connected to a Discovery v2 service instance. + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. - Answer finding is not supported on IBM Cloud Pak for Data. """ @@ -8242,8 +8406,8 @@ def __init__(self, to the search query. Currently, only the single answer with the highest confidence (if any) is returned. **Notes:** - - This property uses the answer finding beta feature, and is available - only if the search skill is connected to a Discovery v2 service instance. + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. - Answer finding is not supported on IBM Cloud Pak for Data. """ self.id = id @@ -8604,6 +8768,525 @@ def __ne__(self, other: 'SearchResultMetadata') -> bool: return not self == other +class SearchSettings(): + """ + An object describing the search skill configuration. + + :attr SearchSettingsDiscovery discovery: Configuration settings for the Watson + Discovery service instance used by the search integration. + :attr SearchSettingsMessages messages: The messages included with responses from + the search integration. + :attr SearchSettingsSchemaMapping schema_mapping: The mapping between fields in + the Watson Discovery collection and properties in the search response. + """ + + def __init__(self, discovery: 'SearchSettingsDiscovery', + messages: 'SearchSettingsMessages', + schema_mapping: 'SearchSettingsSchemaMapping') -> None: + """ + Initialize a SearchSettings object. + + :param SearchSettingsDiscovery discovery: Configuration settings for the + Watson Discovery service instance used by the search integration. + :param SearchSettingsMessages messages: The messages included with + responses from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between + fields in the Watson Discovery collection and properties in the search + response. + """ + self.discovery = discovery + self.messages = messages + self.schema_mapping = schema_mapping + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettings': + """Initialize a SearchSettings object from a json dictionary.""" + args = {} + if 'discovery' in _dict: + args['discovery'] = SearchSettingsDiscovery.from_dict( + _dict.get('discovery')) + else: + raise ValueError( + 'Required property \'discovery\' not present in SearchSettings JSON' + ) + if 'messages' in _dict: + args['messages'] = SearchSettingsMessages.from_dict( + _dict.get('messages')) + else: + raise ValueError( + 'Required property \'messages\' not present in SearchSettings JSON' + ) + if 'schema_mapping' in _dict: + args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( + _dict.get('schema_mapping')) + else: + raise ValueError( + 'Required property \'schema_mapping\' not present in SearchSettings JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettings 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, 'discovery') and self.discovery is not None: + if isinstance(self.discovery, dict): + _dict['discovery'] = self.discovery + else: + _dict['discovery'] = self.discovery.to_dict() + if hasattr(self, 'messages') and self.messages is not None: + if isinstance(self.messages, dict): + _dict['messages'] = self.messages + else: + _dict['messages'] = self.messages.to_dict() + if hasattr(self, 'schema_mapping') and self.schema_mapping is not None: + if isinstance(self.schema_mapping, dict): + _dict['schema_mapping'] = self.schema_mapping + else: + _dict['schema_mapping'] = self.schema_mapping.to_dict() + 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 SearchSettings object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettings') -> 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: 'SearchSettings') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsDiscovery(): + """ + Configuration settings for the Watson Discovery service instance used by the search + integration. + + :attr str instance_id: The ID for the Watson Discovery service instance. + :attr str project_id: The ID for the Watson Discovery project. + :attr str url: The URL for the Watson Discovery service instance. + :attr int max_primary_results: (optional) The maximum number of primary results + to include in the response. + :attr int max_total_results: (optional) The maximum total number of primary and + additional results to include in the response. + :attr float confidence_threshold: (optional) The minimum confidence threshold + for included results. Any results with a confidence below this threshold will be + discarded. + :attr bool highlight: (optional) Whether to include the most relevant passages + of text in the **highlight** property of each result. + :attr bool find_answers: (optional) Whether to use the answer finding feature to + emphasize answers within highlighted passages. This property is ignored if + **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + :attr SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + """ + + def __init__(self, + instance_id: str, + project_id: str, + url: str, + authentication: 'SearchSettingsDiscoveryAuthentication', + *, + max_primary_results: int = None, + max_total_results: int = None, + confidence_threshold: float = None, + highlight: bool = None, + find_answers: bool = None) -> None: + """ + Initialize a SearchSettingsDiscovery object. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + :param int max_primary_results: (optional) The maximum number of primary + results to include in the response. + :param int max_total_results: (optional) The maximum total number of + primary and additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence + threshold for included results. Any results with a confidence below this + threshold will be discarded. + :param bool highlight: (optional) Whether to include the most relevant + passages of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding + feature to emphasize answers within highlighted passages. This property is + ignored if **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.instance_id = instance_id + self.project_id = project_id + self.url = url + self.max_primary_results = max_primary_results + self.max_total_results = max_total_results + self.confidence_threshold = confidence_threshold + self.highlight = highlight + self.find_answers = find_answers + self.authentication = authentication + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': + """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + args = {} + if 'instance_id' in _dict: + args['instance_id'] = _dict.get('instance_id') + else: + raise ValueError( + 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' + ) + if 'project_id' in _dict: + args['project_id'] = _dict.get('project_id') + else: + raise ValueError( + 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' + ) + if 'url' in _dict: + args['url'] = _dict.get('url') + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsDiscovery JSON' + ) + if 'max_primary_results' in _dict: + args['max_primary_results'] = _dict.get('max_primary_results') + if 'max_total_results' in _dict: + args['max_total_results'] = _dict.get('max_total_results') + if 'confidence_threshold' in _dict: + args['confidence_threshold'] = _dict.get('confidence_threshold') + if 'highlight' in _dict: + args['highlight'] = _dict.get('highlight') + if 'find_answers' in _dict: + args['find_answers'] = _dict.get('find_answers') + if 'authentication' in _dict: + args[ + 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( + _dict.get('authentication')) + else: + raise ValueError( + 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscovery 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, 'instance_id') and self.instance_id is not None: + _dict['instance_id'] = self.instance_id + if hasattr(self, 'project_id') and self.project_id is not None: + _dict['project_id'] = self.project_id + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr( + self, + 'max_primary_results') and self.max_primary_results is not None: + _dict['max_primary_results'] = self.max_primary_results + if hasattr(self, + 'max_total_results') and self.max_total_results is not None: + _dict['max_total_results'] = self.max_total_results + if hasattr(self, 'confidence_threshold' + ) and self.confidence_threshold is not None: + _dict['confidence_threshold'] = self.confidence_threshold + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'find_answers') and self.find_answers is not None: + _dict['find_answers'] = self.find_answers + if hasattr(self, 'authentication') and self.authentication is not None: + if isinstance(self.authentication, dict): + _dict['authentication'] = self.authentication + else: + _dict['authentication'] = self.authentication.to_dict() + 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 SearchSettingsDiscovery object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscovery') -> 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: 'SearchSettingsDiscovery') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsDiscoveryAuthentication(): + """ + Authentication information for the Watson Discovery service. For more information, see + the [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + + :attr str basic: (optional) The HTTP basic authentication credentials for Watson + Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :attr str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + + def __init__(self, *, basic: str = None, bearer: str = None) -> None: + """ + Initialize a SearchSettingsDiscoveryAuthentication object. + + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + self.basic = basic + self.bearer = bearer + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': + """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + args = {} + if 'basic' in _dict: + args['basic'] = _dict.get('basic') + if 'bearer' in _dict: + args['bearer'] = _dict.get('bearer') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscoveryAuthentication 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, 'basic') and self.basic is not None: + _dict['basic'] = self.basic + if hasattr(self, 'bearer') and self.bearer is not None: + _dict['bearer'] = self.bearer + 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 SearchSettingsDiscoveryAuthentication object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscoveryAuthentication') -> 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: 'SearchSettingsDiscoveryAuthentication') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsMessages(): + """ + The messages included with responses from the search integration. + + :attr str success: The message to include in the response to a successful query. + :attr str error: The message to include in the response when the query + encounters an error. + :attr str no_result: The message to include in the response when there is no + result from the query. + """ + + def __init__(self, success: str, error: str, no_result: str) -> None: + """ + Initialize a SearchSettingsMessages object. + + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is + no result from the query. + """ + self.success = success + self.error = error + self.no_result = no_result + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': + """Initialize a SearchSettingsMessages object from a json dictionary.""" + args = {} + if 'success' in _dict: + args['success'] = _dict.get('success') + else: + raise ValueError( + 'Required property \'success\' not present in SearchSettingsMessages JSON' + ) + if 'error' in _dict: + args['error'] = _dict.get('error') + else: + raise ValueError( + 'Required property \'error\' not present in SearchSettingsMessages JSON' + ) + if 'no_result' in _dict: + args['no_result'] = _dict.get('no_result') + else: + raise ValueError( + 'Required property \'no_result\' not present in SearchSettingsMessages JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsMessages 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, 'success') and self.success is not None: + _dict['success'] = self.success + if hasattr(self, 'error') and self.error is not None: + _dict['error'] = self.error + if hasattr(self, 'no_result') and self.no_result is not None: + _dict['no_result'] = self.no_result + 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 SearchSettingsMessages object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsMessages') -> 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: 'SearchSettingsMessages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsSchemaMapping(): + """ + The mapping between fields in the Watson Discovery collection and properties in the + search response. + + :attr str url: The field in the collection to map to the **url** property of the + response. + :attr str body: The field in the collection to map to the **body** property in + the response. + :attr str title: The field in the collection to map to the **title** property + for the schema. + """ + + def __init__(self, url: str, body: str, title: str) -> None: + """ + Initialize a SearchSettingsSchemaMapping object. + + :param str url: The field in the collection to map to the **url** property + of the response. + :param str body: The field in the collection to map to the **body** + property in the response. + :param str title: The field in the collection to map to the **title** + property for the schema. + """ + self.url = url + self.body = body + self.title = title + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': + """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + args = {} + if 'url' in _dict: + args['url'] = _dict.get('url') + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' + ) + if 'body' in _dict: + args['body'] = _dict.get('body') + else: + raise ValueError( + 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + else: + raise ValueError( + 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsSchemaMapping 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, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + 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 SearchSettingsSchemaMapping object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsSchemaMapping') -> 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: 'SearchSettingsSchemaMapping') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class SearchSkillWarning(): """ A warning describing an error in the search skill configuration. @@ -8771,8 +9454,8 @@ class Skill(): :attr str next_snapshot_version: (optional) The name that will be given to the next snapshot that is created for the skill. A snapshot of each versionable skill is saved for each new release of an assistant. - :attr dict search_settings: (optional) A JSON object describing the search skill - configuration. + :attr SearchSettings search_settings: (optional) An object describing the search + skill configuration. :attr List[SearchSkillWarning] warnings: (optional) An array of warnings describing errors with the search skill configuration. Included only for search skills. @@ -8797,7 +9480,7 @@ def __init__(self, environment_id: str = None, valid: bool = None, next_snapshot_version: str = None, - search_settings: dict = None, + search_settings: 'SearchSettings' = None, warnings: List['SearchSkillWarning'] = None) -> None: """ Initialize a Skill object. @@ -8811,8 +9494,8 @@ def __init__(self, :param dict workspace: (optional) An object containing the conversational content of an action or dialog skill. :param dict dialog_settings: (optional) For internal use only. - :param dict search_settings: (optional) A JSON object describing the search - skill configuration. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. """ self.name = name self.description = description @@ -8865,7 +9548,8 @@ def from_dict(cls, _dict: Dict) -> 'Skill': if 'next_snapshot_version' in _dict: args['next_snapshot_version'] = _dict.get('next_snapshot_version') if 'search_settings' in _dict: - args['search_settings'] = _dict.get('search_settings') + args['search_settings'] = SearchSettings.from_dict( + _dict.get('search_settings')) if 'warnings' in _dict: args['warnings'] = [ SearchSkillWarning.from_dict(v) for v in _dict.get('warnings') @@ -8932,7 +9616,10 @@ def to_dict(self) -> Dict: 'next_snapshot_version') if hasattr(self, 'search_settings') and self.search_settings is not None: - _dict['search_settings'] = self.search_settings + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: warnings_list = [] for v in getattr(self, 'warnings'): @@ -9026,8 +9713,8 @@ class SkillImport(): :attr str next_snapshot_version: (optional) The name that will be given to the next snapshot that is created for the skill. A snapshot of each versionable skill is saved for each new release of an assistant. - :attr dict search_settings: (optional) A JSON object describing the search skill - configuration. + :attr SearchSettings search_settings: (optional) An object describing the search + skill configuration. :attr List[SearchSkillWarning] warnings: (optional) An array of warnings describing errors with the search skill configuration. Included only for search skills. @@ -9052,7 +9739,7 @@ def __init__(self, environment_id: str = None, valid: bool = None, next_snapshot_version: str = None, - search_settings: dict = None, + search_settings: 'SearchSettings' = None, warnings: List['SearchSkillWarning'] = None) -> None: """ Initialize a SkillImport object. @@ -9066,8 +9753,8 @@ def __init__(self, :param dict workspace: (optional) An object containing the conversational content of an action or dialog skill. :param dict dialog_settings: (optional) For internal use only. - :param dict search_settings: (optional) A JSON object describing the search - skill configuration. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. """ self.name = name self.description = description @@ -9120,7 +9807,8 @@ def from_dict(cls, _dict: Dict) -> 'SkillImport': if 'next_snapshot_version' in _dict: args['next_snapshot_version'] = _dict.get('next_snapshot_version') if 'search_settings' in _dict: - args['search_settings'] = _dict.get('search_settings') + args['search_settings'] = SearchSettings.from_dict( + _dict.get('search_settings')) if 'warnings' in _dict: args['warnings'] = [ SearchSkillWarning.from_dict(v) for v in _dict.get('warnings') @@ -9188,7 +9876,10 @@ def to_dict(self) -> Dict: 'next_snapshot_version') if hasattr(self, 'search_settings') and self.search_settings is not None: - _dict['search_settings'] = self.search_settings + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: warnings_list = [] for v in getattr(self, 'warnings'): @@ -9253,10 +9944,11 @@ class SkillsAsyncRequestStatus(): :attr str assistant_id: (optional) The assistant ID of the assistant. :attr str status: (optional) The current status of the asynchronous operation: - - **Available**: The export is available. - - **Failed**: An asynchronous export operation has failed. See the - **status_errors** property for more information about the cause of the failure. - - **Processing**: An asynchronous export operation has not yet completed. + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. :attr str status_description: (optional) The description of the failed asynchronous operation. Included only if **status**=`Failed`. :attr List[StatusError] status_errors: (optional) An array of messages about @@ -9343,12 +10035,14 @@ def __ne__(self, other: 'SkillsAsyncRequestStatus') -> bool: class StatusEnum(str, Enum): """ The current status of the asynchronous operation: - - **Available**: The export is available. - - **Failed**: An asynchronous export operation has failed. See the - **status_errors** property for more information about the cause of the failure. - - **Processing**: An asynchronous export operation has not yet completed. + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. """ AVAILABLE = 'Available' + COMPLETED = 'Completed' FAILED = 'Failed' PROCESSING = 'Processing' diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 8caf4ccde..a257366a5 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -271,6 +271,37 @@ def test_list_assistants_required_params_with_retries(self): _service.disable_retries() self.test_list_assistants_required_params() + @responses.activate + def test_list_assistants_value_error(self): + """ + test_list_assistants_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants') + mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add(responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_assistants(**req_copy) + + def test_list_assistants_value_error_with_retries(self): + # Enable retries and run test_list_assistants_value_error. + _service.enable_retries() + self.test_list_assistants_value_error() + + # Disable retries and run test_list_assistants_value_error. + _service.disable_retries() + self.test_list_assistants_value_error() + class TestDeleteAssistant(): """ Test Class for delete_assistant @@ -570,7 +601,7 @@ def test_message_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -694,15 +725,27 @@ def test_message_all_params(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - # Construct a dict representation of a MessageContextSkill model - message_context_skill_model = {} - message_context_skill_model['user_defined'] = {'foo': 'bar'} - message_context_skill_model['system'] = message_context_skill_system_model + # Construct a dict representation of a MessageContextSkillDialog model + message_context_skill_dialog_model = {} + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a MessageContextSkillAction model + message_context_skill_action_model = {} + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + # Construct a dict representation of a MessageContextSkills model + message_context_skills_model = {} + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model # Construct a dict representation of a MessageContext model message_context_model = {} message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {'key1': message_context_skill_model} + message_context_model['skills'] = message_context_skills_model message_context_model['integrations'] = {'foo': 'bar'} # Set up parameter values @@ -747,7 +790,7 @@ def test_message_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -785,7 +828,7 @@ def test_message_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -827,7 +870,7 @@ def test_message_stateless_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -950,15 +993,27 @@ def test_message_stateless_all_params(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - # Construct a dict representation of a MessageContextSkill model - message_context_skill_model = {} - message_context_skill_model['user_defined'] = {'foo': 'bar'} - message_context_skill_model['system'] = message_context_skill_system_model + # Construct a dict representation of a MessageContextSkillDialog model + message_context_skill_dialog_model = {} + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a MessageContextSkillAction model + message_context_skill_action_model = {} + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + # Construct a dict representation of a MessageContextSkills model + message_context_skills_model = {} + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model # Construct a dict representation of a MessageContextStateless model message_context_stateless_model = {} message_context_stateless_model['global'] = message_context_global_stateless_model - message_context_stateless_model['skills'] = {'key1': message_context_skill_model} + message_context_stateless_model['skills'] = message_context_skills_model message_context_stateless_model['integrations'] = {'foo': 'bar'} # Set up parameter values @@ -1001,7 +1056,7 @@ def test_message_stateless_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -1037,7 +1092,7 @@ def test_message_stateless_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' responses.add(responses.POST, url, body=mock_response, @@ -1188,7 +1243,7 @@ def test_list_logs_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -1239,7 +1294,7 @@ def test_list_logs_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -1275,7 +1330,7 @@ def test_list_logs_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"mapKey": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add(responses.GET, url, body=mock_response, @@ -2404,7 +2459,7 @@ def test_get_skill_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' responses.add(responses.GET, url, body=mock_response, @@ -2442,7 +2497,7 @@ def test_get_skill_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' responses.add(responses.GET, url, body=mock_response, @@ -2484,13 +2539,48 @@ def test_update_skill_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=202) + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + # Set up parameter values assistant_id = 'testString' skill_id = 'testString' @@ -2498,7 +2588,7 @@ def test_update_skill_all_params(self): description = 'testString' workspace = {'foo': 'bar'} dialog_settings = {'foo': 'bar'} - search_settings = {'foo': 'bar'} + search_settings = search_settings_model # Invoke method response = _service.update_skill( @@ -2521,7 +2611,7 @@ def test_update_skill_all_params(self): assert req_body['description'] == 'testString' assert req_body['workspace'] == {'foo': 'bar'} assert req_body['dialog_settings'] == {'foo': 'bar'} - assert req_body['search_settings'] == {'foo': 'bar'} + assert req_body['search_settings'] == search_settings_model def test_update_skill_all_params_with_retries(self): # Enable retries and run test_update_skill_all_params. @@ -2539,13 +2629,48 @@ def test_update_skill_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' responses.add(responses.POST, url, body=mock_response, content_type='application/json', status=202) + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + # Set up parameter values assistant_id = 'testString' skill_id = 'testString' @@ -2553,7 +2678,7 @@ def test_update_skill_value_error(self): description = 'testString' workspace = {'foo': 'bar'} dialog_settings = {'foo': 'bar'} - search_settings = {'foo': 'bar'} + search_settings = search_settings_model # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -2586,7 +2711,7 @@ def test_export_skills_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/skills_export') - mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' responses.add(responses.GET, url, body=mock_response, @@ -2628,7 +2753,7 @@ def test_export_skills_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/skills_export') - mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' responses.add(responses.GET, url, body=mock_response, @@ -2664,7 +2789,7 @@ def test_export_skills_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/skills_export') - mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"anyKey": "anyValue"}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' responses.add(responses.GET, url, body=mock_response, @@ -2711,13 +2836,48 @@ def test_import_skills_all_params(self): content_type='application/json', status=202) + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + # Construct a dict representation of a SkillImport model skill_import_model = {} skill_import_model['name'] = 'testString' skill_import_model['description'] = 'testString' skill_import_model['workspace'] = {'foo': 'bar'} skill_import_model['dialog_settings'] = {'foo': 'bar'} - skill_import_model['search_settings'] = {'foo': 'bar'} + skill_import_model['search_settings'] = search_settings_model skill_import_model['language'] = 'testString' skill_import_model['type'] = 'action' @@ -2776,13 +2936,48 @@ def test_import_skills_required_params(self): content_type='application/json', status=202) + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + # Construct a dict representation of a SkillImport model skill_import_model = {} skill_import_model['name'] = 'testString' skill_import_model['description'] = 'testString' skill_import_model['workspace'] = {'foo': 'bar'} skill_import_model['dialog_settings'] = {'foo': 'bar'} - skill_import_model['search_settings'] = {'foo': 'bar'} + skill_import_model['search_settings'] = search_settings_model skill_import_model['language'] = 'testString' skill_import_model['type'] = 'action' @@ -2835,13 +3030,48 @@ def test_import_skills_value_error(self): content_type='application/json', status=202) + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + # Construct a dict representation of a SkillImport model skill_import_model = {} skill_import_model['name'] = 'testString' skill_import_model['description'] = 'testString' skill_import_model['workspace'] = {'foo': 'bar'} skill_import_model['dialog_settings'] = {'foo': 'bar'} - skill_import_model['search_settings'] = {'foo': 'bar'} + skill_import_model['search_settings'] = search_settings_model skill_import_model['language'] = 'testString' skill_import_model['type'] = 'action' @@ -4437,13 +4667,23 @@ def test_log_serialization(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'foo': 'bar'} - message_context_skill_model['system'] = message_context_skill_system_model + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {'key1': message_context_skill_model} + message_context_model['skills'] = message_context_skills_model message_context_model['integrations'] = {'foo': 'bar'} message_request_model = {} # MessageRequest @@ -4665,13 +4905,23 @@ def test_log_collection_serialization(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'foo': 'bar'} - message_context_skill_model['system'] = message_context_skill_system_model + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {'key1': message_context_skill_model} + message_context_model['skills'] = message_context_skills_model message_context_model['integrations'] = {'foo': 'bar'} message_request_model = {} # MessageRequest @@ -4847,14 +5097,24 @@ def test_message_context_serialization(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'foo': 'bar'} - message_context_skill_model['system'] = message_context_skill_system_model + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model # Construct a json representation of a MessageContext model message_context_model_json = {} message_context_model_json['global'] = message_context_global_model - message_context_model_json['skills'] = {'key1': message_context_skill_model} + message_context_model_json['skills'] = message_context_skills_model message_context_model_json['integrations'] = {'foo': 'bar'} # Construct a model instance of MessageContext by calling from_dict on the json representation @@ -4991,14 +5251,14 @@ def test_message_context_global_system_serialization(self): message_context_global_system_model_json2 = message_context_global_system_model.to_dict() assert message_context_global_system_model_json2 == message_context_global_system_model_json -class TestModel_MessageContextSkill(): +class TestModel_MessageContextSkillAction(): """ - Test Class for MessageContextSkill + Test Class for MessageContextSkillAction """ - def test_message_context_skill_serialization(self): + def test_message_context_skill_action_serialization(self): """ - Test serialization/deserialization for MessageContextSkill + Test serialization/deserialization for MessageContextSkillAction """ # Construct dict forms of any model objects needed in order to build this model. @@ -5007,25 +5267,63 @@ def test_message_context_skill_serialization(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - # Construct a json representation of a MessageContextSkill model - message_context_skill_model_json = {} - message_context_skill_model_json['user_defined'] = {'foo': 'bar'} - message_context_skill_model_json['system'] = message_context_skill_system_model + # Construct a json representation of a MessageContextSkillAction model + message_context_skill_action_model_json = {} + message_context_skill_action_model_json['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model_json['system'] = message_context_skill_system_model + message_context_skill_action_model_json['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model_json['skill_variables'] = {'foo': 'bar'} - # Construct a model instance of MessageContextSkill by calling from_dict on the json representation - message_context_skill_model = MessageContextSkill.from_dict(message_context_skill_model_json) - assert message_context_skill_model != False + # Construct a model instance of MessageContextSkillAction by calling from_dict on the json representation + message_context_skill_action_model = MessageContextSkillAction.from_dict(message_context_skill_action_model_json) + assert message_context_skill_action_model != False - # Construct a model instance of MessageContextSkill by calling from_dict on the json representation - message_context_skill_model_dict = MessageContextSkill.from_dict(message_context_skill_model_json).__dict__ - message_context_skill_model2 = MessageContextSkill(**message_context_skill_model_dict) + # Construct a model instance of MessageContextSkillAction by calling from_dict on the json representation + message_context_skill_action_model_dict = MessageContextSkillAction.from_dict(message_context_skill_action_model_json).__dict__ + message_context_skill_action_model2 = MessageContextSkillAction(**message_context_skill_action_model_dict) # Verify the model instances are equivalent - assert message_context_skill_model == message_context_skill_model2 + assert message_context_skill_action_model == message_context_skill_action_model2 # Convert model instance back to dict and verify no loss of data - message_context_skill_model_json2 = message_context_skill_model.to_dict() - assert message_context_skill_model_json2 == message_context_skill_model_json + message_context_skill_action_model_json2 = message_context_skill_action_model.to_dict() + assert message_context_skill_action_model_json2 == message_context_skill_action_model_json + +class TestModel_MessageContextSkillDialog(): + """ + Test Class for MessageContextSkillDialog + """ + + def test_message_context_skill_dialog_serialization(self): + """ + Test serialization/deserialization for MessageContextSkillDialog + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + # Construct a json representation of a MessageContextSkillDialog model + message_context_skill_dialog_model_json = {} + message_context_skill_dialog_model_json['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model_json['system'] = message_context_skill_system_model + + # Construct a model instance of MessageContextSkillDialog by calling from_dict on the json representation + message_context_skill_dialog_model = MessageContextSkillDialog.from_dict(message_context_skill_dialog_model_json) + assert message_context_skill_dialog_model != False + + # Construct a model instance of MessageContextSkillDialog by calling from_dict on the json representation + message_context_skill_dialog_model_dict = MessageContextSkillDialog.from_dict(message_context_skill_dialog_model_json).__dict__ + message_context_skill_dialog_model2 = MessageContextSkillDialog(**message_context_skill_dialog_model_dict) + + # Verify the model instances are equivalent + assert message_context_skill_dialog_model == message_context_skill_dialog_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_skill_dialog_model_json2 = message_context_skill_dialog_model.to_dict() + assert message_context_skill_dialog_model_json2 == message_context_skill_dialog_model_json class TestModel_MessageContextSkillSystem(): """ @@ -5067,6 +5365,52 @@ def test_message_context_skill_system_serialization(self): actual_dict = message_context_skill_system_model.get_properties() assert actual_dict == expected_dict +class TestModel_MessageContextSkills(): + """ + Test Class for MessageContextSkills + """ + + def test_message_context_skills_serialization(self): + """ + Test serialization/deserialization for MessageContextSkills + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + # Construct a json representation of a MessageContextSkills model + message_context_skills_model_json = {} + message_context_skills_model_json['main skill'] = message_context_skill_dialog_model + message_context_skills_model_json['actions skill'] = message_context_skill_action_model + + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) + assert message_context_skills_model != False + + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ + message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) + + # Verify the model instances are equivalent + assert message_context_skills_model == message_context_skills_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_skills_model_json2 = message_context_skills_model.to_dict() + assert message_context_skills_model_json2 == message_context_skills_model_json + class TestModel_MessageContextStateless(): """ Test Class for MessageContextStateless @@ -5097,14 +5441,24 @@ def test_message_context_stateless_serialization(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'foo': 'bar'} - message_context_skill_model['system'] = message_context_skill_system_model + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model # Construct a json representation of a MessageContextStateless model message_context_stateless_model_json = {} message_context_stateless_model_json['global'] = message_context_global_stateless_model - message_context_stateless_model_json['skills'] = {'key1': message_context_skill_model} + message_context_stateless_model_json['skills'] = message_context_skills_model message_context_stateless_model_json['integrations'] = {'foo': 'bar'} # Construct a model instance of MessageContextStateless by calling from_dict on the json representation @@ -5844,13 +6198,23 @@ def test_message_request_serialization(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'foo': 'bar'} - message_context_skill_model['system'] = message_context_skill_system_model + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {'key1': message_context_skill_model} + message_context_model['skills'] = message_context_skills_model message_context_model['integrations'] = {'foo': 'bar'} # Construct a json representation of a MessageRequest model @@ -6023,13 +6387,23 @@ def test_message_response_serialization(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'foo': 'bar'} - message_context_skill_model['system'] = message_context_skill_system_model + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model - message_context_model['skills'] = {'key1': message_context_skill_model} + message_context_model['skills'] = message_context_skills_model message_context_model['integrations'] = {'foo': 'bar'} # Construct a json representation of a MessageResponse model @@ -6203,13 +6577,23 @@ def test_message_response_stateless_serialization(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_model = {} # MessageContextSkill - message_context_skill_model['user_defined'] = {'foo': 'bar'} - message_context_skill_model['system'] = message_context_skill_system_model + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['system'] = message_context_skill_system_model + + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['system'] = message_context_skill_system_model + message_context_skill_action_model['action_variables'] = {'foo': 'bar'} + message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_skill_dialog_model + message_context_skills_model['actions skill'] = message_context_skill_action_model message_context_stateless_model = {} # MessageContextStateless message_context_stateless_model['global'] = message_context_global_stateless_model - message_context_stateless_model['skills'] = {'key1': message_context_skill_model} + message_context_stateless_model['skills'] = message_context_skills_model message_context_stateless_model['integrations'] = {'foo': 'bar'} # Construct a json representation of a MessageResponseStateless model @@ -6833,6 +7217,199 @@ def test_search_result_metadata_serialization(self): search_result_metadata_model_json2 = search_result_metadata_model.to_dict() assert search_result_metadata_model_json2 == search_result_metadata_model_json +class TestModel_SearchSettings(): + """ + Test Class for SearchSettings + """ + + def test_search_settings_serialization(self): + """ + Test serialization/deserialization for SearchSettings + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a json representation of a SearchSettings model + search_settings_model_json = {} + search_settings_model_json['discovery'] = search_settings_discovery_model + search_settings_model_json['messages'] = search_settings_messages_model + search_settings_model_json['schema_mapping'] = search_settings_schema_mapping_model + + # Construct a model instance of SearchSettings by calling from_dict on the json representation + search_settings_model = SearchSettings.from_dict(search_settings_model_json) + assert search_settings_model != False + + # Construct a model instance of SearchSettings by calling from_dict on the json representation + search_settings_model_dict = SearchSettings.from_dict(search_settings_model_json).__dict__ + search_settings_model2 = SearchSettings(**search_settings_model_dict) + + # Verify the model instances are equivalent + assert search_settings_model == search_settings_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_model_json2 = search_settings_model.to_dict() + assert search_settings_model_json2 == search_settings_model_json + +class TestModel_SearchSettingsDiscovery(): + """ + Test Class for SearchSettingsDiscovery + """ + + def test_search_settings_discovery_serialization(self): + """ + Test serialization/deserialization for SearchSettingsDiscovery + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a json representation of a SearchSettingsDiscovery model + search_settings_discovery_model_json = {} + search_settings_discovery_model_json['instance_id'] = 'testString' + search_settings_discovery_model_json['project_id'] = 'testString' + search_settings_discovery_model_json['url'] = 'testString' + search_settings_discovery_model_json['max_primary_results'] = 10000 + search_settings_discovery_model_json['max_total_results'] = 10000 + search_settings_discovery_model_json['confidence_threshold'] = 0.0 + search_settings_discovery_model_json['highlight'] = True + search_settings_discovery_model_json['find_answers'] = True + search_settings_discovery_model_json['authentication'] = search_settings_discovery_authentication_model + + # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation + search_settings_discovery_model = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json) + assert search_settings_discovery_model != False + + # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation + search_settings_discovery_model_dict = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json).__dict__ + search_settings_discovery_model2 = SearchSettingsDiscovery(**search_settings_discovery_model_dict) + + # Verify the model instances are equivalent + assert search_settings_discovery_model == search_settings_discovery_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_discovery_model_json2 = search_settings_discovery_model.to_dict() + assert search_settings_discovery_model_json2 == search_settings_discovery_model_json + +class TestModel_SearchSettingsDiscoveryAuthentication(): + """ + Test Class for SearchSettingsDiscoveryAuthentication + """ + + def test_search_settings_discovery_authentication_serialization(self): + """ + Test serialization/deserialization for SearchSettingsDiscoveryAuthentication + """ + + # Construct a json representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model_json = {} + search_settings_discovery_authentication_model_json['basic'] = 'testString' + search_settings_discovery_authentication_model_json['bearer'] = 'testString' + + # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation + search_settings_discovery_authentication_model = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json) + assert search_settings_discovery_authentication_model != False + + # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation + search_settings_discovery_authentication_model_dict = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json).__dict__ + search_settings_discovery_authentication_model2 = SearchSettingsDiscoveryAuthentication(**search_settings_discovery_authentication_model_dict) + + # Verify the model instances are equivalent + assert search_settings_discovery_authentication_model == search_settings_discovery_authentication_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_discovery_authentication_model_json2 = search_settings_discovery_authentication_model.to_dict() + assert search_settings_discovery_authentication_model_json2 == search_settings_discovery_authentication_model_json + +class TestModel_SearchSettingsMessages(): + """ + Test Class for SearchSettingsMessages + """ + + def test_search_settings_messages_serialization(self): + """ + Test serialization/deserialization for SearchSettingsMessages + """ + + # Construct a json representation of a SearchSettingsMessages model + search_settings_messages_model_json = {} + search_settings_messages_model_json['success'] = 'testString' + search_settings_messages_model_json['error'] = 'testString' + search_settings_messages_model_json['no_result'] = 'testString' + + # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation + search_settings_messages_model = SearchSettingsMessages.from_dict(search_settings_messages_model_json) + assert search_settings_messages_model != False + + # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation + search_settings_messages_model_dict = SearchSettingsMessages.from_dict(search_settings_messages_model_json).__dict__ + search_settings_messages_model2 = SearchSettingsMessages(**search_settings_messages_model_dict) + + # Verify the model instances are equivalent + assert search_settings_messages_model == search_settings_messages_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_messages_model_json2 = search_settings_messages_model.to_dict() + assert search_settings_messages_model_json2 == search_settings_messages_model_json + +class TestModel_SearchSettingsSchemaMapping(): + """ + Test Class for SearchSettingsSchemaMapping + """ + + def test_search_settings_schema_mapping_serialization(self): + """ + Test serialization/deserialization for SearchSettingsSchemaMapping + """ + + # Construct a json representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model_json = {} + search_settings_schema_mapping_model_json['url'] = 'testString' + search_settings_schema_mapping_model_json['body'] = 'testString' + search_settings_schema_mapping_model_json['title'] = 'testString' + + # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation + search_settings_schema_mapping_model = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json) + assert search_settings_schema_mapping_model != False + + # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation + search_settings_schema_mapping_model_dict = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json).__dict__ + search_settings_schema_mapping_model2 = SearchSettingsSchemaMapping(**search_settings_schema_mapping_model_dict) + + # Verify the model instances are equivalent + assert search_settings_schema_mapping_model == search_settings_schema_mapping_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_schema_mapping_model_json2 = search_settings_schema_mapping_model.to_dict() + assert search_settings_schema_mapping_model_json2 == search_settings_schema_mapping_model_json + class TestModel_SearchSkillWarning(): """ Test Class for SearchSkillWarning @@ -6903,13 +7480,45 @@ def test_skill_serialization(self): Test serialization/deserialization for Skill """ + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + # Construct a json representation of a Skill model skill_model_json = {} skill_model_json['name'] = 'testString' skill_model_json['description'] = 'testString' skill_model_json['workspace'] = {'foo': 'bar'} skill_model_json['dialog_settings'] = {'foo': 'bar'} - skill_model_json['search_settings'] = {'foo': 'bar'} + skill_model_json['search_settings'] = search_settings_model skill_model_json['language'] = 'testString' skill_model_json['type'] = 'action' @@ -6938,13 +7547,45 @@ def test_skill_import_serialization(self): Test serialization/deserialization for SkillImport """ + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + # Construct a json representation of a SkillImport model skill_import_model_json = {} skill_import_model_json['name'] = 'testString' skill_import_model_json['description'] = 'testString' skill_import_model_json['workspace'] = {'foo': 'bar'} skill_import_model_json['dialog_settings'] = {'foo': 'bar'} - skill_import_model_json['search_settings'] = {'foo': 'bar'} + skill_import_model_json['search_settings'] = search_settings_model skill_import_model_json['language'] = 'testString' skill_import_model_json['type'] = 'action' @@ -7003,12 +7644,42 @@ def test_skills_export_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + skill_model = {} # Skill skill_model['name'] = 'testString' skill_model['description'] = 'testString' skill_model['workspace'] = {'foo': 'bar'} skill_model['dialog_settings'] = {'foo': 'bar'} - skill_model['search_settings'] = {'foo': 'bar'} + skill_model['search_settings'] = search_settings_model skill_model['language'] = 'testString' skill_model['type'] = 'action' From 65b749ba98fa29531ca7e281f2d2295ea5bb5644 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 2 Mar 2023 10:47:57 -0600 Subject: [PATCH 392/455] build(version): update versions and readmes --- .bumpversion.cfg | 2 +- .github/workflows/build-test.yml | 26 +-- .github/workflows/deploy.yml | 2 +- .github/workflows/integration-test.yml | 2 +- CONTRIBUTING.md | 2 +- MIGRATION-V4.md | 215 ------------------------- MIGRATION-V5.md | 175 -------------------- MIGRATION-V7.md | 54 +++++++ README.md | 96 +---------- ibm_watson/version.py | 2 +- setup.py | 2 +- 11 files changed, 76 insertions(+), 502 deletions(-) delete mode 100644 MIGRATION-V4.md delete mode 100644 MIGRATION-V5.md create mode 100644 MIGRATION-V7.md diff --git a/.bumpversion.cfg b/.bumpversion.cfg index de99fb6cb..02119c949 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 6.0.1 +current_version = 6.1.0 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index dad38e7f5..4849b2f45 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -21,11 +21,11 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ['3.7', '3.8', '3.9'] + python-version: ['3.9', '3.10', '3.11'] os: [ubuntu-latest, windows-latest] exclude: - os: windows-latest - python-version: '3.7' + python-version: '3.9' steps: - uses: actions/checkout@v2 @@ -45,33 +45,33 @@ jobs: pip3 install -r requirements.txt --use-deprecated=legacy-resolver pip3 install -r requirements-dev.txt --use-deprecated=legacy-resolver pip3 install --editable . --use-deprecated=legacy-resolver - - name: Execute Python 3.7 unit tests - if: matrix.python-version == '3.7' + - name: Execute Python 3.9 unit tests + if: matrix.python-version == '3.9' run: | pip3 install -U python-dotenv py.test test/unit - - name: Execute Python 3.8 unit tests (windows) - if: matrix.python-version == '3.8' && matrix.os == 'windows-latest' + - name: Execute Python 3.10 unit tests (windows) + if: matrix.python-version == '3.10' && matrix.os == 'windows-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 - - name: Execute Python 3.8 unit tests (ubuntu) - if: matrix.python-version == '3.8' && matrix.os == 'ubuntu-latest' + - name: Execute Python 3.10 unit tests (ubuntu) + if: matrix.python-version == '3.10' && matrix.os == 'ubuntu-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 --cov=ibm_watson - - name: Execute Python 3.9 unit tests (windows) - if: matrix.python-version == '3.9' && matrix.os == 'windows-latest' + - name: Execute Python 3.11 unit tests (windows) + if: matrix.python-version == '3.11' && matrix.os == 'windows-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 - - name: Execute Python 3.9 unit tests (ubuntu) - if: matrix.python-version == '3.9' && matrix.os == 'ubuntu-latest' + - name: Execute Python 3.11 unit tests (ubuntu) + if: matrix.python-version == '3.11' && matrix.os == 'ubuntu-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 - name: Upload coverage to Codecov - if: matrix.python-version == '3.8' && matrix.os == 'ubuntu-latest' + if: matrix.python-version == '3.10' && matrix.os == 'ubuntu-latest' uses: codecov/codecov-action@v1 with: name: py${{ matrix.python-version }}-${{ matrix.os }} diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index d8bae9d26..cbd1d4c5e 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -29,7 +29,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v2 with: - python-version: '3.9' + python-version: '3.11' - name: Setup Node uses: actions/setup-node@v1 diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index 059bf7220..05e66e579 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -15,7 +15,7 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ["3.8"] + python-version: ["3.11"] os: [ubuntu-latest] steps: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 85c67d0af..c431459c8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,7 +20,7 @@ If you want to contribute to the repository, here's a quick guide: - Only use spaces for indentation. - Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change. - Check for unnecessary whitespace with `git diff --check` before committing. - - Make sure your code supports Python 3.7, 3.8, 3.9. You can use `pyenv` and `tox` for this + - Make sure your code supports Python 3.9, 3.10, 3.11. You can use `pyenv` and `tox` for this 1. Make the test pass 1. Commit your changes diff --git a/MIGRATION-V4.md b/MIGRATION-V4.md deleted file mode 100644 index 52fc40182..000000000 --- a/MIGRATION-V4.md +++ /dev/null @@ -1,215 +0,0 @@ -Here are simple steps to move from `v3.0.0` to `v4.0.0`. Note that `v4.0,0` supports only python `3.5` and above - -## AUTHENTICATION MECHANISM -The constructor no longer accepts individual credentials like `iam_apikey`, etc. We initialize authenticators from the [core](https://github.com/IBM/python-sdk-core). The core supports various authentication mechanisms, choose the one appropriate to your instance and use case. - -For example, to pass a IAM apikey: -#### Before -```python -from ibm_watson import MyService - -service = MyService( - iam_apikey='{apikey}', - url='{url}' -) -``` - -#### After(V4.0) -```python -from ibm_watson import MyService -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('{apikey}') -service = MyService( - authenticator=authenticator -) -service.set_service_url('{url}') -``` - -There are 5 authentication variants supplied in the SDK (shown below), and it's possible now to create your own authentication implementation if you need something specific by implementing the Authenticator implementation. - -#### BasicAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import BasicAuthenticator - -authenticator = BasicAuthenticator(, ) -service = MyService(authenticator=authenticator) -``` - -#### BearerTokenAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator - -authenticator = BearerTokenAuthenticator() -service = MyService(authenticator=authenticator) - -# can set bearer token -service.get_authenticator().set_bearer_token('xxx'); -``` - -#### CloudPakForDataAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator - -authenticator = CloudPakForDataAuthenticator( - 'my_username', - 'my_password', - 'https://my-cp4d-url', - disable_ssl_verification=True) -service = MyService(authenticator=authenticator) -``` - -#### IAMAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('my_apikey') -service = MyService(authenticator=authenticator) -``` - -#### NoAuthAuthenticator -```python -from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator - -authenticator = NoAuthAuthenticator() -service = MyService(authenticator=authenticator) -``` - -#### Creating an Authenticator from Environmental Configuration -```python -from ibm_cloud_sdk_core import get_authenticator_from_environment - -authenticator = get_authenticator_from_environment('Assistant') -service = MyService(authenticator=authenticator) -``` - -## SETTING THE SERVICE URL -We can set the service url using `set_service_url()` or from external configurations. - -#### Before -```python -service = MyService( - iam_apikey='{apikey}', - url='{url}' # <= here -) -``` - -#### After(V4.0) -```python -service = MyService( - authenticator=authenticator, -) -service.set_service_url('{url}') -``` - -OR, pass from external configurations like environment variable -```bash -export MY_SERVICE_URL="" -``` - -## METHOD OPTIONAL PARAM -The method params which are optional would need to be specified by name rather than position. For example - -#### Before -The list_workspaces with page_limit as 10 was: - -```python -assistant_service.list_workspaces(10) -``` - -#### After(V4.0) -We need to specify the optional param name: - -```python -assistant_service.list_workspaces(page_limit=10) -``` - -## DISABLING SSL VERIFICATION -#### Before -```python -service.disable_ssl_verification(True) -``` - -#### After(v4.0) -```python -service.set_disable_ssl_verification(True) -``` - -## SUPPORT FOR CONSTANTS -Constants for methods and models are shown in the form of Enums - -## SUPPORT FOR PYTHON 2.7 and 3.4 AND BELOW DROPPED -The SDK no longer supports Pyhton versions 2.7 and <=3.4. - -## SERVICE CHANGES -#### AssistantV1 -* `include_count` is no longer a parameter of the list_workspaces() method -* `include_count` is no longer a parameter of the list_intents() method -* `include_count` is no longer a parameter of the list_examples() method -* `include_count` is no longer a parameter of the list_counterexamples() method -* `include_count` is no longer a parameter of the list_entities() method -* `include_count` is no longer a parameter of the list_values() method -* `include_count` is no longer a parameter of the list_synonyms() method -* `include_count` is no longer a parameter of the list_dialog_nodes() method -* `value_type` was renamed to `type` in the create_value() method -* `new_value_type` was renamed to `new_type` in the update_value() method -* `node_type` was renamed to `type` in the create_dialog_node() method -* `new_node_type` was renamed to `new_type` in the update_dialog_node() method -* `value_type` was renamed to `type` in the CreateValue model -* `node_type` was renamed to `type` in the DialogNode model -* `action_type` was renamed to `type` in the DialogNodeAction model -* `query_type` property was added to the DialogNodeOutputGeneric model -* `query` property was added to the DialogNodeOutputGeneric model -* `filter` property was added to the DialogNodeOutputGeneric model -* `discovery_version` property was added to the DialogNodeOutputGeneric model -* LogMessage model no longer has `_additionalProperties` -* `DialogRuntimeResponseGeneric` was renamed to `RuntimeResponseGeneric` -* RuntimeEntity model no longer has `_additionalProperties` -* RuntimeIntent model no longer has `_additionalProperties` -* `value_type` was renamed to `type` in the Value model - -#### AssistantV2 -* `action_type` was renamed to `type` in the DialogNodeAction model -* DialogRuntimeResponseGeneric was renamed to RuntimeResponseGeneric - -#### Compare and Comply -* `convert_to_html()` method does not require a filename parameter - -#### DiscoveryV1 -* `return_fields` was renamed to `return_` in the query() method -* `logging_opt_out` was renamed to `x_watson_logging_opt_out` in the query() method -* `spelling_suggestions` was added to the query() method -* `collection_ids` is no longer a parameter of the query() method -* `return_fields` was renamed to `return_` in the QueryNotices() method -* `logging_opt_out` was renamed to `x_watson_logging_opt_out` in the federated_query() method -* `collection_ids` is now required in the federated_query() method -* `collection_ids` changed position in the federated_query() method -* `return_fields` was renamed to `return_` in the federated_query() method -* `return_fields` was renamed to `return_` in the federated_query_notices() method -* `enrichment_name` was renamed to `enrichment` in the Enrichment model -* `field_type` was renamed to `type` in the Field model -* `field_name` was renamed to `field` in the Field model -* test_configuration_in_environment() method was removed -* query_entities() method was removed -* query_relations() method was removed - -#### Language Translator V3 -* `default_models` was renamed to `default` in the list_models() method -* `translation_output` was renamed to `translation` in the Translation model - -#### Natural Language Classifier V1 -* `metadata` was renamed to `training_metadata` in the `create_classifier()` method - -#### Speech to Text V1 -* `final_results` was renamed to `final` in the SpeakerLabelsResult model -* `final_results` was renamed to `final` in the SpeechRecognitionResult model - -#### Visual Recognition V3 -* `detect_faces()` method was removed -* `class_name` was renamed to `class_` in the ClassResult model -* `class_name` was renamed to `class_` in the ModelClass model - -#### Visual Recognition V4 -* New Service! - - diff --git a/MIGRATION-V5.md b/MIGRATION-V5.md deleted file mode 100644 index 88b36428f..000000000 --- a/MIGRATION-V5.md +++ /dev/null @@ -1,175 +0,0 @@ -## Python SDK V5 Migration guide - -### Service changes - -#### Assistant v1 - -* `include_count` is now a parameter of the `list_workspaces()` method -* `include_count` is now a parameter of the `list_intents()` method -* `include_count` is now a parameter of the `list_examples()` method -* `include_count` is now a parameter of the `list_counterexamples()` method -* `include_count` is now a parameter of the `list_entities()` method -* `include_count` is now a parameter of the `list_values()` method -* `include_count` is now a parameter of the `list_synonyms()` method -* `include_count` is now a parameter of the `list_dialogNodes()` method -* `context` type was changed from `dict` to `DialogNodeContext` in the `create_dialog_node()` method -* `new_context` type was changed from `dict` to `DialogNodeContext` in the `update_dialog_node()` method -* `bulk_classify()` method was addded - -##### Models Added - -`BulkClassifyOutput`, -`BulkClassifyResponse`, -`BulkClassifyUtterance`, -`DialogNodeContext`, -`DialogNodeOutputConnectToAgentTransferInfo`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeImage`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeOption`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypePause`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill`, -`DialogNodeOutputGenericDialogNodeOutputResponseTypeText`, -`RuntimeResponseGenericRuntimeResponseTypeConnectToAgent`, -`RuntimeResponseGenericRuntimeResponseTypeImage`, -`RuntimeResponseGenericRuntimeResponseTypeOption`, -`RuntimeResponseGenericRuntimeResponseTypePause`, -`RuntimeResponseGenericRuntimeResponseTypeSuggestion`, -`RuntimeResponseGenericRuntimeResponseTypeText` - -##### Models Removed - -`DialogSuggestionOutput`, -`DialogSuggestionResponseGeneric` - -##### Model Properties Changed - -`DialogNode` -* `context` property type changed from `Dictionary` to `DialogNodeContext` - -`DialogNodeOutput` -* Added `Integrations` property with getter and setter - -`DialogNodeOutputGeneric`, `RuntimeResponseGeneric` -* Added `agent_available`, `agent_unavailable`, and `transfer_info` properties - -`DialogSuggestion` -* `output` property type changed from `DialogSuggestionOutput` to `Dictionary` - -#### Assistant v2 - -* `bulk_classify()` method was addded - -##### Models Added - -`BulkClassifyOutput`, -`BulkClassifyResponse`, -`BulkClassifyUtterance`, -`DialogNodeOutputConnectToAgentTransferInfo`, -`RuntimeResponseGenericRuntimeResponseTypeConnectToAgent`, -`RuntimeResponseGenericRuntimeResponseTypeImage`, -`RuntimeResponseGenericRuntimeResponseTypeOption`, -`RuntimeResponseGenericRuntimeResponseTypePause`, -`RuntimeResponseGenericRuntimeResponseTypeSearch`, -`RuntimeResponseGenericRuntimeResponseTypeSuggestion`, -`RuntimeResponseGenericRuntimeResponseTypeText` - -##### Model Properties Changed - -`MessageContext`, `MessageContextStateless` -* `Skills` property type changed from `MessageContextSkills` to `Dictionary` - -`MessageContextSkill` -* `System` property type changed from `Dictionary` to `MessageContextSkillSystem` - -`RuntimeResponseGeneric` -* Added `agent_available`, `agent_unavailable`, and `transfer_info` properties - -#### Compare Comply v1 - -* `before` and `after` parameters were removed from `list_feedback` method - -##### Model Properties Changed - -`Category`, `TypeLabel` -* Added `modification` property - -`OriginalLabelsOut`, `UpdatedLabelsOut` -* Removed `modification` property - -#### Discovery v1 - -No changes - -#### Discovery v2 - -##### Models Added - -`QueryResponsePassage` - -##### Models Removed - -`QueryNoticesResult` - -##### Model Properties Changed - -`QueryResponse` -* Added `Passages` property - -#### Language Translator v3 - -No changes - -#### Natural Language Classifier v1 - -No changes - -#### Natural Language Understanding v1 - -No changes - -#### Personality Insights - -No changes - -#### Speech To Text v1 - -No changes - -#### Text To Speech v1 - -* Renamed `CreateVoiceModel()` method to `CreateCustomModel()` - -* Renamed `ListVoiceModels()` method to `ListCustomModels()` - -* Renamed `UpdateVoiceModel()` method to `UpdateCustomModel()` - -* Renamed `GetVoiceModel()` method to `GetCustomModel()` - -* Renamed `DeleteVoiceModel()` method to `GetCustomModel()` - -##### Models Added - -`CustomModel`, -`CustomModels` - -##### Models Removed - -`VoiceModel`, -`VoiceModels` - -##### Model Properties Changed - -`Voice` -* Change return type of `customization` from `VoiceModel` to `CustomModel` - -#### Tone Analyzer v3 - -No changes - -#### Visual Recognition v3 - -No changes - -#### Visual Recognition v4 - -* Changed `start_time` and `end_time` parameter types from `string` to `date` in `get_training_usage()` method \ No newline at end of file diff --git a/MIGRATION-V7.md b/MIGRATION-V7.md new file mode 100644 index 000000000..5a5deba3d --- /dev/null +++ b/MIGRATION-V7.md @@ -0,0 +1,54 @@ +# Upgrading to ibm-watson@8.0 + [Breaking Changes](#breaking-changes) + - [Breaking changes by service](#breaking-changes-by-service) + +- [New Features by Service](#new-features-by-service) + +### Breaking changes by service + +#### Assistant v2 +- Parameter `createSession` removed from `createSession` function +- Class `Environment` property `language` removed +- Class `EnvironmentReleaseReference` renamed to `BaseEnvironmentReleaseReference` +- Class `EnvironmentOrchestration` renamed to `BaseEnvironmentOrchestration` +- Class `SkillReference` renamed to `EnvironmentSkill` + +#### Discovery v2 +- Parameter `smartDocumentUnderstanding` removed from `createCollection` function +- Class `QueryResponsePassage` and `QueryResultPassage` property `confidence` removed +- Class `DocumentClassifierEnrichment` property `enrichmentId` is no longer an optional +- QueryAggregation classes restructured + +#### Natural Language Understanding +- All `sentimentModel` functions removed + +#### Speech to Text +- `AR_AR_BROADBANDMODEL` model removed in favor of `AR_MS_BROADBANDMODEL` model + +### New Features by Service + +#### Assistant v2 +- `createAssistant` function +- `listAssistants` function +- `deleteAssistant` function +- `updateEnvironment` function +- `createRelease` function +- `deleteRelease` function +- `getSkill` function +- `updateSkill` function +- `exportSkills` function +- `importSkills` function +- `importSkillsStatus` function +- Improved typing for `message` function call +See details of these functions on IBM's documentation site [here](https://cloud.ibm.com/apidocs/assistant-v2?code=node) + +#### Discovery v2 +- Aggregation types `QueryTopicAggregation` and `QueryTrendAggregation` added + +#### Speech to Text +- added `FR_CA_MULTIMEDIA`, `JA_JP_TELEPHONY`, `NL_NL_MULTIMEDIA`, `SV_SE_TELEPHONY` models + +#### Text to Speech +- added `EN_AU_HEIDIEXPRESSIVE`, `EN_AU_JACKEXPRESSIVE`, `EN_US_ALLISONEXPRESSIVE`, `EN_US_EMMAEXPRESSIVE`, `EN_US_LISAEXPRESSIVE`, `EN_US_MICHAELEXPRESSIVE`, `KO_KR_JINV3VOICE` +- Parameters `ratePercentage` and `pitchPercentage` added to `synthesize` function +See details of these new parameters on IBM's documentation site [here](https://cloud.ibm.com/apidocs/text-to-speech?code=node#synthesize) diff --git a/README.md b/README.md index 8fb71fc37..9733d0262 100755 --- a/README.md +++ b/README.md @@ -12,24 +12,6 @@ Python client library to quickly get started with the various [Watson APIs][wdc] services. -## Announcements - -### Tone Analyzer Deprecation - -As of this major release, 6.0.0, the Tone Analyzer api has been removed in preparation for deprecation. If you wish to continue using this sdk to make calls to Tone Analyzer until its final deprecation, you will have to use a previous version. - -On 24 February 2022, IBM announced the deprecation of the Tone Analyzer service. The service will no longer be available as of 24 February 2023. As of 24 February 2022, you will not be able to create new instances. Existing instances will be supported until 24 February 2023. - -As an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud. With Natural Language Understanding, tone analysis is done by using a pre-built classifications model, which provides an easy way to detect language tones in written text. For more information, see [Migrating from Watson Tone Analyzer Customer Engagement endpoint to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-tone_analytics). - -### Natural Language Classifier Deprecation - -As of this major release, 6.0.0, the NLC api has been removed in preparation for deprecation. If you wish to continue using this sdk to make calls to NLC until its final deprecation, you will have to use a previous version. - -On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. - -As an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud that uses deep learning to extract data and insights from text such as keywords, categories, sentiment, emotion, and syntax, along with advanced multi-label text classification capabilities, to provide even richer insights for your business or industry. For more information, see [Migrating to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating). - ## Before you begin - You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support `python 3.5` and above @@ -219,64 +201,12 @@ discovery.set_service_url('') ## Python version -Tested on Python 3.5, 3.6, and 3.7. +Tested on Python 3.9, 3.10, and 3.11. ## Questions If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+python). -## Changes for v1.0 - -Version 1.0 focuses on the move to programmatically-generated code for many of the services. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. - -## Changes for v2.0 - -`DetailedResponse` which contains the result, headers and HTTP status code is now the default response for all methods. - -```python -from ibm_watson import AssistantV1 - -assistant = AssistantV1( - username='xxx', - password='yyy', - url='', - version='2018-07-10') - -response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}) -print(response.get_result()) -print(response.get_headers()) -print(response.get_status_code()) -``` - -See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. - -## Changes for v3.0 - -The SDK is generated using OpenAPI Specification(OAS3). Changes are basic reordering of parameters in function calls. - -The package is renamed to ibm_watson. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. - -## Changes for v4.0 - -Authenticator variable indicates the type of authentication to be used. - -```python -from ibm_watson import AssistantV1 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2018-07-10', - authenticator=authenticator) -assistant.set_service_url('') -``` - -For more information, follow the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md) - -## Migration - -To move from v3.x to v4.0, refer to the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md). - ## Configuring the http client (Supported from v1.1.0) To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://2.python-requests.org/en/master/api/#requests.request) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance @@ -558,33 +488,13 @@ HTTPConnection.debuglevel = 1 - `python_dateutil` >= 2.5.3 - [responses] for testing - Following for web sockets support in speech to text - - `websocket-client` 0.48.0 -- `ibm_cloud_sdk_core` == 1.0.0 + - `websocket-client` 1.1.0 +- `ibm_cloud_sdk_core` >= 3.16.2 ## Contributing See [CONTRIBUTING.md][contributing]. -## Featured Projects - -Here are some projects that have been using the SDK: - -- [NLC ICD-10 Classifier](https://github.com/IBM/nlc-icd10-classifier) -- [Cognitive Moderator Service](https://github.com/IBM/cognitive-moderator-service) - -We'd love to highlight cool open-source projects that use this SDK! If you'd like to get your project added to the list, feel free to make an issue linking us to it. - ## License This library is licensed under the [Apache 2.0 license][license]. - -[wdc]: http://www.ibm.com/watson/developercloud/ -[ibm_cloud]: https://cloud.ibm.com/ -[watson-dashboard]: https://cloud.ibm.com/catalog?category=ai -[responses]: https://github.com/getsentry/responses -[requests]: http://docs.python-requests.org/en/latest/ -[examples]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples -[contributing]: https://github.com/watson-developer-cloud/python-sdk/blob/master/CONTRIBUTING.md -[license]: http://www.apache.org/licenses/LICENSE-2.0 -[vcap_services]: https://cloud.ibm.com/docs/watson?topic=watson-vcapServices -[ibm-cloud-onboarding]: https://cloud.ibm.com/registration?target=/developer/watson&cm_sp=WatsonPlatform-WatsonServices-_-OnPageNavLink-IBMWatson_SDKs-_-Python diff --git a/ibm_watson/version.py b/ibm_watson/version.py index c4b0ef895..9f62d7687 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '6.0.1' +__version__ = '6.1.0' diff --git a/setup.py b/setup.py index f33720748..766b8b236 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '6.0.1' +__version__ = '6.1.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From b1b37449c469e6cd973c21942d45c3aabf27bcec Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 8 Mar 2023 11:50:35 -0600 Subject: [PATCH 393/455] refactor(assistantv2): update model names --- ibm_watson/assistant_v1.py | 20 +- ibm_watson/assistant_v2.py | 193 +++++++++--------- .../natural_language_understanding_v1.py | 9 + ibm_watson/speech_to_text_v1.py | 20 +- ibm_watson/text_to_speech_v1.py | 24 +-- test/unit/test_assistant_v2.py | 72 +++---- 6 files changed, 178 insertions(+), 160 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index ac77027c2..d0a1620e5 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -674,8 +674,8 @@ def create_workspace_async( workspace components defining the content of the new workspace. A successful call to this method only initiates asynchronous creation of the workspace. The new workspace is not available until processing completes. To check - the status of the asynchronous operation, use the **Export workspace - asynchronously** method. + the status of the asynchronous operation, use the **Get information about a + workspace** method. :param str name: (optional) The name of the workspace. This string cannot contain carriage return, newline, or tab characters. @@ -781,8 +781,8 @@ def update_workspace_async( provide component objects defining the content of the updated workspace. A successful call to this method only initiates an asynchronous update of the workspace. The updated workspace is not available until processing completes. To - check the status of the asynchronous operation, use the **Export workspace - asynchronously** method. + check the status of the asynchronous operation, use the **Get information about a + workspace** method. :param str workspace_id: Unique identifier of the workspace. :param str name: (optional) The name of the workspace. This string cannot @@ -10519,11 +10519,9 @@ class Workspace(): :attr str status: (optional) The current status of the workspace: - **Available**: The workspace is available and ready to process messages. - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. Returned only by - the **Export workspace asynchronously** method. + property for more information about the cause of the failure. - **Non Existent**: The workspace does not exist. - - **Processing**: An asynchronous operation has not yet completed. Returned - only by the **Export workspace asynchronously** method. + - **Processing**: An asynchronous operation has not yet completed. - **Training**: The workspace is training based on new data such as intents or examples. :attr List[StatusError] status_errors: (optional) An array of messages about @@ -10778,11 +10776,9 @@ class StatusEnum(str, Enum): The current status of the workspace: - **Available**: The workspace is available and ready to process messages. - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. Returned only by the - **Export workspace asynchronously** method. + property for more information about the cause of the failure. - **Non Existent**: The workspace does not exist. - - **Processing**: An asynchronous operation has not yet completed. Returned only - by the **Export workspace asynchronously** method. + - **Processing**: An asynchronous operation has not yet completed. - **Training**: The workspace is training based on new data such as intents or examples. """ diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 6c7017fa1..1875780d3 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -100,7 +100,7 @@ def create_assistant(self, string cannot contain carriage return, newline, or tab characters. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Assistant` object + :rtype: DetailedResponse with `dict` result representing a `AssistantData` object """ headers = {} @@ -1865,9 +1865,94 @@ def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: return not self == other -class Assistant(): +class AssistantCollection(): + """ + AssistantCollection. + + :attr List[AssistantData] assistants: An array of objects describing the + assistants associated with the instance. + :attr Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ - Assistant. + + def __init__(self, assistants: List['AssistantData'], + pagination: 'Pagination') -> None: + """ + Initialize a AssistantCollection object. + + :param List[AssistantData] assistants: An array of objects describing the + assistants associated with the instance. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + self.assistants = assistants + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AssistantCollection': + """Initialize a AssistantCollection object from a json dictionary.""" + args = {} + if 'assistants' in _dict: + args['assistants'] = [ + AssistantData.from_dict(v) for v in _dict.get('assistants') + ] + else: + raise ValueError( + 'Required property \'assistants\' not present in AssistantCollection JSON' + ) + if 'pagination' in _dict: + args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + else: + raise ValueError( + 'Required property \'pagination\' not present in AssistantCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AssistantCollection 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, 'assistants') and self.assistants is not None: + assistants_list = [] + for v in self.assistants: + if isinstance(v, dict): + assistants_list.append(v) + else: + assistants_list.append(v.to_dict()) + _dict['assistants'] = assistants_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() + 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 AssistantCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AssistantCollection') -> 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: 'AssistantCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AssistantData(): + """ + AssistantData. :attr str assistant_id: (optional) The unique identifier of the assistant. :attr str name: (optional) The name of the assistant. This string cannot contain @@ -1892,7 +1977,7 @@ def __init__( assistant_environments: List['EnvironmentReference'] = None ) -> None: """ - Initialize a Assistant object. + Initialize a AssistantData object. :param str language: The language of the assistant. :param str name: (optional) The name of the assistant. This string cannot @@ -1908,8 +1993,8 @@ def __init__( self.assistant_environments = assistant_environments @classmethod - def from_dict(cls, _dict: Dict) -> 'Assistant': - """Initialize a Assistant object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AssistantData': + """Initialize a AssistantData object from a json dictionary.""" args = {} if 'assistant_id' in _dict: args['assistant_id'] = _dict.get('assistant_id') @@ -1921,7 +2006,8 @@ def from_dict(cls, _dict: Dict) -> 'Assistant': args['language'] = _dict.get('language') else: raise ValueError( - 'Required property \'language\' not present in Assistant JSON') + 'Required property \'language\' not present in AssistantData JSON' + ) if 'assistant_skills' in _dict: args['assistant_skills'] = [ AssistantSkill.from_dict(v) @@ -1936,7 +2022,7 @@ def from_dict(cls, _dict: Dict) -> 'Assistant': @classmethod def _from_dict(cls, _dict): - """Initialize a Assistant object from a json dictionary.""" + """Initialize a AssistantData object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -1976,101 +2062,16 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Assistant object.""" + """Return a `str` version of this AssistantData object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Assistant') -> bool: + def __eq__(self, other: 'AssistantData') -> 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: 'Assistant') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class AssistantCollection(): - """ - AssistantCollection. - - :attr List[Assistant] assistants: An array of objects describing the assistants - associated with the instance. - :attr Pagination pagination: The pagination data for the returned objects. For - more information about using pagination, see [Pagination](#pagination). - """ - - def __init__(self, assistants: List['Assistant'], - pagination: 'Pagination') -> None: - """ - Initialize a AssistantCollection object. - - :param List[Assistant] assistants: An array of objects describing the - assistants associated with the instance. - :param Pagination pagination: The pagination data for the returned objects. - For more information about using pagination, see [Pagination](#pagination). - """ - self.assistants = assistants - self.pagination = pagination - - @classmethod - def from_dict(cls, _dict: Dict) -> 'AssistantCollection': - """Initialize a AssistantCollection object from a json dictionary.""" - args = {} - if 'assistants' in _dict: - args['assistants'] = [ - Assistant.from_dict(v) for v in _dict.get('assistants') - ] - else: - raise ValueError( - 'Required property \'assistants\' not present in AssistantCollection JSON' - ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) - else: - raise ValueError( - 'Required property \'pagination\' not present in AssistantCollection JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a AssistantCollection 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, 'assistants') and self.assistants is not None: - assistants_list = [] - for v in self.assistants: - if isinstance(v, dict): - assistants_list.append(v) - else: - assistants_list.append(v.to_dict()) - _dict['assistants'] = assistants_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination - else: - _dict['pagination'] = self.pagination.to_dict() - 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 AssistantCollection object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'AssistantCollection') -> 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: 'AssistantCollection') -> bool: + def __ne__(self, other: 'AssistantData') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index acfe964c1..3b7aa10dd 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -24,6 +24,15 @@ models](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) with Watson Knowledge Studio to detect custom entities and relations in Natural Language Understanding. +IBM is sunsetting Watson Natural Language Understanding Custom Sentiment (BETA). From +**June 1, 2023** onward, you will no longer be able to use the Custom Sentiment +feature.

To ensure we continue providing our clients with robust and powerful +text classification capabilities, IBM recently announced the general availability of a new +[single-label text classification +capability](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-classifications). +This new feature includes extended language support and training data customizations +suited for building a custom sentiment classifier.

If you would like more +information or further guidance, please contact IBM Cloud Support.{: deprecated} API Version: 1.0 See: https://cloud.ibm.com/docs/natural-language-understanding diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index bd2c5b713..7d35d6eb5 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1700,11 +1700,17 @@ def train_language_model(self, fields. A status of `available` means that the custom model is trained and ready to use. The service cannot accept subsequent training requests or requests to add new resources until the existing request completes. + For custom models that are based on improved base language models, training also + performs an automatic upgrade to a newer version of the base model. You do not + need to use the [Upgrade a custom language model](#upgradelanguagemodel) method to + perform the upgrade. **See also:** - * [Train the custom language - model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language) * [Language support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support) + * [Train the custom language + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language) + * [Upgrading custom language models that are based on improved next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language-ng) ### Training failures Training can fail to start for the following reasons: * The service is currently handling another request for the custom model, such as @@ -1862,11 +1868,17 @@ def upgrade_language_model(self, customization_id: str, upgrade is complete, the model resumes the status that it had prior to upgrade. The service cannot accept subsequent requests for the model until the upgrade completes. + For custom models that are based on improved base language models, the [Train a + custom language model](#trainlanguagemodel) method also performs an automatic + upgrade to a newer version of the base model. You do not need to use the upgrade + method. **See also:** + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support) * [Upgrading a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language) - * [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). + * [Upgrading custom language models that are based on improved next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language-ng). :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 diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index a96478e8c..f2cfe225f 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -38,8 +38,8 @@ Effective **31 March 2022**, all *neural voices* are deprecated. The deprecated voices remain available to existing users until 31 March 2023, when they will be removed from the service and the documentation. *No enhanced neural voices or expressive neural voices are -deprecated.* For more information, see the [31 March 2022 service -update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) +deprecated.*

For more information, see the [1 March 2023 service +update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) in the release notes for {{site.data.keyword.texttospeechshort}} for {{site.data.keyword.cloud_notm}}.{: deprecated} @@ -105,8 +105,8 @@ def list_voices(self, **kwargs) -> DetailedResponse: deprecated voices remain available to existing users until 31 March 2023, when they will be removed from the service and the documentation. *No enhanced neural voices or expressive neural voices are deprecated.* For more information, see the - [31 March 2022 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) + [1 March 2023 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) in the release notes. **See also:** [Listing all voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-list#list-all-voices). @@ -152,8 +152,8 @@ def get_voice(self, deprecated voices remain available to existing users until 31 March 2023, when they will be removed from the service and the documentation. *No enhanced neural voices or expressive neural voices are deprecated.* For more information, see the - [31 March 2022 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) + [1 March 2023 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) in the release notes. :param str voice: The voice for which information is to be returned. @@ -225,8 +225,8 @@ def synthesize(self, deprecated voices remain available to existing users until 31 March 2023, when they will be removed from the service and the documentation. *No enhanced neural voices or expressive neural voices are deprecated.* For more information, see the - [31 March 2022 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) + [1 March 2023 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) in the release notes. ### Audio formats (accept types) The service can return audio in the following formats (MIME types). @@ -417,8 +417,8 @@ def get_pronunciation(self, deprecated voices remain available to existing users until 31 March 2023, when they will be removed from the service and the documentation. *No enhanced neural voices or expressive neural voices are deprecated.* For more information, see the - [31 March 2022 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) + [1 March 2023 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) in the release notes. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). @@ -502,8 +502,8 @@ def create_custom_model(self, deprecated voices remain available to existing users until 31 March 2023, when they will be removed from the service and the documentation. *No enhanced neural voices or expressive neural voices are deprecated.* For more information, see the - [31 March 2022 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-31march2022) + [1 March 2023 service + update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) in the release notes. :param str name: The name of the new custom model. Use a localized name diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index a257366a5..f0a15e812 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -3220,37 +3220,6 @@ def test_agent_availability_message_serialization(self): agent_availability_message_model_json2 = agent_availability_message_model.to_dict() assert agent_availability_message_model_json2 == agent_availability_message_model_json -class TestModel_Assistant(): - """ - Test Class for Assistant - """ - - def test_assistant_serialization(self): - """ - Test serialization/deserialization for Assistant - """ - - # Construct a json representation of a Assistant model - assistant_model_json = {} - assistant_model_json['name'] = 'testString' - assistant_model_json['description'] = 'testString' - assistant_model_json['language'] = 'testString' - - # Construct a model instance of Assistant by calling from_dict on the json representation - assistant_model = Assistant.from_dict(assistant_model_json) - assert assistant_model != False - - # Construct a model instance of Assistant by calling from_dict on the json representation - assistant_model_dict = Assistant.from_dict(assistant_model_json).__dict__ - assistant_model2 = Assistant(**assistant_model_dict) - - # Verify the model instances are equivalent - assert assistant_model == assistant_model2 - - # Convert model instance back to dict and verify no loss of data - assistant_model_json2 = assistant_model.to_dict() - assert assistant_model_json2 == assistant_model_json - class TestModel_AssistantCollection(): """ Test Class for AssistantCollection @@ -3263,10 +3232,10 @@ def test_assistant_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - assistant_model = {} # Assistant - assistant_model['name'] = 'testString' - assistant_model['description'] = 'testString' - assistant_model['language'] = 'testString' + assistant_data_model = {} # AssistantData + assistant_data_model['name'] = 'testString' + assistant_data_model['description'] = 'testString' + assistant_data_model['language'] = 'testString' pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -3278,7 +3247,7 @@ def test_assistant_collection_serialization(self): # Construct a json representation of a AssistantCollection model assistant_collection_model_json = {} - assistant_collection_model_json['assistants'] = [assistant_model] + assistant_collection_model_json['assistants'] = [assistant_data_model] assistant_collection_model_json['pagination'] = pagination_model # Construct a model instance of AssistantCollection by calling from_dict on the json representation @@ -3296,6 +3265,37 @@ def test_assistant_collection_serialization(self): assistant_collection_model_json2 = assistant_collection_model.to_dict() assert assistant_collection_model_json2 == assistant_collection_model_json +class TestModel_AssistantData(): + """ + Test Class for AssistantData + """ + + def test_assistant_data_serialization(self): + """ + Test serialization/deserialization for AssistantData + """ + + # Construct a json representation of a AssistantData model + assistant_data_model_json = {} + assistant_data_model_json['name'] = 'testString' + assistant_data_model_json['description'] = 'testString' + assistant_data_model_json['language'] = 'testString' + + # Construct a model instance of AssistantData by calling from_dict on the json representation + assistant_data_model = AssistantData.from_dict(assistant_data_model_json) + assert assistant_data_model != False + + # Construct a model instance of AssistantData by calling from_dict on the json representation + assistant_data_model_dict = AssistantData.from_dict(assistant_data_model_json).__dict__ + assistant_data_model2 = AssistantData(**assistant_data_model_dict) + + # Verify the model instances are equivalent + assert assistant_data_model == assistant_data_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_data_model_json2 = assistant_data_model.to_dict() + assert assistant_data_model_json2 == assistant_data_model_json + class TestModel_AssistantSkill(): """ Test Class for AssistantSkill From 1469190590cdaff60156816964b88822fef5e933 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 8 Mar 2023 15:26:42 -0600 Subject: [PATCH 394/455] feat(nlu): remove beta model param from Sentiment --- .../natural_language_understanding_v1.py | 18 +----------------- .../test_natural_language_understanding_v1.py | 4 ---- 2 files changed, 1 insertion(+), 21 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 3b7aa10dd..1e76ade39 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -5252,18 +5252,12 @@ class SentimentOptions(): sentiment results. :attr List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. - :attr str model: (optional) (Beta) Enter a [custom - model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) - ID to override the standard sentiment model for all sentiment analysis - operations in the request, including targeted sentiment for entities and - keywords. """ def __init__(self, *, document: bool = None, - targets: List[str] = None, - model: str = None) -> None: + targets: List[str] = None) -> None: """ Initialize a SentimentOptions object. @@ -5271,15 +5265,9 @@ def __init__(self, sentiment results. :param List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. - :param str model: (optional) (Beta) Enter a [custom - model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) - ID to override the standard sentiment model for all sentiment analysis - operations in the request, including targeted sentiment for entities and - keywords. """ self.document = document self.targets = targets - self.model = model @classmethod def from_dict(cls, _dict: Dict) -> 'SentimentOptions': @@ -5289,8 +5277,6 @@ def from_dict(cls, _dict: Dict) -> 'SentimentOptions': args['document'] = _dict.get('document') if 'targets' in _dict: args['targets'] = _dict.get('targets') - if 'model' in _dict: - args['model'] = _dict.get('model') return cls(**args) @classmethod @@ -5305,8 +5291,6 @@ def to_dict(self) -> Dict: _dict['document'] = self.document if hasattr(self, 'targets') and self.targets is not None: _dict['targets'] = self.targets - if hasattr(self, 'model') and self.model is not None: - _dict['model'] = self.model return _dict def _to_dict(self): diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 053bf8c6b..4efc2d992 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -133,7 +133,6 @@ def test_analyze_all_params(self): sentiment_options_model = {} sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - sentiment_options_model['model'] = 'testString' # Construct a dict representation of a SummarizationOptions model summarization_options_model = {} @@ -277,7 +276,6 @@ def test_analyze_value_error(self): sentiment_options_model = {} sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - sentiment_options_model['model'] = 'testString' # Construct a dict representation of a SummarizationOptions model summarization_options_model = {} @@ -2678,7 +2676,6 @@ def test_features_serialization(self): sentiment_options_model = {} # SentimentOptions sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - sentiment_options_model['model'] = 'testString' summarization_options_model = {} # SummarizationOptions summarization_options_model['limit'] = 10 @@ -3453,7 +3450,6 @@ def test_sentiment_options_serialization(self): sentiment_options_model_json = {} sentiment_options_model_json['document'] = True sentiment_options_model_json['targets'] = ['testString'] - sentiment_options_model_json['model'] = 'testString' # Construct a model instance of SentimentOptions by calling from_dict on the json representation sentiment_options_model = SentimentOptions.from_dict(sentiment_options_model_json) From 1f970bb0be0d913792c30175884aa25edf5b42de Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 16 Mar 2023 16:48:04 -0500 Subject: [PATCH 395/455] chore(secrets): update secrets.baseline --- .secrets.baseline | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/.secrets.baseline b/.secrets.baseline index bf19efa9e..bb6f52015 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "package-lock.json|^.secrets.baseline$", "lines": null }, - "generated_at": "2022-08-10T14:28:21Z", + "generated_at": "2023-03-16T21:47:10Z", "plugins_used": [ { "name": "AWSKeyDetector" @@ -70,7 +70,7 @@ "hashed_secret": "d9e9019d9eb455a3d72a3bc252c26927bb148a10", "is_secret": false, "is_verified": false, - "line_number": 137, + "line_number": 119, "type": "Secret Keyword", "verified_result": null }, @@ -78,15 +78,7 @@ "hashed_secret": "32e8612d8ca77c7ea8374aa7918db8e5df9252ed", "is_secret": false, "is_verified": false, - "line_number": 181, - "type": "Secret Keyword", - "verified_result": null - }, - { - "hashed_secret": "186154712b2d5f6791d85b9a0987b98fa231779c", - "is_secret": false, - "is_verified": false, - "line_number": 241, + "line_number": 163, "type": "Secret Keyword", "verified_result": null } @@ -106,7 +98,7 @@ "hashed_secret": "e8fc807ce6fbcda13f91c5b64850173873de0cdc", "is_secret": false, "is_verified": false, - "line_number": 5029, + "line_number": 5220, "type": "Secret Keyword", "verified_result": null }, @@ -114,7 +106,7 @@ "hashed_secret": "fdee05598fdd57ff8e9ae29e92c25a04f2c52fa6", "is_secret": false, "is_verified": false, - "line_number": 5030, + "line_number": 5221, "type": "Secret Keyword", "verified_result": null } @@ -144,7 +136,7 @@ "hashed_secret": "d506bd5213c46bd49e16c634754ad70113408252", "is_secret": false, "is_verified": false, - "line_number": 7655, + "line_number": 7661, "type": "Secret Keyword", "verified_result": null }, @@ -152,7 +144,7 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 11429, + "line_number": 11192, "type": "Secret Keyword", "verified_result": null } @@ -162,7 +154,7 @@ "hashed_secret": "d506bd5213c46bd49e16c634754ad70113408252", "is_secret": false, "is_verified": false, - "line_number": 975, + "line_number": 1333, "type": "Secret Keyword", "verified_result": null }, @@ -170,7 +162,7 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 4876, + "line_number": 6510, "type": "Secret Keyword", "verified_result": null } @@ -188,7 +180,7 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 7899, + "line_number": 7882, "type": "Secret Keyword", "verified_result": null }, @@ -196,7 +188,7 @@ "hashed_secret": "b8e758b5ad59a72f146fcf065239d5c7b695a39a", "is_secret": false, "is_verified": false, - "line_number": 10179, + "line_number": 10064, "type": "Hex High Entropy String", "verified_result": null } @@ -206,13 +198,13 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 416, + "line_number": 411, "type": "Secret Keyword", "verified_result": null } ] }, - "version": "0.13.1+ibm.50.dss", + "version": "0.13.1+ibm.56.dss", "word_list": { "file": null, "hash": null From 37aa172dd0ff176326f147a5ebf6b34bfed86227 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 16 Mar 2023 17:10:12 -0500 Subject: [PATCH 396/455] build(actions): use node 18 in deploy.yml --- .github/workflows/deploy.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index cbd1d4c5e..16f3dda0c 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -34,7 +34,7 @@ jobs: - name: Setup Node uses: actions/setup-node@v1 with: - node-version: 14 + node-version: 18 - name: Install Semantic Release dependencies run: | @@ -74,4 +74,4 @@ jobs: uses: pypa/gh-action-pypi-publish@v1.4.2 # Try to update version tag every release with: password: ${{ secrets.PYPI_TOKEN }} - repository_url: https://upload.pypi.org/legacy/ # This must be changed if testing deploys to test.pypi.org \ No newline at end of file + repository_url: https://upload.pypi.org/legacy/ # This must be changed if testing deploys to test.pypi.org From d91f007fafd568cc30abf15d54c53935f32197a8 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 17 Mar 2023 12:43:45 -0500 Subject: [PATCH 397/455] fix(nlu): require training_data_content_type --- ibm_watson/natural_language_understanding_v1.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 1e76ade39..fd80a2695 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -289,8 +289,8 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: def create_categories_model(self, language: str, training_data: BinaryIO, + training_data_content_type: str, *, - training_data_content_type: str = None, name: str = None, description: str = None, model_version: str = None, @@ -325,6 +325,8 @@ def create_categories_model(self, raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') + if not training_data_content_type: + raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', @@ -449,8 +451,8 @@ def update_categories_model(self, model_id: str, language: str, training_data: BinaryIO, + training_data_content_type: str, *, - training_data_content_type: str = None, name: str = None, description: str = None, model_version: str = None, @@ -487,6 +489,8 @@ def update_categories_model(self, raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') + if not training_data_content_type: + raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', @@ -585,8 +589,8 @@ def create_classifications_model( self, language: str, training_data: BinaryIO, + training_data_content_type: str, *, - training_data_content_type: str = None, name: str = None, description: str = None, model_version: str = None, @@ -625,6 +629,8 @@ def create_classifications_model( raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') + if not training_data_content_type: + raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, @@ -757,8 +763,8 @@ def update_classifications_model( model_id: str, language: str, training_data: BinaryIO, + training_data_content_type: str, *, - training_data_content_type: str = None, name: str = None, description: str = None, model_version: str = None, @@ -799,6 +805,8 @@ def update_classifications_model( raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') + if not training_data_content_type: + raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, From c24aac54d08c57327a5c41fc2e98b3a577e9a291 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 17 Mar 2023 12:48:12 -0500 Subject: [PATCH 398/455] docs(readme): update migration guide --- MIGRATION-V7.md | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/MIGRATION-V7.md b/MIGRATION-V7.md index 5a5deba3d..765ac9ad7 100644 --- a/MIGRATION-V7.md +++ b/MIGRATION-V7.md @@ -20,7 +20,8 @@ - QueryAggregation classes restructured #### Natural Language Understanding -- All `sentimentModel` functions removed +- All `sentiment_model` functions removed +- `create_classifications_model`, `update_classifications_model`, `create_categories_model`, and `update_categories_model` now require `training_data_content_type` #### Speech to Text - `AR_AR_BROADBANDMODEL` model removed in favor of `AR_MS_BROADBANDMODEL` model @@ -28,19 +29,19 @@ ### New Features by Service #### Assistant v2 -- `createAssistant` function -- `listAssistants` function -- `deleteAssistant` function -- `updateEnvironment` function -- `createRelease` function -- `deleteRelease` function -- `getSkill` function -- `updateSkill` function -- `exportSkills` function -- `importSkills` function -- `importSkillsStatus` function +- `create_assistant` function +- `list_assistants` function +- `delete_assistant` function +- `update_environment` function +- `create_release` function +- `delete_release` function +- `get_skill` function +- `update_skill` function +- `export_skills` function +- `import_skills` function +- `import_skills_status` function - Improved typing for `message` function call -See details of these functions on IBM's documentation site [here](https://cloud.ibm.com/apidocs/assistant-v2?code=node) +See details of these functions on IBM's documentation site [here](https://cloud.ibm.com/apidocs/assistant-v2?code=python) #### Discovery v2 - Aggregation types `QueryTopicAggregation` and `QueryTrendAggregation` added @@ -50,5 +51,5 @@ See details of these functions on IBM's documentation site [here](https://cloud. #### Text to Speech - added `EN_AU_HEIDIEXPRESSIVE`, `EN_AU_JACKEXPRESSIVE`, `EN_US_ALLISONEXPRESSIVE`, `EN_US_EMMAEXPRESSIVE`, `EN_US_LISAEXPRESSIVE`, `EN_US_MICHAELEXPRESSIVE`, `KO_KR_JINV3VOICE` -- Parameters `ratePercentage` and `pitchPercentage` added to `synthesize` function -See details of these new parameters on IBM's documentation site [here](https://cloud.ibm.com/apidocs/text-to-speech?code=node#synthesize) +- Parameters `rate_percentage` and `pitch_percentage` added to `synthesize` function +See details of these new parameters on IBM's documentation site [here](https://cloud.ibm.com/apidocs/text-to-speech?code=python#synthesize) From 869e83a9b7560bab5824d487ea96ec380ca25386 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 17 Mar 2023 12:59:03 -0500 Subject: [PATCH 399/455] test(nlu): update unit tests for hand edits --- .../test_natural_language_understanding_v1.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 4efc2d992..547082976 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -577,11 +577,13 @@ def test_create_categories_model_required_params(self): # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Invoke method response = _service.create_categories_model( language, training_data, + training_data_content_type, headers={} ) @@ -615,11 +617,13 @@ def test_create_categories_model_value_error(self): # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "language": language, "training_data": training_data, + "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} @@ -853,12 +857,14 @@ def test_update_categories_model_required_params(self): model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Invoke method response = _service.update_categories_model( model_id, language, training_data, + training_data_content_type, headers={} ) @@ -893,12 +899,14 @@ def test_update_categories_model_value_error(self): model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "model_id": model_id, "language": language, "training_data": training_data, + "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} @@ -1078,11 +1086,13 @@ def test_create_classifications_model_required_params(self): # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Invoke method response = _service.create_classifications_model( language, training_data, + training_data_content_type, headers={} ) @@ -1116,11 +1126,13 @@ def test_create_classifications_model_value_error(self): # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "language": language, "training_data": training_data, + "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} @@ -1360,12 +1372,14 @@ def test_update_classifications_model_required_params(self): model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Invoke method response = _service.update_classifications_model( model_id, language, training_data, + training_data_content_type, headers={} ) @@ -1400,12 +1414,14 @@ def test_update_classifications_model_value_error(self): model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() + training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "model_id": model_id, "language": language, "training_data": training_data, + "training_data_content_type": training_data_content_type } for param in req_param_dict.keys(): req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} From aee877ce8ae50f495f1dacfd7cbd26a117aab594 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 17 Mar 2023 14:45:15 -0500 Subject: [PATCH 400/455] fix(version): change version strings for release --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 02119c949..de99fb6cb 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 6.1.0 +current_version = 6.0.1 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 9f62d7687..c4b0ef895 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '6.1.0' +__version__ = '6.0.1' diff --git a/setup.py b/setup.py index 766b8b236..f33720748 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '6.1.0' +__version__ = '6.0.1' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From c08a117294c9d2a52b8493c1cec55b8826621abc Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 17 Mar 2023 15:59:33 -0500 Subject: [PATCH 401/455] feat(release): trigger release BREAKING CHANGE: trigger release --- .secrets.baseline | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.secrets.baseline b/.secrets.baseline index bb6f52015..400f98f69 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "package-lock.json|^.secrets.baseline$", "lines": null }, - "generated_at": "2023-03-16T21:47:10Z", + "generated_at": "2023-03-17T19:47:10Z", "plugins_used": [ { "name": "AWSKeyDetector" From 75432a6ab4b737a3a7afd8009e70f68e6f02d312 Mon Sep 17 00:00:00 2001 From: Arne <44215085+arne-kapell@users.noreply.github.com> Date: Fri, 4 Aug 2023 20:26:48 +0000 Subject: [PATCH 402/455] fix(tts,stt,version): unpinned websocket-client fixes #810 and adds support for up to latest websocket-client (1.6.1) --- ibm_watson/websocket/recognize_listener.py | 2 +- ibm_watson/websocket/synthesize_listener.py | 2 +- requirements-dev.txt | 2 +- requirements.txt | 2 +- setup.py | 2 +- test/integration/test_speech_to_text_v1.py | 2 +- test/integration/test_text_to_speech_v1.py | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index c0d988c58..43eb79618 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -227,7 +227,7 @@ def on_error(self, ws, error): """ self.callback.on_error(error) - def on_close(self, ws): + def on_close(self, ws, *args): """ Callback executed when websocket connection is closed diff --git a/ibm_watson/websocket/synthesize_listener.py b/ibm_watson/websocket/synthesize_listener.py index dee6e28a6..33caf81d5 100644 --- a/ibm_watson/websocket/synthesize_listener.py +++ b/ibm_watson/websocket/synthesize_listener.py @@ -120,7 +120,7 @@ def on_error(self, ws, error): """ self.callback.on_error(error) - def on_close(self, ws, **kwargs): + def on_close(self, ws, *args, **kwargs): """ Callback executed when websocket connection is closed diff --git a/requirements-dev.txt b/requirements-dev.txt index 086cfe4e8..f04883ea7 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -17,4 +17,4 @@ Sphinx==3.5.2 bumpversion==0.6.0 # Web sockets -websocket-client==1.1.0 +websocket-client>=1.1.0 diff --git a/requirements.txt b/requirements.txt index 7df31b85a..461b8746a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 -websocket-client==1.1.0 +websocket-client>=1.1.0 ibm_cloud_sdk_core>=3.3.6, == 3.* diff --git a/setup.py b/setup.py index f33720748..6d47ba208 100644 --- a/setup.py +++ b/setup.py @@ -27,7 +27,7 @@ version=__version__, description='Client library to use the IBM Watson Services', packages=['ibm_watson'], - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==1.1.0', 'ibm_cloud_sdk_core>=3.3.6, == 3.*'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client>=1.1.0', 'ibm_cloud_sdk_core>=3.3.6, == 3.*'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures'], license='Apache 2.0', author='IBM Watson', diff --git a/test/integration/test_speech_to_text_v1.py b/test/integration/test_speech_to_text_v1.py index c0e0d1865..808a88474 100644 --- a/test/integration/test_speech_to_text_v1.py +++ b/test/integration/test_speech_to_text_v1.py @@ -140,7 +140,7 @@ def on_transcription(self, transcript): interim_results=False, low_latency=False) assert test_callback.error is None assert test_callback.transcript is not None - assert test_callback.transcript[0][0]['transcript'] == 'isolated tornadoes ' + assert test_callback.transcript[0][0]['transcript'] in ['isolated tornadoes ', 'isolated tornados '] assert test_callback.transcript[1][0]['transcript'] == 'and heavy rain ' def test_on_transcription_interim_results_true(self): diff --git a/test/integration/test_text_to_speech_v1.py b/test/integration/test_text_to_speech_v1.py index d0eee91a1..407abd68d 100644 --- a/test/integration/test_text_to_speech_v1.py +++ b/test/integration/test_text_to_speech_v1.py @@ -163,7 +163,7 @@ def on_close(self): 'She sells seashells by the seashore', test_callback, accept='audio/wav', - voice='en-AU_CraigVoice') + voice='en-GB_JamesV3Voice') assert test_callback.error is None assert test_callback.fd is not None assert os.stat(file).st_size > 0 From 609e75df66d65240eec6b2a01dfebdacedec76d7 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 7 Aug 2023 12:19:14 -0500 Subject: [PATCH 403/455] fix(version): fast froward versioning --- .bumpversion.cfg | 2 +- CHANGELOG.md | 133 ++++++++++++++++++++++++++++++++++++++++++ ibm_watson/version.py | 2 +- setup.py | 2 +- 4 files changed, 136 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index de99fb6cb..3f0bf36fc 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 6.0.1 +current_version = 7.0.1 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/CHANGELOG.md b/CHANGELOG.md index cbb2fead0..9116f1278 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,136 @@ +## [7.0.1](https://github.com/watson-developer-cloud/python-sdk/compare/v7.0.0...v7.0.1) (2022-08-07) + + +### Bug Fixes + +* **tts,stt,version:** unpinned websocket-client ([75432a6](https://github.com/watson-developer-cloud/python-sdk/commit/75432a6ab4b737a3a7afd8009e70f68e6f02d312)) + +# [7.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v6.0.1...v7.0.0) (2023-03-17) + + +### Bug Fixes + +* **assistantv2:** use original createSession method signature ([ac82c45](https://github.com/watson-developer-cloud/python-sdk/commit/ac82c45c14ddcd0d608496d1193da09d555b6f15)) +* **nlu:** require training_data_content_type ([d91f007](https://github.com/watson-developer-cloud/python-sdk/commit/d91f007fafd568cc30abf15d54c53935f32197a8)) +* **version:** change version strings for release ([aee877c](https://github.com/watson-developer-cloud/python-sdk/commit/aee877ce8ae50f495f1dacfd7cbd26a117aab594)) + + +### Features + +* **assistant-v1:** update models and add new methods ([fbcebd0](https://github.com/watson-developer-cloud/python-sdk/commit/fbcebd088c205070e9bae22821b2a2e8920a07c5)) +* **assistant-v2:** update models and add new methods ([a1586ec](https://github.com/watson-developer-cloud/python-sdk/commit/a1586ec6750e5130493fa8d08ac01d13a36e3715)) +* **assistantv2:** add several new functions ([d2d6fbf](https://github.com/watson-developer-cloud/python-sdk/commit/d2d6fbfce304bdb197b665e612022d4c4cc6b5bd)) +* **assistantv2:** improved typing ([a84cd6c](https://github.com/watson-developer-cloud/python-sdk/commit/a84cd6c983d913811b7943e579126e6a1c71781f)) +* **discov2:** new aggregation types ([41cb185](https://github.com/watson-developer-cloud/python-sdk/commit/41cb1853267528dcedfd49f42710ff28e6885d37)) +* **discovery-v2:** update models and add several new methods ([972a1ae](https://github.com/watson-developer-cloud/python-sdk/commit/972a1ae6f774a4849ffc6e8fe1a77e04090a7441)) +* **nlu:** add trainingParameters ([c8e056c](https://github.com/watson-developer-cloud/python-sdk/commit/c8e056c8d503656271bde6315b84838771975179)) +* **nlu:** remove all sentimentModel functions ([d6e342f](https://github.com/watson-developer-cloud/python-sdk/commit/d6e342f7fc34fdc82cf6042f585d3110bd38abfd)) +* **nlu:** remove beta model param from Sentiment ([1469190](https://github.com/watson-developer-cloud/python-sdk/commit/1469190590cdaff60156816964b88822fef5e933)) +* **release:** trigger release ([c08a117](https://github.com/watson-developer-cloud/python-sdk/commit/c08a117294c9d2a52b8493c1cec55b8826621abc)) +* **stt, tts:** add more models ([8b9f6a8](https://github.com/watson-developer-cloud/python-sdk/commit/8b9f6a897e2e9d3fdb43aa0ce1adc8b2a581f4e9)) +* **stt:** add and remove models ([14fd5f2](https://github.com/watson-developer-cloud/python-sdk/commit/14fd5f22096ac83e99a5c6092fbead23cf309f45)) +* **stt:** update parameters ([e40c06c](https://github.com/watson-developer-cloud/python-sdk/commit/e40c06c52ec00168d9a5f7f0e174c8a1fef65d21)) +* **tts:** add parameters ([b300c55](https://github.com/watson-developer-cloud/python-sdk/commit/b300c5527794eee5ab692a51eb858164dddfef93)) +* **tts:** add params and add model constants ([546796d](https://github.com/watson-developer-cloud/python-sdk/commit/546796d3db37f4af52a7745a62f24e769094b567)) +* **wss:** add and remove websocket params ([1b5f171](https://github.com/watson-developer-cloud/python-sdk/commit/1b5f1715ad92573bc8fce2e44ba8b6e5efda3780)) + + +### BREAKING CHANGES + +* **release:** trigger release +* **assistantv2:** createSession param removed +* **assistantv2:** removing and changing of classes +* **discov2:** confidence property removed +* **discov2:** smartDocumentUnderstanding param removed +* **discov2:** QueryAggregation structure changed +* **nlu:** remove all sentimentModel functions and models + +# [6.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v6.0.1...v6.1.0) (2022-08-10) + + +### Bug Fixes + +* **assistantv2:** use original createSession method signature ([ac82c45](https://github.com/watson-developer-cloud/python-sdk/commit/ac82c45c14ddcd0d608496d1193da09d555b6f15)) + + +### Features + +* **assistant-v1:** update models and add new methods ([fbcebd0](https://github.com/watson-developer-cloud/python-sdk/commit/fbcebd088c205070e9bae22821b2a2e8920a07c5)) +* **assistant-v2:** update models and add new methods ([a1586ec](https://github.com/watson-developer-cloud/python-sdk/commit/a1586ec6750e5130493fa8d08ac01d13a36e3715)) +* **discovery-v2:** update models and add several new methods ([972a1ae](https://github.com/watson-developer-cloud/python-sdk/commit/972a1ae6f774a4849ffc6e8fe1a77e04090a7441)) +* **nlu:** add trainingParameters ([c8e056c](https://github.com/watson-developer-cloud/python-sdk/commit/c8e056c8d503656271bde6315b84838771975179)) +* **stt:** update parameters ([e40c06c](https://github.com/watson-developer-cloud/python-sdk/commit/e40c06c52ec00168d9a5f7f0e174c8a1fef65d21)) +* **tts:** add parameters ([b300c55](https://github.com/watson-developer-cloud/python-sdk/commit/b300c5527794eee5ab692a51eb858164dddfef93)) +* **wss:** add and remove websocket params ([1b5f171](https://github.com/watson-developer-cloud/python-sdk/commit/1b5f1715ad92573bc8fce2e44ba8b6e5efda3780)) + +# [6.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v5.3.0...v6.0.0) (2022-03-21) + + +### Bug Fixes + +* **ws:** remove websocket debug code ([21399b7](https://github.com/watson-developer-cloud/python-sdk/commit/21399b769608a25f00fe4790b850ced77a8fc748)) + + +* Major release 2022 (#816) ([97de097](https://github.com/watson-developer-cloud/python-sdk/commit/97de097b8c86622ab2f30f5386bb74321d28addf)), closes [#816](https://github.com/watson-developer-cloud/python-sdk/issues/816) + + +### BREAKING CHANGES + +* OutputData: required text property removed, RuntimeEntity: optional metadata property removed +RuntimeResponseGeneric: Three new response types added +Workspace: workspaceID changed form required to optional + +* feat(assistantv2): add three new response types, rename model, remove properties +* RuntimeEntity: optional metadata property removed, MessageOutputDebug: nodesVisited type DialogNodesVisited changed to DialogNodeVisited. +MessageContext: integrations property added +MessageContextGlobalSystem: skipUserInput property added +MessageContextStateless: integrations property added +MessageInput: attachments property added +MessageInputStateless: attachments property added +RuntimeResponseGeneric: Three new response types added + +* refactor(cc): remove compare and comply ヾ(・‿・) + +* refactor(nlc): remove nlc ヾ(・‿・) + +* feat(nlu): remove MetadataOptions model + +* refactor(lt): comment change and test updates + +* refactor(pi): remove personality insights ヾ(・‿・) + +* feat(stt/tts): add new property and comment changes + +* refactor(ta/visrec): remove ta and visrec ヾ(・‿・) + +* refactor(all): remove remaining traces of removed services + +* feat(assistantv1): add new dialogNode models and additional properties for Workspace + +* feat(discov1): update QueryAggregation subclasses +* QueryAggregation: QueryAggregation subclasses changed. +DocumentStatus: documentID, status, and statusDescription are now optional + +* feat(stt): change grammarFile property type +* addGrammar parameter grammarFile changed from String to Data type + +SupportedFeatures: customAcousticModel property added + +* chore: copyright changes + +* build(secrets): upload detect-secrets baseline + +* docs(readme): add deprecation note and remove old references + +* ci(version): remove python 3.6 support and add 3.9 support + +## [5.3.1](https://github.com/watson-developer-cloud/python-sdk/compare/v5.3.0...v5.3.1) (2022-01-26) + + +### Bug Fixes + +* **ws:** remove websocket debug code ([21399b7](https://github.com/watson-developer-cloud/python-sdk/commit/21399b769608a25f00fe4790b850ced77a8fc748)) + # [5.3.0](https://github.com/watson-developer-cloud/python-sdk/compare/v5.2.3...v5.3.0) (2021-09-14) diff --git a/ibm_watson/version.py b/ibm_watson/version.py index c4b0ef895..2f21dd167 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '6.0.1' +__version__ = '7.0.1' diff --git a/setup.py b/setup.py index 6d47ba208..8c8bc7c3a 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '6.0.1' +__version__ = '7.0.1' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From 00af8b934d82e35498bf6f24c55463b98db1f393 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 12 Oct 2023 11:56:53 -0500 Subject: [PATCH 404/455] docs(readme): request library link update --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9733d0262..924ecb0e4 100755 --- a/README.md +++ b/README.md @@ -209,7 +209,7 @@ If you have issues with the APIs or have a question about the Watson services, s ## Configuring the http client (Supported from v1.1.0) -To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://2.python-requests.org/en/master/api/#requests.request) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance +To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://requests.readthedocs.io/en/latest/api/) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance ```python from ibm_watson import AssistantV1 From 75285eaf75765e4c4a1ac97f861fbb7e3c57ed34 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 12 Oct 2023 15:30:36 -0500 Subject: [PATCH 405/455] docs(readme): remove broken tags --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 924ecb0e4..d09f490b0 100755 --- a/README.md +++ b/README.md @@ -2,7 +2,6 @@ [![Build and Test](https://github.com/watson-developer-cloud/python-sdk/workflows/Build%20and%20Test/badge.svg?branch=master)](https://github.com/watson-developer-cloud/python-sdk/actions?query=workflow%3A"Build+and+Test") [![Deploy and Publish](https://github.com/watson-developer-cloud/python-sdk/workflows/Deploy%20and%20Publish/badge.svg?branch=master)](https://github.com/watson-developer-cloud/python-sdk/actions?query=workflow%3A%22Deploy+and+Publish%22) -[![Slack](https://wdc-slack-inviter.mybluemix.net/badge.svg)](https://wdc-slack-inviter.mybluemix.net) [![Latest Stable Version](https://img.shields.io/pypi/v/ibm-watson.svg)](https://pypi.python.org/pypi/ibm-watson) [![CLA assistant](https://cla-assistant.io/readme/badge/watson-developer-cloud/python-sdk)](https://cla-assistant.io/watson-developer-cloud/python-sdk) From 223a4dd28abc26775a1d0d4a6e8a574ce92b437b Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 21 Feb 2024 12:49:49 -0600 Subject: [PATCH 406/455] chore(all): formatting changes --- ibm_watson/assistant_v1.py | 5913 ++++++++-------- ibm_watson/assistant_v2.py | 5241 +++++++------- ibm_watson/discovery_v1.py | 6071 +++++++++-------- ibm_watson/discovery_v2.py | 5533 ++++++++------- ibm_watson/language_translator_v3.py | 854 ++- .../natural_language_understanding_v1.py | 2410 ++++--- ibm_watson/speech_to_text_v1.py | 2622 ++++--- ibm_watson/text_to_speech_v1.py | 1113 +-- test/unit/test_assistant_v1.py | 3291 +++++---- test/unit/test_assistant_v2.py | 2147 +++--- test/unit/test_discovery_v1.py | 3004 ++++---- test/unit/test_discovery_v2.py | 2444 ++++--- test/unit/test_language_translator_v3.py | 515 +- .../test_natural_language_understanding_v1.py | 937 +-- test/unit/test_speech_to_text_v1.py | 1521 +++-- test/unit/test_text_to_speech_v1.py | 786 ++- 16 files changed, 24897 insertions(+), 19505 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index d0a1620e5..387e1956e 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -28,7 +28,7 @@ from datetime import datetime from enum import Enum -from typing import Dict, List +from typing import Dict, List, Optional import json import sys @@ -81,18 +81,20 @@ def __init__( # Message ######################### - def message(self, - workspace_id: str, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - alternate_intents: bool = None, - context: 'Context' = None, - output: 'OutputData' = None, - user_id: str = None, - nodes_visited_details: bool = None, - **kwargs) -> DetailedResponse: + def message( + self, + workspace_id: str, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + alternate_intents: Optional[bool] = None, + context: Optional['Context'] = None, + output: Optional['OutputData'] = None, + user_id: Optional[str] = None, + nodes_visited_details: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get response to user input. @@ -151,9 +153,11 @@ def message(self, if output is not None: output = convert_model(output) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='message') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='message', + ) headers.update(sdk_headers) params = { @@ -183,11 +187,13 @@ def message(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/message'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -196,11 +202,13 @@ def message(self, # Bulk classify ######################### - def bulk_classify(self, - workspace_id: str, - *, - input: List['BulkClassifyUtterance'] = None, - **kwargs) -> DetailedResponse: + def bulk_classify( + self, + workspace_id: str, + *, + input: Optional[List['BulkClassifyUtterance']] = None, + **kwargs, + ) -> DetailedResponse: """ Identify intents and entities in multiple user utterances. @@ -222,9 +230,11 @@ def bulk_classify(self, if input is not None: input = [convert_model(x) for x in input] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='bulk_classify') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='bulk_classify', + ) headers.update(sdk_headers) params = { @@ -248,11 +258,13 @@ def bulk_classify(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/bulk_classify'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -261,14 +273,16 @@ def bulk_classify(self, # Workspaces ######################### - def list_workspaces(self, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_workspaces( + self, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List workspaces. @@ -293,9 +307,11 @@ def list_workspaces(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_workspaces') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_workspaces', + ) headers.update(sdk_headers) params = { @@ -313,29 +329,33 @@ def list_workspaces(self, headers['Accept'] = 'application/json' url = '/v1/workspaces' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_workspace(self, - *, - name: str = None, - description: str = None, - language: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - metadata: dict = None, - learning_opt_out: bool = None, - system_settings: 'WorkspaceSystemSettings' = None, - webhooks: List['Webhook'] = None, - intents: List['CreateIntent'] = None, - entities: List['CreateEntity'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_workspace( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create workspace. @@ -385,9 +405,11 @@ def create_workspace(self, if entities is not None: entities = [convert_model(x) for x in entities] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_workspace', + ) headers.update(sdk_headers) params = { @@ -418,22 +440,26 @@ def create_workspace(self, headers['Accept'] = 'application/json' url = '/v1/workspaces' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_workspace(self, - workspace_id: str, - *, - export: bool = None, - include_audit: bool = None, - sort: str = None, - **kwargs) -> DetailedResponse: + def get_workspace( + self, + workspace_id: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + sort: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Get information about a workspace. @@ -458,9 +484,11 @@ def get_workspace(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_workspace', + ) headers.update(sdk_headers) params = { @@ -479,31 +507,35 @@ def get_workspace(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_workspace(self, - workspace_id: str, - *, - name: str = None, - description: str = None, - language: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - metadata: dict = None, - learning_opt_out: bool = None, - system_settings: 'WorkspaceSystemSettings' = None, - webhooks: List['Webhook'] = None, - intents: List['CreateIntent'] = None, - entities: List['CreateEntity'] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_workspace( + self, + workspace_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update workspace. @@ -565,9 +597,11 @@ def update_workspace(self, if entities is not None: entities = [convert_model(x) for x in entities] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_workspace', + ) headers.update(sdk_headers) params = { @@ -602,16 +636,22 @@ def update_workspace(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: + def delete_workspace( + self, + workspace_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete workspace. @@ -626,9 +666,11 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_workspace') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_workspace', + ) headers.update(sdk_headers) params = { @@ -644,29 +686,32 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response def create_workspace_async( - self, - *, - name: str = None, - description: str = None, - language: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - metadata: dict = None, - learning_opt_out: bool = None, - system_settings: 'WorkspaceSystemSettings' = None, - webhooks: List['Webhook'] = None, - intents: List['CreateIntent'] = None, - entities: List['CreateEntity'] = None, - **kwargs) -> DetailedResponse: + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + **kwargs, + ) -> DetailedResponse: """ Create workspace asynchronously. @@ -716,9 +761,11 @@ def create_workspace_async( if entities is not None: entities = [convert_model(x) for x in entities] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_workspace_async') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_workspace_async', + ) headers.update(sdk_headers) params = { @@ -748,32 +795,35 @@ def create_workspace_async( headers['Accept'] = 'application/json' url = '/v1/workspaces_async' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response def update_workspace_async( - self, - workspace_id: str, - *, - name: str = None, - description: str = None, - language: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - metadata: dict = None, - learning_opt_out: bool = None, - system_settings: 'WorkspaceSystemSettings' = None, - webhooks: List['Webhook'] = None, - intents: List['CreateIntent'] = None, - entities: List['CreateEntity'] = None, - append: bool = None, - **kwargs) -> DetailedResponse: + self, + workspace_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + language: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + metadata: Optional[dict] = None, + learning_opt_out: Optional[bool] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['CreateIntent']] = None, + entities: Optional[List['CreateEntity']] = None, + append: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update workspace asynchronously. @@ -835,9 +885,11 @@ def update_workspace_async( if entities is not None: entities = [convert_model(x) for x in entities] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_workspace_async') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_workspace_async', + ) headers.update(sdk_headers) params = { @@ -871,22 +923,26 @@ def update_workspace_async( path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces_async/{workspace_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def export_workspace_async(self, - workspace_id: str, - *, - include_audit: bool = None, - sort: str = None, - verbose: bool = None, - **kwargs) -> DetailedResponse: + def export_workspace_async( + self, + workspace_id: str, + *, + include_audit: Optional[bool] = None, + sort: Optional[str] = None, + verbose: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Export workspace asynchronously. @@ -915,9 +971,11 @@ def export_workspace_async(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='export_workspace_async') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='export_workspace_async', + ) headers.update(sdk_headers) params = { @@ -937,10 +995,12 @@ def export_workspace_async(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces_async/{workspace_id}/export'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -949,16 +1009,18 @@ def export_workspace_async(self, # Intents ######################### - def list_intents(self, - workspace_id: str, - *, - export: bool = None, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_intents( + self, + workspace_id: str, + *, + export: Optional[bool] = None, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List intents. @@ -990,9 +1052,11 @@ def list_intents(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_intents') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_intents', + ) headers.update(sdk_headers) params = { @@ -1014,22 +1078,26 @@ def list_intents(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_intent(self, - workspace_id: str, - intent: str, - *, - description: str = None, - examples: List['Example'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_intent( + self, + workspace_id: str, + intent: str, + *, + description: Optional[str] = None, + examples: Optional[List['Example']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create intent. @@ -1061,9 +1129,11 @@ def create_intent(self, if examples is not None: examples = [convert_model(x) for x in examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_intent', + ) headers.update(sdk_headers) params = { @@ -1089,22 +1159,26 @@ def create_intent(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_intent(self, - workspace_id: str, - intent: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_intent( + self, + workspace_id: str, + intent: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get intent. @@ -1128,9 +1202,11 @@ def get_intent(self, if not intent: raise ValueError('intent must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_intent', + ) headers.update(sdk_headers) params = { @@ -1149,24 +1225,28 @@ def get_intent(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_intent(self, - workspace_id: str, - intent: str, - *, - new_intent: str = None, - new_description: str = None, - new_examples: List['Example'] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_intent( + self, + workspace_id: str, + intent: str, + *, + new_intent: Optional[str] = None, + new_description: Optional[str] = None, + new_examples: Optional[List['Example']] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update intent. @@ -1209,9 +1289,11 @@ def update_intent(self, if new_examples is not None: new_examples = [convert_model(x) for x in new_examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_intent', + ) headers.update(sdk_headers) params = { @@ -1239,17 +1321,23 @@ def update_intent(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_intent(self, workspace_id: str, intent: str, - **kwargs) -> DetailedResponse: + def delete_intent( + self, + workspace_id: str, + intent: str, + **kwargs, + ) -> DetailedResponse: """ Delete intent. @@ -1267,9 +1355,11 @@ def delete_intent(self, workspace_id: str, intent: str, if not intent: raise ValueError('intent must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_intent') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_intent', + ) headers.update(sdk_headers) params = { @@ -1286,10 +1376,12 @@ def delete_intent(self, workspace_id: str, intent: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1298,16 +1390,18 @@ def delete_intent(self, workspace_id: str, intent: str, # Examples ######################### - def list_examples(self, - workspace_id: str, - intent: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_examples( + self, + workspace_id: str, + intent: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List user input examples. @@ -1339,9 +1433,11 @@ def list_examples(self, if not intent: raise ValueError('intent must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_examples') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_examples', + ) headers.update(sdk_headers) params = { @@ -1363,22 +1459,26 @@ def list_examples(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_example(self, - workspace_id: str, - intent: str, - text: str, - *, - mentions: List['Mention'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_example( + self, + workspace_id: str, + intent: str, + text: str, + *, + mentions: Optional[List['Mention']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create user input example. @@ -1410,9 +1510,11 @@ def create_example(self, if mentions is not None: mentions = [convert_model(x) for x in mentions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_example', + ) headers.update(sdk_headers) params = { @@ -1438,22 +1540,26 @@ def create_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_example(self, - workspace_id: str, - intent: str, - text: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_example( + self, + workspace_id: str, + intent: str, + text: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get user input example. @@ -1476,9 +1582,11 @@ def get_example(self, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_example', + ) headers.update(sdk_headers) params = { @@ -1496,23 +1604,27 @@ def get_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_example(self, - workspace_id: str, - intent: str, - text: str, - *, - new_text: str = None, - new_mentions: List['Mention'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_example( + self, + workspace_id: str, + intent: str, + text: str, + *, + new_text: Optional[str] = None, + new_mentions: Optional[List['Mention']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update user input example. @@ -1545,9 +1657,11 @@ def update_example(self, if new_mentions is not None: new_mentions = [convert_model(x) for x in new_mentions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_example', + ) headers.update(sdk_headers) params = { @@ -1573,17 +1687,24 @@ def update_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_example(self, workspace_id: str, intent: str, text: str, - **kwargs) -> DetailedResponse: + def delete_example( + self, + workspace_id: str, + intent: str, + text: str, + **kwargs, + ) -> DetailedResponse: """ Delete user input example. @@ -1604,9 +1725,11 @@ def delete_example(self, workspace_id: str, intent: str, text: str, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_example', + ) headers.update(sdk_headers) params = { @@ -1623,10 +1746,12 @@ def delete_example(self, workspace_id: str, intent: str, text: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/intents/{intent}/examples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1635,15 +1760,17 @@ def delete_example(self, workspace_id: str, intent: str, text: str, # Counterexamples ######################### - def list_counterexamples(self, - workspace_id: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_counterexamples( + self, + workspace_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List counterexamples. @@ -1672,9 +1799,11 @@ def list_counterexamples(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_counterexamples') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_counterexamples', + ) headers.update(sdk_headers) params = { @@ -1696,20 +1825,24 @@ def list_counterexamples(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_counterexample(self, - workspace_id: str, - text: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_counterexample( + self, + workspace_id: str, + text: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create counterexample. @@ -1735,9 +1868,11 @@ def create_counterexample(self, if text is None: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_counterexample', + ) headers.update(sdk_headers) params = { @@ -1762,21 +1897,25 @@ def create_counterexample(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_counterexample(self, - workspace_id: str, - text: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_counterexample( + self, + workspace_id: str, + text: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get counterexample. @@ -1798,9 +1937,11 @@ def get_counterexample(self, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_counterexample', + ) headers.update(sdk_headers) params = { @@ -1818,21 +1959,25 @@ def get_counterexample(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_counterexample(self, - workspace_id: str, - text: str, - *, - new_text: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_counterexample( + self, + workspace_id: str, + text: str, + *, + new_text: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update counterexample. @@ -1858,9 +2003,11 @@ def update_counterexample(self, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_counterexample', + ) headers.update(sdk_headers) params = { @@ -1885,17 +2032,23 @@ def update_counterexample(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_counterexample(self, workspace_id: str, text: str, - **kwargs) -> DetailedResponse: + def delete_counterexample( + self, + workspace_id: str, + text: str, + **kwargs, + ) -> DetailedResponse: """ Delete counterexample. @@ -1915,9 +2068,11 @@ def delete_counterexample(self, workspace_id: str, text: str, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_counterexample') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_counterexample', + ) headers.update(sdk_headers) params = { @@ -1934,10 +2089,12 @@ def delete_counterexample(self, workspace_id: str, text: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/counterexamples/{text}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1946,16 +2103,18 @@ def delete_counterexample(self, workspace_id: str, text: str, # Entities ######################### - def list_entities(self, - workspace_id: str, - *, - export: bool = None, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_entities( + self, + workspace_id: str, + *, + export: Optional[bool] = None, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entities. @@ -1987,9 +2146,11 @@ def list_entities(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_entities') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_entities', + ) headers.update(sdk_headers) params = { @@ -2011,24 +2172,28 @@ def list_entities(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_entity(self, - workspace_id: str, - entity: str, - *, - description: str = None, - metadata: dict = None, - fuzzy_match: bool = None, - values: List['CreateValue'] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_entity( + self, + workspace_id: str, + entity: str, + *, + description: Optional[str] = None, + metadata: Optional[dict] = None, + fuzzy_match: Optional[bool] = None, + values: Optional[List['CreateValue']] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create entity. @@ -2065,9 +2230,11 @@ def create_entity(self, if values is not None: values = [convert_model(x) for x in values] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_entity', + ) headers.update(sdk_headers) params = { @@ -2095,22 +2262,26 @@ def create_entity(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_entity(self, - workspace_id: str, - entity: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_entity( + self, + workspace_id: str, + entity: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get entity. @@ -2134,9 +2305,11 @@ def get_entity(self, if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_entity', + ) headers.update(sdk_headers) params = { @@ -2155,26 +2328,30 @@ def get_entity(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_entity(self, - workspace_id: str, - entity: str, - *, - new_entity: str = None, - new_description: str = None, - new_metadata: dict = None, - new_fuzzy_match: bool = None, - new_values: List['CreateValue'] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_entity( + self, + workspace_id: str, + entity: str, + *, + new_entity: Optional[str] = None, + new_description: Optional[str] = None, + new_metadata: Optional[dict] = None, + new_fuzzy_match: Optional[bool] = None, + new_values: Optional[List['CreateValue']] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update entity. @@ -2220,9 +2397,11 @@ def update_entity(self, if new_values is not None: new_values = [convert_model(x) for x in new_values] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_entity', + ) headers.update(sdk_headers) params = { @@ -2252,17 +2431,23 @@ def update_entity(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_entity(self, workspace_id: str, entity: str, - **kwargs) -> DetailedResponse: + def delete_entity( + self, + workspace_id: str, + entity: str, + **kwargs, + ) -> DetailedResponse: """ Delete entity. @@ -2280,9 +2465,11 @@ def delete_entity(self, workspace_id: str, entity: str, if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_entity') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_entity', + ) headers.update(sdk_headers) params = { @@ -2299,10 +2486,12 @@ def delete_entity(self, workspace_id: str, entity: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2311,13 +2500,15 @@ def delete_entity(self, workspace_id: str, entity: str, # Mentions ######################### - def list_mentions(self, - workspace_id: str, - entity: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_mentions( + self, + workspace_id: str, + entity: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entity mentions. @@ -2342,9 +2533,11 @@ def list_mentions(self, if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_mentions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_mentions', + ) headers.update(sdk_headers) params = { @@ -2363,10 +2556,12 @@ def list_mentions(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/mentions'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2375,17 +2570,19 @@ def list_mentions(self, # Values ######################### - def list_values(self, - workspace_id: str, - entity: str, - *, - export: bool = None, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_values( + self, + workspace_id: str, + entity: str, + *, + export: Optional[bool] = None, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entity values. @@ -2420,9 +2617,11 @@ def list_values(self, if not entity: raise ValueError('entity must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_values') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_values', + ) headers.update(sdk_headers) params = { @@ -2445,25 +2644,29 @@ def list_values(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_value(self, - workspace_id: str, - entity: str, - value: str, - *, - metadata: dict = None, - type: str = None, - synonyms: List[str] = None, - patterns: List[str] = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_value( + self, + workspace_id: str, + entity: str, + value: str, + *, + metadata: Optional[dict] = None, + type: Optional[str] = None, + synonyms: Optional[List[str]] = None, + patterns: Optional[List[str]] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create entity value. @@ -2504,9 +2707,11 @@ def create_value(self, if value is None: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_value', + ) headers.update(sdk_headers) params = { @@ -2535,23 +2740,27 @@ def create_value(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_value(self, - workspace_id: str, - entity: str, - value: str, - *, - export: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_value( + self, + workspace_id: str, + entity: str, + value: str, + *, + export: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get entity value. @@ -2578,9 +2787,11 @@ def get_value(self, if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_value', + ) headers.update(sdk_headers) params = { @@ -2599,27 +2810,31 @@ def get_value(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_value(self, - workspace_id: str, - entity: str, - value: str, - *, - new_value: str = None, - new_metadata: dict = None, - new_type: str = None, - new_synonyms: List[str] = None, - new_patterns: List[str] = None, - append: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_value( + self, + workspace_id: str, + entity: str, + value: str, + *, + new_value: Optional[str] = None, + new_metadata: Optional[dict] = None, + new_type: Optional[str] = None, + new_synonyms: Optional[List[str]] = None, + new_patterns: Optional[List[str]] = None, + append: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update entity value. @@ -2673,9 +2888,11 @@ def update_value(self, if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_value', + ) headers.update(sdk_headers) params = { @@ -2705,17 +2922,24 @@ def update_value(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_value(self, workspace_id: str, entity: str, value: str, - **kwargs) -> DetailedResponse: + def delete_value( + self, + workspace_id: str, + entity: str, + value: str, + **kwargs, + ) -> DetailedResponse: """ Delete entity value. @@ -2736,9 +2960,11 @@ def delete_value(self, workspace_id: str, entity: str, value: str, if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_value') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_value', + ) headers.update(sdk_headers) params = { @@ -2755,10 +2981,12 @@ def delete_value(self, workspace_id: str, entity: str, value: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2767,17 +2995,19 @@ def delete_value(self, workspace_id: str, entity: str, value: str, # Synonyms ######################### - def list_synonyms(self, - workspace_id: str, - entity: str, - value: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_synonyms( + self, + workspace_id: str, + entity: str, + value: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List entity value synonyms. @@ -2811,9 +3041,11 @@ def list_synonyms(self, if not value: raise ValueError('value must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_synonyms') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_synonyms', + ) headers.update(sdk_headers) params = { @@ -2835,22 +3067,26 @@ def list_synonyms(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_synonym(self, - workspace_id: str, - entity: str, - value: str, - synonym: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create entity value synonym. @@ -2882,9 +3118,11 @@ def create_synonym(self, if synonym is None: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_synonym', + ) headers.update(sdk_headers) params = { @@ -2909,23 +3147,27 @@ def create_synonym(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_synonym(self, - workspace_id: str, - entity: str, - value: str, - synonym: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get entity value synonym. @@ -2951,9 +3193,11 @@ def get_synonym(self, if not synonym: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_synonym', + ) headers.update(sdk_headers) params = { @@ -2972,23 +3216,27 @@ def get_synonym(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_synonym(self, - workspace_id: str, - entity: str, - value: str, - synonym: str, - *, - new_synonym: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + *, + new_synonym: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update entity value synonym. @@ -3021,9 +3269,11 @@ def update_synonym(self, if not synonym: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_synonym', + ) headers.update(sdk_headers) params = { @@ -3049,17 +3299,25 @@ def update_synonym(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_synonym(self, workspace_id: str, entity: str, value: str, - synonym: str, **kwargs) -> DetailedResponse: + def delete_synonym( + self, + workspace_id: str, + entity: str, + value: str, + synonym: str, + **kwargs, + ) -> DetailedResponse: """ Delete entity value synonym. @@ -3083,9 +3341,11 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, if not synonym: raise ValueError('synonym must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_synonym') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_synonym', + ) headers.update(sdk_headers) params = { @@ -3103,10 +3363,12 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/entities/{entity}/values/{value}/synonyms/{synonym}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3115,15 +3377,17 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, # Dialog nodes ######################### - def list_dialog_nodes(self, - workspace_id: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_dialog_nodes( + self, + workspace_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List dialog nodes. @@ -3151,9 +3415,11 @@ def list_dialog_nodes(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_dialog_nodes') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_dialog_nodes', + ) headers.update(sdk_headers) params = { @@ -3175,38 +3441,42 @@ def list_dialog_nodes(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_dialog_node(self, - workspace_id: str, - dialog_node: str, - *, - description: str = None, - conditions: str = None, - parent: str = None, - previous_sibling: str = None, - output: 'DialogNodeOutput' = None, - context: 'DialogNodeContext' = None, - metadata: dict = None, - next_step: 'DialogNodeNextStep' = None, - title: str = None, - type: str = None, - event_name: str = None, - variable: str = None, - actions: List['DialogNodeAction'] = None, - digress_in: str = None, - digress_out: str = None, - digress_out_slots: str = None, - user_label: str = None, - disambiguation_opt_out: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def create_dialog_node( + self, + workspace_id: str, + dialog_node: str, + *, + description: Optional[str] = None, + conditions: Optional[str] = None, + parent: Optional[str] = None, + previous_sibling: Optional[str] = None, + output: Optional['DialogNodeOutput'] = None, + context: Optional['DialogNodeContext'] = None, + metadata: Optional[dict] = None, + next_step: Optional['DialogNodeNextStep'] = None, + title: Optional[str] = None, + type: Optional[str] = None, + event_name: Optional[str] = None, + variable: Optional[str] = None, + actions: Optional[List['DialogNodeAction']] = None, + digress_in: Optional[str] = None, + digress_out: Optional[str] = None, + digress_out_slots: Optional[str] = None, + user_label: Optional[str] = None, + disambiguation_opt_out: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Create dialog node. @@ -3285,9 +3555,11 @@ def create_dialog_node(self, if actions is not None: actions = [convert_model(x) for x in actions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_dialog_node', + ) headers.update(sdk_headers) params = { @@ -3330,21 +3602,25 @@ def create_dialog_node(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_dialog_node(self, - workspace_id: str, - dialog_node: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_dialog_node( + self, + workspace_id: str, + dialog_node: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get dialog node. @@ -3365,9 +3641,11 @@ def get_dialog_node(self, if not dialog_node: raise ValueError('dialog_node must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_dialog_node', + ) headers.update(sdk_headers) params = { @@ -3385,39 +3663,43 @@ def get_dialog_node(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_dialog_node(self, - workspace_id: str, - dialog_node: str, - *, - new_dialog_node: str = None, - new_description: str = None, - new_conditions: str = None, - new_parent: str = None, - new_previous_sibling: str = None, - new_output: 'DialogNodeOutput' = None, - new_context: 'DialogNodeContext' = None, - new_metadata: dict = None, - new_next_step: 'DialogNodeNextStep' = None, - new_title: str = None, - new_type: str = None, - new_event_name: str = None, - new_variable: str = None, - new_actions: List['DialogNodeAction'] = None, - new_digress_in: str = None, - new_digress_out: str = None, - new_digress_out_slots: str = None, - new_user_label: str = None, - new_disambiguation_opt_out: bool = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def update_dialog_node( + self, + workspace_id: str, + dialog_node: str, + *, + new_dialog_node: Optional[str] = None, + new_description: Optional[str] = None, + new_conditions: Optional[str] = None, + new_parent: Optional[str] = None, + new_previous_sibling: Optional[str] = None, + new_output: Optional['DialogNodeOutput'] = None, + new_context: Optional['DialogNodeContext'] = None, + new_metadata: Optional[dict] = None, + new_next_step: Optional['DialogNodeNextStep'] = None, + new_title: Optional[str] = None, + new_type: Optional[str] = None, + new_event_name: Optional[str] = None, + new_variable: Optional[str] = None, + new_actions: Optional[List['DialogNodeAction']] = None, + new_digress_in: Optional[str] = None, + new_digress_out: Optional[str] = None, + new_digress_out_slots: Optional[str] = None, + new_user_label: Optional[str] = None, + new_disambiguation_opt_out: Optional[bool] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update dialog node. @@ -3500,9 +3782,11 @@ def update_dialog_node(self, if new_actions is not None: new_actions = [convert_model(x) for x in new_actions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_dialog_node', + ) headers.update(sdk_headers) params = { @@ -3545,17 +3829,23 @@ def update_dialog_node(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_dialog_node(self, workspace_id: str, dialog_node: str, - **kwargs) -> DetailedResponse: + def delete_dialog_node( + self, + workspace_id: str, + dialog_node: str, + **kwargs, + ) -> DetailedResponse: """ Delete dialog node. @@ -3574,9 +3864,11 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, if not dialog_node: raise ValueError('dialog_node must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_dialog_node') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_dialog_node', + ) headers.update(sdk_headers) params = { @@ -3593,10 +3885,12 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/dialog_nodes/{dialog_node}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3605,14 +3899,16 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, # Logs ######################### - def list_logs(self, - workspace_id: str, - *, - sort: str = None, - filter: str = None, - page_limit: int = None, - cursor: str = None, - **kwargs) -> DetailedResponse: + def list_logs( + self, + workspace_id: str, + *, + sort: Optional[str] = None, + filter: Optional[str] = None, + page_limit: Optional[int] = None, + cursor: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List log events in a workspace. @@ -3642,9 +3938,11 @@ def list_logs(self, if not workspace_id: raise ValueError('workspace_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_logs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_logs', + ) headers.update(sdk_headers) params = { @@ -3664,21 +3962,25 @@ def list_logs(self, path_param_values = self.encode_path_vars(workspace_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/workspaces/{workspace_id}/logs'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_all_logs(self, - filter: str, - *, - sort: str = None, - page_limit: int = None, - cursor: str = None, - **kwargs) -> DetailedResponse: + def list_all_logs( + self, + filter: str, + *, + sort: Optional[str] = None, + page_limit: Optional[int] = None, + cursor: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List log events in all workspaces. @@ -3711,9 +4013,11 @@ def list_all_logs(self, if not filter: raise ValueError('filter must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_all_logs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_all_logs', + ) headers.update(sdk_headers) params = { @@ -3730,10 +4034,12 @@ def list_all_logs(self, headers['Accept'] = 'application/json' url = '/v1/logs' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3742,7 +4048,11 @@ def list_all_logs(self, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -3768,9 +4078,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -3784,10 +4096,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3803,6 +4117,7 @@ class Sort(str, Enum): The attribute by which returned workspaces will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + NAME = 'name' UPDATED = 'updated' @@ -3818,6 +4133,7 @@ class Sort(str, Enum): only if **export**=`true`. Specify `sort=stable` to sort all workspace objects by unique identifier, in ascending alphabetical order. """ + STABLE = 'stable' @@ -3831,6 +4147,7 @@ class Sort(str, Enum): Indicates how the returned workspace data will be sorted. Specify `sort=stable` to sort all workspace objects by unique identifier, in ascending alphabetical order. """ + STABLE = 'stable' @@ -3844,6 +4161,7 @@ class Sort(str, Enum): The attribute by which returned intents will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + INTENT = 'intent' UPDATED = 'updated' @@ -3858,6 +4176,7 @@ class Sort(str, Enum): The attribute by which returned examples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + TEXT = 'text' UPDATED = 'updated' @@ -3872,6 +4191,7 @@ class Sort(str, Enum): The attribute by which returned counterexamples will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + TEXT = 'text' UPDATED = 'updated' @@ -3886,6 +4206,7 @@ class Sort(str, Enum): The attribute by which returned entities will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + ENTITY = 'entity' UPDATED = 'updated' @@ -3900,6 +4221,7 @@ class Sort(str, Enum): The attribute by which returned entity values will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + VALUE = 'value' UPDATED = 'updated' @@ -3914,6 +4236,7 @@ class Sort(str, Enum): The attribute by which returned entity value synonyms will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + SYNONYM = 'synonym' UPDATED = 'updated' @@ -3928,6 +4251,7 @@ class Sort(str, Enum): The attribute by which returned dialog nodes will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + DIALOG_NODE = 'dialog_node' UPDATED = 'updated' @@ -3937,14 +4261,18 @@ class Sort(str, Enum): ############################################################################## -class AgentAvailabilityMessage(): +class AgentAvailabilityMessage: """ AgentAvailabilityMessage. - :attr str message: (optional) The text of the message. + :param str message: (optional) The text of the message. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a AgentAvailabilityMessage object. @@ -3956,8 +4284,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': """Initialize a AgentAvailabilityMessage object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -3991,23 +4319,25 @@ def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: return not self == other -class BulkClassifyOutput(): +class BulkClassifyOutput: """ BulkClassifyOutput. - :attr BulkClassifyUtterance input: (optional) The user input utterance to + :param BulkClassifyUtterance input: (optional) The user input utterance to classify. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified + :param List[RuntimeEntity] entities: (optional) An array of entities identified in the utterance. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in the utterance. """ - def __init__(self, - *, - input: 'BulkClassifyUtterance' = None, - entities: List['RuntimeEntity'] = None, - intents: List['RuntimeIntent'] = None) -> None: + def __init__( + self, + *, + input: Optional['BulkClassifyUtterance'] = None, + entities: Optional[List['RuntimeEntity']] = None, + intents: Optional[List['RuntimeIntent']] = None, + ) -> None: """ Initialize a BulkClassifyOutput object. @@ -4026,16 +4356,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': """Initialize a BulkClassifyOutput object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] + if (input := _dict.get('input')) is not None: + args['input'] = BulkClassifyUtterance.from_dict(input) + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] return cls(**args) @classmethod @@ -4088,15 +4414,19 @@ def __ne__(self, other: 'BulkClassifyOutput') -> bool: return not self == other -class BulkClassifyResponse(): +class BulkClassifyResponse: """ BulkClassifyResponse. - :attr List[BulkClassifyOutput] output: (optional) An array of objects that + :param List[BulkClassifyOutput] output: (optional) An array of objects that contain classification information for the submitted input utterances. """ - def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: + def __init__( + self, + *, + output: Optional[List['BulkClassifyOutput']] = None, + ) -> None: """ Initialize a BulkClassifyResponse object. @@ -4109,10 +4439,8 @@ def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': """Initialize a BulkClassifyResponse object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = [ - BulkClassifyOutput.from_dict(v) for v in _dict.get('output') - ] + if (output := _dict.get('output')) is not None: + args['output'] = [BulkClassifyOutput.from_dict(v) for v in output] return cls(**args) @classmethod @@ -4152,14 +4480,17 @@ def __ne__(self, other: 'BulkClassifyResponse') -> bool: return not self == other -class BulkClassifyUtterance(): +class BulkClassifyUtterance: """ The user input utterance to classify. - :attr str text: The text of the input utterance. + :param str text: The text of the input utterance. """ - def __init__(self, text: str) -> None: + def __init__( + self, + text: str, + ) -> None: """ Initialize a BulkClassifyUtterance object. @@ -4171,8 +4502,8 @@ def __init__(self, text: str) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': """Initialize a BulkClassifyUtterance object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in BulkClassifyUtterance JSON' @@ -4210,16 +4541,21 @@ def __ne__(self, other: 'BulkClassifyUtterance') -> bool: return not self == other -class CaptureGroup(): +class CaptureGroup: """ A recognized capture group for a pattern-based entity. - :attr str group: A recognized capture group for the entity. - :attr List[int] location: (optional) Zero-based character offsets that indicate + :param str group: A recognized capture group for the entity. + :param List[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ - def __init__(self, group: str, *, location: List[int] = None) -> None: + def __init__( + self, + group: str, + *, + location: Optional[List[int]] = None, + ) -> None: """ Initialize a CaptureGroup object. @@ -4234,13 +4570,13 @@ def __init__(self, group: str, *, location: List[int] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CaptureGroup': """Initialize a CaptureGroup object from a json dictionary.""" args = {} - if 'group' in _dict: - args['group'] = _dict.get('group') + if (group := _dict.get('group')) is not None: + args['group'] = group else: raise ValueError( 'Required property \'group\' not present in CaptureGroup JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (location := _dict.get('location')) is not None: + args['location'] = location return cls(**args) @classmethod @@ -4276,18 +4612,21 @@ def __ne__(self, other: 'CaptureGroup') -> bool: return not self == other -class ChannelTransferInfo(): +class ChannelTransferInfo: """ Information used by an integration to transfer the conversation to a different channel. - :attr ChannelTransferTarget target: An object specifying target channels + :param ChannelTransferTarget target: An object specifying target channels available for the transfer. Each property of this object represents an available transfer target. Currently, the only supported property is **chat**, representing the web chat integration. """ - def __init__(self, target: 'ChannelTransferTarget') -> None: + def __init__( + self, + target: 'ChannelTransferTarget', + ) -> None: """ Initialize a ChannelTransferInfo object. @@ -4302,9 +4641,8 @@ def __init__(self, target: 'ChannelTransferTarget') -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': """Initialize a ChannelTransferInfo object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = ChannelTransferTarget.from_dict( - _dict.get('target')) + if (target := _dict.get('target')) is not None: + args['target'] = ChannelTransferTarget.from_dict(target) else: raise ValueError( 'Required property \'target\' not present in ChannelTransferInfo JSON' @@ -4345,17 +4683,21 @@ def __ne__(self, other: 'ChannelTransferInfo') -> bool: return not self == other -class ChannelTransferTarget(): +class ChannelTransferTarget: """ An object specifying target channels available for the transfer. Each property of this object represents an available transfer target. Currently, the only supported property is **chat**, representing the web chat integration. - :attr ChannelTransferTargetChat chat: (optional) Information for transferring to - the web chat integration. + :param ChannelTransferTargetChat chat: (optional) Information for transferring + to the web chat integration. """ - def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: + def __init__( + self, + *, + chat: Optional['ChannelTransferTargetChat'] = None, + ) -> None: """ Initialize a ChannelTransferTarget object. @@ -4368,9 +4710,8 @@ def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': """Initialize a ChannelTransferTarget object from a json dictionary.""" args = {} - if 'chat' in _dict: - args['chat'] = ChannelTransferTargetChat.from_dict( - _dict.get('chat')) + if (chat := _dict.get('chat')) is not None: + args['chat'] = ChannelTransferTargetChat.from_dict(chat) return cls(**args) @classmethod @@ -4407,14 +4748,18 @@ def __ne__(self, other: 'ChannelTransferTarget') -> bool: return not self == other -class ChannelTransferTargetChat(): +class ChannelTransferTargetChat: """ Information for transferring to the web chat integration. - :attr str url: (optional) The URL of the target web chat. + :param str url: (optional) The URL of the target web chat. """ - def __init__(self, *, url: str = None) -> None: + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: """ Initialize a ChannelTransferTargetChat object. @@ -4426,8 +4771,8 @@ def __init__(self, *, url: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': """Initialize a ChannelTransferTargetChat object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url return cls(**args) @classmethod @@ -4461,28 +4806,31 @@ def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: return not self == other -class Context(): +class Context: """ State information for the conversation. To maintain state, include the context from the previous response. - :attr str conversation_id: (optional) The unique identifier of the conversation. - The conversation ID cannot contain any of the following characters: `+` `=` `&&` - `||` `>` `<` `!` `(` `)` `{` `}` `[` `]` `^` `"` `~` `*` `?` `:` `\` `/`. - :attr dict system: (optional) For internal use only. - :attr MessageContextMetadata metadata: (optional) Metadata related to the + :param str conversation_id: (optional) The unique identifier of the + conversation. The conversation ID cannot contain any of the following + characters: `+` `=` `&&` `||` `>` `<` `!` `(` `)` `{` `}` `[` `]` `^` `"` `~` + `*` `?` `:` `\` `/`. + :param dict system: (optional) For internal use only. + :param MessageContextMetadata metadata: (optional) Metadata related to the message. """ # The set of defined properties for the class _properties = frozenset(['conversation_id', 'system', 'metadata']) - def __init__(self, - *, - conversation_id: str = None, - system: dict = None, - metadata: 'MessageContextMetadata' = None, - **kwargs) -> None: + def __init__( + self, + *, + conversation_id: Optional[str] = None, + system: Optional[dict] = None, + metadata: Optional['MessageContextMetadata'] = None, + **kwargs, + ) -> None: """ Initialize a Context object. @@ -4505,13 +4853,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Context': """Initialize a Context object from a json dictionary.""" args = {} - if 'conversation_id' in _dict: - args['conversation_id'] = _dict.get('conversation_id') - if 'system' in _dict: - args['system'] = _dict.get('system') - if 'metadata' in _dict: - args['metadata'] = MessageContextMetadata.from_dict( - _dict.get('metadata')) + if (conversation_id := _dict.get('conversation_id')) is not None: + args['conversation_id'] = conversation_id + if (system := _dict.get('system')) is not None: + args['system'] = system + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = MessageContextMetadata.from_dict(metadata) args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -4580,24 +4927,26 @@ def __ne__(self, other: 'Context') -> bool: return not self == other -class Counterexample(): +class Counterexample: """ Counterexample. - :attr str text: The text of a user input marked as irrelevant input. This string - must conform to the following restrictions: + :param str text: The text of a user input marked as 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. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - text: str, - *, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + text: str, + *, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Counterexample object. @@ -4614,15 +4963,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Counterexample': """Initialize a Counterexample object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in Counterexample JSON') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -4660,18 +5009,21 @@ def __ne__(self, other: 'Counterexample') -> bool: return not self == other -class CounterexampleCollection(): +class CounterexampleCollection: """ CounterexampleCollection. - :attr List[Counterexample] counterexamples: An array of objects describing the + :param List[Counterexample] counterexamples: An array of objects describing the examples marked as irrelevant input. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, counterexamples: List['Counterexample'], - pagination: 'Pagination') -> None: + def __init__( + self, + counterexamples: List['Counterexample'], + pagination: 'Pagination', + ) -> None: """ Initialize a CounterexampleCollection object. @@ -4687,17 +5039,16 @@ def __init__(self, counterexamples: List['Counterexample'], def from_dict(cls, _dict: Dict) -> 'CounterexampleCollection': """Initialize a CounterexampleCollection object from a json dictionary.""" args = {} - if 'counterexamples' in _dict: + if (counterexamples := _dict.get('counterexamples')) is not None: args['counterexamples'] = [ - Counterexample.from_dict(v) - for v in _dict.get('counterexamples') + Counterexample.from_dict(v) for v in counterexamples ] else: raise ValueError( 'Required property \'counterexamples\' not present in CounterexampleCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in CounterexampleCollection JSON' @@ -4747,36 +5098,39 @@ def __ne__(self, other: 'CounterexampleCollection') -> bool: return not self == other -class CreateEntity(): +class CreateEntity: """ CreateEntity. - :attr str entity: The name of the entity. This string must conform to the + :param str entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity that you want to enable. (Any entity content specified with the request is ignored.). - :attr str description: (optional) The description of the entity. This string + :param str description: (optional) The description of the entity. This string cannot contain carriage return, newline, or tab characters. - :attr dict metadata: (optional) Any metadata related to the entity. - :attr bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param dict metadata: (optional) Any metadata related to the entity. + :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the + entity. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[CreateValue] values: (optional) An array of objects describing the + :param List[CreateValue] values: (optional) An array of objects describing the entity values. """ - def __init__(self, - entity: str, - *, - description: str = None, - metadata: dict = None, - fuzzy_match: bool = None, - created: datetime = None, - updated: datetime = None, - values: List['CreateValue'] = None) -> None: + def __init__( + self, + entity: str, + *, + description: Optional[str] = None, + metadata: Optional[dict] = None, + fuzzy_match: Optional[bool] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + values: Optional[List['CreateValue']] = None, + ) -> None: """ Initialize a CreateEntity object. @@ -4807,25 +5161,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateEntity': """Initialize a CreateEntity object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in CreateEntity JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'fuzzy_match' in _dict: - args['fuzzy_match'] = _dict.get('fuzzy_match') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'values' in _dict: - args['values'] = [ - CreateValue.from_dict(v) for v in _dict.get('values') - ] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (fuzzy_match := _dict.get('fuzzy_match')) is not None: + args['fuzzy_match'] = fuzzy_match + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (values := _dict.get('values')) is not None: + args['values'] = [CreateValue.from_dict(v) for v in values] return cls(**args) @classmethod @@ -4877,31 +5229,33 @@ def __ne__(self, other: 'CreateEntity') -> bool: return not self == other -class CreateIntent(): +class CreateIntent: """ CreateIntent. - :attr str intent: The name of the intent. This string must conform to the + :param str intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - :attr str description: (optional) The description of the intent. This string + :param str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[Example] examples: (optional) An array of user input examples for the - intent. + :param List[Example] examples: (optional) An array of user input examples for + the intent. """ - def __init__(self, - intent: str, - *, - description: str = None, - created: datetime = None, - updated: datetime = None, - examples: List['Example'] = None) -> None: + def __init__( + self, + intent: str, + *, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + examples: Optional[List['Example']] = None, + ) -> None: """ Initialize a CreateIntent object. @@ -4925,21 +5279,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateIntent': """Initialize a CreateIntent object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in CreateIntent JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'examples' in _dict: - args['examples'] = [ - Example.from_dict(v) for v in _dict.get('examples') - ] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (examples := _dict.get('examples')) is not None: + args['examples'] = [Example.from_dict(v) for v in examples] return cls(**args) @classmethod @@ -4987,40 +5339,42 @@ def __ne__(self, other: 'CreateIntent') -> bool: return not self == other -class CreateValue(): +class CreateValue: """ CreateValue. - :attr str value: The text of the entity value. This string must conform to the + :param str value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr dict metadata: (optional) Any metadata related to the entity value. - :attr str type: (optional) Specifies the type of entity value. - :attr List[str] synonyms: (optional) An array of synonyms for the entity value. + :param dict metadata: (optional) Any metadata related to the entity value. + :param str type: (optional) Specifies the type of entity value. + :param List[str] synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr List[str] patterns: (optional) An array of patterns for the entity value. + :param List[str] patterns: (optional) An array of patterns for the 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/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 + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - value: str, - *, - metadata: dict = None, - type: str = None, - synonyms: List[str] = None, - patterns: List[str] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + value: str, + *, + metadata: Optional[dict] = None, + type: Optional[str] = None, + synonyms: Optional[List[str]] = None, + patterns: Optional[List[str]] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a CreateValue object. @@ -5054,23 +5408,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateValue': """Initialize a CreateValue object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in CreateValue JSON') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'synonyms' in _dict: - args['synonyms'] = _dict.get('synonyms') - if 'patterns' in _dict: - args['patterns'] = _dict.get('patterns') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (type := _dict.get('type')) is not None: + args['type'] = type + if (synonyms := _dict.get('synonyms')) is not None: + args['synonyms'] = synonyms + if (patterns := _dict.get('patterns')) is not None: + args['patterns'] = patterns + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -5119,91 +5473,94 @@ class TypeEnum(str, Enum): """ Specifies the type of entity value. """ + SYNONYMS = 'synonyms' PATTERNS = 'patterns' -class DialogNode(): +class DialogNode: """ DialogNode. - :attr str dialog_node: The unique ID of the dialog node. This is an internal + :param str dialog_node: The unique ID of the dialog node. This is an internal identifier used to refer to the dialog node from other dialog nodes and in the diagnostic information included with message responses. This string can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - :attr str description: (optional) The description of the dialog node. This + :param str description: (optional) The description of the dialog node. This string cannot contain carriage return, newline, or tab characters. - :attr str conditions: (optional) The condition that will trigger the dialog + :param str conditions: (optional) The condition that will trigger the dialog node. This string cannot contain carriage return, newline, or tab characters. - :attr str parent: (optional) The unique ID of the parent dialog node. This + :param str parent: (optional) The unique ID of the parent dialog node. This property is omitted if the dialog node has no parent. - :attr str previous_sibling: (optional) The unique ID of the previous sibling + :param str previous_sibling: (optional) The unique ID of the previous sibling dialog node. This property is omitted if the dialog node has no previous sibling. - :attr DialogNodeOutput output: (optional) The output of the dialog node. For + :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/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :attr DialogNodeContext 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 + :param DialogNodeContext 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 following this dialog node. - :attr str title: (optional) A human-readable name for the dialog node. If the + :param str title: (optional) A human-readable name for the dialog node. If the node is included in disambiguation, this title is used to populate the **label** property of the corresponding suggestion in the `suggestion` response type (unless it is overridden by the **user_label** property). The title is also used to populate the **topic** property in the `connect_to_agent` response type. This string can contain only Unicode alphanumeric, space, underscore, hyphen, and dot characters. - :attr str type: (optional) How the dialog node is processed. - :attr str event_name: (optional) How an `event_handler` node is processed. - :attr str variable: (optional) The location in the dialog context where output + :param str type: (optional) How the dialog node is processed. + :param str event_name: (optional) How an `event_handler` node is processed. + :param str variable: (optional) The location in the dialog context where output is stored. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions to be invoked by the dialog node. - :attr str digress_in: (optional) Whether this top-level dialog node can be + :param str digress_in: (optional) Whether this top-level dialog node can be digressed into. - :attr str digress_out: (optional) Whether this dialog node can be returned to + :param str digress_out: (optional) Whether this dialog node can be returned to after a digression. - :attr str digress_out_slots: (optional) Whether the user can digress to + :param str digress_out_slots: (optional) Whether the user can digress to top-level nodes while filling out slots. - :attr str user_label: (optional) A label that can be displayed externally to + :param str user_label: (optional) A label that can be displayed externally to describe the purpose of the node to users. If set, this label is used to identify the node in disambiguation responses (overriding the value of the **title** property). - :attr bool disambiguation_opt_out: (optional) Whether the dialog node should be + :param bool disambiguation_opt_out: (optional) Whether the dialog node should be excluded from disambiguation suggestions. Valid only when **type**=`standard` or `frame`. - :attr bool disabled: (optional) For internal use only. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param bool disabled: (optional) For internal use only. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - dialog_node: str, - *, - description: str = None, - conditions: str = None, - parent: str = None, - previous_sibling: str = None, - output: 'DialogNodeOutput' = None, - context: 'DialogNodeContext' = None, - metadata: dict = None, - next_step: 'DialogNodeNextStep' = None, - title: str = None, - type: str = None, - event_name: str = None, - variable: str = None, - actions: List['DialogNodeAction'] = None, - digress_in: str = None, - digress_out: str = None, - digress_out_slots: str = None, - user_label: str = None, - disambiguation_opt_out: bool = None, - disabled: bool = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + dialog_node: str, + *, + description: Optional[str] = None, + conditions: Optional[str] = None, + parent: Optional[str] = None, + previous_sibling: Optional[str] = None, + output: Optional['DialogNodeOutput'] = None, + context: Optional['DialogNodeContext'] = None, + metadata: Optional[dict] = None, + next_step: Optional['DialogNodeNextStep'] = None, + title: Optional[str] = None, + type: Optional[str] = None, + event_name: Optional[str] = None, + variable: Optional[str] = None, + actions: Optional[List['DialogNodeAction']] = None, + digress_in: Optional[str] = None, + digress_out: Optional[str] = None, + digress_out_slots: Optional[str] = None, + user_label: Optional[str] = None, + disambiguation_opt_out: Optional[bool] = None, + disabled: Optional[bool] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a DialogNode object. @@ -5285,57 +5642,55 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNode': """Initialize a DialogNode object from a json dictionary.""" args = {} - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node else: raise ValueError( 'Required property \'dialog_node\' not present in DialogNode JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'conditions' in _dict: - args['conditions'] = _dict.get('conditions') - if 'parent' in _dict: - args['parent'] = _dict.get('parent') - if 'previous_sibling' in _dict: - args['previous_sibling'] = _dict.get('previous_sibling') - if 'output' in _dict: - args['output'] = DialogNodeOutput.from_dict(_dict.get('output')) - if 'context' in _dict: - args['context'] = DialogNodeContext.from_dict(_dict.get('context')) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'next_step' in _dict: - args['next_step'] = DialogNodeNextStep.from_dict( - _dict.get('next_step')) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'event_name' in _dict: - args['event_name'] = _dict.get('event_name') - if 'variable' in _dict: - args['variable'] = _dict.get('variable') - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(v) for v in _dict.get('actions') - ] - if 'digress_in' in _dict: - args['digress_in'] = _dict.get('digress_in') - if 'digress_out' in _dict: - args['digress_out'] = _dict.get('digress_out') - if 'digress_out_slots' in _dict: - args['digress_out_slots'] = _dict.get('digress_out_slots') - if 'user_label' in _dict: - args['user_label'] = _dict.get('user_label') - if 'disambiguation_opt_out' in _dict: - args['disambiguation_opt_out'] = _dict.get('disambiguation_opt_out') - if 'disabled' in _dict: - args['disabled'] = _dict.get('disabled') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (description := _dict.get('description')) is not None: + args['description'] = description + if (conditions := _dict.get('conditions')) is not None: + args['conditions'] = conditions + if (parent := _dict.get('parent')) is not None: + args['parent'] = parent + if (previous_sibling := _dict.get('previous_sibling')) is not None: + args['previous_sibling'] = previous_sibling + if (output := _dict.get('output')) is not None: + args['output'] = DialogNodeOutput.from_dict(output) + if (context := _dict.get('context')) is not None: + args['context'] = DialogNodeContext.from_dict(context) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (next_step := _dict.get('next_step')) is not None: + args['next_step'] = DialogNodeNextStep.from_dict(next_step) + if (title := _dict.get('title')) is not None: + args['title'] = title + if (type := _dict.get('type')) is not None: + args['type'] = type + if (event_name := _dict.get('event_name')) is not None: + args['event_name'] = event_name + if (variable := _dict.get('variable')) is not None: + args['variable'] = variable + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (digress_in := _dict.get('digress_in')) is not None: + args['digress_in'] = digress_in + if (digress_out := _dict.get('digress_out')) is not None: + args['digress_out'] = digress_out + if (digress_out_slots := _dict.get('digress_out_slots')) is not None: + args['digress_out_slots'] = digress_out_slots + if (user_label := _dict.get('user_label')) is not None: + args['user_label'] = user_label + if (disambiguation_opt_out := + _dict.get('disambiguation_opt_out')) is not None: + args['disambiguation_opt_out'] = disambiguation_opt_out + if (disabled := _dict.get('disabled')) is not None: + args['disabled'] = disabled + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -5432,6 +5787,7 @@ class TypeEnum(str, Enum): """ How the dialog node is processed. """ + STANDARD = 'standard' EVENT_HANDLER = 'event_handler' FRAME = 'frame' @@ -5443,6 +5799,7 @@ class EventNameEnum(str, Enum): """ How an `event_handler` node is processed. """ + FOCUS = 'focus' INPUT = 'input' FILLED = 'filled' @@ -5457,6 +5814,7 @@ class DigressInEnum(str, Enum): """ Whether this top-level dialog node can be digressed into. """ + NOT_AVAILABLE = 'not_available' RETURNS = 'returns' DOES_NOT_RETURN = 'does_not_return' @@ -5465,6 +5823,7 @@ class DigressOutEnum(str, Enum): """ Whether this dialog node can be returned to after a digression. """ + ALLOW_RETURNING = 'allow_returning' ALLOW_ALL = 'allow_all' ALLOW_ALL_NEVER_RETURN = 'allow_all_never_return' @@ -5473,32 +5832,35 @@ class DigressOutSlotsEnum(str, Enum): """ Whether the user can digress to top-level nodes while filling out slots. """ + NOT_ALLOWED = 'not_allowed' ALLOW_RETURNING = 'allow_returning' ALLOW_ALL = 'allow_all' -class DialogNodeAction(): +class DialogNodeAction: """ DialogNodeAction. - :attr str name: The name of the action. - :attr str type: (optional) The type of action to invoke. - :attr dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :attr str result_variable: The location in the dialog context where the result + :param str name: The name of the action. + :param str type: (optional) The type of action to invoke. + :param dict parameters: (optional) A map of key/value pairs to be provided to + the action. + :param str result_variable: The location in the dialog context where the result of the action is stored. - :attr str credentials: (optional) The name of the context variable that the + :param str credentials: (optional) The name of the context variable that the client application will use to pass in credentials for the action. """ - def __init__(self, - name: str, - result_variable: str, - *, - type: str = None, - parameters: dict = None, - credentials: str = None) -> None: + def __init__( + self, + name: str, + result_variable: str, + *, + type: Optional[str] = None, + parameters: Optional[dict] = None, + credentials: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeAction object. @@ -5521,24 +5883,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': """Initialize a DialogNodeAction object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in DialogNodeAction JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'parameters' in _dict: - args['parameters'] = _dict.get('parameters') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (parameters := _dict.get('parameters')) is not None: + args['parameters'] = parameters + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable else: raise ValueError( 'Required property \'result_variable\' not present in DialogNodeAction JSON' ) - if 'credentials' in _dict: - args['credentials'] = _dict.get('credentials') + if (credentials := _dict.get('credentials')) is not None: + args['credentials'] = credentials return cls(**args) @classmethod @@ -5584,6 +5946,7 @@ class TypeEnum(str, Enum): """ The type of action to invoke. """ + CLIENT = 'client' SERVER = 'server' CLOUD_FUNCTION = 'cloud_function' @@ -5591,18 +5954,21 @@ class TypeEnum(str, Enum): WEBHOOK = 'webhook' -class DialogNodeCollection(): +class DialogNodeCollection: """ An array of dialog nodes. - :attr List[DialogNode] dialog_nodes: An array of objects describing the dialog + :param List[DialogNode] dialog_nodes: An array of objects describing the dialog nodes defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, dialog_nodes: List['DialogNode'], - pagination: 'Pagination') -> None: + def __init__( + self, + dialog_nodes: List['DialogNode'], + pagination: 'Pagination', + ) -> None: """ Initialize a DialogNodeCollection object. @@ -5618,16 +5984,16 @@ def __init__(self, dialog_nodes: List['DialogNode'], def from_dict(cls, _dict: Dict) -> 'DialogNodeCollection': """Initialize a DialogNodeCollection object from a json dictionary.""" args = {} - if 'dialog_nodes' in _dict: + if (dialog_nodes := _dict.get('dialog_nodes')) is not None: args['dialog_nodes'] = [ - DialogNode.from_dict(v) for v in _dict.get('dialog_nodes') + DialogNode.from_dict(v) for v in dialog_nodes ] else: raise ValueError( 'Required property \'dialog_nodes\' not present in DialogNodeCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in DialogNodeCollection JSON' @@ -5676,18 +6042,23 @@ def __ne__(self, other: 'DialogNodeCollection') -> bool: return not self == other -class DialogNodeContext(): +class DialogNodeContext: """ The context for the dialog node. - :attr dict integrations: (optional) Context data intended for specific + :param dict integrations: (optional) Context data intended for specific integrations. """ # The set of defined properties for the class _properties = frozenset(['integrations']) - def __init__(self, *, integrations: dict = None, **kwargs) -> None: + def __init__( + self, + *, + integrations: Optional[dict] = None, + **kwargs, + ) -> None: """ Initialize a DialogNodeContext object. @@ -5703,8 +6074,8 @@ def __init__(self, *, integrations: dict = None, **kwargs) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeContext': """Initialize a DialogNodeContext object from a json dictionary.""" args = {} - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -5768,11 +6139,11 @@ def __ne__(self, other: 'DialogNodeContext') -> bool: return not self == other -class DialogNodeNextStep(): +class DialogNodeNextStep: """ The next step to execute following this dialog node. - :attr str behavior: What happens after the dialog node completes. The valid + :param str behavior: What happens after the dialog node completes. The valid values depend on the node type: - The following values are valid for any node: - `get_user_input` @@ -5793,16 +6164,18 @@ class DialogNodeNextStep(): - `skip_all_slots` If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. - :attr str dialog_node: (optional) The unique ID of the dialog node to process + :param str dialog_node: (optional) The unique ID of the dialog node to process next. This parameter is required if **behavior**=`jump_to`. - :attr str selector: (optional) Which part of the dialog node to process next. + :param str selector: (optional) Which part of the dialog node to process next. """ - def __init__(self, - behavior: str, - *, - dialog_node: str = None, - selector: str = None) -> None: + def __init__( + self, + behavior: str, + *, + dialog_node: Optional[str] = None, + selector: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeNextStep object. @@ -5840,16 +6213,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeNextStep': """Initialize a DialogNodeNextStep object from a json dictionary.""" args = {} - if 'behavior' in _dict: - args['behavior'] = _dict.get('behavior') + if (behavior := _dict.get('behavior')) is not None: + args['behavior'] = behavior else: raise ValueError( 'Required property \'behavior\' not present in DialogNodeNextStep JSON' ) - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'selector' in _dict: - args['selector'] = _dict.get('selector') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (selector := _dict.get('selector')) is not None: + args['selector'] = selector return cls(**args) @classmethod @@ -5910,6 +6283,7 @@ class BehaviorEnum(str, Enum): If you specify `jump_to`, then you must also specify a value for the `dialog_node` property. """ + GET_USER_INPUT = 'get_user_input' SKIP_USER_INPUT = 'skip_user_input' JUMP_TO = 'jump_to' @@ -5921,36 +6295,39 @@ class SelectorEnum(str, Enum): """ Which part of the dialog node to process next. """ + CONDITION = 'condition' CLIENT = 'client' USER_INPUT = 'user_input' BODY = 'body' -class DialogNodeOutput(): +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/assistant?topic=assistant-dialog-overview#dialog-overview-responses). - :attr List[DialogNodeOutputGeneric] generic: (optional) An array of objects + :param List[DialogNodeOutputGeneric] generic: (optional) An array of objects describing the output defined for the dialog node. - :attr dict integrations: (optional) Output intended for specific integrations. + :param dict integrations: (optional) Output intended for specific integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-responses-json). - :attr DialogNodeOutputModifiers modifiers: (optional) Options that modify how + :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. """ # The set of defined properties for the class _properties = frozenset(['generic', 'integrations', 'modifiers']) - def __init__(self, - *, - generic: List['DialogNodeOutputGeneric'] = None, - integrations: dict = None, - modifiers: 'DialogNodeOutputModifiers' = None, - **kwargs) -> None: + def __init__( + self, + *, + generic: Optional[List['DialogNodeOutputGeneric']] = None, + integrations: Optional[dict] = None, + modifiers: Optional['DialogNodeOutputModifiers'] = None, + **kwargs, + ) -> None: """ Initialize a DialogNodeOutput object. @@ -5973,16 +6350,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': """Initialize a DialogNodeOutput object from a json dictionary.""" args = {} - if 'generic' in _dict: + if (generic := _dict.get('generic')) is not None: args['generic'] = [ - DialogNodeOutputGeneric.from_dict(v) - for v in _dict.get('generic') + DialogNodeOutputGeneric.from_dict(v) for v in generic ] - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') - if 'modifiers' in _dict: - args['modifiers'] = DialogNodeOutputModifiers.from_dict( - _dict.get('modifiers')) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations + if (modifiers := _dict.get('modifiers')) is not None: + args['modifiers'] = DialogNodeOutputModifiers.from_dict(modifiers) args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -6059,14 +6434,18 @@ def __ne__(self, other: 'DialogNodeOutput') -> bool: return not self == other -class DialogNodeOutputConnectToAgentTransferInfo(): +class DialogNodeOutputConnectToAgentTransferInfo: """ Routing or other contextual information to be used by target service desk systems. - :attr dict target: (optional) + :param dict target: (optional) """ - def __init__(self, *, target: dict = None) -> None: + def __init__( + self, + *, + target: Optional[dict] = None, + ) -> None: """ Initialize a DialogNodeOutputConnectToAgentTransferInfo object. @@ -6079,8 +6458,8 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = _dict.get('target') + if (target := _dict.get('target')) is not None: + args['target'] = target return cls(**args) @classmethod @@ -6116,13 +6495,13 @@ def __ne__(self, return not self == other -class DialogNodeOutputGeneric(): +class DialogNodeOutputGeneric: """ DialogNodeOutputGeneric. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a DialogNodeOutputGeneric object. @@ -6149,22 +6528,20 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputGeneric': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'DialogNodeOutputGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe' - ])) + msg = "Cannot convert dictionary into an instance of base class 'DialogNodeOutputGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe' + ])) raise Exception(msg) @classmethod @@ -6212,17 +6589,21 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class DialogNodeOutputModifiers(): +class DialogNodeOutputModifiers: """ Options that modify how specified output is handled. - :attr bool overwrite: (optional) Whether values in the output will overwrite + :param bool overwrite: (optional) Whether values in the output will overwrite output values in an array specified by previously executed dialog nodes. If this option is set to `false`, new values will be appended to previously specified values. """ - def __init__(self, *, overwrite: bool = None) -> None: + def __init__( + self, + *, + overwrite: Optional[bool] = None, + ) -> None: """ Initialize a DialogNodeOutputModifiers object. @@ -6237,8 +6618,8 @@ def __init__(self, *, overwrite: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputModifiers': """Initialize a DialogNodeOutputModifiers object from a json dictionary.""" args = {} - if 'overwrite' in _dict: - args['overwrite'] = _dict.get('overwrite') + if (overwrite := _dict.get('overwrite')) is not None: + args['overwrite'] = overwrite return cls(**args) @classmethod @@ -6272,18 +6653,21 @@ def __ne__(self, other: 'DialogNodeOutputModifiers') -> bool: return not self == other -class DialogNodeOutputOptionsElement(): +class DialogNodeOutputOptionsElement: """ DialogNodeOutputOptionsElement. - :attr str label: The user-facing label for the option. - :attr DialogNodeOutputOptionsElementValue value: An object defining the message + :param str label: The user-facing label for the option. + :param DialogNodeOutputOptionsElementValue value: An object defining the message input to be sent to the Watson Assistant service if the user selects the corresponding option. """ - def __init__(self, label: str, - value: 'DialogNodeOutputOptionsElementValue') -> None: + def __init__( + self, + label: str, + value: 'DialogNodeOutputOptionsElementValue', + ) -> None: """ Initialize a DialogNodeOutputOptionsElement object. @@ -6299,15 +6683,14 @@ def __init__(self, label: str, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') + if (label := _dict.get('label')) is not None: + args['label'] = label else: raise ValueError( 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' ) - if 'value' in _dict: - args['value'] = DialogNodeOutputOptionsElementValue.from_dict( - _dict.get('value')) + if (value := _dict.get('value')) is not None: + args['value'] = DialogNodeOutputOptionsElementValue.from_dict(value) else: raise ValueError( 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' @@ -6350,28 +6733,30 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: return not self == other -class DialogNodeOutputOptionsElementValue(): +class DialogNodeOutputOptionsElementValue: """ An object defining the message input to be sent to the Watson Assistant service if the user selects the corresponding option. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. - :attr List[RuntimeIntent] intents: (optional) An array of intents to be used + :param List[RuntimeIntent] intents: (optional) An array of intents to be used while processing the input. **Note:** This property is supported for backward compatibility with applications that use the v1 **Get response to user input** method. - :attr List[RuntimeEntity] entities: (optional) An array of entities to be used + :param List[RuntimeEntity] entities: (optional) An array of entities to be used while processing the user input. **Note:** This property is supported for backward compatibility with applications that use the v1 **Get response to user input** method. """ - def __init__(self, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + ) -> None: """ Initialize a DialogNodeOutputOptionsElementValue object. @@ -6394,16 +6779,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] return cls(**args) @classmethod @@ -6456,16 +6837,20 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: return not self == other -class DialogNodeOutputTextValuesElement(): +class DialogNodeOutputTextValuesElement: """ DialogNodeOutputTextValuesElement. - :attr str text: (optional) The text of a response. This string can include + :param str text: (optional) The text of a response. This string can include newline characters (`\n`), Markdown tagging, or other special characters, if supported by the channel. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputTextValuesElement object. @@ -6479,8 +6864,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputTextValuesElement': """Initialize a DialogNodeOutputTextValuesElement object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -6514,21 +6899,23 @@ def __ne__(self, other: 'DialogNodeOutputTextValuesElement') -> bool: return not self == other -class DialogNodeVisitedDetails(): +class DialogNodeVisitedDetails: """ DialogNodeVisitedDetails. - :attr str dialog_node: (optional) The unique ID of a dialog node that was + :param str dialog_node: (optional) The unique ID of a dialog node that was triggered during processing of the input message. - :attr str title: (optional) The title of the dialog node. - :attr str conditions: (optional) The conditions that trigger the dialog node. + :param str title: (optional) The title of the dialog node. + :param str conditions: (optional) The conditions that trigger the dialog node. """ - def __init__(self, - *, - dialog_node: str = None, - title: str = None, - conditions: str = None) -> None: + def __init__( + self, + *, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + conditions: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeVisitedDetails object. @@ -6546,12 +6933,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeVisitedDetails': """Initialize a DialogNodeVisitedDetails object from a json dictionary.""" args = {} - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'conditions' in _dict: - args['conditions'] = _dict.get('conditions') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (conditions := _dict.get('conditions')) is not None: + args['conditions'] = conditions return cls(**args) @classmethod @@ -6589,32 +6976,34 @@ def __ne__(self, other: 'DialogNodeVisitedDetails') -> bool: return not self == other -class DialogSuggestion(): +class DialogSuggestion: """ DialogSuggestion. - :attr str label: The user-facing label for the disambiguation option. This label - is taken from the **title** or **user_label** property of the corresponding - dialog node. - :attr DialogSuggestionValue value: An object defining the message input, + :param str label: The user-facing label for the disambiguation option. This + label is taken from the **title** or **user_label** property of the + corresponding dialog node. + :param DialogSuggestionValue value: An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. **Note:** These properties must be included in the request body of the next message sent to the assistant. Do not modify or remove any of the included properties. - :attr dict output: (optional) The dialog output that will be returned from the + :param dict output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. - :attr str dialog_node: (optional) The unique ID of the dialog node that the + :param str dialog_node: (optional) The unique ID of the dialog node that the **label** property is taken from. The **label** property is populated using the value of the dialog node's **title** or **user_label** property. """ - def __init__(self, - label: str, - value: 'DialogSuggestionValue', - *, - output: dict = None, - dialog_node: str = None) -> None: + def __init__( + self, + label: str, + value: 'DialogSuggestionValue', + *, + output: Optional[dict] = None, + dialog_node: Optional[str] = None, + ) -> None: """ Initialize a DialogSuggestion object. @@ -6642,22 +7031,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') + if (label := _dict.get('label')) is not None: + args['label'] = label else: raise ValueError( 'Required property \'label\' not present in DialogSuggestion JSON' ) - if 'value' in _dict: - args['value'] = DialogSuggestionValue.from_dict(_dict.get('value')) + if (value := _dict.get('value')) is not None: + args['value'] = DialogSuggestionValue.from_dict(value) else: raise ValueError( 'Required property \'value\' not present in DialogSuggestion JSON' ) - if 'output' in _dict: - args['output'] = _dict.get('output') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (output := _dict.get('output')) is not None: + args['output'] = output + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node return cls(**args) @classmethod @@ -6700,26 +7089,28 @@ def __ne__(self, other: 'DialogSuggestion') -> bool: return not self == other -class DialogSuggestionValue(): +class DialogSuggestionValue: """ An object defining the message input, intents, and entities to be sent to the Watson Assistant service if the user selects the corresponding disambiguation option. **Note:** These properties must be included in the request body of the next message sent to the assistant. Do not modify or remove any of the included properties. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. - :attr List[RuntimeIntent] intents: (optional) An array of intents to be sent + :param List[RuntimeIntent] intents: (optional) An array of intents to be sent along with the user input. - :attr List[RuntimeEntity] entities: (optional) An array of entities to be sent + :param List[RuntimeEntity] entities: (optional) An array of entities to be sent along with the user input. """ - def __init__(self, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + ) -> None: """ Initialize a DialogSuggestionValue object. @@ -6738,16 +7129,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] return cls(**args) @classmethod @@ -6800,36 +7187,39 @@ def __ne__(self, other: 'DialogSuggestionValue') -> bool: return not self == other -class Entity(): +class Entity: """ Entity. - :attr str entity: The name of the entity. This string must conform to the + :param str entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity that you want to enable. (Any entity content specified with the request is ignored.). - :attr str description: (optional) The description of the entity. This string + :param str description: (optional) The description of the entity. This string cannot contain carriage return, newline, or tab characters. - :attr dict metadata: (optional) Any metadata related to the entity. - :attr bool fuzzy_match: (optional) Whether to use fuzzy matching for the entity. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param dict metadata: (optional) Any metadata related to the entity. + :param bool fuzzy_match: (optional) Whether to use fuzzy matching for the + entity. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[Value] values: (optional) An array of objects describing the entity + :param List[Value] values: (optional) An array of objects describing the entity values. """ - def __init__(self, - entity: str, - *, - description: str = None, - metadata: dict = None, - fuzzy_match: bool = None, - created: datetime = None, - updated: datetime = None, - values: List['Value'] = None) -> None: + def __init__( + self, + entity: str, + *, + description: Optional[str] = None, + metadata: Optional[dict] = None, + fuzzy_match: Optional[bool] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + values: Optional[List['Value']] = None, + ) -> None: """ Initialize a Entity object. @@ -6860,23 +7250,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Entity': """Initialize a Entity object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in Entity JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'fuzzy_match' in _dict: - args['fuzzy_match'] = _dict.get('fuzzy_match') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'values' in _dict: - args['values'] = [Value.from_dict(v) for v in _dict.get('values')] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (fuzzy_match := _dict.get('fuzzy_match')) is not None: + args['fuzzy_match'] = fuzzy_match + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (values := _dict.get('values')) is not None: + args['values'] = [Value.from_dict(v) for v in values] return cls(**args) @classmethod @@ -6928,18 +7318,21 @@ def __ne__(self, other: 'Entity') -> bool: return not self == other -class EntityCollection(): +class EntityCollection: """ An array of objects describing the entities for the workspace. - :attr List[Entity] entities: An array of objects describing the entities defined - for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. For + :param List[Entity] entities: An array of objects describing the entities + defined for the workspace. + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, entities: List['Entity'], - pagination: 'Pagination') -> None: + def __init__( + self, + entities: List['Entity'], + pagination: 'Pagination', + ) -> None: """ Initialize a EntityCollection object. @@ -6955,16 +7348,14 @@ def __init__(self, entities: List['Entity'], def from_dict(cls, _dict: Dict) -> 'EntityCollection': """Initialize a EntityCollection object from a json dictionary.""" args = {} - if 'entities' in _dict: - args['entities'] = [ - Entity.from_dict(v) for v in _dict.get('entities') - ] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [Entity.from_dict(v) for v in entities] else: raise ValueError( 'Required property \'entities\' not present in EntityCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in EntityCollection JSON' @@ -7013,17 +7404,22 @@ def __ne__(self, other: 'EntityCollection') -> bool: return not self == other -class EntityMention(): +class EntityMention: """ An object describing a contextual entity mention. - :attr str text: The text of the user input example. - :attr str intent: The name of the intent. - :attr List[int] location: An array of zero-based character offsets that indicate - where the entity mentions begin and end in the input text. + :param str text: The text of the user input example. + :param str intent: The name of the intent. + :param List[int] location: An array of zero-based character offsets that + indicate where the entity mentions begin and end in the input text. """ - def __init__(self, text: str, intent: str, location: List[int]) -> None: + def __init__( + self, + text: str, + intent: str, + location: List[int], + ) -> None: """ Initialize a EntityMention object. @@ -7040,19 +7436,19 @@ def __init__(self, text: str, intent: str, location: List[int]) -> None: def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in EntityMention JSON') - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in EntityMention JSON' ) - if 'location' in _dict: - args['location'] = _dict.get('location') + if (location := _dict.get('location')) is not None: + args['location'] = location else: raise ValueError( 'Required property \'location\' not present in EntityMention JSON' @@ -7094,18 +7490,21 @@ def __ne__(self, other: 'EntityMention') -> bool: return not self == other -class EntityMentionCollection(): +class EntityMentionCollection: """ EntityMentionCollection. - :attr List[EntityMention] examples: An array of objects describing the entity + :param List[EntityMention] examples: An array of objects describing the entity mentions defined for an entity. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, examples: List['EntityMention'], - pagination: 'Pagination') -> None: + def __init__( + self, + examples: List['EntityMention'], + pagination: 'Pagination', + ) -> None: """ Initialize a EntityMentionCollection object. @@ -7121,16 +7520,14 @@ def __init__(self, examples: List['EntityMention'], def from_dict(cls, _dict: Dict) -> 'EntityMentionCollection': """Initialize a EntityMentionCollection object from a json dictionary.""" args = {} - if 'examples' in _dict: - args['examples'] = [ - EntityMention.from_dict(v) for v in _dict.get('examples') - ] + if (examples := _dict.get('examples')) is not None: + args['examples'] = [EntityMention.from_dict(v) for v in examples] else: raise ValueError( 'Required property \'examples\' not present in EntityMentionCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in EntityMentionCollection JSON' @@ -7179,26 +7576,29 @@ def __ne__(self, other: 'EntityMentionCollection') -> bool: return not self == other -class Example(): +class Example: """ Example. - :attr str text: The text of a user input example. This string must conform to + :param str text: The text of a user input example. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr List[Mention] mentions: (optional) An array of contextual entity mentions. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param List[Mention] mentions: (optional) An array of contextual entity + mentions. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - text: str, - *, - mentions: List['Mention'] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + text: str, + *, + mentions: Optional[List['Mention']] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Example object. @@ -7218,19 +7618,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Example': """Initialize a Example object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in Example JSON') - if 'mentions' in _dict: - args['mentions'] = [ - Mention.from_dict(v) for v in _dict.get('mentions') - ] - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (mentions := _dict.get('mentions')) is not None: + args['mentions'] = [Mention.from_dict(v) for v in mentions] + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -7276,18 +7674,21 @@ def __ne__(self, other: 'Example') -> bool: return not self == other -class ExampleCollection(): +class ExampleCollection: """ ExampleCollection. - :attr List[Example] examples: An array of objects describing the examples + :param List[Example] examples: An array of objects describing the examples defined for the intent. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, examples: List['Example'], - pagination: 'Pagination') -> None: + def __init__( + self, + examples: List['Example'], + pagination: 'Pagination', + ) -> None: """ Initialize a ExampleCollection object. @@ -7303,16 +7704,14 @@ def __init__(self, examples: List['Example'], def from_dict(cls, _dict: Dict) -> 'ExampleCollection': """Initialize a ExampleCollection object from a json dictionary.""" args = {} - if 'examples' in _dict: - args['examples'] = [ - Example.from_dict(v) for v in _dict.get('examples') - ] + if (examples := _dict.get('examples')) is not None: + args['examples'] = [Example.from_dict(v) for v in examples] else: raise ValueError( 'Required property \'examples\' not present in ExampleCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in ExampleCollection JSON' @@ -7361,31 +7760,33 @@ def __ne__(self, other: 'ExampleCollection') -> bool: return not self == other -class Intent(): +class Intent: """ Intent. - :attr str intent: The name of the intent. This string must conform to the + :param str intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - :attr str description: (optional) The description of the intent. This string + :param str description: (optional) The description of the intent. This string cannot contain carriage return, newline, or tab characters. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr List[Example] examples: (optional) An array of user input examples for the - intent. + :param List[Example] examples: (optional) An array of user input examples for + the intent. """ - def __init__(self, - intent: str, - *, - description: str = None, - created: datetime = None, - updated: datetime = None, - examples: List['Example'] = None) -> None: + def __init__( + self, + intent: str, + *, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + examples: Optional[List['Example']] = None, + ) -> None: """ Initialize a Intent object. @@ -7409,21 +7810,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Intent': """Initialize a Intent object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in Intent JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'examples' in _dict: - args['examples'] = [ - Example.from_dict(v) for v in _dict.get('examples') - ] + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (examples := _dict.get('examples')) is not None: + args['examples'] = [Example.from_dict(v) for v in examples] return cls(**args) @classmethod @@ -7471,18 +7870,21 @@ def __ne__(self, other: 'Intent') -> bool: return not self == other -class IntentCollection(): +class IntentCollection: """ IntentCollection. - :attr List[Intent] intents: An array of objects describing the intents defined + :param List[Intent] intents: An array of objects describing the intents defined for the workspace. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, intents: List['Intent'], - pagination: 'Pagination') -> None: + def __init__( + self, + intents: List['Intent'], + pagination: 'Pagination', + ) -> None: """ Initialize a IntentCollection object. @@ -7498,16 +7900,14 @@ def __init__(self, intents: List['Intent'], def from_dict(cls, _dict: Dict) -> 'IntentCollection': """Initialize a IntentCollection object from a json dictionary.""" args = {} - if 'intents' in _dict: - args['intents'] = [ - Intent.from_dict(v) for v in _dict.get('intents') - ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [Intent.from_dict(v) for v in intents] else: raise ValueError( 'Required property \'intents\' not present in IntentCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in IntentCollection JSON' @@ -7556,27 +7956,34 @@ def __ne__(self, other: 'IntentCollection') -> bool: return not self == other -class Log(): +class Log: """ Log. - :attr MessageRequest request: A request sent to the workspace, including the + :param MessageRequest request: A request sent to the workspace, including the user input and context. - :attr MessageResponse response: The response sent by the workspace, including + :param MessageResponse response: The response sent by the workspace, including the output text, detected intents and entities, and context. - :attr str log_id: A unique identifier for the logged event. - :attr str request_timestamp: The timestamp for receipt of the message. - :attr str response_timestamp: The timestamp for the system response to the + :param str log_id: A unique identifier for the logged event. + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the message. - :attr str workspace_id: The unique identifier of the workspace where the request - was made. - :attr str language: The language of the workspace where the message request was + :param str workspace_id: The unique identifier of the workspace where the + request was made. + :param str language: The language of the workspace where the message request was made. """ - def __init__(self, request: 'MessageRequest', response: 'MessageResponse', - log_id: str, request_timestamp: str, response_timestamp: str, - workspace_id: str, language: str) -> None: + def __init__( + self, + request: 'MessageRequest', + response: 'MessageResponse', + log_id: str, + request_timestamp: str, + response_timestamp: str, + workspace_id: str, + language: str, + ) -> None: """ Initialize a Log object. @@ -7605,40 +8012,40 @@ def __init__(self, request: 'MessageRequest', response: 'MessageResponse', def from_dict(cls, _dict: Dict) -> 'Log': """Initialize a Log object from a json dictionary.""" args = {} - if 'request' in _dict: - args['request'] = MessageRequest.from_dict(_dict.get('request')) + if (request := _dict.get('request')) is not None: + args['request'] = MessageRequest.from_dict(request) else: raise ValueError( 'Required property \'request\' not present in Log JSON') - if 'response' in _dict: - args['response'] = MessageResponse.from_dict(_dict.get('response')) + if (response := _dict.get('response')) is not None: + args['response'] = MessageResponse.from_dict(response) else: raise ValueError( 'Required property \'response\' not present in Log JSON') - if 'log_id' in _dict: - args['log_id'] = _dict.get('log_id') + if (log_id := _dict.get('log_id')) is not None: + args['log_id'] = log_id else: raise ValueError( 'Required property \'log_id\' not present in Log JSON') - if 'request_timestamp' in _dict: - args['request_timestamp'] = _dict.get('request_timestamp') + if (request_timestamp := _dict.get('request_timestamp')) is not None: + args['request_timestamp'] = request_timestamp else: raise ValueError( 'Required property \'request_timestamp\' not present in Log JSON' ) - if 'response_timestamp' in _dict: - args['response_timestamp'] = _dict.get('response_timestamp') + if (response_timestamp := _dict.get('response_timestamp')) is not None: + args['response_timestamp'] = response_timestamp else: raise ValueError( 'Required property \'response_timestamp\' not present in Log JSON' ) - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id else: raise ValueError( 'Required property \'workspace_id\' not present in Log JSON') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Log JSON') @@ -7696,16 +8103,20 @@ def __ne__(self, other: 'Log') -> bool: return not self == other -class LogCollection(): +class LogCollection: """ LogCollection. - :attr List[Log] logs: An array of objects describing log events. - :attr LogPagination pagination: The pagination data for the returned objects. + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: + def __init__( + self, + logs: List['Log'], + pagination: 'LogPagination', + ) -> None: """ Initialize a LogCollection object. @@ -7721,14 +8132,13 @@ def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} - if 'logs' in _dict: - args['logs'] = [Log.from_dict(v) for v in _dict.get('logs')] + if (logs := _dict.get('logs')) is not None: + args['logs'] = [Log.from_dict(v) for v in logs] else: raise ValueError( 'Required property \'logs\' not present in LogCollection JSON') - if 'pagination' in _dict: - args['pagination'] = LogPagination.from_dict( - _dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = LogPagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in LogCollection JSON' @@ -7777,24 +8187,26 @@ def __ne__(self, other: 'LogCollection') -> bool: return not self == other -class LogMessage(): +class LogMessage: """ Log message details. - :attr str level: The severity of the log message. - :attr str msg: The text of the log message. - :attr str code: A code that indicates the category to which the error message + :param str level: The severity of the log message. + :param str msg: The text of the log message. + :param str code: A code that indicates the category to which the error message belongs. - :attr LogMessageSource source: (optional) An object that identifies the dialog + :param LogMessageSource source: (optional) An object that identifies the dialog element that generated the error message. """ - def __init__(self, - level: str, - msg: str, - code: str, - *, - source: 'LogMessageSource' = None) -> None: + def __init__( + self, + level: str, + msg: str, + code: str, + *, + source: Optional['LogMessageSource'] = None, + ) -> None: """ Initialize a LogMessage object. @@ -7814,23 +8226,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogMessage': """Initialize a LogMessage object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') + if (level := _dict.get('level')) is not None: + args['level'] = level else: raise ValueError( 'Required property \'level\' not present in LogMessage JSON') - if 'msg' in _dict: - args['msg'] = _dict.get('msg') + if (msg := _dict.get('msg')) is not None: + args['msg'] = msg else: raise ValueError( 'Required property \'msg\' not present in LogMessage JSON') - if 'code' in _dict: - args['code'] = _dict.get('code') + if (code := _dict.get('code')) is not None: + args['code'] = code else: raise ValueError( 'Required property \'code\' not present in LogMessage JSON') - if 'source' in _dict: - args['source'] = LogMessageSource.from_dict(_dict.get('source')) + if (source := _dict.get('source')) is not None: + args['source'] = LogMessageSource.from_dict(source) return cls(**args) @classmethod @@ -7876,22 +8288,28 @@ class LevelEnum(str, Enum): """ The severity of the log message. """ + INFO = 'info' ERROR = 'error' WARN = 'warn' -class LogMessageSource(): +class LogMessageSource: """ An object that identifies the dialog element that generated the error message. - :attr str type: (optional) A string that indicates the type of dialog element + :param str type: (optional) A string that indicates the type of dialog element that generated the error message. - :attr str dialog_node: (optional) The unique identifier of the dialog node that + :param str dialog_node: (optional) The unique identifier of the dialog node that generated the error message. """ - def __init__(self, *, type: str = None, dialog_node: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + dialog_node: Optional[str] = None, + ) -> None: """ Initialize a LogMessageSource object. @@ -7907,10 +8325,10 @@ def __init__(self, *, type: str = None, dialog_node: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'LogMessageSource': """Initialize a LogMessageSource object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node return cls(**args) @classmethod @@ -7950,25 +8368,28 @@ class TypeEnum(str, Enum): A string that indicates the type of dialog element that generated the error message. """ + DIALOG_NODE = 'dialog_node' -class LogPagination(): +class LogPagination: """ The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). - :attr str next_url: (optional) The URL that will return the next page of + :param str next_url: (optional) The URL that will return the next page of results, if any. - :attr int matched: (optional) Reserved for future use. - :attr str next_cursor: (optional) A token identifying the next page of results. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, - *, - next_url: str = None, - matched: int = None, - next_cursor: str = None) -> None: + def __init__( + self, + *, + next_url: Optional[str] = None, + matched: Optional[int] = None, + next_cursor: Optional[str] = None, + ) -> None: """ Initialize a LogPagination object. @@ -7986,12 +8407,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogPagination': """Initialize a LogPagination object from a json dictionary.""" args = {} - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod @@ -8029,16 +8450,20 @@ def __ne__(self, other: 'LogPagination') -> bool: return not self == other -class Mention(): +class Mention: """ A mention of a contextual entity. - :attr str entity: The name of the entity. - :attr List[int] location: An array of zero-based character offsets that indicate - where the entity mentions begin and end in the input text. + :param str entity: The name of the entity. + :param List[int] location: An array of zero-based character offsets that + indicate where the entity mentions begin and end in the input text. """ - def __init__(self, entity: str, location: List[int]) -> None: + def __init__( + self, + entity: str, + location: List[int], + ) -> None: """ Initialize a Mention object. @@ -8053,13 +8478,13 @@ def __init__(self, entity: str, location: List[int]) -> None: def from_dict(cls, _dict: Dict) -> 'Mention': """Initialize a Mention object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in Mention JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (location := _dict.get('location')) is not None: + args['location'] = location else: raise ValueError( 'Required property \'location\' not present in Mention JSON') @@ -8098,14 +8523,14 @@ def __ne__(self, other: 'Mention') -> bool: return not self == other -class MessageContextMetadata(): +class MessageContextMetadata: """ Metadata related to the message. - :attr str deployment: (optional) A label identifying the deployment environment, - used for filtering log data. This string cannot contain carriage return, - newline, or tab characters. - :attr str user_id: (optional) A string value that identifies the user who is + :param str deployment: (optional) A label identifying the deployment + environment, used for filtering log data. This string cannot contain carriage + return, newline, or tab characters. + :param str user_id: (optional) A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -8117,7 +8542,12 @@ class MessageContextMetadata(): request, the value specified at the root is used. """ - def __init__(self, *, deployment: str = None, user_id: str = None) -> None: + def __init__( + self, + *, + deployment: Optional[str] = None, + user_id: Optional[str] = None, + ) -> None: """ Initialize a MessageContextMetadata object. @@ -8142,10 +8572,10 @@ def __init__(self, *, deployment: str = None, user_id: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'MessageContextMetadata': """Initialize a MessageContextMetadata object from a json dictionary.""" args = {} - if 'deployment' in _dict: - args['deployment'] = _dict.get('deployment') - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (deployment := _dict.get('deployment')) is not None: + args['deployment'] = deployment + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod @@ -8181,16 +8611,16 @@ def __ne__(self, other: 'MessageContextMetadata') -> bool: return not self == other -class MessageInput(): +class MessageInput: """ An input object that includes the input text. - :attr str text: (optional) The text of the user input. This string cannot + :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. - :attr bool spelling_suggestions: (optional) Whether to use spelling correction + :param bool spelling_suggestions: (optional) Whether to use spelling correction when processing the input. This property overrides the value of the **spelling_suggestions** property in the workspace settings. - :attr bool spelling_auto_correct: (optional) Whether to use autocorrection when + :param bool spelling_auto_correct: (optional) Whether to use autocorrection when processing the input. If spelling correction is used and this property is `false`, any suggested corrections are returned in the **suggested_text** property of the message response. If this property is `true`, any corrections @@ -8198,10 +8628,10 @@ class MessageInput(): in the **original_text** property of the message response. This property overrides the value of the **spelling_auto_correct** property in the workspace settings. - :attr str suggested_text: (optional) Any suggested corrections of the input + :param str suggested_text: (optional) Any suggested corrections of the input text. This property is returned only if spelling correction is enabled and autocorrection is disabled. - :attr str original_text: (optional) The original user input text. This property + :param str original_text: (optional) The original user input text. This property is returned only if autocorrection is enabled and the user input was corrected. """ @@ -8211,14 +8641,16 @@ class MessageInput(): 'suggested_text', 'original_text' ]) - def __init__(self, - *, - text: str = None, - spelling_suggestions: bool = None, - spelling_auto_correct: bool = None, - suggested_text: str = None, - original_text: str = None, - **kwargs) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + spelling_suggestions: Optional[bool] = None, + spelling_auto_correct: Optional[bool] = None, + suggested_text: Optional[str] = None, + original_text: Optional[str] = None, + **kwargs, + ) -> None: """ Initialize a MessageInput object. @@ -8249,16 +8681,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'spelling_auto_correct' in _dict: - args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') - if 'suggested_text' in _dict: - args['suggested_text'] = _dict.get('suggested_text') - if 'original_text' in _dict: - args['original_text'] = _dict.get('original_text') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (spelling_suggestions := + _dict.get('spelling_suggestions')) is not None: + args['spelling_suggestions'] = spelling_suggestions + if (spelling_auto_correct := + _dict.get('spelling_auto_correct')) is not None: + args['spelling_auto_correct'] = spelling_auto_correct + if (suggested_text := _dict.get('suggested_text')) is not None: + args['suggested_text'] = suggested_text + if (original_text := _dict.get('original_text')) is not None: + args['original_text'] = original_text args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -8334,27 +8768,27 @@ def __ne__(self, other: 'MessageInput') -> bool: return not self == other -class MessageRequest(): +class MessageRequest: """ A request sent to the workspace, including the user input and context. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - A value of `true` indicates that all matching intents are returned. - :attr Context context: (optional) State information for the conversation. To + :param bool alternate_intents: (optional) Whether to return more than one + intent. A value of `true` indicates that all matching intents are returned. + :param Context context: (optional) State information for the conversation. To maintain state, include the context from the previous response. - :attr OutputData output: (optional) An output object that includes the response + :param OutputData output: (optional) An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. - :attr str user_id: (optional) A string value that identifies the user who is + :param str user_id: (optional) A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -8366,16 +8800,18 @@ class MessageRequest(): the value specified at the root is used. """ - def __init__(self, - *, - input: 'MessageInput' = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - alternate_intents: bool = None, - context: 'Context' = None, - output: 'OutputData' = None, - actions: List['DialogNodeAction'] = None, - user_id: str = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + alternate_intents: Optional[bool] = None, + context: Optional['Context'] = None, + output: Optional['OutputData'] = None, + actions: Optional[List['DialogNodeAction']] = None, + user_id: Optional[str] = None, + ) -> None: """ Initialize a MessageRequest object. @@ -8420,28 +8856,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageRequest': """Initialize a MessageRequest object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'context' in _dict: - args['context'] = Context.from_dict(_dict.get('context')) - if 'output' in _dict: - args['output'] = OutputData.from_dict(_dict.get('output')) - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(v) for v in _dict.get('actions') - ] - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (context := _dict.get('context')) is not None: + args['context'] = Context.from_dict(context) + if (output := _dict.get('output')) is not None: + args['output'] = OutputData.from_dict(output) + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod @@ -8517,25 +8947,25 @@ def __ne__(self, other: 'MessageRequest') -> bool: return not self == other -class MessageResponse(): +class MessageResponse: """ The response sent by the workspace, including the output text, detected intents and entities, and context. - :attr MessageInput input: An input object that includes the input text. - :attr List[RuntimeIntent] intents: An array of intents recognized in the user + :param MessageInput input: An input object that includes the input text. + :param List[RuntimeIntent] intents: An array of intents recognized in the user input, sorted in descending order of confidence. - :attr List[RuntimeEntity] entities: An array of entities identified in the user + :param List[RuntimeEntity] entities: An array of entities identified in the user input. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - A value of `true` indicates that all matching intents are returned. - :attr Context context: State information for the conversation. To maintain + :param bool alternate_intents: (optional) Whether to return more than one + intent. A value of `true` indicates that all matching intents are returned. + :param Context context: State information for the conversation. To maintain state, include the context from the previous response. - :attr OutputData output: An output object that includes the response to the + :param OutputData output: An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. - :attr str user_id: A string value that identifies the user who is interacting + :param str user_id: A string value that identifies the user who is interacting with the workspace. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -8547,16 +8977,18 @@ class MessageResponse(): the value specified at the root is used. """ - def __init__(self, - input: 'MessageInput', - intents: List['RuntimeIntent'], - entities: List['RuntimeEntity'], - context: 'Context', - output: 'OutputData', - user_id: str, - *, - alternate_intents: bool = None, - actions: List['DialogNodeAction'] = None) -> None: + def __init__( + self, + input: 'MessageInput', + intents: List['RuntimeIntent'], + entities: List['RuntimeEntity'], + context: 'Context', + output: 'OutputData', + user_id: str, + *, + alternate_intents: Optional[bool] = None, + actions: Optional[List['DialogNodeAction']] = None, + ) -> None: """ Initialize a MessageResponse object. @@ -8595,48 +9027,42 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageResponse': """Initialize a MessageResponse object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) else: raise ValueError( 'Required property \'input\' not present in MessageResponse JSON' ) - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] else: raise ValueError( 'Required property \'intents\' not present in MessageResponse JSON' ) - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] else: raise ValueError( 'Required property \'entities\' not present in MessageResponse JSON' ) - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'context' in _dict: - args['context'] = Context.from_dict(_dict.get('context')) + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (context := _dict.get('context')) is not None: + args['context'] = Context.from_dict(context) else: raise ValueError( 'Required property \'context\' not present in MessageResponse JSON' ) - if 'output' in _dict: - args['output'] = OutputData.from_dict(_dict.get('output')) + if (output := _dict.get('output')) is not None: + args['output'] = OutputData.from_dict(output) else: raise ValueError( 'Required property \'output\' not present in MessageResponse JSON' ) - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(v) for v in _dict.get('actions') - ] - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id else: raise ValueError( 'Required property \'user_id\' not present in MessageResponse JSON' @@ -8716,22 +9142,22 @@ def __ne__(self, other: 'MessageResponse') -> bool: return not self == other -class OutputData(): +class OutputData: """ An output object that includes the response to the user, the dialog nodes that were triggered, and messages from the log. - :attr List[str] nodes_visited: (optional) An array of the nodes that were + :param List[str] nodes_visited: (optional) An array of the nodes that were triggered to create the response, in the order in which they were visited. This information is useful for debugging and for tracing the path taken through the node tree. - :attr List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array + :param List[DialogNodeVisitedDetails] nodes_visited_details: (optional) An array of objects containing detailed diagnostic information about the nodes that were triggered during processing of the input message. Included only if **nodes_visited_details** is set to `true` in the message request. - :attr List[LogMessage] log_messages: An array of up to 50 messages logged with + :param List[LogMessage] log_messages: An array of up to 50 messages logged with the request. - :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. """ @@ -8740,13 +9166,16 @@ class OutputData(): _properties = frozenset( ['nodes_visited', 'nodes_visited_details', 'log_messages', 'generic']) - def __init__(self, - log_messages: List['LogMessage'], - *, - nodes_visited: List[str] = None, - nodes_visited_details: List['DialogNodeVisitedDetails'] = None, - generic: List['RuntimeResponseGeneric'] = None, - **kwargs) -> None: + def __init__( + self, + log_messages: List['LogMessage'], + *, + nodes_visited: Optional[List[str]] = None, + nodes_visited_details: Optional[ + List['DialogNodeVisitedDetails']] = None, + generic: Optional[List['RuntimeResponseGeneric']] = None, + **kwargs, + ) -> None: """ Initialize a OutputData object. @@ -8776,25 +9205,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'OutputData': """Initialize a OutputData object from a json dictionary.""" args = {} - if 'nodes_visited' in _dict: - args['nodes_visited'] = _dict.get('nodes_visited') - if 'nodes_visited_details' in _dict: + if (nodes_visited := _dict.get('nodes_visited')) is not None: + args['nodes_visited'] = nodes_visited + if (nodes_visited_details := + _dict.get('nodes_visited_details')) is not None: args['nodes_visited_details'] = [ DialogNodeVisitedDetails.from_dict(v) - for v in _dict.get('nodes_visited_details') + for v in nodes_visited_details ] - if 'log_messages' in _dict: + if (log_messages := _dict.get('log_messages')) is not None: args['log_messages'] = [ - LogMessage.from_dict(v) for v in _dict.get('log_messages') + LogMessage.from_dict(v) for v in log_messages ] else: raise ValueError( 'Required property \'log_messages\' not present in OutputData JSON' ) - if 'generic' in _dict: + if (generic := _dict.get('generic')) is not None: args['generic'] = [ - RuntimeResponseGeneric.from_dict(v) - for v in _dict.get('generic') + RuntimeResponseGeneric.from_dict(v) for v in generic ] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) @@ -8881,31 +9310,33 @@ def __ne__(self, other: 'OutputData') -> bool: return not self == other -class Pagination(): +class Pagination: """ The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). - :attr str refresh_url: The URL that will return the same page of results. - :attr str next_url: (optional) The URL that will return the next page of + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of results. - :attr int total: (optional) The total number of objects that satisfy the + :param int total: (optional) The total number of objects that satisfy the request. This total includes all results, not just those included in the current page. - :attr int matched: (optional) Reserved for future use. - :attr str refresh_cursor: (optional) A token identifying the current page of + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page of results. - :attr str next_cursor: (optional) A token identifying the next page of results. + :param str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, - refresh_url: str, - *, - next_url: str = None, - total: int = None, - matched: int = None, - refresh_cursor: str = None, - next_cursor: str = None) -> None: + def __init__( + self, + refresh_url: str, + *, + next_url: Optional[str] = None, + total: Optional[int] = None, + matched: Optional[int] = None, + refresh_cursor: Optional[str] = None, + next_cursor: Optional[str] = None, + ) -> None: """ Initialize a Pagination object. @@ -8932,22 +9363,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Pagination': """Initialize a Pagination object from a json dictionary.""" args = {} - if 'refresh_url' in _dict: - args['refresh_url'] = _dict.get('refresh_url') + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url else: raise ValueError( 'Required property \'refresh_url\' not present in Pagination JSON' ) - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'total' in _dict: - args['total'] = _dict.get('total') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'refresh_cursor' in _dict: - args['refresh_cursor'] = _dict.get('refresh_cursor') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (total := _dict.get('total')) is not None: + args['total'] = total + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (refresh_cursor := _dict.get('refresh_cursor')) is not None: + args['refresh_cursor'] = refresh_cursor + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod @@ -8991,15 +9422,19 @@ def __ne__(self, other: 'Pagination') -> bool: return not self == other -class ResponseGenericChannel(): +class ResponseGenericChannel: """ ResponseGenericChannel. - :attr str channel: (optional) A channel for which the response is intended. + :param str channel: (optional) A channel for which the response is intended. **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ - def __init__(self, *, channel: str = None) -> None: + def __init__( + self, + *, + channel: Optional[str] = None, + ) -> None: """ Initialize a ResponseGenericChannel object. @@ -9013,8 +9448,8 @@ def __init__(self, *, channel: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': """Initialize a ResponseGenericChannel object from a json dictionary.""" args = {} - if 'channel' in _dict: - args['channel'] = _dict.get('channel') + if (channel := _dict.get('channel')) is not None: + args['channel'] = channel return cls(**args) @classmethod @@ -9052,6 +9487,7 @@ class ChannelEnum(str, Enum): A channel for which the response is intended. **Note:** On IBM Cloud Pak for Data, only `chat` is supported. """ + CHAT = 'chat' FACEBOOK = 'facebook' INTERCOM = 'intercom' @@ -9061,44 +9497,46 @@ class ChannelEnum(str, Enum): WHATSAPP = 'whatsapp' -class RuntimeEntity(): +class RuntimeEntity: """ A term from the request that was identified as an entity. - :attr str entity: An entity detected in the input. - :attr List[int] location: (optional) An array of zero-based character offsets + :param str entity: An entity detected in the input. + :param List[int] location: (optional) An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. - :attr str value: 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. - :attr List[CaptureGroup] groups: (optional) The recognized capture groups for + :param str value: 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. + :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. - :attr RuntimeEntityInterpretation interpretation: (optional) An object + :param RuntimeEntityInterpretation interpretation: (optional) An object containing detailed information about the entity recognized in the user input. For more information about how system entities are interpreted, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-system-entities). - :attr List[RuntimeEntityAlternative] alternatives: (optional) An array of + :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 workspace. - :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 + :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. """ - def __init__(self, - entity: str, - value: str, - *, - location: List[int] = None, - confidence: float = None, - groups: List['CaptureGroup'] = None, - interpretation: 'RuntimeEntityInterpretation' = None, - alternatives: List['RuntimeEntityAlternative'] = None, - role: 'RuntimeEntityRole' = None) -> None: + def __init__( + self, + entity: str, + value: str, + *, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + groups: Optional[List['CaptureGroup']] = None, + interpretation: Optional['RuntimeEntityInterpretation'] = None, + alternatives: Optional[List['RuntimeEntityAlternative']] = None, + role: Optional['RuntimeEntityRole'] = None, + ) -> None: """ Initialize a RuntimeEntity object. @@ -9141,35 +9579,32 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in RuntimeEntity JSON' ) - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'value' in _dict: - args['value'] = _dict.get('value') + if (location := _dict.get('location')) is not None: + args['location'] = location + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in RuntimeEntity JSON') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'groups' in _dict: - args['groups'] = [ - CaptureGroup.from_dict(v) for v in _dict.get('groups') - ] - if 'interpretation' in _dict: + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (groups := _dict.get('groups')) is not None: + args['groups'] = [CaptureGroup.from_dict(v) for v in groups] + if (interpretation := _dict.get('interpretation')) is not None: args['interpretation'] = RuntimeEntityInterpretation.from_dict( - _dict.get('interpretation')) - if 'alternatives' in _dict: + interpretation) + if (alternatives := _dict.get('alternatives')) is not None: args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(v) - for v in _dict.get('alternatives') + RuntimeEntityAlternative.from_dict(v) for v in alternatives ] - if 'role' in _dict: - args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) + if (role := _dict.get('role')) is not None: + args['role'] = RuntimeEntityRole.from_dict(role) return cls(**args) @classmethod @@ -9235,17 +9670,22 @@ def __ne__(self, other: 'RuntimeEntity') -> bool: return not self == other -class RuntimeEntityAlternative(): +class RuntimeEntityAlternative: """ An alternative value for the recognized entity. - :attr str value: (optional) The entity value that was recognized in the user + :param 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. + :param 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: + def __init__( + self, + *, + value: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a RuntimeEntityAlternative object. @@ -9261,10 +9701,10 @@ def __init__(self, *, value: str = None, confidence: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': """Initialize a RuntimeEntityAlternative object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (value := _dict.get('value')) is not None: + args['value'] = value + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -9300,108 +9740,110 @@ def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: return not self == other -class RuntimeEntityInterpretation(): +class RuntimeEntityInterpretation: """ RuntimeEntityInterpretation. - :attr str calendar_type: (optional) The calendar used to represent a recognized + :param 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 + :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). - :attr str festival: (optional) A locale-specific holiday name (such as + :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. - :attr str granularity: (optional) The precision or duration of a time range + :param 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 + :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`). - :attr str range_modifier: (optional) The word in the user input that indicates + :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`). - :attr float relative_day: (optional) A recognized mention of a relative day, + :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`). - :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, + :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). - :attr float relative_weekend: (optional) A recognized mention of a relative date - range for a weekend, represented numerically as an offset from the current + :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`). - :attr float relative_year: (optional) A recognized mention of a relative year, + :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`). - :attr float specific_day: (optional) A recognized mention of a specific date, + :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`.). - :attr str specific_day_of_week: (optional) A recognized mention of a specific + :param 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 + :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`). - :attr float specific_year: (optional) A recognized mention of a specific year + :param 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 + :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`). - :attr str part_of_day: (optional) A recognized term for a time that was + :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`). - :attr float relative_hour: (optional) A recognized mention of a relative hour, + :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`). - :attr float relative_minute: (optional) A recognized mention of a relative time, - represented numerically as an offset in minutes from the current time (for + :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`). - :attr float relative_second: (optional) A recognized mention of a relative time, - represented numerically as an offset in seconds from the current time (for + :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`). - :attr float specific_hour: (optional) A recognized specific hour mentioned as + :param 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 + :param 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 + :param 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 + :param 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: + def __init__( + self, + *, + calendar_type: Optional[str] = None, + datetime_link: Optional[str] = None, + festival: Optional[str] = None, + granularity: Optional[str] = None, + range_link: Optional[str] = None, + range_modifier: Optional[str] = None, + relative_day: Optional[float] = None, + relative_month: Optional[float] = None, + relative_week: Optional[float] = None, + relative_weekend: Optional[float] = None, + relative_year: Optional[float] = None, + specific_day: Optional[float] = None, + specific_day_of_week: Optional[str] = None, + specific_month: Optional[float] = None, + specific_quarter: Optional[float] = None, + specific_year: Optional[float] = None, + numeric_value: Optional[float] = None, + subtype: Optional[str] = None, + part_of_day: Optional[str] = None, + relative_hour: Optional[float] = None, + relative_minute: Optional[float] = None, + relative_second: Optional[float] = None, + specific_hour: Optional[float] = None, + specific_minute: Optional[float] = None, + specific_second: Optional[float] = None, + timezone: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntityInterpretation object. @@ -9510,58 +9952,59 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" args = {} - 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') + if (calendar_type := _dict.get('calendar_type')) is not None: + args['calendar_type'] = calendar_type + if (datetime_link := _dict.get('datetime_link')) is not None: + args['datetime_link'] = datetime_link + if (festival := _dict.get('festival')) is not None: + args['festival'] = festival + if (granularity := _dict.get('granularity')) is not None: + args['granularity'] = granularity + if (range_link := _dict.get('range_link')) is not None: + args['range_link'] = range_link + if (range_modifier := _dict.get('range_modifier')) is not None: + args['range_modifier'] = range_modifier + if (relative_day := _dict.get('relative_day')) is not None: + args['relative_day'] = relative_day + if (relative_month := _dict.get('relative_month')) is not None: + args['relative_month'] = relative_month + if (relative_week := _dict.get('relative_week')) is not None: + args['relative_week'] = relative_week + if (relative_weekend := _dict.get('relative_weekend')) is not None: + args['relative_weekend'] = relative_weekend + if (relative_year := _dict.get('relative_year')) is not None: + args['relative_year'] = relative_year + if (specific_day := _dict.get('specific_day')) is not None: + args['specific_day'] = specific_day + if (specific_day_of_week := + _dict.get('specific_day_of_week')) is not None: + args['specific_day_of_week'] = specific_day_of_week + if (specific_month := _dict.get('specific_month')) is not None: + args['specific_month'] = specific_month + if (specific_quarter := _dict.get('specific_quarter')) is not None: + args['specific_quarter'] = specific_quarter + if (specific_year := _dict.get('specific_year')) is not None: + args['specific_year'] = specific_year + if (numeric_value := _dict.get('numeric_value')) is not None: + args['numeric_value'] = numeric_value + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype + if (part_of_day := _dict.get('part_of_day')) is not None: + args['part_of_day'] = part_of_day + if (relative_hour := _dict.get('relative_hour')) is not None: + args['relative_hour'] = relative_hour + if (relative_minute := _dict.get('relative_minute')) is not None: + args['relative_minute'] = relative_minute + if (relative_second := _dict.get('relative_second')) is not None: + args['relative_second'] = relative_second + if (specific_hour := _dict.get('specific_hour')) is not None: + args['specific_hour'] = specific_hour + if (specific_minute := _dict.get('specific_minute')) is not None: + args['specific_minute'] = specific_minute + if (specific_second := _dict.get('specific_second')) is not None: + args['specific_second'] = specific_second + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone return cls(**args) @classmethod @@ -9656,6 +10099,7 @@ class GranularityEnum(str, 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' @@ -9669,16 +10113,20 @@ class GranularityEnum(str, Enum): YEAR = 'year' -class RuntimeEntityRole(): +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. + :param str type: (optional) The relationship of the entity to the range. """ - def __init__(self, *, type: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntityRole object. @@ -9690,8 +10138,8 @@ def __init__(self, *, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': """Initialize a RuntimeEntityRole object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -9728,6 +10176,7 @@ class TypeEnum(str, Enum): """ The relationship of the entity to the range. """ + DATE_FROM = 'date_from' DATE_TO = 'date_to' NUMBER_FROM = 'number_from' @@ -9736,17 +10185,22 @@ class TypeEnum(str, Enum): TIME_TO = 'time_to' -class RuntimeIntent(): +class RuntimeIntent: """ An intent identified in the user input. - :attr str intent: The name of the recognized intent. - :attr float confidence: (optional) A decimal percentage that represents Watson's - confidence in the intent. If you are specifying an intent as part of a request, - but you do not have a calculated confidence value, specify `1`. + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. """ - def __init__(self, intent: str, *, confidence: float = None) -> None: + def __init__( + self, + intent: str, + *, + confidence: Optional[float] = None, + ) -> None: """ Initialize a RuntimeIntent object. @@ -9763,14 +10217,14 @@ def __init__(self, intent: str, *, confidence: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': """Initialize a RuntimeIntent object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in RuntimeIntent JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -9806,13 +10260,13 @@ def __ne__(self, other: 'RuntimeIntent') -> bool: return not self == other -class RuntimeResponseGeneric(): +class RuntimeResponseGeneric: """ RuntimeResponseGeneric. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a RuntimeResponseGeneric object. @@ -9839,22 +10293,20 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe' - ])) + msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe' + ])) raise Exception(msg) @classmethod @@ -9895,15 +10347,19 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class StatusError(): +class StatusError: """ An object describing an error that occurred during processing of an asynchronous operation. - :attr str message: (optional) The text of the error message. + :param str message: (optional) The text of the error message. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a StatusError object. @@ -9915,8 +10371,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'StatusError': """Initialize a StatusError object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -9950,24 +10406,26 @@ def __ne__(self, other: 'StatusError') -> bool: return not self == other -class Synonym(): +class Synonym: """ Synonym. - :attr str synonym: The text of the synonym. This string must conform to the + :param str synonym: The text of the synonym. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - synonym: str, - *, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + synonym: str, + *, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Synonym object. @@ -9984,15 +10442,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Synonym': """Initialize a Synonym object from a json dictionary.""" args = {} - if 'synonym' in _dict: - args['synonym'] = _dict.get('synonym') + if (synonym := _dict.get('synonym')) is not None: + args['synonym'] = synonym else: raise ValueError( 'Required property \'synonym\' not present in Synonym JSON') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -10030,17 +10488,20 @@ def __ne__(self, other: 'Synonym') -> bool: return not self == other -class SynonymCollection(): +class SynonymCollection: """ SynonymCollection. - :attr List[Synonym] synonyms: An array of synonyms. - :attr Pagination pagination: The pagination data for the returned objects. For + :param List[Synonym] synonyms: An array of synonyms. + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, synonyms: List['Synonym'], - pagination: 'Pagination') -> None: + def __init__( + self, + synonyms: List['Synonym'], + pagination: 'Pagination', + ) -> None: """ Initialize a SynonymCollection object. @@ -10055,16 +10516,14 @@ def __init__(self, synonyms: List['Synonym'], def from_dict(cls, _dict: Dict) -> 'SynonymCollection': """Initialize a SynonymCollection object from a json dictionary.""" args = {} - if 'synonyms' in _dict: - args['synonyms'] = [ - Synonym.from_dict(v) for v in _dict.get('synonyms') - ] + if (synonyms := _dict.get('synonyms')) is not None: + args['synonyms'] = [Synonym.from_dict(v) for v in synonyms] else: raise ValueError( 'Required property \'synonyms\' not present in SynonymCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in SynonymCollection JSON' @@ -10113,40 +10572,42 @@ def __ne__(self, other: 'SynonymCollection') -> bool: return not self == other -class Value(): +class Value: """ Value. - :attr str value: The text of the entity value. This string must conform to the + :param str value: The text of the entity value. This string must conform to the following restrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr dict metadata: (optional) Any metadata related to the entity value. - :attr str type: Specifies the type of entity value. - :attr List[str] synonyms: (optional) An array of synonyms for the entity value. + :param dict metadata: (optional) Any metadata related to the entity value. + :param str type: Specifies the type of entity value. + :param List[str] synonyms: (optional) An array of synonyms for the entity value. A value can specify either synonyms or patterns (depending on the value type), but not both. A synonym must conform to the following resrictions: - It cannot contain carriage return, newline, or tab characters. - It cannot consist of only whitespace characters. - :attr List[str] patterns: (optional) An array of patterns for the entity value. + :param List[str] patterns: (optional) An array of patterns for the 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/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 + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - value: str, - type: str, - *, - metadata: dict = None, - synonyms: List[str] = None, - patterns: List[str] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + value: str, + type: str, + *, + metadata: Optional[dict] = None, + synonyms: Optional[List[str]] = None, + patterns: Optional[List[str]] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Value object. @@ -10180,26 +10641,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Value': """Initialize a Value object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in Value JSON') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in Value JSON') - if 'synonyms' in _dict: - args['synonyms'] = _dict.get('synonyms') - if 'patterns' in _dict: - args['patterns'] = _dict.get('patterns') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (synonyms := _dict.get('synonyms')) is not None: + args['synonyms'] = synonyms + if (patterns := _dict.get('patterns')) is not None: + args['patterns'] = patterns + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -10248,20 +10709,25 @@ class TypeEnum(str, Enum): """ Specifies the type of entity value. """ + SYNONYMS = 'synonyms' PATTERNS = 'patterns' -class ValueCollection(): +class ValueCollection: """ ValueCollection. - :attr List[Value] values: An array of entity values. - :attr Pagination pagination: The pagination data for the returned objects. For + :param List[Value] values: An array of entity values. + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: + def __init__( + self, + values: List['Value'], + pagination: 'Pagination', + ) -> None: """ Initialize a ValueCollection object. @@ -10276,14 +10742,14 @@ def __init__(self, values: List['Value'], pagination: 'Pagination') -> None: def from_dict(cls, _dict: Dict) -> 'ValueCollection': """Initialize a ValueCollection object from a json dictionary.""" args = {} - if 'values' in _dict: - args['values'] = [Value.from_dict(v) for v in _dict.get('values')] + if (values := _dict.get('values')) is not None: + args['values'] = [Value.from_dict(v) for v in values] else: raise ValueError( 'Required property \'values\' not present in ValueCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in ValueCollection JSON' @@ -10332,25 +10798,27 @@ def __ne__(self, other: 'ValueCollection') -> bool: return not self == other -class Webhook(): +class Webhook: """ A webhook that can be used by dialog nodes to make programmatic calls to an external function. **Note:** Currently, only a single webhook named `main_webhook` is supported. - :attr str url: The URL for the external service or application to which you want - to send HTTP POST requests. - :attr str name: The name of the webhook. Currently, `main_webhook` is the only + :param str url: The URL for the external service or application to which you + want to send HTTP POST requests. + :param str name: The name of the webhook. Currently, `main_webhook` is the only supported value. - :attr List[WebhookHeader] headers_: (optional) An optional array of HTTP headers - to pass with the HTTP request. + :param List[WebhookHeader] headers_: (optional) An optional array of HTTP + headers to pass with the HTTP request. """ - def __init__(self, - url: str, - name: str, - *, - headers_: List['WebhookHeader'] = None) -> None: + def __init__( + self, + url: str, + name: str, + *, + headers_: Optional[List['WebhookHeader']] = None, + ) -> None: """ Initialize a Webhook object. @@ -10369,20 +10837,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Webhook': """Initialize a Webhook object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in Webhook JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Webhook JSON') - if 'headers' in _dict: - args['headers_'] = [ - WebhookHeader.from_dict(v) for v in _dict.get('headers') - ] + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = [WebhookHeader.from_dict(v) for v in headers_] return cls(**args) @classmethod @@ -10426,15 +10892,19 @@ def __ne__(self, other: 'Webhook') -> bool: return not self == other -class WebhookHeader(): +class WebhookHeader: """ A key/value pair defining an HTTP header and a value. - :attr str name: The name of an HTTP header (for example, `Authorization`). - :attr str value: The value of an HTTP header. + :param str name: The name of an HTTP header (for example, `Authorization`). + :param str value: The value of an HTTP header. """ - def __init__(self, name: str, value: str) -> None: + def __init__( + self, + name: str, + value: str, + ) -> None: """ Initialize a WebhookHeader object. @@ -10448,13 +10918,13 @@ def __init__(self, name: str, value: str) -> None: def from_dict(cls, _dict: Dict) -> 'WebhookHeader': """Initialize a WebhookHeader object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in WebhookHeader JSON') - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in WebhookHeader JSON') @@ -10493,30 +10963,31 @@ def __ne__(self, other: 'WebhookHeader') -> bool: return not self == other -class Workspace(): +class Workspace: """ Workspace. - :attr str name: The name of the workspace. This string cannot contain carriage + :param str name: The name of the workspace. This string cannot contain carriage return, newline, or tab characters. - :attr str description: (optional) The description of the workspace. This string + :param str description: (optional) The description of the workspace. This string cannot contain carriage return, newline, or tab characters. - :attr str language: The language of the workspace. - :attr str workspace_id: (optional) The workspace ID of the workspace. - :attr List[DialogNode] dialog_nodes: (optional) An array of objects describing + :param str language: The language of the workspace. + :param str workspace_id: (optional) The workspace ID of the workspace. + :param List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. - :attr List[Counterexample] counterexamples: (optional) An array of objects + :param List[Counterexample] counterexamples: (optional) An array of objects defining input examples that have been marked as irrelevant input. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. - :attr dict metadata: (optional) Any metadata related to the workspace. - :attr bool learning_opt_out: Whether training data from the workspace (including - artifacts such as intents and entities) can be used by IBM for general service - improvements. `true` indicates that workspace training data is not to be used. - :attr WorkspaceSystemSettings system_settings: (optional) Global settings for + :param dict metadata: (optional) Any metadata related to the workspace. + :param bool learning_opt_out: Whether training data from the workspace + (including artifacts such as intents and entities) can be used by IBM for + general service improvements. `true` indicates that workspace training data is + not to be used. + :param WorkspaceSystemSettings system_settings: (optional) Global settings for the workspace. - :attr str status: (optional) The current status of the workspace: + :param str status: (optional) The current status of the workspace: - **Available**: The workspace is available and ready to process messages. - **Failed**: An asynchronous operation has failed. See the **status_errors** property for more information about the cause of the failure. @@ -10524,38 +10995,40 @@ class Workspace(): - **Processing**: An asynchronous operation has not yet completed. - **Training**: The workspace is training based on new data such as intents or examples. - :attr List[StatusError] status_errors: (optional) An array of messages about + :param List[StatusError] status_errors: (optional) An array of messages about errors that caused an asynchronous operation to fail. - :attr List[Webhook] webhooks: (optional) - :attr List[Intent] intents: (optional) An array of intents. - :attr List[Entity] entities: (optional) An array of objects describing the + :param List[Webhook] webhooks: (optional) + :param List[Intent] intents: (optional) An array of intents. + :param List[Entity] entities: (optional) An array of objects describing the entities for the workspace. - :attr WorkspaceCounts counts: (optional) An object containing properties that + :param WorkspaceCounts counts: (optional) An object containing properties that indicate how many intents, entities, and dialog nodes are defined in the workspace. This property is included only in responses from the **Export workspace asynchronously** method, and only when the **verbose** query parameter is set to `true`. """ - def __init__(self, - name: str, - language: str, - learning_opt_out: bool, - *, - description: str = None, - workspace_id: str = None, - dialog_nodes: List['DialogNode'] = None, - counterexamples: List['Counterexample'] = None, - created: datetime = None, - updated: datetime = None, - metadata: dict = None, - system_settings: 'WorkspaceSystemSettings' = None, - status: str = None, - status_errors: List['StatusError'] = None, - webhooks: List['Webhook'] = None, - intents: List['Intent'] = None, - entities: List['Entity'] = None, - counts: 'WorkspaceCounts' = None) -> None: + def __init__( + self, + name: str, + language: str, + learning_opt_out: bool, + *, + description: Optional[str] = None, + workspace_id: Optional[str] = None, + dialog_nodes: Optional[List['DialogNode']] = None, + counterexamples: Optional[List['Counterexample']] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + metadata: Optional[dict] = None, + system_settings: Optional['WorkspaceSystemSettings'] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + webhooks: Optional[List['Webhook']] = None, + intents: Optional[List['Intent']] = None, + entities: Optional[List['Entity']] = None, + counts: Optional['WorkspaceCounts'] = None, + ) -> None: """ Initialize a Workspace object. @@ -10602,64 +11075,57 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Workspace': """Initialize a Workspace object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Workspace JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Workspace JSON') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'dialog_nodes' in _dict: + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (dialog_nodes := _dict.get('dialog_nodes')) is not None: args['dialog_nodes'] = [ - DialogNode.from_dict(v) for v in _dict.get('dialog_nodes') + DialogNode.from_dict(v) for v in dialog_nodes ] - if 'counterexamples' in _dict: + if (counterexamples := _dict.get('counterexamples')) is not None: args['counterexamples'] = [ - Counterexample.from_dict(v) - for v in _dict.get('counterexamples') + Counterexample.from_dict(v) for v in counterexamples ] - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'learning_opt_out' in _dict: - args['learning_opt_out'] = _dict.get('learning_opt_out') + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (learning_opt_out := _dict.get('learning_opt_out')) is not None: + args['learning_opt_out'] = learning_opt_out else: raise ValueError( 'Required property \'learning_opt_out\' not present in Workspace JSON' ) - if 'system_settings' in _dict: + if (system_settings := _dict.get('system_settings')) is not None: args['system_settings'] = WorkspaceSystemSettings.from_dict( - _dict.get('system_settings')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_errors' in _dict: + system_settings) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: args['status_errors'] = [ - StatusError.from_dict(v) for v in _dict.get('status_errors') - ] - if 'webhooks' in _dict: - args['webhooks'] = [ - Webhook.from_dict(v) for v in _dict.get('webhooks') - ] - if 'intents' in _dict: - args['intents'] = [ - Intent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - Entity.from_dict(v) for v in _dict.get('entities') + StatusError.from_dict(v) for v in status_errors ] - if 'counts' in _dict: - args['counts'] = WorkspaceCounts.from_dict(_dict.get('counts')) + if (webhooks := _dict.get('webhooks')) is not None: + args['webhooks'] = [Webhook.from_dict(v) for v in webhooks] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [Intent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [Entity.from_dict(v) for v in entities] + if (counts := _dict.get('counts')) is not None: + args['counts'] = WorkspaceCounts.from_dict(counts) return cls(**args) @classmethod @@ -10782,6 +11248,7 @@ class StatusEnum(str, Enum): - **Training**: The workspace is training based on new data such as intents or examples. """ + AVAILABLE = 'Available' FAILED = 'Failed' NON_EXISTENT = 'Non Existent' @@ -10790,18 +11257,21 @@ class StatusEnum(str, Enum): UNAVAILABLE = 'Unavailable' -class WorkspaceCollection(): +class WorkspaceCollection: """ WorkspaceCollection. - :attr List[Workspace] workspaces: An array of objects describing the workspaces + :param List[Workspace] workspaces: An array of objects describing the workspaces associated with the service instance. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, workspaces: List['Workspace'], - pagination: 'Pagination') -> None: + def __init__( + self, + workspaces: List['Workspace'], + pagination: 'Pagination', + ) -> None: """ Initialize a WorkspaceCollection object. @@ -10817,16 +11287,14 @@ def __init__(self, workspaces: List['Workspace'], def from_dict(cls, _dict: Dict) -> 'WorkspaceCollection': """Initialize a WorkspaceCollection object from a json dictionary.""" args = {} - if 'workspaces' in _dict: - args['workspaces'] = [ - Workspace.from_dict(v) for v in _dict.get('workspaces') - ] + if (workspaces := _dict.get('workspaces')) is not None: + args['workspaces'] = [Workspace.from_dict(v) for v in workspaces] else: raise ValueError( 'Required property \'workspaces\' not present in WorkspaceCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in WorkspaceCollection JSON' @@ -10875,23 +11343,25 @@ def __ne__(self, other: 'WorkspaceCollection') -> bool: return not self == other -class WorkspaceCounts(): +class WorkspaceCounts: """ An object containing properties that indicate how many intents, entities, and dialog nodes are defined in the workspace. This property is included only in responses from the **Export workspace asynchronously** method, and only when the **verbose** query parameter is set to `true`. - :attr int intent: (optional) The number of intents defined in the workspace. - :attr int entity: (optional) The number of entities defined in the workspace. - :attr int node: (optional) The number of nodes defined in the workspace. + :param int intent: (optional) The number of intents defined in the workspace. + :param int entity: (optional) The number of entities defined in the workspace. + :param int node: (optional) The number of nodes defined in the workspace. """ - def __init__(self, - *, - intent: int = None, - entity: int = None, - node: int = None) -> None: + def __init__( + self, + *, + intent: Optional[int] = None, + entity: Optional[int] = None, + node: Optional[int] = None, + ) -> None: """ Initialize a WorkspaceCounts object. @@ -10909,12 +11379,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'WorkspaceCounts': """Initialize a WorkspaceCounts object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') - if 'entity' in _dict: - args['entity'] = _dict.get('entity') - if 'node' in _dict: - args['node'] = _dict.get('node') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity + if (node := _dict.get('node')) is not None: + args['node'] = node return cls(**args) @classmethod @@ -10952,28 +11422,28 @@ def __ne__(self, other: 'WorkspaceCounts') -> bool: return not self == other -class WorkspaceSystemSettings(): +class WorkspaceSystemSettings: """ Global settings for the workspace. - :attr WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings + :param WorkspaceSystemSettingsTooling tooling: (optional) Workspace settings related to the Watson Assistant user interface. - :attr WorkspaceSystemSettingsDisambiguation disambiguation: (optional) Workspace - settings related to the disambiguation feature. - :attr dict human_agent_assist: (optional) For internal use only. - :attr bool spelling_suggestions: (optional) Whether spelling correction is + :param WorkspaceSystemSettingsDisambiguation disambiguation: (optional) + Workspace settings related to the disambiguation feature. + :param dict human_agent_assist: (optional) For internal use only. + :param bool spelling_suggestions: (optional) Whether spelling correction is enabled for the workspace. - :attr bool spelling_auto_correct: (optional) Whether autocorrection is enabled + :param bool spelling_auto_correct: (optional) Whether autocorrection is enabled for the workspace. If spelling correction is enabled and this property is `false`, any suggested corrections are returned in the **suggested_text** property of the message response. If this property is `true`, any corrections are automatically applied to the user input, and the original text is returned in the **original_text** property of the message response. - :attr WorkspaceSystemSettingsSystemEntities system_entities: (optional) + :param WorkspaceSystemSettingsSystemEntities system_entities: (optional) Workspace settings related to the behavior of system entities. - :attr WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings + :param WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings related to detection of irrelevant input. - :attr WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings related to + :param WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings related to the version of the training algorithms currently used by the skill. """ @@ -10985,17 +11455,20 @@ class WorkspaceSystemSettings(): ]) def __init__( - self, - *, - tooling: 'WorkspaceSystemSettingsTooling' = None, - disambiguation: 'WorkspaceSystemSettingsDisambiguation' = None, - human_agent_assist: dict = None, - spelling_suggestions: bool = None, - spelling_auto_correct: bool = None, - system_entities: 'WorkspaceSystemSettingsSystemEntities' = None, - off_topic: 'WorkspaceSystemSettingsOffTopic' = None, - nlp: 'WorkspaceSystemSettingsNlp' = None, - **kwargs) -> None: + self, + *, + tooling: Optional['WorkspaceSystemSettingsTooling'] = None, + disambiguation: Optional[ + 'WorkspaceSystemSettingsDisambiguation'] = None, + human_agent_assist: Optional[dict] = None, + spelling_suggestions: Optional[bool] = None, + spelling_auto_correct: Optional[bool] = None, + system_entities: Optional[ + 'WorkspaceSystemSettingsSystemEntities'] = None, + off_topic: Optional['WorkspaceSystemSettingsOffTopic'] = None, + nlp: Optional['WorkspaceSystemSettingsNlp'] = None, + **kwargs, + ) -> None: """ Initialize a WorkspaceSystemSettings object. @@ -11037,28 +11510,29 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': """Initialize a WorkspaceSystemSettings object from a json dictionary.""" args = {} - if 'tooling' in _dict: - args['tooling'] = WorkspaceSystemSettingsTooling.from_dict( - _dict.get('tooling')) - if 'disambiguation' in _dict: + if (tooling := _dict.get('tooling')) is not None: + args['tooling'] = WorkspaceSystemSettingsTooling.from_dict(tooling) + if (disambiguation := _dict.get('disambiguation')) is not None: args[ 'disambiguation'] = WorkspaceSystemSettingsDisambiguation.from_dict( - _dict.get('disambiguation')) - if 'human_agent_assist' in _dict: - args['human_agent_assist'] = _dict.get('human_agent_assist') - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'spelling_auto_correct' in _dict: - args['spelling_auto_correct'] = _dict.get('spelling_auto_correct') - if 'system_entities' in _dict: + disambiguation) + if (human_agent_assist := _dict.get('human_agent_assist')) is not None: + args['human_agent_assist'] = human_agent_assist + if (spelling_suggestions := + _dict.get('spelling_suggestions')) is not None: + args['spelling_suggestions'] = spelling_suggestions + if (spelling_auto_correct := + _dict.get('spelling_auto_correct')) is not None: + args['spelling_auto_correct'] = spelling_auto_correct + if (system_entities := _dict.get('system_entities')) is not None: args[ 'system_entities'] = WorkspaceSystemSettingsSystemEntities.from_dict( - _dict.get('system_entities')) - if 'off_topic' in _dict: + system_entities) + if (off_topic := _dict.get('off_topic')) is not None: args['off_topic'] = WorkspaceSystemSettingsOffTopic.from_dict( - _dict.get('off_topic')) - if 'nlp' in _dict: - args['nlp'] = WorkspaceSystemSettingsNlp.from_dict(_dict.get('nlp')) + off_topic) + if (nlp := _dict.get('nlp')) is not None: + args['nlp'] = WorkspaceSystemSettingsNlp.from_dict(nlp) args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -11156,37 +11630,39 @@ def __ne__(self, other: 'WorkspaceSystemSettings') -> bool: return not self == other -class WorkspaceSystemSettingsDisambiguation(): +class WorkspaceSystemSettingsDisambiguation: """ Workspace settings related to the disambiguation feature. - :attr str prompt: (optional) The text of the introductory prompt that + :param str prompt: (optional) The text of the introductory prompt that accompanies disambiguation options presented to the user. - :attr str none_of_the_above_prompt: (optional) The user-facing label for the + :param str none_of_the_above_prompt: (optional) The user-facing label for the option users can select if none of the suggested options is correct. If no value is specified for this property, this option does not appear. - :attr bool enabled: (optional) Whether the disambiguation feature is enabled for - the workspace. - :attr str sensitivity: (optional) The sensitivity of the disambiguation feature + :param bool enabled: (optional) Whether the disambiguation feature is enabled + for the workspace. + :param str sensitivity: (optional) The sensitivity of the disambiguation feature to intent detection uncertainty. Higher sensitivity means that the disambiguation feature is triggered more often and includes more choices. - :attr bool randomize: (optional) Whether the order in which disambiguation + :param bool randomize: (optional) Whether the order in which disambiguation suggestions are presented should be randomized (but still influenced by relative confidence). - :attr int max_suggestions: (optional) The maximum number of disambigation + :param int max_suggestions: (optional) The maximum number of disambigation suggestions that can be included in a `suggestion` response. - :attr str suggestion_text_policy: (optional) For internal use only. + :param str suggestion_text_policy: (optional) For internal use only. """ - def __init__(self, - *, - prompt: str = None, - none_of_the_above_prompt: str = None, - enabled: bool = None, - sensitivity: str = None, - randomize: bool = None, - max_suggestions: int = None, - suggestion_text_policy: str = None) -> None: + def __init__( + self, + *, + prompt: Optional[str] = None, + none_of_the_above_prompt: Optional[str] = None, + enabled: Optional[bool] = None, + sensitivity: Optional[str] = None, + randomize: Optional[bool] = None, + max_suggestions: Optional[int] = None, + suggestion_text_policy: Optional[str] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsDisambiguation object. @@ -11219,21 +11695,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsDisambiguation': """Initialize a WorkspaceSystemSettingsDisambiguation object from a json dictionary.""" args = {} - if 'prompt' in _dict: - args['prompt'] = _dict.get('prompt') - if 'none_of_the_above_prompt' in _dict: - args['none_of_the_above_prompt'] = _dict.get( - 'none_of_the_above_prompt') - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'sensitivity' in _dict: - args['sensitivity'] = _dict.get('sensitivity') - if 'randomize' in _dict: - args['randomize'] = _dict.get('randomize') - if 'max_suggestions' in _dict: - args['max_suggestions'] = _dict.get('max_suggestions') - if 'suggestion_text_policy' in _dict: - args['suggestion_text_policy'] = _dict.get('suggestion_text_policy') + if (prompt := _dict.get('prompt')) is not None: + args['prompt'] = prompt + if (none_of_the_above_prompt := + _dict.get('none_of_the_above_prompt')) is not None: + args['none_of_the_above_prompt'] = none_of_the_above_prompt + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (sensitivity := _dict.get('sensitivity')) is not None: + args['sensitivity'] = sensitivity + if (randomize := _dict.get('randomize')) is not None: + args['randomize'] = randomize + if (max_suggestions := _dict.get('max_suggestions')) is not None: + args['max_suggestions'] = max_suggestions + if (suggestion_text_policy := + _dict.get('suggestion_text_policy')) is not None: + args['suggestion_text_policy'] = suggestion_text_policy return cls(**args) @classmethod @@ -11287,6 +11764,7 @@ class SensitivityEnum(str, Enum): Higher sensitivity means that the disambiguation feature is triggered more often and includes more choices. """ + AUTO = 'auto' HIGH = 'high' MEDIUM_HIGH = 'medium_high' @@ -11295,12 +11773,12 @@ class SensitivityEnum(str, Enum): LOW = 'low' -class WorkspaceSystemSettingsNlp(): +class WorkspaceSystemSettingsNlp: """ Workspace settings related to the version of the training algorithms currently used by the skill. - :attr str model: (optional) The policy the skill follows for selecting the + :param str model: (optional) The policy the skill follows for selecting the algorithm version to use. For more information, see the [documentation](/docs/watson-assistant?topic=watson-assistant-algorithm-version). On IBM Cloud, you can specify `latest`, `previous`, or `beta`. @@ -11308,7 +11786,11 @@ class WorkspaceSystemSettingsNlp(): version you want to use, in `YYYY-MM-DD` format. """ - def __init__(self, *, model: str = None) -> None: + def __init__( + self, + *, + model: Optional[str] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsNlp object. @@ -11325,8 +11807,8 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsNlp': """Initialize a WorkspaceSystemSettingsNlp object from a json dictionary.""" args = {} - if 'model' in _dict: - args['model'] = _dict.get('model') + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -11360,15 +11842,19 @@ def __ne__(self, other: 'WorkspaceSystemSettingsNlp') -> bool: return not self == other -class WorkspaceSystemSettingsOffTopic(): +class WorkspaceSystemSettingsOffTopic: """ Workspace settings related to detection of irrelevant input. - :attr bool enabled: (optional) Whether enhanced irrelevance detection is enabled - for the workspace. + :param bool enabled: (optional) Whether enhanced irrelevance detection is + enabled for the workspace. """ - def __init__(self, *, enabled: bool = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsOffTopic object. @@ -11381,8 +11867,8 @@ def __init__(self, *, enabled: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsOffTopic': """Initialize a WorkspaceSystemSettingsOffTopic object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled return cls(**args) @classmethod @@ -11416,15 +11902,19 @@ def __ne__(self, other: 'WorkspaceSystemSettingsOffTopic') -> bool: return not self == other -class WorkspaceSystemSettingsSystemEntities(): +class WorkspaceSystemSettingsSystemEntities: """ Workspace settings related to the behavior of system entities. - :attr bool enabled: (optional) Whether the new system entities are enabled for + :param bool enabled: (optional) Whether the new system entities are enabled for the workspace. """ - def __init__(self, *, enabled: bool = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsSystemEntities object. @@ -11437,8 +11927,8 @@ def __init__(self, *, enabled: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsSystemEntities': """Initialize a WorkspaceSystemSettingsSystemEntities object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled return cls(**args) @classmethod @@ -11472,15 +11962,19 @@ def __ne__(self, other: 'WorkspaceSystemSettingsSystemEntities') -> bool: return not self == other -class WorkspaceSystemSettingsTooling(): +class WorkspaceSystemSettingsTooling: """ Workspace settings related to the Watson Assistant user interface. - :attr bool store_generic_responses: (optional) Whether the dialog JSON editor + :param bool store_generic_responses: (optional) Whether the dialog JSON editor displays text responses within the `output.generic` object. """ - def __init__(self, *, store_generic_responses: bool = None) -> None: + def __init__( + self, + *, + store_generic_responses: Optional[bool] = None, + ) -> None: """ Initialize a WorkspaceSystemSettingsTooling object. @@ -11493,9 +11987,9 @@ def __init__(self, *, store_generic_responses: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettingsTooling': """Initialize a WorkspaceSystemSettingsTooling object from a json dictionary.""" args = {} - if 'store_generic_responses' in _dict: - args['store_generic_responses'] = _dict.get( - 'store_generic_responses') + if (store_generic_responses := + _dict.get('store_generic_responses')) is not None: + args['store_generic_responses'] = store_generic_responses return cls(**args) @classmethod @@ -11535,30 +12029,32 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the audio clip. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio object. @@ -11592,31 +12088,30 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -11678,24 +12173,26 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The `channel_transfer` response type is not supported on IBM Cloud Pak for Data. - :attr str message_to_user: The message to display to the user when initiating a + :param str message_to_user: The message to display to the user when initiating a channel transfer. - :attr ChannelTransferInfo transfer_info: Information used by an integration to + :param ChannelTransferInfo transfer_info: Information used by an integration to transfer the conversation to a different channel. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - message_to_user: str, - transfer_info: 'ChannelTransferInfo', - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer object. @@ -11723,29 +12220,27 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' ) - if 'message_to_user' in _dict: - args['message_to_user'] = _dict.get('message_to_user') + if (message_to_user := _dict.get('message_to_user')) is not None: + args['message_to_user'] = message_to_user else: raise ValueError( 'Required property \'message_to_user\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' ) - if 'transfer_info' in _dict: - args['transfer_info'] = ChannelTransferInfo.from_dict( - _dict.get('transfer_info')) + if (transfer_info := _dict.get('transfer_info')) is not None: + args['transfer_info'] = ChannelTransferInfo.from_dict(transfer_info) else: raise ValueError( 'Required property \'transfer_info\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -11807,32 +12302,34 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_human_agent: (optional) An optional message to be sent to + :param str message_to_human_agent: (optional) An optional message to be sent to the human agent who will be taking over the conversation. - :attr AgentAvailabilityMessage agent_available: (optional) An optional message + :param AgentAvailabilityMessage agent_available: (optional) An optional message to be displayed to the user to indicate that the conversation will be transferred to the next available agent. - :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message - to be displayed to the user to indicate that no online agent is available to - take over the conversation. - :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ def __init__( - self, - response_type: str, - *, - message_to_human_agent: str = None, - agent_available: 'AgentAvailabilityMessage' = None, - agent_unavailable: 'AgentAvailabilityMessage' = None, - transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, - channels: List['ResponseGenericChannel'] = None) -> None: + self, + response_type: str, + *, + message_to_human_agent: Optional[str] = None, + agent_available: Optional['AgentAvailabilityMessage'] = None, + agent_unavailable: Optional['AgentAvailabilityMessage'] = None, + transfer_info: Optional[ + 'DialogNodeOutputConnectToAgentTransferInfo'] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object. @@ -11867,28 +12364,28 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent JSON' ) - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'agent_available' in _dict: + if (message_to_human_agent := + _dict.get('message_to_human_agent')) is not None: + args['message_to_human_agent'] = message_to_human_agent + if (agent_available := _dict.get('agent_available')) is not None: args['agent_available'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_available')) - if 'agent_unavailable' in _dict: + agent_available) + if (agent_unavailable := _dict.get('agent_unavailable')) is not None: args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_unavailable')) - if 'transfer_info' in _dict: + agent_unavailable) + if (transfer_info := _dict.get('transfer_info')) is not None: args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( - _dict.get('transfer_info')) - if 'channels' in _dict: + transfer_info) + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -11962,28 +12459,30 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the embeddable content. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the embeddable content. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr str image_url: (optional) The URL of an image that shows a preview of the + :param str image_url: (optional) The URL of an image that shows a preview of the embedded content. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - image_url: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + image_url: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe object. @@ -12015,28 +12514,27 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'image_url' in _dict: - args['image_url'] = _dict.get('image_url') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (image_url := _dict.get('image_url')) is not None: + args['image_url'] = image_url + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12096,26 +12594,28 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeImage. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the image. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the image. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the image cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object. @@ -12145,29 +12645,28 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -12226,28 +12725,30 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeOption( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeOption. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str title: An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr str preference: (optional) The preferred type of control to display, if + :param str preference: (optional) The preferred type of control to display, if supported by the channel. - :attr List[DialogNodeOutputOptionsElement] options: An array of objects + :param List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. You can include up to 20 options. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - title: str, - options: List['DialogNodeOutputOptionsElement'], - *, - description: str = None, - preference: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: Optional[str] = None, + preference: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object. @@ -12279,35 +12780,33 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (preference := _dict.get('preference')) is not None: + args['preference'] = preference + if (options := _dict.get('options')) is not None: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(v) - for v in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) for v in options ] else: raise ValueError( 'Required property \'options\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12371,6 +12870,7 @@ class PreferenceEnum(str, Enum): """ The preferred type of control to display, if supported by the channel. """ + DROPDOWN = 'dropdown' BUTTON = 'button' @@ -12380,22 +12880,24 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypePause( """ DialogNodeOutputGenericDialogNodeOutputResponseTypePause. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr int time: How long to pause, in milliseconds. The valid values are from 0 + :param int time: How long to pause, in milliseconds. The valid values are from 0 to 10000. - :attr bool typing: (optional) Whether to send a "user is typing" event during + :param bool typing: (optional) Whether to send a "user is typing" event during the pause. Ignored if the channel does not support this event. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - time: int, - *, - typing: bool = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + time: int, + *, + typing: Optional[bool] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypePause object. @@ -12421,24 +12923,23 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypePause': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypePause object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypePause JSON' ) - if 'time' in _dict: - args['time'] = _dict.get('time') + if (time := _dict.get('time')) is not None: + args['time'] = time else: raise ValueError( 'Required property \'time\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypePause JSON' ) - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'channels' in _dict: + if (typing := _dict.get('typing')) is not None: + args['typing'] = typing + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12494,33 +12995,35 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The **search_skill** response type is used only by the v2 runtime API. - :attr str query: The text of the search query. This can be either a + :param str query: The text of the search query. This can be either a natural-language query or a query that uses the Discovery query language syntax, depending on the value of the **query_type** property. For more information, see the [Discovery service documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-operators#query-operators). - :attr str query_type: The type of the search query. - :attr str filter: (optional) An optional filter that narrows the set of + :param str query_type: The type of the search query. + :param str filter: (optional) An optional filter that narrows the set of documents to be searched. For more information, see the [Discovery service documentation]([Discovery service documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-parameters#filter). - :attr str discovery_version: (optional) The version of the Discovery service API - to use for the query. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str discovery_version: (optional) The version of the Discovery service + API to use for the query. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - query: str, - query_type: str, - *, - filter: str = None, - discovery_version: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + query: str, + query_type: str, + *, + filter: Optional[str] = None, + discovery_version: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object. @@ -12558,32 +13061,31 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' ) - if 'query' in _dict: - args['query'] = _dict.get('query') + if (query := _dict.get('query')) is not None: + args['query'] = query else: raise ValueError( 'Required property \'query\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' ) - if 'query_type' in _dict: - args['query_type'] = _dict.get('query_type') + if (query_type := _dict.get('query_type')) is not None: + args['query_type'] = query_type else: raise ValueError( 'Required property \'query_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill JSON' ) - if 'filter' in _dict: - args['filter'] = _dict.get('filter') - if 'discovery_version' in _dict: - args['discovery_version'] = _dict.get('discovery_version') - if 'channels' in _dict: + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (discovery_version := _dict.get('discovery_version')) is not None: + args['discovery_version'] = discovery_version + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12644,6 +13146,7 @@ class QueryTypeEnum(str, Enum): """ The type of the search query. """ + NATURAL_LANGUAGE = 'natural_language' DISCOVERY_QUERY_LANGUAGE = 'discovery_query_language' @@ -12653,25 +13156,27 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeText( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeText. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr List[DialogNodeOutputTextValuesElement] values: A list of one or more + :param List[DialogNodeOutputTextValuesElement] values: A list of one or more objects defining text responses. - :attr str selection_policy: (optional) How a response is selected from the list, - if more than one response is specified. - :attr str delimiter: (optional) The delimiter to use as a separator between + :param str selection_policy: (optional) How a response is selected from the + list, if more than one response is specified. + :param str delimiter: (optional) The delimiter to use as a separator between responses when `selection_policy`=`multiline`. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - values: List['DialogNodeOutputTextValuesElement'], - *, - selection_policy: str = None, - delimiter: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + values: List['DialogNodeOutputTextValuesElement'], + *, + selection_policy: Optional[str] = None, + delimiter: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeText object. @@ -12700,29 +13205,27 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeText object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeText JSON' ) - if 'values' in _dict: + if (values := _dict.get('values')) is not None: args['values'] = [ - DialogNodeOutputTextValuesElement.from_dict(v) - for v in _dict.get('values') + DialogNodeOutputTextValuesElement.from_dict(v) for v in values ] else: raise ValueError( 'Required property \'values\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeText JSON' ) - if 'selection_policy' in _dict: - args['selection_policy'] = _dict.get('selection_policy') - if 'delimiter' in _dict: - args['delimiter'] = _dict.get('delimiter') - if 'channels' in _dict: + if (selection_policy := _dict.get('selection_policy')) is not None: + args['selection_policy'] = selection_policy + if (delimiter := _dict.get('delimiter')) is not None: + args['delimiter'] = delimiter + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12785,6 +13288,7 @@ class SelectionPolicyEnum(str, Enum): """ How a response is selected from the list, if more than one response is specified. """ + SEQUENTIAL = 'sequential' RANDOM = 'random' MULTILINE = 'multiline' @@ -12795,20 +13299,22 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr dict user_defined: An object containing any properties for the + :param dict user_defined: An object containing any properties for the user-defined response type. The total size of this object cannot exceed 5000 bytes. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. """ - def __init__(self, - response_type: str, - user_defined: dict, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + user_defined: dict, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object. @@ -12832,22 +13338,21 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' ) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined else: raise ValueError( 'Required property \'user_defined\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12903,30 +13408,32 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo( """ DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the video. - :attr str title: (optional) An optional title to show before the response. - :attr str description: (optional) An optional description to show with the + :param str source: The `https:` URL of the video. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo object. @@ -12960,31 +13467,30 @@ def from_dict( ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo': """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -13045,30 +13551,32 @@ class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeAudio. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the audio clip. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str description: (optional) The description to show with the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. @@ -13103,31 +13611,30 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeAudio': """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -13187,26 +13694,28 @@ class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( """ RuntimeResponseGenericRuntimeResponseTypeChannelTransfer. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The `channel_transfer` response type is not supported on IBM Cloud Pak for Data. - :attr str message_to_user: The message to display to the user when initiating a + :param str message_to_user: The message to display to the user when initiating a channel transfer. - :attr ChannelTransferInfo transfer_info: Information used by an integration to + :param ChannelTransferInfo transfer_info: Information used by an integration to transfer the conversation to a different channel. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended only for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - message_to_user: str, - transfer_info: 'ChannelTransferInfo', - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object. @@ -13236,29 +13745,27 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer': """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'message_to_user' in _dict: - args['message_to_user'] = _dict.get('message_to_user') + if (message_to_user := _dict.get('message_to_user')) is not None: + args['message_to_user'] = message_to_user else: raise ValueError( 'Required property \'message_to_user\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'transfer_info' in _dict: - args['transfer_info'] = ChannelTransferInfo.from_dict( - _dict.get('transfer_info')) + if (transfer_info := _dict.get('transfer_info')) is not None: + args['transfer_info'] = ChannelTransferInfo.from_dict(transfer_info) else: raise ValueError( 'Required property \'transfer_info\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13318,42 +13825,44 @@ class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( """ RuntimeResponseGenericRuntimeResponseTypeConnectToAgent. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_human_agent: (optional) A message to be sent to the human + :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. - :attr AgentAvailabilityMessage agent_available: (optional) An optional message + :param AgentAvailabilityMessage agent_available: (optional) An optional message to be displayed to the user to indicate that the conversation will be transferred to the next available agent. - :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message - to be displayed to the user to indicate that no online agent is available to - take over the conversation. - :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. - :attr str topic: (optional) A label identifying the topic of the conversation, + :param str topic: (optional) A label identifying the topic of the conversation, derived from the **title** property of the relevant node or the **topic** property of the dialog node response. - :attr str dialog_node: (optional) The unique ID of the dialog node that the + :param str dialog_node: (optional) The unique ID of the dialog node that the **topic** property is taken from. The **topic** property is populated using the value of the dialog node's **title** property. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ def __init__( - self, - response_type: str, - *, - message_to_human_agent: str = None, - agent_available: 'AgentAvailabilityMessage' = None, - agent_unavailable: 'AgentAvailabilityMessage' = None, - transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, - topic: str = None, - dialog_node: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + self, + response_type: str, + *, + message_to_human_agent: Optional[str] = None, + agent_available: Optional['AgentAvailabilityMessage'] = None, + agent_unavailable: Optional['AgentAvailabilityMessage'] = None, + transfer_info: Optional[ + 'DialogNodeOutputConnectToAgentTransferInfo'] = None, + topic: Optional[str] = None, + dialog_node: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object. @@ -13398,32 +13907,32 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent': """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeConnectToAgent JSON' ) - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'agent_available' in _dict: + if (message_to_human_agent := + _dict.get('message_to_human_agent')) is not None: + args['message_to_human_agent'] = message_to_human_agent + if (agent_available := _dict.get('agent_available')) is not None: args['agent_available'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_available')) - if 'agent_unavailable' in _dict: + agent_available) + if (agent_unavailable := _dict.get('agent_unavailable')) is not None: args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_unavailable')) - if 'transfer_info' in _dict: + agent_unavailable) + if (transfer_info := _dict.get('transfer_info')) is not None: args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( - _dict.get('transfer_info')) - if 'topic' in _dict: - args['topic'] = _dict.get('topic') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'channels' in _dict: + transfer_info) + if (topic := _dict.get('topic')) is not None: + args['topic'] = topic + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13498,28 +14007,30 @@ class RuntimeResponseGenericRuntimeResponseTypeIframe(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeIframe. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the embeddable content. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the embeddable content. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr str image_url: (optional) The URL of an image that shows a preview of the + :param str description: (optional) The description to show with the response. + :param str image_url: (optional) The URL of an image that shows a preview of the embedded content. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - image_url: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + image_url: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object. @@ -13552,28 +14063,27 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeIframe': """Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'image_url' in _dict: - args['image_url'] = _dict.get('image_url') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (image_url := _dict.get('image_url')) is not None: + args['image_url'] = image_url + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13632,28 +14142,30 @@ class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeImage. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the image. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the image. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str description: (optional) The description to show with the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the image cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. @@ -13686,29 +14198,28 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeImage': """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -13764,27 +14275,29 @@ class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeOption. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr str preference: (optional) The preferred type of control to display. - :attr List[DialogNodeOutputOptionsElement] options: An array of objects + :param str title: The title or introductory text to show before the response. + :param str description: (optional) The description to show with the response. + :param str preference: (optional) The preferred type of control to display. + :param List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - options: List['DialogNodeOutputOptionsElement'], - *, - description: str = None, - preference: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: Optional[str] = None, + preference: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object. @@ -13817,35 +14330,33 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeOption': """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (preference := _dict.get('preference')) is not None: + args['preference'] = preference + if (options := _dict.get('options')) is not None: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(v) - for v in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) for v in options ] else: raise ValueError( 'Required property \'options\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13909,6 +14420,7 @@ class PreferenceEnum(str, Enum): """ The preferred type of control to display. """ + DROPDOWN = 'dropdown' BUTTON = 'button' @@ -13917,23 +14429,25 @@ class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypePause. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr int time: How long to pause, in milliseconds. - :attr bool typing: (optional) Whether to send a "user is typing" event during + :param int time: How long to pause, in milliseconds. + :param bool typing: (optional) Whether to send a "user is typing" event during the pause. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - time: int, - *, - typing: bool = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + time: int, + *, + typing: Optional[bool] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypePause object. @@ -13960,24 +14474,23 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypePause': """Initialize a RuntimeResponseGenericRuntimeResponseTypePause object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'time' in _dict: - args['time'] = _dict.get('time') + if (time := _dict.get('time')) is not None: + args['time'] = time else: raise ValueError( 'Required property \'time\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'channels' in _dict: + if (typing := _dict.get('typing')) is not None: + args['typing'] = typing + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -14031,23 +14544,25 @@ class RuntimeResponseGenericRuntimeResponseTypeSuggestion( """ RuntimeResponseGenericRuntimeResponseTypeSuggestion. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr List[DialogSuggestion] suggestions: An array of objects describing the + :param str title: The title or introductory text to show before the response. + :param List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - suggestions: List['DialogSuggestion'], - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + suggestions: List['DialogSuggestion'], + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object. @@ -14075,30 +14590,29 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeSuggestion': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'suggestions' in _dict: + if (suggestions := _dict.get('suggestions')) is not None: args['suggestions'] = [ - DialogSuggestion.from_dict(v) for v in _dict.get('suggestions') + DialogSuggestion.from_dict(v) for v in suggestions ] else: raise ValueError( 'Required property \'suggestions\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -14159,20 +14673,22 @@ class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeText. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str text: The text of the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str text: The text of the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - text: str, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + text: str, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeText object. @@ -14196,22 +14712,21 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeText': """Initialize a RuntimeResponseGenericRuntimeResponseTypeText object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -14263,21 +14778,23 @@ class RuntimeResponseGenericRuntimeResponseTypeUserDefined( """ RuntimeResponseGenericRuntimeResponseTypeUserDefined. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr dict user_defined: An object containing any properties for the + :param dict user_defined: An object containing any properties for the user-defined response type. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - user_defined: dict, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + user_defined: dict, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object. @@ -14302,22 +14819,21 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeUserDefined': """Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined else: raise ValueError( 'Required property \'user_defined\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -14370,30 +14886,32 @@ class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeVideo. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the video. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the video. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str description: (optional) The description to show with the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. @@ -14428,31 +14946,30 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeVideo': """Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 1875780d3..a39305c74 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -28,7 +28,7 @@ from datetime import datetime from enum import Enum -from typing import Dict, List +from typing import Dict, List, Optional import json import sys @@ -81,12 +81,14 @@ def __init__( # Assistants ######################### - def create_assistant(self, - *, - language: str = None, - name: str = None, - description: str = None, - **kwargs) -> DetailedResponse: + def create_assistant( + self, + *, + language: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create an assistant. @@ -104,9 +106,11 @@ def create_assistant(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_assistant') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_assistant', + ) headers.update(sdk_headers) params = { @@ -128,23 +132,27 @@ def create_assistant(self, headers['Accept'] = 'application/json' url = '/v2/assistants' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def list_assistants(self, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_assistants( + self, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List assistants. @@ -170,9 +178,11 @@ def list_assistants(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_assistants') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_assistants', + ) headers.update(sdk_headers) params = { @@ -190,15 +200,21 @@ def list_assistants(self, headers['Accept'] = 'application/json' url = '/v2/assistants' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_assistant(self, assistant_id: str, **kwargs) -> DetailedResponse: + def delete_assistant( + self, + assistant_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete assistant. @@ -225,9 +241,11 @@ def delete_assistant(self, assistant_id: str, **kwargs) -> DetailedResponse: if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_assistant') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_assistant', + ) headers.update(sdk_headers) params = { @@ -243,10 +261,12 @@ def delete_assistant(self, assistant_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -255,11 +275,13 @@ def delete_assistant(self, assistant_id: str, **kwargs) -> DetailedResponse: # Sessions ######################### - def create_session(self, - assistant_id: str, - *, - analytics: 'RequestAnalytics' = None, - **kwargs) -> DetailedResponse: + def create_session( + self, + assistant_id: str, + *, + analytics: Optional['RequestAnalytics'] = None, + **kwargs, + ) -> DetailedResponse: """ Create a session. @@ -294,9 +316,11 @@ def create_session(self, if analytics is not None: analytics = convert_model(analytics) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_session') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_session', + ) headers.update(sdk_headers) params = { @@ -319,17 +343,23 @@ def create_session(self, path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/sessions'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_session(self, assistant_id: str, session_id: str, - **kwargs) -> DetailedResponse: + def delete_session( + self, + assistant_id: str, + session_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete session. @@ -360,9 +390,11 @@ def delete_session(self, assistant_id: str, session_id: str, if not session_id: raise ValueError('session_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_session') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_session', + ) headers.update(sdk_headers) params = { @@ -379,10 +411,12 @@ def delete_session(self, assistant_id: str, session_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/sessions/{session_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -391,14 +425,16 @@ def delete_session(self, assistant_id: str, session_id: str, # Message ######################### - def message(self, - assistant_id: str, - session_id: str, - *, - input: 'MessageInput' = None, - context: 'MessageContext' = None, - user_id: str = None, - **kwargs) -> DetailedResponse: + def message( + self, + assistant_id: str, + session_id: str, + *, + input: Optional['MessageInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Send user input to assistant (stateful). @@ -451,9 +487,11 @@ def message(self, if context is not None: context = convert_model(context) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='message') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message', + ) headers.update(sdk_headers) params = { @@ -479,22 +517,26 @@ def message(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/sessions/{session_id}/message'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def message_stateless(self, - assistant_id: str, - *, - input: 'MessageInputStateless' = None, - context: 'MessageContextStateless' = None, - user_id: str = None, - **kwargs) -> DetailedResponse: + def message_stateless( + self, + assistant_id: str, + *, + input: Optional['MessageInputStateless'] = None, + context: Optional['MessageContextStateless'] = None, + user_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Send user input to assistant (stateless). @@ -544,9 +586,11 @@ def message_stateless(self, if context is not None: context = convert_model(context) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='message_stateless') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message_stateless', + ) headers.update(sdk_headers) params = { @@ -571,11 +615,13 @@ def message_stateless(self, path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/message'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -584,8 +630,12 @@ def message_stateless(self, # Bulk classify ######################### - def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], - **kwargs) -> DetailedResponse: + def bulk_classify( + self, + skill_id: str, + input: List['BulkClassifyUtterance'], + **kwargs, + ) -> DetailedResponse: """ Identify intents and entities in multiple user utterances. @@ -611,9 +661,11 @@ def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], raise ValueError('input must be provided') input = [convert_model(x) for x in input] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='bulk_classify') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='bulk_classify', + ) headers.update(sdk_headers) params = { @@ -637,11 +689,13 @@ def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/skills/{skill_id}/workspace/bulk_classify'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -650,14 +704,16 @@ def bulk_classify(self, skill_id: str, input: List['BulkClassifyUtterance'], # Logs ######################### - def list_logs(self, - assistant_id: str, - *, - sort: str = None, - filter: str = None, - page_limit: int = None, - cursor: str = None, - **kwargs) -> DetailedResponse: + def list_logs( + self, + assistant_id: str, + *, + sort: Optional[str] = None, + filter: Optional[str] = None, + page_limit: Optional[int] = None, + cursor: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List log events for an assistant. @@ -699,9 +755,11 @@ def list_logs(self, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_logs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_logs', + ) headers.update(sdk_headers) params = { @@ -721,10 +779,12 @@ def list_logs(self, path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/logs'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -733,7 +793,11 @@ def list_logs(self, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -759,9 +823,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -775,10 +841,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v2/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -787,15 +855,17 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: # Environments ######################### - def list_environments(self, - assistant_id: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_environments( + self, + assistant_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List environments. @@ -835,9 +905,11 @@ def list_environments(self, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_environments') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_environments', + ) headers.update(sdk_headers) params = { @@ -859,20 +931,24 @@ def list_environments(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/environments'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_environment(self, - assistant_id: str, - environment_id: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_environment( + self, + assistant_id: str, + environment_id: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get environment. @@ -908,9 +984,11 @@ def get_environment(self, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_environment', + ) headers.update(sdk_headers) params = { @@ -928,23 +1006,27 @@ def get_environment(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/environments/{environment_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_environment(self, - assistant_id: str, - environment_id: str, - *, - name: str = None, - description: str = None, - session_timeout: int = None, - skill_references: List['EnvironmentSkill'] = None, - **kwargs) -> DetailedResponse: + def update_environment( + self, + assistant_id: str, + environment_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + session_timeout: Optional[int] = None, + skill_references: Optional[List['EnvironmentSkill']] = None, + **kwargs, + ) -> DetailedResponse: """ Update environment. @@ -988,9 +1070,11 @@ def update_environment(self, if skill_references is not None: skill_references = [convert_model(x) for x in skill_references] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_environment', + ) headers.update(sdk_headers) params = { @@ -1017,11 +1101,13 @@ def update_environment(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/environments/{environment_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -1030,11 +1116,13 @@ def update_environment(self, # Releases ######################### - def create_release(self, - assistant_id: str, - *, - description: str = None, - **kwargs) -> DetailedResponse: + def create_release( + self, + assistant_id: str, + *, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create release. @@ -1064,9 +1152,11 @@ def create_release(self, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_release') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_release', + ) headers.update(sdk_headers) params = { @@ -1089,24 +1179,28 @@ def create_release(self, path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/releases'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def list_releases(self, - assistant_id: str, - *, - page_limit: int = None, - include_count: bool = None, - sort: str = None, - cursor: str = None, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def list_releases( + self, + assistant_id: str, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List releases. @@ -1147,9 +1241,11 @@ def list_releases(self, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_releases') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_releases', + ) headers.update(sdk_headers) params = { @@ -1170,20 +1266,24 @@ def list_releases(self, path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/releases'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_release(self, - assistant_id: str, - release: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def get_release( + self, + assistant_id: str, + release: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Get release. @@ -1219,9 +1319,11 @@ def get_release(self, if not release: raise ValueError('release must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_release') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_release', + ) headers.update(sdk_headers) params = { @@ -1239,16 +1341,22 @@ def get_release(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/releases/{release}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_release(self, assistant_id: str, release: str, - **kwargs) -> DetailedResponse: + def delete_release( + self, + assistant_id: str, + release: str, + **kwargs, + ) -> DetailedResponse: """ Delete release. @@ -1279,9 +1387,11 @@ def delete_release(self, assistant_id: str, release: str, if not release: raise ValueError('release must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_release') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_release', + ) headers.update(sdk_headers) params = { @@ -1298,21 +1408,25 @@ def delete_release(self, assistant_id: str, release: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/releases/{release}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def deploy_release(self, - assistant_id: str, - release: str, - environment_id: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def deploy_release( + self, + assistant_id: str, + release: str, + environment_id: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Deploy release. @@ -1349,9 +1463,11 @@ def deploy_release(self, if environment_id is None: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='deploy_release') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='deploy_release', + ) headers.update(sdk_headers) params = { @@ -1376,11 +1492,13 @@ def deploy_release(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/releases/{release}/deploy'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -1389,8 +1507,12 @@ def deploy_release(self, # Skills ######################### - def get_skill(self, assistant_id: str, skill_id: str, - **kwargs) -> DetailedResponse: + def get_skill( + self, + assistant_id: str, + skill_id: str, + **kwargs, + ) -> DetailedResponse: """ Get skill. @@ -1422,9 +1544,11 @@ def get_skill(self, assistant_id: str, skill_id: str, if not skill_id: raise ValueError('skill_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_skill') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_skill', + ) headers.update(sdk_headers) params = { @@ -1441,24 +1565,28 @@ def get_skill(self, assistant_id: str, skill_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_skill(self, - assistant_id: str, - skill_id: str, - *, - name: str = None, - description: str = None, - workspace: dict = None, - dialog_settings: dict = None, - search_settings: 'SearchSettings' = None, - **kwargs) -> DetailedResponse: + def update_skill( + self, + assistant_id: str, + skill_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + dialog_settings: Optional[dict] = None, + search_settings: Optional['SearchSettings'] = None, + **kwargs, + ) -> DetailedResponse: """ Update skill. @@ -1504,9 +1632,11 @@ def update_skill(self, if search_settings is not None: search_settings = convert_model(search_settings) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_skill') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_skill', + ) headers.update(sdk_headers) params = { @@ -1534,20 +1664,24 @@ def update_skill(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def export_skills(self, - assistant_id: str, - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def export_skills( + self, + assistant_id: str, + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Export skills. @@ -1588,9 +1722,11 @@ def export_skills(self, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='export_skills') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='export_skills', + ) headers.update(sdk_headers) params = { @@ -1608,21 +1744,25 @@ def export_skills(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/skills_export'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def import_skills(self, - assistant_id: str, - assistant_skills: List['SkillImport'], - assistant_state: 'AssistantState', - *, - include_audit: bool = None, - **kwargs) -> DetailedResponse: + def import_skills( + self, + assistant_id: str, + assistant_skills: List['SkillImport'], + assistant_state: 'AssistantState', + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Import skills. @@ -1670,9 +1810,11 @@ def import_skills(self, assistant_skills = [convert_model(x) for x in assistant_skills] assistant_state = convert_model(assistant_state) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='import_skills') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills', + ) headers.update(sdk_headers) params = { @@ -1698,17 +1840,22 @@ def import_skills(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/skills_import'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def import_skills_status(self, assistant_id: str, - **kwargs) -> DetailedResponse: + def import_skills_status( + self, + assistant_id: str, + **kwargs, + ) -> DetailedResponse: """ Get status of skills import. @@ -1736,9 +1883,11 @@ def import_skills_status(self, assistant_id: str, if not assistant_id: raise ValueError('assistant_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='import_skills_status') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills_status', + ) headers.update(sdk_headers) params = { @@ -1755,10 +1904,12 @@ def import_skills_status(self, assistant_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/skills_import/status'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1774,6 +1925,7 @@ class Sort(str, Enum): The attribute by which returned assistants will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + NAME = 'name' UPDATED = 'updated' @@ -1788,6 +1940,7 @@ class Sort(str, Enum): The attribute by which returned environments will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + NAME = 'name' UPDATED = 'updated' @@ -1802,6 +1955,7 @@ class Sort(str, Enum): The attribute by which returned workspaces will be sorted. To reverse the sort order, prefix the value with a minus sign (`-`). """ + NAME = 'name' UPDATED = 'updated' @@ -1811,14 +1965,18 @@ class Sort(str, Enum): ############################################################################## -class AgentAvailabilityMessage(): +class AgentAvailabilityMessage: """ AgentAvailabilityMessage. - :attr str message: (optional) The text of the message. + :param str message: (optional) The text of the message. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a AgentAvailabilityMessage object. @@ -1830,8 +1988,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': """Initialize a AgentAvailabilityMessage object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -1865,18 +2023,21 @@ def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: return not self == other -class AssistantCollection(): +class AssistantCollection: """ AssistantCollection. - :attr List[AssistantData] assistants: An array of objects describing the + :param List[AssistantData] assistants: An array of objects describing the assistants associated with the instance. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, assistants: List['AssistantData'], - pagination: 'Pagination') -> None: + def __init__( + self, + assistants: List['AssistantData'], + pagination: 'Pagination', + ) -> None: """ Initialize a AssistantCollection object. @@ -1892,16 +2053,16 @@ def __init__(self, assistants: List['AssistantData'], def from_dict(cls, _dict: Dict) -> 'AssistantCollection': """Initialize a AssistantCollection object from a json dictionary.""" args = {} - if 'assistants' in _dict: + if (assistants := _dict.get('assistants')) is not None: args['assistants'] = [ - AssistantData.from_dict(v) for v in _dict.get('assistants') + AssistantData.from_dict(v) for v in assistants ] else: raise ValueError( 'Required property \'assistants\' not present in AssistantCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in AssistantCollection JSON' @@ -1950,31 +2111,31 @@ def __ne__(self, other: 'AssistantCollection') -> bool: return not self == other -class AssistantData(): +class AssistantData: """ AssistantData. - :attr str assistant_id: (optional) The unique identifier of the assistant. - :attr str name: (optional) The name of the assistant. This string cannot contain - carriage return, newline, or tab characters. - :attr str description: (optional) The description of the assistant. This string + :param str assistant_id: (optional) The unique identifier of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This string cannot contain carriage return, newline, or tab characters. - :attr str language: The language of the assistant. - :attr List[AssistantSkill] assistant_skills: (optional) An array of skill + :param str language: The language of the assistant. + :param List[AssistantSkill] assistant_skills: (optional) An array of skill references identifying the skills associated with the assistant. - :attr List[EnvironmentReference] assistant_environments: (optional) An array of + :param List[EnvironmentReference] assistant_environments: (optional) An array of objects describing the environments defined for the assistant. """ def __init__( - self, - language: str, - *, - assistant_id: str = None, - name: str = None, - description: str = None, - assistant_skills: List['AssistantSkill'] = None, - assistant_environments: List['EnvironmentReference'] = None + self, + language: str, + *, + assistant_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + assistant_skills: Optional[List['AssistantSkill']] = None, + assistant_environments: Optional[List['EnvironmentReference']] = None, ) -> None: """ Initialize a AssistantData object. @@ -1996,27 +2157,27 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'AssistantData': """Initialize a AssistantData object from a json dictionary.""" args = {} - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in AssistantData JSON' ) - if 'assistant_skills' in _dict: + if (assistant_skills := _dict.get('assistant_skills')) is not None: args['assistant_skills'] = [ - AssistantSkill.from_dict(v) - for v in _dict.get('assistant_skills') + AssistantSkill.from_dict(v) for v in assistant_skills ] - if 'assistant_environments' in _dict: + if (assistant_environments := + _dict.get('assistant_environments')) is not None: args['assistant_environments'] = [ EnvironmentReference.from_dict(v) - for v in _dict.get('assistant_environments') + for v in assistant_environments ] return cls(**args) @@ -2076,15 +2237,20 @@ def __ne__(self, other: 'AssistantData') -> bool: return not self == other -class AssistantSkill(): +class AssistantSkill: """ AssistantSkill. - :attr str skill_id: The skill ID of the skill. - :attr str type: (optional) The type of the skill. + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. """ - def __init__(self, skill_id: str, *, type: str = None) -> None: + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + ) -> None: """ Initialize a AssistantSkill object. @@ -2098,14 +2264,14 @@ def __init__(self, skill_id: str, *, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'AssistantSkill': """Initialize a AssistantSkill object from a json dictionary.""" args = {} - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id else: raise ValueError( 'Required property \'skill_id\' not present in AssistantSkill JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -2144,23 +2310,28 @@ class TypeEnum(str, Enum): """ The type of the skill. """ + DIALOG = 'dialog' ACTION = 'action' SEARCH = 'search' -class AssistantState(): +class AssistantState: """ Status information about the skills for the assistant. Included in responses only if **status**=`Available`. - :attr bool action_disabled: Whether the action skill is disabled in the draft + :param bool action_disabled: Whether the action skill is disabled in the draft environment. - :attr bool dialog_disabled: Whether the dialog skill is disabled in the draft + :param bool dialog_disabled: Whether the dialog skill is disabled in the draft environment. """ - def __init__(self, action_disabled: bool, dialog_disabled: bool) -> None: + def __init__( + self, + action_disabled: bool, + dialog_disabled: bool, + ) -> None: """ Initialize a AssistantState object. @@ -2176,14 +2347,14 @@ def __init__(self, action_disabled: bool, dialog_disabled: bool) -> None: def from_dict(cls, _dict: Dict) -> 'AssistantState': """Initialize a AssistantState object from a json dictionary.""" args = {} - if 'action_disabled' in _dict: - args['action_disabled'] = _dict.get('action_disabled') + if (action_disabled := _dict.get('action_disabled')) is not None: + args['action_disabled'] = action_disabled else: raise ValueError( 'Required property \'action_disabled\' not present in AssistantState JSON' ) - if 'dialog_disabled' in _dict: - args['dialog_disabled'] = _dict.get('dialog_disabled') + if (dialog_disabled := _dict.get('dialog_disabled')) is not None: + args['dialog_disabled'] = dialog_disabled else: raise ValueError( 'Required property \'dialog_disabled\' not present in AssistantState JSON' @@ -2225,17 +2396,21 @@ def __ne__(self, other: 'AssistantState') -> bool: return not self == other -class BaseEnvironmentOrchestration(): +class BaseEnvironmentOrchestration: """ The search skill orchestration settings for the environment. - :attr bool search_skill_fallback: (optional) Whether assistants deployed to the + :param bool search_skill_fallback: (optional) Whether assistants deployed to the environment fall back to a search skill when responding to messages that do not match any intent. If no search skill is configured for the assistant, this property is ignored. """ - def __init__(self, *, search_skill_fallback: bool = None) -> None: + def __init__( + self, + *, + search_skill_fallback: Optional[bool] = None, + ) -> None: """ Initialize a BaseEnvironmentOrchestration object. @@ -2250,8 +2425,9 @@ def __init__(self, *, search_skill_fallback: bool = None) -> None: def from_dict(cls, _dict: Dict) -> 'BaseEnvironmentOrchestration': """Initialize a BaseEnvironmentOrchestration object from a json dictionary.""" args = {} - if 'search_skill_fallback' in _dict: - args['search_skill_fallback'] = _dict.get('search_skill_fallback') + if (search_skill_fallback := + _dict.get('search_skill_fallback')) is not None: + args['search_skill_fallback'] = search_skill_fallback return cls(**args) @classmethod @@ -2286,14 +2462,18 @@ def __ne__(self, other: 'BaseEnvironmentOrchestration') -> bool: return not self == other -class BaseEnvironmentReleaseReference(): +class BaseEnvironmentReleaseReference: """ An object describing the release that is currently deployed in the environment. - :attr str release: (optional) The name of the deployed release. + :param str release: (optional) The name of the deployed release. """ - def __init__(self, *, release: str = None) -> None: + def __init__( + self, + *, + release: Optional[str] = None, + ) -> None: """ Initialize a BaseEnvironmentReleaseReference object. @@ -2305,8 +2485,8 @@ def __init__(self, *, release: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'BaseEnvironmentReleaseReference': """Initialize a BaseEnvironmentReleaseReference object from a json dictionary.""" args = {} - if 'release' in _dict: - args['release'] = _dict.get('release') + if (release := _dict.get('release')) is not None: + args['release'] = release return cls(**args) @classmethod @@ -2340,23 +2520,25 @@ def __ne__(self, other: 'BaseEnvironmentReleaseReference') -> bool: return not self == other -class BulkClassifyOutput(): +class BulkClassifyOutput: """ BulkClassifyOutput. - :attr BulkClassifyUtterance input: (optional) The user input utterance to + :param BulkClassifyUtterance input: (optional) The user input utterance to classify. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified + :param List[RuntimeEntity] entities: (optional) An array of entities identified in the utterance. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in the utterance. """ - def __init__(self, - *, - input: 'BulkClassifyUtterance' = None, - entities: List['RuntimeEntity'] = None, - intents: List['RuntimeIntent'] = None) -> None: + def __init__( + self, + *, + input: Optional['BulkClassifyUtterance'] = None, + entities: Optional[List['RuntimeEntity']] = None, + intents: Optional[List['RuntimeIntent']] = None, + ) -> None: """ Initialize a BulkClassifyOutput object. @@ -2375,16 +2557,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'BulkClassifyOutput': """Initialize a BulkClassifyOutput object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = BulkClassifyUtterance.from_dict(_dict.get('input')) - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] + if (input := _dict.get('input')) is not None: + args['input'] = BulkClassifyUtterance.from_dict(input) + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] return cls(**args) @classmethod @@ -2437,15 +2615,19 @@ def __ne__(self, other: 'BulkClassifyOutput') -> bool: return not self == other -class BulkClassifyResponse(): +class BulkClassifyResponse: """ BulkClassifyResponse. - :attr List[BulkClassifyOutput] output: (optional) An array of objects that + :param List[BulkClassifyOutput] output: (optional) An array of objects that contain classification information for the submitted input utterances. """ - def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: + def __init__( + self, + *, + output: Optional[List['BulkClassifyOutput']] = None, + ) -> None: """ Initialize a BulkClassifyResponse object. @@ -2458,10 +2640,8 @@ def __init__(self, *, output: List['BulkClassifyOutput'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyResponse': """Initialize a BulkClassifyResponse object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = [ - BulkClassifyOutput.from_dict(v) for v in _dict.get('output') - ] + if (output := _dict.get('output')) is not None: + args['output'] = [BulkClassifyOutput.from_dict(v) for v in output] return cls(**args) @classmethod @@ -2501,14 +2681,17 @@ def __ne__(self, other: 'BulkClassifyResponse') -> bool: return not self == other -class BulkClassifyUtterance(): +class BulkClassifyUtterance: """ The user input utterance to classify. - :attr str text: The text of the input utterance. + :param str text: The text of the input utterance. """ - def __init__(self, text: str) -> None: + def __init__( + self, + text: str, + ) -> None: """ Initialize a BulkClassifyUtterance object. @@ -2520,8 +2703,8 @@ def __init__(self, text: str) -> None: def from_dict(cls, _dict: Dict) -> 'BulkClassifyUtterance': """Initialize a BulkClassifyUtterance object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in BulkClassifyUtterance JSON' @@ -2559,16 +2742,21 @@ def __ne__(self, other: 'BulkClassifyUtterance') -> bool: return not self == other -class CaptureGroup(): +class CaptureGroup: """ CaptureGroup. - :attr str group: A recognized capture group for the entity. - :attr List[int] location: (optional) Zero-based character offsets that indicate + :param str group: A recognized capture group for the entity. + :param List[int] location: (optional) Zero-based character offsets that indicate where the entity value begins and ends in the input text. """ - def __init__(self, group: str, *, location: List[int] = None) -> None: + def __init__( + self, + group: str, + *, + location: Optional[List[int]] = None, + ) -> None: """ Initialize a CaptureGroup object. @@ -2583,13 +2771,13 @@ def __init__(self, group: str, *, location: List[int] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CaptureGroup': """Initialize a CaptureGroup object from a json dictionary.""" args = {} - if 'group' in _dict: - args['group'] = _dict.get('group') + if (group := _dict.get('group')) is not None: + args['group'] = group else: raise ValueError( 'Required property \'group\' not present in CaptureGroup JSON') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (location := _dict.get('location')) is not None: + args['location'] = location return cls(**args) @classmethod @@ -2625,18 +2813,21 @@ def __ne__(self, other: 'CaptureGroup') -> bool: return not self == other -class ChannelTransferInfo(): +class ChannelTransferInfo: """ Information used by an integration to transfer the conversation to a different channel. - :attr ChannelTransferTarget target: An object specifying target channels + :param ChannelTransferTarget target: An object specifying target channels available for the transfer. Each property of this object represents an available transfer target. Currently, the only supported property is **chat**, representing the web chat integration. """ - def __init__(self, target: 'ChannelTransferTarget') -> None: + def __init__( + self, + target: 'ChannelTransferTarget', + ) -> None: """ Initialize a ChannelTransferInfo object. @@ -2651,9 +2842,8 @@ def __init__(self, target: 'ChannelTransferTarget') -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferInfo': """Initialize a ChannelTransferInfo object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = ChannelTransferTarget.from_dict( - _dict.get('target')) + if (target := _dict.get('target')) is not None: + args['target'] = ChannelTransferTarget.from_dict(target) else: raise ValueError( 'Required property \'target\' not present in ChannelTransferInfo JSON' @@ -2694,17 +2884,21 @@ def __ne__(self, other: 'ChannelTransferInfo') -> bool: return not self == other -class ChannelTransferTarget(): +class ChannelTransferTarget: """ An object specifying target channels available for the transfer. Each property of this object represents an available transfer target. Currently, the only supported property is **chat**, representing the web chat integration. - :attr ChannelTransferTargetChat chat: (optional) Information for transferring to - the web chat integration. + :param ChannelTransferTargetChat chat: (optional) Information for transferring + to the web chat integration. """ - def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: + def __init__( + self, + *, + chat: Optional['ChannelTransferTargetChat'] = None, + ) -> None: """ Initialize a ChannelTransferTarget object. @@ -2717,9 +2911,8 @@ def __init__(self, *, chat: 'ChannelTransferTargetChat' = None) -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferTarget': """Initialize a ChannelTransferTarget object from a json dictionary.""" args = {} - if 'chat' in _dict: - args['chat'] = ChannelTransferTargetChat.from_dict( - _dict.get('chat')) + if (chat := _dict.get('chat')) is not None: + args['chat'] = ChannelTransferTargetChat.from_dict(chat) return cls(**args) @classmethod @@ -2756,14 +2949,18 @@ def __ne__(self, other: 'ChannelTransferTarget') -> bool: return not self == other -class ChannelTransferTargetChat(): +class ChannelTransferTargetChat: """ Information for transferring to the web chat integration. - :attr str url: (optional) The URL of the target web chat. + :param str url: (optional) The URL of the target web chat. """ - def __init__(self, *, url: str = None) -> None: + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: """ Initialize a ChannelTransferTargetChat object. @@ -2775,8 +2972,8 @@ def __init__(self, *, url: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ChannelTransferTargetChat': """Initialize a ChannelTransferTargetChat object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url return cls(**args) @classmethod @@ -2810,24 +3007,26 @@ def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: return not self == other -class DialogLogMessage(): +class DialogLogMessage: """ Dialog log message details. - :attr str level: The severity of the log message. - :attr str message: The text of the log message. - :attr str code: A code that indicates the category to which the error message + :param str level: The severity of the log message. + :param str message: The text of the log message. + :param str code: A code that indicates the category to which the error message belongs. - :attr LogMessageSource source: (optional) An object that identifies the dialog + :param LogMessageSource source: (optional) An object that identifies the dialog element that generated the error message. """ - def __init__(self, - level: str, - message: str, - code: str, - *, - source: 'LogMessageSource' = None) -> None: + def __init__( + self, + level: str, + message: str, + code: str, + *, + source: Optional['LogMessageSource'] = None, + ) -> None: """ Initialize a DialogLogMessage object. @@ -2847,26 +3046,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': """Initialize a DialogLogMessage object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') + if (level := _dict.get('level')) is not None: + args['level'] = level else: raise ValueError( 'Required property \'level\' not present in DialogLogMessage JSON' ) - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message else: raise ValueError( 'Required property \'message\' not present in DialogLogMessage JSON' ) - if 'code' in _dict: - args['code'] = _dict.get('code') + if (code := _dict.get('code')) is not None: + args['code'] = code else: raise ValueError( 'Required property \'code\' not present in DialogLogMessage JSON' ) - if 'source' in _dict: - args['source'] = LogMessageSource.from_dict(_dict.get('source')) + if (source := _dict.get('source')) is not None: + args['source'] = LogMessageSource.from_dict(source) return cls(**args) @classmethod @@ -2912,32 +3111,35 @@ class LevelEnum(str, Enum): """ The severity of the log message. """ + INFO = 'info' ERROR = 'error' WARN = 'warn' -class DialogNodeAction(): +class DialogNodeAction: """ DialogNodeAction. - :attr str name: The name of the action. - :attr str type: (optional) The type of action to invoke. - :attr dict parameters: (optional) A map of key/value pairs to be provided to the - action. - :attr str result_variable: The location in the dialog context where the result + :param str name: The name of the action. + :param str type: (optional) The type of action to invoke. + :param dict parameters: (optional) A map of key/value pairs to be provided to + the action. + :param str result_variable: The location in the dialog context where the result of the action is stored. - :attr str credentials: (optional) The name of the context variable that the + :param str credentials: (optional) The name of the context variable that the client application will use to pass in credentials for the action. """ - def __init__(self, - name: str, - result_variable: str, - *, - type: str = None, - parameters: dict = None, - credentials: str = None) -> None: + def __init__( + self, + name: str, + result_variable: str, + *, + type: Optional[str] = None, + parameters: Optional[dict] = None, + credentials: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeAction object. @@ -2960,24 +3162,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeAction': """Initialize a DialogNodeAction object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in DialogNodeAction JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'parameters' in _dict: - args['parameters'] = _dict.get('parameters') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (parameters := _dict.get('parameters')) is not None: + args['parameters'] = parameters + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable else: raise ValueError( 'Required property \'result_variable\' not present in DialogNodeAction JSON' ) - if 'credentials' in _dict: - args['credentials'] = _dict.get('credentials') + if (credentials := _dict.get('credentials')) is not None: + args['credentials'] = credentials return cls(**args) @classmethod @@ -3023,20 +3225,25 @@ class TypeEnum(str, Enum): """ The type of action to invoke. """ + CLIENT = 'client' SERVER = 'server' WEB_ACTION = 'web-action' CLOUD_FUNCTION = 'cloud-function' -class DialogNodeOutputConnectToAgentTransferInfo(): +class DialogNodeOutputConnectToAgentTransferInfo: """ Routing or other contextual information to be used by target service desk systems. - :attr dict target: (optional) + :param dict target: (optional) """ - def __init__(self, *, target: dict = None) -> None: + def __init__( + self, + *, + target: Optional[dict] = None, + ) -> None: """ Initialize a DialogNodeOutputConnectToAgentTransferInfo object. @@ -3049,8 +3256,8 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputConnectToAgentTransferInfo': """Initialize a DialogNodeOutputConnectToAgentTransferInfo object from a json dictionary.""" args = {} - if 'target' in _dict: - args['target'] = _dict.get('target') + if (target := _dict.get('target')) is not None: + args['target'] = target return cls(**args) @classmethod @@ -3086,17 +3293,20 @@ def __ne__(self, return not self == other -class DialogNodeOutputOptionsElement(): +class DialogNodeOutputOptionsElement: """ DialogNodeOutputOptionsElement. - :attr str label: The user-facing label for the option. - :attr DialogNodeOutputOptionsElementValue value: An object defining the message + :param str label: The user-facing label for the option. + :param DialogNodeOutputOptionsElementValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding option. """ - def __init__(self, label: str, - value: 'DialogNodeOutputOptionsElementValue') -> None: + def __init__( + self, + label: str, + value: 'DialogNodeOutputOptionsElementValue', + ) -> None: """ Initialize a DialogNodeOutputOptionsElement object. @@ -3112,15 +3322,14 @@ def __init__(self, label: str, def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElement': """Initialize a DialogNodeOutputOptionsElement object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') + if (label := _dict.get('label')) is not None: + args['label'] = label else: raise ValueError( 'Required property \'label\' not present in DialogNodeOutputOptionsElement JSON' ) - if 'value' in _dict: - args['value'] = DialogNodeOutputOptionsElementValue.from_dict( - _dict.get('value')) + if (value := _dict.get('value')) is not None: + args['value'] = DialogNodeOutputOptionsElementValue.from_dict(value) else: raise ValueError( 'Required property \'value\' not present in DialogNodeOutputOptionsElement JSON' @@ -3163,16 +3372,20 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElement') -> bool: return not self == other -class DialogNodeOutputOptionsElementValue(): +class DialogNodeOutputOptionsElementValue: """ An object defining the message input to be sent to the assistant if the user selects the corresponding option. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. """ - def __init__(self, *, input: 'MessageInput' = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + ) -> None: """ Initialize a DialogNodeOutputOptionsElementValue object. @@ -3185,8 +3398,8 @@ def __init__(self, *, input: 'MessageInput' = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputOptionsElementValue': """Initialize a DialogNodeOutputOptionsElementValue object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) return cls(**args) @classmethod @@ -3223,22 +3436,24 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: return not self == other -class DialogNodeVisited(): +class DialogNodeVisited: """ An objects containing detailed diagnostic information about a dialog node that was visited during processing of the input message. - :attr str dialog_node: (optional) A dialog node that was visited during + :param str dialog_node: (optional) A dialog node that was visited during processing of the input message. - :attr str title: (optional) The title of the dialog node. - :attr str conditions: (optional) The conditions that trigger the dialog node. + :param str title: (optional) The title of the dialog node. + :param str conditions: (optional) The conditions that trigger the dialog node. """ - def __init__(self, - *, - dialog_node: str = None, - title: str = None, - conditions: str = None) -> None: + def __init__( + self, + *, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + conditions: Optional[str] = None, + ) -> None: """ Initialize a DialogNodeVisited object. @@ -3256,12 +3471,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogNodeVisited': """Initialize a DialogNodeVisited object from a json dictionary.""" args = {} - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'conditions' in _dict: - args['conditions'] = _dict.get('conditions') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (conditions := _dict.get('conditions')) is not None: + args['conditions'] = conditions return cls(**args) @classmethod @@ -3299,28 +3514,30 @@ def __ne__(self, other: 'DialogNodeVisited') -> bool: return not self == other -class DialogSuggestion(): +class DialogSuggestion: """ DialogSuggestion. - :attr str label: The user-facing label for the suggestion. This label is taken + :param str label: The user-facing label for the suggestion. This label is taken from the **title** or **user_label** property of the corresponding dialog node, depending on the disambiguation options. - :attr DialogSuggestionValue value: An object defining the message input to be + :param DialogSuggestionValue value: An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. **Note:** This entire message input object must be included in the request body of the next message sent to the assistant. Do not modify or remove any of the included properties. - :attr dict output: (optional) The dialog output that will be returned from the + :param dict output: (optional) The dialog output that will be returned from the Watson Assistant service if the user selects the corresponding option. """ - def __init__(self, - label: str, - value: 'DialogSuggestionValue', - *, - output: dict = None) -> None: + def __init__( + self, + label: str, + value: 'DialogSuggestionValue', + *, + output: Optional[dict] = None, + ) -> None: """ Initialize a DialogSuggestion object. @@ -3344,20 +3561,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DialogSuggestion': """Initialize a DialogSuggestion object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') + if (label := _dict.get('label')) is not None: + args['label'] = label else: raise ValueError( 'Required property \'label\' not present in DialogSuggestion JSON' ) - if 'value' in _dict: - args['value'] = DialogSuggestionValue.from_dict(_dict.get('value')) + if (value := _dict.get('value')) is not None: + args['value'] = DialogSuggestionValue.from_dict(value) else: raise ValueError( 'Required property \'value\' not present in DialogSuggestion JSON' ) - if 'output' in _dict: - args['output'] = _dict.get('output') + if (output := _dict.get('output')) is not None: + args['output'] = output return cls(**args) @classmethod @@ -3398,7 +3615,7 @@ def __ne__(self, other: 'DialogSuggestion') -> bool: return not self == other -class DialogSuggestionValue(): +class DialogSuggestionValue: """ An object defining the message input to be sent to the assistant if the user selects the corresponding disambiguation option. @@ -3406,11 +3623,15 @@ class DialogSuggestionValue(): the next message sent to the assistant. Do not modify or remove any of the included properties. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. """ - def __init__(self, *, input: 'MessageInput' = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + ) -> None: """ Initialize a DialogSuggestionValue object. @@ -3423,8 +3644,8 @@ def __init__(self, *, input: 'MessageInput' = None) -> None: def from_dict(cls, _dict: Dict) -> 'DialogSuggestionValue': """Initialize a DialogSuggestionValue object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) return cls(**args) @classmethod @@ -3461,46 +3682,48 @@ def __ne__(self, other: 'DialogSuggestionValue') -> bool: return not self == other -class Environment(): +class Environment: """ Environment. - :attr str name: (optional) The name of the environment. - :attr str description: (optional) The description of the environment. - :attr str assistant_id: (optional) The assistant ID of the assistant the + :param str name: (optional) The name of the environment. + :param str description: (optional) The description of the environment. + :param str assistant_id: (optional) The assistant ID of the assistant the environment is associated with. - :attr str environment_id: (optional) The environment ID of the environment. - :attr str environment: (optional) The type of the environment. All environments + :param str environment_id: (optional) The environment ID of the environment. + :param str environment: (optional) The type of the environment. All environments other than the `draft` and `live` environments have the type `staging`. - :attr BaseEnvironmentReleaseReference release_reference: (optional) An object + :param BaseEnvironmentReleaseReference release_reference: (optional) An object describing the release that is currently deployed in the environment. - :attr BaseEnvironmentOrchestration orchestration: (optional) The search skill + :param BaseEnvironmentOrchestration orchestration: (optional) The search skill orchestration settings for the environment. - :attr int session_timeout: The session inactivity timeout setting for the + :param int session_timeout: The session inactivity timeout setting for the environment (in seconds). - :attr List[IntegrationReference] integration_references: (optional) An array of + :param List[IntegrationReference] integration_references: (optional) An array of objects describing the integrations that exist in the environment. - :attr List[EnvironmentSkill] skill_references: An array of objects identifying + :param List[EnvironmentSkill] skill_references: An array of objects identifying the skills (such as action and dialog) that exist in the environment. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - session_timeout: int, - skill_references: List['EnvironmentSkill'], - *, - name: str = None, - description: str = None, - assistant_id: str = None, - environment_id: str = None, - environment: str = None, - release_reference: 'BaseEnvironmentReleaseReference' = None, - orchestration: 'BaseEnvironmentOrchestration' = None, - integration_references: List['IntegrationReference'] = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + session_timeout: int, + skill_references: List['EnvironmentSkill'], + *, + name: Optional[str] = None, + description: Optional[str] = None, + assistant_id: Optional[str] = None, + environment_id: Optional[str] = None, + environment: Optional[str] = None, + release_reference: Optional['BaseEnvironmentReleaseReference'] = None, + orchestration: Optional['BaseEnvironmentOrchestration'] = None, + integration_references: Optional[List['IntegrationReference']] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Environment object. @@ -3529,47 +3752,47 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Environment': """Initialize a Environment object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'environment' in _dict: - args['environment'] = _dict.get('environment') - if 'release_reference' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (environment := _dict.get('environment')) is not None: + args['environment'] = environment + if (release_reference := _dict.get('release_reference')) is not None: args[ 'release_reference'] = BaseEnvironmentReleaseReference.from_dict( - _dict.get('release_reference')) - if 'orchestration' in _dict: + release_reference) + if (orchestration := _dict.get('orchestration')) is not None: args['orchestration'] = BaseEnvironmentOrchestration.from_dict( - _dict.get('orchestration')) - if 'session_timeout' in _dict: - args['session_timeout'] = _dict.get('session_timeout') + orchestration) + if (session_timeout := _dict.get('session_timeout')) is not None: + args['session_timeout'] = session_timeout else: raise ValueError( 'Required property \'session_timeout\' not present in Environment JSON' ) - if 'integration_references' in _dict: + if (integration_references := + _dict.get('integration_references')) is not None: args['integration_references'] = [ IntegrationReference.from_dict(v) - for v in _dict.get('integration_references') + for v in integration_references ] - if 'skill_references' in _dict: + if (skill_references := _dict.get('skill_references')) is not None: args['skill_references'] = [ - EnvironmentSkill.from_dict(v) - for v in _dict.get('skill_references') + EnvironmentSkill.from_dict(v) for v in skill_references ] else: raise ValueError( 'Required property \'skill_references\' not present in Environment JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -3653,18 +3876,21 @@ def __ne__(self, other: 'Environment') -> bool: return not self == other -class EnvironmentCollection(): +class EnvironmentCollection: """ EnvironmentCollection. - :attr List[Environment] environments: An array of objects describing the + :param List[Environment] environments: An array of objects describing the environments associated with an assistant. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, environments: List['Environment'], - pagination: 'Pagination') -> None: + def __init__( + self, + environments: List['Environment'], + pagination: 'Pagination', + ) -> None: """ Initialize a EnvironmentCollection object. @@ -3680,16 +3906,16 @@ def __init__(self, environments: List['Environment'], def from_dict(cls, _dict: Dict) -> 'EnvironmentCollection': """Initialize a EnvironmentCollection object from a json dictionary.""" args = {} - if 'environments' in _dict: + if (environments := _dict.get('environments')) is not None: args['environments'] = [ - Environment.from_dict(v) for v in _dict.get('environments') + Environment.from_dict(v) for v in environments ] else: raise ValueError( 'Required property \'environments\' not present in EnvironmentCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in EnvironmentCollection JSON' @@ -3738,21 +3964,23 @@ def __ne__(self, other: 'EnvironmentCollection') -> bool: return not self == other -class EnvironmentReference(): +class EnvironmentReference: """ EnvironmentReference. - :attr str name: (optional) The name of the environment. - :attr str environment_id: (optional) The unique identifier of the environment. - :attr str environment: (optional) The type of the environment. All environments + :param str name: (optional) The name of the environment. + :param str environment_id: (optional) The unique identifier of the environment. + :param str environment: (optional) The type of the environment. All environments other than the draft and live environments have the type `staging`. """ - def __init__(self, - *, - name: str = None, - environment_id: str = None, - environment: str = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + environment_id: Optional[str] = None, + environment: Optional[str] = None, + ) -> None: """ Initialize a EnvironmentReference object. @@ -3766,12 +3994,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnvironmentReference': """Initialize a EnvironmentReference object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'environment' in _dict: - args['environment'] = _dict.get('environment') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (environment := _dict.get('environment')) is not None: + args['environment'] = environment return cls(**args) @classmethod @@ -3815,34 +4043,37 @@ class EnvironmentEnum(str, Enum): The type of the environment. All environments other than the draft and live environments have the type `staging`. """ + DRAFT = 'draft' LIVE = 'live' STAGING = 'staging' -class EnvironmentSkill(): +class EnvironmentSkill: """ EnvironmentSkill. - :attr str skill_id: The skill ID of the skill. - :attr str type: (optional) The type of the skill. - :attr bool disabled: (optional) Whether the skill is disabled. A disabled skill + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param bool disabled: (optional) Whether the skill is disabled. A disabled skill in the draft environment does not handle any messages at run time, and it is not included in saved releases. - :attr str snapshot: (optional) The name of the skill snapshot that is deployed + :param str snapshot: (optional) The name of the skill snapshot that is deployed to the environment (for example, `draft` or `1`). - :attr str skill_reference: (optional) The type of skill identified by the skill + :param str skill_reference: (optional) The type of skill identified by the skill reference. The possible values are `main skill` (for a dialog skill), `actions skill`, and `search skill`. """ - def __init__(self, - skill_id: str, - *, - type: str = None, - disabled: bool = None, - snapshot: str = None, - skill_reference: str = None) -> None: + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + disabled: Optional[bool] = None, + snapshot: Optional[str] = None, + skill_reference: Optional[str] = None, + ) -> None: """ Initialize a EnvironmentSkill object. @@ -3867,20 +4098,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnvironmentSkill': """Initialize a EnvironmentSkill object from a json dictionary.""" args = {} - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id else: raise ValueError( 'Required property \'skill_id\' not present in EnvironmentSkill JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'disabled' in _dict: - args['disabled'] = _dict.get('disabled') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') - if 'skill_reference' in _dict: - args['skill_reference'] = _dict.get('skill_reference') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (disabled := _dict.get('disabled')) is not None: + args['disabled'] = disabled + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot + if (skill_reference := _dict.get('skill_reference')) is not None: + args['skill_reference'] = skill_reference return cls(**args) @classmethod @@ -3926,20 +4157,26 @@ class TypeEnum(str, Enum): """ The type of the skill. """ + DIALOG = 'dialog' ACTION = 'action' SEARCH = 'search' -class IntegrationReference(): +class IntegrationReference: """ IntegrationReference. - :attr str integration_id: (optional) The integration ID of the integration. - :attr str type: (optional) The type of the integration. + :param str integration_id: (optional) The integration ID of the integration. + :param str type: (optional) The type of the integration. """ - def __init__(self, *, integration_id: str = None, type: str = None) -> None: + def __init__( + self, + *, + integration_id: Optional[str] = None, + type: Optional[str] = None, + ) -> None: """ Initialize a IntegrationReference object. @@ -3954,10 +4191,10 @@ def __init__(self, *, integration_id: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'IntegrationReference': """Initialize a IntegrationReference object from a json dictionary.""" args = {} - if 'integration_id' in _dict: - args['integration_id'] = _dict.get('integration_id') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (integration_id := _dict.get('integration_id')) is not None: + args['integration_id'] = integration_id + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -3993,42 +4230,44 @@ def __ne__(self, other: 'IntegrationReference') -> bool: return not self == other -class Log(): +class Log: """ Log. - :attr str log_id: A unique identifier for the logged event. - :attr MessageRequest request: A stateful message request formatted for the + :param str log_id: A unique identifier for the logged event. + :param MessageRequest request: A stateful message request formatted for the Watson Assistant service. - :attr MessageResponse response: A response from the Watson Assistant service. - :attr str assistant_id: Unique identifier of the assistant. - :attr str session_id: The ID of the session the message was part of. - :attr str skill_id: The unique identifier of the skill that responded to the + :param MessageResponse response: A response from the Watson Assistant service. + :param str assistant_id: Unique identifier of the assistant. + :param str session_id: The ID of the session the message was part of. + :param str skill_id: The unique identifier of the skill that responded to the message. - :attr str snapshot: The name of the snapshot (dialog skill version) that + :param str snapshot: The name of the snapshot (dialog skill version) that responded to the message (for example, `draft`). - :attr str request_timestamp: The timestamp for receipt of the message. - :attr str response_timestamp: The timestamp for the system response to the + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the message. - :attr str language: The language of the assistant to which the message request + :param str language: The language of the assistant to which the message request was made. - :attr str customer_id: (optional) The customer ID specified for the message, if + :param str customer_id: (optional) The customer ID specified for the message, if any. """ - def __init__(self, - log_id: str, - request: 'MessageRequest', - response: 'MessageResponse', - assistant_id: str, - session_id: str, - skill_id: str, - snapshot: str, - request_timestamp: str, - response_timestamp: str, - language: str, - *, - customer_id: str = None) -> None: + def __init__( + self, + log_id: str, + request: 'MessageRequest', + response: 'MessageResponse', + assistant_id: str, + session_id: str, + skill_id: str, + snapshot: str, + request_timestamp: str, + response_timestamp: str, + language: str, + *, + customer_id: Optional[str] = None, + ) -> None: """ Initialize a Log object. @@ -4067,60 +4306,60 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Log': """Initialize a Log object from a json dictionary.""" args = {} - if 'log_id' in _dict: - args['log_id'] = _dict.get('log_id') + if (log_id := _dict.get('log_id')) is not None: + args['log_id'] = log_id else: raise ValueError( 'Required property \'log_id\' not present in Log JSON') - if 'request' in _dict: - args['request'] = MessageRequest.from_dict(_dict.get('request')) + if (request := _dict.get('request')) is not None: + args['request'] = MessageRequest.from_dict(request) else: raise ValueError( 'Required property \'request\' not present in Log JSON') - if 'response' in _dict: - args['response'] = MessageResponse.from_dict(_dict.get('response')) + if (response := _dict.get('response')) is not None: + args['response'] = MessageResponse.from_dict(response) else: raise ValueError( 'Required property \'response\' not present in Log JSON') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id else: raise ValueError( 'Required property \'assistant_id\' not present in Log JSON') - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id else: raise ValueError( 'Required property \'session_id\' not present in Log JSON') - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id else: raise ValueError( 'Required property \'skill_id\' not present in Log JSON') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot else: raise ValueError( 'Required property \'snapshot\' not present in Log JSON') - if 'request_timestamp' in _dict: - args['request_timestamp'] = _dict.get('request_timestamp') + if (request_timestamp := _dict.get('request_timestamp')) is not None: + args['request_timestamp'] = request_timestamp else: raise ValueError( 'Required property \'request_timestamp\' not present in Log JSON' ) - if 'response_timestamp' in _dict: - args['response_timestamp'] = _dict.get('response_timestamp') + if (response_timestamp := _dict.get('response_timestamp')) is not None: + args['response_timestamp'] = response_timestamp else: raise ValueError( 'Required property \'response_timestamp\' not present in Log JSON' ) - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Log JSON') - if 'customer_id' in _dict: - args['customer_id'] = _dict.get('customer_id') + if (customer_id := _dict.get('customer_id')) is not None: + args['customer_id'] = customer_id return cls(**args) @classmethod @@ -4183,16 +4422,20 @@ def __ne__(self, other: 'Log') -> bool: return not self == other -class LogCollection(): +class LogCollection: """ LogCollection. - :attr List[Log] logs: An array of objects describing log events. - :attr LogPagination pagination: The pagination data for the returned objects. + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: + def __init__( + self, + logs: List['Log'], + pagination: 'LogPagination', + ) -> None: """ Initialize a LogCollection object. @@ -4208,14 +4451,13 @@ def __init__(self, logs: List['Log'], pagination: 'LogPagination') -> None: def from_dict(cls, _dict: Dict) -> 'LogCollection': """Initialize a LogCollection object from a json dictionary.""" args = {} - if 'logs' in _dict: - args['logs'] = [Log.from_dict(v) for v in _dict.get('logs')] + if (logs := _dict.get('logs')) is not None: + args['logs'] = [Log.from_dict(v) for v in logs] else: raise ValueError( 'Required property \'logs\' not present in LogCollection JSON') - if 'pagination' in _dict: - args['pagination'] = LogPagination.from_dict( - _dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = LogPagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in LogCollection JSON' @@ -4264,13 +4506,13 @@ def __ne__(self, other: 'LogCollection') -> bool: return not self == other -class LogMessageSource(): +class LogMessageSource: """ An object that identifies the dialog element that generated the error message. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a LogMessageSource object. @@ -4288,13 +4530,11 @@ def from_dict(cls, _dict: Dict) -> 'LogMessageSource': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'LogMessageSource'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) + msg = "Cannot convert dictionary into an instance of base class 'LogMessageSource'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) raise Exception(msg) @classmethod @@ -4324,22 +4564,24 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class LogPagination(): +class LogPagination: """ The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). - :attr str next_url: (optional) The URL that will return the next page of + :param str next_url: (optional) The URL that will return the next page of results, if any. - :attr int matched: (optional) Reserved for future use. - :attr str next_cursor: (optional) A token identifying the next page of results. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, - *, - next_url: str = None, - matched: int = None, - next_cursor: str = None) -> None: + def __init__( + self, + *, + next_url: Optional[str] = None, + matched: Optional[int] = None, + next_cursor: Optional[str] = None, + ) -> None: """ Initialize a LogPagination object. @@ -4357,12 +4599,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogPagination': """Initialize a LogPagination object from a json dictionary.""" args = {} - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod @@ -4400,24 +4642,26 @@ def __ne__(self, other: 'LogPagination') -> bool: return not self == other -class MessageContext(): +class MessageContext: """ MessageContext. - :attr MessageContextGlobal global_: (optional) Session context data that is + :param MessageContextGlobal global_: (optional) Session context data that is shared by all skills used by the assistant. - :attr MessageContextSkills skills: (optional) Context data specific to + :param MessageContextSkills skills: (optional) Context data specific to particular skills used by the assistant. - :attr dict integrations: (optional) An object containing context data that is + :param dict integrations: (optional) An object containing context data that is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - def __init__(self, - *, - global_: 'MessageContextGlobal' = None, - skills: 'MessageContextSkills' = None, - integrations: dict = None) -> None: + def __init__( + self, + *, + global_: Optional['MessageContextGlobal'] = None, + skills: Optional['MessageContextSkills'] = None, + integrations: Optional[dict] = None, + ) -> None: """ Initialize a MessageContext object. @@ -4437,13 +4681,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContext': """Initialize a MessageContext object from a json dictionary.""" args = {} - if 'global' in _dict: - args['global_'] = MessageContextGlobal.from_dict( - _dict.get('global')) - if 'skills' in _dict: - args['skills'] = MessageContextSkills.from_dict(_dict.get('skills')) - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if (global_ := _dict.get('global')) is not None: + args['global_'] = MessageContextGlobal.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = MessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations return cls(**args) @classmethod @@ -4487,19 +4730,21 @@ def __ne__(self, other: 'MessageContext') -> bool: return not self == other -class MessageContextGlobal(): +class MessageContextGlobal: """ Session context data that is shared by all skills used by the assistant. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties + :param MessageContextGlobalSystem system: (optional) Built-in system properties that apply to all skills used by the assistant. - :attr str session_id: (optional) The session ID. + :param str session_id: (optional) The session ID. """ - def __init__(self, - *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: + def __init__( + self, + *, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, + ) -> None: """ Initialize a MessageContextGlobal object. @@ -4513,11 +4758,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id return cls(**args) @classmethod @@ -4557,19 +4801,21 @@ def __ne__(self, other: 'MessageContextGlobal') -> bool: return not self == other -class MessageContextGlobalStateless(): +class MessageContextGlobalStateless: """ Session context data that is shared by all skills used by the assistant. - :attr MessageContextGlobalSystem system: (optional) Built-in system properties + :param MessageContextGlobalSystem system: (optional) Built-in system properties that apply to all skills used by the assistant. - :attr str session_id: (optional) The unique identifier of the session. + :param str session_id: (optional) The unique identifier of the session. """ - def __init__(self, - *, - system: 'MessageContextGlobalSystem' = None, - session_id: str = None) -> None: + def __init__( + self, + *, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, + ) -> None: """ Initialize a MessageContextGlobalStateless object. @@ -4584,11 +4830,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': """Initialize a MessageContextGlobalStateless object from a json dictionary.""" args = {} - if 'system' in _dict: - args['system'] = MessageContextGlobalSystem.from_dict( - _dict.get('system')) - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id return cls(**args) @classmethod @@ -4627,13 +4872,13 @@ def __ne__(self, other: 'MessageContextGlobalStateless') -> bool: return not self == other -class MessageContextGlobalSystem(): +class MessageContextGlobalSystem: """ Built-in system properties that apply to all skills used by the assistant. - :attr str timezone: (optional) The user time zone. The assistant uses the time + :param str timezone: (optional) The user time zone. The assistant uses the time zone to correctly resolve relative time references. - :attr str user_id: (optional) A string value that identifies the user who is + :param str user_id: (optional) A string value that identifies the user who is interacting with the assistant. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -4643,27 +4888,27 @@ class MessageContextGlobalSystem(): **Note:** This property is the same as the **user_id** property at the root of the message body. If **user_id** is specified in both locations in a message request, the value specified at the root is used. - :attr int turn_count: (optional) A counter that is automatically incremented + :param int turn_count: (optional) A counter that is automatically incremented 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 + :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. - :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. + :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). This property is included only if the new system entities are enabled for the skill. - :attr str session_start_time: (optional) The time at which the session started. + :param str session_start_time: (optional) The time at which the session started. With the stateful `message` method, the start time is always present, and is set by the service based on the time the session was created. With the stateless `message` method, the start time is set by the service in the response to the @@ -4671,25 +4916,27 @@ class MessageContextGlobalSystem(): subsequent message in the session. This value is a UTC time value formatted according to ISO 8601 (for example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :attr str state: (optional) An encoded string that represents the configuration + :param str state: (optional) An encoded string that represents the configuration state of the assistant at the beginning of the conversation. If you are using the stateless `message` method, save this value and then send it in the context of the subsequent message request to avoid disruptions if there are configuration changes during the conversation (such as a change to a skill the assistant uses). - :attr bool skip_user_input: (optional) For internal use only. + :param bool skip_user_input: (optional) For internal use only. """ - def __init__(self, - *, - timezone: str = None, - user_id: str = None, - turn_count: int = None, - locale: str = None, - reference_time: str = None, - session_start_time: str = None, - state: str = None, - skip_user_input: bool = None) -> None: + def __init__( + self, + *, + timezone: Optional[str] = None, + user_id: Optional[str] = None, + turn_count: Optional[int] = None, + locale: Optional[str] = None, + reference_time: Optional[str] = None, + session_start_time: Optional[str] = None, + state: Optional[str] = None, + skip_user_input: Optional[bool] = None, + ) -> None: """ Initialize a MessageContextGlobalSystem object. @@ -4756,22 +5003,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} - if 'timezone' in _dict: - args['timezone'] = _dict.get('timezone') - if 'user_id' in _dict: - 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') - if 'session_start_time' in _dict: - args['session_start_time'] = _dict.get('session_start_time') - if 'state' in _dict: - args['state'] = _dict.get('state') - if 'skip_user_input' in _dict: - args['skip_user_input'] = _dict.get('skip_user_input') + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + if (turn_count := _dict.get('turn_count')) is not None: + args['turn_count'] = turn_count + if (locale := _dict.get('locale')) is not None: + args['locale'] = locale + if (reference_time := _dict.get('reference_time')) is not None: + args['reference_time'] = reference_time + if (session_start_time := _dict.get('session_start_time')) is not None: + args['session_start_time'] = session_start_time + if (state := _dict.get('state')) is not None: + args['state'] = state + if (skip_user_input := _dict.get('skip_user_input')) is not None: + args['skip_user_input'] = skip_user_input return cls(**args) @classmethod @@ -4830,6 +5077,7 @@ class LocaleEnum(str, Enum): 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' @@ -4847,29 +5095,31 @@ class LocaleEnum(str, Enum): ZH_TW = 'zh-tw' -class MessageContextSkillAction(): +class MessageContextSkillAction: """ Context variables that are used by the action skill. - :attr dict user_defined: (optional) An object containing any arbitrary variables - that can be read and written by a particular skill. - :attr MessageContextSkillSystem system: (optional) System context data used by + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by the skill. - :attr dict action_variables: (optional) An object containing action variables. + :param dict action_variables: (optional) An object containing action variables. Action variables can be accessed only by steps in the same action, and do not persist after the action ends. - :attr dict skill_variables: (optional) An object containing skill variables. (In - the Watson Assistant user interface, skill variables are called _session + :param dict skill_variables: (optional) An object containing skill variables. + (In the Watson Assistant user interface, skill variables are called _session variables_.) Skill variables can be accessed by any action and persist for the duration of the session. """ - def __init__(self, - *, - user_defined: dict = None, - system: 'MessageContextSkillSystem' = None, - action_variables: dict = None, - skill_variables: dict = None) -> None: + def __init__( + self, + *, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + action_variables: Optional[dict] = None, + skill_variables: Optional[dict] = None, + ) -> None: """ Initialize a MessageContextSkillAction object. @@ -4894,15 +5144,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextSkillAction': """Initialize a MessageContextSkillAction object from a json dictionary.""" args = {} - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'system' in _dict: - args['system'] = MessageContextSkillSystem.from_dict( - _dict.get('system')) - if 'action_variables' in _dict: - args['action_variables'] = _dict.get('action_variables') - if 'skill_variables' in _dict: - args['skill_variables'] = _dict.get('skill_variables') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables + if (skill_variables := _dict.get('skill_variables')) is not None: + args['skill_variables'] = skill_variables return cls(**args) @classmethod @@ -4947,20 +5196,22 @@ def __ne__(self, other: 'MessageContextSkillAction') -> bool: return not self == other -class MessageContextSkillDialog(): +class MessageContextSkillDialog: """ Context variables that are used by the dialog skill. - :attr dict user_defined: (optional) An object containing any arbitrary variables - that can be read and written by a particular skill. - :attr MessageContextSkillSystem system: (optional) System context data used by + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by the skill. """ - def __init__(self, - *, - user_defined: dict = None, - system: 'MessageContextSkillSystem' = None) -> None: + def __init__( + self, + *, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + ) -> None: """ Initialize a MessageContextSkillDialog object. @@ -4976,11 +5227,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextSkillDialog': """Initialize a MessageContextSkillDialog object from a json dictionary.""" args = {} - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'system' in _dict: - args['system'] = MessageContextSkillSystem.from_dict( - _dict.get('system')) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) return cls(**args) @classmethod @@ -5019,11 +5269,11 @@ def __ne__(self, other: 'MessageContextSkillDialog') -> bool: return not self == other -class MessageContextSkillSystem(): +class MessageContextSkillSystem: """ System context data used by the skill. - :attr str state: (optional) An encoded string that represents the current + :param str state: (optional) An encoded string that represents the current conversation state. By saving this value and then sending it in the context of a subsequent message request, you can return to an earlier point in the conversation. If you are using stateful sessions, you can also use a stored @@ -5033,7 +5283,12 @@ class MessageContextSkillSystem(): # The set of defined properties for the class _properties = frozenset(['state']) - def __init__(self, *, state: str = None, **kwargs) -> None: + def __init__( + self, + *, + state: Optional[str] = None, + **kwargs, + ) -> None: """ Initialize a MessageContextSkillSystem object. @@ -5052,8 +5307,8 @@ def __init__(self, *, state: str = None, **kwargs) -> None: def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': """Initialize a MessageContextSkillSystem object from a json dictionary.""" args = {} - if 'state' in _dict: - args['state'] = _dict.get('state') + if (state := _dict.get('state')) is not None: + args['state'] = state args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -5117,20 +5372,22 @@ def __ne__(self, other: 'MessageContextSkillSystem') -> bool: return not self == other -class MessageContextSkills(): +class MessageContextSkills: """ Context data specific to particular skills used by the assistant. - :attr MessageContextSkillDialog main_skill: (optional) Context variables that + :param MessageContextSkillDialog main_skill: (optional) Context variables that are used by the dialog skill. - :attr MessageContextSkillAction actions_skill: (optional) Context variables that - are used by the action skill. + :param MessageContextSkillAction actions_skill: (optional) Context variables + that are used by the action skill. """ - def __init__(self, - *, - main_skill: 'MessageContextSkillDialog' = None, - actions_skill: 'MessageContextSkillAction' = None) -> None: + def __init__( + self, + *, + main_skill: Optional['MessageContextSkillDialog'] = None, + actions_skill: Optional['MessageContextSkillAction'] = None, + ) -> None: """ Initialize a MessageContextSkills object. @@ -5146,12 +5403,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': """Initialize a MessageContextSkills object from a json dictionary.""" args = {} - if 'main skill' in _dict: - args['main_skill'] = MessageContextSkillDialog.from_dict( - _dict.get('main skill')) - if 'actions skill' in _dict: + if (main_skill := _dict.get('main skill')) is not None: + args['main_skill'] = MessageContextSkillDialog.from_dict(main_skill) + if (actions_skill := _dict.get('actions skill')) is not None: args['actions_skill'] = MessageContextSkillAction.from_dict( - _dict.get('actions skill')) + actions_skill) return cls(**args) @classmethod @@ -5193,24 +5449,26 @@ def __ne__(self, other: 'MessageContextSkills') -> bool: return not self == other -class MessageContextStateless(): +class MessageContextStateless: """ MessageContextStateless. - :attr MessageContextGlobalStateless global_: (optional) Session context data + :param MessageContextGlobalStateless global_: (optional) Session context data that is shared by all skills used by the assistant. - :attr MessageContextSkills skills: (optional) Context data specific to + :param MessageContextSkills skills: (optional) Context data specific to particular skills used by the assistant. - :attr dict integrations: (optional) An object containing context data that is + :param dict integrations: (optional) An object containing context data that is specific to particular integrations. For more information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - def __init__(self, - *, - global_: 'MessageContextGlobalStateless' = None, - skills: 'MessageContextSkills' = None, - integrations: dict = None) -> None: + def __init__( + self, + *, + global_: Optional['MessageContextGlobalStateless'] = None, + skills: Optional['MessageContextSkills'] = None, + integrations: Optional[dict] = None, + ) -> None: """ Initialize a MessageContextStateless object. @@ -5230,13 +5488,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': """Initialize a MessageContextStateless object from a json dictionary.""" args = {} - if 'global' in _dict: - args['global_'] = MessageContextGlobalStateless.from_dict( - _dict.get('global')) - if 'skills' in _dict: - args['skills'] = MessageContextSkills.from_dict(_dict.get('skills')) - if 'integrations' in _dict: - args['integrations'] = _dict.get('integrations') + if (global_ := _dict.get('global')) is not None: + args['global_'] = MessageContextGlobalStateless.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = MessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations return cls(**args) @classmethod @@ -5280,47 +5537,49 @@ def __ne__(self, other: 'MessageContextStateless') -> bool: return not self == other -class MessageInput(): +class MessageInput: """ An input object that includes the input text. - :attr str message_type: (optional) The type of the message: + :param str message_type: (optional) The type of the message: - `text`: The user input is processed normally by the assistant. - `search`: Only search results are returned. (Any dialog or action skill is bypassed.) **Note:** A `search` message results in an error if no search skill is configured for the assistant. - :attr str text: (optional) The text of the user input. This string cannot + :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. - :attr str suggestion_id: (optional) For internal use only. - :attr List[MessageInputAttachment] attachments: (optional) An array of + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of multimedia attachments to be sent with the message. Attachments are not processed by the assistant itself, but can be sent to external services by webhooks. **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :attr RequestAnalytics analytics: (optional) An optional object containing + :param RequestAnalytics analytics: (optional) An optional object containing analytics data. Currently, this data is used only for events sent to the Segment extension. - :attr MessageInputOptions options: (optional) Optional properties that control + :param MessageInputOptions options: (optional) Optional properties that control how the assistant responds. """ - def __init__(self, - *, - message_type: str = None, - text: str = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - suggestion_id: str = None, - attachments: List['MessageInputAttachment'] = None, - analytics: 'RequestAnalytics' = None, - options: 'MessageInputOptions' = None) -> None: + def __init__( + self, + *, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['MessageInputOptions'] = None, + ) -> None: """ Initialize a MessageInput object. @@ -5365,31 +5624,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInput': """Initialize a MessageInput object from a json dictionary.""" args = {} - if 'message_type' in _dict: - args['message_type'] = _dict.get('message_type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'suggestion_id' in _dict: - args['suggestion_id'] = _dict.get('suggestion_id') - if 'attachments' in _dict: + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: args['attachments'] = [ - MessageInputAttachment.from_dict(v) - for v in _dict.get('attachments') + MessageInputAttachment.from_dict(v) for v in attachments ] - if 'analytics' in _dict: - args['analytics'] = RequestAnalytics.from_dict( - _dict.get('analytics')) - if 'options' in _dict: - args['options'] = MessageInputOptions.from_dict( - _dict.get('options')) + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = MessageInputOptions.from_dict(options) return cls(**args) @classmethod @@ -5469,20 +5721,26 @@ class MessageTypeEnum(str, Enum): **Note:** A `search` message results in an error if no search skill is configured for the assistant. """ + TEXT = 'text' SEARCH = 'search' -class MessageInputAttachment(): +class MessageInputAttachment: """ A reference to a media file to be sent as an attachment with the message. - :attr str url: The URL of the media file. - :attr str media_type: (optional) The media content type (such as a MIME type) of - the attachment. + :param str url: The URL of the media file. + :param str media_type: (optional) The media content type (such as a MIME type) + of the attachment. """ - def __init__(self, url: str, *, media_type: str = None) -> None: + def __init__( + self, + url: str, + *, + media_type: Optional[str] = None, + ) -> None: """ Initialize a MessageInputAttachment object. @@ -5497,14 +5755,14 @@ def __init__(self, url: str, *, media_type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': """Initialize a MessageInputAttachment object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in MessageInputAttachment JSON' ) - if 'media_type' in _dict: - args['media_type'] = _dict.get('media_type') + if (media_type := _dict.get('media_type')) is not None: + args['media_type'] = media_type return cls(**args) @classmethod @@ -5540,41 +5798,43 @@ def __ne__(self, other: 'MessageInputAttachment') -> bool: return not self == other -class MessageInputOptions(): +class MessageInputOptions: """ Optional properties that control how the assistant responds. - :attr bool restart: (optional) Whether to restart dialog processing at the root + :param bool restart: (optional) Whether to restart dialog processing at the root of the dialog, regardless of any previously visited nodes. **Note:** This does not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction options for the message. Any options specified on an individual message override the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic + :param bool debug: (optional) Whether to return additional diagnostic information. Set to `true` to return additional information in the `output.debug` property. If you also specify **return_context**=`true`, the returned skill context includes the `system.state` property. - :attr bool return_context: (optional) Whether to return session context with the - response. If you specify `true`, the response includes the `context` property. - If you also specify **debug**=`true`, the returned skill context includes the - `system.state` property. - :attr bool export: (optional) Whether to return session context, including full + :param bool return_context: (optional) Whether to return session context with + the response. If you specify `true`, the response includes the `context` + property. If you also specify **debug**=`true`, the returned skill context + includes the `system.state` property. + :param bool export: (optional) Whether to return session context, including full conversation state. If you specify `true`, the response includes the `context` property, and the skill context includes the `system.state` property. **Note:** If **export**=`true`, the context is returned regardless of the value of **return_context**. """ - def __init__(self, - *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None, - return_context: bool = None, - export: bool = None) -> None: + def __init__( + self, + *, + restart: Optional[bool] = None, + alternate_intents: Optional[bool] = None, + spelling: Optional['MessageInputOptionsSpelling'] = None, + debug: Optional[bool] = None, + return_context: Optional[bool] = None, + export: Optional[bool] = None, + ) -> None: """ Initialize a MessageInputOptions object. @@ -5612,19 +5872,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': """Initialize a MessageInputOptions object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') - if 'return_context' in _dict: - args['return_context'] = _dict.get('return_context') - if 'export' in _dict: - args['export'] = _dict.get('export') + if (restart := _dict.get('restart')) is not None: + args['restart'] = restart + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (debug := _dict.get('debug')) is not None: + args['debug'] = debug + if (return_context := _dict.get('return_context')) is not None: + args['return_context'] = return_context + if (export := _dict.get('export')) is not None: + args['export'] = export return cls(**args) @classmethod @@ -5672,19 +5931,19 @@ def __ne__(self, other: 'MessageInputOptions') -> bool: return not self == other -class MessageInputOptionsSpelling(): +class MessageInputOptionsSpelling: """ Spelling correction options for the message. Any options specified on an individual message override the settings configured for the skill. - :attr bool suggestions: (optional) Whether to use spelling correction when + :param bool suggestions: (optional) Whether to use spelling correction when processing the input. If spelling correction is used and **auto_correct** is `true`, any spelling corrections are automatically applied to the user input. If **auto_correct** is `false`, any suggested corrections are returned in the **output.spelling** property. This property overrides the value of the **spelling_suggestions** property in the workspace settings for the skill. - :attr bool auto_correct: (optional) Whether to use autocorrection when + :param bool auto_correct: (optional) Whether to use autocorrection when processing the input. If this property is `true`, any corrections are automatically applied to the user input, and the original text is returned in the **output.spelling** property of the message response. This property @@ -5692,10 +5951,12 @@ class MessageInputOptionsSpelling(): settings for the skill. """ - def __init__(self, - *, - suggestions: bool = None, - auto_correct: bool = None) -> None: + def __init__( + self, + *, + suggestions: Optional[bool] = None, + auto_correct: Optional[bool] = None, + ) -> None: """ Initialize a MessageInputOptionsSpelling object. @@ -5720,10 +5981,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" args = {} - if 'suggestions' in _dict: - args['suggestions'] = _dict.get('suggestions') - if 'auto_correct' in _dict: - args['auto_correct'] = _dict.get('auto_correct') + if (suggestions := _dict.get('suggestions')) is not None: + args['suggestions'] = suggestions + if (auto_correct := _dict.get('auto_correct')) is not None: + args['auto_correct'] = auto_correct return cls(**args) @classmethod @@ -5759,29 +6020,31 @@ def __ne__(self, other: 'MessageInputOptionsSpelling') -> bool: return not self == other -class MessageInputOptionsStateless(): +class MessageInputOptionsStateless: """ Optional properties that control how the assistant responds. - :attr bool restart: (optional) Whether to restart dialog processing at the root + :param bool restart: (optional) Whether to restart dialog processing at the root of the dialog, regardless of any previously visited nodes. **Note:** This does not affect `turn_count` or any other context variables. - :attr bool alternate_intents: (optional) Whether to return more than one intent. - Set to `true` to return all matching intents. - :attr MessageInputOptionsSpelling spelling: (optional) Spelling correction + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction options for the message. Any options specified on an individual message override the settings configured for the skill. - :attr bool debug: (optional) Whether to return additional diagnostic + :param bool debug: (optional) Whether to return additional diagnostic information. Set to `true` to return additional information in the `output.debug` property. """ - def __init__(self, - *, - restart: bool = None, - alternate_intents: bool = None, - spelling: 'MessageInputOptionsSpelling' = None, - debug: bool = None) -> None: + def __init__( + self, + *, + restart: Optional[bool] = None, + alternate_intents: Optional[bool] = None, + spelling: Optional['MessageInputOptionsSpelling'] = None, + debug: Optional[bool] = None, + ) -> None: """ Initialize a MessageInputOptionsStateless object. @@ -5806,15 +6069,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': """Initialize a MessageInputOptionsStateless object from a json dictionary.""" args = {} - if 'restart' in _dict: - args['restart'] = _dict.get('restart') - if 'alternate_intents' in _dict: - args['alternate_intents'] = _dict.get('alternate_intents') - if 'spelling' in _dict: - args['spelling'] = MessageInputOptionsSpelling.from_dict( - _dict.get('spelling')) - if 'debug' in _dict: - args['debug'] = _dict.get('debug') + if (restart := _dict.get('restart')) is not None: + args['restart'] = restart + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (debug := _dict.get('debug')) is not None: + args['debug'] = debug return cls(**args) @classmethod @@ -5858,47 +6120,49 @@ def __ne__(self, other: 'MessageInputOptionsStateless') -> bool: return not self == other -class MessageInputStateless(): +class MessageInputStateless: """ An input object that includes the input text. - :attr str message_type: (optional) The type of the message: + :param str message_type: (optional) The type of the message: - `text`: The user input is processed normally by the assistant. - `search`: Only search results are returned. (Any dialog or action skill is bypassed.) **Note:** A `search` message results in an error if no search skill is configured for the assistant. - :attr str text: (optional) The text of the user input. This string cannot + :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. - :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the - user input. Include intents from the previous response to continue using those - intents rather than trying to recognize intents in the new input. - :attr List[RuntimeEntity] entities: (optional) Entities to use when evaluating + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. - :attr str suggestion_id: (optional) For internal use only. - :attr List[MessageInputAttachment] attachments: (optional) An array of + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of multimedia attachments to be sent with the message. Attachments are not processed by the assistant itself, but can be sent to external services by webhooks. **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :attr RequestAnalytics analytics: (optional) An optional object containing + :param RequestAnalytics analytics: (optional) An optional object containing analytics data. Currently, this data is used only for events sent to the Segment extension. - :attr MessageInputOptionsStateless options: (optional) Optional properties that + :param MessageInputOptionsStateless options: (optional) Optional properties that control how the assistant responds. """ - def __init__(self, - *, - message_type: str = None, - text: str = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - suggestion_id: str = None, - attachments: List['MessageInputAttachment'] = None, - analytics: 'RequestAnalytics' = None, - options: 'MessageInputOptionsStateless' = None) -> None: + def __init__( + self, + *, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['MessageInputOptionsStateless'] = None, + ) -> None: """ Initialize a MessageInputStateless object. @@ -5943,31 +6207,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': """Initialize a MessageInputStateless object from a json dictionary.""" args = {} - if 'message_type' in _dict: - args['message_type'] = _dict.get('message_type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') - ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'suggestion_id' in _dict: - args['suggestion_id'] = _dict.get('suggestion_id') - if 'attachments' in _dict: + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: args['attachments'] = [ - MessageInputAttachment.from_dict(v) - for v in _dict.get('attachments') + MessageInputAttachment.from_dict(v) for v in attachments ] - if 'analytics' in _dict: - args['analytics'] = RequestAnalytics.from_dict( - _dict.get('analytics')) - if 'options' in _dict: - args['options'] = MessageInputOptionsStateless.from_dict( - _dict.get('options')) + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = MessageInputOptionsStateless.from_dict(options) return cls(**args) @classmethod @@ -6047,41 +6304,44 @@ class MessageTypeEnum(str, Enum): **Note:** A `search` message results in an error if no search skill is configured for the assistant. """ + TEXT = 'text' SEARCH = 'search' -class MessageOutput(): +class MessageOutput: """ Assistant output to be rendered or processed by the client. - :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. - :attr List[RuntimeIntent] intents: (optional) An array of intents recognized in + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in the user input, sorted in descending order of confidence. - :attr List[RuntimeEntity] entities: (optional) An array of entities identified + :param List[RuntimeEntity] entities: (optional) An array of entities identified in the user input. - :attr List[DialogNodeAction] actions: (optional) An array of objects describing + :param List[DialogNodeAction] actions: (optional) An array of objects describing any actions requested by the dialog node. - :attr MessageOutputDebug debug: (optional) Additional detailed information about - a message response and how it was generated. - :attr dict user_defined: (optional) An object containing any custom properties + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties included in the response. This object includes any arbitrary properties defined in the dialog JSON editor as part of the dialog node output. - :attr MessageOutputSpelling spelling: (optional) Properties describing any + :param MessageOutputSpelling spelling: (optional) Properties describing any spelling corrections in the user input that was received. """ - def __init__(self, - *, - generic: List['RuntimeResponseGeneric'] = None, - intents: List['RuntimeIntent'] = None, - entities: List['RuntimeEntity'] = None, - actions: List['DialogNodeAction'] = None, - debug: 'MessageOutputDebug' = None, - user_defined: dict = None, - spelling: 'MessageOutputSpelling' = None) -> None: + def __init__( + self, + *, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, + ) -> None: """ Initialize a MessageOutput object. @@ -6115,30 +6375,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageOutput': """Initialize a MessageOutput object from a json dictionary.""" args = {} - if 'generic' in _dict: + if (generic := _dict.get('generic')) is not None: args['generic'] = [ - RuntimeResponseGeneric.from_dict(v) - for v in _dict.get('generic') - ] - if 'intents' in _dict: - args['intents'] = [ - RuntimeIntent.from_dict(v) for v in _dict.get('intents') + RuntimeResponseGeneric.from_dict(v) for v in generic ] - if 'entities' in _dict: - args['entities'] = [ - RuntimeEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'actions' in _dict: - args['actions'] = [ - DialogNodeAction.from_dict(v) for v in _dict.get('actions') - ] - if 'debug' in _dict: - args['debug'] = MessageOutputDebug.from_dict(_dict.get('debug')) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') - if 'spelling' in _dict: - args['spelling'] = MessageOutputSpelling.from_dict( - _dict.get('spelling')) + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) return cls(**args) @classmethod @@ -6214,34 +6466,35 @@ def __ne__(self, other: 'MessageOutput') -> bool: return not self == other -class MessageOutputDebug(): +class MessageOutputDebug: """ Additional detailed information about a message response and how it was generated. - :attr List[DialogNodeVisited] nodes_visited: (optional) An array of objects + :param List[DialogNodeVisited] nodes_visited: (optional) An array of objects containing detailed diagnostic information about dialog nodes that were visited during processing of the input message. - :attr List[DialogLogMessage] log_messages: (optional) An array of up to 50 + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 messages logged with the request. - :attr bool branch_exited: (optional) Assistant sets this to true when this + :param bool branch_exited: (optional) Assistant sets this to true when this message response concludes or interrupts a dialog. - :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` - by the assistant, the `branch_exited_reason` specifies whether the dialog + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the dialog completed by itself or got interrupted. - :attr List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of objects containing detailed diagnostic information about dialog nodes and actions that were visited during processing of the input message. This property is present only if the assistant has an action skill. """ def __init__( - self, - *, - nodes_visited: List['DialogNodeVisited'] = None, - log_messages: List['DialogLogMessage'] = None, - branch_exited: bool = None, - branch_exited_reason: str = None, - turn_events: List['MessageOutputDebugTurnEvent'] = None) -> None: + self, + *, + nodes_visited: Optional[List['DialogNodeVisited']] = None, + log_messages: Optional[List['DialogLogMessage']] = None, + branch_exited: Optional[bool] = None, + branch_exited_reason: Optional[str] = None, + turn_events: Optional[List['MessageOutputDebugTurnEvent']] = None, + ) -> None: """ Initialize a MessageOutputDebug object. @@ -6270,23 +6523,22 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': """Initialize a MessageOutputDebug object from a json dictionary.""" args = {} - if 'nodes_visited' in _dict: + if (nodes_visited := _dict.get('nodes_visited')) is not None: args['nodes_visited'] = [ - DialogNodeVisited.from_dict(v) - for v in _dict.get('nodes_visited') + DialogNodeVisited.from_dict(v) for v in nodes_visited ] - if 'log_messages' in _dict: + if (log_messages := _dict.get('log_messages')) is not None: args['log_messages'] = [ - DialogLogMessage.from_dict(v) for v in _dict.get('log_messages') + DialogLogMessage.from_dict(v) for v in log_messages ] - if 'branch_exited' in _dict: - args['branch_exited'] = _dict.get('branch_exited') - if 'branch_exited_reason' in _dict: - args['branch_exited_reason'] = _dict.get('branch_exited_reason') - if 'turn_events' in _dict: + if (branch_exited := _dict.get('branch_exited')) is not None: + args['branch_exited'] = branch_exited + if (branch_exited_reason := + _dict.get('branch_exited_reason')) is not None: + args['branch_exited_reason'] = branch_exited_reason + if (turn_events := _dict.get('turn_events')) is not None: args['turn_events'] = [ - MessageOutputDebugTurnEvent.from_dict(v) - for v in _dict.get('turn_events') + MessageOutputDebugTurnEvent.from_dict(v) for v in turn_events ] return cls(**args) @@ -6352,17 +6604,18 @@ class BranchExitedReasonEnum(str, Enum): When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` specifies whether the dialog completed by itself or got interrupted. """ + COMPLETED = 'completed' FALLBACK = 'fallback' -class MessageOutputDebugTurnEvent(): +class MessageOutputDebugTurnEvent: """ MessageOutputDebugTurnEvent. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a MessageOutputDebugTurnEvent object. @@ -6386,19 +6639,17 @@ def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'MessageOutputDebugTurnEventTurnEventActionVisited', - 'MessageOutputDebugTurnEventTurnEventActionFinished', - 'MessageOutputDebugTurnEventTurnEventStepVisited', - 'MessageOutputDebugTurnEventTurnEventStepAnswered', - 'MessageOutputDebugTurnEventTurnEventHandlerVisited', - 'MessageOutputDebugTurnEventTurnEventCallout', - 'MessageOutputDebugTurnEventTurnEventSearch', - 'MessageOutputDebugTurnEventTurnEventNodeVisited' - ])) + msg = "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited' + ])) raise Exception(msg) @classmethod @@ -6438,25 +6689,27 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class MessageOutputSpelling(): +class MessageOutputSpelling: """ Properties describing any spelling corrections in the user input that was received. - :attr str text: (optional) The user input text that was used to generate the + :param str text: (optional) The user input text that was used to generate the response. If spelling autocorrection is enabled, this text reflects any spelling corrections that were applied. - :attr str original_text: (optional) The original user input text. This property + :param str original_text: (optional) The original user input text. This property is returned only if autocorrection is enabled and the user input was corrected. - :attr str suggested_text: (optional) Any suggested corrections of the input + :param str suggested_text: (optional) Any suggested corrections of the input text. This property is returned only if spelling correction is enabled and autocorrection is disabled. """ - def __init__(self, - *, - text: str = None, - original_text: str = None, - suggested_text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + original_text: Optional[str] = None, + suggested_text: Optional[str] = None, + ) -> None: """ Initialize a MessageOutputSpelling object. @@ -6478,12 +6731,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': """Initialize a MessageOutputSpelling object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'original_text' in _dict: - args['original_text'] = _dict.get('original_text') - if 'suggested_text' in _dict: - args['suggested_text'] = _dict.get('suggested_text') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (original_text := _dict.get('original_text')) is not None: + args['original_text'] = original_text + if (suggested_text := _dict.get('suggested_text')) is not None: + args['suggested_text'] = suggested_text return cls(**args) @classmethod @@ -6521,19 +6774,19 @@ def __ne__(self, other: 'MessageOutputSpelling') -> bool: return not self == other -class MessageRequest(): +class MessageRequest: """ A stateful message request formatted for the Watson Assistant service. - :attr MessageInput input: (optional) An input object that includes the input + :param MessageInput input: (optional) An input object that includes the input text. - :attr MessageContext context: (optional) Context data for the conversation. You + :param MessageContext context: (optional) Context data for the conversation. You can use this property to set or modify context variables, which can also be accessed by dialog nodes. The context is stored by the assistant on a per-session basis. **Note:** The total size of the context data stored for a stateful session cannot exceed 100KB. - :attr str user_id: (optional) A string value that identifies the user who is + :param str user_id: (optional) A string value that identifies the user who is interacting with the assistant. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -6545,11 +6798,13 @@ class MessageRequest(): specified at the root is used. """ - def __init__(self, - *, - input: 'MessageInput' = None, - context: 'MessageContext' = None, - user_id: str = None) -> None: + def __init__( + self, + *, + input: Optional['MessageInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + ) -> None: """ Initialize a MessageRequest object. @@ -6580,12 +6835,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageRequest': """Initialize a MessageRequest object from a json dictionary.""" args = {} - if 'input' in _dict: - args['input'] = MessageInput.from_dict(_dict.get('input')) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (input := _dict.get('input')) is not None: + args['input'] = MessageInput.from_dict(input) + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod @@ -6629,19 +6884,19 @@ def __ne__(self, other: 'MessageRequest') -> bool: return not self == other -class MessageResponse(): +class MessageResponse: """ A response from the Watson Assistant service. - :attr MessageOutput output: Assistant output to be rendered or processed by the + :param MessageOutput output: Assistant output to be rendered or processed by the client. - :attr MessageContext context: (optional) Context data for the conversation. You + :param MessageContext context: (optional) Context data for the conversation. You can use this property to access context variables. The context is stored by the assistant on a per-session basis. **Note:** The context is included in message responses only if **return_context**=`true` in the message request. Full context is always included in logs. - :attr str user_id: A string value that identifies the user who is interacting + :param str user_id: A string value that identifies the user who is interacting with the assistant. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -6652,11 +6907,13 @@ class MessageResponse(): system context. """ - def __init__(self, - output: 'MessageOutput', - user_id: str, - *, - context: 'MessageContext' = None) -> None: + def __init__( + self, + output: 'MessageOutput', + user_id: str, + *, + context: Optional['MessageContext'] = None, + ) -> None: """ Initialize a MessageResponse object. @@ -6686,16 +6943,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageResponse': """Initialize a MessageResponse object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) else: raise ValueError( 'Required property \'output\' not present in MessageResponse JSON' ) - if 'context' in _dict: - args['context'] = MessageContext.from_dict(_dict.get('context')) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id else: raise ValueError( 'Required property \'user_id\' not present in MessageResponse JSON' @@ -6743,17 +7000,17 @@ def __ne__(self, other: 'MessageResponse') -> bool: return not self == other -class MessageResponseStateless(): +class MessageResponseStateless: """ A stateless response from the Watson Assistant service. - :attr MessageOutput output: Assistant output to be rendered or processed by the + :param MessageOutput output: Assistant output to be rendered or processed by the client. - :attr MessageContextStateless context: Context data for the conversation. You + :param MessageContextStateless context: Context data for the conversation. You can use this property to access context variables. The context is not stored by the assistant; to maintain session state, include the context from the response in the next message. - :attr str user_id: (optional) A string value that identifies the user who is + :param str user_id: (optional) A string value that identifies the user who is interacting with the assistant. The client must provide a unique identifier for each individual end user who accesses the application. For user-based plans, this user ID is used to identify unique users for billing purposes. This string @@ -6764,11 +7021,13 @@ class MessageResponseStateless(): system context. """ - def __init__(self, - output: 'MessageOutput', - context: 'MessageContextStateless', - *, - user_id: str = None) -> None: + def __init__( + self, + output: 'MessageOutput', + context: 'MessageContextStateless', + *, + user_id: Optional[str] = None, + ) -> None: """ Initialize a MessageResponseStateless object. @@ -6796,21 +7055,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': """Initialize a MessageResponseStateless object from a json dictionary.""" args = {} - if 'output' in _dict: - args['output'] = MessageOutput.from_dict(_dict.get('output')) + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) else: raise ValueError( 'Required property \'output\' not present in MessageResponseStateless JSON' ) - if 'context' in _dict: - args['context'] = MessageContextStateless.from_dict( - _dict.get('context')) + if (context := _dict.get('context')) is not None: + args['context'] = MessageContextStateless.from_dict(context) else: raise ValueError( 'Required property \'context\' not present in MessageResponseStateless JSON' ) - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod @@ -6854,31 +7112,33 @@ def __ne__(self, other: 'MessageResponseStateless') -> bool: return not self == other -class Pagination(): +class Pagination: """ The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). - :attr str refresh_url: The URL that will return the same page of results. - :attr str next_url: (optional) The URL that will return the next page of + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of results. - :attr int total: (optional) The total number of objects that satisfy the + :param int total: (optional) The total number of objects that satisfy the request. This total includes all results, not just those included in the current page. - :attr int matched: (optional) Reserved for future use. - :attr str refresh_cursor: (optional) A token identifying the current page of + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page of results. - :attr str next_cursor: (optional) A token identifying the next page of results. + :param str next_cursor: (optional) A token identifying the next page of results. """ - def __init__(self, - refresh_url: str, - *, - next_url: str = None, - total: int = None, - matched: int = None, - refresh_cursor: str = None, - next_cursor: str = None) -> None: + def __init__( + self, + refresh_url: str, + *, + next_url: Optional[str] = None, + total: Optional[int] = None, + matched: Optional[int] = None, + refresh_cursor: Optional[str] = None, + next_cursor: Optional[str] = None, + ) -> None: """ Initialize a Pagination object. @@ -6905,22 +7165,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Pagination': """Initialize a Pagination object from a json dictionary.""" args = {} - if 'refresh_url' in _dict: - args['refresh_url'] = _dict.get('refresh_url') + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url else: raise ValueError( 'Required property \'refresh_url\' not present in Pagination JSON' ) - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'total' in _dict: - args['total'] = _dict.get('total') - if 'matched' in _dict: - args['matched'] = _dict.get('matched') - if 'refresh_cursor' in _dict: - args['refresh_cursor'] = _dict.get('refresh_cursor') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (total := _dict.get('total')) is not None: + args['total'] = total + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (refresh_cursor := _dict.get('refresh_cursor')) is not None: + args['refresh_cursor'] = refresh_cursor + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod @@ -6964,35 +7224,37 @@ def __ne__(self, other: 'Pagination') -> bool: return not self == other -class Release(): +class Release: """ Release. - :attr str release: (optional) The name of the release. The name is the version + :param str release: (optional) The name of the release. The name is the version number (an integer), returned as a string. - :attr str description: (optional) The description of the release. - :attr List[EnvironmentReference] environment_references: (optional) An array of + :param str description: (optional) The description of the release. + :param List[EnvironmentReference] environment_references: (optional) An array of objects describing the environments where this release has been deployed. - :attr ReleaseContent content: (optional) An object identifying the versionable + :param ReleaseContent content: (optional) An object identifying the versionable content objects (such as skill snapshots) that are included in the release. - :attr str status: (optional) The current status of the release: + :param str status: (optional) The current status of the release: - **Available**: The release is available for deployment. - **Failed**: An asynchronous publish operation has failed. - **Processing**: An asynchronous publish operation has not yet completed. - :attr datetime created: (optional) The timestamp for creation of the object. - :attr datetime updated: (optional) The timestamp for the most recent update to + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to the object. """ - def __init__(self, - *, - release: str = None, - description: str = None, - environment_references: List['EnvironmentReference'] = None, - content: 'ReleaseContent' = None, - status: str = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + *, + release: Optional[str] = None, + description: Optional[str] = None, + environment_references: Optional[List['EnvironmentReference']] = None, + content: Optional['ReleaseContent'] = None, + status: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a Release object. @@ -7010,23 +7272,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Release': """Initialize a Release object from a json dictionary.""" args = {} - if 'release' in _dict: - args['release'] = _dict.get('release') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'environment_references' in _dict: + if (release := _dict.get('release')) is not None: + args['release'] = release + if (description := _dict.get('description')) is not None: + args['description'] = description + if (environment_references := + _dict.get('environment_references')) is not None: args['environment_references'] = [ EnvironmentReference.from_dict(v) - for v in _dict.get('environment_references') + for v in environment_references ] - if 'content' in _dict: - args['content'] = ReleaseContent.from_dict(_dict.get('content')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (content := _dict.get('content')) is not None: + args['content'] = ReleaseContent.from_dict(content) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -7088,23 +7351,27 @@ class StatusEnum(str, Enum): - **Failed**: An asynchronous publish operation has failed. - **Processing**: An asynchronous publish operation has not yet completed. """ + AVAILABLE = 'Available' FAILED = 'Failed' PROCESSING = 'Processing' -class ReleaseCollection(): +class ReleaseCollection: """ ReleaseCollection. - :attr List[Release] releases: An array of objects describing the releases + :param List[Release] releases: An array of objects describing the releases associated with an assistant. - :attr Pagination pagination: The pagination data for the returned objects. For + :param Pagination pagination: The pagination data for the returned objects. For more information about using pagination, see [Pagination](#pagination). """ - def __init__(self, releases: List['Release'], - pagination: 'Pagination') -> None: + def __init__( + self, + releases: List['Release'], + pagination: 'Pagination', + ) -> None: """ Initialize a ReleaseCollection object. @@ -7120,16 +7387,14 @@ def __init__(self, releases: List['Release'], def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': """Initialize a ReleaseCollection object from a json dictionary.""" args = {} - if 'releases' in _dict: - args['releases'] = [ - Release.from_dict(v) for v in _dict.get('releases') - ] + if (releases := _dict.get('releases')) is not None: + args['releases'] = [Release.from_dict(v) for v in releases] else: raise ValueError( 'Required property \'releases\' not present in ReleaseCollection JSON' ) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( 'Required property \'pagination\' not present in ReleaseCollection JSON' @@ -7178,16 +7443,20 @@ def __ne__(self, other: 'ReleaseCollection') -> bool: return not self == other -class ReleaseContent(): +class ReleaseContent: """ An object identifying the versionable content objects (such as skill snapshots) that are included in the release. - :attr List[ReleaseSkill] skills: (optional) The skill snapshots that are + :param List[ReleaseSkill] skills: (optional) The skill snapshots that are included in the release. """ - def __init__(self, *, skills: List['ReleaseSkill'] = None) -> None: + def __init__( + self, + *, + skills: Optional[List['ReleaseSkill']] = None, + ) -> None: """ Initialize a ReleaseContent object. @@ -7198,10 +7467,8 @@ def __init__(self, *, skills: List['ReleaseSkill'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ReleaseContent': """Initialize a ReleaseContent object from a json dictionary.""" args = {} - if 'skills' in _dict: - args['skills'] = [ - ReleaseSkill.from_dict(v) for v in _dict.get('skills') - ] + if (skills := _dict.get('skills')) is not None: + args['skills'] = [ReleaseSkill.from_dict(v) for v in skills] return cls(**args) @classmethod @@ -7241,21 +7508,23 @@ def __ne__(self, other: 'ReleaseContent') -> bool: return not self == other -class ReleaseSkill(): +class ReleaseSkill: """ ReleaseSkill. - :attr str skill_id: The skill ID of the skill. - :attr str type: (optional) The type of the skill. - :attr str snapshot: (optional) The name of the skill snapshot that is saved as + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is saved as part of the release (for example, `draft` or `1`). """ - def __init__(self, - skill_id: str, - *, - type: str = None, - snapshot: str = None) -> None: + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + snapshot: Optional[str] = None, + ) -> None: """ Initialize a ReleaseSkill object. @@ -7272,16 +7541,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': """Initialize a ReleaseSkill object from a json dictionary.""" args = {} - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id else: raise ValueError( 'Required property \'skill_id\' not present in ReleaseSkill JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'snapshot' in _dict: - args['snapshot'] = _dict.get('snapshot') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot return cls(**args) @classmethod @@ -7322,29 +7591,32 @@ class TypeEnum(str, Enum): """ The type of the skill. """ + DIALOG = 'dialog' ACTION = 'action' SEARCH = 'search' -class RequestAnalytics(): +class RequestAnalytics: """ An optional object containing analytics data. Currently, this data is used only for events sent to the Segment extension. - :attr str browser: (optional) The browser that was used to send the message that - triggered the event. - :attr str device: (optional) The type of device that was used to send the - message that triggered the event. - :attr str page_url: (optional) The URL of the web page that was used to send the + :param str browser: (optional) The browser that was used to send the message + that triggered the event. + :param str device: (optional) The type of device that was used to send the message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to send + the message that triggered the event. """ - def __init__(self, - *, - browser: str = None, - device: str = None, - page_url: str = None) -> None: + def __init__( + self, + *, + browser: Optional[str] = None, + device: Optional[str] = None, + page_url: Optional[str] = None, + ) -> None: """ Initialize a RequestAnalytics object. @@ -7363,12 +7635,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': """Initialize a RequestAnalytics object from a json dictionary.""" args = {} - if 'browser' in _dict: - args['browser'] = _dict.get('browser') - if 'device' in _dict: - args['device'] = _dict.get('device') - if 'pageUrl' in _dict: - args['page_url'] = _dict.get('pageUrl') + if (browser := _dict.get('browser')) is not None: + args['browser'] = browser + if (device := _dict.get('device')) is not None: + args['device'] = device + if (page_url := _dict.get('pageUrl')) is not None: + args['page_url'] = page_url return cls(**args) @classmethod @@ -7406,14 +7678,18 @@ def __ne__(self, other: 'RequestAnalytics') -> bool: return not self == other -class ResponseGenericChannel(): +class ResponseGenericChannel: """ ResponseGenericChannel. - :attr str channel: (optional) A channel for which the response is intended. + :param str channel: (optional) A channel for which the response is intended. """ - def __init__(self, *, channel: str = None) -> None: + def __init__( + self, + *, + channel: Optional[str] = None, + ) -> None: """ Initialize a ResponseGenericChannel object. @@ -7426,8 +7702,8 @@ def __init__(self, *, channel: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': """Initialize a ResponseGenericChannel object from a json dictionary.""" args = {} - if 'channel' in _dict: - args['channel'] = _dict.get('channel') + if (channel := _dict.get('channel')) is not None: + args['channel'] = channel return cls(**args) @classmethod @@ -7461,53 +7737,55 @@ def __ne__(self, other: 'ResponseGenericChannel') -> bool: return not self == other -class RuntimeEntity(): +class RuntimeEntity: """ The entity value that was recognized in the user input. - :attr str entity: An entity detected in the input. - :attr List[int] location: (optional) An array of zero-based character offsets + :param str entity: An entity detected in the input. + :param List[int] location: (optional) An array of zero-based character offsets that indicate where the detected entity values begin and end in the input text. - :attr str value: The term in the input text that was recognized as an entity + :param str value: The term in the input text that was recognized as an entity value. - :attr float confidence: (optional) A decimal percentage that represents Watson's - confidence in the recognized entity. - :attr List[CaptureGroup] groups: (optional) The recognized capture groups for + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the recognized entity. + :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. - :attr RuntimeEntityInterpretation interpretation: (optional) An object + :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). - :attr List[RuntimeEntityAlternative] alternatives: (optional) An array of + :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. - :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 + :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. - :attr str skill: (optional) The skill that recognized the entity value. + :param str skill: (optional) The skill that recognized the entity value. Currently, the only possible values are `main skill` for the dialog skill (if enabled) and `actions skill` for the action skill. This property is present only if the assistant has both a dialog skill and an action skill. """ - def __init__(self, - entity: str, - value: str, - *, - location: List[int] = None, - confidence: float = None, - groups: List['CaptureGroup'] = None, - interpretation: 'RuntimeEntityInterpretation' = None, - alternatives: List['RuntimeEntityAlternative'] = None, - role: 'RuntimeEntityRole' = None, - skill: str = None) -> None: + def __init__( + self, + entity: str, + value: str, + *, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + groups: Optional[List['CaptureGroup']] = None, + interpretation: Optional['RuntimeEntityInterpretation'] = None, + alternatives: Optional[List['RuntimeEntityAlternative']] = None, + role: Optional['RuntimeEntityRole'] = None, + skill: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntity object. @@ -7559,37 +7837,34 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': """Initialize a RuntimeEntity object from a json dictionary.""" args = {} - if 'entity' in _dict: - args['entity'] = _dict.get('entity') + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( 'Required property \'entity\' not present in RuntimeEntity JSON' ) - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'value' in _dict: - args['value'] = _dict.get('value') + if (location := _dict.get('location')) is not None: + args['location'] = location + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( 'Required property \'value\' not present in RuntimeEntity JSON') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'groups' in _dict: - args['groups'] = [ - CaptureGroup.from_dict(v) for v in _dict.get('groups') - ] - if 'interpretation' in _dict: + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (groups := _dict.get('groups')) is not None: + args['groups'] = [CaptureGroup.from_dict(v) for v in groups] + if (interpretation := _dict.get('interpretation')) is not None: args['interpretation'] = RuntimeEntityInterpretation.from_dict( - _dict.get('interpretation')) - if 'alternatives' in _dict: + interpretation) + if (alternatives := _dict.get('alternatives')) is not None: args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(v) - for v in _dict.get('alternatives') + RuntimeEntityAlternative.from_dict(v) for v in alternatives ] - if 'role' in _dict: - args['role'] = RuntimeEntityRole.from_dict(_dict.get('role')) - if 'skill' in _dict: - args['skill'] = _dict.get('skill') + if (role := _dict.get('role')) is not None: + args['role'] = RuntimeEntityRole.from_dict(role) + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill return cls(**args) @classmethod @@ -7657,17 +7932,22 @@ def __ne__(self, other: 'RuntimeEntity') -> bool: return not self == other -class RuntimeEntityAlternative(): +class RuntimeEntityAlternative: """ An alternative value for the recognized entity. - :attr str value: (optional) The entity value that was recognized in the user + :param 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. + :param 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: + def __init__( + self, + *, + value: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a RuntimeEntityAlternative object. @@ -7683,10 +7963,10 @@ def __init__(self, *, value: str = None, confidence: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': """Initialize a RuntimeEntityAlternative object from a json dictionary.""" args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (value := _dict.get('value')) is not None: + args['value'] = value + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -7722,108 +8002,110 @@ def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: return not self == other -class RuntimeEntityInterpretation(): +class RuntimeEntityInterpretation: """ RuntimeEntityInterpretation. - :attr str calendar_type: (optional) The calendar used to represent a recognized + :param 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 + :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). - :attr str festival: (optional) A locale-specific holiday name (such as + :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. - :attr str granularity: (optional) The precision or duration of a time range + :param 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 + :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`). - :attr str range_modifier: (optional) The word in the user input that indicates + :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`). - :attr float relative_day: (optional) A recognized mention of a relative day, + :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`). - :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, + :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). - :attr float relative_weekend: (optional) A recognized mention of a relative date - range for a weekend, represented numerically as an offset from the current + :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`). - :attr float relative_year: (optional) A recognized mention of a relative year, + :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`). - :attr float specific_day: (optional) A recognized mention of a specific date, + :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`.). - :attr str specific_day_of_week: (optional) A recognized mention of a specific + :param 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 + :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`). - :attr float specific_year: (optional) A recognized mention of a specific year + :param 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 + :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`). - :attr str part_of_day: (optional) A recognized term for a time that was + :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`). - :attr float relative_hour: (optional) A recognized mention of a relative hour, + :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`). - :attr float relative_minute: (optional) A recognized mention of a relative time, - represented numerically as an offset in minutes from the current time (for + :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`). - :attr float relative_second: (optional) A recognized mention of a relative time, - represented numerically as an offset in seconds from the current time (for + :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`). - :attr float specific_hour: (optional) A recognized specific hour mentioned as + :param 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 + :param 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 + :param 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 + :param 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: + def __init__( + self, + *, + calendar_type: Optional[str] = None, + datetime_link: Optional[str] = None, + festival: Optional[str] = None, + granularity: Optional[str] = None, + range_link: Optional[str] = None, + range_modifier: Optional[str] = None, + relative_day: Optional[float] = None, + relative_month: Optional[float] = None, + relative_week: Optional[float] = None, + relative_weekend: Optional[float] = None, + relative_year: Optional[float] = None, + specific_day: Optional[float] = None, + specific_day_of_week: Optional[str] = None, + specific_month: Optional[float] = None, + specific_quarter: Optional[float] = None, + specific_year: Optional[float] = None, + numeric_value: Optional[float] = None, + subtype: Optional[str] = None, + part_of_day: Optional[str] = None, + relative_hour: Optional[float] = None, + relative_minute: Optional[float] = None, + relative_second: Optional[float] = None, + specific_hour: Optional[float] = None, + specific_minute: Optional[float] = None, + specific_second: Optional[float] = None, + timezone: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntityInterpretation object. @@ -7932,58 +8214,59 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" args = {} - 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') + if (calendar_type := _dict.get('calendar_type')) is not None: + args['calendar_type'] = calendar_type + if (datetime_link := _dict.get('datetime_link')) is not None: + args['datetime_link'] = datetime_link + if (festival := _dict.get('festival')) is not None: + args['festival'] = festival + if (granularity := _dict.get('granularity')) is not None: + args['granularity'] = granularity + if (range_link := _dict.get('range_link')) is not None: + args['range_link'] = range_link + if (range_modifier := _dict.get('range_modifier')) is not None: + args['range_modifier'] = range_modifier + if (relative_day := _dict.get('relative_day')) is not None: + args['relative_day'] = relative_day + if (relative_month := _dict.get('relative_month')) is not None: + args['relative_month'] = relative_month + if (relative_week := _dict.get('relative_week')) is not None: + args['relative_week'] = relative_week + if (relative_weekend := _dict.get('relative_weekend')) is not None: + args['relative_weekend'] = relative_weekend + if (relative_year := _dict.get('relative_year')) is not None: + args['relative_year'] = relative_year + if (specific_day := _dict.get('specific_day')) is not None: + args['specific_day'] = specific_day + if (specific_day_of_week := + _dict.get('specific_day_of_week')) is not None: + args['specific_day_of_week'] = specific_day_of_week + if (specific_month := _dict.get('specific_month')) is not None: + args['specific_month'] = specific_month + if (specific_quarter := _dict.get('specific_quarter')) is not None: + args['specific_quarter'] = specific_quarter + if (specific_year := _dict.get('specific_year')) is not None: + args['specific_year'] = specific_year + if (numeric_value := _dict.get('numeric_value')) is not None: + args['numeric_value'] = numeric_value + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype + if (part_of_day := _dict.get('part_of_day')) is not None: + args['part_of_day'] = part_of_day + if (relative_hour := _dict.get('relative_hour')) is not None: + args['relative_hour'] = relative_hour + if (relative_minute := _dict.get('relative_minute')) is not None: + args['relative_minute'] = relative_minute + if (relative_second := _dict.get('relative_second')) is not None: + args['relative_second'] = relative_second + if (specific_hour := _dict.get('specific_hour')) is not None: + args['specific_hour'] = specific_hour + if (specific_minute := _dict.get('specific_minute')) is not None: + args['specific_minute'] = specific_minute + if (specific_second := _dict.get('specific_second')) is not None: + args['specific_second'] = specific_second + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone return cls(**args) @classmethod @@ -8078,6 +8361,7 @@ class GranularityEnum(str, 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' @@ -8091,16 +8375,20 @@ class GranularityEnum(str, Enum): YEAR = 'year' -class RuntimeEntityRole(): +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. + :param str type: (optional) The relationship of the entity to the range. """ - def __init__(self, *, type: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + ) -> None: """ Initialize a RuntimeEntityRole object. @@ -8112,8 +8400,8 @@ def __init__(self, *, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': """Initialize a RuntimeEntityRole object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -8150,6 +8438,7 @@ class TypeEnum(str, Enum): """ The relationship of the entity to the range. """ + DATE_FROM = 'date_from' DATE_TO = 'date_to' NUMBER_FROM = 'number_from' @@ -8158,26 +8447,28 @@ class TypeEnum(str, Enum): TIME_TO = 'time_to' -class RuntimeIntent(): +class RuntimeIntent: """ An intent identified in the user input. - :attr str intent: The name of the recognized intent. - :attr float confidence: (optional) A decimal percentage that represents Watson's - confidence in the intent. If you are specifying an intent as part of a request, - but you do not have a calculated confidence value, specify `1`. - :attr str skill: (optional) The skill that identified the intent. Currently, the - only possible values are `main skill` for the dialog skill (if enabled) and + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + Watson's confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. + :param str skill: (optional) The skill that identified the intent. Currently, + the only possible values are `main skill` for the dialog skill (if enabled) and `actions skill` for the action skill. This property is present only if the assistant has both a dialog skill and an action skill. """ - def __init__(self, - intent: str, - *, - confidence: float = None, - skill: str = None) -> None: + def __init__( + self, + intent: str, + *, + confidence: Optional[float] = None, + skill: Optional[str] = None, + ) -> None: """ Initialize a RuntimeIntent object. @@ -8200,16 +8491,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': """Initialize a RuntimeIntent object from a json dictionary.""" args = {} - if 'intent' in _dict: - args['intent'] = _dict.get('intent') + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent else: raise ValueError( 'Required property \'intent\' not present in RuntimeIntent JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'skill' in _dict: - args['skill'] = _dict.get('skill') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill return cls(**args) @classmethod @@ -8247,13 +8538,13 @@ def __ne__(self, other: 'RuntimeIntent') -> bool: return not self == other -class RuntimeResponseGeneric(): +class RuntimeResponseGeneric: """ RuntimeResponseGeneric. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a RuntimeResponseGeneric object. @@ -8282,24 +8573,22 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) + msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) raise Exception(msg) @classmethod @@ -8342,28 +8631,28 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class SearchResult(): +class SearchResult: """ SearchResult. - :attr str id: The unique identifier of the document in the Discovery service + :param str id: The unique identifier of the document in the Discovery service collection. This property is included in responses from search skills, which are available only to Plus or Enterprise plan users. - :attr SearchResultMetadata result_metadata: An object containing search result + :param SearchResultMetadata result_metadata: An object containing search result metadata from the Discovery service. - :attr str body: (optional) A description of the search result. This is taken + :param str body: (optional) A description of the search result. This is taken from an abstract, summary, or highlight field in the Discovery service response, as specified in the search skill configuration. - :attr str title: (optional) The title of the search result. This is taken from a - title or name field in the Discovery service response, as specified in the + :param str title: (optional) The title of the search result. This is taken from + a title or name field in the Discovery service response, as specified in the search skill configuration. - :attr str url: (optional) The URL of the original data object in its native data - source. - :attr SearchResultHighlight highlight: (optional) An object containing segments + :param str url: (optional) The URL of the original data object in its native + data source. + :param SearchResultHighlight highlight: (optional) An object containing segments of text from search results with query-matching text highlighted using HTML `` tags. - :attr List[SearchResultAnswer] answers: (optional) An array specifying segments + :param List[SearchResultAnswer] answers: (optional) An array specifying segments of text within the result that were identified as direct answers to the search query. Currently, only the single answer with the highest confidence (if any) is returned. @@ -8373,15 +8662,17 @@ class SearchResult(): - Answer finding is not supported on IBM Cloud Pak for Data. """ - def __init__(self, - id: str, - result_metadata: 'SearchResultMetadata', - *, - body: str = None, - title: str = None, - url: str = None, - highlight: 'SearchResultHighlight' = None, - answers: List['SearchResultAnswer'] = None) -> None: + def __init__( + self, + id: str, + result_metadata: 'SearchResultMetadata', + *, + body: Optional[str] = None, + title: Optional[str] = None, + url: Optional[str] = None, + highlight: Optional['SearchResultHighlight'] = None, + answers: Optional[List['SearchResultAnswer']] = None, + ) -> None: """ Initialize a SearchResult object. @@ -8423,31 +8714,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchResult': """Initialize a SearchResult object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') + if (id := _dict.get('id')) is not None: + args['id'] = id else: raise ValueError( 'Required property \'id\' not present in SearchResult JSON') - if 'result_metadata' in _dict: + if (result_metadata := _dict.get('result_metadata')) is not None: args['result_metadata'] = SearchResultMetadata.from_dict( - _dict.get('result_metadata')) + result_metadata) else: raise ValueError( 'Required property \'result_metadata\' not present in SearchResult JSON' ) - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'highlight' in _dict: - args['highlight'] = SearchResultHighlight.from_dict( - _dict.get('highlight')) - if 'answers' in _dict: - args['answers'] = [ - SearchResultAnswer.from_dict(v) for v in _dict.get('answers') - ] + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = SearchResultHighlight.from_dict(highlight) + if (answers := _dict.get('answers')) is not None: + args['answers'] = [SearchResultAnswer.from_dict(v) for v in answers] return cls(**args) @classmethod @@ -8506,17 +8794,21 @@ def __ne__(self, other: 'SearchResult') -> bool: return not self == other -class SearchResultAnswer(): +class SearchResultAnswer: """ An object specifing a segment of text that was identified as a direct answer to the search query. - :attr str text: The text of the answer. - :attr float confidence: The confidence score for the answer, as returned by the + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned by the Discovery service. """ - def __init__(self, text: str, confidence: float) -> None: + def __init__( + self, + text: str, + confidence: float, + ) -> None: """ Initialize a SearchResultAnswer object. @@ -8531,14 +8823,14 @@ def __init__(self, text: str, confidence: float) -> None: def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': """Initialize a SearchResultAnswer object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in SearchResultAnswer JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in SearchResultAnswer JSON' @@ -8578,30 +8870,32 @@ def __ne__(self, other: 'SearchResultAnswer') -> bool: return not self == other -class SearchResultHighlight(): +class SearchResultHighlight: """ An object containing segments of text from search results with query-matching text highlighted using HTML `` tags. - :attr List[str] body: (optional) An array of strings containing segments taken + :param List[str] body: (optional) An array of strings containing segments taken from body text in the search results, with query-matching substrings highlighted. - :attr List[str] title: (optional) An array of strings containing segments taken + :param List[str] title: (optional) An array of strings containing segments taken from title text in the search results, with query-matching substrings highlighted. - :attr List[str] url: (optional) An array of strings containing segments taken + :param List[str] url: (optional) An array of strings containing segments taken from URLs in the search results, with query-matching substrings highlighted. """ # The set of defined properties for the class _properties = frozenset(['body', 'title', 'url']) - def __init__(self, - *, - body: List[str] = None, - title: List[str] = None, - url: List[str] = None, - **kwargs) -> None: + def __init__( + self, + *, + body: Optional[List[str]] = None, + title: Optional[List[str]] = None, + url: Optional[List[str]] = None, + **kwargs, + ) -> None: """ Initialize a SearchResultHighlight object. @@ -8626,12 +8920,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': """Initialize a SearchResultHighlight object from a json dictionary.""" args = {} - if 'body' in _dict: - args['body'] = _dict.get('body') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'url' in _dict: - args['url'] = _dict.get('url') + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -8699,21 +8993,23 @@ def __ne__(self, other: 'SearchResultHighlight') -> bool: return not self == other -class SearchResultMetadata(): +class SearchResultMetadata: """ An object containing search result metadata from the Discovery service. - :attr float confidence: (optional) The confidence score for the given result, as - returned by the Discovery service. - :attr float score: (optional) An unbounded measure of the relevance of a + :param float confidence: (optional) The confidence score for the given result, + as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a particular result, dependent on the query and matching document. A higher score indicates a greater match to the query parameters. """ - def __init__(self, - *, - confidence: float = None, - score: float = None) -> None: + def __init__( + self, + *, + confidence: Optional[float] = None, + score: Optional[float] = None, + ) -> None: """ Initialize a SearchResultMetadata object. @@ -8730,10 +9026,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': """Initialize a SearchResultMetadata object from a json dictionary.""" args = {} - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'score' in _dict: - args['score'] = _dict.get('score') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (score := _dict.get('score')) is not None: + args['score'] = score return cls(**args) @classmethod @@ -8769,21 +9065,24 @@ def __ne__(self, other: 'SearchResultMetadata') -> bool: return not self == other -class SearchSettings(): +class SearchSettings: """ An object describing the search skill configuration. - :attr SearchSettingsDiscovery discovery: Configuration settings for the Watson + :param SearchSettingsDiscovery discovery: Configuration settings for the Watson Discovery service instance used by the search integration. - :attr SearchSettingsMessages messages: The messages included with responses from - the search integration. - :attr SearchSettingsSchemaMapping schema_mapping: The mapping between fields in + :param SearchSettingsMessages messages: The messages included with responses + from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between fields in the Watson Discovery collection and properties in the search response. """ - def __init__(self, discovery: 'SearchSettingsDiscovery', - messages: 'SearchSettingsMessages', - schema_mapping: 'SearchSettingsSchemaMapping') -> None: + def __init__( + self, + discovery: 'SearchSettingsDiscovery', + messages: 'SearchSettingsMessages', + schema_mapping: 'SearchSettingsSchemaMapping', + ) -> None: """ Initialize a SearchSettings object. @@ -8803,23 +9102,21 @@ def __init__(self, discovery: 'SearchSettingsDiscovery', def from_dict(cls, _dict: Dict) -> 'SearchSettings': """Initialize a SearchSettings object from a json dictionary.""" args = {} - if 'discovery' in _dict: - args['discovery'] = SearchSettingsDiscovery.from_dict( - _dict.get('discovery')) + if (discovery := _dict.get('discovery')) is not None: + args['discovery'] = SearchSettingsDiscovery.from_dict(discovery) else: raise ValueError( 'Required property \'discovery\' not present in SearchSettings JSON' ) - if 'messages' in _dict: - args['messages'] = SearchSettingsMessages.from_dict( - _dict.get('messages')) + if (messages := _dict.get('messages')) is not None: + args['messages'] = SearchSettingsMessages.from_dict(messages) else: raise ValueError( 'Required property \'messages\' not present in SearchSettings JSON' ) - if 'schema_mapping' in _dict: + if (schema_mapping := _dict.get('schema_mapping')) is not None: args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( - _dict.get('schema_mapping')) + schema_mapping) else: raise ValueError( 'Required property \'schema_mapping\' not present in SearchSettings JSON' @@ -8870,48 +9167,50 @@ def __ne__(self, other: 'SearchSettings') -> bool: return not self == other -class SearchSettingsDiscovery(): +class SearchSettingsDiscovery: """ Configuration settings for the Watson Discovery service instance used by the search integration. - :attr str instance_id: The ID for the Watson Discovery service instance. - :attr str project_id: The ID for the Watson Discovery project. - :attr str url: The URL for the Watson Discovery service instance. - :attr int max_primary_results: (optional) The maximum number of primary results + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param int max_primary_results: (optional) The maximum number of primary results to include in the response. - :attr int max_total_results: (optional) The maximum total number of primary and + :param int max_total_results: (optional) The maximum total number of primary and additional results to include in the response. - :attr float confidence_threshold: (optional) The minimum confidence threshold + :param float confidence_threshold: (optional) The minimum confidence threshold for included results. Any results with a confidence below this threshold will be discarded. - :attr bool highlight: (optional) Whether to include the most relevant passages + :param bool highlight: (optional) Whether to include the most relevant passages of text in the **highlight** property of each result. - :attr bool find_answers: (optional) Whether to use the answer finding feature to - emphasize answers within highlighted passages. This property is ignored if + :param bool find_answers: (optional) Whether to use the answer finding feature + to emphasize answers within highlighted passages. This property is ignored if **highlight**=`false`. **Notes:** - Answer finding is available only if the search skill is connected to a Discovery v2 service instance. - Answer finding is not supported on IBM Cloud Pak for Data. - :attr SearchSettingsDiscoveryAuthentication authentication: Authentication + :param SearchSettingsDiscoveryAuthentication authentication: Authentication information for the Watson Discovery service. For more information, see the [Watson Discovery documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). **Note:** You must specify either **basic** or **bearer**, but not both. """ - def __init__(self, - instance_id: str, - project_id: str, - url: str, - authentication: 'SearchSettingsDiscoveryAuthentication', - *, - max_primary_results: int = None, - max_total_results: int = None, - confidence_threshold: float = None, - highlight: bool = None, - find_answers: bool = None) -> None: + def __init__( + self, + instance_id: str, + project_id: str, + url: str, + authentication: 'SearchSettingsDiscoveryAuthentication', + *, + max_primary_results: Optional[int] = None, + max_total_results: Optional[int] = None, + confidence_threshold: Optional[float] = None, + highlight: Optional[bool] = None, + find_answers: Optional[bool] = None, + ) -> None: """ Initialize a SearchSettingsDiscovery object. @@ -8954,38 +9253,40 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': """Initialize a SearchSettingsDiscovery object from a json dictionary.""" args = {} - if 'instance_id' in _dict: - args['instance_id'] = _dict.get('instance_id') + if (instance_id := _dict.get('instance_id')) is not None: + args['instance_id'] = instance_id else: raise ValueError( 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' ) - if 'project_id' in _dict: - args['project_id'] = _dict.get('project_id') + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id else: raise ValueError( 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' ) - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in SearchSettingsDiscovery JSON' ) - if 'max_primary_results' in _dict: - args['max_primary_results'] = _dict.get('max_primary_results') - if 'max_total_results' in _dict: - args['max_total_results'] = _dict.get('max_total_results') - if 'confidence_threshold' in _dict: - args['confidence_threshold'] = _dict.get('confidence_threshold') - if 'highlight' in _dict: - args['highlight'] = _dict.get('highlight') - if 'find_answers' in _dict: - args['find_answers'] = _dict.get('find_answers') - if 'authentication' in _dict: + if (max_primary_results := + _dict.get('max_primary_results')) is not None: + args['max_primary_results'] = max_primary_results + if (max_total_results := _dict.get('max_total_results')) is not None: + args['max_total_results'] = max_total_results + if (confidence_threshold := + _dict.get('confidence_threshold')) is not None: + args['confidence_threshold'] = confidence_threshold + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = highlight + if (find_answers := _dict.get('find_answers')) is not None: + args['find_answers'] = find_answers + if (authentication := _dict.get('authentication')) is not None: args[ 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( - _dict.get('authentication')) + authentication) else: raise ValueError( 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' @@ -9046,21 +9347,26 @@ def __ne__(self, other: 'SearchSettingsDiscovery') -> bool: return not self == other -class SearchSettingsDiscoveryAuthentication(): +class SearchSettingsDiscoveryAuthentication: """ Authentication information for the Watson Discovery service. For more information, see the [Watson Discovery documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). **Note:** You must specify either **basic** or **bearer**, but not both. - :attr str basic: (optional) The HTTP basic authentication credentials for Watson - Discovery. Specify your Watson Discovery API key in the format + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format `apikey:{apikey}`. - :attr str bearer: (optional) The authentication bearer token for Watson + :param str bearer: (optional) The authentication bearer token for Watson Discovery. """ - def __init__(self, *, basic: str = None, bearer: str = None) -> None: + def __init__( + self, + *, + basic: Optional[str] = None, + bearer: Optional[str] = None, + ) -> None: """ Initialize a SearchSettingsDiscoveryAuthentication object. @@ -9077,10 +9383,10 @@ def __init__(self, *, basic: str = None, bearer: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" args = {} - if 'basic' in _dict: - args['basic'] = _dict.get('basic') - if 'bearer' in _dict: - args['bearer'] = _dict.get('bearer') + if (basic := _dict.get('basic')) is not None: + args['basic'] = basic + if (bearer := _dict.get('bearer')) is not None: + args['bearer'] = bearer return cls(**args) @classmethod @@ -9116,18 +9422,24 @@ def __ne__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: return not self == other -class SearchSettingsMessages(): +class SearchSettingsMessages: """ The messages included with responses from the search integration. - :attr str success: The message to include in the response to a successful query. - :attr str error: The message to include in the response when the query + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query encounters an error. - :attr str no_result: The message to include in the response when there is no + :param str no_result: The message to include in the response when there is no result from the query. """ - def __init__(self, success: str, error: str, no_result: str) -> None: + def __init__( + self, + success: str, + error: str, + no_result: str, + ) -> None: """ Initialize a SearchSettingsMessages object. @@ -9146,20 +9458,20 @@ def __init__(self, success: str, error: str, no_result: str) -> None: def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': """Initialize a SearchSettingsMessages object from a json dictionary.""" args = {} - if 'success' in _dict: - args['success'] = _dict.get('success') + if (success := _dict.get('success')) is not None: + args['success'] = success else: raise ValueError( 'Required property \'success\' not present in SearchSettingsMessages JSON' ) - if 'error' in _dict: - args['error'] = _dict.get('error') + if (error := _dict.get('error')) is not None: + args['error'] = error else: raise ValueError( 'Required property \'error\' not present in SearchSettingsMessages JSON' ) - if 'no_result' in _dict: - args['no_result'] = _dict.get('no_result') + if (no_result := _dict.get('no_result')) is not None: + args['no_result'] = no_result else: raise ValueError( 'Required property \'no_result\' not present in SearchSettingsMessages JSON' @@ -9201,20 +9513,25 @@ def __ne__(self, other: 'SearchSettingsMessages') -> bool: return not self == other -class SearchSettingsSchemaMapping(): +class SearchSettingsSchemaMapping: """ The mapping between fields in the Watson Discovery collection and properties in the search response. - :attr str url: The field in the collection to map to the **url** property of the - response. - :attr str body: The field in the collection to map to the **body** property in + :param str url: The field in the collection to map to the **url** property of + the response. + :param str body: The field in the collection to map to the **body** property in the response. - :attr str title: The field in the collection to map to the **title** property + :param str title: The field in the collection to map to the **title** property for the schema. """ - def __init__(self, url: str, body: str, title: str) -> None: + def __init__( + self, + url: str, + body: str, + title: str, + ) -> None: """ Initialize a SearchSettingsSchemaMapping object. @@ -9233,20 +9550,20 @@ def __init__(self, url: str, body: str, title: str) -> None: def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' ) - if 'body' in _dict: - args['body'] = _dict.get('body') + if (body := _dict.get('body')) is not None: + args['body'] = body else: raise ValueError( 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' @@ -9288,21 +9605,23 @@ def __ne__(self, other: 'SearchSettingsSchemaMapping') -> bool: return not self == other -class SearchSkillWarning(): +class SearchSkillWarning: """ A warning describing an error in the search skill configuration. - :attr str code: (optional) The error code. - :attr str path: (optional) The location of the error in the search skill + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill configuration object. - :attr str message: (optional) The error message. + :param str message: (optional) The error message. """ - def __init__(self, - *, - code: str = None, - path: str = None, - message: str = None) -> None: + def __init__( + self, + *, + code: Optional[str] = None, + path: Optional[str] = None, + message: Optional[str] = None, + ) -> None: """ Initialize a SearchSkillWarning object. @@ -9319,12 +9638,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': """Initialize a SearchSkillWarning object from a json dictionary.""" args = {} - if 'code' in _dict: - args['code'] = _dict.get('code') - if 'path' in _dict: - args['path'] = _dict.get('path') - if 'message' in _dict: - args['message'] = _dict.get('message') + if (code := _dict.get('code')) is not None: + args['code'] = code + if (path := _dict.get('path')) is not None: + args['path'] = path + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -9362,14 +9681,17 @@ def __ne__(self, other: 'SearchSkillWarning') -> bool: return not self == other -class SessionResponse(): +class SessionResponse: """ SessionResponse. - :attr str session_id: The session ID. + :param str session_id: The session ID. """ - def __init__(self, session_id: str) -> None: + def __init__( + self, + session_id: str, + ) -> None: """ Initialize a SessionResponse object. @@ -9381,8 +9703,8 @@ def __init__(self, session_id: str) -> None: def from_dict(cls, _dict: Dict) -> 'SessionResponse': """Initialize a SessionResponse object from a json dictionary.""" args = {} - if 'session_id' in _dict: - args['session_id'] = _dict.get('session_id') + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id else: raise ValueError( 'Required property \'session_id\' not present in SessionResponse JSON' @@ -9420,69 +9742,71 @@ def __ne__(self, other: 'SessionResponse') -> bool: return not self == other -class Skill(): +class Skill: """ Skill. - :attr str name: (optional) The name of the skill. This string cannot contain + :param str name: (optional) The name of the skill. This string cannot contain carriage return, newline, or tab characters. - :attr str description: (optional) The description of the skill. This string + :param str description: (optional) The description of the skill. This string cannot contain carriage return, newline, or tab characters. - :attr dict workspace: (optional) An object containing the conversational content - of an action or dialog skill. - :attr str skill_id: (optional) The skill ID of the skill. - :attr str status: (optional) The current status of the skill: + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: - **Available**: The skill is available and ready to process messages. - **Failed**: An asynchronous operation has failed. See the **status_errors** property for more information about the cause of the failure. - **Non Existent**: The skill does not exist. - **Processing**: An asynchronous operation has not yet completed. - **Training**: The skill is training based on new data. - :attr List[StatusError] status_errors: (optional) An array of messages about + :param List[StatusError] status_errors: (optional) An array of messages about errors that caused an asynchronous operation to fail. Included only if **status**=`Failed`. - :attr str status_description: (optional) The description of the failed + :param str status_description: (optional) The description of the failed asynchronous operation. Included only if **status**=`Failed`. - :attr dict dialog_settings: (optional) For internal use only. - :attr str assistant_id: (optional) The unique identifier of the assistant the + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the skill is associated with. - :attr str workspace_id: (optional) The unique identifier of the workspace that + :param str workspace_id: (optional) The unique identifier of the workspace that contains the skill content. Included only for action and dialog skills. - :attr str environment_id: (optional) The unique identifier of the environment + :param str environment_id: (optional) The unique identifier of the environment where the skill is defined. For action and dialog skills, this is always the draft environment. - :attr bool valid: (optional) Whether the skill is structurally valid. - :attr str next_snapshot_version: (optional) The name that will be given to the + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the next snapshot that is created for the skill. A snapshot of each versionable skill is saved for each new release of an assistant. - :attr SearchSettings search_settings: (optional) An object describing the search - skill configuration. - :attr List[SearchSkillWarning] warnings: (optional) An array of warnings + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings describing errors with the search skill configuration. Included only for search skills. - :attr str language: The language of the skill. - :attr str type: The type of skill. - """ - - def __init__(self, - language: str, - type: str, - *, - name: str = None, - description: str = None, - workspace: dict = None, - skill_id: str = None, - status: str = None, - status_errors: List['StatusError'] = None, - status_description: str = None, - dialog_settings: dict = None, - assistant_id: str = None, - workspace_id: str = None, - environment_id: str = None, - valid: bool = None, - next_snapshot_version: str = None, - search_settings: 'SearchSettings' = None, - warnings: List['SearchSkillWarning'] = None) -> None: + :param str language: The language of the skill. + :param str type: The type of skill. + """ + + def __init__( + self, + language: str, + type: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, + ) -> None: """ Initialize a Skill object. @@ -9520,48 +9844,48 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Skill': """Initialize a Skill object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'workspace' in _dict: - args['workspace'] = _dict.get('workspace') - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_errors' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: args['status_errors'] = [ - StatusError.from_dict(v) for v in _dict.get('status_errors') + StatusError.from_dict(v) for v in status_errors ] - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'dialog_settings' in _dict: - args['dialog_settings'] = _dict.get('dialog_settings') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'valid' in _dict: - args['valid'] = _dict.get('valid') - if 'next_snapshot_version' in _dict: - args['next_snapshot_version'] = _dict.get('next_snapshot_version') - if 'search_settings' in _dict: - args['search_settings'] = SearchSettings.from_dict( - _dict.get('search_settings')) - if 'warnings' in _dict: + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in _dict.get('warnings') + SearchSkillWarning.from_dict(v) for v in warnings ] - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Skill JSON') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in Skill JSON') @@ -9663,6 +9987,7 @@ class StatusEnum(str, Enum): - **Processing**: An asynchronous operation has not yet completed. - **Training**: The skill is training based on new data. """ + AVAILABLE = 'Available' FAILED = 'Failed' NON_EXISTENT = 'Non Existent' @@ -9674,74 +9999,77 @@ class TypeEnum(str, Enum): """ The type of skill. """ + ACTION = 'action' DIALOG = 'dialog' SEARCH = 'search' -class SkillImport(): +class SkillImport: """ SkillImport. - :attr str name: (optional) The name of the skill. This string cannot contain + :param str name: (optional) The name of the skill. This string cannot contain carriage return, newline, or tab characters. - :attr str description: (optional) The description of the skill. This string + :param str description: (optional) The description of the skill. This string cannot contain carriage return, newline, or tab characters. - :attr dict workspace: (optional) An object containing the conversational content - of an action or dialog skill. - :attr str skill_id: (optional) The skill ID of the skill. - :attr str status: (optional) The current status of the skill: + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: - **Available**: The skill is available and ready to process messages. - **Failed**: An asynchronous operation has failed. See the **status_errors** property for more information about the cause of the failure. - **Non Existent**: The skill does not exist. - **Processing**: An asynchronous operation has not yet completed. - **Training**: The skill is training based on new data. - :attr List[StatusError] status_errors: (optional) An array of messages about + :param List[StatusError] status_errors: (optional) An array of messages about errors that caused an asynchronous operation to fail. Included only if **status**=`Failed`. - :attr str status_description: (optional) The description of the failed + :param str status_description: (optional) The description of the failed asynchronous operation. Included only if **status**=`Failed`. - :attr dict dialog_settings: (optional) For internal use only. - :attr str assistant_id: (optional) The unique identifier of the assistant the + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the skill is associated with. - :attr str workspace_id: (optional) The unique identifier of the workspace that + :param str workspace_id: (optional) The unique identifier of the workspace that contains the skill content. Included only for action and dialog skills. - :attr str environment_id: (optional) The unique identifier of the environment + :param str environment_id: (optional) The unique identifier of the environment where the skill is defined. For action and dialog skills, this is always the draft environment. - :attr bool valid: (optional) Whether the skill is structurally valid. - :attr str next_snapshot_version: (optional) The name that will be given to the + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the next snapshot that is created for the skill. A snapshot of each versionable skill is saved for each new release of an assistant. - :attr SearchSettings search_settings: (optional) An object describing the search - skill configuration. - :attr List[SearchSkillWarning] warnings: (optional) An array of warnings + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings describing errors with the search skill configuration. Included only for search skills. - :attr str language: The language of the skill. - :attr str type: The type of skill. - """ - - def __init__(self, - language: str, - type: str, - *, - name: str = None, - description: str = None, - workspace: dict = None, - skill_id: str = None, - status: str = None, - status_errors: List['StatusError'] = None, - status_description: str = None, - dialog_settings: dict = None, - assistant_id: str = None, - workspace_id: str = None, - environment_id: str = None, - valid: bool = None, - next_snapshot_version: str = None, - search_settings: 'SearchSettings' = None, - warnings: List['SearchSkillWarning'] = None) -> None: + :param str language: The language of the skill. + :param str type: The type of skill. + """ + + def __init__( + self, + language: str, + type: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, + ) -> None: """ Initialize a SkillImport object. @@ -9779,49 +10107,49 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SkillImport': """Initialize a SkillImport object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'workspace' in _dict: - args['workspace'] = _dict.get('workspace') - if 'skill_id' in _dict: - args['skill_id'] = _dict.get('skill_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_errors' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: args['status_errors'] = [ - StatusError.from_dict(v) for v in _dict.get('status_errors') + StatusError.from_dict(v) for v in status_errors ] - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'dialog_settings' in _dict: - args['dialog_settings'] = _dict.get('dialog_settings') - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'valid' in _dict: - args['valid'] = _dict.get('valid') - if 'next_snapshot_version' in _dict: - args['next_snapshot_version'] = _dict.get('next_snapshot_version') - if 'search_settings' in _dict: - args['search_settings'] = SearchSettings.from_dict( - _dict.get('search_settings')) - if 'warnings' in _dict: + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in _dict.get('warnings') + SearchSkillWarning.from_dict(v) for v in warnings ] - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in SkillImport JSON' ) - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in SkillImport JSON') @@ -9923,6 +10251,7 @@ class StatusEnum(str, Enum): - **Processing**: An asynchronous operation has not yet completed. - **Training**: The skill is training based on new data. """ + AVAILABLE = 'Available' FAILED = 'Failed' NON_EXISTENT = 'Non Existent' @@ -9934,35 +10263,38 @@ class TypeEnum(str, Enum): """ The type of skill. """ + ACTION = 'action' DIALOG = 'dialog' SEARCH = 'search' -class SkillsAsyncRequestStatus(): +class SkillsAsyncRequestStatus: """ SkillsAsyncRequestStatus. - :attr str assistant_id: (optional) The assistant ID of the assistant. - :attr str status: (optional) The current status of the asynchronous operation: + :param str assistant_id: (optional) The assistant ID of the assistant. + :param str status: (optional) The current status of the asynchronous operation: - `Available`: An asynchronous export is available. - `Completed`: An asynchronous import operation has completed successfully. - `Failed`: An asynchronous operation has failed. See the **status_errors** property for more information about the cause of the failure. - `Processing`: An asynchronous operation has not yet completed. - :attr str status_description: (optional) The description of the failed + :param str status_description: (optional) The description of the failed asynchronous operation. Included only if **status**=`Failed`. - :attr List[StatusError] status_errors: (optional) An array of messages about + :param List[StatusError] status_errors: (optional) An array of messages about errors that caused an asynchronous operation to fail. Included only if **status**=`Failed`. """ - def __init__(self, - *, - assistant_id: str = None, - status: str = None, - status_description: str = None, - status_errors: List['StatusError'] = None) -> None: + def __init__( + self, + *, + assistant_id: Optional[str] = None, + status: Optional[str] = None, + status_description: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + ) -> None: """ Initialize a SkillsAsyncRequestStatus object. @@ -9976,15 +10308,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" args = {} - if 'assistant_id' in _dict: - args['assistant_id'] = _dict.get('assistant_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'status_errors' in _dict: + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (status_errors := _dict.get('status_errors')) is not None: args['status_errors'] = [ - StatusError.from_dict(v) for v in _dict.get('status_errors') + StatusError.from_dict(v) for v in status_errors ] return cls(**args) @@ -10042,24 +10374,28 @@ class StatusEnum(str, Enum): property for more information about the cause of the failure. - `Processing`: An asynchronous operation has not yet completed. """ + AVAILABLE = 'Available' COMPLETED = 'Completed' FAILED = 'Failed' PROCESSING = 'Processing' -class SkillsExport(): +class SkillsExport: """ SkillsExport. - :attr List[Skill] assistant_skills: An array of objects describing the skills + :param List[Skill] assistant_skills: An array of objects describing the skills for the assistant. Included in responses only if **status**=`Available`. - :attr AssistantState assistant_state: Status information about the skills for + :param AssistantState assistant_state: Status information about the skills for the assistant. Included in responses only if **status**=`Available`. """ - def __init__(self, assistant_skills: List['Skill'], - assistant_state: 'AssistantState') -> None: + def __init__( + self, + assistant_skills: List['Skill'], + assistant_state: 'AssistantState', + ) -> None: """ Initialize a SkillsExport object. @@ -10076,17 +10412,16 @@ def __init__(self, assistant_skills: List['Skill'], def from_dict(cls, _dict: Dict) -> 'SkillsExport': """Initialize a SkillsExport object from a json dictionary.""" args = {} - if 'assistant_skills' in _dict: + if (assistant_skills := _dict.get('assistant_skills')) is not None: args['assistant_skills'] = [ - Skill.from_dict(v) for v in _dict.get('assistant_skills') + Skill.from_dict(v) for v in assistant_skills ] else: raise ValueError( 'Required property \'assistant_skills\' not present in SkillsExport JSON' ) - if 'assistant_state' in _dict: - args['assistant_state'] = AssistantState.from_dict( - _dict.get('assistant_state')) + if (assistant_state := _dict.get('assistant_state')) is not None: + args['assistant_state'] = AssistantState.from_dict(assistant_state) else: raise ValueError( 'Required property \'assistant_state\' not present in SkillsExport JSON' @@ -10137,15 +10472,19 @@ def __ne__(self, other: 'SkillsExport') -> bool: return not self == other -class StatusError(): +class StatusError: """ An object describing an error that occurred during processing of an asynchronous operation. - :attr str message: (optional) The text of the error message. + :param str message: (optional) The text of the error message. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a StatusError object. @@ -10157,8 +10496,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'StatusError': """Initialize a StatusError object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -10192,23 +10531,25 @@ def __ne__(self, other: 'StatusError') -> bool: return not self == other -class TurnEventActionSource(): +class TurnEventActionSource: """ TurnEventActionSource. - :attr str type: (optional) The type of turn event. - :attr str action: (optional) An action that was visited during processing of the - message. - :attr str action_title: (optional) The title of the action. - :attr str condition: (optional) The condition that triggered the dialog node. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing of + the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog node. """ - def __init__(self, - *, - type: str = None, - action: str = None, - action_title: str = None, - condition: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + action: Optional[str] = None, + action_title: Optional[str] = None, + condition: Optional[str] = None, + ) -> None: """ Initialize a TurnEventActionSource object. @@ -10228,14 +10569,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TurnEventActionSource': """Initialize a TurnEventActionSource object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'action' in _dict: - args['action'] = _dict.get('action') - if 'action_title' in _dict: - args['action_title'] = _dict.get('action_title') - if 'condition' in _dict: - args['condition'] = _dict.get('condition') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (action := _dict.get('action')) is not None: + args['action'] = action + if (action_title := _dict.get('action_title')) is not None: + args['action_title'] = action_title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod @@ -10278,25 +10619,28 @@ class TypeEnum(str, Enum): """ The type of turn event. """ + ACTION = 'action' -class TurnEventCalloutCallout(): +class TurnEventCalloutCallout: """ TurnEventCalloutCallout. - :attr str type: (optional) The type of callout. Currently, the only supported + :param str type: (optional) The type of callout. Currently, the only supported value is `integration_interaction` (for calls to extensions). - :attr dict internal: (optional) For internal use only. - :attr str result_variable: (optional) The name of the variable where the callout - result is stored. + :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. """ - def __init__(self, - *, - type: str = None, - internal: dict = None, - result_variable: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + internal: Optional[dict] = None, + result_variable: Optional[str] = None, + ) -> None: """ Initialize a TurnEventCalloutCallout object. @@ -10314,12 +10658,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': """Initialize a TurnEventCalloutCallout object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'internal' in _dict: - args['internal'] = _dict.get('internal') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (internal := _dict.get('internal')) is not None: + args['internal'] = internal + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable return cls(**args) @classmethod @@ -10362,18 +10706,23 @@ class TypeEnum(str, Enum): The type of callout. Currently, the only supported value is `integration_interaction` (for calls to extensions). """ + INTEGRATION_INTERACTION = 'integration_interaction' -class TurnEventCalloutError(): +class TurnEventCalloutError: """ TurnEventCalloutError. - :attr str message: (optional) Any error message returned by a failed call to an + :param str message: (optional) Any error message returned by a failed call to an external service. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a TurnEventCalloutError object. @@ -10386,8 +10735,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutError': """Initialize a TurnEventCalloutError object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -10421,23 +10770,25 @@ def __ne__(self, other: 'TurnEventCalloutError') -> bool: return not self == other -class TurnEventNodeSource(): +class TurnEventNodeSource: """ TurnEventNodeSource. - :attr str type: (optional) The type of turn event. - :attr str dialog_node: (optional) A dialog node that was visited during + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during processing of the input message. - :attr str title: (optional) The title of the dialog node. - :attr str condition: (optional) The condition that triggered the dialog node. + :param str title: (optional) The title of the dialog node. + :param str condition: (optional) The condition that triggered the dialog node. """ - def __init__(self, - *, - type: str = None, - dialog_node: str = None, - title: str = None, - condition: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + condition: Optional[str] = None, + ) -> None: """ Initialize a TurnEventNodeSource object. @@ -10457,14 +10808,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TurnEventNodeSource': """Initialize a TurnEventNodeSource object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'condition' in _dict: - args['condition'] = _dict.get('condition') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod @@ -10507,18 +10858,23 @@ class TypeEnum(str, Enum): """ The type of turn event. """ + DIALOG_NODE = 'dialog_node' -class TurnEventSearchError(): +class TurnEventSearchError: """ TurnEventSearchError. - :attr str message: (optional) Any error message returned by a failed call to a + :param str message: (optional) Any error message returned by a failed call to a search skill. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a TurnEventSearchError object. @@ -10531,8 +10887,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError': """Initialize a TurnEventSearchError object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -10570,13 +10926,17 @@ class LogMessageSourceAction(LogMessageSource): """ An object that identifies the dialog element that generated the error message. - :attr str type: A string that indicates the type of dialog element that + :param str type: A string that indicates the type of dialog element that generated the error message. - :attr str action: The unique identifier of the action that generated the error + :param str action: The unique identifier of the action that generated the error message. """ - def __init__(self, type: str, action: str) -> None: + def __init__( + self, + type: str, + action: str, + ) -> None: """ Initialize a LogMessageSourceAction object. @@ -10593,14 +10953,14 @@ def __init__(self, type: str, action: str) -> None: def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': """Initialize a LogMessageSourceAction object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in LogMessageSourceAction JSON' ) - if 'action' in _dict: - args['action'] = _dict.get('action') + if (action := _dict.get('action')) is not None: + args['action'] = action else: raise ValueError( 'Required property \'action\' not present in LogMessageSourceAction JSON' @@ -10644,13 +11004,17 @@ class LogMessageSourceDialogNode(LogMessageSource): """ An object that identifies the dialog element that generated the error message. - :attr str type: A string that indicates the type of dialog element that + :param str type: A string that indicates the type of dialog element that generated the error message. - :attr str dialog_node: The unique identifier of the dialog node that generated + :param str dialog_node: The unique identifier of the dialog node that generated the error message. """ - def __init__(self, type: str, dialog_node: str) -> None: + def __init__( + self, + type: str, + dialog_node: str, + ) -> None: """ Initialize a LogMessageSourceDialogNode object. @@ -10667,14 +11031,14 @@ def __init__(self, type: str, dialog_node: str) -> None: def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' ) - if 'dialog_node' in _dict: - args['dialog_node'] = _dict.get('dialog_node') + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node else: raise ValueError( 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' @@ -10718,22 +11082,24 @@ class LogMessageSourceHandler(LogMessageSource): """ An object that identifies the dialog element that generated the error message. - :attr str type: A string that indicates the type of dialog element that + :param str type: A string that indicates the type of dialog element that generated the error message. - :attr str action: The unique identifier of the action that generated the error + :param str action: The unique identifier of the action that generated the error message. - :attr str step: (optional) The unique identifier of the step that generated the + :param str step: (optional) The unique identifier of the step that generated the + error message. + :param str handler: The unique identifier of the handler that generated the error message. - :attr str handler: The unique identifier of the handler that generated the error - message. """ - def __init__(self, - type: str, - action: str, - handler: str, - *, - step: str = None) -> None: + def __init__( + self, + type: str, + action: str, + handler: str, + *, + step: Optional[str] = None, + ) -> None: """ Initialize a LogMessageSourceHandler object. @@ -10756,22 +11122,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': """Initialize a LogMessageSourceHandler object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in LogMessageSourceHandler JSON' ) - if 'action' in _dict: - args['action'] = _dict.get('action') + if (action := _dict.get('action')) is not None: + args['action'] = action else: raise ValueError( 'Required property \'action\' not present in LogMessageSourceHandler JSON' ) - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'handler' in _dict: - args['handler'] = _dict.get('handler') + if (step := _dict.get('step')) is not None: + args['step'] = step + if (handler := _dict.get('handler')) is not None: + args['handler'] = handler else: raise ValueError( 'Required property \'handler\' not present in LogMessageSourceHandler JSON' @@ -10819,15 +11185,20 @@ class LogMessageSourceStep(LogMessageSource): """ An object that identifies the dialog element that generated the error message. - :attr str type: A string that indicates the type of dialog element that + :param str type: A string that indicates the type of dialog element that generated the error message. - :attr str action: The unique identifier of the action that generated the error + :param str action: The unique identifier of the action that generated the error message. - :attr str step: The unique identifier of the step that generated the error + :param str step: The unique identifier of the step that generated the error message. """ - def __init__(self, type: str, action: str, step: str) -> None: + def __init__( + self, + type: str, + action: str, + step: str, + ) -> None: """ Initialize a LogMessageSourceStep object. @@ -10847,20 +11218,20 @@ def __init__(self, type: str, action: str, step: str) -> None: def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': """Initialize a LogMessageSourceStep object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in LogMessageSourceStep JSON' ) - if 'action' in _dict: - args['action'] = _dict.get('action') + if (action := _dict.get('action')) is not None: + args['action'] = action else: raise ValueError( 'Required property \'action\' not present in LogMessageSourceStep JSON' ) - if 'step' in _dict: - args['step'] = _dict.get('step') + if (step := _dict.get('step')) is not None: + args['step'] = step else: raise ValueError( 'Required property \'step\' not present in LogMessageSourceStep JSON' @@ -10907,25 +11278,27 @@ class MessageOutputDebugTurnEventTurnEventActionFinished( """ MessageOutputDebugTurnEventTurnEventActionFinished. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr str action_start_time: (optional) The time when the action started + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started processing the message. - :attr str condition_type: (optional) The type of condition (if any) that is + :param str condition_type: (optional) The type of condition (if any) that is defined for the action. - :attr str reason: (optional) The reason the action finished processing. - :attr dict action_variables: (optional) The state of all action variables at the - time the action finished. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables at + the time the action finished. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - action_start_time: str = None, - condition_type: str = None, - reason: str = None, - action_variables: dict = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + action_variables: Optional[dict] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object. @@ -10953,19 +11326,18 @@ def from_dict( ) -> 'MessageOutputDebugTurnEventTurnEventActionFinished': """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'action_start_time' in _dict: - args['action_start_time'] = _dict.get('action_start_time') - if 'condition_type' in _dict: - args['condition_type'] = _dict.get('condition_type') - if 'reason' in _dict: - args['reason'] = _dict.get('reason') - if 'action_variables' in _dict: - args['action_variables'] = _dict.get('action_variables') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables return cls(**args) @classmethod @@ -11021,6 +11393,7 @@ class ConditionTypeEnum(str, Enum): """ The type of condition (if any) that is defined for the action. """ + USER_DEFINED = 'user_defined' WELCOME = 'welcome' ANYTHING_ELSE = 'anything_else' @@ -11029,6 +11402,7 @@ class ReasonEnum(str, Enum): """ The reason the action finished processing. """ + ALL_STEPS_DONE = 'all_steps_done' NO_STEPS_VISITED = 'no_steps_visited' ENDED_BY_STEP = 'ended_by_step' @@ -11042,25 +11416,27 @@ class MessageOutputDebugTurnEventTurnEventActionVisited( """ MessageOutputDebugTurnEventTurnEventActionVisited. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr str action_start_time: (optional) The time when the action started + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started processing the message. - :attr str condition_type: (optional) The type of condition (if any) that is + :param str condition_type: (optional) The type of condition (if any) that is defined for the action. - :attr str reason: (optional) The reason the action was visited. - :attr str result_variable: (optional) The variable where the result of the call + :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the call to the action is stored. Included only if **reason**=`subaction_return`. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - action_start_time: str = None, - condition_type: str = None, - reason: str = None, - result_variable: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + result_variable: Optional[str] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. @@ -11089,19 +11465,18 @@ def from_dict( _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventActionVisited': """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'action_start_time' in _dict: - args['action_start_time'] = _dict.get('action_start_time') - if 'condition_type' in _dict: - args['condition_type'] = _dict.get('condition_type') - if 'reason' in _dict: - args['reason'] = _dict.get('reason') - if 'result_variable' in _dict: - args['result_variable'] = _dict.get('result_variable') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable return cls(**args) @classmethod @@ -11157,6 +11532,7 @@ class ConditionTypeEnum(str, Enum): """ The type of condition (if any) that is defined for the action. """ + USER_DEFINED = 'user_defined' WELCOME = 'welcome' ANYTHING_ELSE = 'anything_else' @@ -11165,6 +11541,7 @@ class ReasonEnum(str, Enum): """ The reason the action was visited. """ + INTENT = 'intent' INVOKE_SUBACTION = 'invoke_subaction' SUBACTION_RETURN = 'subaction_return' @@ -11180,18 +11557,20 @@ class MessageOutputDebugTurnEventTurnEventCallout(MessageOutputDebugTurnEvent): """ MessageOutputDebugTurnEventTurnEventCallout. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr TurnEventCalloutCallout callout: (optional) - :attr TurnEventCalloutError error: (optional) + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - callout: 'TurnEventCalloutCallout' = None, - error: 'TurnEventCalloutError' = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + callout: Optional['TurnEventCalloutCallout'] = None, + error: Optional['TurnEventCalloutError'] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventCallout object. @@ -11211,16 +11590,14 @@ def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventCallout': """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'callout' in _dict: - args['callout'] = TurnEventCalloutCallout.from_dict( - _dict.get('callout')) - if 'error' in _dict: - args['error'] = TurnEventCalloutError.from_dict(_dict.get('error')) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (callout := _dict.get('callout')) is not None: + args['callout'] = TurnEventCalloutCallout.from_dict(callout) + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventCalloutError.from_dict(error) return cls(**args) @classmethod @@ -11276,17 +11653,19 @@ class MessageOutputDebugTurnEventTurnEventHandlerVisited( """ MessageOutputDebugTurnEventTurnEventHandlerVisited. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr str action_start_time: (optional) The time when the action started + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started processing the message. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - action_start_time: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object. @@ -11306,13 +11685,12 @@ def from_dict( ) -> 'MessageOutputDebugTurnEventTurnEventHandlerVisited': """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'action_start_time' in _dict: - args['action_start_time'] = _dict.get('action_start_time') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time return cls(**args) @classmethod @@ -11363,16 +11741,18 @@ class MessageOutputDebugTurnEventTurnEventNodeVisited( """ MessageOutputDebugTurnEventTurnEventNodeVisited. - :attr str event: (optional) The type of turn event. - :attr TurnEventNodeSource source: (optional) - :attr str reason: (optional) The reason the dialog node was visited. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventNodeSource' = None, - reason: str = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventNodeSource'] = None, + reason: Optional[str] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object. @@ -11391,12 +11771,12 @@ def from_dict( _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventNodeVisited': """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventNodeSource.from_dict(_dict.get('source')) - if 'reason' in _dict: - args['reason'] = _dict.get('reason') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventNodeSource.from_dict(source) + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason return cls(**args) @classmethod @@ -11444,6 +11824,7 @@ class ReasonEnum(str, Enum): """ The reason the dialog node was visited. """ + WELCOME = 'welcome' BRANCH_START = 'branch_start' TOPIC_SWITCH = 'topic_switch' @@ -11456,16 +11837,18 @@ class MessageOutputDebugTurnEventTurnEventSearch(MessageOutputDebugTurnEvent): """ MessageOutputDebugTurnEventTurnEventSearch. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr TurnEventSearchError error: (optional) + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventSearchError error: (optional) """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - error: 'TurnEventSearchError' = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + error: Optional['TurnEventSearchError'] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventSearch object. @@ -11483,13 +11866,12 @@ def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventSearch': """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'error' in _dict: - args['error'] = TurnEventSearchError.from_dict(_dict.get('error')) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventSearchError.from_dict(error) return cls(**args) @classmethod @@ -11540,24 +11922,26 @@ class MessageOutputDebugTurnEventTurnEventStepAnswered( """ MessageOutputDebugTurnEventTurnEventStepAnswered. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr str condition_type: (optional) The type of condition (if any) that is + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is defined for the action. - :attr str action_start_time: (optional) The time when the action started + :param str action_start_time: (optional) The time when the action started processing the message. - :attr bool prompted: (optional) Whether the step was answered in response to a + :param bool prompted: (optional) Whether the step was answered in response to a prompt from the assistant. If this property is `false`, the user provided the answer without visiting the step. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - condition_type: str = None, - action_start_time: str = None, - prompted: bool = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + prompted: Optional[bool] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object. @@ -11584,17 +11968,16 @@ def from_dict( _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepAnswered': """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'condition_type' in _dict: - args['condition_type'] = _dict.get('condition_type') - if 'action_start_time' in _dict: - args['action_start_time'] = _dict.get('action_start_time') - if 'prompted' in _dict: - args['prompted'] = _dict.get('prompted') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (prompted := _dict.get('prompted')) is not None: + args['prompted'] = prompted return cls(**args) @classmethod @@ -11647,6 +12030,7 @@ class ConditionTypeEnum(str, Enum): """ The type of condition (if any) that is defined for the action. """ + USER_DEFINED = 'user_defined' WELCOME = 'welcome' ANYTHING_ELSE = 'anything_else' @@ -11657,23 +12041,25 @@ class MessageOutputDebugTurnEventTurnEventStepVisited( """ MessageOutputDebugTurnEventTurnEventStepVisited. - :attr str event: (optional) The type of turn event. - :attr TurnEventActionSource source: (optional) - :attr str condition_type: (optional) The type of condition (if any) that is + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is defined for the action. - :attr str action_start_time: (optional) The time when the action started + :param str action_start_time: (optional) The time when the action started processing the message. - :attr bool has_question: (optional) Whether the step collects a customer + :param bool has_question: (optional) Whether the step collects a customer response. """ - def __init__(self, - *, - event: str = None, - source: 'TurnEventActionSource' = None, - condition_type: str = None, - action_start_time: str = None, - has_question: bool = None) -> None: + def __init__( + self, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + has_question: Optional[bool] = None, + ) -> None: """ Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object. @@ -11699,17 +12085,16 @@ def from_dict( _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepVisited': """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" args = {} - if 'event' in _dict: - args['event'] = _dict.get('event') - if 'source' in _dict: - args['source'] = TurnEventActionSource.from_dict( - _dict.get('source')) - if 'condition_type' in _dict: - args['condition_type'] = _dict.get('condition_type') - if 'action_start_time' in _dict: - args['action_start_time'] = _dict.get('action_start_time') - if 'has_question' in _dict: - args['has_question'] = _dict.get('has_question') + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (has_question := _dict.get('has_question')) is not None: + args['has_question'] = has_question return cls(**args) @classmethod @@ -11762,6 +12147,7 @@ class ConditionTypeEnum(str, Enum): """ The type of condition (if any) that is defined for the action. """ + USER_DEFINED = 'user_defined' WELCOME = 'welcome' ANYTHING_ELSE = 'anything_else' @@ -11771,30 +12157,33 @@ class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeAudio. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the audio clip. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) The title or introductory text to show before the + response. + :param str description: (optional) The description to show with the the response. - :attr str description: (optional) The description to show with the the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the audio player cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. @@ -11829,31 +12218,30 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeAudio': """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -11913,26 +12301,28 @@ class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( """ RuntimeResponseGenericRuntimeResponseTypeChannelTransfer. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. **Note:** The `channel_transfer` response type is not supported on IBM Cloud Pak for Data. - :attr str message_to_user: The message to display to the user when initiating a + :param str message_to_user: The message to display to the user when initiating a channel transfer. - :attr ChannelTransferInfo transfer_info: Information used by an integration to + :param ChannelTransferInfo transfer_info: Information used by an integration to transfer the conversation to a different channel. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - message_to_user: str, - transfer_info: 'ChannelTransferInfo', - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + message_to_user: str, + transfer_info: 'ChannelTransferInfo', + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object. @@ -11962,29 +12352,27 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer': """Initialize a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'message_to_user' in _dict: - args['message_to_user'] = _dict.get('message_to_user') + if (message_to_user := _dict.get('message_to_user')) is not None: + args['message_to_user'] = message_to_user else: raise ValueError( 'Required property \'message_to_user\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'transfer_info' in _dict: - args['transfer_info'] = ChannelTransferInfo.from_dict( - _dict.get('transfer_info')) + if (transfer_info := _dict.get('transfer_info')) is not None: + args['transfer_info'] = ChannelTransferInfo.from_dict(transfer_info) else: raise ValueError( 'Required property \'transfer_info\' not present in RuntimeResponseGenericRuntimeResponseTypeChannelTransfer JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12044,38 +12432,40 @@ class RuntimeResponseGenericRuntimeResponseTypeConnectToAgent( """ RuntimeResponseGenericRuntimeResponseTypeConnectToAgent. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str message_to_human_agent: (optional) A message to be sent to the human + :param str message_to_human_agent: (optional) A message to be sent to the human agent who will be taking over the conversation. - :attr AgentAvailabilityMessage agent_available: (optional) An optional message + :param AgentAvailabilityMessage agent_available: (optional) An optional message to be displayed to the user to indicate that the conversation will be transferred to the next available agent. - :attr AgentAvailabilityMessage agent_unavailable: (optional) An optional message - to be displayed to the user to indicate that no online agent is available to - take over the conversation. - :attr DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) + :param AgentAvailabilityMessage agent_unavailable: (optional) An optional + message to be displayed to the user to indicate that no online agent is + available to take over the conversation. + :param DialogNodeOutputConnectToAgentTransferInfo transfer_info: (optional) Routing or other contextual information to be used by target service desk systems. - :attr str topic: (optional) A label identifying the topic of the conversation, + :param str topic: (optional) A label identifying the topic of the conversation, derived from the **title** property of the relevant node or the **topic** property of the dialog node response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ def __init__( - self, - response_type: str, - *, - message_to_human_agent: str = None, - agent_available: 'AgentAvailabilityMessage' = None, - agent_unavailable: 'AgentAvailabilityMessage' = None, - transfer_info: 'DialogNodeOutputConnectToAgentTransferInfo' = None, - topic: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + self, + response_type: str, + *, + message_to_human_agent: Optional[str] = None, + agent_available: Optional['AgentAvailabilityMessage'] = None, + agent_unavailable: Optional['AgentAvailabilityMessage'] = None, + transfer_info: Optional[ + 'DialogNodeOutputConnectToAgentTransferInfo'] = None, + topic: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object. @@ -12116,30 +12506,30 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent': """Initialize a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeConnectToAgent JSON' ) - if 'message_to_human_agent' in _dict: - args['message_to_human_agent'] = _dict.get('message_to_human_agent') - if 'agent_available' in _dict: + if (message_to_human_agent := + _dict.get('message_to_human_agent')) is not None: + args['message_to_human_agent'] = message_to_human_agent + if (agent_available := _dict.get('agent_available')) is not None: args['agent_available'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_available')) - if 'agent_unavailable' in _dict: + agent_available) + if (agent_unavailable := _dict.get('agent_unavailable')) is not None: args['agent_unavailable'] = AgentAvailabilityMessage.from_dict( - _dict.get('agent_unavailable')) - if 'transfer_info' in _dict: + agent_unavailable) + if (transfer_info := _dict.get('transfer_info')) is not None: args[ 'transfer_info'] = DialogNodeOutputConnectToAgentTransferInfo.from_dict( - _dict.get('transfer_info')) - if 'topic' in _dict: - args['topic'] = _dict.get('topic') - if 'channels' in _dict: + transfer_info) + if (topic := _dict.get('topic')) is not None: + args['topic'] = topic + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12212,11 +12602,14 @@ class RuntimeResponseGenericRuntimeResponseTypeDate(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeDate. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. """ - def __init__(self, response_type: str) -> None: + def __init__( + self, + response_type: str, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object. @@ -12233,8 +12626,8 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeDate': """Initialize a RuntimeResponseGenericRuntimeResponseTypeDate object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeDate JSON' @@ -12278,28 +12671,31 @@ class RuntimeResponseGenericRuntimeResponseTypeIframe(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeIframe. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the embeddable content. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the embeddable content. + :param str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the the response. - :attr str image_url: (optional) The URL of an image that shows a preview of the + :param str description: (optional) The description to show with the the + response. + :param str image_url: (optional) The URL of an image that shows a preview of the embedded content. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - image_url: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + image_url: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object. @@ -12332,28 +12728,27 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeIframe': """Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'image_url' in _dict: - args['image_url'] = _dict.get('image_url') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (image_url := _dict.get('image_url')) is not None: + args['image_url'] = image_url + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12412,27 +12807,30 @@ class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeImage. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the image. - :attr str title: (optional) The title to show before the response. - :attr str description: (optional) The description to show with the the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str source: The `https:` URL of the image. + :param str title: (optional) The title to show before the response. + :param str description: (optional) The description to show with the the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the image cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. @@ -12464,29 +12862,28 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeImage': """Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeImage JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod @@ -12542,27 +12939,30 @@ class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeOption. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the the response. - :attr str preference: (optional) The preferred type of control to display. - :attr List[DialogNodeOutputOptionsElement] options: An array of objects + :param str title: The title or introductory text to show before the response. + :param str description: (optional) The description to show with the the + response. + :param str preference: (optional) The preferred type of control to display. + :param List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - options: List['DialogNodeOutputOptionsElement'], - *, - description: str = None, - preference: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: Optional[str] = None, + preference: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object. @@ -12595,35 +12995,33 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeOption': """Initialize a RuntimeResponseGenericRuntimeResponseTypeOption object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (preference := _dict.get('preference')) is not None: + args['preference'] = preference + if (options := _dict.get('options')) is not None: args['options'] = [ - DialogNodeOutputOptionsElement.from_dict(v) - for v in _dict.get('options') + DialogNodeOutputOptionsElement.from_dict(v) for v in options ] else: raise ValueError( 'Required property \'options\' not present in RuntimeResponseGenericRuntimeResponseTypeOption JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12687,6 +13085,7 @@ class PreferenceEnum(str, Enum): """ The preferred type of control to display. """ + DROPDOWN = 'dropdown' BUTTON = 'button' @@ -12695,23 +13094,25 @@ class RuntimeResponseGenericRuntimeResponseTypePause(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypePause. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr int time: How long to pause, in milliseconds. - :attr bool typing: (optional) Whether to send a "user is typing" event during + :param int time: How long to pause, in milliseconds. + :param bool typing: (optional) Whether to send a "user is typing" event during the pause. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - time: int, - *, - typing: bool = None, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + time: int, + *, + typing: Optional[bool] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypePause object. @@ -12738,24 +13139,23 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypePause': """Initialize a RuntimeResponseGenericRuntimeResponseTypePause object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'time' in _dict: - args['time'] = _dict.get('time') + if (time := _dict.get('time')) is not None: + args['time'] = time else: raise ValueError( 'Required property \'time\' not present in RuntimeResponseGenericRuntimeResponseTypePause JSON' ) - if 'typing' in _dict: - args['typing'] = _dict.get('typing') - if 'channels' in _dict: + if (typing := _dict.get('typing')) is not None: + args['typing'] = typing + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12808,27 +13208,29 @@ class RuntimeResponseGenericRuntimeResponseTypeSearch(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeSearch. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str header: The title or introductory text to show before the response. + :param str header: The title or introductory text to show before the response. This text is defined in the search skill configuration. - :attr List[SearchResult] primary_results: An array of objects that contains the + :param List[SearchResult] primary_results: An array of objects that contains the search results to be displayed in the initial response to the user. - :attr List[SearchResult] additional_results: An array of objects that contains + :param List[SearchResult] additional_results: An array of objects that contains additional search results that can be displayed to the user upon request. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - header: str, - primary_results: List['SearchResult'], - additional_results: List['SearchResult'], - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + header: str, + primary_results: List['SearchResult'], + additional_results: List['SearchResult'], + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSearch object. @@ -12861,39 +13263,37 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeSearch': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSearch object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'header' in _dict: - args['header'] = _dict.get('header') + if (header := _dict.get('header')) is not None: + args['header'] = header else: raise ValueError( 'Required property \'header\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'primary_results' in _dict: + if (primary_results := _dict.get('primary_results')) is not None: args['primary_results'] = [ - SearchResult.from_dict(v) for v in _dict.get('primary_results') + SearchResult.from_dict(v) for v in primary_results ] else: raise ValueError( 'Required property \'primary_results\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'additional_results' in _dict: + if (additional_results := _dict.get('additional_results')) is not None: args['additional_results'] = [ - SearchResult.from_dict(v) - for v in _dict.get('additional_results') + SearchResult.from_dict(v) for v in additional_results ] else: raise ValueError( 'Required property \'additional_results\' not present in RuntimeResponseGenericRuntimeResponseTypeSearch JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -12966,23 +13366,25 @@ class RuntimeResponseGenericRuntimeResponseTypeSuggestion( """ RuntimeResponseGenericRuntimeResponseTypeSuggestion. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: The title or introductory text to show before the response. - :attr List[DialogSuggestion] suggestions: An array of objects describing the + :param str title: The title or introductory text to show before the response. + :param List[DialogSuggestion] suggestions: An array of objects describing the possible matching dialog nodes from which the user can choose. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - title: str, - suggestions: List['DialogSuggestion'], - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + title: str, + suggestions: List['DialogSuggestion'], + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object. @@ -13010,30 +13412,29 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeSuggestion': """Initialize a RuntimeResponseGenericRuntimeResponseTypeSuggestion object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if (title := _dict.get('title')) is not None: + args['title'] = title else: raise ValueError( 'Required property \'title\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'suggestions' in _dict: + if (suggestions := _dict.get('suggestions')) is not None: args['suggestions'] = [ - DialogSuggestion.from_dict(v) for v in _dict.get('suggestions') + DialogSuggestion.from_dict(v) for v in suggestions ] else: raise ValueError( 'Required property \'suggestions\' not present in RuntimeResponseGenericRuntimeResponseTypeSuggestion JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13094,20 +13495,22 @@ class RuntimeResponseGenericRuntimeResponseTypeText(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeText. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str text: The text of the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param str text: The text of the response. + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - text: str, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + text: str, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeText object. @@ -13131,22 +13534,21 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeText': """Initialize a RuntimeResponseGenericRuntimeResponseTypeText object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeText JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13198,21 +13600,23 @@ class RuntimeResponseGenericRuntimeResponseTypeUserDefined( """ RuntimeResponseGenericRuntimeResponseTypeUserDefined. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr dict user_defined: An object containing any properties for the + :param dict user_defined: An object containing any properties for the user-defined response type. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. """ - def __init__(self, - response_type: str, - user_defined: dict, - *, - channels: List['ResponseGenericChannel'] = None) -> None: + def __init__( + self, + response_type: str, + user_defined: dict, + *, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object. @@ -13237,22 +13641,21 @@ def from_dict( ) -> 'RuntimeResponseGenericRuntimeResponseTypeUserDefined': """Initialize a RuntimeResponseGenericRuntimeResponseTypeUserDefined object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined else: raise ValueError( 'Required property \'user_defined\' not present in RuntimeResponseGenericRuntimeResponseTypeUserDefined JSON' ) - if 'channels' in _dict: + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] return cls(**args) @@ -13305,30 +13708,33 @@ class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeVideo. - :attr str response_type: The type of response returned by the dialog node. The + :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the video. - :attr str title: (optional) The title or introductory text to show before the + :param str source: The `https:` URL of the video. + :param str title: (optional) The title or introductory text to show before the + response. + :param str description: (optional) The description to show with the the response. - :attr str description: (optional) The description to show with the the response. - :attr List[ResponseGenericChannel] channels: (optional) An array of objects + :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. - :attr dict channel_options: (optional) For internal use only. - :attr str alt_text: (optional) Descriptive text that can be used for screen + :param dict channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for screen readers or other situations where the video cannot be seen. """ - def __init__(self, - response_type: str, - source: str, - *, - title: str = None, - description: str = None, - channels: List['ResponseGenericChannel'] = None, - channel_options: dict = None, - alt_text: str = None) -> None: + def __init__( + self, + response_type: str, + source: str, + *, + title: Optional[str] = None, + description: Optional[str] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + channel_options: Optional[dict] = None, + alt_text: Optional[str] = None, + ) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. @@ -13363,31 +13769,30 @@ def from_dict( _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeVideo': """Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object from a json dictionary.""" args = {} - if 'response_type' in _dict: - args['response_type'] = _dict.get('response_type') + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type else: raise ValueError( 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'channels' in _dict: + if (title := _dict.get('title')) is not None: + args['title'] = title + if (description := _dict.get('description')) is not None: + args['description'] = description + if (channels := _dict.get('channels')) is not None: args['channels'] = [ - ResponseGenericChannel.from_dict(v) - for v in _dict.get('channels') + ResponseGenericChannel.from_dict(v) for v in channels ] - if 'channel_options' in _dict: - args['channel_options'] = _dict.get('channel_options') - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + if (alt_text := _dict.get('alt_text')) is not None: + args['alt_text'] = alt_text return cls(**args) @classmethod diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 28c723130..b8285e54a 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ IBM Watson™ Discovery v1 is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive @@ -30,7 +30,7 @@ from datetime import datetime from enum import Enum from os.path import basename -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json import sys @@ -83,12 +83,14 @@ def __init__( # Environments ######################### - def create_environment(self, - name: str, - *, - description: str = None, - size: str = None, - **kwargs) -> DetailedResponse: + def create_environment( + self, + name: str, + *, + description: Optional[str] = None, + size: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create an environment. @@ -110,9 +112,11 @@ def create_environment(self, if name is None: raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_environment', + ) headers.update(sdk_headers) params = { @@ -134,19 +138,23 @@ def create_environment(self, headers['Accept'] = 'application/json' url = '/v1/environments' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def list_environments(self, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def list_environments( + self, + *, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List environments. @@ -159,9 +167,11 @@ def list_environments(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_environments') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_environments', + ) headers.update(sdk_headers) params = { @@ -175,16 +185,21 @@ def list_environments(self, headers['Accept'] = 'application/json' url = '/v1/environments' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_environment(self, environment_id: str, - **kwargs) -> DetailedResponse: + def get_environment( + self, + environment_id: str, + **kwargs, + ) -> DetailedResponse: """ Get environment info. @@ -197,9 +212,11 @@ def get_environment(self, environment_id: str, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_environment', + ) headers.update(sdk_headers) params = { @@ -215,21 +232,25 @@ def get_environment(self, environment_id: str, path_param_values = self.encode_path_vars(environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_environment(self, - environment_id: str, - *, - name: str = None, - description: str = None, - size: str = None, - **kwargs) -> DetailedResponse: + def update_environment( + self, + environment_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + size: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update an environment. @@ -249,9 +270,11 @@ def update_environment(self, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_environment', + ) headers.update(sdk_headers) params = { @@ -276,17 +299,22 @@ def update_environment(self, path_param_values = self.encode_path_vars(environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_environment(self, environment_id: str, - **kwargs) -> DetailedResponse: + def delete_environment( + self, + environment_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete environment. @@ -299,9 +327,11 @@ def delete_environment(self, environment_id: str, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_environment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_environment', + ) headers.update(sdk_headers) params = { @@ -317,16 +347,22 @@ def delete_environment(self, environment_id: str, path_param_values = self.encode_path_vars(environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_fields(self, environment_id: str, collection_ids: List[str], - **kwargs) -> DetailedResponse: + def list_fields( + self, + environment_id: str, + collection_ids: List[str], + **kwargs, + ) -> DetailedResponse: """ List fields across collections. @@ -346,9 +382,11 @@ def list_fields(self, environment_id: str, collection_ids: List[str], if collection_ids is None: raise ValueError('collection_ids must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_fields') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_fields', + ) headers.update(sdk_headers) params = { @@ -366,10 +404,12 @@ def list_fields(self, environment_id: str, collection_ids: List[str], path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/fields'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -379,16 +419,17 @@ def list_fields(self, environment_id: str, collection_ids: List[str], ######################### def create_configuration( - self, - environment_id: str, - name: str, - *, - description: str = None, - conversions: 'Conversions' = None, - enrichments: List['Enrichment'] = None, - normalizations: List['NormalizationOperation'] = None, - source: 'Source' = None, - **kwargs) -> DetailedResponse: + self, + environment_id: str, + name: str, + *, + description: Optional[str] = None, + conversions: Optional['Conversions'] = None, + enrichments: Optional[List['Enrichment']] = None, + normalizations: Optional[List['NormalizationOperation']] = None, + source: Optional['Source'] = None, + **kwargs, + ) -> DetailedResponse: """ Add configuration. @@ -434,9 +475,11 @@ def create_configuration( if source is not None: source = convert_model(source) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_configuration') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_configuration', + ) headers.update(sdk_headers) params = { @@ -465,20 +508,24 @@ def create_configuration( path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/configurations'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def list_configurations(self, - environment_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def list_configurations( + self, + environment_id: str, + *, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List configurations. @@ -494,9 +541,11 @@ def list_configurations(self, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_configurations') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_configurations', + ) headers.update(sdk_headers) params = { @@ -514,16 +563,22 @@ def list_configurations(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/configurations'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_configuration(self, environment_id: str, configuration_id: str, - **kwargs) -> DetailedResponse: + def get_configuration( + self, + environment_id: str, + configuration_id: str, + **kwargs, + ) -> DetailedResponse: """ Get configuration details. @@ -539,9 +594,11 @@ def get_configuration(self, environment_id: str, configuration_id: str, if not configuration_id: raise ValueError('configuration_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_configuration') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_configuration', + ) headers.update(sdk_headers) params = { @@ -559,26 +616,29 @@ def get_configuration(self, environment_id: str, configuration_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response def update_configuration( - self, - environment_id: str, - configuration_id: str, - name: str, - *, - description: str = None, - conversions: 'Conversions' = None, - enrichments: List['Enrichment'] = None, - normalizations: List['NormalizationOperation'] = None, - source: 'Source' = None, - **kwargs) -> DetailedResponse: + self, + environment_id: str, + configuration_id: str, + name: str, + *, + description: Optional[str] = None, + conversions: Optional['Conversions'] = None, + enrichments: Optional[List['Enrichment']] = None, + normalizations: Optional[List['NormalizationOperation']] = None, + source: Optional['Source'] = None, + **kwargs, + ) -> DetailedResponse: """ Update a configuration. @@ -626,9 +686,11 @@ def update_configuration( if source is not None: source = convert_model(source) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_configuration') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_configuration', + ) headers.update(sdk_headers) params = { @@ -658,17 +720,23 @@ def update_configuration( path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_configuration(self, environment_id: str, configuration_id: str, - **kwargs) -> DetailedResponse: + def delete_configuration( + self, + environment_id: str, + configuration_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a configuration. @@ -691,9 +759,11 @@ def delete_configuration(self, environment_id: str, configuration_id: str, if not configuration_id: raise ValueError('configuration_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_configuration') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_configuration', + ) headers.update(sdk_headers) params = { @@ -711,10 +781,12 @@ def delete_configuration(self, environment_id: str, configuration_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -723,14 +795,16 @@ def delete_configuration(self, environment_id: str, configuration_id: str, # Collections ######################### - def create_collection(self, - environment_id: str, - name: str, - *, - description: str = None, - configuration_id: str = None, - language: str = None, - **kwargs) -> DetailedResponse: + def create_collection( + self, + environment_id: str, + name: str, + *, + description: Optional[str] = None, + configuration_id: Optional[str] = None, + language: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create a collection. @@ -751,9 +825,11 @@ def create_collection(self, if name is None: raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_collection', + ) headers.update(sdk_headers) params = { @@ -780,20 +856,24 @@ def create_collection(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def list_collections(self, - environment_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def list_collections( + self, + environment_id: str, + *, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List collections. @@ -809,9 +889,11 @@ def list_collections(self, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_collections') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_collections', + ) headers.update(sdk_headers) params = { @@ -829,16 +911,22 @@ def list_collections(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_collection(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def get_collection( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get collection details. @@ -854,9 +942,11 @@ def get_collection(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_collection', + ) headers.update(sdk_headers) params = { @@ -873,22 +963,26 @@ def get_collection(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_collection(self, - environment_id: str, - collection_id: str, - name: str, - *, - description: str = None, - configuration_id: str = None, - **kwargs) -> DetailedResponse: + def update_collection( + self, + environment_id: str, + collection_id: str, + name: str, + *, + description: Optional[str] = None, + configuration_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update a collection. @@ -910,9 +1004,11 @@ def update_collection(self, if name is None: raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_collection', + ) headers.update(sdk_headers) params = { @@ -938,17 +1034,23 @@ def update_collection(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_collection(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_collection( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a collection. @@ -964,9 +1066,11 @@ def delete_collection(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_collection', + ) headers.update(sdk_headers) params = { @@ -983,16 +1087,22 @@ def delete_collection(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_collection_fields(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def list_collection_fields( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ List collection fields. @@ -1010,9 +1120,11 @@ def list_collection_fields(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_collection_fields') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_collection_fields', + ) headers.update(sdk_headers) params = { @@ -1029,10 +1141,12 @@ def list_collection_fields(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/fields'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1041,8 +1155,12 @@ def list_collection_fields(self, environment_id: str, collection_id: str, # Query modifications ######################### - def list_expansions(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def list_expansions( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get the expansion list. @@ -1061,9 +1179,11 @@ def list_expansions(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_expansions', + ) headers.update(sdk_headers) params = { @@ -1080,17 +1200,23 @@ def list_expansions(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_expansions(self, environment_id: str, collection_id: str, - expansions: List['Expansion'], - **kwargs) -> DetailedResponse: + def create_expansions( + self, + environment_id: str, + collection_id: str, + expansions: List['Expansion'], + **kwargs, + ) -> DetailedResponse: """ Create or update expansion list. @@ -1126,9 +1252,11 @@ def create_expansions(self, environment_id: str, collection_id: str, raise ValueError('expansions must be provided') expansions = [convert_model(x) for x in expansions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_expansions', + ) headers.update(sdk_headers) params = { @@ -1152,17 +1280,23 @@ def create_expansions(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_expansions(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_expansions( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete the expansion list. @@ -1181,9 +1315,11 @@ def delete_expansions(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_expansions', + ) headers.update(sdk_headers) params = { @@ -1199,17 +1335,22 @@ def delete_expansions(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_tokenization_dictionary_status(self, environment_id: str, - collection_id: str, - **kwargs) -> DetailedResponse: + def get_tokenization_dictionary_status( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get tokenization dictionary status. @@ -1231,7 +1372,8 @@ def get_tokenization_dictionary_status(self, environment_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='get_tokenization_dictionary_status') + operation_id='get_tokenization_dictionary_status', + ) headers.update(sdk_headers) params = { @@ -1248,21 +1390,24 @@ def get_tokenization_dictionary_status(self, environment_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response def create_tokenization_dictionary( - self, - environment_id: str, - collection_id: str, - *, - tokenization_rules: List['TokenDictRule'] = None, - **kwargs) -> DetailedResponse: + self, + environment_id: str, + collection_id: str, + *, + tokenization_rules: Optional[List['TokenDictRule']] = None, + **kwargs, + ) -> DetailedResponse: """ Create tokenization dictionary. @@ -1289,7 +1434,8 @@ def create_tokenization_dictionary( sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='create_tokenization_dictionary') + operation_id='create_tokenization_dictionary', + ) headers.update(sdk_headers) params = { @@ -1313,18 +1459,23 @@ def create_tokenization_dictionary( path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_tokenization_dictionary(self, environment_id: str, - collection_id: str, - **kwargs) -> DetailedResponse: + def delete_tokenization_dictionary( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete tokenization dictionary. @@ -1345,7 +1496,8 @@ def delete_tokenization_dictionary(self, environment_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='delete_tokenization_dictionary') + operation_id='delete_tokenization_dictionary', + ) headers.update(sdk_headers) params = { @@ -1361,16 +1513,22 @@ def delete_tokenization_dictionary(self, environment_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_stopword_list_status(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def get_stopword_list_status( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get stopword list status. @@ -1388,9 +1546,11 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_stopword_list_status') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_stopword_list_status', + ) headers.update(sdk_headers) params = { @@ -1407,21 +1567,25 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_stopword_list(self, - environment_id: str, - collection_id: str, - stopword_file: BinaryIO, - *, - stopword_filename: str = None, - **kwargs) -> DetailedResponse: + def create_stopword_list( + self, + environment_id: str, + collection_id: str, + stopword_file: BinaryIO, + *, + stopword_filename: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create stopword list. @@ -1443,9 +1607,11 @@ def create_stopword_list(self, if stopword_file is None: raise ValueError('stopword_file must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_stopword_list') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_stopword_list', + ) headers.update(sdk_headers) params = { @@ -1470,17 +1636,23 @@ def create_stopword_list(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_stopword_list(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_stopword_list( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom stopword list. @@ -1499,9 +1671,11 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_stopword_list') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_stopword_list', + ) headers.update(sdk_headers) params = { @@ -1517,10 +1691,12 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1529,15 +1705,17 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, # Documents ######################### - def add_document(self, - environment_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - **kwargs) -> DetailedResponse: + def add_document( + self, + environment_id: str, + collection_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Add a document. @@ -1585,9 +1763,11 @@ def add_document(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_document', + ) headers.update(sdk_headers) params = { @@ -1615,17 +1795,24 @@ def add_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/documents'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_document_status(self, environment_id: str, collection_id: str, - document_id: str, **kwargs) -> DetailedResponse: + def get_document_status( + self, + environment_id: str, + collection_id: str, + document_id: str, + **kwargs, + ) -> DetailedResponse: """ Get document details. @@ -1649,9 +1836,11 @@ def get_document_status(self, environment_id: str, collection_id: str, if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_document_status') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_document_status', + ) headers.update(sdk_headers) params = { @@ -1669,24 +1858,28 @@ def get_document_status(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_document(self, - environment_id: str, - collection_id: str, - document_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - **kwargs) -> DetailedResponse: + def update_document( + self, + environment_id: str, + collection_id: str, + document_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update a document. @@ -1721,9 +1914,11 @@ def update_document(self, if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_document', + ) headers.update(sdk_headers) params = { @@ -1752,17 +1947,24 @@ def update_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_document(self, environment_id: str, collection_id: str, - document_id: str, **kwargs) -> DetailedResponse: + def delete_document( + self, + environment_id: str, + collection_id: str, + document_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a document. @@ -1785,9 +1987,11 @@ def delete_document(self, environment_id: str, collection_id: str, if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_document', + ) headers.update(sdk_headers) params = { @@ -1805,10 +2009,12 @@ def delete_document(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1817,32 +2023,34 @@ def delete_document(self, environment_id: str, collection_id: str, # Queries ######################### - def query(self, - environment_id: str, - collection_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - passages: bool = None, - aggregation: str = None, - count: int = None, - return_: str = None, - offset: int = None, - sort: str = None, - highlight: bool = None, - passages_fields: str = None, - passages_count: int = None, - passages_characters: int = None, - deduplicate: bool = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: str = None, - similar_fields: str = None, - bias: str = None, - spelling_suggestions: bool = None, - x_watson_logging_opt_out: bool = None, - **kwargs) -> DetailedResponse: + def query( + self, + environment_id: str, + collection_id: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + passages: Optional[bool] = None, + aggregation: Optional[str] = None, + count: Optional[int] = None, + return_: Optional[str] = None, + offset: Optional[int] = None, + sort: Optional[str] = None, + highlight: Optional[bool] = None, + passages_fields: Optional[str] = None, + passages_count: Optional[int] = None, + passages_characters: Optional[int] = None, + deduplicate: Optional[bool] = None, + deduplicate_field: Optional[str] = None, + similar: Optional[bool] = None, + similar_document_ids: Optional[str] = None, + similar_fields: Optional[str] = None, + bias: Optional[str] = None, + spelling_suggestions: Optional[bool] = None, + x_watson_logging_opt_out: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Query a collection. @@ -1938,9 +2146,11 @@ def query(self, headers = { 'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='query', + ) headers.update(sdk_headers) params = { @@ -1983,37 +2193,41 @@ def query(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/query'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def query_notices(self, - environment_id: str, - collection_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - passages: bool = None, - aggregation: str = None, - count: int = None, - return_: List[str] = None, - offset: int = None, - sort: List[str] = None, - highlight: bool = None, - passages_fields: List[str] = None, - passages_count: int = None, - passages_characters: int = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: List[str] = None, - similar_fields: List[str] = None, - **kwargs) -> DetailedResponse: + def query_notices( + self, + environment_id: str, + collection_id: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + passages: Optional[bool] = None, + aggregation: Optional[str] = None, + count: Optional[int] = None, + return_: Optional[List[str]] = None, + offset: Optional[int] = None, + sort: Optional[List[str]] = None, + highlight: Optional[bool] = None, + passages_fields: Optional[List[str]] = None, + passages_count: Optional[int] = None, + passages_characters: Optional[int] = None, + deduplicate_field: Optional[str] = None, + similar: Optional[bool] = None, + similar_document_ids: Optional[List[str]] = None, + similar_fields: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: """ Query system notices. @@ -2089,9 +2303,11 @@ def query_notices(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query_notices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='query_notices', + ) headers.update(sdk_headers) params = { @@ -2125,39 +2341,43 @@ def query_notices(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/notices'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def federated_query(self, - environment_id: str, - collection_ids: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - passages: bool = None, - aggregation: str = None, - count: int = None, - return_: str = None, - offset: int = None, - sort: str = None, - highlight: bool = None, - passages_fields: str = None, - passages_count: int = None, - passages_characters: int = None, - deduplicate: bool = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: str = None, - similar_fields: str = None, - bias: str = None, - x_watson_logging_opt_out: bool = None, - **kwargs) -> DetailedResponse: + def federated_query( + self, + environment_id: str, + collection_ids: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + passages: Optional[bool] = None, + aggregation: Optional[str] = None, + count: Optional[int] = None, + return_: Optional[str] = None, + offset: Optional[int] = None, + sort: Optional[str] = None, + highlight: Optional[bool] = None, + passages_fields: Optional[str] = None, + passages_count: Optional[int] = None, + passages_characters: Optional[int] = None, + deduplicate: Optional[bool] = None, + deduplicate_field: Optional[str] = None, + similar: Optional[bool] = None, + similar_document_ids: Optional[str] = None, + similar_fields: Optional[str] = None, + bias: Optional[str] = None, + x_watson_logging_opt_out: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Query multiple collections. @@ -2248,9 +2468,11 @@ def federated_query(self, headers = { 'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='federated_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='federated_query', + ) headers.update(sdk_headers) params = { @@ -2293,33 +2515,37 @@ def federated_query(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/query'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def federated_query_notices(self, - environment_id: str, - collection_ids: List[str], - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - aggregation: str = None, - count: int = None, - return_: List[str] = None, - offset: int = None, - sort: List[str] = None, - highlight: bool = None, - deduplicate_field: str = None, - similar: bool = None, - similar_document_ids: List[str] = None, - similar_fields: List[str] = None, - **kwargs) -> DetailedResponse: + def federated_query_notices( + self, + environment_id: str, + collection_ids: List[str], + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + aggregation: Optional[str] = None, + count: Optional[int] = None, + return_: Optional[List[str]] = None, + offset: Optional[int] = None, + sort: Optional[List[str]] = None, + highlight: Optional[bool] = None, + deduplicate_field: Optional[str] = None, + similar: Optional[bool] = None, + similar_document_ids: Optional[List[str]] = None, + similar_fields: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: """ Query multiple collection system notices. @@ -2386,9 +2612,11 @@ def federated_query_notices(self, if collection_ids is None: raise ValueError('collection_ids must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='federated_query_notices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='federated_query_notices', + ) headers.update(sdk_headers) params = { @@ -2419,22 +2647,26 @@ def federated_query_notices(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/notices'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_autocompletion(self, - environment_id: str, - collection_id: str, - prefix: str, - *, - field: str = None, - count: int = None, - **kwargs) -> DetailedResponse: + def get_autocompletion( + self, + environment_id: str, + collection_id: str, + prefix: str, + *, + field: Optional[str] = None, + count: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Get Autocomplete Suggestions. @@ -2462,9 +2694,11 @@ def get_autocompletion(self, if not prefix: raise ValueError('prefix must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_autocompletion') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_autocompletion', + ) headers.update(sdk_headers) params = { @@ -2484,10 +2718,12 @@ def get_autocompletion(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/autocompletion'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2496,8 +2732,12 @@ def get_autocompletion(self, # Training data ######################### - def list_training_data(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def list_training_data( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ List training data. @@ -2515,9 +2755,11 @@ def list_training_data(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_training_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_training_data', + ) headers.update(sdk_headers) params = { @@ -2534,22 +2776,26 @@ def list_training_data(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def add_training_data(self, - environment_id: str, - collection_id: str, - *, - natural_language_query: str = None, - filter: str = None, - examples: List['TrainingExample'] = None, - **kwargs) -> DetailedResponse: + def add_training_data( + self, + environment_id: str, + collection_id: str, + *, + natural_language_query: Optional[str] = None, + filter: Optional[str] = None, + examples: Optional[List['TrainingExample']] = None, + **kwargs, + ) -> DetailedResponse: """ Add query to training data. @@ -2576,9 +2822,11 @@ def add_training_data(self, if examples is not None: examples = [convert_model(x) for x in examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_training_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_training_data', + ) headers.update(sdk_headers) params = { @@ -2604,17 +2852,23 @@ def add_training_data(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_all_training_data(self, environment_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_all_training_data( + self, + environment_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete all training data. @@ -2632,9 +2886,11 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_all_training_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_all_training_data', + ) headers.update(sdk_headers) params = { @@ -2650,16 +2906,23 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_training_data(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> DetailedResponse: + def get_training_data( + self, + environment_id: str, + collection_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ Get details about a query. @@ -2681,9 +2944,11 @@ def get_training_data(self, environment_id: str, collection_id: str, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_training_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_training_data', + ) headers.update(sdk_headers) params = { @@ -2701,16 +2966,23 @@ def get_training_data(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_training_data(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> DetailedResponse: + def delete_training_data( + self, + environment_id: str, + collection_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a training data query. @@ -2732,9 +3004,11 @@ def delete_training_data(self, environment_id: str, collection_id: str, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_training_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_training_data', + ) headers.update(sdk_headers) params = { @@ -2751,16 +3025,23 @@ def delete_training_data(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_training_examples(self, environment_id: str, collection_id: str, - query_id: str, **kwargs) -> DetailedResponse: + def list_training_examples( + self, + environment_id: str, + collection_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ List examples for a training data query. @@ -2781,9 +3062,11 @@ def list_training_examples(self, environment_id: str, collection_id: str, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_training_examples') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_training_examples', + ) headers.update(sdk_headers) params = { @@ -2801,23 +3084,27 @@ def list_training_examples(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_training_example(self, - environment_id: str, - collection_id: str, - query_id: str, - *, - document_id: str = None, - cross_reference: str = None, - relevance: int = None, - **kwargs) -> DetailedResponse: + def create_training_example( + self, + environment_id: str, + collection_id: str, + query_id: str, + *, + document_id: Optional[str] = None, + cross_reference: Optional[str] = None, + relevance: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Add example to training data query. @@ -2843,9 +3130,11 @@ def create_training_example(self, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_training_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_training_example', + ) headers.update(sdk_headers) params = { @@ -2872,18 +3161,25 @@ def create_training_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_training_example(self, environment_id: str, collection_id: str, - query_id: str, example_id: str, - **kwargs) -> DetailedResponse: + def delete_training_example( + self, + environment_id: str, + collection_id: str, + query_id: str, + example_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete example for training data query. @@ -2907,9 +3203,11 @@ def delete_training_example(self, environment_id: str, collection_id: str, if not example_id: raise ValueError('example_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_training_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_training_example', + ) headers.update(sdk_headers) params = { @@ -2928,23 +3226,27 @@ def delete_training_example(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_training_example(self, - environment_id: str, - collection_id: str, - query_id: str, - example_id: str, - *, - cross_reference: str = None, - relevance: int = None, - **kwargs) -> DetailedResponse: + def update_training_example( + self, + environment_id: str, + collection_id: str, + query_id: str, + example_id: str, + *, + cross_reference: Optional[str] = None, + relevance: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Change label or cross reference for example. @@ -2970,9 +3272,11 @@ def update_training_example(self, if not example_id: raise ValueError('example_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_training_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_training_example', + ) headers.update(sdk_headers) params = { @@ -3000,18 +3304,25 @@ def update_training_example(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_training_example(self, environment_id: str, collection_id: str, - query_id: str, example_id: str, - **kwargs) -> DetailedResponse: + def get_training_example( + self, + environment_id: str, + collection_id: str, + query_id: str, + example_id: str, + **kwargs, + ) -> DetailedResponse: """ Get details for training data example. @@ -3035,9 +3346,11 @@ def get_training_example(self, environment_id: str, collection_id: str, if not example_id: raise ValueError('example_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_training_example') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_training_example', + ) headers.update(sdk_headers) params = { @@ -3057,10 +3370,12 @@ def get_training_example(self, environment_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3069,7 +3384,11 @@ def get_training_example(self, environment_id: str, collection_id: str, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -3090,9 +3409,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -3105,10 +3426,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: del kwargs['headers'] url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3117,8 +3440,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: # Events and feedback ######################### - def create_event(self, type: str, data: 'EventData', - **kwargs) -> DetailedResponse: + def create_event( + self, + type: str, + data: 'EventData', + **kwargs, + ) -> DetailedResponse: """ Create event. @@ -3139,9 +3466,11 @@ def create_event(self, type: str, data: 'EventData', raise ValueError('data must be provided') data = convert_model(data) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_event') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_event', + ) headers.update(sdk_headers) params = { @@ -3162,23 +3491,27 @@ def create_event(self, type: str, data: 'EventData', headers['Accept'] = 'application/json' url = '/v1/events' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def query_log(self, - *, - filter: str = None, - query: str = None, - count: int = None, - offset: int = None, - sort: List[str] = None, - **kwargs) -> DetailedResponse: + def query_log( + self, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + count: Optional[int] = None, + offset: Optional[int] = None, + sort: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: """ Search the query and event log. @@ -3208,9 +3541,11 @@ def query_log(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query_log') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='query_log', + ) headers.update(sdk_headers) params = { @@ -3228,20 +3563,24 @@ def query_log(self, headers['Accept'] = 'application/json' url = '/v1/logs' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_metrics_query(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: + def get_metrics_query( + self, + *, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + result_type: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Number of queries over time. @@ -3260,9 +3599,11 @@ def get_metrics_query(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_query', + ) headers.update(sdk_headers) params = { @@ -3278,20 +3619,24 @@ def get_metrics_query(self, headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_metrics_query_event(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: + def get_metrics_query_event( + self, + *, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + result_type: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Number of queries with an event over time. @@ -3311,9 +3656,11 @@ def get_metrics_query_event(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query_event') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_query_event', + ) headers.update(sdk_headers) params = { @@ -3329,20 +3676,24 @@ def get_metrics_query_event(self, headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries_with_event' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_metrics_query_no_results(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: + def get_metrics_query_no_results( + self, + *, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + result_type: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Number of queries with no search results over time. @@ -3364,7 +3715,8 @@ def get_metrics_query_no_results(self, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='get_metrics_query_no_results') + operation_id='get_metrics_query_no_results', + ) headers.update(sdk_headers) params = { @@ -3380,20 +3732,24 @@ def get_metrics_query_no_results(self, headers['Accept'] = 'application/json' url = '/v1/metrics/number_of_queries_with_no_search_results' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_metrics_event_rate(self, - *, - start_time: datetime = None, - end_time: datetime = None, - result_type: str = None, - **kwargs) -> DetailedResponse: + def get_metrics_event_rate( + self, + *, + start_time: Optional[datetime] = None, + end_time: Optional[datetime] = None, + result_type: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Percentage of queries with an associated event. @@ -3413,9 +3769,11 @@ def get_metrics_event_rate(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_event_rate') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_metrics_event_rate', + ) headers.update(sdk_headers) params = { @@ -3431,18 +3789,22 @@ def get_metrics_event_rate(self, headers['Accept'] = 'application/json' url = '/v1/metrics/event_rate' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_metrics_query_token_event(self, - *, - count: int = None, - **kwargs) -> DetailedResponse: + def get_metrics_query_token_event( + self, + *, + count: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Most frequent query tokens with an event. @@ -3462,7 +3824,8 @@ def get_metrics_query_token_event(self, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='get_metrics_query_token_event') + operation_id='get_metrics_query_token_event', + ) headers.update(sdk_headers) params = { @@ -3476,10 +3839,12 @@ def get_metrics_query_token_event(self, headers['Accept'] = 'application/json' url = '/v1/metrics/top_query_tokens_with_event_rate' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3488,8 +3853,11 @@ def get_metrics_query_token_event(self, # Credentials ######################### - def list_credentials(self, environment_id: str, - **kwargs) -> DetailedResponse: + def list_credentials( + self, + environment_id: str, + **kwargs, + ) -> DetailedResponse: """ List credentials. @@ -3506,9 +3874,11 @@ def list_credentials(self, environment_id: str, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_credentials') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_credentials', + ) headers.update(sdk_headers) params = { @@ -3525,21 +3895,25 @@ def list_credentials(self, environment_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/credentials'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_credentials(self, - environment_id: str, - *, - source_type: str = None, - credential_details: 'CredentialDetails' = None, - status: 'StatusDetails' = None, - **kwargs) -> DetailedResponse: + def create_credentials( + self, + environment_id: str, + *, + source_type: Optional[str] = None, + credential_details: Optional['CredentialDetails'] = None, + status: Optional['StatusDetails'] = None, + **kwargs, + ) -> DetailedResponse: """ Create credentials. @@ -3577,9 +3951,11 @@ def create_credentials(self, if status is not None: status = convert_model(status) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_credentials') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_credentials', + ) headers.update(sdk_headers) params = { @@ -3605,17 +3981,23 @@ def create_credentials(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/credentials'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_credentials(self, environment_id: str, credential_id: str, - **kwargs) -> DetailedResponse: + def get_credentials( + self, + environment_id: str, + credential_id: str, + **kwargs, + ) -> DetailedResponse: """ View Credentials. @@ -3636,9 +4018,11 @@ def get_credentials(self, environment_id: str, credential_id: str, if not credential_id: raise ValueError('credential_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_credentials') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_credentials', + ) headers.update(sdk_headers) params = { @@ -3655,22 +4039,26 @@ def get_credentials(self, environment_id: str, credential_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_credentials(self, - environment_id: str, - credential_id: str, - *, - source_type: str = None, - credential_details: 'CredentialDetails' = None, - status: 'StatusDetails' = None, - **kwargs) -> DetailedResponse: + def update_credentials( + self, + environment_id: str, + credential_id: str, + *, + source_type: Optional[str] = None, + credential_details: Optional['CredentialDetails'] = None, + status: Optional['StatusDetails'] = None, + **kwargs, + ) -> DetailedResponse: """ Update credentials. @@ -3711,9 +4099,11 @@ def update_credentials(self, if status is not None: status = convert_model(status) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_credentials') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_credentials', + ) headers.update(sdk_headers) params = { @@ -3739,17 +4129,23 @@ def update_credentials(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_credentials(self, environment_id: str, credential_id: str, - **kwargs) -> DetailedResponse: + def delete_credentials( + self, + environment_id: str, + credential_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete credentials. @@ -3768,9 +4164,11 @@ def delete_credentials(self, environment_id: str, credential_id: str, if not credential_id: raise ValueError('credential_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_credentials') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_credentials', + ) headers.update(sdk_headers) params = { @@ -3787,10 +4185,12 @@ def delete_credentials(self, environment_id: str, credential_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3799,7 +4199,11 @@ def delete_credentials(self, environment_id: str, credential_id: str, # gatewayConfiguration ######################### - def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: + def list_gateways( + self, + environment_id: str, + **kwargs, + ) -> DetailedResponse: """ List Gateways. @@ -3814,9 +4218,11 @@ def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_gateways') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_gateways', + ) headers.update(sdk_headers) params = { @@ -3833,19 +4239,23 @@ def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/gateways'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_gateway(self, - environment_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def create_gateway( + self, + environment_id: str, + *, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create Gateway. @@ -3861,9 +4271,11 @@ def create_gateway(self, if not environment_id: raise ValueError('environment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_gateway') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_gateway', + ) headers.update(sdk_headers) params = { @@ -3887,17 +4299,23 @@ def create_gateway(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/gateways'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_gateway(self, environment_id: str, gateway_id: str, - **kwargs) -> DetailedResponse: + def get_gateway( + self, + environment_id: str, + gateway_id: str, + **kwargs, + ) -> DetailedResponse: """ List Gateway Details. @@ -3915,9 +4333,11 @@ def get_gateway(self, environment_id: str, gateway_id: str, if not gateway_id: raise ValueError('gateway_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_gateway') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_gateway', + ) headers.update(sdk_headers) params = { @@ -3934,16 +4354,22 @@ def get_gateway(self, environment_id: str, gateway_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_gateway(self, environment_id: str, gateway_id: str, - **kwargs) -> DetailedResponse: + def delete_gateway( + self, + environment_id: str, + gateway_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete Gateway. @@ -3961,9 +4387,11 @@ def delete_gateway(self, environment_id: str, gateway_id: str, if not gateway_id: raise ValueError('gateway_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_gateway') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_gateway', + ) headers.update(sdk_headers) params = { @@ -3980,10 +4408,12 @@ def delete_gateway(self, environment_id: str, gateway_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3998,6 +4428,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_JSON = 'application/json' APPLICATION_MSWORD = 'application/msword' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' @@ -4015,6 +4446,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_JSON = 'application/json' APPLICATION_MSWORD = 'application/msword' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' @@ -4032,6 +4464,7 @@ class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ + DOCUMENT = 'document' @@ -4044,6 +4477,7 @@ class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ + DOCUMENT = 'document' @@ -4056,6 +4490,7 @@ class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ + DOCUMENT = 'document' @@ -4068,6 +4503,7 @@ class ResultType(str, Enum): """ The type of result to consider when calculating the metric. """ + DOCUMENT = 'document' @@ -4076,49 +4512,51 @@ class ResultType(str, Enum): ############################################################################## -class Collection(): +class Collection: """ A collection for storing documents. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: (optional) The name of the collection. - :attr str description: (optional) The description of the collection. - :attr datetime created: (optional) The creation date of the collection in the + :param str collection_id: (optional) The unique identifier of the collection. + :param str name: (optional) The name of the collection. + :param str description: (optional) The description of the collection. + :param datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. - :attr datetime updated: (optional) The timestamp of when the collection was last - updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str status: (optional) The status of the collection. - :attr str configuration_id: (optional) The unique identifier of the collection's - configuration. - :attr str language: (optional) The language of the documents stored in the + :param datetime updated: (optional) The timestamp of when the collection was + last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :param str status: (optional) The status of the collection. + :param str configuration_id: (optional) The unique identifier of the + collection's configuration. + :param str language: (optional) The language of the documents stored in the collection. Permitted values include `en` (English), `de` (German), and `es` (Spanish). - :attr DocumentCounts document_counts: (optional) Object containing collection + :param DocumentCounts document_counts: (optional) Object containing collection document count information. - :attr CollectionDiskUsage disk_usage: (optional) Summary of the disk usage + :param CollectionDiskUsage disk_usage: (optional) Summary of the disk usage statistics for this collection. - :attr TrainingStatus training_status: (optional) Training status details. - :attr CollectionCrawlStatus crawl_status: (optional) Object containing + :param TrainingStatus training_status: (optional) Training status details. + :param CollectionCrawlStatus crawl_status: (optional) Object containing information about the crawl status of this collection. - :attr SduStatus smart_document_understanding: (optional) Object containing smart - document understanding information for this collection. - """ - - def __init__(self, - *, - collection_id: str = None, - name: str = None, - description: str = None, - created: datetime = None, - updated: datetime = None, - status: str = None, - configuration_id: str = None, - language: str = None, - document_counts: 'DocumentCounts' = None, - disk_usage: 'CollectionDiskUsage' = None, - training_status: 'TrainingStatus' = None, - crawl_status: 'CollectionCrawlStatus' = None, - smart_document_understanding: 'SduStatus' = None) -> None: + :param SduStatus smart_document_understanding: (optional) Object containing + smart document understanding information for this collection. + """ + + def __init__( + self, + *, + collection_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + status: Optional[str] = None, + configuration_id: Optional[str] = None, + language: Optional[str] = None, + document_counts: Optional['DocumentCounts'] = None, + disk_usage: Optional['CollectionDiskUsage'] = None, + training_status: Optional['TrainingStatus'] = None, + crawl_status: Optional['CollectionCrawlStatus'] = None, + smart_document_understanding: Optional['SduStatus'] = None, + ) -> None: """ Initialize a Collection object. @@ -4157,37 +4595,34 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'document_counts' in _dict: - args['document_counts'] = DocumentCounts.from_dict( - _dict.get('document_counts')) - if 'disk_usage' in _dict: - args['disk_usage'] = CollectionDiskUsage.from_dict( - _dict.get('disk_usage')) - if 'training_status' in _dict: - args['training_status'] = TrainingStatus.from_dict( - _dict.get('training_status')) - if 'crawl_status' in _dict: - args['crawl_status'] = CollectionCrawlStatus.from_dict( - _dict.get('crawl_status')) - if 'smart_document_understanding' in _dict: + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (configuration_id := _dict.get('configuration_id')) is not None: + args['configuration_id'] = configuration_id + if (language := _dict.get('language')) is not None: + args['language'] = language + if (document_counts := _dict.get('document_counts')) is not None: + args['document_counts'] = DocumentCounts.from_dict(document_counts) + if (disk_usage := _dict.get('disk_usage')) is not None: + args['disk_usage'] = CollectionDiskUsage.from_dict(disk_usage) + if (training_status := _dict.get('training_status')) is not None: + args['training_status'] = TrainingStatus.from_dict(training_status) + if (crawl_status := _dict.get('crawl_status')) is not None: + args['crawl_status'] = CollectionCrawlStatus.from_dict(crawl_status) + if (smart_document_understanding := + _dict.get('smart_document_understanding')) is not None: args['smart_document_understanding'] = SduStatus.from_dict( - _dict.get('smart_document_understanding')) + smart_document_understanding) return cls(**args) @classmethod @@ -4271,20 +4706,25 @@ class StatusEnum(str, Enum): """ The status of the collection. """ + ACTIVE = 'active' PENDING = 'pending' MAINTENANCE = 'maintenance' -class CollectionCrawlStatus(): +class CollectionCrawlStatus: """ Object containing information about the crawl status of this collection. - :attr SourceStatus source_crawl: (optional) Object containing source crawl + :param SourceStatus source_crawl: (optional) Object containing source crawl status information. """ - def __init__(self, *, source_crawl: 'SourceStatus' = None) -> None: + def __init__( + self, + *, + source_crawl: Optional['SourceStatus'] = None, + ) -> None: """ Initialize a CollectionCrawlStatus object. @@ -4297,9 +4737,8 @@ def __init__(self, *, source_crawl: 'SourceStatus' = None) -> None: def from_dict(cls, _dict: Dict) -> 'CollectionCrawlStatus': """Initialize a CollectionCrawlStatus object from a json dictionary.""" args = {} - if 'source_crawl' in _dict: - args['source_crawl'] = SourceStatus.from_dict( - _dict.get('source_crawl')) + if (source_crawl := _dict.get('source_crawl')) is not None: + args['source_crawl'] = SourceStatus.from_dict(source_crawl) return cls(**args) @classmethod @@ -4336,14 +4775,18 @@ def __ne__(self, other: 'CollectionCrawlStatus') -> bool: return not self == other -class CollectionDiskUsage(): +class CollectionDiskUsage: """ Summary of the disk usage statistics for this collection. - :attr int used_bytes: (optional) Number of bytes used by the collection. + :param int used_bytes: (optional) Number of bytes used by the collection. """ - def __init__(self, *, used_bytes: int = None) -> None: + def __init__( + self, + *, + used_bytes: Optional[int] = None, + ) -> None: """ Initialize a CollectionDiskUsage object. @@ -4354,8 +4797,8 @@ def __init__(self, *, used_bytes: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'CollectionDiskUsage': """Initialize a CollectionDiskUsage object from a json dictionary.""" args = {} - if 'used_bytes' in _dict: - args['used_bytes'] = _dict.get('used_bytes') + if (used_bytes := _dict.get('used_bytes')) is not None: + args['used_bytes'] = used_bytes return cls(**args) @classmethod @@ -4390,19 +4833,22 @@ def __ne__(self, other: 'CollectionDiskUsage') -> bool: return not self == other -class CollectionUsage(): +class CollectionUsage: """ Summary of the collection usage in the environment. - :attr int available: (optional) Number of active collections in the environment. - :attr int maximum_allowed: (optional) Total number of collections allowed in the + :param int available: (optional) Number of active collections in the environment. + :param int maximum_allowed: (optional) Total number of collections allowed in + the environment. """ - def __init__(self, - *, - available: int = None, - maximum_allowed: int = None) -> None: + def __init__( + self, + *, + available: Optional[int] = None, + maximum_allowed: Optional[int] = None, + ) -> None: """ Initialize a CollectionUsage object. @@ -4414,10 +4860,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CollectionUsage': """Initialize a CollectionUsage object from a json dictionary.""" args = {} - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'maximum_allowed' in _dict: - args['maximum_allowed'] = _dict.get('maximum_allowed') + if (available := _dict.get('available')) is not None: + args['available'] = available + if (maximum_allowed := _dict.get('maximum_allowed')) is not None: + args['maximum_allowed'] = maximum_allowed return cls(**args) @classmethod @@ -4455,15 +4901,19 @@ def __ne__(self, other: 'CollectionUsage') -> bool: return not self == other -class Completions(): +class Completions: """ An object containing an array of autocompletion suggestions. - :attr List[str] completions: (optional) Array of autcomplete suggestion based on - the provided prefix. + :param List[str] completions: (optional) Array of autcomplete suggestion based + on the provided prefix. """ - def __init__(self, *, completions: List[str] = None) -> None: + def __init__( + self, + *, + completions: Optional[List[str]] = None, + ) -> None: """ Initialize a Completions object. @@ -4476,8 +4926,8 @@ def __init__(self, *, completions: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'Completions': """Initialize a Completions object from a json dictionary.""" args = {} - if 'completions' in _dict: - args['completions'] = _dict.get('completions') + if (completions := _dict.get('completions')) is not None: + args['completions'] = completions return cls(**args) @classmethod @@ -4511,40 +4961,42 @@ def __ne__(self, other: 'Completions') -> bool: return not self == other -class Configuration(): +class Configuration: """ A custom configuration for the environment. - :attr str configuration_id: (optional) The unique identifier of the + :param str configuration_id: (optional) The unique identifier of the configuration. - :attr str name: The name of the configuration. - :attr datetime created: (optional) The creation date of the configuration in the - format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr datetime updated: (optional) The timestamp of when the configuration was + :param str name: The name of the configuration. + :param datetime created: (optional) The creation date of the configuration in + the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. + :param datetime updated: (optional) The timestamp of when the configuration was last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str description: (optional) The description of the configuration, if + :param str description: (optional) The description of the configuration, if available. - :attr Conversions conversions: (optional) Document conversion settings. - :attr List[Enrichment] enrichments: (optional) An array of document enrichment + :param Conversions conversions: (optional) Document conversion settings. + :param List[Enrichment] enrichments: (optional) An array of document enrichment settings for the configuration. - :attr List[NormalizationOperation] normalizations: (optional) Defines operations - that can be used to transform the final output JSON into a normalized form. - Operations are executed in the order that they appear in the array. - :attr Source source: (optional) Object containing source parameters for the + :param List[NormalizationOperation] normalizations: (optional) Defines + operations that can be used to transform the final output JSON into a normalized + form. Operations are executed in the order that they appear in the array. + :param Source source: (optional) Object containing source parameters for the configuration. """ - def __init__(self, - name: str, - *, - configuration_id: str = None, - created: datetime = None, - updated: datetime = None, - description: str = None, - conversions: 'Conversions' = None, - enrichments: List['Enrichment'] = None, - normalizations: List['NormalizationOperation'] = None, - source: 'Source' = None) -> None: + def __init__( + self, + name: str, + *, + configuration_id: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + description: Optional[str] = None, + conversions: Optional['Conversions'] = None, + enrichments: Optional[List['Enrichment']] = None, + normalizations: Optional[List['NormalizationOperation']] = None, + source: Optional['Source'] = None, + ) -> None: """ Initialize a Configuration object. @@ -4575,33 +5027,29 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Configuration': """Initialize a Configuration object from a json dictionary.""" args = {} - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (configuration_id := _dict.get('configuration_id')) is not None: + args['configuration_id'] = configuration_id + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Configuration JSON') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'conversions' in _dict: - args['conversions'] = Conversions.from_dict( - _dict.get('conversions')) - if 'enrichments' in _dict: - args['enrichments'] = [ - Enrichment.from_dict(v) for v in _dict.get('enrichments') - ] - if 'normalizations' in _dict: + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (description := _dict.get('description')) is not None: + args['description'] = description + if (conversions := _dict.get('conversions')) is not None: + args['conversions'] = Conversions.from_dict(conversions) + if (enrichments := _dict.get('enrichments')) is not None: + args['enrichments'] = [Enrichment.from_dict(v) for v in enrichments] + if (normalizations := _dict.get('normalizations')) is not None: args['normalizations'] = [ - NormalizationOperation.from_dict(v) - for v in _dict.get('normalizations') + NormalizationOperation.from_dict(v) for v in normalizations ] - if 'source' in _dict: - args['source'] = Source.from_dict(_dict.get('source')) + if (source := _dict.get('source')) is not None: + args['source'] = Source.from_dict(source) return cls(**args) @classmethod @@ -4670,19 +5118,19 @@ def __ne__(self, other: 'Configuration') -> bool: return not self == other -class Conversions(): +class Conversions: """ Document conversion settings. - :attr PdfSettings pdf: (optional) A list of PDF conversion settings. - :attr WordSettings word: (optional) A list of Word conversion settings. - :attr HtmlSettings html: (optional) A list of HTML conversion settings. - :attr SegmentSettings segment: (optional) A list of Document Segmentation + :param PdfSettings pdf: (optional) A list of PDF conversion settings. + :param WordSettings word: (optional) A list of Word conversion settings. + :param HtmlSettings html: (optional) A list of HTML conversion settings. + :param SegmentSettings segment: (optional) A list of Document Segmentation settings. - :attr List[NormalizationOperation] json_normalizations: (optional) Defines + :param List[NormalizationOperation] json_normalizations: (optional) Defines operations that can be used to transform the final output JSON into a normalized form. Operations are executed in the order that they appear in the array. - :attr bool image_text_recognition: (optional) When `true`, automatic text + :param bool image_text_recognition: (optional) When `true`, automatic text extraction from images (this includes images embedded in supported document formats, for example PDF, and suppported image formats, for example TIFF) is performed on documents uploaded to the collection. This field is supported on @@ -4690,14 +5138,16 @@ class Conversions(): recognition. """ - def __init__(self, - *, - pdf: 'PdfSettings' = None, - word: 'WordSettings' = None, - html: 'HtmlSettings' = None, - segment: 'SegmentSettings' = None, - json_normalizations: List['NormalizationOperation'] = None, - image_text_recognition: bool = None) -> None: + def __init__( + self, + *, + pdf: Optional['PdfSettings'] = None, + word: Optional['WordSettings'] = None, + html: Optional['HtmlSettings'] = None, + segment: Optional['SegmentSettings'] = None, + json_normalizations: Optional[List['NormalizationOperation']] = None, + image_text_recognition: Optional[bool] = None, + ) -> None: """ Initialize a Conversions object. @@ -4728,21 +5178,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Conversions': """Initialize a Conversions object from a json dictionary.""" args = {} - if 'pdf' in _dict: - args['pdf'] = PdfSettings.from_dict(_dict.get('pdf')) - if 'word' in _dict: - args['word'] = WordSettings.from_dict(_dict.get('word')) - if 'html' in _dict: - args['html'] = HtmlSettings.from_dict(_dict.get('html')) - if 'segment' in _dict: - args['segment'] = SegmentSettings.from_dict(_dict.get('segment')) - if 'json_normalizations' in _dict: + if (pdf := _dict.get('pdf')) is not None: + args['pdf'] = PdfSettings.from_dict(pdf) + if (word := _dict.get('word')) is not None: + args['word'] = WordSettings.from_dict(word) + if (html := _dict.get('html')) is not None: + args['html'] = HtmlSettings.from_dict(html) + if (segment := _dict.get('segment')) is not None: + args['segment'] = SegmentSettings.from_dict(segment) + if (json_normalizations := + _dict.get('json_normalizations')) is not None: args['json_normalizations'] = [ - NormalizationOperation.from_dict(v) - for v in _dict.get('json_normalizations') + NormalizationOperation.from_dict(v) for v in json_normalizations ] - if 'image_text_recognition' in _dict: - args['image_text_recognition'] = _dict.get('image_text_recognition') + if (image_text_recognition := + _dict.get('image_text_recognition')) is not None: + args['image_text_recognition'] = image_text_recognition return cls(**args) @classmethod @@ -4807,15 +5258,20 @@ def __ne__(self, other: 'Conversions') -> bool: return not self == other -class CreateEventResponse(): +class CreateEventResponse: """ An object defining the event being created. - :attr str type: (optional) The event type that was created. - :attr EventData data: (optional) Query event data object. + :param str type: (optional) The event type that was created. + :param EventData data: (optional) Query event data object. """ - def __init__(self, *, type: str = None, data: 'EventData' = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + data: Optional['EventData'] = None, + ) -> None: """ Initialize a CreateEventResponse object. @@ -4829,10 +5285,10 @@ def __init__(self, *, type: str = None, data: 'EventData' = None) -> None: def from_dict(cls, _dict: Dict) -> 'CreateEventResponse': """Initialize a CreateEventResponse object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'data' in _dict: - args['data'] = EventData.from_dict(_dict.get('data')) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (data := _dict.get('data')) is not None: + args['data'] = EventData.from_dict(data) return cls(**args) @classmethod @@ -4874,15 +5330,16 @@ class TypeEnum(str, Enum): """ The event type that was created. """ + CLICK = 'click' -class CredentialDetails(): +class CredentialDetails: """ Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. - :attr str credential_type: (optional) The authentication method for this + :param str credential_type: (optional) The authentication method for this credentials definition. The **credential_type** specified must be supported by the **source_type**. The following combinations are possible: - `"source_type": "box"` - valid `credential_type`s: `oauth2` @@ -4892,95 +5349,98 @@ class CredentialDetails(): - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. - :attr str client_id: (optional) The **client_id** of the source that these + :param str client_id: (optional) The **client_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. - :attr str enterprise_id: (optional) The **enterprise_id** of the Box site that + :param str enterprise_id: (optional) The **enterprise_id** of the Box site that these credentials connect to. Only valid, and required, with a **source_type** of `box`. - :attr str url: (optional) The **url** of the source that these credentials + :param str url: (optional) The **url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `username_password`, `noauth`, and `basic`. - :attr str username: (optional) The **username** of the source that these + :param str username: (optional) The **username** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`, `username_password`, `basic`, or `ntlm_v1`. - :attr str organization_url: (optional) The **organization_url** of the source + :param str organization_url: (optional) The **organization_url** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `saml`. - :attr str site_collection_path: (optional) The **site_collection.path** of the + :param str site_collection_path: (optional) The **site_collection.path** of the source that these credentials connect to. Only valid, and required, with a **source_type** of `sharepoint`. - :attr str client_secret: (optional) The **client_secret** of the source that + :param str client_secret: (optional) The **client_secret** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - :attr str public_key_id: (optional) The **public_key_id** of the source that + :param str public_key_id: (optional) The **public_key_id** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - :attr str private_key: (optional) The **private_key** of the source that these + :param str private_key: (optional) The **private_key** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - :attr str passphrase: (optional) The **passphrase** of the source that these + :param str passphrase: (optional) The **passphrase** of the source that these credentials connect to. Only valid, and required, with a **credential_type** of `oauth2`. This value is never returned and is only used when creating or modifying **credentials**. - :attr str password: (optional) The **password** of the source that these + :param str password: (optional) The **password** of the source that these credentials connect to. Only valid, and required, with **credential_type**s of `saml`, `username_password`, `basic`, or `ntlm_v1`. **Note:** When used with a **source_type** of `salesforce`, the password consists of the Salesforce password and a valid Salesforce security token concatenated. This value is never returned and is only used when creating or modifying **credentials**. - :attr str gateway_id: (optional) The ID of the **gateway** to be connected + :param str gateway_id: (optional) The ID of the **gateway** to be connected through (when connecting to intranet sites). Only valid with a **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are created using the `/v1/environments/{environment_id}/gateways` methods. - :attr str source_version: (optional) The type of Sharepoint repository to + :param str source_version: (optional) The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of `sharepoint`. - :attr str web_application_url: (optional) SharePoint OnPrem WebApplication URL. + :param str web_application_url: (optional) SharePoint OnPrem WebApplication URL. Only valid, and required, with a **source_version** of `2016`. If a port is not supplied, the default to port `80` for http and port `443` for https connections are used. - :attr str domain: (optional) The domain used to log in to your OnPrem SharePoint - account. Only valid, and required, with a **source_version** of `2016`. - :attr str endpoint: (optional) The endpoint associated with the cloud object + :param str domain: (optional) The domain used to log in to your OnPrem + SharePoint account. Only valid, and required, with a **source_version** of + `2016`. + :param str endpoint: (optional) The endpoint associated with the cloud object store that your are connecting to. Only valid, and required, with a **credential_type** of `aws4_hmac`. - :attr str access_key_id: (optional) The access key ID associated with the cloud + :param str access_key_id: (optional) The access key ID associated with the cloud object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - :attr str secret_access_key: (optional) The secret access key associated with + :param str secret_access_key: (optional) The secret access key associated with the cloud object store. Only valid, and required, with a **credential_type** of `aws4_hmac`. This value is never returned and is only used when creating or modifying **credentials**. For more infomation, see the [cloud object store documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). """ - def __init__(self, - *, - credential_type: str = None, - client_id: str = None, - enterprise_id: str = None, - url: str = None, - username: str = None, - organization_url: str = None, - site_collection_path: str = None, - client_secret: str = None, - public_key_id: str = None, - private_key: str = None, - passphrase: str = None, - password: str = None, - gateway_id: str = None, - source_version: str = None, - web_application_url: str = None, - domain: str = None, - endpoint: str = None, - access_key_id: str = None, - secret_access_key: str = None) -> None: + def __init__( + self, + *, + credential_type: Optional[str] = None, + client_id: Optional[str] = None, + enterprise_id: Optional[str] = None, + url: Optional[str] = None, + username: Optional[str] = None, + organization_url: Optional[str] = None, + site_collection_path: Optional[str] = None, + client_secret: Optional[str] = None, + public_key_id: Optional[str] = None, + private_key: Optional[str] = None, + passphrase: Optional[str] = None, + password: Optional[str] = None, + gateway_id: Optional[str] = None, + source_version: Optional[str] = None, + web_application_url: Optional[str] = None, + domain: Optional[str] = None, + endpoint: Optional[str] = None, + access_key_id: Optional[str] = None, + secret_access_key: Optional[str] = None, + ) -> None: """ Initialize a CredentialDetails object. @@ -5091,44 +5551,46 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CredentialDetails': """Initialize a CredentialDetails object from a json dictionary.""" args = {} - if 'credential_type' in _dict: - args['credential_type'] = _dict.get('credential_type') - if 'client_id' in _dict: - args['client_id'] = _dict.get('client_id') - if 'enterprise_id' in _dict: - args['enterprise_id'] = _dict.get('enterprise_id') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'username' in _dict: - args['username'] = _dict.get('username') - if 'organization_url' in _dict: - args['organization_url'] = _dict.get('organization_url') - if 'site_collection.path' in _dict: - args['site_collection_path'] = _dict.get('site_collection.path') - if 'client_secret' in _dict: - args['client_secret'] = _dict.get('client_secret') - if 'public_key_id' in _dict: - args['public_key_id'] = _dict.get('public_key_id') - if 'private_key' in _dict: - args['private_key'] = _dict.get('private_key') - if 'passphrase' in _dict: - args['passphrase'] = _dict.get('passphrase') - if 'password' in _dict: - args['password'] = _dict.get('password') - if 'gateway_id' in _dict: - args['gateway_id'] = _dict.get('gateway_id') - if 'source_version' in _dict: - args['source_version'] = _dict.get('source_version') - if 'web_application_url' in _dict: - args['web_application_url'] = _dict.get('web_application_url') - if 'domain' in _dict: - args['domain'] = _dict.get('domain') - if 'endpoint' in _dict: - args['endpoint'] = _dict.get('endpoint') - if 'access_key_id' in _dict: - args['access_key_id'] = _dict.get('access_key_id') - if 'secret_access_key' in _dict: - args['secret_access_key'] = _dict.get('secret_access_key') + if (credential_type := _dict.get('credential_type')) is not None: + args['credential_type'] = credential_type + if (client_id := _dict.get('client_id')) is not None: + args['client_id'] = client_id + if (enterprise_id := _dict.get('enterprise_id')) is not None: + args['enterprise_id'] = enterprise_id + if (url := _dict.get('url')) is not None: + args['url'] = url + if (username := _dict.get('username')) is not None: + args['username'] = username + if (organization_url := _dict.get('organization_url')) is not None: + args['organization_url'] = organization_url + if (site_collection_path := + _dict.get('site_collection.path')) is not None: + args['site_collection_path'] = site_collection_path + if (client_secret := _dict.get('client_secret')) is not None: + args['client_secret'] = client_secret + if (public_key_id := _dict.get('public_key_id')) is not None: + args['public_key_id'] = public_key_id + if (private_key := _dict.get('private_key')) is not None: + args['private_key'] = private_key + if (passphrase := _dict.get('passphrase')) is not None: + args['passphrase'] = passphrase + if (password := _dict.get('password')) is not None: + args['password'] = password + if (gateway_id := _dict.get('gateway_id')) is not None: + args['gateway_id'] = gateway_id + if (source_version := _dict.get('source_version')) is not None: + args['source_version'] = source_version + if (web_application_url := + _dict.get('web_application_url')) is not None: + args['web_application_url'] = web_application_url + if (domain := _dict.get('domain')) is not None: + args['domain'] = domain + if (endpoint := _dict.get('endpoint')) is not None: + args['endpoint'] = endpoint + if (access_key_id := _dict.get('access_key_id')) is not None: + args['access_key_id'] = access_key_id + if (secret_access_key := _dict.get('secret_access_key')) is not None: + args['secret_access_key'] = secret_access_key return cls(**args) @classmethod @@ -5215,6 +5677,7 @@ class CredentialTypeEnum(str, Enum): - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. """ + OAUTH2 = 'oauth2' SAML = 'saml' USERNAME_PASSWORD = 'username_password' @@ -5228,16 +5691,17 @@ class SourceVersionEnum(str, Enum): The type of Sharepoint repository to connect to. Only valid, and required, with a **source_type** of `sharepoint`. """ + ONLINE = 'online' -class Credentials(): +class Credentials: """ Object containing credential information. - :attr str credential_id: (optional) Unique identifier for this set of + :param str credential_id: (optional) Unique identifier for this set of credentials. - :attr str source_type: (optional) The source that this credentials object + :param str source_type: (optional) The source that this credentials object connects to. - `box` indicates the credentials are used to connect an instance of Enterprise Box. @@ -5247,19 +5711,21 @@ class Credentials(): - `web_crawl` indicates the credentials are used to perform a web crawl. = `cloud_object_storage` indicates the credentials are used to connect to an IBM Cloud Object Store. - :attr CredentialDetails credential_details: (optional) Object containing details - of the stored credentials. + :param CredentialDetails credential_details: (optional) Object containing + details of the stored credentials. Obtain credentials for your source from the administrator of the source. - :attr StatusDetails status: (optional) Object that contains details about the + :param StatusDetails status: (optional) Object that contains details about the status of the authentication process. """ - def __init__(self, - *, - credential_id: str = None, - source_type: str = None, - credential_details: 'CredentialDetails' = None, - status: 'StatusDetails' = None) -> None: + def __init__( + self, + *, + credential_id: Optional[str] = None, + source_type: Optional[str] = None, + credential_details: Optional['CredentialDetails'] = None, + status: Optional['StatusDetails'] = None, + ) -> None: """ Initialize a Credentials object. @@ -5289,15 +5755,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Credentials': """Initialize a Credentials object from a json dictionary.""" args = {} - if 'credential_id' in _dict: - args['credential_id'] = _dict.get('credential_id') - if 'source_type' in _dict: - args['source_type'] = _dict.get('source_type') - if 'credential_details' in _dict: + if (credential_id := _dict.get('credential_id')) is not None: + args['credential_id'] = credential_id + if (source_type := _dict.get('source_type')) is not None: + args['source_type'] = source_type + if (credential_details := _dict.get('credential_details')) is not None: args['credential_details'] = CredentialDetails.from_dict( - _dict.get('credential_details')) - if 'status' in _dict: - args['status'] = StatusDetails.from_dict(_dict.get('status')) + credential_details) + if (status := _dict.get('status')) is not None: + args['status'] = StatusDetails.from_dict(status) return cls(**args) @classmethod @@ -5357,6 +5823,7 @@ class SourceTypeEnum(str, Enum): = `cloud_object_storage` indicates the credentials are used to connect to an IBM Cloud Object Store. """ + BOX = 'box' SALESFORCE = 'salesforce' SHAREPOINT = 'sharepoint' @@ -5364,15 +5831,19 @@ class SourceTypeEnum(str, Enum): CLOUD_OBJECT_STORAGE = 'cloud_object_storage' -class CredentialsList(): +class CredentialsList: """ Object containing array of credential definitions. - :attr List[Credentials] credentials: (optional) An array of credential + :param List[Credentials] credentials: (optional) An array of credential definitions that were created for this instance. """ - def __init__(self, *, credentials: List['Credentials'] = None) -> None: + def __init__( + self, + *, + credentials: Optional[List['Credentials']] = None, + ) -> None: """ Initialize a CredentialsList object. @@ -5385,9 +5856,9 @@ def __init__(self, *, credentials: List['Credentials'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CredentialsList': """Initialize a CredentialsList object from a json dictionary.""" args = {} - if 'credentials' in _dict: + if (credentials := _dict.get('credentials')) is not None: args['credentials'] = [ - Credentials.from_dict(v) for v in _dict.get('credentials') + Credentials.from_dict(v) for v in credentials ] return cls(**args) @@ -5428,17 +5899,21 @@ def __ne__(self, other: 'CredentialsList') -> bool: return not self == other -class DeleteCollectionResponse(): +class DeleteCollectionResponse: """ Response object returned when deleting a colleciton. - :attr str collection_id: The unique identifier of the collection that is being + :param str collection_id: The unique identifier of the collection that is being deleted. - :attr str status: The status of the collection. The status of a successful + :param str status: The status of the collection. The status of a successful deletion operation is `deleted`. """ - def __init__(self, collection_id: str, status: str) -> None: + def __init__( + self, + collection_id: str, + status: str, + ) -> None: """ Initialize a DeleteCollectionResponse object. @@ -5454,14 +5929,14 @@ def __init__(self, collection_id: str, status: str) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteCollectionResponse': """Initialize a DeleteCollectionResponse object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id else: raise ValueError( 'Required property \'collection_id\' not present in DeleteCollectionResponse JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in DeleteCollectionResponse JSON' @@ -5505,24 +5980,27 @@ class StatusEnum(str, Enum): The status of the collection. The status of a successful deletion operation is `deleted`. """ + DELETED = 'deleted' -class DeleteConfigurationResponse(): +class DeleteConfigurationResponse: """ Information returned when a configuration is deleted. - :attr str configuration_id: The unique identifier for the configuration. - :attr str status: Status of the configuration. A deleted configuration has the + :param str configuration_id: The unique identifier for the configuration. + :param str status: Status of the configuration. A deleted configuration has the status deleted. - :attr List[Notice] notices: (optional) An array of notice messages, if any. + :param List[Notice] notices: (optional) An array of notice messages, if any. """ - def __init__(self, - configuration_id: str, - status: str, - *, - notices: List['Notice'] = None) -> None: + def __init__( + self, + configuration_id: str, + status: str, + *, + notices: Optional[List['Notice']] = None, + ) -> None: """ Initialize a DeleteConfigurationResponse object. @@ -5540,22 +6018,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DeleteConfigurationResponse': """Initialize a DeleteConfigurationResponse object from a json dictionary.""" args = {} - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') + if (configuration_id := _dict.get('configuration_id')) is not None: + args['configuration_id'] = configuration_id else: raise ValueError( 'Required property \'configuration_id\' not present in DeleteConfigurationResponse JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in DeleteConfigurationResponse JSON' ) - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] return cls(**args) @classmethod @@ -5603,22 +6079,25 @@ class StatusEnum(str, Enum): """ Status of the configuration. A deleted configuration has the status deleted. """ + DELETED = 'deleted' -class DeleteCredentials(): +class DeleteCredentials: """ Object returned after credentials are deleted. - :attr str credential_id: (optional) The unique identifier of the credentials + :param str credential_id: (optional) The unique identifier of the credentials that have been deleted. - :attr str status: (optional) The status of the deletion request. + :param str status: (optional) The status of the deletion request. """ - def __init__(self, - *, - credential_id: str = None, - status: str = None) -> None: + def __init__( + self, + *, + credential_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a DeleteCredentials object. @@ -5633,10 +6112,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DeleteCredentials': """Initialize a DeleteCredentials object from a json dictionary.""" args = {} - if 'credential_id' in _dict: - args['credential_id'] = _dict.get('credential_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (credential_id := _dict.get('credential_id')) is not None: + args['credential_id'] = credential_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -5675,19 +6154,25 @@ class StatusEnum(str, Enum): """ The status of the deletion request. """ + DELETED = 'deleted' -class DeleteDocumentResponse(): +class DeleteDocumentResponse: """ Information returned when a document is deleted. - :attr str document_id: (optional) The unique identifier of the document. - :attr str status: (optional) Status of the document. A deleted document has the + :param str document_id: (optional) The unique identifier of the document. + :param str status: (optional) Status of the document. A deleted document has the status deleted. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a DeleteDocumentResponse object. @@ -5702,10 +6187,10 @@ def __init__(self, *, document_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -5744,18 +6229,23 @@ class StatusEnum(str, Enum): """ Status of the document. A deleted document has the status deleted. """ + DELETED = 'deleted' -class DeleteEnvironmentResponse(): +class DeleteEnvironmentResponse: """ Response object returned when deleting an environment. - :attr str environment_id: The unique identifier for the environment. - :attr str status: Status of the environment. + :param str environment_id: The unique identifier for the environment. + :param str status: Status of the environment. """ - def __init__(self, environment_id: str, status: str) -> None: + def __init__( + self, + environment_id: str, + status: str, + ) -> None: """ Initialize a DeleteEnvironmentResponse object. @@ -5769,14 +6259,14 @@ def __init__(self, environment_id: str, status: str) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteEnvironmentResponse': """Initialize a DeleteEnvironmentResponse object from a json dictionary.""" args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id else: raise ValueError( 'Required property \'environment_id\' not present in DeleteEnvironmentResponse JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in DeleteEnvironmentResponse JSON' @@ -5819,23 +6309,26 @@ class StatusEnum(str, Enum): """ Status of the environment. """ + DELETED = 'deleted' -class DiskUsage(): +class DiskUsage: """ Summary of the disk usage statistics for the environment. - :attr int used_bytes: (optional) Number of bytes within the environment's disk + :param int used_bytes: (optional) Number of bytes within the environment's disk capacity that are currently used to store data. - :attr int maximum_allowed_bytes: (optional) Total number of bytes available in + :param int maximum_allowed_bytes: (optional) Total number of bytes available in the environment's disk capacity. """ - def __init__(self, - *, - used_bytes: int = None, - maximum_allowed_bytes: int = None) -> None: + def __init__( + self, + *, + used_bytes: Optional[int] = None, + maximum_allowed_bytes: Optional[int] = None, + ) -> None: """ Initialize a DiskUsage object. @@ -5847,10 +6340,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DiskUsage': """Initialize a DiskUsage object from a json dictionary.""" args = {} - if 'used_bytes' in _dict: - args['used_bytes'] = _dict.get('used_bytes') - if 'maximum_allowed_bytes' in _dict: - args['maximum_allowed_bytes'] = _dict.get('maximum_allowed_bytes') + if (used_bytes := _dict.get('used_bytes')) is not None: + args['used_bytes'] = used_bytes + if (maximum_allowed_bytes := + _dict.get('maximum_allowed_bytes')) is not None: + args['maximum_allowed_bytes'] = maximum_allowed_bytes return cls(**args) @classmethod @@ -5889,25 +6383,27 @@ def __ne__(self, other: 'DiskUsage') -> bool: return not self == other -class DocumentAccepted(): +class DocumentAccepted: """ Information returned after an uploaded document is accepted. - :attr str document_id: (optional) The unique identifier of the ingested + :param str document_id: (optional) The unique identifier of the ingested document. - :attr str status: (optional) Status of the document in the ingestion process. A + :param str status: (optional) Status of the document in the ingestion process. A status of `processing` is returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. - :attr List[Notice] notices: (optional) Array of notices produced by the + :param List[Notice] notices: (optional) Array of notices produced by the document-ingestion process. """ - def __init__(self, - *, - document_id: str = None, - status: str = None, - notices: List['Notice'] = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + status: Optional[str] = None, + notices: Optional[List['Notice']] = None, + ) -> None: """ Initialize a DocumentAccepted object. @@ -5928,14 +6424,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': """Initialize a DocumentAccepted object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] return cls(**args) @classmethod @@ -5984,30 +6478,33 @@ class StatusEnum(str, Enum): returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. """ + PROCESSING = 'processing' PENDING = 'pending' -class DocumentCounts(): +class DocumentCounts: """ Object containing collection document count information. - :attr int available: (optional) The total number of available documents in the + :param int available: (optional) The total number of available documents in the collection. - :attr int processing: (optional) The number of documents in the collection that + :param int processing: (optional) The number of documents in the collection that are currently being processed. - :attr int failed: (optional) The number of documents in the collection that + :param int failed: (optional) The number of documents in the collection that failed to be ingested. - :attr int pending: (optional) The number of documents that have been uploaded to - the collection, but have not yet started processing. + :param int pending: (optional) The number of documents that have been uploaded + to the collection, but have not yet started processing. """ - def __init__(self, - *, - available: int = None, - processing: int = None, - failed: int = None, - pending: int = None) -> None: + def __init__( + self, + *, + available: Optional[int] = None, + processing: Optional[int] = None, + failed: Optional[int] = None, + pending: Optional[int] = None, + ) -> None: """ Initialize a DocumentCounts object. @@ -6021,14 +6518,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentCounts': """Initialize a DocumentCounts object from a json dictionary.""" args = {} - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'processing' in _dict: - args['processing'] = _dict.get('processing') - if 'failed' in _dict: - args['failed'] = _dict.get('failed') - if 'pending' in _dict: - args['pending'] = _dict.get('pending') + if (available := _dict.get('available')) is not None: + args['available'] = available + if (processing := _dict.get('processing')) is not None: + args['processing'] = processing + if (failed := _dict.get('failed')) is not None: + args['failed'] = failed + if (pending := _dict.get('pending')) is not None: + args['pending'] = pending return cls(**args) @classmethod @@ -6070,33 +6567,35 @@ def __ne__(self, other: 'DocumentCounts') -> bool: return not self == other -class DocumentStatus(): +class DocumentStatus: """ Status information about a submitted document. - :attr str document_id: (optional) The unique identifier of the document. - :attr str configuration_id: (optional) The unique identifier for the + :param str document_id: (optional) The unique identifier of the document. + :param str configuration_id: (optional) The unique identifier for the configuration. - :attr str status: (optional) Status of the document in the ingestion process. - :attr str status_description: (optional) Description of the document status. - :attr str filename: (optional) Name of the original source file (if available). - :attr str file_type: (optional) The type of the original source file. - :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted - as a hexadecimal string). - :attr List[Notice] notices: (optional) Array of notices produced by the + :param str status: (optional) Status of the document in the ingestion process. + :param str status_description: (optional) Description of the document status. + :param str filename: (optional) Name of the original source file (if available). + :param str file_type: (optional) The type of the original source file. + :param str sha1: (optional) The SHA-1 hash of the original source file + (formatted as a hexadecimal string). + :param List[Notice] notices: (optional) Array of notices produced by the document-ingestion process. """ - def __init__(self, - *, - document_id: str = None, - configuration_id: str = None, - status: str = None, - status_description: str = None, - filename: str = None, - file_type: str = None, - sha1: str = None, - notices: List['Notice'] = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + configuration_id: Optional[str] = None, + status: Optional[str] = None, + status_description: Optional[str] = None, + filename: Optional[str] = None, + file_type: Optional[str] = None, + sha1: Optional[str] = None, + notices: Optional[List['Notice']] = None, + ) -> None: """ Initialize a DocumentStatus object. @@ -6119,24 +6618,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentStatus': """Initialize a DocumentStatus object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'configuration_id' in _dict: - args['configuration_id'] = _dict.get('configuration_id') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - if 'file_type' in _dict: - args['file_type'] = _dict.get('file_type') - if 'sha1' in _dict: - args['sha1'] = _dict.get('sha1') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (configuration_id := _dict.get('configuration_id')) is not None: + args['configuration_id'] = configuration_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (filename := _dict.get('filename')) is not None: + args['filename'] = filename + if (file_type := _dict.get('file_type')) is not None: + args['file_type'] = file_type + if (sha1 := _dict.get('sha1')) is not None: + args['sha1'] = sha1 + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] return cls(**args) @classmethod @@ -6196,6 +6693,7 @@ class StatusEnum(str, Enum): """ Status of the document in the ingestion process. """ + AVAILABLE = 'available' AVAILABLE_WITH_NOTICES = 'available with notices' FAILED = 'failed' @@ -6206,50 +6704,53 @@ class FileTypeEnum(str, Enum): """ The type of the original source file. """ + PDF = 'pdf' HTML = 'html' WORD = 'word' JSON = 'json' -class Enrichment(): +class Enrichment: """ Enrichment step to perform on the document. Each enrichment is performed on the specified field in the order that they are listed in the configuration. - :attr str description: (optional) Describes what the enrichment step does. - :attr str destination_field: Field where enrichments will be stored. This field + :param str description: (optional) Describes what the enrichment step does. + :param str destination_field: Field where enrichments will be stored. This field must already exist or be at most 1 level deeper than an existing field. For example, if `text` is a top-level field with no sub-fields, `text.foo` is a valid destination but `text.foo.bar` is not. - :attr str source_field: Field to be enriched. + :param str source_field: Field to be enriched. Arrays can be specified as the **source_field** if the **enrichment** service for this enrichment is set to `natural_language_undstanding`. - :attr bool overwrite: (optional) Indicates that the enrichments will overwrite + :param bool overwrite: (optional) Indicates that the enrichments will overwrite the destination_field field if it already exists. - :attr str enrichment: Name of the enrichment service to call. The only supported - option is `natural_language_understanding`. The `elements` option is deprecated - and support ended on 10 July 2020. + :param str enrichment: Name of the enrichment service to call. The only + supported option is `natural_language_understanding`. The `elements` option is + deprecated and support ended on 10 July 2020. The **options** object must contain Natural Language Understanding options. - :attr bool ignore_downstream_errors: (optional) If true, then most errors + :param bool ignore_downstream_errors: (optional) If true, then most errors generated during the enrichment process will be treated as warnings and will not cause the document to fail processing. - :attr EnrichmentOptions options: (optional) Options that are specific to a + :param EnrichmentOptions options: (optional) Options that are specific to a particular enrichment. The `elements` enrichment type is deprecated. Use the [Create a project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of the Discovery v2 API to create a `content_intelligence` project type instead. """ - def __init__(self, - destination_field: str, - source_field: str, - enrichment: str, - *, - description: str = None, - overwrite: bool = None, - ignore_downstream_errors: bool = None, - options: 'EnrichmentOptions' = None) -> None: + def __init__( + self, + destination_field: str, + source_field: str, + enrichment: str, + *, + description: Optional[str] = None, + overwrite: Optional[bool] = None, + ignore_downstream_errors: Optional[bool] = None, + options: Optional['EnrichmentOptions'] = None, + ) -> None: """ Initialize a Enrichment object. @@ -6290,33 +6791,33 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Enrichment': """Initialize a Enrichment object from a json dictionary.""" args = {} - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'destination_field' in _dict: - args['destination_field'] = _dict.get('destination_field') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (destination_field := _dict.get('destination_field')) is not None: + args['destination_field'] = destination_field else: raise ValueError( 'Required property \'destination_field\' not present in Enrichment JSON' ) - if 'source_field' in _dict: - args['source_field'] = _dict.get('source_field') + if (source_field := _dict.get('source_field')) is not None: + args['source_field'] = source_field else: raise ValueError( 'Required property \'source_field\' not present in Enrichment JSON' ) - if 'overwrite' in _dict: - args['overwrite'] = _dict.get('overwrite') - if 'enrichment' in _dict: - args['enrichment'] = _dict.get('enrichment') + if (overwrite := _dict.get('overwrite')) is not None: + args['overwrite'] = overwrite + if (enrichment := _dict.get('enrichment')) is not None: + args['enrichment'] = enrichment else: raise ValueError( 'Required property \'enrichment\' not present in Enrichment JSON' ) - if 'ignore_downstream_errors' in _dict: - args['ignore_downstream_errors'] = _dict.get( - 'ignore_downstream_errors') - if 'options' in _dict: - args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) + if (ignore_downstream_errors := + _dict.get('ignore_downstream_errors')) is not None: + args['ignore_downstream_errors'] = ignore_downstream_errors + if (options := _dict.get('options')) is not None: + args['options'] = EnrichmentOptions.from_dict(options) return cls(**args) @classmethod @@ -6367,30 +6868,32 @@ def __ne__(self, other: 'Enrichment') -> bool: return not self == other -class EnrichmentOptions(): +class EnrichmentOptions: """ Options that are specific to a particular enrichment. The `elements` enrichment type is deprecated. Use the [Create a project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of the Discovery v2 API to create a `content_intelligence` project type instead. - :attr NluEnrichmentFeatures features: (optional) Object containing Natural + :param NluEnrichmentFeatures features: (optional) Object containing Natural Language Understanding features to be used. - :attr str language: (optional) ISO 639-1 code indicating the language to use for - the analysis. This code overrides the automatic language detection performed by - the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), `de` - (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and - `sv` (Swedish). **Note:** Not all features support all languages, automatic - detection is recommended. - :attr str model: (optional) Deprecated: The element extraction model to use, + :param str language: (optional) ISO 639-1 code indicating the language to use + for the analysis. This code overrides the automatic language detection performed + by the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), + `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` + (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, + automatic detection is recommended. + :param str model: (optional) Deprecated: The element extraction model to use, which can be `contract` only. The `elements` enrichment is deprecated. """ - def __init__(self, - *, - features: 'NluEnrichmentFeatures' = None, - language: str = None, - model: str = None) -> None: + def __init__( + self, + *, + features: Optional['NluEnrichmentFeatures'] = None, + language: Optional[str] = None, + model: Optional[str] = None, + ) -> None: """ Initialize a EnrichmentOptions object. @@ -6413,13 +6916,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} - if 'features' in _dict: - args['features'] = NluEnrichmentFeatures.from_dict( - _dict.get('features')) - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'model' in _dict: - args['model'] = _dict.get('model') + if (features := _dict.get('features')) is not None: + args['features'] = NluEnrichmentFeatures.from_dict(features) + if (language := _dict.get('language')) is not None: + args['language'] = language + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -6467,6 +6969,7 @@ class LanguageEnum(str, Enum): `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. """ + AR = 'ar' EN = 'en' FR = 'fr' @@ -6478,46 +6981,48 @@ class LanguageEnum(str, Enum): SV = 'sv' -class Environment(): +class Environment: """ Details about an environment. - :attr str environment_id: (optional) Unique identifier for the environment. - :attr str name: (optional) Name that identifies the environment. - :attr str description: (optional) Description of the environment. - :attr datetime created: (optional) Creation date of the environment, in the + :param str environment_id: (optional) Unique identifier for the environment. + :param str name: (optional) Name that identifies the environment. + :param str description: (optional) Description of the environment. + :param datetime created: (optional) Creation date of the environment, in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :attr datetime updated: (optional) Date of most recent environment update, in + :param datetime updated: (optional) Date of most recent environment update, in the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :attr str status: (optional) Current status of the environment. `resizing` is + :param str status: (optional) Current status of the environment. `resizing` is displayed when a request to increase the environment size has been made, but is still in the process of being completed. - :attr bool read_only: (optional) If `true`, the environment contains read-only + :param bool read_only: (optional) If `true`, the environment contains read-only collections that are maintained by IBM. - :attr str size: (optional) Current size of the environment. - :attr str requested_size: (optional) The new size requested for this + :param str size: (optional) Current size of the environment. + :param str requested_size: (optional) The new size requested for this environment. Only returned when the environment *status* is `resizing`. *Note:* Querying and indexing can still be performed during an environment upsize. - :attr IndexCapacity index_capacity: (optional) Details about the resource usage + :param IndexCapacity index_capacity: (optional) Details about the resource usage and capacity of the environment. - :attr SearchStatus search_status: (optional) Information about the Continuous + :param SearchStatus search_status: (optional) Information about the Continuous Relevancy Training for this environment. """ - def __init__(self, - *, - environment_id: str = None, - name: str = None, - description: str = None, - created: datetime = None, - updated: datetime = None, - status: str = None, - read_only: bool = None, - size: str = None, - requested_size: str = None, - index_capacity: 'IndexCapacity' = None, - search_status: 'SearchStatus' = None) -> None: + def __init__( + self, + *, + environment_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + status: Optional[str] = None, + read_only: Optional[bool] = None, + size: Optional[str] = None, + requested_size: Optional[str] = None, + index_capacity: Optional['IndexCapacity'] = None, + search_status: Optional['SearchStatus'] = None, + ) -> None: """ Initialize a Environment object. @@ -6549,30 +7054,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Environment': """Initialize a Environment object from a json dictionary.""" args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'read_only' in _dict: - args['read_only'] = _dict.get('read_only') - if 'size' in _dict: - args['size'] = _dict.get('size') - if 'requested_size' in _dict: - args['requested_size'] = _dict.get('requested_size') - if 'index_capacity' in _dict: - args['index_capacity'] = IndexCapacity.from_dict( - _dict.get('index_capacity')) - if 'search_status' in _dict: - args['search_status'] = SearchStatus.from_dict( - _dict.get('search_status')) + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (read_only := _dict.get('read_only')) is not None: + args['read_only'] = read_only + if (size := _dict.get('size')) is not None: + args['size'] = size + if (requested_size := _dict.get('requested_size')) is not None: + args['requested_size'] = requested_size + if (index_capacity := _dict.get('index_capacity')) is not None: + args['index_capacity'] = IndexCapacity.from_dict(index_capacity) + if (search_status := _dict.get('search_status')) is not None: + args['search_status'] = SearchStatus.from_dict(search_status) return cls(**args) @classmethod @@ -6639,6 +7142,7 @@ class StatusEnum(str, Enum): increase the environment size has been made, but is still in the process of being completed. """ + ACTIVE = 'active' PENDING = 'pending' MAINTENANCE = 'maintenance' @@ -6648,6 +7152,7 @@ class SizeEnum(str, Enum): """ Current size of the environment. """ + LT = 'LT' XS = 'XS' S = 'S' @@ -6660,19 +7165,22 @@ class SizeEnum(str, Enum): XXXL = 'XXXL' -class EnvironmentDocuments(): +class EnvironmentDocuments: """ Summary of the document usage statistics for the environment. - :attr int available: (optional) Number of documents indexed for the environment. - :attr int maximum_allowed: (optional) Total number of documents allowed in the + :param int available: (optional) Number of documents indexed for the + environment. + :param int maximum_allowed: (optional) Total number of documents allowed in the environment's capacity. """ - def __init__(self, - *, - available: int = None, - maximum_allowed: int = None) -> None: + def __init__( + self, + *, + available: Optional[int] = None, + maximum_allowed: Optional[int] = None, + ) -> None: """ Initialize a EnvironmentDocuments object. @@ -6684,10 +7192,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnvironmentDocuments': """Initialize a EnvironmentDocuments object from a json dictionary.""" args = {} - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'maximum_allowed' in _dict: - args['maximum_allowed'] = _dict.get('maximum_allowed') + if (available := _dict.get('available')) is not None: + args['available'] = available + if (maximum_allowed := _dict.get('maximum_allowed')) is not None: + args['maximum_allowed'] = maximum_allowed return cls(**args) @classmethod @@ -6725,36 +7233,39 @@ def __ne__(self, other: 'EnvironmentDocuments') -> bool: return not self == other -class EventData(): +class EventData: """ Query event data object. - :attr str environment_id: The **environment_id** associated with the query that + :param str environment_id: The **environment_id** associated with the query that the event is associated with. - :attr str session_token: The session token that was returned as part of the + :param str session_token: The session token that was returned as part of the query results that this event is associated with. - :attr datetime client_timestamp: (optional) The optional timestamp for the event - that was created. If not provided, the time that the event was created in the - log was used. - :attr int display_rank: (optional) The rank of the result item which the event + :param datetime client_timestamp: (optional) The optional timestamp for the + event that was created. If not provided, the time that the event was created in + the log was used. + :param int display_rank: (optional) The rank of the result item which the event is associated with. - :attr str collection_id: The **collection_id** of the document that this event + :param str collection_id: The **collection_id** of the document that this event is associated with. - :attr str document_id: The **document_id** of the document that this event is + :param str document_id: The **document_id** of the document that this event is associated with. - :attr str query_id: (optional) The query identifier stored in the log. The query - and any events associated with that query are stored with the same **query_id**. + :param str query_id: (optional) The query identifier stored in the log. The + query and any events associated with that query are stored with the same + **query_id**. """ - def __init__(self, - environment_id: str, - session_token: str, - collection_id: str, - document_id: str, - *, - client_timestamp: datetime = None, - display_rank: int = None, - query_id: str = None) -> None: + def __init__( + self, + environment_id: str, + session_token: str, + collection_id: str, + document_id: str, + *, + client_timestamp: Optional[datetime] = None, + display_rank: Optional[int] = None, + query_id: Optional[str] = None, + ) -> None: """ Initialize a EventData object. @@ -6784,37 +7295,36 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EventData': """Initialize a EventData object from a json dictionary.""" args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id else: raise ValueError( 'Required property \'environment_id\' not present in EventData JSON' ) - if 'session_token' in _dict: - args['session_token'] = _dict.get('session_token') + if (session_token := _dict.get('session_token')) is not None: + args['session_token'] = session_token else: raise ValueError( 'Required property \'session_token\' not present in EventData JSON' ) - if 'client_timestamp' in _dict: - args['client_timestamp'] = string_to_datetime( - _dict.get('client_timestamp')) - if 'display_rank' in _dict: - args['display_rank'] = _dict.get('display_rank') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (client_timestamp := _dict.get('client_timestamp')) is not None: + args['client_timestamp'] = string_to_datetime(client_timestamp) + if (display_rank := _dict.get('display_rank')) is not None: + args['display_rank'] = display_rank + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id else: raise ValueError( 'Required property \'collection_id\' not present in EventData JSON' ) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id else: raise ValueError( 'Required property \'document_id\' not present in EventData JSON' ) - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id return cls(**args) @classmethod @@ -6862,23 +7372,25 @@ def __ne__(self, other: 'EventData') -> bool: return not self == other -class Expansion(): +class Expansion: """ An expansion definition. Each object respresents one set of expandable strings. For example, you could have expansions for the word `hot` in one object, and expansions for the word `cold` in another. - :attr List[str] input_terms: (optional) A list of terms that will be expanded + :param List[str] input_terms: (optional) A list of terms that will be expanded for this expansion. If specified, only the items in this list are expanded. - :attr List[str] expanded_terms: A list of terms that this expansion will be + :param List[str] expanded_terms: A list of terms that this expansion will be expanded to. If specified without **input_terms**, it also functions as the input term list. """ - def __init__(self, - expanded_terms: List[str], - *, - input_terms: List[str] = None) -> None: + def __init__( + self, + expanded_terms: List[str], + *, + input_terms: Optional[List[str]] = None, + ) -> None: """ Initialize a Expansion object. @@ -6896,10 +7408,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Expansion': """Initialize a Expansion object from a json dictionary.""" args = {} - if 'input_terms' in _dict: - args['input_terms'] = _dict.get('input_terms') - if 'expanded_terms' in _dict: - args['expanded_terms'] = _dict.get('expanded_terms') + if (input_terms := _dict.get('input_terms')) is not None: + args['input_terms'] = input_terms + if (expanded_terms := _dict.get('expanded_terms')) is not None: + args['expanded_terms'] = expanded_terms else: raise ValueError( 'Required property \'expanded_terms\' not present in Expansion JSON' @@ -6939,11 +7451,11 @@ def __ne__(self, other: 'Expansion') -> bool: return not self == other -class Expansions(): +class Expansions: """ The query expansion definitions for the specified collection. - :attr List[Expansion] expansions: An array of query expansion definitions. + :param List[Expansion] expansions: An array of query expansion definitions. Each object in the **expansions** array represents a term or set of terms that will be expanded into other terms. Each expansion object can be configured as bidirectional or unidirectional. Bidirectional means that all terms are expanded @@ -6958,7 +7470,10 @@ class Expansions(): **expanded_terms** array. """ - def __init__(self, expansions: List['Expansion']) -> None: + def __init__( + self, + expansions: List['Expansion'], + ) -> None: """ Initialize a Expansions object. @@ -6982,10 +7497,8 @@ def __init__(self, expansions: List['Expansion']) -> None: def from_dict(cls, _dict: Dict) -> 'Expansions': """Initialize a Expansions object from a json dictionary.""" args = {} - if 'expansions' in _dict: - args['expansions'] = [ - Expansion.from_dict(v) for v in _dict.get('expansions') - ] + if (expansions := _dict.get('expansions')) is not None: + args['expansions'] = [Expansion.from_dict(v) for v in expansions] else: raise ValueError( 'Required property \'expansions\' not present in Expansions JSON' @@ -7029,15 +7542,20 @@ def __ne__(self, other: 'Expansions') -> bool: return not self == other -class Field(): +class Field: """ Object containing field details. - :attr str field: (optional) The name of the field. - :attr str type: (optional) The type of the field. + :param str field: (optional) The name of the field. + :param str type: (optional) The type of the field. """ - def __init__(self, *, field: str = None, type: str = None) -> None: + def __init__( + self, + *, + field: Optional[str] = None, + type: Optional[str] = None, + ) -> None: """ Initialize a Field object. @@ -7049,10 +7567,10 @@ def __init__(self, *, field: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Field': """Initialize a Field object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (field := _dict.get('field')) is not None: + args['field'] = field + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -7091,6 +7609,7 @@ class TypeEnum(str, Enum): """ The type of the field. """ + NESTED = 'nested' STRING = 'string' DATE = 'date' @@ -7104,27 +7623,29 @@ class TypeEnum(str, Enum): BINARY = 'binary' -class FontSetting(): +class FontSetting: """ Font matching configuration. - :attr int level: (optional) The HTML heading level that any content with the + :param int level: (optional) The HTML heading level that any content with the matching font is converted to. - :attr int min_size: (optional) The minimum size of the font to match. - :attr int max_size: (optional) The maximum size of the font to match. - :attr bool bold: (optional) When `true`, the font is matched if it is bold. - :attr bool italic: (optional) When `true`, the font is matched if it is italic. - :attr str name: (optional) The name of the font. - """ - - def __init__(self, - *, - level: int = None, - min_size: int = None, - max_size: int = None, - bold: bool = None, - italic: bool = None, - name: str = None) -> None: + :param int min_size: (optional) The minimum size of the font to match. + :param int max_size: (optional) The maximum size of the font to match. + :param bool bold: (optional) When `true`, the font is matched if it is bold. + :param bool italic: (optional) When `true`, the font is matched if it is italic. + :param str name: (optional) The name of the font. + """ + + def __init__( + self, + *, + level: Optional[int] = None, + min_size: Optional[int] = None, + max_size: Optional[int] = None, + bold: Optional[bool] = None, + italic: Optional[bool] = None, + name: Optional[str] = None, + ) -> None: """ Initialize a FontSetting object. @@ -7149,18 +7670,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'FontSetting': """Initialize a FontSetting object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') - if 'min_size' in _dict: - args['min_size'] = _dict.get('min_size') - if 'max_size' in _dict: - args['max_size'] = _dict.get('max_size') - if 'bold' in _dict: - args['bold'] = _dict.get('bold') - if 'italic' in _dict: - args['italic'] = _dict.get('italic') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (level := _dict.get('level')) is not None: + args['level'] = level + if (min_size := _dict.get('min_size')) is not None: + args['min_size'] = min_size + if (max_size := _dict.get('max_size')) is not None: + args['max_size'] = max_size + if (bold := _dict.get('bold')) is not None: + args['bold'] = bold + if (italic := _dict.get('italic')) is not None: + args['italic'] = italic + if (name := _dict.get('name')) is not None: + args['name'] = name return cls(**args) @classmethod @@ -7204,28 +7725,30 @@ def __ne__(self, other: 'FontSetting') -> bool: return not self == other -class Gateway(): +class Gateway: """ Object describing a specific gateway. - :attr str gateway_id: (optional) The gateway ID of the gateway. - :attr str name: (optional) The user defined name of the gateway. - :attr str status: (optional) The current status of the gateway. `connected` + :param str gateway_id: (optional) The gateway ID of the gateway. + :param str name: (optional) The user defined name of the gateway. + :param str status: (optional) The current status of the gateway. `connected` means the gateway is connected to the remotly installed gateway. `idle` means this gateway is not currently in use. - :attr str token: (optional) The generated **token** for this gateway. The value + :param str token: (optional) The generated **token** for this gateway. The value of this field is used when configuring the remotly installed gateway. - :attr str token_id: (optional) The generated **token_id** for this gateway. The + :param str token_id: (optional) The generated **token_id** for this gateway. The value of this field is used when configuring the remotly installed gateway. """ - def __init__(self, - *, - gateway_id: str = None, - name: str = None, - status: str = None, - token: str = None, - token_id: str = None) -> None: + def __init__( + self, + *, + gateway_id: Optional[str] = None, + name: Optional[str] = None, + status: Optional[str] = None, + token: Optional[str] = None, + token_id: Optional[str] = None, + ) -> None: """ Initialize a Gateway object. @@ -7250,16 +7773,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Gateway': """Initialize a Gateway object from a json dictionary.""" args = {} - if 'gateway_id' in _dict: - args['gateway_id'] = _dict.get('gateway_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'token' in _dict: - args['token'] = _dict.get('token') - if 'token_id' in _dict: - args['token_id'] = _dict.get('token_id') + if (gateway_id := _dict.get('gateway_id')) is not None: + args['gateway_id'] = gateway_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (status := _dict.get('status')) is not None: + args['status'] = status + if (token := _dict.get('token')) is not None: + args['token'] = token + if (token_id := _dict.get('token_id')) is not None: + args['token_id'] = token_id return cls(**args) @classmethod @@ -7305,19 +7828,25 @@ class StatusEnum(str, Enum): The current status of the gateway. `connected` means the gateway is connected to the remotly installed gateway. `idle` means this gateway is not currently in use. """ + CONNECTED = 'connected' IDLE = 'idle' -class GatewayDelete(): +class GatewayDelete: """ Gatway deletion confirmation. - :attr str gateway_id: (optional) The gateway ID of the deleted gateway. - :attr str status: (optional) The status of the request. + :param str gateway_id: (optional) The gateway ID of the deleted gateway. + :param str status: (optional) The status of the request. """ - def __init__(self, *, gateway_id: str = None, status: str = None) -> None: + def __init__( + self, + *, + gateway_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a GatewayDelete object. @@ -7331,10 +7860,10 @@ def __init__(self, *, gateway_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'GatewayDelete': """Initialize a GatewayDelete object from a json dictionary.""" args = {} - if 'gateway_id' in _dict: - args['gateway_id'] = _dict.get('gateway_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (gateway_id := _dict.get('gateway_id')) is not None: + args['gateway_id'] = gateway_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -7370,15 +7899,19 @@ def __ne__(self, other: 'GatewayDelete') -> bool: return not self == other -class GatewayList(): +class GatewayList: """ Object containing gateways array. - :attr List[Gateway] gateways: (optional) Array of configured gateway + :param List[Gateway] gateways: (optional) Array of configured gateway connections. """ - def __init__(self, *, gateways: List['Gateway'] = None) -> None: + def __init__( + self, + *, + gateways: Optional[List['Gateway']] = None, + ) -> None: """ Initialize a GatewayList object. @@ -7391,10 +7924,8 @@ def __init__(self, *, gateways: List['Gateway'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'GatewayList': """Initialize a GatewayList object from a json dictionary.""" args = {} - if 'gateways' in _dict: - args['gateways'] = [ - Gateway.from_dict(v) for v in _dict.get('gateways') - ] + if (gateways := _dict.get('gateways')) is not None: + args['gateways'] = [Gateway.from_dict(v) for v in gateways] return cls(**args) @classmethod @@ -7434,32 +7965,34 @@ def __ne__(self, other: 'GatewayList') -> bool: return not self == other -class HtmlSettings(): +class HtmlSettings: """ A list of HTML conversion settings. - :attr List[str] exclude_tags_completely: (optional) Array of HTML tags that are + :param List[str] exclude_tags_completely: (optional) Array of HTML tags that are excluded completely. - :attr List[str] exclude_tags_keep_content: (optional) Array of HTML tags which + :param List[str] exclude_tags_keep_content: (optional) Array of HTML tags which are excluded but still retain content. - :attr XPathPatterns keep_content: (optional) Object containing an array of + :param XPathPatterns keep_content: (optional) Object containing an array of XPaths. - :attr XPathPatterns exclude_content: (optional) Object containing an array of + :param XPathPatterns exclude_content: (optional) Object containing an array of XPaths. - :attr List[str] keep_tag_attributes: (optional) An array of HTML tag attributes + :param List[str] keep_tag_attributes: (optional) An array of HTML tag attributes to keep in the converted document. - :attr List[str] exclude_tag_attributes: (optional) Array of HTML tag attributes + :param List[str] exclude_tag_attributes: (optional) Array of HTML tag attributes to exclude. """ - def __init__(self, - *, - exclude_tags_completely: List[str] = None, - exclude_tags_keep_content: List[str] = None, - keep_content: 'XPathPatterns' = None, - exclude_content: 'XPathPatterns' = None, - keep_tag_attributes: List[str] = None, - exclude_tag_attributes: List[str] = None) -> None: + def __init__( + self, + *, + exclude_tags_completely: Optional[List[str]] = None, + exclude_tags_keep_content: Optional[List[str]] = None, + keep_content: Optional['XPathPatterns'] = None, + exclude_content: Optional['XPathPatterns'] = None, + keep_tag_attributes: Optional[List[str]] = None, + exclude_tag_attributes: Optional[List[str]] = None, + ) -> None: """ Initialize a HtmlSettings object. @@ -7487,22 +8020,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'HtmlSettings': """Initialize a HtmlSettings object from a json dictionary.""" args = {} - if 'exclude_tags_completely' in _dict: - args['exclude_tags_completely'] = _dict.get( - 'exclude_tags_completely') - if 'exclude_tags_keep_content' in _dict: - args['exclude_tags_keep_content'] = _dict.get( - 'exclude_tags_keep_content') - if 'keep_content' in _dict: - args['keep_content'] = XPathPatterns.from_dict( - _dict.get('keep_content')) - if 'exclude_content' in _dict: - args['exclude_content'] = XPathPatterns.from_dict( - _dict.get('exclude_content')) - if 'keep_tag_attributes' in _dict: - args['keep_tag_attributes'] = _dict.get('keep_tag_attributes') - if 'exclude_tag_attributes' in _dict: - args['exclude_tag_attributes'] = _dict.get('exclude_tag_attributes') + if (exclude_tags_completely := + _dict.get('exclude_tags_completely')) is not None: + args['exclude_tags_completely'] = exclude_tags_completely + if (exclude_tags_keep_content := + _dict.get('exclude_tags_keep_content')) is not None: + args['exclude_tags_keep_content'] = exclude_tags_keep_content + if (keep_content := _dict.get('keep_content')) is not None: + args['keep_content'] = XPathPatterns.from_dict(keep_content) + if (exclude_content := _dict.get('exclude_content')) is not None: + args['exclude_content'] = XPathPatterns.from_dict(exclude_content) + if (keep_tag_attributes := + _dict.get('keep_tag_attributes')) is not None: + args['keep_tag_attributes'] = keep_tag_attributes + if (exclude_tag_attributes := + _dict.get('exclude_tag_attributes')) is not None: + args['exclude_tag_attributes'] = exclude_tag_attributes return cls(**args) @classmethod @@ -7558,23 +8091,25 @@ def __ne__(self, other: 'HtmlSettings') -> bool: return not self == other -class IndexCapacity(): +class IndexCapacity: """ Details about the resource usage and capacity of the environment. - :attr EnvironmentDocuments documents: (optional) Summary of the document usage + :param EnvironmentDocuments documents: (optional) Summary of the document usage statistics for the environment. - :attr DiskUsage disk_usage: (optional) Summary of the disk usage statistics for - the environment. - :attr CollectionUsage collections: (optional) Summary of the collection usage in + :param DiskUsage disk_usage: (optional) Summary of the disk usage statistics for the environment. + :param CollectionUsage collections: (optional) Summary of the collection usage + in the environment. """ - def __init__(self, - *, - documents: 'EnvironmentDocuments' = None, - disk_usage: 'DiskUsage' = None, - collections: 'CollectionUsage' = None) -> None: + def __init__( + self, + *, + documents: Optional['EnvironmentDocuments'] = None, + disk_usage: Optional['DiskUsage'] = None, + collections: Optional['CollectionUsage'] = None, + ) -> None: """ Initialize a IndexCapacity object. @@ -7593,14 +8128,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'IndexCapacity': """Initialize a IndexCapacity object from a json dictionary.""" args = {} - if 'documents' in _dict: - args['documents'] = EnvironmentDocuments.from_dict( - _dict.get('documents')) - if 'disk_usage' in _dict: - args['disk_usage'] = DiskUsage.from_dict(_dict.get('disk_usage')) - if 'collections' in _dict: - args['collections'] = CollectionUsage.from_dict( - _dict.get('collections')) + if (documents := _dict.get('documents')) is not None: + args['documents'] = EnvironmentDocuments.from_dict(documents) + if (disk_usage := _dict.get('disk_usage')) is not None: + args['disk_usage'] = DiskUsage.from_dict(disk_usage) + if (collections := _dict.get('collections')) is not None: + args['collections'] = CollectionUsage.from_dict(collections) return cls(**args) @classmethod @@ -7647,7 +8180,7 @@ def __ne__(self, other: 'IndexCapacity') -> bool: return not self == other -class ListCollectionFieldsResponse(): +class ListCollectionFieldsResponse: """ The list of fetched fields. The fields are returned using a fully qualified name format, however, the format @@ -7660,11 +8193,15 @@ class ListCollectionFieldsResponse(): `v{N}-fullnews-t3-{YEAR}.mappings` (for example, `v5-fullnews-t3-2016.mappings.text.properties.author`). - :attr List[Field] fields: (optional) An array containing information about each + :param List[Field] fields: (optional) An array containing information about each field in the collections. """ - def __init__(self, *, fields: List['Field'] = None) -> None: + def __init__( + self, + *, + fields: Optional[List['Field']] = None, + ) -> None: """ Initialize a ListCollectionFieldsResponse object. @@ -7677,8 +8214,8 @@ def __init__(self, *, fields: List['Field'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListCollectionFieldsResponse': """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" args = {} - if 'fields' in _dict: - args['fields'] = [Field.from_dict(v) for v in _dict.get('fields')] + if (fields := _dict.get('fields')) is not None: + args['fields'] = [Field.from_dict(v) for v in fields] return cls(**args) @classmethod @@ -7718,15 +8255,19 @@ def __ne__(self, other: 'ListCollectionFieldsResponse') -> bool: return not self == other -class ListCollectionsResponse(): +class ListCollectionsResponse: """ Response object containing an array of collection details. - :attr List[Collection] collections: (optional) An array containing information + :param List[Collection] collections: (optional) An array containing information about each collection in the environment. """ - def __init__(self, *, collections: List['Collection'] = None) -> None: + def __init__( + self, + *, + collections: Optional[List['Collection']] = None, + ) -> None: """ Initialize a ListCollectionsResponse object. @@ -7739,10 +8280,8 @@ def __init__(self, *, collections: List['Collection'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} - if 'collections' in _dict: - args['collections'] = [ - Collection.from_dict(v) for v in _dict.get('collections') - ] + if (collections := _dict.get('collections')) is not None: + args['collections'] = [Collection.from_dict(v) for v in collections] return cls(**args) @classmethod @@ -7782,15 +8321,19 @@ def __ne__(self, other: 'ListCollectionsResponse') -> bool: return not self == other -class ListConfigurationsResponse(): +class ListConfigurationsResponse: """ Object containing an array of available configurations. - :attr List[Configuration] configurations: (optional) An array of configurations + :param List[Configuration] configurations: (optional) An array of configurations that are available for the service instance. """ - def __init__(self, *, configurations: List['Configuration'] = None) -> None: + def __init__( + self, + *, + configurations: Optional[List['Configuration']] = None, + ) -> None: """ Initialize a ListConfigurationsResponse object. @@ -7803,9 +8346,9 @@ def __init__(self, *, configurations: List['Configuration'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListConfigurationsResponse': """Initialize a ListConfigurationsResponse object from a json dictionary.""" args = {} - if 'configurations' in _dict: + if (configurations := _dict.get('configurations')) is not None: args['configurations'] = [ - Configuration.from_dict(v) for v in _dict.get('configurations') + Configuration.from_dict(v) for v in configurations ] return cls(**args) @@ -7846,15 +8389,19 @@ def __ne__(self, other: 'ListConfigurationsResponse') -> bool: return not self == other -class ListEnvironmentsResponse(): +class ListEnvironmentsResponse: """ Response object containing an array of configured environments. - :attr List[Environment] environments: (optional) An array of [environments] that - are available for the service instance. + :param List[Environment] environments: (optional) An array of [environments] + that are available for the service instance. """ - def __init__(self, *, environments: List['Environment'] = None) -> None: + def __init__( + self, + *, + environments: Optional[List['Environment']] = None, + ) -> None: """ Initialize a ListEnvironmentsResponse object. @@ -7867,9 +8414,9 @@ def __init__(self, *, environments: List['Environment'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListEnvironmentsResponse': """Initialize a ListEnvironmentsResponse object from a json dictionary.""" args = {} - if 'environments' in _dict: + if (environments := _dict.get('environments')) is not None: args['environments'] = [ - Environment.from_dict(v) for v in _dict.get('environments') + Environment.from_dict(v) for v in environments ] return cls(**args) @@ -7910,19 +8457,21 @@ def __ne__(self, other: 'ListEnvironmentsResponse') -> bool: return not self == other -class LogQueryResponse(): +class LogQueryResponse: """ Object containing results that match the requested **logs** query. - :attr int matching_results: (optional) Number of matching results. - :attr List[LogQueryResponseResult] results: (optional) Array of log query + :param int matching_results: (optional) Number of matching results. + :param List[LogQueryResponseResult] results: (optional) Array of log query response results. """ - def __init__(self, - *, - matching_results: int = None, - results: List['LogQueryResponseResult'] = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + results: Optional[List['LogQueryResponseResult']] = None, + ) -> None: """ Initialize a LogQueryResponse object. @@ -7937,12 +8486,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponse': """Initialize a LogQueryResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (results := _dict.get('results')) is not None: args['results'] = [ - LogQueryResponseResult.from_dict(v) - for v in _dict.get('results') + LogQueryResponseResult.from_dict(v) for v in results ] return cls(**args) @@ -7986,40 +8534,40 @@ def __ne__(self, other: 'LogQueryResponse') -> bool: return not self == other -class LogQueryResponseResult(): +class LogQueryResponseResult: """ Individual result object for a **logs** query. Each object represents either a query to a Discovery collection or an event that is associated with a query. - :attr str environment_id: (optional) The environment ID that is associated with + :param str environment_id: (optional) The environment ID that is associated with this log entry. - :attr str customer_id: (optional) The **customer_id** label that was specified + :param str customer_id: (optional) The **customer_id** label that was specified in the header of the query or event API call that corresponds to this log entry. - :attr str document_type: (optional) The type of log entry returned. + :param str document_type: (optional) The type of log entry returned. **query** indicates that the log represents the results of a call to the single collection **query** method. **event** indicates that the log represents a call to the **events** API. - :attr str natural_language_query: (optional) The value of the + :param str natural_language_query: (optional) The value of the **natural_language_query** query parameter that was used to create these results. Only returned with logs of type **query**. **Note:** Other query parameters (such as **filter** or **deduplicate**) might have been used with this query, but are not recorded. - :attr LogQueryResponseResultDocuments document_results: (optional) Object + :param LogQueryResponseResultDocuments document_results: (optional) Object containing result information that was returned by the query used to create this log entry. Only returned with logs of type `query`. - :attr datetime created_timestamp: (optional) Date that the log result was + :param datetime created_timestamp: (optional) Date that the log result was created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. - :attr datetime client_timestamp: (optional) Date specified by the user when + :param datetime client_timestamp: (optional) Date specified by the user when recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only returned with logs of type **event**. - :attr str query_id: (optional) Identifier that corresponds to the + :param str query_id: (optional) Identifier that corresponds to the **natural_language_query** string used in the original or associated query. All **event** and **query** log entries that have the same original **natural_language_query** string also have them same **query_id**. This field can be used to recall all **event** and **query** log results that have the same original query (**event** logs do not contain the original **natural_language_query** field). - :attr str session_token: (optional) Unique identifier (within a 24-hour period) + :param str session_token: (optional) Unique identifier (within a 24-hour period) that identifies a single `query` log and any `event` logs that were created for it. **Note:** If the exact same query is run at the exact same time on different @@ -8028,36 +8576,38 @@ class LogQueryResponseResult(): **Note:** Session tokens are case sensitive. To avoid matching on session tokens that are identical except for case, use the exact match operator (`::`) when you query for a specific session token. - :attr str collection_id: (optional) The collection ID of the document associated - with this event. Only returned with logs of type `event`. - :attr int display_rank: (optional) The original display rank of the document + :param str collection_id: (optional) The collection ID of the document + associated with this event. Only returned with logs of type `event`. + :param int display_rank: (optional) The original display rank of the document associated with this event. Only returned with logs of type `event`. - :attr str document_id: (optional) The document ID of the document associated + :param str document_id: (optional) The document ID of the document associated with this event. Only returned with logs of type `event`. - :attr str event_type: (optional) The type of event that this object respresents. - Possible values are + :param str event_type: (optional) The type of event that this object + respresents. Possible values are - `query` the log of a query to a collection - `click` the result of a call to the **events** endpoint. - :attr str result_type: (optional) The type of result that this **event** is + :param str result_type: (optional) The type of result that this **event** is associated with. Only returned with logs of type `event`. """ - def __init__(self, - *, - environment_id: str = None, - customer_id: str = None, - document_type: str = None, - natural_language_query: str = None, - document_results: 'LogQueryResponseResultDocuments' = None, - created_timestamp: datetime = None, - client_timestamp: datetime = None, - query_id: str = None, - session_token: str = None, - collection_id: str = None, - display_rank: int = None, - document_id: str = None, - event_type: str = None, - result_type: str = None) -> None: + def __init__( + self, + *, + environment_id: Optional[str] = None, + customer_id: Optional[str] = None, + document_type: Optional[str] = None, + natural_language_query: Optional[str] = None, + document_results: Optional['LogQueryResponseResultDocuments'] = None, + created_timestamp: Optional[datetime] = None, + client_timestamp: Optional[datetime] = None, + query_id: Optional[str] = None, + session_token: Optional[str] = None, + collection_id: Optional[str] = None, + display_rank: Optional[int] = None, + document_id: Optional[str] = None, + event_type: Optional[str] = None, + result_type: Optional[str] = None, + ) -> None: """ Initialize a LogQueryResponseResult object. @@ -8132,38 +8682,37 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResult': """Initialize a LogQueryResponseResult object from a json dictionary.""" args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'customer_id' in _dict: - args['customer_id'] = _dict.get('customer_id') - if 'document_type' in _dict: - args['document_type'] = _dict.get('document_type') - if 'natural_language_query' in _dict: - args['natural_language_query'] = _dict.get('natural_language_query') - if 'document_results' in _dict: + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (customer_id := _dict.get('customer_id')) is not None: + args['customer_id'] = customer_id + if (document_type := _dict.get('document_type')) is not None: + args['document_type'] = document_type + if (natural_language_query := + _dict.get('natural_language_query')) is not None: + args['natural_language_query'] = natural_language_query + if (document_results := _dict.get('document_results')) is not None: args[ 'document_results'] = LogQueryResponseResultDocuments.from_dict( - _dict.get('document_results')) - if 'created_timestamp' in _dict: - args['created_timestamp'] = string_to_datetime( - _dict.get('created_timestamp')) - if 'client_timestamp' in _dict: - args['client_timestamp'] = string_to_datetime( - _dict.get('client_timestamp')) - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'session_token' in _dict: - args['session_token'] = _dict.get('session_token') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'display_rank' in _dict: - args['display_rank'] = _dict.get('display_rank') - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'event_type' in _dict: - args['event_type'] = _dict.get('event_type') - if 'result_type' in _dict: - args['result_type'] = _dict.get('result_type') + document_results) + if (created_timestamp := _dict.get('created_timestamp')) is not None: + args['created_timestamp'] = string_to_datetime(created_timestamp) + if (client_timestamp := _dict.get('client_timestamp')) is not None: + args['client_timestamp'] = string_to_datetime(client_timestamp) + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (session_token := _dict.get('session_token')) is not None: + args['session_token'] = session_token + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (display_rank := _dict.get('display_rank')) is not None: + args['display_rank'] = display_rank + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (event_type := _dict.get('event_type')) is not None: + args['event_type'] = event_type + if (result_type := _dict.get('result_type')) is not None: + args['result_type'] = result_type return cls(**args) @classmethod @@ -8238,6 +8787,7 @@ class DocumentTypeEnum(str, Enum): collection **query** method. **event** indicates that the log represents a call to the **events** API. """ + QUERY = 'query' EVENT = 'event' @@ -8247,6 +8797,7 @@ class EventTypeEnum(str, Enum): - `query` the log of a query to a collection - `click` the result of a call to the **events** endpoint. """ + CLICK = 'click' QUERY = 'query' @@ -8255,24 +8806,27 @@ class ResultTypeEnum(str, Enum): The type of result that this **event** is associated with. Only returned with logs of type `event`. """ + DOCUMENT = 'document' -class LogQueryResponseResultDocuments(): +class LogQueryResponseResultDocuments: """ Object containing result information that was returned by the query used to create this log entry. Only returned with logs of type `query`. - :attr List[LogQueryResponseResultDocumentsResult] results: (optional) Array of + :param List[LogQueryResponseResultDocumentsResult] results: (optional) Array of log query response results. - :attr int count: (optional) The number of results returned in the query + :param int count: (optional) The number of results returned in the query associate with this log. """ - def __init__(self, - *, - results: List['LogQueryResponseResultDocumentsResult'] = None, - count: int = None) -> None: + def __init__( + self, + *, + results: Optional[List['LogQueryResponseResultDocumentsResult']] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a LogQueryResponseResultDocuments object. @@ -8288,13 +8842,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocuments': """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" args = {} - if 'results' in _dict: + if (results := _dict.get('results')) is not None: args['results'] = [ LogQueryResponseResultDocumentsResult.from_dict(v) - for v in _dict.get('results') + for v in results ] - if 'count' in _dict: - args['count'] = _dict.get('count') + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -8336,30 +8890,32 @@ def __ne__(self, other: 'LogQueryResponseResultDocuments') -> bool: return not self == other -class LogQueryResponseResultDocumentsResult(): +class LogQueryResponseResultDocumentsResult: """ Each object in the **results** array corresponds to an individual document returned by the original query. - :attr int position: (optional) The result rank of this document. A position of + :param int position: (optional) The result rank of this document. A position of `1` indicates that it was the first returned result. - :attr str document_id: (optional) The **document_id** of the document that this + :param str document_id: (optional) The **document_id** of the document that this result represents. - :attr float score: (optional) The raw score of this result. A higher score + :param float score: (optional) The raw score of this result. A higher score indicates a greater match to the query parameters. - :attr float confidence: (optional) The confidence score of the result's + :param float confidence: (optional) The confidence score of the result's analysis. A higher score indicating greater confidence. - :attr str collection_id: (optional) The **collection_id** of the document + :param str collection_id: (optional) The **collection_id** of the document represented by this result. """ - def __init__(self, - *, - position: int = None, - document_id: str = None, - score: float = None, - confidence: float = None, - collection_id: str = None) -> None: + def __init__( + self, + *, + position: Optional[int] = None, + document_id: Optional[str] = None, + score: Optional[float] = None, + confidence: Optional[float] = None, + collection_id: Optional[str] = None, + ) -> None: """ Initialize a LogQueryResponseResultDocumentsResult object. @@ -8384,16 +8940,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocumentsResult': """Initialize a LogQueryResponseResultDocumentsResult object from a json dictionary.""" args = {} - if 'position' in _dict: - args['position'] = _dict.get('position') - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'score' in _dict: - args['score'] = _dict.get('score') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (position := _dict.get('position')) is not None: + args['position'] = position + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (score := _dict.get('score')) is not None: + args['score'] = score + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id return cls(**args) @classmethod @@ -8435,23 +8991,25 @@ def __ne__(self, other: 'LogQueryResponseResultDocumentsResult') -> bool: return not self == other -class MetricAggregation(): +class MetricAggregation: """ An aggregation analyzing log information for queries and events. - :attr str interval: (optional) The measurement interval for this metric. Metric + :param str interval: (optional) The measurement interval for this metric. Metric intervals are always 1 day (`1d`). - :attr str event_type: (optional) The event type associated with this metric + :param str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. - :attr List[MetricAggregationResult] results: (optional) Array of metric + :param List[MetricAggregationResult] results: (optional) Array of metric aggregation query results. """ - def __init__(self, - *, - interval: str = None, - event_type: str = None, - results: List['MetricAggregationResult'] = None) -> None: + def __init__( + self, + *, + interval: Optional[str] = None, + event_type: Optional[str] = None, + results: Optional[List['MetricAggregationResult']] = None, + ) -> None: """ Initialize a MetricAggregation object. @@ -8470,14 +9028,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricAggregation': """Initialize a MetricAggregation object from a json dictionary.""" args = {} - if 'interval' in _dict: - args['interval'] = _dict.get('interval') - if 'event_type' in _dict: - args['event_type'] = _dict.get('event_type') - if 'results' in _dict: + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval + if (event_type := _dict.get('event_type')) is not None: + args['event_type'] = event_type + if (results := _dict.get('results')) is not None: args['results'] = [ - MetricAggregationResult.from_dict(v) - for v in _dict.get('results') + MetricAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -8522,26 +9079,28 @@ def __ne__(self, other: 'MetricAggregation') -> bool: return not self == other -class MetricAggregationResult(): +class MetricAggregationResult: """ Aggregation result data for the requested metric. - :attr datetime key_as_string: (optional) Date in string form representing the + :param datetime key_as_string: (optional) Date in string form representing the start of this interval. - :attr int key: (optional) Unix epoch time equivalent of the **key_as_string**, + :param int key: (optional) Unix epoch time equivalent of the **key_as_string**, that represents the start of this interval. - :attr int matching_results: (optional) Number of matching results. - :attr float event_rate: (optional) The number of queries with associated events + :param int matching_results: (optional) Number of matching results. + :param float event_rate: (optional) The number of queries with associated events divided by the total number of queries for the interval. Only returned with **event_rate** metrics. """ - def __init__(self, - *, - key_as_string: datetime = None, - key: int = None, - matching_results: int = None, - event_rate: float = None) -> None: + def __init__( + self, + *, + key_as_string: Optional[datetime] = None, + key: Optional[int] = None, + matching_results: Optional[int] = None, + event_rate: Optional[float] = None, + ) -> None: """ Initialize a MetricAggregationResult object. @@ -8563,15 +9122,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricAggregationResult': """Initialize a MetricAggregationResult object from a json dictionary.""" args = {} - if 'key_as_string' in _dict: - args['key_as_string'] = string_to_datetime( - _dict.get('key_as_string')) - if 'key' in _dict: - args['key'] = _dict.get('key') - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'event_rate' in _dict: - args['event_rate'] = _dict.get('event_rate') + if (key_as_string := _dict.get('key_as_string')) is not None: + args['key_as_string'] = string_to_datetime(key_as_string) + if (key := _dict.get('key')) is not None: + args['key'] = key + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (event_rate := _dict.get('event_rate')) is not None: + args['event_rate'] = event_rate return cls(**args) @classmethod @@ -8612,17 +9170,19 @@ def __ne__(self, other: 'MetricAggregationResult') -> bool: return not self == other -class MetricResponse(): +class MetricResponse: """ The response generated from a call to a **metrics** method. - :attr List[MetricAggregation] aggregations: (optional) Array of metric + :param List[MetricAggregation] aggregations: (optional) Array of metric aggregations. """ - def __init__(self, - *, - aggregations: List['MetricAggregation'] = None) -> None: + def __init__( + self, + *, + aggregations: Optional[List['MetricAggregation']] = None, + ) -> None: """ Initialize a MetricResponse object. @@ -8635,10 +9195,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricResponse': """Initialize a MetricResponse object from a json dictionary.""" args = {} - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - MetricAggregation.from_dict(v) - for v in _dict.get('aggregations') + MetricAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -8679,20 +9238,22 @@ def __ne__(self, other: 'MetricResponse') -> bool: return not self == other -class MetricTokenAggregation(): +class MetricTokenAggregation: """ An aggregation analyzing log information for queries and events. - :attr str event_type: (optional) The event type associated with this metric + :param str event_type: (optional) The event type associated with this metric result. This field, when present, will always be `click`. - :attr List[MetricTokenAggregationResult] results: (optional) Array of results + :param List[MetricTokenAggregationResult] results: (optional) Array of results for the metric token aggregation. """ - def __init__(self, - *, - event_type: str = None, - results: List['MetricTokenAggregationResult'] = None) -> None: + def __init__( + self, + *, + event_type: Optional[str] = None, + results: Optional[List['MetricTokenAggregationResult']] = None, + ) -> None: """ Initialize a MetricTokenAggregation object. @@ -8708,12 +9269,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregation': """Initialize a MetricTokenAggregation object from a json dictionary.""" args = {} - if 'event_type' in _dict: - args['event_type'] = _dict.get('event_type') - if 'results' in _dict: + if (event_type := _dict.get('event_type')) is not None: + args['event_type'] = event_type + if (results := _dict.get('results')) is not None: args['results'] = [ - MetricTokenAggregationResult.from_dict(v) - for v in _dict.get('results') + MetricTokenAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -8756,23 +9316,25 @@ def __ne__(self, other: 'MetricTokenAggregation') -> bool: return not self == other -class MetricTokenAggregationResult(): +class MetricTokenAggregationResult: """ Aggregation result data for the requested metric. - :attr str key: (optional) The content of the **natural_language_query** + :param str key: (optional) The content of the **natural_language_query** parameter used in the query that this result represents. - :attr int matching_results: (optional) Number of matching results. - :attr float event_rate: (optional) The number of queries with associated events + :param int matching_results: (optional) Number of matching results. + :param float event_rate: (optional) The number of queries with associated events divided by the total number of queries currently stored (queries and events are stored in the log for 30 days). """ - def __init__(self, - *, - key: str = None, - matching_results: int = None, - event_rate: float = None) -> None: + def __init__( + self, + *, + key: Optional[str] = None, + matching_results: Optional[int] = None, + event_rate: Optional[float] = None, + ) -> None: """ Initialize a MetricTokenAggregationResult object. @@ -8791,12 +9353,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregationResult': """Initialize a MetricTokenAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'event_rate' in _dict: - args['event_rate'] = _dict.get('event_rate') + if (key := _dict.get('key')) is not None: + args['key'] = key + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (event_rate := _dict.get('event_rate')) is not None: + args['event_rate'] = event_rate return cls(**args) @classmethod @@ -8835,17 +9397,19 @@ def __ne__(self, other: 'MetricTokenAggregationResult') -> bool: return not self == other -class MetricTokenResponse(): +class MetricTokenResponse: """ The response generated from a call to a **metrics** method that evaluates tokens. - :attr List[MetricTokenAggregation] aggregations: (optional) Array of metric + :param List[MetricTokenAggregation] aggregations: (optional) Array of metric token aggregations. """ - def __init__(self, - *, - aggregations: List['MetricTokenAggregation'] = None) -> None: + def __init__( + self, + *, + aggregations: Optional[List['MetricTokenAggregation']] = None, + ) -> None: """ Initialize a MetricTokenResponse object. @@ -8858,10 +9422,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'MetricTokenResponse': """Initialize a MetricTokenResponse object from a json dictionary.""" args = {} - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - MetricTokenAggregation.from_dict(v) - for v in _dict.get('aggregations') + MetricTokenAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -8902,15 +9465,19 @@ def __ne__(self, other: 'MetricTokenResponse') -> bool: return not self == other -class NluEnrichmentConcepts(): +class NluEnrichmentConcepts: """ An object specifiying the concepts enrichment and related parameters. - :attr int limit: (optional) The maximum number of concepts enrichments to extact - from each instance of the specified field. + :param int limit: (optional) The maximum number of concepts enrichments to + extact from each instance of the specified field. """ - def __init__(self, *, limit: int = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a NluEnrichmentConcepts object. @@ -8923,8 +9490,8 @@ def __init__(self, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'NluEnrichmentConcepts': """Initialize a NluEnrichmentConcepts object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -8958,20 +9525,22 @@ def __ne__(self, other: 'NluEnrichmentConcepts') -> bool: return not self == other -class NluEnrichmentEmotion(): +class NluEnrichmentEmotion: """ An object specifying the emotion detection enrichment and related parameters. - :attr bool document: (optional) When `true`, emotion detection is performed on + :param bool document: (optional) When `true`, emotion detection is performed on the entire field. - :attr List[str] targets: (optional) A comma-separated list of target strings + :param List[str] targets: (optional) A comma-separated list of target strings that will have any associated emotions detected. """ - def __init__(self, - *, - document: bool = None, - targets: List[str] = None) -> None: + def __init__( + self, + *, + document: Optional[bool] = None, + targets: Optional[List[str]] = None, + ) -> None: """ Initialize a NluEnrichmentEmotion object. @@ -8987,10 +9556,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEmotion': """Initialize a NluEnrichmentEmotion object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') + if (document := _dict.get('document')) is not None: + args['document'] = document + if (targets := _dict.get('targets')) is not None: + args['targets'] = targets return cls(**args) @classmethod @@ -9026,37 +9595,39 @@ def __ne__(self, other: 'NluEnrichmentEmotion') -> bool: return not self == other -class NluEnrichmentEntities(): +class NluEnrichmentEntities: """ An object speficying the Entities enrichment and related parameters. - :attr bool sentiment: (optional) When `true`, sentiment analysis of entities + :param bool sentiment: (optional) When `true`, sentiment analysis of entities will be performed on the specified field. - :attr bool emotion: (optional) When `true`, emotion detection of entities will + :param bool emotion: (optional) When `true`, emotion detection of entities will be performed on the specified field. - :attr int limit: (optional) The maximum number of entities to extract for each + :param int limit: (optional) The maximum number of entities to extract for each instance of the specified field. - :attr bool mentions: (optional) When `true`, the number of mentions of each + :param bool mentions: (optional) When `true`, the number of mentions of each identified entity is recorded. The default is `false`. - :attr bool mention_types: (optional) When `true`, the types of mentions for each - idetifieid entity is recorded. The default is `false`. - :attr bool sentence_locations: (optional) When `true`, a list of sentence + :param bool mention_types: (optional) When `true`, the types of mentions for + each idetifieid entity is recorded. The default is `false`. + :param bool sentence_locations: (optional) When `true`, a list of sentence locations for each instance of each identified entity is recorded. The default is `false`. - :attr str model: (optional) The enrichement model to use with entity extraction. - May be a custom model provided by Watson Knowledge Studio, or the default public - model `alchemy`. + :param str model: (optional) The enrichement model to use with entity + extraction. May be a custom model provided by Watson Knowledge Studio, or the + default public model `alchemy`. """ - def __init__(self, - *, - sentiment: bool = None, - emotion: bool = None, - limit: int = None, - mentions: bool = None, - mention_types: bool = None, - sentence_locations: bool = None, - model: str = None) -> None: + def __init__( + self, + *, + sentiment: Optional[bool] = None, + emotion: Optional[bool] = None, + limit: Optional[int] = None, + mentions: Optional[bool] = None, + mention_types: Optional[bool] = None, + sentence_locations: Optional[bool] = None, + model: Optional[str] = None, + ) -> None: """ Initialize a NluEnrichmentEntities object. @@ -9089,20 +9660,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEntities': """Initialize a NluEnrichmentEntities object from a json dictionary.""" args = {} - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'mentions' in _dict: - args['mentions'] = _dict.get('mentions') - if 'mention_types' in _dict: - args['mention_types'] = _dict.get('mention_types') - if 'sentence_locations' in _dict: - args['sentence_locations'] = _dict.get('sentence_locations') - if 'model' in _dict: - args['model'] = _dict.get('model') + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = sentiment + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = emotion + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (mentions := _dict.get('mentions')) is not None: + args['mentions'] = mentions + if (mention_types := _dict.get('mention_types')) is not None: + args['mention_types'] = mention_types + if (sentence_locations := _dict.get('sentence_locations')) is not None: + args['sentence_locations'] = sentence_locations + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -9150,38 +9721,40 @@ def __ne__(self, other: 'NluEnrichmentEntities') -> bool: return not self == other -class NluEnrichmentFeatures(): +class NluEnrichmentFeatures: """ Object containing Natural Language Understanding features to be used. - :attr NluEnrichmentKeywords keywords: (optional) An object specifying the + :param NluEnrichmentKeywords keywords: (optional) An object specifying the Keyword enrichment and related parameters. - :attr NluEnrichmentEntities entities: (optional) An object speficying the + :param NluEnrichmentEntities entities: (optional) An object speficying the Entities enrichment and related parameters. - :attr NluEnrichmentSentiment sentiment: (optional) An object specifying the + :param NluEnrichmentSentiment sentiment: (optional) An object specifying the sentiment extraction enrichment and related parameters. - :attr NluEnrichmentEmotion emotion: (optional) An object specifying the emotion + :param NluEnrichmentEmotion emotion: (optional) An object specifying the emotion detection enrichment and related parameters. - :attr dict categories: (optional) An object that indicates the Categories + :param dict categories: (optional) An object that indicates the Categories enrichment will be applied to the specified field. - :attr NluEnrichmentSemanticRoles semantic_roles: (optional) An object + :param NluEnrichmentSemanticRoles semantic_roles: (optional) An object specifiying the semantic roles enrichment and related parameters. - :attr NluEnrichmentRelations relations: (optional) An object specifying the + :param NluEnrichmentRelations relations: (optional) An object specifying the relations enrichment and related parameters. - :attr NluEnrichmentConcepts concepts: (optional) An object specifiying the + :param NluEnrichmentConcepts concepts: (optional) An object specifiying the concepts enrichment and related parameters. """ - def __init__(self, - *, - keywords: 'NluEnrichmentKeywords' = None, - entities: 'NluEnrichmentEntities' = None, - sentiment: 'NluEnrichmentSentiment' = None, - emotion: 'NluEnrichmentEmotion' = None, - categories: dict = None, - semantic_roles: 'NluEnrichmentSemanticRoles' = None, - relations: 'NluEnrichmentRelations' = None, - concepts: 'NluEnrichmentConcepts' = None) -> None: + def __init__( + self, + *, + keywords: Optional['NluEnrichmentKeywords'] = None, + entities: Optional['NluEnrichmentEntities'] = None, + sentiment: Optional['NluEnrichmentSentiment'] = None, + emotion: Optional['NluEnrichmentEmotion'] = None, + categories: Optional[dict] = None, + semantic_roles: Optional['NluEnrichmentSemanticRoles'] = None, + relations: Optional['NluEnrichmentRelations'] = None, + concepts: Optional['NluEnrichmentConcepts'] = None, + ) -> None: """ Initialize a NluEnrichmentFeatures object. @@ -9215,29 +9788,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentFeatures': """Initialize a NluEnrichmentFeatures object from a json dictionary.""" args = {} - if 'keywords' in _dict: - args['keywords'] = NluEnrichmentKeywords.from_dict( - _dict.get('keywords')) - if 'entities' in _dict: - args['entities'] = NluEnrichmentEntities.from_dict( - _dict.get('entities')) - if 'sentiment' in _dict: - args['sentiment'] = NluEnrichmentSentiment.from_dict( - _dict.get('sentiment')) - if 'emotion' in _dict: - args['emotion'] = NluEnrichmentEmotion.from_dict( - _dict.get('emotion')) - if 'categories' in _dict: - args['categories'] = _dict.get('categories') - if 'semantic_roles' in _dict: + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = NluEnrichmentKeywords.from_dict(keywords) + if (entities := _dict.get('entities')) is not None: + args['entities'] = NluEnrichmentEntities.from_dict(entities) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = NluEnrichmentSentiment.from_dict(sentiment) + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = NluEnrichmentEmotion.from_dict(emotion) + if (categories := _dict.get('categories')) is not None: + args['categories'] = categories + if (semantic_roles := _dict.get('semantic_roles')) is not None: args['semantic_roles'] = NluEnrichmentSemanticRoles.from_dict( - _dict.get('semantic_roles')) - if 'relations' in _dict: - args['relations'] = NluEnrichmentRelations.from_dict( - _dict.get('relations')) - if 'concepts' in _dict: - args['concepts'] = NluEnrichmentConcepts.from_dict( - _dict.get('concepts')) + semantic_roles) + if (relations := _dict.get('relations')) is not None: + args['relations'] = NluEnrichmentRelations.from_dict(relations) + if (concepts := _dict.get('concepts')) is not None: + args['concepts'] = NluEnrichmentConcepts.from_dict(concepts) return cls(**args) @classmethod @@ -9306,23 +9873,25 @@ def __ne__(self, other: 'NluEnrichmentFeatures') -> bool: return not self == other -class NluEnrichmentKeywords(): +class NluEnrichmentKeywords: """ An object specifying the Keyword enrichment and related parameters. - :attr bool sentiment: (optional) When `true`, sentiment analysis of keywords + :param bool sentiment: (optional) When `true`, sentiment analysis of keywords will be performed on the specified field. - :attr bool emotion: (optional) When `true`, emotion detection of keywords will + :param bool emotion: (optional) When `true`, emotion detection of keywords will be performed on the specified field. - :attr int limit: (optional) The maximum number of keywords to extract for each + :param int limit: (optional) The maximum number of keywords to extract for each instance of the specified field. """ - def __init__(self, - *, - sentiment: bool = None, - emotion: bool = None, - limit: int = None) -> None: + def __init__( + self, + *, + sentiment: Optional[bool] = None, + emotion: Optional[bool] = None, + limit: Optional[int] = None, + ) -> None: """ Initialize a NluEnrichmentKeywords object. @@ -9341,12 +9910,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentKeywords': """Initialize a NluEnrichmentKeywords object from a json dictionary.""" args = {} - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = sentiment + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = emotion + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -9384,17 +9953,21 @@ def __ne__(self, other: 'NluEnrichmentKeywords') -> bool: return not self == other -class NluEnrichmentRelations(): +class NluEnrichmentRelations: """ An object specifying the relations enrichment and related parameters. - :attr str model: (optional) *For use with `natural_language_understanding` + :param str model: (optional) *For use with `natural_language_understanding` enrichments only.* The enrichement model to use with relationship extraction. May be a custom model provided by Watson Knowledge Studio, the default public model is`en-news`. """ - def __init__(self, *, model: str = None) -> None: + def __init__( + self, + *, + model: Optional[str] = None, + ) -> None: """ Initialize a NluEnrichmentRelations object. @@ -9409,8 +9982,8 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'NluEnrichmentRelations': """Initialize a NluEnrichmentRelations object from a json dictionary.""" args = {} - if 'model' in _dict: - args['model'] = _dict.get('model') + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -9444,23 +10017,25 @@ def __ne__(self, other: 'NluEnrichmentRelations') -> bool: return not self == other -class NluEnrichmentSemanticRoles(): +class NluEnrichmentSemanticRoles: """ An object specifiying the semantic roles enrichment and related parameters. - :attr bool entities: (optional) When `true`, entities are extracted from the + :param bool entities: (optional) When `true`, entities are extracted from the identified sentence parts. - :attr bool keywords: (optional) When `true`, keywords are extracted from the + :param bool keywords: (optional) When `true`, keywords are extracted from the identified sentence parts. - :attr int limit: (optional) The maximum number of semantic roles enrichments to + :param int limit: (optional) The maximum number of semantic roles enrichments to extact from each instance of the specified field. """ - def __init__(self, - *, - entities: bool = None, - keywords: bool = None, - limit: int = None) -> None: + def __init__( + self, + *, + entities: Optional[bool] = None, + keywords: Optional[bool] = None, + limit: Optional[int] = None, + ) -> None: """ Initialize a NluEnrichmentSemanticRoles object. @@ -9479,12 +10054,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSemanticRoles': """Initialize a NluEnrichmentSemanticRoles object from a json dictionary.""" args = {} - if 'entities' in _dict: - args['entities'] = _dict.get('entities') - if 'keywords' in _dict: - args['keywords'] = _dict.get('keywords') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (entities := _dict.get('entities')) is not None: + args['entities'] = entities + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = keywords + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -9522,20 +10097,22 @@ def __ne__(self, other: 'NluEnrichmentSemanticRoles') -> bool: return not self == other -class NluEnrichmentSentiment(): +class NluEnrichmentSentiment: """ An object specifying the sentiment extraction enrichment and related parameters. - :attr bool document: (optional) When `true`, sentiment analysis is performed on + :param bool document: (optional) When `true`, sentiment analysis is performed on the entire field. - :attr List[str] targets: (optional) A comma-separated list of target strings + :param List[str] targets: (optional) A comma-separated list of target strings that will have any associated sentiment analyzed. """ - def __init__(self, - *, - document: bool = None, - targets: List[str] = None) -> None: + def __init__( + self, + *, + document: Optional[bool] = None, + targets: Optional[List[str]] = None, + ) -> None: """ Initialize a NluEnrichmentSentiment object. @@ -9551,10 +10128,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSentiment': """Initialize a NluEnrichmentSentiment object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') + if (document := _dict.get('document')) is not None: + args['document'] = document + if (targets := _dict.get('targets')) is not None: + args['targets'] = targets return cls(**args) @classmethod @@ -9590,11 +10167,11 @@ def __ne__(self, other: 'NluEnrichmentSentiment') -> bool: return not self == other -class NormalizationOperation(): +class NormalizationOperation: """ Object containing normalization operations. - :attr str operation: (optional) Identifies what type of operation to perform. + :param str operation: (optional) Identifies what type of operation to perform. **copy** - Copies the value of the **source_field** to the **destination_field** field. If the **destination_field** already exists, then the value of the **source_field** overwrites the original value of the **destination_field**. @@ -9619,15 +10196,18 @@ class NormalizationOperation(): this operation because _remove_nulls_ operates on the entire ingested document. Typically, **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it can be time-expensive). - :attr str source_field: (optional) The source field for the operation. - :attr str destination_field: (optional) The destination field for the operation. + :param str source_field: (optional) The source field for the operation. + :param str destination_field: (optional) The destination field for the + operation. """ - def __init__(self, - *, - operation: str = None, - source_field: str = None, - destination_field: str = None) -> None: + def __init__( + self, + *, + operation: Optional[str] = None, + source_field: Optional[str] = None, + destination_field: Optional[str] = None, + ) -> None: """ Initialize a NormalizationOperation object. @@ -9670,12 +10250,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'NormalizationOperation': """Initialize a NormalizationOperation object from a json dictionary.""" args = {} - if 'operation' in _dict: - args['operation'] = _dict.get('operation') - if 'source_field' in _dict: - args['source_field'] = _dict.get('source_field') - if 'destination_field' in _dict: - args['destination_field'] = _dict.get('destination_field') + if (operation := _dict.get('operation')) is not None: + args['operation'] = operation + if (source_field := _dict.get('source_field')) is not None: + args['source_field'] = source_field + if (destination_field := _dict.get('destination_field')) is not None: + args['destination_field'] = destination_field return cls(**args) @classmethod @@ -9740,6 +10320,7 @@ class OperationEnum(str, Enum): **remove_nulls** is invoked as the last normalization operation (if it is invoked at all, it can be time-expensive). """ + COPY = 'copy' MOVE = 'move' MERGE = 'merge' @@ -9747,11 +10328,11 @@ class OperationEnum(str, Enum): REMOVE_NULLS = 'remove_nulls' -class Notice(): +class Notice: """ A notice produced for the collection. - :attr str notice_id: (optional) Identifies the notice. Many notices might have + :param str notice_id: (optional) Identifies the notice. Many notices might have the same ID. This field exists so that user applications can programmatically identify a notice and take automatic corrective action. Typical notice IDs include: `index_failed`, `index_failed_too_many_requests`, @@ -9765,28 +10346,30 @@ class Notice(): `smart_document_understanding_page_error`, `smart_document_understanding_page_warning`. **Note:** This is not a complete list; other values might be returned. - :attr datetime created: (optional) The creation date of the collection in the + :param datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str document_id: (optional) Unique identifier of the document. - :attr str query_id: (optional) Unique identifier of the query used for relevance - training. - :attr str severity: (optional) Severity level of the notice. - :attr str step: (optional) Ingestion or training step in which the notice + :param str document_id: (optional) Unique identifier of the document. + :param str query_id: (optional) Unique identifier of the query used for + relevance training. + :param str severity: (optional) Severity level of the notice. + :param str step: (optional) Ingestion or training step in which the notice occurred. Typical step values include: `smartDocumentUnderstanding`, `ingestion`, `indexing`, `convert`. **Note:** This is not a complete list; other values might be returned. - :attr str description: (optional) The description of the notice. + :param str description: (optional) The description of the notice. """ - def __init__(self, - *, - notice_id: str = None, - created: datetime = None, - document_id: str = None, - query_id: str = None, - severity: str = None, - step: str = None, - description: str = None) -> None: + def __init__( + self, + *, + notice_id: Optional[str] = None, + created: Optional[datetime] = None, + document_id: Optional[str] = None, + query_id: Optional[str] = None, + severity: Optional[str] = None, + step: Optional[str] = None, + description: Optional[str] = None, + ) -> None: """ Initialize a Notice object. @@ -9803,20 +10386,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} - if 'notice_id' in _dict: - args['notice_id'] = _dict.get('notice_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'severity' in _dict: - args['severity'] = _dict.get('severity') - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'description' in _dict: - args['description'] = _dict.get('description') + if (notice_id := _dict.get('notice_id')) is not None: + args['notice_id'] = notice_id + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (severity := _dict.get('severity')) is not None: + args['severity'] = severity + if (step := _dict.get('step')) is not None: + args['step'] = step + if (description := _dict.get('description')) is not None: + args['description'] = description return cls(**args) @classmethod @@ -9868,18 +10451,24 @@ class SeverityEnum(str, Enum): """ Severity level of the notice. """ + WARNING = 'warning' ERROR = 'error' -class PdfHeadingDetection(): +class PdfHeadingDetection: """ Object containing heading detection conversion settings for PDF documents. - :attr List[FontSetting] fonts: (optional) Array of font matching configurations. + :param List[FontSetting] fonts: (optional) Array of font matching + configurations. """ - def __init__(self, *, fonts: List['FontSetting'] = None) -> None: + def __init__( + self, + *, + fonts: Optional[List['FontSetting']] = None, + ) -> None: """ Initialize a PdfHeadingDetection object. @@ -9892,10 +10481,8 @@ def __init__(self, *, fonts: List['FontSetting'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'PdfHeadingDetection': """Initialize a PdfHeadingDetection object from a json dictionary.""" args = {} - if 'fonts' in _dict: - args['fonts'] = [ - FontSetting.from_dict(v) for v in _dict.get('fonts') - ] + if (fonts := _dict.get('fonts')) is not None: + args['fonts'] = [FontSetting.from_dict(v) for v in fonts] return cls(**args) @classmethod @@ -9935,15 +10522,19 @@ def __ne__(self, other: 'PdfHeadingDetection') -> bool: return not self == other -class PdfSettings(): +class PdfSettings: """ A list of PDF conversion settings. - :attr PdfHeadingDetection heading: (optional) Object containing heading + :param PdfHeadingDetection heading: (optional) Object containing heading detection conversion settings for PDF documents. """ - def __init__(self, *, heading: 'PdfHeadingDetection' = None) -> None: + def __init__( + self, + *, + heading: Optional['PdfHeadingDetection'] = None, + ) -> None: """ Initialize a PdfSettings object. @@ -9956,9 +10547,8 @@ def __init__(self, *, heading: 'PdfHeadingDetection' = None) -> None: def from_dict(cls, _dict: Dict) -> 'PdfSettings': """Initialize a PdfSettings object from a json dictionary.""" args = {} - if 'heading' in _dict: - args['heading'] = PdfHeadingDetection.from_dict( - _dict.get('heading')) + if (heading := _dict.get('heading')) is not None: + args['heading'] = PdfHeadingDetection.from_dict(heading) return cls(**args) @classmethod @@ -9995,15 +10585,18 @@ def __ne__(self, other: 'PdfSettings') -> bool: return not self == other -class QueryAggregation(): +class QueryAggregation: """ An aggregation produced by Discovery to analyze the input provided. - :attr str type: The type of aggregation command used. For example: term, filter, - max, min, etc. + :param str type: The type of aggregation command used. For example: term, + filter, max, min, etc. """ - def __init__(self, type: str) -> None: + def __init__( + self, + type: str, + ) -> None: """ Initialize a QueryAggregation object. @@ -10019,8 +10612,8 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregation': if disc_class != cls: return disc_class.from_dict(_dict) args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryAggregation JSON' @@ -10086,22 +10679,24 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class QueryHistogramAggregationResult(): +class QueryHistogramAggregationResult: """ Histogram numeric interval result. - :attr int key: The value of the upper bound for the numeric segment. - :attr int matching_results: Number of documents with the specified key as the + :param int key: The value of the upper bound for the numeric segment. + :param int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of + :param List[QueryAggregation] aggregations: (optional) An array of sub-aggregations. """ - def __init__(self, - key: int, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + key: int, + matching_results: int, + *, + aggregations: Optional[List['QueryAggregation']] = None, + ) -> None: """ Initialize a QueryHistogramAggregationResult object. @@ -10119,21 +10714,21 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' ) - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -10179,28 +10774,30 @@ def __ne__(self, other: 'QueryHistogramAggregationResult') -> bool: return not self == other -class QueryNoticesResponse(): +class QueryNoticesResponse: """ Object containing notice query results. - :attr int matching_results: (optional) The number of matching results. - :attr List[QueryNoticesResult] results: (optional) Array of document results + :param int matching_results: (optional) The number of matching results. + :param List[QueryNoticesResult] results: (optional) Array of document results that match the query. - :attr List[QueryAggregation] aggregations: (optional) Array of aggregation + :param List[QueryAggregation] aggregations: (optional) Array of aggregation results that match the query. - :attr List[QueryPassages] passages: (optional) Array of passage results that + :param List[QueryPassages] passages: (optional) Array of passage results that match the query. - :attr int duplicates_removed: (optional) The number of duplicates removed from + :param int duplicates_removed: (optional) The number of duplicates removed from this notices query. """ - def __init__(self, - *, - matching_results: int = None, - results: List['QueryNoticesResult'] = None, - aggregations: List['QueryAggregation'] = None, - passages: List['QueryPassages'] = None, - duplicates_removed: int = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + results: Optional[List['QueryNoticesResult']] = None, + aggregations: Optional[List['QueryAggregation']] = None, + passages: Optional[List['QueryPassages']] = None, + duplicates_removed: Optional[int] = None, + ) -> None: """ Initialize a QueryNoticesResponse object. @@ -10224,22 +10821,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: - args['results'] = [ - QueryNoticesResult.from_dict(v) for v in _dict.get('results') - ] - if 'aggregations' in _dict: + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (results := _dict.get('results')) is not None: + args['results'] = [QueryNoticesResult.from_dict(v) for v in results] + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') - ] - if 'passages' in _dict: - args['passages'] = [ - QueryPassages.from_dict(v) for v in _dict.get('passages') + QueryAggregation.from_dict(v) for v in aggregations ] - if 'duplicates_removed' in _dict: - args['duplicates_removed'] = _dict.get('duplicates_removed') + if (passages := _dict.get('passages')) is not None: + args['passages'] = [QueryPassages.from_dict(v) for v in passages] + if (duplicates_removed := _dict.get('duplicates_removed')) is not None: + args['duplicates_removed'] = duplicates_removed return cls(**args) @classmethod @@ -10302,23 +10895,23 @@ def __ne__(self, other: 'QueryNoticesResponse') -> bool: return not self == other -class QueryNoticesResult(): +class QueryNoticesResult: """ Query result object. - :attr str id: (optional) The unique identifier of the document. - :attr dict metadata: (optional) Metadata of the document. - :attr str collection_id: (optional) The collection ID of the collection + :param str id: (optional) The unique identifier of the document. + :param dict metadata: (optional) Metadata of the document. + :param str collection_id: (optional) The collection ID of the collection containing the document for this result. - :attr QueryResultMetadata result_metadata: (optional) Metadata of a query + :param QueryResultMetadata result_metadata: (optional) Metadata of a query result. - :attr int code: (optional) The internal status code returned by the ingestion + :param int code: (optional) The internal status code returned by the ingestion subsystem indicating the overall result of ingesting the source document. - :attr str filename: (optional) Name of the original source file (if available). - :attr str file_type: (optional) The type of the original source file. - :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted - as a hexadecimal string). - :attr List[Notice] notices: (optional) Array of notices for the document. + :param str filename: (optional) Name of the original source file (if available). + :param str file_type: (optional) The type of the original source file. + :param str sha1: (optional) The SHA-1 hash of the original source file + (formatted as a hexadecimal string). + :param List[Notice] notices: (optional) Array of notices for the document. """ # The set of defined properties for the class @@ -10327,18 +10920,20 @@ class QueryNoticesResult(): 'filename', 'file_type', 'sha1', 'notices' ]) - def __init__(self, - *, - id: str = None, - metadata: dict = None, - collection_id: str = None, - result_metadata: 'QueryResultMetadata' = None, - code: int = None, - filename: str = None, - file_type: str = None, - sha1: str = None, - notices: List['Notice'] = None, - **kwargs) -> None: + def __init__( + self, + *, + id: Optional[str] = None, + metadata: Optional[dict] = None, + collection_id: Optional[str] = None, + result_metadata: Optional['QueryResultMetadata'] = None, + code: Optional[int] = None, + filename: Optional[str] = None, + file_type: Optional[str] = None, + sha1: Optional[str] = None, + notices: Optional[List['Notice']] = None, + **kwargs, + ) -> None: """ Initialize a QueryNoticesResult object. @@ -10375,27 +10970,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNoticesResult': """Initialize a QueryNoticesResult object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'result_metadata' in _dict: + if (id := _dict.get('id')) is not None: + args['id'] = id + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (result_metadata := _dict.get('result_metadata')) is not None: args['result_metadata'] = QueryResultMetadata.from_dict( - _dict.get('result_metadata')) - if 'code' in _dict: - args['code'] = _dict.get('code') - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - if 'file_type' in _dict: - args['file_type'] = _dict.get('file_type') - if 'sha1' in _dict: - args['sha1'] = _dict.get('sha1') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] + result_metadata) + if (code := _dict.get('code')) is not None: + args['code'] = code + if (filename := _dict.get('filename')) is not None: + args['filename'] = filename + if (file_type := _dict.get('file_type')) is not None: + args['file_type'] = file_type + if (sha1 := _dict.get('sha1')) is not None: + args['sha1'] = sha1 + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -10488,37 +11081,40 @@ class FileTypeEnum(str, Enum): """ The type of the original source file. """ + PDF = 'pdf' HTML = 'html' WORD = 'word' JSON = 'json' -class QueryPassages(): +class QueryPassages: """ A passage query result. - :attr str document_id: (optional) The unique identifier of the document from + :param str document_id: (optional) The unique identifier of the document from which the passage has been extracted. - :attr float passage_score: (optional) The confidence score of the passages's + :param float passage_score: (optional) The confidence score of the passages's analysis. A higher score indicates greater confidence. - :attr str passage_text: (optional) The content of the extracted passage. - :attr int start_offset: (optional) The position of the first character of the + :param str passage_text: (optional) The content of the extracted passage. + :param int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :attr int end_offset: (optional) The position of the last character of the + :param int end_offset: (optional) The position of the last character of the extracted passage in the originating field. - :attr str field: (optional) The label of the field from which the passage has + :param str field: (optional) The label of the field from which the passage has been extracted. """ - def __init__(self, - *, - document_id: str = None, - passage_score: float = None, - passage_text: str = None, - start_offset: int = None, - end_offset: int = None, - field: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + passage_score: Optional[float] = None, + passage_text: Optional[str] = None, + start_offset: Optional[int] = None, + end_offset: Optional[int] = None, + field: Optional[str] = None, + ) -> None: """ Initialize a QueryPassages object. @@ -10545,18 +11141,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryPassages': """Initialize a QueryPassages object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'passage_score' in _dict: - args['passage_score'] = _dict.get('passage_score') - if 'passage_text' in _dict: - args['passage_text'] = _dict.get('passage_text') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'field' in _dict: - args['field'] = _dict.get('field') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (passage_score := _dict.get('passage_score')) is not None: + args['passage_score'] = passage_score + if (passage_text := _dict.get('passage_text')) is not None: + args['passage_text'] = passage_text + if (start_offset := _dict.get('start_offset')) is not None: + args['start_offset'] = start_offset + if (end_offset := _dict.get('end_offset')) is not None: + args['end_offset'] = end_offset + if (field := _dict.get('field')) is not None: + args['field'] = field return cls(**args) @classmethod @@ -10600,40 +11196,42 @@ def __ne__(self, other: 'QueryPassages') -> bool: return not self == other -class QueryResponse(): +class QueryResponse: """ A response containing the documents and aggregations for the query. - :attr int matching_results: (optional) The number of matching results for the + :param int matching_results: (optional) The number of matching results for the query. - :attr List[QueryResult] results: (optional) Array of document results for the + :param List[QueryResult] results: (optional) Array of document results for the query. - :attr List[QueryAggregation] aggregations: (optional) Array of aggregation + :param List[QueryAggregation] aggregations: (optional) Array of aggregation results for the query. - :attr List[QueryPassages] passages: (optional) Array of passage results for the + :param List[QueryPassages] passages: (optional) Array of passage results for the query. - :attr int duplicates_removed: (optional) The number of duplicate results + :param int duplicates_removed: (optional) The number of duplicate results removed. - :attr str session_token: (optional) The session token for this query. The + :param str session_token: (optional) The session token for this query. The session token can be used to add events associated with this query to the query and event log. **Important:** Session tokens are case sensitive. - :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval - type information. - :attr str suggested_query: (optional) The suggestions for a misspelled natural + :param RetrievalDetails retrieval_details: (optional) An object contain + retrieval type information. + :param str suggested_query: (optional) The suggestions for a misspelled natural language query. """ - def __init__(self, - *, - matching_results: int = None, - results: List['QueryResult'] = None, - aggregations: List['QueryAggregation'] = None, - passages: List['QueryPassages'] = None, - duplicates_removed: int = None, - session_token: str = None, - retrieval_details: 'RetrievalDetails' = None, - suggested_query: str = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + results: Optional[List['QueryResult']] = None, + aggregations: Optional[List['QueryAggregation']] = None, + passages: Optional[List['QueryPassages']] = None, + duplicates_removed: Optional[int] = None, + session_token: Optional[str] = None, + retrieval_details: Optional['RetrievalDetails'] = None, + suggested_query: Optional[str] = None, + ) -> None: """ Initialize a QueryResponse object. @@ -10669,29 +11267,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResponse': """Initialize a QueryResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: - args['results'] = [ - QueryResult.from_dict(v) for v in _dict.get('results') - ] - if 'aggregations' in _dict: + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (results := _dict.get('results')) is not None: + args['results'] = [QueryResult.from_dict(v) for v in results] + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') - ] - if 'passages' in _dict: - args['passages'] = [ - QueryPassages.from_dict(v) for v in _dict.get('passages') + QueryAggregation.from_dict(v) for v in aggregations ] - if 'duplicates_removed' in _dict: - args['duplicates_removed'] = _dict.get('duplicates_removed') - if 'session_token' in _dict: - args['session_token'] = _dict.get('session_token') - if 'retrieval_details' in _dict: + if (passages := _dict.get('passages')) is not None: + args['passages'] = [QueryPassages.from_dict(v) for v in passages] + if (duplicates_removed := _dict.get('duplicates_removed')) is not None: + args['duplicates_removed'] = duplicates_removed + if (session_token := _dict.get('session_token')) is not None: + args['session_token'] = session_token + if (retrieval_details := _dict.get('retrieval_details')) is not None: args['retrieval_details'] = RetrievalDetails.from_dict( - _dict.get('retrieval_details')) - if 'suggested_query' in _dict: - args['suggested_query'] = _dict.get('suggested_query') + retrieval_details) + if (suggested_query := _dict.get('suggested_query')) is not None: + args['suggested_query'] = suggested_query return cls(**args) @classmethod @@ -10765,15 +11359,15 @@ def __ne__(self, other: 'QueryResponse') -> bool: return not self == other -class QueryResult(): +class QueryResult: """ Query result object. - :attr str id: (optional) The unique identifier of the document. - :attr dict metadata: (optional) Metadata of the document. - :attr str collection_id: (optional) The collection ID of the collection + :param str id: (optional) The unique identifier of the document. + :param dict metadata: (optional) Metadata of the document. + :param str collection_id: (optional) The collection ID of the collection containing the document for this result. - :attr QueryResultMetadata result_metadata: (optional) Metadata of a query + :param QueryResultMetadata result_metadata: (optional) Metadata of a query result. """ @@ -10781,13 +11375,15 @@ class QueryResult(): _properties = frozenset( ['id', 'metadata', 'collection_id', 'result_metadata']) - def __init__(self, - *, - id: str = None, - metadata: dict = None, - collection_id: str = None, - result_metadata: 'QueryResultMetadata' = None, - **kwargs) -> None: + def __init__( + self, + *, + id: Optional[str] = None, + metadata: Optional[dict] = None, + collection_id: Optional[str] = None, + result_metadata: Optional['QueryResultMetadata'] = None, + **kwargs, + ) -> None: """ Initialize a QueryResult object. @@ -10810,15 +11406,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResult': """Initialize a QueryResult object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'result_metadata' in _dict: + if (id := _dict.get('id')) is not None: + args['id'] = id + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (result_metadata := _dict.get('result_metadata')) is not None: args['result_metadata'] = QueryResultMetadata.from_dict( - _dict.get('result_metadata')) + result_metadata) args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -10889,21 +11485,26 @@ def __ne__(self, other: 'QueryResult') -> bool: return not self == other -class QueryResultMetadata(): +class QueryResultMetadata: """ Metadata of a query result. - :attr float score: An unbounded measure of the relevance of a particular result, - dependent on the query and matching document. A higher score indicates a greater - match to the query parameters. - :attr float confidence: (optional) The confidence score for the given result. + :param float score: An unbounded measure of the relevance of a particular + result, dependent on the query and matching document. A higher score indicates a + greater match to the query parameters. + :param float confidence: (optional) The confidence score for the given result. Calculated based on how relevant the result is estimated to be. confidence can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model specified in the `document_retrieval_strategy` field of the result set. """ - def __init__(self, score: float, *, confidence: float = None) -> None: + def __init__( + self, + score: float, + *, + confidence: Optional[float] = None, + ) -> None: """ Initialize a QueryResultMetadata object. @@ -10924,14 +11525,14 @@ def __init__(self, score: float, *, confidence: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} - if 'score' in _dict: - args['score'] = _dict.get('score') + if (score := _dict.get('score')) is not None: + args['score'] = score else: raise ValueError( 'Required property \'score\' not present in QueryResultMetadata JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -10967,31 +11568,34 @@ def __ne__(self, other: 'QueryResultMetadata') -> bool: return not self == other -class QueryTermAggregationResult(): +class QueryTermAggregationResult: """ Top value result for the term aggregation. - :attr str key: Value of the field with a non-zero frequency in the document set. - :attr int matching_results: Number of documents that contain the 'key'. - :attr float relevancy: (optional) The relevancy for this term. - :attr int total_matching_documents: (optional) The number of documents which + :param str key: Value of the field with a non-zero frequency in the document + set. + :param int matching_results: Number of documents that contain the 'key'. + :param float relevancy: (optional) The relevancy for this term. + :param int total_matching_documents: (optional) The number of documents which have the term as the value of specified field in the whole set of documents in this collection. Returned only when the `relevancy` parameter is set to `true`. - :attr int estimated_matching_documents: (optional) The estimated number of + :param int estimated_matching_documents: (optional) The estimated number of documents which would match the query and also meet the condition. Returned only when the `relevancy` parameter is set to `true`. - :attr List[QueryAggregation] aggregations: (optional) An array of + :param List[QueryAggregation] aggregations: (optional) An array of sub-aggregations. """ - def __init__(self, - key: str, - matching_results: int, - *, - relevancy: float = None, - total_matching_documents: int = None, - estimated_matching_documents: int = None, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + key: str, + matching_results: int, + *, + relevancy: Optional[float] = None, + total_matching_documents: Optional[int] = None, + estimated_matching_documents: Optional[int] = None, + aggregations: Optional[List['QueryAggregation']] = None, + ) -> None: """ Initialize a QueryTermAggregationResult object. @@ -11020,29 +11624,29 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': """Initialize a QueryTermAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryTermAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' ) - if 'relevancy' in _dict: - args['relevancy'] = _dict.get('relevancy') - if 'total_matching_documents' in _dict: - args['total_matching_documents'] = _dict.get( - 'total_matching_documents') - if 'estimated_matching_documents' in _dict: - args['estimated_matching_documents'] = _dict.get( - 'estimated_matching_documents') - if 'aggregations' in _dict: + if (relevancy := _dict.get('relevancy')) is not None: + args['relevancy'] = relevancy + if (total_matching_documents := + _dict.get('total_matching_documents')) is not None: + args['total_matching_documents'] = total_matching_documents + if (estimated_matching_documents := + _dict.get('estimated_matching_documents')) is not None: + args['estimated_matching_documents'] = estimated_matching_documents + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -11097,26 +11701,28 @@ def __ne__(self, other: 'QueryTermAggregationResult') -> bool: return not self == other -class QueryTimesliceAggregationResult(): +class QueryTimesliceAggregationResult: """ A timeslice interval segment. - :attr str key_as_string: String date value of the upper bound for the timeslice + :param str key_as_string: String date value of the upper bound for the timeslice interval in ISO-8601 format. - :attr int key: Numeric date value of the upper bound for the timeslice interval + :param int key: Numeric date value of the upper bound for the timeslice interval in UNIX milliseconds since epoch. - :attr int matching_results: Number of documents with the specified key as the + :param int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of + :param List[QueryAggregation] aggregations: (optional) An array of sub-aggregations. """ - def __init__(self, - key_as_string: str, - key: int, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + key_as_string: str, + key: int, + matching_results: int, + *, + aggregations: Optional[List['QueryAggregation']] = None, + ) -> None: """ Initialize a QueryTimesliceAggregationResult object. @@ -11138,27 +11744,27 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" args = {} - if 'key_as_string' in _dict: - args['key_as_string'] = _dict.get('key_as_string') + if (key_as_string := _dict.get('key_as_string')) is not None: + args['key_as_string'] = key_as_string else: raise ValueError( 'Required property \'key_as_string\' not present in QueryTimesliceAggregationResult JSON' ) - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryTimesliceAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' ) - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -11206,18 +11812,20 @@ def __ne__(self, other: 'QueryTimesliceAggregationResult') -> bool: return not self == other -class QueryTopHitsAggregationResult(): +class QueryTopHitsAggregationResult: """ A query response that contains the matching documents for the preceding aggregations. - :attr int matching_results: Number of matching results. - :attr List[dict] hits: (optional) An array of the document results. + :param int matching_results: Number of matching results. + :param List[dict] hits: (optional) An array of the document results. """ - def __init__(self, - matching_results: int, - *, - hits: List[dict] = None) -> None: + def __init__( + self, + matching_results: int, + *, + hits: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTopHitsAggregationResult object. @@ -11231,14 +11839,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTopHitsAggregationResult JSON' ) - if 'hits' in _dict: - args['hits'] = _dict.get('hits') + if (hits := _dict.get('hits')) is not None: + args['hits'] = hits return cls(**args) @classmethod @@ -11275,11 +11883,11 @@ def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: return not self == other -class RetrievalDetails(): +class RetrievalDetails: """ An object contain retrieval type information. - :attr str document_retrieval_strategy: (optional) Indentifies the document + :param str document_retrieval_strategy: (optional) Indentifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. `continuous_relevancy_training` indicates that the results were returned using @@ -11290,7 +11898,11 @@ class RetrievalDetails(): listed as `untrained`. """ - def __init__(self, *, document_retrieval_strategy: str = None) -> None: + def __init__( + self, + *, + document_retrieval_strategy: Optional[str] = None, + ) -> None: """ Initialize a RetrievalDetails object. @@ -11311,9 +11923,9 @@ def __init__(self, *, document_retrieval_strategy: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': """Initialize a RetrievalDetails object from a json dictionary.""" args = {} - if 'document_retrieval_strategy' in _dict: - args['document_retrieval_strategy'] = _dict.get( - 'document_retrieval_strategy') + if (document_retrieval_strategy := + _dict.get('document_retrieval_strategy')) is not None: + args['document_retrieval_strategy'] = document_retrieval_strategy return cls(**args) @classmethod @@ -11360,45 +11972,48 @@ class DocumentRetrievalStrategyEnum(str, Enum): model is not used to return results, the **document_retrieval_strategy** will be listed as `untrained`. """ + UNTRAINED = 'untrained' RELEVANCY_TRAINING = 'relevancy_training' CONTINUOUS_RELEVANCY_TRAINING = 'continuous_relevancy_training' -class SduStatus(): +class SduStatus: """ Object containing smart document understanding information for this collection. - :attr bool enabled: (optional) When `true`, smart document understanding + :param bool enabled: (optional) When `true`, smart document understanding conversion is enabled for this collection. All collections created with a version date after `2019-04-30` have smart document understanding enabled. If `false`, documents added to the collection are converted using the **conversion** settings specified in the configuration associated with the collection. - :attr int total_annotated_pages: (optional) The total number of pages annotated + :param int total_annotated_pages: (optional) The total number of pages annotated using smart document understanding in this collection. - :attr int total_pages: (optional) The current number of pages that can be used + :param int total_pages: (optional) The current number of pages that can be used for training smart document understanding. The `total_pages` number is calculated as the total number of pages identified from the documents listed in the **total_documents** field. - :attr int total_documents: (optional) The total number of documents in this + :param int total_documents: (optional) The total number of documents in this collection that can be used to train smart document understanding. For **lite** plan collections, the maximum is the first 20 uploaded documents (not including HTML or JSON documents). For other plans, the maximum is the first 40 uploaded documents (not including HTML or JSON documents). When the maximum is reached, additional documents uploaded to the collection are not considered for training smart document understanding. - :attr SduStatusCustomFields custom_fields: (optional) Information about custom + :param SduStatusCustomFields custom_fields: (optional) Information about custom smart document understanding fields that exist in this collection. """ - def __init__(self, - *, - enabled: bool = None, - total_annotated_pages: int = None, - total_pages: int = None, - total_documents: int = None, - custom_fields: 'SduStatusCustomFields' = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + total_annotated_pages: Optional[int] = None, + total_pages: Optional[int] = None, + total_documents: Optional[int] = None, + custom_fields: Optional['SduStatusCustomFields'] = None, + ) -> None: """ Initialize a SduStatus object. @@ -11434,17 +12049,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SduStatus': """Initialize a SduStatus object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'total_annotated_pages' in _dict: - args['total_annotated_pages'] = _dict.get('total_annotated_pages') - if 'total_pages' in _dict: - args['total_pages'] = _dict.get('total_pages') - if 'total_documents' in _dict: - args['total_documents'] = _dict.get('total_documents') - if 'custom_fields' in _dict: + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (total_annotated_pages := + _dict.get('total_annotated_pages')) is not None: + args['total_annotated_pages'] = total_annotated_pages + if (total_pages := _dict.get('total_pages')) is not None: + args['total_pages'] = total_pages + if (total_documents := _dict.get('total_documents')) is not None: + args['total_documents'] = total_documents + if (custom_fields := _dict.get('custom_fields')) is not None: args['custom_fields'] = SduStatusCustomFields.from_dict( - _dict.get('custom_fields')) + custom_fields) return cls(**args) @classmethod @@ -11491,21 +12107,23 @@ def __ne__(self, other: 'SduStatus') -> bool: return not self == other -class SduStatusCustomFields(): +class SduStatusCustomFields: """ Information about custom smart document understanding fields that exist in this collection. - :attr int defined: (optional) The number of custom fields defined for this + :param int defined: (optional) The number of custom fields defined for this collection. - :attr int maximum_allowed: (optional) The maximum number of custom fields that + :param int maximum_allowed: (optional) The maximum number of custom fields that are allowed in this collection. """ - def __init__(self, - *, - defined: int = None, - maximum_allowed: int = None) -> None: + def __init__( + self, + *, + defined: Optional[int] = None, + maximum_allowed: Optional[int] = None, + ) -> None: """ Initialize a SduStatusCustomFields object. @@ -11521,10 +12139,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SduStatusCustomFields': """Initialize a SduStatusCustomFields object from a json dictionary.""" args = {} - if 'defined' in _dict: - args['defined'] = _dict.get('defined') - if 'maximum_allowed' in _dict: - args['maximum_allowed'] = _dict.get('maximum_allowed') + if (defined := _dict.get('defined')) is not None: + args['defined'] = defined + if (maximum_allowed := _dict.get('maximum_allowed')) is not None: + args['maximum_allowed'] = maximum_allowed return cls(**args) @classmethod @@ -11561,26 +12179,28 @@ def __ne__(self, other: 'SduStatusCustomFields') -> bool: return not self == other -class SearchStatus(): +class SearchStatus: """ Information about the Continuous Relevancy Training for this environment. - :attr str scope: (optional) Current scope of the training. Always returned as + :param str scope: (optional) Current scope of the training. Always returned as `environment`. - :attr str status: (optional) The current status of Continuous Relevancy Training - for this environment. - :attr str status_description: (optional) Long description of the current + :param str status: (optional) The current status of Continuous Relevancy + Training for this environment. + :param str status_description: (optional) Long description of the current Continuous Relevancy Training status. - :attr date last_trained: (optional) The date stamp of the most recent completed + :param date last_trained: (optional) The date stamp of the most recent completed training for this environment. """ - def __init__(self, - *, - scope: str = None, - status: str = None, - status_description: str = None, - last_trained: date = None) -> None: + def __init__( + self, + *, + scope: Optional[str] = None, + status: Optional[str] = None, + status_description: Optional[str] = None, + last_trained: Optional[date] = None, + ) -> None: """ Initialize a SearchStatus object. @@ -11602,14 +12222,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SearchStatus': """Initialize a SearchStatus object from a json dictionary.""" args = {} - if 'scope' in _dict: - args['scope'] = _dict.get('scope') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'last_trained' in _dict: - args['last_trained'] = string_to_date(_dict.get('last_trained')) + if (scope := _dict.get('scope')) is not None: + args['scope'] = scope + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (last_trained := _dict.get('last_trained')) is not None: + args['last_trained'] = string_to_date(last_trained) return cls(**args) @classmethod @@ -11654,6 +12274,7 @@ class StatusEnum(str, Enum): """ The current status of Continuous Relevancy Training for this environment. """ + NO_DATA = 'NO_DATA' INSUFFICENT_DATA = 'INSUFFICENT_DATA' TRAINING = 'TRAINING' @@ -11661,18 +12282,18 @@ class StatusEnum(str, Enum): NOT_APPLICABLE = 'NOT_APPLICABLE' -class SegmentSettings(): +class SegmentSettings: """ A list of Document Segmentation settings. - :attr bool enabled: (optional) Enables/disables the Document Segmentation + :param bool enabled: (optional) Enables/disables the Document Segmentation feature. - :attr List[str] selector_tags: (optional) Defines the heading level that splits + :param List[str] selector_tags: (optional) Defines the heading level that splits into document segments. Valid values are h1, h2, h3, h4, h5, h6. The content of the header field that the segmentation splits at is used as the **title** field for that segmented result. Only valid if used with a collection that has **enabled** set to `false` in the **smart_document_understanding** object. - :attr List[str] annotated_fields: (optional) Defines the annotated smart + :param List[str] annotated_fields: (optional) Defines the annotated smart document understanding fields that the document is split on. The content of the annotated field that the segmentation splits at is used as the **title** field for that segmented result. For example, if the field `sub-title` is specified, @@ -11684,11 +12305,13 @@ class SegmentSettings(): `true` in the **smart_document_understanding** object. """ - def __init__(self, - *, - enabled: bool = None, - selector_tags: List[str] = None, - annotated_fields: List[str] = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + selector_tags: Optional[List[str]] = None, + annotated_fields: Optional[List[str]] = None, + ) -> None: """ Initialize a SegmentSettings object. @@ -11720,12 +12343,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SegmentSettings': """Initialize a SegmentSettings object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'selector_tags' in _dict: - args['selector_tags'] = _dict.get('selector_tags') - if 'annotated_fields' in _dict: - args['annotated_fields'] = _dict.get('annotated_fields') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (selector_tags := _dict.get('selector_tags')) is not None: + args['selector_tags'] = selector_tags + if (annotated_fields := _dict.get('annotated_fields')) is not None: + args['annotated_fields'] = annotated_fields return cls(**args) @classmethod @@ -11764,11 +12387,11 @@ def __ne__(self, other: 'SegmentSettings') -> bool: return not self == other -class Source(): +class Source: """ Object containing source parameters for the configuration. - :attr str type: (optional) The type of source to connect to. + :param str type: (optional) The type of source to connect to. - `box` indicates the configuration is to connect an instance of Enterprise Box. - `salesforce` indicates the configuration is to connect to Salesforce. @@ -11777,22 +12400,24 @@ class Source(): - `web_crawl` indicates the configuration is to perform a web page crawl. - `cloud_object_storage` indicates the configuration is to connect to a cloud object store. - :attr str credential_id: (optional) The **credential_id** of the credentials to + :param str credential_id: (optional) The **credential_id** of the credentials to use to connect to the source. Credentials are defined using the **credentials** method. The **source_type** of the credentials used must match the **type** field specified in this object. - :attr SourceSchedule schedule: (optional) Object containing the schedule + :param SourceSchedule schedule: (optional) Object containing the schedule information for the source. - :attr SourceOptions options: (optional) The **options** object defines which + :param SourceOptions options: (optional) The **options** object defines which items to crawl from the source system. """ - def __init__(self, - *, - type: str = None, - credential_id: str = None, - schedule: 'SourceSchedule' = None, - options: 'SourceOptions' = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + credential_id: Optional[str] = None, + schedule: Optional['SourceSchedule'] = None, + options: Optional['SourceOptions'] = None, + ) -> None: """ Initialize a Source object. @@ -11823,14 +12448,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Source': """Initialize a Source object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'credential_id' in _dict: - args['credential_id'] = _dict.get('credential_id') - if 'schedule' in _dict: - args['schedule'] = SourceSchedule.from_dict(_dict.get('schedule')) - if 'options' in _dict: - args['options'] = SourceOptions.from_dict(_dict.get('options')) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (credential_id := _dict.get('credential_id')) is not None: + args['credential_id'] = credential_id + if (schedule := _dict.get('schedule')) is not None: + args['schedule'] = SourceSchedule.from_dict(schedule) + if (options := _dict.get('options')) is not None: + args['options'] = SourceOptions.from_dict(options) return cls(**args) @classmethod @@ -11886,6 +12511,7 @@ class TypeEnum(str, Enum): - `cloud_object_storage` indicates the configuration is to connect to a cloud object store. """ + BOX = 'box' SALESFORCE = 'salesforce' SHAREPOINT = 'sharepoint' @@ -11893,40 +12519,43 @@ class TypeEnum(str, Enum): CLOUD_OBJECT_STORAGE = 'cloud_object_storage' -class SourceOptions(): +class SourceOptions: """ The **options** object defines which items to crawl from the source system. - :attr List[SourceOptionsFolder] folders: (optional) Array of folders to crawl + :param List[SourceOptionsFolder] folders: (optional) Array of folders to crawl from the Box source. Only valid, and required, when the **type** field of the **source** object is set to `box`. - :attr List[SourceOptionsObject] objects: (optional) Array of Salesforce document - object types to crawl from the Salesforce source. Only valid, and required, when - the **type** field of the **source** object is set to `salesforce`. - :attr List[SourceOptionsSiteColl] site_collections: (optional) Array of + :param List[SourceOptionsObject] objects: (optional) Array of Salesforce + document object types to crawl from the Salesforce source. Only valid, and + required, when the **type** field of the **source** object is set to + `salesforce`. + :param List[SourceOptionsSiteColl] site_collections: (optional) Array of Microsoft SharePointoint Online site collections to crawl from the SharePoint source. Only valid and required when the **type** field of the **source** object is set to `sharepoint`. - :attr List[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to + :param List[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to begin crawling the web from. Only valid and required when the **type** field of the **source** object is set to `web_crawl`. - :attr List[SourceOptionsBuckets] buckets: (optional) Array of cloud object store - buckets to begin crawling. Only valid and required when the **type** field of - the **source** object is set to `cloud_object_store`, and the + :param List[SourceOptionsBuckets] buckets: (optional) Array of cloud object + store buckets to begin crawling. Only valid and required when the **type** field + of the **source** object is set to `cloud_object_store`, and the **crawl_all_buckets** field is `false` or not specified. - :attr bool crawl_all_buckets: (optional) When `true`, all buckets in the + :param bool crawl_all_buckets: (optional) When `true`, all buckets in the specified cloud object store are crawled. If set to `true`, the **buckets** array must not be specified. """ - def __init__(self, - *, - folders: List['SourceOptionsFolder'] = None, - objects: List['SourceOptionsObject'] = None, - site_collections: List['SourceOptionsSiteColl'] = None, - urls: List['SourceOptionsWebCrawl'] = None, - buckets: List['SourceOptionsBuckets'] = None, - crawl_all_buckets: bool = None) -> None: + def __init__( + self, + *, + folders: Optional[List['SourceOptionsFolder']] = None, + objects: Optional[List['SourceOptionsObject']] = None, + site_collections: Optional[List['SourceOptionsSiteColl']] = None, + urls: Optional[List['SourceOptionsWebCrawl']] = None, + buckets: Optional[List['SourceOptionsBuckets']] = None, + crawl_all_buckets: Optional[bool] = None, + ) -> None: """ Initialize a SourceOptions object. @@ -11963,29 +12592,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceOptions': """Initialize a SourceOptions object from a json dictionary.""" args = {} - if 'folders' in _dict: + if (folders := _dict.get('folders')) is not None: args['folders'] = [ - SourceOptionsFolder.from_dict(v) for v in _dict.get('folders') + SourceOptionsFolder.from_dict(v) for v in folders ] - if 'objects' in _dict: + if (objects := _dict.get('objects')) is not None: args['objects'] = [ - SourceOptionsObject.from_dict(v) for v in _dict.get('objects') + SourceOptionsObject.from_dict(v) for v in objects ] - if 'site_collections' in _dict: + if (site_collections := _dict.get('site_collections')) is not None: args['site_collections'] = [ - SourceOptionsSiteColl.from_dict(v) - for v in _dict.get('site_collections') + SourceOptionsSiteColl.from_dict(v) for v in site_collections ] - if 'urls' in _dict: - args['urls'] = [ - SourceOptionsWebCrawl.from_dict(v) for v in _dict.get('urls') - ] - if 'buckets' in _dict: + if (urls := _dict.get('urls')) is not None: + args['urls'] = [SourceOptionsWebCrawl.from_dict(v) for v in urls] + if (buckets := _dict.get('buckets')) is not None: args['buckets'] = [ - SourceOptionsBuckets.from_dict(v) for v in _dict.get('buckets') + SourceOptionsBuckets.from_dict(v) for v in buckets ] - if 'crawl_all_buckets' in _dict: - args['crawl_all_buckets'] = _dict.get('crawl_all_buckets') + if (crawl_all_buckets := _dict.get('crawl_all_buckets')) is not None: + args['crawl_all_buckets'] = crawl_all_buckets return cls(**args) @classmethod @@ -12061,16 +12687,21 @@ def __ne__(self, other: 'SourceOptions') -> bool: return not self == other -class SourceOptionsBuckets(): +class SourceOptionsBuckets: """ Object defining a cloud object store bucket to crawl. - :attr str name: The name of the cloud object store bucket to crawl. - :attr int limit: (optional) The number of documents to crawl from this cloud + :param str name: The name of the cloud object store bucket to crawl. + :param int limit: (optional) The number of documents to crawl from this cloud object store bucket. If not specified, all documents in the bucket are crawled. """ - def __init__(self, name: str, *, limit: int = None) -> None: + def __init__( + self, + name: str, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a SourceOptionsBuckets object. @@ -12086,14 +12717,14 @@ def __init__(self, name: str, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'SourceOptionsBuckets': """Initialize a SourceOptionsBuckets object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in SourceOptionsBuckets JSON' ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -12129,22 +12760,24 @@ def __ne__(self, other: 'SourceOptionsBuckets') -> bool: return not self == other -class SourceOptionsFolder(): +class SourceOptionsFolder: """ Object that defines a box folder to crawl with this configuration. - :attr str owner_user_id: The Box user ID of the user who owns the folder to + :param str owner_user_id: The Box user ID of the user who owns the folder to crawl. - :attr str folder_id: The Box folder ID of the folder to crawl. - :attr int limit: (optional) The maximum number of documents to crawl for this + :param str folder_id: The Box folder ID of the folder to crawl. + :param int limit: (optional) The maximum number of documents to crawl for this folder. By default, all documents in the folder are crawled. """ - def __init__(self, - owner_user_id: str, - folder_id: str, - *, - limit: int = None) -> None: + def __init__( + self, + owner_user_id: str, + folder_id: str, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a SourceOptionsFolder object. @@ -12162,20 +12795,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceOptionsFolder': """Initialize a SourceOptionsFolder object from a json dictionary.""" args = {} - if 'owner_user_id' in _dict: - args['owner_user_id'] = _dict.get('owner_user_id') + if (owner_user_id := _dict.get('owner_user_id')) is not None: + args['owner_user_id'] = owner_user_id else: raise ValueError( 'Required property \'owner_user_id\' not present in SourceOptionsFolder JSON' ) - if 'folder_id' in _dict: - args['folder_id'] = _dict.get('folder_id') + if (folder_id := _dict.get('folder_id')) is not None: + args['folder_id'] = folder_id else: raise ValueError( 'Required property \'folder_id\' not present in SourceOptionsFolder JSON' ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -12213,17 +12846,22 @@ def __ne__(self, other: 'SourceOptionsFolder') -> bool: return not self == other -class SourceOptionsObject(): +class SourceOptionsObject: """ Object that defines a Salesforce document object type crawl with this configuration. - :attr str name: The name of the Salesforce document object to crawl. For + :param str name: The name of the Salesforce document object to crawl. For example, `case`. - :attr int limit: (optional) The maximum number of documents to crawl for this + :param int limit: (optional) The maximum number of documents to crawl for this document object. By default, all documents in the document object are crawled. """ - def __init__(self, name: str, *, limit: int = None) -> None: + def __init__( + self, + name: str, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a SourceOptionsObject object. @@ -12240,14 +12878,14 @@ def __init__(self, name: str, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'SourceOptionsObject': """Initialize a SourceOptionsObject object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in SourceOptionsObject JSON' ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -12283,19 +12921,24 @@ def __ne__(self, other: 'SourceOptionsObject') -> bool: return not self == other -class SourceOptionsSiteColl(): +class SourceOptionsSiteColl: """ Object that defines a Microsoft SharePoint site collection to crawl with this configuration. - :attr str site_collection_path: The Microsoft SharePoint Online site collection + :param str site_collection_path: The Microsoft SharePoint Online site collection path to crawl. The path must be be relative to the **organization_url** that was specified in the credentials associated with this source configuration. - :attr int limit: (optional) The maximum number of documents to crawl for this + :param int limit: (optional) The maximum number of documents to crawl for this site collection. By default, all documents in the site collection are crawled. """ - def __init__(self, site_collection_path: str, *, limit: int = None) -> None: + def __init__( + self, + site_collection_path: str, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a SourceOptionsSiteColl object. @@ -12314,14 +12957,15 @@ def __init__(self, site_collection_path: str, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'SourceOptionsSiteColl': """Initialize a SourceOptionsSiteColl object from a json dictionary.""" args = {} - if 'site_collection_path' in _dict: - args['site_collection_path'] = _dict.get('site_collection_path') + if (site_collection_path := + _dict.get('site_collection_path')) is not None: + args['site_collection_path'] = site_collection_path else: raise ValueError( 'Required property \'site_collection_path\' not present in SourceOptionsSiteColl JSON' ) - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -12358,47 +13002,49 @@ def __ne__(self, other: 'SourceOptionsSiteColl') -> bool: return not self == other -class SourceOptionsWebCrawl(): +class SourceOptionsWebCrawl: """ Object defining which URL to crawl and how to crawl it. - :attr str url: The starting URL to crawl. - :attr bool limit_to_starting_hosts: (optional) When `true`, crawls of the + :param str url: The starting URL to crawl. + :param bool limit_to_starting_hosts: (optional) When `true`, crawls of the specified URL are limited to the host part of the **url** field. - :attr str crawl_speed: (optional) The number of concurrent URLs to fetch. + :param str crawl_speed: (optional) The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a time with a delay between each call. `normal` means as many as two URLs are fectched concurrently with a short delay between fetch calls. `aggressive` means that up to ten URLs are fetched concurrently with a short delay between fetch calls. - :attr bool allow_untrusted_certificate: (optional) When `true`, allows the crawl - to interact with HTTPS sites with SSL certificates with untrusted signers. - :attr int maximum_hops: (optional) The maximum number of hops to make from the + :param bool allow_untrusted_certificate: (optional) When `true`, allows the + crawl to interact with HTTPS sites with SSL certificates with untrusted signers. + :param int maximum_hops: (optional) The maximum number of hops to make from the initial URL. When a page is crawled each link on that page will also be crawled if it is within the **maximum_hops** from the initial URL. The first page crawled is 0 hops, each link crawled from the first page is 1 hop, each link crawled from those pages is 2 hops, and so on. - :attr int request_timeout: (optional) The maximum milliseconds to wait for a + :param int request_timeout: (optional) The maximum milliseconds to wait for a response from the web server. - :attr bool override_robots_txt: (optional) When `true`, the crawler will ignore + :param bool override_robots_txt: (optional) When `true`, the crawler will ignore any `robots.txt` encountered by the crawler. This should only ever be done when crawling a web site the user owns. This must be be set to `true` when a **gateway_id** is specied in the **credentials**. - :attr List[str] blacklist: (optional) Array of URL's to be excluded while + :param List[str] blacklist: (optional) Array of URL's to be excluded while crawling. The crawler will not follow links which contains this string. For example, listing `https://ibm.com/watson` also excludes `https://ibm.com/watson/discovery`. """ - def __init__(self, - url: str, - *, - limit_to_starting_hosts: bool = None, - crawl_speed: str = None, - allow_untrusted_certificate: bool = None, - maximum_hops: int = None, - request_timeout: int = None, - override_robots_txt: bool = None, - blacklist: List[str] = None) -> None: + def __init__( + self, + url: str, + *, + limit_to_starting_hosts: Optional[bool] = None, + crawl_speed: Optional[str] = None, + allow_untrusted_certificate: Optional[bool] = None, + maximum_hops: Optional[int] = None, + request_timeout: Optional[int] = None, + override_robots_txt: Optional[bool] = None, + blacklist: Optional[List[str]] = None, + ) -> None: """ Initialize a SourceOptionsWebCrawl object. @@ -12442,28 +13088,29 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceOptionsWebCrawl': """Initialize a SourceOptionsWebCrawl object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in SourceOptionsWebCrawl JSON' ) - if 'limit_to_starting_hosts' in _dict: - args['limit_to_starting_hosts'] = _dict.get( - 'limit_to_starting_hosts') - if 'crawl_speed' in _dict: - args['crawl_speed'] = _dict.get('crawl_speed') - if 'allow_untrusted_certificate' in _dict: - args['allow_untrusted_certificate'] = _dict.get( - 'allow_untrusted_certificate') - if 'maximum_hops' in _dict: - args['maximum_hops'] = _dict.get('maximum_hops') - if 'request_timeout' in _dict: - args['request_timeout'] = _dict.get('request_timeout') - if 'override_robots_txt' in _dict: - args['override_robots_txt'] = _dict.get('override_robots_txt') - if 'blacklist' in _dict: - args['blacklist'] = _dict.get('blacklist') + if (limit_to_starting_hosts := + _dict.get('limit_to_starting_hosts')) is not None: + args['limit_to_starting_hosts'] = limit_to_starting_hosts + if (crawl_speed := _dict.get('crawl_speed')) is not None: + args['crawl_speed'] = crawl_speed + if (allow_untrusted_certificate := + _dict.get('allow_untrusted_certificate')) is not None: + args['allow_untrusted_certificate'] = allow_untrusted_certificate + if (maximum_hops := _dict.get('maximum_hops')) is not None: + args['maximum_hops'] = maximum_hops + if (request_timeout := _dict.get('request_timeout')) is not None: + args['request_timeout'] = request_timeout + if (override_robots_txt := + _dict.get('override_robots_txt')) is not None: + args['override_robots_txt'] = override_robots_txt + if (blacklist := _dict.get('blacklist')) is not None: + args['blacklist'] = blacklist return cls(**args) @classmethod @@ -12524,23 +13171,24 @@ class CrawlSpeedEnum(str, Enum): that up to ten URLs are fetched concurrently with a short delay between fetch calls. """ + GENTLE = 'gentle' NORMAL = 'normal' AGGRESSIVE = 'aggressive' -class SourceSchedule(): +class SourceSchedule: """ Object containing the schedule information for the source. - :attr bool enabled: (optional) When `true`, the source is re-crawled based on + :param bool enabled: (optional) When `true`, the source is re-crawled based on the **frequency** field in this object. When `false` the source is not re-crawled; When `false` and connecting to Salesforce the source is crawled annually. - :attr str time_zone: (optional) The time zone to base source crawl times on. + :param str time_zone: (optional) The time zone to base source crawl times on. Possible values correspond to the IANA (Internet Assigned Numbers Authority) time zones list. - :attr str frequency: (optional) The crawl schedule in the specified + :param str frequency: (optional) The crawl schedule in the specified **time_zone**. - `five_minutes`: Runs every five minutes. - `hourly`: Runs every hour. @@ -12550,11 +13198,13 @@ class SourceSchedule(): 06:00. """ - def __init__(self, - *, - enabled: bool = None, - time_zone: str = None, - frequency: str = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + time_zone: Optional[str] = None, + frequency: Optional[str] = None, + ) -> None: """ Initialize a SourceSchedule object. @@ -12582,12 +13232,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceSchedule': """Initialize a SourceSchedule object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'time_zone' in _dict: - args['time_zone'] = _dict.get('time_zone') - if 'frequency' in _dict: - args['frequency'] = _dict.get('frequency') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (time_zone := _dict.get('time_zone')) is not None: + args['time_zone'] = time_zone + if (frequency := _dict.get('frequency')) is not None: + args['frequency'] = frequency return cls(**args) @classmethod @@ -12633,6 +13283,7 @@ class FrequencyEnum(str, Enum): - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - `monthly`: Runs the on the first Sunday of every month between 00:00 and 06:00. """ + DAILY = 'daily' WEEKLY = 'weekly' MONTHLY = 'monthly' @@ -12640,11 +13291,11 @@ class FrequencyEnum(str, Enum): HOURLY = 'hourly' -class SourceStatus(): +class SourceStatus: """ Object containing source crawl status information. - :attr str status: (optional) The current status of the source crawl for this + :param str status: (optional) The current status of the source crawl for this collection. This field returns `not_configured` if the default configuration for this source does not have a **source** object defined. - `running` indicates that a crawl to fetch more documents is in progress. @@ -12652,14 +13303,16 @@ class SourceStatus(): - `queued` indicates that the crawl has been paused by the system and will automatically restart when possible. - `unknown` indicates that an unidentified error has occured in the service. - :attr datetime next_crawl: (optional) Date in `RFC 3339` format indicating the + :param datetime next_crawl: (optional) Date in `RFC 3339` format indicating the time of the next crawl attempt. """ - def __init__(self, - *, - status: str = None, - next_crawl: datetime = None) -> None: + def __init__( + self, + *, + status: Optional[str] = None, + next_crawl: Optional[datetime] = None, + ) -> None: """ Initialize a SourceStatus object. @@ -12682,10 +13335,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SourceStatus': """Initialize a SourceStatus object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'next_crawl' in _dict: - args['next_crawl'] = string_to_datetime(_dict.get('next_crawl')) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (next_crawl := _dict.get('next_crawl')) is not None: + args['next_crawl'] = string_to_datetime(next_crawl) return cls(**args) @classmethod @@ -12731,6 +13384,7 @@ class StatusEnum(str, Enum): automatically restart when possible. - `unknown` indicates that an unidentified error has occured in the service. """ + RUNNING = 'running' COMPLETE = 'complete' NOT_CONFIGURED = 'not_configured' @@ -12738,20 +13392,22 @@ class StatusEnum(str, Enum): UNKNOWN = 'unknown' -class StatusDetails(): +class StatusDetails: """ Object that contains details about the status of the authentication process. - :attr bool authenticated: (optional) Indicates whether the credential is + :param bool authenticated: (optional) Indicates whether the credential is accepted by the target data source. - :attr str error_message: (optional) If `authenticated` is `false`, a message + :param str error_message: (optional) If `authenticated` is `false`, a message describes why authentication is unsuccessful. """ - def __init__(self, - *, - authenticated: bool = None, - error_message: str = None) -> None: + def __init__( + self, + *, + authenticated: Optional[bool] = None, + error_message: Optional[str] = None, + ) -> None: """ Initialize a StatusDetails object. @@ -12767,10 +13423,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'StatusDetails': """Initialize a StatusDetails object from a json dictionary.""" args = {} - if 'authenticated' in _dict: - args['authenticated'] = _dict.get('authenticated') - if 'error_message' in _dict: - args['error_message'] = _dict.get('error_message') + if (authenticated := _dict.get('authenticated')) is not None: + args['authenticated'] = authenticated + if (error_message := _dict.get('error_message')) is not None: + args['error_message'] = error_message return cls(**args) @classmethod @@ -12806,25 +13462,27 @@ def __ne__(self, other: 'StatusDetails') -> bool: return not self == other -class TokenDictRule(): +class TokenDictRule: """ An object defining a single tokenizaion rule. - :attr str text: The string to tokenize. - :attr List[str] tokens: Array of tokens that the `text` field is split into when - found. - :attr List[str] readings: (optional) Array of tokens that represent the content + :param str text: The string to tokenize. + :param List[str] tokens: Array of tokens that the `text` field is split into + when found. + :param List[str] readings: (optional) Array of tokens that represent the content of the `text` field in an alternate character set. - :attr str part_of_speech: The part of speech that the `text` string belongs to. + :param str part_of_speech: The part of speech that the `text` string belongs to. For example `noun`. Custom parts of speech can be specified. """ - def __init__(self, - text: str, - tokens: List[str], - part_of_speech: str, - *, - readings: List[str] = None) -> None: + def __init__( + self, + text: str, + tokens: List[str], + part_of_speech: str, + *, + readings: Optional[List[str]] = None, + ) -> None: """ Initialize a TokenDictRule object. @@ -12845,21 +13503,21 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TokenDictRule': """Initialize a TokenDictRule object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text else: raise ValueError( 'Required property \'text\' not present in TokenDictRule JSON') - if 'tokens' in _dict: - args['tokens'] = _dict.get('tokens') + if (tokens := _dict.get('tokens')) is not None: + args['tokens'] = tokens else: raise ValueError( 'Required property \'tokens\' not present in TokenDictRule JSON' ) - if 'readings' in _dict: - args['readings'] = _dict.get('readings') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') + if (readings := _dict.get('readings')) is not None: + args['readings'] = readings + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech else: raise ValueError( 'Required property \'part_of_speech\' not present in TokenDictRule JSON' @@ -12903,17 +13561,22 @@ def __ne__(self, other: 'TokenDictRule') -> bool: return not self == other -class TokenDictStatusResponse(): +class TokenDictStatusResponse: """ Object describing the current status of the wordlist. - :attr str status: (optional) Current wordlist status for the specified + :param str status: (optional) Current wordlist status for the specified collection. - :attr str type: (optional) The type for this wordlist. Can be + :param str type: (optional) The type for this wordlist. Can be `tokenization_dictionary` or `stopwords`. """ - def __init__(self, *, status: str = None, type: str = None) -> None: + def __init__( + self, + *, + status: Optional[str] = None, + type: Optional[str] = None, + ) -> None: """ Initialize a TokenDictStatusResponse object. @@ -12929,10 +13592,10 @@ def __init__(self, *, status: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TokenDictStatusResponse': """Initialize a TokenDictStatusResponse object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (status := _dict.get('status')) is not None: + args['status'] = status + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -12971,29 +13634,32 @@ class StatusEnum(str, Enum): """ Current wordlist status for the specified collection. """ + ACTIVE = 'active' PENDING = 'pending' NOT_FOUND = 'not found' -class TrainingDataSet(): +class TrainingDataSet: """ Training information for a specific collection. - :attr str environment_id: (optional) The environment id associated with this + :param str environment_id: (optional) The environment id associated with this training data set. - :attr str collection_id: (optional) The collection id associated with this + :param str collection_id: (optional) The collection id associated with this training data set. - :attr List[TrainingQuery] queries: (optional) Array of training queries. At + :param List[TrainingQuery] queries: (optional) Array of training queries. At least 50 queries are required for training to begin. A maximum of 10,000 queries are returned. """ - def __init__(self, - *, - environment_id: str = None, - collection_id: str = None, - queries: List['TrainingQuery'] = None) -> None: + def __init__( + self, + *, + environment_id: Optional[str] = None, + collection_id: Optional[str] = None, + queries: Optional[List['TrainingQuery']] = None, + ) -> None: """ Initialize a TrainingDataSet object. @@ -13013,14 +13679,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingDataSet': """Initialize a TrainingDataSet object from a json dictionary.""" args = {} - if 'environment_id' in _dict: - args['environment_id'] = _dict.get('environment_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'queries' in _dict: - args['queries'] = [ - TrainingQuery.from_dict(v) for v in _dict.get('queries') - ] + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (queries := _dict.get('queries')) is not None: + args['queries'] = [TrainingQuery.from_dict(v) for v in queries] return cls(**args) @classmethod @@ -13064,22 +13728,24 @@ def __ne__(self, other: 'TrainingDataSet') -> bool: return not self == other -class TrainingExample(): +class TrainingExample: """ Training example details. - :attr str document_id: (optional) The document ID associated with this training + :param str document_id: (optional) The document ID associated with this training example. - :attr str cross_reference: (optional) The cross reference associated with this + :param str cross_reference: (optional) The cross reference associated with this training example. - :attr int relevance: (optional) The relevance of the training example. + :param int relevance: (optional) The relevance of the training example. """ - def __init__(self, - *, - document_id: str = None, - cross_reference: str = None, - relevance: int = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + cross_reference: Optional[str] = None, + relevance: Optional[int] = None, + ) -> None: """ Initialize a TrainingExample object. @@ -13097,12 +13763,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingExample': """Initialize a TrainingExample object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'cross_reference' in _dict: - args['cross_reference'] = _dict.get('cross_reference') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (cross_reference := _dict.get('cross_reference')) is not None: + args['cross_reference'] = cross_reference + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance return cls(**args) @classmethod @@ -13141,14 +13807,18 @@ def __ne__(self, other: 'TrainingExample') -> bool: return not self == other -class TrainingExampleList(): +class TrainingExampleList: """ Object containing an array of training examples. - :attr List[TrainingExample] examples: (optional) Array of training examples. + :param List[TrainingExample] examples: (optional) Array of training examples. """ - def __init__(self, *, examples: List['TrainingExample'] = None) -> None: + def __init__( + self, + *, + examples: Optional[List['TrainingExample']] = None, + ) -> None: """ Initialize a TrainingExampleList object. @@ -13161,10 +13831,8 @@ def __init__(self, *, examples: List['TrainingExample'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingExampleList': """Initialize a TrainingExampleList object from a json dictionary.""" args = {} - if 'examples' in _dict: - args['examples'] = [ - TrainingExample.from_dict(v) for v in _dict.get('examples') - ] + if (examples := _dict.get('examples')) is not None: + args['examples'] = [TrainingExample.from_dict(v) for v in examples] return cls(**args) @classmethod @@ -13204,24 +13872,26 @@ def __ne__(self, other: 'TrainingExampleList') -> bool: return not self == other -class TrainingQuery(): +class TrainingQuery: """ Training query details. - :attr str query_id: (optional) The query ID associated with the training query. - :attr str natural_language_query: (optional) The natural text query for the + :param str query_id: (optional) The query ID associated with the training query. + :param str natural_language_query: (optional) The natural text query for the training query. - :attr str filter: (optional) The filter used on the collection before the + :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :attr List[TrainingExample] examples: (optional) Array of training examples. + :param List[TrainingExample] examples: (optional) Array of training examples. """ - def __init__(self, - *, - query_id: str = None, - natural_language_query: str = None, - filter: str = None, - examples: List['TrainingExample'] = None) -> None: + def __init__( + self, + *, + query_id: Optional[str] = None, + natural_language_query: Optional[str] = None, + filter: Optional[str] = None, + examples: Optional[List['TrainingExample']] = None, + ) -> None: """ Initialize a TrainingQuery object. @@ -13243,16 +13913,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingQuery': """Initialize a TrainingQuery object from a json dictionary.""" args = {} - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'natural_language_query' in _dict: - args['natural_language_query'] = _dict.get('natural_language_query') - if 'filter' in _dict: - args['filter'] = _dict.get('filter') - if 'examples' in _dict: - args['examples'] = [ - TrainingExample.from_dict(v) for v in _dict.get('examples') - ] + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (natural_language_query := + _dict.get('natural_language_query')) is not None: + args['natural_language_query'] = natural_language_query + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (examples := _dict.get('examples')) is not None: + args['examples'] = [TrainingExample.from_dict(v) for v in examples] return cls(**args) @classmethod @@ -13299,41 +13968,43 @@ def __ne__(self, other: 'TrainingQuery') -> bool: return not self == other -class TrainingStatus(): +class TrainingStatus: """ Training status details. - :attr int total_examples: (optional) The total number of training examples + :param int total_examples: (optional) The total number of training examples uploaded to this collection. - :attr bool available: (optional) When `true`, the collection has been + :param bool available: (optional) When `true`, the collection has been successfully trained. - :attr bool processing: (optional) When `true`, the collection is currently + :param bool processing: (optional) When `true`, the collection is currently processing training. - :attr bool minimum_queries_added: (optional) When `true`, the collection has a + :param bool minimum_queries_added: (optional) When `true`, the collection has a sufficent amount of queries added for training to occur. - :attr bool minimum_examples_added: (optional) When `true`, the collection has a + :param bool minimum_examples_added: (optional) When `true`, the collection has a sufficent amount of examples added for training to occur. - :attr bool sufficient_label_diversity: (optional) When `true`, the collection + :param bool sufficient_label_diversity: (optional) When `true`, the collection has a sufficent amount of diversity in labeled results for training to occur. - :attr int notices: (optional) The number of notices associated with this data + :param int notices: (optional) The number of notices associated with this data set. - :attr datetime successfully_trained: (optional) The timestamp of when the + :param datetime successfully_trained: (optional) The timestamp of when the collection was successfully trained. - :attr datetime data_updated: (optional) The timestamp of when the data was + :param datetime data_updated: (optional) The timestamp of when the data was uploaded. """ - def __init__(self, - *, - total_examples: int = None, - available: bool = None, - processing: bool = None, - minimum_queries_added: bool = None, - minimum_examples_added: bool = None, - sufficient_label_diversity: bool = None, - notices: int = None, - successfully_trained: datetime = None, - data_updated: datetime = None) -> None: + def __init__( + self, + *, + total_examples: Optional[int] = None, + available: Optional[bool] = None, + processing: Optional[bool] = None, + minimum_queries_added: Optional[bool] = None, + minimum_examples_added: Optional[bool] = None, + sufficient_label_diversity: Optional[bool] = None, + notices: Optional[int] = None, + successfully_trained: Optional[datetime] = None, + data_updated: Optional[datetime] = None, + ) -> None: """ Initialize a TrainingStatus object. @@ -13371,26 +14042,29 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingStatus': """Initialize a TrainingStatus object from a json dictionary.""" args = {} - if 'total_examples' in _dict: - args['total_examples'] = _dict.get('total_examples') - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'processing' in _dict: - args['processing'] = _dict.get('processing') - if 'minimum_queries_added' in _dict: - args['minimum_queries_added'] = _dict.get('minimum_queries_added') - if 'minimum_examples_added' in _dict: - args['minimum_examples_added'] = _dict.get('minimum_examples_added') - if 'sufficient_label_diversity' in _dict: - args['sufficient_label_diversity'] = _dict.get( - 'sufficient_label_diversity') - if 'notices' in _dict: - args['notices'] = _dict.get('notices') - if 'successfully_trained' in _dict: + if (total_examples := _dict.get('total_examples')) is not None: + args['total_examples'] = total_examples + if (available := _dict.get('available')) is not None: + args['available'] = available + if (processing := _dict.get('processing')) is not None: + args['processing'] = processing + if (minimum_queries_added := + _dict.get('minimum_queries_added')) is not None: + args['minimum_queries_added'] = minimum_queries_added + if (minimum_examples_added := + _dict.get('minimum_examples_added')) is not None: + args['minimum_examples_added'] = minimum_examples_added + if (sufficient_label_diversity := + _dict.get('sufficient_label_diversity')) is not None: + args['sufficient_label_diversity'] = sufficient_label_diversity + if (notices := _dict.get('notices')) is not None: + args['notices'] = notices + if (successfully_trained := + _dict.get('successfully_trained')) is not None: args['successfully_trained'] = string_to_datetime( - _dict.get('successfully_trained')) - if 'data_updated' in _dict: - args['data_updated'] = string_to_datetime(_dict.get('data_updated')) + successfully_trained) + if (data_updated := _dict.get('data_updated')) is not None: + args['data_updated'] = string_to_datetime(data_updated) return cls(**args) @classmethod @@ -13446,19 +14120,22 @@ def __ne__(self, other: 'TrainingStatus') -> bool: return not self == other -class WordHeadingDetection(): +class WordHeadingDetection: """ Object containing heading detection conversion settings for Microsoft Word documents. - :attr List[FontSetting] fonts: (optional) Array of font matching configurations. - :attr List[WordStyle] styles: (optional) Array of Microsoft Word styles to + :param List[FontSetting] fonts: (optional) Array of font matching + configurations. + :param List[WordStyle] styles: (optional) Array of Microsoft Word styles to convert. """ - def __init__(self, - *, - fonts: List['FontSetting'] = None, - styles: List['WordStyle'] = None) -> None: + def __init__( + self, + *, + fonts: Optional[List['FontSetting']] = None, + styles: Optional[List['WordStyle']] = None, + ) -> None: """ Initialize a WordHeadingDetection object. @@ -13474,14 +14151,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'WordHeadingDetection': """Initialize a WordHeadingDetection object from a json dictionary.""" args = {} - if 'fonts' in _dict: - args['fonts'] = [ - FontSetting.from_dict(v) for v in _dict.get('fonts') - ] - if 'styles' in _dict: - args['styles'] = [ - WordStyle.from_dict(v) for v in _dict.get('styles') - ] + if (fonts := _dict.get('fonts')) is not None: + args['fonts'] = [FontSetting.from_dict(v) for v in fonts] + if (styles := _dict.get('styles')) is not None: + args['styles'] = [WordStyle.from_dict(v) for v in styles] return cls(**args) @classmethod @@ -13529,15 +14202,19 @@ def __ne__(self, other: 'WordHeadingDetection') -> bool: return not self == other -class WordSettings(): +class WordSettings: """ A list of Word conversion settings. - :attr WordHeadingDetection heading: (optional) Object containing heading + :param WordHeadingDetection heading: (optional) Object containing heading detection conversion settings for Microsoft Word documents. """ - def __init__(self, *, heading: 'WordHeadingDetection' = None) -> None: + def __init__( + self, + *, + heading: Optional['WordHeadingDetection'] = None, + ) -> None: """ Initialize a WordSettings object. @@ -13550,9 +14227,8 @@ def __init__(self, *, heading: 'WordHeadingDetection' = None) -> None: def from_dict(cls, _dict: Dict) -> 'WordSettings': """Initialize a WordSettings object from a json dictionary.""" args = {} - if 'heading' in _dict: - args['heading'] = WordHeadingDetection.from_dict( - _dict.get('heading')) + if (heading := _dict.get('heading')) is not None: + args['heading'] = WordHeadingDetection.from_dict(heading) return cls(**args) @classmethod @@ -13589,16 +14265,21 @@ def __ne__(self, other: 'WordSettings') -> bool: return not self == other -class WordStyle(): +class WordStyle: """ Microsoft Word styles to convert into a specified HTML head level. - :attr int level: (optional) HTML head level that content matching this style is + :param int level: (optional) HTML head level that content matching this style is tagged with. - :attr List[str] names: (optional) Array of word style names to convert. + :param List[str] names: (optional) Array of word style names to convert. """ - def __init__(self, *, level: int = None, names: List[str] = None) -> None: + def __init__( + self, + *, + level: Optional[int] = None, + names: Optional[List[str]] = None, + ) -> None: """ Initialize a WordStyle object. @@ -13613,10 +14294,10 @@ def __init__(self, *, level: int = None, names: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'WordStyle': """Initialize a WordStyle object from a json dictionary.""" args = {} - if 'level' in _dict: - args['level'] = _dict.get('level') - if 'names' in _dict: - args['names'] = _dict.get('names') + if (level := _dict.get('level')) is not None: + args['level'] = level + if (names := _dict.get('names')) is not None: + args['names'] = names return cls(**args) @classmethod @@ -13652,14 +14333,18 @@ def __ne__(self, other: 'WordStyle') -> bool: return not self == other -class XPathPatterns(): +class XPathPatterns: """ Object containing an array of XPaths. - :attr List[str] xpaths: (optional) An array to XPaths. + :param List[str] xpaths: (optional) An array to XPaths. """ - def __init__(self, *, xpaths: List[str] = None) -> None: + def __init__( + self, + *, + xpaths: Optional[List[str]] = None, + ) -> None: """ Initialize a XPathPatterns object. @@ -13671,8 +14356,8 @@ def __init__(self, *, xpaths: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'XPathPatterns': """Initialize a XPathPatterns object from a json dictionary.""" args = {} - if 'xpaths' in _dict: - args['xpaths'] = _dict.get('xpaths') + if (xpaths := _dict.get('xpaths')) is not None: + args['xpaths'] = xpaths return cls(**args) @classmethod @@ -13711,11 +14396,17 @@ class QueryCalculationAggregation(QueryAggregation): Returns a scalar calculation across all documents for the field specified. Possible calculations include min, max, sum, average, and unique_count. - :attr str field: The field to perform the calculation on. - :attr float value: (optional) The value of the calculation. + :param str field: The field to perform the calculation on. + :param float value: (optional) The value of the calculation. """ - def __init__(self, type: str, field: str, *, value: float = None) -> None: + def __init__( + self, + type: str, + field: str, + *, + value: Optional[float] = None, + ) -> None: """ Initialize a QueryCalculationAggregation object. @@ -13732,20 +14423,20 @@ def __init__(self, type: str, field: str, *, value: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': """Initialize a QueryCalculationAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryCalculationAggregation JSON' ) - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryCalculationAggregation JSON' ) - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod @@ -13787,19 +14478,21 @@ class QueryFilterAggregation(QueryAggregation): """ A modifier that narrows the document set of the sub-aggregations it precedes. - :attr str match: The filter that is written in Discovery Query Language syntax + :param str match: The filter that is written in Discovery Query Language syntax and is applied to the documents before sub-aggregations are run. - :attr int matching_results: Number of documents that match the filter. - :attr List[QueryAggregation] aggregations: (optional) An array of + :param int matching_results: Number of documents that match the filter. + :param List[QueryAggregation] aggregations: (optional) An array of sub-aggregations. """ - def __init__(self, - type: str, - match: str, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + type: str, + match: str, + matching_results: int, + *, + aggregations: Optional[List['QueryAggregation']] = None, + ) -> None: """ Initialize a QueryFilterAggregation object. @@ -13820,27 +14513,27 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': """Initialize a QueryFilterAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryFilterAggregation JSON' ) - if 'match' in _dict: - args['match'] = _dict.get('match') + if (match := _dict.get('match')) is not None: + args['match'] = match else: raise ValueError( 'Required property \'match\' not present in QueryFilterAggregation JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' ) - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -13893,22 +14586,23 @@ class QueryHistogramAggregation(QueryAggregation): Numeric interval segments to categorize documents by using field values from a single numeric field to describe the category. - :attr str field: The numeric field name used to create the histogram. - :attr int interval: The size of the sections that the results are split into. - :attr str name: (optional) Identifier specified in the query request of this + :param str field: The numeric field name used to create the histogram. + :param int interval: The size of the sections that the results are split into. + :param str name: (optional) Identifier specified in the query request of this aggregation. - :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric - intervals. + :param List[QueryHistogramAggregationResult] results: (optional) Array of + numeric intervals. """ def __init__( - self, - type: str, - field: str, - interval: int, - *, - name: str = None, - results: List['QueryHistogramAggregationResult'] = None) -> None: + self, + type: str, + field: str, + interval: int, + *, + name: Optional[str] = None, + results: Optional[List['QueryHistogramAggregationResult']] = None, + ) -> None: """ Initialize a QueryHistogramAggregation object. @@ -13932,30 +14626,29 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': """Initialize a QueryHistogramAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryHistogramAggregation JSON' ) - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryHistogramAggregation JSON' ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval else: raise ValueError( 'Required property \'interval\' not present in QueryHistogramAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryHistogramAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryHistogramAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -14009,19 +14702,21 @@ class QueryNestedAggregation(QueryAggregation): A restriction that alters the document set that is used for sub-aggregations it precedes to nested documents found in the field specified. - :attr str path: The path to the document field to scope sub-aggregations to. - :attr int matching_results: Number of nested documents found in the specified + :param str path: The path to the document field to scope sub-aggregations to. + :param int matching_results: Number of nested documents found in the specified field. - :attr List[QueryAggregation] aggregations: (optional) An array of + :param List[QueryAggregation] aggregations: (optional) An array of sub-aggregations. """ - def __init__(self, - type: str, - path: str, - matching_results: int, - *, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__( + self, + type: str, + path: str, + matching_results: int, + *, + aggregations: Optional[List['QueryAggregation']] = None, + ) -> None: """ Initialize a QueryNestedAggregation object. @@ -14043,27 +14738,27 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': """Initialize a QueryNestedAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryNestedAggregation JSON' ) - if 'path' in _dict: - args['path'] = _dict.get('path') + if (path := _dict.get('path')) is not None: + args['path'] = path else: raise ValueError( 'Required property \'path\' not present in QueryNestedAggregation JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' ) - if 'aggregations' in _dict: + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -14115,21 +14810,23 @@ class QueryTermAggregation(QueryAggregation): """ Returns the top values for the field specified. - :attr str field: The field in the document used to generate top values from. - :attr int count: (optional) The number of top values returned. - :attr str name: (optional) Identifier specified in the query request of this + :param str field: The field in the document used to generate top values from. + :param int count: (optional) The number of top values returned. + :param str name: (optional) Identifier specified in the query request of this aggregation. - :attr List[QueryTermAggregationResult] results: (optional) Array of top values + :param List[QueryTermAggregationResult] results: (optional) Array of top values for the field. """ - def __init__(self, - type: str, - field: str, - *, - count: int = None, - name: str = None, - results: List['QueryTermAggregationResult'] = None) -> None: + def __init__( + self, + type: str, + field: str, + *, + count: Optional[int] = None, + name: Optional[str] = None, + results: Optional[List['QueryTermAggregationResult']] = None, + ) -> None: """ Initialize a QueryTermAggregation object. @@ -14153,26 +14850,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': """Initialize a QueryTermAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryTermAggregation JSON' ) - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryTermAggregation JSON' ) - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (count := _dict.get('count')) is not None: + args['count'] = count + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTermAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTermAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -14225,23 +14921,24 @@ class QueryTimesliceAggregation(QueryAggregation): """ A specialized histogram aggregation that uses dates to create interval segments. - :attr str field: The date field name used to create the timeslice. - :attr str interval: The date interval value. Valid values are seconds, minutes, + :param str field: The date field name used to create the timeslice. + :param str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. - :attr str name: (optional) Identifier specified in the query request of this + :param str name: (optional) Identifier specified in the query request of this aggregation. - :attr List[QueryTimesliceAggregationResult] results: (optional) Array of + :param List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ def __init__( - self, - type: str, - field: str, - interval: str, - *, - name: str = None, - results: List['QueryTimesliceAggregationResult'] = None) -> None: + self, + type: str, + field: str, + interval: str, + *, + name: Optional[str] = None, + results: Optional[List['QueryTimesliceAggregationResult']] = None, + ) -> None: """ Initialize a QueryTimesliceAggregation object. @@ -14265,30 +14962,29 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': """Initialize a QueryTimesliceAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryTimesliceAggregation JSON' ) - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryTimesliceAggregation JSON' ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval else: raise ValueError( 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTimesliceAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTimesliceAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -14341,18 +15037,20 @@ class QueryTopHitsAggregation(QueryAggregation): """ Returns the top documents ranked by the score of the query. - :attr int size: The number of documents to return. - :attr str name: (optional) Identifier specified in the query request of this + :param int size: The number of documents to return. + :param str name: (optional) Identifier specified in the query request of this aggregation. - :attr QueryTopHitsAggregationResult hits: (optional) + :param QueryTopHitsAggregationResult hits: (optional) """ - def __init__(self, - type: str, - size: int, - *, - name: str = None, - hits: 'QueryTopHitsAggregationResult' = None) -> None: + def __init__( + self, + type: str, + size: int, + *, + name: Optional[str] = None, + hits: Optional['QueryTopHitsAggregationResult'] = None, + ) -> None: """ Initialize a QueryTopHitsAggregation object. @@ -14372,23 +15070,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': """Initialize a QueryTopHitsAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( 'Required property \'type\' not present in QueryTopHitsAggregation JSON' ) - if 'size' in _dict: - args['size'] = _dict.get('size') + if (size := _dict.get('size')) is not None: + args['size'] = size else: raise ValueError( 'Required property \'size\' not present in QueryTopHitsAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'hits' in _dict: - args['hits'] = QueryTopHitsAggregationResult.from_dict( - _dict.get('hits')) + if (name := _dict.get('name')) is not None: + args['name'] = name + if (hits := _dict.get('hits')) is not None: + args['hits'] = QueryTopHitsAggregationResult.from_dict(hits) return cls(**args) @classmethod diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index d6af60eb8..5253de7b2 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ IBM Watson® Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive better @@ -29,7 +29,7 @@ from datetime import datetime from enum import Enum from os.path import basename -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json import sys @@ -82,7 +82,10 @@ def __init__( # Projects ######################### - def list_projects(self, **kwargs) -> DetailedResponse: + def list_projects( + self, + **kwargs, + ) -> DetailedResponse: """ List projects. @@ -94,9 +97,11 @@ def list_projects(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_projects') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_projects', + ) headers.update(sdk_headers) params = { @@ -109,20 +114,24 @@ def list_projects(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v2/projects' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_project(self, - name: str, - type: str, - *, - default_query_parameters: 'DefaultQueryParams' = None, - **kwargs) -> DetailedResponse: + def create_project( + self, + name: str, + type: str, + *, + default_query_parameters: Optional['DefaultQueryParams'] = None, + **kwargs, + ) -> DetailedResponse: """ Create a project. @@ -148,9 +157,11 @@ def create_project(self, if default_query_parameters is not None: default_query_parameters = convert_model(default_query_parameters) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_project', + ) headers.update(sdk_headers) params = { @@ -172,16 +183,22 @@ def create_project(self, headers['Accept'] = 'application/json' url = '/v2/projects' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_project(self, project_id: str, **kwargs) -> DetailedResponse: + def get_project( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ Get project. @@ -197,9 +214,11 @@ def get_project(self, project_id: str, **kwargs) -> DetailedResponse: if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_project', + ) headers.update(sdk_headers) params = { @@ -215,19 +234,23 @@ def get_project(self, project_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_project(self, - project_id: str, - *, - name: str = None, - **kwargs) -> DetailedResponse: + def update_project( + self, + project_id: str, + *, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update a project. @@ -244,9 +267,11 @@ def update_project(self, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_project', + ) headers.update(sdk_headers) params = { @@ -269,16 +294,22 @@ def update_project(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: + def delete_project( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a project. @@ -296,9 +327,11 @@ def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_project') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_project', + ) headers.update(sdk_headers) params = { @@ -313,19 +346,23 @@ def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_fields(self, - project_id: str, - *, - collection_ids: List[str] = None, - **kwargs) -> DetailedResponse: + def list_fields( + self, + project_id: str, + *, + collection_ids: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: """ List fields. @@ -345,9 +382,11 @@ def list_fields(self, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_fields') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_fields', + ) headers.update(sdk_headers) params = { @@ -364,10 +403,12 @@ def list_fields(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/fields'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -376,7 +417,11 @@ def list_fields(self, # Collections ######################### - def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: + def list_collections( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ List collections. @@ -392,9 +437,11 @@ def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_collections') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_collections', + ) headers.update(sdk_headers) params = { @@ -410,22 +457,26 @@ def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_collection(self, - project_id: str, - name: str, - *, - description: str = None, - language: str = None, - enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> DetailedResponse: + def create_collection( + self, + project_id: str, + name: str, + *, + description: Optional[str] = None, + language: Optional[str] = None, + enrichments: Optional[List['CollectionEnrichment']] = None, + **kwargs, + ) -> DetailedResponse: """ Create a collection. @@ -458,9 +509,11 @@ def create_collection(self, if enrichments is not None: enrichments = [convert_model(x) for x in enrichments] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_collection', + ) headers.update(sdk_headers) params = { @@ -486,17 +539,23 @@ def create_collection(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_collection(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def get_collection( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get collection. @@ -515,9 +574,11 @@ def get_collection(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_collection', + ) headers.update(sdk_headers) params = { @@ -534,22 +595,26 @@ def get_collection(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_collection(self, - project_id: str, - collection_id: str, - *, - name: str = None, - description: str = None, - enrichments: List['CollectionEnrichment'] = None, - **kwargs) -> DetailedResponse: + def update_collection( + self, + project_id: str, + collection_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + enrichments: Optional[List['CollectionEnrichment']] = None, + **kwargs, + ) -> DetailedResponse: """ Update a collection. @@ -574,9 +639,11 @@ def update_collection(self, if enrichments is not None: enrichments = [convert_model(x) for x in enrichments] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_collection', + ) headers.update(sdk_headers) params = { @@ -602,17 +669,23 @@ def update_collection(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_collection(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_collection( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a collection. @@ -632,9 +705,11 @@ def delete_collection(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_collection') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_collection', + ) headers.update(sdk_headers) params = { @@ -650,10 +725,12 @@ def delete_collection(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -662,17 +739,19 @@ def delete_collection(self, project_id: str, collection_id: str, # Documents ######################### - def list_documents(self, - project_id: str, - collection_id: str, - *, - count: int = None, - status: str = None, - has_notices: bool = None, - is_parent: bool = None, - parent_document_id: str = None, - sha256: str = None, - **kwargs) -> DetailedResponse: + def list_documents( + self, + project_id: str, + collection_id: str, + *, + count: Optional[int] = None, + status: Optional[str] = None, + has_notices: Optional[bool] = None, + is_parent: Optional[bool] = None, + parent_document_id: Optional[str] = None, + sha256: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List documents. @@ -729,9 +808,11 @@ def list_documents(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_documents') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_documents', + ) headers.update(sdk_headers) params = { @@ -754,24 +835,28 @@ def list_documents(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def add_document(self, - project_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - x_watson_discovery_force: bool = None, - **kwargs) -> DetailedResponse: + def add_document( + self, + project_id: str, + collection_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + x_watson_discovery_force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add a document. @@ -834,9 +919,11 @@ def add_document(self, headers = { 'X-Watson-Discovery-Force': x_watson_discovery_force, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='add_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='add_document', + ) headers.update(sdk_headers) params = { @@ -864,17 +951,24 @@ def add_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_document(self, project_id: str, collection_id: str, - document_id: str, **kwargs) -> DetailedResponse: + def get_document( + self, + project_id: str, + collection_id: str, + document_id: str, + **kwargs, + ) -> DetailedResponse: """ Get document details. @@ -900,9 +994,11 @@ def get_document(self, project_id: str, collection_id: str, if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document', + ) headers.update(sdk_headers) params = { @@ -920,25 +1016,29 @@ def get_document(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_document(self, - project_id: str, - collection_id: str, - document_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - x_watson_discovery_force: bool = None, - **kwargs) -> DetailedResponse: + def update_document( + self, + project_id: str, + collection_id: str, + document_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + x_watson_discovery_force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Update a document. @@ -995,9 +1095,11 @@ def update_document(self, headers = { 'X-Watson-Discovery-Force': x_watson_discovery_force, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document', + ) headers.update(sdk_headers) params = { @@ -1026,22 +1128,26 @@ def update_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_document(self, - project_id: str, - collection_id: str, - document_id: str, - *, - x_watson_discovery_force: bool = None, - **kwargs) -> DetailedResponse: + def delete_document( + self, + project_id: str, + collection_id: str, + document_id: str, + *, + x_watson_discovery_force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Delete a document. @@ -1078,9 +1184,11 @@ def delete_document(self, headers = { 'X-Watson-Discovery-Force': x_watson_discovery_force, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document', + ) headers.update(sdk_headers) params = { @@ -1098,10 +1206,12 @@ def delete_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1110,25 +1220,28 @@ def delete_document(self, # Queries ######################### - def query(self, - project_id: str, - *, - collection_ids: List[str] = None, - filter: str = None, - query: str = None, - natural_language_query: str = None, - aggregation: str = None, - count: int = None, - return_: List[str] = None, - offset: int = None, - sort: str = None, - highlight: bool = None, - spelling_suggestions: bool = None, - table_results: 'QueryLargeTableResults' = None, - suggested_refinements: 'QueryLargeSuggestedRefinements' = None, - passages: 'QueryLargePassages' = None, - similar: 'QueryLargeSimilar' = None, - **kwargs) -> DetailedResponse: + def query( + self, + project_id: str, + *, + collection_ids: Optional[List[str]] = None, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + aggregation: Optional[str] = None, + count: Optional[int] = None, + return_: Optional[List[str]] = None, + offset: Optional[int] = None, + sort: Optional[str] = None, + highlight: Optional[bool] = None, + spelling_suggestions: Optional[bool] = None, + table_results: Optional['QueryLargeTableResults'] = None, + suggested_refinements: Optional[ + 'QueryLargeSuggestedRefinements'] = None, + passages: Optional['QueryLargePassages'] = None, + similar: Optional['QueryLargeSimilar'] = None, + **kwargs, + ) -> DetailedResponse: """ Query a project. @@ -1220,9 +1333,11 @@ def query(self, if similar is not None: similar = convert_model(similar) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query', + ) headers.update(sdk_headers) params = { @@ -1259,23 +1374,27 @@ def query(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/query'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_autocompletion(self, - project_id: str, - prefix: str, - *, - collection_ids: List[str] = None, - field: str = None, - count: int = None, - **kwargs) -> DetailedResponse: + def get_autocompletion( + self, + project_id: str, + prefix: str, + *, + collection_ids: Optional[List[str]] = None, + field: Optional[str] = None, + count: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Get Autocomplete Suggestions. @@ -1302,9 +1421,11 @@ def get_autocompletion(self, if not prefix: raise ValueError('prefix must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_autocompletion') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_autocompletion', + ) headers.update(sdk_headers) params = { @@ -1325,24 +1446,28 @@ def get_autocompletion(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/autocompletion'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def query_collection_notices(self, - project_id: str, - collection_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - count: int = None, - offset: int = None, - **kwargs) -> DetailedResponse: + def query_collection_notices( + self, + project_id: str, + collection_id: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + count: Optional[int] = None, + offset: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Query collection notices. @@ -1383,9 +1508,11 @@ def query_collection_notices(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='query_collection_notices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query_collection_notices', + ) headers.update(sdk_headers) params = { @@ -1407,23 +1534,27 @@ def query_collection_notices(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/notices'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def query_notices(self, - project_id: str, - *, - filter: str = None, - query: str = None, - natural_language_query: str = None, - count: int = None, - offset: int = None, - **kwargs) -> DetailedResponse: + def query_notices( + self, + project_id: str, + *, + filter: Optional[str] = None, + query: Optional[str] = None, + natural_language_query: Optional[str] = None, + count: Optional[int] = None, + offset: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Query project notices. @@ -1461,9 +1592,11 @@ def query_notices(self, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='query_notices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='query_notices', + ) headers.update(sdk_headers) params = { @@ -1484,10 +1617,12 @@ def query_notices(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/notices'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1496,8 +1631,12 @@ def query_notices(self, # Query modifications ######################### - def get_stopword_list(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def get_stopword_list( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom stop words list. @@ -1518,9 +1657,11 @@ def get_stopword_list(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_stopword_list') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_stopword_list', + ) headers.update(sdk_headers) params = { @@ -1537,20 +1678,24 @@ def get_stopword_list(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_stopword_list(self, - project_id: str, - collection_id: str, - *, - stopwords: List[str] = None, - **kwargs) -> DetailedResponse: + def create_stopword_list( + self, + project_id: str, + collection_id: str, + *, + stopwords: Optional[List[str]] = None, + **kwargs, + ) -> DetailedResponse: """ Create a custom stop words list. @@ -1579,9 +1724,11 @@ def create_stopword_list(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_stopword_list') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_stopword_list', + ) headers.update(sdk_headers) params = { @@ -1605,17 +1752,23 @@ def create_stopword_list(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_stopword_list(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_stopword_list( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom stop words list. @@ -1636,9 +1789,11 @@ def delete_stopword_list(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_stopword_list') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_stopword_list', + ) headers.update(sdk_headers) params = { @@ -1654,16 +1809,22 @@ def delete_stopword_list(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/stopwords'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def list_expansions(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def list_expansions( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Get the expansion list. @@ -1683,9 +1844,11 @@ def list_expansions(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_expansions', + ) headers.update(sdk_headers) params = { @@ -1702,17 +1865,23 @@ def list_expansions(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_expansions(self, project_id: str, collection_id: str, - expansions: List['Expansion'], - **kwargs) -> DetailedResponse: + def create_expansions( + self, + project_id: str, + collection_id: str, + expansions: List['Expansion'], + **kwargs, + ) -> DetailedResponse: """ Create or update an expansion list. @@ -1751,9 +1920,11 @@ def create_expansions(self, project_id: str, collection_id: str, raise ValueError('expansions must be provided') expansions = [convert_model(x) for x in expansions] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_expansions', + ) headers.update(sdk_headers) params = { @@ -1777,17 +1948,23 @@ def create_expansions(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_expansions(self, project_id: str, collection_id: str, - **kwargs) -> DetailedResponse: + def delete_expansions( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete the expansion list. @@ -1807,9 +1984,11 @@ def delete_expansions(self, project_id: str, collection_id: str, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_expansions') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_expansions', + ) headers.update(sdk_headers) params = { @@ -1825,10 +2004,12 @@ def delete_expansions(self, project_id: str, collection_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/expansions'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1837,8 +2018,11 @@ def delete_expansions(self, project_id: str, collection_id: str, # Component settings ######################### - def get_component_settings(self, project_id: str, - **kwargs) -> DetailedResponse: + def get_component_settings( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ List component settings. @@ -1854,9 +2038,11 @@ def get_component_settings(self, project_id: str, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_component_settings') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_component_settings', + ) headers.update(sdk_headers) params = { @@ -1873,10 +2059,12 @@ def get_component_settings(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/component_settings'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1885,8 +2073,11 @@ def get_component_settings(self, project_id: str, # Training data ######################### - def list_training_queries(self, project_id: str, - **kwargs) -> DetailedResponse: + def list_training_queries( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ List training queries. @@ -1902,9 +2093,11 @@ def list_training_queries(self, project_id: str, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_training_queries') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_training_queries', + ) headers.update(sdk_headers) params = { @@ -1921,16 +2114,21 @@ def list_training_queries(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_training_queries(self, project_id: str, - **kwargs) -> DetailedResponse: + def delete_training_queries( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete training queries. @@ -1946,9 +2144,11 @@ def delete_training_queries(self, project_id: str, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_training_queries') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_training_queries', + ) headers.update(sdk_headers) params = { @@ -1964,21 +2164,25 @@ def delete_training_queries(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_training_query(self, - project_id: str, - natural_language_query: str, - examples: List['TrainingExample'], - *, - filter: str = None, - **kwargs) -> DetailedResponse: + def create_training_query( + self, + project_id: str, + natural_language_query: str, + examples: List['TrainingExample'], + *, + filter: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create training query. @@ -2005,9 +2209,11 @@ def create_training_query(self, raise ValueError('examples must be provided') examples = [convert_model(x) for x in examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_training_query', + ) headers.update(sdk_headers) params = { @@ -2033,17 +2239,23 @@ def create_training_query(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_training_query(self, project_id: str, query_id: str, - **kwargs) -> DetailedResponse: + def get_training_query( + self, + project_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a training data query. @@ -2063,9 +2275,11 @@ def get_training_query(self, project_id: str, query_id: str, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_training_query', + ) headers.update(sdk_headers) params = { @@ -2082,22 +2296,26 @@ def get_training_query(self, project_id: str, query_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_training_query(self, - project_id: str, - query_id: str, - natural_language_query: str, - examples: List['TrainingExample'], - *, - filter: str = None, - **kwargs) -> DetailedResponse: + def update_training_query( + self, + project_id: str, + query_id: str, + natural_language_query: str, + examples: List['TrainingExample'], + *, + filter: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update a training query. @@ -2126,9 +2344,11 @@ def update_training_query(self, raise ValueError('examples must be provided') examples = [convert_model(x) for x in examples] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_training_query', + ) headers.update(sdk_headers) params = { @@ -2154,17 +2374,23 @@ def update_training_query(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_training_query(self, project_id: str, query_id: str, - **kwargs) -> DetailedResponse: + def delete_training_query( + self, + project_id: str, + query_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a training data query. @@ -2184,9 +2410,11 @@ def delete_training_query(self, project_id: str, query_id: str, if not query_id: raise ValueError('query_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_training_query') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_training_query', + ) headers.update(sdk_headers) params = { @@ -2202,10 +2430,12 @@ def delete_training_query(self, project_id: str, query_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/training_data/queries/{query_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2214,7 +2444,11 @@ def delete_training_query(self, project_id: str, query_id: str, # Enrichments ######################### - def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: + def list_enrichments( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ List enrichments. @@ -2232,9 +2466,11 @@ def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_enrichments') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_enrichments', + ) headers.update(sdk_headers) params = { @@ -2250,20 +2486,24 @@ def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_enrichment(self, - project_id: str, - enrichment: 'CreateEnrichment', - *, - file: BinaryIO = None, - **kwargs) -> DetailedResponse: + def create_enrichment( + self, + project_id: str, + enrichment: 'CreateEnrichment', + *, + file: Optional[BinaryIO] = None, + **kwargs, + ) -> DetailedResponse: """ Create an enrichment. @@ -2291,9 +2531,11 @@ def create_enrichment(self, if enrichment is None: raise ValueError('enrichment must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_enrichment', + ) headers.update(sdk_headers) params = { @@ -2315,17 +2557,23 @@ def create_enrichment(self, path_param_values = self.encode_path_vars(project_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/enrichments'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> DetailedResponse: + def get_enrichment( + self, + project_id: str, + enrichment_id: str, + **kwargs, + ) -> DetailedResponse: """ Get enrichment. @@ -2344,9 +2592,11 @@ def get_enrichment(self, project_id: str, enrichment_id: str, if not enrichment_id: raise ValueError('enrichment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_enrichment', + ) headers.update(sdk_headers) params = { @@ -2363,21 +2613,25 @@ def get_enrichment(self, project_id: str, enrichment_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_enrichment(self, - project_id: str, - enrichment_id: str, - name: str, - *, - description: str = None, - **kwargs) -> DetailedResponse: + def update_enrichment( + self, + project_id: str, + enrichment_id: str, + name: str, + *, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update an enrichment. @@ -2400,9 +2654,11 @@ def update_enrichment(self, if name is None: raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_enrichment', + ) headers.update(sdk_headers) params = { @@ -2427,17 +2683,23 @@ def update_enrichment(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_enrichment(self, project_id: str, enrichment_id: str, - **kwargs) -> DetailedResponse: + def delete_enrichment( + self, + project_id: str, + enrichment_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete an enrichment. @@ -2457,9 +2719,11 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, if not enrichment_id: raise ValueError('enrichment_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_enrichment') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_enrichment', + ) headers.update(sdk_headers) params = { @@ -2475,10 +2739,12 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/enrichments/{enrichment_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2487,8 +2753,11 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, # Document classifiers ######################### - def list_document_classifiers(self, project_id: str, - **kwargs) -> DetailedResponse: + def list_document_classifiers( + self, + project_id: str, + **kwargs, + ) -> DetailedResponse: """ List document classifiers. @@ -2505,9 +2774,11 @@ def list_document_classifiers(self, project_id: str, if not project_id: raise ValueError('project_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='list_document_classifiers') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_document_classifiers', + ) headers.update(sdk_headers) params = { @@ -2524,21 +2795,25 @@ def list_document_classifiers(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_document_classifier(self, - project_id: str, - training_data: BinaryIO, - classifier: 'CreateDocumentClassifier', - *, - test_data: BinaryIO = None, - **kwargs) -> DetailedResponse: + def create_document_classifier( + self, + project_id: str, + training_data: BinaryIO, + classifier: 'CreateDocumentClassifier', + *, + test_data: Optional[BinaryIO] = None, + **kwargs, + ) -> DetailedResponse: """ Create a document classifier. @@ -2577,9 +2852,11 @@ def create_document_classifier(self, if classifier is None: raise ValueError('classifier must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='create_document_classifier') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_document_classifier', + ) headers.update(sdk_headers) params = { @@ -2603,17 +2880,23 @@ def create_document_classifier(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_document_classifier(self, project_id: str, classifier_id: str, - **kwargs) -> DetailedResponse: + def get_document_classifier( + self, + project_id: str, + classifier_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a document classifier. @@ -2632,9 +2915,11 @@ def get_document_classifier(self, project_id: str, classifier_id: str, if not classifier_id: raise ValueError('classifier_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='get_document_classifier') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='get_document_classifier', + ) headers.update(sdk_headers) params = { @@ -2651,22 +2936,26 @@ def get_document_classifier(self, project_id: str, classifier_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_document_classifier(self, - project_id: str, - classifier_id: str, - classifier: 'UpdateDocumentClassifier', - *, - training_data: BinaryIO = None, - test_data: BinaryIO = None, - **kwargs) -> DetailedResponse: + def update_document_classifier( + self, + project_id: str, + classifier_id: str, + classifier: 'UpdateDocumentClassifier', + *, + training_data: Optional[BinaryIO] = None, + test_data: Optional[BinaryIO] = None, + **kwargs, + ) -> DetailedResponse: """ Update a document classifier. @@ -2702,9 +2991,11 @@ def update_document_classifier(self, if classifier is None: raise ValueError('classifier must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='update_document_classifier') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_document_classifier', + ) headers.update(sdk_headers) params = { @@ -2730,17 +3021,23 @@ def update_document_classifier(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_document_classifier(self, project_id: str, classifier_id: str, - **kwargs) -> DetailedResponse: + def delete_document_classifier( + self, + project_id: str, + classifier_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a document classifier. @@ -2759,9 +3056,11 @@ def delete_document_classifier(self, project_id: str, classifier_id: str, if not classifier_id: raise ValueError('classifier_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_document_classifier') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_document_classifier', + ) headers.update(sdk_headers) params = { @@ -2777,10 +3076,12 @@ def delete_document_classifier(self, project_id: str, classifier_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -2789,9 +3090,12 @@ def delete_document_classifier(self, project_id: str, classifier_id: str, # Document classifier models ######################### - def list_document_classifier_models(self, project_id: str, - classifier_id: str, - **kwargs) -> DetailedResponse: + def list_document_classifier_models( + self, + project_id: str, + classifier_id: str, + **kwargs, + ) -> DetailedResponse: """ List document classifier models. @@ -2814,7 +3118,8 @@ def list_document_classifier_models(self, project_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='list_document_classifier_models') + operation_id='list_document_classifier_models', + ) headers.update(sdk_headers) params = { @@ -2831,27 +3136,30 @@ def list_document_classifier_models(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response def create_document_classifier_model( - self, - project_id: str, - classifier_id: str, - name: str, - *, - description: str = None, - learning_rate: float = None, - l1_regularization_strengths: List[float] = None, - l2_regularization_strengths: List[float] = None, - training_max_steps: int = None, - improvement_ratio: float = None, - **kwargs) -> DetailedResponse: + self, + project_id: str, + classifier_id: str, + name: str, + *, + description: Optional[str] = None, + learning_rate: Optional[float] = None, + l1_regularization_strengths: Optional[List[float]] = None, + l2_regularization_strengths: Optional[List[float]] = None, + training_max_steps: Optional[int] = None, + improvement_ratio: Optional[float] = None, + **kwargs, + ) -> DetailedResponse: """ Create a document classifier model. @@ -2902,7 +3210,8 @@ def create_document_classifier_model( sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='create_document_classifier_model') + operation_id='create_document_classifier_model', + ) headers.update(sdk_headers) params = { @@ -2932,18 +3241,24 @@ def create_document_classifier_model( path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_document_classifier_model(self, project_id: str, classifier_id: str, - model_id: str, - **kwargs) -> DetailedResponse: + def get_document_classifier_model( + self, + project_id: str, + classifier_id: str, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a document classifier model. @@ -2968,7 +3283,8 @@ def get_document_classifier_model(self, project_id: str, classifier_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_document_classifier_model') + operation_id='get_document_classifier_model', + ) headers.update(sdk_headers) params = { @@ -2986,22 +3302,26 @@ def get_document_classifier_model(self, project_id: str, classifier_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_document_classifier_model(self, - project_id: str, - classifier_id: str, - model_id: str, - *, - name: str = None, - description: str = None, - **kwargs) -> DetailedResponse: + def update_document_classifier_model( + self, + project_id: str, + classifier_id: str, + model_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update a document classifier model. @@ -3028,7 +3348,8 @@ def update_document_classifier_model(self, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_document_classifier_model') + operation_id='update_document_classifier_model', + ) headers.update(sdk_headers) params = { @@ -3054,18 +3375,24 @@ def update_document_classifier_model(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def delete_document_classifier_model(self, project_id: str, - classifier_id: str, model_id: str, - **kwargs) -> DetailedResponse: + def delete_document_classifier_model( + self, + project_id: str, + classifier_id: str, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a document classifier model. @@ -3090,7 +3417,8 @@ def delete_document_classifier_model(self, project_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='delete_document_classifier_model') + operation_id='delete_document_classifier_model', + ) headers.update(sdk_headers) params = { @@ -3107,10 +3435,12 @@ def delete_document_classifier_model(self, project_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/document_classifiers/{classifier_id}/models/{model_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3119,15 +3449,17 @@ def delete_document_classifier_model(self, project_id: str, # Analyze ######################### - def analyze_document(self, - project_id: str, - collection_id: str, - *, - file: BinaryIO = None, - filename: str = None, - file_content_type: str = None, - metadata: str = None, - **kwargs) -> DetailedResponse: + def analyze_document( + self, + project_id: str, + collection_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + metadata: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Analyze a Document. @@ -3174,9 +3506,11 @@ def analyze_document(self, if not collection_id: raise ValueError('collection_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='analyze_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='analyze_document', + ) headers.update(sdk_headers) params = { @@ -3204,11 +3538,13 @@ def analyze_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/projects/{project_id}/collections/{collection_id}/analyze'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response @@ -3217,7 +3553,11 @@ def analyze_document(self, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -3239,9 +3579,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V2', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -3254,10 +3596,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: del kwargs['headers'] url = '/v2/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3272,6 +3616,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_JSON = 'application/json' APPLICATION_MSWORD = 'application/msword' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' @@ -3289,6 +3634,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_JSON = 'application/json' APPLICATION_MSWORD = 'application/msword' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' @@ -3306,6 +3652,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_JSON = 'application/json' APPLICATION_MSWORD = 'application/msword' APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' @@ -3319,20 +3666,22 @@ class FileContentType(str, Enum): ############################################################################## -class AnalyzedDocument(): +class AnalyzedDocument: """ An object that contains the converted document and any identified enrichments. Root-level fields from the original file are returned also. - :attr List[Notice] notices: (optional) Array of notices that are triggered when + :param List[Notice] notices: (optional) Array of notices that are triggered when the files are processed. - :attr AnalyzedResult result: (optional) Result of the document analysis. + :param AnalyzedResult result: (optional) Result of the document analysis. """ - def __init__(self, - *, - notices: List['Notice'] = None, - result: 'AnalyzedResult' = None) -> None: + def __init__( + self, + *, + notices: Optional[List['Notice']] = None, + result: Optional['AnalyzedResult'] = None, + ) -> None: """ Initialize a AnalyzedDocument object. @@ -3347,12 +3696,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalyzedDocument': """Initialize a AnalyzedDocument object from a json dictionary.""" args = {} - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] - if 'result' in _dict: - args['result'] = AnalyzedResult.from_dict(_dict.get('result')) + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (result := _dict.get('result')) is not None: + args['result'] = AnalyzedResult.from_dict(result) return cls(**args) @classmethod @@ -3397,17 +3744,22 @@ def __ne__(self, other: 'AnalyzedDocument') -> bool: return not self == other -class AnalyzedResult(): +class AnalyzedResult: """ Result of the document analysis. - :attr dict metadata: (optional) Metadata that was specified with the request. + :param dict metadata: (optional) Metadata that was specified with the request. """ # The set of defined properties for the class _properties = frozenset(['metadata']) - def __init__(self, *, metadata: dict = None, **kwargs) -> None: + def __init__( + self, + *, + metadata: Optional[dict] = None, + **kwargs, + ) -> None: """ Initialize a AnalyzedResult object. @@ -3423,8 +3775,8 @@ def __init__(self, *, metadata: dict = None, **kwargs) -> None: def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': """Initialize a AnalyzedResult object from a json dictionary.""" args = {} - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @@ -3488,16 +3840,19 @@ def __ne__(self, other: 'AnalyzedResult') -> bool: return not self == other -class ClassifierFederatedModel(): +class ClassifierFederatedModel: """ An object with details for creating federated document classifier models. - :attr str field: Name of the field that contains the values from which multiple + :param str field: Name of the field that contains the values from which multiple classifier models are defined. For example, you can specify a field that lists product lines to create a separate model per product line. """ - def __init__(self, field: str) -> None: + def __init__( + self, + field: str, + ) -> None: """ Initialize a ClassifierFederatedModel object. @@ -3511,8 +3866,8 @@ def __init__(self, field: str) -> None: def from_dict(cls, _dict: Dict) -> 'ClassifierFederatedModel': """Initialize a ClassifierFederatedModel object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in ClassifierFederatedModel JSON' @@ -3550,24 +3905,27 @@ def __ne__(self, other: 'ClassifierFederatedModel') -> bool: return not self == other -class ClassifierModelEvaluation(): +class ClassifierModelEvaluation: """ An object that contains information about a trained document classifier model. - :attr ModelEvaluationMicroAverage micro_average: A micro-average aggregates the + :param ModelEvaluationMicroAverage micro_average: A micro-average aggregates the contributions of all classes to compute the average metric. Classes refers to the classification labels that are specified in the **answer_field**. - :attr ModelEvaluationMacroAverage macro_average: A macro-average computes metric - independently for each class and then takes the average. Class refers to the - classification label that is specified in the **answer_field**. - :attr List[PerClassModelEvaluation] per_class: An array of evaluation metrics, + :param ModelEvaluationMacroAverage macro_average: A macro-average computes + metric independently for each class and then takes the average. Class refers to + the classification label that is specified in the **answer_field**. + :param List[PerClassModelEvaluation] per_class: An array of evaluation metrics, one set of metrics for each class, where class refers to the classification label that is specified in the **answer_field**. """ - def __init__(self, micro_average: 'ModelEvaluationMicroAverage', - macro_average: 'ModelEvaluationMacroAverage', - per_class: List['PerClassModelEvaluation']) -> None: + def __init__( + self, + micro_average: 'ModelEvaluationMicroAverage', + macro_average: 'ModelEvaluationMacroAverage', + per_class: List['PerClassModelEvaluation'], + ) -> None: """ Initialize a ClassifierModelEvaluation object. @@ -3591,24 +3949,23 @@ def __init__(self, micro_average: 'ModelEvaluationMicroAverage', def from_dict(cls, _dict: Dict) -> 'ClassifierModelEvaluation': """Initialize a ClassifierModelEvaluation object from a json dictionary.""" args = {} - if 'micro_average' in _dict: + if (micro_average := _dict.get('micro_average')) is not None: args['micro_average'] = ModelEvaluationMicroAverage.from_dict( - _dict.get('micro_average')) + micro_average) else: raise ValueError( 'Required property \'micro_average\' not present in ClassifierModelEvaluation JSON' ) - if 'macro_average' in _dict: + if (macro_average := _dict.get('macro_average')) is not None: args['macro_average'] = ModelEvaluationMacroAverage.from_dict( - _dict.get('macro_average')) + macro_average) else: raise ValueError( 'Required property \'macro_average\' not present in ClassifierModelEvaluation JSON' ) - if 'per_class' in _dict: + if (per_class := _dict.get('per_class')) is not None: args['per_class'] = [ - PerClassModelEvaluation.from_dict(v) - for v in _dict.get('per_class') + PerClassModelEvaluation.from_dict(v) for v in per_class ] else: raise ValueError( @@ -3663,15 +4020,20 @@ def __ne__(self, other: 'ClassifierModelEvaluation') -> bool: return not self == other -class Collection(): +class Collection: """ A collection for storing documents. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: (optional) The name of the collection. + :param str collection_id: (optional) The unique identifier of the collection. + :param str name: (optional) The name of the collection. """ - def __init__(self, *, collection_id: str = None, name: str = None) -> None: + def __init__( + self, + *, + collection_id: Optional[str] = None, + name: Optional[str] = None, + ) -> None: """ Initialize a Collection object. @@ -3684,10 +4046,10 @@ def __init__(self, *, collection_id: str = None, name: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Collection': """Initialize a Collection object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (name := _dict.get('name')) is not None: + args['name'] = name return cls(**args) @classmethod @@ -3724,25 +4086,26 @@ def __ne__(self, other: 'Collection') -> bool: return not self == other -class CollectionDetails(): +class CollectionDetails: """ A collection for storing documents. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr str name: The name of the collection. - :attr str description: (optional) A description of the collection. - :attr datetime created: (optional) The date that the collection was created. - :attr str language: (optional) The language of the collection. For a list of + :param str collection_id: (optional) The unique identifier of the collection. + :param str name: The name of the collection. + :param str description: (optional) A description of the collection. + :param datetime created: (optional) The date that the collection was created. + :param str language: (optional) The language of the collection. For a list of supported languages, see the [product documentation](/docs/discovery-data?topic=discovery-data-language-support). - :attr List[CollectionEnrichment] enrichments: (optional) An array of enrichments - that are applied to this collection. To get a list of enrichments that are - available for a project, use the [List enrichments](#listenrichments) method. + :param List[CollectionEnrichment] enrichments: (optional) An array of + enrichments that are applied to this collection. To get a list of enrichments + that are available for a project, use the [List enrichments](#listenrichments) + method. If no enrichments are specified when the collection is created, the default enrichments for the project type are applied. For more information about project default settings, see the [product documentation](/docs/discovery-data?topic=discovery-data-project-defaults). - :attr CollectionDetailsSmartDocumentUnderstanding smart_document_understanding: + :param CollectionDetailsSmartDocumentUnderstanding smart_document_understanding: (optional) An object that describes the Smart Document Understanding model for a collection. """ @@ -3751,13 +4114,13 @@ def __init__( self, name: str, *, - collection_id: str = None, - description: str = None, - created: datetime = None, - language: str = None, - enrichments: List['CollectionEnrichment'] = None, - smart_document_understanding: - 'CollectionDetailsSmartDocumentUnderstanding' = None + collection_id: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + language: Optional[str] = None, + enrichments: Optional[List['CollectionEnrichment']] = None, + smart_document_understanding: Optional[ + 'CollectionDetailsSmartDocumentUnderstanding'] = None, ) -> None: """ Initialize a CollectionDetails object. @@ -3788,29 +4151,29 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'CollectionDetails': """Initialize a CollectionDetails object from a json dictionary.""" args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in CollectionDetails JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'enrichments' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (language := _dict.get('language')) is not None: + args['language'] = language + if (enrichments := _dict.get('enrichments')) is not None: args['enrichments'] = [ - CollectionEnrichment.from_dict(v) - for v in _dict.get('enrichments') + CollectionEnrichment.from_dict(v) for v in enrichments ] - if 'smart_document_understanding' in _dict: + if (smart_document_understanding := + _dict.get('smart_document_understanding')) is not None: args[ 'smart_document_understanding'] = CollectionDetailsSmartDocumentUnderstanding.from_dict( - _dict.get('smart_document_understanding')) + smart_document_understanding) return cls(**args) @classmethod @@ -3869,13 +4232,13 @@ def __ne__(self, other: 'CollectionDetails') -> bool: return not self == other -class CollectionDetailsSmartDocumentUnderstanding(): +class CollectionDetailsSmartDocumentUnderstanding: """ An object that describes the Smart Document Understanding model for a collection. - :attr bool enabled: (optional) When `true`, smart document understanding + :param bool enabled: (optional) When `true`, smart document understanding conversion is enabled for the collection. - :attr str model: (optional) Specifies the type of Smart Document Understanding + :param str model: (optional) Specifies the type of Smart Document Understanding (SDU) model that is enabled for the collection. The following types of models are supported: * `custom`: A user-trained model is applied. @@ -3891,7 +4254,12 @@ class CollectionDetailsSmartDocumentUnderstanding(): documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). """ - def __init__(self, *, enabled: bool = None, model: str = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + model: Optional[str] = None, + ) -> None: """ Initialize a CollectionDetailsSmartDocumentUnderstanding object. @@ -3920,10 +4288,10 @@ def from_dict(cls, _dict: Dict) -> 'CollectionDetailsSmartDocumentUnderstanding': """Initialize a CollectionDetailsSmartDocumentUnderstanding object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'model' in _dict: - args['model'] = _dict.get('model') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -3974,29 +4342,32 @@ class ModelEnum(str, Enum): fields* page of the product user interface. For more information, see [the product documentation](/docs/discovery-data?topic=discovery-data-configuring-fields). """ + CUSTOM = 'custom' PRE_TRAINED = 'pre_trained' TEXT_EXTRACTION = 'text_extraction' -class CollectionEnrichment(): +class CollectionEnrichment: """ An object describing an enrichment for a collection. - :attr str enrichment_id: (optional) The unique identifier of this enrichment. + :param str enrichment_id: (optional) The unique identifier of this enrichment. For more information about how to determine the ID of an enrichment, see [the product documentation](/docs/discovery-data?topic=discovery-data-manage-enrichments#enrichments-ids). - :attr List[str] fields: (optional) An array of field names that the enrichment + :param List[str] fields: (optional) An array of field names that the enrichment is applied to. If you apply an enrichment to a field from a JSON file, the data is converted to an array automatically, even if the field contains a single value. """ - def __init__(self, - *, - enrichment_id: str = None, - fields: List[str] = None) -> None: + def __init__( + self, + *, + enrichment_id: Optional[str] = None, + fields: Optional[List[str]] = None, + ) -> None: """ Initialize a CollectionEnrichment object. @@ -4017,10 +4388,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CollectionEnrichment': """Initialize a CollectionEnrichment object from a json dictionary.""" args = {} - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields return cls(**args) @classmethod @@ -4056,15 +4427,19 @@ def __ne__(self, other: 'CollectionEnrichment') -> bool: return not self == other -class Completions(): +class Completions: """ An object that contains an array of autocompletion suggestions. - :attr List[str] completions: (optional) Array of autocomplete suggestion based + :param List[str] completions: (optional) Array of autocomplete suggestion based on the provided prefix. """ - def __init__(self, *, completions: List[str] = None) -> None: + def __init__( + self, + *, + completions: Optional[List[str]] = None, + ) -> None: """ Initialize a Completions object. @@ -4077,8 +4452,8 @@ def __init__(self, *, completions: List[str] = None) -> None: def from_dict(cls, _dict: Dict) -> 'Completions': """Initialize a Completions object from a json dictionary.""" args = {} - if 'completions' in _dict: - args['completions'] = _dict.get('completions') + if (completions := _dict.get('completions')) is not None: + args['completions'] = completions return cls(**args) @classmethod @@ -4112,25 +4487,27 @@ def __ne__(self, other: 'Completions') -> bool: return not self == other -class ComponentSettingsAggregation(): +class ComponentSettingsAggregation: """ Display settings for aggregations. - :attr str name: (optional) Identifier used to map aggregation settings to + :param str name: (optional) Identifier used to map aggregation settings to aggregation configuration. - :attr str label: (optional) User-friendly alias for the aggregation. - :attr bool multiple_selections_allowed: (optional) Whether users is allowed to + :param str label: (optional) User-friendly alias for the aggregation. + :param bool multiple_selections_allowed: (optional) Whether users is allowed to select more than one of the aggregation terms. - :attr str visualization_type: (optional) Type of visualization to use when + :param str visualization_type: (optional) Type of visualization to use when rendering the aggregation. """ - def __init__(self, - *, - name: str = None, - label: str = None, - multiple_selections_allowed: bool = None, - visualization_type: str = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + label: Optional[str] = None, + multiple_selections_allowed: Optional[bool] = None, + visualization_type: Optional[str] = None, + ) -> None: """ Initialize a ComponentSettingsAggregation object. @@ -4151,15 +4528,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ComponentSettingsAggregation': """Initialize a ComponentSettingsAggregation object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'multiple_selections_allowed' in _dict: - args['multiple_selections_allowed'] = _dict.get( - 'multiple_selections_allowed') - if 'visualization_type' in _dict: - args['visualization_type'] = _dict.get('visualization_type') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (label := _dict.get('label')) is not None: + args['label'] = label + if (multiple_selections_allowed := + _dict.get('multiple_selections_allowed')) is not None: + args['multiple_selections_allowed'] = multiple_selections_allowed + if (visualization_type := _dict.get('visualization_type')) is not None: + args['visualization_type'] = visualization_type return cls(**args) @classmethod @@ -4206,24 +4583,27 @@ class VisualizationTypeEnum(str, Enum): """ Type of visualization to use when rendering the aggregation. """ + AUTO = 'auto' FACET_TABLE = 'facet_table' WORD_CLOUD = 'word_cloud' MAP = 'map' -class ComponentSettingsFieldsShown(): +class ComponentSettingsFieldsShown: """ Fields shown in the results section of the UI. - :attr ComponentSettingsFieldsShownBody body: (optional) Body label. - :attr ComponentSettingsFieldsShownTitle title: (optional) Title label. + :param ComponentSettingsFieldsShownBody body: (optional) Body label. + :param ComponentSettingsFieldsShownTitle title: (optional) Title label. """ - def __init__(self, - *, - body: 'ComponentSettingsFieldsShownBody' = None, - title: 'ComponentSettingsFieldsShownTitle' = None) -> None: + def __init__( + self, + *, + body: Optional['ComponentSettingsFieldsShownBody'] = None, + title: Optional['ComponentSettingsFieldsShownTitle'] = None, + ) -> None: """ Initialize a ComponentSettingsFieldsShown object. @@ -4237,12 +4617,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShown': """Initialize a ComponentSettingsFieldsShown object from a json dictionary.""" args = {} - if 'body' in _dict: - args['body'] = ComponentSettingsFieldsShownBody.from_dict( - _dict.get('body')) - if 'title' in _dict: - args['title'] = ComponentSettingsFieldsShownTitle.from_dict( - _dict.get('title')) + if (body := _dict.get('body')) is not None: + args['body'] = ComponentSettingsFieldsShownBody.from_dict(body) + if (title := _dict.get('title')) is not None: + args['title'] = ComponentSettingsFieldsShownTitle.from_dict(title) return cls(**args) @classmethod @@ -4284,15 +4662,20 @@ def __ne__(self, other: 'ComponentSettingsFieldsShown') -> bool: return not self == other -class ComponentSettingsFieldsShownBody(): +class ComponentSettingsFieldsShownBody: """ Body label. - :attr bool use_passage: (optional) Use the whole passage as the body. - :attr str field: (optional) Use a specific field as the title. + :param bool use_passage: (optional) Use the whole passage as the body. + :param str field: (optional) Use a specific field as the title. """ - def __init__(self, *, use_passage: bool = None, field: str = None) -> None: + def __init__( + self, + *, + use_passage: Optional[bool] = None, + field: Optional[str] = None, + ) -> None: """ Initialize a ComponentSettingsFieldsShownBody object. @@ -4306,10 +4689,10 @@ def __init__(self, *, use_passage: bool = None, field: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownBody': """Initialize a ComponentSettingsFieldsShownBody object from a json dictionary.""" args = {} - if 'use_passage' in _dict: - args['use_passage'] = _dict.get('use_passage') - if 'field' in _dict: - args['field'] = _dict.get('field') + if (use_passage := _dict.get('use_passage')) is not None: + args['use_passage'] = use_passage + if (field := _dict.get('field')) is not None: + args['field'] = field return cls(**args) @classmethod @@ -4345,14 +4728,18 @@ def __ne__(self, other: 'ComponentSettingsFieldsShownBody') -> bool: return not self == other -class ComponentSettingsFieldsShownTitle(): +class ComponentSettingsFieldsShownTitle: """ Title label. - :attr str field: (optional) Use a specific field as the title. + :param str field: (optional) Use a specific field as the title. """ - def __init__(self, *, field: str = None) -> None: + def __init__( + self, + *, + field: Optional[str] = None, + ) -> None: """ Initialize a ComponentSettingsFieldsShownTitle object. @@ -4364,8 +4751,8 @@ def __init__(self, *, field: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ComponentSettingsFieldsShownTitle': """Initialize a ComponentSettingsFieldsShownTitle object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') + if (field := _dict.get('field')) is not None: + args['field'] = field return cls(**args) @classmethod @@ -4399,28 +4786,29 @@ def __ne__(self, other: 'ComponentSettingsFieldsShownTitle') -> bool: return not self == other -class ComponentSettingsResponse(): +class ComponentSettingsResponse: """ The default component settings for this project. - :attr ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the + :param ComponentSettingsFieldsShown fields_shown: (optional) Fields shown in the results section of the UI. - :attr bool autocomplete: (optional) Whether or not autocomplete is enabled. - :attr bool structured_search: (optional) Whether or not structured search is + :param bool autocomplete: (optional) Whether or not autocomplete is enabled. + :param bool structured_search: (optional) Whether or not structured search is enabled. - :attr int results_per_page: (optional) Number or results shown per page. - :attr List[ComponentSettingsAggregation] aggregations: (optional) a list of + :param int results_per_page: (optional) Number or results shown per page. + :param List[ComponentSettingsAggregation] aggregations: (optional) a list of component setting aggregations. """ def __init__( - self, - *, - fields_shown: 'ComponentSettingsFieldsShown' = None, - autocomplete: bool = None, - structured_search: bool = None, - results_per_page: int = None, - aggregations: List['ComponentSettingsAggregation'] = None) -> None: + self, + *, + fields_shown: Optional['ComponentSettingsFieldsShown'] = None, + autocomplete: Optional[bool] = None, + structured_search: Optional[bool] = None, + results_per_page: Optional[int] = None, + aggregations: Optional[List['ComponentSettingsAggregation']] = None, + ) -> None: """ Initialize a ComponentSettingsResponse object. @@ -4444,19 +4832,18 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'ComponentSettingsResponse': """Initialize a ComponentSettingsResponse object from a json dictionary.""" args = {} - if 'fields_shown' in _dict: + if (fields_shown := _dict.get('fields_shown')) is not None: args['fields_shown'] = ComponentSettingsFieldsShown.from_dict( - _dict.get('fields_shown')) - if 'autocomplete' in _dict: - args['autocomplete'] = _dict.get('autocomplete') - if 'structured_search' in _dict: - args['structured_search'] = _dict.get('structured_search') - if 'results_per_page' in _dict: - args['results_per_page'] = _dict.get('results_per_page') - if 'aggregations' in _dict: + fields_shown) + if (autocomplete := _dict.get('autocomplete')) is not None: + args['autocomplete'] = autocomplete + if (structured_search := _dict.get('structured_search')) is not None: + args['structured_search'] = structured_search + if (results_per_page := _dict.get('results_per_page')) is not None: + args['results_per_page'] = results_per_page + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - ComponentSettingsAggregation.from_dict(v) - for v in _dict.get('aggregations') + ComponentSettingsAggregation.from_dict(v) for v in aggregations ] return cls(**args) @@ -4510,36 +4897,36 @@ def __ne__(self, other: 'ComponentSettingsResponse') -> bool: return not self == other -class CreateDocumentClassifier(): +class CreateDocumentClassifier: """ An object that manages the settings and data that is required to train a document classification model. - :attr str name: A human-readable name of the document classifier. - :attr str description: (optional) A description of the document classifier. - :attr str language: The language of the training data that is associated with + :param str name: A human-readable name of the document classifier. + :param str description: (optional) A description of the document classifier. + :param str language: The language of the training data that is associated with the document classifier. Language is specified by using the ISO 639-1 language code, such as `en` for English or `ja` for Japanese. - :attr str answer_field: The name of the field from the training and test data + :param str answer_field: The name of the field from the training and test data that contains the classification labels. - :attr List[DocumentClassifierEnrichment] enrichments: (optional) An array of + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array of enrichments to apply to the data that is used to train and test the document classifier. The output from the enrichments is used as features by the classifier to classify the document content both during training and at run time. - :attr ClassifierFederatedModel federated_classification: (optional) An object + :param ClassifierFederatedModel federated_classification: (optional) An object with details for creating federated document classifier models. """ def __init__( - self, - name: str, - language: str, - answer_field: str, - *, - description: str = None, - enrichments: List['DocumentClassifierEnrichment'] = None, - federated_classification: 'ClassifierFederatedModel' = None + self, + name: str, + language: str, + answer_field: str, + *, + description: Optional[str] = None, + enrichments: Optional[List['DocumentClassifierEnrichment']] = None, + federated_classification: Optional['ClassifierFederatedModel'] = None, ) -> None: """ Initialize a CreateDocumentClassifier object. @@ -4571,35 +4958,35 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'CreateDocumentClassifier': """Initialize a CreateDocumentClassifier object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in CreateDocumentClassifier JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in CreateDocumentClassifier JSON' ) - if 'answer_field' in _dict: - args['answer_field'] = _dict.get('answer_field') + if (answer_field := _dict.get('answer_field')) is not None: + args['answer_field'] = answer_field else: raise ValueError( 'Required property \'answer_field\' not present in CreateDocumentClassifier JSON' ) - if 'enrichments' in _dict: + if (enrichments := _dict.get('enrichments')) is not None: args['enrichments'] = [ - DocumentClassifierEnrichment.from_dict(v) - for v in _dict.get('enrichments') + DocumentClassifierEnrichment.from_dict(v) for v in enrichments ] - if 'federated_classification' in _dict: + if (federated_classification := + _dict.get('federated_classification')) is not None: args[ 'federated_classification'] = ClassifierFederatedModel.from_dict( - _dict.get('federated_classification')) + federated_classification) return cls(**args) @classmethod @@ -4656,13 +5043,13 @@ def __ne__(self, other: 'CreateDocumentClassifier') -> bool: return not self == other -class CreateEnrichment(): +class CreateEnrichment: """ Information about a specific enrichment. - :attr str name: (optional) The human readable name for this enrichment. - :attr str description: (optional) The description of this enrichment. - :attr str type: (optional) The type of this enrichment. The following types are + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. The following types are supported: * `classifier`: Creates a document classifier enrichment from a document classifier model that you create by using the [Document classifier @@ -4681,17 +5068,19 @@ class CreateEnrichment(): * Rule-based model that is created in Watson Knowledge Studio. * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. - :attr EnrichmentOptions options: (optional) An object that contains options for + :param EnrichmentOptions options: (optional) An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. """ - def __init__(self, - *, - name: str = None, - description: str = None, - type: str = None, - options: 'EnrichmentOptions' = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + type: Optional[str] = None, + options: Optional['EnrichmentOptions'] = None, + ) -> None: """ Initialize a CreateEnrichment object. @@ -4730,14 +5119,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CreateEnrichment': """Initialize a CreateEnrichment object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'options' in _dict: - args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (type := _dict.get('type')) is not None: + args['type'] = type + if (options := _dict.get('options')) is not None: + args['options'] = EnrichmentOptions.from_dict(options) return cls(**args) @classmethod @@ -4800,6 +5189,7 @@ class TypeEnum(str, Enum): * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. """ + CLASSIFIER = 'classifier' DICTIONARY = 'dictionary' REGULAR_EXPRESSION = 'regular_expression' @@ -4808,46 +5198,48 @@ class TypeEnum(str, Enum): WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' -class DefaultQueryParams(): +class DefaultQueryParams: """ Default query parameters for this project. - :attr List[str] collection_ids: (optional) An array of collection identifiers to - query. If empty or omitted all collections in the project are queried. - :attr DefaultQueryParamsPassages passages: (optional) Default settings + :param List[str] collection_ids: (optional) An array of collection identifiers + to query. If empty or omitted all collections in the project are queried. + :param DefaultQueryParamsPassages passages: (optional) Default settings configuration for passage search options. - :attr DefaultQueryParamsTableResults table_results: (optional) Default project + :param DefaultQueryParamsTableResults table_results: (optional) Default project query settings for table results. - :attr str aggregation: (optional) A string representing the default aggregation + :param str aggregation: (optional) A string representing the default aggregation query for the project. - :attr DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) + :param DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) Object that contains suggested refinement settings. **Note**: The `suggested_refinements` parameter that identified dynamic facets from the data is deprecated. - :attr bool spelling_suggestions: (optional) When `true`, a spelling suggestions + :param bool spelling_suggestions: (optional) When `true`, a spelling suggestions for the query are returned by default. - :attr bool highlight: (optional) When `true`, highlights for the query are + :param bool highlight: (optional) When `true`, highlights for the query are returned by default. - :attr int count: (optional) The number of document results returned by default. - :attr str sort: (optional) A comma separated list of document fields to sort + :param int count: (optional) The number of document results returned by default. + :param str sort: (optional) A comma separated list of document fields to sort results by default. - :attr List[str] return_: (optional) An array of field names to return in + :param List[str] return_: (optional) An array of field names to return in document results if present by default. """ - def __init__(self, - *, - collection_ids: List[str] = None, - passages: 'DefaultQueryParamsPassages' = None, - table_results: 'DefaultQueryParamsTableResults' = None, - aggregation: str = None, - suggested_refinements: - 'DefaultQueryParamsSuggestedRefinements' = None, - spelling_suggestions: bool = None, - highlight: bool = None, - count: int = None, - sort: str = None, - return_: List[str] = None) -> None: + def __init__( + self, + *, + collection_ids: Optional[List[str]] = None, + passages: Optional['DefaultQueryParamsPassages'] = None, + table_results: Optional['DefaultQueryParamsTableResults'] = None, + aggregation: Optional[str] = None, + suggested_refinements: Optional[ + 'DefaultQueryParamsSuggestedRefinements'] = None, + spelling_suggestions: Optional[bool] = None, + highlight: Optional[bool] = None, + count: Optional[int] = None, + sort: Optional[str] = None, + return_: Optional[List[str]] = None, + ) -> None: """ Initialize a DefaultQueryParams object. @@ -4890,30 +5282,31 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DefaultQueryParams': """Initialize a DefaultQueryParams object from a json dictionary.""" args = {} - if 'collection_ids' in _dict: - args['collection_ids'] = _dict.get('collection_ids') - if 'passages' in _dict: - args['passages'] = DefaultQueryParamsPassages.from_dict( - _dict.get('passages')) - if 'table_results' in _dict: + if (collection_ids := _dict.get('collection_ids')) is not None: + args['collection_ids'] = collection_ids + if (passages := _dict.get('passages')) is not None: + args['passages'] = DefaultQueryParamsPassages.from_dict(passages) + if (table_results := _dict.get('table_results')) is not None: args['table_results'] = DefaultQueryParamsTableResults.from_dict( - _dict.get('table_results')) - if 'aggregation' in _dict: - args['aggregation'] = _dict.get('aggregation') - if 'suggested_refinements' in _dict: + table_results) + if (aggregation := _dict.get('aggregation')) is not None: + args['aggregation'] = aggregation + if (suggested_refinements := + _dict.get('suggested_refinements')) is not None: args[ 'suggested_refinements'] = DefaultQueryParamsSuggestedRefinements.from_dict( - _dict.get('suggested_refinements')) - if 'spelling_suggestions' in _dict: - args['spelling_suggestions'] = _dict.get('spelling_suggestions') - if 'highlight' in _dict: - args['highlight'] = _dict.get('highlight') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'sort' in _dict: - args['sort'] = _dict.get('sort') - if 'return' in _dict: - args['return_'] = _dict.get('return') + suggested_refinements) + if (spelling_suggestions := + _dict.get('spelling_suggestions')) is not None: + args['spelling_suggestions'] = spelling_suggestions + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = highlight + if (count := _dict.get('count')) is not None: + args['count'] = count + if (sort := _dict.get('sort')) is not None: + args['sort'] = sort + if (return_ := _dict.get('return')) is not None: + args['return_'] = return_ return cls(**args) @classmethod @@ -4978,32 +5371,34 @@ def __ne__(self, other: 'DefaultQueryParams') -> bool: return not self == other -class DefaultQueryParamsPassages(): +class DefaultQueryParamsPassages: """ Default settings configuration for passage search options. - :attr bool enabled: (optional) When `true`, a passage search is performed by + :param bool enabled: (optional) When `true`, a passage search is performed by default. - :attr int count: (optional) The number of passages to return. - :attr List[str] fields: (optional) An array of field names to perform the + :param int count: (optional) The number of passages to return. + :param List[str] fields: (optional) An array of field names to perform the passage search on. - :attr int characters: (optional) The approximate number of characters that each + :param int characters: (optional) The approximate number of characters that each returned passage will contain. - :attr bool per_document: (optional) When `true` the number of passages that can + :param bool per_document: (optional) When `true` the number of passages that can be returned from a single document is restricted to the *max_per_document* value. - :attr int max_per_document: (optional) The default maximum number of passages + :param int max_per_document: (optional) The default maximum number of passages that can be taken from a single document as the result of a passage query. """ - def __init__(self, - *, - enabled: bool = None, - count: int = None, - fields: List[str] = None, - characters: int = None, - per_document: bool = None, - max_per_document: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + fields: Optional[List[str]] = None, + characters: Optional[int] = None, + per_document: Optional[bool] = None, + max_per_document: Optional[int] = None, + ) -> None: """ Initialize a DefaultQueryParamsPassages object. @@ -5032,18 +5427,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsPassages': """Initialize a DefaultQueryParamsPassages object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') - if 'characters' in _dict: - args['characters'] = _dict.get('characters') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') - if 'max_per_document' in _dict: - args['max_per_document'] = _dict.get('max_per_document') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields + if (characters := _dict.get('characters')) is not None: + args['characters'] = characters + if (per_document := _dict.get('per_document')) is not None: + args['per_document'] = per_document + if (max_per_document := _dict.get('max_per_document')) is not None: + args['max_per_document'] = max_per_document return cls(**args) @classmethod @@ -5088,19 +5483,24 @@ def __ne__(self, other: 'DefaultQueryParamsPassages') -> bool: return not self == other -class DefaultQueryParamsSuggestedRefinements(): +class DefaultQueryParamsSuggestedRefinements: """ Object that contains suggested refinement settings. **Note**: The `suggested_refinements` parameter that identified dynamic facets from the data is deprecated. - :attr bool enabled: (optional) When `true`, suggested refinements for the query + :param bool enabled: (optional) When `true`, suggested refinements for the query are returned by default. - :attr int count: (optional) The number of suggested refinements to return by + :param int count: (optional) The number of suggested refinements to return by default. """ - def __init__(self, *, enabled: bool = None, count: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a DefaultQueryParamsSuggestedRefinements object. @@ -5116,10 +5516,10 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsSuggestedRefinements': """Initialize a DefaultQueryParamsSuggestedRefinements object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -5155,22 +5555,24 @@ def __ne__(self, other: 'DefaultQueryParamsSuggestedRefinements') -> bool: return not self == other -class DefaultQueryParamsTableResults(): +class DefaultQueryParamsTableResults: """ Default project query settings for table results. - :attr bool enabled: (optional) When `true`, a table results for the query are + :param bool enabled: (optional) When `true`, a table results for the query are returned by default. - :attr int count: (optional) The number of table results to return by default. - :attr int per_document: (optional) The number of table results to include in + :param int count: (optional) The number of table results to return by default. + :param int per_document: (optional) The number of table results to include in each result document. """ - def __init__(self, - *, - enabled: bool = None, - count: int = None, - per_document: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + per_document: Optional[int] = None, + ) -> None: """ Initialize a DefaultQueryParamsTableResults object. @@ -5189,12 +5591,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DefaultQueryParamsTableResults': """Initialize a DefaultQueryParamsTableResults object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count + if (per_document := _dict.get('per_document')) is not None: + args['per_document'] = per_document return cls(**args) @classmethod @@ -5232,16 +5634,21 @@ def __ne__(self, other: 'DefaultQueryParamsTableResults') -> bool: return not self == other -class DeleteDocumentResponse(): +class DeleteDocumentResponse: """ Information returned when a document is deleted. - :attr str document_id: (optional) The unique identifier of the document. - :attr str status: (optional) Status of the document. A deleted document has the + :param str document_id: (optional) The unique identifier of the document. + :param str status: (optional) Status of the document. A deleted document has the status deleted. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a DeleteDocumentResponse object. @@ -5256,10 +5663,10 @@ def __init__(self, *, document_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': """Initialize a DeleteDocumentResponse object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -5298,22 +5705,28 @@ class StatusEnum(str, Enum): """ Status of the document. A deleted document has the status deleted. """ + DELETED = 'deleted' -class DocumentAccepted(): +class DocumentAccepted: """ Information returned after an uploaded document is accepted. - :attr str document_id: (optional) The unique identifier of the ingested + :param str document_id: (optional) The unique identifier of the ingested document. - :attr str status: (optional) Status of the document in the ingestion process. A + :param str status: (optional) Status of the document in the ingestion process. A status of `processing` is returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. """ - def __init__(self, *, document_id: str = None, status: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a DocumentAccepted object. @@ -5331,10 +5744,10 @@ def __init__(self, *, document_id: str = None, status: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': """Initialize a DocumentAccepted object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -5375,26 +5788,29 @@ class StatusEnum(str, Enum): returned for documents that are ingested with a *version* date before `2019-01-01`. The `pending` status is returned for all others. """ + PROCESSING = 'processing' PENDING = 'pending' -class DocumentAttribute(): +class DocumentAttribute: """ List of document attributes. - :attr str type: (optional) The type of attribute. - :attr str text: (optional) The text associated with the attribute. - :attr TableElementLocation location: (optional) The numeric location of the + :param str type: (optional) The type of attribute. + :param str text: (optional) The text associated with the attribute. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ - def __init__(self, - *, - type: str = None, - text: str = None, - location: 'TableElementLocation' = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + text: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + ) -> None: """ Initialize a DocumentAttribute object. @@ -5412,13 +5828,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentAttribute': """Initialize a DocumentAttribute object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) return cls(**args) @classmethod @@ -5459,53 +5874,53 @@ def __ne__(self, other: 'DocumentAttribute') -> bool: return not self == other -class DocumentClassifier(): +class DocumentClassifier: """ Information about a document classifier. - :attr str classifier_id: (optional) A unique identifier of the document + :param str classifier_id: (optional) A unique identifier of the document classifier. - :attr str name: A human-readable name of the document classifier. - :attr str description: (optional) A description of the document classifier. - :attr datetime created: (optional) The date that the document classifier was + :param str name: A human-readable name of the document classifier. + :param str description: (optional) A description of the document classifier. + :param datetime created: (optional) The date that the document classifier was created. - :attr str language: (optional) The language of the training data that is + :param str language: (optional) The language of the training data that is associated with the document classifier. Language is specified by using the ISO 639-1 language code, such as `en` for English or `ja` for Japanese. - :attr List[DocumentClassifierEnrichment] enrichments: (optional) An array of + :param List[DocumentClassifierEnrichment] enrichments: (optional) An array of enrichments to apply to the data that is used to train and test the document classifier. The output from the enrichments is used as features by the classifier to classify the document content both during training and at run time. - :attr List[str] recognized_fields: (optional) An array of fields that are used + :param List[str] recognized_fields: (optional) An array of fields that are used to train the document classifier. The same set of fields must exist in the training data, the test data, and the documents where the resulting document classifier enrichment is applied at run time. - :attr str answer_field: (optional) The name of the field from the training and + :param str answer_field: (optional) The name of the field from the training and test data that contains the classification labels. - :attr str training_data_file: (optional) Name of the CSV file with training data - that is used to train the document classifier. - :attr str test_data_file: (optional) Name of the CSV file with data that is used - to test the document classifier. If no test data is provided, a subset of the - training data is used for testing purposes. - :attr ClassifierFederatedModel federated_classification: (optional) An object + :param str training_data_file: (optional) Name of the CSV file with training + data that is used to train the document classifier. + :param str test_data_file: (optional) Name of the CSV file with data that is + used to test the document classifier. If no test data is provided, a subset of + the training data is used for testing purposes. + :param ClassifierFederatedModel federated_classification: (optional) An object with details for creating federated document classifier models. """ def __init__( - self, - name: str, - *, - classifier_id: str = None, - description: str = None, - created: datetime = None, - language: str = None, - enrichments: List['DocumentClassifierEnrichment'] = None, - recognized_fields: List[str] = None, - answer_field: str = None, - training_data_file: str = None, - test_data_file: str = None, - federated_classification: 'ClassifierFederatedModel' = None + self, + name: str, + *, + classifier_id: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + language: Optional[str] = None, + enrichments: Optional[List['DocumentClassifierEnrichment']] = None, + recognized_fields: Optional[List[str]] = None, + answer_field: Optional[str] = None, + training_data_file: Optional[str] = None, + test_data_file: Optional[str] = None, + federated_classification: Optional['ClassifierFederatedModel'] = None, ) -> None: """ Initialize a DocumentClassifier object. @@ -5551,37 +5966,37 @@ def __init__( def from_dict(cls, _dict: Dict) -> 'DocumentClassifier': """Initialize a DocumentClassifier object from a json dictionary.""" args = {} - if 'classifier_id' in _dict: - args['classifier_id'] = _dict.get('classifier_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (classifier_id := _dict.get('classifier_id')) is not None: + args['classifier_id'] = classifier_id + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in DocumentClassifier JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'enrichments' in _dict: + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (language := _dict.get('language')) is not None: + args['language'] = language + if (enrichments := _dict.get('enrichments')) is not None: args['enrichments'] = [ - DocumentClassifierEnrichment.from_dict(v) - for v in _dict.get('enrichments') + DocumentClassifierEnrichment.from_dict(v) for v in enrichments ] - if 'recognized_fields' in _dict: - args['recognized_fields'] = _dict.get('recognized_fields') - if 'answer_field' in _dict: - args['answer_field'] = _dict.get('answer_field') - if 'training_data_file' in _dict: - args['training_data_file'] = _dict.get('training_data_file') - if 'test_data_file' in _dict: - args['test_data_file'] = _dict.get('test_data_file') - if 'federated_classification' in _dict: + if (recognized_fields := _dict.get('recognized_fields')) is not None: + args['recognized_fields'] = recognized_fields + if (answer_field := _dict.get('answer_field')) is not None: + args['answer_field'] = answer_field + if (training_data_file := _dict.get('training_data_file')) is not None: + args['training_data_file'] = training_data_file + if (test_data_file := _dict.get('test_data_file')) is not None: + args['test_data_file'] = test_data_file + if (federated_classification := + _dict.get('federated_classification')) is not None: args[ 'federated_classification'] = ClassifierFederatedModel.from_dict( - _dict.get('federated_classification')) + federated_classification) return cls(**args) @classmethod @@ -5652,16 +6067,21 @@ def __ne__(self, other: 'DocumentClassifier') -> bool: return not self == other -class DocumentClassifierEnrichment(): +class DocumentClassifierEnrichment: """ An object that describes enrichments that are applied to the training and test data that is used by the document classifier. - :attr str enrichment_id: A unique identifier of the enrichment. - :attr List[str] fields: An array of field names where the enrichment is applied. + :param str enrichment_id: A unique identifier of the enrichment. + :param List[str] fields: An array of field names where the enrichment is + applied. """ - def __init__(self, enrichment_id: str, fields: List[str]) -> None: + def __init__( + self, + enrichment_id: str, + fields: List[str], + ) -> None: """ Initialize a DocumentClassifierEnrichment object. @@ -5676,14 +6096,14 @@ def __init__(self, enrichment_id: str, fields: List[str]) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentClassifierEnrichment': """Initialize a DocumentClassifierEnrichment object from a json dictionary.""" args = {} - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id else: raise ValueError( 'Required property \'enrichment_id\' not present in DocumentClassifierEnrichment JSON' ) - if 'fields' in _dict: - args['fields'] = _dict.get('fields') + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields else: raise ValueError( 'Required property \'fields\' not present in DocumentClassifierEnrichment JSON' @@ -5723,46 +6143,48 @@ def __ne__(self, other: 'DocumentClassifierEnrichment') -> bool: return not self == other -class DocumentClassifierModel(): +class DocumentClassifierModel: """ Information about a document classifier model. - :attr str model_id: (optional) A unique identifier of the document classifier + :param str model_id: (optional) A unique identifier of the document classifier model. - :attr str name: A human-readable name of the document classifier model. - :attr str description: (optional) A description of the document classifier + :param str name: A human-readable name of the document classifier model. + :param str description: (optional) A description of the document classifier model. - :attr datetime created: (optional) The date that the document classifier model + :param datetime created: (optional) The date that the document classifier model was created. - :attr datetime updated: (optional) The date that the document classifier model + :param datetime updated: (optional) The date that the document classifier model was last updated. - :attr str training_data_file: (optional) Name of the CSV file that contains the + :param str training_data_file: (optional) Name of the CSV file that contains the training data that is used to train the document classifier model. - :attr str test_data_file: (optional) Name of the CSV file that contains data + :param str test_data_file: (optional) Name of the CSV file that contains data that is used to test the document classifier model. If no test data is provided, a subset of the training data is used for testing purposes. - :attr str status: (optional) The status of the training run. - :attr ClassifierModelEvaluation evaluation: (optional) An object that contains + :param str status: (optional) The status of the training run. + :param ClassifierModelEvaluation evaluation: (optional) An object that contains information about a trained document classifier model. - :attr str enrichment_id: (optional) A unique identifier of the enrichment that + :param str enrichment_id: (optional) A unique identifier of the enrichment that is generated by this document classifier model. - :attr datetime deployed_at: (optional) The date that the document classifier + :param datetime deployed_at: (optional) The date that the document classifier model was deployed. """ - def __init__(self, - name: str, - *, - model_id: str = None, - description: str = None, - created: datetime = None, - updated: datetime = None, - training_data_file: str = None, - test_data_file: str = None, - status: str = None, - evaluation: 'ClassifierModelEvaluation' = None, - enrichment_id: str = None, - deployed_at: datetime = None) -> None: + def __init__( + self, + name: str, + *, + model_id: Optional[str] = None, + description: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + training_data_file: Optional[str] = None, + test_data_file: Optional[str] = None, + status: Optional[str] = None, + evaluation: Optional['ClassifierModelEvaluation'] = None, + enrichment_id: Optional[str] = None, + deployed_at: Optional[datetime] = None, + ) -> None: """ Initialize a DocumentClassifierModel object. @@ -5797,33 +6219,32 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentClassifierModel': """Initialize a DocumentClassifierModel object from a json dictionary.""" args = {} - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in DocumentClassifierModel JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'training_data_file' in _dict: - args['training_data_file'] = _dict.get('training_data_file') - if 'test_data_file' in _dict: - args['test_data_file'] = _dict.get('test_data_file') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'evaluation' in _dict: - args['evaluation'] = ClassifierModelEvaluation.from_dict( - _dict.get('evaluation')) - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') - if 'deployed_at' in _dict: - args['deployed_at'] = string_to_datetime(_dict.get('deployed_at')) + if (description := _dict.get('description')) is not None: + args['description'] = description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (training_data_file := _dict.get('training_data_file')) is not None: + args['training_data_file'] = training_data_file + if (test_data_file := _dict.get('test_data_file')) is not None: + args['test_data_file'] = test_data_file + if (status := _dict.get('status')) is not None: + args['status'] = status + if (evaluation := _dict.get('evaluation')) is not None: + args['evaluation'] = ClassifierModelEvaluation.from_dict(evaluation) + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + if (deployed_at := _dict.get('deployed_at')) is not None: + args['deployed_at'] = string_to_datetime(deployed_at) return cls(**args) @classmethod @@ -5887,22 +6308,25 @@ class StatusEnum(str, Enum): """ The status of the training run. """ + TRAINING = 'training' AVAILABLE = 'available' FAILED = 'failed' -class DocumentClassifierModels(): +class DocumentClassifierModels: """ An object that contains a list of document classifier model definitions. - :attr List[DocumentClassifierModel] models: (optional) An array of document + :param List[DocumentClassifierModel] models: (optional) An array of document classifier model definitions. """ - def __init__(self, - *, - models: List['DocumentClassifierModel'] = None) -> None: + def __init__( + self, + *, + models: Optional[List['DocumentClassifierModel']] = None, + ) -> None: """ Initialize a DocumentClassifierModels object. @@ -5915,10 +6339,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentClassifierModels': """Initialize a DocumentClassifierModels object from a json dictionary.""" args = {} - if 'models' in _dict: + if (models := _dict.get('models')) is not None: args['models'] = [ - DocumentClassifierModel.from_dict(v) - for v in _dict.get('models') + DocumentClassifierModel.from_dict(v) for v in models ] return cls(**args) @@ -5959,17 +6382,19 @@ def __ne__(self, other: 'DocumentClassifierModels') -> bool: return not self == other -class DocumentClassifiers(): +class DocumentClassifiers: """ An object that contains a list of document classifier definitions. - :attr List[DocumentClassifier] classifiers: (optional) An array of document + :param List[DocumentClassifier] classifiers: (optional) An array of document classifier definitions. """ - def __init__(self, - *, - classifiers: List['DocumentClassifier'] = None) -> None: + def __init__( + self, + *, + classifiers: Optional[List['DocumentClassifier']] = None, + ) -> None: """ Initialize a DocumentClassifiers object. @@ -5982,10 +6407,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentClassifiers': """Initialize a DocumentClassifiers object from a json dictionary.""" args = {} - if 'classifiers' in _dict: + if (classifiers := _dict.get('classifiers')) is not None: args['classifiers'] = [ - DocumentClassifier.from_dict(v) - for v in _dict.get('classifiers') + DocumentClassifier.from_dict(v) for v in classifiers ] return cls(**args) @@ -6026,51 +6450,53 @@ def __ne__(self, other: 'DocumentClassifiers') -> bool: return not self == other -class DocumentDetails(): +class DocumentDetails: """ Information about a document. - :attr str document_id: (optional) The unique identifier of the document. - :attr datetime created: (optional) Date and time that the document is added to + :param str document_id: (optional) The unique identifier of the document. + :param datetime created: (optional) Date and time that the document is added to the collection. For a child document, the date and time when the process that generates the child document runs. The date-time format is `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :attr datetime updated: (optional) Date and time that the document is finished + :param datetime updated: (optional) Date and time that the document is finished being processed and is indexed. This date changes whenever the document is reprocessed, including for enrichment changes. The date-time format is `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :attr str status: (optional) The status of the ingestion of the document. The + :param str status: (optional) The status of the ingestion of the document. The possible values are: * `available`: Ingestion is finished and the document is indexed. * `failed`: Ingestion is finished, but the document is not indexed because of an error. * `pending`: The document is uploaded, but the ingestion process is not started. * `processing`: Ingestion is in progress. - :attr List[Notice] notices: (optional) Array of JSON objects for notices, + :param List[Notice] notices: (optional) Array of JSON objects for notices, meaning warning or error messages, that are produced by the document ingestion process. The array does not include notices that are produced for child documents that are generated when a document is processed. - :attr DocumentDetailsChildren children: (optional) Information about the child + :param DocumentDetailsChildren children: (optional) Information about the child documents that are generated from a single document during ingestion or other processing. - :attr str filename: (optional) Name of the original source file (if available). - :attr str file_type: (optional) The type of the original source file, such as + :param str filename: (optional) Name of the original source file (if available). + :param str file_type: (optional) The type of the original source file, such as `csv`, `excel`, `html`, `json`, `pdf`, `text`, `word`, and so on. - :attr str sha256: (optional) The SHA-256 hash of the original source file. The + :param str sha256: (optional) The SHA-256 hash of the original source file. The hash is formatted as a hexadecimal string. """ - def __init__(self, - *, - document_id: str = None, - created: datetime = None, - updated: datetime = None, - status: str = None, - notices: List['Notice'] = None, - children: 'DocumentDetailsChildren' = None, - filename: str = None, - file_type: str = None, - sha256: str = None) -> None: + def __init__( + self, + *, + document_id: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + status: Optional[str] = None, + notices: Optional[List['Notice']] = None, + children: Optional['DocumentDetailsChildren'] = None, + filename: Optional[str] = None, + file_type: Optional[str] = None, + sha256: Optional[str] = None, + ) -> None: """ Initialize a DocumentDetails object. @@ -6110,27 +6536,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentDetails': """Initialize a DocumentDetails object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] - if 'children' in _dict: - args['children'] = DocumentDetailsChildren.from_dict( - _dict.get('children')) - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - if 'file_type' in _dict: - args['file_type'] = _dict.get('file_type') - if 'sha256' in _dict: - args['sha256'] = _dict.get('sha256') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (children := _dict.get('children')) is not None: + args['children'] = DocumentDetailsChildren.from_dict(children) + if (filename := _dict.get('filename')) is not None: + args['filename'] = filename + if (file_type := _dict.get('file_type')) is not None: + args['file_type'] = file_type + if (sha256 := _dict.get('sha256')) is not None: + args['sha256'] = sha256 return cls(**args) @classmethod @@ -6198,24 +6621,30 @@ class StatusEnum(str, Enum): * `pending`: The document is uploaded, but the ingestion process is not started. * `processing`: Ingestion is in progress. """ + AVAILABLE = 'available' FAILED = 'failed' PENDING = 'pending' PROCESSING = 'processing' -class DocumentDetailsChildren(): +class DocumentDetailsChildren: """ Information about the child documents that are generated from a single document during ingestion or other processing. - :attr bool have_notices: (optional) Indicates whether the child documents have + :param bool have_notices: (optional) Indicates whether the child documents have any notices. The value is `false` if the document does not have child documents. - :attr int count: (optional) Number of child documents. The value is `0` when + :param int count: (optional) Number of child documents. The value is `0` when processing of the document doesn't generate any child documents. """ - def __init__(self, *, have_notices: bool = None, count: int = None) -> None: + def __init__( + self, + *, + have_notices: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a DocumentDetailsChildren object. @@ -6232,10 +6661,10 @@ def __init__(self, *, have_notices: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentDetailsChildren': """Initialize a DocumentDetailsChildren object from a json dictionary.""" args = {} - if 'have_notices' in _dict: - args['have_notices'] = _dict.get('have_notices') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (have_notices := _dict.get('have_notices')) is not None: + args['have_notices'] = have_notices + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -6271,26 +6700,28 @@ def __ne__(self, other: 'DocumentDetailsChildren') -> bool: return not self == other -class Enrichment(): +class Enrichment: """ Information about a specific enrichment. - :attr str enrichment_id: (optional) The unique identifier of this enrichment. - :attr str name: (optional) The human readable name for this enrichment. - :attr str description: (optional) The description of this enrichment. - :attr str type: (optional) The type of this enrichment. - :attr EnrichmentOptions options: (optional) An object that contains options for + :param str enrichment_id: (optional) The unique identifier of this enrichment. + :param str name: (optional) The human readable name for this enrichment. + :param str description: (optional) The description of this enrichment. + :param str type: (optional) The type of this enrichment. + :param EnrichmentOptions options: (optional) An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. """ - def __init__(self, - *, - enrichment_id: str = None, - name: str = None, - description: str = None, - type: str = None, - options: 'EnrichmentOptions' = None) -> None: + def __init__( + self, + *, + enrichment_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + type: Optional[str] = None, + options: Optional['EnrichmentOptions'] = None, + ) -> None: """ Initialize a Enrichment object. @@ -6312,16 +6743,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Enrichment': """Initialize a Enrichment object from a json dictionary.""" args = {} - if 'enrichment_id' in _dict: - args['enrichment_id'] = _dict.get('enrichment_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'options' in _dict: - args['options'] = EnrichmentOptions.from_dict(_dict.get('options')) + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (type := _dict.get('type')) is not None: + args['type'] = type + if (options := _dict.get('options')) is not None: + args['options'] = EnrichmentOptions.from_dict(options) return cls(**args) @classmethod @@ -6370,6 +6801,7 @@ class TypeEnum(str, Enum): """ The type of this enrichment. """ + PART_OF_SPEECH = 'part_of_speech' SENTIMENT = 'sentiment' NATURAL_LANGUAGE_UNDERSTANDING = 'natural_language_understanding' @@ -6381,37 +6813,37 @@ class TypeEnum(str, Enum): CLASSIFIER = 'classifier' -class EnrichmentOptions(): +class EnrichmentOptions: """ An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. - :attr List[str] languages: (optional) An array of supported languages for this + :param List[str] languages: (optional) An array of supported languages for this enrichment. When creating an enrichment, only specify a language that is used by the model or in the dictionary. Required when **type** is `dictionary`. Optional when **type** is `rule_based`. Not valid when creating any other type of enrichment. - :attr str entity_type: (optional) The name of the entity type. This value is + :param str entity_type: (optional) The name of the entity type. This value is used as the field name in the index. Required when **type** is `dictionary` or `regular_expression`. Not valid when creating any other type of enrichment. - :attr str regular_expression: (optional) The regular expression to apply for + :param str regular_expression: (optional) The regular expression to apply for this enrichment. Required when **type** is `regular_expression`. Not valid when creating any other type of enrichment. - :attr str result_field: (optional) The name of the result document field that + :param str result_field: (optional) The name of the result document field that this enrichment creates. Required when **type** is `rule_based` or `classifier`. Not valid when creating any other type of enrichment. - :attr str classifier_id: (optional) A unique identifier of the document + :param str classifier_id: (optional) A unique identifier of the document classifier. Required when **type** is `classifier`. Not valid when creating any other type of enrichment. - :attr str model_id: (optional) A unique identifier of the document classifier + :param str model_id: (optional) A unique identifier of the document classifier model. Required when **type** is `classifier`. Not valid when creating any other type of enrichment. - :attr float confidence_threshold: (optional) Specifies a threshold. Only classes - with evaluation confidence scores that are higher than the specified threshold - are included in the output. Optional when **type** is `classifier`. Not valid - when creating any other type of enrichment. - :attr int top_k: (optional) Evaluates only the classes that fall in the top set + :param float confidence_threshold: (optional) Specifies a threshold. Only + classes with evaluation confidence scores that are higher than the specified + threshold are included in the output. Optional when **type** is `classifier`. + Not valid when creating any other type of enrichment. + :param int top_k: (optional) Evaluates only the classes that fall in the top set of results when ranked by confidence. For example, if set to `5`, then the top five classes for each document are evaluated. If set to 0, the **confidence_threshold** is used to determine the predicted classes. Optional @@ -6419,16 +6851,18 @@ class EnrichmentOptions(): enrichment. """ - def __init__(self, - *, - languages: List[str] = None, - entity_type: str = None, - regular_expression: str = None, - result_field: str = None, - classifier_id: str = None, - model_id: str = None, - confidence_threshold: float = None, - top_k: int = None) -> None: + def __init__( + self, + *, + languages: Optional[List[str]] = None, + entity_type: Optional[str] = None, + regular_expression: Optional[str] = None, + result_field: Optional[str] = None, + classifier_id: Optional[str] = None, + model_id: Optional[str] = None, + confidence_threshold: Optional[float] = None, + top_k: Optional[int] = None, + ) -> None: """ Initialize a EnrichmentOptions object. @@ -6477,22 +6911,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': """Initialize a EnrichmentOptions object from a json dictionary.""" args = {} - if 'languages' in _dict: - args['languages'] = _dict.get('languages') - if 'entity_type' in _dict: - args['entity_type'] = _dict.get('entity_type') - if 'regular_expression' in _dict: - args['regular_expression'] = _dict.get('regular_expression') - if 'result_field' in _dict: - args['result_field'] = _dict.get('result_field') - if 'classifier_id' in _dict: - args['classifier_id'] = _dict.get('classifier_id') - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'confidence_threshold' in _dict: - args['confidence_threshold'] = _dict.get('confidence_threshold') - if 'top_k' in _dict: - args['top_k'] = _dict.get('top_k') + if (languages := _dict.get('languages')) is not None: + args['languages'] = languages + if (entity_type := _dict.get('entity_type')) is not None: + args['entity_type'] = entity_type + if (regular_expression := _dict.get('regular_expression')) is not None: + args['regular_expression'] = regular_expression + if (result_field := _dict.get('result_field')) is not None: + args['result_field'] = result_field + if (classifier_id := _dict.get('classifier_id')) is not None: + args['classifier_id'] = classifier_id + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + if (confidence_threshold := + _dict.get('confidence_threshold')) is not None: + args['confidence_threshold'] = confidence_threshold + if (top_k := _dict.get('top_k')) is not None: + args['top_k'] = top_k return cls(**args) @classmethod @@ -6543,15 +6978,19 @@ def __ne__(self, other: 'EnrichmentOptions') -> bool: return not self == other -class Enrichments(): +class Enrichments: """ An object that contains an array of enrichment definitions. - :attr List[Enrichment] enrichments: (optional) An array of enrichment + :param List[Enrichment] enrichments: (optional) An array of enrichment definitions. """ - def __init__(self, *, enrichments: List['Enrichment'] = None) -> None: + def __init__( + self, + *, + enrichments: Optional[List['Enrichment']] = None, + ) -> None: """ Initialize a Enrichments object. @@ -6564,10 +7003,8 @@ def __init__(self, *, enrichments: List['Enrichment'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'Enrichments': """Initialize a Enrichments object from a json dictionary.""" args = {} - if 'enrichments' in _dict: - args['enrichments'] = [ - Enrichment.from_dict(v) for v in _dict.get('enrichments') - ] + if (enrichments := _dict.get('enrichments')) is not None: + args['enrichments'] = [Enrichment.from_dict(v) for v in enrichments] return cls(**args) @classmethod @@ -6607,7 +7044,7 @@ def __ne__(self, other: 'Enrichments') -> bool: return not self == other -class Expansion(): +class Expansion: """ An expansion definition. Each object respresents one set of expandable strings. For example, you could have expansions for the word `hot` in one object, and expansions @@ -6616,17 +7053,19 @@ class Expansion(): * Multiword terms are supported only in bidirectional expansions. * Do not specify a term that is specified in the stop words list for the collection. - :attr List[str] input_terms: (optional) A list of terms that will be expanded + :param List[str] input_terms: (optional) A list of terms that will be expanded for this expansion. If specified, only the items in this list are expanded. - :attr List[str] expanded_terms: A list of terms that this expansion will be + :param List[str] expanded_terms: A list of terms that this expansion will be expanded to. If specified without **input_terms**, the list also functions as the input term list. """ - def __init__(self, - expanded_terms: List[str], - *, - input_terms: List[str] = None) -> None: + def __init__( + self, + expanded_terms: List[str], + *, + input_terms: Optional[List[str]] = None, + ) -> None: """ Initialize a Expansion object. @@ -6644,10 +7083,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Expansion': """Initialize a Expansion object from a json dictionary.""" args = {} - if 'input_terms' in _dict: - args['input_terms'] = _dict.get('input_terms') - if 'expanded_terms' in _dict: - args['expanded_terms'] = _dict.get('expanded_terms') + if (input_terms := _dict.get('input_terms')) is not None: + args['input_terms'] = input_terms + if (expanded_terms := _dict.get('expanded_terms')) is not None: + args['expanded_terms'] = expanded_terms else: raise ValueError( 'Required property \'expanded_terms\' not present in Expansion JSON' @@ -6687,11 +7126,11 @@ def __ne__(self, other: 'Expansion') -> bool: return not self == other -class Expansions(): +class Expansions: """ The query expansion definitions for the specified collection. - :attr List[Expansion] expansions: An array of query expansion definitions. + :param List[Expansion] expansions: An array of query expansion definitions. Each object in the **expansions** array represents a term or set of terms that will be expanded into other terms. Each expansion object can be configured as `bidirectional` or `unidirectional`. @@ -6705,7 +7144,10 @@ class Expansions(): repeat the input term in the expanded terms list. """ - def __init__(self, expansions: List['Expansion']) -> None: + def __init__( + self, + expansions: List['Expansion'], + ) -> None: """ Initialize a Expansions object. @@ -6729,10 +7171,8 @@ def __init__(self, expansions: List['Expansion']) -> None: def from_dict(cls, _dict: Dict) -> 'Expansions': """Initialize a Expansions object from a json dictionary.""" args = {} - if 'expansions' in _dict: - args['expansions'] = [ - Expansion.from_dict(v) for v in _dict.get('expansions') - ] + if (expansions := _dict.get('expansions')) is not None: + args['expansions'] = [Expansion.from_dict(v) for v in expansions] else: raise ValueError( 'Required property \'expansions\' not present in Expansions JSON' @@ -6776,21 +7216,23 @@ def __ne__(self, other: 'Expansions') -> bool: return not self == other -class Field(): +class Field: """ Object that contains field details. - :attr str field: (optional) The name of the field. - :attr str type: (optional) The type of the field. - :attr str collection_id: (optional) The collection Id of the collection where + :param str field: (optional) The name of the field. + :param str type: (optional) The type of the field. + :param str collection_id: (optional) The collection Id of the collection where the field was found. """ - def __init__(self, - *, - field: str = None, - type: str = None, - collection_id: str = None) -> None: + def __init__( + self, + *, + field: Optional[str] = None, + type: Optional[str] = None, + collection_id: Optional[str] = None, + ) -> None: """ Initialize a Field object. @@ -6803,12 +7245,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Field': """Initialize a Field object from a json dictionary.""" args = {} - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (field := _dict.get('field')) is not None: + args['field'] = field + if (type := _dict.get('type')) is not None: + args['type'] = type + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id return cls(**args) @classmethod @@ -6850,6 +7292,7 @@ class TypeEnum(str, Enum): """ The type of the field. """ + NESTED = 'nested' STRING = 'string' DATE = 'date' @@ -6863,15 +7306,19 @@ class TypeEnum(str, Enum): BINARY = 'binary' -class ListCollectionsResponse(): +class ListCollectionsResponse: """ Response object that contains an array of collection details. - :attr List[Collection] collections: (optional) An array that contains + :param List[Collection] collections: (optional) An array that contains information about each collection in the project. """ - def __init__(self, *, collections: List['Collection'] = None) -> None: + def __init__( + self, + *, + collections: Optional[List['Collection']] = None, + ) -> None: """ Initialize a ListCollectionsResponse object. @@ -6884,10 +7331,8 @@ def __init__(self, *, collections: List['Collection'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': """Initialize a ListCollectionsResponse object from a json dictionary.""" args = {} - if 'collections' in _dict: - args['collections'] = [ - Collection.from_dict(v) for v in _dict.get('collections') - ] + if (collections := _dict.get('collections')) is not None: + args['collections'] = [Collection.from_dict(v) for v in collections] return cls(**args) @classmethod @@ -6927,22 +7372,24 @@ def __ne__(self, other: 'ListCollectionsResponse') -> bool: return not self == other -class ListDocumentsResponse(): +class ListDocumentsResponse: """ Response object that contains an array of documents. - :attr int matching_results: (optional) The number of matching results for the + :param int matching_results: (optional) The number of matching results for the document query. - :attr List[DocumentDetails] documents: (optional) An array that lists the + :param List[DocumentDetails] documents: (optional) An array that lists the documents in a collection. Only the document ID of each document is returned in the list. You can use the [Get document](#getdocument) method to get more information about an individual document. """ - def __init__(self, - *, - matching_results: int = None, - documents: List['DocumentDetails'] = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + documents: Optional[List['DocumentDetails']] = None, + ) -> None: """ Initialize a ListDocumentsResponse object. @@ -6960,11 +7407,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ListDocumentsResponse': """Initialize a ListDocumentsResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'documents' in _dict: + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (documents := _dict.get('documents')) is not None: args['documents'] = [ - DocumentDetails.from_dict(v) for v in _dict.get('documents') + DocumentDetails.from_dict(v) for v in documents ] return cls(**args) @@ -7008,7 +7455,7 @@ def __ne__(self, other: 'ListDocumentsResponse') -> bool: return not self == other -class ListFieldsResponse(): +class ListFieldsResponse: """ The list of fetched fields. The fields are returned using a fully qualified name format, however, the format @@ -7018,11 +7465,15 @@ class ListFieldsResponse(): example, `warnings.properties.severity` means that the `warnings` object has a property called `severity`). - :attr List[Field] fields: (optional) An array that contains information about + :param List[Field] fields: (optional) An array that contains information about each field in the collections. """ - def __init__(self, *, fields: List['Field'] = None) -> None: + def __init__( + self, + *, + fields: Optional[List['Field']] = None, + ) -> None: """ Initialize a ListFieldsResponse object. @@ -7035,8 +7486,8 @@ def __init__(self, *, fields: List['Field'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListFieldsResponse': """Initialize a ListFieldsResponse object from a json dictionary.""" args = {} - if 'fields' in _dict: - args['fields'] = [Field.from_dict(v) for v in _dict.get('fields')] + if (fields := _dict.get('fields')) is not None: + args['fields'] = [Field.from_dict(v) for v in fields] return cls(**args) @classmethod @@ -7076,14 +7527,19 @@ def __ne__(self, other: 'ListFieldsResponse') -> bool: return not self == other -class ListProjectsResponse(): +class ListProjectsResponse: """ A list of projects in this instance. - :attr List[ProjectListDetails] projects: (optional) An array of project details. + :param List[ProjectListDetails] projects: (optional) An array of project + details. """ - def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: + def __init__( + self, + *, + projects: Optional[List['ProjectListDetails']] = None, + ) -> None: """ Initialize a ListProjectsResponse object. @@ -7096,9 +7552,9 @@ def __init__(self, *, projects: List['ProjectListDetails'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListProjectsResponse': """Initialize a ListProjectsResponse object from a json dictionary.""" args = {} - if 'projects' in _dict: + if (projects := _dict.get('projects')) is not None: args['projects'] = [ - ProjectListDetails.from_dict(v) for v in _dict.get('projects') + ProjectListDetails.from_dict(v) for v in projects ] return cls(**args) @@ -7139,23 +7595,28 @@ def __ne__(self, other: 'ListProjectsResponse') -> bool: return not self == other -class ModelEvaluationMacroAverage(): +class ModelEvaluationMacroAverage: """ A macro-average computes metric independently for each class and then takes the average. Class refers to the classification label that is specified in the **answer_field**. - :attr float precision: A metric that measures how many of the overall documents + :param float precision: A metric that measures how many of the overall documents are classified correctly. - :attr float recall: A metric that measures how often documents that should be + :param float recall: A metric that measures how often documents that should be classified into certain classes are classified into those classes. - :attr float f1: A metric that measures whether the optimal balance between + :param float f1: A metric that measures whether the optimal balance between precision and recall is reached. The F1 score can be interpreted as a weighted average of the precision and recall values. An F1 score reaches its best value at 1 and worst value at 0. """ - def __init__(self, precision: float, recall: float, f1: float) -> None: + def __init__( + self, + precision: float, + recall: float, + f1: float, + ) -> None: """ Initialize a ModelEvaluationMacroAverage object. @@ -7176,20 +7637,20 @@ def __init__(self, precision: float, recall: float, f1: float) -> None: def from_dict(cls, _dict: Dict) -> 'ModelEvaluationMacroAverage': """Initialize a ModelEvaluationMacroAverage object from a json dictionary.""" args = {} - if 'precision' in _dict: - args['precision'] = _dict.get('precision') + if (precision := _dict.get('precision')) is not None: + args['precision'] = precision else: raise ValueError( 'Required property \'precision\' not present in ModelEvaluationMacroAverage JSON' ) - if 'recall' in _dict: - args['recall'] = _dict.get('recall') + if (recall := _dict.get('recall')) is not None: + args['recall'] = recall else: raise ValueError( 'Required property \'recall\' not present in ModelEvaluationMacroAverage JSON' ) - if 'f1' in _dict: - args['f1'] = _dict.get('f1') + if (f1 := _dict.get('f1')) is not None: + args['f1'] = f1 else: raise ValueError( 'Required property \'f1\' not present in ModelEvaluationMacroAverage JSON' @@ -7231,23 +7692,28 @@ def __ne__(self, other: 'ModelEvaluationMacroAverage') -> bool: return not self == other -class ModelEvaluationMicroAverage(): +class ModelEvaluationMicroAverage: """ A micro-average aggregates the contributions of all classes to compute the average metric. Classes refers to the classification labels that are specified in the **answer_field**. - :attr float precision: A metric that measures how many of the overall documents + :param float precision: A metric that measures how many of the overall documents are classified correctly. - :attr float recall: A metric that measures how often documents that should be + :param float recall: A metric that measures how often documents that should be classified into certain classes are classified into those classes. - :attr float f1: A metric that measures whether the optimal balance between + :param float f1: A metric that measures whether the optimal balance between precision and recall is reached. The F1 score can be interpreted as a weighted average of the precision and recall values. An F1 score reaches its best value at 1 and worst value at 0. """ - def __init__(self, precision: float, recall: float, f1: float) -> None: + def __init__( + self, + precision: float, + recall: float, + f1: float, + ) -> None: """ Initialize a ModelEvaluationMicroAverage object. @@ -7268,20 +7734,20 @@ def __init__(self, precision: float, recall: float, f1: float) -> None: def from_dict(cls, _dict: Dict) -> 'ModelEvaluationMicroAverage': """Initialize a ModelEvaluationMicroAverage object from a json dictionary.""" args = {} - if 'precision' in _dict: - args['precision'] = _dict.get('precision') + if (precision := _dict.get('precision')) is not None: + args['precision'] = precision else: raise ValueError( 'Required property \'precision\' not present in ModelEvaluationMicroAverage JSON' ) - if 'recall' in _dict: - args['recall'] = _dict.get('recall') + if (recall := _dict.get('recall')) is not None: + args['recall'] = recall else: raise ValueError( 'Required property \'recall\' not present in ModelEvaluationMicroAverage JSON' ) - if 'f1' in _dict: - args['f1'] = _dict.get('f1') + if (f1 := _dict.get('f1')) is not None: + args['f1'] = f1 else: raise ValueError( 'Required property \'f1\' not present in ModelEvaluationMicroAverage JSON' @@ -7323,11 +7789,11 @@ def __ne__(self, other: 'ModelEvaluationMicroAverage') -> bool: return not self == other -class Notice(): +class Notice: """ A notice produced for the collection. - :attr str notice_id: (optional) Identifies the notice. Many notices might have + :param str notice_id: (optional) Identifies the notice. Many notices might have the same ID. This field exists so that user applications can programmatically identify a notice and take automatic corrective action. Typical notice IDs include: @@ -7342,28 +7808,30 @@ class Notice(): `smart_document_understanding_page_error`, `smart_document_understanding_page_warning`. **Note:** This is not a complete list. Other values might be returned. - :attr datetime created: (optional) The creation date of the collection in the + :param datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :attr str document_id: (optional) Unique identifier of the document. - :attr str collection_id: (optional) Unique identifier of the collection. - :attr str query_id: (optional) Unique identifier of the query used for relevance - training. - :attr str severity: (optional) Severity level of the notice. - :attr str step: (optional) Ingestion or training step in which the notice + :param str document_id: (optional) Unique identifier of the document. + :param str collection_id: (optional) Unique identifier of the collection. + :param str query_id: (optional) Unique identifier of the query used for + relevance training. + :param str severity: (optional) Severity level of the notice. + :param str step: (optional) Ingestion or training step in which the notice occurred. - :attr str description: (optional) The description of the notice. + :param str description: (optional) The description of the notice. """ - def __init__(self, - *, - notice_id: str = None, - created: datetime = None, - document_id: str = None, - collection_id: str = None, - query_id: str = None, - severity: str = None, - step: str = None, - description: str = None) -> None: + def __init__( + self, + *, + notice_id: Optional[str] = None, + created: Optional[datetime] = None, + document_id: Optional[str] = None, + collection_id: Optional[str] = None, + query_id: Optional[str] = None, + severity: Optional[str] = None, + step: Optional[str] = None, + description: Optional[str] = None, + ) -> None: """ Initialize a Notice object. @@ -7381,22 +7849,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} - if 'notice_id' in _dict: - args['notice_id'] = _dict.get('notice_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'severity' in _dict: - args['severity'] = _dict.get('severity') - if 'step' in _dict: - args['step'] = _dict.get('step') - if 'description' in _dict: - args['description'] = _dict.get('description') + if (notice_id := _dict.get('notice_id')) is not None: + args['notice_id'] = notice_id + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (severity := _dict.get('severity')) is not None: + args['severity'] = severity + if (step := _dict.get('step')) is not None: + args['step'] = step + if (description := _dict.get('description')) is not None: + args['description'] = description return cls(**args) @classmethod @@ -7451,29 +7919,35 @@ class SeverityEnum(str, Enum): """ Severity level of the notice. """ + WARNING = 'warning' ERROR = 'error' -class PerClassModelEvaluation(): +class PerClassModelEvaluation: """ An object that measures the metrics from a training run for each classification label separately. - :attr str name: Class name. Each class name is derived from a value in the + :param str name: Class name. Each class name is derived from a value in the **answer_field**. - :attr float precision: A metric that measures how many of the overall documents + :param float precision: A metric that measures how many of the overall documents are classified correctly. - :attr float recall: A metric that measures how often documents that should be + :param float recall: A metric that measures how often documents that should be classified into certain classes are classified into those classes. - :attr float f1: A metric that measures whether the optimal balance between + :param float f1: A metric that measures whether the optimal balance between precision and recall is reached. The F1 score can be interpreted as a weighted average of the precision and recall values. An F1 score reaches its best value at 1 and worst value at 0. """ - def __init__(self, name: str, precision: float, recall: float, - f1: float) -> None: + def __init__( + self, + name: str, + precision: float, + recall: float, + f1: float, + ) -> None: """ Initialize a PerClassModelEvaluation object. @@ -7497,26 +7971,26 @@ def __init__(self, name: str, precision: float, recall: float, def from_dict(cls, _dict: Dict) -> 'PerClassModelEvaluation': """Initialize a PerClassModelEvaluation object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in PerClassModelEvaluation JSON' ) - if 'precision' in _dict: - args['precision'] = _dict.get('precision') + if (precision := _dict.get('precision')) is not None: + args['precision'] = precision else: raise ValueError( 'Required property \'precision\' not present in PerClassModelEvaluation JSON' ) - if 'recall' in _dict: - args['recall'] = _dict.get('recall') + if (recall := _dict.get('recall')) is not None: + args['recall'] = recall else: raise ValueError( 'Required property \'recall\' not present in PerClassModelEvaluation JSON' ) - if 'f1' in _dict: - args['f1'] = _dict.get('f1') + if (f1 := _dict.get('f1')) is not None: + args['f1'] = f1 else: raise ValueError( 'Required property \'f1\' not present in PerClassModelEvaluation JSON' @@ -7560,34 +8034,36 @@ def __ne__(self, other: 'PerClassModelEvaluation') -> bool: return not self == other -class ProjectDetails(): +class ProjectDetails: """ Detailed information about the specified project. - :attr str project_id: (optional) The unique identifier of this project. - :attr str name: (optional) The human readable name of this project. - :attr str type: (optional) The type of project. + :param str project_id: (optional) The unique identifier of this project. + :param str name: (optional) The human readable name of this project. + :param str type: (optional) The type of project. The `content_intelligence` type is a *Document Retrieval for Contracts* project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. - :attr int collection_count: (optional) The number of collections configured in + :param int collection_count: (optional) The number of collections configured in this project. - :attr DefaultQueryParams default_query_parameters: (optional) Default query + :param DefaultQueryParams default_query_parameters: (optional) Default query parameters for this project. """ - def __init__(self, - *, - project_id: str = None, - name: str = None, - type: str = None, - relevancy_training_status: - 'ProjectListDetailsRelevancyTrainingStatus' = None, - collection_count: int = None, - default_query_parameters: 'DefaultQueryParams' = None) -> None: + def __init__( + self, + *, + project_id: Optional[str] = None, + name: Optional[str] = None, + type: Optional[str] = None, + relevancy_training_status: Optional[ + 'ProjectListDetailsRelevancyTrainingStatus'] = None, + collection_count: Optional[int] = None, + default_query_parameters: Optional['DefaultQueryParams'] = None, + ) -> None: """ Initialize a ProjectDetails object. @@ -7611,21 +8087,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProjectDetails': """Initialize a ProjectDetails object from a json dictionary.""" args = {} - if 'project_id' in _dict: - args['project_id'] = _dict.get('project_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'relevancy_training_status' in _dict: + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (type := _dict.get('type')) is not None: + args['type'] = type + if (relevancy_training_status := + _dict.get('relevancy_training_status')) is not None: args[ 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus.from_dict( - _dict.get('relevancy_training_status')) - if 'collection_count' in _dict: - args['collection_count'] = _dict.get('collection_count') - if 'default_query_parameters' in _dict: + relevancy_training_status) + if (collection_count := _dict.get('collection_count')) is not None: + args['collection_count'] = collection_count + if (default_query_parameters := + _dict.get('default_query_parameters')) is not None: args['default_query_parameters'] = DefaultQueryParams.from_dict( - _dict.get('default_query_parameters')) + default_query_parameters) return cls(**args) @classmethod @@ -7691,6 +8169,7 @@ class TypeEnum(str, Enum): The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. """ + DOCUMENT_RETRIEVAL = 'document_retrieval' CONVERSATIONAL_SEARCH = 'conversational_search' CONTENT_MINING = 'content_mining' @@ -7698,31 +8177,33 @@ class TypeEnum(str, Enum): OTHER = 'other' -class ProjectListDetails(): +class ProjectListDetails: """ Details about a specific project. - :attr str project_id: (optional) The unique identifier of this project. - :attr str name: (optional) The human readable name of this project. - :attr str type: (optional) The type of project. + :param str project_id: (optional) The unique identifier of this project. + :param str name: (optional) The human readable name of this project. + :param str type: (optional) The type of project. The `content_intelligence` type is a *Document Retrieval for Contracts* project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. - :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: + :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. - :attr int collection_count: (optional) The number of collections configured in + :param int collection_count: (optional) The number of collections configured in this project. """ - def __init__(self, - *, - project_id: str = None, - name: str = None, - type: str = None, - relevancy_training_status: - 'ProjectListDetailsRelevancyTrainingStatus' = None, - collection_count: int = None) -> None: + def __init__( + self, + *, + project_id: Optional[str] = None, + name: Optional[str] = None, + type: Optional[str] = None, + relevancy_training_status: Optional[ + 'ProjectListDetailsRelevancyTrainingStatus'] = None, + collection_count: Optional[int] = None, + ) -> None: """ Initialize a ProjectListDetails object. @@ -7743,18 +8224,19 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProjectListDetails': """Initialize a ProjectListDetails object from a json dictionary.""" args = {} - if 'project_id' in _dict: - args['project_id'] = _dict.get('project_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'relevancy_training_status' in _dict: + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (type := _dict.get('type')) is not None: + args['type'] = type + if (relevancy_training_status := + _dict.get('relevancy_training_status')) is not None: args[ 'relevancy_training_status'] = ProjectListDetailsRelevancyTrainingStatus.from_dict( - _dict.get('relevancy_training_status')) - if 'collection_count' in _dict: - args['collection_count'] = _dict.get('collection_count') + relevancy_training_status) + if (collection_count := _dict.get('collection_count')) is not None: + args['collection_count'] = collection_count return cls(**args) @classmethod @@ -7811,6 +8293,7 @@ class TypeEnum(str, Enum): The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. """ + DOCUMENT_RETRIEVAL = 'document_retrieval' CONVERSATIONAL_SEARCH = 'conversational_search' CONTENT_MINING = 'content_mining' @@ -7818,39 +8301,41 @@ class TypeEnum(str, Enum): OTHER = 'other' -class ProjectListDetailsRelevancyTrainingStatus(): +class ProjectListDetailsRelevancyTrainingStatus: """ Relevancy training status information for this project. - :attr str data_updated: (optional) When the training data was updated. - :attr int total_examples: (optional) The total number of examples. - :attr bool sufficient_label_diversity: (optional) When `true`, sufficient label + :param str data_updated: (optional) When the training data was updated. + :param int total_examples: (optional) The total number of examples. + :param bool sufficient_label_diversity: (optional) When `true`, sufficient label diversity is present to allow training for this project. - :attr bool processing: (optional) When `true`, the relevancy training is in + :param bool processing: (optional) When `true`, the relevancy training is in processing. - :attr bool minimum_examples_added: (optional) When `true`, the minimum number of - examples required to train has been met. - :attr str successfully_trained: (optional) The time that the most recent + :param bool minimum_examples_added: (optional) When `true`, the minimum number + of examples required to train has been met. + :param str successfully_trained: (optional) The time that the most recent successful training occurred. - :attr bool available: (optional) When `true`, relevancy training is available + :param bool available: (optional) When `true`, relevancy training is available when querying collections in the project. - :attr int notices: (optional) The number of notices generated during the + :param int notices: (optional) The number of notices generated during the relevancy training. - :attr bool minimum_queries_added: (optional) When `true`, the minimum number of + :param bool minimum_queries_added: (optional) When `true`, the minimum number of queries required to train has been met. """ - def __init__(self, - *, - data_updated: str = None, - total_examples: int = None, - sufficient_label_diversity: bool = None, - processing: bool = None, - minimum_examples_added: bool = None, - successfully_trained: str = None, - available: bool = None, - notices: int = None, - minimum_queries_added: bool = None) -> None: + def __init__( + self, + *, + data_updated: Optional[str] = None, + total_examples: Optional[int] = None, + sufficient_label_diversity: Optional[bool] = None, + processing: Optional[bool] = None, + minimum_examples_added: Optional[bool] = None, + successfully_trained: Optional[str] = None, + available: Optional[bool] = None, + notices: Optional[int] = None, + minimum_queries_added: Optional[bool] = None, + ) -> None: """ Initialize a ProjectListDetailsRelevancyTrainingStatus object. @@ -7886,25 +8371,28 @@ def from_dict(cls, _dict: Dict) -> 'ProjectListDetailsRelevancyTrainingStatus': """Initialize a ProjectListDetailsRelevancyTrainingStatus object from a json dictionary.""" args = {} - if 'data_updated' in _dict: - args['data_updated'] = _dict.get('data_updated') - if 'total_examples' in _dict: - args['total_examples'] = _dict.get('total_examples') - if 'sufficient_label_diversity' in _dict: - args['sufficient_label_diversity'] = _dict.get( - 'sufficient_label_diversity') - if 'processing' in _dict: - args['processing'] = _dict.get('processing') - if 'minimum_examples_added' in _dict: - args['minimum_examples_added'] = _dict.get('minimum_examples_added') - if 'successfully_trained' in _dict: - args['successfully_trained'] = _dict.get('successfully_trained') - if 'available' in _dict: - args['available'] = _dict.get('available') - if 'notices' in _dict: - args['notices'] = _dict.get('notices') - if 'minimum_queries_added' in _dict: - args['minimum_queries_added'] = _dict.get('minimum_queries_added') + if (data_updated := _dict.get('data_updated')) is not None: + args['data_updated'] = data_updated + if (total_examples := _dict.get('total_examples')) is not None: + args['total_examples'] = total_examples + if (sufficient_label_diversity := + _dict.get('sufficient_label_diversity')) is not None: + args['sufficient_label_diversity'] = sufficient_label_diversity + if (processing := _dict.get('processing')) is not None: + args['processing'] = processing + if (minimum_examples_added := + _dict.get('minimum_examples_added')) is not None: + args['minimum_examples_added'] = minimum_examples_added + if (successfully_trained := + _dict.get('successfully_trained')) is not None: + args['successfully_trained'] = successfully_trained + if (available := _dict.get('available')) is not None: + args['available'] = available + if (notices := _dict.get('notices')) is not None: + args['notices'] = notices + if (minimum_queries_added := + _dict.get('minimum_queries_added')) is not None: + args['minimum_queries_added'] = minimum_queries_added return cls(**args) @classmethod @@ -7961,13 +8449,13 @@ def __ne__(self, return not self == other -class QueryAggregation(): +class QueryAggregation: """ An object that defines how to aggregate query results. """ - def __init__(self) -> None: + def __init__(self,) -> None: """ Initialize a QueryAggregation object. @@ -7994,22 +8482,20 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregation': disc_class = cls._get_class_by_discriminator(_dict) if disc_class != cls: return disc_class.from_dict(_dict) - msg = ( - "Cannot convert dictionary into an instance of base class 'QueryAggregation'. " - + "The discriminator value should map to a valid subclass: {1}" - ).format(", ".join([ - 'QueryAggregationQueryTermAggregation', - 'QueryAggregationQueryGroupByAggregation', - 'QueryAggregationQueryHistogramAggregation', - 'QueryAggregationQueryTimesliceAggregation', - 'QueryAggregationQueryNestedAggregation', - 'QueryAggregationQueryFilterAggregation', - 'QueryAggregationQueryCalculationAggregation', - 'QueryAggregationQueryTopHitsAggregation', - 'QueryAggregationQueryPairAggregation', - 'QueryAggregationQueryTrendAggregation', - 'QueryAggregationQueryTopicAggregation' - ])) + msg = "Cannot convert dictionary into an instance of base class 'QueryAggregation'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'QueryAggregationQueryTermAggregation', + 'QueryAggregationQueryGroupByAggregation', + 'QueryAggregationQueryHistogramAggregation', + 'QueryAggregationQueryTimesliceAggregation', + 'QueryAggregationQueryNestedAggregation', + 'QueryAggregationQueryFilterAggregation', + 'QueryAggregationQueryCalculationAggregation', + 'QueryAggregationQueryTopHitsAggregation', + 'QueryAggregationQueryPairAggregation', + 'QueryAggregationQueryTrendAggregation', + 'QueryAggregationQueryTopicAggregation' + ])) raise Exception(msg) @classmethod @@ -8050,34 +8536,36 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class QueryGroupByAggregationResult(): +class QueryGroupByAggregationResult: """ Result group for the `group_by` aggregation. - :attr str key: The condition that is met by the documents in this group. For + :param str key: The condition that is met by the documents in this group. For example, `YEARTXT<2000`. - :attr int matching_results: Number of documents that meet the query and + :param int matching_results: Number of documents that meet the query and condition. - :attr float relevancy: (optional) The relevancy for this group. Returned only if - `relevancy:true` is specified in the request. - :attr int total_matching_documents: (optional) Number of documents that meet the - condition in the whole set of documents in this collection. Returned only when - `relevancy:true` is specified in the request. - :attr float estimated_matching_results: (optional) The number of documents that + :param float relevancy: (optional) The relevancy for this group. Returned only + if `relevancy:true` is specified in the request. + :param int total_matching_documents: (optional) Number of documents that meet + the condition in the whole set of documents in this collection. Returned only + when `relevancy:true` is specified in the request. + :param float estimated_matching_results: (optional) The number of documents that are estimated to match the query and condition. Returned only when `relevancy:true` is specified in the request. - :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + :param List[dict] aggregations: (optional) An array of subaggregations. Returned only when this aggregation is returned as a subaggregation. """ - def __init__(self, - key: str, - matching_results: int, - *, - relevancy: float = None, - total_matching_documents: int = None, - estimated_matching_results: float = None, - aggregations: List[dict] = None) -> None: + def __init__( + self, + key: str, + matching_results: int, + *, + relevancy: Optional[float] = None, + total_matching_documents: Optional[int] = None, + estimated_matching_results: Optional[float] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryGroupByAggregationResult object. @@ -8107,28 +8595,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryGroupByAggregationResult': """Initialize a QueryGroupByAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryGroupByAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryGroupByAggregationResult JSON' ) - if 'relevancy' in _dict: - args['relevancy'] = _dict.get('relevancy') - if 'total_matching_documents' in _dict: - args['total_matching_documents'] = _dict.get( - 'total_matching_documents') - if 'estimated_matching_results' in _dict: - args['estimated_matching_results'] = _dict.get( - 'estimated_matching_results') - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (relevancy := _dict.get('relevancy')) is not None: + args['relevancy'] = relevancy + if (total_matching_documents := + _dict.get('total_matching_documents')) is not None: + args['total_matching_documents'] = total_matching_documents + if (estimated_matching_results := + _dict.get('estimated_matching_results')) is not None: + args['estimated_matching_results'] = estimated_matching_results + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -8176,22 +8664,24 @@ def __ne__(self, other: 'QueryGroupByAggregationResult') -> bool: return not self == other -class QueryHistogramAggregationResult(): +class QueryHistogramAggregationResult: """ Histogram numeric interval result. - :attr int key: The value of the upper bound for the numeric segment. - :attr int matching_results: Number of documents with the specified key as the + :param int key: The value of the upper bound for the numeric segment. + :param int matching_results: Number of documents with the specified key as the upper bound. - :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + :param List[dict] aggregations: (optional) An array of subaggregations. Returned only when this aggregation is returned as a subaggregation. """ - def __init__(self, - key: int, - matching_results: int, - *, - aggregations: List[dict] = None) -> None: + def __init__( + self, + key: int, + matching_results: int, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryHistogramAggregationResult object. @@ -8209,20 +8699,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' ) - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -8261,30 +8751,30 @@ def __ne__(self, other: 'QueryHistogramAggregationResult') -> bool: return not self == other -class QueryLargePassages(): +class QueryLargePassages: """ Configuration for passage retrieval. - :attr bool enabled: (optional) A passages query that returns the most relevant + :param bool enabled: (optional) A passages query that returns the most relevant passages from the results. - :attr bool per_document: (optional) If `true`, ranks the documents by document + :param bool per_document: (optional) If `true`, ranks the documents by document quality, and then returns the highest-ranked passages per document in a `document_passages` field for each document entry in the results list of the response. If `false`, ranks the passages from all of the documents by passage quality regardless of the document quality and returns them in a separate `passages` field in the response. - :attr int max_per_document: (optional) Maximum number of passages to return per + :param int max_per_document: (optional) Maximum number of passages to return per document in the result. Ignored if **passages.per_document** is `false`. - :attr List[str] fields: (optional) A list of fields to extract passages from. By - default, passages are extracted from the `text` and `title` fields only. If you - add this parameter and specify an empty list (`[]`) as its value, then the + :param List[str] fields: (optional) A list of fields to extract passages from. + By default, passages are extracted from the `text` and `title` fields only. If + you add this parameter and specify an empty list (`[]`) as its value, then the service searches all root-level fields for suitable passages. - :attr int count: (optional) The maximum number of passages to return. Ignored if - **passages.per_document** is `true`. - :attr int characters: (optional) The approximate number of characters that any + :param int count: (optional) The maximum number of passages to return. Ignored + if **passages.per_document** is `true`. + :param int characters: (optional) The approximate number of characters that any one passage will have. - :attr bool find_answers: (optional) When true, `answer` objects are returned as + :param bool find_answers: (optional) When true, `answer` objects are returned as part of each passage in the query results. The primary difference between an `answer` and a `passage` is that the length of a passage is defined by the query, where the length of an `answer` is calculated by Discovery based on how @@ -8301,20 +8791,22 @@ class QueryLargePassages(): order of the highest confidence answer for each document and passage. The **find_answers** parameter is available only on managed instances of Discovery. - :attr int max_answers_per_passage: (optional) The number of `answer` objects to + :param int max_answers_per_passage: (optional) The number of `answer` objects to return per passage if the **find_answers** parmeter is specified as `true`. """ - def __init__(self, - *, - enabled: bool = None, - per_document: bool = None, - max_per_document: int = None, - fields: List[str] = None, - count: int = None, - characters: int = None, - find_answers: bool = None, - max_answers_per_passage: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + per_document: Optional[bool] = None, + max_per_document: Optional[int] = None, + fields: Optional[List[str]] = None, + count: Optional[int] = None, + characters: Optional[int] = None, + find_answers: Optional[bool] = None, + max_answers_per_passage: Optional[int] = None, + ) -> None: """ Initialize a QueryLargePassages object. @@ -8375,23 +8867,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryLargePassages': """Initialize a QueryLargePassages object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'per_document' in _dict: - args['per_document'] = _dict.get('per_document') - if 'max_per_document' in _dict: - args['max_per_document'] = _dict.get('max_per_document') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'characters' in _dict: - args['characters'] = _dict.get('characters') - if 'find_answers' in _dict: - args['find_answers'] = _dict.get('find_answers') - if 'max_answers_per_passage' in _dict: - args['max_answers_per_passage'] = _dict.get( - 'max_answers_per_passage') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (per_document := _dict.get('per_document')) is not None: + args['per_document'] = per_document + if (max_per_document := _dict.get('max_per_document')) is not None: + args['max_per_document'] = max_per_document + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields + if (count := _dict.get('count')) is not None: + args['count'] = count + if (characters := _dict.get('characters')) is not None: + args['characters'] = characters + if (find_answers := _dict.get('find_answers')) is not None: + args['find_answers'] = find_answers + if (max_answers_per_passage := + _dict.get('max_answers_per_passage')) is not None: + args['max_answers_per_passage'] = max_answers_per_passage return cls(**args) @classmethod @@ -8441,27 +8933,29 @@ def __ne__(self, other: 'QueryLargePassages') -> bool: return not self == other -class QueryLargeSimilar(): +class QueryLargeSimilar: """ Finds results from documents that are similar to documents of interest. Use this parameter to add a *More like these* function to your search. You can include this parameter with or without a **query**, **filter** or **natural_language_query** parameter. - :attr bool enabled: (optional) When `true`, includes documents in the query + :param bool enabled: (optional) When `true`, includes documents in the query results that are similar to documents you specify. - :attr List[str] document_ids: (optional) The list of documents of interest. + :param List[str] document_ids: (optional) The list of documents of interest. Required if **enabled** is `true`. - :attr List[str] fields: (optional) Looks for similarities in the specified + :param List[str] fields: (optional) Looks for similarities in the specified subset of fields in the documents. If not specified, all of the document fields are used. """ - def __init__(self, - *, - enabled: bool = None, - document_ids: List[str] = None, - fields: List[str] = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + document_ids: Optional[List[str]] = None, + fields: Optional[List[str]] = None, + ) -> None: """ Initialize a QueryLargeSimilar object. @@ -8481,12 +8975,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryLargeSimilar': """Initialize a QueryLargeSimilar object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'document_ids' in _dict: - args['document_ids'] = _dict.get('document_ids') - if 'fields' in _dict: - args['fields'] = _dict.get('fields') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (document_ids := _dict.get('document_ids')) is not None: + args['document_ids'] = document_ids + if (fields := _dict.get('fields')) is not None: + args['fields'] = fields return cls(**args) @classmethod @@ -8524,18 +9018,23 @@ def __ne__(self, other: 'QueryLargeSimilar') -> bool: return not self == other -class QueryLargeSuggestedRefinements(): +class QueryLargeSuggestedRefinements: """ Configuration for suggested refinements. **Note**: The **suggested_refinements** parameter that identified dynamic facets from the data is deprecated. - :attr bool enabled: (optional) Whether to perform suggested refinements. - :attr int count: (optional) Maximum number of suggested refinements texts to be + :param bool enabled: (optional) Whether to perform suggested refinements. + :param int count: (optional) Maximum number of suggested refinements texts to be returned. The maximum is `100`. """ - def __init__(self, *, enabled: bool = None, count: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a QueryLargeSuggestedRefinements object. @@ -8550,10 +9049,10 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryLargeSuggestedRefinements': """Initialize a QueryLargeSuggestedRefinements object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -8589,15 +9088,20 @@ def __ne__(self, other: 'QueryLargeSuggestedRefinements') -> bool: return not self == other -class QueryLargeTableResults(): +class QueryLargeTableResults: """ Configuration for table retrieval. - :attr bool enabled: (optional) Whether to enable table retrieval. - :attr int count: (optional) Maximum number of tables to return. + :param bool enabled: (optional) Whether to enable table retrieval. + :param int count: (optional) Maximum number of tables to return. """ - def __init__(self, *, enabled: bool = None, count: int = None) -> None: + def __init__( + self, + *, + enabled: Optional[bool] = None, + count: Optional[int] = None, + ) -> None: """ Initialize a QueryLargeTableResults object. @@ -8611,10 +9115,10 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryLargeTableResults': """Initialize a QueryLargeTableResults object from a json dictionary.""" args = {} - if 'enabled' in _dict: - args['enabled'] = _dict.get('enabled') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + if (count := _dict.get('count')) is not None: + args['count'] = count return cls(**args) @classmethod @@ -8650,19 +9154,21 @@ def __ne__(self, other: 'QueryLargeTableResults') -> bool: return not self == other -class QueryNoticesResponse(): +class QueryNoticesResponse: """ Object that contains notice query results. - :attr int matching_results: (optional) The number of matching results. - :attr List[Notice] notices: (optional) Array of document results that match the + :param int matching_results: (optional) The number of matching results. + :param List[Notice] notices: (optional) Array of document results that match the query. """ - def __init__(self, - *, - matching_results: int = None, - notices: List['Notice'] = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + notices: Optional[List['Notice']] = None, + ) -> None: """ Initialize a QueryNoticesResponse object. @@ -8677,12 +9183,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': """Initialize a QueryNoticesResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] return cls(**args) @classmethod @@ -8725,17 +9229,21 @@ def __ne__(self, other: 'QueryNoticesResponse') -> bool: return not self == other -class QueryPairAggregationResult(): +class QueryPairAggregationResult: """ Result for the `pair` aggregation. - :attr List[dict] aggregations: (optional) Array of subaggregations of type + :param List[dict] aggregations: (optional) Array of subaggregations of type `term`, `group_by`, `histogram`, or `timeslice`. Each element of the matrix that is returned contains a **relevancy** value that is calculated from the combination of each value from the first and second aggregations. """ - def __init__(self, *, aggregations: List[dict] = None) -> None: + def __init__( + self, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryPairAggregationResult object. @@ -8750,8 +9258,8 @@ def __init__(self, *, aggregations: List[dict] = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryPairAggregationResult': """Initialize a QueryPairAggregationResult object from a json dictionary.""" args = {} - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -8785,40 +9293,43 @@ def __ne__(self, other: 'QueryPairAggregationResult') -> bool: return not self == other -class QueryResponse(): +class QueryResponse: """ A response that contains the documents and aggregations for the query. - :attr int matching_results: (optional) The number of matching results for the + :param int matching_results: (optional) The number of matching results for the query. Results that match due to a curation only are not counted in the total. - :attr List[QueryResult] results: (optional) Array of document results for the + :param List[QueryResult] results: (optional) Array of document results for the query. - :attr List[QueryAggregation] aggregations: (optional) Array of aggregations for + :param List[QueryAggregation] aggregations: (optional) Array of aggregations for the query. - :attr RetrievalDetails retrieval_details: (optional) An object contain retrieval - type information. - :attr str suggested_query: (optional) Suggested correction to the submitted + :param RetrievalDetails retrieval_details: (optional) An object contain + retrieval type information. + :param str suggested_query: (optional) Suggested correction to the submitted **natural_language_query** value. - :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) + :param List[QuerySuggestedRefinement] suggested_refinements: (optional) Deprecated: Array of suggested refinements. **Note**: The `suggested_refinements` parameter that identified dynamic facets from the data is deprecated. - :attr List[QueryTableResult] table_results: (optional) Array of table results. - :attr List[QueryResponsePassage] passages: (optional) Passages that best match + :param List[QueryTableResult] table_results: (optional) Array of table results. + :param List[QueryResponsePassage] passages: (optional) Passages that best match the query from across all of the collections in the project. Returned if **passages.per_document** is `false`. """ - def __init__(self, - *, - matching_results: int = None, - results: List['QueryResult'] = None, - aggregations: List['QueryAggregation'] = None, - retrieval_details: 'RetrievalDetails' = None, - suggested_query: str = None, - suggested_refinements: List['QuerySuggestedRefinement'] = None, - table_results: List['QueryTableResult'] = None, - passages: List['QueryResponsePassage'] = None) -> None: + def __init__( + self, + *, + matching_results: Optional[int] = None, + results: Optional[List['QueryResult']] = None, + aggregations: Optional[List['QueryAggregation']] = None, + retrieval_details: Optional['RetrievalDetails'] = None, + suggested_query: Optional[str] = None, + suggested_refinements: Optional[ + List['QuerySuggestedRefinement']] = None, + table_results: Optional[List['QueryTableResult']] = None, + passages: Optional[List['QueryResponsePassage']] = None, + ) -> None: """ Initialize a QueryResponse object. @@ -8856,34 +9367,32 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResponse': """Initialize a QueryResponse object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'results' in _dict: - args['results'] = [ - QueryResult.from_dict(v) for v in _dict.get('results') - ] - if 'aggregations' in _dict: + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results + if (results := _dict.get('results')) is not None: + args['results'] = [QueryResult.from_dict(v) for v in results] + if (aggregations := _dict.get('aggregations')) is not None: args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in _dict.get('aggregations') + QueryAggregation.from_dict(v) for v in aggregations ] - if 'retrieval_details' in _dict: + if (retrieval_details := _dict.get('retrieval_details')) is not None: args['retrieval_details'] = RetrievalDetails.from_dict( - _dict.get('retrieval_details')) - if 'suggested_query' in _dict: - args['suggested_query'] = _dict.get('suggested_query') - if 'suggested_refinements' in _dict: + retrieval_details) + if (suggested_query := _dict.get('suggested_query')) is not None: + args['suggested_query'] = suggested_query + if (suggested_refinements := + _dict.get('suggested_refinements')) is not None: args['suggested_refinements'] = [ QuerySuggestedRefinement.from_dict(v) - for v in _dict.get('suggested_refinements') + for v in suggested_refinements ] - if 'table_results' in _dict: + if (table_results := _dict.get('table_results')) is not None: args['table_results'] = [ - QueryTableResult.from_dict(v) - for v in _dict.get('table_results') + QueryTableResult.from_dict(v) for v in table_results ] - if 'passages' in _dict: + if (passages := _dict.get('passages')) is not None: args['passages'] = [ - QueryResponsePassage.from_dict(v) for v in _dict.get('passages') + QueryResponsePassage.from_dict(v) for v in passages ] return cls(**args) @@ -8969,39 +9478,41 @@ def __ne__(self, other: 'QueryResponse') -> bool: return not self == other -class QueryResponsePassage(): +class QueryResponsePassage: """ A passage query response. - :attr str passage_text: (optional) The content of the extracted passage. - :attr float passage_score: (optional) The confidence score of the passage's + :param str passage_text: (optional) The content of the extracted passage. + :param float passage_score: (optional) The confidence score of the passage's analysis. A higher score indicates greater confidence. The score is used to rank the passages from all documents and is returned only if **passages.per_document** is `false`. - :attr str document_id: (optional) The unique identifier of the ingested + :param str document_id: (optional) The unique identifier of the ingested document. - :attr str collection_id: (optional) The unique identifier of the collection. - :attr int start_offset: (optional) The position of the first character of the + :param str collection_id: (optional) The unique identifier of the collection. + :param int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :attr int end_offset: (optional) The position after the last character of the + :param int end_offset: (optional) The position after the last character of the extracted passage in the originating field. - :attr str field: (optional) The label of the field from which the passage has + :param str field: (optional) The label of the field from which the passage has been extracted. - :attr List[ResultPassageAnswer] answers: (optional) An array of extracted + :param List[ResultPassageAnswer] answers: (optional) An array of extracted answers to the specified query. Returned for natural language queries when **passages.per_document** is `false`. """ - def __init__(self, - *, - passage_text: str = None, - passage_score: float = None, - document_id: str = None, - collection_id: str = None, - start_offset: int = None, - end_offset: int = None, - field: str = None, - answers: List['ResultPassageAnswer'] = None) -> None: + def __init__( + self, + *, + passage_text: Optional[str] = None, + passage_score: Optional[float] = None, + document_id: Optional[str] = None, + collection_id: Optional[str] = None, + start_offset: Optional[int] = None, + end_offset: Optional[int] = None, + field: Optional[str] = None, + answers: Optional[List['ResultPassageAnswer']] = None, + ) -> None: """ Initialize a QueryResponsePassage object. @@ -9037,23 +9548,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResponsePassage': """Initialize a QueryResponsePassage object from a json dictionary.""" args = {} - if 'passage_text' in _dict: - args['passage_text'] = _dict.get('passage_text') - if 'passage_score' in _dict: - args['passage_score'] = _dict.get('passage_score') - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'answers' in _dict: + if (passage_text := _dict.get('passage_text')) is not None: + args['passage_text'] = passage_text + if (passage_score := _dict.get('passage_score')) is not None: + args['passage_score'] = passage_score + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (start_offset := _dict.get('start_offset')) is not None: + args['start_offset'] = start_offset + if (end_offset := _dict.get('end_offset')) is not None: + args['end_offset'] = end_offset + if (field := _dict.get('field')) is not None: + args['field'] = field + if (answers := _dict.get('answers')) is not None: args['answers'] = [ - ResultPassageAnswer.from_dict(v) for v in _dict.get('answers') + ResultPassageAnswer.from_dict(v) for v in answers ] return cls(**args) @@ -9108,14 +9619,14 @@ def __ne__(self, other: 'QueryResponsePassage') -> bool: return not self == other -class QueryResult(): +class QueryResult: """ Result document for the specified query. - :attr str document_id: The unique identifier of the document. - :attr dict metadata: (optional) Metadata of the document. - :attr QueryResultMetadata result_metadata: Metadata of a query result. - :attr List[QueryResultPassage] document_passages: (optional) Passages from the + :param str document_id: The unique identifier of the document. + :param dict metadata: (optional) Metadata of the document. + :param QueryResultMetadata result_metadata: Metadata of a query result. + :param List[QueryResultPassage] document_passages: (optional) Passages from the document that best matches the query. Returned if **passages.per_document** is `true`. """ @@ -9124,13 +9635,15 @@ class QueryResult(): _properties = frozenset( ['document_id', 'metadata', 'result_metadata', 'document_passages']) - def __init__(self, - document_id: str, - result_metadata: 'QueryResultMetadata', - *, - metadata: dict = None, - document_passages: List['QueryResultPassage'] = None, - **kwargs) -> None: + def __init__( + self, + document_id: str, + result_metadata: 'QueryResultMetadata', + *, + metadata: Optional[dict] = None, + document_passages: Optional[List['QueryResultPassage']] = None, + **kwargs, + ) -> None: """ Initialize a QueryResult object. @@ -9153,25 +9666,24 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResult': """Initialize a QueryResult object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id else: raise ValueError( 'Required property \'document_id\' not present in QueryResult JSON' ) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'result_metadata' in _dict: + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (result_metadata := _dict.get('result_metadata')) is not None: args['result_metadata'] = QueryResultMetadata.from_dict( - _dict.get('result_metadata')) + result_metadata) else: raise ValueError( 'Required property \'result_metadata\' not present in QueryResult JSON' ) - if 'document_passages' in _dict: + if (document_passages := _dict.get('document_passages')) is not None: args['document_passages'] = [ - QueryResultPassage.from_dict(v) - for v in _dict.get('document_passages') + QueryResultPassage.from_dict(v) for v in document_passages ] args.update( {k: v for (k, v) in _dict.items() if k not in cls._properties}) @@ -9250,15 +9762,15 @@ def __ne__(self, other: 'QueryResult') -> bool: return not self == other -class QueryResultMetadata(): +class QueryResultMetadata: """ Metadata of a query result. - :attr str document_retrieval_source: (optional) The document retrieval source + :param str document_retrieval_source: (optional) The document retrieval source that produced this search result. - :attr str collection_id: The collection id associated with this training data + :param str collection_id: The collection id associated with this training data set. - :attr float confidence: (optional) The confidence score for the given result. + :param float confidence: (optional) The confidence score for the given result. Calculated based on how relevant the result is estimated to be. The score can range from `0.0` to `1.0`. The higher the number, the more relevant the document. The `confidence` value for a result was calculated using the model @@ -9267,11 +9779,13 @@ class QueryResultMetadata(): in the query. """ - def __init__(self, - collection_id: str, - *, - document_retrieval_source: str = None, - confidence: float = None) -> None: + def __init__( + self, + collection_id: str, + *, + document_retrieval_source: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a QueryResultMetadata object. @@ -9295,17 +9809,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': """Initialize a QueryResultMetadata object from a json dictionary.""" args = {} - if 'document_retrieval_source' in _dict: - args['document_retrieval_source'] = _dict.get( - 'document_retrieval_source') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (document_retrieval_source := + _dict.get('document_retrieval_source')) is not None: + args['document_retrieval_source'] = document_retrieval_source + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id else: raise ValueError( 'Required property \'collection_id\' not present in QueryResultMetadata JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -9347,33 +9861,36 @@ class DocumentRetrievalSourceEnum(str, Enum): """ The document retrieval source that produced this search result. """ + SEARCH = 'search' CURATION = 'curation' -class QueryResultPassage(): +class QueryResultPassage: """ A passage query result. - :attr str passage_text: (optional) The content of the extracted passage. - :attr int start_offset: (optional) The position of the first character of the + :param str passage_text: (optional) The content of the extracted passage. + :param int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :attr int end_offset: (optional) The position after the last character of the + :param int end_offset: (optional) The position after the last character of the extracted passage in the originating field. - :attr str field: (optional) The label of the field from which the passage has + :param str field: (optional) The label of the field from which the passage has been extracted. - :attr List[ResultPassageAnswer] answers: (optional) An arry of extracted answers - to the specified query. Returned for natural language queries when + :param List[ResultPassageAnswer] answers: (optional) An arry of extracted + answers to the specified query. Returned for natural language queries when **passages.per_document** is `true`. """ - def __init__(self, - *, - passage_text: str = None, - start_offset: int = None, - end_offset: int = None, - field: str = None, - answers: List['ResultPassageAnswer'] = None) -> None: + def __init__( + self, + *, + passage_text: Optional[str] = None, + start_offset: Optional[int] = None, + end_offset: Optional[int] = None, + field: Optional[str] = None, + answers: Optional[List['ResultPassageAnswer']] = None, + ) -> None: """ Initialize a QueryResultPassage object. @@ -9398,17 +9915,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryResultPassage': """Initialize a QueryResultPassage object from a json dictionary.""" args = {} - if 'passage_text' in _dict: - args['passage_text'] = _dict.get('passage_text') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'answers' in _dict: + if (passage_text := _dict.get('passage_text')) is not None: + args['passage_text'] = passage_text + if (start_offset := _dict.get('start_offset')) is not None: + args['start_offset'] = start_offset + if (end_offset := _dict.get('end_offset')) is not None: + args['end_offset'] = end_offset + if (field := _dict.get('field')) is not None: + args['field'] = field + if (answers := _dict.get('answers')) is not None: args['answers'] = [ - ResultPassageAnswer.from_dict(v) for v in _dict.get('answers') + ResultPassageAnswer.from_dict(v) for v in answers ] return cls(**args) @@ -9457,15 +9974,19 @@ def __ne__(self, other: 'QueryResultPassage') -> bool: return not self == other -class QuerySuggestedRefinement(): +class QuerySuggestedRefinement: """ A suggested additional query term or terms user to filter results. **Note**: The `suggested_refinements` parameter is deprecated. - :attr str text: (optional) The text used to filter. + :param str text: (optional) The text used to filter. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a QuerySuggestedRefinement object. @@ -9477,8 +9998,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'QuerySuggestedRefinement': """Initialize a QuerySuggestedRefinement object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -9512,30 +10033,32 @@ def __ne__(self, other: 'QuerySuggestedRefinement') -> bool: return not self == other -class QueryTableResult(): +class QueryTableResult: """ A tables whose content or context match a search query. - :attr str table_id: (optional) The identifier for the retrieved table. - :attr str source_document_id: (optional) The identifier of the document the + :param str table_id: (optional) The identifier for the retrieved table. + :param str source_document_id: (optional) The identifier of the document the table was retrieved from. - :attr str collection_id: (optional) The identifier of the collection the table + :param str collection_id: (optional) The identifier of the collection the table was retrieved from. - :attr str table_html: (optional) HTML snippet of the table info. - :attr int table_html_offset: (optional) The offset of the table html snippet in + :param str table_html: (optional) HTML snippet of the table info. + :param int table_html_offset: (optional) The offset of the table html snippet in the original document html. - :attr TableResultTable table: (optional) Full table object retrieved from Table + :param TableResultTable table: (optional) Full table object retrieved from Table Understanding Enrichment. """ - def __init__(self, - *, - table_id: str = None, - source_document_id: str = None, - collection_id: str = None, - table_html: str = None, - table_html_offset: int = None, - table: 'TableResultTable' = None) -> None: + def __init__( + self, + *, + table_id: Optional[str] = None, + source_document_id: Optional[str] = None, + collection_id: Optional[str] = None, + table_html: Optional[str] = None, + table_html_offset: Optional[int] = None, + table: Optional['TableResultTable'] = None, + ) -> None: """ Initialize a QueryTableResult object. @@ -9561,18 +10084,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTableResult': """Initialize a QueryTableResult object from a json dictionary.""" args = {} - if 'table_id' in _dict: - args['table_id'] = _dict.get('table_id') - if 'source_document_id' in _dict: - args['source_document_id'] = _dict.get('source_document_id') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'table_html' in _dict: - args['table_html'] = _dict.get('table_html') - if 'table_html_offset' in _dict: - args['table_html_offset'] = _dict.get('table_html_offset') - if 'table' in _dict: - args['table'] = TableResultTable.from_dict(_dict.get('table')) + if (table_id := _dict.get('table_id')) is not None: + args['table_id'] = table_id + if (source_document_id := _dict.get('source_document_id')) is not None: + args['source_document_id'] = source_document_id + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id + if (table_html := _dict.get('table_html')) is not None: + args['table_html'] = table_html + if (table_html_offset := _dict.get('table_html_offset')) is not None: + args['table_html_offset'] = table_html_offset + if (table := _dict.get('table')) is not None: + args['table'] = TableResultTable.from_dict(table) return cls(**args) @classmethod @@ -9622,33 +10145,35 @@ def __ne__(self, other: 'QueryTableResult') -> bool: return not self == other -class QueryTermAggregationResult(): +class QueryTermAggregationResult: """ Top value result for the `term` aggregation. - :attr str key: Value of the field with a nonzero frequency in the document set. - :attr int matching_results: Number of documents that contain the 'key'. - :attr float relevancy: (optional) The relevancy score for this result. Returned + :param str key: Value of the field with a nonzero frequency in the document set. + :param int matching_results: Number of documents that contain the 'key'. + :param float relevancy: (optional) The relevancy score for this result. Returned only if `relevancy:true` is specified in the request. - :attr int total_matching_documents: (optional) Number of documents in the + :param int total_matching_documents: (optional) Number of documents in the collection that contain the term in the specified field. Returned only when `relevancy:true` is specified in the request. - :attr float estimated_matching_results: (optional) Number of documents that are + :param float estimated_matching_results: (optional) Number of documents that are estimated to match the query and also meet the condition. Returned only when `relevancy:true` is specified in the request. - :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + :param List[dict] aggregations: (optional) An array of subaggregations. Returned only when this aggregation is combined with other aggregations in the request or is returned as a subaggregation. """ - def __init__(self, - key: str, - matching_results: int, - *, - relevancy: float = None, - total_matching_documents: int = None, - estimated_matching_results: float = None, - aggregations: List[dict] = None) -> None: + def __init__( + self, + key: str, + matching_results: int, + *, + relevancy: Optional[float] = None, + total_matching_documents: Optional[int] = None, + estimated_matching_results: Optional[float] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTermAggregationResult object. @@ -9678,28 +10203,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': """Initialize a QueryTermAggregationResult object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryTermAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' ) - if 'relevancy' in _dict: - args['relevancy'] = _dict.get('relevancy') - if 'total_matching_documents' in _dict: - args['total_matching_documents'] = _dict.get( - 'total_matching_documents') - if 'estimated_matching_results' in _dict: - args['estimated_matching_results'] = _dict.get( - 'estimated_matching_results') - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (relevancy := _dict.get('relevancy')) is not None: + args['relevancy'] = relevancy + if (total_matching_documents := + _dict.get('total_matching_documents')) is not None: + args['total_matching_documents'] = total_matching_documents + if (estimated_matching_results := + _dict.get('estimated_matching_results')) is not None: + args['estimated_matching_results'] = estimated_matching_results + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -9747,26 +10272,28 @@ def __ne__(self, other: 'QueryTermAggregationResult') -> bool: return not self == other -class QueryTimesliceAggregationResult(): +class QueryTimesliceAggregationResult: """ A timeslice interval segment. - :attr str key_as_string: String date value of the upper bound for the timeslice + :param str key_as_string: String date value of the upper bound for the timeslice interval in ISO-8601 format. - :attr int key: Numeric date value of the upper bound for the timeslice interval + :param int key: Numeric date value of the upper bound for the timeslice interval in UNIX milliseconds since epoch. - :attr int matching_results: Number of documents with the specified key as the + :param int matching_results: Number of documents with the specified key as the upper bound. - :attr List[dict] aggregations: (optional) An array of subaggregations. Returned + :param List[dict] aggregations: (optional) An array of subaggregations. Returned only when this aggregation is returned as a subaggregation. """ - def __init__(self, - key_as_string: str, - key: int, - matching_results: int, - *, - aggregations: List[dict] = None) -> None: + def __init__( + self, + key_as_string: str, + key: int, + matching_results: int, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTimesliceAggregationResult object. @@ -9788,26 +10315,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" args = {} - if 'key_as_string' in _dict: - args['key_as_string'] = _dict.get('key_as_string') + if (key_as_string := _dict.get('key_as_string')) is not None: + args['key_as_string'] = key_as_string else: raise ValueError( 'Required property \'key_as_string\' not present in QueryTimesliceAggregationResult JSON' ) - if 'key' in _dict: - args['key'] = _dict.get('key') + if (key := _dict.get('key')) is not None: + args['key'] = key else: raise ValueError( 'Required property \'key\' not present in QueryTimesliceAggregationResult JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' ) - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -9848,19 +10375,21 @@ def __ne__(self, other: 'QueryTimesliceAggregationResult') -> bool: return not self == other -class QueryTopHitsAggregationResult(): +class QueryTopHitsAggregationResult: """ A query response that contains the matching documents for the preceding aggregations. - :attr int matching_results: Number of matching results. - :attr List[dict] hits: (optional) An array of the document results in an ordered - list. + :param int matching_results: Number of matching results. + :param List[dict] hits: (optional) An array of the document results in an + ordered list. """ - def __init__(self, - matching_results: int, - *, - hits: List[dict] = None) -> None: + def __init__( + self, + matching_results: int, + *, + hits: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTopHitsAggregationResult object. @@ -9875,14 +10404,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryTopHitsAggregationResult JSON' ) - if 'hits' in _dict: - args['hits'] = _dict.get('hits') + if (hits := _dict.get('hits')) is not None: + args['hits'] = hits return cls(**args) @classmethod @@ -9919,17 +10448,21 @@ def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: return not self == other -class QueryTopicAggregationResult(): +class QueryTopicAggregationResult: """ Result for the `topic` aggregation. - :attr List[dict] aggregations: (optional) Array of subaggregations of type + :param List[dict] aggregations: (optional) Array of subaggregations of type `term` or `group_by` and `timeslice`. Each element of the matrix that is returned contains a **topic_indicator** that is calculated from the combination of each aggregation value and segment of time. """ - def __init__(self, *, aggregations: List[dict] = None) -> None: + def __init__( + self, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTopicAggregationResult object. @@ -9944,8 +10477,8 @@ def __init__(self, *, aggregations: List[dict] = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryTopicAggregationResult': """Initialize a QueryTopicAggregationResult object from a json dictionary.""" args = {} - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -9979,17 +10512,21 @@ def __ne__(self, other: 'QueryTopicAggregationResult') -> bool: return not self == other -class QueryTrendAggregationResult(): +class QueryTrendAggregationResult: """ Result for the `trend` aggregation. - :attr List[dict] aggregations: (optional) Array of subaggregations of type + :param List[dict] aggregations: (optional) Array of subaggregations of type `term` or `group_by` and `timeslice`. Each element of the matrix that is returned contains a **trend_indicator** that is calculated from the combination of each aggregation value and segment of time. """ - def __init__(self, *, aggregations: List[dict] = None) -> None: + def __init__( + self, + *, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryTrendAggregationResult object. @@ -10004,8 +10541,8 @@ def __init__(self, *, aggregations: List[dict] = None) -> None: def from_dict(cls, _dict: Dict) -> 'QueryTrendAggregationResult': """Initialize a QueryTrendAggregationResult object from a json dictionary.""" args = {} - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -10039,26 +10576,28 @@ def __ne__(self, other: 'QueryTrendAggregationResult') -> bool: return not self == other -class ResultPassageAnswer(): +class ResultPassageAnswer: """ Object that contains a potential answer to the specified query. - :attr str answer_text: (optional) Answer text for the specified query as + :param str answer_text: (optional) Answer text for the specified query as identified by Discovery. - :attr int start_offset: (optional) The position of the first character of the + :param int start_offset: (optional) The position of the first character of the extracted answer in the originating field. - :attr int end_offset: (optional) The position after the last character of the + :param int end_offset: (optional) The position after the last character of the extracted answer in the originating field. - :attr float confidence: (optional) An estimate of the probability that the + :param float confidence: (optional) An estimate of the probability that the answer is relevant. """ - def __init__(self, - *, - answer_text: str = None, - start_offset: int = None, - end_offset: int = None, - confidence: float = None) -> None: + def __init__( + self, + *, + answer_text: Optional[str] = None, + start_offset: Optional[int] = None, + end_offset: Optional[int] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a ResultPassageAnswer object. @@ -10080,14 +10619,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ResultPassageAnswer': """Initialize a ResultPassageAnswer object from a json dictionary.""" args = {} - if 'answer_text' in _dict: - args['answer_text'] = _dict.get('answer_text') - if 'start_offset' in _dict: - args['start_offset'] = _dict.get('start_offset') - if 'end_offset' in _dict: - args['end_offset'] = _dict.get('end_offset') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (answer_text := _dict.get('answer_text')) is not None: + args['answer_text'] = answer_text + if (start_offset := _dict.get('start_offset')) is not None: + args['start_offset'] = start_offset + if (end_offset := _dict.get('end_offset')) is not None: + args['end_offset'] = end_offset + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -10127,11 +10666,11 @@ def __ne__(self, other: 'ResultPassageAnswer') -> bool: return not self == other -class RetrievalDetails(): +class RetrievalDetails: """ An object contain retrieval type information. - :attr str document_retrieval_strategy: (optional) Identifies the document + :param str document_retrieval_strategy: (optional) Identifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. **Note**: In the event of trained collections being queried, but the trained @@ -10139,7 +10678,11 @@ class RetrievalDetails(): listed as `untrained`. """ - def __init__(self, *, document_retrieval_strategy: str = None) -> None: + def __init__( + self, + *, + document_retrieval_strategy: Optional[str] = None, + ) -> None: """ Initialize a RetrievalDetails object. @@ -10156,9 +10699,9 @@ def __init__(self, *, document_retrieval_strategy: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': """Initialize a RetrievalDetails object from a json dictionary.""" args = {} - if 'document_retrieval_strategy' in _dict: - args['document_retrieval_strategy'] = _dict.get( - 'document_retrieval_strategy') + if (document_retrieval_strategy := + _dict.get('document_retrieval_strategy')) is not None: + args['document_retrieval_strategy'] = document_retrieval_strategy return cls(**args) @classmethod @@ -10202,18 +10745,22 @@ class DocumentRetrievalStrategyEnum(str, Enum): is not used to return results, the **document_retrieval_strategy** is listed as `untrained`. """ + UNTRAINED = 'untrained' RELEVANCY_TRAINING = 'relevancy_training' -class StopWordList(): +class StopWordList: """ List of words to filter out of text that is submitted in queries. - :attr List[str] stopwords: List of stop words. + :param List[str] stopwords: List of stop words. """ - def __init__(self, stopwords: List[str]) -> None: + def __init__( + self, + stopwords: List[str], + ) -> None: """ Initialize a StopWordList object. @@ -10225,8 +10772,8 @@ def __init__(self, stopwords: List[str]) -> None: def from_dict(cls, _dict: Dict) -> 'StopWordList': """Initialize a StopWordList object from a json dictionary.""" args = {} - if 'stopwords' in _dict: - args['stopwords'] = _dict.get('stopwords') + if (stopwords := _dict.get('stopwords')) is not None: + args['stopwords'] = stopwords else: raise ValueError( 'Required property \'stopwords\' not present in StopWordList JSON' @@ -10264,58 +10811,60 @@ def __ne__(self, other: 'StopWordList') -> bool: return not self == other -class TableBodyCells(): +class TableBodyCells: """ Cells that are not table header, column header, or row header cells. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr TableElementLocation location: (optional) The numeric location of the + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The textual contents of this cell from the input + :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :attr List[TableRowHeaderIds] row_header_ids: (optional) A list of table row + :param List[TableRowHeaderIds] row_header_ids: (optional) A list of table row header ids. - :attr List[TableRowHeaderTexts] row_header_texts: (optional) A list of table row - header texts. - :attr List[TableRowHeaderTextsNormalized] row_header_texts_normalized: + :param List[TableRowHeaderTexts] row_header_texts: (optional) A list of table + row header texts. + :param List[TableRowHeaderTextsNormalized] row_header_texts_normalized: (optional) A list of table row header texts normalized. - :attr List[TableColumnHeaderIds] column_header_ids: (optional) A list of table + :param List[TableColumnHeaderIds] column_header_ids: (optional) A list of table column header ids. - :attr List[TableColumnHeaderTexts] column_header_texts: (optional) A list of + :param List[TableColumnHeaderTexts] column_header_texts: (optional) A list of table column header texts. - :attr List[TableColumnHeaderTextsNormalized] column_header_texts_normalized: + :param List[TableColumnHeaderTextsNormalized] column_header_texts_normalized: (optional) A list of table column header texts normalized. - :attr List[DocumentAttribute] attributes: (optional) A list of document + :param List[DocumentAttribute] attributes: (optional) A list of document attributes. """ - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None, - row_header_ids: List['TableRowHeaderIds'] = None, - row_header_texts: List['TableRowHeaderTexts'] = None, - row_header_texts_normalized: List[ - 'TableRowHeaderTextsNormalized'] = None, - column_header_ids: List['TableColumnHeaderIds'] = None, - column_header_texts: List['TableColumnHeaderTexts'] = None, - column_header_texts_normalized: List[ - 'TableColumnHeaderTextsNormalized'] = None, - attributes: List['DocumentAttribute'] = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + row_header_ids: Optional[List['TableRowHeaderIds']] = None, + row_header_texts: Optional[List['TableRowHeaderTexts']] = None, + row_header_texts_normalized: Optional[ + List['TableRowHeaderTextsNormalized']] = None, + column_header_ids: Optional[List['TableColumnHeaderIds']] = None, + column_header_texts: Optional[List['TableColumnHeaderTexts']] = None, + column_header_texts_normalized: Optional[ + List['TableColumnHeaderTextsNormalized']] = None, + attributes: Optional[List['DocumentAttribute']] = None, + ) -> None: """ Initialize a TableBodyCells object. @@ -10369,54 +10918,52 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableBodyCells': """Initialize a TableBodyCells object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') - if 'row_header_ids' in _dict: + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end + if (row_header_ids := _dict.get('row_header_ids')) is not None: args['row_header_ids'] = [ - TableRowHeaderIds.from_dict(v) - for v in _dict.get('row_header_ids') + TableRowHeaderIds.from_dict(v) for v in row_header_ids ] - if 'row_header_texts' in _dict: + if (row_header_texts := _dict.get('row_header_texts')) is not None: args['row_header_texts'] = [ - TableRowHeaderTexts.from_dict(v) - for v in _dict.get('row_header_texts') + TableRowHeaderTexts.from_dict(v) for v in row_header_texts ] - if 'row_header_texts_normalized' in _dict: + if (row_header_texts_normalized := + _dict.get('row_header_texts_normalized')) is not None: args['row_header_texts_normalized'] = [ TableRowHeaderTextsNormalized.from_dict(v) - for v in _dict.get('row_header_texts_normalized') + for v in row_header_texts_normalized ] - if 'column_header_ids' in _dict: + if (column_header_ids := _dict.get('column_header_ids')) is not None: args['column_header_ids'] = [ - TableColumnHeaderIds.from_dict(v) - for v in _dict.get('column_header_ids') + TableColumnHeaderIds.from_dict(v) for v in column_header_ids ] - if 'column_header_texts' in _dict: + if (column_header_texts := + _dict.get('column_header_texts')) is not None: args['column_header_texts'] = [ - TableColumnHeaderTexts.from_dict(v) - for v in _dict.get('column_header_texts') + TableColumnHeaderTexts.from_dict(v) for v in column_header_texts ] - if 'column_header_texts_normalized' in _dict: + if (column_header_texts_normalized := + _dict.get('column_header_texts_normalized')) is not None: args['column_header_texts_normalized'] = [ TableColumnHeaderTextsNormalized.from_dict(v) - for v in _dict.get('column_header_texts_normalized') + for v in column_header_texts_normalized ] - if 'attributes' in _dict: + if (attributes := _dict.get('attributes')) is not None: args['attributes'] = [ - DocumentAttribute.from_dict(v) for v in _dict.get('attributes') + DocumentAttribute.from_dict(v) for v in attributes ] return cls(**args) @@ -10534,23 +11081,25 @@ def __ne__(self, other: 'TableBodyCells') -> bool: return not self == other -class TableCellKey(): +class TableCellKey: """ A key in a key-value pair. - :attr str cell_id: (optional) The unique ID of the key in the table. - :attr TableElementLocation location: (optional) The numeric location of the + :param str cell_id: (optional) The unique ID of the key in the table. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The text content of the table cell without HTML + :param str text: (optional) The text content of the table cell without HTML markup. """ - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + ) -> None: """ Initialize a TableCellKey object. @@ -10569,13 +11118,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableCellKey': """Initialize a TableCellKey object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -10616,23 +11164,25 @@ def __ne__(self, other: 'TableCellKey') -> bool: return not self == other -class TableCellValues(): +class TableCellValues: """ A value in a key-value pair. - :attr str cell_id: (optional) The unique ID of the value in the table. - :attr TableElementLocation location: (optional) The numeric location of the + :param str cell_id: (optional) The unique ID of the value in the table. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The text content of the table cell without HTML + :param str text: (optional) The text content of the table cell without HTML markup. """ - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + ) -> None: """ Initialize a TableCellValues object. @@ -10651,13 +11201,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableCellValues': """Initialize a TableCellValues object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -10698,15 +11247,19 @@ def __ne__(self, other: 'TableCellValues') -> bool: return not self == other -class TableColumnHeaderIds(): +class TableColumnHeaderIds: """ An array of values, each being the `id` value of a column header that is applicable to the current cell. - :attr str id: (optional) The `id` value of a column header. + :param str id: (optional) The `id` value of a column header. """ - def __init__(self, *, id: str = None) -> None: + def __init__( + self, + *, + id: Optional[str] = None, + ) -> None: """ Initialize a TableColumnHeaderIds object. @@ -10718,8 +11271,8 @@ def __init__(self, *, id: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderIds': """Initialize a TableColumnHeaderIds object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') + if (id := _dict.get('id')) is not None: + args['id'] = id return cls(**args) @classmethod @@ -10753,15 +11306,19 @@ def __ne__(self, other: 'TableColumnHeaderIds') -> bool: return not self == other -class TableColumnHeaderTexts(): +class TableColumnHeaderTexts: """ An array of values, each being the `text` value of a column header that is applicable to the current cell. - :attr str text: (optional) The `text` value of a column header. + :param str text: (optional) The `text` value of a column header. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a TableColumnHeaderTexts object. @@ -10773,8 +11330,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTexts': """Initialize a TableColumnHeaderTexts object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -10808,16 +11365,20 @@ def __ne__(self, other: 'TableColumnHeaderTexts') -> bool: return not self == other -class TableColumnHeaderTextsNormalized(): +class TableColumnHeaderTextsNormalized: """ If you provide customization input, the normalized version of the column header texts according to the customization; otherwise, the same value as `column_header_texts`. - :attr str text_normalized: (optional) The normalized version of a column header + :param str text_normalized: (optional) The normalized version of a column header text. """ - def __init__(self, *, text_normalized: str = None) -> None: + def __init__( + self, + *, + text_normalized: Optional[str] = None, + ) -> None: """ Initialize a TableColumnHeaderTextsNormalized object. @@ -10830,8 +11391,8 @@ def __init__(self, *, text_normalized: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTextsNormalized': """Initialize a TableColumnHeaderTextsNormalized object from a json dictionary.""" args = {} - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') + if (text_normalized := _dict.get('text_normalized')) is not None: + args['text_normalized'] = text_normalized return cls(**args) @classmethod @@ -10866,40 +11427,42 @@ def __ne__(self, other: 'TableColumnHeaderTextsNormalized') -> bool: return not self == other -class TableColumnHeaders(): +class TableColumnHeaders: """ Column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr dict location: (optional) The location of the column header cell in the + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param dict location: (optional) The location of the column header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. - :attr str text: (optional) The textual contents of this cell from the input + :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :attr str text_normalized: (optional) If you provide customization input, the + :param str text_normalized: (optional) If you provide customization input, the normalized version of the cell text according to the customization; otherwise, the same value as `text`. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ - def __init__(self, - *, - cell_id: str = None, - location: dict = None, - text: str = None, - text_normalized: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional[dict] = None, + text: Optional[str] = None, + text_normalized: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + ) -> None: """ Initialize a TableColumnHeaders object. @@ -10935,22 +11498,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableColumnHeaders': """Initialize a TableColumnHeaders object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = location + if (text := _dict.get('text')) is not None: + args['text'] = text + if (text_normalized := _dict.get('text_normalized')) is not None: + args['text_normalized'] = text_normalized + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end return cls(**args) @classmethod @@ -11003,16 +11566,20 @@ def __ne__(self, other: 'TableColumnHeaders') -> bool: return not self == other -class TableElementLocation(): +class TableElementLocation: """ The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr int begin: The element's `begin` index. - :attr int end: The element's `end` index. + :param int begin: The element's `begin` index. + :param int end: The element's `end` index. """ - def __init__(self, begin: int, end: int) -> None: + def __init__( + self, + begin: int, + end: int, + ) -> None: """ Initialize a TableElementLocation object. @@ -11026,14 +11593,14 @@ def __init__(self, begin: int, end: int) -> None: def from_dict(cls, _dict: Dict) -> 'TableElementLocation': """Initialize a TableElementLocation object from a json dictionary.""" args = {} - if 'begin' in _dict: - args['begin'] = _dict.get('begin') + if (begin := _dict.get('begin')) is not None: + args['begin'] = begin else: raise ValueError( 'Required property \'begin\' not present in TableElementLocation JSON' ) - if 'end' in _dict: - args['end'] = _dict.get('end') + if (end := _dict.get('end')) is not None: + args['end'] = end else: raise ValueError( 'Required property \'end\' not present in TableElementLocation JSON' @@ -11073,35 +11640,37 @@ def __ne__(self, other: 'TableElementLocation') -> bool: return not self == other -class TableHeaders(): +class TableHeaders: """ The contents of the current table's header. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr dict location: (optional) The location of the table header cell in the + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param dict location: (optional) The location of the table header cell in the current table as defined by its `begin` and `end` offsets, respectfully, in the input document. - :attr str text: (optional) The textual contents of the cell from the input + :param str text: (optional) The textual contents of the cell from the input document without associated markup content. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ - def __init__(self, - *, - cell_id: str = None, - location: dict = None, - text: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional[dict] = None, + text: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + ) -> None: """ Initialize a TableHeaders object. @@ -11133,20 +11702,20 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableHeaders': """Initialize a TableHeaders object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = location + if (text := _dict.get('text')) is not None: + args['text'] = text + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end return cls(**args) @classmethod @@ -11196,19 +11765,21 @@ def __ne__(self, other: 'TableHeaders') -> bool: return not self == other -class TableKeyValuePairs(): +class TableKeyValuePairs: """ Key-value pairs detected across cell boundaries. - :attr TableCellKey key: (optional) A key in a key-value pair. - :attr List[TableCellValues] value: (optional) A list of values in a key-value + :param TableCellKey key: (optional) A key in a key-value pair. + :param List[TableCellValues] value: (optional) A list of values in a key-value pair. """ - def __init__(self, - *, - key: 'TableCellKey' = None, - value: List['TableCellValues'] = None) -> None: + def __init__( + self, + *, + key: Optional['TableCellKey'] = None, + value: Optional[List['TableCellValues']] = None, + ) -> None: """ Initialize a TableKeyValuePairs object. @@ -11223,12 +11794,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableKeyValuePairs': """Initialize a TableKeyValuePairs object from a json dictionary.""" args = {} - if 'key' in _dict: - args['key'] = TableCellKey.from_dict(_dict.get('key')) - if 'value' in _dict: - args['value'] = [ - TableCellValues.from_dict(v) for v in _dict.get('value') - ] + if (key := _dict.get('key')) is not None: + args['key'] = TableCellKey.from_dict(key) + if (value := _dict.get('value')) is not None: + args['value'] = [TableCellValues.from_dict(v) for v in value] return cls(**args) @classmethod @@ -11273,48 +11842,50 @@ def __ne__(self, other: 'TableKeyValuePairs') -> bool: return not self == other -class TableResultTable(): +class TableResultTable: """ Full table object retrieved from Table Understanding Enrichment. - :attr TableElementLocation location: (optional) The numeric location of the + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The textual contents of the current table from the + :param str text: (optional) The textual contents of the current table from the input document without associated markup content. - :attr TableTextLocation section_title: (optional) Text and associated location + :param TableTextLocation section_title: (optional) Text and associated location within a table. - :attr TableTextLocation title: (optional) Text and associated location within a + :param TableTextLocation title: (optional) Text and associated location within a table. - :attr List[TableHeaders] table_headers: (optional) An array of table-level cells - that apply as headers to all the other cells in the current table. - :attr List[TableRowHeaders] row_headers: (optional) An array of row-level cells, - each applicable as a header to other cells in the same row as itself, of the - current table. - :attr List[TableColumnHeaders] column_headers: (optional) An array of + :param List[TableHeaders] table_headers: (optional) An array of table-level + cells that apply as headers to all the other cells in the current table. + :param List[TableRowHeaders] row_headers: (optional) An array of row-level + cells, each applicable as a header to other cells in the same row as itself, of + the current table. + :param List[TableColumnHeaders] column_headers: (optional) An array of column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. - :attr List[TableKeyValuePairs] key_value_pairs: (optional) An array of key-value - pairs identified in the current table. - :attr List[TableBodyCells] body_cells: (optional) An array of cells that are + :param List[TableKeyValuePairs] key_value_pairs: (optional) An array of + key-value pairs identified in the current table. + :param List[TableBodyCells] body_cells: (optional) An array of cells that are neither table header nor column header nor row header cells, of the current table with corresponding row and column header associations. - :attr List[TableTextLocation] contexts: (optional) An array of lists of textual + :param List[TableTextLocation] contexts: (optional) An array of lists of textual entries across the document related to the current table being parsed. """ - def __init__(self, - *, - location: 'TableElementLocation' = None, - text: str = None, - section_title: 'TableTextLocation' = None, - title: 'TableTextLocation' = None, - table_headers: List['TableHeaders'] = None, - row_headers: List['TableRowHeaders'] = None, - column_headers: List['TableColumnHeaders'] = None, - key_value_pairs: List['TableKeyValuePairs'] = None, - body_cells: List['TableBodyCells'] = None, - contexts: List['TableTextLocation'] = None) -> None: + def __init__( + self, + *, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + section_title: Optional['TableTextLocation'] = None, + title: Optional['TableTextLocation'] = None, + table_headers: Optional[List['TableHeaders']] = None, + row_headers: Optional[List['TableRowHeaders']] = None, + column_headers: Optional[List['TableColumnHeaders']] = None, + key_value_pairs: Optional[List['TableKeyValuePairs']] = None, + body_cells: Optional[List['TableBodyCells']] = None, + contexts: Optional[List['TableTextLocation']] = None, + ) -> None: """ Initialize a TableResultTable object. @@ -11359,41 +11930,37 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableResultTable': """Initialize a TableResultTable object from a json dictionary.""" args = {} - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'section_title' in _dict: - args['section_title'] = TableTextLocation.from_dict( - _dict.get('section_title')) - if 'title' in _dict: - args['title'] = TableTextLocation.from_dict(_dict.get('title')) - if 'table_headers' in _dict: + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (section_title := _dict.get('section_title')) is not None: + args['section_title'] = TableTextLocation.from_dict(section_title) + if (title := _dict.get('title')) is not None: + args['title'] = TableTextLocation.from_dict(title) + if (table_headers := _dict.get('table_headers')) is not None: args['table_headers'] = [ - TableHeaders.from_dict(v) for v in _dict.get('table_headers') + TableHeaders.from_dict(v) for v in table_headers ] - if 'row_headers' in _dict: + if (row_headers := _dict.get('row_headers')) is not None: args['row_headers'] = [ - TableRowHeaders.from_dict(v) for v in _dict.get('row_headers') + TableRowHeaders.from_dict(v) for v in row_headers ] - if 'column_headers' in _dict: + if (column_headers := _dict.get('column_headers')) is not None: args['column_headers'] = [ - TableColumnHeaders.from_dict(v) - for v in _dict.get('column_headers') + TableColumnHeaders.from_dict(v) for v in column_headers ] - if 'key_value_pairs' in _dict: + if (key_value_pairs := _dict.get('key_value_pairs')) is not None: args['key_value_pairs'] = [ - TableKeyValuePairs.from_dict(v) - for v in _dict.get('key_value_pairs') + TableKeyValuePairs.from_dict(v) for v in key_value_pairs ] - if 'body_cells' in _dict: + if (body_cells := _dict.get('body_cells')) is not None: args['body_cells'] = [ - TableBodyCells.from_dict(v) for v in _dict.get('body_cells') + TableBodyCells.from_dict(v) for v in body_cells ] - if 'contexts' in _dict: + if (contexts := _dict.get('contexts')) is not None: args['contexts'] = [ - TableTextLocation.from_dict(v) for v in _dict.get('contexts') + TableTextLocation.from_dict(v) for v in contexts ] return cls(**args) @@ -11492,15 +12059,19 @@ def __ne__(self, other: 'TableResultTable') -> bool: return not self == other -class TableRowHeaderIds(): +class TableRowHeaderIds: """ An array of values, each being the `id` value of a row header that is applicable to this body cell. - :attr str id: (optional) The `id` values of a row header. + :param str id: (optional) The `id` values of a row header. """ - def __init__(self, *, id: str = None) -> None: + def __init__( + self, + *, + id: Optional[str] = None, + ) -> None: """ Initialize a TableRowHeaderIds object. @@ -11512,8 +12083,8 @@ def __init__(self, *, id: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableRowHeaderIds': """Initialize a TableRowHeaderIds object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') + if (id := _dict.get('id')) is not None: + args['id'] = id return cls(**args) @classmethod @@ -11547,15 +12118,19 @@ def __ne__(self, other: 'TableRowHeaderIds') -> bool: return not self == other -class TableRowHeaderTexts(): +class TableRowHeaderTexts: """ An array of values, each being the `text` value of a row header that is applicable to this body cell. - :attr str text: (optional) The `text` value of a row header. + :param str text: (optional) The `text` value of a row header. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a TableRowHeaderTexts object. @@ -11567,8 +12142,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTexts': """Initialize a TableRowHeaderTexts object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -11602,16 +12177,20 @@ def __ne__(self, other: 'TableRowHeaderTexts') -> bool: return not self == other -class TableRowHeaderTextsNormalized(): +class TableRowHeaderTextsNormalized: """ If you provide customization input, the normalized version of the row header texts according to the customization; otherwise, the same value as `row_header_texts`. - :attr str text_normalized: (optional) The normalized version of a row header + :param str text_normalized: (optional) The normalized version of a row header text. """ - def __init__(self, *, text_normalized: str = None) -> None: + def __init__( + self, + *, + text_normalized: Optional[str] = None, + ) -> None: """ Initialize a TableRowHeaderTextsNormalized object. @@ -11624,8 +12203,8 @@ def __init__(self, *, text_normalized: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTextsNormalized': """Initialize a TableRowHeaderTextsNormalized object from a json dictionary.""" args = {} - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') + if (text_normalized := _dict.get('text_normalized')) is not None: + args['text_normalized'] = text_normalized return cls(**args) @classmethod @@ -11660,40 +12239,42 @@ def __ne__(self, other: 'TableRowHeaderTextsNormalized') -> bool: return not self == other -class TableRowHeaders(): +class TableRowHeaders: """ Row-level cells, each applicable as a header to other cells in the same row as itself, of the current table. - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr TableElementLocation location: (optional) The numeric location of the + :param str cell_id: (optional) The unique ID of the cell in the current table. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. - :attr str text: (optional) The textual contents of this cell from the input + :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :attr str text_normalized: (optional) If you provide customization input, the + :param str text_normalized: (optional) If you provide customization input, the normalized version of the cell text according to the customization; otherwise, the same value as `text`. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` + :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` + :param int row_index_end: (optional) The `end` index of this cell's `row` location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's + :param int column_index_begin: (optional) The `begin` index of this cell's `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` + :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. """ - def __init__(self, - *, - cell_id: str = None, - location: 'TableElementLocation' = None, - text: str = None, - text_normalized: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: + def __init__( + self, + *, + cell_id: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + text: Optional[str] = None, + text_normalized: Optional[str] = None, + row_index_begin: Optional[int] = None, + row_index_end: Optional[int] = None, + column_index_begin: Optional[int] = None, + column_index_end: Optional[int] = None, + ) -> None: """ Initialize a TableRowHeaders object. @@ -11729,23 +12310,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableRowHeaders': """Initialize a TableRowHeaders object from a json dictionary.""" args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') + if (cell_id := _dict.get('cell_id')) is not None: + args['cell_id'] = cell_id + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (text_normalized := _dict.get('text_normalized')) is not None: + args['text_normalized'] = text_normalized + if (row_index_begin := _dict.get('row_index_begin')) is not None: + args['row_index_begin'] = row_index_begin + if (row_index_end := _dict.get('row_index_end')) is not None: + args['row_index_end'] = row_index_end + if (column_index_begin := _dict.get('column_index_begin')) is not None: + args['column_index_begin'] = column_index_begin + if (column_index_end := _dict.get('column_index_end')) is not None: + args['column_index_end'] = column_index_end return cls(**args) @classmethod @@ -11801,20 +12381,22 @@ def __ne__(self, other: 'TableRowHeaders') -> bool: return not self == other -class TableTextLocation(): +class TableTextLocation: """ Text and associated location within a table. - :attr str text: (optional) The text retrieved. - :attr TableElementLocation location: (optional) The numeric location of the + :param str text: (optional) The text retrieved. + :param TableElementLocation location: (optional) The numeric location of the identified element in the document, represented with two integers labeled `begin` and `end`. """ - def __init__(self, - *, - text: str = None, - location: 'TableElementLocation' = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + location: Optional['TableElementLocation'] = None, + ) -> None: """ Initialize a TableTextLocation object. @@ -11830,11 +12412,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TableTextLocation': """Initialize a TableTextLocation object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = TableElementLocation.from_dict( - _dict.get('location')) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = TableElementLocation.from_dict(location) return cls(**args) @classmethod @@ -11873,25 +12454,27 @@ def __ne__(self, other: 'TableTextLocation') -> bool: return not self == other -class TrainingExample(): +class TrainingExample: """ Object that contains example response details for a training query. - :attr str document_id: The document ID associated with this training example. - :attr str collection_id: The collection ID associated with this training + :param str document_id: The document ID associated with this training example. + :param str collection_id: The collection ID associated with this training example. - :attr int relevance: The relevance of the training example. - :attr datetime created: (optional) The date and time the example was created. - :attr datetime updated: (optional) The date and time the example was updated. + :param int relevance: The relevance of the training example. + :param datetime created: (optional) The date and time the example was created. + :param datetime updated: (optional) The date and time the example was updated. """ - def __init__(self, - document_id: str, - collection_id: str, - relevance: int, - *, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + document_id: str, + collection_id: str, + relevance: int, + *, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a TrainingExample object. @@ -11911,28 +12494,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingExample': """Initialize a TrainingExample object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id else: raise ValueError( 'Required property \'document_id\' not present in TrainingExample JSON' ) - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') + if (collection_id := _dict.get('collection_id')) is not None: + args['collection_id'] = collection_id else: raise ValueError( 'Required property \'collection_id\' not present in TrainingExample JSON' ) - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance else: raise ValueError( 'Required property \'relevance\' not present in TrainingExample JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod @@ -11974,28 +12557,30 @@ def __ne__(self, other: 'TrainingExample') -> bool: return not self == other -class TrainingQuery(): +class TrainingQuery: """ Object that contains training query details. - :attr str query_id: (optional) The query ID associated with the training query. - :attr str natural_language_query: The natural text query that is used as the + :param str query_id: (optional) The query ID associated with the training query. + :param str natural_language_query: The natural text query that is used as the training query. - :attr str filter: (optional) The filter used on the collection before the + :param str filter: (optional) The filter used on the collection before the **natural_language_query** is applied. - :attr datetime created: (optional) The date and time the query was created. - :attr datetime updated: (optional) The date and time the query was updated. - :attr List[TrainingExample] examples: Array of training examples. + :param datetime created: (optional) The date and time the query was created. + :param datetime updated: (optional) The date and time the query was updated. + :param List[TrainingExample] examples: Array of training examples. """ - def __init__(self, - natural_language_query: str, - examples: List['TrainingExample'], - *, - query_id: str = None, - filter: str = None, - created: datetime = None, - updated: datetime = None) -> None: + def __init__( + self, + natural_language_query: str, + examples: List['TrainingExample'], + *, + query_id: Optional[str] = None, + filter: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ Initialize a TrainingQuery object. @@ -12016,24 +12601,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TrainingQuery': """Initialize a TrainingQuery object from a json dictionary.""" args = {} - if 'query_id' in _dict: - args['query_id'] = _dict.get('query_id') - if 'natural_language_query' in _dict: - args['natural_language_query'] = _dict.get('natural_language_query') + if (query_id := _dict.get('query_id')) is not None: + args['query_id'] = query_id + if (natural_language_query := + _dict.get('natural_language_query')) is not None: + args['natural_language_query'] = natural_language_query else: raise ValueError( 'Required property \'natural_language_query\' not present in TrainingQuery JSON' ) - if 'filter' in _dict: - args['filter'] = _dict.get('filter') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'examples' in _dict: - args['examples'] = [ - TrainingExample.from_dict(v) for v in _dict.get('examples') - ] + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (examples := _dict.get('examples')) is not None: + args['examples'] = [TrainingExample.from_dict(v) for v in examples] else: raise ValueError( 'Required property \'examples\' not present in TrainingQuery JSON' @@ -12088,16 +12672,20 @@ def __ne__(self, other: 'TrainingQuery') -> bool: return not self == other -class TrainingQuerySet(): +class TrainingQuerySet: """ Object specifying the training queries contained in the identified training set. - :attr List[TrainingQuery] queries: (optional) Array of training queries. At + :param List[TrainingQuery] queries: (optional) Array of training queries. At least 50 queries are required for training to begin. A maximum of 10,000 queries are returned. """ - def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: + def __init__( + self, + *, + queries: Optional[List['TrainingQuery']] = None, + ) -> None: """ Initialize a TrainingQuerySet object. @@ -12111,10 +12699,8 @@ def __init__(self, *, queries: List['TrainingQuery'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingQuerySet': """Initialize a TrainingQuerySet object from a json dictionary.""" args = {} - if 'queries' in _dict: - args['queries'] = [ - TrainingQuery.from_dict(v) for v in _dict.get('queries') - ] + if (queries := _dict.get('queries')) is not None: + args['queries'] = [TrainingQuery.from_dict(v) for v in queries] return cls(**args) @classmethod @@ -12154,16 +12740,21 @@ def __ne__(self, other: 'TrainingQuerySet') -> bool: return not self == other -class UpdateDocumentClassifier(): +class UpdateDocumentClassifier: """ An object that contains a new name or description for a document classifier, updated training data, or new or updated test data. - :attr str name: (optional) A new name for the classifier. - :attr str description: (optional) A new description for the classifier. + :param str name: (optional) A new name for the classifier. + :param str description: (optional) A new description for the classifier. """ - def __init__(self, *, name: str = None, description: str = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + ) -> None: """ Initialize a UpdateDocumentClassifier object. @@ -12177,10 +12768,10 @@ def __init__(self, *, name: str = None, description: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'UpdateDocumentClassifier': """Initialize a UpdateDocumentClassifier object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description return cls(**args) @classmethod @@ -12221,17 +12812,19 @@ class QueryAggregationQueryCalculationAggregation(QueryAggregation): Returns a scalar calculation across all documents for the field specified. Possible calculations include min, max, sum, average, and unique_count. - :attr str type: (optional) Specifies the calculation type, such as 'average`, + :param str type: (optional) Specifies the calculation type, such as 'average`, `max`, `min`, `sum`, or `unique_count`. - :attr str field: The field to perform the calculation on. - :attr float value: (optional) The value of the calculation. + :param str field: The field to perform the calculation on. + :param float value: (optional) The value of the calculation. """ - def __init__(self, - field: str, - *, - type: str = None, - value: float = None) -> None: + def __init__( + self, + field: str, + *, + type: Optional[str] = None, + value: Optional[float] = None, + ) -> None: """ Initialize a QueryAggregationQueryCalculationAggregation object. @@ -12250,16 +12843,16 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryCalculationAggregation': """Initialize a QueryAggregationQueryCalculationAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'field' in _dict: - args['field'] = _dict.get('field') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryAggregationQueryCalculationAggregation JSON' ) - if 'value' in _dict: - args['value'] = _dict.get('value') + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod @@ -12303,19 +12896,21 @@ class QueryAggregationQueryFilterAggregation(QueryAggregation): """ A modifier that narrows the document set of the subaggregations it precedes. - :attr str type: (optional) Specifies that the aggregation type is `filter`. - :attr str match: The filter that is written in Discovery Query Language syntax + :param str type: (optional) Specifies that the aggregation type is `filter`. + :param str match: The filter that is written in Discovery Query Language syntax and is applied to the documents before subaggregations are run. - :attr int matching_results: Number of documents that match the filter. - :attr List[dict] aggregations: (optional) An array of subaggregations. + :param int matching_results: Number of documents that match the filter. + :param List[dict] aggregations: (optional) An array of subaggregations. """ - def __init__(self, - match: str, - matching_results: int, - *, - type: str = None, - aggregations: List[dict] = None) -> None: + def __init__( + self, + match: str, + matching_results: int, + *, + type: Optional[str] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryAggregationQueryFilterAggregation object. @@ -12336,22 +12931,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryFilterAggregation': """Initialize a QueryAggregationQueryFilterAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'match' in _dict: - args['match'] = _dict.get('match') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (match := _dict.get('match')) is not None: + args['match'] = match else: raise ValueError( 'Required property \'match\' not present in QueryAggregationQueryFilterAggregation JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryAggregationQueryFilterAggregation JSON' ) - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -12396,15 +12991,17 @@ class QueryAggregationQueryGroupByAggregation(QueryAggregation): """ Separates document results into groups that meet the conditions you specify. - :attr str type: (optional) Specifies that the aggregation type is `group_by`. - :attr List[QueryGroupByAggregationResult] results: (optional) An array of + :param str type: (optional) Specifies that the aggregation type is `group_by`. + :param List[QueryGroupByAggregationResult] results: (optional) An array of results. """ - def __init__(self, - *, - type: str = None, - results: List['QueryGroupByAggregationResult'] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + results: Optional[List['QueryGroupByAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryGroupByAggregation object. @@ -12422,12 +13019,11 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryGroupByAggregation': """Initialize a QueryAggregationQueryGroupByAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryGroupByAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryGroupByAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -12475,23 +13071,24 @@ class QueryAggregationQueryHistogramAggregation(QueryAggregation): Numeric interval segments to categorize documents by using field values from a single numeric field to describe the category. - :attr str type: (optional) Specifies that the aggregation type is `histogram`. - :attr str field: The numeric field name used to create the histogram. - :attr int interval: The size of the sections that the results are split into. - :attr str name: (optional) Identifier that can optionally be specified in the + :param str type: (optional) Specifies that the aggregation type is `histogram`. + :param str field: The numeric field name used to create the histogram. + :param int interval: The size of the sections that the results are split into. + :param str name: (optional) Identifier that can optionally be specified in the query request of this aggregation. - :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric - intervals. + :param List[QueryHistogramAggregationResult] results: (optional) Array of + numeric intervals. """ def __init__( - self, - field: str, - interval: int, - *, - type: str = None, - name: str = None, - results: List['QueryHistogramAggregationResult'] = None) -> None: + self, + field: str, + interval: int, + *, + type: Optional[str] = None, + name: Optional[str] = None, + results: Optional[List['QueryHistogramAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryHistogramAggregation object. @@ -12517,26 +13114,25 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryHistogramAggregation': """Initialize a QueryAggregationQueryHistogramAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'field' in _dict: - args['field'] = _dict.get('field') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryAggregationQueryHistogramAggregation JSON' ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval else: raise ValueError( 'Required property \'interval\' not present in QueryAggregationQueryHistogramAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryHistogramAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryHistogramAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -12593,20 +13189,22 @@ class QueryAggregationQueryNestedAggregation(QueryAggregation): precedes. Subsequent aggregations are applied to nested documents from the specified field. - :attr str type: (optional) Specifies that the aggregation type is `nested`. - :attr str path: The path to the document field to scope subsequent aggregations + :param str type: (optional) Specifies that the aggregation type is `nested`. + :param str path: The path to the document field to scope subsequent aggregations to. - :attr int matching_results: Number of nested documents found in the specified + :param int matching_results: Number of nested documents found in the specified field. - :attr List[dict] aggregations: (optional) An array of subaggregations. + :param List[dict] aggregations: (optional) An array of subaggregations. """ - def __init__(self, - path: str, - matching_results: int, - *, - type: str = None, - aggregations: List[dict] = None) -> None: + def __init__( + self, + path: str, + matching_results: int, + *, + type: Optional[str] = None, + aggregations: Optional[List[dict]] = None, + ) -> None: """ Initialize a QueryAggregationQueryNestedAggregation object. @@ -12628,22 +13226,22 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryNestedAggregation': """Initialize a QueryAggregationQueryNestedAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'path' in _dict: - args['path'] = _dict.get('path') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (path := _dict.get('path')) is not None: + args['path'] = path else: raise ValueError( 'Required property \'path\' not present in QueryAggregationQueryNestedAggregation JSON' ) - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') + if (matching_results := _dict.get('matching_results')) is not None: + args['matching_results'] = matching_results else: raise ValueError( 'Required property \'matching_results\' not present in QueryAggregationQueryNestedAggregation JSON' ) - if 'aggregations' in _dict: - args['aggregations'] = _dict.get('aggregations') + if (aggregations := _dict.get('aggregations')) is not None: + args['aggregations'] = aggregations return cls(**args) @classmethod @@ -12689,29 +13287,31 @@ class QueryAggregationQueryPairAggregation(QueryAggregation): Calculates relevancy values using combinations of document sets from results of the specified pair of aggregations. - :attr str type: (optional) Specifies that the aggregation type is `pair`. - :attr str first: (optional) Specifies the first aggregation in the pair. The + :param str type: (optional) Specifies that the aggregation type is `pair`. + :param str first: (optional) Specifies the first aggregation in the pair. The aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` aggregation type. - :attr str second: (optional) Specifies the second aggregation in the pair. The + :param str second: (optional) Specifies the second aggregation in the pair. The aggregation must be a `term`, `group_by`, `histogram`, or `timeslice` aggregation type. - :attr bool show_estimated_matching_results: (optional) Indicates whether to + :param bool show_estimated_matching_results: (optional) Indicates whether to include estimated matching result information. - :attr bool show_total_matching_documents: (optional) Indicates whether to + :param bool show_total_matching_documents: (optional) Indicates whether to include total matching documents information. - :attr List[QueryPairAggregationResult] results: (optional) An array of + :param List[QueryPairAggregationResult] results: (optional) An array of aggregations. """ - def __init__(self, - *, - type: str = None, - first: str = None, - second: str = None, - show_estimated_matching_results: bool = None, - show_total_matching_documents: bool = None, - results: List['QueryPairAggregationResult'] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + first: Optional[str] = None, + second: Optional[str] = None, + show_estimated_matching_results: Optional[bool] = None, + show_total_matching_documents: Optional[bool] = None, + results: Optional[List['QueryPairAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryPairAggregation object. @@ -12741,22 +13341,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryPairAggregation': """Initialize a QueryAggregationQueryPairAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'first' in _dict: - args['first'] = _dict.get('first') - if 'second' in _dict: - args['second'] = _dict.get('second') - if 'show_estimated_matching_results' in _dict: - args['show_estimated_matching_results'] = _dict.get( - 'show_estimated_matching_results') - if 'show_total_matching_documents' in _dict: - args['show_total_matching_documents'] = _dict.get( - 'show_total_matching_documents') - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (first := _dict.get('first')) is not None: + args['first'] = first + if (second := _dict.get('second')) is not None: + args['second'] = second + if (show_estimated_matching_results := + _dict.get('show_estimated_matching_results')) is not None: + args[ + 'show_estimated_matching_results'] = show_estimated_matching_results + if (show_total_matching_documents := + _dict.get('show_total_matching_documents')) is not None: + args[ + 'show_total_matching_documents'] = show_total_matching_documents + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryPairAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryPairAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -12815,23 +13416,25 @@ class QueryAggregationQueryTermAggregation(QueryAggregation): """ Returns results from the field that is specified. - :attr str type: (optional) Specifies that the aggregation type is `term`. - :attr str field: (optional) The field in the document where the values come + :param str type: (optional) Specifies that the aggregation type is `term`. + :param str field: (optional) The field in the document where the values come from. - :attr int count: (optional) The number of results returned. Not returned if + :param int count: (optional) The number of results returned. Not returned if `relevancy:true` is specified in the request. - :attr str name: (optional) Identifier specified in the query request of this + :param str name: (optional) Identifier specified in the query request of this aggregation. Not returned if `relevancy:true` is specified in the request. - :attr List[QueryTermAggregationResult] results: (optional) An array of results. + :param List[QueryTermAggregationResult] results: (optional) An array of results. """ - def __init__(self, - *, - type: str = None, - field: str = None, - count: int = None, - name: str = None, - results: List['QueryTermAggregationResult'] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + field: Optional[str] = None, + count: Optional[int] = None, + name: Optional[str] = None, + results: Optional[List['QueryTermAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryTermAggregation object. @@ -12857,18 +13460,17 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTermAggregation': """Initialize a QueryAggregationQueryTermAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'field' in _dict: - args['field'] = _dict.get('field') - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field + if (count := _dict.get('count')) is not None: + args['count'] = count + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTermAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTermAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -12921,24 +13523,25 @@ class QueryAggregationQueryTimesliceAggregation(QueryAggregation): """ A specialized histogram aggregation that uses dates to create interval segments. - :attr str type: (optional) Specifies that the aggregation type is `timeslice`. - :attr str field: The date field name used to create the timeslice. - :attr str interval: The date interval value. Valid values are seconds, minutes, + :param str type: (optional) Specifies that the aggregation type is `timeslice`. + :param str field: The date field name used to create the timeslice. + :param str interval: The date interval value. Valid values are seconds, minutes, hours, days, weeks, and years. - :attr str name: (optional) Identifier that can optionally be specified in the + :param str name: (optional) Identifier that can optionally be specified in the query request of this aggregation. - :attr List[QueryTimesliceAggregationResult] results: (optional) Array of + :param List[QueryTimesliceAggregationResult] results: (optional) Array of aggregation results. """ def __init__( - self, - field: str, - interval: str, - *, - type: str = None, - name: str = None, - results: List['QueryTimesliceAggregationResult'] = None) -> None: + self, + field: str, + interval: str, + *, + type: Optional[str] = None, + name: Optional[str] = None, + results: Optional[List['QueryTimesliceAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryTimesliceAggregation object. @@ -12964,26 +13567,25 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTimesliceAggregation': """Initialize a QueryAggregationQueryTimesliceAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'field' in _dict: - args['field'] = _dict.get('field') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (field := _dict.get('field')) is not None: + args['field'] = field else: raise ValueError( 'Required property \'field\' not present in QueryAggregationQueryTimesliceAggregation JSON' ) - if 'interval' in _dict: - args['interval'] = _dict.get('interval') + if (interval := _dict.get('interval')) is not None: + args['interval'] = interval else: raise ValueError( 'Required property \'interval\' not present in QueryAggregationQueryTimesliceAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'results' in _dict: + if (name := _dict.get('name')) is not None: + args['name'] = name + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTimesliceAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTimesliceAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -13038,20 +13640,22 @@ class QueryAggregationQueryTopHitsAggregation(QueryAggregation): """ Returns the top documents ranked by the score of the query. - :attr str type: (optional) Specifies that the aggregation type is `top_hits`. - :attr int size: The number of documents to return. - :attr str name: (optional) Identifier specified in the query request of this + :param str type: (optional) Specifies that the aggregation type is `top_hits`. + :param int size: The number of documents to return. + :param str name: (optional) Identifier specified in the query request of this aggregation. - :attr QueryTopHitsAggregationResult hits: (optional) A query response that + :param QueryTopHitsAggregationResult hits: (optional) A query response that contains the matching documents for the preceding aggregations. """ - def __init__(self, - size: int, - *, - type: str = None, - name: str = None, - hits: 'QueryTopHitsAggregationResult' = None) -> None: + def __init__( + self, + size: int, + *, + type: Optional[str] = None, + name: Optional[str] = None, + hits: Optional['QueryTopHitsAggregationResult'] = None, + ) -> None: """ Initialize a QueryAggregationQueryTopHitsAggregation object. @@ -13074,19 +13678,18 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTopHitsAggregation': """Initialize a QueryAggregationQueryTopHitsAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'size' in _dict: - args['size'] = _dict.get('size') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (size := _dict.get('size')) is not None: + args['size'] = size else: raise ValueError( 'Required property \'size\' not present in QueryAggregationQueryTopHitsAggregation JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'hits' in _dict: - args['hits'] = QueryTopHitsAggregationResult.from_dict( - _dict.get('hits')) + if (name := _dict.get('name')) is not None: + args['name'] = name + if (hits := _dict.get('hits')) is not None: + args['hits'] = QueryTopHitsAggregationResult.from_dict(hits) return cls(**args) @classmethod @@ -13136,27 +13739,29 @@ class QueryAggregationQueryTopicAggregation(QueryAggregation): previous time periods. It calculates an index by using the averages of frequency counts of other facet values for the given time period. - :attr str type: (optional) Specifies that the aggregation type is `topic`. - :attr str facet: (optional) Specifies the `term` or `group_by` aggregation for + :param str type: (optional) Specifies that the aggregation type is `topic`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation for the facet that you want to analyze. - :attr str time_segments: (optional) Specifies the `timeslice` aggregation that + :param str time_segments: (optional) Specifies the `timeslice` aggregation that defines the time segments. - :attr bool show_estimated_matching_results: (optional) Indicates whether to + :param bool show_estimated_matching_results: (optional) Indicates whether to include estimated matching result information. - :attr bool show_total_matching_documents: (optional) Indicates whether to + :param bool show_total_matching_documents: (optional) Indicates whether to include total matching documents information. - :attr List[QueryTopicAggregationResult] results: (optional) An array of + :param List[QueryTopicAggregationResult] results: (optional) An array of aggregations. """ - def __init__(self, - *, - type: str = None, - facet: str = None, - time_segments: str = None, - show_estimated_matching_results: bool = None, - show_total_matching_documents: bool = None, - results: List['QueryTopicAggregationResult'] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + facet: Optional[str] = None, + time_segments: Optional[str] = None, + show_estimated_matching_results: Optional[bool] = None, + show_total_matching_documents: Optional[bool] = None, + results: Optional[List['QueryTopicAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryTopicAggregation object. @@ -13184,22 +13789,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTopicAggregation': """Initialize a QueryAggregationQueryTopicAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'facet' in _dict: - args['facet'] = _dict.get('facet') - if 'time_segments' in _dict: - args['time_segments'] = _dict.get('time_segments') - if 'show_estimated_matching_results' in _dict: - args['show_estimated_matching_results'] = _dict.get( - 'show_estimated_matching_results') - if 'show_total_matching_documents' in _dict: - args['show_total_matching_documents'] = _dict.get( - 'show_total_matching_documents') - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (facet := _dict.get('facet')) is not None: + args['facet'] = facet + if (time_segments := _dict.get('time_segments')) is not None: + args['time_segments'] = time_segments + if (show_estimated_matching_results := + _dict.get('show_estimated_matching_results')) is not None: + args[ + 'show_estimated_matching_results'] = show_estimated_matching_results + if (show_total_matching_documents := + _dict.get('show_total_matching_documents')) is not None: + args[ + 'show_total_matching_documents'] = show_total_matching_documents + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTopicAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTopicAggregationResult.from_dict(v) for v in results ] return cls(**args) @@ -13259,27 +13865,29 @@ class QueryAggregationQueryTrendAggregation(QueryAggregation): Detects sharp and unexpected changes in the frequency of a facet or facet value over time based on the past history of frequency changes of the facet value. - :attr str type: (optional) Specifies that the aggregation type is `trend`. - :attr str facet: (optional) Specifies the `term` or `group_by` aggregation for + :param str type: (optional) Specifies that the aggregation type is `trend`. + :param str facet: (optional) Specifies the `term` or `group_by` aggregation for the facet that you want to analyze. - :attr str time_segments: (optional) Specifies the `timeslice` aggregation that + :param str time_segments: (optional) Specifies the `timeslice` aggregation that defines the time segments. - :attr bool show_estimated_matching_results: (optional) Indicates whether to + :param bool show_estimated_matching_results: (optional) Indicates whether to include estimated matching result information. - :attr bool show_total_matching_documents: (optional) Indicates whether to + :param bool show_total_matching_documents: (optional) Indicates whether to include total matching documents information. - :attr List[QueryTrendAggregationResult] results: (optional) An array of + :param List[QueryTrendAggregationResult] results: (optional) An array of aggregations. """ - def __init__(self, - *, - type: str = None, - facet: str = None, - time_segments: str = None, - show_estimated_matching_results: bool = None, - show_total_matching_documents: bool = None, - results: List['QueryTrendAggregationResult'] = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + facet: Optional[str] = None, + time_segments: Optional[str] = None, + show_estimated_matching_results: Optional[bool] = None, + show_total_matching_documents: Optional[bool] = None, + results: Optional[List['QueryTrendAggregationResult']] = None, + ) -> None: """ Initialize a QueryAggregationQueryTrendAggregation object. @@ -13307,22 +13915,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'QueryAggregationQueryTrendAggregation': """Initialize a QueryAggregationQueryTrendAggregation object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'facet' in _dict: - args['facet'] = _dict.get('facet') - if 'time_segments' in _dict: - args['time_segments'] = _dict.get('time_segments') - if 'show_estimated_matching_results' in _dict: - args['show_estimated_matching_results'] = _dict.get( - 'show_estimated_matching_results') - if 'show_total_matching_documents' in _dict: - args['show_total_matching_documents'] = _dict.get( - 'show_total_matching_documents') - if 'results' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (facet := _dict.get('facet')) is not None: + args['facet'] = facet + if (time_segments := _dict.get('time_segments')) is not None: + args['time_segments'] = time_segments + if (show_estimated_matching_results := + _dict.get('show_estimated_matching_results')) is not None: + args[ + 'show_estimated_matching_results'] = show_estimated_matching_results + if (show_total_matching_documents := + _dict.get('show_total_matching_documents')) is not None: + args[ + 'show_total_matching_documents'] = show_total_matching_documents + if (results := _dict.get('results')) is not None: args['results'] = [ - QueryTrendAggregationResult.from_dict(v) - for v in _dict.get('results') + QueryTrendAggregationResult.from_dict(v) for v in results ] return cls(**args) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 448e78ec8..4dc606185 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM-provided translation models that you can customize based on @@ -29,7 +29,7 @@ from datetime import datetime from enum import Enum from os.path import basename -from typing import BinaryIO, Dict, List, TextIO, Union +from typing import BinaryIO, Dict, List, Optional, TextIO, Union import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -81,7 +81,10 @@ def __init__( # Languages ######################### - def list_languages(self, **kwargs) -> DetailedResponse: + def list_languages( + self, + **kwargs, + ) -> DetailedResponse: """ List supported languages. @@ -98,9 +101,11 @@ def list_languages(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_languages') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_languages', + ) headers.update(sdk_headers) params = { @@ -113,10 +118,12 @@ def list_languages(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v3/languages' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -125,13 +132,15 @@ def list_languages(self, **kwargs) -> DetailedResponse: # Translation ######################### - def translate(self, - text: List[str], - *, - model_id: str = None, - source: str = None, - target: str = None, - **kwargs) -> DetailedResponse: + def translate( + self, + text: List[str], + *, + model_id: Optional[str] = None, + source: Optional[str] = None, + target: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Translate. @@ -166,9 +175,11 @@ def translate(self, if text is None: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='translate') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='translate', + ) headers.update(sdk_headers) params = { @@ -191,11 +202,13 @@ def translate(self, headers['Accept'] = 'application/json' url = '/v3/translate' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -204,7 +217,10 @@ def translate(self, # Identification ######################### - def list_identifiable_languages(self, **kwargs) -> DetailedResponse: + def list_identifiable_languages( + self, + **kwargs, + ) -> DetailedResponse: """ List identifiable languages. @@ -220,7 +236,8 @@ def list_identifiable_languages(self, **kwargs) -> DetailedResponse: sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V3', - operation_id='list_identifiable_languages') + operation_id='list_identifiable_languages', + ) headers.update(sdk_headers) params = { @@ -233,15 +250,21 @@ def list_identifiable_languages(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v3/identifiable_languages' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: + def identify( + self, + text: Union[str, TextIO], + **kwargs, + ) -> DetailedResponse: """ Identify language. @@ -256,9 +279,11 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='identify') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='identify', + ) headers.update(sdk_headers) params = { @@ -274,11 +299,13 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v3/identify' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -287,12 +314,14 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: # Models ######################### - def list_models(self, - *, - source: str = None, - target: str = None, - default: bool = None, - **kwargs) -> DetailedResponse: + def list_models( + self, + *, + source: Optional[str] = None, + target: Optional[str] = None, + default: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ List models. @@ -313,9 +342,11 @@ def list_models(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_models', + ) headers.update(sdk_headers) params = { @@ -331,23 +362,27 @@ def list_models(self, headers['Accept'] = 'application/json' url = '/v3/models' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_model(self, - base_model_id: str, - *, - forced_glossary: BinaryIO = None, - forced_glossary_content_type: str = None, - parallel_corpus: BinaryIO = None, - parallel_corpus_content_type: str = None, - name: str = None, - **kwargs) -> DetailedResponse: + def create_model( + self, + base_model_id: str, + *, + forced_glossary: Optional[BinaryIO] = None, + forced_glossary_content_type: Optional[str] = None, + parallel_corpus: Optional[BinaryIO] = None, + parallel_corpus_content_type: Optional[str] = None, + name: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create model. @@ -451,9 +486,11 @@ def create_model(self, if not base_model_id: raise ValueError('base_model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='create_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='create_model', + ) headers.update(sdk_headers) params = { @@ -480,16 +517,22 @@ def create_model(self, headers['Accept'] = 'application/json' url = '/v3/models' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: + def delete_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete model. @@ -504,9 +547,11 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='delete_model', + ) headers.update(sdk_headers) params = { @@ -522,15 +567,21 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_model(self, model_id: str, **kwargs) -> DetailedResponse: + def get_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get model details. @@ -547,9 +598,11 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_model', + ) headers.update(sdk_headers) params = { @@ -565,10 +618,12 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -577,7 +632,10 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: # Document translation ######################### - def list_documents(self, **kwargs) -> DetailedResponse: + def list_documents( + self, + **kwargs, + ) -> DetailedResponse: """ List documents. @@ -589,9 +647,11 @@ def list_documents(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_documents') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='list_documents', + ) headers.update(sdk_headers) params = { @@ -604,24 +664,28 @@ def list_documents(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v3/documents' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def translate_document(self, - file: BinaryIO, - *, - filename: str = None, - file_content_type: str = None, - model_id: str = None, - source: str = None, - target: str = None, - document_id: str = None, - **kwargs) -> DetailedResponse: + def translate_document( + self, + file: BinaryIO, + *, + filename: Optional[str] = None, + file_content_type: Optional[str] = None, + model_id: Optional[str] = None, + source: Optional[str] = None, + target: Optional[str] = None, + document_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Translate document. @@ -685,9 +749,11 @@ def translate_document(self, if file is None: raise ValueError('file must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='translate_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='translate_document', + ) headers.update(sdk_headers) params = { @@ -716,17 +782,22 @@ def translate_document(self, headers['Accept'] = 'application/json' url = '/v3/documents' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_document_status(self, document_id: str, - **kwargs) -> DetailedResponse: + def get_document_status( + self, + document_id: str, + **kwargs, + ) -> DetailedResponse: """ Get document status. @@ -741,9 +812,11 @@ def get_document_status(self, document_id: str, if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_document_status') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_document_status', + ) headers.update(sdk_headers) params = { @@ -759,15 +832,21 @@ def get_document_status(self, document_id: str, path_param_values = self.encode_path_vars(document_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/documents/{document_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: + def delete_document( + self, + document_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete document. @@ -782,9 +861,11 @@ def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: if not document_id: raise ValueError('document_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='delete_document', + ) headers.update(sdk_headers) params = { @@ -799,19 +880,23 @@ def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(document_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/documents/{document_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_translated_document(self, - document_id: str, - *, - accept: str = None, - **kwargs) -> DetailedResponse: + def get_translated_document( + self, + document_id: str, + *, + accept: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Get translated document. @@ -843,9 +928,11 @@ def get_translated_document(self, headers = { 'Accept': accept, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_translated_document') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V3', + operation_id='get_translated_document', + ) headers.update(sdk_headers) params = { @@ -861,10 +948,12 @@ def get_translated_document(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v3/documents/{document_id}/translated_document'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -879,6 +968,7 @@ class ForcedGlossaryContentType(str, Enum): """ The content type of forced_glossary. """ + APPLICATION_X_TMX_XML = 'application/x-tmx+xml' APPLICATION_XLIFF_XML = 'application/xliff+xml' TEXT_CSV = 'text/csv' @@ -890,6 +980,7 @@ class ParallelCorpusContentType(str, Enum): """ The content type of parallel_corpus. """ + APPLICATION_X_TMX_XML = 'application/x-tmx+xml' APPLICATION_XLIFF_XML = 'application/xliff+xml' TEXT_CSV = 'text/csv' @@ -907,6 +998,7 @@ class FileContentType(str, Enum): """ The content type of file. """ + APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' APPLICATION_MSWORD = 'application/msword' APPLICATION_OCTET_STREAM = 'application/octet-stream' @@ -957,6 +1049,7 @@ class Accept(str, Enum): character encoding can be specified by including a `charset` parameter. For example, 'text/html;charset=utf-8'. """ + APPLICATION_POWERPOINT = 'application/powerpoint' APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' APPLICATION_X_RTF = 'application/x-rtf' @@ -986,14 +1079,17 @@ class Accept(str, Enum): ############################################################################## -class DeleteModelResult(): +class DeleteModelResult: """ DeleteModelResult. - :attr str status: "OK" indicates that the model was successfully deleted. + :param str status: "OK" indicates that the model was successfully deleted. """ - def __init__(self, status: str) -> None: + def __init__( + self, + status: str, + ) -> None: """ Initialize a DeleteModelResult object. @@ -1005,8 +1101,8 @@ def __init__(self, status: str) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteModelResult': """Initialize a DeleteModelResult object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in DeleteModelResult JSON' @@ -1044,15 +1140,18 @@ def __ne__(self, other: 'DeleteModelResult') -> bool: return not self == other -class DocumentList(): +class DocumentList: """ DocumentList. - :attr List[DocumentStatus] documents: An array of all previously submitted + :param List[DocumentStatus] documents: An array of all previously submitted documents. """ - def __init__(self, documents: List['DocumentStatus']) -> None: + def __init__( + self, + documents: List['DocumentStatus'], + ) -> None: """ Initialize a DocumentList object. @@ -1065,10 +1164,8 @@ def __init__(self, documents: List['DocumentStatus']) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentList': """Initialize a DocumentList object from a json dictionary.""" args = {} - if 'documents' in _dict: - args['documents'] = [ - DocumentStatus.from_dict(v) for v in _dict.get('documents') - ] + if (documents := _dict.get('documents')) is not None: + args['documents'] = [DocumentStatus.from_dict(v) for v in documents] else: raise ValueError( 'Required property \'documents\' not present in DocumentList JSON' @@ -1112,49 +1209,51 @@ def __ne__(self, other: 'DocumentList') -> bool: return not self == other -class DocumentStatus(): +class DocumentStatus: """ Document information, including translation status. - :attr str document_id: System generated ID identifying a document being + :param str document_id: System generated ID identifying a document being translated using one specific translation model. - :attr str filename: filename from the submission (if it was missing in the + :param str filename: filename from the submission (if it was missing in the multipart-form, 'noname.' is used. - :attr str status: The status of the translation job associated with a submitted + :param str status: The status of the translation job associated with a submitted document. - :attr str model_id: A globally unique string that identifies the underlying + :param str model_id: A globally unique string that identifies the underlying model that is used for translation. - :attr str base_model_id: (optional) Model ID of the base model that was used to + :param str base_model_id: (optional) Model ID of the base model that was used to customize the model. If the model is not a custom model, this will be absent or an empty string. - :attr str source: Translation source language code. - :attr float detected_language_confidence: (optional) A score between 0 and 1 + :param str source: Translation source language code. + :param float detected_language_confidence: (optional) A score between 0 and 1 indicating the confidence of source language detection. A higher value indicates greater confidence. This is returned only when the service automatically detects the source language. - :attr str target: Translation target language code. - :attr datetime created: The time when the document was submitted. - :attr datetime completed: (optional) The time when the translation completed. - :attr int word_count: (optional) An estimate of the number of words in the + :param str target: Translation target language code. + :param datetime created: The time when the document was submitted. + :param datetime completed: (optional) The time when the translation completed. + :param int word_count: (optional) An estimate of the number of words in the source document. Returned only if `status` is `available`. - :attr int character_count: (optional) The number of characters in the source + :param int character_count: (optional) The number of characters in the source document, present only if status=available. """ - def __init__(self, - document_id: str, - filename: str, - status: str, - model_id: str, - source: str, - target: str, - created: datetime, - *, - base_model_id: str = None, - detected_language_confidence: float = None, - completed: datetime = None, - word_count: int = None, - character_count: int = None) -> None: + def __init__( + self, + document_id: str, + filename: str, + status: str, + model_id: str, + source: str, + target: str, + created: datetime, + *, + base_model_id: Optional[str] = None, + detected_language_confidence: Optional[float] = None, + completed: Optional[datetime] = None, + word_count: Optional[int] = None, + character_count: Optional[int] = None, + ) -> None: """ Initialize a DocumentStatus object. @@ -1200,59 +1299,59 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DocumentStatus': """Initialize a DocumentStatus object from a json dictionary.""" args = {} - if 'document_id' in _dict: - args['document_id'] = _dict.get('document_id') + if (document_id := _dict.get('document_id')) is not None: + args['document_id'] = document_id else: raise ValueError( 'Required property \'document_id\' not present in DocumentStatus JSON' ) - if 'filename' in _dict: - args['filename'] = _dict.get('filename') + if (filename := _dict.get('filename')) is not None: + args['filename'] = filename else: raise ValueError( 'Required property \'filename\' not present in DocumentStatus JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in DocumentStatus JSON' ) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id else: raise ValueError( 'Required property \'model_id\' not present in DocumentStatus JSON' ) - if 'base_model_id' in _dict: - args['base_model_id'] = _dict.get('base_model_id') - if 'source' in _dict: - args['source'] = _dict.get('source') + if (base_model_id := _dict.get('base_model_id')) is not None: + args['base_model_id'] = base_model_id + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in DocumentStatus JSON' ) - if 'detected_language_confidence' in _dict: - args['detected_language_confidence'] = _dict.get( - 'detected_language_confidence') - if 'target' in _dict: - args['target'] = _dict.get('target') + if (detected_language_confidence := + _dict.get('detected_language_confidence')) is not None: + args['detected_language_confidence'] = detected_language_confidence + if (target := _dict.get('target')) is not None: + args['target'] = target else: raise ValueError( 'Required property \'target\' not present in DocumentStatus JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) else: raise ValueError( 'Required property \'created\' not present in DocumentStatus JSON' ) - if 'completed' in _dict: - args['completed'] = string_to_datetime(_dict.get('completed')) - if 'word_count' in _dict: - args['word_count'] = _dict.get('word_count') - if 'character_count' in _dict: - args['character_count'] = _dict.get('character_count') + if (completed := _dict.get('completed')) is not None: + args['completed'] = string_to_datetime(completed) + if (word_count := _dict.get('word_count')) is not None: + args['word_count'] = word_count + if (character_count := _dict.get('character_count')) is not None: + args['character_count'] = character_count return cls(**args) @classmethod @@ -1314,20 +1413,25 @@ class StatusEnum(str, Enum): """ The status of the translation job associated with a submitted document. """ + PROCESSING = 'processing' AVAILABLE = 'available' FAILED = 'failed' -class IdentifiableLanguage(): +class IdentifiableLanguage: """ IdentifiableLanguage. - :attr str language: The language code for an identifiable language. - :attr str name: The name of the identifiable language. + :param str language: The language code for an identifiable language. + :param str name: The name of the identifiable language. """ - def __init__(self, language: str, name: str) -> None: + def __init__( + self, + language: str, + name: str, + ) -> None: """ Initialize a IdentifiableLanguage object. @@ -1341,14 +1445,14 @@ def __init__(self, language: str, name: str) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguage': """Initialize a IdentifiableLanguage object from a json dictionary.""" args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in IdentifiableLanguage JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in IdentifiableLanguage JSON' @@ -1388,15 +1492,18 @@ def __ne__(self, other: 'IdentifiableLanguage') -> bool: return not self == other -class IdentifiableLanguages(): +class IdentifiableLanguages: """ IdentifiableLanguages. - :attr List[IdentifiableLanguage] languages: A list of all languages that the + :param List[IdentifiableLanguage] languages: A list of all languages that the service can identify. """ - def __init__(self, languages: List['IdentifiableLanguage']) -> None: + def __init__( + self, + languages: List['IdentifiableLanguage'], + ) -> None: """ Initialize a IdentifiableLanguages object. @@ -1409,10 +1516,9 @@ def __init__(self, languages: List['IdentifiableLanguage']) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguages': """Initialize a IdentifiableLanguages object from a json dictionary.""" args = {} - if 'languages' in _dict: + if (languages := _dict.get('languages')) is not None: args['languages'] = [ - IdentifiableLanguage.from_dict(v) - for v in _dict.get('languages') + IdentifiableLanguage.from_dict(v) for v in languages ] else: raise ValueError( @@ -1457,15 +1563,19 @@ def __ne__(self, other: 'IdentifiableLanguages') -> bool: return not self == other -class IdentifiedLanguage(): +class IdentifiedLanguage: """ IdentifiedLanguage. - :attr str language: The language code for an identified language. - :attr float confidence: The confidence score for the identified language. + :param str language: The language code for an identified language. + :param float confidence: The confidence score for the identified language. """ - def __init__(self, language: str, confidence: float) -> None: + def __init__( + self, + language: str, + confidence: float, + ) -> None: """ Initialize a IdentifiedLanguage object. @@ -1479,14 +1589,14 @@ def __init__(self, language: str, confidence: float) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguage': """Initialize a IdentifiedLanguage object from a json dictionary.""" args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in IdentifiedLanguage JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in IdentifiedLanguage JSON' @@ -1526,15 +1636,18 @@ def __ne__(self, other: 'IdentifiedLanguage') -> bool: return not self == other -class IdentifiedLanguages(): +class IdentifiedLanguages: """ IdentifiedLanguages. - :attr List[IdentifiedLanguage] languages: A ranking of identified languages with - confidence scores. + :param List[IdentifiedLanguage] languages: A ranking of identified languages + with confidence scores. """ - def __init__(self, languages: List['IdentifiedLanguage']) -> None: + def __init__( + self, + languages: List['IdentifiedLanguage'], + ) -> None: """ Initialize a IdentifiedLanguages object. @@ -1547,9 +1660,9 @@ def __init__(self, languages: List['IdentifiedLanguage']) -> None: def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguages': """Initialize a IdentifiedLanguages object from a json dictionary.""" args = {} - if 'languages' in _dict: + if (languages := _dict.get('languages')) is not None: args['languages'] = [ - IdentifiedLanguage.from_dict(v) for v in _dict.get('languages') + IdentifiedLanguage.from_dict(v) for v in languages ] else: raise ValueError( @@ -1594,45 +1707,47 @@ def __ne__(self, other: 'IdentifiedLanguages') -> bool: return not self == other -class Language(): +class Language: """ Response payload for languages. - :attr str language: (optional) The language code for the language (for example, + :param str language: (optional) The language code for the language (for example, `af`). - :attr str language_name: (optional) The name of the language in English (for + :param str language_name: (optional) The name of the language in English (for example, `Afrikaans`). - :attr str native_language_name: (optional) The native name of the language (for + :param str native_language_name: (optional) The native name of the language (for example, `Afrikaans`). - :attr str country_code: (optional) The country code for the language (for + :param str country_code: (optional) The country code for the language (for example, `ZA` for South Africa). - :attr bool words_separated: (optional) Indicates whether words of the language + :param bool words_separated: (optional) Indicates whether words of the language are separated by whitespace: `true` if the words are separated; `false` otherwise. - :attr str direction: (optional) Indicates the direction of the language: + :param str direction: (optional) Indicates the direction of the language: `right_to_left` or `left_to_right`. - :attr bool supported_as_source: (optional) Indicates whether the language can be - used as the source for translation: `true` if the language can be used as the + :param bool supported_as_source: (optional) Indicates whether the language can + be used as the source for translation: `true` if the language can be used as the source; `false` otherwise. - :attr bool supported_as_target: (optional) Indicates whether the language can be - used as the target for translation: `true` if the language can be used as the + :param bool supported_as_target: (optional) Indicates whether the language can + be used as the target for translation: `true` if the language can be used as the target; `false` otherwise. - :attr bool identifiable: (optional) Indicates whether the language supports + :param bool identifiable: (optional) Indicates whether the language supports automatic detection: `true` if the language can be detected automatically; `false` otherwise. """ - def __init__(self, - *, - language: str = None, - language_name: str = None, - native_language_name: str = None, - country_code: str = None, - words_separated: bool = None, - direction: str = None, - supported_as_source: bool = None, - supported_as_target: bool = None, - identifiable: bool = None) -> None: + def __init__( + self, + *, + language: Optional[str] = None, + language_name: Optional[str] = None, + native_language_name: Optional[str] = None, + country_code: Optional[str] = None, + words_separated: Optional[bool] = None, + direction: Optional[str] = None, + supported_as_source: Optional[bool] = None, + supported_as_target: Optional[bool] = None, + identifiable: Optional[bool] = None, + ) -> None: """ Initialize a Language object. @@ -1673,24 +1788,27 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Language': """Initialize a Language object from a json dictionary.""" args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'language_name' in _dict: - args['language_name'] = _dict.get('language_name') - if 'native_language_name' in _dict: - args['native_language_name'] = _dict.get('native_language_name') - if 'country_code' in _dict: - args['country_code'] = _dict.get('country_code') - if 'words_separated' in _dict: - args['words_separated'] = _dict.get('words_separated') - if 'direction' in _dict: - args['direction'] = _dict.get('direction') - if 'supported_as_source' in _dict: - args['supported_as_source'] = _dict.get('supported_as_source') - if 'supported_as_target' in _dict: - args['supported_as_target'] = _dict.get('supported_as_target') - if 'identifiable' in _dict: - args['identifiable'] = _dict.get('identifiable') + if (language := _dict.get('language')) is not None: + args['language'] = language + if (language_name := _dict.get('language_name')) is not None: + args['language_name'] = language_name + if (native_language_name := + _dict.get('native_language_name')) is not None: + args['native_language_name'] = native_language_name + if (country_code := _dict.get('country_code')) is not None: + args['country_code'] = country_code + if (words_separated := _dict.get('words_separated')) is not None: + args['words_separated'] = words_separated + if (direction := _dict.get('direction')) is not None: + args['direction'] = direction + if (supported_as_source := + _dict.get('supported_as_source')) is not None: + args['supported_as_source'] = supported_as_source + if (supported_as_target := + _dict.get('supported_as_target')) is not None: + args['supported_as_target'] = supported_as_target + if (identifiable := _dict.get('identifiable')) is not None: + args['identifiable'] = identifiable return cls(**args) @classmethod @@ -1746,15 +1864,18 @@ def __ne__(self, other: 'Language') -> bool: return not self == other -class Languages(): +class Languages: """ The response type for listing supported languages. - :attr List[Language] languages: An array of supported languages with information - about each language. + :param List[Language] languages: An array of supported languages with + information about each language. """ - def __init__(self, languages: List['Language']) -> None: + def __init__( + self, + languages: List['Language'], + ) -> None: """ Initialize a Languages object. @@ -1767,10 +1888,8 @@ def __init__(self, languages: List['Language']) -> None: def from_dict(cls, _dict: Dict) -> 'Languages': """Initialize a Languages object from a json dictionary.""" args = {} - if 'languages' in _dict: - args['languages'] = [ - Language.from_dict(v) for v in _dict.get('languages') - ] + if (languages := _dict.get('languages')) is not None: + args['languages'] = [Language.from_dict(v) for v in languages] else: raise ValueError( 'Required property \'languages\' not present in Languages JSON') @@ -1813,14 +1932,17 @@ def __ne__(self, other: 'Languages') -> bool: return not self == other -class Translation(): +class Translation: """ Translation. - :attr str translation: Translation output in UTF-8. + :param str translation: Translation output in UTF-8. """ - def __init__(self, translation: str) -> None: + def __init__( + self, + translation: str, + ) -> None: """ Initialize a Translation object. @@ -1832,8 +1954,8 @@ def __init__(self, translation: str) -> None: def from_dict(cls, _dict: Dict) -> 'Translation': """Initialize a Translation object from a json dictionary.""" args = {} - if 'translation' in _dict: - args['translation'] = _dict.get('translation') + if (translation := _dict.get('translation')) is not None: + args['translation'] = translation else: raise ValueError( 'Required property \'translation\' not present in Translation JSON' @@ -1871,43 +1993,45 @@ def __ne__(self, other: 'Translation') -> bool: return not self == other -class TranslationModel(): +class TranslationModel: """ Response payload for models. - :attr str model_id: A globally unique string that identifies the underlying + :param str model_id: A globally unique string that identifies the underlying model that is used for translation. - :attr str name: (optional) Optional name that can be specified when the model is - created. - :attr str source: (optional) Translation source language code. - :attr str target: (optional) Translation target language code. - :attr str base_model_id: (optional) Model ID of the base model that was used to + :param str name: (optional) Optional name that can be specified when the model + is created. + :param str source: (optional) Translation source language code. + :param str target: (optional) Translation target language code. + :param str base_model_id: (optional) Model ID of the base model that was used to customize the model. If the model is not a custom model, this will be an empty string. - :attr str domain: (optional) The domain of the translation model. - :attr bool customizable: (optional) Whether this model can be used as a base for - customization. Customized models are not further customizable, and some base + :param str domain: (optional) The domain of the translation model. + :param bool customizable: (optional) Whether this model can be used as a base + for customization. Customized models are not further customizable, and some base models are not customizable. - :attr bool default_model: (optional) Whether or not the model is a default + :param bool default_model: (optional) Whether or not the model is a default model. A default model is the model for a given language pair that will be used when that language pair is specified in the source and target parameters. - :attr str owner: (optional) Either an empty string, indicating the model is not + :param str owner: (optional) Either an empty string, indicating the model is not a custom model, or the ID of the service instance that created the model. - :attr str status: (optional) Availability of a model. + :param str status: (optional) Availability of a model. """ - def __init__(self, - model_id: str, - *, - name: str = None, - source: str = None, - target: str = None, - base_model_id: str = None, - domain: str = None, - customizable: bool = None, - default_model: bool = None, - owner: str = None, - status: str = None) -> None: + def __init__( + self, + model_id: str, + *, + name: Optional[str] = None, + source: Optional[str] = None, + target: Optional[str] = None, + base_model_id: Optional[str] = None, + domain: Optional[str] = None, + customizable: Optional[bool] = None, + default_model: Optional[bool] = None, + owner: Optional[str] = None, + status: Optional[str] = None, + ) -> None: """ Initialize a TranslationModel object. @@ -1948,30 +2072,30 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TranslationModel': """Initialize a TranslationModel object from a json dictionary.""" args = {} - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id else: raise ValueError( 'Required property \'model_id\' not present in TranslationModel JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'source' in _dict: - args['source'] = _dict.get('source') - if 'target' in _dict: - args['target'] = _dict.get('target') - if 'base_model_id' in _dict: - args['base_model_id'] = _dict.get('base_model_id') - if 'domain' in _dict: - args['domain'] = _dict.get('domain') - if 'customizable' in _dict: - args['customizable'] = _dict.get('customizable') - if 'default_model' in _dict: - args['default_model'] = _dict.get('default_model') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (source := _dict.get('source')) is not None: + args['source'] = source + if (target := _dict.get('target')) is not None: + args['target'] = target + if (base_model_id := _dict.get('base_model_id')) is not None: + args['base_model_id'] = base_model_id + if (domain := _dict.get('domain')) is not None: + args['domain'] = domain + if (customizable := _dict.get('customizable')) is not None: + args['customizable'] = customizable + if (default_model := _dict.get('default_model')) is not None: + args['default_model'] = default_model + if (owner := _dict.get('owner')) is not None: + args['owner'] = owner + if (status := _dict.get('status')) is not None: + args['status'] = status return cls(**args) @classmethod @@ -2026,6 +2150,7 @@ class StatusEnum(str, Enum): """ Availability of a model. """ + UPLOADING = 'uploading' UPLOADED = 'uploaded' DISPATCHING = 'dispatching' @@ -2038,14 +2163,17 @@ class StatusEnum(str, Enum): ERROR = 'error' -class TranslationModels(): +class TranslationModels: """ The response type for listing existing translation models. - :attr List[TranslationModel] models: An array of available models. + :param List[TranslationModel] models: An array of available models. """ - def __init__(self, models: List['TranslationModel']) -> None: + def __init__( + self, + models: List['TranslationModel'], + ) -> None: """ Initialize a TranslationModels object. @@ -2057,10 +2185,8 @@ def __init__(self, models: List['TranslationModel']) -> None: def from_dict(cls, _dict: Dict) -> 'TranslationModels': """Initialize a TranslationModels object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - TranslationModel.from_dict(v) for v in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [TranslationModel.from_dict(v) for v in models] else: raise ValueError( 'Required property \'models\' not present in TranslationModels JSON' @@ -2104,29 +2230,31 @@ def __ne__(self, other: 'TranslationModels') -> bool: return not self == other -class TranslationResult(): +class TranslationResult: """ TranslationResult. - :attr int word_count: An estimate of the number of words in the input text. - :attr int character_count: Number of characters in the input text. - :attr str detected_language: (optional) The language code of the source text if + :param int word_count: An estimate of the number of words in the input text. + :param int character_count: Number of characters in the input text. + :param str detected_language: (optional) The language code of the source text if the source language was automatically detected. - :attr float detected_language_confidence: (optional) A score between 0 and 1 + :param float detected_language_confidence: (optional) A score between 0 and 1 indicating the confidence of source language detection. A higher value indicates greater confidence. This is returned only when the service automatically detects the source language. - :attr List[Translation] translations: List of translation output in UTF-8, + :param List[Translation] translations: List of translation output in UTF-8, corresponding to the input text entries. """ - def __init__(self, - word_count: int, - character_count: int, - translations: List['Translation'], - *, - detected_language: str = None, - detected_language_confidence: float = None) -> None: + def __init__( + self, + word_count: int, + character_count: int, + translations: List['Translation'], + *, + detected_language: Optional[str] = None, + detected_language_confidence: Optional[float] = None, + ) -> None: """ Initialize a TranslationResult object. @@ -2152,26 +2280,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TranslationResult': """Initialize a TranslationResult object from a json dictionary.""" args = {} - if 'word_count' in _dict: - args['word_count'] = _dict.get('word_count') + if (word_count := _dict.get('word_count')) is not None: + args['word_count'] = word_count else: raise ValueError( 'Required property \'word_count\' not present in TranslationResult JSON' ) - if 'character_count' in _dict: - args['character_count'] = _dict.get('character_count') + if (character_count := _dict.get('character_count')) is not None: + args['character_count'] = character_count else: raise ValueError( 'Required property \'character_count\' not present in TranslationResult JSON' ) - if 'detected_language' in _dict: - args['detected_language'] = _dict.get('detected_language') - if 'detected_language_confidence' in _dict: - args['detected_language_confidence'] = _dict.get( - 'detected_language_confidence') - if 'translations' in _dict: + if (detected_language := _dict.get('detected_language')) is not None: + args['detected_language'] = detected_language + if (detected_language_confidence := + _dict.get('detected_language_confidence')) is not None: + args['detected_language_confidence'] = detected_language_confidence + if (translations := _dict.get('translations')) is not None: args['translations'] = [ - Translation.from_dict(v) for v in _dict.get('translations') + Translation.from_dict(v) for v in translations ] else: raise ValueError( diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index fd80a2695..43955211d 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you @@ -40,7 +40,7 @@ from datetime import datetime from enum import Enum -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -92,19 +92,21 @@ def __init__( # Analyze ######################### - def analyze(self, - features: 'Features', - *, - text: str = None, - html: str = None, - url: str = None, - clean: bool = None, - xpath: str = None, - fallback_to_raw: bool = None, - return_analyzed_text: bool = None, - language: str = None, - limit_text_characters: int = None, - **kwargs) -> DetailedResponse: + def analyze( + self, + features: 'Features', + *, + text: Optional[str] = None, + html: Optional[str] = None, + url: Optional[str] = None, + clean: Optional[bool] = None, + xpath: Optional[str] = None, + fallback_to_raw: Optional[bool] = None, + return_analyzed_text: Optional[bool] = None, + language: Optional[str] = None, + limit_text_characters: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Analyze text. @@ -160,9 +162,11 @@ def analyze(self, raise ValueError('features must be provided') features = convert_model(features) headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='analyze') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='analyze', + ) headers.update(sdk_headers) params = { @@ -191,11 +195,13 @@ def analyze(self, headers['Accept'] = 'application/json' url = '/v1/analyze' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -204,7 +210,10 @@ def analyze(self, # Manage models ######################### - def list_models(self, **kwargs) -> DetailedResponse: + def list_models( + self, + **kwargs, + ) -> DetailedResponse: """ List models. @@ -218,9 +227,11 @@ def list_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_models', + ) headers.update(sdk_headers) params = { @@ -233,15 +244,21 @@ def list_models(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/models' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: + def delete_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete model. @@ -256,9 +273,11 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_model', + ) headers.update(sdk_headers) params = { @@ -274,10 +293,12 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -286,17 +307,19 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: # Manage categories models ######################### - def create_categories_model(self, - language: str, - training_data: BinaryIO, - training_data_content_type: str, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def create_categories_model( + self, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = 'application/json', + name: Optional[str] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create categories model. @@ -325,12 +348,12 @@ def create_categories_model(self, raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') - if not training_data_content_type: - raise ValueError('training_data_content_type must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_categories_model', + ) headers.update(sdk_headers) params = { @@ -362,16 +385,21 @@ def create_categories_model(self, headers['Accept'] = 'application/json' url = '/v1/models/categories' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def list_categories_models(self, **kwargs) -> DetailedResponse: + def list_categories_models( + self, + **kwargs, + ) -> DetailedResponse: """ List categories models. @@ -383,9 +411,11 @@ def list_categories_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_categories_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_categories_models', + ) headers.update(sdk_headers) params = { @@ -398,15 +428,21 @@ def list_categories_models(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/models/categories' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: + def get_categories_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get categories model details. @@ -421,9 +457,11 @@ def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_categories_model', + ) headers.update(sdk_headers) params = { @@ -439,26 +477,30 @@ def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/categories/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_categories_model(self, - model_id: str, - language: str, - training_data: BinaryIO, - training_data_content_type: str, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - **kwargs) -> DetailedResponse: + def update_categories_model( + self, + model_id: str, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = 'application/json', + name: Optional[str] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Update categories model. @@ -489,12 +531,12 @@ def update_categories_model(self, raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') - if not training_data_content_type: - raise ValueError('training_data_content_type must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_categories_model', + ) headers.update(sdk_headers) params = { @@ -529,17 +571,22 @@ def update_categories_model(self, path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/categories/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_categories_model(self, model_id: str, - **kwargs) -> DetailedResponse: + def delete_categories_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete categories model. @@ -555,9 +602,11 @@ def delete_categories_model(self, model_id: str, if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_categories_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_categories_model', + ) headers.update(sdk_headers) params = { @@ -573,10 +622,12 @@ def delete_categories_model(self, model_id: str, path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/categories/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -586,18 +637,20 @@ def delete_categories_model(self, model_id: str, ######################### def create_classifications_model( - self, - language: str, - training_data: BinaryIO, - training_data_content_type: str, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - training_parameters: 'ClassificationsTrainingParameters' = None, - **kwargs) -> DetailedResponse: + self, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = 'application/json', + name: Optional[str] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + training_parameters: Optional[ + 'ClassificationsTrainingParameters'] = None, + **kwargs, + ) -> DetailedResponse: """ Create classifications model. @@ -629,13 +682,12 @@ def create_classifications_model( raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') - if not training_data_content_type: - raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='create_classifications_model') + operation_id='create_classifications_model', + ) headers.update(sdk_headers) params = { @@ -671,16 +723,21 @@ def create_classifications_model( headers['Accept'] = 'application/json' url = '/v1/models/classifications' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def list_classifications_models(self, **kwargs) -> DetailedResponse: + def list_classifications_models( + self, + **kwargs, + ) -> DetailedResponse: """ List classifications models. @@ -695,7 +752,8 @@ def list_classifications_models(self, **kwargs) -> DetailedResponse: sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='list_classifications_models') + operation_id='list_classifications_models', + ) headers.update(sdk_headers) params = { @@ -708,16 +766,21 @@ def list_classifications_models(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/models/classifications' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_classifications_model(self, model_id: str, - **kwargs) -> DetailedResponse: + def get_classifications_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get classifications model details. @@ -732,9 +795,11 @@ def get_classifications_model(self, model_id: str, if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_classifications_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_classifications_model', + ) headers.update(sdk_headers) params = { @@ -750,28 +815,32 @@ def get_classifications_model(self, model_id: str, path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response def update_classifications_model( - self, - model_id: str, - language: str, - training_data: BinaryIO, - training_data_content_type: str, - *, - name: str = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - training_parameters: 'ClassificationsTrainingParameters' = None, - **kwargs) -> DetailedResponse: + self, + model_id: str, + language: str, + training_data: BinaryIO, + *, + training_data_content_type: Optional[str] = 'application/json', + name: Optional[str] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + training_parameters: Optional[ + 'ClassificationsTrainingParameters'] = None, + **kwargs, + ) -> DetailedResponse: """ Update classifications model. @@ -805,13 +874,12 @@ def update_classifications_model( raise ValueError('language must be provided') if training_data is None: raise ValueError('training_data must be provided') - if not training_data_content_type: - raise ValueError('training_data_content_type must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='update_classifications_model') + operation_id='update_classifications_model', + ) headers.update(sdk_headers) params = { @@ -850,17 +918,22 @@ def update_classifications_model( path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def delete_classifications_model(self, model_id: str, - **kwargs) -> DetailedResponse: + def delete_classifications_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete classifications model. @@ -879,7 +952,8 @@ def delete_classifications_model(self, model_id: str, sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', - operation_id='delete_classifications_model') + operation_id='delete_classifications_model', + ) headers.update(sdk_headers) params = { @@ -895,10 +969,12 @@ def delete_classifications_model(self, model_id: str, path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/classifications/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -913,6 +989,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -926,6 +1003,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -939,6 +1017,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -952,6 +1031,7 @@ class TrainingDataContentType(str, Enum): """ The content type of training_data. """ + JSON = 'json' APPLICATION_JSON = 'application/json' @@ -961,55 +1041,57 @@ class TrainingDataContentType(str, Enum): ############################################################################## -class AnalysisResults(): +class AnalysisResults: """ Results of the analysis, organized by feature. - :attr str language: (optional) Language used to analyze the text. - :attr str analyzed_text: (optional) Text that was used in the analysis. - :attr str retrieved_url: (optional) URL of the webpage that was analyzed. - :attr AnalysisResultsUsage usage: (optional) API usage information for the + :param str language: (optional) Language used to analyze the text. + :param str analyzed_text: (optional) Text that was used in the analysis. + :param str retrieved_url: (optional) URL of the webpage that was analyzed. + :param AnalysisResultsUsage usage: (optional) API usage information for the request. - :attr List[ConceptsResult] concepts: (optional) The general concepts referenced + :param List[ConceptsResult] concepts: (optional) The general concepts referenced or alluded to in the analyzed text. - :attr List[EntitiesResult] entities: (optional) The entities detected in the + :param List[EntitiesResult] entities: (optional) The entities detected in the analyzed text. - :attr List[KeywordsResult] keywords: (optional) The keywords from the analyzed + :param List[KeywordsResult] keywords: (optional) The keywords from the analyzed text. - :attr List[CategoriesResult] categories: (optional) The categories that the + :param List[CategoriesResult] categories: (optional) The categories that the service assigned to the analyzed text. - :attr List[ClassificationsResult] classifications: (optional) The + :param List[ClassificationsResult] classifications: (optional) The classifications assigned to the analyzed text. - :attr EmotionResult emotion: (optional) The anger, disgust, fear, joy, or + :param EmotionResult emotion: (optional) The anger, disgust, fear, joy, or sadness conveyed by the content. - :attr FeaturesResultsMetadata metadata: (optional) Webpage metadata, such as the - author and the title of the page. - :attr List[RelationsResult] relations: (optional) The relationships between + :param FeaturesResultsMetadata metadata: (optional) Webpage metadata, such as + the author and the title of the page. + :param List[RelationsResult] relations: (optional) The relationships between entities in the content. - :attr List[SemanticRolesResult] semantic_roles: (optional) Sentences parsed into - `subject`, `action`, and `object` form. - :attr SentimentResult sentiment: (optional) The sentiment of the content. - :attr SyntaxResult syntax: (optional) Tokens and sentences returned from syntax + :param List[SemanticRolesResult] semantic_roles: (optional) Sentences parsed + into `subject`, `action`, and `object` form. + :param SentimentResult sentiment: (optional) The sentiment of the content. + :param SyntaxResult syntax: (optional) Tokens and sentences returned from syntax analysis. """ - def __init__(self, - *, - language: str = None, - analyzed_text: str = None, - retrieved_url: str = None, - usage: 'AnalysisResultsUsage' = None, - concepts: List['ConceptsResult'] = None, - entities: List['EntitiesResult'] = None, - keywords: List['KeywordsResult'] = None, - categories: List['CategoriesResult'] = None, - classifications: List['ClassificationsResult'] = None, - emotion: 'EmotionResult' = None, - metadata: 'FeaturesResultsMetadata' = None, - relations: List['RelationsResult'] = None, - semantic_roles: List['SemanticRolesResult'] = None, - sentiment: 'SentimentResult' = None, - syntax: 'SyntaxResult' = None) -> None: + def __init__( + self, + *, + language: Optional[str] = None, + analyzed_text: Optional[str] = None, + retrieved_url: Optional[str] = None, + usage: Optional['AnalysisResultsUsage'] = None, + concepts: Optional[List['ConceptsResult']] = None, + entities: Optional[List['EntitiesResult']] = None, + keywords: Optional[List['KeywordsResult']] = None, + categories: Optional[List['CategoriesResult']] = None, + classifications: Optional[List['ClassificationsResult']] = None, + emotion: Optional['EmotionResult'] = None, + metadata: Optional['FeaturesResultsMetadata'] = None, + relations: Optional[List['RelationsResult']] = None, + semantic_roles: Optional[List['SemanticRolesResult']] = None, + sentiment: Optional['SentimentResult'] = None, + syntax: Optional['SyntaxResult'] = None, + ) -> None: """ Initialize a AnalysisResults object. @@ -1060,54 +1142,44 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalysisResults': """Initialize a AnalysisResults object from a json dictionary.""" args = {} - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'analyzed_text' in _dict: - args['analyzed_text'] = _dict.get('analyzed_text') - if 'retrieved_url' in _dict: - args['retrieved_url'] = _dict.get('retrieved_url') - if 'usage' in _dict: - args['usage'] = AnalysisResultsUsage.from_dict(_dict.get('usage')) - if 'concepts' in _dict: - args['concepts'] = [ - ConceptsResult.from_dict(v) for v in _dict.get('concepts') - ] - if 'entities' in _dict: - args['entities'] = [ - EntitiesResult.from_dict(v) for v in _dict.get('entities') - ] - if 'keywords' in _dict: - args['keywords'] = [ - KeywordsResult.from_dict(v) for v in _dict.get('keywords') - ] - if 'categories' in _dict: + if (language := _dict.get('language')) is not None: + args['language'] = language + if (analyzed_text := _dict.get('analyzed_text')) is not None: + args['analyzed_text'] = analyzed_text + if (retrieved_url := _dict.get('retrieved_url')) is not None: + args['retrieved_url'] = retrieved_url + if (usage := _dict.get('usage')) is not None: + args['usage'] = AnalysisResultsUsage.from_dict(usage) + if (concepts := _dict.get('concepts')) is not None: + args['concepts'] = [ConceptsResult.from_dict(v) for v in concepts] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [EntitiesResult.from_dict(v) for v in entities] + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = [KeywordsResult.from_dict(v) for v in keywords] + if (categories := _dict.get('categories')) is not None: args['categories'] = [ - CategoriesResult.from_dict(v) for v in _dict.get('categories') + CategoriesResult.from_dict(v) for v in categories ] - if 'classifications' in _dict: + if (classifications := _dict.get('classifications')) is not None: args['classifications'] = [ - ClassificationsResult.from_dict(v) - for v in _dict.get('classifications') + ClassificationsResult.from_dict(v) for v in classifications ] - if 'emotion' in _dict: - args['emotion'] = EmotionResult.from_dict(_dict.get('emotion')) - if 'metadata' in _dict: - args['metadata'] = FeaturesResultsMetadata.from_dict( - _dict.get('metadata')) - if 'relations' in _dict: + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionResult.from_dict(emotion) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = FeaturesResultsMetadata.from_dict(metadata) + if (relations := _dict.get('relations')) is not None: args['relations'] = [ - RelationsResult.from_dict(v) for v in _dict.get('relations') + RelationsResult.from_dict(v) for v in relations ] - if 'semantic_roles' in _dict: + if (semantic_roles := _dict.get('semantic_roles')) is not None: args['semantic_roles'] = [ - SemanticRolesResult.from_dict(v) - for v in _dict.get('semantic_roles') + SemanticRolesResult.from_dict(v) for v in semantic_roles ] - if 'sentiment' in _dict: - args['sentiment'] = SentimentResult.from_dict( - _dict.get('sentiment')) - if 'syntax' in _dict: - args['syntax'] = SyntaxResult.from_dict(_dict.get('syntax')) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = SentimentResult.from_dict(sentiment) + if (syntax := _dict.get('syntax')) is not None: + args['syntax'] = SyntaxResult.from_dict(syntax) return cls(**args) @classmethod @@ -1227,20 +1299,22 @@ def __ne__(self, other: 'AnalysisResults') -> bool: return not self == other -class AnalysisResultsUsage(): +class AnalysisResultsUsage: """ API usage information for the request. - :attr int features: (optional) Number of features used in the API call. - :attr int text_characters: (optional) Number of text characters processed. - :attr int text_units: (optional) Number of 10,000-character units processed. + :param int features: (optional) Number of features used in the API call. + :param int text_characters: (optional) Number of text characters processed. + :param int text_units: (optional) Number of 10,000-character units processed. """ - def __init__(self, - *, - features: int = None, - text_characters: int = None, - text_units: int = None) -> None: + def __init__( + self, + *, + features: Optional[int] = None, + text_characters: Optional[int] = None, + text_units: Optional[int] = None, + ) -> None: """ Initialize a AnalysisResultsUsage object. @@ -1257,12 +1331,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AnalysisResultsUsage': """Initialize a AnalysisResultsUsage object from a json dictionary.""" args = {} - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'text_characters' in _dict: - args['text_characters'] = _dict.get('text_characters') - if 'text_units' in _dict: - args['text_units'] = _dict.get('text_units') + if (features := _dict.get('features')) is not None: + args['features'] = features + if (text_characters := _dict.get('text_characters')) is not None: + args['text_characters'] = text_characters + if (text_units := _dict.get('text_units')) is not None: + args['text_units'] = text_units return cls(**args) @classmethod @@ -1301,14 +1375,18 @@ def __ne__(self, other: 'AnalysisResultsUsage') -> bool: return not self == other -class Author(): +class Author: """ The author of the analyzed content. - :attr str name: (optional) Name of the author. + :param str name: (optional) Name of the author. """ - def __init__(self, *, name: str = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + ) -> None: """ Initialize a Author object. @@ -1320,8 +1398,8 @@ def __init__(self, *, name: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Author': """Initialize a Author object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name return cls(**args) @classmethod @@ -1355,47 +1433,49 @@ def __ne__(self, other: 'Author') -> bool: return not self == other -class CategoriesModel(): +class CategoriesModel: """ Categories model. - :attr str name: (optional) An optional name for the model. - :attr dict user_metadata: (optional) An optional map of metadata key-value pairs - to store with this model. - :attr str language: The 2-letter language code of this model. - :attr str description: (optional) An optional description of the model. - :attr str model_version: (optional) An optional version string. - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. + :param str language: The 2-letter language code of this model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. - :attr str version_description: (optional) The description of the version. - :attr List[str] features: (optional) The service features that are supported by + :param str version_description: (optional) The description of the version. + :param List[str] features: (optional) The service features that are supported by the custom model. - :attr str status: When the status is `available`, the model is ready to use. - :attr str model_id: Unique model ID. - :attr datetime created: dateTime indicating when the model was created. - :attr List[Notice] notices: (optional) - :attr datetime last_trained: (optional) dateTime of last successful model + :param str status: When the status is `available`, the model is ready to use. + :param str model_id: Unique model ID. + :param datetime created: dateTime indicating when the model was created. + :param List[Notice] notices: (optional) + :param datetime last_trained: (optional) dateTime of last successful model training. - :attr datetime last_deployed: (optional) dateTime of last successful model + :param datetime last_deployed: (optional) dateTime of last successful model deployment. """ - def __init__(self, - language: str, - status: str, - model_id: str, - created: datetime, - *, - name: str = None, - user_metadata: dict = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - features: List[str] = None, - notices: List['Notice'] = None, - last_trained: datetime = None, - last_deployed: datetime = None) -> None: + def __init__( + self, + language: str, + status: str, + model_id: str, + created: datetime, + *, + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + features: Optional[List[str]] = None, + notices: Optional[List['Notice']] = None, + last_trained: Optional[datetime] = None, + last_deployed: Optional[datetime] = None, + ) -> None: """ Initialize a CategoriesModel object. @@ -1439,53 +1519,51 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesModel': """Initialize a CategoriesModel object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'user_metadata' in _dict: - args['user_metadata'] = _dict.get('user_metadata') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (user_metadata := _dict.get('user_metadata')) is not None: + args['user_metadata'] = user_metadata + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in CategoriesModel JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (model_version := _dict.get('model_version')) is not None: + args['model_version'] = model_version + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (version_description := + _dict.get('version_description')) is not None: + args['version_description'] = version_description + if (features := _dict.get('features')) is not None: + args['features'] = features + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in CategoriesModel JSON' ) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id else: raise ValueError( 'Required property \'model_id\' not present in CategoriesModel JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) else: raise ValueError( 'Required property \'created\' not present in CategoriesModel JSON' ) - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] - if 'last_trained' in _dict: - args['last_trained'] = string_to_datetime(_dict.get('last_trained')) - if 'last_deployed' in _dict: - args['last_deployed'] = string_to_datetime( - _dict.get('last_deployed')) + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (last_trained := _dict.get('last_trained')) is not None: + args['last_trained'] = string_to_datetime(last_trained) + if (last_deployed := _dict.get('last_deployed')) is not None: + args['last_deployed'] = string_to_datetime(last_deployed) return cls(**args) @classmethod @@ -1556,6 +1634,7 @@ class StatusEnum(str, Enum): """ When the status is `available`, the model is ready to use. """ + STARTING = 'starting' TRAINING = 'training' DEPLOYING = 'deploying' @@ -1564,14 +1643,18 @@ class StatusEnum(str, Enum): DELETED = 'deleted' -class CategoriesModelList(): +class CategoriesModelList: """ List of categories models. - :attr List[CategoriesModel] models: (optional) The categories models. + :param List[CategoriesModel] models: (optional) The categories models. """ - def __init__(self, *, models: List['CategoriesModel'] = None) -> None: + def __init__( + self, + *, + models: Optional[List['CategoriesModel']] = None, + ) -> None: """ Initialize a CategoriesModelList object. @@ -1583,10 +1666,8 @@ def __init__(self, *, models: List['CategoriesModel'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'CategoriesModelList': """Initialize a CategoriesModelList object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - CategoriesModel.from_dict(v) for v in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [CategoriesModel.from_dict(v) for v in models] return cls(**args) @classmethod @@ -1626,27 +1707,29 @@ def __ne__(self, other: 'CategoriesModelList') -> bool: return not self == other -class CategoriesOptions(): +class CategoriesOptions: """ Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :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) (Beta) Enter a [custom + :param bool explanation: (optional) Set this to `true` to return explanations + for each categorization. **This is available only for English categories.**. + :param int limit: (optional) Maximum number of categories to return. + :param str model: (optional) (Beta) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the standard categories model. **This is available only for English categories.**. """ - def __init__(self, - *, - explanation: bool = None, - limit: int = None, - model: str = None) -> None: + def __init__( + self, + *, + explanation: Optional[bool] = None, + limit: Optional[int] = None, + model: Optional[str] = None, + ) -> None: """ Initialize a CategoriesOptions object. @@ -1667,12 +1750,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesOptions': """Initialize a CategoriesOptions object from a json dictionary.""" args = {} - if 'explanation' in _dict: - args['explanation'] = _dict.get('explanation') - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'model' in _dict: - args['model'] = _dict.get('model') + if (explanation := _dict.get('explanation')) is not None: + args['explanation'] = explanation + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -1710,15 +1793,19 @@ def __ne__(self, other: 'CategoriesOptions') -> bool: return not self == other -class CategoriesRelevantText(): +class CategoriesRelevantText: """ Relevant text that contributed to the categorization. - :attr str text: (optional) Text from the analyzed source that supports the + :param str text: (optional) Text from the analyzed source that supports the categorization. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a CategoriesRelevantText object. @@ -1731,8 +1818,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'CategoriesRelevantText': """Initialize a CategoriesRelevantText object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -1766,24 +1853,26 @@ def __ne__(self, other: 'CategoriesRelevantText') -> bool: return not self == other -class CategoriesResult(): +class CategoriesResult: """ A categorization of the analyzed text. - :attr str label: (optional) The path to the category through the multi-level + :param str label: (optional) The path to the category through the multi-level taxonomy hierarchy. For more information about the categories, see [Categories hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). - :attr float score: (optional) Confidence score for the category classification. + :param float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. - :attr CategoriesResultExplanation explanation: (optional) Information that helps - to explain what contributed to the categories result. + :param CategoriesResultExplanation explanation: (optional) Information that + helps to explain what contributed to the categories result. """ - def __init__(self, - *, - label: str = None, - score: float = None, - explanation: 'CategoriesResultExplanation' = None) -> None: + def __init__( + self, + *, + label: Optional[str] = None, + score: Optional[float] = None, + explanation: Optional['CategoriesResultExplanation'] = None, + ) -> None: """ Initialize a CategoriesResult object. @@ -1804,13 +1893,13 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesResult': """Initialize a CategoriesResult object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'score' in _dict: - args['score'] = _dict.get('score') - if 'explanation' in _dict: + if (label := _dict.get('label')) is not None: + args['label'] = label + if (score := _dict.get('score')) is not None: + args['score'] = score + if (explanation := _dict.get('explanation')) is not None: args['explanation'] = CategoriesResultExplanation.from_dict( - _dict.get('explanation')) + explanation) return cls(**args) @classmethod @@ -1851,19 +1940,21 @@ def __ne__(self, other: 'CategoriesResult') -> bool: return not self == other -class CategoriesResultExplanation(): +class CategoriesResultExplanation: """ Information that helps to explain what contributed to the categories result. - :attr List[CategoriesRelevantText] relevant_text: (optional) An array of + :param List[CategoriesRelevantText] relevant_text: (optional) An array of relevant text from the source that contributed to the categorization. The sorted array begins with the phrase that contributed most significantly to the result, followed by phrases that were less and less impactful. """ - def __init__(self, - *, - relevant_text: List['CategoriesRelevantText'] = None) -> None: + def __init__( + self, + *, + relevant_text: Optional[List['CategoriesRelevantText']] = None, + ) -> None: """ Initialize a CategoriesResultExplanation object. @@ -1878,10 +1969,9 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CategoriesResultExplanation': """Initialize a CategoriesResultExplanation object from a json dictionary.""" args = {} - if 'relevant_text' in _dict: + if (relevant_text := _dict.get('relevant_text')) is not None: args['relevant_text'] = [ - CategoriesRelevantText.from_dict(v) - for v in _dict.get('relevant_text') + CategoriesRelevantText.from_dict(v) for v in relevant_text ] return cls(**args) @@ -1922,47 +2012,49 @@ def __ne__(self, other: 'CategoriesResultExplanation') -> bool: return not self == other -class ClassificationsModel(): +class ClassificationsModel: """ Classifications model. - :attr str name: (optional) An optional name for the model. - :attr dict user_metadata: (optional) An optional map of metadata key-value pairs - to store with this model. - :attr str language: The 2-letter language code of this model. - :attr str description: (optional) An optional description of the model. - :attr str model_version: (optional) An optional version string. - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. + :param str language: The 2-letter language code of this model. + :param str description: (optional) An optional description of the model. + :param str model_version: (optional) An optional version string. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. - :attr str version_description: (optional) The description of the version. - :attr List[str] features: (optional) The service features that are supported by + :param str version_description: (optional) The description of the version. + :param List[str] features: (optional) The service features that are supported by the custom model. - :attr str status: When the status is `available`, the model is ready to use. - :attr str model_id: Unique model ID. - :attr datetime created: dateTime indicating when the model was created. - :attr List[Notice] notices: (optional) - :attr datetime last_trained: (optional) dateTime of last successful model + :param str status: When the status is `available`, the model is ready to use. + :param str model_id: Unique model ID. + :param datetime created: dateTime indicating when the model was created. + :param List[Notice] notices: (optional) + :param datetime last_trained: (optional) dateTime of last successful model training. - :attr datetime last_deployed: (optional) dateTime of last successful model + :param datetime last_deployed: (optional) dateTime of last successful model deployment. """ - def __init__(self, - language: str, - status: str, - model_id: str, - created: datetime, - *, - name: str = None, - user_metadata: dict = None, - description: str = None, - model_version: str = None, - workspace_id: str = None, - version_description: str = None, - features: List[str] = None, - notices: List['Notice'] = None, - last_trained: datetime = None, - last_deployed: datetime = None) -> None: + def __init__( + self, + language: str, + status: str, + model_id: str, + created: datetime, + *, + name: Optional[str] = None, + user_metadata: Optional[dict] = None, + description: Optional[str] = None, + model_version: Optional[str] = None, + workspace_id: Optional[str] = None, + version_description: Optional[str] = None, + features: Optional[List[str]] = None, + notices: Optional[List['Notice']] = None, + last_trained: Optional[datetime] = None, + last_deployed: Optional[datetime] = None, + ) -> None: """ Initialize a ClassificationsModel object. @@ -2006,53 +2098,51 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassificationsModel': """Initialize a ClassificationsModel object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'user_metadata' in _dict: - args['user_metadata'] = _dict.get('user_metadata') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (user_metadata := _dict.get('user_metadata')) is not None: + args['user_metadata'] = user_metadata + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in ClassificationsModel JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - if 'features' in _dict: - args['features'] = _dict.get('features') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (description := _dict.get('description')) is not None: + args['description'] = description + if (model_version := _dict.get('model_version')) is not None: + args['model_version'] = model_version + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (version_description := + _dict.get('version_description')) is not None: + args['version_description'] = version_description + if (features := _dict.get('features')) is not None: + args['features'] = features + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in ClassificationsModel JSON' ) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id else: raise ValueError( 'Required property \'model_id\' not present in ClassificationsModel JSON' ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) else: raise ValueError( 'Required property \'created\' not present in ClassificationsModel JSON' ) - if 'notices' in _dict: - args['notices'] = [ - Notice.from_dict(v) for v in _dict.get('notices') - ] - if 'last_trained' in _dict: - args['last_trained'] = string_to_datetime(_dict.get('last_trained')) - if 'last_deployed' in _dict: - args['last_deployed'] = string_to_datetime( - _dict.get('last_deployed')) + if (notices := _dict.get('notices')) is not None: + args['notices'] = [Notice.from_dict(v) for v in notices] + if (last_trained := _dict.get('last_trained')) is not None: + args['last_trained'] = string_to_datetime(last_trained) + if (last_deployed := _dict.get('last_deployed')) is not None: + args['last_deployed'] = string_to_datetime(last_deployed) return cls(**args) @classmethod @@ -2123,6 +2213,7 @@ class StatusEnum(str, Enum): """ When the status is `available`, the model is ready to use. """ + STARTING = 'starting' TRAINING = 'training' DEPLOYING = 'deploying' @@ -2131,14 +2222,18 @@ class StatusEnum(str, Enum): DELETED = 'deleted' -class ClassificationsModelList(): +class ClassificationsModelList: """ List of classifications models. - :attr List[ClassificationsModel] models: (optional) The classifications models. + :param List[ClassificationsModel] models: (optional) The classifications models. """ - def __init__(self, *, models: List['ClassificationsModel'] = None) -> None: + def __init__( + self, + *, + models: Optional[List['ClassificationsModel']] = None, + ) -> None: """ Initialize a ClassificationsModelList object. @@ -2151,10 +2246,8 @@ def __init__(self, *, models: List['ClassificationsModel'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ClassificationsModelList': """Initialize a ClassificationsModelList object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - ClassificationsModel.from_dict(v) for v in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [ClassificationsModel.from_dict(v) for v in models] return cls(**args) @classmethod @@ -2194,11 +2287,11 @@ def __ne__(self, other: 'ClassificationsModelList') -> bool: return not self == other -class ClassificationsOptions(): +class ClassificationsOptions: """ Returns text classifications for the content. - :attr str model: (optional) Enter a [custom + :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID of the classifications model to be used. You can analyze tone by using a language-specific model ID. See [Tone analytics @@ -2206,7 +2299,11 @@ class ClassificationsOptions(): for more information. """ - def __init__(self, *, model: str = None) -> None: + def __init__( + self, + *, + model: Optional[str] = None, + ) -> None: """ Initialize a ClassificationsOptions object. @@ -2224,8 +2321,8 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ClassificationsOptions': """Initialize a ClassificationsOptions object from a json dictionary.""" args = {} - if 'model' in _dict: - args['model'] = _dict.get('model') + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -2259,19 +2356,21 @@ def __ne__(self, other: 'ClassificationsOptions') -> bool: return not self == other -class ClassificationsResult(): +class ClassificationsResult: """ A classification of the analyzed text. - :attr str class_name: (optional) Classification assigned to the text. - :attr float confidence: (optional) Confidence score for the classification. + :param str class_name: (optional) Classification assigned to the text. + :param float confidence: (optional) Confidence score for the classification. Higher values indicate greater confidence. """ - def __init__(self, - *, - class_name: str = None, - confidence: float = None) -> None: + def __init__( + self, + *, + class_name: Optional[str] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a ClassificationsResult object. @@ -2286,10 +2385,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ClassificationsResult': """Initialize a ClassificationsResult object from a json dictionary.""" args = {} - if 'class_name' in _dict: - args['class_name'] = _dict.get('class_name') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (class_name := _dict.get('class_name')) is not None: + args['class_name'] = class_name + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -2325,15 +2424,19 @@ def __ne__(self, other: 'ClassificationsResult') -> bool: return not self == other -class ClassificationsTrainingParameters(): +class ClassificationsTrainingParameters: """ Optional classifications training parameters along with model train requests. - :attr str model_type: (optional) Model type selector to train either a + :param str model_type: (optional) Model type selector to train either a single_label or a multi_label classifier. """ - def __init__(self, *, model_type: str = None) -> None: + def __init__( + self, + *, + model_type: Optional[str] = None, + ) -> None: """ Initialize a ClassificationsTrainingParameters object. @@ -2346,8 +2449,8 @@ def __init__(self, *, model_type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'ClassificationsTrainingParameters': """Initialize a ClassificationsTrainingParameters object from a json dictionary.""" args = {} - if 'model_type' in _dict: - args['model_type'] = _dict.get('model_type') + if (model_type := _dict.get('model_type')) is not None: + args['model_type'] = model_type return cls(**args) @classmethod @@ -2384,11 +2487,12 @@ class ModelTypeEnum(str, Enum): """ Model type selector to train either a single_label or a multi_label classifier. """ + SINGLE_LABEL = 'single_label' MULTI_LABEL = 'multi_label' -class ConceptsOptions(): +class ConceptsOptions: """ Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not @@ -2396,10 +2500,14 @@ class ConceptsOptions(): Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr int limit: (optional) Maximum number of concepts to return. + :param int limit: (optional) Maximum number of concepts to return. """ - def __init__(self, *, limit: int = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a ConceptsOptions object. @@ -2411,8 +2519,8 @@ def __init__(self, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'ConceptsOptions': """Initialize a ConceptsOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -2446,22 +2554,24 @@ def __ne__(self, other: 'ConceptsOptions') -> bool: return not self == other -class ConceptsResult(): +class ConceptsResult: """ The general concepts referenced or alluded to in the analyzed text. - :attr str text: (optional) Name of the concept. - :attr float relevance: (optional) Relevance score between 0 and 1. Higher scores - indicate greater relevance. - :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia + :param str text: (optional) Name of the concept. + :param float relevance: (optional) Relevance score between 0 and 1. Higher + scores indicate greater relevance. + :param str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. """ - def __init__(self, - *, - text: str = None, - relevance: float = None, - dbpedia_resource: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + relevance: Optional[float] = None, + dbpedia_resource: Optional[str] = None, + ) -> None: """ Initialize a ConceptsResult object. @@ -2479,12 +2589,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ConceptsResult': """Initialize a ConceptsResult object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') - if 'dbpedia_resource' in _dict: - args['dbpedia_resource'] = _dict.get('dbpedia_resource') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance + if (dbpedia_resource := _dict.get('dbpedia_resource')) is not None: + args['dbpedia_resource'] = dbpedia_resource return cls(**args) @classmethod @@ -2523,14 +2633,18 @@ def __ne__(self, other: 'ConceptsResult') -> bool: return not self == other -class DeleteModelResults(): +class DeleteModelResults: """ Delete model results. - :attr str deleted: (optional) model_id of the deleted model. + :param str deleted: (optional) model_id of the deleted model. """ - def __init__(self, *, deleted: str = None) -> None: + def __init__( + self, + *, + deleted: Optional[str] = None, + ) -> None: """ Initialize a DeleteModelResults object. @@ -2542,8 +2656,8 @@ def __init__(self, *, deleted: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'DeleteModelResults': """Initialize a DeleteModelResults object from a json dictionary.""" args = {} - if 'deleted' in _dict: - args['deleted'] = _dict.get('deleted') + if (deleted := _dict.get('deleted')) is not None: + args['deleted'] = deleted return cls(**args) @classmethod @@ -2577,21 +2691,23 @@ def __ne__(self, other: 'DeleteModelResults') -> bool: return not self == other -class DisambiguationResult(): +class DisambiguationResult: """ Disambiguation information for the entity. - :attr str name: (optional) Common entity name. - :attr str dbpedia_resource: (optional) Link to the corresponding DBpedia + :param str name: (optional) Common entity name. + :param str dbpedia_resource: (optional) Link to the corresponding DBpedia resource. - :attr List[str] subtype: (optional) Entity subtype information. + :param List[str] subtype: (optional) Entity subtype information. """ - def __init__(self, - *, - name: str = None, - dbpedia_resource: str = None, - subtype: List[str] = None) -> None: + def __init__( + self, + *, + name: Optional[str] = None, + dbpedia_resource: Optional[str] = None, + subtype: Optional[List[str]] = None, + ) -> None: """ Initialize a DisambiguationResult object. @@ -2608,12 +2724,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'DisambiguationResult': """Initialize a DisambiguationResult object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'dbpedia_resource' in _dict: - args['dbpedia_resource'] = _dict.get('dbpedia_resource') - if 'subtype' in _dict: - args['subtype'] = _dict.get('subtype') + if (name := _dict.get('name')) is not None: + args['name'] = name + if (dbpedia_resource := _dict.get('dbpedia_resource')) is not None: + args['dbpedia_resource'] = dbpedia_resource + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype return cls(**args) @classmethod @@ -2652,15 +2768,19 @@ def __ne__(self, other: 'DisambiguationResult') -> bool: return not self == other -class DocumentEmotionResults(): +class DocumentEmotionResults: """ Emotion results for the document as a whole. - :attr EmotionScores emotion: (optional) Emotion results for the document as a + :param EmotionScores emotion: (optional) Emotion results for the document as a whole. """ - def __init__(self, *, emotion: 'EmotionScores' = None) -> None: + def __init__( + self, + *, + emotion: Optional['EmotionScores'] = None, + ) -> None: """ Initialize a DocumentEmotionResults object. @@ -2673,8 +2793,8 @@ def __init__(self, *, emotion: 'EmotionScores' = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentEmotionResults': """Initialize a DocumentEmotionResults object from a json dictionary.""" args = {} - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) return cls(**args) @classmethod @@ -2711,17 +2831,22 @@ def __ne__(self, other: 'DocumentEmotionResults') -> bool: return not self == other -class DocumentSentimentResults(): +class DocumentSentimentResults: """ DocumentSentimentResults. - :attr str label: (optional) Indicates whether the sentiment is positive, + :param str label: (optional) Indicates whether the sentiment is positive, neutral, or negative. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 + :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ - def __init__(self, *, label: str = None, score: float = None) -> None: + def __init__( + self, + *, + label: Optional[str] = None, + score: Optional[float] = None, + ) -> None: """ Initialize a DocumentSentimentResults object. @@ -2737,10 +2862,10 @@ def __init__(self, *, label: str = None, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'DocumentSentimentResults': """Initialize a DocumentSentimentResults object from a json dictionary.""" args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'score' in _dict: - args['score'] = _dict.get('score') + if (label := _dict.get('label')) is not None: + args['label'] = label + if (score := _dict.get('score')) is not None: + args['score'] = score return cls(**args) @classmethod @@ -2776,7 +2901,7 @@ def __ne__(self, other: 'DocumentSentimentResults') -> bool: return not self == other -class EmotionOptions(): +class EmotionOptions: """ Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze @@ -2784,16 +2909,18 @@ class EmotionOptions(): `keywords.emotion`. Supported languages: English. - :attr bool document: (optional) Set this to `false` to hide document-level + :param bool document: (optional) Set this to `false` to hide document-level emotion results. - :attr List[str] targets: (optional) Emotion results will be returned for each + :param List[str] targets: (optional) Emotion results will be returned for each target string that is found in the document. """ - def __init__(self, - *, - document: bool = None, - targets: List[str] = None) -> None: + def __init__( + self, + *, + document: Optional[bool] = None, + targets: Optional[List[str]] = None, + ) -> None: """ Initialize a EmotionOptions object. @@ -2809,10 +2936,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionOptions': """Initialize a EmotionOptions object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') + if (document := _dict.get('document')) is not None: + args['document'] = document + if (targets := _dict.get('targets')) is not None: + args['targets'] = targets return cls(**args) @classmethod @@ -2848,22 +2975,24 @@ def __ne__(self, other: 'EmotionOptions') -> bool: return not self == other -class EmotionResult(): +class EmotionResult: """ The detected anger, disgust, fear, joy, or sadness that is conveyed by the content. Emotion information can be returned for detected entities, keywords, or user-specified target phrases found in the text. - :attr DocumentEmotionResults document: (optional) Emotion results for the + :param DocumentEmotionResults document: (optional) Emotion results for the document as a whole. - :attr List[TargetedEmotionResults] targets: (optional) Emotion results for + :param List[TargetedEmotionResults] targets: (optional) Emotion results for specified targets. """ - def __init__(self, - *, - document: 'DocumentEmotionResults' = None, - targets: List['TargetedEmotionResults'] = None) -> None: + def __init__( + self, + *, + document: Optional['DocumentEmotionResults'] = None, + targets: Optional[List['TargetedEmotionResults']] = None, + ) -> None: """ Initialize a EmotionResult object. @@ -2879,13 +3008,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionResult': """Initialize a EmotionResult object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = DocumentEmotionResults.from_dict( - _dict.get('document')) - if 'targets' in _dict: + if (document := _dict.get('document')) is not None: + args['document'] = DocumentEmotionResults.from_dict(document) + if (targets := _dict.get('targets')) is not None: args['targets'] = [ - TargetedEmotionResults.from_dict(v) - for v in _dict.get('targets') + TargetedEmotionResults.from_dict(v) for v in targets ] return cls(**args) @@ -2931,29 +3058,31 @@ def __ne__(self, other: 'EmotionResult') -> bool: return not self == other -class EmotionScores(): +class EmotionScores: """ EmotionScores. - :attr float anger: (optional) Anger score from 0 to 1. A higher score means that - the text is more likely to convey anger. - :attr float disgust: (optional) Disgust score from 0 to 1. A higher score means + :param float anger: (optional) Anger score from 0 to 1. A higher score means + that the text is more likely to convey anger. + :param float disgust: (optional) Disgust score from 0 to 1. A higher score means that the text is more likely to convey disgust. - :attr float fear: (optional) Fear score from 0 to 1. A higher score means that + :param float fear: (optional) Fear score from 0 to 1. A higher score means that the text is more likely to convey fear. - :attr float joy: (optional) Joy score from 0 to 1. A higher score means that the - text is more likely to convey joy. - :attr float sadness: (optional) Sadness score from 0 to 1. A higher score means + :param float joy: (optional) Joy score from 0 to 1. A higher score means that + the text is more likely to convey joy. + :param float sadness: (optional) Sadness score from 0 to 1. A higher score means that the text is more likely to convey sadness. """ - def __init__(self, - *, - anger: float = None, - disgust: float = None, - fear: float = None, - joy: float = None, - sadness: float = None) -> None: + def __init__( + self, + *, + anger: Optional[float] = None, + disgust: Optional[float] = None, + fear: Optional[float] = None, + joy: Optional[float] = None, + sadness: Optional[float] = None, + ) -> None: """ Initialize a EmotionScores object. @@ -2978,16 +3107,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EmotionScores': """Initialize a EmotionScores object from a json dictionary.""" args = {} - if 'anger' in _dict: - args['anger'] = _dict.get('anger') - if 'disgust' in _dict: - args['disgust'] = _dict.get('disgust') - if 'fear' in _dict: - args['fear'] = _dict.get('fear') - if 'joy' in _dict: - args['joy'] = _dict.get('joy') - if 'sadness' in _dict: - args['sadness'] = _dict.get('sadness') + if (anger := _dict.get('anger')) is not None: + args['anger'] = anger + if (disgust := _dict.get('disgust')) is not None: + args['disgust'] = disgust + if (fear := _dict.get('fear')) is not None: + args['fear'] = fear + if (joy := _dict.get('joy')) is not None: + args['joy'] = joy + if (sadness := _dict.get('sadness')) is not None: + args['sadness'] = sadness return cls(**args) @classmethod @@ -3029,7 +3158,7 @@ def __ne__(self, other: 'EmotionScores') -> bool: return not self == other -class EntitiesOptions(): +class EntitiesOptions: """ Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and @@ -3038,25 +3167,27 @@ class EntitiesOptions(): Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. - :attr int limit: (optional) Maximum number of entities to return. - :attr bool mentions: (optional) Set this to `true` to return locations of entity - mentions. - :attr str model: (optional) Enter a [custom + :param int limit: (optional) Maximum number of entities to return. + :param bool mentions: (optional) Set this to `true` to return locations of + entity mentions. + :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the standard entity detection model. - :attr bool sentiment: (optional) Set this to `true` to return sentiment + :param bool sentiment: (optional) Set this to `true` to return sentiment information for detected entities. - :attr bool emotion: (optional) Set this to `true` to analyze emotion for + :param bool emotion: (optional) Set this to `true` to analyze emotion for detected keywords. """ - def __init__(self, - *, - limit: int = None, - mentions: bool = None, - model: str = None, - sentiment: bool = None, - emotion: bool = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + mentions: Optional[bool] = None, + model: Optional[str] = None, + sentiment: Optional[bool] = None, + emotion: Optional[bool] = None, + ) -> None: """ Initialize a EntitiesOptions object. @@ -3081,16 +3212,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntitiesOptions': """Initialize a EntitiesOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'mentions' in _dict: - args['mentions'] = _dict.get('mentions') - if 'model' in _dict: - args['model'] = _dict.get('model') - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (mentions := _dict.get('mentions')) is not None: + args['mentions'] = mentions + if (model := _dict.get('model')) is not None: + args['model'] = model + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = sentiment + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = emotion return cls(**args) @classmethod @@ -3132,40 +3263,43 @@ def __ne__(self, other: 'EntitiesOptions') -> bool: return not self == other -class EntitiesResult(): +class EntitiesResult: """ The important people, places, geopolitical entities and other types of entities in your content. - :attr str type: (optional) Entity type. - :attr str text: (optional) The name of the entity. - :attr float relevance: (optional) Relevance score from 0 to 1. Higher values + :param str type: (optional) Entity type. + :param str text: (optional) The name of the entity. + :param float relevance: (optional) Relevance score from 0 to 1. Higher values indicate greater relevance. - :attr float confidence: (optional) Confidence in the entity identification from + :param float confidence: (optional) Confidence in the entity identification from 0 to 1. Higher values indicate higher confidence. In standard entities requests, confidence is returned only for English text. All entities requests that use custom models return the confidence score. - :attr List[EntityMention] mentions: (optional) Entity mentions and locations. - :attr int count: (optional) How many times the entity was mentioned in the text. - :attr EmotionScores emotion: (optional) Emotion analysis results for the entity, - enabled with the `emotion` option. - :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results + :param List[EntityMention] mentions: (optional) Entity mentions and locations. + :param int count: (optional) How many times the entity was mentioned in the + text. + :param EmotionScores emotion: (optional) Emotion analysis results for the + entity, enabled with the `emotion` option. + :param FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the entity, enabled with the `sentiment` option. - :attr DisambiguationResult disambiguation: (optional) Disambiguation information - for the entity. + :param DisambiguationResult disambiguation: (optional) Disambiguation + information for the entity. """ - def __init__(self, - *, - type: str = None, - text: str = None, - relevance: float = None, - confidence: float = None, - mentions: List['EntityMention'] = None, - count: int = None, - emotion: 'EmotionScores' = None, - sentiment: 'FeatureSentimentResults' = None, - disambiguation: 'DisambiguationResult' = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + text: Optional[str] = None, + relevance: Optional[float] = None, + confidence: Optional[float] = None, + mentions: Optional[List['EntityMention']] = None, + count: Optional[int] = None, + emotion: Optional['EmotionScores'] = None, + sentiment: Optional['FeatureSentimentResults'] = None, + disambiguation: Optional['DisambiguationResult'] = None, + ) -> None: """ Initialize a EntitiesResult object. @@ -3202,28 +3336,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntitiesResult': """Initialize a EntitiesResult object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'mentions' in _dict: - args['mentions'] = [ - EntityMention.from_dict(v) for v in _dict.get('mentions') - ] - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) - if 'sentiment' in _dict: - args['sentiment'] = FeatureSentimentResults.from_dict( - _dict.get('sentiment')) - if 'disambiguation' in _dict: + if (type := _dict.get('type')) is not None: + args['type'] = type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (mentions := _dict.get('mentions')) is not None: + args['mentions'] = [EntityMention.from_dict(v) for v in mentions] + if (count := _dict.get('count')) is not None: + args['count'] = count + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = FeatureSentimentResults.from_dict(sentiment) + if (disambiguation := _dict.get('disambiguation')) is not None: args['disambiguation'] = DisambiguationResult.from_dict( - _dict.get('disambiguation')) + disambiguation) return cls(**args) @classmethod @@ -3288,24 +3419,26 @@ def __ne__(self, other: 'EntitiesResult') -> bool: return not self == other -class EntityMention(): +class EntityMention: """ EntityMention. - :attr str text: (optional) Entity mention text. - :attr List[int] location: (optional) Character offsets indicating the beginning + :param str text: (optional) Entity mention text. + :param List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. - :attr float confidence: (optional) Confidence in the entity identification from + :param float confidence: (optional) Confidence in the entity identification from 0 to 1. Higher values indicate higher confidence. In standard entities requests, confidence is returned only for English text. All entities requests that use custom models return the confidence score. """ - def __init__(self, - *, - text: str = None, - location: List[int] = None, - confidence: float = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + ) -> None: """ Initialize a EntityMention object. @@ -3325,12 +3458,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'EntityMention': """Initialize a EntityMention object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = location + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod @@ -3368,15 +3501,19 @@ def __ne__(self, other: 'EntityMention') -> bool: return not self == other -class FeatureSentimentResults(): +class FeatureSentimentResults: """ FeatureSentimentResults. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 + :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ - def __init__(self, *, score: float = None) -> None: + def __init__( + self, + *, + score: Optional[float] = None, + ) -> None: """ Initialize a FeatureSentimentResults object. @@ -3389,8 +3526,8 @@ def __init__(self, *, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'FeatureSentimentResults': """Initialize a FeatureSentimentResults object from a json dictionary.""" args = {} - if 'score' in _dict: - args['score'] = _dict.get('score') + if (score := _dict.get('score')) is not None: + args['score'] = score return cls(**args) @classmethod @@ -3424,37 +3561,37 @@ def __ne__(self, other: 'FeatureSentimentResults') -> bool: return not self == other -class Features(): +class Features: """ Analysis features and options. - :attr ClassificationsOptions classifications: (optional) Returns text + :param ClassificationsOptions classifications: (optional) Returns text classifications for the content. - :attr ConceptsOptions concepts: (optional) Returns high-level concepts in the + :param ConceptsOptions concepts: (optional) Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr EmotionOptions emotion: (optional) Detects anger, disgust, fear, joy, or + :param EmotionOptions emotion: (optional) Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze emotion for detected entities with `entities.emotion` and for keywords with `keywords.emotion`. Supported languages: English. - :attr EntitiesOptions entities: (optional) Identifies people, cities, + :param EntitiesOptions entities: (optional) Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. - :attr KeywordsOptions keywords: (optional) Returns important keywords in the + :param KeywordsOptions keywords: (optional) Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :attr dict metadata: (optional) Returns information from the document, including - author name, title, RSS/ATOM feeds, prominent page image, and publication date. - Supports URL and HTML input types only. - :attr RelationsOptions relations: (optional) Recognizes when two entities are + :param dict metadata: (optional) Returns information from the document, + including author name, title, RSS/ATOM feeds, prominent page image, and + publication date. Supports URL and HTML input types only. + :param RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". For more information, see [Relation @@ -3462,41 +3599,43 @@ class Features(): Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. - :attr SemanticRolesOptions semantic_roles: (optional) Parses sentences into + :param SemanticRolesOptions semantic_roles: (optional) Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. - :attr SentimentOptions sentiment: (optional) Analyzes the general sentiment of + :param SentimentOptions sentiment: (optional) Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :attr SummarizationOptions summarization: (optional) (Experimental) Returns a + :param SummarizationOptions summarization: (optional) (Experimental) Returns a summary of content. Supported languages: English only. Supported regions: Dallas region only. - :attr CategoriesOptions categories: (optional) Returns a hierarchical taxonomy + :param CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - :attr SyntaxOptions syntax: (optional) Returns tokens and sentences from the + :param SyntaxOptions syntax: (optional) Returns tokens and sentences from the input text. """ - def __init__(self, - *, - classifications: 'ClassificationsOptions' = None, - concepts: 'ConceptsOptions' = None, - emotion: 'EmotionOptions' = None, - entities: 'EntitiesOptions' = None, - keywords: 'KeywordsOptions' = None, - metadata: dict = None, - relations: 'RelationsOptions' = None, - semantic_roles: 'SemanticRolesOptions' = None, - sentiment: 'SentimentOptions' = None, - summarization: 'SummarizationOptions' = None, - categories: 'CategoriesOptions' = None, - syntax: 'SyntaxOptions' = None) -> None: + def __init__( + self, + *, + classifications: Optional['ClassificationsOptions'] = None, + concepts: Optional['ConceptsOptions'] = None, + emotion: Optional['EmotionOptions'] = None, + entities: Optional['EntitiesOptions'] = None, + keywords: Optional['KeywordsOptions'] = None, + metadata: Optional[dict] = None, + relations: Optional['RelationsOptions'] = None, + semantic_roles: Optional['SemanticRolesOptions'] = None, + sentiment: Optional['SentimentOptions'] = None, + summarization: Optional['SummarizationOptions'] = None, + categories: Optional['CategoriesOptions'] = None, + syntax: Optional['SyntaxOptions'] = None, + ) -> None: """ Initialize a Features object. @@ -3572,36 +3711,33 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Features': """Initialize a Features object from a json dictionary.""" args = {} - if 'classifications' in _dict: + if (classifications := _dict.get('classifications')) is not None: args['classifications'] = ClassificationsOptions.from_dict( - _dict.get('classifications')) - if 'concepts' in _dict: - args['concepts'] = ConceptsOptions.from_dict(_dict.get('concepts')) - if 'emotion' in _dict: - args['emotion'] = EmotionOptions.from_dict(_dict.get('emotion')) - if 'entities' in _dict: - args['entities'] = EntitiesOptions.from_dict(_dict.get('entities')) - if 'keywords' in _dict: - args['keywords'] = KeywordsOptions.from_dict(_dict.get('keywords')) - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') - if 'relations' in _dict: - args['relations'] = RelationsOptions.from_dict( - _dict.get('relations')) - if 'semantic_roles' in _dict: + classifications) + if (concepts := _dict.get('concepts')) is not None: + args['concepts'] = ConceptsOptions.from_dict(concepts) + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionOptions.from_dict(emotion) + if (entities := _dict.get('entities')) is not None: + args['entities'] = EntitiesOptions.from_dict(entities) + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = KeywordsOptions.from_dict(keywords) + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (relations := _dict.get('relations')) is not None: + args['relations'] = RelationsOptions.from_dict(relations) + if (semantic_roles := _dict.get('semantic_roles')) is not None: args['semantic_roles'] = SemanticRolesOptions.from_dict( - _dict.get('semantic_roles')) - if 'sentiment' in _dict: - args['sentiment'] = SentimentOptions.from_dict( - _dict.get('sentiment')) - if 'summarization' in _dict: + semantic_roles) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = SentimentOptions.from_dict(sentiment) + if (summarization := _dict.get('summarization')) is not None: args['summarization'] = SummarizationOptions.from_dict( - _dict.get('summarization')) - if 'categories' in _dict: - args['categories'] = CategoriesOptions.from_dict( - _dict.get('categories')) - if 'syntax' in _dict: - args['syntax'] = SyntaxOptions.from_dict(_dict.get('syntax')) + summarization) + if (categories := _dict.get('categories')) is not None: + args['categories'] = CategoriesOptions.from_dict(categories) + if (syntax := _dict.get('syntax')) is not None: + args['syntax'] = SyntaxOptions.from_dict(syntax) return cls(**args) @classmethod @@ -3691,25 +3827,27 @@ def __ne__(self, other: 'Features') -> bool: return not self == other -class FeaturesResultsMetadata(): +class FeaturesResultsMetadata: """ Webpage metadata, such as the author and the title of the page. - :attr List[Author] authors: (optional) The authors of the document. - :attr str publication_date: (optional) The publication date in the format ISO + :param List[Author] authors: (optional) The authors of the document. + :param str publication_date: (optional) The publication date in the format ISO 8601. - :attr str title: (optional) The title of the document. - :attr str image: (optional) URL of a prominent image on the webpage. - :attr List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. + :param str title: (optional) The title of the document. + :param str image: (optional) URL of a prominent image on the webpage. + :param List[Feed] feeds: (optional) RSS/ATOM feeds found on the webpage. """ - def __init__(self, - *, - authors: List['Author'] = None, - publication_date: str = None, - title: str = None, - image: str = None, - feeds: List['Feed'] = None) -> None: + def __init__( + self, + *, + authors: Optional[List['Author']] = None, + publication_date: Optional[str] = None, + title: Optional[str] = None, + image: Optional[str] = None, + feeds: Optional[List['Feed']] = None, + ) -> None: """ Initialize a FeaturesResultsMetadata object. @@ -3730,18 +3868,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'FeaturesResultsMetadata': """Initialize a FeaturesResultsMetadata object from a json dictionary.""" args = {} - if 'authors' in _dict: - args['authors'] = [ - Author.from_dict(v) for v in _dict.get('authors') - ] - if 'publication_date' in _dict: - args['publication_date'] = _dict.get('publication_date') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'image' in _dict: - args['image'] = _dict.get('image') - if 'feeds' in _dict: - args['feeds'] = [Feed.from_dict(v) for v in _dict.get('feeds')] + if (authors := _dict.get('authors')) is not None: + args['authors'] = [Author.from_dict(v) for v in authors] + if (publication_date := _dict.get('publication_date')) is not None: + args['publication_date'] = publication_date + if (title := _dict.get('title')) is not None: + args['title'] = title + if (image := _dict.get('image')) is not None: + args['image'] = image + if (feeds := _dict.get('feeds')) is not None: + args['feeds'] = [Feed.from_dict(v) for v in feeds] return cls(**args) @classmethod @@ -3796,14 +3932,18 @@ def __ne__(self, other: 'FeaturesResultsMetadata') -> bool: return not self == other -class Feed(): +class Feed: """ RSS or ATOM feed found on the webpage. - :attr str link: (optional) URL of the RSS or ATOM feed. + :param str link: (optional) URL of the RSS or ATOM feed. """ - def __init__(self, *, link: str = None) -> None: + def __init__( + self, + *, + link: Optional[str] = None, + ) -> None: """ Initialize a Feed object. @@ -3815,8 +3955,8 @@ def __init__(self, *, link: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Feed': """Initialize a Feed object from a json dictionary.""" args = {} - if 'link' in _dict: - args['link'] = _dict.get('link') + if (link := _dict.get('link')) is not None: + args['link'] = link return cls(**args) @classmethod @@ -3850,24 +3990,26 @@ def __ne__(self, other: 'Feed') -> bool: return not self == other -class KeywordsOptions(): +class KeywordsOptions: """ Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :attr int limit: (optional) Maximum number of keywords to return. - :attr bool sentiment: (optional) Set this to `true` to return sentiment + :param int limit: (optional) Maximum number of keywords to return. + :param bool sentiment: (optional) Set this to `true` to return sentiment information for detected keywords. - :attr bool emotion: (optional) Set this to `true` to analyze emotion for + :param bool emotion: (optional) Set this to `true` to analyze emotion for detected keywords. """ - def __init__(self, - *, - limit: int = None, - sentiment: bool = None, - emotion: bool = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + sentiment: Optional[bool] = None, + emotion: Optional[bool] = None, + ) -> None: """ Initialize a KeywordsOptions object. @@ -3885,12 +4027,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'KeywordsOptions': """Initialize a KeywordsOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'sentiment' in _dict: - args['sentiment'] = _dict.get('sentiment') - if 'emotion' in _dict: - args['emotion'] = _dict.get('emotion') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = sentiment + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = emotion return cls(**args) @classmethod @@ -3928,28 +4070,30 @@ def __ne__(self, other: 'KeywordsOptions') -> bool: return not self == other -class KeywordsResult(): +class KeywordsResult: """ The important keywords in the content, organized by relevance. - :attr int count: (optional) Number of times the keyword appears in the analyzed + :param int count: (optional) Number of times the keyword appears in the analyzed text. - :attr float relevance: (optional) Relevance score from 0 to 1. Higher values + :param float relevance: (optional) Relevance score from 0 to 1. Higher values indicate greater relevance. - :attr str text: (optional) The keyword text. - :attr EmotionScores emotion: (optional) Emotion analysis results for the + :param str text: (optional) The keyword text. + :param EmotionScores emotion: (optional) Emotion analysis results for the keyword, enabled with the `emotion` option. - :attr FeatureSentimentResults sentiment: (optional) Sentiment analysis results + :param FeatureSentimentResults sentiment: (optional) Sentiment analysis results for the keyword, enabled with the `sentiment` option. """ - def __init__(self, - *, - count: int = None, - relevance: float = None, - text: str = None, - emotion: 'EmotionScores' = None, - sentiment: 'FeatureSentimentResults' = None) -> None: + def __init__( + self, + *, + count: Optional[int] = None, + relevance: Optional[float] = None, + text: Optional[str] = None, + emotion: Optional['EmotionScores'] = None, + sentiment: Optional['FeatureSentimentResults'] = None, + ) -> None: """ Initialize a KeywordsResult object. @@ -3973,17 +4117,16 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'KeywordsResult': """Initialize a KeywordsResult object from a json dictionary.""" args = {} - if 'count' in _dict: - args['count'] = _dict.get('count') - if 'relevance' in _dict: - args['relevance'] = _dict.get('relevance') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) - if 'sentiment' in _dict: - args['sentiment'] = FeatureSentimentResults.from_dict( - _dict.get('sentiment')) + if (count := _dict.get('count')) is not None: + args['count'] = count + if (relevance := _dict.get('relevance')) is not None: + args['relevance'] = relevance + if (text := _dict.get('text')) is not None: + args['text'] = text + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) + if (sentiment := _dict.get('sentiment')) is not None: + args['sentiment'] = FeatureSentimentResults.from_dict(sentiment) return cls(**args) @classmethod @@ -4031,14 +4174,18 @@ def __ne__(self, other: 'KeywordsResult') -> bool: return not self == other -class ListModelsResults(): +class ListModelsResults: """ Custom models that are available for entities and relations. - :attr List[Model] models: (optional) An array of available models. + :param List[Model] models: (optional) An array of available models. """ - def __init__(self, *, models: List['Model'] = None) -> None: + def __init__( + self, + *, + models: Optional[List['Model']] = None, + ) -> None: """ Initialize a ListModelsResults object. @@ -4050,8 +4197,8 @@ def __init__(self, *, models: List['Model'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'ListModelsResults': """Initialize a ListModelsResults object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [Model.from_dict(v) for v in _dict.get('models')] + if (models := _dict.get('models')) is not None: + args['models'] = [Model.from_dict(v) for v in models] return cls(**args) @classmethod @@ -4091,38 +4238,40 @@ def __ne__(self, other: 'ListModelsResults') -> bool: return not self == other -class Model(): +class Model: """ Model. - :attr str status: (optional) When the status is `available`, the model is ready + :param str status: (optional) When the status is `available`, the model is ready to use. - :attr str model_id: (optional) Unique model ID. - :attr str language: (optional) ISO 639-1 code that indicates the language of the - model. - :attr str description: (optional) Model description. - :attr str workspace_id: (optional) ID of the Watson Knowledge Studio workspace + :param str model_id: (optional) Unique model ID. + :param str language: (optional) ISO 639-1 code that indicates the language of + the model. + :param str description: (optional) Model description. + :param str workspace_id: (optional) ID of the Watson Knowledge Studio workspace that deployed this model to Natural Language Understanding. - :attr str model_version: (optional) The model version, if it was manually + :param str model_version: (optional) The model version, if it was manually provided in Watson Knowledge Studio. - :attr str version: (optional) Deprecated: Deprecated — use `model_version`. - :attr str version_description: (optional) The description of the version, if it + :param str version: (optional) Deprecated: Deprecated — use `model_version`. + :param str version_description: (optional) The description of the version, if it was manually provided in Watson Knowledge Studio. - :attr datetime created: (optional) A dateTime indicating when the model was + :param datetime created: (optional) A dateTime indicating when the model was created. """ - def __init__(self, - *, - status: str = None, - model_id: str = None, - language: str = None, - description: str = None, - workspace_id: str = None, - model_version: str = None, - version: str = None, - version_description: str = None, - created: datetime = None) -> None: + def __init__( + self, + *, + status: Optional[str] = None, + model_id: Optional[str] = None, + language: Optional[str] = None, + description: Optional[str] = None, + workspace_id: Optional[str] = None, + model_version: Optional[str] = None, + version: Optional[str] = None, + version_description: Optional[str] = None, + created: Optional[datetime] = None, + ) -> None: """ Initialize a Model object. @@ -4157,24 +4306,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Model': """Initialize a Model object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'workspace_id' in _dict: - args['workspace_id'] = _dict.get('workspace_id') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'version' in _dict: - args['version'] = _dict.get('version') - if 'version_description' in _dict: - args['version_description'] = _dict.get('version_description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + if (language := _dict.get('language')) is not None: + args['language'] = language + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (model_version := _dict.get('model_version')) is not None: + args['model_version'] = model_version + if (version := _dict.get('version')) is not None: + args['version'] = version + if (version_description := + _dict.get('version_description')) is not None: + args['version_description'] = version_description + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) return cls(**args) @classmethod @@ -4229,6 +4379,7 @@ class StatusEnum(str, Enum): """ When the status is `available`, the model is ready to use. """ + STARTING = 'starting' TRAINING = 'training' DEPLOYING = 'deploying' @@ -4237,15 +4388,19 @@ class StatusEnum(str, Enum): DELETED = 'deleted' -class Notice(): +class Notice: """ A list of messages describing model training issues when model status is `error`. - :attr str message: (optional) Describes deficiencies or inconsistencies in + :param str message: (optional) Describes deficiencies or inconsistencies in training data. """ - def __init__(self, *, message: str = None) -> None: + def __init__( + self, + *, + message: Optional[str] = None, + ) -> None: """ Initialize a Notice object. @@ -4256,8 +4411,8 @@ def __init__(self, *, message: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Notice': """Initialize a Notice object from a json dictionary.""" args = {} - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod @@ -4291,21 +4446,23 @@ def __ne__(self, other: 'Notice') -> bool: return not self == other -class RelationArgument(): +class RelationArgument: """ RelationArgument. - :attr List[RelationEntity] entities: (optional) An array of extracted entities. - :attr List[int] location: (optional) Character offsets indicating the beginning + :param List[RelationEntity] entities: (optional) An array of extracted entities. + :param List[int] location: (optional) Character offsets indicating the beginning and end of the mention in the analyzed text. - :attr str text: (optional) Text that corresponds to the argument. + :param str text: (optional) Text that corresponds to the argument. """ - def __init__(self, - *, - entities: List['RelationEntity'] = None, - location: List[int] = None, - text: str = None) -> None: + def __init__( + self, + *, + entities: Optional[List['RelationEntity']] = None, + location: Optional[List[int]] = None, + text: Optional[str] = None, + ) -> None: """ Initialize a RelationArgument object. @@ -4323,14 +4480,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RelationArgument': """Initialize a RelationArgument object from a json dictionary.""" args = {} - if 'entities' in _dict: - args['entities'] = [ - RelationEntity.from_dict(v) for v in _dict.get('entities') - ] - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'text' in _dict: - args['text'] = _dict.get('text') + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RelationEntity.from_dict(v) for v in entities] + if (location := _dict.get('location')) is not None: + args['location'] = location + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -4374,15 +4529,20 @@ def __ne__(self, other: 'RelationArgument') -> bool: return not self == other -class RelationEntity(): +class RelationEntity: """ An entity that corresponds with an argument in a relation. - :attr str text: (optional) Text that corresponds to the entity. - :attr str type: (optional) Entity type. + :param str text: (optional) Text that corresponds to the entity. + :param str type: (optional) Entity type. """ - def __init__(self, *, text: str = None, type: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + type: Optional[str] = None, + ) -> None: """ Initialize a RelationEntity object. @@ -4396,10 +4556,10 @@ def __init__(self, *, text: str = None, type: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RelationEntity': """Initialize a RelationEntity object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'type' in _dict: - args['type'] = _dict.get('type') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod @@ -4435,7 +4595,7 @@ def __ne__(self, other: 'RelationEntity') -> bool: return not self == other -class RelationsOptions(): +class RelationsOptions: """ Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert @@ -4444,12 +4604,16 @@ class RelationsOptions(): Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. - :attr str model: (optional) Enter a [custom + :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID to override the default model. """ - def __init__(self, *, model: str = None) -> None: + def __init__( + self, + *, + model: Optional[str] = None, + ) -> None: """ Initialize a RelationsOptions object. @@ -4463,8 +4627,8 @@ def __init__(self, *, model: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'RelationsOptions': """Initialize a RelationsOptions object from a json dictionary.""" args = {} - if 'model' in _dict: - args['model'] = _dict.get('model') + if (model := _dict.get('model')) is not None: + args['model'] = model return cls(**args) @classmethod @@ -4498,24 +4662,26 @@ def __ne__(self, other: 'RelationsOptions') -> bool: return not self == other -class RelationsResult(): +class RelationsResult: """ The relations between entities found in the content. - :attr float score: (optional) Confidence score for the relation. Higher values + :param float score: (optional) Confidence score for the relation. Higher values indicate greater confidence. - :attr str sentence: (optional) The sentence that contains the relation. - :attr str type: (optional) The type of the relation. - :attr List[RelationArgument] arguments: (optional) Entity mentions that are + :param str sentence: (optional) The sentence that contains the relation. + :param str type: (optional) The type of the relation. + :param List[RelationArgument] arguments: (optional) Entity mentions that are involved in the relation. """ - def __init__(self, - *, - score: float = None, - sentence: str = None, - type: str = None, - arguments: List['RelationArgument'] = None) -> None: + def __init__( + self, + *, + score: Optional[float] = None, + sentence: Optional[str] = None, + type: Optional[str] = None, + arguments: Optional[List['RelationArgument']] = None, + ) -> None: """ Initialize a RelationsResult object. @@ -4535,15 +4701,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RelationsResult': """Initialize a RelationsResult object from a json dictionary.""" args = {} - if 'score' in _dict: - args['score'] = _dict.get('score') - if 'sentence' in _dict: - args['sentence'] = _dict.get('sentence') - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'arguments' in _dict: + if (score := _dict.get('score')) is not None: + args['score'] = score + if (sentence := _dict.get('sentence')) is not None: + args['sentence'] = sentence + if (type := _dict.get('type')) is not None: + args['type'] = type + if (arguments := _dict.get('arguments')) is not None: args['arguments'] = [ - RelationArgument.from_dict(v) for v in _dict.get('arguments') + RelationArgument.from_dict(v) for v in arguments ] return cls(**args) @@ -4590,15 +4756,20 @@ def __ne__(self, other: 'RelationsResult') -> bool: return not self == other -class SemanticRolesEntity(): +class SemanticRolesEntity: """ SemanticRolesEntity. - :attr str type: (optional) Entity type. - :attr str text: (optional) The entity text. + :param str type: (optional) Entity type. + :param str text: (optional) The entity text. """ - def __init__(self, *, type: str = None, text: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + text: Optional[str] = None, + ) -> None: """ Initialize a SemanticRolesEntity object. @@ -4612,10 +4783,10 @@ def __init__(self, *, type: str = None, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesEntity': """Initialize a SemanticRolesEntity object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -4651,14 +4822,18 @@ def __ne__(self, other: 'SemanticRolesEntity') -> bool: return not self == other -class SemanticRolesKeyword(): +class SemanticRolesKeyword: """ SemanticRolesKeyword. - :attr str text: (optional) The keyword text. + :param str text: (optional) The keyword text. """ - def __init__(self, *, text: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + ) -> None: """ Initialize a SemanticRolesKeyword object. @@ -4670,8 +4845,8 @@ def __init__(self, *, text: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesKeyword': """Initialize a SemanticRolesKeyword object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') + if (text := _dict.get('text')) is not None: + args['text'] = text return cls(**args) @classmethod @@ -4705,23 +4880,25 @@ def __ne__(self, other: 'SemanticRolesKeyword') -> bool: return not self == other -class SemanticRolesOptions(): +class SemanticRolesOptions: """ Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. - :attr int limit: (optional) Maximum number of semantic_roles results to return. - :attr bool keywords: (optional) Set this to `true` to return keyword information - for subjects and objects. - :attr bool entities: (optional) Set this to `true` to return entity information + :param int limit: (optional) Maximum number of semantic_roles results to return. + :param bool keywords: (optional) Set this to `true` to return keyword + information for subjects and objects. + :param bool entities: (optional) Set this to `true` to return entity information for subjects and objects. """ - def __init__(self, - *, - limit: int = None, - keywords: bool = None, - entities: bool = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + keywords: Optional[bool] = None, + entities: Optional[bool] = None, + ) -> None: """ Initialize a SemanticRolesOptions object. @@ -4740,12 +4917,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesOptions': """Initialize a SemanticRolesOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') - if 'keywords' in _dict: - args['keywords'] = _dict.get('keywords') - if 'entities' in _dict: - args['entities'] = _dict.get('entities') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit + if (keywords := _dict.get('keywords')) is not None: + args['keywords'] = keywords + if (entities := _dict.get('entities')) is not None: + args['entities'] = entities return cls(**args) @classmethod @@ -4783,26 +4960,28 @@ def __ne__(self, other: 'SemanticRolesOptions') -> bool: return not self == other -class SemanticRolesResult(): +class SemanticRolesResult: """ The object containing the actions and the objects the actions act upon. - :attr str sentence: (optional) Sentence from the source that contains the + :param str sentence: (optional) Sentence from the source that contains the subject, action, and object. - :attr SemanticRolesResultSubject subject: (optional) The extracted subject from + :param SemanticRolesResultSubject subject: (optional) The extracted subject from + the sentence. + :param SemanticRolesResultAction action: (optional) The extracted action from + the sentence. + :param SemanticRolesResultObject object: (optional) The extracted object from the sentence. - :attr SemanticRolesResultAction action: (optional) The extracted action from the - sentence. - :attr SemanticRolesResultObject object: (optional) The extracted object from the - sentence. """ - def __init__(self, - *, - sentence: str = None, - subject: 'SemanticRolesResultSubject' = None, - action: 'SemanticRolesResultAction' = None, - object: 'SemanticRolesResultObject' = None) -> None: + def __init__( + self, + *, + sentence: Optional[str] = None, + subject: Optional['SemanticRolesResultSubject'] = None, + action: Optional['SemanticRolesResultAction'] = None, + object: Optional['SemanticRolesResultObject'] = None, + ) -> None: """ Initialize a SemanticRolesResult object. @@ -4824,17 +5003,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResult': """Initialize a SemanticRolesResult object from a json dictionary.""" args = {} - if 'sentence' in _dict: - args['sentence'] = _dict.get('sentence') - if 'subject' in _dict: - args['subject'] = SemanticRolesResultSubject.from_dict( - _dict.get('subject')) - if 'action' in _dict: - args['action'] = SemanticRolesResultAction.from_dict( - _dict.get('action')) - if 'object' in _dict: - args['object'] = SemanticRolesResultObject.from_dict( - _dict.get('object')) + if (sentence := _dict.get('sentence')) is not None: + args['sentence'] = sentence + if (subject := _dict.get('subject')) is not None: + args['subject'] = SemanticRolesResultSubject.from_dict(subject) + if (action := _dict.get('action')) is not None: + args['action'] = SemanticRolesResultAction.from_dict(action) + if (object := _dict.get('object')) is not None: + args['object'] = SemanticRolesResultObject.from_dict(object) return cls(**args) @classmethod @@ -4883,20 +5059,22 @@ def __ne__(self, other: 'SemanticRolesResult') -> bool: return not self == other -class SemanticRolesResultAction(): +class SemanticRolesResultAction: """ The extracted action from the sentence. - :attr str text: (optional) Analyzed text that corresponds to the action. - :attr str normalized: (optional) normalized version of the action. - :attr SemanticRolesVerb verb: (optional) + :param str text: (optional) Analyzed text that corresponds to the action. + :param str normalized: (optional) normalized version of the action. + :param SemanticRolesVerb verb: (optional) """ - def __init__(self, - *, - text: str = None, - normalized: str = None, - verb: 'SemanticRolesVerb' = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + normalized: Optional[str] = None, + verb: Optional['SemanticRolesVerb'] = None, + ) -> None: """ Initialize a SemanticRolesResultAction object. @@ -4912,12 +5090,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultAction': """Initialize a SemanticRolesResultAction object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'normalized' in _dict: - args['normalized'] = _dict.get('normalized') - if 'verb' in _dict: - args['verb'] = SemanticRolesVerb.from_dict(_dict.get('verb')) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (normalized := _dict.get('normalized')) is not None: + args['normalized'] = normalized + if (verb := _dict.get('verb')) is not None: + args['verb'] = SemanticRolesVerb.from_dict(verb) return cls(**args) @classmethod @@ -4958,19 +5136,21 @@ def __ne__(self, other: 'SemanticRolesResultAction') -> bool: return not self == other -class SemanticRolesResultObject(): +class SemanticRolesResultObject: """ The extracted object from the sentence. - :attr str text: (optional) Object text. - :attr List[SemanticRolesKeyword] keywords: (optional) An array of extracted + :param str text: (optional) Object text. + :param List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ - def __init__(self, - *, - text: str = None, - keywords: List['SemanticRolesKeyword'] = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + keywords: Optional[List['SemanticRolesKeyword']] = None, + ) -> None: """ Initialize a SemanticRolesResultObject object. @@ -4985,11 +5165,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultObject': """Initialize a SemanticRolesResultObject object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'keywords' in _dict: + if (text := _dict.get('text')) is not None: + args['text'] = text + if (keywords := _dict.get('keywords')) is not None: args['keywords'] = [ - SemanticRolesKeyword.from_dict(v) for v in _dict.get('keywords') + SemanticRolesKeyword.from_dict(v) for v in keywords ] return cls(**args) @@ -5032,22 +5212,24 @@ def __ne__(self, other: 'SemanticRolesResultObject') -> bool: return not self == other -class SemanticRolesResultSubject(): +class SemanticRolesResultSubject: """ The extracted subject from the sentence. - :attr str text: (optional) Text that corresponds to the subject role. - :attr List[SemanticRolesEntity] entities: (optional) An array of extracted + :param str text: (optional) Text that corresponds to the subject role. + :param List[SemanticRolesEntity] entities: (optional) An array of extracted entities. - :attr List[SemanticRolesKeyword] keywords: (optional) An array of extracted + :param List[SemanticRolesKeyword] keywords: (optional) An array of extracted keywords. """ - def __init__(self, - *, - text: str = None, - entities: List['SemanticRolesEntity'] = None, - keywords: List['SemanticRolesKeyword'] = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + entities: Optional[List['SemanticRolesEntity']] = None, + keywords: Optional[List['SemanticRolesKeyword']] = None, + ) -> None: """ Initialize a SemanticRolesResultSubject object. @@ -5065,15 +5247,15 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SemanticRolesResultSubject': """Initialize a SemanticRolesResultSubject object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'entities' in _dict: + if (text := _dict.get('text')) is not None: + args['text'] = text + if (entities := _dict.get('entities')) is not None: args['entities'] = [ - SemanticRolesEntity.from_dict(v) for v in _dict.get('entities') + SemanticRolesEntity.from_dict(v) for v in entities ] - if 'keywords' in _dict: + if (keywords := _dict.get('keywords')) is not None: args['keywords'] = [ - SemanticRolesKeyword.from_dict(v) for v in _dict.get('keywords') + SemanticRolesKeyword.from_dict(v) for v in keywords ] return cls(**args) @@ -5124,15 +5306,20 @@ def __ne__(self, other: 'SemanticRolesResultSubject') -> bool: return not self == other -class SemanticRolesVerb(): +class SemanticRolesVerb: """ SemanticRolesVerb. - :attr str text: (optional) The keyword text. - :attr str tense: (optional) Verb tense. + :param str text: (optional) The keyword text. + :param str tense: (optional) Verb tense. """ - def __init__(self, *, text: str = None, tense: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + tense: Optional[str] = None, + ) -> None: """ Initialize a SemanticRolesVerb object. @@ -5146,10 +5333,10 @@ def __init__(self, *, text: str = None, tense: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'SemanticRolesVerb': """Initialize a SemanticRolesVerb object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'tense' in _dict: - args['tense'] = _dict.get('tense') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (tense := _dict.get('tense')) is not None: + args['tense'] = tense return cls(**args) @classmethod @@ -5185,16 +5372,21 @@ def __ne__(self, other: 'SemanticRolesVerb') -> bool: return not self == other -class SentenceResult(): +class SentenceResult: """ SentenceResult. - :attr str text: (optional) The sentence. - :attr List[int] location: (optional) Character offsets indicating the beginning + :param str text: (optional) The sentence. + :param List[int] location: (optional) Character offsets indicating the beginning and end of the sentence in the analyzed text. """ - def __init__(self, *, text: str = None, location: List[int] = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + location: Optional[List[int]] = None, + ) -> None: """ Initialize a SentenceResult object. @@ -5209,10 +5401,10 @@ def __init__(self, *, text: str = None, location: List[int] = None) -> None: def from_dict(cls, _dict: Dict) -> 'SentenceResult': """Initialize a SentenceResult object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = _dict.get('location') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (location := _dict.get('location')) is not None: + args['location'] = location return cls(**args) @classmethod @@ -5248,7 +5440,7 @@ def __ne__(self, other: 'SentenceResult') -> bool: return not self == other -class SentimentOptions(): +class SentimentOptions: """ Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and @@ -5256,16 +5448,18 @@ class SentimentOptions(): Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :attr bool document: (optional) Set this to `false` to hide document-level + :param bool document: (optional) Set this to `false` to hide document-level sentiment results. - :attr List[str] targets: (optional) Sentiment results will be returned for each + :param List[str] targets: (optional) Sentiment results will be returned for each target string that is found in the document. """ - def __init__(self, - *, - document: bool = None, - targets: List[str] = None) -> None: + def __init__( + self, + *, + document: Optional[bool] = None, + targets: Optional[List[str]] = None, + ) -> None: """ Initialize a SentimentOptions object. @@ -5281,10 +5475,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SentimentOptions': """Initialize a SentimentOptions object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = _dict.get('document') - if 'targets' in _dict: - args['targets'] = _dict.get('targets') + if (document := _dict.get('document')) is not None: + args['document'] = document + if (targets := _dict.get('targets')) is not None: + args['targets'] = targets return cls(**args) @classmethod @@ -5320,20 +5514,22 @@ def __ne__(self, other: 'SentimentOptions') -> bool: return not self == other -class SentimentResult(): +class SentimentResult: """ The sentiment of the content. - :attr DocumentSentimentResults document: (optional) The document level + :param DocumentSentimentResults document: (optional) The document level sentiment. - :attr List[TargetedSentimentResults] targets: (optional) The targeted sentiment + :param List[TargetedSentimentResults] targets: (optional) The targeted sentiment to analyze. """ - def __init__(self, - *, - document: 'DocumentSentimentResults' = None, - targets: List['TargetedSentimentResults'] = None) -> None: + def __init__( + self, + *, + document: Optional['DocumentSentimentResults'] = None, + targets: Optional[List['TargetedSentimentResults']] = None, + ) -> None: """ Initialize a SentimentResult object. @@ -5349,13 +5545,11 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SentimentResult': """Initialize a SentimentResult object from a json dictionary.""" args = {} - if 'document' in _dict: - args['document'] = DocumentSentimentResults.from_dict( - _dict.get('document')) - if 'targets' in _dict: + if (document := _dict.get('document')) is not None: + args['document'] = DocumentSentimentResults.from_dict(document) + if (targets := _dict.get('targets')) is not None: args['targets'] = [ - TargetedSentimentResults.from_dict(v) - for v in _dict.get('targets') + TargetedSentimentResults.from_dict(v) for v in targets ] return cls(**args) @@ -5401,16 +5595,20 @@ def __ne__(self, other: 'SentimentResult') -> bool: return not self == other -class SummarizationOptions(): +class SummarizationOptions: """ (Experimental) Returns a summary of content. Supported languages: English only. Supported regions: Dallas region only. - :attr int limit: (optional) Maximum number of summary sentences to return. + :param int limit: (optional) Maximum number of summary sentences to return. """ - def __init__(self, *, limit: int = None) -> None: + def __init__( + self, + *, + limit: Optional[int] = None, + ) -> None: """ Initialize a SummarizationOptions object. @@ -5422,8 +5620,8 @@ def __init__(self, *, limit: int = None) -> None: def from_dict(cls, _dict: Dict) -> 'SummarizationOptions': """Initialize a SummarizationOptions object from a json dictionary.""" args = {} - if 'limit' in _dict: - args['limit'] = _dict.get('limit') + if (limit := _dict.get('limit')) is not None: + args['limit'] = limit return cls(**args) @classmethod @@ -5457,19 +5655,21 @@ def __ne__(self, other: 'SummarizationOptions') -> bool: return not self == other -class SyntaxOptions(): +class SyntaxOptions: """ Returns tokens and sentences from the input text. - :attr SyntaxOptionsTokens tokens: (optional) Tokenization options. - :attr bool sentences: (optional) Set this to `true` to return sentence + :param SyntaxOptionsTokens tokens: (optional) Tokenization options. + :param bool sentences: (optional) Set this to `true` to return sentence information. """ - def __init__(self, - *, - tokens: 'SyntaxOptionsTokens' = None, - sentences: bool = None) -> None: + def __init__( + self, + *, + tokens: Optional['SyntaxOptionsTokens'] = None, + sentences: Optional[bool] = None, + ) -> None: """ Initialize a SyntaxOptions object. @@ -5484,10 +5684,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxOptions': """Initialize a SyntaxOptions object from a json dictionary.""" args = {} - if 'tokens' in _dict: - args['tokens'] = SyntaxOptionsTokens.from_dict(_dict.get('tokens')) - if 'sentences' in _dict: - args['sentences'] = _dict.get('sentences') + if (tokens := _dict.get('tokens')) is not None: + args['tokens'] = SyntaxOptionsTokens.from_dict(tokens) + if (sentences := _dict.get('sentences')) is not None: + args['sentences'] = sentences return cls(**args) @classmethod @@ -5526,20 +5726,22 @@ def __ne__(self, other: 'SyntaxOptions') -> bool: return not self == other -class SyntaxOptionsTokens(): +class SyntaxOptionsTokens: """ Tokenization options. - :attr bool lemma: (optional) Set this to `true` to return the lemma for each + :param bool lemma: (optional) Set this to `true` to return the lemma for each token. - :attr bool part_of_speech: (optional) Set this to `true` to return the part of + :param bool part_of_speech: (optional) Set this to `true` to return the part of speech for each token. """ - def __init__(self, - *, - lemma: bool = None, - part_of_speech: bool = None) -> None: + def __init__( + self, + *, + lemma: Optional[bool] = None, + part_of_speech: Optional[bool] = None, + ) -> None: """ Initialize a SyntaxOptionsTokens object. @@ -5555,10 +5757,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxOptionsTokens': """Initialize a SyntaxOptionsTokens object from a json dictionary.""" args = {} - if 'lemma' in _dict: - args['lemma'] = _dict.get('lemma') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') + if (lemma := _dict.get('lemma')) is not None: + args['lemma'] = lemma + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech return cls(**args) @classmethod @@ -5594,18 +5796,20 @@ def __ne__(self, other: 'SyntaxOptionsTokens') -> bool: return not self == other -class SyntaxResult(): +class SyntaxResult: """ Tokens and sentences returned from syntax analysis. - :attr List[TokenResult] tokens: (optional) - :attr List[SentenceResult] sentences: (optional) + :param List[TokenResult] tokens: (optional) + :param List[SentenceResult] sentences: (optional) """ - def __init__(self, - *, - tokens: List['TokenResult'] = None, - sentences: List['SentenceResult'] = None) -> None: + def __init__( + self, + *, + tokens: Optional[List['TokenResult']] = None, + sentences: Optional[List['SentenceResult']] = None, + ) -> None: """ Initialize a SyntaxResult object. @@ -5619,14 +5823,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SyntaxResult': """Initialize a SyntaxResult object from a json dictionary.""" args = {} - if 'tokens' in _dict: - args['tokens'] = [ - TokenResult.from_dict(v) for v in _dict.get('tokens') - ] - if 'sentences' in _dict: - args['sentences'] = [ - SentenceResult.from_dict(v) for v in _dict.get('sentences') - ] + if (tokens := _dict.get('tokens')) is not None: + args['tokens'] = [TokenResult.from_dict(v) for v in tokens] + if (sentences := _dict.get('sentences')) is not None: + args['sentences'] = [SentenceResult.from_dict(v) for v in sentences] return cls(**args) @classmethod @@ -5674,18 +5874,20 @@ def __ne__(self, other: 'SyntaxResult') -> bool: return not self == other -class TargetedEmotionResults(): +class TargetedEmotionResults: """ Emotion results for a specified target. - :attr str text: (optional) Targeted text. - :attr EmotionScores emotion: (optional) The emotion results for the target. + :param str text: (optional) Targeted text. + :param EmotionScores emotion: (optional) The emotion results for the target. """ - def __init__(self, - *, - text: str = None, - emotion: 'EmotionScores' = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + emotion: Optional['EmotionScores'] = None, + ) -> None: """ Initialize a TargetedEmotionResults object. @@ -5700,10 +5902,10 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TargetedEmotionResults': """Initialize a TargetedEmotionResults object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'emotion' in _dict: - args['emotion'] = EmotionScores.from_dict(_dict.get('emotion')) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (emotion := _dict.get('emotion')) is not None: + args['emotion'] = EmotionScores.from_dict(emotion) return cls(**args) @classmethod @@ -5742,16 +5944,21 @@ def __ne__(self, other: 'TargetedEmotionResults') -> bool: return not self == other -class TargetedSentimentResults(): +class TargetedSentimentResults: """ TargetedSentimentResults. - :attr str text: (optional) Targeted text. - :attr float score: (optional) Sentiment score from -1 (negative) to 1 + :param str text: (optional) Targeted text. + :param float score: (optional) Sentiment score from -1 (negative) to 1 (positive). """ - def __init__(self, *, text: str = None, score: float = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + score: Optional[float] = None, + ) -> None: """ Initialize a TargetedSentimentResults object. @@ -5766,10 +5973,10 @@ def __init__(self, *, text: str = None, score: float = None) -> None: def from_dict(cls, _dict: Dict) -> 'TargetedSentimentResults': """Initialize a TargetedSentimentResults object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'score' in _dict: - args['score'] = _dict.get('score') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (score := _dict.get('score')) is not None: + args['score'] = score return cls(**args) @classmethod @@ -5805,26 +6012,28 @@ def __ne__(self, other: 'TargetedSentimentResults') -> bool: return not self == other -class TokenResult(): +class TokenResult: """ TokenResult. - :attr str text: (optional) The token as it appears in the analyzed text. - :attr str part_of_speech: (optional) The part of speech of the token. For more + :param str text: (optional) The token as it appears in the analyzed text. + :param str part_of_speech: (optional) The part of speech of the token. For more information about the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). - :attr List[int] location: (optional) Character offsets indicating the beginning + :param List[int] location: (optional) Character offsets indicating the beginning and end of the token in the analyzed text. - :attr str lemma: (optional) The + :param str lemma: (optional) The [lemma](https://wikipedia.org/wiki/Lemma_%28morphology%29) of the token. """ - def __init__(self, - *, - text: str = None, - part_of_speech: str = None, - location: List[int] = None, - lemma: str = None) -> None: + def __init__( + self, + *, + text: Optional[str] = None, + part_of_speech: Optional[str] = None, + location: Optional[List[int]] = None, + lemma: Optional[str] = None, + ) -> None: """ Initialize a TokenResult object. @@ -5846,14 +6055,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'TokenResult': """Initialize a TokenResult object from a json dictionary.""" args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'lemma' in _dict: - args['lemma'] = _dict.get('lemma') + if (text := _dict.get('text')) is not None: + args['text'] = text + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech + if (location := _dict.get('location')) is not None: + args['location'] = location + if (lemma := _dict.get('lemma')) is not None: + args['lemma'] = lemma return cls(**args) @classmethod @@ -5897,6 +6106,7 @@ class PartOfSpeechEnum(str, Enum): The part of speech of the token. For more information about the values, see [Universal Dependencies POS tags](https://universaldependencies.org/u/pos/). """ + ADJ = 'ADJ' ADP = 'ADP' ADV = 'ADV' diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 7d35d6eb5..dda763930 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's speech-recognition capabilities to produce transcripts of spoken audio. The service can @@ -51,7 +51,7 @@ """ from enum import Enum -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -95,7 +95,10 @@ def __init__( # Models ######################### - def list_models(self, **kwargs) -> DetailedResponse: + def list_models( + self, + **kwargs, + ) -> DetailedResponse: """ List models. @@ -112,9 +115,11 @@ def list_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_models', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -123,12 +128,20 @@ def list_models(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/models' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def get_model(self, model_id: str, **kwargs) -> DetailedResponse: + def get_model( + self, + model_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a model. @@ -148,9 +161,11 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: if not model_id: raise ValueError('model_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -162,7 +177,11 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(model_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -171,35 +190,37 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: # Synchronous ######################### - def recognize(self, - audio: BinaryIO, - *, - content_type: str = None, - model: str = None, - language_customization_id: str = None, - acoustic_customization_id: str = None, - base_model_version: str = None, - customization_weight: float = None, - inactivity_timeout: int = None, - keywords: List[str] = None, - keywords_threshold: float = None, - max_alternatives: int = None, - word_alternatives_threshold: float = None, - word_confidence: bool = None, - timestamps: bool = None, - profanity_filter: bool = None, - smart_formatting: bool = None, - speaker_labels: bool = None, - grammar_name: str = None, - redaction: bool = None, - audio_metrics: bool = None, - end_of_phrase_silence_time: float = None, - split_transcript_at_phrase_end: bool = None, - speech_detector_sensitivity: float = None, - background_audio_suppression: float = None, - low_latency: bool = None, - character_insertion_bias: float = None, - **kwargs) -> DetailedResponse: + def recognize( + self, + audio: BinaryIO, + *, + content_type: Optional[str] = None, + model: Optional[str] = None, + language_customization_id: Optional[str] = None, + acoustic_customization_id: Optional[str] = None, + base_model_version: Optional[str] = None, + customization_weight: Optional[float] = None, + inactivity_timeout: Optional[int] = None, + keywords: Optional[List[str]] = None, + keywords_threshold: Optional[float] = None, + max_alternatives: Optional[int] = None, + word_alternatives_threshold: Optional[float] = None, + word_confidence: Optional[bool] = None, + timestamps: Optional[bool] = None, + profanity_filter: Optional[bool] = None, + smart_formatting: Optional[bool] = None, + speaker_labels: Optional[bool] = None, + grammar_name: Optional[str] = None, + redaction: Optional[bool] = None, + audio_metrics: Optional[bool] = None, + end_of_phrase_silence_time: Optional[float] = None, + split_transcript_at_phrase_end: Optional[bool] = None, + speech_detector_sensitivity: Optional[float] = None, + background_audio_suppression: Optional[float] = None, + low_latency: Optional[bool] = None, + character_insertion_bias: Optional[float] = None, + **kwargs, + ) -> DetailedResponse: """ Recognize audio. @@ -575,9 +596,11 @@ def recognize(self, headers = { 'Content-Type': content_type, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='recognize') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='recognize', + ) headers.update(sdk_headers) params = { @@ -615,11 +638,13 @@ def recognize(self, headers['Accept'] = 'application/json' url = '/v1/recognize' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -628,11 +653,13 @@ def recognize(self, # Asynchronous ######################### - def register_callback(self, - callback_url: str, - *, - user_secret: str = None, - **kwargs) -> DetailedResponse: + def register_callback( + self, + callback_url: str, + *, + user_secret: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Register a callback. @@ -685,9 +712,11 @@ def register_callback(self, if not callback_url: raise ValueError('callback_url must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='register_callback') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='register_callback', + ) headers.update(sdk_headers) params = { @@ -701,16 +730,21 @@ def register_callback(self, headers['Accept'] = 'application/json' url = '/v1/register_callback' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def unregister_callback(self, callback_url: str, - **kwargs) -> DetailedResponse: + def unregister_callback( + self, + callback_url: str, + **kwargs, + ) -> DetailedResponse: """ Unregister a callback. @@ -730,9 +764,11 @@ def unregister_callback(self, callback_url: str, if not callback_url: raise ValueError('callback_url must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='unregister_callback') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='unregister_callback', + ) headers.update(sdk_headers) params = { @@ -744,49 +780,53 @@ def unregister_callback(self, callback_url: str, del kwargs['headers'] url = '/v1/unregister_callback' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def create_job(self, - audio: BinaryIO, - *, - content_type: str = None, - model: str = None, - callback_url: str = None, - events: str = None, - user_token: str = None, - results_ttl: int = None, - language_customization_id: str = None, - acoustic_customization_id: str = None, - base_model_version: str = None, - customization_weight: float = None, - inactivity_timeout: int = None, - keywords: List[str] = None, - keywords_threshold: float = None, - max_alternatives: int = None, - word_alternatives_threshold: float = None, - word_confidence: bool = None, - timestamps: bool = None, - profanity_filter: bool = None, - smart_formatting: bool = None, - speaker_labels: bool = None, - grammar_name: str = None, - redaction: bool = None, - processing_metrics: bool = None, - processing_metrics_interval: float = None, - audio_metrics: bool = None, - end_of_phrase_silence_time: float = None, - split_transcript_at_phrase_end: bool = None, - speech_detector_sensitivity: float = None, - background_audio_suppression: float = None, - low_latency: bool = None, - character_insertion_bias: float = None, - **kwargs) -> DetailedResponse: + def create_job( + self, + audio: BinaryIO, + *, + content_type: Optional[str] = None, + model: Optional[str] = None, + callback_url: Optional[str] = None, + events: Optional[str] = None, + user_token: Optional[str] = None, + results_ttl: Optional[int] = None, + language_customization_id: Optional[str] = None, + acoustic_customization_id: Optional[str] = None, + base_model_version: Optional[str] = None, + customization_weight: Optional[float] = None, + inactivity_timeout: Optional[int] = None, + keywords: Optional[List[str]] = None, + keywords_threshold: Optional[float] = None, + max_alternatives: Optional[int] = None, + word_alternatives_threshold: Optional[float] = None, + word_confidence: Optional[bool] = None, + timestamps: Optional[bool] = None, + profanity_filter: Optional[bool] = None, + smart_formatting: Optional[bool] = None, + speaker_labels: Optional[bool] = None, + grammar_name: Optional[str] = None, + redaction: Optional[bool] = None, + processing_metrics: Optional[bool] = None, + processing_metrics_interval: Optional[float] = None, + audio_metrics: Optional[bool] = None, + end_of_phrase_silence_time: Optional[float] = None, + split_transcript_at_phrase_end: Optional[bool] = None, + speech_detector_sensitivity: Optional[float] = None, + background_audio_suppression: Optional[float] = None, + low_latency: Optional[bool] = None, + character_insertion_bias: Optional[float] = None, + **kwargs, + ) -> DetailedResponse: """ Create a job. @@ -1232,9 +1272,11 @@ def create_job(self, headers = { 'Content-Type': content_type, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_job') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_job', + ) headers.update(sdk_headers) params = { @@ -1278,16 +1320,21 @@ def create_job(self, headers['Accept'] = 'application/json' url = '/v1/recognitions' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def check_jobs(self, **kwargs) -> DetailedResponse: + def check_jobs( + self, + **kwargs, + ) -> DetailedResponse: """ Check jobs. @@ -1308,9 +1355,11 @@ def check_jobs(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='check_jobs') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='check_jobs', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1319,12 +1368,20 @@ def check_jobs(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/recognitions' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def check_job(self, id: str, **kwargs) -> DetailedResponse: + def check_job( + self, + id: str, + **kwargs, + ) -> DetailedResponse: """ Check a job. @@ -1352,9 +1409,11 @@ def check_job(self, id: str, **kwargs) -> DetailedResponse: if not id: raise ValueError('id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='check_job') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='check_job', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1366,12 +1425,20 @@ def check_job(self, id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/recognitions/{id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_job(self, id: str, **kwargs) -> DetailedResponse: + def delete_job( + self, + id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a job. @@ -1394,9 +1461,11 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: if not id: raise ValueError('id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_job') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_job', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1407,9 +1476,11 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/recognitions/{id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1418,13 +1489,15 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: # Custom language models ######################### - def create_language_model(self, - name: str, - base_model_name: str, - *, - dialect: str = None, - description: str = None, - **kwargs) -> DetailedResponse: + def create_language_model( + self, + name: str, + base_model_name: str, + *, + dialect: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create a custom language model. @@ -1493,9 +1566,11 @@ def create_language_model(self, if base_model_name is None: raise ValueError('base_model_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_language_model', + ) headers.update(sdk_headers) data = { @@ -1514,18 +1589,22 @@ def create_language_model(self, headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_language_models(self, - *, - language: str = None, - **kwargs) -> DetailedResponse: + def list_language_models( + self, + *, + language: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom language models. @@ -1555,9 +1634,11 @@ def list_language_models(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_language_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_language_models', + ) headers.update(sdk_headers) params = { @@ -1570,16 +1651,21 @@ def list_language_models(self, headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def get_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom language model. @@ -1603,9 +1689,11 @@ def get_language_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1617,13 +1705,20 @@ def get_language_model(self, customization_id: str, path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def delete_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom language model. @@ -1649,9 +1744,11 @@ def delete_language_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1663,20 +1760,24 @@ def delete_language_model(self, customization_id: str, path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def train_language_model(self, - customization_id: str, - *, - word_type_to_add: str = None, - customization_weight: float = None, - strict: bool = None, - **kwargs) -> DetailedResponse: + def train_language_model( + self, + customization_id: str, + *, + word_type_to_add: Optional[str] = None, + customization_weight: Optional[float] = None, + strict: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Train a custom language model. @@ -1770,9 +1871,11 @@ def train_language_model(self, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='train_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='train_language_model', + ) headers.update(sdk_headers) params = { @@ -1791,16 +1894,21 @@ def train_language_model(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/train'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def reset_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def reset_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Reset a custom language model. @@ -1828,9 +1936,11 @@ def reset_language_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='reset_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='reset_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1843,13 +1953,20 @@ def reset_language_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/reset'.format( **path_param_dict) - request = self.prepare_request(method='POST', url=url, headers=headers) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def upgrade_language_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def upgrade_language_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Upgrade a custom language model. @@ -1892,9 +2009,11 @@ def upgrade_language_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='upgrade_language_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='upgrade_language_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1907,7 +2026,11 @@ def upgrade_language_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/upgrade_model'.format( **path_param_dict) - request = self.prepare_request(method='POST', url=url, headers=headers) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1916,7 +2039,11 @@ def upgrade_language_model(self, customization_id: str, # Custom corpora ######################### - def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: + def list_corpora( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List corpora. @@ -1940,9 +2067,11 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_corpora') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_corpora', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1955,18 +2084,24 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_corpus(self, - customization_id: str, - corpus_name: str, - corpus_file: BinaryIO, - *, - allow_overwrite: bool = None, - **kwargs) -> DetailedResponse: + def add_corpus( + self, + customization_id: str, + corpus_name: str, + corpus_file: BinaryIO, + *, + allow_overwrite: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add a corpus. @@ -2067,9 +2202,11 @@ def add_corpus(self, if corpus_file is None: raise ValueError('corpus_file must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_corpus') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_corpus', + ) headers.update(sdk_headers) params = { @@ -2089,17 +2226,23 @@ def add_corpus(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_corpus(self, customization_id: str, corpus_name: str, - **kwargs) -> DetailedResponse: + def get_corpus( + self, + customization_id: str, + corpus_name: str, + **kwargs, + ) -> DetailedResponse: """ Get a corpus. @@ -2127,9 +2270,11 @@ def get_corpus(self, customization_id: str, corpus_name: str, if not corpus_name: raise ValueError('corpus_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_corpus') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_corpus', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2142,13 +2287,21 @@ def get_corpus(self, customization_id: str, corpus_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_corpus(self, customization_id: str, corpus_name: str, - **kwargs) -> DetailedResponse: + def delete_corpus( + self, + customization_id: str, + corpus_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete a corpus. @@ -2180,9 +2333,11 @@ def delete_corpus(self, customization_id: str, corpus_name: str, if not corpus_name: raise ValueError('corpus_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_corpus') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_corpus', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2195,9 +2350,11 @@ def delete_corpus(self, customization_id: str, corpus_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/corpora/{corpus_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -2206,12 +2363,14 @@ def delete_corpus(self, customization_id: str, corpus_name: str, # Custom words ######################### - def list_words(self, - customization_id: str, - *, - word_type: str = None, - sort: str = None, - **kwargs) -> DetailedResponse: + def list_words( + self, + customization_id: str, + *, + word_type: Optional[str] = None, + sort: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom words. @@ -2260,9 +2419,11 @@ def list_words(self, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_words', + ) headers.update(sdk_headers) params = { @@ -2280,16 +2441,22 @@ def list_words(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def add_words(self, customization_id: str, words: List['CustomWord'], - **kwargs) -> DetailedResponse: + def add_words( + self, + customization_id: str, + words: List['CustomWord'], + **kwargs, + ) -> DetailedResponse: """ Add custom words. @@ -2373,9 +2540,11 @@ def add_words(self, customization_id: str, words: List['CustomWord'], raise ValueError('words must be provided') words = [convert_model(x) for x in words] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_words', + ) headers.update(sdk_headers) data = { @@ -2395,22 +2564,26 @@ def add_words(self, customization_id: str, words: List['CustomWord'], path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def add_word(self, - customization_id: str, - word_name: str, - *, - word: str = None, - sounds_like: List[str] = None, - display_as: str = None, - **kwargs) -> DetailedResponse: + def add_word( + self, + customization_id: str, + word_name: str, + *, + word: Optional[str] = None, + sounds_like: Optional[List[str]] = None, + display_as: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Add a custom word. @@ -2505,9 +2678,11 @@ def add_word(self, if not word_name: raise ValueError('word_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_word', + ) headers.update(sdk_headers) data = { @@ -2529,16 +2704,22 @@ def add_word(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word_name}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def get_word(self, customization_id: str, word_name: str, - **kwargs) -> DetailedResponse: + def get_word( + self, + customization_id: str, + word_name: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom word. @@ -2566,9 +2747,11 @@ def get_word(self, customization_id: str, word_name: str, if not word_name: raise ValueError('word_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2581,13 +2764,21 @@ def get_word(self, customization_id: str, word_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_word(self, customization_id: str, word_name: str, - **kwargs) -> DetailedResponse: + def delete_word( + self, + customization_id: str, + word_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom word. @@ -2619,9 +2810,11 @@ def delete_word(self, customization_id: str, word_name: str, if not word_name: raise ValueError('word_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2634,9 +2827,11 @@ def delete_word(self, customization_id: str, word_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -2645,8 +2840,11 @@ def delete_word(self, customization_id: str, word_name: str, # Custom grammars ######################### - def list_grammars(self, customization_id: str, - **kwargs) -> DetailedResponse: + def list_grammars( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List grammars. @@ -2673,9 +2871,11 @@ def list_grammars(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_grammars') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_grammars', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2688,19 +2888,25 @@ def list_grammars(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_grammar(self, - customization_id: str, - grammar_name: str, - grammar_file: BinaryIO, - content_type: str, - *, - allow_overwrite: bool = None, - **kwargs) -> DetailedResponse: + def add_grammar( + self, + customization_id: str, + grammar_name: str, + grammar_file: BinaryIO, + content_type: str, + *, + allow_overwrite: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add a grammar. @@ -2797,9 +3003,11 @@ def add_grammar(self, headers = { 'Content-Type': content_type, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_grammar') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_grammar', + ) headers.update(sdk_headers) params = { @@ -2819,17 +3027,23 @@ def add_grammar(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_grammar(self, customization_id: str, grammar_name: str, - **kwargs) -> DetailedResponse: + def get_grammar( + self, + customization_id: str, + grammar_name: str, + **kwargs, + ) -> DetailedResponse: """ Get a grammar. @@ -2860,9 +3074,11 @@ def get_grammar(self, customization_id: str, grammar_name: str, if not grammar_name: raise ValueError('grammar_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_grammar') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_grammar', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2876,13 +3092,21 @@ def get_grammar(self, customization_id: str, grammar_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_grammar(self, customization_id: str, grammar_name: str, - **kwargs) -> DetailedResponse: + def delete_grammar( + self, + customization_id: str, + grammar_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete a grammar. @@ -2917,9 +3141,11 @@ def delete_grammar(self, customization_id: str, grammar_name: str, if not grammar_name: raise ValueError('grammar_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_grammar') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_grammar', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -2933,9 +3159,11 @@ def delete_grammar(self, customization_id: str, grammar_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/grammars/{grammar_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -2944,12 +3172,14 @@ def delete_grammar(self, customization_id: str, grammar_name: str, # Custom acoustic models ######################### - def create_acoustic_model(self, - name: str, - base_model_name: str, - *, - description: str = None, - **kwargs) -> DetailedResponse: + def create_acoustic_model( + self, + name: str, + base_model_name: str, + *, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create a custom acoustic model. @@ -2999,9 +3229,11 @@ def create_acoustic_model(self, if base_model_name is None: raise ValueError('base_model_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_acoustic_model', + ) headers.update(sdk_headers) data = { @@ -3019,18 +3251,22 @@ def create_acoustic_model(self, headers['Accept'] = 'application/json' url = '/v1/acoustic_customizations' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_acoustic_models(self, - *, - language: str = None, - **kwargs) -> DetailedResponse: + def list_acoustic_models( + self, + *, + language: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom acoustic models. @@ -3059,9 +3295,11 @@ def list_acoustic_models(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_acoustic_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_acoustic_models', + ) headers.update(sdk_headers) params = { @@ -3074,16 +3312,21 @@ def list_acoustic_models(self, headers['Accept'] = 'application/json' url = '/v1/acoustic_customizations' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def get_acoustic_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def get_acoustic_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom acoustic model. @@ -3106,9 +3349,11 @@ def get_acoustic_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_acoustic_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3121,13 +3366,20 @@ def get_acoustic_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_acoustic_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def delete_acoustic_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom acoustic model. @@ -3152,9 +3404,11 @@ def delete_acoustic_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_acoustic_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3167,19 +3421,23 @@ def delete_acoustic_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def train_acoustic_model(self, - customization_id: str, - *, - custom_language_model_id: str = None, - strict: bool = None, - **kwargs) -> DetailedResponse: + def train_acoustic_model( + self, + customization_id: str, + *, + custom_language_model_id: Optional[str] = None, + strict: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Train a custom acoustic model. @@ -3269,9 +3527,11 @@ def train_acoustic_model(self, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='train_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='train_acoustic_model', + ) headers.update(sdk_headers) params = { @@ -3289,16 +3549,21 @@ def train_acoustic_model(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/train'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def reset_acoustic_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def reset_acoustic_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Reset a custom acoustic model. @@ -3327,9 +3592,11 @@ def reset_acoustic_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='reset_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='reset_acoustic_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3342,17 +3609,23 @@ def reset_acoustic_model(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/reset'.format( **path_param_dict) - request = self.prepare_request(method='POST', url=url, headers=headers) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def upgrade_acoustic_model(self, - customization_id: str, - *, - custom_language_model_id: str = None, - force: bool = None, - **kwargs) -> DetailedResponse: + def upgrade_acoustic_model( + self, + customization_id: str, + *, + custom_language_model_id: Optional[str] = None, + force: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Upgrade a custom acoustic model. @@ -3408,9 +3681,11 @@ def upgrade_acoustic_model(self, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='upgrade_acoustic_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='upgrade_acoustic_model', + ) headers.update(sdk_headers) params = { @@ -3428,10 +3703,12 @@ def upgrade_acoustic_model(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/upgrade_model'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3440,7 +3717,11 @@ def upgrade_acoustic_model(self, # Custom audio resources ######################### - def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: + def list_audio( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List audio resources. @@ -3467,9 +3748,11 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_audio', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3482,20 +3765,26 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_audio(self, - customization_id: str, - audio_name: str, - audio_resource: BinaryIO, - *, - content_type: str = None, - contained_content_type: str = None, - allow_overwrite: bool = None, - **kwargs) -> DetailedResponse: + def add_audio( + self, + customization_id: str, + audio_name: str, + audio_resource: BinaryIO, + *, + content_type: Optional[str] = None, + contained_content_type: Optional[str] = None, + allow_overwrite: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ Add an audio resource. @@ -3649,9 +3938,11 @@ def add_audio(self, 'Content-Type': content_type, 'Contained-Content-Type': contained_content_type, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_audio', + ) headers.update(sdk_headers) params = { @@ -3670,17 +3961,23 @@ def add_audio(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_audio(self, customization_id: str, audio_name: str, - **kwargs) -> DetailedResponse: + def get_audio( + self, + customization_id: str, + audio_name: str, + **kwargs, + ) -> DetailedResponse: """ Get an audio resource. @@ -3723,9 +4020,11 @@ def get_audio(self, customization_id: str, audio_name: str, if not audio_name: raise ValueError('audio_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_audio', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3738,13 +4037,21 @@ def get_audio(self, customization_id: str, audio_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_audio(self, customization_id: str, audio_name: str, - **kwargs) -> DetailedResponse: + def delete_audio( + self, + customization_id: str, + audio_name: str, + **kwargs, + ) -> DetailedResponse: """ Delete an audio resource. @@ -3778,9 +4085,11 @@ def delete_audio(self, customization_id: str, audio_name: str, if not audio_name: raise ValueError('audio_name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_audio') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_audio', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -3793,9 +4102,11 @@ def delete_audio(self, customization_id: str, audio_name: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/acoustic_customizations/{customization_id}/audio/{audio_name}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -3804,7 +4115,11 @@ def delete_audio(self, customization_id: str, audio_name: str, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -3833,9 +4148,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -3847,10 +4164,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: del kwargs['headers'] url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -3866,6 +4185,7 @@ class ModelId(str, Enum): The identifier of the model in the form of its name from the output of the [List models](#listmodels) method. """ + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -3949,6 +4269,7 @@ class ContentType(str, Enum): The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. """ + APPLICATION_OCTET_STREAM = 'application/octet-stream' AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' @@ -3979,6 +4300,7 @@ class Model(str, Enum): * [Using the default model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -4062,6 +4384,7 @@ class ContentType(str, Enum): The format (MIME type) of the audio. For more information about specifying an audio format, see **Audio formats (content types)** in the method description. """ + APPLICATION_OCTET_STREAM = 'application/octet-stream' AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' @@ -4092,6 +4415,7 @@ class Model(str, Enum): * [Using the default model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). """ + AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' @@ -4184,6 +4508,7 @@ class Events(str, Enum): `recognitions.failed`. If the job does not include a callback URL, omit the parameter. """ + RECOGNITIONS_STARTED = 'recognitions.started' RECOGNITIONS_COMPLETED = 'recognitions.completed' RECOGNITIONS_COMPLETED_WITH_RESULTS = 'recognitions.completed_with_results' @@ -4206,6 +4531,7 @@ class Language(str, Enum): support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ + AR_MS = 'ar-MS' CS_CZ = 'cs-CZ' DE_DE = 'de-DE' @@ -4253,6 +4579,7 @@ class WordTypeToAdd(str, Enum): the parameter. The words resource contains only custom words that the user adds or modifies directly, so the parameter is unnecessary. """ + ALL = 'all' USER = 'user' @@ -4273,6 +4600,7 @@ class WordType(str, Enum): `user` apply. Both options return the same results. Words from other sources are not added to custom models that are based on next-generation models. """ + ALL = 'all' USER = 'user' CORPORA = 'corpora' @@ -4288,6 +4616,7 @@ class Sort(str, Enum): letters. For count ordering, values with the same count are ordered alphabetically. With the `curl` command, URL-encode the `+` symbol as `%2B`. """ + ALPHABETICAL = 'alphabetical' COUNT = 'count' @@ -4305,6 +4634,7 @@ class ContentType(str, Enum): * `application/srgs+xml` for XML Form, which uses XML elements to represent the grammar. """ + APPLICATION_SRGS = 'application/srgs' APPLICATION_SRGS_XML = 'application/srgs+xml' @@ -4325,6 +4655,7 @@ class Language(str, Enum): support for customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ + AR_MS = 'ar-MS' CS_CZ = 'cs-CZ' DE_DE = 'de-DE' @@ -4367,6 +4698,7 @@ class ContentType(str, Enum): information, see **Content types for archive-type resources** in the method description. """ + APPLICATION_ZIP = 'application/zip' APPLICATION_GZIP = 'application/gzip' AUDIO_ALAW = 'audio/alaw' @@ -4400,6 +4732,7 @@ class ContainedContentType(str, Enum): resources** in the method description. _For an audio-type resource_, omit the header. """ + AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' AUDIO_FLAC = 'audio/flac' @@ -4422,35 +4755,35 @@ class ContainedContentType(str, Enum): ############################################################################## -class AcousticModel(): +class AcousticModel: """ Information about an existing custom acoustic model. - :attr str customization_id: The customization ID (GUID) of the custom acoustic + :param str customization_id: The customization ID (GUID) of the custom acoustic model. The [Create a custom acoustic model](#createacousticmodel) method returns only this field of the object; it does not return the other fields. - :attr str created: (optional) The date and time in Coordinated Universal Time + :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom acoustic model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time + :param str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom acoustic model was last modified. The `created` and `updated` fields are equal when an acoustic model is first added but has yet to be updated. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - :attr str language: (optional) The language identifier of the custom acoustic + :param str language: (optional) The language identifier of the custom acoustic model (for example, `en-US`). - :attr List[str] versions: (optional) A list of the available versions of the + :param List[str] versions: (optional) A list of the available versions of the custom acoustic model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded to a new version of its base model. Otherwise, only a single version is shown. - :attr str owner: (optional) The GUID of the credentials for the instance of the + :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom acoustic model. - :attr str name: (optional) The name of the custom acoustic model. - :attr str description: (optional) The description of the custom acoustic model. - :attr str base_model_name: (optional) The name of the language model for which + :param str name: (optional) The name of the custom acoustic model. + :param str description: (optional) The description of the custom acoustic model. + :param str base_model_name: (optional) The name of the language model for which the custom acoustic model was created. - :attr str status: (optional) The current status of the custom acoustic model: + :param str status: (optional) The current status of the custom acoustic model: * `pending`: The model was created but is waiting either for valid training data to be added or for the service to finish analyzing added data. * `ready`: The model contains valid data and is ready to be trained. If the @@ -4460,31 +4793,33 @@ class AcousticModel(): * `available`: The model is trained and ready to use. * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. - :attr int progress: (optional) A percentage that indicates the progress of the + :param int progress: (optional) A percentage that indicates the progress of the custom acoustic model's current training. A value of `100` means that the model is fully trained. **Note:** The `progress` field does not currently reflect the progress of the training. The field changes from `0` to `100` when training is complete. - :attr str warnings: (optional) If the request included unknown parameters, the + :param str warnings: (optional) If the request included unknown parameters, the following message: `Unexpected query parameter(s) ['parameters'] detected`, where `parameters` is a list that includes a quoted string for each unknown parameter. """ - def __init__(self, - customization_id: str, - *, - created: str = None, - updated: str = None, - language: str = None, - versions: List[str] = None, - owner: str = None, - name: str = None, - description: str = None, - base_model_name: str = None, - status: str = None, - progress: int = None, - warnings: str = None) -> None: + def __init__( + self, + customization_id: str, + *, + created: Optional[str] = None, + updated: Optional[str] = None, + language: Optional[str] = None, + versions: Optional[List[str]] = None, + owner: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + base_model_name: Optional[str] = None, + status: Optional[str] = None, + progress: Optional[int] = None, + warnings: Optional[str] = None, + ) -> None: """ Initialize a AcousticModel object. @@ -4552,34 +4887,34 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AcousticModel': """Initialize a AcousticModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in AcousticModel JSON' ) - if 'created' in _dict: - args['created'] = _dict.get('created') - if 'updated' in _dict: - args['updated'] = _dict.get('updated') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'versions' in _dict: - args['versions'] = _dict.get('versions') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'base_model_name' in _dict: - args['base_model_name'] = _dict.get('base_model_name') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'progress' in _dict: - args['progress'] = _dict.get('progress') - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + if (created := _dict.get('created')) is not None: + args['created'] = created + if (updated := _dict.get('updated')) is not None: + args['updated'] = updated + if (language := _dict.get('language')) is not None: + args['language'] = language + if (versions := _dict.get('versions')) is not None: + args['versions'] = versions + if (owner := _dict.get('owner')) is not None: + args['owner'] = owner + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (base_model_name := _dict.get('base_model_name')) is not None: + args['base_model_name'] = base_model_name + if (status := _dict.get('status')) is not None: + args['status'] = status + if (progress := _dict.get('progress')) is not None: + args['progress'] = progress + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings return cls(**args) @classmethod @@ -4649,6 +4984,7 @@ class StatusEnum(str, Enum): * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. """ + PENDING = 'pending' READY = 'ready' TRAINING = 'training' @@ -4657,18 +4993,21 @@ class StatusEnum(str, Enum): FAILED = 'failed' -class AcousticModels(): +class AcousticModels: """ Information about existing custom acoustic models. - :attr List[AcousticModel] customizations: An array of `AcousticModel` objects + :param List[AcousticModel] customizations: An array of `AcousticModel` objects that provides information about each available custom acoustic model. The array is empty if the requesting credentials own no custom acoustic models (if no language is specified) or own no custom acoustic models for the specified language. """ - def __init__(self, customizations: List['AcousticModel']) -> None: + def __init__( + self, + customizations: List['AcousticModel'], + ) -> None: """ Initialize a AcousticModels object. @@ -4684,9 +5023,9 @@ def __init__(self, customizations: List['AcousticModel']) -> None: def from_dict(cls, _dict: Dict) -> 'AcousticModels': """Initialize a AcousticModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - AcousticModel.from_dict(v) for v in _dict.get('customizations') + AcousticModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -4731,35 +5070,37 @@ def __ne__(self, other: 'AcousticModels') -> bool: return not self == other -class AudioDetails(): +class AudioDetails: """ Information about an audio resource from a custom acoustic model. - :attr str type: (optional) The type of the audio resource: + :param str type: (optional) The type of the audio resource: * `audio` for an individual audio file * `archive` for an archive (**.zip** or **.tar.gz**) file that contains audio files * `undetermined` for a resource that the service cannot validate (for example, if the user mistakenly passes a file that does not contain audio, such as a JPEG file). - :attr str codec: (optional) _For an audio-type resource_, the codec in which the - audio is encoded. Omitted for an archive-type resource. - :attr int frequency: (optional) _For an audio-type resource_, the sampling rate + :param str codec: (optional) _For an audio-type resource_, the codec in which + the audio is encoded. Omitted for an archive-type resource. + :param int frequency: (optional) _For an audio-type resource_, the sampling rate of the audio in Hertz (samples per second). Omitted for an archive-type resource. - :attr str compression: (optional) _For an archive-type resource_, the format of + :param str compression: (optional) _For an archive-type resource_, the format of the compressed archive: * `zip` for a **.zip** file * `gzip` for a **.tar.gz** file Omitted for an audio-type resource. """ - def __init__(self, - *, - type: str = None, - codec: str = None, - frequency: int = None, - compression: str = None) -> None: + def __init__( + self, + *, + type: Optional[str] = None, + codec: Optional[str] = None, + frequency: Optional[int] = None, + compression: Optional[str] = None, + ) -> None: """ Initialize a AudioDetails object. @@ -4790,14 +5131,14 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioDetails': """Initialize a AudioDetails object from a json dictionary.""" args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'codec' in _dict: - args['codec'] = _dict.get('codec') - if 'frequency' in _dict: - args['frequency'] = _dict.get('frequency') - if 'compression' in _dict: - args['compression'] = _dict.get('compression') + if (type := _dict.get('type')) is not None: + args['type'] = type + if (codec := _dict.get('codec')) is not None: + args['codec'] = codec + if (frequency := _dict.get('frequency')) is not None: + args['frequency'] = frequency + if (compression := _dict.get('compression')) is not None: + args['compression'] = compression return cls(**args) @classmethod @@ -4846,6 +5187,7 @@ class TypeEnum(str, Enum): the user mistakenly passes a file that does not contain audio, such as a JPEG file). """ + AUDIO = 'audio' ARCHIVE = 'archive' UNDETERMINED = 'undetermined' @@ -4857,23 +5199,24 @@ class CompressionEnum(str, Enum): * `gzip` for a **.tar.gz** file Omitted for an audio-type resource. """ + ZIP = 'zip' GZIP = 'gzip' -class AudioListing(): +class AudioListing: """ Information about an audio resource from a custom acoustic model. - :attr int duration: (optional) _For an audio-type resource_, the total seconds + :param int duration: (optional) _For an audio-type resource_, the total seconds of audio in the resource. Omitted for an archive-type resource. - :attr str name: (optional) _For an audio-type resource_, the user-specified name - of the resource. Omitted for an archive-type resource. - :attr AudioDetails details: (optional) _For an audio-type resource_, an + :param str name: (optional) _For an audio-type resource_, the user-specified + name of the resource. Omitted for an archive-type resource. + :param AudioDetails details: (optional) _For an audio-type resource_, an `AudioDetails` object that provides detailed information about the resource. The object is empty until the service finishes processing the audio. Omitted for an archive-type resource. - :attr str status: (optional) _For an audio-type resource_, the status of the + :param str status: (optional) _For an audio-type resource_, the status of the resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. @@ -4883,23 +5226,25 @@ class AudioListing(): * `invalid`: The audio data is not valid for training the custom model (possibly because it has the wrong format or sampling rate, or because it is corrupted). Omitted for an archive-type resource. - :attr AudioResource container: (optional) _For an archive-type resource_, an + :param AudioResource container: (optional) _For an archive-type resource_, an object of type `AudioResource` that provides information about the resource. Omitted for an audio-type resource. - :attr List[AudioResource] audio: (optional) _For an archive-type resource_, an + :param List[AudioResource] audio: (optional) _For an archive-type resource_, an array of `AudioResource` objects that provides information about the audio-type resources that are contained in the resource. Omitted for an audio-type resource. """ - def __init__(self, - *, - duration: int = None, - name: str = None, - details: 'AudioDetails' = None, - status: str = None, - container: 'AudioResource' = None, - audio: List['AudioResource'] = None) -> None: + def __init__( + self, + *, + duration: Optional[int] = None, + name: Optional[str] = None, + details: Optional['AudioDetails'] = None, + status: Optional[str] = None, + container: Optional['AudioResource'] = None, + audio: Optional[List['AudioResource']] = None, + ) -> None: """ Initialize a AudioListing object. @@ -4941,20 +5286,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioListing': """Initialize a AudioListing object from a json dictionary.""" args = {} - if 'duration' in _dict: - args['duration'] = _dict.get('duration') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'details' in _dict: - args['details'] = AudioDetails.from_dict(_dict.get('details')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'container' in _dict: - args['container'] = AudioResource.from_dict(_dict.get('container')) - if 'audio' in _dict: - args['audio'] = [ - AudioResource.from_dict(v) for v in _dict.get('audio') - ] + if (duration := _dict.get('duration')) is not None: + args['duration'] = duration + if (name := _dict.get('name')) is not None: + args['name'] = name + if (details := _dict.get('details')) is not None: + args['details'] = AudioDetails.from_dict(details) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (container := _dict.get('container')) is not None: + args['container'] = AudioResource.from_dict(container) + if (audio := _dict.get('audio')) is not None: + args['audio'] = [AudioResource.from_dict(v) for v in audio] return cls(**args) @classmethod @@ -5021,27 +5364,31 @@ class StatusEnum(str, Enum): because it has the wrong format or sampling rate, or because it is corrupted). Omitted for an archive-type resource. """ + OK = 'ok' BEING_PROCESSED = 'being_processed' INVALID = 'invalid' -class AudioMetrics(): +class AudioMetrics: """ If audio metrics are requested, information about the signal characteristics of the input audio. - :attr float sampling_interval: The interval in seconds (typically 0.1 seconds) + :param float sampling_interval: The interval in seconds (typically 0.1 seconds) at which the service calculated the audio metrics. In other words, how often the service calculated the metrics. A single unit in each histogram (see the `AudioMetricsHistogramBin` object) is calculated based on a `sampling_interval` length of audio. - :attr AudioMetricsDetails accumulated: Detailed information about the signal + :param AudioMetricsDetails accumulated: Detailed information about the signal characteristics of the input audio. """ - def __init__(self, sampling_interval: float, - accumulated: 'AudioMetricsDetails') -> None: + def __init__( + self, + sampling_interval: float, + accumulated: 'AudioMetricsDetails', + ) -> None: """ Initialize a AudioMetrics object. @@ -5060,15 +5407,14 @@ def __init__(self, sampling_interval: float, def from_dict(cls, _dict: Dict) -> 'AudioMetrics': """Initialize a AudioMetrics object from a json dictionary.""" args = {} - if 'sampling_interval' in _dict: - args['sampling_interval'] = _dict.get('sampling_interval') + if (sampling_interval := _dict.get('sampling_interval')) is not None: + args['sampling_interval'] = sampling_interval else: raise ValueError( 'Required property \'sampling_interval\' not present in AudioMetrics JSON' ) - if 'accumulated' in _dict: - args['accumulated'] = AudioMetricsDetails.from_dict( - _dict.get('accumulated')) + if (accumulated := _dict.get('accumulated')) is not None: + args['accumulated'] = AudioMetricsDetails.from_dict(accumulated) else: raise ValueError( 'Required property \'accumulated\' not present in AudioMetrics JSON' @@ -5112,23 +5458,23 @@ def __ne__(self, other: 'AudioMetrics') -> bool: return not self == other -class AudioMetricsDetails(): +class AudioMetricsDetails: """ Detailed information about the signal characteristics of the input audio. - :attr bool final: If `true`, indicates the end of the audio stream, meaning that - transcription is complete. Currently, the field is always `true`. The service - returns metrics just once per audio stream. The results provide aggregated audio - metrics that pertain to the complete audio stream. - :attr float end_time: The end time in seconds of the block of audio to which the - metrics apply. - :attr float signal_to_noise_ratio: (optional) The signal-to-noise ratio (SNR) + :param bool final: If `true`, indicates the end of the audio stream, meaning + that transcription is complete. Currently, the field is always `true`. The + service returns metrics just once per audio stream. The results provide + aggregated audio metrics that pertain to the complete audio stream. + :param float end_time: The end time in seconds of the block of audio to which + the metrics apply. + :param float signal_to_noise_ratio: (optional) The signal-to-noise ratio (SNR) for the audio signal. The value indicates the ratio of speech to noise in the audio. A valid value lies in the range of 0 to 100 decibels (dB). The service omits the field if it cannot compute the SNR for the audio. - :attr float speech_ratio: The ratio of speech to non-speech segments in the + :param float speech_ratio: The ratio of speech to non-speech segments in the audio signal. The value lies in the range of 0.0 to 1.0. - :attr float high_frequency_loss: The probability that the audio signal is + :param float high_frequency_loss: The probability that the audio signal is missing the upper half of its frequency content. * A value close to 1.0 typically indicates artificially up-sampled audio, which negatively impacts the accuracy of the transcription results. @@ -5136,10 +5482,10 @@ class AudioMetricsDetails(): spectrum. * A value around 0.5 means that detection of the frequency content is unreliable or not available. - :attr List[AudioMetricsHistogramBin] direct_current_offset: An array of + :param List[AudioMetricsHistogramBin] direct_current_offset: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the cumulative direct current (DC) component of the audio signal. - :attr List[AudioMetricsHistogramBin] clipping_rate: An array of + :param List[AudioMetricsHistogramBin] clipping_rate: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the clipping rate for the audio segments. The clipping rate is defined as the fraction of samples in the segment that reach the maximum or minimum value that is offered by the @@ -5147,29 +5493,31 @@ class AudioMetricsDetails(): Modulation(PCM) audio range (-32768 to +32767) or a unit range (-1.0 to +1.0). The clipping rate is between 0.0 and 1.0, with higher values indicating possible degradation of speech recognition. - :attr List[AudioMetricsHistogramBin] speech_level: An array of + :param List[AudioMetricsHistogramBin] speech_level: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in segments of the audio that contain speech. The signal level is computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range 0.0 (minimum level) to 1.0 (maximum level). - :attr List[AudioMetricsHistogramBin] non_speech_level: An array of + :param List[AudioMetricsHistogramBin] non_speech_level: An array of `AudioMetricsHistogramBin` objects that defines a histogram of the signal level in segments of the audio that do not contain speech. The signal level is computed as the Root-Mean-Square (RMS) value in a decibel (dB) scale normalized to the range 0.0 (minimum level) to 1.0 (maximum level). """ - def __init__(self, - final: bool, - end_time: float, - speech_ratio: float, - high_frequency_loss: float, - direct_current_offset: List['AudioMetricsHistogramBin'], - clipping_rate: List['AudioMetricsHistogramBin'], - speech_level: List['AudioMetricsHistogramBin'], - non_speech_level: List['AudioMetricsHistogramBin'], - *, - signal_to_noise_ratio: float = None) -> None: + def __init__( + self, + final: bool, + end_time: float, + speech_ratio: float, + high_frequency_loss: float, + direct_current_offset: List['AudioMetricsHistogramBin'], + clipping_rate: List['AudioMetricsHistogramBin'], + speech_level: List['AudioMetricsHistogramBin'], + non_speech_level: List['AudioMetricsHistogramBin'], + *, + signal_to_noise_ratio: Optional[float] = None, + ) -> None: """ Initialize a AudioMetricsDetails object. @@ -5230,63 +5578,63 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'AudioMetricsDetails': """Initialize a AudioMetricsDetails object from a json dictionary.""" args = {} - if 'final' in _dict: - args['final'] = _dict.get('final') + if (final := _dict.get('final')) is not None: + args['final'] = final else: raise ValueError( 'Required property \'final\' not present in AudioMetricsDetails JSON' ) - if 'end_time' in _dict: - args['end_time'] = _dict.get('end_time') + if (end_time := _dict.get('end_time')) is not None: + args['end_time'] = end_time else: raise ValueError( 'Required property \'end_time\' not present in AudioMetricsDetails JSON' ) - if 'signal_to_noise_ratio' in _dict: - args['signal_to_noise_ratio'] = _dict.get('signal_to_noise_ratio') - if 'speech_ratio' in _dict: - args['speech_ratio'] = _dict.get('speech_ratio') + if (signal_to_noise_ratio := + _dict.get('signal_to_noise_ratio')) is not None: + args['signal_to_noise_ratio'] = signal_to_noise_ratio + if (speech_ratio := _dict.get('speech_ratio')) is not None: + args['speech_ratio'] = speech_ratio else: raise ValueError( 'Required property \'speech_ratio\' not present in AudioMetricsDetails JSON' ) - if 'high_frequency_loss' in _dict: - args['high_frequency_loss'] = _dict.get('high_frequency_loss') + if (high_frequency_loss := + _dict.get('high_frequency_loss')) is not None: + args['high_frequency_loss'] = high_frequency_loss else: raise ValueError( 'Required property \'high_frequency_loss\' not present in AudioMetricsDetails JSON' ) - if 'direct_current_offset' in _dict: + if (direct_current_offset := + _dict.get('direct_current_offset')) is not None: args['direct_current_offset'] = [ AudioMetricsHistogramBin.from_dict(v) - for v in _dict.get('direct_current_offset') + for v in direct_current_offset ] else: raise ValueError( 'Required property \'direct_current_offset\' not present in AudioMetricsDetails JSON' ) - if 'clipping_rate' in _dict: + if (clipping_rate := _dict.get('clipping_rate')) is not None: args['clipping_rate'] = [ - AudioMetricsHistogramBin.from_dict(v) - for v in _dict.get('clipping_rate') + AudioMetricsHistogramBin.from_dict(v) for v in clipping_rate ] else: raise ValueError( 'Required property \'clipping_rate\' not present in AudioMetricsDetails JSON' ) - if 'speech_level' in _dict: + if (speech_level := _dict.get('speech_level')) is not None: args['speech_level'] = [ - AudioMetricsHistogramBin.from_dict(v) - for v in _dict.get('speech_level') + AudioMetricsHistogramBin.from_dict(v) for v in speech_level ] else: raise ValueError( 'Required property \'speech_level\' not present in AudioMetricsDetails JSON' ) - if 'non_speech_level' in _dict: + if (non_speech_level := _dict.get('non_speech_level')) is not None: args['non_speech_level'] = [ - AudioMetricsHistogramBin.from_dict(v) - for v in _dict.get('non_speech_level') + AudioMetricsHistogramBin.from_dict(v) for v in non_speech_level ] else: raise ValueError( @@ -5370,19 +5718,24 @@ def __ne__(self, other: 'AudioMetricsDetails') -> bool: return not self == other -class AudioMetricsHistogramBin(): +class AudioMetricsHistogramBin: """ A bin with defined boundaries that indicates the number of values in a range of signal characteristics for a histogram. The first and last bins of a histogram are the boundary bins. They cover the intervals between negative infinity and the first boundary, and between the last boundary and positive infinity, respectively. - :attr float begin: The lower boundary of the bin in the histogram. - :attr float end: The upper boundary of the bin in the histogram. - :attr int count: The number of values in the bin of the histogram. + :param float begin: The lower boundary of the bin in the histogram. + :param float end: The upper boundary of the bin in the histogram. + :param int count: The number of values in the bin of the histogram. """ - def __init__(self, begin: float, end: float, count: int) -> None: + def __init__( + self, + begin: float, + end: float, + count: int, + ) -> None: """ Initialize a AudioMetricsHistogramBin object. @@ -5398,20 +5751,20 @@ def __init__(self, begin: float, end: float, count: int) -> None: def from_dict(cls, _dict: Dict) -> 'AudioMetricsHistogramBin': """Initialize a AudioMetricsHistogramBin object from a json dictionary.""" args = {} - if 'begin' in _dict: - args['begin'] = _dict.get('begin') + if (begin := _dict.get('begin')) is not None: + args['begin'] = begin else: raise ValueError( 'Required property \'begin\' not present in AudioMetricsHistogramBin JSON' ) - if 'end' in _dict: - args['end'] = _dict.get('end') + if (end := _dict.get('end')) is not None: + args['end'] = end else: raise ValueError( 'Required property \'end\' not present in AudioMetricsHistogramBin JSON' ) - if 'count' in _dict: - args['count'] = _dict.get('count') + if (count := _dict.get('count')) is not None: + args['count'] = count else: raise ValueError( 'Required property \'count\' not present in AudioMetricsHistogramBin JSON' @@ -5453,20 +5806,20 @@ def __ne__(self, other: 'AudioMetricsHistogramBin') -> bool: return not self == other -class AudioResource(): +class AudioResource: """ Information about an audio resource from a custom acoustic model. - :attr int duration: The total seconds of audio in the audio resource. - :attr str name: _For an archive-type resource_, the user-specified name of the + :param int duration: The total seconds of audio in the audio resource. + :param str name: _For an archive-type resource_, the user-specified name of the resource. _For an audio-type resource_, the user-specified name of the resource or the name of the audio file that the user added for the resource. The value depends on the method that is called. - :attr AudioDetails details: An `AudioDetails` object that provides detailed + :param AudioDetails details: An `AudioDetails` object that provides detailed information about the audio resource. The object is empty until the service finishes processing the audio. - :attr str status: The status of the audio resource: + :param str status: The status of the audio resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. * `being_processed`: The service is still analyzing the audio data. The service @@ -5478,8 +5831,13 @@ class AudioResource(): invalid. """ - def __init__(self, duration: int, name: str, details: 'AudioDetails', - status: str) -> None: + def __init__( + self, + duration: int, + name: str, + details: 'AudioDetails', + status: str, + ) -> None: """ Initialize a AudioResource object. @@ -5512,25 +5870,25 @@ def __init__(self, duration: int, name: str, details: 'AudioDetails', def from_dict(cls, _dict: Dict) -> 'AudioResource': """Initialize a AudioResource object from a json dictionary.""" args = {} - if 'duration' in _dict: - args['duration'] = _dict.get('duration') + if (duration := _dict.get('duration')) is not None: + args['duration'] = duration else: raise ValueError( 'Required property \'duration\' not present in AudioResource JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in AudioResource JSON') - if 'details' in _dict: - args['details'] = AudioDetails.from_dict(_dict.get('details')) + if (details := _dict.get('details')) is not None: + args['details'] = AudioDetails.from_dict(details) else: raise ValueError( 'Required property \'details\' not present in AudioResource JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in AudioResource JSON' @@ -5589,26 +5947,30 @@ class StatusEnum(str, Enum): an archive file, the entire archive is invalid if any of its audio files are invalid. """ + OK = 'ok' BEING_PROCESSED = 'being_processed' INVALID = 'invalid' -class AudioResources(): +class AudioResources: """ Information about the audio resources from a custom acoustic model. - :attr float total_minutes_of_audio: The total minutes of accumulated audio + :param float total_minutes_of_audio: The total minutes of accumulated audio summed over all of the valid audio resources for the custom acoustic model. You can use this value to determine whether the custom model has too little or too much audio to begin training. - :attr List[AudioResource] audio: An array of `AudioResource` objects that + :param List[AudioResource] audio: An array of `AudioResource` objects that provides information about the audio resources of the custom acoustic model. The array is empty if the custom model has no audio resources. """ - def __init__(self, total_minutes_of_audio: float, - audio: List['AudioResource']) -> None: + def __init__( + self, + total_minutes_of_audio: float, + audio: List['AudioResource'], + ) -> None: """ Initialize a AudioResources object. @@ -5627,16 +5989,15 @@ def __init__(self, total_minutes_of_audio: float, def from_dict(cls, _dict: Dict) -> 'AudioResources': """Initialize a AudioResources object from a json dictionary.""" args = {} - if 'total_minutes_of_audio' in _dict: - args['total_minutes_of_audio'] = _dict.get('total_minutes_of_audio') + if (total_minutes_of_audio := + _dict.get('total_minutes_of_audio')) is not None: + args['total_minutes_of_audio'] = total_minutes_of_audio else: raise ValueError( 'Required property \'total_minutes_of_audio\' not present in AudioResources JSON' ) - if 'audio' in _dict: - args['audio'] = [ - AudioResource.from_dict(v) for v in _dict.get('audio') - ] + if (audio := _dict.get('audio')) is not None: + args['audio'] = [AudioResource.from_dict(v) for v in audio] else: raise ValueError( 'Required property \'audio\' not present in AudioResources JSON' @@ -5683,16 +6044,19 @@ def __ne__(self, other: 'AudioResources') -> bool: return not self == other -class Corpora(): +class Corpora: """ Information about the corpora from a custom language model. - :attr List[Corpus] corpora: An array of `Corpus` objects that provides + :param List[Corpus] corpora: An array of `Corpus` objects that provides information about the corpora for the custom model. The array is empty if the custom model has no corpora. """ - def __init__(self, corpora: List['Corpus']) -> None: + def __init__( + self, + corpora: List['Corpus'], + ) -> None: """ Initialize a Corpora object. @@ -5706,10 +6070,8 @@ def __init__(self, corpora: List['Corpus']) -> None: def from_dict(cls, _dict: Dict) -> 'Corpora': """Initialize a Corpora object from a json dictionary.""" args = {} - if 'corpora' in _dict: - args['corpora'] = [ - Corpus.from_dict(v) for v in _dict.get('corpora') - ] + if (corpora := _dict.get('corpora')) is not None: + args['corpora'] = [Corpus.from_dict(v) for v in corpora] else: raise ValueError( 'Required property \'corpora\' not present in Corpora JSON') @@ -5752,37 +6114,39 @@ def __ne__(self, other: 'Corpora') -> bool: return not self == other -class Corpus(): +class Corpus: """ Information about a corpus from a custom language model. - :attr str name: The name of the corpus. - :attr int total_words: The total number of words in the corpus. The value is `0` - while the corpus is being processed. - :attr int out_of_vocabulary_words: _For custom models that are based on + :param str name: The name of the corpus. + :param int total_words: The total number of words in the corpus. The value is + `0` while the corpus is being processed. + :param int out_of_vocabulary_words: _For custom models that are based on previous-generation models_, the number of OOV words extracted from the corpus. The value is `0` while the corpus is being processed. _For custom models that are based on next-generation models_, no OOV words are extracted from corpora, so the value is always `0`. - :attr str status: The status of the corpus: + :param str status: The status of the corpus: * `analyzed`: The service successfully analyzed the corpus. The custom model can be trained with data from the corpus. * `being_processed`: The service is still analyzing the corpus. The service cannot accept requests to add new resources or to train the custom model. * `undetermined`: The service encountered an error while processing the corpus. The `error` field describes the failure. - :attr str error: (optional) If the status of the corpus is `undetermined`, the + :param str error: (optional) If the status of the corpus is `undetermined`, the following message: `Analysis of corpus 'name' failed. Please try adding the corpus again by setting the 'allow_overwrite' flag to 'true'`. """ - def __init__(self, - name: str, - total_words: int, - out_of_vocabulary_words: int, - status: str, - *, - error: str = None) -> None: + def __init__( + self, + name: str, + total_words: int, + out_of_vocabulary_words: int, + status: str, + *, + error: Optional[str] = None, + ) -> None: """ Initialize a Corpus object. @@ -5815,30 +6179,30 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Corpus': """Initialize a Corpus object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Corpus JSON') - if 'total_words' in _dict: - args['total_words'] = _dict.get('total_words') + if (total_words := _dict.get('total_words')) is not None: + args['total_words'] = total_words else: raise ValueError( 'Required property \'total_words\' not present in Corpus JSON') - if 'out_of_vocabulary_words' in _dict: - args['out_of_vocabulary_words'] = _dict.get( - 'out_of_vocabulary_words') + if (out_of_vocabulary_words := + _dict.get('out_of_vocabulary_words')) is not None: + args['out_of_vocabulary_words'] = out_of_vocabulary_words else: raise ValueError( 'Required property \'out_of_vocabulary_words\' not present in Corpus JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in Corpus JSON') - if 'error' in _dict: - args['error'] = _dict.get('error') + if (error := _dict.get('error')) is not None: + args['error'] = error return cls(**args) @classmethod @@ -5890,21 +6254,22 @@ class StatusEnum(str, Enum): * `undetermined`: The service encountered an error while processing the corpus. The `error` field describes the failure. """ + ANALYZED = 'analyzed' BEING_PROCESSED = 'being_processed' UNDETERMINED = 'undetermined' -class CustomWord(): +class CustomWord: """ Information about a word that is to be added to a custom language model. - :attr str word: (optional) For the [Add custom words](#addwords) method, you + :param str word: (optional) For the [Add custom words](#addwords) 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 `_` (underscore) to connect the tokens of compound words. Omit this parameter for the [Add a custom word](#addword) method. - :attr List[str] sounds_like: (optional) As array of sounds-like pronunciations + :param List[str] sounds_like: (optional) As array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. * _For custom models that are based on previous-generation models_, for a word @@ -5916,7 +6281,7 @@ class CustomWord(): the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. - :attr str display_as: (optional) An alternative spelling for the custom word + :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its spelling in corpora training data. @@ -5924,11 +6289,13 @@ class CustomWord(): the spelling of the word as the display-as value if you omit the field. """ - def __init__(self, - *, - word: str = None, - sounds_like: List[str] = None, - display_as: str = None) -> None: + def __init__( + self, + *, + word: Optional[str] = None, + sounds_like: Optional[List[str]] = None, + display_as: Optional[str] = None, + ) -> None: """ Initialize a CustomWord object. @@ -5966,12 +6333,12 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CustomWord': """Initialize a CustomWord object from a json dictionary.""" args = {} - if 'word' in _dict: - args['word'] = _dict.get('word') - if 'sounds_like' in _dict: - args['sounds_like'] = _dict.get('sounds_like') - if 'display_as' in _dict: - args['display_as'] = _dict.get('display_as') + if (word := _dict.get('word')) is not None: + args['word'] = word + if (sounds_like := _dict.get('sounds_like')) is not None: + args['sounds_like'] = sounds_like + if (display_as := _dict.get('display_as')) is not None: + args['display_as'] = display_as return cls(**args) @classmethod @@ -6009,35 +6376,37 @@ def __ne__(self, other: 'CustomWord') -> bool: return not self == other -class Grammar(): +class Grammar: """ Information about a grammar from a custom language model. - :attr str name: The name of the grammar. - :attr int out_of_vocabulary_words: _For custom models that are based on + :param str name: The name of the grammar. + :param int out_of_vocabulary_words: _For custom models that are based on previous-generation models_, the number of OOV words extracted from the grammar. The value is `0` while the grammar is being processed. _For custom models that are based on next-generation models_, no OOV words are extracted from grammars, so the value is always `0`. - :attr str status: The status of the grammar: + :param str status: The status of the grammar: * `analyzed`: The service successfully analyzed the grammar. The custom model can be trained with data from the grammar. * `being_processed`: The service is still analyzing the grammar. The service cannot accept requests to add new resources or to train the custom model. * `undetermined`: The service encountered an error while processing the grammar. The `error` field describes the failure. - :attr str error: (optional) If the status of the grammar is `undetermined`, the + :param str error: (optional) If the status of the grammar is `undetermined`, the following message: `Analysis of grammar '{grammar_name}' failed. Please try fixing the error or adding the grammar again by setting the 'allow_overwrite' flag to 'true'.`. """ - def __init__(self, - name: str, - out_of_vocabulary_words: int, - status: str, - *, - error: str = None) -> None: + def __init__( + self, + name: str, + out_of_vocabulary_words: int, + status: str, + *, + error: Optional[str] = None, + ) -> None: """ Initialize a Grammar object. @@ -6069,25 +6438,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Grammar': """Initialize a Grammar object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Grammar JSON') - if 'out_of_vocabulary_words' in _dict: - args['out_of_vocabulary_words'] = _dict.get( - 'out_of_vocabulary_words') + if (out_of_vocabulary_words := + _dict.get('out_of_vocabulary_words')) is not None: + args['out_of_vocabulary_words'] = out_of_vocabulary_words else: raise ValueError( 'Required property \'out_of_vocabulary_words\' not present in Grammar JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in Grammar JSON') - if 'error' in _dict: - args['error'] = _dict.get('error') + if (error := _dict.get('error')) is not None: + args['error'] = error return cls(**args) @classmethod @@ -6137,21 +6506,25 @@ class StatusEnum(str, Enum): * `undetermined`: The service encountered an error while processing the grammar. The `error` field describes the failure. """ + ANALYZED = 'analyzed' BEING_PROCESSED = 'being_processed' UNDETERMINED = 'undetermined' -class Grammars(): +class Grammars: """ Information about the grammars from a custom language model. - :attr List[Grammar] grammars: An array of `Grammar` objects that provides + :param List[Grammar] grammars: An array of `Grammar` objects that provides information about the grammars for the custom model. The array is empty if the custom model has no grammars. """ - def __init__(self, grammars: List['Grammar']) -> None: + def __init__( + self, + grammars: List['Grammar'], + ) -> None: """ Initialize a Grammars object. @@ -6165,10 +6538,8 @@ def __init__(self, grammars: List['Grammar']) -> None: def from_dict(cls, _dict: Dict) -> 'Grammars': """Initialize a Grammars object from a json dictionary.""" args = {} - if 'grammars' in _dict: - args['grammars'] = [ - Grammar.from_dict(v) for v in _dict.get('grammars') - ] + if (grammars := _dict.get('grammars')) is not None: + args['grammars'] = [Grammar.from_dict(v) for v in grammars] else: raise ValueError( 'Required property \'grammars\' not present in Grammars JSON') @@ -6211,20 +6582,25 @@ def __ne__(self, other: 'Grammars') -> bool: return not self == other -class KeywordResult(): +class KeywordResult: """ Information about a match for a keyword from speech recognition results. - :attr str normalized_text: A specified keyword normalized to the spoken phrase + :param str normalized_text: A specified keyword normalized to the spoken phrase that matched in the audio input. - :attr float start_time: The start time in seconds of the keyword match. - :attr float end_time: The end time in seconds of the keyword match. - :attr float confidence: A confidence score for the keyword match in the range of - 0.0 to 1.0. + :param float start_time: The start time in seconds of the keyword match. + :param float end_time: The end time in seconds of the keyword match. + :param float confidence: A confidence score for the keyword match in the range + of 0.0 to 1.0. """ - def __init__(self, normalized_text: str, start_time: float, end_time: float, - confidence: float) -> None: + def __init__( + self, + normalized_text: str, + start_time: float, + end_time: float, + confidence: float, + ) -> None: """ Initialize a KeywordResult object. @@ -6244,26 +6620,26 @@ def __init__(self, normalized_text: str, start_time: float, end_time: float, def from_dict(cls, _dict: Dict) -> 'KeywordResult': """Initialize a KeywordResult object from a json dictionary.""" args = {} - if 'normalized_text' in _dict: - args['normalized_text'] = _dict.get('normalized_text') + if (normalized_text := _dict.get('normalized_text')) is not None: + args['normalized_text'] = normalized_text else: raise ValueError( 'Required property \'normalized_text\' not present in KeywordResult JSON' ) - if 'start_time' in _dict: - args['start_time'] = _dict.get('start_time') + if (start_time := _dict.get('start_time')) is not None: + args['start_time'] = start_time else: raise ValueError( 'Required property \'start_time\' not present in KeywordResult JSON' ) - if 'end_time' in _dict: - args['end_time'] = _dict.get('end_time') + if (end_time := _dict.get('end_time')) is not None: + args['end_time'] = end_time else: raise ValueError( 'Required property \'end_time\' not present in KeywordResult JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in KeywordResult JSON' @@ -6308,26 +6684,26 @@ def __ne__(self, other: 'KeywordResult') -> bool: return not self == other -class LanguageModel(): +class LanguageModel: """ Information about an existing custom language model. - :attr str customization_id: The customization ID (GUID) of the custom language + :param str customization_id: The customization ID (GUID) of the custom language model. The [Create a custom language model](#createlanguagemodel) method returns only this field of the object; it does not return the other fields. - :attr str created: (optional) The date and time in Coordinated Universal Time + :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom language model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time + :param str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom language model was last modified. The `created` and `updated` fields are equal when a language model is first added but has yet to be updated. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). - :attr str language: (optional) The language identifier of the custom language + :param str language: (optional) The language identifier of the custom language model (for example, `en-US`). The value matches the five-character language identifier from the name of the base model for the custom model. This value might be different from the value of the `dialect` field. - :attr str dialect: (optional) The dialect of the language for the custom + :param str dialect: (optional) The dialect of the language for the custom language model. _For custom models that are based on non-Spanish previous-generation models and on next-generation models,_ the field matches the language of the base model; for example, `en-US` for one of the US English @@ -6340,18 +6716,18 @@ class LanguageModel(): models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) Dialect values are case-insensitive. - :attr List[str] versions: (optional) A list of the available versions of the + :param List[str] versions: (optional) A list of the available versions of the custom language model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if the custom model has been upgraded to a new version of its base model. Otherwise, only a single version is shown. - :attr str owner: (optional) The GUID of the credentials for the instance of the + :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom language model. - :attr str name: (optional) The name of the custom language model. - :attr str description: (optional) The description of the custom language model. - :attr str base_model_name: (optional) The name of the language model for which + :param str name: (optional) The name of the custom language model. + :param str description: (optional) The description of the custom language model. + :param str base_model_name: (optional) The name of the language model for which the custom language model was created. - :attr str status: (optional) The current status of the custom language model: + :param str status: (optional) The current status of the custom language model: * `pending`: The model was created but is waiting either for valid training data to be added or for the service to finish analyzing added data. * `ready`: The model contains valid data and is ready to be trained. If the @@ -6361,37 +6737,39 @@ class LanguageModel(): * `available`: The model is trained and ready to use. * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. - :attr int progress: (optional) A percentage that indicates the progress of the + :param int progress: (optional) A percentage that indicates the progress of the custom language model's current training. A value of `100` means that the model is fully trained. **Note:** The `progress` field does not currently reflect the progress of the training. The field changes from `0` to `100` when training is complete. - :attr str error: (optional) If an error occurred while adding a grammar file to + :param str error: (optional) If an error occurred while adding a grammar file to the custom language model, a message that describes an `Internal Server Error` and includes the string `Cannot compile grammar`. The status of the custom model is not affected by the error, but the grammar cannot be used with the model. - :attr str warnings: (optional) If the request included unknown parameters, the + :param str warnings: (optional) If the request included unknown parameters, the following message: `Unexpected query parameter(s) ['parameters'] detected`, where `parameters` is a list that includes a quoted string for each unknown parameter. """ - def __init__(self, - customization_id: str, - *, - created: str = None, - updated: str = None, - language: str = None, - dialect: str = None, - versions: List[str] = None, - owner: str = None, - name: str = None, - description: str = None, - base_model_name: str = None, - status: str = None, - progress: int = None, - error: str = None, - warnings: str = None) -> None: + def __init__( + self, + customization_id: str, + *, + created: Optional[str] = None, + updated: Optional[str] = None, + language: Optional[str] = None, + dialect: Optional[str] = None, + versions: Optional[List[str]] = None, + owner: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + base_model_name: Optional[str] = None, + status: Optional[str] = None, + progress: Optional[int] = None, + error: Optional[str] = None, + warnings: Optional[str] = None, + ) -> None: """ Initialize a LanguageModel object. @@ -6481,38 +6859,38 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'LanguageModel': """Initialize a LanguageModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in LanguageModel JSON' ) - if 'created' in _dict: - args['created'] = _dict.get('created') - if 'updated' in _dict: - args['updated'] = _dict.get('updated') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'dialect' in _dict: - args['dialect'] = _dict.get('dialect') - if 'versions' in _dict: - args['versions'] = _dict.get('versions') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'base_model_name' in _dict: - args['base_model_name'] = _dict.get('base_model_name') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'progress' in _dict: - args['progress'] = _dict.get('progress') - if 'error' in _dict: - args['error'] = _dict.get('error') - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + if (created := _dict.get('created')) is not None: + args['created'] = created + if (updated := _dict.get('updated')) is not None: + args['updated'] = updated + if (language := _dict.get('language')) is not None: + args['language'] = language + if (dialect := _dict.get('dialect')) is not None: + args['dialect'] = dialect + if (versions := _dict.get('versions')) is not None: + args['versions'] = versions + if (owner := _dict.get('owner')) is not None: + args['owner'] = owner + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (base_model_name := _dict.get('base_model_name')) is not None: + args['base_model_name'] = base_model_name + if (status := _dict.get('status')) is not None: + args['status'] = status + if (progress := _dict.get('progress')) is not None: + args['progress'] = progress + if (error := _dict.get('error')) is not None: + args['error'] = error + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings return cls(**args) @classmethod @@ -6586,6 +6964,7 @@ class StatusEnum(str, Enum): * `upgrading`: The model is currently being upgraded. * `failed`: Training of the model failed. """ + PENDING = 'pending' READY = 'ready' TRAINING = 'training' @@ -6594,18 +6973,21 @@ class StatusEnum(str, Enum): FAILED = 'failed' -class LanguageModels(): +class LanguageModels: """ Information about existing custom language models. - :attr List[LanguageModel] customizations: An array of `LanguageModel` objects + :param List[LanguageModel] customizations: An array of `LanguageModel` objects that provides information about each available custom language model. The array is empty if the requesting credentials own no custom language models (if no language is specified) or own no custom language models for the specified language. """ - def __init__(self, customizations: List['LanguageModel']) -> None: + def __init__( + self, + customizations: List['LanguageModel'], + ) -> None: """ Initialize a LanguageModels object. @@ -6621,9 +7003,9 @@ def __init__(self, customizations: List['LanguageModel']) -> None: def from_dict(cls, _dict: Dict) -> 'LanguageModels': """Initialize a LanguageModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - LanguageModel.from_dict(v) for v in _dict.get('customizations') + LanguageModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -6668,38 +7050,40 @@ def __ne__(self, other: 'LanguageModels') -> bool: return not self == other -class ProcessedAudio(): +class ProcessedAudio: """ Detailed timing information about the service's processing of the input audio. - :attr float received: The seconds of audio that the service has received as of + :param float received: The seconds of audio that the service has received as of this response. The value of the field is greater than the values of the `transcription` and `speaker_labels` fields during speech recognition processing, since the service first has to receive the audio before it can begin to process it. The final value can also be greater than the value of the `transcription` and `speaker_labels` fields by a fractional number of seconds. - :attr float seen_by_engine: The seconds of audio that the service has passed to + :param float seen_by_engine: The seconds of audio that the service has passed to its speech-processing engine as of this response. The value of the field is greater than the values of the `transcription` and `speaker_labels` fields during speech recognition processing. The `received` and `seen_by_engine` fields have identical values when the service has finished processing all audio. This final value can be greater than the value of the `transcription` and `speaker_labels` fields by a fractional number of seconds. - :attr float transcription: The seconds of audio that the service has processed + :param float transcription: The seconds of audio that the service has processed for speech recognition as of this response. - :attr float speaker_labels: (optional) If speaker labels are requested, the + :param float speaker_labels: (optional) If speaker labels are requested, the seconds of audio that the service has processed to determine speaker labels as of this response. This value often trails the value of the `transcription` field during speech recognition processing. The `transcription` and `speaker_labels` fields have identical values when the service has finished processing all audio. """ - def __init__(self, - received: float, - seen_by_engine: float, - transcription: float, - *, - speaker_labels: float = None) -> None: + def __init__( + self, + received: float, + seen_by_engine: float, + transcription: float, + *, + speaker_labels: Optional[float] = None, + ) -> None: """ Initialize a ProcessedAudio object. @@ -6736,26 +7120,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'ProcessedAudio': """Initialize a ProcessedAudio object from a json dictionary.""" args = {} - if 'received' in _dict: - args['received'] = _dict.get('received') + if (received := _dict.get('received')) is not None: + args['received'] = received else: raise ValueError( 'Required property \'received\' not present in ProcessedAudio JSON' ) - if 'seen_by_engine' in _dict: - args['seen_by_engine'] = _dict.get('seen_by_engine') + if (seen_by_engine := _dict.get('seen_by_engine')) is not None: + args['seen_by_engine'] = seen_by_engine else: raise ValueError( 'Required property \'seen_by_engine\' not present in ProcessedAudio JSON' ) - if 'transcription' in _dict: - args['transcription'] = _dict.get('transcription') + if (transcription := _dict.get('transcription')) is not None: + args['transcription'] = transcription else: raise ValueError( 'Required property \'transcription\' not present in ProcessedAudio JSON' ) - if 'speaker_labels' in _dict: - args['speaker_labels'] = _dict.get('speaker_labels') + if (speaker_labels := _dict.get('speaker_labels')) is not None: + args['speaker_labels'] = speaker_labels return cls(**args) @classmethod @@ -6795,15 +7179,15 @@ def __ne__(self, other: 'ProcessedAudio') -> bool: return not self == other -class ProcessingMetrics(): +class ProcessingMetrics: """ If processing metrics are requested, information about the service's processing of the input audio. Processing metrics are not available with the synchronous [Recognize audio](#recognize) method. - :attr ProcessedAudio processed_audio: Detailed timing information about the + :param ProcessedAudio processed_audio: Detailed timing information about the service's processing of the input audio. - :attr float wall_clock_since_first_byte_received: The amount of real time in + :param float wall_clock_since_first_byte_received: The amount of real time in seconds that has passed since the service received the first byte of input audio. Values in this field are generally multiples of the specified metrics interval, with two differences: @@ -6813,7 +7197,7 @@ class ProcessingMetrics(): * The service also returns values for transcription events if you set the `interim_results` parameter to `true`. The service returns both processing metrics and transcription results when such events occur. - :attr bool periodic: An indication of whether the metrics apply to a periodic + :param bool periodic: An indication of whether the metrics apply to a periodic interval or a transcription event: * `true` means that the response was triggered by a specified processing interval. The information contains processing metrics only. @@ -6823,9 +7207,12 @@ class ProcessingMetrics(): different results if necessary. """ - def __init__(self, processed_audio: 'ProcessedAudio', - wall_clock_since_first_byte_received: float, - periodic: bool) -> None: + def __init__( + self, + processed_audio: 'ProcessedAudio', + wall_clock_since_first_byte_received: float, + periodic: bool, + ) -> None: """ Initialize a ProcessingMetrics object. @@ -6858,22 +7245,22 @@ def __init__(self, processed_audio: 'ProcessedAudio', def from_dict(cls, _dict: Dict) -> 'ProcessingMetrics': """Initialize a ProcessingMetrics object from a json dictionary.""" args = {} - if 'processed_audio' in _dict: - args['processed_audio'] = ProcessedAudio.from_dict( - _dict.get('processed_audio')) + if (processed_audio := _dict.get('processed_audio')) is not None: + args['processed_audio'] = ProcessedAudio.from_dict(processed_audio) else: raise ValueError( 'Required property \'processed_audio\' not present in ProcessingMetrics JSON' ) - if 'wall_clock_since_first_byte_received' in _dict: - args['wall_clock_since_first_byte_received'] = _dict.get( - 'wall_clock_since_first_byte_received') + if (wall_clock_since_first_byte_received := + _dict.get('wall_clock_since_first_byte_received')) is not None: + args[ + 'wall_clock_since_first_byte_received'] = wall_clock_since_first_byte_received else: raise ValueError( 'Required property \'wall_clock_since_first_byte_received\' not present in ProcessingMetrics JSON' ) - if 'periodic' in _dict: - args['periodic'] = _dict.get('periodic') + if (periodic := _dict.get('periodic')) is not None: + args['periodic'] = periodic else: raise ValueError( 'Required property \'periodic\' not present in ProcessingMetrics JSON' @@ -6921,12 +7308,12 @@ def __ne__(self, other: 'ProcessingMetrics') -> bool: return not self == other -class RecognitionJob(): +class RecognitionJob: """ Information about a current asynchronous speech recognition job. - :attr str id: The ID of the asynchronous job. - :attr str status: The current status of the job: + :param str id: The ID of the asynchronous job. + :param str status: The current status of the job: * `waiting`: The service is preparing the job for processing. The service returns this status when the job is initially created or when it is waiting for capacity to process the job. The job remains in this state until the service has @@ -6937,24 +7324,24 @@ class RecognitionJob(): sent the results with the callback notification. Otherwise, you must retrieve the results by checking the individual job. * `failed`: The job failed. - :attr str created: The date and time in Coordinated Universal Time (UTC) at + :param str created: The date and time in Coordinated Universal Time (UTC) at which the job was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str updated: (optional) The date and time in Coordinated Universal Time + :param str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the job was last updated by the service. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). This field is returned only by the [Check jobs](#checkjobs) and [Check a job[(#checkjob) methods. - :attr str url: (optional) The URL to use to request information about the job + :param str url: (optional) The URL to use to request information about the job with the [Check a job](#checkjob) method. This field is returned only by the [Create a job](#createjob) method. - :attr str user_token: (optional) The user token associated with a job that was + :param str user_token: (optional) The user token associated with a job that was created with a callback URL and a user token. This field can be returned only by the [Check jobs](#checkjobs) method. - :attr List[SpeechRecognitionResults] results: (optional) If the status is + :param List[SpeechRecognitionResults] results: (optional) If the status is `completed`, the results of the recognition request as an array that includes a single instance of a `SpeechRecognitionResults` object. This field is returned only by the [Check a job](#checkjob) method. - :attr List[str] warnings: (optional) An array of warning messages about invalid + :param List[str] warnings: (optional) An array of warning messages about invalid parameters included with the request. Each warning includes a descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The @@ -6964,16 +7351,18 @@ class RecognitionJob(): parameter as `lambdaBias`.). """ - def __init__(self, - id: str, - status: str, - created: str, - *, - updated: str = None, - url: str = None, - user_token: str = None, - results: List['SpeechRecognitionResults'] = None, - warnings: List[str] = None) -> None: + def __init__( + self, + id: str, + status: str, + created: str, + *, + updated: Optional[str] = None, + url: Optional[str] = None, + user_token: Optional[str] = None, + results: Optional[List['SpeechRecognitionResults']] = None, + warnings: Optional[List[str]] = None, + ) -> None: """ Initialize a RecognitionJob object. @@ -7030,36 +7419,35 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'RecognitionJob': """Initialize a RecognitionJob object from a json dictionary.""" args = {} - if 'id' in _dict: - args['id'] = _dict.get('id') + if (id := _dict.get('id')) is not None: + args['id'] = id else: raise ValueError( 'Required property \'id\' not present in RecognitionJob JSON') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in RecognitionJob JSON' ) - if 'created' in _dict: - args['created'] = _dict.get('created') + if (created := _dict.get('created')) is not None: + args['created'] = created else: raise ValueError( 'Required property \'created\' not present in RecognitionJob JSON' ) - if 'updated' in _dict: - args['updated'] = _dict.get('updated') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'user_token' in _dict: - args['user_token'] = _dict.get('user_token') - if 'results' in _dict: + if (updated := _dict.get('updated')) is not None: + args['updated'] = updated + if (url := _dict.get('url')) is not None: + args['url'] = url + if (user_token := _dict.get('user_token')) is not None: + args['user_token'] = user_token + if (results := _dict.get('results')) is not None: args['results'] = [ - SpeechRecognitionResults.from_dict(v) - for v in _dict.get('results') + SpeechRecognitionResults.from_dict(v) for v in results ] - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings return cls(**args) @classmethod @@ -7126,22 +7514,26 @@ class StatusEnum(str, Enum): results by checking the individual job. * `failed`: The job failed. """ + WAITING = 'waiting' PROCESSING = 'processing' COMPLETED = 'completed' FAILED = 'failed' -class RecognitionJobs(): +class RecognitionJobs: """ Information about current asynchronous speech recognition jobs. - :attr List[RecognitionJob] recognitions: An array of `RecognitionJob` objects + :param List[RecognitionJob] recognitions: An array of `RecognitionJob` objects that provides the status for each of the user's current jobs. The array is empty if the user has no current jobs. """ - def __init__(self, recognitions: List['RecognitionJob']) -> None: + def __init__( + self, + recognitions: List['RecognitionJob'], + ) -> None: """ Initialize a RecognitionJobs object. @@ -7155,9 +7547,9 @@ def __init__(self, recognitions: List['RecognitionJob']) -> None: def from_dict(cls, _dict: Dict) -> 'RecognitionJobs': """Initialize a RecognitionJobs object from a json dictionary.""" args = {} - if 'recognitions' in _dict: + if (recognitions := _dict.get('recognitions')) is not None: args['recognitions'] = [ - RecognitionJob.from_dict(v) for v in _dict.get('recognitions') + RecognitionJob.from_dict(v) for v in recognitions ] else: raise ValueError( @@ -7202,19 +7594,23 @@ def __ne__(self, other: 'RecognitionJobs') -> bool: return not self == other -class RegisterStatus(): +class RegisterStatus: """ Information about a request to register a callback for asynchronous speech recognition. - :attr str status: The current status of the job: + :param str status: The current status of the job: * `created`: The service successfully allowlisted the callback URL as a result of the call. * `already created`: The URL was already allowlisted. - :attr str url: The callback URL that is successfully registered. + :param str url: The callback URL that is successfully registered. """ - def __init__(self, status: str, url: str) -> None: + def __init__( + self, + status: str, + url: str, + ) -> None: """ Initialize a RegisterStatus object. @@ -7231,14 +7627,14 @@ def __init__(self, status: str, url: str) -> None: def from_dict(cls, _dict: Dict) -> 'RegisterStatus': """Initialize a RegisterStatus object from a json dictionary.""" args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in RegisterStatus JSON' ) - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in RegisterStatus JSON') @@ -7283,33 +7679,41 @@ class StatusEnum(str, Enum): the call. * `already created`: The URL was already allowlisted. """ + CREATED = 'created' ALREADY_CREATED = 'already created' -class SpeakerLabelsResult(): +class SpeakerLabelsResult: """ Information about the speakers from speech recognition results. - :attr float from_: The start time of a word from the transcript. The value + :param float from_: The start time of a word from the transcript. The value matches the start time of a word from the `timestamps` array. - :attr float to: The end time of a word from the transcript. The value matches + :param float to: The end time of a word from the transcript. The value matches the end time of a word from the `timestamps` array. - :attr int speaker: The numeric identifier that the service assigns to a speaker + :param int speaker: The numeric identifier that the service assigns to a speaker from the audio. Speaker IDs begin at `0` initially but can evolve and change across interim results (if supported by the method) and between interim and final results as the service processes the audio. They are not guaranteed to be sequential, contiguous, or ordered. - :attr float confidence: A score that indicates the service's confidence in its + :param float confidence: A score that indicates the service's confidence in its identification of the speaker in the range of 0.0 to 1.0. - :attr bool final: An indication of whether the service might further change word - and speaker-label results. A value of `true` means that the service guarantees - not to send any further updates for the current or any preceding results; - `false` means that the service might send further updates to the results. + :param bool final: An indication of whether the service might further change + word and speaker-label results. A value of `true` means that the service + guarantees not to send any further updates for the current or any preceding + results; `false` means that the service might send further updates to the + results. """ - def __init__(self, from_: float, to: float, speaker: int, confidence: float, - final: bool) -> None: + def __init__( + self, + from_: float, + to: float, + speaker: int, + confidence: float, + final: bool, + ) -> None: """ Initialize a SpeakerLabelsResult object. @@ -7340,32 +7744,32 @@ def __init__(self, from_: float, to: float, speaker: int, confidence: float, def from_dict(cls, _dict: Dict) -> 'SpeakerLabelsResult': """Initialize a SpeakerLabelsResult object from a json dictionary.""" args = {} - if 'from' in _dict: - args['from_'] = _dict.get('from') + if (from_ := _dict.get('from')) is not None: + args['from_'] = from_ else: raise ValueError( 'Required property \'from\' not present in SpeakerLabelsResult JSON' ) - if 'to' in _dict: - args['to'] = _dict.get('to') + if (to := _dict.get('to')) is not None: + args['to'] = to else: raise ValueError( 'Required property \'to\' not present in SpeakerLabelsResult JSON' ) - if 'speaker' in _dict: - args['speaker'] = _dict.get('speaker') + if (speaker := _dict.get('speaker')) is not None: + args['speaker'] = speaker else: raise ValueError( 'Required property \'speaker\' not present in SpeakerLabelsResult JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in SpeakerLabelsResult JSON' ) - if 'final' in _dict: - args['final'] = _dict.get('final') + if (final := _dict.get('final')) is not None: + args['final'] = final else: raise ValueError( 'Required property \'final\' not present in SpeakerLabelsResult JSON' @@ -7411,24 +7815,31 @@ def __ne__(self, other: 'SpeakerLabelsResult') -> bool: return not self == other -class SpeechModel(): +class SpeechModel: """ Information about an available language model. - :attr str name: The name of the model for use as an identifier in calls to the + :param str name: The name of the model for use as an identifier in calls to the service (for example, `en-US_BroadbandModel`). - :attr str language: The language identifier of the model (for example, `en-US`). - :attr int rate: The sampling rate (minimum acceptable rate for audio) used by + :param str language: The language identifier of the model (for example, + `en-US`). + :param int rate: The sampling rate (minimum acceptable rate for audio) used by the model in Hertz. - :attr str url: The URI for the model. - :attr SupportedFeatures supported_features: Indicates whether select service + :param str url: The URI for the model. + :param SupportedFeatures supported_features: Indicates whether select service features are supported with the model. - :attr str description: A brief description of the model. + :param str description: A brief description of the model. """ - def __init__(self, name: str, language: str, rate: int, url: str, - supported_features: 'SupportedFeatures', - description: str) -> None: + def __init__( + self, + name: str, + language: str, + rate: int, + url: str, + supported_features: 'SupportedFeatures', + description: str, + ) -> None: """ Initialize a SpeechModel object. @@ -7454,36 +7865,36 @@ def __init__(self, name: str, language: str, rate: int, url: str, def from_dict(cls, _dict: Dict) -> 'SpeechModel': """Initialize a SpeechModel object from a json dictionary.""" args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in SpeechModel JSON') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in SpeechModel JSON' ) - if 'rate' in _dict: - args['rate'] = _dict.get('rate') + if (rate := _dict.get('rate')) is not None: + args['rate'] = rate else: raise ValueError( 'Required property \'rate\' not present in SpeechModel JSON') - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in SpeechModel JSON') - if 'supported_features' in _dict: + if (supported_features := _dict.get('supported_features')) is not None: args['supported_features'] = SupportedFeatures.from_dict( - _dict.get('supported_features')) + supported_features) else: raise ValueError( 'Required property \'supported_features\' not present in SpeechModel JSON' ) - if 'description' in _dict: - args['description'] = _dict.get('description') + if (description := _dict.get('description')) is not None: + args['description'] = description else: raise ValueError( 'Required property \'description\' not present in SpeechModel JSON' @@ -7536,15 +7947,18 @@ def __ne__(self, other: 'SpeechModel') -> bool: return not self == other -class SpeechModels(): +class SpeechModels: """ Information about the available language models. - :attr List[SpeechModel] models: An array of `SpeechModel` objects that provides + :param List[SpeechModel] models: An array of `SpeechModel` objects that provides information about each available model. """ - def __init__(self, models: List['SpeechModel']) -> None: + def __init__( + self, + models: List['SpeechModel'], + ) -> None: """ Initialize a SpeechModels object. @@ -7557,10 +7971,8 @@ def __init__(self, models: List['SpeechModel']) -> None: def from_dict(cls, _dict: Dict) -> 'SpeechModels': """Initialize a SpeechModels object from a json dictionary.""" args = {} - if 'models' in _dict: - args['models'] = [ - SpeechModel.from_dict(v) for v in _dict.get('models') - ] + if (models := _dict.get('models')) is not None: + args['models'] = [SpeechModel.from_dict(v) for v in models] else: raise ValueError( 'Required property \'models\' not present in SpeechModels JSON') @@ -7603,33 +8015,35 @@ def __ne__(self, other: 'SpeechModels') -> bool: return not self == other -class SpeechRecognitionAlternative(): +class SpeechRecognitionAlternative: """ An alternative transcript from speech recognition results. - :attr str transcript: A transcription of the audio. - :attr float confidence: (optional) A score that indicates the service's + :param str transcript: A transcription of the audio. + :param float confidence: (optional) A score that indicates the service's confidence in the transcript in the range of 0.0 to 1.0. The service returns a confidence score only for the best alternative and only with results marked as final. - :attr List[str] timestamps: (optional) Time alignments for each word from the + :param List[str] timestamps: (optional) Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds, for example: `[["hello",0.0,1.2],["world",1.2,2.5]]`. Timestamps are returned only for the best alternative. - :attr List[str] word_confidence: (optional) A confidence score for each word of + :param List[str] word_confidence: (optional) A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0.0 to 1.0, for example: `[["hello",0.95],["world",0.86]]`. Confidence scores are returned only for the best alternative and only with results marked as final. """ - def __init__(self, - transcript: str, - *, - confidence: float = None, - timestamps: List[str] = None, - word_confidence: List[str] = None) -> None: + def __init__( + self, + transcript: str, + *, + confidence: Optional[float] = None, + timestamps: Optional[List[str]] = None, + word_confidence: Optional[List[str]] = None, + ) -> None: """ Initialize a SpeechRecognitionAlternative object. @@ -7658,18 +8072,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionAlternative': """Initialize a SpeechRecognitionAlternative object from a json dictionary.""" args = {} - if 'transcript' in _dict: - args['transcript'] = _dict.get('transcript') + if (transcript := _dict.get('transcript')) is not None: + args['transcript'] = transcript else: raise ValueError( 'Required property \'transcript\' not present in SpeechRecognitionAlternative JSON' ) - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'timestamps' in _dict: - args['timestamps'] = _dict.get('timestamps') - if 'word_confidence' in _dict: - args['word_confidence'] = _dict.get('word_confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (timestamps := _dict.get('timestamps')) is not None: + args['timestamps'] = timestamps + if (word_confidence := _dict.get('word_confidence')) is not None: + args['word_confidence'] = word_confidence return cls(**args) @classmethod @@ -7710,31 +8124,31 @@ def __ne__(self, other: 'SpeechRecognitionAlternative') -> bool: return not self == other -class SpeechRecognitionResult(): +class SpeechRecognitionResult: """ Component results for a speech recognition request. - :attr bool final: An indication of whether the transcription results are final: + :param bool final: An indication of whether the transcription results are final: * If `true`, the results for this utterance are final. They are guaranteed not to be updated further. * If `false`, the results are interim. They can be updated with further interim results until final results are eventually sent. **Note:** Because `final` is a reserved word in Java and Swift, the field is renamed `xFinal` in Java and is escaped with back quotes in Swift. - :attr List[SpeechRecognitionAlternative] alternatives: An array of alternative + :param List[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. - :attr dict keywords_result: (optional) A dictionary (or associative array) whose - keys are the strings specified for `keywords` if both that parameter and + :param dict keywords_result: (optional) A dictionary (or associative array) + whose keys are the strings specified for `keywords` if both that parameter and `keywords_threshold` are specified. The value for each key is an array of matches spotted in the audio for that keyword. Each match is described by a `KeywordResult` object. A keyword for which no matches are found is omitted from the dictionary. The dictionary is omitted entirely if no matches are found for any keywords. - :attr List[WordAlternativeResults] word_alternatives: (optional) An array of + :param List[WordAlternativeResults] word_alternatives: (optional) An array of alternative hypotheses found for words of the input audio if a `word_alternatives_threshold` is specified. - :attr str end_of_utterance: (optional) If the `split_transcript_at_phrase_end` + :param str end_of_utterance: (optional) If the `split_transcript_at_phrase_end` parameter is `true`, describes the reason for the split: * `end_of_data` - The end of the input audio stream. * `full_stop` - A full semantic stop, such as for the conclusion of a @@ -7746,13 +8160,15 @@ class SpeechRecognitionResult(): * `silence` - A pause or silence that is at least as long as the pause interval. """ - def __init__(self, - final: bool, - alternatives: List['SpeechRecognitionAlternative'], - *, - keywords_result: dict = None, - word_alternatives: List['WordAlternativeResults'] = None, - end_of_utterance: str = None) -> None: + def __init__( + self, + final: bool, + alternatives: List['SpeechRecognitionAlternative'], + *, + keywords_result: Optional[dict] = None, + word_alternatives: Optional[List['WordAlternativeResults']] = None, + end_of_utterance: Optional[str] = None, + ) -> None: """ Initialize a SpeechRecognitionResult object. @@ -7800,30 +8216,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResult': """Initialize a SpeechRecognitionResult object from a json dictionary.""" args = {} - if 'final' in _dict: - args['final'] = _dict.get('final') + if (final := _dict.get('final')) is not None: + args['final'] = final else: raise ValueError( 'Required property \'final\' not present in SpeechRecognitionResult JSON' ) - if 'alternatives' in _dict: + if (alternatives := _dict.get('alternatives')) is not None: args['alternatives'] = [ - SpeechRecognitionAlternative.from_dict(v) - for v in _dict.get('alternatives') + SpeechRecognitionAlternative.from_dict(v) for v in alternatives ] else: raise ValueError( 'Required property \'alternatives\' not present in SpeechRecognitionResult JSON' ) - if 'keywords_result' in _dict: - args['keywords_result'] = _dict.get('keywords_result') - if 'word_alternatives' in _dict: + if (keywords_result := _dict.get('keywords_result')) is not None: + args['keywords_result'] = keywords_result + if (word_alternatives := _dict.get('word_alternatives')) is not None: args['word_alternatives'] = [ - WordAlternativeResults.from_dict(v) - for v in _dict.get('word_alternatives') + WordAlternativeResults.from_dict(v) for v in word_alternatives ] - if 'end_of_utterance' in _dict: - args['end_of_utterance'] = _dict.get('end_of_utterance') + if (end_of_utterance := _dict.get('end_of_utterance')) is not None: + args['end_of_utterance'] = end_of_utterance return cls(**args) @classmethod @@ -7892,17 +8306,18 @@ class EndOfUtteranceEnum(str, Enum): use. * `silence` - A pause or silence that is at least as long as the pause interval. """ + END_OF_DATA = 'end_of_data' FULL_STOP = 'full_stop' RESET = 'reset' SILENCE = 'silence' -class SpeechRecognitionResults(): +class SpeechRecognitionResults: """ The complete results for a speech recognition request. - :attr List[SpeechRecognitionResult] results: (optional) An array of + :param List[SpeechRecognitionResult] results: (optional) An array of `SpeechRecognitionResult` objects that can include interim and final results (interim results are returned only if supported by the method). Final results are guaranteed not to change; interim results might be replaced by further @@ -7913,24 +8328,24 @@ class SpeechRecognitionResults(): incremented to the lowest index in the array that has changed for new results. For more information, see [Understanding speech recognition results](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-basic-response). - :attr int result_index: (optional) An index that indicates a change point in the - `results` array. The service increments the index for additional results that it - sends for new audio for the same request. All results with the same index are - delivered at the same time. The same index can include multiple final results - that are delivered with the same response. - :attr List[SpeakerLabelsResult] speaker_labels: (optional) An array of + :param int result_index: (optional) An index that indicates a change point in + the `results` array. The service increments the index for additional results + that it sends for new audio for the same request. All results with the same + index are delivered at the same time. The same index can include multiple final + results that are delivered with the same response. + :param List[SpeakerLabelsResult] speaker_labels: (optional) An array of `SpeakerLabelsResult` objects that identifies which words were spoken by which speakers in a multi-person exchange. The array is returned only if the `speaker_labels` parameter is `true`. When interim results are also requested for methods that support them, it is possible for a `SpeechRecognitionResults` object to include only the `speaker_labels` field. - :attr ProcessingMetrics processing_metrics: (optional) If processing metrics are - requested, information about the service's processing of the input audio. + :param ProcessingMetrics processing_metrics: (optional) If processing metrics + are requested, information about the service's processing of the input audio. Processing metrics are not available with the synchronous [Recognize audio](#recognize) method. - :attr AudioMetrics audio_metrics: (optional) If audio metrics are requested, + :param AudioMetrics audio_metrics: (optional) If audio metrics are requested, information about the signal characteristics of the input audio. - :attr List[str] warnings: (optional) An array of warning messages associated + :param List[str] warnings: (optional) An array of warning messages associated with the request: * Warnings for invalid parameters or fields can include a descriptive message and a list of invalid argument strings, for example, `"Unknown arguments:"` or @@ -7948,14 +8363,16 @@ class SpeechRecognitionResults(): In both cases, the request succeeds despite the warnings. """ - def __init__(self, - *, - results: List['SpeechRecognitionResult'] = None, - result_index: int = None, - speaker_labels: List['SpeakerLabelsResult'] = None, - processing_metrics: 'ProcessingMetrics' = None, - audio_metrics: 'AudioMetrics' = None, - warnings: List[str] = None) -> None: + def __init__( + self, + *, + results: Optional[List['SpeechRecognitionResult']] = None, + result_index: Optional[int] = None, + speaker_labels: Optional[List['SpeakerLabelsResult']] = None, + processing_metrics: Optional['ProcessingMetrics'] = None, + audio_metrics: Optional['AudioMetrics'] = None, + warnings: Optional[List[str]] = None, + ) -> None: """ Initialize a SpeechRecognitionResults object. @@ -8017,26 +8434,23 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResults': """Initialize a SpeechRecognitionResults object from a json dictionary.""" args = {} - if 'results' in _dict: + if (results := _dict.get('results')) is not None: args['results'] = [ - SpeechRecognitionResult.from_dict(v) - for v in _dict.get('results') + SpeechRecognitionResult.from_dict(v) for v in results ] - if 'result_index' in _dict: - args['result_index'] = _dict.get('result_index') - if 'speaker_labels' in _dict: + if (result_index := _dict.get('result_index')) is not None: + args['result_index'] = result_index + if (speaker_labels := _dict.get('speaker_labels')) is not None: args['speaker_labels'] = [ - SpeakerLabelsResult.from_dict(v) - for v in _dict.get('speaker_labels') + SpeakerLabelsResult.from_dict(v) for v in speaker_labels ] - if 'processing_metrics' in _dict: + if (processing_metrics := _dict.get('processing_metrics')) is not None: args['processing_metrics'] = ProcessingMetrics.from_dict( - _dict.get('processing_metrics')) - if 'audio_metrics' in _dict: - args['audio_metrics'] = AudioMetrics.from_dict( - _dict.get('audio_metrics')) - if 'warnings' in _dict: - args['warnings'] = _dict.get('warnings') + processing_metrics) + if (audio_metrics := _dict.get('audio_metrics')) is not None: + args['audio_metrics'] = AudioMetrics.from_dict(audio_metrics) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = warnings return cls(**args) @classmethod @@ -8100,15 +8514,15 @@ def __ne__(self, other: 'SpeechRecognitionResults') -> bool: return not self == other -class SupportedFeatures(): +class SupportedFeatures: """ Indicates whether select service features are supported with the model. - :attr bool custom_language_model: Indicates whether the customization interface + :param bool custom_language_model: Indicates whether the customization interface can be used to create a custom language model based on the language model. - :attr bool custom_acoustic_model: Indicates whether the customization interface + :param bool custom_acoustic_model: Indicates whether the customization interface can be used to create a custom acoustic model based on the language model. - :attr bool speaker_labels: Indicates whether the `speaker_labels` parameter can + :param bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. **Note:** The field returns `true` for all models. However, speaker labels are supported for use only with the following languages and models: @@ -8119,18 +8533,20 @@ class SupportedFeatures(): (Australian, Indian, UK, and US), German, Japanese, Korean, and Spanish transcription only. Speaker labels are not supported for use with any other languages or models. - :attr bool low_latency: (optional) Indicates whether the `low_latency` parameter - can be used with a next-generation language model. The field is returned only - for next-generation models. Previous-generation models do not support the - `low_latency` parameter. + :param bool low_latency: (optional) Indicates whether the `low_latency` + parameter can be used with a next-generation language model. The field is + returned only for next-generation models. Previous-generation models do not + support the `low_latency` parameter. """ - def __init__(self, - custom_language_model: bool, - custom_acoustic_model: bool, - speaker_labels: bool, - *, - low_latency: bool = None) -> None: + def __init__( + self, + custom_language_model: bool, + custom_acoustic_model: bool, + speaker_labels: bool, + *, + low_latency: Optional[bool] = None, + ) -> None: """ Initialize a SupportedFeatures object. @@ -8167,26 +8583,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} - if 'custom_language_model' in _dict: - args['custom_language_model'] = _dict.get('custom_language_model') + if (custom_language_model := + _dict.get('custom_language_model')) is not None: + args['custom_language_model'] = custom_language_model else: raise ValueError( 'Required property \'custom_language_model\' not present in SupportedFeatures JSON' ) - if 'custom_acoustic_model' in _dict: - args['custom_acoustic_model'] = _dict.get('custom_acoustic_model') + if (custom_acoustic_model := + _dict.get('custom_acoustic_model')) is not None: + args['custom_acoustic_model'] = custom_acoustic_model else: raise ValueError( 'Required property \'custom_acoustic_model\' not present in SupportedFeatures JSON' ) - if 'speaker_labels' in _dict: - args['speaker_labels'] = _dict.get('speaker_labels') + if (speaker_labels := _dict.get('speaker_labels')) is not None: + args['speaker_labels'] = speaker_labels else: raise ValueError( 'Required property \'speaker_labels\' not present in SupportedFeatures JSON' ) - if 'low_latency' in _dict: - args['low_latency'] = _dict.get('low_latency') + if (low_latency := _dict.get('low_latency')) is not None: + args['low_latency'] = low_latency return cls(**args) @classmethod @@ -8228,18 +8646,22 @@ def __ne__(self, other: 'SupportedFeatures') -> bool: return not self == other -class TrainingResponse(): +class TrainingResponse: """ The response from training of a custom language or custom acoustic model. - :attr List[TrainingWarning] warnings: (optional) An array of `TrainingWarning` + :param List[TrainingWarning] warnings: (optional) An array of `TrainingWarning` objects that lists any invalid resources contained in the custom model. For custom language models, invalid resources are grouped and identified by type of resource. The method can return warnings only if the `strict` parameter is set to `false`. """ - def __init__(self, *, warnings: List['TrainingWarning'] = None) -> None: + def __init__( + self, + *, + warnings: Optional[List['TrainingWarning']] = None, + ) -> None: """ Initialize a TrainingResponse object. @@ -8255,10 +8677,8 @@ def __init__(self, *, warnings: List['TrainingWarning'] = None) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingResponse': """Initialize a TrainingResponse object from a json dictionary.""" args = {} - if 'warnings' in _dict: - args['warnings'] = [ - TrainingWarning.from_dict(v) for v in _dict.get('warnings') - ] + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [TrainingWarning.from_dict(v) for v in warnings] return cls(**args) @classmethod @@ -8298,20 +8718,24 @@ def __ne__(self, other: 'TrainingResponse') -> bool: return not self == other -class TrainingWarning(): +class TrainingWarning: """ A warning from training of a custom language or custom acoustic model. - :attr str code: An identifier for the type of invalid resources listed in the + :param str code: An identifier for the type of invalid resources listed in the `description` field. - :attr str message: A warning message that lists the invalid resources that are + :param str message: A warning message that lists the invalid resources that are excluded from the custom model's training. The message has the following format: `Analysis of the following {resource_type} has not completed successfully: [{resource_names}]. They will be excluded from custom {model_type} model training.`. """ - def __init__(self, code: str, message: str) -> None: + def __init__( + self, + code: str, + message: str, + ) -> None: """ Initialize a TrainingWarning object. @@ -8330,14 +8754,14 @@ def __init__(self, code: str, message: str) -> None: def from_dict(cls, _dict: Dict) -> 'TrainingWarning': """Initialize a TrainingWarning object from a json dictionary.""" args = {} - if 'code' in _dict: - args['code'] = _dict.get('code') + if (code := _dict.get('code')) is not None: + args['code'] = code else: raise ValueError( 'Required property \'code\' not present in TrainingWarning JSON' ) - if 'message' in _dict: - args['message'] = _dict.get('message') + if (message := _dict.get('message')) is not None: + args['message'] = message else: raise ValueError( 'Required property \'message\' not present in TrainingWarning JSON' @@ -8380,19 +8804,20 @@ class CodeEnum(str, Enum): """ An identifier for the type of invalid resources listed in the `description` field. """ + INVALID_AUDIO_FILES = 'invalid_audio_files' INVALID_CORPUS_FILES = 'invalid_corpus_files' INVALID_GRAMMAR_FILES = 'invalid_grammar_files' INVALID_WORDS = 'invalid_words' -class Word(): +class Word: """ Information about a word from a custom language model. - :attr str word: A word from the custom model's words resource. The spelling of + :param str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :attr List[str] sounds_like: An array of as many as five pronunciations for the + :param List[str] sounds_like: An array of as many as five pronunciations for the word. * _For a custom model that is based on a previous-generation model_, in addition to sounds-like pronunciations that were added by a user, the array can include a @@ -8400,7 +8825,7 @@ class Word(): is provided when the word is added to the custom model. * _For a custom model that is based on a next-generation model_, the array can include only sounds-like pronunciations that were added by a user. - :attr str display_as: The spelling of the word that the service uses to display + :param str display_as: The spelling of the word that the service uses to display the word in a transcript. * _For a custom model that is based on a previous-generation model_, the field can contain an empty string if no display-as value is provided for a word that @@ -8409,7 +8834,7 @@ class Word(): * _For a custom model that is based on a next-generation model_, the service uses the spelling of the word as the value of the display-as field when the word is added to the model. - :attr int count: _For a custom model that is based on a previous-generation + :param int count: _For a custom model that is based on a previous-generation model_, a sum of the number of times the word is found across all corpora and grammars. For example, if the word occurs five times in one corpus and seven times in another, its count is `12`. If you add a custom word to a model before @@ -8418,7 +8843,7 @@ class Word(): the number of times it is found in corpora and grammars. _For a custom model that is based on a next-generation model_, the `count` field for any word is always `1`. - :attr List[str] source: An array of sources that describes how the word was + :param List[str] source: An array of sources that describes how the word was added to the custom model's words resource. * _For a custom model that is based on previous-generation model,_ the field includes the name of each corpus and grammar from which the service extracted @@ -8429,19 +8854,21 @@ class Word(): shows only `user` for custom words that were added directly to the custom model. Words from corpora and grammars are not added to the words resource for custom models that are based on next-generation models. - :attr List[WordError] error: (optional) If the service discovered one or more + :param List[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. """ - def __init__(self, - word: str, - sounds_like: List[str], - display_as: str, - count: int, - source: List[str], - *, - error: List['WordError'] = None) -> None: + def __init__( + self, + word: str, + sounds_like: List[str], + display_as: str, + count: int, + source: List[str], + *, + error: Optional[List['WordError']] = None, + ) -> None: """ Initialize a Word object. @@ -8500,33 +8927,33 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} - if 'word' in _dict: - args['word'] = _dict.get('word') + if (word := _dict.get('word')) is not None: + args['word'] = word else: raise ValueError( 'Required property \'word\' not present in Word JSON') - if 'sounds_like' in _dict: - args['sounds_like'] = _dict.get('sounds_like') + if (sounds_like := _dict.get('sounds_like')) is not None: + args['sounds_like'] = sounds_like else: raise ValueError( 'Required property \'sounds_like\' not present in Word JSON') - if 'display_as' in _dict: - args['display_as'] = _dict.get('display_as') + if (display_as := _dict.get('display_as')) is not None: + args['display_as'] = display_as else: raise ValueError( 'Required property \'display_as\' not present in Word JSON') - if 'count' in _dict: - args['count'] = _dict.get('count') + if (count := _dict.get('count')) is not None: + args['count'] = count else: raise ValueError( 'Required property \'count\' not present in Word JSON') - if 'source' in _dict: - args['source'] = _dict.get('source') + if (source := _dict.get('source')) is not None: + args['source'] = source else: raise ValueError( 'Required property \'source\' not present in Word JSON') - if 'error' in _dict: - args['error'] = [WordError.from_dict(v) for v in _dict.get('error')] + if (error := _dict.get('error')) is not None: + args['error'] = [WordError.from_dict(v) for v in error] return cls(**args) @classmethod @@ -8576,16 +9003,20 @@ def __ne__(self, other: 'Word') -> bool: return not self == other -class WordAlternativeResult(): +class WordAlternativeResult: """ An alternative hypothesis for a word from speech recognition results. - :attr float confidence: A confidence score for the word alternative hypothesis + :param float confidence: A confidence score for the word alternative hypothesis in the range of 0.0 to 1.0. - :attr str word: An alternative hypothesis for a word from the input audio. + :param str word: An alternative hypothesis for a word from the input audio. """ - def __init__(self, confidence: float, word: str) -> None: + def __init__( + self, + confidence: float, + word: str, + ) -> None: """ Initialize a WordAlternativeResult object. @@ -8600,14 +9031,14 @@ def __init__(self, confidence: float, word: str) -> None: def from_dict(cls, _dict: Dict) -> 'WordAlternativeResult': """Initialize a WordAlternativeResult object from a json dictionary.""" args = {} - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence else: raise ValueError( 'Required property \'confidence\' not present in WordAlternativeResult JSON' ) - if 'word' in _dict: - args['word'] = _dict.get('word') + if (word := _dict.get('word')) is not None: + args['word'] = word else: raise ValueError( 'Required property \'word\' not present in WordAlternativeResult JSON' @@ -8647,20 +9078,24 @@ def __ne__(self, other: 'WordAlternativeResult') -> bool: return not self == other -class WordAlternativeResults(): +class WordAlternativeResults: """ Information about alternative hypotheses for words from speech recognition results. - :attr float start_time: The start time in seconds of the word from the input + :param float start_time: The start time in seconds of the word from the input audio that corresponds to the word alternatives. - :attr float end_time: The end time in seconds of the word from the input audio + :param float end_time: The end time in seconds of the word from the input audio that corresponds to the word alternatives. - :attr List[WordAlternativeResult] alternatives: An array of alternative + :param List[WordAlternativeResult] alternatives: An array of alternative hypotheses for a word from the input audio. """ - def __init__(self, start_time: float, end_time: float, - alternatives: List['WordAlternativeResult']) -> None: + def __init__( + self, + start_time: float, + end_time: float, + alternatives: List['WordAlternativeResult'], + ) -> None: """ Initialize a WordAlternativeResults object. @@ -8679,22 +9114,21 @@ def __init__(self, start_time: float, end_time: float, def from_dict(cls, _dict: Dict) -> 'WordAlternativeResults': """Initialize a WordAlternativeResults object from a json dictionary.""" args = {} - if 'start_time' in _dict: - args['start_time'] = _dict.get('start_time') + if (start_time := _dict.get('start_time')) is not None: + args['start_time'] = start_time else: raise ValueError( 'Required property \'start_time\' not present in WordAlternativeResults JSON' ) - if 'end_time' in _dict: - args['end_time'] = _dict.get('end_time') + if (end_time := _dict.get('end_time')) is not None: + args['end_time'] = end_time else: raise ValueError( 'Required property \'end_time\' not present in WordAlternativeResults JSON' ) - if 'alternatives' in _dict: + if (alternatives := _dict.get('alternatives')) is not None: args['alternatives'] = [ - WordAlternativeResult.from_dict(v) - for v in _dict.get('alternatives') + WordAlternativeResult.from_dict(v) for v in alternatives ] else: raise ValueError( @@ -8743,11 +9177,11 @@ def __ne__(self, other: 'WordAlternativeResults') -> bool: return not self == other -class WordError(): +class WordError: """ An error associated with a word from a custom language model. - :attr str element: A key-value pair that describes an error associated with the + :param str element: A key-value pair that describes an error associated with the definition of a word in the words resource. The pair has the format `"element": "message"`, where `element` is the aspect of the definition that caused the problem and `message` describes the problem. The following example describes a @@ -8756,7 +9190,10 @@ class WordError(): '{suggested_string}'."`. """ - def __init__(self, element: str) -> None: + def __init__( + self, + element: str, + ) -> None: """ Initialize a WordError object. @@ -8774,8 +9211,8 @@ def __init__(self, element: str) -> None: def from_dict(cls, _dict: Dict) -> 'WordError': """Initialize a WordError object from a json dictionary.""" args = {} - if 'element' in _dict: - args['element'] = _dict.get('element') + if (element := _dict.get('element')) is not None: + args['element'] = element else: raise ValueError( 'Required property \'element\' not present in WordError JSON') @@ -8812,16 +9249,19 @@ def __ne__(self, other: 'WordError') -> bool: return not self == other -class Words(): +class Words: """ Information about the words from a custom language model. - :attr List[Word] words: An array of `Word` objects that provides information + :param List[Word] words: An array of `Word` objects that provides information about each word in the custom model's words resource. The array is empty if the custom model has no words. """ - def __init__(self, words: List['Word']) -> None: + def __init__( + self, + words: List['Word'], + ) -> None: """ Initialize a Words object. @@ -8835,8 +9275,8 @@ def __init__(self, words: List['Word']) -> None: def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} - if 'words' in _dict: - args['words'] = [Word.from_dict(v) for v in _dict.get('words')] + if (words := _dict.get('words')) is not None: + args['words'] = [Word.from_dict(v) for v in words] else: raise ValueError( 'Required property \'words\' not present in Words JSON') diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index f2cfe225f..a8f24f2ff 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.64.1-cee95189-20230124-211647 +# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, @@ -48,7 +48,7 @@ """ from enum import Enum -from typing import BinaryIO, Dict, List +from typing import BinaryIO, Dict, List, Optional import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -92,7 +92,10 @@ def __init__( # Voices ######################### - def list_voices(self, **kwargs) -> DetailedResponse: + def list_voices( + self, + **kwargs, + ) -> DetailedResponse: """ List voices. @@ -117,9 +120,11 @@ def list_voices(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_voices') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_voices', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -128,16 +133,22 @@ def list_voices(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/voices' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def get_voice(self, - voice: str, - *, - customization_id: str = None, - **kwargs) -> DetailedResponse: + def get_voice( + self, + voice: str, + *, + customization_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Get a voice. @@ -170,9 +181,11 @@ def get_voice(self, if not voice: raise ValueError('voice must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_voice') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_voice', + ) headers.update(sdk_headers) params = { @@ -188,10 +201,12 @@ def get_voice(self, path_param_values = self.encode_path_vars(voice) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/voices/{voice}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -200,16 +215,18 @@ def get_voice(self, # Synthesis ######################### - def synthesize(self, - text: str, - *, - accept: str = None, - voice: str = None, - customization_id: str = None, - spell_out_mode: str = None, - rate_percentage: int = None, - pitch_percentage: int = None, - **kwargs) -> DetailedResponse: + def synthesize( + self, + text: str, + *, + accept: Optional[str] = None, + voice: Optional[str] = None, + customization_id: Optional[str] = None, + spell_out_mode: Optional[str] = None, + rate_percentage: Optional[int] = None, + pitch_percentage: Optional[int] = None, + **kwargs, + ) -> DetailedResponse: """ Synthesize audio. @@ -361,9 +378,11 @@ def synthesize(self, headers = { 'Accept': accept, } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='synthesize') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='synthesize', + ) headers.update(sdk_headers) params = { @@ -386,11 +405,13 @@ def synthesize(self, del kwargs['headers'] url = '/v1/synthesize' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response @@ -399,13 +420,15 @@ def synthesize(self, # Pronunciation ######################### - def get_pronunciation(self, - text: str, - *, - voice: str = None, - format: str = None, - customization_id: str = None, - **kwargs) -> DetailedResponse: + def get_pronunciation( + self, + text: str, + *, + voice: Optional[str] = None, + format: Optional[str] = None, + customization_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Get pronunciation. @@ -453,9 +476,11 @@ def get_pronunciation(self, if not text: raise ValueError('text must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_pronunciation') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_pronunciation', + ) headers.update(sdk_headers) params = { @@ -471,10 +496,12 @@ def get_pronunciation(self, headers['Accept'] = 'application/json' url = '/v1/pronunciation' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -483,12 +510,14 @@ def get_pronunciation(self, # Custom models ######################### - def create_custom_model(self, - name: str, - *, - language: str = None, - description: str = None, - **kwargs) -> DetailedResponse: + def create_custom_model( + self, + name: str, + *, + language: Optional[str] = None, + description: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Create a custom model. @@ -528,9 +557,11 @@ def create_custom_model(self, if name is None: raise ValueError('name must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_custom_model', + ) headers.update(sdk_headers) data = { @@ -548,18 +579,22 @@ def create_custom_model(self, headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_custom_models(self, - *, - language: str = None, - **kwargs) -> DetailedResponse: + def list_custom_models( + self, + *, + language: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ List custom models. @@ -581,9 +616,11 @@ def list_custom_models(self, """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_custom_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_custom_models', + ) headers.update(sdk_headers) params = { @@ -596,21 +633,25 @@ def list_custom_models(self, headers['Accept'] = 'application/json' url = '/v1/customizations' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response - def update_custom_model(self, - customization_id: str, - *, - name: str = None, - description: str = None, - words: List['Word'] = None, - **kwargs) -> DetailedResponse: + def update_custom_model( + self, + customization_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + words: Optional[List['Word']] = None, + **kwargs, + ) -> DetailedResponse: """ Update a custom model. @@ -656,9 +697,11 @@ def update_custom_model(self, if words is not None: words = [convert_model(x) for x in words] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='update_custom_model', + ) headers.update(sdk_headers) data = { @@ -679,16 +722,21 @@ def update_custom_model(self, path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def get_custom_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def get_custom_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom model. @@ -711,9 +759,11 @@ def get_custom_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_custom_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -725,13 +775,20 @@ def get_custom_model(self, customization_id: str, path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_custom_model(self, customization_id: str, - **kwargs) -> DetailedResponse: + def delete_custom_model( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom model. @@ -751,9 +808,11 @@ def delete_custom_model(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_custom_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_custom_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -764,9 +823,11 @@ def delete_custom_model(self, customization_id: str, path_param_values = self.encode_path_vars(customization_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -775,8 +836,12 @@ def delete_custom_model(self, customization_id: str, # Custom words ######################### - def add_words(self, customization_id: str, words: List['Word'], - **kwargs) -> DetailedResponse: + def add_words( + self, + customization_id: str, + words: List['Word'], + **kwargs, + ) -> DetailedResponse: """ Add custom words. @@ -825,9 +890,11 @@ def add_words(self, customization_id: str, words: List['Word'], raise ValueError('words must be provided') words = [convert_model(x) for x in words] headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_words', + ) headers.update(sdk_headers) data = { @@ -847,15 +914,21 @@ def add_words(self, customization_id: str, words: List['Word'], path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: + def list_words( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List custom words. @@ -876,9 +949,11 @@ def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_words') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_words', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -891,18 +966,24 @@ def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_word(self, - customization_id: str, - word: str, - translation: str, - *, - part_of_speech: str = None, - **kwargs) -> DetailedResponse: + def add_word( + self, + customization_id: str, + word: str, + translation: str, + *, + part_of_speech: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: """ Add a custom word. @@ -959,9 +1040,11 @@ def add_word(self, if translation is None: raise ValueError('translation must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_word', + ) headers.update(sdk_headers) data = { @@ -981,16 +1064,22 @@ def add_word(self, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word}'.format( **path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - data=data) + request = self.prepare_request( + method='PUT', + url=url, + headers=headers, + data=data, + ) response = self.send(request, **kwargs) return response - def get_word(self, customization_id: str, word: str, - **kwargs) -> DetailedResponse: + def get_word( + self, + customization_id: str, + word: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom word. @@ -1014,9 +1103,11 @@ def get_word(self, customization_id: str, word: str, if not word: raise ValueError('word must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1029,13 +1120,21 @@ def get_word(self, customization_id: str, word: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_word(self, customization_id: str, word: str, - **kwargs) -> DetailedResponse: + def delete_word( + self, + customization_id: str, + word: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom word. @@ -1058,9 +1157,11 @@ def delete_word(self, customization_id: str, word: str, if not word: raise ValueError('word must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_word') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_word', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1072,9 +1173,11 @@ def delete_word(self, customization_id: str, word: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/words/{word}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1083,8 +1186,11 @@ def delete_word(self, customization_id: str, word: str, # Custom prompts ######################### - def list_custom_prompts(self, customization_id: str, - **kwargs) -> DetailedResponse: + def list_custom_prompts( + self, + customization_id: str, + **kwargs, + ) -> DetailedResponse: """ List custom prompts. @@ -1111,9 +1217,11 @@ def list_custom_prompts(self, customization_id: str, if not customization_id: raise ValueError('customization_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_custom_prompts') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_custom_prompts', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1126,14 +1234,23 @@ def list_custom_prompts(self, customization_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def add_custom_prompt(self, customization_id: str, prompt_id: str, - metadata: 'PromptMetadata', file: BinaryIO, - **kwargs) -> DetailedResponse: + def add_custom_prompt( + self, + customization_id: str, + prompt_id: str, + metadata: 'PromptMetadata', + file: BinaryIO, + **kwargs, + ) -> DetailedResponse: """ Add a custom prompt. @@ -1245,9 +1362,11 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, if file is None: raise ValueError('file must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_custom_prompt') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='add_custom_prompt', + ) headers.update(sdk_headers) form_data = [] @@ -1265,16 +1384,22 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - files=form_data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + files=form_data, + ) response = self.send(request, **kwargs) return response - def get_custom_prompt(self, customization_id: str, prompt_id: str, - **kwargs) -> DetailedResponse: + def get_custom_prompt( + self, + customization_id: str, + prompt_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a custom prompt. @@ -1300,9 +1425,11 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, if not prompt_id: raise ValueError('prompt_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_custom_prompt') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_custom_prompt', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1315,13 +1442,21 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( **path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_custom_prompt(self, customization_id: str, prompt_id: str, - **kwargs) -> DetailedResponse: + def delete_custom_prompt( + self, + customization_id: str, + prompt_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a custom prompt. @@ -1350,9 +1485,11 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, if not prompt_id: raise ValueError('prompt_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_custom_prompt') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_custom_prompt', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1364,9 +1501,11 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/customizations/{customization_id}/prompts/{prompt_id}'.format( **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1375,7 +1514,10 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, # Speaker models ######################### - def list_speaker_models(self, **kwargs) -> DetailedResponse: + def list_speaker_models( + self, + **kwargs, + ) -> DetailedResponse: """ List speaker models. @@ -1393,9 +1535,11 @@ def list_speaker_models(self, **kwargs) -> DetailedResponse: """ headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_speaker_models') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='list_speaker_models', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1404,13 +1548,21 @@ def list_speaker_models(self, **kwargs) -> DetailedResponse: headers['Accept'] = 'application/json' url = '/v1/speakers' - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def create_speaker_model(self, speaker_name: str, audio: BinaryIO, - **kwargs) -> DetailedResponse: + def create_speaker_model( + self, + speaker_name: str, + audio: BinaryIO, + **kwargs, + ) -> DetailedResponse: """ Create a speaker model. @@ -1480,9 +1632,11 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, if audio is None: raise ValueError('audio must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_speaker_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='create_speaker_model', + ) headers.update(sdk_headers) params = { @@ -1498,16 +1652,22 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, headers['Accept'] = 'application/json' url = '/v1/speakers' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) response = self.send(request, **kwargs) return response - def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: + def get_speaker_model( + self, + speaker_id: str, + **kwargs, + ) -> DetailedResponse: """ Get a speaker model. @@ -1533,9 +1693,11 @@ def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: if not speaker_id: raise ValueError('speaker_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_speaker_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='get_speaker_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1547,13 +1709,20 @@ def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: path_param_values = self.encode_path_vars(speaker_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/speakers/{speaker_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response - def delete_speaker_model(self, speaker_id: str, - **kwargs) -> DetailedResponse: + def delete_speaker_model( + self, + speaker_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete a speaker model. @@ -1581,9 +1750,11 @@ def delete_speaker_model(self, speaker_id: str, if not speaker_id: raise ValueError('speaker_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_speaker_model') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_speaker_model', + ) headers.update(sdk_headers) if 'headers' in kwargs: @@ -1594,9 +1765,11 @@ def delete_speaker_model(self, speaker_id: str, path_param_values = self.encode_path_vars(speaker_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v1/speakers/{speaker_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + ) response = self.send(request, **kwargs) return response @@ -1605,7 +1778,11 @@ def delete_speaker_model(self, speaker_id: str, # User data ######################### - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: + def delete_user_data( + self, + customer_id: str, + **kwargs, + ) -> DetailedResponse: """ Delete labeled data. @@ -1633,9 +1810,11 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: if not customer_id: raise ValueError('customer_id must be provided') headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data') + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='delete_user_data', + ) headers.update(sdk_headers) params = { @@ -1647,10 +1826,12 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: del kwargs['headers'] url = '/v1/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) + request = self.prepare_request( + method='DELETE', + url=url, + headers=headers, + params=params, + ) response = self.send(request, **kwargs) return response @@ -1665,6 +1846,7 @@ class Voice(str, Enum): """ The voice for which information is to be returned. """ + AR_MS_OMARVOICE = 'ar-MS_OmarVoice' CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' @@ -1726,6 +1908,7 @@ class Accept(str, Enum): specifying an audio format, see **Audio formats (accept types)** in the method description. """ + AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' AUDIO_FLAC = 'audio/flac' @@ -1754,6 +1937,7 @@ class Voice(str, Enum): * [Using the default voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). """ + AR_MS_OMARVOICE = 'ar-MS_OmarVoice' CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' @@ -1819,6 +2003,7 @@ class SpellOutMode(str, Enum): For more information, see [Specifying how strings are spelled out](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-synthesis-params#params-spell-out-mode). """ + DEFAULT = 'default' SINGLES = 'singles' PAIRS = 'pairs' @@ -1842,6 +2027,7 @@ class Voice(str, Enum): **See also:** [Using the default voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). """ + AR_MS_OMARVOICE = 'ar-MS_OmarVoice' CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' @@ -1896,6 +2082,7 @@ class Format(str, Enum): Dutch, Australian English, and Korean languages support only IPA. Omit the parameter to obtain the pronunciation in the default format. """ + IBM = 'ibm' IPA = 'ipa' @@ -1911,6 +2098,7 @@ class Language(str, Enum): are to be returned. Omit the parameter to see all custom models that are owned by the requester. """ + AR_MS = 'ar-MS' CS_CZ = 'cs-CZ' DE_DE = 'de-DE' @@ -1937,49 +2125,51 @@ class Language(str, Enum): ############################################################################## -class CustomModel(): +class CustomModel: """ Information about an existing custom model. - :attr str customization_id: The customization ID (GUID) of the custom model. The - [Create a custom model](#createcustommodel) method returns only this field. It - does not not return the other fields of this object. - :attr str name: (optional) The name of the custom model. - :attr str language: (optional) The language identifier of the custom model (for + :param str customization_id: The customization ID (GUID) of the custom model. + The [Create a custom model](#createcustommodel) method returns only this field. + It does not not return the other fields of this object. + :param str name: (optional) The name of the custom model. + :param str language: (optional) The language identifier of the custom model (for example, `en-US`). - :attr str owner: (optional) The GUID of the credentials for the instance of the + :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom model. - :attr str created: (optional) The date and time in Coordinated Universal Time + :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str last_modified: (optional) The date and time in Coordinated Universal + :param str last_modified: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom model was last modified. The `created` and `updated` fields are equal when a model is first added but has yet to be updated. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). - :attr str description: (optional) The description of the custom model. - :attr List[Word] words: (optional) An array of `Word` objects that lists the + :param str description: (optional) The description of the custom model. + :param List[Word] words: (optional) An array of `Word` objects that lists the words and their translations from the custom model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if no words are defined for the custom model. This field is returned only by the [Get a custom model](#getcustommodel) method. - :attr List[Prompt] prompts: (optional) An array of `Prompt` objects that + :param List[Prompt] prompts: (optional) An array of `Prompt` objects that provides information about the prompts that are defined for the specified custom model. The array is empty if no prompts are defined for the custom model. This field is returned only by the [Get a custom model](#getcustommodel) method. """ - def __init__(self, - customization_id: str, - *, - name: str = None, - language: str = None, - owner: str = None, - created: str = None, - last_modified: str = None, - description: str = None, - words: List['Word'] = None, - prompts: List['Prompt'] = None) -> None: + def __init__( + self, + customization_id: str, + *, + name: Optional[str] = None, + language: Optional[str] = None, + owner: Optional[str] = None, + created: Optional[str] = None, + last_modified: Optional[str] = None, + description: Optional[str] = None, + words: Optional[List['Word']] = None, + prompts: Optional[List['Prompt']] = None, + ) -> None: """ Initialize a CustomModel object. @@ -2026,30 +2216,28 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'CustomModel': """Initialize a CustomModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in CustomModel JSON' ) - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'created' in _dict: - args['created'] = _dict.get('created') - if 'last_modified' in _dict: - args['last_modified'] = _dict.get('last_modified') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'words' in _dict: - args['words'] = [Word.from_dict(v) for v in _dict.get('words')] - if 'prompts' in _dict: - args['prompts'] = [ - Prompt.from_dict(v) for v in _dict.get('prompts') - ] + if (name := _dict.get('name')) is not None: + args['name'] = name + if (language := _dict.get('language')) is not None: + args['language'] = language + if (owner := _dict.get('owner')) is not None: + args['owner'] = owner + if (created := _dict.get('created')) is not None: + args['created'] = created + if (last_modified := _dict.get('last_modified')) is not None: + args['last_modified'] = last_modified + if (description := _dict.get('description')) is not None: + args['description'] = description + if (words := _dict.get('words')) is not None: + args['words'] = [Word.from_dict(v) for v in words] + if (prompts := _dict.get('prompts')) is not None: + args['prompts'] = [Prompt.from_dict(v) for v in prompts] return cls(**args) @classmethod @@ -2112,17 +2300,20 @@ def __ne__(self, other: 'CustomModel') -> bool: return not self == other -class CustomModels(): +class CustomModels: """ Information about existing custom models. - :attr List[CustomModel] customizations: An array of `CustomModel` objects that + :param List[CustomModel] customizations: An array of `CustomModel` objects that provides information about each available custom model. The array is empty if the requesting credentials own no custom models (if no language is specified) or own no custom models for the specified language. """ - def __init__(self, customizations: List['CustomModel']) -> None: + def __init__( + self, + customizations: List['CustomModel'], + ) -> None: """ Initialize a CustomModels object. @@ -2137,9 +2328,9 @@ def __init__(self, customizations: List['CustomModel']) -> None: def from_dict(cls, _dict: Dict) -> 'CustomModels': """Initialize a CustomModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - CustomModel.from_dict(v) for v in _dict.get('customizations') + CustomModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -2184,33 +2375,35 @@ def __ne__(self, other: 'CustomModels') -> bool: return not self == other -class Prompt(): +class Prompt: """ Information about a custom prompt. - :attr str prompt: The user-specified text of the prompt. - :attr str prompt_id: The user-specified identifier (name) of the prompt. - :attr str status: The status of the prompt: + :param str prompt: The user-specified text of the prompt. + :param str prompt_id: The user-specified identifier (name) of the prompt. + :param str status: The status of the prompt: * `processing`: The service received the request to add the prompt and is analyzing the validity of the prompt. * `available`: The service successfully validated the prompt, which is now ready for use in a speech synthesis request. * `failed`: The service's validation of the prompt failed. The status of the prompt includes an `error` field that describes the reason for the failure. - :attr str error: (optional) If the status of the prompt is `failed`, an error + :param str error: (optional) If the status of the prompt is `failed`, an error message that describes the reason for the failure. The field is omitted if no error occurred. - :attr str speaker_id: (optional) The speaker ID (GUID) of the speaker for which + :param str speaker_id: (optional) The speaker ID (GUID) of the speaker for which the prompt was defined. The field is omitted if no speaker ID was specified. """ - def __init__(self, - prompt: str, - prompt_id: str, - status: str, - *, - error: str = None, - speaker_id: str = None) -> None: + def __init__( + self, + prompt: str, + prompt_id: str, + status: str, + *, + error: Optional[str] = None, + speaker_id: Optional[str] = None, + ) -> None: """ Initialize a Prompt object. @@ -2241,25 +2434,25 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Prompt': """Initialize a Prompt object from a json dictionary.""" args = {} - if 'prompt' in _dict: - args['prompt'] = _dict.get('prompt') + if (prompt := _dict.get('prompt')) is not None: + args['prompt'] = prompt else: raise ValueError( 'Required property \'prompt\' not present in Prompt JSON') - if 'prompt_id' in _dict: - args['prompt_id'] = _dict.get('prompt_id') + if (prompt_id := _dict.get('prompt_id')) is not None: + args['prompt_id'] = prompt_id else: raise ValueError( 'Required property \'prompt_id\' not present in Prompt JSON') - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in Prompt JSON') - if 'error' in _dict: - args['error'] = _dict.get('error') - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (error := _dict.get('error')) is not None: + args['error'] = error + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id return cls(**args) @classmethod @@ -2301,7 +2494,7 @@ def __ne__(self, other: 'Prompt') -> bool: return not self == other -class PromptMetadata(): +class PromptMetadata: """ Information about the prompt that is to be added to a custom model. The following example of a `PromptMetadata` object includes both the required prompt text and an @@ -2309,17 +2502,22 @@ class PromptMetadata(): `{ "prompt_text": "Thank you and good-bye!", "speaker_id": "823068b2-ed4e-11ea-b6e0-7b6456aa95cc" }`. - :attr str prompt_text: The required written text of the spoken prompt. The + :param str prompt_text: The required written text of the spoken prompt. The length of a prompt's text is limited to a few sentences. Speaking one or two sentences of text is the recommended limit. A prompt cannot contain more than 1000 characters of text. Escape any XML control characters (double quotes, single quotes, ampersands, angle brackets, and slashes) that appear in the text of the prompt. - :attr str speaker_id: (optional) The optional speaker ID (GUID) of a previously + :param str speaker_id: (optional) The optional speaker ID (GUID) of a previously defined speaker model that is to be associated with the prompt. """ - def __init__(self, prompt_text: str, *, speaker_id: str = None) -> None: + def __init__( + self, + prompt_text: str, + *, + speaker_id: Optional[str] = None, + ) -> None: """ Initialize a PromptMetadata object. @@ -2339,14 +2537,14 @@ def __init__(self, prompt_text: str, *, speaker_id: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'PromptMetadata': """Initialize a PromptMetadata object from a json dictionary.""" args = {} - if 'prompt_text' in _dict: - args['prompt_text'] = _dict.get('prompt_text') + if (prompt_text := _dict.get('prompt_text')) is not None: + args['prompt_text'] = prompt_text else: raise ValueError( 'Required property \'prompt_text\' not present in PromptMetadata JSON' ) - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id return cls(**args) @classmethod @@ -2382,16 +2580,19 @@ def __ne__(self, other: 'PromptMetadata') -> bool: return not self == other -class Prompts(): +class Prompts: """ Information about the custom prompts that are defined for a custom model. - :attr List[Prompt] prompts: An array of `Prompt` objects that provides + :param List[Prompt] prompts: An array of `Prompt` objects that provides information about the prompts that are defined for the specified custom model. The array is empty if no prompts are defined for the custom model. """ - def __init__(self, prompts: List['Prompt']) -> None: + def __init__( + self, + prompts: List['Prompt'], + ) -> None: """ Initialize a Prompts object. @@ -2405,10 +2606,8 @@ def __init__(self, prompts: List['Prompt']) -> None: def from_dict(cls, _dict: Dict) -> 'Prompts': """Initialize a Prompts object from a json dictionary.""" args = {} - if 'prompts' in _dict: - args['prompts'] = [ - Prompt.from_dict(v) for v in _dict.get('prompts') - ] + if (prompts := _dict.get('prompts')) is not None: + args['prompts'] = [Prompt.from_dict(v) for v in prompts] else: raise ValueError( 'Required property \'prompts\' not present in Prompts JSON') @@ -2451,16 +2650,19 @@ def __ne__(self, other: 'Prompts') -> bool: return not self == other -class Pronunciation(): +class Pronunciation: """ The pronunciation of the specified text. - :attr str pronunciation: The pronunciation of the specified text in the + :param str pronunciation: The pronunciation of the specified text in the requested voice and format. If a custom model is specified, the pronunciation also reflects that custom model. """ - def __init__(self, pronunciation: str) -> None: + def __init__( + self, + pronunciation: str, + ) -> None: """ Initialize a Pronunciation object. @@ -2474,8 +2676,8 @@ def __init__(self, pronunciation: str) -> None: def from_dict(cls, _dict: Dict) -> 'Pronunciation': """Initialize a Pronunciation object from a json dictionary.""" args = {} - if 'pronunciation' in _dict: - args['pronunciation'] = _dict.get('pronunciation') + if (pronunciation := _dict.get('pronunciation')) is not None: + args['pronunciation'] = pronunciation else: raise ValueError( 'Required property \'pronunciation\' not present in Pronunciation JSON' @@ -2513,15 +2715,19 @@ def __ne__(self, other: 'Pronunciation') -> bool: return not self == other -class Speaker(): +class Speaker: """ Information about a speaker model. - :attr str speaker_id: The speaker ID (GUID) of the speaker. - :attr str name: The user-defined name of the speaker. + :param str speaker_id: The speaker ID (GUID) of the speaker. + :param str name: The user-defined name of the speaker. """ - def __init__(self, speaker_id: str, name: str) -> None: + def __init__( + self, + speaker_id: str, + name: str, + ) -> None: """ Initialize a Speaker object. @@ -2535,13 +2741,13 @@ def __init__(self, speaker_id: str, name: str) -> None: def from_dict(cls, _dict: Dict) -> 'Speaker': """Initialize a Speaker object from a json dictionary.""" args = {} - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id else: raise ValueError( 'Required property \'speaker_id\' not present in Speaker JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Speaker JSON') @@ -2580,19 +2786,22 @@ def __ne__(self, other: 'Speaker') -> bool: return not self == other -class SpeakerCustomModel(): +class SpeakerCustomModel: """ A custom models for which the speaker has defined prompts. - :attr str customization_id: The customization ID (GUID) of a custom model for + :param str customization_id: The customization ID (GUID) of a custom model for which the speaker has defined one or more prompts. - :attr List[SpeakerPrompt] prompts: An array of `SpeakerPrompt` objects that + :param List[SpeakerPrompt] prompts: An array of `SpeakerPrompt` objects that provides information about each prompt that the user has defined for the custom model. """ - def __init__(self, customization_id: str, - prompts: List['SpeakerPrompt']) -> None: + def __init__( + self, + customization_id: str, + prompts: List['SpeakerPrompt'], + ) -> None: """ Initialize a SpeakerCustomModel object. @@ -2609,16 +2818,14 @@ def __init__(self, customization_id: str, def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModel': """Initialize a SpeakerCustomModel object from a json dictionary.""" args = {} - if 'customization_id' in _dict: - args['customization_id'] = _dict.get('customization_id') + if (customization_id := _dict.get('customization_id')) is not None: + args['customization_id'] = customization_id else: raise ValueError( 'Required property \'customization_id\' not present in SpeakerCustomModel JSON' ) - if 'prompts' in _dict: - args['prompts'] = [ - SpeakerPrompt.from_dict(v) for v in _dict.get('prompts') - ] + if (prompts := _dict.get('prompts')) is not None: + args['prompts'] = [SpeakerPrompt.from_dict(v) for v in prompts] else: raise ValueError( 'Required property \'prompts\' not present in SpeakerCustomModel JSON' @@ -2665,17 +2872,20 @@ def __ne__(self, other: 'SpeakerCustomModel') -> bool: return not self == other -class SpeakerCustomModels(): +class SpeakerCustomModels: """ Custom models for which the speaker has defined prompts. - :attr List[SpeakerCustomModel] customizations: An array of `SpeakerCustomModel` + :param List[SpeakerCustomModel] customizations: An array of `SpeakerCustomModel` objects. Each object provides information about the prompts that are defined for a specified speaker in the custom models that are owned by a specified service instance. The array is empty if no prompts are defined for the speaker. """ - def __init__(self, customizations: List['SpeakerCustomModel']) -> None: + def __init__( + self, + customizations: List['SpeakerCustomModel'], + ) -> None: """ Initialize a SpeakerCustomModels object. @@ -2691,10 +2901,9 @@ def __init__(self, customizations: List['SpeakerCustomModel']) -> None: def from_dict(cls, _dict: Dict) -> 'SpeakerCustomModels': """Initialize a SpeakerCustomModels object from a json dictionary.""" args = {} - if 'customizations' in _dict: + if (customizations := _dict.get('customizations')) is not None: args['customizations'] = [ - SpeakerCustomModel.from_dict(v) - for v in _dict.get('customizations') + SpeakerCustomModel.from_dict(v) for v in customizations ] else: raise ValueError( @@ -2739,14 +2948,17 @@ def __ne__(self, other: 'SpeakerCustomModels') -> bool: return not self == other -class SpeakerModel(): +class SpeakerModel: """ The speaker ID of the speaker model. - :attr str speaker_id: The speaker ID (GUID) of the speaker model. + :param str speaker_id: The speaker ID (GUID) of the speaker model. """ - def __init__(self, speaker_id: str) -> None: + def __init__( + self, + speaker_id: str, + ) -> None: """ Initialize a SpeakerModel object. @@ -2758,8 +2970,8 @@ def __init__(self, speaker_id: str) -> None: def from_dict(cls, _dict: Dict) -> 'SpeakerModel': """Initialize a SpeakerModel object from a json dictionary.""" args = {} - if 'speaker_id' in _dict: - args['speaker_id'] = _dict.get('speaker_id') + if (speaker_id := _dict.get('speaker_id')) is not None: + args['speaker_id'] = speaker_id else: raise ValueError( 'Required property \'speaker_id\' not present in SpeakerModel JSON' @@ -2797,30 +3009,32 @@ def __ne__(self, other: 'SpeakerModel') -> bool: return not self == other -class SpeakerPrompt(): +class SpeakerPrompt: """ A prompt that a speaker has defined for a custom model. - :attr str prompt: The user-specified text of the prompt. - :attr str prompt_id: The user-specified identifier (name) of the prompt. - :attr str status: The status of the prompt: + :param str prompt: The user-specified text of the prompt. + :param str prompt_id: The user-specified identifier (name) of the prompt. + :param str status: The status of the prompt: * `processing`: The service received the request to add the prompt and is analyzing the validity of the prompt. * `available`: The service successfully validated the prompt, which is now ready for use in a speech synthesis request. * `failed`: The service's validation of the prompt failed. The status of the prompt includes an `error` field that describes the reason for the failure. - :attr str error: (optional) If the status of the prompt is `failed`, an error + :param str error: (optional) If the status of the prompt is `failed`, an error message that describes the reason for the failure. The field is omitted if no error occurred. """ - def __init__(self, - prompt: str, - prompt_id: str, - status: str, - *, - error: str = None) -> None: + def __init__( + self, + prompt: str, + prompt_id: str, + status: str, + *, + error: Optional[str] = None, + ) -> None: """ Initialize a SpeakerPrompt object. @@ -2847,26 +3061,26 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'SpeakerPrompt': """Initialize a SpeakerPrompt object from a json dictionary.""" args = {} - if 'prompt' in _dict: - args['prompt'] = _dict.get('prompt') + if (prompt := _dict.get('prompt')) is not None: + args['prompt'] = prompt else: raise ValueError( 'Required property \'prompt\' not present in SpeakerPrompt JSON' ) - if 'prompt_id' in _dict: - args['prompt_id'] = _dict.get('prompt_id') + if (prompt_id := _dict.get('prompt_id')) is not None: + args['prompt_id'] = prompt_id else: raise ValueError( 'Required property \'prompt_id\' not present in SpeakerPrompt JSON' ) - if 'status' in _dict: - args['status'] = _dict.get('status') + if (status := _dict.get('status')) is not None: + args['status'] = status else: raise ValueError( 'Required property \'status\' not present in SpeakerPrompt JSON' ) - if 'error' in _dict: - args['error'] = _dict.get('error') + if (error := _dict.get('error')) is not None: + args['error'] = error return cls(**args) @classmethod @@ -2906,16 +3120,19 @@ def __ne__(self, other: 'SpeakerPrompt') -> bool: return not self == other -class Speakers(): +class Speakers: """ Information about all speaker models for the service instance. - :attr List[Speaker] speakers: An array of `Speaker` objects that provides + :param List[Speaker] speakers: An array of `Speaker` objects that provides information about the speakers for the service instance. The array is empty if the service instance has no speakers. """ - def __init__(self, speakers: List['Speaker']) -> None: + def __init__( + self, + speakers: List['Speaker'], + ) -> None: """ Initialize a Speakers object. @@ -2929,10 +3146,8 @@ def __init__(self, speakers: List['Speaker']) -> None: def from_dict(cls, _dict: Dict) -> 'Speakers': """Initialize a Speakers object from a json dictionary.""" args = {} - if 'speakers' in _dict: - args['speakers'] = [ - Speaker.from_dict(v) for v in _dict.get('speakers') - ] + if (speakers := _dict.get('speakers')) is not None: + args['speakers'] = [Speaker.from_dict(v) for v in speakers] else: raise ValueError( 'Required property \'speakers\' not present in Speakers JSON') @@ -2975,20 +3190,23 @@ def __ne__(self, other: 'Speakers') -> bool: return not self == other -class SupportedFeatures(): +class SupportedFeatures: """ Additional service features that are supported with the voice. - :attr bool custom_pronunciation: If `true`, the voice can be customized; if + :param bool custom_pronunciation: If `true`, the voice can be customized; if `false`, the voice cannot be customized. (Same as `customizable`.). - :attr bool voice_transformation: If `true`, the voice can be transformed by + :param bool voice_transformation: If `true`, the voice can be transformed by using the SSML <voice-transformation> element; if `false`, the voice cannot be transformed. The feature was available only for the now-deprecated standard voices. You cannot use the feature with neural voices. """ - def __init__(self, custom_pronunciation: bool, - voice_transformation: bool) -> None: + def __init__( + self, + custom_pronunciation: bool, + voice_transformation: bool, + ) -> None: """ Initialize a SupportedFeatures object. @@ -3007,14 +3225,16 @@ def __init__(self, custom_pronunciation: bool, def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': """Initialize a SupportedFeatures object from a json dictionary.""" args = {} - if 'custom_pronunciation' in _dict: - args['custom_pronunciation'] = _dict.get('custom_pronunciation') + if (custom_pronunciation := + _dict.get('custom_pronunciation')) is not None: + args['custom_pronunciation'] = custom_pronunciation else: raise ValueError( 'Required property \'custom_pronunciation\' not present in SupportedFeatures JSON' ) - if 'voice_transformation' in _dict: - args['voice_transformation'] = _dict.get('voice_transformation') + if (voice_transformation := + _dict.get('voice_transformation')) is not None: + args['voice_transformation'] = voice_transformation else: raise ValueError( 'Required property \'voice_transformation\' not present in SupportedFeatures JSON' @@ -3056,17 +3276,17 @@ def __ne__(self, other: 'SupportedFeatures') -> bool: return not self == other -class Translation(): +class Translation: """ Information about the translation for the specified text. - :attr str translation: The phonetic or sounds-like translation for the word. A + :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR translation. The Arabic, Chinese, Dutch, Australian English, and Korean languages support only IPA. A sounds-like is one or more words that, when combined, sound like the word. - :attr str part_of_speech: (optional) **Japanese only.** The part of speech for + :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the 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 @@ -3074,7 +3294,12 @@ class Translation(): 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: + def __init__( + self, + translation: str, + *, + part_of_speech: Optional[str] = None, + ) -> None: """ Initialize a Translation object. @@ -3099,14 +3324,14 @@ def __init__(self, translation: str, *, part_of_speech: str = None) -> None: def from_dict(cls, _dict: Dict) -> 'Translation': """Initialize a Translation object from a json dictionary.""" args = {} - if 'translation' in _dict: - args['translation'] = _dict.get('translation') + if (translation := _dict.get('translation')) is not None: + args['translation'] = translation else: raise ValueError( 'Required property \'translation\' not present in Translation JSON' ) - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech return cls(**args) @classmethod @@ -3150,6 +3375,7 @@ class PartOfSpeechEnum(str, Enum): see [Working with Japanese entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ + DOSI = 'Dosi' FUKU = 'Fuku' GOBI = 'Gobi' @@ -3169,37 +3395,40 @@ class PartOfSpeechEnum(str, Enum): SUJI = 'Suji' -class Voice(): +class Voice: """ Information about an available voice. - :attr str url: The URI of the voice. - :attr str gender: The gender of the voice: `male` or `female`. - :attr str name: The name of the voice. Use this as the voice identifier in all + :param str url: The URI of the voice. + :param str gender: The gender of the voice: `male` or `female`. + :param str name: The name of the voice. Use this as the voice identifier in all requests. - :attr str language: The language and region of the voice (for example, `en-US`). - :attr str description: A textual description of the voice. - :attr bool customizable: If `true`, the voice can be customized; if `false`, the - voice cannot be customized. (Same as `custom_pronunciation`; maintained for + :param str language: The language and region of the voice (for example, + `en-US`). + :param str description: A textual description of the voice. + :param bool customizable: If `true`, the voice can be customized; if `false`, + the voice cannot be customized. (Same as `custom_pronunciation`; maintained for backward compatibility.). - :attr SupportedFeatures supported_features: Additional service features that are - supported with the voice. - :attr CustomModel customization: (optional) Returns information about a + :param SupportedFeatures supported_features: Additional service features that + are supported with the voice. + :param CustomModel customization: (optional) Returns information about a specified custom model. This field is returned only by the [Get a voice](#getvoice) method and only when you specify the customization ID of a custom model. """ - def __init__(self, - url: str, - gender: str, - name: str, - language: str, - description: str, - customizable: bool, - supported_features: 'SupportedFeatures', - *, - customization: 'CustomModel' = None) -> None: + def __init__( + self, + url: str, + gender: str, + name: str, + language: str, + description: str, + customizable: bool, + supported_features: 'SupportedFeatures', + *, + customization: Optional['CustomModel'] = None, + ) -> None: """ Initialize a Voice object. @@ -3233,46 +3462,45 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Voice': """Initialize a Voice object from a json dictionary.""" args = {} - if 'url' in _dict: - args['url'] = _dict.get('url') + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( 'Required property \'url\' not present in Voice JSON') - if 'gender' in _dict: - args['gender'] = _dict.get('gender') + if (gender := _dict.get('gender')) is not None: + args['gender'] = gender else: raise ValueError( 'Required property \'gender\' not present in Voice JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') + if (name := _dict.get('name')) is not None: + args['name'] = name else: raise ValueError( 'Required property \'name\' not present in Voice JSON') - if 'language' in _dict: - args['language'] = _dict.get('language') + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( 'Required property \'language\' not present in Voice JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') + if (description := _dict.get('description')) is not None: + args['description'] = description else: raise ValueError( 'Required property \'description\' not present in Voice JSON') - if 'customizable' in _dict: - args['customizable'] = _dict.get('customizable') + if (customizable := _dict.get('customizable')) is not None: + args['customizable'] = customizable else: raise ValueError( 'Required property \'customizable\' not present in Voice JSON') - if 'supported_features' in _dict: + if (supported_features := _dict.get('supported_features')) is not None: args['supported_features'] = SupportedFeatures.from_dict( - _dict.get('supported_features')) + supported_features) else: raise ValueError( 'Required property \'supported_features\' not present in Voice JSON' ) - if 'customization' in _dict: - args['customization'] = CustomModel.from_dict( - _dict.get('customization')) + if (customization := _dict.get('customization')) is not None: + args['customization'] = CustomModel.from_dict(customization) return cls(**args) @classmethod @@ -3328,14 +3556,17 @@ def __ne__(self, other: 'Voice') -> bool: return not self == other -class Voices(): +class Voices: """ Information about all available voices. - :attr List[Voice] voices: A list of available voices. + :param List[Voice] voices: A list of available voices. """ - def __init__(self, voices: List['Voice']) -> None: + def __init__( + self, + voices: List['Voice'], + ) -> None: """ Initialize a Voices object. @@ -3347,8 +3578,8 @@ def __init__(self, voices: List['Voice']) -> None: def from_dict(cls, _dict: Dict) -> 'Voices': """Initialize a Voices object from a json dictionary.""" args = {} - if 'voices' in _dict: - args['voices'] = [Voice.from_dict(v) for v in _dict.get('voices')] + if (voices := _dict.get('voices')) is not None: + args['voices'] = [Voice.from_dict(v) for v in voices] else: raise ValueError( 'Required property \'voices\' not present in Voices JSON') @@ -3391,19 +3622,19 @@ def __ne__(self, other: 'Voices') -> bool: return not self == other -class Word(): +class Word: """ Information about a word for the custom model. - :attr str word: The word for the custom model. The maximum length of a word is + :param str word: The word for the custom model. The maximum length of a word is 49 characters. - :attr str translation: The phonetic or sounds-like translation for the word. A + :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. The Arabic, Chinese, Dutch, Australian English, and Korean languages support only IPA. A sounds-like translation consists of one or more words that, when combined, sound like the word. The maximum length of a translation is 499 characters. - :attr str part_of_speech: (optional) **Japanese only.** The part of speech for + :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the 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 @@ -3411,11 +3642,13 @@ class Word(): entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ - def __init__(self, - word: str, - translation: str, - *, - part_of_speech: str = None) -> None: + def __init__( + self, + word: str, + translation: str, + *, + part_of_speech: Optional[str] = None, + ) -> None: """ Initialize a Word object. @@ -3444,18 +3677,18 @@ def __init__(self, def from_dict(cls, _dict: Dict) -> 'Word': """Initialize a Word object from a json dictionary.""" args = {} - if 'word' in _dict: - args['word'] = _dict.get('word') + if (word := _dict.get('word')) is not None: + args['word'] = word else: raise ValueError( 'Required property \'word\' not present in Word JSON') - if 'translation' in _dict: - args['translation'] = _dict.get('translation') + if (translation := _dict.get('translation')) is not None: + args['translation'] = translation else: raise ValueError( 'Required property \'translation\' not present in Word JSON') - if 'part_of_speech' in _dict: - args['part_of_speech'] = _dict.get('part_of_speech') + if (part_of_speech := _dict.get('part_of_speech')) is not None: + args['part_of_speech'] = part_of_speech return cls(**args) @classmethod @@ -3501,6 +3734,7 @@ class PartOfSpeechEnum(str, Enum): see [Working with Japanese entries](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-rules#jaNotes). """ + DOSI = 'Dosi' FUKU = 'Fuku' GOBI = 'Gobi' @@ -3520,14 +3754,14 @@ class PartOfSpeechEnum(str, Enum): SUJI = 'Suji' -class Words(): +class Words: """ For the [Add custom words](#addwords) method, one or more words that are to be added or updated for the custom model and the translation for each specified word. For the [List custom words](#listwords) method, the words and their translations from the custom model. - :attr List[Word] words: The [Add custom words](#addwords) method accepts an + :param List[Word] words: The [Add custom words](#addwords) method accepts an array of `Word` objects. Each object provides a word that is to be added or updated for the custom model and the word's translation. The [List custom words](#listwords) method returns an array of `Word` objects. @@ -3536,7 +3770,10 @@ class Words(): letters. The array is empty if the custom model contains no words. """ - def __init__(self, words: List['Word']) -> None: + def __init__( + self, + words: List['Word'], + ) -> None: """ Initialize a Words object. @@ -3555,8 +3792,8 @@ def __init__(self, words: List['Word']) -> None: def from_dict(cls, _dict: Dict) -> 'Words': """Initialize a Words object from a json dictionary.""" args = {} - if 'words' in _dict: - args['words'] = [Word.from_dict(v) for v in _dict.get('words')] + if (words := _dict.get('words')) is not None: + args['words'] = [Word.from_dict(v) for v in words] else: raise ValueError( 'Required property \'words\' not present in Words JSON') diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 86aa0933f..5b307c5e9 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -62,8 +62,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -71,7 +70,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestMessage(): + +class TestMessage: """ Test Class for message """ @@ -84,11 +84,13 @@ def test_message_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/message') mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a MessageInput model message_input_model = {} @@ -164,7 +166,7 @@ def test_message_all_params(self): # Construct a dict representation of a Context model context_model = {} context_model['conversation_id'] = 'testString' - context_model['system'] = {'foo': 'bar'} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' @@ -226,14 +228,14 @@ def test_message_all_params(self): output=output, user_id=user_id, nodes_visited_details=nodes_visited_details, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'nodes_visited_details={}'.format('true' if nodes_visited_details else 'false') in query_string # Validate body params @@ -263,11 +265,13 @@ def test_message_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/message') mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -275,7 +279,7 @@ def test_message_required_params(self): # Invoke method response = _service.message( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -299,11 +303,13 @@ def test_message_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/message') mock_response = '{"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -313,7 +319,7 @@ def test_message_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.message(**req_copy) @@ -326,6 +332,7 @@ def test_message_value_error_with_retries(self): _service.disable_retries() self.test_message_value_error() + # endregion ############################################################################## # End of Service: Message @@ -336,7 +343,8 @@ def test_message_value_error_with_retries(self): ############################################################################## # region -class TestBulkClassify(): + +class TestBulkClassify: """ Test Class for bulk_classify """ @@ -349,11 +357,13 @@ def test_bulk_classify_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a BulkClassifyUtterance model bulk_classify_utterance_model = {} @@ -367,7 +377,7 @@ def test_bulk_classify_all_params(self): response = _service.bulk_classify( workspace_id, input=input, - headers={} + headers={}, ) # Check for correct operation @@ -394,11 +404,13 @@ def test_bulk_classify_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -406,7 +418,7 @@ def test_bulk_classify_required_params(self): # Invoke method response = _service.bulk_classify( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -430,11 +442,13 @@ def test_bulk_classify_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "intents": [{"intent": "intent", "confidence": 10}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -444,7 +458,7 @@ def test_bulk_classify_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.bulk_classify(**req_copy) @@ -457,6 +471,7 @@ def test_bulk_classify_value_error_with_retries(self): _service.disable_retries() self.test_bulk_classify_value_error() + # endregion ############################################################################## # End of Service: BulkClassify @@ -467,7 +482,8 @@ def test_bulk_classify_value_error_with_retries(self): ############################################################################## # region -class TestListWorkspaces(): + +class TestListWorkspaces: """ Test Class for list_workspaces """ @@ -480,14 +496,16 @@ def test_list_workspaces_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - page_limit = 38 + page_limit = 100 include_count = False sort = 'name' cursor = 'testString' @@ -500,14 +518,14 @@ def test_list_workspaces_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -532,16 +550,17 @@ def test_list_workspaces_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_workspaces() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -563,17 +582,19 @@ def test_list_workspaces_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"workspaces": [{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_workspaces(**req_copy) @@ -586,7 +607,8 @@ def test_list_workspaces_value_error_with_retries(self): _service.disable_retries() self.test_list_workspaces_value_error() -class TestCreateWorkspace(): + +class TestCreateWorkspace: """ Test Class for create_workspace """ @@ -599,11 +621,13 @@ def test_create_workspace_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -618,7 +642,7 @@ def test_create_workspace_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -628,13 +652,13 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -647,7 +671,7 @@ def test_create_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -660,7 +684,7 @@ def test_create_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -707,7 +731,7 @@ def test_create_workspace_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -745,7 +769,7 @@ def test_create_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -754,7 +778,7 @@ def test_create_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'foo': 'bar'} + create_entity_model['metadata'] = {'anyKey': 'anyValue'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -764,7 +788,7 @@ def test_create_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -786,14 +810,14 @@ def test_create_workspace_all_params(self): intents=intents, entities=entities, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -803,7 +827,7 @@ def test_create_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -827,16 +851,17 @@ def test_create_workspace_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Invoke method response = _service.create_workspace() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 @@ -858,17 +883,19 @@ def test_create_workspace_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_workspace(**req_copy) @@ -881,7 +908,8 @@ def test_create_workspace_value_error_with_retries(self): _service.disable_retries() self.test_create_workspace_value_error() -class TestGetWorkspace(): + +class TestGetWorkspace: """ Test Class for get_workspace """ @@ -894,11 +922,13 @@ def test_get_workspace_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -912,14 +942,14 @@ def test_get_workspace_all_params(self): export=export, include_audit=include_audit, sort=sort, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -942,11 +972,13 @@ def test_get_workspace_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -954,7 +986,7 @@ def test_get_workspace_required_params(self): # Invoke method response = _service.get_workspace( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -978,11 +1010,13 @@ def test_get_workspace_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -992,7 +1026,7 @@ def test_get_workspace_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_workspace(**req_copy) @@ -1005,7 +1039,8 @@ def test_get_workspace_value_error_with_retries(self): _service.disable_retries() self.test_get_workspace_value_error() -class TestUpdateWorkspace(): + +class TestUpdateWorkspace: """ Test Class for update_workspace """ @@ -1018,11 +1053,13 @@ def test_update_workspace_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -1037,7 +1074,7 @@ def test_update_workspace_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -1047,13 +1084,13 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1066,7 +1103,7 @@ def test_update_workspace_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1079,7 +1116,7 @@ def test_update_workspace_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1126,7 +1163,7 @@ def test_update_workspace_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -1164,7 +1201,7 @@ def test_update_workspace_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1173,7 +1210,7 @@ def test_update_workspace_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'foo': 'bar'} + create_entity_model['metadata'] = {'anyKey': 'anyValue'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1184,7 +1221,7 @@ def test_update_workspace_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -1209,14 +1246,14 @@ def test_update_workspace_all_params(self): entities=entities, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -1227,7 +1264,7 @@ def test_update_workspace_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -1251,11 +1288,13 @@ def test_update_workspace_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1263,7 +1302,7 @@ def test_update_workspace_required_params(self): # Invoke method response = _service.update_workspace( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -1287,11 +1326,13 @@ def test_update_workspace_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1301,7 +1342,7 @@ def test_update_workspace_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_workspace(**req_copy) @@ -1314,7 +1355,8 @@ def test_update_workspace_value_error_with_retries(self): _service.disable_retries() self.test_update_workspace_value_error() -class TestDeleteWorkspace(): + +class TestDeleteWorkspace: """ Test Class for delete_workspace """ @@ -1326,9 +1368,11 @@ def test_delete_workspace_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1336,7 +1380,7 @@ def test_delete_workspace_all_params(self): # Invoke method response = _service.delete_workspace( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -1359,9 +1403,11 @@ def test_delete_workspace_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -1371,7 +1417,7 @@ def test_delete_workspace_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_workspace(**req_copy) @@ -1384,7 +1430,8 @@ def test_delete_workspace_value_error_with_retries(self): _service.disable_retries() self.test_delete_workspace_value_error() -class TestCreateWorkspaceAsync(): + +class TestCreateWorkspaceAsync: """ Test Class for create_workspace_async """ @@ -1397,11 +1444,13 @@ def test_create_workspace_async_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -1416,7 +1465,7 @@ def test_create_workspace_async_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -1426,13 +1475,13 @@ def test_create_workspace_async_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1445,7 +1494,7 @@ def test_create_workspace_async_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1458,7 +1507,7 @@ def test_create_workspace_async_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1505,7 +1554,7 @@ def test_create_workspace_async_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -1543,7 +1592,7 @@ def test_create_workspace_async_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1552,7 +1601,7 @@ def test_create_workspace_async_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'foo': 'bar'} + create_entity_model['metadata'] = {'anyKey': 'anyValue'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1562,7 +1611,7 @@ def test_create_workspace_async_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -1582,7 +1631,7 @@ def test_create_workspace_async_all_params(self): webhooks=webhooks, intents=intents, entities=entities, - headers={} + headers={}, ) # Check for correct operation @@ -1595,7 +1644,7 @@ def test_create_workspace_async_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -1619,16 +1668,17 @@ def test_create_workspace_async_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Invoke method response = _service.create_workspace_async() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 @@ -1650,17 +1700,19 @@ def test_create_workspace_async_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces_async') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_workspace_async(**req_copy) @@ -1673,7 +1725,8 @@ def test_create_workspace_async_value_error_with_retries(self): _service.disable_retries() self.test_create_workspace_async_value_error() -class TestUpdateWorkspaceAsync(): + +class TestUpdateWorkspaceAsync: """ Test Class for update_workspace_async """ @@ -1686,11 +1739,13 @@ def test_update_workspace_async_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -1705,7 +1760,7 @@ def test_update_workspace_async_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -1715,13 +1770,13 @@ def test_update_workspace_async_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -1734,7 +1789,7 @@ def test_update_workspace_async_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -1747,7 +1802,7 @@ def test_update_workspace_async_all_params(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -1794,7 +1849,7 @@ def test_update_workspace_async_all_params(self): workspace_system_settings_model = {} workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -1832,7 +1887,7 @@ def test_update_workspace_async_all_params(self): # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -1841,7 +1896,7 @@ def test_update_workspace_async_all_params(self): create_entity_model = {} create_entity_model['entity'] = 'testString' create_entity_model['description'] = 'testString' - create_entity_model['metadata'] = {'foo': 'bar'} + create_entity_model['metadata'] = {'anyKey': 'anyValue'} create_entity_model['fuzzy_match'] = True create_entity_model['values'] = [create_value_model] @@ -1852,7 +1907,7 @@ def test_update_workspace_async_all_params(self): language = 'testString' dialog_nodes = [dialog_node_model] counterexamples = [counterexample_model] - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} learning_opt_out = False system_settings = workspace_system_settings_model webhooks = [webhook_model] @@ -1875,14 +1930,14 @@ def test_update_workspace_async_all_params(self): intents=intents, entities=entities, append=append, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string # Validate body params @@ -1892,7 +1947,7 @@ def test_update_workspace_async_all_params(self): assert req_body['language'] == 'testString' assert req_body['dialog_nodes'] == [dialog_node_model] assert req_body['counterexamples'] == [counterexample_model] - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['learning_opt_out'] == False assert req_body['system_settings'] == workspace_system_settings_model assert req_body['webhooks'] == [webhook_model] @@ -1916,11 +1971,13 @@ def test_update_workspace_async_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values workspace_id = 'testString' @@ -1928,7 +1985,7 @@ def test_update_workspace_async_required_params(self): # Invoke method response = _service.update_workspace_async( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -1952,11 +2009,13 @@ def test_update_workspace_async_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values workspace_id = 'testString' @@ -1966,7 +2025,7 @@ def test_update_workspace_async_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_workspace_async(**req_copy) @@ -1979,7 +2038,8 @@ def test_update_workspace_async_value_error_with_retries(self): _service.disable_retries() self.test_update_workspace_async_value_error() -class TestExportWorkspaceAsync(): + +class TestExportWorkspaceAsync: """ Test Class for export_workspace_async """ @@ -1992,11 +2052,13 @@ def test_export_workspace_async_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2010,14 +2072,14 @@ def test_export_workspace_async_all_params(self): include_audit=include_audit, sort=sort, verbose=verbose, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string assert 'sort={}'.format(sort) in query_string @@ -2040,11 +2102,13 @@ def test_export_workspace_async_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2052,7 +2116,7 @@ def test_export_workspace_async_required_params(self): # Invoke method response = _service.export_workspace_async( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -2076,11 +2140,13 @@ def test_export_workspace_async_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces_async/testString/export') mock_response = '{"name": "name", "description": "description", "language": "language", "workspace_id": "workspace_id", "dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "metadata": {"anyKey": "anyValue"}, "learning_opt_out": false, "system_settings": {"tooling": {"store_generic_responses": false}, "disambiguation": {"prompt": "prompt", "none_of_the_above_prompt": "none_of_the_above_prompt", "enabled": false, "sensitivity": "auto", "randomize": false, "max_suggestions": 1, "suggestion_text_policy": "suggestion_text_policy"}, "human_agent_assist": {"anyKey": "anyValue"}, "spelling_suggestions": false, "spelling_auto_correct": false, "system_entities": {"enabled": false}, "off_topic": {"enabled": false}, "nlp": {"model": "model"}}, "status": "Available", "status_errors": [{"message": "message"}], "webhooks": [{"url": "url", "name": "name", "headers": [{"name": "name", "value": "value"}]}], "intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "counts": {"intent": 6, "entity": 6, "node": 4}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2090,7 +2156,7 @@ def test_export_workspace_async_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.export_workspace_async(**req_copy) @@ -2103,6 +2169,7 @@ def test_export_workspace_async_value_error_with_retries(self): _service.disable_retries() self.test_export_workspace_async_value_error() + # endregion ############################################################################## # End of Service: Workspaces @@ -2113,7 +2180,8 @@ def test_export_workspace_async_value_error_with_retries(self): ############################################################################## # region -class TestListIntents(): + +class TestListIntents: """ Test Class for list_intents """ @@ -2126,16 +2194,18 @@ def test_list_intents_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' export = False - page_limit = 38 + page_limit = 100 include_count = False sort = 'intent' cursor = 'testString' @@ -2150,14 +2220,14 @@ def test_list_intents_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'page_limit={}'.format(page_limit) in query_string @@ -2183,11 +2253,13 @@ def test_list_intents_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2195,7 +2267,7 @@ def test_list_intents_required_params(self): # Invoke method response = _service.list_intents( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -2219,11 +2291,13 @@ def test_list_intents_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intents": [{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2233,7 +2307,7 @@ def test_list_intents_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_intents(**req_copy) @@ -2246,7 +2320,8 @@ def test_list_intents_value_error_with_retries(self): _service.disable_retries() self.test_list_intents_value_error() -class TestCreateIntent(): + +class TestCreateIntent: """ Test Class for create_intent """ @@ -2259,11 +2334,13 @@ def test_create_intent_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2289,14 +2366,14 @@ def test_create_intent_all_params(self): description=description, examples=examples, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -2322,11 +2399,13 @@ def test_create_intent_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2350,7 +2429,7 @@ def test_create_intent_required_params(self): intent, description=description, examples=examples, - headers={} + headers={}, ) # Check for correct operation @@ -2379,11 +2458,13 @@ def test_create_intent_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2407,7 +2488,7 @@ def test_create_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_intent(**req_copy) @@ -2420,7 +2501,8 @@ def test_create_intent_value_error_with_retries(self): _service.disable_retries() self.test_create_intent_value_error() -class TestGetIntent(): + +class TestGetIntent: """ Test Class for get_intent """ @@ -2433,11 +2515,13 @@ def test_get_intent_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2451,14 +2535,14 @@ def test_get_intent_all_params(self): intent, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -2480,11 +2564,13 @@ def test_get_intent_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2494,7 +2580,7 @@ def test_get_intent_required_params(self): response = _service.get_intent( workspace_id, intent, - headers={} + headers={}, ) # Check for correct operation @@ -2518,11 +2604,13 @@ def test_get_intent_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2534,7 +2622,7 @@ def test_get_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_intent(**req_copy) @@ -2547,7 +2635,8 @@ def test_get_intent_value_error_with_retries(self): _service.disable_retries() self.test_get_intent_value_error() -class TestUpdateIntent(): + +class TestUpdateIntent: """ Test Class for update_intent """ @@ -2560,11 +2649,13 @@ def test_update_intent_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2594,14 +2685,14 @@ def test_update_intent_all_params(self): new_examples=new_examples, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -2628,11 +2719,13 @@ def test_update_intent_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2658,7 +2751,7 @@ def test_update_intent_required_params(self): new_intent=new_intent, new_description=new_description, new_examples=new_examples, - headers={} + headers={}, ) # Check for correct operation @@ -2687,11 +2780,13 @@ def test_update_intent_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') mock_response = '{"intent": "intent", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2716,7 +2811,7 @@ def test_update_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_intent(**req_copy) @@ -2729,7 +2824,8 @@ def test_update_intent_value_error_with_retries(self): _service.disable_retries() self.test_update_intent_value_error() -class TestDeleteIntent(): + +class TestDeleteIntent: """ Test Class for delete_intent """ @@ -2741,9 +2837,11 @@ def test_delete_intent_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2753,7 +2851,7 @@ def test_delete_intent_all_params(self): response = _service.delete_intent( workspace_id, intent, - headers={} + headers={}, ) # Check for correct operation @@ -2776,9 +2874,11 @@ def test_delete_intent_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2790,7 +2890,7 @@ def test_delete_intent_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_intent(**req_copy) @@ -2803,6 +2903,7 @@ def test_delete_intent_value_error_with_retries(self): _service.disable_retries() self.test_delete_intent_value_error() + # endregion ############################################################################## # End of Service: Intents @@ -2813,7 +2914,8 @@ def test_delete_intent_value_error_with_retries(self): ############################################################################## # region -class TestListExamples(): + +class TestListExamples: """ Test Class for list_examples """ @@ -2826,16 +2928,18 @@ def test_list_examples_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' intent = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'text' cursor = 'testString' @@ -2850,14 +2954,14 @@ def test_list_examples_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -2882,11 +2986,13 @@ def test_list_examples_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2896,7 +3002,7 @@ def test_list_examples_required_params(self): response = _service.list_examples( workspace_id, intent, - headers={} + headers={}, ) # Check for correct operation @@ -2920,11 +3026,13 @@ def test_list_examples_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"examples": [{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -2936,7 +3044,7 @@ def test_list_examples_value_error(self): "intent": intent, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_examples(**req_copy) @@ -2949,7 +3057,8 @@ def test_list_examples_value_error_with_retries(self): _service.disable_retries() self.test_list_examples_value_error() -class TestCreateExample(): + +class TestCreateExample: """ Test Class for create_example """ @@ -2962,11 +3071,13 @@ def test_create_example_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -2987,14 +3098,14 @@ def test_create_example_all_params(self): text, mentions=mentions, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -3019,11 +3130,13 @@ def test_create_example_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -3042,7 +3155,7 @@ def test_create_example_required_params(self): intent, text, mentions=mentions, - headers={} + headers={}, ) # Check for correct operation @@ -3070,11 +3183,13 @@ def test_create_example_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -3094,7 +3209,7 @@ def test_create_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_example(**req_copy) @@ -3107,7 +3222,8 @@ def test_create_example_value_error_with_retries(self): _service.disable_retries() self.test_create_example_value_error() -class TestGetExample(): + +class TestGetExample: """ Test Class for get_example """ @@ -3120,11 +3236,13 @@ def test_get_example_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3138,14 +3256,14 @@ def test_get_example_all_params(self): intent, text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -3166,11 +3284,13 @@ def test_get_example_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3182,7 +3302,7 @@ def test_get_example_required_params(self): workspace_id, intent, text, - headers={} + headers={}, ) # Check for correct operation @@ -3206,11 +3326,13 @@ def test_get_example_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3224,7 +3346,7 @@ def test_get_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_example(**req_copy) @@ -3237,7 +3359,8 @@ def test_get_example_value_error_with_retries(self): _service.disable_retries() self.test_get_example_value_error() -class TestUpdateExample(): + +class TestUpdateExample: """ Test Class for update_example """ @@ -3250,11 +3373,13 @@ def test_update_example_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -3277,14 +3402,14 @@ def test_update_example_all_params(self): new_text=new_text, new_mentions=new_mentions, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -3309,11 +3434,13 @@ def test_update_example_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -3334,7 +3461,7 @@ def test_update_example_required_params(self): text, new_text=new_text, new_mentions=new_mentions, - headers={} + headers={}, ) # Check for correct operation @@ -3362,11 +3489,13 @@ def test_update_example_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') mock_response = '{"text": "text", "mentions": [{"entity": "entity", "location": [8]}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Mention model mention_model = {} @@ -3387,7 +3516,7 @@ def test_update_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_example(**req_copy) @@ -3400,7 +3529,8 @@ def test_update_example_value_error_with_retries(self): _service.disable_retries() self.test_update_example_value_error() -class TestDeleteExample(): + +class TestDeleteExample: """ Test Class for delete_example """ @@ -3412,9 +3542,11 @@ def test_delete_example_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3426,7 +3558,7 @@ def test_delete_example_all_params(self): workspace_id, intent, text, - headers={} + headers={}, ) # Check for correct operation @@ -3449,9 +3581,11 @@ def test_delete_example_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/intents/testString/examples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3465,7 +3599,7 @@ def test_delete_example_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_example(**req_copy) @@ -3478,6 +3612,7 @@ def test_delete_example_value_error_with_retries(self): _service.disable_retries() self.test_delete_example_value_error() + # endregion ############################################################################## # End of Service: Examples @@ -3488,7 +3623,8 @@ def test_delete_example_value_error_with_retries(self): ############################################################################## # region -class TestListCounterexamples(): + +class TestListCounterexamples: """ Test Class for list_counterexamples """ @@ -3501,15 +3637,17 @@ def test_list_counterexamples_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'text' cursor = 'testString' @@ -3523,14 +3661,14 @@ def test_list_counterexamples_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -3555,11 +3693,13 @@ def test_list_counterexamples_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3567,7 +3707,7 @@ def test_list_counterexamples_required_params(self): # Invoke method response = _service.list_counterexamples( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -3591,11 +3731,13 @@ def test_list_counterexamples_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"counterexamples": [{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3605,7 +3747,7 @@ def test_list_counterexamples_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_counterexamples(**req_copy) @@ -3618,7 +3760,8 @@ def test_list_counterexamples_value_error_with_retries(self): _service.disable_retries() self.test_list_counterexamples_value_error() -class TestCreateCounterexample(): + +class TestCreateCounterexample: """ Test Class for create_counterexample """ @@ -3631,11 +3774,13 @@ def test_create_counterexample_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -3647,14 +3792,14 @@ def test_create_counterexample_all_params(self): workspace_id, text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -3678,11 +3823,13 @@ def test_create_counterexample_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -3692,7 +3839,7 @@ def test_create_counterexample_required_params(self): response = _service.create_counterexample( workspace_id, text, - headers={} + headers={}, ) # Check for correct operation @@ -3719,11 +3866,13 @@ def test_create_counterexample_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -3735,7 +3884,7 @@ def test_create_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_counterexample(**req_copy) @@ -3748,7 +3897,8 @@ def test_create_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_create_counterexample_value_error() -class TestGetCounterexample(): + +class TestGetCounterexample: """ Test Class for get_counterexample """ @@ -3761,11 +3911,13 @@ def test_get_counterexample_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3777,14 +3929,14 @@ def test_get_counterexample_all_params(self): workspace_id, text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -3805,11 +3957,13 @@ def test_get_counterexample_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3819,7 +3973,7 @@ def test_get_counterexample_required_params(self): response = _service.get_counterexample( workspace_id, text, - headers={} + headers={}, ) # Check for correct operation @@ -3843,11 +3997,13 @@ def test_get_counterexample_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3859,7 +4015,7 @@ def test_get_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_counterexample(**req_copy) @@ -3872,7 +4028,8 @@ def test_get_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_get_counterexample_value_error() -class TestUpdateCounterexample(): + +class TestUpdateCounterexample: """ Test Class for update_counterexample """ @@ -3885,11 +4042,13 @@ def test_update_counterexample_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3903,14 +4062,14 @@ def test_update_counterexample_all_params(self): text, new_text=new_text, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -3934,11 +4093,13 @@ def test_update_counterexample_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3950,7 +4111,7 @@ def test_update_counterexample_required_params(self): workspace_id, text, new_text=new_text, - headers={} + headers={}, ) # Check for correct operation @@ -3977,11 +4138,13 @@ def test_update_counterexample_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') mock_response = '{"text": "text", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -3994,7 +4157,7 @@ def test_update_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_counterexample(**req_copy) @@ -4007,7 +4170,8 @@ def test_update_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_update_counterexample_value_error() -class TestDeleteCounterexample(): + +class TestDeleteCounterexample: """ Test Class for delete_counterexample """ @@ -4019,9 +4183,11 @@ def test_delete_counterexample_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4031,7 +4197,7 @@ def test_delete_counterexample_all_params(self): response = _service.delete_counterexample( workspace_id, text, - headers={} + headers={}, ) # Check for correct operation @@ -4054,9 +4220,11 @@ def test_delete_counterexample_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/counterexamples/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4068,7 +4236,7 @@ def test_delete_counterexample_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_counterexample(**req_copy) @@ -4081,6 +4249,7 @@ def test_delete_counterexample_value_error_with_retries(self): _service.disable_retries() self.test_delete_counterexample_value_error() + # endregion ############################################################################## # End of Service: Counterexamples @@ -4091,7 +4260,8 @@ def test_delete_counterexample_value_error_with_retries(self): ############################################################################## # region -class TestListEntities(): + +class TestListEntities: """ Test Class for list_entities """ @@ -4104,16 +4274,18 @@ def test_list_entities_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' export = False - page_limit = 38 + page_limit = 100 include_count = False sort = 'entity' cursor = 'testString' @@ -4128,14 +4300,14 @@ def test_list_entities_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'page_limit={}'.format(page_limit) in query_string @@ -4161,11 +4333,13 @@ def test_list_entities_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4173,7 +4347,7 @@ def test_list_entities_required_params(self): # Invoke method response = _service.list_entities( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -4197,11 +4371,13 @@ def test_list_entities_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entities": [{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4211,7 +4387,7 @@ def test_list_entities_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_entities(**req_copy) @@ -4224,7 +4400,8 @@ def test_list_entities_value_error_with_retries(self): _service.disable_retries() self.test_list_entities_value_error() -class TestCreateEntity(): + +class TestCreateEntity: """ Test Class for create_entity """ @@ -4237,16 +4414,18 @@ def test_create_entity_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4255,7 +4434,7 @@ def test_create_entity_all_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} fuzzy_match = True values = [create_value_model] include_audit = False @@ -4269,21 +4448,21 @@ def test_create_entity_all_params(self): fuzzy_match=fuzzy_match, values=values, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4304,16 +4483,18 @@ def test_create_entity_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4322,7 +4503,7 @@ def test_create_entity_required_params(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} fuzzy_match = True values = [create_value_model] @@ -4334,7 +4515,7 @@ def test_create_entity_required_params(self): metadata=metadata, fuzzy_match=fuzzy_match, values=values, - headers={} + headers={}, ) # Check for correct operation @@ -4344,7 +4525,7 @@ def test_create_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4365,16 +4546,18 @@ def test_create_entity_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4383,7 +4566,7 @@ def test_create_entity_value_error(self): workspace_id = 'testString' entity = 'testString' description = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} fuzzy_match = True values = [create_value_model] @@ -4393,7 +4576,7 @@ def test_create_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_entity(**req_copy) @@ -4406,7 +4589,8 @@ def test_create_entity_value_error_with_retries(self): _service.disable_retries() self.test_create_entity_value_error() -class TestGetEntity(): + +class TestGetEntity: """ Test Class for get_entity """ @@ -4419,11 +4603,13 @@ def test_get_entity_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4437,14 +4623,14 @@ def test_get_entity_all_params(self): entity, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -4466,11 +4652,13 @@ def test_get_entity_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4480,7 +4668,7 @@ def test_get_entity_required_params(self): response = _service.get_entity( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -4504,11 +4692,13 @@ def test_get_entity_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4520,7 +4710,7 @@ def test_get_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_entity(**req_copy) @@ -4533,7 +4723,8 @@ def test_get_entity_value_error_with_retries(self): _service.disable_retries() self.test_get_entity_value_error() -class TestUpdateEntity(): + +class TestUpdateEntity: """ Test Class for update_entity """ @@ -4546,16 +4737,18 @@ def test_update_entity_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4565,7 +4758,7 @@ def test_update_entity_all_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_fuzzy_match = True new_values = [create_value_model] append = False @@ -4582,14 +4775,14 @@ def test_update_entity_all_params(self): new_values=new_values, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -4597,7 +4790,7 @@ def test_update_entity_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4618,16 +4811,18 @@ def test_update_entity_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4637,7 +4832,7 @@ def test_update_entity_required_params(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_fuzzy_match = True new_values = [create_value_model] @@ -4650,7 +4845,7 @@ def test_update_entity_required_params(self): new_metadata=new_metadata, new_fuzzy_match=new_fuzzy_match, new_values=new_values, - headers={} + headers={}, ) # Check for correct operation @@ -4660,7 +4855,7 @@ def test_update_entity_required_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['entity'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['fuzzy_match'] == True assert req_body['values'] == [create_value_model] @@ -4681,16 +4876,18 @@ def test_update_entity_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') mock_response = '{"entity": "entity", "description": "description", "metadata": {"anyKey": "anyValue"}, "fuzzy_match": false, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CreateValue model create_value_model = {} create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -4700,7 +4897,7 @@ def test_update_entity_value_error(self): entity = 'testString' new_entity = 'testString' new_description = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_fuzzy_match = True new_values = [create_value_model] @@ -4710,7 +4907,7 @@ def test_update_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_entity(**req_copy) @@ -4723,7 +4920,8 @@ def test_update_entity_value_error_with_retries(self): _service.disable_retries() self.test_update_entity_value_error() -class TestDeleteEntity(): + +class TestDeleteEntity: """ Test Class for delete_entity """ @@ -4735,9 +4933,11 @@ def test_delete_entity_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4747,7 +4947,7 @@ def test_delete_entity_all_params(self): response = _service.delete_entity( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -4770,9 +4970,11 @@ def test_delete_entity_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4784,7 +4986,7 @@ def test_delete_entity_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_entity(**req_copy) @@ -4797,6 +4999,7 @@ def test_delete_entity_value_error_with_retries(self): _service.disable_retries() self.test_delete_entity_value_error() + # endregion ############################################################################## # End of Service: Entities @@ -4807,7 +5010,8 @@ def test_delete_entity_value_error_with_retries(self): ############################################################################## # region -class TestListMentions(): + +class TestListMentions: """ Test Class for list_mentions """ @@ -4820,11 +5024,13 @@ def test_list_mentions_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4838,14 +5044,14 @@ def test_list_mentions_all_params(self): entity, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -4867,11 +5073,13 @@ def test_list_mentions_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4881,7 +5089,7 @@ def test_list_mentions_required_params(self): response = _service.list_mentions( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -4905,11 +5113,13 @@ def test_list_mentions_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/mentions') mock_response = '{"examples": [{"text": "text", "intent": "intent", "location": [8]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -4921,7 +5131,7 @@ def test_list_mentions_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_mentions(**req_copy) @@ -4934,6 +5144,7 @@ def test_list_mentions_value_error_with_retries(self): _service.disable_retries() self.test_list_mentions_value_error() + # endregion ############################################################################## # End of Service: Mentions @@ -4944,7 +5155,8 @@ def test_list_mentions_value_error_with_retries(self): ############################################################################## # region -class TestListValues(): + +class TestListValues: """ Test Class for list_values """ @@ -4957,17 +5169,19 @@ def test_list_values_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' export = False - page_limit = 38 + page_limit = 100 include_count = False sort = 'value' cursor = 'testString' @@ -4983,14 +5197,14 @@ def test_list_values_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'page_limit={}'.format(page_limit) in query_string @@ -5016,11 +5230,13 @@ def test_list_values_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5030,7 +5246,7 @@ def test_list_values_required_params(self): response = _service.list_values( workspace_id, entity, - headers={} + headers={}, ) # Check for correct operation @@ -5054,11 +5270,13 @@ def test_list_values_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"values": [{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5070,7 +5288,7 @@ def test_list_values_value_error(self): "entity": entity, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_values(**req_copy) @@ -5083,7 +5301,8 @@ def test_list_values_value_error_with_retries(self): _service.disable_retries() self.test_list_values_value_error() -class TestCreateValue(): + +class TestCreateValue: """ Test Class for create_value """ @@ -5096,17 +5315,19 @@ def test_create_value_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -5122,20 +5343,20 @@ def test_create_value_all_params(self): synonyms=synonyms, patterns=patterns, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5157,17 +5378,19 @@ def test_create_value_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -5181,7 +5404,7 @@ def test_create_value_required_params(self): type=type, synonyms=synonyms, patterns=patterns, - headers={} + headers={}, ) # Check for correct operation @@ -5190,7 +5413,7 @@ def test_create_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5212,17 +5435,19 @@ def test_create_value_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} type = 'synonyms' synonyms = ['testString'] patterns = ['testString'] @@ -5234,7 +5459,7 @@ def test_create_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_value(**req_copy) @@ -5247,7 +5472,8 @@ def test_create_value_value_error_with_retries(self): _service.disable_retries() self.test_create_value_value_error() -class TestGetValue(): + +class TestGetValue: """ Test Class for get_value """ @@ -5260,11 +5486,13 @@ def test_get_value_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5280,14 +5508,14 @@ def test_get_value_all_params(self): value, export=export, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'export={}'.format('true' if export else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -5309,11 +5537,13 @@ def test_get_value_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5325,7 +5555,7 @@ def test_get_value_required_params(self): workspace_id, entity, value, - headers={} + headers={}, ) # Check for correct operation @@ -5349,11 +5579,13 @@ def test_get_value_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5367,7 +5599,7 @@ def test_get_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_value(**req_copy) @@ -5380,7 +5612,8 @@ def test_get_value_value_error_with_retries(self): _service.disable_retries() self.test_get_value_value_error() -class TestUpdateValue(): + +class TestUpdateValue: """ Test Class for update_value """ @@ -5393,18 +5626,20 @@ def test_update_value_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -5423,21 +5658,21 @@ def test_update_value_all_params(self): new_patterns=new_patterns, append=append, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'append={}'.format('true' if append else 'false') in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5459,18 +5694,20 @@ def test_update_value_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -5485,7 +5722,7 @@ def test_update_value_required_params(self): new_type=new_type, new_synonyms=new_synonyms, new_patterns=new_patterns, - headers={} + headers={}, ) # Check for correct operation @@ -5494,7 +5731,7 @@ def test_update_value_required_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['value'] == 'testString' - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['type'] == 'synonyms' assert req_body['synonyms'] == ['testString'] assert req_body['patterns'] == ['testString'] @@ -5516,18 +5753,20 @@ def test_update_value_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') mock_response = '{"value": "value", "metadata": {"anyKey": "anyValue"}, "type": "synonyms", "synonyms": ["synonym"], "patterns": ["pattern"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' new_value = 'testString' - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_type = 'synonyms' new_synonyms = ['testString'] new_patterns = ['testString'] @@ -5539,7 +5778,7 @@ def test_update_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_value(**req_copy) @@ -5552,7 +5791,8 @@ def test_update_value_value_error_with_retries(self): _service.disable_retries() self.test_update_value_value_error() -class TestDeleteValue(): + +class TestDeleteValue: """ Test Class for delete_value """ @@ -5564,9 +5804,11 @@ def test_delete_value_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5578,7 +5820,7 @@ def test_delete_value_all_params(self): workspace_id, entity, value, - headers={} + headers={}, ) # Check for correct operation @@ -5601,9 +5843,11 @@ def test_delete_value_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5617,7 +5861,7 @@ def test_delete_value_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_value(**req_copy) @@ -5630,6 +5874,7 @@ def test_delete_value_value_error_with_retries(self): _service.disable_retries() self.test_delete_value_value_error() + # endregion ############################################################################## # End of Service: Values @@ -5640,7 +5885,8 @@ def test_delete_value_value_error_with_retries(self): ############################################################################## # region -class TestListSynonyms(): + +class TestListSynonyms: """ Test Class for list_synonyms """ @@ -5653,17 +5899,19 @@ def test_list_synonyms_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' entity = 'testString' value = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'synonym' cursor = 'testString' @@ -5679,14 +5927,14 @@ def test_list_synonyms_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -5711,11 +5959,13 @@ def test_list_synonyms_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5727,7 +5977,7 @@ def test_list_synonyms_required_params(self): workspace_id, entity, value, - headers={} + headers={}, ) # Check for correct operation @@ -5751,11 +6001,13 @@ def test_list_synonyms_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonyms": [{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5769,7 +6021,7 @@ def test_list_synonyms_value_error(self): "value": value, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_synonyms(**req_copy) @@ -5782,7 +6034,8 @@ def test_list_synonyms_value_error_with_retries(self): _service.disable_retries() self.test_list_synonyms_value_error() -class TestCreateSynonym(): + +class TestCreateSynonym: """ Test Class for create_synonym """ @@ -5795,11 +6048,13 @@ def test_create_synonym_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -5815,14 +6070,14 @@ def test_create_synonym_all_params(self): value, synonym, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -5846,11 +6101,13 @@ def test_create_synonym_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -5864,7 +6121,7 @@ def test_create_synonym_required_params(self): entity, value, synonym, - headers={} + headers={}, ) # Check for correct operation @@ -5891,11 +6148,13 @@ def test_create_synonym_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values workspace_id = 'testString' @@ -5911,7 +6170,7 @@ def test_create_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_synonym(**req_copy) @@ -5924,7 +6183,8 @@ def test_create_synonym_value_error_with_retries(self): _service.disable_retries() self.test_create_synonym_value_error() -class TestGetSynonym(): + +class TestGetSynonym: """ Test Class for get_synonym """ @@ -5937,11 +6197,13 @@ def test_get_synonym_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -5957,14 +6219,14 @@ def test_get_synonym_all_params(self): value, synonym, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -5985,11 +6247,13 @@ def test_get_synonym_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6003,7 +6267,7 @@ def test_get_synonym_required_params(self): entity, value, synonym, - headers={} + headers={}, ) # Check for correct operation @@ -6027,11 +6291,13 @@ def test_get_synonym_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6047,7 +6313,7 @@ def test_get_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_synonym(**req_copy) @@ -6060,7 +6326,8 @@ def test_get_synonym_value_error_with_retries(self): _service.disable_retries() self.test_get_synonym_value_error() -class TestUpdateSynonym(): + +class TestUpdateSynonym: """ Test Class for update_synonym """ @@ -6073,11 +6340,13 @@ def test_update_synonym_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6095,14 +6364,14 @@ def test_update_synonym_all_params(self): synonym, new_synonym=new_synonym, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -6126,11 +6395,13 @@ def test_update_synonym_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6146,7 +6417,7 @@ def test_update_synonym_required_params(self): value, synonym, new_synonym=new_synonym, - headers={} + headers={}, ) # Check for correct operation @@ -6173,11 +6444,13 @@ def test_update_synonym_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') mock_response = '{"synonym": "synonym", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6194,7 +6467,7 @@ def test_update_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_synonym(**req_copy) @@ -6207,7 +6480,8 @@ def test_update_synonym_value_error_with_retries(self): _service.disable_retries() self.test_update_synonym_value_error() -class TestDeleteSynonym(): + +class TestDeleteSynonym: """ Test Class for delete_synonym """ @@ -6219,9 +6493,11 @@ def test_delete_synonym_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6235,7 +6511,7 @@ def test_delete_synonym_all_params(self): entity, value, synonym, - headers={} + headers={}, ) # Check for correct operation @@ -6258,9 +6534,11 @@ def test_delete_synonym_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/entities/testString/values/testString/synonyms/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6276,7 +6554,7 @@ def test_delete_synonym_value_error(self): "synonym": synonym, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_synonym(**req_copy) @@ -6289,6 +6567,7 @@ def test_delete_synonym_value_error_with_retries(self): _service.disable_retries() self.test_delete_synonym_value_error() + # endregion ############################################################################## # End of Service: Synonyms @@ -6299,7 +6578,8 @@ def test_delete_synonym_value_error_with_retries(self): ############################################################################## # region -class TestListDialogNodes(): + +class TestListDialogNodes: """ Test Class for list_dialog_nodes """ @@ -6312,15 +6592,17 @@ def test_list_dialog_nodes_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'dialog_node' cursor = 'testString' @@ -6334,14 +6616,14 @@ def test_list_dialog_nodes_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -6366,11 +6648,13 @@ def test_list_dialog_nodes_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6378,7 +6662,7 @@ def test_list_dialog_nodes_required_params(self): # Invoke method response = _service.list_dialog_nodes( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -6402,11 +6686,13 @@ def test_list_dialog_nodes_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_nodes": [{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6416,7 +6702,7 @@ def test_list_dialog_nodes_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_dialog_nodes(**req_copy) @@ -6429,7 +6715,8 @@ def test_list_dialog_nodes_value_error_with_retries(self): _service.disable_retries() self.test_list_dialog_nodes_value_error() -class TestCreateDialogNode(): + +class TestCreateDialogNode: """ Test Class for create_dialog_node """ @@ -6442,11 +6729,13 @@ def test_create_dialog_node_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -6461,7 +6750,7 @@ def test_create_dialog_node_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6471,13 +6760,13 @@ def test_create_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6490,7 +6779,7 @@ def test_create_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6503,7 +6792,7 @@ def test_create_dialog_node_all_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6540,14 +6829,14 @@ def test_create_dialog_node_all_params(self): user_label=user_label, disambiguation_opt_out=disambiguation_opt_out, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -6559,7 +6848,7 @@ def test_create_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6589,11 +6878,13 @@ def test_create_dialog_node_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -6608,7 +6899,7 @@ def test_create_dialog_node_required_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6618,13 +6909,13 @@ def test_create_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6637,7 +6928,7 @@ def test_create_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6650,7 +6941,7 @@ def test_create_dialog_node_required_params(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6685,7 +6976,7 @@ def test_create_dialog_node_required_params(self): digress_out_slots=digress_out_slots, user_label=user_label, disambiguation_opt_out=disambiguation_opt_out, - headers={} + headers={}, ) # Check for correct operation @@ -6700,7 +6991,7 @@ def test_create_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -6730,11 +7021,13 @@ def test_create_dialog_node_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -6749,7 +7042,7 @@ def test_create_dialog_node_value_error(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6759,13 +7052,13 @@ def test_create_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -6778,7 +7071,7 @@ def test_create_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -6791,7 +7084,7 @@ def test_create_dialog_node_value_error(self): previous_sibling = 'testString' output = dialog_node_output_model context = dialog_node_context_model - metadata = {'foo': 'bar'} + metadata = {'anyKey': 'anyValue'} next_step = dialog_node_next_step_model title = 'testString' type = 'standard' @@ -6810,7 +7103,7 @@ def test_create_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_dialog_node(**req_copy) @@ -6823,7 +7116,8 @@ def test_create_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_create_dialog_node_value_error() -class TestGetDialogNode(): + +class TestGetDialogNode: """ Test Class for get_dialog_node """ @@ -6836,11 +7130,13 @@ def test_get_dialog_node_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6852,14 +7148,14 @@ def test_get_dialog_node_all_params(self): workspace_id, dialog_node, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -6880,11 +7176,13 @@ def test_get_dialog_node_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6894,7 +7192,7 @@ def test_get_dialog_node_required_params(self): response = _service.get_dialog_node( workspace_id, dialog_node, - headers={} + headers={}, ) # Check for correct operation @@ -6918,11 +7216,13 @@ def test_get_dialog_node_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -6934,7 +7234,7 @@ def test_get_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_dialog_node(**req_copy) @@ -6947,7 +7247,8 @@ def test_get_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_get_dialog_node_value_error() -class TestUpdateDialogNode(): + +class TestUpdateDialogNode: """ Test Class for update_dialog_node """ @@ -6960,11 +7261,13 @@ def test_update_dialog_node_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -6979,7 +7282,7 @@ def test_update_dialog_node_all_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -6989,13 +7292,13 @@ def test_update_dialog_node_all_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -7008,7 +7311,7 @@ def test_update_dialog_node_all_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7022,7 +7325,7 @@ def test_update_dialog_node_all_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -7060,14 +7363,14 @@ def test_update_dialog_node_all_params(self): new_user_label=new_user_label, new_disambiguation_opt_out=new_disambiguation_opt_out, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -7079,7 +7382,7 @@ def test_update_dialog_node_all_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -7109,11 +7412,13 @@ def test_update_dialog_node_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -7128,7 +7433,7 @@ def test_update_dialog_node_required_params(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -7138,13 +7443,13 @@ def test_update_dialog_node_required_params(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -7157,7 +7462,7 @@ def test_update_dialog_node_required_params(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7171,7 +7476,7 @@ def test_update_dialog_node_required_params(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -7207,7 +7512,7 @@ def test_update_dialog_node_required_params(self): new_digress_out_slots=new_digress_out_slots, new_user_label=new_user_label, new_disambiguation_opt_out=new_disambiguation_opt_out, - headers={} + headers={}, ) # Check for correct operation @@ -7222,7 +7527,7 @@ def test_update_dialog_node_required_params(self): assert req_body['previous_sibling'] == 'testString' assert req_body['output'] == dialog_node_output_model assert req_body['context'] == dialog_node_context_model - assert req_body['metadata'] == {'foo': 'bar'} + assert req_body['metadata'] == {'anyKey': 'anyValue'} assert req_body['next_step'] == dialog_node_next_step_model assert req_body['title'] == 'testString' assert req_body['type'] == 'standard' @@ -7252,11 +7557,13 @@ def test_update_dialog_node_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') mock_response = '{"dialog_node": "dialog_node", "description": "description", "conditions": "conditions", "parent": "parent", "previous_sibling": "previous_sibling", "output": {"generic": [{"response_type": "text", "values": [{"text": "text"}], "selection_policy": "sequential", "delimiter": "\n", "channels": [{"channel": "chat"}]}], "integrations": {"mapKey": {"anyKey": "anyValue"}}, "modifiers": {"overwrite": true}}, "context": {"integrations": {"mapKey": {"anyKey": "anyValue"}}}, "metadata": {"anyKey": "anyValue"}, "next_step": {"behavior": "get_user_input", "dialog_node": "dialog_node", "selector": "condition"}, "title": "title", "type": "standard", "event_name": "focus", "variable": "variable", "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "digress_in": "not_available", "digress_out": "allow_returning", "digress_out_slots": "not_allowed", "user_label": "user_label", "disambiguation_opt_out": false, "disabled": true, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a DialogNodeOutputTextValuesElement model dialog_node_output_text_values_element_model = {} @@ -7271,7 +7578,7 @@ def test_update_dialog_node_value_error(self): dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] # Construct a dict representation of a DialogNodeOutputModifiers model @@ -7281,13 +7588,13 @@ def test_update_dialog_node_value_error(self): # Construct a dict representation of a DialogNodeOutput model dialog_node_output_model = {} dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeContext model dialog_node_context_model = {} - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' # Construct a dict representation of a DialogNodeNextStep model @@ -7300,7 +7607,7 @@ def test_update_dialog_node_value_error(self): dialog_node_action_model = {} dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -7314,7 +7621,7 @@ def test_update_dialog_node_value_error(self): new_previous_sibling = 'testString' new_output = dialog_node_output_model new_context = dialog_node_context_model - new_metadata = {'foo': 'bar'} + new_metadata = {'anyKey': 'anyValue'} new_next_step = dialog_node_next_step_model new_title = 'testString' new_type = 'standard' @@ -7333,7 +7640,7 @@ def test_update_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_dialog_node(**req_copy) @@ -7346,7 +7653,8 @@ def test_update_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_update_dialog_node_value_error() -class TestDeleteDialogNode(): + +class TestDeleteDialogNode: """ Test Class for delete_dialog_node """ @@ -7358,9 +7666,11 @@ def test_delete_dialog_node_all_params(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -7370,7 +7680,7 @@ def test_delete_dialog_node_all_params(self): response = _service.delete_dialog_node( workspace_id, dialog_node, - headers={} + headers={}, ) # Check for correct operation @@ -7393,9 +7703,11 @@ def test_delete_dialog_node_value_error(self): """ # Set up mock url = preprocess_url('/v1/workspaces/testString/dialog_nodes/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -7407,7 +7719,7 @@ def test_delete_dialog_node_value_error(self): "dialog_node": dialog_node, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_dialog_node(**req_copy) @@ -7420,6 +7732,7 @@ def test_delete_dialog_node_value_error_with_retries(self): _service.disable_retries() self.test_delete_dialog_node_value_error() + # endregion ############################################################################## # End of Service: DialogNodes @@ -7430,7 +7743,8 @@ def test_delete_dialog_node_value_error_with_retries(self): ############################################################################## # region -class TestListLogs(): + +class TestListLogs: """ Test Class for list_logs """ @@ -7443,17 +7757,19 @@ def test_list_logs_all_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' sort = 'testString' filter = 'testString' - page_limit = 38 + page_limit = 100 cursor = 'testString' # Invoke method @@ -7463,14 +7779,14 @@ def test_list_logs_all_params(self): filter=filter, page_limit=page_limit, cursor=cursor, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'sort={}'.format(sort) in query_string assert 'filter={}'.format(filter) in query_string @@ -7494,11 +7810,13 @@ def test_list_logs_required_params(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -7506,7 +7824,7 @@ def test_list_logs_required_params(self): # Invoke method response = _service.list_logs( workspace_id, - headers={} + headers={}, ) # Check for correct operation @@ -7530,11 +7848,13 @@ def test_list_logs_value_error(self): # Set up mock url = preprocess_url('/v1/workspaces/testString/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values workspace_id = 'testString' @@ -7544,7 +7864,7 @@ def test_list_logs_value_error(self): "workspace_id": workspace_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_logs(**req_copy) @@ -7557,7 +7877,8 @@ def test_list_logs_value_error_with_retries(self): _service.disable_retries() self.test_list_logs_value_error() -class TestListAllLogs(): + +class TestListAllLogs: """ Test Class for list_all_logs """ @@ -7570,16 +7891,18 @@ def test_list_all_logs_all_params(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values filter = 'testString' sort = 'testString' - page_limit = 38 + page_limit = 100 cursor = 'testString' # Invoke method @@ -7588,14 +7911,14 @@ def test_list_all_logs_all_params(self): sort=sort, page_limit=page_limit, cursor=cursor, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string assert 'sort={}'.format(sort) in query_string @@ -7619,11 +7942,13 @@ def test_list_all_logs_required_params(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values filter = 'testString' @@ -7631,14 +7956,14 @@ def test_list_all_logs_required_params(self): # Invoke method response = _service.list_all_logs( filter, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string @@ -7659,11 +7984,13 @@ def test_list_all_logs_value_error(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"logs": [{"request": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "response": {"input": {"text": "text", "spelling_suggestions": false, "spelling_auto_correct": false, "suggested_text": "suggested_text", "original_text": "original_text"}, "intents": [{"intent": "intent", "confidence": 10}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}}], "alternate_intents": false, "context": {"conversation_id": "conversation_id", "system": {"anyKey": "anyValue"}, "metadata": {"deployment": "deployment", "user_id": "user_id"}}, "output": {"nodes_visited": ["nodes_visited"], "nodes_visited_details": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "msg": "msg", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "chat"}]}]}, "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "user_id": "user_id"}, "log_id": "log_id", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "workspace_id": "workspace_id", "language": "language"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values filter = 'testString' @@ -7673,7 +8000,7 @@ def test_list_all_logs_value_error(self): "filter": filter, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_all_logs(**req_copy) @@ -7686,6 +8013,7 @@ def test_list_all_logs_value_error_with_retries(self): _service.disable_retries() self.test_list_all_logs_value_error() + # endregion ############################################################################## # End of Service: Logs @@ -7696,7 +8024,8 @@ def test_list_all_logs_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -7708,9 +8037,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=202) + responses.add( + responses.DELETE, + url, + status=202, + ) # Set up parameter values customer_id = 'testString' @@ -7718,14 +8049,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -7745,9 +8076,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=202) + responses.add( + responses.DELETE, + url, + status=202, + ) # Set up parameter values customer_id = 'testString' @@ -7757,7 +8090,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -7770,6 +8103,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -7780,7 +8114,9 @@ def test_delete_user_data_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_AgentAvailabilityMessage(): + + +class TestModel_AgentAvailabilityMessage: """ Test Class for AgentAvailabilityMessage """ @@ -7809,7 +8145,8 @@ def test_agent_availability_message_serialization(self): agent_availability_message_model_json2 = agent_availability_message_model.to_dict() assert agent_availability_message_model_json2 == agent_availability_message_model_json -class TestModel_BulkClassifyOutput(): + +class TestModel_BulkClassifyOutput: """ Test Class for BulkClassifyOutput """ @@ -7821,14 +8158,14 @@ def test_bulk_classify_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model = {} # BulkClassifyUtterance bulk_classify_utterance_model['text'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -7856,14 +8193,14 @@ def test_bulk_classify_output_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -7873,7 +8210,7 @@ def test_bulk_classify_output_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 @@ -7898,7 +8235,8 @@ def test_bulk_classify_output_serialization(self): bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() assert bulk_classify_output_model_json2 == bulk_classify_output_model_json -class TestModel_BulkClassifyResponse(): + +class TestModel_BulkClassifyResponse: """ Test Class for BulkClassifyResponse """ @@ -7910,14 +8248,14 @@ def test_bulk_classify_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model = {} # BulkClassifyUtterance bulk_classify_utterance_model['text'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -7945,14 +8283,14 @@ def test_bulk_classify_response_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -7962,11 +8300,11 @@ def test_bulk_classify_response_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - bulk_classify_output_model = {} # BulkClassifyOutput + bulk_classify_output_model = {} # BulkClassifyOutput bulk_classify_output_model['input'] = bulk_classify_utterance_model bulk_classify_output_model['entities'] = [runtime_entity_model] bulk_classify_output_model['intents'] = [runtime_intent_model] @@ -7990,7 +8328,8 @@ def test_bulk_classify_response_serialization(self): bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() assert bulk_classify_response_model_json2 == bulk_classify_response_model_json -class TestModel_BulkClassifyUtterance(): + +class TestModel_BulkClassifyUtterance: """ Test Class for BulkClassifyUtterance """ @@ -8019,7 +8358,8 @@ def test_bulk_classify_utterance_serialization(self): bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json -class TestModel_CaptureGroup(): + +class TestModel_CaptureGroup: """ Test Class for CaptureGroup """ @@ -8049,7 +8389,8 @@ def test_capture_group_serialization(self): capture_group_model_json2 = capture_group_model.to_dict() assert capture_group_model_json2 == capture_group_model_json -class TestModel_ChannelTransferInfo(): + +class TestModel_ChannelTransferInfo: """ Test Class for ChannelTransferInfo """ @@ -8061,10 +8402,10 @@ def test_channel_transfer_info_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model # Construct a json representation of a ChannelTransferInfo model @@ -8086,7 +8427,8 @@ def test_channel_transfer_info_serialization(self): channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() assert channel_transfer_info_model_json2 == channel_transfer_info_model_json -class TestModel_ChannelTransferTarget(): + +class TestModel_ChannelTransferTarget: """ Test Class for ChannelTransferTarget """ @@ -8098,7 +8440,7 @@ def test_channel_transfer_target_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' # Construct a json representation of a ChannelTransferTarget model @@ -8120,7 +8462,8 @@ def test_channel_transfer_target_serialization(self): channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() assert channel_transfer_target_model_json2 == channel_transfer_target_model_json -class TestModel_ChannelTransferTargetChat(): + +class TestModel_ChannelTransferTargetChat: """ Test Class for ChannelTransferTargetChat """ @@ -8149,7 +8492,8 @@ def test_channel_transfer_target_chat_serialization(self): channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json -class TestModel_Context(): + +class TestModel_Context: """ Test Class for Context """ @@ -8161,14 +8505,14 @@ def test_context_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' # Construct a json representation of a Context model context_model_json = {} context_model_json['conversation_id'] = 'testString' - context_model_json['system'] = {'foo': 'bar'} + context_model_json['system'] = {'anyKey': 'anyValue'} context_model_json['metadata'] = message_context_metadata_model context_model_json['foo'] = 'testString' @@ -8197,7 +8541,8 @@ def test_context_serialization(self): actual_dict = context_model.get_properties() assert actual_dict == expected_dict -class TestModel_Counterexample(): + +class TestModel_Counterexample: """ Test Class for Counterexample """ @@ -8226,7 +8571,8 @@ def test_counterexample_serialization(self): counterexample_model_json2 = counterexample_model.to_dict() assert counterexample_model_json2 == counterexample_model_json -class TestModel_CounterexampleCollection(): + +class TestModel_CounterexampleCollection: """ Test Class for CounterexampleCollection """ @@ -8238,10 +8584,10 @@ def test_counterexample_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - counterexample_model = {} # Counterexample + counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -8269,7 +8615,8 @@ def test_counterexample_collection_serialization(self): counterexample_collection_model_json2 = counterexample_collection_model.to_dict() assert counterexample_collection_model_json2 == counterexample_collection_model_json -class TestModel_CreateEntity(): + +class TestModel_CreateEntity: """ Test Class for CreateEntity """ @@ -8281,9 +8628,9 @@ def test_create_entity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - create_value_model = {} # CreateValue + create_value_model = {} # CreateValue create_value_model['value'] = 'testString' - create_value_model['metadata'] = {'foo': 'bar'} + create_value_model['metadata'] = {'anyKey': 'anyValue'} create_value_model['type'] = 'synonyms' create_value_model['synonyms'] = ['testString'] create_value_model['patterns'] = ['testString'] @@ -8292,7 +8639,7 @@ def test_create_entity_serialization(self): create_entity_model_json = {} create_entity_model_json['entity'] = 'testString' create_entity_model_json['description'] = 'testString' - create_entity_model_json['metadata'] = {'foo': 'bar'} + create_entity_model_json['metadata'] = {'anyKey': 'anyValue'} create_entity_model_json['fuzzy_match'] = True create_entity_model_json['values'] = [create_value_model] @@ -8311,7 +8658,8 @@ def test_create_entity_serialization(self): create_entity_model_json2 = create_entity_model.to_dict() assert create_entity_model_json2 == create_entity_model_json -class TestModel_CreateIntent(): + +class TestModel_CreateIntent: """ Test Class for CreateIntent """ @@ -8323,11 +8671,11 @@ def test_create_intent_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] @@ -8352,7 +8700,8 @@ def test_create_intent_serialization(self): create_intent_model_json2 = create_intent_model.to_dict() assert create_intent_model_json2 == create_intent_model_json -class TestModel_CreateValue(): + +class TestModel_CreateValue: """ Test Class for CreateValue """ @@ -8365,7 +8714,7 @@ def test_create_value_serialization(self): # Construct a json representation of a CreateValue model create_value_model_json = {} create_value_model_json['value'] = 'testString' - create_value_model_json['metadata'] = {'foo': 'bar'} + create_value_model_json['metadata'] = {'anyKey': 'anyValue'} create_value_model_json['type'] = 'synonyms' create_value_model_json['synonyms'] = ['testString'] create_value_model_json['patterns'] = ['testString'] @@ -8385,7 +8734,8 @@ def test_create_value_serialization(self): create_value_model_json2 = create_value_model.to_dict() assert create_value_model_json2 == create_value_model_json -class TestModel_DialogNode(): + +class TestModel_DialogNode: """ Test Class for DialogNode """ @@ -8397,41 +8747,41 @@ def test_dialog_node_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' @@ -8444,7 +8794,7 @@ def test_dialog_node_serialization(self): dialog_node_model_json['previous_sibling'] = 'testString' dialog_node_model_json['output'] = dialog_node_output_model dialog_node_model_json['context'] = dialog_node_context_model - dialog_node_model_json['metadata'] = {'foo': 'bar'} + dialog_node_model_json['metadata'] = {'anyKey': 'anyValue'} dialog_node_model_json['next_step'] = dialog_node_next_step_model dialog_node_model_json['title'] = 'testString' dialog_node_model_json['type'] = 'standard' @@ -8472,7 +8822,8 @@ def test_dialog_node_serialization(self): dialog_node_model_json2 = dialog_node_model.to_dict() assert dialog_node_model_json2 == dialog_node_model_json -class TestModel_DialogNodeAction(): + +class TestModel_DialogNodeAction: """ Test Class for DialogNodeAction """ @@ -8486,7 +8837,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json = {} dialog_node_action_model_json['name'] = 'testString' dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {'foo': 'bar'} + dialog_node_action_model_json['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model_json['result_variable'] = 'testString' dialog_node_action_model_json['credentials'] = 'testString' @@ -8505,7 +8856,8 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json2 = dialog_node_action_model.to_dict() assert dialog_node_action_model_json2 == dialog_node_action_model_json -class TestModel_DialogNodeCollection(): + +class TestModel_DialogNodeCollection: """ Test Class for DialogNodeCollection """ @@ -8517,45 +8869,45 @@ def test_dialog_node_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_model = {} # DialogNode + dialog_node_model = {} # DialogNode dialog_node_model['dialog_node'] = 'testString' dialog_node_model['description'] = 'testString' dialog_node_model['conditions'] = 'testString' @@ -8563,7 +8915,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -8576,7 +8928,7 @@ def test_dialog_node_collection_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -8604,7 +8956,8 @@ def test_dialog_node_collection_serialization(self): dialog_node_collection_model_json2 = dialog_node_collection_model.to_dict() assert dialog_node_collection_model_json2 == dialog_node_collection_model_json -class TestModel_DialogNodeContext(): + +class TestModel_DialogNodeContext: """ Test Class for DialogNodeContext """ @@ -8616,7 +8969,7 @@ def test_dialog_node_context_serialization(self): # Construct a json representation of a DialogNodeContext model dialog_node_context_model_json = {} - dialog_node_context_model_json['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model_json['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model_json['foo'] = 'testString' # Construct a model instance of DialogNodeContext by calling from_dict on the json representation @@ -8644,7 +8997,8 @@ def test_dialog_node_context_serialization(self): actual_dict = dialog_node_context_model.get_properties() assert actual_dict == expected_dict -class TestModel_DialogNodeNextStep(): + +class TestModel_DialogNodeNextStep: """ Test Class for DialogNodeNextStep """ @@ -8675,7 +9029,8 @@ def test_dialog_node_next_step_serialization(self): dialog_node_next_step_model_json2 = dialog_node_next_step_model.to_dict() assert dialog_node_next_step_model_json2 == dialog_node_next_step_model_json -class TestModel_DialogNodeOutput(): + +class TestModel_DialogNodeOutput: """ Test Class for DialogNodeOutput """ @@ -8687,26 +9042,26 @@ def test_dialog_node_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True # Construct a json representation of a DialogNodeOutput model dialog_node_output_model_json = {} dialog_node_output_model_json['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model_json['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model_json['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model_json['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model_json['foo'] = 'testString' @@ -8735,7 +9090,8 @@ def test_dialog_node_output_serialization(self): actual_dict = dialog_node_output_model.get_properties() assert actual_dict == expected_dict -class TestModel_DialogNodeOutputConnectToAgentTransferInfo(): + +class TestModel_DialogNodeOutputConnectToAgentTransferInfo: """ Test Class for DialogNodeOutputConnectToAgentTransferInfo """ @@ -8747,7 +9103,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'foo': 'bar'}} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'anyKey': 'anyValue'}} # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) @@ -8764,7 +9120,8 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json -class TestModel_DialogNodeOutputModifiers(): + +class TestModel_DialogNodeOutputModifiers: """ Test Class for DialogNodeOutputModifiers """ @@ -8793,7 +9150,8 @@ def test_dialog_node_output_modifiers_serialization(self): dialog_node_output_modifiers_model_json2 = dialog_node_output_modifiers_model.to_dict() assert dialog_node_output_modifiers_model_json2 == dialog_node_output_modifiers_model_json -class TestModel_DialogNodeOutputOptionsElement(): + +class TestModel_DialogNodeOutputOptionsElement: """ Test Class for DialogNodeOutputOptionsElement """ @@ -8805,21 +9163,21 @@ def test_dialog_node_output_options_element_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8847,14 +9205,14 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8864,7 +9222,7 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] @@ -8889,7 +9247,8 @@ def test_dialog_node_output_options_element_serialization(self): dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json -class TestModel_DialogNodeOutputOptionsElementValue(): + +class TestModel_DialogNodeOutputOptionsElementValue: """ Test Class for DialogNodeOutputOptionsElementValue """ @@ -8901,21 +9260,21 @@ def test_dialog_node_output_options_element_value_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8943,14 +9302,14 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8981,7 +9340,8 @@ def test_dialog_node_output_options_element_value_serialization(self): dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json -class TestModel_DialogNodeOutputTextValuesElement(): + +class TestModel_DialogNodeOutputTextValuesElement: """ Test Class for DialogNodeOutputTextValuesElement """ @@ -9010,7 +9370,8 @@ def test_dialog_node_output_text_values_element_serialization(self): dialog_node_output_text_values_element_model_json2 = dialog_node_output_text_values_element_model.to_dict() assert dialog_node_output_text_values_element_model_json2 == dialog_node_output_text_values_element_model_json -class TestModel_DialogNodeVisitedDetails(): + +class TestModel_DialogNodeVisitedDetails: """ Test Class for DialogNodeVisitedDetails """ @@ -9041,7 +9402,8 @@ def test_dialog_node_visited_details_serialization(self): dialog_node_visited_details_model_json2 = dialog_node_visited_details_model.to_dict() assert dialog_node_visited_details_model_json2 == dialog_node_visited_details_model_json -class TestModel_DialogSuggestion(): + +class TestModel_DialogSuggestion: """ Test Class for DialogSuggestion """ @@ -9053,21 +9415,21 @@ def test_dialog_suggestion_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -9095,14 +9457,14 @@ def test_dialog_suggestion_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9112,7 +9474,7 @@ def test_dialog_suggestion_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model = {} # DialogSuggestionValue dialog_suggestion_value_model['input'] = message_input_model dialog_suggestion_value_model['intents'] = [runtime_intent_model] dialog_suggestion_value_model['entities'] = [runtime_entity_model] @@ -9121,7 +9483,7 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json = {} dialog_suggestion_model_json['label'] = 'testString' dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {'foo': 'bar'} + dialog_suggestion_model_json['output'] = {'anyKey': 'anyValue'} dialog_suggestion_model_json['dialog_node'] = 'testString' # Construct a model instance of DialogSuggestion by calling from_dict on the json representation @@ -9139,7 +9501,8 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() assert dialog_suggestion_model_json2 == dialog_suggestion_model_json -class TestModel_DialogSuggestionValue(): + +class TestModel_DialogSuggestionValue: """ Test Class for DialogSuggestionValue """ @@ -9151,21 +9514,21 @@ def test_dialog_suggestion_value_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -9193,14 +9556,14 @@ def test_dialog_suggestion_value_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9231,7 +9594,8 @@ def test_dialog_suggestion_value_serialization(self): dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json -class TestModel_Entity(): + +class TestModel_Entity: """ Test Class for Entity """ @@ -9243,9 +9607,9 @@ def test_entity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'foo': 'bar'} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] @@ -9254,7 +9618,7 @@ def test_entity_serialization(self): entity_model_json = {} entity_model_json['entity'] = 'testString' entity_model_json['description'] = 'testString' - entity_model_json['metadata'] = {'foo': 'bar'} + entity_model_json['metadata'] = {'anyKey': 'anyValue'} entity_model_json['fuzzy_match'] = True entity_model_json['values'] = [value_model] @@ -9273,7 +9637,8 @@ def test_entity_serialization(self): entity_model_json2 = entity_model.to_dict() assert entity_model_json2 == entity_model_json -class TestModel_EntityCollection(): + +class TestModel_EntityCollection: """ Test Class for EntityCollection """ @@ -9285,21 +9650,21 @@ def test_entity_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'foo': 'bar'} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - entity_model = {} # Entity + entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {'foo': 'bar'} + entity_model['metadata'] = {'anyKey': 'anyValue'} entity_model['fuzzy_match'] = True entity_model['values'] = [value_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -9327,7 +9692,8 @@ def test_entity_collection_serialization(self): entity_collection_model_json2 = entity_collection_model.to_dict() assert entity_collection_model_json2 == entity_collection_model_json -class TestModel_EntityMention(): + +class TestModel_EntityMention: """ Test Class for EntityMention """ @@ -9358,7 +9724,8 @@ def test_entity_mention_serialization(self): entity_mention_model_json2 = entity_mention_model.to_dict() assert entity_mention_model_json2 == entity_mention_model_json -class TestModel_EntityMentionCollection(): + +class TestModel_EntityMentionCollection: """ Test Class for EntityMentionCollection """ @@ -9370,12 +9737,12 @@ def test_entity_mention_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - entity_mention_model = {} # EntityMention + entity_mention_model = {} # EntityMention entity_mention_model['text'] = 'testString' entity_mention_model['intent'] = 'testString' entity_mention_model['location'] = [38] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -9403,7 +9770,8 @@ def test_entity_mention_collection_serialization(self): entity_mention_collection_model_json2 = entity_mention_collection_model.to_dict() assert entity_mention_collection_model_json2 == entity_mention_collection_model_json -class TestModel_Example(): + +class TestModel_Example: """ Test Class for Example """ @@ -9415,7 +9783,7 @@ def test_example_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] @@ -9439,7 +9807,8 @@ def test_example_serialization(self): example_model_json2 = example_model.to_dict() assert example_model_json2 == example_model_json -class TestModel_ExampleCollection(): + +class TestModel_ExampleCollection: """ Test Class for ExampleCollection """ @@ -9451,15 +9820,15 @@ def test_example_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -9487,7 +9856,8 @@ def test_example_collection_serialization(self): example_collection_model_json2 = example_collection_model.to_dict() assert example_collection_model_json2 == example_collection_model_json -class TestModel_Intent(): + +class TestModel_Intent: """ Test Class for Intent """ @@ -9499,11 +9869,11 @@ def test_intent_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] @@ -9528,7 +9898,8 @@ def test_intent_serialization(self): intent_model_json2 = intent_model.to_dict() assert intent_model_json2 == intent_model_json -class TestModel_IntentCollection(): + +class TestModel_IntentCollection: """ Test Class for IntentCollection """ @@ -9540,20 +9911,20 @@ def test_intent_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - intent_model = {} # Intent + intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' intent_model['examples'] = [example_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -9581,7 +9952,8 @@ def test_intent_collection_serialization(self): intent_collection_model_json2 = intent_collection_model.to_dict() assert intent_collection_model_json2 == intent_collection_model_json -class TestModel_Log(): + +class TestModel_Log: """ Test Class for Log """ @@ -9593,21 +9965,21 @@ def test_log_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -9635,14 +10007,14 @@ def test_log_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9652,47 +10024,47 @@ def test_log_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'foo': 'bar'} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - message_request_model = {} # MessageRequest + message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] message_request_model['entities'] = [runtime_entity_model] @@ -9701,7 +10073,7 @@ def test_log_serialization(self): message_request_model['output'] = output_data_model message_request_model['user_id'] = 'testString' - message_response_model = {} # MessageResponse + message_response_model = {} # MessageResponse message_response_model['input'] = message_input_model message_response_model['intents'] = [runtime_intent_model] message_response_model['entities'] = [runtime_entity_model] @@ -9735,7 +10107,8 @@ def test_log_serialization(self): log_model_json2 = log_model.to_dict() assert log_model_json2 == log_model_json -class TestModel_LogCollection(): + +class TestModel_LogCollection: """ Test Class for LogCollection """ @@ -9747,21 +10120,21 @@ def test_log_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -9789,14 +10162,14 @@ def test_log_collection_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -9806,47 +10179,47 @@ def test_log_collection_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'foo': 'bar'} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] output_data_model['generic'] = [runtime_response_generic_model] output_data_model['foo'] = 'testString' - message_request_model = {} # MessageRequest + message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['intents'] = [runtime_intent_model] message_request_model['entities'] = [runtime_entity_model] @@ -9855,7 +10228,7 @@ def test_log_collection_serialization(self): message_request_model['output'] = output_data_model message_request_model['user_id'] = 'testString' - message_response_model = {} # MessageResponse + message_response_model = {} # MessageResponse message_response_model['input'] = message_input_model message_response_model['intents'] = [runtime_intent_model] message_response_model['entities'] = [runtime_entity_model] @@ -9864,7 +10237,7 @@ def test_log_collection_serialization(self): message_response_model['output'] = output_data_model message_response_model['user_id'] = 'testString' - log_model = {} # Log + log_model = {} # Log log_model['request'] = message_request_model log_model['response'] = message_response_model log_model['log_id'] = 'testString' @@ -9873,7 +10246,7 @@ def test_log_collection_serialization(self): log_model['workspace_id'] = 'testString' log_model['language'] = 'testString' - log_pagination_model = {} # LogPagination + log_pagination_model = {} # LogPagination log_pagination_model['next_url'] = 'testString' log_pagination_model['matched'] = 38 log_pagination_model['next_cursor'] = 'testString' @@ -9898,7 +10271,8 @@ def test_log_collection_serialization(self): log_collection_model_json2 = log_collection_model.to_dict() assert log_collection_model_json2 == log_collection_model_json -class TestModel_LogMessage(): + +class TestModel_LogMessage: """ Test Class for LogMessage """ @@ -9910,7 +10284,7 @@ def test_log_message_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' @@ -9936,7 +10310,8 @@ def test_log_message_serialization(self): log_message_model_json2 = log_message_model.to_dict() assert log_message_model_json2 == log_message_model_json -class TestModel_LogMessageSource(): + +class TestModel_LogMessageSource: """ Test Class for LogMessageSource """ @@ -9966,7 +10341,8 @@ def test_log_message_source_serialization(self): log_message_source_model_json2 = log_message_source_model.to_dict() assert log_message_source_model_json2 == log_message_source_model_json -class TestModel_LogPagination(): + +class TestModel_LogPagination: """ Test Class for LogPagination """ @@ -9997,7 +10373,8 @@ def test_log_pagination_serialization(self): log_pagination_model_json2 = log_pagination_model.to_dict() assert log_pagination_model_json2 == log_pagination_model_json -class TestModel_Mention(): + +class TestModel_Mention: """ Test Class for Mention """ @@ -10027,7 +10404,8 @@ def test_mention_serialization(self): mention_model_json2 = mention_model.to_dict() assert mention_model_json2 == mention_model_json -class TestModel_MessageContextMetadata(): + +class TestModel_MessageContextMetadata: """ Test Class for MessageContextMetadata """ @@ -10057,7 +10435,8 @@ def test_message_context_metadata_serialization(self): message_context_metadata_model_json2 = message_context_metadata_model.to_dict() assert message_context_metadata_model_json2 == message_context_metadata_model_json -class TestModel_MessageInput(): + +class TestModel_MessageInput: """ Test Class for MessageInput """ @@ -10099,7 +10478,8 @@ def test_message_input_serialization(self): actual_dict = message_input_model.get_properties() assert actual_dict == expected_dict -class TestModel_MessageRequest(): + +class TestModel_MessageRequest: """ Test Class for MessageRequest """ @@ -10111,21 +10491,21 @@ def test_message_request_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -10153,14 +10533,14 @@ def test_message_request_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -10170,40 +10550,40 @@ def test_message_request_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'foo': 'bar'} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] @@ -10235,7 +10615,8 @@ def test_message_request_serialization(self): message_request_model_json2 = message_request_model.to_dict() assert message_request_model_json2 == message_request_model_json -class TestModel_MessageResponse(): + +class TestModel_MessageResponse: """ Test Class for MessageResponse """ @@ -10247,21 +10628,21 @@ def test_message_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -10289,14 +10670,14 @@ def test_message_response_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -10306,40 +10687,40 @@ def test_message_response_serialization(self): runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - message_context_metadata_model = {} # MessageContextMetadata + message_context_metadata_model = {} # MessageContextMetadata message_context_metadata_model['deployment'] = 'testString' message_context_metadata_model['user_id'] = 'testString' - context_model = {} # Context + context_model = {} # Context context_model['conversation_id'] = 'testString' - context_model['system'] = {'foo': 'bar'} + context_model['system'] = {'anyKey': 'anyValue'} context_model['metadata'] = message_context_metadata_model context_model['foo'] = 'testString' - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - output_data_model = {} # OutputData + output_data_model = {} # OutputData output_data_model['nodes_visited'] = ['testString'] output_data_model['nodes_visited_details'] = [dialog_node_visited_details_model] output_data_model['log_messages'] = [log_message_model] @@ -10371,7 +10752,8 @@ def test_message_response_serialization(self): message_response_model_json2 = message_response_model.to_dict() assert message_response_model_json2 == message_response_model_json -class TestModel_OutputData(): + +class TestModel_OutputData: """ Test Class for OutputData """ @@ -10383,25 +10765,25 @@ def test_output_data_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_visited_details_model = {} # DialogNodeVisitedDetails + dialog_node_visited_details_model = {} # DialogNodeVisitedDetails dialog_node_visited_details_model['dialog_node'] = 'testString' dialog_node_visited_details_model['title'] = 'testString' dialog_node_visited_details_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSource + log_message_source_model = {} # LogMessageSource log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - log_message_model = {} # LogMessage + log_message_model = {} # LogMessage log_message_model['level'] = 'info' log_message_model['msg'] = 'testString' log_message_model['code'] = 'testString' log_message_model['source'] = log_message_source_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] @@ -10439,7 +10821,8 @@ def test_output_data_serialization(self): actual_dict = output_data_model.get_properties() assert actual_dict == expected_dict -class TestModel_Pagination(): + +class TestModel_Pagination: """ Test Class for Pagination """ @@ -10473,7 +10856,8 @@ def test_pagination_serialization(self): pagination_model_json2 = pagination_model.to_dict() assert pagination_model_json2 == pagination_model_json -class TestModel_ResponseGenericChannel(): + +class TestModel_ResponseGenericChannel: """ Test Class for ResponseGenericChannel """ @@ -10502,7 +10886,8 @@ def test_response_generic_channel_serialization(self): response_generic_channel_model_json2 = response_generic_channel_model.to_dict() assert response_generic_channel_model_json2 == response_generic_channel_model_json -class TestModel_RuntimeEntity(): + +class TestModel_RuntimeEntity: """ Test Class for RuntimeEntity """ @@ -10514,11 +10899,11 @@ def test_runtime_entity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -10546,11 +10931,11 @@ def test_runtime_entity_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' # Construct a json representation of a RuntimeEntity model @@ -10579,7 +10964,8 @@ def test_runtime_entity_serialization(self): runtime_entity_model_json2 = runtime_entity_model.to_dict() assert runtime_entity_model_json2 == runtime_entity_model_json -class TestModel_RuntimeEntityAlternative(): + +class TestModel_RuntimeEntityAlternative: """ Test Class for RuntimeEntityAlternative """ @@ -10609,7 +10995,8 @@ def test_runtime_entity_alternative_serialization(self): runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json -class TestModel_RuntimeEntityInterpretation(): + +class TestModel_RuntimeEntityInterpretation: """ Test Class for RuntimeEntityInterpretation """ @@ -10663,7 +11050,8 @@ def test_runtime_entity_interpretation_serialization(self): runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json -class TestModel_RuntimeEntityRole(): + +class TestModel_RuntimeEntityRole: """ Test Class for RuntimeEntityRole """ @@ -10692,7 +11080,8 @@ def test_runtime_entity_role_serialization(self): runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() assert runtime_entity_role_model_json2 == runtime_entity_role_model_json -class TestModel_RuntimeIntent(): + +class TestModel_RuntimeIntent: """ Test Class for RuntimeIntent """ @@ -10722,7 +11111,8 @@ def test_runtime_intent_serialization(self): runtime_intent_model_json2 = runtime_intent_model.to_dict() assert runtime_intent_model_json2 == runtime_intent_model_json -class TestModel_StatusError(): + +class TestModel_StatusError: """ Test Class for StatusError """ @@ -10751,7 +11141,8 @@ def test_status_error_serialization(self): status_error_model_json2 = status_error_model.to_dict() assert status_error_model_json2 == status_error_model_json -class TestModel_Synonym(): + +class TestModel_Synonym: """ Test Class for Synonym """ @@ -10780,7 +11171,8 @@ def test_synonym_serialization(self): synonym_model_json2 = synonym_model.to_dict() assert synonym_model_json2 == synonym_model_json -class TestModel_SynonymCollection(): + +class TestModel_SynonymCollection: """ Test Class for SynonymCollection """ @@ -10792,10 +11184,10 @@ def test_synonym_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - synonym_model = {} # Synonym + synonym_model = {} # Synonym synonym_model['synonym'] = 'testString' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -10823,7 +11215,8 @@ def test_synonym_collection_serialization(self): synonym_collection_model_json2 = synonym_collection_model.to_dict() assert synonym_collection_model_json2 == synonym_collection_model_json -class TestModel_Value(): + +class TestModel_Value: """ Test Class for Value """ @@ -10836,7 +11229,7 @@ def test_value_serialization(self): # Construct a json representation of a Value model value_model_json = {} value_model_json['value'] = 'testString' - value_model_json['metadata'] = {'foo': 'bar'} + value_model_json['metadata'] = {'anyKey': 'anyValue'} value_model_json['type'] = 'synonyms' value_model_json['synonyms'] = ['testString'] value_model_json['patterns'] = ['testString'] @@ -10856,7 +11249,8 @@ def test_value_serialization(self): value_model_json2 = value_model.to_dict() assert value_model_json2 == value_model_json -class TestModel_ValueCollection(): + +class TestModel_ValueCollection: """ Test Class for ValueCollection """ @@ -10868,14 +11262,14 @@ def test_value_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'foo': 'bar'} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -10903,7 +11297,8 @@ def test_value_collection_serialization(self): value_collection_model_json2 = value_collection_model.to_dict() assert value_collection_model_json2 == value_collection_model_json -class TestModel_Webhook(): + +class TestModel_Webhook: """ Test Class for Webhook """ @@ -10915,7 +11310,7 @@ def test_webhook_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - webhook_header_model = {} # WebhookHeader + webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' @@ -10940,7 +11335,8 @@ def test_webhook_serialization(self): webhook_model_json2 = webhook_model.to_dict() assert webhook_model_json2 == webhook_model_json -class TestModel_WebhookHeader(): + +class TestModel_WebhookHeader: """ Test Class for WebhookHeader """ @@ -10970,7 +11366,8 @@ def test_webhook_header_serialization(self): webhook_header_model_json2 = webhook_header_model.to_dict() assert webhook_header_model_json2 == webhook_header_model_json -class TestModel_Workspace(): + +class TestModel_Workspace: """ Test Class for Workspace """ @@ -10982,45 +11379,45 @@ def test_workspace_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_model = {} # DialogNode + dialog_node_model = {} # DialogNode dialog_node_model['dialog_node'] = 'testString' dialog_node_model['description'] = 'testString' dialog_node_model['conditions'] = 'testString' @@ -11028,7 +11425,7 @@ def test_workspace_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -11041,13 +11438,13 @@ def test_workspace_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - counterexample_model = {} # Counterexample + counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True - workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' workspace_system_settings_disambiguation_model['enabled'] = False @@ -11056,19 +11453,19 @@ def test_workspace_serialization(self): workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' - workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities workspace_system_settings_system_entities_model['enabled'] = False - workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False - workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp workspace_system_settings_nlp_model['model'] = 'testString' - workspace_system_settings_model = {} # WorkspaceSystemSettings + workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -11076,39 +11473,39 @@ def test_workspace_serialization(self): workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' - webhook_header_model = {} # WebhookHeader + webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' - webhook_model = {} # Webhook + webhook_model = {} # Webhook webhook_model['url'] = 'testString' webhook_model['name'] = 'testString' webhook_model['headers'] = [webhook_header_model] - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - intent_model = {} # Intent + intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' intent_model['examples'] = [example_model] - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'foo': 'bar'} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - entity_model = {} # Entity + entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {'foo': 'bar'} + entity_model['metadata'] = {'anyKey': 'anyValue'} entity_model['fuzzy_match'] = True entity_model['values'] = [value_model] @@ -11119,7 +11516,7 @@ def test_workspace_serialization(self): workspace_model_json['language'] = 'testString' workspace_model_json['dialog_nodes'] = [dialog_node_model] workspace_model_json['counterexamples'] = [counterexample_model] - workspace_model_json['metadata'] = {'foo': 'bar'} + workspace_model_json['metadata'] = {'anyKey': 'anyValue'} workspace_model_json['learning_opt_out'] = False workspace_model_json['system_settings'] = workspace_system_settings_model workspace_model_json['webhooks'] = [webhook_model] @@ -11141,7 +11538,8 @@ def test_workspace_serialization(self): workspace_model_json2 = workspace_model.to_dict() assert workspace_model_json2 == workspace_model_json -class TestModel_WorkspaceCollection(): + +class TestModel_WorkspaceCollection: """ Test Class for WorkspaceCollection """ @@ -11153,45 +11551,45 @@ def test_workspace_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' - dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText + dialog_node_output_generic_model = {} # DialogNodeOutputGenericDialogNodeOutputResponseTypeText dialog_node_output_generic_model['response_type'] = 'text' dialog_node_output_generic_model['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_model['selection_policy'] = 'sequential' - dialog_node_output_generic_model['delimiter'] = '\n' + dialog_node_output_generic_model['delimiter'] = '\\n' dialog_node_output_generic_model['channels'] = [response_generic_channel_model] - dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers + dialog_node_output_modifiers_model = {} # DialogNodeOutputModifiers dialog_node_output_modifiers_model['overwrite'] = True - dialog_node_output_model = {} # DialogNodeOutput + dialog_node_output_model = {} # DialogNodeOutput dialog_node_output_model['generic'] = [dialog_node_output_generic_model] - dialog_node_output_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_output_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_output_model['modifiers'] = dialog_node_output_modifiers_model dialog_node_output_model['foo'] = 'testString' - dialog_node_context_model = {} # DialogNodeContext - dialog_node_context_model['integrations'] = {'key1': {'foo': 'bar'}} + dialog_node_context_model = {} # DialogNodeContext + dialog_node_context_model['integrations'] = {'key1': {'anyKey': 'anyValue'}} dialog_node_context_model['foo'] = 'testString' - dialog_node_next_step_model = {} # DialogNodeNextStep + dialog_node_next_step_model = {} # DialogNodeNextStep dialog_node_next_step_model['behavior'] = 'get_user_input' dialog_node_next_step_model['dialog_node'] = 'testString' dialog_node_next_step_model['selector'] = 'condition' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_model = {} # DialogNode + dialog_node_model = {} # DialogNode dialog_node_model['dialog_node'] = 'testString' dialog_node_model['description'] = 'testString' dialog_node_model['conditions'] = 'testString' @@ -11199,7 +11597,7 @@ def test_workspace_collection_serialization(self): dialog_node_model['previous_sibling'] = 'testString' dialog_node_model['output'] = dialog_node_output_model dialog_node_model['context'] = dialog_node_context_model - dialog_node_model['metadata'] = {'foo': 'bar'} + dialog_node_model['metadata'] = {'anyKey': 'anyValue'} dialog_node_model['next_step'] = dialog_node_next_step_model dialog_node_model['title'] = 'testString' dialog_node_model['type'] = 'standard' @@ -11212,13 +11610,13 @@ def test_workspace_collection_serialization(self): dialog_node_model['user_label'] = 'testString' dialog_node_model['disambiguation_opt_out'] = False - counterexample_model = {} # Counterexample + counterexample_model = {} # Counterexample counterexample_model['text'] = 'testString' - workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True - workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' workspace_system_settings_disambiguation_model['enabled'] = False @@ -11227,19 +11625,19 @@ def test_workspace_collection_serialization(self): workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' - workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities workspace_system_settings_system_entities_model['enabled'] = False - workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False - workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp workspace_system_settings_nlp_model['model'] = 'testString' - workspace_system_settings_model = {} # WorkspaceSystemSettings + workspace_system_settings_model = {} # WorkspaceSystemSettings workspace_system_settings_model['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model['spelling_suggestions'] = False workspace_system_settings_model['spelling_auto_correct'] = False workspace_system_settings_model['system_entities'] = workspace_system_settings_system_entities_model @@ -11247,56 +11645,56 @@ def test_workspace_collection_serialization(self): workspace_system_settings_model['nlp'] = workspace_system_settings_nlp_model workspace_system_settings_model['foo'] = 'testString' - webhook_header_model = {} # WebhookHeader + webhook_header_model = {} # WebhookHeader webhook_header_model['name'] = 'testString' webhook_header_model['value'] = 'testString' - webhook_model = {} # Webhook + webhook_model = {} # Webhook webhook_model['url'] = 'testString' webhook_model['name'] = 'testString' webhook_model['headers'] = [webhook_header_model] - mention_model = {} # Mention + mention_model = {} # Mention mention_model['entity'] = 'testString' mention_model['location'] = [38] - example_model = {} # Example + example_model = {} # Example example_model['text'] = 'testString' example_model['mentions'] = [mention_model] - intent_model = {} # Intent + intent_model = {} # Intent intent_model['intent'] = 'testString' intent_model['description'] = 'testString' intent_model['examples'] = [example_model] - value_model = {} # Value + value_model = {} # Value value_model['value'] = 'testString' - value_model['metadata'] = {'foo': 'bar'} + value_model['metadata'] = {'anyKey': 'anyValue'} value_model['type'] = 'synonyms' value_model['synonyms'] = ['testString'] value_model['patterns'] = ['testString'] - entity_model = {} # Entity + entity_model = {} # Entity entity_model['entity'] = 'testString' entity_model['description'] = 'testString' - entity_model['metadata'] = {'foo': 'bar'} + entity_model['metadata'] = {'anyKey': 'anyValue'} entity_model['fuzzy_match'] = True entity_model['values'] = [value_model] - workspace_model = {} # Workspace + workspace_model = {} # Workspace workspace_model['name'] = 'testString' workspace_model['description'] = 'testString' workspace_model['language'] = 'testString' workspace_model['dialog_nodes'] = [dialog_node_model] workspace_model['counterexamples'] = [counterexample_model] - workspace_model['metadata'] = {'foo': 'bar'} + workspace_model['metadata'] = {'anyKey': 'anyValue'} workspace_model['learning_opt_out'] = False workspace_model['system_settings'] = workspace_system_settings_model workspace_model['webhooks'] = [webhook_model] workspace_model['intents'] = [intent_model] workspace_model['entities'] = [entity_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -11324,7 +11722,8 @@ def test_workspace_collection_serialization(self): workspace_collection_model_json2 = workspace_collection_model.to_dict() assert workspace_collection_model_json2 == workspace_collection_model_json -class TestModel_WorkspaceCounts(): + +class TestModel_WorkspaceCounts: """ Test Class for WorkspaceCounts """ @@ -11355,7 +11754,8 @@ def test_workspace_counts_serialization(self): workspace_counts_model_json2 = workspace_counts_model.to_dict() assert workspace_counts_model_json2 == workspace_counts_model_json -class TestModel_WorkspaceSystemSettings(): + +class TestModel_WorkspaceSystemSettings: """ Test Class for WorkspaceSystemSettings """ @@ -11367,10 +11767,10 @@ def test_workspace_system_settings_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling + workspace_system_settings_tooling_model = {} # WorkspaceSystemSettingsTooling workspace_system_settings_tooling_model['store_generic_responses'] = True - workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation + workspace_system_settings_disambiguation_model = {} # WorkspaceSystemSettingsDisambiguation workspace_system_settings_disambiguation_model['prompt'] = 'testString' workspace_system_settings_disambiguation_model['none_of_the_above_prompt'] = 'testString' workspace_system_settings_disambiguation_model['enabled'] = False @@ -11379,20 +11779,20 @@ def test_workspace_system_settings_serialization(self): workspace_system_settings_disambiguation_model['max_suggestions'] = 1 workspace_system_settings_disambiguation_model['suggestion_text_policy'] = 'testString' - workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities + workspace_system_settings_system_entities_model = {} # WorkspaceSystemSettingsSystemEntities workspace_system_settings_system_entities_model['enabled'] = False - workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic + workspace_system_settings_off_topic_model = {} # WorkspaceSystemSettingsOffTopic workspace_system_settings_off_topic_model['enabled'] = False - workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp + workspace_system_settings_nlp_model = {} # WorkspaceSystemSettingsNlp workspace_system_settings_nlp_model['model'] = 'testString' # Construct a json representation of a WorkspaceSystemSettings model workspace_system_settings_model_json = {} workspace_system_settings_model_json['tooling'] = workspace_system_settings_tooling_model workspace_system_settings_model_json['disambiguation'] = workspace_system_settings_disambiguation_model - workspace_system_settings_model_json['human_agent_assist'] = {'foo': 'bar'} + workspace_system_settings_model_json['human_agent_assist'] = {'anyKey': 'anyValue'} workspace_system_settings_model_json['spelling_suggestions'] = False workspace_system_settings_model_json['spelling_auto_correct'] = False workspace_system_settings_model_json['system_entities'] = workspace_system_settings_system_entities_model @@ -11425,7 +11825,8 @@ def test_workspace_system_settings_serialization(self): actual_dict = workspace_system_settings_model.get_properties() assert actual_dict == expected_dict -class TestModel_WorkspaceSystemSettingsDisambiguation(): + +class TestModel_WorkspaceSystemSettingsDisambiguation: """ Test Class for WorkspaceSystemSettingsDisambiguation """ @@ -11460,7 +11861,8 @@ def test_workspace_system_settings_disambiguation_serialization(self): workspace_system_settings_disambiguation_model_json2 = workspace_system_settings_disambiguation_model.to_dict() assert workspace_system_settings_disambiguation_model_json2 == workspace_system_settings_disambiguation_model_json -class TestModel_WorkspaceSystemSettingsNlp(): + +class TestModel_WorkspaceSystemSettingsNlp: """ Test Class for WorkspaceSystemSettingsNlp """ @@ -11489,7 +11891,8 @@ def test_workspace_system_settings_nlp_serialization(self): workspace_system_settings_nlp_model_json2 = workspace_system_settings_nlp_model.to_dict() assert workspace_system_settings_nlp_model_json2 == workspace_system_settings_nlp_model_json -class TestModel_WorkspaceSystemSettingsOffTopic(): + +class TestModel_WorkspaceSystemSettingsOffTopic: """ Test Class for WorkspaceSystemSettingsOffTopic """ @@ -11518,7 +11921,8 @@ def test_workspace_system_settings_off_topic_serialization(self): workspace_system_settings_off_topic_model_json2 = workspace_system_settings_off_topic_model.to_dict() assert workspace_system_settings_off_topic_model_json2 == workspace_system_settings_off_topic_model_json -class TestModel_WorkspaceSystemSettingsSystemEntities(): + +class TestModel_WorkspaceSystemSettingsSystemEntities: """ Test Class for WorkspaceSystemSettingsSystemEntities """ @@ -11547,7 +11951,8 @@ def test_workspace_system_settings_system_entities_serialization(self): workspace_system_settings_system_entities_model_json2 = workspace_system_settings_system_entities_model.to_dict() assert workspace_system_settings_system_entities_model_json2 == workspace_system_settings_system_entities_model_json -class TestModel_WorkspaceSystemSettingsTooling(): + +class TestModel_WorkspaceSystemSettingsTooling: """ Test Class for WorkspaceSystemSettingsTooling """ @@ -11576,7 +11981,8 @@ def test_workspace_system_settings_tooling_serialization(self): workspace_system_settings_tooling_model_json2 = workspace_system_settings_tooling_model.to_dict() assert workspace_system_settings_tooling_model_json2 == workspace_system_settings_tooling_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio """ @@ -11588,7 +11994,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_audio_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio model @@ -11598,7 +12004,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_audio_seria dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channels'] = [response_generic_channel_model] - dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} + dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['channel_options'] = {'anyKey': 'anyValue'} dialog_node_output_generic_dialog_node_output_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio by calling from_dict on the json representation @@ -11616,7 +12022,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_audio_seria dialog_node_output_generic_dialog_node_output_response_type_audio_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_audio_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_audio_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_audio_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer """ @@ -11628,16 +12035,16 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_channel_tra # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model = {} # ChannelTransferInfo channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer model @@ -11662,7 +12069,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_channel_tra dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_channel_transfer_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent """ @@ -11674,13 +12082,13 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ # Construct dict forms of any model objects needed in order to build this model. - agent_availability_message_model = {} # AgentAvailabilityMessage + agent_availability_message_model = {} # AgentAvailabilityMessage agent_availability_message_model['message'] = 'testString' - dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'anyKey': 'anyValue'}} - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent model @@ -11707,7 +12115,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_connect_to_ dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_connect_to_agent_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe """ @@ -11719,7 +12128,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_iframe_seri # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe model @@ -11746,7 +12155,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_iframe_seri dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_iframe_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_iframe_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeImage(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeImage: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeImage """ @@ -11758,7 +12168,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_image_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage model @@ -11785,7 +12195,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_image_seria dialog_node_output_generic_dialog_node_output_response_type_image_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_image_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_image_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_image_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeOption(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeOption: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeOption """ @@ -11797,21 +12208,21 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -11839,14 +12250,14 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -11856,16 +12267,16 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption model @@ -11892,7 +12303,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_option_seri dialog_node_output_generic_dialog_node_output_response_type_option_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_option_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_option_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_option_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypePause(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypePause: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypePause """ @@ -11904,7 +12316,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_pause_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypePause model @@ -11929,7 +12341,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_pause_seria dialog_node_output_generic_dialog_node_output_response_type_pause_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_pause_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_pause_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_pause_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill """ @@ -11941,7 +12354,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_search_skil # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill model @@ -11968,7 +12381,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_search_skil dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_search_skill_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_search_skill_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeText(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeText: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeText """ @@ -11980,10 +12394,10 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial # Construct dict forms of any model objects needed in order to build this model. - dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement + dialog_node_output_text_values_element_model = {} # DialogNodeOutputTextValuesElement dialog_node_output_text_values_element_model['text'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeText model @@ -11991,7 +12405,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial dialog_node_output_generic_dialog_node_output_response_type_text_model_json['response_type'] = 'text' dialog_node_output_generic_dialog_node_output_response_type_text_model_json['values'] = [dialog_node_output_text_values_element_model] dialog_node_output_generic_dialog_node_output_response_type_text_model_json['selection_policy'] = 'sequential' - dialog_node_output_generic_dialog_node_output_response_type_text_model_json['delimiter'] = '\n' + dialog_node_output_generic_dialog_node_output_response_type_text_model_json['delimiter'] = '\\n' dialog_node_output_generic_dialog_node_output_response_type_text_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeText by calling from_dict on the json representation @@ -12009,7 +12423,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_text_serial dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_text_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_text_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_text_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined """ @@ -12021,13 +12436,13 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_user_define # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined model dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json = {} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['response_type'] = 'user_defined' - dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} + dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['user_defined'] = {'anyKey': 'anyValue'} dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined by calling from_dict on the json representation @@ -12045,7 +12460,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_user_define dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_user_defined_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_user_defined_model_json -class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo(): + +class TestModel_DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo: """ Test Class for DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo """ @@ -12057,7 +12473,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_video_seria # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo model @@ -12067,7 +12483,7 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_video_seria dialog_node_output_generic_dialog_node_output_response_type_video_model_json['title'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_video_model_json['description'] = 'testString' dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channels'] = [response_generic_channel_model] - dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channel_options'] = {'foo': 'bar'} + dialog_node_output_generic_dialog_node_output_response_type_video_model_json['channel_options'] = {'anyKey': 'anyValue'} dialog_node_output_generic_dialog_node_output_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo by calling from_dict on the json representation @@ -12085,7 +12501,8 @@ def test_dialog_node_output_generic_dialog_node_output_response_type_video_seria dialog_node_output_generic_dialog_node_output_response_type_video_model_json2 = dialog_node_output_generic_dialog_node_output_response_type_video_model.to_dict() assert dialog_node_output_generic_dialog_node_output_response_type_video_model_json2 == dialog_node_output_generic_dialog_node_output_response_type_video_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeAudio """ @@ -12097,7 +12514,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeAudio model @@ -12107,7 +12524,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation @@ -12125,7 +12542,8 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json2 = runtime_response_generic_runtime_response_type_audio_model.to_dict() assert runtime_response_generic_runtime_response_type_audio_model_json2 == runtime_response_generic_runtime_response_type_audio_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer """ @@ -12137,16 +12555,16 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model = {} # ChannelTransferInfo channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer model @@ -12171,7 +12589,8 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali runtime_response_generic_runtime_response_type_channel_transfer_model_json2 = runtime_response_generic_runtime_response_type_channel_transfer_model.to_dict() assert runtime_response_generic_runtime_response_type_channel_transfer_model_json2 == runtime_response_generic_runtime_response_type_channel_transfer_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent """ @@ -12183,13 +12602,13 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali # Construct dict forms of any model objects needed in order to build this model. - agent_availability_message_model = {} # AgentAvailabilityMessage + agent_availability_message_model = {} # AgentAvailabilityMessage agent_availability_message_model['message'] = 'testString' - dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'anyKey': 'anyValue'}} - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent model @@ -12218,7 +12637,8 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeIframe """ @@ -12230,7 +12650,7 @@ def test_runtime_response_generic_runtime_response_type_iframe_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeIframe model @@ -12257,7 +12677,8 @@ def test_runtime_response_generic_runtime_response_type_iframe_serialization(sel runtime_response_generic_runtime_response_type_iframe_model_json2 = runtime_response_generic_runtime_response_type_iframe_model.to_dict() assert runtime_response_generic_runtime_response_type_iframe_model_json2 == runtime_response_generic_runtime_response_type_iframe_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeImage """ @@ -12269,7 +12690,7 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeImage model @@ -12296,7 +12717,8 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self runtime_response_generic_runtime_response_type_image_model_json2 = runtime_response_generic_runtime_response_type_image_model.to_dict() assert runtime_response_generic_runtime_response_type_image_model_json2 == runtime_response_generic_runtime_response_type_image_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeOption """ @@ -12308,21 +12730,21 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -12350,14 +12772,14 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -12367,16 +12789,16 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model dialog_node_output_options_element_value_model['intents'] = [runtime_intent_model] dialog_node_output_options_element_value_model['entities'] = [runtime_entity_model] - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeOption model @@ -12403,7 +12825,8 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_response_generic_runtime_response_type_option_model_json2 = runtime_response_generic_runtime_response_type_option_model.to_dict() assert runtime_response_generic_runtime_response_type_option_model_json2 == runtime_response_generic_runtime_response_type_option_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypePause(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypePause: """ Test Class for RuntimeResponseGenericRuntimeResponseTypePause """ @@ -12415,7 +12838,7 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypePause model @@ -12440,7 +12863,8 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self runtime_response_generic_runtime_response_type_pause_model_json2 = runtime_response_generic_runtime_response_type_pause_model.to_dict() assert runtime_response_generic_runtime_response_type_pause_model_json2 == runtime_response_generic_runtime_response_type_pause_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeSuggestion """ @@ -12452,21 +12876,21 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization # Construct dict forms of any model objects needed in order to build this model. - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['text'] = 'testString' message_input_model['spelling_suggestions'] = False message_input_model['spelling_auto_correct'] = False message_input_model['foo'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -12494,14 +12918,14 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -12511,18 +12935,18 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] runtime_entity_model['role'] = runtime_entity_role_model - dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model = {} # DialogSuggestionValue dialog_suggestion_value_model['input'] = message_input_model dialog_suggestion_value_model['intents'] = [runtime_intent_model] dialog_suggestion_value_model['entities'] = [runtime_entity_model] - dialog_suggestion_model = {} # DialogSuggestion + dialog_suggestion_model = {} # DialogSuggestion dialog_suggestion_model['label'] = 'testString' dialog_suggestion_model['value'] = dialog_suggestion_value_model - dialog_suggestion_model['output'] = {'foo': 'bar'} + dialog_suggestion_model['output'] = {'anyKey': 'anyValue'} dialog_suggestion_model['dialog_node'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSuggestion model @@ -12547,7 +12971,8 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_response_generic_runtime_response_type_suggestion_model_json2 = runtime_response_generic_runtime_response_type_suggestion_model.to_dict() assert runtime_response_generic_runtime_response_type_suggestion_model_json2 == runtime_response_generic_runtime_response_type_suggestion_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeText(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeText: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeText """ @@ -12559,7 +12984,7 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeText model @@ -12583,7 +13008,8 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) runtime_response_generic_runtime_response_type_text_model_json2 = runtime_response_generic_runtime_response_type_text_model.to_dict() assert runtime_response_generic_runtime_response_type_text_model_json2 == runtime_response_generic_runtime_response_type_text_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeUserDefined """ @@ -12595,13 +13021,13 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model runtime_response_generic_runtime_response_type_user_defined_model_json = {} runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' - runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation @@ -12619,7 +13045,8 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati runtime_response_generic_runtime_response_type_user_defined_model_json2 = runtime_response_generic_runtime_response_type_user_defined_model.to_dict() assert runtime_response_generic_runtime_response_type_user_defined_model_json2 == runtime_response_generic_runtime_response_type_user_defined_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeVideo """ @@ -12631,7 +13058,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'chat' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeVideo model @@ -12641,7 +13068,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self runtime_response_generic_runtime_response_type_video_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index f0a15e812..0e6681be4 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -62,8 +62,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -71,7 +70,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestCreateAssistant(): + +class TestCreateAssistant: """ Test Class for create_assistant """ @@ -84,11 +84,13 @@ def test_create_assistant_all_params(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values language = 'testString' @@ -100,7 +102,7 @@ def test_create_assistant_all_params(self): language=language, name=name, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -129,16 +131,17 @@ def test_create_assistant_required_params(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.create_assistant() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -160,17 +163,19 @@ def test_create_assistant_value_error(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_assistant(**req_copy) @@ -183,7 +188,8 @@ def test_create_assistant_value_error_with_retries(self): _service.disable_retries() self.test_create_assistant_value_error() -class TestListAssistants(): + +class TestListAssistants: """ Test Class for list_assistants """ @@ -196,14 +202,16 @@ def test_list_assistants_all_params(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - page_limit = 38 + page_limit = 100 include_count = False sort = 'name' cursor = 'testString' @@ -216,14 +224,14 @@ def test_list_assistants_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -248,16 +256,17 @@ def test_list_assistants_required_params(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_assistants() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -279,17 +288,19 @@ def test_list_assistants_value_error(self): # Set up mock url = preprocess_url('/v2/assistants') mock_response = '{"assistants": [{"assistant_id": "assistant_id", "name": "name", "description": "description", "language": "language", "assistant_skills": [{"skill_id": "skill_id", "type": "dialog"}], "assistant_environments": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}]}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_assistants(**req_copy) @@ -302,7 +313,8 @@ def test_list_assistants_value_error_with_retries(self): _service.disable_retries() self.test_list_assistants_value_error() -class TestDeleteAssistant(): + +class TestDeleteAssistant: """ Test Class for delete_assistant """ @@ -314,9 +326,11 @@ def test_delete_assistant_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -324,7 +338,7 @@ def test_delete_assistant_all_params(self): # Invoke method response = _service.delete_assistant( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -347,9 +361,11 @@ def test_delete_assistant_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -359,7 +375,7 @@ def test_delete_assistant_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_assistant(**req_copy) @@ -372,6 +388,7 @@ def test_delete_assistant_value_error_with_retries(self): _service.disable_retries() self.test_delete_assistant_value_error() + # endregion ############################################################################## # End of Service: Assistants @@ -382,7 +399,8 @@ def test_delete_assistant_value_error_with_retries(self): ############################################################################## # region -class TestCreateSession(): + +class TestCreateSession: """ Test Class for create_session """ @@ -395,11 +413,13 @@ def test_create_session_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/sessions') mock_response = '{"session_id": "session_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a RequestAnalytics model request_analytics_model = {} @@ -415,7 +435,7 @@ def test_create_session_all_params(self): response = _service.create_session( assistant_id, analytics=analytics, - headers={} + headers={}, ) # Check for correct operation @@ -442,11 +462,13 @@ def test_create_session_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/sessions') mock_response = '{"session_id": "session_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values assistant_id = 'testString' @@ -454,7 +476,7 @@ def test_create_session_required_params(self): # Invoke method response = _service.create_session( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -478,11 +500,13 @@ def test_create_session_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/sessions') mock_response = '{"session_id": "session_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values assistant_id = 'testString' @@ -492,7 +516,7 @@ def test_create_session_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_session(**req_copy) @@ -505,7 +529,8 @@ def test_create_session_value_error_with_retries(self): _service.disable_retries() self.test_create_session_value_error() -class TestDeleteSession(): + +class TestDeleteSession: """ Test Class for delete_session """ @@ -517,9 +542,11 @@ def test_delete_session_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -529,7 +556,7 @@ def test_delete_session_all_params(self): response = _service.delete_session( assistant_id, session_id, - headers={} + headers={}, ) # Check for correct operation @@ -552,9 +579,11 @@ def test_delete_session_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -566,7 +595,7 @@ def test_delete_session_value_error(self): "session_id": session_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_session(**req_copy) @@ -579,6 +608,7 @@ def test_delete_session_value_error_with_retries(self): _service.disable_retries() self.test_delete_session_value_error() + # endregion ############################################################################## # End of Service: Sessions @@ -589,7 +619,8 @@ def test_delete_session_value_error_with_retries(self): ############################################################################## # region -class TestMessage(): + +class TestMessage: """ Test Class for message """ @@ -602,11 +633,13 @@ def test_message_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a RuntimeIntent model runtime_intent_model = {} @@ -727,15 +760,15 @@ def test_message_all_params(self): # Construct a dict representation of a MessageContextSkillDialog model message_context_skill_dialog_model = {} - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_dialog_model['system'] = message_context_skill_system_model # Construct a dict representation of a MessageContextSkillAction model message_context_skill_action_model = {} - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} # Construct a dict representation of a MessageContextSkills model message_context_skills_model = {} @@ -746,7 +779,7 @@ def test_message_all_params(self): message_context_model = {} message_context_model['global'] = message_context_global_model message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'foo': 'bar'} + message_context_model['integrations'] = {'anyKey': 'anyValue'} # Set up parameter values assistant_id = 'testString' @@ -762,7 +795,7 @@ def test_message_all_params(self): input=input, context=context, user_id=user_id, - headers={} + headers={}, ) # Check for correct operation @@ -791,11 +824,13 @@ def test_message_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -805,7 +840,7 @@ def test_message_required_params(self): response = _service.message( assistant_id, session_id, - headers={} + headers={}, ) # Check for correct operation @@ -829,11 +864,13 @@ def test_message_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -845,7 +882,7 @@ def test_message_value_error(self): "session_id": session_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.message(**req_copy) @@ -858,7 +895,8 @@ def test_message_value_error_with_retries(self): _service.disable_retries() self.test_message_value_error() -class TestMessageStateless(): + +class TestMessageStateless: """ Test Class for message_stateless """ @@ -871,11 +909,13 @@ def test_message_stateless_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/message') mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a RuntimeIntent model runtime_intent_model = {} @@ -995,15 +1035,15 @@ def test_message_stateless_all_params(self): # Construct a dict representation of a MessageContextSkillDialog model message_context_skill_dialog_model = {} - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_dialog_model['system'] = message_context_skill_system_model # Construct a dict representation of a MessageContextSkillAction model message_context_skill_action_model = {} - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} # Construct a dict representation of a MessageContextSkills model message_context_skills_model = {} @@ -1014,7 +1054,7 @@ def test_message_stateless_all_params(self): message_context_stateless_model = {} message_context_stateless_model['global'] = message_context_global_stateless_model message_context_stateless_model['skills'] = message_context_skills_model - message_context_stateless_model['integrations'] = {'foo': 'bar'} + message_context_stateless_model['integrations'] = {'anyKey': 'anyValue'} # Set up parameter values assistant_id = 'testString' @@ -1028,7 +1068,7 @@ def test_message_stateless_all_params(self): input=input, context=context, user_id=user_id, - headers={} + headers={}, ) # Check for correct operation @@ -1057,11 +1097,13 @@ def test_message_stateless_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/message') mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1069,7 +1111,7 @@ def test_message_stateless_required_params(self): # Invoke method response = _service.message_stateless( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -1093,11 +1135,13 @@ def test_message_stateless_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/message') mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1107,7 +1151,7 @@ def test_message_stateless_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.message_stateless(**req_copy) @@ -1120,6 +1164,7 @@ def test_message_stateless_value_error_with_retries(self): _service.disable_retries() self.test_message_stateless_value_error() + # endregion ############################################################################## # End of Service: Message @@ -1130,7 +1175,8 @@ def test_message_stateless_value_error_with_retries(self): ############################################################################## # region -class TestBulkClassify(): + +class TestBulkClassify: """ Test Class for bulk_classify """ @@ -1143,11 +1189,13 @@ def test_bulk_classify_all_params(self): # Set up mock url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a BulkClassifyUtterance model bulk_classify_utterance_model = {} @@ -1161,7 +1209,7 @@ def test_bulk_classify_all_params(self): response = _service.bulk_classify( skill_id, input, - headers={} + headers={}, ) # Check for correct operation @@ -1188,11 +1236,13 @@ def test_bulk_classify_value_error(self): # Set up mock url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a BulkClassifyUtterance model bulk_classify_utterance_model = {} @@ -1208,7 +1258,7 @@ def test_bulk_classify_value_error(self): "input": input, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.bulk_classify(**req_copy) @@ -1221,6 +1271,7 @@ def test_bulk_classify_value_error_with_retries(self): _service.disable_retries() self.test_bulk_classify_value_error() + # endregion ############################################################################## # End of Service: BulkClassify @@ -1231,7 +1282,8 @@ def test_bulk_classify_value_error_with_retries(self): ############################################################################## # region -class TestListLogs(): + +class TestListLogs: """ Test Class for list_logs """ @@ -1244,17 +1296,19 @@ def test_list_logs_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/logs') mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' sort = 'testString' filter = 'testString' - page_limit = 38 + page_limit = 100 cursor = 'testString' # Invoke method @@ -1264,14 +1318,14 @@ def test_list_logs_all_params(self): filter=filter, page_limit=page_limit, cursor=cursor, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'sort={}'.format(sort) in query_string assert 'filter={}'.format(filter) in query_string @@ -1295,11 +1349,13 @@ def test_list_logs_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/logs') mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1307,7 +1363,7 @@ def test_list_logs_required_params(self): # Invoke method response = _service.list_logs( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -1331,11 +1387,13 @@ def test_list_logs_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/logs') mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1345,7 +1403,7 @@ def test_list_logs_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_logs(**req_copy) @@ -1358,6 +1416,7 @@ def test_list_logs_value_error_with_retries(self): _service.disable_retries() self.test_list_logs_value_error() + # endregion ############################################################################## # End of Service: Logs @@ -1368,7 +1427,8 @@ def test_list_logs_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -1380,9 +1440,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v2/user_data') - responses.add(responses.DELETE, - url, - status=202) + responses.add( + responses.DELETE, + url, + status=202, + ) # Set up parameter values customer_id = 'testString' @@ -1390,14 +1452,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -1417,9 +1479,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v2/user_data') - responses.add(responses.DELETE, - url, - status=202) + responses.add( + responses.DELETE, + url, + status=202, + ) # Set up parameter values customer_id = 'testString' @@ -1429,7 +1493,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -1442,6 +1506,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -1452,7 +1517,8 @@ def test_delete_user_data_value_error_with_retries(self): ############################################################################## # region -class TestListEnvironments(): + +class TestListEnvironments: """ Test Class for list_environments """ @@ -1465,15 +1531,17 @@ def test_list_environments_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments') mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'name' cursor = 'testString' @@ -1487,14 +1555,14 @@ def test_list_environments_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -1519,11 +1587,13 @@ def test_list_environments_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments') mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1531,7 +1601,7 @@ def test_list_environments_required_params(self): # Invoke method response = _service.list_environments( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -1555,11 +1625,13 @@ def test_list_environments_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments') mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1569,7 +1641,7 @@ def test_list_environments_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_environments(**req_copy) @@ -1582,7 +1654,8 @@ def test_list_environments_value_error_with_retries(self): _service.disable_retries() self.test_list_environments_value_error() -class TestGetEnvironment(): + +class TestGetEnvironment: """ Test Class for get_environment """ @@ -1595,11 +1668,13 @@ def test_get_environment_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1611,14 +1686,14 @@ def test_get_environment_all_params(self): assistant_id, environment_id, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -1639,11 +1714,13 @@ def test_get_environment_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1653,7 +1730,7 @@ def test_get_environment_required_params(self): response = _service.get_environment( assistant_id, environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -1677,11 +1754,13 @@ def test_get_environment_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1693,7 +1772,7 @@ def test_get_environment_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_environment(**req_copy) @@ -1706,7 +1785,8 @@ def test_get_environment_value_error_with_retries(self): _service.disable_retries() self.test_get_environment_value_error() -class TestUpdateEnvironment(): + +class TestUpdateEnvironment: """ Test Class for update_environment """ @@ -1719,11 +1799,13 @@ def test_update_environment_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a EnvironmentSkill model environment_skill_model = {} @@ -1749,7 +1831,7 @@ def test_update_environment_all_params(self): description=description, session_timeout=session_timeout, skill_references=skill_references, - headers={} + headers={}, ) # Check for correct operation @@ -1779,11 +1861,13 @@ def test_update_environment_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1793,7 +1877,7 @@ def test_update_environment_required_params(self): response = _service.update_environment( assistant_id, environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -1817,11 +1901,13 @@ def test_update_environment_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/environments/testString') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -1833,7 +1919,7 @@ def test_update_environment_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_environment(**req_copy) @@ -1846,6 +1932,7 @@ def test_update_environment_value_error_with_retries(self): _service.disable_retries() self.test_update_environment_value_error() + # endregion ############################################################################## # End of Service: Environments @@ -1856,7 +1943,8 @@ def test_update_environment_value_error_with_retries(self): ############################################################################## # region -class TestCreateRelease(): + +class TestCreateRelease: """ Test Class for create_release """ @@ -1869,11 +1957,13 @@ def test_create_release_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values assistant_id = 'testString' @@ -1883,7 +1973,7 @@ def test_create_release_all_params(self): response = _service.create_release( assistant_id, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -1910,11 +2000,13 @@ def test_create_release_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values assistant_id = 'testString' @@ -1922,7 +2014,7 @@ def test_create_release_required_params(self): # Invoke method response = _service.create_release( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -1946,11 +2038,13 @@ def test_create_release_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values assistant_id = 'testString' @@ -1960,7 +2054,7 @@ def test_create_release_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_release(**req_copy) @@ -1973,7 +2067,8 @@ def test_create_release_value_error_with_retries(self): _service.disable_retries() self.test_create_release_value_error() -class TestListReleases(): + +class TestListReleases: """ Test Class for list_releases """ @@ -1986,15 +2081,17 @@ def test_list_releases_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' - page_limit = 38 + page_limit = 100 include_count = False sort = 'name' cursor = 'testString' @@ -2008,14 +2105,14 @@ def test_list_releases_all_params(self): sort=sort, cursor=cursor, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'page_limit={}'.format(page_limit) in query_string assert 'include_count={}'.format('true' if include_count else 'false') in query_string @@ -2040,11 +2137,13 @@ def test_list_releases_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2052,7 +2151,7 @@ def test_list_releases_required_params(self): # Invoke method response = _service.list_releases( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -2076,11 +2175,13 @@ def test_list_releases_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases') mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2090,7 +2191,7 @@ def test_list_releases_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_releases(**req_copy) @@ -2103,7 +2204,8 @@ def test_list_releases_value_error_with_retries(self): _service.disable_retries() self.test_list_releases_value_error() -class TestGetRelease(): + +class TestGetRelease: """ Test Class for get_release """ @@ -2116,11 +2218,13 @@ def test_get_release_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2132,14 +2236,14 @@ def test_get_release_all_params(self): assistant_id, release, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -2160,11 +2264,13 @@ def test_get_release_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2174,7 +2280,7 @@ def test_get_release_required_params(self): response = _service.get_release( assistant_id, release, - headers={} + headers={}, ) # Check for correct operation @@ -2198,11 +2304,13 @@ def test_get_release_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString') mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2214,7 +2322,7 @@ def test_get_release_value_error(self): "release": release, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_release(**req_copy) @@ -2227,7 +2335,8 @@ def test_get_release_value_error_with_retries(self): _service.disable_retries() self.test_get_release_value_error() -class TestDeleteRelease(): + +class TestDeleteRelease: """ Test Class for delete_release """ @@ -2239,9 +2348,11 @@ def test_delete_release_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2251,7 +2362,7 @@ def test_delete_release_all_params(self): response = _service.delete_release( assistant_id, release, - headers={} + headers={}, ) # Check for correct operation @@ -2274,9 +2385,11 @@ def test_delete_release_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2288,7 +2401,7 @@ def test_delete_release_value_error(self): "release": release, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_release(**req_copy) @@ -2301,7 +2414,8 @@ def test_delete_release_value_error_with_retries(self): _service.disable_retries() self.test_delete_release_value_error() -class TestDeployRelease(): + +class TestDeployRelease: """ Test Class for deploy_release """ @@ -2314,11 +2428,13 @@ def test_deploy_release_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2332,14 +2448,14 @@ def test_deploy_release_all_params(self): release, environment_id, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -2363,11 +2479,13 @@ def test_deploy_release_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2379,7 +2497,7 @@ def test_deploy_release_required_params(self): assistant_id, release, environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -2406,11 +2524,13 @@ def test_deploy_release_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2424,7 +2544,7 @@ def test_deploy_release_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.deploy_release(**req_copy) @@ -2437,6 +2557,7 @@ def test_deploy_release_value_error_with_retries(self): _service.disable_retries() self.test_deploy_release_value_error() + # endregion ############################################################################## # End of Service: Releases @@ -2447,7 +2568,8 @@ def test_deploy_release_value_error_with_retries(self): ############################################################################## # region -class TestGetSkill(): + +class TestGetSkill: """ Test Class for get_skill """ @@ -2460,11 +2582,13 @@ def test_get_skill_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2474,7 +2598,7 @@ def test_get_skill_all_params(self): response = _service.get_skill( assistant_id, skill_id, - headers={} + headers={}, ) # Check for correct operation @@ -2498,11 +2622,13 @@ def test_get_skill_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2514,7 +2640,7 @@ def test_get_skill_value_error(self): "skill_id": skill_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_skill(**req_copy) @@ -2527,7 +2653,8 @@ def test_get_skill_value_error_with_retries(self): _service.disable_retries() self.test_get_skill_value_error() -class TestUpdateSkill(): + +class TestUpdateSkill: """ Test Class for update_skill """ @@ -2540,11 +2667,13 @@ def test_update_skill_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model search_settings_discovery_authentication_model = {} @@ -2586,8 +2715,8 @@ def test_update_skill_all_params(self): skill_id = 'testString' name = 'testString' description = 'testString' - workspace = {'foo': 'bar'} - dialog_settings = {'foo': 'bar'} + workspace = {'anyKey': 'anyValue'} + dialog_settings = {'anyKey': 'anyValue'} search_settings = search_settings_model # Invoke method @@ -2599,7 +2728,7 @@ def test_update_skill_all_params(self): workspace=workspace, dialog_settings=dialog_settings, search_settings=search_settings, - headers={} + headers={}, ) # Check for correct operation @@ -2609,8 +2738,8 @@ def test_update_skill_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['workspace'] == {'foo': 'bar'} - assert req_body['dialog_settings'] == {'foo': 'bar'} + assert req_body['workspace'] == {'anyKey': 'anyValue'} + assert req_body['dialog_settings'] == {'anyKey': 'anyValue'} assert req_body['search_settings'] == search_settings_model def test_update_skill_all_params_with_retries(self): @@ -2630,11 +2759,13 @@ def test_update_skill_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills/testString') mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model search_settings_discovery_authentication_model = {} @@ -2676,8 +2807,8 @@ def test_update_skill_value_error(self): skill_id = 'testString' name = 'testString' description = 'testString' - workspace = {'foo': 'bar'} - dialog_settings = {'foo': 'bar'} + workspace = {'anyKey': 'anyValue'} + dialog_settings = {'anyKey': 'anyValue'} search_settings = search_settings_model # Pass in all but one required param and check for a ValueError @@ -2686,7 +2817,7 @@ def test_update_skill_value_error(self): "skill_id": skill_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_skill(**req_copy) @@ -2699,7 +2830,8 @@ def test_update_skill_value_error_with_retries(self): _service.disable_retries() self.test_update_skill_value_error() -class TestExportSkills(): + +class TestExportSkills: """ Test Class for export_skills """ @@ -2712,11 +2844,13 @@ def test_export_skills_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_export') mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2726,14 +2860,14 @@ def test_export_skills_all_params(self): response = _service.export_skills( assistant_id, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string @@ -2754,11 +2888,13 @@ def test_export_skills_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_export') mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2766,7 +2902,7 @@ def test_export_skills_required_params(self): # Invoke method response = _service.export_skills( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -2790,11 +2926,13 @@ def test_export_skills_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_export') mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -2804,7 +2942,7 @@ def test_export_skills_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.export_skills(**req_copy) @@ -2817,7 +2955,8 @@ def test_export_skills_value_error_with_retries(self): _service.disable_retries() self.test_export_skills_value_error() -class TestImportSkills(): + +class TestImportSkills: """ Test Class for import_skills """ @@ -2830,11 +2969,13 @@ def test_import_skills_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_import') mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model search_settings_discovery_authentication_model = {} @@ -2875,8 +3016,8 @@ def test_import_skills_all_params(self): skill_import_model = {} skill_import_model['name'] = 'testString' skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'foo': 'bar'} - skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} skill_import_model['search_settings'] = search_settings_model skill_import_model['language'] = 'testString' skill_import_model['type'] = 'action' @@ -2898,14 +3039,14 @@ def test_import_skills_all_params(self): assistant_skills, assistant_state, include_audit=include_audit, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 202 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string # Validate body params @@ -2930,11 +3071,13 @@ def test_import_skills_required_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_import') mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model search_settings_discovery_authentication_model = {} @@ -2975,8 +3118,8 @@ def test_import_skills_required_params(self): skill_import_model = {} skill_import_model['name'] = 'testString' skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'foo': 'bar'} - skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} skill_import_model['search_settings'] = search_settings_model skill_import_model['language'] = 'testString' skill_import_model['type'] = 'action' @@ -2996,7 +3139,7 @@ def test_import_skills_required_params(self): assistant_id, assistant_skills, assistant_state, - headers={} + headers={}, ) # Check for correct operation @@ -3024,11 +3167,13 @@ def test_import_skills_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_import') mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model search_settings_discovery_authentication_model = {} @@ -3069,8 +3214,8 @@ def test_import_skills_value_error(self): skill_import_model = {} skill_import_model['name'] = 'testString' skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'foo': 'bar'} - skill_import_model['dialog_settings'] = {'foo': 'bar'} + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} skill_import_model['search_settings'] = search_settings_model skill_import_model['language'] = 'testString' skill_import_model['type'] = 'action' @@ -3092,7 +3237,7 @@ def test_import_skills_value_error(self): "assistant_state": assistant_state, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.import_skills(**req_copy) @@ -3105,7 +3250,8 @@ def test_import_skills_value_error_with_retries(self): _service.disable_retries() self.test_import_skills_value_error() -class TestImportSkillsStatus(): + +class TestImportSkillsStatus: """ Test Class for import_skills_status """ @@ -3118,11 +3264,13 @@ def test_import_skills_status_all_params(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_import/status') mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -3130,7 +3278,7 @@ def test_import_skills_status_all_params(self): # Invoke method response = _service.import_skills_status( assistant_id, - headers={} + headers={}, ) # Check for correct operation @@ -3154,11 +3302,13 @@ def test_import_skills_status_value_error(self): # Set up mock url = preprocess_url('/v2/assistants/testString/skills_import/status') mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values assistant_id = 'testString' @@ -3168,7 +3318,7 @@ def test_import_skills_status_value_error(self): "assistant_id": assistant_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.import_skills_status(**req_copy) @@ -3181,6 +3331,7 @@ def test_import_skills_status_value_error_with_retries(self): _service.disable_retries() self.test_import_skills_status_value_error() + # endregion ############################################################################## # End of Service: Skills @@ -3191,7 +3342,9 @@ def test_import_skills_status_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_AgentAvailabilityMessage(): + + +class TestModel_AgentAvailabilityMessage: """ Test Class for AgentAvailabilityMessage """ @@ -3220,7 +3373,8 @@ def test_agent_availability_message_serialization(self): agent_availability_message_model_json2 = agent_availability_message_model.to_dict() assert agent_availability_message_model_json2 == agent_availability_message_model_json -class TestModel_AssistantCollection(): + +class TestModel_AssistantCollection: """ Test Class for AssistantCollection """ @@ -3232,12 +3386,12 @@ def test_assistant_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - assistant_data_model = {} # AssistantData + assistant_data_model = {} # AssistantData assistant_data_model['name'] = 'testString' assistant_data_model['description'] = 'testString' assistant_data_model['language'] = 'testString' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -3265,7 +3419,8 @@ def test_assistant_collection_serialization(self): assistant_collection_model_json2 = assistant_collection_model.to_dict() assert assistant_collection_model_json2 == assistant_collection_model_json -class TestModel_AssistantData(): + +class TestModel_AssistantData: """ Test Class for AssistantData """ @@ -3296,7 +3451,8 @@ def test_assistant_data_serialization(self): assistant_data_model_json2 = assistant_data_model.to_dict() assert assistant_data_model_json2 == assistant_data_model_json -class TestModel_AssistantSkill(): + +class TestModel_AssistantSkill: """ Test Class for AssistantSkill """ @@ -3326,7 +3482,8 @@ def test_assistant_skill_serialization(self): assistant_skill_model_json2 = assistant_skill_model.to_dict() assert assistant_skill_model_json2 == assistant_skill_model_json -class TestModel_AssistantState(): + +class TestModel_AssistantState: """ Test Class for AssistantState """ @@ -3356,7 +3513,8 @@ def test_assistant_state_serialization(self): assistant_state_model_json2 = assistant_state_model.to_dict() assert assistant_state_model_json2 == assistant_state_model_json -class TestModel_BaseEnvironmentOrchestration(): + +class TestModel_BaseEnvironmentOrchestration: """ Test Class for BaseEnvironmentOrchestration """ @@ -3385,7 +3543,8 @@ def test_base_environment_orchestration_serialization(self): base_environment_orchestration_model_json2 = base_environment_orchestration_model.to_dict() assert base_environment_orchestration_model_json2 == base_environment_orchestration_model_json -class TestModel_BaseEnvironmentReleaseReference(): + +class TestModel_BaseEnvironmentReleaseReference: """ Test Class for BaseEnvironmentReleaseReference """ @@ -3414,7 +3573,8 @@ def test_base_environment_release_reference_serialization(self): base_environment_release_reference_model_json2 = base_environment_release_reference_model.to_dict() assert base_environment_release_reference_model_json2 == base_environment_release_reference_model_json -class TestModel_BulkClassifyOutput(): + +class TestModel_BulkClassifyOutput: """ Test Class for BulkClassifyOutput """ @@ -3426,14 +3586,14 @@ def test_bulk_classify_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model = {} # BulkClassifyUtterance bulk_classify_utterance_model['text'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -3461,14 +3621,14 @@ def test_bulk_classify_output_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -3479,7 +3639,7 @@ def test_bulk_classify_output_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' @@ -3505,7 +3665,8 @@ def test_bulk_classify_output_serialization(self): bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() assert bulk_classify_output_model_json2 == bulk_classify_output_model_json -class TestModel_BulkClassifyResponse(): + +class TestModel_BulkClassifyResponse: """ Test Class for BulkClassifyResponse """ @@ -3517,14 +3678,14 @@ def test_bulk_classify_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model = {} # BulkClassifyUtterance bulk_classify_utterance_model['text'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -3552,14 +3713,14 @@ def test_bulk_classify_response_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -3570,12 +3731,12 @@ def test_bulk_classify_response_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - bulk_classify_output_model = {} # BulkClassifyOutput + bulk_classify_output_model = {} # BulkClassifyOutput bulk_classify_output_model['input'] = bulk_classify_utterance_model bulk_classify_output_model['entities'] = [runtime_entity_model] bulk_classify_output_model['intents'] = [runtime_intent_model] @@ -3599,7 +3760,8 @@ def test_bulk_classify_response_serialization(self): bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() assert bulk_classify_response_model_json2 == bulk_classify_response_model_json -class TestModel_BulkClassifyUtterance(): + +class TestModel_BulkClassifyUtterance: """ Test Class for BulkClassifyUtterance """ @@ -3628,7 +3790,8 @@ def test_bulk_classify_utterance_serialization(self): bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json -class TestModel_CaptureGroup(): + +class TestModel_CaptureGroup: """ Test Class for CaptureGroup """ @@ -3658,7 +3821,8 @@ def test_capture_group_serialization(self): capture_group_model_json2 = capture_group_model.to_dict() assert capture_group_model_json2 == capture_group_model_json -class TestModel_ChannelTransferInfo(): + +class TestModel_ChannelTransferInfo: """ Test Class for ChannelTransferInfo """ @@ -3670,10 +3834,10 @@ def test_channel_transfer_info_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model # Construct a json representation of a ChannelTransferInfo model @@ -3695,7 +3859,8 @@ def test_channel_transfer_info_serialization(self): channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() assert channel_transfer_info_model_json2 == channel_transfer_info_model_json -class TestModel_ChannelTransferTarget(): + +class TestModel_ChannelTransferTarget: """ Test Class for ChannelTransferTarget """ @@ -3707,7 +3872,7 @@ def test_channel_transfer_target_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' # Construct a json representation of a ChannelTransferTarget model @@ -3729,7 +3894,8 @@ def test_channel_transfer_target_serialization(self): channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() assert channel_transfer_target_model_json2 == channel_transfer_target_model_json -class TestModel_ChannelTransferTargetChat(): + +class TestModel_ChannelTransferTargetChat: """ Test Class for ChannelTransferTargetChat """ @@ -3758,7 +3924,8 @@ def test_channel_transfer_target_chat_serialization(self): channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json -class TestModel_DialogLogMessage(): + +class TestModel_DialogLogMessage: """ Test Class for DialogLogMessage """ @@ -3770,7 +3937,7 @@ def test_dialog_log_message_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' @@ -3796,7 +3963,8 @@ def test_dialog_log_message_serialization(self): dialog_log_message_model_json2 = dialog_log_message_model.to_dict() assert dialog_log_message_model_json2 == dialog_log_message_model_json -class TestModel_DialogNodeAction(): + +class TestModel_DialogNodeAction: """ Test Class for DialogNodeAction """ @@ -3810,7 +3978,7 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json = {} dialog_node_action_model_json['name'] = 'testString' dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {'foo': 'bar'} + dialog_node_action_model_json['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model_json['result_variable'] = 'testString' dialog_node_action_model_json['credentials'] = 'testString' @@ -3829,7 +3997,8 @@ def test_dialog_node_action_serialization(self): dialog_node_action_model_json2 = dialog_node_action_model.to_dict() assert dialog_node_action_model_json2 == dialog_node_action_model_json -class TestModel_DialogNodeOutputConnectToAgentTransferInfo(): + +class TestModel_DialogNodeOutputConnectToAgentTransferInfo: """ Test Class for DialogNodeOutputConnectToAgentTransferInfo """ @@ -3841,7 +4010,7 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'foo': 'bar'}} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'anyKey': 'anyValue'}} # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) @@ -3858,7 +4027,8 @@ def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json -class TestModel_DialogNodeOutputOptionsElement(): + +class TestModel_DialogNodeOutputOptionsElement: """ Test Class for DialogNodeOutputOptionsElement """ @@ -3870,16 +4040,16 @@ def test_dialog_node_output_options_element_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -3907,14 +4077,14 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -3925,20 +4095,20 @@ def test_dialog_node_output_options_element_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model @@ -3946,7 +4116,7 @@ def test_dialog_node_output_options_element_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -3956,7 +4126,7 @@ def test_dialog_node_output_options_element_serialization(self): message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model # Construct a json representation of a DialogNodeOutputOptionsElement model @@ -3979,7 +4149,8 @@ def test_dialog_node_output_options_element_serialization(self): dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json -class TestModel_DialogNodeOutputOptionsElementValue(): + +class TestModel_DialogNodeOutputOptionsElementValue: """ Test Class for DialogNodeOutputOptionsElementValue """ @@ -3991,16 +4162,16 @@ def test_dialog_node_output_options_element_value_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -4028,14 +4199,14 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -4046,20 +4217,20 @@ def test_dialog_node_output_options_element_value_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model @@ -4067,7 +4238,7 @@ def test_dialog_node_output_options_element_value_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -4096,7 +4267,8 @@ def test_dialog_node_output_options_element_value_serialization(self): dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json -class TestModel_DialogNodeVisited(): + +class TestModel_DialogNodeVisited: """ Test Class for DialogNodeVisited """ @@ -4127,7 +4299,8 @@ def test_dialog_node_visited_serialization(self): dialog_node_visited_model_json2 = dialog_node_visited_model.to_dict() assert dialog_node_visited_model_json2 == dialog_node_visited_model_json -class TestModel_DialogSuggestion(): + +class TestModel_DialogSuggestion: """ Test Class for DialogSuggestion """ @@ -4139,16 +4312,16 @@ def test_dialog_suggestion_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -4176,14 +4349,14 @@ def test_dialog_suggestion_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -4194,20 +4367,20 @@ def test_dialog_suggestion_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model @@ -4215,7 +4388,7 @@ def test_dialog_suggestion_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -4225,14 +4398,14 @@ def test_dialog_suggestion_serialization(self): message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model = {} # DialogSuggestionValue dialog_suggestion_value_model['input'] = message_input_model # Construct a json representation of a DialogSuggestion model dialog_suggestion_model_json = {} dialog_suggestion_model_json['label'] = 'testString' dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {'foo': 'bar'} + dialog_suggestion_model_json['output'] = {'anyKey': 'anyValue'} # Construct a model instance of DialogSuggestion by calling from_dict on the json representation dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) @@ -4249,7 +4422,8 @@ def test_dialog_suggestion_serialization(self): dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() assert dialog_suggestion_model_json2 == dialog_suggestion_model_json -class TestModel_DialogSuggestionValue(): + +class TestModel_DialogSuggestionValue: """ Test Class for DialogSuggestionValue """ @@ -4261,16 +4435,16 @@ def test_dialog_suggestion_value_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -4298,14 +4472,14 @@ def test_dialog_suggestion_value_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -4316,20 +4490,20 @@ def test_dialog_suggestion_value_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model @@ -4337,7 +4511,7 @@ def test_dialog_suggestion_value_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -4366,7 +4540,8 @@ def test_dialog_suggestion_value_serialization(self): dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json -class TestModel_Environment(): + +class TestModel_Environment: """ Test Class for Environment """ @@ -4378,7 +4553,7 @@ def test_environment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_skill_model = {} # EnvironmentSkill + environment_skill_model = {} # EnvironmentSkill environment_skill_model['skill_id'] = 'testString' environment_skill_model['type'] = 'dialog' environment_skill_model['disabled'] = True @@ -4407,7 +4582,8 @@ def test_environment_serialization(self): environment_model_json2 = environment_model.to_dict() assert environment_model_json2 == environment_model_json -class TestModel_EnvironmentCollection(): + +class TestModel_EnvironmentCollection: """ Test Class for EnvironmentCollection """ @@ -4419,20 +4595,20 @@ def test_environment_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_skill_model = {} # EnvironmentSkill + environment_skill_model = {} # EnvironmentSkill environment_skill_model['skill_id'] = 'testString' environment_skill_model['type'] = 'dialog' environment_skill_model['disabled'] = True environment_skill_model['snapshot'] = 'testString' environment_skill_model['skill_reference'] = 'testString' - environment_model = {} # Environment + environment_model = {} # Environment environment_model['name'] = 'testString' environment_model['description'] = 'testString' environment_model['session_timeout'] = 10 environment_model['skill_references'] = [environment_skill_model] - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -4460,7 +4636,8 @@ def test_environment_collection_serialization(self): environment_collection_model_json2 = environment_collection_model.to_dict() assert environment_collection_model_json2 == environment_collection_model_json -class TestModel_EnvironmentReference(): + +class TestModel_EnvironmentReference: """ Test Class for EnvironmentReference """ @@ -4489,7 +4666,8 @@ def test_environment_reference_serialization(self): environment_reference_model_json2 = environment_reference_model.to_dict() assert environment_reference_model_json2 == environment_reference_model_json -class TestModel_EnvironmentSkill(): + +class TestModel_EnvironmentSkill: """ Test Class for EnvironmentSkill """ @@ -4522,7 +4700,8 @@ def test_environment_skill_serialization(self): environment_skill_model_json2 = environment_skill_model.to_dict() assert environment_skill_model_json2 == environment_skill_model_json -class TestModel_IntegrationReference(): + +class TestModel_IntegrationReference: """ Test Class for IntegrationReference """ @@ -4552,7 +4731,8 @@ def test_integration_reference_serialization(self): integration_reference_model_json2 = integration_reference_model.to_dict() assert integration_reference_model_json2 == integration_reference_model_json -class TestModel_Log(): + +class TestModel_Log: """ Test Class for Log """ @@ -4564,16 +4744,16 @@ def test_log_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -4601,14 +4781,14 @@ def test_log_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -4619,20 +4799,20 @@ def test_log_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model @@ -4640,7 +4820,7 @@ def test_log_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -4650,7 +4830,7 @@ def test_log_serialization(self): message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 @@ -4660,74 +4840,74 @@ def test_log_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal + message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_dialog_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills + message_context_skills_model = {} # MessageContextSkills message_context_skills_model['main skill'] = message_context_skill_dialog_model message_context_skills_model['actions skill'] = message_context_skill_action_model - message_context_model = {} # MessageContext + message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'foo': 'bar'} + message_context_model['integrations'] = {'anyKey': 'anyValue'} - message_request_model = {} # MessageRequest + message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['context'] = message_context_model message_request_model['user_id'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model = {} # DialogNodeVisited dialog_node_visited_model['dialog_node'] = 'testString' dialog_node_visited_model['title'] = 'testString' dialog_node_visited_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited message_output_debug_turn_event_model['event'] = 'action_visited' message_output_debug_turn_event_model['source'] = turn_event_action_source_model message_output_debug_turn_event_model['action_start_time'] = 'testString' @@ -4735,28 +4915,28 @@ def test_log_serialization(self): message_output_debug_turn_event_model['reason'] = 'intent' message_output_debug_turn_event_model['result_variable'] = 'testString' - message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - message_output_model = {} # MessageOutput + message_output_model = {} # MessageOutput message_output_model['generic'] = [runtime_response_generic_model] message_output_model['intents'] = [runtime_intent_model] message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'foo': 'bar'} + message_output_model['user_defined'] = {'anyKey': 'anyValue'} message_output_model['spelling'] = message_output_spelling_model - message_response_model = {} # MessageResponse + message_response_model = {} # MessageResponse message_response_model['output'] = message_output_model message_response_model['context'] = message_context_model message_response_model['user_id'] = 'testString' @@ -4790,7 +4970,8 @@ def test_log_serialization(self): log_model_json2 = log_model.to_dict() assert log_model_json2 == log_model_json -class TestModel_LogCollection(): + +class TestModel_LogCollection: """ Test Class for LogCollection """ @@ -4802,16 +4983,16 @@ def test_log_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -4839,14 +5020,14 @@ def test_log_collection_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -4857,20 +5038,20 @@ def test_log_collection_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model @@ -4878,7 +5059,7 @@ def test_log_collection_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -4888,7 +5069,7 @@ def test_log_collection_serialization(self): message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 @@ -4898,74 +5079,74 @@ def test_log_collection_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal + message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_dialog_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills + message_context_skills_model = {} # MessageContextSkills message_context_skills_model['main skill'] = message_context_skill_dialog_model message_context_skills_model['actions skill'] = message_context_skill_action_model - message_context_model = {} # MessageContext + message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'foo': 'bar'} + message_context_model['integrations'] = {'anyKey': 'anyValue'} - message_request_model = {} # MessageRequest + message_request_model = {} # MessageRequest message_request_model['input'] = message_input_model message_request_model['context'] = message_context_model message_request_model['user_id'] = 'testString' - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model = {} # DialogNodeVisited dialog_node_visited_model['dialog_node'] = 'testString' dialog_node_visited_model['title'] = 'testString' dialog_node_visited_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited message_output_debug_turn_event_model['event'] = 'action_visited' message_output_debug_turn_event_model['source'] = turn_event_action_source_model message_output_debug_turn_event_model['action_start_time'] = 'testString' @@ -4973,33 +5154,33 @@ def test_log_collection_serialization(self): message_output_debug_turn_event_model['reason'] = 'intent' message_output_debug_turn_event_model['result_variable'] = 'testString' - message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - message_output_model = {} # MessageOutput + message_output_model = {} # MessageOutput message_output_model['generic'] = [runtime_response_generic_model] message_output_model['intents'] = [runtime_intent_model] message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'foo': 'bar'} + message_output_model['user_defined'] = {'anyKey': 'anyValue'} message_output_model['spelling'] = message_output_spelling_model - message_response_model = {} # MessageResponse + message_response_model = {} # MessageResponse message_response_model['output'] = message_output_model message_response_model['context'] = message_context_model message_response_model['user_id'] = 'testString' - log_model = {} # Log + log_model = {} # Log log_model['log_id'] = 'testString' log_model['request'] = message_request_model log_model['response'] = message_response_model @@ -5012,7 +5193,7 @@ def test_log_collection_serialization(self): log_model['language'] = 'testString' log_model['customer_id'] = 'testString' - log_pagination_model = {} # LogPagination + log_pagination_model = {} # LogPagination log_pagination_model['next_url'] = 'testString' log_pagination_model['matched'] = 38 log_pagination_model['next_cursor'] = 'testString' @@ -5037,7 +5218,8 @@ def test_log_collection_serialization(self): log_collection_model_json2 = log_collection_model.to_dict() assert log_collection_model_json2 == log_collection_model_json -class TestModel_LogPagination(): + +class TestModel_LogPagination: """ Test Class for LogPagination """ @@ -5068,7 +5250,8 @@ def test_log_pagination_serialization(self): log_pagination_model_json2 = log_pagination_model.to_dict() assert log_pagination_model_json2 == log_pagination_model_json -class TestModel_MessageContext(): + +class TestModel_MessageContext: """ Test Class for MessageContext """ @@ -5080,7 +5263,7 @@ def test_message_context_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 @@ -5090,24 +5273,24 @@ def test_message_context_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal + message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_dialog_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills + message_context_skills_model = {} # MessageContextSkills message_context_skills_model['main skill'] = message_context_skill_dialog_model message_context_skills_model['actions skill'] = message_context_skill_action_model @@ -5115,7 +5298,7 @@ def test_message_context_serialization(self): message_context_model_json = {} message_context_model_json['global'] = message_context_global_model message_context_model_json['skills'] = message_context_skills_model - message_context_model_json['integrations'] = {'foo': 'bar'} + message_context_model_json['integrations'] = {'anyKey': 'anyValue'} # Construct a model instance of MessageContext by calling from_dict on the json representation message_context_model = MessageContext.from_dict(message_context_model_json) @@ -5132,7 +5315,8 @@ def test_message_context_serialization(self): message_context_model_json2 = message_context_model.to_dict() assert message_context_model_json2 == message_context_model_json -class TestModel_MessageContextGlobal(): + +class TestModel_MessageContextGlobal: """ Test Class for MessageContextGlobal """ @@ -5144,7 +5328,7 @@ def test_message_context_global_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 @@ -5173,7 +5357,8 @@ def test_message_context_global_serialization(self): message_context_global_model_json2 = message_context_global_model.to_dict() assert message_context_global_model_json2 == message_context_global_model_json -class TestModel_MessageContextGlobalStateless(): + +class TestModel_MessageContextGlobalStateless: """ Test Class for MessageContextGlobalStateless """ @@ -5185,7 +5370,7 @@ def test_message_context_global_stateless_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 @@ -5215,7 +5400,8 @@ def test_message_context_global_stateless_serialization(self): message_context_global_stateless_model_json2 = message_context_global_stateless_model.to_dict() assert message_context_global_stateless_model_json2 == message_context_global_stateless_model_json -class TestModel_MessageContextGlobalSystem(): + +class TestModel_MessageContextGlobalSystem: """ Test Class for MessageContextGlobalSystem """ @@ -5251,7 +5437,8 @@ def test_message_context_global_system_serialization(self): message_context_global_system_model_json2 = message_context_global_system_model.to_dict() assert message_context_global_system_model_json2 == message_context_global_system_model_json -class TestModel_MessageContextSkillAction(): + +class TestModel_MessageContextSkillAction: """ Test Class for MessageContextSkillAction """ @@ -5263,16 +5450,16 @@ def test_message_context_skill_action_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' # Construct a json representation of a MessageContextSkillAction model message_context_skill_action_model_json = {} - message_context_skill_action_model_json['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model_json['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_action_model_json['system'] = message_context_skill_system_model - message_context_skill_action_model_json['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model_json['skill_variables'] = {'foo': 'bar'} + message_context_skill_action_model_json['action_variables'] = {'anyKey': 'anyValue'} + message_context_skill_action_model_json['skill_variables'] = {'anyKey': 'anyValue'} # Construct a model instance of MessageContextSkillAction by calling from_dict on the json representation message_context_skill_action_model = MessageContextSkillAction.from_dict(message_context_skill_action_model_json) @@ -5289,7 +5476,8 @@ def test_message_context_skill_action_serialization(self): message_context_skill_action_model_json2 = message_context_skill_action_model.to_dict() assert message_context_skill_action_model_json2 == message_context_skill_action_model_json -class TestModel_MessageContextSkillDialog(): + +class TestModel_MessageContextSkillDialog: """ Test Class for MessageContextSkillDialog """ @@ -5301,13 +5489,13 @@ def test_message_context_skill_dialog_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' # Construct a json representation of a MessageContextSkillDialog model message_context_skill_dialog_model_json = {} - message_context_skill_dialog_model_json['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model_json['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_dialog_model_json['system'] = message_context_skill_system_model # Construct a model instance of MessageContextSkillDialog by calling from_dict on the json representation @@ -5325,7 +5513,8 @@ def test_message_context_skill_dialog_serialization(self): message_context_skill_dialog_model_json2 = message_context_skill_dialog_model.to_dict() assert message_context_skill_dialog_model_json2 == message_context_skill_dialog_model_json -class TestModel_MessageContextSkillSystem(): + +class TestModel_MessageContextSkillSystem: """ Test Class for MessageContextSkillSystem """ @@ -5365,7 +5554,8 @@ def test_message_context_skill_system_serialization(self): actual_dict = message_context_skill_system_model.get_properties() assert actual_dict == expected_dict -class TestModel_MessageContextSkills(): + +class TestModel_MessageContextSkills: """ Test Class for MessageContextSkills """ @@ -5377,19 +5567,19 @@ def test_message_context_skills_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_dialog_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} # Construct a json representation of a MessageContextSkills model message_context_skills_model_json = {} @@ -5411,7 +5601,8 @@ def test_message_context_skills_serialization(self): message_context_skills_model_json2 = message_context_skills_model.to_dict() assert message_context_skills_model_json2 == message_context_skills_model_json -class TestModel_MessageContextStateless(): + +class TestModel_MessageContextStateless: """ Test Class for MessageContextStateless """ @@ -5423,7 +5614,7 @@ def test_message_context_stateless_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 @@ -5433,25 +5624,25 @@ def test_message_context_stateless_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_stateless_model = {} # MessageContextGlobalStateless + message_context_global_stateless_model = {} # MessageContextGlobalStateless message_context_global_stateless_model['system'] = message_context_global_system_model message_context_global_stateless_model['session_id'] = 'testString' - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_dialog_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills + message_context_skills_model = {} # MessageContextSkills message_context_skills_model['main skill'] = message_context_skill_dialog_model message_context_skills_model['actions skill'] = message_context_skill_action_model @@ -5459,7 +5650,7 @@ def test_message_context_stateless_serialization(self): message_context_stateless_model_json = {} message_context_stateless_model_json['global'] = message_context_global_stateless_model message_context_stateless_model_json['skills'] = message_context_skills_model - message_context_stateless_model_json['integrations'] = {'foo': 'bar'} + message_context_stateless_model_json['integrations'] = {'anyKey': 'anyValue'} # Construct a model instance of MessageContextStateless by calling from_dict on the json representation message_context_stateless_model = MessageContextStateless.from_dict(message_context_stateless_model_json) @@ -5476,7 +5667,8 @@ def test_message_context_stateless_serialization(self): message_context_stateless_model_json2 = message_context_stateless_model.to_dict() assert message_context_stateless_model_json2 == message_context_stateless_model_json -class TestModel_MessageInput(): + +class TestModel_MessageInput: """ Test Class for MessageInput """ @@ -5488,16 +5680,16 @@ def test_message_input_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -5525,14 +5717,14 @@ def test_message_input_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -5543,20 +5735,20 @@ def test_message_input_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model @@ -5590,7 +5782,8 @@ def test_message_input_serialization(self): message_input_model_json2 = message_input_model.to_dict() assert message_input_model_json2 == message_input_model_json -class TestModel_MessageInputAttachment(): + +class TestModel_MessageInputAttachment: """ Test Class for MessageInputAttachment """ @@ -5620,7 +5813,8 @@ def test_message_input_attachment_serialization(self): message_input_attachment_model_json2 = message_input_attachment_model.to_dict() assert message_input_attachment_model_json2 == message_input_attachment_model_json -class TestModel_MessageInputOptions(): + +class TestModel_MessageInputOptions: """ Test Class for MessageInputOptions """ @@ -5632,7 +5826,7 @@ def test_message_input_options_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -5660,7 +5854,8 @@ def test_message_input_options_serialization(self): message_input_options_model_json2 = message_input_options_model.to_dict() assert message_input_options_model_json2 == message_input_options_model_json -class TestModel_MessageInputOptionsSpelling(): + +class TestModel_MessageInputOptionsSpelling: """ Test Class for MessageInputOptionsSpelling """ @@ -5690,7 +5885,8 @@ def test_message_input_options_spelling_serialization(self): message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json -class TestModel_MessageInputOptionsStateless(): + +class TestModel_MessageInputOptionsStateless: """ Test Class for MessageInputOptionsStateless """ @@ -5702,7 +5898,7 @@ def test_message_input_options_stateless_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True @@ -5728,7 +5924,8 @@ def test_message_input_options_stateless_serialization(self): message_input_options_stateless_model_json2 = message_input_options_stateless_model.to_dict() assert message_input_options_stateless_model_json2 == message_input_options_stateless_model_json -class TestModel_MessageInputStateless(): + +class TestModel_MessageInputStateless: """ Test Class for MessageInputStateless """ @@ -5740,16 +5937,16 @@ def test_message_input_stateless_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -5777,14 +5974,14 @@ def test_message_input_stateless_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -5795,20 +5992,20 @@ def test_message_input_stateless_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_stateless_model = {} # MessageInputOptionsStateless + message_input_options_stateless_model = {} # MessageInputOptionsStateless message_input_options_stateless_model['restart'] = False message_input_options_stateless_model['alternate_intents'] = False message_input_options_stateless_model['spelling'] = message_input_options_spelling_model @@ -5840,7 +6037,8 @@ def test_message_input_stateless_serialization(self): message_input_stateless_model_json2 = message_input_stateless_model.to_dict() assert message_input_stateless_model_json2 == message_input_stateless_model_json -class TestModel_MessageOutput(): + +class TestModel_MessageOutput: """ Test Class for MessageOutput """ @@ -5852,24 +6050,24 @@ def test_message_output_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -5897,14 +6095,14 @@ def test_message_output_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -5915,35 +6113,35 @@ def test_message_output_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model = {} # DialogNodeVisited dialog_node_visited_model['dialog_node'] = 'testString' dialog_node_visited_model['title'] = 'testString' dialog_node_visited_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited message_output_debug_turn_event_model['event'] = 'action_visited' message_output_debug_turn_event_model['source'] = turn_event_action_source_model message_output_debug_turn_event_model['action_start_time'] = 'testString' @@ -5951,14 +6149,14 @@ def test_message_output_serialization(self): message_output_debug_turn_event_model['reason'] = 'intent' message_output_debug_turn_event_model['result_variable'] = 'testString' - message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' @@ -5970,7 +6168,7 @@ def test_message_output_serialization(self): message_output_model_json['entities'] = [runtime_entity_model] message_output_model_json['actions'] = [dialog_node_action_model] message_output_model_json['debug'] = message_output_debug_model - message_output_model_json['user_defined'] = {'foo': 'bar'} + message_output_model_json['user_defined'] = {'anyKey': 'anyValue'} message_output_model_json['spelling'] = message_output_spelling_model # Construct a model instance of MessageOutput by calling from_dict on the json representation @@ -5988,7 +6186,8 @@ def test_message_output_serialization(self): message_output_model_json2 = message_output_model.to_dict() assert message_output_model_json2 == message_output_model_json -class TestModel_MessageOutputDebug(): + +class TestModel_MessageOutputDebug: """ Test Class for MessageOutputDebug """ @@ -6000,28 +6199,28 @@ def test_message_output_debug_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model = {} # DialogNodeVisited dialog_node_visited_model['dialog_node'] = 'testString' dialog_node_visited_model['title'] = 'testString' dialog_node_visited_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited message_output_debug_turn_event_model['event'] = 'action_visited' message_output_debug_turn_event_model['source'] = turn_event_action_source_model message_output_debug_turn_event_model['action_start_time'] = 'testString' @@ -6052,7 +6251,8 @@ def test_message_output_debug_serialization(self): message_output_debug_model_json2 = message_output_debug_model.to_dict() assert message_output_debug_model_json2 == message_output_debug_model_json -class TestModel_MessageOutputSpelling(): + +class TestModel_MessageOutputSpelling: """ Test Class for MessageOutputSpelling """ @@ -6083,7 +6283,8 @@ def test_message_output_spelling_serialization(self): message_output_spelling_model_json2 = message_output_spelling_model.to_dict() assert message_output_spelling_model_json2 == message_output_spelling_model_json -class TestModel_MessageRequest(): + +class TestModel_MessageRequest: """ Test Class for MessageRequest """ @@ -6095,16 +6296,16 @@ def test_message_request_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -6132,14 +6333,14 @@ def test_message_request_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -6150,20 +6351,20 @@ def test_message_request_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model @@ -6171,7 +6372,7 @@ def test_message_request_serialization(self): message_input_options_model['return_context'] = True message_input_options_model['export'] = True - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'Hello' message_input_model['intents'] = [runtime_intent_model] @@ -6181,7 +6382,7 @@ def test_message_request_serialization(self): message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' message_context_global_system_model['user_id'] = 'my_user_id' message_context_global_system_model['turn_count'] = 38 @@ -6191,31 +6392,31 @@ def test_message_request_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal + message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_dialog_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills + message_context_skills_model = {} # MessageContextSkills message_context_skills_model['main skill'] = message_context_skill_dialog_model message_context_skills_model['actions skill'] = message_context_skill_action_model - message_context_model = {} # MessageContext + message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'foo': 'bar'} + message_context_model['integrations'] = {'anyKey': 'anyValue'} # Construct a json representation of a MessageRequest model message_request_model_json = {} @@ -6238,7 +6439,8 @@ def test_message_request_serialization(self): message_request_model_json2 = message_request_model.to_dict() assert message_request_model_json2 == message_request_model_json -class TestModel_MessageResponse(): + +class TestModel_MessageResponse: """ Test Class for MessageResponse """ @@ -6250,24 +6452,24 @@ def test_message_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -6295,14 +6497,14 @@ def test_message_response_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -6313,35 +6515,35 @@ def test_message_response_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model = {} # DialogNodeVisited dialog_node_visited_model['dialog_node'] = 'testString' dialog_node_visited_model['title'] = 'testString' dialog_node_visited_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited message_output_debug_turn_event_model['event'] = 'action_visited' message_output_debug_turn_event_model['source'] = turn_event_action_source_model message_output_debug_turn_event_model['action_start_time'] = 'testString' @@ -6349,28 +6551,28 @@ def test_message_response_serialization(self): message_output_debug_turn_event_model['reason'] = 'intent' message_output_debug_turn_event_model['result_variable'] = 'testString' - message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - message_output_model = {} # MessageOutput + message_output_model = {} # MessageOutput message_output_model['generic'] = [runtime_response_generic_model] message_output_model['intents'] = [runtime_intent_model] message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'foo': 'bar'} + message_output_model['user_defined'] = {'anyKey': 'anyValue'} message_output_model['spelling'] = message_output_spelling_model - message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 @@ -6380,31 +6582,31 @@ def test_message_response_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal + message_context_global_model = {} # MessageContextGlobal message_context_global_model['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_dialog_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills + message_context_skills_model = {} # MessageContextSkills message_context_skills_model['main skill'] = message_context_skill_dialog_model message_context_skills_model['actions skill'] = message_context_skill_action_model - message_context_model = {} # MessageContext + message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'foo': 'bar'} + message_context_model['integrations'] = {'anyKey': 'anyValue'} # Construct a json representation of a MessageResponse model message_response_model_json = {} @@ -6427,7 +6629,8 @@ def test_message_response_serialization(self): message_response_model_json2 = message_response_model.to_dict() assert message_response_model_json2 == message_response_model_json -class TestModel_MessageResponseStateless(): + +class TestModel_MessageResponseStateless: """ Test Class for MessageResponseStateless """ @@ -6439,24 +6642,24 @@ def test_message_response_stateless_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText runtime_response_generic_model['response_type'] = 'text' runtime_response_generic_model['text'] = 'testString' runtime_response_generic_model['channels'] = [response_generic_channel_model] - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -6484,14 +6687,14 @@ def test_message_response_stateless_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -6502,35 +6705,35 @@ def test_message_response_stateless_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'foo': 'bar'} + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} dialog_node_action_model['result_variable'] = 'testString' dialog_node_action_model['credentials'] = 'testString' - dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model = {} # DialogNodeVisited dialog_node_visited_model['dialog_node'] = 'testString' dialog_node_visited_model['title'] = 'testString' dialog_node_visited_model['conditions'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model = {} # LogMessageSourceDialogNode log_message_source_model['type'] = 'dialog_node' log_message_source_model['dialog_node'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model = {} # DialogLogMessage dialog_log_message_model['level'] = 'info' dialog_log_message_model['message'] = 'testString' dialog_log_message_model['code'] = 'testString' dialog_log_message_model['source'] = log_message_source_model - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited message_output_debug_turn_event_model['event'] = 'action_visited' message_output_debug_turn_event_model['source'] = turn_event_action_source_model message_output_debug_turn_event_model['action_start_time'] = 'testString' @@ -6538,28 +6741,28 @@ def test_message_response_stateless_serialization(self): message_output_debug_turn_event_model['reason'] = 'intent' message_output_debug_turn_event_model['result_variable'] = 'testString' - message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model = {} # MessageOutputDebug message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] message_output_debug_model['log_messages'] = [dialog_log_message_model] message_output_debug_model['branch_exited'] = True message_output_debug_model['branch_exited_reason'] = 'completed' message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model = {} # MessageOutputSpelling message_output_spelling_model['text'] = 'testString' message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - message_output_model = {} # MessageOutput + message_output_model = {} # MessageOutput message_output_model['generic'] = [runtime_response_generic_model] message_output_model['intents'] = [runtime_intent_model] message_output_model['entities'] = [runtime_entity_model] message_output_model['actions'] = [dialog_node_action_model] message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'foo': 'bar'} + message_output_model['user_defined'] = {'anyKey': 'anyValue'} message_output_model['spelling'] = message_output_spelling_model - message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 @@ -6569,32 +6772,32 @@ def test_message_response_stateless_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_stateless_model = {} # MessageContextGlobalStateless + message_context_global_stateless_model = {} # MessageContextGlobalStateless message_context_global_stateless_model['system'] = message_context_global_system_model message_context_global_stateless_model['session_id'] = 'testString' - message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'foo': 'bar'} + message_context_skill_dialog_model = {} # MessageContextSkillDialog + message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_dialog_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'foo': 'bar'} + message_context_skill_action_model = {} # MessageContextSkillAction + message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'foo': 'bar'} - message_context_skill_action_model['skill_variables'] = {'foo': 'bar'} + message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills + message_context_skills_model = {} # MessageContextSkills message_context_skills_model['main skill'] = message_context_skill_dialog_model message_context_skills_model['actions skill'] = message_context_skill_action_model - message_context_stateless_model = {} # MessageContextStateless + message_context_stateless_model = {} # MessageContextStateless message_context_stateless_model['global'] = message_context_global_stateless_model message_context_stateless_model['skills'] = message_context_skills_model - message_context_stateless_model['integrations'] = {'foo': 'bar'} + message_context_stateless_model['integrations'] = {'anyKey': 'anyValue'} # Construct a json representation of a MessageResponseStateless model message_response_stateless_model_json = {} @@ -6617,7 +6820,8 @@ def test_message_response_stateless_serialization(self): message_response_stateless_model_json2 = message_response_stateless_model.to_dict() assert message_response_stateless_model_json2 == message_response_stateless_model_json -class TestModel_Pagination(): + +class TestModel_Pagination: """ Test Class for Pagination """ @@ -6651,7 +6855,8 @@ def test_pagination_serialization(self): pagination_model_json2 = pagination_model.to_dict() assert pagination_model_json2 == pagination_model_json -class TestModel_Release(): + +class TestModel_Release: """ Test Class for Release """ @@ -6680,7 +6885,8 @@ def test_release_serialization(self): release_model_json2 = release_model.to_dict() assert release_model_json2 == release_model_json -class TestModel_ReleaseCollection(): + +class TestModel_ReleaseCollection: """ Test Class for ReleaseCollection """ @@ -6692,10 +6898,10 @@ def test_release_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - release_model = {} # Release + release_model = {} # Release release_model['description'] = 'testString' - pagination_model = {} # Pagination + pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' pagination_model['next_url'] = 'testString' pagination_model['total'] = 38 @@ -6723,7 +6929,8 @@ def test_release_collection_serialization(self): release_collection_model_json2 = release_collection_model.to_dict() assert release_collection_model_json2 == release_collection_model_json -class TestModel_ReleaseContent(): + +class TestModel_ReleaseContent: """ Test Class for ReleaseContent """ @@ -6751,7 +6958,8 @@ def test_release_content_serialization(self): release_content_model_json2 = release_content_model.to_dict() assert release_content_model_json2 == release_content_model_json -class TestModel_ReleaseSkill(): + +class TestModel_ReleaseSkill: """ Test Class for ReleaseSkill """ @@ -6782,7 +6990,8 @@ def test_release_skill_serialization(self): release_skill_model_json2 = release_skill_model.to_dict() assert release_skill_model_json2 == release_skill_model_json -class TestModel_RequestAnalytics(): + +class TestModel_RequestAnalytics: """ Test Class for RequestAnalytics """ @@ -6813,7 +7022,8 @@ def test_request_analytics_serialization(self): request_analytics_model_json2 = request_analytics_model.to_dict() assert request_analytics_model_json2 == request_analytics_model_json -class TestModel_ResponseGenericChannel(): + +class TestModel_ResponseGenericChannel: """ Test Class for ResponseGenericChannel """ @@ -6842,7 +7052,8 @@ def test_response_generic_channel_serialization(self): response_generic_channel_model_json2 = response_generic_channel_model.to_dict() assert response_generic_channel_model_json2 == response_generic_channel_model_json -class TestModel_RuntimeEntity(): + +class TestModel_RuntimeEntity: """ Test Class for RuntimeEntity """ @@ -6854,11 +7065,11 @@ def test_runtime_entity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -6886,11 +7097,11 @@ def test_runtime_entity_serialization(self): runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' # Construct a json representation of a RuntimeEntity model @@ -6920,7 +7131,8 @@ def test_runtime_entity_serialization(self): runtime_entity_model_json2 = runtime_entity_model.to_dict() assert runtime_entity_model_json2 == runtime_entity_model_json -class TestModel_RuntimeEntityAlternative(): + +class TestModel_RuntimeEntityAlternative: """ Test Class for RuntimeEntityAlternative """ @@ -6950,7 +7162,8 @@ def test_runtime_entity_alternative_serialization(self): runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json -class TestModel_RuntimeEntityInterpretation(): + +class TestModel_RuntimeEntityInterpretation: """ Test Class for RuntimeEntityInterpretation """ @@ -7004,7 +7217,8 @@ def test_runtime_entity_interpretation_serialization(self): runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json -class TestModel_RuntimeEntityRole(): + +class TestModel_RuntimeEntityRole: """ Test Class for RuntimeEntityRole """ @@ -7033,7 +7247,8 @@ def test_runtime_entity_role_serialization(self): runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() assert runtime_entity_role_model_json2 == runtime_entity_role_model_json -class TestModel_RuntimeIntent(): + +class TestModel_RuntimeIntent: """ Test Class for RuntimeIntent """ @@ -7064,7 +7279,8 @@ def test_runtime_intent_serialization(self): runtime_intent_model_json2 = runtime_intent_model.to_dict() assert runtime_intent_model_json2 == runtime_intent_model_json -class TestModel_SearchResult(): + +class TestModel_SearchResult: """ Test Class for SearchResult """ @@ -7076,17 +7292,17 @@ def test_search_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - search_result_metadata_model = {} # SearchResultMetadata + search_result_metadata_model = {} # SearchResultMetadata search_result_metadata_model['confidence'] = 72.5 search_result_metadata_model['score'] = 72.5 - search_result_highlight_model = {} # SearchResultHighlight + search_result_highlight_model = {} # SearchResultHighlight search_result_highlight_model['body'] = ['testString'] search_result_highlight_model['title'] = ['testString'] search_result_highlight_model['url'] = ['testString'] search_result_highlight_model['foo'] = ['testString'] - search_result_answer_model = {} # SearchResultAnswer + search_result_answer_model = {} # SearchResultAnswer search_result_answer_model['text'] = 'testString' search_result_answer_model['confidence'] = 0 @@ -7115,7 +7331,8 @@ def test_search_result_serialization(self): search_result_model_json2 = search_result_model.to_dict() assert search_result_model_json2 == search_result_model_json -class TestModel_SearchResultAnswer(): + +class TestModel_SearchResultAnswer: """ Test Class for SearchResultAnswer """ @@ -7145,7 +7362,8 @@ def test_search_result_answer_serialization(self): search_result_answer_model_json2 = search_result_answer_model.to_dict() assert search_result_answer_model_json2 == search_result_answer_model_json -class TestModel_SearchResultHighlight(): + +class TestModel_SearchResultHighlight: """ Test Class for SearchResultHighlight """ @@ -7187,7 +7405,8 @@ def test_search_result_highlight_serialization(self): actual_dict = search_result_highlight_model.get_properties() assert actual_dict == expected_dict -class TestModel_SearchResultMetadata(): + +class TestModel_SearchResultMetadata: """ Test Class for SearchResultMetadata """ @@ -7217,7 +7436,8 @@ def test_search_result_metadata_serialization(self): search_result_metadata_model_json2 = search_result_metadata_model.to_dict() assert search_result_metadata_model_json2 == search_result_metadata_model_json -class TestModel_SearchSettings(): + +class TestModel_SearchSettings: """ Test Class for SearchSettings """ @@ -7229,11 +7449,11 @@ def test_search_settings_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication search_settings_discovery_authentication_model['basic'] = 'testString' search_settings_discovery_authentication_model['bearer'] = 'testString' - search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model = {} # SearchSettingsDiscovery search_settings_discovery_model['instance_id'] = 'testString' search_settings_discovery_model['project_id'] = 'testString' search_settings_discovery_model['url'] = 'testString' @@ -7244,12 +7464,12 @@ def test_search_settings_serialization(self): search_settings_discovery_model['find_answers'] = True search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model = {} # SearchSettingsMessages search_settings_messages_model['success'] = 'testString' search_settings_messages_model['error'] = 'testString' search_settings_messages_model['no_result'] = 'testString' - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping search_settings_schema_mapping_model['url'] = 'testString' search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' @@ -7275,7 +7495,8 @@ def test_search_settings_serialization(self): search_settings_model_json2 = search_settings_model.to_dict() assert search_settings_model_json2 == search_settings_model_json -class TestModel_SearchSettingsDiscovery(): + +class TestModel_SearchSettingsDiscovery: """ Test Class for SearchSettingsDiscovery """ @@ -7287,7 +7508,7 @@ def test_search_settings_discovery_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication search_settings_discovery_authentication_model['basic'] = 'testString' search_settings_discovery_authentication_model['bearer'] = 'testString' @@ -7318,7 +7539,8 @@ def test_search_settings_discovery_serialization(self): search_settings_discovery_model_json2 = search_settings_discovery_model.to_dict() assert search_settings_discovery_model_json2 == search_settings_discovery_model_json -class TestModel_SearchSettingsDiscoveryAuthentication(): + +class TestModel_SearchSettingsDiscoveryAuthentication: """ Test Class for SearchSettingsDiscoveryAuthentication """ @@ -7348,7 +7570,8 @@ def test_search_settings_discovery_authentication_serialization(self): search_settings_discovery_authentication_model_json2 = search_settings_discovery_authentication_model.to_dict() assert search_settings_discovery_authentication_model_json2 == search_settings_discovery_authentication_model_json -class TestModel_SearchSettingsMessages(): + +class TestModel_SearchSettingsMessages: """ Test Class for SearchSettingsMessages """ @@ -7379,7 +7602,8 @@ def test_search_settings_messages_serialization(self): search_settings_messages_model_json2 = search_settings_messages_model.to_dict() assert search_settings_messages_model_json2 == search_settings_messages_model_json -class TestModel_SearchSettingsSchemaMapping(): + +class TestModel_SearchSettingsSchemaMapping: """ Test Class for SearchSettingsSchemaMapping """ @@ -7410,7 +7634,8 @@ def test_search_settings_schema_mapping_serialization(self): search_settings_schema_mapping_model_json2 = search_settings_schema_mapping_model.to_dict() assert search_settings_schema_mapping_model_json2 == search_settings_schema_mapping_model_json -class TestModel_SearchSkillWarning(): + +class TestModel_SearchSkillWarning: """ Test Class for SearchSkillWarning """ @@ -7441,7 +7666,8 @@ def test_search_skill_warning_serialization(self): search_skill_warning_model_json2 = search_skill_warning_model.to_dict() assert search_skill_warning_model_json2 == search_skill_warning_model_json -class TestModel_SessionResponse(): + +class TestModel_SessionResponse: """ Test Class for SessionResponse """ @@ -7470,7 +7696,8 @@ def test_session_response_serialization(self): session_response_model_json2 = session_response_model.to_dict() assert session_response_model_json2 == session_response_model_json -class TestModel_Skill(): + +class TestModel_Skill: """ Test Class for Skill """ @@ -7482,11 +7709,11 @@ def test_skill_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication search_settings_discovery_authentication_model['basic'] = 'testString' search_settings_discovery_authentication_model['bearer'] = 'testString' - search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model = {} # SearchSettingsDiscovery search_settings_discovery_model['instance_id'] = 'testString' search_settings_discovery_model['project_id'] = 'testString' search_settings_discovery_model['url'] = 'testString' @@ -7497,17 +7724,17 @@ def test_skill_serialization(self): search_settings_discovery_model['find_answers'] = True search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model = {} # SearchSettingsMessages search_settings_messages_model['success'] = 'testString' search_settings_messages_model['error'] = 'testString' search_settings_messages_model['no_result'] = 'testString' - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping search_settings_schema_mapping_model['url'] = 'testString' search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' - search_settings_model = {} # SearchSettings + search_settings_model = {} # SearchSettings search_settings_model['discovery'] = search_settings_discovery_model search_settings_model['messages'] = search_settings_messages_model search_settings_model['schema_mapping'] = search_settings_schema_mapping_model @@ -7516,8 +7743,8 @@ def test_skill_serialization(self): skill_model_json = {} skill_model_json['name'] = 'testString' skill_model_json['description'] = 'testString' - skill_model_json['workspace'] = {'foo': 'bar'} - skill_model_json['dialog_settings'] = {'foo': 'bar'} + skill_model_json['workspace'] = {'anyKey': 'anyValue'} + skill_model_json['dialog_settings'] = {'anyKey': 'anyValue'} skill_model_json['search_settings'] = search_settings_model skill_model_json['language'] = 'testString' skill_model_json['type'] = 'action' @@ -7537,7 +7764,8 @@ def test_skill_serialization(self): skill_model_json2 = skill_model.to_dict() assert skill_model_json2 == skill_model_json -class TestModel_SkillImport(): + +class TestModel_SkillImport: """ Test Class for SkillImport """ @@ -7549,11 +7777,11 @@ def test_skill_import_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication search_settings_discovery_authentication_model['basic'] = 'testString' search_settings_discovery_authentication_model['bearer'] = 'testString' - search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model = {} # SearchSettingsDiscovery search_settings_discovery_model['instance_id'] = 'testString' search_settings_discovery_model['project_id'] = 'testString' search_settings_discovery_model['url'] = 'testString' @@ -7564,17 +7792,17 @@ def test_skill_import_serialization(self): search_settings_discovery_model['find_answers'] = True search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model = {} # SearchSettingsMessages search_settings_messages_model['success'] = 'testString' search_settings_messages_model['error'] = 'testString' search_settings_messages_model['no_result'] = 'testString' - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping search_settings_schema_mapping_model['url'] = 'testString' search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' - search_settings_model = {} # SearchSettings + search_settings_model = {} # SearchSettings search_settings_model['discovery'] = search_settings_discovery_model search_settings_model['messages'] = search_settings_messages_model search_settings_model['schema_mapping'] = search_settings_schema_mapping_model @@ -7583,8 +7811,8 @@ def test_skill_import_serialization(self): skill_import_model_json = {} skill_import_model_json['name'] = 'testString' skill_import_model_json['description'] = 'testString' - skill_import_model_json['workspace'] = {'foo': 'bar'} - skill_import_model_json['dialog_settings'] = {'foo': 'bar'} + skill_import_model_json['workspace'] = {'anyKey': 'anyValue'} + skill_import_model_json['dialog_settings'] = {'anyKey': 'anyValue'} skill_import_model_json['search_settings'] = search_settings_model skill_import_model_json['language'] = 'testString' skill_import_model_json['type'] = 'action' @@ -7604,7 +7832,8 @@ def test_skill_import_serialization(self): skill_import_model_json2 = skill_import_model.to_dict() assert skill_import_model_json2 == skill_import_model_json -class TestModel_SkillsAsyncRequestStatus(): + +class TestModel_SkillsAsyncRequestStatus: """ Test Class for SkillsAsyncRequestStatus """ @@ -7632,7 +7861,8 @@ def test_skills_async_request_status_serialization(self): skills_async_request_status_model_json2 = skills_async_request_status_model.to_dict() assert skills_async_request_status_model_json2 == skills_async_request_status_model_json -class TestModel_SkillsExport(): + +class TestModel_SkillsExport: """ Test Class for SkillsExport """ @@ -7644,11 +7874,11 @@ def test_skills_export_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication search_settings_discovery_authentication_model['basic'] = 'testString' search_settings_discovery_authentication_model['bearer'] = 'testString' - search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model = {} # SearchSettingsDiscovery search_settings_discovery_model['instance_id'] = 'testString' search_settings_discovery_model['project_id'] = 'testString' search_settings_discovery_model['url'] = 'testString' @@ -7659,31 +7889,31 @@ def test_skills_export_serialization(self): search_settings_discovery_model['find_answers'] = True search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model = {} # SearchSettingsMessages search_settings_messages_model['success'] = 'testString' search_settings_messages_model['error'] = 'testString' search_settings_messages_model['no_result'] = 'testString' - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping search_settings_schema_mapping_model['url'] = 'testString' search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' - search_settings_model = {} # SearchSettings + search_settings_model = {} # SearchSettings search_settings_model['discovery'] = search_settings_discovery_model search_settings_model['messages'] = search_settings_messages_model search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - skill_model = {} # Skill + skill_model = {} # Skill skill_model['name'] = 'testString' skill_model['description'] = 'testString' - skill_model['workspace'] = {'foo': 'bar'} - skill_model['dialog_settings'] = {'foo': 'bar'} + skill_model['workspace'] = {'anyKey': 'anyValue'} + skill_model['dialog_settings'] = {'anyKey': 'anyValue'} skill_model['search_settings'] = search_settings_model skill_model['language'] = 'testString' skill_model['type'] = 'action' - assistant_state_model = {} # AssistantState + assistant_state_model = {} # AssistantState assistant_state_model['action_disabled'] = True assistant_state_model['dialog_disabled'] = True @@ -7707,7 +7937,8 @@ def test_skills_export_serialization(self): skills_export_model_json2 = skills_export_model.to_dict() assert skills_export_model_json2 == skills_export_model_json -class TestModel_StatusError(): + +class TestModel_StatusError: """ Test Class for StatusError """ @@ -7736,7 +7967,8 @@ def test_status_error_serialization(self): status_error_model_json2 = status_error_model.to_dict() assert status_error_model_json2 == status_error_model_json -class TestModel_TurnEventActionSource(): + +class TestModel_TurnEventActionSource: """ Test Class for TurnEventActionSource """ @@ -7768,7 +8000,8 @@ def test_turn_event_action_source_serialization(self): turn_event_action_source_model_json2 = turn_event_action_source_model.to_dict() assert turn_event_action_source_model_json2 == turn_event_action_source_model_json -class TestModel_TurnEventCalloutCallout(): + +class TestModel_TurnEventCalloutCallout: """ Test Class for TurnEventCalloutCallout """ @@ -7781,7 +8014,7 @@ def test_turn_event_callout_callout_serialization(self): # Construct a json representation of a TurnEventCalloutCallout model turn_event_callout_callout_model_json = {} turn_event_callout_callout_model_json['type'] = 'integration_interaction' - turn_event_callout_callout_model_json['internal'] = {'foo': 'bar'} + turn_event_callout_callout_model_json['internal'] = {'anyKey': 'anyValue'} turn_event_callout_callout_model_json['result_variable'] = 'testString' # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation @@ -7799,7 +8032,8 @@ def test_turn_event_callout_callout_serialization(self): turn_event_callout_callout_model_json2 = turn_event_callout_callout_model.to_dict() assert turn_event_callout_callout_model_json2 == turn_event_callout_callout_model_json -class TestModel_TurnEventCalloutError(): + +class TestModel_TurnEventCalloutError: """ Test Class for TurnEventCalloutError """ @@ -7828,7 +8062,8 @@ def test_turn_event_callout_error_serialization(self): turn_event_callout_error_model_json2 = turn_event_callout_error_model.to_dict() assert turn_event_callout_error_model_json2 == turn_event_callout_error_model_json -class TestModel_TurnEventNodeSource(): + +class TestModel_TurnEventNodeSource: """ Test Class for TurnEventNodeSource """ @@ -7860,7 +8095,8 @@ def test_turn_event_node_source_serialization(self): turn_event_node_source_model_json2 = turn_event_node_source_model.to_dict() assert turn_event_node_source_model_json2 == turn_event_node_source_model_json -class TestModel_TurnEventSearchError(): + +class TestModel_TurnEventSearchError: """ Test Class for TurnEventSearchError """ @@ -7889,7 +8125,8 @@ def test_turn_event_search_error_serialization(self): turn_event_search_error_model_json2 = turn_event_search_error_model.to_dict() assert turn_event_search_error_model_json2 == turn_event_search_error_model_json -class TestModel_LogMessageSourceAction(): + +class TestModel_LogMessageSourceAction: """ Test Class for LogMessageSourceAction """ @@ -7919,7 +8156,8 @@ def test_log_message_source_action_serialization(self): log_message_source_action_model_json2 = log_message_source_action_model.to_dict() assert log_message_source_action_model_json2 == log_message_source_action_model_json -class TestModel_LogMessageSourceDialogNode(): + +class TestModel_LogMessageSourceDialogNode: """ Test Class for LogMessageSourceDialogNode """ @@ -7949,7 +8187,8 @@ def test_log_message_source_dialog_node_serialization(self): log_message_source_dialog_node_model_json2 = log_message_source_dialog_node_model.to_dict() assert log_message_source_dialog_node_model_json2 == log_message_source_dialog_node_model_json -class TestModel_LogMessageSourceHandler(): + +class TestModel_LogMessageSourceHandler: """ Test Class for LogMessageSourceHandler """ @@ -7981,7 +8220,8 @@ def test_log_message_source_handler_serialization(self): log_message_source_handler_model_json2 = log_message_source_handler_model.to_dict() assert log_message_source_handler_model_json2 == log_message_source_handler_model_json -class TestModel_LogMessageSourceStep(): + +class TestModel_LogMessageSourceStep: """ Test Class for LogMessageSourceStep """ @@ -8012,7 +8252,8 @@ def test_log_message_source_step_serialization(self): log_message_source_step_model_json2 = log_message_source_step_model.to_dict() assert log_message_source_step_model_json2 == log_message_source_step_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventActionFinished(): + +class TestModel_MessageOutputDebugTurnEventTurnEventActionFinished: """ Test Class for MessageOutputDebugTurnEventTurnEventActionFinished """ @@ -8024,7 +8265,7 @@ def test_message_output_debug_turn_event_turn_event_action_finished_serializatio # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' @@ -8037,7 +8278,7 @@ def test_message_output_debug_turn_event_turn_event_action_finished_serializatio message_output_debug_turn_event_turn_event_action_finished_model_json['action_start_time'] = 'testString' message_output_debug_turn_event_turn_event_action_finished_model_json['condition_type'] = 'user_defined' message_output_debug_turn_event_turn_event_action_finished_model_json['reason'] = 'all_steps_done' - message_output_debug_turn_event_turn_event_action_finished_model_json['action_variables'] = {'foo': 'bar'} + message_output_debug_turn_event_turn_event_action_finished_model_json['action_variables'] = {'anyKey': 'anyValue'} # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionFinished by calling from_dict on the json representation message_output_debug_turn_event_turn_event_action_finished_model = MessageOutputDebugTurnEventTurnEventActionFinished.from_dict(message_output_debug_turn_event_turn_event_action_finished_model_json) @@ -8054,7 +8295,8 @@ def test_message_output_debug_turn_event_turn_event_action_finished_serializatio message_output_debug_turn_event_turn_event_action_finished_model_json2 = message_output_debug_turn_event_turn_event_action_finished_model.to_dict() assert message_output_debug_turn_event_turn_event_action_finished_model_json2 == message_output_debug_turn_event_turn_event_action_finished_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventActionVisited(): + +class TestModel_MessageOutputDebugTurnEventTurnEventActionVisited: """ Test Class for MessageOutputDebugTurnEventTurnEventActionVisited """ @@ -8066,7 +8308,7 @@ def test_message_output_debug_turn_event_turn_event_action_visited_serialization # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' @@ -8096,7 +8338,8 @@ def test_message_output_debug_turn_event_turn_event_action_visited_serialization message_output_debug_turn_event_turn_event_action_visited_model_json2 = message_output_debug_turn_event_turn_event_action_visited_model.to_dict() assert message_output_debug_turn_event_turn_event_action_visited_model_json2 == message_output_debug_turn_event_turn_event_action_visited_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventCallout(): + +class TestModel_MessageOutputDebugTurnEventTurnEventCallout: """ Test Class for MessageOutputDebugTurnEventTurnEventCallout """ @@ -8108,18 +8351,18 @@ def test_message_output_debug_turn_event_turn_event_callout_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - turn_event_callout_callout_model = {} # TurnEventCalloutCallout + turn_event_callout_callout_model = {} # TurnEventCalloutCallout turn_event_callout_callout_model['type'] = 'integration_interaction' - turn_event_callout_callout_model['internal'] = {'foo': 'bar'} + turn_event_callout_callout_model['internal'] = {'anyKey': 'anyValue'} turn_event_callout_callout_model['result_variable'] = 'testString' - turn_event_callout_error_model = {} # TurnEventCalloutError + turn_event_callout_error_model = {} # TurnEventCalloutError turn_event_callout_error_model['message'] = 'testString' # Construct a json representation of a MessageOutputDebugTurnEventTurnEventCallout model @@ -8144,7 +8387,8 @@ def test_message_output_debug_turn_event_turn_event_callout_serialization(self): message_output_debug_turn_event_turn_event_callout_model_json2 = message_output_debug_turn_event_turn_event_callout_model.to_dict() assert message_output_debug_turn_event_turn_event_callout_model_json2 == message_output_debug_turn_event_turn_event_callout_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventHandlerVisited(): + +class TestModel_MessageOutputDebugTurnEventTurnEventHandlerVisited: """ Test Class for MessageOutputDebugTurnEventTurnEventHandlerVisited """ @@ -8156,7 +8400,7 @@ def test_message_output_debug_turn_event_turn_event_handler_visited_serializatio # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' @@ -8183,7 +8427,8 @@ def test_message_output_debug_turn_event_turn_event_handler_visited_serializatio message_output_debug_turn_event_turn_event_handler_visited_model_json2 = message_output_debug_turn_event_turn_event_handler_visited_model.to_dict() assert message_output_debug_turn_event_turn_event_handler_visited_model_json2 == message_output_debug_turn_event_turn_event_handler_visited_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventNodeVisited(): + +class TestModel_MessageOutputDebugTurnEventTurnEventNodeVisited: """ Test Class for MessageOutputDebugTurnEventTurnEventNodeVisited """ @@ -8195,7 +8440,7 @@ def test_message_output_debug_turn_event_turn_event_node_visited_serialization(s # Construct dict forms of any model objects needed in order to build this model. - turn_event_node_source_model = {} # TurnEventNodeSource + turn_event_node_source_model = {} # TurnEventNodeSource turn_event_node_source_model['type'] = 'dialog_node' turn_event_node_source_model['dialog_node'] = 'testString' turn_event_node_source_model['title'] = 'testString' @@ -8222,7 +8467,8 @@ def test_message_output_debug_turn_event_turn_event_node_visited_serialization(s message_output_debug_turn_event_turn_event_node_visited_model_json2 = message_output_debug_turn_event_turn_event_node_visited_model.to_dict() assert message_output_debug_turn_event_turn_event_node_visited_model_json2 == message_output_debug_turn_event_turn_event_node_visited_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventSearch(): + +class TestModel_MessageOutputDebugTurnEventTurnEventSearch: """ Test Class for MessageOutputDebugTurnEventTurnEventSearch """ @@ -8234,13 +8480,13 @@ def test_message_output_debug_turn_event_turn_event_search_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - turn_event_search_error_model = {} # TurnEventSearchError + turn_event_search_error_model = {} # TurnEventSearchError turn_event_search_error_model['message'] = 'testString' # Construct a json representation of a MessageOutputDebugTurnEventTurnEventSearch model @@ -8264,7 +8510,8 @@ def test_message_output_debug_turn_event_turn_event_search_serialization(self): message_output_debug_turn_event_turn_event_search_model_json2 = message_output_debug_turn_event_turn_event_search_model.to_dict() assert message_output_debug_turn_event_turn_event_search_model_json2 == message_output_debug_turn_event_turn_event_search_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventStepAnswered(): + +class TestModel_MessageOutputDebugTurnEventTurnEventStepAnswered: """ Test Class for MessageOutputDebugTurnEventTurnEventStepAnswered """ @@ -8276,7 +8523,7 @@ def test_message_output_debug_turn_event_turn_event_step_answered_serialization( # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' @@ -8305,7 +8552,8 @@ def test_message_output_debug_turn_event_turn_event_step_answered_serialization( message_output_debug_turn_event_turn_event_step_answered_model_json2 = message_output_debug_turn_event_turn_event_step_answered_model.to_dict() assert message_output_debug_turn_event_turn_event_step_answered_model_json2 == message_output_debug_turn_event_turn_event_step_answered_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventStepVisited(): + +class TestModel_MessageOutputDebugTurnEventTurnEventStepVisited: """ Test Class for MessageOutputDebugTurnEventTurnEventStepVisited """ @@ -8317,7 +8565,7 @@ def test_message_output_debug_turn_event_turn_event_step_visited_serialization(s # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' @@ -8346,7 +8594,8 @@ def test_message_output_debug_turn_event_turn_event_step_visited_serialization(s message_output_debug_turn_event_turn_event_step_visited_model_json2 = message_output_debug_turn_event_turn_event_step_visited_model.to_dict() assert message_output_debug_turn_event_turn_event_step_visited_model_json2 == message_output_debug_turn_event_turn_event_step_visited_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeAudio """ @@ -8358,7 +8607,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeAudio model @@ -8368,7 +8617,7 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_audio_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_audio_model_json['channel_options'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_audio_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeAudio by calling from_dict on the json representation @@ -8386,7 +8635,8 @@ def test_runtime_response_generic_runtime_response_type_audio_serialization(self runtime_response_generic_runtime_response_type_audio_model_json2 = runtime_response_generic_runtime_response_type_audio_model.to_dict() assert runtime_response_generic_runtime_response_type_audio_model_json2 == runtime_response_generic_runtime_response_type_audio_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeChannelTransfer: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeChannelTransfer """ @@ -8398,16 +8648,16 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat channel_transfer_target_chat_model['url'] = 'testString' - channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model = {} # ChannelTransferTarget channel_transfer_target_model['chat'] = channel_transfer_target_chat_model - channel_transfer_info_model = {} # ChannelTransferInfo + channel_transfer_info_model = {} # ChannelTransferInfo channel_transfer_info_model['target'] = channel_transfer_target_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeChannelTransfer model @@ -8432,7 +8682,8 @@ def test_runtime_response_generic_runtime_response_type_channel_transfer_seriali runtime_response_generic_runtime_response_type_channel_transfer_model_json2 = runtime_response_generic_runtime_response_type_channel_transfer_model.to_dict() assert runtime_response_generic_runtime_response_type_channel_transfer_model_json2 == runtime_response_generic_runtime_response_type_channel_transfer_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeConnectToAgent: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeConnectToAgent """ @@ -8444,13 +8695,13 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali # Construct dict forms of any model objects needed in order to build this model. - agent_availability_message_model = {} # AgentAvailabilityMessage + agent_availability_message_model = {} # AgentAvailabilityMessage agent_availability_message_model['message'] = 'testString' - dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo - dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'foo': 'bar'}} + dialog_node_output_connect_to_agent_transfer_info_model = {} # DialogNodeOutputConnectToAgentTransferInfo + dialog_node_output_connect_to_agent_transfer_info_model['target'] = {'key1': {'anyKey': 'anyValue'}} - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeConnectToAgent model @@ -8478,7 +8729,8 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 = runtime_response_generic_runtime_response_type_connect_to_agent_model.to_dict() assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeDate(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeDate: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeDate """ @@ -8507,7 +8759,8 @@ def test_runtime_response_generic_runtime_response_type_date_serialization(self) runtime_response_generic_runtime_response_type_date_model_json2 = runtime_response_generic_runtime_response_type_date_model.to_dict() assert runtime_response_generic_runtime_response_type_date_model_json2 == runtime_response_generic_runtime_response_type_date_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeIframe """ @@ -8519,7 +8772,7 @@ def test_runtime_response_generic_runtime_response_type_iframe_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeIframe model @@ -8546,7 +8799,8 @@ def test_runtime_response_generic_runtime_response_type_iframe_serialization(sel runtime_response_generic_runtime_response_type_iframe_model_json2 = runtime_response_generic_runtime_response_type_iframe_model.to_dict() assert runtime_response_generic_runtime_response_type_iframe_model_json2 == runtime_response_generic_runtime_response_type_iframe_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeImage: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeImage """ @@ -8558,7 +8812,7 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeImage model @@ -8585,7 +8839,8 @@ def test_runtime_response_generic_runtime_response_type_image_serialization(self runtime_response_generic_runtime_response_type_image_model_json2 = runtime_response_generic_runtime_response_type_image_model.to_dict() assert runtime_response_generic_runtime_response_type_image_model_json2 == runtime_response_generic_runtime_response_type_image_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeOption: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeOption """ @@ -8597,16 +8852,16 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8634,14 +8889,14 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8652,20 +8907,20 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model @@ -8673,7 +8928,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -8683,14 +8938,14 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue dialog_node_output_options_element_value_model['input'] = message_input_model - dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement + dialog_node_output_options_element_model = {} # DialogNodeOutputOptionsElement dialog_node_output_options_element_model['label'] = 'testString' dialog_node_output_options_element_model['value'] = dialog_node_output_options_element_value_model - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeOption model @@ -8717,7 +8972,8 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel runtime_response_generic_runtime_response_type_option_model_json2 = runtime_response_generic_runtime_response_type_option_model.to_dict() assert runtime_response_generic_runtime_response_type_option_model_json2 == runtime_response_generic_runtime_response_type_option_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypePause(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypePause: """ Test Class for RuntimeResponseGenericRuntimeResponseTypePause """ @@ -8729,7 +8985,7 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypePause model @@ -8754,7 +9010,8 @@ def test_runtime_response_generic_runtime_response_type_pause_serialization(self runtime_response_generic_runtime_response_type_pause_model_json2 = runtime_response_generic_runtime_response_type_pause_model.to_dict() assert runtime_response_generic_runtime_response_type_pause_model_json2 == runtime_response_generic_runtime_response_type_pause_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeSearch(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeSearch: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeSearch """ @@ -8766,21 +9023,21 @@ def test_runtime_response_generic_runtime_response_type_search_serialization(sel # Construct dict forms of any model objects needed in order to build this model. - search_result_metadata_model = {} # SearchResultMetadata + search_result_metadata_model = {} # SearchResultMetadata search_result_metadata_model['confidence'] = 72.5 search_result_metadata_model['score'] = 72.5 - search_result_highlight_model = {} # SearchResultHighlight + search_result_highlight_model = {} # SearchResultHighlight search_result_highlight_model['body'] = ['testString'] search_result_highlight_model['title'] = ['testString'] search_result_highlight_model['url'] = ['testString'] search_result_highlight_model['foo'] = ['testString'] - search_result_answer_model = {} # SearchResultAnswer + search_result_answer_model = {} # SearchResultAnswer search_result_answer_model['text'] = 'testString' search_result_answer_model['confidence'] = 0 - search_result_model = {} # SearchResult + search_result_model = {} # SearchResult search_result_model['id'] = 'testString' search_result_model['result_metadata'] = search_result_metadata_model search_result_model['body'] = 'testString' @@ -8789,7 +9046,7 @@ def test_runtime_response_generic_runtime_response_type_search_serialization(sel search_result_model['highlight'] = search_result_highlight_model search_result_model['answers'] = [search_result_answer_model] - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSearch model @@ -8815,7 +9072,8 @@ def test_runtime_response_generic_runtime_response_type_search_serialization(sel runtime_response_generic_runtime_response_type_search_model_json2 = runtime_response_generic_runtime_response_type_search_model.to_dict() assert runtime_response_generic_runtime_response_type_search_model_json2 == runtime_response_generic_runtime_response_type_search_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeSuggestion: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeSuggestion """ @@ -8827,16 +9085,16 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup + capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation runtime_entity_interpretation_model['calendar_type'] = 'testString' runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' @@ -8864,14 +9122,14 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_interpretation_model['specific_second'] = 72.5 runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model = {} # RuntimeEntityAlternative runtime_entity_alternative_model['value'] = 'testString' runtime_entity_alternative_model['confidence'] = 72.5 - runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity + runtime_entity_model = {} # RuntimeEntity runtime_entity_model['entity'] = 'testString' runtime_entity_model['location'] = [38] runtime_entity_model['value'] = 'testString' @@ -8882,20 +9140,20 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' message_input_attachment_model['media_type'] = 'testString' - request_analytics_model = {} # RequestAnalytics + request_analytics_model = {} # RequestAnalytics request_analytics_model['browser'] = 'testString' request_analytics_model['device'] = 'testString' request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model = {} # MessageInputOptionsSpelling message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_model = {} # MessageInputOptions + message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False message_input_options_model['spelling'] = message_input_options_spelling_model @@ -8903,7 +9161,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput + message_input_model = {} # MessageInput message_input_model['message_type'] = 'text' message_input_model['text'] = 'testString' message_input_model['intents'] = [runtime_intent_model] @@ -8913,15 +9171,15 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model = {} # DialogSuggestionValue dialog_suggestion_value_model['input'] = message_input_model - dialog_suggestion_model = {} # DialogSuggestion + dialog_suggestion_model = {} # DialogSuggestion dialog_suggestion_model['label'] = 'testString' dialog_suggestion_model['value'] = dialog_suggestion_value_model - dialog_suggestion_model['output'] = {'foo': 'bar'} + dialog_suggestion_model['output'] = {'anyKey': 'anyValue'} - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeSuggestion model @@ -8946,7 +9204,8 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization runtime_response_generic_runtime_response_type_suggestion_model_json2 = runtime_response_generic_runtime_response_type_suggestion_model.to_dict() assert runtime_response_generic_runtime_response_type_suggestion_model_json2 == runtime_response_generic_runtime_response_type_suggestion_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeText(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeText: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeText """ @@ -8958,7 +9217,7 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeText model @@ -8982,7 +9241,8 @@ def test_runtime_response_generic_runtime_response_type_text_serialization(self) runtime_response_generic_runtime_response_type_text_model_json2 = runtime_response_generic_runtime_response_type_text_model.to_dict() assert runtime_response_generic_runtime_response_type_text_model_json2 == runtime_response_generic_runtime_response_type_text_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeUserDefined: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeUserDefined """ @@ -8994,13 +9254,13 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeUserDefined model runtime_response_generic_runtime_response_type_user_defined_model_json = {} runtime_response_generic_runtime_response_type_user_defined_model_json['response_type'] = 'user_defined' - runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_user_defined_model_json['user_defined'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_user_defined_model_json['channels'] = [response_generic_channel_model] # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeUserDefined by calling from_dict on the json representation @@ -9018,7 +9278,8 @@ def test_runtime_response_generic_runtime_response_type_user_defined_serializati runtime_response_generic_runtime_response_type_user_defined_model_json2 = runtime_response_generic_runtime_response_type_user_defined_model.to_dict() assert runtime_response_generic_runtime_response_type_user_defined_model_json2 == runtime_response_generic_runtime_response_type_user_defined_model_json -class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo(): + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeVideo: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeVideo """ @@ -9030,7 +9291,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeVideo model @@ -9040,7 +9301,7 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self runtime_response_generic_runtime_response_type_video_model_json['title'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['description'] = 'testString' runtime_response_generic_runtime_response_type_video_model_json['channels'] = [response_generic_channel_model] - runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'foo': 'bar'} + runtime_response_generic_runtime_response_type_video_model_json['channel_options'] = {'anyKey': 'anyValue'} runtime_response_generic_runtime_response_type_video_model_json['alt_text'] = 'testString' # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeVideo by calling from_dict on the json representation diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 945c28ba5..0a1544439 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2023. +# (C) Copyright IBM Corp. 2016, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -65,8 +65,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -74,7 +73,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestCreateEnvironment(): + +class TestCreateEnvironment: """ Test Class for create_environment """ @@ -87,11 +87,13 @@ def test_create_environment_all_params(self): # Set up mock url = preprocess_url('/v1/environments') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -103,7 +105,7 @@ def test_create_environment_all_params(self): name, description=description, size=size, - headers={} + headers={}, ) # Check for correct operation @@ -132,11 +134,13 @@ def test_create_environment_value_error(self): # Set up mock url = preprocess_url('/v1/environments') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -148,7 +152,7 @@ def test_create_environment_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_environment(**req_copy) @@ -161,7 +165,8 @@ def test_create_environment_value_error_with_retries(self): _service.disable_retries() self.test_create_environment_value_error() -class TestListEnvironments(): + +class TestListEnvironments: """ Test Class for list_environments """ @@ -174,11 +179,13 @@ def test_list_environments_all_params(self): # Set up mock url = preprocess_url('/v1/environments') mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values name = 'testString' @@ -186,14 +193,14 @@ def test_list_environments_all_params(self): # Invoke method response = _service.list_environments( name=name, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'name={}'.format(name) in query_string @@ -214,16 +221,17 @@ def test_list_environments_required_params(self): # Set up mock url = preprocess_url('/v1/environments') mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_environments() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -245,17 +253,19 @@ def test_list_environments_value_error(self): # Set up mock url = preprocess_url('/v1/environments') mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_environments(**req_copy) @@ -268,7 +278,8 @@ def test_list_environments_value_error_with_retries(self): _service.disable_retries() self.test_list_environments_value_error() -class TestGetEnvironment(): + +class TestGetEnvironment: """ Test Class for get_environment """ @@ -281,11 +292,13 @@ def test_get_environment_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -293,7 +306,7 @@ def test_get_environment_all_params(self): # Invoke method response = _service.get_environment( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -317,11 +330,13 @@ def test_get_environment_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -331,7 +346,7 @@ def test_get_environment_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_environment(**req_copy) @@ -344,7 +359,8 @@ def test_get_environment_value_error_with_retries(self): _service.disable_retries() self.test_get_environment_value_error() -class TestUpdateEnvironment(): + +class TestUpdateEnvironment: """ Test Class for update_environment """ @@ -357,11 +373,13 @@ def test_update_environment_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -375,7 +393,7 @@ def test_update_environment_all_params(self): name=name, description=description, size=size, - headers={} + headers={}, ) # Check for correct operation @@ -404,11 +422,13 @@ def test_update_environment_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -421,7 +441,7 @@ def test_update_environment_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_environment(**req_copy) @@ -434,7 +454,8 @@ def test_update_environment_value_error_with_retries(self): _service.disable_retries() self.test_update_environment_value_error() -class TestDeleteEnvironment(): + +class TestDeleteEnvironment: """ Test Class for delete_environment """ @@ -447,11 +468,13 @@ def test_delete_environment_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -459,7 +482,7 @@ def test_delete_environment_all_params(self): # Invoke method response = _service.delete_environment( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -483,11 +506,13 @@ def test_delete_environment_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString') mock_response = '{"environment_id": "environment_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -497,7 +522,7 @@ def test_delete_environment_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_environment(**req_copy) @@ -510,7 +535,8 @@ def test_delete_environment_value_error_with_retries(self): _service.disable_retries() self.test_delete_environment_value_error() -class TestListFields(): + +class TestListFields: """ Test Class for list_fields """ @@ -523,11 +549,13 @@ def test_list_fields_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -537,14 +565,14 @@ def test_list_fields_all_params(self): response = _service.list_fields( environment_id, collection_ids, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string @@ -565,11 +593,13 @@ def test_list_fields_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -581,7 +611,7 @@ def test_list_fields_value_error(self): "collection_ids": collection_ids, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_fields(**req_copy) @@ -594,6 +624,7 @@ def test_list_fields_value_error_with_retries(self): _service.disable_retries() self.test_list_fields_value_error() + # endregion ############################################################################## # End of Service: Environments @@ -604,7 +635,8 @@ def test_list_fields_value_error_with_retries(self): ############################################################################## # region -class TestCreateConfiguration(): + +class TestCreateConfiguration: """ Test Class for create_configuration """ @@ -616,12 +648,14 @@ def test_create_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a FontSetting model font_setting_model = {} @@ -734,7 +768,7 @@ def test_create_configuration_all_params(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -783,8 +817,8 @@ def test_create_configuration_all_params(self): source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] @@ -827,7 +861,7 @@ def test_create_configuration_all_params(self): enrichments=enrichments, normalizations=normalizations, source=source, - headers={} + headers={}, ) # Check for correct operation @@ -858,12 +892,14 @@ def test_create_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a FontSetting model font_setting_model = {} @@ -976,7 +1012,7 @@ def test_create_configuration_value_error(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1025,8 +1061,8 @@ def test_create_configuration_value_error(self): source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] @@ -1066,7 +1102,7 @@ def test_create_configuration_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_configuration(**req_copy) @@ -1079,7 +1115,8 @@ def test_create_configuration_value_error_with_retries(self): _service.disable_retries() self.test_create_configuration_value_error() -class TestListConfigurations(): + +class TestListConfigurations: """ Test Class for list_configurations """ @@ -1091,12 +1128,14 @@ def test_list_configurations_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1106,14 +1145,14 @@ def test_list_configurations_all_params(self): response = _service.list_configurations( environment_id, name=name, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'name={}'.format(name) in query_string @@ -1133,12 +1172,14 @@ def test_list_configurations_required_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1146,7 +1187,7 @@ def test_list_configurations_required_params(self): # Invoke method response = _service.list_configurations( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -1169,12 +1210,14 @@ def test_list_configurations_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1184,7 +1227,7 @@ def test_list_configurations_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_configurations(**req_copy) @@ -1197,7 +1240,8 @@ def test_list_configurations_value_error_with_retries(self): _service.disable_retries() self.test_list_configurations_value_error() -class TestGetConfiguration(): + +class TestGetConfiguration: """ Test Class for get_configuration """ @@ -1209,12 +1253,14 @@ def test_get_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1224,7 +1270,7 @@ def test_get_configuration_all_params(self): response = _service.get_configuration( environment_id, configuration_id, - headers={} + headers={}, ) # Check for correct operation @@ -1247,12 +1293,14 @@ def test_get_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1264,7 +1312,7 @@ def test_get_configuration_value_error(self): "configuration_id": configuration_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_configuration(**req_copy) @@ -1277,7 +1325,8 @@ def test_get_configuration_value_error_with_retries(self): _service.disable_retries() self.test_get_configuration_value_error() -class TestUpdateConfiguration(): + +class TestUpdateConfiguration: """ Test Class for update_configuration """ @@ -1289,12 +1338,14 @@ def test_update_configuration_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a FontSetting model font_setting_model = {} @@ -1407,7 +1458,7 @@ def test_update_configuration_all_params(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1456,8 +1507,8 @@ def test_update_configuration_all_params(self): source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] @@ -1502,7 +1553,7 @@ def test_update_configuration_all_params(self): enrichments=enrichments, normalizations=normalizations, source=source, - headers={} + headers={}, ) # Check for correct operation @@ -1533,12 +1584,14 @@ def test_update_configuration_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 12, "request_timeout": 15, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a FontSetting model font_setting_model = {} @@ -1651,7 +1704,7 @@ def test_update_configuration_value_error(self): nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -1700,8 +1753,8 @@ def test_update_configuration_value_error(self): source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] @@ -1743,7 +1796,7 @@ def test_update_configuration_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_configuration(**req_copy) @@ -1756,7 +1809,8 @@ def test_update_configuration_value_error_with_retries(self): _service.disable_retries() self.test_update_configuration_value_error() -class TestDeleteConfiguration(): + +class TestDeleteConfiguration: """ Test Class for delete_configuration """ @@ -1769,11 +1823,13 @@ def test_delete_configuration_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1783,7 +1839,7 @@ def test_delete_configuration_all_params(self): response = _service.delete_configuration( environment_id, configuration_id, - headers={} + headers={}, ) # Check for correct operation @@ -1807,11 +1863,13 @@ def test_delete_configuration_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/configurations/testString') mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1823,7 +1881,7 @@ def test_delete_configuration_value_error(self): "configuration_id": configuration_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_configuration(**req_copy) @@ -1836,6 +1894,7 @@ def test_delete_configuration_value_error_with_retries(self): _service.disable_retries() self.test_delete_configuration_value_error() + # endregion ############################################################################## # End of Service: Configurations @@ -1846,7 +1905,8 @@ def test_delete_configuration_value_error_with_retries(self): ############################################################################## # region -class TestCreateCollection(): + +class TestCreateCollection: """ Test Class for create_collection """ @@ -1859,11 +1919,13 @@ def test_create_collection_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -1879,7 +1941,7 @@ def test_create_collection_all_params(self): description=description, configuration_id=configuration_id, language=language, - headers={} + headers={}, ) # Check for correct operation @@ -1909,11 +1971,13 @@ def test_create_collection_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -1928,7 +1992,7 @@ def test_create_collection_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_collection(**req_copy) @@ -1941,7 +2005,8 @@ def test_create_collection_value_error_with_retries(self): _service.disable_retries() self.test_create_collection_value_error() -class TestListCollections(): + +class TestListCollections: """ Test Class for list_collections """ @@ -1954,11 +2019,13 @@ def test_list_collections_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -1968,14 +2035,14 @@ def test_list_collections_all_params(self): response = _service.list_collections( environment_id, name=name, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'name={}'.format(name) in query_string @@ -1996,11 +2063,13 @@ def test_list_collections_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2008,7 +2077,7 @@ def test_list_collections_required_params(self): # Invoke method response = _service.list_collections( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -2032,11 +2101,13 @@ def test_list_collections_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2046,7 +2117,7 @@ def test_list_collections_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_collections(**req_copy) @@ -2059,7 +2130,8 @@ def test_list_collections_value_error_with_retries(self): _service.disable_retries() self.test_list_collections_value_error() -class TestGetCollection(): + +class TestGetCollection: """ Test Class for get_collection """ @@ -2072,11 +2144,13 @@ def test_get_collection_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2086,7 +2160,7 @@ def test_get_collection_all_params(self): response = _service.get_collection( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2110,11 +2184,13 @@ def test_get_collection_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2126,7 +2202,7 @@ def test_get_collection_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_collection(**req_copy) @@ -2139,7 +2215,8 @@ def test_get_collection_value_error_with_retries(self): _service.disable_retries() self.test_get_collection_value_error() -class TestUpdateCollection(): + +class TestUpdateCollection: """ Test Class for update_collection """ @@ -2152,11 +2229,13 @@ def test_update_collection_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -2172,7 +2251,7 @@ def test_update_collection_all_params(self): name, description=description, configuration_id=configuration_id, - headers={} + headers={}, ) # Check for correct operation @@ -2201,11 +2280,13 @@ def test_update_collection_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -2221,7 +2302,7 @@ def test_update_collection_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_collection(**req_copy) @@ -2234,7 +2315,8 @@ def test_update_collection_value_error_with_retries(self): _service.disable_retries() self.test_update_collection_value_error() -class TestDeleteCollection(): + +class TestDeleteCollection: """ Test Class for delete_collection """ @@ -2247,11 +2329,13 @@ def test_delete_collection_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2261,7 +2345,7 @@ def test_delete_collection_all_params(self): response = _service.delete_collection( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2285,11 +2369,13 @@ def test_delete_collection_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2301,7 +2387,7 @@ def test_delete_collection_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_collection(**req_copy) @@ -2314,7 +2400,8 @@ def test_delete_collection_value_error_with_retries(self): _service.disable_retries() self.test_delete_collection_value_error() -class TestListCollectionFields(): + +class TestListCollectionFields: """ Test Class for list_collection_fields """ @@ -2327,11 +2414,13 @@ def test_list_collection_fields_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2341,7 +2430,7 @@ def test_list_collection_fields_all_params(self): response = _service.list_collection_fields( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2365,11 +2454,13 @@ def test_list_collection_fields_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2381,7 +2472,7 @@ def test_list_collection_fields_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_collection_fields(**req_copy) @@ -2394,6 +2485,7 @@ def test_list_collection_fields_value_error_with_retries(self): _service.disable_retries() self.test_list_collection_fields_value_error() + # endregion ############################################################################## # End of Service: Collections @@ -2404,7 +2496,8 @@ def test_list_collection_fields_value_error_with_retries(self): ############################################################################## # region -class TestListExpansions(): + +class TestListExpansions: """ Test Class for list_expansions """ @@ -2417,11 +2510,13 @@ def test_list_expansions_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2431,7 +2526,7 @@ def test_list_expansions_all_params(self): response = _service.list_expansions( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2455,11 +2550,13 @@ def test_list_expansions_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2471,7 +2568,7 @@ def test_list_expansions_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_expansions(**req_copy) @@ -2484,7 +2581,8 @@ def test_list_expansions_value_error_with_retries(self): _service.disable_retries() self.test_list_expansions_value_error() -class TestCreateExpansions(): + +class TestCreateExpansions: """ Test Class for create_expansions """ @@ -2497,11 +2595,13 @@ def test_create_expansions_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Expansion model expansion_model = {} @@ -2518,7 +2618,7 @@ def test_create_expansions_all_params(self): environment_id, collection_id, expansions, - headers={} + headers={}, ) # Check for correct operation @@ -2545,11 +2645,13 @@ def test_create_expansions_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Expansion model expansion_model = {} @@ -2568,7 +2670,7 @@ def test_create_expansions_value_error(self): "expansions": expansions, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_expansions(**req_copy) @@ -2581,7 +2683,8 @@ def test_create_expansions_value_error_with_retries(self): _service.disable_retries() self.test_create_expansions_value_error() -class TestDeleteExpansions(): + +class TestDeleteExpansions: """ Test Class for delete_expansions """ @@ -2593,9 +2696,11 @@ def test_delete_expansions_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -2605,7 +2710,7 @@ def test_delete_expansions_all_params(self): response = _service.delete_expansions( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2628,9 +2733,11 @@ def test_delete_expansions_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -2642,7 +2749,7 @@ def test_delete_expansions_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_expansions(**req_copy) @@ -2655,7 +2762,8 @@ def test_delete_expansions_value_error_with_retries(self): _service.disable_retries() self.test_delete_expansions_value_error() -class TestGetTokenizationDictionaryStatus(): + +class TestGetTokenizationDictionaryStatus: """ Test Class for get_tokenization_dictionary_status """ @@ -2668,11 +2776,13 @@ def test_get_tokenization_dictionary_status_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2682,7 +2792,7 @@ def test_get_tokenization_dictionary_status_all_params(self): response = _service.get_tokenization_dictionary_status( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2706,11 +2816,13 @@ def test_get_tokenization_dictionary_status_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2722,7 +2834,7 @@ def test_get_tokenization_dictionary_status_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_tokenization_dictionary_status(**req_copy) @@ -2735,7 +2847,8 @@ def test_get_tokenization_dictionary_status_value_error_with_retries(self): _service.disable_retries() self.test_get_tokenization_dictionary_status_value_error() -class TestCreateTokenizationDictionary(): + +class TestCreateTokenizationDictionary: """ Test Class for create_tokenization_dictionary """ @@ -2748,11 +2861,13 @@ def test_create_tokenization_dictionary_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Construct a dict representation of a TokenDictRule model token_dict_rule_model = {} @@ -2771,7 +2886,7 @@ def test_create_tokenization_dictionary_all_params(self): environment_id, collection_id, tokenization_rules=tokenization_rules, - headers={} + headers={}, ) # Check for correct operation @@ -2798,11 +2913,13 @@ def test_create_tokenization_dictionary_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -2812,7 +2929,7 @@ def test_create_tokenization_dictionary_required_params(self): response = _service.create_tokenization_dictionary( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2836,11 +2953,13 @@ def test_create_tokenization_dictionary_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -2852,7 +2971,7 @@ def test_create_tokenization_dictionary_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_tokenization_dictionary(**req_copy) @@ -2865,7 +2984,8 @@ def test_create_tokenization_dictionary_value_error_with_retries(self): _service.disable_retries() self.test_create_tokenization_dictionary_value_error() -class TestDeleteTokenizationDictionary(): + +class TestDeleteTokenizationDictionary: """ Test Class for delete_tokenization_dictionary """ @@ -2877,9 +2997,11 @@ def test_delete_tokenization_dictionary_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2889,7 +3011,7 @@ def test_delete_tokenization_dictionary_all_params(self): response = _service.delete_tokenization_dictionary( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2912,9 +3034,11 @@ def test_delete_tokenization_dictionary_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2926,7 +3050,7 @@ def test_delete_tokenization_dictionary_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_tokenization_dictionary(**req_copy) @@ -2939,7 +3063,8 @@ def test_delete_tokenization_dictionary_value_error_with_retries(self): _service.disable_retries() self.test_delete_tokenization_dictionary_value_error() -class TestGetStopwordListStatus(): + +class TestGetStopwordListStatus: """ Test Class for get_stopword_list_status """ @@ -2952,11 +3077,13 @@ def test_get_stopword_list_status_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -2966,7 +3093,7 @@ def test_get_stopword_list_status_all_params(self): response = _service.get_stopword_list_status( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2990,11 +3117,13 @@ def test_get_stopword_list_status_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3006,7 +3135,7 @@ def test_get_stopword_list_status_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_stopword_list_status(**req_copy) @@ -3019,7 +3148,8 @@ def test_get_stopword_list_status_value_error_with_retries(self): _service.disable_retries() self.test_get_stopword_list_status_value_error() -class TestCreateStopwordList(): + +class TestCreateStopwordList: """ Test Class for create_stopword_list """ @@ -3032,11 +3162,13 @@ def test_create_stopword_list_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3050,7 +3182,7 @@ def test_create_stopword_list_all_params(self): collection_id, stopword_file, stopword_filename=stopword_filename, - headers={} + headers={}, ) # Check for correct operation @@ -3074,11 +3206,13 @@ def test_create_stopword_list_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3092,7 +3226,7 @@ def test_create_stopword_list_required_params(self): collection_id, stopword_file, stopword_filename=stopword_filename, - headers={} + headers={}, ) # Check for correct operation @@ -3116,11 +3250,13 @@ def test_create_stopword_list_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') mock_response = '{"status": "active", "type": "type"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3135,7 +3271,7 @@ def test_create_stopword_list_value_error(self): "stopword_file": stopword_file, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_stopword_list(**req_copy) @@ -3148,7 +3284,8 @@ def test_create_stopword_list_value_error_with_retries(self): _service.disable_retries() self.test_create_stopword_list_value_error() -class TestDeleteStopwordList(): + +class TestDeleteStopwordList: """ Test Class for delete_stopword_list """ @@ -3160,9 +3297,11 @@ def test_delete_stopword_list_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3172,7 +3311,7 @@ def test_delete_stopword_list_all_params(self): response = _service.delete_stopword_list( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -3195,9 +3334,11 @@ def test_delete_stopword_list_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3209,7 +3350,7 @@ def test_delete_stopword_list_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_stopword_list(**req_copy) @@ -3222,6 +3363,7 @@ def test_delete_stopword_list_value_error_with_retries(self): _service.disable_retries() self.test_delete_stopword_list_value_error() + # endregion ############################################################################## # End of Service: QueryModifications @@ -3232,7 +3374,8 @@ def test_delete_stopword_list_value_error_with_retries(self): ############################################################################## # region -class TestAddDocument(): + +class TestAddDocument: """ Test Class for add_document """ @@ -3245,11 +3388,13 @@ def test_add_document_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3267,7 +3412,7 @@ def test_add_document_all_params(self): filename=filename, file_content_type=file_content_type, metadata=metadata, - headers={} + headers={}, ) # Check for correct operation @@ -3291,11 +3436,13 @@ def test_add_document_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3305,7 +3452,7 @@ def test_add_document_required_params(self): response = _service.add_document( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -3329,11 +3476,13 @@ def test_add_document_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3345,7 +3494,7 @@ def test_add_document_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_document(**req_copy) @@ -3358,7 +3507,8 @@ def test_add_document_value_error_with_retries(self): _service.disable_retries() self.test_add_document_value_error() -class TestGetDocumentStatus(): + +class TestGetDocumentStatus: """ Test Class for get_document_status """ @@ -3371,11 +3521,13 @@ def test_get_document_status_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3387,7 +3539,7 @@ def test_get_document_status_all_params(self): environment_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -3411,11 +3563,13 @@ def test_get_document_status_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3429,7 +3583,7 @@ def test_get_document_status_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_status(**req_copy) @@ -3442,7 +3596,8 @@ def test_get_document_status_value_error_with_retries(self): _service.disable_retries() self.test_get_document_status_value_error() -class TestUpdateDocument(): + +class TestUpdateDocument: """ Test Class for update_document """ @@ -3455,11 +3610,13 @@ def test_update_document_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3479,7 +3636,7 @@ def test_update_document_all_params(self): filename=filename, file_content_type=file_content_type, metadata=metadata, - headers={} + headers={}, ) # Check for correct operation @@ -3503,11 +3660,13 @@ def test_update_document_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3519,7 +3678,7 @@ def test_update_document_required_params(self): environment_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -3543,11 +3702,13 @@ def test_update_document_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values environment_id = 'testString' @@ -3561,7 +3722,7 @@ def test_update_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_document(**req_copy) @@ -3574,7 +3735,8 @@ def test_update_document_value_error_with_retries(self): _service.disable_retries() self.test_update_document_value_error() -class TestDeleteDocument(): + +class TestDeleteDocument: """ Test Class for delete_document """ @@ -3587,11 +3749,13 @@ def test_delete_document_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3603,7 +3767,7 @@ def test_delete_document_all_params(self): environment_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -3627,11 +3791,13 @@ def test_delete_document_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3645,7 +3811,7 @@ def test_delete_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document(**req_copy) @@ -3658,6 +3824,7 @@ def test_delete_document_value_error_with_retries(self): _service.disable_retries() self.test_delete_document_value_error() + # endregion ############################################################################## # End of Service: Documents @@ -3668,7 +3835,8 @@ def test_delete_document_value_error_with_retries(self): ############################################################################## # region -class TestQuery(): + +class TestQuery: """ Test Class for query """ @@ -3681,11 +3849,13 @@ def test_query_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3695,14 +3865,14 @@ def test_query_all_params(self): natural_language_query = 'testString' passages = True aggregation = 'testString' - count = 38 + count = 10 return_ = 'testString' offset = 38 sort = 'testString' highlight = False passages_fields = 'testString' - passages_count = 100 - passages_characters = 50 + passages_count = 10 + passages_characters = 400 deduplicate = False deduplicate_field = 'testString' similar = False @@ -3737,7 +3907,7 @@ def test_query_all_params(self): bias=bias, spelling_suggestions=spelling_suggestions, x_watson_logging_opt_out=x_watson_logging_opt_out, - headers={} + headers={}, ) # Check for correct operation @@ -3750,14 +3920,14 @@ def test_query_all_params(self): assert req_body['natural_language_query'] == 'testString' assert req_body['passages'] == True assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 38 + assert req_body['count'] == 10 assert req_body['return'] == 'testString' assert req_body['offset'] == 38 assert req_body['sort'] == 'testString' assert req_body['highlight'] == False assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 100 - assert req_body['passages.characters'] == 50 + assert req_body['passages.count'] == 10 + assert req_body['passages.characters'] == 400 assert req_body['deduplicate'] == False assert req_body['deduplicate.field'] == 'testString' assert req_body['similar'] == False @@ -3783,11 +3953,13 @@ def test_query_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3797,7 +3969,7 @@ def test_query_required_params(self): response = _service.query( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -3821,11 +3993,13 @@ def test_query_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3837,7 +4011,7 @@ def test_query_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query(**req_copy) @@ -3850,7 +4024,8 @@ def test_query_value_error_with_retries(self): _service.disable_retries() self.test_query_value_error() -class TestQueryNotices(): + +class TestQueryNotices: """ Test Class for query_notices """ @@ -3863,11 +4038,13 @@ def test_query_notices_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3877,14 +4054,14 @@ def test_query_notices_all_params(self): natural_language_query = 'testString' passages = True aggregation = 'testString' - count = 38 + count = 10 return_ = ['testString'] offset = 38 sort = ['testString'] highlight = False passages_fields = ['testString'] - passages_count = 100 - passages_characters = 50 + passages_count = 10 + passages_characters = 400 deduplicate_field = 'testString' similar = False similar_document_ids = ['testString'] @@ -3911,14 +4088,14 @@ def test_query_notices_all_params(self): similar=similar, similar_document_ids=similar_document_ids, similar_fields=similar_fields, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string assert 'query={}'.format(query) in query_string @@ -3955,11 +4132,13 @@ def test_query_notices_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -3969,7 +4148,7 @@ def test_query_notices_required_params(self): response = _service.query_notices( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -3993,11 +4172,13 @@ def test_query_notices_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4009,7 +4190,7 @@ def test_query_notices_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query_notices(**req_copy) @@ -4022,7 +4203,8 @@ def test_query_notices_value_error_with_retries(self): _service.disable_retries() self.test_query_notices_value_error() -class TestFederatedQuery(): + +class TestFederatedQuery: """ Test Class for federated_query """ @@ -4035,11 +4217,13 @@ def test_federated_query_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4049,14 +4233,14 @@ def test_federated_query_all_params(self): natural_language_query = 'testString' passages = True aggregation = 'testString' - count = 38 + count = 10 return_ = 'testString' offset = 38 sort = 'testString' highlight = False passages_fields = 'testString' - passages_count = 100 - passages_characters = 50 + passages_count = 10 + passages_characters = 400 deduplicate = False deduplicate_field = 'testString' similar = False @@ -4089,7 +4273,7 @@ def test_federated_query_all_params(self): similar_fields=similar_fields, bias=bias, x_watson_logging_opt_out=x_watson_logging_opt_out, - headers={} + headers={}, ) # Check for correct operation @@ -4103,14 +4287,14 @@ def test_federated_query_all_params(self): assert req_body['natural_language_query'] == 'testString' assert req_body['passages'] == True assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 38 + assert req_body['count'] == 10 assert req_body['return'] == 'testString' assert req_body['offset'] == 38 assert req_body['sort'] == 'testString' assert req_body['highlight'] == False assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 100 - assert req_body['passages.characters'] == 50 + assert req_body['passages.count'] == 10 + assert req_body['passages.characters'] == 400 assert req_body['deduplicate'] == False assert req_body['deduplicate.field'] == 'testString' assert req_body['similar'] == False @@ -4135,11 +4319,13 @@ def test_federated_query_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4149,14 +4335,14 @@ def test_federated_query_required_params(self): natural_language_query = 'testString' passages = True aggregation = 'testString' - count = 38 + count = 10 return_ = 'testString' offset = 38 sort = 'testString' highlight = False passages_fields = 'testString' - passages_count = 100 - passages_characters = 50 + passages_count = 10 + passages_characters = 400 deduplicate = False deduplicate_field = 'testString' similar = False @@ -4187,7 +4373,7 @@ def test_federated_query_required_params(self): similar_document_ids=similar_document_ids, similar_fields=similar_fields, bias=bias, - headers={} + headers={}, ) # Check for correct operation @@ -4201,14 +4387,14 @@ def test_federated_query_required_params(self): assert req_body['natural_language_query'] == 'testString' assert req_body['passages'] == True assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 38 + assert req_body['count'] == 10 assert req_body['return'] == 'testString' assert req_body['offset'] == 38 assert req_body['sort'] == 'testString' assert req_body['highlight'] == False assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 100 - assert req_body['passages.characters'] == 50 + assert req_body['passages.count'] == 10 + assert req_body['passages.characters'] == 400 assert req_body['deduplicate'] == False assert req_body['deduplicate.field'] == 'testString' assert req_body['similar'] == False @@ -4233,11 +4419,13 @@ def test_federated_query_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/query') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4247,14 +4435,14 @@ def test_federated_query_value_error(self): natural_language_query = 'testString' passages = True aggregation = 'testString' - count = 38 + count = 10 return_ = 'testString' offset = 38 sort = 'testString' highlight = False passages_fields = 'testString' - passages_count = 100 - passages_characters = 50 + passages_count = 10 + passages_characters = 400 deduplicate = False deduplicate_field = 'testString' similar = False @@ -4268,7 +4456,7 @@ def test_federated_query_value_error(self): "collection_ids": collection_ids, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.federated_query(**req_copy) @@ -4281,7 +4469,8 @@ def test_federated_query_value_error_with_retries(self): _service.disable_retries() self.test_federated_query_value_error() -class TestFederatedQueryNotices(): + +class TestFederatedQueryNotices: """ Test Class for federated_query_notices """ @@ -4294,11 +4483,13 @@ def test_federated_query_notices_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4307,7 +4498,7 @@ def test_federated_query_notices_all_params(self): query = 'testString' natural_language_query = 'testString' aggregation = 'testString' - count = 38 + count = 10 return_ = ['testString'] offset = 38 sort = ['testString'] @@ -4334,14 +4525,14 @@ def test_federated_query_notices_all_params(self): similar=similar, similar_document_ids=similar_document_ids, similar_fields=similar_fields, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string assert 'filter={}'.format(filter) in query_string @@ -4375,11 +4566,13 @@ def test_federated_query_notices_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4389,14 +4582,14 @@ def test_federated_query_notices_required_params(self): response = _service.federated_query_notices( environment_id, collection_ids, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string @@ -4417,11 +4610,13 @@ def test_federated_query_notices_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/notices') mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4433,7 +4628,7 @@ def test_federated_query_notices_value_error(self): "collection_ids": collection_ids, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.federated_query_notices(**req_copy) @@ -4446,7 +4641,8 @@ def test_federated_query_notices_value_error_with_retries(self): _service.disable_retries() self.test_federated_query_notices_value_error() -class TestGetAutocompletion(): + +class TestGetAutocompletion: """ Test Class for get_autocompletion """ @@ -4459,18 +4655,20 @@ def test_get_autocompletion_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' collection_id = 'testString' prefix = 'testString' field = 'testString' - count = 38 + count = 5 # Invoke method response = _service.get_autocompletion( @@ -4479,14 +4677,14 @@ def test_get_autocompletion_all_params(self): prefix, field=field, count=count, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'prefix={}'.format(prefix) in query_string assert 'field={}'.format(field) in query_string @@ -4509,11 +4707,13 @@ def test_get_autocompletion_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4525,14 +4725,14 @@ def test_get_autocompletion_required_params(self): environment_id, collection_id, prefix, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'prefix={}'.format(prefix) in query_string @@ -4553,11 +4753,13 @@ def test_get_autocompletion_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4571,7 +4773,7 @@ def test_get_autocompletion_value_error(self): "prefix": prefix, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_autocompletion(**req_copy) @@ -4584,6 +4786,7 @@ def test_get_autocompletion_value_error_with_retries(self): _service.disable_retries() self.test_get_autocompletion_value_error() + # endregion ############################################################################## # End of Service: Queries @@ -4594,7 +4797,8 @@ def test_get_autocompletion_value_error_with_retries(self): ############################################################################## # region -class TestListTrainingData(): + +class TestListTrainingData: """ Test Class for list_training_data """ @@ -4607,11 +4811,13 @@ def test_list_training_data_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4621,7 +4827,7 @@ def test_list_training_data_all_params(self): response = _service.list_training_data( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -4645,11 +4851,13 @@ def test_list_training_data_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4661,7 +4869,7 @@ def test_list_training_data_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_training_data(**req_copy) @@ -4674,7 +4882,8 @@ def test_list_training_data_value_error_with_retries(self): _service.disable_retries() self.test_list_training_data_value_error() -class TestAddTrainingData(): + +class TestAddTrainingData: """ Test Class for add_training_data """ @@ -4687,11 +4896,13 @@ def test_add_training_data_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -4713,7 +4924,7 @@ def test_add_training_data_all_params(self): natural_language_query=natural_language_query, filter=filter, examples=examples, - headers={} + headers={}, ) # Check for correct operation @@ -4742,11 +4953,13 @@ def test_add_training_data_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -4767,7 +4980,7 @@ def test_add_training_data_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_training_data(**req_copy) @@ -4780,7 +4993,8 @@ def test_add_training_data_value_error_with_retries(self): _service.disable_retries() self.test_add_training_data_value_error() -class TestDeleteAllTrainingData(): + +class TestDeleteAllTrainingData: """ Test Class for delete_all_training_data """ @@ -4792,9 +5006,11 @@ def test_delete_all_training_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -4804,7 +5020,7 @@ def test_delete_all_training_data_all_params(self): response = _service.delete_all_training_data( environment_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -4827,9 +5043,11 @@ def test_delete_all_training_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -4841,7 +5059,7 @@ def test_delete_all_training_data_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_all_training_data(**req_copy) @@ -4854,7 +5072,8 @@ def test_delete_all_training_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_all_training_data_value_error() -class TestGetTrainingData(): + +class TestGetTrainingData: """ Test Class for get_training_data """ @@ -4867,11 +5086,13 @@ def test_get_training_data_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4883,7 +5104,7 @@ def test_get_training_data_all_params(self): environment_id, collection_id, query_id, - headers={} + headers={}, ) # Check for correct operation @@ -4907,11 +5128,13 @@ def test_get_training_data_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -4925,7 +5148,7 @@ def test_get_training_data_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_training_data(**req_copy) @@ -4938,7 +5161,8 @@ def test_get_training_data_value_error_with_retries(self): _service.disable_retries() self.test_get_training_data_value_error() -class TestDeleteTrainingData(): + +class TestDeleteTrainingData: """ Test Class for delete_training_data """ @@ -4950,9 +5174,11 @@ def test_delete_training_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -4964,7 +5190,7 @@ def test_delete_training_data_all_params(self): environment_id, collection_id, query_id, - headers={} + headers={}, ) # Check for correct operation @@ -4987,9 +5213,11 @@ def test_delete_training_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -5003,7 +5231,7 @@ def test_delete_training_data_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_training_data(**req_copy) @@ -5016,7 +5244,8 @@ def test_delete_training_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_training_data_value_error() -class TestListTrainingExamples(): + +class TestListTrainingExamples: """ Test Class for list_training_examples """ @@ -5029,11 +5258,13 @@ def test_list_training_examples_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5045,7 +5276,7 @@ def test_list_training_examples_all_params(self): environment_id, collection_id, query_id, - headers={} + headers={}, ) # Check for correct operation @@ -5069,11 +5300,13 @@ def test_list_training_examples_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5087,7 +5320,7 @@ def test_list_training_examples_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_training_examples(**req_copy) @@ -5100,7 +5333,8 @@ def test_list_training_examples_value_error_with_retries(self): _service.disable_retries() self.test_list_training_examples_value_error() -class TestCreateTrainingExample(): + +class TestCreateTrainingExample: """ Test Class for create_training_example """ @@ -5113,11 +5347,13 @@ def test_create_training_example_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -5135,7 +5371,7 @@ def test_create_training_example_all_params(self): document_id=document_id, cross_reference=cross_reference, relevance=relevance, - headers={} + headers={}, ) # Check for correct operation @@ -5164,11 +5400,13 @@ def test_create_training_example_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values environment_id = 'testString' @@ -5185,7 +5423,7 @@ def test_create_training_example_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_training_example(**req_copy) @@ -5198,7 +5436,8 @@ def test_create_training_example_value_error_with_retries(self): _service.disable_retries() self.test_create_training_example_value_error() -class TestDeleteTrainingExample(): + +class TestDeleteTrainingExample: """ Test Class for delete_training_example """ @@ -5210,9 +5449,11 @@ def test_delete_training_example_all_params(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -5226,7 +5467,7 @@ def test_delete_training_example_all_params(self): collection_id, query_id, example_id, - headers={} + headers={}, ) # Check for correct operation @@ -5249,9 +5490,11 @@ def test_delete_training_example_value_error(self): """ # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values environment_id = 'testString' @@ -5267,7 +5510,7 @@ def test_delete_training_example_value_error(self): "example_id": example_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_training_example(**req_copy) @@ -5280,7 +5523,8 @@ def test_delete_training_example_value_error_with_retries(self): _service.disable_retries() self.test_delete_training_example_value_error() -class TestUpdateTrainingExample(): + +class TestUpdateTrainingExample: """ Test Class for update_training_example """ @@ -5293,11 +5537,13 @@ def test_update_training_example_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5315,7 +5561,7 @@ def test_update_training_example_all_params(self): example_id, cross_reference=cross_reference, relevance=relevance, - headers={} + headers={}, ) # Check for correct operation @@ -5343,11 +5589,13 @@ def test_update_training_example_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5365,7 +5613,7 @@ def test_update_training_example_value_error(self): "example_id": example_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_training_example(**req_copy) @@ -5378,7 +5626,8 @@ def test_update_training_example_value_error_with_retries(self): _service.disable_retries() self.test_update_training_example_value_error() -class TestGetTrainingExample(): + +class TestGetTrainingExample: """ Test Class for get_training_example """ @@ -5391,11 +5640,13 @@ def test_get_training_example_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5409,7 +5660,7 @@ def test_get_training_example_all_params(self): collection_id, query_id, example_id, - headers={} + headers={}, ) # Check for correct operation @@ -5433,11 +5684,13 @@ def test_get_training_example_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -5453,7 +5706,7 @@ def test_get_training_example_value_error(self): "example_id": example_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_training_example(**req_copy) @@ -5466,6 +5719,7 @@ def test_get_training_example_value_error_with_retries(self): _service.disable_retries() self.test_get_training_example_value_error() + # endregion ############################################################################## # End of Service: TrainingData @@ -5476,7 +5730,8 @@ def test_get_training_example_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -5488,9 +5743,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -5498,14 +5755,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -5525,9 +5782,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -5537,7 +5796,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -5550,6 +5809,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -5560,7 +5820,8 @@ def test_delete_user_data_value_error_with_retries(self): ############################################################################## # region -class TestCreateEvent(): + +class TestCreateEvent: """ Test Class for create_event """ @@ -5573,11 +5834,13 @@ def test_create_event_all_params(self): # Set up mock url = preprocess_url('/v1/events') mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a EventData model event_data_model = {} @@ -5596,7 +5859,7 @@ def test_create_event_all_params(self): response = _service.create_event( type, data, - headers={} + headers={}, ) # Check for correct operation @@ -5624,11 +5887,13 @@ def test_create_event_value_error(self): # Set up mock url = preprocess_url('/v1/events') mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a EventData model event_data_model = {} @@ -5649,7 +5914,7 @@ def test_create_event_value_error(self): "data": data, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_event(**req_copy) @@ -5662,7 +5927,8 @@ def test_create_event_value_error_with_retries(self): _service.disable_retries() self.test_create_event_value_error() -class TestQueryLog(): + +class TestQueryLog: """ Test Class for query_log """ @@ -5675,16 +5941,18 @@ def test_query_log_all_params(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values filter = 'testString' query = 'testString' - count = 38 + count = 10 offset = 38 sort = ['testString'] @@ -5695,14 +5963,14 @@ def test_query_log_all_params(self): count=count, offset=offset, sort=sort, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string assert 'query={}'.format(query) in query_string @@ -5727,16 +5995,17 @@ def test_query_log_required_params(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.query_log() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -5758,17 +6027,19 @@ def test_query_log_value_error(self): # Set up mock url = preprocess_url('/v1/logs') mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query_log(**req_copy) @@ -5781,7 +6052,8 @@ def test_query_log_value_error_with_retries(self): _service.disable_retries() self.test_query_log_value_error() -class TestGetMetricsQuery(): + +class TestGetMetricsQuery: """ Test Class for get_metrics_query """ @@ -5794,11 +6066,13 @@ def test_get_metrics_query_all_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values start_time = string_to_datetime('2019-01-01T12:00:00.000Z') @@ -5810,14 +6084,14 @@ def test_get_metrics_query_all_params(self): start_time=start_time, end_time=end_time, result_type=result_type, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string @@ -5838,16 +6112,17 @@ def test_get_metrics_query_required_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.get_metrics_query() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -5869,17 +6144,19 @@ def test_get_metrics_query_value_error(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_metrics_query(**req_copy) @@ -5892,7 +6169,8 @@ def test_get_metrics_query_value_error_with_retries(self): _service.disable_retries() self.test_get_metrics_query_value_error() -class TestGetMetricsQueryEvent(): + +class TestGetMetricsQueryEvent: """ Test Class for get_metrics_query_event """ @@ -5905,11 +6183,13 @@ def test_get_metrics_query_event_all_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_event') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values start_time = string_to_datetime('2019-01-01T12:00:00.000Z') @@ -5921,14 +6201,14 @@ def test_get_metrics_query_event_all_params(self): start_time=start_time, end_time=end_time, result_type=result_type, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string @@ -5949,16 +6229,17 @@ def test_get_metrics_query_event_required_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_event') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.get_metrics_query_event() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -5980,17 +6261,19 @@ def test_get_metrics_query_event_value_error(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_event') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_metrics_query_event(**req_copy) @@ -6003,7 +6286,8 @@ def test_get_metrics_query_event_value_error_with_retries(self): _service.disable_retries() self.test_get_metrics_query_event_value_error() -class TestGetMetricsQueryNoResults(): + +class TestGetMetricsQueryNoResults: """ Test Class for get_metrics_query_no_results """ @@ -6016,11 +6300,13 @@ def test_get_metrics_query_no_results_all_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values start_time = string_to_datetime('2019-01-01T12:00:00.000Z') @@ -6032,14 +6318,14 @@ def test_get_metrics_query_no_results_all_params(self): start_time=start_time, end_time=end_time, result_type=result_type, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string @@ -6060,16 +6346,17 @@ def test_get_metrics_query_no_results_required_params(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.get_metrics_query_no_results() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -6091,17 +6378,19 @@ def test_get_metrics_query_no_results_value_error(self): # Set up mock url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_metrics_query_no_results(**req_copy) @@ -6114,7 +6403,8 @@ def test_get_metrics_query_no_results_value_error_with_retries(self): _service.disable_retries() self.test_get_metrics_query_no_results_value_error() -class TestGetMetricsEventRate(): + +class TestGetMetricsEventRate: """ Test Class for get_metrics_event_rate """ @@ -6127,11 +6417,13 @@ def test_get_metrics_event_rate_all_params(self): # Set up mock url = preprocess_url('/v1/metrics/event_rate') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values start_time = string_to_datetime('2019-01-01T12:00:00.000Z') @@ -6143,14 +6435,14 @@ def test_get_metrics_event_rate_all_params(self): start_time=start_time, end_time=end_time, result_type=result_type, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'result_type={}'.format(result_type) in query_string @@ -6171,16 +6463,17 @@ def test_get_metrics_event_rate_required_params(self): # Set up mock url = preprocess_url('/v1/metrics/event_rate') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.get_metrics_event_rate() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -6202,17 +6495,19 @@ def test_get_metrics_event_rate_value_error(self): # Set up mock url = preprocess_url('/v1/metrics/event_rate') mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_metrics_event_rate(**req_copy) @@ -6225,7 +6520,8 @@ def test_get_metrics_event_rate_value_error_with_retries(self): _service.disable_retries() self.test_get_metrics_event_rate_value_error() -class TestGetMetricsQueryTokenEvent(): + +class TestGetMetricsQueryTokenEvent: """ Test Class for get_metrics_query_token_event """ @@ -6238,26 +6534,28 @@ def test_get_metrics_query_token_event_all_params(self): # Set up mock url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values - count = 38 + count = 10 # Invoke method response = _service.get_metrics_query_token_event( count=count, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'count={}'.format(count) in query_string @@ -6278,16 +6576,17 @@ def test_get_metrics_query_token_event_required_params(self): # Set up mock url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.get_metrics_query_token_event() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -6309,17 +6608,19 @@ def test_get_metrics_query_token_event_value_error(self): # Set up mock url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_metrics_query_token_event(**req_copy) @@ -6332,6 +6633,7 @@ def test_get_metrics_query_token_event_value_error_with_retries(self): _service.disable_retries() self.test_get_metrics_query_token_event_value_error() + # endregion ############################################################################## # End of Service: EventsAndFeedback @@ -6342,7 +6644,8 @@ def test_get_metrics_query_token_event_value_error_with_retries(self): ############################################################################## # region -class TestListCredentials(): + +class TestListCredentials: """ Test Class for list_credentials """ @@ -6355,11 +6658,13 @@ def test_list_credentials_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6367,7 +6672,7 @@ def test_list_credentials_all_params(self): # Invoke method response = _service.list_credentials( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -6391,11 +6696,13 @@ def test_list_credentials_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6405,7 +6712,7 @@ def test_list_credentials_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_credentials(**req_copy) @@ -6418,7 +6725,8 @@ def test_list_credentials_value_error_with_retries(self): _service.disable_retries() self.test_list_credentials_value_error() -class TestCreateCredentials(): + +class TestCreateCredentials: """ Test Class for create_credentials """ @@ -6431,11 +6739,13 @@ def test_create_credentials_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CredentialDetails model credential_details_model = {} @@ -6476,7 +6786,7 @@ def test_create_credentials_all_params(self): source_type=source_type, credential_details=credential_details, status=status, - headers={} + headers={}, ) # Check for correct operation @@ -6505,11 +6815,13 @@ def test_create_credentials_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CredentialDetails model credential_details_model = {} @@ -6549,7 +6861,7 @@ def test_create_credentials_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_credentials(**req_copy) @@ -6562,7 +6874,8 @@ def test_create_credentials_value_error_with_retries(self): _service.disable_retries() self.test_create_credentials_value_error() -class TestGetCredentials(): + +class TestGetCredentials: """ Test Class for get_credentials """ @@ -6575,11 +6888,13 @@ def test_get_credentials_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6589,7 +6904,7 @@ def test_get_credentials_all_params(self): response = _service.get_credentials( environment_id, credential_id, - headers={} + headers={}, ) # Check for correct operation @@ -6613,11 +6928,13 @@ def test_get_credentials_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6629,7 +6946,7 @@ def test_get_credentials_value_error(self): "credential_id": credential_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_credentials(**req_copy) @@ -6642,7 +6959,8 @@ def test_get_credentials_value_error_with_retries(self): _service.disable_retries() self.test_get_credentials_value_error() -class TestUpdateCredentials(): + +class TestUpdateCredentials: """ Test Class for update_credentials """ @@ -6655,11 +6973,13 @@ def test_update_credentials_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CredentialDetails model credential_details_model = {} @@ -6702,7 +7022,7 @@ def test_update_credentials_all_params(self): source_type=source_type, credential_details=credential_details, status=status, - headers={} + headers={}, ) # Check for correct operation @@ -6731,11 +7051,13 @@ def test_update_credentials_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CredentialDetails model credential_details_model = {} @@ -6777,7 +7099,7 @@ def test_update_credentials_value_error(self): "credential_id": credential_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_credentials(**req_copy) @@ -6790,7 +7112,8 @@ def test_update_credentials_value_error_with_retries(self): _service.disable_retries() self.test_update_credentials_value_error() -class TestDeleteCredentials(): + +class TestDeleteCredentials: """ Test Class for delete_credentials """ @@ -6803,11 +7126,13 @@ def test_delete_credentials_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6817,7 +7142,7 @@ def test_delete_credentials_all_params(self): response = _service.delete_credentials( environment_id, credential_id, - headers={} + headers={}, ) # Check for correct operation @@ -6841,11 +7166,13 @@ def test_delete_credentials_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/credentials/testString') mock_response = '{"credential_id": "credential_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6857,7 +7184,7 @@ def test_delete_credentials_value_error(self): "credential_id": credential_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_credentials(**req_copy) @@ -6870,6 +7197,7 @@ def test_delete_credentials_value_error_with_retries(self): _service.disable_retries() self.test_delete_credentials_value_error() + # endregion ############################################################################## # End of Service: Credentials @@ -6880,7 +7208,8 @@ def test_delete_credentials_value_error_with_retries(self): ############################################################################## # region -class TestListGateways(): + +class TestListGateways: """ Test Class for list_gateways """ @@ -6893,11 +7222,13 @@ def test_list_gateways_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6905,7 +7236,7 @@ def test_list_gateways_all_params(self): # Invoke method response = _service.list_gateways( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -6929,11 +7260,13 @@ def test_list_gateways_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6943,7 +7276,7 @@ def test_list_gateways_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_gateways(**req_copy) @@ -6956,7 +7289,8 @@ def test_list_gateways_value_error_with_retries(self): _service.disable_retries() self.test_list_gateways_value_error() -class TestCreateGateway(): + +class TestCreateGateway: """ Test Class for create_gateway """ @@ -6969,11 +7303,13 @@ def test_create_gateway_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -6983,7 +7319,7 @@ def test_create_gateway_all_params(self): response = _service.create_gateway( environment_id, name=name, - headers={} + headers={}, ) # Check for correct operation @@ -7010,11 +7346,13 @@ def test_create_gateway_required_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7022,7 +7360,7 @@ def test_create_gateway_required_params(self): # Invoke method response = _service.create_gateway( environment_id, - headers={} + headers={}, ) # Check for correct operation @@ -7046,11 +7384,13 @@ def test_create_gateway_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7060,7 +7400,7 @@ def test_create_gateway_value_error(self): "environment_id": environment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_gateway(**req_copy) @@ -7073,7 +7413,8 @@ def test_create_gateway_value_error_with_retries(self): _service.disable_retries() self.test_create_gateway_value_error() -class TestGetGateway(): + +class TestGetGateway: """ Test Class for get_gateway """ @@ -7086,11 +7427,13 @@ def test_get_gateway_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7100,7 +7443,7 @@ def test_get_gateway_all_params(self): response = _service.get_gateway( environment_id, gateway_id, - headers={} + headers={}, ) # Check for correct operation @@ -7124,11 +7467,13 @@ def test_get_gateway_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7140,7 +7485,7 @@ def test_get_gateway_value_error(self): "gateway_id": gateway_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_gateway(**req_copy) @@ -7153,7 +7498,8 @@ def test_get_gateway_value_error_with_retries(self): _service.disable_retries() self.test_get_gateway_value_error() -class TestDeleteGateway(): + +class TestDeleteGateway: """ Test Class for delete_gateway """ @@ -7166,11 +7512,13 @@ def test_delete_gateway_all_params(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "status": "status"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7180,7 +7528,7 @@ def test_delete_gateway_all_params(self): response = _service.delete_gateway( environment_id, gateway_id, - headers={} + headers={}, ) # Check for correct operation @@ -7204,11 +7552,13 @@ def test_delete_gateway_value_error(self): # Set up mock url = preprocess_url('/v1/environments/testString/gateways/testString') mock_response = '{"gateway_id": "gateway_id", "status": "status"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values environment_id = 'testString' @@ -7220,7 +7570,7 @@ def test_delete_gateway_value_error(self): "gateway_id": gateway_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_gateway(**req_copy) @@ -7233,6 +7583,7 @@ def test_delete_gateway_value_error_with_retries(self): _service.disable_retries() self.test_delete_gateway_value_error() + # endregion ############################################################################## # End of Service: GatewayConfiguration @@ -7243,7 +7594,9 @@ def test_delete_gateway_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_Collection(): + + +class TestModel_Collection: """ Test Class for Collection """ @@ -7255,11 +7608,11 @@ def test_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_counts_model = {} # DocumentCounts + document_counts_model = {} # DocumentCounts - collection_disk_usage_model = {} # CollectionDiskUsage + collection_disk_usage_model = {} # CollectionDiskUsage - training_status_model = {} # TrainingStatus + training_status_model = {} # TrainingStatus training_status_model['total_examples'] = 0 training_status_model['available'] = False training_status_model['processing'] = False @@ -7270,18 +7623,18 @@ def test_collection_serialization(self): training_status_model['successfully_trained'] = '2019-01-01T12:00:00Z' training_status_model['data_updated'] = '2019-01-01T12:00:00Z' - source_status_model = {} # SourceStatus + source_status_model = {} # SourceStatus source_status_model['status'] = 'complete' source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' - collection_crawl_status_model = {} # CollectionCrawlStatus + collection_crawl_status_model = {} # CollectionCrawlStatus collection_crawl_status_model['source_crawl'] = source_status_model - sdu_status_custom_fields_model = {} # SduStatusCustomFields + sdu_status_custom_fields_model = {} # SduStatusCustomFields sdu_status_custom_fields_model['defined'] = 26 sdu_status_custom_fields_model['maximum_allowed'] = 5 - sdu_status_model = {} # SduStatus + sdu_status_model = {} # SduStatus sdu_status_model['enabled'] = True sdu_status_model['total_annotated_pages'] = 0 sdu_status_model['total_pages'] = 0 @@ -7315,7 +7668,8 @@ def test_collection_serialization(self): collection_model_json2 = collection_model.to_dict() assert collection_model_json2 == collection_model_json -class TestModel_CollectionCrawlStatus(): + +class TestModel_CollectionCrawlStatus: """ Test Class for CollectionCrawlStatus """ @@ -7327,7 +7681,7 @@ def test_collection_crawl_status_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - source_status_model = {} # SourceStatus + source_status_model = {} # SourceStatus source_status_model['status'] = 'running' source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' @@ -7350,7 +7704,8 @@ def test_collection_crawl_status_serialization(self): collection_crawl_status_model_json2 = collection_crawl_status_model.to_dict() assert collection_crawl_status_model_json2 == collection_crawl_status_model_json -class TestModel_CollectionDiskUsage(): + +class TestModel_CollectionDiskUsage: """ Test Class for CollectionDiskUsage """ @@ -7378,7 +7733,8 @@ def test_collection_disk_usage_serialization(self): collection_disk_usage_model_json2 = collection_disk_usage_model.to_dict() assert collection_disk_usage_model_json2 == collection_disk_usage_model_json -class TestModel_CollectionUsage(): + +class TestModel_CollectionUsage: """ Test Class for CollectionUsage """ @@ -7406,7 +7762,8 @@ def test_collection_usage_serialization(self): collection_usage_model_json2 = collection_usage_model.to_dict() assert collection_usage_model_json2 == collection_usage_model_json -class TestModel_Completions(): + +class TestModel_Completions: """ Test Class for Completions """ @@ -7435,7 +7792,8 @@ def test_completions_serialization(self): completions_model_json2 = completions_model.to_dict() assert completions_model_json2 == completions_model_json -class TestModel_Configuration(): + +class TestModel_Configuration: """ Test Class for Configuration """ @@ -7447,7 +7805,7 @@ def test_configuration_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -7455,27 +7813,27 @@ def test_configuration_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model = {} # PdfHeadingDetection pdf_heading_detection_model['fonts'] = [font_setting_model] - pdf_settings_model = {} # PdfSettings + pdf_settings_model = {} # PdfSettings pdf_settings_model['heading'] = pdf_heading_detection_model - word_style_model = {} # WordStyle + word_style_model = {} # WordStyle word_style_model['level'] = 38 word_style_model['names'] = ['testString'] - word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model = {} # WordHeadingDetection word_heading_detection_model['fonts'] = [font_setting_model] word_heading_detection_model['styles'] = [word_style_model] - word_settings_model = {} # WordSettings + word_settings_model = {} # WordSettings word_settings_model['heading'] = word_heading_detection_model - x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model = {} # XPathPatterns x_path_patterns_model['xpaths'] = ['testString'] - html_settings_model = {} # HtmlSettings + html_settings_model = {} # HtmlSettings html_settings_model['exclude_tags_completely'] = ['testString'] html_settings_model['exclude_tags_keep_content'] = ['span'] html_settings_model['keep_content'] = x_path_patterns_model @@ -7483,17 +7841,17 @@ def test_configuration_serialization(self): html_settings_model['keep_tag_attributes'] = ['testString'] html_settings_model['exclude_tag_attributes'] = ['testString'] - segment_settings_model = {} # SegmentSettings + segment_settings_model = {} # SegmentSettings segment_settings_model['enabled'] = True segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['custom-field-1', 'custom-field-2'] - normalization_operation_model = {} # NormalizationOperation + normalization_operation_model = {} # NormalizationOperation normalization_operation_model['operation'] = 'move' normalization_operation_model['source_field'] = 'extracted_metadata.title' normalization_operation_model['destination_field'] = 'metadata.title' - conversions_model = {} # Conversions + conversions_model = {} # Conversions conversions_model['pdf'] = pdf_settings_model conversions_model['word'] = word_settings_model conversions_model['html'] = html_settings_model @@ -7501,12 +7859,12 @@ def test_configuration_serialization(self): conversions_model['json_normalizations'] = [normalization_operation_model] conversions_model['image_text_recognition'] = True - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords nlu_enrichment_keywords_model['sentiment'] = True nlu_enrichment_keywords_model['emotion'] = False nlu_enrichment_keywords_model['limit'] = 50 - nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model = {} # NluEnrichmentEntities nlu_enrichment_entities_model['sentiment'] = True nlu_enrichment_entities_model['emotion'] = False nlu_enrichment_entities_model['limit'] = 50 @@ -7515,41 +7873,41 @@ def test_configuration_serialization(self): nlu_enrichment_entities_model['sentence_locations'] = True nlu_enrichment_entities_model['model'] = 'WKS-model-id' - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment nlu_enrichment_sentiment_model['document'] = True nlu_enrichment_sentiment_model['targets'] = ['IBM', 'Watson'] - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion nlu_enrichment_emotion_model['document'] = True nlu_enrichment_emotion_model['targets'] = ['IBM', 'Watson'] - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles nlu_enrichment_semantic_roles_model['entities'] = True nlu_enrichment_semantic_roles_model['keywords'] = True nlu_enrichment_semantic_roles_model['limit'] = 50 - nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model = {} # NluEnrichmentRelations nlu_enrichment_relations_model['model'] = 'WKS-model-id' - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts nlu_enrichment_concepts_model['limit'] = 8 - nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model = {} # NluEnrichmentFeatures nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['features'] = nlu_enrichment_features_model enrichment_options_model['language'] = 'ar' enrichment_options_model['model'] = 'testString' - enrichment_model = {} # Enrichment + enrichment_model = {} # Enrichment enrichment_model['description'] = 'testString' enrichment_model['destination_field'] = 'enriched_title' enrichment_model['source_field'] = 'title' @@ -7558,39 +7916,39 @@ def test_configuration_serialization(self): enrichment_model['ignore_downstream_errors'] = False enrichment_model['options'] = enrichment_options_model - source_schedule_model = {} # SourceSchedule + source_schedule_model = {} # SourceSchedule source_schedule_model['enabled'] = True source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'weekly' - source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model = {} # SourceOptionsFolder source_options_folder_model['owner_user_id'] = 'testString' source_options_folder_model['folder_id'] = 'testString' source_options_folder_model['limit'] = 38 - source_options_object_model = {} # SourceOptionsObject + source_options_object_model = {} # SourceOptionsObject source_options_object_model['name'] = 'testString' source_options_object_model['limit'] = 38 - source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model = {} # SourceOptionsSiteColl source_options_site_coll_model['site_collection_path'] = '/sites/TestSiteA' source_options_site_coll_model['limit'] = 10 - source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] - source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model = {} # SourceOptionsBuckets source_options_buckets_model['name'] = 'testString' source_options_buckets_model['limit'] = 38 - source_options_model = {} # SourceOptions + source_options_model = {} # SourceOptions source_options_model['folders'] = [source_options_folder_model] source_options_model['objects'] = [source_options_object_model] source_options_model['site_collections'] = [source_options_site_coll_model] @@ -7598,7 +7956,7 @@ def test_configuration_serialization(self): source_options_model['buckets'] = [source_options_buckets_model] source_options_model['crawl_all_buckets'] = True - source_model = {} # Source + source_model = {} # Source source_model['type'] = 'salesforce' source_model['credential_id'] = '00ad0000-0000-11e8-ba89-0ed5f00f718b' source_model['schedule'] = source_schedule_model @@ -7628,7 +7986,8 @@ def test_configuration_serialization(self): configuration_model_json2 = configuration_model.to_dict() assert configuration_model_json2 == configuration_model_json -class TestModel_Conversions(): + +class TestModel_Conversions: """ Test Class for Conversions """ @@ -7640,7 +7999,7 @@ def test_conversions_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -7648,27 +8007,27 @@ def test_conversions_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model = {} # PdfHeadingDetection pdf_heading_detection_model['fonts'] = [font_setting_model] - pdf_settings_model = {} # PdfSettings + pdf_settings_model = {} # PdfSettings pdf_settings_model['heading'] = pdf_heading_detection_model - word_style_model = {} # WordStyle + word_style_model = {} # WordStyle word_style_model['level'] = 38 word_style_model['names'] = ['testString'] - word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model = {} # WordHeadingDetection word_heading_detection_model['fonts'] = [font_setting_model] word_heading_detection_model['styles'] = [word_style_model] - word_settings_model = {} # WordSettings + word_settings_model = {} # WordSettings word_settings_model['heading'] = word_heading_detection_model - x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model = {} # XPathPatterns x_path_patterns_model['xpaths'] = ['testString'] - html_settings_model = {} # HtmlSettings + html_settings_model = {} # HtmlSettings html_settings_model['exclude_tags_completely'] = ['testString'] html_settings_model['exclude_tags_keep_content'] = ['testString'] html_settings_model['keep_content'] = x_path_patterns_model @@ -7676,12 +8035,12 @@ def test_conversions_serialization(self): html_settings_model['keep_tag_attributes'] = ['testString'] html_settings_model['exclude_tag_attributes'] = ['testString'] - segment_settings_model = {} # SegmentSettings + segment_settings_model = {} # SegmentSettings segment_settings_model['enabled'] = False segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['testString'] - normalization_operation_model = {} # NormalizationOperation + normalization_operation_model = {} # NormalizationOperation normalization_operation_model['operation'] = 'copy' normalization_operation_model['source_field'] = 'testString' normalization_operation_model['destination_field'] = 'testString' @@ -7710,7 +8069,8 @@ def test_conversions_serialization(self): conversions_model_json2 = conversions_model.to_dict() assert conversions_model_json2 == conversions_model_json -class TestModel_CreateEventResponse(): + +class TestModel_CreateEventResponse: """ Test Class for CreateEventResponse """ @@ -7722,7 +8082,7 @@ def test_create_event_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - event_data_model = {} # EventData + event_data_model = {} # EventData event_data_model['environment_id'] = 'testString' event_data_model['session_token'] = 'testString' event_data_model['client_timestamp'] = '2019-01-01T12:00:00Z' @@ -7750,7 +8110,8 @@ def test_create_event_response_serialization(self): create_event_response_model_json2 = create_event_response_model.to_dict() assert create_event_response_model_json2 == create_event_response_model_json -class TestModel_CredentialDetails(): + +class TestModel_CredentialDetails: """ Test Class for CredentialDetails """ @@ -7797,7 +8158,8 @@ def test_credential_details_serialization(self): credential_details_model_json2 = credential_details_model.to_dict() assert credential_details_model_json2 == credential_details_model_json -class TestModel_Credentials(): + +class TestModel_Credentials: """ Test Class for Credentials """ @@ -7809,7 +8171,7 @@ def test_credentials_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - credential_details_model = {} # CredentialDetails + credential_details_model = {} # CredentialDetails credential_details_model['credential_type'] = 'username_password' credential_details_model['client_id'] = 'testString' credential_details_model['enterprise_id'] = 'testString' @@ -7830,7 +8192,7 @@ def test_credentials_serialization(self): credential_details_model['access_key_id'] = 'testString' credential_details_model['secret_access_key'] = 'testString' - status_details_model = {} # StatusDetails + status_details_model = {} # StatusDetails status_details_model['authenticated'] = True status_details_model['error_message'] = 'testString' @@ -7855,7 +8217,8 @@ def test_credentials_serialization(self): credentials_model_json2 = credentials_model.to_dict() assert credentials_model_json2 == credentials_model_json -class TestModel_CredentialsList(): + +class TestModel_CredentialsList: """ Test Class for CredentialsList """ @@ -7867,7 +8230,7 @@ def test_credentials_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - credential_details_model = {} # CredentialDetails + credential_details_model = {} # CredentialDetails credential_details_model['credential_type'] = 'username_password' credential_details_model['client_id'] = 'testString' credential_details_model['enterprise_id'] = 'testString' @@ -7888,11 +8251,11 @@ def test_credentials_list_serialization(self): credential_details_model['access_key_id'] = 'testString' credential_details_model['secret_access_key'] = 'testString' - status_details_model = {} # StatusDetails + status_details_model = {} # StatusDetails status_details_model['authenticated'] = True status_details_model['error_message'] = 'testString' - credentials_model = {} # Credentials + credentials_model = {} # Credentials credentials_model['source_type'] = 'salesforce' credentials_model['credential_details'] = credential_details_model credentials_model['status'] = status_details_model @@ -7916,7 +8279,8 @@ def test_credentials_list_serialization(self): credentials_list_model_json2 = credentials_list_model.to_dict() assert credentials_list_model_json2 == credentials_list_model_json -class TestModel_DeleteCollectionResponse(): + +class TestModel_DeleteCollectionResponse: """ Test Class for DeleteCollectionResponse """ @@ -7946,7 +8310,8 @@ def test_delete_collection_response_serialization(self): delete_collection_response_model_json2 = delete_collection_response_model.to_dict() assert delete_collection_response_model_json2 == delete_collection_response_model_json -class TestModel_DeleteConfigurationResponse(): + +class TestModel_DeleteConfigurationResponse: """ Test Class for DeleteConfigurationResponse """ @@ -7958,7 +8323,7 @@ def test_delete_configuration_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a DeleteConfigurationResponse model delete_configuration_response_model_json = {} @@ -7981,7 +8346,8 @@ def test_delete_configuration_response_serialization(self): delete_configuration_response_model_json2 = delete_configuration_response_model.to_dict() assert delete_configuration_response_model_json2 == delete_configuration_response_model_json -class TestModel_DeleteCredentials(): + +class TestModel_DeleteCredentials: """ Test Class for DeleteCredentials """ @@ -8011,7 +8377,8 @@ def test_delete_credentials_serialization(self): delete_credentials_model_json2 = delete_credentials_model.to_dict() assert delete_credentials_model_json2 == delete_credentials_model_json -class TestModel_DeleteDocumentResponse(): + +class TestModel_DeleteDocumentResponse: """ Test Class for DeleteDocumentResponse """ @@ -8041,7 +8408,8 @@ def test_delete_document_response_serialization(self): delete_document_response_model_json2 = delete_document_response_model.to_dict() assert delete_document_response_model_json2 == delete_document_response_model_json -class TestModel_DeleteEnvironmentResponse(): + +class TestModel_DeleteEnvironmentResponse: """ Test Class for DeleteEnvironmentResponse """ @@ -8071,7 +8439,8 @@ def test_delete_environment_response_serialization(self): delete_environment_response_model_json2 = delete_environment_response_model.to_dict() assert delete_environment_response_model_json2 == delete_environment_response_model_json -class TestModel_DiskUsage(): + +class TestModel_DiskUsage: """ Test Class for DiskUsage """ @@ -8099,7 +8468,8 @@ def test_disk_usage_serialization(self): disk_usage_model_json2 = disk_usage_model.to_dict() assert disk_usage_model_json2 == disk_usage_model_json -class TestModel_DocumentAccepted(): + +class TestModel_DocumentAccepted: """ Test Class for DocumentAccepted """ @@ -8111,7 +8481,7 @@ def test_document_accepted_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a DocumentAccepted model document_accepted_model_json = {} @@ -8134,7 +8504,8 @@ def test_document_accepted_serialization(self): document_accepted_model_json2 = document_accepted_model.to_dict() assert document_accepted_model_json2 == document_accepted_model_json -class TestModel_DocumentCounts(): + +class TestModel_DocumentCounts: """ Test Class for DocumentCounts """ @@ -8162,7 +8533,8 @@ def test_document_counts_serialization(self): document_counts_model_json2 = document_counts_model.to_dict() assert document_counts_model_json2 == document_counts_model_json -class TestModel_DocumentStatus(): + +class TestModel_DocumentStatus: """ Test Class for DocumentStatus """ @@ -8193,7 +8565,8 @@ def test_document_status_serialization(self): document_status_model_json2 = document_status_model.to_dict() assert document_status_model_json2 == document_status_model_json -class TestModel_Enrichment(): + +class TestModel_Enrichment: """ Test Class for Enrichment """ @@ -8205,12 +8578,12 @@ def test_enrichment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords nlu_enrichment_keywords_model['sentiment'] = True nlu_enrichment_keywords_model['emotion'] = True nlu_enrichment_keywords_model['limit'] = 38 - nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model = {} # NluEnrichmentEntities nlu_enrichment_entities_model['sentiment'] = True nlu_enrichment_entities_model['emotion'] = True nlu_enrichment_entities_model['limit'] = 38 @@ -8219,36 +8592,36 @@ def test_enrichment_serialization(self): nlu_enrichment_entities_model['sentence_locations'] = True nlu_enrichment_entities_model['model'] = 'testString' - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment nlu_enrichment_sentiment_model['document'] = True nlu_enrichment_sentiment_model['targets'] = ['testString'] - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion nlu_enrichment_emotion_model['document'] = True nlu_enrichment_emotion_model['targets'] = ['testString'] - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles nlu_enrichment_semantic_roles_model['entities'] = True nlu_enrichment_semantic_roles_model['keywords'] = True nlu_enrichment_semantic_roles_model['limit'] = 38 - nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model = {} # NluEnrichmentRelations nlu_enrichment_relations_model['model'] = 'testString' - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts nlu_enrichment_concepts_model['limit'] = 38 - nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model = {} # NluEnrichmentFeatures nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['features'] = nlu_enrichment_features_model enrichment_options_model['language'] = 'ar' enrichment_options_model['model'] = 'testString' @@ -8278,7 +8651,8 @@ def test_enrichment_serialization(self): enrichment_model_json2 = enrichment_model.to_dict() assert enrichment_model_json2 == enrichment_model_json -class TestModel_EnrichmentOptions(): + +class TestModel_EnrichmentOptions: """ Test Class for EnrichmentOptions """ @@ -8290,12 +8664,12 @@ def test_enrichment_options_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords nlu_enrichment_keywords_model['sentiment'] = True nlu_enrichment_keywords_model['emotion'] = True nlu_enrichment_keywords_model['limit'] = 38 - nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model = {} # NluEnrichmentEntities nlu_enrichment_entities_model['sentiment'] = True nlu_enrichment_entities_model['emotion'] = True nlu_enrichment_entities_model['limit'] = 38 @@ -8304,31 +8678,31 @@ def test_enrichment_options_serialization(self): nlu_enrichment_entities_model['sentence_locations'] = True nlu_enrichment_entities_model['model'] = 'testString' - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment nlu_enrichment_sentiment_model['document'] = True nlu_enrichment_sentiment_model['targets'] = ['testString'] - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion nlu_enrichment_emotion_model['document'] = True nlu_enrichment_emotion_model['targets'] = ['testString'] - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles nlu_enrichment_semantic_roles_model['entities'] = True nlu_enrichment_semantic_roles_model['keywords'] = True nlu_enrichment_semantic_roles_model['limit'] = 38 - nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model = {} # NluEnrichmentRelations nlu_enrichment_relations_model['model'] = 'testString' - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts nlu_enrichment_concepts_model['limit'] = 38 - nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model = {} # NluEnrichmentFeatures nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model @@ -8354,7 +8728,8 @@ def test_enrichment_options_serialization(self): enrichment_options_model_json2 = enrichment_options_model.to_dict() assert enrichment_options_model_json2 == enrichment_options_model_json -class TestModel_Environment(): + +class TestModel_Environment: """ Test Class for Environment """ @@ -8366,18 +8741,18 @@ def test_environment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_documents_model = {} # EnvironmentDocuments + environment_documents_model = {} # EnvironmentDocuments - disk_usage_model = {} # DiskUsage + disk_usage_model = {} # DiskUsage - collection_usage_model = {} # CollectionUsage + collection_usage_model = {} # CollectionUsage - index_capacity_model = {} # IndexCapacity + index_capacity_model = {} # IndexCapacity index_capacity_model['documents'] = environment_documents_model index_capacity_model['disk_usage'] = disk_usage_model index_capacity_model['collections'] = collection_usage_model - search_status_model = {} # SearchStatus + search_status_model = {} # SearchStatus search_status_model['scope'] = 'testString' search_status_model['status'] = 'NO_DATA' search_status_model['status_description'] = 'testString' @@ -8407,7 +8782,8 @@ def test_environment_serialization(self): environment_model_json2 = environment_model.to_dict() assert environment_model_json2 == environment_model_json -class TestModel_EnvironmentDocuments(): + +class TestModel_EnvironmentDocuments: """ Test Class for EnvironmentDocuments """ @@ -8435,7 +8811,8 @@ def test_environment_documents_serialization(self): environment_documents_model_json2 = environment_documents_model.to_dict() assert environment_documents_model_json2 == environment_documents_model_json -class TestModel_EventData(): + +class TestModel_EventData: """ Test Class for EventData """ @@ -8469,7 +8846,8 @@ def test_event_data_serialization(self): event_data_model_json2 = event_data_model.to_dict() assert event_data_model_json2 == event_data_model_json -class TestModel_Expansion(): + +class TestModel_Expansion: """ Test Class for Expansion """ @@ -8499,7 +8877,8 @@ def test_expansion_serialization(self): expansion_model_json2 = expansion_model.to_dict() assert expansion_model_json2 == expansion_model_json -class TestModel_Expansions(): + +class TestModel_Expansions: """ Test Class for Expansions """ @@ -8511,7 +8890,7 @@ def test_expansions_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - expansion_model = {} # Expansion + expansion_model = {} # Expansion expansion_model['input_terms'] = ['testString'] expansion_model['expanded_terms'] = ['testString'] @@ -8534,7 +8913,8 @@ def test_expansions_serialization(self): expansions_model_json2 = expansions_model.to_dict() assert expansions_model_json2 == expansions_model_json -class TestModel_Field(): + +class TestModel_Field: """ Test Class for Field """ @@ -8562,7 +8942,8 @@ def test_field_serialization(self): field_model_json2 = field_model.to_dict() assert field_model_json2 == field_model_json -class TestModel_FontSetting(): + +class TestModel_FontSetting: """ Test Class for FontSetting """ @@ -8596,7 +8977,8 @@ def test_font_setting_serialization(self): font_setting_model_json2 = font_setting_model.to_dict() assert font_setting_model_json2 == font_setting_model_json -class TestModel_Gateway(): + +class TestModel_Gateway: """ Test Class for Gateway """ @@ -8629,7 +9011,8 @@ def test_gateway_serialization(self): gateway_model_json2 = gateway_model.to_dict() assert gateway_model_json2 == gateway_model_json -class TestModel_GatewayDelete(): + +class TestModel_GatewayDelete: """ Test Class for GatewayDelete """ @@ -8659,7 +9042,8 @@ def test_gateway_delete_serialization(self): gateway_delete_model_json2 = gateway_delete_model.to_dict() assert gateway_delete_model_json2 == gateway_delete_model_json -class TestModel_GatewayList(): + +class TestModel_GatewayList: """ Test Class for GatewayList """ @@ -8671,7 +9055,7 @@ def test_gateway_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - gateway_model = {} # Gateway + gateway_model = {} # Gateway gateway_model['gateway_id'] = 'testString' gateway_model['name'] = 'testString' gateway_model['status'] = 'connected' @@ -8697,7 +9081,8 @@ def test_gateway_list_serialization(self): gateway_list_model_json2 = gateway_list_model.to_dict() assert gateway_list_model_json2 == gateway_list_model_json -class TestModel_HtmlSettings(): + +class TestModel_HtmlSettings: """ Test Class for HtmlSettings """ @@ -8709,7 +9094,7 @@ def test_html_settings_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model = {} # XPathPatterns x_path_patterns_model['xpaths'] = ['testString'] # Construct a json representation of a HtmlSettings model @@ -8736,7 +9121,8 @@ def test_html_settings_serialization(self): html_settings_model_json2 = html_settings_model.to_dict() assert html_settings_model_json2 == html_settings_model_json -class TestModel_IndexCapacity(): + +class TestModel_IndexCapacity: """ Test Class for IndexCapacity """ @@ -8748,11 +9134,11 @@ def test_index_capacity_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_documents_model = {} # EnvironmentDocuments + environment_documents_model = {} # EnvironmentDocuments - disk_usage_model = {} # DiskUsage + disk_usage_model = {} # DiskUsage - collection_usage_model = {} # CollectionUsage + collection_usage_model = {} # CollectionUsage # Construct a json representation of a IndexCapacity model index_capacity_model_json = {} @@ -8775,7 +9161,8 @@ def test_index_capacity_serialization(self): index_capacity_model_json2 = index_capacity_model.to_dict() assert index_capacity_model_json2 == index_capacity_model_json -class TestModel_ListCollectionFieldsResponse(): + +class TestModel_ListCollectionFieldsResponse: """ Test Class for ListCollectionFieldsResponse """ @@ -8787,7 +9174,7 @@ def test_list_collection_fields_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - field_model = {} # Field + field_model = {} # Field # Construct a json representation of a ListCollectionFieldsResponse model list_collection_fields_response_model_json = {} @@ -8808,7 +9195,8 @@ def test_list_collection_fields_response_serialization(self): list_collection_fields_response_model_json2 = list_collection_fields_response_model.to_dict() assert list_collection_fields_response_model_json2 == list_collection_fields_response_model_json -class TestModel_ListCollectionsResponse(): + +class TestModel_ListCollectionsResponse: """ Test Class for ListCollectionsResponse """ @@ -8820,11 +9208,11 @@ def test_list_collections_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_counts_model = {} # DocumentCounts + document_counts_model = {} # DocumentCounts - collection_disk_usage_model = {} # CollectionDiskUsage + collection_disk_usage_model = {} # CollectionDiskUsage - training_status_model = {} # TrainingStatus + training_status_model = {} # TrainingStatus training_status_model['total_examples'] = 38 training_status_model['available'] = True training_status_model['processing'] = True @@ -8835,25 +9223,25 @@ def test_list_collections_response_serialization(self): training_status_model['successfully_trained'] = '2019-01-01T12:00:00Z' training_status_model['data_updated'] = '2019-01-01T12:00:00Z' - source_status_model = {} # SourceStatus + source_status_model = {} # SourceStatus source_status_model['status'] = 'running' source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' - collection_crawl_status_model = {} # CollectionCrawlStatus + collection_crawl_status_model = {} # CollectionCrawlStatus collection_crawl_status_model['source_crawl'] = source_status_model - sdu_status_custom_fields_model = {} # SduStatusCustomFields + sdu_status_custom_fields_model = {} # SduStatusCustomFields sdu_status_custom_fields_model['defined'] = 26 sdu_status_custom_fields_model['maximum_allowed'] = 26 - sdu_status_model = {} # SduStatus + sdu_status_model = {} # SduStatus sdu_status_model['enabled'] = True sdu_status_model['total_annotated_pages'] = 26 sdu_status_model['total_pages'] = 26 sdu_status_model['total_documents'] = 26 sdu_status_model['custom_fields'] = sdu_status_custom_fields_model - collection_model = {} # Collection + collection_model = {} # Collection collection_model['name'] = 'example' collection_model['description'] = 'this is a demo collection' collection_model['configuration_id'] = '6963be41-2dea-4f79-8f52-127c63c479b0' @@ -8883,7 +9271,8 @@ def test_list_collections_response_serialization(self): list_collections_response_model_json2 = list_collections_response_model.to_dict() assert list_collections_response_model_json2 == list_collections_response_model_json -class TestModel_ListConfigurationsResponse(): + +class TestModel_ListConfigurationsResponse: """ Test Class for ListConfigurationsResponse """ @@ -8895,7 +9284,7 @@ def test_list_configurations_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -8903,27 +9292,27 @@ def test_list_configurations_response_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model = {} # PdfHeadingDetection pdf_heading_detection_model['fonts'] = [font_setting_model] - pdf_settings_model = {} # PdfSettings + pdf_settings_model = {} # PdfSettings pdf_settings_model['heading'] = pdf_heading_detection_model - word_style_model = {} # WordStyle + word_style_model = {} # WordStyle word_style_model['level'] = 38 word_style_model['names'] = ['testString'] - word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model = {} # WordHeadingDetection word_heading_detection_model['fonts'] = [font_setting_model] word_heading_detection_model['styles'] = [word_style_model] - word_settings_model = {} # WordSettings + word_settings_model = {} # WordSettings word_settings_model['heading'] = word_heading_detection_model - x_path_patterns_model = {} # XPathPatterns + x_path_patterns_model = {} # XPathPatterns x_path_patterns_model['xpaths'] = ['testString'] - html_settings_model = {} # HtmlSettings + html_settings_model = {} # HtmlSettings html_settings_model['exclude_tags_completely'] = ['testString'] html_settings_model['exclude_tags_keep_content'] = ['testString'] html_settings_model['keep_content'] = x_path_patterns_model @@ -8931,17 +9320,17 @@ def test_list_configurations_response_serialization(self): html_settings_model['keep_tag_attributes'] = ['testString'] html_settings_model['exclude_tag_attributes'] = ['testString'] - segment_settings_model = {} # SegmentSettings + segment_settings_model = {} # SegmentSettings segment_settings_model['enabled'] = False segment_settings_model['selector_tags'] = ['h1', 'h2'] segment_settings_model['annotated_fields'] = ['testString'] - normalization_operation_model = {} # NormalizationOperation + normalization_operation_model = {} # NormalizationOperation normalization_operation_model['operation'] = 'copy' normalization_operation_model['source_field'] = 'testString' normalization_operation_model['destination_field'] = 'testString' - conversions_model = {} # Conversions + conversions_model = {} # Conversions conversions_model['pdf'] = pdf_settings_model conversions_model['word'] = word_settings_model conversions_model['html'] = html_settings_model @@ -8949,12 +9338,12 @@ def test_list_configurations_response_serialization(self): conversions_model['json_normalizations'] = [normalization_operation_model] conversions_model['image_text_recognition'] = True - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords nlu_enrichment_keywords_model['sentiment'] = True nlu_enrichment_keywords_model['emotion'] = True nlu_enrichment_keywords_model['limit'] = 38 - nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model = {} # NluEnrichmentEntities nlu_enrichment_entities_model['sentiment'] = True nlu_enrichment_entities_model['emotion'] = True nlu_enrichment_entities_model['limit'] = 38 @@ -8963,41 +9352,41 @@ def test_list_configurations_response_serialization(self): nlu_enrichment_entities_model['sentence_locations'] = True nlu_enrichment_entities_model['model'] = 'testString' - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment nlu_enrichment_sentiment_model['document'] = True nlu_enrichment_sentiment_model['targets'] = ['testString'] - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion nlu_enrichment_emotion_model['document'] = True nlu_enrichment_emotion_model['targets'] = ['testString'] - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles nlu_enrichment_semantic_roles_model['entities'] = True nlu_enrichment_semantic_roles_model['keywords'] = True nlu_enrichment_semantic_roles_model['limit'] = 38 - nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model = {} # NluEnrichmentRelations nlu_enrichment_relations_model['model'] = 'testString' - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts nlu_enrichment_concepts_model['limit'] = 38 - nlu_enrichment_features_model = {} # NluEnrichmentFeatures + nlu_enrichment_features_model = {} # NluEnrichmentFeatures nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['features'] = nlu_enrichment_features_model enrichment_options_model['language'] = 'ar' enrichment_options_model['model'] = 'testString' - enrichment_model = {} # Enrichment + enrichment_model = {} # Enrichment enrichment_model['description'] = 'testString' enrichment_model['destination_field'] = 'testString' enrichment_model['source_field'] = 'testString' @@ -9006,39 +9395,39 @@ def test_list_configurations_response_serialization(self): enrichment_model['ignore_downstream_errors'] = False enrichment_model['options'] = enrichment_options_model - source_schedule_model = {} # SourceSchedule + source_schedule_model = {} # SourceSchedule source_schedule_model['enabled'] = True source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'daily' - source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model = {} # SourceOptionsFolder source_options_folder_model['owner_user_id'] = 'testString' source_options_folder_model['folder_id'] = 'testString' source_options_folder_model['limit'] = 38 - source_options_object_model = {} # SourceOptionsObject + source_options_object_model = {} # SourceOptionsObject source_options_object_model['name'] = 'testString' source_options_object_model['limit'] = 38 - source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model = {} # SourceOptionsSiteColl source_options_site_coll_model['site_collection_path'] = 'testString' source_options_site_coll_model['limit'] = 38 - source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] - source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model = {} # SourceOptionsBuckets source_options_buckets_model['name'] = 'testString' source_options_buckets_model['limit'] = 38 - source_options_model = {} # SourceOptions + source_options_model = {} # SourceOptions source_options_model['folders'] = [source_options_folder_model] source_options_model['objects'] = [source_options_object_model] source_options_model['site_collections'] = [source_options_site_coll_model] @@ -9046,13 +9435,13 @@ def test_list_configurations_response_serialization(self): source_options_model['buckets'] = [source_options_buckets_model] source_options_model['crawl_all_buckets'] = True - source_model = {} # Source + source_model = {} # Source source_model['type'] = 'box' source_model['credential_id'] = 'testString' source_model['schedule'] = source_schedule_model source_model['options'] = source_options_model - configuration_model = {} # Configuration + configuration_model = {} # Configuration configuration_model['name'] = 'testString' configuration_model['description'] = 'testString' configuration_model['conversions'] = conversions_model @@ -9079,7 +9468,8 @@ def test_list_configurations_response_serialization(self): list_configurations_response_model_json2 = list_configurations_response_model.to_dict() assert list_configurations_response_model_json2 == list_configurations_response_model_json -class TestModel_ListEnvironmentsResponse(): + +class TestModel_ListEnvironmentsResponse: """ Test Class for ListEnvironmentsResponse """ @@ -9091,24 +9481,24 @@ def test_list_environments_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - environment_documents_model = {} # EnvironmentDocuments + environment_documents_model = {} # EnvironmentDocuments - disk_usage_model = {} # DiskUsage + disk_usage_model = {} # DiskUsage - collection_usage_model = {} # CollectionUsage + collection_usage_model = {} # CollectionUsage - index_capacity_model = {} # IndexCapacity + index_capacity_model = {} # IndexCapacity index_capacity_model['documents'] = environment_documents_model index_capacity_model['disk_usage'] = disk_usage_model index_capacity_model['collections'] = collection_usage_model - search_status_model = {} # SearchStatus + search_status_model = {} # SearchStatus search_status_model['scope'] = 'testString' search_status_model['status'] = 'NO_DATA' search_status_model['status_description'] = 'testString' search_status_model['last_trained'] = '2019-01-01' - environment_model = {} # Environment + environment_model = {} # Environment environment_model['name'] = 'byod_environment' environment_model['description'] = 'Private Data Environment' environment_model['size'] = 'LT' @@ -9135,7 +9525,8 @@ def test_list_environments_response_serialization(self): list_environments_response_model_json2 = list_environments_response_model.to_dict() assert list_environments_response_model_json2 == list_environments_response_model_json -class TestModel_LogQueryResponse(): + +class TestModel_LogQueryResponse: """ Test Class for LogQueryResponse """ @@ -9147,18 +9538,18 @@ def test_log_query_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult + log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult log_query_response_result_documents_result_model['position'] = 38 log_query_response_result_documents_result_model['document_id'] = 'testString' log_query_response_result_documents_result_model['score'] = 72.5 log_query_response_result_documents_result_model['confidence'] = 72.5 log_query_response_result_documents_result_model['collection_id'] = 'testString' - log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments + log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments log_query_response_result_documents_model['results'] = [log_query_response_result_documents_result_model] log_query_response_result_documents_model['count'] = 38 - log_query_response_result_model = {} # LogQueryResponseResult + log_query_response_result_model = {} # LogQueryResponseResult log_query_response_result_model['environment_id'] = 'testString' log_query_response_result_model['customer_id'] = 'testString' log_query_response_result_model['document_type'] = 'query' @@ -9194,7 +9585,8 @@ def test_log_query_response_serialization(self): log_query_response_model_json2 = log_query_response_model.to_dict() assert log_query_response_model_json2 == log_query_response_model_json -class TestModel_LogQueryResponseResult(): + +class TestModel_LogQueryResponseResult: """ Test Class for LogQueryResponseResult """ @@ -9206,14 +9598,14 @@ def test_log_query_response_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult + log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult log_query_response_result_documents_result_model['position'] = 38 log_query_response_result_documents_result_model['document_id'] = 'testString' log_query_response_result_documents_result_model['score'] = 72.5 log_query_response_result_documents_result_model['confidence'] = 72.5 log_query_response_result_documents_result_model['collection_id'] = 'testString' - log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments + log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments log_query_response_result_documents_model['results'] = [log_query_response_result_documents_result_model] log_query_response_result_documents_model['count'] = 38 @@ -9249,7 +9641,8 @@ def test_log_query_response_result_serialization(self): log_query_response_result_model_json2 = log_query_response_result_model.to_dict() assert log_query_response_result_model_json2 == log_query_response_result_model_json -class TestModel_LogQueryResponseResultDocuments(): + +class TestModel_LogQueryResponseResultDocuments: """ Test Class for LogQueryResponseResultDocuments """ @@ -9261,7 +9654,7 @@ def test_log_query_response_result_documents_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult + log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult log_query_response_result_documents_result_model['position'] = 38 log_query_response_result_documents_result_model['document_id'] = 'testString' log_query_response_result_documents_result_model['score'] = 72.5 @@ -9288,7 +9681,8 @@ def test_log_query_response_result_documents_serialization(self): log_query_response_result_documents_model_json2 = log_query_response_result_documents_model.to_dict() assert log_query_response_result_documents_model_json2 == log_query_response_result_documents_model_json -class TestModel_LogQueryResponseResultDocumentsResult(): + +class TestModel_LogQueryResponseResultDocumentsResult: """ Test Class for LogQueryResponseResultDocumentsResult """ @@ -9321,7 +9715,8 @@ def test_log_query_response_result_documents_result_serialization(self): log_query_response_result_documents_result_model_json2 = log_query_response_result_documents_result_model.to_dict() assert log_query_response_result_documents_result_model_json2 == log_query_response_result_documents_result_model_json -class TestModel_MetricAggregation(): + +class TestModel_MetricAggregation: """ Test Class for MetricAggregation """ @@ -9333,7 +9728,7 @@ def test_metric_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - metric_aggregation_result_model = {} # MetricAggregationResult + metric_aggregation_result_model = {} # MetricAggregationResult metric_aggregation_result_model['key_as_string'] = '2019-01-01T12:00:00Z' metric_aggregation_result_model['key'] = 26 metric_aggregation_result_model['matching_results'] = 38 @@ -9360,7 +9755,8 @@ def test_metric_aggregation_serialization(self): metric_aggregation_model_json2 = metric_aggregation_model.to_dict() assert metric_aggregation_model_json2 == metric_aggregation_model_json -class TestModel_MetricAggregationResult(): + +class TestModel_MetricAggregationResult: """ Test Class for MetricAggregationResult """ @@ -9392,7 +9788,8 @@ def test_metric_aggregation_result_serialization(self): metric_aggregation_result_model_json2 = metric_aggregation_result_model.to_dict() assert metric_aggregation_result_model_json2 == metric_aggregation_result_model_json -class TestModel_MetricResponse(): + +class TestModel_MetricResponse: """ Test Class for MetricResponse """ @@ -9404,13 +9801,13 @@ def test_metric_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - metric_aggregation_result_model = {} # MetricAggregationResult + metric_aggregation_result_model = {} # MetricAggregationResult metric_aggregation_result_model['key_as_string'] = '2019-01-01T12:00:00Z' metric_aggregation_result_model['key'] = 26 metric_aggregation_result_model['matching_results'] = 38 metric_aggregation_result_model['event_rate'] = 72.5 - metric_aggregation_model = {} # MetricAggregation + metric_aggregation_model = {} # MetricAggregation metric_aggregation_model['interval'] = 'testString' metric_aggregation_model['event_type'] = 'testString' metric_aggregation_model['results'] = [metric_aggregation_result_model] @@ -9434,7 +9831,8 @@ def test_metric_response_serialization(self): metric_response_model_json2 = metric_response_model.to_dict() assert metric_response_model_json2 == metric_response_model_json -class TestModel_MetricTokenAggregation(): + +class TestModel_MetricTokenAggregation: """ Test Class for MetricTokenAggregation """ @@ -9446,7 +9844,7 @@ def test_metric_token_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - metric_token_aggregation_result_model = {} # MetricTokenAggregationResult + metric_token_aggregation_result_model = {} # MetricTokenAggregationResult metric_token_aggregation_result_model['key'] = 'testString' metric_token_aggregation_result_model['matching_results'] = 38 metric_token_aggregation_result_model['event_rate'] = 72.5 @@ -9471,7 +9869,8 @@ def test_metric_token_aggregation_serialization(self): metric_token_aggregation_model_json2 = metric_token_aggregation_model.to_dict() assert metric_token_aggregation_model_json2 == metric_token_aggregation_model_json -class TestModel_MetricTokenAggregationResult(): + +class TestModel_MetricTokenAggregationResult: """ Test Class for MetricTokenAggregationResult """ @@ -9502,7 +9901,8 @@ def test_metric_token_aggregation_result_serialization(self): metric_token_aggregation_result_model_json2 = metric_token_aggregation_result_model.to_dict() assert metric_token_aggregation_result_model_json2 == metric_token_aggregation_result_model_json -class TestModel_MetricTokenResponse(): + +class TestModel_MetricTokenResponse: """ Test Class for MetricTokenResponse """ @@ -9514,12 +9914,12 @@ def test_metric_token_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - metric_token_aggregation_result_model = {} # MetricTokenAggregationResult + metric_token_aggregation_result_model = {} # MetricTokenAggregationResult metric_token_aggregation_result_model['key'] = 'testString' metric_token_aggregation_result_model['matching_results'] = 38 metric_token_aggregation_result_model['event_rate'] = 72.5 - metric_token_aggregation_model = {} # MetricTokenAggregation + metric_token_aggregation_model = {} # MetricTokenAggregation metric_token_aggregation_model['event_type'] = 'testString' metric_token_aggregation_model['results'] = [metric_token_aggregation_result_model] @@ -9542,7 +9942,8 @@ def test_metric_token_response_serialization(self): metric_token_response_model_json2 = metric_token_response_model.to_dict() assert metric_token_response_model_json2 == metric_token_response_model_json -class TestModel_NluEnrichmentConcepts(): + +class TestModel_NluEnrichmentConcepts: """ Test Class for NluEnrichmentConcepts """ @@ -9571,7 +9972,8 @@ def test_nlu_enrichment_concepts_serialization(self): nlu_enrichment_concepts_model_json2 = nlu_enrichment_concepts_model.to_dict() assert nlu_enrichment_concepts_model_json2 == nlu_enrichment_concepts_model_json -class TestModel_NluEnrichmentEmotion(): + +class TestModel_NluEnrichmentEmotion: """ Test Class for NluEnrichmentEmotion """ @@ -9601,7 +10003,8 @@ def test_nlu_enrichment_emotion_serialization(self): nlu_enrichment_emotion_model_json2 = nlu_enrichment_emotion_model.to_dict() assert nlu_enrichment_emotion_model_json2 == nlu_enrichment_emotion_model_json -class TestModel_NluEnrichmentEntities(): + +class TestModel_NluEnrichmentEntities: """ Test Class for NluEnrichmentEntities """ @@ -9636,7 +10039,8 @@ def test_nlu_enrichment_entities_serialization(self): nlu_enrichment_entities_model_json2 = nlu_enrichment_entities_model.to_dict() assert nlu_enrichment_entities_model_json2 == nlu_enrichment_entities_model_json -class TestModel_NluEnrichmentFeatures(): + +class TestModel_NluEnrichmentFeatures: """ Test Class for NluEnrichmentFeatures """ @@ -9648,12 +10052,12 @@ def test_nlu_enrichment_features_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords + nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords nlu_enrichment_keywords_model['sentiment'] = True nlu_enrichment_keywords_model['emotion'] = True nlu_enrichment_keywords_model['limit'] = 38 - nlu_enrichment_entities_model = {} # NluEnrichmentEntities + nlu_enrichment_entities_model = {} # NluEnrichmentEntities nlu_enrichment_entities_model['sentiment'] = True nlu_enrichment_entities_model['emotion'] = True nlu_enrichment_entities_model['limit'] = 38 @@ -9662,23 +10066,23 @@ def test_nlu_enrichment_features_serialization(self): nlu_enrichment_entities_model['sentence_locations'] = True nlu_enrichment_entities_model['model'] = 'testString' - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment + nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment nlu_enrichment_sentiment_model['document'] = True nlu_enrichment_sentiment_model['targets'] = ['testString'] - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion + nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion nlu_enrichment_emotion_model['document'] = True nlu_enrichment_emotion_model['targets'] = ['testString'] - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles + nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles nlu_enrichment_semantic_roles_model['entities'] = True nlu_enrichment_semantic_roles_model['keywords'] = True nlu_enrichment_semantic_roles_model['limit'] = 38 - nlu_enrichment_relations_model = {} # NluEnrichmentRelations + nlu_enrichment_relations_model = {} # NluEnrichmentRelations nlu_enrichment_relations_model['model'] = 'testString' - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts + nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts nlu_enrichment_concepts_model['limit'] = 38 # Construct a json representation of a NluEnrichmentFeatures model @@ -9687,7 +10091,7 @@ def test_nlu_enrichment_features_serialization(self): nlu_enrichment_features_model_json['entities'] = nlu_enrichment_entities_model nlu_enrichment_features_model_json['sentiment'] = nlu_enrichment_sentiment_model nlu_enrichment_features_model_json['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model_json['categories'] = {'foo': 'bar'} + nlu_enrichment_features_model_json['categories'] = {'anyKey': 'anyValue'} nlu_enrichment_features_model_json['semantic_roles'] = nlu_enrichment_semantic_roles_model nlu_enrichment_features_model_json['relations'] = nlu_enrichment_relations_model nlu_enrichment_features_model_json['concepts'] = nlu_enrichment_concepts_model @@ -9707,7 +10111,8 @@ def test_nlu_enrichment_features_serialization(self): nlu_enrichment_features_model_json2 = nlu_enrichment_features_model.to_dict() assert nlu_enrichment_features_model_json2 == nlu_enrichment_features_model_json -class TestModel_NluEnrichmentKeywords(): + +class TestModel_NluEnrichmentKeywords: """ Test Class for NluEnrichmentKeywords """ @@ -9738,7 +10143,8 @@ def test_nlu_enrichment_keywords_serialization(self): nlu_enrichment_keywords_model_json2 = nlu_enrichment_keywords_model.to_dict() assert nlu_enrichment_keywords_model_json2 == nlu_enrichment_keywords_model_json -class TestModel_NluEnrichmentRelations(): + +class TestModel_NluEnrichmentRelations: """ Test Class for NluEnrichmentRelations """ @@ -9767,7 +10173,8 @@ def test_nlu_enrichment_relations_serialization(self): nlu_enrichment_relations_model_json2 = nlu_enrichment_relations_model.to_dict() assert nlu_enrichment_relations_model_json2 == nlu_enrichment_relations_model_json -class TestModel_NluEnrichmentSemanticRoles(): + +class TestModel_NluEnrichmentSemanticRoles: """ Test Class for NluEnrichmentSemanticRoles """ @@ -9798,7 +10205,8 @@ def test_nlu_enrichment_semantic_roles_serialization(self): nlu_enrichment_semantic_roles_model_json2 = nlu_enrichment_semantic_roles_model.to_dict() assert nlu_enrichment_semantic_roles_model_json2 == nlu_enrichment_semantic_roles_model_json -class TestModel_NluEnrichmentSentiment(): + +class TestModel_NluEnrichmentSentiment: """ Test Class for NluEnrichmentSentiment """ @@ -9828,7 +10236,8 @@ def test_nlu_enrichment_sentiment_serialization(self): nlu_enrichment_sentiment_model_json2 = nlu_enrichment_sentiment_model.to_dict() assert nlu_enrichment_sentiment_model_json2 == nlu_enrichment_sentiment_model_json -class TestModel_NormalizationOperation(): + +class TestModel_NormalizationOperation: """ Test Class for NormalizationOperation """ @@ -9859,7 +10268,8 @@ def test_normalization_operation_serialization(self): normalization_operation_model_json2 = normalization_operation_model.to_dict() assert normalization_operation_model_json2 == normalization_operation_model_json -class TestModel_Notice(): + +class TestModel_Notice: """ Test Class for Notice """ @@ -9887,7 +10297,8 @@ def test_notice_serialization(self): notice_model_json2 = notice_model.to_dict() assert notice_model_json2 == notice_model_json -class TestModel_PdfHeadingDetection(): + +class TestModel_PdfHeadingDetection: """ Test Class for PdfHeadingDetection """ @@ -9899,7 +10310,7 @@ def test_pdf_heading_detection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -9926,7 +10337,8 @@ def test_pdf_heading_detection_serialization(self): pdf_heading_detection_model_json2 = pdf_heading_detection_model.to_dict() assert pdf_heading_detection_model_json2 == pdf_heading_detection_model_json -class TestModel_PdfSettings(): + +class TestModel_PdfSettings: """ Test Class for PdfSettings """ @@ -9938,7 +10350,7 @@ def test_pdf_settings_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -9946,7 +10358,7 @@ def test_pdf_settings_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - pdf_heading_detection_model = {} # PdfHeadingDetection + pdf_heading_detection_model = {} # PdfHeadingDetection pdf_heading_detection_model['fonts'] = [font_setting_model] # Construct a json representation of a PdfSettings model @@ -9968,7 +10380,8 @@ def test_pdf_settings_serialization(self): pdf_settings_model_json2 = pdf_settings_model.to_dict() assert pdf_settings_model_json2 == pdf_settings_model_json -class TestModel_QueryAggregation(): + +class TestModel_QueryAggregation: """ Test Class for QueryAggregation """ @@ -9997,7 +10410,8 @@ def test_query_aggregation_serialization(self): query_aggregation_model_json2 = query_aggregation_model.to_dict() assert query_aggregation_model_json2 == query_aggregation_model_json -class TestModel_QueryHistogramAggregationResult(): + +class TestModel_QueryHistogramAggregationResult: """ Test Class for QueryHistogramAggregationResult """ @@ -10009,7 +10423,7 @@ def test_query_histogram_aggregation_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' query_aggregation_model['match'] = 'testString' query_aggregation_model['matching_results'] = 26 @@ -10035,7 +10449,8 @@ def test_query_histogram_aggregation_result_serialization(self): query_histogram_aggregation_result_model_json2 = query_histogram_aggregation_result_model.to_dict() assert query_histogram_aggregation_result_model_json2 == query_histogram_aggregation_result_model_json -class TestModel_QueryNoticesResponse(): + +class TestModel_QueryNoticesResponse: """ Test Class for QueryNoticesResponse """ @@ -10047,15 +10462,15 @@ def test_query_notices_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['score'] = 72.5 query_result_metadata_model['confidence'] = 72.5 - notice_model = {} # Notice + notice_model = {} # Notice - query_notices_result_model = {} # QueryNoticesResult + query_notices_result_model = {} # QueryNoticesResult query_notices_result_model['id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' - query_notices_result_model['metadata'] = {'foo': 'bar'} + query_notices_result_model['metadata'] = {'anyKey': 'anyValue'} query_notices_result_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' query_notices_result_model['result_metadata'] = query_result_metadata_model query_notices_result_model['code'] = 200 @@ -10065,12 +10480,12 @@ def test_query_notices_response_serialization(self): query_notices_result_model['notices'] = [notice_model] query_notices_result_model['score'] = '1' - query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' query_aggregation_model['match'] = 'testString' query_aggregation_model['matching_results'] = 26 - query_passages_model = {} # QueryPassages + query_passages_model = {} # QueryPassages query_passages_model['document_id'] = 'testString' query_passages_model['passage_score'] = 72.5 query_passages_model['passage_text'] = 'testString' @@ -10101,7 +10516,8 @@ def test_query_notices_response_serialization(self): query_notices_response_model_json2 = query_notices_response_model.to_dict() assert query_notices_response_model_json2 == query_notices_response_model_json -class TestModel_QueryNoticesResult(): + +class TestModel_QueryNoticesResult: """ Test Class for QueryNoticesResult """ @@ -10113,16 +10529,16 @@ def test_query_notices_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['score'] = 72.5 query_result_metadata_model['confidence'] = 72.5 - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a QueryNoticesResult model query_notices_result_model_json = {} query_notices_result_model_json['id'] = 'testString' - query_notices_result_model_json['metadata'] = {'foo': 'bar'} + query_notices_result_model_json['metadata'] = {'anyKey': 'anyValue'} query_notices_result_model_json['collection_id'] = 'testString' query_notices_result_model_json['result_metadata'] = query_result_metadata_model query_notices_result_model_json['code'] = 38 @@ -10157,7 +10573,8 @@ def test_query_notices_result_serialization(self): actual_dict = query_notices_result_model.get_properties() assert actual_dict == expected_dict -class TestModel_QueryPassages(): + +class TestModel_QueryPassages: """ Test Class for QueryPassages """ @@ -10191,7 +10608,8 @@ def test_query_passages_serialization(self): query_passages_model_json2 = query_passages_model.to_dict() assert query_passages_model_json2 == query_passages_model_json -class TestModel_QueryResponse(): + +class TestModel_QueryResponse: """ Test Class for QueryResponse """ @@ -10203,23 +10621,23 @@ def test_query_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['score'] = 72.5 query_result_metadata_model['confidence'] = 72.5 - query_result_model = {} # QueryResult + query_result_model = {} # QueryResult query_result_model['id'] = 'watson-generated ID' - query_result_model['metadata'] = {'foo': 'bar'} + query_result_model['metadata'] = {'anyKey': 'anyValue'} query_result_model['collection_id'] = 'testString' query_result_model['result_metadata'] = query_result_metadata_model query_result_model['score'] = '1' - query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' query_aggregation_model['match'] = 'testString' query_aggregation_model['matching_results'] = 26 - query_passages_model = {} # QueryPassages + query_passages_model = {} # QueryPassages query_passages_model['document_id'] = 'testString' query_passages_model['passage_score'] = 72.5 query_passages_model['passage_text'] = 'testString' @@ -10227,7 +10645,7 @@ def test_query_response_serialization(self): query_passages_model['end_offset'] = 38 query_passages_model['field'] = 'testString' - retrieval_details_model = {} # RetrievalDetails + retrieval_details_model = {} # RetrievalDetails retrieval_details_model['document_retrieval_strategy'] = 'untrained' # Construct a json representation of a QueryResponse model @@ -10256,7 +10674,8 @@ def test_query_response_serialization(self): query_response_model_json2 = query_response_model.to_dict() assert query_response_model_json2 == query_response_model_json -class TestModel_QueryResult(): + +class TestModel_QueryResult: """ Test Class for QueryResult """ @@ -10268,14 +10687,14 @@ def test_query_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['score'] = 72.5 query_result_metadata_model['confidence'] = 72.5 # Construct a json representation of a QueryResult model query_result_model_json = {} query_result_model_json['id'] = 'testString' - query_result_model_json['metadata'] = {'foo': 'bar'} + query_result_model_json['metadata'] = {'anyKey': 'anyValue'} query_result_model_json['collection_id'] = 'testString' query_result_model_json['result_metadata'] = query_result_metadata_model query_result_model_json['foo'] = 'testString' @@ -10305,7 +10724,8 @@ def test_query_result_serialization(self): actual_dict = query_result_model.get_properties() assert actual_dict == expected_dict -class TestModel_QueryResultMetadata(): + +class TestModel_QueryResultMetadata: """ Test Class for QueryResultMetadata """ @@ -10335,7 +10755,8 @@ def test_query_result_metadata_serialization(self): query_result_metadata_model_json2 = query_result_metadata_model.to_dict() assert query_result_metadata_model_json2 == query_result_metadata_model_json -class TestModel_QueryTermAggregationResult(): + +class TestModel_QueryTermAggregationResult: """ Test Class for QueryTermAggregationResult """ @@ -10347,7 +10768,7 @@ def test_query_term_aggregation_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' query_aggregation_model['match'] = 'testString' query_aggregation_model['matching_results'] = 26 @@ -10376,7 +10797,8 @@ def test_query_term_aggregation_result_serialization(self): query_term_aggregation_result_model_json2 = query_term_aggregation_result_model.to_dict() assert query_term_aggregation_result_model_json2 == query_term_aggregation_result_model_json -class TestModel_QueryTimesliceAggregationResult(): + +class TestModel_QueryTimesliceAggregationResult: """ Test Class for QueryTimesliceAggregationResult """ @@ -10388,7 +10810,7 @@ def test_query_timeslice_aggregation_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_aggregation_model = {} # QueryFilterAggregation + query_aggregation_model = {} # QueryFilterAggregation query_aggregation_model['type'] = 'filter' query_aggregation_model['match'] = 'testString' query_aggregation_model['matching_results'] = 26 @@ -10415,7 +10837,8 @@ def test_query_timeslice_aggregation_result_serialization(self): query_timeslice_aggregation_result_model_json2 = query_timeslice_aggregation_result_model.to_dict() assert query_timeslice_aggregation_result_model_json2 == query_timeslice_aggregation_result_model_json -class TestModel_QueryTopHitsAggregationResult(): + +class TestModel_QueryTopHitsAggregationResult: """ Test Class for QueryTopHitsAggregationResult """ @@ -10428,7 +10851,7 @@ def test_query_top_hits_aggregation_result_serialization(self): # Construct a json representation of a QueryTopHitsAggregationResult model query_top_hits_aggregation_result_model_json = {} query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{'foo': 'bar'}] + query_top_hits_aggregation_result_model_json['hits'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) @@ -10445,7 +10868,8 @@ def test_query_top_hits_aggregation_result_serialization(self): query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json -class TestModel_RetrievalDetails(): + +class TestModel_RetrievalDetails: """ Test Class for RetrievalDetails """ @@ -10474,7 +10898,8 @@ def test_retrieval_details_serialization(self): retrieval_details_model_json2 = retrieval_details_model.to_dict() assert retrieval_details_model_json2 == retrieval_details_model_json -class TestModel_SduStatus(): + +class TestModel_SduStatus: """ Test Class for SduStatus """ @@ -10486,7 +10911,7 @@ def test_sdu_status_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - sdu_status_custom_fields_model = {} # SduStatusCustomFields + sdu_status_custom_fields_model = {} # SduStatusCustomFields sdu_status_custom_fields_model['defined'] = 26 sdu_status_custom_fields_model['maximum_allowed'] = 26 @@ -10513,7 +10938,8 @@ def test_sdu_status_serialization(self): sdu_status_model_json2 = sdu_status_model.to_dict() assert sdu_status_model_json2 == sdu_status_model_json -class TestModel_SduStatusCustomFields(): + +class TestModel_SduStatusCustomFields: """ Test Class for SduStatusCustomFields """ @@ -10543,7 +10969,8 @@ def test_sdu_status_custom_fields_serialization(self): sdu_status_custom_fields_model_json2 = sdu_status_custom_fields_model.to_dict() assert sdu_status_custom_fields_model_json2 == sdu_status_custom_fields_model_json -class TestModel_SearchStatus(): + +class TestModel_SearchStatus: """ Test Class for SearchStatus """ @@ -10575,7 +11002,8 @@ def test_search_status_serialization(self): search_status_model_json2 = search_status_model.to_dict() assert search_status_model_json2 == search_status_model_json -class TestModel_SegmentSettings(): + +class TestModel_SegmentSettings: """ Test Class for SegmentSettings """ @@ -10606,7 +11034,8 @@ def test_segment_settings_serialization(self): segment_settings_model_json2 = segment_settings_model.to_dict() assert segment_settings_model_json2 == segment_settings_model_json -class TestModel_Source(): + +class TestModel_Source: """ Test Class for Source """ @@ -10618,39 +11047,39 @@ def test_source_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - source_schedule_model = {} # SourceSchedule + source_schedule_model = {} # SourceSchedule source_schedule_model['enabled'] = True source_schedule_model['time_zone'] = 'America/New_York' source_schedule_model['frequency'] = 'daily' - source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model = {} # SourceOptionsFolder source_options_folder_model['owner_user_id'] = 'testString' source_options_folder_model['folder_id'] = 'testString' source_options_folder_model['limit'] = 38 - source_options_object_model = {} # SourceOptionsObject + source_options_object_model = {} # SourceOptionsObject source_options_object_model['name'] = 'testString' source_options_object_model['limit'] = 38 - source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model = {} # SourceOptionsSiteColl source_options_site_coll_model['site_collection_path'] = 'testString' source_options_site_coll_model['limit'] = 38 - source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] - source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model = {} # SourceOptionsBuckets source_options_buckets_model['name'] = 'testString' source_options_buckets_model['limit'] = 38 - source_options_model = {} # SourceOptions + source_options_model = {} # SourceOptions source_options_model['folders'] = [source_options_folder_model] source_options_model['objects'] = [source_options_object_model] source_options_model['site_collections'] = [source_options_site_coll_model] @@ -10680,7 +11109,8 @@ def test_source_serialization(self): source_model_json2 = source_model.to_dict() assert source_model_json2 == source_model_json -class TestModel_SourceOptions(): + +class TestModel_SourceOptions: """ Test Class for SourceOptions """ @@ -10692,30 +11122,30 @@ def test_source_options_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - source_options_folder_model = {} # SourceOptionsFolder + source_options_folder_model = {} # SourceOptionsFolder source_options_folder_model['owner_user_id'] = 'testString' source_options_folder_model['folder_id'] = 'testString' source_options_folder_model['limit'] = 38 - source_options_object_model = {} # SourceOptionsObject + source_options_object_model = {} # SourceOptionsObject source_options_object_model['name'] = 'testString' source_options_object_model['limit'] = 38 - source_options_site_coll_model = {} # SourceOptionsSiteColl + source_options_site_coll_model = {} # SourceOptionsSiteColl source_options_site_coll_model['site_collection_path'] = 'testString' source_options_site_coll_model['limit'] = 38 - source_options_web_crawl_model = {} # SourceOptionsWebCrawl + source_options_web_crawl_model = {} # SourceOptionsWebCrawl source_options_web_crawl_model['url'] = 'testString' source_options_web_crawl_model['limit_to_starting_hosts'] = True source_options_web_crawl_model['crawl_speed'] = 'normal' source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 38 - source_options_web_crawl_model['request_timeout'] = 38 + source_options_web_crawl_model['maximum_hops'] = 2 + source_options_web_crawl_model['request_timeout'] = 30000 source_options_web_crawl_model['override_robots_txt'] = False source_options_web_crawl_model['blacklist'] = ['testString'] - source_options_buckets_model = {} # SourceOptionsBuckets + source_options_buckets_model = {} # SourceOptionsBuckets source_options_buckets_model['name'] = 'testString' source_options_buckets_model['limit'] = 38 @@ -10743,7 +11173,8 @@ def test_source_options_serialization(self): source_options_model_json2 = source_options_model.to_dict() assert source_options_model_json2 == source_options_model_json -class TestModel_SourceOptionsBuckets(): + +class TestModel_SourceOptionsBuckets: """ Test Class for SourceOptionsBuckets """ @@ -10773,7 +11204,8 @@ def test_source_options_buckets_serialization(self): source_options_buckets_model_json2 = source_options_buckets_model.to_dict() assert source_options_buckets_model_json2 == source_options_buckets_model_json -class TestModel_SourceOptionsFolder(): + +class TestModel_SourceOptionsFolder: """ Test Class for SourceOptionsFolder """ @@ -10804,7 +11236,8 @@ def test_source_options_folder_serialization(self): source_options_folder_model_json2 = source_options_folder_model.to_dict() assert source_options_folder_model_json2 == source_options_folder_model_json -class TestModel_SourceOptionsObject(): + +class TestModel_SourceOptionsObject: """ Test Class for SourceOptionsObject """ @@ -10834,7 +11267,8 @@ def test_source_options_object_serialization(self): source_options_object_model_json2 = source_options_object_model.to_dict() assert source_options_object_model_json2 == source_options_object_model_json -class TestModel_SourceOptionsSiteColl(): + +class TestModel_SourceOptionsSiteColl: """ Test Class for SourceOptionsSiteColl """ @@ -10864,7 +11298,8 @@ def test_source_options_site_coll_serialization(self): source_options_site_coll_model_json2 = source_options_site_coll_model.to_dict() assert source_options_site_coll_model_json2 == source_options_site_coll_model_json -class TestModel_SourceOptionsWebCrawl(): + +class TestModel_SourceOptionsWebCrawl: """ Test Class for SourceOptionsWebCrawl """ @@ -10880,8 +11315,8 @@ def test_source_options_web_crawl_serialization(self): source_options_web_crawl_model_json['limit_to_starting_hosts'] = True source_options_web_crawl_model_json['crawl_speed'] = 'normal' source_options_web_crawl_model_json['allow_untrusted_certificate'] = False - source_options_web_crawl_model_json['maximum_hops'] = 38 - source_options_web_crawl_model_json['request_timeout'] = 38 + source_options_web_crawl_model_json['maximum_hops'] = 2 + source_options_web_crawl_model_json['request_timeout'] = 30000 source_options_web_crawl_model_json['override_robots_txt'] = False source_options_web_crawl_model_json['blacklist'] = ['testString'] @@ -10900,7 +11335,8 @@ def test_source_options_web_crawl_serialization(self): source_options_web_crawl_model_json2 = source_options_web_crawl_model.to_dict() assert source_options_web_crawl_model_json2 == source_options_web_crawl_model_json -class TestModel_SourceSchedule(): + +class TestModel_SourceSchedule: """ Test Class for SourceSchedule """ @@ -10931,7 +11367,8 @@ def test_source_schedule_serialization(self): source_schedule_model_json2 = source_schedule_model.to_dict() assert source_schedule_model_json2 == source_schedule_model_json -class TestModel_SourceStatus(): + +class TestModel_SourceStatus: """ Test Class for SourceStatus """ @@ -10961,7 +11398,8 @@ def test_source_status_serialization(self): source_status_model_json2 = source_status_model.to_dict() assert source_status_model_json2 == source_status_model_json -class TestModel_StatusDetails(): + +class TestModel_StatusDetails: """ Test Class for StatusDetails """ @@ -10991,7 +11429,8 @@ def test_status_details_serialization(self): status_details_model_json2 = status_details_model.to_dict() assert status_details_model_json2 == status_details_model_json -class TestModel_TokenDictRule(): + +class TestModel_TokenDictRule: """ Test Class for TokenDictRule """ @@ -11023,7 +11462,8 @@ def test_token_dict_rule_serialization(self): token_dict_rule_model_json2 = token_dict_rule_model.to_dict() assert token_dict_rule_model_json2 == token_dict_rule_model_json -class TestModel_TokenDictStatusResponse(): + +class TestModel_TokenDictStatusResponse: """ Test Class for TokenDictStatusResponse """ @@ -11053,7 +11493,8 @@ def test_token_dict_status_response_serialization(self): token_dict_status_response_model_json2 = token_dict_status_response_model.to_dict() assert token_dict_status_response_model_json2 == token_dict_status_response_model_json -class TestModel_TrainingDataSet(): + +class TestModel_TrainingDataSet: """ Test Class for TrainingDataSet """ @@ -11065,12 +11506,12 @@ def test_training_data_set_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_example_model = {} # TrainingExample + training_example_model = {} # TrainingExample training_example_model['document_id'] = 'testString' training_example_model['cross_reference'] = 'testString' training_example_model['relevance'] = 38 - training_query_model = {} # TrainingQuery + training_query_model = {} # TrainingQuery training_query_model['query_id'] = 'testString' training_query_model['natural_language_query'] = 'testString' training_query_model['filter'] = 'testString' @@ -11097,7 +11538,8 @@ def test_training_data_set_serialization(self): training_data_set_model_json2 = training_data_set_model.to_dict() assert training_data_set_model_json2 == training_data_set_model_json -class TestModel_TrainingExample(): + +class TestModel_TrainingExample: """ Test Class for TrainingExample """ @@ -11128,7 +11570,8 @@ def test_training_example_serialization(self): training_example_model_json2 = training_example_model.to_dict() assert training_example_model_json2 == training_example_model_json -class TestModel_TrainingExampleList(): + +class TestModel_TrainingExampleList: """ Test Class for TrainingExampleList """ @@ -11140,7 +11583,7 @@ def test_training_example_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_example_model = {} # TrainingExample + training_example_model = {} # TrainingExample training_example_model['document_id'] = 'testString' training_example_model['cross_reference'] = 'testString' training_example_model['relevance'] = 38 @@ -11164,7 +11607,8 @@ def test_training_example_list_serialization(self): training_example_list_model_json2 = training_example_list_model.to_dict() assert training_example_list_model_json2 == training_example_list_model_json -class TestModel_TrainingQuery(): + +class TestModel_TrainingQuery: """ Test Class for TrainingQuery """ @@ -11176,7 +11620,7 @@ def test_training_query_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_example_model = {} # TrainingExample + training_example_model = {} # TrainingExample training_example_model['document_id'] = 'testString' training_example_model['cross_reference'] = 'testString' training_example_model['relevance'] = 38 @@ -11203,7 +11647,8 @@ def test_training_query_serialization(self): training_query_model_json2 = training_query_model.to_dict() assert training_query_model_json2 == training_query_model_json -class TestModel_TrainingStatus(): + +class TestModel_TrainingStatus: """ Test Class for TrainingStatus """ @@ -11240,7 +11685,8 @@ def test_training_status_serialization(self): training_status_model_json2 = training_status_model.to_dict() assert training_status_model_json2 == training_status_model_json -class TestModel_WordHeadingDetection(): + +class TestModel_WordHeadingDetection: """ Test Class for WordHeadingDetection """ @@ -11252,7 +11698,7 @@ def test_word_heading_detection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -11260,7 +11706,7 @@ def test_word_heading_detection_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - word_style_model = {} # WordStyle + word_style_model = {} # WordStyle word_style_model['level'] = 38 word_style_model['names'] = ['testString'] @@ -11284,7 +11730,8 @@ def test_word_heading_detection_serialization(self): word_heading_detection_model_json2 = word_heading_detection_model.to_dict() assert word_heading_detection_model_json2 == word_heading_detection_model_json -class TestModel_WordSettings(): + +class TestModel_WordSettings: """ Test Class for WordSettings """ @@ -11296,7 +11743,7 @@ def test_word_settings_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - font_setting_model = {} # FontSetting + font_setting_model = {} # FontSetting font_setting_model['level'] = 38 font_setting_model['min_size'] = 38 font_setting_model['max_size'] = 38 @@ -11304,11 +11751,11 @@ def test_word_settings_serialization(self): font_setting_model['italic'] = True font_setting_model['name'] = 'testString' - word_style_model = {} # WordStyle + word_style_model = {} # WordStyle word_style_model['level'] = 38 word_style_model['names'] = ['testString'] - word_heading_detection_model = {} # WordHeadingDetection + word_heading_detection_model = {} # WordHeadingDetection word_heading_detection_model['fonts'] = [font_setting_model] word_heading_detection_model['styles'] = [word_style_model] @@ -11331,7 +11778,8 @@ def test_word_settings_serialization(self): word_settings_model_json2 = word_settings_model.to_dict() assert word_settings_model_json2 == word_settings_model_json -class TestModel_WordStyle(): + +class TestModel_WordStyle: """ Test Class for WordStyle """ @@ -11361,7 +11809,8 @@ def test_word_style_serialization(self): word_style_model_json2 = word_style_model.to_dict() assert word_style_model_json2 == word_style_model_json -class TestModel_XPathPatterns(): + +class TestModel_XPathPatterns: """ Test Class for XPathPatterns """ @@ -11390,7 +11839,8 @@ def test_x_path_patterns_serialization(self): x_path_patterns_model_json2 = x_path_patterns_model.to_dict() assert x_path_patterns_model_json2 == x_path_patterns_model_json -class TestModel_QueryCalculationAggregation(): + +class TestModel_QueryCalculationAggregation: """ Test Class for QueryCalculationAggregation """ @@ -11421,7 +11871,8 @@ def test_query_calculation_aggregation_serialization(self): query_calculation_aggregation_model_json2 = query_calculation_aggregation_model.to_dict() assert query_calculation_aggregation_model_json2 == query_calculation_aggregation_model_json -class TestModel_QueryFilterAggregation(): + +class TestModel_QueryFilterAggregation: """ Test Class for QueryFilterAggregation """ @@ -11452,7 +11903,8 @@ def test_query_filter_aggregation_serialization(self): query_filter_aggregation_model_json2 = query_filter_aggregation_model.to_dict() assert query_filter_aggregation_model_json2 == query_filter_aggregation_model_json -class TestModel_QueryHistogramAggregation(): + +class TestModel_QueryHistogramAggregation: """ Test Class for QueryHistogramAggregation """ @@ -11484,7 +11936,8 @@ def test_query_histogram_aggregation_serialization(self): query_histogram_aggregation_model_json2 = query_histogram_aggregation_model.to_dict() assert query_histogram_aggregation_model_json2 == query_histogram_aggregation_model_json -class TestModel_QueryNestedAggregation(): + +class TestModel_QueryNestedAggregation: """ Test Class for QueryNestedAggregation """ @@ -11515,7 +11968,8 @@ def test_query_nested_aggregation_serialization(self): query_nested_aggregation_model_json2 = query_nested_aggregation_model.to_dict() assert query_nested_aggregation_model_json2 == query_nested_aggregation_model_json -class TestModel_QueryTermAggregation(): + +class TestModel_QueryTermAggregation: """ Test Class for QueryTermAggregation """ @@ -11547,7 +12001,8 @@ def test_query_term_aggregation_serialization(self): query_term_aggregation_model_json2 = query_term_aggregation_model.to_dict() assert query_term_aggregation_model_json2 == query_term_aggregation_model_json -class TestModel_QueryTimesliceAggregation(): + +class TestModel_QueryTimesliceAggregation: """ Test Class for QueryTimesliceAggregation """ @@ -11579,7 +12034,8 @@ def test_query_timeslice_aggregation_serialization(self): query_timeslice_aggregation_model_json2 = query_timeslice_aggregation_model.to_dict() assert query_timeslice_aggregation_model_json2 == query_timeslice_aggregation_model_json -class TestModel_QueryTopHitsAggregation(): + +class TestModel_QueryTopHitsAggregation: """ Test Class for QueryTopHitsAggregation """ @@ -11591,9 +12047,9 @@ def test_query_top_hits_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult + query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{'foo': 'bar'}] + query_top_hits_aggregation_result_model['hits'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryTopHitsAggregation model query_top_hits_aggregation_model_json = {} diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 08c84b145..c8098805a 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -64,8 +64,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -73,7 +72,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestListProjects(): + +class TestListProjects: """ Test Class for list_projects """ @@ -86,16 +86,17 @@ def test_list_projects_all_params(self): # Set up mock url = preprocess_url('/v2/projects') mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_projects() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -117,17 +118,19 @@ def test_list_projects_value_error(self): # Set up mock url = preprocess_url('/v2/projects') mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_projects(**req_copy) @@ -140,7 +143,8 @@ def test_list_projects_value_error_with_retries(self): _service.disable_retries() self.test_list_projects_value_error() -class TestCreateProject(): + +class TestCreateProject: """ Test Class for create_project """ @@ -152,12 +156,14 @@ def test_create_project_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DefaultQueryParamsPassages model default_query_params_passages_model = {} @@ -172,7 +178,7 @@ def test_create_project_all_params(self): default_query_params_table_results_model = {} default_query_params_table_results_model['enabled'] = True default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 + default_query_params_table_results_model['per_document'] = 0 # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model default_query_params_suggested_refinements_model = {} @@ -202,7 +208,7 @@ def test_create_project_all_params(self): name, type, default_query_parameters=default_query_parameters, - headers={} + headers={}, ) # Check for correct operation @@ -230,12 +236,14 @@ def test_create_project_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DefaultQueryParamsPassages model default_query_params_passages_model = {} @@ -250,7 +258,7 @@ def test_create_project_value_error(self): default_query_params_table_results_model = {} default_query_params_table_results_model['enabled'] = True default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 + default_query_params_table_results_model['per_document'] = 0 # Construct a dict representation of a DefaultQueryParamsSuggestedRefinements model default_query_params_suggested_refinements_model = {} @@ -281,7 +289,7 @@ def test_create_project_value_error(self): "type": type, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_project(**req_copy) @@ -294,7 +302,8 @@ def test_create_project_value_error_with_retries(self): _service.disable_retries() self.test_create_project_value_error() -class TestGetProject(): + +class TestGetProject: """ Test Class for get_project """ @@ -306,12 +315,14 @@ def test_get_project_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -319,7 +330,7 @@ def test_get_project_all_params(self): # Invoke method response = _service.get_project( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -342,12 +353,14 @@ def test_get_project_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -357,7 +370,7 @@ def test_get_project_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_project(**req_copy) @@ -370,7 +383,8 @@ def test_get_project_value_error_with_retries(self): _service.disable_retries() self.test_get_project_value_error() -class TestUpdateProject(): + +class TestUpdateProject: """ Test Class for update_project """ @@ -382,12 +396,14 @@ def test_update_project_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -397,7 +413,7 @@ def test_update_project_all_params(self): response = _service.update_project( project_id, name=name, - headers={} + headers={}, ) # Check for correct operation @@ -423,12 +439,14 @@ def test_update_project_required_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -436,7 +454,7 @@ def test_update_project_required_params(self): # Invoke method response = _service.update_project( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -459,12 +477,14 @@ def test_update_project_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 12}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -474,7 +494,7 @@ def test_update_project_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_project(**req_copy) @@ -487,7 +507,8 @@ def test_update_project_value_error_with_retries(self): _service.disable_retries() self.test_update_project_value_error() -class TestDeleteProject(): + +class TestDeleteProject: """ Test Class for delete_project """ @@ -499,9 +520,11 @@ def test_delete_project_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -509,7 +532,7 @@ def test_delete_project_all_params(self): # Invoke method response = _service.delete_project( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -532,9 +555,11 @@ def test_delete_project_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -544,7 +569,7 @@ def test_delete_project_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_project(**req_copy) @@ -557,7 +582,8 @@ def test_delete_project_value_error_with_retries(self): _service.disable_retries() self.test_delete_project_value_error() -class TestListFields(): + +class TestListFields: """ Test Class for list_fields """ @@ -570,11 +596,13 @@ def test_list_fields_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -584,14 +612,14 @@ def test_list_fields_all_params(self): response = _service.list_fields( project_id, collection_ids=collection_ids, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string @@ -612,11 +640,13 @@ def test_list_fields_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -624,7 +654,7 @@ def test_list_fields_required_params(self): # Invoke method response = _service.list_fields( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -648,11 +678,13 @@ def test_list_fields_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/fields') mock_response = '{"fields": [{"field": "field", "type": "nested", "collection_id": "collection_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -662,7 +694,7 @@ def test_list_fields_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_fields(**req_copy) @@ -675,6 +707,7 @@ def test_list_fields_value_error_with_retries(self): _service.disable_retries() self.test_list_fields_value_error() + # endregion ############################################################################## # End of Service: Projects @@ -685,7 +718,8 @@ def test_list_fields_value_error_with_retries(self): ############################################################################## # region -class TestListCollections(): + +class TestListCollections: """ Test Class for list_collections """ @@ -698,11 +732,13 @@ def test_list_collections_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -710,7 +746,7 @@ def test_list_collections_all_params(self): # Invoke method response = _service.list_collections( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -734,11 +770,13 @@ def test_list_collections_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections') mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -748,7 +786,7 @@ def test_list_collections_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_collections(**req_copy) @@ -761,7 +799,8 @@ def test_list_collections_value_error_with_retries(self): _service.disable_retries() self.test_list_collections_value_error() -class TestCreateCollection(): + +class TestCreateCollection: """ Test Class for create_collection """ @@ -774,11 +813,13 @@ def test_create_collection_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CollectionEnrichment model collection_enrichment_model = {} @@ -799,7 +840,7 @@ def test_create_collection_all_params(self): description=description, language=language, enrichments=enrichments, - headers={} + headers={}, ) # Check for correct operation @@ -829,11 +870,13 @@ def test_create_collection_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a CollectionEnrichment model collection_enrichment_model = {} @@ -853,7 +896,7 @@ def test_create_collection_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_collection(**req_copy) @@ -866,7 +909,8 @@ def test_create_collection_value_error_with_retries(self): _service.disable_retries() self.test_create_collection_value_error() -class TestGetCollection(): + +class TestGetCollection: """ Test Class for get_collection """ @@ -879,11 +923,13 @@ def test_get_collection_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -893,7 +939,7 @@ def test_get_collection_all_params(self): response = _service.get_collection( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -917,11 +963,13 @@ def test_get_collection_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -933,7 +981,7 @@ def test_get_collection_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_collection(**req_copy) @@ -946,7 +994,8 @@ def test_get_collection_value_error_with_retries(self): _service.disable_retries() self.test_get_collection_value_error() -class TestUpdateCollection(): + +class TestUpdateCollection: """ Test Class for update_collection """ @@ -959,11 +1008,13 @@ def test_update_collection_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CollectionEnrichment model collection_enrichment_model = {} @@ -984,7 +1035,7 @@ def test_update_collection_all_params(self): name=name, description=description, enrichments=enrichments, - headers={} + headers={}, ) # Check for correct operation @@ -1013,11 +1064,13 @@ def test_update_collection_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a CollectionEnrichment model collection_enrichment_model = {} @@ -1037,7 +1090,7 @@ def test_update_collection_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_collection(**req_copy) @@ -1050,7 +1103,8 @@ def test_update_collection_value_error_with_retries(self): _service.disable_retries() self.test_update_collection_value_error() -class TestDeleteCollection(): + +class TestDeleteCollection: """ Test Class for delete_collection """ @@ -1062,9 +1116,11 @@ def test_delete_collection_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -1074,7 +1130,7 @@ def test_delete_collection_all_params(self): response = _service.delete_collection( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -1097,9 +1153,11 @@ def test_delete_collection_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -1111,7 +1169,7 @@ def test_delete_collection_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_collection(**req_copy) @@ -1124,6 +1182,7 @@ def test_delete_collection_value_error_with_retries(self): _service.disable_retries() self.test_delete_collection_value_error() + # endregion ############################################################################## # End of Service: Collections @@ -1134,7 +1193,8 @@ def test_delete_collection_value_error_with_retries(self): ############################################################################## # region -class TestListDocuments(): + +class TestListDocuments: """ Test Class for list_documents """ @@ -1147,16 +1207,18 @@ def test_list_documents_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' collection_id = 'testString' - count = 38 + count = 1000 status = 'testString' has_notices = True is_parent = True @@ -1173,14 +1235,14 @@ def test_list_documents_all_params(self): is_parent=is_parent, parent_document_id=parent_document_id, sha256=sha256, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'count={}'.format(count) in query_string assert 'status={}'.format(status) in query_string @@ -1206,11 +1268,13 @@ def test_list_documents_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1220,7 +1284,7 @@ def test_list_documents_required_params(self): response = _service.list_documents( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -1244,11 +1308,13 @@ def test_list_documents_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"matching_results": 16, "documents": [{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1260,7 +1326,7 @@ def test_list_documents_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_documents(**req_copy) @@ -1273,7 +1339,8 @@ def test_list_documents_value_error_with_retries(self): _service.disable_retries() self.test_list_documents_value_error() -class TestAddDocument(): + +class TestAddDocument: """ Test Class for add_document """ @@ -1286,11 +1353,13 @@ def test_add_document_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1310,7 +1379,7 @@ def test_add_document_all_params(self): file_content_type=file_content_type, metadata=metadata, x_watson_discovery_force=x_watson_discovery_force, - headers={} + headers={}, ) # Check for correct operation @@ -1334,11 +1403,13 @@ def test_add_document_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1348,7 +1419,7 @@ def test_add_document_required_params(self): response = _service.add_document( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -1372,11 +1443,13 @@ def test_add_document_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1388,7 +1461,7 @@ def test_add_document_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_document(**req_copy) @@ -1401,7 +1474,8 @@ def test_add_document_value_error_with_retries(self): _service.disable_retries() self.test_add_document_value_error() -class TestGetDocument(): + +class TestGetDocument: """ Test Class for get_document """ @@ -1414,11 +1488,13 @@ def test_get_document_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1430,7 +1506,7 @@ def test_get_document_all_params(self): project_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1454,11 +1530,13 @@ def test_get_document_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "available", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "children": {"have_notices": true, "count": 5}, "filename": "filename", "file_type": "file_type", "sha256": "sha256"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1472,7 +1550,7 @@ def test_get_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document(**req_copy) @@ -1485,7 +1563,8 @@ def test_get_document_value_error_with_retries(self): _service.disable_retries() self.test_get_document_value_error() -class TestUpdateDocument(): + +class TestUpdateDocument: """ Test Class for update_document """ @@ -1498,11 +1577,13 @@ def test_update_document_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1524,7 +1605,7 @@ def test_update_document_all_params(self): file_content_type=file_content_type, metadata=metadata, x_watson_discovery_force=x_watson_discovery_force, - headers={} + headers={}, ) # Check for correct operation @@ -1548,11 +1629,13 @@ def test_update_document_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1564,7 +1647,7 @@ def test_update_document_required_params(self): project_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1588,11 +1671,13 @@ def test_update_document_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "processing"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values project_id = 'testString' @@ -1606,7 +1691,7 @@ def test_update_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_document(**req_copy) @@ -1619,7 +1704,8 @@ def test_update_document_value_error_with_retries(self): _service.disable_retries() self.test_update_document_value_error() -class TestDeleteDocument(): + +class TestDeleteDocument: """ Test Class for delete_document """ @@ -1632,11 +1718,13 @@ def test_delete_document_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1650,7 +1738,7 @@ def test_delete_document_all_params(self): collection_id, document_id, x_watson_discovery_force=x_watson_discovery_force, - headers={} + headers={}, ) # Check for correct operation @@ -1674,11 +1762,13 @@ def test_delete_document_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1690,7 +1780,7 @@ def test_delete_document_required_params(self): project_id, collection_id, document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1714,11 +1804,13 @@ def test_delete_document_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/documents/testString') mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1732,7 +1824,7 @@ def test_delete_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document(**req_copy) @@ -1745,6 +1837,7 @@ def test_delete_document_value_error_with_retries(self): _service.disable_retries() self.test_delete_document_value_error() + # endregion ############################################################################## # End of Service: Documents @@ -1755,7 +1848,8 @@ def test_delete_document_value_error_with_retries(self): ############################################################################## # region -class TestQuery(): + +class TestQuery: """ Test Class for query """ @@ -1768,11 +1862,13 @@ def test_query_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/query') mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a QueryLargeTableResults model query_large_table_results_model = {} @@ -1793,7 +1889,7 @@ def test_query_all_params(self): query_large_passages_model['count'] = 400 query_large_passages_model['characters'] = 50 query_large_passages_model['find_answers'] = False - query_large_passages_model['max_answers_per_passage'] = 38 + query_large_passages_model['max_answers_per_passage'] = 1 # Construct a dict representation of a QueryLargeSimilar model query_large_similar_model = {} @@ -1837,7 +1933,7 @@ def test_query_all_params(self): suggested_refinements=suggested_refinements, passages=passages, similar=similar, - headers={} + headers={}, ) # Check for correct operation @@ -1878,11 +1974,13 @@ def test_query_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/query') mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1890,7 +1988,7 @@ def test_query_required_params(self): # Invoke method response = _service.query( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -1914,11 +2012,13 @@ def test_query_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/query') mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -1928,7 +2028,7 @@ def test_query_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query(**req_copy) @@ -1941,7 +2041,8 @@ def test_query_value_error_with_retries(self): _service.disable_retries() self.test_query_value_error() -class TestGetAutocompletion(): + +class TestGetAutocompletion: """ Test Class for get_autocompletion """ @@ -1954,18 +2055,20 @@ def test_get_autocompletion_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' prefix = 'testString' collection_ids = ['testString'] field = 'testString' - count = 38 + count = 5 # Invoke method response = _service.get_autocompletion( @@ -1974,14 +2077,14 @@ def test_get_autocompletion_all_params(self): collection_ids=collection_ids, field=field, count=count, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'prefix={}'.format(prefix) in query_string assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string @@ -2005,11 +2108,13 @@ def test_get_autocompletion_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2019,14 +2124,14 @@ def test_get_autocompletion_required_params(self): response = _service.get_autocompletion( project_id, prefix, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'prefix={}'.format(prefix) in query_string @@ -2047,11 +2152,13 @@ def test_get_autocompletion_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/autocompletion') mock_response = '{"completions": ["completions"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2063,7 +2170,7 @@ def test_get_autocompletion_value_error(self): "prefix": prefix, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_autocompletion(**req_copy) @@ -2076,7 +2183,8 @@ def test_get_autocompletion_value_error_with_retries(self): _service.disable_retries() self.test_get_autocompletion_value_error() -class TestQueryCollectionNotices(): + +class TestQueryCollectionNotices: """ Test Class for query_collection_notices """ @@ -2089,11 +2197,13 @@ def test_query_collection_notices_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2101,7 +2211,7 @@ def test_query_collection_notices_all_params(self): filter = 'testString' query = 'testString' natural_language_query = 'testString' - count = 38 + count = 10 offset = 38 # Invoke method @@ -2113,14 +2223,14 @@ def test_query_collection_notices_all_params(self): natural_language_query=natural_language_query, count=count, offset=offset, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string assert 'query={}'.format(query) in query_string @@ -2145,11 +2255,13 @@ def test_query_collection_notices_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2159,7 +2271,7 @@ def test_query_collection_notices_required_params(self): response = _service.query_collection_notices( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2183,11 +2295,13 @@ def test_query_collection_notices_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2199,7 +2313,7 @@ def test_query_collection_notices_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query_collection_notices(**req_copy) @@ -2212,7 +2326,8 @@ def test_query_collection_notices_value_error_with_retries(self): _service.disable_retries() self.test_query_collection_notices_value_error() -class TestQueryNotices(): + +class TestQueryNotices: """ Test Class for query_notices """ @@ -2225,18 +2340,20 @@ def test_query_notices_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' filter = 'testString' query = 'testString' natural_language_query = 'testString' - count = 38 + count = 10 offset = 38 # Invoke method @@ -2247,14 +2364,14 @@ def test_query_notices_all_params(self): natural_language_query=natural_language_query, count=count, offset=offset, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'filter={}'.format(filter) in query_string assert 'query={}'.format(query) in query_string @@ -2279,11 +2396,13 @@ def test_query_notices_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2291,7 +2410,7 @@ def test_query_notices_required_params(self): # Invoke method response = _service.query_notices( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -2315,11 +2434,13 @@ def test_query_notices_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/notices') mock_response = '{"matching_results": 16, "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2329,7 +2450,7 @@ def test_query_notices_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.query_notices(**req_copy) @@ -2342,6 +2463,7 @@ def test_query_notices_value_error_with_retries(self): _service.disable_retries() self.test_query_notices_value_error() + # endregion ############################################################################## # End of Service: Queries @@ -2352,7 +2474,8 @@ def test_query_notices_value_error_with_retries(self): ############################################################################## # region -class TestGetStopwordList(): + +class TestGetStopwordList: """ Test Class for get_stopword_list """ @@ -2365,11 +2488,13 @@ def test_get_stopword_list_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') mock_response = '{"stopwords": ["stopwords"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2379,7 +2504,7 @@ def test_get_stopword_list_all_params(self): response = _service.get_stopword_list( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2403,11 +2528,13 @@ def test_get_stopword_list_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') mock_response = '{"stopwords": ["stopwords"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2419,7 +2546,7 @@ def test_get_stopword_list_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_stopword_list(**req_copy) @@ -2432,7 +2559,8 @@ def test_get_stopword_list_value_error_with_retries(self): _service.disable_retries() self.test_get_stopword_list_value_error() -class TestCreateStopwordList(): + +class TestCreateStopwordList: """ Test Class for create_stopword_list """ @@ -2445,11 +2573,13 @@ def test_create_stopword_list_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') mock_response = '{"stopwords": ["stopwords"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2461,7 +2591,7 @@ def test_create_stopword_list_all_params(self): project_id, collection_id, stopwords=stopwords, - headers={} + headers={}, ) # Check for correct operation @@ -2488,11 +2618,13 @@ def test_create_stopword_list_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') mock_response = '{"stopwords": ["stopwords"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2502,7 +2634,7 @@ def test_create_stopword_list_required_params(self): response = _service.create_stopword_list( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2526,11 +2658,13 @@ def test_create_stopword_list_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') mock_response = '{"stopwords": ["stopwords"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2542,7 +2676,7 @@ def test_create_stopword_list_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_stopword_list(**req_copy) @@ -2555,7 +2689,8 @@ def test_create_stopword_list_value_error_with_retries(self): _service.disable_retries() self.test_create_stopword_list_value_error() -class TestDeleteStopwordList(): + +class TestDeleteStopwordList: """ Test Class for delete_stopword_list """ @@ -2567,9 +2702,11 @@ def test_delete_stopword_list_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -2579,7 +2716,7 @@ def test_delete_stopword_list_all_params(self): response = _service.delete_stopword_list( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2602,9 +2739,11 @@ def test_delete_stopword_list_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/stopwords') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -2616,7 +2755,7 @@ def test_delete_stopword_list_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_stopword_list(**req_copy) @@ -2629,7 +2768,8 @@ def test_delete_stopword_list_value_error_with_retries(self): _service.disable_retries() self.test_delete_stopword_list_value_error() -class TestListExpansions(): + +class TestListExpansions: """ Test Class for list_expansions """ @@ -2642,11 +2782,13 @@ def test_list_expansions_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2656,7 +2798,7 @@ def test_list_expansions_all_params(self): response = _service.list_expansions( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2680,11 +2822,13 @@ def test_list_expansions_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2696,7 +2840,7 @@ def test_list_expansions_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_expansions(**req_copy) @@ -2709,7 +2853,8 @@ def test_list_expansions_value_error_with_retries(self): _service.disable_retries() self.test_list_expansions_value_error() -class TestCreateExpansions(): + +class TestCreateExpansions: """ Test Class for create_expansions """ @@ -2722,11 +2867,13 @@ def test_create_expansions_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Expansion model expansion_model = {} @@ -2743,7 +2890,7 @@ def test_create_expansions_all_params(self): project_id, collection_id, expansions, - headers={} + headers={}, ) # Check for correct operation @@ -2770,11 +2917,13 @@ def test_create_expansions_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a Expansion model expansion_model = {} @@ -2793,7 +2942,7 @@ def test_create_expansions_value_error(self): "expansions": expansions, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_expansions(**req_copy) @@ -2806,7 +2955,8 @@ def test_create_expansions_value_error_with_retries(self): _service.disable_retries() self.test_create_expansions_value_error() -class TestDeleteExpansions(): + +class TestDeleteExpansions: """ Test Class for delete_expansions """ @@ -2818,9 +2968,11 @@ def test_delete_expansions_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -2830,7 +2982,7 @@ def test_delete_expansions_all_params(self): response = _service.delete_expansions( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -2853,9 +3005,11 @@ def test_delete_expansions_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/expansions') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -2867,7 +3021,7 @@ def test_delete_expansions_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_expansions(**req_copy) @@ -2880,6 +3034,7 @@ def test_delete_expansions_value_error_with_retries(self): _service.disable_retries() self.test_delete_expansions_value_error() + # endregion ############################################################################## # End of Service: QueryModifications @@ -2890,7 +3045,8 @@ def test_delete_expansions_value_error_with_retries(self): ############################################################################## # region -class TestGetComponentSettings(): + +class TestGetComponentSettings: """ Test Class for get_component_settings """ @@ -2903,11 +3059,13 @@ def test_get_component_settings_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/component_settings') mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2915,7 +3073,7 @@ def test_get_component_settings_all_params(self): # Invoke method response = _service.get_component_settings( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -2939,11 +3097,13 @@ def test_get_component_settings_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/component_settings') mock_response = '{"fields_shown": {"body": {"use_passage": false, "field": "field"}, "title": {"field": "field"}}, "autocomplete": true, "structured_search": false, "results_per_page": 16, "aggregations": [{"name": "name", "label": "label", "multiple_selections_allowed": false, "visualization_type": "auto"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -2953,7 +3113,7 @@ def test_get_component_settings_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_component_settings(**req_copy) @@ -2966,6 +3126,7 @@ def test_get_component_settings_value_error_with_retries(self): _service.disable_retries() self.test_get_component_settings_value_error() + # endregion ############################################################################## # End of Service: ComponentSettings @@ -2976,7 +3137,8 @@ def test_get_component_settings_value_error_with_retries(self): ############################################################################## # region -class TestListTrainingQueries(): + +class TestListTrainingQueries: """ Test Class for list_training_queries """ @@ -2989,11 +3151,13 @@ def test_list_training_queries_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3001,7 +3165,7 @@ def test_list_training_queries_all_params(self): # Invoke method response = _service.list_training_queries( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -3025,11 +3189,13 @@ def test_list_training_queries_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') mock_response = '{"queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3039,7 +3205,7 @@ def test_list_training_queries_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_training_queries(**req_copy) @@ -3052,7 +3218,8 @@ def test_list_training_queries_value_error_with_retries(self): _service.disable_retries() self.test_list_training_queries_value_error() -class TestDeleteTrainingQueries(): + +class TestDeleteTrainingQueries: """ Test Class for delete_training_queries """ @@ -3064,9 +3231,11 @@ def test_delete_training_queries_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3074,7 +3243,7 @@ def test_delete_training_queries_all_params(self): # Invoke method response = _service.delete_training_queries( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -3097,9 +3266,11 @@ def test_delete_training_queries_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3109,7 +3280,7 @@ def test_delete_training_queries_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_training_queries(**req_copy) @@ -3122,7 +3293,8 @@ def test_delete_training_queries_value_error_with_retries(self): _service.disable_retries() self.test_delete_training_queries_value_error() -class TestCreateTrainingQuery(): + +class TestCreateTrainingQuery: """ Test Class for create_training_query """ @@ -3135,11 +3307,13 @@ def test_create_training_query_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -3159,7 +3333,7 @@ def test_create_training_query_all_params(self): natural_language_query, examples, filter=filter, - headers={} + headers={}, ) # Check for correct operation @@ -3188,11 +3362,13 @@ def test_create_training_query_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -3213,7 +3389,7 @@ def test_create_training_query_value_error(self): "examples": examples, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_training_query(**req_copy) @@ -3226,7 +3402,8 @@ def test_create_training_query_value_error_with_retries(self): _service.disable_retries() self.test_create_training_query_value_error() -class TestGetTrainingQuery(): + +class TestGetTrainingQuery: """ Test Class for get_training_query """ @@ -3239,11 +3416,13 @@ def test_get_training_query_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3253,7 +3432,7 @@ def test_get_training_query_all_params(self): response = _service.get_training_query( project_id, query_id, - headers={} + headers={}, ) # Check for correct operation @@ -3277,11 +3456,13 @@ def test_get_training_query_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3293,7 +3474,7 @@ def test_get_training_query_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_training_query(**req_copy) @@ -3306,7 +3487,8 @@ def test_get_training_query_value_error_with_retries(self): _service.disable_retries() self.test_get_training_query_value_error() -class TestUpdateTrainingQuery(): + +class TestUpdateTrainingQuery: """ Test Class for update_training_query """ @@ -3319,11 +3501,13 @@ def test_update_training_query_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -3345,7 +3529,7 @@ def test_update_training_query_all_params(self): natural_language_query, examples, filter=filter, - headers={} + headers={}, ) # Check for correct operation @@ -3374,11 +3558,13 @@ def test_update_training_query_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "examples": [{"document_id": "document_id", "collection_id": "collection_id", "relevance": 9, "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a TrainingExample model training_example_model = {} @@ -3401,7 +3587,7 @@ def test_update_training_query_value_error(self): "examples": examples, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_training_query(**req_copy) @@ -3414,7 +3600,8 @@ def test_update_training_query_value_error_with_retries(self): _service.disable_retries() self.test_update_training_query_value_error() -class TestDeleteTrainingQuery(): + +class TestDeleteTrainingQuery: """ Test Class for delete_training_query """ @@ -3426,9 +3613,11 @@ def test_delete_training_query_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3438,7 +3627,7 @@ def test_delete_training_query_all_params(self): response = _service.delete_training_query( project_id, query_id, - headers={} + headers={}, ) # Check for correct operation @@ -3461,9 +3650,11 @@ def test_delete_training_query_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/training_data/queries/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3475,7 +3666,7 @@ def test_delete_training_query_value_error(self): "query_id": query_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_training_query(**req_copy) @@ -3488,6 +3679,7 @@ def test_delete_training_query_value_error_with_retries(self): _service.disable_retries() self.test_delete_training_query_value_error() + # endregion ############################################################################## # End of Service: TrainingData @@ -3498,7 +3690,8 @@ def test_delete_training_query_value_error_with_retries(self): ############################################################################## # region -class TestListEnrichments(): + +class TestListEnrichments: """ Test Class for list_enrichments """ @@ -3510,12 +3703,14 @@ def test_list_enrichments_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3523,7 +3718,7 @@ def test_list_enrichments_all_params(self): # Invoke method response = _service.list_enrichments( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -3546,12 +3741,14 @@ def test_list_enrichments_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3561,7 +3758,7 @@ def test_list_enrichments_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_enrichments(**req_copy) @@ -3574,7 +3771,8 @@ def test_list_enrichments_value_error_with_retries(self): _service.disable_retries() self.test_list_enrichments_value_error() -class TestCreateEnrichment(): + +class TestCreateEnrichment: """ Test Class for create_enrichment """ @@ -3586,12 +3784,14 @@ def test_create_enrichment_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a EnrichmentOptions model enrichment_options_model = {} @@ -3602,7 +3802,7 @@ def test_create_enrichment_all_params(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 + enrichment_options_model['top_k'] = 0 # Construct a dict representation of a CreateEnrichment model create_enrichment_model = {} @@ -3621,7 +3821,7 @@ def test_create_enrichment_all_params(self): project_id, enrichment, file=file, - headers={} + headers={}, ) # Check for correct operation @@ -3644,12 +3844,14 @@ def test_create_enrichment_required_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a EnrichmentOptions model enrichment_options_model = {} @@ -3660,7 +3862,7 @@ def test_create_enrichment_required_params(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 + enrichment_options_model['top_k'] = 0 # Construct a dict representation of a CreateEnrichment model create_enrichment_model = {} @@ -3677,7 +3879,7 @@ def test_create_enrichment_required_params(self): response = _service.create_enrichment( project_id, enrichment, - headers={} + headers={}, ) # Check for correct operation @@ -3700,12 +3902,14 @@ def test_create_enrichment_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a EnrichmentOptions model enrichment_options_model = {} @@ -3716,7 +3920,7 @@ def test_create_enrichment_value_error(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 + enrichment_options_model['top_k'] = 0 # Construct a dict representation of a CreateEnrichment model create_enrichment_model = {} @@ -3735,7 +3939,7 @@ def test_create_enrichment_value_error(self): "enrichment": enrichment, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_enrichment(**req_copy) @@ -3748,7 +3952,8 @@ def test_create_enrichment_value_error_with_retries(self): _service.disable_retries() self.test_create_enrichment_value_error() -class TestGetEnrichment(): + +class TestGetEnrichment: """ Test Class for get_enrichment """ @@ -3760,12 +3965,14 @@ def test_get_enrichment_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3775,7 +3982,7 @@ def test_get_enrichment_all_params(self): response = _service.get_enrichment( project_id, enrichment_id, - headers={} + headers={}, ) # Check for correct operation @@ -3798,12 +4005,14 @@ def test_get_enrichment_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3815,7 +4024,7 @@ def test_get_enrichment_value_error(self): "enrichment_id": enrichment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_enrichment(**req_copy) @@ -3828,7 +4037,8 @@ def test_get_enrichment_value_error_with_retries(self): _service.disable_retries() self.test_get_enrichment_value_error() -class TestUpdateEnrichment(): + +class TestUpdateEnrichment: """ Test Class for update_enrichment """ @@ -3840,12 +4050,14 @@ def test_update_enrichment_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3859,7 +4071,7 @@ def test_update_enrichment_all_params(self): enrichment_id, name, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -3886,12 +4098,14 @@ def test_update_enrichment_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 5}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -3906,7 +4120,7 @@ def test_update_enrichment_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_enrichment(**req_copy) @@ -3919,7 +4133,8 @@ def test_update_enrichment_value_error_with_retries(self): _service.disable_retries() self.test_update_enrichment_value_error() -class TestDeleteEnrichment(): + +class TestDeleteEnrichment: """ Test Class for delete_enrichment """ @@ -3931,9 +4146,11 @@ def test_delete_enrichment_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3943,7 +4160,7 @@ def test_delete_enrichment_all_params(self): response = _service.delete_enrichment( project_id, enrichment_id, - headers={} + headers={}, ) # Check for correct operation @@ -3966,9 +4183,11 @@ def test_delete_enrichment_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -3980,7 +4199,7 @@ def test_delete_enrichment_value_error(self): "enrichment_id": enrichment_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_enrichment(**req_copy) @@ -3993,6 +4212,7 @@ def test_delete_enrichment_value_error_with_retries(self): _service.disable_retries() self.test_delete_enrichment_value_error() + # endregion ############################################################################## # End of Service: Enrichments @@ -4003,7 +4223,8 @@ def test_delete_enrichment_value_error_with_retries(self): ############################################################################## # region -class TestListDocumentClassifiers(): + +class TestListDocumentClassifiers: """ Test Class for list_document_classifiers """ @@ -4016,11 +4237,13 @@ def test_list_document_classifiers_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers') mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4028,7 +4251,7 @@ def test_list_document_classifiers_all_params(self): # Invoke method response = _service.list_document_classifiers( project_id, - headers={} + headers={}, ) # Check for correct operation @@ -4052,11 +4275,13 @@ def test_list_document_classifiers_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers') mock_response = '{"classifiers": [{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4066,7 +4291,7 @@ def test_list_document_classifiers_value_error(self): "project_id": project_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_document_classifiers(**req_copy) @@ -4079,7 +4304,8 @@ def test_list_document_classifiers_value_error_with_retries(self): _service.disable_retries() self.test_list_document_classifiers_value_error() -class TestCreateDocumentClassifier(): + +class TestCreateDocumentClassifier: """ Test Class for create_document_classifier """ @@ -4092,11 +4318,13 @@ def test_create_document_classifier_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DocumentClassifierEnrichment model document_classifier_enrichment_model = {} @@ -4128,7 +4356,7 @@ def test_create_document_classifier_all_params(self): training_data, classifier, test_data=test_data, - headers={} + headers={}, ) # Check for correct operation @@ -4152,11 +4380,13 @@ def test_create_document_classifier_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DocumentClassifierEnrichment model document_classifier_enrichment_model = {} @@ -4186,7 +4416,7 @@ def test_create_document_classifier_required_params(self): project_id, training_data, classifier, - headers={} + headers={}, ) # Check for correct operation @@ -4210,11 +4440,13 @@ def test_create_document_classifier_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a DocumentClassifierEnrichment model document_classifier_enrichment_model = {} @@ -4246,7 +4478,7 @@ def test_create_document_classifier_value_error(self): "classifier": classifier, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_document_classifier(**req_copy) @@ -4259,7 +4491,8 @@ def test_create_document_classifier_value_error_with_retries(self): _service.disable_retries() self.test_create_document_classifier_value_error() -class TestGetDocumentClassifier(): + +class TestGetDocumentClassifier: """ Test Class for get_document_classifier """ @@ -4272,11 +4505,13 @@ def test_get_document_classifier_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4286,7 +4521,7 @@ def test_get_document_classifier_all_params(self): response = _service.get_document_classifier( project_id, classifier_id, - headers={} + headers={}, ) # Check for correct operation @@ -4310,11 +4545,13 @@ def test_get_document_classifier_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4326,7 +4563,7 @@ def test_get_document_classifier_value_error(self): "classifier_id": classifier_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_classifier(**req_copy) @@ -4339,7 +4576,8 @@ def test_get_document_classifier_value_error_with_retries(self): _service.disable_retries() self.test_get_document_classifier_value_error() -class TestUpdateDocumentClassifier(): + +class TestUpdateDocumentClassifier: """ Test Class for update_document_classifier """ @@ -4352,11 +4590,13 @@ def test_update_document_classifier_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a UpdateDocumentClassifier model update_document_classifier_model = {} @@ -4377,7 +4617,7 @@ def test_update_document_classifier_all_params(self): classifier, training_data=training_data, test_data=test_data, - headers={} + headers={}, ) # Check for correct operation @@ -4401,11 +4641,13 @@ def test_update_document_classifier_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a UpdateDocumentClassifier model update_document_classifier_model = {} @@ -4422,7 +4664,7 @@ def test_update_document_classifier_required_params(self): project_id, classifier_id, classifier, - headers={} + headers={}, ) # Check for correct operation @@ -4446,11 +4688,13 @@ def test_update_document_classifier_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') mock_response = '{"classifier_id": "classifier_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "recognized_fields": ["recognized_fields"], "answer_field": "answer_field", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "federated_classification": {"field": "field"}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a UpdateDocumentClassifier model update_document_classifier_model = {} @@ -4469,7 +4713,7 @@ def test_update_document_classifier_value_error(self): "classifier": classifier, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_document_classifier(**req_copy) @@ -4482,7 +4726,8 @@ def test_update_document_classifier_value_error_with_retries(self): _service.disable_retries() self.test_update_document_classifier_value_error() -class TestDeleteDocumentClassifier(): + +class TestDeleteDocumentClassifier: """ Test Class for delete_document_classifier """ @@ -4494,9 +4739,11 @@ def test_delete_document_classifier_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -4506,7 +4753,7 @@ def test_delete_document_classifier_all_params(self): response = _service.delete_document_classifier( project_id, classifier_id, - headers={} + headers={}, ) # Check for correct operation @@ -4529,9 +4776,11 @@ def test_delete_document_classifier_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -4543,7 +4792,7 @@ def test_delete_document_classifier_value_error(self): "classifier_id": classifier_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document_classifier(**req_copy) @@ -4556,6 +4805,7 @@ def test_delete_document_classifier_value_error_with_retries(self): _service.disable_retries() self.test_delete_document_classifier_value_error() + # endregion ############################################################################## # End of Service: DocumentClassifiers @@ -4566,7 +4816,8 @@ def test_delete_document_classifier_value_error_with_retries(self): ############################################################################## # region -class TestListDocumentClassifierModels(): + +class TestListDocumentClassifierModels: """ Test Class for list_document_classifier_models """ @@ -4579,11 +4830,13 @@ def test_list_document_classifier_models_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4593,7 +4846,7 @@ def test_list_document_classifier_models_all_params(self): response = _service.list_document_classifier_models( project_id, classifier_id, - headers={} + headers={}, ) # Check for correct operation @@ -4617,11 +4870,13 @@ def test_list_document_classifier_models_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4633,7 +4888,7 @@ def test_list_document_classifier_models_value_error(self): "classifier_id": classifier_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_document_classifier_models(**req_copy) @@ -4646,7 +4901,8 @@ def test_list_document_classifier_models_value_error_with_retries(self): _service.disable_retries() self.test_list_document_classifier_models_value_error() -class TestCreateDocumentClassifierModel(): + +class TestCreateDocumentClassifierModel: """ Test Class for create_document_classifier_model """ @@ -4659,22 +4915,24 @@ def test_create_document_classifier_model_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values project_id = 'testString' classifier_id = 'testString' name = 'testString' description = 'testString' - learning_rate = 0 + learning_rate = 0.1 l1_regularization_strengths = [1.0E-6] l2_regularization_strengths = [1.0E-6] - training_max_steps = 0 - improvement_ratio = 0 + training_max_steps = 10000000 + improvement_ratio = 0.000010 # Invoke method response = _service.create_document_classifier_model( @@ -4687,7 +4945,7 @@ def test_create_document_classifier_model_all_params(self): l2_regularization_strengths=l2_regularization_strengths, training_max_steps=training_max_steps, improvement_ratio=improvement_ratio, - headers={} + headers={}, ) # Check for correct operation @@ -4697,11 +4955,11 @@ def test_create_document_classifier_model_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' - assert req_body['learning_rate'] == 0 + assert req_body['learning_rate'] == 0.1 assert req_body['l1_regularization_strengths'] == [1.0E-6] assert req_body['l2_regularization_strengths'] == [1.0E-6] - assert req_body['training_max_steps'] == 0 - assert req_body['improvement_ratio'] == 0 + assert req_body['training_max_steps'] == 10000000 + assert req_body['improvement_ratio'] == 0.000010 def test_create_document_classifier_model_all_params_with_retries(self): # Enable retries and run test_create_document_classifier_model_all_params. @@ -4720,22 +4978,24 @@ def test_create_document_classifier_model_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values project_id = 'testString' classifier_id = 'testString' name = 'testString' description = 'testString' - learning_rate = 0 + learning_rate = 0.1 l1_regularization_strengths = [1.0E-6] l2_regularization_strengths = [1.0E-6] - training_max_steps = 0 - improvement_ratio = 0 + training_max_steps = 10000000 + improvement_ratio = 0.000010 # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -4744,7 +5004,7 @@ def test_create_document_classifier_model_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_document_classifier_model(**req_copy) @@ -4757,7 +5017,8 @@ def test_create_document_classifier_model_value_error_with_retries(self): _service.disable_retries() self.test_create_document_classifier_model_value_error() -class TestGetDocumentClassifierModel(): + +class TestGetDocumentClassifierModel: """ Test Class for get_document_classifier_model """ @@ -4770,11 +5031,13 @@ def test_get_document_classifier_model_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4786,7 +5049,7 @@ def test_get_document_classifier_model_all_params(self): project_id, classifier_id, model_id, - headers={} + headers={}, ) # Check for correct operation @@ -4810,11 +5073,13 @@ def test_get_document_classifier_model_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -4828,7 +5093,7 @@ def test_get_document_classifier_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_classifier_model(**req_copy) @@ -4841,7 +5106,8 @@ def test_get_document_classifier_model_value_error_with_retries(self): _service.disable_retries() self.test_get_document_classifier_model_value_error() -class TestUpdateDocumentClassifierModel(): + +class TestUpdateDocumentClassifierModel: """ Test Class for update_document_classifier_model """ @@ -4854,11 +5120,13 @@ def test_update_document_classifier_model_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values project_id = 'testString' @@ -4874,7 +5142,7 @@ def test_update_document_classifier_model_all_params(self): model_id, name=name, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -4902,11 +5170,13 @@ def test_update_document_classifier_model_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "training_data_file": "training_data_file", "test_data_file": "test_data_file", "status": "training", "evaluation": {"micro_average": {"precision": 0, "recall": 0, "f1": 0}, "macro_average": {"precision": 0, "recall": 0, "f1": 0}, "per_class": [{"name": "name", "precision": 0, "recall": 0, "f1": 0}]}, "enrichment_id": "enrichment_id", "deployed_at": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values project_id = 'testString' @@ -4922,7 +5192,7 @@ def test_update_document_classifier_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_document_classifier_model(**req_copy) @@ -4935,7 +5205,8 @@ def test_update_document_classifier_model_value_error_with_retries(self): _service.disable_retries() self.test_update_document_classifier_model_value_error() -class TestDeleteDocumentClassifierModel(): + +class TestDeleteDocumentClassifierModel: """ Test Class for delete_document_classifier_model """ @@ -4947,9 +5218,11 @@ def test_delete_document_classifier_model_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -4961,7 +5234,7 @@ def test_delete_document_classifier_model_all_params(self): project_id, classifier_id, model_id, - headers={} + headers={}, ) # Check for correct operation @@ -4984,9 +5257,11 @@ def test_delete_document_classifier_model_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/document_classifiers/testString/models/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values project_id = 'testString' @@ -5000,7 +5275,7 @@ def test_delete_document_classifier_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document_classifier_model(**req_copy) @@ -5013,6 +5288,7 @@ def test_delete_document_classifier_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_document_classifier_model_value_error() + # endregion ############################################################################## # End of Service: DocumentClassifierModels @@ -5023,7 +5299,8 @@ def test_delete_document_classifier_model_value_error_with_retries(self): ############################################################################## # region -class TestAnalyzeDocument(): + +class TestAnalyzeDocument: """ Test Class for analyze_document """ @@ -5036,11 +5313,13 @@ def test_analyze_document_all_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/analyze') mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -5058,7 +5337,7 @@ def test_analyze_document_all_params(self): filename=filename, file_content_type=file_content_type, metadata=metadata, - headers={} + headers={}, ) # Check for correct operation @@ -5082,11 +5361,13 @@ def test_analyze_document_required_params(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/analyze') mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -5096,7 +5377,7 @@ def test_analyze_document_required_params(self): response = _service.analyze_document( project_id, collection_id, - headers={} + headers={}, ) # Check for correct operation @@ -5120,11 +5401,13 @@ def test_analyze_document_value_error(self): # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString/analyze') mock_response = '{"notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "collection_id": "collection_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}], "result": {"metadata": {"anyKey": "anyValue"}}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values project_id = 'testString' @@ -5136,7 +5419,7 @@ def test_analyze_document_value_error(self): "collection_id": collection_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.analyze_document(**req_copy) @@ -5149,6 +5432,7 @@ def test_analyze_document_value_error_with_retries(self): _service.disable_retries() self.test_analyze_document_value_error() + # endregion ############################################################################## # End of Service: Analyze @@ -5159,7 +5443,8 @@ def test_analyze_document_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -5171,9 +5456,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v2/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -5181,14 +5468,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -5208,9 +5495,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v2/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -5220,7 +5509,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -5233,6 +5522,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -5243,7 +5533,9 @@ def test_delete_user_data_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_AnalyzedDocument(): + + +class TestModel_AnalyzedDocument: """ Test Class for AnalyzedDocument """ @@ -5255,10 +5547,10 @@ def test_analyzed_document_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice - analyzed_result_model = {} # AnalyzedResult - analyzed_result_model['metadata'] = {'foo': 'bar'} + analyzed_result_model = {} # AnalyzedResult + analyzed_result_model['metadata'] = {'anyKey': 'anyValue'} analyzed_result_model['foo'] = 'testString' # Construct a json representation of a AnalyzedDocument model @@ -5281,7 +5573,8 @@ def test_analyzed_document_serialization(self): analyzed_document_model_json2 = analyzed_document_model.to_dict() assert analyzed_document_model_json2 == analyzed_document_model_json -class TestModel_AnalyzedResult(): + +class TestModel_AnalyzedResult: """ Test Class for AnalyzedResult """ @@ -5293,7 +5586,7 @@ def test_analyzed_result_serialization(self): # Construct a json representation of a AnalyzedResult model analyzed_result_model_json = {} - analyzed_result_model_json['metadata'] = {'foo': 'bar'} + analyzed_result_model_json['metadata'] = {'anyKey': 'anyValue'} analyzed_result_model_json['foo'] = 'testString' # Construct a model instance of AnalyzedResult by calling from_dict on the json representation @@ -5321,7 +5614,8 @@ def test_analyzed_result_serialization(self): actual_dict = analyzed_result_model.get_properties() assert actual_dict == expected_dict -class TestModel_ClassifierFederatedModel(): + +class TestModel_ClassifierFederatedModel: """ Test Class for ClassifierFederatedModel """ @@ -5350,7 +5644,8 @@ def test_classifier_federated_model_serialization(self): classifier_federated_model_model_json2 = classifier_federated_model_model.to_dict() assert classifier_federated_model_model_json2 == classifier_federated_model_model_json -class TestModel_ClassifierModelEvaluation(): + +class TestModel_ClassifierModelEvaluation: """ Test Class for ClassifierModelEvaluation """ @@ -5362,17 +5657,17 @@ def test_classifier_model_evaluation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage model_evaluation_micro_average_model['precision'] = 0 model_evaluation_micro_average_model['recall'] = 0 model_evaluation_micro_average_model['f1'] = 0 - model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage model_evaluation_macro_average_model['precision'] = 0 model_evaluation_macro_average_model['recall'] = 0 model_evaluation_macro_average_model['f1'] = 0 - per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model = {} # PerClassModelEvaluation per_class_model_evaluation_model['name'] = 'testString' per_class_model_evaluation_model['precision'] = 0 per_class_model_evaluation_model['recall'] = 0 @@ -5399,7 +5694,8 @@ def test_classifier_model_evaluation_serialization(self): classifier_model_evaluation_model_json2 = classifier_model_evaluation_model.to_dict() assert classifier_model_evaluation_model_json2 == classifier_model_evaluation_model_json -class TestModel_Collection(): + +class TestModel_Collection: """ Test Class for Collection """ @@ -5428,7 +5724,8 @@ def test_collection_serialization(self): collection_model_json2 = collection_model.to_dict() assert collection_model_json2 == collection_model_json -class TestModel_CollectionDetails(): + +class TestModel_CollectionDetails: """ Test Class for CollectionDetails """ @@ -5440,7 +5737,7 @@ def test_collection_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - collection_enrichment_model = {} # CollectionEnrichment + collection_enrichment_model = {} # CollectionEnrichment collection_enrichment_model['enrichment_id'] = 'testString' collection_enrichment_model['fields'] = ['testString'] @@ -5466,7 +5763,8 @@ def test_collection_details_serialization(self): collection_details_model_json2 = collection_details_model.to_dict() assert collection_details_model_json2 == collection_details_model_json -class TestModel_CollectionDetailsSmartDocumentUnderstanding(): + +class TestModel_CollectionDetailsSmartDocumentUnderstanding: """ Test Class for CollectionDetailsSmartDocumentUnderstanding """ @@ -5496,7 +5794,8 @@ def test_collection_details_smart_document_understanding_serialization(self): collection_details_smart_document_understanding_model_json2 = collection_details_smart_document_understanding_model.to_dict() assert collection_details_smart_document_understanding_model_json2 == collection_details_smart_document_understanding_model_json -class TestModel_CollectionEnrichment(): + +class TestModel_CollectionEnrichment: """ Test Class for CollectionEnrichment """ @@ -5526,7 +5825,8 @@ def test_collection_enrichment_serialization(self): collection_enrichment_model_json2 = collection_enrichment_model.to_dict() assert collection_enrichment_model_json2 == collection_enrichment_model_json -class TestModel_Completions(): + +class TestModel_Completions: """ Test Class for Completions """ @@ -5555,7 +5855,8 @@ def test_completions_serialization(self): completions_model_json2 = completions_model.to_dict() assert completions_model_json2 == completions_model_json -class TestModel_ComponentSettingsAggregation(): + +class TestModel_ComponentSettingsAggregation: """ Test Class for ComponentSettingsAggregation """ @@ -5587,7 +5888,8 @@ def test_component_settings_aggregation_serialization(self): component_settings_aggregation_model_json2 = component_settings_aggregation_model.to_dict() assert component_settings_aggregation_model_json2 == component_settings_aggregation_model_json -class TestModel_ComponentSettingsFieldsShown(): + +class TestModel_ComponentSettingsFieldsShown: """ Test Class for ComponentSettingsFieldsShown """ @@ -5599,11 +5901,11 @@ def test_component_settings_fields_shown_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - component_settings_fields_shown_body_model = {} # ComponentSettingsFieldsShownBody + component_settings_fields_shown_body_model = {} # ComponentSettingsFieldsShownBody component_settings_fields_shown_body_model['use_passage'] = True component_settings_fields_shown_body_model['field'] = 'testString' - component_settings_fields_shown_title_model = {} # ComponentSettingsFieldsShownTitle + component_settings_fields_shown_title_model = {} # ComponentSettingsFieldsShownTitle component_settings_fields_shown_title_model['field'] = 'testString' # Construct a json representation of a ComponentSettingsFieldsShown model @@ -5626,7 +5928,8 @@ def test_component_settings_fields_shown_serialization(self): component_settings_fields_shown_model_json2 = component_settings_fields_shown_model.to_dict() assert component_settings_fields_shown_model_json2 == component_settings_fields_shown_model_json -class TestModel_ComponentSettingsFieldsShownBody(): + +class TestModel_ComponentSettingsFieldsShownBody: """ Test Class for ComponentSettingsFieldsShownBody """ @@ -5656,7 +5959,8 @@ def test_component_settings_fields_shown_body_serialization(self): component_settings_fields_shown_body_model_json2 = component_settings_fields_shown_body_model.to_dict() assert component_settings_fields_shown_body_model_json2 == component_settings_fields_shown_body_model_json -class TestModel_ComponentSettingsFieldsShownTitle(): + +class TestModel_ComponentSettingsFieldsShownTitle: """ Test Class for ComponentSettingsFieldsShownTitle """ @@ -5685,7 +5989,8 @@ def test_component_settings_fields_shown_title_serialization(self): component_settings_fields_shown_title_model_json2 = component_settings_fields_shown_title_model.to_dict() assert component_settings_fields_shown_title_model_json2 == component_settings_fields_shown_title_model_json -class TestModel_ComponentSettingsResponse(): + +class TestModel_ComponentSettingsResponse: """ Test Class for ComponentSettingsResponse """ @@ -5697,18 +6002,18 @@ def test_component_settings_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - component_settings_fields_shown_body_model = {} # ComponentSettingsFieldsShownBody + component_settings_fields_shown_body_model = {} # ComponentSettingsFieldsShownBody component_settings_fields_shown_body_model['use_passage'] = True component_settings_fields_shown_body_model['field'] = 'testString' - component_settings_fields_shown_title_model = {} # ComponentSettingsFieldsShownTitle + component_settings_fields_shown_title_model = {} # ComponentSettingsFieldsShownTitle component_settings_fields_shown_title_model['field'] = 'testString' - component_settings_fields_shown_model = {} # ComponentSettingsFieldsShown + component_settings_fields_shown_model = {} # ComponentSettingsFieldsShown component_settings_fields_shown_model['body'] = component_settings_fields_shown_body_model component_settings_fields_shown_model['title'] = component_settings_fields_shown_title_model - component_settings_aggregation_model = {} # ComponentSettingsAggregation + component_settings_aggregation_model = {} # ComponentSettingsAggregation component_settings_aggregation_model['name'] = 'testString' component_settings_aggregation_model['label'] = 'testString' component_settings_aggregation_model['multiple_selections_allowed'] = True @@ -5737,7 +6042,8 @@ def test_component_settings_response_serialization(self): component_settings_response_model_json2 = component_settings_response_model.to_dict() assert component_settings_response_model_json2 == component_settings_response_model_json -class TestModel_CreateDocumentClassifier(): + +class TestModel_CreateDocumentClassifier: """ Test Class for CreateDocumentClassifier """ @@ -5749,11 +6055,11 @@ def test_create_document_classifier_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment document_classifier_enrichment_model['enrichment_id'] = 'testString' document_classifier_enrichment_model['fields'] = ['testString'] - classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model = {} # ClassifierFederatedModel classifier_federated_model_model['field'] = 'testString' # Construct a json representation of a CreateDocumentClassifier model @@ -5780,7 +6086,8 @@ def test_create_document_classifier_serialization(self): create_document_classifier_model_json2 = create_document_classifier_model.to_dict() assert create_document_classifier_model_json2 == create_document_classifier_model_json -class TestModel_CreateEnrichment(): + +class TestModel_CreateEnrichment: """ Test Class for CreateEnrichment """ @@ -5792,7 +6099,7 @@ def test_create_enrichment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['languages'] = ['testString'] enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' @@ -5800,7 +6107,7 @@ def test_create_enrichment_serialization(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 + enrichment_options_model['top_k'] = 0 # Construct a json representation of a CreateEnrichment model create_enrichment_model_json = {} @@ -5824,7 +6131,8 @@ def test_create_enrichment_serialization(self): create_enrichment_model_json2 = create_enrichment_model.to_dict() assert create_enrichment_model_json2 == create_enrichment_model_json -class TestModel_DefaultQueryParams(): + +class TestModel_DefaultQueryParams: """ Test Class for DefaultQueryParams """ @@ -5836,7 +6144,7 @@ def test_default_query_params_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - default_query_params_passages_model = {} # DefaultQueryParamsPassages + default_query_params_passages_model = {} # DefaultQueryParamsPassages default_query_params_passages_model['enabled'] = True default_query_params_passages_model['count'] = 38 default_query_params_passages_model['fields'] = ['testString'] @@ -5844,12 +6152,12 @@ def test_default_query_params_serialization(self): default_query_params_passages_model['per_document'] = True default_query_params_passages_model['max_per_document'] = 38 - default_query_params_table_results_model = {} # DefaultQueryParamsTableResults + default_query_params_table_results_model = {} # DefaultQueryParamsTableResults default_query_params_table_results_model['enabled'] = True default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 + default_query_params_table_results_model['per_document'] = 0 - default_query_params_suggested_refinements_model = {} # DefaultQueryParamsSuggestedRefinements + default_query_params_suggested_refinements_model = {} # DefaultQueryParamsSuggestedRefinements default_query_params_suggested_refinements_model['enabled'] = True default_query_params_suggested_refinements_model['count'] = 38 @@ -5881,7 +6189,8 @@ def test_default_query_params_serialization(self): default_query_params_model_json2 = default_query_params_model.to_dict() assert default_query_params_model_json2 == default_query_params_model_json -class TestModel_DefaultQueryParamsPassages(): + +class TestModel_DefaultQueryParamsPassages: """ Test Class for DefaultQueryParamsPassages """ @@ -5915,7 +6224,8 @@ def test_default_query_params_passages_serialization(self): default_query_params_passages_model_json2 = default_query_params_passages_model.to_dict() assert default_query_params_passages_model_json2 == default_query_params_passages_model_json -class TestModel_DefaultQueryParamsSuggestedRefinements(): + +class TestModel_DefaultQueryParamsSuggestedRefinements: """ Test Class for DefaultQueryParamsSuggestedRefinements """ @@ -5945,7 +6255,8 @@ def test_default_query_params_suggested_refinements_serialization(self): default_query_params_suggested_refinements_model_json2 = default_query_params_suggested_refinements_model.to_dict() assert default_query_params_suggested_refinements_model_json2 == default_query_params_suggested_refinements_model_json -class TestModel_DefaultQueryParamsTableResults(): + +class TestModel_DefaultQueryParamsTableResults: """ Test Class for DefaultQueryParamsTableResults """ @@ -5959,7 +6270,7 @@ def test_default_query_params_table_results_serialization(self): default_query_params_table_results_model_json = {} default_query_params_table_results_model_json['enabled'] = True default_query_params_table_results_model_json['count'] = 38 - default_query_params_table_results_model_json['per_document'] = 38 + default_query_params_table_results_model_json['per_document'] = 0 # Construct a model instance of DefaultQueryParamsTableResults by calling from_dict on the json representation default_query_params_table_results_model = DefaultQueryParamsTableResults.from_dict(default_query_params_table_results_model_json) @@ -5976,7 +6287,8 @@ def test_default_query_params_table_results_serialization(self): default_query_params_table_results_model_json2 = default_query_params_table_results_model.to_dict() assert default_query_params_table_results_model_json2 == default_query_params_table_results_model_json -class TestModel_DeleteDocumentResponse(): + +class TestModel_DeleteDocumentResponse: """ Test Class for DeleteDocumentResponse """ @@ -6006,7 +6318,8 @@ def test_delete_document_response_serialization(self): delete_document_response_model_json2 = delete_document_response_model.to_dict() assert delete_document_response_model_json2 == delete_document_response_model_json -class TestModel_DocumentAccepted(): + +class TestModel_DocumentAccepted: """ Test Class for DocumentAccepted """ @@ -6036,7 +6349,8 @@ def test_document_accepted_serialization(self): document_accepted_model_json2 = document_accepted_model.to_dict() assert document_accepted_model_json2 == document_accepted_model_json -class TestModel_DocumentAttribute(): + +class TestModel_DocumentAttribute: """ Test Class for DocumentAttribute """ @@ -6048,7 +6362,7 @@ def test_document_attribute_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 @@ -6073,7 +6387,8 @@ def test_document_attribute_serialization(self): document_attribute_model_json2 = document_attribute_model.to_dict() assert document_attribute_model_json2 == document_attribute_model_json -class TestModel_DocumentClassifier(): + +class TestModel_DocumentClassifier: """ Test Class for DocumentClassifier """ @@ -6085,11 +6400,11 @@ def test_document_classifier_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment document_classifier_enrichment_model['enrichment_id'] = 'testString' document_classifier_enrichment_model['fields'] = ['testString'] - classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model = {} # ClassifierFederatedModel classifier_federated_model_model['field'] = 'testString' # Construct a json representation of a DocumentClassifier model @@ -6119,7 +6434,8 @@ def test_document_classifier_serialization(self): document_classifier_model_json2 = document_classifier_model.to_dict() assert document_classifier_model_json2 == document_classifier_model_json -class TestModel_DocumentClassifierEnrichment(): + +class TestModel_DocumentClassifierEnrichment: """ Test Class for DocumentClassifierEnrichment """ @@ -6149,7 +6465,8 @@ def test_document_classifier_enrichment_serialization(self): document_classifier_enrichment_model_json2 = document_classifier_enrichment_model.to_dict() assert document_classifier_enrichment_model_json2 == document_classifier_enrichment_model_json -class TestModel_DocumentClassifierModel(): + +class TestModel_DocumentClassifierModel: """ Test Class for DocumentClassifierModel """ @@ -6161,23 +6478,23 @@ def test_document_classifier_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage model_evaluation_micro_average_model['precision'] = 0 model_evaluation_micro_average_model['recall'] = 0 model_evaluation_micro_average_model['f1'] = 0 - model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage model_evaluation_macro_average_model['precision'] = 0 model_evaluation_macro_average_model['recall'] = 0 model_evaluation_macro_average_model['f1'] = 0 - per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model = {} # PerClassModelEvaluation per_class_model_evaluation_model['name'] = 'testString' per_class_model_evaluation_model['precision'] = 0 per_class_model_evaluation_model['recall'] = 0 per_class_model_evaluation_model['f1'] = 0 - classifier_model_evaluation_model = {} # ClassifierModelEvaluation + classifier_model_evaluation_model = {} # ClassifierModelEvaluation classifier_model_evaluation_model['micro_average'] = model_evaluation_micro_average_model classifier_model_evaluation_model['macro_average'] = model_evaluation_macro_average_model classifier_model_evaluation_model['per_class'] = [per_class_model_evaluation_model] @@ -6207,7 +6524,8 @@ def test_document_classifier_model_serialization(self): document_classifier_model_model_json2 = document_classifier_model_model.to_dict() assert document_classifier_model_model_json2 == document_classifier_model_model_json -class TestModel_DocumentClassifierModels(): + +class TestModel_DocumentClassifierModels: """ Test Class for DocumentClassifierModels """ @@ -6219,28 +6537,28 @@ def test_document_classifier_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage + model_evaluation_micro_average_model = {} # ModelEvaluationMicroAverage model_evaluation_micro_average_model['precision'] = 0 model_evaluation_micro_average_model['recall'] = 0 model_evaluation_micro_average_model['f1'] = 0 - model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage + model_evaluation_macro_average_model = {} # ModelEvaluationMacroAverage model_evaluation_macro_average_model['precision'] = 0 model_evaluation_macro_average_model['recall'] = 0 model_evaluation_macro_average_model['f1'] = 0 - per_class_model_evaluation_model = {} # PerClassModelEvaluation + per_class_model_evaluation_model = {} # PerClassModelEvaluation per_class_model_evaluation_model['name'] = 'testString' per_class_model_evaluation_model['precision'] = 0 per_class_model_evaluation_model['recall'] = 0 per_class_model_evaluation_model['f1'] = 0 - classifier_model_evaluation_model = {} # ClassifierModelEvaluation + classifier_model_evaluation_model = {} # ClassifierModelEvaluation classifier_model_evaluation_model['micro_average'] = model_evaluation_micro_average_model classifier_model_evaluation_model['macro_average'] = model_evaluation_macro_average_model classifier_model_evaluation_model['per_class'] = [per_class_model_evaluation_model] - document_classifier_model_model = {} # DocumentClassifierModel + document_classifier_model_model = {} # DocumentClassifierModel document_classifier_model_model['name'] = 'testString' document_classifier_model_model['description'] = 'testString' document_classifier_model_model['training_data_file'] = 'testString' @@ -6268,7 +6586,8 @@ def test_document_classifier_models_serialization(self): document_classifier_models_model_json2 = document_classifier_models_model.to_dict() assert document_classifier_models_model_json2 == document_classifier_models_model_json -class TestModel_DocumentClassifiers(): + +class TestModel_DocumentClassifiers: """ Test Class for DocumentClassifiers """ @@ -6280,14 +6599,14 @@ def test_document_classifiers_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_classifier_enrichment_model = {} # DocumentClassifierEnrichment + document_classifier_enrichment_model = {} # DocumentClassifierEnrichment document_classifier_enrichment_model['enrichment_id'] = 'testString' document_classifier_enrichment_model['fields'] = ['testString'] - classifier_federated_model_model = {} # ClassifierFederatedModel + classifier_federated_model_model = {} # ClassifierFederatedModel classifier_federated_model_model['field'] = 'testString' - document_classifier_model = {} # DocumentClassifier + document_classifier_model = {} # DocumentClassifier document_classifier_model['name'] = 'testString' document_classifier_model['description'] = 'testString' document_classifier_model['language'] = 'en' @@ -6317,7 +6636,8 @@ def test_document_classifiers_serialization(self): document_classifiers_model_json2 = document_classifiers_model.to_dict() assert document_classifiers_model_json2 == document_classifiers_model_json -class TestModel_DocumentDetails(): + +class TestModel_DocumentDetails: """ Test Class for DocumentDetails """ @@ -6329,9 +6649,9 @@ def test_document_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice - document_details_children_model = {} # DocumentDetailsChildren + document_details_children_model = {} # DocumentDetailsChildren document_details_children_model['have_notices'] = True document_details_children_model['count'] = 38 @@ -6359,7 +6679,8 @@ def test_document_details_serialization(self): document_details_model_json2 = document_details_model.to_dict() assert document_details_model_json2 == document_details_model_json -class TestModel_DocumentDetailsChildren(): + +class TestModel_DocumentDetailsChildren: """ Test Class for DocumentDetailsChildren """ @@ -6389,7 +6710,8 @@ def test_document_details_children_serialization(self): document_details_children_model_json2 = document_details_children_model.to_dict() assert document_details_children_model_json2 == document_details_children_model_json -class TestModel_Enrichment(): + +class TestModel_Enrichment: """ Test Class for Enrichment """ @@ -6401,7 +6723,7 @@ def test_enrichment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['languages'] = ['testString'] enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' @@ -6409,7 +6731,7 @@ def test_enrichment_serialization(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 + enrichment_options_model['top_k'] = 0 # Construct a json representation of a Enrichment model enrichment_model_json = {} @@ -6433,7 +6755,8 @@ def test_enrichment_serialization(self): enrichment_model_json2 = enrichment_model.to_dict() assert enrichment_model_json2 == enrichment_model_json -class TestModel_EnrichmentOptions(): + +class TestModel_EnrichmentOptions: """ Test Class for EnrichmentOptions """ @@ -6452,7 +6775,7 @@ def test_enrichment_options_serialization(self): enrichment_options_model_json['classifier_id'] = 'testString' enrichment_options_model_json['model_id'] = 'testString' enrichment_options_model_json['confidence_threshold'] = 0 - enrichment_options_model_json['top_k'] = 38 + enrichment_options_model_json['top_k'] = 0 # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation enrichment_options_model = EnrichmentOptions.from_dict(enrichment_options_model_json) @@ -6469,7 +6792,8 @@ def test_enrichment_options_serialization(self): enrichment_options_model_json2 = enrichment_options_model.to_dict() assert enrichment_options_model_json2 == enrichment_options_model_json -class TestModel_Enrichments(): + +class TestModel_Enrichments: """ Test Class for Enrichments """ @@ -6481,7 +6805,7 @@ def test_enrichments_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - enrichment_options_model = {} # EnrichmentOptions + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['languages'] = ['testString'] enrichment_options_model['entity_type'] = 'testString' enrichment_options_model['regular_expression'] = 'testString' @@ -6489,9 +6813,9 @@ def test_enrichments_serialization(self): enrichment_options_model['classifier_id'] = 'testString' enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 - enrichment_options_model['top_k'] = 38 + enrichment_options_model['top_k'] = 0 - enrichment_model = {} # Enrichment + enrichment_model = {} # Enrichment enrichment_model['name'] = 'testString' enrichment_model['description'] = 'testString' enrichment_model['type'] = 'part_of_speech' @@ -6516,7 +6840,8 @@ def test_enrichments_serialization(self): enrichments_model_json2 = enrichments_model.to_dict() assert enrichments_model_json2 == enrichments_model_json -class TestModel_Expansion(): + +class TestModel_Expansion: """ Test Class for Expansion """ @@ -6546,7 +6871,8 @@ def test_expansion_serialization(self): expansion_model_json2 = expansion_model.to_dict() assert expansion_model_json2 == expansion_model_json -class TestModel_Expansions(): + +class TestModel_Expansions: """ Test Class for Expansions """ @@ -6558,7 +6884,7 @@ def test_expansions_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - expansion_model = {} # Expansion + expansion_model = {} # Expansion expansion_model['input_terms'] = ['testString'] expansion_model['expanded_terms'] = ['testString'] @@ -6581,7 +6907,8 @@ def test_expansions_serialization(self): expansions_model_json2 = expansions_model.to_dict() assert expansions_model_json2 == expansions_model_json -class TestModel_Field(): + +class TestModel_Field: """ Test Class for Field """ @@ -6609,7 +6936,8 @@ def test_field_serialization(self): field_model_json2 = field_model.to_dict() assert field_model_json2 == field_model_json -class TestModel_ListCollectionsResponse(): + +class TestModel_ListCollectionsResponse: """ Test Class for ListCollectionsResponse """ @@ -6621,7 +6949,7 @@ def test_list_collections_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - collection_model = {} # Collection + collection_model = {} # Collection collection_model['name'] = 'example' # Construct a json representation of a ListCollectionsResponse model @@ -6643,7 +6971,8 @@ def test_list_collections_response_serialization(self): list_collections_response_model_json2 = list_collections_response_model.to_dict() assert list_collections_response_model_json2 == list_collections_response_model_json -class TestModel_ListDocumentsResponse(): + +class TestModel_ListDocumentsResponse: """ Test Class for ListDocumentsResponse """ @@ -6655,13 +6984,13 @@ def test_list_documents_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice - document_details_children_model = {} # DocumentDetailsChildren + document_details_children_model = {} # DocumentDetailsChildren document_details_children_model['have_notices'] = True document_details_children_model['count'] = 38 - document_details_model = {} # DocumentDetails + document_details_model = {} # DocumentDetails document_details_model['status'] = 'available' document_details_model['notices'] = [notice_model] document_details_model['children'] = document_details_children_model @@ -6689,7 +7018,8 @@ def test_list_documents_response_serialization(self): list_documents_response_model_json2 = list_documents_response_model.to_dict() assert list_documents_response_model_json2 == list_documents_response_model_json -class TestModel_ListFieldsResponse(): + +class TestModel_ListFieldsResponse: """ Test Class for ListFieldsResponse """ @@ -6701,7 +7031,7 @@ def test_list_fields_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - field_model = {} # Field + field_model = {} # Field # Construct a json representation of a ListFieldsResponse model list_fields_response_model_json = {} @@ -6722,7 +7052,8 @@ def test_list_fields_response_serialization(self): list_fields_response_model_json2 = list_fields_response_model.to_dict() assert list_fields_response_model_json2 == list_fields_response_model_json -class TestModel_ListProjectsResponse(): + +class TestModel_ListProjectsResponse: """ Test Class for ListProjectsResponse """ @@ -6734,7 +7065,7 @@ def test_list_projects_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - project_list_details_model = {} # ProjectListDetails + project_list_details_model = {} # ProjectListDetails project_list_details_model['name'] = 'testString' project_list_details_model['type'] = 'document_retrieval' @@ -6757,7 +7088,8 @@ def test_list_projects_response_serialization(self): list_projects_response_model_json2 = list_projects_response_model.to_dict() assert list_projects_response_model_json2 == list_projects_response_model_json -class TestModel_ModelEvaluationMacroAverage(): + +class TestModel_ModelEvaluationMacroAverage: """ Test Class for ModelEvaluationMacroAverage """ @@ -6788,7 +7120,8 @@ def test_model_evaluation_macro_average_serialization(self): model_evaluation_macro_average_model_json2 = model_evaluation_macro_average_model.to_dict() assert model_evaluation_macro_average_model_json2 == model_evaluation_macro_average_model_json -class TestModel_ModelEvaluationMicroAverage(): + +class TestModel_ModelEvaluationMicroAverage: """ Test Class for ModelEvaluationMicroAverage """ @@ -6819,7 +7152,8 @@ def test_model_evaluation_micro_average_serialization(self): model_evaluation_micro_average_model_json2 = model_evaluation_micro_average_model.to_dict() assert model_evaluation_micro_average_model_json2 == model_evaluation_micro_average_model_json -class TestModel_Notice(): + +class TestModel_Notice: """ Test Class for Notice """ @@ -6847,7 +7181,8 @@ def test_notice_serialization(self): notice_model_json2 = notice_model.to_dict() assert notice_model_json2 == notice_model_json -class TestModel_PerClassModelEvaluation(): + +class TestModel_PerClassModelEvaluation: """ Test Class for PerClassModelEvaluation """ @@ -6879,7 +7214,8 @@ def test_per_class_model_evaluation_serialization(self): per_class_model_evaluation_model_json2 = per_class_model_evaluation_model.to_dict() assert per_class_model_evaluation_model_json2 == per_class_model_evaluation_model_json -class TestModel_ProjectDetails(): + +class TestModel_ProjectDetails: """ Test Class for ProjectDetails """ @@ -6891,7 +7227,7 @@ def test_project_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - default_query_params_passages_model = {} # DefaultQueryParamsPassages + default_query_params_passages_model = {} # DefaultQueryParamsPassages default_query_params_passages_model['enabled'] = True default_query_params_passages_model['count'] = 38 default_query_params_passages_model['fields'] = ['testString'] @@ -6899,16 +7235,16 @@ def test_project_details_serialization(self): default_query_params_passages_model['per_document'] = True default_query_params_passages_model['max_per_document'] = 38 - default_query_params_table_results_model = {} # DefaultQueryParamsTableResults + default_query_params_table_results_model = {} # DefaultQueryParamsTableResults default_query_params_table_results_model['enabled'] = True default_query_params_table_results_model['count'] = 38 - default_query_params_table_results_model['per_document'] = 38 + default_query_params_table_results_model['per_document'] = 0 - default_query_params_suggested_refinements_model = {} # DefaultQueryParamsSuggestedRefinements + default_query_params_suggested_refinements_model = {} # DefaultQueryParamsSuggestedRefinements default_query_params_suggested_refinements_model['enabled'] = True default_query_params_suggested_refinements_model['count'] = 38 - default_query_params_model = {} # DefaultQueryParams + default_query_params_model = {} # DefaultQueryParams default_query_params_model['collection_ids'] = ['testString'] default_query_params_model['passages'] = default_query_params_passages_model default_query_params_model['table_results'] = default_query_params_table_results_model @@ -6941,7 +7277,8 @@ def test_project_details_serialization(self): project_details_model_json2 = project_details_model.to_dict() assert project_details_model_json2 == project_details_model_json -class TestModel_ProjectListDetails(): + +class TestModel_ProjectListDetails: """ Test Class for ProjectListDetails """ @@ -6971,7 +7308,8 @@ def test_project_list_details_serialization(self): project_list_details_model_json2 = project_list_details_model.to_dict() assert project_list_details_model_json2 == project_list_details_model_json -class TestModel_ProjectListDetailsRelevancyTrainingStatus(): + +class TestModel_ProjectListDetailsRelevancyTrainingStatus: """ Test Class for ProjectListDetailsRelevancyTrainingStatus """ @@ -7008,7 +7346,8 @@ def test_project_list_details_relevancy_training_status_serialization(self): project_list_details_relevancy_training_status_model_json2 = project_list_details_relevancy_training_status_model.to_dict() assert project_list_details_relevancy_training_status_model_json2 == project_list_details_relevancy_training_status_model_json -class TestModel_QueryGroupByAggregationResult(): + +class TestModel_QueryGroupByAggregationResult: """ Test Class for QueryGroupByAggregationResult """ @@ -7025,7 +7364,7 @@ def test_query_group_by_aggregation_result_serialization(self): query_group_by_aggregation_result_model_json['relevancy'] = 72.5 query_group_by_aggregation_result_model_json['total_matching_documents'] = 38 query_group_by_aggregation_result_model_json['estimated_matching_results'] = 72.5 - query_group_by_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_group_by_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryGroupByAggregationResult by calling from_dict on the json representation query_group_by_aggregation_result_model = QueryGroupByAggregationResult.from_dict(query_group_by_aggregation_result_model_json) @@ -7042,7 +7381,8 @@ def test_query_group_by_aggregation_result_serialization(self): query_group_by_aggregation_result_model_json2 = query_group_by_aggregation_result_model.to_dict() assert query_group_by_aggregation_result_model_json2 == query_group_by_aggregation_result_model_json -class TestModel_QueryHistogramAggregationResult(): + +class TestModel_QueryHistogramAggregationResult: """ Test Class for QueryHistogramAggregationResult """ @@ -7056,7 +7396,7 @@ def test_query_histogram_aggregation_result_serialization(self): query_histogram_aggregation_result_model_json = {} query_histogram_aggregation_result_model_json['key'] = 26 query_histogram_aggregation_result_model_json['matching_results'] = 38 - query_histogram_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_histogram_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation query_histogram_aggregation_result_model = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json) @@ -7073,7 +7413,8 @@ def test_query_histogram_aggregation_result_serialization(self): query_histogram_aggregation_result_model_json2 = query_histogram_aggregation_result_model.to_dict() assert query_histogram_aggregation_result_model_json2 == query_histogram_aggregation_result_model_json -class TestModel_QueryLargePassages(): + +class TestModel_QueryLargePassages: """ Test Class for QueryLargePassages """ @@ -7092,7 +7433,7 @@ def test_query_large_passages_serialization(self): query_large_passages_model_json['count'] = 400 query_large_passages_model_json['characters'] = 50 query_large_passages_model_json['find_answers'] = False - query_large_passages_model_json['max_answers_per_passage'] = 38 + query_large_passages_model_json['max_answers_per_passage'] = 1 # Construct a model instance of QueryLargePassages by calling from_dict on the json representation query_large_passages_model = QueryLargePassages.from_dict(query_large_passages_model_json) @@ -7109,7 +7450,8 @@ def test_query_large_passages_serialization(self): query_large_passages_model_json2 = query_large_passages_model.to_dict() assert query_large_passages_model_json2 == query_large_passages_model_json -class TestModel_QueryLargeSimilar(): + +class TestModel_QueryLargeSimilar: """ Test Class for QueryLargeSimilar """ @@ -7140,7 +7482,8 @@ def test_query_large_similar_serialization(self): query_large_similar_model_json2 = query_large_similar_model.to_dict() assert query_large_similar_model_json2 == query_large_similar_model_json -class TestModel_QueryLargeSuggestedRefinements(): + +class TestModel_QueryLargeSuggestedRefinements: """ Test Class for QueryLargeSuggestedRefinements """ @@ -7170,7 +7513,8 @@ def test_query_large_suggested_refinements_serialization(self): query_large_suggested_refinements_model_json2 = query_large_suggested_refinements_model.to_dict() assert query_large_suggested_refinements_model_json2 == query_large_suggested_refinements_model_json -class TestModel_QueryLargeTableResults(): + +class TestModel_QueryLargeTableResults: """ Test Class for QueryLargeTableResults """ @@ -7200,7 +7544,8 @@ def test_query_large_table_results_serialization(self): query_large_table_results_model_json2 = query_large_table_results_model.to_dict() assert query_large_table_results_model_json2 == query_large_table_results_model_json -class TestModel_QueryNoticesResponse(): + +class TestModel_QueryNoticesResponse: """ Test Class for QueryNoticesResponse """ @@ -7212,7 +7557,7 @@ def test_query_notices_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a QueryNoticesResponse model query_notices_response_model_json = {} @@ -7234,7 +7579,8 @@ def test_query_notices_response_serialization(self): query_notices_response_model_json2 = query_notices_response_model.to_dict() assert query_notices_response_model_json2 == query_notices_response_model_json -class TestModel_QueryPairAggregationResult(): + +class TestModel_QueryPairAggregationResult: """ Test Class for QueryPairAggregationResult """ @@ -7246,7 +7592,7 @@ def test_query_pair_aggregation_result_serialization(self): # Construct a json representation of a QueryPairAggregationResult model query_pair_aggregation_result_model_json = {} - query_pair_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_pair_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryPairAggregationResult by calling from_dict on the json representation query_pair_aggregation_result_model = QueryPairAggregationResult.from_dict(query_pair_aggregation_result_model_json) @@ -7263,7 +7609,8 @@ def test_query_pair_aggregation_result_serialization(self): query_pair_aggregation_result_model_json2 = query_pair_aggregation_result_model.to_dict() assert query_pair_aggregation_result_model_json2 == query_pair_aggregation_result_model_json -class TestModel_QueryResponse(): + +class TestModel_QueryResponse: """ Test Class for QueryResponse """ @@ -7275,70 +7622,70 @@ def test_query_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['document_retrieval_source'] = 'search' query_result_metadata_model['collection_id'] = 'testString' query_result_metadata_model['confidence'] = 0 - result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' result_passage_answer_model['start_offset'] = 38 result_passage_answer_model['end_offset'] = 38 result_passage_answer_model['confidence'] = 0 - query_result_passage_model = {} # QueryResultPassage + query_result_passage_model = {} # QueryResultPassage query_result_passage_model['passage_text'] = 'testString' query_result_passage_model['start_offset'] = 38 query_result_passage_model['end_offset'] = 38 query_result_passage_model['field'] = 'testString' query_result_passage_model['answers'] = [result_passage_answer_model] - query_result_model = {} # QueryResult + query_result_model = {} # QueryResult query_result_model['document_id'] = 'testString' - query_result_model['metadata'] = {'foo': 'bar'} + query_result_model['metadata'] = {'anyKey': 'anyValue'} query_result_model['result_metadata'] = query_result_metadata_model query_result_model['document_passages'] = [query_result_passage_model] query_result_model['id'] = 'watson-generated ID' - query_term_aggregation_result_model = {} # QueryTermAggregationResult + query_term_aggregation_result_model = {} # QueryTermAggregationResult query_term_aggregation_result_model['key'] = 'active' query_term_aggregation_result_model['matching_results'] = 34 query_term_aggregation_result_model['relevancy'] = 72.5 query_term_aggregation_result_model['total_matching_documents'] = 38 query_term_aggregation_result_model['estimated_matching_results'] = 72.5 - query_term_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_term_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] - query_aggregation_model = {} # QueryAggregationQueryTermAggregation + query_aggregation_model = {} # QueryAggregationQueryTermAggregation query_aggregation_model['type'] = 'term' query_aggregation_model['field'] = 'field' query_aggregation_model['count'] = 1 query_aggregation_model['name'] = 'testString' query_aggregation_model['results'] = [query_term_aggregation_result_model] - retrieval_details_model = {} # RetrievalDetails + retrieval_details_model = {} # RetrievalDetails retrieval_details_model['document_retrieval_strategy'] = 'untrained' - query_suggested_refinement_model = {} # QuerySuggestedRefinement + query_suggested_refinement_model = {} # QuerySuggestedRefinement query_suggested_refinement_model['text'] = 'testString' - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 - table_text_location_model = {} # TableTextLocation + table_text_location_model = {} # TableTextLocation table_text_location_model['text'] = 'testString' table_text_location_model['location'] = table_element_location_model - table_headers_model = {} # TableHeaders + table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = {'foo': 'bar'} + table_headers_model['location'] = {'anyKey': 'anyValue'} table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 table_headers_model['column_index_begin'] = 26 table_headers_model['column_index_end'] = 26 - table_row_headers_model = {} # TableRowHeaders + table_row_headers_model = {} # TableRowHeaders table_row_headers_model['cell_id'] = 'testString' table_row_headers_model['location'] = table_element_location_model table_row_headers_model['text'] = 'testString' @@ -7348,9 +7695,9 @@ def test_query_response_serialization(self): table_row_headers_model['column_index_begin'] = 26 table_row_headers_model['column_index_end'] = 26 - table_column_headers_model = {} # TableColumnHeaders + table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = {'foo': 'bar'} + table_column_headers_model['location'] = {'anyKey': 'anyValue'} table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -7358,44 +7705,44 @@ def test_query_response_serialization(self): table_column_headers_model['column_index_begin'] = 26 table_column_headers_model['column_index_end'] = 26 - table_cell_key_model = {} # TableCellKey + table_cell_key_model = {} # TableCellKey table_cell_key_model['cell_id'] = 'testString' table_cell_key_model['location'] = table_element_location_model table_cell_key_model['text'] = 'testString' - table_cell_values_model = {} # TableCellValues + table_cell_values_model = {} # TableCellValues table_cell_values_model['cell_id'] = 'testString' table_cell_values_model['location'] = table_element_location_model table_cell_values_model['text'] = 'testString' - table_key_value_pairs_model = {} # TableKeyValuePairs + table_key_value_pairs_model = {} # TableKeyValuePairs table_key_value_pairs_model['key'] = table_cell_key_model table_key_value_pairs_model['value'] = [table_cell_values_model] - table_row_header_ids_model = {} # TableRowHeaderIds + table_row_header_ids_model = {} # TableRowHeaderIds table_row_header_ids_model['id'] = 'testString' - table_row_header_texts_model = {} # TableRowHeaderTexts + table_row_header_texts_model = {} # TableRowHeaderTexts table_row_header_texts_model['text'] = 'testString' - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized + table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized table_row_header_texts_normalized_model['text_normalized'] = 'testString' - table_column_header_ids_model = {} # TableColumnHeaderIds + table_column_header_ids_model = {} # TableColumnHeaderIds table_column_header_ids_model['id'] = 'testString' - table_column_header_texts_model = {} # TableColumnHeaderTexts + table_column_header_texts_model = {} # TableColumnHeaderTexts table_column_header_texts_model['text'] = 'testString' - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized + table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized table_column_header_texts_normalized_model['text_normalized'] = 'testString' - document_attribute_model = {} # DocumentAttribute + document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' document_attribute_model['location'] = table_element_location_model - table_body_cells_model = {} # TableBodyCells + table_body_cells_model = {} # TableBodyCells table_body_cells_model['cell_id'] = 'testString' table_body_cells_model['location'] = table_element_location_model table_body_cells_model['text'] = 'testString' @@ -7411,7 +7758,7 @@ def test_query_response_serialization(self): table_body_cells_model['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] table_body_cells_model['attributes'] = [document_attribute_model] - table_result_table_model = {} # TableResultTable + table_result_table_model = {} # TableResultTable table_result_table_model['location'] = table_element_location_model table_result_table_model['text'] = 'testString' table_result_table_model['section_title'] = table_text_location_model @@ -7423,7 +7770,7 @@ def test_query_response_serialization(self): table_result_table_model['body_cells'] = [table_body_cells_model] table_result_table_model['contexts'] = [table_text_location_model] - query_table_result_model = {} # QueryTableResult + query_table_result_model = {} # QueryTableResult query_table_result_model['table_id'] = 'testString' query_table_result_model['source_document_id'] = 'testString' query_table_result_model['collection_id'] = 'testString' @@ -7431,7 +7778,7 @@ def test_query_response_serialization(self): query_table_result_model['table_html_offset'] = 38 query_table_result_model['table'] = table_result_table_model - query_response_passage_model = {} # QueryResponsePassage + query_response_passage_model = {} # QueryResponsePassage query_response_passage_model['passage_text'] = 'testString' query_response_passage_model['passage_score'] = 72.5 query_response_passage_model['document_id'] = 'testString' @@ -7467,7 +7814,8 @@ def test_query_response_serialization(self): query_response_model_json2 = query_response_model.to_dict() assert query_response_model_json2 == query_response_model_json -class TestModel_QueryResponsePassage(): + +class TestModel_QueryResponsePassage: """ Test Class for QueryResponsePassage """ @@ -7479,7 +7827,7 @@ def test_query_response_passage_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' result_passage_answer_model['start_offset'] = 38 result_passage_answer_model['end_offset'] = 38 @@ -7511,7 +7859,8 @@ def test_query_response_passage_serialization(self): query_response_passage_model_json2 = query_response_passage_model.to_dict() assert query_response_passage_model_json2 == query_response_passage_model_json -class TestModel_QueryResult(): + +class TestModel_QueryResult: """ Test Class for QueryResult """ @@ -7523,18 +7872,18 @@ def test_query_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_result_metadata_model = {} # QueryResultMetadata + query_result_metadata_model = {} # QueryResultMetadata query_result_metadata_model['document_retrieval_source'] = 'search' query_result_metadata_model['collection_id'] = 'testString' query_result_metadata_model['confidence'] = 0 - result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' result_passage_answer_model['start_offset'] = 38 result_passage_answer_model['end_offset'] = 38 result_passage_answer_model['confidence'] = 0 - query_result_passage_model = {} # QueryResultPassage + query_result_passage_model = {} # QueryResultPassage query_result_passage_model['passage_text'] = 'testString' query_result_passage_model['start_offset'] = 38 query_result_passage_model['end_offset'] = 38 @@ -7544,7 +7893,7 @@ def test_query_result_serialization(self): # Construct a json representation of a QueryResult model query_result_model_json = {} query_result_model_json['document_id'] = 'testString' - query_result_model_json['metadata'] = {'foo': 'bar'} + query_result_model_json['metadata'] = {'anyKey': 'anyValue'} query_result_model_json['result_metadata'] = query_result_metadata_model query_result_model_json['document_passages'] = [query_result_passage_model] query_result_model_json['foo'] = 'testString' @@ -7574,7 +7923,8 @@ def test_query_result_serialization(self): actual_dict = query_result_model.get_properties() assert actual_dict == expected_dict -class TestModel_QueryResultMetadata(): + +class TestModel_QueryResultMetadata: """ Test Class for QueryResultMetadata """ @@ -7605,7 +7955,8 @@ def test_query_result_metadata_serialization(self): query_result_metadata_model_json2 = query_result_metadata_model.to_dict() assert query_result_metadata_model_json2 == query_result_metadata_model_json -class TestModel_QueryResultPassage(): + +class TestModel_QueryResultPassage: """ Test Class for QueryResultPassage """ @@ -7617,7 +7968,7 @@ def test_query_result_passage_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - result_passage_answer_model = {} # ResultPassageAnswer + result_passage_answer_model = {} # ResultPassageAnswer result_passage_answer_model['answer_text'] = 'testString' result_passage_answer_model['start_offset'] = 38 result_passage_answer_model['end_offset'] = 38 @@ -7646,7 +7997,8 @@ def test_query_result_passage_serialization(self): query_result_passage_model_json2 = query_result_passage_model.to_dict() assert query_result_passage_model_json2 == query_result_passage_model_json -class TestModel_QuerySuggestedRefinement(): + +class TestModel_QuerySuggestedRefinement: """ Test Class for QuerySuggestedRefinement """ @@ -7675,7 +8027,8 @@ def test_query_suggested_refinement_serialization(self): query_suggested_refinement_model_json2 = query_suggested_refinement_model.to_dict() assert query_suggested_refinement_model_json2 == query_suggested_refinement_model_json -class TestModel_QueryTableResult(): + +class TestModel_QueryTableResult: """ Test Class for QueryTableResult """ @@ -7687,24 +8040,24 @@ def test_query_table_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 - table_text_location_model = {} # TableTextLocation + table_text_location_model = {} # TableTextLocation table_text_location_model['text'] = 'testString' table_text_location_model['location'] = table_element_location_model - table_headers_model = {} # TableHeaders + table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = {'foo': 'bar'} + table_headers_model['location'] = {'anyKey': 'anyValue'} table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 table_headers_model['column_index_begin'] = 26 table_headers_model['column_index_end'] = 26 - table_row_headers_model = {} # TableRowHeaders + table_row_headers_model = {} # TableRowHeaders table_row_headers_model['cell_id'] = 'testString' table_row_headers_model['location'] = table_element_location_model table_row_headers_model['text'] = 'testString' @@ -7714,9 +8067,9 @@ def test_query_table_result_serialization(self): table_row_headers_model['column_index_begin'] = 26 table_row_headers_model['column_index_end'] = 26 - table_column_headers_model = {} # TableColumnHeaders + table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = {'foo': 'bar'} + table_column_headers_model['location'] = {'anyKey': 'anyValue'} table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -7724,44 +8077,44 @@ def test_query_table_result_serialization(self): table_column_headers_model['column_index_begin'] = 26 table_column_headers_model['column_index_end'] = 26 - table_cell_key_model = {} # TableCellKey + table_cell_key_model = {} # TableCellKey table_cell_key_model['cell_id'] = 'testString' table_cell_key_model['location'] = table_element_location_model table_cell_key_model['text'] = 'testString' - table_cell_values_model = {} # TableCellValues + table_cell_values_model = {} # TableCellValues table_cell_values_model['cell_id'] = 'testString' table_cell_values_model['location'] = table_element_location_model table_cell_values_model['text'] = 'testString' - table_key_value_pairs_model = {} # TableKeyValuePairs + table_key_value_pairs_model = {} # TableKeyValuePairs table_key_value_pairs_model['key'] = table_cell_key_model table_key_value_pairs_model['value'] = [table_cell_values_model] - table_row_header_ids_model = {} # TableRowHeaderIds + table_row_header_ids_model = {} # TableRowHeaderIds table_row_header_ids_model['id'] = 'testString' - table_row_header_texts_model = {} # TableRowHeaderTexts + table_row_header_texts_model = {} # TableRowHeaderTexts table_row_header_texts_model['text'] = 'testString' - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized + table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized table_row_header_texts_normalized_model['text_normalized'] = 'testString' - table_column_header_ids_model = {} # TableColumnHeaderIds + table_column_header_ids_model = {} # TableColumnHeaderIds table_column_header_ids_model['id'] = 'testString' - table_column_header_texts_model = {} # TableColumnHeaderTexts + table_column_header_texts_model = {} # TableColumnHeaderTexts table_column_header_texts_model['text'] = 'testString' - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized + table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized table_column_header_texts_normalized_model['text_normalized'] = 'testString' - document_attribute_model = {} # DocumentAttribute + document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' document_attribute_model['location'] = table_element_location_model - table_body_cells_model = {} # TableBodyCells + table_body_cells_model = {} # TableBodyCells table_body_cells_model['cell_id'] = 'testString' table_body_cells_model['location'] = table_element_location_model table_body_cells_model['text'] = 'testString' @@ -7777,7 +8130,7 @@ def test_query_table_result_serialization(self): table_body_cells_model['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] table_body_cells_model['attributes'] = [document_attribute_model] - table_result_table_model = {} # TableResultTable + table_result_table_model = {} # TableResultTable table_result_table_model['location'] = table_element_location_model table_result_table_model['text'] = 'testString' table_result_table_model['section_title'] = table_text_location_model @@ -7813,7 +8166,8 @@ def test_query_table_result_serialization(self): query_table_result_model_json2 = query_table_result_model.to_dict() assert query_table_result_model_json2 == query_table_result_model_json -class TestModel_QueryTermAggregationResult(): + +class TestModel_QueryTermAggregationResult: """ Test Class for QueryTermAggregationResult """ @@ -7830,7 +8184,7 @@ def test_query_term_aggregation_result_serialization(self): query_term_aggregation_result_model_json['relevancy'] = 72.5 query_term_aggregation_result_model_json['total_matching_documents'] = 38 query_term_aggregation_result_model_json['estimated_matching_results'] = 72.5 - query_term_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_term_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation query_term_aggregation_result_model = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json) @@ -7847,7 +8201,8 @@ def test_query_term_aggregation_result_serialization(self): query_term_aggregation_result_model_json2 = query_term_aggregation_result_model.to_dict() assert query_term_aggregation_result_model_json2 == query_term_aggregation_result_model_json -class TestModel_QueryTimesliceAggregationResult(): + +class TestModel_QueryTimesliceAggregationResult: """ Test Class for QueryTimesliceAggregationResult """ @@ -7862,7 +8217,7 @@ def test_query_timeslice_aggregation_result_serialization(self): query_timeslice_aggregation_result_model_json['key_as_string'] = 'testString' query_timeslice_aggregation_result_model_json['key'] = 26 query_timeslice_aggregation_result_model_json['matching_results'] = 26 - query_timeslice_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_timeslice_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation query_timeslice_aggregation_result_model = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json) @@ -7879,7 +8234,8 @@ def test_query_timeslice_aggregation_result_serialization(self): query_timeslice_aggregation_result_model_json2 = query_timeslice_aggregation_result_model.to_dict() assert query_timeslice_aggregation_result_model_json2 == query_timeslice_aggregation_result_model_json -class TestModel_QueryTopHitsAggregationResult(): + +class TestModel_QueryTopHitsAggregationResult: """ Test Class for QueryTopHitsAggregationResult """ @@ -7892,7 +8248,7 @@ def test_query_top_hits_aggregation_result_serialization(self): # Construct a json representation of a QueryTopHitsAggregationResult model query_top_hits_aggregation_result_model_json = {} query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{'foo': 'bar'}] + query_top_hits_aggregation_result_model_json['hits'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) @@ -7909,7 +8265,8 @@ def test_query_top_hits_aggregation_result_serialization(self): query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json -class TestModel_QueryTopicAggregationResult(): + +class TestModel_QueryTopicAggregationResult: """ Test Class for QueryTopicAggregationResult """ @@ -7921,7 +8278,7 @@ def test_query_topic_aggregation_result_serialization(self): # Construct a json representation of a QueryTopicAggregationResult model query_topic_aggregation_result_model_json = {} - query_topic_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_topic_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTopicAggregationResult by calling from_dict on the json representation query_topic_aggregation_result_model = QueryTopicAggregationResult.from_dict(query_topic_aggregation_result_model_json) @@ -7938,7 +8295,8 @@ def test_query_topic_aggregation_result_serialization(self): query_topic_aggregation_result_model_json2 = query_topic_aggregation_result_model.to_dict() assert query_topic_aggregation_result_model_json2 == query_topic_aggregation_result_model_json -class TestModel_QueryTrendAggregationResult(): + +class TestModel_QueryTrendAggregationResult: """ Test Class for QueryTrendAggregationResult """ @@ -7950,7 +8308,7 @@ def test_query_trend_aggregation_result_serialization(self): # Construct a json representation of a QueryTrendAggregationResult model query_trend_aggregation_result_model_json = {} - query_trend_aggregation_result_model_json['aggregations'] = [{'foo': 'bar'}] + query_trend_aggregation_result_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryTrendAggregationResult by calling from_dict on the json representation query_trend_aggregation_result_model = QueryTrendAggregationResult.from_dict(query_trend_aggregation_result_model_json) @@ -7967,7 +8325,8 @@ def test_query_trend_aggregation_result_serialization(self): query_trend_aggregation_result_model_json2 = query_trend_aggregation_result_model.to_dict() assert query_trend_aggregation_result_model_json2 == query_trend_aggregation_result_model_json -class TestModel_ResultPassageAnswer(): + +class TestModel_ResultPassageAnswer: """ Test Class for ResultPassageAnswer """ @@ -7999,7 +8358,8 @@ def test_result_passage_answer_serialization(self): result_passage_answer_model_json2 = result_passage_answer_model.to_dict() assert result_passage_answer_model_json2 == result_passage_answer_model_json -class TestModel_RetrievalDetails(): + +class TestModel_RetrievalDetails: """ Test Class for RetrievalDetails """ @@ -8028,7 +8388,8 @@ def test_retrieval_details_serialization(self): retrieval_details_model_json2 = retrieval_details_model.to_dict() assert retrieval_details_model_json2 == retrieval_details_model_json -class TestModel_StopWordList(): + +class TestModel_StopWordList: """ Test Class for StopWordList """ @@ -8057,7 +8418,8 @@ def test_stop_word_list_serialization(self): stop_word_list_model_json2 = stop_word_list_model.to_dict() assert stop_word_list_model_json2 == stop_word_list_model_json -class TestModel_TableBodyCells(): + +class TestModel_TableBodyCells: """ Test Class for TableBodyCells """ @@ -8069,29 +8431,29 @@ def test_table_body_cells_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 - table_row_header_ids_model = {} # TableRowHeaderIds + table_row_header_ids_model = {} # TableRowHeaderIds table_row_header_ids_model['id'] = 'testString' - table_row_header_texts_model = {} # TableRowHeaderTexts + table_row_header_texts_model = {} # TableRowHeaderTexts table_row_header_texts_model['text'] = 'testString' - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized + table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized table_row_header_texts_normalized_model['text_normalized'] = 'testString' - table_column_header_ids_model = {} # TableColumnHeaderIds + table_column_header_ids_model = {} # TableColumnHeaderIds table_column_header_ids_model['id'] = 'testString' - table_column_header_texts_model = {} # TableColumnHeaderTexts + table_column_header_texts_model = {} # TableColumnHeaderTexts table_column_header_texts_model['text'] = 'testString' - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized + table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized table_column_header_texts_normalized_model['text_normalized'] = 'testString' - document_attribute_model = {} # DocumentAttribute + document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' document_attribute_model['location'] = table_element_location_model @@ -8128,7 +8490,8 @@ def test_table_body_cells_serialization(self): table_body_cells_model_json2 = table_body_cells_model.to_dict() assert table_body_cells_model_json2 == table_body_cells_model_json -class TestModel_TableCellKey(): + +class TestModel_TableCellKey: """ Test Class for TableCellKey """ @@ -8140,7 +8503,7 @@ def test_table_cell_key_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 @@ -8165,7 +8528,8 @@ def test_table_cell_key_serialization(self): table_cell_key_model_json2 = table_cell_key_model.to_dict() assert table_cell_key_model_json2 == table_cell_key_model_json -class TestModel_TableCellValues(): + +class TestModel_TableCellValues: """ Test Class for TableCellValues """ @@ -8177,7 +8541,7 @@ def test_table_cell_values_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 @@ -8202,7 +8566,8 @@ def test_table_cell_values_serialization(self): table_cell_values_model_json2 = table_cell_values_model.to_dict() assert table_cell_values_model_json2 == table_cell_values_model_json -class TestModel_TableColumnHeaderIds(): + +class TestModel_TableColumnHeaderIds: """ Test Class for TableColumnHeaderIds """ @@ -8231,7 +8596,8 @@ def test_table_column_header_ids_serialization(self): table_column_header_ids_model_json2 = table_column_header_ids_model.to_dict() assert table_column_header_ids_model_json2 == table_column_header_ids_model_json -class TestModel_TableColumnHeaderTexts(): + +class TestModel_TableColumnHeaderTexts: """ Test Class for TableColumnHeaderTexts """ @@ -8260,7 +8626,8 @@ def test_table_column_header_texts_serialization(self): table_column_header_texts_model_json2 = table_column_header_texts_model.to_dict() assert table_column_header_texts_model_json2 == table_column_header_texts_model_json -class TestModel_TableColumnHeaderTextsNormalized(): + +class TestModel_TableColumnHeaderTextsNormalized: """ Test Class for TableColumnHeaderTextsNormalized """ @@ -8289,7 +8656,8 @@ def test_table_column_header_texts_normalized_serialization(self): table_column_header_texts_normalized_model_json2 = table_column_header_texts_normalized_model.to_dict() assert table_column_header_texts_normalized_model_json2 == table_column_header_texts_normalized_model_json -class TestModel_TableColumnHeaders(): + +class TestModel_TableColumnHeaders: """ Test Class for TableColumnHeaders """ @@ -8302,7 +8670,7 @@ def test_table_column_headers_serialization(self): # Construct a json representation of a TableColumnHeaders model table_column_headers_model_json = {} table_column_headers_model_json['cell_id'] = 'testString' - table_column_headers_model_json['location'] = {'foo': 'bar'} + table_column_headers_model_json['location'] = {'anyKey': 'anyValue'} table_column_headers_model_json['text'] = 'testString' table_column_headers_model_json['text_normalized'] = 'testString' table_column_headers_model_json['row_index_begin'] = 26 @@ -8325,7 +8693,8 @@ def test_table_column_headers_serialization(self): table_column_headers_model_json2 = table_column_headers_model.to_dict() assert table_column_headers_model_json2 == table_column_headers_model_json -class TestModel_TableElementLocation(): + +class TestModel_TableElementLocation: """ Test Class for TableElementLocation """ @@ -8355,7 +8724,8 @@ def test_table_element_location_serialization(self): table_element_location_model_json2 = table_element_location_model.to_dict() assert table_element_location_model_json2 == table_element_location_model_json -class TestModel_TableHeaders(): + +class TestModel_TableHeaders: """ Test Class for TableHeaders """ @@ -8368,7 +8738,7 @@ def test_table_headers_serialization(self): # Construct a json representation of a TableHeaders model table_headers_model_json = {} table_headers_model_json['cell_id'] = 'testString' - table_headers_model_json['location'] = {'foo': 'bar'} + table_headers_model_json['location'] = {'anyKey': 'anyValue'} table_headers_model_json['text'] = 'testString' table_headers_model_json['row_index_begin'] = 26 table_headers_model_json['row_index_end'] = 26 @@ -8390,7 +8760,8 @@ def test_table_headers_serialization(self): table_headers_model_json2 = table_headers_model.to_dict() assert table_headers_model_json2 == table_headers_model_json -class TestModel_TableKeyValuePairs(): + +class TestModel_TableKeyValuePairs: """ Test Class for TableKeyValuePairs """ @@ -8402,16 +8773,16 @@ def test_table_key_value_pairs_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 - table_cell_key_model = {} # TableCellKey + table_cell_key_model = {} # TableCellKey table_cell_key_model['cell_id'] = 'testString' table_cell_key_model['location'] = table_element_location_model table_cell_key_model['text'] = 'testString' - table_cell_values_model = {} # TableCellValues + table_cell_values_model = {} # TableCellValues table_cell_values_model['cell_id'] = 'testString' table_cell_values_model['location'] = table_element_location_model table_cell_values_model['text'] = 'testString' @@ -8436,7 +8807,8 @@ def test_table_key_value_pairs_serialization(self): table_key_value_pairs_model_json2 = table_key_value_pairs_model.to_dict() assert table_key_value_pairs_model_json2 == table_key_value_pairs_model_json -class TestModel_TableResultTable(): + +class TestModel_TableResultTable: """ Test Class for TableResultTable """ @@ -8448,24 +8820,24 @@ def test_table_result_table_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 - table_text_location_model = {} # TableTextLocation + table_text_location_model = {} # TableTextLocation table_text_location_model['text'] = 'testString' table_text_location_model['location'] = table_element_location_model - table_headers_model = {} # TableHeaders + table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = {'foo': 'bar'} + table_headers_model['location'] = {'anyKey': 'anyValue'} table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 table_headers_model['column_index_begin'] = 26 table_headers_model['column_index_end'] = 26 - table_row_headers_model = {} # TableRowHeaders + table_row_headers_model = {} # TableRowHeaders table_row_headers_model['cell_id'] = 'testString' table_row_headers_model['location'] = table_element_location_model table_row_headers_model['text'] = 'testString' @@ -8475,9 +8847,9 @@ def test_table_result_table_serialization(self): table_row_headers_model['column_index_begin'] = 26 table_row_headers_model['column_index_end'] = 26 - table_column_headers_model = {} # TableColumnHeaders + table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = {'foo': 'bar'} + table_column_headers_model['location'] = {'anyKey': 'anyValue'} table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -8485,44 +8857,44 @@ def test_table_result_table_serialization(self): table_column_headers_model['column_index_begin'] = 26 table_column_headers_model['column_index_end'] = 26 - table_cell_key_model = {} # TableCellKey + table_cell_key_model = {} # TableCellKey table_cell_key_model['cell_id'] = 'testString' table_cell_key_model['location'] = table_element_location_model table_cell_key_model['text'] = 'testString' - table_cell_values_model = {} # TableCellValues + table_cell_values_model = {} # TableCellValues table_cell_values_model['cell_id'] = 'testString' table_cell_values_model['location'] = table_element_location_model table_cell_values_model['text'] = 'testString' - table_key_value_pairs_model = {} # TableKeyValuePairs + table_key_value_pairs_model = {} # TableKeyValuePairs table_key_value_pairs_model['key'] = table_cell_key_model table_key_value_pairs_model['value'] = [table_cell_values_model] - table_row_header_ids_model = {} # TableRowHeaderIds + table_row_header_ids_model = {} # TableRowHeaderIds table_row_header_ids_model['id'] = 'testString' - table_row_header_texts_model = {} # TableRowHeaderTexts + table_row_header_texts_model = {} # TableRowHeaderTexts table_row_header_texts_model['text'] = 'testString' - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized + table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized table_row_header_texts_normalized_model['text_normalized'] = 'testString' - table_column_header_ids_model = {} # TableColumnHeaderIds + table_column_header_ids_model = {} # TableColumnHeaderIds table_column_header_ids_model['id'] = 'testString' - table_column_header_texts_model = {} # TableColumnHeaderTexts + table_column_header_texts_model = {} # TableColumnHeaderTexts table_column_header_texts_model['text'] = 'testString' - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized + table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized table_column_header_texts_normalized_model['text_normalized'] = 'testString' - document_attribute_model = {} # DocumentAttribute + document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' document_attribute_model['location'] = table_element_location_model - table_body_cells_model = {} # TableBodyCells + table_body_cells_model = {} # TableBodyCells table_body_cells_model['cell_id'] = 'testString' table_body_cells_model['location'] = table_element_location_model table_body_cells_model['text'] = 'testString' @@ -8566,7 +8938,8 @@ def test_table_result_table_serialization(self): table_result_table_model_json2 = table_result_table_model.to_dict() assert table_result_table_model_json2 == table_result_table_model_json -class TestModel_TableRowHeaderIds(): + +class TestModel_TableRowHeaderIds: """ Test Class for TableRowHeaderIds """ @@ -8595,7 +8968,8 @@ def test_table_row_header_ids_serialization(self): table_row_header_ids_model_json2 = table_row_header_ids_model.to_dict() assert table_row_header_ids_model_json2 == table_row_header_ids_model_json -class TestModel_TableRowHeaderTexts(): + +class TestModel_TableRowHeaderTexts: """ Test Class for TableRowHeaderTexts """ @@ -8624,7 +8998,8 @@ def test_table_row_header_texts_serialization(self): table_row_header_texts_model_json2 = table_row_header_texts_model.to_dict() assert table_row_header_texts_model_json2 == table_row_header_texts_model_json -class TestModel_TableRowHeaderTextsNormalized(): + +class TestModel_TableRowHeaderTextsNormalized: """ Test Class for TableRowHeaderTextsNormalized """ @@ -8653,7 +9028,8 @@ def test_table_row_header_texts_normalized_serialization(self): table_row_header_texts_normalized_model_json2 = table_row_header_texts_normalized_model.to_dict() assert table_row_header_texts_normalized_model_json2 == table_row_header_texts_normalized_model_json -class TestModel_TableRowHeaders(): + +class TestModel_TableRowHeaders: """ Test Class for TableRowHeaders """ @@ -8665,7 +9041,7 @@ def test_table_row_headers_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 @@ -8695,7 +9071,8 @@ def test_table_row_headers_serialization(self): table_row_headers_model_json2 = table_row_headers_model.to_dict() assert table_row_headers_model_json2 == table_row_headers_model_json -class TestModel_TableTextLocation(): + +class TestModel_TableTextLocation: """ Test Class for TableTextLocation """ @@ -8707,7 +9084,7 @@ def test_table_text_location_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - table_element_location_model = {} # TableElementLocation + table_element_location_model = {} # TableElementLocation table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 @@ -8731,7 +9108,8 @@ def test_table_text_location_serialization(self): table_text_location_model_json2 = table_text_location_model.to_dict() assert table_text_location_model_json2 == table_text_location_model_json -class TestModel_TrainingExample(): + +class TestModel_TrainingExample: """ Test Class for TrainingExample """ @@ -8762,7 +9140,8 @@ def test_training_example_serialization(self): training_example_model_json2 = training_example_model.to_dict() assert training_example_model_json2 == training_example_model_json -class TestModel_TrainingQuery(): + +class TestModel_TrainingQuery: """ Test Class for TrainingQuery """ @@ -8774,7 +9153,7 @@ def test_training_query_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_example_model = {} # TrainingExample + training_example_model = {} # TrainingExample training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 @@ -8800,7 +9179,8 @@ def test_training_query_serialization(self): training_query_model_json2 = training_query_model.to_dict() assert training_query_model_json2 == training_query_model_json -class TestModel_TrainingQuerySet(): + +class TestModel_TrainingQuerySet: """ Test Class for TrainingQuerySet """ @@ -8812,12 +9192,12 @@ def test_training_query_set_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_example_model = {} # TrainingExample + training_example_model = {} # TrainingExample training_example_model['document_id'] = 'testString' training_example_model['collection_id'] = 'testString' training_example_model['relevance'] = 38 - training_query_model = {} # TrainingQuery + training_query_model = {} # TrainingQuery training_query_model['natural_language_query'] = 'testString' training_query_model['filter'] = 'testString' training_query_model['examples'] = [training_example_model] @@ -8841,7 +9221,8 @@ def test_training_query_set_serialization(self): training_query_set_model_json2 = training_query_set_model.to_dict() assert training_query_set_model_json2 == training_query_set_model_json -class TestModel_UpdateDocumentClassifier(): + +class TestModel_UpdateDocumentClassifier: """ Test Class for UpdateDocumentClassifier """ @@ -8871,7 +9252,8 @@ def test_update_document_classifier_serialization(self): update_document_classifier_model_json2 = update_document_classifier_model.to_dict() assert update_document_classifier_model_json2 == update_document_classifier_model_json -class TestModel_QueryAggregationQueryCalculationAggregation(): + +class TestModel_QueryAggregationQueryCalculationAggregation: """ Test Class for QueryAggregationQueryCalculationAggregation """ @@ -8902,7 +9284,8 @@ def test_query_aggregation_query_calculation_aggregation_serialization(self): query_aggregation_query_calculation_aggregation_model_json2 = query_aggregation_query_calculation_aggregation_model.to_dict() assert query_aggregation_query_calculation_aggregation_model_json2 == query_aggregation_query_calculation_aggregation_model_json -class TestModel_QueryAggregationQueryFilterAggregation(): + +class TestModel_QueryAggregationQueryFilterAggregation: """ Test Class for QueryAggregationQueryFilterAggregation """ @@ -8917,7 +9300,7 @@ def test_query_aggregation_query_filter_aggregation_serialization(self): query_aggregation_query_filter_aggregation_model_json['type'] = 'filter' query_aggregation_query_filter_aggregation_model_json['match'] = 'testString' query_aggregation_query_filter_aggregation_model_json['matching_results'] = 26 - query_aggregation_query_filter_aggregation_model_json['aggregations'] = [{'foo': 'bar'}] + query_aggregation_query_filter_aggregation_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryAggregationQueryFilterAggregation by calling from_dict on the json representation query_aggregation_query_filter_aggregation_model = QueryAggregationQueryFilterAggregation.from_dict(query_aggregation_query_filter_aggregation_model_json) @@ -8934,7 +9317,8 @@ def test_query_aggregation_query_filter_aggregation_serialization(self): query_aggregation_query_filter_aggregation_model_json2 = query_aggregation_query_filter_aggregation_model.to_dict() assert query_aggregation_query_filter_aggregation_model_json2 == query_aggregation_query_filter_aggregation_model_json -class TestModel_QueryAggregationQueryGroupByAggregation(): + +class TestModel_QueryAggregationQueryGroupByAggregation: """ Test Class for QueryAggregationQueryGroupByAggregation """ @@ -8946,13 +9330,13 @@ def test_query_aggregation_query_group_by_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_group_by_aggregation_result_model = {} # QueryGroupByAggregationResult + query_group_by_aggregation_result_model = {} # QueryGroupByAggregationResult query_group_by_aggregation_result_model['key'] = 'testString' query_group_by_aggregation_result_model['matching_results'] = 38 query_group_by_aggregation_result_model['relevancy'] = 72.5 query_group_by_aggregation_result_model['total_matching_documents'] = 38 query_group_by_aggregation_result_model['estimated_matching_results'] = 72.5 - query_group_by_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_group_by_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryGroupByAggregation model query_aggregation_query_group_by_aggregation_model_json = {} @@ -8974,7 +9358,8 @@ def test_query_aggregation_query_group_by_aggregation_serialization(self): query_aggregation_query_group_by_aggregation_model_json2 = query_aggregation_query_group_by_aggregation_model.to_dict() assert query_aggregation_query_group_by_aggregation_model_json2 == query_aggregation_query_group_by_aggregation_model_json -class TestModel_QueryAggregationQueryHistogramAggregation(): + +class TestModel_QueryAggregationQueryHistogramAggregation: """ Test Class for QueryAggregationQueryHistogramAggregation """ @@ -8986,10 +9371,10 @@ def test_query_aggregation_query_histogram_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_histogram_aggregation_result_model = {} # QueryHistogramAggregationResult + query_histogram_aggregation_result_model = {} # QueryHistogramAggregationResult query_histogram_aggregation_result_model['key'] = 26 query_histogram_aggregation_result_model['matching_results'] = 38 - query_histogram_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_histogram_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryHistogramAggregation model query_aggregation_query_histogram_aggregation_model_json = {} @@ -9014,7 +9399,8 @@ def test_query_aggregation_query_histogram_aggregation_serialization(self): query_aggregation_query_histogram_aggregation_model_json2 = query_aggregation_query_histogram_aggregation_model.to_dict() assert query_aggregation_query_histogram_aggregation_model_json2 == query_aggregation_query_histogram_aggregation_model_json -class TestModel_QueryAggregationQueryNestedAggregation(): + +class TestModel_QueryAggregationQueryNestedAggregation: """ Test Class for QueryAggregationQueryNestedAggregation """ @@ -9029,7 +9415,7 @@ def test_query_aggregation_query_nested_aggregation_serialization(self): query_aggregation_query_nested_aggregation_model_json['type'] = 'nested' query_aggregation_query_nested_aggregation_model_json['path'] = 'testString' query_aggregation_query_nested_aggregation_model_json['matching_results'] = 26 - query_aggregation_query_nested_aggregation_model_json['aggregations'] = [{'foo': 'bar'}] + query_aggregation_query_nested_aggregation_model_json['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a model instance of QueryAggregationQueryNestedAggregation by calling from_dict on the json representation query_aggregation_query_nested_aggregation_model = QueryAggregationQueryNestedAggregation.from_dict(query_aggregation_query_nested_aggregation_model_json) @@ -9046,7 +9432,8 @@ def test_query_aggregation_query_nested_aggregation_serialization(self): query_aggregation_query_nested_aggregation_model_json2 = query_aggregation_query_nested_aggregation_model.to_dict() assert query_aggregation_query_nested_aggregation_model_json2 == query_aggregation_query_nested_aggregation_model_json -class TestModel_QueryAggregationQueryPairAggregation(): + +class TestModel_QueryAggregationQueryPairAggregation: """ Test Class for QueryAggregationQueryPairAggregation """ @@ -9058,8 +9445,8 @@ def test_query_aggregation_query_pair_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_pair_aggregation_result_model = {} # QueryPairAggregationResult - query_pair_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_pair_aggregation_result_model = {} # QueryPairAggregationResult + query_pair_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryPairAggregation model query_aggregation_query_pair_aggregation_model_json = {} @@ -9085,7 +9472,8 @@ def test_query_aggregation_query_pair_aggregation_serialization(self): query_aggregation_query_pair_aggregation_model_json2 = query_aggregation_query_pair_aggregation_model.to_dict() assert query_aggregation_query_pair_aggregation_model_json2 == query_aggregation_query_pair_aggregation_model_json -class TestModel_QueryAggregationQueryTermAggregation(): + +class TestModel_QueryAggregationQueryTermAggregation: """ Test Class for QueryAggregationQueryTermAggregation """ @@ -9097,13 +9485,13 @@ def test_query_aggregation_query_term_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_term_aggregation_result_model = {} # QueryTermAggregationResult + query_term_aggregation_result_model = {} # QueryTermAggregationResult query_term_aggregation_result_model['key'] = 'testString' query_term_aggregation_result_model['matching_results'] = 38 query_term_aggregation_result_model['relevancy'] = 72.5 query_term_aggregation_result_model['total_matching_documents'] = 38 query_term_aggregation_result_model['estimated_matching_results'] = 72.5 - query_term_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_term_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryTermAggregation model query_aggregation_query_term_aggregation_model_json = {} @@ -9128,7 +9516,8 @@ def test_query_aggregation_query_term_aggregation_serialization(self): query_aggregation_query_term_aggregation_model_json2 = query_aggregation_query_term_aggregation_model.to_dict() assert query_aggregation_query_term_aggregation_model_json2 == query_aggregation_query_term_aggregation_model_json -class TestModel_QueryAggregationQueryTimesliceAggregation(): + +class TestModel_QueryAggregationQueryTimesliceAggregation: """ Test Class for QueryAggregationQueryTimesliceAggregation """ @@ -9140,11 +9529,11 @@ def test_query_aggregation_query_timeslice_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_timeslice_aggregation_result_model = {} # QueryTimesliceAggregationResult + query_timeslice_aggregation_result_model = {} # QueryTimesliceAggregationResult query_timeslice_aggregation_result_model['key_as_string'] = 'testString' query_timeslice_aggregation_result_model['key'] = 26 query_timeslice_aggregation_result_model['matching_results'] = 26 - query_timeslice_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_timeslice_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryTimesliceAggregation model query_aggregation_query_timeslice_aggregation_model_json = {} @@ -9169,7 +9558,8 @@ def test_query_aggregation_query_timeslice_aggregation_serialization(self): query_aggregation_query_timeslice_aggregation_model_json2 = query_aggregation_query_timeslice_aggregation_model.to_dict() assert query_aggregation_query_timeslice_aggregation_model_json2 == query_aggregation_query_timeslice_aggregation_model_json -class TestModel_QueryAggregationQueryTopHitsAggregation(): + +class TestModel_QueryAggregationQueryTopHitsAggregation: """ Test Class for QueryAggregationQueryTopHitsAggregation """ @@ -9181,9 +9571,9 @@ def test_query_aggregation_query_top_hits_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult + query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{'foo': 'bar'}] + query_top_hits_aggregation_result_model['hits'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryTopHitsAggregation model query_aggregation_query_top_hits_aggregation_model_json = {} @@ -9207,7 +9597,8 @@ def test_query_aggregation_query_top_hits_aggregation_serialization(self): query_aggregation_query_top_hits_aggregation_model_json2 = query_aggregation_query_top_hits_aggregation_model.to_dict() assert query_aggregation_query_top_hits_aggregation_model_json2 == query_aggregation_query_top_hits_aggregation_model_json -class TestModel_QueryAggregationQueryTopicAggregation(): + +class TestModel_QueryAggregationQueryTopicAggregation: """ Test Class for QueryAggregationQueryTopicAggregation """ @@ -9219,8 +9610,8 @@ def test_query_aggregation_query_topic_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_topic_aggregation_result_model = {} # QueryTopicAggregationResult - query_topic_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_topic_aggregation_result_model = {} # QueryTopicAggregationResult + query_topic_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryTopicAggregation model query_aggregation_query_topic_aggregation_model_json = {} @@ -9246,7 +9637,8 @@ def test_query_aggregation_query_topic_aggregation_serialization(self): query_aggregation_query_topic_aggregation_model_json2 = query_aggregation_query_topic_aggregation_model.to_dict() assert query_aggregation_query_topic_aggregation_model_json2 == query_aggregation_query_topic_aggregation_model_json -class TestModel_QueryAggregationQueryTrendAggregation(): + +class TestModel_QueryAggregationQueryTrendAggregation: """ Test Class for QueryAggregationQueryTrendAggregation """ @@ -9258,8 +9650,8 @@ def test_query_aggregation_query_trend_aggregation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - query_trend_aggregation_result_model = {} # QueryTrendAggregationResult - query_trend_aggregation_result_model['aggregations'] = [{'foo': 'bar'}] + query_trend_aggregation_result_model = {} # QueryTrendAggregationResult + query_trend_aggregation_result_model['aggregations'] = [{'anyKey': 'anyValue'}] # Construct a json representation of a QueryAggregationQueryTrendAggregation model query_aggregation_query_trend_aggregation_model_json = {} diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py index fdb19dd00..2fe38ed45 100644 --- a/test/unit/test_language_translator_v3.py +++ b/test/unit/test_language_translator_v3.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2023. +# (C) Copyright IBM Corp. 2018, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -64,8 +64,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -73,7 +72,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestListLanguages(): + +class TestListLanguages: """ Test Class for list_languages """ @@ -86,16 +86,17 @@ def test_list_languages_all_params(self): # Set up mock url = preprocess_url('/v3/languages') mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_languages() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -117,17 +118,19 @@ def test_list_languages_value_error(self): # Set up mock url = preprocess_url('/v3/languages') mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_languages(**req_copy) @@ -140,6 +143,7 @@ def test_list_languages_value_error_with_retries(self): _service.disable_retries() self.test_list_languages_value_error() + # endregion ############################################################################## # End of Service: Languages @@ -150,7 +154,8 @@ def test_list_languages_value_error_with_retries(self): ############################################################################## # region -class TestTranslate(): + +class TestTranslate: """ Test Class for translate """ @@ -163,11 +168,13 @@ def test_translate_all_params(self): # Set up mock url = preprocess_url('/v3/translate') mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = ['testString'] @@ -181,7 +188,7 @@ def test_translate_all_params(self): model_id=model_id, source=source, target=target, - headers={} + headers={}, ) # Check for correct operation @@ -211,11 +218,13 @@ def test_translate_value_error(self): # Set up mock url = preprocess_url('/v3/translate') mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = ['testString'] @@ -228,7 +237,7 @@ def test_translate_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.translate(**req_copy) @@ -241,6 +250,7 @@ def test_translate_value_error_with_retries(self): _service.disable_retries() self.test_translate_value_error() + # endregion ############################################################################## # End of Service: Translation @@ -251,7 +261,8 @@ def test_translate_value_error_with_retries(self): ############################################################################## # region -class TestListIdentifiableLanguages(): + +class TestListIdentifiableLanguages: """ Test Class for list_identifiable_languages """ @@ -264,16 +275,17 @@ def test_list_identifiable_languages_all_params(self): # Set up mock url = preprocess_url('/v3/identifiable_languages') mock_response = '{"languages": [{"language": "language", "name": "name"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_identifiable_languages() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -295,17 +307,19 @@ def test_list_identifiable_languages_value_error(self): # Set up mock url = preprocess_url('/v3/identifiable_languages') mock_response = '{"languages": [{"language": "language", "name": "name"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_identifiable_languages(**req_copy) @@ -318,7 +332,8 @@ def test_list_identifiable_languages_value_error_with_retries(self): _service.disable_retries() self.test_list_identifiable_languages_value_error() -class TestIdentify(): + +class TestIdentify: """ Test Class for identify """ @@ -331,11 +346,13 @@ def test_identify_all_params(self): # Set up mock url = preprocess_url('/v3/identify') mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = 'testString' @@ -343,7 +360,7 @@ def test_identify_all_params(self): # Invoke method response = _service.identify( text, - headers={} + headers={}, ) # Check for correct operation @@ -369,11 +386,13 @@ def test_identify_value_error(self): # Set up mock url = preprocess_url('/v3/identify') mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = 'testString' @@ -383,7 +402,7 @@ def test_identify_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.identify(**req_copy) @@ -396,6 +415,7 @@ def test_identify_value_error_with_retries(self): _service.disable_retries() self.test_identify_value_error() + # endregion ############################################################################## # End of Service: Identification @@ -406,7 +426,8 @@ def test_identify_value_error_with_retries(self): ############################################################################## # region -class TestListModels(): + +class TestListModels: """ Test Class for list_models """ @@ -419,11 +440,13 @@ def test_list_models_all_params(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values source = 'testString' @@ -435,14 +458,14 @@ def test_list_models_all_params(self): source=source, target=target, default=default, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'source={}'.format(source) in query_string assert 'target={}'.format(target) in query_string @@ -465,16 +488,17 @@ def test_list_models_required_params(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -496,17 +520,19 @@ def test_list_models_value_error(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_models(**req_copy) @@ -519,7 +545,8 @@ def test_list_models_value_error_with_retries(self): _service.disable_retries() self.test_list_models_value_error() -class TestCreateModel(): + +class TestCreateModel: """ Test Class for create_model """ @@ -532,11 +559,13 @@ def test_create_model_all_params(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values base_model_id = 'testString' @@ -554,14 +583,14 @@ def test_create_model_all_params(self): parallel_corpus=parallel_corpus, parallel_corpus_content_type=parallel_corpus_content_type, name=name, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'base_model_id={}'.format(base_model_id) in query_string assert 'name={}'.format(name) in query_string @@ -583,11 +612,13 @@ def test_create_model_required_params(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values base_model_id = 'testString' @@ -595,14 +626,14 @@ def test_create_model_required_params(self): # Invoke method response = _service.create_model( base_model_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'base_model_id={}'.format(base_model_id) in query_string @@ -623,11 +654,13 @@ def test_create_model_value_error(self): # Set up mock url = preprocess_url('/v3/models') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values base_model_id = 'testString' @@ -637,7 +670,7 @@ def test_create_model_value_error(self): "base_model_id": base_model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_model(**req_copy) @@ -650,7 +683,8 @@ def test_create_model_value_error_with_retries(self): _service.disable_retries() self.test_create_model_value_error() -class TestDeleteModel(): + +class TestDeleteModel: """ Test Class for delete_model """ @@ -663,11 +697,13 @@ def test_delete_model_all_params(self): # Set up mock url = preprocess_url('/v3/models/testString') mock_response = '{"status": "status"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -675,7 +711,7 @@ def test_delete_model_all_params(self): # Invoke method response = _service.delete_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -699,11 +735,13 @@ def test_delete_model_value_error(self): # Set up mock url = preprocess_url('/v3/models/testString') mock_response = '{"status": "status"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -713,7 +751,7 @@ def test_delete_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_model(**req_copy) @@ -726,7 +764,8 @@ def test_delete_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_model_value_error() -class TestGetModel(): + +class TestGetModel: """ Test Class for get_model """ @@ -739,11 +778,13 @@ def test_get_model_all_params(self): # Set up mock url = preprocess_url('/v3/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -751,7 +792,7 @@ def test_get_model_all_params(self): # Invoke method response = _service.get_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -775,11 +816,13 @@ def test_get_model_value_error(self): # Set up mock url = preprocess_url('/v3/models/testString') mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -789,7 +832,7 @@ def test_get_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_model(**req_copy) @@ -802,6 +845,7 @@ def test_get_model_value_error_with_retries(self): _service.disable_retries() self.test_get_model_value_error() + # endregion ############################################################################## # End of Service: Models @@ -812,7 +856,8 @@ def test_get_model_value_error_with_retries(self): ############################################################################## # region -class TestListDocuments(): + +class TestListDocuments: """ Test Class for list_documents """ @@ -825,16 +870,17 @@ def test_list_documents_all_params(self): # Set up mock url = preprocess_url('/v3/documents') mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_documents() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -856,17 +902,19 @@ def test_list_documents_value_error(self): # Set up mock url = preprocess_url('/v3/documents') mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_documents(**req_copy) @@ -879,7 +927,8 @@ def test_list_documents_value_error_with_retries(self): _service.disable_retries() self.test_list_documents_value_error() -class TestTranslateDocument(): + +class TestTranslateDocument: """ Test Class for translate_document """ @@ -892,11 +941,13 @@ def test_translate_document_all_params(self): # Set up mock url = preprocess_url('/v3/documents') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values file = io.BytesIO(b'This is a mock file.').getvalue() @@ -916,7 +967,7 @@ def test_translate_document_all_params(self): source=source, target=target, document_id=document_id, - headers={} + headers={}, ) # Check for correct operation @@ -940,11 +991,13 @@ def test_translate_document_required_params(self): # Set up mock url = preprocess_url('/v3/documents') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values file = io.BytesIO(b'This is a mock file.').getvalue() @@ -954,7 +1007,7 @@ def test_translate_document_required_params(self): response = _service.translate_document( file, filename=filename, - headers={} + headers={}, ) # Check for correct operation @@ -978,11 +1031,13 @@ def test_translate_document_value_error(self): # Set up mock url = preprocess_url('/v3/documents') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) # Set up parameter values file = io.BytesIO(b'This is a mock file.').getvalue() @@ -993,7 +1048,7 @@ def test_translate_document_value_error(self): "file": file, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.translate_document(**req_copy) @@ -1006,7 +1061,8 @@ def test_translate_document_value_error_with_retries(self): _service.disable_retries() self.test_translate_document_value_error() -class TestGetDocumentStatus(): + +class TestGetDocumentStatus: """ Test Class for get_document_status """ @@ -1019,11 +1075,13 @@ def test_get_document_status_all_params(self): # Set up mock url = preprocess_url('/v3/documents/testString') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values document_id = 'testString' @@ -1031,7 +1089,7 @@ def test_get_document_status_all_params(self): # Invoke method response = _service.get_document_status( document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1055,11 +1113,13 @@ def test_get_document_status_value_error(self): # Set up mock url = preprocess_url('/v3/documents/testString') mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values document_id = 'testString' @@ -1069,7 +1129,7 @@ def test_get_document_status_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_document_status(**req_copy) @@ -1082,7 +1142,8 @@ def test_get_document_status_value_error_with_retries(self): _service.disable_retries() self.test_get_document_status_value_error() -class TestDeleteDocument(): + +class TestDeleteDocument: """ Test Class for delete_document """ @@ -1094,9 +1155,11 @@ def test_delete_document_all_params(self): """ # Set up mock url = preprocess_url('/v3/documents/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values document_id = 'testString' @@ -1104,7 +1167,7 @@ def test_delete_document_all_params(self): # Invoke method response = _service.delete_document( document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1127,9 +1190,11 @@ def test_delete_document_value_error(self): """ # Set up mock url = preprocess_url('/v3/documents/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values document_id = 'testString' @@ -1139,7 +1204,7 @@ def test_delete_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_document(**req_copy) @@ -1152,7 +1217,8 @@ def test_delete_document_value_error_with_retries(self): _service.disable_retries() self.test_delete_document_value_error() -class TestGetTranslatedDocument(): + +class TestGetTranslatedDocument: """ Test Class for get_translated_document """ @@ -1165,11 +1231,13 @@ def test_get_translated_document_all_params(self): # Set up mock url = preprocess_url('/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/powerpoint', + status=200, + ) # Set up parameter values document_id = 'testString' @@ -1179,7 +1247,7 @@ def test_get_translated_document_all_params(self): response = _service.get_translated_document( document_id, accept=accept, - headers={} + headers={}, ) # Check for correct operation @@ -1203,11 +1271,13 @@ def test_get_translated_document_required_params(self): # Set up mock url = preprocess_url('/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/powerpoint', + status=200, + ) # Set up parameter values document_id = 'testString' @@ -1215,7 +1285,7 @@ def test_get_translated_document_required_params(self): # Invoke method response = _service.get_translated_document( document_id, - headers={} + headers={}, ) # Check for correct operation @@ -1239,11 +1309,13 @@ def test_get_translated_document_value_error(self): # Set up mock url = preprocess_url('/v3/documents/testString/translated_document') mock_response = 'This is a mock binary response.' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/powerpoint', + status=200, + ) # Set up parameter values document_id = 'testString' @@ -1253,7 +1325,7 @@ def test_get_translated_document_value_error(self): "document_id": document_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_translated_document(**req_copy) @@ -1266,6 +1338,7 @@ def test_get_translated_document_value_error_with_retries(self): _service.disable_retries() self.test_get_translated_document_value_error() + # endregion ############################################################################## # End of Service: DocumentTranslation @@ -1276,7 +1349,9 @@ def test_get_translated_document_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_DeleteModelResult(): + + +class TestModel_DeleteModelResult: """ Test Class for DeleteModelResult """ @@ -1305,7 +1380,8 @@ def test_delete_model_result_serialization(self): delete_model_result_model_json2 = delete_model_result_model.to_dict() assert delete_model_result_model_json2 == delete_model_result_model_json -class TestModel_DocumentList(): + +class TestModel_DocumentList: """ Test Class for DocumentList """ @@ -1317,7 +1393,7 @@ def test_document_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_status_model = {} # DocumentStatus + document_status_model = {} # DocumentStatus document_status_model['document_id'] = 'testString' document_status_model['filename'] = 'testString' document_status_model['status'] = 'processing' @@ -1350,7 +1426,8 @@ def test_document_list_serialization(self): document_list_model_json2 = document_list_model.to_dict() assert document_list_model_json2 == document_list_model_json -class TestModel_DocumentStatus(): + +class TestModel_DocumentStatus: """ Test Class for DocumentStatus """ @@ -1390,7 +1467,8 @@ def test_document_status_serialization(self): document_status_model_json2 = document_status_model.to_dict() assert document_status_model_json2 == document_status_model_json -class TestModel_IdentifiableLanguage(): + +class TestModel_IdentifiableLanguage: """ Test Class for IdentifiableLanguage """ @@ -1420,7 +1498,8 @@ def test_identifiable_language_serialization(self): identifiable_language_model_json2 = identifiable_language_model.to_dict() assert identifiable_language_model_json2 == identifiable_language_model_json -class TestModel_IdentifiableLanguages(): + +class TestModel_IdentifiableLanguages: """ Test Class for IdentifiableLanguages """ @@ -1432,7 +1511,7 @@ def test_identifiable_languages_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - identifiable_language_model = {} # IdentifiableLanguage + identifiable_language_model = {} # IdentifiableLanguage identifiable_language_model['language'] = 'testString' identifiable_language_model['name'] = 'testString' @@ -1455,7 +1534,8 @@ def test_identifiable_languages_serialization(self): identifiable_languages_model_json2 = identifiable_languages_model.to_dict() assert identifiable_languages_model_json2 == identifiable_languages_model_json -class TestModel_IdentifiedLanguage(): + +class TestModel_IdentifiedLanguage: """ Test Class for IdentifiedLanguage """ @@ -1485,7 +1565,8 @@ def test_identified_language_serialization(self): identified_language_model_json2 = identified_language_model.to_dict() assert identified_language_model_json2 == identified_language_model_json -class TestModel_IdentifiedLanguages(): + +class TestModel_IdentifiedLanguages: """ Test Class for IdentifiedLanguages """ @@ -1497,7 +1578,7 @@ def test_identified_languages_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - identified_language_model = {} # IdentifiedLanguage + identified_language_model = {} # IdentifiedLanguage identified_language_model['language'] = 'testString' identified_language_model['confidence'] = 0 @@ -1520,7 +1601,8 @@ def test_identified_languages_serialization(self): identified_languages_model_json2 = identified_languages_model.to_dict() assert identified_languages_model_json2 == identified_languages_model_json -class TestModel_Language(): + +class TestModel_Language: """ Test Class for Language """ @@ -1557,7 +1639,8 @@ def test_language_serialization(self): language_model_json2 = language_model.to_dict() assert language_model_json2 == language_model_json -class TestModel_Languages(): + +class TestModel_Languages: """ Test Class for Languages """ @@ -1569,7 +1652,7 @@ def test_languages_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - language_model = {} # Language + language_model = {} # Language language_model['language'] = 'testString' language_model['language_name'] = 'testString' language_model['native_language_name'] = 'testString' @@ -1599,7 +1682,8 @@ def test_languages_serialization(self): languages_model_json2 = languages_model.to_dict() assert languages_model_json2 == languages_model_json -class TestModel_Translation(): + +class TestModel_Translation: """ Test Class for Translation """ @@ -1628,7 +1712,8 @@ def test_translation_serialization(self): translation_model_json2 = translation_model.to_dict() assert translation_model_json2 == translation_model_json -class TestModel_TranslationModel(): + +class TestModel_TranslationModel: """ Test Class for TranslationModel """ @@ -1666,7 +1751,8 @@ def test_translation_model_serialization(self): translation_model_model_json2 = translation_model_model.to_dict() assert translation_model_model_json2 == translation_model_model_json -class TestModel_TranslationModels(): + +class TestModel_TranslationModels: """ Test Class for TranslationModels """ @@ -1678,7 +1764,7 @@ def test_translation_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - translation_model_model = {} # TranslationModel + translation_model_model = {} # TranslationModel translation_model_model['model_id'] = 'testString' translation_model_model['name'] = 'testString' translation_model_model['source'] = 'testString' @@ -1709,7 +1795,8 @@ def test_translation_models_serialization(self): translation_models_model_json2 = translation_models_model.to_dict() assert translation_models_model_json2 == translation_models_model_json -class TestModel_TranslationResult(): + +class TestModel_TranslationResult: """ Test Class for TranslationResult """ @@ -1721,7 +1808,7 @@ def test_translation_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - translation_model = {} # Translation + translation_model = {} # Translation translation_model['translation'] = 'testString' # Construct a json representation of a TranslationResult model diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 547082976..b79c21c48 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -64,8 +64,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -73,7 +72,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestAnalyze(): + +class TestAnalyze: """ Test Class for analyze """ @@ -86,11 +86,13 @@ def test_analyze_all_params(self): # Set up mock url = preprocess_url('/v1/analyze') mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "classifications": [{"class_name": "class_name", "confidence": 10}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a ClassificationsOptions model classifications_options_model = {} @@ -98,7 +100,7 @@ def test_analyze_all_params(self): # Construct a dict representation of a ConceptsOptions model concepts_options_model = {} - concepts_options_model['limit'] = 50 + concepts_options_model['limit'] = 8 # Construct a dict representation of a EmotionOptions model emotion_options_model = {} @@ -107,7 +109,7 @@ def test_analyze_all_params(self): # Construct a dict representation of a EntitiesOptions model entities_options_model = {} - entities_options_model['limit'] = 250 + entities_options_model['limit'] = 50 entities_options_model['mentions'] = False entities_options_model['model'] = 'testString' entities_options_model['sentiment'] = False @@ -115,7 +117,7 @@ def test_analyze_all_params(self): # Construct a dict representation of a KeywordsOptions model keywords_options_model = {} - keywords_options_model['limit'] = 250 + keywords_options_model['limit'] = 50 keywords_options_model['sentiment'] = False keywords_options_model['emotion'] = False @@ -125,7 +127,7 @@ def test_analyze_all_params(self): # Construct a dict representation of a SemanticRolesOptions model semantic_roles_options_model = {} - semantic_roles_options_model['limit'] = 38 + semantic_roles_options_model['limit'] = 50 semantic_roles_options_model['keywords'] = False semantic_roles_options_model['entities'] = False @@ -136,12 +138,12 @@ def test_analyze_all_params(self): # Construct a dict representation of a SummarizationOptions model summarization_options_model = {} - summarization_options_model['limit'] = 10 + summarization_options_model['limit'] = 3 # Construct a dict representation of a CategoriesOptions model categories_options_model = {} categories_options_model['explanation'] = False - categories_options_model['limit'] = 10 + categories_options_model['limit'] = 3 categories_options_model['model'] = 'testString' # Construct a dict representation of a SyntaxOptionsTokens model @@ -161,7 +163,7 @@ def test_analyze_all_params(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = {'foo': 'bar'} + features_model['metadata'] = {'anyKey': 'anyValue'} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -193,7 +195,7 @@ def test_analyze_all_params(self): return_analyzed_text=return_analyzed_text, language=language, limit_text_characters=limit_text_characters, - headers={} + headers={}, ) # Check for correct operation @@ -229,11 +231,13 @@ def test_analyze_value_error(self): # Set up mock url = preprocess_url('/v1/analyze') mock_response = '{"language": "language", "analyzed_text": "analyzed_text", "retrieved_url": "retrieved_url", "usage": {"features": 8, "text_characters": 15, "text_units": 10}, "concepts": [{"text": "text", "relevance": 9, "dbpedia_resource": "dbpedia_resource"}], "entities": [{"type": "type", "text": "text", "relevance": 9, "confidence": 10, "mentions": [{"text": "text", "location": [8], "confidence": 10}], "count": 5, "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}, "disambiguation": {"name": "name", "dbpedia_resource": "dbpedia_resource", "subtype": ["subtype"]}}], "keywords": [{"count": 5, "relevance": 9, "text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}, "sentiment": {"score": 5}}], "categories": [{"label": "label", "score": 5, "explanation": {"relevant_text": [{"text": "text"}]}}], "classifications": [{"class_name": "class_name", "confidence": 10}], "emotion": {"document": {"emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}, "targets": [{"text": "text", "emotion": {"anger": 5, "disgust": 7, "fear": 4, "joy": 3, "sadness": 7}}]}, "metadata": {"authors": [{"name": "name"}], "publication_date": "publication_date", "title": "title", "image": "image", "feeds": [{"link": "link"}]}, "relations": [{"score": 5, "sentence": "sentence", "type": "type", "arguments": [{"entities": [{"text": "text", "type": "type"}], "location": [8], "text": "text"}]}], "semantic_roles": [{"sentence": "sentence", "subject": {"text": "text", "entities": [{"type": "type", "text": "text"}], "keywords": [{"text": "text"}]}, "action": {"text": "text", "normalized": "normalized", "verb": {"text": "text", "tense": "tense"}}, "object": {"text": "text", "keywords": [{"text": "text"}]}}], "sentiment": {"document": {"label": "label", "score": 5}, "targets": [{"text": "text", "score": 5}]}, "syntax": {"tokens": [{"text": "text", "part_of_speech": "ADJ", "location": [8], "lemma": "lemma"}], "sentences": [{"text": "text", "location": [8]}]}}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a ClassificationsOptions model classifications_options_model = {} @@ -241,7 +245,7 @@ def test_analyze_value_error(self): # Construct a dict representation of a ConceptsOptions model concepts_options_model = {} - concepts_options_model['limit'] = 50 + concepts_options_model['limit'] = 8 # Construct a dict representation of a EmotionOptions model emotion_options_model = {} @@ -250,7 +254,7 @@ def test_analyze_value_error(self): # Construct a dict representation of a EntitiesOptions model entities_options_model = {} - entities_options_model['limit'] = 250 + entities_options_model['limit'] = 50 entities_options_model['mentions'] = False entities_options_model['model'] = 'testString' entities_options_model['sentiment'] = False @@ -258,7 +262,7 @@ def test_analyze_value_error(self): # Construct a dict representation of a KeywordsOptions model keywords_options_model = {} - keywords_options_model['limit'] = 250 + keywords_options_model['limit'] = 50 keywords_options_model['sentiment'] = False keywords_options_model['emotion'] = False @@ -268,7 +272,7 @@ def test_analyze_value_error(self): # Construct a dict representation of a SemanticRolesOptions model semantic_roles_options_model = {} - semantic_roles_options_model['limit'] = 38 + semantic_roles_options_model['limit'] = 50 semantic_roles_options_model['keywords'] = False semantic_roles_options_model['entities'] = False @@ -279,12 +283,12 @@ def test_analyze_value_error(self): # Construct a dict representation of a SummarizationOptions model summarization_options_model = {} - summarization_options_model['limit'] = 10 + summarization_options_model['limit'] = 3 # Construct a dict representation of a CategoriesOptions model categories_options_model = {} categories_options_model['explanation'] = False - categories_options_model['limit'] = 10 + categories_options_model['limit'] = 3 categories_options_model['model'] = 'testString' # Construct a dict representation of a SyntaxOptionsTokens model @@ -304,7 +308,7 @@ def test_analyze_value_error(self): features_model['emotion'] = emotion_options_model features_model['entities'] = entities_options_model features_model['keywords'] = keywords_options_model - features_model['metadata'] = {'foo': 'bar'} + features_model['metadata'] = {'anyKey': 'anyValue'} features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model @@ -329,7 +333,7 @@ def test_analyze_value_error(self): "features": features, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.analyze(**req_copy) @@ -342,6 +346,7 @@ def test_analyze_value_error_with_retries(self): _service.disable_retries() self.test_analyze_value_error() + # endregion ############################################################################## # End of Service: Analyze @@ -352,7 +357,8 @@ def test_analyze_value_error_with_retries(self): ############################################################################## # region -class TestListModels(): + +class TestListModels: """ Test Class for list_models """ @@ -365,16 +371,17 @@ def test_list_models_all_params(self): # Set up mock url = preprocess_url('/v1/models') mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -396,17 +403,19 @@ def test_list_models_value_error(self): # Set up mock url = preprocess_url('/v1/models') mock_response = '{"models": [{"status": "starting", "model_id": "model_id", "language": "language", "description": "description", "workspace_id": "workspace_id", "model_version": "model_version", "version": "version", "version_description": "version_description", "created": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_models(**req_copy) @@ -419,7 +428,8 @@ def test_list_models_value_error_with_retries(self): _service.disable_retries() self.test_list_models_value_error() -class TestDeleteModel(): + +class TestDeleteModel: """ Test Class for delete_model """ @@ -432,11 +442,13 @@ def test_delete_model_all_params(self): # Set up mock url = preprocess_url('/v1/models/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -444,7 +456,7 @@ def test_delete_model_all_params(self): # Invoke method response = _service.delete_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -468,11 +480,13 @@ def test_delete_model_value_error(self): # Set up mock url = preprocess_url('/v1/models/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -482,7 +496,7 @@ def test_delete_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_model(**req_copy) @@ -495,6 +509,7 @@ def test_delete_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_model_value_error() + # endregion ############################################################################## # End of Service: ManageModels @@ -505,7 +520,8 @@ def test_delete_model_value_error_with_retries(self): ############################################################################## # region -class TestCreateCategoriesModel(): + +class TestCreateCategoriesModel: """ Test Class for create_categories_model """ @@ -517,18 +533,21 @@ def test_create_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() training_data_content_type = 'json' name = 'testString' + user_metadata = {'region': 'North America', 'latest': True} description = 'testString' model_version = 'testString' workspace_id = 'testString' @@ -540,11 +559,12 @@ def test_create_categories_model_all_params(self): training_data, training_data_content_type=training_data_content_type, name=name, + user_metadata=user_metadata, description=description, model_version=model_version, workspace_id=workspace_id, version_description=version_description, - headers={} + headers={}, ) # Check for correct operation @@ -567,24 +587,24 @@ def test_create_categories_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Invoke method response = _service.create_categories_model( language, training_data, - training_data_content_type, - headers={} + headers={}, ) # Check for correct operation @@ -607,26 +627,26 @@ def test_create_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "language": language, "training_data": training_data, - "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_categories_model(**req_copy) @@ -639,7 +659,8 @@ def test_create_categories_model_value_error_with_retries(self): _service.disable_retries() self.test_create_categories_model_value_error() -class TestListCategoriesModels(): + +class TestListCategoriesModels: """ Test Class for list_categories_models """ @@ -651,17 +672,18 @@ def test_list_categories_models_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"models": [{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_categories_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -682,18 +704,20 @@ def test_list_categories_models_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"models": [{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_categories_models(**req_copy) @@ -706,7 +730,8 @@ def test_list_categories_models_value_error_with_retries(self): _service.disable_retries() self.test_list_categories_models_value_error() -class TestGetCategoriesModel(): + +class TestGetCategoriesModel: """ Test Class for get_categories_model """ @@ -718,12 +743,14 @@ def test_get_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -731,7 +758,7 @@ def test_get_categories_model_all_params(self): # Invoke method response = _service.get_categories_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -754,12 +781,14 @@ def test_get_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -769,7 +798,7 @@ def test_get_categories_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_categories_model(**req_copy) @@ -782,7 +811,8 @@ def test_get_categories_model_value_error_with_retries(self): _service.disable_retries() self.test_get_categories_model_value_error() -class TestUpdateCategoriesModel(): + +class TestUpdateCategoriesModel: """ Test Class for update_categories_model """ @@ -794,12 +824,14 @@ def test_update_categories_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -807,6 +839,7 @@ def test_update_categories_model_all_params(self): training_data = io.BytesIO(b'This is a mock file.').getvalue() training_data_content_type = 'json' name = 'testString' + user_metadata = {'region': 'North America', 'latest': True} description = 'testString' model_version = 'testString' workspace_id = 'testString' @@ -819,11 +852,12 @@ def test_update_categories_model_all_params(self): training_data, training_data_content_type=training_data_content_type, name=name, + user_metadata=user_metadata, description=description, model_version=model_version, workspace_id=workspace_id, version_description=version_description, - headers={} + headers={}, ) # Check for correct operation @@ -846,26 +880,26 @@ def test_update_categories_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Invoke method response = _service.update_categories_model( model_id, language, training_data, - training_data_content_type, - headers={} + headers={}, ) # Check for correct operation @@ -888,28 +922,28 @@ def test_update_categories_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/categories/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "model_id": model_id, "language": language, "training_data": training_data, - "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_categories_model(**req_copy) @@ -922,7 +956,8 @@ def test_update_categories_model_value_error_with_retries(self): _service.disable_retries() self.test_update_categories_model_value_error() -class TestDeleteCategoriesModel(): + +class TestDeleteCategoriesModel: """ Test Class for delete_categories_model """ @@ -935,11 +970,13 @@ def test_delete_categories_model_all_params(self): # Set up mock url = preprocess_url('/v1/models/categories/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -947,7 +984,7 @@ def test_delete_categories_model_all_params(self): # Invoke method response = _service.delete_categories_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -971,11 +1008,13 @@ def test_delete_categories_model_value_error(self): # Set up mock url = preprocess_url('/v1/models/categories/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -985,7 +1024,7 @@ def test_delete_categories_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_categories_model(**req_copy) @@ -998,6 +1037,7 @@ def test_delete_categories_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_categories_model_value_error() + # endregion ############################################################################## # End of Service: ManageCategoriesModels @@ -1008,7 +1048,8 @@ def test_delete_categories_model_value_error_with_retries(self): ############################################################################## # region -class TestCreateClassificationsModel(): + +class TestCreateClassificationsModel: """ Test Class for create_classifications_model """ @@ -1020,12 +1061,14 @@ def test_create_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a ClassificationsTrainingParameters model classifications_training_parameters_model = {} @@ -1036,6 +1079,7 @@ def test_create_classifications_model_all_params(self): training_data = io.BytesIO(b'This is a mock file.').getvalue() training_data_content_type = 'json' name = 'testString' + user_metadata = {'region': 'North America', 'latest': True} description = 'testString' model_version = 'testString' workspace_id = 'testString' @@ -1048,12 +1092,13 @@ def test_create_classifications_model_all_params(self): training_data, training_data_content_type=training_data_content_type, name=name, + user_metadata=user_metadata, description=description, model_version=model_version, workspace_id=workspace_id, version_description=version_description, training_parameters=training_parameters, - headers={} + headers={}, ) # Check for correct operation @@ -1076,24 +1121,24 @@ def test_create_classifications_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Invoke method response = _service.create_classifications_model( language, training_data, - training_data_content_type, - headers={} + headers={}, ) # Check for correct operation @@ -1116,26 +1161,26 @@ def test_create_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "language": language, "training_data": training_data, - "training_data_content_type": training_data_content_type, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_classifications_model(**req_copy) @@ -1148,7 +1193,8 @@ def test_create_classifications_model_value_error_with_retries(self): _service.disable_retries() self.test_create_classifications_model_value_error() -class TestListClassificationsModels(): + +class TestListClassificationsModels: """ Test Class for list_classifications_models """ @@ -1160,17 +1206,18 @@ def test_list_classifications_models_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"models": [{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_classifications_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -1191,18 +1238,20 @@ def test_list_classifications_models_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications') - mock_response = '{"models": [{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"models": [{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Pass in all but one required param and check for a ValueError req_param_dict = { } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_classifications_models(**req_copy) @@ -1215,7 +1264,8 @@ def test_list_classifications_models_value_error_with_retries(self): _service.disable_retries() self.test_list_classifications_models_value_error() -class TestGetClassificationsModel(): + +class TestGetClassificationsModel: """ Test Class for get_classifications_model """ @@ -1227,12 +1277,14 @@ def test_get_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -1240,7 +1292,7 @@ def test_get_classifications_model_all_params(self): # Invoke method response = _service.get_classifications_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -1263,12 +1315,14 @@ def test_get_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -1278,7 +1332,7 @@ def test_get_classifications_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_classifications_model(**req_copy) @@ -1291,7 +1345,8 @@ def test_get_classifications_model_value_error_with_retries(self): _service.disable_retries() self.test_get_classifications_model_value_error() -class TestUpdateClassificationsModel(): + +class TestUpdateClassificationsModel: """ Test Class for update_classifications_model """ @@ -1303,12 +1358,14 @@ def test_update_classifications_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Construct a dict representation of a ClassificationsTrainingParameters model classifications_training_parameters_model = {} @@ -1320,6 +1377,7 @@ def test_update_classifications_model_all_params(self): training_data = io.BytesIO(b'This is a mock file.').getvalue() training_data_content_type = 'json' name = 'testString' + user_metadata = {'region': 'North America', 'latest': True} description = 'testString' model_version = 'testString' workspace_id = 'testString' @@ -1333,12 +1391,13 @@ def test_update_classifications_model_all_params(self): training_data, training_data_content_type=training_data_content_type, name=name, + user_metadata=user_metadata, description=description, model_version=model_version, workspace_id=workspace_id, version_description=version_description, training_parameters=training_parameters, - headers={} + headers={}, ) # Check for correct operation @@ -1361,26 +1420,26 @@ def test_update_classifications_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Invoke method response = _service.update_classifications_model( model_id, language, training_data, - training_data_content_type, - headers={} + headers={}, ) # Check for correct operation @@ -1403,28 +1462,28 @@ def test_update_classifications_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/models/classifications/testString') - mock_response = '{"name": "name", "user_metadata": {"mapKey": "unknown property type: inner"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' - responses.add(responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200) + mock_response = '{"name": "name", "user_metadata": {"anyKey": "anyValue"}, "language": "language", "description": "description", "model_version": "model_version", "workspace_id": "workspace_id", "version_description": "version_description", "features": ["features"], "status": "starting", "model_id": "model_id", "created": "2019-01-01T12:00:00.000Z", "notices": [{"message": "message"}], "last_trained": "2019-01-01T12:00:00.000Z", "last_deployed": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.PUT, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' language = 'testString' training_data = io.BytesIO(b'This is a mock file.').getvalue() - training_data_content_type = 'application/json' # Pass in all but one required param and check for a ValueError req_param_dict = { "model_id": model_id, "language": language, "training_data": training_data, - "training_data_content_type": training_data_content_type } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_classifications_model(**req_copy) @@ -1437,7 +1496,8 @@ def test_update_classifications_model_value_error_with_retries(self): _service.disable_retries() self.test_update_classifications_model_value_error() -class TestDeleteClassificationsModel(): + +class TestDeleteClassificationsModel: """ Test Class for delete_classifications_model """ @@ -1450,11 +1510,13 @@ def test_delete_classifications_model_all_params(self): # Set up mock url = preprocess_url('/v1/models/classifications/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -1462,7 +1524,7 @@ def test_delete_classifications_model_all_params(self): # Invoke method response = _service.delete_classifications_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -1486,11 +1548,13 @@ def test_delete_classifications_model_value_error(self): # Set up mock url = preprocess_url('/v1/models/classifications/testString') mock_response = '{"deleted": "deleted"}' - responses.add(responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.DELETE, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'testString' @@ -1500,7 +1564,7 @@ def test_delete_classifications_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_classifications_model(**req_copy) @@ -1513,6 +1577,7 @@ def test_delete_classifications_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_classifications_model_value_error() + # endregion ############################################################################## # End of Service: ManageClassificationsModels @@ -1523,7 +1588,9 @@ def test_delete_classifications_model_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_AnalysisResults(): + + +class TestModel_AnalysisResults: """ Test Class for AnalysisResults """ @@ -1535,37 +1602,37 @@ def test_analysis_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - analysis_results_usage_model = {} # AnalysisResultsUsage + analysis_results_usage_model = {} # AnalysisResultsUsage analysis_results_usage_model['features'] = 38 analysis_results_usage_model['text_characters'] = 38 analysis_results_usage_model['text_units'] = 38 - concepts_result_model = {} # ConceptsResult + concepts_result_model = {} # ConceptsResult concepts_result_model['text'] = 'Social network service' concepts_result_model['relevance'] = 0.92186 concepts_result_model['dbpedia_resource'] = 'http://dbpedia.org/resource/Social_network_service' - entity_mention_model = {} # EntityMention + entity_mention_model = {} # EntityMention entity_mention_model['text'] = 'testString' entity_mention_model['location'] = [38] entity_mention_model['confidence'] = 72.5 - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 72.5 emotion_scores_model['disgust'] = 72.5 emotion_scores_model['fear'] = 72.5 emotion_scores_model['joy'] = 72.5 emotion_scores_model['sadness'] = 72.5 - feature_sentiment_results_model = {} # FeatureSentimentResults + feature_sentiment_results_model = {} # FeatureSentimentResults feature_sentiment_results_model['score'] = 72.5 - disambiguation_result_model = {} # DisambiguationResult + disambiguation_result_model = {} # DisambiguationResult disambiguation_result_model['name'] = 'testString' disambiguation_result_model['dbpedia_resource'] = 'testString' disambiguation_result_model['subtype'] = ['testString'] - entities_result_model = {} # EntitiesResult + entities_result_model = {} # EntitiesResult entities_result_model['type'] = 'testString' entities_result_model['text'] = 'Social network service' entities_result_model['relevance'] = 0.92186 @@ -1576,121 +1643,121 @@ def test_analysis_results_serialization(self): entities_result_model['sentiment'] = feature_sentiment_results_model entities_result_model['disambiguation'] = disambiguation_result_model - keywords_result_model = {} # KeywordsResult + keywords_result_model = {} # KeywordsResult keywords_result_model['count'] = 1 keywords_result_model['relevance'] = 0.864624 keywords_result_model['text'] = 'curated online courses' keywords_result_model['emotion'] = emotion_scores_model keywords_result_model['sentiment'] = feature_sentiment_results_model - categories_relevant_text_model = {} # CategoriesRelevantText + categories_relevant_text_model = {} # CategoriesRelevantText categories_relevant_text_model['text'] = 'testString' - categories_result_explanation_model = {} # CategoriesResultExplanation + categories_result_explanation_model = {} # CategoriesResultExplanation categories_result_explanation_model['relevant_text'] = [categories_relevant_text_model] - categories_result_model = {} # CategoriesResult + categories_result_model = {} # CategoriesResult categories_result_model['label'] = '/technology and computing/computing/computer software and applications' categories_result_model['score'] = 0.594296 categories_result_model['explanation'] = categories_result_explanation_model - classifications_result_model = {} # ClassificationsResult + classifications_result_model = {} # ClassificationsResult classifications_result_model['class_name'] = 'temperature' classifications_result_model['confidence'] = 0.562519 - document_emotion_results_model = {} # DocumentEmotionResults + document_emotion_results_model = {} # DocumentEmotionResults document_emotion_results_model['emotion'] = emotion_scores_model - targeted_emotion_results_model = {} # TargetedEmotionResults + targeted_emotion_results_model = {} # TargetedEmotionResults targeted_emotion_results_model['text'] = 'testString' targeted_emotion_results_model['emotion'] = emotion_scores_model - emotion_result_model = {} # EmotionResult + emotion_result_model = {} # EmotionResult emotion_result_model['document'] = document_emotion_results_model emotion_result_model['targets'] = [targeted_emotion_results_model] - author_model = {} # Author + author_model = {} # Author author_model['name'] = 'testString' - feed_model = {} # Feed + feed_model = {} # Feed feed_model['link'] = 'testString' - features_results_metadata_model = {} # FeaturesResultsMetadata + features_results_metadata_model = {} # FeaturesResultsMetadata features_results_metadata_model['authors'] = [author_model] features_results_metadata_model['publication_date'] = 'testString' features_results_metadata_model['title'] = 'testString' features_results_metadata_model['image'] = 'testString' features_results_metadata_model['feeds'] = [feed_model] - relation_entity_model = {} # RelationEntity + relation_entity_model = {} # RelationEntity relation_entity_model['text'] = 'Best Actor' relation_entity_model['type'] = 'EntertainmentAward' - relation_argument_model = {} # RelationArgument + relation_argument_model = {} # RelationArgument relation_argument_model['entities'] = [relation_entity_model] relation_argument_model['location'] = [22, 32] relation_argument_model['text'] = 'Best Actor' - relations_result_model = {} # RelationsResult + relations_result_model = {} # RelationsResult relations_result_model['score'] = 0.680715 relations_result_model['sentence'] = 'Leonardo DiCaprio won Best Actor in a Leading Role for his performance.' relations_result_model['type'] = 'awardedTo' relations_result_model['arguments'] = [relation_argument_model] - semantic_roles_entity_model = {} # SemanticRolesEntity + semantic_roles_entity_model = {} # SemanticRolesEntity semantic_roles_entity_model['type'] = 'testString' semantic_roles_entity_model['text'] = 'testString' - semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model = {} # SemanticRolesKeyword semantic_roles_keyword_model['text'] = 'testString' - semantic_roles_result_subject_model = {} # SemanticRolesResultSubject + semantic_roles_result_subject_model = {} # SemanticRolesResultSubject semantic_roles_result_subject_model['text'] = 'IBM' semantic_roles_result_subject_model['entities'] = [semantic_roles_entity_model] semantic_roles_result_subject_model['keywords'] = [semantic_roles_keyword_model] - semantic_roles_verb_model = {} # SemanticRolesVerb + semantic_roles_verb_model = {} # SemanticRolesVerb semantic_roles_verb_model['text'] = 'have' semantic_roles_verb_model['tense'] = 'present' - semantic_roles_result_action_model = {} # SemanticRolesResultAction + semantic_roles_result_action_model = {} # SemanticRolesResultAction semantic_roles_result_action_model['text'] = 'has' semantic_roles_result_action_model['normalized'] = 'have' semantic_roles_result_action_model['verb'] = semantic_roles_verb_model - semantic_roles_result_object_model = {} # SemanticRolesResultObject + semantic_roles_result_object_model = {} # SemanticRolesResultObject semantic_roles_result_object_model['text'] = 'one of the largest workforces in the world' semantic_roles_result_object_model['keywords'] = [semantic_roles_keyword_model] - semantic_roles_result_model = {} # SemanticRolesResult + semantic_roles_result_model = {} # SemanticRolesResult semantic_roles_result_model['sentence'] = 'IBM has one of the largest workforces in the world' semantic_roles_result_model['subject'] = semantic_roles_result_subject_model semantic_roles_result_model['action'] = semantic_roles_result_action_model semantic_roles_result_model['object'] = semantic_roles_result_object_model - document_sentiment_results_model = {} # DocumentSentimentResults + document_sentiment_results_model = {} # DocumentSentimentResults document_sentiment_results_model['label'] = 'testString' document_sentiment_results_model['score'] = 72.5 - targeted_sentiment_results_model = {} # TargetedSentimentResults + targeted_sentiment_results_model = {} # TargetedSentimentResults targeted_sentiment_results_model['text'] = 'testString' targeted_sentiment_results_model['score'] = 72.5 - sentiment_result_model = {} # SentimentResult + sentiment_result_model = {} # SentimentResult sentiment_result_model['document'] = document_sentiment_results_model sentiment_result_model['targets'] = [targeted_sentiment_results_model] - token_result_model = {} # TokenResult + token_result_model = {} # TokenResult token_result_model['text'] = 'testString' token_result_model['part_of_speech'] = 'ADJ' token_result_model['location'] = [38] token_result_model['lemma'] = 'testString' - sentence_result_model = {} # SentenceResult + sentence_result_model = {} # SentenceResult sentence_result_model['text'] = 'testString' sentence_result_model['location'] = [38] - syntax_result_model = {} # SyntaxResult + syntax_result_model = {} # SyntaxResult syntax_result_model['tokens'] = [token_result_model] syntax_result_model['sentences'] = [sentence_result_model] @@ -1727,7 +1794,8 @@ def test_analysis_results_serialization(self): analysis_results_model_json2 = analysis_results_model.to_dict() assert analysis_results_model_json2 == analysis_results_model_json -class TestModel_AnalysisResultsUsage(): + +class TestModel_AnalysisResultsUsage: """ Test Class for AnalysisResultsUsage """ @@ -1758,7 +1826,8 @@ def test_analysis_results_usage_serialization(self): analysis_results_usage_model_json2 = analysis_results_usage_model.to_dict() assert analysis_results_usage_model_json2 == analysis_results_usage_model_json -class TestModel_Author(): + +class TestModel_Author: """ Test Class for Author """ @@ -1787,7 +1856,8 @@ def test_author_serialization(self): author_model_json2 = author_model.to_dict() assert author_model_json2 == author_model_json -class TestModel_CategoriesModel(): + +class TestModel_CategoriesModel: """ Test Class for CategoriesModel """ @@ -1799,12 +1869,12 @@ def test_categories_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a CategoriesModel model categories_model_model_json = {} categories_model_model_json['name'] = 'testString' - categories_model_model_json['user_metadata'] = {'key1': 'unknown type: dict'} + categories_model_model_json['user_metadata'] = {'region': 'North America', 'latest': True} categories_model_model_json['language'] = 'testString' categories_model_model_json['description'] = 'testString' categories_model_model_json['model_version'] = 'testString' @@ -1833,7 +1903,8 @@ def test_categories_model_serialization(self): categories_model_model_json2 = categories_model_model.to_dict() assert categories_model_model_json2 == categories_model_model_json -class TestModel_CategoriesModelList(): + +class TestModel_CategoriesModelList: """ Test Class for CategoriesModelList """ @@ -1845,11 +1916,11 @@ def test_categories_model_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice - categories_model_model = {} # CategoriesModel + categories_model_model = {} # CategoriesModel categories_model_model['name'] = 'testString' - categories_model_model['user_metadata'] = {'key1': 'unknown type: dict'} + categories_model_model['user_metadata'] = {'region': 'North America', 'latest': True} categories_model_model['language'] = 'testString' categories_model_model['description'] = 'testString' categories_model_model['model_version'] = 'testString' @@ -1882,7 +1953,8 @@ def test_categories_model_list_serialization(self): categories_model_list_model_json2 = categories_model_list_model.to_dict() assert categories_model_list_model_json2 == categories_model_list_model_json -class TestModel_CategoriesOptions(): + +class TestModel_CategoriesOptions: """ Test Class for CategoriesOptions """ @@ -1895,7 +1967,7 @@ def test_categories_options_serialization(self): # Construct a json representation of a CategoriesOptions model categories_options_model_json = {} categories_options_model_json['explanation'] = False - categories_options_model_json['limit'] = 10 + categories_options_model_json['limit'] = 3 categories_options_model_json['model'] = 'testString' # Construct a model instance of CategoriesOptions by calling from_dict on the json representation @@ -1913,7 +1985,8 @@ def test_categories_options_serialization(self): categories_options_model_json2 = categories_options_model.to_dict() assert categories_options_model_json2 == categories_options_model_json -class TestModel_CategoriesRelevantText(): + +class TestModel_CategoriesRelevantText: """ Test Class for CategoriesRelevantText """ @@ -1942,7 +2015,8 @@ def test_categories_relevant_text_serialization(self): categories_relevant_text_model_json2 = categories_relevant_text_model.to_dict() assert categories_relevant_text_model_json2 == categories_relevant_text_model_json -class TestModel_CategoriesResult(): + +class TestModel_CategoriesResult: """ Test Class for CategoriesResult """ @@ -1954,10 +2028,10 @@ def test_categories_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - categories_relevant_text_model = {} # CategoriesRelevantText + categories_relevant_text_model = {} # CategoriesRelevantText categories_relevant_text_model['text'] = 'testString' - categories_result_explanation_model = {} # CategoriesResultExplanation + categories_result_explanation_model = {} # CategoriesResultExplanation categories_result_explanation_model['relevant_text'] = [categories_relevant_text_model] # Construct a json representation of a CategoriesResult model @@ -1981,7 +2055,8 @@ def test_categories_result_serialization(self): categories_result_model_json2 = categories_result_model.to_dict() assert categories_result_model_json2 == categories_result_model_json -class TestModel_CategoriesResultExplanation(): + +class TestModel_CategoriesResultExplanation: """ Test Class for CategoriesResultExplanation """ @@ -1993,7 +2068,7 @@ def test_categories_result_explanation_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - categories_relevant_text_model = {} # CategoriesRelevantText + categories_relevant_text_model = {} # CategoriesRelevantText categories_relevant_text_model['text'] = 'testString' # Construct a json representation of a CategoriesResultExplanation model @@ -2015,7 +2090,8 @@ def test_categories_result_explanation_serialization(self): categories_result_explanation_model_json2 = categories_result_explanation_model.to_dict() assert categories_result_explanation_model_json2 == categories_result_explanation_model_json -class TestModel_ClassificationsModel(): + +class TestModel_ClassificationsModel: """ Test Class for ClassificationsModel """ @@ -2027,12 +2103,12 @@ def test_classifications_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice # Construct a json representation of a ClassificationsModel model classifications_model_model_json = {} classifications_model_model_json['name'] = 'testString' - classifications_model_model_json['user_metadata'] = {'key1': 'unknown type: dict'} + classifications_model_model_json['user_metadata'] = {'region': 'North America', 'latest': True} classifications_model_model_json['language'] = 'testString' classifications_model_model_json['description'] = 'testString' classifications_model_model_json['model_version'] = 'testString' @@ -2061,7 +2137,8 @@ def test_classifications_model_serialization(self): classifications_model_model_json2 = classifications_model_model.to_dict() assert classifications_model_model_json2 == classifications_model_model_json -class TestModel_ClassificationsModelList(): + +class TestModel_ClassificationsModelList: """ Test Class for ClassificationsModelList """ @@ -2073,11 +2150,11 @@ def test_classifications_model_list_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - notice_model = {} # Notice + notice_model = {} # Notice - classifications_model_model = {} # ClassificationsModel + classifications_model_model = {} # ClassificationsModel classifications_model_model['name'] = 'testString' - classifications_model_model['user_metadata'] = {'key1': 'unknown type: dict'} + classifications_model_model['user_metadata'] = {'region': 'North America', 'latest': True} classifications_model_model['language'] = 'testString' classifications_model_model['description'] = 'testString' classifications_model_model['model_version'] = 'testString' @@ -2110,7 +2187,8 @@ def test_classifications_model_list_serialization(self): classifications_model_list_model_json2 = classifications_model_list_model.to_dict() assert classifications_model_list_model_json2 == classifications_model_list_model_json -class TestModel_ClassificationsOptions(): + +class TestModel_ClassificationsOptions: """ Test Class for ClassificationsOptions """ @@ -2139,7 +2217,8 @@ def test_classifications_options_serialization(self): classifications_options_model_json2 = classifications_options_model.to_dict() assert classifications_options_model_json2 == classifications_options_model_json -class TestModel_ClassificationsResult(): + +class TestModel_ClassificationsResult: """ Test Class for ClassificationsResult """ @@ -2169,7 +2248,8 @@ def test_classifications_result_serialization(self): classifications_result_model_json2 = classifications_result_model.to_dict() assert classifications_result_model_json2 == classifications_result_model_json -class TestModel_ClassificationsTrainingParameters(): + +class TestModel_ClassificationsTrainingParameters: """ Test Class for ClassificationsTrainingParameters """ @@ -2198,7 +2278,8 @@ def test_classifications_training_parameters_serialization(self): classifications_training_parameters_model_json2 = classifications_training_parameters_model.to_dict() assert classifications_training_parameters_model_json2 == classifications_training_parameters_model_json -class TestModel_ConceptsOptions(): + +class TestModel_ConceptsOptions: """ Test Class for ConceptsOptions """ @@ -2210,7 +2291,7 @@ def test_concepts_options_serialization(self): # Construct a json representation of a ConceptsOptions model concepts_options_model_json = {} - concepts_options_model_json['limit'] = 50 + concepts_options_model_json['limit'] = 8 # Construct a model instance of ConceptsOptions by calling from_dict on the json representation concepts_options_model = ConceptsOptions.from_dict(concepts_options_model_json) @@ -2227,7 +2308,8 @@ def test_concepts_options_serialization(self): concepts_options_model_json2 = concepts_options_model.to_dict() assert concepts_options_model_json2 == concepts_options_model_json -class TestModel_ConceptsResult(): + +class TestModel_ConceptsResult: """ Test Class for ConceptsResult """ @@ -2258,7 +2340,8 @@ def test_concepts_result_serialization(self): concepts_result_model_json2 = concepts_result_model.to_dict() assert concepts_result_model_json2 == concepts_result_model_json -class TestModel_DeleteModelResults(): + +class TestModel_DeleteModelResults: """ Test Class for DeleteModelResults """ @@ -2287,7 +2370,8 @@ def test_delete_model_results_serialization(self): delete_model_results_model_json2 = delete_model_results_model.to_dict() assert delete_model_results_model_json2 == delete_model_results_model_json -class TestModel_DisambiguationResult(): + +class TestModel_DisambiguationResult: """ Test Class for DisambiguationResult """ @@ -2318,7 +2402,8 @@ def test_disambiguation_result_serialization(self): disambiguation_result_model_json2 = disambiguation_result_model.to_dict() assert disambiguation_result_model_json2 == disambiguation_result_model_json -class TestModel_DocumentEmotionResults(): + +class TestModel_DocumentEmotionResults: """ Test Class for DocumentEmotionResults """ @@ -2330,7 +2415,7 @@ def test_document_emotion_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 72.5 emotion_scores_model['disgust'] = 72.5 emotion_scores_model['fear'] = 72.5 @@ -2356,7 +2441,8 @@ def test_document_emotion_results_serialization(self): document_emotion_results_model_json2 = document_emotion_results_model.to_dict() assert document_emotion_results_model_json2 == document_emotion_results_model_json -class TestModel_DocumentSentimentResults(): + +class TestModel_DocumentSentimentResults: """ Test Class for DocumentSentimentResults """ @@ -2386,7 +2472,8 @@ def test_document_sentiment_results_serialization(self): document_sentiment_results_model_json2 = document_sentiment_results_model.to_dict() assert document_sentiment_results_model_json2 == document_sentiment_results_model_json -class TestModel_EmotionOptions(): + +class TestModel_EmotionOptions: """ Test Class for EmotionOptions """ @@ -2416,7 +2503,8 @@ def test_emotion_options_serialization(self): emotion_options_model_json2 = emotion_options_model.to_dict() assert emotion_options_model_json2 == emotion_options_model_json -class TestModel_EmotionResult(): + +class TestModel_EmotionResult: """ Test Class for EmotionResult """ @@ -2428,17 +2516,17 @@ def test_emotion_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 0.041796 emotion_scores_model['disgust'] = 0.022637 emotion_scores_model['fear'] = 0.033387 emotion_scores_model['joy'] = 0.563273 emotion_scores_model['sadness'] = 0.32665 - document_emotion_results_model = {} # DocumentEmotionResults + document_emotion_results_model = {} # DocumentEmotionResults document_emotion_results_model['emotion'] = emotion_scores_model - targeted_emotion_results_model = {} # TargetedEmotionResults + targeted_emotion_results_model = {} # TargetedEmotionResults targeted_emotion_results_model['text'] = 'apples' targeted_emotion_results_model['emotion'] = emotion_scores_model @@ -2462,7 +2550,8 @@ def test_emotion_result_serialization(self): emotion_result_model_json2 = emotion_result_model.to_dict() assert emotion_result_model_json2 == emotion_result_model_json -class TestModel_EmotionScores(): + +class TestModel_EmotionScores: """ Test Class for EmotionScores """ @@ -2495,7 +2584,8 @@ def test_emotion_scores_serialization(self): emotion_scores_model_json2 = emotion_scores_model.to_dict() assert emotion_scores_model_json2 == emotion_scores_model_json -class TestModel_EntitiesOptions(): + +class TestModel_EntitiesOptions: """ Test Class for EntitiesOptions """ @@ -2507,7 +2597,7 @@ def test_entities_options_serialization(self): # Construct a json representation of a EntitiesOptions model entities_options_model_json = {} - entities_options_model_json['limit'] = 250 + entities_options_model_json['limit'] = 50 entities_options_model_json['mentions'] = False entities_options_model_json['model'] = 'testString' entities_options_model_json['sentiment'] = False @@ -2528,7 +2618,8 @@ def test_entities_options_serialization(self): entities_options_model_json2 = entities_options_model.to_dict() assert entities_options_model_json2 == entities_options_model_json -class TestModel_EntitiesResult(): + +class TestModel_EntitiesResult: """ Test Class for EntitiesResult """ @@ -2540,22 +2631,22 @@ def test_entities_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - entity_mention_model = {} # EntityMention + entity_mention_model = {} # EntityMention entity_mention_model['text'] = 'testString' entity_mention_model['location'] = [38] entity_mention_model['confidence'] = 72.5 - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 72.5 emotion_scores_model['disgust'] = 72.5 emotion_scores_model['fear'] = 72.5 emotion_scores_model['joy'] = 72.5 emotion_scores_model['sadness'] = 72.5 - feature_sentiment_results_model = {} # FeatureSentimentResults + feature_sentiment_results_model = {} # FeatureSentimentResults feature_sentiment_results_model['score'] = 72.5 - disambiguation_result_model = {} # DisambiguationResult + disambiguation_result_model = {} # DisambiguationResult disambiguation_result_model['name'] = 'testString' disambiguation_result_model['dbpedia_resource'] = 'testString' disambiguation_result_model['subtype'] = ['testString'] @@ -2587,7 +2678,8 @@ def test_entities_result_serialization(self): entities_result_model_json2 = entities_result_model.to_dict() assert entities_result_model_json2 == entities_result_model_json -class TestModel_EntityMention(): + +class TestModel_EntityMention: """ Test Class for EntityMention """ @@ -2618,7 +2710,8 @@ def test_entity_mention_serialization(self): entity_mention_model_json2 = entity_mention_model.to_dict() assert entity_mention_model_json2 == entity_mention_model_json -class TestModel_FeatureSentimentResults(): + +class TestModel_FeatureSentimentResults: """ Test Class for FeatureSentimentResults """ @@ -2647,7 +2740,8 @@ def test_feature_sentiment_results_serialization(self): feature_sentiment_results_model_json2 = feature_sentiment_results_model.to_dict() assert feature_sentiment_results_model_json2 == feature_sentiment_results_model_json -class TestModel_Features(): + +class TestModel_Features: """ Test Class for Features """ @@ -2659,53 +2753,53 @@ def test_features_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - classifications_options_model = {} # ClassificationsOptions + classifications_options_model = {} # ClassificationsOptions classifications_options_model['model'] = 'testString' - concepts_options_model = {} # ConceptsOptions - concepts_options_model['limit'] = 50 + concepts_options_model = {} # ConceptsOptions + concepts_options_model['limit'] = 8 - emotion_options_model = {} # EmotionOptions + emotion_options_model = {} # EmotionOptions emotion_options_model['document'] = True emotion_options_model['targets'] = ['testString'] - entities_options_model = {} # EntitiesOptions - entities_options_model['limit'] = 250 + entities_options_model = {} # EntitiesOptions + entities_options_model['limit'] = 50 entities_options_model['mentions'] = False entities_options_model['model'] = 'testString' entities_options_model['sentiment'] = False entities_options_model['emotion'] = False - keywords_options_model = {} # KeywordsOptions - keywords_options_model['limit'] = 250 + keywords_options_model = {} # KeywordsOptions + keywords_options_model['limit'] = 50 keywords_options_model['sentiment'] = False keywords_options_model['emotion'] = False - relations_options_model = {} # RelationsOptions + relations_options_model = {} # RelationsOptions relations_options_model['model'] = 'testString' - semantic_roles_options_model = {} # SemanticRolesOptions - semantic_roles_options_model['limit'] = 38 + semantic_roles_options_model = {} # SemanticRolesOptions + semantic_roles_options_model['limit'] = 50 semantic_roles_options_model['keywords'] = False semantic_roles_options_model['entities'] = False - sentiment_options_model = {} # SentimentOptions + sentiment_options_model = {} # SentimentOptions sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - summarization_options_model = {} # SummarizationOptions - summarization_options_model['limit'] = 10 + summarization_options_model = {} # SummarizationOptions + summarization_options_model['limit'] = 3 - categories_options_model = {} # CategoriesOptions + categories_options_model = {} # CategoriesOptions categories_options_model['explanation'] = False - categories_options_model['limit'] = 10 + categories_options_model['limit'] = 3 categories_options_model['model'] = 'testString' - syntax_options_tokens_model = {} # SyntaxOptionsTokens + syntax_options_tokens_model = {} # SyntaxOptionsTokens syntax_options_tokens_model['lemma'] = True syntax_options_tokens_model['part_of_speech'] = True - syntax_options_model = {} # SyntaxOptions + syntax_options_model = {} # SyntaxOptions syntax_options_model['tokens'] = syntax_options_tokens_model syntax_options_model['sentences'] = True @@ -2716,7 +2810,7 @@ def test_features_serialization(self): features_model_json['emotion'] = emotion_options_model features_model_json['entities'] = entities_options_model features_model_json['keywords'] = keywords_options_model - features_model_json['metadata'] = {'foo': 'bar'} + features_model_json['metadata'] = {'anyKey': 'anyValue'} features_model_json['relations'] = relations_options_model features_model_json['semantic_roles'] = semantic_roles_options_model features_model_json['sentiment'] = sentiment_options_model @@ -2739,7 +2833,8 @@ def test_features_serialization(self): features_model_json2 = features_model.to_dict() assert features_model_json2 == features_model_json -class TestModel_FeaturesResultsMetadata(): + +class TestModel_FeaturesResultsMetadata: """ Test Class for FeaturesResultsMetadata """ @@ -2751,10 +2846,10 @@ def test_features_results_metadata_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - author_model = {} # Author + author_model = {} # Author author_model['name'] = 'testString' - feed_model = {} # Feed + feed_model = {} # Feed feed_model['link'] = 'testString' # Construct a json representation of a FeaturesResultsMetadata model @@ -2780,7 +2875,8 @@ def test_features_results_metadata_serialization(self): features_results_metadata_model_json2 = features_results_metadata_model.to_dict() assert features_results_metadata_model_json2 == features_results_metadata_model_json -class TestModel_Feed(): + +class TestModel_Feed: """ Test Class for Feed """ @@ -2809,7 +2905,8 @@ def test_feed_serialization(self): feed_model_json2 = feed_model.to_dict() assert feed_model_json2 == feed_model_json -class TestModel_KeywordsOptions(): + +class TestModel_KeywordsOptions: """ Test Class for KeywordsOptions """ @@ -2821,7 +2918,7 @@ def test_keywords_options_serialization(self): # Construct a json representation of a KeywordsOptions model keywords_options_model_json = {} - keywords_options_model_json['limit'] = 250 + keywords_options_model_json['limit'] = 50 keywords_options_model_json['sentiment'] = False keywords_options_model_json['emotion'] = False @@ -2840,7 +2937,8 @@ def test_keywords_options_serialization(self): keywords_options_model_json2 = keywords_options_model.to_dict() assert keywords_options_model_json2 == keywords_options_model_json -class TestModel_KeywordsResult(): + +class TestModel_KeywordsResult: """ Test Class for KeywordsResult """ @@ -2852,14 +2950,14 @@ def test_keywords_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 72.5 emotion_scores_model['disgust'] = 72.5 emotion_scores_model['fear'] = 72.5 emotion_scores_model['joy'] = 72.5 emotion_scores_model['sadness'] = 72.5 - feature_sentiment_results_model = {} # FeatureSentimentResults + feature_sentiment_results_model = {} # FeatureSentimentResults feature_sentiment_results_model['score'] = 72.5 # Construct a json representation of a KeywordsResult model @@ -2885,7 +2983,8 @@ def test_keywords_result_serialization(self): keywords_result_model_json2 = keywords_result_model.to_dict() assert keywords_result_model_json2 == keywords_result_model_json -class TestModel_ListModelsResults(): + +class TestModel_ListModelsResults: """ Test Class for ListModelsResults """ @@ -2897,7 +2996,7 @@ def test_list_models_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - model_model = {} # Model + model_model = {} # Model model_model['status'] = 'starting' model_model['model_id'] = 'testString' model_model['language'] = 'testString' @@ -2927,7 +3026,8 @@ def test_list_models_results_serialization(self): list_models_results_model_json2 = list_models_results_model.to_dict() assert list_models_results_model_json2 == list_models_results_model_json -class TestModel_Model(): + +class TestModel_Model: """ Test Class for Model """ @@ -2964,7 +3064,8 @@ def test_model_serialization(self): model_model_json2 = model_model.to_dict() assert model_model_json2 == model_model_json -class TestModel_Notice(): + +class TestModel_Notice: """ Test Class for Notice """ @@ -2992,7 +3093,8 @@ def test_notice_serialization(self): notice_model_json2 = notice_model.to_dict() assert notice_model_json2 == notice_model_json -class TestModel_RelationArgument(): + +class TestModel_RelationArgument: """ Test Class for RelationArgument """ @@ -3004,7 +3106,7 @@ def test_relation_argument_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - relation_entity_model = {} # RelationEntity + relation_entity_model = {} # RelationEntity relation_entity_model['text'] = 'testString' relation_entity_model['type'] = 'testString' @@ -3029,7 +3131,8 @@ def test_relation_argument_serialization(self): relation_argument_model_json2 = relation_argument_model.to_dict() assert relation_argument_model_json2 == relation_argument_model_json -class TestModel_RelationEntity(): + +class TestModel_RelationEntity: """ Test Class for RelationEntity """ @@ -3059,7 +3162,8 @@ def test_relation_entity_serialization(self): relation_entity_model_json2 = relation_entity_model.to_dict() assert relation_entity_model_json2 == relation_entity_model_json -class TestModel_RelationsOptions(): + +class TestModel_RelationsOptions: """ Test Class for RelationsOptions """ @@ -3088,7 +3192,8 @@ def test_relations_options_serialization(self): relations_options_model_json2 = relations_options_model.to_dict() assert relations_options_model_json2 == relations_options_model_json -class TestModel_RelationsResult(): + +class TestModel_RelationsResult: """ Test Class for RelationsResult """ @@ -3100,11 +3205,11 @@ def test_relations_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - relation_entity_model = {} # RelationEntity + relation_entity_model = {} # RelationEntity relation_entity_model['text'] = 'testString' relation_entity_model['type'] = 'testString' - relation_argument_model = {} # RelationArgument + relation_argument_model = {} # RelationArgument relation_argument_model['entities'] = [relation_entity_model] relation_argument_model['location'] = [38] relation_argument_model['text'] = 'testString' @@ -3131,7 +3236,8 @@ def test_relations_result_serialization(self): relations_result_model_json2 = relations_result_model.to_dict() assert relations_result_model_json2 == relations_result_model_json -class TestModel_SemanticRolesEntity(): + +class TestModel_SemanticRolesEntity: """ Test Class for SemanticRolesEntity """ @@ -3161,7 +3267,8 @@ def test_semantic_roles_entity_serialization(self): semantic_roles_entity_model_json2 = semantic_roles_entity_model.to_dict() assert semantic_roles_entity_model_json2 == semantic_roles_entity_model_json -class TestModel_SemanticRolesKeyword(): + +class TestModel_SemanticRolesKeyword: """ Test Class for SemanticRolesKeyword """ @@ -3190,7 +3297,8 @@ def test_semantic_roles_keyword_serialization(self): semantic_roles_keyword_model_json2 = semantic_roles_keyword_model.to_dict() assert semantic_roles_keyword_model_json2 == semantic_roles_keyword_model_json -class TestModel_SemanticRolesOptions(): + +class TestModel_SemanticRolesOptions: """ Test Class for SemanticRolesOptions """ @@ -3202,7 +3310,7 @@ def test_semantic_roles_options_serialization(self): # Construct a json representation of a SemanticRolesOptions model semantic_roles_options_model_json = {} - semantic_roles_options_model_json['limit'] = 38 + semantic_roles_options_model_json['limit'] = 50 semantic_roles_options_model_json['keywords'] = False semantic_roles_options_model_json['entities'] = False @@ -3221,7 +3329,8 @@ def test_semantic_roles_options_serialization(self): semantic_roles_options_model_json2 = semantic_roles_options_model.to_dict() assert semantic_roles_options_model_json2 == semantic_roles_options_model_json -class TestModel_SemanticRolesResult(): + +class TestModel_SemanticRolesResult: """ Test Class for SemanticRolesResult """ @@ -3233,28 +3342,28 @@ def test_semantic_roles_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - semantic_roles_entity_model = {} # SemanticRolesEntity + semantic_roles_entity_model = {} # SemanticRolesEntity semantic_roles_entity_model['type'] = 'testString' semantic_roles_entity_model['text'] = 'testString' - semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model = {} # SemanticRolesKeyword semantic_roles_keyword_model['text'] = 'testString' - semantic_roles_result_subject_model = {} # SemanticRolesResultSubject + semantic_roles_result_subject_model = {} # SemanticRolesResultSubject semantic_roles_result_subject_model['text'] = 'testString' semantic_roles_result_subject_model['entities'] = [semantic_roles_entity_model] semantic_roles_result_subject_model['keywords'] = [semantic_roles_keyword_model] - semantic_roles_verb_model = {} # SemanticRolesVerb + semantic_roles_verb_model = {} # SemanticRolesVerb semantic_roles_verb_model['text'] = 'testString' semantic_roles_verb_model['tense'] = 'testString' - semantic_roles_result_action_model = {} # SemanticRolesResultAction + semantic_roles_result_action_model = {} # SemanticRolesResultAction semantic_roles_result_action_model['text'] = 'testString' semantic_roles_result_action_model['normalized'] = 'testString' semantic_roles_result_action_model['verb'] = semantic_roles_verb_model - semantic_roles_result_object_model = {} # SemanticRolesResultObject + semantic_roles_result_object_model = {} # SemanticRolesResultObject semantic_roles_result_object_model['text'] = 'testString' semantic_roles_result_object_model['keywords'] = [semantic_roles_keyword_model] @@ -3280,7 +3389,8 @@ def test_semantic_roles_result_serialization(self): semantic_roles_result_model_json2 = semantic_roles_result_model.to_dict() assert semantic_roles_result_model_json2 == semantic_roles_result_model_json -class TestModel_SemanticRolesResultAction(): + +class TestModel_SemanticRolesResultAction: """ Test Class for SemanticRolesResultAction """ @@ -3292,7 +3402,7 @@ def test_semantic_roles_result_action_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - semantic_roles_verb_model = {} # SemanticRolesVerb + semantic_roles_verb_model = {} # SemanticRolesVerb semantic_roles_verb_model['text'] = 'testString' semantic_roles_verb_model['tense'] = 'testString' @@ -3317,7 +3427,8 @@ def test_semantic_roles_result_action_serialization(self): semantic_roles_result_action_model_json2 = semantic_roles_result_action_model.to_dict() assert semantic_roles_result_action_model_json2 == semantic_roles_result_action_model_json -class TestModel_SemanticRolesResultObject(): + +class TestModel_SemanticRolesResultObject: """ Test Class for SemanticRolesResultObject """ @@ -3329,7 +3440,7 @@ def test_semantic_roles_result_object_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model = {} # SemanticRolesKeyword semantic_roles_keyword_model['text'] = 'testString' # Construct a json representation of a SemanticRolesResultObject model @@ -3352,7 +3463,8 @@ def test_semantic_roles_result_object_serialization(self): semantic_roles_result_object_model_json2 = semantic_roles_result_object_model.to_dict() assert semantic_roles_result_object_model_json2 == semantic_roles_result_object_model_json -class TestModel_SemanticRolesResultSubject(): + +class TestModel_SemanticRolesResultSubject: """ Test Class for SemanticRolesResultSubject """ @@ -3364,11 +3476,11 @@ def test_semantic_roles_result_subject_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - semantic_roles_entity_model = {} # SemanticRolesEntity + semantic_roles_entity_model = {} # SemanticRolesEntity semantic_roles_entity_model['type'] = 'testString' semantic_roles_entity_model['text'] = 'testString' - semantic_roles_keyword_model = {} # SemanticRolesKeyword + semantic_roles_keyword_model = {} # SemanticRolesKeyword semantic_roles_keyword_model['text'] = 'testString' # Construct a json representation of a SemanticRolesResultSubject model @@ -3392,7 +3504,8 @@ def test_semantic_roles_result_subject_serialization(self): semantic_roles_result_subject_model_json2 = semantic_roles_result_subject_model.to_dict() assert semantic_roles_result_subject_model_json2 == semantic_roles_result_subject_model_json -class TestModel_SemanticRolesVerb(): + +class TestModel_SemanticRolesVerb: """ Test Class for SemanticRolesVerb """ @@ -3422,7 +3535,8 @@ def test_semantic_roles_verb_serialization(self): semantic_roles_verb_model_json2 = semantic_roles_verb_model.to_dict() assert semantic_roles_verb_model_json2 == semantic_roles_verb_model_json -class TestModel_SentenceResult(): + +class TestModel_SentenceResult: """ Test Class for SentenceResult """ @@ -3452,7 +3566,8 @@ def test_sentence_result_serialization(self): sentence_result_model_json2 = sentence_result_model.to_dict() assert sentence_result_model_json2 == sentence_result_model_json -class TestModel_SentimentOptions(): + +class TestModel_SentimentOptions: """ Test Class for SentimentOptions """ @@ -3482,7 +3597,8 @@ def test_sentiment_options_serialization(self): sentiment_options_model_json2 = sentiment_options_model.to_dict() assert sentiment_options_model_json2 == sentiment_options_model_json -class TestModel_SentimentResult(): + +class TestModel_SentimentResult: """ Test Class for SentimentResult """ @@ -3494,11 +3610,11 @@ def test_sentiment_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - document_sentiment_results_model = {} # DocumentSentimentResults + document_sentiment_results_model = {} # DocumentSentimentResults document_sentiment_results_model['label'] = 'positive' document_sentiment_results_model['score'] = 0.127034 - targeted_sentiment_results_model = {} # TargetedSentimentResults + targeted_sentiment_results_model = {} # TargetedSentimentResults targeted_sentiment_results_model['text'] = 'stocks' targeted_sentiment_results_model['score'] = 0.279964 @@ -3522,7 +3638,8 @@ def test_sentiment_result_serialization(self): sentiment_result_model_json2 = sentiment_result_model.to_dict() assert sentiment_result_model_json2 == sentiment_result_model_json -class TestModel_SummarizationOptions(): + +class TestModel_SummarizationOptions: """ Test Class for SummarizationOptions """ @@ -3534,7 +3651,7 @@ def test_summarization_options_serialization(self): # Construct a json representation of a SummarizationOptions model summarization_options_model_json = {} - summarization_options_model_json['limit'] = 10 + summarization_options_model_json['limit'] = 3 # Construct a model instance of SummarizationOptions by calling from_dict on the json representation summarization_options_model = SummarizationOptions.from_dict(summarization_options_model_json) @@ -3551,7 +3668,8 @@ def test_summarization_options_serialization(self): summarization_options_model_json2 = summarization_options_model.to_dict() assert summarization_options_model_json2 == summarization_options_model_json -class TestModel_SyntaxOptions(): + +class TestModel_SyntaxOptions: """ Test Class for SyntaxOptions """ @@ -3563,7 +3681,7 @@ def test_syntax_options_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - syntax_options_tokens_model = {} # SyntaxOptionsTokens + syntax_options_tokens_model = {} # SyntaxOptionsTokens syntax_options_tokens_model['lemma'] = True syntax_options_tokens_model['part_of_speech'] = True @@ -3587,7 +3705,8 @@ def test_syntax_options_serialization(self): syntax_options_model_json2 = syntax_options_model.to_dict() assert syntax_options_model_json2 == syntax_options_model_json -class TestModel_SyntaxOptionsTokens(): + +class TestModel_SyntaxOptionsTokens: """ Test Class for SyntaxOptionsTokens """ @@ -3617,7 +3736,8 @@ def test_syntax_options_tokens_serialization(self): syntax_options_tokens_model_json2 = syntax_options_tokens_model.to_dict() assert syntax_options_tokens_model_json2 == syntax_options_tokens_model_json -class TestModel_SyntaxResult(): + +class TestModel_SyntaxResult: """ Test Class for SyntaxResult """ @@ -3629,13 +3749,13 @@ def test_syntax_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - token_result_model = {} # TokenResult + token_result_model = {} # TokenResult token_result_model['text'] = 'testString' token_result_model['part_of_speech'] = 'ADJ' token_result_model['location'] = [38] token_result_model['lemma'] = 'testString' - sentence_result_model = {} # SentenceResult + sentence_result_model = {} # SentenceResult sentence_result_model['text'] = 'testString' sentence_result_model['location'] = [38] @@ -3659,7 +3779,8 @@ def test_syntax_result_serialization(self): syntax_result_model_json2 = syntax_result_model.to_dict() assert syntax_result_model_json2 == syntax_result_model_json -class TestModel_TargetedEmotionResults(): + +class TestModel_TargetedEmotionResults: """ Test Class for TargetedEmotionResults """ @@ -3671,7 +3792,7 @@ def test_targeted_emotion_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - emotion_scores_model = {} # EmotionScores + emotion_scores_model = {} # EmotionScores emotion_scores_model['anger'] = 72.5 emotion_scores_model['disgust'] = 72.5 emotion_scores_model['fear'] = 72.5 @@ -3698,7 +3819,8 @@ def test_targeted_emotion_results_serialization(self): targeted_emotion_results_model_json2 = targeted_emotion_results_model.to_dict() assert targeted_emotion_results_model_json2 == targeted_emotion_results_model_json -class TestModel_TargetedSentimentResults(): + +class TestModel_TargetedSentimentResults: """ Test Class for TargetedSentimentResults """ @@ -3728,7 +3850,8 @@ def test_targeted_sentiment_results_serialization(self): targeted_sentiment_results_model_json2 = targeted_sentiment_results_model.to_dict() assert targeted_sentiment_results_model_json2 == targeted_sentiment_results_model_json -class TestModel_TokenResult(): + +class TestModel_TokenResult: """ Test Class for TokenResult """ diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index b2578b8f3..3dca289f2 100644 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2023. +# (C) Copyright IBM Corp. 2015, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -69,7 +68,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestListModels(): + +class TestListModels: """ Test Class for list_models """ @@ -82,16 +82,17 @@ def test_list_models_all_params(self): # Set up mock url = preprocess_url('/v1/models') mock_response = '{"models": [{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -105,7 +106,8 @@ def test_list_models_all_params_with_retries(self): _service.disable_retries() self.test_list_models_all_params() -class TestGetModel(): + +class TestGetModel: """ Test Class for get_model """ @@ -118,11 +120,13 @@ def test_get_model_all_params(self): # Set up mock url = preprocess_url('/v1/models/ar-MS_BroadbandModel') mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'ar-MS_BroadbandModel' @@ -130,7 +134,7 @@ def test_get_model_all_params(self): # Invoke method response = _service.get_model( model_id, - headers={} + headers={}, ) # Check for correct operation @@ -154,11 +158,13 @@ def test_get_model_value_error(self): # Set up mock url = preprocess_url('/v1/models/ar-MS_BroadbandModel') mock_response = '{"name": "name", "language": "language", "rate": 4, "url": "url", "supported_features": {"custom_language_model": false, "custom_acoustic_model": false, "speaker_labels": true, "low_latency": false}, "description": "description"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values model_id = 'ar-MS_BroadbandModel' @@ -168,7 +174,7 @@ def test_get_model_value_error(self): "model_id": model_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_model(**req_copy) @@ -181,6 +187,7 @@ def test_get_model_value_error_with_retries(self): _service.disable_retries() self.test_get_model_value_error() + # endregion ############################################################################## # End of Service: Models @@ -191,7 +198,8 @@ def test_get_model_value_error_with_retries(self): ############################################################################## # region -class TestRecognize(): + +class TestRecognize: """ Test Class for recognize """ @@ -204,11 +212,13 @@ def test_recognize_all_params(self): # Set up mock url = preprocess_url('/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -218,10 +228,10 @@ def test_recognize_all_params(self): acoustic_customization_id = 'testString' base_model_version = 'testString' customization_weight = 72.5 - inactivity_timeout = 38 + inactivity_timeout = 30 keywords = ['testString'] keywords_threshold = 36.0 - max_alternatives = 38 + max_alternatives = 1 word_alternatives_threshold = 36.0 word_confidence = False timestamps = False @@ -231,12 +241,12 @@ def test_recognize_all_params(self): grammar_name = 'testString' redaction = False audio_metrics = False - end_of_phrase_silence_time = 72.5 + end_of_phrase_silence_time = 0.8 split_transcript_at_phrase_end = False - speech_detector_sensitivity = 36.0 - background_audio_suppression = 36.0 + speech_detector_sensitivity = 0.5 + background_audio_suppression = 0.0 low_latency = False - character_insertion_bias = 36.0 + character_insertion_bias = 0.0 # Invoke method response = _service.recognize( @@ -266,14 +276,14 @@ def test_recognize_all_params(self): background_audio_suppression=background_audio_suppression, low_latency=low_latency, character_insertion_bias=character_insertion_bias, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'model={}'.format(model) in query_string assert 'language_customization_id={}'.format(language_customization_id) in query_string @@ -313,11 +323,13 @@ def test_recognize_required_params(self): # Set up mock url = preprocess_url('/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -325,7 +337,7 @@ def test_recognize_required_params(self): # Invoke method response = _service.recognize( audio, - headers={} + headers={}, ) # Check for correct operation @@ -350,11 +362,13 @@ def test_recognize_value_error(self): # Set up mock url = preprocess_url('/v1/recognize') mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -364,7 +378,7 @@ def test_recognize_value_error(self): "audio": audio, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.recognize(**req_copy) @@ -377,6 +391,7 @@ def test_recognize_value_error_with_retries(self): _service.disable_retries() self.test_recognize_value_error() + # endregion ############################################################################## # End of Service: Synchronous @@ -387,7 +402,8 @@ def test_recognize_value_error_with_retries(self): ############################################################################## # region -class TestRegisterCallback(): + +class TestRegisterCallback: """ Test Class for register_callback """ @@ -400,11 +416,13 @@ def test_register_callback_all_params(self): # Set up mock url = preprocess_url('/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values callback_url = 'testString' @@ -414,14 +432,14 @@ def test_register_callback_all_params(self): response = _service.register_callback( callback_url, user_secret=user_secret, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'callback_url={}'.format(callback_url) in query_string assert 'user_secret={}'.format(user_secret) in query_string @@ -443,11 +461,13 @@ def test_register_callback_required_params(self): # Set up mock url = preprocess_url('/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values callback_url = 'testString' @@ -455,14 +475,14 @@ def test_register_callback_required_params(self): # Invoke method response = _service.register_callback( callback_url, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'callback_url={}'.format(callback_url) in query_string @@ -483,11 +503,13 @@ def test_register_callback_value_error(self): # Set up mock url = preprocess_url('/v1/register_callback') mock_response = '{"status": "created", "url": "url"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values callback_url = 'testString' @@ -497,7 +519,7 @@ def test_register_callback_value_error(self): "callback_url": callback_url, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.register_callback(**req_copy) @@ -510,7 +532,8 @@ def test_register_callback_value_error_with_retries(self): _service.disable_retries() self.test_register_callback_value_error() -class TestUnregisterCallback(): + +class TestUnregisterCallback: """ Test Class for unregister_callback """ @@ -522,9 +545,11 @@ def test_unregister_callback_all_params(self): """ # Set up mock url = preprocess_url('/v1/unregister_callback') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values callback_url = 'testString' @@ -532,14 +557,14 @@ def test_unregister_callback_all_params(self): # Invoke method response = _service.unregister_callback( callback_url, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'callback_url={}'.format(callback_url) in query_string @@ -559,9 +584,11 @@ def test_unregister_callback_value_error(self): """ # Set up mock url = preprocess_url('/v1/unregister_callback') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values callback_url = 'testString' @@ -571,7 +598,7 @@ def test_unregister_callback_value_error(self): "callback_url": callback_url, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.unregister_callback(**req_copy) @@ -584,7 +611,8 @@ def test_unregister_callback_value_error_with_retries(self): _service.disable_retries() self.test_unregister_callback_value_error() -class TestCreateJob(): + +class TestCreateJob: """ Test Class for create_job """ @@ -597,11 +625,13 @@ def test_create_job_all_params(self): # Set up mock url = preprocess_url('/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -615,10 +645,10 @@ def test_create_job_all_params(self): acoustic_customization_id = 'testString' base_model_version = 'testString' customization_weight = 72.5 - inactivity_timeout = 38 + inactivity_timeout = 30 keywords = ['testString'] keywords_threshold = 36.0 - max_alternatives = 38 + max_alternatives = 1 word_alternatives_threshold = 36.0 word_confidence = False timestamps = False @@ -628,14 +658,14 @@ def test_create_job_all_params(self): grammar_name = 'testString' redaction = False processing_metrics = False - processing_metrics_interval = 36.0 + processing_metrics_interval = 1.0 audio_metrics = False - end_of_phrase_silence_time = 72.5 + end_of_phrase_silence_time = 0.8 split_transcript_at_phrase_end = False - speech_detector_sensitivity = 36.0 - background_audio_suppression = 36.0 + speech_detector_sensitivity = 0.5 + background_audio_suppression = 0.0 low_latency = False - character_insertion_bias = 36.0 + character_insertion_bias = 0.0 # Invoke method response = _service.create_job( @@ -671,14 +701,14 @@ def test_create_job_all_params(self): background_audio_suppression=background_audio_suppression, low_latency=low_latency, character_insertion_bias=character_insertion_bias, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'model={}'.format(model) in query_string assert 'callback_url={}'.format(callback_url) in query_string @@ -723,11 +753,13 @@ def test_create_job_required_params(self): # Set up mock url = preprocess_url('/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -735,7 +767,7 @@ def test_create_job_required_params(self): # Invoke method response = _service.create_job( audio, - headers={} + headers={}, ) # Check for correct operation @@ -760,11 +792,13 @@ def test_create_job_value_error(self): # Set up mock url = preprocess_url('/v1/recognitions') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values audio = io.BytesIO(b'This is a mock file.').getvalue() @@ -774,7 +808,7 @@ def test_create_job_value_error(self): "audio": audio, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_job(**req_copy) @@ -787,7 +821,8 @@ def test_create_job_value_error_with_retries(self): _service.disable_retries() self.test_create_job_value_error() -class TestCheckJobs(): + +class TestCheckJobs: """ Test Class for check_jobs """ @@ -800,16 +835,17 @@ def test_check_jobs_all_params(self): # Set up mock url = preprocess_url('/v1/recognitions') mock_response = '{"recognitions": [{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.check_jobs() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -823,7 +859,8 @@ def test_check_jobs_all_params_with_retries(self): _service.disable_retries() self.test_check_jobs_all_params() -class TestCheckJob(): + +class TestCheckJob: """ Test Class for check_job """ @@ -836,11 +873,13 @@ def test_check_job_all_params(self): # Set up mock url = preprocess_url('/v1/recognitions/testString') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values id = 'testString' @@ -848,7 +887,7 @@ def test_check_job_all_params(self): # Invoke method response = _service.check_job( id, - headers={} + headers={}, ) # Check for correct operation @@ -872,11 +911,13 @@ def test_check_job_value_error(self): # Set up mock url = preprocess_url('/v1/recognitions/testString') mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values id = 'testString' @@ -886,7 +927,7 @@ def test_check_job_value_error(self): "id": id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.check_job(**req_copy) @@ -899,7 +940,8 @@ def test_check_job_value_error_with_retries(self): _service.disable_retries() self.test_check_job_value_error() -class TestDeleteJob(): + +class TestDeleteJob: """ Test Class for delete_job """ @@ -911,9 +953,11 @@ def test_delete_job_all_params(self): """ # Set up mock url = preprocess_url('/v1/recognitions/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values id = 'testString' @@ -921,7 +965,7 @@ def test_delete_job_all_params(self): # Invoke method response = _service.delete_job( id, - headers={} + headers={}, ) # Check for correct operation @@ -944,9 +988,11 @@ def test_delete_job_value_error(self): """ # Set up mock url = preprocess_url('/v1/recognitions/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values id = 'testString' @@ -956,7 +1002,7 @@ def test_delete_job_value_error(self): "id": id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_job(**req_copy) @@ -969,6 +1015,7 @@ def test_delete_job_value_error_with_retries(self): _service.disable_retries() self.test_delete_job_value_error() + # endregion ############################################################################## # End of Service: Asynchronous @@ -979,7 +1026,8 @@ def test_delete_job_value_error_with_retries(self): ############################################################################## # region -class TestCreateLanguageModel(): + +class TestCreateLanguageModel: """ Test Class for create_language_model """ @@ -992,11 +1040,13 @@ def test_create_language_model_all_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -1010,7 +1060,7 @@ def test_create_language_model_all_params(self): base_model_name, dialect=dialect, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -1040,11 +1090,13 @@ def test_create_language_model_value_error(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -1058,7 +1110,7 @@ def test_create_language_model_value_error(self): "base_model_name": base_model_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_language_model(**req_copy) @@ -1071,7 +1123,8 @@ def test_create_language_model_value_error_with_retries(self): _service.disable_retries() self.test_create_language_model_value_error() -class TestListLanguageModels(): + +class TestListLanguageModels: """ Test Class for list_language_models """ @@ -1084,11 +1137,13 @@ def test_list_language_models_all_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values language = 'ar-MS' @@ -1096,14 +1151,14 @@ def test_list_language_models_all_params(self): # Invoke method response = _service.list_language_models( language=language, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'language={}'.format(language) in query_string @@ -1124,16 +1179,17 @@ def test_list_language_models_required_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_language_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -1147,7 +1203,8 @@ def test_list_language_models_required_params_with_retries(self): _service.disable_retries() self.test_list_language_models_required_params() -class TestGetLanguageModel(): + +class TestGetLanguageModel: """ Test Class for get_language_model """ @@ -1160,11 +1217,13 @@ def test_get_language_model_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1172,7 +1231,7 @@ def test_get_language_model_all_params(self): # Invoke method response = _service.get_language_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1196,11 +1255,13 @@ def test_get_language_model_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "dialect": "dialect", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "error": "error", "warnings": "warnings"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1210,7 +1271,7 @@ def test_get_language_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_language_model(**req_copy) @@ -1223,7 +1284,8 @@ def test_get_language_model_value_error_with_retries(self): _service.disable_retries() self.test_get_language_model_value_error() -class TestDeleteLanguageModel(): + +class TestDeleteLanguageModel: """ Test Class for delete_language_model """ @@ -1235,9 +1297,11 @@ def test_delete_language_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1245,7 +1309,7 @@ def test_delete_language_model_all_params(self): # Invoke method response = _service.delete_language_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1268,9 +1332,11 @@ def test_delete_language_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1280,7 +1346,7 @@ def test_delete_language_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_language_model(**req_copy) @@ -1293,7 +1359,8 @@ def test_delete_language_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_language_model_value_error() -class TestTrainLanguageModel(): + +class TestTrainLanguageModel: """ Test Class for train_language_model """ @@ -1306,11 +1373,13 @@ def test_train_language_model_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1324,14 +1393,14 @@ def test_train_language_model_all_params(self): word_type_to_add=word_type_to_add, customization_weight=customization_weight, strict=strict, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'word_type_to_add={}'.format(word_type_to_add) in query_string assert 'customization_weight={}'.format(customization_weight) in query_string @@ -1354,11 +1423,13 @@ def test_train_language_model_required_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1366,7 +1437,7 @@ def test_train_language_model_required_params(self): # Invoke method response = _service.train_language_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1390,11 +1461,13 @@ def test_train_language_model_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1404,7 +1477,7 @@ def test_train_language_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.train_language_model(**req_copy) @@ -1417,7 +1490,8 @@ def test_train_language_model_value_error_with_retries(self): _service.disable_retries() self.test_train_language_model_value_error() -class TestResetLanguageModel(): + +class TestResetLanguageModel: """ Test Class for reset_language_model """ @@ -1429,9 +1503,11 @@ def test_reset_language_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/reset') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1439,7 +1515,7 @@ def test_reset_language_model_all_params(self): # Invoke method response = _service.reset_language_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1462,9 +1538,11 @@ def test_reset_language_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/reset') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1474,7 +1552,7 @@ def test_reset_language_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.reset_language_model(**req_copy) @@ -1487,7 +1565,8 @@ def test_reset_language_model_value_error_with_retries(self): _service.disable_retries() self.test_reset_language_model_value_error() -class TestUpgradeLanguageModel(): + +class TestUpgradeLanguageModel: """ Test Class for upgrade_language_model """ @@ -1499,9 +1578,11 @@ def test_upgrade_language_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/upgrade_model') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1509,7 +1590,7 @@ def test_upgrade_language_model_all_params(self): # Invoke method response = _service.upgrade_language_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1532,9 +1613,11 @@ def test_upgrade_language_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/upgrade_model') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1544,7 +1627,7 @@ def test_upgrade_language_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.upgrade_language_model(**req_copy) @@ -1557,6 +1640,7 @@ def test_upgrade_language_model_value_error_with_retries(self): _service.disable_retries() self.test_upgrade_language_model_value_error() + # endregion ############################################################################## # End of Service: CustomLanguageModels @@ -1567,7 +1651,8 @@ def test_upgrade_language_model_value_error_with_retries(self): ############################################################################## # region -class TestListCorpora(): + +class TestListCorpora: """ Test Class for list_corpora """ @@ -1580,11 +1665,13 @@ def test_list_corpora_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/corpora') mock_response = '{"corpora": [{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1592,7 +1679,7 @@ def test_list_corpora_all_params(self): # Invoke method response = _service.list_corpora( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1616,11 +1703,13 @@ def test_list_corpora_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/corpora') mock_response = '{"corpora": [{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1630,7 +1719,7 @@ def test_list_corpora_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_corpora(**req_copy) @@ -1643,7 +1732,8 @@ def test_list_corpora_value_error_with_retries(self): _service.disable_retries() self.test_list_corpora_value_error() -class TestAddCorpus(): + +class TestAddCorpus: """ Test Class for add_corpus """ @@ -1655,9 +1745,11 @@ def test_add_corpus_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -1671,14 +1763,14 @@ def test_add_corpus_all_params(self): corpus_name, corpus_file, allow_overwrite=allow_overwrite, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string @@ -1698,9 +1790,11 @@ def test_add_corpus_required_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -1712,7 +1806,7 @@ def test_add_corpus_required_params(self): customization_id, corpus_name, corpus_file, - headers={} + headers={}, ) # Check for correct operation @@ -1735,9 +1829,11 @@ def test_add_corpus_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -1751,7 +1847,7 @@ def test_add_corpus_value_error(self): "corpus_file": corpus_file, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_corpus(**req_copy) @@ -1764,7 +1860,8 @@ def test_add_corpus_value_error_with_retries(self): _service.disable_retries() self.test_add_corpus_value_error() -class TestGetCorpus(): + +class TestGetCorpus: """ Test Class for get_corpus """ @@ -1777,11 +1874,13 @@ def test_get_corpus_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') mock_response = '{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1791,7 +1890,7 @@ def test_get_corpus_all_params(self): response = _service.get_corpus( customization_id, corpus_name, - headers={} + headers={}, ) # Check for correct operation @@ -1815,11 +1914,13 @@ def test_get_corpus_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') mock_response = '{"name": "name", "total_words": 11, "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1831,7 +1932,7 @@ def test_get_corpus_value_error(self): "corpus_name": corpus_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_corpus(**req_copy) @@ -1844,7 +1945,8 @@ def test_get_corpus_value_error_with_retries(self): _service.disable_retries() self.test_get_corpus_value_error() -class TestDeleteCorpus(): + +class TestDeleteCorpus: """ Test Class for delete_corpus """ @@ -1856,9 +1958,11 @@ def test_delete_corpus_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1868,7 +1972,7 @@ def test_delete_corpus_all_params(self): response = _service.delete_corpus( customization_id, corpus_name, - headers={} + headers={}, ) # Check for correct operation @@ -1891,9 +1995,11 @@ def test_delete_corpus_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/corpora/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1905,7 +2011,7 @@ def test_delete_corpus_value_error(self): "corpus_name": corpus_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_corpus(**req_copy) @@ -1918,6 +2024,7 @@ def test_delete_corpus_value_error_with_retries(self): _service.disable_retries() self.test_delete_corpus_value_error() + # endregion ############################################################################## # End of Service: CustomCorpora @@ -1928,7 +2035,8 @@ def test_delete_corpus_value_error_with_retries(self): ############################################################################## # region -class TestListWords(): + +class TestListWords: """ Test Class for list_words """ @@ -1941,11 +2049,13 @@ def test_list_words_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1957,14 +2067,14 @@ def test_list_words_all_params(self): customization_id, word_type=word_type, sort=sort, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'word_type={}'.format(word_type) in query_string assert 'sort={}'.format(sort) in query_string @@ -1986,11 +2096,13 @@ def test_list_words_required_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1998,7 +2110,7 @@ def test_list_words_required_params(self): # Invoke method response = _service.list_words( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -2022,11 +2134,13 @@ def test_list_words_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2036,7 +2150,7 @@ def test_list_words_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_words(**req_copy) @@ -2049,7 +2163,8 @@ def test_list_words_value_error_with_retries(self): _service.disable_retries() self.test_list_words_value_error() -class TestAddWords(): + +class TestAddWords: """ Test Class for add_words """ @@ -2061,9 +2176,11 @@ def test_add_words_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Construct a dict representation of a CustomWord model custom_word_model = {} @@ -2079,7 +2196,7 @@ def test_add_words_all_params(self): response = _service.add_words( customization_id, words, - headers={} + headers={}, ) # Check for correct operation @@ -2105,9 +2222,11 @@ def test_add_words_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Construct a dict representation of a CustomWord model custom_word_model = {} @@ -2125,7 +2244,7 @@ def test_add_words_value_error(self): "words": words, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_words(**req_copy) @@ -2138,7 +2257,8 @@ def test_add_words_value_error_with_retries(self): _service.disable_retries() self.test_add_words_value_error() -class TestAddWord(): + +class TestAddWord: """ Test Class for add_word """ @@ -2150,9 +2270,11 @@ def test_add_word_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.PUT, - url, - status=201) + responses.add( + responses.PUT, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -2168,7 +2290,7 @@ def test_add_word_all_params(self): word=word, sounds_like=sounds_like, display_as=display_as, - headers={} + headers={}, ) # Check for correct operation @@ -2196,9 +2318,11 @@ def test_add_word_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.PUT, - url, - status=201) + responses.add( + responses.PUT, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -2213,7 +2337,7 @@ def test_add_word_value_error(self): "word_name": word_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_word(**req_copy) @@ -2226,7 +2350,8 @@ def test_add_word_value_error_with_retries(self): _service.disable_retries() self.test_add_word_value_error() -class TestGetWord(): + +class TestGetWord: """ Test Class for get_word """ @@ -2239,11 +2364,13 @@ def test_get_word_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2253,7 +2380,7 @@ def test_get_word_all_params(self): response = _service.get_word( customization_id, word_name, - headers={} + headers={}, ) # Check for correct operation @@ -2277,11 +2404,13 @@ def test_get_word_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2293,7 +2422,7 @@ def test_get_word_value_error(self): "word_name": word_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_word(**req_copy) @@ -2306,7 +2435,8 @@ def test_get_word_value_error_with_retries(self): _service.disable_retries() self.test_get_word_value_error() -class TestDeleteWord(): + +class TestDeleteWord: """ Test Class for delete_word """ @@ -2318,9 +2448,11 @@ def test_delete_word_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2330,7 +2462,7 @@ def test_delete_word_all_params(self): response = _service.delete_word( customization_id, word_name, - headers={} + headers={}, ) # Check for correct operation @@ -2353,9 +2485,11 @@ def test_delete_word_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2367,7 +2501,7 @@ def test_delete_word_value_error(self): "word_name": word_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_word(**req_copy) @@ -2380,6 +2514,7 @@ def test_delete_word_value_error_with_retries(self): _service.disable_retries() self.test_delete_word_value_error() + # endregion ############################################################################## # End of Service: CustomWords @@ -2390,7 +2525,8 @@ def test_delete_word_value_error_with_retries(self): ############################################################################## # region -class TestListGrammars(): + +class TestListGrammars: """ Test Class for list_grammars """ @@ -2403,11 +2539,13 @@ def test_list_grammars_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/grammars') mock_response = '{"grammars": [{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2415,7 +2553,7 @@ def test_list_grammars_all_params(self): # Invoke method response = _service.list_grammars( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -2439,11 +2577,13 @@ def test_list_grammars_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/grammars') mock_response = '{"grammars": [{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2453,7 +2593,7 @@ def test_list_grammars_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_grammars(**req_copy) @@ -2466,7 +2606,8 @@ def test_list_grammars_value_error_with_retries(self): _service.disable_retries() self.test_list_grammars_value_error() -class TestAddGrammar(): + +class TestAddGrammar: """ Test Class for add_grammar """ @@ -2478,9 +2619,11 @@ def test_add_grammar_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -2496,14 +2639,14 @@ def test_add_grammar_all_params(self): grammar_file, content_type, allow_overwrite=allow_overwrite, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string # Validate body params @@ -2524,9 +2667,11 @@ def test_add_grammar_required_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -2540,7 +2685,7 @@ def test_add_grammar_required_params(self): grammar_name, grammar_file, content_type, - headers={} + headers={}, ) # Check for correct operation @@ -2564,9 +2709,11 @@ def test_add_grammar_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -2582,7 +2729,7 @@ def test_add_grammar_value_error(self): "content_type": content_type, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_grammar(**req_copy) @@ -2595,7 +2742,8 @@ def test_add_grammar_value_error_with_retries(self): _service.disable_retries() self.test_add_grammar_value_error() -class TestGetGrammar(): + +class TestGetGrammar: """ Test Class for get_grammar """ @@ -2608,11 +2756,13 @@ def test_get_grammar_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') mock_response = '{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2622,7 +2772,7 @@ def test_get_grammar_all_params(self): response = _service.get_grammar( customization_id, grammar_name, - headers={} + headers={}, ) # Check for correct operation @@ -2646,11 +2796,13 @@ def test_get_grammar_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') mock_response = '{"name": "name", "out_of_vocabulary_words": 23, "status": "analyzed", "error": "error"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2662,7 +2814,7 @@ def test_get_grammar_value_error(self): "grammar_name": grammar_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_grammar(**req_copy) @@ -2675,7 +2827,8 @@ def test_get_grammar_value_error_with_retries(self): _service.disable_retries() self.test_get_grammar_value_error() -class TestDeleteGrammar(): + +class TestDeleteGrammar: """ Test Class for delete_grammar """ @@ -2687,9 +2840,11 @@ def test_delete_grammar_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2699,7 +2854,7 @@ def test_delete_grammar_all_params(self): response = _service.delete_grammar( customization_id, grammar_name, - headers={} + headers={}, ) # Check for correct operation @@ -2722,9 +2877,11 @@ def test_delete_grammar_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/grammars/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2736,7 +2893,7 @@ def test_delete_grammar_value_error(self): "grammar_name": grammar_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_grammar(**req_copy) @@ -2749,6 +2906,7 @@ def test_delete_grammar_value_error_with_retries(self): _service.disable_retries() self.test_delete_grammar_value_error() + # endregion ############################################################################## # End of Service: CustomGrammars @@ -2759,7 +2917,8 @@ def test_delete_grammar_value_error_with_retries(self): ############################################################################## # region -class TestCreateAcousticModel(): + +class TestCreateAcousticModel: """ Test Class for create_acoustic_model """ @@ -2772,11 +2931,13 @@ def test_create_acoustic_model_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -2788,7 +2949,7 @@ def test_create_acoustic_model_all_params(self): name, base_model_name, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -2817,11 +2978,13 @@ def test_create_acoustic_model_value_error(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -2834,7 +2997,7 @@ def test_create_acoustic_model_value_error(self): "base_model_name": base_model_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_acoustic_model(**req_copy) @@ -2847,7 +3010,8 @@ def test_create_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_create_acoustic_model_value_error() -class TestListAcousticModels(): + +class TestListAcousticModels: """ Test Class for list_acoustic_models """ @@ -2860,11 +3024,13 @@ def test_list_acoustic_models_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values language = 'ar-MS' @@ -2872,14 +3038,14 @@ def test_list_acoustic_models_all_params(self): # Invoke method response = _service.list_acoustic_models( language=language, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'language={}'.format(language) in query_string @@ -2900,16 +3066,17 @@ def test_list_acoustic_models_required_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_acoustic_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -2923,7 +3090,8 @@ def test_list_acoustic_models_required_params_with_retries(self): _service.disable_retries() self.test_list_acoustic_models_required_params() -class TestGetAcousticModel(): + +class TestGetAcousticModel: """ Test Class for get_acoustic_model """ @@ -2936,11 +3104,13 @@ def test_get_acoustic_model_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2948,7 +3118,7 @@ def test_get_acoustic_model_all_params(self): # Invoke method response = _service.get_acoustic_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -2972,11 +3142,13 @@ def test_get_acoustic_model_value_error(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString') mock_response = '{"customization_id": "customization_id", "created": "created", "updated": "updated", "language": "language", "versions": ["versions"], "owner": "owner", "name": "name", "description": "description", "base_model_name": "base_model_name", "status": "pending", "progress": 8, "warnings": "warnings"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -2986,7 +3158,7 @@ def test_get_acoustic_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_acoustic_model(**req_copy) @@ -2999,7 +3171,8 @@ def test_get_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_get_acoustic_model_value_error() -class TestDeleteAcousticModel(): + +class TestDeleteAcousticModel: """ Test Class for delete_acoustic_model """ @@ -3011,9 +3184,11 @@ def test_delete_acoustic_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3021,7 +3196,7 @@ def test_delete_acoustic_model_all_params(self): # Invoke method response = _service.delete_acoustic_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -3044,9 +3219,11 @@ def test_delete_acoustic_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3056,7 +3233,7 @@ def test_delete_acoustic_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_acoustic_model(**req_copy) @@ -3069,7 +3246,8 @@ def test_delete_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_acoustic_model_value_error() -class TestTrainAcousticModel(): + +class TestTrainAcousticModel: """ Test Class for train_acoustic_model """ @@ -3082,11 +3260,13 @@ def test_train_acoustic_model_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3098,14 +3278,14 @@ def test_train_acoustic_model_all_params(self): customization_id, custom_language_model_id=custom_language_model_id, strict=strict, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'custom_language_model_id={}'.format(custom_language_model_id) in query_string assert 'strict={}'.format('true' if strict else 'false') in query_string @@ -3127,11 +3307,13 @@ def test_train_acoustic_model_required_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3139,7 +3321,7 @@ def test_train_acoustic_model_required_params(self): # Invoke method response = _service.train_acoustic_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -3163,11 +3345,13 @@ def test_train_acoustic_model_value_error(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/train') mock_response = '{"warnings": [{"code": "invalid_audio_files", "message": "message"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3177,7 +3361,7 @@ def test_train_acoustic_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.train_acoustic_model(**req_copy) @@ -3190,7 +3374,8 @@ def test_train_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_train_acoustic_model_value_error() -class TestResetAcousticModel(): + +class TestResetAcousticModel: """ Test Class for reset_acoustic_model """ @@ -3202,9 +3387,11 @@ def test_reset_acoustic_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/reset') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3212,7 +3399,7 @@ def test_reset_acoustic_model_all_params(self): # Invoke method response = _service.reset_acoustic_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -3235,9 +3422,11 @@ def test_reset_acoustic_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/reset') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3247,7 +3436,7 @@ def test_reset_acoustic_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.reset_acoustic_model(**req_copy) @@ -3260,7 +3449,8 @@ def test_reset_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_reset_acoustic_model_value_error() -class TestUpgradeAcousticModel(): + +class TestUpgradeAcousticModel: """ Test Class for upgrade_acoustic_model """ @@ -3272,9 +3462,11 @@ def test_upgrade_acoustic_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/upgrade_model') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3286,14 +3478,14 @@ def test_upgrade_acoustic_model_all_params(self): customization_id, custom_language_model_id=custom_language_model_id, force=force, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'custom_language_model_id={}'.format(custom_language_model_id) in query_string assert 'force={}'.format('true' if force else 'false') in query_string @@ -3314,9 +3506,11 @@ def test_upgrade_acoustic_model_required_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/upgrade_model') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3324,7 +3518,7 @@ def test_upgrade_acoustic_model_required_params(self): # Invoke method response = _service.upgrade_acoustic_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -3347,9 +3541,11 @@ def test_upgrade_acoustic_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/upgrade_model') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3359,7 +3555,7 @@ def test_upgrade_acoustic_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.upgrade_acoustic_model(**req_copy) @@ -3372,6 +3568,7 @@ def test_upgrade_acoustic_model_value_error_with_retries(self): _service.disable_retries() self.test_upgrade_acoustic_model_value_error() + # endregion ############################################################################## # End of Service: CustomAcousticModels @@ -3382,7 +3579,8 @@ def test_upgrade_acoustic_model_value_error_with_retries(self): ############################################################################## # region -class TestListAudio(): + +class TestListAudio: """ Test Class for list_audio """ @@ -3395,11 +3593,13 @@ def test_list_audio_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio') mock_response = '{"total_minutes_of_audio": 22, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3407,7 +3607,7 @@ def test_list_audio_all_params(self): # Invoke method response = _service.list_audio( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -3431,11 +3631,13 @@ def test_list_audio_value_error(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio') mock_response = '{"total_minutes_of_audio": 22, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3445,7 +3647,7 @@ def test_list_audio_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_audio(**req_copy) @@ -3458,7 +3660,8 @@ def test_list_audio_value_error_with_retries(self): _service.disable_retries() self.test_list_audio_value_error() -class TestAddAudio(): + +class TestAddAudio: """ Test Class for add_audio """ @@ -3470,9 +3673,11 @@ def test_add_audio_all_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -3490,14 +3695,14 @@ def test_add_audio_all_params(self): content_type=content_type, contained_content_type=contained_content_type, allow_overwrite=allow_overwrite, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'allow_overwrite={}'.format('true' if allow_overwrite else 'false') in query_string # Validate body params @@ -3518,9 +3723,11 @@ def test_add_audio_required_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -3532,7 +3739,7 @@ def test_add_audio_required_params(self): customization_id, audio_name, audio_resource, - headers={} + headers={}, ) # Check for correct operation @@ -3556,9 +3763,11 @@ def test_add_audio_value_error(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') - responses.add(responses.POST, - url, - status=201) + responses.add( + responses.POST, + url, + status=201, + ) # Set up parameter values customization_id = 'testString' @@ -3572,7 +3781,7 @@ def test_add_audio_value_error(self): "audio_resource": audio_resource, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_audio(**req_copy) @@ -3585,7 +3794,8 @@ def test_add_audio_value_error_with_retries(self): _service.disable_retries() self.test_add_audio_value_error() -class TestGetAudio(): + +class TestGetAudio: """ Test Class for get_audio """ @@ -3598,11 +3808,13 @@ def test_get_audio_all_params(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') mock_response = '{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok", "container": {"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3612,7 +3824,7 @@ def test_get_audio_all_params(self): response = _service.get_audio( customization_id, audio_name, - headers={} + headers={}, ) # Check for correct operation @@ -3636,11 +3848,13 @@ def test_get_audio_value_error(self): # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') mock_response = '{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok", "container": {"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}, "audio": [{"duration": 8, "name": "name", "details": {"type": "audio", "codec": "codec", "frequency": 9, "compression": "zip"}, "status": "ok"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3652,7 +3866,7 @@ def test_get_audio_value_error(self): "audio_name": audio_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_audio(**req_copy) @@ -3665,7 +3879,8 @@ def test_get_audio_value_error_with_retries(self): _service.disable_retries() self.test_get_audio_value_error() -class TestDeleteAudio(): + +class TestDeleteAudio: """ Test Class for delete_audio """ @@ -3677,9 +3892,11 @@ def test_delete_audio_all_params(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3689,7 +3906,7 @@ def test_delete_audio_all_params(self): response = _service.delete_audio( customization_id, audio_name, - headers={} + headers={}, ) # Check for correct operation @@ -3712,9 +3929,11 @@ def test_delete_audio_value_error(self): """ # Set up mock url = preprocess_url('/v1/acoustic_customizations/testString/audio/testString') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -3726,7 +3945,7 @@ def test_delete_audio_value_error(self): "audio_name": audio_name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_audio(**req_copy) @@ -3739,6 +3958,7 @@ def test_delete_audio_value_error_with_retries(self): _service.disable_retries() self.test_delete_audio_value_error() + # endregion ############################################################################## # End of Service: CustomAudioResources @@ -3749,7 +3969,8 @@ def test_delete_audio_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -3761,9 +3982,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -3771,14 +3994,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -3798,9 +4021,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -3810,7 +4035,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -3823,6 +4048,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -3833,7 +4059,9 @@ def test_delete_user_data_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_AcousticModel(): + + +class TestModel_AcousticModel: """ Test Class for AcousticModel """ @@ -3873,7 +4101,8 @@ def test_acoustic_model_serialization(self): acoustic_model_model_json2 = acoustic_model_model.to_dict() assert acoustic_model_model_json2 == acoustic_model_model_json -class TestModel_AcousticModels(): + +class TestModel_AcousticModels: """ Test Class for AcousticModels """ @@ -3885,7 +4114,7 @@ def test_acoustic_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - acoustic_model_model = {} # AcousticModel + acoustic_model_model = {} # AcousticModel acoustic_model_model['customization_id'] = 'testString' acoustic_model_model['created'] = 'testString' acoustic_model_model['updated'] = 'testString' @@ -3918,7 +4147,8 @@ def test_acoustic_models_serialization(self): acoustic_models_model_json2 = acoustic_models_model.to_dict() assert acoustic_models_model_json2 == acoustic_models_model_json -class TestModel_AudioDetails(): + +class TestModel_AudioDetails: """ Test Class for AudioDetails """ @@ -3950,7 +4180,8 @@ def test_audio_details_serialization(self): audio_details_model_json2 = audio_details_model.to_dict() assert audio_details_model_json2 == audio_details_model_json -class TestModel_AudioListing(): + +class TestModel_AudioListing: """ Test Class for AudioListing """ @@ -3962,13 +4193,13 @@ def test_audio_listing_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - audio_details_model = {} # AudioDetails + audio_details_model = {} # AudioDetails audio_details_model['type'] = 'audio' audio_details_model['codec'] = 'testString' audio_details_model['frequency'] = 38 audio_details_model['compression'] = 'zip' - audio_resource_model = {} # AudioResource + audio_resource_model = {} # AudioResource audio_resource_model['duration'] = 38 audio_resource_model['name'] = 'testString' audio_resource_model['details'] = audio_details_model @@ -3998,7 +4229,8 @@ def test_audio_listing_serialization(self): audio_listing_model_json2 = audio_listing_model.to_dict() assert audio_listing_model_json2 == audio_listing_model_json -class TestModel_AudioMetrics(): + +class TestModel_AudioMetrics: """ Test Class for AudioMetrics """ @@ -4010,12 +4242,12 @@ def test_audio_metrics_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin audio_metrics_histogram_bin_model['begin'] = 36.0 audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 - audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True audio_metrics_details_model['end_time'] = 36.0 audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 @@ -4046,7 +4278,8 @@ def test_audio_metrics_serialization(self): audio_metrics_model_json2 = audio_metrics_model.to_dict() assert audio_metrics_model_json2 == audio_metrics_model_json -class TestModel_AudioMetricsDetails(): + +class TestModel_AudioMetricsDetails: """ Test Class for AudioMetricsDetails """ @@ -4058,7 +4291,7 @@ def test_audio_metrics_details_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin audio_metrics_histogram_bin_model['begin'] = 36.0 audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 @@ -4090,7 +4323,8 @@ def test_audio_metrics_details_serialization(self): audio_metrics_details_model_json2 = audio_metrics_details_model.to_dict() assert audio_metrics_details_model_json2 == audio_metrics_details_model_json -class TestModel_AudioMetricsHistogramBin(): + +class TestModel_AudioMetricsHistogramBin: """ Test Class for AudioMetricsHistogramBin """ @@ -4121,7 +4355,8 @@ def test_audio_metrics_histogram_bin_serialization(self): audio_metrics_histogram_bin_model_json2 = audio_metrics_histogram_bin_model.to_dict() assert audio_metrics_histogram_bin_model_json2 == audio_metrics_histogram_bin_model_json -class TestModel_AudioResource(): + +class TestModel_AudioResource: """ Test Class for AudioResource """ @@ -4133,7 +4368,7 @@ def test_audio_resource_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - audio_details_model = {} # AudioDetails + audio_details_model = {} # AudioDetails audio_details_model['type'] = 'audio' audio_details_model['codec'] = 'testString' audio_details_model['frequency'] = 38 @@ -4161,7 +4396,8 @@ def test_audio_resource_serialization(self): audio_resource_model_json2 = audio_resource_model.to_dict() assert audio_resource_model_json2 == audio_resource_model_json -class TestModel_AudioResources(): + +class TestModel_AudioResources: """ Test Class for AudioResources """ @@ -4173,13 +4409,13 @@ def test_audio_resources_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - audio_details_model = {} # AudioDetails + audio_details_model = {} # AudioDetails audio_details_model['type'] = 'audio' audio_details_model['codec'] = 'testString' audio_details_model['frequency'] = 38 audio_details_model['compression'] = 'zip' - audio_resource_model = {} # AudioResource + audio_resource_model = {} # AudioResource audio_resource_model['duration'] = 38 audio_resource_model['name'] = 'testString' audio_resource_model['details'] = audio_details_model @@ -4205,7 +4441,8 @@ def test_audio_resources_serialization(self): audio_resources_model_json2 = audio_resources_model.to_dict() assert audio_resources_model_json2 == audio_resources_model_json -class TestModel_Corpora(): + +class TestModel_Corpora: """ Test Class for Corpora """ @@ -4217,7 +4454,7 @@ def test_corpora_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - corpus_model = {} # Corpus + corpus_model = {} # Corpus corpus_model['name'] = 'testString' corpus_model['total_words'] = 38 corpus_model['out_of_vocabulary_words'] = 38 @@ -4243,7 +4480,8 @@ def test_corpora_serialization(self): corpora_model_json2 = corpora_model.to_dict() assert corpora_model_json2 == corpora_model_json -class TestModel_Corpus(): + +class TestModel_Corpus: """ Test Class for Corpus """ @@ -4276,7 +4514,8 @@ def test_corpus_serialization(self): corpus_model_json2 = corpus_model.to_dict() assert corpus_model_json2 == corpus_model_json -class TestModel_CustomWord(): + +class TestModel_CustomWord: """ Test Class for CustomWord """ @@ -4307,7 +4546,8 @@ def test_custom_word_serialization(self): custom_word_model_json2 = custom_word_model.to_dict() assert custom_word_model_json2 == custom_word_model_json -class TestModel_Grammar(): + +class TestModel_Grammar: """ Test Class for Grammar """ @@ -4339,7 +4579,8 @@ def test_grammar_serialization(self): grammar_model_json2 = grammar_model.to_dict() assert grammar_model_json2 == grammar_model_json -class TestModel_Grammars(): + +class TestModel_Grammars: """ Test Class for Grammars """ @@ -4351,7 +4592,7 @@ def test_grammars_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - grammar_model = {} # Grammar + grammar_model = {} # Grammar grammar_model['name'] = 'testString' grammar_model['out_of_vocabulary_words'] = 38 grammar_model['status'] = 'analyzed' @@ -4376,7 +4617,8 @@ def test_grammars_serialization(self): grammars_model_json2 = grammars_model.to_dict() assert grammars_model_json2 == grammars_model_json -class TestModel_KeywordResult(): + +class TestModel_KeywordResult: """ Test Class for KeywordResult """ @@ -4408,7 +4650,8 @@ def test_keyword_result_serialization(self): keyword_result_model_json2 = keyword_result_model.to_dict() assert keyword_result_model_json2 == keyword_result_model_json -class TestModel_LanguageModel(): + +class TestModel_LanguageModel: """ Test Class for LanguageModel """ @@ -4450,7 +4693,8 @@ def test_language_model_serialization(self): language_model_model_json2 = language_model_model.to_dict() assert language_model_model_json2 == language_model_model_json -class TestModel_LanguageModels(): + +class TestModel_LanguageModels: """ Test Class for LanguageModels """ @@ -4462,7 +4706,7 @@ def test_language_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - language_model_model = {} # LanguageModel + language_model_model = {} # LanguageModel language_model_model['customization_id'] = 'testString' language_model_model['created'] = 'testString' language_model_model['updated'] = 'testString' @@ -4497,7 +4741,8 @@ def test_language_models_serialization(self): language_models_model_json2 = language_models_model.to_dict() assert language_models_model_json2 == language_models_model_json -class TestModel_ProcessedAudio(): + +class TestModel_ProcessedAudio: """ Test Class for ProcessedAudio """ @@ -4529,7 +4774,8 @@ def test_processed_audio_serialization(self): processed_audio_model_json2 = processed_audio_model.to_dict() assert processed_audio_model_json2 == processed_audio_model_json -class TestModel_ProcessingMetrics(): + +class TestModel_ProcessingMetrics: """ Test Class for ProcessingMetrics """ @@ -4541,7 +4787,7 @@ def test_processing_metrics_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - processed_audio_model = {} # ProcessedAudio + processed_audio_model = {} # ProcessedAudio processed_audio_model['received'] = 36.0 processed_audio_model['seen_by_engine'] = 36.0 processed_audio_model['transcription'] = 36.0 @@ -4568,7 +4814,8 @@ def test_processing_metrics_serialization(self): processing_metrics_model_json2 = processing_metrics_model.to_dict() assert processing_metrics_model_json2 == processing_metrics_model_json -class TestModel_RecognitionJob(): + +class TestModel_RecognitionJob: """ Test Class for RecognitionJob """ @@ -4580,58 +4827,58 @@ def test_recognition_job_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative speech_recognition_alternative_model['transcript'] = 'testString' speech_recognition_alternative_model['confidence'] = 0 speech_recognition_alternative_model['timestamps'] = ['testString'] speech_recognition_alternative_model['word_confidence'] = ['testString'] - keyword_result_model = {} # KeywordResult + keyword_result_model = {} # KeywordResult keyword_result_model['normalized_text'] = 'testString' keyword_result_model['start_time'] = 72.5 keyword_result_model['end_time'] = 72.5 keyword_result_model['confidence'] = 0 - word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model = {} # WordAlternativeResult word_alternative_result_model['confidence'] = 0 word_alternative_result_model['word'] = 'testString' - word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model = {} # WordAlternativeResults word_alternative_results_model['start_time'] = 72.5 word_alternative_results_model['end_time'] = 72.5 word_alternative_results_model['alternatives'] = [word_alternative_result_model] - speech_recognition_result_model = {} # SpeechRecognitionResult + speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' - speaker_labels_result_model = {} # SpeakerLabelsResult + speaker_labels_result_model = {} # SpeakerLabelsResult speaker_labels_result_model['from'] = 36.0 speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True - processed_audio_model = {} # ProcessedAudio + processed_audio_model = {} # ProcessedAudio processed_audio_model['received'] = 36.0 processed_audio_model['seen_by_engine'] = 36.0 processed_audio_model['transcription'] = 36.0 processed_audio_model['speaker_labels'] = 36.0 - processing_metrics_model = {} # ProcessingMetrics + processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True - audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin audio_metrics_histogram_bin_model['begin'] = 36.0 audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 - audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True audio_metrics_details_model['end_time'] = 36.0 audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 @@ -4642,11 +4889,11 @@ def test_recognition_job_serialization(self): audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] - audio_metrics_model = {} # AudioMetrics + audio_metrics_model = {} # AudioMetrics audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model - speech_recognition_results_model = {} # SpeechRecognitionResults + speech_recognition_results_model = {} # SpeechRecognitionResults speech_recognition_results_model['results'] = [speech_recognition_result_model] speech_recognition_results_model['result_index'] = 38 speech_recognition_results_model['speaker_labels'] = [speaker_labels_result_model] @@ -4680,7 +4927,8 @@ def test_recognition_job_serialization(self): recognition_job_model_json2 = recognition_job_model.to_dict() assert recognition_job_model_json2 == recognition_job_model_json -class TestModel_RecognitionJobs(): + +class TestModel_RecognitionJobs: """ Test Class for RecognitionJobs """ @@ -4692,58 +4940,58 @@ def test_recognition_jobs_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative speech_recognition_alternative_model['transcript'] = 'testString' speech_recognition_alternative_model['confidence'] = 0 speech_recognition_alternative_model['timestamps'] = ['testString'] speech_recognition_alternative_model['word_confidence'] = ['testString'] - keyword_result_model = {} # KeywordResult + keyword_result_model = {} # KeywordResult keyword_result_model['normalized_text'] = 'testString' keyword_result_model['start_time'] = 72.5 keyword_result_model['end_time'] = 72.5 keyword_result_model['confidence'] = 0 - word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model = {} # WordAlternativeResult word_alternative_result_model['confidence'] = 0 word_alternative_result_model['word'] = 'testString' - word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model = {} # WordAlternativeResults word_alternative_results_model['start_time'] = 72.5 word_alternative_results_model['end_time'] = 72.5 word_alternative_results_model['alternatives'] = [word_alternative_result_model] - speech_recognition_result_model = {} # SpeechRecognitionResult + speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' - speaker_labels_result_model = {} # SpeakerLabelsResult + speaker_labels_result_model = {} # SpeakerLabelsResult speaker_labels_result_model['from'] = 36.0 speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True - processed_audio_model = {} # ProcessedAudio + processed_audio_model = {} # ProcessedAudio processed_audio_model['received'] = 36.0 processed_audio_model['seen_by_engine'] = 36.0 processed_audio_model['transcription'] = 36.0 processed_audio_model['speaker_labels'] = 36.0 - processing_metrics_model = {} # ProcessingMetrics + processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True - audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin audio_metrics_histogram_bin_model['begin'] = 36.0 audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 - audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True audio_metrics_details_model['end_time'] = 36.0 audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 @@ -4754,11 +5002,11 @@ def test_recognition_jobs_serialization(self): audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] - audio_metrics_model = {} # AudioMetrics + audio_metrics_model = {} # AudioMetrics audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model - speech_recognition_results_model = {} # SpeechRecognitionResults + speech_recognition_results_model = {} # SpeechRecognitionResults speech_recognition_results_model['results'] = [speech_recognition_result_model] speech_recognition_results_model['result_index'] = 38 speech_recognition_results_model['speaker_labels'] = [speaker_labels_result_model] @@ -4766,7 +5014,7 @@ def test_recognition_jobs_serialization(self): speech_recognition_results_model['audio_metrics'] = audio_metrics_model speech_recognition_results_model['warnings'] = ['testString'] - recognition_job_model = {} # RecognitionJob + recognition_job_model = {} # RecognitionJob recognition_job_model['id'] = 'testString' recognition_job_model['status'] = 'waiting' recognition_job_model['created'] = 'testString' @@ -4795,7 +5043,8 @@ def test_recognition_jobs_serialization(self): recognition_jobs_model_json2 = recognition_jobs_model.to_dict() assert recognition_jobs_model_json2 == recognition_jobs_model_json -class TestModel_RegisterStatus(): + +class TestModel_RegisterStatus: """ Test Class for RegisterStatus """ @@ -4825,7 +5074,8 @@ def test_register_status_serialization(self): register_status_model_json2 = register_status_model.to_dict() assert register_status_model_json2 == register_status_model_json -class TestModel_SpeakerLabelsResult(): + +class TestModel_SpeakerLabelsResult: """ Test Class for SpeakerLabelsResult """ @@ -4858,7 +5108,8 @@ def test_speaker_labels_result_serialization(self): speaker_labels_result_model_json2 = speaker_labels_result_model.to_dict() assert speaker_labels_result_model_json2 == speaker_labels_result_model_json -class TestModel_SpeechModel(): + +class TestModel_SpeechModel: """ Test Class for SpeechModel """ @@ -4870,7 +5121,7 @@ def test_speech_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - supported_features_model = {} # SupportedFeatures + supported_features_model = {} # SupportedFeatures supported_features_model['custom_language_model'] = True supported_features_model['custom_acoustic_model'] = True supported_features_model['speaker_labels'] = True @@ -4900,7 +5151,8 @@ def test_speech_model_serialization(self): speech_model_model_json2 = speech_model_model.to_dict() assert speech_model_model_json2 == speech_model_model_json -class TestModel_SpeechModels(): + +class TestModel_SpeechModels: """ Test Class for SpeechModels """ @@ -4912,13 +5164,13 @@ def test_speech_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - supported_features_model = {} # SupportedFeatures + supported_features_model = {} # SupportedFeatures supported_features_model['custom_language_model'] = True supported_features_model['custom_acoustic_model'] = True supported_features_model['speaker_labels'] = True supported_features_model['low_latency'] = True - speech_model_model = {} # SpeechModel + speech_model_model = {} # SpeechModel speech_model_model['name'] = 'testString' speech_model_model['language'] = 'testString' speech_model_model['rate'] = 38 @@ -4945,7 +5197,8 @@ def test_speech_models_serialization(self): speech_models_model_json2 = speech_models_model.to_dict() assert speech_models_model_json2 == speech_models_model_json -class TestModel_SpeechRecognitionAlternative(): + +class TestModel_SpeechRecognitionAlternative: """ Test Class for SpeechRecognitionAlternative """ @@ -4977,7 +5230,8 @@ def test_speech_recognition_alternative_serialization(self): speech_recognition_alternative_model_json2 = speech_recognition_alternative_model.to_dict() assert speech_recognition_alternative_model_json2 == speech_recognition_alternative_model_json -class TestModel_SpeechRecognitionResult(): + +class TestModel_SpeechRecognitionResult: """ Test Class for SpeechRecognitionResult """ @@ -4989,23 +5243,23 @@ def test_speech_recognition_result_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative speech_recognition_alternative_model['transcript'] = 'testString' speech_recognition_alternative_model['confidence'] = 0 speech_recognition_alternative_model['timestamps'] = ['testString'] speech_recognition_alternative_model['word_confidence'] = ['testString'] - keyword_result_model = {} # KeywordResult + keyword_result_model = {} # KeywordResult keyword_result_model['normalized_text'] = 'testString' keyword_result_model['start_time'] = 72.5 keyword_result_model['end_time'] = 72.5 keyword_result_model['confidence'] = 0 - word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model = {} # WordAlternativeResult word_alternative_result_model['confidence'] = 0 word_alternative_result_model['word'] = 'testString' - word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model = {} # WordAlternativeResults word_alternative_results_model['start_time'] = 72.5 word_alternative_results_model['end_time'] = 72.5 word_alternative_results_model['alternatives'] = [word_alternative_result_model] @@ -5033,7 +5287,8 @@ def test_speech_recognition_result_serialization(self): speech_recognition_result_model_json2 = speech_recognition_result_model.to_dict() assert speech_recognition_result_model_json2 == speech_recognition_result_model_json -class TestModel_SpeechRecognitionResults(): + +class TestModel_SpeechRecognitionResults: """ Test Class for SpeechRecognitionResults """ @@ -5045,58 +5300,58 @@ def test_speech_recognition_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speech_recognition_alternative_model = {} # SpeechRecognitionAlternative + speech_recognition_alternative_model = {} # SpeechRecognitionAlternative speech_recognition_alternative_model['transcript'] = 'testString' speech_recognition_alternative_model['confidence'] = 0 speech_recognition_alternative_model['timestamps'] = ['testString'] speech_recognition_alternative_model['word_confidence'] = ['testString'] - keyword_result_model = {} # KeywordResult + keyword_result_model = {} # KeywordResult keyword_result_model['normalized_text'] = 'testString' keyword_result_model['start_time'] = 72.5 keyword_result_model['end_time'] = 72.5 keyword_result_model['confidence'] = 0 - word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model = {} # WordAlternativeResult word_alternative_result_model['confidence'] = 0 word_alternative_result_model['word'] = 'testString' - word_alternative_results_model = {} # WordAlternativeResults + word_alternative_results_model = {} # WordAlternativeResults word_alternative_results_model['start_time'] = 72.5 word_alternative_results_model['end_time'] = 72.5 word_alternative_results_model['alternatives'] = [word_alternative_result_model] - speech_recognition_result_model = {} # SpeechRecognitionResult + speech_recognition_result_model = {} # SpeechRecognitionResult speech_recognition_result_model['final'] = True speech_recognition_result_model['alternatives'] = [speech_recognition_alternative_model] speech_recognition_result_model['keywords_result'] = {'key1': [keyword_result_model]} speech_recognition_result_model['word_alternatives'] = [word_alternative_results_model] speech_recognition_result_model['end_of_utterance'] = 'end_of_data' - speaker_labels_result_model = {} # SpeakerLabelsResult + speaker_labels_result_model = {} # SpeakerLabelsResult speaker_labels_result_model['from'] = 36.0 speaker_labels_result_model['to'] = 36.0 speaker_labels_result_model['speaker'] = 38 speaker_labels_result_model['confidence'] = 36.0 speaker_labels_result_model['final'] = True - processed_audio_model = {} # ProcessedAudio + processed_audio_model = {} # ProcessedAudio processed_audio_model['received'] = 36.0 processed_audio_model['seen_by_engine'] = 36.0 processed_audio_model['transcription'] = 36.0 processed_audio_model['speaker_labels'] = 36.0 - processing_metrics_model = {} # ProcessingMetrics + processing_metrics_model = {} # ProcessingMetrics processing_metrics_model['processed_audio'] = processed_audio_model processing_metrics_model['wall_clock_since_first_byte_received'] = 36.0 processing_metrics_model['periodic'] = True - audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin + audio_metrics_histogram_bin_model = {} # AudioMetricsHistogramBin audio_metrics_histogram_bin_model['begin'] = 36.0 audio_metrics_histogram_bin_model['end'] = 36.0 audio_metrics_histogram_bin_model['count'] = 38 - audio_metrics_details_model = {} # AudioMetricsDetails + audio_metrics_details_model = {} # AudioMetricsDetails audio_metrics_details_model['final'] = True audio_metrics_details_model['end_time'] = 36.0 audio_metrics_details_model['signal_to_noise_ratio'] = 36.0 @@ -5107,7 +5362,7 @@ def test_speech_recognition_results_serialization(self): audio_metrics_details_model['speech_level'] = [audio_metrics_histogram_bin_model] audio_metrics_details_model['non_speech_level'] = [audio_metrics_histogram_bin_model] - audio_metrics_model = {} # AudioMetrics + audio_metrics_model = {} # AudioMetrics audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model @@ -5135,7 +5390,8 @@ def test_speech_recognition_results_serialization(self): speech_recognition_results_model_json2 = speech_recognition_results_model.to_dict() assert speech_recognition_results_model_json2 == speech_recognition_results_model_json -class TestModel_SupportedFeatures(): + +class TestModel_SupportedFeatures: """ Test Class for SupportedFeatures """ @@ -5167,7 +5423,8 @@ def test_supported_features_serialization(self): supported_features_model_json2 = supported_features_model.to_dict() assert supported_features_model_json2 == supported_features_model_json -class TestModel_TrainingResponse(): + +class TestModel_TrainingResponse: """ Test Class for TrainingResponse """ @@ -5179,7 +5436,7 @@ def test_training_response_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - training_warning_model = {} # TrainingWarning + training_warning_model = {} # TrainingWarning training_warning_model['code'] = 'invalid_audio_files' training_warning_model['message'] = 'testString' @@ -5202,7 +5459,8 @@ def test_training_response_serialization(self): training_response_model_json2 = training_response_model.to_dict() assert training_response_model_json2 == training_response_model_json -class TestModel_TrainingWarning(): + +class TestModel_TrainingWarning: """ Test Class for TrainingWarning """ @@ -5232,7 +5490,8 @@ def test_training_warning_serialization(self): training_warning_model_json2 = training_warning_model.to_dict() assert training_warning_model_json2 == training_warning_model_json -class TestModel_Word(): + +class TestModel_Word: """ Test Class for Word """ @@ -5244,7 +5503,7 @@ def test_word_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_error_model = {} # WordError + word_error_model = {} # WordError word_error_model['element'] = 'testString' # Construct a json representation of a Word model @@ -5271,7 +5530,8 @@ def test_word_serialization(self): word_model_json2 = word_model.to_dict() assert word_model_json2 == word_model_json -class TestModel_WordAlternativeResult(): + +class TestModel_WordAlternativeResult: """ Test Class for WordAlternativeResult """ @@ -5301,7 +5561,8 @@ def test_word_alternative_result_serialization(self): word_alternative_result_model_json2 = word_alternative_result_model.to_dict() assert word_alternative_result_model_json2 == word_alternative_result_model_json -class TestModel_WordAlternativeResults(): + +class TestModel_WordAlternativeResults: """ Test Class for WordAlternativeResults """ @@ -5313,7 +5574,7 @@ def test_word_alternative_results_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_alternative_result_model = {} # WordAlternativeResult + word_alternative_result_model = {} # WordAlternativeResult word_alternative_result_model['confidence'] = 0 word_alternative_result_model['word'] = 'testString' @@ -5338,7 +5599,8 @@ def test_word_alternative_results_serialization(self): word_alternative_results_model_json2 = word_alternative_results_model.to_dict() assert word_alternative_results_model_json2 == word_alternative_results_model_json -class TestModel_WordError(): + +class TestModel_WordError: """ Test Class for WordError """ @@ -5367,7 +5629,8 @@ def test_word_error_serialization(self): word_error_model_json2 = word_error_model.to_dict() assert word_error_model_json2 == word_error_model_json -class TestModel_Words(): + +class TestModel_Words: """ Test Class for Words """ @@ -5379,10 +5642,10 @@ def test_words_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_error_model = {} # WordError + word_error_model = {} # WordError word_error_model['element'] = 'testString' - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' word_model['sounds_like'] = ['testString'] word_model['display_as'] = 'testString' diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 9d3d8c252..c779f8e3e 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2023. +# (C) Copyright IBM Corp. 2015, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -60,8 +60,7 @@ def preprocess_url(operation_path: str): # Otherwise, return a regular expression that matches one or more trailing /. if re.fullmatch('.*/+', request_url) is None: return request_url - else: - return re.compile(request_url.rstrip('/') + '/+') + return re.compile(request_url.rstrip('/') + '/+') ############################################################################## @@ -69,7 +68,8 @@ def preprocess_url(operation_path: str): ############################################################################## # region -class TestListVoices(): + +class TestListVoices: """ Test Class for list_voices """ @@ -82,16 +82,17 @@ def test_list_voices_all_params(self): # Set up mock url = preprocess_url('/v1/voices') mock_response = '{"voices": [{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_voices() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -105,7 +106,8 @@ def test_list_voices_all_params_with_retries(self): _service.disable_retries() self.test_list_voices_all_params() -class TestGetVoice(): + +class TestGetVoice: """ Test Class for get_voice """ @@ -118,11 +120,13 @@ def test_get_voice_all_params(self): # Set up mock url = preprocess_url('/v1/voices/ar-MS_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values voice = 'ar-MS_OmarVoice' @@ -132,14 +136,14 @@ def test_get_voice_all_params(self): response = _service.get_voice( voice, customization_id=customization_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customization_id={}'.format(customization_id) in query_string @@ -160,11 +164,13 @@ def test_get_voice_required_params(self): # Set up mock url = preprocess_url('/v1/voices/ar-MS_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values voice = 'ar-MS_OmarVoice' @@ -172,7 +178,7 @@ def test_get_voice_required_params(self): # Invoke method response = _service.get_voice( voice, - headers={} + headers={}, ) # Check for correct operation @@ -196,11 +202,13 @@ def test_get_voice_value_error(self): # Set up mock url = preprocess_url('/v1/voices/ar-MS_OmarVoice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values voice = 'ar-MS_OmarVoice' @@ -210,7 +218,7 @@ def test_get_voice_value_error(self): "voice": voice, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_voice(**req_copy) @@ -223,6 +231,7 @@ def test_get_voice_value_error_with_retries(self): _service.disable_retries() self.test_get_voice_value_error() + # endregion ############################################################################## # End of Service: Voices @@ -233,7 +242,8 @@ def test_get_voice_value_error_with_retries(self): ############################################################################## # region -class TestSynthesize(): + +class TestSynthesize: """ Test Class for synthesize """ @@ -246,11 +256,13 @@ def test_synthesize_all_params(self): # Set up mock url = preprocess_url('/v1/synthesize') mock_response = 'This is a mock binary response.' - responses.add(responses.POST, - url, - body=mock_response, - content_type='audio/alaw', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='audio/alaw', + status=200, + ) # Set up parameter values text = 'testString' @@ -258,8 +270,8 @@ def test_synthesize_all_params(self): voice = 'en-US_MichaelV3Voice' customization_id = 'testString' spell_out_mode = 'default' - rate_percentage = 38 - pitch_percentage = 38 + rate_percentage = 0 + pitch_percentage = 0 # Invoke method response = _service.synthesize( @@ -270,14 +282,14 @@ def test_synthesize_all_params(self): spell_out_mode=spell_out_mode, rate_percentage=rate_percentage, pitch_percentage=pitch_percentage, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'voice={}'.format(voice) in query_string assert 'customization_id={}'.format(customization_id) in query_string @@ -305,11 +317,13 @@ def test_synthesize_required_params(self): # Set up mock url = preprocess_url('/v1/synthesize') mock_response = 'This is a mock binary response.' - responses.add(responses.POST, - url, - body=mock_response, - content_type='audio/alaw', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='audio/alaw', + status=200, + ) # Set up parameter values text = 'testString' @@ -317,7 +331,7 @@ def test_synthesize_required_params(self): # Invoke method response = _service.synthesize( text, - headers={} + headers={}, ) # Check for correct operation @@ -344,11 +358,13 @@ def test_synthesize_value_error(self): # Set up mock url = preprocess_url('/v1/synthesize') mock_response = 'This is a mock binary response.' - responses.add(responses.POST, - url, - body=mock_response, - content_type='audio/alaw', - status=200) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='audio/alaw', + status=200, + ) # Set up parameter values text = 'testString' @@ -358,7 +374,7 @@ def test_synthesize_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.synthesize(**req_copy) @@ -371,6 +387,7 @@ def test_synthesize_value_error_with_retries(self): _service.disable_retries() self.test_synthesize_value_error() + # endregion ############################################################################## # End of Service: Synthesis @@ -381,7 +398,8 @@ def test_synthesize_value_error_with_retries(self): ############################################################################## # region -class TestGetPronunciation(): + +class TestGetPronunciation: """ Test Class for get_pronunciation """ @@ -394,11 +412,13 @@ def test_get_pronunciation_all_params(self): # Set up mock url = preprocess_url('/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = 'testString' @@ -412,14 +432,14 @@ def test_get_pronunciation_all_params(self): voice=voice, format=format, customization_id=customization_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'text={}'.format(text) in query_string assert 'voice={}'.format(voice) in query_string @@ -443,11 +463,13 @@ def test_get_pronunciation_required_params(self): # Set up mock url = preprocess_url('/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = 'testString' @@ -455,14 +477,14 @@ def test_get_pronunciation_required_params(self): # Invoke method response = _service.get_pronunciation( text, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'text={}'.format(text) in query_string @@ -483,11 +505,13 @@ def test_get_pronunciation_value_error(self): # Set up mock url = preprocess_url('/v1/pronunciation') mock_response = '{"pronunciation": "pronunciation"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values text = 'testString' @@ -497,7 +521,7 @@ def test_get_pronunciation_value_error(self): "text": text, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_pronunciation(**req_copy) @@ -510,6 +534,7 @@ def test_get_pronunciation_value_error_with_retries(self): _service.disable_retries() self.test_get_pronunciation_value_error() + # endregion ############################################################################## # End of Service: Pronunciation @@ -520,7 +545,8 @@ def test_get_pronunciation_value_error_with_retries(self): ############################################################################## # region -class TestCreateCustomModel(): + +class TestCreateCustomModel: """ Test Class for create_custom_model """ @@ -533,11 +559,13 @@ def test_create_custom_model_all_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -549,7 +577,7 @@ def test_create_custom_model_all_params(self): name, language=language, description=description, - headers={} + headers={}, ) # Check for correct operation @@ -578,11 +606,13 @@ def test_create_custom_model_value_error(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values name = 'testString' @@ -594,7 +624,7 @@ def test_create_custom_model_value_error(self): "name": name, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_custom_model(**req_copy) @@ -607,7 +637,8 @@ def test_create_custom_model_value_error_with_retries(self): _service.disable_retries() self.test_create_custom_model_value_error() -class TestListCustomModels(): + +class TestListCustomModels: """ Test Class for list_custom_models """ @@ -620,11 +651,13 @@ def test_list_custom_models_all_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values language = 'ar-MS' @@ -632,14 +665,14 @@ def test_list_custom_models_all_params(self): # Invoke method response = _service.list_custom_models( language=language, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'language={}'.format(language) in query_string @@ -660,16 +693,17 @@ def test_list_custom_models_required_params(self): # Set up mock url = preprocess_url('/v1/customizations') mock_response = '{"customizations": [{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_custom_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -683,7 +717,8 @@ def test_list_custom_models_required_params_with_retries(self): _service.disable_retries() self.test_list_custom_models_required_params() -class TestUpdateCustomModel(): + +class TestUpdateCustomModel: """ Test Class for update_custom_model """ @@ -695,9 +730,11 @@ def test_update_custom_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Construct a dict representation of a Word model word_model = {} @@ -717,7 +754,7 @@ def test_update_custom_model_all_params(self): name=name, description=description, words=words, - headers={} + headers={}, ) # Check for correct operation @@ -745,9 +782,11 @@ def test_update_custom_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Construct a dict representation of a Word model word_model = {} @@ -766,7 +805,7 @@ def test_update_custom_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.update_custom_model(**req_copy) @@ -779,7 +818,8 @@ def test_update_custom_model_value_error_with_retries(self): _service.disable_retries() self.test_update_custom_model_value_error() -class TestGetCustomModel(): + +class TestGetCustomModel: """ Test Class for get_custom_model """ @@ -792,11 +832,13 @@ def test_get_custom_model_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -804,7 +846,7 @@ def test_get_custom_model_all_params(self): # Invoke method response = _service.get_custom_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -828,11 +870,13 @@ def test_get_custom_model_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString') mock_response = '{"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -842,7 +886,7 @@ def test_get_custom_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_custom_model(**req_copy) @@ -855,7 +899,8 @@ def test_get_custom_model_value_error_with_retries(self): _service.disable_retries() self.test_get_custom_model_value_error() -class TestDeleteCustomModel(): + +class TestDeleteCustomModel: """ Test Class for delete_custom_model """ @@ -867,9 +912,11 @@ def test_delete_custom_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -877,7 +924,7 @@ def test_delete_custom_model_all_params(self): # Invoke method response = _service.delete_custom_model( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -900,9 +947,11 @@ def test_delete_custom_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -912,7 +961,7 @@ def test_delete_custom_model_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_custom_model(**req_copy) @@ -925,6 +974,7 @@ def test_delete_custom_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_custom_model_value_error() + # endregion ############################################################################## # End of Service: CustomModels @@ -935,7 +985,8 @@ def test_delete_custom_model_value_error_with_retries(self): ############################################################################## # region -class TestAddWords(): + +class TestAddWords: """ Test Class for add_words """ @@ -947,9 +998,11 @@ def test_add_words_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Construct a dict representation of a Word model word_model = {} @@ -965,7 +1018,7 @@ def test_add_words_all_params(self): response = _service.add_words( customization_id, words, - headers={} + headers={}, ) # Check for correct operation @@ -991,9 +1044,11 @@ def test_add_words_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - responses.add(responses.POST, - url, - status=200) + responses.add( + responses.POST, + url, + status=200, + ) # Construct a dict representation of a Word model word_model = {} @@ -1011,7 +1066,7 @@ def test_add_words_value_error(self): "words": words, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_words(**req_copy) @@ -1024,7 +1079,8 @@ def test_add_words_value_error_with_retries(self): _service.disable_retries() self.test_add_words_value_error() -class TestListWords(): + +class TestListWords: """ Test Class for list_words """ @@ -1037,11 +1093,13 @@ def test_list_words_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1049,7 +1107,7 @@ def test_list_words_all_params(self): # Invoke method response = _service.list_words( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1073,11 +1131,13 @@ def test_list_words_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words') mock_response = '{"words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1087,7 +1147,7 @@ def test_list_words_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_words(**req_copy) @@ -1100,7 +1160,8 @@ def test_list_words_value_error_with_retries(self): _service.disable_retries() self.test_list_words_value_error() -class TestAddWord(): + +class TestAddWord: """ Test Class for add_word """ @@ -1112,9 +1173,11 @@ def test_add_word_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.PUT, - url, - status=200) + responses.add( + responses.PUT, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1128,7 +1191,7 @@ def test_add_word_all_params(self): word, translation, part_of_speech=part_of_speech, - headers={} + headers={}, ) # Check for correct operation @@ -1155,9 +1218,11 @@ def test_add_word_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.PUT, - url, - status=200) + responses.add( + responses.PUT, + url, + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1172,7 +1237,7 @@ def test_add_word_value_error(self): "translation": translation, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_word(**req_copy) @@ -1185,7 +1250,8 @@ def test_add_word_value_error_with_retries(self): _service.disable_retries() self.test_add_word_value_error() -class TestGetWord(): + +class TestGetWord: """ Test Class for get_word """ @@ -1198,11 +1264,13 @@ def test_get_word_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') mock_response = '{"translation": "translation", "part_of_speech": "Dosi"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1212,7 +1280,7 @@ def test_get_word_all_params(self): response = _service.get_word( customization_id, word, - headers={} + headers={}, ) # Check for correct operation @@ -1236,11 +1304,13 @@ def test_get_word_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') mock_response = '{"translation": "translation", "part_of_speech": "Dosi"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1252,7 +1322,7 @@ def test_get_word_value_error(self): "word": word, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_word(**req_copy) @@ -1265,7 +1335,8 @@ def test_get_word_value_error_with_retries(self): _service.disable_retries() self.test_get_word_value_error() -class TestDeleteWord(): + +class TestDeleteWord: """ Test Class for delete_word """ @@ -1277,9 +1348,11 @@ def test_delete_word_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -1289,7 +1362,7 @@ def test_delete_word_all_params(self): response = _service.delete_word( customization_id, word, - headers={} + headers={}, ) # Check for correct operation @@ -1312,9 +1385,11 @@ def test_delete_word_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -1326,7 +1401,7 @@ def test_delete_word_value_error(self): "word": word, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_word(**req_copy) @@ -1339,6 +1414,7 @@ def test_delete_word_value_error_with_retries(self): _service.disable_retries() self.test_delete_word_value_error() + # endregion ############################################################################## # End of Service: CustomWords @@ -1349,7 +1425,8 @@ def test_delete_word_value_error_with_retries(self): ############################################################################## # region -class TestListCustomPrompts(): + +class TestListCustomPrompts: """ Test Class for list_custom_prompts """ @@ -1362,11 +1439,13 @@ def test_list_custom_prompts_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts') mock_response = '{"prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1374,7 +1453,7 @@ def test_list_custom_prompts_all_params(self): # Invoke method response = _service.list_custom_prompts( customization_id, - headers={} + headers={}, ) # Check for correct operation @@ -1398,11 +1477,13 @@ def test_list_custom_prompts_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts') mock_response = '{"prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1412,7 +1493,7 @@ def test_list_custom_prompts_value_error(self): "customization_id": customization_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.list_custom_prompts(**req_copy) @@ -1425,7 +1506,8 @@ def test_list_custom_prompts_value_error_with_retries(self): _service.disable_retries() self.test_list_custom_prompts_value_error() -class TestAddCustomPrompt(): + +class TestAddCustomPrompt: """ Test Class for add_custom_prompt """ @@ -1438,11 +1520,13 @@ def test_add_custom_prompt_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a PromptMetadata model prompt_metadata_model = {} @@ -1461,7 +1545,7 @@ def test_add_custom_prompt_all_params(self): prompt_id, metadata, file, - headers={} + headers={}, ) # Check for correct operation @@ -1485,11 +1569,13 @@ def test_add_custom_prompt_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Construct a dict representation of a PromptMetadata model prompt_metadata_model = {} @@ -1510,7 +1596,7 @@ def test_add_custom_prompt_value_error(self): "file": file, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.add_custom_prompt(**req_copy) @@ -1523,7 +1609,8 @@ def test_add_custom_prompt_value_error_with_retries(self): _service.disable_retries() self.test_add_custom_prompt_value_error() -class TestGetCustomPrompt(): + +class TestGetCustomPrompt: """ Test Class for get_custom_prompt """ @@ -1536,11 +1623,13 @@ def test_get_custom_prompt_all_params(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1550,7 +1639,7 @@ def test_get_custom_prompt_all_params(self): response = _service.get_custom_prompt( customization_id, prompt_id, - headers={} + headers={}, ) # Check for correct operation @@ -1574,11 +1663,13 @@ def test_get_custom_prompt_value_error(self): # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') mock_response = '{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values customization_id = 'testString' @@ -1590,7 +1681,7 @@ def test_get_custom_prompt_value_error(self): "prompt_id": prompt_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_custom_prompt(**req_copy) @@ -1603,7 +1694,8 @@ def test_get_custom_prompt_value_error_with_retries(self): _service.disable_retries() self.test_get_custom_prompt_value_error() -class TestDeleteCustomPrompt(): + +class TestDeleteCustomPrompt: """ Test Class for delete_custom_prompt """ @@ -1615,9 +1707,11 @@ def test_delete_custom_prompt_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -1627,7 +1721,7 @@ def test_delete_custom_prompt_all_params(self): response = _service.delete_custom_prompt( customization_id, prompt_id, - headers={} + headers={}, ) # Check for correct operation @@ -1650,9 +1744,11 @@ def test_delete_custom_prompt_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/prompts/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values customization_id = 'testString' @@ -1664,7 +1760,7 @@ def test_delete_custom_prompt_value_error(self): "prompt_id": prompt_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_custom_prompt(**req_copy) @@ -1677,6 +1773,7 @@ def test_delete_custom_prompt_value_error_with_retries(self): _service.disable_retries() self.test_delete_custom_prompt_value_error() + # endregion ############################################################################## # End of Service: CustomPrompts @@ -1687,7 +1784,8 @@ def test_delete_custom_prompt_value_error_with_retries(self): ############################################################################## # region -class TestListSpeakerModels(): + +class TestListSpeakerModels: """ Test Class for list_speaker_models """ @@ -1700,16 +1798,17 @@ def test_list_speaker_models_all_params(self): # Set up mock url = preprocess_url('/v1/speakers') mock_response = '{"speakers": [{"speaker_id": "speaker_id", "name": "name"}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Invoke method response = _service.list_speaker_models() - # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 @@ -1723,7 +1822,8 @@ def test_list_speaker_models_all_params_with_retries(self): _service.disable_retries() self.test_list_speaker_models_all_params() -class TestCreateSpeakerModel(): + +class TestCreateSpeakerModel: """ Test Class for create_speaker_model """ @@ -1736,11 +1836,13 @@ def test_create_speaker_model_all_params(self): # Set up mock url = preprocess_url('/v1/speakers') mock_response = '{"speaker_id": "speaker_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values speaker_name = 'testString' @@ -1750,14 +1852,14 @@ def test_create_speaker_model_all_params(self): response = _service.create_speaker_model( speaker_name, audio, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 201 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'speaker_name={}'.format(speaker_name) in query_string # Validate body params @@ -1780,11 +1882,13 @@ def test_create_speaker_model_value_error(self): # Set up mock url = preprocess_url('/v1/speakers') mock_response = '{"speaker_id": "speaker_id"}' - responses.add(responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201) + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=201, + ) # Set up parameter values speaker_name = 'testString' @@ -1796,7 +1900,7 @@ def test_create_speaker_model_value_error(self): "audio": audio, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.create_speaker_model(**req_copy) @@ -1809,7 +1913,8 @@ def test_create_speaker_model_value_error_with_retries(self): _service.disable_retries() self.test_create_speaker_model_value_error() -class TestGetSpeakerModel(): + +class TestGetSpeakerModel: """ Test Class for get_speaker_model """ @@ -1822,11 +1927,13 @@ def test_get_speaker_model_all_params(self): # Set up mock url = preprocess_url('/v1/speakers/testString') mock_response = '{"customizations": [{"customization_id": "customization_id", "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values speaker_id = 'testString' @@ -1834,7 +1941,7 @@ def test_get_speaker_model_all_params(self): # Invoke method response = _service.get_speaker_model( speaker_id, - headers={} + headers={}, ) # Check for correct operation @@ -1858,11 +1965,13 @@ def test_get_speaker_model_value_error(self): # Set up mock url = preprocess_url('/v1/speakers/testString') mock_response = '{"customizations": [{"customization_id": "customization_id", "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error"}]}]}' - responses.add(responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200) + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) # Set up parameter values speaker_id = 'testString' @@ -1872,7 +1981,7 @@ def test_get_speaker_model_value_error(self): "speaker_id": speaker_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.get_speaker_model(**req_copy) @@ -1885,7 +1994,8 @@ def test_get_speaker_model_value_error_with_retries(self): _service.disable_retries() self.test_get_speaker_model_value_error() -class TestDeleteSpeakerModel(): + +class TestDeleteSpeakerModel: """ Test Class for delete_speaker_model """ @@ -1897,9 +2007,11 @@ def test_delete_speaker_model_all_params(self): """ # Set up mock url = preprocess_url('/v1/speakers/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values speaker_id = 'testString' @@ -1907,7 +2019,7 @@ def test_delete_speaker_model_all_params(self): # Invoke method response = _service.delete_speaker_model( speaker_id, - headers={} + headers={}, ) # Check for correct operation @@ -1930,9 +2042,11 @@ def test_delete_speaker_model_value_error(self): """ # Set up mock url = preprocess_url('/v1/speakers/testString') - responses.add(responses.DELETE, - url, - status=204) + responses.add( + responses.DELETE, + url, + status=204, + ) # Set up parameter values speaker_id = 'testString' @@ -1942,7 +2056,7 @@ def test_delete_speaker_model_value_error(self): "speaker_id": speaker_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_speaker_model(**req_copy) @@ -1955,6 +2069,7 @@ def test_delete_speaker_model_value_error_with_retries(self): _service.disable_retries() self.test_delete_speaker_model_value_error() + # endregion ############################################################################## # End of Service: SpeakerModels @@ -1965,7 +2080,8 @@ def test_delete_speaker_model_value_error_with_retries(self): ############################################################################## # region -class TestDeleteUserData(): + +class TestDeleteUserData: """ Test Class for delete_user_data """ @@ -1977,9 +2093,11 @@ def test_delete_user_data_all_params(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -1987,14 +2105,14 @@ def test_delete_user_data_all_params(self): # Invoke method response = _service.delete_user_data( customer_id, - headers={} + headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 # Validate query params - query_string = responses.calls[0].request.url.split('?',1)[1] + query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'customer_id={}'.format(customer_id) in query_string @@ -2014,9 +2132,11 @@ def test_delete_user_data_value_error(self): """ # Set up mock url = preprocess_url('/v1/user_data') - responses.add(responses.DELETE, - url, - status=200) + responses.add( + responses.DELETE, + url, + status=200, + ) # Set up parameter values customer_id = 'testString' @@ -2026,7 +2146,7 @@ def test_delete_user_data_value_error(self): "customer_id": customer_id, } for param in req_param_dict.keys(): - req_copy = {key:val if key is not param else None for (key,val) in req_param_dict.items()} + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): _service.delete_user_data(**req_copy) @@ -2039,6 +2159,7 @@ def test_delete_user_data_value_error_with_retries(self): _service.disable_retries() self.test_delete_user_data_value_error() + # endregion ############################################################################## # End of Service: UserData @@ -2049,7 +2170,9 @@ def test_delete_user_data_value_error_with_retries(self): # Start of Model Tests ############################################################################## # region -class TestModel_CustomModel(): + + +class TestModel_CustomModel: """ Test Class for CustomModel """ @@ -2061,12 +2184,12 @@ def test_custom_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' - prompt_model = {} # Prompt + prompt_model = {} # Prompt prompt_model['prompt'] = 'testString' prompt_model['prompt_id'] = 'testString' prompt_model['status'] = 'testString' @@ -2100,7 +2223,8 @@ def test_custom_model_serialization(self): custom_model_model_json2 = custom_model_model.to_dict() assert custom_model_model_json2 == custom_model_model_json -class TestModel_CustomModels(): + +class TestModel_CustomModels: """ Test Class for CustomModels """ @@ -2112,19 +2236,19 @@ def test_custom_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' - prompt_model = {} # Prompt + prompt_model = {} # Prompt prompt_model['prompt'] = 'testString' prompt_model['prompt_id'] = 'testString' prompt_model['status'] = 'testString' prompt_model['error'] = 'testString' prompt_model['speaker_id'] = 'testString' - custom_model_model = {} # CustomModel + custom_model_model = {} # CustomModel custom_model_model['customization_id'] = 'testString' custom_model_model['name'] = 'testString' custom_model_model['language'] = 'testString' @@ -2154,7 +2278,8 @@ def test_custom_models_serialization(self): custom_models_model_json2 = custom_models_model.to_dict() assert custom_models_model_json2 == custom_models_model_json -class TestModel_Prompt(): + +class TestModel_Prompt: """ Test Class for Prompt """ @@ -2187,7 +2312,8 @@ def test_prompt_serialization(self): prompt_model_json2 = prompt_model.to_dict() assert prompt_model_json2 == prompt_model_json -class TestModel_PromptMetadata(): + +class TestModel_PromptMetadata: """ Test Class for PromptMetadata """ @@ -2217,7 +2343,8 @@ def test_prompt_metadata_serialization(self): prompt_metadata_model_json2 = prompt_metadata_model.to_dict() assert prompt_metadata_model_json2 == prompt_metadata_model_json -class TestModel_Prompts(): + +class TestModel_Prompts: """ Test Class for Prompts """ @@ -2229,7 +2356,7 @@ def test_prompts_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - prompt_model = {} # Prompt + prompt_model = {} # Prompt prompt_model['prompt'] = 'testString' prompt_model['prompt_id'] = 'testString' prompt_model['status'] = 'testString' @@ -2255,7 +2382,8 @@ def test_prompts_serialization(self): prompts_model_json2 = prompts_model.to_dict() assert prompts_model_json2 == prompts_model_json -class TestModel_Pronunciation(): + +class TestModel_Pronunciation: """ Test Class for Pronunciation """ @@ -2284,7 +2412,8 @@ def test_pronunciation_serialization(self): pronunciation_model_json2 = pronunciation_model.to_dict() assert pronunciation_model_json2 == pronunciation_model_json -class TestModel_Speaker(): + +class TestModel_Speaker: """ Test Class for Speaker """ @@ -2314,7 +2443,8 @@ def test_speaker_serialization(self): speaker_model_json2 = speaker_model.to_dict() assert speaker_model_json2 == speaker_model_json -class TestModel_SpeakerCustomModel(): + +class TestModel_SpeakerCustomModel: """ Test Class for SpeakerCustomModel """ @@ -2326,7 +2456,7 @@ def test_speaker_custom_model_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speaker_prompt_model = {} # SpeakerPrompt + speaker_prompt_model = {} # SpeakerPrompt speaker_prompt_model['prompt'] = 'testString' speaker_prompt_model['prompt_id'] = 'testString' speaker_prompt_model['status'] = 'testString' @@ -2352,7 +2482,8 @@ def test_speaker_custom_model_serialization(self): speaker_custom_model_model_json2 = speaker_custom_model_model.to_dict() assert speaker_custom_model_model_json2 == speaker_custom_model_model_json -class TestModel_SpeakerCustomModels(): + +class TestModel_SpeakerCustomModels: """ Test Class for SpeakerCustomModels """ @@ -2364,13 +2495,13 @@ def test_speaker_custom_models_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speaker_prompt_model = {} # SpeakerPrompt + speaker_prompt_model = {} # SpeakerPrompt speaker_prompt_model['prompt'] = 'testString' speaker_prompt_model['prompt_id'] = 'testString' speaker_prompt_model['status'] = 'testString' speaker_prompt_model['error'] = 'testString' - speaker_custom_model_model = {} # SpeakerCustomModel + speaker_custom_model_model = {} # SpeakerCustomModel speaker_custom_model_model['customization_id'] = 'testString' speaker_custom_model_model['prompts'] = [speaker_prompt_model] @@ -2393,7 +2524,8 @@ def test_speaker_custom_models_serialization(self): speaker_custom_models_model_json2 = speaker_custom_models_model.to_dict() assert speaker_custom_models_model_json2 == speaker_custom_models_model_json -class TestModel_SpeakerModel(): + +class TestModel_SpeakerModel: """ Test Class for SpeakerModel """ @@ -2422,7 +2554,8 @@ def test_speaker_model_serialization(self): speaker_model_model_json2 = speaker_model_model.to_dict() assert speaker_model_model_json2 == speaker_model_model_json -class TestModel_SpeakerPrompt(): + +class TestModel_SpeakerPrompt: """ Test Class for SpeakerPrompt """ @@ -2454,7 +2587,8 @@ def test_speaker_prompt_serialization(self): speaker_prompt_model_json2 = speaker_prompt_model.to_dict() assert speaker_prompt_model_json2 == speaker_prompt_model_json -class TestModel_Speakers(): + +class TestModel_Speakers: """ Test Class for Speakers """ @@ -2466,7 +2600,7 @@ def test_speakers_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - speaker_model = {} # Speaker + speaker_model = {} # Speaker speaker_model['speaker_id'] = 'testString' speaker_model['name'] = 'testString' @@ -2489,7 +2623,8 @@ def test_speakers_serialization(self): speakers_model_json2 = speakers_model.to_dict() assert speakers_model_json2 == speakers_model_json -class TestModel_SupportedFeatures(): + +class TestModel_SupportedFeatures: """ Test Class for SupportedFeatures """ @@ -2519,7 +2654,8 @@ def test_supported_features_serialization(self): supported_features_model_json2 = supported_features_model.to_dict() assert supported_features_model_json2 == supported_features_model_json -class TestModel_Translation(): + +class TestModel_Translation: """ Test Class for Translation """ @@ -2549,7 +2685,8 @@ def test_translation_serialization(self): translation_model_json2 = translation_model.to_dict() assert translation_model_json2 == translation_model_json -class TestModel_Voice(): + +class TestModel_Voice: """ Test Class for Voice """ @@ -2561,23 +2698,23 @@ def test_voice_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - supported_features_model = {} # SupportedFeatures + supported_features_model = {} # SupportedFeatures supported_features_model['custom_pronunciation'] = True supported_features_model['voice_transformation'] = True - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' - prompt_model = {} # Prompt + prompt_model = {} # Prompt prompt_model['prompt'] = 'testString' prompt_model['prompt_id'] = 'testString' prompt_model['status'] = 'testString' prompt_model['error'] = 'testString' prompt_model['speaker_id'] = 'testString' - custom_model_model = {} # CustomModel + custom_model_model = {} # CustomModel custom_model_model['customization_id'] = 'testString' custom_model_model['name'] = 'testString' custom_model_model['language'] = 'testString' @@ -2614,7 +2751,8 @@ def test_voice_serialization(self): voice_model_json2 = voice_model.to_dict() assert voice_model_json2 == voice_model_json -class TestModel_Voices(): + +class TestModel_Voices: """ Test Class for Voices """ @@ -2626,23 +2764,23 @@ def test_voices_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - supported_features_model = {} # SupportedFeatures + supported_features_model = {} # SupportedFeatures supported_features_model['custom_pronunciation'] = True supported_features_model['voice_transformation'] = True - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' - prompt_model = {} # Prompt + prompt_model = {} # Prompt prompt_model['prompt'] = 'testString' prompt_model['prompt_id'] = 'testString' prompt_model['status'] = 'testString' prompt_model['error'] = 'testString' prompt_model['speaker_id'] = 'testString' - custom_model_model = {} # CustomModel + custom_model_model = {} # CustomModel custom_model_model['customization_id'] = 'testString' custom_model_model['name'] = 'testString' custom_model_model['language'] = 'testString' @@ -2653,7 +2791,7 @@ def test_voices_serialization(self): custom_model_model['words'] = [word_model] custom_model_model['prompts'] = [prompt_model] - voice_model = {} # Voice + voice_model = {} # Voice voice_model['url'] = 'testString' voice_model['gender'] = 'testString' voice_model['name'] = 'testString' @@ -2682,7 +2820,8 @@ def test_voices_serialization(self): voices_model_json2 = voices_model.to_dict() assert voices_model_json2 == voices_model_json -class TestModel_Word(): + +class TestModel_Word: """ Test Class for Word """ @@ -2713,7 +2852,8 @@ def test_word_serialization(self): word_model_json2 = word_model.to_dict() assert word_model_json2 == word_model_json -class TestModel_Words(): + +class TestModel_Words: """ Test Class for Words """ @@ -2725,7 +2865,7 @@ def test_words_serialization(self): # Construct dict forms of any model objects needed in order to build this model. - word_model = {} # Word + word_model = {} # Word word_model['word'] = 'testString' word_model['translation'] = 'testString' word_model['part_of_speech'] = 'Dosi' From add5e7a2d76ef74df4d8de9ec8f82af2eaf75e33 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 21 Feb 2024 13:10:42 -0600 Subject: [PATCH 407/455] chore(wa,dis,lt,nlu,tts): small changes --- ibm_watson/assistant_v1.py | 21 ++-- ibm_watson/discovery_v1.py | 10 +- ibm_watson/language_translator_v3.py | 17 ++- ibm_watson/text_to_speech_v1.py | 159 +++++---------------------- test/unit/test_text_to_speech_v1.py | 14 +-- 5 files changed, 65 insertions(+), 156 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 387e1956e..b98b688bb 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -3928,6 +3928,8 @@ def list_logs( [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. + **Note:** If the API is not returning your data, try lowering the + page_limit value. :param str cursor: (optional) A token identifying the page of results to retrieve. :param dict headers: A `dict` containing the request headers @@ -9506,7 +9508,7 @@ class RuntimeEntity: that indicate where the detected entity values begin and end in the input text. :param str value: 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. + confidence in the recognized 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 @@ -9546,7 +9548,7 @@ def __init__( offsets that indicate where the detected entity values begin and end in the input text. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. + confidence in the recognized 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 @@ -9677,7 +9679,7 @@ class RuntimeEntityAlternative: :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. + confidence in the recognized entity. """ def __init__( @@ -9692,7 +9694,7 @@ def __init__( :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. + confidence in the recognized entity. """ self.value = value self.confidence = confidence @@ -10191,8 +10193,8 @@ class RuntimeIntent: :param str intent: The name of the recognized intent. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the intent. If you are specifying an intent as part of a - request, but you do not have a calculated confidence value, specify `1`. + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. """ def __init__( @@ -10206,9 +10208,8 @@ def __init__( :param str intent: The name of the recognized intent. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the intent. If you are specifying an intent as part - of a request, but you do not have a calculated confidence value, specify - `1`. + confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. """ self.intent = intent self.confidence = confidence diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index b8285e54a..a604775e5 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -12297,10 +12297,10 @@ class SegmentSettings: document understanding fields that the document is split on. The content of the annotated field that the segmentation splits at is used as the **title** field for that segmented result. For example, if the field `sub-title` is specified, - when a document is uploaded each time the smart documement understanding + when a document is uploaded each time the smart document understanding conversion encounters a field of type `sub-title` the document is split at that point and the content of the field used as the title of the remaining content. - Thnis split is performed for all instances of the listed fields in the uploaded + This split is performed for all instances of the listed fields in the uploaded document. Only valid if used with a collection that has **enabled** set to `true` in the **smart_document_understanding** object. """ @@ -12328,9 +12328,9 @@ def __init__( the annotated field that the segmentation splits at is used as the **title** field for that segmented result. For example, if the field `sub-title` is specified, when a document is uploaded each time the smart - documement understanding conversion encounters a field of type `sub-title` + document understanding conversion encounters a field of type `sub-title` the document is split at that point and the content of the field used as - the title of the remaining content. Thnis split is performed for all + the title of the remaining content. This split is performed for all instances of the listed fields in the uploaded document. Only valid if used with a collection that has **enabled** set to `true` in the **smart_document_understanding** object. diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 4dc606185..1fd5a426c 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,6 +16,12 @@ # IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ +IBM® is announcing the deprecation of the Watson® Language Translator service for +IBM Cloud® in all regions. As of 10 June 2023, the Language Translator tile will be +removed from the IBM Cloud Platform for new customers; only existing customers will be +able to access the product. As of 10 June 2024, the service will reach its End of Support +date. As of 10 December 2024, the service will be withdrawn entirely and will no longer be +available to any customers.{: deprecated} IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM-provided translation models that you can customize based on your unique terminology and language. Use Language Translator to take news from across the @@ -68,6 +74,15 @@ def __init__( """ if version is None: raise ValueError('version must be provided') + + print( + """ + On 10 June 2023, IBM announced the deprecation of the Natural Language Translator service. + The service will no longer be available from 8 August 2022. As of 10 June 2024, the service will reach its End of Support + date. As of 10 December 2024, the service will be withdrawn entirely and will no longer be + available to any customers. + """ + ) if not authenticator: authenticator = get_authenticator_from_environment(service_name) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index a8f24f2ff..23fe1b487 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2023. +# (C) Copyright IBM Corp. 2015, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -30,18 +30,10 @@ that, when combined, sound like the word. A phonetic translation is based on the SSML phoneme format for representing a word. You can specify a phonetic translation in standard International Phonetic Alphabet (IPA) representation or in the proprietary IBM Symbolic -Phonetic Representation (SPR). For phonetic translation, the Arabic, Chinese, Dutch, -Australian English, Korean, and Swedish voices support only IPA, not SPR. +Phonetic Representation (SPR). The service also offers a Tune by Example feature that lets you define custom prompts. You can also define speaker models to improve the quality of your custom prompts. The service -support custom prompts only for US English custom models and voices. -Effective **31 March 2022**, all *neural voices* are deprecated. The deprecated voices -remain available to existing users until 31 March 2023, when they will be removed from the -service and the documentation. *No enhanced neural voices or expressive neural voices are -deprecated.*

For more information, see the [1 March 2023 service -update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) -in the release notes for {{site.data.keyword.texttospeechshort}} for -{{site.data.keyword.cloud_notm}}.{: deprecated} +supports custom prompts only for US English custom models and voices. API Version: 1.0.0 See: https://cloud.ibm.com/docs/text-to-speech @@ -104,13 +96,6 @@ def list_voices( list of voices can change from call to call; do not rely on an alphabetized or static list of voices. To see information about a specific voice, use the [Get a voice](#getvoice). - **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The - deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. *No enhanced neural - voices or expressive neural voices are deprecated.* For more information, see the - [1 March 2023 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) - in the release notes. **See also:** [Listing all voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-list#list-all-voices). @@ -159,13 +144,6 @@ def get_voice( voices](#listvoices) method. **See also:** [Listing a specific voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-list#list-specific-voice). - **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The - deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. *No enhanced neural - voices or expressive neural voices are deprecated.* For more information, see the - [1 March 2023 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) - in the release notes. :param str voice: The voice for which information is to be returned. :param str customization_id: (optional) The customization ID (GUID) of a @@ -238,13 +216,6 @@ def synthesize( specify. The service returns the synthesized audio stream as an array of bytes. **See also:** [The HTTP interface](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-usingHTTP#usingHTTP). - **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The - deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. *No enhanced neural - voices or expressive neural voices are deprecated.* For more information, see the - [1 March 2023 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) - in the release notes. ### 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 @@ -436,13 +407,6 @@ def get_pronunciation( pronunciation for a specific format. You can also request the pronunciation for a specific voice to see the default translation for the language of that voice or for a specific custom model to see the translation for that model. - **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The - deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. *No enhanced neural - voices or expressive neural voices are deprecated.* For more information, see the - [1 March 2023 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) - in the release notes. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). @@ -457,9 +421,8 @@ def get_pronunciation( **See also:** [Using the default voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). :param str format: (optional) The phoneme format in which to return the - pronunciation. The Arabic, Chinese, Dutch, Australian English, and Korean - languages support only IPA. Omit the parameter to obtain the pronunciation - in the default format. + pronunciation. Omit the parameter to obtain the pronunciation in the + default format. :param str customization_id: (optional) The customization ID (GUID) of a custom model for which the pronunciation is to be returned. The language of a specified custom model must match the language of the specified voice. If @@ -527,13 +490,6 @@ def create_custom_model( used to create it. **See also:** [Creating a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). - **Note:** Effective **31 March 2022**, all *neural voices* are deprecated. The - deprecated voices remain available to existing users until 31 March 2023, when - they will be removed from the service and the documentation. *No enhanced neural - voices or expressive neural voices are deprecated.* For more information, see the - [1 March 2023 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#text-to-speech-1march2023) - in the release notes. :param str name: The name of the new custom model. Use a localized name that matches the language of the custom model. Use a name that describes @@ -1018,9 +974,8 @@ def add_word( :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR - translation. The Arabic, Chinese, Dutch, Australian English, and Korean - languages support only IPA. A sounds-like is one or more words that, when - combined, sound like the word. + translation. A sounds-like is one or more words that, when combined, sound + like the word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -1847,16 +1802,11 @@ class Voice(str, Enum): The voice for which information is to be returned. """ - AR_MS_OMARVOICE = 'ar-MS_OmarVoice' - CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' - EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' - EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' @@ -1880,20 +1830,9 @@ class Voice(str, Enum): FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' - KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' - KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' - KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' - KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' - NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' - NL_BE_BRAMVOICE = 'nl-BE_BramVoice' - NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' - NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' + NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' - SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' - ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' - ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' - ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' class SynthesizeEnums: @@ -1938,16 +1877,11 @@ class Voice(str, Enum): voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). """ - AR_MS_OMARVOICE = 'ar-MS_OmarVoice' - CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' - EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' - EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' @@ -1971,20 +1905,9 @@ class Voice(str, Enum): FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' - KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' - KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' - KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' - KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' - NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' - NL_BE_BRAMVOICE = 'nl-BE_BramVoice' - NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' - NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' + NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' - SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' - ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' - ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' - ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' class SpellOutMode(str, Enum): """ @@ -2028,16 +1951,11 @@ class Voice(str, Enum): voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices-use#specify-voice-default). """ - AR_MS_OMARVOICE = 'ar-MS_OmarVoice' - CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' - EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' - EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' @@ -2061,26 +1979,14 @@ class Voice(str, Enum): FR_FR_RENEEV3VOICE = 'fr-FR_ReneeV3Voice' IT_IT_FRANCESCAV3VOICE = 'it-IT_FrancescaV3Voice' JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' - KO_KR_HYUNJUNVOICE = 'ko-KR_HyunjunVoice' KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' - KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' - KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' - KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' - NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' - NL_BE_BRAMVOICE = 'nl-BE_BramVoice' - NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' - NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' + NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' - SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' - ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' - ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' - ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' class Format(str, Enum): """ - The phoneme format in which to return the pronunciation. The Arabic, Chinese, - Dutch, Australian English, and Korean languages support only IPA. Omit the - parameter to obtain the pronunciation in the default format. + The phoneme format in which to return the pronunciation. Omit the parameter to + obtain the pronunciation in the default format. """ IBM = 'ibm' @@ -2099,8 +2005,6 @@ class Language(str, Enum): the requester. """ - AR_MS = 'ar-MS' - CS_CZ = 'cs-CZ' DE_DE = 'de-DE' EN_AU = 'en-AU' EN_GB = 'en-GB' @@ -2112,12 +2016,8 @@ class Language(str, Enum): FR_FR = 'fr-FR' IT_IT = 'it-IT' JA_JP = 'ja-JP' - KO_KR = 'ko-KR' - NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' - SV_SE = 'sv-SE' - ZH_CN = 'zh-CN' ############################################################################## @@ -3197,9 +3097,9 @@ class SupportedFeatures: :param bool custom_pronunciation: If `true`, the voice can be customized; if `false`, the voice cannot be customized. (Same as `customizable`.). :param bool voice_transformation: If `true`, the voice can be transformed by - using the SSML <voice-transformation> element; if `false`, the voice - cannot be transformed. The feature was available only for the now-deprecated - standard voices. You cannot use the feature with neural voices. + using the SSML `` element; if `false`, the voice cannot be + transformed. **Note:** The SSML `` element is obsolete. + You can no longer use the element with any supported voice. """ def __init__( @@ -3213,10 +3113,9 @@ def __init__( :param bool custom_pronunciation: If `true`, the voice can be customized; if `false`, the voice cannot be customized. (Same as `customizable`.). :param bool voice_transformation: If `true`, the voice can be transformed - by using the SSML <voice-transformation> element; if `false`, the - voice cannot be transformed. The feature was available only for the - now-deprecated standard voices. You cannot use the feature with neural - voices. + by using the SSML `` element; if `false`, the voice + cannot be transformed. **Note:** The SSML `` element + is obsolete. You can no longer use the element with any supported voice. """ self.custom_pronunciation = custom_pronunciation self.voice_transformation = voice_transformation @@ -3282,10 +3181,8 @@ class Translation: :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic - string of a word either as an IPA translation or as an IBM SPR translation. The - Arabic, Chinese, Dutch, Australian English, and Korean languages support only - IPA. A sounds-like is one or more words that, when combined, sound like the - word. + string of a word either as an IPA translation or as an IBM SPR translation. A + sounds-like is one or more words that, when combined, sound like the word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single part of @@ -3306,9 +3203,8 @@ def __init__( :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA translation or as an IBM SPR - translation. The Arabic, Chinese, Dutch, Australian English, and Korean - languages support only IPA. A sounds-like is one or more words that, when - combined, sound like the word. + translation. A sounds-like is one or more words that, when combined, sound + like the word. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single @@ -3630,8 +3526,7 @@ class Word: 49 characters. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic - string of a word either as an IPA or IBM SPR translation. The Arabic, Chinese, - Dutch, Australian English, and Korean languages support only IPA. A sounds-like + string of a word either as an IPA or IBM SPR translation. A sounds-like translation consists of one or more words that, when combined, sound like the word. The maximum length of a translation is 499 characters. :param str part_of_speech: (optional) **Japanese only.** The part of speech for @@ -3656,11 +3551,9 @@ def __init__( word is 49 characters. :param str translation: The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing - the phonetic string of a word either as an IPA or IBM SPR translation. The - Arabic, Chinese, Dutch, Australian English, and Korean languages support - only IPA. A sounds-like translation consists of one or more words that, - when combined, sound like the word. The maximum length of a translation is - 499 characters. + the phonetic string of a word either as an IPA or IBM SPR translation. A + sounds-like translation consists of one or more words that, when combined, + sound like the word. The maximum length of a translation is 499 characters. :param str part_of_speech: (optional) **Japanese only.** The part of speech for the word. The service uses the value to produce the correct intonation for the word. You can create only a single entry, with or without a single diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index c779f8e3e..26341c541 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -118,7 +118,7 @@ def test_get_voice_all_params(self): get_voice() """ # Set up mock - url = preprocess_url('/v1/voices/ar-MS_OmarVoice') + url = preprocess_url('/v1/voices/de-DE_BirgitV3Voice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add( responses.GET, @@ -129,7 +129,7 @@ def test_get_voice_all_params(self): ) # Set up parameter values - voice = 'ar-MS_OmarVoice' + voice = 'de-DE_BirgitV3Voice' customization_id = 'testString' # Invoke method @@ -162,7 +162,7 @@ def test_get_voice_required_params(self): test_get_voice_required_params() """ # Set up mock - url = preprocess_url('/v1/voices/ar-MS_OmarVoice') + url = preprocess_url('/v1/voices/de-DE_BirgitV3Voice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add( responses.GET, @@ -173,7 +173,7 @@ def test_get_voice_required_params(self): ) # Set up parameter values - voice = 'ar-MS_OmarVoice' + voice = 'de-DE_BirgitV3Voice' # Invoke method response = _service.get_voice( @@ -200,7 +200,7 @@ def test_get_voice_value_error(self): test_get_voice_value_error() """ # Set up mock - url = preprocess_url('/v1/voices/ar-MS_OmarVoice') + url = preprocess_url('/v1/voices/de-DE_BirgitV3Voice') mock_response = '{"url": "url", "gender": "gender", "name": "name", "language": "language", "description": "description", "customizable": true, "supported_features": {"custom_pronunciation": true, "voice_transformation": true}, "customization": {"customization_id": "customization_id", "name": "name", "language": "language", "owner": "owner", "created": "created", "last_modified": "last_modified", "description": "description", "words": [{"word": "word", "translation": "translation", "part_of_speech": "Dosi"}], "prompts": [{"prompt": "prompt", "prompt_id": "prompt_id", "status": "status", "error": "error", "speaker_id": "speaker_id"}]}}' responses.add( responses.GET, @@ -211,7 +211,7 @@ def test_get_voice_value_error(self): ) # Set up parameter values - voice = 'ar-MS_OmarVoice' + voice = 'de-DE_BirgitV3Voice' # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -660,7 +660,7 @@ def test_list_custom_models_all_params(self): ) # Set up parameter values - language = 'ar-MS' + language = 'de-DE' # Invoke method response = _service.list_custom_models( From 69523c5f023717ff911b714e2a58571f19b51b04 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 21 Feb 2024 13:37:22 -0600 Subject: [PATCH 408/455] feat(wa-v2): new params orchestration and asyncCallout --- ibm_watson/assistant_v2.py | 203 +++++++++++++++++++++---------------- 1 file changed, 115 insertions(+), 88 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index a39305c74..bcb616c0a 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,11 +16,12 @@ # IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 """ -The IBM Watson™ Assistant service combines machine learning, natural language +The IBM® watsonx™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your apps and your users. The Assistant v2 API provides runtime methods your client application can use to send user input to an assistant and receive a response. +You need a paid Plus plan or higher to use the watsonx Assistant v2 API. API Version: 2.0 See: https://cloud.ibm.com/docs/assistant @@ -60,7 +61,7 @@ def __init__( Construct a new client for the Assistant service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2021-11-27`. + Specify dates in YYYY-MM-DD format. The current version is `2023-06-15`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md @@ -93,7 +94,6 @@ def create_assistant( Create an assistant. Create a new assistant. - This method is available only with Enterprise plans. :param str language: (optional) The language of the assistant. :param str name: (optional) The name of the assistant. This string cannot @@ -156,8 +156,7 @@ def list_assistants( """ List assistants. - List the assistants associated with a Watson Assistant service instance. - This method is available only with Enterprise plans. + List the assistants associated with a watsonx Assistant service instance. :param int page_limit: (optional) The number of records to return in each page of results. @@ -219,7 +218,6 @@ def delete_assistant( Delete assistant. Delete an assistant. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -227,7 +225,7 @@ def delete_assistant( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -289,7 +287,7 @@ def create_session( 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/assistant?topic=assistant-assistant-settings). + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings).). :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -297,7 +295,7 @@ def create_session( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -373,7 +371,7 @@ def delete_session( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -439,7 +437,7 @@ def message( Send user input to assistant (stateful). Send user input to an assistant and receive a response, with conversation state - (including context data) stored by Watson Assistant for the duration of the + (including context data) stored by watsonx Assistant for the duration of the session. :param str assistant_id: The assistant ID or the environment ID of the @@ -448,7 +446,7 @@ def message( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -475,7 +473,7 @@ def message( value specified at the root is used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MessageResponse` object + :rtype: DetailedResponse with `dict` result representing a `StatefulMessageResponse` object """ if not assistant_id: @@ -549,15 +547,15 @@ def message_stateless( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. - :param MessageInputStateless input: (optional) An input object that + :param StatelessMessageInput input: (optional) An input object that includes the input text. - :param MessageContextStateless context: (optional) Context data for the + :param StatelessMessageContext context: (optional) Context data for the conversation. You can use this property to set or modify context variables, which can also be accessed by dialog nodes. The context is not stored by the assistant. To maintain session state, include the context from the @@ -576,7 +574,7 @@ def message_stateless( message request, the value specified at the root is used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MessageResponseStateless` object + :rtype: DetailedResponse with `dict` result representing a `StatelessMessageResponse` object """ if not assistant_id: @@ -646,7 +644,7 @@ def bulk_classify( This method is available only with Enterprise with Data Isolation plans. :param str skill_id: Unique identifier of the skill. To find the skill ID - in the Watson Assistant user interface, open the skill settings and click + in the watsonx Assistant user interface, open the skill settings and click **API Details**. :param List[BulkClassifyUtterance] input: An array of input utterances to classify. @@ -718,8 +716,7 @@ def list_logs( List log events for an assistant. List the events from the log of an assistant. - This method requires Manager access, and is available only with Plus and - Enterprise plans. + This method requires Manager access. **Note:** If you use the **cursor** parameter to retrieve results one page at a time, subsequent requests must be no more than 5 minutes apart. Any returned value for the **cursor** parameter becomes invalid after 5 minutes. For more information @@ -731,7 +728,7 @@ def list_logs( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -745,6 +742,8 @@ def list_logs( [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. + **Note:** If the API is not returning your data, try lowering the + page_limit value. :param str cursor: (optional) A token identifying the page of results to retrieve. :param dict headers: A `dict` containing the request headers @@ -810,7 +809,7 @@ def delete_user_data( **Note:** This operation is intended only for deleting data associated with a single specific customer, not for deleting data associated with multiple customers or for any other purpose. For more information, see [Labeling and deleting data in - Watson + watsonx Assistant](https://cloud.ibm.com/docs/assistant?topic=assistant-information-security#information-security-gdpr-wa). :param str customer_id: The customer ID for which all data is to be @@ -870,7 +869,6 @@ def list_environments( List environments. List the environments associated with an assistant. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -878,7 +876,7 @@ def list_environments( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -954,7 +952,6 @@ def get_environment( Get information about an environment. For more information about environments, see [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -962,14 +959,14 @@ def get_environment( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. :param str environment_id: Unique identifier of the environment. To find - the environment ID in the Watson Assistant user interface, open the + the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the API does not support creating environments. :param bool include_audit: (optional) Whether to include the audit @@ -1023,6 +1020,7 @@ def update_environment( *, name: Optional[str] = None, description: Optional[str] = None, + orchestration: Optional['BaseEnvironmentOrchestration'] = None, session_timeout: Optional[int] = None, skill_references: Optional[List['EnvironmentSkill']] = None, **kwargs, @@ -1033,7 +1031,6 @@ def update_environment( Update an environment with new or modified data. For more information about environments, see [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1041,18 +1038,20 @@ def update_environment( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. :param str environment_id: Unique identifier of the environment. To find - the environment ID in the Watson Assistant user interface, open the + the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the API does not support creating environments. :param str name: (optional) The name of the environment. :param str description: (optional) The description of the environment. + :param BaseEnvironmentOrchestration orchestration: (optional) The search + skill orchestration settings for the environment. :param int session_timeout: (optional) The session inactivity timeout setting for the environment (in seconds). :param List[EnvironmentSkill] skill_references: (optional) An array of @@ -1067,6 +1066,8 @@ def update_environment( raise ValueError('assistant_id must be provided') if not environment_id: raise ValueError('environment_id must be provided') + if orchestration is not None: + orchestration = convert_model(orchestration) if skill_references is not None: skill_references = [convert_model(x) for x in skill_references] headers = {} @@ -1084,6 +1085,7 @@ def update_environment( data = { 'name': name, 'description': description, + 'orchestration': orchestration, 'session_timeout': session_timeout, 'skill_references': skill_references, } @@ -1127,9 +1129,8 @@ def create_release( Create release. Create a new release using the current content of the dialog and action skills in - the draft environment. (In the Watson Assistant user interface, a release is - called a *version*.) - This method is available only with Enterprise plans. + the draft environment. (In the watsonx Assistant user interface, a release is + called a *version*.). :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1137,7 +1138,7 @@ def create_release( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1204,9 +1205,8 @@ def list_releases( """ List releases. - List the releases associated with an assistant. (In the Watson Assistant user - interface, a release is called a *version*.) - This method is available only with Enterprise plans. + List the releases associated with an assistant. (In the watsonx Assistant user + interface, a release is called a *version*.). :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1214,7 +1214,7 @@ def list_releases( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1292,7 +1292,6 @@ def get_release( publishing is still in progress, you can continue to poll by calling the same request again and checking the value of the **status** property. When processing has completed, the request returns the release data. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1300,7 +1299,7 @@ def get_release( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1360,9 +1359,8 @@ def delete_release( """ Delete release. - Delete a release. (In the Watson Assistant user interface, a release is called a - *version*.) - This method is available only with Enterprise plans. + Delete a release. (In the watsonx Assistant user interface, a release is called a + *version*.). :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1370,7 +1368,7 @@ def delete_release( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1432,7 +1430,6 @@ def deploy_release( Update the environment with the content of the release. All snapshots saved as part of the release become active in the environment. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1440,7 +1437,7 @@ def deploy_release( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1517,7 +1514,6 @@ def get_skill( Get skill. Get information about a skill. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1525,14 +1521,14 @@ def get_skill( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. :param str skill_id: Unique identifier of the skill. To find the skill ID - in the Watson Assistant user interface, open the skill settings and click + in the watsonx Assistant user interface, open the skill settings and click **API Details**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1594,7 +1590,6 @@ def update_skill( **Note:** The update is performed asynchronously; you can see the status of the update by calling the **Get skill** method and checking the value of the **status** property. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1602,14 +1597,14 @@ def update_skill( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. :param str skill_id: Unique identifier of the skill. To find the skill ID - in the Watson Assistant user interface, open the skill settings and click + in the watsonx Assistant user interface, open the skill settings and click **API Details**. :param str name: (optional) The name of the skill. This string cannot contain carriage return, newline, or tab characters. @@ -1620,6 +1615,8 @@ def update_skill( :param dict dialog_settings: (optional) For internal use only. :param SearchSettings search_settings: (optional) An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Skill` object @@ -1698,7 +1695,6 @@ def export_skills( failure. When processing has completed, the request returns the exported JSON data. Remember that the usual rate limits apply. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1706,7 +1702,7 @@ def export_skills( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1775,7 +1771,6 @@ def import_skills( skills belonging to the assistant are not available until processing completes. To check the status of the asynchronous import operation, use the **Get status of skills import** method. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1783,7 +1778,7 @@ def import_skills( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -1861,7 +1856,6 @@ def import_skills_status( Retrieve the status of an asynchronous import operation previously initiated by using the **Import skills** method. - This method is available only with Enterprise plans. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1869,7 +1863,7 @@ def import_skills_status( - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the Watson Assistant user + To find the environment ID or assistant ID in the watsonx Assistant user interface, open the assistant settings and scroll to the **Environments** section. **Note:** If you are using the classic Watson Assistant experience, always @@ -2400,10 +2394,10 @@ class BaseEnvironmentOrchestration: """ The search skill orchestration settings for the environment. - :param bool search_skill_fallback: (optional) Whether assistants deployed to the - environment fall back to a search skill when responding to messages that do not - match any intent. If no search skill is configured for the assistant, this - property is ignored. + :param bool search_skill_fallback: (optional) Whether to fall back to a search + skill when responding to messages that do not match any intent or action defined + in dialog or action skills. (If no search skill is configured for the + environment, this property is ignored.). """ def __init__( @@ -2414,10 +2408,10 @@ def __init__( """ Initialize a BaseEnvironmentOrchestration object. - :param bool search_skill_fallback: (optional) Whether assistants deployed - to the environment fall back to a search skill when responding to messages - that do not match any intent. If no search skill is configured for the - assistant, this property is ignored. + :param bool search_skill_fallback: (optional) Whether to fall back to a + search skill when responding to messages that do not match any intent or + action defined in dialog or action skills. (If no search skill is + configured for the environment, this property is ignored.). """ self.search_skill_fallback = search_skill_fallback @@ -3528,7 +3522,7 @@ class DialogSuggestion: of the next message sent to the assistant. Do not modify or remove any of the included properties. :param dict output: (optional) The dialog output that will be returned from the - Watson Assistant service if the user selects the corresponding option. + watsonx Assistant service if the user selects the corresponding option. """ def __init__( @@ -3551,7 +3545,7 @@ def __init__( body of the next message sent to the assistant. Do not modify or remove any of the included properties. :param dict output: (optional) The dialog output that will be returned from - the Watson Assistant service if the user selects the corresponding option. + the watsonx Assistant service if the user selects the corresponding option. """ self.label = label self.value = value @@ -3695,7 +3689,7 @@ class Environment: other than the `draft` and `live` environments have the type `staging`. :param BaseEnvironmentReleaseReference release_reference: (optional) An object describing the release that is currently deployed in the environment. - :param BaseEnvironmentOrchestration orchestration: (optional) The search skill + :param BaseEnvironmentOrchestration orchestration: The search skill orchestration settings for the environment. :param int session_timeout: The session inactivity timeout setting for the environment (in seconds). @@ -3710,6 +3704,7 @@ class Environment: def __init__( self, + orchestration: 'BaseEnvironmentOrchestration', session_timeout: int, skill_references: List['EnvironmentSkill'], *, @@ -3719,7 +3714,6 @@ def __init__( environment_id: Optional[str] = None, environment: Optional[str] = None, release_reference: Optional['BaseEnvironmentReleaseReference'] = None, - orchestration: Optional['BaseEnvironmentOrchestration'] = None, integration_references: Optional[List['IntegrationReference']] = None, created: Optional[datetime] = None, updated: Optional[datetime] = None, @@ -3727,6 +3721,8 @@ def __init__( """ Initialize a Environment object. + :param BaseEnvironmentOrchestration orchestration: The search skill + orchestration settings for the environment. :param int session_timeout: The session inactivity timeout setting for the environment (in seconds). :param List[EnvironmentSkill] skill_references: An array of objects @@ -3769,6 +3765,10 @@ def from_dict(cls, _dict: Dict) -> 'Environment': if (orchestration := _dict.get('orchestration')) is not None: args['orchestration'] = BaseEnvironmentOrchestration.from_dict( orchestration) + else: + raise ValueError( + 'Required property \'orchestration\' not present in Environment JSON' + ) if (session_timeout := _dict.get('session_timeout')) is not None: args['session_timeout'] = session_timeout else: @@ -3823,13 +3823,11 @@ def to_dict(self) -> Dict: else: _dict['release_reference'] = getattr( self, 'release_reference').to_dict() - if hasattr(self, 'orchestration') and getattr( - self, 'orchestration') is not None: - if isinstance(getattr(self, 'orchestration'), dict): - _dict['orchestration'] = getattr(self, 'orchestration') + if hasattr(self, 'orchestration') and self.orchestration is not None: + if isinstance(self.orchestration, dict): + _dict['orchestration'] = self.orchestration else: - _dict['orchestration'] = getattr(self, - 'orchestration').to_dict() + _dict['orchestration'] = self.orchestration.to_dict() if hasattr(self, 'session_timeout') and self.session_timeout is not None: _dict['session_timeout'] = self.session_timeout @@ -4807,7 +4805,7 @@ class MessageContextGlobalStateless: :param MessageContextGlobalSystem system: (optional) Built-in system properties that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param str session_id: (optional) The session ID. """ def __init__( @@ -5807,6 +5805,13 @@ class MessageInputOptions: not affect `turn_count` or any other context variables. :param bool alternate_intents: (optional) Whether to return more than one intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the initial + message response signals to the client that the operation may be long running. + With synchronous execution the custom extension is executed and returns the + response in a single message turn. **Note:** **async_callout** defaults to true + for API versions earlier than 2023-06-15. :param MessageInputOptionsSpelling spelling: (optional) Spelling correction options for the message. Any options specified on an individual message override the settings configured for the skill. @@ -5830,6 +5835,7 @@ def __init__( *, restart: Optional[bool] = None, alternate_intents: Optional[bool] = None, + async_callout: Optional[bool] = None, spelling: Optional['MessageInputOptionsSpelling'] = None, debug: Optional[bool] = None, return_context: Optional[bool] = None, @@ -5843,6 +5849,14 @@ def __init__( This does not affect `turn_count` or any other context variables. :param bool alternate_intents: (optional) Whether to return more than one intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the + initial message response signals to the client that the operation may be + long running. With synchronous execution the custom extension is executed + and returns the response in a single message turn. **Note:** + **async_callout** defaults to true for API versions earlier than + 2023-06-15. :param MessageInputOptionsSpelling spelling: (optional) Spelling correction options for the message. Any options specified on an individual message override the settings configured for the skill. @@ -5863,6 +5877,7 @@ def __init__( """ self.restart = restart self.alternate_intents = alternate_intents + self.async_callout = async_callout self.spelling = spelling self.debug = debug self.return_context = return_context @@ -5876,6 +5891,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': args['restart'] = restart if (alternate_intents := _dict.get('alternate_intents')) is not None: args['alternate_intents'] = alternate_intents + if (async_callout := _dict.get('async_callout')) is not None: + args['async_callout'] = async_callout if (spelling := _dict.get('spelling')) is not None: args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) if (debug := _dict.get('debug')) is not None: @@ -5899,6 +5916,8 @@ def to_dict(self) -> Dict: if hasattr(self, 'alternate_intents') and self.alternate_intents is not None: _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'async_callout') and self.async_callout is not None: + _dict['async_callout'] = self.async_callout if hasattr(self, 'spelling') and self.spelling is not None: if isinstance(self.spelling, dict): _dict['spelling'] = self.spelling @@ -7747,7 +7766,7 @@ class RuntimeEntity: :param str value: The term in the input text that was recognized as an entity value. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. + confidence in the recognized 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 @@ -7796,7 +7815,7 @@ def __init__( offsets that indicate where the detected entity values begin and end in the input text. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the recognized entity. + confidence in the recognized 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 @@ -7939,7 +7958,7 @@ class RuntimeEntityAlternative: :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. + confidence in the recognized entity. """ def __init__( @@ -7954,7 +7973,7 @@ def __init__( :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. + confidence in the recognized entity. """ self.value = value self.confidence = confidence @@ -8453,8 +8472,8 @@ class RuntimeIntent: :param str intent: The name of the recognized intent. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the intent. If you are specifying an intent as part of a - request, but you do not have a calculated confidence value, specify `1`. + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. :param str skill: (optional) The skill that identified the intent. Currently, the only possible values are `main skill` for the dialog skill (if enabled) and `actions skill` for the action skill. @@ -8474,9 +8493,8 @@ def __init__( :param str intent: The name of the recognized intent. :param float confidence: (optional) A decimal percentage that represents - Watson's confidence in the intent. If you are specifying an intent as part - of a request, but you do not have a calculated confidence value, specify - `1`. + confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. :param str skill: (optional) The skill that identified the intent. Currently, the only possible values are `main skill` for the dialog skill (if enabled) and `actions skill` for the action skill. @@ -9068,6 +9086,8 @@ def __ne__(self, other: 'SearchResultMetadata') -> bool: class SearchSettings: """ An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and are not + included in **Export skills** responses. :param SearchSettingsDiscovery discovery: Configuration settings for the Watson Discovery service instance used by the search integration. @@ -9779,6 +9799,8 @@ class Skill: skill is saved for each new release of an assistant. :param SearchSettings search_settings: (optional) An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. :param List[SearchSkillWarning] warnings: (optional) An array of warnings describing errors with the search skill configuration. Included only for search skills. @@ -9821,6 +9843,8 @@ def __init__( :param dict dialog_settings: (optional) For internal use only. :param SearchSettings search_settings: (optional) An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. """ self.name = name self.description = description @@ -10042,6 +10066,8 @@ class SkillImport: skill is saved for each new release of an assistant. :param SearchSettings search_settings: (optional) An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. :param List[SearchSkillWarning] warnings: (optional) An array of warnings describing errors with the search skill configuration. Included only for search skills. @@ -10084,6 +10110,8 @@ def __init__( :param dict dialog_settings: (optional) For internal use only. :param SearchSettings search_settings: (optional) An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. """ self.name = name self.description = description @@ -10266,7 +10294,6 @@ class TypeEnum(str, Enum): ACTION = 'action' DIALOG = 'dialog' - SEARCH = 'search' class SkillsAsyncRequestStatus: From d980178de2ffbf9ffd491113a9a5fd1f82ed4557 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 21 Feb 2024 13:49:12 -0600 Subject: [PATCH 409/455] feat(disco-v2): new params for EnrichmentOptions --- ibm_watson/discovery_v2.py | 299 ++++++++++++++++++++++++++++++++----- 1 file changed, 259 insertions(+), 40 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 5253de7b2..ba7aba4cd 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2023. +# (C) Copyright IBM Corp. 2019, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ def __init__( Construct a new client for the Discovery service. :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2020-08-30`. + Specify dates in YYYY-MM-DD format. The current version is `2023-03-31`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md @@ -557,7 +557,7 @@ def get_collection( **kwargs, ) -> DetailedResponse: """ - Get collection. + Get collection details. Get details about the specified collection. @@ -618,7 +618,19 @@ def update_collection( """ Update a collection. - Updates the specified collection's name, description, and enrichments. + Updates the specified collection's name, description, enrichments, and + configuration. + If you apply normalization rules to data in an existing collection, you must + initiate reprocessing of the collection. To do so, from the *Manage fields* page + in the product user interface, temporarily change the data type of a field to + enable the reprocess button. Change the data type of the field back to its + original value, and then click **Apply changes and reprocess**. + To remove a configuration that applies JSON normalization operations as part of + the conversion phase of ingestion, specify an empty `json_normalizations` object + (`[]`) in the request. + To remove a configuration that applies JSON normalization operations after + enrichments are applied, specify an empty `normalizations` object (`[]`) in the + request. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -758,8 +770,7 @@ def list_documents( Lists the documents in the specified collection. The list includes only the document ID of each document and returns information for up to 10,000 documents. **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and - later installed instances and from Plus and Enterprise plan IBM Cloud-managed - instances. It is not currently available from Premium plan instances. + later installed instances, and from IBM Cloud-managed instances. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -885,12 +896,13 @@ def add_document( :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) When adding a document, the content of the - document to ingest. For maximum supported file size limits, see [the - documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). - When analyzing a document, the content of the document to analyze but not - ingest. Only the `application/json` content type is supported currently. - For maximum supported file size limits, see [the product + :param BinaryIO file: (optional) **Add a document**: The content of the + document to ingest. For the supported file types and maximum supported file + size limits when adding a document, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + **Analyze a document**: The content of the document to analyze but not + ingest. Only the `application/json` content type is supported by the + Analyze API. For maximum supported file size limits, see [the product documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -975,8 +987,7 @@ def get_document( Get details about a specific document, whether the document is added by uploading a file or by crawling an external data source. **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and - later installed instances and from Plus and Enterprise plan IBM Cloud-managed - instances. It is not currently available from Premium plan instances. + later installed instances, and from IBM Cloud-managed instances. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -1059,12 +1070,13 @@ def update_document( from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param BinaryIO file: (optional) When adding a document, the content of the - document to ingest. For maximum supported file size limits, see [the - documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). - When analyzing a document, the content of the document to analyze but not - ingest. Only the `application/json` content type is supported currently. - For maximum supported file size limits, see [the product + :param BinaryIO file: (optional) **Add a document**: The content of the + document to ingest. For the supported file types and maximum supported file + size limits when adding a document, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + **Analyze a document**: The content of the document to analyze but not + ingest. Only the `application/json` content type is supported by the + Analyze API. For maximum supported file size limits, see [the product documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -1272,10 +1284,14 @@ def query( Discovery Query Language and returns all matching documents in your data set with full enrichments and full text, and with the most relevant documents listed first. Use a query search when you want to find the most - relevant search results. + relevant search results. You can use this parameter or the + **natural_language_query** parameter to specify the query input, but not + both. :param str natural_language_query: (optional) A natural language query that returns relevant documents by using training data and natural language - understanding. + understanding. You can use this parameter or the **query** parameter to + specify the query input, but not both. To filter the results based on + criteria you specify, include the **filter** parameter in the request. :param str aggregation: (optional) An aggregation search that returns an exact answer by combining query search with filters. Useful for applications to build lists, tables, and time series. For more information @@ -1399,6 +1415,9 @@ def get_autocompletion( Get Autocomplete Suggestions. Returns completion query suggestions for the specified prefix. + Suggested words are based on terms from the project documents. Suggestions are not + based on terms from the project's search history, and the project does not learn + from previous user choices. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -1487,10 +1506,14 @@ def query_collection_notices( :param str query: (optional) A query search that is written in the Discovery Query Language and returns all matching documents in your data set with full enrichments and full text, and with the most relevant - documents listed first. + documents listed first. You can use this parameter or the + **natural_language_query** parameter to specify the query input, but not + both. :param str natural_language_query: (optional) A natural language query that - returns relevant documents by using training data and natural language - understanding. + returns relevant documents by using natural language understanding. You can + use this parameter or the **query** parameter to specify the query input, + but not both. To filter the results based on criteria you specify, include + the **filter** parameter in the request. :param int count: (optional) Number of results to return. The maximum for the **count** and **offset** values together in any one query is **10,000**. @@ -1573,10 +1596,14 @@ def query_notices( :param str query: (optional) A query search that is written in the Discovery Query Language and returns all matching documents in your data set with full enrichments and full text, and with the most relevant - documents listed first. + documents listed first. You can use this parameter or the + **natural_language_query** parameter to specify the query input, but not + both. :param str natural_language_query: (optional) A natural language query that - returns relevant documents by using training data and natural language - understanding. + returns relevant documents by using natural language understanding. You can + use this parameter or the **query** parameter to specify the query input, + but not both. To filter the results based on criteria you specify, include + the **filter** parameter in the request. :param int count: (optional) Number of results to return. The maximum for the **count** and **offset** values together in any one query is **10,000**. @@ -2184,10 +2211,11 @@ def create_training_query( **kwargs, ) -> DetailedResponse: """ - Create training query. + Create a training query. Add a query to the training data for this project. The query can contain a filter and natural language query. + **Note**: You cannot apply relevancy training to a `content_mining` project type. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -2195,7 +2223,11 @@ def create_training_query( the training query. :param List[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + **natural_language_query** is applied. Only specify a filter if the + documents that you consider to be most relevant are not included in the top + 100 results when you submit test queries. If you specify a filter during + training, apply the same filter to queries that are submitted at runtime + for optimal ranking results. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object @@ -2319,7 +2351,8 @@ def update_training_query( """ Update a training query. - Updates an existing training query and it's examples. + Updates an existing training query and its examples. You must resubmit all of the + examples with the update request. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -2328,7 +2361,11 @@ def update_training_query( the training query. :param List[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + **natural_language_query** is applied. Only specify a filter if the + documents that you consider to be most relevant are not included in the top + 100 results when you submit test queries. If you specify a filter during + training, apply the same filter to queries that are submitted at runtime + for optimal ranking results. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object @@ -2396,6 +2433,8 @@ def delete_training_query( Removes details from a training data query, including the query string and all examples. + To delete an example, use the *Update a training query* method and omit the + example that you want to delete from the example set. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. @@ -2517,7 +2556,8 @@ def create_enrichment( enrichment. :param BinaryIO file: (optional) The enrichment file to upload. Expected file types per enrichment are as follows: - * CSV for `dictionary` + * CSV for `dictionary` and `sentence_classifier` (the training data CSV + file to upload). * PEAR for `uima_annotator` and `rule_based` (Explorer) * ZIP for `watson_knowledge_studio_model` and `rule_based` (Studio Advanced Rule Editor). @@ -3461,7 +3501,7 @@ def analyze_document( **kwargs, ) -> DetailedResponse: """ - Analyze a Document. + Analyze a document. Process a document and return it for realtime use. Supports JSON files only. The file is not stored in the collection, but is processed according to the @@ -3471,18 +3511,23 @@ def analyze_document( enrichments to the `Quote` field in the collection configuration. Then, when you analyze the file, the text in the `Quote` field is analyzed and results are written to a field named `enriched_Quote`. + Submit a request against only one collection at a time. Remember, the documents in + the collection are not significant. It is the enrichments that are defined for the + collection that matter. If you submit requests to several collections, then + several models are initiated at the same time, which can cause request failures. **Note:** This method is supported with Enterprise plan deployments and installed deployments only. :param str project_id: The ID of the project. This information can be found from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) When adding a document, the content of the - document to ingest. For maximum supported file size limits, see [the - documentation](/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). - When analyzing a document, the content of the document to analyze but not - ingest. Only the `application/json` content type is supported currently. - For maximum supported file size limits, see [the product + :param BinaryIO file: (optional) **Add a document**: The content of the + document to ingest. For the supported file types and maximum supported file + size limits when adding a document, see [the + documentation](/docs/discovery-data?topic=discovery-data-collections#supportedfiletypes). + **Analyze a document**: The content of the document to analyze but not + ingest. Only the `application/json` content type is supported by the + Analyze API. For maximum supported file size limits, see [the product documentation](/docs/discovery-data?topic=discovery-data-analyzeapi#analyzeapi-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. @@ -5068,6 +5113,14 @@ class CreateEnrichment: * Rule-based model that is created in Watson Knowledge Studio. * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. + * `webhook`: Connects to an external enrichment application by using a webhook. + The feature is available from IBM Cloud-managed instances only. The external + enrichment feature is beta functionality. Beta features are not supported by the + SDKs. + * `sentence_classifier`: Use sentence classifier to classify sentences in your + documents. This feature is available in IBM Cloud-managed instances only. The + sentence classifier feature is beta functionality. Beta features are not + supported by the SDKs. :param EnrichmentOptions options: (optional) An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments method. @@ -5105,6 +5158,14 @@ def __init__( * Rule-based model that is created in Watson Knowledge Studio. * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. + * `webhook`: Connects to an external enrichment application by using a + webhook. The feature is available from IBM Cloud-managed instances only. + The external enrichment feature is beta functionality. Beta features are + not supported by the SDKs. + * `sentence_classifier`: Use sentence classifier to classify sentences in + your documents. This feature is available in IBM Cloud-managed instances + only. The sentence classifier feature is beta functionality. Beta features + are not supported by the SDKs. :param EnrichmentOptions options: (optional) An object that contains options for the current enrichment. Starting with version `2020-08-30`, the enrichment options are not included in responses from the List Enrichments @@ -5188,6 +5249,14 @@ class TypeEnum(str, Enum): * Rule-based model that is created in Watson Knowledge Studio. * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. + * `webhook`: Connects to an external enrichment application by using a webhook. + The feature is available from IBM Cloud-managed instances only. The external + enrichment feature is beta functionality. Beta features are not supported by the + SDKs. + * `sentence_classifier`: Use sentence classifier to classify sentences in your + documents. This feature is available in IBM Cloud-managed instances only. The + sentence classifier feature is beta functionality. Beta features are not supported + by the SDKs. """ CLASSIFIER = 'classifier' @@ -5196,6 +5265,8 @@ class TypeEnum(str, Enum): UIMA_ANNOTATOR = 'uima_annotator' RULE_BASED = 'rule_based' WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' + WEBHOOK = 'webhook' + SENTENCE_CLASSIFIER = 'sentence_classifier' class DefaultQueryParams: @@ -6811,6 +6882,8 @@ class TypeEnum(str, Enum): RULE_BASED = 'rule_based' WATSON_KNOWLEDGE_STUDIO_MODEL = 'watson_knowledge_studio_model' CLASSIFIER = 'classifier' + WEBHOOK = 'webhook' + SENTENCE_CLASSIFIER = 'sentence_classifier' class EnrichmentOptions: @@ -6849,6 +6922,25 @@ class EnrichmentOptions: **confidence_threshold** is used to determine the predicted classes. Optional when **type** is `classifier`. Not valid when creating any other type of enrichment. + :param str url: (optional) A URL that uses the SSL protocol (begins with https) + for the webhook. Required when type is `webhook`. Not valid when creating any + other type of enrichment. + :param str version: (optional) The Discovery API version that allows to + distinguish the schema. The version is specified in the `yyyy-mm-dd` format. + Optional when `type` is `webhook`. Not valid when creating any other type of + enrichment. + :param str secret: (optional) A private key can be included in the request to + authenticate with the external service. The maximum length is 1,024 characters. + Optional when `type` is `webhook`. Not valid when creating any other type of + enrichment. + :param WebhookHeader headers_: (optional) An array of headers to pass with the + HTTP request. Optional when `type` is `webhook`. Not valid when creating any + other type of enrichment. + :param str location_encoding: (optional) Discovery calculates offsets of the + text's location with this encoding type in documents. Use the same location + encoding type in both Discovery and external enrichment for a document. + These encoding types are supported: `utf-8`, `utf-16`, and `utf-32`. Optional + when `type` is `webhook`. Not valid when creating any other type of enrichment. """ def __init__( @@ -6862,6 +6954,11 @@ def __init__( model_id: Optional[str] = None, confidence_threshold: Optional[float] = None, top_k: Optional[int] = None, + url: Optional[str] = None, + version: Optional[str] = None, + secret: Optional[str] = None, + headers_: Optional['WebhookHeader'] = None, + location_encoding: Optional[str] = None, ) -> None: """ Initialize a EnrichmentOptions object. @@ -6897,6 +6994,27 @@ def __init__( **confidence_threshold** is used to determine the predicted classes. Optional when **type** is `classifier`. Not valid when creating any other type of enrichment. + :param str url: (optional) A URL that uses the SSL protocol (begins with + https) for the webhook. Required when type is `webhook`. Not valid when + creating any other type of enrichment. + :param str version: (optional) The Discovery API version that allows to + distinguish the schema. The version is specified in the `yyyy-mm-dd` + format. Optional when `type` is `webhook`. Not valid when creating any + other type of enrichment. + :param str secret: (optional) A private key can be included in the request + to authenticate with the external service. The maximum length is 1,024 + characters. Optional when `type` is `webhook`. Not valid when creating any + other type of enrichment. + :param WebhookHeader headers_: (optional) An array of headers to pass with + the HTTP request. Optional when `type` is `webhook`. Not valid when + creating any other type of enrichment. + :param str location_encoding: (optional) Discovery calculates offsets of + the text's location with this encoding type in documents. Use the same + location encoding type in both Discovery and external enrichment for a + document. + These encoding types are supported: `utf-8`, `utf-16`, and `utf-32`. + Optional when `type` is `webhook`. Not valid when creating any other type + of enrichment. """ self.languages = languages self.entity_type = entity_type @@ -6906,6 +7024,11 @@ def __init__( self.model_id = model_id self.confidence_threshold = confidence_threshold self.top_k = top_k + self.url = url + self.version = version + self.secret = secret + self.headers_ = headers_ + self.location_encoding = location_encoding @classmethod def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': @@ -6928,6 +7051,16 @@ def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': args['confidence_threshold'] = confidence_threshold if (top_k := _dict.get('top_k')) is not None: args['top_k'] = top_k + if (url := _dict.get('url')) is not None: + args['url'] = url + if (version := _dict.get('version')) is not None: + args['version'] = version + if (secret := _dict.get('secret')) is not None: + args['secret'] = secret + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = WebhookHeader.from_dict(headers_) + if (location_encoding := _dict.get('location_encoding')) is not None: + args['location_encoding'] = location_encoding return cls(**args) @classmethod @@ -6957,6 +7090,20 @@ def to_dict(self) -> Dict: _dict['confidence_threshold'] = self.confidence_threshold if hasattr(self, 'top_k') and self.top_k is not None: _dict['top_k'] = self.top_k + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'version') and self.version is not None: + _dict['version'] = self.version + if hasattr(self, 'secret') and self.secret is not None: + _dict['secret'] = self.secret + if hasattr(self, 'headers_') and self.headers_ is not None: + if isinstance(self.headers_, dict): + _dict['headers'] = self.headers_ + else: + _dict['headers'] = self.headers_.to_dict() + if hasattr(self, + 'location_encoding') and self.location_encoding is not None: + _dict['location_encoding'] = self.location_encoding return _dict def _to_dict(self): @@ -12807,6 +12954,78 @@ def __ne__(self, other: 'UpdateDocumentClassifier') -> bool: return not self == other +class WebhookHeader: + """ + An array of headers to pass with the HTTP request. Optional when `type` is `webhook`. + Not valid when creating any other type of enrichment. + + :param str name: The name of an HTTP header. + :param str value: The value of an HTTP header. + """ + + def __init__( + self, + name: str, + value: str, + ) -> None: + """ + Initialize a WebhookHeader object. + + :param str name: The name of an HTTP header. + :param str value: The value of an HTTP header. + """ + self.name = name + self.value = value + + @classmethod + def from_dict(cls, _dict: Dict) -> 'WebhookHeader': + """Initialize a WebhookHeader object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + else: + raise ValueError( + 'Required property \'name\' not present in WebhookHeader JSON') + if (value := _dict.get('value')) is not None: + args['value'] = value + else: + raise ValueError( + 'Required property \'value\' not present in WebhookHeader JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a WebhookHeader 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value + 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 WebhookHeader object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'WebhookHeader') -> 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: 'WebhookHeader') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryAggregationQueryCalculationAggregation(QueryAggregation): """ Returns a scalar calculation across all documents for the field specified. Possible From 134fa6d868396875a33806d1e688156ceecd60c5 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 21 Feb 2024 14:15:17 -0600 Subject: [PATCH 410/455] feat(nlu): add support for userMetadata param --- .../natural_language_understanding_v1.py | 34 ++++++++++++++++--- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 43955211d..967e52c05 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2017, 2023. +# (C) Copyright IBM Corp. 2017, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ with Watson Knowledge Studio to detect custom entities and relations in Natural Language Understanding. IBM is sunsetting Watson Natural Language Understanding Custom Sentiment (BETA). From -**June 1, 2023** onward, you will no longer be able to use the Custom Sentiment +**June 3, 2023** onward, you will no longer be able to use the Custom Sentiment feature.

To ensure we continue providing our clients with robust and powerful text classification capabilities, IBM recently announced the general availability of a new [single-label text classification @@ -314,6 +314,7 @@ def create_categories_model( *, training_data_content_type: Optional[str] = 'application/json', name: Optional[str] = None, + user_metadata: Optional[dict] = None, description: Optional[str] = None, model_version: Optional[str] = None, workspace_id: Optional[str] = None, @@ -334,6 +335,8 @@ def create_categories_model( :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio @@ -367,6 +370,9 @@ def create_categories_model( 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -495,6 +501,7 @@ def update_categories_model( *, training_data_content_type: Optional[str] = 'application/json', name: Optional[str] = None, + user_metadata: Optional[dict] = None, description: Optional[str] = None, model_version: Optional[str] = None, workspace_id: Optional[str] = None, @@ -515,6 +522,8 @@ def update_categories_model( :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio @@ -550,6 +559,9 @@ def update_categories_model( 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -643,6 +655,7 @@ def create_classifications_model( *, training_data_content_type: Optional[str] = 'application/json', name: Optional[str] = None, + user_metadata: Optional[dict] = None, description: Optional[str] = None, model_version: Optional[str] = None, workspace_id: Optional[str] = None, @@ -665,6 +678,8 @@ def create_classifications_model( :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio @@ -701,6 +716,9 @@ def create_classifications_model( 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -833,6 +851,7 @@ def update_classifications_model( *, training_data_content_type: Optional[str] = 'application/json', name: Optional[str] = None, + user_metadata: Optional[dict] = None, description: Optional[str] = None, model_version: Optional[str] = None, workspace_id: Optional[str] = None, @@ -855,6 +874,8 @@ def update_classifications_model( :param str training_data_content_type: (optional) The content type of training_data. :param str name: (optional) An optional name for the model. + :param dict user_metadata: (optional) An optional map of metadata key-value + pairs to store with this model. :param str description: (optional) An optional description of the model. :param str model_version: (optional) An optional version string. :param str workspace_id: (optional) ID of the Watson Knowledge Studio @@ -893,6 +914,9 @@ def update_classifications_model( 'application/octet-stream'))) if name: form_data.append(('name', (None, name, 'text/plain'))) + if user_metadata: + form_data.append(('user_metadata', (None, json.dumps(user_metadata), + 'application/json'))) if description: form_data.append(('description', (None, description, 'text/plain'))) if model_version: @@ -3162,7 +3186,7 @@ class EntitiesOptions: """ Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and - subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-type-systems). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. @@ -3580,7 +3604,7 @@ class Features: :param EntitiesOptions entities: (optional) Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and - subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-type-systems). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. @@ -3655,7 +3679,7 @@ def __init__( :param EntitiesOptions entities: (optional) Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and - subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). + subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-type-systems). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. From 0fa495cf24438d7a937904735f1dd23e33f3cd31 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 21 Feb 2024 14:19:07 -0600 Subject: [PATCH 411/455] feat(stt): new params smart_formatting_version, force, mapping_only --- ibm_watson/speech_to_text_v1.py | 121 +++++++++++++++++++++++++--- test/unit/test_speech_to_text_v1.py | 28 +++++-- 2 files changed, 133 insertions(+), 16 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index dda763930..f6d1022bc 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2023. +# (C) Copyright IBM Corp. 2015, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -209,6 +209,7 @@ def recognize( timestamps: Optional[bool] = None, profanity_filter: Optional[bool] = None, smart_formatting: Optional[bool] = None, + smart_formatting_version: Optional[bool] = None, speaker_labels: Optional[bool] = None, grammar_name: Optional[str] = None, redaction: Optional[bool] = None, @@ -446,6 +447,9 @@ def recognize( (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). + :param bool smart_formatting_version: (optional) Smart formatting version + is for next-generation models and that is supported in US English, + Brazilian Portuguese, French and German languages. :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. @@ -618,6 +622,7 @@ def recognize( 'timestamps': timestamps, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, + 'smart_formatting_version': smart_formatting_version, 'speaker_labels': speaker_labels, 'grammar_name': grammar_name, 'redaction': redaction, @@ -813,6 +818,7 @@ def create_job( timestamps: Optional[bool] = None, profanity_filter: Optional[bool] = None, smart_formatting: Optional[bool] = None, + smart_formatting_version: Optional[bool] = None, speaker_labels: Optional[bool] = None, grammar_name: Optional[str] = None, redaction: Optional[bool] = None, @@ -1100,6 +1106,9 @@ def create_job( (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). + :param bool smart_formatting_version: (optional) Smart formatting version + is for next-generation models and that is supported in US English, + Brazilian Portuguese, French and German languages. :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. @@ -1298,6 +1307,7 @@ def create_job( 'timestamps': timestamps, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, + 'smart_formatting_version': smart_formatting_version, 'speaker_labels': speaker_labels, 'grammar_name': grammar_name, 'redaction': redaction, @@ -1776,6 +1786,7 @@ def train_language_model( word_type_to_add: Optional[str] = None, customization_weight: Optional[float] = None, strict: Optional[bool] = None, + force: Optional[bool] = None, **kwargs, ) -> DetailedResponse: """ @@ -1863,6 +1874,15 @@ def train_language_model( lists any invalid resources. By default (`true`), training of a custom language model fails (status code 400) if the model contains one or more invalid resources (corpus files, grammar files, or custom words). + :param bool force: (optional) If `true`, forces the training of the custom + language model regardless of whether it contains any changes (is in the + `ready` or `available` state). By default (`false`), the model must be in + the `ready` state to be trained. You can use the parameter to train and + thus upgrade a custom model that is based on an improved next-generation + model. *The parameter is available only for IBM Cloud, not for IBM Cloud + Pak for Data.* + See [Upgrading a custom language model based on an improved next-generation + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language-ng). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingResponse` object @@ -1882,6 +1902,7 @@ def train_language_model( 'word_type_to_add': word_type_to_add, 'customization_weight': customization_weight, 'strict': strict, + 'force': force, } if 'headers' in kwargs: @@ -2491,6 +2512,13 @@ def add_words( omit the `sounds_like` field, the service attempts to set the field to its pronunciation of the word. It cannot generate a pronunciation for all words, so you must review the word's definition to ensure that it is complete and valid. + * The `mapping_only` field provides parameter for custom words. You can use the + 'mapping_only' key in custom words as a form of post processing. This key + parameter has a boolean value to determine whether 'sounds_like' (for non-Japanese + models) or word (for Japanese) is not used for the model fine-tuning, but for the + replacement for 'display_as'. This feature helps you when you use custom words + exclusively to map 'sounds_like' (or word) to 'display_as' value. When you use + custom words solely for post-processing purposes that does not need fine-tuning. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error with the input data, it returns a failure code and @@ -2580,6 +2608,7 @@ def add_word( word_name: str, *, word: Optional[str] = None, + mapping_only: Optional[List[str]] = None, sounds_like: Optional[List[str]] = None, display_as: Optional[str] = None, **kwargs, @@ -2638,16 +2667,30 @@ def add_word( request with credentials for the instance of the service that owns the custom model. :param str word_name: The custom word that is to be added to or updated in - the custom language model. Do not include spaces in the word. Use a `-` + the custom language model. Do not use characters that need to be + URL-encoded, for example, spaces, slashes, backslashes, colons, ampersands, + double quotes, plus signs, equals signs, or question marks. Use a `-` (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/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). :param str word: (optional) For the [Add custom words](#addwords) 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 `_` - (underscore) to connect the tokens of compound words. + custom model. Do not use characters that need to be URL-encoded, for + example, spaces, slashes, backslashes, colons, ampersands, double quotes, + plus signs, equals signs, or question marks. Use a `-` (dash) or `_` + (underscore) to connect the tokens of compound words. A Japanese custom + word can include at most 25 characters, not including leading or trailing + spaces. Omit this parameter for the [Add a custom word](#addword) method. + :param List[str] mapping_only: (optional) Parameter for custom words. You + can use the 'mapping_only' key in custom words as a form of post + processing. This key parameter has a boolean value to determine whether + 'sounds_like' (for non-Japanese models) or word (for Japanese) is not used + for the model fine-tuning, but for the replacement for 'display_as'. This + feature helps you when you use custom words exclusively to map + 'sounds_like' (or word) to 'display_as' value. When you use custom words + solely for post-processing purposes that does not need fine-tuning. :param List[str] sounds_like: (optional) As array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. @@ -2660,7 +2703,9 @@ def add_word( default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation - can include at most 40 characters not including spaces. + can include at most 40 characters, not including leading or trailing + spaces. A Japanese pronunciation can include at most 25 characters, not + including leading or trailing spaces. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or @@ -2687,6 +2732,7 @@ def add_word( data = { 'word': word, + 'mapping_only': mapping_only, 'sounds_like': sounds_like, 'display_as': display_as, } @@ -6266,9 +6312,20 @@ class CustomWord: :param str word: (optional) For the [Add custom words](#addwords) 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 `_` (underscore) - to connect the tokens of compound words. + model. Do not use characters that need to be URL-encoded, for example, spaces, + slashes, backslashes, colons, ampersands, double quotes, plus signs, equals + signs, or question marks. Use a `-` (dash) or `_` (underscore) to connect the + tokens of compound words. A Japanese custom word can include at most 25 + characters, not including leading or trailing spaces. Omit this parameter for the [Add a custom word](#addword) method. + :param List[str] mapping_only: (optional) Parameter for custom words. You can + use the 'mapping_only' key in custom words as a form of post processing. This + key parameter has a boolean value to determine whether 'sounds_like' (for + non-Japanese models) or word (for Japanese) is not used for the model + fine-tuning, but for the replacement for 'display_as'. This feature helps you + when you use custom words exclusively to map 'sounds_like' (or word) to + 'display_as' value. When you use custom words solely for post-processing + purposes that does not need fine-tuning. :param List[str] sounds_like: (optional) As array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. @@ -6280,7 +6337,9 @@ class CustomWord: pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can - include at most 40 characters not including spaces. + include at most 40 characters, not including leading or trailing spaces. A + Japanese pronunciation can include at most 25 characters, not including leading + or trailing spaces. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its @@ -6293,6 +6352,7 @@ def __init__( self, *, word: Optional[str] = None, + mapping_only: Optional[List[str]] = None, sounds_like: Optional[List[str]] = None, display_as: Optional[str] = None, ) -> None: @@ -6301,9 +6361,21 @@ def __init__( :param str word: (optional) For the [Add custom words](#addwords) 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 `_` - (underscore) to connect the tokens of compound words. + custom model. Do not use characters that need to be URL-encoded, for + example, spaces, slashes, backslashes, colons, ampersands, double quotes, + plus signs, equals signs, or question marks. Use a `-` (dash) or `_` + (underscore) to connect the tokens of compound words. A Japanese custom + word can include at most 25 characters, not including leading or trailing + spaces. Omit this parameter for the [Add a custom word](#addword) method. + :param List[str] mapping_only: (optional) Parameter for custom words. You + can use the 'mapping_only' key in custom words as a form of post + processing. This key parameter has a boolean value to determine whether + 'sounds_like' (for non-Japanese models) or word (for Japanese) is not used + for the model fine-tuning, but for the replacement for 'display_as'. This + feature helps you when you use custom words exclusively to map + 'sounds_like' (or word) to 'display_as' value. When you use custom words + solely for post-processing purposes that does not need fine-tuning. :param List[str] sounds_like: (optional) As array of sounds-like pronunciations for the custom word. Specify how words that are difficult to pronounce, foreign words, acronyms, and so on can be pronounced by users. @@ -6316,7 +6388,9 @@ def __init__( default pronunciation of a word; pronunciations you add augment the pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation - can include at most 40 characters not including spaces. + can include at most 40 characters, not including leading or trailing + spaces. A Japanese pronunciation can include at most 25 characters, not + including leading or trailing spaces. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or @@ -6326,6 +6400,7 @@ def __init__( field. """ self.word = word + self.mapping_only = mapping_only self.sounds_like = sounds_like self.display_as = display_as @@ -6335,6 +6410,8 @@ def from_dict(cls, _dict: Dict) -> 'CustomWord': args = {} if (word := _dict.get('word')) is not None: args['word'] = word + if (mapping_only := _dict.get('mapping_only')) is not None: + args['mapping_only'] = mapping_only if (sounds_like := _dict.get('sounds_like')) is not None: args['sounds_like'] = sounds_like if (display_as := _dict.get('display_as')) is not None: @@ -6351,6 +6428,8 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word + if hasattr(self, 'mapping_only') and self.mapping_only is not None: + _dict['mapping_only'] = self.mapping_only if hasattr(self, 'sounds_like') and self.sounds_like is not None: _dict['sounds_like'] = self.sounds_like if hasattr(self, 'display_as') and self.display_as is not None: @@ -8817,6 +8896,13 @@ class Word: :param str word: A word from the custom model's words resource. The spelling of the word is used to train the model. + :param List[str] mapping_only: (optional) (Optional) Parameter for custom words. + You can use the 'mapping_only' key in custom words as a form of post processing. + A boolean value that indicates whether the added word should be used to + fine-tune the mode for selected next-gen models. This field appears in the + response body only when it's 'For a custom model that is based on a + previous-generation model', the mapping_only field is populated with the value + set by the user, but would not be used. :param List[str] sounds_like: An array of as many as five pronunciations for the word. * _For a custom model that is based on a previous-generation model_, in addition @@ -8867,6 +8953,7 @@ def __init__( count: int, source: List[str], *, + mapping_only: Optional[List[str]] = None, error: Optional[List['WordError']] = None, ) -> None: """ @@ -8912,11 +8999,19 @@ def __init__( shows only `user` for custom words that were added directly to the custom model. Words from corpora and grammars are not added to the words resource for custom models that are based on next-generation models. + :param List[str] mapping_only: (optional) (Optional) Parameter for custom + words. You can use the 'mapping_only' key in custom words as a form of post + processing. A boolean value that indicates whether the added word should be + used to fine-tune the mode for selected next-gen models. This field appears + in the response body only when it's 'For a custom model that is based on a + previous-generation model', the mapping_only field is populated with the + value set by the user, but would not be used. :param List[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. """ self.word = word + self.mapping_only = mapping_only self.sounds_like = sounds_like self.display_as = display_as self.count = count @@ -8932,6 +9027,8 @@ def from_dict(cls, _dict: Dict) -> 'Word': else: raise ValueError( 'Required property \'word\' not present in Word JSON') + if (mapping_only := _dict.get('mapping_only')) is not None: + args['mapping_only'] = mapping_only if (sounds_like := _dict.get('sounds_like')) is not None: args['sounds_like'] = sounds_like else: @@ -8966,6 +9063,8 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'word') and self.word is not None: _dict['word'] = self.word + if hasattr(self, 'mapping_only') and self.mapping_only is not None: + _dict['mapping_only'] = self.mapping_only if hasattr(self, 'sounds_like') and self.sounds_like is not None: _dict['sounds_like'] = self.sounds_like if hasattr(self, 'display_as') and self.display_as is not None: diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 3dca289f2..922c7815a 100644 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -237,6 +237,7 @@ def test_recognize_all_params(self): timestamps = False profanity_filter = True smart_formatting = False + smart_formatting_version = False speaker_labels = False grammar_name = 'testString' redaction = False @@ -266,6 +267,7 @@ def test_recognize_all_params(self): timestamps=timestamps, profanity_filter=profanity_filter, smart_formatting=smart_formatting, + smart_formatting_version=smart_formatting_version, speaker_labels=speaker_labels, grammar_name=grammar_name, redaction=redaction, @@ -297,6 +299,7 @@ def test_recognize_all_params(self): assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string + assert 'smart_formatting_version={}'.format('true' if smart_formatting_version else 'false') in query_string assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string assert 'grammar_name={}'.format(grammar_name) in query_string assert 'redaction={}'.format('true' if redaction else 'false') in query_string @@ -654,6 +657,7 @@ def test_create_job_all_params(self): timestamps = False profanity_filter = True smart_formatting = False + smart_formatting_version = False speaker_labels = False grammar_name = 'testString' redaction = False @@ -689,6 +693,7 @@ def test_create_job_all_params(self): timestamps=timestamps, profanity_filter=profanity_filter, smart_formatting=smart_formatting, + smart_formatting_version=smart_formatting_version, speaker_labels=speaker_labels, grammar_name=grammar_name, redaction=redaction, @@ -726,6 +731,7 @@ def test_create_job_all_params(self): assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string + assert 'smart_formatting_version={}'.format('true' if smart_formatting_version else 'false') in query_string assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string assert 'grammar_name={}'.format(grammar_name) in query_string assert 'redaction={}'.format('true' if redaction else 'false') in query_string @@ -1386,6 +1392,7 @@ def test_train_language_model_all_params(self): word_type_to_add = 'all' customization_weight = 72.5 strict = True + force = False # Invoke method response = _service.train_language_model( @@ -1393,6 +1400,7 @@ def test_train_language_model_all_params(self): word_type_to_add=word_type_to_add, customization_weight=customization_weight, strict=strict, + force=force, headers={}, ) @@ -1405,6 +1413,7 @@ def test_train_language_model_all_params(self): assert 'word_type_to_add={}'.format(word_type_to_add) in query_string assert 'customization_weight={}'.format(customization_weight) in query_string assert 'strict={}'.format('true' if strict else 'false') in query_string + assert 'force={}'.format('true' if force else 'false') in query_string def test_train_language_model_all_params_with_retries(self): # Enable retries and run test_train_language_model_all_params. @@ -2048,7 +2057,7 @@ def test_list_words_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' + mock_response = '{"words": [{"word": "word", "mapping_only": ["mapping_only"], "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' responses.add( responses.GET, url, @@ -2095,7 +2104,7 @@ def test_list_words_required_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' + mock_response = '{"words": [{"word": "word", "mapping_only": ["mapping_only"], "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' responses.add( responses.GET, url, @@ -2133,7 +2142,7 @@ def test_list_words_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words') - mock_response = '{"words": [{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' + mock_response = '{"words": [{"word": "word", "mapping_only": ["mapping_only"], "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}]}' responses.add( responses.GET, url, @@ -2185,6 +2194,7 @@ def test_add_words_all_params(self): # Construct a dict representation of a CustomWord model custom_word_model = {} custom_word_model['word'] = 'testString' + custom_word_model['mapping_only'] = ['testString'] custom_word_model['sounds_like'] = ['testString'] custom_word_model['display_as'] = 'testString' @@ -2231,6 +2241,7 @@ def test_add_words_value_error(self): # Construct a dict representation of a CustomWord model custom_word_model = {} custom_word_model['word'] = 'testString' + custom_word_model['mapping_only'] = ['testString'] custom_word_model['sounds_like'] = ['testString'] custom_word_model['display_as'] = 'testString' @@ -2280,6 +2291,7 @@ def test_add_word_all_params(self): customization_id = 'testString' word_name = 'testString' word = 'testString' + mapping_only = ['testString'] sounds_like = ['testString'] display_as = 'testString' @@ -2288,6 +2300,7 @@ def test_add_word_all_params(self): customization_id, word_name, word=word, + mapping_only=mapping_only, sounds_like=sounds_like, display_as=display_as, headers={}, @@ -2299,6 +2312,7 @@ def test_add_word_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['word'] == 'testString' + assert req_body['mapping_only'] == ['testString'] assert req_body['sounds_like'] == ['testString'] assert req_body['display_as'] == 'testString' @@ -2328,6 +2342,7 @@ def test_add_word_value_error(self): customization_id = 'testString' word_name = 'testString' word = 'testString' + mapping_only = ['testString'] sounds_like = ['testString'] display_as = 'testString' @@ -2363,7 +2378,7 @@ def test_get_word_all_params(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' + mock_response = '{"word": "word", "mapping_only": ["mapping_only"], "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' responses.add( responses.GET, url, @@ -2403,7 +2418,7 @@ def test_get_word_value_error(self): """ # Set up mock url = preprocess_url('/v1/customizations/testString/words/testString') - mock_response = '{"word": "word", "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' + mock_response = '{"word": "word", "mapping_only": ["mapping_only"], "sounds_like": ["sounds_like"], "display_as": "display_as", "count": 5, "source": ["source"], "error": [{"element": "element"}]}' responses.add( responses.GET, url, @@ -4528,6 +4543,7 @@ def test_custom_word_serialization(self): # Construct a json representation of a CustomWord model custom_word_model_json = {} custom_word_model_json['word'] = 'testString' + custom_word_model_json['mapping_only'] = ['testString'] custom_word_model_json['sounds_like'] = ['testString'] custom_word_model_json['display_as'] = 'testString' @@ -5509,6 +5525,7 @@ def test_word_serialization(self): # Construct a json representation of a Word model word_model_json = {} word_model_json['word'] = 'testString' + word_model_json['mapping_only'] = ['testString'] word_model_json['sounds_like'] = ['testString'] word_model_json['display_as'] = 'testString' word_model_json['count'] = 38 @@ -5647,6 +5664,7 @@ def test_words_serialization(self): word_model = {} # Word word_model['word'] = 'testString' + word_model['mapping_only'] = ['testString'] word_model['sounds_like'] = ['testString'] word_model['display_as'] = 'testString' word_model['count'] = 38 From 052384fcb0e273a94919455143f4b60043e06698 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 22 Feb 2024 16:37:50 -0600 Subject: [PATCH 412/455] chore(lt): formatting --- ibm_watson/language_translator_v3.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 1fd5a426c..ea5be9f68 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -74,15 +74,13 @@ def __init__( """ if version is None: raise ValueError('version must be provided') - - print( - """ + + print(""" On 10 June 2023, IBM announced the deprecation of the Natural Language Translator service. The service will no longer be available from 8 August 2022. As of 10 June 2024, the service will reach its End of Support date. As of 10 December 2024, the service will be withdrawn entirely and will no longer be available to any customers. - """ - ) + """) if not authenticator: authenticator = get_authenticator_from_environment(service_name) From 6cd5ebae52f93ab64f89bb1dea52b3ef4b27f444 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 22 Feb 2024 16:47:09 -0600 Subject: [PATCH 413/455] feat(wa-v2): support for private variables BREAKING CHANGE: Name changes for multiple classes --- ibm_watson/assistant_v2.py | 7644 ++++++++++++++++++-------------- test/unit/test_assistant_v2.py | 4057 ++++++++++------- 2 files changed, 6551 insertions(+), 5150 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index bcb616c0a..764f567fa 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -530,8 +530,8 @@ def message_stateless( self, assistant_id: str, *, - input: Optional['MessageInputStateless'] = None, - context: Optional['MessageContextStateless'] = None, + input: Optional['StatelessMessageInput'] = None, + context: Optional['StatelessMessageContext'] = None, user_id: Optional[str] = None, **kwargs, ) -> DetailedResponse: @@ -4233,9 +4233,9 @@ class Log: Log. :param str log_id: A unique identifier for the logged event. - :param MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :param MessageResponse response: A response from the Watson Assistant service. + :param LogRequest request: A message request formatted for the watsonx Assistant + service. + :param LogResponse response: A response from the watsonx Assistant service. :param str assistant_id: Unique identifier of the assistant. :param str session_id: The ID of the session the message was part of. :param str skill_id: The unique identifier of the skill that responded to the @@ -4254,8 +4254,8 @@ class Log: def __init__( self, log_id: str, - request: 'MessageRequest', - response: 'MessageResponse', + request: 'LogRequest', + response: 'LogResponse', assistant_id: str, session_id: str, skill_id: str, @@ -4270,10 +4270,9 @@ def __init__( Initialize a Log object. :param str log_id: A unique identifier for the logged event. - :param MessageRequest request: A stateful message request formatted for the - Watson Assistant service. - :param MessageResponse response: A response from the Watson Assistant - service. + :param LogRequest request: A message request formatted for the watsonx + Assistant service. + :param LogResponse response: A response from the watsonx Assistant service. :param str assistant_id: Unique identifier of the assistant. :param str session_id: The ID of the session the message was part of. :param str skill_id: The unique identifier of the skill that responded to @@ -4310,12 +4309,12 @@ def from_dict(cls, _dict: Dict) -> 'Log': raise ValueError( 'Required property \'log_id\' not present in Log JSON') if (request := _dict.get('request')) is not None: - args['request'] = MessageRequest.from_dict(request) + args['request'] = LogRequest.from_dict(request) else: raise ValueError( 'Required property \'request\' not present in Log JSON') if (response := _dict.get('response')) is not None: - args['response'] = MessageResponse.from_dict(response) + args['response'] = LogResponse.from_dict(response) else: raise ValueError( 'Required property \'response\' not present in Log JSON') @@ -4640,73 +4639,95 @@ def __ne__(self, other: 'LogPagination') -> bool: return not self == other -class MessageContext: +class LogRequest: """ - MessageContext. + A message request formatted for the watsonx Assistant service. - :param MessageContextGlobal global_: (optional) Session context data that is - shared by all skills used by the assistant. - :param MessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param LogRequestInput input: (optional) An input object that includes the input + text. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to set or modify context variables, which can also be + accessed by dialog nodes. The context is stored by the assistant on a + per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. If **user_id** is specified in both locations, the value + specified at the root is used. """ def __init__( self, *, - global_: Optional['MessageContextGlobal'] = None, - skills: Optional['MessageContextSkills'] = None, - integrations: Optional[dict] = None, + input: Optional['LogRequestInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, ) -> None: """ - Initialize a MessageContext object. + Initialize a LogRequest object. - :param MessageContextGlobal global_: (optional) Session context data that - is shared by all skills used by the assistant. - :param MessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that - is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param LogRequestInput input: (optional) An input object that includes the + input text. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.input = input + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContext': - """Initialize a MessageContext object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogRequest': + """Initialize a LogRequest object from a json dictionary.""" args = {} - if (global_ := _dict.get('global')) is not None: - args['global_'] = MessageContextGlobal.from_dict(global_) - if (skills := _dict.get('skills')) is not None: - args['skills'] = MessageContextSkills.from_dict(skills) - if (integrations := _dict.get('integrations')) is not None: - args['integrations'] = integrations + if (input := _dict.get('input')) is not None: + args['input'] = LogRequestInput.from_dict(input) + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContext object from a json dictionary.""" + """Initialize a LogRequest 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, 'global_') and self.global_ is not None: - if isinstance(self.global_, dict): - _dict['global'] = self.global_ + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input else: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - if isinstance(self.skills, dict): - _dict['skills'] = self.skills + _dict['input'] = self.input.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context else: - _dict['skills'] = self.skills.to_dict() - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -4714,70 +4735,175 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContext object.""" + """Return a `str` version of this LogRequest object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContext') -> bool: + def __eq__(self, other: 'LogRequest') -> 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: 'MessageContext') -> bool: + def __ne__(self, other: 'LogRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobal: +class LogRequestInput: """ - Session context data that is shared by all skills used by the assistant. + An input object that includes the input text. All private data is masked or removed. - :param MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :param str session_id: (optional) The session ID. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param MessageInputOptions options: (optional) Optional properties that control + how the assistant responds. """ def __init__( self, *, - system: Optional['MessageContextGlobalSystem'] = None, - session_id: Optional[str] = None, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['MessageInputOptions'] = None, ) -> None: """ - Initialize a MessageContextGlobal object. + Initialize a LogRequestInput object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param MessageInputOptions options: (optional) Optional properties that + control how the assistant responds. """ - self.system = system - self.session_id = session_id + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': - """Initialize a MessageContextGlobal object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogRequestInput': + """Initialize a LogRequestInput object from a json dictionary.""" args = {} - if (system := _dict.get('system')) is not None: - args['system'] = MessageContextGlobalSystem.from_dict(system) - if (session_id := _dict.get('session_id')) is not None: - args['session_id'] = session_id + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments + ] + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = MessageInputOptions.from_dict(options) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobal object from a json dictionary.""" + """Initialize a LogRequestInput 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, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics else: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and getattr(self, - 'session_id') is not None: - _dict['session_id'] = getattr(self, 'session_id') + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -4785,70 +4911,126 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobal object.""" + """Return a `str` version of this LogRequestInput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobal') -> bool: + def __eq__(self, other: 'LogRequestInput') -> 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: 'MessageContextGlobal') -> bool: + def __ne__(self, other: 'LogRequestInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - -class MessageContextGlobalStateless: - """ - Session context data that is shared by all skills used by the assistant. - - :param MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :param str session_id: (optional) The session ID. + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + + TEXT = 'text' + SEARCH = 'search' + + +class LogResponse: + """ + A response from the watsonx Assistant service. + + :param LogResponseOutput output: Assistant output to be rendered or processed by + the client. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ def __init__( self, + output: 'LogResponseOutput', + user_id: str, *, - system: Optional['MessageContextGlobalSystem'] = None, - session_id: Optional[str] = None, + context: Optional['MessageContext'] = None, ) -> None: """ - Initialize a MessageContextGlobalStateless object. + Initialize a LogResponse object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param LogResponseOutput output: Assistant output to be rendered or + processed by the client. All private data is masked or removed. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. """ - self.system = system - self.session_id = session_id + self.output = output + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalStateless': - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogResponse': + """Initialize a LogResponse object from a json dictionary.""" args = {} - if (system := _dict.get('system')) is not None: - args['system'] = MessageContextGlobalSystem.from_dict(system) - if (session_id := _dict.get('session_id')) is not None: - args['session_id'] = session_id + if (output := _dict.get('output')) is not None: + args['output'] = LogResponseOutput.from_dict(output) + else: + raise ValueError( + 'Required property \'output\' not present in LogResponse JSON') + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + else: + raise ValueError( + 'Required property \'user_id\' not present in LogResponse JSON') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalStateless object from a json dictionary.""" + """Initialize a LogResponse 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, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output else: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -4856,196 +5038,157 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalStateless object.""" + """Return a `str` version of this LogResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalStateless') -> bool: + def __eq__(self, other: 'LogResponse') -> 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: 'MessageContextGlobalStateless') -> bool: + def __ne__(self, other: 'LogResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobalSystem: +class LogResponseOutput: """ - Built-in system properties that apply to all skills used by the assistant. + Assistant output to be rendered or processed by the client. All private data is masked + or removed. - :param str timezone: (optional) The user time zone. The assistant uses the time - zone to correctly resolve relative time references. - :param str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root of - the message body. If **user_id** is specified in both locations in a message - request, the value specified at the root is used. - :param int turn_count: (optional) A counter that is automatically incremented - 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). - :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for the - skill. - :param str session_start_time: (optional) The time at which the session started. - With the stateful `message` method, the start time is always present, and is set - by the service based on the time the session was created. With the stateless - `message` method, the start time is set by the service in the response to the - first message, and should be returned as part of the context with each - subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for example, - `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :param str state: (optional) An encoded string that represents the configuration - state of the assistant at the beginning of the conversation. If you are using - the stateless `message` method, save this value and then send it in the context - of the subsequent message request to avoid disruptions if there are - configuration changes during the conversation (such as a change to a skill the - assistant uses). - :param bool skip_user_input: (optional) For internal use only. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ def __init__( self, *, - timezone: Optional[str] = None, - user_id: Optional[str] = None, - turn_count: Optional[int] = None, - locale: Optional[str] = None, - reference_time: Optional[str] = None, - session_start_time: Optional[str] = None, - state: Optional[str] = None, - skip_user_input: Optional[bool] = None, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, ) -> None: """ - Initialize a MessageContextGlobalSystem object. + Initialize a LogResponseOutput object. - :param str timezone: (optional) The user time zone. The assistant uses the - time zone to correctly resolve relative time references. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root - of the message body. If **user_id** is specified in both locations in a - message request, the value specified at the root is used. - :param int turn_count: (optional) A counter that is automatically - incremented 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). - :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for - the skill. - :param str session_start_time: (optional) The time at which the session - started. With the stateful `message` method, the start time is always - present, and is set by the service based on the time the session was - created. With the stateless `message` method, the start time is set by the - service in the response to the first message, and should be returned as - part of the context with each subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :param str state: (optional) An encoded string that represents the - configuration state of the assistant at the beginning of the conversation. - If you are using the stateless `message` method, save this value and then - send it in the context of the subsequent message request to avoid - disruptions if there are configuration changes during the conversation - (such as a change to a skill the assistant uses). - :param bool skip_user_input: (optional) For internal use only. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ - self.timezone = timezone - self.user_id = user_id - self.turn_count = turn_count - self.locale = locale - self.reference_time = reference_time - self.session_start_time = session_start_time - self.state = state - self.skip_user_input = skip_user_input + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogResponseOutput': + """Initialize a LogResponseOutput object from a json dictionary.""" args = {} - if (timezone := _dict.get('timezone')) is not None: - args['timezone'] = timezone - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id - if (turn_count := _dict.get('turn_count')) is not None: - args['turn_count'] = turn_count - if (locale := _dict.get('locale')) is not None: - args['locale'] = locale - if (reference_time := _dict.get('reference_time')) is not None: - args['reference_time'] = reference_time - if (session_start_time := _dict.get('session_start_time')) is not None: - args['session_start_time'] = session_start_time - if (state := _dict.get('state')) is not None: - args['state'] = state - if (skip_user_input := _dict.get('skip_user_input')) is not None: - args['skip_user_input'] = skip_user_input + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + """Initialize a LogResponseOutput 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, 'timezone') and self.timezone is not None: - _dict['timezone'] = self.timezone - if hasattr(self, 'user_id') and self.user_id is not None: - _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 - if hasattr( - self, - 'session_start_time') and self.session_start_time is not None: - _dict['session_start_time'] = self.session_start_time - if hasattr(self, 'state') and self.state is not None: - _dict['state'] = self.state - if hasattr(self, - 'skip_user_input') and self.skip_user_input is not None: - _dict['skip_user_input'] = self.skip_user_input + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() return _dict def _to_dict(self): @@ -5053,49 +5196,112 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalSystem object.""" + """Return a `str` version of this LogResponseOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalSystem') -> bool: + def __eq__(self, other: 'LogResponseOutput') -> 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: 'MessageContextGlobalSystem') -> bool: + def __ne__(self, other: 'LogResponseOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LocaleEnum(str, Enum): + +class MessageContext: + """ + MessageContext. + + :param MessageContextGlobal global_: (optional) Session context data that is + shared by all skills used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + """ + + def __init__( + self, + *, + global_: Optional['MessageContextGlobal'] = None, + skills: Optional['MessageContextSkills'] = None, + integrations: Optional[dict] = None, + ) -> None: """ - 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. + Initialize a MessageContext object. + + :param MessageContextGlobal global_: (optional) Session context data that + is shared by all skills used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ + self.global_ = global_ + self.skills = skills + self.integrations = integrations - 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' + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContext': + """Initialize a MessageContext object from a json dictionary.""" + args = {} + if (global_ := _dict.get('global')) is not None: + args['global_'] = MessageContextGlobal.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = MessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContext 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, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations + 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 MessageContext object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContext') -> 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: 'MessageContext') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other -class MessageContextSkillAction: +class MessageContextActionSkill: """ - Context variables that are used by the action skill. + Context variables that are used by the action skill. Private variables are persisted, + but not shown. :param dict user_defined: (optional) An object containing any arbitrary variables that can be read and written by a particular skill. @@ -5105,7 +5311,7 @@ class MessageContextSkillAction: Action variables can be accessed only by steps in the same action, and do not persist after the action ends. :param dict skill_variables: (optional) An object containing skill variables. - (In the Watson Assistant user interface, skill variables are called _session + (In the watsonx Assistant user interface, skill variables are called _session variables_.) Skill variables can be accessed by any action and persist for the duration of the session. """ @@ -5119,7 +5325,7 @@ def __init__( skill_variables: Optional[dict] = None, ) -> None: """ - Initialize a MessageContextSkillAction object. + Initialize a MessageContextActionSkill object. :param dict user_defined: (optional) An object containing any arbitrary variables that can be read and written by a particular skill. @@ -5129,7 +5335,7 @@ def __init__( variables. Action variables can be accessed only by steps in the same action, and do not persist after the action ends. :param dict skill_variables: (optional) An object containing skill - variables. (In the Watson Assistant user interface, skill variables are + variables. (In the watsonx Assistant user interface, skill variables are called _session variables_.) Skill variables can be accessed by any action and persist for the duration of the session. """ @@ -5139,8 +5345,8 @@ def __init__( self.skill_variables = skill_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillAction': - """Initialize a MessageContextSkillAction object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextActionSkill': + """Initialize a MessageContextActionSkill object from a json dictionary.""" args = {} if (user_defined := _dict.get('user_defined')) is not None: args['user_defined'] = user_defined @@ -5154,7 +5360,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextSkillAction': @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkillAction object from a json dictionary.""" + """Initialize a MessageContextActionSkill object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -5180,21 +5386,21 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillAction object.""" + """Return a `str` version of this MessageContextActionSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkillAction') -> bool: + def __eq__(self, other: 'MessageContextActionSkill') -> 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: 'MessageContextSkillAction') -> bool: + def __ne__(self, other: 'MessageContextActionSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextSkillDialog: +class MessageContextDialogSkill: """ Context variables that are used by the dialog skill. @@ -5211,7 +5417,7 @@ def __init__( system: Optional['MessageContextSkillSystem'] = None, ) -> None: """ - Initialize a MessageContextSkillDialog object. + Initialize a MessageContextDialogSkill object. :param dict user_defined: (optional) An object containing any arbitrary variables that can be read and written by a particular skill. @@ -5222,8 +5428,8 @@ def __init__( self.system = system @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillDialog': - """Initialize a MessageContextSkillDialog object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextDialogSkill': + """Initialize a MessageContextDialogSkill object from a json dictionary.""" args = {} if (user_defined := _dict.get('user_defined')) is not None: args['user_defined'] = user_defined @@ -5233,7 +5439,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextSkillDialog': @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkillDialog object from a json dictionary.""" + """Initialize a MessageContextDialogSkill object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -5253,179 +5459,267 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillDialog object.""" + """Return a `str` version of this MessageContextDialogSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkillDialog') -> bool: + def __eq__(self, other: 'MessageContextDialogSkill') -> 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: 'MessageContextSkillDialog') -> bool: + def __ne__(self, other: 'MessageContextDialogSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextSkillSystem: +class MessageContextGlobal: """ - System context data used by the skill. + Session context data that is shared by all skills used by the assistant. - :param str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context of a - subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. + :param MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :param str session_id: (optional) The session ID. """ - # The set of defined properties for the class - _properties = frozenset(['state']) - def __init__( self, *, - state: Optional[str] = None, - **kwargs, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, ) -> None: """ - Initialize a MessageContextSkillSystem object. + Initialize a MessageContextGlobal object. - :param str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context - of a subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. - :param **kwargs: (optional) Any additional properties. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. """ - self.state = state - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': + """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} - if (state := _dict.get('state')) is not None: - args['state'] = state - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + """Initialize a MessageContextGlobal 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, 'state') and self.state is not None: - _dict['state'] = self.state - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and getattr(self, + 'session_id') is not None: + _dict['session_id'] = getattr(self, 'session_id') return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in MessageContextSkillSystem._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillSystem object.""" + """Return a `str` version of this MessageContextGlobal object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkillSystem') -> bool: + def __eq__(self, other: 'MessageContextGlobal') -> 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: 'MessageContextSkillSystem') -> bool: + def __ne__(self, other: 'MessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextSkills: +class MessageContextGlobalSystem: """ - Context data specific to particular skills used by the assistant. + Built-in system properties that apply to all skills used by the assistant. - :param MessageContextSkillDialog main_skill: (optional) Context variables that - are used by the dialog skill. - :param MessageContextSkillAction actions_skill: (optional) Context variables - that are used by the action skill. + :param str timezone: (optional) The user time zone. The assistant uses the time + zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root of + the message body. If **user_id** is specified in both locations in a message + request, the value specified at the root is used. + :param int turn_count: (optional) A counter that is automatically incremented + 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). + :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for the + skill. + :param str session_start_time: (optional) The time at which the session started. + With the stateful `message` method, the start time is always present, and is set + by the service based on the time the session was created. With the stateless + `message` method, the start time is set by the service in the response to the + first message, and should be returned as part of the context with each + subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for example, + `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the configuration + state of the assistant at the beginning of the conversation. If you are using + the stateless `message` method, save this value and then send it in the context + of the subsequent message request to avoid disruptions if there are + configuration changes during the conversation (such as a change to a skill the + assistant uses). + :param bool skip_user_input: (optional) For internal use only. """ def __init__( self, *, - main_skill: Optional['MessageContextSkillDialog'] = None, - actions_skill: Optional['MessageContextSkillAction'] = None, + timezone: Optional[str] = None, + user_id: Optional[str] = None, + turn_count: Optional[int] = None, + locale: Optional[str] = None, + reference_time: Optional[str] = None, + session_start_time: Optional[str] = None, + state: Optional[str] = None, + skip_user_input: Optional[bool] = None, ) -> None: """ - Initialize a MessageContextSkills object. + Initialize a MessageContextGlobalSystem object. - :param MessageContextSkillDialog main_skill: (optional) Context variables - that are used by the dialog skill. - :param MessageContextSkillAction actions_skill: (optional) Context - variables that are used by the action skill. + :param str timezone: (optional) The user time zone. The assistant uses the + time zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root + of the message body. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. + :param int turn_count: (optional) A counter that is automatically + incremented 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). + :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for + the skill. + :param str session_start_time: (optional) The time at which the session + started. With the stateful `message` method, the start time is always + present, and is set by the service based on the time the session was + created. With the stateless `message` method, the start time is set by the + service in the response to the first message, and should be returned as + part of the context with each subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the + configuration state of the assistant at the beginning of the conversation. + If you are using the stateless `message` method, save this value and then + send it in the context of the subsequent message request to avoid + disruptions if there are configuration changes during the conversation + (such as a change to a skill the assistant uses). + :param bool skip_user_input: (optional) For internal use only. """ - self.main_skill = main_skill - self.actions_skill = actions_skill + self.timezone = timezone + self.user_id = user_id + self.turn_count = turn_count + self.locale = locale + self.reference_time = reference_time + self.session_start_time = session_start_time + self.state = state + self.skip_user_input = skip_user_input @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': - """Initialize a MessageContextSkills object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': + """Initialize a MessageContextGlobalSystem object from a json dictionary.""" args = {} - if (main_skill := _dict.get('main skill')) is not None: - args['main_skill'] = MessageContextSkillDialog.from_dict(main_skill) - if (actions_skill := _dict.get('actions skill')) is not None: - args['actions_skill'] = MessageContextSkillAction.from_dict( - actions_skill) + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + if (turn_count := _dict.get('turn_count')) is not None: + args['turn_count'] = turn_count + if (locale := _dict.get('locale')) is not None: + args['locale'] = locale + if (reference_time := _dict.get('reference_time')) is not None: + args['reference_time'] = reference_time + if (session_start_time := _dict.get('session_start_time')) is not None: + args['session_start_time'] = session_start_time + if (state := _dict.get('state')) is not None: + args['state'] = state + if (skip_user_input := _dict.get('skip_user_input')) is not None: + args['skip_user_input'] = skip_user_input return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkills object from a json dictionary.""" + """Initialize a MessageContextGlobalSystem 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, 'main_skill') and self.main_skill is not None: - if isinstance(self.main_skill, dict): - _dict['main skill'] = self.main_skill - else: - _dict['main skill'] = self.main_skill.to_dict() - if hasattr(self, 'actions_skill') and self.actions_skill is not None: - if isinstance(self.actions_skill, dict): - _dict['actions skill'] = self.actions_skill - else: - _dict['actions skill'] = self.actions_skill.to_dict() + if hasattr(self, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + if hasattr(self, 'user_id') and self.user_id is not None: + _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 + if hasattr( + self, + 'session_start_time') and self.session_start_time is not None: + _dict['session_start_time'] = self.session_start_time + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state + if hasattr(self, + 'skip_user_input') and self.skip_user_input is not None: + _dict['skip_user_input'] = self.skip_user_input return _dict def _to_dict(self): @@ -5433,87 +5727,207 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextSkills object.""" + """Return a `str` version of this MessageContextGlobalSystem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkills') -> bool: + def __eq__(self, other: 'MessageContextGlobalSystem') -> 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: 'MessageContextSkills') -> bool: + def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LocaleEnum(str, 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 MessageContextStateless: - """ - MessageContextStateless. - :param MessageContextGlobalStateless global_: (optional) Session context data - that is shared by all skills used by the assistant. - :param MessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). +class MessageContextSkillSystem: """ + System context data used by the skill. + + :param str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context of a + subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + """ + + # The set of defined properties for the class + _properties = frozenset(['state']) def __init__( self, *, - global_: Optional['MessageContextGlobalStateless'] = None, - skills: Optional['MessageContextSkills'] = None, - integrations: Optional[dict] = None, + state: Optional[str] = None, + **kwargs, ) -> None: """ - Initialize a MessageContextStateless object. + Initialize a MessageContextSkillSystem object. - :param MessageContextGlobalStateless global_: (optional) Session context - data that is shared by all skills used by the assistant. - :param MessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that - is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context + of a subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + :param **kwargs: (optional) Any additional properties. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.state = state + for _key, _value in kwargs.items(): + setattr(self, _key, _value) @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': - """Initialize a MessageContextStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': + """Initialize a MessageContextSkillSystem object from a json dictionary.""" args = {} - if (global_ := _dict.get('global')) is not None: - args['global_'] = MessageContextGlobalStateless.from_dict(global_) - if (skills := _dict.get('skills')) is not None: - args['skills'] = MessageContextSkills.from_dict(skills) - if (integrations := _dict.get('integrations')) is not None: - args['integrations'] = integrations + if (state := _dict.get('state')) is not None: + args['state'] = state + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextStateless object from a json dictionary.""" + """Initialize a MessageContextSkillSystem 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, 'global_') and self.global_ is not None: - if isinstance(self.global_, dict): - _dict['global'] = self.global_ + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in MessageContextSkillSystem._properties: + setattr(self, _key, _value) + + def __str__(self) -> str: + """Return a `str` version of this MessageContextSkillSystem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageContextSkillSystem') -> 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: 'MessageContextSkillSystem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class MessageContextSkills: + """ + Context data specific to particular skills used by the assistant. + + :param MessageContextDialogSkill main_skill: (optional) Context variables that + are used by the dialog skill. + :param MessageContextActionSkill actions_skill: (optional) Context variables + that are used by the action skill. Private variables are persisted, but not + shown. + """ + + def __init__( + self, + *, + main_skill: Optional['MessageContextDialogSkill'] = None, + actions_skill: Optional['MessageContextActionSkill'] = None, + ) -> None: + """ + Initialize a MessageContextSkills object. + + :param MessageContextDialogSkill main_skill: (optional) Context variables + that are used by the dialog skill. + :param MessageContextActionSkill actions_skill: (optional) Context + variables that are used by the action skill. Private variables are + persisted, but not shown. + """ + self.main_skill = main_skill + self.actions_skill = actions_skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': + """Initialize a MessageContextSkills object from a json dictionary.""" + args = {} + if (main_skill := _dict.get('main skill')) is not None: + args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) + if (actions_skill := _dict.get('actions skill')) is not None: + args['actions_skill'] = MessageContextActionSkill.from_dict( + actions_skill) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageContextSkills 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, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill else: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - if isinstance(self.skills, dict): - _dict['skills'] = self.skills + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill else: - _dict['skills'] = self.skills.to_dict() - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + _dict['actions skill'] = self.actions_skill.to_dict() return _dict def _to_dict(self): @@ -5521,16 +5935,16 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextStateless object.""" + """Return a `str` version of this MessageContextSkills object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextStateless') -> bool: + def __eq__(self, other: 'MessageContextSkills') -> 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: 'MessageContextStateless') -> bool: + def __ne__(self, other: 'MessageContextSkills') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -6039,85 +6453,142 @@ def __ne__(self, other: 'MessageInputOptionsSpelling') -> bool: return not self == other -class MessageInputOptionsStateless: +class MessageOutput: """ - Optional properties that control how the assistant responds. + Assistant output to be rendered or processed by the client. - :param bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ def __init__( self, *, - restart: Optional[bool] = None, - alternate_intents: Optional[bool] = None, - spelling: Optional['MessageInputOptionsSpelling'] = None, - debug: Optional[bool] = None, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, ) -> None: """ - Initialize a MessageInputOptionsStateless object. + Initialize a MessageOutput object. - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. """ - self.restart = restart - self.alternate_intents = alternate_intents - self.spelling = spelling + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions self.debug = debug + self.user_defined = user_defined + self.spelling = spelling @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsStateless': - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutput': + """Initialize a MessageOutput object from a json dictionary.""" args = {} - if (restart := _dict.get('restart')) is not None: - args['restart'] = restart - if (alternate_intents := _dict.get('alternate_intents')) is not None: - args['alternate_intents'] = alternate_intents - if (spelling := _dict.get('spelling')) is not None: - args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] if (debug := _dict.get('debug')) is not None: - args['debug'] = debug + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptionsStateless object from a json dictionary.""" + """Initialize a MessageOutput 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, 'restart') and self.restart is not None: - _dict['restart'] = self.restart - if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined if hasattr(self, 'spelling') and self.spelling is not None: if isinstance(self.spelling, dict): _dict['spelling'] = self.spelling else: _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug return _dict def _to_dict(self): @@ -6125,175 +6596,133 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptionsStateless object.""" + """Return a `str` version of this MessageOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptionsStateless') -> bool: + def __eq__(self, other: 'MessageOutput') -> 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: 'MessageInputOptionsStateless') -> bool: + def __ne__(self, other: 'MessageOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputStateless: +class MessageOutputDebug: """ - An input object that includes the input text. + Additional detailed information about a message response and how it was generated. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating - the user input. Include intents from the previous response to continue using - those intents rather than trying to recognize intents in the new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the Segment - extension. - :param MessageInputOptionsStateless options: (optional) Optional properties that - control how the assistant responds. + :param List[DialogNodeVisited] nodes_visited: (optional) An array of objects + containing detailed diagnostic information about dialog nodes that were visited + during processing of the input message. + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :param bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the dialog + completed by itself or got interrupted. + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of + objects containing detailed diagnostic information about dialog nodes and + actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. """ def __init__( self, *, - message_type: Optional[str] = None, - text: Optional[str] = None, - intents: Optional[List['RuntimeIntent']] = None, - entities: Optional[List['RuntimeEntity']] = None, - suggestion_id: Optional[str] = None, - attachments: Optional[List['MessageInputAttachment']] = None, - analytics: Optional['RequestAnalytics'] = None, - options: Optional['MessageInputOptionsStateless'] = None, + nodes_visited: Optional[List['DialogNodeVisited']] = None, + log_messages: Optional[List['DialogLogMessage']] = None, + branch_exited: Optional[bool] = None, + branch_exited_reason: Optional[str] = None, + turn_events: Optional[List['MessageOutputDebugTurnEvent']] = None, ) -> None: """ - Initialize a MessageInputStateless object. + Initialize a MessageOutputDebug object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the - Segment extension. - :param MessageInputOptionsStateless options: (optional) Optional properties - that control how the assistant responds. + :param List[DialogNodeVisited] nodes_visited: (optional) An array of + objects containing detailed diagnostic information about dialog nodes that + were visited during processing of the input message. + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :param bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the + dialog completed by itself or got interrupted. + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array + of objects containing detailed diagnostic information about dialog nodes + and actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.analytics = analytics - self.options = options + self.nodes_visited = nodes_visited + self.log_messages = log_messages + self.branch_exited = branch_exited + self.branch_exited_reason = branch_exited_reason + self.turn_events = turn_events @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': - """Initialize a MessageInputStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': + """Initialize a MessageOutputDebug object from a json dictionary.""" args = {} - if (message_type := _dict.get('message_type')) is not None: - args['message_type'] = message_type - if (text := _dict.get('text')) is not None: - args['text'] = text - if (intents := _dict.get('intents')) is not None: - args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] - if (entities := _dict.get('entities')) is not None: - args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] - if (suggestion_id := _dict.get('suggestion_id')) is not None: - args['suggestion_id'] = suggestion_id - if (attachments := _dict.get('attachments')) is not None: - args['attachments'] = [ - MessageInputAttachment.from_dict(v) for v in attachments + if (nodes_visited := _dict.get('nodes_visited')) is not None: + args['nodes_visited'] = [ + DialogNodeVisited.from_dict(v) for v in nodes_visited + ] + if (log_messages := _dict.get('log_messages')) is not None: + args['log_messages'] = [ + DialogLogMessage.from_dict(v) for v in log_messages + ] + if (branch_exited := _dict.get('branch_exited')) is not None: + args['branch_exited'] = branch_exited + if (branch_exited_reason := + _dict.get('branch_exited_reason')) is not None: + args['branch_exited_reason'] = branch_exited_reason + if (turn_events := _dict.get('turn_events')) is not None: + args['turn_events'] = [ + MessageOutputDebugTurnEvent.from_dict(v) for v in turn_events ] - if (analytics := _dict.get('analytics')) is not None: - args['analytics'] = RequestAnalytics.from_dict(analytics) - if (options := _dict.get('options')) is not None: - args['options'] = MessageInputOptionsStateless.from_dict(options) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputStateless object from a json dictionary.""" + """Initialize a MessageOutputDebug 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, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: + if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: + nodes_visited_list = [] + for v in self.nodes_visited: if isinstance(v, dict): - intents_list.append(v) + nodes_visited_list.append(v) else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: + nodes_visited_list.append(v.to_dict()) + _dict['nodes_visited'] = nodes_visited_list + if hasattr(self, 'log_messages') and self.log_messages is not None: + log_messages_list = [] + for v in self.log_messages: if isinstance(v, dict): - entities_list.append(v) + log_messages_list.append(v) else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - attachments_list = [] - for v in self.attachments: + log_messages_list.append(v.to_dict()) + _dict['log_messages'] = log_messages_list + if hasattr(self, 'branch_exited') and self.branch_exited is not None: + _dict['branch_exited'] = self.branch_exited + if hasattr(self, 'branch_exited_reason' + ) and self.branch_exited_reason is not None: + _dict['branch_exited_reason'] = self.branch_exited_reason + if hasattr(self, 'turn_events') and self.turn_events is not None: + turn_events_list = [] + for v in self.turn_events: if isinstance(v, dict): - attachments_list.append(v) + turn_events_list.append(v) else: - attachments_list.append(v.to_dict()) - _dict['attachments'] = attachments_list - if hasattr(self, 'analytics') and self.analytics is not None: - if isinstance(self.analytics, dict): - _dict['analytics'] = self.analytics - else: - _dict['analytics'] = self.analytics.to_dict() - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options - else: - _dict['options'] = self.options.to_dict() + turn_events_list.append(v.to_dict()) + _dict['turn_events'] = turn_events_list return _dict def _to_dict(self): @@ -6301,169 +6730,173 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputStateless object.""" + """Return a `str` version of this MessageOutputDebug object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputStateless') -> bool: + def __eq__(self, other: 'MessageOutputDebug') -> 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: 'MessageInputStateless') -> bool: + def __ne__(self, other: 'MessageOutputDebug') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): + class BranchExitedReasonEnum(str, Enum): """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. + When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` + specifies whether the dialog completed by itself or got interrupted. """ - TEXT = 'text' - SEARCH = 'search' + COMPLETED = 'completed' + FALLBACK = 'fallback' -class MessageOutput: +class MessageOutputDebugTurnEvent: """ - Assistant output to be rendered or processed by the client. + MessageOutputDebugTurnEvent. - :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any - channel. It is the responsibility of the client application to implement the - supported response types. - :param List[RuntimeIntent] intents: (optional) An array of intents recognized in - the user input, sorted in descending order of confidence. - :param List[RuntimeEntity] entities: (optional) An array of entities identified - in the user input. - :param List[DialogNodeAction] actions: (optional) An array of objects describing - any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information - about a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom properties - included in the response. This object includes any arbitrary properties defined - in the dialog JSON editor as part of the dialog node output. - :param MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + """ + + def __init__(self,) -> None: + """ + Initialize a MessageOutputDebugTurnEvent object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'action_visited'] = 'MessageOutputDebugTurnEventTurnEventActionVisited' + mapping[ + 'action_finished'] = 'MessageOutputDebugTurnEventTurnEventActionFinished' + mapping[ + 'step_visited'] = 'MessageOutputDebugTurnEventTurnEventStepVisited' + mapping[ + 'step_answered'] = 'MessageOutputDebugTurnEventTurnEventStepAnswered' + mapping[ + 'handler_visited'] = 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + mapping['callout'] = 'MessageOutputDebugTurnEventTurnEventCallout' + mapping['search'] = 'MessageOutputDebugTurnEventTurnEventSearch' + mapping[ + 'node_visited'] = 'MessageOutputDebugTurnEventTurnEventNodeVisited' + disc_value = _dict.get('event') + if disc_value is None: + raise ValueError( + 'Discriminator property \'event\' not found in MessageOutputDebugTurnEvent JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class MessageOutputSpelling: + """ + Properties describing any spelling corrections in the user input that was received. + + :param str text: (optional) The user input text that was used to generate the + response. If spelling autocorrection is enabled, this text reflects any spelling + corrections that were applied. + :param str original_text: (optional) The original user input text. This property + is returned only if autocorrection is enabled and the user input was corrected. + :param str suggested_text: (optional) Any suggested corrections of the input + text. This property is returned only if spelling correction is enabled and + autocorrection is disabled. """ def __init__( self, *, - generic: Optional[List['RuntimeResponseGeneric']] = None, - intents: Optional[List['RuntimeIntent']] = None, - entities: Optional[List['RuntimeEntity']] = None, - actions: Optional[List['DialogNodeAction']] = None, - debug: Optional['MessageOutputDebug'] = None, - user_defined: Optional[dict] = None, - spelling: Optional['MessageOutputSpelling'] = None, + text: Optional[str] = None, + original_text: Optional[str] = None, + suggested_text: Optional[str] = None, ) -> None: """ - Initialize a MessageOutput object. + Initialize a MessageOutputSpelling object. - :param List[RuntimeResponseGeneric] generic: (optional) Output intended for - any channel. It is the responsibility of the client application to - implement the supported response types. - :param List[RuntimeIntent] intents: (optional) An array of intents - recognized in the user input, sorted in descending order of confidence. - :param List[RuntimeEntity] entities: (optional) An array of entities - identified in the user input. - :param List[DialogNodeAction] actions: (optional) An array of objects - describing any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information - about a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom - properties included in the response. This object includes any arbitrary - properties defined in the dialog JSON editor as part of the dialog node - output. - :param MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + :param str text: (optional) The user input text that was used to generate + the response. If spelling autocorrection is enabled, this text reflects any + spelling corrections that were applied. + :param str original_text: (optional) The original user input text. This + property is returned only if autocorrection is enabled and the user input + was corrected. + :param str suggested_text: (optional) Any suggested corrections of the + input text. This property is returned only if spelling correction is + enabled and autocorrection is disabled. """ - self.generic = generic - self.intents = intents - self.entities = entities - self.actions = actions - self.debug = debug - self.user_defined = user_defined - self.spelling = spelling + self.text = text + self.original_text = original_text + self.suggested_text = suggested_text @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutput': - """Initialize a MessageOutput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': + """Initialize a MessageOutputSpelling object from a json dictionary.""" args = {} - if (generic := _dict.get('generic')) is not None: - args['generic'] = [ - RuntimeResponseGeneric.from_dict(v) for v in generic - ] - if (intents := _dict.get('intents')) is not None: - args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] - if (entities := _dict.get('entities')) is not None: - args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] - if (actions := _dict.get('actions')) is not None: - args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] - if (debug := _dict.get('debug')) is not None: - args['debug'] = MessageOutputDebug.from_dict(debug) - if (user_defined := _dict.get('user_defined')) is not None: - args['user_defined'] = user_defined - if (spelling := _dict.get('spelling')) is not None: - args['spelling'] = MessageOutputSpelling.from_dict(spelling) + if (text := _dict.get('text')) is not None: + args['text'] = text + if (original_text := _dict.get('original_text')) is not None: + args['original_text'] = original_text + if (suggested_text := _dict.get('suggested_text')) is not None: + args['suggested_text'] = suggested_text return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutput object from a json dictionary.""" + """Initialize a MessageOutputSpelling 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, 'generic') and self.generic is not None: - generic_list = [] - for v in self.generic: - if isinstance(v, dict): - generic_list.append(v) - else: - generic_list.append(v.to_dict()) - _dict['generic'] = generic_list - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'actions') and self.actions is not None: - actions_list = [] - for v in self.actions: - if isinstance(v, dict): - actions_list.append(v) - else: - actions_list.append(v.to_dict()) - _dict['actions'] = actions_list - if hasattr(self, 'debug') and self.debug is not None: - if isinstance(self.debug, dict): - _dict['debug'] = self.debug - else: - _dict['debug'] = self.debug.to_dict() - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'spelling') and self.spelling is not None: - if isinstance(self.spelling, dict): - _dict['spelling'] = self.spelling - else: - _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'original_text') and self.original_text is not None: + _dict['original_text'] = self.original_text + if hasattr(self, 'suggested_text') and self.suggested_text is not None: + _dict['suggested_text'] = self.suggested_text return _dict def _to_dict(self): @@ -6471,133 +6904,111 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutput object.""" + """Return a `str` version of this MessageOutputSpelling object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutput') -> bool: + def __eq__(self, other: 'MessageOutputSpelling') -> 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: 'MessageOutput') -> bool: + def __ne__(self, other: 'MessageOutputSpelling') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebug: +class Pagination: """ - Additional detailed information about a message response and how it was generated. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). - :param List[DialogNodeVisited] nodes_visited: (optional) An array of objects - containing detailed diagnostic information about dialog nodes that were visited - during processing of the input message. - :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :param bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :param str branch_exited_reason: (optional) When `branch_exited` is set to - `true` by the assistant, the `branch_exited_reason` specifies whether the dialog - completed by itself or got interrupted. - :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of - objects containing detailed diagnostic information about dialog nodes and - actions that were visited during processing of the input message. - This property is present only if the assistant has an action skill. + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the current + page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page of + results. + :param str next_cursor: (optional) A token identifying the next page of results. """ def __init__( self, + refresh_url: str, *, - nodes_visited: Optional[List['DialogNodeVisited']] = None, - log_messages: Optional[List['DialogLogMessage']] = None, - branch_exited: Optional[bool] = None, - branch_exited_reason: Optional[str] = None, - turn_events: Optional[List['MessageOutputDebugTurnEvent']] = None, + next_url: Optional[str] = None, + total: Optional[int] = None, + matched: Optional[int] = None, + refresh_cursor: Optional[str] = None, + next_cursor: Optional[str] = None, ) -> None: """ - Initialize a MessageOutputDebug object. + Initialize a Pagination object. - :param List[DialogNodeVisited] nodes_visited: (optional) An array of - objects containing detailed diagnostic information about dialog nodes that - were visited during processing of the input message. - :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :param bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :param str branch_exited_reason: (optional) When `branch_exited` is set to - `true` by the assistant, the `branch_exited_reason` specifies whether the - dialog completed by itself or got interrupted. - :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array - of objects containing detailed diagnostic information about dialog nodes - and actions that were visited during processing of the input message. - This property is present only if the assistant has an action skill. + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the + current page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page + of results. + :param str next_cursor: (optional) A token identifying the next page of + results. """ - self.nodes_visited = nodes_visited - self.log_messages = log_messages - self.branch_exited = branch_exited - self.branch_exited_reason = branch_exited_reason - self.turn_events = turn_events + self.refresh_url = refresh_url + self.next_url = next_url + self.total = total + self.matched = matched + self.refresh_cursor = refresh_cursor + self.next_cursor = next_cursor @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': - """Initialize a MessageOutputDebug object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Pagination': + """Initialize a Pagination object from a json dictionary.""" args = {} - if (nodes_visited := _dict.get('nodes_visited')) is not None: - args['nodes_visited'] = [ - DialogNodeVisited.from_dict(v) for v in nodes_visited - ] - if (log_messages := _dict.get('log_messages')) is not None: - args['log_messages'] = [ - DialogLogMessage.from_dict(v) for v in log_messages - ] - if (branch_exited := _dict.get('branch_exited')) is not None: - args['branch_exited'] = branch_exited - if (branch_exited_reason := - _dict.get('branch_exited_reason')) is not None: - args['branch_exited_reason'] = branch_exited_reason - if (turn_events := _dict.get('turn_events')) is not None: - args['turn_events'] = [ - MessageOutputDebugTurnEvent.from_dict(v) for v in turn_events - ] + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + else: + raise ValueError( + 'Required property \'refresh_url\' not present in Pagination JSON' + ) + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (total := _dict.get('total')) is not None: + args['total'] = total + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (refresh_cursor := _dict.get('refresh_cursor')) is not None: + args['refresh_cursor'] = refresh_cursor + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebug object from a json dictionary.""" + """Initialize a Pagination 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, 'nodes_visited') and self.nodes_visited is not None: - nodes_visited_list = [] - for v in self.nodes_visited: - if isinstance(v, dict): - nodes_visited_list.append(v) - else: - nodes_visited_list.append(v.to_dict()) - _dict['nodes_visited'] = nodes_visited_list - if hasattr(self, 'log_messages') and self.log_messages is not None: - log_messages_list = [] - for v in self.log_messages: - if isinstance(v, dict): - log_messages_list.append(v) - else: - log_messages_list.append(v.to_dict()) - _dict['log_messages'] = log_messages_list - if hasattr(self, 'branch_exited') and self.branch_exited is not None: - _dict['branch_exited'] = self.branch_exited - if hasattr(self, 'branch_exited_reason' - ) and self.branch_exited_reason is not None: - _dict['branch_exited_reason'] = self.branch_exited_reason - if hasattr(self, 'turn_events') and self.turn_events is not None: - turn_events_list = [] - for v in self.turn_events: - if isinstance(v, dict): - turn_events_list.append(v) - else: - turn_events_list.append(v.to_dict()) - _dict['turn_events'] = turn_events_list + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'total') and self.total is not None: + _dict['total'] = self.total + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: + _dict['refresh_cursor'] = self.refresh_cursor + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor return _dict def _to_dict(self): @@ -6605,173 +7016,120 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebug object.""" + """Return a `str` version of this Pagination object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputDebug') -> bool: + def __eq__(self, other: 'Pagination') -> 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: 'MessageOutputDebug') -> bool: + def __ne__(self, other: 'Pagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class BranchExitedReasonEnum(str, Enum): - """ - When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` - specifies whether the dialog completed by itself or got interrupted. - """ - - COMPLETED = 'completed' - FALLBACK = 'fallback' - -class MessageOutputDebugTurnEvent: +class Release: """ - MessageOutputDebugTurnEvent. + Release. + :param str release: (optional) The name of the release. The name is the version + number (an integer), returned as a string. + :param str description: (optional) The description of the release. + :param List[EnvironmentReference] environment_references: (optional) An array of + objects describing the environments where this release has been deployed. + :param ReleaseContent content: (optional) An object identifying the versionable + content objects (such as skill snapshots) that are included in the release. + :param str status: (optional) The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. """ - def __init__(self,) -> None: + def __init__( + self, + *, + release: Optional[str] = None, + description: Optional[str] = None, + environment_references: Optional[List['EnvironmentReference']] = None, + content: Optional['ReleaseContent'] = None, + status: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: """ - Initialize a MessageOutputDebugTurnEvent object. + Initialize a Release object. + :param str description: (optional) The description of the release. """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'MessageOutputDebugTurnEventTurnEventActionVisited', - 'MessageOutputDebugTurnEventTurnEventActionFinished', - 'MessageOutputDebugTurnEventTurnEventStepVisited', - 'MessageOutputDebugTurnEventTurnEventStepAnswered', - 'MessageOutputDebugTurnEventTurnEventHandlerVisited', - 'MessageOutputDebugTurnEventTurnEventCallout', - 'MessageOutputDebugTurnEventTurnEventSearch', - 'MessageOutputDebugTurnEventTurnEventNodeVisited' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': - """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. The discriminator value should map to a valid subclass: {1}".format( - ", ".join([ - 'MessageOutputDebugTurnEventTurnEventActionVisited', - 'MessageOutputDebugTurnEventTurnEventActionFinished', - 'MessageOutputDebugTurnEventTurnEventStepVisited', - 'MessageOutputDebugTurnEventTurnEventStepAnswered', - 'MessageOutputDebugTurnEventTurnEventHandlerVisited', - 'MessageOutputDebugTurnEventTurnEventCallout', - 'MessageOutputDebugTurnEventTurnEventSearch', - 'MessageOutputDebugTurnEventTurnEventNodeVisited' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" - return cls.from_dict(_dict) + self.release = release + self.description = description + self.environment_references = environment_references + self.content = content + self.status = status + self.created = created + self.updated = updated @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping[ - 'action_visited'] = 'MessageOutputDebugTurnEventTurnEventActionVisited' - mapping[ - 'action_finished'] = 'MessageOutputDebugTurnEventTurnEventActionFinished' - mapping[ - 'step_visited'] = 'MessageOutputDebugTurnEventTurnEventStepVisited' - mapping[ - 'step_answered'] = 'MessageOutputDebugTurnEventTurnEventStepAnswered' - mapping[ - 'handler_visited'] = 'MessageOutputDebugTurnEventTurnEventHandlerVisited' - mapping['callout'] = 'MessageOutputDebugTurnEventTurnEventCallout' - mapping['search'] = 'MessageOutputDebugTurnEventTurnEventSearch' - mapping[ - 'node_visited'] = 'MessageOutputDebugTurnEventTurnEventNodeVisited' - disc_value = _dict.get('event') - if disc_value is None: - raise ValueError( - 'Discriminator property \'event\' not found in MessageOutputDebugTurnEvent JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - - -class MessageOutputSpelling: - """ - Properties describing any spelling corrections in the user input that was received. - - :param str text: (optional) The user input text that was used to generate the - response. If spelling autocorrection is enabled, this text reflects any spelling - corrections that were applied. - :param str original_text: (optional) The original user input text. This property - is returned only if autocorrection is enabled and the user input was corrected. - :param str suggested_text: (optional) Any suggested corrections of the input - text. This property is returned only if spelling correction is enabled and - autocorrection is disabled. - """ - - def __init__( - self, - *, - text: Optional[str] = None, - original_text: Optional[str] = None, - suggested_text: Optional[str] = None, - ) -> None: - """ - Initialize a MessageOutputSpelling object. - - :param str text: (optional) The user input text that was used to generate - the response. If spelling autocorrection is enabled, this text reflects any - spelling corrections that were applied. - :param str original_text: (optional) The original user input text. This - property is returned only if autocorrection is enabled and the user input - was corrected. - :param str suggested_text: (optional) Any suggested corrections of the - input text. This property is returned only if spelling correction is - enabled and autocorrection is disabled. - """ - self.text = text - self.original_text = original_text - self.suggested_text = suggested_text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': - """Initialize a MessageOutputSpelling object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Release': + """Initialize a Release object from a json dictionary.""" args = {} - if (text := _dict.get('text')) is not None: - args['text'] = text - if (original_text := _dict.get('original_text')) is not None: - args['original_text'] = original_text - if (suggested_text := _dict.get('suggested_text')) is not None: - args['suggested_text'] = suggested_text + if (release := _dict.get('release')) is not None: + args['release'] = release + if (description := _dict.get('description')) is not None: + args['description'] = description + if (environment_references := + _dict.get('environment_references')) is not None: + args['environment_references'] = [ + EnvironmentReference.from_dict(v) + for v in environment_references + ] + if (content := _dict.get('content')) is not None: + args['content'] = ReleaseContent.from_dict(content) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputSpelling object from a json dictionary.""" + """Initialize a Release 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'original_text') and self.original_text is not None: - _dict['original_text'] = self.original_text - if hasattr(self, 'suggested_text') and self.suggested_text is not None: - _dict['suggested_text'] = self.suggested_text + if hasattr(self, 'release') and getattr(self, 'release') is not None: + _dict['release'] = getattr(self, 'release') + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'environment_references') and getattr( + self, 'environment_references') is not None: + environment_references_list = [] + for v in getattr(self, 'environment_references'): + if isinstance(v, dict): + environment_references_list.append(v) + else: + environment_references_list.append(v.to_dict()) + _dict['environment_references'] = environment_references_list + if hasattr(self, 'content') and getattr(self, 'content') is not None: + if isinstance(getattr(self, 'content'), dict): + _dict['content'] = getattr(self, 'content') + else: + _dict['content'] = getattr(self, 'content').to_dict() + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) return _dict def _to_dict(self): @@ -6779,109 +7137,97 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputSpelling object.""" + """Return a `str` version of this Release object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputSpelling') -> bool: + def __eq__(self, other: 'Release') -> 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: 'MessageOutputSpelling') -> bool: + def __ne__(self, other: 'Release') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + -class MessageRequest: +class ReleaseCollection: """ - A stateful message request formatted for the Watson Assistant service. + ReleaseCollection. - :param MessageInput input: (optional) An input object that includes the input - text. - :param MessageContext context: (optional) Context data for the conversation. You - can use this property to set or modify context variables, which can also be - accessed by dialog nodes. The context is stored by the assistant on a - per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :param str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. If **user_id** is specified in both locations, the value - specified at the root is used. + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__( self, - *, - input: Optional['MessageInput'] = None, - context: Optional['MessageContext'] = None, - user_id: Optional[str] = None, + releases: List['Release'], + pagination: 'Pagination', ) -> None: """ - Initialize a MessageRequest object. + Initialize a ReleaseCollection object. - :param MessageInput input: (optional) An input object that includes the - input text. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to set or modify context variables, - which can also be accessed by dialog nodes. The context is stored by the - assistant on a per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. If **user_id** is specified in both locations, the - value specified at the root is used. + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - self.input = input - self.context = context - self.user_id = user_id + self.releases = releases + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageRequest': - """Initialize a MessageRequest object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': + """Initialize a ReleaseCollection object from a json dictionary.""" args = {} - if (input := _dict.get('input')) is not None: - args['input'] = MessageInput.from_dict(input) - if (context := _dict.get('context')) is not None: - args['context'] = MessageContext.from_dict(context) - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id + if (releases := _dict.get('releases')) is not None: + args['releases'] = [Release.from_dict(v) for v in releases] + else: + raise ValueError( + 'Required property \'releases\' not present in ReleaseCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in ReleaseCollection JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageRequest object from a json dictionary.""" + """Initialize a ReleaseCollection 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, 'input') and self.input is not None: - if isinstance(self.input, dict): - _dict['input'] = self.input - else: - _dict['input'] = self.input.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context + if hasattr(self, 'releases') and self.releases is not None: + releases_list = [] + for v in self.releases: + if isinstance(v, dict): + releases_list.append(v) + else: + releases_list.append(v.to_dict()) + _dict['releases'] = releases_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6889,115 +7235,64 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageRequest object.""" + """Return a `str` version of this ReleaseCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageRequest') -> bool: + def __eq__(self, other: 'ReleaseCollection') -> 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: 'MessageRequest') -> bool: + def __ne__(self, other: 'ReleaseCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageResponse: +class ReleaseContent: """ - A response from the Watson Assistant service. + An object identifying the versionable content objects (such as skill snapshots) that + are included in the release. - :param MessageOutput output: Assistant output to be rendered or processed by the - client. - :param MessageContext context: (optional) Context data for the conversation. You - can use this property to access context variables. The context is stored by the - assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :param str user_id: A string value that identifies the user who is interacting - with the assistant. The client must provide a unique identifier for each - individual end user who accesses the application. For user-based plans, this - user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :param List[ReleaseSkill] skills: (optional) The skill snapshots that are + included in the release. """ def __init__( self, - output: 'MessageOutput', - user_id: str, *, - context: Optional['MessageContext'] = None, + skills: Optional[List['ReleaseSkill']] = None, ) -> None: """ - Initialize a MessageResponse object. + Initialize a ReleaseContent object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param str user_id: A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier - for each individual end user who accesses the application. For user-based - plans, this user ID is used to identify unique users for billing purposes. - This string cannot contain carriage return, newline, or tab characters. If - no value is specified in the input, **user_id** is automatically set to the - value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to access context variables. The - context is stored by the assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. """ - self.output = output - self.context = context - self.user_id = user_id + self.skills = skills @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponse': - """Initialize a MessageResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ReleaseContent': + """Initialize a ReleaseContent object from a json dictionary.""" args = {} - if (output := _dict.get('output')) is not None: - args['output'] = MessageOutput.from_dict(output) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponse JSON' - ) - if (context := _dict.get('context')) is not None: - args['context'] = MessageContext.from_dict(context) - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id - else: - raise ValueError( - 'Required property \'user_id\' not present in MessageResponse JSON' - ) + if (skills := _dict.get('skills')) is not None: + args['skills'] = [ReleaseSkill.from_dict(v) for v in skills] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageResponse object from a json dictionary.""" + """Initialize a ReleaseContent 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, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'skills') and getattr(self, 'skills') is not None: + skills_list = [] + for v in getattr(self, 'skills'): + if isinstance(v, dict): + skills_list.append(v) + else: + skills_list.append(v.to_dict()) + _dict['skills'] = skills_list return _dict def _to_dict(self): @@ -7005,111 +7300,79 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageResponse object.""" + """Return a `str` version of this ReleaseContent object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageResponse') -> bool: + def __eq__(self, other: 'ReleaseContent') -> 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: 'MessageResponse') -> bool: + def __ne__(self, other: 'ReleaseContent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageResponseStateless: +class ReleaseSkill: """ - A stateless response from the Watson Assistant service. + ReleaseSkill. - :param MessageOutput output: Assistant output to be rendered or processed by the - client. - :param MessageContextStateless context: Context data for the conversation. You - can use this property to access context variables. The context is not stored by - the assistant; to maintain session state, include the context from the response - in the next message. - :param str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is saved as + part of the release (for example, `draft` or `1`). """ def __init__( self, - output: 'MessageOutput', - context: 'MessageContextStateless', + skill_id: str, *, - user_id: Optional[str] = None, + type: Optional[str] = None, + snapshot: Optional[str] = None, ) -> None: """ - Initialize a MessageResponseStateless object. + Initialize a ReleaseSkill object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param MessageContextStateless context: Context data for the conversation. - You can use this property to access context variables. The context is not - stored by the assistant; to maintain session state, include the context - from the response in the next message. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is + saved as part of the release (for example, `draft` or `1`). """ - self.output = output - self.context = context - self.user_id = user_id + self.skill_id = skill_id + self.type = type + self.snapshot = snapshot @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageResponseStateless': - """Initialize a MessageResponseStateless object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': + """Initialize a ReleaseSkill object from a json dictionary.""" args = {} - if (output := _dict.get('output')) is not None: - args['output'] = MessageOutput.from_dict(output) - else: - raise ValueError( - 'Required property \'output\' not present in MessageResponseStateless JSON' - ) - if (context := _dict.get('context')) is not None: - args['context'] = MessageContextStateless.from_dict(context) + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id else: raise ValueError( - 'Required property \'context\' not present in MessageResponseStateless JSON' + 'Required property \'skill_id\' not present in ReleaseSkill JSON' ) - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id + if (type := _dict.get('type')) is not None: + args['type'] = type + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageResponseStateless object from a json dictionary.""" + """Initialize a ReleaseSkill 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, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot return _dict def _to_dict(self): @@ -7117,111 +7380,89 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageResponseStateless object.""" + """Return a `str` version of this ReleaseSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageResponseStateless') -> bool: + def __eq__(self, other: 'ReleaseSkill') -> 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: 'MessageResponseStateless') -> bool: + def __ne__(self, other: 'ReleaseSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of the skill. + """ -class Pagination: + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + + +class RequestAnalytics: """ - The pagination data for the returned objects. For more information about using - pagination, see [Pagination](#pagination). + An optional object containing analytics data. Currently, this data is used only for + events sent to the Segment extension. - :param str refresh_url: The URL that will return the same page of results. - :param str next_url: (optional) The URL that will return the next page of - results. - :param int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the current - page. - :param int matched: (optional) Reserved for future use. - :param str refresh_cursor: (optional) A token identifying the current page of - results. - :param str next_cursor: (optional) A token identifying the next page of results. + :param str browser: (optional) The browser that was used to send the message + that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to send + the message that triggered the event. """ def __init__( self, - refresh_url: str, *, - next_url: Optional[str] = None, - total: Optional[int] = None, - matched: Optional[int] = None, - refresh_cursor: Optional[str] = None, - next_cursor: Optional[str] = None, + browser: Optional[str] = None, + device: Optional[str] = None, + page_url: Optional[str] = None, ) -> None: """ - Initialize a Pagination object. + Initialize a RequestAnalytics object. - :param str refresh_url: The URL that will return the same page of results. - :param str next_url: (optional) The URL that will return the next page of - results. - :param int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the - current page. - :param int matched: (optional) Reserved for future use. - :param str refresh_cursor: (optional) A token identifying the current page - of results. - :param str next_cursor: (optional) A token identifying the next page of - results. + :param str browser: (optional) The browser that was used to send the + message that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to + send the message that triggered the event. """ - self.refresh_url = refresh_url - self.next_url = next_url - self.total = total - self.matched = matched - self.refresh_cursor = refresh_cursor - self.next_cursor = next_cursor + self.browser = browser + self.device = device + self.page_url = page_url @classmethod - def from_dict(cls, _dict: Dict) -> 'Pagination': - """Initialize a Pagination object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': + """Initialize a RequestAnalytics object from a json dictionary.""" args = {} - if (refresh_url := _dict.get('refresh_url')) is not None: - args['refresh_url'] = refresh_url - else: - raise ValueError( - 'Required property \'refresh_url\' not present in Pagination JSON' - ) - if (next_url := _dict.get('next_url')) is not None: - args['next_url'] = next_url - if (total := _dict.get('total')) is not None: - args['total'] = total - if (matched := _dict.get('matched')) is not None: - args['matched'] = matched - if (refresh_cursor := _dict.get('refresh_cursor')) is not None: - args['refresh_cursor'] = refresh_cursor - if (next_cursor := _dict.get('next_cursor')) is not None: - args['next_cursor'] = next_cursor + if (browser := _dict.get('browser')) is not None: + args['browser'] = browser + if (device := _dict.get('device')) is not None: + args['device'] = device + if (page_url := _dict.get('pageUrl')) is not None: + args['page_url'] = page_url return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Pagination object from a json dictionary.""" + """Initialize a RequestAnalytics 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, 'refresh_url') and self.refresh_url is not None: - _dict['refresh_url'] = self.refresh_url - if hasattr(self, 'next_url') and self.next_url is not None: - _dict['next_url'] = self.next_url - if hasattr(self, 'total') and self.total is not None: - _dict['total'] = self.total - if hasattr(self, 'matched') and self.matched is not None: - _dict['matched'] = self.matched - if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: - _dict['refresh_cursor'] = self.refresh_cursor - if hasattr(self, 'next_cursor') and self.next_cursor is not None: - _dict['next_cursor'] = self.next_cursor + if hasattr(self, 'browser') and self.browser is not None: + _dict['browser'] = self.browser + if hasattr(self, 'device') and self.device is not None: + _dict['device'] = self.device + if hasattr(self, 'page_url') and self.page_url is not None: + _dict['pageUrl'] = self.page_url return _dict def _to_dict(self): @@ -7229,120 +7470,58 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Pagination object.""" + """Return a `str` version of this RequestAnalytics object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Pagination') -> bool: + def __eq__(self, other: 'RequestAnalytics') -> 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: 'Pagination') -> bool: + def __ne__(self, other: 'RequestAnalytics') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Release: +class ResponseGenericChannel: """ - Release. + ResponseGenericChannel. - :param str release: (optional) The name of the release. The name is the version - number (an integer), returned as a string. - :param str description: (optional) The description of the release. - :param List[EnvironmentReference] environment_references: (optional) An array of - objects describing the environments where this release has been deployed. - :param ReleaseContent content: (optional) An object identifying the versionable - content objects (such as skill snapshots) that are included in the release. - :param str status: (optional) The current status of the release: - - **Available**: The release is available for deployment. - - **Failed**: An asynchronous publish operation has failed. - - **Processing**: An asynchronous publish operation has not yet completed. - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. + :param str channel: (optional) A channel for which the response is intended. """ def __init__( self, *, - release: Optional[str] = None, - description: Optional[str] = None, - environment_references: Optional[List['EnvironmentReference']] = None, - content: Optional['ReleaseContent'] = None, - status: Optional[str] = None, - created: Optional[datetime] = None, - updated: Optional[datetime] = None, + channel: Optional[str] = None, ) -> None: """ - Initialize a Release object. + Initialize a ResponseGenericChannel object. - :param str description: (optional) The description of the release. + :param str channel: (optional) A channel for which the response is + intended. """ - self.release = release - self.description = description - self.environment_references = environment_references - self.content = content - self.status = status - self.created = created - self.updated = updated + self.channel = channel @classmethod - def from_dict(cls, _dict: Dict) -> 'Release': - """Initialize a Release object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': + """Initialize a ResponseGenericChannel object from a json dictionary.""" args = {} - if (release := _dict.get('release')) is not None: - args['release'] = release - if (description := _dict.get('description')) is not None: - args['description'] = description - if (environment_references := - _dict.get('environment_references')) is not None: - args['environment_references'] = [ - EnvironmentReference.from_dict(v) - for v in environment_references - ] - if (content := _dict.get('content')) is not None: - args['content'] = ReleaseContent.from_dict(content) - if (status := _dict.get('status')) is not None: - args['status'] = status - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - if (updated := _dict.get('updated')) is not None: - args['updated'] = string_to_datetime(updated) + if (channel := _dict.get('channel')) is not None: + args['channel'] = channel return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Release object from a json dictionary.""" + """Initialize a ResponseGenericChannel 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, 'release') and getattr(self, 'release') is not None: - _dict['release'] = getattr(self, 'release') - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'environment_references') and getattr( - self, 'environment_references') is not None: - environment_references_list = [] - for v in getattr(self, 'environment_references'): - if isinstance(v, dict): - environment_references_list.append(v) - else: - environment_references_list.append(v.to_dict()) - _dict['environment_references'] = environment_references_list - if hasattr(self, 'content') and getattr(self, 'content') is not None: - if isinstance(getattr(self, 'content'), dict): - _dict['content'] = getattr(self, 'content') - else: - _dict['content'] = getattr(self, 'content').to_dict() - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + if hasattr(self, 'channel') and self.channel is not None: + _dict['channel'] = self.channel return _dict def _to_dict(self): @@ -7350,97 +7529,194 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Release object.""" + """Return a `str` version of this ResponseGenericChannel object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Release') -> bool: + def __eq__(self, other: 'ResponseGenericChannel') -> 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: 'Release') -> bool: + def __ne__(self, other: 'ResponseGenericChannel') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the release: - - **Available**: The release is available for deployment. - - **Failed**: An asynchronous publish operation has failed. - - **Processing**: An asynchronous publish operation has not yet completed. - """ - - AVAILABLE = 'Available' - FAILED = 'Failed' - PROCESSING = 'Processing' - -class ReleaseCollection: +class RuntimeEntity: """ - ReleaseCollection. + The entity value that was recognized in the user input. - :param List[Release] releases: An array of objects describing the releases - associated with an assistant. - :param Pagination pagination: The pagination data for the returned objects. For - more information about using pagination, see [Pagination](#pagination). + :param str entity: An entity detected in the input. + :param List[int] location: (optional) An array of zero-based character offsets + that indicate where the detected entity values begin and end in the input text. + :param str value: The term in the input text that was recognized as an entity + value. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized 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. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill (if + enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. """ def __init__( self, - releases: List['Release'], - pagination: 'Pagination', + entity: str, + value: str, + *, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + groups: Optional[List['CaptureGroup']] = None, + interpretation: Optional['RuntimeEntityInterpretation'] = None, + alternatives: Optional[List['RuntimeEntityAlternative']] = None, + role: Optional['RuntimeEntityRole'] = None, + skill: Optional[str] = None, ) -> None: """ - Initialize a ReleaseCollection object. + Initialize a RuntimeEntity object. - :param List[Release] releases: An array of objects describing the releases - associated with an assistant. - :param Pagination pagination: The pagination data for the returned objects. - For more information about using pagination, see [Pagination](#pagination). + :param str entity: An entity detected in the input. + :param str value: The term in the input text that was recognized as an + entity value. + :param List[int] location: (optional) An array of zero-based character + offsets that indicate where the detected entity values begin and end in the + input text. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized 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. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. """ - self.releases = releases - self.pagination = pagination + self.entity = entity + self.location = location + self.value = value + self.confidence = confidence + self.groups = groups + self.interpretation = interpretation + self.alternatives = alternatives + self.role = role + self.skill = skill @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': - """Initialize a ReleaseCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': + """Initialize a RuntimeEntity object from a json dictionary.""" args = {} - if (releases := _dict.get('releases')) is not None: - args['releases'] = [Release.from_dict(v) for v in releases] + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity else: raise ValueError( - 'Required property \'releases\' not present in ReleaseCollection JSON' + 'Required property \'entity\' not present in RuntimeEntity JSON' ) - if (pagination := _dict.get('pagination')) is not None: - args['pagination'] = Pagination.from_dict(pagination) + if (location := _dict.get('location')) is not None: + args['location'] = location + if (value := _dict.get('value')) is not None: + args['value'] = value else: raise ValueError( - 'Required property \'pagination\' not present in ReleaseCollection JSON' - ) - return cls(**args) - - @classmethod + 'Required property \'value\' not present in RuntimeEntity JSON') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (groups := _dict.get('groups')) is not None: + args['groups'] = [CaptureGroup.from_dict(v) for v in groups] + if (interpretation := _dict.get('interpretation')) is not None: + args['interpretation'] = RuntimeEntityInterpretation.from_dict( + interpretation) + if (alternatives := _dict.get('alternatives')) is not None: + args['alternatives'] = [ + RuntimeEntityAlternative.from_dict(v) for v in alternatives + ] + if (role := _dict.get('role')) is not None: + args['role'] = RuntimeEntityRole.from_dict(role) + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill + return cls(**args) + + @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseCollection object from a json dictionary.""" + """Initialize a RuntimeEntity 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, 'releases') and self.releases is not None: - releases_list = [] - for v in self.releases: + if hasattr(self, 'entity') and self.entity is not None: + _dict['entity'] = self.entity + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + 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 + if hasattr(self, 'groups') and self.groups is not None: + groups_list = [] + for v in self.groups: if isinstance(v, dict): - releases_list.append(v) + groups_list.append(v) else: - releases_list.append(v.to_dict()) - _dict['releases'] = releases_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination + groups_list.append(v.to_dict()) + _dict['groups'] = groups_list + if hasattr(self, 'interpretation') and self.interpretation is not None: + if isinstance(self.interpretation, dict): + _dict['interpretation'] = self.interpretation else: - _dict['pagination'] = self.pagination.to_dict() + _dict['interpretation'] = self.interpretation.to_dict() + if hasattr(self, 'alternatives') and self.alternatives is not None: + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list + if hasattr(self, 'role') and self.role is not None: + if isinstance(self.role, dict): + _dict['role'] = self.role + else: + _dict['role'] = self.role.to_dict() + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill return _dict def _to_dict(self): @@ -7448,64 +7724,69 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseCollection object.""" + """Return a `str` version of this RuntimeEntity object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseCollection') -> bool: + def __eq__(self, other: 'RuntimeEntity') -> 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: 'ReleaseCollection') -> bool: + def __ne__(self, other: 'RuntimeEntity') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ReleaseContent: +class RuntimeEntityAlternative: """ - An object identifying the versionable content objects (such as skill snapshots) that - are included in the release. + An alternative value for the recognized entity. - :param List[ReleaseSkill] skills: (optional) The skill snapshots that are - included in the release. + :param str value: (optional) The entity value that was recognized in the user + input. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized entity. """ def __init__( self, *, - skills: Optional[List['ReleaseSkill']] = None, + value: Optional[str] = None, + confidence: Optional[float] = None, ) -> None: """ - Initialize a ReleaseContent object. + 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 + confidence in the recognized entity. """ - self.skills = skills + self.value = value + self.confidence = confidence @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseContent': - """Initialize a ReleaseContent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': + """Initialize a RuntimeEntityAlternative object from a json dictionary.""" args = {} - if (skills := _dict.get('skills')) is not None: - args['skills'] = [ReleaseSkill.from_dict(v) for v in skills] + if (value := _dict.get('value')) is not None: + args['value'] = value + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseContent object from a json dictionary.""" + """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, 'skills') and getattr(self, 'skills') is not None: - skills_list = [] - for v in getattr(self, 'skills'): - if isinstance(v, dict): - skills_list.append(v) - else: - skills_list.append(v.to_dict()) - _dict['skills'] = skills_list + 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): @@ -7513,79 +7794,354 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseContent object.""" + """Return a `str` version of this RuntimeEntityAlternative object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseContent') -> bool: + 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: 'ReleaseContent') -> bool: + def __ne__(self, other: 'RuntimeEntityAlternative') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ReleaseSkill: +class RuntimeEntityInterpretation: """ - ReleaseSkill. + RuntimeEntityInterpretation. - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. - :param str snapshot: (optional) The name of the skill snapshot that is saved as - part of the release (for example, `draft` or `1`). + :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`). """ def __init__( self, - skill_id: str, *, - type: Optional[str] = None, - snapshot: Optional[str] = None, + calendar_type: Optional[str] = None, + datetime_link: Optional[str] = None, + festival: Optional[str] = None, + granularity: Optional[str] = None, + range_link: Optional[str] = None, + range_modifier: Optional[str] = None, + relative_day: Optional[float] = None, + relative_month: Optional[float] = None, + relative_week: Optional[float] = None, + relative_weekend: Optional[float] = None, + relative_year: Optional[float] = None, + specific_day: Optional[float] = None, + specific_day_of_week: Optional[str] = None, + specific_month: Optional[float] = None, + specific_quarter: Optional[float] = None, + specific_year: Optional[float] = None, + numeric_value: Optional[float] = None, + subtype: Optional[str] = None, + part_of_day: Optional[str] = None, + relative_hour: Optional[float] = None, + relative_minute: Optional[float] = None, + relative_second: Optional[float] = None, + specific_hour: Optional[float] = None, + specific_minute: Optional[float] = None, + specific_second: Optional[float] = None, + timezone: Optional[str] = None, ) -> None: """ - Initialize a ReleaseSkill object. - - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. - :param str snapshot: (optional) The name of the skill snapshot that is - saved as part of the release (for example, `draft` or `1`). - """ - self.skill_id = skill_id - self.type = type - self.snapshot = snapshot - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': - """Initialize a ReleaseSkill object from a json dictionary.""" - args = {} - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - else: - raise ValueError( - 'Required property \'skill_id\' not present in ReleaseSkill JSON' - ) - if (type := _dict.get('type')) is not None: - args['type'] = type - if (snapshot := _dict.get('snapshot')) is not None: - args['snapshot'] = snapshot - return cls(**args) + Initialize a RuntimeEntityInterpretation object. - @classmethod + :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 = {} + if (calendar_type := _dict.get('calendar_type')) is not None: + args['calendar_type'] = calendar_type + if (datetime_link := _dict.get('datetime_link')) is not None: + args['datetime_link'] = datetime_link + if (festival := _dict.get('festival')) is not None: + args['festival'] = festival + if (granularity := _dict.get('granularity')) is not None: + args['granularity'] = granularity + if (range_link := _dict.get('range_link')) is not None: + args['range_link'] = range_link + if (range_modifier := _dict.get('range_modifier')) is not None: + args['range_modifier'] = range_modifier + if (relative_day := _dict.get('relative_day')) is not None: + args['relative_day'] = relative_day + if (relative_month := _dict.get('relative_month')) is not None: + args['relative_month'] = relative_month + if (relative_week := _dict.get('relative_week')) is not None: + args['relative_week'] = relative_week + if (relative_weekend := _dict.get('relative_weekend')) is not None: + args['relative_weekend'] = relative_weekend + if (relative_year := _dict.get('relative_year')) is not None: + args['relative_year'] = relative_year + if (specific_day := _dict.get('specific_day')) is not None: + args['specific_day'] = specific_day + if (specific_day_of_week := + _dict.get('specific_day_of_week')) is not None: + args['specific_day_of_week'] = specific_day_of_week + if (specific_month := _dict.get('specific_month')) is not None: + args['specific_month'] = specific_month + if (specific_quarter := _dict.get('specific_quarter')) is not None: + args['specific_quarter'] = specific_quarter + if (specific_year := _dict.get('specific_year')) is not None: + args['specific_year'] = specific_year + if (numeric_value := _dict.get('numeric_value')) is not None: + args['numeric_value'] = numeric_value + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype + if (part_of_day := _dict.get('part_of_day')) is not None: + args['part_of_day'] = part_of_day + if (relative_hour := _dict.get('relative_hour')) is not None: + args['relative_hour'] = relative_hour + if (relative_minute := _dict.get('relative_minute')) is not None: + args['relative_minute'] = relative_minute + if (relative_second := _dict.get('relative_second')) is not None: + args['relative_second'] = relative_second + if (specific_hour := _dict.get('specific_hour')) is not None: + args['specific_hour'] = specific_hour + if (specific_minute := _dict.get('specific_minute')) is not None: + args['specific_minute'] = specific_minute + if (specific_second := _dict.get('specific_second')) is not None: + args['specific_second'] = specific_second + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone + return cls(**args) + + @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseSkill object from a json dictionary.""" + """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, 'skill_id') and self.skill_id is not None: - _dict['skill_id'] = self.skill_id - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot + 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): @@ -7593,89 +8149,77 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseSkill object.""" + """Return a `str` version of this RuntimeEntityInterpretation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseSkill') -> bool: + 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: 'ReleaseSkill') -> bool: + def __ne__(self, other: 'RuntimeEntityInterpretation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): + class GranularityEnum(str, Enum): """ - The type of the skill. + The precision or duration of a time range specified by a recognized `@sys-time` or + `@sys-date` entity. """ - DIALOG = 'dialog' - ACTION = 'action' - SEARCH = 'search' + DAY = 'day' + FORTNIGHT = 'fortnight' + HOUR = 'hour' + INSTANT = 'instant' + MINUTE = 'minute' + MONTH = 'month' + QUARTER = 'quarter' + SECOND = 'second' + WEEK = 'week' + WEEKEND = 'weekend' + YEAR = 'year' -class RequestAnalytics: +class RuntimeEntityRole: """ - An optional object containing analytics data. Currently, this data is used only for - events sent to the Segment extension. + 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. - :param str browser: (optional) The browser that was used to send the message - that triggered the event. - :param str device: (optional) The type of device that was used to send the - message that triggered the event. - :param str page_url: (optional) The URL of the web page that was used to send - the message that triggered the event. + :param str type: (optional) The relationship of the entity to the range. """ def __init__( self, *, - browser: Optional[str] = None, - device: Optional[str] = None, - page_url: Optional[str] = None, + type: Optional[str] = None, ) -> None: """ - Initialize a RequestAnalytics object. + Initialize a RuntimeEntityRole object. - :param str browser: (optional) The browser that was used to send the - message that triggered the event. - :param str device: (optional) The type of device that was used to send the - message that triggered the event. - :param str page_url: (optional) The URL of the web page that was used to - send the message that triggered the event. + :param str type: (optional) The relationship of the entity to the range. """ - self.browser = browser - self.device = device - self.page_url = page_url + self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': - """Initialize a RequestAnalytics object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': + """Initialize a RuntimeEntityRole object from a json dictionary.""" args = {} - if (browser := _dict.get('browser')) is not None: - args['browser'] = browser - if (device := _dict.get('device')) is not None: - args['device'] = device - if (page_url := _dict.get('pageUrl')) is not None: - args['page_url'] = page_url + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RequestAnalytics object from a json dictionary.""" + """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, 'browser') and self.browser is not None: - _dict['browser'] = self.browser - if hasattr(self, 'device') and self.device is not None: - _dict['device'] = self.device - if hasattr(self, 'page_url') and self.page_url is not None: - _dict['pageUrl'] = self.page_url + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -7683,58 +8227,101 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RequestAnalytics object.""" + """Return a `str` version of this RuntimeEntityRole object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RequestAnalytics') -> bool: + 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: 'RequestAnalytics') -> bool: + def __ne__(self, other: 'RuntimeEntityRole') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The relationship of the entity to the range. + """ -class ResponseGenericChannel: + 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: """ - ResponseGenericChannel. + An intent identified in the user input. - :param str channel: (optional) A channel for which the response is intended. + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. + :param str skill: (optional) The skill that identified the intent. Currently, + the only possible values are `main skill` for the dialog skill (if enabled) and + `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. """ def __init__( self, + intent: str, *, - channel: Optional[str] = None, + confidence: Optional[float] = None, + skill: Optional[str] = None, ) -> None: """ - Initialize a ResponseGenericChannel object. + Initialize a RuntimeIntent object. - :param str channel: (optional) A channel for which the response is - intended. + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. + :param str skill: (optional) The skill that identified the intent. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. """ - self.channel = channel + self.intent = intent + self.confidence = confidence + self.skill = skill @classmethod - def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': - """Initialize a ResponseGenericChannel object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': + """Initialize a RuntimeIntent object from a json dictionary.""" args = {} - if (channel := _dict.get('channel')) is not None: - args['channel'] = channel + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent + else: + raise ValueError( + 'Required property \'intent\' not present in RuntimeIntent JSON' + ) + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ResponseGenericChannel object from a json dictionary.""" + """Initialize a RuntimeIntent 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, 'channel') and self.channel is not None: - _dict['channel'] = self.channel + if hasattr(self, 'intent') and self.intent is not None: + _dict['intent'] = self.intent + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill return _dict def _to_dict(self): @@ -7742,194 +8329,255 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ResponseGenericChannel object.""" + """Return a `str` version of this RuntimeIntent object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ResponseGenericChannel') -> bool: + def __eq__(self, other: 'RuntimeIntent') -> 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: 'ResponseGenericChannel') -> bool: + def __ne__(self, other: 'RuntimeIntent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntity: +class RuntimeResponseGeneric: """ - The entity value that was recognized in the user input. + RuntimeResponseGeneric. - :param str entity: An entity detected in the input. - :param List[int] location: (optional) An array of zero-based character offsets - that indicate where the detected entity values begin and end in the input text. - :param str value: The term in the input text that was recognized as an entity - value. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized 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. - :param str skill: (optional) The skill that recognized the entity value. - Currently, the only possible values are `main skill` for the dialog skill (if - enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and an - action skill. """ - def __init__( - self, - entity: str, - value: str, - *, - location: Optional[List[int]] = None, - confidence: Optional[float] = None, - groups: Optional[List['CaptureGroup']] = None, - interpretation: Optional['RuntimeEntityInterpretation'] = None, - alternatives: Optional[List['RuntimeEntityAlternative']] = None, - role: Optional['RuntimeEntityRole'] = None, - skill: Optional[str] = None, - ) -> None: + def __init__(self,) -> None: """ - Initialize a RuntimeEntity object. + Initialize a RuntimeResponseGeneric object. - :param str entity: An entity detected in the input. - :param str value: The term in the input text that was recognized as an - entity value. - :param List[int] location: (optional) An array of zero-based character - offsets that indicate where the detected entity values begin and end in the - input text. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized 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. - :param str skill: (optional) The skill that recognized the entity value. - Currently, the only possible values are `main skill` for the dialog skill - (if enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and - an action skill. """ - self.entity = entity - self.location = location - self.value = value - self.confidence = confidence - self.groups = groups - self.interpretation = interpretation - self.alternatives = alternatives - self.role = role - self.skill = skill + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': - """Initialize a RuntimeEntity object from a json dictionary.""" - args = {} - if (entity := _dict.get('entity')) is not None: - args['entity'] = entity - else: - raise ValueError( - 'Required property \'entity\' not present in RuntimeEntity JSON' - ) - if (location := _dict.get('location')) is not None: - args['location'] = location - if (value := _dict.get('value')) is not None: - args['value'] = value + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' + mapping[ + 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + mapping[ + 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' + mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' + mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' + mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' + mapping[ + 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' + mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' + mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + mapping[ + 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class SearchResult: + """ + SearchResult. + + :param str id: The unique identifier of the document in the Discovery service + collection. + This property is included in responses from search skills, which are available + only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search result + metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is taken + from an abstract, summary, or highlight field in the Discovery service response, + as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken from + a title or name field in the Discovery service response, as specified in the + search skill configuration. + :param str url: (optional) The URL of the original data object in its native + data source. + :param SearchResultHighlight highlight: (optional) An object containing segments + of text from search results with query-matching text highlighted using HTML + `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying segments + of text within the result that were identified as direct answers to the search + query. Currently, only the single answer with the highest confidence (if any) is + returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + + def __init__( + self, + id: str, + result_metadata: 'SearchResultMetadata', + *, + body: Optional[str] = None, + title: Optional[str] = None, + url: Optional[str] = None, + highlight: Optional['SearchResultHighlight'] = None, + answers: Optional[List['SearchResultAnswer']] = None, + ) -> None: + """ + Initialize a SearchResult object. + + :param str id: The unique identifier of the document in the Discovery + service collection. + This property is included in responses from search skills, which are + available only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search + result metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is + taken from an abstract, summary, or highlight field in the Discovery + service response, as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken + from a title or name field in the Discovery service response, as specified + in the search skill configuration. + :param str url: (optional) The URL of the original data object in its + native data source. + :param SearchResultHighlight highlight: (optional) An object containing + segments of text from search results with query-matching text highlighted + using HTML `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying + segments of text within the result that were identified as direct answers + to the search query. Currently, only the single answer with the highest + confidence (if any) is returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.id = id + self.result_metadata = result_metadata + self.body = body + self.title = title + self.url = url + self.highlight = highlight + self.answers = answers + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResult': + """Initialize a SearchResult object from a json dictionary.""" + args = {} + if (id := _dict.get('id')) is not None: + args['id'] = id else: raise ValueError( - 'Required property \'value\' not present in RuntimeEntity JSON') - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (groups := _dict.get('groups')) is not None: - args['groups'] = [CaptureGroup.from_dict(v) for v in groups] - if (interpretation := _dict.get('interpretation')) is not None: - args['interpretation'] = RuntimeEntityInterpretation.from_dict( - interpretation) - if (alternatives := _dict.get('alternatives')) is not None: - args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(v) for v in alternatives - ] - if (role := _dict.get('role')) is not None: - args['role'] = RuntimeEntityRole.from_dict(role) - if (skill := _dict.get('skill')) is not None: - args['skill'] = skill + 'Required property \'id\' not present in SearchResult JSON') + if (result_metadata := _dict.get('result_metadata')) is not None: + args['result_metadata'] = SearchResultMetadata.from_dict( + result_metadata) + else: + raise ValueError( + 'Required property \'result_metadata\' not present in SearchResult JSON' + ) + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = SearchResultHighlight.from_dict(highlight) + if (answers := _dict.get('answers')) is not None: + args['answers'] = [SearchResultAnswer.from_dict(v) for v in answers] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntity object from a json dictionary.""" + """Initialize a SearchResult 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, 'entity') and self.entity is not None: - _dict['entity'] = self.entity - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location - 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 - if hasattr(self, 'groups') and self.groups is not None: - groups_list = [] - for v in self.groups: - if isinstance(v, dict): - groups_list.append(v) - else: - groups_list.append(v.to_dict()) - _dict['groups'] = groups_list - if hasattr(self, 'interpretation') and self.interpretation is not None: - if isinstance(self.interpretation, dict): - _dict['interpretation'] = self.interpretation + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id + if hasattr(self, + 'result_metadata') and self.result_metadata is not None: + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata else: - _dict['interpretation'] = self.interpretation.to_dict() - if hasattr(self, 'alternatives') and self.alternatives is not None: - alternatives_list = [] - for v in self.alternatives: + _dict['result_metadata'] = self.result_metadata.to_dict() + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'highlight') and self.highlight is not None: + if isinstance(self.highlight, dict): + _dict['highlight'] = self.highlight + else: + _dict['highlight'] = self.highlight.to_dict() + if hasattr(self, 'answers') and self.answers is not None: + answers_list = [] + for v in self.answers: if isinstance(v, dict): - alternatives_list.append(v) + answers_list.append(v) else: - alternatives_list.append(v.to_dict()) - _dict['alternatives'] = alternatives_list - if hasattr(self, 'role') and self.role is not None: - if isinstance(self.role, dict): - _dict['role'] = self.role - else: - _dict['role'] = self.role.to_dict() - if hasattr(self, 'skill') and self.skill is not None: - _dict['skill'] = self.skill + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list return _dict def _to_dict(self): @@ -7937,67 +8585,73 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntity object.""" + """Return a `str` version of this SearchResult object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntity') -> bool: + def __eq__(self, other: 'SearchResult') -> 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: 'RuntimeEntity') -> bool: + def __ne__(self, other: 'SearchResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityAlternative: +class SearchResultAnswer: """ - An alternative value for the recognized entity. + An object specifing a segment of text that was identified as a direct answer to the + search query. - :param str value: (optional) The entity value that was recognized in the user - input. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized entity. + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned by the + Discovery service. """ def __init__( self, - *, - value: Optional[str] = None, - confidence: Optional[float] = None, + text: str, + confidence: float, ) -> None: """ - Initialize a RuntimeEntityAlternative object. + Initialize a SearchResultAnswer object. - :param str value: (optional) The entity value that was recognized in the - user input. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized entity. + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned + by the Discovery service. """ - self.value = value + self.text = text self.confidence = confidence @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': + """Initialize a SearchResultAnswer object from a json dictionary.""" args = {} - if (value := _dict.get('value')) is not None: - args['value'] = value + if (text := _dict.get('text')) is not None: + args['text'] = text + else: + raise ValueError( + 'Required property \'text\' not present in SearchResultAnswer JSON' + ) if (confidence := _dict.get('confidence')) is not None: args['confidence'] = confidence + else: + raise ValueError( + 'Required property \'confidence\' not present in SearchResultAnswer JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + """Initialize a SearchResultAnswer 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, 'text') and self.text is not None: + _dict['text'] = self.text if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence return _dict @@ -8007,354 +8661,478 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityAlternative object.""" + """Return a `str` version of this SearchResultAnswer object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + def __eq__(self, other: 'SearchResultAnswer') -> 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: + def __ne__(self, other: 'SearchResultAnswer') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityInterpretation: +class SearchResultHighlight: """ - RuntimeEntityInterpretation. + An object containing segments of text from search results with query-matching text + highlighted using HTML `` tags. - :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`). + :param List[str] body: (optional) An array of strings containing segments taken + from body text in the search results, with query-matching substrings + highlighted. + :param List[str] title: (optional) An array of strings containing segments taken + from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments taken + from URLs in the search results, with query-matching substrings highlighted. """ + # The set of defined properties for the class + _properties = frozenset(['body', 'title', 'url']) + def __init__( self, *, - calendar_type: Optional[str] = None, - datetime_link: Optional[str] = None, - festival: Optional[str] = None, - granularity: Optional[str] = None, - range_link: Optional[str] = None, - range_modifier: Optional[str] = None, - relative_day: Optional[float] = None, - relative_month: Optional[float] = None, - relative_week: Optional[float] = None, - relative_weekend: Optional[float] = None, - relative_year: Optional[float] = None, - specific_day: Optional[float] = None, - specific_day_of_week: Optional[str] = None, - specific_month: Optional[float] = None, - specific_quarter: Optional[float] = None, - specific_year: Optional[float] = None, - numeric_value: Optional[float] = None, - subtype: Optional[str] = None, - part_of_day: Optional[str] = None, - relative_hour: Optional[float] = None, - relative_minute: Optional[float] = None, - relative_second: Optional[float] = None, - specific_hour: Optional[float] = None, - specific_minute: Optional[float] = None, - specific_second: Optional[float] = None, - timezone: Optional[str] = None, + body: Optional[List[str]] = None, + title: Optional[List[str]] = None, + url: Optional[List[str]] = None, + **kwargs, ) -> None: """ - Initialize a RuntimeEntityInterpretation object. + Initialize a SearchResultHighlight 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`). + :param List[str] body: (optional) An array of strings containing segments + taken from body text in the search results, with query-matching substrings + highlighted. + :param List[str] title: (optional) An array of strings containing segments + taken from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments + taken from URLs in the search results, with query-matching substrings + highlighted. + :param **kwargs: (optional) Any additional properties. """ - 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 + self.body = body + self.title = title + self.url = url + for _key, _value in kwargs.items(): + setattr(self, _key, _value) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': + """Initialize a SearchResultHighlight object from a json dictionary.""" + args = {} + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultHighlight 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, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in SearchResultHighlight._properties: + setattr(self, _key, _value) + + def __str__(self) -> str: + """Return a `str` version of this SearchResultHighlight object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultHighlight') -> 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: 'SearchResultHighlight') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultMetadata: + """ + An object containing search result metadata from the Discovery service. + + :param float confidence: (optional) The confidence score for the given result, + as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher score + indicates a greater match to the query parameters. + """ + + def __init__( + self, + *, + confidence: Optional[float] = None, + score: Optional[float] = None, + ) -> None: + """ + Initialize a SearchResultMetadata object. + + :param float confidence: (optional) The confidence score for the given + result, as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher + score indicates a greater match to the query parameters. + """ + self.confidence = confidence + self.score = score + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': + """Initialize a SearchResultMetadata object from a json dictionary.""" + args = {} + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (score := _dict.get('score')) is not None: + args['score'] = score + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultMetadata 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, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score + 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 SearchResultMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultMetadata') -> 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: 'SearchResultMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettings: + """ + An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and are not + included in **Export skills** responses. + + :param SearchSettingsDiscovery discovery: Configuration settings for the Watson + Discovery service instance used by the search integration. + :param SearchSettingsMessages messages: The messages included with responses + from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between fields in + the Watson Discovery collection and properties in the search response. + """ + + def __init__( + self, + discovery: 'SearchSettingsDiscovery', + messages: 'SearchSettingsMessages', + schema_mapping: 'SearchSettingsSchemaMapping', + ) -> None: + """ + Initialize a SearchSettings object. + + :param SearchSettingsDiscovery discovery: Configuration settings for the + Watson Discovery service instance used by the search integration. + :param SearchSettingsMessages messages: The messages included with + responses from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between + fields in the Watson Discovery collection and properties in the search + response. + """ + self.discovery = discovery + self.messages = messages + self.schema_mapping = schema_mapping + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettings': + """Initialize a SearchSettings object from a json dictionary.""" + args = {} + if (discovery := _dict.get('discovery')) is not None: + args['discovery'] = SearchSettingsDiscovery.from_dict(discovery) + else: + raise ValueError( + 'Required property \'discovery\' not present in SearchSettings JSON' + ) + if (messages := _dict.get('messages')) is not None: + args['messages'] = SearchSettingsMessages.from_dict(messages) + else: + raise ValueError( + 'Required property \'messages\' not present in SearchSettings JSON' + ) + if (schema_mapping := _dict.get('schema_mapping')) is not None: + args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( + schema_mapping) + else: + raise ValueError( + 'Required property \'schema_mapping\' not present in SearchSettings JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettings 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, 'discovery') and self.discovery is not None: + if isinstance(self.discovery, dict): + _dict['discovery'] = self.discovery + else: + _dict['discovery'] = self.discovery.to_dict() + if hasattr(self, 'messages') and self.messages is not None: + if isinstance(self.messages, dict): + _dict['messages'] = self.messages + else: + _dict['messages'] = self.messages.to_dict() + if hasattr(self, 'schema_mapping') and self.schema_mapping is not None: + if isinstance(self.schema_mapping, dict): + _dict['schema_mapping'] = self.schema_mapping + else: + _dict['schema_mapping'] = self.schema_mapping.to_dict() + 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 SearchSettings object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettings') -> 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: 'SearchSettings') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsDiscovery: + """ + Configuration settings for the Watson Discovery service instance used by the search + integration. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param int max_primary_results: (optional) The maximum number of primary results + to include in the response. + :param int max_total_results: (optional) The maximum total number of primary and + additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence threshold + for included results. Any results with a confidence below this threshold will be + discarded. + :param bool highlight: (optional) Whether to include the most relevant passages + of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding feature + to emphasize answers within highlighted passages. This property is ignored if + **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + """ + + def __init__( + self, + instance_id: str, + project_id: str, + url: str, + authentication: 'SearchSettingsDiscoveryAuthentication', + *, + max_primary_results: Optional[int] = None, + max_total_results: Optional[int] = None, + confidence_threshold: Optional[float] = None, + highlight: Optional[bool] = None, + find_answers: Optional[bool] = None, + ) -> None: + """ + Initialize a SearchSettingsDiscovery object. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + :param int max_primary_results: (optional) The maximum number of primary + results to include in the response. + :param int max_total_results: (optional) The maximum total number of + primary and additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence + threshold for included results. Any results with a confidence below this + threshold will be discarded. + :param bool highlight: (optional) Whether to include the most relevant + passages of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding + feature to emphasize answers within highlighted passages. This property is + ignored if **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.instance_id = instance_id + self.project_id = project_id + self.url = url + self.max_primary_results = max_primary_results + self.max_total_results = max_total_results + self.confidence_threshold = confidence_threshold + self.highlight = highlight + self.find_answers = find_answers + self.authentication = authentication @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': + """Initialize a SearchSettingsDiscovery object from a json dictionary.""" args = {} - if (calendar_type := _dict.get('calendar_type')) is not None: - args['calendar_type'] = calendar_type - if (datetime_link := _dict.get('datetime_link')) is not None: - args['datetime_link'] = datetime_link - if (festival := _dict.get('festival')) is not None: - args['festival'] = festival - if (granularity := _dict.get('granularity')) is not None: - args['granularity'] = granularity - if (range_link := _dict.get('range_link')) is not None: - args['range_link'] = range_link - if (range_modifier := _dict.get('range_modifier')) is not None: - args['range_modifier'] = range_modifier - if (relative_day := _dict.get('relative_day')) is not None: - args['relative_day'] = relative_day - if (relative_month := _dict.get('relative_month')) is not None: - args['relative_month'] = relative_month - if (relative_week := _dict.get('relative_week')) is not None: - args['relative_week'] = relative_week - if (relative_weekend := _dict.get('relative_weekend')) is not None: - args['relative_weekend'] = relative_weekend - if (relative_year := _dict.get('relative_year')) is not None: - args['relative_year'] = relative_year - if (specific_day := _dict.get('specific_day')) is not None: - args['specific_day'] = specific_day - if (specific_day_of_week := - _dict.get('specific_day_of_week')) is not None: - args['specific_day_of_week'] = specific_day_of_week - if (specific_month := _dict.get('specific_month')) is not None: - args['specific_month'] = specific_month - if (specific_quarter := _dict.get('specific_quarter')) is not None: - args['specific_quarter'] = specific_quarter - if (specific_year := _dict.get('specific_year')) is not None: - args['specific_year'] = specific_year - if (numeric_value := _dict.get('numeric_value')) is not None: - args['numeric_value'] = numeric_value - if (subtype := _dict.get('subtype')) is not None: - args['subtype'] = subtype - if (part_of_day := _dict.get('part_of_day')) is not None: - args['part_of_day'] = part_of_day - if (relative_hour := _dict.get('relative_hour')) is not None: - args['relative_hour'] = relative_hour - if (relative_minute := _dict.get('relative_minute')) is not None: - args['relative_minute'] = relative_minute - if (relative_second := _dict.get('relative_second')) is not None: - args['relative_second'] = relative_second - if (specific_hour := _dict.get('specific_hour')) is not None: - args['specific_hour'] = specific_hour - if (specific_minute := _dict.get('specific_minute')) is not None: - args['specific_minute'] = specific_minute - if (specific_second := _dict.get('specific_second')) is not None: - args['specific_second'] = specific_second - if (timezone := _dict.get('timezone')) is not None: - args['timezone'] = timezone + if (instance_id := _dict.get('instance_id')) is not None: + args['instance_id'] = instance_id + else: + raise ValueError( + 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' + ) + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id + else: + raise ValueError( + 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' + ) + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsDiscovery JSON' + ) + if (max_primary_results := + _dict.get('max_primary_results')) is not None: + args['max_primary_results'] = max_primary_results + if (max_total_results := _dict.get('max_total_results')) is not None: + args['max_total_results'] = max_total_results + if (confidence_threshold := + _dict.get('confidence_threshold')) is not None: + args['confidence_threshold'] = confidence_threshold + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = highlight + if (find_answers := _dict.get('find_answers')) is not None: + args['find_answers'] = find_answers + if (authentication := _dict.get('authentication')) is not None: + args[ + 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( + authentication) + else: + raise ValueError( + 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + """Initialize a SearchSettingsDiscovery 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, 'instance_id') and self.instance_id is not None: + _dict['instance_id'] = self.instance_id + if hasattr(self, 'project_id') and self.project_id is not None: + _dict['project_id'] = self.project_id + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr( + self, + 'max_primary_results') and self.max_primary_results is not None: + _dict['max_primary_results'] = self.max_primary_results 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 + 'max_total_results') and self.max_total_results is not None: + _dict['max_total_results'] = self.max_total_results + if hasattr(self, 'confidence_threshold' + ) and self.confidence_threshold is not None: + _dict['confidence_threshold'] = self.confidence_threshold + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'find_answers') and self.find_answers is not None: + _dict['find_answers'] = self.find_answers + if hasattr(self, 'authentication') and self.authentication is not None: + if isinstance(self.authentication, dict): + _dict['authentication'] = self.authentication + else: + _dict['authentication'] = self.authentication.to_dict() return _dict def _to_dict(self): @@ -8362,77 +9140,74 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityInterpretation object.""" + """Return a `str` version of this SearchSettingsDiscovery object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + def __eq__(self, other: 'SearchSettingsDiscovery') -> 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: + def __ne__(self, other: 'SearchSettingsDiscovery') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class GranularityEnum(str, 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: +class SearchSettingsDiscoveryAuthentication: """ - 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. + Authentication information for the Watson Discovery service. For more information, see + the [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. - :param str type: (optional) The relationship of the entity to the range. + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. """ def __init__( self, *, - type: Optional[str] = None, + basic: Optional[str] = None, + bearer: Optional[str] = None, ) -> None: """ - Initialize a RuntimeEntityRole object. + Initialize a SearchSettingsDiscoveryAuthentication object. - :param str type: (optional) The relationship of the entity to the range. + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. """ - self.type = type + self.basic = basic + self.bearer = bearer - @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': - """Initialize a RuntimeEntityRole object from a json dictionary.""" + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': + """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type + if (basic := _dict.get('basic')) is not None: + args['basic'] = basic + if (bearer := _dict.get('bearer')) is not None: + args['bearer'] = bearer return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityRole object from a json dictionary.""" + """Initialize a SearchSettingsDiscoveryAuthentication 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 + if hasattr(self, 'basic') and self.basic is not None: + _dict['basic'] = self.basic + if hasattr(self, 'bearer') and self.bearer is not None: + _dict['bearer'] = self.bearer return _dict def _to_dict(self): @@ -8440,101 +9215,90 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityRole object.""" + """Return a `str` version of this SearchSettingsDiscoveryAuthentication object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityRole') -> bool: + def __eq__(self, other: 'SearchSettingsDiscoveryAuthentication') -> 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: + def __ne__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, 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: +class SearchSettingsMessages: """ - An intent identified in the user input. + The messages included with responses from the search integration. - :param str intent: The name of the recognized intent. - :param float confidence: (optional) A decimal percentage that represents - confidence in the intent. If you are specifying an intent as part of a request, - but you do not have a calculated confidence value, specify `1`. - :param str skill: (optional) The skill that identified the intent. Currently, - the only possible values are `main skill` for the dialog skill (if enabled) and - `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and an - action skill. + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is no + result from the query. """ def __init__( self, - intent: str, - *, - confidence: Optional[float] = None, - skill: Optional[str] = None, + success: str, + error: str, + no_result: str, ) -> None: """ - Initialize a RuntimeIntent object. + Initialize a SearchSettingsMessages object. - :param str intent: The name of the recognized intent. - :param float confidence: (optional) A decimal percentage that represents - confidence in the intent. If you are specifying an intent as part of a - request, but you do not have a calculated confidence value, specify `1`. - :param str skill: (optional) The skill that identified the intent. - Currently, the only possible values are `main skill` for the dialog skill - (if enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and - an action skill. + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is + no result from the query. """ - self.intent = intent - self.confidence = confidence - self.skill = skill + self.success = success + self.error = error + self.no_result = no_result @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': - """Initialize a RuntimeIntent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': + """Initialize a SearchSettingsMessages object from a json dictionary.""" args = {} - if (intent := _dict.get('intent')) is not None: - args['intent'] = intent + if (success := _dict.get('success')) is not None: + args['success'] = success else: raise ValueError( - 'Required property \'intent\' not present in RuntimeIntent JSON' + 'Required property \'success\' not present in SearchSettingsMessages JSON' + ) + if (error := _dict.get('error')) is not None: + args['error'] = error + else: + raise ValueError( + 'Required property \'error\' not present in SearchSettingsMessages JSON' + ) + if (no_result := _dict.get('no_result')) is not None: + args['no_result'] = no_result + else: + raise ValueError( + 'Required property \'no_result\' not present in SearchSettingsMessages JSON' ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (skill := _dict.get('skill')) is not None: - args['skill'] = skill return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeIntent object from a json dictionary.""" + """Initialize a SearchSettingsMessages 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, 'intent') and self.intent is not None: - _dict['intent'] = self.intent - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'skill') and self.skill is not None: - _dict['skill'] = self.skill + if hasattr(self, 'success') and self.success is not None: + _dict['success'] = self.success + if hasattr(self, 'error') and self.error is not None: + _dict['error'] = self.error + if hasattr(self, 'no_result') and self.no_result is not None: + _dict['no_result'] = self.no_result return _dict def _to_dict(self): @@ -8542,255 +9306,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeIntent object.""" + """Return a `str` version of this SearchSettingsMessages object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeIntent') -> bool: + def __eq__(self, other: 'SearchSettingsMessages') -> 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: 'RuntimeIntent') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class RuntimeResponseGeneric: - """ - RuntimeResponseGeneric. - - """ - - def __init__(self,) -> None: - """ - Initialize a RuntimeResponseGeneric object. - - """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - return cls.from_dict(_dict) - - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' - mapping[ - 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' - mapping[ - 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' - mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' - mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' - mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' - mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' - mapping[ - 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' - mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' - mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' - mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' - mapping[ - 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' - mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' - disc_value = _dict.get('response_type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - - -class SearchResult: - """ - SearchResult. - - :param str id: The unique identifier of the document in the Discovery service - collection. - This property is included in responses from search skills, which are available - only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search result - metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is taken - from an abstract, summary, or highlight field in the Discovery service response, - as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken from - a title or name field in the Discovery service response, as specified in the - search skill configuration. - :param str url: (optional) The URL of the original data object in its native - data source. - :param SearchResultHighlight highlight: (optional) An object containing segments - of text from search results with query-matching text highlighted using HTML - `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying segments - of text within the result that were identified as direct answers to the search - query. Currently, only the single answer with the highest confidence (if any) is - returned. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. + + def __ne__(self, other: 'SearchSettingsMessages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsSchemaMapping: + """ + The mapping between fields in the Watson Discovery collection and properties in the + search response. + + :param str url: The field in the collection to map to the **url** property of + the response. + :param str body: The field in the collection to map to the **body** property in + the response. + :param str title: The field in the collection to map to the **title** property + for the schema. """ def __init__( self, - id: str, - result_metadata: 'SearchResultMetadata', - *, - body: Optional[str] = None, - title: Optional[str] = None, - url: Optional[str] = None, - highlight: Optional['SearchResultHighlight'] = None, - answers: Optional[List['SearchResultAnswer']] = None, + url: str, + body: str, + title: str, ) -> None: """ - Initialize a SearchResult object. + Initialize a SearchSettingsSchemaMapping object. - :param str id: The unique identifier of the document in the Discovery - service collection. - This property is included in responses from search skills, which are - available only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search - result metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is - taken from an abstract, summary, or highlight field in the Discovery - service response, as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken - from a title or name field in the Discovery service response, as specified - in the search skill configuration. - :param str url: (optional) The URL of the original data object in its - native data source. - :param SearchResultHighlight highlight: (optional) An object containing - segments of text from search results with query-matching text highlighted - using HTML `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying - segments of text within the result that were identified as direct answers - to the search query. Currently, only the single answer with the highest - confidence (if any) is returned. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. + :param str url: The field in the collection to map to the **url** property + of the response. + :param str body: The field in the collection to map to the **body** + property in the response. + :param str title: The field in the collection to map to the **title** + property for the schema. """ - self.id = id - self.result_metadata = result_metadata + self.url = url self.body = body self.title = title - self.url = url - self.highlight = highlight - self.answers = answers @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResult': - """Initialize a SearchResult object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': + """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" args = {} - if (id := _dict.get('id')) is not None: - args['id'] = id - else: - raise ValueError( - 'Required property \'id\' not present in SearchResult JSON') - if (result_metadata := _dict.get('result_metadata')) is not None: - args['result_metadata'] = SearchResultMetadata.from_dict( - result_metadata) + if (url := _dict.get('url')) is not None: + args['url'] = url else: raise ValueError( - 'Required property \'result_metadata\' not present in SearchResult JSON' + 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' ) if (body := _dict.get('body')) is not None: args['body'] = body + else: + raise ValueError( + 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' + ) if (title := _dict.get('title')) is not None: args['title'] = title - if (url := _dict.get('url')) is not None: - args['url'] = url - if (highlight := _dict.get('highlight')) is not None: - args['highlight'] = SearchResultHighlight.from_dict(highlight) - if (answers := _dict.get('answers')) is not None: - args['answers'] = [SearchResultAnswer.from_dict(v) for v in answers] + else: + raise ValueError( + 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResult object from a json dictionary.""" + """Initialize a SearchSettingsSchemaMapping 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, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - if isinstance(self.result_metadata, dict): - _dict['result_metadata'] = self.result_metadata - else: - _dict['result_metadata'] = self.result_metadata.to_dict() + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url if hasattr(self, 'body') and self.body is not None: _dict['body'] = self.body if hasattr(self, 'title') and self.title is not None: _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'highlight') and self.highlight is not None: - if isinstance(self.highlight, dict): - _dict['highlight'] = self.highlight - else: - _dict['highlight'] = self.highlight.to_dict() - if hasattr(self, 'answers') and self.answers is not None: - answers_list = [] - for v in self.answers: - if isinstance(v, dict): - answers_list.append(v) - else: - answers_list.append(v.to_dict()) - _dict['answers'] = answers_list return _dict def _to_dict(self): @@ -8798,75 +9398,75 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResult object.""" + """Return a `str` version of this SearchSettingsSchemaMapping object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResult') -> bool: + def __eq__(self, other: 'SearchSettingsSchemaMapping') -> 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: 'SearchResult') -> bool: + def __ne__(self, other: 'SearchSettingsSchemaMapping') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultAnswer: +class SearchSkillWarning: """ - An object specifing a segment of text that was identified as a direct answer to the - search query. + A warning describing an error in the search skill configuration. - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned by the - Discovery service. + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. """ def __init__( self, - text: str, - confidence: float, + *, + code: Optional[str] = None, + path: Optional[str] = None, + message: Optional[str] = None, ) -> None: """ - Initialize a SearchResultAnswer object. + Initialize a SearchSkillWarning object. - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned - by the Discovery service. + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. """ - self.text = text - self.confidence = confidence + self.code = code + self.path = path + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': - """Initialize a SearchResultAnswer object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': + """Initialize a SearchSkillWarning object from a json dictionary.""" args = {} - if (text := _dict.get('text')) is not None: - args['text'] = text - else: - raise ValueError( - 'Required property \'text\' not present in SearchResultAnswer JSON' - ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - else: - raise ValueError( - 'Required property \'confidence\' not present in SearchResultAnswer JSON' - ) + if (code := _dict.get('code')) is not None: + args['code'] = code + if (path := _dict.get('path')) is not None: + args['path'] = path + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultAnswer object from a json dictionary.""" + """Initialize a SearchSkillWarning 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -8874,194 +9474,300 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultAnswer object.""" + """Return a `str` version of this SearchSkillWarning object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultAnswer') -> bool: + def __eq__(self, other: 'SearchSkillWarning') -> 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: 'SearchResultAnswer') -> bool: + def __ne__(self, other: 'SearchSkillWarning') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultHighlight: +class SessionResponse: """ - An object containing segments of text from search results with query-matching text - highlighted using HTML `` tags. + SessionResponse. - :param List[str] body: (optional) An array of strings containing segments taken - from body text in the search results, with query-matching substrings - highlighted. - :param List[str] title: (optional) An array of strings containing segments taken - from title text in the search results, with query-matching substrings - highlighted. - :param List[str] url: (optional) An array of strings containing segments taken - from URLs in the search results, with query-matching substrings highlighted. + :param str session_id: The session ID. """ - # The set of defined properties for the class - _properties = frozenset(['body', 'title', 'url']) - def __init__( self, - *, - body: Optional[List[str]] = None, - title: Optional[List[str]] = None, - url: Optional[List[str]] = None, - **kwargs, + session_id: str, ) -> None: """ - Initialize a SearchResultHighlight object. + Initialize a SessionResponse object. - :param List[str] body: (optional) An array of strings containing segments - taken from body text in the search results, with query-matching substrings - highlighted. - :param List[str] title: (optional) An array of strings containing segments - taken from title text in the search results, with query-matching substrings - highlighted. - :param List[str] url: (optional) An array of strings containing segments - taken from URLs in the search results, with query-matching substrings - highlighted. - :param **kwargs: (optional) Any additional properties. + :param str session_id: The session ID. """ - self.body = body - self.title = title - self.url = url - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': - """Initialize a SearchResultHighlight object from a json dictionary.""" - args = {} - if (body := _dict.get('body')) is not None: - args['body'] = body - if (title := _dict.get('title')) is not None: - args['title'] = title - if (url := _dict.get('url')) is not None: - args['url'] = url - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + self.session_id = session_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SessionResponse': + """Initialize a SessionResponse object from a json dictionary.""" + args = {} + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id + else: + raise ValueError( + 'Required property \'session_id\' not present in SessionResponse JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultHighlight object from a json dictionary.""" + """Initialize a SessionResponse 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, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in SearchResultHighlight._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this SearchResultHighlight object.""" + """Return a `str` version of this SessionResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultHighlight') -> bool: + def __eq__(self, other: 'SessionResponse') -> 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: 'SearchResultHighlight') -> bool: + def __ne__(self, other: 'SessionResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultMetadata: +class Skill: """ - An object containing search result metadata from the Discovery service. + Skill. - :param float confidence: (optional) The confidence score for the given result, - as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. + :param str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :param str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :param str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :param str language: The language of the skill. + :param str type: The type of skill. """ def __init__( self, + language: str, + type: str, *, - confidence: Optional[float] = None, - score: Optional[float] = None, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, ) -> None: """ - Initialize a SearchResultMetadata object. + Initialize a Skill object. - :param float confidence: (optional) The confidence score for the given - result, as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher - score indicates a greater match to the query parameters. + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. """ - self.confidence = confidence - self.score = score + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': - """Initialize a SearchResultMetadata object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Skill': + """Initialize a Skill object from a json dictionary.""" args = {} - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (score := _dict.get('score')) is not None: - args['score'] = score + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in warnings + ] + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in Skill JSON') + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in Skill JSON') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultMetadata object from a json dictionary.""" + """Initialize a Skill 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, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') + if hasattr(self, + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -9069,103 +9775,267 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultMetadata object.""" + """Return a `str` version of this Skill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultMetadata') -> bool: + def __eq__(self, other: 'Skill') -> 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: 'SearchResultMetadata') -> bool: + def __ne__(self, other: 'Skill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' -class SearchSettings: + class TypeEnum(str, Enum): + """ + The type of skill. + """ + + ACTION = 'action' + DIALOG = 'dialog' + SEARCH = 'search' + + +class SkillImport: """ - An object describing the search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and are not - included in **Export skills** responses. + SkillImport. - :param SearchSettingsDiscovery discovery: Configuration settings for the Watson - Discovery service instance used by the search integration. - :param SearchSettingsMessages messages: The messages included with responses - from the search integration. - :param SearchSettingsSchemaMapping schema_mapping: The mapping between fields in - the Watson Discovery collection and properties in the search response. + :param str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :param str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :param str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :param str language: The language of the skill. + :param str type: The type of skill. """ def __init__( self, - discovery: 'SearchSettingsDiscovery', - messages: 'SearchSettingsMessages', - schema_mapping: 'SearchSettingsSchemaMapping', + language: str, + type: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, ) -> None: """ - Initialize a SearchSettings object. + Initialize a SkillImport object. - :param SearchSettingsDiscovery discovery: Configuration settings for the - Watson Discovery service instance used by the search integration. - :param SearchSettingsMessages messages: The messages included with - responses from the search integration. - :param SearchSettingsSchemaMapping schema_mapping: The mapping between - fields in the Watson Discovery collection and properties in the search - response. + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. """ - self.discovery = discovery - self.messages = messages - self.schema_mapping = schema_mapping + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettings': - """Initialize a SearchSettings object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillImport': + """Initialize a SkillImport object from a json dictionary.""" args = {} - if (discovery := _dict.get('discovery')) is not None: - args['discovery'] = SearchSettingsDiscovery.from_dict(discovery) - else: - raise ValueError( - 'Required property \'discovery\' not present in SearchSettings JSON' - ) - if (messages := _dict.get('messages')) is not None: - args['messages'] = SearchSettingsMessages.from_dict(messages) + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in warnings + ] + if (language := _dict.get('language')) is not None: + args['language'] = language else: raise ValueError( - 'Required property \'messages\' not present in SearchSettings JSON' + 'Required property \'language\' not present in SkillImport JSON' ) - if (schema_mapping := _dict.get('schema_mapping')) is not None: - args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( - schema_mapping) + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( - 'Required property \'schema_mapping\' not present in SearchSettings JSON' - ) + 'Required property \'type\' not present in SkillImport JSON') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettings object from a json dictionary.""" + """Initialize a SkillImport 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, 'discovery') and self.discovery is not None: - if isinstance(self.discovery, dict): - _dict['discovery'] = self.discovery - else: - _dict['discovery'] = self.discovery.to_dict() - if hasattr(self, 'messages') and self.messages is not None: - if isinstance(self.messages, dict): - _dict['messages'] = self.messages - else: - _dict['messages'] = self.messages.to_dict() - if hasattr(self, 'schema_mapping') and self.schema_mapping is not None: - if isinstance(self.schema_mapping, dict): - _dict['schema_mapping'] = self.schema_mapping + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') + if hasattr(self, + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings else: - _dict['schema_mapping'] = self.schema_mapping.to_dict() + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -9173,179 +10043,122 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettings object.""" + """Return a `str` version of this SkillImport object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettings') -> bool: + def __eq__(self, other: 'SkillImport') -> 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: 'SearchSettings') -> bool: + def __ne__(self, other: 'SkillImport') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' -class SearchSettingsDiscovery: + class TypeEnum(str, Enum): + """ + The type of skill. + """ + + ACTION = 'action' + DIALOG = 'dialog' + + +class SkillsAsyncRequestStatus: """ - Configuration settings for the Watson Discovery service instance used by the search - integration. + SkillsAsyncRequestStatus. - :param str instance_id: The ID for the Watson Discovery service instance. - :param str project_id: The ID for the Watson Discovery project. - :param str url: The URL for the Watson Discovery service instance. - :param int max_primary_results: (optional) The maximum number of primary results - to include in the response. - :param int max_total_results: (optional) The maximum total number of primary and - additional results to include in the response. - :param float confidence_threshold: (optional) The minimum confidence threshold - for included results. Any results with a confidence below this threshold will be - discarded. - :param bool highlight: (optional) Whether to include the most relevant passages - of text in the **highlight** property of each result. - :param bool find_answers: (optional) Whether to use the answer finding feature - to emphasize answers within highlighted passages. This property is ignored if - **highlight**=`false`. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. - :param SearchSettingsDiscoveryAuthentication authentication: Authentication - information for the Watson Discovery service. For more information, see the - [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. + :param str assistant_id: (optional) The assistant ID of the assistant. + :param str status: (optional) The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. """ def __init__( self, - instance_id: str, - project_id: str, - url: str, - authentication: 'SearchSettingsDiscoveryAuthentication', *, - max_primary_results: Optional[int] = None, - max_total_results: Optional[int] = None, - confidence_threshold: Optional[float] = None, - highlight: Optional[bool] = None, - find_answers: Optional[bool] = None, + assistant_id: Optional[str] = None, + status: Optional[str] = None, + status_description: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, ) -> None: """ - Initialize a SearchSettingsDiscovery object. + Initialize a SkillsAsyncRequestStatus object. - :param str instance_id: The ID for the Watson Discovery service instance. - :param str project_id: The ID for the Watson Discovery project. - :param str url: The URL for the Watson Discovery service instance. - :param SearchSettingsDiscoveryAuthentication authentication: Authentication - information for the Watson Discovery service. For more information, see the - [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. - :param int max_primary_results: (optional) The maximum number of primary - results to include in the response. - :param int max_total_results: (optional) The maximum total number of - primary and additional results to include in the response. - :param float confidence_threshold: (optional) The minimum confidence - threshold for included results. Any results with a confidence below this - threshold will be discarded. - :param bool highlight: (optional) Whether to include the most relevant - passages of text in the **highlight** property of each result. - :param bool find_answers: (optional) Whether to use the answer finding - feature to emphasize answers within highlighted passages. This property is - ignored if **highlight**=`false`. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. """ - self.instance_id = instance_id - self.project_id = project_id - self.url = url - self.max_primary_results = max_primary_results - self.max_total_results = max_total_results - self.confidence_threshold = confidence_threshold - self.highlight = highlight - self.find_answers = find_answers - self.authentication = authentication + self.assistant_id = assistant_id + self.status = status + self.status_description = status_description + self.status_errors = status_errors @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': - """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" args = {} - if (instance_id := _dict.get('instance_id')) is not None: - args['instance_id'] = instance_id - else: - raise ValueError( - 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' - ) - if (project_id := _dict.get('project_id')) is not None: - args['project_id'] = project_id - else: - raise ValueError( - 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' - ) - if (url := _dict.get('url')) is not None: - args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in SearchSettingsDiscovery JSON' - ) - if (max_primary_results := - _dict.get('max_primary_results')) is not None: - args['max_primary_results'] = max_primary_results - if (max_total_results := _dict.get('max_total_results')) is not None: - args['max_total_results'] = max_total_results - if (confidence_threshold := - _dict.get('confidence_threshold')) is not None: - args['confidence_threshold'] = confidence_threshold - if (highlight := _dict.get('highlight')) is not None: - args['highlight'] = highlight - if (find_answers := _dict.get('find_answers')) is not None: - args['find_answers'] = find_answers - if (authentication := _dict.get('authentication')) is not None: - args[ - 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( - authentication) - else: - raise ValueError( - 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' - ) + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + """Initialize a SkillsAsyncRequestStatus 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, 'instance_id') and self.instance_id is not None: - _dict['instance_id'] = self.instance_id - if hasattr(self, 'project_id') and self.project_id is not None: - _dict['project_id'] = self.project_id - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr( - self, - 'max_primary_results') and self.max_primary_results is not None: - _dict['max_primary_results'] = self.max_primary_results - if hasattr(self, - 'max_total_results') and self.max_total_results is not None: - _dict['max_total_results'] = self.max_total_results - if hasattr(self, 'confidence_threshold' - ) and self.confidence_threshold is not None: - _dict['confidence_threshold'] = self.confidence_threshold - if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight - if hasattr(self, 'find_answers') and self.find_answers is not None: - _dict['find_answers'] = self.find_answers - if hasattr(self, 'authentication') and self.authentication is not None: - if isinstance(self.authentication, dict): - _dict['authentication'] = self.authentication - else: - _dict['authentication'] = self.authentication.to_dict() + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list return _dict def _to_dict(self): @@ -9353,74 +10166,105 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsDiscovery object.""" + """Return a `str` version of this SkillsAsyncRequestStatus object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsDiscovery') -> bool: + def __eq__(self, other: 'SkillsAsyncRequestStatus') -> 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: 'SearchSettingsDiscovery') -> bool: + def __ne__(self, other: 'SkillsAsyncRequestStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. + """ -class SearchSettingsDiscoveryAuthentication: + AVAILABLE = 'Available' + COMPLETED = 'Completed' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class SkillsExport: """ - Authentication information for the Watson Discovery service. For more information, see - the [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. + SkillsExport. - :param str basic: (optional) The HTTP basic authentication credentials for - Watson Discovery. Specify your Watson Discovery API key in the format - `apikey:{apikey}`. - :param str bearer: (optional) The authentication bearer token for Watson - Discovery. + :param List[Skill] assistant_skills: An array of objects describing the skills + for the assistant. Included in responses only if **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills for + the assistant. Included in responses only if **status**=`Available`. """ def __init__( self, - *, - basic: Optional[str] = None, - bearer: Optional[str] = None, + assistant_skills: List['Skill'], + assistant_state: 'AssistantState', ) -> None: """ - Initialize a SearchSettingsDiscoveryAuthentication object. + Initialize a SkillsExport object. - :param str basic: (optional) The HTTP basic authentication credentials for - Watson Discovery. Specify your Watson Discovery API key in the format - `apikey:{apikey}`. - :param str bearer: (optional) The authentication bearer token for Watson - Discovery. + :param List[Skill] assistant_skills: An array of objects describing the + skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. """ - self.basic = basic - self.bearer = bearer + self.assistant_skills = assistant_skills + self.assistant_state = assistant_state @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': - """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillsExport': + """Initialize a SkillsExport object from a json dictionary.""" args = {} - if (basic := _dict.get('basic')) is not None: - args['basic'] = basic - if (bearer := _dict.get('bearer')) is not None: - args['bearer'] = bearer + if (assistant_skills := _dict.get('assistant_skills')) is not None: + args['assistant_skills'] = [ + Skill.from_dict(v) for v in assistant_skills + ] + else: + raise ValueError( + 'Required property \'assistant_skills\' not present in SkillsExport JSON' + ) + if (assistant_state := _dict.get('assistant_state')) is not None: + args['assistant_state'] = AssistantState.from_dict(assistant_state) + else: + raise ValueError( + 'Required property \'assistant_state\' not present in SkillsExport JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + """Initialize a SkillsExport 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, 'basic') and self.basic is not None: - _dict['basic'] = self.basic - if hasattr(self, 'bearer') and self.bearer is not None: - _dict['bearer'] = self.bearer + if hasattr(self, + 'assistant_skills') and self.assistant_skills is not None: + assistant_skills_list = [] + for v in self.assistant_skills: + if isinstance(v, dict): + assistant_skills_list.append(v) + else: + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, + 'assistant_state') and self.assistant_state is not None: + if isinstance(self.assistant_state, dict): + _dict['assistant_state'] = self.assistant_state + else: + _dict['assistant_state'] = self.assistant_state.to_dict() return _dict def _to_dict(self): @@ -9428,90 +10272,141 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsDiscoveryAuthentication object.""" + """Return a `str` version of this SkillsExport object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: + def __eq__(self, other: 'SkillsExport') -> 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: 'SearchSettingsDiscoveryAuthentication') -> bool: + def __ne__(self, other: 'SkillsExport') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsMessages: +class StatefulMessageResponse: """ - The messages included with responses from the search integration. + A response from the watsonx Assistant service. - :param str success: The message to include in the response to a successful - query. - :param str error: The message to include in the response when the query - encounters an error. - :param str no_result: The message to include in the response when there is no - result from the query. + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. """ def __init__( self, - success: str, - error: str, - no_result: str, + output: 'MessageOutput', + user_id: str, + *, + context: Optional['MessageContext'] = None, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, ) -> None: """ - Initialize a SearchSettingsMessages object. + Initialize a StatefulMessageResponse object. - :param str success: The message to include in the response to a successful - query. - :param str error: The message to include in the response when the query - encounters an error. - :param str no_result: The message to include in the response when there is - no result from the query. + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. """ - self.success = success - self.error = error - self.no_result = no_result + self.output = output + self.context = context + self.user_id = user_id + self.masked_output = masked_output + self.masked_input = masked_input @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': - """Initialize a SearchSettingsMessages object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatefulMessageResponse': + """Initialize a StatefulMessageResponse object from a json dictionary.""" args = {} - if (success := _dict.get('success')) is not None: - args['success'] = success - else: - raise ValueError( - 'Required property \'success\' not present in SearchSettingsMessages JSON' - ) - if (error := _dict.get('error')) is not None: - args['error'] = error + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) else: raise ValueError( - 'Required property \'error\' not present in SearchSettingsMessages JSON' + 'Required property \'output\' not present in StatefulMessageResponse JSON' ) - if (no_result := _dict.get('no_result')) is not None: - args['no_result'] = no_result + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id else: raise ValueError( - 'Required property \'no_result\' not present in SearchSettingsMessages JSON' + 'Required property \'user_id\' not present in StatefulMessageResponse JSON' ) + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsMessages object from a json dictionary.""" + """Initialize a StatefulMessageResponse 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, 'success') and self.success is not None: - _dict['success'] = self.success - if hasattr(self, 'error') and self.error is not None: - _dict['error'] = self.error - if hasattr(self, 'no_result') and self.no_result is not None: - _dict['no_result'] = self.no_result + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() return _dict def _to_dict(self): @@ -9519,91 +10414,87 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsMessages object.""" + """Return a `str` version of this StatefulMessageResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsMessages') -> bool: + def __eq__(self, other: 'StatefulMessageResponse') -> 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: 'SearchSettingsMessages') -> bool: + def __ne__(self, other: 'StatefulMessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsSchemaMapping: +class StatelessMessageContext: """ - The mapping between fields in the Watson Discovery collection and properties in the - search response. + StatelessMessageContext. - :param str url: The field in the collection to map to the **url** property of - the response. - :param str body: The field in the collection to map to the **body** property in - the response. - :param str title: The field in the collection to map to the **title** property - for the schema. + :param StatelessMessageContextGlobal global_: (optional) Session context data + that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ def __init__( self, - url: str, - body: str, - title: str, + *, + global_: Optional['StatelessMessageContextGlobal'] = None, + skills: Optional['StatelessMessageContextSkills'] = None, + integrations: Optional[dict] = None, ) -> None: """ - Initialize a SearchSettingsSchemaMapping object. + Initialize a StatelessMessageContext object. - :param str url: The field in the collection to map to the **url** property - of the response. - :param str body: The field in the collection to map to the **body** - property in the response. - :param str title: The field in the collection to map to the **title** - property for the schema. + :param StatelessMessageContextGlobal global_: (optional) Session context + data that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data + specific to particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - self.url = url - self.body = body - self.title = title + self.global_ = global_ + self.skills = skills + self.integrations = integrations @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': - """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContext': + """Initialize a StatelessMessageContext object from a json dictionary.""" args = {} - if (url := _dict.get('url')) is not None: - args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' - ) - if (body := _dict.get('body')) is not None: - args['body'] = body - else: - raise ValueError( - 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' - ) - if (title := _dict.get('title')) is not None: - args['title'] = title - else: - raise ValueError( - 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' - ) + if (global_ := _dict.get('global')) is not None: + args['global_'] = StatelessMessageContextGlobal.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = StatelessMessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + """Initialize a StatelessMessageContext 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, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations return _dict def _to_dict(self): @@ -9611,75 +10502,70 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsSchemaMapping object.""" + """Return a `str` version of this StatelessMessageContext object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsSchemaMapping') -> bool: + def __eq__(self, other: 'StatelessMessageContext') -> 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: 'SearchSettingsSchemaMapping') -> bool: + def __ne__(self, other: 'StatelessMessageContext') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSkillWarning: +class StatelessMessageContextGlobal: """ - A warning describing an error in the search skill configuration. + Session context data that is shared by all skills used by the assistant. - :param str code: (optional) The error code. - :param str path: (optional) The location of the error in the search skill - configuration object. - :param str message: (optional) The error message. + :param MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. """ def __init__( self, *, - code: Optional[str] = None, - path: Optional[str] = None, - message: Optional[str] = None, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, ) -> None: """ - Initialize a SearchSkillWarning object. + Initialize a StatelessMessageContextGlobal object. - :param str code: (optional) The error code. - :param str path: (optional) The location of the error in the search skill - configuration object. - :param str message: (optional) The error message. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. """ - self.code = code - self.path = path - self.message = message + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': - """Initialize a SearchSkillWarning object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextGlobal': + """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" args = {} - if (code := _dict.get('code')) is not None: - args['code'] = code - if (path := _dict.get('path')) is not None: - args['path'] = path - if (message := _dict.get('message')) is not None: - args['message'] = message + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSkillWarning object from a json dictionary.""" + """Initialize a StatelessMessageContextGlobal 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, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id return _dict def _to_dict(self): @@ -9687,60 +10573,78 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSkillWarning object.""" + """Return a `str` version of this StatelessMessageContextGlobal object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSkillWarning') -> bool: + def __eq__(self, other: 'StatelessMessageContextGlobal') -> 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: 'SearchSkillWarning') -> bool: + def __ne__(self, other: 'StatelessMessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SessionResponse: +class StatelessMessageContextSkills: """ - SessionResponse. + Context data specific to particular skills used by the assistant. - :param str session_id: The session ID. + :param MessageContextDialogSkill main_skill: (optional) Context variables that + are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. """ def __init__( self, - session_id: str, + *, + main_skill: Optional['MessageContextDialogSkill'] = None, + actions_skill: Optional[ + 'StatelessMessageContextSkillsActionsSkill'] = None, ) -> None: """ - Initialize a SessionResponse object. + Initialize a StatelessMessageContextSkills object. - :param str session_id: The session ID. + :param MessageContextDialogSkill main_skill: (optional) Context variables + that are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. """ - self.session_id = session_id + self.main_skill = main_skill + self.actions_skill = actions_skill @classmethod - def from_dict(cls, _dict: Dict) -> 'SessionResponse': - """Initialize a SessionResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextSkills': + """Initialize a StatelessMessageContextSkills object from a json dictionary.""" args = {} - if (session_id := _dict.get('session_id')) is not None: - args['session_id'] = session_id - else: - raise ValueError( - 'Required property \'session_id\' not present in SessionResponse JSON' - ) + if (main_skill := _dict.get('main skill')) is not None: + args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) + if (actions_skill := _dict.get('actions skill')) is not None: + args[ + 'actions_skill'] = StatelessMessageContextSkillsActionsSkill.from_dict( + actions_skill) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SessionResponse object from a json dictionary.""" + """Initialize a StatelessMessageContextSkills 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, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill + else: + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill + else: + _dict['actions skill'] = self.actions_skill.to_dict() return _dict def _to_dict(self): @@ -9748,239 +10652,134 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SessionResponse object.""" + """Return a `str` version of this StatelessMessageContextSkills object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SessionResponse') -> bool: + def __eq__(self, other: 'StatelessMessageContextSkills') -> 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: 'SessionResponse') -> bool: + def __ne__(self, other: 'StatelessMessageContextSkills') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Skill: +class StatelessMessageContextSkillsActionsSkill: """ - Skill. + Context variables that are used by the action skill. - :param str name: (optional) The name of the skill. This string cannot contain - carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This string - cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param str skill_id: (optional) The skill ID of the skill. - :param str status: (optional) The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param dict dialog_settings: (optional) For internal use only. - :param str assistant_id: (optional) The unique identifier of the assistant the - skill is associated with. - :param str workspace_id: (optional) The unique identifier of the workspace that - contains the skill content. Included only for action and dialog skills. - :param str environment_id: (optional) The unique identifier of the environment - where the skill is defined. For action and dialog skills, this is always the - draft environment. - :param bool valid: (optional) Whether the skill is structurally valid. - :param str next_snapshot_version: (optional) The name that will be given to the - next snapshot that is created for the skill. A snapshot of each versionable - skill is saved for each new release of an assistant. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and - are not included in **Export skills** responses. - :param List[SearchSkillWarning] warnings: (optional) An array of warnings - describing errors with the search skill configuration. Included only for search - skills. - :param str language: The language of the skill. - :param str type: The type of skill. + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by + the skill. + :param dict action_variables: (optional) An object containing action variables. + Action variables can be accessed only by steps in the same action, and do not + persist after the action ends. + :param dict skill_variables: (optional) An object containing skill variables. + (In the watsonx Assistant user interface, skill variables are called _session + variables_.) Skill variables can be accessed by any action and persist for the + duration of the session. + :param dict private_action_variables: (optional) An object containing private + action variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. Private variables are + encrypted. + :param dict private_skill_variables: (optional) An object containing private + skill variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action and + persist for the duration of the session. Private variables are encrypted. """ def __init__( self, - language: str, - type: str, *, - name: Optional[str] = None, - description: Optional[str] = None, - workspace: Optional[dict] = None, - skill_id: Optional[str] = None, - status: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, - status_description: Optional[str] = None, - dialog_settings: Optional[dict] = None, - assistant_id: Optional[str] = None, - workspace_id: Optional[str] = None, - environment_id: Optional[str] = None, - valid: Optional[bool] = None, - next_snapshot_version: Optional[str] = None, - search_settings: Optional['SearchSettings'] = None, - warnings: Optional[List['SearchSkillWarning']] = None, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + action_variables: Optional[dict] = None, + skill_variables: Optional[dict] = None, + private_action_variables: Optional[dict] = None, + private_skill_variables: Optional[dict] = None, ) -> None: """ - Initialize a Skill object. + Initialize a StatelessMessageContextSkillsActionsSkill object. - :param str language: The language of the skill. - :param str type: The type of skill. - :param str name: (optional) The name of the skill. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This - string cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param dict dialog_settings: (optional) For internal use only. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, - and are not included in **Export skills** responses. - """ - self.name = name - self.description = description - self.workspace = workspace - self.skill_id = skill_id - self.status = status - self.status_errors = status_errors - self.status_description = status_description - self.dialog_settings = dialog_settings - self.assistant_id = assistant_id - self.workspace_id = workspace_id - self.environment_id = environment_id - self.valid = valid - self.next_snapshot_version = next_snapshot_version - self.search_settings = search_settings - self.warnings = warnings - self.language = language - self.type = type + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + :param dict action_variables: (optional) An object containing action + variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. + :param dict skill_variables: (optional) An object containing skill + variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action + and persist for the duration of the session. + :param dict private_action_variables: (optional) An object containing + private action variables. Action variables can be accessed only by steps in + the same action, and do not persist after the action ends. Private + variables are encrypted. + :param dict private_skill_variables: (optional) An object containing + private skill variables. (In the watsonx Assistant user interface, skill + variables are called _session variables_.) Skill variables can be accessed + by any action and persist for the duration of the session. Private + variables are encrypted. + """ + self.user_defined = user_defined + self.system = system + self.action_variables = action_variables + self.skill_variables = skill_variables + self.private_action_variables = private_action_variables + self.private_skill_variables = private_skill_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'Skill': - """Initialize a Skill object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'StatelessMessageContextSkillsActionsSkill': + """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (workspace := _dict.get('workspace')) is not None: - args['workspace'] = workspace - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (dialog_settings := _dict.get('dialog_settings')) is not None: - args['dialog_settings'] = dialog_settings - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (workspace_id := _dict.get('workspace_id')) is not None: - args['workspace_id'] = workspace_id - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (valid := _dict.get('valid')) is not None: - args['valid'] = valid - if (next_snapshot_version := - _dict.get('next_snapshot_version')) is not None: - args['next_snapshot_version'] = next_snapshot_version - if (search_settings := _dict.get('search_settings')) is not None: - args['search_settings'] = SearchSettings.from_dict(search_settings) - if (warnings := _dict.get('warnings')) is not None: - args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in warnings - ] - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in Skill JSON') - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in Skill JSON') + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables + if (skill_variables := _dict.get('skill_variables')) is not None: + args['skill_variables'] = skill_variables + if (private_action_variables := + _dict.get('private_action_variables')) is not None: + args['private_action_variables'] = private_action_variables + if (private_skill_variables := + _dict.get('private_skill_variables')) is not None: + args['private_skill_variables'] = private_skill_variables return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Skill object from a json dictionary.""" + """Initialize a StatelessMessageContextSkillsActionsSkill 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'workspace') and self.workspace is not None: - _dict['workspace'] = self.workspace - if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: - _dict['skill_id'] = getattr(self, 'skill_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() if hasattr(self, - 'dialog_settings') and self.dialog_settings is not None: - _dict['dialog_settings'] = self.dialog_settings - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'workspace_id') and getattr( - self, 'workspace_id') is not None: - _dict['workspace_id'] = getattr(self, 'workspace_id') - if hasattr(self, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'valid') and getattr(self, 'valid') is not None: - _dict['valid'] = getattr(self, 'valid') - if hasattr(self, 'next_snapshot_version') and getattr( - self, 'next_snapshot_version') is not None: - _dict['next_snapshot_version'] = getattr(self, - 'next_snapshot_version') + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables if hasattr(self, - 'search_settings') and self.search_settings is not None: - if isinstance(self.search_settings, dict): - _dict['search_settings'] = self.search_settings - else: - _dict['search_settings'] = self.search_settings.to_dict() - if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: - warnings_list = [] - for v in getattr(self, 'warnings'): - if isinstance(v, dict): - warnings_list.append(v) - else: - warnings_list.append(v.to_dict()) - _dict['warnings'] = warnings_list - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type + 'skill_variables') and self.skill_variables is not None: + _dict['skill_variables'] = self.skill_variables + if hasattr(self, 'private_action_variables' + ) and self.private_action_variables is not None: + _dict['private_action_variables'] = self.private_action_variables + if hasattr(self, 'private_skill_variables' + ) and self.private_skill_variables is not None: + _dict['private_skill_variables'] = self.private_skill_variables return _dict def _to_dict(self): @@ -9988,267 +10787,177 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Skill object.""" + """Return a `str` version of this StatelessMessageContextSkillsActionsSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Skill') -> bool: + def __eq__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> 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: 'Skill') -> bool: + def __ne__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - """ - - AVAILABLE = 'Available' - FAILED = 'Failed' - NON_EXISTENT = 'Non Existent' - PROCESSING = 'Processing' - TRAINING = 'Training' - UNAVAILABLE = 'Unavailable' - - class TypeEnum(str, Enum): - """ - The type of skill. - """ - - ACTION = 'action' - DIALOG = 'dialog' - SEARCH = 'search' - -class SkillImport: - """ - SkillImport. - - :param str name: (optional) The name of the skill. This string cannot contain - carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This string - cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param str skill_id: (optional) The skill ID of the skill. - :param str status: (optional) The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param dict dialog_settings: (optional) For internal use only. - :param str assistant_id: (optional) The unique identifier of the assistant the - skill is associated with. - :param str workspace_id: (optional) The unique identifier of the workspace that - contains the skill content. Included only for action and dialog skills. - :param str environment_id: (optional) The unique identifier of the environment - where the skill is defined. For action and dialog skills, this is always the - draft environment. - :param bool valid: (optional) Whether the skill is structurally valid. - :param str next_snapshot_version: (optional) The name that will be given to the - next snapshot that is created for the skill. A snapshot of each versionable - skill is saved for each new release of an assistant. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and - are not included in **Export skills** responses. - :param List[SearchSkillWarning] warnings: (optional) An array of warnings - describing errors with the search skill configuration. Included only for search - skills. - :param str language: The language of the skill. - :param str type: The type of skill. +class StatelessMessageInput: """ + An input object that includes the input text. - def __init__( - self, - language: str, - type: str, - *, - name: Optional[str] = None, - description: Optional[str] = None, - workspace: Optional[dict] = None, - skill_id: Optional[str] = None, - status: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, - status_description: Optional[str] = None, - dialog_settings: Optional[dict] = None, - assistant_id: Optional[str] = None, - workspace_id: Optional[str] = None, - environment_id: Optional[str] = None, - valid: Optional[bool] = None, - next_snapshot_version: Optional[str] = None, - search_settings: Optional['SearchSettings'] = None, - warnings: Optional[List['SearchSkillWarning']] = None, + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param StatelessMessageInputOptions options: (optional) Optional properties that + control how the assistant responds. + """ + + def __init__( + self, + *, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['StatelessMessageInputOptions'] = None, ) -> None: """ - Initialize a SkillImport object. + Initialize a StatelessMessageInput object. - :param str language: The language of the skill. - :param str type: The type of skill. - :param str name: (optional) The name of the skill. This string cannot + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This - string cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param dict dialog_settings: (optional) For internal use only. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, - and are not included in **Export skills** responses. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param StatelessMessageInputOptions options: (optional) Optional properties + that control how the assistant responds. """ - self.name = name - self.description = description - self.workspace = workspace - self.skill_id = skill_id - self.status = status - self.status_errors = status_errors - self.status_description = status_description - self.dialog_settings = dialog_settings - self.assistant_id = assistant_id - self.workspace_id = workspace_id - self.environment_id = environment_id - self.valid = valid - self.next_snapshot_version = next_snapshot_version - self.search_settings = search_settings - self.warnings = warnings - self.language = language - self.type = type + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillImport': - """Initialize a SkillImport object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInput': + """Initialize a StatelessMessageInput object from a json dictionary.""" args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (workspace := _dict.get('workspace')) is not None: - args['workspace'] = workspace - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (dialog_settings := _dict.get('dialog_settings')) is not None: - args['dialog_settings'] = dialog_settings - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (workspace_id := _dict.get('workspace_id')) is not None: - args['workspace_id'] = workspace_id - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (valid := _dict.get('valid')) is not None: - args['valid'] = valid - if (next_snapshot_version := - _dict.get('next_snapshot_version')) is not None: - args['next_snapshot_version'] = next_snapshot_version - if (search_settings := _dict.get('search_settings')) is not None: - args['search_settings'] = SearchSettings.from_dict(search_settings) - if (warnings := _dict.get('warnings')) is not None: - args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in warnings + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments ] - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in SkillImport JSON' - ) - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in SkillImport JSON') + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = StatelessMessageInputOptions.from_dict(options) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillImport object from a json dictionary.""" + """Initialize a StatelessMessageInput 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'workspace') and self.workspace is not None: - _dict['workspace'] = self.workspace - if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: - _dict['skill_id'] = getattr(self, 'skill_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: if isinstance(v, dict): - status_errors_list.append(v) + intents_list.append(v) else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, - 'dialog_settings') and self.dialog_settings is not None: - _dict['dialog_settings'] = self.dialog_settings - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'workspace_id') and getattr( - self, 'workspace_id') is not None: - _dict['workspace_id'] = getattr(self, 'workspace_id') - if hasattr(self, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'valid') and getattr(self, 'valid') is not None: - _dict['valid'] = getattr(self, 'valid') - if hasattr(self, 'next_snapshot_version') and getattr( - self, 'next_snapshot_version') is not None: - _dict['next_snapshot_version'] = getattr(self, - 'next_snapshot_version') - if hasattr(self, - 'search_settings') and self.search_settings is not None: - if isinstance(self.search_settings, dict): - _dict['search_settings'] = self.search_settings - else: - _dict['search_settings'] = self.search_settings.to_dict() - if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: - warnings_list = [] - for v in getattr(self, 'warnings'): + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: if isinstance(v, dict): - warnings_list.append(v) + entities_list.append(v) else: - warnings_list.append(v.to_dict()) - _dict['warnings'] = warnings_list - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -10256,122 +10965,133 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillImport object.""" + """Return a `str` version of this StatelessMessageInput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillImport') -> bool: + def __eq__(self, other: 'StatelessMessageInput') -> 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: 'SkillImport') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - """ - - AVAILABLE = 'Available' - FAILED = 'Failed' - NON_EXISTENT = 'Non Existent' - PROCESSING = 'Processing' - TRAINING = 'Training' - UNAVAILABLE = 'Unavailable' + return self.__dict__ == other.__dict__ - class TypeEnum(str, Enum): + def __ne__(self, other: 'StatelessMessageInput') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageTypeEnum(str, Enum): """ - The type of skill. + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. """ - ACTION = 'action' - DIALOG = 'dialog' + TEXT = 'text' + SEARCH = 'search' -class SkillsAsyncRequestStatus: +class StatelessMessageInputOptions: """ - SkillsAsyncRequestStatus. + Optional properties that control how the assistant responds. - :param str assistant_id: (optional) The assistant ID of the assistant. - :param str status: (optional) The current status of the asynchronous operation: - - `Available`: An asynchronous export is available. - - `Completed`: An asynchronous import operation has completed successfully. - - `Failed`: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - `Processing`: An asynchronous operation has not yet completed. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. + :param bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the initial + message response signals to the client that the operation may be long running. + With synchronous execution the custom extension is executed and returns the + response in a single message turn. **Note:** **async_callout** defaults to true + for API versions earlier than 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ def __init__( self, *, - assistant_id: Optional[str] = None, - status: Optional[str] = None, - status_description: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, + restart: Optional[bool] = None, + alternate_intents: Optional[bool] = None, + async_callout: Optional[bool] = None, + spelling: Optional['MessageInputOptionsSpelling'] = None, + debug: Optional[bool] = None, ) -> None: """ - Initialize a SkillsAsyncRequestStatus object. + Initialize a StatelessMessageInputOptions object. + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the + initial message response signals to the client that the operation may be + long running. With synchronous execution the custom extension is executed + and returns the response in a single message turn. **Note:** + **async_callout** defaults to true for API versions earlier than + 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ - self.assistant_id = assistant_id - self.status = status - self.status_description = status_description - self.status_errors = status_errors + self.restart = restart + self.alternate_intents = alternate_intents + self.async_callout = async_callout + self.spelling = spelling + self.debug = debug @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': - """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInputOptions': + """Initialize a StatelessMessageInputOptions object from a json dictionary.""" args = {} - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] + if (restart := _dict.get('restart')) is not None: + args['restart'] = restart + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (async_callout := _dict.get('async_callout')) is not None: + args['async_callout'] = async_callout + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (debug := _dict.get('debug')) is not None: + args['debug'] = debug return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + """Initialize a StatelessMessageInputOptions 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, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'async_callout') and self.async_callout is not None: + _dict['async_callout'] = self.async_callout + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug return _dict def _to_dict(self): @@ -10379,105 +11099,137 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillsAsyncRequestStatus object.""" + """Return a `str` version of this StatelessMessageInputOptions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillsAsyncRequestStatus') -> bool: + def __eq__(self, other: 'StatelessMessageInputOptions') -> 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: 'SkillsAsyncRequestStatus') -> bool: + def __ne__(self, other: 'StatelessMessageInputOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the asynchronous operation: - - `Available`: An asynchronous export is available. - - `Completed`: An asynchronous import operation has completed successfully. - - `Failed`: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - `Processing`: An asynchronous operation has not yet completed. - """ - - AVAILABLE = 'Available' - COMPLETED = 'Completed' - FAILED = 'Failed' - PROCESSING = 'Processing' - -class SkillsExport: +class StatelessMessageResponse: """ - SkillsExport. + A stateless response from the watsonx Assistant service. - :param List[Skill] assistant_skills: An array of objects describing the skills - for the assistant. Included in responses only if **status**=`Available`. - :param AssistantState assistant_state: Status information about the skills for - the assistant. Included in responses only if **status**=`Available`. + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param StatelessMessageContext context: Context data for the conversation. You + can use this property to access context variables. The context is not stored by + the assistant; to maintain session state, include the context from the response + in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ def __init__( self, - assistant_skills: List['Skill'], - assistant_state: 'AssistantState', + output: 'MessageOutput', + context: 'StatelessMessageContext', + *, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, + user_id: Optional[str] = None, ) -> None: """ - Initialize a SkillsExport object. + Initialize a StatelessMessageResponse object. - :param List[Skill] assistant_skills: An array of objects describing the - skills for the assistant. Included in responses only if - **status**=`Available`. - :param AssistantState assistant_state: Status information about the skills - for the assistant. Included in responses only if **status**=`Available`. + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param StatelessMessageContext context: Context data for the conversation. + You can use this property to access context variables. The context is not + stored by the assistant; to maintain session state, include the context + from the response in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. """ - self.assistant_skills = assistant_skills - self.assistant_state = assistant_state + self.output = output + self.context = context + self.masked_output = masked_output + self.masked_input = masked_input + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillsExport': - """Initialize a SkillsExport object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageResponse': + """Initialize a StatelessMessageResponse object from a json dictionary.""" args = {} - if (assistant_skills := _dict.get('assistant_skills')) is not None: - args['assistant_skills'] = [ - Skill.from_dict(v) for v in assistant_skills - ] + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) else: raise ValueError( - 'Required property \'assistant_skills\' not present in SkillsExport JSON' + 'Required property \'output\' not present in StatelessMessageResponse JSON' ) - if (assistant_state := _dict.get('assistant_state')) is not None: - args['assistant_state'] = AssistantState.from_dict(assistant_state) + if (context := _dict.get('context')) is not None: + args['context'] = StatelessMessageContext.from_dict(context) else: raise ValueError( - 'Required property \'assistant_state\' not present in SkillsExport JSON' + 'Required property \'context\' not present in StatelessMessageResponse JSON' ) + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillsExport object from a json dictionary.""" + """Initialize a StatelessMessageResponse 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, - 'assistant_skills') and self.assistant_skills is not None: - assistant_skills_list = [] - for v in self.assistant_skills: - if isinstance(v, dict): - assistant_skills_list.append(v) - else: - assistant_skills_list.append(v.to_dict()) - _dict['assistant_skills'] = assistant_skills_list - if hasattr(self, - 'assistant_state') and self.assistant_state is not None: - if isinstance(self.assistant_state, dict): - _dict['assistant_state'] = self.assistant_state + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output else: - _dict['assistant_state'] = self.assistant_state.to_dict() + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -10485,16 +11237,16 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillsExport object.""" + """Return a `str` version of this StatelessMessageResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillsExport') -> bool: + def __eq__(self, other: 'StatelessMessageResponse') -> 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: 'SkillsExport') -> bool: + def __ne__(self, other: 'StatelessMessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 0e6681be4..181ca3b5e 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -632,7 +632,7 @@ def test_message_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' responses.add( responses.POST, url, @@ -722,6 +722,7 @@ def test_message_all_params(self): message_input_options_model = {} message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False @@ -758,22 +759,22 @@ def test_message_all_params(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - # Construct a dict representation of a MessageContextSkillDialog model - message_context_skill_dialog_model = {} - message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - # Construct a dict representation of a MessageContextSkillAction model - message_context_skill_action_model = {} - message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} + # Construct a dict representation of a MessageContextActionSkill model + message_context_action_skill_model = {} + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} # Construct a dict representation of a MessageContextSkills model message_context_skills_model = {} - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model # Construct a dict representation of a MessageContext model message_context_model = {} @@ -823,7 +824,7 @@ def test_message_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' responses.add( responses.POST, url, @@ -863,7 +864,7 @@ def test_message_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' responses.add( responses.POST, url, @@ -908,7 +909,7 @@ def test_message_stateless_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' responses.add( responses.POST, url, @@ -994,23 +995,24 @@ def test_message_stateless_all_params(self): message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - # Construct a dict representation of a MessageInputOptionsStateless model - message_input_options_stateless_model = {} - message_input_options_stateless_model['restart'] = False - message_input_options_stateless_model['alternate_intents'] = False - message_input_options_stateless_model['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model['debug'] = False - - # Construct a dict representation of a MessageInputStateless model - message_input_stateless_model = {} - message_input_stateless_model['message_type'] = 'text' - message_input_stateless_model['text'] = 'testString' - message_input_stateless_model['intents'] = [runtime_intent_model] - message_input_stateless_model['entities'] = [runtime_entity_model] - message_input_stateless_model['suggestion_id'] = 'testString' - message_input_stateless_model['attachments'] = [message_input_attachment_model] - message_input_stateless_model['analytics'] = request_analytics_model - message_input_stateless_model['options'] = message_input_options_stateless_model + # Construct a dict representation of a StatelessMessageInputOptions model + stateless_message_input_options_model = {} + stateless_message_input_options_model['restart'] = False + stateless_message_input_options_model['alternate_intents'] = False + stateless_message_input_options_model['async_callout'] = False + stateless_message_input_options_model['spelling'] = message_input_options_spelling_model + stateless_message_input_options_model['debug'] = False + + # Construct a dict representation of a StatelessMessageInput model + stateless_message_input_model = {} + stateless_message_input_model['message_type'] = 'text' + stateless_message_input_model['text'] = 'testString' + stateless_message_input_model['intents'] = [runtime_intent_model] + stateless_message_input_model['entities'] = [runtime_entity_model] + stateless_message_input_model['suggestion_id'] = 'testString' + stateless_message_input_model['attachments'] = [message_input_attachment_model] + stateless_message_input_model['analytics'] = request_analytics_model + stateless_message_input_model['options'] = stateless_message_input_options_model # Construct a dict representation of a MessageContextGlobalSystem model message_context_global_system_model = {} @@ -1023,43 +1025,45 @@ def test_message_stateless_all_params(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - # Construct a dict representation of a MessageContextGlobalStateless model - message_context_global_stateless_model = {} - message_context_global_stateless_model['system'] = message_context_global_system_model - message_context_global_stateless_model['session_id'] = 'testString' + # Construct a dict representation of a StatelessMessageContextGlobal model + stateless_message_context_global_model = {} + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' # Construct a dict representation of a MessageContextSkillSystem model message_context_skill_system_model = {} message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - # Construct a dict representation of a MessageContextSkillDialog model - message_context_skill_dialog_model = {} - message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model - - # Construct a dict representation of a MessageContextSkillAction model - message_context_skill_action_model = {} - message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} - - # Construct a dict representation of a MessageContextSkills model - message_context_skills_model = {} - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model - - # Construct a dict representation of a MessageContextStateless model - message_context_stateless_model = {} - message_context_stateless_model['global'] = message_context_global_stateless_model - message_context_stateless_model['skills'] = message_context_skills_model - message_context_stateless_model['integrations'] = {'anyKey': 'anyValue'} + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a StatelessMessageContextSkillsActionsSkill model + stateless_message_context_skills_actions_skill_model = {} + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a StatelessMessageContextSkills model + stateless_message_context_skills_model = {} + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model + + # Construct a dict representation of a StatelessMessageContext model + stateless_message_context_model = {} + stateless_message_context_model['global'] = stateless_message_context_global_model + stateless_message_context_model['skills'] = stateless_message_context_skills_model + stateless_message_context_model['integrations'] = {'anyKey': 'anyValue'} # Set up parameter values assistant_id = 'testString' - input = message_input_stateless_model - context = message_context_stateless_model + input = stateless_message_input_model + context = stateless_message_context_model user_id = 'testString' # Invoke method @@ -1076,8 +1080,8 @@ def test_message_stateless_all_params(self): assert response.status_code == 200 # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['input'] == message_input_stateless_model - assert req_body['context'] == message_context_stateless_model + assert req_body['input'] == stateless_message_input_model + assert req_body['context'] == stateless_message_context_model assert req_body['user_id'] == 'testString' def test_message_stateless_all_params_with_retries(self): @@ -1096,7 +1100,7 @@ def test_message_stateless_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' responses.add( responses.POST, url, @@ -1134,7 +1138,7 @@ def test_message_stateless_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' responses.add( responses.POST, url, @@ -1295,7 +1299,7 @@ def test_list_logs_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -1348,7 +1352,7 @@ def test_list_logs_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -1386,7 +1390,7 @@ def test_list_logs_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -1807,6 +1811,10 @@ def test_update_environment_all_params(self): status=200, ) + # Construct a dict representation of a BaseEnvironmentOrchestration model + base_environment_orchestration_model = {} + base_environment_orchestration_model['search_skill_fallback'] = True + # Construct a dict representation of a EnvironmentSkill model environment_skill_model = {} environment_skill_model['skill_id'] = 'testString' @@ -1820,6 +1828,7 @@ def test_update_environment_all_params(self): environment_id = 'testString' name = 'testString' description = 'testString' + orchestration = base_environment_orchestration_model session_timeout = 10 skill_references = [environment_skill_model] @@ -1829,6 +1838,7 @@ def test_update_environment_all_params(self): environment_id, name=name, description=description, + orchestration=orchestration, session_timeout=session_timeout, skill_references=skill_references, headers={}, @@ -1841,6 +1851,7 @@ def test_update_environment_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' + assert req_body['orchestration'] == base_environment_orchestration_model assert req_body['session_timeout'] == 10 assert req_body['skill_references'] == [environment_skill_model] @@ -4111,6 +4122,7 @@ def test_dialog_node_output_options_element_serialization(self): message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False @@ -4233,6 +4245,7 @@ def test_dialog_node_output_options_element_value_serialization(self): message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False @@ -4383,6 +4396,7 @@ def test_dialog_suggestion_serialization(self): message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False @@ -4506,6 +4520,7 @@ def test_dialog_suggestion_value_serialization(self): message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False @@ -4553,6 +4568,9 @@ def test_environment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + base_environment_orchestration_model = {} # BaseEnvironmentOrchestration + base_environment_orchestration_model['search_skill_fallback'] = True + environment_skill_model = {} # EnvironmentSkill environment_skill_model['skill_id'] = 'testString' environment_skill_model['type'] = 'dialog' @@ -4564,6 +4582,7 @@ def test_environment_serialization(self): environment_model_json = {} environment_model_json['name'] = 'testString' environment_model_json['description'] = 'testString' + environment_model_json['orchestration'] = base_environment_orchestration_model environment_model_json['session_timeout'] = 10 environment_model_json['skill_references'] = [environment_skill_model] @@ -4595,6 +4614,9 @@ def test_environment_collection_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + base_environment_orchestration_model = {} # BaseEnvironmentOrchestration + base_environment_orchestration_model['search_skill_fallback'] = True + environment_skill_model = {} # EnvironmentSkill environment_skill_model['skill_id'] = 'testString' environment_skill_model['type'] = 'dialog' @@ -4605,6 +4627,7 @@ def test_environment_collection_serialization(self): environment_model = {} # Environment environment_model['name'] = 'testString' environment_model['description'] = 'testString' + environment_model['orchestration'] = base_environment_orchestration_model environment_model['session_timeout'] = 10 environment_model['skill_references'] = [environment_skill_model] @@ -4815,20 +4838,21 @@ def test_log_serialization(self): message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'testString' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' @@ -4847,29 +4871,29 @@ def test_log_serialization(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = message_context_skills_model message_context_model['integrations'] = {'anyKey': 'anyValue'} - message_request_model = {} # MessageRequest - message_request_model['input'] = message_input_model - message_request_model['context'] = message_context_model - message_request_model['user_id'] = 'testString' + log_request_model = {} # LogRequest + log_request_model['input'] = log_request_input_model + log_request_model['context'] = message_context_model + log_request_model['user_id'] = 'testString' response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' @@ -4927,25 +4951,25 @@ def test_log_serialization(self): message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'anyKey': 'anyValue'} - message_output_model['spelling'] = message_output_spelling_model + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model - message_response_model = {} # MessageResponse - message_response_model['output'] = message_output_model - message_response_model['context'] = message_context_model - message_response_model['user_id'] = 'testString' + log_response_model = {} # LogResponse + log_response_model['output'] = log_response_output_model + log_response_model['context'] = message_context_model + log_response_model['user_id'] = 'testString' # Construct a json representation of a Log model log_model_json = {} log_model_json['log_id'] = 'testString' - log_model_json['request'] = message_request_model - log_model_json['response'] = message_response_model + log_model_json['request'] = log_request_model + log_model_json['response'] = log_response_model log_model_json['assistant_id'] = 'testString' log_model_json['session_id'] = 'testString' log_model_json['skill_id'] = 'testString' @@ -5054,20 +5078,21 @@ def test_log_collection_serialization(self): message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'testString' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' @@ -5086,29 +5111,29 @@ def test_log_collection_serialization(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model message_context_model = {} # MessageContext message_context_model['global'] = message_context_global_model message_context_model['skills'] = message_context_skills_model message_context_model['integrations'] = {'anyKey': 'anyValue'} - message_request_model = {} # MessageRequest - message_request_model['input'] = message_input_model - message_request_model['context'] = message_context_model - message_request_model['user_id'] = 'testString' + log_request_model = {} # LogRequest + log_request_model['input'] = log_request_input_model + log_request_model['context'] = message_context_model + log_request_model['user_id'] = 'testString' response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' @@ -5166,24 +5191,24 @@ def test_log_collection_serialization(self): message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'anyKey': 'anyValue'} - message_output_model['spelling'] = message_output_spelling_model + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model - message_response_model = {} # MessageResponse - message_response_model['output'] = message_output_model - message_response_model['context'] = message_context_model - message_response_model['user_id'] = 'testString' + log_response_model = {} # LogResponse + log_response_model['output'] = log_response_output_model + log_response_model['context'] = message_context_model + log_response_model['user_id'] = 'testString' log_model = {} # Log log_model['log_id'] = 'testString' - log_model['request'] = message_request_model - log_model['response'] = message_response_model + log_model['request'] = log_request_model + log_model['response'] = log_response_model log_model['assistant_id'] = 'testString' log_model['session_id'] = 'testString' log_model['skill_id'] = 'testString' @@ -5251,21 +5276,108 @@ def test_log_pagination_serialization(self): assert log_pagination_model_json2 == log_pagination_model_json -class TestModel_MessageContext: +class TestModel_LogRequest: """ - Test Class for MessageContext + Test Class for LogRequest """ - def test_message_context_serialization(self): + def test_log_request_serialization(self): """ - Test serialization/deserialization for MessageContext + Test serialization/deserialization for LogRequest """ # Construct dict forms of any model objects needed in order to build this model. + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True + + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'Hello' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model + message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['user_id'] = 'my_user_id' message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' @@ -5280,339 +5392,294 @@ def test_message_context_serialization(self): message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - # Construct a json representation of a MessageContext model - message_context_model_json = {} - message_context_model_json['global'] = message_context_global_model - message_context_model_json['skills'] = message_context_skills_model - message_context_model_json['integrations'] = {'anyKey': 'anyValue'} + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model = MessageContext.from_dict(message_context_model_json) - assert message_context_model != False + # Construct a json representation of a LogRequest model + log_request_model_json = {} + log_request_model_json['input'] = log_request_input_model + log_request_model_json['context'] = message_context_model + log_request_model_json['user_id'] = 'testString' - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ - message_context_model2 = MessageContext(**message_context_model_dict) + # Construct a model instance of LogRequest by calling from_dict on the json representation + log_request_model = LogRequest.from_dict(log_request_model_json) + assert log_request_model != False + + # Construct a model instance of LogRequest by calling from_dict on the json representation + log_request_model_dict = LogRequest.from_dict(log_request_model_json).__dict__ + log_request_model2 = LogRequest(**log_request_model_dict) # Verify the model instances are equivalent - assert message_context_model == message_context_model2 + assert log_request_model == log_request_model2 # Convert model instance back to dict and verify no loss of data - message_context_model_json2 = message_context_model.to_dict() - assert message_context_model_json2 == message_context_model_json + log_request_model_json2 = log_request_model.to_dict() + assert log_request_model_json2 == log_request_model_json -class TestModel_MessageContextGlobal: +class TestModel_LogRequestInput: """ - Test Class for MessageContextGlobal + Test Class for LogRequestInput """ - def test_message_context_global_serialization(self): + def test_log_request_input_serialization(self): """ - Test serialization/deserialization for MessageContextGlobal + Test serialization/deserialization for LogRequestInput """ # Construct dict forms of any model objects needed in order to build this model. - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - - # Construct a json representation of a MessageContextGlobal model - message_context_global_model_json = {} - message_context_global_model_json['system'] = message_context_global_system_model - - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) - assert message_context_global_model != False - - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ - message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' - # Verify the model instances are equivalent - assert message_context_global_model == message_context_global_model2 + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] - # Convert model instance back to dict and verify no loss of data - message_context_global_model_json2 = message_context_global_model.to_dict() - assert message_context_global_model_json2 == message_context_global_model_json + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 -class TestModel_MessageContextGlobalStateless: - """ - Test Class for MessageContextGlobalStateless - """ + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' - def test_message_context_global_stateless_serialization(self): - """ - Test serialization/deserialization for MessageContextGlobalStateless - """ + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - # Construct dict forms of any model objects needed in order to build this model. + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' - # Construct a json representation of a MessageContextGlobalStateless model - message_context_global_stateless_model_json = {} - message_context_global_stateless_model_json['system'] = message_context_global_system_model - message_context_global_stateless_model_json['session_id'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - # Construct a model instance of MessageContextGlobalStateless by calling from_dict on the json representation - message_context_global_stateless_model = MessageContextGlobalStateless.from_dict(message_context_global_stateless_model_json) - assert message_context_global_stateless_model != False + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False - # Construct a model instance of MessageContextGlobalStateless by calling from_dict on the json representation - message_context_global_stateless_model_dict = MessageContextGlobalStateless.from_dict(message_context_global_stateless_model_json).__dict__ - message_context_global_stateless_model2 = MessageContextGlobalStateless(**message_context_global_stateless_model_dict) + # Construct a json representation of a LogRequestInput model + log_request_input_model_json = {} + log_request_input_model_json['message_type'] = 'text' + log_request_input_model_json['text'] = 'testString' + log_request_input_model_json['intents'] = [runtime_intent_model] + log_request_input_model_json['entities'] = [runtime_entity_model] + log_request_input_model_json['suggestion_id'] = 'testString' + log_request_input_model_json['attachments'] = [message_input_attachment_model] + log_request_input_model_json['analytics'] = request_analytics_model + log_request_input_model_json['options'] = message_input_options_model + + # Construct a model instance of LogRequestInput by calling from_dict on the json representation + log_request_input_model = LogRequestInput.from_dict(log_request_input_model_json) + assert log_request_input_model != False + + # Construct a model instance of LogRequestInput by calling from_dict on the json representation + log_request_input_model_dict = LogRequestInput.from_dict(log_request_input_model_json).__dict__ + log_request_input_model2 = LogRequestInput(**log_request_input_model_dict) # Verify the model instances are equivalent - assert message_context_global_stateless_model == message_context_global_stateless_model2 + assert log_request_input_model == log_request_input_model2 # Convert model instance back to dict and verify no loss of data - message_context_global_stateless_model_json2 = message_context_global_stateless_model.to_dict() - assert message_context_global_stateless_model_json2 == message_context_global_stateless_model_json + log_request_input_model_json2 = log_request_input_model.to_dict() + assert log_request_input_model_json2 == log_request_input_model_json -class TestModel_MessageContextGlobalSystem: +class TestModel_LogResponse: """ - Test Class for MessageContextGlobalSystem + Test Class for LogResponse """ - def test_message_context_global_system_serialization(self): - """ - Test serialization/deserialization for MessageContextGlobalSystem - """ - - # Construct a json representation of a MessageContextGlobalSystem model - message_context_global_system_model_json = {} - message_context_global_system_model_json['timezone'] = 'testString' - message_context_global_system_model_json['user_id'] = 'testString' - message_context_global_system_model_json['turn_count'] = 38 - message_context_global_system_model_json['locale'] = 'en-us' - message_context_global_system_model_json['reference_time'] = 'testString' - message_context_global_system_model_json['session_start_time'] = 'testString' - message_context_global_system_model_json['state'] = 'testString' - message_context_global_system_model_json['skip_user_input'] = True - - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) - assert message_context_global_system_model != False - - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ - message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) - - # Verify the model instances are equivalent - assert message_context_global_system_model == message_context_global_system_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_global_system_model_json2 = message_context_global_system_model.to_dict() - assert message_context_global_system_model_json2 == message_context_global_system_model_json - - -class TestModel_MessageContextSkillAction: - """ - Test Class for MessageContextSkillAction - """ - - def test_message_context_skill_action_serialization(self): - """ - Test serialization/deserialization for MessageContextSkillAction - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - # Construct a json representation of a MessageContextSkillAction model - message_context_skill_action_model_json = {} - message_context_skill_action_model_json['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_action_model_json['system'] = message_context_skill_system_model - message_context_skill_action_model_json['action_variables'] = {'anyKey': 'anyValue'} - message_context_skill_action_model_json['skill_variables'] = {'anyKey': 'anyValue'} - - # Construct a model instance of MessageContextSkillAction by calling from_dict on the json representation - message_context_skill_action_model = MessageContextSkillAction.from_dict(message_context_skill_action_model_json) - assert message_context_skill_action_model != False - - # Construct a model instance of MessageContextSkillAction by calling from_dict on the json representation - message_context_skill_action_model_dict = MessageContextSkillAction.from_dict(message_context_skill_action_model_json).__dict__ - message_context_skill_action_model2 = MessageContextSkillAction(**message_context_skill_action_model_dict) - - # Verify the model instances are equivalent - assert message_context_skill_action_model == message_context_skill_action_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_skill_action_model_json2 = message_context_skill_action_model.to_dict() - assert message_context_skill_action_model_json2 == message_context_skill_action_model_json - - -class TestModel_MessageContextSkillDialog: - """ - Test Class for MessageContextSkillDialog - """ - - def test_message_context_skill_dialog_serialization(self): + def test_log_response_serialization(self): """ - Test serialization/deserialization for MessageContextSkillDialog + Test serialization/deserialization for LogResponse """ # Construct dict forms of any model objects needed in order to build this model. - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - # Construct a json representation of a MessageContextSkillDialog model - message_context_skill_dialog_model_json = {} - message_context_skill_dialog_model_json['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_dialog_model_json['system'] = message_context_skill_system_model - - # Construct a model instance of MessageContextSkillDialog by calling from_dict on the json representation - message_context_skill_dialog_model = MessageContextSkillDialog.from_dict(message_context_skill_dialog_model_json) - assert message_context_skill_dialog_model != False - - # Construct a model instance of MessageContextSkillDialog by calling from_dict on the json representation - message_context_skill_dialog_model_dict = MessageContextSkillDialog.from_dict(message_context_skill_dialog_model_json).__dict__ - message_context_skill_dialog_model2 = MessageContextSkillDialog(**message_context_skill_dialog_model_dict) - - # Verify the model instances are equivalent - assert message_context_skill_dialog_model == message_context_skill_dialog_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_skill_dialog_model_json2 = message_context_skill_dialog_model.to_dict() - assert message_context_skill_dialog_model_json2 == message_context_skill_dialog_model_json - - -class TestModel_MessageContextSkillSystem: - """ - Test Class for MessageContextSkillSystem - """ - - def test_message_context_skill_system_serialization(self): - """ - Test serialization/deserialization for MessageContextSkillSystem - """ - - # Construct a json representation of a MessageContextSkillSystem model - message_context_skill_system_model_json = {} - message_context_skill_system_model_json['state'] = 'testString' - message_context_skill_system_model_json['foo'] = 'testString' - - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) - assert message_context_skill_system_model != False - - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ - message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) - - # Verify the model instances are equivalent - assert message_context_skill_system_model == message_context_skill_system_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() - assert message_context_skill_system_model_json2 == message_context_skill_system_model_json - - # Test get_properties and set_properties methods. - message_context_skill_system_model.set_properties({}) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict == {} - - expected_dict = {'foo': 'testString'} - message_context_skill_system_model.set_properties(expected_dict) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict == expected_dict + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] -class TestModel_MessageContextSkills: - """ - Test Class for MessageContextSkills - """ + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' - def test_message_context_skills_serialization(self): - """ - Test serialization/deserialization for MessageContextSkills - """ + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] - # Construct dict forms of any model objects needed in order to build this model. + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - # Construct a json representation of a MessageContextSkills model - message_context_skills_model_json = {} - message_context_skills_model_json['main skill'] = message_context_skill_dialog_model - message_context_skills_model_json['actions skill'] = message_context_skill_action_model + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' - # Construct a model instance of MessageContextSkills by calling from_dict on the json representation - message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) - assert message_context_skills_model != False + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - # Construct a model instance of MessageContextSkills by calling from_dict on the json representation - message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ - message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' - # Verify the model instances are equivalent - assert message_context_skills_model == message_context_skills_model2 + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model - # Convert model instance back to dict and verify no loss of data - message_context_skills_model_json2 = message_context_skills_model.to_dict() - assert message_context_skills_model_json2 == message_context_skills_model_json + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' -class TestModel_MessageContextStateless: - """ - Test Class for MessageContextStateless - """ + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - def test_message_context_stateless_serialization(self): - """ - Test serialization/deserialization for MessageContextStateless - """ + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' - # Construct dict forms of any model objects needed in order to build this model. + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' @@ -5624,62 +5691,74 @@ def test_message_context_stateless_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_stateless_model = {} # MessageContextGlobalStateless - message_context_global_stateless_model['system'] = message_context_global_system_model - message_context_global_stateless_model['session_id'] = 'testString' + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' message_context_skill_system_model['foo'] = 'testString' - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} - # Construct a json representation of a MessageContextStateless model - message_context_stateless_model_json = {} - message_context_stateless_model_json['global'] = message_context_global_stateless_model - message_context_stateless_model_json['skills'] = message_context_skills_model - message_context_stateless_model_json['integrations'] = {'anyKey': 'anyValue'} + # Construct a json representation of a LogResponse model + log_response_model_json = {} + log_response_model_json['output'] = log_response_output_model + log_response_model_json['context'] = message_context_model + log_response_model_json['user_id'] = 'testString' - # Construct a model instance of MessageContextStateless by calling from_dict on the json representation - message_context_stateless_model = MessageContextStateless.from_dict(message_context_stateless_model_json) - assert message_context_stateless_model != False + # Construct a model instance of LogResponse by calling from_dict on the json representation + log_response_model = LogResponse.from_dict(log_response_model_json) + assert log_response_model != False - # Construct a model instance of MessageContextStateless by calling from_dict on the json representation - message_context_stateless_model_dict = MessageContextStateless.from_dict(message_context_stateless_model_json).__dict__ - message_context_stateless_model2 = MessageContextStateless(**message_context_stateless_model_dict) + # Construct a model instance of LogResponse by calling from_dict on the json representation + log_response_model_dict = LogResponse.from_dict(log_response_model_json).__dict__ + log_response_model2 = LogResponse(**log_response_model_dict) # Verify the model instances are equivalent - assert message_context_stateless_model == message_context_stateless_model2 + assert log_response_model == log_response_model2 # Convert model instance back to dict and verify no loss of data - message_context_stateless_model_json2 = message_context_stateless_model.to_dict() - assert message_context_stateless_model_json2 == message_context_stateless_model_json + log_response_model_json2 = log_response_model.to_dict() + assert log_response_model_json2 == log_response_model_json -class TestModel_MessageInput: +class TestModel_LogResponseOutput: """ - Test Class for MessageInput + Test Class for LogResponseOutput """ - def test_message_input_serialization(self): + def test_log_response_output_serialization(self): """ - Test serialization/deserialization for MessageInput + Test serialization/deserialization for LogResponseOutput """ # Construct dict forms of any model objects needed in order to build this model. + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 @@ -5735,233 +5814,425 @@ def test_message_input_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' - - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' - # Construct a json representation of a MessageInput model - message_input_model_json = {} - message_input_model_json['message_type'] = 'text' - message_input_model_json['text'] = 'testString' - message_input_model_json['intents'] = [runtime_intent_model] - message_input_model_json['entities'] = [runtime_entity_model] - message_input_model_json['suggestion_id'] = 'testString' - message_input_model_json['attachments'] = [message_input_attachment_model] - message_input_model_json['analytics'] = request_analytics_model - message_input_model_json['options'] = message_input_options_model + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model = MessageInput.from_dict(message_input_model_json) - assert message_input_model != False + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ - message_input_model2 = MessageInput(**message_input_model_dict) + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + # Construct a json representation of a LogResponseOutput model + log_response_output_model_json = {} + log_response_output_model_json['generic'] = [runtime_response_generic_model] + log_response_output_model_json['intents'] = [runtime_intent_model] + log_response_output_model_json['entities'] = [runtime_entity_model] + log_response_output_model_json['actions'] = [dialog_node_action_model] + log_response_output_model_json['debug'] = message_output_debug_model + log_response_output_model_json['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model_json['spelling'] = message_output_spelling_model + + # Construct a model instance of LogResponseOutput by calling from_dict on the json representation + log_response_output_model = LogResponseOutput.from_dict(log_response_output_model_json) + assert log_response_output_model != False + + # Construct a model instance of LogResponseOutput by calling from_dict on the json representation + log_response_output_model_dict = LogResponseOutput.from_dict(log_response_output_model_json).__dict__ + log_response_output_model2 = LogResponseOutput(**log_response_output_model_dict) # Verify the model instances are equivalent - assert message_input_model == message_input_model2 + assert log_response_output_model == log_response_output_model2 # Convert model instance back to dict and verify no loss of data - message_input_model_json2 = message_input_model.to_dict() - assert message_input_model_json2 == message_input_model_json + log_response_output_model_json2 = log_response_output_model.to_dict() + assert log_response_output_model_json2 == log_response_output_model_json -class TestModel_MessageInputAttachment: +class TestModel_MessageContext: """ - Test Class for MessageInputAttachment + Test Class for MessageContext """ - def test_message_input_attachment_serialization(self): + def test_message_context_serialization(self): """ - Test serialization/deserialization for MessageInputAttachment + Test serialization/deserialization for MessageContext """ - # Construct a json representation of a MessageInputAttachment model - message_input_attachment_model_json = {} - message_input_attachment_model_json['url'] = 'testString' - message_input_attachment_model_json['media_type'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) - assert message_input_attachment_model != False + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ - message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + # Construct a json representation of a MessageContext model + message_context_model_json = {} + message_context_model_json['global'] = message_context_global_model + message_context_model_json['skills'] = message_context_skills_model + message_context_model_json['integrations'] = {'anyKey': 'anyValue'} + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model = MessageContext.from_dict(message_context_model_json) + assert message_context_model != False + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ + message_context_model2 = MessageContext(**message_context_model_dict) # Verify the model instances are equivalent - assert message_input_attachment_model == message_input_attachment_model2 + assert message_context_model == message_context_model2 # Convert model instance back to dict and verify no loss of data - message_input_attachment_model_json2 = message_input_attachment_model.to_dict() - assert message_input_attachment_model_json2 == message_input_attachment_model_json + message_context_model_json2 = message_context_model.to_dict() + assert message_context_model_json2 == message_context_model_json -class TestModel_MessageInputOptions: +class TestModel_MessageContextActionSkill: """ - Test Class for MessageInputOptions + Test Class for MessageContextActionSkill """ - def test_message_input_options_serialization(self): + def test_message_context_action_skill_serialization(self): """ - Test serialization/deserialization for MessageInputOptions + Test serialization/deserialization for MessageContextActionSkill """ # Construct dict forms of any model objects needed in order to build this model. - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - # Construct a json representation of a MessageInputOptions model - message_input_options_model_json = {} - message_input_options_model_json['restart'] = False - message_input_options_model_json['alternate_intents'] = False - message_input_options_model_json['spelling'] = message_input_options_spelling_model - message_input_options_model_json['debug'] = False - message_input_options_model_json['return_context'] = False - message_input_options_model_json['export'] = False + # Construct a json representation of a MessageContextActionSkill model + message_context_action_skill_model_json = {} + message_context_action_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model_json['system'] = message_context_skill_system_model + message_context_action_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) - assert message_input_options_model != False + # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation + message_context_action_skill_model = MessageContextActionSkill.from_dict(message_context_action_skill_model_json) + assert message_context_action_skill_model != False - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ - message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) + # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation + message_context_action_skill_model_dict = MessageContextActionSkill.from_dict(message_context_action_skill_model_json).__dict__ + message_context_action_skill_model2 = MessageContextActionSkill(**message_context_action_skill_model_dict) # Verify the model instances are equivalent - assert message_input_options_model == message_input_options_model2 + assert message_context_action_skill_model == message_context_action_skill_model2 # Convert model instance back to dict and verify no loss of data - message_input_options_model_json2 = message_input_options_model.to_dict() - assert message_input_options_model_json2 == message_input_options_model_json + message_context_action_skill_model_json2 = message_context_action_skill_model.to_dict() + assert message_context_action_skill_model_json2 == message_context_action_skill_model_json -class TestModel_MessageInputOptionsSpelling: +class TestModel_MessageContextDialogSkill: """ - Test Class for MessageInputOptionsSpelling + Test Class for MessageContextDialogSkill """ - def test_message_input_options_spelling_serialization(self): + def test_message_context_dialog_skill_serialization(self): """ - Test serialization/deserialization for MessageInputOptionsSpelling + Test serialization/deserialization for MessageContextDialogSkill """ - # Construct a json representation of a MessageInputOptionsSpelling model - message_input_options_spelling_model_json = {} - message_input_options_spelling_model_json['suggestions'] = True - message_input_options_spelling_model_json['auto_correct'] = True + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) - assert message_input_options_spelling_model != False + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ - message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) + # Construct a json representation of a MessageContextDialogSkill model + message_context_dialog_skill_model_json = {} + message_context_dialog_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model_json['system'] = message_context_skill_system_model + + # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation + message_context_dialog_skill_model = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json) + assert message_context_dialog_skill_model != False + + # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation + message_context_dialog_skill_model_dict = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json).__dict__ + message_context_dialog_skill_model2 = MessageContextDialogSkill(**message_context_dialog_skill_model_dict) # Verify the model instances are equivalent - assert message_input_options_spelling_model == message_input_options_spelling_model2 + assert message_context_dialog_skill_model == message_context_dialog_skill_model2 # Convert model instance back to dict and verify no loss of data - message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() - assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json + message_context_dialog_skill_model_json2 = message_context_dialog_skill_model.to_dict() + assert message_context_dialog_skill_model_json2 == message_context_dialog_skill_model_json -class TestModel_MessageInputOptionsStateless: +class TestModel_MessageContextGlobal: """ - Test Class for MessageInputOptionsStateless + Test Class for MessageContextGlobal """ - def test_message_input_options_stateless_serialization(self): + def test_message_context_global_serialization(self): """ - Test serialization/deserialization for MessageInputOptionsStateless + Test serialization/deserialization for MessageContextGlobal """ # Construct dict forms of any model objects needed in order to build this model. - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a json representation of a MessageInputOptionsStateless model - message_input_options_stateless_model_json = {} - message_input_options_stateless_model_json['restart'] = False - message_input_options_stateless_model_json['alternate_intents'] = False - message_input_options_stateless_model_json['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model_json['debug'] = False + # Construct a json representation of a MessageContextGlobal model + message_context_global_model_json = {} + message_context_global_model_json['system'] = message_context_global_system_model - # Construct a model instance of MessageInputOptionsStateless by calling from_dict on the json representation - message_input_options_stateless_model = MessageInputOptionsStateless.from_dict(message_input_options_stateless_model_json) - assert message_input_options_stateless_model != False + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) + assert message_context_global_model != False - # Construct a model instance of MessageInputOptionsStateless by calling from_dict on the json representation - message_input_options_stateless_model_dict = MessageInputOptionsStateless.from_dict(message_input_options_stateless_model_json).__dict__ - message_input_options_stateless_model2 = MessageInputOptionsStateless(**message_input_options_stateless_model_dict) + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ + message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) # Verify the model instances are equivalent - assert message_input_options_stateless_model == message_input_options_stateless_model2 + assert message_context_global_model == message_context_global_model2 # Convert model instance back to dict and verify no loss of data - message_input_options_stateless_model_json2 = message_input_options_stateless_model.to_dict() - assert message_input_options_stateless_model_json2 == message_input_options_stateless_model_json + message_context_global_model_json2 = message_context_global_model.to_dict() + assert message_context_global_model_json2 == message_context_global_model_json -class TestModel_MessageInputStateless: +class TestModel_MessageContextGlobalSystem: """ - Test Class for MessageInputStateless + Test Class for MessageContextGlobalSystem """ - def test_message_input_stateless_serialization(self): + def test_message_context_global_system_serialization(self): """ - Test serialization/deserialization for MessageInputStateless + Test serialization/deserialization for MessageContextGlobalSystem """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a MessageContextGlobalSystem model + message_context_global_system_model_json = {} + message_context_global_system_model_json['timezone'] = 'testString' + message_context_global_system_model_json['user_id'] = 'testString' + message_context_global_system_model_json['turn_count'] = 38 + message_context_global_system_model_json['locale'] = 'en-us' + message_context_global_system_model_json['reference_time'] = 'testString' + message_context_global_system_model_json['session_start_time'] = 'testString' + message_context_global_system_model_json['state'] = 'testString' + message_context_global_system_model_json['skip_user_input'] = True - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) + assert message_context_global_system_model != False - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ + message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 + # Verify the model instances are equivalent + assert message_context_global_system_model == message_context_global_system_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_global_system_model_json2 = message_context_global_system_model.to_dict() + assert message_context_global_system_model_json2 == message_context_global_system_model_json + + +class TestModel_MessageContextSkillSystem: + """ + Test Class for MessageContextSkillSystem + """ + + def test_message_context_skill_system_serialization(self): + """ + Test serialization/deserialization for MessageContextSkillSystem + """ + + # Construct a json representation of a MessageContextSkillSystem model + message_context_skill_system_model_json = {} + message_context_skill_system_model_json['state'] = 'testString' + message_context_skill_system_model_json['foo'] = 'testString' + + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) + assert message_context_skill_system_model != False + + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ + message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) + + # Verify the model instances are equivalent + assert message_context_skill_system_model == message_context_skill_system_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() + assert message_context_skill_system_model_json2 == message_context_skill_system_model_json + + # Test get_properties and set_properties methods. + message_context_skill_system_model.set_properties({}) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': 'testString'} + message_context_skill_system_model.set_properties(expected_dict) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict == expected_dict + + +class TestModel_MessageContextSkills: + """ + Test Class for MessageContextSkills + """ + + def test_message_context_skills_serialization(self): + """ + Test serialization/deserialization for MessageContextSkills + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a json representation of a MessageContextSkills model + message_context_skills_model_json = {} + message_context_skills_model_json['main skill'] = message_context_dialog_skill_model + message_context_skills_model_json['actions skill'] = message_context_action_skill_model + + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) + assert message_context_skills_model != False + + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ + message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) + + # Verify the model instances are equivalent + assert message_context_skills_model == message_context_skills_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_skills_model_json2 = message_context_skills_model.to_dict() + assert message_context_skills_model_json2 == message_context_skills_model_json + + +class TestModel_MessageInput: + """ + Test Class for MessageInput + """ + + def test_message_input_serialization(self): + """ + Test serialization/deserialization for MessageInput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 runtime_entity_interpretation_model['specific_year'] = 72.5 runtime_entity_interpretation_model['numeric_value'] = 72.5 runtime_entity_interpretation_model['subtype'] = 'testString' @@ -6005,37 +6276,144 @@ def test_message_input_stateless_serialization(self): message_input_options_spelling_model['suggestions'] = True message_input_options_spelling_model['auto_correct'] = True - message_input_options_stateless_model = {} # MessageInputOptionsStateless - message_input_options_stateless_model['restart'] = False - message_input_options_stateless_model['alternate_intents'] = False - message_input_options_stateless_model['spelling'] = message_input_options_spelling_model - message_input_options_stateless_model['debug'] = False - - # Construct a json representation of a MessageInputStateless model - message_input_stateless_model_json = {} - message_input_stateless_model_json['message_type'] = 'text' - message_input_stateless_model_json['text'] = 'testString' - message_input_stateless_model_json['intents'] = [runtime_intent_model] - message_input_stateless_model_json['entities'] = [runtime_entity_model] - message_input_stateless_model_json['suggestion_id'] = 'testString' - message_input_stateless_model_json['attachments'] = [message_input_attachment_model] - message_input_stateless_model_json['analytics'] = request_analytics_model - message_input_stateless_model_json['options'] = message_input_options_stateless_model - - # Construct a model instance of MessageInputStateless by calling from_dict on the json representation - message_input_stateless_model = MessageInputStateless.from_dict(message_input_stateless_model_json) - assert message_input_stateless_model != False - - # Construct a model instance of MessageInputStateless by calling from_dict on the json representation - message_input_stateless_model_dict = MessageInputStateless.from_dict(message_input_stateless_model_json).__dict__ - message_input_stateless_model2 = MessageInputStateless(**message_input_stateless_model_dict) + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + # Construct a json representation of a MessageInput model + message_input_model_json = {} + message_input_model_json['message_type'] = 'text' + message_input_model_json['text'] = 'testString' + message_input_model_json['intents'] = [runtime_intent_model] + message_input_model_json['entities'] = [runtime_entity_model] + message_input_model_json['suggestion_id'] = 'testString' + message_input_model_json['attachments'] = [message_input_attachment_model] + message_input_model_json['analytics'] = request_analytics_model + message_input_model_json['options'] = message_input_options_model + + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model = MessageInput.from_dict(message_input_model_json) + assert message_input_model != False + + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ + message_input_model2 = MessageInput(**message_input_model_dict) + + # Verify the model instances are equivalent + assert message_input_model == message_input_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_model_json2 = message_input_model.to_dict() + assert message_input_model_json2 == message_input_model_json + + +class TestModel_MessageInputAttachment: + """ + Test Class for MessageInputAttachment + """ + + def test_message_input_attachment_serialization(self): + """ + Test serialization/deserialization for MessageInputAttachment + """ + + # Construct a json representation of a MessageInputAttachment model + message_input_attachment_model_json = {} + message_input_attachment_model_json['url'] = 'testString' + message_input_attachment_model_json['media_type'] = 'testString' + + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) + assert message_input_attachment_model != False + + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ + message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) + + # Verify the model instances are equivalent + assert message_input_attachment_model == message_input_attachment_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_attachment_model_json2 = message_input_attachment_model.to_dict() + assert message_input_attachment_model_json2 == message_input_attachment_model_json + + +class TestModel_MessageInputOptions: + """ + Test Class for MessageInputOptions + """ + + def test_message_input_options_serialization(self): + """ + Test serialization/deserialization for MessageInputOptions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a json representation of a MessageInputOptions model + message_input_options_model_json = {} + message_input_options_model_json['restart'] = False + message_input_options_model_json['alternate_intents'] = False + message_input_options_model_json['async_callout'] = False + message_input_options_model_json['spelling'] = message_input_options_spelling_model + message_input_options_model_json['debug'] = False + message_input_options_model_json['return_context'] = False + message_input_options_model_json['export'] = False + + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) + assert message_input_options_model != False + + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ + message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) + + # Verify the model instances are equivalent + assert message_input_options_model == message_input_options_model2 + + # Convert model instance back to dict and verify no loss of data + message_input_options_model_json2 = message_input_options_model.to_dict() + assert message_input_options_model_json2 == message_input_options_model_json + + +class TestModel_MessageInputOptionsSpelling: + """ + Test Class for MessageInputOptionsSpelling + """ + + def test_message_input_options_spelling_serialization(self): + """ + Test serialization/deserialization for MessageInputOptionsSpelling + """ + + # Construct a json representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model_json = {} + message_input_options_spelling_model_json['suggestions'] = True + message_input_options_spelling_model_json['auto_correct'] = True + + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) + assert message_input_options_spelling_model != False + + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ + message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) # Verify the model instances are equivalent - assert message_input_stateless_model == message_input_stateless_model2 + assert message_input_options_spelling_model == message_input_options_spelling_model2 # Convert model instance back to dict and verify no loss of data - message_input_stateless_model_json2 = message_input_stateless_model.to_dict() - assert message_input_stateless_model_json2 == message_input_stateless_model_json + message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() + assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json class TestModel_MessageOutput: @@ -6284,377 +6662,250 @@ def test_message_output_spelling_serialization(self): assert message_output_spelling_model_json2 == message_output_spelling_model_json -class TestModel_MessageRequest: +class TestModel_Pagination: """ - Test Class for MessageRequest + Test Class for Pagination """ - def test_message_request_serialization(self): + def test_pagination_serialization(self): """ - Test serialization/deserialization for MessageRequest + Test serialization/deserialization for Pagination """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a Pagination model + pagination_model_json = {} + pagination_model_json['refresh_url'] = 'testString' + pagination_model_json['next_url'] = 'testString' + pagination_model_json['total'] = 38 + pagination_model_json['matched'] = 38 + pagination_model_json['refresh_cursor'] = 'testString' + pagination_model_json['next_cursor'] = 'testString' - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model = Pagination.from_dict(pagination_model_json) + assert pagination_model != False - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ + pagination_model2 = Pagination(**pagination_model_dict) - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Verify the model instances are equivalent + assert pagination_model == pagination_model2 - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Convert model instance back to dict and verify no loss of data + pagination_model_json2 = pagination_model.to_dict() + assert pagination_model_json2 == pagination_model_json - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' +class TestModel_Release: + """ + Test Class for Release + """ - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + def test_release_serialization(self): + """ + Test serialization/deserialization for Release + """ - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' + # Construct a json representation of a Release model + release_model_json = {} + release_model_json['description'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + # Construct a model instance of Release by calling from_dict on the json representation + release_model = Release.from_dict(release_model_json) + assert release_model != False - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + # Construct a model instance of Release by calling from_dict on the json representation + release_model_dict = Release.from_dict(release_model_json).__dict__ + release_model2 = Release(**release_model_dict) - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'Hello' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model + # Verify the model instances are equivalent + assert release_model == release_model2 - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'my_user_id' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Convert model instance back to dict and verify no loss of data + release_model_json2 = release_model.to_dict() + assert release_model_json2 == release_model_json - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' +class TestModel_ReleaseCollection: + """ + Test Class for ReleaseCollection + """ - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + def test_release_collection_serialization(self): + """ + Test serialization/deserialization for ReleaseCollection + """ - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} + # Construct dict forms of any model objects needed in order to build this model. - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model + release_model = {} # Release + release_model['description'] = 'testString' - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' - # Construct a json representation of a MessageRequest model - message_request_model_json = {} - message_request_model_json['input'] = message_input_model - message_request_model_json['context'] = message_context_model - message_request_model_json['user_id'] = 'testString' + # Construct a json representation of a ReleaseCollection model + release_collection_model_json = {} + release_collection_model_json['releases'] = [release_model] + release_collection_model_json['pagination'] = pagination_model - # Construct a model instance of MessageRequest by calling from_dict on the json representation - message_request_model = MessageRequest.from_dict(message_request_model_json) - assert message_request_model != False + # Construct a model instance of ReleaseCollection by calling from_dict on the json representation + release_collection_model = ReleaseCollection.from_dict(release_collection_model_json) + assert release_collection_model != False - # Construct a model instance of MessageRequest by calling from_dict on the json representation - message_request_model_dict = MessageRequest.from_dict(message_request_model_json).__dict__ - message_request_model2 = MessageRequest(**message_request_model_dict) + # Construct a model instance of ReleaseCollection by calling from_dict on the json representation + release_collection_model_dict = ReleaseCollection.from_dict(release_collection_model_json).__dict__ + release_collection_model2 = ReleaseCollection(**release_collection_model_dict) # Verify the model instances are equivalent - assert message_request_model == message_request_model2 + assert release_collection_model == release_collection_model2 # Convert model instance back to dict and verify no loss of data - message_request_model_json2 = message_request_model.to_dict() - assert message_request_model_json2 == message_request_model_json + release_collection_model_json2 = release_collection_model.to_dict() + assert release_collection_model_json2 == release_collection_model_json -class TestModel_MessageResponse: +class TestModel_ReleaseContent: """ - Test Class for MessageResponse + Test Class for ReleaseContent """ - def test_message_response_serialization(self): + def test_release_content_serialization(self): """ - Test serialization/deserialization for MessageResponse + Test serialization/deserialization for ReleaseContent """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a ReleaseContent model + release_content_model_json = {} - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + # Construct a model instance of ReleaseContent by calling from_dict on the json representation + release_content_model = ReleaseContent.from_dict(release_content_model_json) + assert release_content_model != False - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + # Construct a model instance of ReleaseContent by calling from_dict on the json representation + release_content_model_dict = ReleaseContent.from_dict(release_content_model_json).__dict__ + release_content_model2 = ReleaseContent(**release_content_model_dict) - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + # Verify the model instances are equivalent + assert release_content_model == release_content_model2 - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Convert model instance back to dict and verify no loss of data + release_content_model_json2 = release_content_model.to_dict() + assert release_content_model_json2 == release_content_model_json - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 +class TestModel_ReleaseSkill: + """ + Test Class for ReleaseSkill + """ - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + def test_release_skill_serialization(self): + """ + Test serialization/deserialization for ReleaseSkill + """ - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + # Construct a json representation of a ReleaseSkill model + release_skill_model_json = {} + release_skill_model_json['skill_id'] = 'testString' + release_skill_model_json['type'] = 'dialog' + release_skill_model_json['snapshot'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + # Construct a model instance of ReleaseSkill by calling from_dict on the json representation + release_skill_model = ReleaseSkill.from_dict(release_skill_model_json) + assert release_skill_model != False - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + # Construct a model instance of ReleaseSkill by calling from_dict on the json representation + release_skill_model_dict = ReleaseSkill.from_dict(release_skill_model_json).__dict__ + release_skill_model2 = ReleaseSkill(**release_skill_model_dict) - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + # Verify the model instances are equivalent + assert release_skill_model == release_skill_model2 - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' + # Convert model instance back to dict and verify no loss of data + release_skill_model_json2 = release_skill_model.to_dict() + assert release_skill_model_json2 == release_skill_model_json - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] +class TestModel_RequestAnalytics: + """ + Test Class for RequestAnalytics + """ - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' + def test_request_analytics_serialization(self): + """ + Test serialization/deserialization for RequestAnalytics + """ - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'anyKey': 'anyValue'} - message_output_model['spelling'] = message_output_spelling_model + # Construct a json representation of a RequestAnalytics model + request_analytics_model_json = {} + request_analytics_model_json['browser'] = 'testString' + request_analytics_model_json['device'] = 'testString' + request_analytics_model_json['pageUrl'] = 'testString' - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Construct a model instance of RequestAnalytics by calling from_dict on the json representation + request_analytics_model = RequestAnalytics.from_dict(request_analytics_model_json) + assert request_analytics_model != False - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + # Construct a model instance of RequestAnalytics by calling from_dict on the json representation + request_analytics_model_dict = RequestAnalytics.from_dict(request_analytics_model_json).__dict__ + request_analytics_model2 = RequestAnalytics(**request_analytics_model_dict) - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Verify the model instances are equivalent + assert request_analytics_model == request_analytics_model2 - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model + # Convert model instance back to dict and verify no loss of data + request_analytics_model_json2 = request_analytics_model.to_dict() + assert request_analytics_model_json2 == request_analytics_model_json - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model +class TestModel_ResponseGenericChannel: + """ + Test Class for ResponseGenericChannel + """ - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} + def test_response_generic_channel_serialization(self): + """ + Test serialization/deserialization for ResponseGenericChannel + """ - # Construct a json representation of a MessageResponse model - message_response_model_json = {} - message_response_model_json['output'] = message_output_model - message_response_model_json['context'] = message_context_model - message_response_model_json['user_id'] = 'testString' + # Construct a json representation of a ResponseGenericChannel model + response_generic_channel_model_json = {} + response_generic_channel_model_json['channel'] = 'testString' - # Construct a model instance of MessageResponse by calling from_dict on the json representation - message_response_model = MessageResponse.from_dict(message_response_model_json) - assert message_response_model != False + # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation + response_generic_channel_model = ResponseGenericChannel.from_dict(response_generic_channel_model_json) + assert response_generic_channel_model != False - # Construct a model instance of MessageResponse by calling from_dict on the json representation - message_response_model_dict = MessageResponse.from_dict(message_response_model_json).__dict__ - message_response_model2 = MessageResponse(**message_response_model_dict) + # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation + response_generic_channel_model_dict = ResponseGenericChannel.from_dict(response_generic_channel_model_json).__dict__ + response_generic_channel_model2 = ResponseGenericChannel(**response_generic_channel_model_dict) # Verify the model instances are equivalent - assert message_response_model == message_response_model2 + assert response_generic_channel_model == response_generic_channel_model2 # Convert model instance back to dict and verify no loss of data - message_response_model_json2 = message_response_model.to_dict() - assert message_response_model_json2 == message_response_model_json + response_generic_channel_model_json2 = response_generic_channel_model.to_dict() + assert response_generic_channel_model_json2 == response_generic_channel_model_json -class TestModel_MessageResponseStateless: +class TestModel_RuntimeEntity: """ - Test Class for MessageResponseStateless + Test Class for RuntimeEntity """ - def test_message_response_stateless_serialization(self): + def test_runtime_entity_serialization(self): """ - Test serialization/deserialization for MessageResponseStateless + Test serialization/deserialization for RuntimeEntity """ # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] - - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' - capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' capture_group_model['location'] = [38] @@ -6694,757 +6945,607 @@ def test_message_response_stateless_serialization(self): runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' - - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' - - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' - - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model - - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' - - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' - - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' - - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'anyKey': 'anyValue'} - message_output_model['spelling'] = message_output_spelling_model - - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - - message_context_global_stateless_model = {} # MessageContextGlobalStateless - message_context_global_stateless_model['system'] = message_context_global_system_model - message_context_global_stateless_model['session_id'] = 'testString' - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - message_context_skill_dialog_model = {} # MessageContextSkillDialog - message_context_skill_dialog_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_dialog_model['system'] = message_context_skill_system_model - - message_context_skill_action_model = {} # MessageContextSkillAction - message_context_skill_action_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['system'] = message_context_skill_system_model - message_context_skill_action_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_skill_action_model['skill_variables'] = {'anyKey': 'anyValue'} - - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_skill_dialog_model - message_context_skills_model['actions skill'] = message_context_skill_action_model - - message_context_stateless_model = {} # MessageContextStateless - message_context_stateless_model['global'] = message_context_global_stateless_model - message_context_stateless_model['skills'] = message_context_skills_model - message_context_stateless_model['integrations'] = {'anyKey': 'anyValue'} - - # Construct a json representation of a MessageResponseStateless model - message_response_stateless_model_json = {} - message_response_stateless_model_json['output'] = message_output_model - message_response_stateless_model_json['context'] = message_context_stateless_model - message_response_stateless_model_json['user_id'] = 'testString' + # Construct a json representation of a RuntimeEntity model + runtime_entity_model_json = {} + runtime_entity_model_json['entity'] = 'testString' + runtime_entity_model_json['location'] = [38] + runtime_entity_model_json['value'] = 'testString' + runtime_entity_model_json['confidence'] = 72.5 + runtime_entity_model_json['groups'] = [capture_group_model] + runtime_entity_model_json['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model_json['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model_json['role'] = runtime_entity_role_model + runtime_entity_model_json['skill'] = 'testString' - # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation - message_response_stateless_model = MessageResponseStateless.from_dict(message_response_stateless_model_json) - assert message_response_stateless_model != False + # Construct a model instance of RuntimeEntity by calling from_dict on the json representation + runtime_entity_model = RuntimeEntity.from_dict(runtime_entity_model_json) + assert runtime_entity_model != False - # Construct a model instance of MessageResponseStateless by calling from_dict on the json representation - message_response_stateless_model_dict = MessageResponseStateless.from_dict(message_response_stateless_model_json).__dict__ - message_response_stateless_model2 = MessageResponseStateless(**message_response_stateless_model_dict) + # Construct a model instance of RuntimeEntity by calling from_dict on the json representation + runtime_entity_model_dict = RuntimeEntity.from_dict(runtime_entity_model_json).__dict__ + runtime_entity_model2 = RuntimeEntity(**runtime_entity_model_dict) # Verify the model instances are equivalent - assert message_response_stateless_model == message_response_stateless_model2 + assert runtime_entity_model == runtime_entity_model2 # Convert model instance back to dict and verify no loss of data - message_response_stateless_model_json2 = message_response_stateless_model.to_dict() - assert message_response_stateless_model_json2 == message_response_stateless_model_json + runtime_entity_model_json2 = runtime_entity_model.to_dict() + assert runtime_entity_model_json2 == runtime_entity_model_json -class TestModel_Pagination: +class TestModel_RuntimeEntityAlternative: """ - Test Class for Pagination + Test Class for RuntimeEntityAlternative """ - def test_pagination_serialization(self): + def test_runtime_entity_alternative_serialization(self): """ - Test serialization/deserialization for Pagination + Test serialization/deserialization for RuntimeEntityAlternative """ - # Construct a json representation of a Pagination model - pagination_model_json = {} - pagination_model_json['refresh_url'] = 'testString' - pagination_model_json['next_url'] = 'testString' - pagination_model_json['total'] = 38 - pagination_model_json['matched'] = 38 - pagination_model_json['refresh_cursor'] = 'testString' - pagination_model_json['next_cursor'] = 'testString' + # Construct a json representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model_json = {} + runtime_entity_alternative_model_json['value'] = 'testString' + runtime_entity_alternative_model_json['confidence'] = 72.5 - # Construct a model instance of Pagination by calling from_dict on the json representation - pagination_model = Pagination.from_dict(pagination_model_json) - assert pagination_model != False + # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation + runtime_entity_alternative_model = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json) + assert runtime_entity_alternative_model != False - # Construct a model instance of Pagination by calling from_dict on the json representation - pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ - pagination_model2 = Pagination(**pagination_model_dict) + # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation + runtime_entity_alternative_model_dict = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json).__dict__ + runtime_entity_alternative_model2 = RuntimeEntityAlternative(**runtime_entity_alternative_model_dict) # Verify the model instances are equivalent - assert pagination_model == pagination_model2 + assert runtime_entity_alternative_model == runtime_entity_alternative_model2 # Convert model instance back to dict and verify no loss of data - pagination_model_json2 = pagination_model.to_dict() - assert pagination_model_json2 == pagination_model_json + runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() + assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json -class TestModel_Release: +class TestModel_RuntimeEntityInterpretation: """ - Test Class for Release + Test Class for RuntimeEntityInterpretation """ - def test_release_serialization(self): + def test_runtime_entity_interpretation_serialization(self): """ - Test serialization/deserialization for Release + Test serialization/deserialization for RuntimeEntityInterpretation """ - # Construct a json representation of a Release model - release_model_json = {} - release_model_json['description'] = 'testString' + # Construct a json representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model_json = {} + runtime_entity_interpretation_model_json['calendar_type'] = 'testString' + runtime_entity_interpretation_model_json['datetime_link'] = 'testString' + runtime_entity_interpretation_model_json['festival'] = 'testString' + runtime_entity_interpretation_model_json['granularity'] = 'day' + runtime_entity_interpretation_model_json['range_link'] = 'testString' + runtime_entity_interpretation_model_json['range_modifier'] = 'testString' + runtime_entity_interpretation_model_json['relative_day'] = 72.5 + runtime_entity_interpretation_model_json['relative_month'] = 72.5 + runtime_entity_interpretation_model_json['relative_week'] = 72.5 + runtime_entity_interpretation_model_json['relative_weekend'] = 72.5 + runtime_entity_interpretation_model_json['relative_year'] = 72.5 + runtime_entity_interpretation_model_json['specific_day'] = 72.5 + runtime_entity_interpretation_model_json['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model_json['specific_month'] = 72.5 + runtime_entity_interpretation_model_json['specific_quarter'] = 72.5 + runtime_entity_interpretation_model_json['specific_year'] = 72.5 + runtime_entity_interpretation_model_json['numeric_value'] = 72.5 + runtime_entity_interpretation_model_json['subtype'] = 'testString' + runtime_entity_interpretation_model_json['part_of_day'] = 'testString' + runtime_entity_interpretation_model_json['relative_hour'] = 72.5 + runtime_entity_interpretation_model_json['relative_minute'] = 72.5 + runtime_entity_interpretation_model_json['relative_second'] = 72.5 + runtime_entity_interpretation_model_json['specific_hour'] = 72.5 + runtime_entity_interpretation_model_json['specific_minute'] = 72.5 + runtime_entity_interpretation_model_json['specific_second'] = 72.5 + runtime_entity_interpretation_model_json['timezone'] = 'testString' - # Construct a model instance of Release by calling from_dict on the json representation - release_model = Release.from_dict(release_model_json) - assert release_model != False + # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation + runtime_entity_interpretation_model = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json) + assert runtime_entity_interpretation_model != False - # Construct a model instance of Release by calling from_dict on the json representation - release_model_dict = Release.from_dict(release_model_json).__dict__ - release_model2 = Release(**release_model_dict) + # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation + runtime_entity_interpretation_model_dict = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json).__dict__ + runtime_entity_interpretation_model2 = RuntimeEntityInterpretation(**runtime_entity_interpretation_model_dict) # Verify the model instances are equivalent - assert release_model == release_model2 + assert runtime_entity_interpretation_model == runtime_entity_interpretation_model2 # Convert model instance back to dict and verify no loss of data - release_model_json2 = release_model.to_dict() - assert release_model_json2 == release_model_json + runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() + assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json -class TestModel_ReleaseCollection: +class TestModel_RuntimeEntityRole: """ - Test Class for ReleaseCollection + Test Class for RuntimeEntityRole """ - def test_release_collection_serialization(self): + def test_runtime_entity_role_serialization(self): """ - Test serialization/deserialization for ReleaseCollection + Test serialization/deserialization for RuntimeEntityRole """ - # Construct dict forms of any model objects needed in order to build this model. - - release_model = {} # Release - release_model['description'] = 'testString' - - pagination_model = {} # Pagination - pagination_model['refresh_url'] = 'testString' - pagination_model['next_url'] = 'testString' - pagination_model['total'] = 38 - pagination_model['matched'] = 38 - pagination_model['refresh_cursor'] = 'testString' - pagination_model['next_cursor'] = 'testString' - - # Construct a json representation of a ReleaseCollection model - release_collection_model_json = {} - release_collection_model_json['releases'] = [release_model] - release_collection_model_json['pagination'] = pagination_model + # Construct a json representation of a RuntimeEntityRole model + runtime_entity_role_model_json = {} + runtime_entity_role_model_json['type'] = 'date_from' - # Construct a model instance of ReleaseCollection by calling from_dict on the json representation - release_collection_model = ReleaseCollection.from_dict(release_collection_model_json) - assert release_collection_model != False + # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation + runtime_entity_role_model = RuntimeEntityRole.from_dict(runtime_entity_role_model_json) + assert runtime_entity_role_model != False - # Construct a model instance of ReleaseCollection by calling from_dict on the json representation - release_collection_model_dict = ReleaseCollection.from_dict(release_collection_model_json).__dict__ - release_collection_model2 = ReleaseCollection(**release_collection_model_dict) + # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation + runtime_entity_role_model_dict = RuntimeEntityRole.from_dict(runtime_entity_role_model_json).__dict__ + runtime_entity_role_model2 = RuntimeEntityRole(**runtime_entity_role_model_dict) # Verify the model instances are equivalent - assert release_collection_model == release_collection_model2 + assert runtime_entity_role_model == runtime_entity_role_model2 # Convert model instance back to dict and verify no loss of data - release_collection_model_json2 = release_collection_model.to_dict() - assert release_collection_model_json2 == release_collection_model_json + runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() + assert runtime_entity_role_model_json2 == runtime_entity_role_model_json -class TestModel_ReleaseContent: +class TestModel_RuntimeIntent: """ - Test Class for ReleaseContent + Test Class for RuntimeIntent """ - def test_release_content_serialization(self): + def test_runtime_intent_serialization(self): """ - Test serialization/deserialization for ReleaseContent + Test serialization/deserialization for RuntimeIntent """ - # Construct a json representation of a ReleaseContent model - release_content_model_json = {} + # Construct a json representation of a RuntimeIntent model + runtime_intent_model_json = {} + runtime_intent_model_json['intent'] = 'testString' + runtime_intent_model_json['confidence'] = 72.5 + runtime_intent_model_json['skill'] = 'testString' - # Construct a model instance of ReleaseContent by calling from_dict on the json representation - release_content_model = ReleaseContent.from_dict(release_content_model_json) - assert release_content_model != False + # Construct a model instance of RuntimeIntent by calling from_dict on the json representation + runtime_intent_model = RuntimeIntent.from_dict(runtime_intent_model_json) + assert runtime_intent_model != False - # Construct a model instance of ReleaseContent by calling from_dict on the json representation - release_content_model_dict = ReleaseContent.from_dict(release_content_model_json).__dict__ - release_content_model2 = ReleaseContent(**release_content_model_dict) + # Construct a model instance of RuntimeIntent by calling from_dict on the json representation + runtime_intent_model_dict = RuntimeIntent.from_dict(runtime_intent_model_json).__dict__ + runtime_intent_model2 = RuntimeIntent(**runtime_intent_model_dict) # Verify the model instances are equivalent - assert release_content_model == release_content_model2 + assert runtime_intent_model == runtime_intent_model2 # Convert model instance back to dict and verify no loss of data - release_content_model_json2 = release_content_model.to_dict() - assert release_content_model_json2 == release_content_model_json + runtime_intent_model_json2 = runtime_intent_model.to_dict() + assert runtime_intent_model_json2 == runtime_intent_model_json -class TestModel_ReleaseSkill: +class TestModel_SearchResult: """ - Test Class for ReleaseSkill + Test Class for SearchResult """ - def test_release_skill_serialization(self): + def test_search_result_serialization(self): """ - Test serialization/deserialization for ReleaseSkill + Test serialization/deserialization for SearchResult """ - # Construct a json representation of a ReleaseSkill model - release_skill_model_json = {} - release_skill_model_json['skill_id'] = 'testString' - release_skill_model_json['type'] = 'dialog' - release_skill_model_json['snapshot'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of ReleaseSkill by calling from_dict on the json representation - release_skill_model = ReleaseSkill.from_dict(release_skill_model_json) - assert release_skill_model != False + search_result_metadata_model = {} # SearchResultMetadata + search_result_metadata_model['confidence'] = 72.5 + search_result_metadata_model['score'] = 72.5 - # Construct a model instance of ReleaseSkill by calling from_dict on the json representation - release_skill_model_dict = ReleaseSkill.from_dict(release_skill_model_json).__dict__ - release_skill_model2 = ReleaseSkill(**release_skill_model_dict) + search_result_highlight_model = {} # SearchResultHighlight + search_result_highlight_model['body'] = ['testString'] + search_result_highlight_model['title'] = ['testString'] + search_result_highlight_model['url'] = ['testString'] + search_result_highlight_model['foo'] = ['testString'] + + search_result_answer_model = {} # SearchResultAnswer + search_result_answer_model['text'] = 'testString' + search_result_answer_model['confidence'] = 0 + + # Construct a json representation of a SearchResult model + search_result_model_json = {} + search_result_model_json['id'] = 'testString' + search_result_model_json['result_metadata'] = search_result_metadata_model + search_result_model_json['body'] = 'testString' + search_result_model_json['title'] = 'testString' + search_result_model_json['url'] = 'testString' + search_result_model_json['highlight'] = search_result_highlight_model + search_result_model_json['answers'] = [search_result_answer_model] + + # Construct a model instance of SearchResult by calling from_dict on the json representation + search_result_model = SearchResult.from_dict(search_result_model_json) + assert search_result_model != False + + # Construct a model instance of SearchResult by calling from_dict on the json representation + search_result_model_dict = SearchResult.from_dict(search_result_model_json).__dict__ + search_result_model2 = SearchResult(**search_result_model_dict) # Verify the model instances are equivalent - assert release_skill_model == release_skill_model2 + assert search_result_model == search_result_model2 # Convert model instance back to dict and verify no loss of data - release_skill_model_json2 = release_skill_model.to_dict() - assert release_skill_model_json2 == release_skill_model_json + search_result_model_json2 = search_result_model.to_dict() + assert search_result_model_json2 == search_result_model_json -class TestModel_RequestAnalytics: +class TestModel_SearchResultAnswer: """ - Test Class for RequestAnalytics + Test Class for SearchResultAnswer """ - def test_request_analytics_serialization(self): + def test_search_result_answer_serialization(self): """ - Test serialization/deserialization for RequestAnalytics + Test serialization/deserialization for SearchResultAnswer """ - # Construct a json representation of a RequestAnalytics model - request_analytics_model_json = {} - request_analytics_model_json['browser'] = 'testString' - request_analytics_model_json['device'] = 'testString' - request_analytics_model_json['pageUrl'] = 'testString' + # Construct a json representation of a SearchResultAnswer model + search_result_answer_model_json = {} + search_result_answer_model_json['text'] = 'testString' + search_result_answer_model_json['confidence'] = 0 - # Construct a model instance of RequestAnalytics by calling from_dict on the json representation - request_analytics_model = RequestAnalytics.from_dict(request_analytics_model_json) - assert request_analytics_model != False + # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation + search_result_answer_model = SearchResultAnswer.from_dict(search_result_answer_model_json) + assert search_result_answer_model != False - # Construct a model instance of RequestAnalytics by calling from_dict on the json representation - request_analytics_model_dict = RequestAnalytics.from_dict(request_analytics_model_json).__dict__ - request_analytics_model2 = RequestAnalytics(**request_analytics_model_dict) + # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation + search_result_answer_model_dict = SearchResultAnswer.from_dict(search_result_answer_model_json).__dict__ + search_result_answer_model2 = SearchResultAnswer(**search_result_answer_model_dict) # Verify the model instances are equivalent - assert request_analytics_model == request_analytics_model2 + assert search_result_answer_model == search_result_answer_model2 # Convert model instance back to dict and verify no loss of data - request_analytics_model_json2 = request_analytics_model.to_dict() - assert request_analytics_model_json2 == request_analytics_model_json + search_result_answer_model_json2 = search_result_answer_model.to_dict() + assert search_result_answer_model_json2 == search_result_answer_model_json -class TestModel_ResponseGenericChannel: +class TestModel_SearchResultHighlight: """ - Test Class for ResponseGenericChannel + Test Class for SearchResultHighlight """ - def test_response_generic_channel_serialization(self): + def test_search_result_highlight_serialization(self): """ - Test serialization/deserialization for ResponseGenericChannel + Test serialization/deserialization for SearchResultHighlight """ - # Construct a json representation of a ResponseGenericChannel model - response_generic_channel_model_json = {} - response_generic_channel_model_json['channel'] = 'testString' + # Construct a json representation of a SearchResultHighlight model + search_result_highlight_model_json = {} + search_result_highlight_model_json['body'] = ['testString'] + search_result_highlight_model_json['title'] = ['testString'] + search_result_highlight_model_json['url'] = ['testString'] + search_result_highlight_model_json['foo'] = ['testString'] - # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation - response_generic_channel_model = ResponseGenericChannel.from_dict(response_generic_channel_model_json) - assert response_generic_channel_model != False + # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation + search_result_highlight_model = SearchResultHighlight.from_dict(search_result_highlight_model_json) + assert search_result_highlight_model != False - # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation - response_generic_channel_model_dict = ResponseGenericChannel.from_dict(response_generic_channel_model_json).__dict__ - response_generic_channel_model2 = ResponseGenericChannel(**response_generic_channel_model_dict) + # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation + search_result_highlight_model_dict = SearchResultHighlight.from_dict(search_result_highlight_model_json).__dict__ + search_result_highlight_model2 = SearchResultHighlight(**search_result_highlight_model_dict) # Verify the model instances are equivalent - assert response_generic_channel_model == response_generic_channel_model2 + assert search_result_highlight_model == search_result_highlight_model2 # Convert model instance back to dict and verify no loss of data - response_generic_channel_model_json2 = response_generic_channel_model.to_dict() - assert response_generic_channel_model_json2 == response_generic_channel_model_json + search_result_highlight_model_json2 = search_result_highlight_model.to_dict() + assert search_result_highlight_model_json2 == search_result_highlight_model_json + # Test get_properties and set_properties methods. + search_result_highlight_model.set_properties({}) + actual_dict = search_result_highlight_model.get_properties() + assert actual_dict == {} -class TestModel_RuntimeEntity: + expected_dict = {'foo': ['testString']} + search_result_highlight_model.set_properties(expected_dict) + actual_dict = search_result_highlight_model.get_properties() + assert actual_dict == expected_dict + + +class TestModel_SearchResultMetadata: """ - Test Class for RuntimeEntity + Test Class for SearchResultMetadata """ - def test_runtime_entity_serialization(self): + def test_search_result_metadata_serialization(self): """ - Test serialization/deserialization for RuntimeEntity + Test serialization/deserialization for SearchResultMetadata """ - # Construct dict forms of any model objects needed in order to build this model. - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' - - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 - - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - - # Construct a json representation of a RuntimeEntity model - runtime_entity_model_json = {} - runtime_entity_model_json['entity'] = 'testString' - runtime_entity_model_json['location'] = [38] - runtime_entity_model_json['value'] = 'testString' - runtime_entity_model_json['confidence'] = 72.5 - runtime_entity_model_json['groups'] = [capture_group_model] - runtime_entity_model_json['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model_json['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model_json['role'] = runtime_entity_role_model - runtime_entity_model_json['skill'] = 'testString' + # Construct a json representation of a SearchResultMetadata model + search_result_metadata_model_json = {} + search_result_metadata_model_json['confidence'] = 72.5 + search_result_metadata_model_json['score'] = 72.5 - # Construct a model instance of RuntimeEntity by calling from_dict on the json representation - runtime_entity_model = RuntimeEntity.from_dict(runtime_entity_model_json) - assert runtime_entity_model != False + # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation + search_result_metadata_model = SearchResultMetadata.from_dict(search_result_metadata_model_json) + assert search_result_metadata_model != False - # Construct a model instance of RuntimeEntity by calling from_dict on the json representation - runtime_entity_model_dict = RuntimeEntity.from_dict(runtime_entity_model_json).__dict__ - runtime_entity_model2 = RuntimeEntity(**runtime_entity_model_dict) + # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation + search_result_metadata_model_dict = SearchResultMetadata.from_dict(search_result_metadata_model_json).__dict__ + search_result_metadata_model2 = SearchResultMetadata(**search_result_metadata_model_dict) # Verify the model instances are equivalent - assert runtime_entity_model == runtime_entity_model2 + assert search_result_metadata_model == search_result_metadata_model2 # Convert model instance back to dict and verify no loss of data - runtime_entity_model_json2 = runtime_entity_model.to_dict() - assert runtime_entity_model_json2 == runtime_entity_model_json + search_result_metadata_model_json2 = search_result_metadata_model.to_dict() + assert search_result_metadata_model_json2 == search_result_metadata_model_json -class TestModel_RuntimeEntityAlternative: +class TestModel_SearchSettings: """ - Test Class for RuntimeEntityAlternative + Test Class for SearchSettings """ - def test_runtime_entity_alternative_serialization(self): + def test_search_settings_serialization(self): """ - Test serialization/deserialization for RuntimeEntityAlternative + Test serialization/deserialization for SearchSettings """ - # Construct a json representation of a RuntimeEntityAlternative model - runtime_entity_alternative_model_json = {} - runtime_entity_alternative_model_json['value'] = 'testString' - runtime_entity_alternative_model_json['confidence'] = 72.5 - - # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation - runtime_entity_alternative_model = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json) - assert runtime_entity_alternative_model != False - - # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation - runtime_entity_alternative_model_dict = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json).__dict__ - runtime_entity_alternative_model2 = RuntimeEntityAlternative(**runtime_entity_alternative_model_dict) - - # Verify the model instances are equivalent - assert runtime_entity_alternative_model == runtime_entity_alternative_model2 + # Construct dict forms of any model objects needed in order to build this model. - # Convert model instance back to dict and verify no loss of data - runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() - assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model -class TestModel_RuntimeEntityInterpretation: - """ - Test Class for RuntimeEntityInterpretation - """ + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' - def test_runtime_entity_interpretation_serialization(self): - """ - Test serialization/deserialization for RuntimeEntityInterpretation - """ + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' - # Construct a json representation of a RuntimeEntityInterpretation model - runtime_entity_interpretation_model_json = {} - runtime_entity_interpretation_model_json['calendar_type'] = 'testString' - runtime_entity_interpretation_model_json['datetime_link'] = 'testString' - runtime_entity_interpretation_model_json['festival'] = 'testString' - runtime_entity_interpretation_model_json['granularity'] = 'day' - runtime_entity_interpretation_model_json['range_link'] = 'testString' - runtime_entity_interpretation_model_json['range_modifier'] = 'testString' - runtime_entity_interpretation_model_json['relative_day'] = 72.5 - runtime_entity_interpretation_model_json['relative_month'] = 72.5 - runtime_entity_interpretation_model_json['relative_week'] = 72.5 - runtime_entity_interpretation_model_json['relative_weekend'] = 72.5 - runtime_entity_interpretation_model_json['relative_year'] = 72.5 - runtime_entity_interpretation_model_json['specific_day'] = 72.5 - runtime_entity_interpretation_model_json['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model_json['specific_month'] = 72.5 - runtime_entity_interpretation_model_json['specific_quarter'] = 72.5 - runtime_entity_interpretation_model_json['specific_year'] = 72.5 - runtime_entity_interpretation_model_json['numeric_value'] = 72.5 - runtime_entity_interpretation_model_json['subtype'] = 'testString' - runtime_entity_interpretation_model_json['part_of_day'] = 'testString' - runtime_entity_interpretation_model_json['relative_hour'] = 72.5 - runtime_entity_interpretation_model_json['relative_minute'] = 72.5 - runtime_entity_interpretation_model_json['relative_second'] = 72.5 - runtime_entity_interpretation_model_json['specific_hour'] = 72.5 - runtime_entity_interpretation_model_json['specific_minute'] = 72.5 - runtime_entity_interpretation_model_json['specific_second'] = 72.5 - runtime_entity_interpretation_model_json['timezone'] = 'testString' + # Construct a json representation of a SearchSettings model + search_settings_model_json = {} + search_settings_model_json['discovery'] = search_settings_discovery_model + search_settings_model_json['messages'] = search_settings_messages_model + search_settings_model_json['schema_mapping'] = search_settings_schema_mapping_model - # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation - runtime_entity_interpretation_model = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json) - assert runtime_entity_interpretation_model != False + # Construct a model instance of SearchSettings by calling from_dict on the json representation + search_settings_model = SearchSettings.from_dict(search_settings_model_json) + assert search_settings_model != False - # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation - runtime_entity_interpretation_model_dict = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json).__dict__ - runtime_entity_interpretation_model2 = RuntimeEntityInterpretation(**runtime_entity_interpretation_model_dict) + # Construct a model instance of SearchSettings by calling from_dict on the json representation + search_settings_model_dict = SearchSettings.from_dict(search_settings_model_json).__dict__ + search_settings_model2 = SearchSettings(**search_settings_model_dict) # Verify the model instances are equivalent - assert runtime_entity_interpretation_model == runtime_entity_interpretation_model2 + assert search_settings_model == search_settings_model2 # Convert model instance back to dict and verify no loss of data - runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() - assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json + search_settings_model_json2 = search_settings_model.to_dict() + assert search_settings_model_json2 == search_settings_model_json -class TestModel_RuntimeEntityRole: +class TestModel_SearchSettingsDiscovery: """ - Test Class for RuntimeEntityRole + Test Class for SearchSettingsDiscovery """ - def test_runtime_entity_role_serialization(self): + def test_search_settings_discovery_serialization(self): """ - Test serialization/deserialization for RuntimeEntityRole + Test serialization/deserialization for SearchSettingsDiscovery """ - # Construct a json representation of a RuntimeEntityRole model - runtime_entity_role_model_json = {} - runtime_entity_role_model_json['type'] = 'date_from' - - # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation - runtime_entity_role_model = RuntimeEntityRole.from_dict(runtime_entity_role_model_json) - assert runtime_entity_role_model != False + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation - runtime_entity_role_model_dict = RuntimeEntityRole.from_dict(runtime_entity_role_model_json).__dict__ - runtime_entity_role_model2 = RuntimeEntityRole(**runtime_entity_role_model_dict) + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a json representation of a SearchSettingsDiscovery model + search_settings_discovery_model_json = {} + search_settings_discovery_model_json['instance_id'] = 'testString' + search_settings_discovery_model_json['project_id'] = 'testString' + search_settings_discovery_model_json['url'] = 'testString' + search_settings_discovery_model_json['max_primary_results'] = 10000 + search_settings_discovery_model_json['max_total_results'] = 10000 + search_settings_discovery_model_json['confidence_threshold'] = 0.0 + search_settings_discovery_model_json['highlight'] = True + search_settings_discovery_model_json['find_answers'] = True + search_settings_discovery_model_json['authentication'] = search_settings_discovery_authentication_model + + # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation + search_settings_discovery_model = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json) + assert search_settings_discovery_model != False + + # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation + search_settings_discovery_model_dict = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json).__dict__ + search_settings_discovery_model2 = SearchSettingsDiscovery(**search_settings_discovery_model_dict) # Verify the model instances are equivalent - assert runtime_entity_role_model == runtime_entity_role_model2 + assert search_settings_discovery_model == search_settings_discovery_model2 # Convert model instance back to dict and verify no loss of data - runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() - assert runtime_entity_role_model_json2 == runtime_entity_role_model_json + search_settings_discovery_model_json2 = search_settings_discovery_model.to_dict() + assert search_settings_discovery_model_json2 == search_settings_discovery_model_json -class TestModel_RuntimeIntent: +class TestModel_SearchSettingsDiscoveryAuthentication: """ - Test Class for RuntimeIntent + Test Class for SearchSettingsDiscoveryAuthentication """ - def test_runtime_intent_serialization(self): + def test_search_settings_discovery_authentication_serialization(self): """ - Test serialization/deserialization for RuntimeIntent + Test serialization/deserialization for SearchSettingsDiscoveryAuthentication """ - # Construct a json representation of a RuntimeIntent model - runtime_intent_model_json = {} - runtime_intent_model_json['intent'] = 'testString' - runtime_intent_model_json['confidence'] = 72.5 - runtime_intent_model_json['skill'] = 'testString' + # Construct a json representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model_json = {} + search_settings_discovery_authentication_model_json['basic'] = 'testString' + search_settings_discovery_authentication_model_json['bearer'] = 'testString' - # Construct a model instance of RuntimeIntent by calling from_dict on the json representation - runtime_intent_model = RuntimeIntent.from_dict(runtime_intent_model_json) - assert runtime_intent_model != False + # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation + search_settings_discovery_authentication_model = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json) + assert search_settings_discovery_authentication_model != False - # Construct a model instance of RuntimeIntent by calling from_dict on the json representation - runtime_intent_model_dict = RuntimeIntent.from_dict(runtime_intent_model_json).__dict__ - runtime_intent_model2 = RuntimeIntent(**runtime_intent_model_dict) + # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation + search_settings_discovery_authentication_model_dict = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json).__dict__ + search_settings_discovery_authentication_model2 = SearchSettingsDiscoveryAuthentication(**search_settings_discovery_authentication_model_dict) # Verify the model instances are equivalent - assert runtime_intent_model == runtime_intent_model2 + assert search_settings_discovery_authentication_model == search_settings_discovery_authentication_model2 # Convert model instance back to dict and verify no loss of data - runtime_intent_model_json2 = runtime_intent_model.to_dict() - assert runtime_intent_model_json2 == runtime_intent_model_json + search_settings_discovery_authentication_model_json2 = search_settings_discovery_authentication_model.to_dict() + assert search_settings_discovery_authentication_model_json2 == search_settings_discovery_authentication_model_json -class TestModel_SearchResult: +class TestModel_SearchSettingsMessages: """ - Test Class for SearchResult + Test Class for SearchSettingsMessages """ - def test_search_result_serialization(self): + def test_search_settings_messages_serialization(self): """ - Test serialization/deserialization for SearchResult + Test serialization/deserialization for SearchSettingsMessages """ - # Construct dict forms of any model objects needed in order to build this model. - - search_result_metadata_model = {} # SearchResultMetadata - search_result_metadata_model['confidence'] = 72.5 - search_result_metadata_model['score'] = 72.5 - - search_result_highlight_model = {} # SearchResultHighlight - search_result_highlight_model['body'] = ['testString'] - search_result_highlight_model['title'] = ['testString'] - search_result_highlight_model['url'] = ['testString'] - search_result_highlight_model['foo'] = ['testString'] - - search_result_answer_model = {} # SearchResultAnswer - search_result_answer_model['text'] = 'testString' - search_result_answer_model['confidence'] = 0 - - # Construct a json representation of a SearchResult model - search_result_model_json = {} - search_result_model_json['id'] = 'testString' - search_result_model_json['result_metadata'] = search_result_metadata_model - search_result_model_json['body'] = 'testString' - search_result_model_json['title'] = 'testString' - search_result_model_json['url'] = 'testString' - search_result_model_json['highlight'] = search_result_highlight_model - search_result_model_json['answers'] = [search_result_answer_model] + # Construct a json representation of a SearchSettingsMessages model + search_settings_messages_model_json = {} + search_settings_messages_model_json['success'] = 'testString' + search_settings_messages_model_json['error'] = 'testString' + search_settings_messages_model_json['no_result'] = 'testString' - # Construct a model instance of SearchResult by calling from_dict on the json representation - search_result_model = SearchResult.from_dict(search_result_model_json) - assert search_result_model != False + # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation + search_settings_messages_model = SearchSettingsMessages.from_dict(search_settings_messages_model_json) + assert search_settings_messages_model != False - # Construct a model instance of SearchResult by calling from_dict on the json representation - search_result_model_dict = SearchResult.from_dict(search_result_model_json).__dict__ - search_result_model2 = SearchResult(**search_result_model_dict) + # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation + search_settings_messages_model_dict = SearchSettingsMessages.from_dict(search_settings_messages_model_json).__dict__ + search_settings_messages_model2 = SearchSettingsMessages(**search_settings_messages_model_dict) # Verify the model instances are equivalent - assert search_result_model == search_result_model2 + assert search_settings_messages_model == search_settings_messages_model2 # Convert model instance back to dict and verify no loss of data - search_result_model_json2 = search_result_model.to_dict() - assert search_result_model_json2 == search_result_model_json + search_settings_messages_model_json2 = search_settings_messages_model.to_dict() + assert search_settings_messages_model_json2 == search_settings_messages_model_json -class TestModel_SearchResultAnswer: +class TestModel_SearchSettingsSchemaMapping: """ - Test Class for SearchResultAnswer + Test Class for SearchSettingsSchemaMapping """ - def test_search_result_answer_serialization(self): + def test_search_settings_schema_mapping_serialization(self): """ - Test serialization/deserialization for SearchResultAnswer + Test serialization/deserialization for SearchSettingsSchemaMapping """ - # Construct a json representation of a SearchResultAnswer model - search_result_answer_model_json = {} - search_result_answer_model_json['text'] = 'testString' - search_result_answer_model_json['confidence'] = 0 + # Construct a json representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model_json = {} + search_settings_schema_mapping_model_json['url'] = 'testString' + search_settings_schema_mapping_model_json['body'] = 'testString' + search_settings_schema_mapping_model_json['title'] = 'testString' - # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation - search_result_answer_model = SearchResultAnswer.from_dict(search_result_answer_model_json) - assert search_result_answer_model != False + # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation + search_settings_schema_mapping_model = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json) + assert search_settings_schema_mapping_model != False - # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation - search_result_answer_model_dict = SearchResultAnswer.from_dict(search_result_answer_model_json).__dict__ - search_result_answer_model2 = SearchResultAnswer(**search_result_answer_model_dict) + # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation + search_settings_schema_mapping_model_dict = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json).__dict__ + search_settings_schema_mapping_model2 = SearchSettingsSchemaMapping(**search_settings_schema_mapping_model_dict) # Verify the model instances are equivalent - assert search_result_answer_model == search_result_answer_model2 + assert search_settings_schema_mapping_model == search_settings_schema_mapping_model2 # Convert model instance back to dict and verify no loss of data - search_result_answer_model_json2 = search_result_answer_model.to_dict() - assert search_result_answer_model_json2 == search_result_answer_model_json + search_settings_schema_mapping_model_json2 = search_settings_schema_mapping_model.to_dict() + assert search_settings_schema_mapping_model_json2 == search_settings_schema_mapping_model_json -class TestModel_SearchResultHighlight: +class TestModel_SearchSkillWarning: """ - Test Class for SearchResultHighlight + Test Class for SearchSkillWarning """ - def test_search_result_highlight_serialization(self): + def test_search_skill_warning_serialization(self): """ - Test serialization/deserialization for SearchResultHighlight + Test serialization/deserialization for SearchSkillWarning """ - # Construct a json representation of a SearchResultHighlight model - search_result_highlight_model_json = {} - search_result_highlight_model_json['body'] = ['testString'] - search_result_highlight_model_json['title'] = ['testString'] - search_result_highlight_model_json['url'] = ['testString'] - search_result_highlight_model_json['foo'] = ['testString'] + # Construct a json representation of a SearchSkillWarning model + search_skill_warning_model_json = {} + search_skill_warning_model_json['code'] = 'testString' + search_skill_warning_model_json['path'] = 'testString' + search_skill_warning_model_json['message'] = 'testString' - # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation - search_result_highlight_model = SearchResultHighlight.from_dict(search_result_highlight_model_json) - assert search_result_highlight_model != False + # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation + search_skill_warning_model = SearchSkillWarning.from_dict(search_skill_warning_model_json) + assert search_skill_warning_model != False - # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation - search_result_highlight_model_dict = SearchResultHighlight.from_dict(search_result_highlight_model_json).__dict__ - search_result_highlight_model2 = SearchResultHighlight(**search_result_highlight_model_dict) + # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation + search_skill_warning_model_dict = SearchSkillWarning.from_dict(search_skill_warning_model_json).__dict__ + search_skill_warning_model2 = SearchSkillWarning(**search_skill_warning_model_dict) # Verify the model instances are equivalent - assert search_result_highlight_model == search_result_highlight_model2 + assert search_skill_warning_model == search_skill_warning_model2 # Convert model instance back to dict and verify no loss of data - search_result_highlight_model_json2 = search_result_highlight_model.to_dict() - assert search_result_highlight_model_json2 == search_result_highlight_model_json - - # Test get_properties and set_properties methods. - search_result_highlight_model.set_properties({}) - actual_dict = search_result_highlight_model.get_properties() - assert actual_dict == {} - - expected_dict = {'foo': ['testString']} - search_result_highlight_model.set_properties(expected_dict) - actual_dict = search_result_highlight_model.get_properties() - assert actual_dict == expected_dict + search_skill_warning_model_json2 = search_skill_warning_model.to_dict() + assert search_skill_warning_model_json2 == search_skill_warning_model_json -class TestModel_SearchResultMetadata: +class TestModel_SessionResponse: """ - Test Class for SearchResultMetadata + Test Class for SessionResponse """ - def test_search_result_metadata_serialization(self): + def test_session_response_serialization(self): """ - Test serialization/deserialization for SearchResultMetadata + Test serialization/deserialization for SessionResponse """ - # Construct a json representation of a SearchResultMetadata model - search_result_metadata_model_json = {} - search_result_metadata_model_json['confidence'] = 72.5 - search_result_metadata_model_json['score'] = 72.5 + # Construct a json representation of a SessionResponse model + session_response_model_json = {} + session_response_model_json['session_id'] = 'testString' - # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation - search_result_metadata_model = SearchResultMetadata.from_dict(search_result_metadata_model_json) - assert search_result_metadata_model != False + # Construct a model instance of SessionResponse by calling from_dict on the json representation + session_response_model = SessionResponse.from_dict(session_response_model_json) + assert session_response_model != False - # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation - search_result_metadata_model_dict = SearchResultMetadata.from_dict(search_result_metadata_model_json).__dict__ - search_result_metadata_model2 = SearchResultMetadata(**search_result_metadata_model_dict) + # Construct a model instance of SessionResponse by calling from_dict on the json representation + session_response_model_dict = SessionResponse.from_dict(session_response_model_json).__dict__ + session_response_model2 = SessionResponse(**session_response_model_dict) # Verify the model instances are equivalent - assert search_result_metadata_model == search_result_metadata_model2 + assert session_response_model == session_response_model2 # Convert model instance back to dict and verify no loss of data - search_result_metadata_model_json2 = search_result_metadata_model.to_dict() - assert search_result_metadata_model_json2 == search_result_metadata_model_json + session_response_model_json2 = session_response_model.to_dict() + assert session_response_model_json2 == session_response_model_json -class TestModel_SearchSettings: +class TestModel_Skill: """ - Test Class for SearchSettings + Test Class for Skill """ - def test_search_settings_serialization(self): + def test_skill_serialization(self): """ - Test serialization/deserialization for SearchSettings + Test serialization/deserialization for Skill """ # Construct dict forms of any model objects needed in order to build this model. @@ -7474,270 +7575,10 @@ def test_search_settings_serialization(self): search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' - # Construct a json representation of a SearchSettings model - search_settings_model_json = {} - search_settings_model_json['discovery'] = search_settings_discovery_model - search_settings_model_json['messages'] = search_settings_messages_model - search_settings_model_json['schema_mapping'] = search_settings_schema_mapping_model - - # Construct a model instance of SearchSettings by calling from_dict on the json representation - search_settings_model = SearchSettings.from_dict(search_settings_model_json) - assert search_settings_model != False - - # Construct a model instance of SearchSettings by calling from_dict on the json representation - search_settings_model_dict = SearchSettings.from_dict(search_settings_model_json).__dict__ - search_settings_model2 = SearchSettings(**search_settings_model_dict) - - # Verify the model instances are equivalent - assert search_settings_model == search_settings_model2 - - # Convert model instance back to dict and verify no loss of data - search_settings_model_json2 = search_settings_model.to_dict() - assert search_settings_model_json2 == search_settings_model_json - - -class TestModel_SearchSettingsDiscovery: - """ - Test Class for SearchSettingsDiscovery - """ - - def test_search_settings_discovery_serialization(self): - """ - Test serialization/deserialization for SearchSettingsDiscovery - """ - - # Construct dict forms of any model objects needed in order to build this model. - - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - # Construct a json representation of a SearchSettingsDiscovery model - search_settings_discovery_model_json = {} - search_settings_discovery_model_json['instance_id'] = 'testString' - search_settings_discovery_model_json['project_id'] = 'testString' - search_settings_discovery_model_json['url'] = 'testString' - search_settings_discovery_model_json['max_primary_results'] = 10000 - search_settings_discovery_model_json['max_total_results'] = 10000 - search_settings_discovery_model_json['confidence_threshold'] = 0.0 - search_settings_discovery_model_json['highlight'] = True - search_settings_discovery_model_json['find_answers'] = True - search_settings_discovery_model_json['authentication'] = search_settings_discovery_authentication_model - - # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation - search_settings_discovery_model = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json) - assert search_settings_discovery_model != False - - # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation - search_settings_discovery_model_dict = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json).__dict__ - search_settings_discovery_model2 = SearchSettingsDiscovery(**search_settings_discovery_model_dict) - - # Verify the model instances are equivalent - assert search_settings_discovery_model == search_settings_discovery_model2 - - # Convert model instance back to dict and verify no loss of data - search_settings_discovery_model_json2 = search_settings_discovery_model.to_dict() - assert search_settings_discovery_model_json2 == search_settings_discovery_model_json - - -class TestModel_SearchSettingsDiscoveryAuthentication: - """ - Test Class for SearchSettingsDiscoveryAuthentication - """ - - def test_search_settings_discovery_authentication_serialization(self): - """ - Test serialization/deserialization for SearchSettingsDiscoveryAuthentication - """ - - # Construct a json representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model_json = {} - search_settings_discovery_authentication_model_json['basic'] = 'testString' - search_settings_discovery_authentication_model_json['bearer'] = 'testString' - - # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation - search_settings_discovery_authentication_model = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json) - assert search_settings_discovery_authentication_model != False - - # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation - search_settings_discovery_authentication_model_dict = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json).__dict__ - search_settings_discovery_authentication_model2 = SearchSettingsDiscoveryAuthentication(**search_settings_discovery_authentication_model_dict) - - # Verify the model instances are equivalent - assert search_settings_discovery_authentication_model == search_settings_discovery_authentication_model2 - - # Convert model instance back to dict and verify no loss of data - search_settings_discovery_authentication_model_json2 = search_settings_discovery_authentication_model.to_dict() - assert search_settings_discovery_authentication_model_json2 == search_settings_discovery_authentication_model_json - - -class TestModel_SearchSettingsMessages: - """ - Test Class for SearchSettingsMessages - """ - - def test_search_settings_messages_serialization(self): - """ - Test serialization/deserialization for SearchSettingsMessages - """ - - # Construct a json representation of a SearchSettingsMessages model - search_settings_messages_model_json = {} - search_settings_messages_model_json['success'] = 'testString' - search_settings_messages_model_json['error'] = 'testString' - search_settings_messages_model_json['no_result'] = 'testString' - - # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation - search_settings_messages_model = SearchSettingsMessages.from_dict(search_settings_messages_model_json) - assert search_settings_messages_model != False - - # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation - search_settings_messages_model_dict = SearchSettingsMessages.from_dict(search_settings_messages_model_json).__dict__ - search_settings_messages_model2 = SearchSettingsMessages(**search_settings_messages_model_dict) - - # Verify the model instances are equivalent - assert search_settings_messages_model == search_settings_messages_model2 - - # Convert model instance back to dict and verify no loss of data - search_settings_messages_model_json2 = search_settings_messages_model.to_dict() - assert search_settings_messages_model_json2 == search_settings_messages_model_json - - -class TestModel_SearchSettingsSchemaMapping: - """ - Test Class for SearchSettingsSchemaMapping - """ - - def test_search_settings_schema_mapping_serialization(self): - """ - Test serialization/deserialization for SearchSettingsSchemaMapping - """ - - # Construct a json representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model_json = {} - search_settings_schema_mapping_model_json['url'] = 'testString' - search_settings_schema_mapping_model_json['body'] = 'testString' - search_settings_schema_mapping_model_json['title'] = 'testString' - - # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation - search_settings_schema_mapping_model = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json) - assert search_settings_schema_mapping_model != False - - # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation - search_settings_schema_mapping_model_dict = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json).__dict__ - search_settings_schema_mapping_model2 = SearchSettingsSchemaMapping(**search_settings_schema_mapping_model_dict) - - # Verify the model instances are equivalent - assert search_settings_schema_mapping_model == search_settings_schema_mapping_model2 - - # Convert model instance back to dict and verify no loss of data - search_settings_schema_mapping_model_json2 = search_settings_schema_mapping_model.to_dict() - assert search_settings_schema_mapping_model_json2 == search_settings_schema_mapping_model_json - - -class TestModel_SearchSkillWarning: - """ - Test Class for SearchSkillWarning - """ - - def test_search_skill_warning_serialization(self): - """ - Test serialization/deserialization for SearchSkillWarning - """ - - # Construct a json representation of a SearchSkillWarning model - search_skill_warning_model_json = {} - search_skill_warning_model_json['code'] = 'testString' - search_skill_warning_model_json['path'] = 'testString' - search_skill_warning_model_json['message'] = 'testString' - - # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation - search_skill_warning_model = SearchSkillWarning.from_dict(search_skill_warning_model_json) - assert search_skill_warning_model != False - - # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation - search_skill_warning_model_dict = SearchSkillWarning.from_dict(search_skill_warning_model_json).__dict__ - search_skill_warning_model2 = SearchSkillWarning(**search_skill_warning_model_dict) - - # Verify the model instances are equivalent - assert search_skill_warning_model == search_skill_warning_model2 - - # Convert model instance back to dict and verify no loss of data - search_skill_warning_model_json2 = search_skill_warning_model.to_dict() - assert search_skill_warning_model_json2 == search_skill_warning_model_json - - -class TestModel_SessionResponse: - """ - Test Class for SessionResponse - """ - - def test_session_response_serialization(self): - """ - Test serialization/deserialization for SessionResponse - """ - - # Construct a json representation of a SessionResponse model - session_response_model_json = {} - session_response_model_json['session_id'] = 'testString' - - # Construct a model instance of SessionResponse by calling from_dict on the json representation - session_response_model = SessionResponse.from_dict(session_response_model_json) - assert session_response_model != False - - # Construct a model instance of SessionResponse by calling from_dict on the json representation - session_response_model_dict = SessionResponse.from_dict(session_response_model_json).__dict__ - session_response_model2 = SessionResponse(**session_response_model_dict) - - # Verify the model instances are equivalent - assert session_response_model == session_response_model2 - - # Convert model instance back to dict and verify no loss of data - session_response_model_json2 = session_response_model.to_dict() - assert session_response_model_json2 == session_response_model_json - - -class TestModel_Skill: - """ - Test Class for Skill - """ - - def test_skill_serialization(self): - """ - Test serialization/deserialization for Skill - """ - - # Construct dict forms of any model objects needed in order to build this model. - - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - search_settings_discovery_model = {} # SearchSettingsDiscovery - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - search_settings_messages_model = {} # SearchSettingsMessages - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - search_settings_model = {} # SearchSettings - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model # Construct a json representation of a Skill model skill_model_json = {} @@ -7938,6 +7779,812 @@ def test_skills_export_serialization(self): assert skills_export_model_json2 == skills_export_model_json +class TestModel_StatefulMessageResponse: + """ + Test Class for StatefulMessageResponse + """ + + def test_stateful_message_response_serialization(self): + """ + Test serialization/deserialization for StatefulMessageResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {'anyKey': 'anyValue'} + message_output_model['spelling'] = message_output_spelling_model + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a json representation of a StatefulMessageResponse model + stateful_message_response_model_json = {} + stateful_message_response_model_json['output'] = message_output_model + stateful_message_response_model_json['context'] = message_context_model + stateful_message_response_model_json['user_id'] = 'testString' + stateful_message_response_model_json['masked_output'] = message_output_model + stateful_message_response_model_json['masked_input'] = message_input_model + + # Construct a model instance of StatefulMessageResponse by calling from_dict on the json representation + stateful_message_response_model = StatefulMessageResponse.from_dict(stateful_message_response_model_json) + assert stateful_message_response_model != False + + # Construct a model instance of StatefulMessageResponse by calling from_dict on the json representation + stateful_message_response_model_dict = StatefulMessageResponse.from_dict(stateful_message_response_model_json).__dict__ + stateful_message_response_model2 = StatefulMessageResponse(**stateful_message_response_model_dict) + + # Verify the model instances are equivalent + assert stateful_message_response_model == stateful_message_response_model2 + + # Convert model instance back to dict and verify no loss of data + stateful_message_response_model_json2 = stateful_message_response_model.to_dict() + assert stateful_message_response_model_json2 == stateful_message_response_model_json + + +class TestModel_StatelessMessageContext: + """ + Test Class for StatelessMessageContext + """ + + def test_stateless_message_context_serialization(self): + """ + Test serialization/deserialization for StatelessMessageContext + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + stateless_message_context_global_model = {} # StatelessMessageContextGlobal + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + stateless_message_context_skills_model = {} # StatelessMessageContextSkills + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model + + # Construct a json representation of a StatelessMessageContext model + stateless_message_context_model_json = {} + stateless_message_context_model_json['global'] = stateless_message_context_global_model + stateless_message_context_model_json['skills'] = stateless_message_context_skills_model + stateless_message_context_model_json['integrations'] = {'anyKey': 'anyValue'} + + # Construct a model instance of StatelessMessageContext by calling from_dict on the json representation + stateless_message_context_model = StatelessMessageContext.from_dict(stateless_message_context_model_json) + assert stateless_message_context_model != False + + # Construct a model instance of StatelessMessageContext by calling from_dict on the json representation + stateless_message_context_model_dict = StatelessMessageContext.from_dict(stateless_message_context_model_json).__dict__ + stateless_message_context_model2 = StatelessMessageContext(**stateless_message_context_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_context_model == stateless_message_context_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_context_model_json2 = stateless_message_context_model.to_dict() + assert stateless_message_context_model_json2 == stateless_message_context_model_json + + +class TestModel_StatelessMessageContextGlobal: + """ + Test Class for StatelessMessageContextGlobal + """ + + def test_stateless_message_context_global_serialization(self): + """ + Test serialization/deserialization for StatelessMessageContextGlobal + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + # Construct a json representation of a StatelessMessageContextGlobal model + stateless_message_context_global_model_json = {} + stateless_message_context_global_model_json['system'] = message_context_global_system_model + stateless_message_context_global_model_json['session_id'] = 'testString' + + # Construct a model instance of StatelessMessageContextGlobal by calling from_dict on the json representation + stateless_message_context_global_model = StatelessMessageContextGlobal.from_dict(stateless_message_context_global_model_json) + assert stateless_message_context_global_model != False + + # Construct a model instance of StatelessMessageContextGlobal by calling from_dict on the json representation + stateless_message_context_global_model_dict = StatelessMessageContextGlobal.from_dict(stateless_message_context_global_model_json).__dict__ + stateless_message_context_global_model2 = StatelessMessageContextGlobal(**stateless_message_context_global_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_context_global_model == stateless_message_context_global_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_context_global_model_json2 = stateless_message_context_global_model.to_dict() + assert stateless_message_context_global_model_json2 == stateless_message_context_global_model_json + + +class TestModel_StatelessMessageContextSkills: + """ + Test Class for StatelessMessageContextSkills + """ + + def test_stateless_message_context_skills_serialization(self): + """ + Test serialization/deserialization for StatelessMessageContextSkills + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a json representation of a StatelessMessageContextSkills model + stateless_message_context_skills_model_json = {} + stateless_message_context_skills_model_json['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model_json['actions skill'] = stateless_message_context_skills_actions_skill_model + + # Construct a model instance of StatelessMessageContextSkills by calling from_dict on the json representation + stateless_message_context_skills_model = StatelessMessageContextSkills.from_dict(stateless_message_context_skills_model_json) + assert stateless_message_context_skills_model != False + + # Construct a model instance of StatelessMessageContextSkills by calling from_dict on the json representation + stateless_message_context_skills_model_dict = StatelessMessageContextSkills.from_dict(stateless_message_context_skills_model_json).__dict__ + stateless_message_context_skills_model2 = StatelessMessageContextSkills(**stateless_message_context_skills_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_context_skills_model == stateless_message_context_skills_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_context_skills_model_json2 = stateless_message_context_skills_model.to_dict() + assert stateless_message_context_skills_model_json2 == stateless_message_context_skills_model_json + + +class TestModel_StatelessMessageContextSkillsActionsSkill: + """ + Test Class for StatelessMessageContextSkillsActionsSkill + """ + + def test_stateless_message_context_skills_actions_skill_serialization(self): + """ + Test serialization/deserialization for StatelessMessageContextSkillsActionsSkill + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + # Construct a json representation of a StatelessMessageContextSkillsActionsSkill model + stateless_message_context_skills_actions_skill_model_json = {} + stateless_message_context_skills_actions_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['private_skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a model instance of StatelessMessageContextSkillsActionsSkill by calling from_dict on the json representation + stateless_message_context_skills_actions_skill_model = StatelessMessageContextSkillsActionsSkill.from_dict(stateless_message_context_skills_actions_skill_model_json) + assert stateless_message_context_skills_actions_skill_model != False + + # Construct a model instance of StatelessMessageContextSkillsActionsSkill by calling from_dict on the json representation + stateless_message_context_skills_actions_skill_model_dict = StatelessMessageContextSkillsActionsSkill.from_dict(stateless_message_context_skills_actions_skill_model_json).__dict__ + stateless_message_context_skills_actions_skill_model2 = StatelessMessageContextSkillsActionsSkill(**stateless_message_context_skills_actions_skill_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_context_skills_actions_skill_model == stateless_message_context_skills_actions_skill_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_context_skills_actions_skill_model_json2 = stateless_message_context_skills_actions_skill_model.to_dict() + assert stateless_message_context_skills_actions_skill_model_json2 == stateless_message_context_skills_actions_skill_model_json + + +class TestModel_StatelessMessageInput: + """ + Test Class for StatelessMessageInput + """ + + def test_stateless_message_input_serialization(self): + """ + Test serialization/deserialization for StatelessMessageInput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + stateless_message_input_options_model = {} # StatelessMessageInputOptions + stateless_message_input_options_model['restart'] = False + stateless_message_input_options_model['alternate_intents'] = False + stateless_message_input_options_model['async_callout'] = False + stateless_message_input_options_model['spelling'] = message_input_options_spelling_model + stateless_message_input_options_model['debug'] = False + + # Construct a json representation of a StatelessMessageInput model + stateless_message_input_model_json = {} + stateless_message_input_model_json['message_type'] = 'text' + stateless_message_input_model_json['text'] = 'testString' + stateless_message_input_model_json['intents'] = [runtime_intent_model] + stateless_message_input_model_json['entities'] = [runtime_entity_model] + stateless_message_input_model_json['suggestion_id'] = 'testString' + stateless_message_input_model_json['attachments'] = [message_input_attachment_model] + stateless_message_input_model_json['analytics'] = request_analytics_model + stateless_message_input_model_json['options'] = stateless_message_input_options_model + + # Construct a model instance of StatelessMessageInput by calling from_dict on the json representation + stateless_message_input_model = StatelessMessageInput.from_dict(stateless_message_input_model_json) + assert stateless_message_input_model != False + + # Construct a model instance of StatelessMessageInput by calling from_dict on the json representation + stateless_message_input_model_dict = StatelessMessageInput.from_dict(stateless_message_input_model_json).__dict__ + stateless_message_input_model2 = StatelessMessageInput(**stateless_message_input_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_input_model == stateless_message_input_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_input_model_json2 = stateless_message_input_model.to_dict() + assert stateless_message_input_model_json2 == stateless_message_input_model_json + + +class TestModel_StatelessMessageInputOptions: + """ + Test Class for StatelessMessageInputOptions + """ + + def test_stateless_message_input_options_serialization(self): + """ + Test serialization/deserialization for StatelessMessageInputOptions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a json representation of a StatelessMessageInputOptions model + stateless_message_input_options_model_json = {} + stateless_message_input_options_model_json['restart'] = False + stateless_message_input_options_model_json['alternate_intents'] = False + stateless_message_input_options_model_json['async_callout'] = False + stateless_message_input_options_model_json['spelling'] = message_input_options_spelling_model + stateless_message_input_options_model_json['debug'] = False + + # Construct a model instance of StatelessMessageInputOptions by calling from_dict on the json representation + stateless_message_input_options_model = StatelessMessageInputOptions.from_dict(stateless_message_input_options_model_json) + assert stateless_message_input_options_model != False + + # Construct a model instance of StatelessMessageInputOptions by calling from_dict on the json representation + stateless_message_input_options_model_dict = StatelessMessageInputOptions.from_dict(stateless_message_input_options_model_json).__dict__ + stateless_message_input_options_model2 = StatelessMessageInputOptions(**stateless_message_input_options_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_input_options_model == stateless_message_input_options_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_input_options_model_json2 = stateless_message_input_options_model.to_dict() + assert stateless_message_input_options_model_json2 == stateless_message_input_options_model_json + + +class TestModel_StatelessMessageResponse: + """ + Test Class for StatelessMessageResponse + """ + + def test_stateless_message_response_serialization(self): + """ + Test serialization/deserialization for StatelessMessageResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {'anyKey': 'anyValue'} + message_output_model['spelling'] = message_output_spelling_model + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + stateless_message_context_global_model = {} # StatelessMessageContextGlobal + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + stateless_message_context_skills_model = {} # StatelessMessageContextSkills + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model + + stateless_message_context_model = {} # StatelessMessageContext + stateless_message_context_model['global'] = stateless_message_context_global_model + stateless_message_context_model['skills'] = stateless_message_context_skills_model + stateless_message_context_model['integrations'] = {'anyKey': 'anyValue'} + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a json representation of a StatelessMessageResponse model + stateless_message_response_model_json = {} + stateless_message_response_model_json['output'] = message_output_model + stateless_message_response_model_json['context'] = stateless_message_context_model + stateless_message_response_model_json['masked_output'] = message_output_model + stateless_message_response_model_json['masked_input'] = message_input_model + stateless_message_response_model_json['user_id'] = 'testString' + + # Construct a model instance of StatelessMessageResponse by calling from_dict on the json representation + stateless_message_response_model = StatelessMessageResponse.from_dict(stateless_message_response_model_json) + assert stateless_message_response_model != False + + # Construct a model instance of StatelessMessageResponse by calling from_dict on the json representation + stateless_message_response_model_dict = StatelessMessageResponse.from_dict(stateless_message_response_model_json).__dict__ + stateless_message_response_model2 = StatelessMessageResponse(**stateless_message_response_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_response_model == stateless_message_response_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_response_model_json2 = stateless_message_response_model.to_dict() + assert stateless_message_response_model_json2 == stateless_message_response_model_json + + class TestModel_StatusError: """ Test Class for StatusError @@ -8923,6 +9570,7 @@ def test_runtime_response_generic_runtime_response_type_option_serialization(sel message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False @@ -9156,6 +9804,7 @@ def test_runtime_response_generic_runtime_response_type_suggestion_serialization message_input_options_model = {} # MessageInputOptions message_input_options_model['restart'] = False message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False message_input_options_model['return_context'] = False From a109e2e3f43442fdc0d0c7c09bdf3ccd0682628e Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 22 Feb 2024 16:48:08 -0600 Subject: [PATCH 414/455] feat(disco-v2): class changes --- ibm_watson/discovery_v2.py | 576 +++++---------------------------- test/unit/test_discovery_v2.py | 451 +++++++++----------------- 2 files changed, 242 insertions(+), 785 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index ba7aba4cd..3bfead3d6 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -10976,18 +10976,18 @@ class TableBodyCells: `column` location in the current table. :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :param List[TableRowHeaderIds] row_header_ids: (optional) A list of table row - header ids. - :param List[TableRowHeaderTexts] row_header_texts: (optional) A list of table - row header texts. - :param List[TableRowHeaderTextsNormalized] row_header_texts_normalized: - (optional) A list of table row header texts normalized. - :param List[TableColumnHeaderIds] column_header_ids: (optional) A list of table - column header ids. - :param List[TableColumnHeaderTexts] column_header_texts: (optional) A list of - table column header texts. - :param List[TableColumnHeaderTextsNormalized] column_header_texts_normalized: - (optional) A list of table column header texts normalized. + :param List[str] row_header_ids: (optional) A list of ID values that represent + the table row headers that are associated with this body cell. + :param List[str] row_header_texts: (optional) A list of row header values that + are associated with this body cell. + :param List[str] row_header_texts_normalized: (optional) A list of normalized + row header values that are associated with this body cell. + :param List[str] column_header_ids: (optional) A list of ID values that + represent the column headers that are associated with this body cell. + :param List[str] column_header_texts: (optional) A list of column header values + that are associated with this body cell. + :param List[str] column_header_texts_normalized: (optional) A list of normalized + column header values that are associated with this body cell. :param List[DocumentAttribute] attributes: (optional) A list of document attributes. """ @@ -11002,14 +11002,12 @@ def __init__( row_index_end: Optional[int] = None, column_index_begin: Optional[int] = None, column_index_end: Optional[int] = None, - row_header_ids: Optional[List['TableRowHeaderIds']] = None, - row_header_texts: Optional[List['TableRowHeaderTexts']] = None, - row_header_texts_normalized: Optional[ - List['TableRowHeaderTextsNormalized']] = None, - column_header_ids: Optional[List['TableColumnHeaderIds']] = None, - column_header_texts: Optional[List['TableColumnHeaderTexts']] = None, - column_header_texts_normalized: Optional[ - List['TableColumnHeaderTextsNormalized']] = None, + row_header_ids: Optional[List[str]] = None, + row_header_texts: Optional[List[str]] = None, + row_header_texts_normalized: Optional[List[str]] = None, + column_header_ids: Optional[List[str]] = None, + column_header_texts: Optional[List[str]] = None, + column_header_texts_normalized: Optional[List[str]] = None, attributes: Optional[List['DocumentAttribute']] = None, ) -> None: """ @@ -11030,19 +11028,18 @@ def __init__( `column` location in the current table. :param int column_index_end: (optional) The `end` index of this cell's `column` location in the current table. - :param List[TableRowHeaderIds] row_header_ids: (optional) A list of table - row header ids. - :param List[TableRowHeaderTexts] row_header_texts: (optional) A list of - table row header texts. - :param List[TableRowHeaderTextsNormalized] row_header_texts_normalized: - (optional) A list of table row header texts normalized. - :param List[TableColumnHeaderIds] column_header_ids: (optional) A list of - table column header ids. - :param List[TableColumnHeaderTexts] column_header_texts: (optional) A list - of table column header texts. - :param List[TableColumnHeaderTextsNormalized] - column_header_texts_normalized: (optional) A list of table column header - texts normalized. + :param List[str] row_header_ids: (optional) A list of ID values that + represent the table row headers that are associated with this body cell. + :param List[str] row_header_texts: (optional) A list of row header values + that are associated with this body cell. + :param List[str] row_header_texts_normalized: (optional) A list of + normalized row header values that are associated with this body cell. + :param List[str] column_header_ids: (optional) A list of ID values that + represent the column headers that are associated with this body cell. + :param List[str] column_header_texts: (optional) A list of column header + values that are associated with this body cell. + :param List[str] column_header_texts_normalized: (optional) A list of + normalized column header values that are associated with this body cell. :param List[DocumentAttribute] attributes: (optional) A list of document attributes. """ @@ -11080,34 +11077,21 @@ def from_dict(cls, _dict: Dict) -> 'TableBodyCells': if (column_index_end := _dict.get('column_index_end')) is not None: args['column_index_end'] = column_index_end if (row_header_ids := _dict.get('row_header_ids')) is not None: - args['row_header_ids'] = [ - TableRowHeaderIds.from_dict(v) for v in row_header_ids - ] + args['row_header_ids'] = row_header_ids if (row_header_texts := _dict.get('row_header_texts')) is not None: - args['row_header_texts'] = [ - TableRowHeaderTexts.from_dict(v) for v in row_header_texts - ] + args['row_header_texts'] = row_header_texts if (row_header_texts_normalized := _dict.get('row_header_texts_normalized')) is not None: - args['row_header_texts_normalized'] = [ - TableRowHeaderTextsNormalized.from_dict(v) - for v in row_header_texts_normalized - ] + args['row_header_texts_normalized'] = row_header_texts_normalized if (column_header_ids := _dict.get('column_header_ids')) is not None: - args['column_header_ids'] = [ - TableColumnHeaderIds.from_dict(v) for v in column_header_ids - ] + args['column_header_ids'] = column_header_ids if (column_header_texts := _dict.get('column_header_texts')) is not None: - args['column_header_texts'] = [ - TableColumnHeaderTexts.from_dict(v) for v in column_header_texts - ] + args['column_header_texts'] = column_header_texts if (column_header_texts_normalized := _dict.get('column_header_texts_normalized')) is not None: - args['column_header_texts_normalized'] = [ - TableColumnHeaderTextsNormalized.from_dict(v) - for v in column_header_texts_normalized - ] + args[ + 'column_header_texts_normalized'] = column_header_texts_normalized if (attributes := _dict.get('attributes')) is not None: args['attributes'] = [ DocumentAttribute.from_dict(v) for v in attributes @@ -11144,61 +11128,25 @@ def to_dict(self) -> Dict: 'column_index_end') and self.column_index_end is not None: _dict['column_index_end'] = self.column_index_end if hasattr(self, 'row_header_ids') and self.row_header_ids is not None: - row_header_ids_list = [] - for v in self.row_header_ids: - if isinstance(v, dict): - row_header_ids_list.append(v) - else: - row_header_ids_list.append(v.to_dict()) - _dict['row_header_ids'] = row_header_ids_list + _dict['row_header_ids'] = self.row_header_ids if hasattr(self, 'row_header_texts') and self.row_header_texts is not None: - row_header_texts_list = [] - for v in self.row_header_texts: - if isinstance(v, dict): - row_header_texts_list.append(v) - else: - row_header_texts_list.append(v.to_dict()) - _dict['row_header_texts'] = row_header_texts_list + _dict['row_header_texts'] = self.row_header_texts if hasattr(self, 'row_header_texts_normalized' ) and self.row_header_texts_normalized is not None: - row_header_texts_normalized_list = [] - for v in self.row_header_texts_normalized: - if isinstance(v, dict): - row_header_texts_normalized_list.append(v) - else: - row_header_texts_normalized_list.append(v.to_dict()) _dict[ - 'row_header_texts_normalized'] = row_header_texts_normalized_list + 'row_header_texts_normalized'] = self.row_header_texts_normalized if hasattr(self, 'column_header_ids') and self.column_header_ids is not None: - column_header_ids_list = [] - for v in self.column_header_ids: - if isinstance(v, dict): - column_header_ids_list.append(v) - else: - column_header_ids_list.append(v.to_dict()) - _dict['column_header_ids'] = column_header_ids_list + _dict['column_header_ids'] = self.column_header_ids if hasattr( self, 'column_header_texts') and self.column_header_texts is not None: - column_header_texts_list = [] - for v in self.column_header_texts: - if isinstance(v, dict): - column_header_texts_list.append(v) - else: - column_header_texts_list.append(v.to_dict()) - _dict['column_header_texts'] = column_header_texts_list + _dict['column_header_texts'] = self.column_header_texts if hasattr(self, 'column_header_texts_normalized' ) and self.column_header_texts_normalized is not None: - column_header_texts_normalized_list = [] - for v in self.column_header_texts_normalized: - if isinstance(v, dict): - column_header_texts_normalized_list.append(v) - else: - column_header_texts_normalized_list.append(v.to_dict()) _dict[ - 'column_header_texts_normalized'] = column_header_texts_normalized_list + 'column_header_texts_normalized'] = self.column_header_texts_normalized if hasattr(self, 'attributes') and self.attributes is not None: attributes_list = [] for v in self.attributes: @@ -11394,200 +11342,18 @@ def __ne__(self, other: 'TableCellValues') -> bool: return not self == other -class TableColumnHeaderIds: - """ - An array of values, each being the `id` value of a column header that is applicable to - the current cell. - - :param str id: (optional) The `id` value of a column header. - """ - - def __init__( - self, - *, - id: Optional[str] = None, - ) -> None: - """ - Initialize a TableColumnHeaderIds object. - - :param str id: (optional) The `id` value of a column header. - """ - self.id = id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderIds': - """Initialize a TableColumnHeaderIds object from a json dictionary.""" - args = {} - if (id := _dict.get('id')) is not None: - args['id'] = id - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableColumnHeaderIds 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, 'id') and self.id is not None: - _dict['id'] = self.id - 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 TableColumnHeaderIds object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableColumnHeaderIds') -> 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: 'TableColumnHeaderIds') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableColumnHeaderTexts: - """ - An array of values, each being the `text` value of a column header that is applicable - to the current cell. - - :param str text: (optional) The `text` value of a column header. - """ - - def __init__( - self, - *, - text: Optional[str] = None, - ) -> None: - """ - Initialize a TableColumnHeaderTexts object. - - :param str text: (optional) The `text` value of a column header. - """ - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTexts': - """Initialize a TableColumnHeaderTexts object from a json dictionary.""" - args = {} - if (text := _dict.get('text')) is not None: - args['text'] = text - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableColumnHeaderTexts 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, 'text') and self.text is not None: - _dict['text'] = self.text - 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 TableColumnHeaderTexts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableColumnHeaderTexts') -> 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: 'TableColumnHeaderTexts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableColumnHeaderTextsNormalized: - """ - If you provide customization input, the normalized version of the column header texts - according to the customization; otherwise, the same value as `column_header_texts`. - - :param str text_normalized: (optional) The normalized version of a column header - text. - """ - - def __init__( - self, - *, - text_normalized: Optional[str] = None, - ) -> None: - """ - Initialize a TableColumnHeaderTextsNormalized object. - - :param str text_normalized: (optional) The normalized version of a column - header text. - """ - self.text_normalized = text_normalized - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableColumnHeaderTextsNormalized': - """Initialize a TableColumnHeaderTextsNormalized object from a json dictionary.""" - args = {} - if (text_normalized := _dict.get('text_normalized')) is not None: - args['text_normalized'] = text_normalized - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableColumnHeaderTextsNormalized 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, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - 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 TableColumnHeaderTextsNormalized object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableColumnHeaderTextsNormalized') -> 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: 'TableColumnHeaderTextsNormalized') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TableColumnHeaders: """ Column-level cells, each applicable as a header to other cells in the same column as itself, of the current table. :param str cell_id: (optional) The unique ID of the cell in the current table. - :param dict location: (optional) The location of the column header cell in the - current table as defined by its `begin` and `end` offsets, respectfully, in the - input document. + :param TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, - the same value as `text`. + :param str text_normalized: (optional) Normalized column header text. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` @@ -11602,7 +11368,7 @@ def __init__( self, *, cell_id: Optional[str] = None, - location: Optional[dict] = None, + location: Optional['TableElementLocation'] = None, text: Optional[str] = None, text_normalized: Optional[str] = None, row_index_begin: Optional[int] = None, @@ -11615,14 +11381,12 @@ def __init__( :param str cell_id: (optional) The unique ID of the cell in the current table. - :param dict location: (optional) The location of the column header cell in - the current table as defined by its `begin` and `end` offsets, - respectfully, in the input document. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, - the normalized version of the cell text according to the customization; - otherwise, the same value as `text`. + :param str text_normalized: (optional) Normalized column header text. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` @@ -11648,7 +11412,7 @@ def from_dict(cls, _dict: Dict) -> 'TableColumnHeaders': if (cell_id := _dict.get('cell_id')) is not None: args['cell_id'] = cell_id if (location := _dict.get('location')) is not None: - args['location'] = location + args['location'] = TableElementLocation.from_dict(location) if (text := _dict.get('text')) is not None: args['text'] = text if (text_normalized := _dict.get('text_normalized')) is not None: @@ -11674,7 +11438,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -11792,9 +11559,9 @@ class TableHeaders: The contents of the current table's header. :param str cell_id: (optional) The unique ID of the cell in the current table. - :param dict location: (optional) The location of the table header cell in the - current table as defined by its `begin` and `end` offsets, respectfully, in the - input document. + :param TableElementLocation location: (optional) The numeric location of the + identified element in the document, represented with two integers labeled + `begin` and `end`. :param str text: (optional) The textual contents of the cell from the input document without associated markup content. :param int row_index_begin: (optional) The `begin` index of this cell's `row` @@ -11811,7 +11578,7 @@ def __init__( self, *, cell_id: Optional[str] = None, - location: Optional[dict] = None, + location: Optional['TableElementLocation'] = None, text: Optional[str] = None, row_index_begin: Optional[int] = None, row_index_end: Optional[int] = None, @@ -11823,9 +11590,9 @@ def __init__( :param str cell_id: (optional) The unique ID of the cell in the current table. - :param dict location: (optional) The location of the table header cell in - the current table as defined by its `begin` and `end` offsets, - respectfully, in the input document. + :param TableElementLocation location: (optional) The numeric location of + the identified element in the document, represented with two integers + labeled `begin` and `end`. :param str text: (optional) The textual contents of the cell from the input document without associated markup content. :param int row_index_begin: (optional) The `begin` index of this cell's @@ -11852,7 +11619,7 @@ def from_dict(cls, _dict: Dict) -> 'TableHeaders': if (cell_id := _dict.get('cell_id')) is not None: args['cell_id'] = cell_id if (location := _dict.get('location')) is not None: - args['location'] = location + args['location'] = TableElementLocation.from_dict(location) if (text := _dict.get('text')) is not None: args['text'] = text if (row_index_begin := _dict.get('row_index_begin')) is not None: @@ -11876,7 +11643,10 @@ def to_dict(self) -> Dict: if hasattr(self, 'cell_id') and self.cell_id is not None: _dict['cell_id'] = self.cell_id if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location + if isinstance(self.location, dict): + _dict['location'] = self.location + else: + _dict['location'] = self.location.to_dict() if hasattr(self, 'text') and self.text is not None: _dict['text'] = self.text if hasattr(self, @@ -12206,186 +11976,6 @@ def __ne__(self, other: 'TableResultTable') -> bool: return not self == other -class TableRowHeaderIds: - """ - An array of values, each being the `id` value of a row header that is applicable to - this body cell. - - :param str id: (optional) The `id` values of a row header. - """ - - def __init__( - self, - *, - id: Optional[str] = None, - ) -> None: - """ - Initialize a TableRowHeaderIds object. - - :param str id: (optional) The `id` values of a row header. - """ - self.id = id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableRowHeaderIds': - """Initialize a TableRowHeaderIds object from a json dictionary.""" - args = {} - if (id := _dict.get('id')) is not None: - args['id'] = id - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableRowHeaderIds 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, 'id') and self.id is not None: - _dict['id'] = self.id - 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 TableRowHeaderIds object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableRowHeaderIds') -> 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: 'TableRowHeaderIds') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableRowHeaderTexts: - """ - An array of values, each being the `text` value of a row header that is applicable to - this body cell. - - :param str text: (optional) The `text` value of a row header. - """ - - def __init__( - self, - *, - text: Optional[str] = None, - ) -> None: - """ - Initialize a TableRowHeaderTexts object. - - :param str text: (optional) The `text` value of a row header. - """ - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTexts': - """Initialize a TableRowHeaderTexts object from a json dictionary.""" - args = {} - if (text := _dict.get('text')) is not None: - args['text'] = text - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableRowHeaderTexts 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, 'text') and self.text is not None: - _dict['text'] = self.text - 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 TableRowHeaderTexts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableRowHeaderTexts') -> 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: 'TableRowHeaderTexts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableRowHeaderTextsNormalized: - """ - If you provide customization input, the normalized version of the row header texts - according to the customization; otherwise, the same value as `row_header_texts`. - - :param str text_normalized: (optional) The normalized version of a row header - text. - """ - - def __init__( - self, - *, - text_normalized: Optional[str] = None, - ) -> None: - """ - Initialize a TableRowHeaderTextsNormalized object. - - :param str text_normalized: (optional) The normalized version of a row - header text. - """ - self.text_normalized = text_normalized - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableRowHeaderTextsNormalized': - """Initialize a TableRowHeaderTextsNormalized object from a json dictionary.""" - args = {} - if (text_normalized := _dict.get('text_normalized')) is not None: - args['text_normalized'] = text_normalized - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableRowHeaderTextsNormalized 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, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - 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 TableRowHeaderTextsNormalized object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableRowHeaderTextsNormalized') -> 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: 'TableRowHeaderTextsNormalized') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TableRowHeaders: """ Row-level cells, each applicable as a header to other cells in the same row as itself, @@ -12397,9 +11987,7 @@ class TableRowHeaders: `begin` and `end`. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, - the same value as `text`. + :param str text_normalized: (optional) Normalized row header text. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` @@ -12432,9 +12020,7 @@ def __init__( labeled `begin` and `end`. :param str text: (optional) The textual contents of this cell from the input document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, - the normalized version of the cell text according to the customization; - otherwise, the same value as `text`. + :param str text_normalized: (optional) Normalized row header text. :param int row_index_begin: (optional) The `begin` index of this cell's `row` location in the current table. :param int row_index_end: (optional) The `end` index of this cell's `row` @@ -12608,7 +12194,9 @@ class TrainingExample: :param str document_id: The document ID associated with this training example. :param str collection_id: The collection ID associated with this training example. - :param int relevance: The relevance of the training example. + :param int relevance: The relevance score of the training example. Scores range + from `0` to `100`. Zero means not relevant. The higher the number, the more + relevant the example. :param datetime created: (optional) The date and time the example was created. :param datetime updated: (optional) The date and time the example was updated. """ @@ -12629,7 +12217,9 @@ def __init__( example. :param str collection_id: The collection ID associated with this training example. - :param int relevance: The relevance of the training example. + :param int relevance: The relevance score of the training example. Scores + range from `0` to `100`. Zero means not relevant. The higher the number, + the more relevant the example. """ self.document_id = document_id self.collection_id = collection_id @@ -12712,7 +12302,11 @@ class TrainingQuery: :param str natural_language_query: The natural text query that is used as the training query. :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + **natural_language_query** is applied. Only specify a filter if the documents + that you consider to be most relevant are not included in the top 100 results + when you submit test queries. If you specify a filter during training, apply the + same filter to queries that are submitted at runtime for optimal ranking + results. :param datetime created: (optional) The date and time the query was created. :param datetime updated: (optional) The date and time the query was updated. :param List[TrainingExample] examples: Array of training examples. @@ -12735,7 +12329,11 @@ def __init__( the training query. :param List[TrainingExample] examples: Array of training examples. :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. + **natural_language_query** is applied. Only specify a filter if the + documents that you consider to be most relevant are not included in the top + 100 results when you submit test queries. If you specify a filter during + training, apply the same filter to queries that are submitted at runtime + for optimal ranking results. """ self.query_id = query_id self.natural_language_query = natural_language_query diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index c8098805a..3b1008aa9 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -1861,7 +1861,7 @@ def test_query_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add( responses.POST, url, @@ -1973,7 +1973,7 @@ def test_query_required_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add( responses.POST, url, @@ -2011,7 +2011,7 @@ def test_query_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/query') - mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"anyKey": "anyValue"}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": [{"id": "id"}], "row_header_texts": [{"text": "text"}], "row_header_texts_normalized": [{"text_normalized": "text_normalized"}], "column_header_ids": [{"id": "id"}], "column_header_texts": [{"text": "text"}], "column_header_texts_normalized": [{"text_normalized": "text_normalized"}], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' + mock_response = '{"matching_results": 16, "results": [{"document_id": "document_id", "metadata": {"anyKey": "anyValue"}, "result_metadata": {"document_retrieval_source": "search", "collection_id": "collection_id", "confidence": 0}, "document_passages": [{"passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}], "aggregations": [{"type": "term", "field": "field", "count": 5, "name": "name", "results": [{"key": "key", "matching_results": 16, "relevancy": 9, "total_matching_documents": 24, "estimated_matching_results": 26, "aggregations": [{"anyKey": "anyValue"}]}]}], "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query", "suggested_refinements": [{"text": "text"}], "table_results": [{"table_id": "table_id", "source_document_id": "source_document_id", "collection_id": "collection_id", "table_html": "table_html", "table_html_offset": 17, "table": {"location": {"begin": 5, "end": 3}, "text": "text", "section_title": {"text": "text", "location": {"begin": 5, "end": 3}}, "title": {"text": "text", "location": {"begin": 5, "end": 3}}, "table_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "row_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "column_headers": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "text_normalized": "text_normalized", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16}], "key_value_pairs": [{"key": {"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}, "value": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text"}]}], "body_cells": [{"cell_id": "cell_id", "location": {"begin": 5, "end": 3}, "text": "text", "row_index_begin": 15, "row_index_end": 13, "column_index_begin": 18, "column_index_end": 16, "row_header_ids": ["row_header_ids"], "row_header_texts": ["row_header_texts"], "row_header_texts_normalized": ["row_header_texts_normalized"], "column_header_ids": ["column_header_ids"], "column_header_texts": ["column_header_texts"], "column_header_texts_normalized": ["column_header_texts_normalized"], "attributes": [{"type": "type", "text": "text", "location": {"begin": 5, "end": 3}}]}], "contexts": [{"text": "text", "location": {"begin": 5, "end": 3}}]}}], "passages": [{"passage_text": "passage_text", "passage_score": 13, "document_id": "document_id", "collection_id": "collection_id", "start_offset": 12, "end_offset": 10, "field": "field", "answers": [{"answer_text": "answer_text", "start_offset": 12, "end_offset": 10, "confidence": 0}]}]}' responses.add( responses.POST, url, @@ -3703,7 +3703,7 @@ def test_list_enrichments_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}]}' + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}]}' responses.add( responses.GET, url, @@ -3741,7 +3741,7 @@ def test_list_enrichments_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}]}' + mock_response = '{"enrichments": [{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}]}' responses.add( responses.GET, url, @@ -3784,7 +3784,7 @@ def test_create_enrichment_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' responses.add( responses.POST, url, @@ -3793,6 +3793,11 @@ def test_create_enrichment_all_params(self): status=201, ) + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + # Construct a dict representation of a EnrichmentOptions model enrichment_options_model = {} enrichment_options_model['languages'] = ['testString'] @@ -3803,6 +3808,11 @@ def test_create_enrichment_all_params(self): enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' # Construct a dict representation of a CreateEnrichment model create_enrichment_model = {} @@ -3844,7 +3854,7 @@ def test_create_enrichment_required_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' responses.add( responses.POST, url, @@ -3853,6 +3863,11 @@ def test_create_enrichment_required_params(self): status=201, ) + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + # Construct a dict representation of a EnrichmentOptions model enrichment_options_model = {} enrichment_options_model['languages'] = ['testString'] @@ -3863,6 +3878,11 @@ def test_create_enrichment_required_params(self): enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' # Construct a dict representation of a CreateEnrichment model create_enrichment_model = {} @@ -3902,7 +3922,7 @@ def test_create_enrichment_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' responses.add( responses.POST, url, @@ -3911,6 +3931,11 @@ def test_create_enrichment_value_error(self): status=201, ) + # Construct a dict representation of a WebhookHeader model + webhook_header_model = {} + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + # Construct a dict representation of a EnrichmentOptions model enrichment_options_model = {} enrichment_options_model['languages'] = ['testString'] @@ -3921,6 +3946,11 @@ def test_create_enrichment_value_error(self): enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' # Construct a dict representation of a CreateEnrichment model create_enrichment_model = {} @@ -3965,7 +3995,7 @@ def test_get_enrichment_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' responses.add( responses.GET, url, @@ -4005,7 +4035,7 @@ def test_get_enrichment_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' responses.add( responses.GET, url, @@ -4050,7 +4080,7 @@ def test_update_enrichment_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' responses.add( responses.POST, url, @@ -4098,7 +4128,7 @@ def test_update_enrichment_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/enrichments/testString') - mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0}}' + mock_response = '{"enrichment_id": "enrichment_id", "name": "name", "description": "description", "type": "part_of_speech", "options": {"languages": ["languages"], "entity_type": "entity_type", "regular_expression": "regular_expression", "result_field": "result_field", "classifier_id": "classifier_id", "model_id": "model_id", "confidence_threshold": 0, "top_k": 0, "url": "url", "version": "2023-03-31", "secret": "secret", "headers": {"name": "name", "value": "value"}, "location_encoding": "`utf-16`"}}' responses.add( responses.POST, url, @@ -6099,6 +6129,10 @@ def test_create_enrichment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + webhook_header_model = {} # WebhookHeader + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['languages'] = ['testString'] enrichment_options_model['entity_type'] = 'testString' @@ -6108,6 +6142,11 @@ def test_create_enrichment_serialization(self): enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' # Construct a json representation of a CreateEnrichment model create_enrichment_model_json = {} @@ -6723,6 +6762,10 @@ def test_enrichment_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + webhook_header_model = {} # WebhookHeader + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['languages'] = ['testString'] enrichment_options_model['entity_type'] = 'testString' @@ -6732,6 +6775,11 @@ def test_enrichment_serialization(self): enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' # Construct a json representation of a Enrichment model enrichment_model_json = {} @@ -6766,6 +6814,12 @@ def test_enrichment_options_serialization(self): Test serialization/deserialization for EnrichmentOptions """ + # Construct dict forms of any model objects needed in order to build this model. + + webhook_header_model = {} # WebhookHeader + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + # Construct a json representation of a EnrichmentOptions model enrichment_options_model_json = {} enrichment_options_model_json['languages'] = ['testString'] @@ -6776,6 +6830,11 @@ def test_enrichment_options_serialization(self): enrichment_options_model_json['model_id'] = 'testString' enrichment_options_model_json['confidence_threshold'] = 0 enrichment_options_model_json['top_k'] = 0 + enrichment_options_model_json['url'] = 'testString' + enrichment_options_model_json['version'] = '2023-03-31' + enrichment_options_model_json['secret'] = 'testString' + enrichment_options_model_json['headers'] = webhook_header_model + enrichment_options_model_json['location_encoding'] = '`utf-16`' # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation enrichment_options_model = EnrichmentOptions.from_dict(enrichment_options_model_json) @@ -6805,6 +6864,10 @@ def test_enrichments_serialization(self): # Construct dict forms of any model objects needed in order to build this model. + webhook_header_model = {} # WebhookHeader + webhook_header_model['name'] = 'testString' + webhook_header_model['value'] = 'testString' + enrichment_options_model = {} # EnrichmentOptions enrichment_options_model['languages'] = ['testString'] enrichment_options_model['entity_type'] = 'testString' @@ -6814,6 +6877,11 @@ def test_enrichments_serialization(self): enrichment_options_model['model_id'] = 'testString' enrichment_options_model['confidence_threshold'] = 0 enrichment_options_model['top_k'] = 0 + enrichment_options_model['url'] = 'testString' + enrichment_options_model['version'] = '2023-03-31' + enrichment_options_model['secret'] = 'testString' + enrichment_options_model['headers'] = webhook_header_model + enrichment_options_model['location_encoding'] = '`utf-16`' enrichment_model = {} # Enrichment enrichment_model['name'] = 'testString' @@ -7678,7 +7746,7 @@ def test_query_response_serialization(self): table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = {'anyKey': 'anyValue'} + table_headers_model['location'] = table_element_location_model table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 @@ -7697,7 +7765,7 @@ def test_query_response_serialization(self): table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = {'anyKey': 'anyValue'} + table_column_headers_model['location'] = table_element_location_model table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -7719,24 +7787,6 @@ def test_query_response_serialization(self): table_key_value_pairs_model['key'] = table_cell_key_model table_key_value_pairs_model['value'] = [table_cell_values_model] - table_row_header_ids_model = {} # TableRowHeaderIds - table_row_header_ids_model['id'] = 'testString' - - table_row_header_texts_model = {} # TableRowHeaderTexts - table_row_header_texts_model['text'] = 'testString' - - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized - table_row_header_texts_normalized_model['text_normalized'] = 'testString' - - table_column_header_ids_model = {} # TableColumnHeaderIds - table_column_header_ids_model['id'] = 'testString' - - table_column_header_texts_model = {} # TableColumnHeaderTexts - table_column_header_texts_model['text'] = 'testString' - - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized - table_column_header_texts_normalized_model['text_normalized'] = 'testString' - document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' @@ -7750,12 +7800,12 @@ def test_query_response_serialization(self): table_body_cells_model['row_index_end'] = 26 table_body_cells_model['column_index_begin'] = 26 table_body_cells_model['column_index_end'] = 26 - table_body_cells_model['row_header_ids'] = [table_row_header_ids_model] - table_body_cells_model['row_header_texts'] = [table_row_header_texts_model] - table_body_cells_model['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] - table_body_cells_model['column_header_ids'] = [table_column_header_ids_model] - table_body_cells_model['column_header_texts'] = [table_column_header_texts_model] - table_body_cells_model['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model['row_header_ids'] = ['testString'] + table_body_cells_model['row_header_texts'] = ['testString'] + table_body_cells_model['row_header_texts_normalized'] = ['testString'] + table_body_cells_model['column_header_ids'] = ['testString'] + table_body_cells_model['column_header_texts'] = ['testString'] + table_body_cells_model['column_header_texts_normalized'] = ['testString'] table_body_cells_model['attributes'] = [document_attribute_model] table_result_table_model = {} # TableResultTable @@ -8050,7 +8100,7 @@ def test_query_table_result_serialization(self): table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = {'anyKey': 'anyValue'} + table_headers_model['location'] = table_element_location_model table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 @@ -8069,7 +8119,7 @@ def test_query_table_result_serialization(self): table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = {'anyKey': 'anyValue'} + table_column_headers_model['location'] = table_element_location_model table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -8091,24 +8141,6 @@ def test_query_table_result_serialization(self): table_key_value_pairs_model['key'] = table_cell_key_model table_key_value_pairs_model['value'] = [table_cell_values_model] - table_row_header_ids_model = {} # TableRowHeaderIds - table_row_header_ids_model['id'] = 'testString' - - table_row_header_texts_model = {} # TableRowHeaderTexts - table_row_header_texts_model['text'] = 'testString' - - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized - table_row_header_texts_normalized_model['text_normalized'] = 'testString' - - table_column_header_ids_model = {} # TableColumnHeaderIds - table_column_header_ids_model['id'] = 'testString' - - table_column_header_texts_model = {} # TableColumnHeaderTexts - table_column_header_texts_model['text'] = 'testString' - - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized - table_column_header_texts_normalized_model['text_normalized'] = 'testString' - document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' @@ -8122,12 +8154,12 @@ def test_query_table_result_serialization(self): table_body_cells_model['row_index_end'] = 26 table_body_cells_model['column_index_begin'] = 26 table_body_cells_model['column_index_end'] = 26 - table_body_cells_model['row_header_ids'] = [table_row_header_ids_model] - table_body_cells_model['row_header_texts'] = [table_row_header_texts_model] - table_body_cells_model['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] - table_body_cells_model['column_header_ids'] = [table_column_header_ids_model] - table_body_cells_model['column_header_texts'] = [table_column_header_texts_model] - table_body_cells_model['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model['row_header_ids'] = ['testString'] + table_body_cells_model['row_header_texts'] = ['testString'] + table_body_cells_model['row_header_texts_normalized'] = ['testString'] + table_body_cells_model['column_header_ids'] = ['testString'] + table_body_cells_model['column_header_texts'] = ['testString'] + table_body_cells_model['column_header_texts_normalized'] = ['testString'] table_body_cells_model['attributes'] = [document_attribute_model] table_result_table_model = {} # TableResultTable @@ -8435,24 +8467,6 @@ def test_table_body_cells_serialization(self): table_element_location_model['begin'] = 26 table_element_location_model['end'] = 26 - table_row_header_ids_model = {} # TableRowHeaderIds - table_row_header_ids_model['id'] = 'testString' - - table_row_header_texts_model = {} # TableRowHeaderTexts - table_row_header_texts_model['text'] = 'testString' - - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized - table_row_header_texts_normalized_model['text_normalized'] = 'testString' - - table_column_header_ids_model = {} # TableColumnHeaderIds - table_column_header_ids_model['id'] = 'testString' - - table_column_header_texts_model = {} # TableColumnHeaderTexts - table_column_header_texts_model['text'] = 'testString' - - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized - table_column_header_texts_normalized_model['text_normalized'] = 'testString' - document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' @@ -8467,12 +8481,12 @@ def test_table_body_cells_serialization(self): table_body_cells_model_json['row_index_end'] = 26 table_body_cells_model_json['column_index_begin'] = 26 table_body_cells_model_json['column_index_end'] = 26 - table_body_cells_model_json['row_header_ids'] = [table_row_header_ids_model] - table_body_cells_model_json['row_header_texts'] = [table_row_header_texts_model] - table_body_cells_model_json['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] - table_body_cells_model_json['column_header_ids'] = [table_column_header_ids_model] - table_body_cells_model_json['column_header_texts'] = [table_column_header_texts_model] - table_body_cells_model_json['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model_json['row_header_ids'] = ['testString'] + table_body_cells_model_json['row_header_texts'] = ['testString'] + table_body_cells_model_json['row_header_texts_normalized'] = ['testString'] + table_body_cells_model_json['column_header_ids'] = ['testString'] + table_body_cells_model_json['column_header_texts'] = ['testString'] + table_body_cells_model_json['column_header_texts_normalized'] = ['testString'] table_body_cells_model_json['attributes'] = [document_attribute_model] # Construct a model instance of TableBodyCells by calling from_dict on the json representation @@ -8567,96 +8581,6 @@ def test_table_cell_values_serialization(self): assert table_cell_values_model_json2 == table_cell_values_model_json -class TestModel_TableColumnHeaderIds: - """ - Test Class for TableColumnHeaderIds - """ - - def test_table_column_header_ids_serialization(self): - """ - Test serialization/deserialization for TableColumnHeaderIds - """ - - # Construct a json representation of a TableColumnHeaderIds model - table_column_header_ids_model_json = {} - table_column_header_ids_model_json['id'] = 'testString' - - # Construct a model instance of TableColumnHeaderIds by calling from_dict on the json representation - table_column_header_ids_model = TableColumnHeaderIds.from_dict(table_column_header_ids_model_json) - assert table_column_header_ids_model != False - - # Construct a model instance of TableColumnHeaderIds by calling from_dict on the json representation - table_column_header_ids_model_dict = TableColumnHeaderIds.from_dict(table_column_header_ids_model_json).__dict__ - table_column_header_ids_model2 = TableColumnHeaderIds(**table_column_header_ids_model_dict) - - # Verify the model instances are equivalent - assert table_column_header_ids_model == table_column_header_ids_model2 - - # Convert model instance back to dict and verify no loss of data - table_column_header_ids_model_json2 = table_column_header_ids_model.to_dict() - assert table_column_header_ids_model_json2 == table_column_header_ids_model_json - - -class TestModel_TableColumnHeaderTexts: - """ - Test Class for TableColumnHeaderTexts - """ - - def test_table_column_header_texts_serialization(self): - """ - Test serialization/deserialization for TableColumnHeaderTexts - """ - - # Construct a json representation of a TableColumnHeaderTexts model - table_column_header_texts_model_json = {} - table_column_header_texts_model_json['text'] = 'testString' - - # Construct a model instance of TableColumnHeaderTexts by calling from_dict on the json representation - table_column_header_texts_model = TableColumnHeaderTexts.from_dict(table_column_header_texts_model_json) - assert table_column_header_texts_model != False - - # Construct a model instance of TableColumnHeaderTexts by calling from_dict on the json representation - table_column_header_texts_model_dict = TableColumnHeaderTexts.from_dict(table_column_header_texts_model_json).__dict__ - table_column_header_texts_model2 = TableColumnHeaderTexts(**table_column_header_texts_model_dict) - - # Verify the model instances are equivalent - assert table_column_header_texts_model == table_column_header_texts_model2 - - # Convert model instance back to dict and verify no loss of data - table_column_header_texts_model_json2 = table_column_header_texts_model.to_dict() - assert table_column_header_texts_model_json2 == table_column_header_texts_model_json - - -class TestModel_TableColumnHeaderTextsNormalized: - """ - Test Class for TableColumnHeaderTextsNormalized - """ - - def test_table_column_header_texts_normalized_serialization(self): - """ - Test serialization/deserialization for TableColumnHeaderTextsNormalized - """ - - # Construct a json representation of a TableColumnHeaderTextsNormalized model - table_column_header_texts_normalized_model_json = {} - table_column_header_texts_normalized_model_json['text_normalized'] = 'testString' - - # Construct a model instance of TableColumnHeaderTextsNormalized by calling from_dict on the json representation - table_column_header_texts_normalized_model = TableColumnHeaderTextsNormalized.from_dict(table_column_header_texts_normalized_model_json) - assert table_column_header_texts_normalized_model != False - - # Construct a model instance of TableColumnHeaderTextsNormalized by calling from_dict on the json representation - table_column_header_texts_normalized_model_dict = TableColumnHeaderTextsNormalized.from_dict(table_column_header_texts_normalized_model_json).__dict__ - table_column_header_texts_normalized_model2 = TableColumnHeaderTextsNormalized(**table_column_header_texts_normalized_model_dict) - - # Verify the model instances are equivalent - assert table_column_header_texts_normalized_model == table_column_header_texts_normalized_model2 - - # Convert model instance back to dict and verify no loss of data - table_column_header_texts_normalized_model_json2 = table_column_header_texts_normalized_model.to_dict() - assert table_column_header_texts_normalized_model_json2 == table_column_header_texts_normalized_model_json - - class TestModel_TableColumnHeaders: """ Test Class for TableColumnHeaders @@ -8667,10 +8591,16 @@ def test_table_column_headers_serialization(self): Test serialization/deserialization for TableColumnHeaders """ + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + # Construct a json representation of a TableColumnHeaders model table_column_headers_model_json = {} table_column_headers_model_json['cell_id'] = 'testString' - table_column_headers_model_json['location'] = {'anyKey': 'anyValue'} + table_column_headers_model_json['location'] = table_element_location_model table_column_headers_model_json['text'] = 'testString' table_column_headers_model_json['text_normalized'] = 'testString' table_column_headers_model_json['row_index_begin'] = 26 @@ -8735,10 +8665,16 @@ def test_table_headers_serialization(self): Test serialization/deserialization for TableHeaders """ + # Construct dict forms of any model objects needed in order to build this model. + + table_element_location_model = {} # TableElementLocation + table_element_location_model['begin'] = 26 + table_element_location_model['end'] = 26 + # Construct a json representation of a TableHeaders model table_headers_model_json = {} table_headers_model_json['cell_id'] = 'testString' - table_headers_model_json['location'] = {'anyKey': 'anyValue'} + table_headers_model_json['location'] = table_element_location_model table_headers_model_json['text'] = 'testString' table_headers_model_json['row_index_begin'] = 26 table_headers_model_json['row_index_end'] = 26 @@ -8830,7 +8766,7 @@ def test_table_result_table_serialization(self): table_headers_model = {} # TableHeaders table_headers_model['cell_id'] = 'testString' - table_headers_model['location'] = {'anyKey': 'anyValue'} + table_headers_model['location'] = table_element_location_model table_headers_model['text'] = 'testString' table_headers_model['row_index_begin'] = 26 table_headers_model['row_index_end'] = 26 @@ -8849,7 +8785,7 @@ def test_table_result_table_serialization(self): table_column_headers_model = {} # TableColumnHeaders table_column_headers_model['cell_id'] = 'testString' - table_column_headers_model['location'] = {'anyKey': 'anyValue'} + table_column_headers_model['location'] = table_element_location_model table_column_headers_model['text'] = 'testString' table_column_headers_model['text_normalized'] = 'testString' table_column_headers_model['row_index_begin'] = 26 @@ -8871,24 +8807,6 @@ def test_table_result_table_serialization(self): table_key_value_pairs_model['key'] = table_cell_key_model table_key_value_pairs_model['value'] = [table_cell_values_model] - table_row_header_ids_model = {} # TableRowHeaderIds - table_row_header_ids_model['id'] = 'testString' - - table_row_header_texts_model = {} # TableRowHeaderTexts - table_row_header_texts_model['text'] = 'testString' - - table_row_header_texts_normalized_model = {} # TableRowHeaderTextsNormalized - table_row_header_texts_normalized_model['text_normalized'] = 'testString' - - table_column_header_ids_model = {} # TableColumnHeaderIds - table_column_header_ids_model['id'] = 'testString' - - table_column_header_texts_model = {} # TableColumnHeaderTexts - table_column_header_texts_model['text'] = 'testString' - - table_column_header_texts_normalized_model = {} # TableColumnHeaderTextsNormalized - table_column_header_texts_normalized_model['text_normalized'] = 'testString' - document_attribute_model = {} # DocumentAttribute document_attribute_model['type'] = 'testString' document_attribute_model['text'] = 'testString' @@ -8902,12 +8820,12 @@ def test_table_result_table_serialization(self): table_body_cells_model['row_index_end'] = 26 table_body_cells_model['column_index_begin'] = 26 table_body_cells_model['column_index_end'] = 26 - table_body_cells_model['row_header_ids'] = [table_row_header_ids_model] - table_body_cells_model['row_header_texts'] = [table_row_header_texts_model] - table_body_cells_model['row_header_texts_normalized'] = [table_row_header_texts_normalized_model] - table_body_cells_model['column_header_ids'] = [table_column_header_ids_model] - table_body_cells_model['column_header_texts'] = [table_column_header_texts_model] - table_body_cells_model['column_header_texts_normalized'] = [table_column_header_texts_normalized_model] + table_body_cells_model['row_header_ids'] = ['testString'] + table_body_cells_model['row_header_texts'] = ['testString'] + table_body_cells_model['row_header_texts_normalized'] = ['testString'] + table_body_cells_model['column_header_ids'] = ['testString'] + table_body_cells_model['column_header_texts'] = ['testString'] + table_body_cells_model['column_header_texts_normalized'] = ['testString'] table_body_cells_model['attributes'] = [document_attribute_model] # Construct a json representation of a TableResultTable model @@ -8939,96 +8857,6 @@ def test_table_result_table_serialization(self): assert table_result_table_model_json2 == table_result_table_model_json -class TestModel_TableRowHeaderIds: - """ - Test Class for TableRowHeaderIds - """ - - def test_table_row_header_ids_serialization(self): - """ - Test serialization/deserialization for TableRowHeaderIds - """ - - # Construct a json representation of a TableRowHeaderIds model - table_row_header_ids_model_json = {} - table_row_header_ids_model_json['id'] = 'testString' - - # Construct a model instance of TableRowHeaderIds by calling from_dict on the json representation - table_row_header_ids_model = TableRowHeaderIds.from_dict(table_row_header_ids_model_json) - assert table_row_header_ids_model != False - - # Construct a model instance of TableRowHeaderIds by calling from_dict on the json representation - table_row_header_ids_model_dict = TableRowHeaderIds.from_dict(table_row_header_ids_model_json).__dict__ - table_row_header_ids_model2 = TableRowHeaderIds(**table_row_header_ids_model_dict) - - # Verify the model instances are equivalent - assert table_row_header_ids_model == table_row_header_ids_model2 - - # Convert model instance back to dict and verify no loss of data - table_row_header_ids_model_json2 = table_row_header_ids_model.to_dict() - assert table_row_header_ids_model_json2 == table_row_header_ids_model_json - - -class TestModel_TableRowHeaderTexts: - """ - Test Class for TableRowHeaderTexts - """ - - def test_table_row_header_texts_serialization(self): - """ - Test serialization/deserialization for TableRowHeaderTexts - """ - - # Construct a json representation of a TableRowHeaderTexts model - table_row_header_texts_model_json = {} - table_row_header_texts_model_json['text'] = 'testString' - - # Construct a model instance of TableRowHeaderTexts by calling from_dict on the json representation - table_row_header_texts_model = TableRowHeaderTexts.from_dict(table_row_header_texts_model_json) - assert table_row_header_texts_model != False - - # Construct a model instance of TableRowHeaderTexts by calling from_dict on the json representation - table_row_header_texts_model_dict = TableRowHeaderTexts.from_dict(table_row_header_texts_model_json).__dict__ - table_row_header_texts_model2 = TableRowHeaderTexts(**table_row_header_texts_model_dict) - - # Verify the model instances are equivalent - assert table_row_header_texts_model == table_row_header_texts_model2 - - # Convert model instance back to dict and verify no loss of data - table_row_header_texts_model_json2 = table_row_header_texts_model.to_dict() - assert table_row_header_texts_model_json2 == table_row_header_texts_model_json - - -class TestModel_TableRowHeaderTextsNormalized: - """ - Test Class for TableRowHeaderTextsNormalized - """ - - def test_table_row_header_texts_normalized_serialization(self): - """ - Test serialization/deserialization for TableRowHeaderTextsNormalized - """ - - # Construct a json representation of a TableRowHeaderTextsNormalized model - table_row_header_texts_normalized_model_json = {} - table_row_header_texts_normalized_model_json['text_normalized'] = 'testString' - - # Construct a model instance of TableRowHeaderTextsNormalized by calling from_dict on the json representation - table_row_header_texts_normalized_model = TableRowHeaderTextsNormalized.from_dict(table_row_header_texts_normalized_model_json) - assert table_row_header_texts_normalized_model != False - - # Construct a model instance of TableRowHeaderTextsNormalized by calling from_dict on the json representation - table_row_header_texts_normalized_model_dict = TableRowHeaderTextsNormalized.from_dict(table_row_header_texts_normalized_model_json).__dict__ - table_row_header_texts_normalized_model2 = TableRowHeaderTextsNormalized(**table_row_header_texts_normalized_model_dict) - - # Verify the model instances are equivalent - assert table_row_header_texts_normalized_model == table_row_header_texts_normalized_model2 - - # Convert model instance back to dict and verify no loss of data - table_row_header_texts_normalized_model_json2 = table_row_header_texts_normalized_model.to_dict() - assert table_row_header_texts_normalized_model_json2 == table_row_header_texts_normalized_model_json - - class TestModel_TableRowHeaders: """ Test Class for TableRowHeaders @@ -9253,6 +9081,37 @@ def test_update_document_classifier_serialization(self): assert update_document_classifier_model_json2 == update_document_classifier_model_json +class TestModel_WebhookHeader: + """ + Test Class for WebhookHeader + """ + + def test_webhook_header_serialization(self): + """ + Test serialization/deserialization for WebhookHeader + """ + + # Construct a json representation of a WebhookHeader model + webhook_header_model_json = {} + webhook_header_model_json['name'] = 'testString' + webhook_header_model_json['value'] = 'testString' + + # Construct a model instance of WebhookHeader by calling from_dict on the json representation + webhook_header_model = WebhookHeader.from_dict(webhook_header_model_json) + assert webhook_header_model != False + + # Construct a model instance of WebhookHeader by calling from_dict on the json representation + webhook_header_model_dict = WebhookHeader.from_dict(webhook_header_model_json).__dict__ + webhook_header_model2 = WebhookHeader(**webhook_header_model_dict) + + # Verify the model instances are equivalent + assert webhook_header_model == webhook_header_model2 + + # Convert model instance back to dict and verify no loss of data + webhook_header_model_json2 = webhook_header_model.to_dict() + assert webhook_header_model_json2 == webhook_header_model_json + + class TestModel_QueryAggregationQueryCalculationAggregation: """ Test Class for QueryAggregationQueryCalculationAggregation From f9cd926ba2e8d0cef8c3f8b4af8a61445343d3e3 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 26 Feb 2024 11:26:08 -0600 Subject: [PATCH 415/455] build(deploy): update to node v20 --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 16f3dda0c..37b3e9131 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -34,7 +34,7 @@ jobs: - name: Setup Node uses: actions/setup-node@v1 with: - node-version: 18 + node-version: 20 - name: Install Semantic Release dependencies run: | From 6d7fb8f52b0f35b165cfb21088126d723331db88 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 26 Feb 2024 13:02:48 -0600 Subject: [PATCH 416/455] docs: update readme and secrets baseline --- .secrets.baseline | 36 +++++++++++++++++++++++------------- README.md | 19 +++++++++++++++++-- 2 files changed, 40 insertions(+), 15 deletions(-) diff --git a/.secrets.baseline b/.secrets.baseline index 400f98f69..171a5e191 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -3,7 +3,7 @@ "files": "package-lock.json|^.secrets.baseline$", "lines": null }, - "generated_at": "2023-03-17T19:47:10Z", + "generated_at": "2024-02-26T19:01:03Z", "plugins_used": [ { "name": "AWSKeyDetector" @@ -70,7 +70,7 @@ "hashed_secret": "d9e9019d9eb455a3d72a3bc252c26927bb148a10", "is_secret": false, "is_verified": false, - "line_number": 119, + "line_number": 118, "type": "Secret Keyword", "verified_result": null }, @@ -78,7 +78,7 @@ "hashed_secret": "32e8612d8ca77c7ea8374aa7918db8e5df9252ed", "is_secret": false, "is_verified": false, - "line_number": 163, + "line_number": 162, "type": "Secret Keyword", "verified_result": null } @@ -98,7 +98,7 @@ "hashed_secret": "e8fc807ce6fbcda13f91c5b64850173873de0cdc", "is_secret": false, "is_verified": false, - "line_number": 5220, + "line_number": 5683, "type": "Secret Keyword", "verified_result": null }, @@ -106,7 +106,7 @@ "hashed_secret": "fdee05598fdd57ff8e9ae29e92c25a04f2c52fa6", "is_secret": false, "is_verified": false, - "line_number": 5221, + "line_number": 5684, "type": "Secret Keyword", "verified_result": null } @@ -136,7 +136,7 @@ "hashed_secret": "d506bd5213c46bd49e16c634754ad70113408252", "is_secret": false, "is_verified": false, - "line_number": 7661, + "line_number": 7986, "type": "Secret Keyword", "verified_result": null }, @@ -144,7 +144,7 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 11192, + "line_number": 11590, "type": "Secret Keyword", "verified_result": null } @@ -154,7 +154,7 @@ "hashed_secret": "d506bd5213c46bd49e16c634754ad70113408252", "is_secret": false, "is_verified": false, - "line_number": 1333, + "line_number": 1393, "type": "Secret Keyword", "verified_result": null }, @@ -162,7 +162,7 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 6510, + "line_number": 8441, "type": "Secret Keyword", "verified_result": null } @@ -172,7 +172,7 @@ "hashed_secret": "8318df9ecda039deac9868adf1944a29a95c7114", "is_secret": false, "is_verified": false, - "line_number": 6733, + "line_number": 7053, "type": "Secret Keyword", "verified_result": null }, @@ -180,7 +180,7 @@ "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 7882, + "line_number": 8245, "type": "Secret Keyword", "verified_result": null }, @@ -188,17 +188,27 @@ "hashed_secret": "b8e758b5ad59a72f146fcf065239d5c7b695a39a", "is_secret": false, "is_verified": false, - "line_number": 10064, + "line_number": 10479, "type": "Hex High Entropy String", "verified_result": null } ], + "test/unit/test_discovery_v2.py": [ + { + "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", + "is_secret": false, + "is_verified": false, + "line_number": 6882, + "type": "Secret Keyword", + "verified_result": null + } + ], "test/unit/test_speech_to_text_v1.py": [ { "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", "is_secret": false, "is_verified": false, - "line_number": 411, + "line_number": 432, "type": "Secret Keyword", "verified_result": null } diff --git a/README.md b/README.md index d09f490b0..a0aea98db 100755 --- a/README.md +++ b/README.md @@ -176,7 +176,7 @@ discovery = DiscoveryV1(version='2019-04-30', discovery.set_service_url('') ``` -### Username and password +#### Username and password ```python from ibm_watson import DiscoveryV1 @@ -187,7 +187,7 @@ discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) discovery.set_service_url('') ``` -### No Authentication +#### No Authentication ```python from ibm_watson import DiscoveryV1 @@ -198,6 +198,21 @@ discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) discovery.set_service_url('') ``` +### MCSP + +To use the SDK through a third party cloud provider (such as AWS), use the `MCSPAuthenticator`. This will require the base endpoint URL for the MCSP token service (e.g. https://iam.platform.saas.ibm.com) and an apikey. + +```python +from ibm_watson import AssistantV2 +from ibm_cloud_sdk_core.authenticators import MCSPAuthenticator + +# In the constructor, letting the SDK manage the token +authenticator = MCSPAuthenticator('apikey', 'token_service_endpoint') +assistant = AssistantV2(version='2023-06-15', + authenticator=authenticator) +assistant.set_service_url('') +``` + ## Python version Tested on Python 3.9, 3.10, and 3.11. From 3c2bc6f5f74a450bc51663ae0fc5e121e49bc356 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 13 Mar 2024 13:03:39 -0500 Subject: [PATCH 417/455] fix(stt): change smartFormattingVersion to an int --- ibm_watson/speech_to_text_v1.py | 16 ++++++++-------- test/unit/test_speech_to_text_v1.py | 8 ++++---- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index f6d1022bc..c1b3be1fa 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -209,7 +209,7 @@ def recognize( timestamps: Optional[bool] = None, profanity_filter: Optional[bool] = None, smart_formatting: Optional[bool] = None, - smart_formatting_version: Optional[bool] = None, + smart_formatting_version: Optional[int] = None, speaker_labels: Optional[bool] = None, grammar_name: Optional[str] = None, redaction: Optional[bool] = None, @@ -447,9 +447,9 @@ def recognize( (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). - :param bool smart_formatting_version: (optional) Smart formatting version - is for next-generation models and that is supported in US English, - Brazilian Portuguese, French and German languages. + :param int smart_formatting_version: (optional) Smart formatting version is + for next-generation models and that is supported in US English, Brazilian + Portuguese, French and German languages. :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. @@ -818,7 +818,7 @@ def create_job( timestamps: Optional[bool] = None, profanity_filter: Optional[bool] = None, smart_formatting: Optional[bool] = None, - smart_formatting_version: Optional[bool] = None, + smart_formatting_version: Optional[int] = None, speaker_labels: Optional[bool] = None, grammar_name: Optional[str] = None, redaction: Optional[bool] = None, @@ -1106,9 +1106,9 @@ def create_job( (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). - :param bool smart_formatting_version: (optional) Smart formatting version - is for next-generation models and that is supported in US English, - Brazilian Portuguese, French and German languages. + :param int smart_formatting_version: (optional) Smart formatting version is + for next-generation models and that is supported in US English, Brazilian + Portuguese, French and German languages. :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. diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 922c7815a..304752966 100644 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -237,7 +237,7 @@ def test_recognize_all_params(self): timestamps = False profanity_filter = True smart_formatting = False - smart_formatting_version = False + smart_formatting_version = 0 speaker_labels = False grammar_name = 'testString' redaction = False @@ -299,7 +299,7 @@ def test_recognize_all_params(self): assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string - assert 'smart_formatting_version={}'.format('true' if smart_formatting_version else 'false') in query_string + assert 'smart_formatting_version={}'.format(smart_formatting_version) in query_string assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string assert 'grammar_name={}'.format(grammar_name) in query_string assert 'redaction={}'.format('true' if redaction else 'false') in query_string @@ -657,7 +657,7 @@ def test_create_job_all_params(self): timestamps = False profanity_filter = True smart_formatting = False - smart_formatting_version = False + smart_formatting_version = 0 speaker_labels = False grammar_name = 'testString' redaction = False @@ -731,7 +731,7 @@ def test_create_job_all_params(self): assert 'timestamps={}'.format('true' if timestamps else 'false') in query_string assert 'profanity_filter={}'.format('true' if profanity_filter else 'false') in query_string assert 'smart_formatting={}'.format('true' if smart_formatting else 'false') in query_string - assert 'smart_formatting_version={}'.format('true' if smart_formatting_version else 'false') in query_string + assert 'smart_formatting_version={}'.format(smart_formatting_version) in query_string assert 'speaker_labels={}'.format('true' if speaker_labels else 'false') in query_string assert 'grammar_name={}'.format(grammar_name) in query_string assert 'redaction={}'.format('true' if redaction else 'false') in query_string From aa3e7525a8977b2b7252d23873427722fcf8a2eb Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 13 Mar 2024 13:06:45 -0500 Subject: [PATCH 418/455] fix(wss): add smartFormattingVersion param --- ibm_watson/speech_to_text_v1_adapter.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 5b0fa08d7..fedc5af5e 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -42,6 +42,7 @@ def recognize_using_websocket(self, timestamps=None, profanity_filter=None, smart_formatting=None, + smart_formatting_version=None, speaker_labels=None, http_proxy_host=None, http_proxy_port=None, @@ -175,6 +176,9 @@ def recognize_using_websocket(self, **Note:** Applies to US English, Japanese, and Spanish transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). + :param int smart_formatting_version: (optional) Smart formatting version is + for next-generation models and that is supported in US English, Brazilian + Portuguese, French and German languages. :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. @@ -360,6 +364,7 @@ def recognize_using_websocket(self, 'timestamps': timestamps, 'profanity_filter': profanity_filter, 'smart_formatting': smart_formatting, + 'smart_formatting_version': smart_formatting_version, 'speaker_labels': speaker_labels, 'grammar_name': grammar_name, 'redaction': redaction, From 81cc318d3ff6333e9efdd660aea942261893a6df Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 13 Mar 2024 14:14:48 -0500 Subject: [PATCH 419/455] build(version): fix versioning --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 3f0bf36fc..3238a4cc3 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 7.0.1 +current_version = 8.0.1 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 2f21dd167..49920925b 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '7.0.1' +__version__ = '8.0.1' diff --git a/setup.py b/setup.py index 8c8bc7c3a..06d519f81 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '7.0.1' +__version__ = '8.0.1' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From 7c6aaabb8b35278c0445514dc20792504c9feab9 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 13 Mar 2024 14:16:34 -0500 Subject: [PATCH 420/455] build(deploy): upgrade to setup-node v2 --- .github/workflows/deploy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 37b3e9131..45b7fee7c 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -32,7 +32,7 @@ jobs: python-version: '3.11' - name: Setup Node - uses: actions/setup-node@v1 + uses: actions/setup-node@v2 with: node-version: 20 From 050b7a97887b405bf613f1fc57544329e2fabd5d Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 15 Mar 2024 10:16:50 -0500 Subject: [PATCH 421/455] docs(changelog): update with version 8.0.0 info --- CHANGELOG.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9116f1278..df089f2a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,20 @@ +# [8.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v7.0.1...v8.0.0) (2024-02-26) + + +### Features + +* **disco-v2:** class changes ([a109e2e](https://github.com/watson-developer-cloud/python-sdk/commit/a109e2e3f43442fdc0d0c7c09bdf3ccd0682628e)) +* **disco-v2:** new params for EnrichmentOptions ([d980178](https://github.com/watson-developer-cloud/python-sdk/commit/d980178de2ffbf9ffd491113a9a5fd1f82ed4557)) +* **nlu:** add support for userMetadata param ([134fa6d](https://github.com/watson-developer-cloud/python-sdk/commit/134fa6d868396875a33806d1e688156ceecd60c5)) +* **stt:** new params smart_formatting_version, force, mapping_only ([0fa495c](https://github.com/watson-developer-cloud/python-sdk/commit/0fa495cf24438d7a937904735f1dd23e33f3cd31)) +* **wa-v2:** new params orchestration and asyncCallout ([69523c5](https://github.com/watson-developer-cloud/python-sdk/commit/69523c5f023717ff911b714e2a58571f19b51b04)) +* **wa-v2:** support for private variables ([6cd5eba](https://github.com/watson-developer-cloud/python-sdk/commit/6cd5ebae52f93ab64f89bb1dea52b3ef4b27f444)) + + +### BREAKING CHANGES + +* **wa-v2:** Renaming and changing of multiple interfaces + ## [7.0.1](https://github.com/watson-developer-cloud/python-sdk/compare/v7.0.0...v7.0.1) (2022-08-07) From 460593f48fe7e32ea3fc205da05d1dad7318255b Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 15 May 2024 14:15:35 -0500 Subject: [PATCH 422/455] feat(discov2): add ocr_enabled parameter --- ibm_watson/discovery_v2.py | 425 +++++++++++++++++++++------------ test/unit/test_discovery_v2.py | 51 ++-- 2 files changed, 304 insertions(+), 172 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index 3bfead3d6..f3ede4e61 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -143,6 +143,8 @@ def create_project( project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. + The Intelligent Document Processing (IDP) project type is available from + IBM Cloud-managed instances only. :param DefaultQueryParams default_query_parameters: (optional) Default query parameters for this project. :param dict headers: A `dict` containing the request headers @@ -204,8 +206,9 @@ def get_project( Get details on the specified project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object @@ -256,8 +259,9 @@ def update_project( Update the specified project's name. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param str name: (optional) The new name to give this project. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -317,8 +321,9 @@ def delete_project( **Important:** Deleting a project deletes everything that is part of the specified project, including all collections. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -369,8 +374,9 @@ def list_fields( Gets a list of the unique fields (and their types) stored in the specified collections. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param List[str] collection_ids: (optional) Comma separated list of the collection IDs. If this parameter is not specified, all collections in the project are used. @@ -427,8 +433,9 @@ def list_collections( Lists existing collections for the specified project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object @@ -474,6 +481,7 @@ def create_collection( *, description: Optional[str] = None, language: Optional[str] = None, + ocr_enabled: Optional[bool] = None, enrichments: Optional[List['CollectionEnrichment']] = None, **kwargs, ) -> DetailedResponse: @@ -482,13 +490,17 @@ def create_collection( Create a new collection in the specified project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param str name: The name of the collection. :param str description: (optional) A description of the collection. :param str language: (optional) The language of the collection. For a list of supported languages, see the [product documentation](/docs/discovery-data?topic=discovery-data-language-support). + :param bool ocr_enabled: (optional) If set to `true`, optical character + recognition (OCR) is enabled. For more information, see [Optical character + recognition](/docs/discovery-data?topic=discovery-data-collections#ocr). :param List[CollectionEnrichment] enrichments: (optional) An array of enrichments that are applied to this collection. To get a list of enrichments that are available for a project, use the [List @@ -524,6 +536,7 @@ def create_collection( 'name': name, 'description': description, 'language': language, + 'ocr_enabled': ocr_enabled, 'enrichments': enrichments, } data = {k: v for (k, v) in data.items() if v is not None} @@ -561,9 +574,11 @@ def get_collection( Get details about the specified collection. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) 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 with `dict` result representing a `CollectionDetails` object @@ -612,6 +627,7 @@ def update_collection( *, name: Optional[str] = None, description: Optional[str] = None, + ocr_enabled: Optional[bool] = None, enrichments: Optional[List['CollectionEnrichment']] = None, **kwargs, ) -> DetailedResponse: @@ -632,11 +648,16 @@ def update_collection( enrichments are applied, specify an empty `normalizations` object (`[]`) in the request. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param str name: (optional) The new name of the collection. :param str description: (optional) The new description of the collection. + :param bool ocr_enabled: (optional) If set to `true`, optical character + recognition (OCR) is enabled. For more information, see [Optical character + recognition](/docs/discovery-data?topic=discovery-data-collections#ocr). :param List[CollectionEnrichment] enrichments: (optional) An array of enrichments that are applied to this collection. :param dict headers: A `dict` containing the request headers @@ -665,6 +686,7 @@ def update_collection( data = { 'name': name, 'description': description, + 'ocr_enabled': ocr_enabled, 'enrichments': enrichments, } data = {k: v for (k, v) in data.items() if v is not None} @@ -704,9 +726,11 @@ def delete_collection( Deletes the specified collection from the project. All documents stored in the specified collection and not shared is also deleted. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) 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 @@ -772,9 +796,11 @@ def list_documents( **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and later installed instances, and from IBM Cloud-managed instances. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param int count: (optional) The maximum number of documents to return. Up to 1,000 documents are returned by default. The maximum number allowed is 10,000. @@ -893,9 +919,11 @@ def add_document( a file is added to a collection, see the [product documentation](/docs/discovery-data?topic=discovery-data-index-overview#field-name-limits). - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param BinaryIO file: (optional) **Add a document**: The content of the document to ingest. For the supported file types and maximum supported file size limits when adding a document, see [the @@ -989,9 +1017,11 @@ def get_document( **Note**: This method is available only from Cloud Pak for Data version 4.0.9 and later installed instances, and from IBM Cloud-managed instances. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param str document_id: The ID of the document. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1066,9 +1096,11 @@ def update_document( existing child documents are overwritten, even if the updated version of the document has fewer child documents. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param str document_id: The ID of the document. :param BinaryIO file: (optional) **Add a document**: The content of the document to ingest. For the supported file types and maximum supported file @@ -1175,9 +1207,11 @@ def delete_document( document instead. You can get the document ID of the original document from the `parent_document_id` of the subdocument result. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param str document_id: The ID of the document. :param bool x_watson_discovery_force: (optional) When `true`, the uploaded document is added to the collection even if the data for that collection is @@ -1269,8 +1303,9 @@ def query( The length of the UTF-8 encoding of the POST body cannot exceed 10,000 bytes, which is roughly equivalent to 10,000 characters in English. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param List[str] collection_ids: (optional) A comma-separated list of collection IDs to be queried against. :param str filter: (optional) Searches for documents that match the @@ -1419,8 +1454,9 @@ def get_autocompletion( based on terms from the project's search history, and the project does not learn from previous user choices. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param str prefix: The prefix to use for autocompletion. For example, the prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. :param List[str] collection_ids: (optional) Comma separated list of the @@ -1493,9 +1529,11 @@ def query_collection_notices( Finds collection-level notices (errors and warnings) that are generated when documents are ingested. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param str filter: (optional) Searches for documents that match the Discovery Query Language criteria that is specified as input. Filter calls are cached and are faster than query calls because the results are not @@ -1584,8 +1622,9 @@ def query_notices( Finds project-level notices (errors and warnings). Currently, project-level notices are generated by relevancy training. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param str filter: (optional) Searches for documents that match the Discovery Query Language criteria that is specified as input. Filter calls are cached and are faster than query calls because the results are not @@ -1671,9 +1710,11 @@ def get_stopword_list( about the default stop words lists that are applied to queries, see [the product documentation](/docs/discovery-data?topic=discovery-data-stopwords). - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) 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 with `dict` result representing a `StopWordList` object @@ -1737,9 +1778,11 @@ def create_stopword_list( stop words. For information about the default stop words lists per language, see [the product documentation](/docs/discovery-data?topic=discovery-data-stopwords). - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param List[str] stopwords: (optional) List of stop words. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1803,9 +1846,11 @@ def delete_stopword_list( collection. After a custom stop words list is deleted, the default stop words list is used. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) 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 @@ -1858,9 +1903,11 @@ def list_expansions( Returns the current expansion list for the specified collection. If an expansion list is not specified, an empty expansions array is returned. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) 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 with `dict` result representing a `Expansions` object @@ -1918,9 +1965,11 @@ def create_expansions( of a query beyond exact matches. The maximum number of expanded terms allowed per collection is 5,000. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param List[Expansion] expansions: An array of query expansion definitions. Each object in the **expansions** array represents a term or set of terms that will be expanded into other terms. Each expansion object can be @@ -1998,9 +2047,11 @@ def delete_expansions( Removes the expansion information for this collection. To disable query expansion for a collection, delete the expansion list. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) 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 @@ -2055,8 +2106,9 @@ def get_component_settings( Returns default configuration settings for components. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ComponentSettingsResponse` object @@ -2110,8 +2162,9 @@ def list_training_queries( List the training queries for the specified project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingQuerySet` object @@ -2161,8 +2214,9 @@ def delete_training_queries( Removes all training queries for the specified project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2217,8 +2271,9 @@ def create_training_query( and natural language query. **Note**: You cannot apply relevancy training to a `content_mining` project type. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param str natural_language_query: The natural text query that is used as the training query. :param List[TrainingExample] examples: Array of training examples. @@ -2294,8 +2349,9 @@ def get_training_query( Get details for a specific training data query, including the query string and all examples. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -2354,8 +2410,9 @@ def update_training_query( Updates an existing training query and its examples. You must resubmit all of the examples with the update request. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param str query_id: The ID of the query used for training. :param str natural_language_query: The natural text query that is used as the training query. @@ -2436,8 +2493,9 @@ def delete_training_query( To delete an example, use the *Update a training query* method and omit the example that you want to delete from the example set. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -2495,8 +2553,9 @@ def list_enrichments( *Sentiment of Phrases* enrichments might be listed, but are reserved for internal use only. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Enrichments` object @@ -2550,8 +2609,9 @@ def create_enrichment( to a collection in the project, use the [Collections API](/apidocs/discovery-data#createcollection). - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param CreateEnrichment enrichment: Information about a specific enrichment. :param BinaryIO file: (optional) The enrichment file to upload. Expected @@ -2619,9 +2679,11 @@ def get_enrichment( Get details about a specific enrichment. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str enrichment_id: The Universally Unique Identifier (UUID) of the + enrichment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Enrichment` object @@ -2677,9 +2739,11 @@ def update_enrichment( Updates an existing enrichment's name and description. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str enrichment_id: The Universally Unique Identifier (UUID) of the + enrichment. :param str name: A new name for the enrichment. :param str description: (optional) A new description for the enrichment. :param dict headers: A `dict` containing the request headers @@ -2746,9 +2810,11 @@ def delete_enrichment( Deletes an existing enrichment from the specified project. **Note:** Only enrichments that have been manually created can be deleted. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str enrichment_id: The ID of the enrichment. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str enrichment_id: The Universally Unique Identifier (UUID) of the + enrichment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -2804,8 +2870,9 @@ def list_document_classifiers( Get a list of the document classifiers in a project. Returns only the name and classifier ID of each document classifier. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `DocumentClassifiers` object @@ -2864,8 +2931,9 @@ def create_document_classifier( **Note:** This method is supported on installed instances (IBM Cloud Pak for Data) or IBM Cloud-managed Premium or Enterprise plan instances. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. :param BinaryIO training_data: The training data CSV file to upload. The CSV file must have headers. The file must include a field that contains the text you want to classify and a field that contains the classification @@ -2942,9 +3010,11 @@ def get_document_classifier( Get details about a specific document classifier. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str classifier_id: The ID of the classifier. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `DocumentClassifier` object @@ -3002,9 +3072,11 @@ def update_document_classifier( Update the document classifier name or description, update the training data, or add or update the test data. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str classifier_id: The ID of the classifier. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. :param UpdateDocumentClassifier classifier: An object that contains a new name or description for a document classifier, updated training data, or new or updated test data. @@ -3083,9 +3155,11 @@ def delete_document_classifier( Deletes an existing document classifier from the specified project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str classifier_id: The ID of the classifier. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3142,9 +3216,11 @@ def list_document_classifier_models( Get a list of the document classifier models in a project. Returns only the name and model ID of each document classifier model. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str classifier_id: The ID of the classifier. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModels` object @@ -3208,9 +3284,11 @@ def create_document_classifier_model( **Note:** This method is supported on installed intances (IBM Cloud Pak for Data) or IBM Cloud-managed Premium or Enterprise plan instances. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str classifier_id: The ID of the classifier. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. :param str name: The name of the document classifier model. :param str description: (optional) A description of the document classifier model. @@ -3304,10 +3382,13 @@ def get_document_classifier_model( Get details about a specific document classifier model. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str classifier_id: The ID of the classifier. - :param str model_id: The ID of the classifier model. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. + :param str model_id: The Universally Unique Identifier (UUID) of the + classifier model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `DocumentClassifierModel` object @@ -3367,10 +3448,13 @@ def update_document_classifier_model( Update the document classifier model name or description. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str classifier_id: The ID of the classifier. - :param str model_id: The ID of the classifier model. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. + :param str model_id: The Universally Unique Identifier (UUID) of the + classifier model. :param str name: (optional) A new name for the enrichment. :param str description: (optional) A new description for the enrichment. :param dict headers: A `dict` containing the request headers @@ -3438,10 +3522,13 @@ def delete_document_classifier_model( Deletes an existing document classifier model from the specified project. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str classifier_id: The ID of the classifier. - :param str model_id: The ID of the classifier model. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str classifier_id: The Universally Unique Identifier (UUID) of the + classifier. + :param str model_id: The Universally Unique Identifier (UUID) of the + classifier model. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -3518,9 +3605,11 @@ def analyze_document( **Note:** This method is supported with Enterprise plan deployments and installed deployments only. - :param str project_id: The ID of the project. This information can be found - from the *Integrate and Deploy* page in Discovery. - :param str collection_id: The ID of the collection. + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. :param BinaryIO file: (optional) **Add a document**: The content of the document to ingest. For the supported file types and maximum supported file size limits when adding a document, see [the @@ -4069,7 +4158,8 @@ class Collection: """ A collection for storing documents. - :param str collection_id: (optional) The unique identifier of the collection. + :param str collection_id: (optional) The Universally Unique Identifier (UUID) of + the collection. :param str name: (optional) The name of the collection. """ @@ -4135,13 +4225,17 @@ class CollectionDetails: """ A collection for storing documents. - :param str collection_id: (optional) The unique identifier of the collection. + :param str collection_id: (optional) The Universally Unique Identifier (UUID) of + the collection. :param str name: The name of the collection. :param str description: (optional) A description of the collection. :param datetime created: (optional) The date that the collection was created. :param str language: (optional) The language of the collection. For a list of supported languages, see the [product documentation](/docs/discovery-data?topic=discovery-data-language-support). + :param bool ocr_enabled: (optional) If set to `true`, optical character + recognition (OCR) is enabled. For more information, see [Optical character + recognition](/docs/discovery-data?topic=discovery-data-collections#ocr). :param List[CollectionEnrichment] enrichments: (optional) An array of enrichments that are applied to this collection. To get a list of enrichments that are available for a project, use the [List enrichments](#listenrichments) @@ -4163,6 +4257,7 @@ def __init__( description: Optional[str] = None, created: Optional[datetime] = None, language: Optional[str] = None, + ocr_enabled: Optional[bool] = None, enrichments: Optional[List['CollectionEnrichment']] = None, smart_document_understanding: Optional[ 'CollectionDetailsSmartDocumentUnderstanding'] = None, @@ -4175,6 +4270,9 @@ def __init__( :param str language: (optional) The language of the collection. For a list of supported languages, see the [product documentation](/docs/discovery-data?topic=discovery-data-language-support). + :param bool ocr_enabled: (optional) If set to `true`, optical character + recognition (OCR) is enabled. For more information, see [Optical character + recognition](/docs/discovery-data?topic=discovery-data-collections#ocr). :param List[CollectionEnrichment] enrichments: (optional) An array of enrichments that are applied to this collection. To get a list of enrichments that are available for a project, use the [List @@ -4189,6 +4287,7 @@ def __init__( self.description = description self.created = created self.language = language + self.ocr_enabled = ocr_enabled self.enrichments = enrichments self.smart_document_understanding = smart_document_understanding @@ -4210,6 +4309,8 @@ def from_dict(cls, _dict: Dict) -> 'CollectionDetails': args['created'] = string_to_datetime(created) if (language := _dict.get('language')) is not None: args['language'] = language + if (ocr_enabled := _dict.get('ocr_enabled')) is not None: + args['ocr_enabled'] = ocr_enabled if (enrichments := _dict.get('enrichments')) is not None: args['enrichments'] = [ CollectionEnrichment.from_dict(v) for v in enrichments @@ -4240,6 +4341,8 @@ def to_dict(self) -> Dict: _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'language') and self.language is not None: _dict['language'] = self.language + if hasattr(self, 'ocr_enabled') and self.ocr_enabled is not None: + _dict['ocr_enabled'] = self.ocr_enabled if hasattr(self, 'enrichments') and self.enrichments is not None: enrichments_list = [] for v in self.enrichments: @@ -5949,8 +6052,8 @@ class DocumentClassifier: """ Information about a document classifier. - :param str classifier_id: (optional) A unique identifier of the document - classifier. + :param str classifier_id: (optional) The Universally Unique Identifier (UUID) of + the document classifier. :param str name: A human-readable name of the document classifier. :param str description: (optional) A description of the document classifier. :param datetime created: (optional) The date that the document classifier was @@ -6143,7 +6246,8 @@ class DocumentClassifierEnrichment: An object that describes enrichments that are applied to the training and test data that is used by the document classifier. - :param str enrichment_id: A unique identifier of the enrichment. + :param str enrichment_id: The Universally Unique Identifier (UUID) of the + enrichment. :param List[str] fields: An array of field names where the enrichment is applied. """ @@ -6156,7 +6260,8 @@ def __init__( """ Initialize a DocumentClassifierEnrichment object. - :param str enrichment_id: A unique identifier of the enrichment. + :param str enrichment_id: The Universally Unique Identifier (UUID) of the + enrichment. :param List[str] fields: An array of field names where the enrichment is applied. """ @@ -6218,8 +6323,8 @@ class DocumentClassifierModel: """ Information about a document classifier model. - :param str model_id: (optional) A unique identifier of the document classifier - model. + :param str model_id: (optional) The Universally Unique Identifier (UUID) of the + document classifier model. :param str name: A human-readable name of the document classifier model. :param str description: (optional) A description of the document classifier model. @@ -6235,8 +6340,8 @@ class DocumentClassifierModel: :param str status: (optional) The status of the training run. :param ClassifierModelEvaluation evaluation: (optional) An object that contains information about a trained document classifier model. - :param str enrichment_id: (optional) A unique identifier of the enrichment that - is generated by this document classifier model. + :param str enrichment_id: (optional) The Universally Unique Identifier (UUID) of + the enrichment that is generated by this document classifier model. :param datetime deployed_at: (optional) The date that the document classifier model was deployed. """ @@ -6271,8 +6376,9 @@ def __init__( :param str status: (optional) The status of the training run. :param ClassifierModelEvaluation evaluation: (optional) An object that contains information about a trained document classifier model. - :param str enrichment_id: (optional) A unique identifier of the enrichment - that is generated by this document classifier model. + :param str enrichment_id: (optional) The Universally Unique Identifier + (UUID) of the enrichment that is generated by this document classifier + model. """ self.model_id = model_id self.name = name @@ -6775,7 +6881,8 @@ class Enrichment: """ Information about a specific enrichment. - :param str enrichment_id: (optional) The unique identifier of this enrichment. + :param str enrichment_id: (optional) The Universally Unique Identifier (UUID) of + this enrichment. :param str name: (optional) The human readable name for this enrichment. :param str description: (optional) The description of this enrichment. :param str type: (optional) The type of this enrichment. @@ -6906,12 +7013,12 @@ class EnrichmentOptions: :param str result_field: (optional) The name of the result document field that this enrichment creates. Required when **type** is `rule_based` or `classifier`. Not valid when creating any other type of enrichment. - :param str classifier_id: (optional) A unique identifier of the document - classifier. Required when **type** is `classifier`. Not valid when creating any - other type of enrichment. - :param str model_id: (optional) A unique identifier of the document classifier - model. Required when **type** is `classifier`. Not valid when creating any other - type of enrichment. + :param str classifier_id: (optional) The Universally Unique Identifier (UUID) of + the document classifier. Required when **type** is `classifier`. Not valid when + creating any other type of enrichment. + :param str model_id: (optional) The Universally Unique Identifier (UUID) of the + document classifier model. Required when **type** is `classifier`. Not valid + when creating any other type of enrichment. :param float confidence_threshold: (optional) Specifies a threshold. Only classes with evaluation confidence scores that are higher than the specified threshold are included in the output. Optional when **type** is `classifier`. @@ -6978,12 +7085,12 @@ def __init__( :param str result_field: (optional) The name of the result document field that this enrichment creates. Required when **type** is `rule_based` or `classifier`. Not valid when creating any other type of enrichment. - :param str classifier_id: (optional) A unique identifier of the document - classifier. Required when **type** is `classifier`. Not valid when creating - any other type of enrichment. - :param str model_id: (optional) A unique identifier of the document - classifier model. Required when **type** is `classifier`. Not valid when - creating any other type of enrichment. + :param str classifier_id: (optional) The Universally Unique Identifier + (UUID) of the document classifier. Required when **type** is `classifier`. + Not valid when creating any other type of enrichment. + :param str model_id: (optional) The Universally Unique Identifier (UUID) of + the document classifier model. Required when **type** is `classifier`. Not + valid when creating any other type of enrichment. :param float confidence_threshold: (optional) Specifies a threshold. Only classes with evaluation confidence scores that are higher than the specified threshold are included in the output. Optional when **type** is @@ -8185,13 +8292,16 @@ class ProjectDetails: """ Detailed information about the specified project. - :param str project_id: (optional) The unique identifier of this project. + :param str project_id: (optional) The Universally Unique Identifier (UUID) of + this project. :param str name: (optional) The human readable name of this project. :param str type: (optional) The type of project. The `content_intelligence` type is a *Document Retrieval for Contracts* project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. + The Intelligent Document Processing (IDP) project type is available from IBM + Cloud-managed instances only. :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. :param int collection_count: (optional) The number of collections configured in @@ -8220,6 +8330,8 @@ def __init__( project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. + The Intelligent Document Processing (IDP) project type is available from + IBM Cloud-managed instances only. :param DefaultQueryParams default_query_parameters: (optional) Default query parameters for this project. """ @@ -8315,8 +8427,11 @@ class TypeEnum(str, Enum): and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. + The Intelligent Document Processing (IDP) project type is available from IBM + Cloud-managed instances only. """ + INTELLIGENT_DOCUMENT_PROCESSING = 'intelligent_document_processing' DOCUMENT_RETRIEVAL = 'document_retrieval' CONVERSATIONAL_SEARCH = 'conversational_search' CONTENT_MINING = 'content_mining' @@ -8328,13 +8443,16 @@ class ProjectListDetails: """ Details about a specific project. - :param str project_id: (optional) The unique identifier of this project. + :param str project_id: (optional) The Universally Unique Identifier (UUID) of + this project. :param str name: (optional) The human readable name of this project. :param str type: (optional) The type of project. The `content_intelligence` type is a *Document Retrieval for Contracts* project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. + The Intelligent Document Processing (IDP) project type is available from IBM + Cloud-managed instances only. :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. :param int collection_count: (optional) The number of collections configured in @@ -8360,6 +8478,8 @@ def __init__( project and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. + The Intelligent Document Processing (IDP) project type is available from + IBM Cloud-managed instances only. """ self.project_id = project_id self.name = name @@ -8439,8 +8559,11 @@ class TypeEnum(str, Enum): and the `other` type is a *Custom* project. The `content_mining` and `content_intelligence` types are available with Premium plan managed deployments and installed deployments only. + The Intelligent Document Processing (IDP) project type is available from IBM + Cloud-managed instances only. """ + INTELLIGENT_DOCUMENT_PROCESSING = 'intelligent_document_processing' DOCUMENT_RETRIEVAL = 'document_retrieval' CONVERSATIONAL_SEARCH = 'conversational_search' CONTENT_MINING = 'content_mining' diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 3b1008aa9..4a8bf1691 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -85,7 +85,7 @@ def test_list_projects_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects') - mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' + mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "intelligent_document_processing", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' responses.add( responses.GET, url, @@ -117,7 +117,7 @@ def test_list_projects_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects') - mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' + mock_response = '{"projects": [{"project_id": "project_id", "name": "name", "type": "intelligent_document_processing", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16}]}' responses.add( responses.GET, url, @@ -156,7 +156,7 @@ def test_create_project_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + mock_response = '{"project_id": "project_id", "name": "name", "type": "intelligent_document_processing", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add( responses.POST, url, @@ -200,7 +200,7 @@ def test_create_project_all_params(self): # Set up parameter values name = 'testString' - type = 'document_retrieval' + type = 'intelligent_document_processing' default_query_parameters = default_query_params_model # Invoke method @@ -217,7 +217,7 @@ def test_create_project_all_params(self): # Validate body params req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' - assert req_body['type'] == 'document_retrieval' + assert req_body['type'] == 'intelligent_document_processing' assert req_body['default_query_parameters'] == default_query_params_model def test_create_project_all_params_with_retries(self): @@ -236,7 +236,7 @@ def test_create_project_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + mock_response = '{"project_id": "project_id", "name": "name", "type": "intelligent_document_processing", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add( responses.POST, url, @@ -280,7 +280,7 @@ def test_create_project_value_error(self): # Set up parameter values name = 'testString' - type = 'document_retrieval' + type = 'intelligent_document_processing' default_query_parameters = default_query_params_model # Pass in all but one required param and check for a ValueError @@ -315,7 +315,7 @@ def test_get_project_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + mock_response = '{"project_id": "project_id", "name": "name", "type": "intelligent_document_processing", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add( responses.GET, url, @@ -353,7 +353,7 @@ def test_get_project_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + mock_response = '{"project_id": "project_id", "name": "name", "type": "intelligent_document_processing", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add( responses.GET, url, @@ -396,7 +396,7 @@ def test_update_project_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + mock_response = '{"project_id": "project_id", "name": "name", "type": "intelligent_document_processing", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add( responses.POST, url, @@ -439,7 +439,7 @@ def test_update_project_required_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + mock_response = '{"project_id": "project_id", "name": "name", "type": "intelligent_document_processing", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add( responses.POST, url, @@ -477,7 +477,7 @@ def test_update_project_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString') - mock_response = '{"project_id": "project_id", "name": "name", "type": "document_retrieval", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' + mock_response = '{"project_id": "project_id", "name": "name", "type": "intelligent_document_processing", "relevancy_training_status": {"data_updated": "data_updated", "total_examples": 14, "sufficient_label_diversity": true, "processing": true, "minimum_examples_added": true, "successfully_trained": "successfully_trained", "available": false, "notices": 7, "minimum_queries_added": false}, "collection_count": 16, "default_query_parameters": {"collection_ids": ["collection_ids"], "passages": {"enabled": false, "count": 5, "fields": ["fields"], "characters": 10, "per_document": true, "max_per_document": 16}, "table_results": {"enabled": false, "count": 5, "per_document": 0}, "aggregation": "aggregation", "suggested_refinements": {"enabled": false, "count": 5}, "spelling_suggestions": true, "highlight": false, "count": 5, "sort": "sort", "return": ["return_"]}}' responses.add( responses.POST, url, @@ -812,7 +812,7 @@ def test_create_collection_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "ocr_enabled": false, "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' responses.add( responses.POST, url, @@ -831,6 +831,7 @@ def test_create_collection_all_params(self): name = 'testString' description = 'testString' language = 'en' + ocr_enabled = False enrichments = [collection_enrichment_model] # Invoke method @@ -839,6 +840,7 @@ def test_create_collection_all_params(self): name, description=description, language=language, + ocr_enabled=ocr_enabled, enrichments=enrichments, headers={}, ) @@ -851,6 +853,7 @@ def test_create_collection_all_params(self): assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' assert req_body['language'] == 'en' + assert req_body['ocr_enabled'] == False assert req_body['enrichments'] == [collection_enrichment_model] def test_create_collection_all_params_with_retries(self): @@ -869,7 +872,7 @@ def test_create_collection_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "ocr_enabled": false, "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' responses.add( responses.POST, url, @@ -888,6 +891,7 @@ def test_create_collection_value_error(self): name = 'testString' description = 'testString' language = 'en' + ocr_enabled = False enrichments = [collection_enrichment_model] # Pass in all but one required param and check for a ValueError @@ -922,7 +926,7 @@ def test_get_collection_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "ocr_enabled": false, "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' responses.add( responses.GET, url, @@ -962,7 +966,7 @@ def test_get_collection_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "ocr_enabled": false, "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' responses.add( responses.GET, url, @@ -1007,7 +1011,7 @@ def test_update_collection_all_params(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "ocr_enabled": false, "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' responses.add( responses.POST, url, @@ -1026,6 +1030,7 @@ def test_update_collection_all_params(self): collection_id = 'testString' name = 'testString' description = 'testString' + ocr_enabled = False enrichments = [collection_enrichment_model] # Invoke method @@ -1034,6 +1039,7 @@ def test_update_collection_all_params(self): collection_id, name=name, description=description, + ocr_enabled=ocr_enabled, enrichments=enrichments, headers={}, ) @@ -1045,6 +1051,7 @@ def test_update_collection_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['name'] == 'testString' assert req_body['description'] == 'testString' + assert req_body['ocr_enabled'] == False assert req_body['enrichments'] == [collection_enrichment_model] def test_update_collection_all_params_with_retries(self): @@ -1063,7 +1070,7 @@ def test_update_collection_value_error(self): """ # Set up mock url = preprocess_url('/v2/projects/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' + mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "language": "en", "ocr_enabled": false, "enrichments": [{"enrichment_id": "enrichment_id", "fields": ["fields"]}], "smart_document_understanding": {"enabled": false, "model": "custom"}}' responses.add( responses.POST, url, @@ -1082,6 +1089,7 @@ def test_update_collection_value_error(self): collection_id = 'testString' name = 'testString' description = 'testString' + ocr_enabled = False enrichments = [collection_enrichment_model] # Pass in all but one required param and check for a ValueError @@ -5776,6 +5784,7 @@ def test_collection_details_serialization(self): collection_details_model_json['name'] = 'testString' collection_details_model_json['description'] = 'testString' collection_details_model_json['language'] = 'en' + collection_details_model_json['ocr_enabled'] = False collection_details_model_json['enrichments'] = [collection_enrichment_model] # Construct a model instance of CollectionDetails by calling from_dict on the json representation @@ -7135,7 +7144,7 @@ def test_list_projects_response_serialization(self): project_list_details_model = {} # ProjectListDetails project_list_details_model['name'] = 'testString' - project_list_details_model['type'] = 'document_retrieval' + project_list_details_model['type'] = 'intelligent_document_processing' # Construct a json representation of a ListProjectsResponse model list_projects_response_model_json = {} @@ -7327,7 +7336,7 @@ def test_project_details_serialization(self): # Construct a json representation of a ProjectDetails model project_details_model_json = {} project_details_model_json['name'] = 'testString' - project_details_model_json['type'] = 'document_retrieval' + project_details_model_json['type'] = 'intelligent_document_processing' project_details_model_json['default_query_parameters'] = default_query_params_model # Construct a model instance of ProjectDetails by calling from_dict on the json representation @@ -7359,7 +7368,7 @@ def test_project_list_details_serialization(self): # Construct a json representation of a ProjectListDetails model project_list_details_model_json = {} project_list_details_model_json['name'] = 'testString' - project_list_details_model_json['type'] = 'document_retrieval' + project_list_details_model_json['type'] = 'intelligent_document_processing' # Construct a model instance of ProjectListDetails by calling from_dict on the json representation project_list_details_model = ProjectListDetails.from_dict(project_list_details_model_json) From d026ab2a7ffa950a7ba6b655357f2523cda337ef Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 15 May 2024 14:17:02 -0500 Subject: [PATCH 423/455] feat(stt): add speech_begin_event param to recognize func --- ibm_watson/speech_to_text_v1.py | 307 ++++++++++++++++++---------- test/unit/test_speech_to_text_v1.py | 5 +- 2 files changed, 206 insertions(+), 106 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index c1b3be1fa..0ad6d3761 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -29,8 +29,8 @@ transcription accuracy. Effective **31 July 2023**, all previous-generation models will be removed from the service and the documentation. Most previous-generation models were deprecated on 15 March -2022. You must migrate to the equivalent next-generation model by 31 July 2023. For more -information, see [Migrating to next-generation +2022. You must migrate to the equivalent large speech model or next-generation model by 31 +July 2023. For more information, see [Migrating to large speech models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate).{: deprecated} For speech recognition, the service supports synchronous and asynchronous HTTP @@ -196,6 +196,7 @@ def recognize( *, content_type: Optional[str] = None, model: Optional[str] = None, + speech_begin_event: Optional[bool] = None, language_customization_id: Optional[str] = None, acoustic_customization_id: Optional[str] = None, base_model_version: Optional[str] = None, @@ -281,31 +282,36 @@ def recognize( fails. **See also:** [Supported audio formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats). - ### Next-generation models - The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 - kHz) models for many languages. Next-generation models have higher throughput than - the service's previous generation of `Broadband` and `Narrowband` models. When you - use next-generation models, the service can return transcriptions more quickly and - also provide noticeably better transcription accuracy. - You specify a next-generation model by using the `model` query parameter, as you - do a previous-generation model. Most next-generation models support the - `low_latency` parameter, and all next-generation models support the - `character_insertion_bias` parameter. These parameters are not available with - previous-generation models. - Next-generation models do not support all of the speech recognition parameters - that are available for use with previous-generation models. Next-generation models - do not support the following parameters: + ### Large speech models and Next-generation models + The service supports large speech models and next-generation `Multimedia` (16 + kHz) and `Telephony` (8 kHz) models for many languages. Large speech models and + next-generation models have higher throughput than the service's previous + generation of `Broadband` and `Narrowband` models. When you use large speech + models and next-generation models, the service can return transcriptions more + quickly and also provide noticeably better transcription accuracy. + You specify a large speech model or next-generation model by using the `model` + query parameter, as you do a previous-generation model. Only the next-generation + models support the `low_latency` parameter, and all large speech models and + next-generation models support the `character_insertion_bias` parameter. These + parameters are not available with previous-generation models. + Large speech models and next-generation models do not support all of the speech + recognition parameters that are available for use with previous-generation models. + Next-generation models do not support the following parameters: * `acoustic_customization_id` * `keywords` and `keywords_threshold` * `processing_metrics` and `processing_metrics_interval` * `word_alternatives_threshold` **Important:** Effective **31 July 2023**, all previous-generation models will be removed from the service and the documentation. Most previous-generation models - were deprecated on 15 March 2022. You must migrate to the equivalent - next-generation model by 31 July 2023. For more information, see [Migrating to - next-generation + were deprecated on 15 March 2022. You must migrate to the equivalent large speech + model or next-generation model by 31 July 2023. For more information, see + [Migrating to large speech models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** + * [Large speech languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages) + * [Supported features for large speech + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages#models-lsm-supported-features) * [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng) * [Supported features for next-generation @@ -340,6 +346,14 @@ def recognize( recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use) * [Using the default model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use#models-use-default). + :param bool speech_begin_event: (optional) If `true`, the service returns a + response object `SpeechActivity` which contains the time when a speech + activity is detected in the stream. This can be used both in standard and + low latency mode. This feature enables client applications to know that + some words/speech has been detected and the service is in the process of + decoding. This can be used in lieu of interim results in standard mode. See + [Using speech recognition + parameters](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-service-features#features-parameters). :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 @@ -374,6 +388,7 @@ def recognize( Specify a value between 0.0 and 1.0. Unless a different customization weight was specified for the custom model when the model was trained, the default value is: + * 0.5 for large speech models * 0.3 for previous-generation models * 0.2 for most next-generation models * 0.1 for next-generation English and Japanese models @@ -447,9 +462,10 @@ def recognize( (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). - :param int smart_formatting_version: (optional) Smart formatting version is - for next-generation models and that is supported in US English, Brazilian - Portuguese, French and German languages. + :param int smart_formatting_version: (optional) Smart formatting version + for large speech models and next-generation models is supported in US + English, Brazilian Portuguese, French, German, Spanish and French Canadian + languages. :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. @@ -459,9 +475,8 @@ def recognize( Australian English, US English, German, Japanese, Korean, and Spanish (both broadband and narrowband models) and UK English (narrowband model) transcription only. - * _For next-generation models,_ the parameter can be used with Czech, - English (Australian, Indian, UK, and US), German, Japanese, Korean, and - Spanish transcription only. + * _For large speech models and next-generation models,_ the parameter can + be used with all available languages. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). :param str grammar_name: (optional) The name of a grammar that is to be @@ -535,8 +550,8 @@ def recognize( The values increase on a monotonic curve. Specifying one or two decimal places of precision (for example, `0.55`) is typically more than sufficient. - The parameter is supported with all next-generation models and with most - previous-generation models. See [Speech detector + The parameter is supported with all large speech models, next-generation + models and with most previous-generation models. See [Speech detector sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) and [Language model support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). @@ -552,8 +567,8 @@ def recognize( The values increase on a monotonic curve. Specifying one or two decimal places of precision (for example, `0.55`) is typically more than sufficient. - The parameter is supported with all next-generation models and with most - previous-generation models. See [Background audio + The parameter is supported with all large speech models, next-generation + models and with most previous-generation models. See [Background audio suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression) and [Language model support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). @@ -564,18 +579,19 @@ def recognize( previous-generation models. The `low_latency` parameter causes the models to produce results even more quickly, though the results might be less accurate when the parameter is used. - The parameter is not available for previous-generation `Broadband` and - `Narrowband` models. It is available for most next-generation models. + The parameter is not available for large speech models and + previous-generation `Broadband` and `Narrowband` models. It is available + for most next-generation models. * For a list of next-generation models that support low latency, see [Supported next-generation language models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported). * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). - :param float character_insertion_bias: (optional) For next-generation - models, an indication of whether the service is biased to recognize shorter - or longer strings of characters when developing transcription hypotheses. - By default, the service is optimized to produce the best balance of strings - of different lengths. + :param float character_insertion_bias: (optional) For large speech models + and next-generation models, an indication of whether the service is biased + to recognize shorter or longer strings of characters when developing + transcription hypotheses. By default, the service is optimized to produce + the best balance of strings of different lengths. The default bias is 0.0. The allowable range of values is -1.0 to 1.0. * Negative values bias the service to favor hypotheses with shorter strings of characters. @@ -609,6 +625,7 @@ def recognize( params = { 'model': model, + 'speech_begin_event': speech_begin_event, 'language_customization_id': language_customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, @@ -918,31 +935,36 @@ def create_job( fails. **See also:** [Supported audio formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats). - ### Next-generation models - The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 - kHz) models for many languages. Next-generation models have higher throughput than - the service's previous generation of `Broadband` and `Narrowband` models. When you - use next-generation models, the service can return transcriptions more quickly and - also provide noticeably better transcription accuracy. - You specify a next-generation model by using the `model` query parameter, as you - do a previous-generation model. Most next-generation models support the - `low_latency` parameter, and all next-generation models support the - `character_insertion_bias` parameter. These parameters are not available with - previous-generation models. - Next-generation models do not support all of the speech recognition parameters - that are available for use with previous-generation models. Next-generation models - do not support the following parameters: + ### Large speech models and Next-generation models + The service supports large speech models and next-generation `Multimedia` (16 + kHz) and `Telephony` (8 kHz) models for many languages. Large speech models and + next-generation models have higher throughput than the service's previous + generation of `Broadband` and `Narrowband` models. When you use large speech + models and next-generation models, the service can return transcriptions more + quickly and also provide noticeably better transcription accuracy. + You specify a large speech model or next-generation model by using the `model` + query parameter, as you do a previous-generation model. Only the next-generation + models support the `low_latency` parameter, and all large speech models and + next-generation models support the `character_insertion_bias` parameter. These + parameters are not available with previous-generation models. + Large speech models and next-generation models do not support all of the speech + recognition parameters that are available for use with previous-generation models. + Next-generation models do not support the following parameters: * `acoustic_customization_id` * `keywords` and `keywords_threshold` * `processing_metrics` and `processing_metrics_interval` * `word_alternatives_threshold` **Important:** Effective **31 July 2023**, all previous-generation models will be removed from the service and the documentation. Most previous-generation models - were deprecated on 15 March 2022. You must migrate to the equivalent - next-generation model by 31 July 2023. For more information, see [Migrating to - next-generation + were deprecated on 15 March 2022. You must migrate to the equivalent large speech + model or next-generation model by 31 July 2023. For more information, see + [Migrating to large speech models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** + * [Large speech languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages) + * [Supported features for large speech + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages#models-lsm-supported-features) * [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng) * [Supported features for next-generation @@ -1033,6 +1055,7 @@ def create_job( Specify a value between 0.0 and 1.0. Unless a different customization weight was specified for the custom model when the model was trained, the default value is: + * 0.5 for large speech models * 0.3 for previous-generation models * 0.2 for most next-generation models * 0.1 for next-generation English and Japanese models @@ -1106,9 +1129,10 @@ def create_job( (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). - :param int smart_formatting_version: (optional) Smart formatting version is - for next-generation models and that is supported in US English, Brazilian - Portuguese, French and German languages. + :param int smart_formatting_version: (optional) Smart formatting version + for large speech models and next-generation models is supported in US + English, Brazilian Portuguese, French, German, Spanish and French Canadian + languages. :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. @@ -1118,9 +1142,8 @@ def create_job( Australian English, US English, German, Japanese, Korean, and Spanish (both broadband and narrowband models) and UK English (narrowband model) transcription only. - * _For next-generation models,_ the parameter can be used with Czech, - English (Australian, Indian, UK, and US), German, Japanese, Korean, and - Spanish transcription only. + * _For large speech models and next-generation models,_ the parameter can + be used with all available languages. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). :param str grammar_name: (optional) The name of a grammar that is to be @@ -1216,8 +1239,8 @@ def create_job( The values increase on a monotonic curve. Specifying one or two decimal places of precision (for example, `0.55`) is typically more than sufficient. - The parameter is supported with all next-generation models and with most - previous-generation models. See [Speech detector + The parameter is supported with all large speech models, next-generation + models and with most previous-generation models. See [Speech detector sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) and [Language model support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). @@ -1233,8 +1256,8 @@ def create_job( The values increase on a monotonic curve. Specifying one or two decimal places of precision (for example, `0.55`) is typically more than sufficient. - The parameter is supported with all next-generation models and with most - previous-generation models. See [Background audio + The parameter is supported with all large speech models, next-generation + models and with most previous-generation models. See [Background audio suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression) and [Language model support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). @@ -1245,18 +1268,19 @@ def create_job( previous-generation models. The `low_latency` parameter causes the models to produce results even more quickly, though the results might be less accurate when the parameter is used. - The parameter is not available for previous-generation `Broadband` and - `Narrowband` models. It is available for most next-generation models. + The parameter is not available for large speech models and + previous-generation `Broadband` and `Narrowband` models. It is available + for most next-generation models. * For a list of next-generation models that support low latency, see [Supported next-generation language models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported). * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). - :param float character_insertion_bias: (optional) For next-generation - models, an indication of whether the service is biased to recognize shorter - or longer strings of characters when developing transcription hypotheses. - By default, the service is optimized to produce the best balance of strings - of different lengths. + :param float character_insertion_bias: (optional) For large speech models + and next-generation models, an indication of whether the service is biased + to recognize shorter or longer strings of characters when developing + transcription hypotheses. By default, the service is optimized to produce + the best balance of strings of different lengths. The default bias is 0.0. The allowable range of values is -1.0 to 1.0. * Negative values bias the service to favor hypotheses with shorter strings of characters. @@ -1521,15 +1545,49 @@ def create_language_model( below the limit. **Important:** Effective **31 July 2023**, all previous-generation models will be removed from the service and the documentation. Most previous-generation models - were deprecated on 15 March 2022. You must migrate to the equivalent - next-generation model by 31 July 2023. For more information, see [Migrating to - next-generation + were deprecated on 15 March 2022. You must migrate to the equivalent large speech + model or next-generation model by 31 July 2023. For more information, see + [Migrating to large speech models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** * [Create a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#createModel-language) * [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support) + ### Large speech models and Next-generation models + The service supports large speech models and next-generation `Multimedia` (16 + kHz) and `Telephony` (8 kHz) models for many languages. Large speech models and + next-generation models have higher throughput than the service's previous + generation of `Broadband` and `Narrowband` models. When you use large speech + models and next-generation models, the service can return transcriptions more + quickly and also provide noticeably better transcription accuracy. + You specify a large speech model or next-generation model by using the `model` + query parameter, as you do a previous-generation model. Only the next-generation + models support the `low_latency` parameter, and all large speech models and + next-generation models support the `character_insertion_bias` parameter. These + parameters are not available with previous-generation models. + Large speech models and next-generation models do not support all of the speech + recognition parameters that are available for use with previous-generation models. + Next-generation models do not support the following parameters: + * `acoustic_customization_id` + * `keywords` and `keywords_threshold` + * `processing_metrics` and `processing_metrics_interval` + * `word_alternatives_threshold` + **Important:** Effective **31 July 2023**, all previous-generation models will be + removed from the service and the documentation. Most previous-generation models + were deprecated on 15 March 2022. You must migrate to the equivalent large speech + model or next-generation model by 31 July 2023. For more information, see + [Migrating to large speech + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). + **See also:** + * [Large speech languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages) + * [Supported features for large speech + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-large-speech-languages#models-lsm-supported-features) + * [Next-generation languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng) + * [Supported features for next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-features). :param str name: A user-defined name for the new custom language model. Use a localized name that matches the language of the custom model. Use a name @@ -1847,14 +1905,16 @@ def train_language_model( * `user` trains the model only on custom words that were added or modified by the user directly. The model is not trained on new words extracted from corpora or grammars. - _For custom models that are based on next-generation models_, the service - ignores the parameter. The words resource contains only custom words that - the user adds or modifies directly, so the parameter is unnecessary. + _For custom models that are based on large speech models and + next-generation models_, the service ignores the `word_type_to_add` + parameter. The words resource contains only custom words that the user adds + or modifies directly, so the parameter is unnecessary. :param float customization_weight: (optional) Specifies a customization weight for the custom language model. The customization weight tells the service how much weight to give to words from the custom language model compared to those from the base model for speech recognition. Specify a value between 0.0 and 1.0. The default value is: + * 0.5 for large speech models * 0.3 for previous-generation models * 0.2 for most next-generation models * 0.1 for next-generation English and Japanese models @@ -2145,6 +2205,9 @@ def add_corpus( additional resources to the custom model or to train the model until the service's analysis of the corpus for the current request completes. Use the [Get a corpus](#getcorpus) method to check the status of the analysis. + _For custom models that are based on large speech models_, the service parses and + extracts word sequences from one or multiple corpora files. The characters help + the service learn and predict character sequences from audio. _For custom models that are based on previous-generation models_, the service auto-populates the model's words resource with words from the corpus that are not found in its base vocabulary. These words are referred to as out-of-vocabulary @@ -2171,11 +2234,11 @@ def add_corpus( model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addCorpus) * [Working with corpora for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingCorpora) - * [Working with corpora for next-generation + * [Working with corpora for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingCorpora-ng) * [Validating a words resource for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel) - * [Validating a words resource for next-generation + * [Validating a words resource for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng). :param str customization_id: The customization ID (GUID) of the custom @@ -2543,11 +2606,11 @@ def add_words( model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords) * [Working with custom words for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords) - * [Working with custom words for next-generation + * [Working with custom words for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingWords-ng) * [Validating a words resource for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel) - * [Validating a words resource for next-generation + * [Validating a words resource for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng). :param str customization_id: The customization ID (GUID) of the custom @@ -2655,11 +2718,11 @@ def add_word( model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords) * [Working with custom words for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords) - * [Working with custom words for next-generation + * [Working with custom words for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingWords-ng) * [Validating a words resource for previous-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel) - * [Validating a words resource for next-generation + * [Validating a words resource for large speech models and next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng). :param str customization_id: The customization ID (GUID) of the custom @@ -3238,12 +3301,13 @@ def create_acoustic_model( do not lose any models, but you cannot create any more until your model count is below the limit. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **Important:** Effective **31 July 2023**, all previous-generation models will be removed from the service and the documentation. Most previous-generation models - were deprecated on 15 March 2022. You must migrate to the equivalent - next-generation model by 31 July 2023. For more information, see [Migrating to - next-generation + were deprecated on 15 March 2022. You must migrate to the equivalent large speech + model or next-generation model by 31 July 2023. For more information, see + [Migrating to large speech models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** [Create a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#createModel-acoustic). @@ -3322,7 +3386,8 @@ def list_acoustic_models( all languages. You must use credentials for the instance of the service that owns a model to list information about it. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Listing custom acoustic models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). @@ -3379,7 +3444,8 @@ def get_acoustic_model( 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. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Listing custom acoustic models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). @@ -3434,7 +3500,8 @@ def delete_acoustic_model( processed. You must use credentials for the instance of the service that owns a model to delete it. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Deleting a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#deleteModel-acoustic). @@ -3518,7 +3585,8 @@ def train_acoustic_model( same version of the same base model, and the custom language model must be fully trained and available. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** * [Train the custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#trainModel-acoustic) @@ -3622,7 +3690,8 @@ def reset_acoustic_model( request completes. You must use credentials for the instance of the service that owns a model to reset it. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Resetting a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#resetModel-acoustic). @@ -3698,7 +3767,8 @@ def upgrade_acoustic_model( the custom acoustic model can be upgraded. Omit the parameter if the custom acoustic model was not trained with a custom language model. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Upgrading a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-acoustic). @@ -3778,7 +3848,8 @@ def list_audio( 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. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Listing audio resources for a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#listAudio). @@ -3870,7 +3941,8 @@ def add_audio( resource, and it returns the status of the resource. Use a loop to check the status of the audio every few seconds until it becomes `ok`. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Add audio to the custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#addAudio). ### Content types for audio-type resources @@ -4046,7 +4118,8 @@ def get_audio( You must use credentials for the instance of the service that owns a model to list its audio resources. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Listing audio resources for a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#listAudio). @@ -4111,7 +4184,8 @@ def delete_audio( credentials for the instance of the service that owns a model to delete its audio resources. **Note:** Acoustic model customization is supported only for use with - previous-generation models. It is not supported for next-generation models. + previous-generation models. It is not supported for large speech models and + next-generation models. **See also:** [Deleting an audio resource from a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#deleteAudio). @@ -4239,15 +4313,19 @@ class ModelId(str, Enum): DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' DE_DE_TELEPHONY = 'de-DE_Telephony' + EN_AU = 'en-AU' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' EN_AU_MULTIMEDIA = 'en-AU_Multimedia' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_AU_TELEPHONY = 'en-AU_Telephony' + EN_GB = 'en-GB' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_MULTIMEDIA = 'en-GB_Multimedia' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' + EN_IN = 'en-IN' EN_IN_TELEPHONY = 'en-IN_Telephony' + EN_US = 'en-US' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' EN_US_MULTIMEDIA = 'en-US_Multimedia' EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' @@ -4269,10 +4347,12 @@ class ModelId(str, Enum): ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_CA = 'fr-CA' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' + FR_FR = 'fr-FR' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_MULTIMEDIA = 'fr-FR_Multimedia' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' @@ -4282,6 +4362,7 @@ class ModelId(str, Enum): IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' + JA_JP = 'ja-JP' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' @@ -4354,15 +4435,19 @@ class Model(str, Enum): DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' DE_DE_TELEPHONY = 'de-DE_Telephony' + EN_AU = 'en-AU' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' EN_AU_MULTIMEDIA = 'en-AU_Multimedia' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_AU_TELEPHONY = 'en-AU_Telephony' + EN_IN = 'en-IN' EN_IN_TELEPHONY = 'en-IN_Telephony' + EN_GB = 'en-GB' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_MULTIMEDIA = 'en-GB_Multimedia' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' + EN_US = 'en-US' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' EN_US_MULTIMEDIA = 'en-US_Multimedia' EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' @@ -4384,10 +4469,12 @@ class Model(str, Enum): ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_CA = 'fr-CA' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' + FR_FR = 'fr-FR' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_MULTIMEDIA = 'fr-FR_Multimedia' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' @@ -4397,6 +4484,7 @@ class Model(str, Enum): IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' + JA_JP = 'ja-JP' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' @@ -4469,15 +4557,19 @@ class Model(str, Enum): DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' DE_DE_TELEPHONY = 'de-DE_Telephony' + EN_AU = 'en-AU' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' EN_AU_MULTIMEDIA = 'en-AU_Multimedia' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_AU_TELEPHONY = 'en-AU_Telephony' + EN_IN = 'en-IN' EN_IN_TELEPHONY = 'en-IN_Telephony' + EN_GB = 'en-GB' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_MULTIMEDIA = 'en-GB_Multimedia' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' + EN_US = 'en-US' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' EN_US_MULTIMEDIA = 'en-US_Multimedia' EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' @@ -4499,10 +4591,12 @@ class Model(str, Enum): ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' + FR_CA = 'fr-CA' FR_CA_BROADBANDMODEL = 'fr-CA_BroadbandModel' FR_CA_MULTIMEDIA = 'fr-CA_Multimedia' FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' + FR_FR = 'fr-FR' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' FR_FR_MULTIMEDIA = 'fr-FR_Multimedia' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' @@ -4512,6 +4606,7 @@ class Model(str, Enum): IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' IT_IT_MULTIMEDIA = 'it-IT_Multimedia' IT_IT_TELEPHONY = 'it-IT_Telephony' + JA_JP = 'ja-JP' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' @@ -4621,9 +4716,10 @@ class WordTypeToAdd(str, Enum): * `user` trains the model only on custom words that were added or modified by the user directly. The model is not trained on new words extracted from corpora or grammars. - _For custom models that are based on next-generation models_, the service ignores - the parameter. The words resource contains only custom words that the user adds or - modifies directly, so the parameter is unnecessary. + _For custom models that are based on large speech models and next-generation + models_, the service ignores the `word_type_to_add` parameter. The words resource + contains only custom words that the user adds or modifies directly, so the + parameter is unnecessary. """ ALL = 'all' @@ -6167,9 +6263,9 @@ class Corpus: :param str name: The name of the corpus. :param int total_words: The total number of words in the corpus. The value is `0` while the corpus is being processed. - :param int out_of_vocabulary_words: _For custom models that are based on - previous-generation models_, the number of OOV words extracted from the corpus. - The value is `0` while the corpus is being processed. + :param int out_of_vocabulary_words: _For custom models that are based on large + speech models and previous-generation models_, the number of OOV words extracted + from the corpus. The value is `0` while the corpus is being processed. _For custom models that are based on next-generation models_, no OOV words are extracted from corpora, so the value is always `0`. :param str status: The status of the corpus: @@ -6200,8 +6296,9 @@ def __init__( :param int total_words: The total number of words in the corpus. The value is `0` while the corpus is being processed. :param int out_of_vocabulary_words: _For custom models that are based on - previous-generation models_, the number of OOV words extracted from the - corpus. The value is `0` while the corpus is being processed. + large speech models and previous-generation models_, the number of OOV + words extracted from the corpus. The value is `0` while the corpus is being + processed. _For custom models that are based on next-generation models_, no OOV words are extracted from corpora, so the value is always `0`. :param str status: The status of the corpus: diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 304752966..781732ccf 100644 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2015, 2024. +# (C) Copyright IBM Corp. 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -224,6 +224,7 @@ def test_recognize_all_params(self): audio = io.BytesIO(b'This is a mock file.').getvalue() content_type = 'application/octet-stream' model = 'en-US_BroadbandModel' + speech_begin_event = False language_customization_id = 'testString' acoustic_customization_id = 'testString' base_model_version = 'testString' @@ -254,6 +255,7 @@ def test_recognize_all_params(self): audio, content_type=content_type, model=model, + speech_begin_event=speech_begin_event, language_customization_id=language_customization_id, acoustic_customization_id=acoustic_customization_id, base_model_version=base_model_version, @@ -288,6 +290,7 @@ def test_recognize_all_params(self): query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'model={}'.format(model) in query_string + assert 'speech_begin_event={}'.format('true' if speech_begin_event else 'false') in query_string assert 'language_customization_id={}'.format(language_customization_id) in query_string assert 'acoustic_customization_id={}'.format(acoustic_customization_id) in query_string assert 'base_model_version={}'.format(base_model_version) in query_string From 035b29d82c35789f782359a9842e50956665b96c Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 15 May 2024 14:49:52 -0500 Subject: [PATCH 424/455] feat(stt): remove interim_results and low_latency wss params --- examples/microphone-speech-to-text.py | 3 +- ibm_watson/speech_to_text_v1_adapter.py | 22 +------ ibm_watson/websocket/recognize_listener.py | 19 +++--- test/integration/test_speech_to_text_v1.py | 77 ---------------------- 4 files changed, 11 insertions(+), 110 deletions(-) diff --git a/examples/microphone-speech-to-text.py b/examples/microphone-speech-to-text.py index 9174de74f..fb0fbd1ae 100644 --- a/examples/microphone-speech-to-text.py +++ b/examples/microphone-speech-to-text.py @@ -72,8 +72,7 @@ def recognize_using_weboscket(*args): mycallback = MyRecognizeCallback() speech_to_text.recognize_using_websocket(audio=audio_source, content_type='audio/l16; rate=44100', - recognize_callback=mycallback, - interim_results=True) + recognize_callback=mycallback) ############################################### #### Prepare the for recording using Pyaudio ## diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index fedc5af5e..67820be85 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2018, 2021. +# (C) Copyright IBM Corp. 2018, 2024. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -33,7 +33,6 @@ def recognize_using_websocket(self, customization_weight=None, base_model_version=None, inactivity_timeout=None, - interim_results=None, keywords=None, keywords_threshold=None, max_alternatives=None, @@ -55,7 +54,6 @@ def recognize_using_websocket(self, split_transcript_at_phrase_end=None, speech_detector_sensitivity=None, background_audio_suppression=None, - low_latency=None, character_insertion_bias=None, **kwargs): """ @@ -271,22 +269,6 @@ def recognize_using_websocket(self, * 1.0 suppresses all audio (no audio is transcribed). The values increase on a monotonic curve. See [Background audio suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression). - :param bool low_latency: (optional) If `true` for next-generation - `Multimedia` and `Telephony` models that support low latency, directs the - service to produce results even more quickly than it usually does. - Next-generation models produce transcription results faster than - previous-generation models. The `low_latency` parameter causes the models - to produce results even more quickly, though the results might be less - accurate when the parameter is used. - **Note:** The parameter is beta functionality. It is not available for - previous-generation `Broadband` and `Narrowband` models. It is available - only for some next-generation models. - * For a list of next-generation models that support low latency, see - [Supported language - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported) - for next-generation models. - * For more information about the `low_latency` parameter, see [Low - latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). :param float character_insertion_bias: (optional) For next-generation `Multimedia` and `Telephony` models, an indication of whether the service is biased to recognize shorter or longer strings of characters when @@ -355,7 +337,6 @@ def recognize_using_websocket(self, 'customization_weight': customization_weight, 'content_type': content_type, 'inactivity_timeout': inactivity_timeout, - 'interim_results': interim_results, 'keywords': keywords, 'keywords_threshold': keywords_threshold, 'max_alternatives': max_alternatives, @@ -375,7 +356,6 @@ def recognize_using_websocket(self, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, - 'low_latency': low_latency, 'character_insertion_bias': character_insertion_bias } options = {k: v for k, v in options.items() if v is not None} diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index 43eb79618..041bcf693 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -196,16 +196,15 @@ def on_data(self, ws, message, message_type, fin): # set of transcriptions and send them to the appropriate callbacks. results = json_object.get('results') if results: - if (self.options.get('interim_results') is True): - b_final = (results[0].get('final') is True) - alternatives = results[0].get('alternatives') - if alternatives: - hypothesis = alternatives[0].get('transcript') - transcripts = self.extract_transcripts(alternatives) - if b_final: - self.callback.on_transcription(transcripts) - if hypothesis: - self.callback.on_hypothesis(hypothesis) + b_final = (results[0].get('final') is True) + alternatives = results[0].get('alternatives') + if alternatives: + hypothesis = alternatives[0].get('transcript') + transcripts = self.extract_transcripts(alternatives) + if b_final: + self.callback.on_transcription(transcripts) + if hypothesis: + self.callback.on_hypothesis(hypothesis) else: final_transcript = [] for result in results: diff --git a/test/integration/test_speech_to_text_v1.py b/test/integration/test_speech_to_text_v1.py index 808a88474..1d41df968 100644 --- a/test/integration/test_speech_to_text_v1.py +++ b/test/integration/test_speech_to_text_v1.py @@ -118,83 +118,6 @@ def on_data(self, data): assert test_callback.data['results'][0]['alternatives'][0] ['transcript'] == 'thunderstorms could produce large hail isolated tornadoes and heavy rain ' - def test_on_transcription_interim_results_false(self): - - class MyRecognizeCallback(RecognizeCallback): - - def __init__(self): - RecognizeCallback.__init__(self) - self.error = None - self.transcript = None - - def on_error(self, error): - self.error = error - - def on_transcription(self, transcript): - self.transcript = transcript - - test_callback = MyRecognizeCallback() - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: - audio_source = AudioSource(audio_file, False) - self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", - interim_results=False, low_latency=False) - assert test_callback.error is None - assert test_callback.transcript is not None - assert test_callback.transcript[0][0]['transcript'] in ['isolated tornadoes ', 'isolated tornados '] - assert test_callback.transcript[1][0]['transcript'] == 'and heavy rain ' - - def test_on_transcription_interim_results_true(self): - - class MyRecognizeCallback(RecognizeCallback): - - def __init__(self): - RecognizeCallback.__init__(self) - self.error = None - self.transcript = None - - def on_error(self, error): - self.error = error - - def on_transcription(self, transcript): - self.transcript = transcript - assert transcript[0]['confidence'] is not None - assert transcript[0]['transcript'] is not None - - test_callback = MyRecognizeCallback() - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: - audio_source = AudioSource(audio_file, False) - self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", - interim_results=True, low_latency=True) - assert test_callback.error is None - assert test_callback.transcript is not None - assert test_callback.transcript[0]['transcript'] == 'and heavy rain ' - - def test_on_transcription_interim_results_true_low_latency_false(self): - - class MyRecognizeCallback(RecognizeCallback): - - def __init__(self): - RecognizeCallback.__init__(self) - self.error = None - self.transcript = None - - def on_error(self, error): - self.error = error - - def on_transcription(self, transcript): - self.transcript = transcript - assert transcript[0]['confidence'] is not None - assert transcript[0]['transcript'] is not None - - test_callback = MyRecognizeCallback() - with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: - audio_source = AudioSource(audio_file, False) - self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", - interim_results=True, low_latency=False) - assert test_callback.error is None - assert test_callback.transcript is not None - assert test_callback.transcript[0]['transcript'] == 'and heavy rain ' - def test_custom_grammars(self): customization_id = None for custom_model in self.custom_models.get('customizations'): From c497684e3e40a38b9ee961ebd9afea4970ff363f Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 15 May 2024 14:50:57 -0500 Subject: [PATCH 425/455] build(version): upgrade version to 8.1.0 --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 3238a4cc3..9a2744e14 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 8.0.1 +current_version = 8.1.0 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 49920925b..2d63b74a6 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '8.0.1' +__version__ = '8.1.0' diff --git a/setup.py b/setup.py index 06d519f81..e34bb44b2 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '8.0.1' +__version__ = '8.1.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From 397144fec856aef15067fc5f924465e7a4289178 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 17 May 2024 11:21:04 -0500 Subject: [PATCH 426/455] chore: update changelog --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index df089f2a1..1c3541a5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +# [8.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v8.0.0...v8.1.0) (2024-05-17) + + +### Features + +* **stt:** remove interim_results and low_latency wss params ([035b29d](https://github.com/watson-developer-cloud/python-sdk/commit/035b29d82c35789f782359a9842e50956665b96c)) +* **stt:** add speech_begin_event param to recognize func ([d026ab2](https://github.com/watson-developer-cloud/python-sdk/commit/d026ab2a7ffa950a7ba6b655357f2523cda337ef)) +* **disco-v2:** add ocr_enabled parameter ([460593f](https://github.com/watson-developer-cloud/python-sdk/commit/460593f48fe7e32ea3fc205da05d1dad7318255b)) + # [8.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v7.0.1...v8.0.0) (2024-02-26) From f55b18d043a1bae4e00ade89f0e36c55cc7a73f0 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 11 Oct 2024 14:42:47 -0500 Subject: [PATCH 427/455] docs(readme): update and remove refs to deprecated services --- README.md | 84 +++++++++++++++++++++++++++---------------------------- 1 file changed, 42 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index a0aea98db..e99a46d4a 100755 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ The file downloaded will be called `ibm-credentials.env`. This is the name the S As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following: ```python -discovery = DiscoveryV1(version='2019-04-30') +assistant = AssistantV2(version='2024-08-25') ``` And that's it! @@ -122,7 +122,7 @@ export ASSISTANT_AUTH_TYPE="iam" The credentials will be loaded from the environment automatically ```python -assistant = AssistantV1(version='2018-08-01') +assistant = AssistantV2(version='2024-08-25') ``` #### Manually @@ -142,15 +142,15 @@ You supply either an IAM service **API key** or a **bearer token**: #### Supplying the API key ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator # In the constructor, letting the SDK manage the token authenticator = IAMAuthenticator('apikey', url='') # optional - the default value is https://iam.cloud.ibm.com/identity/token -discovery = DiscoveryV1(version='2019-04-30', +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) -discovery.set_service_url('') +assistant.set_service_url('') ``` #### Generating bearer tokens using API key @@ -166,36 +166,36 @@ token = iam_token_manager.get_token() ##### Supplying the bearer token ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator # in the constructor, assuming control of managing the token authenticator = BearerTokenAuthenticator('your bearer token') -discovery = DiscoveryV1(version='2019-04-30', +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) -discovery.set_service_url('') +assistant.set_service_url('') ``` #### Username and password ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import BasicAuthenticator authenticator = BasicAuthenticator('username', 'password') -discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) -discovery.set_service_url('') +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) +assistant.set_service_url('') ``` #### No Authentication ```python -from ibm_watson import DiscoveryV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator authenticator = NoAuthAuthenticator() -discovery = DiscoveryV1(version='2019-04-30', authenticator=authenticator) -discovery.set_service_url('') +assistant = AssistantV2(version='2024-08-25', authenticator=authenticator) +assistant.set_service_url('') ``` ### MCSP @@ -221,17 +221,17 @@ Tested on Python 3.9, 3.10, and 3.11. If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+python). -## Configuring the http client (Supported from v1.1.0) +## Configuring the http client To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://requests.readthedocs.io/en/latest/api/) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2021-11-27', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') @@ -248,12 +248,12 @@ To use the SDK with any proxies you may have they can be set as shown below. For See this example configuration: ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2021-11-27', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') @@ -268,12 +268,12 @@ assistant.set_http_config({'proxies': { To send custom certificates as a security measure in your request, use the cert property of the HTTPS Agent. ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2021-11-27', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') @@ -322,14 +322,14 @@ For example, to send a header called `Custom-Header` to a call in Watson Assista the headers parameter as: ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2018-07-10', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) -assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') +assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() ``` @@ -339,14 +339,14 @@ response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}). If you would like access to some HTTP response information along with the response model, you can set the `set_detailed_response()` to `True`. Since Python SDK `v2.0`, it is set to `True` ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') -assistant = AssistantV1( - version='2018-07-10', +assistant = AssistantV2( + version='2024-08-25', authenticator=authenticator) -assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') +assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') assistant.set_detailed_response(True) response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() @@ -372,9 +372,9 @@ Every SDK call returns a response with a transaction ID in the `X-Global-Transac ### Suceess ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 -service = AssistantV1(authenticator={my_authenticator}) +service = AssistantV2(authenticator={my_authenticator}) response_headers = service.my_service_call().get_headers() print(response_headers.get('X-Global-Transaction-Id')) ``` @@ -382,10 +382,10 @@ print(response_headers.get('X-Global-Transaction-Id')) ### Failure ```python -from ibm_watson import AssistantV1, ApiException +from ibm_watson import AssistantV2, ApiException try: - service = AssistantV1(authenticator={my_authenticator}) + service = AssistantV2(authenticator={my_authenticator}) service.my_service_call() except ApiException as e: print(e.global_transaction_id) @@ -396,9 +396,9 @@ except ApiException as e: However, the transaction ID isn't available when the API doesn't return a response for some reason. In that case, you can set your own transaction ID in the request. For example, replace `` in the following example with a unique transaction ID. ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 -service = AssistantV1(authenticator={my_authenticator}) +service = AssistantV2(authenticator={my_authenticator}) service.my_service_call(headers={'X-Global-Transaction-Id': ''}) ``` @@ -436,7 +436,7 @@ If your service instance is of CP4D, below are two ways of initializing the assi The SDK will manage the token for the user ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator authenticator = CloudPakForDataAuthenticator( @@ -445,7 +445,7 @@ authenticator = CloudPakForDataAuthenticator( '', # should be of the form https://{icp_cluster_host}{instance-id}/api disable_ssl_verification=True) # Disable ssl verification for authenticator -assistant = AssistantV1( +assistant = AssistantV2( version='', authenticator=authenticator) assistant.set_service_url('') # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api @@ -455,11 +455,11 @@ assistant.set_disable_ssl_verification(True) # MAKE SURE SSL VERIFICATION IS DIS ### 2) Supplying the access token ```python -from ibm_watson import AssistantV1 +from ibm_watson import AssistantV2 from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator authenticator = BearerTokenAuthenticator('your managed access token') -assistant = AssistantV1(version='', +assistant = AssistantV2(version='', authenticator=authenticator) assistant.set_service_url('') # should be of the form https://{icp_cluster_host}/{deployment}/assistant/{instance-id}/api assistant.set_disable_ssl_verification(True) # MAKE SURE SSL VERIFICATION IS DISABLED From ffc67b8a0b213530cda23157848d79b5fea4b146 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 17 Oct 2024 10:25:03 -0500 Subject: [PATCH 428/455] feat(stt): readd interimResults and lowLatency wss params --- examples/microphone-speech-to-text.py | 3 +- ibm_watson/speech_to_text_v1_adapter.py | 22 +++++++- ibm_watson/websocket/recognize_listener.py | 19 +++---- test/integration/test_speech_to_text_v1.py | 60 ++++++++++++++++++++++ 4 files changed, 93 insertions(+), 11 deletions(-) diff --git a/examples/microphone-speech-to-text.py b/examples/microphone-speech-to-text.py index fb0fbd1ae..9174de74f 100644 --- a/examples/microphone-speech-to-text.py +++ b/examples/microphone-speech-to-text.py @@ -72,7 +72,8 @@ def recognize_using_weboscket(*args): mycallback = MyRecognizeCallback() speech_to_text.recognize_using_websocket(audio=audio_source, content_type='audio/l16; rate=44100', - recognize_callback=mycallback) + recognize_callback=mycallback, + interim_results=True) ############################################### #### Prepare the for recording using Pyaudio ## diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index 67820be85..dabe6526d 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -33,6 +33,7 @@ def recognize_using_websocket(self, customization_weight=None, base_model_version=None, inactivity_timeout=None, + interim_results=None, keywords=None, keywords_threshold=None, max_alternatives=None, @@ -54,6 +55,7 @@ def recognize_using_websocket(self, split_transcript_at_phrase_end=None, speech_detector_sensitivity=None, background_audio_suppression=None, + low_latency=None, character_insertion_bias=None, **kwargs): """ @@ -269,6 +271,22 @@ def recognize_using_websocket(self, * 1.0 suppresses all audio (no audio is transcribed). The values increase on a monotonic curve. See [Background audio suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression). + :param bool low_latency: (optional) If `true` for next-generation + `Multimedia` and `Telephony` models that support low latency, directs the + service to produce results even more quickly than it usually does. + Next-generation models produce transcription results faster than + previous-generation models. The `low_latency` parameter causes the models + to produce results even more quickly, though the results might be less + accurate when the parameter is used. + **Note:** The parameter is beta functionality. It is not available for + previous-generation `Broadband` and `Narrowband` models. It is available + only for some next-generation models. + * For a list of next-generation models that support low latency, see + [Supported language + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported) + for next-generation models. + * For more information about the `low_latency` parameter, see [Low + latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). :param float character_insertion_bias: (optional) For next-generation `Multimedia` and `Telephony` models, an indication of whether the service is biased to recognize shorter or longer strings of characters when @@ -337,6 +355,7 @@ def recognize_using_websocket(self, 'customization_weight': customization_weight, 'content_type': content_type, 'inactivity_timeout': inactivity_timeout, + 'interim_results': interim_results, 'keywords': keywords, 'keywords_threshold': keywords_threshold, 'max_alternatives': max_alternatives, @@ -356,7 +375,8 @@ def recognize_using_websocket(self, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, 'background_audio_suppression': background_audio_suppression, - 'character_insertion_bias': character_insertion_bias + 'character_insertion_bias': character_insertion_bias, + 'low_latency': low_latency, } options = {k: v for k, v in options.items() if v is not None} request['options'] = options diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index 041bcf693..43eb79618 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -196,15 +196,16 @@ def on_data(self, ws, message, message_type, fin): # set of transcriptions and send them to the appropriate callbacks. results = json_object.get('results') if results: - b_final = (results[0].get('final') is True) - alternatives = results[0].get('alternatives') - if alternatives: - hypothesis = alternatives[0].get('transcript') - transcripts = self.extract_transcripts(alternatives) - if b_final: - self.callback.on_transcription(transcripts) - if hypothesis: - self.callback.on_hypothesis(hypothesis) + if (self.options.get('interim_results') is True): + b_final = (results[0].get('final') is True) + alternatives = results[0].get('alternatives') + if alternatives: + hypothesis = alternatives[0].get('transcript') + transcripts = self.extract_transcripts(alternatives) + if b_final: + self.callback.on_transcription(transcripts) + if hypothesis: + self.callback.on_hypothesis(hypothesis) else: final_transcript = [] for result in results: diff --git a/test/integration/test_speech_to_text_v1.py b/test/integration/test_speech_to_text_v1.py index 1d41df968..4defbea19 100644 --- a/test/integration/test_speech_to_text_v1.py +++ b/test/integration/test_speech_to_text_v1.py @@ -118,6 +118,66 @@ def on_data(self, data): assert test_callback.data['results'][0]['alternatives'][0] ['transcript'] == 'thunderstorms could produce large hail isolated tornadoes and heavy rain ' + def test_on_transcription_interim_results_false(self): + class MyRecognizeCallback(RecognizeCallback): + def __init__(self): + RecognizeCallback.__init__(self) + self.error = None + self.transcript = None + def on_error(self, error): + self.error = error + def on_transcription(self, transcript): + self.transcript = transcript + test_callback = MyRecognizeCallback() + with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: + audio_source = AudioSource(audio_file, False) + self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", + interim_results=False, low_latency=False) + assert test_callback.error is None + assert test_callback.transcript is not None + assert test_callback.transcript[0][0]['transcript'] in ['isolated tornadoes ', 'isolated tornados '] + assert test_callback.transcript[1][0]['transcript'] == 'and heavy rain ' + def test_on_transcription_interim_results_true(self): + class MyRecognizeCallback(RecognizeCallback): + def __init__(self): + RecognizeCallback.__init__(self) + self.error = None + self.transcript = None + def on_error(self, error): + self.error = error + def on_transcription(self, transcript): + self.transcript = transcript + assert transcript[0]['confidence'] is not None + assert transcript[0]['transcript'] is not None + test_callback = MyRecognizeCallback() + with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: + audio_source = AudioSource(audio_file, False) + self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", + interim_results=True, low_latency=True) + assert test_callback.error is None + assert test_callback.transcript is not None + assert test_callback.transcript[0]['transcript'] == 'and heavy rain ' + def test_on_transcription_interim_results_true_low_latency_false(self): + class MyRecognizeCallback(RecognizeCallback): + def __init__(self): + RecognizeCallback.__init__(self) + self.error = None + self.transcript = None + def on_error(self, error): + self.error = error + def on_transcription(self, transcript): + self.transcript = transcript + assert transcript[0]['confidence'] is not None + assert transcript[0]['transcript'] is not None + test_callback = MyRecognizeCallback() + with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: + audio_source = AudioSource(audio_file, False) + self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", + interim_results=True, low_latency=False) + assert test_callback.error is None + assert test_callback.transcript is not None + assert test_callback.transcript[0]['transcript'] == 'and heavy rain ' + def test_custom_grammars(self): customization_id = None for custom_model in self.custom_models.get('customizations'): From 4948b8f210e5b9cd2d856aa90f2262a8bdf64444 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 17 Oct 2024 10:26:03 -0500 Subject: [PATCH 429/455] feat(stt): add new speech models --- ibm_watson/speech_to_text_v1.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 0ad6d3761..b0831533f 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -4332,19 +4332,25 @@ class ModelId(str, Enum): EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' + ES_AR = 'es-AR' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL = 'es-CL' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO = 'es-CO' ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES = 'es-ES' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' ES_LA_TELEPHONY = 'es-LA_Telephony' + ES_MX = 'es-MX' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE = 'es-PE' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA = 'fr-CA' @@ -4376,6 +4382,7 @@ class ModelId(str, Enum): NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' + PT_BR = 'pt-BR' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' @@ -4454,19 +4461,25 @@ class Model(str, Enum): EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' + ES_AR = 'es-AR' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL = 'es-CL' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO = 'es-CO' ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES = 'es-ES' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' ES_LA_TELEPHONY = 'es-LA_Telephony' + ES_MX = 'es-MX' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE = 'es-PE' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA = 'fr-CA' @@ -4498,6 +4511,7 @@ class Model(str, Enum): NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' + PT_BR = 'pt-BR' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' @@ -4576,19 +4590,25 @@ class Model(str, Enum): EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' + ES_AR = 'es-AR' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' + ES_CL = 'es-CL' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' ES_CL_NARROWBANDMODEL = 'es-CL_NarrowbandModel' + ES_CO = 'es-CO' ES_CO_BROADBANDMODEL = 'es-CO_BroadbandModel' ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' + ES_ES = 'es-ES' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' ES_LA_TELEPHONY = 'es-LA_Telephony' + ES_MX = 'es-MX' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' + ES_PE = 'es-PE' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' ES_PE_NARROWBANDMODEL = 'es-PE_NarrowbandModel' FR_CA = 'fr-CA' @@ -4620,6 +4640,7 @@ class Model(str, Enum): NL_NL_MULTIMEDIA = 'nl-NL_Multimedia' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' NL_NL_TELEPHONY = 'nl-NL_Telephony' + PT_BR = 'pt-BR' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_MULTIMEDIA = 'pt-BR_Multimedia' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' From c6b768de4a9b00f58592541f007f9c60f1452320 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 17 Oct 2024 11:26:07 -0500 Subject: [PATCH 430/455] fix(nlu): remove summarization param BREAKING CHANGE: change training_data_content_type default to None --- .../natural_language_understanding_v1.py | 96 +------------------ .../test_natural_language_understanding_v1.py | 44 --------- 2 files changed, 4 insertions(+), 136 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 967e52c05..d56cb3647 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -24,15 +24,6 @@ models](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) with Watson Knowledge Studio to detect custom entities and relations in Natural Language Understanding. -IBM is sunsetting Watson Natural Language Understanding Custom Sentiment (BETA). From -**June 3, 2023** onward, you will no longer be able to use the Custom Sentiment -feature.

To ensure we continue providing our clients with robust and powerful -text classification capabilities, IBM recently announced the general availability of a new -[single-label text classification -capability](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-classifications). -This new feature includes extended language support and training data customizations -suited for building a custom sentiment classifier.

If you would like more -information or further guidance, please contact IBM Cloud Support.{: deprecated} API Version: 1.0 See: https://cloud.ibm.com/docs/natural-language-understanding @@ -122,7 +113,6 @@ def analyze( - Semantic roles - Sentiment - Syntax - - Summarization (Experimental) If a language for the input text is not specified with the `language` parameter, the service [automatically detects the language](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-detectable-languages). @@ -312,7 +302,7 @@ def create_categories_model( language: str, training_data: BinaryIO, *, - training_data_content_type: Optional[str] = 'application/json', + training_data_content_type: Optional[str] = None, name: Optional[str] = None, user_metadata: Optional[dict] = None, description: Optional[str] = None, @@ -499,7 +489,7 @@ def update_categories_model( language: str, training_data: BinaryIO, *, - training_data_content_type: Optional[str] = 'application/json', + training_data_content_type: Optional[str] = None, name: Optional[str] = None, user_metadata: Optional[dict] = None, description: Optional[str] = None, @@ -653,7 +643,7 @@ def create_classifications_model( language: str, training_data: BinaryIO, *, - training_data_content_type: Optional[str] = 'application/json', + training_data_content_type: Optional[str] = None, name: Optional[str] = None, user_metadata: Optional[dict] = None, description: Optional[str] = None, @@ -849,7 +839,7 @@ def update_classifications_model( language: str, training_data: BinaryIO, *, - training_data_content_type: Optional[str] = 'application/json', + training_data_content_type: Optional[str] = None, name: Optional[str] = None, user_metadata: Optional[dict] = None, description: Optional[str] = None, @@ -3632,10 +3622,6 @@ class Features: `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :param SummarizationOptions summarization: (optional) (Experimental) Returns a - summary of content. - Supported languages: English only. - Supported regions: Dallas region only. :param CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, @@ -3656,7 +3642,6 @@ def __init__( relations: Optional['RelationsOptions'] = None, semantic_roles: Optional['SemanticRolesOptions'] = None, sentiment: Optional['SentimentOptions'] = None, - summarization: Optional['SummarizationOptions'] = None, categories: Optional['CategoriesOptions'] = None, syntax: Optional['SyntaxOptions'] = None, ) -> None: @@ -3707,10 +3692,6 @@ def __init__( and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - :param SummarizationOptions summarization: (optional) (Experimental) - Returns a summary of content. - Supported languages: English only. - Supported regions: Dallas region only. :param CategoriesOptions categories: (optional) Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, @@ -3727,7 +3708,6 @@ def __init__( self.relations = relations self.semantic_roles = semantic_roles self.sentiment = sentiment - self.summarization = summarization self.categories = categories self.syntax = syntax @@ -3755,9 +3735,6 @@ def from_dict(cls, _dict: Dict) -> 'Features': semantic_roles) if (sentiment := _dict.get('sentiment')) is not None: args['sentiment'] = SentimentOptions.from_dict(sentiment) - if (summarization := _dict.get('summarization')) is not None: - args['summarization'] = SummarizationOptions.from_dict( - summarization) if (categories := _dict.get('categories')) is not None: args['categories'] = CategoriesOptions.from_dict(categories) if (syntax := _dict.get('syntax')) is not None: @@ -3815,11 +3792,6 @@ def to_dict(self) -> Dict: _dict['sentiment'] = self.sentiment else: _dict['sentiment'] = self.sentiment.to_dict() - if hasattr(self, 'summarization') and self.summarization is not None: - if isinstance(self.summarization, dict): - _dict['summarization'] = self.summarization - else: - _dict['summarization'] = self.summarization.to_dict() if hasattr(self, 'categories') and self.categories is not None: if isinstance(self.categories, dict): _dict['categories'] = self.categories @@ -5619,66 +5591,6 @@ def __ne__(self, other: 'SentimentResult') -> bool: return not self == other -class SummarizationOptions: - """ - (Experimental) Returns a summary of content. - Supported languages: English only. - Supported regions: Dallas region only. - - :param int limit: (optional) Maximum number of summary sentences to return. - """ - - def __init__( - self, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a SummarizationOptions object. - - :param int limit: (optional) Maximum number of summary sentences to return. - """ - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SummarizationOptions': - """Initialize a SummarizationOptions object from a json dictionary.""" - args = {} - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SummarizationOptions 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, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 SummarizationOptions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SummarizationOptions') -> 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: 'SummarizationOptions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class SyntaxOptions: """ Returns tokens and sentences from the input text. diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index b79c21c48..86e529fc1 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -136,10 +136,6 @@ def test_analyze_all_params(self): sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - # Construct a dict representation of a SummarizationOptions model - summarization_options_model = {} - summarization_options_model['limit'] = 3 - # Construct a dict representation of a CategoriesOptions model categories_options_model = {} categories_options_model['explanation'] = False @@ -167,7 +163,6 @@ def test_analyze_all_params(self): features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model - features_model['summarization'] = summarization_options_model features_model['categories'] = categories_options_model features_model['syntax'] = syntax_options_model @@ -281,10 +276,6 @@ def test_analyze_value_error(self): sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - # Construct a dict representation of a SummarizationOptions model - summarization_options_model = {} - summarization_options_model['limit'] = 3 - # Construct a dict representation of a CategoriesOptions model categories_options_model = {} categories_options_model['explanation'] = False @@ -312,7 +303,6 @@ def test_analyze_value_error(self): features_model['relations'] = relations_options_model features_model['semantic_roles'] = semantic_roles_options_model features_model['sentiment'] = sentiment_options_model - features_model['summarization'] = summarization_options_model features_model['categories'] = categories_options_model features_model['syntax'] = syntax_options_model @@ -2787,9 +2777,6 @@ def test_features_serialization(self): sentiment_options_model['document'] = True sentiment_options_model['targets'] = ['testString'] - summarization_options_model = {} # SummarizationOptions - summarization_options_model['limit'] = 3 - categories_options_model = {} # CategoriesOptions categories_options_model['explanation'] = False categories_options_model['limit'] = 3 @@ -2814,7 +2801,6 @@ def test_features_serialization(self): features_model_json['relations'] = relations_options_model features_model_json['semantic_roles'] = semantic_roles_options_model features_model_json['sentiment'] = sentiment_options_model - features_model_json['summarization'] = summarization_options_model features_model_json['categories'] = categories_options_model features_model_json['syntax'] = syntax_options_model @@ -3639,36 +3625,6 @@ def test_sentiment_result_serialization(self): assert sentiment_result_model_json2 == sentiment_result_model_json -class TestModel_SummarizationOptions: - """ - Test Class for SummarizationOptions - """ - - def test_summarization_options_serialization(self): - """ - Test serialization/deserialization for SummarizationOptions - """ - - # Construct a json representation of a SummarizationOptions model - summarization_options_model_json = {} - summarization_options_model_json['limit'] = 3 - - # Construct a model instance of SummarizationOptions by calling from_dict on the json representation - summarization_options_model = SummarizationOptions.from_dict(summarization_options_model_json) - assert summarization_options_model != False - - # Construct a model instance of SummarizationOptions by calling from_dict on the json representation - summarization_options_model_dict = SummarizationOptions.from_dict(summarization_options_model_json).__dict__ - summarization_options_model2 = SummarizationOptions(**summarization_options_model_dict) - - # Verify the model instances are equivalent - assert summarization_options_model == summarization_options_model2 - - # Convert model instance back to dict and verify no loss of data - summarization_options_model_json2 = summarization_options_model.to_dict() - assert summarization_options_model_json2 == summarization_options_model_json - - class TestModel_SyntaxOptions: """ Test Class for SyntaxOptions From 9dd173b4769de6cd70978860e4c04b4436addf93 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 17 Oct 2024 12:08:06 -0500 Subject: [PATCH 431/455] feat(discov1): remove discoV1 BREAKING CHANGE: DiscoveryV1 functionality has been removed --- .github/workflows/integration-test.yml | 6 - examples/discovery_v1.py | 65 - ibm_watson/__init__.py | 1 - ibm_watson/discovery_v1.py | 15128 ----------------------- test/integration/test_discovery_v1.py | 292 - test/unit/test_discovery_v1.py | 12080 ------------------ 6 files changed, 27572 deletions(-) delete mode 100644 examples/discovery_v1.py delete mode 100644 ibm_watson/discovery_v1.py delete mode 100644 test/integration/test_discovery_v1.py delete mode 100644 test/unit/test_discovery_v1.py diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index 05e66e579..4f55f471d 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -47,18 +47,12 @@ jobs: ASSISTANT_WORKSPACE_ID: ${{ secrets.WA_WORKSPACE_ID }} ASSISTANT_ASSISTANT_ID: ${{ secrets.WA_ASSISTANT_ID }} ASSISTANT_URL: "https://api.us-south.assistant.watson.cloud.ibm.com" - DISCOVERY_APIKEY: ${{ secrets.D1_APIKEY }} - DISCOVERY_ENVIRONMENT_ID: ${{ secrets.D1_ENVIRONMENT_ID }} - DISCOVERY_COLLECTION_ID: ${{ secrets.D1_COLLECTION_ID }} - DISCOVERY_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" DISCOVERY_V2_APIKEY: ${{ secrets.D2_APIKEY }} DISCOVERY_V2_PROJECT_ID: ${{ secrets.D2_PROJECT_ID }} DISCOVERY_V2_COLLECTION_ID: ${{ secrets.D2_COLLECTION_ID }} DISCOVERY_V2_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" run: | pip3 install -U python-dotenv - pytest test/integration/test_assistant_v1.py -rap - pytest test/integration/test_discovery_v1.py -rap pytest test/integration/test_discovery_v2.py -rap pytest test/integration/test_language_translator_v3.py -rap pytest test/integration/test_natural_language_understanding_v1.py -rap diff --git a/examples/discovery_v1.py b/examples/discovery_v1.py deleted file mode 100644 index 4f32acf22..000000000 --- a/examples/discovery_v1.py +++ /dev/null @@ -1,65 +0,0 @@ -import json -from ibm_watson import DiscoveryV1 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your_api_key') -discovery = DiscoveryV1( - version='2018-08-01', - authenticator=authenticator) -discovery.set_service_url('https://api.us-south.discovery.watson.cloud.ibm.com') - -environments = discovery.list_environments().get_result() -print(json.dumps(environments, indent=2)) - -news_environment_id = 'system' -print(json.dumps(news_environment_id, indent=2)) - -collections = discovery.list_collections(news_environment_id).get_result() -news_collections = [x for x in collections['collections']] -print(json.dumps(collections, indent=2)) - -configurations = discovery.list_configurations( - environment_id=news_environment_id).get_result() -print(json.dumps(configurations, indent=2)) - -query_results = discovery.query( - news_environment_id, - news_collections[0]['collection_id'], - filter='extracted_metadata.sha1::f5*', - return_fields='extracted_metadata.sha1').get_result() -print(json.dumps(query_results, indent=2)) - -# new_environment = discovery.create_environment(name="new env", description="bogus env").get_result() -# print(new_environment) - -# environment = discovery.get_environment(environment_id=new_environment['environment_id']).get_result() -# if environment['status'] == 'active': -# writable_environment_id = new_environment['environment_id'] -# new_collection = discovery.create_collection(environment_id=writable_environment_id, -# name='Example Collection', -# description="just a test").get_result() - -# print(new_collection) - -# collections = discovery.list_collections(environment_id=writable_environment_id).get_result() -# print(collections) - -# res = discovery.delete_collection(environment_id='', -# collection_id=new_collection['collection_id']).get_result() -# print(res) - -# collections = discovery.list_collections(environment_id=writable_environment_id).get_result() -# print(collections) - -# with open(os.path.join(os.getcwd(), '..','resources', 'simple.html')) as fileinfo: -# res = discovery.add_document(environment_id=writable_environment_id, -# collection_id=collections['collections'][0]['collection_id'], -# file=fileinfo).get_result() -# print(res) - -# res = discovery.get_collection(environment_id=writable_environment_id, -# collection_id=collections['collections'][0]['collection_id']).get_result() -# print(res['document_counts']) - -#res = discovery.delete_environment(environment_id=writable_environment_id).get_result() -#print(res) diff --git a/ibm_watson/__init__.py b/ibm_watson/__init__.py index aed80a796..12ace99e0 100755 --- a/ibm_watson/__init__.py +++ b/ibm_watson/__init__.py @@ -20,7 +20,6 @@ from .language_translator_v3 import LanguageTranslatorV3 from .natural_language_understanding_v1 import NaturalLanguageUnderstandingV1 from .text_to_speech_v1 import TextToSpeechV1 -from .discovery_v1 import DiscoveryV1 from .discovery_v2 import DiscoveryV2 from .version import __version__ from .common import get_sdk_headers diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py deleted file mode 100644 index a604775e5..000000000 --- a/ibm_watson/discovery_v1.py +++ /dev/null @@ -1,15128 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2019, 2024. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 -""" -IBM Watson™ Discovery v1 is a cognitive search and content analytics engine that you -can add to applications to identify patterns, trends and actionable insights to drive -better decision-making. Securely unify structured and unstructured data with pre-enriched -content, and use a simplified query language to eliminate the need for manual filtering of -results. - -API Version: 1.0 -See: https://cloud.ibm.com/docs/discovery -""" - -from datetime import date -from datetime import datetime -from enum import Enum -from os.path import basename -from typing import BinaryIO, Dict, List, Optional -import json -import sys - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import convert_list, convert_model, date_to_string, datetime_to_string, string_to_date, string_to_datetime - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class DiscoveryV1(BaseService): - """The Discovery V1 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.discovery.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'discovery' - - def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Discovery service. - - :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2019-04-30`. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md - about initializing the authenticator of your choice. - """ - if version is None: - raise ValueError('version must be provided') - - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.version = version - self.configure_service(service_name) - - ######################### - # Environments - ######################### - - def create_environment( - self, - name: str, - *, - description: Optional[str] = None, - size: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create an environment. - - Creates a new environment for private data. An environment must be created before - collections can be created. - **Note**: You can create only one environment for private data per service - instance. An attempt to create another environment results in an error. - - :param str name: Name that identifies the environment. - :param str description: (optional) Description of the environment. - :param str size: (optional) Size of the environment. In the Lite plan the - default and only accepted value is `LT`, in all other plans the default is - `S`. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Environment` object - """ - - if name is None: - raise ValueError('name must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_environment', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'size': size, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/environments' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def list_environments( - self, - *, - name: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - List environments. - - List existing environments for the service instance. - - :param str name: (optional) Show only the environment with the given name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListEnvironmentsResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_environments', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'name': name, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/environments' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_environment( - self, - environment_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get environment info. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Environment` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_environment', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_environment( - self, - environment_id: str, - *, - name: Optional[str] = None, - description: Optional[str] = None, - size: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Update an environment. - - Updates an environment. The environment's **name** and **description** parameters - can be changed. You must specify a **name** for the environment. - - :param str environment_id: The ID of the environment. - :param str name: (optional) Name that identifies the environment. - :param str description: (optional) Description of the environment. - :param str size: (optional) Size to change the environment to. **Note:** - Lite plan users cannot change the environment size. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Environment` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_environment', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'size': size, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_environment( - self, - environment_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete environment. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteEnvironmentResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_environment', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}'.format(**path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def list_fields( - self, - environment_id: str, - collection_ids: List[str], - **kwargs, - ) -> DetailedResponse: - """ - List fields across collections. - - Gets a list of the unique fields (and their types) stored in the indexes of the - specified collections. - - :param str environment_id: The ID of the environment. - :param List[str] collection_ids: A comma-separated list of collection IDs - to be queried against. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListCollectionFieldsResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if collection_ids is None: - raise ValueError('collection_ids must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_fields', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'collection_ids': convert_list(collection_ids), - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/fields'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Configurations - ######################### - - def create_configuration( - self, - environment_id: str, - name: str, - *, - description: Optional[str] = None, - conversions: Optional['Conversions'] = None, - enrichments: Optional[List['Enrichment']] = None, - normalizations: Optional[List['NormalizationOperation']] = None, - source: Optional['Source'] = None, - **kwargs, - ) -> DetailedResponse: - """ - Add configuration. - - Creates a new configuration. - If the input configuration contains the **configuration_id**, **created**, or - **updated** properties, then they are ignored and overridden by the system, and an - error is not returned so that the overridden fields do not need to be removed when - copying a configuration. - The configuration can contain unrecognized JSON fields. Any such fields are - ignored and do not generate an error. This makes it easier to use newer - configuration files with older versions of the API and the service. It also makes - it possible for the tooling to add additional metadata and information to the - configuration. - - :param str environment_id: The ID of the environment. - :param str name: The name of the configuration. - :param str description: (optional) The description of the configuration, if - available. - :param Conversions conversions: (optional) Document conversion settings. - :param List[Enrichment] enrichments: (optional) An array of document - enrichment settings for the configuration. - :param List[NormalizationOperation] normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a - normalized form. Operations are executed in the order that they appear in - the array. - :param Source source: (optional) Object containing source parameters for - the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Configuration` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if name is None: - raise ValueError('name must be provided') - if conversions is not None: - conversions = convert_model(conversions) - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] - if normalizations is not None: - normalizations = [convert_model(x) for x in normalizations] - if source is not None: - source = convert_model(source) - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_configuration', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'conversions': conversions, - 'enrichments': enrichments, - 'normalizations': normalizations, - 'source': source, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def list_configurations( - self, - environment_id: str, - *, - name: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - List configurations. - - Lists existing configurations for the service instance. - - :param str environment_id: The ID of the environment. - :param str name: (optional) Find configurations with the given name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListConfigurationsResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_configurations', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'name': name, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_configuration( - self, - environment_id: str, - configuration_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get configuration details. - - :param str environment_id: The ID of the environment. - :param str configuration_id: The ID of the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Configuration` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not configuration_id: - raise ValueError('configuration_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_configuration', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'configuration_id'] - path_param_values = self.encode_path_vars(environment_id, - configuration_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_configuration( - self, - environment_id: str, - configuration_id: str, - name: str, - *, - description: Optional[str] = None, - conversions: Optional['Conversions'] = None, - enrichments: Optional[List['Enrichment']] = None, - normalizations: Optional[List['NormalizationOperation']] = None, - source: Optional['Source'] = None, - **kwargs, - ) -> DetailedResponse: - """ - Update a configuration. - - Replaces an existing configuration. - * Completely replaces the original configuration. - * The **configuration_id**, **updated**, and **created** fields are accepted in - the request, but they are ignored, and an error is not generated. It is also - acceptable for users to submit an updated configuration with none of the three - properties. - * Documents are processed with a snapshot of the configuration as it was at the - time the document was submitted to be ingested. This means that already submitted - documents will not see any updates made to the configuration. - - :param str environment_id: The ID of the environment. - :param str configuration_id: The ID of the configuration. - :param str name: The name of the configuration. - :param str description: (optional) The description of the configuration, if - available. - :param Conversions conversions: (optional) Document conversion settings. - :param List[Enrichment] enrichments: (optional) An array of document - enrichment settings for the configuration. - :param List[NormalizationOperation] normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a - normalized form. Operations are executed in the order that they appear in - the array. - :param Source source: (optional) Object containing source parameters for - the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Configuration` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not configuration_id: - raise ValueError('configuration_id must be provided') - if name is None: - raise ValueError('name must be provided') - if conversions is not None: - conversions = convert_model(conversions) - if enrichments is not None: - enrichments = [convert_model(x) for x in enrichments] - if normalizations is not None: - normalizations = [convert_model(x) for x in normalizations] - if source is not None: - source = convert_model(source) - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_configuration', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'conversions': conversions, - 'enrichments': enrichments, - 'normalizations': normalizations, - 'source': source, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'configuration_id'] - path_param_values = self.encode_path_vars(environment_id, - configuration_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_configuration( - self, - environment_id: str, - configuration_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete a configuration. - - The deletion is performed unconditionally. A configuration deletion request - succeeds even if the configuration is referenced by a collection or document - ingestion. However, documents that have already been submitted for processing - continue to use the deleted configuration. Documents are always processed with a - snapshot of the configuration as it existed at the time the document was - submitted. - - :param str environment_id: The ID of the environment. - :param str configuration_id: The ID of the configuration. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteConfigurationResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not configuration_id: - raise ValueError('configuration_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_configuration', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'configuration_id'] - path_param_values = self.encode_path_vars(environment_id, - configuration_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/configurations/{configuration_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Collections - ######################### - - def create_collection( - self, - environment_id: str, - name: str, - *, - description: Optional[str] = None, - configuration_id: Optional[str] = None, - language: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create a collection. - - :param str environment_id: The ID of the environment. - :param str name: The name of the collection to be created. - :param str description: (optional) A description of the collection. - :param str configuration_id: (optional) The ID of the configuration in - which the collection is to be created. - :param str language: (optional) The language of the documents stored in the - collection, in the form of an ISO 639-1 language code. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Collection` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if name is None: - raise ValueError('name must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_collection', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'configuration_id': configuration_id, - 'language': language, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def list_collections( - self, - environment_id: str, - *, - name: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - List collections. - - Lists existing collections for the service instance. - - :param str environment_id: The ID of the environment. - :param str name: (optional) Find collections with the given name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_collections', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'name': name, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_collection( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get collection details. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID 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 with `dict` result representing a `Collection` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_collection', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_collection( - self, - environment_id: str, - collection_id: str, - name: str, - *, - description: Optional[str] = None, - configuration_id: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Update a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str name: The name of the collection. - :param str description: (optional) A description of the collection. - :param str configuration_id: (optional) The ID of the configuration in - which the collection is to be updated. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Collection` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if name is None: - raise ValueError('name must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_collection', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - 'description': description, - 'configuration_id': configuration_id, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_collection( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID 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 with `dict` result representing a `DeleteCollectionResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_collection', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def list_collection_fields( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List collection fields. - - Gets a list of the unique fields (and their types) stored in the index. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID 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 with `dict` result representing a `ListCollectionFieldsResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_collection_fields', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/fields'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Query modifications - ######################### - - def list_expansions( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get the expansion list. - - Returns the current expansion list for the specified collection. If an expansion - list is not specified, an object with empty expansion arrays is returned. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID 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 with `dict` result representing a `Expansions` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_expansions', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_expansions( - self, - environment_id: str, - collection_id: str, - expansions: List['Expansion'], - **kwargs, - ) -> DetailedResponse: - """ - Create or update expansion list. - - Create or replace the Expansion list for this collection. The maximum number of - expanded terms per collection is `500`. The current expansion list is replaced - with the uploaded content. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param List[Expansion] expansions: An array of query expansion definitions. - Each object in the **expansions** array represents a term or set of terms - that will be expanded into other terms. Each expansion object can be - configured as bidirectional or unidirectional. Bidirectional means that all - terms are expanded to all other terms in the object. Unidirectional means - that a set list of terms can be expanded into a second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. - When found in a query, all items in the **expanded_terms** array are then - expanded to the other items in the same array. - To create a uni-directional expansion, specify both an array of - **input_terms** and an array of **expanded_terms**. When items in the - **input_terms** array are present in a query, they are expanded using the - items listed in the **expanded_terms** array. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Expansions` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if expansions is None: - raise ValueError('expansions must be provided') - expansions = [convert_model(x) for x in expansions] - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_expansions', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'expansions': expansions, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_expansions( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete the expansion list. - - Remove the expansion information for this collection. The expansion list must be - deleted to disable query expansion for a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID 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 not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_expansions', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/expansions'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_tokenization_dictionary_status( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get tokenization dictionary status. - - Returns the current status of the tokenization dictionary for the specified - collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID 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 with `dict` result representing a `TokenDictStatusResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_tokenization_dictionary_status', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_tokenization_dictionary( - self, - environment_id: str, - collection_id: str, - *, - tokenization_rules: Optional[List['TokenDictRule']] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create tokenization dictionary. - - Upload a custom tokenization dictionary to use with the specified collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param List[TokenDictRule] tokenization_rules: (optional) An array of - tokenization rules. Each rule contains, the original `text` string, - component `tokens`, any alternate character set `readings`, and which - `part_of_speech` the text is from. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if tokenization_rules is not None: - tokenization_rules = [convert_model(x) for x in tokenization_rules] - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_tokenization_dictionary', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'tokenization_rules': tokenization_rules, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_tokenization_dictionary( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete tokenization dictionary. - - Delete the tokenization dictionary from the collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID 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 not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_tokenization_dictionary', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/tokenization_dictionary'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_stopword_list_status( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get stopword list status. - - Returns the current status of the stopword list for the specified collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID 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 with `dict` result representing a `TokenDictStatusResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_stopword_list_status', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_stopword_list( - self, - environment_id: str, - collection_id: str, - stopword_file: BinaryIO, - *, - stopword_filename: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create stopword list. - - Upload a custom stopword list to use with the specified collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param BinaryIO stopword_file: The content of the stopword list to ingest. - :param str stopword_filename: (optional) The filename for stopword_file. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TokenDictStatusResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if stopword_file is None: - raise ValueError('stopword_file must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_stopword_list', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - form_data = [] - if not stopword_filename and hasattr(stopword_file, 'name'): - stopword_filename = basename(stopword_file.name) - if not stopword_filename: - raise ValueError('stopword_filename must be provided') - form_data.append(('stopword_file', (stopword_filename, stopword_file, - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_stopword_list( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete a custom stopword list. - - Delete a custom stopword list from the collection. After a custom stopword list is - deleted, the default list is used for the collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID 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 not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_stopword_list', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/word_lists/stopwords'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Documents - ######################### - - def add_document( - self, - environment_id: str, - collection_id: str, - *, - file: Optional[BinaryIO] = None, - filename: Optional[str] = None, - file_content_type: Optional[str] = None, - metadata: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Add a document. - - Add a document to a collection with optional metadata. - * The **version** query parameter is still required. - * Returns immediately after the system has accepted the document for processing. - * The user must provide document content, metadata, or both. If the request is - missing both document content and metadata, it is rejected. - * The user can set the **Content-Type** parameter on the **file** part to - indicate the media type of the document. If the **Content-Type** parameter is - missing or is one of the generic media types (for example, - `application/octet-stream`), then the service attempts to automatically detect the - document's media type. - * The following field names are reserved and will be filtered out if present - after normalization: `id`, `score`, `highlight`, and any field with the prefix of: - `_`, `+`, or `-` - * Fields with empty name values after normalization are filtered out before - indexing. - * Fields containing the following characters after normalization are filtered - out before indexing: `#` and `,` - **Note:** Documents can be added with a specific **document_id** by using the - **/v1/environments/{environment_id}/collections/{collection_id}/documents** - method. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) The content of the document to ingest. The - maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a configuration is - 1 megabyte. Files larger than the supported size are rejected. - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_document', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - form_data = [] - if file: - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if metadata: - form_data.append(('metadata', (None, metadata, 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - ) - - response = self.send(request, **kwargs) - return response - - def get_document_status( - self, - environment_id: str, - collection_id: str, - document_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get document details. - - Fetch status details about a submitted document. **Note:** this operation does not - return the document itself. Instead, it returns only the document's processing - status and any notices (warnings or errors) that were generated when the document - was ingested. Use the query API to retrieve the actual document content. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str document_id: The ID of the document. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not document_id: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_document_status', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'document_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_document( - self, - environment_id: str, - collection_id: str, - document_id: str, - *, - file: Optional[BinaryIO] = None, - filename: Optional[str] = None, - file_content_type: Optional[str] = None, - metadata: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Update a document. - - Replace an existing document or add a document with a specified **document_id**. - Starts ingesting a document with optional metadata. - **Note:** When uploading a new document with this method it automatically replaces - any document stored with the same **document_id** if it exists. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str document_id: The ID of the document. - :param BinaryIO file: (optional) The content of the document to ingest. The - maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a configuration is - 1 megabyte. Files larger than the supported size are rejected. - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str metadata: (optional) The maximum supported metadata file size is - 1 MB. Metadata parts larger than 1 MB are rejected. Example: ``` { - "Creator": "Johnny Appleseed", - "Subject": "Apples" - } ```. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentAccepted` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not document_id: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_document', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - form_data = [] - if file: - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if metadata: - form_data.append(('metadata', (None, metadata, 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'document_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_document( - self, - environment_id: str, - collection_id: str, - document_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete a document. - - If the given document ID is invalid, or if the document is not found, then the a - success response is returned (HTTP status code `200`) with the status set to - 'deleted'. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str document_id: The ID of the document. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteDocumentResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not document_id: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_document', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'document_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/documents/{document_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Queries - ######################### - - def query( - self, - environment_id: str, - collection_id: str, - *, - filter: Optional[str] = None, - query: Optional[str] = None, - natural_language_query: Optional[str] = None, - passages: Optional[bool] = None, - aggregation: Optional[str] = None, - count: Optional[int] = None, - return_: Optional[str] = None, - offset: Optional[int] = None, - sort: Optional[str] = None, - highlight: Optional[bool] = None, - passages_fields: Optional[str] = None, - passages_count: Optional[int] = None, - passages_characters: Optional[int] = None, - deduplicate: Optional[bool] = None, - deduplicate_field: Optional[str] = None, - similar: Optional[bool] = None, - similar_document_ids: Optional[str] = None, - similar_fields: Optional[str] = None, - bias: Optional[str] = None, - spelling_suggestions: Optional[bool] = None, - x_watson_logging_opt_out: Optional[bool] = None, - **kwargs, - ) -> DetailedResponse: - """ - Query a collection. - - By using this method, you can construct long queries. For details, see the - [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts). - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. Use a query search when you want to find the most - relevant search results. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param bool passages: (optional) A passages query that returns the most - relevant passages from the results. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. - :param str return_: (optional) A comma-separated list of the portion of the - document hierarchy to return. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. - :param str sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. This parameter - cannot be used in the same query as the **bias** parameter. - :param bool highlight: (optional) When true, a highlight field is returned - for each result which contains the fields which match the query with - `` tags around the matching query terms. - :param str passages_fields: (optional) A comma-separated list of fields - that passages are drawn from. If this parameter not specified, then all - top-level fields are included. - :param int passages_count: (optional) The maximum number of passages to - return. The search returns fewer passages if the requested total is not - found. The default is `10`. The maximum is `100`. - :param int passages_characters: (optional) The approximate number of - characters that any one passage will have. - :param bool deduplicate: (optional) When `true`, and used with a Watson - Discovery News collection, duplicate results (based on the contents of the - **title** field) are removed. Duplicate comparison is limited to the - current query only; **offset** is not considered. This parameter is - currently Beta functionality. - :param str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :param bool similar: (optional) When `true`, results are returned based on - their similarity to the document IDs specified in the - **similar.document_ids** parameter. - :param str similar_document_ids: (optional) A comma-separated list of - document IDs to find similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the - scope of the document similarity search with the natural language query. - Other query parameters, such as **filter** and **query**, are subsequently - applied and reduce the scope. - :param str similar_fields: (optional) A comma-separated list of field names - that are used as a basis for comparison to identify similar documents. If - not specified, the entire document is used for comparison. - :param str bias: (optional) Field which the returned results will be biased - against. The specified field must be either a **date** or **number** - format. When a **date** type field is specified returned results are biased - towards field values closer to the current date. When a **number** type - field is specified, returned results are biased towards higher field - values. This parameter cannot be used in the same query as the **sort** - parameter. - :param bool spelling_suggestions: (optional) When `true` and the - **natural_language_query** parameter is used, the **natural_languge_query** - parameter is spell checked. The most likely correction is returned in the - **suggested_query** field of the response (if one exists). - **Important:** this parameter is only valid when using the Cloud Pak - version of Discovery. - :param bool x_watson_logging_opt_out: (optional) If `true`, queries are not - stored in the Discovery **Logs** endpoint. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = { - 'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out, - } - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'passages': passages, - 'aggregation': aggregation, - 'count': count, - 'return': return_, - 'offset': offset, - 'sort': sort, - 'highlight': highlight, - 'passages.fields': passages_fields, - 'passages.count': passages_count, - 'passages.characters': passages_characters, - 'deduplicate': deduplicate, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': similar_document_ids, - 'similar.fields': similar_fields, - 'bias': bias, - 'spelling_suggestions': spelling_suggestions, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/query'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def query_notices( - self, - environment_id: str, - collection_id: str, - *, - filter: Optional[str] = None, - query: Optional[str] = None, - natural_language_query: Optional[str] = None, - passages: Optional[bool] = None, - aggregation: Optional[str] = None, - count: Optional[int] = None, - return_: Optional[List[str]] = None, - offset: Optional[int] = None, - sort: Optional[List[str]] = None, - highlight: Optional[bool] = None, - passages_fields: Optional[List[str]] = None, - passages_count: Optional[int] = None, - passages_characters: Optional[int] = None, - deduplicate_field: Optional[str] = None, - similar: Optional[bool] = None, - similar_document_ids: Optional[List[str]] = None, - similar_fields: Optional[List[str]] = None, - **kwargs, - ) -> DetailedResponse: - """ - Query system notices. - - Queries for notices (errors or warnings) that might have been generated by the - system. Notices are generated when ingesting documents and performing relevance - training. See the [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts) - for more details on the query language. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param bool passages: (optional) A passages query that returns the most - relevant passages from the results. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param List[str] return_: (optional) A comma-separated list of the portion - of the document hierarchy to return. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param List[str] sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. - :param bool highlight: (optional) When true, a highlight field is returned - for each result which contains the fields which match the query with - `` tags around the matching query terms. - :param List[str] passages_fields: (optional) A comma-separated list of - fields that passages are drawn from. If this parameter not specified, then - all top-level fields are included. - :param int passages_count: (optional) The maximum number of passages to - return. The search returns fewer passages if the requested total is not - found. - :param int passages_characters: (optional) The approximate number of - characters that any one passage will have. - :param str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :param bool similar: (optional) When `true`, results are returned based on - their similarity to the document IDs specified in the - **similar.document_ids** parameter. - :param List[str] similar_document_ids: (optional) A comma-separated list of - document IDs to find similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the - scope of the document similarity search with the natural language query. - Other query parameters, such as **filter** and **query**, are subsequently - applied and reduce the scope. - :param List[str] similar_fields: (optional) A comma-separated list of field - names that are used as a basis for comparison to identify similar - documents. If not specified, the entire document is used for comparison. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query_notices', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'passages': passages, - 'aggregation': aggregation, - 'count': count, - 'return': convert_list(return_), - 'offset': offset, - 'sort': convert_list(sort), - 'highlight': highlight, - 'passages.fields': convert_list(passages_fields), - 'passages.count': passages_count, - 'passages.characters': passages_characters, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': convert_list(similar_document_ids), - 'similar.fields': convert_list(similar_fields), - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/notices'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def federated_query( - self, - environment_id: str, - collection_ids: str, - *, - filter: Optional[str] = None, - query: Optional[str] = None, - natural_language_query: Optional[str] = None, - passages: Optional[bool] = None, - aggregation: Optional[str] = None, - count: Optional[int] = None, - return_: Optional[str] = None, - offset: Optional[int] = None, - sort: Optional[str] = None, - highlight: Optional[bool] = None, - passages_fields: Optional[str] = None, - passages_count: Optional[int] = None, - passages_characters: Optional[int] = None, - deduplicate: Optional[bool] = None, - deduplicate_field: Optional[str] = None, - similar: Optional[bool] = None, - similar_document_ids: Optional[str] = None, - similar_fields: Optional[str] = None, - bias: Optional[str] = None, - x_watson_logging_opt_out: Optional[bool] = None, - **kwargs, - ) -> DetailedResponse: - """ - Query multiple collections. - - By using this method, you can construct long queries that search multiple - collection. For details, see the [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts). - - :param str environment_id: The ID of the environment. - :param str collection_ids: A comma-separated list of collection IDs to be - queried against. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. Use a query search when you want to find the most - relevant search results. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param bool passages: (optional) A passages query that returns the most - relevant passages from the results. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. - :param str return_: (optional) A comma-separated list of the portion of the - document hierarchy to return. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. - :param str sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. This parameter - cannot be used in the same query as the **bias** parameter. - :param bool highlight: (optional) When true, a highlight field is returned - for each result which contains the fields which match the query with - `` tags around the matching query terms. - :param str passages_fields: (optional) A comma-separated list of fields - that passages are drawn from. If this parameter not specified, then all - top-level fields are included. - :param int passages_count: (optional) The maximum number of passages to - return. The search returns fewer passages if the requested total is not - found. The default is `10`. The maximum is `100`. - :param int passages_characters: (optional) The approximate number of - characters that any one passage will have. - :param bool deduplicate: (optional) When `true`, and used with a Watson - Discovery News collection, duplicate results (based on the contents of the - **title** field) are removed. Duplicate comparison is limited to the - current query only; **offset** is not considered. This parameter is - currently Beta functionality. - :param str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :param bool similar: (optional) When `true`, results are returned based on - their similarity to the document IDs specified in the - **similar.document_ids** parameter. - :param str similar_document_ids: (optional) A comma-separated list of - document IDs to find similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the - scope of the document similarity search with the natural language query. - Other query parameters, such as **filter** and **query**, are subsequently - applied and reduce the scope. - :param str similar_fields: (optional) A comma-separated list of field names - that are used as a basis for comparison to identify similar documents. If - not specified, the entire document is used for comparison. - :param str bias: (optional) Field which the returned results will be biased - against. The specified field must be either a **date** or **number** - format. When a **date** type field is specified returned results are biased - towards field values closer to the current date. When a **number** type - field is specified, returned results are biased towards higher field - values. This parameter cannot be used in the same query as the **sort** - parameter. - :param bool x_watson_logging_opt_out: (optional) If `true`, queries are not - stored in the Discovery **Logs** endpoint. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if collection_ids is None: - raise ValueError('collection_ids must be provided') - headers = { - 'X-Watson-Logging-Opt-Out': x_watson_logging_opt_out, - } - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='federated_query', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'collection_ids': collection_ids, - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'passages': passages, - 'aggregation': aggregation, - 'count': count, - 'return': return_, - 'offset': offset, - 'sort': sort, - 'highlight': highlight, - 'passages.fields': passages_fields, - 'passages.count': passages_count, - 'passages.characters': passages_characters, - 'deduplicate': deduplicate, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': similar_document_ids, - 'similar.fields': similar_fields, - 'bias': bias, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/query'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def federated_query_notices( - self, - environment_id: str, - collection_ids: List[str], - *, - filter: Optional[str] = None, - query: Optional[str] = None, - natural_language_query: Optional[str] = None, - aggregation: Optional[str] = None, - count: Optional[int] = None, - return_: Optional[List[str]] = None, - offset: Optional[int] = None, - sort: Optional[List[str]] = None, - highlight: Optional[bool] = None, - deduplicate_field: Optional[str] = None, - similar: Optional[bool] = None, - similar_document_ids: Optional[List[str]] = None, - similar_fields: Optional[List[str]] = None, - **kwargs, - ) -> DetailedResponse: - """ - Query multiple collection system notices. - - Queries for notices (errors or warnings) that might have been generated by the - system. Notices are generated when ingesting documents and performing relevance - training. See the [Discovery - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-query-concepts#query-concepts) - for more details on the query language. - - :param str environment_id: The ID of the environment. - :param List[str] collection_ids: A comma-separated list of collection IDs - to be queried against. - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param str natural_language_query: (optional) A natural language query that - returns relevant documents by utilizing training data and natural language - understanding. - :param str aggregation: (optional) An aggregation search that returns an - exact answer by combining query search with filters. Useful for - applications to build lists, tables, and time series. For a full list of - possible aggregations, see the Query reference. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param List[str] return_: (optional) A comma-separated list of the portion - of the document hierarchy to return. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param List[str] sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. - :param bool highlight: (optional) When true, a highlight field is returned - for each result which contains the fields which match the query with - `` tags around the matching query terms. - :param str deduplicate_field: (optional) When specified, duplicate results - based on the field specified are removed from the returned results. - Duplicate comparison is limited to the current query only, **offset** is - not considered. This parameter is currently Beta functionality. - :param bool similar: (optional) When `true`, results are returned based on - their similarity to the document IDs specified in the - **similar.document_ids** parameter. - :param List[str] similar_document_ids: (optional) A comma-separated list of - document IDs to find similar documents. - **Tip:** Include the **natural_language_query** parameter to expand the - scope of the document similarity search with the natural language query. - Other query parameters, such as **filter** and **query**, are subsequently - applied and reduce the scope. - :param List[str] similar_fields: (optional) A comma-separated list of field - names that are used as a basis for comparison to identify similar - documents. If not specified, the entire document is used for comparison. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `QueryNoticesResponse` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if collection_ids is None: - raise ValueError('collection_ids must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='federated_query_notices', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'collection_ids': convert_list(collection_ids), - 'filter': filter, - 'query': query, - 'natural_language_query': natural_language_query, - 'aggregation': aggregation, - 'count': count, - 'return': convert_list(return_), - 'offset': offset, - 'sort': convert_list(sort), - 'highlight': highlight, - 'deduplicate.field': deduplicate_field, - 'similar': similar, - 'similar.document_ids': convert_list(similar_document_ids), - 'similar.fields': convert_list(similar_fields), - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/notices'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_autocompletion( - self, - environment_id: str, - collection_id: str, - prefix: str, - *, - field: Optional[str] = None, - count: Optional[int] = None, - **kwargs, - ) -> DetailedResponse: - """ - Get Autocomplete Suggestions. - - Returns completion query suggestions for the specified prefix. /n/n - **Important:** this method is only valid when using the Cloud Pak version of - Discovery. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str prefix: The prefix to use for autocompletion. For example, the - prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. - :param str field: (optional) The field in the result documents that - autocompletion suggestions are identified from. - :param int count: (optional) The number of autocompletion suggestions to - return. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Completions` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not prefix: - raise ValueError('prefix must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_autocompletion', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'prefix': prefix, - 'field': field, - 'count': count, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/autocompletion'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Training data - ######################### - - def list_training_data( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List training data. - - Lists the training data for the specified collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID 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 with `dict` result representing a `TrainingDataSet` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_training_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def add_training_data( - self, - environment_id: str, - collection_id: str, - *, - natural_language_query: Optional[str] = None, - filter: Optional[str] = None, - examples: Optional[List['TrainingExample']] = None, - **kwargs, - ) -> DetailedResponse: - """ - Add query to training data. - - Adds a query to the training data for this collection. The query can contain a - filter and natural language query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str natural_language_query: (optional) The natural text query for - the new training query. - :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. - :param List[TrainingExample] examples: (optional) Array of training - examples. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if examples is not None: - examples = [convert_model(x) for x in examples] - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_training_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'natural_language_query': natural_language_query, - 'filter': filter, - 'examples': examples, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_all_training_data( - self, - environment_id: str, - collection_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete all training data. - - Deletes all training data from a collection. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID 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 not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_all_training_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['environment_id', 'collection_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_training_data( - self, - environment_id: str, - collection_id: str, - query_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get details about a query. - - Gets details for a specific training data query, including the query string and - all examples. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingQuery` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_training_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def delete_training_data( - self, - environment_id: str, - collection_id: str, - query_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete a training data query. - - Removes the training data query and all associated examples from the training data - set. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_training_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def list_training_examples( - self, - environment_id: str, - collection_id: str, - query_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List examples for a training data query. - - List all examples for this training data query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExampleList` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_training_examples', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_training_example( - self, - environment_id: str, - collection_id: str, - query_id: str, - *, - document_id: Optional[str] = None, - cross_reference: Optional[str] = None, - relevance: Optional[int] = None, - **kwargs, - ) -> DetailedResponse: - """ - Add example to training data query. - - Adds a example to this training data query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str document_id: (optional) The document ID associated with this - training example. - :param str cross_reference: (optional) The cross reference associated with - this training example. - :param int relevance: (optional) The relevance of the training example. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_training_example', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'document_id': document_id, - 'cross_reference': cross_reference, - 'relevance': relevance, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'collection_id', 'query_id'] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_training_example( - self, - environment_id: str, - collection_id: str, - query_id: str, - example_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete example for training data query. - - Deletes the example document with the given ID from the training data query. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str example_id: The ID of the document as it is indexed. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - if not example_id: - raise ValueError('example_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_training_example', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = [ - 'environment_id', 'collection_id', 'query_id', 'example_id' - ] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id, example_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_training_example( - self, - environment_id: str, - collection_id: str, - query_id: str, - example_id: str, - *, - cross_reference: Optional[str] = None, - relevance: Optional[int] = None, - **kwargs, - ) -> DetailedResponse: - """ - Change label or cross reference for example. - - Changes the label or cross reference query for this training data example. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str example_id: The ID of the document as it is indexed. - :param str cross_reference: (optional) The example to add. - :param int relevance: (optional) The relevance value for this example. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - if not example_id: - raise ValueError('example_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_training_example', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'cross_reference': cross_reference, - 'relevance': relevance, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = [ - 'environment_id', 'collection_id', 'query_id', 'example_id' - ] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id, example_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def get_training_example( - self, - environment_id: str, - collection_id: str, - query_id: str, - example_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get details for training data example. - - Gets the details for this training example. - - :param str environment_id: The ID of the environment. - :param str collection_id: The ID of the collection. - :param str query_id: The ID of the query used for training. - :param str example_id: The ID of the document as it is indexed. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingExample` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not collection_id: - raise ValueError('collection_id must be provided') - if not query_id: - raise ValueError('query_id must be provided') - if not example_id: - raise ValueError('example_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_training_example', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = [ - 'environment_id', 'collection_id', 'query_id', 'example_id' - ] - path_param_values = self.encode_path_vars(environment_id, collection_id, - query_id, example_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/collections/{collection_id}/training_data/{query_id}/examples/{example_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # User data - ######################### - - def delete_user_data( - self, - customer_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete labeled data. - - Deletes all data associated with a specified customer ID. The method has no effect - if no data is associated with the customer ID. - 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/discovery?topic=discovery-information-security#information-security). - - :param str customer_id: The customer ID for which all data is to be - deleted. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not customer_id: - raise ValueError('customer_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_user_data', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'customer_id': customer_id, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - url = '/v1/user_data' - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Events and feedback - ######################### - - def create_event( - self, - type: str, - data: 'EventData', - **kwargs, - ) -> DetailedResponse: - """ - Create event. - - The **Events** API can be used to create log entries that are associated with - specific queries. For example, you can record which documents in the results set - were "clicked" by a user and when that click occurred. - - :param str type: The event type to be created. - :param EventData data: Query event data object. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CreateEventResponse` object - """ - - if type is None: - raise ValueError('type must be provided') - if data is None: - raise ValueError('data must be provided') - data = convert_model(data) - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_event', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'type': type, - 'data': data, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/events' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def query_log( - self, - *, - filter: Optional[str] = None, - query: Optional[str] = None, - count: Optional[int] = None, - offset: Optional[int] = None, - sort: Optional[List[str]] = None, - **kwargs, - ) -> DetailedResponse: - """ - Search the query and event log. - - Searches the query and event log to find query sessions that match the specified - criteria. Searching the **logs** endpoint uses the standard Discovery query syntax - for the parameters that are supported. - - :param str filter: (optional) A cacheable query that excludes documents - that don't mention the query content. Filter searches are better for - metadata-type searches and for assessing the concepts in the data set. - :param str query: (optional) A query search returns all documents in your - data set with full enrichments and full text, but with the most relevant - documents listed first. - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param List[str] sort: (optional) A comma-separated list of fields in the - document to sort on. You can optionally specify a sort direction by - prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `LogQueryResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='query_log', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'filter': filter, - 'query': query, - 'count': count, - 'offset': offset, - 'sort': convert_list(sort), - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/logs' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query( - self, - *, - start_time: Optional[datetime] = None, - end_time: Optional[datetime] = None, - result_type: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Number of queries over time. - - Total number of queries using the **natural_language_query** parameter over a - specific time window. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/metrics/number_of_queries' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query_event( - self, - *, - start_time: Optional[datetime] = None, - end_time: Optional[datetime] = None, - result_type: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Number of queries with an event over time. - - Total number of queries using the **natural_language_query** parameter that have a - corresponding "click" event over a specified time window. This metric requires - having integrated event tracking in your application using the **Events** API. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query_event', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/metrics/number_of_queries_with_event' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query_no_results( - self, - *, - start_time: Optional[datetime] = None, - end_time: Optional[datetime] = None, - result_type: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Number of queries with no search results over time. - - Total number of queries using the **natural_language_query** parameter that have - no results returned over a specified time window. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query_no_results', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/metrics/number_of_queries_with_no_search_results' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_metrics_event_rate( - self, - *, - start_time: Optional[datetime] = None, - end_time: Optional[datetime] = None, - result_type: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Percentage of queries with an associated event. - - The percentage of queries using the **natural_language_query** parameter that have - a corresponding "click" event over a specified time window. This metric requires - having integrated event tracking in your application using the **Events** API. - - :param datetime start_time: (optional) Metric is computed from data - recorded after this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime end_time: (optional) Metric is computed from data recorded - before this timestamp; must be in `YYYY-MM-DDThh:mm:ssZ` format. - :param str result_type: (optional) The type of result to consider when - calculating the metric. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_event_rate', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time, - 'result_type': result_type, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/metrics/event_rate' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_metrics_query_token_event( - self, - *, - count: Optional[int] = None, - **kwargs, - ) -> DetailedResponse: - """ - Most frequent query tokens with an event. - - The most frequent query tokens parsed from the **natural_language_query** - parameter and their corresponding "click" event rate within the recording period - (queries and events are stored for 30 days). A query token is an individual word - or unigram within the query string. - - :param int count: (optional) Number of results to return. The maximum for - the **count** and **offset** values together in any one query is **10000**. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `MetricTokenResponse` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_metrics_query_token_event', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'count': count, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v1/metrics/top_query_tokens_with_event_rate' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Credentials - ######################### - - def list_credentials( - self, - environment_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List credentials. - - List all the source credentials that have been created for this service instance. - **Note:** All credentials are sent over an encrypted connection and encrypted at - rest. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CredentialsList` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_credentials', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_credentials( - self, - environment_id: str, - *, - source_type: Optional[str] = None, - credential_details: Optional['CredentialDetails'] = None, - status: Optional['StatusDetails'] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create credentials. - - Creates a set of credentials to connect to a remote source. Created credentials - are used in a configuration to associate a collection with the remote source. - **Note:** All credentials are sent over an encrypted connection and encrypted at - rest. - - :param str environment_id: The ID of the environment. - :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of - Enterprise Box. - - `salesforce` indicates the credentials are used to connect to - Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to - an IBM Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing - details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param StatusDetails status: (optional) Object that contains details about - the status of the authentication process. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Credentials` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if credential_details is not None: - credential_details = convert_model(credential_details) - if status is not None: - status = convert_model(status) - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_credentials', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'source_type': source_type, - 'credential_details': credential_details, - 'status': status, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def get_credentials( - self, - environment_id: str, - credential_id: str, - **kwargs, - ) -> DetailedResponse: - """ - View Credentials. - - Returns details about the specified credentials. - **Note:** Secure credential information such as a password or SSH key is never - returned and must be obtained from the source system. - - :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source - credentials. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Credentials` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not credential_id: - raise ValueError('credential_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_credentials', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'credential_id'] - path_param_values = self.encode_path_vars(environment_id, credential_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def update_credentials( - self, - environment_id: str, - credential_id: str, - *, - source_type: Optional[str] = None, - credential_details: Optional['CredentialDetails'] = None, - status: Optional['StatusDetails'] = None, - **kwargs, - ) -> DetailedResponse: - """ - Update credentials. - - Updates an existing set of source credentials. - **Note:** All credentials are sent over an encrypted connection and encrypted at - rest. - - :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source - credentials. - :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of - Enterprise Box. - - `salesforce` indicates the credentials are used to connect to - Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to - an IBM Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing - details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param StatusDetails status: (optional) Object that contains details about - the status of the authentication process. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Credentials` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not credential_id: - raise ValueError('credential_id must be provided') - if credential_details is not None: - credential_details = convert_model(credential_details) - if status is not None: - status = convert_model(status) - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_credentials', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'source_type': source_type, - 'credential_details': credential_details, - 'status': status, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'credential_id'] - path_param_values = self.encode_path_vars(environment_id, credential_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='PUT', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_credentials( - self, - environment_id: str, - credential_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete credentials. - - Deletes a set of stored credentials from your Discovery instance. - - :param str environment_id: The ID of the environment. - :param str credential_id: The unique identifier for a set of source - credentials. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteCredentials` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not credential_id: - raise ValueError('credential_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_credentials', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'credential_id'] - path_param_values = self.encode_path_vars(environment_id, credential_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/credentials/{credential_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # gatewayConfiguration - ######################### - - def list_gateways( - self, - environment_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List Gateways. - - List the currently configured gateways. - - :param str environment_id: The ID of the environment. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `GatewayList` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_gateways', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_gateway( - self, - environment_id: str, - *, - name: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create Gateway. - - Create a gateway configuration to use with a remotely installed gateway. - - :param str environment_id: The ID of the environment. - :param str name: (optional) User-defined name. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Gateway` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_gateway', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'name': name, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id'] - path_param_values = self.encode_path_vars(environment_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways'.format( - **path_param_dict) - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - def get_gateway( - self, - environment_id: str, - gateway_id: str, - **kwargs, - ) -> DetailedResponse: - """ - List Gateway Details. - - List information about the specified gateway. - - :param str environment_id: The ID of the environment. - :param str gateway_id: The requested gateway ID. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Gateway` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not gateway_id: - raise ValueError('gateway_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_gateway', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'gateway_id'] - path_param_values = self.encode_path_vars(environment_id, gateway_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def delete_gateway( - self, - environment_id: str, - gateway_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete Gateway. - - Delete the specified gateway configuration. - - :param str environment_id: The ID of the environment. - :param str gateway_id: The requested gateway ID. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `GatewayDelete` object - """ - - if not environment_id: - raise ValueError('environment_id must be provided') - if not gateway_id: - raise ValueError('gateway_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_gateway', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['environment_id', 'gateway_id'] - path_param_values = self.encode_path_vars(environment_id, gateway_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/environments/{environment_id}/gateways/{gateway_id}'.format( - **path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - -class AddDocumentEnums: - """ - Enums for add_document parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' - - -class UpdateDocumentEnums: - """ - Enums for update_document parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_PDF = 'application/pdf' - TEXT_HTML = 'text/html' - APPLICATION_XHTML_XML = 'application/xhtml+xml' - - -class GetMetricsQueryEnums: - """ - Enums for get_metrics_query parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - - DOCUMENT = 'document' - - -class GetMetricsQueryEventEnums: - """ - Enums for get_metrics_query_event parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - - DOCUMENT = 'document' - - -class GetMetricsQueryNoResultsEnums: - """ - Enums for get_metrics_query_no_results parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - - DOCUMENT = 'document' - - -class GetMetricsEventRateEnums: - """ - Enums for get_metrics_event_rate parameters. - """ - - class ResultType(str, Enum): - """ - The type of result to consider when calculating the metric. - """ - - DOCUMENT = 'document' - - -############################################################################## -# Models -############################################################################## - - -class Collection: - """ - A collection for storing documents. - - :param str collection_id: (optional) The unique identifier of the collection. - :param str name: (optional) The name of the collection. - :param str description: (optional) The description of the collection. - :param datetime created: (optional) The creation date of the collection in the - format yyyy-MM-dd'T'HH:mmcon:ss.SSS'Z'. - :param datetime updated: (optional) The timestamp of when the collection was - last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param str status: (optional) The status of the collection. - :param str configuration_id: (optional) The unique identifier of the - collection's configuration. - :param str language: (optional) The language of the documents stored in the - collection. Permitted values include `en` (English), `de` (German), and `es` - (Spanish). - :param DocumentCounts document_counts: (optional) Object containing collection - document count information. - :param CollectionDiskUsage disk_usage: (optional) Summary of the disk usage - statistics for this collection. - :param TrainingStatus training_status: (optional) Training status details. - :param CollectionCrawlStatus crawl_status: (optional) Object containing - information about the crawl status of this collection. - :param SduStatus smart_document_understanding: (optional) Object containing - smart document understanding information for this collection. - """ - - def __init__( - self, - *, - collection_id: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - created: Optional[datetime] = None, - updated: Optional[datetime] = None, - status: Optional[str] = None, - configuration_id: Optional[str] = None, - language: Optional[str] = None, - document_counts: Optional['DocumentCounts'] = None, - disk_usage: Optional['CollectionDiskUsage'] = None, - training_status: Optional['TrainingStatus'] = None, - crawl_status: Optional['CollectionCrawlStatus'] = None, - smart_document_understanding: Optional['SduStatus'] = None, - ) -> None: - """ - Initialize a Collection object. - - :param str name: (optional) The name of the collection. - :param str description: (optional) The description of the collection. - :param str configuration_id: (optional) The unique identifier of the - collection's configuration. - :param str language: (optional) The language of the documents stored in the - collection. Permitted values include `en` (English), `de` (German), and - `es` (Spanish). - :param DocumentCounts document_counts: (optional) Object containing - collection document count information. - :param CollectionDiskUsage disk_usage: (optional) Summary of the disk usage - statistics for this collection. - :param TrainingStatus training_status: (optional) Training status details. - :param CollectionCrawlStatus crawl_status: (optional) Object containing - information about the crawl status of this collection. - :param SduStatus smart_document_understanding: (optional) Object containing - smart document understanding information for this collection. - """ - self.collection_id = collection_id - self.name = name - self.description = description - self.created = created - self.updated = updated - self.status = status - self.configuration_id = configuration_id - self.language = language - self.document_counts = document_counts - self.disk_usage = disk_usage - self.training_status = training_status - self.crawl_status = crawl_status - self.smart_document_understanding = smart_document_understanding - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Collection': - """Initialize a Collection object from a json dictionary.""" - args = {} - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - if (updated := _dict.get('updated')) is not None: - args['updated'] = string_to_datetime(updated) - if (status := _dict.get('status')) is not None: - args['status'] = status - if (configuration_id := _dict.get('configuration_id')) is not None: - args['configuration_id'] = configuration_id - if (language := _dict.get('language')) is not None: - args['language'] = language - if (document_counts := _dict.get('document_counts')) is not None: - args['document_counts'] = DocumentCounts.from_dict(document_counts) - if (disk_usage := _dict.get('disk_usage')) is not None: - args['disk_usage'] = CollectionDiskUsage.from_dict(disk_usage) - if (training_status := _dict.get('training_status')) is not None: - args['training_status'] = TrainingStatus.from_dict(training_status) - if (crawl_status := _dict.get('crawl_status')) is not None: - args['crawl_status'] = CollectionCrawlStatus.from_dict(crawl_status) - if (smart_document_understanding := - _dict.get('smart_document_understanding')) is not None: - args['smart_document_understanding'] = SduStatus.from_dict( - smart_document_understanding) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Collection 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, 'collection_id') and getattr( - self, 'collection_id') is not None: - _dict['collection_id'] = getattr(self, 'collection_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, - 'configuration_id') and self.configuration_id is not None: - _dict['configuration_id'] = self.configuration_id - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, - 'document_counts') and self.document_counts is not None: - if isinstance(self.document_counts, dict): - _dict['document_counts'] = self.document_counts - else: - _dict['document_counts'] = self.document_counts.to_dict() - if hasattr(self, 'disk_usage') and self.disk_usage is not None: - if isinstance(self.disk_usage, dict): - _dict['disk_usage'] = self.disk_usage - else: - _dict['disk_usage'] = self.disk_usage.to_dict() - if hasattr(self, - 'training_status') and self.training_status is not None: - if isinstance(self.training_status, dict): - _dict['training_status'] = self.training_status - else: - _dict['training_status'] = self.training_status.to_dict() - if hasattr(self, 'crawl_status') and self.crawl_status is not None: - if isinstance(self.crawl_status, dict): - _dict['crawl_status'] = self.crawl_status - else: - _dict['crawl_status'] = self.crawl_status.to_dict() - if hasattr(self, 'smart_document_understanding' - ) and self.smart_document_understanding is not None: - if isinstance(self.smart_document_understanding, dict): - _dict[ - 'smart_document_understanding'] = self.smart_document_understanding - else: - _dict[ - 'smart_document_understanding'] = self.smart_document_understanding.to_dict( - ) - 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 Collection object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Collection') -> 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: 'Collection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the collection. - """ - - ACTIVE = 'active' - PENDING = 'pending' - MAINTENANCE = 'maintenance' - - -class CollectionCrawlStatus: - """ - Object containing information about the crawl status of this collection. - - :param SourceStatus source_crawl: (optional) Object containing source crawl - status information. - """ - - def __init__( - self, - *, - source_crawl: Optional['SourceStatus'] = None, - ) -> None: - """ - Initialize a CollectionCrawlStatus object. - - :param SourceStatus source_crawl: (optional) Object containing source crawl - status information. - """ - self.source_crawl = source_crawl - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionCrawlStatus': - """Initialize a CollectionCrawlStatus object from a json dictionary.""" - args = {} - if (source_crawl := _dict.get('source_crawl')) is not None: - args['source_crawl'] = SourceStatus.from_dict(source_crawl) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CollectionCrawlStatus 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, 'source_crawl') and self.source_crawl is not None: - if isinstance(self.source_crawl, dict): - _dict['source_crawl'] = self.source_crawl - else: - _dict['source_crawl'] = self.source_crawl.to_dict() - 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 CollectionCrawlStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CollectionCrawlStatus') -> 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: 'CollectionCrawlStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CollectionDiskUsage: - """ - Summary of the disk usage statistics for this collection. - - :param int used_bytes: (optional) Number of bytes used by the collection. - """ - - def __init__( - self, - *, - used_bytes: Optional[int] = None, - ) -> None: - """ - Initialize a CollectionDiskUsage object. - - """ - self.used_bytes = used_bytes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionDiskUsage': - """Initialize a CollectionDiskUsage object from a json dictionary.""" - args = {} - if (used_bytes := _dict.get('used_bytes')) is not None: - args['used_bytes'] = used_bytes - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CollectionDiskUsage 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, 'used_bytes') and getattr(self, - 'used_bytes') is not None: - _dict['used_bytes'] = getattr(self, 'used_bytes') - 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 CollectionDiskUsage object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CollectionDiskUsage') -> 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: 'CollectionDiskUsage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CollectionUsage: - """ - Summary of the collection usage in the environment. - - :param int available: (optional) Number of active collections in the - environment. - :param int maximum_allowed: (optional) Total number of collections allowed in - the environment. - """ - - def __init__( - self, - *, - available: Optional[int] = None, - maximum_allowed: Optional[int] = None, - ) -> None: - """ - Initialize a CollectionUsage object. - - """ - self.available = available - self.maximum_allowed = maximum_allowed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionUsage': - """Initialize a CollectionUsage object from a json dictionary.""" - args = {} - if (available := _dict.get('available')) is not None: - args['available'] = available - if (maximum_allowed := _dict.get('maximum_allowed')) is not None: - args['maximum_allowed'] = maximum_allowed - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CollectionUsage 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, 'available') and getattr(self, - 'available') is not None: - _dict['available'] = getattr(self, 'available') - if hasattr(self, 'maximum_allowed') and getattr( - self, 'maximum_allowed') is not None: - _dict['maximum_allowed'] = getattr(self, 'maximum_allowed') - 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 CollectionUsage object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CollectionUsage') -> 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: 'CollectionUsage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Completions: - """ - An object containing an array of autocompletion suggestions. - - :param List[str] completions: (optional) Array of autcomplete suggestion based - on the provided prefix. - """ - - def __init__( - self, - *, - completions: Optional[List[str]] = None, - ) -> None: - """ - Initialize a Completions object. - - :param List[str] completions: (optional) Array of autcomplete suggestion - based on the provided prefix. - """ - self.completions = completions - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Completions': - """Initialize a Completions object from a json dictionary.""" - args = {} - if (completions := _dict.get('completions')) is not None: - args['completions'] = completions - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Completions 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, 'completions') and self.completions is not None: - _dict['completions'] = self.completions - 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 Completions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Completions') -> 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: 'Completions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Configuration: - """ - A custom configuration for the environment. - - :param str configuration_id: (optional) The unique identifier of the - configuration. - :param str name: The name of the configuration. - :param datetime created: (optional) The creation date of the configuration in - the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param datetime updated: (optional) The timestamp of when the configuration was - last updated in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param str description: (optional) The description of the configuration, if - available. - :param Conversions conversions: (optional) Document conversion settings. - :param List[Enrichment] enrichments: (optional) An array of document enrichment - settings for the configuration. - :param List[NormalizationOperation] normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a normalized - form. Operations are executed in the order that they appear in the array. - :param Source source: (optional) Object containing source parameters for the - configuration. - """ - - def __init__( - self, - name: str, - *, - configuration_id: Optional[str] = None, - created: Optional[datetime] = None, - updated: Optional[datetime] = None, - description: Optional[str] = None, - conversions: Optional['Conversions'] = None, - enrichments: Optional[List['Enrichment']] = None, - normalizations: Optional[List['NormalizationOperation']] = None, - source: Optional['Source'] = None, - ) -> None: - """ - Initialize a Configuration object. - - :param str name: The name of the configuration. - :param str description: (optional) The description of the configuration, if - available. - :param Conversions conversions: (optional) Document conversion settings. - :param List[Enrichment] enrichments: (optional) An array of document - enrichment settings for the configuration. - :param List[NormalizationOperation] normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a - normalized form. Operations are executed in the order that they appear in - the array. - :param Source source: (optional) Object containing source parameters for - the configuration. - """ - self.configuration_id = configuration_id - self.name = name - self.created = created - self.updated = updated - self.description = description - self.conversions = conversions - self.enrichments = enrichments - self.normalizations = normalizations - self.source = source - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Configuration': - """Initialize a Configuration object from a json dictionary.""" - args = {} - if (configuration_id := _dict.get('configuration_id')) is not None: - args['configuration_id'] = configuration_id - if (name := _dict.get('name')) is not None: - args['name'] = name - else: - raise ValueError( - 'Required property \'name\' not present in Configuration JSON') - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - if (updated := _dict.get('updated')) is not None: - args['updated'] = string_to_datetime(updated) - if (description := _dict.get('description')) is not None: - args['description'] = description - if (conversions := _dict.get('conversions')) is not None: - args['conversions'] = Conversions.from_dict(conversions) - if (enrichments := _dict.get('enrichments')) is not None: - args['enrichments'] = [Enrichment.from_dict(v) for v in enrichments] - if (normalizations := _dict.get('normalizations')) is not None: - args['normalizations'] = [ - NormalizationOperation.from_dict(v) for v in normalizations - ] - if (source := _dict.get('source')) is not None: - args['source'] = Source.from_dict(source) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Configuration 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, 'configuration_id') and getattr( - self, 'configuration_id') is not None: - _dict['configuration_id'] = getattr(self, 'configuration_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'conversions') and self.conversions is not None: - if isinstance(self.conversions, dict): - _dict['conversions'] = self.conversions - else: - _dict['conversions'] = self.conversions.to_dict() - if hasattr(self, 'enrichments') and self.enrichments is not None: - enrichments_list = [] - for v in self.enrichments: - if isinstance(v, dict): - enrichments_list.append(v) - else: - enrichments_list.append(v.to_dict()) - _dict['enrichments'] = enrichments_list - if hasattr(self, 'normalizations') and self.normalizations is not None: - normalizations_list = [] - for v in self.normalizations: - if isinstance(v, dict): - normalizations_list.append(v) - else: - normalizations_list.append(v.to_dict()) - _dict['normalizations'] = normalizations_list - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() - 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 Configuration object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Configuration') -> 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: 'Configuration') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Conversions: - """ - Document conversion settings. - - :param PdfSettings pdf: (optional) A list of PDF conversion settings. - :param WordSettings word: (optional) A list of Word conversion settings. - :param HtmlSettings html: (optional) A list of HTML conversion settings. - :param SegmentSettings segment: (optional) A list of Document Segmentation - settings. - :param List[NormalizationOperation] json_normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a normalized - form. Operations are executed in the order that they appear in the array. - :param bool image_text_recognition: (optional) When `true`, automatic text - extraction from images (this includes images embedded in supported document - formats, for example PDF, and suppported image formats, for example TIFF) is - performed on documents uploaded to the collection. This field is supported on - **Advanced** and higher plans only. **Lite** plans do not support image text - recognition. - """ - - def __init__( - self, - *, - pdf: Optional['PdfSettings'] = None, - word: Optional['WordSettings'] = None, - html: Optional['HtmlSettings'] = None, - segment: Optional['SegmentSettings'] = None, - json_normalizations: Optional[List['NormalizationOperation']] = None, - image_text_recognition: Optional[bool] = None, - ) -> None: - """ - Initialize a Conversions object. - - :param PdfSettings pdf: (optional) A list of PDF conversion settings. - :param WordSettings word: (optional) A list of Word conversion settings. - :param HtmlSettings html: (optional) A list of HTML conversion settings. - :param SegmentSettings segment: (optional) A list of Document Segmentation - settings. - :param List[NormalizationOperation] json_normalizations: (optional) Defines - operations that can be used to transform the final output JSON into a - normalized form. Operations are executed in the order that they appear in - the array. - :param bool image_text_recognition: (optional) When `true`, automatic text - extraction from images (this includes images embedded in supported document - formats, for example PDF, and suppported image formats, for example TIFF) - is performed on documents uploaded to the collection. This field is - supported on **Advanced** and higher plans only. **Lite** plans do not - support image text recognition. - """ - self.pdf = pdf - self.word = word - self.html = html - self.segment = segment - self.json_normalizations = json_normalizations - self.image_text_recognition = image_text_recognition - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Conversions': - """Initialize a Conversions object from a json dictionary.""" - args = {} - if (pdf := _dict.get('pdf')) is not None: - args['pdf'] = PdfSettings.from_dict(pdf) - if (word := _dict.get('word')) is not None: - args['word'] = WordSettings.from_dict(word) - if (html := _dict.get('html')) is not None: - args['html'] = HtmlSettings.from_dict(html) - if (segment := _dict.get('segment')) is not None: - args['segment'] = SegmentSettings.from_dict(segment) - if (json_normalizations := - _dict.get('json_normalizations')) is not None: - args['json_normalizations'] = [ - NormalizationOperation.from_dict(v) for v in json_normalizations - ] - if (image_text_recognition := - _dict.get('image_text_recognition')) is not None: - args['image_text_recognition'] = image_text_recognition - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Conversions 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, 'pdf') and self.pdf is not None: - if isinstance(self.pdf, dict): - _dict['pdf'] = self.pdf - else: - _dict['pdf'] = self.pdf.to_dict() - if hasattr(self, 'word') and self.word is not None: - if isinstance(self.word, dict): - _dict['word'] = self.word - else: - _dict['word'] = self.word.to_dict() - if hasattr(self, 'html') and self.html is not None: - if isinstance(self.html, dict): - _dict['html'] = self.html - else: - _dict['html'] = self.html.to_dict() - if hasattr(self, 'segment') and self.segment is not None: - if isinstance(self.segment, dict): - _dict['segment'] = self.segment - else: - _dict['segment'] = self.segment.to_dict() - if hasattr( - self, - 'json_normalizations') and self.json_normalizations is not None: - json_normalizations_list = [] - for v in self.json_normalizations: - if isinstance(v, dict): - json_normalizations_list.append(v) - else: - json_normalizations_list.append(v.to_dict()) - _dict['json_normalizations'] = json_normalizations_list - if hasattr(self, 'image_text_recognition' - ) and self.image_text_recognition is not None: - _dict['image_text_recognition'] = self.image_text_recognition - 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 Conversions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Conversions') -> 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: 'Conversions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CreateEventResponse: - """ - An object defining the event being created. - - :param str type: (optional) The event type that was created. - :param EventData data: (optional) Query event data object. - """ - - def __init__( - self, - *, - type: Optional[str] = None, - data: Optional['EventData'] = None, - ) -> None: - """ - Initialize a CreateEventResponse object. - - :param str type: (optional) The event type that was created. - :param EventData data: (optional) Query event data object. - """ - self.type = type - self.data = data - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CreateEventResponse': - """Initialize a CreateEventResponse object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (data := _dict.get('data')) is not None: - args['data'] = EventData.from_dict(data) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CreateEventResponse 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 - if hasattr(self, 'data') and self.data is not None: - if isinstance(self.data, dict): - _dict['data'] = self.data - else: - _dict['data'] = self.data.to_dict() - 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 CreateEventResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CreateEventResponse') -> 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: 'CreateEventResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The event type that was created. - """ - - CLICK = 'click' - - -class CredentialDetails: - """ - Object containing details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - - :param str credential_type: (optional) The authentication method for this - credentials definition. The **credential_type** specified must be supported by - the **source_type**. The following combinations are possible: - - `"source_type": "box"` - valid `credential_type`s: `oauth2` - - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with - **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - - "source_type": "cloud_object_storage"` - valid `credential_type`s: - `aws4_hmac`. - :param str client_id: (optional) The **client_id** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. - :param str enterprise_id: (optional) The **enterprise_id** of the Box site that - these credentials connect to. Only valid, and required, with a **source_type** - of `box`. - :param str url: (optional) The **url** of the source that these credentials - connect to. Only valid, and required, with a **credential_type** of - `username_password`, `noauth`, and `basic`. - :param str username: (optional) The **username** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `saml`, `username_password`, `basic`, or `ntlm_v1`. - :param str organization_url: (optional) The **organization_url** of the source - that these credentials connect to. Only valid, and required, with a - **credential_type** of `saml`. - :param str site_collection_path: (optional) The **site_collection.path** of the - source that these credentials connect to. Only valid, and required, with a - **source_type** of `sharepoint`. - :param str client_secret: (optional) The **client_secret** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only used - when creating or modifying **credentials**. - :param str public_key_id: (optional) The **public_key_id** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only used - when creating or modifying **credentials**. - :param str private_key: (optional) The **private_key** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or - modifying **credentials**. - :param str passphrase: (optional) The **passphrase** of the source that these - credentials connect to. Only valid, and required, with a **credential_type** of - `oauth2`. This value is never returned and is only used when creating or - modifying **credentials**. - :param str password: (optional) The **password** of the source that these - credentials connect to. Only valid, and required, with **credential_type**s of - `saml`, `username_password`, `basic`, or `ntlm_v1`. - **Note:** When used with a **source_type** of `salesforce`, the password - consists of the Salesforce password and a valid Salesforce security token - concatenated. This value is never returned and is only used when creating or - modifying **credentials**. - :param str gateway_id: (optional) The ID of the **gateway** to be connected - through (when connecting to intranet sites). Only valid with a - **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are created - using the `/v1/environments/{environment_id}/gateways` methods. - :param str source_version: (optional) The type of Sharepoint repository to - connect to. Only valid, and required, with a **source_type** of `sharepoint`. - :param str web_application_url: (optional) SharePoint OnPrem WebApplication URL. - Only valid, and required, with a **source_version** of `2016`. If a port is not - supplied, the default to port `80` for http and port `443` for https connections - are used. - :param str domain: (optional) The domain used to log in to your OnPrem - SharePoint account. Only valid, and required, with a **source_version** of - `2016`. - :param str endpoint: (optional) The endpoint associated with the cloud object - store that your are connecting to. Only valid, and required, with a - **credential_type** of `aws4_hmac`. - :param str access_key_id: (optional) The access key ID associated with the cloud - object store. Only valid, and required, with a **credential_type** of - `aws4_hmac`. This value is never returned and is only used when creating or - modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - :param str secret_access_key: (optional) The secret access key associated with - the cloud object store. Only valid, and required, with a **credential_type** of - `aws4_hmac`. This value is never returned and is only used when creating or - modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - """ - - def __init__( - self, - *, - credential_type: Optional[str] = None, - client_id: Optional[str] = None, - enterprise_id: Optional[str] = None, - url: Optional[str] = None, - username: Optional[str] = None, - organization_url: Optional[str] = None, - site_collection_path: Optional[str] = None, - client_secret: Optional[str] = None, - public_key_id: Optional[str] = None, - private_key: Optional[str] = None, - passphrase: Optional[str] = None, - password: Optional[str] = None, - gateway_id: Optional[str] = None, - source_version: Optional[str] = None, - web_application_url: Optional[str] = None, - domain: Optional[str] = None, - endpoint: Optional[str] = None, - access_key_id: Optional[str] = None, - secret_access_key: Optional[str] = None, - ) -> None: - """ - Initialize a CredentialDetails object. - - :param str credential_type: (optional) The authentication method for this - credentials definition. The **credential_type** specified must be - supported by the **source_type**. The following combinations are possible: - - `"source_type": "box"` - valid `credential_type`s: `oauth2` - - `"source_type": "salesforce"` - valid `credential_type`s: - `username_password` - - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with - **source_version** of `online`, or `ntlm_v1` with **source_version** of - `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or - `basic` - - "source_type": "cloud_object_storage"` - valid `credential_type`s: - `aws4_hmac`. - :param str client_id: (optional) The **client_id** of the source that these - credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. - :param str enterprise_id: (optional) The **enterprise_id** of the Box site - that these credentials connect to. Only valid, and required, with a - **source_type** of `box`. - :param str url: (optional) The **url** of the source that these credentials - connect to. Only valid, and required, with a **credential_type** of - `username_password`, `noauth`, and `basic`. - :param str username: (optional) The **username** of the source that these - credentials connect to. Only valid, and required, with a - **credential_type** of `saml`, `username_password`, `basic`, or `ntlm_v1`. - :param str organization_url: (optional) The **organization_url** of the - source that these credentials connect to. Only valid, and required, with a - **credential_type** of `saml`. - :param str site_collection_path: (optional) The **site_collection.path** of - the source that these credentials connect to. Only valid, and required, - with a **source_type** of `sharepoint`. - :param str client_secret: (optional) The **client_secret** of the source - that these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str public_key_id: (optional) The **public_key_id** of the source - that these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str private_key: (optional) The **private_key** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str passphrase: (optional) The **passphrase** of the source that - these credentials connect to. Only valid, and required, with a - **credential_type** of `oauth2`. This value is never returned and is only - used when creating or modifying **credentials**. - :param str password: (optional) The **password** of the source that these - credentials connect to. Only valid, and required, with **credential_type**s - of `saml`, `username_password`, `basic`, or `ntlm_v1`. - **Note:** When used with a **source_type** of `salesforce`, the password - consists of the Salesforce password and a valid Salesforce security token - concatenated. This value is never returned and is only used when creating - or modifying **credentials**. - :param str gateway_id: (optional) The ID of the **gateway** to be connected - through (when connecting to intranet sites). Only valid with a - **credential_type** of `noauth`, `basic`, or `ntlm_v1`. Gateways are - created using the `/v1/environments/{environment_id}/gateways` methods. - :param str source_version: (optional) The type of Sharepoint repository to - connect to. Only valid, and required, with a **source_type** of - `sharepoint`. - :param str web_application_url: (optional) SharePoint OnPrem WebApplication - URL. Only valid, and required, with a **source_version** of `2016`. If a - port is not supplied, the default to port `80` for http and port `443` for - https connections are used. - :param str domain: (optional) The domain used to log in to your OnPrem - SharePoint account. Only valid, and required, with a **source_version** of - `2016`. - :param str endpoint: (optional) The endpoint associated with the cloud - object store that your are connecting to. Only valid, and required, with a - **credential_type** of `aws4_hmac`. - :param str access_key_id: (optional) The access key ID associated with the - cloud object store. Only valid, and required, with a **credential_type** of - `aws4_hmac`. This value is never returned and is only used when creating or - modifying **credentials**. For more infomation, see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - :param str secret_access_key: (optional) The secret access key associated - with the cloud object store. Only valid, and required, with a - **credential_type** of `aws4_hmac`. This value is never returned and is - only used when creating or modifying **credentials**. For more infomation, - see the [cloud object store - documentation](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-using-hmac-credentials#using-hmac-credentials). - """ - self.credential_type = credential_type - self.client_id = client_id - self.enterprise_id = enterprise_id - self.url = url - self.username = username - self.organization_url = organization_url - self.site_collection_path = site_collection_path - self.client_secret = client_secret - self.public_key_id = public_key_id - self.private_key = private_key - self.passphrase = passphrase - self.password = password - self.gateway_id = gateway_id - self.source_version = source_version - self.web_application_url = web_application_url - self.domain = domain - self.endpoint = endpoint - self.access_key_id = access_key_id - self.secret_access_key = secret_access_key - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CredentialDetails': - """Initialize a CredentialDetails object from a json dictionary.""" - args = {} - if (credential_type := _dict.get('credential_type')) is not None: - args['credential_type'] = credential_type - if (client_id := _dict.get('client_id')) is not None: - args['client_id'] = client_id - if (enterprise_id := _dict.get('enterprise_id')) is not None: - args['enterprise_id'] = enterprise_id - if (url := _dict.get('url')) is not None: - args['url'] = url - if (username := _dict.get('username')) is not None: - args['username'] = username - if (organization_url := _dict.get('organization_url')) is not None: - args['organization_url'] = organization_url - if (site_collection_path := - _dict.get('site_collection.path')) is not None: - args['site_collection_path'] = site_collection_path - if (client_secret := _dict.get('client_secret')) is not None: - args['client_secret'] = client_secret - if (public_key_id := _dict.get('public_key_id')) is not None: - args['public_key_id'] = public_key_id - if (private_key := _dict.get('private_key')) is not None: - args['private_key'] = private_key - if (passphrase := _dict.get('passphrase')) is not None: - args['passphrase'] = passphrase - if (password := _dict.get('password')) is not None: - args['password'] = password - if (gateway_id := _dict.get('gateway_id')) is not None: - args['gateway_id'] = gateway_id - if (source_version := _dict.get('source_version')) is not None: - args['source_version'] = source_version - if (web_application_url := - _dict.get('web_application_url')) is not None: - args['web_application_url'] = web_application_url - if (domain := _dict.get('domain')) is not None: - args['domain'] = domain - if (endpoint := _dict.get('endpoint')) is not None: - args['endpoint'] = endpoint - if (access_key_id := _dict.get('access_key_id')) is not None: - args['access_key_id'] = access_key_id - if (secret_access_key := _dict.get('secret_access_key')) is not None: - args['secret_access_key'] = secret_access_key - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CredentialDetails 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, - 'credential_type') and self.credential_type is not None: - _dict['credential_type'] = self.credential_type - if hasattr(self, 'client_id') and self.client_id is not None: - _dict['client_id'] = self.client_id - if hasattr(self, 'enterprise_id') and self.enterprise_id is not None: - _dict['enterprise_id'] = self.enterprise_id - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'username') and self.username is not None: - _dict['username'] = self.username - if hasattr(self, - 'organization_url') and self.organization_url is not None: - _dict['organization_url'] = self.organization_url - if hasattr(self, 'site_collection_path' - ) and self.site_collection_path is not None: - _dict['site_collection.path'] = self.site_collection_path - if hasattr(self, 'client_secret') and self.client_secret is not None: - _dict['client_secret'] = self.client_secret - if hasattr(self, 'public_key_id') and self.public_key_id is not None: - _dict['public_key_id'] = self.public_key_id - if hasattr(self, 'private_key') and self.private_key is not None: - _dict['private_key'] = self.private_key - if hasattr(self, 'passphrase') and self.passphrase is not None: - _dict['passphrase'] = self.passphrase - if hasattr(self, 'password') and self.password is not None: - _dict['password'] = self.password - if hasattr(self, 'gateway_id') and self.gateway_id is not None: - _dict['gateway_id'] = self.gateway_id - if hasattr(self, 'source_version') and self.source_version is not None: - _dict['source_version'] = self.source_version - if hasattr( - self, - 'web_application_url') and self.web_application_url is not None: - _dict['web_application_url'] = self.web_application_url - if hasattr(self, 'domain') and self.domain is not None: - _dict['domain'] = self.domain - if hasattr(self, 'endpoint') and self.endpoint is not None: - _dict['endpoint'] = self.endpoint - if hasattr(self, 'access_key_id') and self.access_key_id is not None: - _dict['access_key_id'] = self.access_key_id - if hasattr(self, - 'secret_access_key') and self.secret_access_key is not None: - _dict['secret_access_key'] = self.secret_access_key - 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 CredentialDetails object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CredentialDetails') -> 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: 'CredentialDetails') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class CredentialTypeEnum(str, Enum): - """ - The authentication method for this credentials definition. The - **credential_type** specified must be supported by the **source_type**. The - following combinations are possible: - - `"source_type": "box"` - valid `credential_type`s: `oauth2` - - `"source_type": "salesforce"` - valid `credential_type`s: `username_password` - - `"source_type": "sharepoint"` - valid `credential_type`s: `saml` with - **source_version** of `online`, or `ntlm_v1` with **source_version** of `2016` - - `"source_type": "web_crawl"` - valid `credential_type`s: `noauth` or `basic` - - "source_type": "cloud_object_storage"` - valid `credential_type`s: `aws4_hmac`. - """ - - OAUTH2 = 'oauth2' - SAML = 'saml' - USERNAME_PASSWORD = 'username_password' - NOAUTH = 'noauth' - BASIC = 'basic' - NTLM_V1 = 'ntlm_v1' - AWS4_HMAC = 'aws4_hmac' - - class SourceVersionEnum(str, Enum): - """ - The type of Sharepoint repository to connect to. Only valid, and required, with a - **source_type** of `sharepoint`. - """ - - ONLINE = 'online' - - -class Credentials: - """ - Object containing credential information. - - :param str credential_id: (optional) Unique identifier for this set of - credentials. - :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of Enterprise - Box. - - `salesforce` indicates the credentials are used to connect to Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to an - IBM Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing - details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param StatusDetails status: (optional) Object that contains details about the - status of the authentication process. - """ - - def __init__( - self, - *, - credential_id: Optional[str] = None, - source_type: Optional[str] = None, - credential_details: Optional['CredentialDetails'] = None, - status: Optional['StatusDetails'] = None, - ) -> None: - """ - Initialize a Credentials object. - - :param str source_type: (optional) The source that this credentials object - connects to. - - `box` indicates the credentials are used to connect an instance of - Enterprise Box. - - `salesforce` indicates the credentials are used to connect to - Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to - an IBM Cloud Object Store. - :param CredentialDetails credential_details: (optional) Object containing - details of the stored credentials. - Obtain credentials for your source from the administrator of the source. - :param StatusDetails status: (optional) Object that contains details about - the status of the authentication process. - """ - self.credential_id = credential_id - self.source_type = source_type - self.credential_details = credential_details - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Credentials': - """Initialize a Credentials object from a json dictionary.""" - args = {} - if (credential_id := _dict.get('credential_id')) is not None: - args['credential_id'] = credential_id - if (source_type := _dict.get('source_type')) is not None: - args['source_type'] = source_type - if (credential_details := _dict.get('credential_details')) is not None: - args['credential_details'] = CredentialDetails.from_dict( - credential_details) - if (status := _dict.get('status')) is not None: - args['status'] = StatusDetails.from_dict(status) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Credentials 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, 'credential_id') and getattr( - self, 'credential_id') is not None: - _dict['credential_id'] = getattr(self, 'credential_id') - if hasattr(self, 'source_type') and self.source_type is not None: - _dict['source_type'] = self.source_type - if hasattr( - self, - 'credential_details') and self.credential_details is not None: - if isinstance(self.credential_details, dict): - _dict['credential_details'] = self.credential_details - else: - _dict['credential_details'] = self.credential_details.to_dict() - if hasattr(self, 'status') and self.status is not None: - if isinstance(self.status, dict): - _dict['status'] = self.status - else: - _dict['status'] = self.status.to_dict() - 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 Credentials object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Credentials') -> 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: 'Credentials') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class SourceTypeEnum(str, Enum): - """ - The source that this credentials object connects to. - - `box` indicates the credentials are used to connect an instance of Enterprise - Box. - - `salesforce` indicates the credentials are used to connect to Salesforce. - - `sharepoint` indicates the credentials are used to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the credentials are used to perform a web crawl. - = `cloud_object_storage` indicates the credentials are used to connect to an IBM - Cloud Object Store. - """ - - BOX = 'box' - SALESFORCE = 'salesforce' - SHAREPOINT = 'sharepoint' - WEB_CRAWL = 'web_crawl' - CLOUD_OBJECT_STORAGE = 'cloud_object_storage' - - -class CredentialsList: - """ - Object containing array of credential definitions. - - :param List[Credentials] credentials: (optional) An array of credential - definitions that were created for this instance. - """ - - def __init__( - self, - *, - credentials: Optional[List['Credentials']] = None, - ) -> None: - """ - Initialize a CredentialsList object. - - :param List[Credentials] credentials: (optional) An array of credential - definitions that were created for this instance. - """ - self.credentials = credentials - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CredentialsList': - """Initialize a CredentialsList object from a json dictionary.""" - args = {} - if (credentials := _dict.get('credentials')) is not None: - args['credentials'] = [ - Credentials.from_dict(v) for v in credentials - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CredentialsList 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, 'credentials') and self.credentials is not None: - credentials_list = [] - for v in self.credentials: - if isinstance(v, dict): - credentials_list.append(v) - else: - credentials_list.append(v.to_dict()) - _dict['credentials'] = credentials_list - 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 CredentialsList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CredentialsList') -> 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: 'CredentialsList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DeleteCollectionResponse: - """ - Response object returned when deleting a colleciton. - - :param str collection_id: The unique identifier of the collection that is being - deleted. - :param str status: The status of the collection. The status of a successful - deletion operation is `deleted`. - """ - - def __init__( - self, - collection_id: str, - status: str, - ) -> None: - """ - Initialize a DeleteCollectionResponse object. - - :param str collection_id: The unique identifier of the collection that is - being deleted. - :param str status: The status of the collection. The status of a successful - deletion operation is `deleted`. - """ - self.collection_id = collection_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteCollectionResponse': - """Initialize a DeleteCollectionResponse object from a json dictionary.""" - args = {} - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - else: - raise ValueError( - 'Required property \'collection_id\' not present in DeleteCollectionResponse JSON' - ) - if (status := _dict.get('status')) is not None: - args['status'] = status - else: - raise ValueError( - 'Required property \'status\' not present in DeleteCollectionResponse JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteCollectionResponse 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, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 DeleteCollectionResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteCollectionResponse') -> 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: 'DeleteCollectionResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the collection. The status of a successful deletion operation is - `deleted`. - """ - - DELETED = 'deleted' - - -class DeleteConfigurationResponse: - """ - Information returned when a configuration is deleted. - - :param str configuration_id: The unique identifier for the configuration. - :param str status: Status of the configuration. A deleted configuration has the - status deleted. - :param List[Notice] notices: (optional) An array of notice messages, if any. - """ - - def __init__( - self, - configuration_id: str, - status: str, - *, - notices: Optional[List['Notice']] = None, - ) -> None: - """ - Initialize a DeleteConfigurationResponse object. - - :param str configuration_id: The unique identifier for the configuration. - :param str status: Status of the configuration. A deleted configuration has - the status deleted. - :param List[Notice] notices: (optional) An array of notice messages, if - any. - """ - self.configuration_id = configuration_id - self.status = status - self.notices = notices - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteConfigurationResponse': - """Initialize a DeleteConfigurationResponse object from a json dictionary.""" - args = {} - if (configuration_id := _dict.get('configuration_id')) is not None: - args['configuration_id'] = configuration_id - else: - raise ValueError( - 'Required property \'configuration_id\' not present in DeleteConfigurationResponse JSON' - ) - if (status := _dict.get('status')) is not None: - args['status'] = status - else: - raise ValueError( - 'Required property \'status\' not present in DeleteConfigurationResponse JSON' - ) - if (notices := _dict.get('notices')) is not None: - args['notices'] = [Notice.from_dict(v) for v in notices] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteConfigurationResponse 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, - 'configuration_id') and self.configuration_id is not None: - _dict['configuration_id'] = self.configuration_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'notices') and self.notices is not None: - notices_list = [] - for v in self.notices: - if isinstance(v, dict): - notices_list.append(v) - else: - notices_list.append(v.to_dict()) - _dict['notices'] = notices_list - 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 DeleteConfigurationResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteConfigurationResponse') -> 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: 'DeleteConfigurationResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the configuration. A deleted configuration has the status deleted. - """ - - DELETED = 'deleted' - - -class DeleteCredentials: - """ - Object returned after credentials are deleted. - - :param str credential_id: (optional) The unique identifier of the credentials - that have been deleted. - :param str status: (optional) The status of the deletion request. - """ - - def __init__( - self, - *, - credential_id: Optional[str] = None, - status: Optional[str] = None, - ) -> None: - """ - Initialize a DeleteCredentials object. - - :param str credential_id: (optional) The unique identifier of the - credentials that have been deleted. - :param str status: (optional) The status of the deletion request. - """ - self.credential_id = credential_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteCredentials': - """Initialize a DeleteCredentials object from a json dictionary.""" - args = {} - if (credential_id := _dict.get('credential_id')) is not None: - args['credential_id'] = credential_id - if (status := _dict.get('status')) is not None: - args['status'] = status - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteCredentials 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, 'credential_id') and self.credential_id is not None: - _dict['credential_id'] = self.credential_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 DeleteCredentials object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteCredentials') -> 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: 'DeleteCredentials') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the deletion request. - """ - - DELETED = 'deleted' - - -class DeleteDocumentResponse: - """ - Information returned when a document is deleted. - - :param str document_id: (optional) The unique identifier of the document. - :param str status: (optional) Status of the document. A deleted document has the - status deleted. - """ - - def __init__( - self, - *, - document_id: Optional[str] = None, - status: Optional[str] = None, - ) -> None: - """ - Initialize a DeleteDocumentResponse object. - - :param str document_id: (optional) The unique identifier of the document. - :param str status: (optional) Status of the document. A deleted document - has the status deleted. - """ - self.document_id = document_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteDocumentResponse': - """Initialize a DeleteDocumentResponse object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (status := _dict.get('status')) is not None: - args['status'] = status - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteDocumentResponse 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, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 DeleteDocumentResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteDocumentResponse') -> 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: 'DeleteDocumentResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the document. A deleted document has the status deleted. - """ - - DELETED = 'deleted' - - -class DeleteEnvironmentResponse: - """ - Response object returned when deleting an environment. - - :param str environment_id: The unique identifier for the environment. - :param str status: Status of the environment. - """ - - def __init__( - self, - environment_id: str, - status: str, - ) -> None: - """ - Initialize a DeleteEnvironmentResponse object. - - :param str environment_id: The unique identifier for the environment. - :param str status: Status of the environment. - """ - self.environment_id = environment_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteEnvironmentResponse': - """Initialize a DeleteEnvironmentResponse object from a json dictionary.""" - args = {} - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - else: - raise ValueError( - 'Required property \'environment_id\' not present in DeleteEnvironmentResponse JSON' - ) - if (status := _dict.get('status')) is not None: - args['status'] = status - else: - raise ValueError( - 'Required property \'status\' not present in DeleteEnvironmentResponse JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteEnvironmentResponse 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, 'environment_id') and self.environment_id is not None: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 DeleteEnvironmentResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteEnvironmentResponse') -> 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: 'DeleteEnvironmentResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the environment. - """ - - DELETED = 'deleted' - - -class DiskUsage: - """ - Summary of the disk usage statistics for the environment. - - :param int used_bytes: (optional) Number of bytes within the environment's disk - capacity that are currently used to store data. - :param int maximum_allowed_bytes: (optional) Total number of bytes available in - the environment's disk capacity. - """ - - def __init__( - self, - *, - used_bytes: Optional[int] = None, - maximum_allowed_bytes: Optional[int] = None, - ) -> None: - """ - Initialize a DiskUsage object. - - """ - self.used_bytes = used_bytes - self.maximum_allowed_bytes = maximum_allowed_bytes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DiskUsage': - """Initialize a DiskUsage object from a json dictionary.""" - args = {} - if (used_bytes := _dict.get('used_bytes')) is not None: - args['used_bytes'] = used_bytes - if (maximum_allowed_bytes := - _dict.get('maximum_allowed_bytes')) is not None: - args['maximum_allowed_bytes'] = maximum_allowed_bytes - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DiskUsage 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, 'used_bytes') and getattr(self, - 'used_bytes') is not None: - _dict['used_bytes'] = getattr(self, 'used_bytes') - if hasattr(self, 'maximum_allowed_bytes') and getattr( - self, 'maximum_allowed_bytes') is not None: - _dict['maximum_allowed_bytes'] = getattr(self, - 'maximum_allowed_bytes') - 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 DiskUsage object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DiskUsage') -> 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: 'DiskUsage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentAccepted: - """ - Information returned after an uploaded document is accepted. - - :param str document_id: (optional) The unique identifier of the ingested - document. - :param str status: (optional) Status of the document in the ingestion process. A - status of `processing` is returned for documents that are ingested with a - *version* date before `2019-01-01`. The `pending` status is returned for all - others. - :param List[Notice] notices: (optional) Array of notices produced by the - document-ingestion process. - """ - - def __init__( - self, - *, - document_id: Optional[str] = None, - status: Optional[str] = None, - notices: Optional[List['Notice']] = None, - ) -> None: - """ - Initialize a DocumentAccepted object. - - :param str document_id: (optional) The unique identifier of the ingested - document. - :param str status: (optional) Status of the document in the ingestion - process. A status of `processing` is returned for documents that are - ingested with a *version* date before `2019-01-01`. The `pending` status is - returned for all others. - :param List[Notice] notices: (optional) Array of notices produced by the - document-ingestion process. - """ - self.document_id = document_id - self.status = status - self.notices = notices - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAccepted': - """Initialize a DocumentAccepted object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (notices := _dict.get('notices')) is not None: - args['notices'] = [Notice.from_dict(v) for v in notices] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentAccepted 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, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'notices') and self.notices is not None: - notices_list = [] - for v in self.notices: - if isinstance(v, dict): - notices_list.append(v) - else: - notices_list.append(v.to_dict()) - _dict['notices'] = notices_list - 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 DocumentAccepted object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocumentAccepted') -> 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: 'DocumentAccepted') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the document in the ingestion process. A status of `processing` is - returned for documents that are ingested with a *version* date before - `2019-01-01`. The `pending` status is returned for all others. - """ - - PROCESSING = 'processing' - PENDING = 'pending' - - -class DocumentCounts: - """ - Object containing collection document count information. - - :param int available: (optional) The total number of available documents in the - collection. - :param int processing: (optional) The number of documents in the collection that - are currently being processed. - :param int failed: (optional) The number of documents in the collection that - failed to be ingested. - :param int pending: (optional) The number of documents that have been uploaded - to the collection, but have not yet started processing. - """ - - def __init__( - self, - *, - available: Optional[int] = None, - processing: Optional[int] = None, - failed: Optional[int] = None, - pending: Optional[int] = None, - ) -> None: - """ - Initialize a DocumentCounts object. - - """ - self.available = available - self.processing = processing - self.failed = failed - self.pending = pending - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentCounts': - """Initialize a DocumentCounts object from a json dictionary.""" - args = {} - if (available := _dict.get('available')) is not None: - args['available'] = available - if (processing := _dict.get('processing')) is not None: - args['processing'] = processing - if (failed := _dict.get('failed')) is not None: - args['failed'] = failed - if (pending := _dict.get('pending')) is not None: - args['pending'] = pending - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentCounts 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, 'available') and getattr(self, - 'available') is not None: - _dict['available'] = getattr(self, 'available') - if hasattr(self, 'processing') and getattr(self, - 'processing') is not None: - _dict['processing'] = getattr(self, 'processing') - if hasattr(self, 'failed') and getattr(self, 'failed') is not None: - _dict['failed'] = getattr(self, 'failed') - if hasattr(self, 'pending') and getattr(self, 'pending') is not None: - _dict['pending'] = getattr(self, 'pending') - 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 DocumentCounts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocumentCounts') -> 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: 'DocumentCounts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentStatus: - """ - Status information about a submitted document. - - :param str document_id: (optional) The unique identifier of the document. - :param str configuration_id: (optional) The unique identifier for the - configuration. - :param str status: (optional) Status of the document in the ingestion process. - :param str status_description: (optional) Description of the document status. - :param str filename: (optional) Name of the original source file (if available). - :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file - (formatted as a hexadecimal string). - :param List[Notice] notices: (optional) Array of notices produced by the - document-ingestion process. - """ - - def __init__( - self, - *, - document_id: Optional[str] = None, - configuration_id: Optional[str] = None, - status: Optional[str] = None, - status_description: Optional[str] = None, - filename: Optional[str] = None, - file_type: Optional[str] = None, - sha1: Optional[str] = None, - notices: Optional[List['Notice']] = None, - ) -> None: - """ - Initialize a DocumentStatus object. - - :param str filename: (optional) Name of the original source file (if - available). - :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file - (formatted as a hexadecimal string). - """ - self.document_id = document_id - self.configuration_id = configuration_id - self.status = status - self.status_description = status_description - self.filename = filename - self.file_type = file_type - self.sha1 = sha1 - self.notices = notices - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentStatus': - """Initialize a DocumentStatus object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (configuration_id := _dict.get('configuration_id')) is not None: - args['configuration_id'] = configuration_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (filename := _dict.get('filename')) is not None: - args['filename'] = filename - if (file_type := _dict.get('file_type')) is not None: - args['file_type'] = file_type - if (sha1 := _dict.get('sha1')) is not None: - args['sha1'] = sha1 - if (notices := _dict.get('notices')) is not None: - args['notices'] = [Notice.from_dict(v) for v in notices] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentStatus 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, 'document_id') and getattr(self, - 'document_id') is not None: - _dict['document_id'] = getattr(self, 'document_id') - if hasattr(self, 'configuration_id') and getattr( - self, 'configuration_id') is not None: - _dict['configuration_id'] = getattr(self, 'configuration_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, 'file_type') and self.file_type is not None: - _dict['file_type'] = self.file_type - if hasattr(self, 'sha1') and self.sha1 is not None: - _dict['sha1'] = self.sha1 - if hasattr(self, 'notices') and getattr(self, 'notices') is not None: - notices_list = [] - for v in getattr(self, 'notices'): - if isinstance(v, dict): - notices_list.append(v) - else: - notices_list.append(v.to_dict()) - _dict['notices'] = notices_list - 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 DocumentStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocumentStatus') -> 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: 'DocumentStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Status of the document in the ingestion process. - """ - - AVAILABLE = 'available' - AVAILABLE_WITH_NOTICES = 'available with notices' - FAILED = 'failed' - PROCESSING = 'processing' - PENDING = 'pending' - - class FileTypeEnum(str, Enum): - """ - The type of the original source file. - """ - - PDF = 'pdf' - HTML = 'html' - WORD = 'word' - JSON = 'json' - - -class Enrichment: - """ - Enrichment step to perform on the document. Each enrichment is performed on the - specified field in the order that they are listed in the configuration. - - :param str description: (optional) Describes what the enrichment step does. - :param str destination_field: Field where enrichments will be stored. This field - must already exist or be at most 1 level deeper than an existing field. For - example, if `text` is a top-level field with no sub-fields, `text.foo` is a - valid destination but `text.foo.bar` is not. - :param str source_field: Field to be enriched. - Arrays can be specified as the **source_field** if the **enrichment** service - for this enrichment is set to `natural_language_undstanding`. - :param bool overwrite: (optional) Indicates that the enrichments will overwrite - the destination_field field if it already exists. - :param str enrichment: Name of the enrichment service to call. The only - supported option is `natural_language_understanding`. The `elements` option is - deprecated and support ended on 10 July 2020. - The **options** object must contain Natural Language Understanding options. - :param bool ignore_downstream_errors: (optional) If true, then most errors - generated during the enrichment process will be treated as warnings and will not - cause the document to fail processing. - :param EnrichmentOptions options: (optional) Options that are specific to a - particular enrichment. - The `elements` enrichment type is deprecated. Use the [Create a - project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of - the Discovery v2 API to create a `content_intelligence` project type instead. - """ - - def __init__( - self, - destination_field: str, - source_field: str, - enrichment: str, - *, - description: Optional[str] = None, - overwrite: Optional[bool] = None, - ignore_downstream_errors: Optional[bool] = None, - options: Optional['EnrichmentOptions'] = None, - ) -> None: - """ - Initialize a Enrichment object. - - :param str destination_field: Field where enrichments will be stored. This - field must already exist or be at most 1 level deeper than an existing - field. For example, if `text` is a top-level field with no sub-fields, - `text.foo` is a valid destination but `text.foo.bar` is not. - :param str source_field: Field to be enriched. - Arrays can be specified as the **source_field** if the **enrichment** - service for this enrichment is set to `natural_language_undstanding`. - :param str enrichment: Name of the enrichment service to call. The only - supported option is `natural_language_understanding`. The `elements` option - is deprecated and support ended on 10 July 2020. - The **options** object must contain Natural Language Understanding - options. - :param str description: (optional) Describes what the enrichment step does. - :param bool overwrite: (optional) Indicates that the enrichments will - overwrite the destination_field field if it already exists. - :param bool ignore_downstream_errors: (optional) If true, then most errors - generated during the enrichment process will be treated as warnings and - will not cause the document to fail processing. - :param EnrichmentOptions options: (optional) Options that are specific to a - particular enrichment. - The `elements` enrichment type is deprecated. Use the [Create a - project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method - of the Discovery v2 API to create a `content_intelligence` project type - instead. - """ - self.description = description - self.destination_field = destination_field - self.source_field = source_field - self.overwrite = overwrite - self.enrichment = enrichment - self.ignore_downstream_errors = ignore_downstream_errors - self.options = options - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Enrichment': - """Initialize a Enrichment object from a json dictionary.""" - args = {} - if (description := _dict.get('description')) is not None: - args['description'] = description - if (destination_field := _dict.get('destination_field')) is not None: - args['destination_field'] = destination_field - else: - raise ValueError( - 'Required property \'destination_field\' not present in Enrichment JSON' - ) - if (source_field := _dict.get('source_field')) is not None: - args['source_field'] = source_field - else: - raise ValueError( - 'Required property \'source_field\' not present in Enrichment JSON' - ) - if (overwrite := _dict.get('overwrite')) is not None: - args['overwrite'] = overwrite - if (enrichment := _dict.get('enrichment')) is not None: - args['enrichment'] = enrichment - else: - raise ValueError( - 'Required property \'enrichment\' not present in Enrichment JSON' - ) - if (ignore_downstream_errors := - _dict.get('ignore_downstream_errors')) is not None: - args['ignore_downstream_errors'] = ignore_downstream_errors - if (options := _dict.get('options')) is not None: - args['options'] = EnrichmentOptions.from_dict(options) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Enrichment 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, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, - 'destination_field') and self.destination_field is not None: - _dict['destination_field'] = self.destination_field - if hasattr(self, 'source_field') and self.source_field is not None: - _dict['source_field'] = self.source_field - if hasattr(self, 'overwrite') and self.overwrite is not None: - _dict['overwrite'] = self.overwrite - if hasattr(self, 'enrichment') and self.enrichment is not None: - _dict['enrichment'] = self.enrichment - if hasattr(self, 'ignore_downstream_errors' - ) and self.ignore_downstream_errors is not None: - _dict['ignore_downstream_errors'] = self.ignore_downstream_errors - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options - else: - _dict['options'] = self.options.to_dict() - 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 Enrichment object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Enrichment') -> 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: 'Enrichment') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class EnrichmentOptions: - """ - Options that are specific to a particular enrichment. - The `elements` enrichment type is deprecated. Use the [Create a - project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of the - Discovery v2 API to create a `content_intelligence` project type instead. - - :param NluEnrichmentFeatures features: (optional) Object containing Natural - Language Understanding features to be used. - :param str language: (optional) ISO 639-1 code indicating the language to use - for the analysis. This code overrides the automatic language detection performed - by the service. Valid codes are `ar` (Arabic), `en` (English), `fr` (French), - `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` - (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, - automatic detection is recommended. - :param str model: (optional) Deprecated: The element extraction model to use, - which can be `contract` only. The `elements` enrichment is deprecated. - """ - - def __init__( - self, - *, - features: Optional['NluEnrichmentFeatures'] = None, - language: Optional[str] = None, - model: Optional[str] = None, - ) -> None: - """ - Initialize a EnrichmentOptions object. - - :param NluEnrichmentFeatures features: (optional) Object containing Natural - Language Understanding features to be used. - :param str language: (optional) ISO 639-1 code indicating the language to - use for the analysis. This code overrides the automatic language detection - performed by the service. Valid codes are `ar` (Arabic), `en` (English), - `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` - (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features - support all languages, automatic detection is recommended. - :param str model: (optional) Deprecated: The element extraction model to - use, which can be `contract` only. The `elements` enrichment is deprecated. - """ - self.features = features - self.language = language - self.model = model - - @classmethod - def from_dict(cls, _dict: Dict) -> 'EnrichmentOptions': - """Initialize a EnrichmentOptions object from a json dictionary.""" - args = {} - if (features := _dict.get('features')) is not None: - args['features'] = NluEnrichmentFeatures.from_dict(features) - if (language := _dict.get('language')) is not None: - args['language'] = language - if (model := _dict.get('model')) is not None: - args['model'] = model - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a EnrichmentOptions 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, 'features') and self.features is not None: - if isinstance(self.features, dict): - _dict['features'] = self.features - else: - _dict['features'] = self.features.to_dict() - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'model') and self.model is not None: - _dict['model'] = self.model - 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 EnrichmentOptions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'EnrichmentOptions') -> 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: 'EnrichmentOptions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class LanguageEnum(str, Enum): - """ - ISO 639-1 code indicating the language to use for the analysis. This code - overrides the automatic language detection performed by the service. Valid codes - are `ar` (Arabic), `en` (English), `fr` (French), `de` (German), `it` (Italian), - `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** - Not all features support all languages, automatic detection is recommended. - """ - - AR = 'ar' - EN = 'en' - FR = 'fr' - DE = 'de' - IT = 'it' - PT = 'pt' - RU = 'ru' - ES = 'es' - SV = 'sv' - - -class Environment: - """ - Details about an environment. - - :param str environment_id: (optional) Unique identifier for the environment. - :param str name: (optional) Name that identifies the environment. - :param str description: (optional) Description of the environment. - :param datetime created: (optional) Creation date of the environment, in the - format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :param datetime updated: (optional) Date of most recent environment update, in - the format `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`. - :param str status: (optional) Current status of the environment. `resizing` is - displayed when a request to increase the environment size has been made, but is - still in the process of being completed. - :param bool read_only: (optional) If `true`, the environment contains read-only - collections that are maintained by IBM. - :param str size: (optional) Current size of the environment. - :param str requested_size: (optional) The new size requested for this - environment. Only returned when the environment *status* is `resizing`. - *Note:* Querying and indexing can still be performed during an environment - upsize. - :param IndexCapacity index_capacity: (optional) Details about the resource usage - and capacity of the environment. - :param SearchStatus search_status: (optional) Information about the Continuous - Relevancy Training for this environment. - """ - - def __init__( - self, - *, - environment_id: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - created: Optional[datetime] = None, - updated: Optional[datetime] = None, - status: Optional[str] = None, - read_only: Optional[bool] = None, - size: Optional[str] = None, - requested_size: Optional[str] = None, - index_capacity: Optional['IndexCapacity'] = None, - search_status: Optional['SearchStatus'] = None, - ) -> None: - """ - Initialize a Environment object. - - :param str name: (optional) Name that identifies the environment. - :param str description: (optional) Description of the environment. - :param str size: (optional) Current size of the environment. - :param str requested_size: (optional) The new size requested for this - environment. Only returned when the environment *status* is `resizing`. - *Note:* Querying and indexing can still be performed during an environment - upsize. - :param IndexCapacity index_capacity: (optional) Details about the resource - usage and capacity of the environment. - :param SearchStatus search_status: (optional) Information about the - Continuous Relevancy Training for this environment. - """ - self.environment_id = environment_id - self.name = name - self.description = description - self.created = created - self.updated = updated - self.status = status - self.read_only = read_only - self.size = size - self.requested_size = requested_size - self.index_capacity = index_capacity - self.search_status = search_status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Environment': - """Initialize a Environment object from a json dictionary.""" - args = {} - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - if (updated := _dict.get('updated')) is not None: - args['updated'] = string_to_datetime(updated) - if (status := _dict.get('status')) is not None: - args['status'] = status - if (read_only := _dict.get('read_only')) is not None: - args['read_only'] = read_only - if (size := _dict.get('size')) is not None: - args['size'] = size - if (requested_size := _dict.get('requested_size')) is not None: - args['requested_size'] = requested_size - if (index_capacity := _dict.get('index_capacity')) is not None: - args['index_capacity'] = IndexCapacity.from_dict(index_capacity) - if (search_status := _dict.get('search_status')) is not None: - args['search_status'] = SearchStatus.from_dict(search_status) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Environment 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, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'read_only') and getattr(self, - 'read_only') is not None: - _dict['read_only'] = getattr(self, 'read_only') - if hasattr(self, 'size') and self.size is not None: - _dict['size'] = self.size - if hasattr(self, 'requested_size') and self.requested_size is not None: - _dict['requested_size'] = self.requested_size - if hasattr(self, 'index_capacity') and self.index_capacity is not None: - if isinstance(self.index_capacity, dict): - _dict['index_capacity'] = self.index_capacity - else: - _dict['index_capacity'] = self.index_capacity.to_dict() - if hasattr(self, 'search_status') and self.search_status is not None: - if isinstance(self.search_status, dict): - _dict['search_status'] = self.search_status - else: - _dict['search_status'] = self.search_status.to_dict() - 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 Environment object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Environment') -> 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: 'Environment') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Current status of the environment. `resizing` is displayed when a request to - increase the environment size has been made, but is still in the process of being - completed. - """ - - ACTIVE = 'active' - PENDING = 'pending' - MAINTENANCE = 'maintenance' - RESIZING = 'resizing' - - class SizeEnum(str, Enum): - """ - Current size of the environment. - """ - - LT = 'LT' - XS = 'XS' - S = 'S' - MS = 'MS' - M = 'M' - ML = 'ML' - L = 'L' - XL = 'XL' - XXL = 'XXL' - XXXL = 'XXXL' - - -class EnvironmentDocuments: - """ - Summary of the document usage statistics for the environment. - - :param int available: (optional) Number of documents indexed for the - environment. - :param int maximum_allowed: (optional) Total number of documents allowed in the - environment's capacity. - """ - - def __init__( - self, - *, - available: Optional[int] = None, - maximum_allowed: Optional[int] = None, - ) -> None: - """ - Initialize a EnvironmentDocuments object. - - """ - self.available = available - self.maximum_allowed = maximum_allowed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'EnvironmentDocuments': - """Initialize a EnvironmentDocuments object from a json dictionary.""" - args = {} - if (available := _dict.get('available')) is not None: - args['available'] = available - if (maximum_allowed := _dict.get('maximum_allowed')) is not None: - args['maximum_allowed'] = maximum_allowed - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a EnvironmentDocuments 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, 'available') and getattr(self, - 'available') is not None: - _dict['available'] = getattr(self, 'available') - if hasattr(self, 'maximum_allowed') and getattr( - self, 'maximum_allowed') is not None: - _dict['maximum_allowed'] = getattr(self, 'maximum_allowed') - 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 EnvironmentDocuments object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'EnvironmentDocuments') -> 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: 'EnvironmentDocuments') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class EventData: - """ - Query event data object. - - :param str environment_id: The **environment_id** associated with the query that - the event is associated with. - :param str session_token: The session token that was returned as part of the - query results that this event is associated with. - :param datetime client_timestamp: (optional) The optional timestamp for the - event that was created. If not provided, the time that the event was created in - the log was used. - :param int display_rank: (optional) The rank of the result item which the event - is associated with. - :param str collection_id: The **collection_id** of the document that this event - is associated with. - :param str document_id: The **document_id** of the document that this event is - associated with. - :param str query_id: (optional) The query identifier stored in the log. The - query and any events associated with that query are stored with the same - **query_id**. - """ - - def __init__( - self, - environment_id: str, - session_token: str, - collection_id: str, - document_id: str, - *, - client_timestamp: Optional[datetime] = None, - display_rank: Optional[int] = None, - query_id: Optional[str] = None, - ) -> None: - """ - Initialize a EventData object. - - :param str environment_id: The **environment_id** associated with the query - that the event is associated with. - :param str session_token: The session token that was returned as part of - the query results that this event is associated with. - :param str collection_id: The **collection_id** of the document that this - event is associated with. - :param str document_id: The **document_id** of the document that this event - is associated with. - :param datetime client_timestamp: (optional) The optional timestamp for the - event that was created. If not provided, the time that the event was - created in the log was used. - :param int display_rank: (optional) The rank of the result item which the - event is associated with. - """ - self.environment_id = environment_id - self.session_token = session_token - self.client_timestamp = client_timestamp - self.display_rank = display_rank - self.collection_id = collection_id - self.document_id = document_id - self.query_id = query_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'EventData': - """Initialize a EventData object from a json dictionary.""" - args = {} - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - else: - raise ValueError( - 'Required property \'environment_id\' not present in EventData JSON' - ) - if (session_token := _dict.get('session_token')) is not None: - args['session_token'] = session_token - else: - raise ValueError( - 'Required property \'session_token\' not present in EventData JSON' - ) - if (client_timestamp := _dict.get('client_timestamp')) is not None: - args['client_timestamp'] = string_to_datetime(client_timestamp) - if (display_rank := _dict.get('display_rank')) is not None: - args['display_rank'] = display_rank - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - else: - raise ValueError( - 'Required property \'collection_id\' not present in EventData JSON' - ) - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - else: - raise ValueError( - 'Required property \'document_id\' not present in EventData JSON' - ) - if (query_id := _dict.get('query_id')) is not None: - args['query_id'] = query_id - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a EventData 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, 'environment_id') and self.environment_id is not None: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'session_token') and self.session_token is not None: - _dict['session_token'] = self.session_token - if hasattr(self, - 'client_timestamp') and self.client_timestamp is not None: - _dict['client_timestamp'] = datetime_to_string( - self.client_timestamp) - if hasattr(self, 'display_rank') and self.display_rank is not None: - _dict['display_rank'] = self.display_rank - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'query_id') and getattr(self, 'query_id') is not None: - _dict['query_id'] = getattr(self, 'query_id') - 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 EventData object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'EventData') -> 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: 'EventData') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Expansion: - """ - An expansion definition. Each object respresents one set of expandable strings. For - example, you could have expansions for the word `hot` in one object, and expansions - for the word `cold` in another. - - :param List[str] input_terms: (optional) A list of terms that will be expanded - for this expansion. If specified, only the items in this list are expanded. - :param List[str] expanded_terms: A list of terms that this expansion will be - expanded to. If specified without **input_terms**, it also functions as the - input term list. - """ - - def __init__( - self, - expanded_terms: List[str], - *, - input_terms: Optional[List[str]] = None, - ) -> None: - """ - Initialize a Expansion object. - - :param List[str] expanded_terms: A list of terms that this expansion will - be expanded to. If specified without **input_terms**, it also functions as - the input term list. - :param List[str] input_terms: (optional) A list of terms that will be - expanded for this expansion. If specified, only the items in this list are - expanded. - """ - self.input_terms = input_terms - self.expanded_terms = expanded_terms - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Expansion': - """Initialize a Expansion object from a json dictionary.""" - args = {} - if (input_terms := _dict.get('input_terms')) is not None: - args['input_terms'] = input_terms - if (expanded_terms := _dict.get('expanded_terms')) is not None: - args['expanded_terms'] = expanded_terms - else: - raise ValueError( - 'Required property \'expanded_terms\' not present in Expansion JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Expansion 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, 'input_terms') and self.input_terms is not None: - _dict['input_terms'] = self.input_terms - if hasattr(self, 'expanded_terms') and self.expanded_terms is not None: - _dict['expanded_terms'] = self.expanded_terms - 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 Expansion object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Expansion') -> 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: 'Expansion') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Expansions: - """ - The query expansion definitions for the specified collection. - - :param List[Expansion] expansions: An array of query expansion definitions. - Each object in the **expansions** array represents a term or set of terms that - will be expanded into other terms. Each expansion object can be configured as - bidirectional or unidirectional. Bidirectional means that all terms are expanded - to all other terms in the object. Unidirectional means that a set list of terms - can be expanded into a second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. When - found in a query, all items in the **expanded_terms** array are then expanded to - the other items in the same array. - To create a uni-directional expansion, specify both an array of **input_terms** - and an array of **expanded_terms**. When items in the **input_terms** array are - present in a query, they are expanded using the items listed in the - **expanded_terms** array. - """ - - def __init__( - self, - expansions: List['Expansion'], - ) -> None: - """ - Initialize a Expansions object. - - :param List[Expansion] expansions: An array of query expansion definitions. - Each object in the **expansions** array represents a term or set of terms - that will be expanded into other terms. Each expansion object can be - configured as bidirectional or unidirectional. Bidirectional means that all - terms are expanded to all other terms in the object. Unidirectional means - that a set list of terms can be expanded into a second list of terms. - To create a bi-directional expansion specify an **expanded_terms** array. - When found in a query, all items in the **expanded_terms** array are then - expanded to the other items in the same array. - To create a uni-directional expansion, specify both an array of - **input_terms** and an array of **expanded_terms**. When items in the - **input_terms** array are present in a query, they are expanded using the - items listed in the **expanded_terms** array. - """ - self.expansions = expansions - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Expansions': - """Initialize a Expansions object from a json dictionary.""" - args = {} - if (expansions := _dict.get('expansions')) is not None: - args['expansions'] = [Expansion.from_dict(v) for v in expansions] - else: - raise ValueError( - 'Required property \'expansions\' not present in Expansions JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Expansions 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, 'expansions') and self.expansions is not None: - expansions_list = [] - for v in self.expansions: - if isinstance(v, dict): - expansions_list.append(v) - else: - expansions_list.append(v.to_dict()) - _dict['expansions'] = expansions_list - 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 Expansions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Expansions') -> 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: 'Expansions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Field: - """ - Object containing field details. - - :param str field: (optional) The name of the field. - :param str type: (optional) The type of the field. - """ - - def __init__( - self, - *, - field: Optional[str] = None, - type: Optional[str] = None, - ) -> None: - """ - Initialize a Field object. - - """ - self.field = field - self.type = type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Field': - """Initialize a Field object from a json dictionary.""" - args = {} - if (field := _dict.get('field')) is not None: - args['field'] = field - if (type := _dict.get('type')) is not None: - args['type'] = type - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Field 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, 'field') and getattr(self, 'field') is not None: - _dict['field'] = getattr(self, 'field') - if hasattr(self, 'type') and getattr(self, 'type') is not None: - _dict['type'] = getattr(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 Field object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Field') -> 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: 'Field') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The type of the field. - """ - - NESTED = 'nested' - STRING = 'string' - DATE = 'date' - LONG = 'long' - INTEGER = 'integer' - SHORT = 'short' - BYTE = 'byte' - DOUBLE = 'double' - FLOAT = 'float' - BOOLEAN = 'boolean' - BINARY = 'binary' - - -class FontSetting: - """ - Font matching configuration. - - :param int level: (optional) The HTML heading level that any content with the - matching font is converted to. - :param int min_size: (optional) The minimum size of the font to match. - :param int max_size: (optional) The maximum size of the font to match. - :param bool bold: (optional) When `true`, the font is matched if it is bold. - :param bool italic: (optional) When `true`, the font is matched if it is italic. - :param str name: (optional) The name of the font. - """ - - def __init__( - self, - *, - level: Optional[int] = None, - min_size: Optional[int] = None, - max_size: Optional[int] = None, - bold: Optional[bool] = None, - italic: Optional[bool] = None, - name: Optional[str] = None, - ) -> None: - """ - Initialize a FontSetting object. - - :param int level: (optional) The HTML heading level that any content with - the matching font is converted to. - :param int min_size: (optional) The minimum size of the font to match. - :param int max_size: (optional) The maximum size of the font to match. - :param bool bold: (optional) When `true`, the font is matched if it is - bold. - :param bool italic: (optional) When `true`, the font is matched if it is - italic. - :param str name: (optional) The name of the font. - """ - self.level = level - self.min_size = min_size - self.max_size = max_size - self.bold = bold - self.italic = italic - self.name = name - - @classmethod - def from_dict(cls, _dict: Dict) -> 'FontSetting': - """Initialize a FontSetting object from a json dictionary.""" - args = {} - if (level := _dict.get('level')) is not None: - args['level'] = level - if (min_size := _dict.get('min_size')) is not None: - args['min_size'] = min_size - if (max_size := _dict.get('max_size')) is not None: - args['max_size'] = max_size - if (bold := _dict.get('bold')) is not None: - args['bold'] = bold - if (italic := _dict.get('italic')) is not None: - args['italic'] = italic - if (name := _dict.get('name')) is not None: - args['name'] = name - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a FontSetting 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, 'level') and self.level is not None: - _dict['level'] = self.level - if hasattr(self, 'min_size') and self.min_size is not None: - _dict['min_size'] = self.min_size - if hasattr(self, 'max_size') and self.max_size is not None: - _dict['max_size'] = self.max_size - if hasattr(self, 'bold') and self.bold is not None: - _dict['bold'] = self.bold - if hasattr(self, 'italic') and self.italic is not None: - _dict['italic'] = self.italic - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - 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 FontSetting object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'FontSetting') -> 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: 'FontSetting') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Gateway: - """ - Object describing a specific gateway. - - :param str gateway_id: (optional) The gateway ID of the gateway. - :param str name: (optional) The user defined name of the gateway. - :param str status: (optional) The current status of the gateway. `connected` - means the gateway is connected to the remotly installed gateway. `idle` means - this gateway is not currently in use. - :param str token: (optional) The generated **token** for this gateway. The value - of this field is used when configuring the remotly installed gateway. - :param str token_id: (optional) The generated **token_id** for this gateway. The - value of this field is used when configuring the remotly installed gateway. - """ - - def __init__( - self, - *, - gateway_id: Optional[str] = None, - name: Optional[str] = None, - status: Optional[str] = None, - token: Optional[str] = None, - token_id: Optional[str] = None, - ) -> None: - """ - Initialize a Gateway object. - - :param str gateway_id: (optional) The gateway ID of the gateway. - :param str name: (optional) The user defined name of the gateway. - :param str status: (optional) The current status of the gateway. - `connected` means the gateway is connected to the remotly installed - gateway. `idle` means this gateway is not currently in use. - :param str token: (optional) The generated **token** for this gateway. The - value of this field is used when configuring the remotly installed gateway. - :param str token_id: (optional) The generated **token_id** for this - gateway. The value of this field is used when configuring the remotly - installed gateway. - """ - self.gateway_id = gateway_id - self.name = name - self.status = status - self.token = token - self.token_id = token_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Gateway': - """Initialize a Gateway object from a json dictionary.""" - args = {} - if (gateway_id := _dict.get('gateway_id')) is not None: - args['gateway_id'] = gateway_id - if (name := _dict.get('name')) is not None: - args['name'] = name - if (status := _dict.get('status')) is not None: - args['status'] = status - if (token := _dict.get('token')) is not None: - args['token'] = token - if (token_id := _dict.get('token_id')) is not None: - args['token_id'] = token_id - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Gateway 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, 'gateway_id') and self.gateway_id is not None: - _dict['gateway_id'] = self.gateway_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'token') and self.token is not None: - _dict['token'] = self.token - if hasattr(self, 'token_id') and self.token_id is not None: - _dict['token_id'] = self.token_id - 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 Gateway object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Gateway') -> 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: 'Gateway') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The current status of the gateway. `connected` means the gateway is connected to - the remotly installed gateway. `idle` means this gateway is not currently in use. - """ - - CONNECTED = 'connected' - IDLE = 'idle' - - -class GatewayDelete: - """ - Gatway deletion confirmation. - - :param str gateway_id: (optional) The gateway ID of the deleted gateway. - :param str status: (optional) The status of the request. - """ - - def __init__( - self, - *, - gateway_id: Optional[str] = None, - status: Optional[str] = None, - ) -> None: - """ - Initialize a GatewayDelete object. - - :param str gateway_id: (optional) The gateway ID of the deleted gateway. - :param str status: (optional) The status of the request. - """ - self.gateway_id = gateway_id - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'GatewayDelete': - """Initialize a GatewayDelete object from a json dictionary.""" - args = {} - if (gateway_id := _dict.get('gateway_id')) is not None: - args['gateway_id'] = gateway_id - if (status := _dict.get('status')) is not None: - args['status'] = status - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a GatewayDelete 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, 'gateway_id') and self.gateway_id is not None: - _dict['gateway_id'] = self.gateway_id - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 GatewayDelete object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'GatewayDelete') -> 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: 'GatewayDelete') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class GatewayList: - """ - Object containing gateways array. - - :param List[Gateway] gateways: (optional) Array of configured gateway - connections. - """ - - def __init__( - self, - *, - gateways: Optional[List['Gateway']] = None, - ) -> None: - """ - Initialize a GatewayList object. - - :param List[Gateway] gateways: (optional) Array of configured gateway - connections. - """ - self.gateways = gateways - - @classmethod - def from_dict(cls, _dict: Dict) -> 'GatewayList': - """Initialize a GatewayList object from a json dictionary.""" - args = {} - if (gateways := _dict.get('gateways')) is not None: - args['gateways'] = [Gateway.from_dict(v) for v in gateways] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a GatewayList 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, 'gateways') and self.gateways is not None: - gateways_list = [] - for v in self.gateways: - if isinstance(v, dict): - gateways_list.append(v) - else: - gateways_list.append(v.to_dict()) - _dict['gateways'] = gateways_list - 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 GatewayList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'GatewayList') -> 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: 'GatewayList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class HtmlSettings: - """ - A list of HTML conversion settings. - - :param List[str] exclude_tags_completely: (optional) Array of HTML tags that are - excluded completely. - :param List[str] exclude_tags_keep_content: (optional) Array of HTML tags which - are excluded but still retain content. - :param XPathPatterns keep_content: (optional) Object containing an array of - XPaths. - :param XPathPatterns exclude_content: (optional) Object containing an array of - XPaths. - :param List[str] keep_tag_attributes: (optional) An array of HTML tag attributes - to keep in the converted document. - :param List[str] exclude_tag_attributes: (optional) Array of HTML tag attributes - to exclude. - """ - - def __init__( - self, - *, - exclude_tags_completely: Optional[List[str]] = None, - exclude_tags_keep_content: Optional[List[str]] = None, - keep_content: Optional['XPathPatterns'] = None, - exclude_content: Optional['XPathPatterns'] = None, - keep_tag_attributes: Optional[List[str]] = None, - exclude_tag_attributes: Optional[List[str]] = None, - ) -> None: - """ - Initialize a HtmlSettings object. - - :param List[str] exclude_tags_completely: (optional) Array of HTML tags - that are excluded completely. - :param List[str] exclude_tags_keep_content: (optional) Array of HTML tags - which are excluded but still retain content. - :param XPathPatterns keep_content: (optional) Object containing an array of - XPaths. - :param XPathPatterns exclude_content: (optional) Object containing an array - of XPaths. - :param List[str] keep_tag_attributes: (optional) An array of HTML tag - attributes to keep in the converted document. - :param List[str] exclude_tag_attributes: (optional) Array of HTML tag - attributes to exclude. - """ - self.exclude_tags_completely = exclude_tags_completely - self.exclude_tags_keep_content = exclude_tags_keep_content - self.keep_content = keep_content - self.exclude_content = exclude_content - self.keep_tag_attributes = keep_tag_attributes - self.exclude_tag_attributes = exclude_tag_attributes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'HtmlSettings': - """Initialize a HtmlSettings object from a json dictionary.""" - args = {} - if (exclude_tags_completely := - _dict.get('exclude_tags_completely')) is not None: - args['exclude_tags_completely'] = exclude_tags_completely - if (exclude_tags_keep_content := - _dict.get('exclude_tags_keep_content')) is not None: - args['exclude_tags_keep_content'] = exclude_tags_keep_content - if (keep_content := _dict.get('keep_content')) is not None: - args['keep_content'] = XPathPatterns.from_dict(keep_content) - if (exclude_content := _dict.get('exclude_content')) is not None: - args['exclude_content'] = XPathPatterns.from_dict(exclude_content) - if (keep_tag_attributes := - _dict.get('keep_tag_attributes')) is not None: - args['keep_tag_attributes'] = keep_tag_attributes - if (exclude_tag_attributes := - _dict.get('exclude_tag_attributes')) is not None: - args['exclude_tag_attributes'] = exclude_tag_attributes - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a HtmlSettings 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, 'exclude_tags_completely' - ) and self.exclude_tags_completely is not None: - _dict['exclude_tags_completely'] = self.exclude_tags_completely - if hasattr(self, 'exclude_tags_keep_content' - ) and self.exclude_tags_keep_content is not None: - _dict['exclude_tags_keep_content'] = self.exclude_tags_keep_content - if hasattr(self, 'keep_content') and self.keep_content is not None: - if isinstance(self.keep_content, dict): - _dict['keep_content'] = self.keep_content - else: - _dict['keep_content'] = self.keep_content.to_dict() - if hasattr(self, - 'exclude_content') and self.exclude_content is not None: - if isinstance(self.exclude_content, dict): - _dict['exclude_content'] = self.exclude_content - else: - _dict['exclude_content'] = self.exclude_content.to_dict() - if hasattr( - self, - 'keep_tag_attributes') and self.keep_tag_attributes is not None: - _dict['keep_tag_attributes'] = self.keep_tag_attributes - if hasattr(self, 'exclude_tag_attributes' - ) and self.exclude_tag_attributes is not None: - _dict['exclude_tag_attributes'] = self.exclude_tag_attributes - 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 HtmlSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'HtmlSettings') -> 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: 'HtmlSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IndexCapacity: - """ - Details about the resource usage and capacity of the environment. - - :param EnvironmentDocuments documents: (optional) Summary of the document usage - statistics for the environment. - :param DiskUsage disk_usage: (optional) Summary of the disk usage statistics for - the environment. - :param CollectionUsage collections: (optional) Summary of the collection usage - in the environment. - """ - - def __init__( - self, - *, - documents: Optional['EnvironmentDocuments'] = None, - disk_usage: Optional['DiskUsage'] = None, - collections: Optional['CollectionUsage'] = None, - ) -> None: - """ - Initialize a IndexCapacity object. - - :param EnvironmentDocuments documents: (optional) Summary of the document - usage statistics for the environment. - :param DiskUsage disk_usage: (optional) Summary of the disk usage - statistics for the environment. - :param CollectionUsage collections: (optional) Summary of the collection - usage in the environment. - """ - self.documents = documents - self.disk_usage = disk_usage - self.collections = collections - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IndexCapacity': - """Initialize a IndexCapacity object from a json dictionary.""" - args = {} - if (documents := _dict.get('documents')) is not None: - args['documents'] = EnvironmentDocuments.from_dict(documents) - if (disk_usage := _dict.get('disk_usage')) is not None: - args['disk_usage'] = DiskUsage.from_dict(disk_usage) - if (collections := _dict.get('collections')) is not None: - args['collections'] = CollectionUsage.from_dict(collections) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a IndexCapacity 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, 'documents') and self.documents is not None: - if isinstance(self.documents, dict): - _dict['documents'] = self.documents - else: - _dict['documents'] = self.documents.to_dict() - if hasattr(self, 'disk_usage') and self.disk_usage is not None: - if isinstance(self.disk_usage, dict): - _dict['disk_usage'] = self.disk_usage - else: - _dict['disk_usage'] = self.disk_usage.to_dict() - if hasattr(self, 'collections') and self.collections is not None: - if isinstance(self.collections, dict): - _dict['collections'] = self.collections - else: - _dict['collections'] = self.collections.to_dict() - 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 IndexCapacity object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'IndexCapacity') -> 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: 'IndexCapacity') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListCollectionFieldsResponse: - """ - The list of fetched fields. - The fields are returned using a fully qualified name format, however, the format - differs slightly from that used by the query operations. - * Fields which contain nested JSON objects are assigned a type of "nested". - * Fields which belong to a nested object are prefixed with `.properties` (for - example, `warnings.properties.severity` means that the `warnings` object has a - property called `severity`). - * Fields returned from the News collection are prefixed with - `v{N}-fullnews-t3-{YEAR}.mappings` (for example, - `v5-fullnews-t3-2016.mappings.text.properties.author`). - - :param List[Field] fields: (optional) An array containing information about each - field in the collections. - """ - - def __init__( - self, - *, - fields: Optional[List['Field']] = None, - ) -> None: - """ - Initialize a ListCollectionFieldsResponse object. - - :param List[Field] fields: (optional) An array containing information about - each field in the collections. - """ - self.fields = fields - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListCollectionFieldsResponse': - """Initialize a ListCollectionFieldsResponse object from a json dictionary.""" - args = {} - if (fields := _dict.get('fields')) is not None: - args['fields'] = [Field.from_dict(v) for v in fields] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListCollectionFieldsResponse 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, 'fields') and self.fields is not None: - fields_list = [] - for v in self.fields: - if isinstance(v, dict): - fields_list.append(v) - else: - fields_list.append(v.to_dict()) - _dict['fields'] = fields_list - 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 ListCollectionFieldsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListCollectionFieldsResponse') -> 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: 'ListCollectionFieldsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListCollectionsResponse: - """ - Response object containing an array of collection details. - - :param List[Collection] collections: (optional) An array containing information - about each collection in the environment. - """ - - def __init__( - self, - *, - collections: Optional[List['Collection']] = None, - ) -> None: - """ - Initialize a ListCollectionsResponse object. - - :param List[Collection] collections: (optional) An array containing - information about each collection in the environment. - """ - self.collections = collections - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListCollectionsResponse': - """Initialize a ListCollectionsResponse object from a json dictionary.""" - args = {} - if (collections := _dict.get('collections')) is not None: - args['collections'] = [Collection.from_dict(v) for v in collections] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListCollectionsResponse 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, 'collections') and self.collections is not None: - collections_list = [] - for v in self.collections: - if isinstance(v, dict): - collections_list.append(v) - else: - collections_list.append(v.to_dict()) - _dict['collections'] = collections_list - 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 ListCollectionsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListCollectionsResponse') -> 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: 'ListCollectionsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListConfigurationsResponse: - """ - Object containing an array of available configurations. - - :param List[Configuration] configurations: (optional) An array of configurations - that are available for the service instance. - """ - - def __init__( - self, - *, - configurations: Optional[List['Configuration']] = None, - ) -> None: - """ - Initialize a ListConfigurationsResponse object. - - :param List[Configuration] configurations: (optional) An array of - configurations that are available for the service instance. - """ - self.configurations = configurations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListConfigurationsResponse': - """Initialize a ListConfigurationsResponse object from a json dictionary.""" - args = {} - if (configurations := _dict.get('configurations')) is not None: - args['configurations'] = [ - Configuration.from_dict(v) for v in configurations - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListConfigurationsResponse 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, 'configurations') and self.configurations is not None: - configurations_list = [] - for v in self.configurations: - if isinstance(v, dict): - configurations_list.append(v) - else: - configurations_list.append(v.to_dict()) - _dict['configurations'] = configurations_list - 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 ListConfigurationsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListConfigurationsResponse') -> 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: 'ListConfigurationsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ListEnvironmentsResponse: - """ - Response object containing an array of configured environments. - - :param List[Environment] environments: (optional) An array of [environments] - that are available for the service instance. - """ - - def __init__( - self, - *, - environments: Optional[List['Environment']] = None, - ) -> None: - """ - Initialize a ListEnvironmentsResponse object. - - :param List[Environment] environments: (optional) An array of - [environments] that are available for the service instance. - """ - self.environments = environments - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListEnvironmentsResponse': - """Initialize a ListEnvironmentsResponse object from a json dictionary.""" - args = {} - if (environments := _dict.get('environments')) is not None: - args['environments'] = [ - Environment.from_dict(v) for v in environments - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListEnvironmentsResponse 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, 'environments') and self.environments is not None: - environments_list = [] - for v in self.environments: - if isinstance(v, dict): - environments_list.append(v) - else: - environments_list.append(v.to_dict()) - _dict['environments'] = environments_list - 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 ListEnvironmentsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListEnvironmentsResponse') -> 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: 'ListEnvironmentsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LogQueryResponse: - """ - Object containing results that match the requested **logs** query. - - :param int matching_results: (optional) Number of matching results. - :param List[LogQueryResponseResult] results: (optional) Array of log query - response results. - """ - - def __init__( - self, - *, - matching_results: Optional[int] = None, - results: Optional[List['LogQueryResponseResult']] = None, - ) -> None: - """ - Initialize a LogQueryResponse object. - - :param int matching_results: (optional) Number of matching results. - :param List[LogQueryResponseResult] results: (optional) Array of log query - response results. - """ - self.matching_results = matching_results - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponse': - """Initialize a LogQueryResponse object from a json dictionary.""" - args = {} - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - if (results := _dict.get('results')) is not None: - args['results'] = [ - LogQueryResponseResult.from_dict(v) for v in results - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a LogQueryResponse 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, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - 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 LogQueryResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'LogQueryResponse') -> 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: 'LogQueryResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LogQueryResponseResult: - """ - Individual result object for a **logs** query. Each object represents either a query - to a Discovery collection or an event that is associated with a query. - - :param str environment_id: (optional) The environment ID that is associated with - this log entry. - :param str customer_id: (optional) The **customer_id** label that was specified - in the header of the query or event API call that corresponds to this log entry. - :param str document_type: (optional) The type of log entry returned. - **query** indicates that the log represents the results of a call to the single - collection **query** method. - **event** indicates that the log represents a call to the **events** API. - :param str natural_language_query: (optional) The value of the - **natural_language_query** query parameter that was used to create these - results. Only returned with logs of type **query**. - **Note:** Other query parameters (such as **filter** or **deduplicate**) might - have been used with this query, but are not recorded. - :param LogQueryResponseResultDocuments document_results: (optional) Object - containing result information that was returned by the query used to create this - log entry. Only returned with logs of type `query`. - :param datetime created_timestamp: (optional) Date that the log result was - created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime client_timestamp: (optional) Date specified by the user when - recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only returned - with logs of type **event**. - :param str query_id: (optional) Identifier that corresponds to the - **natural_language_query** string used in the original or associated query. All - **event** and **query** log entries that have the same original - **natural_language_query** string also have them same **query_id**. This field - can be used to recall all **event** and **query** log results that have the same - original query (**event** logs do not contain the original - **natural_language_query** field). - :param str session_token: (optional) Unique identifier (within a 24-hour period) - that identifies a single `query` log and any `event` logs that were created for - it. - **Note:** If the exact same query is run at the exact same time on different - days, the **session_token** for those queries might be identical. However, the - **created_timestamp** differs. - **Note:** Session tokens are case sensitive. To avoid matching on session tokens - that are identical except for case, use the exact match operator (`::`) when you - query for a specific session token. - :param str collection_id: (optional) The collection ID of the document - associated with this event. Only returned with logs of type `event`. - :param int display_rank: (optional) The original display rank of the document - associated with this event. Only returned with logs of type `event`. - :param str document_id: (optional) The document ID of the document associated - with this event. Only returned with logs of type `event`. - :param str event_type: (optional) The type of event that this object - respresents. Possible values are - - `query` the log of a query to a collection - - `click` the result of a call to the **events** endpoint. - :param str result_type: (optional) The type of result that this **event** is - associated with. Only returned with logs of type `event`. - """ - - def __init__( - self, - *, - environment_id: Optional[str] = None, - customer_id: Optional[str] = None, - document_type: Optional[str] = None, - natural_language_query: Optional[str] = None, - document_results: Optional['LogQueryResponseResultDocuments'] = None, - created_timestamp: Optional[datetime] = None, - client_timestamp: Optional[datetime] = None, - query_id: Optional[str] = None, - session_token: Optional[str] = None, - collection_id: Optional[str] = None, - display_rank: Optional[int] = None, - document_id: Optional[str] = None, - event_type: Optional[str] = None, - result_type: Optional[str] = None, - ) -> None: - """ - Initialize a LogQueryResponseResult object. - - :param str environment_id: (optional) The environment ID that is associated - with this log entry. - :param str customer_id: (optional) The **customer_id** label that was - specified in the header of the query or event API call that corresponds to - this log entry. - :param str document_type: (optional) The type of log entry returned. - **query** indicates that the log represents the results of a call to the - single collection **query** method. - **event** indicates that the log represents a call to the **events** API. - :param str natural_language_query: (optional) The value of the - **natural_language_query** query parameter that was used to create these - results. Only returned with logs of type **query**. - **Note:** Other query parameters (such as **filter** or **deduplicate**) - might have been used with this query, but are not recorded. - :param LogQueryResponseResultDocuments document_results: (optional) Object - containing result information that was returned by the query used to create - this log entry. Only returned with logs of type `query`. - :param datetime created_timestamp: (optional) Date that the log result was - created. Returned in `YYYY-MM-DDThh:mm:ssZ` format. - :param datetime client_timestamp: (optional) Date specified by the user - when recording an event. Returned in `YYYY-MM-DDThh:mm:ssZ` format. Only - returned with logs of type **event**. - :param str query_id: (optional) Identifier that corresponds to the - **natural_language_query** string used in the original or associated query. - All **event** and **query** log entries that have the same original - **natural_language_query** string also have them same **query_id**. This - field can be used to recall all **event** and **query** log results that - have the same original query (**event** logs do not contain the original - **natural_language_query** field). - :param str session_token: (optional) Unique identifier (within a 24-hour - period) that identifies a single `query` log and any `event` logs that were - created for it. - **Note:** If the exact same query is run at the exact same time on - different days, the **session_token** for those queries might be identical. - However, the **created_timestamp** differs. - **Note:** Session tokens are case sensitive. To avoid matching on session - tokens that are identical except for case, use the exact match operator - (`::`) when you query for a specific session token. - :param str collection_id: (optional) The collection ID of the document - associated with this event. Only returned with logs of type `event`. - :param int display_rank: (optional) The original display rank of the - document associated with this event. Only returned with logs of type - `event`. - :param str document_id: (optional) The document ID of the document - associated with this event. Only returned with logs of type `event`. - :param str event_type: (optional) The type of event that this object - respresents. Possible values are - - `query` the log of a query to a collection - - `click` the result of a call to the **events** endpoint. - :param str result_type: (optional) The type of result that this **event** - is associated with. Only returned with logs of type `event`. - """ - self.environment_id = environment_id - self.customer_id = customer_id - self.document_type = document_type - self.natural_language_query = natural_language_query - self.document_results = document_results - self.created_timestamp = created_timestamp - self.client_timestamp = client_timestamp - self.query_id = query_id - self.session_token = session_token - self.collection_id = collection_id - self.display_rank = display_rank - self.document_id = document_id - self.event_type = event_type - self.result_type = result_type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResult': - """Initialize a LogQueryResponseResult object from a json dictionary.""" - args = {} - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (customer_id := _dict.get('customer_id')) is not None: - args['customer_id'] = customer_id - if (document_type := _dict.get('document_type')) is not None: - args['document_type'] = document_type - if (natural_language_query := - _dict.get('natural_language_query')) is not None: - args['natural_language_query'] = natural_language_query - if (document_results := _dict.get('document_results')) is not None: - args[ - 'document_results'] = LogQueryResponseResultDocuments.from_dict( - document_results) - if (created_timestamp := _dict.get('created_timestamp')) is not None: - args['created_timestamp'] = string_to_datetime(created_timestamp) - if (client_timestamp := _dict.get('client_timestamp')) is not None: - args['client_timestamp'] = string_to_datetime(client_timestamp) - if (query_id := _dict.get('query_id')) is not None: - args['query_id'] = query_id - if (session_token := _dict.get('session_token')) is not None: - args['session_token'] = session_token - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - if (display_rank := _dict.get('display_rank')) is not None: - args['display_rank'] = display_rank - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (event_type := _dict.get('event_type')) is not None: - args['event_type'] = event_type - if (result_type := _dict.get('result_type')) is not None: - args['result_type'] = result_type - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a LogQueryResponseResult 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, 'environment_id') and self.environment_id is not None: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'customer_id') and self.customer_id is not None: - _dict['customer_id'] = self.customer_id - if hasattr(self, 'document_type') and self.document_type is not None: - _dict['document_type'] = self.document_type - if hasattr(self, 'natural_language_query' - ) and self.natural_language_query is not None: - _dict['natural_language_query'] = self.natural_language_query - if hasattr(self, - 'document_results') and self.document_results is not None: - if isinstance(self.document_results, dict): - _dict['document_results'] = self.document_results - else: - _dict['document_results'] = self.document_results.to_dict() - if hasattr(self, - 'created_timestamp') and self.created_timestamp is not None: - _dict['created_timestamp'] = datetime_to_string( - self.created_timestamp) - if hasattr(self, - 'client_timestamp') and self.client_timestamp is not None: - _dict['client_timestamp'] = datetime_to_string( - self.client_timestamp) - if hasattr(self, 'query_id') and self.query_id is not None: - _dict['query_id'] = self.query_id - if hasattr(self, 'session_token') and self.session_token is not None: - _dict['session_token'] = self.session_token - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'display_rank') and self.display_rank is not None: - _dict['display_rank'] = self.display_rank - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'event_type') and self.event_type is not None: - _dict['event_type'] = self.event_type - if hasattr(self, 'result_type') and self.result_type is not None: - _dict['result_type'] = self.result_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 LogQueryResponseResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'LogQueryResponseResult') -> 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: 'LogQueryResponseResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class DocumentTypeEnum(str, Enum): - """ - The type of log entry returned. - **query** indicates that the log represents the results of a call to the single - collection **query** method. - **event** indicates that the log represents a call to the **events** API. - """ - - QUERY = 'query' - EVENT = 'event' - - class EventTypeEnum(str, Enum): - """ - The type of event that this object respresents. Possible values are - - `query` the log of a query to a collection - - `click` the result of a call to the **events** endpoint. - """ - - CLICK = 'click' - QUERY = 'query' - - class ResultTypeEnum(str, Enum): - """ - The type of result that this **event** is associated with. Only returned with logs - of type `event`. - """ - - DOCUMENT = 'document' - - -class LogQueryResponseResultDocuments: - """ - Object containing result information that was returned by the query used to create - this log entry. Only returned with logs of type `query`. - - :param List[LogQueryResponseResultDocumentsResult] results: (optional) Array of - log query response results. - :param int count: (optional) The number of results returned in the query - associate with this log. - """ - - def __init__( - self, - *, - results: Optional[List['LogQueryResponseResultDocumentsResult']] = None, - count: Optional[int] = None, - ) -> None: - """ - Initialize a LogQueryResponseResultDocuments object. - - :param List[LogQueryResponseResultDocumentsResult] results: (optional) - Array of log query response results. - :param int count: (optional) The number of results returned in the query - associate with this log. - """ - self.results = results - self.count = count - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocuments': - """Initialize a LogQueryResponseResultDocuments object from a json dictionary.""" - args = {} - if (results := _dict.get('results')) is not None: - args['results'] = [ - LogQueryResponseResultDocumentsResult.from_dict(v) - for v in results - ] - if (count := _dict.get('count')) is not None: - args['count'] = count - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a LogQueryResponseResultDocuments 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, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - 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 LogQueryResponseResultDocuments object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'LogQueryResponseResultDocuments') -> 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: 'LogQueryResponseResultDocuments') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LogQueryResponseResultDocumentsResult: - """ - Each object in the **results** array corresponds to an individual document returned by - the original query. - - :param int position: (optional) The result rank of this document. A position of - `1` indicates that it was the first returned result. - :param str document_id: (optional) The **document_id** of the document that this - result represents. - :param float score: (optional) The raw score of this result. A higher score - indicates a greater match to the query parameters. - :param float confidence: (optional) The confidence score of the result's - analysis. A higher score indicating greater confidence. - :param str collection_id: (optional) The **collection_id** of the document - represented by this result. - """ - - def __init__( - self, - *, - position: Optional[int] = None, - document_id: Optional[str] = None, - score: Optional[float] = None, - confidence: Optional[float] = None, - collection_id: Optional[str] = None, - ) -> None: - """ - Initialize a LogQueryResponseResultDocumentsResult object. - - :param int position: (optional) The result rank of this document. A - position of `1` indicates that it was the first returned result. - :param str document_id: (optional) The **document_id** of the document that - this result represents. - :param float score: (optional) The raw score of this result. A higher score - indicates a greater match to the query parameters. - :param float confidence: (optional) The confidence score of the result's - analysis. A higher score indicating greater confidence. - :param str collection_id: (optional) The **collection_id** of the document - represented by this result. - """ - self.position = position - self.document_id = document_id - self.score = score - self.confidence = confidence - self.collection_id = collection_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogQueryResponseResultDocumentsResult': - """Initialize a LogQueryResponseResultDocumentsResult object from a json dictionary.""" - args = {} - if (position := _dict.get('position')) is not None: - args['position'] = position - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (score := _dict.get('score')) is not None: - args['score'] = score - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a LogQueryResponseResultDocumentsResult 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, 'position') and self.position is not None: - _dict['position'] = self.position - if hasattr(self, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - 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 LogQueryResponseResultDocumentsResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'LogQueryResponseResultDocumentsResult') -> 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: 'LogQueryResponseResultDocumentsResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricAggregation: - """ - An aggregation analyzing log information for queries and events. - - :param str interval: (optional) The measurement interval for this metric. Metric - intervals are always 1 day (`1d`). - :param str event_type: (optional) The event type associated with this metric - result. This field, when present, will always be `click`. - :param List[MetricAggregationResult] results: (optional) Array of metric - aggregation query results. - """ - - def __init__( - self, - *, - interval: Optional[str] = None, - event_type: Optional[str] = None, - results: Optional[List['MetricAggregationResult']] = None, - ) -> None: - """ - Initialize a MetricAggregation object. - - :param str interval: (optional) The measurement interval for this metric. - Metric intervals are always 1 day (`1d`). - :param str event_type: (optional) The event type associated with this - metric result. This field, when present, will always be `click`. - :param List[MetricAggregationResult] results: (optional) Array of metric - aggregation query results. - """ - self.interval = interval - self.event_type = event_type - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricAggregation': - """Initialize a MetricAggregation object from a json dictionary.""" - args = {} - if (interval := _dict.get('interval')) is not None: - args['interval'] = interval - if (event_type := _dict.get('event_type')) is not None: - args['event_type'] = event_type - if (results := _dict.get('results')) is not None: - args['results'] = [ - MetricAggregationResult.from_dict(v) for v in results - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricAggregation 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, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'event_type') and self.event_type is not None: - _dict['event_type'] = self.event_type - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - 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 MetricAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricAggregation') -> 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: 'MetricAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricAggregationResult: - """ - Aggregation result data for the requested metric. - - :param datetime key_as_string: (optional) Date in string form representing the - start of this interval. - :param int key: (optional) Unix epoch time equivalent of the **key_as_string**, - that represents the start of this interval. - :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated events - divided by the total number of queries for the interval. Only returned with - **event_rate** metrics. - """ - - def __init__( - self, - *, - key_as_string: Optional[datetime] = None, - key: Optional[int] = None, - matching_results: Optional[int] = None, - event_rate: Optional[float] = None, - ) -> None: - """ - Initialize a MetricAggregationResult object. - - :param datetime key_as_string: (optional) Date in string form representing - the start of this interval. - :param int key: (optional) Unix epoch time equivalent of the - **key_as_string**, that represents the start of this interval. - :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated - events divided by the total number of queries for the interval. Only - returned with **event_rate** metrics. - """ - self.key_as_string = key_as_string - self.key = key - self.matching_results = matching_results - self.event_rate = event_rate - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricAggregationResult': - """Initialize a MetricAggregationResult object from a json dictionary.""" - args = {} - if (key_as_string := _dict.get('key_as_string')) is not None: - args['key_as_string'] = string_to_datetime(key_as_string) - if (key := _dict.get('key')) is not None: - args['key'] = key - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - if (event_rate := _dict.get('event_rate')) is not None: - args['event_rate'] = event_rate - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricAggregationResult 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, 'key_as_string') and self.key_as_string is not None: - _dict['key_as_string'] = datetime_to_string(self.key_as_string) - if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'event_rate') and self.event_rate is not None: - _dict['event_rate'] = self.event_rate - 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 MetricAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricAggregationResult') -> 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: 'MetricAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricResponse: - """ - The response generated from a call to a **metrics** method. - - :param List[MetricAggregation] aggregations: (optional) Array of metric - aggregations. - """ - - def __init__( - self, - *, - aggregations: Optional[List['MetricAggregation']] = None, - ) -> None: - """ - Initialize a MetricResponse object. - - :param List[MetricAggregation] aggregations: (optional) Array of metric - aggregations. - """ - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricResponse': - """Initialize a MetricResponse object from a json dictionary.""" - args = {} - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - MetricAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricResponse 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, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - 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 MetricResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricResponse') -> 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: 'MetricResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricTokenAggregation: - """ - An aggregation analyzing log information for queries and events. - - :param str event_type: (optional) The event type associated with this metric - result. This field, when present, will always be `click`. - :param List[MetricTokenAggregationResult] results: (optional) Array of results - for the metric token aggregation. - """ - - def __init__( - self, - *, - event_type: Optional[str] = None, - results: Optional[List['MetricTokenAggregationResult']] = None, - ) -> None: - """ - Initialize a MetricTokenAggregation object. - - :param str event_type: (optional) The event type associated with this - metric result. This field, when present, will always be `click`. - :param List[MetricTokenAggregationResult] results: (optional) Array of - results for the metric token aggregation. - """ - self.event_type = event_type - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregation': - """Initialize a MetricTokenAggregation object from a json dictionary.""" - args = {} - if (event_type := _dict.get('event_type')) is not None: - args['event_type'] = event_type - if (results := _dict.get('results')) is not None: - args['results'] = [ - MetricTokenAggregationResult.from_dict(v) for v in results - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricTokenAggregation 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, 'event_type') and self.event_type is not None: - _dict['event_type'] = self.event_type - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - 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 MetricTokenAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricTokenAggregation') -> 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: 'MetricTokenAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricTokenAggregationResult: - """ - Aggregation result data for the requested metric. - - :param str key: (optional) The content of the **natural_language_query** - parameter used in the query that this result represents. - :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated events - divided by the total number of queries currently stored (queries and events are - stored in the log for 30 days). - """ - - def __init__( - self, - *, - key: Optional[str] = None, - matching_results: Optional[int] = None, - event_rate: Optional[float] = None, - ) -> None: - """ - Initialize a MetricTokenAggregationResult object. - - :param str key: (optional) The content of the **natural_language_query** - parameter used in the query that this result represents. - :param int matching_results: (optional) Number of matching results. - :param float event_rate: (optional) The number of queries with associated - events divided by the total number of queries currently stored (queries and - events are stored in the log for 30 days). - """ - self.key = key - self.matching_results = matching_results - self.event_rate = event_rate - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricTokenAggregationResult': - """Initialize a MetricTokenAggregationResult object from a json dictionary.""" - args = {} - if (key := _dict.get('key')) is not None: - args['key'] = key - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - if (event_rate := _dict.get('event_rate')) is not None: - args['event_rate'] = event_rate - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricTokenAggregationResult 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, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'event_rate') and self.event_rate is not None: - _dict['event_rate'] = self.event_rate - 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 MetricTokenAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricTokenAggregationResult') -> 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: 'MetricTokenAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class MetricTokenResponse: - """ - The response generated from a call to a **metrics** method that evaluates tokens. - - :param List[MetricTokenAggregation] aggregations: (optional) Array of metric - token aggregations. - """ - - def __init__( - self, - *, - aggregations: Optional[List['MetricTokenAggregation']] = None, - ) -> None: - """ - Initialize a MetricTokenResponse object. - - :param List[MetricTokenAggregation] aggregations: (optional) Array of - metric token aggregations. - """ - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetricTokenResponse': - """Initialize a MetricTokenResponse object from a json dictionary.""" - args = {} - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - MetricTokenAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetricTokenResponse 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, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - 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 MetricTokenResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetricTokenResponse') -> 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: 'MetricTokenResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentConcepts: - """ - An object specifiying the concepts enrichment and related parameters. - - :param int limit: (optional) The maximum number of concepts enrichments to - extact from each instance of the specified field. - """ - - def __init__( - self, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a NluEnrichmentConcepts object. - - :param int limit: (optional) The maximum number of concepts enrichments to - extact from each instance of the specified field. - """ - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentConcepts': - """Initialize a NluEnrichmentConcepts object from a json dictionary.""" - args = {} - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentConcepts 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, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 NluEnrichmentConcepts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentConcepts') -> 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: 'NluEnrichmentConcepts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentEmotion: - """ - An object specifying the emotion detection enrichment and related parameters. - - :param bool document: (optional) When `true`, emotion detection is performed on - the entire field. - :param List[str] targets: (optional) A comma-separated list of target strings - that will have any associated emotions detected. - """ - - def __init__( - self, - *, - document: Optional[bool] = None, - targets: Optional[List[str]] = None, - ) -> None: - """ - Initialize a NluEnrichmentEmotion object. - - :param bool document: (optional) When `true`, emotion detection is - performed on the entire field. - :param List[str] targets: (optional) A comma-separated list of target - strings that will have any associated emotions detected. - """ - self.document = document - self.targets = targets - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEmotion': - """Initialize a NluEnrichmentEmotion object from a json dictionary.""" - args = {} - if (document := _dict.get('document')) is not None: - args['document'] = document - if (targets := _dict.get('targets')) is not None: - args['targets'] = targets - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentEmotion 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, 'document') and self.document is not None: - _dict['document'] = self.document - if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = self.targets - 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 NluEnrichmentEmotion object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentEmotion') -> 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: 'NluEnrichmentEmotion') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentEntities: - """ - An object speficying the Entities enrichment and related parameters. - - :param bool sentiment: (optional) When `true`, sentiment analysis of entities - will be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of entities will - be performed on the specified field. - :param int limit: (optional) The maximum number of entities to extract for each - instance of the specified field. - :param bool mentions: (optional) When `true`, the number of mentions of each - identified entity is recorded. The default is `false`. - :param bool mention_types: (optional) When `true`, the types of mentions for - each idetifieid entity is recorded. The default is `false`. - :param bool sentence_locations: (optional) When `true`, a list of sentence - locations for each instance of each identified entity is recorded. The default - is `false`. - :param str model: (optional) The enrichement model to use with entity - extraction. May be a custom model provided by Watson Knowledge Studio, or the - default public model `alchemy`. - """ - - def __init__( - self, - *, - sentiment: Optional[bool] = None, - emotion: Optional[bool] = None, - limit: Optional[int] = None, - mentions: Optional[bool] = None, - mention_types: Optional[bool] = None, - sentence_locations: Optional[bool] = None, - model: Optional[str] = None, - ) -> None: - """ - Initialize a NluEnrichmentEntities object. - - :param bool sentiment: (optional) When `true`, sentiment analysis of - entities will be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of entities - will be performed on the specified field. - :param int limit: (optional) The maximum number of entities to extract for - each instance of the specified field. - :param bool mentions: (optional) When `true`, the number of mentions of - each identified entity is recorded. The default is `false`. - :param bool mention_types: (optional) When `true`, the types of mentions - for each idetifieid entity is recorded. The default is `false`. - :param bool sentence_locations: (optional) When `true`, a list of sentence - locations for each instance of each identified entity is recorded. The - default is `false`. - :param str model: (optional) The enrichement model to use with entity - extraction. May be a custom model provided by Watson Knowledge Studio, or - the default public model `alchemy`. - """ - self.sentiment = sentiment - self.emotion = emotion - self.limit = limit - self.mentions = mentions - self.mention_types = mention_types - self.sentence_locations = sentence_locations - self.model = model - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentEntities': - """Initialize a NluEnrichmentEntities object from a json dictionary.""" - args = {} - if (sentiment := _dict.get('sentiment')) is not None: - args['sentiment'] = sentiment - if (emotion := _dict.get('emotion')) is not None: - args['emotion'] = emotion - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - if (mentions := _dict.get('mentions')) is not None: - args['mentions'] = mentions - if (mention_types := _dict.get('mention_types')) is not None: - args['mention_types'] = mention_types - if (sentence_locations := _dict.get('sentence_locations')) is not None: - args['sentence_locations'] = sentence_locations - if (model := _dict.get('model')) is not None: - args['model'] = model - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentEntities 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, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment - if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = self.mentions - if hasattr(self, 'mention_types') and self.mention_types is not None: - _dict['mention_types'] = self.mention_types - if hasattr( - self, - 'sentence_locations') and self.sentence_locations is not None: - _dict['sentence_locations'] = self.sentence_locations - if hasattr(self, 'model') and self.model is not None: - _dict['model'] = self.model - 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 NluEnrichmentEntities object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentEntities') -> 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: 'NluEnrichmentEntities') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentFeatures: - """ - Object containing Natural Language Understanding features to be used. - - :param NluEnrichmentKeywords keywords: (optional) An object specifying the - Keyword enrichment and related parameters. - :param NluEnrichmentEntities entities: (optional) An object speficying the - Entities enrichment and related parameters. - :param NluEnrichmentSentiment sentiment: (optional) An object specifying the - sentiment extraction enrichment and related parameters. - :param NluEnrichmentEmotion emotion: (optional) An object specifying the emotion - detection enrichment and related parameters. - :param dict categories: (optional) An object that indicates the Categories - enrichment will be applied to the specified field. - :param NluEnrichmentSemanticRoles semantic_roles: (optional) An object - specifiying the semantic roles enrichment and related parameters. - :param NluEnrichmentRelations relations: (optional) An object specifying the - relations enrichment and related parameters. - :param NluEnrichmentConcepts concepts: (optional) An object specifiying the - concepts enrichment and related parameters. - """ - - def __init__( - self, - *, - keywords: Optional['NluEnrichmentKeywords'] = None, - entities: Optional['NluEnrichmentEntities'] = None, - sentiment: Optional['NluEnrichmentSentiment'] = None, - emotion: Optional['NluEnrichmentEmotion'] = None, - categories: Optional[dict] = None, - semantic_roles: Optional['NluEnrichmentSemanticRoles'] = None, - relations: Optional['NluEnrichmentRelations'] = None, - concepts: Optional['NluEnrichmentConcepts'] = None, - ) -> None: - """ - Initialize a NluEnrichmentFeatures object. - - :param NluEnrichmentKeywords keywords: (optional) An object specifying the - Keyword enrichment and related parameters. - :param NluEnrichmentEntities entities: (optional) An object speficying the - Entities enrichment and related parameters. - :param NluEnrichmentSentiment sentiment: (optional) An object specifying - the sentiment extraction enrichment and related parameters. - :param NluEnrichmentEmotion emotion: (optional) An object specifying the - emotion detection enrichment and related parameters. - :param dict categories: (optional) An object that indicates the Categories - enrichment will be applied to the specified field. - :param NluEnrichmentSemanticRoles semantic_roles: (optional) An object - specifiying the semantic roles enrichment and related parameters. - :param NluEnrichmentRelations relations: (optional) An object specifying - the relations enrichment and related parameters. - :param NluEnrichmentConcepts concepts: (optional) An object specifiying the - concepts enrichment and related parameters. - """ - self.keywords = keywords - self.entities = entities - self.sentiment = sentiment - self.emotion = emotion - self.categories = categories - self.semantic_roles = semantic_roles - self.relations = relations - self.concepts = concepts - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentFeatures': - """Initialize a NluEnrichmentFeatures object from a json dictionary.""" - args = {} - if (keywords := _dict.get('keywords')) is not None: - args['keywords'] = NluEnrichmentKeywords.from_dict(keywords) - if (entities := _dict.get('entities')) is not None: - args['entities'] = NluEnrichmentEntities.from_dict(entities) - if (sentiment := _dict.get('sentiment')) is not None: - args['sentiment'] = NluEnrichmentSentiment.from_dict(sentiment) - if (emotion := _dict.get('emotion')) is not None: - args['emotion'] = NluEnrichmentEmotion.from_dict(emotion) - if (categories := _dict.get('categories')) is not None: - args['categories'] = categories - if (semantic_roles := _dict.get('semantic_roles')) is not None: - args['semantic_roles'] = NluEnrichmentSemanticRoles.from_dict( - semantic_roles) - if (relations := _dict.get('relations')) is not None: - args['relations'] = NluEnrichmentRelations.from_dict(relations) - if (concepts := _dict.get('concepts')) is not None: - args['concepts'] = NluEnrichmentConcepts.from_dict(concepts) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentFeatures 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, 'keywords') and self.keywords is not None: - if isinstance(self.keywords, dict): - _dict['keywords'] = self.keywords - else: - _dict['keywords'] = self.keywords.to_dict() - if hasattr(self, 'entities') and self.entities is not None: - if isinstance(self.entities, dict): - _dict['entities'] = self.entities - else: - _dict['entities'] = self.entities.to_dict() - if hasattr(self, 'sentiment') and self.sentiment is not None: - if isinstance(self.sentiment, dict): - _dict['sentiment'] = self.sentiment - else: - _dict['sentiment'] = self.sentiment.to_dict() - if hasattr(self, 'emotion') and self.emotion is not None: - if isinstance(self.emotion, dict): - _dict['emotion'] = self.emotion - else: - _dict['emotion'] = self.emotion.to_dict() - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = self.categories - if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: - if isinstance(self.semantic_roles, dict): - _dict['semantic_roles'] = self.semantic_roles - else: - _dict['semantic_roles'] = self.semantic_roles.to_dict() - if hasattr(self, 'relations') and self.relations is not None: - if isinstance(self.relations, dict): - _dict['relations'] = self.relations - else: - _dict['relations'] = self.relations.to_dict() - if hasattr(self, 'concepts') and self.concepts is not None: - if isinstance(self.concepts, dict): - _dict['concepts'] = self.concepts - else: - _dict['concepts'] = self.concepts.to_dict() - 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 NluEnrichmentFeatures object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentFeatures') -> 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: 'NluEnrichmentFeatures') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentKeywords: - """ - An object specifying the Keyword enrichment and related parameters. - - :param bool sentiment: (optional) When `true`, sentiment analysis of keywords - will be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of keywords will - be performed on the specified field. - :param int limit: (optional) The maximum number of keywords to extract for each - instance of the specified field. - """ - - def __init__( - self, - *, - sentiment: Optional[bool] = None, - emotion: Optional[bool] = None, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a NluEnrichmentKeywords object. - - :param bool sentiment: (optional) When `true`, sentiment analysis of - keywords will be performed on the specified field. - :param bool emotion: (optional) When `true`, emotion detection of keywords - will be performed on the specified field. - :param int limit: (optional) The maximum number of keywords to extract for - each instance of the specified field. - """ - self.sentiment = sentiment - self.emotion = emotion - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentKeywords': - """Initialize a NluEnrichmentKeywords object from a json dictionary.""" - args = {} - if (sentiment := _dict.get('sentiment')) is not None: - args['sentiment'] = sentiment - if (emotion := _dict.get('emotion')) is not None: - args['emotion'] = emotion - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentKeywords 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, 'sentiment') and self.sentiment is not None: - _dict['sentiment'] = self.sentiment - if hasattr(self, 'emotion') and self.emotion is not None: - _dict['emotion'] = self.emotion - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 NluEnrichmentKeywords object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentKeywords') -> 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: 'NluEnrichmentKeywords') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentRelations: - """ - An object specifying the relations enrichment and related parameters. - - :param str model: (optional) *For use with `natural_language_understanding` - enrichments only.* The enrichement model to use with relationship extraction. - May be a custom model provided by Watson Knowledge Studio, the default public - model is`en-news`. - """ - - def __init__( - self, - *, - model: Optional[str] = None, - ) -> None: - """ - Initialize a NluEnrichmentRelations object. - - :param str model: (optional) *For use with `natural_language_understanding` - enrichments only.* The enrichement model to use with relationship - extraction. May be a custom model provided by Watson Knowledge Studio, the - default public model is`en-news`. - """ - self.model = model - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentRelations': - """Initialize a NluEnrichmentRelations object from a json dictionary.""" - args = {} - if (model := _dict.get('model')) is not None: - args['model'] = model - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentRelations 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, 'model') and self.model is not None: - _dict['model'] = self.model - 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 NluEnrichmentRelations object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentRelations') -> 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: 'NluEnrichmentRelations') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentSemanticRoles: - """ - An object specifiying the semantic roles enrichment and related parameters. - - :param bool entities: (optional) When `true`, entities are extracted from the - identified sentence parts. - :param bool keywords: (optional) When `true`, keywords are extracted from the - identified sentence parts. - :param int limit: (optional) The maximum number of semantic roles enrichments to - extact from each instance of the specified field. - """ - - def __init__( - self, - *, - entities: Optional[bool] = None, - keywords: Optional[bool] = None, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a NluEnrichmentSemanticRoles object. - - :param bool entities: (optional) When `true`, entities are extracted from - the identified sentence parts. - :param bool keywords: (optional) When `true`, keywords are extracted from - the identified sentence parts. - :param int limit: (optional) The maximum number of semantic roles - enrichments to extact from each instance of the specified field. - """ - self.entities = entities - self.keywords = keywords - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSemanticRoles': - """Initialize a NluEnrichmentSemanticRoles object from a json dictionary.""" - args = {} - if (entities := _dict.get('entities')) is not None: - args['entities'] = entities - if (keywords := _dict.get('keywords')) is not None: - args['keywords'] = keywords - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentSemanticRoles 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, 'entities') and self.entities is not None: - _dict['entities'] = self.entities - if hasattr(self, 'keywords') and self.keywords is not None: - _dict['keywords'] = self.keywords - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 NluEnrichmentSemanticRoles object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentSemanticRoles') -> 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: 'NluEnrichmentSemanticRoles') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NluEnrichmentSentiment: - """ - An object specifying the sentiment extraction enrichment and related parameters. - - :param bool document: (optional) When `true`, sentiment analysis is performed on - the entire field. - :param List[str] targets: (optional) A comma-separated list of target strings - that will have any associated sentiment analyzed. - """ - - def __init__( - self, - *, - document: Optional[bool] = None, - targets: Optional[List[str]] = None, - ) -> None: - """ - Initialize a NluEnrichmentSentiment object. - - :param bool document: (optional) When `true`, sentiment analysis is - performed on the entire field. - :param List[str] targets: (optional) A comma-separated list of target - strings that will have any associated sentiment analyzed. - """ - self.document = document - self.targets = targets - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NluEnrichmentSentiment': - """Initialize a NluEnrichmentSentiment object from a json dictionary.""" - args = {} - if (document := _dict.get('document')) is not None: - args['document'] = document - if (targets := _dict.get('targets')) is not None: - args['targets'] = targets - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NluEnrichmentSentiment 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, 'document') and self.document is not None: - _dict['document'] = self.document - if hasattr(self, 'targets') and self.targets is not None: - _dict['targets'] = self.targets - 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 NluEnrichmentSentiment object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NluEnrichmentSentiment') -> 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: 'NluEnrichmentSentiment') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class NormalizationOperation: - """ - Object containing normalization operations. - - :param str operation: (optional) Identifies what type of operation to perform. - **copy** - Copies the value of the **source_field** to the **destination_field** - field. If the **destination_field** already exists, then the value of the - **source_field** overwrites the original value of the **destination_field**. - **move** - Renames (moves) the **source_field** to the **destination_field**. If - the **destination_field** already exists, then the value of the **source_field** - overwrites the original value of the **destination_field**. Rename is identical - to copy, except that the **source_field** is removed after the value has been - copied to the **destination_field** (it is the same as a _copy_ followed by a - _remove_). - **merge** - Merges the value of the **source_field** with the value of the - **destination_field**. The **destination_field** is converted into an array if - it is not already an array, and the value of the **source_field** is appended to - the array. This operation removes the **source_field** after the merge. If the - **source_field** does not exist in the current document, then the - **destination_field** is still converted into an array (if it is not an array - already). This conversion ensures the type for **destination_field** is - consistent across all documents. - **remove** - Deletes the **source_field** field. The **destination_field** is - ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the - ingested document. **source_field** and **destination_field** are ignored by - this operation because _remove_nulls_ operates on the entire ingested document. - Typically, **remove_nulls** is invoked as the last normalization operation (if - it is invoked at all, it can be time-expensive). - :param str source_field: (optional) The source field for the operation. - :param str destination_field: (optional) The destination field for the - operation. - """ - - def __init__( - self, - *, - operation: Optional[str] = None, - source_field: Optional[str] = None, - destination_field: Optional[str] = None, - ) -> None: - """ - Initialize a NormalizationOperation object. - - :param str operation: (optional) Identifies what type of operation to - perform. - **copy** - Copies the value of the **source_field** to the - **destination_field** field. If the **destination_field** already exists, - then the value of the **source_field** overwrites the original value of the - **destination_field**. - **move** - Renames (moves) the **source_field** to the - **destination_field**. If the **destination_field** already exists, then - the value of the **source_field** overwrites the original value of the - **destination_field**. Rename is identical to copy, except that the - **source_field** is removed after the value has been copied to the - **destination_field** (it is the same as a _copy_ followed by a _remove_). - **merge** - Merges the value of the **source_field** with the value of the - **destination_field**. The **destination_field** is converted into an array - if it is not already an array, and the value of the **source_field** is - appended to the array. This operation removes the **source_field** after - the merge. If the **source_field** does not exist in the current document, - then the **destination_field** is still converted into an array (if it is - not an array already). This conversion ensures the type for - **destination_field** is consistent across all documents. - **remove** - Deletes the **source_field** field. The **destination_field** - is ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the - ingested document. **source_field** and **destination_field** are ignored - by this operation because _remove_nulls_ operates on the entire ingested - document. Typically, **remove_nulls** is invoked as the last normalization - operation (if it is invoked at all, it can be time-expensive). - :param str source_field: (optional) The source field for the operation. - :param str destination_field: (optional) The destination field for the - operation. - """ - self.operation = operation - self.source_field = source_field - self.destination_field = destination_field - - @classmethod - def from_dict(cls, _dict: Dict) -> 'NormalizationOperation': - """Initialize a NormalizationOperation object from a json dictionary.""" - args = {} - if (operation := _dict.get('operation')) is not None: - args['operation'] = operation - if (source_field := _dict.get('source_field')) is not None: - args['source_field'] = source_field - if (destination_field := _dict.get('destination_field')) is not None: - args['destination_field'] = destination_field - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a NormalizationOperation 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, 'operation') and self.operation is not None: - _dict['operation'] = self.operation - if hasattr(self, 'source_field') and self.source_field is not None: - _dict['source_field'] = self.source_field - if hasattr(self, - 'destination_field') and self.destination_field is not None: - _dict['destination_field'] = self.destination_field - 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 NormalizationOperation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'NormalizationOperation') -> 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: 'NormalizationOperation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class OperationEnum(str, Enum): - """ - Identifies what type of operation to perform. - **copy** - Copies the value of the **source_field** to the **destination_field** - field. If the **destination_field** already exists, then the value of the - **source_field** overwrites the original value of the **destination_field**. - **move** - Renames (moves) the **source_field** to the **destination_field**. If - the **destination_field** already exists, then the value of the **source_field** - overwrites the original value of the **destination_field**. Rename is identical to - copy, except that the **source_field** is removed after the value has been copied - to the **destination_field** (it is the same as a _copy_ followed by a _remove_). - **merge** - Merges the value of the **source_field** with the value of the - **destination_field**. The **destination_field** is converted into an array if it - is not already an array, and the value of the **source_field** is appended to the - array. This operation removes the **source_field** after the merge. If the - **source_field** does not exist in the current document, then the - **destination_field** is still converted into an array (if it is not an array - already). This conversion ensures the type for **destination_field** is consistent - across all documents. - **remove** - Deletes the **source_field** field. The **destination_field** is - ignored for this operation. - **remove_nulls** - Removes all nested null (blank) field values from the ingested - document. **source_field** and **destination_field** are ignored by this operation - because _remove_nulls_ operates on the entire ingested document. Typically, - **remove_nulls** is invoked as the last normalization operation (if it is invoked - at all, it can be time-expensive). - """ - - COPY = 'copy' - MOVE = 'move' - MERGE = 'merge' - REMOVE = 'remove' - REMOVE_NULLS = 'remove_nulls' - - -class Notice: - """ - A notice produced for the collection. - - :param str notice_id: (optional) Identifies the notice. Many notices might have - the same ID. This field exists so that user applications can programmatically - identify a notice and take automatic corrective action. Typical notice IDs - include: `index_failed`, `index_failed_too_many_requests`, - `index_failed_incompatible_field`, `index_failed_cluster_unavailable`, - `ingestion_timeout`, `ingestion_error`, `bad_request`, `internal_error`, - `missing_model`, `unsupported_model`, - `smart_document_understanding_failed_incompatible_field`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_internal_error`, - `smart_document_understanding_failed_warning`, - `smart_document_understanding_page_error`, - `smart_document_understanding_page_warning`. **Note:** This is not a complete - list; other values might be returned. - :param datetime created: (optional) The creation date of the collection in the - format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. - :param str document_id: (optional) Unique identifier of the document. - :param str query_id: (optional) Unique identifier of the query used for - relevance training. - :param str severity: (optional) Severity level of the notice. - :param str step: (optional) Ingestion or training step in which the notice - occurred. Typical step values include: `smartDocumentUnderstanding`, - `ingestion`, `indexing`, `convert`. **Note:** This is not a complete list; other - values might be returned. - :param str description: (optional) The description of the notice. - """ - - def __init__( - self, - *, - notice_id: Optional[str] = None, - created: Optional[datetime] = None, - document_id: Optional[str] = None, - query_id: Optional[str] = None, - severity: Optional[str] = None, - step: Optional[str] = None, - description: Optional[str] = None, - ) -> None: - """ - Initialize a Notice object. - - """ - self.notice_id = notice_id - self.created = created - self.document_id = document_id - self.query_id = query_id - self.severity = severity - self.step = step - self.description = description - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Notice': - """Initialize a Notice object from a json dictionary.""" - args = {} - if (notice_id := _dict.get('notice_id')) is not None: - args['notice_id'] = notice_id - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (query_id := _dict.get('query_id')) is not None: - args['query_id'] = query_id - if (severity := _dict.get('severity')) is not None: - args['severity'] = severity - if (step := _dict.get('step')) is not None: - args['step'] = step - if (description := _dict.get('description')) is not None: - args['description'] = description - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Notice 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, 'notice_id') and getattr(self, - 'notice_id') is not None: - _dict['notice_id'] = getattr(self, 'notice_id') - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'document_id') and getattr(self, - 'document_id') is not None: - _dict['document_id'] = getattr(self, 'document_id') - if hasattr(self, 'query_id') and getattr(self, 'query_id') is not None: - _dict['query_id'] = getattr(self, 'query_id') - if hasattr(self, 'severity') and getattr(self, 'severity') is not None: - _dict['severity'] = getattr(self, 'severity') - if hasattr(self, 'step') and getattr(self, 'step') is not None: - _dict['step'] = getattr(self, 'step') - if hasattr(self, 'description') and getattr(self, - 'description') is not None: - _dict['description'] = getattr(self, 'description') - 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 Notice object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Notice') -> 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: 'Notice') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class SeverityEnum(str, Enum): - """ - Severity level of the notice. - """ - - WARNING = 'warning' - ERROR = 'error' - - -class PdfHeadingDetection: - """ - Object containing heading detection conversion settings for PDF documents. - - :param List[FontSetting] fonts: (optional) Array of font matching - configurations. - """ - - def __init__( - self, - *, - fonts: Optional[List['FontSetting']] = None, - ) -> None: - """ - Initialize a PdfHeadingDetection object. - - :param List[FontSetting] fonts: (optional) Array of font matching - configurations. - """ - self.fonts = fonts - - @classmethod - def from_dict(cls, _dict: Dict) -> 'PdfHeadingDetection': - """Initialize a PdfHeadingDetection object from a json dictionary.""" - args = {} - if (fonts := _dict.get('fonts')) is not None: - args['fonts'] = [FontSetting.from_dict(v) for v in fonts] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a PdfHeadingDetection 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, 'fonts') and self.fonts is not None: - fonts_list = [] - for v in self.fonts: - if isinstance(v, dict): - fonts_list.append(v) - else: - fonts_list.append(v.to_dict()) - _dict['fonts'] = fonts_list - 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 PdfHeadingDetection object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'PdfHeadingDetection') -> 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: 'PdfHeadingDetection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class PdfSettings: - """ - A list of PDF conversion settings. - - :param PdfHeadingDetection heading: (optional) Object containing heading - detection conversion settings for PDF documents. - """ - - def __init__( - self, - *, - heading: Optional['PdfHeadingDetection'] = None, - ) -> None: - """ - Initialize a PdfSettings object. - - :param PdfHeadingDetection heading: (optional) Object containing heading - detection conversion settings for PDF documents. - """ - self.heading = heading - - @classmethod - def from_dict(cls, _dict: Dict) -> 'PdfSettings': - """Initialize a PdfSettings object from a json dictionary.""" - args = {} - if (heading := _dict.get('heading')) is not None: - args['heading'] = PdfHeadingDetection.from_dict(heading) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a PdfSettings 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, 'heading') and self.heading is not None: - if isinstance(self.heading, dict): - _dict['heading'] = self.heading - else: - _dict['heading'] = self.heading.to_dict() - 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 PdfSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'PdfSettings') -> 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: 'PdfSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryAggregation: - """ - An aggregation produced by Discovery to analyze the input provided. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - """ - - def __init__( - self, - type: str, - ) -> None: - """ - Initialize a QueryAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - """ - self.type = type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryAggregation': - """Initialize a QueryAggregation object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryAggregation JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryAggregation 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 QueryAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryAggregation') -> 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: 'QueryAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['histogram'] = 'QueryHistogramAggregation' - mapping['max'] = 'QueryCalculationAggregation' - mapping['min'] = 'QueryCalculationAggregation' - mapping['average'] = 'QueryCalculationAggregation' - mapping['sum'] = 'QueryCalculationAggregation' - mapping['unique_count'] = 'QueryCalculationAggregation' - mapping['term'] = 'QueryTermAggregation' - mapping['filter'] = 'QueryFilterAggregation' - mapping['nested'] = 'QueryNestedAggregation' - mapping['timeslice'] = 'QueryTimesliceAggregation' - mapping['top_hits'] = 'QueryTopHitsAggregation' - disc_value = _dict.get('type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'type\' not found in QueryAggregation JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - - -class QueryHistogramAggregationResult: - """ - Histogram numeric interval result. - - :param int key: The value of the upper bound for the numeric segment. - :param int matching_results: Number of documents with the specified key as the - upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__( - self, - key: int, - matching_results: int, - *, - aggregations: Optional[List['QueryAggregation']] = None, - ) -> None: - """ - Initialize a QueryHistogramAggregationResult object. - - :param int key: The value of the upper bound for the numeric segment. - :param int matching_results: Number of documents with the specified key as - the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - self.key = key - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': - """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" - args = {} - if (key := _dict.get('key')) is not None: - args['key'] = key - else: - raise ValueError( - 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' - ) - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' - ) - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryHistogramAggregationResult 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, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - 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 QueryHistogramAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryHistogramAggregationResult') -> 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: 'QueryHistogramAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNoticesResponse: - """ - Object containing notice query results. - - :param int matching_results: (optional) The number of matching results. - :param List[QueryNoticesResult] results: (optional) Array of document results - that match the query. - :param List[QueryAggregation] aggregations: (optional) Array of aggregation - results that match the query. - :param List[QueryPassages] passages: (optional) Array of passage results that - match the query. - :param int duplicates_removed: (optional) The number of duplicates removed from - this notices query. - """ - - def __init__( - self, - *, - matching_results: Optional[int] = None, - results: Optional[List['QueryNoticesResult']] = None, - aggregations: Optional[List['QueryAggregation']] = None, - passages: Optional[List['QueryPassages']] = None, - duplicates_removed: Optional[int] = None, - ) -> None: - """ - Initialize a QueryNoticesResponse object. - - :param int matching_results: (optional) The number of matching results. - :param List[QueryNoticesResult] results: (optional) Array of document - results that match the query. - :param List[QueryAggregation] aggregations: (optional) Array of aggregation - results that match the query. - :param List[QueryPassages] passages: (optional) Array of passage results - that match the query. - :param int duplicates_removed: (optional) The number of duplicates removed - from this notices query. - """ - self.matching_results = matching_results - self.results = results - self.aggregations = aggregations - self.passages = passages - self.duplicates_removed = duplicates_removed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryNoticesResponse': - """Initialize a QueryNoticesResponse object from a json dictionary.""" - args = {} - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - if (results := _dict.get('results')) is not None: - args['results'] = [QueryNoticesResult.from_dict(v) for v in results] - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - if (passages := _dict.get('passages')) is not None: - args['passages'] = [QueryPassages.from_dict(v) for v in passages] - if (duplicates_removed := _dict.get('duplicates_removed')) is not None: - args['duplicates_removed'] = duplicates_removed - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryNoticesResponse 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, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - if hasattr(self, 'passages') and self.passages is not None: - passages_list = [] - for v in self.passages: - if isinstance(v, dict): - passages_list.append(v) - else: - passages_list.append(v.to_dict()) - _dict['passages'] = passages_list - if hasattr( - self, - 'duplicates_removed') and self.duplicates_removed is not None: - _dict['duplicates_removed'] = self.duplicates_removed - 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 QueryNoticesResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryNoticesResponse') -> 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: 'QueryNoticesResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNoticesResult: - """ - Query result object. - - :param str id: (optional) The unique identifier of the document. - :param dict metadata: (optional) Metadata of the document. - :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - :param int code: (optional) The internal status code returned by the ingestion - subsystem indicating the overall result of ingesting the source document. - :param str filename: (optional) Name of the original source file (if available). - :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file - (formatted as a hexadecimal string). - :param List[Notice] notices: (optional) Array of notices for the document. - """ - - # The set of defined properties for the class - _properties = frozenset([ - 'id', 'metadata', 'collection_id', 'result_metadata', 'code', - 'filename', 'file_type', 'sha1', 'notices' - ]) - - def __init__( - self, - *, - id: Optional[str] = None, - metadata: Optional[dict] = None, - collection_id: Optional[str] = None, - result_metadata: Optional['QueryResultMetadata'] = None, - code: Optional[int] = None, - filename: Optional[str] = None, - file_type: Optional[str] = None, - sha1: Optional[str] = None, - notices: Optional[List['Notice']] = None, - **kwargs, - ) -> None: - """ - Initialize a QueryNoticesResult object. - - :param str id: (optional) The unique identifier of the document. - :param dict metadata: (optional) Metadata of the document. - :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - :param int code: (optional) The internal status code returned by the - ingestion subsystem indicating the overall result of ingesting the source - document. - :param str filename: (optional) Name of the original source file (if - available). - :param str file_type: (optional) The type of the original source file. - :param str sha1: (optional) The SHA-1 hash of the original source file - (formatted as a hexadecimal string). - :param List[Notice] notices: (optional) Array of notices for the document. - :param **kwargs: (optional) Any additional properties. - """ - self.id = id - self.metadata = metadata - self.collection_id = collection_id - self.result_metadata = result_metadata - self.code = code - self.filename = filename - self.file_type = file_type - self.sha1 = sha1 - self.notices = notices - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryNoticesResult': - """Initialize a QueryNoticesResult object from a json dictionary.""" - args = {} - if (id := _dict.get('id')) is not None: - args['id'] = id - if (metadata := _dict.get('metadata')) is not None: - args['metadata'] = metadata - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - if (result_metadata := _dict.get('result_metadata')) is not None: - args['result_metadata'] = QueryResultMetadata.from_dict( - result_metadata) - if (code := _dict.get('code')) is not None: - args['code'] = code - if (filename := _dict.get('filename')) is not None: - args['filename'] = filename - if (file_type := _dict.get('file_type')) is not None: - args['file_type'] = file_type - if (sha1 := _dict.get('sha1')) is not None: - args['sha1'] = sha1 - if (notices := _dict.get('notices')) is not None: - args['notices'] = [Notice.from_dict(v) for v in notices] - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryNoticesResult 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, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - if isinstance(self.result_metadata, dict): - _dict['result_metadata'] = self.result_metadata - else: - _dict['result_metadata'] = self.result_metadata.to_dict() - if hasattr(self, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, 'file_type') and self.file_type is not None: - _dict['file_type'] = self.file_type - if hasattr(self, 'sha1') and self.sha1 is not None: - _dict['sha1'] = self.sha1 - if hasattr(self, 'notices') and self.notices is not None: - notices_list = [] - for v in self.notices: - if isinstance(v, dict): - notices_list.append(v) - else: - notices_list.append(v.to_dict()) - _dict['notices'] = notices_list - for _key in [ - k for k in vars(self).keys() - if k not in QueryNoticesResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of QueryNoticesResult""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in QueryNoticesResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of QueryNoticesResult""" - for _key in [ - k for k in vars(self).keys() - if k not in QueryNoticesResult._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in QueryNoticesResult._properties: - setattr(self, _key, _value) - - def __str__(self) -> str: - """Return a `str` version of this QueryNoticesResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryNoticesResult') -> 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: 'QueryNoticesResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class FileTypeEnum(str, Enum): - """ - The type of the original source file. - """ - - PDF = 'pdf' - HTML = 'html' - WORD = 'word' - JSON = 'json' - - -class QueryPassages: - """ - A passage query result. - - :param str document_id: (optional) The unique identifier of the document from - which the passage has been extracted. - :param float passage_score: (optional) The confidence score of the passages's - analysis. A higher score indicates greater confidence. - :param str passage_text: (optional) The content of the extracted passage. - :param int start_offset: (optional) The position of the first character of the - extracted passage in the originating field. - :param int end_offset: (optional) The position of the last character of the - extracted passage in the originating field. - :param str field: (optional) The label of the field from which the passage has - been extracted. - """ - - def __init__( - self, - *, - document_id: Optional[str] = None, - passage_score: Optional[float] = None, - passage_text: Optional[str] = None, - start_offset: Optional[int] = None, - end_offset: Optional[int] = None, - field: Optional[str] = None, - ) -> None: - """ - Initialize a QueryPassages object. - - :param str document_id: (optional) The unique identifier of the document - from which the passage has been extracted. - :param float passage_score: (optional) The confidence score of the - passages's analysis. A higher score indicates greater confidence. - :param str passage_text: (optional) The content of the extracted passage. - :param int start_offset: (optional) The position of the first character of - the extracted passage in the originating field. - :param int end_offset: (optional) The position of the last character of the - extracted passage in the originating field. - :param str field: (optional) The label of the field from which the passage - has been extracted. - """ - self.document_id = document_id - self.passage_score = passage_score - self.passage_text = passage_text - self.start_offset = start_offset - self.end_offset = end_offset - self.field = field - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryPassages': - """Initialize a QueryPassages object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (passage_score := _dict.get('passage_score')) is not None: - args['passage_score'] = passage_score - if (passage_text := _dict.get('passage_text')) is not None: - args['passage_text'] = passage_text - if (start_offset := _dict.get('start_offset')) is not None: - args['start_offset'] = start_offset - if (end_offset := _dict.get('end_offset')) is not None: - args['end_offset'] = end_offset - if (field := _dict.get('field')) is not None: - args['field'] = field - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryPassages 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, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'passage_score') and self.passage_score is not None: - _dict['passage_score'] = self.passage_score - if hasattr(self, 'passage_text') and self.passage_text is not None: - _dict['passage_text'] = self.passage_text - if hasattr(self, 'start_offset') and self.start_offset is not None: - _dict['start_offset'] = self.start_offset - if hasattr(self, 'end_offset') and self.end_offset is not None: - _dict['end_offset'] = self.end_offset - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - 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 QueryPassages object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryPassages') -> 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: 'QueryPassages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryResponse: - """ - A response containing the documents and aggregations for the query. - - :param int matching_results: (optional) The number of matching results for the - query. - :param List[QueryResult] results: (optional) Array of document results for the - query. - :param List[QueryAggregation] aggregations: (optional) Array of aggregation - results for the query. - :param List[QueryPassages] passages: (optional) Array of passage results for the - query. - :param int duplicates_removed: (optional) The number of duplicate results - removed. - :param str session_token: (optional) The session token for this query. The - session token can be used to add events associated with this query to the query - and event log. - **Important:** Session tokens are case sensitive. - :param RetrievalDetails retrieval_details: (optional) An object contain - retrieval type information. - :param str suggested_query: (optional) The suggestions for a misspelled natural - language query. - """ - - def __init__( - self, - *, - matching_results: Optional[int] = None, - results: Optional[List['QueryResult']] = None, - aggregations: Optional[List['QueryAggregation']] = None, - passages: Optional[List['QueryPassages']] = None, - duplicates_removed: Optional[int] = None, - session_token: Optional[str] = None, - retrieval_details: Optional['RetrievalDetails'] = None, - suggested_query: Optional[str] = None, - ) -> None: - """ - Initialize a QueryResponse object. - - :param int matching_results: (optional) The number of matching results for - the query. - :param List[QueryResult] results: (optional) Array of document results for - the query. - :param List[QueryAggregation] aggregations: (optional) Array of aggregation - results for the query. - :param List[QueryPassages] passages: (optional) Array of passage results - for the query. - :param int duplicates_removed: (optional) The number of duplicate results - removed. - :param str session_token: (optional) The session token for this query. The - session token can be used to add events associated with this query to the - query and event log. - **Important:** Session tokens are case sensitive. - :param RetrievalDetails retrieval_details: (optional) An object contain - retrieval type information. - :param str suggested_query: (optional) The suggestions for a misspelled - natural language query. - """ - self.matching_results = matching_results - self.results = results - self.aggregations = aggregations - self.passages = passages - self.duplicates_removed = duplicates_removed - self.session_token = session_token - self.retrieval_details = retrieval_details - self.suggested_query = suggested_query - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryResponse': - """Initialize a QueryResponse object from a json dictionary.""" - args = {} - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - if (results := _dict.get('results')) is not None: - args['results'] = [QueryResult.from_dict(v) for v in results] - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - if (passages := _dict.get('passages')) is not None: - args['passages'] = [QueryPassages.from_dict(v) for v in passages] - if (duplicates_removed := _dict.get('duplicates_removed')) is not None: - args['duplicates_removed'] = duplicates_removed - if (session_token := _dict.get('session_token')) is not None: - args['session_token'] = session_token - if (retrieval_details := _dict.get('retrieval_details')) is not None: - args['retrieval_details'] = RetrievalDetails.from_dict( - retrieval_details) - if (suggested_query := _dict.get('suggested_query')) is not None: - args['suggested_query'] = suggested_query - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryResponse 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, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - if hasattr(self, 'passages') and self.passages is not None: - passages_list = [] - for v in self.passages: - if isinstance(v, dict): - passages_list.append(v) - else: - passages_list.append(v.to_dict()) - _dict['passages'] = passages_list - if hasattr( - self, - 'duplicates_removed') and self.duplicates_removed is not None: - _dict['duplicates_removed'] = self.duplicates_removed - if hasattr(self, 'session_token') and self.session_token is not None: - _dict['session_token'] = self.session_token - if hasattr(self, - 'retrieval_details') and self.retrieval_details is not None: - if isinstance(self.retrieval_details, dict): - _dict['retrieval_details'] = self.retrieval_details - else: - _dict['retrieval_details'] = self.retrieval_details.to_dict() - if hasattr(self, - 'suggested_query') and self.suggested_query is not None: - _dict['suggested_query'] = self.suggested_query - 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 QueryResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryResponse') -> 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: 'QueryResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryResult: - """ - Query result object. - - :param str id: (optional) The unique identifier of the document. - :param dict metadata: (optional) Metadata of the document. - :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - """ - - # The set of defined properties for the class - _properties = frozenset( - ['id', 'metadata', 'collection_id', 'result_metadata']) - - def __init__( - self, - *, - id: Optional[str] = None, - metadata: Optional[dict] = None, - collection_id: Optional[str] = None, - result_metadata: Optional['QueryResultMetadata'] = None, - **kwargs, - ) -> None: - """ - Initialize a QueryResult object. - - :param str id: (optional) The unique identifier of the document. - :param dict metadata: (optional) Metadata of the document. - :param str collection_id: (optional) The collection ID of the collection - containing the document for this result. - :param QueryResultMetadata result_metadata: (optional) Metadata of a query - result. - :param **kwargs: (optional) Any additional properties. - """ - self.id = id - self.metadata = metadata - self.collection_id = collection_id - self.result_metadata = result_metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryResult': - """Initialize a QueryResult object from a json dictionary.""" - args = {} - if (id := _dict.get('id')) is not None: - args['id'] = id - if (metadata := _dict.get('metadata')) is not None: - args['metadata'] = metadata - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - if (result_metadata := _dict.get('result_metadata')) is not None: - args['result_metadata'] = QueryResultMetadata.from_dict( - result_metadata) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryResult 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, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - if isinstance(self.result_metadata, dict): - _dict['result_metadata'] = self.result_metadata - else: - _dict['result_metadata'] = self.result_metadata.to_dict() - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() - - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of QueryResult""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of QueryResult""" - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in QueryResult._properties: - setattr(self, _key, _value) - - def __str__(self) -> str: - """Return a `str` version of this QueryResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryResult') -> 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: 'QueryResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryResultMetadata: - """ - Metadata of a query result. - - :param float score: An unbounded measure of the relevance of a particular - result, dependent on the query and matching document. A higher score indicates a - greater match to the query parameters. - :param float confidence: (optional) The confidence score for the given result. - Calculated based on how relevant the result is estimated to be. confidence can - range from `0.0` to `1.0`. The higher the number, the more relevant the - document. The `confidence` value for a result was calculated using the model - specified in the `document_retrieval_strategy` field of the result set. - """ - - def __init__( - self, - score: float, - *, - confidence: Optional[float] = None, - ) -> None: - """ - Initialize a QueryResultMetadata object. - - :param float score: An unbounded measure of the relevance of a particular - result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. - :param float confidence: (optional) The confidence score for the given - result. Calculated based on how relevant the result is estimated to be. - confidence can range from `0.0` to `1.0`. The higher the number, the more - relevant the document. The `confidence` value for a result was calculated - using the model specified in the `document_retrieval_strategy` field of the - result set. - """ - self.score = score - self.confidence = confidence - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryResultMetadata': - """Initialize a QueryResultMetadata object from a json dictionary.""" - args = {} - if (score := _dict.get('score')) is not None: - args['score'] = score - else: - raise ValueError( - 'Required property \'score\' not present in QueryResultMetadata JSON' - ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryResultMetadata 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, 'score') and self.score is not None: - _dict['score'] = self.score - 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 QueryResultMetadata object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryResultMetadata') -> 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: 'QueryResultMetadata') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTermAggregationResult: - """ - Top value result for the term aggregation. - - :param str key: Value of the field with a non-zero frequency in the document - set. - :param int matching_results: Number of documents that contain the 'key'. - :param float relevancy: (optional) The relevancy for this term. - :param int total_matching_documents: (optional) The number of documents which - have the term as the value of specified field in the whole set of documents in - this collection. Returned only when the `relevancy` parameter is set to `true`. - :param int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned only - when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__( - self, - key: str, - matching_results: int, - *, - relevancy: Optional[float] = None, - total_matching_documents: Optional[int] = None, - estimated_matching_documents: Optional[int] = None, - aggregations: Optional[List['QueryAggregation']] = None, - ) -> None: - """ - Initialize a QueryTermAggregationResult object. - - :param str key: Value of the field with a non-zero frequency in the - document set. - :param int matching_results: Number of documents that contain the 'key'. - :param float relevancy: (optional) The relevancy for this term. - :param int total_matching_documents: (optional) The number of documents - which have the term as the value of specified field in the whole set of - documents in this collection. Returned only when the `relevancy` parameter - is set to `true`. - :param int estimated_matching_documents: (optional) The estimated number of - documents which would match the query and also meet the condition. Returned - only when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - self.key = key - self.matching_results = matching_results - self.relevancy = relevancy - self.total_matching_documents = total_matching_documents - self.estimated_matching_documents = estimated_matching_documents - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': - """Initialize a QueryTermAggregationResult object from a json dictionary.""" - args = {} - if (key := _dict.get('key')) is not None: - args['key'] = key - else: - raise ValueError( - 'Required property \'key\' not present in QueryTermAggregationResult JSON' - ) - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' - ) - if (relevancy := _dict.get('relevancy')) is not None: - args['relevancy'] = relevancy - if (total_matching_documents := - _dict.get('total_matching_documents')) is not None: - args['total_matching_documents'] = total_matching_documents - if (estimated_matching_documents := - _dict.get('estimated_matching_documents')) is not None: - args['estimated_matching_documents'] = estimated_matching_documents - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTermAggregationResult 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, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'relevancy') and self.relevancy is not None: - _dict['relevancy'] = self.relevancy - if hasattr(self, 'total_matching_documents' - ) and self.total_matching_documents is not None: - _dict['total_matching_documents'] = self.total_matching_documents - if hasattr(self, 'estimated_matching_documents' - ) and self.estimated_matching_documents is not None: - _dict[ - 'estimated_matching_documents'] = self.estimated_matching_documents - if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - 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 QueryTermAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTermAggregationResult') -> 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: 'QueryTermAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTimesliceAggregationResult: - """ - A timeslice interval segment. - - :param str key_as_string: String date value of the upper bound for the timeslice - interval in ISO-8601 format. - :param int key: Numeric date value of the upper bound for the timeslice interval - in UNIX milliseconds since epoch. - :param int matching_results: Number of documents with the specified key as the - upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__( - self, - key_as_string: str, - key: int, - matching_results: int, - *, - aggregations: Optional[List['QueryAggregation']] = None, - ) -> None: - """ - Initialize a QueryTimesliceAggregationResult object. - - :param str key_as_string: String date value of the upper bound for the - timeslice interval in ISO-8601 format. - :param int key: Numeric date value of the upper bound for the timeslice - interval in UNIX milliseconds since epoch. - :param int matching_results: Number of documents with the specified key as - the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - self.key_as_string = key_as_string - self.key = key - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': - """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" - args = {} - if (key_as_string := _dict.get('key_as_string')) is not None: - args['key_as_string'] = key_as_string - else: - raise ValueError( - 'Required property \'key_as_string\' not present in QueryTimesliceAggregationResult JSON' - ) - if (key := _dict.get('key')) is not None: - args['key'] = key - else: - raise ValueError( - 'Required property \'key\' not present in QueryTimesliceAggregationResult JSON' - ) - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' - ) - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTimesliceAggregationResult 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, 'key_as_string') and self.key_as_string is not None: - _dict['key_as_string'] = self.key_as_string - if hasattr(self, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - 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 QueryTimesliceAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTimesliceAggregationResult') -> 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: 'QueryTimesliceAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTopHitsAggregationResult: - """ - A query response that contains the matching documents for the preceding aggregations. - - :param int matching_results: Number of matching results. - :param List[dict] hits: (optional) An array of the document results. - """ - - def __init__( - self, - matching_results: int, - *, - hits: Optional[List[dict]] = None, - ) -> None: - """ - Initialize a QueryTopHitsAggregationResult object. - - :param int matching_results: Number of matching results. - :param List[dict] hits: (optional) An array of the document results. - """ - self.matching_results = matching_results - self.hits = hits - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': - """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" - args = {} - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryTopHitsAggregationResult JSON' - ) - if (hits := _dict.get('hits')) is not None: - args['hits'] = hits - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTopHitsAggregationResult 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, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = self.hits - 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 QueryTopHitsAggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTopHitsAggregationResult') -> 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: 'QueryTopHitsAggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class RetrievalDetails: - """ - An object contain retrieval type information. - - :param str document_retrieval_strategy: (optional) Indentifies the document - retrieval strategy used for this query. `relevancy_training` indicates that the - results were returned using a relevancy trained model. - `continuous_relevancy_training` indicates that the results were returned using - the continuous relevancy training model created by result feedback analysis. - `untrained` means the results were returned using the standard untrained model. - **Note**: In the event of trained collections being queried, but the trained - model is not used to return results, the **document_retrieval_strategy** will be - listed as `untrained`. - """ - - def __init__( - self, - *, - document_retrieval_strategy: Optional[str] = None, - ) -> None: - """ - Initialize a RetrievalDetails object. - - :param str document_retrieval_strategy: (optional) Indentifies the document - retrieval strategy used for this query. `relevancy_training` indicates that - the results were returned using a relevancy trained model. - `continuous_relevancy_training` indicates that the results were returned - using the continuous relevancy training model created by result feedback - analysis. `untrained` means the results were returned using the standard - untrained model. - **Note**: In the event of trained collections being queried, but the - trained model is not used to return results, the - **document_retrieval_strategy** will be listed as `untrained`. - """ - self.document_retrieval_strategy = document_retrieval_strategy - - @classmethod - def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': - """Initialize a RetrievalDetails object from a json dictionary.""" - args = {} - if (document_retrieval_strategy := - _dict.get('document_retrieval_strategy')) is not None: - args['document_retrieval_strategy'] = document_retrieval_strategy - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a RetrievalDetails 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, 'document_retrieval_strategy' - ) and self.document_retrieval_strategy is not None: - _dict[ - 'document_retrieval_strategy'] = self.document_retrieval_strategy - 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 RetrievalDetails object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'RetrievalDetails') -> 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: 'RetrievalDetails') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class DocumentRetrievalStrategyEnum(str, Enum): - """ - Indentifies the document retrieval strategy used for this query. - `relevancy_training` indicates that the results were returned using a relevancy - trained model. `continuous_relevancy_training` indicates that the results were - returned using the continuous relevancy training model created by result feedback - analysis. `untrained` means the results were returned using the standard untrained - model. - **Note**: In the event of trained collections being queried, but the trained - model is not used to return results, the **document_retrieval_strategy** will be - listed as `untrained`. - """ - - UNTRAINED = 'untrained' - RELEVANCY_TRAINING = 'relevancy_training' - CONTINUOUS_RELEVANCY_TRAINING = 'continuous_relevancy_training' - - -class SduStatus: - """ - Object containing smart document understanding information for this collection. - - :param bool enabled: (optional) When `true`, smart document understanding - conversion is enabled for this collection. All collections created with a - version date after `2019-04-30` have smart document understanding enabled. If - `false`, documents added to the collection are converted using the - **conversion** settings specified in the configuration associated with the - collection. - :param int total_annotated_pages: (optional) The total number of pages annotated - using smart document understanding in this collection. - :param int total_pages: (optional) The current number of pages that can be used - for training smart document understanding. The `total_pages` number is - calculated as the total number of pages identified from the documents listed in - the **total_documents** field. - :param int total_documents: (optional) The total number of documents in this - collection that can be used to train smart document understanding. For **lite** - plan collections, the maximum is the first 20 uploaded documents (not including - HTML or JSON documents). For other plans, the maximum is the first 40 uploaded - documents (not including HTML or JSON documents). When the maximum is reached, - additional documents uploaded to the collection are not considered for training - smart document understanding. - :param SduStatusCustomFields custom_fields: (optional) Information about custom - smart document understanding fields that exist in this collection. - """ - - def __init__( - self, - *, - enabled: Optional[bool] = None, - total_annotated_pages: Optional[int] = None, - total_pages: Optional[int] = None, - total_documents: Optional[int] = None, - custom_fields: Optional['SduStatusCustomFields'] = None, - ) -> None: - """ - Initialize a SduStatus object. - - :param bool enabled: (optional) When `true`, smart document understanding - conversion is enabled for this collection. All collections created with a - version date after `2019-04-30` have smart document understanding enabled. - If `false`, documents added to the collection are converted using the - **conversion** settings specified in the configuration associated with the - collection. - :param int total_annotated_pages: (optional) The total number of pages - annotated using smart document understanding in this collection. - :param int total_pages: (optional) The current number of pages that can be - used for training smart document understanding. The `total_pages` number is - calculated as the total number of pages identified from the documents - listed in the **total_documents** field. - :param int total_documents: (optional) The total number of documents in - this collection that can be used to train smart document understanding. For - **lite** plan collections, the maximum is the first 20 uploaded documents - (not including HTML or JSON documents). For other plans, the maximum is the - first 40 uploaded documents (not including HTML or JSON documents). When - the maximum is reached, additional documents uploaded to the collection are - not considered for training smart document understanding. - :param SduStatusCustomFields custom_fields: (optional) Information about - custom smart document understanding fields that exist in this collection. - """ - self.enabled = enabled - self.total_annotated_pages = total_annotated_pages - self.total_pages = total_pages - self.total_documents = total_documents - self.custom_fields = custom_fields - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SduStatus': - """Initialize a SduStatus object from a json dictionary.""" - args = {} - if (enabled := _dict.get('enabled')) is not None: - args['enabled'] = enabled - if (total_annotated_pages := - _dict.get('total_annotated_pages')) is not None: - args['total_annotated_pages'] = total_annotated_pages - if (total_pages := _dict.get('total_pages')) is not None: - args['total_pages'] = total_pages - if (total_documents := _dict.get('total_documents')) is not None: - args['total_documents'] = total_documents - if (custom_fields := _dict.get('custom_fields')) is not None: - args['custom_fields'] = SduStatusCustomFields.from_dict( - custom_fields) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SduStatus 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 - if hasattr(self, 'total_annotated_pages' - ) and self.total_annotated_pages is not None: - _dict['total_annotated_pages'] = self.total_annotated_pages - if hasattr(self, 'total_pages') and self.total_pages is not None: - _dict['total_pages'] = self.total_pages - if hasattr(self, - 'total_documents') and self.total_documents is not None: - _dict['total_documents'] = self.total_documents - if hasattr(self, 'custom_fields') and self.custom_fields is not None: - if isinstance(self.custom_fields, dict): - _dict['custom_fields'] = self.custom_fields - else: - _dict['custom_fields'] = self.custom_fields.to_dict() - 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 SduStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SduStatus') -> 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: 'SduStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SduStatusCustomFields: - """ - Information about custom smart document understanding fields that exist in this - collection. - - :param int defined: (optional) The number of custom fields defined for this - collection. - :param int maximum_allowed: (optional) The maximum number of custom fields that - are allowed in this collection. - """ - - def __init__( - self, - *, - defined: Optional[int] = None, - maximum_allowed: Optional[int] = None, - ) -> None: - """ - Initialize a SduStatusCustomFields object. - - :param int defined: (optional) The number of custom fields defined for this - collection. - :param int maximum_allowed: (optional) The maximum number of custom fields - that are allowed in this collection. - """ - self.defined = defined - self.maximum_allowed = maximum_allowed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SduStatusCustomFields': - """Initialize a SduStatusCustomFields object from a json dictionary.""" - args = {} - if (defined := _dict.get('defined')) is not None: - args['defined'] = defined - if (maximum_allowed := _dict.get('maximum_allowed')) is not None: - args['maximum_allowed'] = maximum_allowed - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SduStatusCustomFields 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, 'defined') and self.defined is not None: - _dict['defined'] = self.defined - if hasattr(self, - 'maximum_allowed') and self.maximum_allowed is not None: - _dict['maximum_allowed'] = self.maximum_allowed - 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 SduStatusCustomFields object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SduStatusCustomFields') -> 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: 'SduStatusCustomFields') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SearchStatus: - """ - Information about the Continuous Relevancy Training for this environment. - - :param str scope: (optional) Current scope of the training. Always returned as - `environment`. - :param str status: (optional) The current status of Continuous Relevancy - Training for this environment. - :param str status_description: (optional) Long description of the current - Continuous Relevancy Training status. - :param date last_trained: (optional) The date stamp of the most recent completed - training for this environment. - """ - - def __init__( - self, - *, - scope: Optional[str] = None, - status: Optional[str] = None, - status_description: Optional[str] = None, - last_trained: Optional[date] = None, - ) -> None: - """ - Initialize a SearchStatus object. - - :param str scope: (optional) Current scope of the training. Always returned - as `environment`. - :param str status: (optional) The current status of Continuous Relevancy - Training for this environment. - :param str status_description: (optional) Long description of the current - Continuous Relevancy Training status. - :param date last_trained: (optional) The date stamp of the most recent - completed training for this environment. - """ - self.scope = scope - self.status = status - self.status_description = status_description - self.last_trained = last_trained - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchStatus': - """Initialize a SearchStatus object from a json dictionary.""" - args = {} - if (scope := _dict.get('scope')) is not None: - args['scope'] = scope - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (last_trained := _dict.get('last_trained')) is not None: - args['last_trained'] = string_to_date(last_trained) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SearchStatus 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, 'scope') and self.scope is not None: - _dict['scope'] = self.scope - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr( - self, - 'status_description') and self.status_description is not None: - _dict['status_description'] = self.status_description - if hasattr(self, 'last_trained') and self.last_trained is not None: - _dict['last_trained'] = date_to_string(self.last_trained) - 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 SearchStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SearchStatus') -> 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: 'SearchStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The current status of Continuous Relevancy Training for this environment. - """ - - NO_DATA = 'NO_DATA' - INSUFFICENT_DATA = 'INSUFFICENT_DATA' - TRAINING = 'TRAINING' - TRAINED = 'TRAINED' - NOT_APPLICABLE = 'NOT_APPLICABLE' - - -class SegmentSettings: - """ - A list of Document Segmentation settings. - - :param bool enabled: (optional) Enables/disables the Document Segmentation - feature. - :param List[str] selector_tags: (optional) Defines the heading level that splits - into document segments. Valid values are h1, h2, h3, h4, h5, h6. The content of - the header field that the segmentation splits at is used as the **title** field - for that segmented result. Only valid if used with a collection that has - **enabled** set to `false` in the **smart_document_understanding** object. - :param List[str] annotated_fields: (optional) Defines the annotated smart - document understanding fields that the document is split on. The content of the - annotated field that the segmentation splits at is used as the **title** field - for that segmented result. For example, if the field `sub-title` is specified, - when a document is uploaded each time the smart document understanding - conversion encounters a field of type `sub-title` the document is split at that - point and the content of the field used as the title of the remaining content. - This split is performed for all instances of the listed fields in the uploaded - document. Only valid if used with a collection that has **enabled** set to - `true` in the **smart_document_understanding** object. - """ - - def __init__( - self, - *, - enabled: Optional[bool] = None, - selector_tags: Optional[List[str]] = None, - annotated_fields: Optional[List[str]] = None, - ) -> None: - """ - Initialize a SegmentSettings object. - - :param bool enabled: (optional) Enables/disables the Document Segmentation - feature. - :param List[str] selector_tags: (optional) Defines the heading level that - splits into document segments. Valid values are h1, h2, h3, h4, h5, h6. The - content of the header field that the segmentation splits at is used as the - **title** field for that segmented result. Only valid if used with a - collection that has **enabled** set to `false` in the - **smart_document_understanding** object. - :param List[str] annotated_fields: (optional) Defines the annotated smart - document understanding fields that the document is split on. The content of - the annotated field that the segmentation splits at is used as the - **title** field for that segmented result. For example, if the field - `sub-title` is specified, when a document is uploaded each time the smart - document understanding conversion encounters a field of type `sub-title` - the document is split at that point and the content of the field used as - the title of the remaining content. This split is performed for all - instances of the listed fields in the uploaded document. Only valid if used - with a collection that has **enabled** set to `true` in the - **smart_document_understanding** object. - """ - self.enabled = enabled - self.selector_tags = selector_tags - self.annotated_fields = annotated_fields - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SegmentSettings': - """Initialize a SegmentSettings object from a json dictionary.""" - args = {} - if (enabled := _dict.get('enabled')) is not None: - args['enabled'] = enabled - if (selector_tags := _dict.get('selector_tags')) is not None: - args['selector_tags'] = selector_tags - if (annotated_fields := _dict.get('annotated_fields')) is not None: - args['annotated_fields'] = annotated_fields - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SegmentSettings 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 - if hasattr(self, 'selector_tags') and self.selector_tags is not None: - _dict['selector_tags'] = self.selector_tags - if hasattr(self, - 'annotated_fields') and self.annotated_fields is not None: - _dict['annotated_fields'] = self.annotated_fields - 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 SegmentSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SegmentSettings') -> 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: 'SegmentSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Source: - """ - Object containing source parameters for the configuration. - - :param str type: (optional) The type of source to connect to. - - `box` indicates the configuration is to connect an instance of Enterprise - Box. - - `salesforce` indicates the configuration is to connect to Salesforce. - - `sharepoint` indicates the configuration is to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the configuration is to perform a web page crawl. - - `cloud_object_storage` indicates the configuration is to connect to a cloud - object store. - :param str credential_id: (optional) The **credential_id** of the credentials to - use to connect to the source. Credentials are defined using the **credentials** - method. The **source_type** of the credentials used must match the **type** - field specified in this object. - :param SourceSchedule schedule: (optional) Object containing the schedule - information for the source. - :param SourceOptions options: (optional) The **options** object defines which - items to crawl from the source system. - """ - - def __init__( - self, - *, - type: Optional[str] = None, - credential_id: Optional[str] = None, - schedule: Optional['SourceSchedule'] = None, - options: Optional['SourceOptions'] = None, - ) -> None: - """ - Initialize a Source object. - - :param str type: (optional) The type of source to connect to. - - `box` indicates the configuration is to connect an instance of - Enterprise Box. - - `salesforce` indicates the configuration is to connect to Salesforce. - - `sharepoint` indicates the configuration is to connect to Microsoft - SharePoint Online. - - `web_crawl` indicates the configuration is to perform a web page crawl. - - `cloud_object_storage` indicates the configuration is to connect to a - cloud object store. - :param str credential_id: (optional) The **credential_id** of the - credentials to use to connect to the source. Credentials are defined using - the **credentials** method. The **source_type** of the credentials used - must match the **type** field specified in this object. - :param SourceSchedule schedule: (optional) Object containing the schedule - information for the source. - :param SourceOptions options: (optional) The **options** object defines - which items to crawl from the source system. - """ - self.type = type - self.credential_id = credential_id - self.schedule = schedule - self.options = options - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Source': - """Initialize a Source object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (credential_id := _dict.get('credential_id')) is not None: - args['credential_id'] = credential_id - if (schedule := _dict.get('schedule')) is not None: - args['schedule'] = SourceSchedule.from_dict(schedule) - if (options := _dict.get('options')) is not None: - args['options'] = SourceOptions.from_dict(options) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Source 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 - if hasattr(self, 'credential_id') and self.credential_id is not None: - _dict['credential_id'] = self.credential_id - if hasattr(self, 'schedule') and self.schedule is not None: - if isinstance(self.schedule, dict): - _dict['schedule'] = self.schedule - else: - _dict['schedule'] = self.schedule.to_dict() - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options - else: - _dict['options'] = self.options.to_dict() - 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 Source object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Source') -> 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: 'Source') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The type of source to connect to. - - `box` indicates the configuration is to connect an instance of Enterprise Box. - - `salesforce` indicates the configuration is to connect to Salesforce. - - `sharepoint` indicates the configuration is to connect to Microsoft SharePoint - Online. - - `web_crawl` indicates the configuration is to perform a web page crawl. - - `cloud_object_storage` indicates the configuration is to connect to a cloud - object store. - """ - - BOX = 'box' - SALESFORCE = 'salesforce' - SHAREPOINT = 'sharepoint' - WEB_CRAWL = 'web_crawl' - CLOUD_OBJECT_STORAGE = 'cloud_object_storage' - - -class SourceOptions: - """ - The **options** object defines which items to crawl from the source system. - - :param List[SourceOptionsFolder] folders: (optional) Array of folders to crawl - from the Box source. Only valid, and required, when the **type** field of the - **source** object is set to `box`. - :param List[SourceOptionsObject] objects: (optional) Array of Salesforce - document object types to crawl from the Salesforce source. Only valid, and - required, when the **type** field of the **source** object is set to - `salesforce`. - :param List[SourceOptionsSiteColl] site_collections: (optional) Array of - Microsoft SharePointoint Online site collections to crawl from the SharePoint - source. Only valid and required when the **type** field of the **source** object - is set to `sharepoint`. - :param List[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs to - begin crawling the web from. Only valid and required when the **type** field of - the **source** object is set to `web_crawl`. - :param List[SourceOptionsBuckets] buckets: (optional) Array of cloud object - store buckets to begin crawling. Only valid and required when the **type** field - of the **source** object is set to `cloud_object_store`, and the - **crawl_all_buckets** field is `false` or not specified. - :param bool crawl_all_buckets: (optional) When `true`, all buckets in the - specified cloud object store are crawled. If set to `true`, the **buckets** - array must not be specified. - """ - - def __init__( - self, - *, - folders: Optional[List['SourceOptionsFolder']] = None, - objects: Optional[List['SourceOptionsObject']] = None, - site_collections: Optional[List['SourceOptionsSiteColl']] = None, - urls: Optional[List['SourceOptionsWebCrawl']] = None, - buckets: Optional[List['SourceOptionsBuckets']] = None, - crawl_all_buckets: Optional[bool] = None, - ) -> None: - """ - Initialize a SourceOptions object. - - :param List[SourceOptionsFolder] folders: (optional) Array of folders to - crawl from the Box source. Only valid, and required, when the **type** - field of the **source** object is set to `box`. - :param List[SourceOptionsObject] objects: (optional) Array of Salesforce - document object types to crawl from the Salesforce source. Only valid, and - required, when the **type** field of the **source** object is set to - `salesforce`. - :param List[SourceOptionsSiteColl] site_collections: (optional) Array of - Microsoft SharePointoint Online site collections to crawl from the - SharePoint source. Only valid and required when the **type** field of the - **source** object is set to `sharepoint`. - :param List[SourceOptionsWebCrawl] urls: (optional) Array of Web page URLs - to begin crawling the web from. Only valid and required when the **type** - field of the **source** object is set to `web_crawl`. - :param List[SourceOptionsBuckets] buckets: (optional) Array of cloud object - store buckets to begin crawling. Only valid and required when the **type** - field of the **source** object is set to `cloud_object_store`, and the - **crawl_all_buckets** field is `false` or not specified. - :param bool crawl_all_buckets: (optional) When `true`, all buckets in the - specified cloud object store are crawled. If set to `true`, the **buckets** - array must not be specified. - """ - self.folders = folders - self.objects = objects - self.site_collections = site_collections - self.urls = urls - self.buckets = buckets - self.crawl_all_buckets = crawl_all_buckets - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptions': - """Initialize a SourceOptions object from a json dictionary.""" - args = {} - if (folders := _dict.get('folders')) is not None: - args['folders'] = [ - SourceOptionsFolder.from_dict(v) for v in folders - ] - if (objects := _dict.get('objects')) is not None: - args['objects'] = [ - SourceOptionsObject.from_dict(v) for v in objects - ] - if (site_collections := _dict.get('site_collections')) is not None: - args['site_collections'] = [ - SourceOptionsSiteColl.from_dict(v) for v in site_collections - ] - if (urls := _dict.get('urls')) is not None: - args['urls'] = [SourceOptionsWebCrawl.from_dict(v) for v in urls] - if (buckets := _dict.get('buckets')) is not None: - args['buckets'] = [ - SourceOptionsBuckets.from_dict(v) for v in buckets - ] - if (crawl_all_buckets := _dict.get('crawl_all_buckets')) is not None: - args['crawl_all_buckets'] = crawl_all_buckets - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptions 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, 'folders') and self.folders is not None: - folders_list = [] - for v in self.folders: - if isinstance(v, dict): - folders_list.append(v) - else: - folders_list.append(v.to_dict()) - _dict['folders'] = folders_list - if hasattr(self, 'objects') and self.objects is not None: - objects_list = [] - for v in self.objects: - if isinstance(v, dict): - objects_list.append(v) - else: - objects_list.append(v.to_dict()) - _dict['objects'] = objects_list - if hasattr(self, - 'site_collections') and self.site_collections is not None: - site_collections_list = [] - for v in self.site_collections: - if isinstance(v, dict): - site_collections_list.append(v) - else: - site_collections_list.append(v.to_dict()) - _dict['site_collections'] = site_collections_list - if hasattr(self, 'urls') and self.urls is not None: - urls_list = [] - for v in self.urls: - if isinstance(v, dict): - urls_list.append(v) - else: - urls_list.append(v.to_dict()) - _dict['urls'] = urls_list - if hasattr(self, 'buckets') and self.buckets is not None: - buckets_list = [] - for v in self.buckets: - if isinstance(v, dict): - buckets_list.append(v) - else: - buckets_list.append(v.to_dict()) - _dict['buckets'] = buckets_list - if hasattr(self, - 'crawl_all_buckets') and self.crawl_all_buckets is not None: - _dict['crawl_all_buckets'] = self.crawl_all_buckets - 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 SourceOptions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptions') -> 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: 'SourceOptions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsBuckets: - """ - Object defining a cloud object store bucket to crawl. - - :param str name: The name of the cloud object store bucket to crawl. - :param int limit: (optional) The number of documents to crawl from this cloud - object store bucket. If not specified, all documents in the bucket are crawled. - """ - - def __init__( - self, - name: str, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a SourceOptionsBuckets object. - - :param str name: The name of the cloud object store bucket to crawl. - :param int limit: (optional) The number of documents to crawl from this - cloud object store bucket. If not specified, all documents in the bucket - are crawled. - """ - self.name = name - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsBuckets': - """Initialize a SourceOptionsBuckets object from a json dictionary.""" - args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - else: - raise ValueError( - 'Required property \'name\' not present in SourceOptionsBuckets JSON' - ) - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptionsBuckets 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 SourceOptionsBuckets object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptionsBuckets') -> 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: 'SourceOptionsBuckets') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsFolder: - """ - Object that defines a box folder to crawl with this configuration. - - :param str owner_user_id: The Box user ID of the user who owns the folder to - crawl. - :param str folder_id: The Box folder ID of the folder to crawl. - :param int limit: (optional) The maximum number of documents to crawl for this - folder. By default, all documents in the folder are crawled. - """ - - def __init__( - self, - owner_user_id: str, - folder_id: str, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a SourceOptionsFolder object. - - :param str owner_user_id: The Box user ID of the user who owns the folder - to crawl. - :param str folder_id: The Box folder ID of the folder to crawl. - :param int limit: (optional) The maximum number of documents to crawl for - this folder. By default, all documents in the folder are crawled. - """ - self.owner_user_id = owner_user_id - self.folder_id = folder_id - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsFolder': - """Initialize a SourceOptionsFolder object from a json dictionary.""" - args = {} - if (owner_user_id := _dict.get('owner_user_id')) is not None: - args['owner_user_id'] = owner_user_id - else: - raise ValueError( - 'Required property \'owner_user_id\' not present in SourceOptionsFolder JSON' - ) - if (folder_id := _dict.get('folder_id')) is not None: - args['folder_id'] = folder_id - else: - raise ValueError( - 'Required property \'folder_id\' not present in SourceOptionsFolder JSON' - ) - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptionsFolder 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, 'owner_user_id') and self.owner_user_id is not None: - _dict['owner_user_id'] = self.owner_user_id - if hasattr(self, 'folder_id') and self.folder_id is not None: - _dict['folder_id'] = self.folder_id - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 SourceOptionsFolder object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptionsFolder') -> 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: 'SourceOptionsFolder') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsObject: - """ - Object that defines a Salesforce document object type crawl with this configuration. - - :param str name: The name of the Salesforce document object to crawl. For - example, `case`. - :param int limit: (optional) The maximum number of documents to crawl for this - document object. By default, all documents in the document object are crawled. - """ - - def __init__( - self, - name: str, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a SourceOptionsObject object. - - :param str name: The name of the Salesforce document object to crawl. For - example, `case`. - :param int limit: (optional) The maximum number of documents to crawl for - this document object. By default, all documents in the document object are - crawled. - """ - self.name = name - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsObject': - """Initialize a SourceOptionsObject object from a json dictionary.""" - args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - else: - raise ValueError( - 'Required property \'name\' not present in SourceOptionsObject JSON' - ) - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptionsObject 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 SourceOptionsObject object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptionsObject') -> 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: 'SourceOptionsObject') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsSiteColl: - """ - Object that defines a Microsoft SharePoint site collection to crawl with this - configuration. - - :param str site_collection_path: The Microsoft SharePoint Online site collection - path to crawl. The path must be be relative to the **organization_url** that was - specified in the credentials associated with this source configuration. - :param int limit: (optional) The maximum number of documents to crawl for this - site collection. By default, all documents in the site collection are crawled. - """ - - def __init__( - self, - site_collection_path: str, - *, - limit: Optional[int] = None, - ) -> None: - """ - Initialize a SourceOptionsSiteColl object. - - :param str site_collection_path: The Microsoft SharePoint Online site - collection path to crawl. The path must be be relative to the - **organization_url** that was specified in the credentials associated with - this source configuration. - :param int limit: (optional) The maximum number of documents to crawl for - this site collection. By default, all documents in the site collection are - crawled. - """ - self.site_collection_path = site_collection_path - self.limit = limit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsSiteColl': - """Initialize a SourceOptionsSiteColl object from a json dictionary.""" - args = {} - if (site_collection_path := - _dict.get('site_collection_path')) is not None: - args['site_collection_path'] = site_collection_path - else: - raise ValueError( - 'Required property \'site_collection_path\' not present in SourceOptionsSiteColl JSON' - ) - if (limit := _dict.get('limit')) is not None: - args['limit'] = limit - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptionsSiteColl 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, 'site_collection_path' - ) and self.site_collection_path is not None: - _dict['site_collection_path'] = self.site_collection_path - if hasattr(self, 'limit') and self.limit is not None: - _dict['limit'] = self.limit - 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 SourceOptionsSiteColl object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptionsSiteColl') -> 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: 'SourceOptionsSiteColl') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SourceOptionsWebCrawl: - """ - Object defining which URL to crawl and how to crawl it. - - :param str url: The starting URL to crawl. - :param bool limit_to_starting_hosts: (optional) When `true`, crawls of the - specified URL are limited to the host part of the **url** field. - :param str crawl_speed: (optional) The number of concurrent URLs to fetch. - `gentle` means one URL is fetched at a time with a delay between each call. - `normal` means as many as two URLs are fectched concurrently with a short delay - between fetch calls. `aggressive` means that up to ten URLs are fetched - concurrently with a short delay between fetch calls. - :param bool allow_untrusted_certificate: (optional) When `true`, allows the - crawl to interact with HTTPS sites with SSL certificates with untrusted signers. - :param int maximum_hops: (optional) The maximum number of hops to make from the - initial URL. When a page is crawled each link on that page will also be crawled - if it is within the **maximum_hops** from the initial URL. The first page - crawled is 0 hops, each link crawled from the first page is 1 hop, each link - crawled from those pages is 2 hops, and so on. - :param int request_timeout: (optional) The maximum milliseconds to wait for a - response from the web server. - :param bool override_robots_txt: (optional) When `true`, the crawler will ignore - any `robots.txt` encountered by the crawler. This should only ever be done when - crawling a web site the user owns. This must be be set to `true` when a - **gateway_id** is specied in the **credentials**. - :param List[str] blacklist: (optional) Array of URL's to be excluded while - crawling. The crawler will not follow links which contains this string. For - example, listing `https://ibm.com/watson` also excludes - `https://ibm.com/watson/discovery`. - """ - - def __init__( - self, - url: str, - *, - limit_to_starting_hosts: Optional[bool] = None, - crawl_speed: Optional[str] = None, - allow_untrusted_certificate: Optional[bool] = None, - maximum_hops: Optional[int] = None, - request_timeout: Optional[int] = None, - override_robots_txt: Optional[bool] = None, - blacklist: Optional[List[str]] = None, - ) -> None: - """ - Initialize a SourceOptionsWebCrawl object. - - :param str url: The starting URL to crawl. - :param bool limit_to_starting_hosts: (optional) When `true`, crawls of the - specified URL are limited to the host part of the **url** field. - :param str crawl_speed: (optional) The number of concurrent URLs to fetch. - `gentle` means one URL is fetched at a time with a delay between each call. - `normal` means as many as two URLs are fectched concurrently with a short - delay between fetch calls. `aggressive` means that up to ten URLs are - fetched concurrently with a short delay between fetch calls. - :param bool allow_untrusted_certificate: (optional) When `true`, allows the - crawl to interact with HTTPS sites with SSL certificates with untrusted - signers. - :param int maximum_hops: (optional) The maximum number of hops to make from - the initial URL. When a page is crawled each link on that page will also be - crawled if it is within the **maximum_hops** from the initial URL. The - first page crawled is 0 hops, each link crawled from the first page is 1 - hop, each link crawled from those pages is 2 hops, and so on. - :param int request_timeout: (optional) The maximum milliseconds to wait for - a response from the web server. - :param bool override_robots_txt: (optional) When `true`, the crawler will - ignore any `robots.txt` encountered by the crawler. This should only ever - be done when crawling a web site the user owns. This must be be set to - `true` when a **gateway_id** is specied in the **credentials**. - :param List[str] blacklist: (optional) Array of URL's to be excluded while - crawling. The crawler will not follow links which contains this string. For - example, listing `https://ibm.com/watson` also excludes - `https://ibm.com/watson/discovery`. - """ - self.url = url - self.limit_to_starting_hosts = limit_to_starting_hosts - self.crawl_speed = crawl_speed - self.allow_untrusted_certificate = allow_untrusted_certificate - self.maximum_hops = maximum_hops - self.request_timeout = request_timeout - self.override_robots_txt = override_robots_txt - self.blacklist = blacklist - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceOptionsWebCrawl': - """Initialize a SourceOptionsWebCrawl object from a json dictionary.""" - args = {} - if (url := _dict.get('url')) is not None: - args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in SourceOptionsWebCrawl JSON' - ) - if (limit_to_starting_hosts := - _dict.get('limit_to_starting_hosts')) is not None: - args['limit_to_starting_hosts'] = limit_to_starting_hosts - if (crawl_speed := _dict.get('crawl_speed')) is not None: - args['crawl_speed'] = crawl_speed - if (allow_untrusted_certificate := - _dict.get('allow_untrusted_certificate')) is not None: - args['allow_untrusted_certificate'] = allow_untrusted_certificate - if (maximum_hops := _dict.get('maximum_hops')) is not None: - args['maximum_hops'] = maximum_hops - if (request_timeout := _dict.get('request_timeout')) is not None: - args['request_timeout'] = request_timeout - if (override_robots_txt := - _dict.get('override_robots_txt')) is not None: - args['override_robots_txt'] = override_robots_txt - if (blacklist := _dict.get('blacklist')) is not None: - args['blacklist'] = blacklist - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceOptionsWebCrawl 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, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'limit_to_starting_hosts' - ) and self.limit_to_starting_hosts is not None: - _dict['limit_to_starting_hosts'] = self.limit_to_starting_hosts - if hasattr(self, 'crawl_speed') and self.crawl_speed is not None: - _dict['crawl_speed'] = self.crawl_speed - if hasattr(self, 'allow_untrusted_certificate' - ) and self.allow_untrusted_certificate is not None: - _dict[ - 'allow_untrusted_certificate'] = self.allow_untrusted_certificate - if hasattr(self, 'maximum_hops') and self.maximum_hops is not None: - _dict['maximum_hops'] = self.maximum_hops - if hasattr(self, - 'request_timeout') and self.request_timeout is not None: - _dict['request_timeout'] = self.request_timeout - if hasattr( - self, - 'override_robots_txt') and self.override_robots_txt is not None: - _dict['override_robots_txt'] = self.override_robots_txt - if hasattr(self, 'blacklist') and self.blacklist is not None: - _dict['blacklist'] = self.blacklist - 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 SourceOptionsWebCrawl object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceOptionsWebCrawl') -> 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: 'SourceOptionsWebCrawl') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class CrawlSpeedEnum(str, Enum): - """ - The number of concurrent URLs to fetch. `gentle` means one URL is fetched at a - time with a delay between each call. `normal` means as many as two URLs are - fectched concurrently with a short delay between fetch calls. `aggressive` means - that up to ten URLs are fetched concurrently with a short delay between fetch - calls. - """ - - GENTLE = 'gentle' - NORMAL = 'normal' - AGGRESSIVE = 'aggressive' - - -class SourceSchedule: - """ - Object containing the schedule information for the source. - - :param bool enabled: (optional) When `true`, the source is re-crawled based on - the **frequency** field in this object. When `false` the source is not - re-crawled; When `false` and connecting to Salesforce the source is crawled - annually. - :param str time_zone: (optional) The time zone to base source crawl times on. - Possible values correspond to the IANA (Internet Assigned Numbers Authority) - time zones list. - :param str frequency: (optional) The crawl schedule in the specified - **time_zone**. - - `five_minutes`: Runs every five minutes. - - `hourly`: Runs every hour. - - `daily`: Runs every day between 00:00 and 06:00. - - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - - `monthly`: Runs the on the first Sunday of every month between 00:00 and - 06:00. - """ - - def __init__( - self, - *, - enabled: Optional[bool] = None, - time_zone: Optional[str] = None, - frequency: Optional[str] = None, - ) -> None: - """ - Initialize a SourceSchedule object. - - :param bool enabled: (optional) When `true`, the source is re-crawled based - on the **frequency** field in this object. When `false` the source is not - re-crawled; When `false` and connecting to Salesforce the source is crawled - annually. - :param str time_zone: (optional) The time zone to base source crawl times - on. Possible values correspond to the IANA (Internet Assigned Numbers - Authority) time zones list. - :param str frequency: (optional) The crawl schedule in the specified - **time_zone**. - - `five_minutes`: Runs every five minutes. - - `hourly`: Runs every hour. - - `daily`: Runs every day between 00:00 and 06:00. - - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - - `monthly`: Runs the on the first Sunday of every month between 00:00 and - 06:00. - """ - self.enabled = enabled - self.time_zone = time_zone - self.frequency = frequency - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceSchedule': - """Initialize a SourceSchedule object from a json dictionary.""" - args = {} - if (enabled := _dict.get('enabled')) is not None: - args['enabled'] = enabled - if (time_zone := _dict.get('time_zone')) is not None: - args['time_zone'] = time_zone - if (frequency := _dict.get('frequency')) is not None: - args['frequency'] = frequency - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceSchedule 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 - if hasattr(self, 'time_zone') and self.time_zone is not None: - _dict['time_zone'] = self.time_zone - if hasattr(self, 'frequency') and self.frequency is not None: - _dict['frequency'] = self.frequency - 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 SourceSchedule object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceSchedule') -> 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: 'SourceSchedule') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class FrequencyEnum(str, Enum): - """ - The crawl schedule in the specified **time_zone**. - - `five_minutes`: Runs every five minutes. - - `hourly`: Runs every hour. - - `daily`: Runs every day between 00:00 and 06:00. - - `weekly`: Runs every week on Sunday between 00:00 and 06:00. - - `monthly`: Runs the on the first Sunday of every month between 00:00 and 06:00. - """ - - DAILY = 'daily' - WEEKLY = 'weekly' - MONTHLY = 'monthly' - FIVE_MINUTES = 'five_minutes' - HOURLY = 'hourly' - - -class SourceStatus: - """ - Object containing source crawl status information. - - :param str status: (optional) The current status of the source crawl for this - collection. This field returns `not_configured` if the default configuration for - this source does not have a **source** object defined. - - `running` indicates that a crawl to fetch more documents is in progress. - - `complete` indicates that the crawl has completed with no errors. - - `queued` indicates that the crawl has been paused by the system and will - automatically restart when possible. - - `unknown` indicates that an unidentified error has occured in the service. - :param datetime next_crawl: (optional) Date in `RFC 3339` format indicating the - time of the next crawl attempt. - """ - - def __init__( - self, - *, - status: Optional[str] = None, - next_crawl: Optional[datetime] = None, - ) -> None: - """ - Initialize a SourceStatus object. - - :param str status: (optional) The current status of the source crawl for - this collection. This field returns `not_configured` if the default - configuration for this source does not have a **source** object defined. - - `running` indicates that a crawl to fetch more documents is in progress. - - `complete` indicates that the crawl has completed with no errors. - - `queued` indicates that the crawl has been paused by the system and will - automatically restart when possible. - - `unknown` indicates that an unidentified error has occured in the - service. - :param datetime next_crawl: (optional) Date in `RFC 3339` format indicating - the time of the next crawl attempt. - """ - self.status = status - self.next_crawl = next_crawl - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SourceStatus': - """Initialize a SourceStatus object from a json dictionary.""" - args = {} - if (status := _dict.get('status')) is not None: - args['status'] = status - if (next_crawl := _dict.get('next_crawl')) is not None: - args['next_crawl'] = string_to_datetime(next_crawl) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SourceStatus 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, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'next_crawl') and self.next_crawl is not None: - _dict['next_crawl'] = datetime_to_string(self.next_crawl) - 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 SourceStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SourceStatus') -> 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: 'SourceStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The current status of the source crawl for this collection. This field returns - `not_configured` if the default configuration for this source does not have a - **source** object defined. - - `running` indicates that a crawl to fetch more documents is in progress. - - `complete` indicates that the crawl has completed with no errors. - - `queued` indicates that the crawl has been paused by the system and will - automatically restart when possible. - - `unknown` indicates that an unidentified error has occured in the service. - """ - - RUNNING = 'running' - COMPLETE = 'complete' - NOT_CONFIGURED = 'not_configured' - QUEUED = 'queued' - UNKNOWN = 'unknown' - - -class StatusDetails: - """ - Object that contains details about the status of the authentication process. - - :param bool authenticated: (optional) Indicates whether the credential is - accepted by the target data source. - :param str error_message: (optional) If `authenticated` is `false`, a message - describes why authentication is unsuccessful. - """ - - def __init__( - self, - *, - authenticated: Optional[bool] = None, - error_message: Optional[str] = None, - ) -> None: - """ - Initialize a StatusDetails object. - - :param bool authenticated: (optional) Indicates whether the credential is - accepted by the target data source. - :param str error_message: (optional) If `authenticated` is `false`, a - message describes why authentication is unsuccessful. - """ - self.authenticated = authenticated - self.error_message = error_message - - @classmethod - def from_dict(cls, _dict: Dict) -> 'StatusDetails': - """Initialize a StatusDetails object from a json dictionary.""" - args = {} - if (authenticated := _dict.get('authenticated')) is not None: - args['authenticated'] = authenticated - if (error_message := _dict.get('error_message')) is not None: - args['error_message'] = error_message - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a StatusDetails 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, 'authenticated') and self.authenticated is not None: - _dict['authenticated'] = self.authenticated - if hasattr(self, 'error_message') and self.error_message is not None: - _dict['error_message'] = self.error_message - 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 StatusDetails object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'StatusDetails') -> 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: 'StatusDetails') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TokenDictRule: - """ - An object defining a single tokenizaion rule. - - :param str text: The string to tokenize. - :param List[str] tokens: Array of tokens that the `text` field is split into - when found. - :param List[str] readings: (optional) Array of tokens that represent the content - of the `text` field in an alternate character set. - :param str part_of_speech: The part of speech that the `text` string belongs to. - For example `noun`. Custom parts of speech can be specified. - """ - - def __init__( - self, - text: str, - tokens: List[str], - part_of_speech: str, - *, - readings: Optional[List[str]] = None, - ) -> None: - """ - Initialize a TokenDictRule object. - - :param str text: The string to tokenize. - :param List[str] tokens: Array of tokens that the `text` field is split - into when found. - :param str part_of_speech: The part of speech that the `text` string - belongs to. For example `noun`. Custom parts of speech can be specified. - :param List[str] readings: (optional) Array of tokens that represent the - content of the `text` field in an alternate character set. - """ - self.text = text - self.tokens = tokens - self.readings = readings - self.part_of_speech = part_of_speech - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TokenDictRule': - """Initialize a TokenDictRule object from a json dictionary.""" - args = {} - if (text := _dict.get('text')) is not None: - args['text'] = text - else: - raise ValueError( - 'Required property \'text\' not present in TokenDictRule JSON') - if (tokens := _dict.get('tokens')) is not None: - args['tokens'] = tokens - else: - raise ValueError( - 'Required property \'tokens\' not present in TokenDictRule JSON' - ) - if (readings := _dict.get('readings')) is not None: - args['readings'] = readings - if (part_of_speech := _dict.get('part_of_speech')) is not None: - args['part_of_speech'] = part_of_speech - else: - raise ValueError( - 'Required property \'part_of_speech\' not present in TokenDictRule JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TokenDictRule 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'tokens') and self.tokens is not None: - _dict['tokens'] = self.tokens - if hasattr(self, 'readings') and self.readings is not None: - _dict['readings'] = self.readings - if hasattr(self, 'part_of_speech') and self.part_of_speech is not None: - _dict['part_of_speech'] = self.part_of_speech - 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 TokenDictRule object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TokenDictRule') -> 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: 'TokenDictRule') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TokenDictStatusResponse: - """ - Object describing the current status of the wordlist. - - :param str status: (optional) Current wordlist status for the specified - collection. - :param str type: (optional) The type for this wordlist. Can be - `tokenization_dictionary` or `stopwords`. - """ - - def __init__( - self, - *, - status: Optional[str] = None, - type: Optional[str] = None, - ) -> None: - """ - Initialize a TokenDictStatusResponse object. - - :param str status: (optional) Current wordlist status for the specified - collection. - :param str type: (optional) The type for this wordlist. Can be - `tokenization_dictionary` or `stopwords`. - """ - self.status = status - self.type = type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TokenDictStatusResponse': - """Initialize a TokenDictStatusResponse object from a json dictionary.""" - args = {} - if (status := _dict.get('status')) is not None: - args['status'] = status - if (type := _dict.get('type')) is not None: - args['type'] = type - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TokenDictStatusResponse 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, 'status') and self.status is not None: - _dict['status'] = self.status - 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 TokenDictStatusResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TokenDictStatusResponse') -> 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: 'TokenDictStatusResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Current wordlist status for the specified collection. - """ - - ACTIVE = 'active' - PENDING = 'pending' - NOT_FOUND = 'not found' - - -class TrainingDataSet: - """ - Training information for a specific collection. - - :param str environment_id: (optional) The environment id associated with this - training data set. - :param str collection_id: (optional) The collection id associated with this - training data set. - :param List[TrainingQuery] queries: (optional) Array of training queries. At - least 50 queries are required for training to begin. A maximum of 10,000 queries - are returned. - """ - - def __init__( - self, - *, - environment_id: Optional[str] = None, - collection_id: Optional[str] = None, - queries: Optional[List['TrainingQuery']] = None, - ) -> None: - """ - Initialize a TrainingDataSet object. - - :param str environment_id: (optional) The environment id associated with - this training data set. - :param str collection_id: (optional) The collection id associated with this - training data set. - :param List[TrainingQuery] queries: (optional) Array of training queries. - At least 50 queries are required for training to begin. A maximum of 10,000 - queries are returned. - """ - self.environment_id = environment_id - self.collection_id = collection_id - self.queries = queries - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingDataSet': - """Initialize a TrainingDataSet object from a json dictionary.""" - args = {} - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (collection_id := _dict.get('collection_id')) is not None: - args['collection_id'] = collection_id - if (queries := _dict.get('queries')) is not None: - args['queries'] = [TrainingQuery.from_dict(v) for v in queries] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingDataSet 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, 'environment_id') and self.environment_id is not None: - _dict['environment_id'] = self.environment_id - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'queries') and self.queries is not None: - queries_list = [] - for v in self.queries: - if isinstance(v, dict): - queries_list.append(v) - else: - queries_list.append(v.to_dict()) - _dict['queries'] = queries_list - 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 TrainingDataSet object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingDataSet') -> 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: 'TrainingDataSet') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingExample: - """ - Training example details. - - :param str document_id: (optional) The document ID associated with this training - example. - :param str cross_reference: (optional) The cross reference associated with this - training example. - :param int relevance: (optional) The relevance of the training example. - """ - - def __init__( - self, - *, - document_id: Optional[str] = None, - cross_reference: Optional[str] = None, - relevance: Optional[int] = None, - ) -> None: - """ - Initialize a TrainingExample object. - - :param str document_id: (optional) The document ID associated with this - training example. - :param str cross_reference: (optional) The cross reference associated with - this training example. - :param int relevance: (optional) The relevance of the training example. - """ - self.document_id = document_id - self.cross_reference = cross_reference - self.relevance = relevance - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingExample': - """Initialize a TrainingExample object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - if (cross_reference := _dict.get('cross_reference')) is not None: - args['cross_reference'] = cross_reference - if (relevance := _dict.get('relevance')) is not None: - args['relevance'] = relevance - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingExample 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, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, - 'cross_reference') and self.cross_reference is not None: - _dict['cross_reference'] = self.cross_reference - if hasattr(self, 'relevance') and self.relevance is not None: - _dict['relevance'] = self.relevance - 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 TrainingExample object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingExample') -> 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: 'TrainingExample') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingExampleList: - """ - Object containing an array of training examples. - - :param List[TrainingExample] examples: (optional) Array of training examples. - """ - - def __init__( - self, - *, - examples: Optional[List['TrainingExample']] = None, - ) -> None: - """ - Initialize a TrainingExampleList object. - - :param List[TrainingExample] examples: (optional) Array of training - examples. - """ - self.examples = examples - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingExampleList': - """Initialize a TrainingExampleList object from a json dictionary.""" - args = {} - if (examples := _dict.get('examples')) is not None: - args['examples'] = [TrainingExample.from_dict(v) for v in examples] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingExampleList 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, 'examples') and self.examples is not None: - examples_list = [] - for v in self.examples: - if isinstance(v, dict): - examples_list.append(v) - else: - examples_list.append(v.to_dict()) - _dict['examples'] = examples_list - 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 TrainingExampleList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingExampleList') -> 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: 'TrainingExampleList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingQuery: - """ - Training query details. - - :param str query_id: (optional) The query ID associated with the training query. - :param str natural_language_query: (optional) The natural text query for the - training query. - :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. - :param List[TrainingExample] examples: (optional) Array of training examples. - """ - - def __init__( - self, - *, - query_id: Optional[str] = None, - natural_language_query: Optional[str] = None, - filter: Optional[str] = None, - examples: Optional[List['TrainingExample']] = None, - ) -> None: - """ - Initialize a TrainingQuery object. - - :param str query_id: (optional) The query ID associated with the training - query. - :param str natural_language_query: (optional) The natural text query for - the training query. - :param str filter: (optional) The filter used on the collection before the - **natural_language_query** is applied. - :param List[TrainingExample] examples: (optional) Array of training - examples. - """ - self.query_id = query_id - self.natural_language_query = natural_language_query - self.filter = filter - self.examples = examples - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingQuery': - """Initialize a TrainingQuery object from a json dictionary.""" - args = {} - if (query_id := _dict.get('query_id')) is not None: - args['query_id'] = query_id - if (natural_language_query := - _dict.get('natural_language_query')) is not None: - args['natural_language_query'] = natural_language_query - if (filter := _dict.get('filter')) is not None: - args['filter'] = filter - if (examples := _dict.get('examples')) is not None: - args['examples'] = [TrainingExample.from_dict(v) for v in examples] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingQuery 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, 'query_id') and self.query_id is not None: - _dict['query_id'] = self.query_id - if hasattr(self, 'natural_language_query' - ) and self.natural_language_query is not None: - _dict['natural_language_query'] = self.natural_language_query - if hasattr(self, 'filter') and self.filter is not None: - _dict['filter'] = self.filter - if hasattr(self, 'examples') and self.examples is not None: - examples_list = [] - for v in self.examples: - if isinstance(v, dict): - examples_list.append(v) - else: - examples_list.append(v.to_dict()) - _dict['examples'] = examples_list - 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 TrainingQuery object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingQuery') -> 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: 'TrainingQuery') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingStatus: - """ - Training status details. - - :param int total_examples: (optional) The total number of training examples - uploaded to this collection. - :param bool available: (optional) When `true`, the collection has been - successfully trained. - :param bool processing: (optional) When `true`, the collection is currently - processing training. - :param bool minimum_queries_added: (optional) When `true`, the collection has a - sufficent amount of queries added for training to occur. - :param bool minimum_examples_added: (optional) When `true`, the collection has a - sufficent amount of examples added for training to occur. - :param bool sufficient_label_diversity: (optional) When `true`, the collection - has a sufficent amount of diversity in labeled results for training to occur. - :param int notices: (optional) The number of notices associated with this data - set. - :param datetime successfully_trained: (optional) The timestamp of when the - collection was successfully trained. - :param datetime data_updated: (optional) The timestamp of when the data was - uploaded. - """ - - def __init__( - self, - *, - total_examples: Optional[int] = None, - available: Optional[bool] = None, - processing: Optional[bool] = None, - minimum_queries_added: Optional[bool] = None, - minimum_examples_added: Optional[bool] = None, - sufficient_label_diversity: Optional[bool] = None, - notices: Optional[int] = None, - successfully_trained: Optional[datetime] = None, - data_updated: Optional[datetime] = None, - ) -> None: - """ - Initialize a TrainingStatus object. - - :param int total_examples: (optional) The total number of training examples - uploaded to this collection. - :param bool available: (optional) When `true`, the collection has been - successfully trained. - :param bool processing: (optional) When `true`, the collection is currently - processing training. - :param bool minimum_queries_added: (optional) When `true`, the collection - has a sufficent amount of queries added for training to occur. - :param bool minimum_examples_added: (optional) When `true`, the collection - has a sufficent amount of examples added for training to occur. - :param bool sufficient_label_diversity: (optional) When `true`, the - collection has a sufficent amount of diversity in labeled results for - training to occur. - :param int notices: (optional) The number of notices associated with this - data set. - :param datetime successfully_trained: (optional) The timestamp of when the - collection was successfully trained. - :param datetime data_updated: (optional) The timestamp of when the data was - uploaded. - """ - self.total_examples = total_examples - self.available = available - self.processing = processing - self.minimum_queries_added = minimum_queries_added - self.minimum_examples_added = minimum_examples_added - self.sufficient_label_diversity = sufficient_label_diversity - self.notices = notices - self.successfully_trained = successfully_trained - self.data_updated = data_updated - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingStatus': - """Initialize a TrainingStatus object from a json dictionary.""" - args = {} - if (total_examples := _dict.get('total_examples')) is not None: - args['total_examples'] = total_examples - if (available := _dict.get('available')) is not None: - args['available'] = available - if (processing := _dict.get('processing')) is not None: - args['processing'] = processing - if (minimum_queries_added := - _dict.get('minimum_queries_added')) is not None: - args['minimum_queries_added'] = minimum_queries_added - if (minimum_examples_added := - _dict.get('minimum_examples_added')) is not None: - args['minimum_examples_added'] = minimum_examples_added - if (sufficient_label_diversity := - _dict.get('sufficient_label_diversity')) is not None: - args['sufficient_label_diversity'] = sufficient_label_diversity - if (notices := _dict.get('notices')) is not None: - args['notices'] = notices - if (successfully_trained := - _dict.get('successfully_trained')) is not None: - args['successfully_trained'] = string_to_datetime( - successfully_trained) - if (data_updated := _dict.get('data_updated')) is not None: - args['data_updated'] = string_to_datetime(data_updated) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingStatus 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, 'total_examples') and self.total_examples is not None: - _dict['total_examples'] = self.total_examples - if hasattr(self, 'available') and self.available is not None: - _dict['available'] = self.available - if hasattr(self, 'processing') and self.processing is not None: - _dict['processing'] = self.processing - if hasattr(self, 'minimum_queries_added' - ) and self.minimum_queries_added is not None: - _dict['minimum_queries_added'] = self.minimum_queries_added - if hasattr(self, 'minimum_examples_added' - ) and self.minimum_examples_added is not None: - _dict['minimum_examples_added'] = self.minimum_examples_added - if hasattr(self, 'sufficient_label_diversity' - ) and self.sufficient_label_diversity is not None: - _dict[ - 'sufficient_label_diversity'] = self.sufficient_label_diversity - if hasattr(self, 'notices') and self.notices is not None: - _dict['notices'] = self.notices - if hasattr(self, 'successfully_trained' - ) and self.successfully_trained is not None: - _dict['successfully_trained'] = datetime_to_string( - self.successfully_trained) - if hasattr(self, 'data_updated') and self.data_updated is not None: - _dict['data_updated'] = datetime_to_string(self.data_updated) - 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 TrainingStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingStatus') -> 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: 'TrainingStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class WordHeadingDetection: - """ - Object containing heading detection conversion settings for Microsoft Word documents. - - :param List[FontSetting] fonts: (optional) Array of font matching - configurations. - :param List[WordStyle] styles: (optional) Array of Microsoft Word styles to - convert. - """ - - def __init__( - self, - *, - fonts: Optional[List['FontSetting']] = None, - styles: Optional[List['WordStyle']] = None, - ) -> None: - """ - Initialize a WordHeadingDetection object. - - :param List[FontSetting] fonts: (optional) Array of font matching - configurations. - :param List[WordStyle] styles: (optional) Array of Microsoft Word styles to - convert. - """ - self.fonts = fonts - self.styles = styles - - @classmethod - def from_dict(cls, _dict: Dict) -> 'WordHeadingDetection': - """Initialize a WordHeadingDetection object from a json dictionary.""" - args = {} - if (fonts := _dict.get('fonts')) is not None: - args['fonts'] = [FontSetting.from_dict(v) for v in fonts] - if (styles := _dict.get('styles')) is not None: - args['styles'] = [WordStyle.from_dict(v) for v in styles] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a WordHeadingDetection 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, 'fonts') and self.fonts is not None: - fonts_list = [] - for v in self.fonts: - if isinstance(v, dict): - fonts_list.append(v) - else: - fonts_list.append(v.to_dict()) - _dict['fonts'] = fonts_list - if hasattr(self, 'styles') and self.styles is not None: - styles_list = [] - for v in self.styles: - if isinstance(v, dict): - styles_list.append(v) - else: - styles_list.append(v.to_dict()) - _dict['styles'] = styles_list - 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 WordHeadingDetection object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'WordHeadingDetection') -> 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: 'WordHeadingDetection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class WordSettings: - """ - A list of Word conversion settings. - - :param WordHeadingDetection heading: (optional) Object containing heading - detection conversion settings for Microsoft Word documents. - """ - - def __init__( - self, - *, - heading: Optional['WordHeadingDetection'] = None, - ) -> None: - """ - Initialize a WordSettings object. - - :param WordHeadingDetection heading: (optional) Object containing heading - detection conversion settings for Microsoft Word documents. - """ - self.heading = heading - - @classmethod - def from_dict(cls, _dict: Dict) -> 'WordSettings': - """Initialize a WordSettings object from a json dictionary.""" - args = {} - if (heading := _dict.get('heading')) is not None: - args['heading'] = WordHeadingDetection.from_dict(heading) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a WordSettings 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, 'heading') and self.heading is not None: - if isinstance(self.heading, dict): - _dict['heading'] = self.heading - else: - _dict['heading'] = self.heading.to_dict() - 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 WordSettings object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'WordSettings') -> 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: 'WordSettings') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class WordStyle: - """ - Microsoft Word styles to convert into a specified HTML head level. - - :param int level: (optional) HTML head level that content matching this style is - tagged with. - :param List[str] names: (optional) Array of word style names to convert. - """ - - def __init__( - self, - *, - level: Optional[int] = None, - names: Optional[List[str]] = None, - ) -> None: - """ - Initialize a WordStyle object. - - :param int level: (optional) HTML head level that content matching this - style is tagged with. - :param List[str] names: (optional) Array of word style names to convert. - """ - self.level = level - self.names = names - - @classmethod - def from_dict(cls, _dict: Dict) -> 'WordStyle': - """Initialize a WordStyle object from a json dictionary.""" - args = {} - if (level := _dict.get('level')) is not None: - args['level'] = level - if (names := _dict.get('names')) is not None: - args['names'] = names - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a WordStyle 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, 'level') and self.level is not None: - _dict['level'] = self.level - if hasattr(self, 'names') and self.names is not None: - _dict['names'] = self.names - 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 WordStyle object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'WordStyle') -> 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: 'WordStyle') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class XPathPatterns: - """ - Object containing an array of XPaths. - - :param List[str] xpaths: (optional) An array to XPaths. - """ - - def __init__( - self, - *, - xpaths: Optional[List[str]] = None, - ) -> None: - """ - Initialize a XPathPatterns object. - - :param List[str] xpaths: (optional) An array to XPaths. - """ - self.xpaths = xpaths - - @classmethod - def from_dict(cls, _dict: Dict) -> 'XPathPatterns': - """Initialize a XPathPatterns object from a json dictionary.""" - args = {} - if (xpaths := _dict.get('xpaths')) is not None: - args['xpaths'] = xpaths - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a XPathPatterns 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, 'xpaths') and self.xpaths is not None: - _dict['xpaths'] = self.xpaths - 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 XPathPatterns object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'XPathPatterns') -> 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: 'XPathPatterns') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryCalculationAggregation(QueryAggregation): - """ - Returns a scalar calculation across all documents for the field specified. Possible - calculations include min, max, sum, average, and unique_count. - - :param str field: The field to perform the calculation on. - :param float value: (optional) The value of the calculation. - """ - - def __init__( - self, - type: str, - field: str, - *, - value: Optional[float] = None, - ) -> None: - """ - Initialize a QueryCalculationAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str field: The field to perform the calculation on. - :param float value: (optional) The value of the calculation. - """ - self.type = type - self.field = field - self.value = value - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': - """Initialize a QueryCalculationAggregation object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryCalculationAggregation JSON' - ) - if (field := _dict.get('field')) is not None: - args['field'] = field - else: - raise ValueError( - 'Required property \'field\' not present in QueryCalculationAggregation JSON' - ) - if (value := _dict.get('value')) is not None: - args['value'] = value - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryCalculationAggregation 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 - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value - 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 QueryCalculationAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryCalculationAggregation') -> 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: 'QueryCalculationAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryFilterAggregation(QueryAggregation): - """ - A modifier that narrows the document set of the sub-aggregations it precedes. - - :param str match: The filter that is written in Discovery Query Language syntax - and is applied to the documents before sub-aggregations are run. - :param int matching_results: Number of documents that match the filter. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__( - self, - type: str, - match: str, - matching_results: int, - *, - aggregations: Optional[List['QueryAggregation']] = None, - ) -> None: - """ - Initialize a QueryFilterAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str match: The filter that is written in Discovery Query Language - syntax and is applied to the documents before sub-aggregations are run. - :param int matching_results: Number of documents that match the filter. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - self.type = type - self.match = match - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': - """Initialize a QueryFilterAggregation object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryFilterAggregation JSON' - ) - if (match := _dict.get('match')) is not None: - args['match'] = match - else: - raise ValueError( - 'Required property \'match\' not present in QueryFilterAggregation JSON' - ) - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' - ) - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryFilterAggregation 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 - if hasattr(self, 'match') and self.match is not None: - _dict['match'] = self.match - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - 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 QueryFilterAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryFilterAggregation') -> 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: 'QueryFilterAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryHistogramAggregation(QueryAggregation): - """ - Numeric interval segments to categorize documents by using field values from a single - numeric field to describe the category. - - :param str field: The numeric field name used to create the histogram. - :param int interval: The size of the sections that the results are split into. - :param str name: (optional) Identifier specified in the query request of this - aggregation. - :param List[QueryHistogramAggregationResult] results: (optional) Array of - numeric intervals. - """ - - def __init__( - self, - type: str, - field: str, - interval: int, - *, - name: Optional[str] = None, - results: Optional[List['QueryHistogramAggregationResult']] = None, - ) -> None: - """ - Initialize a QueryHistogramAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str field: The numeric field name used to create the histogram. - :param int interval: The size of the sections that the results are split - into. - :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryHistogramAggregationResult] results: (optional) Array of - numeric intervals. - """ - self.type = type - self.field = field - self.interval = interval - self.name = name - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': - """Initialize a QueryHistogramAggregation object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryHistogramAggregation JSON' - ) - if (field := _dict.get('field')) is not None: - args['field'] = field - else: - raise ValueError( - 'Required property \'field\' not present in QueryHistogramAggregation JSON' - ) - if (interval := _dict.get('interval')) is not None: - args['interval'] = interval - else: - raise ValueError( - 'Required property \'interval\' not present in QueryHistogramAggregation JSON' - ) - if (name := _dict.get('name')) is not None: - args['name'] = name - if (results := _dict.get('results')) is not None: - args['results'] = [ - QueryHistogramAggregationResult.from_dict(v) for v in results - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryHistogramAggregation 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 - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - 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 QueryHistogramAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryHistogramAggregation') -> 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: 'QueryHistogramAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryNestedAggregation(QueryAggregation): - """ - A restriction that alters the document set that is used for sub-aggregations it - precedes to nested documents found in the field specified. - - :param str path: The path to the document field to scope sub-aggregations to. - :param int matching_results: Number of nested documents found in the specified - field. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - - def __init__( - self, - type: str, - path: str, - matching_results: int, - *, - aggregations: Optional[List['QueryAggregation']] = None, - ) -> None: - """ - Initialize a QueryNestedAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str path: The path to the document field to scope sub-aggregations - to. - :param int matching_results: Number of nested documents found in the - specified field. - :param List[QueryAggregation] aggregations: (optional) An array of - sub-aggregations. - """ - self.type = type - self.path = path - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': - """Initialize a QueryNestedAggregation object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryNestedAggregation JSON' - ) - if (path := _dict.get('path')) is not None: - args['path'] = path - else: - raise ValueError( - 'Required property \'path\' not present in QueryNestedAggregation JSON' - ) - if (matching_results := _dict.get('matching_results')) is not None: - args['matching_results'] = matching_results - else: - raise ValueError( - 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' - ) - if (aggregations := _dict.get('aggregations')) is not None: - args['aggregations'] = [ - QueryAggregation.from_dict(v) for v in aggregations - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryNestedAggregation 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 - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - aggregations_list = [] - for v in self.aggregations: - if isinstance(v, dict): - aggregations_list.append(v) - else: - aggregations_list.append(v.to_dict()) - _dict['aggregations'] = aggregations_list - 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 QueryNestedAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryNestedAggregation') -> 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: 'QueryNestedAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTermAggregation(QueryAggregation): - """ - Returns the top values for the field specified. - - :param str field: The field in the document used to generate top values from. - :param int count: (optional) The number of top values returned. - :param str name: (optional) Identifier specified in the query request of this - aggregation. - :param List[QueryTermAggregationResult] results: (optional) Array of top values - for the field. - """ - - def __init__( - self, - type: str, - field: str, - *, - count: Optional[int] = None, - name: Optional[str] = None, - results: Optional[List['QueryTermAggregationResult']] = None, - ) -> None: - """ - Initialize a QueryTermAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str field: The field in the document used to generate top values - from. - :param int count: (optional) The number of top values returned. - :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryTermAggregationResult] results: (optional) Array of top - values for the field. - """ - self.type = type - self.field = field - self.count = count - self.name = name - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': - """Initialize a QueryTermAggregation object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryTermAggregation JSON' - ) - if (field := _dict.get('field')) is not None: - args['field'] = field - else: - raise ValueError( - 'Required property \'field\' not present in QueryTermAggregation JSON' - ) - if (count := _dict.get('count')) is not None: - args['count'] = count - if (name := _dict.get('name')) is not None: - args['name'] = name - if (results := _dict.get('results')) is not None: - args['results'] = [ - QueryTermAggregationResult.from_dict(v) for v in results - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTermAggregation 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 - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'count') and self.count is not None: - _dict['count'] = self.count - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - 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 QueryTermAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTermAggregation') -> 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: 'QueryTermAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTimesliceAggregation(QueryAggregation): - """ - A specialized histogram aggregation that uses dates to create interval segments. - - :param str field: The date field name used to create the timeslice. - :param str interval: The date interval value. Valid values are seconds, minutes, - hours, days, weeks, and years. - :param str name: (optional) Identifier specified in the query request of this - aggregation. - :param List[QueryTimesliceAggregationResult] results: (optional) Array of - aggregation results. - """ - - def __init__( - self, - type: str, - field: str, - interval: str, - *, - name: Optional[str] = None, - results: Optional[List['QueryTimesliceAggregationResult']] = None, - ) -> None: - """ - Initialize a QueryTimesliceAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param str field: The date field name used to create the timeslice. - :param str interval: The date interval value. Valid values are seconds, - minutes, hours, days, weeks, and years. - :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param List[QueryTimesliceAggregationResult] results: (optional) Array of - aggregation results. - """ - self.type = type - self.field = field - self.interval = interval - self.name = name - self.results = results - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': - """Initialize a QueryTimesliceAggregation object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryTimesliceAggregation JSON' - ) - if (field := _dict.get('field')) is not None: - args['field'] = field - else: - raise ValueError( - 'Required property \'field\' not present in QueryTimesliceAggregation JSON' - ) - if (interval := _dict.get('interval')) is not None: - args['interval'] = interval - else: - raise ValueError( - 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' - ) - if (name := _dict.get('name')) is not None: - args['name'] = name - if (results := _dict.get('results')) is not None: - args['results'] = [ - QueryTimesliceAggregationResult.from_dict(v) for v in results - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTimesliceAggregation 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 - if hasattr(self, 'field') and self.field is not None: - _dict['field'] = self.field - if hasattr(self, 'interval') and self.interval is not None: - _dict['interval'] = self.interval - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'results') and self.results is not None: - results_list = [] - for v in self.results: - if isinstance(v, dict): - results_list.append(v) - else: - results_list.append(v.to_dict()) - _dict['results'] = results_list - 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 QueryTimesliceAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTimesliceAggregation') -> 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: 'QueryTimesliceAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class QueryTopHitsAggregation(QueryAggregation): - """ - Returns the top documents ranked by the score of the query. - - :param int size: The number of documents to return. - :param str name: (optional) Identifier specified in the query request of this - aggregation. - :param QueryTopHitsAggregationResult hits: (optional) - """ - - def __init__( - self, - type: str, - size: int, - *, - name: Optional[str] = None, - hits: Optional['QueryTopHitsAggregationResult'] = None, - ) -> None: - """ - Initialize a QueryTopHitsAggregation object. - - :param str type: The type of aggregation command used. For example: term, - filter, max, min, etc. - :param int size: The number of documents to return. - :param str name: (optional) Identifier specified in the query request of - this aggregation. - :param QueryTopHitsAggregationResult hits: (optional) - """ - self.type = type - self.size = size - self.name = name - self.hits = hits - - @classmethod - def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': - """Initialize a QueryTopHitsAggregation object from a json dictionary.""" - args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in QueryTopHitsAggregation JSON' - ) - if (size := _dict.get('size')) is not None: - args['size'] = size - else: - raise ValueError( - 'Required property \'size\' not present in QueryTopHitsAggregation JSON' - ) - if (name := _dict.get('name')) is not None: - args['name'] = name - if (hits := _dict.get('hits')) is not None: - args['hits'] = QueryTopHitsAggregationResult.from_dict(hits) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a QueryTopHitsAggregation 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 - if hasattr(self, 'size') and self.size is not None: - _dict['size'] = self.size - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'hits') and self.hits is not None: - if isinstance(self.hits, dict): - _dict['hits'] = self.hits - else: - _dict['hits'] = self.hits.to_dict() - 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 QueryTopHitsAggregation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'QueryTopHitsAggregation') -> 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: 'QueryTopHitsAggregation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other diff --git a/test/integration/test_discovery_v1.py b/test/integration/test_discovery_v1.py deleted file mode 100644 index 6809fefe6..000000000 --- a/test/integration/test_discovery_v1.py +++ /dev/null @@ -1,292 +0,0 @@ -# coding: utf-8 -from unittest import TestCase -import os -import ibm_watson -import random -import pytest - - -@pytest.mark.skipif(os.getenv('DISCOVERY_APIKEY') is None, - reason='requires DISCOVERY_APIKEY') -class Discoveryv1(TestCase): - discovery = None - environment_id = os.getenv('DISCOVERY_ENVIRONMENT_ID') # This environment is created for integration testing - collection_id = None - collection_name = 'FOR-PYTHON-DELETE-ME' - - @classmethod - def setup_class(cls): - cls.discovery = ibm_watson.DiscoveryV1(version='2018-08-01') - cls.discovery.set_default_headers({ - 'X-Watson-Learning-Opt-Out': '1', - 'X-Watson-Test': '1' - }) - - 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'] - - if cls.collection_id is None: - print("Creating a new temporary collection") - cls.collection_id = cls.discovery.create_collection( - cls.environment_id, - cls.collection_name, - 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'] - 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) - break - - def test_environments(self): - envs = self.discovery.list_environments().get_result() - assert envs is not None - env = self.discovery.get_environment( - envs['environments'][0]['environment_id']).get_result() - assert env is not None - fields = self.discovery.list_fields(self.environment_id, - self.collection_id).get_result() - assert fields is not None - - def test_configurations(self): - 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'] - assert new_configuration_id is not None - self.discovery.get_configuration(self.environment_id, - new_configuration_id).get_result() - - updated_config = self.discovery.update_configuration( - self.environment_id, new_configuration_id, 'lala').get_result() - assert updated_config['name'] == 'lala' - - deleted_config = self.discovery.delete_configuration( - self.environment_id, new_configuration_id).get_result() - assert deleted_config['status'] == 'deleted' - - 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() - assert updated_collection['description'] == 'Updating description' - - self.discovery.create_expansions(self.environment_id, - self.collection_id, [{ - 'input_terms': ['a'], - 'expanded_terms': ['aa'] - }]).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: - add_doc = self.discovery.add_document( - environment_id=self.environment_id, - collection_id=self.collection_id, - file=fileinfo).get_result() - 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() - assert doc_status is not None - - 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, - add_doc['document_id'], - file=fileinfo, - 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() - assert delete_doc['status'] == 'deleted' - - def test_queries(self): - query_results = self.discovery.query( - self.environment_id, - self.collection_id, - filter='extracted_metadata.sha1::9181d244*').get_result() - assert query_results is not None - - @pytest.mark.skip( - reason="Temporary skipping because update_credentials fails") - def test_credentials(self): - credential_details = { - 'credential_type': 'username_password', - 'url': 'https://login.salesforce.com', - 'username': 'user@email.com', - 'password': 'xxx' - } - 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() - assert get_credentials['credential_id'] == credential_id - - list_credentials = self.discovery.list_credentials( - self.environment_id).get_result() - assert list_credentials is not None - - new_credential_details = { - 'credential_type': 'username_password', - 'url': 'https://logo.salesforce.com', - '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() - 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'] - - 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: - add_doc = self.discovery.add_document( - environment_id=self.environment_id, - collection_id=self.collection_id, - file=fileinfo).get_result() - assert add_doc['document_id'] is not None - 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() - assert query['session_token'] is not None - - # create_event - event_data = { - "environment_id": self.environment_id, - "session_token": query['session_token'], - "collection_id": self.collection_id, - "document_id": document_id, - } - 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, - 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() - 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() - 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() - 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() - 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() - assert response['aggregations'] is not None - - 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() - assert response is not None - - @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: - create_stopword_list_result = self.discovery.create_stopword_list( - 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() - 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() - 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() - assert get_gateway_result is not None - - list_gateways_result = self.discovery.list_gateways( - 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() - assert delete_gateways_result is not None diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py deleted file mode 100644 index 0a1544439..000000000 --- a/test/unit/test_discovery_v1.py +++ /dev/null @@ -1,12080 +0,0 @@ -# -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2016, 2024. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Unit Tests for DiscoveryV1 -""" - -from datetime import datetime, timezone -from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator -from ibm_cloud_sdk_core.utils import date_to_string, string_to_date -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime -import inspect -import io -import json -import pytest -import re -import requests -import responses -import tempfile -import urllib -from ibm_watson.discovery_v1 import * - -version = 'testString' - -_service = DiscoveryV1( - authenticator=NoAuthAuthenticator(), - version=version, -) - -_base_url = 'https://api.us-south.discovery.watson.cloud.ibm.com' -_service.set_service_url(_base_url) - - -def preprocess_url(operation_path: str): - """ - Returns the request url associated with the specified operation path. - This will be base_url concatenated with a quoted version of operation_path. - The returned request URL is used to register the mock response so it needs - to match the request URL that is formed by the requests library. - """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. - request_url = _base_url + operation_path - - # If the request url does NOT end with a /, then just return it as-is. - # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: - return request_url - return re.compile(request_url.rstrip('/') + '/+') - - -############################################################################## -# Start of Service: Environments -############################################################################## -# region - - -class TestCreateEnvironment: - """ - Test Class for create_environment - """ - - @responses.activate - def test_create_environment_all_params(self): - """ - create_environment() - """ - # Set up mock - url = preprocess_url('/v1/environments') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - name = 'testString' - description = 'testString' - size = 'LT' - - # Invoke method - response = _service.create_environment( - name, - description=description, - size=size, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['size'] == 'LT' - - def test_create_environment_all_params_with_retries(self): - # Enable retries and run test_create_environment_all_params. - _service.enable_retries() - self.test_create_environment_all_params() - - # Disable retries and run test_create_environment_all_params. - _service.disable_retries() - self.test_create_environment_all_params() - - @responses.activate - def test_create_environment_value_error(self): - """ - test_create_environment_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - name = 'testString' - description = 'testString' - size = 'LT' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "name": name, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_environment(**req_copy) - - def test_create_environment_value_error_with_retries(self): - # Enable retries and run test_create_environment_value_error. - _service.enable_retries() - self.test_create_environment_value_error() - - # Disable retries and run test_create_environment_value_error. - _service.disable_retries() - self.test_create_environment_value_error() - - -class TestListEnvironments: - """ - Test Class for list_environments - """ - - @responses.activate - def test_list_environments_all_params(self): - """ - list_environments() - """ - # Set up mock - url = preprocess_url('/v1/environments') - mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - name = 'testString' - - # Invoke method - response = _service.list_environments( - name=name, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'name={}'.format(name) in query_string - - def test_list_environments_all_params_with_retries(self): - # Enable retries and run test_list_environments_all_params. - _service.enable_retries() - self.test_list_environments_all_params() - - # Disable retries and run test_list_environments_all_params. - _service.disable_retries() - self.test_list_environments_all_params() - - @responses.activate - def test_list_environments_required_params(self): - """ - test_list_environments_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments') - mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.list_environments() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_environments_required_params_with_retries(self): - # Enable retries and run test_list_environments_required_params. - _service.enable_retries() - self.test_list_environments_required_params() - - # Disable retries and run test_list_environments_required_params. - _service.disable_retries() - self.test_list_environments_required_params() - - @responses.activate - def test_list_environments_value_error(self): - """ - test_list_environments_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments') - mock_response = '{"environments": [{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_environments(**req_copy) - - def test_list_environments_value_error_with_retries(self): - # Enable retries and run test_list_environments_value_error. - _service.enable_retries() - self.test_list_environments_value_error() - - # Disable retries and run test_list_environments_value_error. - _service.disable_retries() - self.test_list_environments_value_error() - - -class TestGetEnvironment: - """ - Test Class for get_environment - """ - - @responses.activate - def test_get_environment_all_params(self): - """ - get_environment() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.get_environment( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_environment_all_params_with_retries(self): - # Enable retries and run test_get_environment_all_params. - _service.enable_retries() - self.test_get_environment_all_params() - - # Disable retries and run test_get_environment_all_params. - _service.disable_retries() - self.test_get_environment_all_params() - - @responses.activate - def test_get_environment_value_error(self): - """ - test_get_environment_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_environment(**req_copy) - - def test_get_environment_value_error_with_retries(self): - # Enable retries and run test_get_environment_value_error. - _service.enable_retries() - self.test_get_environment_value_error() - - # Disable retries and run test_get_environment_value_error. - _service.disable_retries() - self.test_get_environment_value_error() - - -class TestUpdateEnvironment: - """ - Test Class for update_environment - """ - - @responses.activate - def test_update_environment_all_params(self): - """ - update_environment() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - size = 'S' - - # Invoke method - response = _service.update_environment( - environment_id, - name=name, - description=description, - size=size, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['size'] == 'S' - - def test_update_environment_all_params_with_retries(self): - # Enable retries and run test_update_environment_all_params. - _service.enable_retries() - self.test_update_environment_all_params() - - # Disable retries and run test_update_environment_all_params. - _service.disable_retries() - self.test_update_environment_all_params() - - @responses.activate - def test_update_environment_value_error(self): - """ - test_update_environment_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "read_only": false, "size": "LT", "requested_size": "requested_size", "index_capacity": {"documents": {"available": 9, "maximum_allowed": 15}, "disk_usage": {"used_bytes": 10, "maximum_allowed_bytes": 21}, "collections": {"available": 9, "maximum_allowed": 15}}, "search_status": {"scope": "scope", "status": "NO_DATA", "status_description": "status_description", "last_trained": "2019-01-01"}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - size = 'S' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_environment(**req_copy) - - def test_update_environment_value_error_with_retries(self): - # Enable retries and run test_update_environment_value_error. - _service.enable_retries() - self.test_update_environment_value_error() - - # Disable retries and run test_update_environment_value_error. - _service.disable_retries() - self.test_update_environment_value_error() - - -class TestDeleteEnvironment: - """ - Test Class for delete_environment - """ - - @responses.activate - def test_delete_environment_all_params(self): - """ - delete_environment() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.delete_environment( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_environment_all_params_with_retries(self): - # Enable retries and run test_delete_environment_all_params. - _service.enable_retries() - self.test_delete_environment_all_params() - - # Disable retries and run test_delete_environment_all_params. - _service.disable_retries() - self.test_delete_environment_all_params() - - @responses.activate - def test_delete_environment_value_error(self): - """ - test_delete_environment_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString') - mock_response = '{"environment_id": "environment_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_environment(**req_copy) - - def test_delete_environment_value_error_with_retries(self): - # Enable retries and run test_delete_environment_value_error. - _service.enable_retries() - self.test_delete_environment_value_error() - - # Disable retries and run test_delete_environment_value_error. - _service.disable_retries() - self.test_delete_environment_value_error() - - -class TestListFields: - """ - Test Class for list_fields - """ - - @responses.activate - def test_list_fields_all_params(self): - """ - list_fields() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = ['testString'] - - # Invoke method - response = _service.list_fields( - environment_id, - collection_ids, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string - - def test_list_fields_all_params_with_retries(self): - # Enable retries and run test_list_fields_all_params. - _service.enable_retries() - self.test_list_fields_all_params() - - # Disable retries and run test_list_fields_all_params. - _service.disable_retries() - self.test_list_fields_all_params() - - @responses.activate - def test_list_fields_value_error(self): - """ - test_list_fields_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = ['testString'] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_ids": collection_ids, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_fields(**req_copy) - - def test_list_fields_value_error_with_retries(self): - # Enable retries and run test_list_fields_value_error. - _service.enable_retries() - self.test_list_fields_value_error() - - # Disable retries and run test_list_fields_value_error. - _service.disable_retries() - self.test_list_fields_value_error() - - -# endregion -############################################################################## -# End of Service: Environments -############################################################################## - -############################################################################## -# Start of Service: Configurations -############################################################################## -# region - - -class TestCreateConfiguration: - """ - Test Class for create_configuration - """ - - @responses.activate - def test_create_configuration_all_params(self): - """ - create_configuration() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Construct a dict representation of a FontSetting model - font_setting_model = {} - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - # Construct a dict representation of a PdfHeadingDetection model - pdf_heading_detection_model = {} - pdf_heading_detection_model['fonts'] = [font_setting_model] - - # Construct a dict representation of a PdfSettings model - pdf_settings_model = {} - pdf_settings_model['heading'] = pdf_heading_detection_model - - # Construct a dict representation of a WordStyle model - word_style_model = {} - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - # Construct a dict representation of a WordHeadingDetection model - word_heading_detection_model = {} - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - # Construct a dict representation of a WordSettings model - word_settings_model = {} - word_settings_model['heading'] = word_heading_detection_model - - # Construct a dict representation of a XPathPatterns model - x_path_patterns_model = {} - x_path_patterns_model['xpaths'] = ['testString'] - - # Construct a dict representation of a HtmlSettings model - html_settings_model = {} - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - # Construct a dict representation of a SegmentSettings model - segment_settings_model = {} - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - # Construct a dict representation of a NormalizationOperation model - normalization_operation_model = {} - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - # Construct a dict representation of a Conversions model - conversions_model = {} - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - # Construct a dict representation of a NluEnrichmentKeywords model - nlu_enrichment_keywords_model = {} - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentEntities model - nlu_enrichment_entities_model = {} - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentSentiment model - nlu_enrichment_sentiment_model = {} - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentEmotion model - nlu_enrichment_emotion_model = {} - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentSemanticRoles model - nlu_enrichment_semantic_roles_model = {} - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentRelations model - nlu_enrichment_relations_model = {} - nlu_enrichment_relations_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentConcepts model - nlu_enrichment_concepts_model = {} - nlu_enrichment_concepts_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentFeatures model - nlu_enrichment_features_model = {} - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - # Construct a dict representation of a Enrichment model - enrichment_model = {} - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'testString' - enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - # Construct a dict representation of a SourceSchedule model - source_schedule_model = {} - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - # Construct a dict representation of a SourceOptionsFolder model - source_options_folder_model = {} - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsObject model - source_options_object_model = {} - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsSiteColl model - source_options_site_coll_model = {} - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsWebCrawl model - source_options_web_crawl_model = {} - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - # Construct a dict representation of a SourceOptionsBuckets model - source_options_buckets_model = {} - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - # Construct a dict representation of a SourceOptions model - source_options_model = {} - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - # Construct a dict representation of a Source model - source_model = {} - source_model['type'] = 'box' - source_model['credential_id'] = 'testString' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - conversions = conversions_model - enrichments = [enrichment_model] - normalizations = [normalization_operation_model] - source = source_model - - # Invoke method - response = _service.create_configuration( - environment_id, - name, - description=description, - conversions=conversions, - enrichments=enrichments, - normalizations=normalizations, - source=source, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['conversions'] == conversions_model - assert req_body['enrichments'] == [enrichment_model] - assert req_body['normalizations'] == [normalization_operation_model] - assert req_body['source'] == source_model - - def test_create_configuration_all_params_with_retries(self): - # Enable retries and run test_create_configuration_all_params. - _service.enable_retries() - self.test_create_configuration_all_params() - - # Disable retries and run test_create_configuration_all_params. - _service.disable_retries() - self.test_create_configuration_all_params() - - @responses.activate - def test_create_configuration_value_error(self): - """ - test_create_configuration_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Construct a dict representation of a FontSetting model - font_setting_model = {} - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - # Construct a dict representation of a PdfHeadingDetection model - pdf_heading_detection_model = {} - pdf_heading_detection_model['fonts'] = [font_setting_model] - - # Construct a dict representation of a PdfSettings model - pdf_settings_model = {} - pdf_settings_model['heading'] = pdf_heading_detection_model - - # Construct a dict representation of a WordStyle model - word_style_model = {} - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - # Construct a dict representation of a WordHeadingDetection model - word_heading_detection_model = {} - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - # Construct a dict representation of a WordSettings model - word_settings_model = {} - word_settings_model['heading'] = word_heading_detection_model - - # Construct a dict representation of a XPathPatterns model - x_path_patterns_model = {} - x_path_patterns_model['xpaths'] = ['testString'] - - # Construct a dict representation of a HtmlSettings model - html_settings_model = {} - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - # Construct a dict representation of a SegmentSettings model - segment_settings_model = {} - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - # Construct a dict representation of a NormalizationOperation model - normalization_operation_model = {} - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - # Construct a dict representation of a Conversions model - conversions_model = {} - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - # Construct a dict representation of a NluEnrichmentKeywords model - nlu_enrichment_keywords_model = {} - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentEntities model - nlu_enrichment_entities_model = {} - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentSentiment model - nlu_enrichment_sentiment_model = {} - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentEmotion model - nlu_enrichment_emotion_model = {} - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentSemanticRoles model - nlu_enrichment_semantic_roles_model = {} - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentRelations model - nlu_enrichment_relations_model = {} - nlu_enrichment_relations_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentConcepts model - nlu_enrichment_concepts_model = {} - nlu_enrichment_concepts_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentFeatures model - nlu_enrichment_features_model = {} - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - # Construct a dict representation of a Enrichment model - enrichment_model = {} - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'testString' - enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - # Construct a dict representation of a SourceSchedule model - source_schedule_model = {} - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - # Construct a dict representation of a SourceOptionsFolder model - source_options_folder_model = {} - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsObject model - source_options_object_model = {} - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsSiteColl model - source_options_site_coll_model = {} - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsWebCrawl model - source_options_web_crawl_model = {} - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - # Construct a dict representation of a SourceOptionsBuckets model - source_options_buckets_model = {} - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - # Construct a dict representation of a SourceOptions model - source_options_model = {} - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - # Construct a dict representation of a Source model - source_model = {} - source_model['type'] = 'box' - source_model['credential_id'] = 'testString' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - conversions = conversions_model - enrichments = [enrichment_model] - normalizations = [normalization_operation_model] - source = source_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "name": name, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_configuration(**req_copy) - - def test_create_configuration_value_error_with_retries(self): - # Enable retries and run test_create_configuration_value_error. - _service.enable_retries() - self.test_create_configuration_value_error() - - # Disable retries and run test_create_configuration_value_error. - _service.disable_retries() - self.test_create_configuration_value_error() - - -class TestListConfigurations: - """ - Test Class for list_configurations - """ - - @responses.activate - def test_list_configurations_all_params(self): - """ - list_configurations() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - - # Invoke method - response = _service.list_configurations( - environment_id, - name=name, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'name={}'.format(name) in query_string - - def test_list_configurations_all_params_with_retries(self): - # Enable retries and run test_list_configurations_all_params. - _service.enable_retries() - self.test_list_configurations_all_params() - - # Disable retries and run test_list_configurations_all_params. - _service.disable_retries() - self.test_list_configurations_all_params() - - @responses.activate - def test_list_configurations_required_params(self): - """ - test_list_configurations_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.list_configurations( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_configurations_required_params_with_retries(self): - # Enable retries and run test_list_configurations_required_params. - _service.enable_retries() - self.test_list_configurations_required_params() - - # Disable retries and run test_list_configurations_required_params. - _service.disable_retries() - self.test_list_configurations_required_params() - - @responses.activate - def test_list_configurations_value_error(self): - """ - test_list_configurations_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations') - mock_response = '{"configurations": [{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_configurations(**req_copy) - - def test_list_configurations_value_error_with_retries(self): - # Enable retries and run test_list_configurations_value_error. - _service.enable_retries() - self.test_list_configurations_value_error() - - # Disable retries and run test_list_configurations_value_error. - _service.disable_retries() - self.test_list_configurations_value_error() - - -class TestGetConfiguration: - """ - Test Class for get_configuration - """ - - @responses.activate - def test_get_configuration_all_params(self): - """ - get_configuration() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - - # Invoke method - response = _service.get_configuration( - environment_id, - configuration_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_configuration_all_params_with_retries(self): - # Enable retries and run test_get_configuration_all_params. - _service.enable_retries() - self.test_get_configuration_all_params() - - # Disable retries and run test_get_configuration_all_params. - _service.disable_retries() - self.test_get_configuration_all_params() - - @responses.activate - def test_get_configuration_value_error(self): - """ - test_get_configuration_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "configuration_id": configuration_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_configuration(**req_copy) - - def test_get_configuration_value_error_with_retries(self): - # Enable retries and run test_get_configuration_value_error. - _service.enable_retries() - self.test_get_configuration_value_error() - - # Disable retries and run test_get_configuration_value_error. - _service.disable_retries() - self.test_get_configuration_value_error() - - -class TestUpdateConfiguration: - """ - Test Class for update_configuration - """ - - @responses.activate - def test_update_configuration_all_params(self): - """ - update_configuration() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a FontSetting model - font_setting_model = {} - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - # Construct a dict representation of a PdfHeadingDetection model - pdf_heading_detection_model = {} - pdf_heading_detection_model['fonts'] = [font_setting_model] - - # Construct a dict representation of a PdfSettings model - pdf_settings_model = {} - pdf_settings_model['heading'] = pdf_heading_detection_model - - # Construct a dict representation of a WordStyle model - word_style_model = {} - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - # Construct a dict representation of a WordHeadingDetection model - word_heading_detection_model = {} - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - # Construct a dict representation of a WordSettings model - word_settings_model = {} - word_settings_model['heading'] = word_heading_detection_model - - # Construct a dict representation of a XPathPatterns model - x_path_patterns_model = {} - x_path_patterns_model['xpaths'] = ['testString'] - - # Construct a dict representation of a HtmlSettings model - html_settings_model = {} - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - # Construct a dict representation of a SegmentSettings model - segment_settings_model = {} - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - # Construct a dict representation of a NormalizationOperation model - normalization_operation_model = {} - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - # Construct a dict representation of a Conversions model - conversions_model = {} - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - # Construct a dict representation of a NluEnrichmentKeywords model - nlu_enrichment_keywords_model = {} - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentEntities model - nlu_enrichment_entities_model = {} - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentSentiment model - nlu_enrichment_sentiment_model = {} - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentEmotion model - nlu_enrichment_emotion_model = {} - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentSemanticRoles model - nlu_enrichment_semantic_roles_model = {} - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentRelations model - nlu_enrichment_relations_model = {} - nlu_enrichment_relations_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentConcepts model - nlu_enrichment_concepts_model = {} - nlu_enrichment_concepts_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentFeatures model - nlu_enrichment_features_model = {} - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - # Construct a dict representation of a Enrichment model - enrichment_model = {} - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'testString' - enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - # Construct a dict representation of a SourceSchedule model - source_schedule_model = {} - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - # Construct a dict representation of a SourceOptionsFolder model - source_options_folder_model = {} - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsObject model - source_options_object_model = {} - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsSiteColl model - source_options_site_coll_model = {} - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsWebCrawl model - source_options_web_crawl_model = {} - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - # Construct a dict representation of a SourceOptionsBuckets model - source_options_buckets_model = {} - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - # Construct a dict representation of a SourceOptions model - source_options_model = {} - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - # Construct a dict representation of a Source model - source_model = {} - source_model['type'] = 'box' - source_model['credential_id'] = 'testString' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - name = 'testString' - description = 'testString' - conversions = conversions_model - enrichments = [enrichment_model] - normalizations = [normalization_operation_model] - source = source_model - - # Invoke method - response = _service.update_configuration( - environment_id, - configuration_id, - name, - description=description, - conversions=conversions, - enrichments=enrichments, - normalizations=normalizations, - source=source, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['conversions'] == conversions_model - assert req_body['enrichments'] == [enrichment_model] - assert req_body['normalizations'] == [normalization_operation_model] - assert req_body['source'] == source_model - - def test_update_configuration_all_params_with_retries(self): - # Enable retries and run test_update_configuration_all_params. - _service.enable_retries() - self.test_update_configuration_all_params() - - # Disable retries and run test_update_configuration_all_params. - _service.disable_retries() - self.test_update_configuration_all_params() - - @responses.activate - def test_update_configuration_value_error(self): - """ - test_update_configuration_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "name": "name", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "description": "description", "conversions": {"pdf": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}]}}, "word": {"heading": {"fonts": [{"level": 5, "min_size": 8, "max_size": 8, "bold": true, "italic": true, "name": "name"}], "styles": [{"level": 5, "names": ["names"]}]}}, "html": {"exclude_tags_completely": ["exclude_tags_completely"], "exclude_tags_keep_content": ["exclude_tags_keep_content"], "keep_content": {"xpaths": ["xpaths"]}, "exclude_content": {"xpaths": ["xpaths"]}, "keep_tag_attributes": ["keep_tag_attributes"], "exclude_tag_attributes": ["exclude_tag_attributes"]}, "segment": {"enabled": false, "selector_tags": ["selector_tags"], "annotated_fields": ["annotated_fields"]}, "json_normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "image_text_recognition": true}, "enrichments": [{"description": "description", "destination_field": "destination_field", "source_field": "source_field", "overwrite": false, "enrichment": "enrichment", "ignore_downstream_errors": false, "options": {"features": {"keywords": {"sentiment": false, "emotion": false, "limit": 5}, "entities": {"sentiment": false, "emotion": false, "limit": 5, "mentions": true, "mention_types": false, "sentence_locations": true, "model": "model"}, "sentiment": {"document": true, "targets": ["target"]}, "emotion": {"document": true, "targets": ["target"]}, "categories": {"anyKey": "anyValue"}, "semantic_roles": {"entities": true, "keywords": true, "limit": 5}, "relations": {"model": "model"}, "concepts": {"limit": 5}}, "language": "ar", "model": "model"}}], "normalizations": [{"operation": "copy", "source_field": "source_field", "destination_field": "destination_field"}], "source": {"type": "box", "credential_id": "credential_id", "schedule": {"enabled": true, "time_zone": "America/New_York", "frequency": "daily"}, "options": {"folders": [{"owner_user_id": "owner_user_id", "folder_id": "folder_id", "limit": 5}], "objects": [{"name": "name", "limit": 5}], "site_collections": [{"site_collection_path": "site_collection_path", "limit": 5}], "urls": [{"url": "url", "limit_to_starting_hosts": true, "crawl_speed": "normal", "allow_untrusted_certificate": false, "maximum_hops": 2, "request_timeout": 30000, "override_robots_txt": false, "blacklist": ["blacklist"]}], "buckets": [{"name": "name", "limit": 5}], "crawl_all_buckets": false}}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a FontSetting model - font_setting_model = {} - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - # Construct a dict representation of a PdfHeadingDetection model - pdf_heading_detection_model = {} - pdf_heading_detection_model['fonts'] = [font_setting_model] - - # Construct a dict representation of a PdfSettings model - pdf_settings_model = {} - pdf_settings_model['heading'] = pdf_heading_detection_model - - # Construct a dict representation of a WordStyle model - word_style_model = {} - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - # Construct a dict representation of a WordHeadingDetection model - word_heading_detection_model = {} - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - # Construct a dict representation of a WordSettings model - word_settings_model = {} - word_settings_model['heading'] = word_heading_detection_model - - # Construct a dict representation of a XPathPatterns model - x_path_patterns_model = {} - x_path_patterns_model['xpaths'] = ['testString'] - - # Construct a dict representation of a HtmlSettings model - html_settings_model = {} - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - # Construct a dict representation of a SegmentSettings model - segment_settings_model = {} - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - # Construct a dict representation of a NormalizationOperation model - normalization_operation_model = {} - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - # Construct a dict representation of a Conversions model - conversions_model = {} - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - # Construct a dict representation of a NluEnrichmentKeywords model - nlu_enrichment_keywords_model = {} - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentEntities model - nlu_enrichment_entities_model = {} - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentSentiment model - nlu_enrichment_sentiment_model = {} - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentEmotion model - nlu_enrichment_emotion_model = {} - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - # Construct a dict representation of a NluEnrichmentSemanticRoles model - nlu_enrichment_semantic_roles_model = {} - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentRelations model - nlu_enrichment_relations_model = {} - nlu_enrichment_relations_model['model'] = 'testString' - - # Construct a dict representation of a NluEnrichmentConcepts model - nlu_enrichment_concepts_model = {} - nlu_enrichment_concepts_model['limit'] = 38 - - # Construct a dict representation of a NluEnrichmentFeatures model - nlu_enrichment_features_model = {} - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - # Construct a dict representation of a EnrichmentOptions model - enrichment_options_model = {} - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - # Construct a dict representation of a Enrichment model - enrichment_model = {} - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'testString' - enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - # Construct a dict representation of a SourceSchedule model - source_schedule_model = {} - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - # Construct a dict representation of a SourceOptionsFolder model - source_options_folder_model = {} - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsObject model - source_options_object_model = {} - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsSiteColl model - source_options_site_coll_model = {} - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - # Construct a dict representation of a SourceOptionsWebCrawl model - source_options_web_crawl_model = {} - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - # Construct a dict representation of a SourceOptionsBuckets model - source_options_buckets_model = {} - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - # Construct a dict representation of a SourceOptions model - source_options_model = {} - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - # Construct a dict representation of a Source model - source_model = {} - source_model['type'] = 'box' - source_model['credential_id'] = 'testString' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - name = 'testString' - description = 'testString' - conversions = conversions_model - enrichments = [enrichment_model] - normalizations = [normalization_operation_model] - source = source_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "configuration_id": configuration_id, - "name": name, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_configuration(**req_copy) - - def test_update_configuration_value_error_with_retries(self): - # Enable retries and run test_update_configuration_value_error. - _service.enable_retries() - self.test_update_configuration_value_error() - - # Disable retries and run test_update_configuration_value_error. - _service.disable_retries() - self.test_update_configuration_value_error() - - -class TestDeleteConfiguration: - """ - Test Class for delete_configuration - """ - - @responses.activate - def test_delete_configuration_all_params(self): - """ - delete_configuration() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - - # Invoke method - response = _service.delete_configuration( - environment_id, - configuration_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_configuration_all_params_with_retries(self): - # Enable retries and run test_delete_configuration_all_params. - _service.enable_retries() - self.test_delete_configuration_all_params() - - # Disable retries and run test_delete_configuration_all_params. - _service.disable_retries() - self.test_delete_configuration_all_params() - - @responses.activate - def test_delete_configuration_value_error(self): - """ - test_delete_configuration_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/configurations/testString') - mock_response = '{"configuration_id": "configuration_id", "status": "deleted", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - configuration_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "configuration_id": configuration_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_configuration(**req_copy) - - def test_delete_configuration_value_error_with_retries(self): - # Enable retries and run test_delete_configuration_value_error. - _service.enable_retries() - self.test_delete_configuration_value_error() - - # Disable retries and run test_delete_configuration_value_error. - _service.disable_retries() - self.test_delete_configuration_value_error() - - -# endregion -############################################################################## -# End of Service: Configurations -############################################################################## - -############################################################################## -# Start of Service: Collections -############################################################################## -# region - - -class TestCreateCollection: - """ - Test Class for create_collection - """ - - @responses.activate - def test_create_collection_all_params(self): - """ - create_collection() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - configuration_id = 'testString' - language = 'en' - - # Invoke method - response = _service.create_collection( - environment_id, - name, - description=description, - configuration_id=configuration_id, - language=language, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['configuration_id'] == 'testString' - assert req_body['language'] == 'en' - - def test_create_collection_all_params_with_retries(self): - # Enable retries and run test_create_collection_all_params. - _service.enable_retries() - self.test_create_collection_all_params() - - # Disable retries and run test_create_collection_all_params. - _service.disable_retries() - self.test_create_collection_all_params() - - @responses.activate - def test_create_collection_value_error(self): - """ - test_create_collection_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - description = 'testString' - configuration_id = 'testString' - language = 'en' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "name": name, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_collection(**req_copy) - - def test_create_collection_value_error_with_retries(self): - # Enable retries and run test_create_collection_value_error. - _service.enable_retries() - self.test_create_collection_value_error() - - # Disable retries and run test_create_collection_value_error. - _service.disable_retries() - self.test_create_collection_value_error() - - -class TestListCollections: - """ - Test Class for list_collections - """ - - @responses.activate - def test_list_collections_all_params(self): - """ - list_collections() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - - # Invoke method - response = _service.list_collections( - environment_id, - name=name, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'name={}'.format(name) in query_string - - def test_list_collections_all_params_with_retries(self): - # Enable retries and run test_list_collections_all_params. - _service.enable_retries() - self.test_list_collections_all_params() - - # Disable retries and run test_list_collections_all_params. - _service.disable_retries() - self.test_list_collections_all_params() - - @responses.activate - def test_list_collections_required_params(self): - """ - test_list_collections_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.list_collections( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_collections_required_params_with_retries(self): - # Enable retries and run test_list_collections_required_params. - _service.enable_retries() - self.test_list_collections_required_params() - - # Disable retries and run test_list_collections_required_params. - _service.disable_retries() - self.test_list_collections_required_params() - - @responses.activate - def test_list_collections_value_error(self): - """ - test_list_collections_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections') - mock_response = '{"collections": [{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_collections(**req_copy) - - def test_list_collections_value_error_with_retries(self): - # Enable retries and run test_list_collections_value_error. - _service.enable_retries() - self.test_list_collections_value_error() - - # Disable retries and run test_list_collections_value_error. - _service.disable_retries() - self.test_list_collections_value_error() - - -class TestGetCollection: - """ - Test Class for get_collection - """ - - @responses.activate - def test_get_collection_all_params(self): - """ - get_collection() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.get_collection( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_collection_all_params_with_retries(self): - # Enable retries and run test_get_collection_all_params. - _service.enable_retries() - self.test_get_collection_all_params() - - # Disable retries and run test_get_collection_all_params. - _service.disable_retries() - self.test_get_collection_all_params() - - @responses.activate - def test_get_collection_value_error(self): - """ - test_get_collection_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_collection(**req_copy) - - def test_get_collection_value_error_with_retries(self): - # Enable retries and run test_get_collection_value_error. - _service.enable_retries() - self.test_get_collection_value_error() - - # Disable retries and run test_get_collection_value_error. - _service.disable_retries() - self.test_get_collection_value_error() - - -class TestUpdateCollection: - """ - Test Class for update_collection - """ - - @responses.activate - def test_update_collection_all_params(self): - """ - update_collection() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - name = 'testString' - description = 'testString' - configuration_id = 'testString' - - # Invoke method - response = _service.update_collection( - environment_id, - collection_id, - name, - description=description, - configuration_id=configuration_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['configuration_id'] == 'testString' - - def test_update_collection_all_params_with_retries(self): - # Enable retries and run test_update_collection_all_params. - _service.enable_retries() - self.test_update_collection_all_params() - - # Disable retries and run test_update_collection_all_params. - _service.disable_retries() - self.test_update_collection_all_params() - - @responses.activate - def test_update_collection_value_error(self): - """ - test_update_collection_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "name": "name", "description": "description", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status": "active", "configuration_id": "configuration_id", "language": "language", "document_counts": {"available": 9, "processing": 10, "failed": 6, "pending": 7}, "disk_usage": {"used_bytes": 10}, "training_status": {"total_examples": 14, "available": false, "processing": true, "minimum_queries_added": false, "minimum_examples_added": true, "sufficient_label_diversity": true, "notices": 7, "successfully_trained": "2019-01-01T12:00:00.000Z", "data_updated": "2019-01-01T12:00:00.000Z"}, "crawl_status": {"source_crawl": {"status": "running", "next_crawl": "2019-01-01T12:00:00.000Z"}}, "smart_document_understanding": {"enabled": true, "total_annotated_pages": 21, "total_pages": 11, "total_documents": 15, "custom_fields": {"defined": 7, "maximum_allowed": 15}}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - name = 'testString' - description = 'testString' - configuration_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "name": name, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_collection(**req_copy) - - def test_update_collection_value_error_with_retries(self): - # Enable retries and run test_update_collection_value_error. - _service.enable_retries() - self.test_update_collection_value_error() - - # Disable retries and run test_update_collection_value_error. - _service.disable_retries() - self.test_update_collection_value_error() - - -class TestDeleteCollection: - """ - Test Class for delete_collection - """ - - @responses.activate - def test_delete_collection_all_params(self): - """ - delete_collection() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.delete_collection( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_collection_all_params_with_retries(self): - # Enable retries and run test_delete_collection_all_params. - _service.enable_retries() - self.test_delete_collection_all_params() - - # Disable retries and run test_delete_collection_all_params. - _service.disable_retries() - self.test_delete_collection_all_params() - - @responses.activate - def test_delete_collection_value_error(self): - """ - test_delete_collection_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString') - mock_response = '{"collection_id": "collection_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_collection(**req_copy) - - def test_delete_collection_value_error_with_retries(self): - # Enable retries and run test_delete_collection_value_error. - _service.enable_retries() - self.test_delete_collection_value_error() - - # Disable retries and run test_delete_collection_value_error. - _service.disable_retries() - self.test_delete_collection_value_error() - - -class TestListCollectionFields: - """ - Test Class for list_collection_fields - """ - - @responses.activate - def test_list_collection_fields_all_params(self): - """ - list_collection_fields() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.list_collection_fields( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_collection_fields_all_params_with_retries(self): - # Enable retries and run test_list_collection_fields_all_params. - _service.enable_retries() - self.test_list_collection_fields_all_params() - - # Disable retries and run test_list_collection_fields_all_params. - _service.disable_retries() - self.test_list_collection_fields_all_params() - - @responses.activate - def test_list_collection_fields_value_error(self): - """ - test_list_collection_fields_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/fields') - mock_response = '{"fields": [{"field": "field", "type": "nested"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_collection_fields(**req_copy) - - def test_list_collection_fields_value_error_with_retries(self): - # Enable retries and run test_list_collection_fields_value_error. - _service.enable_retries() - self.test_list_collection_fields_value_error() - - # Disable retries and run test_list_collection_fields_value_error. - _service.disable_retries() - self.test_list_collection_fields_value_error() - - -# endregion -############################################################################## -# End of Service: Collections -############################################################################## - -############################################################################## -# Start of Service: QueryModifications -############################################################################## -# region - - -class TestListExpansions: - """ - Test Class for list_expansions - """ - - @responses.activate - def test_list_expansions_all_params(self): - """ - list_expansions() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.list_expansions( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_expansions_all_params_with_retries(self): - # Enable retries and run test_list_expansions_all_params. - _service.enable_retries() - self.test_list_expansions_all_params() - - # Disable retries and run test_list_expansions_all_params. - _service.disable_retries() - self.test_list_expansions_all_params() - - @responses.activate - def test_list_expansions_value_error(self): - """ - test_list_expansions_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_expansions(**req_copy) - - def test_list_expansions_value_error_with_retries(self): - # Enable retries and run test_list_expansions_value_error. - _service.enable_retries() - self.test_list_expansions_value_error() - - # Disable retries and run test_list_expansions_value_error. - _service.disable_retries() - self.test_list_expansions_value_error() - - -class TestCreateExpansions: - """ - Test Class for create_expansions - """ - - @responses.activate - def test_create_expansions_all_params(self): - """ - create_expansions() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a Expansion model - expansion_model = {} - expansion_model['input_terms'] = ['testString'] - expansion_model['expanded_terms'] = ['testString'] - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - expansions = [expansion_model] - - # Invoke method - response = _service.create_expansions( - environment_id, - collection_id, - expansions, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['expansions'] == [expansion_model] - - def test_create_expansions_all_params_with_retries(self): - # Enable retries and run test_create_expansions_all_params. - _service.enable_retries() - self.test_create_expansions_all_params() - - # Disable retries and run test_create_expansions_all_params. - _service.disable_retries() - self.test_create_expansions_all_params() - - @responses.activate - def test_create_expansions_value_error(self): - """ - test_create_expansions_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - mock_response = '{"expansions": [{"input_terms": ["input_terms"], "expanded_terms": ["expanded_terms"]}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a Expansion model - expansion_model = {} - expansion_model['input_terms'] = ['testString'] - expansion_model['expanded_terms'] = ['testString'] - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - expansions = [expansion_model] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "expansions": expansions, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_expansions(**req_copy) - - def test_create_expansions_value_error_with_retries(self): - # Enable retries and run test_create_expansions_value_error. - _service.enable_retries() - self.test_create_expansions_value_error() - - # Disable retries and run test_create_expansions_value_error. - _service.disable_retries() - self.test_create_expansions_value_error() - - -class TestDeleteExpansions: - """ - Test Class for delete_expansions - """ - - @responses.activate - def test_delete_expansions_all_params(self): - """ - delete_expansions() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.delete_expansions( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 204 - - def test_delete_expansions_all_params_with_retries(self): - # Enable retries and run test_delete_expansions_all_params. - _service.enable_retries() - self.test_delete_expansions_all_params() - - # Disable retries and run test_delete_expansions_all_params. - _service.disable_retries() - self.test_delete_expansions_all_params() - - @responses.activate - def test_delete_expansions_value_error(self): - """ - test_delete_expansions_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/expansions') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_expansions(**req_copy) - - def test_delete_expansions_value_error_with_retries(self): - # Enable retries and run test_delete_expansions_value_error. - _service.enable_retries() - self.test_delete_expansions_value_error() - - # Disable retries and run test_delete_expansions_value_error. - _service.disable_retries() - self.test_delete_expansions_value_error() - - -class TestGetTokenizationDictionaryStatus: - """ - Test Class for get_tokenization_dictionary_status - """ - - @responses.activate - def test_get_tokenization_dictionary_status_all_params(self): - """ - get_tokenization_dictionary_status() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.get_tokenization_dictionary_status( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_tokenization_dictionary_status_all_params_with_retries(self): - # Enable retries and run test_get_tokenization_dictionary_status_all_params. - _service.enable_retries() - self.test_get_tokenization_dictionary_status_all_params() - - # Disable retries and run test_get_tokenization_dictionary_status_all_params. - _service.disable_retries() - self.test_get_tokenization_dictionary_status_all_params() - - @responses.activate - def test_get_tokenization_dictionary_status_value_error(self): - """ - test_get_tokenization_dictionary_status_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_tokenization_dictionary_status(**req_copy) - - def test_get_tokenization_dictionary_status_value_error_with_retries(self): - # Enable retries and run test_get_tokenization_dictionary_status_value_error. - _service.enable_retries() - self.test_get_tokenization_dictionary_status_value_error() - - # Disable retries and run test_get_tokenization_dictionary_status_value_error. - _service.disable_retries() - self.test_get_tokenization_dictionary_status_value_error() - - -class TestCreateTokenizationDictionary: - """ - Test Class for create_tokenization_dictionary - """ - - @responses.activate - def test_create_tokenization_dictionary_all_params(self): - """ - create_tokenization_dictionary() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Construct a dict representation of a TokenDictRule model - token_dict_rule_model = {} - token_dict_rule_model['text'] = 'testString' - token_dict_rule_model['tokens'] = ['testString'] - token_dict_rule_model['readings'] = ['testString'] - token_dict_rule_model['part_of_speech'] = 'testString' - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - tokenization_rules = [token_dict_rule_model] - - # Invoke method - response = _service.create_tokenization_dictionary( - environment_id, - collection_id, - tokenization_rules=tokenization_rules, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['tokenization_rules'] == [token_dict_rule_model] - - def test_create_tokenization_dictionary_all_params_with_retries(self): - # Enable retries and run test_create_tokenization_dictionary_all_params. - _service.enable_retries() - self.test_create_tokenization_dictionary_all_params() - - # Disable retries and run test_create_tokenization_dictionary_all_params. - _service.disable_retries() - self.test_create_tokenization_dictionary_all_params() - - @responses.activate - def test_create_tokenization_dictionary_required_params(self): - """ - test_create_tokenization_dictionary_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.create_tokenization_dictionary( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_create_tokenization_dictionary_required_params_with_retries(self): - # Enable retries and run test_create_tokenization_dictionary_required_params. - _service.enable_retries() - self.test_create_tokenization_dictionary_required_params() - - # Disable retries and run test_create_tokenization_dictionary_required_params. - _service.disable_retries() - self.test_create_tokenization_dictionary_required_params() - - @responses.activate - def test_create_tokenization_dictionary_value_error(self): - """ - test_create_tokenization_dictionary_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_tokenization_dictionary(**req_copy) - - def test_create_tokenization_dictionary_value_error_with_retries(self): - # Enable retries and run test_create_tokenization_dictionary_value_error. - _service.enable_retries() - self.test_create_tokenization_dictionary_value_error() - - # Disable retries and run test_create_tokenization_dictionary_value_error. - _service.disable_retries() - self.test_create_tokenization_dictionary_value_error() - - -class TestDeleteTokenizationDictionary: - """ - Test Class for delete_tokenization_dictionary - """ - - @responses.activate - def test_delete_tokenization_dictionary_all_params(self): - """ - delete_tokenization_dictionary() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.delete_tokenization_dictionary( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_tokenization_dictionary_all_params_with_retries(self): - # Enable retries and run test_delete_tokenization_dictionary_all_params. - _service.enable_retries() - self.test_delete_tokenization_dictionary_all_params() - - # Disable retries and run test_delete_tokenization_dictionary_all_params. - _service.disable_retries() - self.test_delete_tokenization_dictionary_all_params() - - @responses.activate - def test_delete_tokenization_dictionary_value_error(self): - """ - test_delete_tokenization_dictionary_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/tokenization_dictionary') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_tokenization_dictionary(**req_copy) - - def test_delete_tokenization_dictionary_value_error_with_retries(self): - # Enable retries and run test_delete_tokenization_dictionary_value_error. - _service.enable_retries() - self.test_delete_tokenization_dictionary_value_error() - - # Disable retries and run test_delete_tokenization_dictionary_value_error. - _service.disable_retries() - self.test_delete_tokenization_dictionary_value_error() - - -class TestGetStopwordListStatus: - """ - Test Class for get_stopword_list_status - """ - - @responses.activate - def test_get_stopword_list_status_all_params(self): - """ - get_stopword_list_status() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.get_stopword_list_status( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_stopword_list_status_all_params_with_retries(self): - # Enable retries and run test_get_stopword_list_status_all_params. - _service.enable_retries() - self.test_get_stopword_list_status_all_params() - - # Disable retries and run test_get_stopword_list_status_all_params. - _service.disable_retries() - self.test_get_stopword_list_status_all_params() - - @responses.activate - def test_get_stopword_list_status_value_error(self): - """ - test_get_stopword_list_status_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_stopword_list_status(**req_copy) - - def test_get_stopword_list_status_value_error_with_retries(self): - # Enable retries and run test_get_stopword_list_status_value_error. - _service.enable_retries() - self.test_get_stopword_list_status_value_error() - - # Disable retries and run test_get_stopword_list_status_value_error. - _service.disable_retries() - self.test_get_stopword_list_status_value_error() - - -class TestCreateStopwordList: - """ - Test Class for create_stopword_list - """ - - @responses.activate - def test_create_stopword_list_all_params(self): - """ - create_stopword_list() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - stopword_file = io.BytesIO(b'This is a mock file.').getvalue() - stopword_filename = 'testString' - - # Invoke method - response = _service.create_stopword_list( - environment_id, - collection_id, - stopword_file, - stopword_filename=stopword_filename, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_create_stopword_list_all_params_with_retries(self): - # Enable retries and run test_create_stopword_list_all_params. - _service.enable_retries() - self.test_create_stopword_list_all_params() - - # Disable retries and run test_create_stopword_list_all_params. - _service.disable_retries() - self.test_create_stopword_list_all_params() - - @responses.activate - def test_create_stopword_list_required_params(self): - """ - test_create_stopword_list_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - stopword_file = io.BytesIO(b'This is a mock file.').getvalue() - stopword_filename = 'testString' - - # Invoke method - response = _service.create_stopword_list( - environment_id, - collection_id, - stopword_file, - stopword_filename=stopword_filename, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_create_stopword_list_required_params_with_retries(self): - # Enable retries and run test_create_stopword_list_required_params. - _service.enable_retries() - self.test_create_stopword_list_required_params() - - # Disable retries and run test_create_stopword_list_required_params. - _service.disable_retries() - self.test_create_stopword_list_required_params() - - @responses.activate - def test_create_stopword_list_value_error(self): - """ - test_create_stopword_list_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - mock_response = '{"status": "active", "type": "type"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - stopword_file = io.BytesIO(b'This is a mock file.').getvalue() - stopword_filename = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "stopword_file": stopword_file, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_stopword_list(**req_copy) - - def test_create_stopword_list_value_error_with_retries(self): - # Enable retries and run test_create_stopword_list_value_error. - _service.enable_retries() - self.test_create_stopword_list_value_error() - - # Disable retries and run test_create_stopword_list_value_error. - _service.disable_retries() - self.test_create_stopword_list_value_error() - - -class TestDeleteStopwordList: - """ - Test Class for delete_stopword_list - """ - - @responses.activate - def test_delete_stopword_list_all_params(self): - """ - delete_stopword_list() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.delete_stopword_list( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_stopword_list_all_params_with_retries(self): - # Enable retries and run test_delete_stopword_list_all_params. - _service.enable_retries() - self.test_delete_stopword_list_all_params() - - # Disable retries and run test_delete_stopword_list_all_params. - _service.disable_retries() - self.test_delete_stopword_list_all_params() - - @responses.activate - def test_delete_stopword_list_value_error(self): - """ - test_delete_stopword_list_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/word_lists/stopwords') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_stopword_list(**req_copy) - - def test_delete_stopword_list_value_error_with_retries(self): - # Enable retries and run test_delete_stopword_list_value_error. - _service.enable_retries() - self.test_delete_stopword_list_value_error() - - # Disable retries and run test_delete_stopword_list_value_error. - _service.disable_retries() - self.test_delete_stopword_list_value_error() - - -# endregion -############################################################################## -# End of Service: QueryModifications -############################################################################## - -############################################################################## -# Start of Service: Documents -############################################################################## -# region - - -class TestAddDocument: - """ - Test Class for add_document - """ - - @responses.activate - def test_add_document_all_params(self): - """ - add_document() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/json' - metadata = 'testString' - - # Invoke method - response = _service.add_document( - environment_id, - collection_id, - file=file, - filename=filename, - file_content_type=file_content_type, - metadata=metadata, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_add_document_all_params_with_retries(self): - # Enable retries and run test_add_document_all_params. - _service.enable_retries() - self.test_add_document_all_params() - - # Disable retries and run test_add_document_all_params. - _service.disable_retries() - self.test_add_document_all_params() - - @responses.activate - def test_add_document_required_params(self): - """ - test_add_document_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.add_document( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_add_document_required_params_with_retries(self): - # Enable retries and run test_add_document_required_params. - _service.enable_retries() - self.test_add_document_required_params() - - # Disable retries and run test_add_document_required_params. - _service.disable_retries() - self.test_add_document_required_params() - - @responses.activate - def test_add_document_value_error(self): - """ - test_add_document_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.add_document(**req_copy) - - def test_add_document_value_error_with_retries(self): - # Enable retries and run test_add_document_value_error. - _service.enable_retries() - self.test_add_document_value_error() - - # Disable retries and run test_add_document_value_error. - _service.disable_retries() - self.test_add_document_value_error() - - -class TestGetDocumentStatus: - """ - Test Class for get_document_status - """ - - @responses.activate - def test_get_document_status_all_params(self): - """ - get_document_status() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Invoke method - response = _service.get_document_status( - environment_id, - collection_id, - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_document_status_all_params_with_retries(self): - # Enable retries and run test_get_document_status_all_params. - _service.enable_retries() - self.test_get_document_status_all_params() - - # Disable retries and run test_get_document_status_all_params. - _service.disable_retries() - self.test_get_document_status_all_params() - - @responses.activate - def test_get_document_status_value_error(self): - """ - test_get_document_status_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "configuration_id": "configuration_id", "status": "available", "status_description": "status_description", "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_document_status(**req_copy) - - def test_get_document_status_value_error_with_retries(self): - # Enable retries and run test_get_document_status_value_error. - _service.enable_retries() - self.test_get_document_status_value_error() - - # Disable retries and run test_get_document_status_value_error. - _service.disable_retries() - self.test_get_document_status_value_error() - - -class TestUpdateDocument: - """ - Test Class for update_document - """ - - @responses.activate - def test_update_document_all_params(self): - """ - update_document() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/json' - metadata = 'testString' - - # Invoke method - response = _service.update_document( - environment_id, - collection_id, - document_id, - file=file, - filename=filename, - file_content_type=file_content_type, - metadata=metadata, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_update_document_all_params_with_retries(self): - # Enable retries and run test_update_document_all_params. - _service.enable_retries() - self.test_update_document_all_params() - - # Disable retries and run test_update_document_all_params. - _service.disable_retries() - self.test_update_document_all_params() - - @responses.activate - def test_update_document_required_params(self): - """ - test_update_document_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Invoke method - response = _service.update_document( - environment_id, - collection_id, - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_update_document_required_params_with_retries(self): - # Enable retries and run test_update_document_required_params. - _service.enable_retries() - self.test_update_document_required_params() - - # Disable retries and run test_update_document_required_params. - _service.disable_retries() - self.test_update_document_required_params() - - @responses.activate - def test_update_document_value_error(self): - """ - test_update_document_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "processing", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_document(**req_copy) - - def test_update_document_value_error_with_retries(self): - # Enable retries and run test_update_document_value_error. - _service.enable_retries() - self.test_update_document_value_error() - - # Disable retries and run test_update_document_value_error. - _service.disable_retries() - self.test_update_document_value_error() - - -class TestDeleteDocument: - """ - Test Class for delete_document - """ - - @responses.activate - def test_delete_document_all_params(self): - """ - delete_document() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Invoke method - response = _service.delete_document( - environment_id, - collection_id, - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_document_all_params_with_retries(self): - # Enable retries and run test_delete_document_all_params. - _service.enable_retries() - self.test_delete_document_all_params() - - # Disable retries and run test_delete_document_all_params. - _service.disable_retries() - self.test_delete_document_all_params() - - @responses.activate - def test_delete_document_value_error(self): - """ - test_delete_document_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/documents/testString') - mock_response = '{"document_id": "document_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_document(**req_copy) - - def test_delete_document_value_error_with_retries(self): - # Enable retries and run test_delete_document_value_error. - _service.enable_retries() - self.test_delete_document_value_error() - - # Disable retries and run test_delete_document_value_error. - _service.disable_retries() - self.test_delete_document_value_error() - - -# endregion -############################################################################## -# End of Service: Documents -############################################################################## - -############################################################################## -# Start of Service: Queries -############################################################################## -# region - - -class TestQuery: - """ - Test Class for query - """ - - @responses.activate - def test_query_all_params(self): - """ - query() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - passages = True - aggregation = 'testString' - count = 10 - return_ = 'testString' - offset = 38 - sort = 'testString' - highlight = False - passages_fields = 'testString' - passages_count = 10 - passages_characters = 400 - deduplicate = False - deduplicate_field = 'testString' - similar = False - similar_document_ids = 'testString' - similar_fields = 'testString' - bias = 'testString' - spelling_suggestions = False - x_watson_logging_opt_out = False - - # Invoke method - response = _service.query( - environment_id, - collection_id, - filter=filter, - query=query, - natural_language_query=natural_language_query, - passages=passages, - aggregation=aggregation, - count=count, - return_=return_, - offset=offset, - sort=sort, - highlight=highlight, - passages_fields=passages_fields, - passages_count=passages_count, - passages_characters=passages_characters, - deduplicate=deduplicate, - deduplicate_field=deduplicate_field, - similar=similar, - similar_document_ids=similar_document_ids, - similar_fields=similar_fields, - bias=bias, - spelling_suggestions=spelling_suggestions, - x_watson_logging_opt_out=x_watson_logging_opt_out, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['filter'] == 'testString' - assert req_body['query'] == 'testString' - assert req_body['natural_language_query'] == 'testString' - assert req_body['passages'] == True - assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 10 - assert req_body['return'] == 'testString' - assert req_body['offset'] == 38 - assert req_body['sort'] == 'testString' - assert req_body['highlight'] == False - assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 10 - assert req_body['passages.characters'] == 400 - assert req_body['deduplicate'] == False - assert req_body['deduplicate.field'] == 'testString' - assert req_body['similar'] == False - assert req_body['similar.document_ids'] == 'testString' - assert req_body['similar.fields'] == 'testString' - assert req_body['bias'] == 'testString' - assert req_body['spelling_suggestions'] == False - - def test_query_all_params_with_retries(self): - # Enable retries and run test_query_all_params. - _service.enable_retries() - self.test_query_all_params() - - # Disable retries and run test_query_all_params. - _service.disable_retries() - self.test_query_all_params() - - @responses.activate - def test_query_required_params(self): - """ - test_query_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.query( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_query_required_params_with_retries(self): - # Enable retries and run test_query_required_params. - _service.enable_retries() - self.test_query_required_params() - - # Disable retries and run test_query_required_params. - _service.disable_retries() - self.test_query_required_params() - - @responses.activate - def test_query_value_error(self): - """ - test_query_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.query(**req_copy) - - def test_query_value_error_with_retries(self): - # Enable retries and run test_query_value_error. - _service.enable_retries() - self.test_query_value_error() - - # Disable retries and run test_query_value_error. - _service.disable_retries() - self.test_query_value_error() - - -class TestQueryNotices: - """ - Test Class for query_notices - """ - - @responses.activate - def test_query_notices_all_params(self): - """ - query_notices() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - passages = True - aggregation = 'testString' - count = 10 - return_ = ['testString'] - offset = 38 - sort = ['testString'] - highlight = False - passages_fields = ['testString'] - passages_count = 10 - passages_characters = 400 - deduplicate_field = 'testString' - similar = False - similar_document_ids = ['testString'] - similar_fields = ['testString'] - - # Invoke method - response = _service.query_notices( - environment_id, - collection_id, - filter=filter, - query=query, - natural_language_query=natural_language_query, - passages=passages, - aggregation=aggregation, - count=count, - return_=return_, - offset=offset, - sort=sort, - highlight=highlight, - passages_fields=passages_fields, - passages_count=passages_count, - passages_characters=passages_characters, - deduplicate_field=deduplicate_field, - similar=similar, - similar_document_ids=similar_document_ids, - similar_fields=similar_fields, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'filter={}'.format(filter) in query_string - assert 'query={}'.format(query) in query_string - assert 'natural_language_query={}'.format(natural_language_query) in query_string - assert 'passages={}'.format('true' if passages else 'false') in query_string - assert 'aggregation={}'.format(aggregation) in query_string - assert 'count={}'.format(count) in query_string - assert 'return={}'.format(','.join(return_)) in query_string - assert 'offset={}'.format(offset) in query_string - assert 'sort={}'.format(','.join(sort)) in query_string - assert 'highlight={}'.format('true' if highlight else 'false') in query_string - assert 'passages.fields={}'.format(','.join(passages_fields)) in query_string - assert 'passages.count={}'.format(passages_count) in query_string - assert 'passages.characters={}'.format(passages_characters) in query_string - assert 'deduplicate.field={}'.format(deduplicate_field) in query_string - assert 'similar={}'.format('true' if similar else 'false') in query_string - assert 'similar.document_ids={}'.format(','.join(similar_document_ids)) in query_string - assert 'similar.fields={}'.format(','.join(similar_fields)) in query_string - - def test_query_notices_all_params_with_retries(self): - # Enable retries and run test_query_notices_all_params. - _service.enable_retries() - self.test_query_notices_all_params() - - # Disable retries and run test_query_notices_all_params. - _service.disable_retries() - self.test_query_notices_all_params() - - @responses.activate - def test_query_notices_required_params(self): - """ - test_query_notices_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.query_notices( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_query_notices_required_params_with_retries(self): - # Enable retries and run test_query_notices_required_params. - _service.enable_retries() - self.test_query_notices_required_params() - - # Disable retries and run test_query_notices_required_params. - _service.disable_retries() - self.test_query_notices_required_params() - - @responses.activate - def test_query_notices_value_error(self): - """ - test_query_notices_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.query_notices(**req_copy) - - def test_query_notices_value_error_with_retries(self): - # Enable retries and run test_query_notices_value_error. - _service.enable_retries() - self.test_query_notices_value_error() - - # Disable retries and run test_query_notices_value_error. - _service.disable_retries() - self.test_query_notices_value_error() - - -class TestFederatedQuery: - """ - Test Class for federated_query - """ - - @responses.activate - def test_federated_query_all_params(self): - """ - federated_query() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = 'testString' - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - passages = True - aggregation = 'testString' - count = 10 - return_ = 'testString' - offset = 38 - sort = 'testString' - highlight = False - passages_fields = 'testString' - passages_count = 10 - passages_characters = 400 - deduplicate = False - deduplicate_field = 'testString' - similar = False - similar_document_ids = 'testString' - similar_fields = 'testString' - bias = 'testString' - x_watson_logging_opt_out = False - - # Invoke method - response = _service.federated_query( - environment_id, - collection_ids, - filter=filter, - query=query, - natural_language_query=natural_language_query, - passages=passages, - aggregation=aggregation, - count=count, - return_=return_, - offset=offset, - sort=sort, - highlight=highlight, - passages_fields=passages_fields, - passages_count=passages_count, - passages_characters=passages_characters, - deduplicate=deduplicate, - deduplicate_field=deduplicate_field, - similar=similar, - similar_document_ids=similar_document_ids, - similar_fields=similar_fields, - bias=bias, - x_watson_logging_opt_out=x_watson_logging_opt_out, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['collection_ids'] == 'testString' - assert req_body['filter'] == 'testString' - assert req_body['query'] == 'testString' - assert req_body['natural_language_query'] == 'testString' - assert req_body['passages'] == True - assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 10 - assert req_body['return'] == 'testString' - assert req_body['offset'] == 38 - assert req_body['sort'] == 'testString' - assert req_body['highlight'] == False - assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 10 - assert req_body['passages.characters'] == 400 - assert req_body['deduplicate'] == False - assert req_body['deduplicate.field'] == 'testString' - assert req_body['similar'] == False - assert req_body['similar.document_ids'] == 'testString' - assert req_body['similar.fields'] == 'testString' - assert req_body['bias'] == 'testString' - - def test_federated_query_all_params_with_retries(self): - # Enable retries and run test_federated_query_all_params. - _service.enable_retries() - self.test_federated_query_all_params() - - # Disable retries and run test_federated_query_all_params. - _service.disable_retries() - self.test_federated_query_all_params() - - @responses.activate - def test_federated_query_required_params(self): - """ - test_federated_query_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = 'testString' - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - passages = True - aggregation = 'testString' - count = 10 - return_ = 'testString' - offset = 38 - sort = 'testString' - highlight = False - passages_fields = 'testString' - passages_count = 10 - passages_characters = 400 - deduplicate = False - deduplicate_field = 'testString' - similar = False - similar_document_ids = 'testString' - similar_fields = 'testString' - bias = 'testString' - - # Invoke method - response = _service.federated_query( - environment_id, - collection_ids, - filter=filter, - query=query, - natural_language_query=natural_language_query, - passages=passages, - aggregation=aggregation, - count=count, - return_=return_, - offset=offset, - sort=sort, - highlight=highlight, - passages_fields=passages_fields, - passages_count=passages_count, - passages_characters=passages_characters, - deduplicate=deduplicate, - deduplicate_field=deduplicate_field, - similar=similar, - similar_document_ids=similar_document_ids, - similar_fields=similar_fields, - bias=bias, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['collection_ids'] == 'testString' - assert req_body['filter'] == 'testString' - assert req_body['query'] == 'testString' - assert req_body['natural_language_query'] == 'testString' - assert req_body['passages'] == True - assert req_body['aggregation'] == 'testString' - assert req_body['count'] == 10 - assert req_body['return'] == 'testString' - assert req_body['offset'] == 38 - assert req_body['sort'] == 'testString' - assert req_body['highlight'] == False - assert req_body['passages.fields'] == 'testString' - assert req_body['passages.count'] == 10 - assert req_body['passages.characters'] == 400 - assert req_body['deduplicate'] == False - assert req_body['deduplicate.field'] == 'testString' - assert req_body['similar'] == False - assert req_body['similar.document_ids'] == 'testString' - assert req_body['similar.fields'] == 'testString' - assert req_body['bias'] == 'testString' - - def test_federated_query_required_params_with_retries(self): - # Enable retries and run test_federated_query_required_params. - _service.enable_retries() - self.test_federated_query_required_params() - - # Disable retries and run test_federated_query_required_params. - _service.disable_retries() - self.test_federated_query_required_params() - - @responses.activate - def test_federated_query_value_error(self): - """ - test_federated_query_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/query') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18, "session_token": "session_token", "retrieval_details": {"document_retrieval_strategy": "untrained"}, "suggested_query": "suggested_query"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = 'testString' - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - passages = True - aggregation = 'testString' - count = 10 - return_ = 'testString' - offset = 38 - sort = 'testString' - highlight = False - passages_fields = 'testString' - passages_count = 10 - passages_characters = 400 - deduplicate = False - deduplicate_field = 'testString' - similar = False - similar_document_ids = 'testString' - similar_fields = 'testString' - bias = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_ids": collection_ids, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.federated_query(**req_copy) - - def test_federated_query_value_error_with_retries(self): - # Enable retries and run test_federated_query_value_error. - _service.enable_retries() - self.test_federated_query_value_error() - - # Disable retries and run test_federated_query_value_error. - _service.disable_retries() - self.test_federated_query_value_error() - - -class TestFederatedQueryNotices: - """ - Test Class for federated_query_notices - """ - - @responses.activate - def test_federated_query_notices_all_params(self): - """ - federated_query_notices() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = ['testString'] - filter = 'testString' - query = 'testString' - natural_language_query = 'testString' - aggregation = 'testString' - count = 10 - return_ = ['testString'] - offset = 38 - sort = ['testString'] - highlight = False - deduplicate_field = 'testString' - similar = False - similar_document_ids = ['testString'] - similar_fields = ['testString'] - - # Invoke method - response = _service.federated_query_notices( - environment_id, - collection_ids, - filter=filter, - query=query, - natural_language_query=natural_language_query, - aggregation=aggregation, - count=count, - return_=return_, - offset=offset, - sort=sort, - highlight=highlight, - deduplicate_field=deduplicate_field, - similar=similar, - similar_document_ids=similar_document_ids, - similar_fields=similar_fields, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string - assert 'filter={}'.format(filter) in query_string - assert 'query={}'.format(query) in query_string - assert 'natural_language_query={}'.format(natural_language_query) in query_string - assert 'aggregation={}'.format(aggregation) in query_string - assert 'count={}'.format(count) in query_string - assert 'return={}'.format(','.join(return_)) in query_string - assert 'offset={}'.format(offset) in query_string - assert 'sort={}'.format(','.join(sort)) in query_string - assert 'highlight={}'.format('true' if highlight else 'false') in query_string - assert 'deduplicate.field={}'.format(deduplicate_field) in query_string - assert 'similar={}'.format('true' if similar else 'false') in query_string - assert 'similar.document_ids={}'.format(','.join(similar_document_ids)) in query_string - assert 'similar.fields={}'.format(','.join(similar_fields)) in query_string - - def test_federated_query_notices_all_params_with_retries(self): - # Enable retries and run test_federated_query_notices_all_params. - _service.enable_retries() - self.test_federated_query_notices_all_params() - - # Disable retries and run test_federated_query_notices_all_params. - _service.disable_retries() - self.test_federated_query_notices_all_params() - - @responses.activate - def test_federated_query_notices_required_params(self): - """ - test_federated_query_notices_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = ['testString'] - - # Invoke method - response = _service.federated_query_notices( - environment_id, - collection_ids, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'collection_ids={}'.format(','.join(collection_ids)) in query_string - - def test_federated_query_notices_required_params_with_retries(self): - # Enable retries and run test_federated_query_notices_required_params. - _service.enable_retries() - self.test_federated_query_notices_required_params() - - # Disable retries and run test_federated_query_notices_required_params. - _service.disable_retries() - self.test_federated_query_notices_required_params() - - @responses.activate - def test_federated_query_notices_value_error(self): - """ - test_federated_query_notices_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/notices') - mock_response = '{"matching_results": 16, "results": [{"id": "id", "metadata": {"anyKey": "anyValue"}, "collection_id": "collection_id", "result_metadata": {"score": 5, "confidence": 10}, "code": 4, "filename": "filename", "file_type": "pdf", "sha1": "sha1", "notices": [{"notice_id": "notice_id", "created": "2019-01-01T12:00:00.000Z", "document_id": "document_id", "query_id": "query_id", "severity": "warning", "step": "step", "description": "description"}]}], "aggregations": [{"type": "filter", "match": "match", "matching_results": 16}], "passages": [{"document_id": "document_id", "passage_score": 13, "passage_text": "passage_text", "start_offset": 12, "end_offset": 10, "field": "field"}], "duplicates_removed": 18}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_ids = ['testString'] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_ids": collection_ids, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.federated_query_notices(**req_copy) - - def test_federated_query_notices_value_error_with_retries(self): - # Enable retries and run test_federated_query_notices_value_error. - _service.enable_retries() - self.test_federated_query_notices_value_error() - - # Disable retries and run test_federated_query_notices_value_error. - _service.disable_retries() - self.test_federated_query_notices_value_error() - - -class TestGetAutocompletion: - """ - Test Class for get_autocompletion - """ - - @responses.activate - def test_get_autocompletion_all_params(self): - """ - get_autocompletion() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') - mock_response = '{"completions": ["completions"]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - prefix = 'testString' - field = 'testString' - count = 5 - - # Invoke method - response = _service.get_autocompletion( - environment_id, - collection_id, - prefix, - field=field, - count=count, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'prefix={}'.format(prefix) in query_string - assert 'field={}'.format(field) in query_string - assert 'count={}'.format(count) in query_string - - def test_get_autocompletion_all_params_with_retries(self): - # Enable retries and run test_get_autocompletion_all_params. - _service.enable_retries() - self.test_get_autocompletion_all_params() - - # Disable retries and run test_get_autocompletion_all_params. - _service.disable_retries() - self.test_get_autocompletion_all_params() - - @responses.activate - def test_get_autocompletion_required_params(self): - """ - test_get_autocompletion_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') - mock_response = '{"completions": ["completions"]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - prefix = 'testString' - - # Invoke method - response = _service.get_autocompletion( - environment_id, - collection_id, - prefix, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'prefix={}'.format(prefix) in query_string - - def test_get_autocompletion_required_params_with_retries(self): - # Enable retries and run test_get_autocompletion_required_params. - _service.enable_retries() - self.test_get_autocompletion_required_params() - - # Disable retries and run test_get_autocompletion_required_params. - _service.disable_retries() - self.test_get_autocompletion_required_params() - - @responses.activate - def test_get_autocompletion_value_error(self): - """ - test_get_autocompletion_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/autocompletion') - mock_response = '{"completions": ["completions"]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - prefix = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "prefix": prefix, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_autocompletion(**req_copy) - - def test_get_autocompletion_value_error_with_retries(self): - # Enable retries and run test_get_autocompletion_value_error. - _service.enable_retries() - self.test_get_autocompletion_value_error() - - # Disable retries and run test_get_autocompletion_value_error. - _service.disable_retries() - self.test_get_autocompletion_value_error() - - -# endregion -############################################################################## -# End of Service: Queries -############################################################################## - -############################################################################## -# Start of Service: TrainingData -############################################################################## -# region - - -class TestListTrainingData: - """ - Test Class for list_training_data - """ - - @responses.activate - def test_list_training_data_all_params(self): - """ - list_training_data() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.list_training_data( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_training_data_all_params_with_retries(self): - # Enable retries and run test_list_training_data_all_params. - _service.enable_retries() - self.test_list_training_data_all_params() - - # Disable retries and run test_list_training_data_all_params. - _service.disable_retries() - self.test_list_training_data_all_params() - - @responses.activate - def test_list_training_data_value_error(self): - """ - test_list_training_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - mock_response = '{"environment_id": "environment_id", "collection_id": "collection_id", "queries": [{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_training_data(**req_copy) - - def test_list_training_data_value_error_with_retries(self): - # Enable retries and run test_list_training_data_value_error. - _service.enable_retries() - self.test_list_training_data_value_error() - - # Disable retries and run test_list_training_data_value_error. - _service.disable_retries() - self.test_list_training_data_value_error() - - -class TestAddTrainingData: - """ - Test Class for add_training_data - """ - - @responses.activate - def test_add_training_data_all_params(self): - """ - add_training_data() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a TrainingExample model - training_example_model = {} - training_example_model['document_id'] = 'testString' - training_example_model['cross_reference'] = 'testString' - training_example_model['relevance'] = 38 - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - natural_language_query = 'testString' - filter = 'testString' - examples = [training_example_model] - - # Invoke method - response = _service.add_training_data( - environment_id, - collection_id, - natural_language_query=natural_language_query, - filter=filter, - examples=examples, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['natural_language_query'] == 'testString' - assert req_body['filter'] == 'testString' - assert req_body['examples'] == [training_example_model] - - def test_add_training_data_all_params_with_retries(self): - # Enable retries and run test_add_training_data_all_params. - _service.enable_retries() - self.test_add_training_data_all_params() - - # Disable retries and run test_add_training_data_all_params. - _service.disable_retries() - self.test_add_training_data_all_params() - - @responses.activate - def test_add_training_data_value_error(self): - """ - test_add_training_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a TrainingExample model - training_example_model = {} - training_example_model['document_id'] = 'testString' - training_example_model['cross_reference'] = 'testString' - training_example_model['relevance'] = 38 - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - natural_language_query = 'testString' - filter = 'testString' - examples = [training_example_model] - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.add_training_data(**req_copy) - - def test_add_training_data_value_error_with_retries(self): - # Enable retries and run test_add_training_data_value_error. - _service.enable_retries() - self.test_add_training_data_value_error() - - # Disable retries and run test_add_training_data_value_error. - _service.disable_retries() - self.test_add_training_data_value_error() - - -class TestDeleteAllTrainingData: - """ - Test Class for delete_all_training_data - """ - - @responses.activate - def test_delete_all_training_data_all_params(self): - """ - delete_all_training_data() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Invoke method - response = _service.delete_all_training_data( - environment_id, - collection_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 204 - - def test_delete_all_training_data_all_params_with_retries(self): - # Enable retries and run test_delete_all_training_data_all_params. - _service.enable_retries() - self.test_delete_all_training_data_all_params() - - # Disable retries and run test_delete_all_training_data_all_params. - _service.disable_retries() - self.test_delete_all_training_data_all_params() - - @responses.activate - def test_delete_all_training_data_value_error(self): - """ - test_delete_all_training_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_all_training_data(**req_copy) - - def test_delete_all_training_data_value_error_with_retries(self): - # Enable retries and run test_delete_all_training_data_value_error. - _service.enable_retries() - self.test_delete_all_training_data_value_error() - - # Disable retries and run test_delete_all_training_data_value_error. - _service.disable_retries() - self.test_delete_all_training_data_value_error() - - -class TestGetTrainingData: - """ - Test Class for get_training_data - """ - - @responses.activate - def test_get_training_data_all_params(self): - """ - get_training_data() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Invoke method - response = _service.get_training_data( - environment_id, - collection_id, - query_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_training_data_all_params_with_retries(self): - # Enable retries and run test_get_training_data_all_params. - _service.enable_retries() - self.test_get_training_data_all_params() - - # Disable retries and run test_get_training_data_all_params. - _service.disable_retries() - self.test_get_training_data_all_params() - - @responses.activate - def test_get_training_data_value_error(self): - """ - test_get_training_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - mock_response = '{"query_id": "query_id", "natural_language_query": "natural_language_query", "filter": "filter", "examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_training_data(**req_copy) - - def test_get_training_data_value_error_with_retries(self): - # Enable retries and run test_get_training_data_value_error. - _service.enable_retries() - self.test_get_training_data_value_error() - - # Disable retries and run test_get_training_data_value_error. - _service.disable_retries() - self.test_get_training_data_value_error() - - -class TestDeleteTrainingData: - """ - Test Class for delete_training_data - """ - - @responses.activate - def test_delete_training_data_all_params(self): - """ - delete_training_data() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Invoke method - response = _service.delete_training_data( - environment_id, - collection_id, - query_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 204 - - def test_delete_training_data_all_params_with_retries(self): - # Enable retries and run test_delete_training_data_all_params. - _service.enable_retries() - self.test_delete_training_data_all_params() - - # Disable retries and run test_delete_training_data_all_params. - _service.disable_retries() - self.test_delete_training_data_all_params() - - @responses.activate - def test_delete_training_data_value_error(self): - """ - test_delete_training_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_training_data(**req_copy) - - def test_delete_training_data_value_error_with_retries(self): - # Enable retries and run test_delete_training_data_value_error. - _service.enable_retries() - self.test_delete_training_data_value_error() - - # Disable retries and run test_delete_training_data_value_error. - _service.disable_retries() - self.test_delete_training_data_value_error() - - -class TestListTrainingExamples: - """ - Test Class for list_training_examples - """ - - @responses.activate - def test_list_training_examples_all_params(self): - """ - list_training_examples() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') - mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Invoke method - response = _service.list_training_examples( - environment_id, - collection_id, - query_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_training_examples_all_params_with_retries(self): - # Enable retries and run test_list_training_examples_all_params. - _service.enable_retries() - self.test_list_training_examples_all_params() - - # Disable retries and run test_list_training_examples_all_params. - _service.disable_retries() - self.test_list_training_examples_all_params() - - @responses.activate - def test_list_training_examples_value_error(self): - """ - test_list_training_examples_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') - mock_response = '{"examples": [{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_training_examples(**req_copy) - - def test_list_training_examples_value_error_with_retries(self): - # Enable retries and run test_list_training_examples_value_error. - _service.enable_retries() - self.test_list_training_examples_value_error() - - # Disable retries and run test_list_training_examples_value_error. - _service.disable_retries() - self.test_list_training_examples_value_error() - - -class TestCreateTrainingExample: - """ - Test Class for create_training_example - """ - - @responses.activate - def test_create_training_example_all_params(self): - """ - create_training_example() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - document_id = 'testString' - cross_reference = 'testString' - relevance = 38 - - # Invoke method - response = _service.create_training_example( - environment_id, - collection_id, - query_id, - document_id=document_id, - cross_reference=cross_reference, - relevance=relevance, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['document_id'] == 'testString' - assert req_body['cross_reference'] == 'testString' - assert req_body['relevance'] == 38 - - def test_create_training_example_all_params_with_retries(self): - # Enable retries and run test_create_training_example_all_params. - _service.enable_retries() - self.test_create_training_example_all_params() - - # Disable retries and run test_create_training_example_all_params. - _service.disable_retries() - self.test_create_training_example_all_params() - - @responses.activate - def test_create_training_example_value_error(self): - """ - test_create_training_example_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - document_id = 'testString' - cross_reference = 'testString' - relevance = 38 - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_training_example(**req_copy) - - def test_create_training_example_value_error_with_retries(self): - # Enable retries and run test_create_training_example_value_error. - _service.enable_retries() - self.test_create_training_example_value_error() - - # Disable retries and run test_create_training_example_value_error. - _service.disable_retries() - self.test_create_training_example_value_error() - - -class TestDeleteTrainingExample: - """ - Test Class for delete_training_example - """ - - @responses.activate - def test_delete_training_example_all_params(self): - """ - delete_training_example() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - - # Invoke method - response = _service.delete_training_example( - environment_id, - collection_id, - query_id, - example_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 204 - - def test_delete_training_example_all_params_with_retries(self): - # Enable retries and run test_delete_training_example_all_params. - _service.enable_retries() - self.test_delete_training_example_all_params() - - # Disable retries and run test_delete_training_example_all_params. - _service.disable_retries() - self.test_delete_training_example_all_params() - - @responses.activate - def test_delete_training_example_value_error(self): - """ - test_delete_training_example_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - "example_id": example_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_training_example(**req_copy) - - def test_delete_training_example_value_error_with_retries(self): - # Enable retries and run test_delete_training_example_value_error. - _service.enable_retries() - self.test_delete_training_example_value_error() - - # Disable retries and run test_delete_training_example_value_error. - _service.disable_retries() - self.test_delete_training_example_value_error() - - -class TestUpdateTrainingExample: - """ - Test Class for update_training_example - """ - - @responses.activate - def test_update_training_example_all_params(self): - """ - update_training_example() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - cross_reference = 'testString' - relevance = 38 - - # Invoke method - response = _service.update_training_example( - environment_id, - collection_id, - query_id, - example_id, - cross_reference=cross_reference, - relevance=relevance, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['cross_reference'] == 'testString' - assert req_body['relevance'] == 38 - - def test_update_training_example_all_params_with_retries(self): - # Enable retries and run test_update_training_example_all_params. - _service.enable_retries() - self.test_update_training_example_all_params() - - # Disable retries and run test_update_training_example_all_params. - _service.disable_retries() - self.test_update_training_example_all_params() - - @responses.activate - def test_update_training_example_value_error(self): - """ - test_update_training_example_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - cross_reference = 'testString' - relevance = 38 - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - "example_id": example_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_training_example(**req_copy) - - def test_update_training_example_value_error_with_retries(self): - # Enable retries and run test_update_training_example_value_error. - _service.enable_retries() - self.test_update_training_example_value_error() - - # Disable retries and run test_update_training_example_value_error. - _service.disable_retries() - self.test_update_training_example_value_error() - - -class TestGetTrainingExample: - """ - Test Class for get_training_example - """ - - @responses.activate - def test_get_training_example_all_params(self): - """ - get_training_example() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - - # Invoke method - response = _service.get_training_example( - environment_id, - collection_id, - query_id, - example_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_training_example_all_params_with_retries(self): - # Enable retries and run test_get_training_example_all_params. - _service.enable_retries() - self.test_get_training_example_all_params() - - # Disable retries and run test_get_training_example_all_params. - _service.disable_retries() - self.test_get_training_example_all_params() - - @responses.activate - def test_get_training_example_value_error(self): - """ - test_get_training_example_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/collections/testString/training_data/testString/examples/testString') - mock_response = '{"document_id": "document_id", "cross_reference": "cross_reference", "relevance": 9}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - collection_id = 'testString' - query_id = 'testString' - example_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "collection_id": collection_id, - "query_id": query_id, - "example_id": example_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_training_example(**req_copy) - - def test_get_training_example_value_error_with_retries(self): - # Enable retries and run test_get_training_example_value_error. - _service.enable_retries() - self.test_get_training_example_value_error() - - # Disable retries and run test_get_training_example_value_error. - _service.disable_retries() - self.test_get_training_example_value_error() - - -# endregion -############################################################################## -# End of Service: TrainingData -############################################################################## - -############################################################################## -# Start of Service: UserData -############################################################################## -# region - - -class TestDeleteUserData: - """ - Test Class for delete_user_data - """ - - @responses.activate - def test_delete_user_data_all_params(self): - """ - delete_user_data() - """ - # Set up mock - url = preprocess_url('/v1/user_data') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - customer_id = 'testString' - - # Invoke method - response = _service.delete_user_data( - customer_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'customer_id={}'.format(customer_id) in query_string - - def test_delete_user_data_all_params_with_retries(self): - # Enable retries and run test_delete_user_data_all_params. - _service.enable_retries() - self.test_delete_user_data_all_params() - - # Disable retries and run test_delete_user_data_all_params. - _service.disable_retries() - self.test_delete_user_data_all_params() - - @responses.activate - def test_delete_user_data_value_error(self): - """ - test_delete_user_data_value_error() - """ - # Set up mock - url = preprocess_url('/v1/user_data') - responses.add( - responses.DELETE, - url, - status=200, - ) - - # Set up parameter values - customer_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "customer_id": customer_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_user_data(**req_copy) - - def test_delete_user_data_value_error_with_retries(self): - # Enable retries and run test_delete_user_data_value_error. - _service.enable_retries() - self.test_delete_user_data_value_error() - - # Disable retries and run test_delete_user_data_value_error. - _service.disable_retries() - self.test_delete_user_data_value_error() - - -# endregion -############################################################################## -# End of Service: UserData -############################################################################## - -############################################################################## -# Start of Service: EventsAndFeedback -############################################################################## -# region - - -class TestCreateEvent: - """ - Test Class for create_event - """ - - @responses.activate - def test_create_event_all_params(self): - """ - create_event() - """ - # Set up mock - url = preprocess_url('/v1/events') - mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Construct a dict representation of a EventData model - event_data_model = {} - event_data_model['environment_id'] = 'testString' - event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = '2019-01-01T12:00:00Z' - event_data_model['display_rank'] = 38 - event_data_model['collection_id'] = 'testString' - event_data_model['document_id'] = 'testString' - - # Set up parameter values - type = 'click' - data = event_data_model - - # Invoke method - response = _service.create_event( - type, - data, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 201 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['type'] == 'click' - assert req_body['data'] == event_data_model - - def test_create_event_all_params_with_retries(self): - # Enable retries and run test_create_event_all_params. - _service.enable_retries() - self.test_create_event_all_params() - - # Disable retries and run test_create_event_all_params. - _service.disable_retries() - self.test_create_event_all_params() - - @responses.activate - def test_create_event_value_error(self): - """ - test_create_event_value_error() - """ - # Set up mock - url = preprocess_url('/v1/events') - mock_response = '{"type": "click", "data": {"environment_id": "environment_id", "session_token": "session_token", "client_timestamp": "2019-01-01T12:00:00.000Z", "display_rank": 12, "collection_id": "collection_id", "document_id": "document_id", "query_id": "query_id"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=201, - ) - - # Construct a dict representation of a EventData model - event_data_model = {} - event_data_model['environment_id'] = 'testString' - event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = '2019-01-01T12:00:00Z' - event_data_model['display_rank'] = 38 - event_data_model['collection_id'] = 'testString' - event_data_model['document_id'] = 'testString' - - # Set up parameter values - type = 'click' - data = event_data_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "type": type, - "data": data, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_event(**req_copy) - - def test_create_event_value_error_with_retries(self): - # Enable retries and run test_create_event_value_error. - _service.enable_retries() - self.test_create_event_value_error() - - # Disable retries and run test_create_event_value_error. - _service.disable_retries() - self.test_create_event_value_error() - - -class TestQueryLog: - """ - Test Class for query_log - """ - - @responses.activate - def test_query_log_all_params(self): - """ - query_log() - """ - # Set up mock - url = preprocess_url('/v1/logs') - mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - filter = 'testString' - query = 'testString' - count = 10 - offset = 38 - sort = ['testString'] - - # Invoke method - response = _service.query_log( - filter=filter, - query=query, - count=count, - offset=offset, - sort=sort, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'filter={}'.format(filter) in query_string - assert 'query={}'.format(query) in query_string - assert 'count={}'.format(count) in query_string - assert 'offset={}'.format(offset) in query_string - assert 'sort={}'.format(','.join(sort)) in query_string - - def test_query_log_all_params_with_retries(self): - # Enable retries and run test_query_log_all_params. - _service.enable_retries() - self.test_query_log_all_params() - - # Disable retries and run test_query_log_all_params. - _service.disable_retries() - self.test_query_log_all_params() - - @responses.activate - def test_query_log_required_params(self): - """ - test_query_log_required_params() - """ - # Set up mock - url = preprocess_url('/v1/logs') - mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.query_log() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_query_log_required_params_with_retries(self): - # Enable retries and run test_query_log_required_params. - _service.enable_retries() - self.test_query_log_required_params() - - # Disable retries and run test_query_log_required_params. - _service.disable_retries() - self.test_query_log_required_params() - - @responses.activate - def test_query_log_value_error(self): - """ - test_query_log_value_error() - """ - # Set up mock - url = preprocess_url('/v1/logs') - mock_response = '{"matching_results": 16, "results": [{"environment_id": "environment_id", "customer_id": "customer_id", "document_type": "query", "natural_language_query": "natural_language_query", "document_results": {"results": [{"position": 8, "document_id": "document_id", "score": 5, "confidence": 10, "collection_id": "collection_id"}], "count": 5}, "created_timestamp": "2019-01-01T12:00:00.000Z", "client_timestamp": "2019-01-01T12:00:00.000Z", "query_id": "query_id", "session_token": "session_token", "collection_id": "collection_id", "display_rank": 12, "document_id": "document_id", "event_type": "click", "result_type": "document"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.query_log(**req_copy) - - def test_query_log_value_error_with_retries(self): - # Enable retries and run test_query_log_value_error. - _service.enable_retries() - self.test_query_log_value_error() - - # Disable retries and run test_query_log_value_error. - _service.disable_retries() - self.test_query_log_value_error() - - -class TestGetMetricsQuery: - """ - Test Class for get_metrics_query - """ - - @responses.activate - def test_get_metrics_query_all_params(self): - """ - get_metrics_query() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - start_time = string_to_datetime('2019-01-01T12:00:00.000Z') - end_time = string_to_datetime('2019-01-01T12:00:00.000Z') - result_type = 'document' - - # Invoke method - response = _service.get_metrics_query( - start_time=start_time, - end_time=end_time, - result_type=result_type, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'result_type={}'.format(result_type) in query_string - - def test_get_metrics_query_all_params_with_retries(self): - # Enable retries and run test_get_metrics_query_all_params. - _service.enable_retries() - self.test_get_metrics_query_all_params() - - # Disable retries and run test_get_metrics_query_all_params. - _service.disable_retries() - self.test_get_metrics_query_all_params() - - @responses.activate - def test_get_metrics_query_required_params(self): - """ - test_get_metrics_query_required_params() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.get_metrics_query() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_metrics_query_required_params_with_retries(self): - # Enable retries and run test_get_metrics_query_required_params. - _service.enable_retries() - self.test_get_metrics_query_required_params() - - # Disable retries and run test_get_metrics_query_required_params. - _service.disable_retries() - self.test_get_metrics_query_required_params() - - @responses.activate - def test_get_metrics_query_value_error(self): - """ - test_get_metrics_query_value_error() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_metrics_query(**req_copy) - - def test_get_metrics_query_value_error_with_retries(self): - # Enable retries and run test_get_metrics_query_value_error. - _service.enable_retries() - self.test_get_metrics_query_value_error() - - # Disable retries and run test_get_metrics_query_value_error. - _service.disable_retries() - self.test_get_metrics_query_value_error() - - -class TestGetMetricsQueryEvent: - """ - Test Class for get_metrics_query_event - """ - - @responses.activate - def test_get_metrics_query_event_all_params(self): - """ - get_metrics_query_event() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_event') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - start_time = string_to_datetime('2019-01-01T12:00:00.000Z') - end_time = string_to_datetime('2019-01-01T12:00:00.000Z') - result_type = 'document' - - # Invoke method - response = _service.get_metrics_query_event( - start_time=start_time, - end_time=end_time, - result_type=result_type, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'result_type={}'.format(result_type) in query_string - - def test_get_metrics_query_event_all_params_with_retries(self): - # Enable retries and run test_get_metrics_query_event_all_params. - _service.enable_retries() - self.test_get_metrics_query_event_all_params() - - # Disable retries and run test_get_metrics_query_event_all_params. - _service.disable_retries() - self.test_get_metrics_query_event_all_params() - - @responses.activate - def test_get_metrics_query_event_required_params(self): - """ - test_get_metrics_query_event_required_params() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_event') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.get_metrics_query_event() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_metrics_query_event_required_params_with_retries(self): - # Enable retries and run test_get_metrics_query_event_required_params. - _service.enable_retries() - self.test_get_metrics_query_event_required_params() - - # Disable retries and run test_get_metrics_query_event_required_params. - _service.disable_retries() - self.test_get_metrics_query_event_required_params() - - @responses.activate - def test_get_metrics_query_event_value_error(self): - """ - test_get_metrics_query_event_value_error() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_event') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_metrics_query_event(**req_copy) - - def test_get_metrics_query_event_value_error_with_retries(self): - # Enable retries and run test_get_metrics_query_event_value_error. - _service.enable_retries() - self.test_get_metrics_query_event_value_error() - - # Disable retries and run test_get_metrics_query_event_value_error. - _service.disable_retries() - self.test_get_metrics_query_event_value_error() - - -class TestGetMetricsQueryNoResults: - """ - Test Class for get_metrics_query_no_results - """ - - @responses.activate - def test_get_metrics_query_no_results_all_params(self): - """ - get_metrics_query_no_results() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - start_time = string_to_datetime('2019-01-01T12:00:00.000Z') - end_time = string_to_datetime('2019-01-01T12:00:00.000Z') - result_type = 'document' - - # Invoke method - response = _service.get_metrics_query_no_results( - start_time=start_time, - end_time=end_time, - result_type=result_type, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'result_type={}'.format(result_type) in query_string - - def test_get_metrics_query_no_results_all_params_with_retries(self): - # Enable retries and run test_get_metrics_query_no_results_all_params. - _service.enable_retries() - self.test_get_metrics_query_no_results_all_params() - - # Disable retries and run test_get_metrics_query_no_results_all_params. - _service.disable_retries() - self.test_get_metrics_query_no_results_all_params() - - @responses.activate - def test_get_metrics_query_no_results_required_params(self): - """ - test_get_metrics_query_no_results_required_params() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.get_metrics_query_no_results() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_metrics_query_no_results_required_params_with_retries(self): - # Enable retries and run test_get_metrics_query_no_results_required_params. - _service.enable_retries() - self.test_get_metrics_query_no_results_required_params() - - # Disable retries and run test_get_metrics_query_no_results_required_params. - _service.disable_retries() - self.test_get_metrics_query_no_results_required_params() - - @responses.activate - def test_get_metrics_query_no_results_value_error(self): - """ - test_get_metrics_query_no_results_value_error() - """ - # Set up mock - url = preprocess_url('/v1/metrics/number_of_queries_with_no_search_results') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_metrics_query_no_results(**req_copy) - - def test_get_metrics_query_no_results_value_error_with_retries(self): - # Enable retries and run test_get_metrics_query_no_results_value_error. - _service.enable_retries() - self.test_get_metrics_query_no_results_value_error() - - # Disable retries and run test_get_metrics_query_no_results_value_error. - _service.disable_retries() - self.test_get_metrics_query_no_results_value_error() - - -class TestGetMetricsEventRate: - """ - Test Class for get_metrics_event_rate - """ - - @responses.activate - def test_get_metrics_event_rate_all_params(self): - """ - get_metrics_event_rate() - """ - # Set up mock - url = preprocess_url('/v1/metrics/event_rate') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - start_time = string_to_datetime('2019-01-01T12:00:00.000Z') - end_time = string_to_datetime('2019-01-01T12:00:00.000Z') - result_type = 'document' - - # Invoke method - response = _service.get_metrics_event_rate( - start_time=start_time, - end_time=end_time, - result_type=result_type, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'result_type={}'.format(result_type) in query_string - - def test_get_metrics_event_rate_all_params_with_retries(self): - # Enable retries and run test_get_metrics_event_rate_all_params. - _service.enable_retries() - self.test_get_metrics_event_rate_all_params() - - # Disable retries and run test_get_metrics_event_rate_all_params. - _service.disable_retries() - self.test_get_metrics_event_rate_all_params() - - @responses.activate - def test_get_metrics_event_rate_required_params(self): - """ - test_get_metrics_event_rate_required_params() - """ - # Set up mock - url = preprocess_url('/v1/metrics/event_rate') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.get_metrics_event_rate() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_metrics_event_rate_required_params_with_retries(self): - # Enable retries and run test_get_metrics_event_rate_required_params. - _service.enable_retries() - self.test_get_metrics_event_rate_required_params() - - # Disable retries and run test_get_metrics_event_rate_required_params. - _service.disable_retries() - self.test_get_metrics_event_rate_required_params() - - @responses.activate - def test_get_metrics_event_rate_value_error(self): - """ - test_get_metrics_event_rate_value_error() - """ - # Set up mock - url = preprocess_url('/v1/metrics/event_rate') - mock_response = '{"aggregations": [{"interval": "interval", "event_type": "event_type", "results": [{"key_as_string": "2019-01-01T12:00:00.000Z", "key": 3, "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_metrics_event_rate(**req_copy) - - def test_get_metrics_event_rate_value_error_with_retries(self): - # Enable retries and run test_get_metrics_event_rate_value_error. - _service.enable_retries() - self.test_get_metrics_event_rate_value_error() - - # Disable retries and run test_get_metrics_event_rate_value_error. - _service.disable_retries() - self.test_get_metrics_event_rate_value_error() - - -class TestGetMetricsQueryTokenEvent: - """ - Test Class for get_metrics_query_token_event - """ - - @responses.activate - def test_get_metrics_query_token_event_all_params(self): - """ - get_metrics_query_token_event() - """ - # Set up mock - url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') - mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - count = 10 - - # Invoke method - response = _service.get_metrics_query_token_event( - count=count, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'count={}'.format(count) in query_string - - def test_get_metrics_query_token_event_all_params_with_retries(self): - # Enable retries and run test_get_metrics_query_token_event_all_params. - _service.enable_retries() - self.test_get_metrics_query_token_event_all_params() - - # Disable retries and run test_get_metrics_query_token_event_all_params. - _service.disable_retries() - self.test_get_metrics_query_token_event_all_params() - - @responses.activate - def test_get_metrics_query_token_event_required_params(self): - """ - test_get_metrics_query_token_event_required_params() - """ - # Set up mock - url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') - mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.get_metrics_query_token_event() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_metrics_query_token_event_required_params_with_retries(self): - # Enable retries and run test_get_metrics_query_token_event_required_params. - _service.enable_retries() - self.test_get_metrics_query_token_event_required_params() - - # Disable retries and run test_get_metrics_query_token_event_required_params. - _service.disable_retries() - self.test_get_metrics_query_token_event_required_params() - - @responses.activate - def test_get_metrics_query_token_event_value_error(self): - """ - test_get_metrics_query_token_event_value_error() - """ - # Set up mock - url = preprocess_url('/v1/metrics/top_query_tokens_with_event_rate') - mock_response = '{"aggregations": [{"event_type": "event_type", "results": [{"key": "key", "matching_results": 16, "event_rate": 10}]}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_metrics_query_token_event(**req_copy) - - def test_get_metrics_query_token_event_value_error_with_retries(self): - # Enable retries and run test_get_metrics_query_token_event_value_error. - _service.enable_retries() - self.test_get_metrics_query_token_event_value_error() - - # Disable retries and run test_get_metrics_query_token_event_value_error. - _service.disable_retries() - self.test_get_metrics_query_token_event_value_error() - - -# endregion -############################################################################## -# End of Service: EventsAndFeedback -############################################################################## - -############################################################################## -# Start of Service: Credentials -############################################################################## -# region - - -class TestListCredentials: - """ - Test Class for list_credentials - """ - - @responses.activate - def test_list_credentials_all_params(self): - """ - list_credentials() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials') - mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.list_credentials( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_credentials_all_params_with_retries(self): - # Enable retries and run test_list_credentials_all_params. - _service.enable_retries() - self.test_list_credentials_all_params() - - # Disable retries and run test_list_credentials_all_params. - _service.disable_retries() - self.test_list_credentials_all_params() - - @responses.activate - def test_list_credentials_value_error(self): - """ - test_list_credentials_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials') - mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_credentials(**req_copy) - - def test_list_credentials_value_error_with_retries(self): - # Enable retries and run test_list_credentials_value_error. - _service.enable_retries() - self.test_list_credentials_value_error() - - # Disable retries and run test_list_credentials_value_error. - _service.disable_retries() - self.test_list_credentials_value_error() - - -class TestCreateCredentials: - """ - Test Class for create_credentials - """ - - @responses.activate - def test_create_credentials_all_params(self): - """ - create_credentials() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a CredentialDetails model - credential_details_model = {} - credential_details_model['credential_type'] = 'oauth2' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'testString' - credential_details_model['username'] = 'testString' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - # Construct a dict representation of a StatusDetails model - status_details_model = {} - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - # Set up parameter values - environment_id = 'testString' - source_type = 'box' - credential_details = credential_details_model - status = status_details_model - - # Invoke method - response = _service.create_credentials( - environment_id, - source_type=source_type, - credential_details=credential_details, - status=status, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['source_type'] == 'box' - assert req_body['credential_details'] == credential_details_model - assert req_body['status'] == status_details_model - - def test_create_credentials_all_params_with_retries(self): - # Enable retries and run test_create_credentials_all_params. - _service.enable_retries() - self.test_create_credentials_all_params() - - # Disable retries and run test_create_credentials_all_params. - _service.disable_retries() - self.test_create_credentials_all_params() - - @responses.activate - def test_create_credentials_value_error(self): - """ - test_create_credentials_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a CredentialDetails model - credential_details_model = {} - credential_details_model['credential_type'] = 'oauth2' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'testString' - credential_details_model['username'] = 'testString' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - # Construct a dict representation of a StatusDetails model - status_details_model = {} - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - # Set up parameter values - environment_id = 'testString' - source_type = 'box' - credential_details = credential_details_model - status = status_details_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_credentials(**req_copy) - - def test_create_credentials_value_error_with_retries(self): - # Enable retries and run test_create_credentials_value_error. - _service.enable_retries() - self.test_create_credentials_value_error() - - # Disable retries and run test_create_credentials_value_error. - _service.disable_retries() - self.test_create_credentials_value_error() - - -class TestGetCredentials: - """ - Test Class for get_credentials - """ - - @responses.activate - def test_get_credentials_all_params(self): - """ - get_credentials() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - - # Invoke method - response = _service.get_credentials( - environment_id, - credential_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_credentials_all_params_with_retries(self): - # Enable retries and run test_get_credentials_all_params. - _service.enable_retries() - self.test_get_credentials_all_params() - - # Disable retries and run test_get_credentials_all_params. - _service.disable_retries() - self.test_get_credentials_all_params() - - @responses.activate - def test_get_credentials_value_error(self): - """ - test_get_credentials_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "credential_id": credential_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_credentials(**req_copy) - - def test_get_credentials_value_error_with_retries(self): - # Enable retries and run test_get_credentials_value_error. - _service.enable_retries() - self.test_get_credentials_value_error() - - # Disable retries and run test_get_credentials_value_error. - _service.disable_retries() - self.test_get_credentials_value_error() - - -class TestUpdateCredentials: - """ - Test Class for update_credentials - """ - - @responses.activate - def test_update_credentials_all_params(self): - """ - update_credentials() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a CredentialDetails model - credential_details_model = {} - credential_details_model['credential_type'] = 'oauth2' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'testString' - credential_details_model['username'] = 'testString' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - # Construct a dict representation of a StatusDetails model - status_details_model = {} - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - source_type = 'box' - credential_details = credential_details_model - status = status_details_model - - # Invoke method - response = _service.update_credentials( - environment_id, - credential_id, - source_type=source_type, - credential_details=credential_details, - status=status, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['source_type'] == 'box' - assert req_body['credential_details'] == credential_details_model - assert req_body['status'] == status_details_model - - def test_update_credentials_all_params_with_retries(self): - # Enable retries and run test_update_credentials_all_params. - _service.enable_retries() - self.test_update_credentials_all_params() - - # Disable retries and run test_update_credentials_all_params. - _service.disable_retries() - self.test_update_credentials_all_params() - - @responses.activate - def test_update_credentials_value_error(self): - """ - test_update_credentials_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' - responses.add( - responses.PUT, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Construct a dict representation of a CredentialDetails model - credential_details_model = {} - credential_details_model['credential_type'] = 'oauth2' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'testString' - credential_details_model['username'] = 'testString' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - # Construct a dict representation of a StatusDetails model - status_details_model = {} - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - source_type = 'box' - credential_details = credential_details_model - status = status_details_model - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "credential_id": credential_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.update_credentials(**req_copy) - - def test_update_credentials_value_error_with_retries(self): - # Enable retries and run test_update_credentials_value_error. - _service.enable_retries() - self.test_update_credentials_value_error() - - # Disable retries and run test_update_credentials_value_error. - _service.disable_retries() - self.test_update_credentials_value_error() - - -class TestDeleteCredentials: - """ - Test Class for delete_credentials - """ - - @responses.activate - def test_delete_credentials_all_params(self): - """ - delete_credentials() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - - # Invoke method - response = _service.delete_credentials( - environment_id, - credential_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_credentials_all_params_with_retries(self): - # Enable retries and run test_delete_credentials_all_params. - _service.enable_retries() - self.test_delete_credentials_all_params() - - # Disable retries and run test_delete_credentials_all_params. - _service.disable_retries() - self.test_delete_credentials_all_params() - - @responses.activate - def test_delete_credentials_value_error(self): - """ - test_delete_credentials_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "status": "deleted"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - credential_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "credential_id": credential_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_credentials(**req_copy) - - def test_delete_credentials_value_error_with_retries(self): - # Enable retries and run test_delete_credentials_value_error. - _service.enable_retries() - self.test_delete_credentials_value_error() - - # Disable retries and run test_delete_credentials_value_error. - _service.disable_retries() - self.test_delete_credentials_value_error() - - -# endregion -############################################################################## -# End of Service: Credentials -############################################################################## - -############################################################################## -# Start of Service: GatewayConfiguration -############################################################################## -# region - - -class TestListGateways: - """ - Test Class for list_gateways - """ - - @responses.activate - def test_list_gateways_all_params(self): - """ - list_gateways() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways') - mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.list_gateways( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_gateways_all_params_with_retries(self): - # Enable retries and run test_list_gateways_all_params. - _service.enable_retries() - self.test_list_gateways_all_params() - - # Disable retries and run test_list_gateways_all_params. - _service.disable_retries() - self.test_list_gateways_all_params() - - @responses.activate - def test_list_gateways_value_error(self): - """ - test_list_gateways_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways') - mock_response = '{"gateways": [{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_gateways(**req_copy) - - def test_list_gateways_value_error_with_retries(self): - # Enable retries and run test_list_gateways_value_error. - _service.enable_retries() - self.test_list_gateways_value_error() - - # Disable retries and run test_list_gateways_value_error. - _service.disable_retries() - self.test_list_gateways_value_error() - - -class TestCreateGateway: - """ - Test Class for create_gateway - """ - - @responses.activate - def test_create_gateway_all_params(self): - """ - create_gateway() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways') - mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - name = 'testString' - - # Invoke method - response = _service.create_gateway( - environment_id, - name=name, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - - def test_create_gateway_all_params_with_retries(self): - # Enable retries and run test_create_gateway_all_params. - _service.enable_retries() - self.test_create_gateway_all_params() - - # Disable retries and run test_create_gateway_all_params. - _service.disable_retries() - self.test_create_gateway_all_params() - - @responses.activate - def test_create_gateway_required_params(self): - """ - test_create_gateway_required_params() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways') - mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Invoke method - response = _service.create_gateway( - environment_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_create_gateway_required_params_with_retries(self): - # Enable retries and run test_create_gateway_required_params. - _service.enable_retries() - self.test_create_gateway_required_params() - - # Disable retries and run test_create_gateway_required_params. - _service.disable_retries() - self.test_create_gateway_required_params() - - @responses.activate - def test_create_gateway_value_error(self): - """ - test_create_gateway_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways') - mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_gateway(**req_copy) - - def test_create_gateway_value_error_with_retries(self): - # Enable retries and run test_create_gateway_value_error. - _service.enable_retries() - self.test_create_gateway_value_error() - - # Disable retries and run test_create_gateway_value_error. - _service.disable_retries() - self.test_create_gateway_value_error() - - -class TestGetGateway: - """ - Test Class for get_gateway - """ - - @responses.activate - def test_get_gateway_all_params(self): - """ - get_gateway() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways/testString') - mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - gateway_id = 'testString' - - # Invoke method - response = _service.get_gateway( - environment_id, - gateway_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_gateway_all_params_with_retries(self): - # Enable retries and run test_get_gateway_all_params. - _service.enable_retries() - self.test_get_gateway_all_params() - - # Disable retries and run test_get_gateway_all_params. - _service.disable_retries() - self.test_get_gateway_all_params() - - @responses.activate - def test_get_gateway_value_error(self): - """ - test_get_gateway_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways/testString') - mock_response = '{"gateway_id": "gateway_id", "name": "name", "status": "connected", "token": "token", "token_id": "token_id"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - gateway_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "gateway_id": gateway_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_gateway(**req_copy) - - def test_get_gateway_value_error_with_retries(self): - # Enable retries and run test_get_gateway_value_error. - _service.enable_retries() - self.test_get_gateway_value_error() - - # Disable retries and run test_get_gateway_value_error. - _service.disable_retries() - self.test_get_gateway_value_error() - - -class TestDeleteGateway: - """ - Test Class for delete_gateway - """ - - @responses.activate - def test_delete_gateway_all_params(self): - """ - delete_gateway() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways/testString') - mock_response = '{"gateway_id": "gateway_id", "status": "status"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - gateway_id = 'testString' - - # Invoke method - response = _service.delete_gateway( - environment_id, - gateway_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_gateway_all_params_with_retries(self): - # Enable retries and run test_delete_gateway_all_params. - _service.enable_retries() - self.test_delete_gateway_all_params() - - # Disable retries and run test_delete_gateway_all_params. - _service.disable_retries() - self.test_delete_gateway_all_params() - - @responses.activate - def test_delete_gateway_value_error(self): - """ - test_delete_gateway_value_error() - """ - # Set up mock - url = preprocess_url('/v1/environments/testString/gateways/testString') - mock_response = '{"gateway_id": "gateway_id", "status": "status"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - environment_id = 'testString' - gateway_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "environment_id": environment_id, - "gateway_id": gateway_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_gateway(**req_copy) - - def test_delete_gateway_value_error_with_retries(self): - # Enable retries and run test_delete_gateway_value_error. - _service.enable_retries() - self.test_delete_gateway_value_error() - - # Disable retries and run test_delete_gateway_value_error. - _service.disable_retries() - self.test_delete_gateway_value_error() - - -# endregion -############################################################################## -# End of Service: GatewayConfiguration -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region - - -class TestModel_Collection: - """ - Test Class for Collection - """ - - def test_collection_serialization(self): - """ - Test serialization/deserialization for Collection - """ - - # Construct dict forms of any model objects needed in order to build this model. - - document_counts_model = {} # DocumentCounts - - collection_disk_usage_model = {} # CollectionDiskUsage - - training_status_model = {} # TrainingStatus - training_status_model['total_examples'] = 0 - training_status_model['available'] = False - training_status_model['processing'] = False - training_status_model['minimum_queries_added'] = False - training_status_model['minimum_examples_added'] = False - training_status_model['sufficient_label_diversity'] = False - training_status_model['notices'] = 0 - training_status_model['successfully_trained'] = '2019-01-01T12:00:00Z' - training_status_model['data_updated'] = '2019-01-01T12:00:00Z' - - source_status_model = {} # SourceStatus - source_status_model['status'] = 'complete' - source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' - - collection_crawl_status_model = {} # CollectionCrawlStatus - collection_crawl_status_model['source_crawl'] = source_status_model - - sdu_status_custom_fields_model = {} # SduStatusCustomFields - sdu_status_custom_fields_model['defined'] = 26 - sdu_status_custom_fields_model['maximum_allowed'] = 5 - - sdu_status_model = {} # SduStatus - sdu_status_model['enabled'] = True - sdu_status_model['total_annotated_pages'] = 0 - sdu_status_model['total_pages'] = 0 - sdu_status_model['total_documents'] = 0 - sdu_status_model['custom_fields'] = sdu_status_custom_fields_model - - # Construct a json representation of a Collection model - collection_model_json = {} - collection_model_json['name'] = 'testString' - collection_model_json['description'] = 'testString' - collection_model_json['configuration_id'] = 'testString' - collection_model_json['language'] = 'testString' - collection_model_json['document_counts'] = document_counts_model - collection_model_json['disk_usage'] = collection_disk_usage_model - collection_model_json['training_status'] = training_status_model - collection_model_json['crawl_status'] = collection_crawl_status_model - collection_model_json['smart_document_understanding'] = sdu_status_model - - # Construct a model instance of Collection by calling from_dict on the json representation - collection_model = Collection.from_dict(collection_model_json) - assert collection_model != False - - # Construct a model instance of Collection by calling from_dict on the json representation - collection_model_dict = Collection.from_dict(collection_model_json).__dict__ - collection_model2 = Collection(**collection_model_dict) - - # Verify the model instances are equivalent - assert collection_model == collection_model2 - - # Convert model instance back to dict and verify no loss of data - collection_model_json2 = collection_model.to_dict() - assert collection_model_json2 == collection_model_json - - -class TestModel_CollectionCrawlStatus: - """ - Test Class for CollectionCrawlStatus - """ - - def test_collection_crawl_status_serialization(self): - """ - Test serialization/deserialization for CollectionCrawlStatus - """ - - # Construct dict forms of any model objects needed in order to build this model. - - source_status_model = {} # SourceStatus - source_status_model['status'] = 'running' - source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' - - # Construct a json representation of a CollectionCrawlStatus model - collection_crawl_status_model_json = {} - collection_crawl_status_model_json['source_crawl'] = source_status_model - - # Construct a model instance of CollectionCrawlStatus by calling from_dict on the json representation - collection_crawl_status_model = CollectionCrawlStatus.from_dict(collection_crawl_status_model_json) - assert collection_crawl_status_model != False - - # Construct a model instance of CollectionCrawlStatus by calling from_dict on the json representation - collection_crawl_status_model_dict = CollectionCrawlStatus.from_dict(collection_crawl_status_model_json).__dict__ - collection_crawl_status_model2 = CollectionCrawlStatus(**collection_crawl_status_model_dict) - - # Verify the model instances are equivalent - assert collection_crawl_status_model == collection_crawl_status_model2 - - # Convert model instance back to dict and verify no loss of data - collection_crawl_status_model_json2 = collection_crawl_status_model.to_dict() - assert collection_crawl_status_model_json2 == collection_crawl_status_model_json - - -class TestModel_CollectionDiskUsage: - """ - Test Class for CollectionDiskUsage - """ - - def test_collection_disk_usage_serialization(self): - """ - Test serialization/deserialization for CollectionDiskUsage - """ - - # Construct a json representation of a CollectionDiskUsage model - collection_disk_usage_model_json = {} - - # Construct a model instance of CollectionDiskUsage by calling from_dict on the json representation - collection_disk_usage_model = CollectionDiskUsage.from_dict(collection_disk_usage_model_json) - assert collection_disk_usage_model != False - - # Construct a model instance of CollectionDiskUsage by calling from_dict on the json representation - collection_disk_usage_model_dict = CollectionDiskUsage.from_dict(collection_disk_usage_model_json).__dict__ - collection_disk_usage_model2 = CollectionDiskUsage(**collection_disk_usage_model_dict) - - # Verify the model instances are equivalent - assert collection_disk_usage_model == collection_disk_usage_model2 - - # Convert model instance back to dict and verify no loss of data - collection_disk_usage_model_json2 = collection_disk_usage_model.to_dict() - assert collection_disk_usage_model_json2 == collection_disk_usage_model_json - - -class TestModel_CollectionUsage: - """ - Test Class for CollectionUsage - """ - - def test_collection_usage_serialization(self): - """ - Test serialization/deserialization for CollectionUsage - """ - - # Construct a json representation of a CollectionUsage model - collection_usage_model_json = {} - - # Construct a model instance of CollectionUsage by calling from_dict on the json representation - collection_usage_model = CollectionUsage.from_dict(collection_usage_model_json) - assert collection_usage_model != False - - # Construct a model instance of CollectionUsage by calling from_dict on the json representation - collection_usage_model_dict = CollectionUsage.from_dict(collection_usage_model_json).__dict__ - collection_usage_model2 = CollectionUsage(**collection_usage_model_dict) - - # Verify the model instances are equivalent - assert collection_usage_model == collection_usage_model2 - - # Convert model instance back to dict and verify no loss of data - collection_usage_model_json2 = collection_usage_model.to_dict() - assert collection_usage_model_json2 == collection_usage_model_json - - -class TestModel_Completions: - """ - Test Class for Completions - """ - - def test_completions_serialization(self): - """ - Test serialization/deserialization for Completions - """ - - # Construct a json representation of a Completions model - completions_model_json = {} - completions_model_json['completions'] = ['testString'] - - # Construct a model instance of Completions by calling from_dict on the json representation - completions_model = Completions.from_dict(completions_model_json) - assert completions_model != False - - # Construct a model instance of Completions by calling from_dict on the json representation - completions_model_dict = Completions.from_dict(completions_model_json).__dict__ - completions_model2 = Completions(**completions_model_dict) - - # Verify the model instances are equivalent - assert completions_model == completions_model2 - - # Convert model instance back to dict and verify no loss of data - completions_model_json2 = completions_model.to_dict() - assert completions_model_json2 == completions_model_json - - -class TestModel_Configuration: - """ - Test Class for Configuration - """ - - def test_configuration_serialization(self): - """ - Test serialization/deserialization for Configuration - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - pdf_heading_detection_model = {} # PdfHeadingDetection - pdf_heading_detection_model['fonts'] = [font_setting_model] - - pdf_settings_model = {} # PdfSettings - pdf_settings_model['heading'] = pdf_heading_detection_model - - word_style_model = {} # WordStyle - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - word_heading_detection_model = {} # WordHeadingDetection - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - word_settings_model = {} # WordSettings - word_settings_model['heading'] = word_heading_detection_model - - x_path_patterns_model = {} # XPathPatterns - x_path_patterns_model['xpaths'] = ['testString'] - - html_settings_model = {} # HtmlSettings - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['span'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - segment_settings_model = {} # SegmentSettings - segment_settings_model['enabled'] = True - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['custom-field-1', 'custom-field-2'] - - normalization_operation_model = {} # NormalizationOperation - normalization_operation_model['operation'] = 'move' - normalization_operation_model['source_field'] = 'extracted_metadata.title' - normalization_operation_model['destination_field'] = 'metadata.title' - - conversions_model = {} # Conversions - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = False - nlu_enrichment_keywords_model['limit'] = 50 - - nlu_enrichment_entities_model = {} # NluEnrichmentEntities - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = False - nlu_enrichment_entities_model['limit'] = 50 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'WKS-model-id' - - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['IBM', 'Watson'] - - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['IBM', 'Watson'] - - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 50 - - nlu_enrichment_relations_model = {} # NluEnrichmentRelations - nlu_enrichment_relations_model['model'] = 'WKS-model-id' - - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts - nlu_enrichment_concepts_model['limit'] = 8 - - nlu_enrichment_features_model = {} # NluEnrichmentFeatures - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - enrichment_options_model = {} # EnrichmentOptions - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - enrichment_model = {} # Enrichment - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'enriched_title' - enrichment_model['source_field'] = 'title' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'natural_language_understanding' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - source_schedule_model = {} # SourceSchedule - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'weekly' - - source_options_folder_model = {} # SourceOptionsFolder - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - source_options_object_model = {} # SourceOptionsObject - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - source_options_site_coll_model = {} # SourceOptionsSiteColl - source_options_site_coll_model['site_collection_path'] = '/sites/TestSiteA' - source_options_site_coll_model['limit'] = 10 - - source_options_web_crawl_model = {} # SourceOptionsWebCrawl - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - source_options_buckets_model = {} # SourceOptionsBuckets - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - source_options_model = {} # SourceOptions - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - source_model = {} # Source - source_model['type'] = 'salesforce' - source_model['credential_id'] = '00ad0000-0000-11e8-ba89-0ed5f00f718b' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - # Construct a json representation of a Configuration model - configuration_model_json = {} - configuration_model_json['name'] = 'testString' - configuration_model_json['description'] = 'testString' - configuration_model_json['conversions'] = conversions_model - configuration_model_json['enrichments'] = [enrichment_model] - configuration_model_json['normalizations'] = [normalization_operation_model] - configuration_model_json['source'] = source_model - - # Construct a model instance of Configuration by calling from_dict on the json representation - configuration_model = Configuration.from_dict(configuration_model_json) - assert configuration_model != False - - # Construct a model instance of Configuration by calling from_dict on the json representation - configuration_model_dict = Configuration.from_dict(configuration_model_json).__dict__ - configuration_model2 = Configuration(**configuration_model_dict) - - # Verify the model instances are equivalent - assert configuration_model == configuration_model2 - - # Convert model instance back to dict and verify no loss of data - configuration_model_json2 = configuration_model.to_dict() - assert configuration_model_json2 == configuration_model_json - - -class TestModel_Conversions: - """ - Test Class for Conversions - """ - - def test_conversions_serialization(self): - """ - Test serialization/deserialization for Conversions - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - pdf_heading_detection_model = {} # PdfHeadingDetection - pdf_heading_detection_model['fonts'] = [font_setting_model] - - pdf_settings_model = {} # PdfSettings - pdf_settings_model['heading'] = pdf_heading_detection_model - - word_style_model = {} # WordStyle - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - word_heading_detection_model = {} # WordHeadingDetection - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - word_settings_model = {} # WordSettings - word_settings_model['heading'] = word_heading_detection_model - - x_path_patterns_model = {} # XPathPatterns - x_path_patterns_model['xpaths'] = ['testString'] - - html_settings_model = {} # HtmlSettings - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - segment_settings_model = {} # SegmentSettings - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - normalization_operation_model = {} # NormalizationOperation - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - # Construct a json representation of a Conversions model - conversions_model_json = {} - conversions_model_json['pdf'] = pdf_settings_model - conversions_model_json['word'] = word_settings_model - conversions_model_json['html'] = html_settings_model - conversions_model_json['segment'] = segment_settings_model - conversions_model_json['json_normalizations'] = [normalization_operation_model] - conversions_model_json['image_text_recognition'] = True - - # Construct a model instance of Conversions by calling from_dict on the json representation - conversions_model = Conversions.from_dict(conversions_model_json) - assert conversions_model != False - - # Construct a model instance of Conversions by calling from_dict on the json representation - conversions_model_dict = Conversions.from_dict(conversions_model_json).__dict__ - conversions_model2 = Conversions(**conversions_model_dict) - - # Verify the model instances are equivalent - assert conversions_model == conversions_model2 - - # Convert model instance back to dict and verify no loss of data - conversions_model_json2 = conversions_model.to_dict() - assert conversions_model_json2 == conversions_model_json - - -class TestModel_CreateEventResponse: - """ - Test Class for CreateEventResponse - """ - - def test_create_event_response_serialization(self): - """ - Test serialization/deserialization for CreateEventResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - event_data_model = {} # EventData - event_data_model['environment_id'] = 'testString' - event_data_model['session_token'] = 'testString' - event_data_model['client_timestamp'] = '2019-01-01T12:00:00Z' - event_data_model['display_rank'] = 38 - event_data_model['collection_id'] = 'testString' - event_data_model['document_id'] = 'testString' - - # Construct a json representation of a CreateEventResponse model - create_event_response_model_json = {} - create_event_response_model_json['type'] = 'click' - create_event_response_model_json['data'] = event_data_model - - # Construct a model instance of CreateEventResponse by calling from_dict on the json representation - create_event_response_model = CreateEventResponse.from_dict(create_event_response_model_json) - assert create_event_response_model != False - - # Construct a model instance of CreateEventResponse by calling from_dict on the json representation - create_event_response_model_dict = CreateEventResponse.from_dict(create_event_response_model_json).__dict__ - create_event_response_model2 = CreateEventResponse(**create_event_response_model_dict) - - # Verify the model instances are equivalent - assert create_event_response_model == create_event_response_model2 - - # Convert model instance back to dict and verify no loss of data - create_event_response_model_json2 = create_event_response_model.to_dict() - assert create_event_response_model_json2 == create_event_response_model_json - - -class TestModel_CredentialDetails: - """ - Test Class for CredentialDetails - """ - - def test_credential_details_serialization(self): - """ - Test serialization/deserialization for CredentialDetails - """ - - # Construct a json representation of a CredentialDetails model - credential_details_model_json = {} - credential_details_model_json['credential_type'] = 'oauth2' - credential_details_model_json['client_id'] = 'testString' - credential_details_model_json['enterprise_id'] = 'testString' - credential_details_model_json['url'] = 'testString' - credential_details_model_json['username'] = 'testString' - credential_details_model_json['organization_url'] = 'testString' - credential_details_model_json['site_collection.path'] = 'testString' - credential_details_model_json['client_secret'] = 'testString' - credential_details_model_json['public_key_id'] = 'testString' - credential_details_model_json['private_key'] = 'testString' - credential_details_model_json['passphrase'] = 'testString' - credential_details_model_json['password'] = 'testString' - credential_details_model_json['gateway_id'] = 'testString' - credential_details_model_json['source_version'] = 'online' - credential_details_model_json['web_application_url'] = 'testString' - credential_details_model_json['domain'] = 'testString' - credential_details_model_json['endpoint'] = 'testString' - credential_details_model_json['access_key_id'] = 'testString' - credential_details_model_json['secret_access_key'] = 'testString' - - # Construct a model instance of CredentialDetails by calling from_dict on the json representation - credential_details_model = CredentialDetails.from_dict(credential_details_model_json) - assert credential_details_model != False - - # Construct a model instance of CredentialDetails by calling from_dict on the json representation - credential_details_model_dict = CredentialDetails.from_dict(credential_details_model_json).__dict__ - credential_details_model2 = CredentialDetails(**credential_details_model_dict) - - # Verify the model instances are equivalent - assert credential_details_model == credential_details_model2 - - # Convert model instance back to dict and verify no loss of data - credential_details_model_json2 = credential_details_model.to_dict() - assert credential_details_model_json2 == credential_details_model_json - - -class TestModel_Credentials: - """ - Test Class for Credentials - """ - - def test_credentials_serialization(self): - """ - Test serialization/deserialization for Credentials - """ - - # Construct dict forms of any model objects needed in order to build this model. - - credential_details_model = {} # CredentialDetails - credential_details_model['credential_type'] = 'username_password' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'login.salesforce.com' - credential_details_model['username'] = 'user@email.address' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - status_details_model = {} # StatusDetails - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - # Construct a json representation of a Credentials model - credentials_model_json = {} - credentials_model_json['source_type'] = 'box' - credentials_model_json['credential_details'] = credential_details_model - credentials_model_json['status'] = status_details_model - - # Construct a model instance of Credentials by calling from_dict on the json representation - credentials_model = Credentials.from_dict(credentials_model_json) - assert credentials_model != False - - # Construct a model instance of Credentials by calling from_dict on the json representation - credentials_model_dict = Credentials.from_dict(credentials_model_json).__dict__ - credentials_model2 = Credentials(**credentials_model_dict) - - # Verify the model instances are equivalent - assert credentials_model == credentials_model2 - - # Convert model instance back to dict and verify no loss of data - credentials_model_json2 = credentials_model.to_dict() - assert credentials_model_json2 == credentials_model_json - - -class TestModel_CredentialsList: - """ - Test Class for CredentialsList - """ - - def test_credentials_list_serialization(self): - """ - Test serialization/deserialization for CredentialsList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - credential_details_model = {} # CredentialDetails - credential_details_model['credential_type'] = 'username_password' - credential_details_model['client_id'] = 'testString' - credential_details_model['enterprise_id'] = 'testString' - credential_details_model['url'] = 'login.salesforce.com' - credential_details_model['username'] = 'user@email.address' - credential_details_model['organization_url'] = 'testString' - credential_details_model['site_collection.path'] = 'testString' - credential_details_model['client_secret'] = 'testString' - credential_details_model['public_key_id'] = 'testString' - credential_details_model['private_key'] = 'testString' - credential_details_model['passphrase'] = 'testString' - credential_details_model['password'] = 'testString' - credential_details_model['gateway_id'] = 'testString' - credential_details_model['source_version'] = 'online' - credential_details_model['web_application_url'] = 'testString' - credential_details_model['domain'] = 'testString' - credential_details_model['endpoint'] = 'testString' - credential_details_model['access_key_id'] = 'testString' - credential_details_model['secret_access_key'] = 'testString' - - status_details_model = {} # StatusDetails - status_details_model['authenticated'] = True - status_details_model['error_message'] = 'testString' - - credentials_model = {} # Credentials - credentials_model['source_type'] = 'salesforce' - credentials_model['credential_details'] = credential_details_model - credentials_model['status'] = status_details_model - - # Construct a json representation of a CredentialsList model - credentials_list_model_json = {} - credentials_list_model_json['credentials'] = [credentials_model] - - # Construct a model instance of CredentialsList by calling from_dict on the json representation - credentials_list_model = CredentialsList.from_dict(credentials_list_model_json) - assert credentials_list_model != False - - # Construct a model instance of CredentialsList by calling from_dict on the json representation - credentials_list_model_dict = CredentialsList.from_dict(credentials_list_model_json).__dict__ - credentials_list_model2 = CredentialsList(**credentials_list_model_dict) - - # Verify the model instances are equivalent - assert credentials_list_model == credentials_list_model2 - - # Convert model instance back to dict and verify no loss of data - credentials_list_model_json2 = credentials_list_model.to_dict() - assert credentials_list_model_json2 == credentials_list_model_json - - -class TestModel_DeleteCollectionResponse: - """ - Test Class for DeleteCollectionResponse - """ - - def test_delete_collection_response_serialization(self): - """ - Test serialization/deserialization for DeleteCollectionResponse - """ - - # Construct a json representation of a DeleteCollectionResponse model - delete_collection_response_model_json = {} - delete_collection_response_model_json['collection_id'] = 'testString' - delete_collection_response_model_json['status'] = 'deleted' - - # Construct a model instance of DeleteCollectionResponse by calling from_dict on the json representation - delete_collection_response_model = DeleteCollectionResponse.from_dict(delete_collection_response_model_json) - assert delete_collection_response_model != False - - # Construct a model instance of DeleteCollectionResponse by calling from_dict on the json representation - delete_collection_response_model_dict = DeleteCollectionResponse.from_dict(delete_collection_response_model_json).__dict__ - delete_collection_response_model2 = DeleteCollectionResponse(**delete_collection_response_model_dict) - - # Verify the model instances are equivalent - assert delete_collection_response_model == delete_collection_response_model2 - - # Convert model instance back to dict and verify no loss of data - delete_collection_response_model_json2 = delete_collection_response_model.to_dict() - assert delete_collection_response_model_json2 == delete_collection_response_model_json - - -class TestModel_DeleteConfigurationResponse: - """ - Test Class for DeleteConfigurationResponse - """ - - def test_delete_configuration_response_serialization(self): - """ - Test serialization/deserialization for DeleteConfigurationResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - - # Construct a json representation of a DeleteConfigurationResponse model - delete_configuration_response_model_json = {} - delete_configuration_response_model_json['configuration_id'] = 'testString' - delete_configuration_response_model_json['status'] = 'deleted' - delete_configuration_response_model_json['notices'] = [notice_model] - - # Construct a model instance of DeleteConfigurationResponse by calling from_dict on the json representation - delete_configuration_response_model = DeleteConfigurationResponse.from_dict(delete_configuration_response_model_json) - assert delete_configuration_response_model != False - - # Construct a model instance of DeleteConfigurationResponse by calling from_dict on the json representation - delete_configuration_response_model_dict = DeleteConfigurationResponse.from_dict(delete_configuration_response_model_json).__dict__ - delete_configuration_response_model2 = DeleteConfigurationResponse(**delete_configuration_response_model_dict) - - # Verify the model instances are equivalent - assert delete_configuration_response_model == delete_configuration_response_model2 - - # Convert model instance back to dict and verify no loss of data - delete_configuration_response_model_json2 = delete_configuration_response_model.to_dict() - assert delete_configuration_response_model_json2 == delete_configuration_response_model_json - - -class TestModel_DeleteCredentials: - """ - Test Class for DeleteCredentials - """ - - def test_delete_credentials_serialization(self): - """ - Test serialization/deserialization for DeleteCredentials - """ - - # Construct a json representation of a DeleteCredentials model - delete_credentials_model_json = {} - delete_credentials_model_json['credential_id'] = 'testString' - delete_credentials_model_json['status'] = 'deleted' - - # Construct a model instance of DeleteCredentials by calling from_dict on the json representation - delete_credentials_model = DeleteCredentials.from_dict(delete_credentials_model_json) - assert delete_credentials_model != False - - # Construct a model instance of DeleteCredentials by calling from_dict on the json representation - delete_credentials_model_dict = DeleteCredentials.from_dict(delete_credentials_model_json).__dict__ - delete_credentials_model2 = DeleteCredentials(**delete_credentials_model_dict) - - # Verify the model instances are equivalent - assert delete_credentials_model == delete_credentials_model2 - - # Convert model instance back to dict and verify no loss of data - delete_credentials_model_json2 = delete_credentials_model.to_dict() - assert delete_credentials_model_json2 == delete_credentials_model_json - - -class TestModel_DeleteDocumentResponse: - """ - Test Class for DeleteDocumentResponse - """ - - def test_delete_document_response_serialization(self): - """ - Test serialization/deserialization for DeleteDocumentResponse - """ - - # Construct a json representation of a DeleteDocumentResponse model - delete_document_response_model_json = {} - delete_document_response_model_json['document_id'] = 'testString' - delete_document_response_model_json['status'] = 'deleted' - - # Construct a model instance of DeleteDocumentResponse by calling from_dict on the json representation - delete_document_response_model = DeleteDocumentResponse.from_dict(delete_document_response_model_json) - assert delete_document_response_model != False - - # Construct a model instance of DeleteDocumentResponse by calling from_dict on the json representation - delete_document_response_model_dict = DeleteDocumentResponse.from_dict(delete_document_response_model_json).__dict__ - delete_document_response_model2 = DeleteDocumentResponse(**delete_document_response_model_dict) - - # Verify the model instances are equivalent - assert delete_document_response_model == delete_document_response_model2 - - # Convert model instance back to dict and verify no loss of data - delete_document_response_model_json2 = delete_document_response_model.to_dict() - assert delete_document_response_model_json2 == delete_document_response_model_json - - -class TestModel_DeleteEnvironmentResponse: - """ - Test Class for DeleteEnvironmentResponse - """ - - def test_delete_environment_response_serialization(self): - """ - Test serialization/deserialization for DeleteEnvironmentResponse - """ - - # Construct a json representation of a DeleteEnvironmentResponse model - delete_environment_response_model_json = {} - delete_environment_response_model_json['environment_id'] = 'testString' - delete_environment_response_model_json['status'] = 'deleted' - - # Construct a model instance of DeleteEnvironmentResponse by calling from_dict on the json representation - delete_environment_response_model = DeleteEnvironmentResponse.from_dict(delete_environment_response_model_json) - assert delete_environment_response_model != False - - # Construct a model instance of DeleteEnvironmentResponse by calling from_dict on the json representation - delete_environment_response_model_dict = DeleteEnvironmentResponse.from_dict(delete_environment_response_model_json).__dict__ - delete_environment_response_model2 = DeleteEnvironmentResponse(**delete_environment_response_model_dict) - - # Verify the model instances are equivalent - assert delete_environment_response_model == delete_environment_response_model2 - - # Convert model instance back to dict and verify no loss of data - delete_environment_response_model_json2 = delete_environment_response_model.to_dict() - assert delete_environment_response_model_json2 == delete_environment_response_model_json - - -class TestModel_DiskUsage: - """ - Test Class for DiskUsage - """ - - def test_disk_usage_serialization(self): - """ - Test serialization/deserialization for DiskUsage - """ - - # Construct a json representation of a DiskUsage model - disk_usage_model_json = {} - - # Construct a model instance of DiskUsage by calling from_dict on the json representation - disk_usage_model = DiskUsage.from_dict(disk_usage_model_json) - assert disk_usage_model != False - - # Construct a model instance of DiskUsage by calling from_dict on the json representation - disk_usage_model_dict = DiskUsage.from_dict(disk_usage_model_json).__dict__ - disk_usage_model2 = DiskUsage(**disk_usage_model_dict) - - # Verify the model instances are equivalent - assert disk_usage_model == disk_usage_model2 - - # Convert model instance back to dict and verify no loss of data - disk_usage_model_json2 = disk_usage_model.to_dict() - assert disk_usage_model_json2 == disk_usage_model_json - - -class TestModel_DocumentAccepted: - """ - Test Class for DocumentAccepted - """ - - def test_document_accepted_serialization(self): - """ - Test serialization/deserialization for DocumentAccepted - """ - - # Construct dict forms of any model objects needed in order to build this model. - - notice_model = {} # Notice - - # Construct a json representation of a DocumentAccepted model - document_accepted_model_json = {} - document_accepted_model_json['document_id'] = 'testString' - document_accepted_model_json['status'] = 'processing' - document_accepted_model_json['notices'] = [notice_model] - - # Construct a model instance of DocumentAccepted by calling from_dict on the json representation - document_accepted_model = DocumentAccepted.from_dict(document_accepted_model_json) - assert document_accepted_model != False - - # Construct a model instance of DocumentAccepted by calling from_dict on the json representation - document_accepted_model_dict = DocumentAccepted.from_dict(document_accepted_model_json).__dict__ - document_accepted_model2 = DocumentAccepted(**document_accepted_model_dict) - - # Verify the model instances are equivalent - assert document_accepted_model == document_accepted_model2 - - # Convert model instance back to dict and verify no loss of data - document_accepted_model_json2 = document_accepted_model.to_dict() - assert document_accepted_model_json2 == document_accepted_model_json - - -class TestModel_DocumentCounts: - """ - Test Class for DocumentCounts - """ - - def test_document_counts_serialization(self): - """ - Test serialization/deserialization for DocumentCounts - """ - - # Construct a json representation of a DocumentCounts model - document_counts_model_json = {} - - # Construct a model instance of DocumentCounts by calling from_dict on the json representation - document_counts_model = DocumentCounts.from_dict(document_counts_model_json) - assert document_counts_model != False - - # Construct a model instance of DocumentCounts by calling from_dict on the json representation - document_counts_model_dict = DocumentCounts.from_dict(document_counts_model_json).__dict__ - document_counts_model2 = DocumentCounts(**document_counts_model_dict) - - # Verify the model instances are equivalent - assert document_counts_model == document_counts_model2 - - # Convert model instance back to dict and verify no loss of data - document_counts_model_json2 = document_counts_model.to_dict() - assert document_counts_model_json2 == document_counts_model_json - - -class TestModel_DocumentStatus: - """ - Test Class for DocumentStatus - """ - - def test_document_status_serialization(self): - """ - Test serialization/deserialization for DocumentStatus - """ - - # Construct a json representation of a DocumentStatus model - document_status_model_json = {} - document_status_model_json['filename'] = 'testString' - document_status_model_json['file_type'] = 'pdf' - document_status_model_json['sha1'] = 'testString' - - # Construct a model instance of DocumentStatus by calling from_dict on the json representation - document_status_model = DocumentStatus.from_dict(document_status_model_json) - assert document_status_model != False - - # Construct a model instance of DocumentStatus by calling from_dict on the json representation - document_status_model_dict = DocumentStatus.from_dict(document_status_model_json).__dict__ - document_status_model2 = DocumentStatus(**document_status_model_dict) - - # Verify the model instances are equivalent - assert document_status_model == document_status_model2 - - # Convert model instance back to dict and verify no loss of data - document_status_model_json2 = document_status_model.to_dict() - assert document_status_model_json2 == document_status_model_json - - -class TestModel_Enrichment: - """ - Test Class for Enrichment - """ - - def test_enrichment_serialization(self): - """ - Test serialization/deserialization for Enrichment - """ - - # Construct dict forms of any model objects needed in order to build this model. - - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - nlu_enrichment_entities_model = {} # NluEnrichmentEntities - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - nlu_enrichment_relations_model = {} # NluEnrichmentRelations - nlu_enrichment_relations_model['model'] = 'testString' - - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts - nlu_enrichment_concepts_model['limit'] = 38 - - nlu_enrichment_features_model = {} # NluEnrichmentFeatures - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - enrichment_options_model = {} # EnrichmentOptions - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - # Construct a json representation of a Enrichment model - enrichment_model_json = {} - enrichment_model_json['description'] = 'testString' - enrichment_model_json['destination_field'] = 'testString' - enrichment_model_json['source_field'] = 'testString' - enrichment_model_json['overwrite'] = False - enrichment_model_json['enrichment'] = 'testString' - enrichment_model_json['ignore_downstream_errors'] = False - enrichment_model_json['options'] = enrichment_options_model - - # Construct a model instance of Enrichment by calling from_dict on the json representation - enrichment_model = Enrichment.from_dict(enrichment_model_json) - assert enrichment_model != False - - # Construct a model instance of Enrichment by calling from_dict on the json representation - enrichment_model_dict = Enrichment.from_dict(enrichment_model_json).__dict__ - enrichment_model2 = Enrichment(**enrichment_model_dict) - - # Verify the model instances are equivalent - assert enrichment_model == enrichment_model2 - - # Convert model instance back to dict and verify no loss of data - enrichment_model_json2 = enrichment_model.to_dict() - assert enrichment_model_json2 == enrichment_model_json - - -class TestModel_EnrichmentOptions: - """ - Test Class for EnrichmentOptions - """ - - def test_enrichment_options_serialization(self): - """ - Test serialization/deserialization for EnrichmentOptions - """ - - # Construct dict forms of any model objects needed in order to build this model. - - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - nlu_enrichment_entities_model = {} # NluEnrichmentEntities - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - nlu_enrichment_relations_model = {} # NluEnrichmentRelations - nlu_enrichment_relations_model['model'] = 'testString' - - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts - nlu_enrichment_concepts_model['limit'] = 38 - - nlu_enrichment_features_model = {} # NluEnrichmentFeatures - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - # Construct a json representation of a EnrichmentOptions model - enrichment_options_model_json = {} - enrichment_options_model_json['features'] = nlu_enrichment_features_model - enrichment_options_model_json['language'] = 'ar' - enrichment_options_model_json['model'] = 'testString' - - # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation - enrichment_options_model = EnrichmentOptions.from_dict(enrichment_options_model_json) - assert enrichment_options_model != False - - # Construct a model instance of EnrichmentOptions by calling from_dict on the json representation - enrichment_options_model_dict = EnrichmentOptions.from_dict(enrichment_options_model_json).__dict__ - enrichment_options_model2 = EnrichmentOptions(**enrichment_options_model_dict) - - # Verify the model instances are equivalent - assert enrichment_options_model == enrichment_options_model2 - - # Convert model instance back to dict and verify no loss of data - enrichment_options_model_json2 = enrichment_options_model.to_dict() - assert enrichment_options_model_json2 == enrichment_options_model_json - - -class TestModel_Environment: - """ - Test Class for Environment - """ - - def test_environment_serialization(self): - """ - Test serialization/deserialization for Environment - """ - - # Construct dict forms of any model objects needed in order to build this model. - - environment_documents_model = {} # EnvironmentDocuments - - disk_usage_model = {} # DiskUsage - - collection_usage_model = {} # CollectionUsage - - index_capacity_model = {} # IndexCapacity - index_capacity_model['documents'] = environment_documents_model - index_capacity_model['disk_usage'] = disk_usage_model - index_capacity_model['collections'] = collection_usage_model - - search_status_model = {} # SearchStatus - search_status_model['scope'] = 'testString' - search_status_model['status'] = 'NO_DATA' - search_status_model['status_description'] = 'testString' - search_status_model['last_trained'] = '2019-01-01' - - # Construct a json representation of a Environment model - environment_model_json = {} - environment_model_json['name'] = 'testString' - environment_model_json['description'] = 'testString' - environment_model_json['size'] = 'LT' - environment_model_json['requested_size'] = 'testString' - environment_model_json['index_capacity'] = index_capacity_model - environment_model_json['search_status'] = search_status_model - - # Construct a model instance of Environment by calling from_dict on the json representation - environment_model = Environment.from_dict(environment_model_json) - assert environment_model != False - - # Construct a model instance of Environment by calling from_dict on the json representation - environment_model_dict = Environment.from_dict(environment_model_json).__dict__ - environment_model2 = Environment(**environment_model_dict) - - # Verify the model instances are equivalent - assert environment_model == environment_model2 - - # Convert model instance back to dict and verify no loss of data - environment_model_json2 = environment_model.to_dict() - assert environment_model_json2 == environment_model_json - - -class TestModel_EnvironmentDocuments: - """ - Test Class for EnvironmentDocuments - """ - - def test_environment_documents_serialization(self): - """ - Test serialization/deserialization for EnvironmentDocuments - """ - - # Construct a json representation of a EnvironmentDocuments model - environment_documents_model_json = {} - - # Construct a model instance of EnvironmentDocuments by calling from_dict on the json representation - environment_documents_model = EnvironmentDocuments.from_dict(environment_documents_model_json) - assert environment_documents_model != False - - # Construct a model instance of EnvironmentDocuments by calling from_dict on the json representation - environment_documents_model_dict = EnvironmentDocuments.from_dict(environment_documents_model_json).__dict__ - environment_documents_model2 = EnvironmentDocuments(**environment_documents_model_dict) - - # Verify the model instances are equivalent - assert environment_documents_model == environment_documents_model2 - - # Convert model instance back to dict and verify no loss of data - environment_documents_model_json2 = environment_documents_model.to_dict() - assert environment_documents_model_json2 == environment_documents_model_json - - -class TestModel_EventData: - """ - Test Class for EventData - """ - - def test_event_data_serialization(self): - """ - Test serialization/deserialization for EventData - """ - - # Construct a json representation of a EventData model - event_data_model_json = {} - event_data_model_json['environment_id'] = 'testString' - event_data_model_json['session_token'] = 'testString' - event_data_model_json['client_timestamp'] = '2019-01-01T12:00:00Z' - event_data_model_json['display_rank'] = 38 - event_data_model_json['collection_id'] = 'testString' - event_data_model_json['document_id'] = 'testString' - - # Construct a model instance of EventData by calling from_dict on the json representation - event_data_model = EventData.from_dict(event_data_model_json) - assert event_data_model != False - - # Construct a model instance of EventData by calling from_dict on the json representation - event_data_model_dict = EventData.from_dict(event_data_model_json).__dict__ - event_data_model2 = EventData(**event_data_model_dict) - - # Verify the model instances are equivalent - assert event_data_model == event_data_model2 - - # Convert model instance back to dict and verify no loss of data - event_data_model_json2 = event_data_model.to_dict() - assert event_data_model_json2 == event_data_model_json - - -class TestModel_Expansion: - """ - Test Class for Expansion - """ - - def test_expansion_serialization(self): - """ - Test serialization/deserialization for Expansion - """ - - # Construct a json representation of a Expansion model - expansion_model_json = {} - expansion_model_json['input_terms'] = ['testString'] - expansion_model_json['expanded_terms'] = ['testString'] - - # Construct a model instance of Expansion by calling from_dict on the json representation - expansion_model = Expansion.from_dict(expansion_model_json) - assert expansion_model != False - - # Construct a model instance of Expansion by calling from_dict on the json representation - expansion_model_dict = Expansion.from_dict(expansion_model_json).__dict__ - expansion_model2 = Expansion(**expansion_model_dict) - - # Verify the model instances are equivalent - assert expansion_model == expansion_model2 - - # Convert model instance back to dict and verify no loss of data - expansion_model_json2 = expansion_model.to_dict() - assert expansion_model_json2 == expansion_model_json - - -class TestModel_Expansions: - """ - Test Class for Expansions - """ - - def test_expansions_serialization(self): - """ - Test serialization/deserialization for Expansions - """ - - # Construct dict forms of any model objects needed in order to build this model. - - expansion_model = {} # Expansion - expansion_model['input_terms'] = ['testString'] - expansion_model['expanded_terms'] = ['testString'] - - # Construct a json representation of a Expansions model - expansions_model_json = {} - expansions_model_json['expansions'] = [expansion_model] - - # Construct a model instance of Expansions by calling from_dict on the json representation - expansions_model = Expansions.from_dict(expansions_model_json) - assert expansions_model != False - - # Construct a model instance of Expansions by calling from_dict on the json representation - expansions_model_dict = Expansions.from_dict(expansions_model_json).__dict__ - expansions_model2 = Expansions(**expansions_model_dict) - - # Verify the model instances are equivalent - assert expansions_model == expansions_model2 - - # Convert model instance back to dict and verify no loss of data - expansions_model_json2 = expansions_model.to_dict() - assert expansions_model_json2 == expansions_model_json - - -class TestModel_Field: - """ - Test Class for Field - """ - - def test_field_serialization(self): - """ - Test serialization/deserialization for Field - """ - - # Construct a json representation of a Field model - field_model_json = {} - - # Construct a model instance of Field by calling from_dict on the json representation - field_model = Field.from_dict(field_model_json) - assert field_model != False - - # Construct a model instance of Field by calling from_dict on the json representation - field_model_dict = Field.from_dict(field_model_json).__dict__ - field_model2 = Field(**field_model_dict) - - # Verify the model instances are equivalent - assert field_model == field_model2 - - # Convert model instance back to dict and verify no loss of data - field_model_json2 = field_model.to_dict() - assert field_model_json2 == field_model_json - - -class TestModel_FontSetting: - """ - Test Class for FontSetting - """ - - def test_font_setting_serialization(self): - """ - Test serialization/deserialization for FontSetting - """ - - # Construct a json representation of a FontSetting model - font_setting_model_json = {} - font_setting_model_json['level'] = 38 - font_setting_model_json['min_size'] = 38 - font_setting_model_json['max_size'] = 38 - font_setting_model_json['bold'] = True - font_setting_model_json['italic'] = True - font_setting_model_json['name'] = 'testString' - - # Construct a model instance of FontSetting by calling from_dict on the json representation - font_setting_model = FontSetting.from_dict(font_setting_model_json) - assert font_setting_model != False - - # Construct a model instance of FontSetting by calling from_dict on the json representation - font_setting_model_dict = FontSetting.from_dict(font_setting_model_json).__dict__ - font_setting_model2 = FontSetting(**font_setting_model_dict) - - # Verify the model instances are equivalent - assert font_setting_model == font_setting_model2 - - # Convert model instance back to dict and verify no loss of data - font_setting_model_json2 = font_setting_model.to_dict() - assert font_setting_model_json2 == font_setting_model_json - - -class TestModel_Gateway: - """ - Test Class for Gateway - """ - - def test_gateway_serialization(self): - """ - Test serialization/deserialization for Gateway - """ - - # Construct a json representation of a Gateway model - gateway_model_json = {} - gateway_model_json['gateway_id'] = 'testString' - gateway_model_json['name'] = 'testString' - gateway_model_json['status'] = 'connected' - gateway_model_json['token'] = 'testString' - gateway_model_json['token_id'] = 'testString' - - # Construct a model instance of Gateway by calling from_dict on the json representation - gateway_model = Gateway.from_dict(gateway_model_json) - assert gateway_model != False - - # Construct a model instance of Gateway by calling from_dict on the json representation - gateway_model_dict = Gateway.from_dict(gateway_model_json).__dict__ - gateway_model2 = Gateway(**gateway_model_dict) - - # Verify the model instances are equivalent - assert gateway_model == gateway_model2 - - # Convert model instance back to dict and verify no loss of data - gateway_model_json2 = gateway_model.to_dict() - assert gateway_model_json2 == gateway_model_json - - -class TestModel_GatewayDelete: - """ - Test Class for GatewayDelete - """ - - def test_gateway_delete_serialization(self): - """ - Test serialization/deserialization for GatewayDelete - """ - - # Construct a json representation of a GatewayDelete model - gateway_delete_model_json = {} - gateway_delete_model_json['gateway_id'] = 'testString' - gateway_delete_model_json['status'] = 'testString' - - # Construct a model instance of GatewayDelete by calling from_dict on the json representation - gateway_delete_model = GatewayDelete.from_dict(gateway_delete_model_json) - assert gateway_delete_model != False - - # Construct a model instance of GatewayDelete by calling from_dict on the json representation - gateway_delete_model_dict = GatewayDelete.from_dict(gateway_delete_model_json).__dict__ - gateway_delete_model2 = GatewayDelete(**gateway_delete_model_dict) - - # Verify the model instances are equivalent - assert gateway_delete_model == gateway_delete_model2 - - # Convert model instance back to dict and verify no loss of data - gateway_delete_model_json2 = gateway_delete_model.to_dict() - assert gateway_delete_model_json2 == gateway_delete_model_json - - -class TestModel_GatewayList: - """ - Test Class for GatewayList - """ - - def test_gateway_list_serialization(self): - """ - Test serialization/deserialization for GatewayList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - gateway_model = {} # Gateway - gateway_model['gateway_id'] = 'testString' - gateway_model['name'] = 'testString' - gateway_model['status'] = 'connected' - gateway_model['token'] = 'testString' - gateway_model['token_id'] = 'testString' - - # Construct a json representation of a GatewayList model - gateway_list_model_json = {} - gateway_list_model_json['gateways'] = [gateway_model] - - # Construct a model instance of GatewayList by calling from_dict on the json representation - gateway_list_model = GatewayList.from_dict(gateway_list_model_json) - assert gateway_list_model != False - - # Construct a model instance of GatewayList by calling from_dict on the json representation - gateway_list_model_dict = GatewayList.from_dict(gateway_list_model_json).__dict__ - gateway_list_model2 = GatewayList(**gateway_list_model_dict) - - # Verify the model instances are equivalent - assert gateway_list_model == gateway_list_model2 - - # Convert model instance back to dict and verify no loss of data - gateway_list_model_json2 = gateway_list_model.to_dict() - assert gateway_list_model_json2 == gateway_list_model_json - - -class TestModel_HtmlSettings: - """ - Test Class for HtmlSettings - """ - - def test_html_settings_serialization(self): - """ - Test serialization/deserialization for HtmlSettings - """ - - # Construct dict forms of any model objects needed in order to build this model. - - x_path_patterns_model = {} # XPathPatterns - x_path_patterns_model['xpaths'] = ['testString'] - - # Construct a json representation of a HtmlSettings model - html_settings_model_json = {} - html_settings_model_json['exclude_tags_completely'] = ['testString'] - html_settings_model_json['exclude_tags_keep_content'] = ['testString'] - html_settings_model_json['keep_content'] = x_path_patterns_model - html_settings_model_json['exclude_content'] = x_path_patterns_model - html_settings_model_json['keep_tag_attributes'] = ['testString'] - html_settings_model_json['exclude_tag_attributes'] = ['testString'] - - # Construct a model instance of HtmlSettings by calling from_dict on the json representation - html_settings_model = HtmlSettings.from_dict(html_settings_model_json) - assert html_settings_model != False - - # Construct a model instance of HtmlSettings by calling from_dict on the json representation - html_settings_model_dict = HtmlSettings.from_dict(html_settings_model_json).__dict__ - html_settings_model2 = HtmlSettings(**html_settings_model_dict) - - # Verify the model instances are equivalent - assert html_settings_model == html_settings_model2 - - # Convert model instance back to dict and verify no loss of data - html_settings_model_json2 = html_settings_model.to_dict() - assert html_settings_model_json2 == html_settings_model_json - - -class TestModel_IndexCapacity: - """ - Test Class for IndexCapacity - """ - - def test_index_capacity_serialization(self): - """ - Test serialization/deserialization for IndexCapacity - """ - - # Construct dict forms of any model objects needed in order to build this model. - - environment_documents_model = {} # EnvironmentDocuments - - disk_usage_model = {} # DiskUsage - - collection_usage_model = {} # CollectionUsage - - # Construct a json representation of a IndexCapacity model - index_capacity_model_json = {} - index_capacity_model_json['documents'] = environment_documents_model - index_capacity_model_json['disk_usage'] = disk_usage_model - index_capacity_model_json['collections'] = collection_usage_model - - # Construct a model instance of IndexCapacity by calling from_dict on the json representation - index_capacity_model = IndexCapacity.from_dict(index_capacity_model_json) - assert index_capacity_model != False - - # Construct a model instance of IndexCapacity by calling from_dict on the json representation - index_capacity_model_dict = IndexCapacity.from_dict(index_capacity_model_json).__dict__ - index_capacity_model2 = IndexCapacity(**index_capacity_model_dict) - - # Verify the model instances are equivalent - assert index_capacity_model == index_capacity_model2 - - # Convert model instance back to dict and verify no loss of data - index_capacity_model_json2 = index_capacity_model.to_dict() - assert index_capacity_model_json2 == index_capacity_model_json - - -class TestModel_ListCollectionFieldsResponse: - """ - Test Class for ListCollectionFieldsResponse - """ - - def test_list_collection_fields_response_serialization(self): - """ - Test serialization/deserialization for ListCollectionFieldsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - field_model = {} # Field - - # Construct a json representation of a ListCollectionFieldsResponse model - list_collection_fields_response_model_json = {} - list_collection_fields_response_model_json['fields'] = [field_model] - - # Construct a model instance of ListCollectionFieldsResponse by calling from_dict on the json representation - list_collection_fields_response_model = ListCollectionFieldsResponse.from_dict(list_collection_fields_response_model_json) - assert list_collection_fields_response_model != False - - # Construct a model instance of ListCollectionFieldsResponse by calling from_dict on the json representation - list_collection_fields_response_model_dict = ListCollectionFieldsResponse.from_dict(list_collection_fields_response_model_json).__dict__ - list_collection_fields_response_model2 = ListCollectionFieldsResponse(**list_collection_fields_response_model_dict) - - # Verify the model instances are equivalent - assert list_collection_fields_response_model == list_collection_fields_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_collection_fields_response_model_json2 = list_collection_fields_response_model.to_dict() - assert list_collection_fields_response_model_json2 == list_collection_fields_response_model_json - - -class TestModel_ListCollectionsResponse: - """ - Test Class for ListCollectionsResponse - """ - - def test_list_collections_response_serialization(self): - """ - Test serialization/deserialization for ListCollectionsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - document_counts_model = {} # DocumentCounts - - collection_disk_usage_model = {} # CollectionDiskUsage - - training_status_model = {} # TrainingStatus - training_status_model['total_examples'] = 38 - training_status_model['available'] = True - training_status_model['processing'] = True - training_status_model['minimum_queries_added'] = True - training_status_model['minimum_examples_added'] = True - training_status_model['sufficient_label_diversity'] = True - training_status_model['notices'] = 38 - training_status_model['successfully_trained'] = '2019-01-01T12:00:00Z' - training_status_model['data_updated'] = '2019-01-01T12:00:00Z' - - source_status_model = {} # SourceStatus - source_status_model['status'] = 'running' - source_status_model['next_crawl'] = '2019-01-01T12:00:00Z' - - collection_crawl_status_model = {} # CollectionCrawlStatus - collection_crawl_status_model['source_crawl'] = source_status_model - - sdu_status_custom_fields_model = {} # SduStatusCustomFields - sdu_status_custom_fields_model['defined'] = 26 - sdu_status_custom_fields_model['maximum_allowed'] = 26 - - sdu_status_model = {} # SduStatus - sdu_status_model['enabled'] = True - sdu_status_model['total_annotated_pages'] = 26 - sdu_status_model['total_pages'] = 26 - sdu_status_model['total_documents'] = 26 - sdu_status_model['custom_fields'] = sdu_status_custom_fields_model - - collection_model = {} # Collection - collection_model['name'] = 'example' - collection_model['description'] = 'this is a demo collection' - collection_model['configuration_id'] = '6963be41-2dea-4f79-8f52-127c63c479b0' - collection_model['language'] = 'en' - collection_model['document_counts'] = document_counts_model - collection_model['disk_usage'] = collection_disk_usage_model - collection_model['training_status'] = training_status_model - collection_model['crawl_status'] = collection_crawl_status_model - collection_model['smart_document_understanding'] = sdu_status_model - - # Construct a json representation of a ListCollectionsResponse model - list_collections_response_model_json = {} - list_collections_response_model_json['collections'] = [collection_model] - - # Construct a model instance of ListCollectionsResponse by calling from_dict on the json representation - list_collections_response_model = ListCollectionsResponse.from_dict(list_collections_response_model_json) - assert list_collections_response_model != False - - # Construct a model instance of ListCollectionsResponse by calling from_dict on the json representation - list_collections_response_model_dict = ListCollectionsResponse.from_dict(list_collections_response_model_json).__dict__ - list_collections_response_model2 = ListCollectionsResponse(**list_collections_response_model_dict) - - # Verify the model instances are equivalent - assert list_collections_response_model == list_collections_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_collections_response_model_json2 = list_collections_response_model.to_dict() - assert list_collections_response_model_json2 == list_collections_response_model_json - - -class TestModel_ListConfigurationsResponse: - """ - Test Class for ListConfigurationsResponse - """ - - def test_list_configurations_response_serialization(self): - """ - Test serialization/deserialization for ListConfigurationsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - pdf_heading_detection_model = {} # PdfHeadingDetection - pdf_heading_detection_model['fonts'] = [font_setting_model] - - pdf_settings_model = {} # PdfSettings - pdf_settings_model['heading'] = pdf_heading_detection_model - - word_style_model = {} # WordStyle - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - word_heading_detection_model = {} # WordHeadingDetection - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - word_settings_model = {} # WordSettings - word_settings_model['heading'] = word_heading_detection_model - - x_path_patterns_model = {} # XPathPatterns - x_path_patterns_model['xpaths'] = ['testString'] - - html_settings_model = {} # HtmlSettings - html_settings_model['exclude_tags_completely'] = ['testString'] - html_settings_model['exclude_tags_keep_content'] = ['testString'] - html_settings_model['keep_content'] = x_path_patterns_model - html_settings_model['exclude_content'] = x_path_patterns_model - html_settings_model['keep_tag_attributes'] = ['testString'] - html_settings_model['exclude_tag_attributes'] = ['testString'] - - segment_settings_model = {} # SegmentSettings - segment_settings_model['enabled'] = False - segment_settings_model['selector_tags'] = ['h1', 'h2'] - segment_settings_model['annotated_fields'] = ['testString'] - - normalization_operation_model = {} # NormalizationOperation - normalization_operation_model['operation'] = 'copy' - normalization_operation_model['source_field'] = 'testString' - normalization_operation_model['destination_field'] = 'testString' - - conversions_model = {} # Conversions - conversions_model['pdf'] = pdf_settings_model - conversions_model['word'] = word_settings_model - conversions_model['html'] = html_settings_model - conversions_model['segment'] = segment_settings_model - conversions_model['json_normalizations'] = [normalization_operation_model] - conversions_model['image_text_recognition'] = True - - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - nlu_enrichment_entities_model = {} # NluEnrichmentEntities - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - nlu_enrichment_relations_model = {} # NluEnrichmentRelations - nlu_enrichment_relations_model['model'] = 'testString' - - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts - nlu_enrichment_concepts_model['limit'] = 38 - - nlu_enrichment_features_model = {} # NluEnrichmentFeatures - nlu_enrichment_features_model['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model['concepts'] = nlu_enrichment_concepts_model - - enrichment_options_model = {} # EnrichmentOptions - enrichment_options_model['features'] = nlu_enrichment_features_model - enrichment_options_model['language'] = 'ar' - enrichment_options_model['model'] = 'testString' - - enrichment_model = {} # Enrichment - enrichment_model['description'] = 'testString' - enrichment_model['destination_field'] = 'testString' - enrichment_model['source_field'] = 'testString' - enrichment_model['overwrite'] = False - enrichment_model['enrichment'] = 'testString' - enrichment_model['ignore_downstream_errors'] = False - enrichment_model['options'] = enrichment_options_model - - source_schedule_model = {} # SourceSchedule - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - source_options_folder_model = {} # SourceOptionsFolder - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - source_options_object_model = {} # SourceOptionsObject - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - source_options_site_coll_model = {} # SourceOptionsSiteColl - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - source_options_web_crawl_model = {} # SourceOptionsWebCrawl - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - source_options_buckets_model = {} # SourceOptionsBuckets - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - source_options_model = {} # SourceOptions - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - source_model = {} # Source - source_model['type'] = 'box' - source_model['credential_id'] = 'testString' - source_model['schedule'] = source_schedule_model - source_model['options'] = source_options_model - - configuration_model = {} # Configuration - configuration_model['name'] = 'testString' - configuration_model['description'] = 'testString' - configuration_model['conversions'] = conversions_model - configuration_model['enrichments'] = [enrichment_model] - configuration_model['normalizations'] = [normalization_operation_model] - configuration_model['source'] = source_model - - # Construct a json representation of a ListConfigurationsResponse model - list_configurations_response_model_json = {} - list_configurations_response_model_json['configurations'] = [configuration_model] - - # Construct a model instance of ListConfigurationsResponse by calling from_dict on the json representation - list_configurations_response_model = ListConfigurationsResponse.from_dict(list_configurations_response_model_json) - assert list_configurations_response_model != False - - # Construct a model instance of ListConfigurationsResponse by calling from_dict on the json representation - list_configurations_response_model_dict = ListConfigurationsResponse.from_dict(list_configurations_response_model_json).__dict__ - list_configurations_response_model2 = ListConfigurationsResponse(**list_configurations_response_model_dict) - - # Verify the model instances are equivalent - assert list_configurations_response_model == list_configurations_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_configurations_response_model_json2 = list_configurations_response_model.to_dict() - assert list_configurations_response_model_json2 == list_configurations_response_model_json - - -class TestModel_ListEnvironmentsResponse: - """ - Test Class for ListEnvironmentsResponse - """ - - def test_list_environments_response_serialization(self): - """ - Test serialization/deserialization for ListEnvironmentsResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - environment_documents_model = {} # EnvironmentDocuments - - disk_usage_model = {} # DiskUsage - - collection_usage_model = {} # CollectionUsage - - index_capacity_model = {} # IndexCapacity - index_capacity_model['documents'] = environment_documents_model - index_capacity_model['disk_usage'] = disk_usage_model - index_capacity_model['collections'] = collection_usage_model - - search_status_model = {} # SearchStatus - search_status_model['scope'] = 'testString' - search_status_model['status'] = 'NO_DATA' - search_status_model['status_description'] = 'testString' - search_status_model['last_trained'] = '2019-01-01' - - environment_model = {} # Environment - environment_model['name'] = 'byod_environment' - environment_model['description'] = 'Private Data Environment' - environment_model['size'] = 'LT' - environment_model['requested_size'] = 'testString' - environment_model['index_capacity'] = index_capacity_model - environment_model['search_status'] = search_status_model - - # Construct a json representation of a ListEnvironmentsResponse model - list_environments_response_model_json = {} - list_environments_response_model_json['environments'] = [environment_model] - - # Construct a model instance of ListEnvironmentsResponse by calling from_dict on the json representation - list_environments_response_model = ListEnvironmentsResponse.from_dict(list_environments_response_model_json) - assert list_environments_response_model != False - - # Construct a model instance of ListEnvironmentsResponse by calling from_dict on the json representation - list_environments_response_model_dict = ListEnvironmentsResponse.from_dict(list_environments_response_model_json).__dict__ - list_environments_response_model2 = ListEnvironmentsResponse(**list_environments_response_model_dict) - - # Verify the model instances are equivalent - assert list_environments_response_model == list_environments_response_model2 - - # Convert model instance back to dict and verify no loss of data - list_environments_response_model_json2 = list_environments_response_model.to_dict() - assert list_environments_response_model_json2 == list_environments_response_model_json - - -class TestModel_LogQueryResponse: - """ - Test Class for LogQueryResponse - """ - - def test_log_query_response_serialization(self): - """ - Test serialization/deserialization for LogQueryResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult - log_query_response_result_documents_result_model['position'] = 38 - log_query_response_result_documents_result_model['document_id'] = 'testString' - log_query_response_result_documents_result_model['score'] = 72.5 - log_query_response_result_documents_result_model['confidence'] = 72.5 - log_query_response_result_documents_result_model['collection_id'] = 'testString' - - log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments - log_query_response_result_documents_model['results'] = [log_query_response_result_documents_result_model] - log_query_response_result_documents_model['count'] = 38 - - log_query_response_result_model = {} # LogQueryResponseResult - log_query_response_result_model['environment_id'] = 'testString' - log_query_response_result_model['customer_id'] = 'testString' - log_query_response_result_model['document_type'] = 'query' - log_query_response_result_model['natural_language_query'] = 'testString' - log_query_response_result_model['document_results'] = log_query_response_result_documents_model - log_query_response_result_model['created_timestamp'] = '2019-01-01T12:00:00Z' - log_query_response_result_model['client_timestamp'] = '2019-01-01T12:00:00Z' - log_query_response_result_model['query_id'] = 'testString' - log_query_response_result_model['session_token'] = 'testString' - log_query_response_result_model['collection_id'] = 'testString' - log_query_response_result_model['display_rank'] = 38 - log_query_response_result_model['document_id'] = 'testString' - log_query_response_result_model['event_type'] = 'click' - log_query_response_result_model['result_type'] = 'document' - - # Construct a json representation of a LogQueryResponse model - log_query_response_model_json = {} - log_query_response_model_json['matching_results'] = 38 - log_query_response_model_json['results'] = [log_query_response_result_model] - - # Construct a model instance of LogQueryResponse by calling from_dict on the json representation - log_query_response_model = LogQueryResponse.from_dict(log_query_response_model_json) - assert log_query_response_model != False - - # Construct a model instance of LogQueryResponse by calling from_dict on the json representation - log_query_response_model_dict = LogQueryResponse.from_dict(log_query_response_model_json).__dict__ - log_query_response_model2 = LogQueryResponse(**log_query_response_model_dict) - - # Verify the model instances are equivalent - assert log_query_response_model == log_query_response_model2 - - # Convert model instance back to dict and verify no loss of data - log_query_response_model_json2 = log_query_response_model.to_dict() - assert log_query_response_model_json2 == log_query_response_model_json - - -class TestModel_LogQueryResponseResult: - """ - Test Class for LogQueryResponseResult - """ - - def test_log_query_response_result_serialization(self): - """ - Test serialization/deserialization for LogQueryResponseResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult - log_query_response_result_documents_result_model['position'] = 38 - log_query_response_result_documents_result_model['document_id'] = 'testString' - log_query_response_result_documents_result_model['score'] = 72.5 - log_query_response_result_documents_result_model['confidence'] = 72.5 - log_query_response_result_documents_result_model['collection_id'] = 'testString' - - log_query_response_result_documents_model = {} # LogQueryResponseResultDocuments - log_query_response_result_documents_model['results'] = [log_query_response_result_documents_result_model] - log_query_response_result_documents_model['count'] = 38 - - # Construct a json representation of a LogQueryResponseResult model - log_query_response_result_model_json = {} - log_query_response_result_model_json['environment_id'] = 'testString' - log_query_response_result_model_json['customer_id'] = 'testString' - log_query_response_result_model_json['document_type'] = 'query' - log_query_response_result_model_json['natural_language_query'] = 'testString' - log_query_response_result_model_json['document_results'] = log_query_response_result_documents_model - log_query_response_result_model_json['created_timestamp'] = '2019-01-01T12:00:00Z' - log_query_response_result_model_json['client_timestamp'] = '2019-01-01T12:00:00Z' - log_query_response_result_model_json['query_id'] = 'testString' - log_query_response_result_model_json['session_token'] = 'testString' - log_query_response_result_model_json['collection_id'] = 'testString' - log_query_response_result_model_json['display_rank'] = 38 - log_query_response_result_model_json['document_id'] = 'testString' - log_query_response_result_model_json['event_type'] = 'click' - log_query_response_result_model_json['result_type'] = 'document' - - # Construct a model instance of LogQueryResponseResult by calling from_dict on the json representation - log_query_response_result_model = LogQueryResponseResult.from_dict(log_query_response_result_model_json) - assert log_query_response_result_model != False - - # Construct a model instance of LogQueryResponseResult by calling from_dict on the json representation - log_query_response_result_model_dict = LogQueryResponseResult.from_dict(log_query_response_result_model_json).__dict__ - log_query_response_result_model2 = LogQueryResponseResult(**log_query_response_result_model_dict) - - # Verify the model instances are equivalent - assert log_query_response_result_model == log_query_response_result_model2 - - # Convert model instance back to dict and verify no loss of data - log_query_response_result_model_json2 = log_query_response_result_model.to_dict() - assert log_query_response_result_model_json2 == log_query_response_result_model_json - - -class TestModel_LogQueryResponseResultDocuments: - """ - Test Class for LogQueryResponseResultDocuments - """ - - def test_log_query_response_result_documents_serialization(self): - """ - Test serialization/deserialization for LogQueryResponseResultDocuments - """ - - # Construct dict forms of any model objects needed in order to build this model. - - log_query_response_result_documents_result_model = {} # LogQueryResponseResultDocumentsResult - log_query_response_result_documents_result_model['position'] = 38 - log_query_response_result_documents_result_model['document_id'] = 'testString' - log_query_response_result_documents_result_model['score'] = 72.5 - log_query_response_result_documents_result_model['confidence'] = 72.5 - log_query_response_result_documents_result_model['collection_id'] = 'testString' - - # Construct a json representation of a LogQueryResponseResultDocuments model - log_query_response_result_documents_model_json = {} - log_query_response_result_documents_model_json['results'] = [log_query_response_result_documents_result_model] - log_query_response_result_documents_model_json['count'] = 38 - - # Construct a model instance of LogQueryResponseResultDocuments by calling from_dict on the json representation - log_query_response_result_documents_model = LogQueryResponseResultDocuments.from_dict(log_query_response_result_documents_model_json) - assert log_query_response_result_documents_model != False - - # Construct a model instance of LogQueryResponseResultDocuments by calling from_dict on the json representation - log_query_response_result_documents_model_dict = LogQueryResponseResultDocuments.from_dict(log_query_response_result_documents_model_json).__dict__ - log_query_response_result_documents_model2 = LogQueryResponseResultDocuments(**log_query_response_result_documents_model_dict) - - # Verify the model instances are equivalent - assert log_query_response_result_documents_model == log_query_response_result_documents_model2 - - # Convert model instance back to dict and verify no loss of data - log_query_response_result_documents_model_json2 = log_query_response_result_documents_model.to_dict() - assert log_query_response_result_documents_model_json2 == log_query_response_result_documents_model_json - - -class TestModel_LogQueryResponseResultDocumentsResult: - """ - Test Class for LogQueryResponseResultDocumentsResult - """ - - def test_log_query_response_result_documents_result_serialization(self): - """ - Test serialization/deserialization for LogQueryResponseResultDocumentsResult - """ - - # Construct a json representation of a LogQueryResponseResultDocumentsResult model - log_query_response_result_documents_result_model_json = {} - log_query_response_result_documents_result_model_json['position'] = 38 - log_query_response_result_documents_result_model_json['document_id'] = 'testString' - log_query_response_result_documents_result_model_json['score'] = 72.5 - log_query_response_result_documents_result_model_json['confidence'] = 72.5 - log_query_response_result_documents_result_model_json['collection_id'] = 'testString' - - # Construct a model instance of LogQueryResponseResultDocumentsResult by calling from_dict on the json representation - log_query_response_result_documents_result_model = LogQueryResponseResultDocumentsResult.from_dict(log_query_response_result_documents_result_model_json) - assert log_query_response_result_documents_result_model != False - - # Construct a model instance of LogQueryResponseResultDocumentsResult by calling from_dict on the json representation - log_query_response_result_documents_result_model_dict = LogQueryResponseResultDocumentsResult.from_dict(log_query_response_result_documents_result_model_json).__dict__ - log_query_response_result_documents_result_model2 = LogQueryResponseResultDocumentsResult(**log_query_response_result_documents_result_model_dict) - - # Verify the model instances are equivalent - assert log_query_response_result_documents_result_model == log_query_response_result_documents_result_model2 - - # Convert model instance back to dict and verify no loss of data - log_query_response_result_documents_result_model_json2 = log_query_response_result_documents_result_model.to_dict() - assert log_query_response_result_documents_result_model_json2 == log_query_response_result_documents_result_model_json - - -class TestModel_MetricAggregation: - """ - Test Class for MetricAggregation - """ - - def test_metric_aggregation_serialization(self): - """ - Test serialization/deserialization for MetricAggregation - """ - - # Construct dict forms of any model objects needed in order to build this model. - - metric_aggregation_result_model = {} # MetricAggregationResult - metric_aggregation_result_model['key_as_string'] = '2019-01-01T12:00:00Z' - metric_aggregation_result_model['key'] = 26 - metric_aggregation_result_model['matching_results'] = 38 - metric_aggregation_result_model['event_rate'] = 72.5 - - # Construct a json representation of a MetricAggregation model - metric_aggregation_model_json = {} - metric_aggregation_model_json['interval'] = 'testString' - metric_aggregation_model_json['event_type'] = 'testString' - metric_aggregation_model_json['results'] = [metric_aggregation_result_model] - - # Construct a model instance of MetricAggregation by calling from_dict on the json representation - metric_aggregation_model = MetricAggregation.from_dict(metric_aggregation_model_json) - assert metric_aggregation_model != False - - # Construct a model instance of MetricAggregation by calling from_dict on the json representation - metric_aggregation_model_dict = MetricAggregation.from_dict(metric_aggregation_model_json).__dict__ - metric_aggregation_model2 = MetricAggregation(**metric_aggregation_model_dict) - - # Verify the model instances are equivalent - assert metric_aggregation_model == metric_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - metric_aggregation_model_json2 = metric_aggregation_model.to_dict() - assert metric_aggregation_model_json2 == metric_aggregation_model_json - - -class TestModel_MetricAggregationResult: - """ - Test Class for MetricAggregationResult - """ - - def test_metric_aggregation_result_serialization(self): - """ - Test serialization/deserialization for MetricAggregationResult - """ - - # Construct a json representation of a MetricAggregationResult model - metric_aggregation_result_model_json = {} - metric_aggregation_result_model_json['key_as_string'] = '2019-01-01T12:00:00Z' - metric_aggregation_result_model_json['key'] = 26 - metric_aggregation_result_model_json['matching_results'] = 38 - metric_aggregation_result_model_json['event_rate'] = 72.5 - - # Construct a model instance of MetricAggregationResult by calling from_dict on the json representation - metric_aggregation_result_model = MetricAggregationResult.from_dict(metric_aggregation_result_model_json) - assert metric_aggregation_result_model != False - - # Construct a model instance of MetricAggregationResult by calling from_dict on the json representation - metric_aggregation_result_model_dict = MetricAggregationResult.from_dict(metric_aggregation_result_model_json).__dict__ - metric_aggregation_result_model2 = MetricAggregationResult(**metric_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert metric_aggregation_result_model == metric_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - metric_aggregation_result_model_json2 = metric_aggregation_result_model.to_dict() - assert metric_aggregation_result_model_json2 == metric_aggregation_result_model_json - - -class TestModel_MetricResponse: - """ - Test Class for MetricResponse - """ - - def test_metric_response_serialization(self): - """ - Test serialization/deserialization for MetricResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - metric_aggregation_result_model = {} # MetricAggregationResult - metric_aggregation_result_model['key_as_string'] = '2019-01-01T12:00:00Z' - metric_aggregation_result_model['key'] = 26 - metric_aggregation_result_model['matching_results'] = 38 - metric_aggregation_result_model['event_rate'] = 72.5 - - metric_aggregation_model = {} # MetricAggregation - metric_aggregation_model['interval'] = 'testString' - metric_aggregation_model['event_type'] = 'testString' - metric_aggregation_model['results'] = [metric_aggregation_result_model] - - # Construct a json representation of a MetricResponse model - metric_response_model_json = {} - metric_response_model_json['aggregations'] = [metric_aggregation_model] - - # Construct a model instance of MetricResponse by calling from_dict on the json representation - metric_response_model = MetricResponse.from_dict(metric_response_model_json) - assert metric_response_model != False - - # Construct a model instance of MetricResponse by calling from_dict on the json representation - metric_response_model_dict = MetricResponse.from_dict(metric_response_model_json).__dict__ - metric_response_model2 = MetricResponse(**metric_response_model_dict) - - # Verify the model instances are equivalent - assert metric_response_model == metric_response_model2 - - # Convert model instance back to dict and verify no loss of data - metric_response_model_json2 = metric_response_model.to_dict() - assert metric_response_model_json2 == metric_response_model_json - - -class TestModel_MetricTokenAggregation: - """ - Test Class for MetricTokenAggregation - """ - - def test_metric_token_aggregation_serialization(self): - """ - Test serialization/deserialization for MetricTokenAggregation - """ - - # Construct dict forms of any model objects needed in order to build this model. - - metric_token_aggregation_result_model = {} # MetricTokenAggregationResult - metric_token_aggregation_result_model['key'] = 'testString' - metric_token_aggregation_result_model['matching_results'] = 38 - metric_token_aggregation_result_model['event_rate'] = 72.5 - - # Construct a json representation of a MetricTokenAggregation model - metric_token_aggregation_model_json = {} - metric_token_aggregation_model_json['event_type'] = 'testString' - metric_token_aggregation_model_json['results'] = [metric_token_aggregation_result_model] - - # Construct a model instance of MetricTokenAggregation by calling from_dict on the json representation - metric_token_aggregation_model = MetricTokenAggregation.from_dict(metric_token_aggregation_model_json) - assert metric_token_aggregation_model != False - - # Construct a model instance of MetricTokenAggregation by calling from_dict on the json representation - metric_token_aggregation_model_dict = MetricTokenAggregation.from_dict(metric_token_aggregation_model_json).__dict__ - metric_token_aggregation_model2 = MetricTokenAggregation(**metric_token_aggregation_model_dict) - - # Verify the model instances are equivalent - assert metric_token_aggregation_model == metric_token_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - metric_token_aggregation_model_json2 = metric_token_aggregation_model.to_dict() - assert metric_token_aggregation_model_json2 == metric_token_aggregation_model_json - - -class TestModel_MetricTokenAggregationResult: - """ - Test Class for MetricTokenAggregationResult - """ - - def test_metric_token_aggregation_result_serialization(self): - """ - Test serialization/deserialization for MetricTokenAggregationResult - """ - - # Construct a json representation of a MetricTokenAggregationResult model - metric_token_aggregation_result_model_json = {} - metric_token_aggregation_result_model_json['key'] = 'testString' - metric_token_aggregation_result_model_json['matching_results'] = 38 - metric_token_aggregation_result_model_json['event_rate'] = 72.5 - - # Construct a model instance of MetricTokenAggregationResult by calling from_dict on the json representation - metric_token_aggregation_result_model = MetricTokenAggregationResult.from_dict(metric_token_aggregation_result_model_json) - assert metric_token_aggregation_result_model != False - - # Construct a model instance of MetricTokenAggregationResult by calling from_dict on the json representation - metric_token_aggregation_result_model_dict = MetricTokenAggregationResult.from_dict(metric_token_aggregation_result_model_json).__dict__ - metric_token_aggregation_result_model2 = MetricTokenAggregationResult(**metric_token_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert metric_token_aggregation_result_model == metric_token_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - metric_token_aggregation_result_model_json2 = metric_token_aggregation_result_model.to_dict() - assert metric_token_aggregation_result_model_json2 == metric_token_aggregation_result_model_json - - -class TestModel_MetricTokenResponse: - """ - Test Class for MetricTokenResponse - """ - - def test_metric_token_response_serialization(self): - """ - Test serialization/deserialization for MetricTokenResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - metric_token_aggregation_result_model = {} # MetricTokenAggregationResult - metric_token_aggregation_result_model['key'] = 'testString' - metric_token_aggregation_result_model['matching_results'] = 38 - metric_token_aggregation_result_model['event_rate'] = 72.5 - - metric_token_aggregation_model = {} # MetricTokenAggregation - metric_token_aggregation_model['event_type'] = 'testString' - metric_token_aggregation_model['results'] = [metric_token_aggregation_result_model] - - # Construct a json representation of a MetricTokenResponse model - metric_token_response_model_json = {} - metric_token_response_model_json['aggregations'] = [metric_token_aggregation_model] - - # Construct a model instance of MetricTokenResponse by calling from_dict on the json representation - metric_token_response_model = MetricTokenResponse.from_dict(metric_token_response_model_json) - assert metric_token_response_model != False - - # Construct a model instance of MetricTokenResponse by calling from_dict on the json representation - metric_token_response_model_dict = MetricTokenResponse.from_dict(metric_token_response_model_json).__dict__ - metric_token_response_model2 = MetricTokenResponse(**metric_token_response_model_dict) - - # Verify the model instances are equivalent - assert metric_token_response_model == metric_token_response_model2 - - # Convert model instance back to dict and verify no loss of data - metric_token_response_model_json2 = metric_token_response_model.to_dict() - assert metric_token_response_model_json2 == metric_token_response_model_json - - -class TestModel_NluEnrichmentConcepts: - """ - Test Class for NluEnrichmentConcepts - """ - - def test_nlu_enrichment_concepts_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentConcepts - """ - - # Construct a json representation of a NluEnrichmentConcepts model - nlu_enrichment_concepts_model_json = {} - nlu_enrichment_concepts_model_json['limit'] = 38 - - # Construct a model instance of NluEnrichmentConcepts by calling from_dict on the json representation - nlu_enrichment_concepts_model = NluEnrichmentConcepts.from_dict(nlu_enrichment_concepts_model_json) - assert nlu_enrichment_concepts_model != False - - # Construct a model instance of NluEnrichmentConcepts by calling from_dict on the json representation - nlu_enrichment_concepts_model_dict = NluEnrichmentConcepts.from_dict(nlu_enrichment_concepts_model_json).__dict__ - nlu_enrichment_concepts_model2 = NluEnrichmentConcepts(**nlu_enrichment_concepts_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_concepts_model == nlu_enrichment_concepts_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_concepts_model_json2 = nlu_enrichment_concepts_model.to_dict() - assert nlu_enrichment_concepts_model_json2 == nlu_enrichment_concepts_model_json - - -class TestModel_NluEnrichmentEmotion: - """ - Test Class for NluEnrichmentEmotion - """ - - def test_nlu_enrichment_emotion_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentEmotion - """ - - # Construct a json representation of a NluEnrichmentEmotion model - nlu_enrichment_emotion_model_json = {} - nlu_enrichment_emotion_model_json['document'] = True - nlu_enrichment_emotion_model_json['targets'] = ['testString'] - - # Construct a model instance of NluEnrichmentEmotion by calling from_dict on the json representation - nlu_enrichment_emotion_model = NluEnrichmentEmotion.from_dict(nlu_enrichment_emotion_model_json) - assert nlu_enrichment_emotion_model != False - - # Construct a model instance of NluEnrichmentEmotion by calling from_dict on the json representation - nlu_enrichment_emotion_model_dict = NluEnrichmentEmotion.from_dict(nlu_enrichment_emotion_model_json).__dict__ - nlu_enrichment_emotion_model2 = NluEnrichmentEmotion(**nlu_enrichment_emotion_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_emotion_model == nlu_enrichment_emotion_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_emotion_model_json2 = nlu_enrichment_emotion_model.to_dict() - assert nlu_enrichment_emotion_model_json2 == nlu_enrichment_emotion_model_json - - -class TestModel_NluEnrichmentEntities: - """ - Test Class for NluEnrichmentEntities - """ - - def test_nlu_enrichment_entities_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentEntities - """ - - # Construct a json representation of a NluEnrichmentEntities model - nlu_enrichment_entities_model_json = {} - nlu_enrichment_entities_model_json['sentiment'] = True - nlu_enrichment_entities_model_json['emotion'] = True - nlu_enrichment_entities_model_json['limit'] = 38 - nlu_enrichment_entities_model_json['mentions'] = True - nlu_enrichment_entities_model_json['mention_types'] = True - nlu_enrichment_entities_model_json['sentence_locations'] = True - nlu_enrichment_entities_model_json['model'] = 'testString' - - # Construct a model instance of NluEnrichmentEntities by calling from_dict on the json representation - nlu_enrichment_entities_model = NluEnrichmentEntities.from_dict(nlu_enrichment_entities_model_json) - assert nlu_enrichment_entities_model != False - - # Construct a model instance of NluEnrichmentEntities by calling from_dict on the json representation - nlu_enrichment_entities_model_dict = NluEnrichmentEntities.from_dict(nlu_enrichment_entities_model_json).__dict__ - nlu_enrichment_entities_model2 = NluEnrichmentEntities(**nlu_enrichment_entities_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_entities_model == nlu_enrichment_entities_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_entities_model_json2 = nlu_enrichment_entities_model.to_dict() - assert nlu_enrichment_entities_model_json2 == nlu_enrichment_entities_model_json - - -class TestModel_NluEnrichmentFeatures: - """ - Test Class for NluEnrichmentFeatures - """ - - def test_nlu_enrichment_features_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentFeatures - """ - - # Construct dict forms of any model objects needed in order to build this model. - - nlu_enrichment_keywords_model = {} # NluEnrichmentKeywords - nlu_enrichment_keywords_model['sentiment'] = True - nlu_enrichment_keywords_model['emotion'] = True - nlu_enrichment_keywords_model['limit'] = 38 - - nlu_enrichment_entities_model = {} # NluEnrichmentEntities - nlu_enrichment_entities_model['sentiment'] = True - nlu_enrichment_entities_model['emotion'] = True - nlu_enrichment_entities_model['limit'] = 38 - nlu_enrichment_entities_model['mentions'] = True - nlu_enrichment_entities_model['mention_types'] = True - nlu_enrichment_entities_model['sentence_locations'] = True - nlu_enrichment_entities_model['model'] = 'testString' - - nlu_enrichment_sentiment_model = {} # NluEnrichmentSentiment - nlu_enrichment_sentiment_model['document'] = True - nlu_enrichment_sentiment_model['targets'] = ['testString'] - - nlu_enrichment_emotion_model = {} # NluEnrichmentEmotion - nlu_enrichment_emotion_model['document'] = True - nlu_enrichment_emotion_model['targets'] = ['testString'] - - nlu_enrichment_semantic_roles_model = {} # NluEnrichmentSemanticRoles - nlu_enrichment_semantic_roles_model['entities'] = True - nlu_enrichment_semantic_roles_model['keywords'] = True - nlu_enrichment_semantic_roles_model['limit'] = 38 - - nlu_enrichment_relations_model = {} # NluEnrichmentRelations - nlu_enrichment_relations_model['model'] = 'testString' - - nlu_enrichment_concepts_model = {} # NluEnrichmentConcepts - nlu_enrichment_concepts_model['limit'] = 38 - - # Construct a json representation of a NluEnrichmentFeatures model - nlu_enrichment_features_model_json = {} - nlu_enrichment_features_model_json['keywords'] = nlu_enrichment_keywords_model - nlu_enrichment_features_model_json['entities'] = nlu_enrichment_entities_model - nlu_enrichment_features_model_json['sentiment'] = nlu_enrichment_sentiment_model - nlu_enrichment_features_model_json['emotion'] = nlu_enrichment_emotion_model - nlu_enrichment_features_model_json['categories'] = {'anyKey': 'anyValue'} - nlu_enrichment_features_model_json['semantic_roles'] = nlu_enrichment_semantic_roles_model - nlu_enrichment_features_model_json['relations'] = nlu_enrichment_relations_model - nlu_enrichment_features_model_json['concepts'] = nlu_enrichment_concepts_model - - # Construct a model instance of NluEnrichmentFeatures by calling from_dict on the json representation - nlu_enrichment_features_model = NluEnrichmentFeatures.from_dict(nlu_enrichment_features_model_json) - assert nlu_enrichment_features_model != False - - # Construct a model instance of NluEnrichmentFeatures by calling from_dict on the json representation - nlu_enrichment_features_model_dict = NluEnrichmentFeatures.from_dict(nlu_enrichment_features_model_json).__dict__ - nlu_enrichment_features_model2 = NluEnrichmentFeatures(**nlu_enrichment_features_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_features_model == nlu_enrichment_features_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_features_model_json2 = nlu_enrichment_features_model.to_dict() - assert nlu_enrichment_features_model_json2 == nlu_enrichment_features_model_json - - -class TestModel_NluEnrichmentKeywords: - """ - Test Class for NluEnrichmentKeywords - """ - - def test_nlu_enrichment_keywords_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentKeywords - """ - - # Construct a json representation of a NluEnrichmentKeywords model - nlu_enrichment_keywords_model_json = {} - nlu_enrichment_keywords_model_json['sentiment'] = True - nlu_enrichment_keywords_model_json['emotion'] = True - nlu_enrichment_keywords_model_json['limit'] = 38 - - # Construct a model instance of NluEnrichmentKeywords by calling from_dict on the json representation - nlu_enrichment_keywords_model = NluEnrichmentKeywords.from_dict(nlu_enrichment_keywords_model_json) - assert nlu_enrichment_keywords_model != False - - # Construct a model instance of NluEnrichmentKeywords by calling from_dict on the json representation - nlu_enrichment_keywords_model_dict = NluEnrichmentKeywords.from_dict(nlu_enrichment_keywords_model_json).__dict__ - nlu_enrichment_keywords_model2 = NluEnrichmentKeywords(**nlu_enrichment_keywords_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_keywords_model == nlu_enrichment_keywords_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_keywords_model_json2 = nlu_enrichment_keywords_model.to_dict() - assert nlu_enrichment_keywords_model_json2 == nlu_enrichment_keywords_model_json - - -class TestModel_NluEnrichmentRelations: - """ - Test Class for NluEnrichmentRelations - """ - - def test_nlu_enrichment_relations_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentRelations - """ - - # Construct a json representation of a NluEnrichmentRelations model - nlu_enrichment_relations_model_json = {} - nlu_enrichment_relations_model_json['model'] = 'testString' - - # Construct a model instance of NluEnrichmentRelations by calling from_dict on the json representation - nlu_enrichment_relations_model = NluEnrichmentRelations.from_dict(nlu_enrichment_relations_model_json) - assert nlu_enrichment_relations_model != False - - # Construct a model instance of NluEnrichmentRelations by calling from_dict on the json representation - nlu_enrichment_relations_model_dict = NluEnrichmentRelations.from_dict(nlu_enrichment_relations_model_json).__dict__ - nlu_enrichment_relations_model2 = NluEnrichmentRelations(**nlu_enrichment_relations_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_relations_model == nlu_enrichment_relations_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_relations_model_json2 = nlu_enrichment_relations_model.to_dict() - assert nlu_enrichment_relations_model_json2 == nlu_enrichment_relations_model_json - - -class TestModel_NluEnrichmentSemanticRoles: - """ - Test Class for NluEnrichmentSemanticRoles - """ - - def test_nlu_enrichment_semantic_roles_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentSemanticRoles - """ - - # Construct a json representation of a NluEnrichmentSemanticRoles model - nlu_enrichment_semantic_roles_model_json = {} - nlu_enrichment_semantic_roles_model_json['entities'] = True - nlu_enrichment_semantic_roles_model_json['keywords'] = True - nlu_enrichment_semantic_roles_model_json['limit'] = 38 - - # Construct a model instance of NluEnrichmentSemanticRoles by calling from_dict on the json representation - nlu_enrichment_semantic_roles_model = NluEnrichmentSemanticRoles.from_dict(nlu_enrichment_semantic_roles_model_json) - assert nlu_enrichment_semantic_roles_model != False - - # Construct a model instance of NluEnrichmentSemanticRoles by calling from_dict on the json representation - nlu_enrichment_semantic_roles_model_dict = NluEnrichmentSemanticRoles.from_dict(nlu_enrichment_semantic_roles_model_json).__dict__ - nlu_enrichment_semantic_roles_model2 = NluEnrichmentSemanticRoles(**nlu_enrichment_semantic_roles_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_semantic_roles_model == nlu_enrichment_semantic_roles_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_semantic_roles_model_json2 = nlu_enrichment_semantic_roles_model.to_dict() - assert nlu_enrichment_semantic_roles_model_json2 == nlu_enrichment_semantic_roles_model_json - - -class TestModel_NluEnrichmentSentiment: - """ - Test Class for NluEnrichmentSentiment - """ - - def test_nlu_enrichment_sentiment_serialization(self): - """ - Test serialization/deserialization for NluEnrichmentSentiment - """ - - # Construct a json representation of a NluEnrichmentSentiment model - nlu_enrichment_sentiment_model_json = {} - nlu_enrichment_sentiment_model_json['document'] = True - nlu_enrichment_sentiment_model_json['targets'] = ['testString'] - - # Construct a model instance of NluEnrichmentSentiment by calling from_dict on the json representation - nlu_enrichment_sentiment_model = NluEnrichmentSentiment.from_dict(nlu_enrichment_sentiment_model_json) - assert nlu_enrichment_sentiment_model != False - - # Construct a model instance of NluEnrichmentSentiment by calling from_dict on the json representation - nlu_enrichment_sentiment_model_dict = NluEnrichmentSentiment.from_dict(nlu_enrichment_sentiment_model_json).__dict__ - nlu_enrichment_sentiment_model2 = NluEnrichmentSentiment(**nlu_enrichment_sentiment_model_dict) - - # Verify the model instances are equivalent - assert nlu_enrichment_sentiment_model == nlu_enrichment_sentiment_model2 - - # Convert model instance back to dict and verify no loss of data - nlu_enrichment_sentiment_model_json2 = nlu_enrichment_sentiment_model.to_dict() - assert nlu_enrichment_sentiment_model_json2 == nlu_enrichment_sentiment_model_json - - -class TestModel_NormalizationOperation: - """ - Test Class for NormalizationOperation - """ - - def test_normalization_operation_serialization(self): - """ - Test serialization/deserialization for NormalizationOperation - """ - - # Construct a json representation of a NormalizationOperation model - normalization_operation_model_json = {} - normalization_operation_model_json['operation'] = 'copy' - normalization_operation_model_json['source_field'] = 'testString' - normalization_operation_model_json['destination_field'] = 'testString' - - # Construct a model instance of NormalizationOperation by calling from_dict on the json representation - normalization_operation_model = NormalizationOperation.from_dict(normalization_operation_model_json) - assert normalization_operation_model != False - - # Construct a model instance of NormalizationOperation by calling from_dict on the json representation - normalization_operation_model_dict = NormalizationOperation.from_dict(normalization_operation_model_json).__dict__ - normalization_operation_model2 = NormalizationOperation(**normalization_operation_model_dict) - - # Verify the model instances are equivalent - assert normalization_operation_model == normalization_operation_model2 - - # Convert model instance back to dict and verify no loss of data - normalization_operation_model_json2 = normalization_operation_model.to_dict() - assert normalization_operation_model_json2 == normalization_operation_model_json - - -class TestModel_Notice: - """ - Test Class for Notice - """ - - def test_notice_serialization(self): - """ - Test serialization/deserialization for Notice - """ - - # Construct a json representation of a Notice model - notice_model_json = {} - - # Construct a model instance of Notice by calling from_dict on the json representation - notice_model = Notice.from_dict(notice_model_json) - assert notice_model != False - - # Construct a model instance of Notice by calling from_dict on the json representation - notice_model_dict = Notice.from_dict(notice_model_json).__dict__ - notice_model2 = Notice(**notice_model_dict) - - # Verify the model instances are equivalent - assert notice_model == notice_model2 - - # Convert model instance back to dict and verify no loss of data - notice_model_json2 = notice_model.to_dict() - assert notice_model_json2 == notice_model_json - - -class TestModel_PdfHeadingDetection: - """ - Test Class for PdfHeadingDetection - """ - - def test_pdf_heading_detection_serialization(self): - """ - Test serialization/deserialization for PdfHeadingDetection - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - # Construct a json representation of a PdfHeadingDetection model - pdf_heading_detection_model_json = {} - pdf_heading_detection_model_json['fonts'] = [font_setting_model] - - # Construct a model instance of PdfHeadingDetection by calling from_dict on the json representation - pdf_heading_detection_model = PdfHeadingDetection.from_dict(pdf_heading_detection_model_json) - assert pdf_heading_detection_model != False - - # Construct a model instance of PdfHeadingDetection by calling from_dict on the json representation - pdf_heading_detection_model_dict = PdfHeadingDetection.from_dict(pdf_heading_detection_model_json).__dict__ - pdf_heading_detection_model2 = PdfHeadingDetection(**pdf_heading_detection_model_dict) - - # Verify the model instances are equivalent - assert pdf_heading_detection_model == pdf_heading_detection_model2 - - # Convert model instance back to dict and verify no loss of data - pdf_heading_detection_model_json2 = pdf_heading_detection_model.to_dict() - assert pdf_heading_detection_model_json2 == pdf_heading_detection_model_json - - -class TestModel_PdfSettings: - """ - Test Class for PdfSettings - """ - - def test_pdf_settings_serialization(self): - """ - Test serialization/deserialization for PdfSettings - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - pdf_heading_detection_model = {} # PdfHeadingDetection - pdf_heading_detection_model['fonts'] = [font_setting_model] - - # Construct a json representation of a PdfSettings model - pdf_settings_model_json = {} - pdf_settings_model_json['heading'] = pdf_heading_detection_model - - # Construct a model instance of PdfSettings by calling from_dict on the json representation - pdf_settings_model = PdfSettings.from_dict(pdf_settings_model_json) - assert pdf_settings_model != False - - # Construct a model instance of PdfSettings by calling from_dict on the json representation - pdf_settings_model_dict = PdfSettings.from_dict(pdf_settings_model_json).__dict__ - pdf_settings_model2 = PdfSettings(**pdf_settings_model_dict) - - # Verify the model instances are equivalent - assert pdf_settings_model == pdf_settings_model2 - - # Convert model instance back to dict and verify no loss of data - pdf_settings_model_json2 = pdf_settings_model.to_dict() - assert pdf_settings_model_json2 == pdf_settings_model_json - - -class TestModel_QueryAggregation: - """ - Test Class for QueryAggregation - """ - - def test_query_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryAggregation - """ - - # Construct a json representation of a QueryAggregation model - query_aggregation_model_json = {} - query_aggregation_model_json['type'] = 'testString' - - # Construct a model instance of QueryAggregation by calling from_dict on the json representation - query_aggregation_model = QueryAggregation.from_dict(query_aggregation_model_json) - assert query_aggregation_model != False - - # Construct a copy of the model instance by calling from_dict on the output of to_dict - query_aggregation_model_json2 = query_aggregation_model.to_dict() - query_aggregation_model2 = QueryAggregation.from_dict(query_aggregation_model_json2) - - # Verify the model instances are equivalent - assert query_aggregation_model == query_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_aggregation_model_json2 = query_aggregation_model.to_dict() - assert query_aggregation_model_json2 == query_aggregation_model_json - - -class TestModel_QueryHistogramAggregationResult: - """ - Test Class for QueryHistogramAggregationResult - """ - - def test_query_histogram_aggregation_result_serialization(self): - """ - Test serialization/deserialization for QueryHistogramAggregationResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - - # Construct a json representation of a QueryHistogramAggregationResult model - query_histogram_aggregation_result_model_json = {} - query_histogram_aggregation_result_model_json['key'] = 26 - query_histogram_aggregation_result_model_json['matching_results'] = 38 - query_histogram_aggregation_result_model_json['aggregations'] = [query_aggregation_model] - - # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation - query_histogram_aggregation_result_model = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json) - assert query_histogram_aggregation_result_model != False - - # Construct a model instance of QueryHistogramAggregationResult by calling from_dict on the json representation - query_histogram_aggregation_result_model_dict = QueryHistogramAggregationResult.from_dict(query_histogram_aggregation_result_model_json).__dict__ - query_histogram_aggregation_result_model2 = QueryHistogramAggregationResult(**query_histogram_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert query_histogram_aggregation_result_model == query_histogram_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_histogram_aggregation_result_model_json2 = query_histogram_aggregation_result_model.to_dict() - assert query_histogram_aggregation_result_model_json2 == query_histogram_aggregation_result_model_json - - -class TestModel_QueryNoticesResponse: - """ - Test Class for QueryNoticesResponse - """ - - def test_query_notices_response_serialization(self): - """ - Test serialization/deserialization for QueryNoticesResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_result_metadata_model = {} # QueryResultMetadata - query_result_metadata_model['score'] = 72.5 - query_result_metadata_model['confidence'] = 72.5 - - notice_model = {} # Notice - - query_notices_result_model = {} # QueryNoticesResult - query_notices_result_model['id'] = '030ba125-29db-43f2-8552-f941ae30a7a8' - query_notices_result_model['metadata'] = {'anyKey': 'anyValue'} - query_notices_result_model['collection_id'] = 'f1360220-ea2d-4271-9d62-89a910b13c37' - query_notices_result_model['result_metadata'] = query_result_metadata_model - query_notices_result_model['code'] = 200 - query_notices_result_model['filename'] = 'instructions.html' - query_notices_result_model['file_type'] = 'html' - query_notices_result_model['sha1'] = 'de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3' - query_notices_result_model['notices'] = [notice_model] - query_notices_result_model['score'] = '1' - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - - query_passages_model = {} # QueryPassages - query_passages_model['document_id'] = 'testString' - query_passages_model['passage_score'] = 72.5 - query_passages_model['passage_text'] = 'testString' - query_passages_model['start_offset'] = 38 - query_passages_model['end_offset'] = 38 - query_passages_model['field'] = 'testString' - - # Construct a json representation of a QueryNoticesResponse model - query_notices_response_model_json = {} - query_notices_response_model_json['matching_results'] = 38 - query_notices_response_model_json['results'] = [query_notices_result_model] - query_notices_response_model_json['aggregations'] = [query_aggregation_model] - query_notices_response_model_json['passages'] = [query_passages_model] - query_notices_response_model_json['duplicates_removed'] = 38 - - # Construct a model instance of QueryNoticesResponse by calling from_dict on the json representation - query_notices_response_model = QueryNoticesResponse.from_dict(query_notices_response_model_json) - assert query_notices_response_model != False - - # Construct a model instance of QueryNoticesResponse by calling from_dict on the json representation - query_notices_response_model_dict = QueryNoticesResponse.from_dict(query_notices_response_model_json).__dict__ - query_notices_response_model2 = QueryNoticesResponse(**query_notices_response_model_dict) - - # Verify the model instances are equivalent - assert query_notices_response_model == query_notices_response_model2 - - # Convert model instance back to dict and verify no loss of data - query_notices_response_model_json2 = query_notices_response_model.to_dict() - assert query_notices_response_model_json2 == query_notices_response_model_json - - -class TestModel_QueryNoticesResult: - """ - Test Class for QueryNoticesResult - """ - - def test_query_notices_result_serialization(self): - """ - Test serialization/deserialization for QueryNoticesResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_result_metadata_model = {} # QueryResultMetadata - query_result_metadata_model['score'] = 72.5 - query_result_metadata_model['confidence'] = 72.5 - - notice_model = {} # Notice - - # Construct a json representation of a QueryNoticesResult model - query_notices_result_model_json = {} - query_notices_result_model_json['id'] = 'testString' - query_notices_result_model_json['metadata'] = {'anyKey': 'anyValue'} - query_notices_result_model_json['collection_id'] = 'testString' - query_notices_result_model_json['result_metadata'] = query_result_metadata_model - query_notices_result_model_json['code'] = 38 - query_notices_result_model_json['filename'] = 'testString' - query_notices_result_model_json['file_type'] = 'pdf' - query_notices_result_model_json['sha1'] = 'testString' - query_notices_result_model_json['notices'] = [notice_model] - query_notices_result_model_json['foo'] = 'testString' - - # Construct a model instance of QueryNoticesResult by calling from_dict on the json representation - query_notices_result_model = QueryNoticesResult.from_dict(query_notices_result_model_json) - assert query_notices_result_model != False - - # Construct a model instance of QueryNoticesResult by calling from_dict on the json representation - query_notices_result_model_dict = QueryNoticesResult.from_dict(query_notices_result_model_json).__dict__ - query_notices_result_model2 = QueryNoticesResult(**query_notices_result_model_dict) - - # Verify the model instances are equivalent - assert query_notices_result_model == query_notices_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_notices_result_model_json2 = query_notices_result_model.to_dict() - assert query_notices_result_model_json2 == query_notices_result_model_json - - # Test get_properties and set_properties methods. - query_notices_result_model.set_properties({}) - actual_dict = query_notices_result_model.get_properties() - assert actual_dict == {} - - expected_dict = {'foo': 'testString'} - query_notices_result_model.set_properties(expected_dict) - actual_dict = query_notices_result_model.get_properties() - assert actual_dict == expected_dict - - -class TestModel_QueryPassages: - """ - Test Class for QueryPassages - """ - - def test_query_passages_serialization(self): - """ - Test serialization/deserialization for QueryPassages - """ - - # Construct a json representation of a QueryPassages model - query_passages_model_json = {} - query_passages_model_json['document_id'] = 'testString' - query_passages_model_json['passage_score'] = 72.5 - query_passages_model_json['passage_text'] = 'testString' - query_passages_model_json['start_offset'] = 38 - query_passages_model_json['end_offset'] = 38 - query_passages_model_json['field'] = 'testString' - - # Construct a model instance of QueryPassages by calling from_dict on the json representation - query_passages_model = QueryPassages.from_dict(query_passages_model_json) - assert query_passages_model != False - - # Construct a model instance of QueryPassages by calling from_dict on the json representation - query_passages_model_dict = QueryPassages.from_dict(query_passages_model_json).__dict__ - query_passages_model2 = QueryPassages(**query_passages_model_dict) - - # Verify the model instances are equivalent - assert query_passages_model == query_passages_model2 - - # Convert model instance back to dict and verify no loss of data - query_passages_model_json2 = query_passages_model.to_dict() - assert query_passages_model_json2 == query_passages_model_json - - -class TestModel_QueryResponse: - """ - Test Class for QueryResponse - """ - - def test_query_response_serialization(self): - """ - Test serialization/deserialization for QueryResponse - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_result_metadata_model = {} # QueryResultMetadata - query_result_metadata_model['score'] = 72.5 - query_result_metadata_model['confidence'] = 72.5 - - query_result_model = {} # QueryResult - query_result_model['id'] = 'watson-generated ID' - query_result_model['metadata'] = {'anyKey': 'anyValue'} - query_result_model['collection_id'] = 'testString' - query_result_model['result_metadata'] = query_result_metadata_model - query_result_model['score'] = '1' - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - - query_passages_model = {} # QueryPassages - query_passages_model['document_id'] = 'testString' - query_passages_model['passage_score'] = 72.5 - query_passages_model['passage_text'] = 'testString' - query_passages_model['start_offset'] = 38 - query_passages_model['end_offset'] = 38 - query_passages_model['field'] = 'testString' - - retrieval_details_model = {} # RetrievalDetails - retrieval_details_model['document_retrieval_strategy'] = 'untrained' - - # Construct a json representation of a QueryResponse model - query_response_model_json = {} - query_response_model_json['matching_results'] = 38 - query_response_model_json['results'] = [query_result_model] - query_response_model_json['aggregations'] = [query_aggregation_model] - query_response_model_json['passages'] = [query_passages_model] - query_response_model_json['duplicates_removed'] = 38 - query_response_model_json['session_token'] = 'testString' - query_response_model_json['retrieval_details'] = retrieval_details_model - query_response_model_json['suggested_query'] = 'testString' - - # Construct a model instance of QueryResponse by calling from_dict on the json representation - query_response_model = QueryResponse.from_dict(query_response_model_json) - assert query_response_model != False - - # Construct a model instance of QueryResponse by calling from_dict on the json representation - query_response_model_dict = QueryResponse.from_dict(query_response_model_json).__dict__ - query_response_model2 = QueryResponse(**query_response_model_dict) - - # Verify the model instances are equivalent - assert query_response_model == query_response_model2 - - # Convert model instance back to dict and verify no loss of data - query_response_model_json2 = query_response_model.to_dict() - assert query_response_model_json2 == query_response_model_json - - -class TestModel_QueryResult: - """ - Test Class for QueryResult - """ - - def test_query_result_serialization(self): - """ - Test serialization/deserialization for QueryResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_result_metadata_model = {} # QueryResultMetadata - query_result_metadata_model['score'] = 72.5 - query_result_metadata_model['confidence'] = 72.5 - - # Construct a json representation of a QueryResult model - query_result_model_json = {} - query_result_model_json['id'] = 'testString' - query_result_model_json['metadata'] = {'anyKey': 'anyValue'} - query_result_model_json['collection_id'] = 'testString' - query_result_model_json['result_metadata'] = query_result_metadata_model - query_result_model_json['foo'] = 'testString' - - # Construct a model instance of QueryResult by calling from_dict on the json representation - query_result_model = QueryResult.from_dict(query_result_model_json) - assert query_result_model != False - - # Construct a model instance of QueryResult by calling from_dict on the json representation - query_result_model_dict = QueryResult.from_dict(query_result_model_json).__dict__ - query_result_model2 = QueryResult(**query_result_model_dict) - - # Verify the model instances are equivalent - assert query_result_model == query_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_result_model_json2 = query_result_model.to_dict() - assert query_result_model_json2 == query_result_model_json - - # Test get_properties and set_properties methods. - query_result_model.set_properties({}) - actual_dict = query_result_model.get_properties() - assert actual_dict == {} - - expected_dict = {'foo': 'testString'} - query_result_model.set_properties(expected_dict) - actual_dict = query_result_model.get_properties() - assert actual_dict == expected_dict - - -class TestModel_QueryResultMetadata: - """ - Test Class for QueryResultMetadata - """ - - def test_query_result_metadata_serialization(self): - """ - Test serialization/deserialization for QueryResultMetadata - """ - - # Construct a json representation of a QueryResultMetadata model - query_result_metadata_model_json = {} - query_result_metadata_model_json['score'] = 72.5 - query_result_metadata_model_json['confidence'] = 72.5 - - # Construct a model instance of QueryResultMetadata by calling from_dict on the json representation - query_result_metadata_model = QueryResultMetadata.from_dict(query_result_metadata_model_json) - assert query_result_metadata_model != False - - # Construct a model instance of QueryResultMetadata by calling from_dict on the json representation - query_result_metadata_model_dict = QueryResultMetadata.from_dict(query_result_metadata_model_json).__dict__ - query_result_metadata_model2 = QueryResultMetadata(**query_result_metadata_model_dict) - - # Verify the model instances are equivalent - assert query_result_metadata_model == query_result_metadata_model2 - - # Convert model instance back to dict and verify no loss of data - query_result_metadata_model_json2 = query_result_metadata_model.to_dict() - assert query_result_metadata_model_json2 == query_result_metadata_model_json - - -class TestModel_QueryTermAggregationResult: - """ - Test Class for QueryTermAggregationResult - """ - - def test_query_term_aggregation_result_serialization(self): - """ - Test serialization/deserialization for QueryTermAggregationResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - - # Construct a json representation of a QueryTermAggregationResult model - query_term_aggregation_result_model_json = {} - query_term_aggregation_result_model_json['key'] = 'testString' - query_term_aggregation_result_model_json['matching_results'] = 38 - query_term_aggregation_result_model_json['relevancy'] = 72.5 - query_term_aggregation_result_model_json['total_matching_documents'] = 38 - query_term_aggregation_result_model_json['estimated_matching_documents'] = 38 - query_term_aggregation_result_model_json['aggregations'] = [query_aggregation_model] - - # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation - query_term_aggregation_result_model = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json) - assert query_term_aggregation_result_model != False - - # Construct a model instance of QueryTermAggregationResult by calling from_dict on the json representation - query_term_aggregation_result_model_dict = QueryTermAggregationResult.from_dict(query_term_aggregation_result_model_json).__dict__ - query_term_aggregation_result_model2 = QueryTermAggregationResult(**query_term_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert query_term_aggregation_result_model == query_term_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_term_aggregation_result_model_json2 = query_term_aggregation_result_model.to_dict() - assert query_term_aggregation_result_model_json2 == query_term_aggregation_result_model_json - - -class TestModel_QueryTimesliceAggregationResult: - """ - Test Class for QueryTimesliceAggregationResult - """ - - def test_query_timeslice_aggregation_result_serialization(self): - """ - Test serialization/deserialization for QueryTimesliceAggregationResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_aggregation_model = {} # QueryFilterAggregation - query_aggregation_model['type'] = 'filter' - query_aggregation_model['match'] = 'testString' - query_aggregation_model['matching_results'] = 26 - - # Construct a json representation of a QueryTimesliceAggregationResult model - query_timeslice_aggregation_result_model_json = {} - query_timeslice_aggregation_result_model_json['key_as_string'] = 'testString' - query_timeslice_aggregation_result_model_json['key'] = 26 - query_timeslice_aggregation_result_model_json['matching_results'] = 26 - query_timeslice_aggregation_result_model_json['aggregations'] = [query_aggregation_model] - - # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation - query_timeslice_aggregation_result_model = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json) - assert query_timeslice_aggregation_result_model != False - - # Construct a model instance of QueryTimesliceAggregationResult by calling from_dict on the json representation - query_timeslice_aggregation_result_model_dict = QueryTimesliceAggregationResult.from_dict(query_timeslice_aggregation_result_model_json).__dict__ - query_timeslice_aggregation_result_model2 = QueryTimesliceAggregationResult(**query_timeslice_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert query_timeslice_aggregation_result_model == query_timeslice_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_timeslice_aggregation_result_model_json2 = query_timeslice_aggregation_result_model.to_dict() - assert query_timeslice_aggregation_result_model_json2 == query_timeslice_aggregation_result_model_json - - -class TestModel_QueryTopHitsAggregationResult: - """ - Test Class for QueryTopHitsAggregationResult - """ - - def test_query_top_hits_aggregation_result_serialization(self): - """ - Test serialization/deserialization for QueryTopHitsAggregationResult - """ - - # Construct a json representation of a QueryTopHitsAggregationResult model - query_top_hits_aggregation_result_model_json = {} - query_top_hits_aggregation_result_model_json['matching_results'] = 38 - query_top_hits_aggregation_result_model_json['hits'] = [{'anyKey': 'anyValue'}] - - # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation - query_top_hits_aggregation_result_model = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json) - assert query_top_hits_aggregation_result_model != False - - # Construct a model instance of QueryTopHitsAggregationResult by calling from_dict on the json representation - query_top_hits_aggregation_result_model_dict = QueryTopHitsAggregationResult.from_dict(query_top_hits_aggregation_result_model_json).__dict__ - query_top_hits_aggregation_result_model2 = QueryTopHitsAggregationResult(**query_top_hits_aggregation_result_model_dict) - - # Verify the model instances are equivalent - assert query_top_hits_aggregation_result_model == query_top_hits_aggregation_result_model2 - - # Convert model instance back to dict and verify no loss of data - query_top_hits_aggregation_result_model_json2 = query_top_hits_aggregation_result_model.to_dict() - assert query_top_hits_aggregation_result_model_json2 == query_top_hits_aggregation_result_model_json - - -class TestModel_RetrievalDetails: - """ - Test Class for RetrievalDetails - """ - - def test_retrieval_details_serialization(self): - """ - Test serialization/deserialization for RetrievalDetails - """ - - # Construct a json representation of a RetrievalDetails model - retrieval_details_model_json = {} - retrieval_details_model_json['document_retrieval_strategy'] = 'untrained' - - # Construct a model instance of RetrievalDetails by calling from_dict on the json representation - retrieval_details_model = RetrievalDetails.from_dict(retrieval_details_model_json) - assert retrieval_details_model != False - - # Construct a model instance of RetrievalDetails by calling from_dict on the json representation - retrieval_details_model_dict = RetrievalDetails.from_dict(retrieval_details_model_json).__dict__ - retrieval_details_model2 = RetrievalDetails(**retrieval_details_model_dict) - - # Verify the model instances are equivalent - assert retrieval_details_model == retrieval_details_model2 - - # Convert model instance back to dict and verify no loss of data - retrieval_details_model_json2 = retrieval_details_model.to_dict() - assert retrieval_details_model_json2 == retrieval_details_model_json - - -class TestModel_SduStatus: - """ - Test Class for SduStatus - """ - - def test_sdu_status_serialization(self): - """ - Test serialization/deserialization for SduStatus - """ - - # Construct dict forms of any model objects needed in order to build this model. - - sdu_status_custom_fields_model = {} # SduStatusCustomFields - sdu_status_custom_fields_model['defined'] = 26 - sdu_status_custom_fields_model['maximum_allowed'] = 26 - - # Construct a json representation of a SduStatus model - sdu_status_model_json = {} - sdu_status_model_json['enabled'] = True - sdu_status_model_json['total_annotated_pages'] = 26 - sdu_status_model_json['total_pages'] = 26 - sdu_status_model_json['total_documents'] = 26 - sdu_status_model_json['custom_fields'] = sdu_status_custom_fields_model - - # Construct a model instance of SduStatus by calling from_dict on the json representation - sdu_status_model = SduStatus.from_dict(sdu_status_model_json) - assert sdu_status_model != False - - # Construct a model instance of SduStatus by calling from_dict on the json representation - sdu_status_model_dict = SduStatus.from_dict(sdu_status_model_json).__dict__ - sdu_status_model2 = SduStatus(**sdu_status_model_dict) - - # Verify the model instances are equivalent - assert sdu_status_model == sdu_status_model2 - - # Convert model instance back to dict and verify no loss of data - sdu_status_model_json2 = sdu_status_model.to_dict() - assert sdu_status_model_json2 == sdu_status_model_json - - -class TestModel_SduStatusCustomFields: - """ - Test Class for SduStatusCustomFields - """ - - def test_sdu_status_custom_fields_serialization(self): - """ - Test serialization/deserialization for SduStatusCustomFields - """ - - # Construct a json representation of a SduStatusCustomFields model - sdu_status_custom_fields_model_json = {} - sdu_status_custom_fields_model_json['defined'] = 26 - sdu_status_custom_fields_model_json['maximum_allowed'] = 26 - - # Construct a model instance of SduStatusCustomFields by calling from_dict on the json representation - sdu_status_custom_fields_model = SduStatusCustomFields.from_dict(sdu_status_custom_fields_model_json) - assert sdu_status_custom_fields_model != False - - # Construct a model instance of SduStatusCustomFields by calling from_dict on the json representation - sdu_status_custom_fields_model_dict = SduStatusCustomFields.from_dict(sdu_status_custom_fields_model_json).__dict__ - sdu_status_custom_fields_model2 = SduStatusCustomFields(**sdu_status_custom_fields_model_dict) - - # Verify the model instances are equivalent - assert sdu_status_custom_fields_model == sdu_status_custom_fields_model2 - - # Convert model instance back to dict and verify no loss of data - sdu_status_custom_fields_model_json2 = sdu_status_custom_fields_model.to_dict() - assert sdu_status_custom_fields_model_json2 == sdu_status_custom_fields_model_json - - -class TestModel_SearchStatus: - """ - Test Class for SearchStatus - """ - - def test_search_status_serialization(self): - """ - Test serialization/deserialization for SearchStatus - """ - - # Construct a json representation of a SearchStatus model - search_status_model_json = {} - search_status_model_json['scope'] = 'testString' - search_status_model_json['status'] = 'NO_DATA' - search_status_model_json['status_description'] = 'testString' - search_status_model_json['last_trained'] = '2019-01-01' - - # Construct a model instance of SearchStatus by calling from_dict on the json representation - search_status_model = SearchStatus.from_dict(search_status_model_json) - assert search_status_model != False - - # Construct a model instance of SearchStatus by calling from_dict on the json representation - search_status_model_dict = SearchStatus.from_dict(search_status_model_json).__dict__ - search_status_model2 = SearchStatus(**search_status_model_dict) - - # Verify the model instances are equivalent - assert search_status_model == search_status_model2 - - # Convert model instance back to dict and verify no loss of data - search_status_model_json2 = search_status_model.to_dict() - assert search_status_model_json2 == search_status_model_json - - -class TestModel_SegmentSettings: - """ - Test Class for SegmentSettings - """ - - def test_segment_settings_serialization(self): - """ - Test serialization/deserialization for SegmentSettings - """ - - # Construct a json representation of a SegmentSettings model - segment_settings_model_json = {} - segment_settings_model_json['enabled'] = False - segment_settings_model_json['selector_tags'] = ['h1', 'h2'] - segment_settings_model_json['annotated_fields'] = ['testString'] - - # Construct a model instance of SegmentSettings by calling from_dict on the json representation - segment_settings_model = SegmentSettings.from_dict(segment_settings_model_json) - assert segment_settings_model != False - - # Construct a model instance of SegmentSettings by calling from_dict on the json representation - segment_settings_model_dict = SegmentSettings.from_dict(segment_settings_model_json).__dict__ - segment_settings_model2 = SegmentSettings(**segment_settings_model_dict) - - # Verify the model instances are equivalent - assert segment_settings_model == segment_settings_model2 - - # Convert model instance back to dict and verify no loss of data - segment_settings_model_json2 = segment_settings_model.to_dict() - assert segment_settings_model_json2 == segment_settings_model_json - - -class TestModel_Source: - """ - Test Class for Source - """ - - def test_source_serialization(self): - """ - Test serialization/deserialization for Source - """ - - # Construct dict forms of any model objects needed in order to build this model. - - source_schedule_model = {} # SourceSchedule - source_schedule_model['enabled'] = True - source_schedule_model['time_zone'] = 'America/New_York' - source_schedule_model['frequency'] = 'daily' - - source_options_folder_model = {} # SourceOptionsFolder - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - source_options_object_model = {} # SourceOptionsObject - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - source_options_site_coll_model = {} # SourceOptionsSiteColl - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - source_options_web_crawl_model = {} # SourceOptionsWebCrawl - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - source_options_buckets_model = {} # SourceOptionsBuckets - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - source_options_model = {} # SourceOptions - source_options_model['folders'] = [source_options_folder_model] - source_options_model['objects'] = [source_options_object_model] - source_options_model['site_collections'] = [source_options_site_coll_model] - source_options_model['urls'] = [source_options_web_crawl_model] - source_options_model['buckets'] = [source_options_buckets_model] - source_options_model['crawl_all_buckets'] = True - - # Construct a json representation of a Source model - source_model_json = {} - source_model_json['type'] = 'box' - source_model_json['credential_id'] = 'testString' - source_model_json['schedule'] = source_schedule_model - source_model_json['options'] = source_options_model - - # Construct a model instance of Source by calling from_dict on the json representation - source_model = Source.from_dict(source_model_json) - assert source_model != False - - # Construct a model instance of Source by calling from_dict on the json representation - source_model_dict = Source.from_dict(source_model_json).__dict__ - source_model2 = Source(**source_model_dict) - - # Verify the model instances are equivalent - assert source_model == source_model2 - - # Convert model instance back to dict and verify no loss of data - source_model_json2 = source_model.to_dict() - assert source_model_json2 == source_model_json - - -class TestModel_SourceOptions: - """ - Test Class for SourceOptions - """ - - def test_source_options_serialization(self): - """ - Test serialization/deserialization for SourceOptions - """ - - # Construct dict forms of any model objects needed in order to build this model. - - source_options_folder_model = {} # SourceOptionsFolder - source_options_folder_model['owner_user_id'] = 'testString' - source_options_folder_model['folder_id'] = 'testString' - source_options_folder_model['limit'] = 38 - - source_options_object_model = {} # SourceOptionsObject - source_options_object_model['name'] = 'testString' - source_options_object_model['limit'] = 38 - - source_options_site_coll_model = {} # SourceOptionsSiteColl - source_options_site_coll_model['site_collection_path'] = 'testString' - source_options_site_coll_model['limit'] = 38 - - source_options_web_crawl_model = {} # SourceOptionsWebCrawl - source_options_web_crawl_model['url'] = 'testString' - source_options_web_crawl_model['limit_to_starting_hosts'] = True - source_options_web_crawl_model['crawl_speed'] = 'normal' - source_options_web_crawl_model['allow_untrusted_certificate'] = False - source_options_web_crawl_model['maximum_hops'] = 2 - source_options_web_crawl_model['request_timeout'] = 30000 - source_options_web_crawl_model['override_robots_txt'] = False - source_options_web_crawl_model['blacklist'] = ['testString'] - - source_options_buckets_model = {} # SourceOptionsBuckets - source_options_buckets_model['name'] = 'testString' - source_options_buckets_model['limit'] = 38 - - # Construct a json representation of a SourceOptions model - source_options_model_json = {} - source_options_model_json['folders'] = [source_options_folder_model] - source_options_model_json['objects'] = [source_options_object_model] - source_options_model_json['site_collections'] = [source_options_site_coll_model] - source_options_model_json['urls'] = [source_options_web_crawl_model] - source_options_model_json['buckets'] = [source_options_buckets_model] - source_options_model_json['crawl_all_buckets'] = True - - # Construct a model instance of SourceOptions by calling from_dict on the json representation - source_options_model = SourceOptions.from_dict(source_options_model_json) - assert source_options_model != False - - # Construct a model instance of SourceOptions by calling from_dict on the json representation - source_options_model_dict = SourceOptions.from_dict(source_options_model_json).__dict__ - source_options_model2 = SourceOptions(**source_options_model_dict) - - # Verify the model instances are equivalent - assert source_options_model == source_options_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_model_json2 = source_options_model.to_dict() - assert source_options_model_json2 == source_options_model_json - - -class TestModel_SourceOptionsBuckets: - """ - Test Class for SourceOptionsBuckets - """ - - def test_source_options_buckets_serialization(self): - """ - Test serialization/deserialization for SourceOptionsBuckets - """ - - # Construct a json representation of a SourceOptionsBuckets model - source_options_buckets_model_json = {} - source_options_buckets_model_json['name'] = 'testString' - source_options_buckets_model_json['limit'] = 38 - - # Construct a model instance of SourceOptionsBuckets by calling from_dict on the json representation - source_options_buckets_model = SourceOptionsBuckets.from_dict(source_options_buckets_model_json) - assert source_options_buckets_model != False - - # Construct a model instance of SourceOptionsBuckets by calling from_dict on the json representation - source_options_buckets_model_dict = SourceOptionsBuckets.from_dict(source_options_buckets_model_json).__dict__ - source_options_buckets_model2 = SourceOptionsBuckets(**source_options_buckets_model_dict) - - # Verify the model instances are equivalent - assert source_options_buckets_model == source_options_buckets_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_buckets_model_json2 = source_options_buckets_model.to_dict() - assert source_options_buckets_model_json2 == source_options_buckets_model_json - - -class TestModel_SourceOptionsFolder: - """ - Test Class for SourceOptionsFolder - """ - - def test_source_options_folder_serialization(self): - """ - Test serialization/deserialization for SourceOptionsFolder - """ - - # Construct a json representation of a SourceOptionsFolder model - source_options_folder_model_json = {} - source_options_folder_model_json['owner_user_id'] = 'testString' - source_options_folder_model_json['folder_id'] = 'testString' - source_options_folder_model_json['limit'] = 38 - - # Construct a model instance of SourceOptionsFolder by calling from_dict on the json representation - source_options_folder_model = SourceOptionsFolder.from_dict(source_options_folder_model_json) - assert source_options_folder_model != False - - # Construct a model instance of SourceOptionsFolder by calling from_dict on the json representation - source_options_folder_model_dict = SourceOptionsFolder.from_dict(source_options_folder_model_json).__dict__ - source_options_folder_model2 = SourceOptionsFolder(**source_options_folder_model_dict) - - # Verify the model instances are equivalent - assert source_options_folder_model == source_options_folder_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_folder_model_json2 = source_options_folder_model.to_dict() - assert source_options_folder_model_json2 == source_options_folder_model_json - - -class TestModel_SourceOptionsObject: - """ - Test Class for SourceOptionsObject - """ - - def test_source_options_object_serialization(self): - """ - Test serialization/deserialization for SourceOptionsObject - """ - - # Construct a json representation of a SourceOptionsObject model - source_options_object_model_json = {} - source_options_object_model_json['name'] = 'testString' - source_options_object_model_json['limit'] = 38 - - # Construct a model instance of SourceOptionsObject by calling from_dict on the json representation - source_options_object_model = SourceOptionsObject.from_dict(source_options_object_model_json) - assert source_options_object_model != False - - # Construct a model instance of SourceOptionsObject by calling from_dict on the json representation - source_options_object_model_dict = SourceOptionsObject.from_dict(source_options_object_model_json).__dict__ - source_options_object_model2 = SourceOptionsObject(**source_options_object_model_dict) - - # Verify the model instances are equivalent - assert source_options_object_model == source_options_object_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_object_model_json2 = source_options_object_model.to_dict() - assert source_options_object_model_json2 == source_options_object_model_json - - -class TestModel_SourceOptionsSiteColl: - """ - Test Class for SourceOptionsSiteColl - """ - - def test_source_options_site_coll_serialization(self): - """ - Test serialization/deserialization for SourceOptionsSiteColl - """ - - # Construct a json representation of a SourceOptionsSiteColl model - source_options_site_coll_model_json = {} - source_options_site_coll_model_json['site_collection_path'] = 'testString' - source_options_site_coll_model_json['limit'] = 38 - - # Construct a model instance of SourceOptionsSiteColl by calling from_dict on the json representation - source_options_site_coll_model = SourceOptionsSiteColl.from_dict(source_options_site_coll_model_json) - assert source_options_site_coll_model != False - - # Construct a model instance of SourceOptionsSiteColl by calling from_dict on the json representation - source_options_site_coll_model_dict = SourceOptionsSiteColl.from_dict(source_options_site_coll_model_json).__dict__ - source_options_site_coll_model2 = SourceOptionsSiteColl(**source_options_site_coll_model_dict) - - # Verify the model instances are equivalent - assert source_options_site_coll_model == source_options_site_coll_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_site_coll_model_json2 = source_options_site_coll_model.to_dict() - assert source_options_site_coll_model_json2 == source_options_site_coll_model_json - - -class TestModel_SourceOptionsWebCrawl: - """ - Test Class for SourceOptionsWebCrawl - """ - - def test_source_options_web_crawl_serialization(self): - """ - Test serialization/deserialization for SourceOptionsWebCrawl - """ - - # Construct a json representation of a SourceOptionsWebCrawl model - source_options_web_crawl_model_json = {} - source_options_web_crawl_model_json['url'] = 'testString' - source_options_web_crawl_model_json['limit_to_starting_hosts'] = True - source_options_web_crawl_model_json['crawl_speed'] = 'normal' - source_options_web_crawl_model_json['allow_untrusted_certificate'] = False - source_options_web_crawl_model_json['maximum_hops'] = 2 - source_options_web_crawl_model_json['request_timeout'] = 30000 - source_options_web_crawl_model_json['override_robots_txt'] = False - source_options_web_crawl_model_json['blacklist'] = ['testString'] - - # Construct a model instance of SourceOptionsWebCrawl by calling from_dict on the json representation - source_options_web_crawl_model = SourceOptionsWebCrawl.from_dict(source_options_web_crawl_model_json) - assert source_options_web_crawl_model != False - - # Construct a model instance of SourceOptionsWebCrawl by calling from_dict on the json representation - source_options_web_crawl_model_dict = SourceOptionsWebCrawl.from_dict(source_options_web_crawl_model_json).__dict__ - source_options_web_crawl_model2 = SourceOptionsWebCrawl(**source_options_web_crawl_model_dict) - - # Verify the model instances are equivalent - assert source_options_web_crawl_model == source_options_web_crawl_model2 - - # Convert model instance back to dict and verify no loss of data - source_options_web_crawl_model_json2 = source_options_web_crawl_model.to_dict() - assert source_options_web_crawl_model_json2 == source_options_web_crawl_model_json - - -class TestModel_SourceSchedule: - """ - Test Class for SourceSchedule - """ - - def test_source_schedule_serialization(self): - """ - Test serialization/deserialization for SourceSchedule - """ - - # Construct a json representation of a SourceSchedule model - source_schedule_model_json = {} - source_schedule_model_json['enabled'] = True - source_schedule_model_json['time_zone'] = 'America/New_York' - source_schedule_model_json['frequency'] = 'daily' - - # Construct a model instance of SourceSchedule by calling from_dict on the json representation - source_schedule_model = SourceSchedule.from_dict(source_schedule_model_json) - assert source_schedule_model != False - - # Construct a model instance of SourceSchedule by calling from_dict on the json representation - source_schedule_model_dict = SourceSchedule.from_dict(source_schedule_model_json).__dict__ - source_schedule_model2 = SourceSchedule(**source_schedule_model_dict) - - # Verify the model instances are equivalent - assert source_schedule_model == source_schedule_model2 - - # Convert model instance back to dict and verify no loss of data - source_schedule_model_json2 = source_schedule_model.to_dict() - assert source_schedule_model_json2 == source_schedule_model_json - - -class TestModel_SourceStatus: - """ - Test Class for SourceStatus - """ - - def test_source_status_serialization(self): - """ - Test serialization/deserialization for SourceStatus - """ - - # Construct a json representation of a SourceStatus model - source_status_model_json = {} - source_status_model_json['status'] = 'running' - source_status_model_json['next_crawl'] = '2019-01-01T12:00:00Z' - - # Construct a model instance of SourceStatus by calling from_dict on the json representation - source_status_model = SourceStatus.from_dict(source_status_model_json) - assert source_status_model != False - - # Construct a model instance of SourceStatus by calling from_dict on the json representation - source_status_model_dict = SourceStatus.from_dict(source_status_model_json).__dict__ - source_status_model2 = SourceStatus(**source_status_model_dict) - - # Verify the model instances are equivalent - assert source_status_model == source_status_model2 - - # Convert model instance back to dict and verify no loss of data - source_status_model_json2 = source_status_model.to_dict() - assert source_status_model_json2 == source_status_model_json - - -class TestModel_StatusDetails: - """ - Test Class for StatusDetails - """ - - def test_status_details_serialization(self): - """ - Test serialization/deserialization for StatusDetails - """ - - # Construct a json representation of a StatusDetails model - status_details_model_json = {} - status_details_model_json['authenticated'] = True - status_details_model_json['error_message'] = 'testString' - - # Construct a model instance of StatusDetails by calling from_dict on the json representation - status_details_model = StatusDetails.from_dict(status_details_model_json) - assert status_details_model != False - - # Construct a model instance of StatusDetails by calling from_dict on the json representation - status_details_model_dict = StatusDetails.from_dict(status_details_model_json).__dict__ - status_details_model2 = StatusDetails(**status_details_model_dict) - - # Verify the model instances are equivalent - assert status_details_model == status_details_model2 - - # Convert model instance back to dict and verify no loss of data - status_details_model_json2 = status_details_model.to_dict() - assert status_details_model_json2 == status_details_model_json - - -class TestModel_TokenDictRule: - """ - Test Class for TokenDictRule - """ - - def test_token_dict_rule_serialization(self): - """ - Test serialization/deserialization for TokenDictRule - """ - - # Construct a json representation of a TokenDictRule model - token_dict_rule_model_json = {} - token_dict_rule_model_json['text'] = 'testString' - token_dict_rule_model_json['tokens'] = ['testString'] - token_dict_rule_model_json['readings'] = ['testString'] - token_dict_rule_model_json['part_of_speech'] = 'testString' - - # Construct a model instance of TokenDictRule by calling from_dict on the json representation - token_dict_rule_model = TokenDictRule.from_dict(token_dict_rule_model_json) - assert token_dict_rule_model != False - - # Construct a model instance of TokenDictRule by calling from_dict on the json representation - token_dict_rule_model_dict = TokenDictRule.from_dict(token_dict_rule_model_json).__dict__ - token_dict_rule_model2 = TokenDictRule(**token_dict_rule_model_dict) - - # Verify the model instances are equivalent - assert token_dict_rule_model == token_dict_rule_model2 - - # Convert model instance back to dict and verify no loss of data - token_dict_rule_model_json2 = token_dict_rule_model.to_dict() - assert token_dict_rule_model_json2 == token_dict_rule_model_json - - -class TestModel_TokenDictStatusResponse: - """ - Test Class for TokenDictStatusResponse - """ - - def test_token_dict_status_response_serialization(self): - """ - Test serialization/deserialization for TokenDictStatusResponse - """ - - # Construct a json representation of a TokenDictStatusResponse model - token_dict_status_response_model_json = {} - token_dict_status_response_model_json['status'] = 'active' - token_dict_status_response_model_json['type'] = 'testString' - - # Construct a model instance of TokenDictStatusResponse by calling from_dict on the json representation - token_dict_status_response_model = TokenDictStatusResponse.from_dict(token_dict_status_response_model_json) - assert token_dict_status_response_model != False - - # Construct a model instance of TokenDictStatusResponse by calling from_dict on the json representation - token_dict_status_response_model_dict = TokenDictStatusResponse.from_dict(token_dict_status_response_model_json).__dict__ - token_dict_status_response_model2 = TokenDictStatusResponse(**token_dict_status_response_model_dict) - - # Verify the model instances are equivalent - assert token_dict_status_response_model == token_dict_status_response_model2 - - # Convert model instance back to dict and verify no loss of data - token_dict_status_response_model_json2 = token_dict_status_response_model.to_dict() - assert token_dict_status_response_model_json2 == token_dict_status_response_model_json - - -class TestModel_TrainingDataSet: - """ - Test Class for TrainingDataSet - """ - - def test_training_data_set_serialization(self): - """ - Test serialization/deserialization for TrainingDataSet - """ - - # Construct dict forms of any model objects needed in order to build this model. - - training_example_model = {} # TrainingExample - training_example_model['document_id'] = 'testString' - training_example_model['cross_reference'] = 'testString' - training_example_model['relevance'] = 38 - - training_query_model = {} # TrainingQuery - training_query_model['query_id'] = 'testString' - training_query_model['natural_language_query'] = 'testString' - training_query_model['filter'] = 'testString' - training_query_model['examples'] = [training_example_model] - - # Construct a json representation of a TrainingDataSet model - training_data_set_model_json = {} - training_data_set_model_json['environment_id'] = 'testString' - training_data_set_model_json['collection_id'] = 'testString' - training_data_set_model_json['queries'] = [training_query_model] - - # Construct a model instance of TrainingDataSet by calling from_dict on the json representation - training_data_set_model = TrainingDataSet.from_dict(training_data_set_model_json) - assert training_data_set_model != False - - # Construct a model instance of TrainingDataSet by calling from_dict on the json representation - training_data_set_model_dict = TrainingDataSet.from_dict(training_data_set_model_json).__dict__ - training_data_set_model2 = TrainingDataSet(**training_data_set_model_dict) - - # Verify the model instances are equivalent - assert training_data_set_model == training_data_set_model2 - - # Convert model instance back to dict and verify no loss of data - training_data_set_model_json2 = training_data_set_model.to_dict() - assert training_data_set_model_json2 == training_data_set_model_json - - -class TestModel_TrainingExample: - """ - Test Class for TrainingExample - """ - - def test_training_example_serialization(self): - """ - Test serialization/deserialization for TrainingExample - """ - - # Construct a json representation of a TrainingExample model - training_example_model_json = {} - training_example_model_json['document_id'] = 'testString' - training_example_model_json['cross_reference'] = 'testString' - training_example_model_json['relevance'] = 38 - - # Construct a model instance of TrainingExample by calling from_dict on the json representation - training_example_model = TrainingExample.from_dict(training_example_model_json) - assert training_example_model != False - - # Construct a model instance of TrainingExample by calling from_dict on the json representation - training_example_model_dict = TrainingExample.from_dict(training_example_model_json).__dict__ - training_example_model2 = TrainingExample(**training_example_model_dict) - - # Verify the model instances are equivalent - assert training_example_model == training_example_model2 - - # Convert model instance back to dict and verify no loss of data - training_example_model_json2 = training_example_model.to_dict() - assert training_example_model_json2 == training_example_model_json - - -class TestModel_TrainingExampleList: - """ - Test Class for TrainingExampleList - """ - - def test_training_example_list_serialization(self): - """ - Test serialization/deserialization for TrainingExampleList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - training_example_model = {} # TrainingExample - training_example_model['document_id'] = 'testString' - training_example_model['cross_reference'] = 'testString' - training_example_model['relevance'] = 38 - - # Construct a json representation of a TrainingExampleList model - training_example_list_model_json = {} - training_example_list_model_json['examples'] = [training_example_model] - - # Construct a model instance of TrainingExampleList by calling from_dict on the json representation - training_example_list_model = TrainingExampleList.from_dict(training_example_list_model_json) - assert training_example_list_model != False - - # Construct a model instance of TrainingExampleList by calling from_dict on the json representation - training_example_list_model_dict = TrainingExampleList.from_dict(training_example_list_model_json).__dict__ - training_example_list_model2 = TrainingExampleList(**training_example_list_model_dict) - - # Verify the model instances are equivalent - assert training_example_list_model == training_example_list_model2 - - # Convert model instance back to dict and verify no loss of data - training_example_list_model_json2 = training_example_list_model.to_dict() - assert training_example_list_model_json2 == training_example_list_model_json - - -class TestModel_TrainingQuery: - """ - Test Class for TrainingQuery - """ - - def test_training_query_serialization(self): - """ - Test serialization/deserialization for TrainingQuery - """ - - # Construct dict forms of any model objects needed in order to build this model. - - training_example_model = {} # TrainingExample - training_example_model['document_id'] = 'testString' - training_example_model['cross_reference'] = 'testString' - training_example_model['relevance'] = 38 - - # Construct a json representation of a TrainingQuery model - training_query_model_json = {} - training_query_model_json['query_id'] = 'testString' - training_query_model_json['natural_language_query'] = 'testString' - training_query_model_json['filter'] = 'testString' - training_query_model_json['examples'] = [training_example_model] - - # Construct a model instance of TrainingQuery by calling from_dict on the json representation - training_query_model = TrainingQuery.from_dict(training_query_model_json) - assert training_query_model != False - - # Construct a model instance of TrainingQuery by calling from_dict on the json representation - training_query_model_dict = TrainingQuery.from_dict(training_query_model_json).__dict__ - training_query_model2 = TrainingQuery(**training_query_model_dict) - - # Verify the model instances are equivalent - assert training_query_model == training_query_model2 - - # Convert model instance back to dict and verify no loss of data - training_query_model_json2 = training_query_model.to_dict() - assert training_query_model_json2 == training_query_model_json - - -class TestModel_TrainingStatus: - """ - Test Class for TrainingStatus - """ - - def test_training_status_serialization(self): - """ - Test serialization/deserialization for TrainingStatus - """ - - # Construct a json representation of a TrainingStatus model - training_status_model_json = {} - training_status_model_json['total_examples'] = 38 - training_status_model_json['available'] = True - training_status_model_json['processing'] = True - training_status_model_json['minimum_queries_added'] = True - training_status_model_json['minimum_examples_added'] = True - training_status_model_json['sufficient_label_diversity'] = True - training_status_model_json['notices'] = 38 - training_status_model_json['successfully_trained'] = '2019-01-01T12:00:00Z' - training_status_model_json['data_updated'] = '2019-01-01T12:00:00Z' - - # Construct a model instance of TrainingStatus by calling from_dict on the json representation - training_status_model = TrainingStatus.from_dict(training_status_model_json) - assert training_status_model != False - - # Construct a model instance of TrainingStatus by calling from_dict on the json representation - training_status_model_dict = TrainingStatus.from_dict(training_status_model_json).__dict__ - training_status_model2 = TrainingStatus(**training_status_model_dict) - - # Verify the model instances are equivalent - assert training_status_model == training_status_model2 - - # Convert model instance back to dict and verify no loss of data - training_status_model_json2 = training_status_model.to_dict() - assert training_status_model_json2 == training_status_model_json - - -class TestModel_WordHeadingDetection: - """ - Test Class for WordHeadingDetection - """ - - def test_word_heading_detection_serialization(self): - """ - Test serialization/deserialization for WordHeadingDetection - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - word_style_model = {} # WordStyle - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - # Construct a json representation of a WordHeadingDetection model - word_heading_detection_model_json = {} - word_heading_detection_model_json['fonts'] = [font_setting_model] - word_heading_detection_model_json['styles'] = [word_style_model] - - # Construct a model instance of WordHeadingDetection by calling from_dict on the json representation - word_heading_detection_model = WordHeadingDetection.from_dict(word_heading_detection_model_json) - assert word_heading_detection_model != False - - # Construct a model instance of WordHeadingDetection by calling from_dict on the json representation - word_heading_detection_model_dict = WordHeadingDetection.from_dict(word_heading_detection_model_json).__dict__ - word_heading_detection_model2 = WordHeadingDetection(**word_heading_detection_model_dict) - - # Verify the model instances are equivalent - assert word_heading_detection_model == word_heading_detection_model2 - - # Convert model instance back to dict and verify no loss of data - word_heading_detection_model_json2 = word_heading_detection_model.to_dict() - assert word_heading_detection_model_json2 == word_heading_detection_model_json - - -class TestModel_WordSettings: - """ - Test Class for WordSettings - """ - - def test_word_settings_serialization(self): - """ - Test serialization/deserialization for WordSettings - """ - - # Construct dict forms of any model objects needed in order to build this model. - - font_setting_model = {} # FontSetting - font_setting_model['level'] = 38 - font_setting_model['min_size'] = 38 - font_setting_model['max_size'] = 38 - font_setting_model['bold'] = True - font_setting_model['italic'] = True - font_setting_model['name'] = 'testString' - - word_style_model = {} # WordStyle - word_style_model['level'] = 38 - word_style_model['names'] = ['testString'] - - word_heading_detection_model = {} # WordHeadingDetection - word_heading_detection_model['fonts'] = [font_setting_model] - word_heading_detection_model['styles'] = [word_style_model] - - # Construct a json representation of a WordSettings model - word_settings_model_json = {} - word_settings_model_json['heading'] = word_heading_detection_model - - # Construct a model instance of WordSettings by calling from_dict on the json representation - word_settings_model = WordSettings.from_dict(word_settings_model_json) - assert word_settings_model != False - - # Construct a model instance of WordSettings by calling from_dict on the json representation - word_settings_model_dict = WordSettings.from_dict(word_settings_model_json).__dict__ - word_settings_model2 = WordSettings(**word_settings_model_dict) - - # Verify the model instances are equivalent - assert word_settings_model == word_settings_model2 - - # Convert model instance back to dict and verify no loss of data - word_settings_model_json2 = word_settings_model.to_dict() - assert word_settings_model_json2 == word_settings_model_json - - -class TestModel_WordStyle: - """ - Test Class for WordStyle - """ - - def test_word_style_serialization(self): - """ - Test serialization/deserialization for WordStyle - """ - - # Construct a json representation of a WordStyle model - word_style_model_json = {} - word_style_model_json['level'] = 38 - word_style_model_json['names'] = ['testString'] - - # Construct a model instance of WordStyle by calling from_dict on the json representation - word_style_model = WordStyle.from_dict(word_style_model_json) - assert word_style_model != False - - # Construct a model instance of WordStyle by calling from_dict on the json representation - word_style_model_dict = WordStyle.from_dict(word_style_model_json).__dict__ - word_style_model2 = WordStyle(**word_style_model_dict) - - # Verify the model instances are equivalent - assert word_style_model == word_style_model2 - - # Convert model instance back to dict and verify no loss of data - word_style_model_json2 = word_style_model.to_dict() - assert word_style_model_json2 == word_style_model_json - - -class TestModel_XPathPatterns: - """ - Test Class for XPathPatterns - """ - - def test_x_path_patterns_serialization(self): - """ - Test serialization/deserialization for XPathPatterns - """ - - # Construct a json representation of a XPathPatterns model - x_path_patterns_model_json = {} - x_path_patterns_model_json['xpaths'] = ['testString'] - - # Construct a model instance of XPathPatterns by calling from_dict on the json representation - x_path_patterns_model = XPathPatterns.from_dict(x_path_patterns_model_json) - assert x_path_patterns_model != False - - # Construct a model instance of XPathPatterns by calling from_dict on the json representation - x_path_patterns_model_dict = XPathPatterns.from_dict(x_path_patterns_model_json).__dict__ - x_path_patterns_model2 = XPathPatterns(**x_path_patterns_model_dict) - - # Verify the model instances are equivalent - assert x_path_patterns_model == x_path_patterns_model2 - - # Convert model instance back to dict and verify no loss of data - x_path_patterns_model_json2 = x_path_patterns_model.to_dict() - assert x_path_patterns_model_json2 == x_path_patterns_model_json - - -class TestModel_QueryCalculationAggregation: - """ - Test Class for QueryCalculationAggregation - """ - - def test_query_calculation_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryCalculationAggregation - """ - - # Construct a json representation of a QueryCalculationAggregation model - query_calculation_aggregation_model_json = {} - query_calculation_aggregation_model_json['type'] = 'unique_count' - query_calculation_aggregation_model_json['field'] = 'testString' - query_calculation_aggregation_model_json['value'] = 72.5 - - # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation - query_calculation_aggregation_model = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json) - assert query_calculation_aggregation_model != False - - # Construct a model instance of QueryCalculationAggregation by calling from_dict on the json representation - query_calculation_aggregation_model_dict = QueryCalculationAggregation.from_dict(query_calculation_aggregation_model_json).__dict__ - query_calculation_aggregation_model2 = QueryCalculationAggregation(**query_calculation_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_calculation_aggregation_model == query_calculation_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_calculation_aggregation_model_json2 = query_calculation_aggregation_model.to_dict() - assert query_calculation_aggregation_model_json2 == query_calculation_aggregation_model_json - - -class TestModel_QueryFilterAggregation: - """ - Test Class for QueryFilterAggregation - """ - - def test_query_filter_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryFilterAggregation - """ - - # Construct a json representation of a QueryFilterAggregation model - query_filter_aggregation_model_json = {} - query_filter_aggregation_model_json['type'] = 'filter' - query_filter_aggregation_model_json['match'] = 'testString' - query_filter_aggregation_model_json['matching_results'] = 26 - - # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation - query_filter_aggregation_model = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json) - assert query_filter_aggregation_model != False - - # Construct a model instance of QueryFilterAggregation by calling from_dict on the json representation - query_filter_aggregation_model_dict = QueryFilterAggregation.from_dict(query_filter_aggregation_model_json).__dict__ - query_filter_aggregation_model2 = QueryFilterAggregation(**query_filter_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_filter_aggregation_model == query_filter_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_filter_aggregation_model_json2 = query_filter_aggregation_model.to_dict() - assert query_filter_aggregation_model_json2 == query_filter_aggregation_model_json - - -class TestModel_QueryHistogramAggregation: - """ - Test Class for QueryHistogramAggregation - """ - - def test_query_histogram_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryHistogramAggregation - """ - - # Construct a json representation of a QueryHistogramAggregation model - query_histogram_aggregation_model_json = {} - query_histogram_aggregation_model_json['type'] = 'histogram' - query_histogram_aggregation_model_json['field'] = 'testString' - query_histogram_aggregation_model_json['interval'] = 38 - query_histogram_aggregation_model_json['name'] = 'testString' - - # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation - query_histogram_aggregation_model = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json) - assert query_histogram_aggregation_model != False - - # Construct a model instance of QueryHistogramAggregation by calling from_dict on the json representation - query_histogram_aggregation_model_dict = QueryHistogramAggregation.from_dict(query_histogram_aggregation_model_json).__dict__ - query_histogram_aggregation_model2 = QueryHistogramAggregation(**query_histogram_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_histogram_aggregation_model == query_histogram_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_histogram_aggregation_model_json2 = query_histogram_aggregation_model.to_dict() - assert query_histogram_aggregation_model_json2 == query_histogram_aggregation_model_json - - -class TestModel_QueryNestedAggregation: - """ - Test Class for QueryNestedAggregation - """ - - def test_query_nested_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryNestedAggregation - """ - - # Construct a json representation of a QueryNestedAggregation model - query_nested_aggregation_model_json = {} - query_nested_aggregation_model_json['type'] = 'nested' - query_nested_aggregation_model_json['path'] = 'testString' - query_nested_aggregation_model_json['matching_results'] = 26 - - # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation - query_nested_aggregation_model = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json) - assert query_nested_aggregation_model != False - - # Construct a model instance of QueryNestedAggregation by calling from_dict on the json representation - query_nested_aggregation_model_dict = QueryNestedAggregation.from_dict(query_nested_aggregation_model_json).__dict__ - query_nested_aggregation_model2 = QueryNestedAggregation(**query_nested_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_nested_aggregation_model == query_nested_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_nested_aggregation_model_json2 = query_nested_aggregation_model.to_dict() - assert query_nested_aggregation_model_json2 == query_nested_aggregation_model_json - - -class TestModel_QueryTermAggregation: - """ - Test Class for QueryTermAggregation - """ - - def test_query_term_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryTermAggregation - """ - - # Construct a json representation of a QueryTermAggregation model - query_term_aggregation_model_json = {} - query_term_aggregation_model_json['type'] = 'term' - query_term_aggregation_model_json['field'] = 'testString' - query_term_aggregation_model_json['count'] = 38 - query_term_aggregation_model_json['name'] = 'testString' - - # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation - query_term_aggregation_model = QueryTermAggregation.from_dict(query_term_aggregation_model_json) - assert query_term_aggregation_model != False - - # Construct a model instance of QueryTermAggregation by calling from_dict on the json representation - query_term_aggregation_model_dict = QueryTermAggregation.from_dict(query_term_aggregation_model_json).__dict__ - query_term_aggregation_model2 = QueryTermAggregation(**query_term_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_term_aggregation_model == query_term_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_term_aggregation_model_json2 = query_term_aggregation_model.to_dict() - assert query_term_aggregation_model_json2 == query_term_aggregation_model_json - - -class TestModel_QueryTimesliceAggregation: - """ - Test Class for QueryTimesliceAggregation - """ - - def test_query_timeslice_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryTimesliceAggregation - """ - - # Construct a json representation of a QueryTimesliceAggregation model - query_timeslice_aggregation_model_json = {} - query_timeslice_aggregation_model_json['type'] = 'timeslice' - query_timeslice_aggregation_model_json['field'] = 'testString' - query_timeslice_aggregation_model_json['interval'] = 'testString' - query_timeslice_aggregation_model_json['name'] = 'testString' - - # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation - query_timeslice_aggregation_model = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json) - assert query_timeslice_aggregation_model != False - - # Construct a model instance of QueryTimesliceAggregation by calling from_dict on the json representation - query_timeslice_aggregation_model_dict = QueryTimesliceAggregation.from_dict(query_timeslice_aggregation_model_json).__dict__ - query_timeslice_aggregation_model2 = QueryTimesliceAggregation(**query_timeslice_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_timeslice_aggregation_model == query_timeslice_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_timeslice_aggregation_model_json2 = query_timeslice_aggregation_model.to_dict() - assert query_timeslice_aggregation_model_json2 == query_timeslice_aggregation_model_json - - -class TestModel_QueryTopHitsAggregation: - """ - Test Class for QueryTopHitsAggregation - """ - - def test_query_top_hits_aggregation_serialization(self): - """ - Test serialization/deserialization for QueryTopHitsAggregation - """ - - # Construct dict forms of any model objects needed in order to build this model. - - query_top_hits_aggregation_result_model = {} # QueryTopHitsAggregationResult - query_top_hits_aggregation_result_model['matching_results'] = 38 - query_top_hits_aggregation_result_model['hits'] = [{'anyKey': 'anyValue'}] - - # Construct a json representation of a QueryTopHitsAggregation model - query_top_hits_aggregation_model_json = {} - query_top_hits_aggregation_model_json['type'] = 'top_hits' - query_top_hits_aggregation_model_json['size'] = 38 - query_top_hits_aggregation_model_json['name'] = 'testString' - query_top_hits_aggregation_model_json['hits'] = query_top_hits_aggregation_result_model - - # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation - query_top_hits_aggregation_model = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json) - assert query_top_hits_aggregation_model != False - - # Construct a model instance of QueryTopHitsAggregation by calling from_dict on the json representation - query_top_hits_aggregation_model_dict = QueryTopHitsAggregation.from_dict(query_top_hits_aggregation_model_json).__dict__ - query_top_hits_aggregation_model2 = QueryTopHitsAggregation(**query_top_hits_aggregation_model_dict) - - # Verify the model instances are equivalent - assert query_top_hits_aggregation_model == query_top_hits_aggregation_model2 - - # Convert model instance back to dict and verify no loss of data - query_top_hits_aggregation_model_json2 = query_top_hits_aggregation_model.to_dict() - assert query_top_hits_aggregation_model_json2 == query_top_hits_aggregation_model_json - - -# endregion -############################################################################## -# End of Model Tests -############################################################################## From 0b677fdd80095553922191dfb945f751b0eaff90 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 17 Oct 2024 13:19:18 -0500 Subject: [PATCH 432/455] feat(lt): remove lt and other deprecated resources BREAKING CHANGE: LanguageTranslator functionality has been removed --- .github/workflows/integration-test.yml | 3 - examples/language_translator_v3.py | 74 - ibm_watson/__init__.py | 1 - ibm_watson/language_translator_v3.py | 2369 ----------------- setup.py | 10 +- .../test_language_translator_v3.py | 53 - test/unit/test_language_translator_v3.py | 1841 ------------- 7 files changed, 5 insertions(+), 4346 deletions(-) delete mode 100644 examples/language_translator_v3.py delete mode 100644 ibm_watson/language_translator_v3.py delete mode 100644 test/integration/test_language_translator_v3.py delete mode 100644 test/unit/test_language_translator_v3.py diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index 4f55f471d..d95c423b1 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -35,8 +35,6 @@ jobs: - name: Execute Python integration tests # continue-on-error: true env: - LANGUAGE_TRANSLATOR_APIKEY: ${{ secrets.LT_APIKEY }} - LANGUAGE_TRANSLATOR_URL: "https://api.us-south.language-translator.watson.cloud.ibm.com" NATURAL_LANGUAGE_UNDERSTANDING_APIKEY: ${{ secrets.NLU_APIKEY }} NATURAL_LANGUAGE_UNDERSTANDING_URL: "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com" SPEECH_TO_TEXT_APIKEY: ${{ secrets.STT_APIKEY }} @@ -54,7 +52,6 @@ jobs: run: | pip3 install -U python-dotenv pytest test/integration/test_discovery_v2.py -rap - pytest test/integration/test_language_translator_v3.py -rap pytest test/integration/test_natural_language_understanding_v1.py -rap pytest test/integration/test_speech_to_text_v1.py -rap pytest test/integration/test_text_to_speech_v1.py -rap diff --git a/examples/language_translator_v3.py b/examples/language_translator_v3.py deleted file mode 100644 index da7aecf8f..000000000 --- a/examples/language_translator_v3.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -import json -from ibm_watson import LanguageTranslatorV3 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your_api_key') -language_translator = LanguageTranslatorV3( - version='2018-05-01', - authenticator=authenticator) -language_translator.set_service_url('https://api.us-south.language-translator.watson.cloud.ibm.com') - -## Translate -translation = language_translator.translate( - text='Hello', model_id='en-es').get_result() -print(json.dumps(translation, indent=2, ensure_ascii=False)) - -# List identifiable languages -# languages = language_translator.list_identifiable_languages().get_result() -# print(json.dumps(languages, indent=2)) - -# # Identify -# language = language_translator.identify( -# 'Language translator translates text from one language to another').get_result() -# print(json.dumps(language, indent=2)) - -# # List models -# models = language_translator.list_models( -# source='en').get_result() -# print(json.dumps(models, indent=2)) - -# # Create model -# with open('glossary.tmx', 'rb') as glossary: -# response = language_translator.create_model( -# base_model_id='en-es', -# name='custom-english-to-spanish', -# forced_glossary=glossary).get_result() -# print(json.dumps(response, indent=2)) - -# # Delete model -# response = language_translator.delete_model(model_id='').get_result() -# print(json.dumps(response, indent=2)) - -# # Get model details -# model = language_translator.get_model(model_id='').get_result() -# print(json.dumps(model, indent=2)) - -#### Document Translation #### -# List Documents -result = language_translator.list_documents().get_result() -print(json.dumps(result, indent=2)) - -# Translate Document -with open('en.pdf', 'rb') as file: - result = language_translator.translate_document( - file=file, - file_content_type='application/pdf', - filename='en.pdf', - model_id='en-fr').get_result() - print(json.dumps(result, indent=2)) - -# Document Status -result = language_translator.get_document_status( - document_id='{document id}').get_result() -print(json.dumps(result, indent=2)) - -# Translated Document -with open('translated.pdf', 'wb') as f: - result = language_translator.get_translated_document( - document_id='{document id}', - accept='application/pdf').get_result() - f.write(result.content) - -# Delete Document -language_translator.delete_document(document_id='{document id}') diff --git a/ibm_watson/__init__.py b/ibm_watson/__init__.py index 12ace99e0..aaa767998 100755 --- a/ibm_watson/__init__.py +++ b/ibm_watson/__init__.py @@ -17,7 +17,6 @@ from .assistant_v1 import AssistantV1 from .assistant_v2 import AssistantV2 -from .language_translator_v3 import LanguageTranslatorV3 from .natural_language_understanding_v1 import NaturalLanguageUnderstandingV1 from .text_to_speech_v1 import TextToSpeechV1 from .discovery_v2 import DiscoveryV2 diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py deleted file mode 100644 index ea5be9f68..000000000 --- a/ibm_watson/language_translator_v3.py +++ /dev/null @@ -1,2369 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2019, 2024. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 -""" -IBM® is announcing the deprecation of the Watson® Language Translator service for -IBM Cloud® in all regions. As of 10 June 2023, the Language Translator tile will be -removed from the IBM Cloud Platform for new customers; only existing customers will be -able to access the product. As of 10 June 2024, the service will reach its End of Support -date. As of 10 December 2024, the service will be withdrawn entirely and will no longer be -available to any customers.{: deprecated} -IBM Watson™ Language Translator translates text from one language to another. The -service offers multiple IBM-provided translation models that you can customize based on -your unique terminology and language. Use Language Translator to take news from across the -globe and present it in your language, communicate with your customers in their own -language, and more. - -API Version: 3.0.0 -See: https://cloud.ibm.com/docs/language-translator -""" - -from datetime import datetime -from enum import Enum -from os.path import basename -from typing import BinaryIO, Dict, List, Optional, TextIO, Union -import json - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class LanguageTranslatorV3(BaseService): - """The Language Translator V3 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.language-translator.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'language_translator' - - def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Language Translator service. - - :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2018-05-01`. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md - about initializing the authenticator of your choice. - """ - if version is None: - raise ValueError('version must be provided') - - print(""" - On 10 June 2023, IBM announced the deprecation of the Natural Language Translator service. - The service will no longer be available from 8 August 2022. As of 10 June 2024, the service will reach its End of Support - date. As of 10 December 2024, the service will be withdrawn entirely and will no longer be - available to any customers. - """) - - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.version = version - self.configure_service(service_name) - - ######################### - # Languages - ######################### - - def list_languages( - self, - **kwargs, - ) -> DetailedResponse: - """ - List supported languages. - - Lists all supported languages for translation. The method returns an array of - supported languages with information about each language. Languages are listed in - alphabetical order by language code (for example, `af`, `ar`). In addition to - basic information about each language, the response indicates whether the language - is `supported_as_source` for translation and `supported_as_target` for - translation. It also lists whether the language is `identifiable`. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Languages` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_languages', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/languages' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Translation - ######################### - - def translate( - self, - text: List[str], - *, - model_id: Optional[str] = None, - source: Optional[str] = None, - target: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Translate. - - Translates the input text from the source language to the target language. Specify - a model ID that indicates the source and target languages, or specify the source - and target languages individually. You can omit the source language to have the - service attempt to detect the language from the input text. If you omit the source - language, the request must contain sufficient input text for the service to - identify the source language. - You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. - All input text must be encoded in UTF-8 format. - - :param List[str] text: Input text in UTF-8 encoding. Submit a maximum of 50 - KB (51,200 bytes) of text with a single request. Multiple elements result - in multiple translations in the response. - :param str model_id: (optional) The model to use for translation. For - example, `en-de` selects the IBM-provided base model for English-to-German - translation. A model ID overrides the `source` and `target` parameters and - is required if you use a custom model. If no model ID is specified, you - must specify at least a target language. - :param str source: (optional) Language code that specifies the language of - the input text. If omitted, the service derives the source language from - the input text. The input must contain sufficient text for the service to - identify the language reliably. - :param str target: (optional) Language code that specifies the target - language for translation. Required if model ID is not specified. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationResult` object - """ - - if text is None: - raise ValueError('text must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='translate', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = { - 'text': text, - 'model_id': model_id, - 'source': source, - 'target': target, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data, ensure_ascii=False).encode('utf-8') - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/translate' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Identification - ######################### - - def list_identifiable_languages( - self, - **kwargs, - ) -> DetailedResponse: - """ - List identifiable languages. - - Lists the languages that the service can identify. Returns the language code (for - example, `en` for English or `es` for Spanish) and name of each language. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `IdentifiableLanguages` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_identifiable_languages', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/identifiable_languages' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def identify( - self, - text: Union[str, TextIO], - **kwargs, - ) -> DetailedResponse: - """ - Identify language. - - Identifies the language of the input text. - - :param str text: Input text in UTF-8 format. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `IdentifiedLanguages` object - """ - - if not text: - raise ValueError('text must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='identify', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - data = text - headers['content-type'] = 'text/plain' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/identify' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - data=data, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Models - ######################### - - def list_models( - self, - *, - source: Optional[str] = None, - target: Optional[str] = None, - default: Optional[bool] = None, - **kwargs, - ) -> DetailedResponse: - """ - List models. - - Lists available translation models. - - :param str source: (optional) Specify a language code to filter results by - source language. - :param str target: (optional) Specify a language code to filter results by - target language. - :param bool default: (optional) If the `default` parameter isn't specified, - the service returns all models (default and non-default) for each language - pair. To return only default models, set this parameter to `true`. To - return only non-default models, set this parameter to `false`. There is - exactly one default model, the IBM-provided base model, per language pair. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationModels` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_models', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'source': source, - 'target': target, - 'default': default, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/models' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def create_model( - self, - base_model_id: str, - *, - forced_glossary: Optional[BinaryIO] = None, - forced_glossary_content_type: Optional[str] = None, - parallel_corpus: Optional[BinaryIO] = None, - parallel_corpus_content_type: Optional[str] = None, - name: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Create model. - - Uploads training files to customize a translation model. You can customize a model - with a forced glossary or with a parallel corpus: - * Use a *forced glossary* to force certain terms and phrases to be translated in a - specific way. You can upload only a single forced glossary file for a model. The - size of a forced glossary file for a custom model is limited to 10 MB. - * Use a *parallel corpus* when you want your custom model to learn from general - translation patterns in parallel sentences in your samples. What your model learns - from a parallel corpus can improve translation results for input text that the - model has not been trained on. You can upload multiple parallel corpora files with - a request. To successfully train with parallel corpora, the corpora files must - contain a cumulative total of at least 5000 parallel sentences. The cumulative - size of all uploaded corpus files for a custom model is limited to 250 MB. - Depending on the type of customization and the size of the uploaded files, - training time can range from minutes for a glossary to several hours for a large - parallel corpus. To create a model that is customized with a parallel corpus and a - forced glossary, customize the model with a parallel corpus first and then - customize the resulting model with a forced glossary. - You can create a maximum of 10 custom models per language pair. For more - information about customizing a translation model, including the formatting and - character restrictions for data files, see [Customizing your - model](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing). - #### Supported file formats - You can provide your training data for customization in the following document - formats: - * **TMX** (`.tmx`) - Translation Memory eXchange (TMX) is an XML specification for - the exchange of translation memories. - * **XLIFF** (`.xliff`) - XML Localization Interchange File Format (XLIFF) is an - XML specification for the exchange of translation memories. - * **CSV** (`.csv`) - Comma-separated values (CSV) file with two columns for - aligned sentences and phrases. The first row must have two language codes. The - first column is for the source language code, and the second column is for the - target language code. - * **TSV** (`.tsv` or `.tab`) - Tab-separated values (TSV) file with two columns - for aligned sentences and phrases. The first row must have two language codes. The - first column is for the source language code, and the second column is for the - target language code. - * **JSON** (`.json`) - Custom JSON format for specifying aligned sentences and - phrases. - * **Microsoft Excel** (`.xls` or `.xlsx`) - Excel file with the first two columns - for aligned sentences and phrases. The first row contains the language code. - You must encode all text data in UTF-8 format. For more information, see - [Supported document formats for training - data](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing#supported-document-formats-for-training-data). - #### Specifying file formats - You can indicate the format of a file by including the file extension with the - file name. Use the file extensions shown in **Supported file formats**. - Alternatively, you can omit the file extension and specify one of the following - `content-type` specifications for the file: - * **TMX** - `application/x-tmx+xml` - * **XLIFF** - `application/xliff+xml` - * **CSV** - `text/csv` - * **TSV** - `text/tab-separated-values` - * **JSON** - `application/json` - * **Microsoft Excel** - - `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` - For example, with `curl`, use the following `content-type` specification to - indicate the format of a CSV file named **glossary**: - `--form "forced_glossary=@glossary;type=text/csv"`. - - :param str base_model_id: The ID of the translation model to use as the - base for customization. To see available models and IDs, use the `List - models` method. Most models that are provided with the service are - customizable. In addition, all models that you create with parallel corpora - customization can be further customized with a forced glossary. - :param BinaryIO forced_glossary: (optional) A file with forced glossary - terms for the source and target languages. The customizations in the file - completely overwrite the domain translation data, including high frequency - or high confidence phrase translations. - You can upload only one glossary file for a custom model, and the glossary - can have a maximum size of 10 MB. A forced glossary must contain single - words or short phrases. For more information, see **Supported file - formats** in the method description. - *With `curl`, use `--form forced_glossary=@{filename}`.*. - :param str forced_glossary_content_type: (optional) The content type of - forced_glossary. - :param BinaryIO parallel_corpus: (optional) A file with parallel sentences - for the source and target languages. You can upload multiple parallel - corpus files in one request by repeating the parameter. All uploaded - parallel corpus files combined must contain at least 5000 parallel - sentences to train successfully. You can provide a maximum of 500,000 - parallel sentences across all corpora. - A single entry in a corpus file can contain a maximum of 80 words. All - corpora files for a custom model can have a cumulative maximum size of 250 - MB. For more information, see **Supported file formats** in the method - description. - *With `curl`, use `--form parallel_corpus=@{filename}`.*. - :param str parallel_corpus_content_type: (optional) The content type of - parallel_corpus. - :param str name: (optional) An optional model name that you can use to - identify the model. Valid characters are letters, numbers, dashes, - underscores, spaces, and apostrophes. The maximum length of the name is 32 - characters. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object - """ - - if not base_model_id: - raise ValueError('base_model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='create_model', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'base_model_id': base_model_id, - 'name': name, - } - - form_data = [] - if forced_glossary: - form_data.append( - ('forced_glossary', - (None, forced_glossary, forced_glossary_content_type or - 'application/octet-stream'))) - if parallel_corpus: - form_data.append( - ('parallel_corpus', - (None, parallel_corpus, parallel_corpus_content_type or - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/models' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - ) - - response = self.send(request, **kwargs) - return response - - def delete_model( - self, - model_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete model. - - Deletes a custom translation model. - - :param str model_id: Model ID of the model to delete. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DeleteModelResult` object - """ - - if not model_id: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_model', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_model( - self, - model_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get model details. - - Gets information about a translation model, including training status for custom - models. Use this method to poll the status of your customization request. A - successfully completed training request has a status of `available`. - - :param str model_id: Model ID of the model to get. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TranslationModel` object - """ - - if not model_id: - raise ValueError('model_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_model', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['model_id'] - path_param_values = self.encode_path_vars(model_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/models/{model_id}'.format(**path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - ######################### - # Document translation - ######################### - - def list_documents( - self, - **kwargs, - ) -> DetailedResponse: - """ - List documents. - - Lists documents that have been submitted for translation. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentList` object - """ - - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_documents', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/documents' - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def translate_document( - self, - file: BinaryIO, - *, - filename: Optional[str] = None, - file_content_type: Optional[str] = None, - model_id: Optional[str] = None, - source: Optional[str] = None, - target: Optional[str] = None, - document_id: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Translate document. - - Submit a document for translation. You can submit the document contents in the - `file` parameter, or you can specify a previously submitted document by document - ID. The maximum file size for document translation is - * **2 MB** for service instances on the Lite plan - * **20 MB** for service instances on the Standard plan - * **50 MB** for service instances on the Advanced plan - * **150 MB** for service instances on the Premium plan - You can specify the format of the file to be translated in one of two ways: - * By specifying the appropriate file extension for the format. - * By specifying the content type (MIME type) of the format as the `type` of the - `file` parameter. - In some cases, especially for subtitle file formats, you must use either the file - extension or the content type. For more information about all supported file - formats, their file extensions and content types, and how and when to specify the - file extension or content type, see [Supported file - formats](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). - **Note:** When translating a previously submitted document, the target language - must be different from the target language of the original request when the - document was initially submitted. - - :param BinaryIO file: The contents of the source file to translate. The - maximum file size for document translation is - * **2 MB** for service instances on the Lite plan - * **20 MB** for service instances on the Standard plan - * **50 MB** for service instances on the Advanced plan - * **150 MB** for service instances on the Premium plan - You can specify the format of the file to be translated in one of two ways: - * By specifying the appropriate file extension for the format. - * By specifying the content type (MIME type) of the format as the `type` of - the `file` parameter. - In some cases, especially for subtitle file formats, you must use either - the file extension or the content type. - For more information about all supported file formats, their file - extensions and content types, and how and when to specify the file - extension or content type, see [Supported file - formats](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats). - :param str filename: (optional) The filename for file. - :param str file_content_type: (optional) The content type of file. - :param str model_id: (optional) The model to use for translation. For - example, `en-de` selects the IBM-provided base model for English-to-German - translation. A model ID overrides the `source` and `target` parameters and - is required if you use a custom model. If no model ID is specified, you - must specify at least a target language. - :param str source: (optional) Language code that specifies the language of - the source document. If omitted, the service derives the source language - from the input text. The input must contain sufficient text for the service - to identify the language reliably. - :param str target: (optional) Language code that specifies the target - language for translation. Required if model ID is not specified. - :param str document_id: (optional) To use a previously submitted document - as the source for a new translation, enter the `document_id` of the - document. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object - """ - - if file is None: - raise ValueError('file must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='translate_document', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - form_data = [] - if not filename and hasattr(file, 'name'): - filename = basename(file.name) - if not filename: - raise ValueError('filename must be provided') - form_data.append(('file', (filename, file, file_content_type or - 'application/octet-stream'))) - if model_id: - form_data.append(('model_id', (None, model_id, 'text/plain'))) - if source: - form_data.append(('source', (None, source, 'text/plain'))) - if target: - form_data.append(('target', (None, target, 'text/plain'))) - if document_id: - form_data.append(('document_id', (None, document_id, 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - url = '/v3/documents' - request = self.prepare_request( - method='POST', - url=url, - headers=headers, - params=params, - files=form_data, - ) - - response = self.send(request, **kwargs) - return response - - def get_document_status( - self, - document_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Get document status. - - Gets the translation status of a document. - - :param str document_id: The document ID of the document. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `DocumentStatus` object - """ - - if not document_id: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_document_status', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - headers['Accept'] = 'application/json' - - path_param_keys = ['document_id'] - path_param_values = self.encode_path_vars(document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/documents/{document_id}'.format(**path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def delete_document( - self, - document_id: str, - **kwargs, - ) -> DetailedResponse: - """ - Delete document. - - Deletes a document. - - :param str document_id: Document ID of the document to delete. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if not document_id: - raise ValueError('document_id must be provided') - headers = {} - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_document', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['document_id'] - path_param_values = self.encode_path_vars(document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/documents/{document_id}'.format(**path_param_dict) - request = self.prepare_request( - method='DELETE', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - def get_translated_document( - self, - document_id: str, - *, - accept: Optional[str] = None, - **kwargs, - ) -> DetailedResponse: - """ - Get translated document. - - Gets the translated document associated with the given document ID. - - :param str document_id: The document ID of the document that was submitted - for translation. - :param str accept: (optional) The type of the response: - application/powerpoint, application/mspowerpoint, application/x-rtf, - application/json, application/xml, application/vnd.ms-excel, - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, - application/vnd.ms-powerpoint, - application/vnd.openxmlformats-officedocument.presentationml.presentation, - application/msword, - application/vnd.openxmlformats-officedocument.wordprocessingml.document, - application/vnd.oasis.opendocument.spreadsheet, - application/vnd.oasis.opendocument.presentation, - application/vnd.oasis.opendocument.text, application/pdf, application/rtf, - text/html, text/json, text/plain, text/richtext, text/rtf, or text/xml. A - character encoding can be specified by including a `charset` parameter. For - example, 'text/html;charset=utf-8'. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `BinaryIO` result - """ - - if not document_id: - raise ValueError('document_id must be provided') - headers = { - 'Accept': accept, - } - sdk_headers = get_sdk_headers( - service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_translated_document', - ) - headers.update(sdk_headers) - - params = { - 'version': self.version, - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - del kwargs['headers'] - - path_param_keys = ['document_id'] - path_param_values = self.encode_path_vars(document_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/documents/{document_id}/translated_document'.format( - **path_param_dict) - request = self.prepare_request( - method='GET', - url=url, - headers=headers, - params=params, - ) - - response = self.send(request, **kwargs) - return response - - -class CreateModelEnums: - """ - Enums for create_model parameters. - """ - - class ForcedGlossaryContentType(str, Enum): - """ - The content type of forced_glossary. - """ - - APPLICATION_X_TMX_XML = 'application/x-tmx+xml' - APPLICATION_XLIFF_XML = 'application/xliff+xml' - TEXT_CSV = 'text/csv' - TEXT_TAB_SEPARATED_VALUES = 'text/tab-separated-values' - APPLICATION_JSON = 'application/json' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' - - class ParallelCorpusContentType(str, Enum): - """ - The content type of parallel_corpus. - """ - - APPLICATION_X_TMX_XML = 'application/x-tmx+xml' - APPLICATION_XLIFF_XML = 'application/xliff+xml' - TEXT_CSV = 'text/csv' - TEXT_TAB_SEPARATED_VALUES = 'text/tab-separated-values' - APPLICATION_JSON = 'application/json' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' - - -class TranslateDocumentEnums: - """ - Enums for translate_document parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - - APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_OCTET_STREAM = 'application/octet-stream' - APPLICATION_PDF = 'application/pdf' - APPLICATION_POWERPOINT = 'application/powerpoint' - APPLICATION_RTF = 'application/rtf' - APPLICATION_TTAF_XML = 'application/ttaf+xml' - APPLICATION_TTML_XML = 'application/ttml+xml' - APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' - APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' - APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' - APPLICATION_VND_MS_EXCEL = 'application/vnd.ms-excel' - APPLICATION_VND_MS_POWERPOINT = 'application/vnd.ms-powerpoint' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = 'application/vnd.openxmlformats-officedocument.presentationml.presentation' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_X_RTF = 'application/x-rtf' - APPLICATION_XHTML_XML = 'application/xhtml+xml' - APPLICATION_XML = 'application/xml' - TEXT_HTML = 'text/html' - TEXT_JSON = 'text/json' - TEXT_PLAIN = 'text/plain' - TEXT_RICHTEXT = 'text/richtext' - TEXT_RTF = 'text/rtf' - TEXT_SBV = 'text/sbv' - TEXT_SRT = 'text/srt' - TEXT_XML = 'text/xml' - - -class GetTranslatedDocumentEnums: - """ - Enums for get_translated_document parameters. - """ - - class Accept(str, Enum): - """ - The type of the response: application/powerpoint, application/mspowerpoint, - application/x-rtf, application/json, application/xml, application/vnd.ms-excel, - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, - application/vnd.ms-powerpoint, - application/vnd.openxmlformats-officedocument.presentationml.presentation, - application/msword, - application/vnd.openxmlformats-officedocument.wordprocessingml.document, - application/vnd.oasis.opendocument.spreadsheet, - application/vnd.oasis.opendocument.presentation, - application/vnd.oasis.opendocument.text, application/pdf, application/rtf, - text/html, text/json, text/plain, text/richtext, text/rtf, or text/xml. A - character encoding can be specified by including a `charset` parameter. For - example, 'text/html;charset=utf-8'. - """ - - APPLICATION_POWERPOINT = 'application/powerpoint' - APPLICATION_MSPOWERPOINT = 'application/mspowerpoint' - APPLICATION_X_RTF = 'application/x-rtf' - APPLICATION_JSON = 'application/json' - APPLICATION_XML = 'application/xml' - APPLICATION_VND_MS_EXCEL = 'application/vnd.ms-excel' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_SPREADSHEETML_SHEET = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' - APPLICATION_VND_MS_POWERPOINT = 'application/vnd.ms-powerpoint' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_PRESENTATIONML_PRESENTATION = 'application/vnd.openxmlformats-officedocument.presentationml.presentation' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - APPLICATION_VND_OASIS_OPENDOCUMENT_SPREADSHEET = 'application/vnd.oasis.opendocument.spreadsheet' - APPLICATION_VND_OASIS_OPENDOCUMENT_PRESENTATION = 'application/vnd.oasis.opendocument.presentation' - APPLICATION_VND_OASIS_OPENDOCUMENT_TEXT = 'application/vnd.oasis.opendocument.text' - APPLICATION_PDF = 'application/pdf' - APPLICATION_RTF = 'application/rtf' - TEXT_HTML = 'text/html' - TEXT_JSON = 'text/json' - TEXT_PLAIN = 'text/plain' - TEXT_RICHTEXT = 'text/richtext' - TEXT_RTF = 'text/rtf' - TEXT_XML = 'text/xml' - - -############################################################################## -# Models -############################################################################## - - -class DeleteModelResult: - """ - DeleteModelResult. - - :param str status: "OK" indicates that the model was successfully deleted. - """ - - def __init__( - self, - status: str, - ) -> None: - """ - Initialize a DeleteModelResult object. - - :param str status: "OK" indicates that the model was successfully deleted. - """ - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DeleteModelResult': - """Initialize a DeleteModelResult object from a json dictionary.""" - args = {} - if (status := _dict.get('status')) is not None: - args['status'] = status - else: - raise ValueError( - 'Required property \'status\' not present in DeleteModelResult JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DeleteModelResult 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, 'status') and self.status is not None: - _dict['status'] = self.status - 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 DeleteModelResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DeleteModelResult') -> 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: 'DeleteModelResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentList: - """ - DocumentList. - - :param List[DocumentStatus] documents: An array of all previously submitted - documents. - """ - - def __init__( - self, - documents: List['DocumentStatus'], - ) -> None: - """ - Initialize a DocumentList object. - - :param List[DocumentStatus] documents: An array of all previously submitted - documents. - """ - self.documents = documents - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentList': - """Initialize a DocumentList object from a json dictionary.""" - args = {} - if (documents := _dict.get('documents')) is not None: - args['documents'] = [DocumentStatus.from_dict(v) for v in documents] - else: - raise ValueError( - 'Required property \'documents\' not present in DocumentList JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentList 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, 'documents') and self.documents is not None: - documents_list = [] - for v in self.documents: - if isinstance(v, dict): - documents_list.append(v) - else: - documents_list.append(v.to_dict()) - _dict['documents'] = documents_list - 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 DocumentList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocumentList') -> 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: 'DocumentList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocumentStatus: - """ - Document information, including translation status. - - :param str document_id: System generated ID identifying a document being - translated using one specific translation model. - :param str filename: filename from the submission (if it was missing in the - multipart-form, 'noname.' is used. - :param str status: The status of the translation job associated with a submitted - document. - :param str model_id: A globally unique string that identifies the underlying - model that is used for translation. - :param str base_model_id: (optional) Model ID of the base model that was used to - customize the model. If the model is not a custom model, this will be absent or - an empty string. - :param str source: Translation source language code. - :param float detected_language_confidence: (optional) A score between 0 and 1 - indicating the confidence of source language detection. A higher value indicates - greater confidence. This is returned only when the service automatically detects - the source language. - :param str target: Translation target language code. - :param datetime created: The time when the document was submitted. - :param datetime completed: (optional) The time when the translation completed. - :param int word_count: (optional) An estimate of the number of words in the - source document. Returned only if `status` is `available`. - :param int character_count: (optional) The number of characters in the source - document, present only if status=available. - """ - - def __init__( - self, - document_id: str, - filename: str, - status: str, - model_id: str, - source: str, - target: str, - created: datetime, - *, - base_model_id: Optional[str] = None, - detected_language_confidence: Optional[float] = None, - completed: Optional[datetime] = None, - word_count: Optional[int] = None, - character_count: Optional[int] = None, - ) -> None: - """ - Initialize a DocumentStatus object. - - :param str document_id: System generated ID identifying a document being - translated using one specific translation model. - :param str filename: filename from the submission (if it was missing in the - multipart-form, 'noname.' is used. - :param str status: The status of the translation job associated with a - submitted document. - :param str model_id: A globally unique string that identifies the - underlying model that is used for translation. - :param str source: Translation source language code. - :param str target: Translation target language code. - :param datetime created: The time when the document was submitted. - :param str base_model_id: (optional) Model ID of the base model that was - used to customize the model. If the model is not a custom model, this will - be absent or an empty string. - :param float detected_language_confidence: (optional) A score between 0 and - 1 indicating the confidence of source language detection. A higher value - indicates greater confidence. This is returned only when the service - automatically detects the source language. - :param datetime completed: (optional) The time when the translation - completed. - :param int word_count: (optional) An estimate of the number of words in the - source document. Returned only if `status` is `available`. - :param int character_count: (optional) The number of characters in the - source document, present only if status=available. - """ - self.document_id = document_id - self.filename = filename - self.status = status - self.model_id = model_id - self.base_model_id = base_model_id - self.source = source - self.detected_language_confidence = detected_language_confidence - self.target = target - self.created = created - self.completed = completed - self.word_count = word_count - self.character_count = character_count - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentStatus': - """Initialize a DocumentStatus object from a json dictionary.""" - args = {} - if (document_id := _dict.get('document_id')) is not None: - args['document_id'] = document_id - else: - raise ValueError( - 'Required property \'document_id\' not present in DocumentStatus JSON' - ) - if (filename := _dict.get('filename')) is not None: - args['filename'] = filename - else: - raise ValueError( - 'Required property \'filename\' not present in DocumentStatus JSON' - ) - if (status := _dict.get('status')) is not None: - args['status'] = status - else: - raise ValueError( - 'Required property \'status\' not present in DocumentStatus JSON' - ) - if (model_id := _dict.get('model_id')) is not None: - args['model_id'] = model_id - else: - raise ValueError( - 'Required property \'model_id\' not present in DocumentStatus JSON' - ) - if (base_model_id := _dict.get('base_model_id')) is not None: - args['base_model_id'] = base_model_id - if (source := _dict.get('source')) is not None: - args['source'] = source - else: - raise ValueError( - 'Required property \'source\' not present in DocumentStatus JSON' - ) - if (detected_language_confidence := - _dict.get('detected_language_confidence')) is not None: - args['detected_language_confidence'] = detected_language_confidence - if (target := _dict.get('target')) is not None: - args['target'] = target - else: - raise ValueError( - 'Required property \'target\' not present in DocumentStatus JSON' - ) - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - else: - raise ValueError( - 'Required property \'created\' not present in DocumentStatus JSON' - ) - if (completed := _dict.get('completed')) is not None: - args['completed'] = string_to_datetime(completed) - if (word_count := _dict.get('word_count')) is not None: - args['word_count'] = word_count - if (character_count := _dict.get('character_count')) is not None: - args['character_count'] = character_count - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentStatus 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, 'document_id') and self.document_id is not None: - _dict['document_id'] = self.document_id - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'base_model_id') and self.base_model_id is not None: - _dict['base_model_id'] = self.base_model_id - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'detected_language_confidence' - ) and self.detected_language_confidence is not None: - _dict[ - 'detected_language_confidence'] = self.detected_language_confidence - if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'completed') and self.completed is not None: - _dict['completed'] = datetime_to_string(self.completed) - if hasattr(self, 'word_count') and self.word_count is not None: - _dict['word_count'] = self.word_count - if hasattr(self, - 'character_count') and self.character_count is not None: - _dict['character_count'] = self.character_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 DocumentStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocumentStatus') -> 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: 'DocumentStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The status of the translation job associated with a submitted document. - """ - - PROCESSING = 'processing' - AVAILABLE = 'available' - FAILED = 'failed' - - -class IdentifiableLanguage: - """ - IdentifiableLanguage. - - :param str language: The language code for an identifiable language. - :param str name: The name of the identifiable language. - """ - - def __init__( - self, - language: str, - name: str, - ) -> None: - """ - Initialize a IdentifiableLanguage object. - - :param str language: The language code for an identifiable language. - :param str name: The name of the identifiable language. - """ - self.language = language - self.name = name - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguage': - """Initialize a IdentifiableLanguage object from a json dictionary.""" - args = {} - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in IdentifiableLanguage JSON' - ) - if (name := _dict.get('name')) is not None: - args['name'] = name - else: - raise ValueError( - 'Required property \'name\' not present in IdentifiableLanguage JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a IdentifiableLanguage 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, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - 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 IdentifiableLanguage object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'IdentifiableLanguage') -> 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: 'IdentifiableLanguage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IdentifiableLanguages: - """ - IdentifiableLanguages. - - :param List[IdentifiableLanguage] languages: A list of all languages that the - service can identify. - """ - - def __init__( - self, - languages: List['IdentifiableLanguage'], - ) -> None: - """ - Initialize a IdentifiableLanguages object. - - :param List[IdentifiableLanguage] languages: A list of all languages that - the service can identify. - """ - self.languages = languages - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiableLanguages': - """Initialize a IdentifiableLanguages object from a json dictionary.""" - args = {} - if (languages := _dict.get('languages')) is not None: - args['languages'] = [ - IdentifiableLanguage.from_dict(v) for v in languages - ] - else: - raise ValueError( - 'Required property \'languages\' not present in IdentifiableLanguages JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a IdentifiableLanguages 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, 'languages') and self.languages is not None: - languages_list = [] - for v in self.languages: - if isinstance(v, dict): - languages_list.append(v) - else: - languages_list.append(v.to_dict()) - _dict['languages'] = languages_list - 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 IdentifiableLanguages object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'IdentifiableLanguages') -> 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: 'IdentifiableLanguages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IdentifiedLanguage: - """ - IdentifiedLanguage. - - :param str language: The language code for an identified language. - :param float confidence: The confidence score for the identified language. - """ - - def __init__( - self, - language: str, - confidence: float, - ) -> None: - """ - Initialize a IdentifiedLanguage object. - - :param str language: The language code for an identified language. - :param float confidence: The confidence score for the identified language. - """ - self.language = language - self.confidence = confidence - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguage': - """Initialize a IdentifiedLanguage object from a json dictionary.""" - args = {} - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in IdentifiedLanguage JSON' - ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - else: - raise ValueError( - 'Required property \'confidence\' not present in IdentifiedLanguage JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a IdentifiedLanguage 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, 'language') and self.language is not None: - _dict['language'] = self.language - 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 IdentifiedLanguage object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'IdentifiedLanguage') -> 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: 'IdentifiedLanguage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class IdentifiedLanguages: - """ - IdentifiedLanguages. - - :param List[IdentifiedLanguage] languages: A ranking of identified languages - with confidence scores. - """ - - def __init__( - self, - languages: List['IdentifiedLanguage'], - ) -> None: - """ - Initialize a IdentifiedLanguages object. - - :param List[IdentifiedLanguage] languages: A ranking of identified - languages with confidence scores. - """ - self.languages = languages - - @classmethod - def from_dict(cls, _dict: Dict) -> 'IdentifiedLanguages': - """Initialize a IdentifiedLanguages object from a json dictionary.""" - args = {} - if (languages := _dict.get('languages')) is not None: - args['languages'] = [ - IdentifiedLanguage.from_dict(v) for v in languages - ] - else: - raise ValueError( - 'Required property \'languages\' not present in IdentifiedLanguages JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a IdentifiedLanguages 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, 'languages') and self.languages is not None: - languages_list = [] - for v in self.languages: - if isinstance(v, dict): - languages_list.append(v) - else: - languages_list.append(v.to_dict()) - _dict['languages'] = languages_list - 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 IdentifiedLanguages object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'IdentifiedLanguages') -> 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: 'IdentifiedLanguages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Language: - """ - Response payload for languages. - - :param str language: (optional) The language code for the language (for example, - `af`). - :param str language_name: (optional) The name of the language in English (for - example, `Afrikaans`). - :param str native_language_name: (optional) The native name of the language (for - example, `Afrikaans`). - :param str country_code: (optional) The country code for the language (for - example, `ZA` for South Africa). - :param bool words_separated: (optional) Indicates whether words of the language - are separated by whitespace: `true` if the words are separated; `false` - otherwise. - :param str direction: (optional) Indicates the direction of the language: - `right_to_left` or `left_to_right`. - :param bool supported_as_source: (optional) Indicates whether the language can - be used as the source for translation: `true` if the language can be used as the - source; `false` otherwise. - :param bool supported_as_target: (optional) Indicates whether the language can - be used as the target for translation: `true` if the language can be used as the - target; `false` otherwise. - :param bool identifiable: (optional) Indicates whether the language supports - automatic detection: `true` if the language can be detected automatically; - `false` otherwise. - """ - - def __init__( - self, - *, - language: Optional[str] = None, - language_name: Optional[str] = None, - native_language_name: Optional[str] = None, - country_code: Optional[str] = None, - words_separated: Optional[bool] = None, - direction: Optional[str] = None, - supported_as_source: Optional[bool] = None, - supported_as_target: Optional[bool] = None, - identifiable: Optional[bool] = None, - ) -> None: - """ - Initialize a Language object. - - :param str language: (optional) The language code for the language (for - example, `af`). - :param str language_name: (optional) The name of the language in English - (for example, `Afrikaans`). - :param str native_language_name: (optional) The native name of the language - (for example, `Afrikaans`). - :param str country_code: (optional) The country code for the language (for - example, `ZA` for South Africa). - :param bool words_separated: (optional) Indicates whether words of the - language are separated by whitespace: `true` if the words are separated; - `false` otherwise. - :param str direction: (optional) Indicates the direction of the language: - `right_to_left` or `left_to_right`. - :param bool supported_as_source: (optional) Indicates whether the language - can be used as the source for translation: `true` if the language can be - used as the source; `false` otherwise. - :param bool supported_as_target: (optional) Indicates whether the language - can be used as the target for translation: `true` if the language can be - used as the target; `false` otherwise. - :param bool identifiable: (optional) Indicates whether the language - supports automatic detection: `true` if the language can be detected - automatically; `false` otherwise. - """ - self.language = language - self.language_name = language_name - self.native_language_name = native_language_name - self.country_code = country_code - self.words_separated = words_separated - self.direction = direction - self.supported_as_source = supported_as_source - self.supported_as_target = supported_as_target - self.identifiable = identifiable - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Language': - """Initialize a Language object from a json dictionary.""" - args = {} - if (language := _dict.get('language')) is not None: - args['language'] = language - if (language_name := _dict.get('language_name')) is not None: - args['language_name'] = language_name - if (native_language_name := - _dict.get('native_language_name')) is not None: - args['native_language_name'] = native_language_name - if (country_code := _dict.get('country_code')) is not None: - args['country_code'] = country_code - if (words_separated := _dict.get('words_separated')) is not None: - args['words_separated'] = words_separated - if (direction := _dict.get('direction')) is not None: - args['direction'] = direction - if (supported_as_source := - _dict.get('supported_as_source')) is not None: - args['supported_as_source'] = supported_as_source - if (supported_as_target := - _dict.get('supported_as_target')) is not None: - args['supported_as_target'] = supported_as_target - if (identifiable := _dict.get('identifiable')) is not None: - args['identifiable'] = identifiable - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Language 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, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'language_name') and self.language_name is not None: - _dict['language_name'] = self.language_name - if hasattr(self, 'native_language_name' - ) and self.native_language_name is not None: - _dict['native_language_name'] = self.native_language_name - if hasattr(self, 'country_code') and self.country_code is not None: - _dict['country_code'] = self.country_code - if hasattr(self, - 'words_separated') and self.words_separated is not None: - _dict['words_separated'] = self.words_separated - if hasattr(self, 'direction') and self.direction is not None: - _dict['direction'] = self.direction - if hasattr( - self, - 'supported_as_source') and self.supported_as_source is not None: - _dict['supported_as_source'] = self.supported_as_source - if hasattr( - self, - 'supported_as_target') and self.supported_as_target is not None: - _dict['supported_as_target'] = self.supported_as_target - if hasattr(self, 'identifiable') and self.identifiable is not None: - _dict['identifiable'] = self.identifiable - 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 Language object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Language') -> 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: 'Language') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Languages: - """ - The response type for listing supported languages. - - :param List[Language] languages: An array of supported languages with - information about each language. - """ - - def __init__( - self, - languages: List['Language'], - ) -> None: - """ - Initialize a Languages object. - - :param List[Language] languages: An array of supported languages with - information about each language. - """ - self.languages = languages - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Languages': - """Initialize a Languages object from a json dictionary.""" - args = {} - if (languages := _dict.get('languages')) is not None: - args['languages'] = [Language.from_dict(v) for v in languages] - else: - raise ValueError( - 'Required property \'languages\' not present in Languages JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Languages 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, 'languages') and self.languages is not None: - languages_list = [] - for v in self.languages: - if isinstance(v, dict): - languages_list.append(v) - else: - languages_list.append(v.to_dict()) - _dict['languages'] = languages_list - 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 Languages object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Languages') -> 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: 'Languages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Translation: - """ - Translation. - - :param str translation: Translation output in UTF-8. - """ - - def __init__( - self, - translation: str, - ) -> None: - """ - Initialize a Translation object. - - :param str translation: Translation output in UTF-8. - """ - self.translation = translation - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Translation': - """Initialize a Translation object from a json dictionary.""" - args = {} - if (translation := _dict.get('translation')) is not None: - args['translation'] = translation - else: - raise ValueError( - 'Required property \'translation\' not present in Translation JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Translation 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, 'translation') and self.translation is not None: - _dict['translation'] = self.translation - 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 Translation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Translation') -> 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: 'Translation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TranslationModel: - """ - Response payload for models. - - :param str model_id: A globally unique string that identifies the underlying - model that is used for translation. - :param str name: (optional) Optional name that can be specified when the model - is created. - :param str source: (optional) Translation source language code. - :param str target: (optional) Translation target language code. - :param str base_model_id: (optional) Model ID of the base model that was used to - customize the model. If the model is not a custom model, this will be an empty - string. - :param str domain: (optional) The domain of the translation model. - :param bool customizable: (optional) Whether this model can be used as a base - for customization. Customized models are not further customizable, and some base - models are not customizable. - :param bool default_model: (optional) Whether or not the model is a default - model. A default model is the model for a given language pair that will be used - when that language pair is specified in the source and target parameters. - :param str owner: (optional) Either an empty string, indicating the model is not - a custom model, or the ID of the service instance that created the model. - :param str status: (optional) Availability of a model. - """ - - def __init__( - self, - model_id: str, - *, - name: Optional[str] = None, - source: Optional[str] = None, - target: Optional[str] = None, - base_model_id: Optional[str] = None, - domain: Optional[str] = None, - customizable: Optional[bool] = None, - default_model: Optional[bool] = None, - owner: Optional[str] = None, - status: Optional[str] = None, - ) -> None: - """ - Initialize a TranslationModel object. - - :param str model_id: A globally unique string that identifies the - underlying model that is used for translation. - :param str name: (optional) Optional name that can be specified when the - model is created. - :param str source: (optional) Translation source language code. - :param str target: (optional) Translation target language code. - :param str base_model_id: (optional) Model ID of the base model that was - used to customize the model. If the model is not a custom model, this will - be an empty string. - :param str domain: (optional) The domain of the translation model. - :param bool customizable: (optional) Whether this model can be used as a - base for customization. Customized models are not further customizable, and - some base models are not customizable. - :param bool default_model: (optional) Whether or not the model is a default - model. A default model is the model for a given language pair that will be - used when that language pair is specified in the source and target - parameters. - :param str owner: (optional) Either an empty string, indicating the model - is not a custom model, or the ID of the service instance that created the - model. - :param str status: (optional) Availability of a model. - """ - self.model_id = model_id - self.name = name - self.source = source - self.target = target - self.base_model_id = base_model_id - self.domain = domain - self.customizable = customizable - self.default_model = default_model - self.owner = owner - self.status = status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TranslationModel': - """Initialize a TranslationModel object from a json dictionary.""" - args = {} - if (model_id := _dict.get('model_id')) is not None: - args['model_id'] = model_id - else: - raise ValueError( - 'Required property \'model_id\' not present in TranslationModel JSON' - ) - if (name := _dict.get('name')) is not None: - args['name'] = name - if (source := _dict.get('source')) is not None: - args['source'] = source - if (target := _dict.get('target')) is not None: - args['target'] = target - if (base_model_id := _dict.get('base_model_id')) is not None: - args['base_model_id'] = base_model_id - if (domain := _dict.get('domain')) is not None: - args['domain'] = domain - if (customizable := _dict.get('customizable')) is not None: - args['customizable'] = customizable - if (default_model := _dict.get('default_model')) is not None: - args['default_model'] = default_model - if (owner := _dict.get('owner')) is not None: - args['owner'] = owner - if (status := _dict.get('status')) is not None: - args['status'] = status - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TranslationModel 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, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source - if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target - if hasattr(self, 'base_model_id') and self.base_model_id is not None: - _dict['base_model_id'] = self.base_model_id - if hasattr(self, 'domain') and self.domain is not None: - _dict['domain'] = self.domain - if hasattr(self, 'customizable') and self.customizable is not None: - _dict['customizable'] = self.customizable - if hasattr(self, 'default_model') and self.default_model is not None: - _dict['default_model'] = self.default_model - if hasattr(self, 'owner') and self.owner is not None: - _dict['owner'] = self.owner - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - 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 TranslationModel object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TranslationModel') -> 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: 'TranslationModel') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Availability of a model. - """ - - UPLOADING = 'uploading' - UPLOADED = 'uploaded' - DISPATCHING = 'dispatching' - QUEUED = 'queued' - TRAINING = 'training' - TRAINED = 'trained' - PUBLISHING = 'publishing' - AVAILABLE = 'available' - DELETED = 'deleted' - ERROR = 'error' - - -class TranslationModels: - """ - The response type for listing existing translation models. - - :param List[TranslationModel] models: An array of available models. - """ - - def __init__( - self, - models: List['TranslationModel'], - ) -> None: - """ - Initialize a TranslationModels object. - - :param List[TranslationModel] models: An array of available models. - """ - self.models = models - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TranslationModels': - """Initialize a TranslationModels object from a json dictionary.""" - args = {} - if (models := _dict.get('models')) is not None: - args['models'] = [TranslationModel.from_dict(v) for v in models] - else: - raise ValueError( - 'Required property \'models\' not present in TranslationModels JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TranslationModels 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, 'models') and self.models is not None: - models_list = [] - for v in self.models: - if isinstance(v, dict): - models_list.append(v) - else: - models_list.append(v.to_dict()) - _dict['models'] = models_list - 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 TranslationModels object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TranslationModels') -> 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: 'TranslationModels') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TranslationResult: - """ - TranslationResult. - - :param int word_count: An estimate of the number of words in the input text. - :param int character_count: Number of characters in the input text. - :param str detected_language: (optional) The language code of the source text if - the source language was automatically detected. - :param float detected_language_confidence: (optional) A score between 0 and 1 - indicating the confidence of source language detection. A higher value indicates - greater confidence. This is returned only when the service automatically detects - the source language. - :param List[Translation] translations: List of translation output in UTF-8, - corresponding to the input text entries. - """ - - def __init__( - self, - word_count: int, - character_count: int, - translations: List['Translation'], - *, - detected_language: Optional[str] = None, - detected_language_confidence: Optional[float] = None, - ) -> None: - """ - Initialize a TranslationResult object. - - :param int word_count: An estimate of the number of words in the input - text. - :param int character_count: Number of characters in the input text. - :param List[Translation] translations: List of translation output in UTF-8, - corresponding to the input text entries. - :param str detected_language: (optional) The language code of the source - text if the source language was automatically detected. - :param float detected_language_confidence: (optional) A score between 0 and - 1 indicating the confidence of source language detection. A higher value - indicates greater confidence. This is returned only when the service - automatically detects the source language. - """ - self.word_count = word_count - self.character_count = character_count - self.detected_language = detected_language - self.detected_language_confidence = detected_language_confidence - self.translations = translations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TranslationResult': - """Initialize a TranslationResult object from a json dictionary.""" - args = {} - if (word_count := _dict.get('word_count')) is not None: - args['word_count'] = word_count - else: - raise ValueError( - 'Required property \'word_count\' not present in TranslationResult JSON' - ) - if (character_count := _dict.get('character_count')) is not None: - args['character_count'] = character_count - else: - raise ValueError( - 'Required property \'character_count\' not present in TranslationResult JSON' - ) - if (detected_language := _dict.get('detected_language')) is not None: - args['detected_language'] = detected_language - if (detected_language_confidence := - _dict.get('detected_language_confidence')) is not None: - args['detected_language_confidence'] = detected_language_confidence - if (translations := _dict.get('translations')) is not None: - args['translations'] = [ - Translation.from_dict(v) for v in translations - ] - else: - raise ValueError( - 'Required property \'translations\' not present in TranslationResult JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TranslationResult 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, 'word_count') and self.word_count is not None: - _dict['word_count'] = self.word_count - if hasattr(self, - 'character_count') and self.character_count is not None: - _dict['character_count'] = self.character_count - if hasattr(self, - 'detected_language') and self.detected_language is not None: - _dict['detected_language'] = self.detected_language - if hasattr(self, 'detected_language_confidence' - ) and self.detected_language_confidence is not None: - _dict[ - 'detected_language_confidence'] = self.detected_language_confidence - if hasattr(self, 'translations') and self.translations is not None: - translations_list = [] - for v in self.translations: - if isinstance(v, dict): - translations_list.append(v) - else: - translations_list.append(v.to_dict()) - _dict['translations'] = translations_list - 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 TranslationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TranslationResult') -> 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: 'TranslationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other diff --git a/setup.py b/setup.py index e34bb44b2..3e639723e 100644 --- a/setup.py +++ b/setup.py @@ -36,13 +36,13 @@ long_description_content_type='text/markdown', url='https://github.com/watson-developer-cloud/python-sdk', include_package_data=True, - keywords='language, vision, question and answer' + - ' tone_analyzer, natural language classifier,' + - ' text to speech, language translation, ' + + keywords='language, question and answer,' + + ' tone_analyzer,' + + ' text to speech,' + 'language identification, concept expansion, machine translation, ' + - 'personality insights, message resonance, watson developer cloud, ' + + 'message resonance, watson developer cloud, ' + ' wdc, watson, ibm, dialog, user modeling,' + - 'tone analyzer, speech to text, visual recognition', + 'speech to text', classifiers=[ 'Programming Language :: Python', 'Programming Language :: Python :: 2', diff --git a/test/integration/test_language_translator_v3.py b/test/integration/test_language_translator_v3.py deleted file mode 100644 index 1fcfd057d..000000000 --- a/test/integration/test_language_translator_v3.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding: utf-8 -import unittest -import ibm_watson -from os.path import join, dirname -import pytest -import os - - -@pytest.mark.skipif(os.getenv('LANGUAGE_TRANSLATOR_APIKEY') is None, - reason='requires LANGUAGE_TRANSLATOR_APIKEY') -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'}) - - def test_translate(self): - translation = self.language_translator.translate( - text='Hello', model_id='en-es').get_result() - assert translation is not None - translation = self.language_translator.translate( - text='Hello, how are you?', target='es').get_result() - assert translation is not None - - def test_list_languages(self): - languages = self.language_translator.list_languages() - assert languages is not None - - def test_document_translation(self): - 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', - 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() - 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() - 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() - assert delete_document is None diff --git a/test/unit/test_language_translator_v3.py b/test/unit/test_language_translator_v3.py deleted file mode 100644 index 2fe38ed45..000000000 --- a/test/unit/test_language_translator_v3.py +++ /dev/null @@ -1,1841 +0,0 @@ -# -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2018, 2024. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -""" -Unit Tests for LanguageTranslatorV3 -""" - -from datetime import datetime, timezone -from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime -import inspect -import io -import json -import pytest -import re -import requests -import responses -import tempfile -import urllib -from ibm_watson.language_translator_v3 import * - -version = '2018-05-01' - -_service = LanguageTranslatorV3( - authenticator=NoAuthAuthenticator(), - version=version, -) - -_base_url = 'https://api.us-south.language-translator.watson.cloud.ibm.com' -_service.set_service_url(_base_url) - - -def preprocess_url(operation_path: str): - """ - Returns the request url associated with the specified operation path. - This will be base_url concatenated with a quoted version of operation_path. - The returned request URL is used to register the mock response so it needs - to match the request URL that is formed by the requests library. - """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. - request_url = _base_url + operation_path - - # If the request url does NOT end with a /, then just return it as-is. - # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: - return request_url - return re.compile(request_url.rstrip('/') + '/+') - - -############################################################################## -# Start of Service: Languages -############################################################################## -# region - - -class TestListLanguages: - """ - Test Class for list_languages - """ - - @responses.activate - def test_list_languages_all_params(self): - """ - list_languages() - """ - # Set up mock - url = preprocess_url('/v3/languages') - mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.list_languages() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_languages_all_params_with_retries(self): - # Enable retries and run test_list_languages_all_params. - _service.enable_retries() - self.test_list_languages_all_params() - - # Disable retries and run test_list_languages_all_params. - _service.disable_retries() - self.test_list_languages_all_params() - - @responses.activate - def test_list_languages_value_error(self): - """ - test_list_languages_value_error() - """ - # Set up mock - url = preprocess_url('/v3/languages') - mock_response = '{"languages": [{"language": "language", "language_name": "language_name", "native_language_name": "native_language_name", "country_code": "country_code", "words_separated": false, "direction": "direction", "supported_as_source": false, "supported_as_target": false, "identifiable": true}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_languages(**req_copy) - - def test_list_languages_value_error_with_retries(self): - # Enable retries and run test_list_languages_value_error. - _service.enable_retries() - self.test_list_languages_value_error() - - # Disable retries and run test_list_languages_value_error. - _service.disable_retries() - self.test_list_languages_value_error() - - -# endregion -############################################################################## -# End of Service: Languages -############################################################################## - -############################################################################## -# Start of Service: Translation -############################################################################## -# region - - -class TestTranslate: - """ - Test Class for translate - """ - - @responses.activate - def test_translate_all_params(self): - """ - translate() - """ - # Set up mock - url = preprocess_url('/v3/translate') - mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - text = ['testString'] - model_id = 'testString' - source = 'testString' - target = 'testString' - - # Invoke method - response = _service.translate( - text, - model_id=model_id, - source=source, - target=target, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['text'] == ['testString'] - assert req_body['model_id'] == 'testString' - assert req_body['source'] == 'testString' - assert req_body['target'] == 'testString' - - def test_translate_all_params_with_retries(self): - # Enable retries and run test_translate_all_params. - _service.enable_retries() - self.test_translate_all_params() - - # Disable retries and run test_translate_all_params. - _service.disable_retries() - self.test_translate_all_params() - - @responses.activate - def test_translate_value_error(self): - """ - test_translate_value_error() - """ - # Set up mock - url = preprocess_url('/v3/translate') - mock_response = '{"word_count": 10, "character_count": 15, "detected_language": "detected_language", "detected_language_confidence": 0, "translations": [{"translation": "translation"}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - text = ['testString'] - model_id = 'testString' - source = 'testString' - target = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "text": text, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.translate(**req_copy) - - def test_translate_value_error_with_retries(self): - # Enable retries and run test_translate_value_error. - _service.enable_retries() - self.test_translate_value_error() - - # Disable retries and run test_translate_value_error. - _service.disable_retries() - self.test_translate_value_error() - - -# endregion -############################################################################## -# End of Service: Translation -############################################################################## - -############################################################################## -# Start of Service: Identification -############################################################################## -# region - - -class TestListIdentifiableLanguages: - """ - Test Class for list_identifiable_languages - """ - - @responses.activate - def test_list_identifiable_languages_all_params(self): - """ - list_identifiable_languages() - """ - # Set up mock - url = preprocess_url('/v3/identifiable_languages') - mock_response = '{"languages": [{"language": "language", "name": "name"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.list_identifiable_languages() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_identifiable_languages_all_params_with_retries(self): - # Enable retries and run test_list_identifiable_languages_all_params. - _service.enable_retries() - self.test_list_identifiable_languages_all_params() - - # Disable retries and run test_list_identifiable_languages_all_params. - _service.disable_retries() - self.test_list_identifiable_languages_all_params() - - @responses.activate - def test_list_identifiable_languages_value_error(self): - """ - test_list_identifiable_languages_value_error() - """ - # Set up mock - url = preprocess_url('/v3/identifiable_languages') - mock_response = '{"languages": [{"language": "language", "name": "name"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_identifiable_languages(**req_copy) - - def test_list_identifiable_languages_value_error_with_retries(self): - # Enable retries and run test_list_identifiable_languages_value_error. - _service.enable_retries() - self.test_list_identifiable_languages_value_error() - - # Disable retries and run test_list_identifiable_languages_value_error. - _service.disable_retries() - self.test_list_identifiable_languages_value_error() - - -class TestIdentify: - """ - Test Class for identify - """ - - @responses.activate - def test_identify_all_params(self): - """ - identify() - """ - # Set up mock - url = preprocess_url('/v3/identify') - mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - text = 'testString' - - # Invoke method - response = _service.identify( - text, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - assert str(responses.calls[0].request.body, 'utf-8') == text - - def test_identify_all_params_with_retries(self): - # Enable retries and run test_identify_all_params. - _service.enable_retries() - self.test_identify_all_params() - - # Disable retries and run test_identify_all_params. - _service.disable_retries() - self.test_identify_all_params() - - @responses.activate - def test_identify_value_error(self): - """ - test_identify_value_error() - """ - # Set up mock - url = preprocess_url('/v3/identify') - mock_response = '{"languages": [{"language": "language", "confidence": 0}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - text = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "text": text, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.identify(**req_copy) - - def test_identify_value_error_with_retries(self): - # Enable retries and run test_identify_value_error. - _service.enable_retries() - self.test_identify_value_error() - - # Disable retries and run test_identify_value_error. - _service.disable_retries() - self.test_identify_value_error() - - -# endregion -############################################################################## -# End of Service: Identification -############################################################################## - -############################################################################## -# Start of Service: Models -############################################################################## -# region - - -class TestListModels: - """ - Test Class for list_models - """ - - @responses.activate - def test_list_models_all_params(self): - """ - list_models() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - source = 'testString' - target = 'testString' - default = True - - # Invoke method - response = _service.list_models( - source=source, - target=target, - default=default, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'source={}'.format(source) in query_string - assert 'target={}'.format(target) in query_string - assert 'default={}'.format('true' if default else 'false') in query_string - - def test_list_models_all_params_with_retries(self): - # Enable retries and run test_list_models_all_params. - _service.enable_retries() - self.test_list_models_all_params() - - # Disable retries and run test_list_models_all_params. - _service.disable_retries() - self.test_list_models_all_params() - - @responses.activate - def test_list_models_required_params(self): - """ - test_list_models_required_params() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.list_models() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_models_required_params_with_retries(self): - # Enable retries and run test_list_models_required_params. - _service.enable_retries() - self.test_list_models_required_params() - - # Disable retries and run test_list_models_required_params. - _service.disable_retries() - self.test_list_models_required_params() - - @responses.activate - def test_list_models_value_error(self): - """ - test_list_models_value_error() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"models": [{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_models(**req_copy) - - def test_list_models_value_error_with_retries(self): - # Enable retries and run test_list_models_value_error. - _service.enable_retries() - self.test_list_models_value_error() - - # Disable retries and run test_list_models_value_error. - _service.disable_retries() - self.test_list_models_value_error() - - -class TestCreateModel: - """ - Test Class for create_model - """ - - @responses.activate - def test_create_model_all_params(self): - """ - create_model() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - base_model_id = 'testString' - forced_glossary = io.BytesIO(b'This is a mock file.').getvalue() - forced_glossary_content_type = 'application/x-tmx+xml' - parallel_corpus = io.BytesIO(b'This is a mock file.').getvalue() - parallel_corpus_content_type = 'application/x-tmx+xml' - name = 'testString' - - # Invoke method - response = _service.create_model( - base_model_id, - forced_glossary=forced_glossary, - forced_glossary_content_type=forced_glossary_content_type, - parallel_corpus=parallel_corpus, - parallel_corpus_content_type=parallel_corpus_content_type, - name=name, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'base_model_id={}'.format(base_model_id) in query_string - assert 'name={}'.format(name) in query_string - - def test_create_model_all_params_with_retries(self): - # Enable retries and run test_create_model_all_params. - _service.enable_retries() - self.test_create_model_all_params() - - # Disable retries and run test_create_model_all_params. - _service.disable_retries() - self.test_create_model_all_params() - - @responses.activate - def test_create_model_required_params(self): - """ - test_create_model_required_params() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - base_model_id = 'testString' - - # Invoke method - response = _service.create_model( - base_model_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'base_model_id={}'.format(base_model_id) in query_string - - def test_create_model_required_params_with_retries(self): - # Enable retries and run test_create_model_required_params. - _service.enable_retries() - self.test_create_model_required_params() - - # Disable retries and run test_create_model_required_params. - _service.disable_retries() - self.test_create_model_required_params() - - @responses.activate - def test_create_model_value_error(self): - """ - test_create_model_value_error() - """ - # Set up mock - url = preprocess_url('/v3/models') - mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - base_model_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "base_model_id": base_model_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.create_model(**req_copy) - - def test_create_model_value_error_with_retries(self): - # Enable retries and run test_create_model_value_error. - _service.enable_retries() - self.test_create_model_value_error() - - # Disable retries and run test_create_model_value_error. - _service.disable_retries() - self.test_create_model_value_error() - - -class TestDeleteModel: - """ - Test Class for delete_model - """ - - @responses.activate - def test_delete_model_all_params(self): - """ - delete_model() - """ - # Set up mock - url = preprocess_url('/v3/models/testString') - mock_response = '{"status": "status"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - model_id = 'testString' - - # Invoke method - response = _service.delete_model( - model_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_delete_model_all_params_with_retries(self): - # Enable retries and run test_delete_model_all_params. - _service.enable_retries() - self.test_delete_model_all_params() - - # Disable retries and run test_delete_model_all_params. - _service.disable_retries() - self.test_delete_model_all_params() - - @responses.activate - def test_delete_model_value_error(self): - """ - test_delete_model_value_error() - """ - # Set up mock - url = preprocess_url('/v3/models/testString') - mock_response = '{"status": "status"}' - responses.add( - responses.DELETE, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - model_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "model_id": model_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_model(**req_copy) - - def test_delete_model_value_error_with_retries(self): - # Enable retries and run test_delete_model_value_error. - _service.enable_retries() - self.test_delete_model_value_error() - - # Disable retries and run test_delete_model_value_error. - _service.disable_retries() - self.test_delete_model_value_error() - - -class TestGetModel: - """ - Test Class for get_model - """ - - @responses.activate - def test_get_model_all_params(self): - """ - get_model() - """ - # Set up mock - url = preprocess_url('/v3/models/testString') - mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - model_id = 'testString' - - # Invoke method - response = _service.get_model( - model_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_model_all_params_with_retries(self): - # Enable retries and run test_get_model_all_params. - _service.enable_retries() - self.test_get_model_all_params() - - # Disable retries and run test_get_model_all_params. - _service.disable_retries() - self.test_get_model_all_params() - - @responses.activate - def test_get_model_value_error(self): - """ - test_get_model_value_error() - """ - # Set up mock - url = preprocess_url('/v3/models/testString') - mock_response = '{"model_id": "model_id", "name": "name", "source": "source", "target": "target", "base_model_id": "base_model_id", "domain": "domain", "customizable": true, "default_model": false, "owner": "owner", "status": "uploading"}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - model_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "model_id": model_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_model(**req_copy) - - def test_get_model_value_error_with_retries(self): - # Enable retries and run test_get_model_value_error. - _service.enable_retries() - self.test_get_model_value_error() - - # Disable retries and run test_get_model_value_error. - _service.disable_retries() - self.test_get_model_value_error() - - -# endregion -############################################################################## -# End of Service: Models -############################################################################## - -############################################################################## -# Start of Service: DocumentTranslation -############################################################################## -# region - - -class TestListDocuments: - """ - Test Class for list_documents - """ - - @responses.activate - def test_list_documents_all_params(self): - """ - list_documents() - """ - # Set up mock - url = preprocess_url('/v3/documents') - mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Invoke method - response = _service.list_documents() - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_list_documents_all_params_with_retries(self): - # Enable retries and run test_list_documents_all_params. - _service.enable_retries() - self.test_list_documents_all_params() - - # Disable retries and run test_list_documents_all_params. - _service.disable_retries() - self.test_list_documents_all_params() - - @responses.activate - def test_list_documents_value_error(self): - """ - test_list_documents_value_error() - """ - # Set up mock - url = preprocess_url('/v3/documents') - mock_response = '{"documents": [{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}]}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.list_documents(**req_copy) - - def test_list_documents_value_error_with_retries(self): - # Enable retries and run test_list_documents_value_error. - _service.enable_retries() - self.test_list_documents_value_error() - - # Disable retries and run test_list_documents_value_error. - _service.disable_retries() - self.test_list_documents_value_error() - - -class TestTranslateDocument: - """ - Test Class for translate_document - """ - - @responses.activate - def test_translate_document_all_params(self): - """ - translate_document() - """ - # Set up mock - url = preprocess_url('/v3/documents') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - file_content_type = 'application/mspowerpoint' - model_id = 'testString' - source = 'testString' - target = 'testString' - document_id = 'testString' - - # Invoke method - response = _service.translate_document( - file, - filename=filename, - file_content_type=file_content_type, - model_id=model_id, - source=source, - target=target, - document_id=document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_translate_document_all_params_with_retries(self): - # Enable retries and run test_translate_document_all_params. - _service.enable_retries() - self.test_translate_document_all_params() - - # Disable retries and run test_translate_document_all_params. - _service.disable_retries() - self.test_translate_document_all_params() - - @responses.activate - def test_translate_document_required_params(self): - """ - test_translate_document_required_params() - """ - # Set up mock - url = preprocess_url('/v3/documents') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - - # Invoke method - response = _service.translate_document( - file, - filename=filename, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 202 - - def test_translate_document_required_params_with_retries(self): - # Enable retries and run test_translate_document_required_params. - _service.enable_retries() - self.test_translate_document_required_params() - - # Disable retries and run test_translate_document_required_params. - _service.disable_retries() - self.test_translate_document_required_params() - - @responses.activate - def test_translate_document_value_error(self): - """ - test_translate_document_value_error() - """ - # Set up mock - url = preprocess_url('/v3/documents') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=202, - ) - - # Set up parameter values - file = io.BytesIO(b'This is a mock file.').getvalue() - filename = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "file": file, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.translate_document(**req_copy) - - def test_translate_document_value_error_with_retries(self): - # Enable retries and run test_translate_document_value_error. - _service.enable_retries() - self.test_translate_document_value_error() - - # Disable retries and run test_translate_document_value_error. - _service.disable_retries() - self.test_translate_document_value_error() - - -class TestGetDocumentStatus: - """ - Test Class for get_document_status - """ - - @responses.activate - def test_get_document_status_all_params(self): - """ - get_document_status() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - document_id = 'testString' - - # Invoke method - response = _service.get_document_status( - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_document_status_all_params_with_retries(self): - # Enable retries and run test_get_document_status_all_params. - _service.enable_retries() - self.test_get_document_status_all_params() - - # Disable retries and run test_get_document_status_all_params. - _service.disable_retries() - self.test_get_document_status_all_params() - - @responses.activate - def test_get_document_status_value_error(self): - """ - test_get_document_status_value_error() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString') - mock_response = '{"document_id": "document_id", "filename": "filename", "status": "processing", "model_id": "model_id", "base_model_id": "base_model_id", "source": "source", "detected_language_confidence": 0, "target": "target", "created": "2019-01-01T12:00:00.000Z", "completed": "2019-01-01T12:00:00.000Z", "word_count": 10, "character_count": 15}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_document_status(**req_copy) - - def test_get_document_status_value_error_with_retries(self): - # Enable retries and run test_get_document_status_value_error. - _service.enable_retries() - self.test_get_document_status_value_error() - - # Disable retries and run test_get_document_status_value_error. - _service.disable_retries() - self.test_get_document_status_value_error() - - -class TestDeleteDocument: - """ - Test Class for delete_document - """ - - @responses.activate - def test_delete_document_all_params(self): - """ - delete_document() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - document_id = 'testString' - - # Invoke method - response = _service.delete_document( - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 204 - - def test_delete_document_all_params_with_retries(self): - # Enable retries and run test_delete_document_all_params. - _service.enable_retries() - self.test_delete_document_all_params() - - # Disable retries and run test_delete_document_all_params. - _service.disable_retries() - self.test_delete_document_all_params() - - @responses.activate - def test_delete_document_value_error(self): - """ - test_delete_document_value_error() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString') - responses.add( - responses.DELETE, - url, - status=204, - ) - - # Set up parameter values - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_document(**req_copy) - - def test_delete_document_value_error_with_retries(self): - # Enable retries and run test_delete_document_value_error. - _service.enable_retries() - self.test_delete_document_value_error() - - # Disable retries and run test_delete_document_value_error. - _service.disable_retries() - self.test_delete_document_value_error() - - -class TestGetTranslatedDocument: - """ - Test Class for get_translated_document - """ - - @responses.activate - def test_get_translated_document_all_params(self): - """ - get_translated_document() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString/translated_document') - mock_response = 'This is a mock binary response.' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200, - ) - - # Set up parameter values - document_id = 'testString' - accept = 'application/powerpoint' - - # Invoke method - response = _service.get_translated_document( - document_id, - accept=accept, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_translated_document_all_params_with_retries(self): - # Enable retries and run test_get_translated_document_all_params. - _service.enable_retries() - self.test_get_translated_document_all_params() - - # Disable retries and run test_get_translated_document_all_params. - _service.disable_retries() - self.test_get_translated_document_all_params() - - @responses.activate - def test_get_translated_document_required_params(self): - """ - test_get_translated_document_required_params() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString/translated_document') - mock_response = 'This is a mock binary response.' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200, - ) - - # Set up parameter values - document_id = 'testString' - - # Invoke method - response = _service.get_translated_document( - document_id, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - - def test_get_translated_document_required_params_with_retries(self): - # Enable retries and run test_get_translated_document_required_params. - _service.enable_retries() - self.test_get_translated_document_required_params() - - # Disable retries and run test_get_translated_document_required_params. - _service.disable_retries() - self.test_get_translated_document_required_params() - - @responses.activate - def test_get_translated_document_value_error(self): - """ - test_get_translated_document_value_error() - """ - # Set up mock - url = preprocess_url('/v3/documents/testString/translated_document') - mock_response = 'This is a mock binary response.' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/powerpoint', - status=200, - ) - - # Set up parameter values - document_id = 'testString' - - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "document_id": document_id, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.get_translated_document(**req_copy) - - def test_get_translated_document_value_error_with_retries(self): - # Enable retries and run test_get_translated_document_value_error. - _service.enable_retries() - self.test_get_translated_document_value_error() - - # Disable retries and run test_get_translated_document_value_error. - _service.disable_retries() - self.test_get_translated_document_value_error() - - -# endregion -############################################################################## -# End of Service: DocumentTranslation -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region - - -class TestModel_DeleteModelResult: - """ - Test Class for DeleteModelResult - """ - - def test_delete_model_result_serialization(self): - """ - Test serialization/deserialization for DeleteModelResult - """ - - # Construct a json representation of a DeleteModelResult model - delete_model_result_model_json = {} - delete_model_result_model_json['status'] = 'testString' - - # Construct a model instance of DeleteModelResult by calling from_dict on the json representation - delete_model_result_model = DeleteModelResult.from_dict(delete_model_result_model_json) - assert delete_model_result_model != False - - # Construct a model instance of DeleteModelResult by calling from_dict on the json representation - delete_model_result_model_dict = DeleteModelResult.from_dict(delete_model_result_model_json).__dict__ - delete_model_result_model2 = DeleteModelResult(**delete_model_result_model_dict) - - # Verify the model instances are equivalent - assert delete_model_result_model == delete_model_result_model2 - - # Convert model instance back to dict and verify no loss of data - delete_model_result_model_json2 = delete_model_result_model.to_dict() - assert delete_model_result_model_json2 == delete_model_result_model_json - - -class TestModel_DocumentList: - """ - Test Class for DocumentList - """ - - def test_document_list_serialization(self): - """ - Test serialization/deserialization for DocumentList - """ - - # Construct dict forms of any model objects needed in order to build this model. - - document_status_model = {} # DocumentStatus - document_status_model['document_id'] = 'testString' - document_status_model['filename'] = 'testString' - document_status_model['status'] = 'processing' - document_status_model['model_id'] = 'testString' - document_status_model['base_model_id'] = 'testString' - document_status_model['source'] = 'testString' - document_status_model['detected_language_confidence'] = 0 - document_status_model['target'] = 'testString' - document_status_model['created'] = '2019-01-01T12:00:00Z' - document_status_model['completed'] = '2019-01-01T12:00:00Z' - document_status_model['word_count'] = 38 - document_status_model['character_count'] = 38 - - # Construct a json representation of a DocumentList model - document_list_model_json = {} - document_list_model_json['documents'] = [document_status_model] - - # Construct a model instance of DocumentList by calling from_dict on the json representation - document_list_model = DocumentList.from_dict(document_list_model_json) - assert document_list_model != False - - # Construct a model instance of DocumentList by calling from_dict on the json representation - document_list_model_dict = DocumentList.from_dict(document_list_model_json).__dict__ - document_list_model2 = DocumentList(**document_list_model_dict) - - # Verify the model instances are equivalent - assert document_list_model == document_list_model2 - - # Convert model instance back to dict and verify no loss of data - document_list_model_json2 = document_list_model.to_dict() - assert document_list_model_json2 == document_list_model_json - - -class TestModel_DocumentStatus: - """ - Test Class for DocumentStatus - """ - - def test_document_status_serialization(self): - """ - Test serialization/deserialization for DocumentStatus - """ - - # Construct a json representation of a DocumentStatus model - document_status_model_json = {} - document_status_model_json['document_id'] = 'testString' - document_status_model_json['filename'] = 'testString' - document_status_model_json['status'] = 'processing' - document_status_model_json['model_id'] = 'testString' - document_status_model_json['base_model_id'] = 'testString' - document_status_model_json['source'] = 'testString' - document_status_model_json['detected_language_confidence'] = 0 - document_status_model_json['target'] = 'testString' - document_status_model_json['created'] = '2019-01-01T12:00:00Z' - document_status_model_json['completed'] = '2019-01-01T12:00:00Z' - document_status_model_json['word_count'] = 38 - document_status_model_json['character_count'] = 38 - - # Construct a model instance of DocumentStatus by calling from_dict on the json representation - document_status_model = DocumentStatus.from_dict(document_status_model_json) - assert document_status_model != False - - # Construct a model instance of DocumentStatus by calling from_dict on the json representation - document_status_model_dict = DocumentStatus.from_dict(document_status_model_json).__dict__ - document_status_model2 = DocumentStatus(**document_status_model_dict) - - # Verify the model instances are equivalent - assert document_status_model == document_status_model2 - - # Convert model instance back to dict and verify no loss of data - document_status_model_json2 = document_status_model.to_dict() - assert document_status_model_json2 == document_status_model_json - - -class TestModel_IdentifiableLanguage: - """ - Test Class for IdentifiableLanguage - """ - - def test_identifiable_language_serialization(self): - """ - Test serialization/deserialization for IdentifiableLanguage - """ - - # Construct a json representation of a IdentifiableLanguage model - identifiable_language_model_json = {} - identifiable_language_model_json['language'] = 'testString' - identifiable_language_model_json['name'] = 'testString' - - # Construct a model instance of IdentifiableLanguage by calling from_dict on the json representation - identifiable_language_model = IdentifiableLanguage.from_dict(identifiable_language_model_json) - assert identifiable_language_model != False - - # Construct a model instance of IdentifiableLanguage by calling from_dict on the json representation - identifiable_language_model_dict = IdentifiableLanguage.from_dict(identifiable_language_model_json).__dict__ - identifiable_language_model2 = IdentifiableLanguage(**identifiable_language_model_dict) - - # Verify the model instances are equivalent - assert identifiable_language_model == identifiable_language_model2 - - # Convert model instance back to dict and verify no loss of data - identifiable_language_model_json2 = identifiable_language_model.to_dict() - assert identifiable_language_model_json2 == identifiable_language_model_json - - -class TestModel_IdentifiableLanguages: - """ - Test Class for IdentifiableLanguages - """ - - def test_identifiable_languages_serialization(self): - """ - Test serialization/deserialization for IdentifiableLanguages - """ - - # Construct dict forms of any model objects needed in order to build this model. - - identifiable_language_model = {} # IdentifiableLanguage - identifiable_language_model['language'] = 'testString' - identifiable_language_model['name'] = 'testString' - - # Construct a json representation of a IdentifiableLanguages model - identifiable_languages_model_json = {} - identifiable_languages_model_json['languages'] = [identifiable_language_model] - - # Construct a model instance of IdentifiableLanguages by calling from_dict on the json representation - identifiable_languages_model = IdentifiableLanguages.from_dict(identifiable_languages_model_json) - assert identifiable_languages_model != False - - # Construct a model instance of IdentifiableLanguages by calling from_dict on the json representation - identifiable_languages_model_dict = IdentifiableLanguages.from_dict(identifiable_languages_model_json).__dict__ - identifiable_languages_model2 = IdentifiableLanguages(**identifiable_languages_model_dict) - - # Verify the model instances are equivalent - assert identifiable_languages_model == identifiable_languages_model2 - - # Convert model instance back to dict and verify no loss of data - identifiable_languages_model_json2 = identifiable_languages_model.to_dict() - assert identifiable_languages_model_json2 == identifiable_languages_model_json - - -class TestModel_IdentifiedLanguage: - """ - Test Class for IdentifiedLanguage - """ - - def test_identified_language_serialization(self): - """ - Test serialization/deserialization for IdentifiedLanguage - """ - - # Construct a json representation of a IdentifiedLanguage model - identified_language_model_json = {} - identified_language_model_json['language'] = 'testString' - identified_language_model_json['confidence'] = 0 - - # Construct a model instance of IdentifiedLanguage by calling from_dict on the json representation - identified_language_model = IdentifiedLanguage.from_dict(identified_language_model_json) - assert identified_language_model != False - - # Construct a model instance of IdentifiedLanguage by calling from_dict on the json representation - identified_language_model_dict = IdentifiedLanguage.from_dict(identified_language_model_json).__dict__ - identified_language_model2 = IdentifiedLanguage(**identified_language_model_dict) - - # Verify the model instances are equivalent - assert identified_language_model == identified_language_model2 - - # Convert model instance back to dict and verify no loss of data - identified_language_model_json2 = identified_language_model.to_dict() - assert identified_language_model_json2 == identified_language_model_json - - -class TestModel_IdentifiedLanguages: - """ - Test Class for IdentifiedLanguages - """ - - def test_identified_languages_serialization(self): - """ - Test serialization/deserialization for IdentifiedLanguages - """ - - # Construct dict forms of any model objects needed in order to build this model. - - identified_language_model = {} # IdentifiedLanguage - identified_language_model['language'] = 'testString' - identified_language_model['confidence'] = 0 - - # Construct a json representation of a IdentifiedLanguages model - identified_languages_model_json = {} - identified_languages_model_json['languages'] = [identified_language_model] - - # Construct a model instance of IdentifiedLanguages by calling from_dict on the json representation - identified_languages_model = IdentifiedLanguages.from_dict(identified_languages_model_json) - assert identified_languages_model != False - - # Construct a model instance of IdentifiedLanguages by calling from_dict on the json representation - identified_languages_model_dict = IdentifiedLanguages.from_dict(identified_languages_model_json).__dict__ - identified_languages_model2 = IdentifiedLanguages(**identified_languages_model_dict) - - # Verify the model instances are equivalent - assert identified_languages_model == identified_languages_model2 - - # Convert model instance back to dict and verify no loss of data - identified_languages_model_json2 = identified_languages_model.to_dict() - assert identified_languages_model_json2 == identified_languages_model_json - - -class TestModel_Language: - """ - Test Class for Language - """ - - def test_language_serialization(self): - """ - Test serialization/deserialization for Language - """ - - # Construct a json representation of a Language model - language_model_json = {} - language_model_json['language'] = 'testString' - language_model_json['language_name'] = 'testString' - language_model_json['native_language_name'] = 'testString' - language_model_json['country_code'] = 'testString' - language_model_json['words_separated'] = True - language_model_json['direction'] = 'testString' - language_model_json['supported_as_source'] = True - language_model_json['supported_as_target'] = True - language_model_json['identifiable'] = True - - # Construct a model instance of Language by calling from_dict on the json representation - language_model = Language.from_dict(language_model_json) - assert language_model != False - - # Construct a model instance of Language by calling from_dict on the json representation - language_model_dict = Language.from_dict(language_model_json).__dict__ - language_model2 = Language(**language_model_dict) - - # Verify the model instances are equivalent - assert language_model == language_model2 - - # Convert model instance back to dict and verify no loss of data - language_model_json2 = language_model.to_dict() - assert language_model_json2 == language_model_json - - -class TestModel_Languages: - """ - Test Class for Languages - """ - - def test_languages_serialization(self): - """ - Test serialization/deserialization for Languages - """ - - # Construct dict forms of any model objects needed in order to build this model. - - language_model = {} # Language - language_model['language'] = 'testString' - language_model['language_name'] = 'testString' - language_model['native_language_name'] = 'testString' - language_model['country_code'] = 'testString' - language_model['words_separated'] = True - language_model['direction'] = 'testString' - language_model['supported_as_source'] = True - language_model['supported_as_target'] = True - language_model['identifiable'] = True - - # Construct a json representation of a Languages model - languages_model_json = {} - languages_model_json['languages'] = [language_model] - - # Construct a model instance of Languages by calling from_dict on the json representation - languages_model = Languages.from_dict(languages_model_json) - assert languages_model != False - - # Construct a model instance of Languages by calling from_dict on the json representation - languages_model_dict = Languages.from_dict(languages_model_json).__dict__ - languages_model2 = Languages(**languages_model_dict) - - # Verify the model instances are equivalent - assert languages_model == languages_model2 - - # Convert model instance back to dict and verify no loss of data - languages_model_json2 = languages_model.to_dict() - assert languages_model_json2 == languages_model_json - - -class TestModel_Translation: - """ - Test Class for Translation - """ - - def test_translation_serialization(self): - """ - Test serialization/deserialization for Translation - """ - - # Construct a json representation of a Translation model - translation_model_json = {} - translation_model_json['translation'] = 'testString' - - # Construct a model instance of Translation by calling from_dict on the json representation - translation_model = Translation.from_dict(translation_model_json) - assert translation_model != False - - # Construct a model instance of Translation by calling from_dict on the json representation - translation_model_dict = Translation.from_dict(translation_model_json).__dict__ - translation_model2 = Translation(**translation_model_dict) - - # Verify the model instances are equivalent - assert translation_model == translation_model2 - - # Convert model instance back to dict and verify no loss of data - translation_model_json2 = translation_model.to_dict() - assert translation_model_json2 == translation_model_json - - -class TestModel_TranslationModel: - """ - Test Class for TranslationModel - """ - - def test_translation_model_serialization(self): - """ - Test serialization/deserialization for TranslationModel - """ - - # Construct a json representation of a TranslationModel model - translation_model_model_json = {} - translation_model_model_json['model_id'] = 'testString' - translation_model_model_json['name'] = 'testString' - translation_model_model_json['source'] = 'testString' - translation_model_model_json['target'] = 'testString' - translation_model_model_json['base_model_id'] = 'testString' - translation_model_model_json['domain'] = 'testString' - translation_model_model_json['customizable'] = True - translation_model_model_json['default_model'] = True - translation_model_model_json['owner'] = 'testString' - translation_model_model_json['status'] = 'uploading' - - # Construct a model instance of TranslationModel by calling from_dict on the json representation - translation_model_model = TranslationModel.from_dict(translation_model_model_json) - assert translation_model_model != False - - # Construct a model instance of TranslationModel by calling from_dict on the json representation - translation_model_model_dict = TranslationModel.from_dict(translation_model_model_json).__dict__ - translation_model_model2 = TranslationModel(**translation_model_model_dict) - - # Verify the model instances are equivalent - assert translation_model_model == translation_model_model2 - - # Convert model instance back to dict and verify no loss of data - translation_model_model_json2 = translation_model_model.to_dict() - assert translation_model_model_json2 == translation_model_model_json - - -class TestModel_TranslationModels: - """ - Test Class for TranslationModels - """ - - def test_translation_models_serialization(self): - """ - Test serialization/deserialization for TranslationModels - """ - - # Construct dict forms of any model objects needed in order to build this model. - - translation_model_model = {} # TranslationModel - translation_model_model['model_id'] = 'testString' - translation_model_model['name'] = 'testString' - translation_model_model['source'] = 'testString' - translation_model_model['target'] = 'testString' - translation_model_model['base_model_id'] = 'testString' - translation_model_model['domain'] = 'testString' - translation_model_model['customizable'] = True - translation_model_model['default_model'] = True - translation_model_model['owner'] = 'testString' - translation_model_model['status'] = 'uploading' - - # Construct a json representation of a TranslationModels model - translation_models_model_json = {} - translation_models_model_json['models'] = [translation_model_model] - - # Construct a model instance of TranslationModels by calling from_dict on the json representation - translation_models_model = TranslationModels.from_dict(translation_models_model_json) - assert translation_models_model != False - - # Construct a model instance of TranslationModels by calling from_dict on the json representation - translation_models_model_dict = TranslationModels.from_dict(translation_models_model_json).__dict__ - translation_models_model2 = TranslationModels(**translation_models_model_dict) - - # Verify the model instances are equivalent - assert translation_models_model == translation_models_model2 - - # Convert model instance back to dict and verify no loss of data - translation_models_model_json2 = translation_models_model.to_dict() - assert translation_models_model_json2 == translation_models_model_json - - -class TestModel_TranslationResult: - """ - Test Class for TranslationResult - """ - - def test_translation_result_serialization(self): - """ - Test serialization/deserialization for TranslationResult - """ - - # Construct dict forms of any model objects needed in order to build this model. - - translation_model = {} # Translation - translation_model['translation'] = 'testString' - - # Construct a json representation of a TranslationResult model - translation_result_model_json = {} - translation_result_model_json['word_count'] = 38 - translation_result_model_json['character_count'] = 38 - translation_result_model_json['detected_language'] = 'testString' - translation_result_model_json['detected_language_confidence'] = 0 - translation_result_model_json['translations'] = [translation_model] - - # Construct a model instance of TranslationResult by calling from_dict on the json representation - translation_result_model = TranslationResult.from_dict(translation_result_model_json) - assert translation_result_model != False - - # Construct a model instance of TranslationResult by calling from_dict on the json representation - translation_result_model_dict = TranslationResult.from_dict(translation_result_model_json).__dict__ - translation_result_model2 = TranslationResult(**translation_result_model_dict) - - # Verify the model instances are equivalent - assert translation_result_model == translation_result_model2 - - # Convert model instance back to dict and verify no loss of data - translation_result_model_json2 = translation_result_model.to_dict() - assert translation_result_model_json2 == translation_result_model_json - - -# endregion -############################################################################## -# End of Model Tests -############################################################################## From 043eed48f1808ad3c0c325be18e2bd7ecc339c14 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 18 Oct 2024 11:57:31 -0500 Subject: [PATCH 433/455] feat(discov2): add functions for new batches api --- ibm_watson/discovery_v2.py | 452 ++++++++++++++++++++++++++++++++- test/unit/test_discovery_v2.py | 415 ++++++++++++++++++++++++++++++ 2 files changed, 856 insertions(+), 11 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index f3ede4e61..e5c0fbe71 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1338,8 +1338,12 @@ def query( (`extracted_metadata.filename`) fields. If this parameter is an empty list, then all fields are returned. :param int offset: (optional) The number of query results to skip at the - beginning. For example, if the total number of results that are returned is - 10 and the offset is 8, it returns the last two results. + beginning. Consider that the `count` is set to 10 (the default value) and + the total number of results that are returned is 100. In this case, the + following examples show the returned results for different `offset` values: + * If `offset` is set to 95, it returns the last 5 results. + * If `offset` is set to 10, it returns the second batch of 10 results. + * If `offset` is set to 100 or more, it returns empty results. :param str sort: (optional) A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending @@ -2855,6 +2859,231 @@ def delete_enrichment( response = self.send(request, **kwargs) return response + ######################### + # Batches + ######################### + + def list_batches( + self, + project_id: str, + collection_id: str, + **kwargs, + ) -> DetailedResponse: + """ + List batches. + + A batch is a set of documents that are ready for enrichment by an external + application. After you apply a webhook enrichment to a collection, and then + process or upload documents to the collection, Discovery creates a batch with a + unique **batch_id**. + To start, you must register your external application as a **webhook** type by + using the [Create enrichment API](/apidocs/discovery-data#createenrichment) + method. + Use the List batches API to get the following: + * Notified batches that are not yet pulled by the external enrichment + application. + * Batches that are pulled, but not yet pushed to Discovery by the external + enrichment application. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) 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 with `dict` result representing a `ListBatchesResponse` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_batches', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id'] + path_param_values = self.encode_path_vars(project_id, collection_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/batches'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def pull_batches( + self, + project_id: str, + collection_id: str, + batch_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Pull batches. + + Pull a batch of documents from Discovery for enrichment by an external + application. Ensure to include the `Accept-Encoding: gzip` header in this method + to get the file. You can also implement retry logic when calling this method to + avoid any network errors. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param str batch_id: The Universally Unique Identifier (UUID) of the + document batch that is being requested from Discovery. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `PullBatchesResponse` object + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if not batch_id: + raise ValueError('batch_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='pull_batches', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id', 'batch_id'] + path_param_values = self.encode_path_vars(project_id, collection_id, + batch_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/batches/{batch_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def push_batches( + self, + project_id: str, + collection_id: str, + batch_id: str, + *, + file: Optional[BinaryIO] = None, + filename: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Push batches. + + Push a batch of documents to Discovery after annotation by an external + application. You can implement retry logic when calling this method to avoid any + network errors. + + :param str project_id: The Universally Unique Identifier (UUID) of the + project. This information can be found from the *Integrate and Deploy* page + in Discovery. + :param str collection_id: The Universally Unique Identifier (UUID) of the + collection. + :param str batch_id: The Universally Unique Identifier (UUID) of the + document batch that is being requested from Discovery. + :param BinaryIO file: (optional) A compressed newline-delimited JSON + (NDJSON), which is a JSON file with one row of data per line. For example, + `{batch_id}.ndjson.gz`. For more information, see [Binary attachment in the + push batches + method](/docs/discovery-data?topic=discovery-data-external-enrichment#binary-attachment-push-batches). + There is no limitation on the name of the file because Discovery does not + use the name for processing. The list of features in the document is + specified in the `features` object. + :param str filename: (optional) The filename for file. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `bool` result + """ + + if not project_id: + raise ValueError('project_id must be provided') + if not collection_id: + raise ValueError('collection_id must be provided') + if not batch_id: + raise ValueError('batch_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='push_batches', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + form_data = [] + if file: + if not filename and hasattr(file, 'name'): + filename = basename(file.name) + if not filename: + raise ValueError('filename must be provided') + form_data.append( + ('file', (filename, file, 'application/octet-stream'))) + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['project_id', 'collection_id', 'batch_id'] + path_param_values = self.encode_path_vars(project_id, collection_id, + batch_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/projects/{project_id}/collections/{collection_id}/batches/{batch_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + files=form_data, + ) + + response = self.send(request, **kwargs) + return response + ######################### # Document classifiers ######################### @@ -3974,6 +4203,85 @@ def __ne__(self, other: 'AnalyzedResult') -> bool: return not self == other +class BatchDetails: + """ + A batch is a set of documents that are ready for enrichment by an external + application. After you apply a webhook enrichment to a collection, and then process or + upload documents to the collection, Discovery creates a batch with a unique + **batch_id**. + + :param str batch_id: (optional) The Universally Unique Identifier (UUID) for a + batch of documents. + :param datetime created: (optional) The date and time (RFC3339) that the batch + was created. + :param str enrichment_id: (optional) The Universally Unique Identifier (UUID) + for the external enrichment. + """ + + def __init__( + self, + *, + batch_id: Optional[str] = None, + created: Optional[datetime] = None, + enrichment_id: Optional[str] = None, + ) -> None: + """ + Initialize a BatchDetails object. + + :param str enrichment_id: (optional) The Universally Unique Identifier + (UUID) for the external enrichment. + """ + self.batch_id = batch_id + self.created = created + self.enrichment_id = enrichment_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'BatchDetails': + """Initialize a BatchDetails object from a json dictionary.""" + args = {} + if (batch_id := _dict.get('batch_id')) is not None: + args['batch_id'] = batch_id + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (enrichment_id := _dict.get('enrichment_id')) is not None: + args['enrichment_id'] = enrichment_id + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a BatchDetails 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, 'batch_id') and getattr(self, 'batch_id') is not None: + _dict['batch_id'] = getattr(self, 'batch_id') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'enrichment_id') and self.enrichment_id is not None: + _dict['enrichment_id'] = self.enrichment_id + 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 BatchDetails object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'BatchDetails') -> 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: 'BatchDetails') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ClassifierFederatedModel: """ An object with details for creating federated document classifier models. @@ -5217,9 +5525,6 @@ class CreateEnrichment: * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. * `webhook`: Connects to an external enrichment application by using a webhook. - The feature is available from IBM Cloud-managed instances only. The external - enrichment feature is beta functionality. Beta features are not supported by the - SDKs. * `sentence_classifier`: Use sentence classifier to classify sentences in your documents. This feature is available in IBM Cloud-managed instances only. The sentence classifier feature is beta functionality. Beta features are not @@ -5262,9 +5567,7 @@ def __init__( * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. * `webhook`: Connects to an external enrichment application by using a - webhook. The feature is available from IBM Cloud-managed instances only. - The external enrichment feature is beta functionality. Beta features are - not supported by the SDKs. + webhook. * `sentence_classifier`: Use sentence classifier to classify sentences in your documents. This feature is available in IBM Cloud-managed instances only. The sentence classifier feature is beta functionality. Beta features @@ -5353,9 +5656,6 @@ class TypeEnum(str, Enum): * `watson_knowledge_studio_model`: Creates an enrichment from a Watson Knowledge Studio machine learning model that is defined in a ZIP file. * `webhook`: Connects to an external enrichment application by using a webhook. - The feature is available from IBM Cloud-managed instances only. The external - enrichment feature is beta functionality. Beta features are not supported by the - SDKs. * `sentence_classifier`: Use sentence classifier to classify sentences in your documents. This feature is available in IBM Cloud-managed instances only. The sentence classifier feature is beta functionality. Beta features are not supported @@ -7560,6 +7860,73 @@ class TypeEnum(str, Enum): BINARY = 'binary' +class ListBatchesResponse: + """ + An object that contains a list of batches that are ready for enrichment by the + external application. + + :param List[BatchDetails] batches: (optional) An array that lists the batches in + a collection. + """ + + def __init__( + self, + *, + batches: Optional[List['BatchDetails']] = None, + ) -> None: + """ + Initialize a ListBatchesResponse object. + + :param List[BatchDetails] batches: (optional) An array that lists the + batches in a collection. + """ + self.batches = batches + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ListBatchesResponse': + """Initialize a ListBatchesResponse object from a json dictionary.""" + args = {} + if (batches := _dict.get('batches')) is not None: + args['batches'] = [BatchDetails.from_dict(v) for v in batches] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ListBatchesResponse 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, 'batches') and self.batches is not None: + batches_list = [] + for v in self.batches: + if isinstance(v, dict): + batches_list.append(v) + else: + batches_list.append(v.to_dict()) + _dict['batches'] = batches_list + 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 ListBatchesResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ListBatchesResponse') -> 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: 'ListBatchesResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ListCollectionsResponse: """ Response object that contains an array of collection details. @@ -12747,6 +13114,69 @@ def __ne__(self, other: 'WebhookHeader') -> bool: return not self == other +class PullBatchesResponse: + """ + A compressed newline delimited JSON (NDJSON) file containing the document. The NDJSON + format is used to describe structured data. The file name format is + `{batch_id}.ndjson.gz`. For more information, see [Binary attachment from the pull + batches + method](/docs/discovery-data?topic=discovery-data-external-enrichment#binary-attachment-pull-batches). + + :param str file: (optional) A compressed NDJSON file containing the document. + """ + + def __init__( + self, + *, + file: Optional[str] = None, + ) -> None: + """ + Initialize a PullBatchesResponse object. + + :param str file: (optional) A compressed NDJSON file containing the + document. + """ + self.file = file + + @classmethod + def from_dict(cls, _dict: Dict) -> 'PullBatchesResponse': + """Initialize a PullBatchesResponse object from a json dictionary.""" + args = {} + if (file := _dict.get('file')) is not None: + args['file'] = file + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a PullBatchesResponse 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, 'file') and self.file is not None: + _dict['file'] = self.file + 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 PullBatchesResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'PullBatchesResponse') -> 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: 'PullBatchesResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryAggregationQueryCalculationAggregation(QueryAggregation): """ Returns a scalar calculation across all documents for the field specified. Possible diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 4a8bf1691..0e172b946 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -4256,6 +4256,326 @@ def test_delete_enrichment_value_error_with_retries(self): # End of Service: Enrichments ############################################################################## +############################################################################## +# Start of Service: Batches +############################################################################## +# region + + +class TestListBatches: + """ + Test Class for list_batches + """ + + @responses.activate + def test_list_batches_all_params(self): + """ + list_batches() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches') + mock_response = '{"batches": [{"batch_id": "batch_id", "created": "2019-01-01T12:00:00.000Z", "enrichment_id": "enrichment_id"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Invoke method + response = _service.list_batches( + project_id, + collection_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_batches_all_params_with_retries(self): + # Enable retries and run test_list_batches_all_params. + _service.enable_retries() + self.test_list_batches_all_params() + + # Disable retries and run test_list_batches_all_params. + _service.disable_retries() + self.test_list_batches_all_params() + + @responses.activate + def test_list_batches_value_error(self): + """ + test_list_batches_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches') + mock_response = '{"batches": [{"batch_id": "batch_id", "created": "2019-01-01T12:00:00.000Z", "enrichment_id": "enrichment_id"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_batches(**req_copy) + + def test_list_batches_value_error_with_retries(self): + # Enable retries and run test_list_batches_value_error. + _service.enable_retries() + self.test_list_batches_value_error() + + # Disable retries and run test_list_batches_value_error. + _service.disable_retries() + self.test_list_batches_value_error() + + +class TestPullBatches: + """ + Test Class for pull_batches + """ + + @responses.activate + def test_pull_batches_all_params(self): + """ + pull_batches() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches/testString') + mock_response = '{"file": "file"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + batch_id = 'testString' + + # Invoke method + response = _service.pull_batches( + project_id, + collection_id, + batch_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_pull_batches_all_params_with_retries(self): + # Enable retries and run test_pull_batches_all_params. + _service.enable_retries() + self.test_pull_batches_all_params() + + # Disable retries and run test_pull_batches_all_params. + _service.disable_retries() + self.test_pull_batches_all_params() + + @responses.activate + def test_pull_batches_value_error(self): + """ + test_pull_batches_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches/testString') + mock_response = '{"file": "file"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + batch_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + "batch_id": batch_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.pull_batches(**req_copy) + + def test_pull_batches_value_error_with_retries(self): + # Enable retries and run test_pull_batches_value_error. + _service.enable_retries() + self.test_pull_batches_value_error() + + # Disable retries and run test_pull_batches_value_error. + _service.disable_retries() + self.test_pull_batches_value_error() + + +class TestPushBatches: + """ + Test Class for push_batches + """ + + @responses.activate + def test_push_batches_all_params(self): + """ + push_batches() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches/testString') + mock_response = 'false' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + batch_id = 'testString' + file = io.BytesIO(b'This is a mock file.').getvalue() + filename = 'testString' + + # Invoke method + response = _service.push_batches( + project_id, + collection_id, + batch_id, + file=file, + filename=filename, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_push_batches_all_params_with_retries(self): + # Enable retries and run test_push_batches_all_params. + _service.enable_retries() + self.test_push_batches_all_params() + + # Disable retries and run test_push_batches_all_params. + _service.disable_retries() + self.test_push_batches_all_params() + + @responses.activate + def test_push_batches_required_params(self): + """ + test_push_batches_required_params() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches/testString') + mock_response = 'false' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + batch_id = 'testString' + + # Invoke method + response = _service.push_batches( + project_id, + collection_id, + batch_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_push_batches_required_params_with_retries(self): + # Enable retries and run test_push_batches_required_params. + _service.enable_retries() + self.test_push_batches_required_params() + + # Disable retries and run test_push_batches_required_params. + _service.disable_retries() + self.test_push_batches_required_params() + + @responses.activate + def test_push_batches_value_error(self): + """ + test_push_batches_value_error() + """ + # Set up mock + url = preprocess_url('/v2/projects/testString/collections/testString/batches/testString') + mock_response = 'false' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Set up parameter values + project_id = 'testString' + collection_id = 'testString' + batch_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "project_id": project_id, + "collection_id": collection_id, + "batch_id": batch_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.push_batches(**req_copy) + + def test_push_batches_value_error_with_retries(self): + # Enable retries and run test_push_batches_value_error. + _service.enable_retries() + self.test_push_batches_value_error() + + # Disable retries and run test_push_batches_value_error. + _service.disable_retries() + self.test_push_batches_value_error() + + +# endregion +############################################################################## +# End of Service: Batches +############################################################################## + ############################################################################## # Start of Service: DocumentClassifiers ############################################################################## @@ -5653,6 +5973,36 @@ def test_analyzed_result_serialization(self): assert actual_dict == expected_dict +class TestModel_BatchDetails: + """ + Test Class for BatchDetails + """ + + def test_batch_details_serialization(self): + """ + Test serialization/deserialization for BatchDetails + """ + + # Construct a json representation of a BatchDetails model + batch_details_model_json = {} + batch_details_model_json['enrichment_id'] = 'testString' + + # Construct a model instance of BatchDetails by calling from_dict on the json representation + batch_details_model = BatchDetails.from_dict(batch_details_model_json) + assert batch_details_model != False + + # Construct a model instance of BatchDetails by calling from_dict on the json representation + batch_details_model_dict = BatchDetails.from_dict(batch_details_model_json).__dict__ + batch_details_model2 = BatchDetails(**batch_details_model_dict) + + # Verify the model instances are equivalent + assert batch_details_model == batch_details_model2 + + # Convert model instance back to dict and verify no loss of data + batch_details_model_json2 = batch_details_model.to_dict() + assert batch_details_model_json2 == batch_details_model_json + + class TestModel_ClassifierFederatedModel: """ Test Class for ClassifierFederatedModel @@ -7014,6 +7364,41 @@ def test_field_serialization(self): assert field_model_json2 == field_model_json +class TestModel_ListBatchesResponse: + """ + Test Class for ListBatchesResponse + """ + + def test_list_batches_response_serialization(self): + """ + Test serialization/deserialization for ListBatchesResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + batch_details_model = {} # BatchDetails + batch_details_model['enrichment_id'] = 'fd290d8b-53e2-dba1-0000-018a8d150b85' + + # Construct a json representation of a ListBatchesResponse model + list_batches_response_model_json = {} + list_batches_response_model_json['batches'] = [batch_details_model] + + # Construct a model instance of ListBatchesResponse by calling from_dict on the json representation + list_batches_response_model = ListBatchesResponse.from_dict(list_batches_response_model_json) + assert list_batches_response_model != False + + # Construct a model instance of ListBatchesResponse by calling from_dict on the json representation + list_batches_response_model_dict = ListBatchesResponse.from_dict(list_batches_response_model_json).__dict__ + list_batches_response_model2 = ListBatchesResponse(**list_batches_response_model_dict) + + # Verify the model instances are equivalent + assert list_batches_response_model == list_batches_response_model2 + + # Convert model instance back to dict and verify no loss of data + list_batches_response_model_json2 = list_batches_response_model.to_dict() + assert list_batches_response_model_json2 == list_batches_response_model_json + + class TestModel_ListCollectionsResponse: """ Test Class for ListCollectionsResponse @@ -9121,6 +9506,36 @@ def test_webhook_header_serialization(self): assert webhook_header_model_json2 == webhook_header_model_json +class TestModel_PullBatchesResponse: + """ + Test Class for PullBatchesResponse + """ + + def test_pull_batches_response_serialization(self): + """ + Test serialization/deserialization for PullBatchesResponse + """ + + # Construct a json representation of a PullBatchesResponse model + pull_batches_response_model_json = {} + pull_batches_response_model_json['file'] = 'testString' + + # Construct a model instance of PullBatchesResponse by calling from_dict on the json representation + pull_batches_response_model = PullBatchesResponse.from_dict(pull_batches_response_model_json) + assert pull_batches_response_model != False + + # Construct a model instance of PullBatchesResponse by calling from_dict on the json representation + pull_batches_response_model_dict = PullBatchesResponse.from_dict(pull_batches_response_model_json).__dict__ + pull_batches_response_model2 = PullBatchesResponse(**pull_batches_response_model_dict) + + # Verify the model instances are equivalent + assert pull_batches_response_model == pull_batches_response_model2 + + # Convert model instance back to dict and verify no loss of data + pull_batches_response_model_json2 = pull_batches_response_model.to_dict() + assert pull_batches_response_model_json2 == pull_batches_response_model_json + + class TestModel_QueryAggregationQueryCalculationAggregation: """ Test Class for QueryAggregationQueryCalculationAggregation From 6d838c4a10e5de84711a4cfd0e72e21f33cdcb64 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 22 Nov 2024 12:11:57 -0500 Subject: [PATCH 434/455] chore: update services to version 3.97.0 of sdk generator --- ibm_watson/assistant_v1.py | 431 ++++++++++++------ ibm_watson/discovery_v2.py | 145 ++++-- .../natural_language_understanding_v1.py | 2 +- ibm_watson/speech_to_text_v1.py | 2 +- ibm_watson/text_to_speech_v1.py | 2 +- .../test_natural_language_understanding_v1.py | 19 +- test/unit/test_assistant_v1.py | 23 +- test/unit/test_discovery_v2.py | 15 +- .../test_natural_language_understanding_v1.py | 11 +- test/unit/test_speech_to_text_v1.py | 11 +- test/unit/test_text_to_speech_v1.py | 11 +- 11 files changed, 416 insertions(+), 256 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index b98b688bb..7528355d4 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -4820,6 +4820,8 @@ class Context: :param dict system: (optional) For internal use only. :param MessageContextMetadata metadata: (optional) Metadata related to the message. + + This type supports additional properties of type object. Any context variable. """ # The set of defined properties for the class @@ -4831,7 +4833,7 @@ def __init__( conversation_id: Optional[str] = None, system: Optional[dict] = None, metadata: Optional['MessageContextMetadata'] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a Context object. @@ -4843,13 +4845,22 @@ def __init__( :param dict system: (optional) For internal use only. :param MessageContextMetadata metadata: (optional) Metadata related to the message. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any context variable. """ self.conversation_id = conversation_id self.system = system self.metadata = metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in Context._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'Context': @@ -4861,8 +4872,13 @@ def from_dict(cls, _dict: Dict) -> 'Context': args['system'] = system if (metadata := _dict.get('metadata')) is not None: args['metadata'] = MessageContextMetadata.from_dict(metadata) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -4883,10 +4899,10 @@ def to_dict(self) -> Dict: _dict['metadata'] = self.metadata else: _dict['metadata'] = self.metadata.to_dict() - for _key in [ - k for k in vars(self).keys() if k not in Context._properties + for k in [ + _k for _k in vars(self).keys() if _k not in Context._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -4894,25 +4910,31 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of Context""" + """Return the additional properties from this instance of Context in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in Context._properties + for k in [ + _k for _k in vars(self).keys() if _k not in Context._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of Context""" - for _key in [ - k for k in vars(self).keys() if k not in Context._properties + """Set a dictionary of additional properties in this instance of Context""" + for k in [ + _k for _k in vars(self).keys() if _k not in Context._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in Context._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in Context._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this Context object.""" @@ -6050,6 +6072,8 @@ class DialogNodeContext: :param dict integrations: (optional) Context data intended for specific integrations. + + This type supports additional properties of type object. Any context variable. """ # The set of defined properties for the class @@ -6059,18 +6083,27 @@ def __init__( self, *, integrations: Optional[dict] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a DialogNodeContext object. :param dict integrations: (optional) Context data intended for specific integrations. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any context variable. """ self.integrations = integrations - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in DialogNodeContext._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'DialogNodeContext': @@ -6078,8 +6111,13 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeContext': args = {} if (integrations := _dict.get('integrations')) is not None: args['integrations'] = integrations - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -6092,11 +6130,11 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'integrations') and self.integrations is not None: _dict['integrations'] = self.integrations - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeContext._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeContext._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -6104,27 +6142,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of DialogNodeContext""" + """Return the additional properties from this instance of DialogNodeContext in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeContext._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeContext._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of DialogNodeContext""" - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeContext._properties + """Set a dictionary of additional properties in this instance of DialogNodeContext""" + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeContext._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in DialogNodeContext._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in DialogNodeContext._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this DialogNodeContext object.""" @@ -6317,6 +6361,9 @@ class DialogNodeOutput: [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-responses-json). :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. + + This type supports additional properties of type object. Any additional data included + in the dialog node output. """ # The set of defined properties for the class @@ -6328,7 +6375,7 @@ def __init__( generic: Optional[List['DialogNodeOutputGeneric']] = None, integrations: Optional[dict] = None, modifiers: Optional['DialogNodeOutputModifiers'] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a DialogNodeOutput object. @@ -6340,13 +6387,23 @@ def __init__( [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-responses-json). :param DialogNodeOutputModifiers modifiers: (optional) Options that modify how specified output is handled. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any additional data included in the + dialog node output. """ self.generic = generic self.integrations = integrations self.modifiers = modifiers - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in DialogNodeOutput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': @@ -6360,8 +6417,13 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutput': args['integrations'] = integrations if (modifiers := _dict.get('modifiers')) is not None: args['modifiers'] = DialogNodeOutputModifiers.from_dict(modifiers) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -6387,11 +6449,11 @@ def to_dict(self) -> Dict: _dict['modifiers'] = self.modifiers else: _dict['modifiers'] = self.modifiers.to_dict() - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeOutput._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeOutput._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -6399,27 +6461,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of DialogNodeOutput""" + """Return the additional properties from this instance of DialogNodeOutput in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeOutput._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeOutput._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of DialogNodeOutput""" - for _key in [ - k for k in vars(self).keys() - if k not in DialogNodeOutput._properties + """Set a dictionary of additional properties in this instance of DialogNodeOutput""" + for k in [ + _k for _k in vars(self).keys() + if _k not in DialogNodeOutput._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in DialogNodeOutput._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in DialogNodeOutput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this DialogNodeOutput object.""" @@ -8635,6 +8703,9 @@ class MessageInput: autocorrection is disabled. :param str original_text: (optional) The original user input text. This property is returned only if autocorrection is enabled and the user input was corrected. + + This type supports additional properties of type object. Any additional data included + with the message input. """ # The set of defined properties for the class @@ -8651,7 +8722,7 @@ def __init__( spelling_auto_correct: Optional[bool] = None, suggested_text: Optional[str] = None, original_text: Optional[str] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a MessageInput object. @@ -8669,15 +8740,25 @@ def __init__( the original text is returned in the **original_text** property of the message response. This property overrides the value of the **spelling_auto_correct** property in the workspace settings. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any additional data included with the + message input. """ self.text = text self.spelling_suggestions = spelling_suggestions self.spelling_auto_correct = spelling_auto_correct self.suggested_text = suggested_text self.original_text = original_text - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in MessageInput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'MessageInput': @@ -8695,8 +8776,13 @@ def from_dict(cls, _dict: Dict) -> 'MessageInput': args['suggested_text'] = suggested_text if (original_text := _dict.get('original_text')) is not None: args['original_text'] = original_text - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -8721,11 +8807,11 @@ def to_dict(self) -> Dict: if hasattr(self, 'original_text') and getattr( self, 'original_text') is not None: _dict['original_text'] = getattr(self, 'original_text') - for _key in [ - k for k in vars(self).keys() - if k not in MessageInput._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageInput._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -8733,27 +8819,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of MessageInput""" + """Return the additional properties from this instance of MessageInput in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in MessageInput._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageInput._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of MessageInput""" - for _key in [ - k for k in vars(self).keys() - if k not in MessageInput._properties + """Set a dictionary of additional properties in this instance of MessageInput""" + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageInput._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in MessageInput._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in MessageInput._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this MessageInput object.""" @@ -9162,6 +9254,9 @@ class OutputData: :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. + + This type supports additional properties of type object. Any additional data included + with the output. """ # The set of defined properties for the class @@ -9176,7 +9271,7 @@ def __init__( nodes_visited_details: Optional[ List['DialogNodeVisitedDetails']] = None, generic: Optional[List['RuntimeResponseGeneric']] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a OutputData object. @@ -9194,14 +9289,24 @@ def __init__( :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) Any additional data included with the + output. """ self.nodes_visited = nodes_visited self.nodes_visited_details = nodes_visited_details self.log_messages = log_messages self.generic = generic - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in OutputData._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'OutputData': @@ -9227,8 +9332,13 @@ def from_dict(cls, _dict: Dict) -> 'OutputData': args['generic'] = [ RuntimeResponseGeneric.from_dict(v) for v in generic ] - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -9266,10 +9376,11 @@ def to_dict(self) -> Dict: else: generic_list.append(v.to_dict()) _dict['generic'] = generic_list - for _key in [ - k for k in vars(self).keys() if k not in OutputData._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in OutputData._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -9277,25 +9388,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of OutputData""" + """Return the additional properties from this instance of OutputData in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in OutputData._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in OutputData._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of OutputData""" - for _key in [ - k for k in vars(self).keys() if k not in OutputData._properties + """Set a dictionary of additional properties in this instance of OutputData""" + for k in [ + _k for _k in vars(self).keys() + if _k not in OutputData._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in OutputData._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in OutputData._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this OutputData object.""" @@ -11446,6 +11565,8 @@ class WorkspaceSystemSettings: related to detection of irrelevant input. :param WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings related to the version of the training algorithms currently used by the skill. + + This type supports additional properties of type object. For internal use only. """ # The set of defined properties for the class @@ -11468,7 +11589,7 @@ def __init__( 'WorkspaceSystemSettingsSystemEntities'] = None, off_topic: Optional['WorkspaceSystemSettingsOffTopic'] = None, nlp: Optional['WorkspaceSystemSettingsNlp'] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a WorkspaceSystemSettings object. @@ -11494,7 +11615,7 @@ def __init__( :param WorkspaceSystemSettingsNlp nlp: (optional) Workspace settings related to the version of the training algorithms currently used by the skill. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) For internal use only. """ self.tooling = tooling self.disambiguation = disambiguation @@ -11504,8 +11625,17 @@ def __init__( self.system_entities = system_entities self.off_topic = off_topic self.nlp = nlp - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in WorkspaceSystemSettings._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': @@ -11534,8 +11664,13 @@ def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': off_topic) if (nlp := _dict.get('nlp')) is not None: args['nlp'] = WorkspaceSystemSettingsNlp.from_dict(nlp) - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -11582,11 +11717,11 @@ def to_dict(self) -> Dict: _dict['nlp'] = self.nlp else: _dict['nlp'] = self.nlp.to_dict() - for _key in [ - k for k in vars(self).keys() - if k not in WorkspaceSystemSettings._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in WorkspaceSystemSettings._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -11594,27 +11729,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of WorkspaceSystemSettings""" + """Return the additional properties from this instance of WorkspaceSystemSettings in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in WorkspaceSystemSettings._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in WorkspaceSystemSettings._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of WorkspaceSystemSettings""" - for _key in [ - k for k in vars(self).keys() - if k not in WorkspaceSystemSettings._properties + """Set a dictionary of additional properties in this instance of WorkspaceSystemSettings""" + for k in [ + _k for _k in vars(self).keys() + if _k not in WorkspaceSystemSettings._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in WorkspaceSystemSettings._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in WorkspaceSystemSettings._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this WorkspaceSystemSettings object.""" diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index e5c0fbe71..f9a994904 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ IBM Watson® Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive better @@ -4112,6 +4112,9 @@ class AnalyzedResult: Result of the document analysis. :param dict metadata: (optional) Metadata that was specified with the request. + + This type supports additional properties of type object. The remaining key-value + pairs. """ # The set of defined properties for the class @@ -4121,18 +4124,27 @@ def __init__( self, *, metadata: Optional[dict] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a AnalyzedResult object. :param dict metadata: (optional) Metadata that was specified with the request. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) The remaining key-value pairs. """ self.metadata = metadata - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in AnalyzedResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': @@ -4140,8 +4152,13 @@ def from_dict(cls, _dict: Dict) -> 'AnalyzedResult': args = {} if (metadata := _dict.get('metadata')) is not None: args['metadata'] = metadata - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -4154,11 +4171,11 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'metadata') and self.metadata is not None: _dict['metadata'] = self.metadata - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in AnalyzedResult._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -4166,27 +4183,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of AnalyzedResult""" + """Return the additional properties from this instance of AnalyzedResult in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in AnalyzedResult._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of AnalyzedResult""" - for _key in [ - k for k in vars(self).keys() - if k not in AnalyzedResult._properties + """Set a dictionary of additional properties in this instance of AnalyzedResult""" + for k in [ + _k for _k in vars(self).keys() + if _k not in AnalyzedResult._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in AnalyzedResult._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in AnalyzedResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this AnalyzedResult object.""" @@ -10266,6 +10289,9 @@ class QueryResult: :param List[QueryResultPassage] document_passages: (optional) Passages from the document that best matches the query. Returned if **passages.per_document** is `true`. + + This type supports additional properties of type object. The remaining key-value + pairs. """ # The set of defined properties for the class @@ -10279,7 +10305,7 @@ def __init__( *, metadata: Optional[dict] = None, document_passages: Optional[List['QueryResultPassage']] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a QueryResult object. @@ -10290,14 +10316,23 @@ def __init__( :param List[QueryResultPassage] document_passages: (optional) Passages from the document that best matches the query. Returned if **passages.per_document** is `true`. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) The remaining key-value pairs. """ self.document_id = document_id self.metadata = metadata self.result_metadata = result_metadata self.document_passages = document_passages - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in QueryResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'QueryResult': @@ -10322,8 +10357,13 @@ def from_dict(cls, _dict: Dict) -> 'QueryResult': args['document_passages'] = [ QueryResultPassage.from_dict(v) for v in document_passages ] - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -10353,10 +10393,11 @@ def to_dict(self) -> Dict: else: document_passages_list.append(v.to_dict()) _dict['document_passages'] = document_passages_list - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in QueryResult._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -10364,25 +10405,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of QueryResult""" + """Return the additional properties from this instance of QueryResult in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in QueryResult._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of QueryResult""" - for _key in [ - k for k in vars(self).keys() if k not in QueryResult._properties + """Set a dictionary of additional properties in this instance of QueryResult""" + for k in [ + _k for _k in vars(self).keys() + if _k not in QueryResult._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in QueryResult._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in QueryResult._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this QueryResult object.""" diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index d56cb3647..c3561e275 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index b0831533f..459564a85 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's speech-recognition capabilities to produce transcripts of spoken audio. The service can diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 23fe1b487..145fdcae3 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, diff --git a/test/integration/test_natural_language_understanding_v1.py b/test/integration/test_natural_language_understanding_v1.py index faedb7593..1255b5067 100644 --- a/test/integration/test_natural_language_understanding_v1.py +++ b/test/integration/test_natural_language_understanding_v1.py @@ -6,17 +6,22 @@ import json import time from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -@pytest.mark.skipif(os.getenv('NATURAL_LANGUAGE_UNDERSTANDING_APIKEY') is None, - reason='requires NATURAL_LANGUAGE_UNDERSTANDING_APIKEY') class TestNaturalLanguageUnderstandingV1(TestCase): def setUp(self): - self.natural_language_understanding = ibm_watson.NaturalLanguageUnderstandingV1(version='2018-03-16') - self.natural_language_understanding.set_default_headers({ - 'X-Watson-Learning-Opt-Out': '1', - 'X-Watson-Test': '1' - }) + + with open('./auth.json') as f: + data = json.load(f) + nlu_auth = data.get("nlu") + + self.authenticator = IAMAuthenticator(nlu_auth.get("apikey")) + self.natural_language_understanding = ibm_watson.NaturalLanguageUnderstandingV1(version='2018-03-16', authenticator=self.authenticator) + self.natural_language_understanding.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) def test_analyze(self): response = self.natural_language_understanding.analyze( diff --git a/test/unit/test_assistant_v1.py b/test/unit/test_assistant_v1.py index 5b307c5e9..82781955f 100644 --- a/test/unit/test_assistant_v1.py +++ b/test/unit/test_assistant_v1.py @@ -47,20 +47,13 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') @@ -8539,7 +8532,7 @@ def test_context_serialization(self): expected_dict = {'foo': 'testString'} context_model.set_properties(expected_dict) actual_dict = context_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_Counterexample: @@ -8995,7 +8988,7 @@ def test_dialog_node_context_serialization(self): expected_dict = {'foo': 'testString'} dialog_node_context_model.set_properties(expected_dict) actual_dict = dialog_node_context_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_DialogNodeNextStep: @@ -9088,7 +9081,7 @@ def test_dialog_node_output_serialization(self): expected_dict = {'foo': 'testString'} dialog_node_output_model.set_properties(expected_dict) actual_dict = dialog_node_output_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_DialogNodeOutputConnectToAgentTransferInfo: @@ -10476,7 +10469,7 @@ def test_message_input_serialization(self): expected_dict = {'foo': 'testString'} message_input_model.set_properties(expected_dict) actual_dict = message_input_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_MessageRequest: @@ -10819,7 +10812,7 @@ def test_output_data_serialization(self): expected_dict = {'foo': 'testString'} output_data_model.set_properties(expected_dict) actual_dict = output_data_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_Pagination: @@ -11823,7 +11816,7 @@ def test_workspace_system_settings_serialization(self): expected_dict = {'foo': 'testString'} workspace_system_settings_model.set_properties(expected_dict) actual_dict = workspace_system_settings_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_WorkspaceSystemSettingsDisambiguation: diff --git a/test/unit/test_discovery_v2.py b/test/unit/test_discovery_v2.py index 0e172b946..10401163d 100644 --- a/test/unit/test_discovery_v2.py +++ b/test/unit/test_discovery_v2.py @@ -49,20 +49,13 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') @@ -5970,7 +5963,7 @@ def test_analyzed_result_serialization(self): expected_dict = {'foo': 'testString'} analyzed_result_model.set_properties(expected_dict) actual_dict = analyzed_result_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_BatchDetails: @@ -8365,7 +8358,7 @@ def test_query_result_serialization(self): expected_dict = {'foo': 'testString'} query_result_model.set_properties(expected_dict) actual_dict = query_result_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_QueryResultMetadata: diff --git a/test/unit/test_natural_language_understanding_v1.py b/test/unit/test_natural_language_understanding_v1.py index 86e529fc1..40ca030a6 100644 --- a/test/unit/test_natural_language_understanding_v1.py +++ b/test/unit/test_natural_language_understanding_v1.py @@ -49,20 +49,13 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 781732ccf..658ae8999 100644 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -45,20 +45,13 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') diff --git a/test/unit/test_text_to_speech_v1.py b/test/unit/test_text_to_speech_v1.py index 26341c541..e151e4503 100644 --- a/test/unit/test_text_to_speech_v1.py +++ b/test/unit/test_text_to_speech_v1.py @@ -45,20 +45,13 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') From 3fe62430c57e660b0903b0988fa3c53c489012d3 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 22 Nov 2024 12:24:15 -0500 Subject: [PATCH 435/455] feat(WxA): add new functions and update required params BREAKING CHANGE: `environmentId` now required for `message` and `messageStateless` functions Add support for message streaming and new APIs New functions: createProviders, listProviders, updateProviders, createReleaseExport, downloadReleaseExport, createReleaseImport, getReleaseImportStatus , messageStream, messageStreamStateless --- ibm_watson/assistant_v2.py | 13147 +++++++++++++++++++++---------- test/unit/test_assistant_v2.py | 9822 ++++++++++++++++------- 2 files changed, 15709 insertions(+), 7260 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 764f567fa..31ff57d20 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.85.0-75c38f8f-20240206-210220 +# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 """ The IBM® watsonx™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -29,7 +29,7 @@ from datetime import datetime from enum import Enum -from typing import Dict, List, Optional +from typing import BinaryIO, Dict, List, Optional import json import sys @@ -78,6 +78,214 @@ def __init__( self.version = version self.configure_service(service_name) + ######################### + # Conversational skill providers + ######################### + + def create_provider( + self, + provider_id: str, + specification: 'ProviderSpecification', + private: 'ProviderPrivate', + **kwargs, + ) -> DetailedResponse: + """ + Create a conversational skill provider. + + Create a new conversational skill provider. + + :param str provider_id: The unique identifier of the provider. + :param ProviderSpecification specification: The specification of the + provider. + :param ProviderPrivate private: Private information of the provider. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ProviderResponse` object + """ + + if provider_id is None: + raise ValueError('provider_id must be provided') + if specification is None: + raise ValueError('specification must be provided') + if private is None: + raise ValueError('private must be provided') + specification = convert_model(specification) + private = convert_model(private) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='create_provider', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'provider_id': provider_id, + 'specification': specification, + 'private': private, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/providers' + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + def list_providers( + self, + *, + page_limit: Optional[int] = None, + include_count: Optional[bool] = None, + sort: Optional[str] = None, + cursor: Optional[str] = None, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: + """ + List conversational skill providers. + + List the conversational skill providers associated with a Watson Assistant service + instance. + + :param int page_limit: (optional) The number of records to return in each + page of results. + :param bool include_count: (optional) Whether to include information about + the number of records that satisfy the request, regardless of the page + limit. If this parameter is `true`, the `pagination` object in the response + includes the `total` property. + :param str sort: (optional) The attribute by which returned conversational + skill providers will be sorted. To reverse the sort order, prefix the value + with a minus sign (`-`). + :param str cursor: (optional) A token identifying the page of results to + retrieve. + :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 with `dict` result representing a `ProviderCollection` object + """ + + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='list_providers', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'page_limit': page_limit, + 'include_count': include_count, + 'sort': sort, + 'cursor': cursor, + 'include_audit': include_audit, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v2/providers' + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + def update_provider( + self, + provider_id: str, + specification: 'ProviderSpecification', + private: 'ProviderPrivate', + **kwargs, + ) -> DetailedResponse: + """ + Update a conversational skill provider. + + Update a new conversational skill provider. + + :param str provider_id: Unique identifier of the conversational skill + provider. + :param ProviderSpecification specification: The specification of the + provider. + :param ProviderPrivate private: Private information of the provider. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `ProviderResponse` object + """ + + if not provider_id: + raise ValueError('provider_id must be provided') + if specification is None: + raise ValueError('specification must be provided') + if private is None: + raise ValueError('private must be provided') + specification = convert_model(specification) + private = convert_model(private) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_provider', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'specification': specification, + 'private': private, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['provider_id'] + path_param_values = self.encode_path_vars(provider_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/providers/{provider_id}'.format(**path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + ######################### # Assistants ######################### @@ -426,6 +634,7 @@ def delete_session( def message( self, assistant_id: str, + environment_id: str, session_id: str, *, input: Optional['MessageInput'] = None, @@ -452,6 +661,10 @@ def message( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. :param str session_id: Unique identifier of the session. :param MessageInput input: (optional) An input object that includes the input text. @@ -478,6 +691,8 @@ def message( if not assistant_id: raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') if not session_id: raise ValueError('session_id must be provided') if input is not None: @@ -510,8 +725,9 @@ def message( del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id', 'session_id'] - path_param_values = self.encode_path_vars(assistant_id, session_id) + path_param_keys = ['assistant_id', 'environment_id', 'session_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id, + session_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/sessions/{session_id}/message'.format( **path_param_dict) @@ -529,6 +745,7 @@ def message( def message_stateless( self, assistant_id: str, + environment_id: str, *, input: Optional['StatelessMessageInput'] = None, context: Optional['StatelessMessageContext'] = None, @@ -553,6 +770,10 @@ def message_stateless( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. :param StatelessMessageInput input: (optional) An input object that includes the input text. :param StatelessMessageContext context: (optional) Context data for the @@ -579,6 +800,8 @@ def message_stateless( if not assistant_id: raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') if input is not None: input = convert_model(input) if context is not None: @@ -609,8 +832,8 @@ def message_stateless( del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id'] - path_param_values = self.encode_path_vars(assistant_id) + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) url = '/v2/assistants/{assistant_id}/message'.format(**path_param_dict) request = self.prepare_request( @@ -625,44 +848,82 @@ def message_stateless( return response ######################### - # Bulk classify + # Message Stream ######################### - def bulk_classify( + def message_stream( self, - skill_id: str, - input: List['BulkClassifyUtterance'], + assistant_id: str, + environment_id: str, + session_id: str, + *, + input: Optional['MessageInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, **kwargs, ) -> DetailedResponse: """ - Identify intents and entities in multiple user utterances. + Send user input to assistant (stateful). - Send multiple user inputs to a dialog skill in a single request and receive - information about the intents and entities recognized in each input. This method - is useful for testing and comparing the performance of different skills or skill - versions. - This method is available only with Enterprise with Data Isolation plans. + Send user input to an assistant and receive a streamed response, with conversation + state (including context data) stored by watsonx Assistant for the duration of the + session. - :param str skill_id: Unique identifier of the skill. To find the skill ID - in the watsonx Assistant user interface, open the skill settings and click - **API Details**. - :param List[BulkClassifyUtterance] input: An array of input utterances to - classify. + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param str session_id: Unique identifier of the session. + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object + :rtype: DetailedResponse with `BinaryIO` result """ - if not skill_id: - raise ValueError('skill_id must be provided') - if input is None: - raise ValueError('input must be provided') - input = [convert_model(x) for x in input] + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + if not session_id: + raise ValueError('session_id must be provided') + if input is not None: + input = convert_model(input) + if context is not None: + context = convert_model(context) headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='bulk_classify', + operation_id='message_stream', ) headers.update(sdk_headers) @@ -672,6 +933,8 @@ def bulk_classify( data = { 'input': input, + 'context': context, + 'user_id': user_id, } data = {k: v for (k, v) in data.items() if v is not None} data = json.dumps(data) @@ -680,12 +943,13 @@ def bulk_classify( if 'headers' in kwargs: headers.update(kwargs.get('headers')) del kwargs['headers'] - headers['Accept'] = 'application/json' + headers['Accept'] = 'text/event-stream' - path_param_keys = ['skill_id'] - path_param_values = self.encode_path_vars(skill_id) + path_param_keys = ['assistant_id', 'environment_id', 'session_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id, + session_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/skills/{skill_id}/workspace/bulk_classify'.format( + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/sessions/{session_id}/message_stream'.format( **path_param_dict) request = self.prepare_request( method='POST', @@ -698,15 +962,194 @@ def bulk_classify( response = self.send(request, **kwargs) return response - ######################### - # Logs - ######################### - - def list_logs( + def message_stream_stateless( self, assistant_id: str, + environment_id: str, *, - sort: Optional[str] = None, + input: Optional['MessageInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Send user input to assistant (stateless). + + Send user input to an assistant and receive a response, with conversation state + (including context data) managed by your application. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. + :param MessageInput input: (optional) An input object that includes the + input text. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `BinaryIO` result + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') + if input is not None: + input = convert_model(input) + if context is not None: + context = convert_model(context) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='message_stream_stateless', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'input': input, + 'context': context, + 'user_id': user_id, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'text/event-stream' + + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/message_stream'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Bulk classify + ######################### + + def bulk_classify( + self, + skill_id: str, + input: List['BulkClassifyUtterance'], + **kwargs, + ) -> DetailedResponse: + """ + Identify intents and entities in multiple user utterances. + + Send multiple user inputs to a dialog skill in a single request and receive + information about the intents and entities recognized in each input. This method + is useful for testing and comparing the performance of different skills or skill + versions. + This method is available only with Enterprise with Data Isolation plans. + + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the watsonx Assistant user interface, open the skill settings and click + **API Details**. + :param List[BulkClassifyUtterance] input: An array of input utterances to + classify. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `BulkClassifyResponse` object + """ + + if not skill_id: + raise ValueError('skill_id must be provided') + if input is None: + raise ValueError('input must be provided') + input = [convert_model(x) for x in input] + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='bulk_classify', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + data = { + 'input': input, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['skill_id'] + path_param_values = self.encode_path_vars(skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/skills/{skill_id}/workspace/bulk_classify'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + + ######################### + # Logs + ######################### + + def list_logs( + self, + assistant_id: str, + *, + sort: Optional[str] = None, filter: Optional[str] = None, page_limit: Optional[int] = None, cursor: Optional[str] = None, @@ -1020,7 +1463,7 @@ def update_environment( *, name: Optional[str] = None, description: Optional[str] = None, - orchestration: Optional['BaseEnvironmentOrchestration'] = None, + orchestration: Optional['UpdateEnvironmentOrchestration'] = None, session_timeout: Optional[int] = None, skill_references: Optional[List['EnvironmentSkill']] = None, **kwargs, @@ -1050,7 +1493,7 @@ def update_environment( API does not support creating environments. :param str name: (optional) The name of the environment. :param str description: (optional) The description of the environment. - :param BaseEnvironmentOrchestration orchestration: (optional) The search + :param UpdateEnvironmentOrchestration orchestration: (optional) The search skill orchestration settings for the environment. :param int session_timeout: (optional) The session inactivity timeout setting for the environment (in seconds). @@ -1500,20 +1943,25 @@ def deploy_release( response = self.send(request, **kwargs) return response - ######################### - # Skills - ######################### - - def get_skill( + def create_release_export( self, assistant_id: str, - skill_id: str, + release: str, + *, + include_audit: Optional[bool] = None, **kwargs, ) -> DetailedResponse: """ - Get skill. + Create release export. - Get information about a skill. + Initiate an asynchronous process which will create a downloadable Zip file + artifact (/package) for an assistant release. This artifact will contain Action + and/or Dialog skills that are part of the release. The Dialog skill will only be + included in the event that coexistence is enabled on the assistant. The expected + workflow with the use of Release Export endpoint is to first initiate the creation + of the artifact with the POST endpoint and then poll the GET endpoint to retrieve + the artifact. Once the artifact has been created, it will last for the duration + (/scope) of the release. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1527,28 +1975,29 @@ def get_skill( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. - :param str skill_id: Unique identifier of the skill. To find the skill ID - in the watsonx Assistant user interface, open the skill settings and click - **API Details**. + :param str release: Unique identifier of the release. + :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 with `dict` result representing a `Skill` object + :rtype: DetailedResponse with `dict` result representing a `CreateReleaseExportWithStatusErrors` object """ if not assistant_id: raise ValueError('assistant_id must be provided') - if not skill_id: - raise ValueError('skill_id must be provided') + if not release: + raise ValueError('release must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='get_skill', + operation_id='create_release_export', ) headers.update(sdk_headers) params = { 'version': self.version, + 'include_audit': include_audit, } if 'headers' in kwargs: @@ -1556,13 +2005,13 @@ def get_skill( del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id', 'skill_id'] - path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + url = '/v2/assistants/{assistant_id}/releases/{release}/export'.format( **path_param_dict) request = self.prepare_request( - method='GET', + method='POST', url=url, headers=headers, params=params, @@ -1571,25 +2020,33 @@ def get_skill( response = self.send(request, **kwargs) return response - def update_skill( + def download_release_export( self, assistant_id: str, - skill_id: str, + release: str, *, - name: Optional[str] = None, - description: Optional[str] = None, - workspace: Optional[dict] = None, - dialog_settings: Optional[dict] = None, - search_settings: Optional['SearchSettings'] = None, + accept: Optional[str] = None, + include_audit: Optional[bool] = None, **kwargs, ) -> DetailedResponse: """ - Update skill. - - Update a skill with new or modified data. - **Note:** The update is performed asynchronously; you can see the status of the - update by calling the **Get skill** method and checking the value of the - **status** property. + Get release export. + + A dual function endpoint to either retrieve the Zip file artifact that is + associated with an assistant release or, retrieve the status of the artifact's + creation. It is assumed that the artifact creation was already initiated prior to + calling this endpoint. In the event that the artifact is not yet created and ready + for download, this endpoint can be used to poll the system until the creation is + completed or has failed. On the other hand, if the artifact is created, this + endpoint will return the Zip file artifact as an octet stream. Once the artifact + has been created, it will last for the duration (/scope) of the release.

When you will have downloaded the Zip file artifact, you have one of three ways + to import it into an assistant's draft environment. These are as follows.
  1. Import the zip package in Tooling via "Assistant Settings" -> + "Download/Upload files" -> "Upload" -> "Assistant only".
  2. Import the + zip package via "Create release import" endpoint using the APIs.
  3. Extract + the contents of the Zip file artifact and individually import the skill JSONs via + skill update endpoints.
. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1603,98 +2060,82 @@ def update_skill( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. - :param str skill_id: Unique identifier of the skill. To find the skill ID - in the watsonx Assistant user interface, open the skill settings and click - **API Details**. - :param str name: (optional) The name of the skill. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This - string cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param dict dialog_settings: (optional) For internal use only. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, - and are not included in **Export skills** responses. + :param str release: Unique identifier of the release. + :param str accept: (optional) The type of the response: application/json or + application/octet-stream. + :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 with `dict` result representing a `Skill` object + :rtype: DetailedResponse with `dict` result representing a `CreateReleaseExportWithStatusErrors` object """ if not assistant_id: raise ValueError('assistant_id must be provided') - if not skill_id: - raise ValueError('skill_id must be provided') - if search_settings is not None: - search_settings = convert_model(search_settings) - headers = {} + if not release: + raise ValueError('release must be provided') + headers = { + 'Accept': accept, + } sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='update_skill', + operation_id='download_release_export', ) headers.update(sdk_headers) params = { 'version': self.version, + 'include_audit': include_audit, } - data = { - 'name': name, - 'description': description, - 'workspace': workspace, - 'dialog_settings': dialog_settings, - 'search_settings': search_settings, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - if 'headers' in kwargs: headers.update(kwargs.get('headers')) del kwargs['headers'] - headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id', 'skill_id'] - path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_keys = ['assistant_id', 'release'] + path_param_values = self.encode_path_vars(assistant_id, release) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + url = '/v2/assistants/{assistant_id}/releases/{release}/export'.format( **path_param_dict) request = self.prepare_request( - method='POST', + method='GET', url=url, headers=headers, params=params, - data=data, ) response = self.send(request, **kwargs) return response - def export_skills( + def create_release_import( self, assistant_id: str, + body: BinaryIO, *, include_audit: Optional[bool] = None, **kwargs, ) -> DetailedResponse: """ - Export skills. - - Asynchronously export the action skill and dialog skill (if enabled) for the - assistant. Use this method to save all skill data so that you can import it to a - different assistant using the **Import skills** method. - A successful call to this method only initiates an asynchronous export. The - exported JSON data is not available until processing completes. - After the initial request is submitted, you can poll the status of the operation - by calling the same request again and checking the value of the **status** - property. If an error occurs (indicated by a **status** value of `Failed`), the - `status_description` property provides more information about the error, and the - `status_errors` property contains an array of error messages that caused the - failure. - When processing has completed, the request returns the exported JSON data. - Remember that the usual rate limits apply. + Create release import. + + Import a previously exported assistant release Zip file artifact (/package) into + an assistant. This endpoint creates (/initiates) an asynchronous task (/job) in + the background which will import the artifact contents into the draft environment + of the assistant on which this endpoint is called. Specifically, the asynchronous + operation will override the action and/or dialog skills in the assistant. It will + be worth noting that when the artifact that is provided to this endpoint is from + an assistant release which has coexistence enabled (i.e., it has both action and + dialog skills), the import process will automatically enable coexistence, if not + already enabled, on the assistant into which said artifact is being uploaded to. + On the other hand, if the artifact package being imported only has action skill in + it, the import asynchronous process will only override the draft environment's + action skill, regardless of whether coexistence is enabled on the assistant into + which the package is being imported. Lastly, the system will only run one + asynchronous import at a time on an assistant. As such, consecutive imports will + override previous import's updates to the skills in the draft environment. Once + created, you may poll the completion of the import via the "Get release import + Status" endpoint. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1708,20 +2149,24 @@ def export_skills( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. + :param BinaryIO body: Request body is an Octet-stream of the artifact Zip + file that is being imported. :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 with `dict` result representing a `SkillsExport` object + :rtype: DetailedResponse with `dict` result representing a `CreateAssistantReleaseImportResponse` object """ if not assistant_id: raise ValueError('assistant_id must be provided') + if body is None: + raise ValueError('body must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='export_skills', + operation_id='create_release_import', ) headers.update(sdk_headers) @@ -1730,6 +2175,9 @@ def export_skills( 'include_audit': include_audit, } + data = body + headers['content-type'] = 'application/octet-stream' + if 'headers' in kwargs: headers.update(kwargs.get('headers')) del kwargs['headers'] @@ -1738,39 +2186,30 @@ def export_skills( path_param_keys = ['assistant_id'] path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/skills_export'.format( - **path_param_dict) + url = '/v2/assistants/{assistant_id}/import'.format(**path_param_dict) request = self.prepare_request( - method='GET', + method='POST', url=url, headers=headers, params=params, + data=data, ) response = self.send(request, **kwargs) return response - def import_skills( + def get_release_import_status( self, assistant_id: str, - assistant_skills: List['SkillImport'], - assistant_state: 'AssistantState', *, include_audit: Optional[bool] = None, **kwargs, ) -> DetailedResponse: """ - Import skills. + Get release import Status. - Asynchronously import skills into an existing assistant from a previously exported - file. - The request body for this method should contain the response data that was - received from a previous call to the **Export skills** method, without - modification. - A successful call to this method initiates an asynchronous import. The updated - skills belonging to the assistant are not available until processing completes. To - check the status of the asynchronous import operation, use the **Get status of - skills import** method. + Monitor the status of an assistant release import. You may poll this endpoint + until the status of the import has either succeeded or failed. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1784,31 +2223,20 @@ def import_skills( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. - :param List[SkillImport] assistant_skills: An array of objects describing - the skills for the assistant. Included in responses only if - **status**=`Available`. - :param AssistantState assistant_state: Status information about the skills - for the assistant. Included in responses only if **status**=`Available`. :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 with `dict` result representing a `SkillsAsyncRequestStatus` object + :rtype: DetailedResponse with `dict` result representing a `MonitorAssistantReleaseImportArtifactResponse` object """ if not assistant_id: raise ValueError('assistant_id must be provided') - if assistant_skills is None: - raise ValueError('assistant_skills must be provided') - if assistant_state is None: - raise ValueError('assistant_state must be provided') - assistant_skills = [convert_model(x) for x in assistant_skills] - assistant_state = convert_model(assistant_state) headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='import_skills', + operation_id='get_release_import_status', ) headers.update(sdk_headers) @@ -1817,14 +2245,6 @@ def import_skills( 'include_audit': include_audit, } - data = { - 'assistant_skills': assistant_skills, - 'assistant_state': assistant_state, - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - if 'headers' in kwargs: headers.update(kwargs.get('headers')) del kwargs['headers'] @@ -1833,29 +2253,31 @@ def import_skills( path_param_keys = ['assistant_id'] path_param_values = self.encode_path_vars(assistant_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/skills_import'.format( - **path_param_dict) + url = '/v2/assistants/{assistant_id}/import'.format(**path_param_dict) request = self.prepare_request( - method='POST', + method='GET', url=url, headers=headers, params=params, - data=data, ) response = self.send(request, **kwargs) return response - def import_skills_status( + ######################### + # Skills + ######################### + + def get_skill( self, assistant_id: str, + skill_id: str, **kwargs, ) -> DetailedResponse: """ - Get status of skills import. + Get skill. - Retrieve the status of an asynchronous import operation previously initiated by - using the **Import skills** method. + Get information about a skill. :param str assistant_id: The assistant ID or the environment ID of the environment where the assistant is deployed, depending on the type of @@ -1869,18 +2291,23 @@ def import_skills_status( **Note:** If you are using the classic Watson Assistant experience, always use the assistant ID. To find the assistant ID in the user interface, open the assistant settings and click API Details. + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the watsonx Assistant user interface, open the skill settings and click + **API Details**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object + :rtype: DetailedResponse with `dict` result representing a `Skill` object """ if not assistant_id: raise ValueError('assistant_id must be provided') + if not skill_id: + raise ValueError('skill_id must be provided') headers = {} sdk_headers = get_sdk_headers( service_name=self.DEFAULT_SERVICE_NAME, service_version='V2', - operation_id='import_skills_status', + operation_id='get_skill', ) headers.update(sdk_headers) @@ -1893,10 +2320,10 @@ def import_skills_status( del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id'] - path_param_values = self.encode_path_vars(assistant_id) + path_param_keys = ['assistant_id', 'skill_id'] + path_param_values = self.encode_path_vars(assistant_id, skill_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/skills_import/status'.format( + url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( **path_param_dict) request = self.prepare_request( method='GET', @@ -1908,308 +2335,460 @@ def import_skills_status( response = self.send(request, **kwargs) return response - -class ListAssistantsEnums: - """ - Enums for list_assistants parameters. - """ - - class Sort(str, Enum): - """ - The attribute by which returned assistants will be sorted. To reverse the sort - order, prefix the value with a minus sign (`-`). - """ - - NAME = 'name' - UPDATED = 'updated' - - -class ListEnvironmentsEnums: - """ - Enums for list_environments parameters. - """ - - class Sort(str, Enum): - """ - The attribute by which returned environments will be sorted. To reverse the sort - order, prefix the value with a minus sign (`-`). + def update_skill( + self, + assistant_id: str, + skill_id: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + dialog_settings: Optional[dict] = None, + search_settings: Optional['SearchSettings'] = None, + **kwargs, + ) -> DetailedResponse: """ + Update skill. - NAME = 'name' - UPDATED = 'updated' - - -class ListReleasesEnums: - """ - Enums for list_releases parameters. - """ + Update a skill with new or modified data. + **Note:** The update is performed asynchronously; you can see the status of the + update by calling the **Get skill** method and checking the value of the + **status** property. - class Sort(str, Enum): - """ - The attribute by which returned workspaces will be sorted. To reverse the sort - order, prefix the value with a minus sign (`-`). + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param str skill_id: Unique identifier of the skill. To find the skill ID + in the watsonx Assistant user interface, open the skill settings and click + **API Details**. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `Skill` object """ - NAME = 'name' - UPDATED = 'updated' + if not assistant_id: + raise ValueError('assistant_id must be provided') + if not skill_id: + raise ValueError('skill_id must be provided') + if search_settings is not None: + search_settings = convert_model(search_settings) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='update_skill', + ) + headers.update(sdk_headers) + params = { + 'version': self.version, + } -############################################################################## -# Models -############################################################################## + data = { + 'name': name, + 'description': description, + 'workspace': workspace, + 'dialog_settings': dialog_settings, + 'search_settings': search_settings, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -class AgentAvailabilityMessage: - """ - AgentAvailabilityMessage. + path_param_keys = ['assistant_id', 'skill_id'] + path_param_values = self.encode_path_vars(assistant_id, skill_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills/{skill_id}'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) - :param str message: (optional) The text of the message. - """ + response = self.send(request, **kwargs) + return response - def __init__( + def export_skills( self, + assistant_id: str, *, - message: Optional[str] = None, - ) -> None: + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ - Initialize a AgentAvailabilityMessage object. + Export skills. - :param str message: (optional) The text of the message. - """ - self.message = message - - @classmethod - def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': - """Initialize a AgentAvailabilityMessage object from a json dictionary.""" - args = {} - if (message := _dict.get('message')) is not None: - args['message'] = message - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a AgentAvailabilityMessage 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, 'message') and self.message is not None: - _dict['message'] = self.message - return _dict - - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + Asynchronously export the action skill and dialog skill (if enabled) for the + assistant. Use this method to save all skill data so that you can import it to a + different assistant using the **Import skills** method. + A successful call to this method only initiates an asynchronous export. The + exported JSON data is not available until processing completes. + After the initial request is submitted, you can poll the status of the operation + by calling the same request again and checking the value of the **status** + property. If an error occurs (indicated by a **status** value of `Failed`), the + `status_description` property provides more information about the error, and the + `status_errors` property contains an array of error messages that caused the + failure. + When processing has completed, the request returns the exported JSON data. + Remember that the usual rate limits apply. - def __str__(self) -> str: - """Return a `str` version of this AgentAvailabilityMessage object.""" - return json.dumps(self.to_dict(), indent=2) + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :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 with `dict` result representing a `SkillsExport` object + """ - def __eq__(self, other: 'AgentAvailabilityMessage') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='export_skills', + ) + headers.update(sdk_headers) - def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + params = { + 'version': self.version, + 'include_audit': include_audit, + } + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' -class AssistantCollection: - """ - AssistantCollection. + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_export'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) - :param List[AssistantData] assistants: An array of objects describing the - assistants associated with the instance. - :param Pagination pagination: The pagination data for the returned objects. For - more information about using pagination, see [Pagination](#pagination). - """ + response = self.send(request, **kwargs) + return response - def __init__( + def import_skills( self, - assistants: List['AssistantData'], - pagination: 'Pagination', - ) -> None: + assistant_id: str, + assistant_skills: List['SkillImport'], + assistant_state: 'AssistantState', + *, + include_audit: Optional[bool] = None, + **kwargs, + ) -> DetailedResponse: """ - Initialize a AssistantCollection object. + Import skills. - :param List[AssistantData] assistants: An array of objects describing the - assistants associated with the instance. - :param Pagination pagination: The pagination data for the returned objects. - For more information about using pagination, see [Pagination](#pagination). - """ - self.assistants = assistants - self.pagination = pagination + Asynchronously import skills into an existing assistant from a previously exported + file. + The request body for this method should contain the response data that was + received from a previous call to the **Export skills** method, without + modification. + A successful call to this method initiates an asynchronous import. The updated + skills belonging to the assistant are not available until processing completes. To + check the status of the asynchronous import operation, use the **Get status of + skills import** method. - @classmethod - def from_dict(cls, _dict: Dict) -> 'AssistantCollection': - """Initialize a AssistantCollection object from a json dictionary.""" - args = {} - if (assistants := _dict.get('assistants')) is not None: - args['assistants'] = [ - AssistantData.from_dict(v) for v in assistants - ] - else: - raise ValueError( - 'Required property \'assistants\' not present in AssistantCollection JSON' - ) - if (pagination := _dict.get('pagination')) is not None: - args['pagination'] = Pagination.from_dict(pagination) - else: - raise ValueError( - 'Required property \'pagination\' not present in AssistantCollection JSON' - ) - return cls(**args) + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param List[SkillImport] assistant_skills: An array of objects describing + the skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. + :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 with `dict` result representing a `SkillsAsyncRequestStatus` object + """ - @classmethod - def _from_dict(cls, _dict): - """Initialize a AssistantCollection object from a json dictionary.""" - return cls.from_dict(_dict) + if not assistant_id: + raise ValueError('assistant_id must be provided') + if assistant_skills is None: + raise ValueError('assistant_skills must be provided') + if assistant_state is None: + raise ValueError('assistant_state must be provided') + assistant_skills = [convert_model(x) for x in assistant_skills] + assistant_state = convert_model(assistant_state) + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills', + ) + headers.update(sdk_headers) - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'assistants') and self.assistants is not None: - assistants_list = [] - for v in self.assistants: - if isinstance(v, dict): - assistants_list.append(v) - else: - assistants_list.append(v.to_dict()) - _dict['assistants'] = assistants_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination - else: - _dict['pagination'] = self.pagination.to_dict() - return _dict + params = { + 'version': self.version, + 'include_audit': include_audit, + } - def _to_dict(self): - """Return a json dictionary representing this model.""" - return self.to_dict() + data = { + 'assistant_skills': assistant_skills, + 'assistant_state': assistant_state, + } + data = {k: v for (k, v) in data.items() if v is not None} + data = json.dumps(data) + headers['content-type'] = 'application/json' - def __str__(self) -> str: - """Return a `str` version of this AssistantCollection object.""" - return json.dumps(self.to_dict(), indent=2) + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' - def __eq__(self, other: 'AssistantCollection') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_import'.format( + **path_param_dict) + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) - def __ne__(self, other: 'AssistantCollection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other + response = self.send(request, **kwargs) + return response + def import_skills_status( + self, + assistant_id: str, + **kwargs, + ) -> DetailedResponse: + """ + Get status of skills import. -class AssistantData: + Retrieve the status of an asynchronous import operation previously initiated by + using the **Import skills** method. + + :param str assistant_id: The assistant ID or the environment ID of the + environment where the assistant is deployed, depending on the type of + request: + - For message, session, and log requests, specify the environment ID of + the environment where the assistant is deployed. + - For all other requests, specify the assistant ID of the assistant. + To find the environment ID or assistant ID in the watsonx Assistant user + interface, open the assistant settings and scroll to the **Environments** + section. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. To find the assistant ID in the user interface, open + the assistant settings and click API Details. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object + """ + + if not assistant_id: + raise ValueError('assistant_id must be provided') + headers = {} + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V2', + operation_id='import_skills_status', + ) + headers.update(sdk_headers) + + params = { + 'version': self.version, + } + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + path_param_keys = ['assistant_id'] + path_param_values = self.encode_path_vars(assistant_id) + path_param_dict = dict(zip(path_param_keys, path_param_values)) + url = '/v2/assistants/{assistant_id}/skills_import/status'.format( + **path_param_dict) + request = self.prepare_request( + method='GET', + url=url, + headers=headers, + params=params, + ) + + response = self.send(request, **kwargs) + return response + + +class ListProvidersEnums: + """ + Enums for list_providers parameters. """ - AssistantData. - :param str assistant_id: (optional) The unique identifier of the assistant. - :param str name: (optional) The name of the assistant. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the assistant. This string - cannot contain carriage return, newline, or tab characters. - :param str language: The language of the assistant. - :param List[AssistantSkill] assistant_skills: (optional) An array of skill - references identifying the skills associated with the assistant. - :param List[EnvironmentReference] assistant_environments: (optional) An array of - objects describing the environments defined for the assistant. + class Sort(str, Enum): + """ + The attribute by which returned conversational skill providers will be sorted. To + reverse the sort order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class ListAssistantsEnums: + """ + Enums for list_assistants parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned assistants will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class ListEnvironmentsEnums: + """ + Enums for list_environments parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned environments will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class ListReleasesEnums: + """ + Enums for list_releases parameters. + """ + + class Sort(str, Enum): + """ + The attribute by which returned workspaces will be sorted. To reverse the sort + order, prefix the value with a minus sign (`-`). + """ + + NAME = 'name' + UPDATED = 'updated' + + +class DownloadReleaseExportEnums: + """ + Enums for download_release_export parameters. + """ + + class Accept(str, Enum): + """ + The type of the response: application/json or application/octet-stream. + """ + + APPLICATION_JSON = 'application/json' + APPLICATION_OCTET_STREAM = 'application/octet-stream' + + +############################################################################## +# Models +############################################################################## + + +class AgentAvailabilityMessage: + """ + AgentAvailabilityMessage. + + :param str message: (optional) The text of the message. """ def __init__( self, - language: str, *, - assistant_id: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - assistant_skills: Optional[List['AssistantSkill']] = None, - assistant_environments: Optional[List['EnvironmentReference']] = None, + message: Optional[str] = None, ) -> None: """ - Initialize a AssistantData object. + Initialize a AgentAvailabilityMessage object. - :param str language: The language of the assistant. - :param str name: (optional) The name of the assistant. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the assistant. This - string cannot contain carriage return, newline, or tab characters. + :param str message: (optional) The text of the message. """ - self.assistant_id = assistant_id - self.name = name - self.description = description - self.language = language - self.assistant_skills = assistant_skills - self.assistant_environments = assistant_environments + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'AssistantData': - """Initialize a AssistantData object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'AgentAvailabilityMessage': + """Initialize a AgentAvailabilityMessage object from a json dictionary.""" args = {} - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in AssistantData JSON' - ) - if (assistant_skills := _dict.get('assistant_skills')) is not None: - args['assistant_skills'] = [ - AssistantSkill.from_dict(v) for v in assistant_skills - ] - if (assistant_environments := - _dict.get('assistant_environments')) is not None: - args['assistant_environments'] = [ - EnvironmentReference.from_dict(v) - for v in assistant_environments - ] + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a AssistantData object from a json dictionary.""" + """Initialize a AgentAvailabilityMessage 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, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'assistant_skills') and getattr( - self, 'assistant_skills') is not None: - assistant_skills_list = [] - for v in getattr(self, 'assistant_skills'): - if isinstance(v, dict): - assistant_skills_list.append(v) - else: - assistant_skills_list.append(v.to_dict()) - _dict['assistant_skills'] = assistant_skills_list - if hasattr(self, 'assistant_environments') and getattr( - self, 'assistant_environments') is not None: - assistant_environments_list = [] - for v in getattr(self, 'assistant_environments'): - if isinstance(v, dict): - assistant_environments_list.append(v) - else: - assistant_environments_list.append(v.to_dict()) - _dict['assistant_environments'] = assistant_environments_list + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -2217,39 +2796,253 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this AssistantData object.""" + """Return a `str` version of this AgentAvailabilityMessage object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'AssistantData') -> bool: + def __eq__(self, other: 'AgentAvailabilityMessage') -> 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: 'AssistantData') -> bool: + def __ne__(self, other: 'AgentAvailabilityMessage') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class AssistantSkill: +class AssistantCollection: """ - AssistantSkill. + AssistantCollection. - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. + :param List[AssistantData] assistants: An array of objects describing the + assistants associated with the instance. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__( self, - skill_id: str, - *, - type: Optional[str] = None, + assistants: List['AssistantData'], + pagination: 'Pagination', ) -> None: """ - Initialize a AssistantSkill object. + Initialize a AssistantCollection object. - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. + :param List[AssistantData] assistants: An array of objects describing the + assistants associated with the instance. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + self.assistants = assistants + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AssistantCollection': + """Initialize a AssistantCollection object from a json dictionary.""" + args = {} + if (assistants := _dict.get('assistants')) is not None: + args['assistants'] = [ + AssistantData.from_dict(v) for v in assistants + ] + else: + raise ValueError( + 'Required property \'assistants\' not present in AssistantCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in AssistantCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AssistantCollection 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, 'assistants') and self.assistants is not None: + assistants_list = [] + for v in self.assistants: + if isinstance(v, dict): + assistants_list.append(v) + else: + assistants_list.append(v.to_dict()) + _dict['assistants'] = assistants_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() + 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 AssistantCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AssistantCollection') -> 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: 'AssistantCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AssistantData: + """ + AssistantData. + + :param str assistant_id: (optional) The unique identifier of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This string + cannot contain carriage return, newline, or tab characters. + :param str language: The language of the assistant. + :param List[AssistantSkill] assistant_skills: (optional) An array of skill + references identifying the skills associated with the assistant. + :param List[EnvironmentReference] assistant_environments: (optional) An array of + objects describing the environments defined for the assistant. + """ + + def __init__( + self, + language: str, + *, + assistant_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + assistant_skills: Optional[List['AssistantSkill']] = None, + assistant_environments: Optional[List['EnvironmentReference']] = None, + ) -> None: + """ + Initialize a AssistantData object. + + :param str language: The language of the assistant. + :param str name: (optional) The name of the assistant. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the assistant. This + string cannot contain carriage return, newline, or tab characters. + """ + self.assistant_id = assistant_id + self.name = name + self.description = description + self.language = language + self.assistant_skills = assistant_skills + self.assistant_environments = assistant_environments + + @classmethod + def from_dict(cls, _dict: Dict) -> 'AssistantData': + """Initialize a AssistantData object from a json dictionary.""" + args = {} + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in AssistantData JSON' + ) + if (assistant_skills := _dict.get('assistant_skills')) is not None: + args['assistant_skills'] = [ + AssistantSkill.from_dict(v) for v in assistant_skills + ] + if (assistant_environments := + _dict.get('assistant_environments')) is not None: + args['assistant_environments'] = [ + EnvironmentReference.from_dict(v) + for v in assistant_environments + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a AssistantData 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, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'assistant_skills') and getattr( + self, 'assistant_skills') is not None: + assistant_skills_list = [] + for v in getattr(self, 'assistant_skills'): + if isinstance(v, dict): + assistant_skills_list.append(v) + else: + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, 'assistant_environments') and getattr( + self, 'assistant_environments') is not None: + assistant_environments_list = [] + for v in getattr(self, 'assistant_environments'): + if isinstance(v, dict): + assistant_environments_list.append(v) + else: + assistant_environments_list.append(v.to_dict()) + _dict['assistant_environments'] = assistant_environments_list + 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 AssistantData object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'AssistantData') -> 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: 'AssistantData') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class AssistantSkill: + """ + AssistantSkill. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + """ + + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + ) -> None: + """ + Initialize a AssistantSkill object. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. """ self.skill_id = skill_id self.type = type @@ -3001,54 +3794,323 @@ def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: return not self == other -class DialogLogMessage: +class CreateAssistantReleaseImportResponse: """ - Dialog log message details. - - :param str level: The severity of the log message. - :param str message: The text of the log message. - :param str code: A code that indicates the category to which the error message + CreateAssistantReleaseImportResponse. + + :param str status: (optional) The current status of the artifact import process: + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import artifact is underway and + not yet completed. + :param str task_id: (optional) A unique identifier for a background asynchronous + task that is executing or has executed the operation. + :param str assistant_id: (optional) The ID of the assistant to which the release belongs. - :param LogMessageSource source: (optional) An object that identifies the dialog - element that generated the error message. + :param List[str] skill_impact_in_draft: (optional) An array of skill types in + the draft environment which will be overridden with skills from the artifact + being imported. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. """ def __init__( self, - level: str, - message: str, - code: str, *, - source: Optional['LogMessageSource'] = None, + status: Optional[str] = None, + task_id: Optional[str] = None, + assistant_id: Optional[str] = None, + skill_impact_in_draft: Optional[List[str]] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, ) -> None: """ - Initialize a DialogLogMessage object. + Initialize a CreateAssistantReleaseImportResponse object. - :param str level: The severity of the log message. - :param str message: The text of the log message. - :param str code: A code that indicates the category to which the error - message belongs. - :param LogMessageSource source: (optional) An object that identifies the - dialog element that generated the error message. + :param List[str] skill_impact_in_draft: (optional) An array of skill types + in the draft environment which will be overridden with skills from the + artifact being imported. """ - self.level = level - self.message = message - self.code = code - self.source = source + self.status = status + self.task_id = task_id + self.assistant_id = assistant_id + self.skill_impact_in_draft = skill_impact_in_draft + self.created = created + self.updated = updated @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': - """Initialize a DialogLogMessage object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CreateAssistantReleaseImportResponse': + """Initialize a CreateAssistantReleaseImportResponse object from a json dictionary.""" args = {} - if (level := _dict.get('level')) is not None: - args['level'] = level - else: - raise ValueError( - 'Required property \'level\' not present in DialogLogMessage JSON' - ) - if (message := _dict.get('message')) is not None: - args['message'] = message - else: + if (status := _dict.get('status')) is not None: + args['status'] = status + if (task_id := _dict.get('task_id')) is not None: + args['task_id'] = task_id + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (skill_impact_in_draft := + _dict.get('skill_impact_in_draft')) is not None: + args['skill_impact_in_draft'] = skill_impact_in_draft + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateAssistantReleaseImportResponse 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, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'task_id') and getattr(self, 'task_id') is not None: + _dict['task_id'] = getattr(self, 'task_id') + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'skill_impact_in_draft' + ) and self.skill_impact_in_draft is not None: + _dict['skill_impact_in_draft'] = self.skill_impact_in_draft + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + 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 CreateAssistantReleaseImportResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CreateAssistantReleaseImportResponse') -> 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: 'CreateAssistantReleaseImportResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the artifact import process: + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import artifact is underway and + not yet completed. + """ + + FAILED = 'Failed' + PROCESSING = 'Processing' + + class SkillImpactInDraftEnum(str, Enum): + """ + The type of the skill in the draft environment. + """ + + ACTION = 'action' + DIALOG = 'dialog' + + +class CreateReleaseExportWithStatusErrors: + """ + CreateReleaseExportWithStatusErrors. + + :param str status: (optional) The current status of the release export creation + process: + - **Available**: The release export package is available for download. + - **Failed**: The asynchronous release export package creation process has + failed. + - **Processing**: An asynchronous operation to create the release export + package is underway and not yet completed. + :param str task_id: (optional) A unique identifier for a background asynchronous + task that is executing or has executed the operation. + :param str assistant_id: (optional) The ID of the assistant to which the release + belongs. + :param str release: (optional) The name of the release. The name is the version + number (an integer), returned as a string. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + """ + + def __init__( + self, + *, + status: Optional[str] = None, + task_id: Optional[str] = None, + assistant_id: Optional[str] = None, + release: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + ) -> None: + """ + Initialize a CreateReleaseExportWithStatusErrors object. + + """ + self.status = status + self.task_id = task_id + self.assistant_id = assistant_id + self.release = release + self.created = created + self.updated = updated + self.status_errors = status_errors + self.status_description = status_description + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CreateReleaseExportWithStatusErrors': + """Initialize a CreateReleaseExportWithStatusErrors object from a json dictionary.""" + args = {} + if (status := _dict.get('status')) is not None: + args['status'] = status + if (task_id := _dict.get('task_id')) is not None: + args['task_id'] = task_id + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (release := _dict.get('release')) is not None: + args['release'] = release + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a CreateReleaseExportWithStatusErrors 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, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'task_id') and getattr(self, 'task_id') is not None: + _dict['task_id'] = getattr(self, 'task_id') + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'release') and getattr(self, 'release') is not None: + _dict['release'] = getattr(self, 'release') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + 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 CreateReleaseExportWithStatusErrors object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'CreateReleaseExportWithStatusErrors') -> 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: 'CreateReleaseExportWithStatusErrors') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the release export creation process: + - **Available**: The release export package is available for download. + - **Failed**: The asynchronous release export package creation process has + failed. + - **Processing**: An asynchronous operation to create the release export package + is underway and not yet completed. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class DialogLogMessage: + """ + Dialog log message details. + + :param str level: The severity of the log message. + :param str message: The text of the log message. + :param str code: A code that indicates the category to which the error message + belongs. + :param LogMessageSource source: (optional) An object that identifies the dialog + element that generated the error message. + """ + + def __init__( + self, + level: str, + message: str, + code: str, + *, + source: Optional['LogMessageSource'] = None, + ) -> None: + """ + Initialize a DialogLogMessage object. + + :param str level: The severity of the log message. + :param str message: The text of the log message. + :param str code: A code that indicates the category to which the error + message belongs. + :param LogMessageSource source: (optional) An object that identifies the + dialog element that generated the error message. + """ + self.level = level + self.message = message + self.code = code + self.source = source + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DialogLogMessage': + """Initialize a DialogLogMessage object from a json dictionary.""" + args = {} + if (level := _dict.get('level')) is not None: + args['level'] = level + else: + raise ValueError( + 'Required property \'level\' not present in DialogLogMessage JSON' + ) + if (message := _dict.get('message')) is not None: + args['message'] = message + else: raise ValueError( 'Required property \'message\' not present in DialogLogMessage JSON' ) @@ -5776,6 +6838,8 @@ class MessageContextSkillSystem: subsequent message request, you can return to an earlier point in the conversation. If you are using stateful sessions, you can also use a stored state value to restore a paused conversation whose session is expired. + + This type supports additional properties of type object. For internal use only. """ # The set of defined properties for the class @@ -5785,7 +6849,7 @@ def __init__( self, *, state: Optional[str] = None, - **kwargs, + **kwargs: Optional[object], ) -> None: """ Initialize a MessageContextSkillSystem object. @@ -5795,11 +6859,20 @@ def __init__( of a subsequent message request, you can return to an earlier point in the conversation. If you are using stateful sessions, you can also use a stored state value to restore a paused conversation whose session is expired. - :param **kwargs: (optional) Any additional properties. + :param object **kwargs: (optional) For internal use only. """ self.state = state - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + for k, v in kwargs.items(): + if k not in MessageContextSkillSystem._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': @@ -5807,8 +6880,13 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': args = {} if (state := _dict.get('state')) is not None: args['state'] = state - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod @@ -5821,11 +6899,11 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'state') and self.state is not None: _dict['state'] = self.state - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def _to_dict(self): @@ -5833,27 +6911,33 @@ def _to_dict(self): return self.to_dict() def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" + """Return the additional properties from this instance of MessageContextSkillSystem in the form of a dict.""" _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties ]: - _dict[_key] = getattr(self, _key) + _dict[k] = getattr(self, k) return _dict def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" - for _key in [ - k for k in vars(self).keys() - if k not in MessageContextSkillSystem._properties + """Set a dictionary of additional properties in this instance of MessageContextSkillSystem""" + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in MessageContextSkillSystem._properties: - setattr(self, _key, _value) + delattr(self, k) + for k, v in _dict.items(): + if k not in MessageContextSkillSystem._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) def __str__(self) -> str: """Return a `str` version of this MessageContextSkillSystem object.""" @@ -6918,97 +8002,45 @@ def __ne__(self, other: 'MessageOutputSpelling') -> bool: return not self == other -class Pagination: +class Metadata: """ - The pagination data for the returned objects. For more information about using - pagination, see [Pagination](#pagination). + Contains meta-information about the item(s) being streamed. - :param str refresh_url: The URL that will return the same page of results. - :param str next_url: (optional) The URL that will return the next page of - results. - :param int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the current - page. - :param int matched: (optional) Reserved for future use. - :param str refresh_cursor: (optional) A token identifying the current page of - results. - :param str next_cursor: (optional) A token identifying the next page of results. + :param int id: (optional) Identifies the index and sequence of the current + streamed response item. """ def __init__( self, - refresh_url: str, *, - next_url: Optional[str] = None, - total: Optional[int] = None, - matched: Optional[int] = None, - refresh_cursor: Optional[str] = None, - next_cursor: Optional[str] = None, + id: Optional[int] = None, ) -> None: """ - Initialize a Pagination object. + Initialize a Metadata object. - :param str refresh_url: The URL that will return the same page of results. - :param str next_url: (optional) The URL that will return the next page of - results. - :param int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the - current page. - :param int matched: (optional) Reserved for future use. - :param str refresh_cursor: (optional) A token identifying the current page - of results. - :param str next_cursor: (optional) A token identifying the next page of - results. + :param int id: (optional) Identifies the index and sequence of the current + streamed response item. """ - self.refresh_url = refresh_url - self.next_url = next_url - self.total = total - self.matched = matched - self.refresh_cursor = refresh_cursor - self.next_cursor = next_cursor + self.id = id @classmethod - def from_dict(cls, _dict: Dict) -> 'Pagination': - """Initialize a Pagination object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Metadata': + """Initialize a Metadata object from a json dictionary.""" args = {} - if (refresh_url := _dict.get('refresh_url')) is not None: - args['refresh_url'] = refresh_url - else: - raise ValueError( - 'Required property \'refresh_url\' not present in Pagination JSON' - ) - if (next_url := _dict.get('next_url')) is not None: - args['next_url'] = next_url - if (total := _dict.get('total')) is not None: - args['total'] = total - if (matched := _dict.get('matched')) is not None: - args['matched'] = matched - if (refresh_cursor := _dict.get('refresh_cursor')) is not None: - args['refresh_cursor'] = refresh_cursor - if (next_cursor := _dict.get('next_cursor')) is not None: - args['next_cursor'] = next_cursor + if (id := _dict.get('id')) is not None: + args['id'] = id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Pagination object from a json dictionary.""" + """Initialize a Metadata 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, 'refresh_url') and self.refresh_url is not None: - _dict['refresh_url'] = self.refresh_url - if hasattr(self, 'next_url') and self.next_url is not None: - _dict['next_url'] = self.next_url - if hasattr(self, 'total') and self.total is not None: - _dict['total'] = self.total - if hasattr(self, 'matched') and self.matched is not None: - _dict['matched'] = self.matched - if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: - _dict['refresh_cursor'] = self.refresh_cursor - if hasattr(self, 'next_cursor') and self.next_cursor is not None: - _dict['next_cursor'] = self.next_cursor + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id return _dict def _to_dict(self): @@ -7016,35 +8048,41 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Pagination object.""" + """Return a `str` version of this Metadata object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Pagination') -> bool: + def __eq__(self, other: 'Metadata') -> 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: 'Pagination') -> bool: + def __ne__(self, other: 'Metadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Release: +class MonitorAssistantReleaseImportArtifactResponse: """ - Release. - - :param str release: (optional) The name of the release. The name is the version - number (an integer), returned as a string. - :param str description: (optional) The description of the release. - :param List[EnvironmentReference] environment_references: (optional) An array of - objects describing the environments where this release has been deployed. - :param ReleaseContent content: (optional) An object identifying the versionable - content objects (such as skill snapshots) that are included in the release. - :param str status: (optional) The current status of the release: - - **Available**: The release is available for deployment. - - **Failed**: An asynchronous publish operation has failed. - - **Processing**: An asynchronous publish operation has not yet completed. + MonitorAssistantReleaseImportArtifactResponse. + + :param str status: (optional) The current status of the release import process: + - **Completed**: The artifact import has completed. + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import the artifact is underway + and not yet completed. + :param str task_id: (optional) A unique identifier for a background asynchronous + task that is executing or has executed the operation. + :param str assistant_id: (optional) The ID of the assistant to which the release + belongs. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param List[str] skill_impact_in_draft: (optional) An array of skill types in + the draft environment which will be overridden with skills from the artifact + being imported. :param datetime created: (optional) The timestamp for creation of the object. :param datetime updated: (optional) The timestamp for the most recent update to the object. @@ -7053,45 +8091,52 @@ class Release: def __init__( self, *, - release: Optional[str] = None, - description: Optional[str] = None, - environment_references: Optional[List['EnvironmentReference']] = None, - content: Optional['ReleaseContent'] = None, status: Optional[str] = None, + task_id: Optional[str] = None, + assistant_id: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + skill_impact_in_draft: Optional[List[str]] = None, created: Optional[datetime] = None, updated: Optional[datetime] = None, ) -> None: """ - Initialize a Release object. + Initialize a MonitorAssistantReleaseImportArtifactResponse object. - :param str description: (optional) The description of the release. + :param List[str] skill_impact_in_draft: (optional) An array of skill types + in the draft environment which will be overridden with skills from the + artifact being imported. """ - self.release = release - self.description = description - self.environment_references = environment_references - self.content = content self.status = status + self.task_id = task_id + self.assistant_id = assistant_id + self.status_errors = status_errors + self.status_description = status_description + self.skill_impact_in_draft = skill_impact_in_draft self.created = created self.updated = updated @classmethod - def from_dict(cls, _dict: Dict) -> 'Release': - """Initialize a Release object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MonitorAssistantReleaseImportArtifactResponse': + """Initialize a MonitorAssistantReleaseImportArtifactResponse object from a json dictionary.""" args = {} - if (release := _dict.get('release')) is not None: - args['release'] = release - if (description := _dict.get('description')) is not None: - args['description'] = description - if (environment_references := - _dict.get('environment_references')) is not None: - args['environment_references'] = [ - EnvironmentReference.from_dict(v) - for v in environment_references - ] - if (content := _dict.get('content')) is not None: - args['content'] = ReleaseContent.from_dict(content) if (status := _dict.get('status')) is not None: args['status'] = status + if (task_id := _dict.get('task_id')) is not None: + args['task_id'] = task_id + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (skill_impact_in_draft := + _dict.get('skill_impact_in_draft')) is not None: + args['skill_impact_in_draft'] = skill_impact_in_draft if (created := _dict.get('created')) is not None: args['created'] = string_to_datetime(created) if (updated := _dict.get('updated')) is not None: @@ -7100,32 +8145,34 @@ def from_dict(cls, _dict: Dict) -> 'Release': @classmethod def _from_dict(cls, _dict): - """Initialize a Release object from a json dictionary.""" + """Initialize a MonitorAssistantReleaseImportArtifactResponse 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, 'release') and getattr(self, 'release') is not None: - _dict['release'] = getattr(self, 'release') - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'environment_references') and getattr( - self, 'environment_references') is not None: - environment_references_list = [] - for v in getattr(self, 'environment_references'): - if isinstance(v, dict): - environment_references_list.append(v) - else: - environment_references_list.append(v.to_dict()) - _dict['environment_references'] = environment_references_list - if hasattr(self, 'content') and getattr(self, 'content') is not None: - if isinstance(getattr(self, 'content'), dict): - _dict['content'] = getattr(self, 'content') - else: - _dict['content'] = getattr(self, 'content').to_dict() if hasattr(self, 'status') and getattr(self, 'status') is not None: _dict['status'] = getattr(self, 'status') + if hasattr(self, 'task_id') and getattr(self, 'task_id') is not None: + _dict['task_id'] = getattr(self, 'task_id') + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'skill_impact_in_draft' + ) and self.skill_impact_in_draft is not None: + _dict['skill_impact_in_draft'] = self.skill_impact_in_draft if hasattr(self, 'created') and getattr(self, 'created') is not None: _dict['created'] = datetime_to_string(getattr(self, 'created')) if hasattr(self, 'updated') and getattr(self, 'updated') is not None: @@ -7137,162 +8184,208 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Release object.""" + """Return a `str` version of this MonitorAssistantReleaseImportArtifactResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Release') -> bool: + def __eq__(self, + other: 'MonitorAssistantReleaseImportArtifactResponse') -> 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: 'Release') -> bool: + def __ne__(self, + other: 'MonitorAssistantReleaseImportArtifactResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class StatusEnum(str, Enum): """ - The current status of the release: - - **Available**: The release is available for deployment. - - **Failed**: An asynchronous publish operation has failed. - - **Processing**: An asynchronous publish operation has not yet completed. + The current status of the release import process: + - **Completed**: The artifact import has completed. + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import the artifact is underway + and not yet completed. """ - AVAILABLE = 'Available' + COMPLETED = 'Completed' FAILED = 'Failed' PROCESSING = 'Processing' + class SkillImpactInDraftEnum(str, Enum): + """ + The type of the skill in the draft environment. + """ -class ReleaseCollection: + ACTION = 'action' + DIALOG = 'dialog' + + +class Pagination: """ - ReleaseCollection. + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). - :param List[Release] releases: An array of objects describing the releases - associated with an assistant. - :param Pagination pagination: The pagination data for the returned objects. For - more information about using pagination, see [Pagination](#pagination). + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the current + page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page of + results. + :param str next_cursor: (optional) A token identifying the next page of results. """ def __init__( self, - releases: List['Release'], - pagination: 'Pagination', + refresh_url: str, + *, + next_url: Optional[str] = None, + total: Optional[int] = None, + matched: Optional[int] = None, + refresh_cursor: Optional[str] = None, + next_cursor: Optional[str] = None, ) -> None: """ - Initialize a ReleaseCollection object. + Initialize a Pagination object. - :param List[Release] releases: An array of objects describing the releases - associated with an assistant. - :param Pagination pagination: The pagination data for the returned objects. - For more information about using pagination, see [Pagination](#pagination). + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the + current page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page + of results. + :param str next_cursor: (optional) A token identifying the next page of + results. """ - self.releases = releases - self.pagination = pagination + self.refresh_url = refresh_url + self.next_url = next_url + self.total = total + self.matched = matched + self.refresh_cursor = refresh_cursor + self.next_cursor = next_cursor @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': - """Initialize a ReleaseCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Pagination': + """Initialize a Pagination object from a json dictionary.""" args = {} - if (releases := _dict.get('releases')) is not None: - args['releases'] = [Release.from_dict(v) for v in releases] - else: - raise ValueError( - 'Required property \'releases\' not present in ReleaseCollection JSON' - ) - if (pagination := _dict.get('pagination')) is not None: - args['pagination'] = Pagination.from_dict(pagination) + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url else: raise ValueError( - 'Required property \'pagination\' not present in ReleaseCollection JSON' + 'Required property \'refresh_url\' not present in Pagination JSON' ) + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (total := _dict.get('total')) is not None: + args['total'] = total + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (refresh_cursor := _dict.get('refresh_cursor')) is not None: + args['refresh_cursor'] = refresh_cursor + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseCollection object from a json dictionary.""" + """Initialize a Pagination 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, 'releases') and self.releases is not None: - releases_list = [] - for v in self.releases: - if isinstance(v, dict): - releases_list.append(v) - else: - releases_list.append(v.to_dict()) - _dict['releases'] = releases_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination - else: - _dict['pagination'] = self.pagination.to_dict() - 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 ReleaseCollection object.""" + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'total') and self.total is not None: + _dict['total'] = self.total + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: + _dict['refresh_cursor'] = self.refresh_cursor + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor + 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 Pagination object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseCollection') -> bool: + def __eq__(self, other: 'Pagination') -> 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: 'ReleaseCollection') -> bool: + def __ne__(self, other: 'Pagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ReleaseContent: +class ProviderAuthenticationOAuth2: """ - An object identifying the versionable content objects (such as skill snapshots) that - are included in the release. + Non-private settings for oauth2 authentication. - :param List[ReleaseSkill] skills: (optional) The skill snapshots that are - included in the release. + :param str preferred_flow: (optional) The preferred "flow" or "grant type" for + the API client to fetch an access token from the authorization server. + :param ProviderAuthenticationOAuth2Flows flows: (optional) Scenarios performed + by the API client to fetch an access token from the authorization server. """ def __init__( self, *, - skills: Optional[List['ReleaseSkill']] = None, + preferred_flow: Optional[str] = None, + flows: Optional['ProviderAuthenticationOAuth2Flows'] = None, ) -> None: """ - Initialize a ReleaseContent object. + Initialize a ProviderAuthenticationOAuth2 object. + :param str preferred_flow: (optional) The preferred "flow" or "grant type" + for the API client to fetch an access token from the authorization server. + :param ProviderAuthenticationOAuth2Flows flows: (optional) Scenarios + performed by the API client to fetch an access token from the authorization + server. """ - self.skills = skills + self.preferred_flow = preferred_flow + self.flows = flows @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseContent': - """Initialize a ReleaseContent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderAuthenticationOAuth2': + """Initialize a ProviderAuthenticationOAuth2 object from a json dictionary.""" args = {} - if (skills := _dict.get('skills')) is not None: - args['skills'] = [ReleaseSkill.from_dict(v) for v in skills] + if (preferred_flow := _dict.get('preferred_flow')) is not None: + args['preferred_flow'] = preferred_flow + if (flows := _dict.get('flows')) is not None: + args['flows'] = flows return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseContent object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2 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, 'skills') and getattr(self, 'skills') is not None: - skills_list = [] - for v in getattr(self, 'skills'): - if isinstance(v, dict): - skills_list.append(v) - else: - skills_list.append(v.to_dict()) - _dict['skills'] = skills_list + if hasattr(self, 'preferred_flow') and self.preferred_flow is not None: + _dict['preferred_flow'] = self.preferred_flow + if hasattr(self, 'flows') and self.flows is not None: + if isinstance(self.flows, dict): + _dict['flows'] = self.flows + else: + _dict['flows'] = self.flows.to_dict() return _dict def _to_dict(self): @@ -7300,79 +8393,98 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseContent object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2 object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseContent') -> bool: + def __eq__(self, other: 'ProviderAuthenticationOAuth2') -> 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: 'ReleaseContent') -> bool: + def __ne__(self, other: 'ProviderAuthenticationOAuth2') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class PreferredFlowEnum(str, Enum): + """ + The preferred "flow" or "grant type" for the API client to fetch an access token + from the authorization server. + """ -class ReleaseSkill: + PASSWORD = 'password' + CLIENT_CREDENTIALS = 'client_credentials' + AUTHORIZATION_CODE = 'authorization_code' + CUSTOM_FLOW_NAME = '<$custom_flow_name>' + + +class ProviderAuthenticationOAuth2Flows: """ - ReleaseSkill. + Scenarios performed by the API client to fetch an access token from the authorization + server. - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. - :param str snapshot: (optional) The name of the skill snapshot that is saved as - part of the release (for example, `draft` or `1`). + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderAuthenticationOAuth2Flows object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password', + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials', + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode' + ])) + raise Exception(msg) + + +class ProviderAuthenticationOAuth2PasswordUsername: + """ + The username for oauth2 authentication when the preferred flow is "password". + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ def __init__( self, - skill_id: str, *, type: Optional[str] = None, - snapshot: Optional[str] = None, + value: Optional[str] = None, ) -> None: """ - Initialize a ReleaseSkill object. + Initialize a ProviderAuthenticationOAuth2PasswordUsername object. - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. - :param str snapshot: (optional) The name of the skill snapshot that is - saved as part of the release (for example, `draft` or `1`). + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ - self.skill_id = skill_id self.type = type - self.snapshot = snapshot + self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': - """Initialize a ReleaseSkill object from a json dictionary.""" + def from_dict( + cls, _dict: Dict) -> 'ProviderAuthenticationOAuth2PasswordUsername': + """Initialize a ProviderAuthenticationOAuth2PasswordUsername object from a json dictionary.""" args = {} - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - else: - raise ValueError( - 'Required property \'skill_id\' not present in ReleaseSkill JSON' - ) if (type := _dict.get('type')) is not None: args['type'] = type - if (snapshot := _dict.get('snapshot')) is not None: - args['snapshot'] = snapshot + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseSkill object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2PasswordUsername 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, 'skill_id') and self.skill_id is not None: - _dict['skill_id'] = self.skill_id if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value return _dict def _to_dict(self): @@ -7380,89 +8492,74 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseSkill object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2PasswordUsername object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseSkill') -> bool: + def __eq__(self, + other: 'ProviderAuthenticationOAuth2PasswordUsername') -> 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: 'ReleaseSkill') -> bool: + def __ne__(self, + other: 'ProviderAuthenticationOAuth2PasswordUsername') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other class TypeEnum(str, Enum): """ - The type of the skill. + The type of property observed in "value". """ - DIALOG = 'dialog' - ACTION = 'action' - SEARCH = 'search' + VALUE = 'value' -class RequestAnalytics: +class ProviderAuthenticationTypeAndValue: """ - An optional object containing analytics data. Currently, this data is used only for - events sent to the Segment extension. + ProviderAuthenticationTypeAndValue. - :param str browser: (optional) The browser that was used to send the message - that triggered the event. - :param str device: (optional) The type of device that was used to send the - message that triggered the event. - :param str page_url: (optional) The URL of the web page that was used to send - the message that triggered the event. + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ def __init__( self, *, - browser: Optional[str] = None, - device: Optional[str] = None, - page_url: Optional[str] = None, + type: Optional[str] = None, + value: Optional[str] = None, ) -> None: """ - Initialize a RequestAnalytics object. + Initialize a ProviderAuthenticationTypeAndValue object. - :param str browser: (optional) The browser that was used to send the - message that triggered the event. - :param str device: (optional) The type of device that was used to send the - message that triggered the event. - :param str page_url: (optional) The URL of the web page that was used to - send the message that triggered the event. + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ - self.browser = browser - self.device = device - self.page_url = page_url + self.type = type + self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': - """Initialize a RequestAnalytics object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderAuthenticationTypeAndValue': + """Initialize a ProviderAuthenticationTypeAndValue object from a json dictionary.""" args = {} - if (browser := _dict.get('browser')) is not None: - args['browser'] = browser - if (device := _dict.get('device')) is not None: - args['device'] = device - if (page_url := _dict.get('pageUrl')) is not None: - args['page_url'] = page_url + if (type := _dict.get('type')) is not None: + args['type'] = type + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RequestAnalytics object from a json dictionary.""" + """Initialize a ProviderAuthenticationTypeAndValue 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, 'browser') and self.browser is not None: - _dict['browser'] = self.browser - if hasattr(self, 'device') and self.device is not None: - _dict['device'] = self.device - if hasattr(self, 'page_url') and self.page_url is not None: - _dict['pageUrl'] = self.page_url + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value return _dict def _to_dict(self): @@ -7470,58 +8567,100 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RequestAnalytics object.""" + """Return a `str` version of this ProviderAuthenticationTypeAndValue object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RequestAnalytics') -> bool: + def __eq__(self, other: 'ProviderAuthenticationTypeAndValue') -> 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: 'RequestAnalytics') -> bool: + def __ne__(self, other: 'ProviderAuthenticationTypeAndValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of property observed in "value". + """ + + VALUE = 'value' -class ResponseGenericChannel: + +class ProviderCollection: """ - ResponseGenericChannel. + ProviderCollection. - :param str channel: (optional) A channel for which the response is intended. + :param List[ProviderResponse] conversational_skill_providers: An array of + objects describing the conversational skill providers associated with the + instance. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__( self, - *, - channel: Optional[str] = None, + conversational_skill_providers: List['ProviderResponse'], + pagination: 'Pagination', ) -> None: """ - Initialize a ResponseGenericChannel object. + Initialize a ProviderCollection object. - :param str channel: (optional) A channel for which the response is - intended. + :param List[ProviderResponse] conversational_skill_providers: An array of + objects describing the conversational skill providers associated with the + instance. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - self.channel = channel + self.conversational_skill_providers = conversational_skill_providers + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': - """Initialize a ResponseGenericChannel object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderCollection': + """Initialize a ProviderCollection object from a json dictionary.""" args = {} - if (channel := _dict.get('channel')) is not None: - args['channel'] = channel + if (conversational_skill_providers := + _dict.get('conversational_skill_providers')) is not None: + args['conversational_skill_providers'] = [ + ProviderResponse.from_dict(v) + for v in conversational_skill_providers + ] + else: + raise ValueError( + 'Required property \'conversational_skill_providers\' not present in ProviderCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in ProviderCollection JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ResponseGenericChannel object from a json dictionary.""" + """Initialize a ProviderCollection 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, 'channel') and self.channel is not None: - _dict['channel'] = self.channel + if hasattr(self, 'conversational_skill_providers' + ) and self.conversational_skill_providers is not None: + conversational_skill_providers_list = [] + for v in self.conversational_skill_providers: + if isinstance(v, dict): + conversational_skill_providers_list.append(v) + else: + conversational_skill_providers_list.append(v.to_dict()) + _dict[ + 'conversational_skill_providers'] = conversational_skill_providers_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -7529,194 +8668,65 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ResponseGenericChannel object.""" + """Return a `str` version of this ProviderCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ResponseGenericChannel') -> bool: + def __eq__(self, other: 'ProviderCollection') -> 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: 'ResponseGenericChannel') -> bool: + def __ne__(self, other: 'ProviderCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntity: +class ProviderPrivate: """ - The entity value that was recognized in the user input. + Private information of the provider. - :param str entity: An entity detected in the input. - :param List[int] location: (optional) An array of zero-based character offsets - that indicate where the detected entity values begin and end in the input text. - :param str value: The term in the input text that was recognized as an entity - value. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized 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. - :param str skill: (optional) The skill that recognized the entity value. - Currently, the only possible values are `main skill` for the dialog skill (if - enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and an - action skill. + :param ProviderPrivateAuthentication authentication: Private authentication + information of the provider. """ def __init__( self, - entity: str, - value: str, - *, - location: Optional[List[int]] = None, - confidence: Optional[float] = None, - groups: Optional[List['CaptureGroup']] = None, - interpretation: Optional['RuntimeEntityInterpretation'] = None, - alternatives: Optional[List['RuntimeEntityAlternative']] = None, - role: Optional['RuntimeEntityRole'] = None, - skill: Optional[str] = None, + authentication: 'ProviderPrivateAuthentication', ) -> None: """ - Initialize a RuntimeEntity object. + Initialize a ProviderPrivate object. - :param str entity: An entity detected in the input. - :param str value: The term in the input text that was recognized as an - entity value. - :param List[int] location: (optional) An array of zero-based character - offsets that indicate where the detected entity values begin and end in the - input text. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized 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. - :param str skill: (optional) The skill that recognized the entity value. - Currently, the only possible values are `main skill` for the dialog skill - (if enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and - an action skill. + :param ProviderPrivateAuthentication authentication: Private authentication + information of the provider. """ - self.entity = entity - self.location = location - self.value = value - self.confidence = confidence - self.groups = groups - self.interpretation = interpretation - self.alternatives = alternatives - self.role = role - self.skill = skill + self.authentication = authentication @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': - """Initialize a RuntimeEntity object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderPrivate': + """Initialize a ProviderPrivate object from a json dictionary.""" args = {} - if (entity := _dict.get('entity')) is not None: - args['entity'] = entity + if (authentication := _dict.get('authentication')) is not None: + args['authentication'] = authentication else: raise ValueError( - 'Required property \'entity\' not present in RuntimeEntity JSON' + 'Required property \'authentication\' not present in ProviderPrivate JSON' ) - if (location := _dict.get('location')) is not None: - args['location'] = location - if (value := _dict.get('value')) is not None: - args['value'] = value - else: - raise ValueError( - 'Required property \'value\' not present in RuntimeEntity JSON') - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (groups := _dict.get('groups')) is not None: - args['groups'] = [CaptureGroup.from_dict(v) for v in groups] - if (interpretation := _dict.get('interpretation')) is not None: - args['interpretation'] = RuntimeEntityInterpretation.from_dict( - interpretation) - if (alternatives := _dict.get('alternatives')) is not None: - args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(v) for v in alternatives - ] - if (role := _dict.get('role')) is not None: - args['role'] = RuntimeEntityRole.from_dict(role) - if (skill := _dict.get('skill')) is not None: - args['skill'] = skill return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntity object from a json dictionary.""" + """Initialize a ProviderPrivate 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, 'entity') and self.entity is not None: - _dict['entity'] = self.entity - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location - 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 - if hasattr(self, 'groups') and self.groups is not None: - groups_list = [] - for v in self.groups: - if isinstance(v, dict): - groups_list.append(v) - else: - groups_list.append(v.to_dict()) - _dict['groups'] = groups_list - if hasattr(self, 'interpretation') and self.interpretation is not None: - if isinstance(self.interpretation, dict): - _dict['interpretation'] = self.interpretation - else: - _dict['interpretation'] = self.interpretation.to_dict() - if hasattr(self, 'alternatives') and self.alternatives is not None: - alternatives_list = [] - for v in self.alternatives: - if isinstance(v, dict): - alternatives_list.append(v) - else: - alternatives_list.append(v.to_dict()) - _dict['alternatives'] = alternatives_list - if hasattr(self, 'role') and self.role is not None: - if isinstance(self.role, dict): - _dict['role'] = self.role + if hasattr(self, 'authentication') and self.authentication is not None: + if isinstance(self.authentication, dict): + _dict['authentication'] = self.authentication else: - _dict['role'] = self.role.to_dict() - if hasattr(self, 'skill') and self.skill is not None: - _dict['skill'] = self.skill + _dict['authentication'] = self.authentication.to_dict() return _dict def _to_dict(self): @@ -7724,69 +8734,108 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntity object.""" + """Return a `str` version of this ProviderPrivate object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntity') -> bool: + def __eq__(self, other: 'ProviderPrivate') -> 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: 'RuntimeEntity') -> bool: + def __ne__(self, other: 'ProviderPrivate') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityAlternative: +class ProviderPrivateAuthentication: """ - An alternative value for the recognized entity. + Private authentication information of the provider. - :param str value: (optional) The entity value that was recognized in the user - input. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized entity. + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderPrivateAuthentication object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderPrivateAuthenticationBearerFlow', + 'ProviderPrivateAuthenticationBasicFlow', + 'ProviderPrivateAuthenticationOAuth2Flow' + ])) + raise Exception(msg) + + +class ProviderPrivateAuthenticationOAuth2FlowFlows: + """ + Scenarios performed by the API client to fetch an access token from the authorization + server. + + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlows object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password', + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials', + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode' + ])) + raise Exception(msg) + + +class ProviderPrivateAuthenticationOAuth2PasswordPassword: + """ + The password for oauth2 authentication when the preferred flow is "password". + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ def __init__( self, *, + type: Optional[str] = None, value: Optional[str] = None, - confidence: Optional[float] = None, ) -> None: """ - Initialize a RuntimeEntityAlternative object. + Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object. - :param str value: (optional) The entity value that was recognized in the - user input. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized entity. + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ + self.type = type self.value = value - self.confidence = confidence @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2PasswordPassword': + """Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object from a json dictionary.""" args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type if (value := _dict.get('value')) is not None: args['value'] = value - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword 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 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): @@ -7794,103 +8843,1752 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityAlternative object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2PasswordPassword object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + def __eq__( + self, other: 'ProviderPrivateAuthenticationOAuth2PasswordPassword' + ) -> 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: + def __ne__( + self, other: 'ProviderPrivateAuthenticationOAuth2PasswordPassword' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of property observed in "value". + """ + + VALUE = 'value' -class RuntimeEntityInterpretation: + +class ProviderResponse: """ - RuntimeEntityInterpretation. + ProviderResponse. - :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`). + :param str provider_id: (optional) The unique identifier of the provider. + :param ProviderResponseSpecification specification: (optional) The specification + of the provider. """ def __init__( self, *, - calendar_type: Optional[str] = None, - datetime_link: Optional[str] = None, - festival: Optional[str] = None, - granularity: Optional[str] = None, - range_link: Optional[str] = None, - range_modifier: Optional[str] = None, + provider_id: Optional[str] = None, + specification: Optional['ProviderResponseSpecification'] = None, + ) -> None: + """ + Initialize a ProviderResponse object. + + :param str provider_id: (optional) The unique identifier of the provider. + :param ProviderResponseSpecification specification: (optional) The + specification of the provider. + """ + self.provider_id = provider_id + self.specification = specification + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderResponse': + """Initialize a ProviderResponse object from a json dictionary.""" + args = {} + if (provider_id := _dict.get('provider_id')) is not None: + args['provider_id'] = provider_id + if (specification := _dict.get('specification')) is not None: + args['specification'] = ProviderResponseSpecification.from_dict( + specification) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponse 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, 'provider_id') and self.provider_id is not None: + _dict['provider_id'] = self.provider_id + if hasattr(self, 'specification') and self.specification is not None: + if isinstance(self.specification, dict): + _dict['specification'] = self.specification + else: + _dict['specification'] = self.specification.to_dict() + 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 ProviderResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponse') -> 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: 'ProviderResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecification: + """ + The specification of the provider. + + :param List[ProviderResponseSpecificationServersItem] servers: (optional) An + array of objects defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderResponseSpecificationComponents components: (optional) An object + defining various reusable definitions of the provider. + """ + + def __init__( + self, + *, + servers: Optional[ + List['ProviderResponseSpecificationServersItem']] = None, + components: Optional['ProviderResponseSpecificationComponents'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecification object. + + :param List[ProviderResponseSpecificationServersItem] servers: (optional) + An array of objects defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderResponseSpecificationComponents components: (optional) An + object defining various reusable definitions of the provider. + """ + self.servers = servers + self.components = components + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderResponseSpecification': + """Initialize a ProviderResponseSpecification object from a json dictionary.""" + args = {} + if (servers := _dict.get('servers')) is not None: + args['servers'] = [ + ProviderResponseSpecificationServersItem.from_dict(v) + for v in servers + ] + if (components := _dict.get('components')) is not None: + args[ + 'components'] = ProviderResponseSpecificationComponents.from_dict( + components) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecification 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, 'servers') and self.servers is not None: + servers_list = [] + for v in self.servers: + if isinstance(v, dict): + servers_list.append(v) + else: + servers_list.append(v.to_dict()) + _dict['servers'] = servers_list + if hasattr(self, 'components') and self.components is not None: + if isinstance(self.components, dict): + _dict['components'] = self.components + else: + _dict['components'] = self.components.to_dict() + 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 ProviderResponseSpecification object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponseSpecification') -> 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: 'ProviderResponseSpecification') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecificationComponents: + """ + An object defining various reusable definitions of the provider. + + :param ProviderResponseSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. + """ + + def __init__( + self, + *, + security_schemes: Optional[ + 'ProviderResponseSpecificationComponentsSecuritySchemes'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationComponents object. + + :param ProviderResponseSpecificationComponentsSecuritySchemes + security_schemes: (optional) The definition of the security scheme for the + provider. + """ + self.security_schemes = security_schemes + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'ProviderResponseSpecificationComponents': + """Initialize a ProviderResponseSpecificationComponents object from a json dictionary.""" + args = {} + if (security_schemes := _dict.get('securitySchemes')) is not None: + args[ + 'security_schemes'] = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict( + security_schemes) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationComponents 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, + 'security_schemes') and self.security_schemes is not None: + if isinstance(self.security_schemes, dict): + _dict['securitySchemes'] = self.security_schemes + else: + _dict['securitySchemes'] = self.security_schemes.to_dict() + 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 ProviderResponseSpecificationComponents object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponseSpecificationComponents') -> 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: 'ProviderResponseSpecificationComponents') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecificationComponentsSecuritySchemes: + """ + The definition of the security scheme for the provider. + + :param str authentication_method: (optional) The authentication method required + for requests made from watsonx Assistant to the conversational skill provider. + :param ProviderResponseSpecificationComponentsSecuritySchemesBasic basic: + (optional) Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings for + oauth2 authentication. + """ + + def __init__( + self, + *, + authentication_method: Optional[str] = None, + basic: Optional[ + 'ProviderResponseSpecificationComponentsSecuritySchemesBasic'] = None, + oauth2: Optional['ProviderAuthenticationOAuth2'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object. + + :param str authentication_method: (optional) The authentication method + required for requests made from watsonx Assistant to the conversational + skill provider. + :param ProviderResponseSpecificationComponentsSecuritySchemesBasic basic: + (optional) Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings + for oauth2 authentication. + """ + self.authentication_method = authentication_method + self.basic = basic + self.oauth2 = oauth2 + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'ProviderResponseSpecificationComponentsSecuritySchemes': + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object from a json dictionary.""" + args = {} + if (authentication_method := + _dict.get('authentication_method')) is not None: + args['authentication_method'] = authentication_method + if (basic := _dict.get('basic')) is not None: + args[ + 'basic'] = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict( + basic) + if (oauth2 := _dict.get('oauth2')) is not None: + args['oauth2'] = ProviderAuthenticationOAuth2.from_dict(oauth2) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemes 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, 'authentication_method' + ) and self.authentication_method is not None: + _dict['authentication_method'] = self.authentication_method + if hasattr(self, 'basic') and self.basic is not None: + if isinstance(self.basic, dict): + _dict['basic'] = self.basic + else: + _dict['basic'] = self.basic.to_dict() + if hasattr(self, 'oauth2') and self.oauth2 is not None: + if isinstance(self.oauth2, dict): + _dict['oauth2'] = self.oauth2 + else: + _dict['oauth2'] = self.oauth2.to_dict() + 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 ProviderResponseSpecificationComponentsSecuritySchemes object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'ProviderResponseSpecificationComponentsSecuritySchemes' + ) -> 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: 'ProviderResponseSpecificationComponentsSecuritySchemes' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class AuthenticationMethodEnum(str, Enum): + """ + The authentication method required for requests made from watsonx Assistant to the + conversational skill provider. + """ + + BASIC = 'basic' + BEARER = 'bearer' + API_KEY = 'api_key' + OAUTH2 = 'oauth2' + NONE = 'none' + + +class ProviderResponseSpecificationComponentsSecuritySchemesBasic: + """ + Non-private settings for basic access authentication. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username for + basic access authentication. + """ + + def __init__( + self, + *, + username: Optional['ProviderAuthenticationTypeAndValue'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username + for basic access authentication. + """ + self.username = username + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'ProviderResponseSpecificationComponentsSecuritySchemesBasic': + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + args = {} + if (username := _dict.get('username')) is not None: + args['username'] = ProviderAuthenticationTypeAndValue.from_dict( + username) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic 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, 'username') and self.username is not None: + if isinstance(self.username, dict): + _dict['username'] = self.username + else: + _dict['username'] = self.username.to_dict() + 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 ProviderResponseSpecificationComponentsSecuritySchemesBasic object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'ProviderResponseSpecificationComponentsSecuritySchemesBasic' + ) -> 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: 'ProviderResponseSpecificationComponentsSecuritySchemesBasic' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecificationServersItem: + """ + ProviderResponseSpecificationServersItem. + + :param str url: (optional) The URL of the conversational skill provider. + """ + + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationServersItem object. + + :param str url: (optional) The URL of the conversational skill provider. + """ + self.url = url + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'ProviderResponseSpecificationServersItem': + """Initialize a ProviderResponseSpecificationServersItem object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationServersItem 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, 'url') and self.url is not None: + _dict['url'] = self.url + 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 ProviderResponseSpecificationServersItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponseSpecificationServersItem') -> 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: 'ProviderResponseSpecificationServersItem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecification: + """ + The specification of the provider. + + :param List[ProviderSpecificationServersItem] servers: An array of objects + defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderSpecificationComponents components: (optional) An object defining + various reusable definitions of the provider. + """ + + def __init__( + self, + servers: List['ProviderSpecificationServersItem'], + *, + components: Optional['ProviderSpecificationComponents'] = None, + ) -> None: + """ + Initialize a ProviderSpecification object. + + :param List[ProviderSpecificationServersItem] servers: An array of objects + defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderSpecificationComponents components: (optional) An object + defining various reusable definitions of the provider. + """ + self.servers = servers + self.components = components + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderSpecification': + """Initialize a ProviderSpecification object from a json dictionary.""" + args = {} + if (servers := _dict.get('servers')) is not None: + args['servers'] = [ + ProviderSpecificationServersItem.from_dict(v) for v in servers + ] + else: + raise ValueError( + 'Required property \'servers\' not present in ProviderSpecification JSON' + ) + if (components := _dict.get('components')) is not None: + args['components'] = ProviderSpecificationComponents.from_dict( + components) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecification 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, 'servers') and self.servers is not None: + servers_list = [] + for v in self.servers: + if isinstance(v, dict): + servers_list.append(v) + else: + servers_list.append(v.to_dict()) + _dict['servers'] = servers_list + if hasattr(self, 'components') and self.components is not None: + if isinstance(self.components, dict): + _dict['components'] = self.components + else: + _dict['components'] = self.components.to_dict() + 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 ProviderSpecification object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderSpecification') -> 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: 'ProviderSpecification') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecificationComponents: + """ + An object defining various reusable definitions of the provider. + + :param ProviderSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. + """ + + def __init__( + self, + *, + security_schemes: Optional[ + 'ProviderSpecificationComponentsSecuritySchemes'] = None, + ) -> None: + """ + Initialize a ProviderSpecificationComponents object. + + :param ProviderSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. + """ + self.security_schemes = security_schemes + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderSpecificationComponents': + """Initialize a ProviderSpecificationComponents object from a json dictionary.""" + args = {} + if (security_schemes := _dict.get('securitySchemes')) is not None: + args[ + 'security_schemes'] = ProviderSpecificationComponentsSecuritySchemes.from_dict( + security_schemes) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationComponents 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, + 'security_schemes') and self.security_schemes is not None: + if isinstance(self.security_schemes, dict): + _dict['securitySchemes'] = self.security_schemes + else: + _dict['securitySchemes'] = self.security_schemes.to_dict() + 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 ProviderSpecificationComponents object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderSpecificationComponents') -> 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: 'ProviderSpecificationComponents') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecificationComponentsSecuritySchemes: + """ + The definition of the security scheme for the provider. + + :param str authentication_method: (optional) The authentication method required + for requests made from watsonx Assistant to the conversational skill provider. + :param ProviderSpecificationComponentsSecuritySchemesBasic basic: (optional) + Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings for + oauth2 authentication. + """ + + def __init__( + self, + *, + authentication_method: Optional[str] = None, + basic: Optional[ + 'ProviderSpecificationComponentsSecuritySchemesBasic'] = None, + oauth2: Optional['ProviderAuthenticationOAuth2'] = None, + ) -> None: + """ + Initialize a ProviderSpecificationComponentsSecuritySchemes object. + + :param str authentication_method: (optional) The authentication method + required for requests made from watsonx Assistant to the conversational + skill provider. + :param ProviderSpecificationComponentsSecuritySchemesBasic basic: + (optional) Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings + for oauth2 authentication. + """ + self.authentication_method = authentication_method + self.basic = basic + self.oauth2 = oauth2 + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'ProviderSpecificationComponentsSecuritySchemes': + """Initialize a ProviderSpecificationComponentsSecuritySchemes object from a json dictionary.""" + args = {} + if (authentication_method := + _dict.get('authentication_method')) is not None: + args['authentication_method'] = authentication_method + if (basic := _dict.get('basic')) is not None: + args[ + 'basic'] = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict( + basic) + if (oauth2 := _dict.get('oauth2')) is not None: + args['oauth2'] = ProviderAuthenticationOAuth2.from_dict(oauth2) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationComponentsSecuritySchemes 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, 'authentication_method' + ) and self.authentication_method is not None: + _dict['authentication_method'] = self.authentication_method + if hasattr(self, 'basic') and self.basic is not None: + if isinstance(self.basic, dict): + _dict['basic'] = self.basic + else: + _dict['basic'] = self.basic.to_dict() + if hasattr(self, 'oauth2') and self.oauth2 is not None: + if isinstance(self.oauth2, dict): + _dict['oauth2'] = self.oauth2 + else: + _dict['oauth2'] = self.oauth2.to_dict() + 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 ProviderSpecificationComponentsSecuritySchemes object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'ProviderSpecificationComponentsSecuritySchemes') -> 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: 'ProviderSpecificationComponentsSecuritySchemes') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class AuthenticationMethodEnum(str, Enum): + """ + The authentication method required for requests made from watsonx Assistant to the + conversational skill provider. + """ + + BASIC = 'basic' + BEARER = 'bearer' + API_KEY = 'api_key' + OAUTH2 = 'oauth2' + NONE = 'none' + + +class ProviderSpecificationComponentsSecuritySchemesBasic: + """ + Non-private settings for basic access authentication. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username for + basic access authentication. + """ + + def __init__( + self, + *, + username: Optional['ProviderAuthenticationTypeAndValue'] = None, + ) -> None: + """ + Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object. + + :param ProviderAuthenticationTypeAndValue username: (optional) The username + for basic access authentication. + """ + self.username = username + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'ProviderSpecificationComponentsSecuritySchemesBasic': + """Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + args = {} + if (username := _dict.get('username')) is not None: + args['username'] = ProviderAuthenticationTypeAndValue.from_dict( + username) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationComponentsSecuritySchemesBasic 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, 'username') and self.username is not None: + if isinstance(self.username, dict): + _dict['username'] = self.username + else: + _dict['username'] = self.username.to_dict() + 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 ProviderSpecificationComponentsSecuritySchemesBasic object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'ProviderSpecificationComponentsSecuritySchemesBasic' + ) -> 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: 'ProviderSpecificationComponentsSecuritySchemesBasic' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderSpecificationServersItem: + """ + ProviderSpecificationServersItem. + + :param str url: (optional) The URL of the conversational skill provider. + """ + + def __init__( + self, + *, + url: Optional[str] = None, + ) -> None: + """ + Initialize a ProviderSpecificationServersItem object. + + :param str url: (optional) The URL of the conversational skill provider. + """ + self.url = url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderSpecificationServersItem': + """Initialize a ProviderSpecificationServersItem object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderSpecificationServersItem 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, 'url') and self.url is not None: + _dict['url'] = self.url + 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 ProviderSpecificationServersItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderSpecificationServersItem') -> 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: 'ProviderSpecificationServersItem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Release: + """ + Release. + + :param str release: (optional) The name of the release. The name is the version + number (an integer), returned as a string. + :param str description: (optional) The description of the release. + :param List[EnvironmentReference] environment_references: (optional) An array of + objects describing the environments where this release has been deployed. + :param ReleaseContent content: (optional) An object identifying the versionable + content objects (such as skill snapshots) that are included in the release. + :param str status: (optional) The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. + """ + + def __init__( + self, + *, + release: Optional[str] = None, + description: Optional[str] = None, + environment_references: Optional[List['EnvironmentReference']] = None, + content: Optional['ReleaseContent'] = None, + status: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, + ) -> None: + """ + Initialize a Release object. + + :param str description: (optional) The description of the release. + """ + self.release = release + self.description = description + self.environment_references = environment_references + self.content = content + self.status = status + self.created = created + self.updated = updated + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Release': + """Initialize a Release object from a json dictionary.""" + args = {} + if (release := _dict.get('release')) is not None: + args['release'] = release + if (description := _dict.get('description')) is not None: + args['description'] = description + if (environment_references := + _dict.get('environment_references')) is not None: + args['environment_references'] = [ + EnvironmentReference.from_dict(v) + for v in environment_references + ] + if (content := _dict.get('content')) is not None: + args['content'] = ReleaseContent.from_dict(content) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Release 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, 'release') and getattr(self, 'release') is not None: + _dict['release'] = getattr(self, 'release') + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'environment_references') and getattr( + self, 'environment_references') is not None: + environment_references_list = [] + for v in getattr(self, 'environment_references'): + if isinstance(v, dict): + environment_references_list.append(v) + else: + environment_references_list.append(v.to_dict()) + _dict['environment_references'] = environment_references_list + if hasattr(self, 'content') and getattr(self, 'content') is not None: + if isinstance(getattr(self, 'content'), dict): + _dict['content'] = getattr(self, 'content') + else: + _dict['content'] = getattr(self, 'content').to_dict() + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + 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 Release object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Release') -> 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: 'Release') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + + +class ReleaseCollection: + """ + ReleaseCollection. + + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). + """ + + def __init__( + self, + releases: List['Release'], + pagination: 'Pagination', + ) -> None: + """ + Initialize a ReleaseCollection object. + + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). + """ + self.releases = releases + self.pagination = pagination + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': + """Initialize a ReleaseCollection object from a json dictionary.""" + args = {} + if (releases := _dict.get('releases')) is not None: + args['releases'] = [Release.from_dict(v) for v in releases] + else: + raise ValueError( + 'Required property \'releases\' not present in ReleaseCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in ReleaseCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseCollection 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, 'releases') and self.releases is not None: + releases_list = [] + for v in self.releases: + if isinstance(v, dict): + releases_list.append(v) + else: + releases_list.append(v.to_dict()) + _dict['releases'] = releases_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination + else: + _dict['pagination'] = self.pagination.to_dict() + 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 ReleaseCollection object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseCollection') -> 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: 'ReleaseCollection') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseContent: + """ + An object identifying the versionable content objects (such as skill snapshots) that + are included in the release. + + :param List[ReleaseSkill] skills: (optional) The skill snapshots that are + included in the release. + """ + + def __init__( + self, + *, + skills: Optional[List['ReleaseSkill']] = None, + ) -> None: + """ + Initialize a ReleaseContent object. + + """ + self.skills = skills + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseContent': + """Initialize a ReleaseContent object from a json dictionary.""" + args = {} + if (skills := _dict.get('skills')) is not None: + args['skills'] = [ReleaseSkill.from_dict(v) for v in skills] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseContent 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, 'skills') and getattr(self, 'skills') is not None: + skills_list = [] + for v in getattr(self, 'skills'): + if isinstance(v, dict): + skills_list.append(v) + else: + skills_list.append(v.to_dict()) + _dict['skills'] = skills_list + 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 ReleaseContent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseContent') -> 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: 'ReleaseContent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ReleaseSkill: + """ + ReleaseSkill. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is saved as + part of the release (for example, `draft` or `1`). + """ + + def __init__( + self, + skill_id: str, + *, + type: Optional[str] = None, + snapshot: Optional[str] = None, + ) -> None: + """ + Initialize a ReleaseSkill object. + + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is + saved as part of the release (for example, `draft` or `1`). + """ + self.skill_id = skill_id + self.type = type + self.snapshot = snapshot + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': + """Initialize a ReleaseSkill object from a json dictionary.""" + args = {} + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + else: + raise ValueError( + 'Required property \'skill_id\' not present in ReleaseSkill JSON' + ) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ReleaseSkill 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, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + 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 ReleaseSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseSkill') -> 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: 'ReleaseSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of the skill. + """ + + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + + +class RequestAnalytics: + """ + An optional object containing analytics data. Currently, this data is used only for + events sent to the Segment extension. + + :param str browser: (optional) The browser that was used to send the message + that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to send + the message that triggered the event. + """ + + def __init__( + self, + *, + browser: Optional[str] = None, + device: Optional[str] = None, + page_url: Optional[str] = None, + ) -> None: + """ + Initialize a RequestAnalytics object. + + :param str browser: (optional) The browser that was used to send the + message that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to + send the message that triggered the event. + """ + self.browser = browser + self.device = device + self.page_url = page_url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': + """Initialize a RequestAnalytics object from a json dictionary.""" + args = {} + if (browser := _dict.get('browser')) is not None: + args['browser'] = browser + if (device := _dict.get('device')) is not None: + args['device'] = device + if (page_url := _dict.get('pageUrl')) is not None: + args['page_url'] = page_url + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RequestAnalytics 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, 'browser') and self.browser is not None: + _dict['browser'] = self.browser + if hasattr(self, 'device') and self.device is not None: + _dict['device'] = self.device + if hasattr(self, 'page_url') and self.page_url is not None: + _dict['pageUrl'] = self.page_url + 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 RequestAnalytics object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RequestAnalytics') -> 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: 'RequestAnalytics') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericChannel: + """ + ResponseGenericChannel. + + :param str channel: (optional) A channel for which the response is intended. + """ + + def __init__( + self, + *, + channel: Optional[str] = None, + ) -> None: + """ + Initialize a ResponseGenericChannel object. + + :param str channel: (optional) A channel for which the response is + intended. + """ + self.channel = channel + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': + """Initialize a ResponseGenericChannel object from a json dictionary.""" + args = {} + if (channel := _dict.get('channel')) is not None: + args['channel'] = channel + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericChannel 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, 'channel') and self.channel is not None: + _dict['channel'] = self.channel + 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 ResponseGenericChannel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericChannel') -> 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: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntity: + """ + The entity value that was recognized in the user input. + + :param str entity: An entity detected in the input. + :param List[int] location: (optional) An array of zero-based character offsets + that indicate where the detected entity values begin and end in the input text. + :param str value: The term in the input text that was recognized as an entity + value. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized 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. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill (if + enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__( + self, + entity: str, + value: str, + *, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + groups: Optional[List['CaptureGroup']] = None, + interpretation: Optional['RuntimeEntityInterpretation'] = None, + alternatives: Optional[List['RuntimeEntityAlternative']] = None, + role: Optional['RuntimeEntityRole'] = None, + skill: Optional[str] = None, + ) -> None: + """ + Initialize a RuntimeEntity object. + + :param str entity: An entity detected in the input. + :param str value: The term in the input text that was recognized as an + entity value. + :param List[int] location: (optional) An array of zero-based character + offsets that indicate where the detected entity values begin and end in the + input text. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized 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. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.entity = entity + self.location = location + self.value = value + self.confidence = confidence + self.groups = groups + self.interpretation = interpretation + self.alternatives = alternatives + self.role = role + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': + """Initialize a RuntimeEntity object from a json dictionary.""" + args = {} + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity + else: + raise ValueError( + 'Required property \'entity\' not present in RuntimeEntity JSON' + ) + if (location := _dict.get('location')) is not None: + args['location'] = location + if (value := _dict.get('value')) is not None: + args['value'] = value + else: + raise ValueError( + 'Required property \'value\' not present in RuntimeEntity JSON') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (groups := _dict.get('groups')) is not None: + args['groups'] = [CaptureGroup.from_dict(v) for v in groups] + if (interpretation := _dict.get('interpretation')) is not None: + args['interpretation'] = RuntimeEntityInterpretation.from_dict( + interpretation) + if (alternatives := _dict.get('alternatives')) is not None: + args['alternatives'] = [ + RuntimeEntityAlternative.from_dict(v) for v in alternatives + ] + if (role := _dict.get('role')) is not None: + args['role'] = RuntimeEntityRole.from_dict(role) + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntity 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, 'entity') and self.entity is not None: + _dict['entity'] = self.entity + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + 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 + if hasattr(self, 'groups') and self.groups is not None: + groups_list = [] + for v in self.groups: + if isinstance(v, dict): + groups_list.append(v) + else: + groups_list.append(v.to_dict()) + _dict['groups'] = groups_list + if hasattr(self, 'interpretation') and self.interpretation is not None: + if isinstance(self.interpretation, dict): + _dict['interpretation'] = self.interpretation + else: + _dict['interpretation'] = self.interpretation.to_dict() + if hasattr(self, 'alternatives') and self.alternatives is not None: + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list + if hasattr(self, 'role') and self.role is not None: + if isinstance(self.role, dict): + _dict['role'] = self.role + else: + _dict['role'] = self.role.to_dict() + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + 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 RuntimeEntity object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntity') -> 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: 'RuntimeEntity') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntityAlternative: + """ + An alternative value for the recognized entity. + + :param str value: (optional) The entity value that was recognized in the user + input. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized entity. + """ + + def __init__( + self, + *, + value: Optional[str] = None, + confidence: Optional[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 + 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 = {} + if (value := _dict.get('value')) is not None: + args['value'] = value + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = 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. + + :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`). + """ + + def __init__( + self, + *, + calendar_type: Optional[str] = None, + datetime_link: Optional[str] = None, + festival: Optional[str] = None, + granularity: Optional[str] = None, + range_link: Optional[str] = None, + range_modifier: Optional[str] = None, relative_day: Optional[float] = None, relative_month: Optional[float] = None, relative_week: Optional[float] = None, @@ -7913,235 +10611,2611 @@ def __init__( timezone: Optional[str] = None, ) -> None: """ - Initialize a RuntimeEntityInterpretation object. + 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 = {} + if (calendar_type := _dict.get('calendar_type')) is not None: + args['calendar_type'] = calendar_type + if (datetime_link := _dict.get('datetime_link')) is not None: + args['datetime_link'] = datetime_link + if (festival := _dict.get('festival')) is not None: + args['festival'] = festival + if (granularity := _dict.get('granularity')) is not None: + args['granularity'] = granularity + if (range_link := _dict.get('range_link')) is not None: + args['range_link'] = range_link + if (range_modifier := _dict.get('range_modifier')) is not None: + args['range_modifier'] = range_modifier + if (relative_day := _dict.get('relative_day')) is not None: + args['relative_day'] = relative_day + if (relative_month := _dict.get('relative_month')) is not None: + args['relative_month'] = relative_month + if (relative_week := _dict.get('relative_week')) is not None: + args['relative_week'] = relative_week + if (relative_weekend := _dict.get('relative_weekend')) is not None: + args['relative_weekend'] = relative_weekend + if (relative_year := _dict.get('relative_year')) is not None: + args['relative_year'] = relative_year + if (specific_day := _dict.get('specific_day')) is not None: + args['specific_day'] = specific_day + if (specific_day_of_week := + _dict.get('specific_day_of_week')) is not None: + args['specific_day_of_week'] = specific_day_of_week + if (specific_month := _dict.get('specific_month')) is not None: + args['specific_month'] = specific_month + if (specific_quarter := _dict.get('specific_quarter')) is not None: + args['specific_quarter'] = specific_quarter + if (specific_year := _dict.get('specific_year')) is not None: + args['specific_year'] = specific_year + if (numeric_value := _dict.get('numeric_value')) is not None: + args['numeric_value'] = numeric_value + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype + if (part_of_day := _dict.get('part_of_day')) is not None: + args['part_of_day'] = part_of_day + if (relative_hour := _dict.get('relative_hour')) is not None: + args['relative_hour'] = relative_hour + if (relative_minute := _dict.get('relative_minute')) is not None: + args['relative_minute'] = relative_minute + if (relative_second := _dict.get('relative_second')) is not None: + args['relative_second'] = relative_second + if (specific_hour := _dict.get('specific_hour')) is not None: + args['specific_hour'] = specific_hour + if (specific_minute := _dict.get('specific_minute')) is not None: + args['specific_minute'] = specific_minute + if (specific_second := _dict.get('specific_second')) is not None: + args['specific_second'] = specific_second + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = 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(str, 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. + + :param str type: (optional) The relationship of the entity to the range. + """ + + def __init__( + self, + *, + type: Optional[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 = {} + if (type := _dict.get('type')) is not None: + args['type'] = 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(str, 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. + + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. + :param str skill: (optional) The skill that identified the intent. Currently, + the only possible values are `main skill` for the dialog skill (if enabled) and + `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__( + self, + intent: str, + *, + confidence: Optional[float] = None, + skill: Optional[str] = None, + ) -> None: + """ + Initialize a RuntimeIntent object. + + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. + :param str skill: (optional) The skill that identified the intent. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.intent = intent + self.confidence = confidence + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': + """Initialize a RuntimeIntent object from a json dictionary.""" + args = {} + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent + else: + raise ValueError( + 'Required property \'intent\' not present in RuntimeIntent JSON' + ) + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeIntent 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, 'intent') and self.intent is not None: + _dict['intent'] = self.intent + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + 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 RuntimeIntent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeIntent') -> 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: 'RuntimeIntent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGeneric: + """ + RuntimeResponseGeneric. + + """ + + def __init__(self,) -> None: + """ + Initialize a RuntimeResponseGeneric object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' + mapping[ + 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + mapping[ + 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' + mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' + mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' + mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' + mapping[ + 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' + mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' + mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + mapping[ + 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class SearchResult: + """ + SearchResult. + + :param str id: The unique identifier of the document in the Discovery service + collection. + This property is included in responses from search skills, which are available + only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search result + metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is taken + from an abstract, summary, or highlight field in the Discovery service response, + as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken from + a title or name field in the Discovery service response, as specified in the + search skill configuration. + :param str url: (optional) The URL of the original data object in its native + data source. + :param SearchResultHighlight highlight: (optional) An object containing segments + of text from search results with query-matching text highlighted using HTML + `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying segments + of text within the result that were identified as direct answers to the search + query. Currently, only the single answer with the highest confidence (if any) is + returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + + def __init__( + self, + id: str, + result_metadata: 'SearchResultMetadata', + *, + body: Optional[str] = None, + title: Optional[str] = None, + url: Optional[str] = None, + highlight: Optional['SearchResultHighlight'] = None, + answers: Optional[List['SearchResultAnswer']] = None, + ) -> None: + """ + Initialize a SearchResult object. + + :param str id: The unique identifier of the document in the Discovery + service collection. + This property is included in responses from search skills, which are + available only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search + result metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is + taken from an abstract, summary, or highlight field in the Discovery + service response, as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken + from a title or name field in the Discovery service response, as specified + in the search skill configuration. + :param str url: (optional) The URL of the original data object in its + native data source. + :param SearchResultHighlight highlight: (optional) An object containing + segments of text from search results with query-matching text highlighted + using HTML `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying + segments of text within the result that were identified as direct answers + to the search query. Currently, only the single answer with the highest + confidence (if any) is returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.id = id + self.result_metadata = result_metadata + self.body = body + self.title = title + self.url = url + self.highlight = highlight + self.answers = answers + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResult': + """Initialize a SearchResult object from a json dictionary.""" + args = {} + if (id := _dict.get('id')) is not None: + args['id'] = id + else: + raise ValueError( + 'Required property \'id\' not present in SearchResult JSON') + if (result_metadata := _dict.get('result_metadata')) is not None: + args['result_metadata'] = SearchResultMetadata.from_dict( + result_metadata) + else: + raise ValueError( + 'Required property \'result_metadata\' not present in SearchResult JSON' + ) + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = SearchResultHighlight.from_dict(highlight) + if (answers := _dict.get('answers')) is not None: + args['answers'] = [SearchResultAnswer.from_dict(v) for v in answers] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResult 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, 'id') and self.id is not None: + _dict['id'] = self.id + if hasattr(self, + 'result_metadata') and self.result_metadata is not None: + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'highlight') and self.highlight is not None: + if isinstance(self.highlight, dict): + _dict['highlight'] = self.highlight + else: + _dict['highlight'] = self.highlight.to_dict() + if hasattr(self, 'answers') and self.answers is not None: + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list + 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 SearchResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResult') -> 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: 'SearchResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultAnswer: + """ + An object specifing a segment of text that was identified as a direct answer to the + search query. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned by the + Discovery service. + """ + + def __init__( + self, + text: str, + confidence: float, + ) -> None: + """ + Initialize a SearchResultAnswer object. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned + by the Discovery service. + """ + self.text = text + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': + """Initialize a SearchResultAnswer object from a json dictionary.""" + args = {} + if (text := _dict.get('text')) is not None: + args['text'] = text + else: + raise ValueError( + 'Required property \'text\' not present in SearchResultAnswer JSON' + ) + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + else: + raise ValueError( + 'Required property \'confidence\' not present in SearchResultAnswer JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultAnswer 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, 'text') and self.text is not None: + _dict['text'] = self.text + 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 SearchResultAnswer object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultAnswer') -> 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: 'SearchResultAnswer') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultHighlight: + """ + An object containing segments of text from search results with query-matching text + highlighted using HTML `` tags. + + :param List[str] body: (optional) An array of strings containing segments taken + from body text in the search results, with query-matching substrings + highlighted. + :param List[str] title: (optional) An array of strings containing segments taken + from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments taken + from URLs in the search results, with query-matching substrings highlighted. + + This type supports additional properties of type List[str]. An array of strings + containing segments taken from a field in the search results that is not mapped to the + `body`, `title`, or `url` property, with query-matching substrings highlighted. The + property name is the name of the field in the Discovery collection. + """ + + # The set of defined properties for the class + _properties = frozenset(['body', 'title', 'url']) + + def __init__( + self, + *, + body: Optional[List[str]] = None, + title: Optional[List[str]] = None, + url: Optional[List[str]] = None, + **kwargs: Optional[List[str]], + ) -> None: + """ + Initialize a SearchResultHighlight object. + + :param List[str] body: (optional) An array of strings containing segments + taken from body text in the search results, with query-matching substrings + highlighted. + :param List[str] title: (optional) An array of strings containing segments + taken from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments + taken from URLs in the search results, with query-matching substrings + highlighted. + :param List[str] **kwargs: (optional) An array of strings containing + segments taken from a field in the search results that is not mapped to the + `body`, `title`, or `url` property, with query-matching substrings + highlighted. The property name is the name of the field in the Discovery + collection. + """ + self.body = body + self.title = title + self.url = url + for k, v in kwargs.items(): + if k not in SearchResultHighlight._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[Foo]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + setattr(self, k, _v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': + """Initialize a SearchResultHighlight object from a json dictionary.""" + args = {} + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + args[k] = _v + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultHighlight 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, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return the additional properties from this instance of SearchResultHighlight in the form of a dict.""" + _dict = {} + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of additional properties in this instance of SearchResultHighlight""" + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + delattr(self, k) + for k, v in _dict.items(): + if k not in SearchResultHighlight._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + setattr(self, k, _v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + def __str__(self) -> str: + """Return a `str` version of this SearchResultHighlight object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultHighlight') -> 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: 'SearchResultHighlight') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultMetadata: + """ + An object containing search result metadata from the Discovery service. + + :param float confidence: (optional) The confidence score for the given result, + as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher score + indicates a greater match to the query parameters. + """ + + def __init__( + self, + *, + confidence: Optional[float] = None, + score: Optional[float] = None, + ) -> None: + """ + Initialize a SearchResultMetadata object. + + :param float confidence: (optional) The confidence score for the given + result, as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher + score indicates a greater match to the query parameters. + """ + self.confidence = confidence + self.score = score + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': + """Initialize a SearchResultMetadata object from a json dictionary.""" + args = {} + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (score := _dict.get('score')) is not None: + args['score'] = score + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultMetadata 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, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score + 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 SearchResultMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultMetadata') -> 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: 'SearchResultMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettings: + """ + An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and are not + included in **Export skills** responses. + + :param SearchSettingsDiscovery discovery: Configuration settings for the Watson + Discovery service instance used by the search integration. + :param SearchSettingsMessages messages: The messages included with responses + from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between fields in + the Watson Discovery collection and properties in the search response. + :param SearchSettingsElasticSearch elastic_search: (optional) Configuration + settings for the Elasticsearch service used by the search integration. You can + provide either basic auth or apiKey auth. + :param SearchSettingsConversationalSearch conversational_search: (optional) + Configuration settings for conversational search. + :param SearchSettingsServerSideSearch server_side_search: (optional) + Configuration settings for the server-side search service used by the search + integration. You can provide either basic auth, apiKey auth or none. + :param SearchSettingsClientSideSearch client_side_search: (optional) + Configuration settings for the client-side search service or server-side search + service used by the search integration. + """ + + def __init__( + self, + discovery: 'SearchSettingsDiscovery', + messages: 'SearchSettingsMessages', + schema_mapping: 'SearchSettingsSchemaMapping', + *, + elastic_search: Optional['SearchSettingsElasticSearch'] = None, + conversational_search: Optional[ + 'SearchSettingsConversationalSearch'] = None, + server_side_search: Optional['SearchSettingsServerSideSearch'] = None, + client_side_search: Optional['SearchSettingsClientSideSearch'] = None, + ) -> None: + """ + Initialize a SearchSettings object. + + :param SearchSettingsDiscovery discovery: Configuration settings for the + Watson Discovery service instance used by the search integration. + :param SearchSettingsMessages messages: The messages included with + responses from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between + fields in the Watson Discovery collection and properties in the search + response. + :param SearchSettingsElasticSearch elastic_search: (optional) Configuration + settings for the Elasticsearch service used by the search integration. You + can provide either basic auth or apiKey auth. + :param SearchSettingsConversationalSearch conversational_search: (optional) + Configuration settings for conversational search. + :param SearchSettingsServerSideSearch server_side_search: (optional) + Configuration settings for the server-side search service used by the + search integration. You can provide either basic auth, apiKey auth or none. + :param SearchSettingsClientSideSearch client_side_search: (optional) + Configuration settings for the client-side search service or server-side + search service used by the search integration. + """ + self.discovery = discovery + self.messages = messages + self.schema_mapping = schema_mapping + self.elastic_search = elastic_search + self.conversational_search = conversational_search + self.server_side_search = server_side_search + self.client_side_search = client_side_search + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettings': + """Initialize a SearchSettings object from a json dictionary.""" + args = {} + if (discovery := _dict.get('discovery')) is not None: + args['discovery'] = SearchSettingsDiscovery.from_dict(discovery) + else: + raise ValueError( + 'Required property \'discovery\' not present in SearchSettings JSON' + ) + if (messages := _dict.get('messages')) is not None: + args['messages'] = SearchSettingsMessages.from_dict(messages) + else: + raise ValueError( + 'Required property \'messages\' not present in SearchSettings JSON' + ) + if (schema_mapping := _dict.get('schema_mapping')) is not None: + args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( + schema_mapping) + else: + raise ValueError( + 'Required property \'schema_mapping\' not present in SearchSettings JSON' + ) + if (elastic_search := _dict.get('elastic_search')) is not None: + args['elastic_search'] = SearchSettingsElasticSearch.from_dict( + elastic_search) + if (conversational_search := + _dict.get('conversational_search')) is not None: + args[ + 'conversational_search'] = SearchSettingsConversationalSearch.from_dict( + conversational_search) + if (server_side_search := _dict.get('server_side_search')) is not None: + args[ + 'server_side_search'] = SearchSettingsServerSideSearch.from_dict( + server_side_search) + if (client_side_search := _dict.get('client_side_search')) is not None: + args[ + 'client_side_search'] = SearchSettingsClientSideSearch.from_dict( + client_side_search) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettings 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, 'discovery') and self.discovery is not None: + if isinstance(self.discovery, dict): + _dict['discovery'] = self.discovery + else: + _dict['discovery'] = self.discovery.to_dict() + if hasattr(self, 'messages') and self.messages is not None: + if isinstance(self.messages, dict): + _dict['messages'] = self.messages + else: + _dict['messages'] = self.messages.to_dict() + if hasattr(self, 'schema_mapping') and self.schema_mapping is not None: + if isinstance(self.schema_mapping, dict): + _dict['schema_mapping'] = self.schema_mapping + else: + _dict['schema_mapping'] = self.schema_mapping.to_dict() + if hasattr(self, 'elastic_search') and self.elastic_search is not None: + if isinstance(self.elastic_search, dict): + _dict['elastic_search'] = self.elastic_search + else: + _dict['elastic_search'] = self.elastic_search.to_dict() + if hasattr(self, 'conversational_search' + ) and self.conversational_search is not None: + if isinstance(self.conversational_search, dict): + _dict['conversational_search'] = self.conversational_search + else: + _dict[ + 'conversational_search'] = self.conversational_search.to_dict( + ) + if hasattr( + self, + 'server_side_search') and self.server_side_search is not None: + if isinstance(self.server_side_search, dict): + _dict['server_side_search'] = self.server_side_search + else: + _dict['server_side_search'] = self.server_side_search.to_dict() + if hasattr( + self, + 'client_side_search') and self.client_side_search is not None: + if isinstance(self.client_side_search, dict): + _dict['client_side_search'] = self.client_side_search + else: + _dict['client_side_search'] = self.client_side_search.to_dict() + 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 SearchSettings object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettings') -> 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: 'SearchSettings') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsClientSideSearch: + """ + Configuration settings for the client-side search service or server-side search + service used by the search integration. + + :param str filter: (optional) The filter string that is applied to the search + results. + :param dict metadata: (optional) The metadata object. + """ + + def __init__( + self, + *, + filter: Optional[str] = None, + metadata: Optional[dict] = None, + ) -> None: + """ + Initialize a SearchSettingsClientSideSearch object. + + :param str filter: (optional) The filter string that is applied to the + search results. + :param dict metadata: (optional) The metadata object. + """ + self.filter = filter + self.metadata = metadata + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsClientSideSearch': + """Initialize a SearchSettingsClientSideSearch object from a json dictionary.""" + args = {} + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsClientSideSearch 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, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + 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 SearchSettingsClientSideSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsClientSideSearch') -> 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: 'SearchSettingsClientSideSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsConversationalSearch: + """ + Configuration settings for conversational search. + + :param bool enabled: Whether to enable conversational search. + :param SearchSettingsConversationalSearchResponseLength response_length: + (optional) + :param SearchSettingsConversationalSearchSearchConfidence search_confidence: + (optional) + """ + + def __init__( + self, + enabled: bool, + *, + response_length: Optional[ + 'SearchSettingsConversationalSearchResponseLength'] = None, + search_confidence: Optional[ + 'SearchSettingsConversationalSearchSearchConfidence'] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearch object. + + :param bool enabled: Whether to enable conversational search. + :param SearchSettingsConversationalSearchResponseLength response_length: + (optional) + :param SearchSettingsConversationalSearchSearchConfidence + search_confidence: (optional) + """ + self.enabled = enabled + self.response_length = response_length + self.search_confidence = search_confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsConversationalSearch': + """Initialize a SearchSettingsConversationalSearch object from a json dictionary.""" + args = {} + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + else: + raise ValueError( + 'Required property \'enabled\' not present in SearchSettingsConversationalSearch JSON' + ) + if (response_length := _dict.get('response_length')) is not None: + args[ + 'response_length'] = SearchSettingsConversationalSearchResponseLength.from_dict( + response_length) + if (search_confidence := _dict.get('search_confidence')) is not None: + args[ + 'search_confidence'] = SearchSettingsConversationalSearchSearchConfidence.from_dict( + search_confidence) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearch 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 + if hasattr(self, + 'response_length') and self.response_length is not None: + if isinstance(self.response_length, dict): + _dict['response_length'] = self.response_length + else: + _dict['response_length'] = self.response_length.to_dict() + if hasattr(self, + 'search_confidence') and self.search_confidence is not None: + if isinstance(self.search_confidence, dict): + _dict['search_confidence'] = self.search_confidence + else: + _dict['search_confidence'] = self.search_confidence.to_dict() + 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 SearchSettingsConversationalSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsConversationalSearch') -> 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: 'SearchSettingsConversationalSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsConversationalSearchResponseLength: + """ + SearchSettingsConversationalSearchResponseLength. + + :param str option: (optional) The response length option. It controls the length + of the generated response. + """ + + def __init__( + self, + *, + option: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearchResponseLength object. + + :param str option: (optional) The response length option. It controls the + length of the generated response. + """ + self.option = option + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'SearchSettingsConversationalSearchResponseLength': + """Initialize a SearchSettingsConversationalSearchResponseLength object from a json dictionary.""" + args = {} + if (option := _dict.get('option')) is not None: + args['option'] = option + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearchResponseLength 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, 'option') and self.option is not None: + _dict['option'] = self.option + 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 SearchSettingsConversationalSearchResponseLength object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'SearchSettingsConversationalSearchResponseLength') -> 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: 'SearchSettingsConversationalSearchResponseLength') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class OptionEnum(str, Enum): + """ + The response length option. It controls the length of the generated response. + """ + + CONCISE = 'concise' + MODERATE = 'moderate' + VERBOSE = 'verbose' + + +class SearchSettingsConversationalSearchSearchConfidence: + """ + SearchSettingsConversationalSearchSearchConfidence. + + :param str threshold: (optional) The search confidence threshold. + It controls the tendency for conversational search to produce “I don't know” + answers. + """ + + def __init__( + self, + *, + threshold: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearchSearchConfidence object. + + :param str threshold: (optional) The search confidence threshold. + It controls the tendency for conversational search to produce “I don't + know” answers. + """ + self.threshold = threshold + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'SearchSettingsConversationalSearchSearchConfidence': + """Initialize a SearchSettingsConversationalSearchSearchConfidence object from a json dictionary.""" + args = {} + if (threshold := _dict.get('threshold')) is not None: + args['threshold'] = threshold + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearchSearchConfidence 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, 'threshold') and self.threshold is not None: + _dict['threshold'] = self.threshold + 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 SearchSettingsConversationalSearchSearchConfidence object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'SearchSettingsConversationalSearchSearchConfidence' + ) -> 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: 'SearchSettingsConversationalSearchSearchConfidence' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ThresholdEnum(str, Enum): + """ + The search confidence threshold. + It controls the tendency for conversational search to produce “I don't know” + answers. + """ + + RARELY = 'rarely' + LESS_OFTEN = 'less_often' + MORE_OFTEN = 'more_often' + MOST_OFTEN = 'most_often' + + +class SearchSettingsDiscovery: + """ + Configuration settings for the Watson Discovery service instance used by the search + integration. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param int max_primary_results: (optional) The maximum number of primary results + to include in the response. + :param int max_total_results: (optional) The maximum total number of primary and + additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence threshold + for included results. Any results with a confidence below this threshold will be + discarded. + :param bool highlight: (optional) Whether to include the most relevant passages + of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding feature + to emphasize answers within highlighted passages. This property is ignored if + **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + """ + + def __init__( + self, + instance_id: str, + project_id: str, + url: str, + authentication: 'SearchSettingsDiscoveryAuthentication', + *, + max_primary_results: Optional[int] = None, + max_total_results: Optional[int] = None, + confidence_threshold: Optional[float] = None, + highlight: Optional[bool] = None, + find_answers: Optional[bool] = None, + ) -> None: + """ + Initialize a SearchSettingsDiscovery object. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + :param int max_primary_results: (optional) The maximum number of primary + results to include in the response. + :param int max_total_results: (optional) The maximum total number of + primary and additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence + threshold for included results. Any results with a confidence below this + threshold will be discarded. + :param bool highlight: (optional) Whether to include the most relevant + passages of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding + feature to emphasize answers within highlighted passages. This property is + ignored if **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.instance_id = instance_id + self.project_id = project_id + self.url = url + self.max_primary_results = max_primary_results + self.max_total_results = max_total_results + self.confidence_threshold = confidence_threshold + self.highlight = highlight + self.find_answers = find_answers + self.authentication = authentication + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': + """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + args = {} + if (instance_id := _dict.get('instance_id')) is not None: + args['instance_id'] = instance_id + else: + raise ValueError( + 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' + ) + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id + else: + raise ValueError( + 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' + ) + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsDiscovery JSON' + ) + if (max_primary_results := + _dict.get('max_primary_results')) is not None: + args['max_primary_results'] = max_primary_results + if (max_total_results := _dict.get('max_total_results')) is not None: + args['max_total_results'] = max_total_results + if (confidence_threshold := + _dict.get('confidence_threshold')) is not None: + args['confidence_threshold'] = confidence_threshold + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = highlight + if (find_answers := _dict.get('find_answers')) is not None: + args['find_answers'] = find_answers + if (authentication := _dict.get('authentication')) is not None: + args[ + 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( + authentication) + else: + raise ValueError( + 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscovery 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, 'instance_id') and self.instance_id is not None: + _dict['instance_id'] = self.instance_id + if hasattr(self, 'project_id') and self.project_id is not None: + _dict['project_id'] = self.project_id + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr( + self, + 'max_primary_results') and self.max_primary_results is not None: + _dict['max_primary_results'] = self.max_primary_results + if hasattr(self, + 'max_total_results') and self.max_total_results is not None: + _dict['max_total_results'] = self.max_total_results + if hasattr(self, 'confidence_threshold' + ) and self.confidence_threshold is not None: + _dict['confidence_threshold'] = self.confidence_threshold + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'find_answers') and self.find_answers is not None: + _dict['find_answers'] = self.find_answers + if hasattr(self, 'authentication') and self.authentication is not None: + if isinstance(self.authentication, dict): + _dict['authentication'] = self.authentication + else: + _dict['authentication'] = self.authentication.to_dict() + 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 SearchSettingsDiscovery object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscovery') -> 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: 'SearchSettingsDiscovery') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsDiscoveryAuthentication: + """ + Authentication information for the Watson Discovery service. For more information, see + the [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + + def __init__( + self, + *, + basic: Optional[str] = None, + bearer: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsDiscoveryAuthentication object. + + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + self.basic = basic + self.bearer = bearer + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': + """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + args = {} + if (basic := _dict.get('basic')) is not None: + args['basic'] = basic + if (bearer := _dict.get('bearer')) is not None: + args['bearer'] = bearer + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscoveryAuthentication 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, 'basic') and self.basic is not None: + _dict['basic'] = self.basic + if hasattr(self, 'bearer') and self.bearer is not None: + _dict['bearer'] = self.bearer + 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 SearchSettingsDiscoveryAuthentication object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscoveryAuthentication') -> 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: 'SearchSettingsDiscoveryAuthentication') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsElasticSearch: + """ + Configuration settings for the Elasticsearch service used by the search integration. + You can provide either basic auth or apiKey auth. + + :param str url: The URL for the Elasticsearch service. + :param str port: The port number for the Elasticsearch service URL. + **Note:** It can be omitted if a port number is appended to the URL. + :param str username: (optional) The username of the basic authentication method. + :param str password: (optional) The password of the basic authentication method. + The credentials are not returned due to security reasons. + :param str index: The Elasticsearch index to use for the search integration. + :param List[object] filter: (optional) An array of filters that can be applied + to the search results via the `$FILTER` variable in the `query_body`.For more + information, see [Elasticsearch filter + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/filter-search-results.html). + :param dict query_body: (optional) The Elasticsearch query object. For more + information, see [Elasticsearch search API + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html). + :param str managed_index: (optional) The Elasticsearch index for uploading + documents. It is created automatically when the upload document option is + selected from the user interface. + :param str apikey: (optional) The API key of the apiKey authentication method. + Use either basic auth or apiKey auth. The credentials are not returned due to + security reasons. + """ + + def __init__( + self, + url: str, + port: str, + index: str, + *, + username: Optional[str] = None, + password: Optional[str] = None, + filter: Optional[List[object]] = None, + query_body: Optional[dict] = None, + managed_index: Optional[str] = None, + apikey: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsElasticSearch object. + + :param str url: The URL for the Elasticsearch service. + :param str port: The port number for the Elasticsearch service URL. + **Note:** It can be omitted if a port number is appended to the URL. + :param str index: The Elasticsearch index to use for the search + integration. + :param str username: (optional) The username of the basic authentication + method. + :param str password: (optional) The password of the basic authentication + method. The credentials are not returned due to security reasons. + :param List[object] filter: (optional) An array of filters that can be + applied to the search results via the `$FILTER` variable in the + `query_body`.For more information, see [Elasticsearch filter + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/filter-search-results.html). + :param dict query_body: (optional) The Elasticsearch query object. For more + information, see [Elasticsearch search API + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html). + :param str managed_index: (optional) The Elasticsearch index for uploading + documents. It is created automatically when the upload document option is + selected from the user interface. + :param str apikey: (optional) The API key of the apiKey authentication + method. Use either basic auth or apiKey auth. The credentials are not + returned due to security reasons. + """ + self.url = url + self.port = port + self.username = username + self.password = password + self.index = index + self.filter = filter + self.query_body = query_body + self.managed_index = managed_index + self.apikey = apikey + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsElasticSearch': + """Initialize a SearchSettingsElasticSearch object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsElasticSearch JSON' + ) + if (port := _dict.get('port')) is not None: + args['port'] = port + else: + raise ValueError( + 'Required property \'port\' not present in SearchSettingsElasticSearch JSON' + ) + if (username := _dict.get('username')) is not None: + args['username'] = username + if (password := _dict.get('password')) is not None: + args['password'] = password + if (index := _dict.get('index')) is not None: + args['index'] = index + else: + raise ValueError( + 'Required property \'index\' not present in SearchSettingsElasticSearch JSON' + ) + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (query_body := _dict.get('query_body')) is not None: + args['query_body'] = query_body + if (managed_index := _dict.get('managed_index')) is not None: + args['managed_index'] = managed_index + if (apikey := _dict.get('apikey')) is not None: + args['apikey'] = apikey + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsElasticSearch 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, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'port') and self.port is not None: + _dict['port'] = self.port + if hasattr(self, 'username') and self.username is not None: + _dict['username'] = self.username + if hasattr(self, 'password') and self.password is not None: + _dict['password'] = self.password + if hasattr(self, 'index') and self.index is not None: + _dict['index'] = self.index + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'query_body') and self.query_body is not None: + _dict['query_body'] = self.query_body + if hasattr(self, 'managed_index') and self.managed_index is not None: + _dict['managed_index'] = self.managed_index + if hasattr(self, 'apikey') and self.apikey is not None: + _dict['apikey'] = self.apikey + 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 SearchSettingsElasticSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsElasticSearch') -> 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: 'SearchSettingsElasticSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsMessages: + """ + The messages included with responses from the search integration. + + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is no + result from the query. + """ + + def __init__( + self, + success: str, + error: str, + no_result: str, + ) -> None: + """ + Initialize a SearchSettingsMessages object. + + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is + no result from the query. + """ + self.success = success + self.error = error + self.no_result = no_result + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': + """Initialize a SearchSettingsMessages object from a json dictionary.""" + args = {} + if (success := _dict.get('success')) is not None: + args['success'] = success + else: + raise ValueError( + 'Required property \'success\' not present in SearchSettingsMessages JSON' + ) + if (error := _dict.get('error')) is not None: + args['error'] = error + else: + raise ValueError( + 'Required property \'error\' not present in SearchSettingsMessages JSON' + ) + if (no_result := _dict.get('no_result')) is not None: + args['no_result'] = no_result + else: + raise ValueError( + 'Required property \'no_result\' not present in SearchSettingsMessages JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsMessages 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, 'success') and self.success is not None: + _dict['success'] = self.success + if hasattr(self, 'error') and self.error is not None: + _dict['error'] = self.error + if hasattr(self, 'no_result') and self.no_result is not None: + _dict['no_result'] = self.no_result + 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 SearchSettingsMessages object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsMessages') -> 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: 'SearchSettingsMessages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsSchemaMapping: + """ + The mapping between fields in the Watson Discovery collection and properties in the + search response. + + :param str url: The field in the collection to map to the **url** property of + the response. + :param str body: The field in the collection to map to the **body** property in + the response. + :param str title: The field in the collection to map to the **title** property + for the schema. + """ + + def __init__( + self, + url: str, + body: str, + title: str, + ) -> None: + """ + Initialize a SearchSettingsSchemaMapping object. + + :param str url: The field in the collection to map to the **url** property + of the response. + :param str body: The field in the collection to map to the **body** + property in the response. + :param str title: The field in the collection to map to the **title** + property for the schema. + """ + self.url = url + self.body = body + self.title = title + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': + """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' + ) + if (body := _dict.get('body')) is not None: + args['body'] = body + else: + raise ValueError( + 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' + ) + if (title := _dict.get('title')) is not None: + args['title'] = title + else: + raise ValueError( + 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsSchemaMapping 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, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + 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 SearchSettingsSchemaMapping object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsSchemaMapping') -> 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: 'SearchSettingsSchemaMapping') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsServerSideSearch: + """ + Configuration settings for the server-side search service used by the search + integration. You can provide either basic auth, apiKey auth or none. + + :param str url: The URL of the server-side search service. + :param str port: (optional) The port number of the server-side search service. + :param str username: (optional) The username of the basic authentication method. + :param str password: (optional) The password of the basic authentication method. + The credentials are not returned due to security reasons. + :param str filter: (optional) The filter string that is applied to the search + results. + :param dict metadata: (optional) The metadata object. + :param str apikey: (optional) The API key of the apiKey authentication method. + The credentails are not returned due to security reasons. + :param bool no_auth: (optional) To clear previous auth, specify `no_auth = + true`. + :param str auth_type: (optional) The authorization type that is used. + """ + + def __init__( + self, + url: str, + *, + port: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + filter: Optional[str] = None, + metadata: Optional[dict] = None, + apikey: Optional[str] = None, + no_auth: Optional[bool] = None, + auth_type: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsServerSideSearch object. + + :param str url: The URL of the server-side search service. + :param str port: (optional) The port number of the server-side search + service. + :param str username: (optional) The username of the basic authentication + method. + :param str password: (optional) The password of the basic authentication + method. The credentials are not returned due to security reasons. + :param str filter: (optional) The filter string that is applied to the + search results. + :param dict metadata: (optional) The metadata object. + :param str apikey: (optional) The API key of the apiKey authentication + method. The credentails are not returned due to security reasons. + :param bool no_auth: (optional) To clear previous auth, specify `no_auth = + true`. + :param str auth_type: (optional) The authorization type that is used. + """ + self.url = url + self.port = port + self.username = username + self.password = password + self.filter = filter + self.metadata = metadata + self.apikey = apikey + self.no_auth = no_auth + self.auth_type = auth_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsServerSideSearch': + """Initialize a SearchSettingsServerSideSearch object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsServerSideSearch JSON' + ) + if (port := _dict.get('port')) is not None: + args['port'] = port + if (username := _dict.get('username')) is not None: + args['username'] = username + if (password := _dict.get('password')) is not None: + args['password'] = password + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (apikey := _dict.get('apikey')) is not None: + args['apikey'] = apikey + if (no_auth := _dict.get('no_auth')) is not None: + args['no_auth'] = no_auth + if (auth_type := _dict.get('auth_type')) is not None: + args['auth_type'] = auth_type + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsServerSideSearch 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, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'port') and self.port is not None: + _dict['port'] = self.port + if hasattr(self, 'username') and self.username is not None: + _dict['username'] = self.username + if hasattr(self, 'password') and self.password is not None: + _dict['password'] = self.password + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + if hasattr(self, 'apikey') and self.apikey is not None: + _dict['apikey'] = self.apikey + if hasattr(self, 'no_auth') and self.no_auth is not None: + _dict['no_auth'] = self.no_auth + if hasattr(self, 'auth_type') and self.auth_type is not None: + _dict['auth_type'] = self.auth_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 SearchSettingsServerSideSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsServerSideSearch') -> 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: 'SearchSettingsServerSideSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class AuthTypeEnum(str, Enum): + """ + The authorization type that is used. + """ + + BASIC = 'basic' + APIKEY = 'apikey' + NONE = 'none' + + +class SearchSkillWarning: + """ + A warning describing an error in the search skill configuration. + + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. + """ + + def __init__( + self, + *, + code: Optional[str] = None, + path: Optional[str] = None, + message: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSkillWarning object. + + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. + """ + self.code = code + self.path = path + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': + """Initialize a SearchSkillWarning object from a json dictionary.""" + args = {} + if (code := _dict.get('code')) is not None: + args['code'] = code + if (path := _dict.get('path')) is not None: + args['path'] = path + if (message := _dict.get('message')) is not None: + args['message'] = message + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSkillWarning 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, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + 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 SearchSkillWarning object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSkillWarning') -> 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: 'SearchSkillWarning') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SessionResponse: + """ + SessionResponse. + + :param str session_id: The session ID. + """ + + def __init__( + self, + session_id: str, + ) -> None: + """ + Initialize a SessionResponse object. + + :param str session_id: The session ID. + """ + self.session_id = session_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SessionResponse': + """Initialize a SessionResponse object from a json dictionary.""" + args = {} + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id + else: + raise ValueError( + 'Required property \'session_id\' not present in SessionResponse JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SessionResponse 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, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + 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 SessionResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SessionResponse') -> 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: 'SessionResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Skill: + """ + Skill. + + :param str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :param str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :param str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :param str language: The language of the skill. + :param str type: The type of skill. + """ + + def __init__( + self, + language: str, + type: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, + ) -> None: + """ + Initialize a Skill 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`). + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. """ - 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 + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Skill': + """Initialize a Skill object from a json dictionary.""" args = {} - if (calendar_type := _dict.get('calendar_type')) is not None: - args['calendar_type'] = calendar_type - if (datetime_link := _dict.get('datetime_link')) is not None: - args['datetime_link'] = datetime_link - if (festival := _dict.get('festival')) is not None: - args['festival'] = festival - if (granularity := _dict.get('granularity')) is not None: - args['granularity'] = granularity - if (range_link := _dict.get('range_link')) is not None: - args['range_link'] = range_link - if (range_modifier := _dict.get('range_modifier')) is not None: - args['range_modifier'] = range_modifier - if (relative_day := _dict.get('relative_day')) is not None: - args['relative_day'] = relative_day - if (relative_month := _dict.get('relative_month')) is not None: - args['relative_month'] = relative_month - if (relative_week := _dict.get('relative_week')) is not None: - args['relative_week'] = relative_week - if (relative_weekend := _dict.get('relative_weekend')) is not None: - args['relative_weekend'] = relative_weekend - if (relative_year := _dict.get('relative_year')) is not None: - args['relative_year'] = relative_year - if (specific_day := _dict.get('specific_day')) is not None: - args['specific_day'] = specific_day - if (specific_day_of_week := - _dict.get('specific_day_of_week')) is not None: - args['specific_day_of_week'] = specific_day_of_week - if (specific_month := _dict.get('specific_month')) is not None: - args['specific_month'] = specific_month - if (specific_quarter := _dict.get('specific_quarter')) is not None: - args['specific_quarter'] = specific_quarter - if (specific_year := _dict.get('specific_year')) is not None: - args['specific_year'] = specific_year - if (numeric_value := _dict.get('numeric_value')) is not None: - args['numeric_value'] = numeric_value - if (subtype := _dict.get('subtype')) is not None: - args['subtype'] = subtype - if (part_of_day := _dict.get('part_of_day')) is not None: - args['part_of_day'] = part_of_day - if (relative_hour := _dict.get('relative_hour')) is not None: - args['relative_hour'] = relative_hour - if (relative_minute := _dict.get('relative_minute')) is not None: - args['relative_minute'] = relative_minute - if (relative_second := _dict.get('relative_second')) is not None: - args['relative_second'] = relative_second - if (specific_hour := _dict.get('specific_hour')) is not None: - args['specific_hour'] = specific_hour - if (specific_minute := _dict.get('specific_minute')) is not None: - args['specific_minute'] = specific_minute - if (specific_second := _dict.get('specific_second')) is not None: - args['specific_second'] = specific_second - if (timezone := _dict.get('timezone')) is not None: - args['timezone'] = timezone + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in warnings + ] + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in Skill JSON') + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in Skill JSON') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + """Initialize a Skill 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') if hasattr(self, - 'specific_minute') and self.specific_minute is not None: - _dict['specific_minute'] = self.specific_minute + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') 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 + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -8149,75 +13223,265 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityInterpretation object.""" + """Return a `str` version of this Skill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + def __eq__(self, other: 'Skill') -> 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: + def __ne__(self, other: 'Skill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class GranularityEnum(str, Enum): + class StatusEnum(str, Enum): """ - The precision or duration of a time range specified by a recognized `@sys-time` or - `@sys-date` entity. + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. """ - DAY = 'day' - FORTNIGHT = 'fortnight' - HOUR = 'hour' - INSTANT = 'instant' - MINUTE = 'minute' - MONTH = 'month' - QUARTER = 'quarter' - SECOND = 'second' - WEEK = 'week' - WEEKEND = 'weekend' - YEAR = 'year' + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' + + class TypeEnum(str, Enum): + """ + The type of skill. + """ + + ACTION = 'action' + DIALOG = 'dialog' + SEARCH = 'search' -class RuntimeEntityRole: +class SkillImport: """ - 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. + SkillImport. - :param str type: (optional) The relationship of the entity to the range. + :param str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :param str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :param str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :param str language: The language of the skill. + :param str type: The type of skill. """ def __init__( self, + language: str, + type: str, *, - type: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, ) -> None: """ - Initialize a RuntimeEntityRole object. + Initialize a SkillImport object. - :param str type: (optional) The relationship of the entity to the range. + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. """ + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': - """Initialize a RuntimeEntityRole object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillImport': + """Initialize a SkillImport object from a json dictionary.""" args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in warnings + ] + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in SkillImport JSON' + ) if (type := _dict.get('type')) is not None: args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in SkillImport JSON') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityRole object from a json dictionary.""" + """Initialize a SkillImport 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') + if hasattr(self, + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type return _dict @@ -8227,101 +13491,122 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityRole object.""" + """Return a `str` version of this SkillImport object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityRole') -> bool: + def __eq__(self, other: 'SkillImport') -> 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: + def __ne__(self, other: 'SkillImport') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' + class TypeEnum(str, Enum): """ - The relationship of the entity to the range. + The type of skill. """ - DATE_FROM = 'date_from' - DATE_TO = 'date_to' - NUMBER_FROM = 'number_from' - NUMBER_TO = 'number_to' - TIME_FROM = 'time_from' - TIME_TO = 'time_to' + ACTION = 'action' + DIALOG = 'dialog' -class RuntimeIntent: +class SkillsAsyncRequestStatus: """ - An intent identified in the user input. + SkillsAsyncRequestStatus. - :param str intent: The name of the recognized intent. - :param float confidence: (optional) A decimal percentage that represents - confidence in the intent. If you are specifying an intent as part of a request, - but you do not have a calculated confidence value, specify `1`. - :param str skill: (optional) The skill that identified the intent. Currently, - the only possible values are `main skill` for the dialog skill (if enabled) and - `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and an - action skill. + :param str assistant_id: (optional) The assistant ID of the assistant. + :param str status: (optional) The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. """ def __init__( self, - intent: str, *, - confidence: Optional[float] = None, - skill: Optional[str] = None, + assistant_id: Optional[str] = None, + status: Optional[str] = None, + status_description: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, ) -> None: """ - Initialize a RuntimeIntent object. + Initialize a SkillsAsyncRequestStatus object. - :param str intent: The name of the recognized intent. - :param float confidence: (optional) A decimal percentage that represents - confidence in the intent. If you are specifying an intent as part of a - request, but you do not have a calculated confidence value, specify `1`. - :param str skill: (optional) The skill that identified the intent. - Currently, the only possible values are `main skill` for the dialog skill - (if enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and - an action skill. """ - self.intent = intent - self.confidence = confidence - self.skill = skill + self.assistant_id = assistant_id + self.status = status + self.status_description = status_description + self.status_errors = status_errors @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': - """Initialize a RuntimeIntent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" args = {} - if (intent := _dict.get('intent')) is not None: - args['intent'] = intent - else: - raise ValueError( - 'Required property \'intent\' not present in RuntimeIntent JSON' - ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (skill := _dict.get('skill')) is not None: - args['skill'] = skill + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeIntent object from a json dictionary.""" + """Initialize a SkillsAsyncRequestStatus 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, 'intent') and self.intent is not None: - _dict['intent'] = self.intent - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'skill') and self.skill is not None: - _dict['skill'] = self.skill + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list return _dict def _to_dict(self): @@ -8329,255 +13614,105 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeIntent object.""" + """Return a `str` version of this SkillsAsyncRequestStatus object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeIntent') -> bool: + def __eq__(self, other: 'SkillsAsyncRequestStatus') -> 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: 'RuntimeIntent') -> bool: + def __ne__(self, other: 'SkillsAsyncRequestStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - -class RuntimeResponseGeneric: - """ - RuntimeResponseGeneric. - - """ - - def __init__(self,) -> None: + class StatusEnum(str, Enum): """ - Initialize a RuntimeResponseGeneric object. - + The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - return cls.from_dict(_dict) - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' - mapping[ - 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' - mapping[ - 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' - mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' - mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' - mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' - mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' - mapping[ - 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' - mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' - mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' - mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' - mapping[ - 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' - mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' - disc_value = _dict.get('response_type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) + AVAILABLE = 'Available' + COMPLETED = 'Completed' + FAILED = 'Failed' + PROCESSING = 'Processing' -class SearchResult: +class SkillsExport: """ - SearchResult. + SkillsExport. - :param str id: The unique identifier of the document in the Discovery service - collection. - This property is included in responses from search skills, which are available - only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search result - metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is taken - from an abstract, summary, or highlight field in the Discovery service response, - as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken from - a title or name field in the Discovery service response, as specified in the - search skill configuration. - :param str url: (optional) The URL of the original data object in its native - data source. - :param SearchResultHighlight highlight: (optional) An object containing segments - of text from search results with query-matching text highlighted using HTML - `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying segments - of text within the result that were identified as direct answers to the search - query. Currently, only the single answer with the highest confidence (if any) is - returned. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. + :param List[Skill] assistant_skills: An array of objects describing the skills + for the assistant. Included in responses only if **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills for + the assistant. Included in responses only if **status**=`Available`. """ def __init__( self, - id: str, - result_metadata: 'SearchResultMetadata', - *, - body: Optional[str] = None, - title: Optional[str] = None, - url: Optional[str] = None, - highlight: Optional['SearchResultHighlight'] = None, - answers: Optional[List['SearchResultAnswer']] = None, + assistant_skills: List['Skill'], + assistant_state: 'AssistantState', ) -> None: """ - Initialize a SearchResult object. + Initialize a SkillsExport object. - :param str id: The unique identifier of the document in the Discovery - service collection. - This property is included in responses from search skills, which are - available only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search - result metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is - taken from an abstract, summary, or highlight field in the Discovery - service response, as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken - from a title or name field in the Discovery service response, as specified - in the search skill configuration. - :param str url: (optional) The URL of the original data object in its - native data source. - :param SearchResultHighlight highlight: (optional) An object containing - segments of text from search results with query-matching text highlighted - using HTML `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying - segments of text within the result that were identified as direct answers - to the search query. Currently, only the single answer with the highest - confidence (if any) is returned. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. + :param List[Skill] assistant_skills: An array of objects describing the + skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. """ - self.id = id - self.result_metadata = result_metadata - self.body = body - self.title = title - self.url = url - self.highlight = highlight - self.answers = answers + self.assistant_skills = assistant_skills + self.assistant_state = assistant_state @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResult': - """Initialize a SearchResult object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillsExport': + """Initialize a SkillsExport object from a json dictionary.""" args = {} - if (id := _dict.get('id')) is not None: - args['id'] = id + if (assistant_skills := _dict.get('assistant_skills')) is not None: + args['assistant_skills'] = [ + Skill.from_dict(v) for v in assistant_skills + ] else: raise ValueError( - 'Required property \'id\' not present in SearchResult JSON') - if (result_metadata := _dict.get('result_metadata')) is not None: - args['result_metadata'] = SearchResultMetadata.from_dict( - result_metadata) + 'Required property \'assistant_skills\' not present in SkillsExport JSON' + ) + if (assistant_state := _dict.get('assistant_state')) is not None: + args['assistant_state'] = AssistantState.from_dict(assistant_state) else: raise ValueError( - 'Required property \'result_metadata\' not present in SearchResult JSON' + 'Required property \'assistant_state\' not present in SkillsExport JSON' ) - if (body := _dict.get('body')) is not None: - args['body'] = body - if (title := _dict.get('title')) is not None: - args['title'] = title - if (url := _dict.get('url')) is not None: - args['url'] = url - if (highlight := _dict.get('highlight')) is not None: - args['highlight'] = SearchResultHighlight.from_dict(highlight) - if (answers := _dict.get('answers')) is not None: - args['answers'] = [SearchResultAnswer.from_dict(v) for v in answers] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResult object from a json dictionary.""" + """Initialize a SkillsExport 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, 'id') and self.id is not None: - _dict['id'] = self.id if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - if isinstance(self.result_metadata, dict): - _dict['result_metadata'] = self.result_metadata - else: - _dict['result_metadata'] = self.result_metadata.to_dict() - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'highlight') and self.highlight is not None: - if isinstance(self.highlight, dict): - _dict['highlight'] = self.highlight - else: - _dict['highlight'] = self.highlight.to_dict() - if hasattr(self, 'answers') and self.answers is not None: - answers_list = [] - for v in self.answers: + 'assistant_skills') and self.assistant_skills is not None: + assistant_skills_list = [] + for v in self.assistant_skills: if isinstance(v, dict): - answers_list.append(v) + assistant_skills_list.append(v) else: - answers_list.append(v.to_dict()) - _dict['answers'] = answers_list + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, + 'assistant_state') and self.assistant_state is not None: + if isinstance(self.assistant_state, dict): + _dict['assistant_state'] = self.assistant_state + else: + _dict['assistant_state'] = self.assistant_state.to_dict() return _dict def _to_dict(self): @@ -8585,75 +13720,141 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResult object.""" + """Return a `str` version of this SkillsExport object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResult') -> bool: + def __eq__(self, other: 'SkillsExport') -> 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: 'SearchResult') -> bool: + def __ne__(self, other: 'SkillsExport') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultAnswer: +class StatefulMessageResponse: """ - An object specifing a segment of text that was identified as a direct answer to the - search query. + A response from the watsonx Assistant service. - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned by the - Discovery service. + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. """ def __init__( self, - text: str, - confidence: float, + output: 'MessageOutput', + user_id: str, + *, + context: Optional['MessageContext'] = None, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, ) -> None: """ - Initialize a SearchResultAnswer object. + Initialize a StatefulMessageResponse object. - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned - by the Discovery service. + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. """ - self.text = text - self.confidence = confidence + self.output = output + self.context = context + self.user_id = user_id + self.masked_output = masked_output + self.masked_input = masked_input @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': - """Initialize a SearchResultAnswer object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatefulMessageResponse': + """Initialize a StatefulMessageResponse object from a json dictionary.""" args = {} - if (text := _dict.get('text')) is not None: - args['text'] = text + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) else: raise ValueError( - 'Required property \'text\' not present in SearchResultAnswer JSON' + 'Required property \'output\' not present in StatefulMessageResponse JSON' ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id else: raise ValueError( - 'Required property \'confidence\' not present in SearchResultAnswer JSON' + 'Required property \'user_id\' not present in StatefulMessageResponse JSON' ) + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultAnswer object from a json dictionary.""" + """Initialize a StatefulMessageResponse 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() return _dict def _to_dict(self): @@ -8661,194 +13862,158 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultAnswer object.""" + """Return a `str` version of this StatefulMessageResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultAnswer') -> bool: + def __eq__(self, other: 'StatefulMessageResponse') -> 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: 'SearchResultAnswer') -> bool: + def __ne__(self, other: 'StatefulMessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultHighlight: +class StatelessMessageContext: """ - An object containing segments of text from search results with query-matching text - highlighted using HTML `` tags. + StatelessMessageContext. - :param List[str] body: (optional) An array of strings containing segments taken - from body text in the search results, with query-matching substrings - highlighted. - :param List[str] title: (optional) An array of strings containing segments taken - from title text in the search results, with query-matching substrings - highlighted. - :param List[str] url: (optional) An array of strings containing segments taken - from URLs in the search results, with query-matching substrings highlighted. + :param StatelessMessageContextGlobal global_: (optional) Session context data + that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - # The set of defined properties for the class - _properties = frozenset(['body', 'title', 'url']) - def __init__( self, *, - body: Optional[List[str]] = None, - title: Optional[List[str]] = None, - url: Optional[List[str]] = None, - **kwargs, + global_: Optional['StatelessMessageContextGlobal'] = None, + skills: Optional['StatelessMessageContextSkills'] = None, + integrations: Optional[dict] = None, ) -> None: """ - Initialize a SearchResultHighlight object. + Initialize a StatelessMessageContext object. - :param List[str] body: (optional) An array of strings containing segments - taken from body text in the search results, with query-matching substrings - highlighted. - :param List[str] title: (optional) An array of strings containing segments - taken from title text in the search results, with query-matching substrings - highlighted. - :param List[str] url: (optional) An array of strings containing segments - taken from URLs in the search results, with query-matching substrings - highlighted. - :param **kwargs: (optional) Any additional properties. + :param StatelessMessageContextGlobal global_: (optional) Session context + data that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data + specific to particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - self.body = body - self.title = title - self.url = url - for _key, _value in kwargs.items(): - setattr(self, _key, _value) + self.global_ = global_ + self.skills = skills + self.integrations = integrations @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': - """Initialize a SearchResultHighlight object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContext': + """Initialize a StatelessMessageContext object from a json dictionary.""" args = {} - if (body := _dict.get('body')) is not None: - args['body'] = body - if (title := _dict.get('title')) is not None: - args['title'] = title - if (url := _dict.get('url')) is not None: - args['url'] = url - args.update( - {k: v for (k, v) in _dict.items() if k not in cls._properties}) + if (global_ := _dict.get('global')) is not None: + args['global_'] = StatelessMessageContextGlobal.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = StatelessMessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultHighlight object from a json dictionary.""" + """Initialize a StatelessMessageContext 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, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - _dict[_key] = getattr(self, _key) + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" - _dict = {} - - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - _dict[_key] = getattr(self, _key) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" - for _key in [ - k for k in vars(self).keys() - if k not in SearchResultHighlight._properties - ]: - delattr(self, _key) - - for _key, _value in _dict.items(): - if _key not in SearchResultHighlight._properties: - setattr(self, _key, _value) - def __str__(self) -> str: - """Return a `str` version of this SearchResultHighlight object.""" + """Return a `str` version of this StatelessMessageContext object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultHighlight') -> bool: + def __eq__(self, other: 'StatelessMessageContext') -> 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: 'SearchResultHighlight') -> bool: + def __ne__(self, other: 'StatelessMessageContext') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultMetadata: +class StatelessMessageContextGlobal: """ - An object containing search result metadata from the Discovery service. + Session context data that is shared by all skills used by the assistant. - :param float confidence: (optional) The confidence score for the given result, - as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. + :param MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. """ def __init__( self, *, - confidence: Optional[float] = None, - score: Optional[float] = None, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, ) -> None: """ - Initialize a SearchResultMetadata object. + Initialize a StatelessMessageContextGlobal object. - :param float confidence: (optional) The confidence score for the given - result, as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher - score indicates a greater match to the query parameters. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. """ - self.confidence = confidence - self.score = score + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': - """Initialize a SearchResultMetadata object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextGlobal': + """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" args = {} - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (score := _dict.get('score')) is not None: - args['score'] = score + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultMetadata object from a json dictionary.""" + """Initialize a StatelessMessageContextGlobal 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, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id return _dict def _to_dict(self): @@ -8856,103 +14021,78 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultMetadata object.""" + """Return a `str` version of this StatelessMessageContextGlobal object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultMetadata') -> bool: + def __eq__(self, other: 'StatelessMessageContextGlobal') -> 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: 'SearchResultMetadata') -> bool: + def __ne__(self, other: 'StatelessMessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettings: +class StatelessMessageContextSkills: """ - An object describing the search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and are not - included in **Export skills** responses. + Context data specific to particular skills used by the assistant. - :param SearchSettingsDiscovery discovery: Configuration settings for the Watson - Discovery service instance used by the search integration. - :param SearchSettingsMessages messages: The messages included with responses - from the search integration. - :param SearchSettingsSchemaMapping schema_mapping: The mapping between fields in - the Watson Discovery collection and properties in the search response. + :param MessageContextDialogSkill main_skill: (optional) Context variables that + are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. """ def __init__( self, - discovery: 'SearchSettingsDiscovery', - messages: 'SearchSettingsMessages', - schema_mapping: 'SearchSettingsSchemaMapping', + *, + main_skill: Optional['MessageContextDialogSkill'] = None, + actions_skill: Optional[ + 'StatelessMessageContextSkillsActionsSkill'] = None, ) -> None: """ - Initialize a SearchSettings object. + Initialize a StatelessMessageContextSkills object. - :param SearchSettingsDiscovery discovery: Configuration settings for the - Watson Discovery service instance used by the search integration. - :param SearchSettingsMessages messages: The messages included with - responses from the search integration. - :param SearchSettingsSchemaMapping schema_mapping: The mapping between - fields in the Watson Discovery collection and properties in the search - response. + :param MessageContextDialogSkill main_skill: (optional) Context variables + that are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. """ - self.discovery = discovery - self.messages = messages - self.schema_mapping = schema_mapping + self.main_skill = main_skill + self.actions_skill = actions_skill @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettings': - """Initialize a SearchSettings object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextSkills': + """Initialize a StatelessMessageContextSkills object from a json dictionary.""" args = {} - if (discovery := _dict.get('discovery')) is not None: - args['discovery'] = SearchSettingsDiscovery.from_dict(discovery) - else: - raise ValueError( - 'Required property \'discovery\' not present in SearchSettings JSON' - ) - if (messages := _dict.get('messages')) is not None: - args['messages'] = SearchSettingsMessages.from_dict(messages) - else: - raise ValueError( - 'Required property \'messages\' not present in SearchSettings JSON' - ) - if (schema_mapping := _dict.get('schema_mapping')) is not None: - args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( - schema_mapping) - else: - raise ValueError( - 'Required property \'schema_mapping\' not present in SearchSettings JSON' - ) + if (main_skill := _dict.get('main skill')) is not None: + args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) + if (actions_skill := _dict.get('actions skill')) is not None: + args[ + 'actions_skill'] = StatelessMessageContextSkillsActionsSkill.from_dict( + actions_skill) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettings object from a json dictionary.""" + """Initialize a StatelessMessageContextSkills 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, 'discovery') and self.discovery is not None: - if isinstance(self.discovery, dict): - _dict['discovery'] = self.discovery - else: - _dict['discovery'] = self.discovery.to_dict() - if hasattr(self, 'messages') and self.messages is not None: - if isinstance(self.messages, dict): - _dict['messages'] = self.messages + if hasattr(self, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill else: - _dict['messages'] = self.messages.to_dict() - if hasattr(self, 'schema_mapping') and self.schema_mapping is not None: - if isinstance(self.schema_mapping, dict): - _dict['schema_mapping'] = self.schema_mapping + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill else: - _dict['schema_mapping'] = self.schema_mapping.to_dict() + _dict['actions skill'] = self.actions_skill.to_dict() return _dict def _to_dict(self): @@ -8960,179 +14100,134 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettings object.""" + """Return a `str` version of this StatelessMessageContextSkills object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettings') -> bool: + def __eq__(self, other: 'StatelessMessageContextSkills') -> 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: 'SearchSettings') -> bool: + def __ne__(self, other: 'StatelessMessageContextSkills') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsDiscovery: +class StatelessMessageContextSkillsActionsSkill: """ - Configuration settings for the Watson Discovery service instance used by the search - integration. + Context variables that are used by the action skill. - :param str instance_id: The ID for the Watson Discovery service instance. - :param str project_id: The ID for the Watson Discovery project. - :param str url: The URL for the Watson Discovery service instance. - :param int max_primary_results: (optional) The maximum number of primary results - to include in the response. - :param int max_total_results: (optional) The maximum total number of primary and - additional results to include in the response. - :param float confidence_threshold: (optional) The minimum confidence threshold - for included results. Any results with a confidence below this threshold will be - discarded. - :param bool highlight: (optional) Whether to include the most relevant passages - of text in the **highlight** property of each result. - :param bool find_answers: (optional) Whether to use the answer finding feature - to emphasize answers within highlighted passages. This property is ignored if - **highlight**=`false`. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. - :param SearchSettingsDiscoveryAuthentication authentication: Authentication - information for the Watson Discovery service. For more information, see the - [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by + the skill. + :param dict action_variables: (optional) An object containing action variables. + Action variables can be accessed only by steps in the same action, and do not + persist after the action ends. + :param dict skill_variables: (optional) An object containing skill variables. + (In the watsonx Assistant user interface, skill variables are called _session + variables_.) Skill variables can be accessed by any action and persist for the + duration of the session. + :param dict private_action_variables: (optional) An object containing private + action variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. Private variables are + encrypted. + :param dict private_skill_variables: (optional) An object containing private + skill variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action and + persist for the duration of the session. Private variables are encrypted. """ def __init__( self, - instance_id: str, - project_id: str, - url: str, - authentication: 'SearchSettingsDiscoveryAuthentication', *, - max_primary_results: Optional[int] = None, - max_total_results: Optional[int] = None, - confidence_threshold: Optional[float] = None, - highlight: Optional[bool] = None, - find_answers: Optional[bool] = None, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + action_variables: Optional[dict] = None, + skill_variables: Optional[dict] = None, + private_action_variables: Optional[dict] = None, + private_skill_variables: Optional[dict] = None, ) -> None: """ - Initialize a SearchSettingsDiscovery object. + Initialize a StatelessMessageContextSkillsActionsSkill object. - :param str instance_id: The ID for the Watson Discovery service instance. - :param str project_id: The ID for the Watson Discovery project. - :param str url: The URL for the Watson Discovery service instance. - :param SearchSettingsDiscoveryAuthentication authentication: Authentication - information for the Watson Discovery service. For more information, see the - [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. - :param int max_primary_results: (optional) The maximum number of primary - results to include in the response. - :param int max_total_results: (optional) The maximum total number of - primary and additional results to include in the response. - :param float confidence_threshold: (optional) The minimum confidence - threshold for included results. Any results with a confidence below this - threshold will be discarded. - :param bool highlight: (optional) Whether to include the most relevant - passages of text in the **highlight** property of each result. - :param bool find_answers: (optional) Whether to use the answer finding - feature to emphasize answers within highlighted passages. This property is - ignored if **highlight**=`false`. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + :param dict action_variables: (optional) An object containing action + variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. + :param dict skill_variables: (optional) An object containing skill + variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action + and persist for the duration of the session. + :param dict private_action_variables: (optional) An object containing + private action variables. Action variables can be accessed only by steps in + the same action, and do not persist after the action ends. Private + variables are encrypted. + :param dict private_skill_variables: (optional) An object containing + private skill variables. (In the watsonx Assistant user interface, skill + variables are called _session variables_.) Skill variables can be accessed + by any action and persist for the duration of the session. Private + variables are encrypted. """ - self.instance_id = instance_id - self.project_id = project_id - self.url = url - self.max_primary_results = max_primary_results - self.max_total_results = max_total_results - self.confidence_threshold = confidence_threshold - self.highlight = highlight - self.find_answers = find_answers - self.authentication = authentication + self.user_defined = user_defined + self.system = system + self.action_variables = action_variables + self.skill_variables = skill_variables + self.private_action_variables = private_action_variables + self.private_skill_variables = private_skill_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': - """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'StatelessMessageContextSkillsActionsSkill': + """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" args = {} - if (instance_id := _dict.get('instance_id')) is not None: - args['instance_id'] = instance_id - else: - raise ValueError( - 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' - ) - if (project_id := _dict.get('project_id')) is not None: - args['project_id'] = project_id - else: - raise ValueError( - 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' - ) - if (url := _dict.get('url')) is not None: - args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in SearchSettingsDiscovery JSON' - ) - if (max_primary_results := - _dict.get('max_primary_results')) is not None: - args['max_primary_results'] = max_primary_results - if (max_total_results := _dict.get('max_total_results')) is not None: - args['max_total_results'] = max_total_results - if (confidence_threshold := - _dict.get('confidence_threshold')) is not None: - args['confidence_threshold'] = confidence_threshold - if (highlight := _dict.get('highlight')) is not None: - args['highlight'] = highlight - if (find_answers := _dict.get('find_answers')) is not None: - args['find_answers'] = find_answers - if (authentication := _dict.get('authentication')) is not None: - args[ - 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( - authentication) - else: - raise ValueError( - 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' - ) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables + if (skill_variables := _dict.get('skill_variables')) is not None: + args['skill_variables'] = skill_variables + if (private_action_variables := + _dict.get('private_action_variables')) is not None: + args['private_action_variables'] = private_action_variables + if (private_skill_variables := + _dict.get('private_skill_variables')) is not None: + args['private_skill_variables'] = private_skill_variables return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + """Initialize a StatelessMessageContextSkillsActionsSkill 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, 'instance_id') and self.instance_id is not None: - _dict['instance_id'] = self.instance_id - if hasattr(self, 'project_id') and self.project_id is not None: - _dict['project_id'] = self.project_id - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr( - self, - 'max_primary_results') and self.max_primary_results is not None: - _dict['max_primary_results'] = self.max_primary_results - if hasattr(self, - 'max_total_results') and self.max_total_results is not None: - _dict['max_total_results'] = self.max_total_results - if hasattr(self, 'confidence_threshold' - ) and self.confidence_threshold is not None: - _dict['confidence_threshold'] = self.confidence_threshold - if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight - if hasattr(self, 'find_answers') and self.find_answers is not None: - _dict['find_answers'] = self.find_answers - if hasattr(self, 'authentication') and self.authentication is not None: - if isinstance(self.authentication, dict): - _dict['authentication'] = self.authentication + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system else: - _dict['authentication'] = self.authentication.to_dict() + _dict['system'] = self.system.to_dict() + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables + if hasattr(self, + 'skill_variables') and self.skill_variables is not None: + _dict['skill_variables'] = self.skill_variables + if hasattr(self, 'private_action_variables' + ) and self.private_action_variables is not None: + _dict['private_action_variables'] = self.private_action_variables + if hasattr(self, 'private_skill_variables' + ) and self.private_skill_variables is not None: + _dict['private_skill_variables'] = self.private_skill_variables return _dict def _to_dict(self): @@ -9140,74 +14235,177 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsDiscovery object.""" + """Return a `str` version of this StatelessMessageContextSkillsActionsSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsDiscovery') -> bool: + def __eq__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> 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: 'SearchSettingsDiscovery') -> bool: + def __ne__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsDiscoveryAuthentication: +class StatelessMessageInput: """ - Authentication information for the Watson Discovery service. For more information, see - the [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. + An input object that includes the input text. - :param str basic: (optional) The HTTP basic authentication credentials for - Watson Discovery. Specify your Watson Discovery API key in the format - `apikey:{apikey}`. - :param str bearer: (optional) The authentication bearer token for Watson - Discovery. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param StatelessMessageInputOptions options: (optional) Optional properties that + control how the assistant responds. """ def __init__( self, *, - basic: Optional[str] = None, - bearer: Optional[str] = None, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['StatelessMessageInputOptions'] = None, ) -> None: """ - Initialize a SearchSettingsDiscoveryAuthentication object. + Initialize a StatelessMessageInput object. - :param str basic: (optional) The HTTP basic authentication credentials for - Watson Discovery. Specify your Watson Discovery API key in the format - `apikey:{apikey}`. - :param str bearer: (optional) The authentication bearer token for Watson - Discovery. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param StatelessMessageInputOptions options: (optional) Optional properties + that control how the assistant responds. """ - self.basic = basic - self.bearer = bearer + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': - """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInput': + """Initialize a StatelessMessageInput object from a json dictionary.""" args = {} - if (basic := _dict.get('basic')) is not None: - args['basic'] = basic - if (bearer := _dict.get('bearer')) is not None: - args['bearer'] = bearer + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments + ] + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = StatelessMessageInputOptions.from_dict(options) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + """Initialize a StatelessMessageInput 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, 'basic') and self.basic is not None: - _dict['basic'] = self.basic - if hasattr(self, 'bearer') and self.bearer is not None: - _dict['bearer'] = self.bearer + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -9215,90 +14413,133 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsDiscoveryAuthentication object.""" + """Return a `str` version of this StatelessMessageInput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: + def __eq__(self, other: 'StatelessMessageInput') -> 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: 'SearchSettingsDiscoveryAuthentication') -> bool: + def __ne__(self, other: 'StatelessMessageInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + + TEXT = 'text' + SEARCH = 'search' + -class SearchSettingsMessages: +class StatelessMessageInputOptions: """ - The messages included with responses from the search integration. + Optional properties that control how the assistant responds. - :param str success: The message to include in the response to a successful - query. - :param str error: The message to include in the response when the query - encounters an error. - :param str no_result: The message to include in the response when there is no - result from the query. + :param bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the initial + message response signals to the client that the operation may be long running. + With synchronous execution the custom extension is executed and returns the + response in a single message turn. **Note:** **async_callout** defaults to true + for API versions earlier than 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ def __init__( self, - success: str, - error: str, - no_result: str, + *, + restart: Optional[bool] = None, + alternate_intents: Optional[bool] = None, + async_callout: Optional[bool] = None, + spelling: Optional['MessageInputOptionsSpelling'] = None, + debug: Optional[bool] = None, ) -> None: """ - Initialize a SearchSettingsMessages object. + Initialize a StatelessMessageInputOptions object. - :param str success: The message to include in the response to a successful - query. - :param str error: The message to include in the response when the query - encounters an error. - :param str no_result: The message to include in the response when there is - no result from the query. + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the + initial message response signals to the client that the operation may be + long running. With synchronous execution the custom extension is executed + and returns the response in a single message turn. **Note:** + **async_callout** defaults to true for API versions earlier than + 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ - self.success = success - self.error = error - self.no_result = no_result + self.restart = restart + self.alternate_intents = alternate_intents + self.async_callout = async_callout + self.spelling = spelling + self.debug = debug @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': - """Initialize a SearchSettingsMessages object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInputOptions': + """Initialize a StatelessMessageInputOptions object from a json dictionary.""" args = {} - if (success := _dict.get('success')) is not None: - args['success'] = success - else: - raise ValueError( - 'Required property \'success\' not present in SearchSettingsMessages JSON' - ) - if (error := _dict.get('error')) is not None: - args['error'] = error - else: - raise ValueError( - 'Required property \'error\' not present in SearchSettingsMessages JSON' - ) - if (no_result := _dict.get('no_result')) is not None: - args['no_result'] = no_result - else: - raise ValueError( - 'Required property \'no_result\' not present in SearchSettingsMessages JSON' - ) + if (restart := _dict.get('restart')) is not None: + args['restart'] = restart + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (async_callout := _dict.get('async_callout')) is not None: + args['async_callout'] = async_callout + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (debug := _dict.get('debug')) is not None: + args['debug'] = debug return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsMessages object from a json dictionary.""" + """Initialize a StatelessMessageInputOptions 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, 'success') and self.success is not None: - _dict['success'] = self.success - if hasattr(self, 'error') and self.error is not None: - _dict['error'] = self.error - if hasattr(self, 'no_result') and self.no_result is not None: - _dict['no_result'] = self.no_result + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'async_callout') and self.async_callout is not None: + _dict['async_callout'] = self.async_callout + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug return _dict def _to_dict(self): @@ -9306,91 +14547,137 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsMessages object.""" + """Return a `str` version of this StatelessMessageInputOptions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsMessages') -> bool: + def __eq__(self, other: 'StatelessMessageInputOptions') -> 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: 'SearchSettingsMessages') -> bool: + def __ne__(self, other: 'StatelessMessageInputOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsSchemaMapping: +class StatelessMessageResponse: """ - The mapping between fields in the Watson Discovery collection and properties in the - search response. + A stateless response from the watsonx Assistant service. - :param str url: The field in the collection to map to the **url** property of - the response. - :param str body: The field in the collection to map to the **body** property in - the response. - :param str title: The field in the collection to map to the **title** property - for the schema. + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param StatelessMessageContext context: Context data for the conversation. You + can use this property to access context variables. The context is not stored by + the assistant; to maintain session state, include the context from the response + in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ def __init__( self, - url: str, - body: str, - title: str, + output: 'MessageOutput', + context: 'StatelessMessageContext', + *, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, + user_id: Optional[str] = None, ) -> None: """ - Initialize a SearchSettingsSchemaMapping object. + Initialize a StatelessMessageResponse object. - :param str url: The field in the collection to map to the **url** property - of the response. - :param str body: The field in the collection to map to the **body** - property in the response. - :param str title: The field in the collection to map to the **title** - property for the schema. + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param StatelessMessageContext context: Context data for the conversation. + You can use this property to access context variables. The context is not + stored by the assistant; to maintain session state, include the context + from the response in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. """ - self.url = url - self.body = body - self.title = title + self.output = output + self.context = context + self.masked_output = masked_output + self.masked_input = masked_input + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': - """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageResponse': + """Initialize a StatelessMessageResponse object from a json dictionary.""" args = {} - if (url := _dict.get('url')) is not None: - args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' - ) - if (body := _dict.get('body')) is not None: - args['body'] = body + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) else: raise ValueError( - 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' + 'Required property \'output\' not present in StatelessMessageResponse JSON' ) - if (title := _dict.get('title')) is not None: - args['title'] = title + if (context := _dict.get('context')) is not None: + args['context'] = StatelessMessageContext.from_dict(context) else: raise ValueError( - 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' + 'Required property \'context\' not present in StatelessMessageResponse JSON' ) + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + """Initialize a StatelessMessageResponse 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, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -9398,73 +14685,56 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsSchemaMapping object.""" + """Return a `str` version of this StatelessMessageResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsSchemaMapping') -> bool: + def __eq__(self, other: 'StatelessMessageResponse') -> 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: 'SearchSettingsSchemaMapping') -> bool: + def __ne__(self, other: 'StatelessMessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSkillWarning: +class StatusError: """ - A warning describing an error in the search skill configuration. + An object describing an error that occurred during processing of an asynchronous + operation. - :param str code: (optional) The error code. - :param str path: (optional) The location of the error in the search skill - configuration object. - :param str message: (optional) The error message. + :param str message: (optional) The text of the error message. """ def __init__( self, *, - code: Optional[str] = None, - path: Optional[str] = None, message: Optional[str] = None, ) -> None: """ - Initialize a SearchSkillWarning object. + Initialize a StatusError object. - :param str code: (optional) The error code. - :param str path: (optional) The location of the error in the search skill - configuration object. - :param str message: (optional) The error message. + :param str message: (optional) The text of the error message. """ - self.code = code - self.path = path self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': - """Initialize a SearchSkillWarning object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatusError': + """Initialize a StatusError object from a json dictionary.""" args = {} - if (code := _dict.get('code')) is not None: - args['code'] = code - if (path := _dict.get('path')) is not None: - args['path'] = path if (message := _dict.get('message')) is not None: args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSkillWarning object from a json dictionary.""" + """Initialize a StatusError 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, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path if hasattr(self, 'message') and self.message is not None: _dict['message'] = self.message return _dict @@ -9474,300 +14744,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSkillWarning object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SearchSkillWarning') -> 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: 'SearchSkillWarning') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SessionResponse: - """ - SessionResponse. - - :param str session_id: The session ID. - """ - - def __init__( - self, - session_id: str, - ) -> None: - """ - Initialize a SessionResponse object. - - :param str session_id: The session ID. - """ - self.session_id = session_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SessionResponse': - """Initialize a SessionResponse object from a json dictionary.""" - args = {} - if (session_id := _dict.get('session_id')) is not None: - args['session_id'] = session_id - else: - raise ValueError( - 'Required property \'session_id\' not present in SessionResponse JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SessionResponse 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, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id - 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 SessionResponse object.""" + """Return a `str` version of this StatusError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SessionResponse') -> bool: + def __eq__(self, other: 'StatusError') -> 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: 'SessionResponse') -> bool: + def __ne__(self, other: 'StatusError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Skill: +class TurnEventActionSource: """ - Skill. + TurnEventActionSource. - :param str name: (optional) The name of the skill. This string cannot contain - carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This string - cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param str skill_id: (optional) The skill ID of the skill. - :param str status: (optional) The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param dict dialog_settings: (optional) For internal use only. - :param str assistant_id: (optional) The unique identifier of the assistant the - skill is associated with. - :param str workspace_id: (optional) The unique identifier of the workspace that - contains the skill content. Included only for action and dialog skills. - :param str environment_id: (optional) The unique identifier of the environment - where the skill is defined. For action and dialog skills, this is always the - draft environment. - :param bool valid: (optional) Whether the skill is structurally valid. - :param str next_snapshot_version: (optional) The name that will be given to the - next snapshot that is created for the skill. A snapshot of each versionable - skill is saved for each new release of an assistant. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and - are not included in **Export skills** responses. - :param List[SearchSkillWarning] warnings: (optional) An array of warnings - describing errors with the search skill configuration. Included only for search - skills. - :param str language: The language of the skill. - :param str type: The type of skill. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing of + the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog node. """ def __init__( self, - language: str, - type: str, *, - name: Optional[str] = None, - description: Optional[str] = None, - workspace: Optional[dict] = None, - skill_id: Optional[str] = None, - status: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, - status_description: Optional[str] = None, - dialog_settings: Optional[dict] = None, - assistant_id: Optional[str] = None, - workspace_id: Optional[str] = None, - environment_id: Optional[str] = None, - valid: Optional[bool] = None, - next_snapshot_version: Optional[str] = None, - search_settings: Optional['SearchSettings'] = None, - warnings: Optional[List['SearchSkillWarning']] = None, + type: Optional[str] = None, + action: Optional[str] = None, + action_title: Optional[str] = None, + condition: Optional[str] = None, ) -> None: """ - Initialize a Skill object. - - :param str language: The language of the skill. - :param str type: The type of skill. - :param str name: (optional) The name of the skill. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This - string cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param dict dialog_settings: (optional) For internal use only. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, - and are not included in **Export skills** responses. - """ - self.name = name - self.description = description - self.workspace = workspace - self.skill_id = skill_id - self.status = status - self.status_errors = status_errors - self.status_description = status_description - self.dialog_settings = dialog_settings - self.assistant_id = assistant_id - self.workspace_id = workspace_id - self.environment_id = environment_id - self.valid = valid - self.next_snapshot_version = next_snapshot_version - self.search_settings = search_settings - self.warnings = warnings - self.language = language + Initialize a TurnEventActionSource object. + + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing + of the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog + node. + """ self.type = type + self.action = action + self.action_title = action_title + self.condition = condition @classmethod - def from_dict(cls, _dict: Dict) -> 'Skill': - """Initialize a Skill object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventActionSource': + """Initialize a TurnEventActionSource object from a json dictionary.""" args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (workspace := _dict.get('workspace')) is not None: - args['workspace'] = workspace - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (dialog_settings := _dict.get('dialog_settings')) is not None: - args['dialog_settings'] = dialog_settings - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (workspace_id := _dict.get('workspace_id')) is not None: - args['workspace_id'] = workspace_id - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (valid := _dict.get('valid')) is not None: - args['valid'] = valid - if (next_snapshot_version := - _dict.get('next_snapshot_version')) is not None: - args['next_snapshot_version'] = next_snapshot_version - if (search_settings := _dict.get('search_settings')) is not None: - args['search_settings'] = SearchSettings.from_dict(search_settings) - if (warnings := _dict.get('warnings')) is not None: - args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in warnings - ] - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in Skill JSON') if (type := _dict.get('type')) is not None: args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in Skill JSON') + if (action := _dict.get('action')) is not None: + args['action'] = action + if (action_title := _dict.get('action_title')) is not None: + args['action_title'] = action_title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Skill object from a json dictionary.""" + """Initialize a TurnEventActionSource 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'workspace') and self.workspace is not None: - _dict['workspace'] = self.workspace - if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: - _dict['skill_id'] = getattr(self, 'skill_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, - 'dialog_settings') and self.dialog_settings is not None: - _dict['dialog_settings'] = self.dialog_settings - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'workspace_id') and getattr( - self, 'workspace_id') is not None: - _dict['workspace_id'] = getattr(self, 'workspace_id') - if hasattr(self, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'valid') and getattr(self, 'valid') is not None: - _dict['valid'] = getattr(self, 'valid') - if hasattr(self, 'next_snapshot_version') and getattr( - self, 'next_snapshot_version') is not None: - _dict['next_snapshot_version'] = getattr(self, - 'next_snapshot_version') - if hasattr(self, - 'search_settings') and self.search_settings is not None: - if isinstance(self.search_settings, dict): - _dict['search_settings'] = self.search_settings - else: - _dict['search_settings'] = self.search_settings.to_dict() - if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: - warnings_list = [] - for v in getattr(self, 'warnings'): - if isinstance(v, dict): - warnings_list.append(v) - else: - warnings_list.append(v.to_dict()) - _dict['warnings'] = warnings_list - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'action_title') and self.action_title is not None: + _dict['action_title'] = self.action_title + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition return _dict def _to_dict(self): @@ -9775,267 +14829,112 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Skill object.""" + """Return a `str` version of this TurnEventActionSource object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Skill') -> bool: + def __eq__(self, other: 'TurnEventActionSource') -> 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: 'Skill') -> bool: + def __ne__(self, other: 'TurnEventActionSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - """ - - AVAILABLE = 'Available' - FAILED = 'Failed' - NON_EXISTENT = 'Non Existent' - PROCESSING = 'Processing' - TRAINING = 'Training' - UNAVAILABLE = 'Unavailable' - class TypeEnum(str, Enum): """ - The type of skill. + The type of turn event. """ ACTION = 'action' - DIALOG = 'dialog' - SEARCH = 'search' -class SkillImport: +class TurnEventCalloutCallout: """ - SkillImport. + TurnEventCalloutCallout. - :param str name: (optional) The name of the skill. This string cannot contain - carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This string - cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param str skill_id: (optional) The skill ID of the skill. - :param str status: (optional) The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param dict dialog_settings: (optional) For internal use only. - :param str assistant_id: (optional) The unique identifier of the assistant the - skill is associated with. - :param str workspace_id: (optional) The unique identifier of the workspace that - contains the skill content. Included only for action and dialog skills. - :param str environment_id: (optional) The unique identifier of the environment - where the skill is defined. For action and dialog skills, this is always the - draft environment. - :param bool valid: (optional) Whether the skill is structurally valid. - :param str next_snapshot_version: (optional) The name that will be given to the - next snapshot that is created for the skill. A snapshot of each versionable - skill is saved for each new release of an assistant. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and - are not included in **Export skills** responses. - :param List[SearchSkillWarning] warnings: (optional) An array of warnings - describing errors with the search skill configuration. Included only for search - skills. - :param str language: The language of the skill. - :param str type: The type of skill. + :param str type: (optional) The type of callout. Currently, the only supported + value is `integration_interaction` (for calls to extensions). + :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. + :param TurnEventCalloutCalloutRequest request: (optional) The request object + executed to the external server specified by the extension. + :param TurnEventCalloutCalloutResponse response: (optional) The response object + received by the external server made by the extension. """ def __init__( self, - language: str, - type: str, *, - name: Optional[str] = None, - description: Optional[str] = None, - workspace: Optional[dict] = None, - skill_id: Optional[str] = None, - status: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, - status_description: Optional[str] = None, - dialog_settings: Optional[dict] = None, - assistant_id: Optional[str] = None, - workspace_id: Optional[str] = None, - environment_id: Optional[str] = None, - valid: Optional[bool] = None, - next_snapshot_version: Optional[str] = None, - search_settings: Optional['SearchSettings'] = None, - warnings: Optional[List['SearchSkillWarning']] = None, - ) -> None: - """ - Initialize a SkillImport object. - - :param str language: The language of the skill. - :param str type: The type of skill. - :param str name: (optional) The name of the skill. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This - string cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param dict dialog_settings: (optional) For internal use only. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, - and are not included in **Export skills** responses. + type: Optional[str] = None, + internal: Optional[dict] = None, + result_variable: Optional[str] = None, + request: Optional['TurnEventCalloutCalloutRequest'] = None, + response: Optional['TurnEventCalloutCalloutResponse'] = None, + ) -> None: + """ + Initialize a TurnEventCalloutCallout object. + + :param str type: (optional) The type of callout. Currently, the only + supported value is `integration_interaction` (for calls to extensions). + :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. + :param TurnEventCalloutCalloutRequest request: (optional) The request + object executed to the external server specified by the extension. + :param TurnEventCalloutCalloutResponse response: (optional) The response + object received by the external server made by the extension. """ - self.name = name - self.description = description - self.workspace = workspace - self.skill_id = skill_id - self.status = status - self.status_errors = status_errors - self.status_description = status_description - self.dialog_settings = dialog_settings - self.assistant_id = assistant_id - self.workspace_id = workspace_id - self.environment_id = environment_id - self.valid = valid - self.next_snapshot_version = next_snapshot_version - self.search_settings = search_settings - self.warnings = warnings - self.language = language self.type = type + self.internal = internal + self.result_variable = result_variable + self.request = request + self.response = response @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillImport': - """Initialize a SkillImport object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': + """Initialize a TurnEventCalloutCallout object from a json dictionary.""" args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (workspace := _dict.get('workspace')) is not None: - args['workspace'] = workspace - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (dialog_settings := _dict.get('dialog_settings')) is not None: - args['dialog_settings'] = dialog_settings - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (workspace_id := _dict.get('workspace_id')) is not None: - args['workspace_id'] = workspace_id - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (valid := _dict.get('valid')) is not None: - args['valid'] = valid - if (next_snapshot_version := - _dict.get('next_snapshot_version')) is not None: - args['next_snapshot_version'] = next_snapshot_version - if (search_settings := _dict.get('search_settings')) is not None: - args['search_settings'] = SearchSettings.from_dict(search_settings) - if (warnings := _dict.get('warnings')) is not None: - args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in warnings - ] - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in SkillImport JSON' - ) if (type := _dict.get('type')) is not None: args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in SkillImport JSON') + if (internal := _dict.get('internal')) is not None: + args['internal'] = internal + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable + if (request := _dict.get('request')) is not None: + args['request'] = TurnEventCalloutCalloutRequest.from_dict(request) + if (response := _dict.get('response')) is not None: + args['response'] = TurnEventCalloutCalloutResponse.from_dict( + response) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillImport object from a json dictionary.""" + """Initialize a TurnEventCalloutCallout 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'workspace') and self.workspace is not None: - _dict['workspace'] = self.workspace - if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: - _dict['skill_id'] = getattr(self, 'skill_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, - 'dialog_settings') and self.dialog_settings is not None: - _dict['dialog_settings'] = self.dialog_settings - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'workspace_id') and getattr( - self, 'workspace_id') is not None: - _dict['workspace_id'] = getattr(self, 'workspace_id') - if hasattr(self, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'valid') and getattr(self, 'valid') is not None: - _dict['valid'] = getattr(self, 'valid') - if hasattr(self, 'next_snapshot_version') and getattr( - self, 'next_snapshot_version') is not None: - _dict['next_snapshot_version'] = getattr(self, - 'next_snapshot_version') - if hasattr(self, - 'search_settings') and self.search_settings is not None: - if isinstance(self.search_settings, dict): - _dict['search_settings'] = self.search_settings - else: - _dict['search_settings'] = self.search_settings.to_dict() - if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: - warnings_list = [] - for v in getattr(self, 'warnings'): - if isinstance(v, dict): - warnings_list.append(v) - else: - warnings_list.append(v.to_dict()) - _dict['warnings'] = warnings_list - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type + if hasattr(self, 'internal') and self.internal is not None: + _dict['internal'] = self.internal + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable + if hasattr(self, 'request') and self.request is not None: + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() return _dict def _to_dict(self): @@ -10043,122 +14942,112 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillImport object.""" + """Return a `str` version of this TurnEventCalloutCallout object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillImport') -> bool: + def __eq__(self, other: 'TurnEventCalloutCallout') -> 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: 'SkillImport') -> bool: + def __ne__(self, other: 'TurnEventCalloutCallout') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - """ - - AVAILABLE = 'Available' - FAILED = 'Failed' - NON_EXISTENT = 'Non Existent' - PROCESSING = 'Processing' - TRAINING = 'Training' - UNAVAILABLE = 'Unavailable' - class TypeEnum(str, Enum): """ - The type of skill. + The type of callout. Currently, the only supported value is + `integration_interaction` (for calls to extensions). """ - ACTION = 'action' - DIALOG = 'dialog' + INTEGRATION_INTERACTION = 'integration_interaction' -class SkillsAsyncRequestStatus: +class TurnEventCalloutCalloutRequest: """ - SkillsAsyncRequestStatus. - - :param str assistant_id: (optional) The assistant ID of the assistant. - :param str status: (optional) The current status of the asynchronous operation: - - `Available`: An asynchronous export is available. - - `Completed`: An asynchronous import operation has completed successfully. - - `Failed`: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - `Processing`: An asynchronous operation has not yet completed. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. + TurnEventCalloutCalloutRequest. + + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to the URL + of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server or an + object. In cases like timeouts or connections errors, it will contain details of + why the callout to the external server failed. """ def __init__( self, *, - assistant_id: Optional[str] = None, - status: Optional[str] = None, - status_description: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, + method: Optional[str] = None, + url: Optional[str] = None, + path: Optional[str] = None, + query_parameters: Optional[str] = None, + headers_: Optional[dict] = None, + body: Optional[dict] = None, ) -> None: """ - Initialize a SkillsAsyncRequestStatus object. + Initialize a TurnEventCalloutCalloutRequest object. + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to + the URL of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server + or an object. In cases like timeouts or connections errors, it will contain + details of why the callout to the external server failed. """ - self.assistant_id = assistant_id - self.status = status - self.status_description = status_description - self.status_errors = status_errors + self.method = method + self.url = url + self.path = path + self.query_parameters = query_parameters + self.headers_ = headers_ + self.body = body @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': - """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCalloutRequest': + """Initialize a TurnEventCalloutCalloutRequest object from a json dictionary.""" args = {} - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] + if (method := _dict.get('method')) is not None: + args['method'] = method + if (url := _dict.get('url')) is not None: + args['url'] = url + if (path := _dict.get('path')) is not None: + args['path'] = path + if (query_parameters := _dict.get('query_parameters')) is not None: + args['query_parameters'] = query_parameters + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = headers_ + if (body := _dict.get('body')) is not None: + args['body'] = body return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + """Initialize a TurnEventCalloutCalloutRequest 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, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'method') and self.method is not None: + _dict['method'] = self.method + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, + 'query_parameters') and self.query_parameters is not None: + _dict['query_parameters'] = self.query_parameters + if hasattr(self, 'headers_') and self.headers_ is not None: + _dict['headers'] = self.headers_ + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body return _dict def _to_dict(self): @@ -10166,105 +15055,88 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillsAsyncRequestStatus object.""" + """Return a `str` version of this TurnEventCalloutCalloutRequest object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillsAsyncRequestStatus') -> bool: + def __eq__(self, other: 'TurnEventCalloutCalloutRequest') -> 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: 'SkillsAsyncRequestStatus') -> bool: + def __ne__(self, other: 'TurnEventCalloutCalloutRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): + class MethodEnum(str, Enum): """ - The current status of the asynchronous operation: - - `Available`: An asynchronous export is available. - - `Completed`: An asynchronous import operation has completed successfully. - - `Failed`: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - `Processing`: An asynchronous operation has not yet completed. + The REST method of the request. """ - AVAILABLE = 'Available' - COMPLETED = 'Completed' - FAILED = 'Failed' - PROCESSING = 'Processing' + GET = 'get' + POST = 'post' + PUT = 'put' + DELETE = 'delete' + PATCH = 'patch' -class SkillsExport: +class TurnEventCalloutCalloutResponse: """ - SkillsExport. + TurnEventCalloutCalloutResponse. - :param List[Skill] assistant_skills: An array of objects describing the skills - for the assistant. Included in responses only if **status**=`Available`. - :param AssistantState assistant_state: Status information about the skills for - the assistant. Included in responses only if **status**=`Available`. + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. + :param dict last_event: (optional) The response from the last chunk received + from the response stream. """ def __init__( self, - assistant_skills: List['Skill'], - assistant_state: 'AssistantState', + *, + body: Optional[str] = None, + status_code: Optional[int] = None, + last_event: Optional[dict] = None, ) -> None: """ - Initialize a SkillsExport object. + Initialize a TurnEventCalloutCalloutResponse object. - :param List[Skill] assistant_skills: An array of objects describing the - skills for the assistant. Included in responses only if - **status**=`Available`. - :param AssistantState assistant_state: Status information about the skills - for the assistant. Included in responses only if **status**=`Available`. + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. + :param dict last_event: (optional) The response from the last chunk + received from the response stream. """ - self.assistant_skills = assistant_skills - self.assistant_state = assistant_state + self.body = body + self.status_code = status_code + self.last_event = last_event @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillsExport': - """Initialize a SkillsExport object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCalloutResponse': + """Initialize a TurnEventCalloutCalloutResponse object from a json dictionary.""" args = {} - if (assistant_skills := _dict.get('assistant_skills')) is not None: - args['assistant_skills'] = [ - Skill.from_dict(v) for v in assistant_skills - ] - else: - raise ValueError( - 'Required property \'assistant_skills\' not present in SkillsExport JSON' - ) - if (assistant_state := _dict.get('assistant_state')) is not None: - args['assistant_state'] = AssistantState.from_dict(assistant_state) - else: - raise ValueError( - 'Required property \'assistant_state\' not present in SkillsExport JSON' - ) + if (body := _dict.get('body')) is not None: + args['body'] = body + if (status_code := _dict.get('status_code')) is not None: + args['status_code'] = status_code + if (last_event := _dict.get('last_event')) is not None: + args['last_event'] = last_event return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillsExport object from a json dictionary.""" + """Initialize a TurnEventCalloutCalloutResponse 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, - 'assistant_skills') and self.assistant_skills is not None: - assistant_skills_list = [] - for v in self.assistant_skills: - if isinstance(v, dict): - assistant_skills_list.append(v) - else: - assistant_skills_list.append(v.to_dict()) - _dict['assistant_skills'] = assistant_skills_list - if hasattr(self, - 'assistant_state') and self.assistant_state is not None: - if isinstance(self.assistant_state, dict): - _dict['assistant_state'] = self.assistant_state - else: - _dict['assistant_state'] = self.assistant_state.to_dict() + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'status_code') and self.status_code is not None: + _dict['status_code'] = self.status_code + if hasattr(self, 'last_event') and self.last_event is not None: + _dict['last_event'] = self.last_event return _dict def _to_dict(self): @@ -10272,141 +15144,59 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillsExport object.""" + """Return a `str` version of this TurnEventCalloutCalloutResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillsExport') -> bool: + def __eq__(self, other: 'TurnEventCalloutCalloutResponse') -> 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: 'SkillsExport') -> bool: + def __ne__(self, other: 'TurnEventCalloutCalloutResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatefulMessageResponse: +class TurnEventCalloutError: """ - A response from the watsonx Assistant service. + TurnEventCalloutError. - :param MessageOutput output: Assistant output to be rendered or processed by the - client. - :param MessageContext context: (optional) Context data for the conversation. You - can use this property to access context variables. The context is stored by the - assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :param str user_id: A string value that identifies the user who is interacting - with the assistant. The client must provide a unique identifier for each - individual end user who accesses the application. For user-based plans, this - user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. - :param MessageOutput masked_output: (optional) Assistant output to be rendered - or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes the - input text. All private data is masked or removed. + :param str message: (optional) Any error message returned by a failed call to an + external service. """ def __init__( self, - output: 'MessageOutput', - user_id: str, *, - context: Optional['MessageContext'] = None, - masked_output: Optional['MessageOutput'] = None, - masked_input: Optional['MessageInput'] = None, + message: Optional[str] = None, ) -> None: """ - Initialize a StatefulMessageResponse object. + Initialize a TurnEventCalloutError object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param str user_id: A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier - for each individual end user who accesses the application. For user-based - plans, this user ID is used to identify unique users for billing purposes. - This string cannot contain carriage return, newline, or tab characters. If - no value is specified in the input, **user_id** is automatically set to the - value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to access context variables. The - context is stored by the assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :param MessageOutput masked_output: (optional) Assistant output to be - rendered or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes - the input text. All private data is masked or removed. + :param str message: (optional) Any error message returned by a failed call + to an external service. """ - self.output = output - self.context = context - self.user_id = user_id - self.masked_output = masked_output - self.masked_input = masked_input + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'StatefulMessageResponse': - """Initialize a StatefulMessageResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutError': + """Initialize a TurnEventCalloutError object from a json dictionary.""" args = {} - if (output := _dict.get('output')) is not None: - args['output'] = MessageOutput.from_dict(output) - else: - raise ValueError( - 'Required property \'output\' not present in StatefulMessageResponse JSON' - ) - if (context := _dict.get('context')) is not None: - args['context'] = MessageContext.from_dict(context) - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id - else: - raise ValueError( - 'Required property \'user_id\' not present in StatefulMessageResponse JSON' - ) - if (masked_output := _dict.get('masked_output')) is not None: - args['masked_output'] = MessageOutput.from_dict(masked_output) - if (masked_input := _dict.get('masked_input')) is not None: - args['masked_input'] = MessageInput.from_dict(masked_input) + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatefulMessageResponse object from a json dictionary.""" + """Initialize a TurnEventCalloutError 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, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - if hasattr(self, 'masked_output') and self.masked_output is not None: - if isinstance(self.masked_output, dict): - _dict['masked_output'] = self.masked_output - else: - _dict['masked_output'] = self.masked_output.to_dict() - if hasattr(self, 'masked_input') and self.masked_input is not None: - if isinstance(self.masked_input, dict): - _dict['masked_input'] = self.masked_input - else: - _dict['masked_input'] = self.masked_input.to_dict() + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -10414,87 +15204,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatefulMessageResponse object.""" + """Return a `str` version of this TurnEventCalloutError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatefulMessageResponse') -> bool: + def __eq__(self, other: 'TurnEventCalloutError') -> 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: 'StatefulMessageResponse') -> bool: + def __ne__(self, other: 'TurnEventCalloutError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageContext: +class TurnEventNodeSource: """ - StatelessMessageContext. + TurnEventNodeSource. - :param StatelessMessageContextGlobal global_: (optional) Session context data - that is shared by all skills used by the assistant. - :param StatelessMessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str condition: (optional) The condition that triggered the dialog node. """ def __init__( self, *, - global_: Optional['StatelessMessageContextGlobal'] = None, - skills: Optional['StatelessMessageContextSkills'] = None, - integrations: Optional[dict] = None, + type: Optional[str] = None, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + condition: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageContext object. + Initialize a TurnEventNodeSource object. - :param StatelessMessageContextGlobal global_: (optional) Session context - data that is shared by all skills used by the assistant. - :param StatelessMessageContextSkills skills: (optional) Context data - specific to particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that - is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str condition: (optional) The condition that triggered the dialog + node. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.type = type + self.dialog_node = dialog_node + self.title = title + self.condition = condition @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageContext': - """Initialize a StatelessMessageContext object from a json dictionary.""" - args = {} - if (global_ := _dict.get('global')) is not None: - args['global_'] = StatelessMessageContextGlobal.from_dict(global_) - if (skills := _dict.get('skills')) is not None: - args['skills'] = StatelessMessageContextSkills.from_dict(skills) - if (integrations := _dict.get('integrations')) is not None: - args['integrations'] = integrations + def from_dict(cls, _dict: Dict) -> 'TurnEventNodeSource': + """Initialize a TurnEventNodeSource object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageContext object from a json dictionary.""" + """Initialize a TurnEventNodeSource 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, 'global_') and self.global_ is not None: - if isinstance(self.global_, dict): - _dict['global'] = self.global_ - else: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - if isinstance(self.skills, dict): - _dict['skills'] = self.skills - else: - _dict['skills'] = self.skills.to_dict() - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition return _dict def _to_dict(self): @@ -10502,70 +15289,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContext object.""" + """Return a `str` version of this TurnEventNodeSource object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageContext') -> bool: + def __eq__(self, other: 'TurnEventNodeSource') -> 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: 'StatelessMessageContext') -> bool: + def __ne__(self, other: 'TurnEventNodeSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of turn event. + """ + + DIALOG_NODE = 'dialog_node' + -class StatelessMessageContextGlobal: +class TurnEventSearchError: """ - Session context data that is shared by all skills used by the assistant. + TurnEventSearchError. - :param MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param str message: (optional) Any error message returned by a failed call to a + search skill. """ def __init__( self, *, - system: Optional['MessageContextGlobalSystem'] = None, - session_id: Optional[str] = None, + message: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageContextGlobal object. + Initialize a TurnEventSearchError object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param str message: (optional) Any error message returned by a failed call + to a search skill. """ - self.system = system - self.session_id = session_id + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextGlobal': - """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError': + """Initialize a TurnEventSearchError object from a json dictionary.""" args = {} - if (system := _dict.get('system')) is not None: - args['system'] = MessageContextGlobalSystem.from_dict(system) - if (session_id := _dict.get('session_id')) is not None: - args['session_id'] = session_id + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" + """Initialize a TurnEventSearchError 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, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system - else: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -10573,78 +15356,65 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContextGlobal object.""" + """Return a `str` version of this TurnEventSearchError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageContextGlobal') -> bool: + def __eq__(self, other: 'TurnEventSearchError') -> 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: 'StatelessMessageContextGlobal') -> bool: + def __ne__(self, other: 'TurnEventSearchError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageContextSkills: +class UpdateEnvironmentOrchestration: """ - Context data specific to particular skills used by the assistant. + The search skill orchestration settings for the environment. - :param MessageContextDialogSkill main_skill: (optional) Context variables that - are used by the dialog skill. - :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) - Context variables that are used by the action skill. + :param bool search_skill_fallback: (optional) Whether to fall back to a search + skill when responding to messages that do not match any intent or action defined + in dialog or action skills. (If no search skill is configured for the + environment, this property is ignored.). """ def __init__( self, *, - main_skill: Optional['MessageContextDialogSkill'] = None, - actions_skill: Optional[ - 'StatelessMessageContextSkillsActionsSkill'] = None, + search_skill_fallback: Optional[bool] = None, ) -> None: """ - Initialize a StatelessMessageContextSkills object. + Initialize a UpdateEnvironmentOrchestration object. - :param MessageContextDialogSkill main_skill: (optional) Context variables - that are used by the dialog skill. - :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) - Context variables that are used by the action skill. + :param bool search_skill_fallback: (optional) Whether to fall back to a + search skill when responding to messages that do not match any intent or + action defined in dialog or action skills. (If no search skill is + configured for the environment, this property is ignored.). """ - self.main_skill = main_skill - self.actions_skill = actions_skill + self.search_skill_fallback = search_skill_fallback @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextSkills': - """Initialize a StatelessMessageContextSkills object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'UpdateEnvironmentOrchestration': + """Initialize a UpdateEnvironmentOrchestration object from a json dictionary.""" args = {} - if (main_skill := _dict.get('main skill')) is not None: - args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) - if (actions_skill := _dict.get('actions skill')) is not None: - args[ - 'actions_skill'] = StatelessMessageContextSkillsActionsSkill.from_dict( - actions_skill) + if (search_skill_fallback := + _dict.get('search_skill_fallback')) is not None: + args['search_skill_fallback'] = search_skill_fallback return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageContextSkills object from a json dictionary.""" + """Initialize a UpdateEnvironmentOrchestration 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, 'main_skill') and self.main_skill is not None: - if isinstance(self.main_skill, dict): - _dict['main skill'] = self.main_skill - else: - _dict['main skill'] = self.main_skill.to_dict() - if hasattr(self, 'actions_skill') and self.actions_skill is not None: - if isinstance(self.actions_skill, dict): - _dict['actions skill'] = self.actions_skill - else: - _dict['actions skill'] = self.actions_skill.to_dict() + if hasattr(self, 'search_skill_fallback' + ) and self.search_skill_fallback is not None: + _dict['search_skill_fallback'] = self.search_skill_fallback return _dict def _to_dict(self): @@ -10652,134 +15422,57 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContextSkills object.""" + """Return a `str` version of this UpdateEnvironmentOrchestration object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageContextSkills') -> bool: + def __eq__(self, other: 'UpdateEnvironmentOrchestration') -> 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: 'StatelessMessageContextSkills') -> bool: + def __ne__(self, other: 'UpdateEnvironmentOrchestration') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageContextSkillsActionsSkill: +class UpdateEnvironmentReleaseReference: """ - Context variables that are used by the action skill. + An object describing the release that is currently deployed in the environment. - :param dict user_defined: (optional) An object containing any arbitrary - variables that can be read and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data used by - the skill. - :param dict action_variables: (optional) An object containing action variables. - Action variables can be accessed only by steps in the same action, and do not - persist after the action ends. - :param dict skill_variables: (optional) An object containing skill variables. - (In the watsonx Assistant user interface, skill variables are called _session - variables_.) Skill variables can be accessed by any action and persist for the - duration of the session. - :param dict private_action_variables: (optional) An object containing private - action variables. Action variables can be accessed only by steps in the same - action, and do not persist after the action ends. Private variables are - encrypted. - :param dict private_skill_variables: (optional) An object containing private - skill variables. (In the watsonx Assistant user interface, skill variables are - called _session variables_.) Skill variables can be accessed by any action and - persist for the duration of the session. Private variables are encrypted. + :param str release: (optional) The name of the deployed release. """ def __init__( self, *, - user_defined: Optional[dict] = None, - system: Optional['MessageContextSkillSystem'] = None, - action_variables: Optional[dict] = None, - skill_variables: Optional[dict] = None, - private_action_variables: Optional[dict] = None, - private_skill_variables: Optional[dict] = None, + release: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageContextSkillsActionsSkill object. + Initialize a UpdateEnvironmentReleaseReference object. - :param dict user_defined: (optional) An object containing any arbitrary - variables that can be read and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data - used by the skill. - :param dict action_variables: (optional) An object containing action - variables. Action variables can be accessed only by steps in the same - action, and do not persist after the action ends. - :param dict skill_variables: (optional) An object containing skill - variables. (In the watsonx Assistant user interface, skill variables are - called _session variables_.) Skill variables can be accessed by any action - and persist for the duration of the session. - :param dict private_action_variables: (optional) An object containing - private action variables. Action variables can be accessed only by steps in - the same action, and do not persist after the action ends. Private - variables are encrypted. - :param dict private_skill_variables: (optional) An object containing - private skill variables. (In the watsonx Assistant user interface, skill - variables are called _session variables_.) Skill variables can be accessed - by any action and persist for the duration of the session. Private - variables are encrypted. + :param str release: (optional) The name of the deployed release. """ - self.user_defined = user_defined - self.system = system - self.action_variables = action_variables - self.skill_variables = skill_variables - self.private_action_variables = private_action_variables - self.private_skill_variables = private_skill_variables - - @classmethod - def from_dict(cls, - _dict: Dict) -> 'StatelessMessageContextSkillsActionsSkill': - """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" - args = {} - if (user_defined := _dict.get('user_defined')) is not None: - args['user_defined'] = user_defined - if (system := _dict.get('system')) is not None: - args['system'] = MessageContextSkillSystem.from_dict(system) - if (action_variables := _dict.get('action_variables')) is not None: - args['action_variables'] = action_variables - if (skill_variables := _dict.get('skill_variables')) is not None: - args['skill_variables'] = skill_variables - if (private_action_variables := - _dict.get('private_action_variables')) is not None: - args['private_action_variables'] = private_action_variables - if (private_skill_variables := - _dict.get('private_skill_variables')) is not None: - args['private_skill_variables'] = private_skill_variables - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a StatelessMessageContextSkillsActionsSkill 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, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system - else: - _dict['system'] = self.system.to_dict() - if hasattr(self, - 'action_variables') and self.action_variables is not None: - _dict['action_variables'] = self.action_variables - if hasattr(self, - 'skill_variables') and self.skill_variables is not None: - _dict['skill_variables'] = self.skill_variables - if hasattr(self, 'private_action_variables' - ) and self.private_action_variables is not None: - _dict['private_action_variables'] = self.private_action_variables - if hasattr(self, 'private_skill_variables' - ) and self.private_skill_variables is not None: - _dict['private_skill_variables'] = self.private_skill_variables + self.release = release + + @classmethod + def from_dict(cls, _dict: Dict) -> 'UpdateEnvironmentReleaseReference': + """Initialize a UpdateEnvironmentReleaseReference object from a json dictionary.""" + args = {} + if (release := _dict.get('release')) is not None: + args['release'] = release + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a UpdateEnvironmentReleaseReference 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, 'release') and self.release is not None: + _dict['release'] = self.release return _dict def _to_dict(self): @@ -10787,177 +15480,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContextSkillsActionsSkill object.""" + """Return a `str` version of this UpdateEnvironmentReleaseReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'StatelessMessageContextSkillsActionsSkill') -> bool: + def __eq__(self, other: 'UpdateEnvironmentReleaseReference') -> 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: 'StatelessMessageContextSkillsActionsSkill') -> bool: + def __ne__(self, other: 'UpdateEnvironmentReleaseReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageInput: +class CompleteItem(RuntimeResponseGeneric): """ - An input object that includes the input text. + CompleteItem. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating - the user input. Include intents from the previous response to continue using - those intents rather than trying to recognize intents in the new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the Segment - extension. - :param StatelessMessageInputOptions options: (optional) Optional properties that - control how the assistant responds. + :param Metadata streaming_metadata: """ def __init__( self, - *, - message_type: Optional[str] = None, - text: Optional[str] = None, - intents: Optional[List['RuntimeIntent']] = None, - entities: Optional[List['RuntimeEntity']] = None, - suggestion_id: Optional[str] = None, - attachments: Optional[List['MessageInputAttachment']] = None, - analytics: Optional['RequestAnalytics'] = None, - options: Optional['StatelessMessageInputOptions'] = None, + streaming_metadata: 'Metadata', ) -> None: """ - Initialize a StatelessMessageInput object. + Initialize a CompleteItem object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the - Segment extension. - :param StatelessMessageInputOptions options: (optional) Optional properties - that control how the assistant responds. + :param Metadata streaming_metadata: """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.analytics = analytics - self.options = options + # pylint: disable=super-init-not-called + self.streaming_metadata = streaming_metadata @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageInput': - """Initialize a StatelessMessageInput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'CompleteItem': + """Initialize a CompleteItem object from a json dictionary.""" args = {} - if (message_type := _dict.get('message_type')) is not None: - args['message_type'] = message_type - if (text := _dict.get('text')) is not None: - args['text'] = text - if (intents := _dict.get('intents')) is not None: - args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] - if (entities := _dict.get('entities')) is not None: - args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] - if (suggestion_id := _dict.get('suggestion_id')) is not None: - args['suggestion_id'] = suggestion_id - if (attachments := _dict.get('attachments')) is not None: - args['attachments'] = [ - MessageInputAttachment.from_dict(v) for v in attachments - ] - if (analytics := _dict.get('analytics')) is not None: - args['analytics'] = RequestAnalytics.from_dict(analytics) - if (options := _dict.get('options')) is not None: - args['options'] = StatelessMessageInputOptions.from_dict(options) + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = Metadata.from_dict(streaming_metadata) + else: + raise ValueError( + 'Required property \'streaming_metadata\' not present in CompleteItem JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageInput object from a json dictionary.""" + """Initialize a CompleteItem 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, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - attachments_list = [] - for v in self.attachments: - if isinstance(v, dict): - attachments_list.append(v) - else: - attachments_list.append(v.to_dict()) - _dict['attachments'] = attachments_list - if hasattr(self, 'analytics') and self.analytics is not None: - if isinstance(self.analytics, dict): - _dict['analytics'] = self.analytics - else: - _dict['analytics'] = self.analytics.to_dict() - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options + if hasattr( + self, + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata else: - _dict['options'] = self.options.to_dict() + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() return _dict def _to_dict(self): @@ -10965,133 +15547,155 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageInput object.""" + """Return a `str` version of this CompleteItem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageInput') -> bool: + def __eq__(self, other: 'CompleteItem') -> 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: 'StatelessMessageInput') -> bool: + def __ne__(self, other: 'CompleteItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): + +class LogMessageSourceAction(LogMessageSource): + """ + An object that identifies the dialog element that generated the error message. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. + """ + + def __init__( + self, + type: str, + action: str, + ) -> None: """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. + Initialize a LogMessageSourceAction object. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. """ + # pylint: disable=super-init-not-called + self.type = type + self.action = action - TEXT = 'text' - SEARCH = 'search' + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': + """Initialize a LogMessageSourceAction object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceAction JSON' + ) + if (action := _dict.get('action')) is not None: + args['action'] = action + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceAction JSON' + ) + return cls(**args) + @classmethod + def _from_dict(cls, _dict): + """Initialize a LogMessageSourceAction object from a json dictionary.""" + return cls.from_dict(_dict) -class StatelessMessageInputOptions: - """ - Optional properties that control how the assistant responds. + 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 + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + return _dict - :param bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param bool async_callout: (optional) Whether custom extension callouts are - executed asynchronously. Asynchronous execution means the response to the - extension callout will be processed on the subsequent message call, the initial - message response signals to the client that the operation may be long running. - With synchronous execution the custom extension is executed and returns the - response in a single message turn. **Note:** **async_callout** defaults to true - for API versions earlier than 2023-06-15. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + 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 LogMessageSourceAction object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LogMessageSourceAction') -> 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: 'LogMessageSourceAction') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LogMessageSourceDialogNode(LogMessageSource): + """ + An object that identifies the dialog element that generated the error message. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str dialog_node: The unique identifier of the dialog node that generated + the error message. """ def __init__( self, - *, - restart: Optional[bool] = None, - alternate_intents: Optional[bool] = None, - async_callout: Optional[bool] = None, - spelling: Optional['MessageInputOptionsSpelling'] = None, - debug: Optional[bool] = None, + type: str, + dialog_node: str, ) -> None: """ - Initialize a StatelessMessageInputOptions object. + Initialize a LogMessageSourceDialogNode object. - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param bool async_callout: (optional) Whether custom extension callouts are - executed asynchronously. Asynchronous execution means the response to the - extension callout will be processed on the subsequent message call, the - initial message response signals to the client that the operation may be - long running. With synchronous execution the custom extension is executed - and returns the response in a single message turn. **Note:** - **async_callout** defaults to true for API versions earlier than - 2023-06-15. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str dialog_node: The unique identifier of the dialog node that + generated the error message. """ - self.restart = restart - self.alternate_intents = alternate_intents - self.async_callout = async_callout - self.spelling = spelling - self.debug = debug + # pylint: disable=super-init-not-called + self.type = type + self.dialog_node = dialog_node @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageInputOptions': - """Initialize a StatelessMessageInputOptions object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': + """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" args = {} - if (restart := _dict.get('restart')) is not None: - args['restart'] = restart - if (alternate_intents := _dict.get('alternate_intents')) is not None: - args['alternate_intents'] = alternate_intents - if (async_callout := _dict.get('async_callout')) is not None: - args['async_callout'] = async_callout - if (spelling := _dict.get('spelling')) is not None: - args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) - if (debug := _dict.get('debug')) is not None: - args['debug'] = debug + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' + ) + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + else: + raise ValueError( + 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageInputOptions object from a json dictionary.""" + """Initialize a LogMessageSourceDialogNode 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, 'restart') and self.restart is not None: - _dict['restart'] = self.restart - if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'async_callout') and self.async_callout is not None: - _dict['async_callout'] = self.async_callout - if hasattr(self, 'spelling') and self.spelling is not None: - if isinstance(self.spelling, dict): - _dict['spelling'] = self.spelling - else: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node return _dict def _to_dict(self): @@ -11099,137 +15703,102 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageInputOptions object.""" + """Return a `str` version of this LogMessageSourceDialogNode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageInputOptions') -> bool: + def __eq__(self, other: 'LogMessageSourceDialogNode') -> 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: 'StatelessMessageInputOptions') -> bool: + def __ne__(self, other: 'LogMessageSourceDialogNode') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageResponse: +class LogMessageSourceHandler(LogMessageSource): """ - A stateless response from the watsonx Assistant service. + An object that identifies the dialog element that generated the error message. - :param MessageOutput output: Assistant output to be rendered or processed by the - client. - :param StatelessMessageContext context: Context data for the conversation. You - can use this property to access context variables. The context is not stored by - the assistant; to maintain session state, include the context from the response - in the next message. - :param MessageOutput masked_output: (optional) Assistant output to be rendered - or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes the - input text. All private data is masked or removed. - :param str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. + :param str step: (optional) The unique identifier of the step that generated the + error message. + :param str handler: The unique identifier of the handler that generated the + error message. """ def __init__( self, - output: 'MessageOutput', - context: 'StatelessMessageContext', + type: str, + action: str, + handler: str, *, - masked_output: Optional['MessageOutput'] = None, - masked_input: Optional['MessageInput'] = None, - user_id: Optional[str] = None, + step: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageResponse object. + Initialize a LogMessageSourceHandler object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param StatelessMessageContext context: Context data for the conversation. - You can use this property to access context variables. The context is not - stored by the assistant; to maintain session state, include the context - from the response in the next message. - :param MessageOutput masked_output: (optional) Assistant output to be - rendered or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes - the input text. All private data is masked or removed. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str handler: The unique identifier of the handler that generated the + error message. + :param str step: (optional) The unique identifier of the step that + generated the error message. """ - self.output = output - self.context = context - self.masked_output = masked_output - self.masked_input = masked_input - self.user_id = user_id + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step + self.handler = handler @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageResponse': - """Initialize a StatelessMessageResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': + """Initialize a LogMessageSourceHandler object from a json dictionary.""" args = {} - if (output := _dict.get('output')) is not None: - args['output'] = MessageOutput.from_dict(output) + if (type := _dict.get('type')) is not None: + args['type'] = type else: raise ValueError( - 'Required property \'output\' not present in StatelessMessageResponse JSON' + 'Required property \'type\' not present in LogMessageSourceHandler JSON' ) - if (context := _dict.get('context')) is not None: - args['context'] = StatelessMessageContext.from_dict(context) + if (action := _dict.get('action')) is not None: + args['action'] = action else: raise ValueError( - 'Required property \'context\' not present in StatelessMessageResponse JSON' + 'Required property \'action\' not present in LogMessageSourceHandler JSON' + ) + if (step := _dict.get('step')) is not None: + args['step'] = step + if (handler := _dict.get('handler')) is not None: + args['handler'] = handler + else: + raise ValueError( + 'Required property \'handler\' not present in LogMessageSourceHandler JSON' ) - if (masked_output := _dict.get('masked_output')) is not None: - args['masked_output'] = MessageOutput.from_dict(masked_output) - if (masked_input := _dict.get('masked_input')) is not None: - args['masked_input'] = MessageInput.from_dict(masked_input) - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageResponse object from a json dictionary.""" + """Initialize a LogMessageSourceHandler 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, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'masked_output') and self.masked_output is not None: - if isinstance(self.masked_output, dict): - _dict['masked_output'] = self.masked_output - else: - _dict['masked_output'] = self.masked_output.to_dict() - if hasattr(self, 'masked_input') and self.masked_input is not None: - if isinstance(self.masked_input, dict): - _dict['masked_input'] = self.masked_input - else: - _dict['masked_input'] = self.masked_input.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'handler') and self.handler is not None: + _dict['handler'] = self.handler return _dict def _to_dict(self): @@ -11237,58 +15806,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageResponse object.""" + """Return a `str` version of this LogMessageSourceHandler object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageResponse') -> bool: + def __eq__(self, other: 'LogMessageSourceHandler') -> 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: 'StatelessMessageResponse') -> bool: + def __ne__(self, other: 'LogMessageSourceHandler') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatusError: +class LogMessageSourceStep(LogMessageSource): """ - An object describing an error that occurred during processing of an asynchronous - operation. + An object that identifies the dialog element that generated the error message. - :param str message: (optional) The text of the error message. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. + :param str step: The unique identifier of the step that generated the error + message. """ def __init__( self, - *, - message: Optional[str] = None, + type: str, + action: str, + step: str, ) -> None: """ - Initialize a StatusError object. + Initialize a LogMessageSourceStep object. - :param str message: (optional) The text of the error message. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str step: The unique identifier of the step that generated the error + message. """ - self.message = message + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step @classmethod - def from_dict(cls, _dict: Dict) -> 'StatusError': - """Initialize a StatusError object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': + """Initialize a LogMessageSourceStep object from a json dictionary.""" args = {} - if (message := _dict.get('message')) is not None: - args['message'] = message + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceStep JSON' + ) + if (action := _dict.get('action')) is not None: + args['action'] = action + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceStep JSON' + ) + if (step := _dict.get('step')) is not None: + args['step'] = step + else: + raise ValueError( + 'Required property \'step\' not present in LogMessageSourceStep JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatusError object from a json dictionary.""" + """Initialize a LogMessageSourceStep 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, 'message') and self.message is not None: - _dict['message'] = self.message + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step return _dict def _to_dict(self): @@ -11296,84 +15898,112 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatusError object.""" + """Return a `str` version of this LogMessageSourceStep object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatusError') -> bool: + def __eq__(self, other: 'LogMessageSourceStep') -> 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: 'StatusError') -> bool: + def __ne__(self, other: 'LogMessageSourceStep') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TurnEventActionSource: +class MessageOutputDebugTurnEventTurnEventActionFinished( + MessageOutputDebugTurnEvent): """ - TurnEventActionSource. + MessageOutputDebugTurnEventTurnEventActionFinished. - :param str type: (optional) The type of turn event. - :param str action: (optional) An action that was visited during processing of - the message. - :param str action_title: (optional) The title of the action. - :param str condition: (optional) The condition that triggered the dialog node. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables at + the time the action finished. """ def __init__( self, *, - type: Optional[str] = None, - action: Optional[str] = None, - action_title: Optional[str] = None, - condition: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + action_variables: Optional[dict] = None, ) -> None: """ - Initialize a TurnEventActionSource object. + Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object. - :param str type: (optional) The type of turn event. - :param str action: (optional) An action that was visited during processing - of the message. - :param str action_title: (optional) The title of the action. - :param str condition: (optional) The condition that triggered the dialog - node. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables + at the time the action finished. """ - self.type = type - self.action = action - self.action_title = action_title - self.condition = condition + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason + self.action_variables = action_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventActionSource': - """Initialize a TurnEventActionSource object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventActionFinished': + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (action := _dict.get('action')) is not None: - args['action'] = action - if (action_title := _dict.get('action_title')) is not None: - args['action_title'] = action_title - if (condition := _dict.get('condition')) is not None: - args['condition'] = condition + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventActionSource object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished 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 - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'action_title') and self.action_title is not None: - _dict['action_title'] = self.action_title - if hasattr(self, 'condition') and self.condition is not None: - _dict['condition'] = self.condition + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables return _dict def _to_dict(self): @@ -11381,82 +16011,135 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventActionSource object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionFinished object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventActionSource') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> 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: 'TurnEventActionSource') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): + class ConditionTypeEnum(str, Enum): """ - The type of turn event. + The type of condition (if any) that is defined for the action. """ - ACTION = 'action' + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + class ReasonEnum(str, Enum): + """ + The reason the action finished processing. + """ -class TurnEventCalloutCallout: + ALL_STEPS_DONE = 'all_steps_done' + NO_STEPS_VISITED = 'no_steps_visited' + ENDED_BY_STEP = 'ended_by_step' + CONNECT_TO_AGENT = 'connect_to_agent' + MAX_RETRIES_REACHED = 'max_retries_reached' + FALLBACK = 'fallback' + + +class MessageOutputDebugTurnEventTurnEventActionVisited( + MessageOutputDebugTurnEvent): """ - TurnEventCalloutCallout. + MessageOutputDebugTurnEventTurnEventActionVisited. - :param str type: (optional) The type of callout. Currently, the only supported - value is `integration_interaction` (for calls to extensions). - :param dict internal: (optional) For internal use only. - :param str result_variable: (optional) The name of the variable where the - callout result is stored. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the call + to the action is stored. Included only if **reason**=`subaction_return`. """ def __init__( self, *, - type: Optional[str] = None, - internal: Optional[dict] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, result_variable: Optional[str] = None, ) -> None: """ - Initialize a TurnEventCalloutCallout object. + Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. - :param str type: (optional) The type of callout. Currently, the only - supported value is `integration_interaction` (for calls to extensions). - :param dict internal: (optional) For internal use only. - :param str result_variable: (optional) The name of the variable where the - callout result is stored. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the + call to the action is stored. Included only if + **reason**=`subaction_return`. """ - self.type = type - self.internal = internal + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason self.result_variable = result_variable @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': - """Initialize a TurnEventCalloutCallout object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventActionVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (internal := _dict.get('internal')) is not None: - args['internal'] = internal + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason if (result_variable := _dict.get('result_variable')) is not None: args['result_variable'] = result_variable return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventCalloutCallout object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited 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 - if hasattr(self, 'internal') and self.internal is not None: - _dict['internal'] = self.internal + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason if hasattr(self, 'result_variable') and self.result_variable is not None: _dict['result_variable'] = self.result_variable @@ -11467,67 +16150,120 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventCalloutCallout object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventCalloutCallout') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> 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: 'TurnEventCalloutCallout') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): + class ConditionTypeEnum(str, Enum): """ - The type of callout. Currently, the only supported value is - `integration_interaction` (for calls to extensions). + The type of condition (if any) that is defined for the action. """ - INTEGRATION_INTERACTION = 'integration_interaction' + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + class ReasonEnum(str, Enum): + """ + The reason the action was visited. + """ -class TurnEventCalloutError: + INTENT = 'intent' + INVOKE_SUBACTION = 'invoke_subaction' + SUBACTION_RETURN = 'subaction_return' + INVOKE_EXTERNAL = 'invoke_external' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + AGENT_REQUESTED = 'agent_requested' + STEP_VALIDATION_FAILED = 'step_validation_failed' + NO_ACTION_MATCHES = 'no_action_matches' + + +class MessageOutputDebugTurnEventTurnEventCallout(MessageOutputDebugTurnEvent): """ - TurnEventCalloutError. + MessageOutputDebugTurnEventTurnEventCallout. - :param str message: (optional) Any error message returned by a failed call to an - external service. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ def __init__( self, *, - message: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + callout: Optional['TurnEventCalloutCallout'] = None, + error: Optional['TurnEventCalloutError'] = None, ) -> None: """ - Initialize a TurnEventCalloutError object. + Initialize a MessageOutputDebugTurnEventTurnEventCallout object. - :param str message: (optional) Any error message returned by a failed call - to an external service. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ - self.message = message + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.callout = callout + self.error = error @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutError': - """Initialize a TurnEventCalloutError object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventCallout': + """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" args = {} - if (message := _dict.get('message')) is not None: - args['message'] = message + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (callout := _dict.get('callout')) is not None: + args['callout'] = TurnEventCalloutCallout.from_dict(callout) + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventCalloutError.from_dict(error) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventCalloutError object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventCallout 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, 'message') and self.message is not None: - _dict['message'] = self.message + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'callout') and self.callout is not None: + if isinstance(self.callout, dict): + _dict['callout'] = self.callout + else: + _dict['callout'] = self.callout.to_dict() + if hasattr(self, 'error') and self.error is not None: + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -11535,84 +16271,85 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventCalloutError object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventCallout object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventCalloutError') -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> 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: 'TurnEventCalloutError') -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TurnEventNodeSource: +class MessageOutputDebugTurnEventTurnEventHandlerVisited( + MessageOutputDebugTurnEvent): """ - TurnEventNodeSource. + MessageOutputDebugTurnEventTurnEventHandlerVisited. - :param str type: (optional) The type of turn event. - :param str dialog_node: (optional) A dialog node that was visited during - processing of the input message. - :param str title: (optional) The title of the dialog node. - :param str condition: (optional) The condition that triggered the dialog node. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. """ def __init__( self, *, - type: Optional[str] = None, - dialog_node: Optional[str] = None, - title: Optional[str] = None, - condition: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, ) -> None: """ - Initialize a TurnEventNodeSource object. + Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object. - :param str type: (optional) The type of turn event. - :param str dialog_node: (optional) A dialog node that was visited during - processing of the input message. - :param str title: (optional) The title of the dialog node. - :param str condition: (optional) The condition that triggered the dialog - node. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. """ - self.type = type - self.dialog_node = dialog_node - self.title = title - self.condition = condition + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventNodeSource': - """Initialize a TurnEventNodeSource object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventHandlerVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (dialog_node := _dict.get('dialog_node')) is not None: - args['dialog_node'] = dialog_node - if (title := _dict.get('title')) is not None: - args['title'] = title - if (condition := _dict.get('condition')) is not None: - args['condition'] = condition + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventNodeSource object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited 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 - if hasattr(self, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'condition') and self.condition is not None: - _dict['condition'] = self.condition + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time return _dict def _to_dict(self): @@ -11620,66 +16357,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventNodeSource object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventHandlerVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventNodeSource') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> 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: 'TurnEventNodeSource') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of turn event. - """ - - DIALOG_NODE = 'dialog_node' - -class TurnEventSearchError: +class MessageOutputDebugTurnEventTurnEventNodeVisited( + MessageOutputDebugTurnEvent): """ - TurnEventSearchError. + MessageOutputDebugTurnEventTurnEventNodeVisited. - :param str message: (optional) Any error message returned by a failed call to a - search skill. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ def __init__( self, *, - message: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventNodeSource'] = None, + reason: Optional[str] = None, ) -> None: """ - Initialize a TurnEventSearchError object. + Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object. - :param str message: (optional) Any error message returned by a failed call - to a search skill. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ - self.message = message + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.reason = reason @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError': - """Initialize a TurnEventSearchError object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventNodeVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" args = {} - if (message := _dict.get('message')) is not None: - args['message'] = message + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventNodeSource.from_dict(source) + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventSearchError object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited 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, 'message') and self.message is not None: - _dict['message'] = self.message + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason return _dict def _to_dict(self): @@ -11687,77 +16442,97 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventSearchError object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventNodeVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventSearchError') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> 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: 'TurnEventSearchError') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ReasonEnum(str, Enum): + """ + The reason the dialog node was visited. + """ + + WELCOME = 'welcome' + BRANCH_START = 'branch_start' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + TOPIC_SWITCH_WITHOUT_RETURN = 'topic_switch_without_return' + JUMP = 'jump' -class LogMessageSourceAction(LogMessageSource): + +class MessageOutputDebugTurnEventTurnEventSearch(MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventSearch. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the error - message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventSearchError error: (optional) """ def __init__( self, - type: str, - action: str, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + error: Optional['TurnEventSearchError'] = None, ) -> None: """ - Initialize a LogMessageSourceAction object. + Initialize a MessageOutputDebugTurnEventTurnEventSearch object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventSearchError error: (optional) """ # pylint: disable=super-init-not-called - self.type = type - self.action = action + self.event = event + self.source = source + self.error = error @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': - """Initialize a LogMessageSourceAction object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventSearch': + """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceAction JSON' - ) - if (action := _dict.get('action')) is not None: - args['action'] = action - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceAction JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventSearchError.from_dict(error) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceAction object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventSearch 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 - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'error') and self.error is not None: + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -11765,77 +16540,107 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceAction object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventSearch object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceAction') -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> 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: 'LogMessageSourceAction') -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSourceDialogNode(LogMessageSource): +class MessageOutputDebugTurnEventTurnEventStepAnswered( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventStepAnswered. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str dialog_node: The unique identifier of the dialog node that generated - the error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool prompted: (optional) Whether the step was answered in response to a + prompt from the assistant. If this property is `false`, the user provided the + answer without visiting the step. """ def __init__( self, - type: str, - dialog_node: str, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + prompted: Optional[bool] = None, ) -> None: """ - Initialize a LogMessageSourceDialogNode object. + Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str dialog_node: The unique identifier of the dialog node that - generated the error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool prompted: (optional) Whether the step was answered in response + to a prompt from the assistant. If this property is `false`, the user + provided the answer without visiting the step. """ # pylint: disable=super-init-not-called - self.type = type - self.dialog_node = dialog_node + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.prompted = prompted @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepAnswered': + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' - ) - if (dialog_node := _dict.get('dialog_node')) is not None: - args['dialog_node'] = dialog_node - else: - raise ValueError( - 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (prompted := _dict.get('prompted')) is not None: + args['prompted'] = prompted return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered 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 - if hasattr(self, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'prompted') and self.prompted is not None: + _dict['prompted'] = self.prompted return _dict def _to_dict(self): @@ -11843,102 +16648,116 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceDialogNode object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepAnswered object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceDialogNode') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> 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: 'LogMessageSourceDialogNode') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ -class LogMessageSourceHandler(LogMessageSource): + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + +class MessageOutputDebugTurnEventTurnEventStepVisited( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventStepVisited. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the error - message. - :param str step: (optional) The unique identifier of the step that generated the - error message. - :param str handler: The unique identifier of the handler that generated the - error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool has_question: (optional) Whether the step collects a customer + response. """ def __init__( self, - type: str, - action: str, - handler: str, *, - step: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + has_question: Optional[bool] = None, ) -> None: """ - Initialize a LogMessageSourceHandler object. + Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str handler: The unique identifier of the handler that generated the - error message. - :param str step: (optional) The unique identifier of the step that - generated the error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool has_question: (optional) Whether the step collects a customer + response. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step - self.handler = handler + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.has_question = has_question @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': - """Initialize a LogMessageSourceHandler object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceHandler JSON' - ) - if (action := _dict.get('action')) is not None: - args['action'] = action - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceHandler JSON' - ) - if (step := _dict.get('step')) is not None: - args['step'] = step - if (handler := _dict.get('handler')) is not None: - args['handler'] = handler - else: - raise ValueError( - 'Required property \'handler\' not present in LogMessageSourceHandler JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (has_question := _dict.get('has_question')) is not None: + args['has_question'] = has_question return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceHandler object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited 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 - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step - if hasattr(self, 'handler') and self.handler is not None: - _dict['handler'] = self.handler + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'has_question') and self.has_question is not None: + _dict['has_question'] = self.has_question return _dict def _to_dict(self): @@ -11946,91 +16765,124 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceHandler object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceHandler') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> 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: 'LogMessageSourceHandler') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ -class LogMessageSourceStep(LogMessageSource): - """ - An object that identifies the dialog element that generated the error message. + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the error - message. - :param str step: The unique identifier of the step that generated the error - message. + +class ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode( + ProviderAuthenticationOAuth2Flows): + """ + Non-private authentication settings for authorization-code flow. + + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param str authorization_url: (optional) The authorization URL. + :param str redirect_uri: (optional) The redirect URI. """ def __init__( self, - type: str, - action: str, - step: str, + *, + token_url: Optional[str] = None, + refresh_url: Optional[str] = None, + client_auth_type: Optional[str] = None, + content_type: Optional[str] = None, + header_prefix: Optional[str] = None, + authorization_url: Optional[str] = None, + redirect_uri: Optional[str] = None, ) -> None: """ - Initialize a LogMessageSourceStep object. + Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str step: The unique identifier of the step that generated the error - message. + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param str authorization_url: (optional) The authorization URL. + :param str redirect_uri: (optional) The redirect URI. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step + self.token_url = token_url + self.refresh_url = refresh_url + self.client_auth_type = client_auth_type + self.content_type = content_type + self.header_prefix = header_prefix + self.authorization_url = authorization_url + self.redirect_uri = redirect_uri @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': - """Initialize a LogMessageSourceStep object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode': + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceStep JSON' - ) - if (action := _dict.get('action')) is not None: - args['action'] = action - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceStep JSON' - ) - if (step := _dict.get('step')) is not None: - args['step'] = step - else: - raise ValueError( - 'Required property \'step\' not present in LogMessageSourceStep JSON' - ) + if (token_url := _dict.get('token_url')) is not None: + args['token_url'] = token_url + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + if (client_auth_type := _dict.get('client_auth_type')) is not None: + args['client_auth_type'] = client_auth_type + if (content_type := _dict.get('content_type')) is not None: + args['content_type'] = content_type + if (header_prefix := _dict.get('header_prefix')) is not None: + args['header_prefix'] = header_prefix + if (authorization_url := _dict.get('authorization_url')) is not None: + args['authorization_url'] = authorization_url + if (redirect_uri := _dict.get('redirect_uri')) is not None: + args['redirect_uri'] = redirect_uri return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceStep object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode 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 - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step + if hasattr(self, 'token_url') and self.token_url is not None: + _dict['token_url'] = self.token_url + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, + 'client_auth_type') and self.client_auth_type is not None: + _dict['client_auth_type'] = self.client_auth_type + if hasattr(self, 'content_type') and self.content_type is not None: + _dict['content_type'] = self.content_type + if hasattr(self, 'header_prefix') and self.header_prefix is not None: + _dict['header_prefix'] = self.header_prefix + if hasattr(self, + 'authorization_url') and self.authorization_url is not None: + _dict['authorization_url'] = self.authorization_url + if hasattr(self, 'redirect_uri') and self.redirect_uri is not None: + _dict['redirect_uri'] = self.redirect_uri return _dict def _to_dict(self): @@ -12038,112 +16890,108 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceStep object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceStep') -> bool: + def __eq__( + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode' + ) -> 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: 'LogMessageSourceStep') -> bool: + def __ne__( + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ClientAuthTypeEnum(str, Enum): + """ + The client authorization type. + """ -class MessageOutputDebugTurnEventTurnEventActionFinished( - MessageOutputDebugTurnEvent): + BODY = 'Body' + BASICAUTHHEADER = 'BasicAuthHeader' + + +class ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials( + ProviderAuthenticationOAuth2Flows): """ - MessageOutputDebugTurnEventTurnEventActionFinished. + ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. - :param str condition_type: (optional) The type of condition (if any) that is - defined for the action. - :param str reason: (optional) The reason the action finished processing. - :param dict action_variables: (optional) The state of all action variables at - the time the action finished. + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - action_start_time: Optional[str] = None, - condition_type: Optional[str] = None, - reason: Optional[str] = None, - action_variables: Optional[dict] = None, + token_url: Optional[str] = None, + refresh_url: Optional[str] = None, + client_auth_type: Optional[str] = None, + content_type: Optional[str] = None, + header_prefix: Optional[str] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object. + Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. - :param str condition_type: (optional) The type of condition (if any) that - is defined for the action. - :param str reason: (optional) The reason the action finished processing. - :param dict action_variables: (optional) The state of all action variables - at the time the action finished. + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.action_start_time = action_start_time - self.condition_type = condition_type - self.reason = reason - self.action_variables = action_variables + self.token_url = token_url + self.refresh_url = refresh_url + self.client_auth_type = client_auth_type + self.content_type = content_type + self.header_prefix = header_prefix @classmethod def from_dict( - cls, _dict: Dict - ) -> 'MessageOutputDebugTurnEventTurnEventActionFinished': - """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" + cls, _dict: Dict + ) -> 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials': + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time - if (condition_type := _dict.get('condition_type')) is not None: - args['condition_type'] = condition_type - if (reason := _dict.get('reason')) is not None: - args['reason'] = reason - if (action_variables := _dict.get('action_variables')) is not None: - args['action_variables'] = action_variables + if (token_url := _dict.get('token_url')) is not None: + args['token_url'] = token_url + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + if (client_auth_type := _dict.get('client_auth_type')) is not None: + args['client_auth_type'] = client_auth_type + if (content_type := _dict.get('content_type')) is not None: + args['content_type'] = content_type + if (header_prefix := _dict.get('header_prefix')) is not None: + args['header_prefix'] = header_prefix return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time - if hasattr(self, 'condition_type') and self.condition_type is not None: - _dict['condition_type'] = self.condition_type - if hasattr(self, 'reason') and self.reason is not None: - _dict['reason'] = self.reason + if hasattr(self, 'token_url') and self.token_url is not None: + _dict['token_url'] = self.token_url + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url if hasattr(self, - 'action_variables') and self.action_variables is not None: - _dict['action_variables'] = self.action_variables + 'client_auth_type') and self.client_auth_type is not None: + _dict['client_auth_type'] = self.client_auth_type + if hasattr(self, 'content_type') and self.content_type is not None: + _dict['content_type'] = self.content_type + if hasattr(self, 'header_prefix') and self.header_prefix is not None: + _dict['header_prefix'] = self.header_prefix return _dict def _to_dict(self): @@ -12151,11 +16999,12 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionFinished object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials' ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): @@ -12163,126 +17012,112 @@ def __eq__( return self.__dict__ == other.__dict__ def __ne__( - self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials' ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConditionTypeEnum(str, Enum): - """ - The type of condition (if any) that is defined for the action. - """ - - USER_DEFINED = 'user_defined' - WELCOME = 'welcome' - ANYTHING_ELSE = 'anything_else' - - class ReasonEnum(str, Enum): + class ClientAuthTypeEnum(str, Enum): """ - The reason the action finished processing. + The client authorization type. """ - ALL_STEPS_DONE = 'all_steps_done' - NO_STEPS_VISITED = 'no_steps_visited' - ENDED_BY_STEP = 'ended_by_step' - CONNECT_TO_AGENT = 'connect_to_agent' - MAX_RETRIES_REACHED = 'max_retries_reached' - FALLBACK = 'fallback' + BODY = 'Body' + BASICAUTHHEADER = 'BasicAuthHeader' -class MessageOutputDebugTurnEventTurnEventActionVisited( - MessageOutputDebugTurnEvent): +class ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password( + ProviderAuthenticationOAuth2Flows): """ - MessageOutputDebugTurnEventTurnEventActionVisited. - - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. - :param str condition_type: (optional) The type of condition (if any) that is - defined for the action. - :param str reason: (optional) The reason the action was visited. - :param str result_variable: (optional) The variable where the result of the call - to the action is stored. Included only if **reason**=`subaction_return`. + Non-private authentication settings for resource owner password flow. + + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param ProviderAuthenticationOAuth2PasswordUsername username: (optional) The + username for oauth2 authentication when the preferred flow is "password". """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - action_start_time: Optional[str] = None, - condition_type: Optional[str] = None, - reason: Optional[str] = None, - result_variable: Optional[str] = None, + token_url: Optional[str] = None, + refresh_url: Optional[str] = None, + client_auth_type: Optional[str] = None, + content_type: Optional[str] = None, + header_prefix: Optional[str] = None, + username: Optional[ + 'ProviderAuthenticationOAuth2PasswordUsername'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. + Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. - :param str condition_type: (optional) The type of condition (if any) that - is defined for the action. - :param str reason: (optional) The reason the action was visited. - :param str result_variable: (optional) The variable where the result of the - call to the action is stored. Included only if - **reason**=`subaction_return`. + :param str token_url: (optional) The token URL. + :param str refresh_url: (optional) The refresh token URL. + :param str client_auth_type: (optional) The client authorization type. + :param str content_type: (optional) The content type. + :param str header_prefix: (optional) The prefix fo the header. + :param ProviderAuthenticationOAuth2PasswordUsername username: (optional) + The username for oauth2 authentication when the preferred flow is + "password". """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.action_start_time = action_start_time - self.condition_type = condition_type - self.reason = reason - self.result_variable = result_variable + self.token_url = token_url + self.refresh_url = refresh_url + self.client_auth_type = client_auth_type + self.content_type = content_type + self.header_prefix = header_prefix + self.username = username @classmethod def from_dict( - cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventActionVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" + cls, _dict: Dict + ) -> 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password': + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time - if (condition_type := _dict.get('condition_type')) is not None: - args['condition_type'] = condition_type - if (reason := _dict.get('reason')) is not None: - args['reason'] = reason - if (result_variable := _dict.get('result_variable')) is not None: - args['result_variable'] = result_variable + if (token_url := _dict.get('token_url')) is not None: + args['token_url'] = token_url + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + if (client_auth_type := _dict.get('client_auth_type')) is not None: + args['client_auth_type'] = client_auth_type + if (content_type := _dict.get('content_type')) is not None: + args['content_type'] = content_type + if (header_prefix := _dict.get('header_prefix')) is not None: + args['header_prefix'] = header_prefix + if (username := _dict.get('username')) is not None: + args[ + 'username'] = ProviderAuthenticationOAuth2PasswordUsername.from_dict( + username) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time - if hasattr(self, 'condition_type') and self.condition_type is not None: - _dict['condition_type'] = self.condition_type - if hasattr(self, 'reason') and self.reason is not None: - _dict['reason'] = self.reason + if hasattr(self, 'token_url') and self.token_url is not None: + _dict['token_url'] = self.token_url + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url if hasattr(self, - 'result_variable') and self.result_variable is not None: - _dict['result_variable'] = self.result_variable + 'client_auth_type') and self.client_auth_type is not None: + _dict['client_auth_type'] = self.client_auth_type + if hasattr(self, 'content_type') and self.content_type is not None: + _dict['content_type'] = self.content_type + if hasattr(self, 'header_prefix') and self.header_prefix is not None: + _dict['header_prefix'] = self.header_prefix + if hasattr(self, 'username') and self.username is not None: + if isinstance(self.username, dict): + _dict['username'] = self.username + else: + _dict['username'] = self.username.to_dict() return _dict def _to_dict(self): @@ -12290,120 +17125,78 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionVisited object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, - other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password' + ) -> 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: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: + self, other: + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConditionTypeEnum(str, Enum): - """ - The type of condition (if any) that is defined for the action. - """ - - USER_DEFINED = 'user_defined' - WELCOME = 'welcome' - ANYTHING_ELSE = 'anything_else' - - class ReasonEnum(str, Enum): + class ClientAuthTypeEnum(str, Enum): """ - The reason the action was visited. + The client authorization type. """ - INTENT = 'intent' - INVOKE_SUBACTION = 'invoke_subaction' - SUBACTION_RETURN = 'subaction_return' - INVOKE_EXTERNAL = 'invoke_external' - TOPIC_SWITCH = 'topic_switch' - TOPIC_RETURN = 'topic_return' - AGENT_REQUESTED = 'agent_requested' - STEP_VALIDATION_FAILED = 'step_validation_failed' - NO_ACTION_MATCHES = 'no_action_matches' + BODY = 'Body' + BASICAUTHHEADER = 'BasicAuthHeader' -class MessageOutputDebugTurnEventTurnEventCallout(MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationBasicFlow(ProviderPrivateAuthentication): """ - MessageOutputDebugTurnEventTurnEventCallout. + The private data for basic authentication. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param TurnEventCalloutCallout callout: (optional) - :param TurnEventCalloutError error: (optional) + :param ProviderAuthenticationTypeAndValue password: (optional) The password for + bearer authentication. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - callout: Optional['TurnEventCalloutCallout'] = None, - error: Optional['TurnEventCalloutError'] = None, + password: Optional['ProviderAuthenticationTypeAndValue'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventCallout object. + Initialize a ProviderPrivateAuthenticationBasicFlow object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param TurnEventCalloutCallout callout: (optional) - :param TurnEventCalloutError error: (optional) + :param ProviderAuthenticationTypeAndValue password: (optional) The password + for bearer authentication. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.callout = callout - self.error = error + self.password = password @classmethod - def from_dict(cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventCallout': - """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderPrivateAuthenticationBasicFlow': + """Initialize a ProviderPrivateAuthenticationBasicFlow object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (callout := _dict.get('callout')) is not None: - args['callout'] = TurnEventCalloutCallout.from_dict(callout) - if (error := _dict.get('error')) is not None: - args['error'] = TurnEventCalloutError.from_dict(error) + if (password := _dict.get('password')) is not None: + args['password'] = ProviderAuthenticationTypeAndValue.from_dict( + password) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationBasicFlow 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source + if hasattr(self, 'password') and self.password is not None: + if isinstance(self.password, dict): + _dict['password'] = self.password else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'callout') and self.callout is not None: - if isinstance(self.callout, dict): - _dict['callout'] = self.callout - else: - _dict['callout'] = self.callout.to_dict() - if hasattr(self, 'error') and self.error is not None: - if isinstance(self.error, dict): - _dict['error'] = self.error - else: - _dict['error'] = self.error.to_dict() + _dict['password'] = self.password.to_dict() return _dict def _to_dict(self): @@ -12411,85 +17204,64 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventCallout object.""" + """Return a `str` version of this ProviderPrivateAuthenticationBasicFlow object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: + def __eq__(self, other: 'ProviderPrivateAuthenticationBasicFlow') -> 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: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: + def __ne__(self, other: 'ProviderPrivateAuthenticationBasicFlow') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebugTurnEventTurnEventHandlerVisited( - MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationBearerFlow(ProviderPrivateAuthentication): """ - MessageOutputDebugTurnEventTurnEventHandlerVisited. + The private data for bearer authentication. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. + :param ProviderAuthenticationTypeAndValue token: (optional) The token for bearer + authentication. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - action_start_time: Optional[str] = None, + token: Optional['ProviderAuthenticationTypeAndValue'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object. + Initialize a ProviderPrivateAuthenticationBearerFlow object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. + :param ProviderAuthenticationTypeAndValue token: (optional) The token for + bearer authentication. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.action_start_time = action_start_time + self.token = token @classmethod - def from_dict( - cls, _dict: Dict - ) -> 'MessageOutputDebugTurnEventTurnEventHandlerVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'ProviderPrivateAuthenticationBearerFlow': + """Initialize a ProviderPrivateAuthenticationBearerFlow object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time + if (token := _dict.get('token')) is not None: + args['token'] = ProviderAuthenticationTypeAndValue.from_dict(token) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationBearerFlow 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source + if hasattr(self, 'token') and self.token is not None: + if isinstance(self.token, dict): + _dict['token'] = self.token else: - _dict['source'] = self.source.to_dict() - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time + _dict['token'] = self.token.to_dict() return _dict def _to_dict(self): @@ -12497,84 +17269,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventHandlerVisited object.""" + """Return a `str` version of this ProviderPrivateAuthenticationBearerFlow object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' - ) -> bool: + def __eq__(self, other: 'ProviderPrivateAuthenticationBearerFlow') -> 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: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' - ) -> bool: + def __ne__(self, other: 'ProviderPrivateAuthenticationBearerFlow') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebugTurnEventTurnEventNodeVisited( - MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationOAuth2Flow(ProviderPrivateAuthentication): """ - MessageOutputDebugTurnEventTurnEventNodeVisited. + The private data for oauth2 authentication. - :param str event: (optional) The type of turn event. - :param TurnEventNodeSource source: (optional) - :param str reason: (optional) The reason the dialog node was visited. + :param ProviderPrivateAuthenticationOAuth2FlowFlows flows: (optional) Scenarios + performed by the API client to fetch an access token from the authorization + server. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventNodeSource'] = None, - reason: Optional[str] = None, + flows: Optional['ProviderPrivateAuthenticationOAuth2FlowFlows'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object. + Initialize a ProviderPrivateAuthenticationOAuth2Flow object. - :param str event: (optional) The type of turn event. - :param TurnEventNodeSource source: (optional) - :param str reason: (optional) The reason the dialog node was visited. + :param ProviderPrivateAuthenticationOAuth2FlowFlows flows: (optional) + Scenarios performed by the API client to fetch an access token from the + authorization server. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.reason = reason + self.flows = flows @classmethod - def from_dict( - cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventNodeVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'ProviderPrivateAuthenticationOAuth2Flow': + """Initialize a ProviderPrivateAuthenticationOAuth2Flow object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventNodeSource.from_dict(source) - if (reason := _dict.get('reason')) is not None: - args['reason'] = reason + if (flows := _dict.get('flows')) is not None: + args['flows'] = flows return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2Flow 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source + if hasattr(self, 'flows') and self.flows is not None: + if isinstance(self.flows, dict): + _dict['flows'] = self.flows else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'reason') and self.reason is not None: - _dict['reason'] = self.reason + _dict['flows'] = self.flows.to_dict() return _dict def _to_dict(self): @@ -12582,97 +17336,95 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventNodeVisited object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2Flow object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, - other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: + def __eq__(self, other: 'ProviderPrivateAuthenticationOAuth2Flow') -> 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: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: + def __ne__(self, other: 'ProviderPrivateAuthenticationOAuth2Flow') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ReasonEnum(str, Enum): - """ - The reason the dialog node was visited. - """ - - WELCOME = 'welcome' - BRANCH_START = 'branch_start' - TOPIC_SWITCH = 'topic_switch' - TOPIC_RETURN = 'topic_return' - TOPIC_SWITCH_WITHOUT_RETURN = 'topic_switch_without_return' - JUMP = 'jump' - -class MessageOutputDebugTurnEventTurnEventSearch(MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode( + ProviderPrivateAuthenticationOAuth2FlowFlows): """ - MessageOutputDebugTurnEventTurnEventSearch. + Private authentication settings for client credentials flow. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param TurnEventSearchError error: (optional) + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param str authorization_code: (optional) The authorization code. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - error: Optional['TurnEventSearchError'] = None, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + access_token: Optional[str] = None, + refresh_token: Optional[str] = None, + authorization_code: Optional[str] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventSearch object. + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param TurnEventSearchError error: (optional) + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param str authorization_code: (optional) The authorization code. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.error = error + self.client_id = client_id + self.client_secret = client_secret + self.access_token = access_token + self.refresh_token = refresh_token + self.authorization_code = authorization_code @classmethod - def from_dict(cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventSearch': - """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode': + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (error := _dict.get('error')) is not None: - args['error'] = TurnEventSearchError.from_dict(error) + if (client_id := _dict.get('client_id')) is not None: + args['client_id'] = client_id + if (client_secret := _dict.get('client_secret')) is not None: + args['client_secret'] = client_secret + if (access_token := _dict.get('access_token')) is not None: + args['access_token'] = access_token + if (refresh_token := _dict.get('refresh_token')) is not None: + args['refresh_token'] = refresh_token + if (authorization_code := _dict.get('authorization_code')) is not None: + args['authorization_code'] = authorization_code return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'error') and self.error is not None: - if isinstance(self.error, dict): - _dict['error'] = self.error - else: - _dict['error'] = self.error.to_dict() + if hasattr(self, 'client_id') and self.client_id is not None: + _dict['client_id'] = self.client_id + if hasattr(self, 'client_secret') and self.client_secret is not None: + _dict['client_secret'] = self.client_secret + if hasattr(self, 'access_token') and self.access_token is not None: + _dict['access_token'] = self.access_token + if hasattr(self, 'refresh_token') and self.refresh_token is not None: + _dict['refresh_token'] = self.refresh_token + if hasattr( + self, + 'authorization_code') and self.authorization_code is not None: + _dict['authorization_code'] = self.authorization_code return _dict def _to_dict(self): @@ -12680,107 +17432,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventSearch object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: + def __eq__( + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode' + ) -> 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: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: + def __ne__( + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebugTurnEventTurnEventStepAnswered( - MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials( + ProviderPrivateAuthenticationOAuth2FlowFlows): """ - MessageOutputDebugTurnEventTurnEventStepAnswered. + ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that is - defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool prompted: (optional) Whether the step was answered in response to a - prompt from the assistant. If this property is `false`, the user provided the - answer without visiting the step. + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - condition_type: Optional[str] = None, - action_start_time: Optional[str] = None, - prompted: Optional[bool] = None, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + access_token: Optional[str] = None, + refresh_token: Optional[str] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object. + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that - is defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool prompted: (optional) Whether the step was answered in response - to a prompt from the assistant. If this property is `false`, the user - provided the answer without visiting the step. + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.condition_type = condition_type - self.action_start_time = action_start_time - self.prompted = prompted + self.client_id = client_id + self.client_secret = client_secret + self.access_token = access_token + self.refresh_token = refresh_token @classmethod def from_dict( - cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepAnswered': - """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials': + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (condition_type := _dict.get('condition_type')) is not None: - args['condition_type'] = condition_type - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time - if (prompted := _dict.get('prompted')) is not None: - args['prompted'] = prompted + if (client_id := _dict.get('client_id')) is not None: + args['client_id'] = client_id + if (client_secret := _dict.get('client_secret')) is not None: + args['client_secret'] = client_secret + if (access_token := _dict.get('access_token')) is not None: + args['access_token'] = access_token + if (refresh_token := _dict.get('refresh_token')) is not None: + args['refresh_token'] = refresh_token return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'condition_type') and self.condition_type is not None: - _dict['condition_type'] = self.condition_type - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time - if hasattr(self, 'prompted') and self.prompted is not None: - _dict['prompted'] = self.prompted + if hasattr(self, 'client_id') and self.client_id is not None: + _dict['client_id'] = self.client_id + if hasattr(self, 'client_secret') and self.client_secret is not None: + _dict['client_secret'] = self.client_secret + if hasattr(self, 'access_token') and self.access_token is not None: + _dict['access_token'] = self.access_token + if hasattr(self, 'refresh_token') and self.refresh_token is not None: + _dict['refresh_token'] = self.refresh_token return _dict def _to_dict(self): @@ -12788,116 +17524,108 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepAnswered object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, - other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials' + ) -> 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: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConditionTypeEnum(str, Enum): - """ - The type of condition (if any) that is defined for the action. - """ - - USER_DEFINED = 'user_defined' - WELCOME = 'welcome' - ANYTHING_ELSE = 'anything_else' - -class MessageOutputDebugTurnEventTurnEventStepVisited( - MessageOutputDebugTurnEvent): +class ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password( + ProviderPrivateAuthenticationOAuth2FlowFlows): """ - MessageOutputDebugTurnEventTurnEventStepVisited. - - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that is - defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool has_question: (optional) Whether the step collects a customer - response. + Private authentication settings for resource owner password flow. + + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param ProviderPrivateAuthenticationOAuth2PasswordPassword password: (optional) + The password for oauth2 authentication when the preferred flow is "password". """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - condition_type: Optional[str] = None, - action_start_time: Optional[str] = None, - has_question: Optional[bool] = None, + client_id: Optional[str] = None, + client_secret: Optional[str] = None, + access_token: Optional[str] = None, + refresh_token: Optional[str] = None, + password: Optional[ + 'ProviderPrivateAuthenticationOAuth2PasswordPassword'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object. + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that - is defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool has_question: (optional) Whether the step collects a customer - response. + :param str client_id: (optional) The client ID. + :param str client_secret: (optional) The client secret. + :param str access_token: (optional) The access token. + :param str refresh_token: (optional) The refresh token. + :param ProviderPrivateAuthenticationOAuth2PasswordPassword password: + (optional) The password for oauth2 authentication when the preferred flow + is "password". """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.condition_type = condition_type - self.action_start_time = action_start_time - self.has_question = has_question + self.client_id = client_id + self.client_secret = client_secret + self.access_token = access_token + self.refresh_token = refresh_token + self.password = password @classmethod def from_dict( - cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password': + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (condition_type := _dict.get('condition_type')) is not None: - args['condition_type'] = condition_type - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time - if (has_question := _dict.get('has_question')) is not None: - args['has_question'] = has_question + if (client_id := _dict.get('client_id')) is not None: + args['client_id'] = client_id + if (client_secret := _dict.get('client_secret')) is not None: + args['client_secret'] = client_secret + if (access_token := _dict.get('access_token')) is not None: + args['access_token'] = access_token + if (refresh_token := _dict.get('refresh_token')) is not None: + args['refresh_token'] = refresh_token + if (password := _dict.get('password')) is not None: + args[ + 'password'] = ProviderPrivateAuthenticationOAuth2PasswordPassword.from_dict( + password) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source + if hasattr(self, 'client_id') and self.client_id is not None: + _dict['client_id'] = self.client_id + if hasattr(self, 'client_secret') and self.client_secret is not None: + _dict['client_secret'] = self.client_secret + if hasattr(self, 'access_token') and self.access_token is not None: + _dict['access_token'] = self.access_token + if hasattr(self, 'refresh_token') and self.refresh_token is not None: + _dict['refresh_token'] = self.refresh_token + if hasattr(self, 'password') and self.password is not None: + if isinstance(self.password, dict): + _dict['password'] = self.password else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'condition_type') and self.condition_type is not None: - _dict['condition_type'] = self.condition_type - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time - if hasattr(self, 'has_question') and self.has_question is not None: - _dict['has_question'] = self.has_question + _dict['password'] = self.password.to_dict() return _dict def _to_dict(self): @@ -12905,32 +17633,25 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepVisited object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, - other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password' + ) -> 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: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: + self, other: + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConditionTypeEnum(str, Enum): - """ - The type of condition (if any) that is defined for the action. - """ - - USER_DEFINED = 'user_defined' - WELCOME = 'welcome' - ANYTHING_ELSE = 'anything_else' - class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): """ diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 181ca3b5e..9ae2b0d2e 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -21,11 +21,13 @@ from ibm_cloud_sdk_core.authenticators.no_auth_authenticator import NoAuthAuthenticator from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime import inspect +import io import json import pytest import re import requests import responses +import tempfile import urllib from ibm_watson.assistant_v2 import * @@ -47,24 +49,560 @@ def preprocess_url(operation_path: str): The returned request URL is used to register the mock response so it needs to match the request URL that is formed by the requests library. """ - # First, unquote the path since it might have some quoted/escaped characters in it - # due to how the generator inserts the operation paths into the unit test code. - operation_path = urllib.parse.unquote(operation_path) - # Next, quote the path using urllib so that we approximate what will - # happen during request processing. - operation_path = urllib.parse.quote(operation_path, safe='/') - - # Finally, form the request URL from the base URL and operation path. + # Form the request URL from the base URL and operation path. request_url = _base_url + operation_path # If the request url does NOT end with a /, then just return it as-is. # Otherwise, return a regular expression that matches one or more trailing /. - if re.fullmatch('.*/+', request_url) is None: + if not request_url.endswith('/'): return request_url return re.compile(request_url.rstrip('/') + '/+') +############################################################################## +# Start of Service: ConversationalSkillProviders +############################################################################## +# region + + +class TestCreateProvider: + """ + Test Class for create_provider + """ + + @responses.activate + def test_create_provider_all_params(self): + """ + create_provider() + """ + # Set up mock + url = preprocess_url('/v2/providers') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model + + # Set up parameter values + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model + + # Invoke method + response = _service.create_provider( + provider_id, + specification, + private, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['provider_id'] == 'testString' + assert req_body['specification'] == provider_specification_model + assert req_body['private'] == provider_private_model + + def test_create_provider_all_params_with_retries(self): + # Enable retries and run test_create_provider_all_params. + _service.enable_retries() + self.test_create_provider_all_params() + + # Disable retries and run test_create_provider_all_params. + _service.disable_retries() + self.test_create_provider_all_params() + + @responses.activate + def test_create_provider_value_error(self): + """ + test_create_provider_value_error() + """ + # Set up mock + url = preprocess_url('/v2/providers') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model + + # Set up parameter values + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "provider_id": provider_id, + "specification": specification, + "private": private, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_provider(**req_copy) + + def test_create_provider_value_error_with_retries(self): + # Enable retries and run test_create_provider_value_error. + _service.enable_retries() + self.test_create_provider_value_error() + + # Disable retries and run test_create_provider_value_error. + _service.disable_retries() + self.test_create_provider_value_error() + + +class TestListProviders: + """ + Test Class for list_providers + """ + + @responses.activate + def test_list_providers_all_params(self): + """ + list_providers() + """ + # Set up mock + url = preprocess_url('/v2/providers') + mock_response = '{"conversational_skill_providers": [{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + page_limit = 100 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False + + # Invoke method + response = _service.list_providers( + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_list_providers_all_params_with_retries(self): + # Enable retries and run test_list_providers_all_params. + _service.enable_retries() + self.test_list_providers_all_params() + + # Disable retries and run test_list_providers_all_params. + _service.disable_retries() + self.test_list_providers_all_params() + + @responses.activate + def test_list_providers_required_params(self): + """ + test_list_providers_required_params() + """ + # Set up mock + url = preprocess_url('/v2/providers') + mock_response = '{"conversational_skill_providers": [{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Invoke method + response = _service.list_providers() + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_list_providers_required_params_with_retries(self): + # Enable retries and run test_list_providers_required_params. + _service.enable_retries() + self.test_list_providers_required_params() + + # Disable retries and run test_list_providers_required_params. + _service.disable_retries() + self.test_list_providers_required_params() + + @responses.activate + def test_list_providers_value_error(self): + """ + test_list_providers_value_error() + """ + # Set up mock + url = preprocess_url('/v2/providers') + mock_response = '{"conversational_skill_providers": [{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.list_providers(**req_copy) + + def test_list_providers_value_error_with_retries(self): + # Enable retries and run test_list_providers_value_error. + _service.enable_retries() + self.test_list_providers_value_error() + + # Disable retries and run test_list_providers_value_error. + _service.disable_retries() + self.test_list_providers_value_error() + + +class TestUpdateProvider: + """ + Test Class for update_provider + """ + + @responses.activate + def test_update_provider_all_params(self): + """ + update_provider() + """ + # Set up mock + url = preprocess_url('/v2/providers/testString') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model + + # Set up parameter values + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model + + # Invoke method + response = _service.update_provider( + provider_id, + specification, + private, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['specification'] == provider_specification_model + assert req_body['private'] == provider_private_model + + def test_update_provider_all_params_with_retries(self): + # Enable retries and run test_update_provider_all_params. + _service.enable_retries() + self.test_update_provider_all_params() + + # Disable retries and run test_update_provider_all_params. + _service.disable_retries() + self.test_update_provider_all_params() + + @responses.activate + def test_update_provider_value_error(self): + """ + test_update_provider_value_error() + """ + # Set up mock + url = preprocess_url('/v2/providers/testString') + mock_response = '{"provider_id": "provider_id", "specification": {"servers": [{"url": "url"}], "components": {"securitySchemes": {"authentication_method": "basic", "basic": {"username": {"type": "value", "value": "value"}}, "oauth2": {"preferred_flow": "password", "flows": {"token_url": "token_url", "refresh_url": "refresh_url", "client_auth_type": "Body", "content_type": "content_type", "header_prefix": "header_prefix", "username": {"type": "value", "value": "value"}}}}}}}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Construct a dict representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model = {} + provider_specification_servers_item_model['url'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model = {} + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model = {} + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model = {} + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a dict representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_model = {} + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a dict representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model = {} + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a dict representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model = {} + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a dict representation of a ProviderSpecificationComponents model + provider_specification_components_model = {} + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a dict representation of a ProviderSpecification model + provider_specification_model = {} + provider_specification_model['servers'] = [provider_specification_servers_item_model] + provider_specification_model['components'] = provider_specification_components_model + + # Construct a dict representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_model = {} + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a dict representation of a ProviderPrivate model + provider_private_model = {} + provider_private_model['authentication'] = provider_private_authentication_model + + # Set up parameter values + provider_id = 'testString' + specification = provider_specification_model + private = provider_private_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "provider_id": provider_id, + "specification": specification, + "private": private, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_provider(**req_copy) + + def test_update_provider_value_error_with_retries(self): + # Enable retries and run test_update_provider_value_error. + _service.enable_retries() + self.test_update_provider_value_error() + + # Disable retries and run test_update_provider_value_error. + _service.disable_retries() + self.test_update_provider_value_error() + + +# endregion +############################################################################## +# End of Service: ConversationalSkillProviders +############################################################################## + ############################################################################## # Start of Service: Assistants ############################################################################## @@ -784,6 +1322,7 @@ def test_message_all_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' session_id = 'testString' input = message_input_model context = message_context_model @@ -792,6 +1331,7 @@ def test_message_all_params(self): # Invoke method response = _service.message( assistant_id, + environment_id, session_id, input=input, context=context, @@ -835,11 +1375,13 @@ def test_message_required_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' session_id = 'testString' # Invoke method response = _service.message( assistant_id, + environment_id, session_id, headers={}, ) @@ -875,11 +1417,13 @@ def test_message_value_error(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' session_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "environment_id": environment_id, "session_id": session_id, } for param in req_param_dict.keys(): @@ -1062,6 +1606,7 @@ def test_message_stateless_all_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' input = stateless_message_input_model context = stateless_message_context_model user_id = 'testString' @@ -1069,6 +1614,7 @@ def test_message_stateless_all_params(self): # Invoke method response = _service.message_stateless( assistant_id, + environment_id, input=input, context=context, user_id=user_id, @@ -1111,10 +1657,12 @@ def test_message_stateless_required_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' # Invoke method response = _service.message_stateless( assistant_id, + environment_id, headers={}, ) @@ -1149,10 +1697,12 @@ def test_message_stateless_value_error(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} @@ -1175,198 +1725,236 @@ def test_message_stateless_value_error_with_retries(self): ############################################################################## ############################################################################## -# Start of Service: BulkClassify +# Start of Service: MessageStream ############################################################################## # region -class TestBulkClassify: +class TestMessageStream: """ - Test Class for bulk_classify + Test Class for message_stream """ @responses.activate - def test_bulk_classify_all_params(self): + def test_message_stream_all_params(self): """ - bulk_classify() + message_stream() """ # Set up mock - url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message_stream') + mock_response = 'This is a mock binary response.' responses.add( responses.POST, url, body=mock_response, - content_type='application/json', + content_type='text/event-stream', status=200, ) - # Construct a dict representation of a BulkClassifyUtterance model - bulk_classify_utterance_model = {} - bulk_classify_utterance_model['text'] = 'testString' + # Construct a dict representation of a RuntimeIntent model + runtime_intent_model = {} + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' - # Set up parameter values - skill_id = 'testString' - input = [bulk_classify_utterance_model] + # Construct a dict representation of a CaptureGroup model + capture_group_model = {} + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] - # Invoke method - response = _service.bulk_classify( - skill_id, - input, - headers={}, - ) + # Construct a dict representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model = {} + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['input'] == [bulk_classify_utterance_model] + # Construct a dict representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model = {} + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 - def test_bulk_classify_all_params_with_retries(self): - # Enable retries and run test_bulk_classify_all_params. - _service.enable_retries() - self.test_bulk_classify_all_params() + # Construct a dict representation of a RuntimeEntityRole model + runtime_entity_role_model = {} + runtime_entity_role_model['type'] = 'date_from' - # Disable retries and run test_bulk_classify_all_params. - _service.disable_retries() - self.test_bulk_classify_all_params() + # Construct a dict representation of a RuntimeEntity model + runtime_entity_model = {} + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - @responses.activate - def test_bulk_classify_value_error(self): - """ - test_bulk_classify_value_error() - """ - # Set up mock - url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') - mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) + # Construct a dict representation of a MessageInputAttachment model + message_input_attachment_model = {} + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' - # Construct a dict representation of a BulkClassifyUtterance model - bulk_classify_utterance_model = {} - bulk_classify_utterance_model['text'] = 'testString' + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' - # Set up parameter values - skill_id = 'testString' - input = [bulk_classify_utterance_model] + # Construct a dict representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model = {} + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "skill_id": skill_id, - "input": input, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.bulk_classify(**req_copy) + # Construct a dict representation of a MessageInputOptions model + message_input_options_model = {} + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False - def test_bulk_classify_value_error_with_retries(self): - # Enable retries and run test_bulk_classify_value_error. - _service.enable_retries() - self.test_bulk_classify_value_error() + # Construct a dict representation of a MessageInput model + message_input_model = {} + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model - # Disable retries and run test_bulk_classify_value_error. - _service.disable_retries() - self.test_bulk_classify_value_error() + # Construct a dict representation of a MessageContextGlobalSystem model + message_context_global_system_model = {} + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + # Construct a dict representation of a MessageContextGlobal model + message_context_global_model = {} + message_context_global_model['system'] = message_context_global_system_model -# endregion -############################################################################## -# End of Service: BulkClassify -############################################################################## + # Construct a dict representation of a MessageContextSkillSystem model + message_context_skill_system_model = {} + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' -############################################################################## -# Start of Service: Logs -############################################################################## -# region + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Construct a dict representation of a MessageContextActionSkill model + message_context_action_skill_model = {} + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} -class TestListLogs: - """ - Test Class for list_logs - """ + # Construct a dict representation of a MessageContextSkills model + message_context_skills_model = {} + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - @responses.activate - def test_list_logs_all_params(self): - """ - list_logs() - """ - # Set up mock - url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) + # Construct a dict representation of a MessageContext model + message_context_model = {} + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} # Set up parameter values assistant_id = 'testString' - sort = 'testString' - filter = 'testString' - page_limit = 100 - cursor = 'testString' + environment_id = 'testString' + session_id = 'testString' + input = message_input_model + context = message_context_model + user_id = 'testString' # Invoke method - response = _service.list_logs( + response = _service.message_stream( assistant_id, - sort=sort, - filter=filter, - page_limit=page_limit, - cursor=cursor, + environment_id, + session_id, + input=input, + context=context, + user_id=user_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'sort={}'.format(sort) in query_string - assert 'filter={}'.format(filter) in query_string - assert 'page_limit={}'.format(page_limit) in query_string - assert 'cursor={}'.format(cursor) in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == message_input_model + assert req_body['context'] == message_context_model + assert req_body['user_id'] == 'testString' - def test_list_logs_all_params_with_retries(self): - # Enable retries and run test_list_logs_all_params. + def test_message_stream_all_params_with_retries(self): + # Enable retries and run test_message_stream_all_params. _service.enable_retries() - self.test_list_logs_all_params() + self.test_message_stream_all_params() - # Disable retries and run test_list_logs_all_params. + # Disable retries and run test_message_stream_all_params. _service.disable_retries() - self.test_list_logs_all_params() + self.test_message_stream_all_params() @responses.activate - def test_list_logs_required_params(self): + def test_message_stream_required_params(self): """ - test_list_logs_required_params() + test_message_stream_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message_stream') + mock_response = 'This is a mock binary response.' responses.add( - responses.GET, + responses.POST, url, body=mock_response, - content_type='application/json', + content_type='text/event-stream', status=200, ) # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' # Invoke method - response = _service.list_logs( + response = _service.message_stream( assistant_id, + environment_id, + session_id, headers={}, ) @@ -1374,304 +1962,465 @@ def test_list_logs_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 - def test_list_logs_required_params_with_retries(self): - # Enable retries and run test_list_logs_required_params. + def test_message_stream_required_params_with_retries(self): + # Enable retries and run test_message_stream_required_params. _service.enable_retries() - self.test_list_logs_required_params() + self.test_message_stream_required_params() - # Disable retries and run test_list_logs_required_params. + # Disable retries and run test_message_stream_required_params. _service.disable_retries() - self.test_list_logs_required_params() + self.test_message_stream_required_params() @responses.activate - def test_list_logs_value_error(self): + def test_message_stream_value_error(self): """ - test_list_logs_value_error() + test_message_stream_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message_stream') + mock_response = 'This is a mock binary response.' responses.add( - responses.GET, + responses.POST, url, body=mock_response, - content_type='application/json', + content_type='text/event-stream', status=200, ) # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' + session_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "environment_id": environment_id, + "session_id": session_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_logs(**req_copy) + _service.message_stream(**req_copy) - def test_list_logs_value_error_with_retries(self): - # Enable retries and run test_list_logs_value_error. + def test_message_stream_value_error_with_retries(self): + # Enable retries and run test_message_stream_value_error. _service.enable_retries() - self.test_list_logs_value_error() + self.test_message_stream_value_error() - # Disable retries and run test_list_logs_value_error. + # Disable retries and run test_message_stream_value_error. _service.disable_retries() - self.test_list_logs_value_error() + self.test_message_stream_value_error() -# endregion -############################################################################## -# End of Service: Logs -############################################################################## +class TestMessageStreamStateless: + """ + Test Class for message_stream_stateless + """ -############################################################################## -# Start of Service: UserData -############################################################################## -# region + @responses.activate + def test_message_stream_stateless_all_params(self): + """ + message_stream_stateless() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/environments/testString/message_stream') + mock_response = 'This is a mock binary response.' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='text/event-stream', + status=200, + ) + + # Construct a dict representation of a RuntimeIntent model + runtime_intent_model = {} + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + # Construct a dict representation of a CaptureGroup model + capture_group_model = {} + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] -class TestDeleteUserData: - """ - Test Class for delete_user_data - """ + # Construct a dict representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model = {} + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + # Construct a dict representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model = {} + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + # Construct a dict representation of a RuntimeEntityRole model + runtime_entity_role_model = {} + runtime_entity_role_model['type'] = 'date_from' + + # Construct a dict representation of a RuntimeEntity model + runtime_entity_model = {} + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + # Construct a dict representation of a MessageInputAttachment model + message_input_attachment_model = {} + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + # Construct a dict representation of a RequestAnalytics model + request_analytics_model = {} + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + # Construct a dict representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model = {} + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a dict representation of a MessageInputOptions model + message_input_options_model = {} + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + # Construct a dict representation of a MessageInput model + message_input_model = {} + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a dict representation of a MessageContextGlobalSystem model + message_context_global_system_model = {} + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + # Construct a dict representation of a MessageContextGlobal model + message_context_global_model = {} + message_context_global_model['system'] = message_context_global_system_model + + # Construct a dict representation of a MessageContextSkillSystem model + message_context_skill_system_model = {} + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + # Construct a dict representation of a MessageContextDialogSkill model + message_context_dialog_skill_model = {} + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + # Construct a dict representation of a MessageContextActionSkill model + message_context_action_skill_model = {} + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a MessageContextSkills model + message_context_skills_model = {} + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + # Construct a dict representation of a MessageContext model + message_context_model = {} + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + # Set up parameter values + assistant_id = 'testString' + environment_id = 'testString' + input = message_input_model + context = message_context_model + user_id = 'testString' + + # Invoke method + response = _service.message_stream_stateless( + assistant_id, + environment_id, + input=input, + context=context, + user_id=user_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == message_input_model + assert req_body['context'] == message_context_model + assert req_body['user_id'] == 'testString' + + def test_message_stream_stateless_all_params_with_retries(self): + # Enable retries and run test_message_stream_stateless_all_params. + _service.enable_retries() + self.test_message_stream_stateless_all_params() + + # Disable retries and run test_message_stream_stateless_all_params. + _service.disable_retries() + self.test_message_stream_stateless_all_params() @responses.activate - def test_delete_user_data_all_params(self): + def test_message_stream_stateless_required_params(self): """ - delete_user_data() + test_message_stream_stateless_required_params() """ # Set up mock - url = preprocess_url('/v2/user_data') + url = preprocess_url('/v2/assistants/testString/environments/testString/message_stream') + mock_response = 'This is a mock binary response.' responses.add( - responses.DELETE, + responses.POST, url, - status=202, + body=mock_response, + content_type='text/event-stream', + status=200, ) # Set up parameter values - customer_id = 'testString' + assistant_id = 'testString' + environment_id = 'testString' # Invoke method - response = _service.delete_user_data( - customer_id, + response = _service.message_stream_stateless( + assistant_id, + environment_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'customer_id={}'.format(customer_id) in query_string + assert response.status_code == 200 - def test_delete_user_data_all_params_with_retries(self): - # Enable retries and run test_delete_user_data_all_params. + def test_message_stream_stateless_required_params_with_retries(self): + # Enable retries and run test_message_stream_stateless_required_params. _service.enable_retries() - self.test_delete_user_data_all_params() + self.test_message_stream_stateless_required_params() - # Disable retries and run test_delete_user_data_all_params. + # Disable retries and run test_message_stream_stateless_required_params. _service.disable_retries() - self.test_delete_user_data_all_params() + self.test_message_stream_stateless_required_params() @responses.activate - def test_delete_user_data_value_error(self): + def test_message_stream_stateless_value_error(self): """ - test_delete_user_data_value_error() + test_message_stream_stateless_value_error() """ # Set up mock - url = preprocess_url('/v2/user_data') + url = preprocess_url('/v2/assistants/testString/environments/testString/message_stream') + mock_response = 'This is a mock binary response.' responses.add( - responses.DELETE, + responses.POST, url, - status=202, + body=mock_response, + content_type='text/event-stream', + status=200, ) # Set up parameter values - customer_id = 'testString' + assistant_id = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { - "customer_id": customer_id, + "assistant_id": assistant_id, + "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.delete_user_data(**req_copy) + _service.message_stream_stateless(**req_copy) - def test_delete_user_data_value_error_with_retries(self): - # Enable retries and run test_delete_user_data_value_error. + def test_message_stream_stateless_value_error_with_retries(self): + # Enable retries and run test_message_stream_stateless_value_error. _service.enable_retries() - self.test_delete_user_data_value_error() + self.test_message_stream_stateless_value_error() - # Disable retries and run test_delete_user_data_value_error. + # Disable retries and run test_message_stream_stateless_value_error. _service.disable_retries() - self.test_delete_user_data_value_error() + self.test_message_stream_stateless_value_error() # endregion ############################################################################## -# End of Service: UserData +# End of Service: MessageStream ############################################################################## ############################################################################## -# Start of Service: Environments +# Start of Service: BulkClassify ############################################################################## # region -class TestListEnvironments: +class TestBulkClassify: """ - Test Class for list_environments + Test Class for bulk_classify """ @responses.activate - def test_list_environments_all_params(self): + def test_bulk_classify_all_params(self): """ - list_environments() + bulk_classify() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments') - mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', status=200, ) - # Set up parameter values - assistant_id = 'testString' - page_limit = 100 - include_count = False - sort = 'name' - cursor = 'testString' - include_audit = False - - # Invoke method - response = _service.list_environments( - assistant_id, - page_limit=page_limit, - include_count=include_count, - sort=sort, - cursor=cursor, - include_audit=include_audit, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'page_limit={}'.format(page_limit) in query_string - assert 'include_count={}'.format('true' if include_count else 'false') in query_string - assert 'sort={}'.format(sort) in query_string - assert 'cursor={}'.format(cursor) in query_string - assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - - def test_list_environments_all_params_with_retries(self): - # Enable retries and run test_list_environments_all_params. - _service.enable_retries() - self.test_list_environments_all_params() - - # Disable retries and run test_list_environments_all_params. - _service.disable_retries() - self.test_list_environments_all_params() - - @responses.activate - def test_list_environments_required_params(self): - """ - test_list_environments_required_params() - """ - # Set up mock - url = preprocess_url('/v2/assistants/testString/environments') - mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' - responses.add( - responses.GET, - url, - body=mock_response, - content_type='application/json', - status=200, - ) + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' # Set up parameter values - assistant_id = 'testString' + skill_id = 'testString' + input = [bulk_classify_utterance_model] # Invoke method - response = _service.list_environments( - assistant_id, + response = _service.bulk_classify( + skill_id, + input, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['input'] == [bulk_classify_utterance_model] - def test_list_environments_required_params_with_retries(self): - # Enable retries and run test_list_environments_required_params. + def test_bulk_classify_all_params_with_retries(self): + # Enable retries and run test_bulk_classify_all_params. _service.enable_retries() - self.test_list_environments_required_params() + self.test_bulk_classify_all_params() - # Disable retries and run test_list_environments_required_params. + # Disable retries and run test_bulk_classify_all_params. _service.disable_retries() - self.test_list_environments_required_params() + self.test_bulk_classify_all_params() @responses.activate - def test_list_environments_value_error(self): + def test_bulk_classify_value_error(self): """ - test_list_environments_value_error() + test_bulk_classify_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments') - mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/skills/testString/workspace/bulk_classify') + mock_response = '{"output": [{"input": {"text": "text"}, "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}]}]}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', status=200, ) + # Construct a dict representation of a BulkClassifyUtterance model + bulk_classify_utterance_model = {} + bulk_classify_utterance_model['text'] = 'testString' + # Set up parameter values - assistant_id = 'testString' + skill_id = 'testString' + input = [bulk_classify_utterance_model] # Pass in all but one required param and check for a ValueError req_param_dict = { - "assistant_id": assistant_id, + "skill_id": skill_id, + "input": input, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_environments(**req_copy) + _service.bulk_classify(**req_copy) - def test_list_environments_value_error_with_retries(self): - # Enable retries and run test_list_environments_value_error. + def test_bulk_classify_value_error_with_retries(self): + # Enable retries and run test_bulk_classify_value_error. _service.enable_retries() - self.test_list_environments_value_error() + self.test_bulk_classify_value_error() - # Disable retries and run test_list_environments_value_error. + # Disable retries and run test_bulk_classify_value_error. _service.disable_retries() - self.test_list_environments_value_error() + self.test_bulk_classify_value_error() -class TestGetEnvironment: +# endregion +############################################################################## +# End of Service: BulkClassify +############################################################################## + +############################################################################## +# Start of Service: Logs +############################################################################## +# region + + +class TestListLogs: """ - Test Class for get_environment + Test Class for list_logs """ @responses.activate - def test_get_environment_all_params(self): + def test_list_logs_all_params(self): """ - get_environment() + list_logs() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -1682,14 +2431,18 @@ def test_get_environment_all_params(self): # Set up parameter values assistant_id = 'testString' - environment_id = 'testString' - include_audit = False + sort = 'testString' + filter = 'testString' + page_limit = 100 + cursor = 'testString' # Invoke method - response = _service.get_environment( + response = _service.list_logs( assistant_id, - environment_id, - include_audit=include_audit, + sort=sort, + filter=filter, + page_limit=page_limit, + cursor=cursor, headers={}, ) @@ -1699,25 +2452,28 @@ def test_get_environment_all_params(self): # Validate query params query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) - assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'filter={}'.format(filter) in query_string + assert 'page_limit={}'.format(page_limit) in query_string + assert 'cursor={}'.format(cursor) in query_string - def test_get_environment_all_params_with_retries(self): - # Enable retries and run test_get_environment_all_params. + def test_list_logs_all_params_with_retries(self): + # Enable retries and run test_list_logs_all_params. _service.enable_retries() - self.test_get_environment_all_params() + self.test_list_logs_all_params() - # Disable retries and run test_get_environment_all_params. + # Disable retries and run test_list_logs_all_params. _service.disable_retries() - self.test_get_environment_all_params() + self.test_list_logs_all_params() @responses.activate - def test_get_environment_required_params(self): + def test_list_logs_required_params(self): """ - test_get_environment_required_params() + test_list_logs_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -1728,12 +2484,10 @@ def test_get_environment_required_params(self): # Set up parameter values assistant_id = 'testString' - environment_id = 'testString' # Invoke method - response = _service.get_environment( + response = _service.list_logs( assistant_id, - environment_id, headers={}, ) @@ -1741,23 +2495,23 @@ def test_get_environment_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 - def test_get_environment_required_params_with_retries(self): - # Enable retries and run test_get_environment_required_params. + def test_list_logs_required_params_with_retries(self): + # Enable retries and run test_list_logs_required_params. _service.enable_retries() - self.test_get_environment_required_params() + self.test_list_logs_required_params() - # Disable retries and run test_get_environment_required_params. + # Disable retries and run test_list_logs_required_params. _service.disable_retries() - self.test_get_environment_required_params() + self.test_list_logs_required_params() @responses.activate - def test_get_environment_value_error(self): + def test_list_logs_value_error(self): """ - test_get_environment_value_error() + test_list_logs_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/logs') + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -1768,293 +2522,240 @@ def test_get_environment_value_error(self): # Set up parameter values assistant_id = 'testString' - environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_environment(**req_copy) + _service.list_logs(**req_copy) - def test_get_environment_value_error_with_retries(self): - # Enable retries and run test_get_environment_value_error. + def test_list_logs_value_error_with_retries(self): + # Enable retries and run test_list_logs_value_error. _service.enable_retries() - self.test_get_environment_value_error() + self.test_list_logs_value_error() - # Disable retries and run test_get_environment_value_error. + # Disable retries and run test_list_logs_value_error. _service.disable_retries() - self.test_get_environment_value_error() + self.test_list_logs_value_error() -class TestUpdateEnvironment: +# endregion +############################################################################## +# End of Service: Logs +############################################################################## + +############################################################################## +# Start of Service: UserData +############################################################################## +# region + + +class TestDeleteUserData: """ - Test Class for update_environment + Test Class for delete_user_data """ @responses.activate - def test_update_environment_all_params(self): + def test_delete_user_data_all_params(self): """ - update_environment() + delete_user_data() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/user_data') responses.add( - responses.POST, + responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=200, + status=202, ) - # Construct a dict representation of a BaseEnvironmentOrchestration model - base_environment_orchestration_model = {} - base_environment_orchestration_model['search_skill_fallback'] = True - - # Construct a dict representation of a EnvironmentSkill model - environment_skill_model = {} - environment_skill_model['skill_id'] = 'testString' - environment_skill_model['type'] = 'dialog' - environment_skill_model['disabled'] = True - environment_skill_model['snapshot'] = 'testString' - environment_skill_model['skill_reference'] = 'testString' - # Set up parameter values - assistant_id = 'testString' - environment_id = 'testString' - name = 'testString' - description = 'testString' - orchestration = base_environment_orchestration_model - session_timeout = 10 - skill_references = [environment_skill_model] - - # Invoke method - response = _service.update_environment( - assistant_id, - environment_id, - name=name, - description=description, - orchestration=orchestration, - session_timeout=session_timeout, - skill_references=skill_references, - headers={}, - ) - - # Check for correct operation - assert len(responses.calls) == 1 - assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['orchestration'] == base_environment_orchestration_model - assert req_body['session_timeout'] == 10 - assert req_body['skill_references'] == [environment_skill_model] - - def test_update_environment_all_params_with_retries(self): - # Enable retries and run test_update_environment_all_params. - _service.enable_retries() - self.test_update_environment_all_params() - - # Disable retries and run test_update_environment_all_params. - _service.disable_retries() - self.test_update_environment_all_params() - - @responses.activate - def test_update_environment_required_params(self): - """ - test_update_environment_required_params() - """ - # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' - responses.add( - responses.POST, - url, - body=mock_response, - content_type='application/json', - status=200, - ) - - # Set up parameter values - assistant_id = 'testString' - environment_id = 'testString' + customer_id = 'testString' # Invoke method - response = _service.update_environment( - assistant_id, - environment_id, + response = _service.delete_user_data( + customer_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'customer_id={}'.format(customer_id) in query_string - def test_update_environment_required_params_with_retries(self): - # Enable retries and run test_update_environment_required_params. + def test_delete_user_data_all_params_with_retries(self): + # Enable retries and run test_delete_user_data_all_params. _service.enable_retries() - self.test_update_environment_required_params() + self.test_delete_user_data_all_params() - # Disable retries and run test_update_environment_required_params. + # Disable retries and run test_delete_user_data_all_params. _service.disable_retries() - self.test_update_environment_required_params() + self.test_delete_user_data_all_params() @responses.activate - def test_update_environment_value_error(self): + def test_delete_user_data_value_error(self): """ - test_update_environment_value_error() + test_delete_user_data_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/environments/testString') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/user_data') responses.add( - responses.POST, + responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=200, + status=202, ) # Set up parameter values - assistant_id = 'testString' - environment_id = 'testString' + customer_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { - "assistant_id": assistant_id, - "environment_id": environment_id, + "customer_id": customer_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_environment(**req_copy) + _service.delete_user_data(**req_copy) - def test_update_environment_value_error_with_retries(self): - # Enable retries and run test_update_environment_value_error. + def test_delete_user_data_value_error_with_retries(self): + # Enable retries and run test_delete_user_data_value_error. _service.enable_retries() - self.test_update_environment_value_error() + self.test_delete_user_data_value_error() - # Disable retries and run test_update_environment_value_error. + # Disable retries and run test_delete_user_data_value_error. _service.disable_retries() - self.test_update_environment_value_error() + self.test_delete_user_data_value_error() # endregion ############################################################################## -# End of Service: Environments +# End of Service: UserData ############################################################################## ############################################################################## -# Start of Service: Releases +# Start of Service: Environments ############################################################################## # region -class TestCreateRelease: +class TestListEnvironments: """ - Test Class for create_release + Test Class for list_environments """ @responses.activate - def test_create_release_all_params(self): + def test_list_environments_all_params(self): """ - create_release() + list_environments() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add( - responses.POST, + responses.GET, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) # Set up parameter values assistant_id = 'testString' - description = 'testString' + page_limit = 100 + include_count = False + sort = 'name' + cursor = 'testString' + include_audit = False # Invoke method - response = _service.create_release( + response = _service.list_environments( assistant_id, - description=description, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, + include_audit=include_audit, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['description'] == 'testString' + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - def test_create_release_all_params_with_retries(self): - # Enable retries and run test_create_release_all_params. + def test_list_environments_all_params_with_retries(self): + # Enable retries and run test_list_environments_all_params. _service.enable_retries() - self.test_create_release_all_params() + self.test_list_environments_all_params() - # Disable retries and run test_create_release_all_params. + # Disable retries and run test_list_environments_all_params. _service.disable_retries() - self.test_create_release_all_params() + self.test_list_environments_all_params() @responses.activate - def test_create_release_required_params(self): + def test_list_environments_required_params(self): """ - test_create_release_required_params() + test_list_environments_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add( - responses.POST, + responses.GET, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) # Set up parameter values assistant_id = 'testString' # Invoke method - response = _service.create_release( + response = _service.list_environments( assistant_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 + assert response.status_code == 200 - def test_create_release_required_params_with_retries(self): - # Enable retries and run test_create_release_required_params. + def test_list_environments_required_params_with_retries(self): + # Enable retries and run test_list_environments_required_params. _service.enable_retries() - self.test_create_release_required_params() + self.test_list_environments_required_params() - # Disable retries and run test_create_release_required_params. + # Disable retries and run test_list_environments_required_params. _service.disable_retries() - self.test_create_release_required_params() + self.test_list_environments_required_params() @responses.activate - def test_create_release_value_error(self): + def test_list_environments_value_error(self): """ - test_create_release_value_error() + test_list_environments_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments') + mock_response = '{"environments": [{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add( - responses.POST, + responses.GET, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) # Set up parameter values @@ -2067,31 +2768,31 @@ def test_create_release_value_error(self): for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.create_release(**req_copy) + _service.list_environments(**req_copy) - def test_create_release_value_error_with_retries(self): - # Enable retries and run test_create_release_value_error. + def test_list_environments_value_error_with_retries(self): + # Enable retries and run test_list_environments_value_error. _service.enable_retries() - self.test_create_release_value_error() + self.test_list_environments_value_error() - # Disable retries and run test_create_release_value_error. + # Disable retries and run test_list_environments_value_error. _service.disable_retries() - self.test_create_release_value_error() + self.test_list_environments_value_error() -class TestListReleases: +class TestGetEnvironment: """ - Test Class for list_releases + Test Class for get_environment """ @responses.activate - def test_list_releases_all_params(self): + def test_get_environment_all_params(self): """ - list_releases() + get_environment() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.GET, url, @@ -2102,19 +2803,13 @@ def test_list_releases_all_params(self): # Set up parameter values assistant_id = 'testString' - page_limit = 100 - include_count = False - sort = 'name' - cursor = 'testString' + environment_id = 'testString' include_audit = False # Invoke method - response = _service.list_releases( + response = _service.get_environment( assistant_id, - page_limit=page_limit, - include_count=include_count, - sort=sort, - cursor=cursor, + environment_id, include_audit=include_audit, headers={}, ) @@ -2125,29 +2820,25 @@ def test_list_releases_all_params(self): # Validate query params query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) - assert 'page_limit={}'.format(page_limit) in query_string - assert 'include_count={}'.format('true' if include_count else 'false') in query_string - assert 'sort={}'.format(sort) in query_string - assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - def test_list_releases_all_params_with_retries(self): - # Enable retries and run test_list_releases_all_params. + def test_get_environment_all_params_with_retries(self): + # Enable retries and run test_get_environment_all_params. _service.enable_retries() - self.test_list_releases_all_params() + self.test_get_environment_all_params() - # Disable retries and run test_list_releases_all_params. + # Disable retries and run test_get_environment_all_params. _service.disable_retries() - self.test_list_releases_all_params() + self.test_get_environment_all_params() @responses.activate - def test_list_releases_required_params(self): + def test_get_environment_required_params(self): """ - test_list_releases_required_params() + test_get_environment_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.GET, url, @@ -2158,10 +2849,12 @@ def test_list_releases_required_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' # Invoke method - response = _service.list_releases( + response = _service.get_environment( assistant_id, + environment_id, headers={}, ) @@ -2169,23 +2862,23 @@ def test_list_releases_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 - def test_list_releases_required_params_with_retries(self): - # Enable retries and run test_list_releases_required_params. + def test_get_environment_required_params_with_retries(self): + # Enable retries and run test_get_environment_required_params. _service.enable_retries() - self.test_list_releases_required_params() + self.test_get_environment_required_params() - # Disable retries and run test_list_releases_required_params. + # Disable retries and run test_get_environment_required_params. _service.disable_retries() - self.test_list_releases_required_params() + self.test_get_environment_required_params() @responses.activate - def test_list_releases_value_error(self): + def test_get_environment_value_error(self): """ - test_list_releases_value_error() + test_get_environment_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases') - mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.GET, url, @@ -2196,87 +2889,112 @@ def test_list_releases_value_error(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.list_releases(**req_copy) + _service.get_environment(**req_copy) - def test_list_releases_value_error_with_retries(self): - # Enable retries and run test_list_releases_value_error. + def test_get_environment_value_error_with_retries(self): + # Enable retries and run test_get_environment_value_error. _service.enable_retries() - self.test_list_releases_value_error() + self.test_get_environment_value_error() - # Disable retries and run test_list_releases_value_error. + # Disable retries and run test_get_environment_value_error. _service.disable_retries() - self.test_list_releases_value_error() + self.test_get_environment_value_error() -class TestGetRelease: +class TestUpdateEnvironment: """ - Test Class for get_release + Test Class for update_environment """ @responses.activate - def test_get_release_all_params(self): + def test_update_environment_all_params(self): """ - get_release() + update_environment() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', status=200, ) + # Construct a dict representation of a UpdateEnvironmentOrchestration model + update_environment_orchestration_model = {} + update_environment_orchestration_model['search_skill_fallback'] = True + + # Construct a dict representation of a EnvironmentSkill model + environment_skill_model = {} + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' + # Set up parameter values assistant_id = 'testString' - release = 'testString' - include_audit = False + environment_id = 'testString' + name = 'testString' + description = 'testString' + orchestration = update_environment_orchestration_model + session_timeout = 10 + skill_references = [environment_skill_model] # Invoke method - response = _service.get_release( + response = _service.update_environment( assistant_id, - release, - include_audit=include_audit, + environment_id, + name=name, + description=description, + orchestration=orchestration, + session_timeout=session_timeout, + skill_references=skill_references, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - # Validate query params - query_string = responses.calls[0].request.url.split('?', 1)[1] - query_string = urllib.parse.unquote_plus(query_string) - assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['orchestration'] == update_environment_orchestration_model + assert req_body['session_timeout'] == 10 + assert req_body['skill_references'] == [environment_skill_model] - def test_get_release_all_params_with_retries(self): - # Enable retries and run test_get_release_all_params. + def test_update_environment_all_params_with_retries(self): + # Enable retries and run test_update_environment_all_params. _service.enable_retries() - self.test_get_release_all_params() + self.test_update_environment_all_params() - # Disable retries and run test_get_release_all_params. + # Disable retries and run test_update_environment_all_params. _service.disable_retries() - self.test_get_release_all_params() + self.test_update_environment_all_params() @responses.activate - def test_get_release_required_params(self): + def test_update_environment_required_params(self): """ - test_get_release_required_params() + test_update_environment_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', @@ -2285,12 +3003,12 @@ def test_get_release_required_params(self): # Set up parameter values assistant_id = 'testString' - release = 'testString' + environment_id = 'testString' # Invoke method - response = _service.get_release( + response = _service.update_environment( assistant_id, - release, + environment_id, headers={}, ) @@ -2298,25 +3016,25 @@ def test_get_release_required_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 - def test_get_release_required_params_with_retries(self): - # Enable retries and run test_get_release_required_params. + def test_update_environment_required_params_with_retries(self): + # Enable retries and run test_update_environment_required_params. _service.enable_retries() - self.test_get_release_required_params() + self.test_update_environment_required_params() - # Disable retries and run test_get_release_required_params. + # Disable retries and run test_update_environment_required_params. _service.disable_retries() - self.test_get_release_required_params() + self.test_update_environment_required_params() @responses.activate - def test_get_release_value_error(self): + def test_update_environment_value_error(self): """ - test_get_release_value_error() + test_update_environment_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString') - mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/environments/testString') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', @@ -2325,139 +3043,199 @@ def test_get_release_value_error(self): # Set up parameter values assistant_id = 'testString' - release = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "release": release, + "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_release(**req_copy) + _service.update_environment(**req_copy) - def test_get_release_value_error_with_retries(self): - # Enable retries and run test_get_release_value_error. + def test_update_environment_value_error_with_retries(self): + # Enable retries and run test_update_environment_value_error. _service.enable_retries() - self.test_get_release_value_error() + self.test_update_environment_value_error() - # Disable retries and run test_get_release_value_error. + # Disable retries and run test_update_environment_value_error. _service.disable_retries() - self.test_get_release_value_error() + self.test_update_environment_value_error() -class TestDeleteRelease: +# endregion +############################################################################## +# End of Service: Environments +############################################################################## + +############################################################################## +# Start of Service: Releases +############################################################################## +# region + + +class TestCreateRelease: """ - Test Class for delete_release + Test Class for create_release """ @responses.activate - def test_delete_release_all_params(self): + def test_create_release_all_params(self): """ - delete_release() + create_release() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString') + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.DELETE, + responses.POST, url, - status=200, + body=mock_response, + content_type='application/json', + status=202, ) # Set up parameter values assistant_id = 'testString' - release = 'testString' + description = 'testString' # Invoke method - response = _service.delete_release( + response = _service.create_release( assistant_id, - release, + description=description, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 200 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['description'] == 'testString' - def test_delete_release_all_params_with_retries(self): - # Enable retries and run test_delete_release_all_params. + def test_create_release_all_params_with_retries(self): + # Enable retries and run test_create_release_all_params. _service.enable_retries() - self.test_delete_release_all_params() + self.test_create_release_all_params() - # Disable retries and run test_delete_release_all_params. + # Disable retries and run test_create_release_all_params. _service.disable_retries() - self.test_delete_release_all_params() + self.test_create_release_all_params() @responses.activate - def test_delete_release_value_error(self): + def test_create_release_required_params(self): """ - test_delete_release_value_error() + test_create_release_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString') + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.DELETE, + responses.POST, url, - status=200, + body=mock_response, + content_type='application/json', + status=202, ) # Set up parameter values assistant_id = 'testString' - release = 'testString' - # Pass in all but one required param and check for a ValueError - req_param_dict = { - "assistant_id": assistant_id, - "release": release, - } - for param in req_param_dict.keys(): - req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} - with pytest.raises(ValueError): - _service.delete_release(**req_copy) + # Invoke method + response = _service.create_release( + assistant_id, + headers={}, + ) - def test_delete_release_value_error_with_retries(self): - # Enable retries and run test_delete_release_value_error. + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + + def test_create_release_required_params_with_retries(self): + # Enable retries and run test_create_release_required_params. _service.enable_retries() - self.test_delete_release_value_error() + self.test_create_release_required_params() - # Disable retries and run test_delete_release_value_error. + # Disable retries and run test_create_release_required_params. _service.disable_retries() - self.test_delete_release_value_error() - - -class TestDeployRelease: - """ - Test Class for deploy_release - """ + self.test_create_release_required_params() @responses.activate - def test_deploy_release_all_params(self): + def test_create_release_value_error(self): """ - deploy_release() + test_create_release_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.POST, url, body=mock_response, content_type='application/json', + status=202, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_release(**req_copy) + + def test_create_release_value_error_with_retries(self): + # Enable retries and run test_create_release_value_error. + _service.enable_retries() + self.test_create_release_value_error() + + # Disable retries and run test_create_release_value_error. + _service.disable_retries() + self.test_create_release_value_error() + + +class TestListReleases: + """ + Test Class for list_releases + """ + + @responses.activate + def test_list_releases_all_params(self): + """ + list_releases() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', status=200, ) # Set up parameter values assistant_id = 'testString' - release = 'testString' - environment_id = 'testString' + page_limit = 100 + include_count = False + sort = 'name' + cursor = 'testString' include_audit = False # Invoke method - response = _service.deploy_release( + response = _service.list_releases( assistant_id, - release, - environment_id, + page_limit=page_limit, + include_count=include_count, + sort=sort, + cursor=cursor, include_audit=include_audit, headers={}, ) @@ -2468,30 +3246,31 @@ def test_deploy_release_all_params(self): # Validate query params query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) + assert 'page_limit={}'.format(page_limit) in query_string + assert 'include_count={}'.format('true' if include_count else 'false') in query_string + assert 'sort={}'.format(sort) in query_string + assert 'cursor={}'.format(cursor) in query_string assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['environment_id'] == 'testString' - def test_deploy_release_all_params_with_retries(self): - # Enable retries and run test_deploy_release_all_params. + def test_list_releases_all_params_with_retries(self): + # Enable retries and run test_list_releases_all_params. _service.enable_retries() - self.test_deploy_release_all_params() + self.test_list_releases_all_params() - # Disable retries and run test_deploy_release_all_params. + # Disable retries and run test_list_releases_all_params. _service.disable_retries() - self.test_deploy_release_all_params() + self.test_list_releases_all_params() @responses.activate - def test_deploy_release_required_params(self): + def test_list_releases_required_params(self): """ - test_deploy_release_required_params() + test_list_releases_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add( - responses.POST, + responses.GET, url, body=mock_response, content_type='application/json', @@ -2500,43 +3279,36 @@ def test_deploy_release_required_params(self): # Set up parameter values assistant_id = 'testString' - release = 'testString' - environment_id = 'testString' # Invoke method - response = _service.deploy_release( + response = _service.list_releases( assistant_id, - release, - environment_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['environment_id'] == 'testString' - def test_deploy_release_required_params_with_retries(self): - # Enable retries and run test_deploy_release_required_params. + def test_list_releases_required_params_with_retries(self): + # Enable retries and run test_list_releases_required_params. _service.enable_retries() - self.test_deploy_release_required_params() + self.test_list_releases_required_params() - # Disable retries and run test_deploy_release_required_params. + # Disable retries and run test_list_releases_required_params. _service.disable_retries() - self.test_deploy_release_required_params() + self.test_list_releases_required_params() @responses.activate - def test_deploy_release_value_error(self): + def test_list_releases_value_error(self): """ - test_deploy_release_value_error() + test_list_releases_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') - mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + url = preprocess_url('/v2/assistants/testString/releases') + mock_response = '{"releases": [{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}], "pagination": {"refresh_url": "refresh_url", "next_url": "next_url", "total": 5, "matched": 7, "refresh_cursor": "refresh_cursor", "next_cursor": "next_cursor"}}' responses.add( - responses.POST, + responses.GET, url, body=mock_response, content_type='application/json', @@ -2545,54 +3317,85 @@ def test_deploy_release_value_error(self): # Set up parameter values assistant_id = 'testString' - release = 'testString' - environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "release": release, - "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.deploy_release(**req_copy) + _service.list_releases(**req_copy) - def test_deploy_release_value_error_with_retries(self): - # Enable retries and run test_deploy_release_value_error. + def test_list_releases_value_error_with_retries(self): + # Enable retries and run test_list_releases_value_error. _service.enable_retries() - self.test_deploy_release_value_error() + self.test_list_releases_value_error() - # Disable retries and run test_deploy_release_value_error. + # Disable retries and run test_list_releases_value_error. _service.disable_retries() - self.test_deploy_release_value_error() + self.test_list_releases_value_error() -# endregion -############################################################################## -# End of Service: Releases -############################################################################## +class TestGetRelease: + """ + Test Class for get_release + """ -############################################################################## -# Start of Service: Skills -############################################################################## -# region + @responses.activate + def test_get_release_all_params(self): + """ + get_release() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + include_audit = False + # Invoke method + response = _service.get_release( + assistant_id, + release, + include_audit=include_audit, + headers={}, + ) -class TestGetSkill: - """ - Test Class for get_skill - """ + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_get_release_all_params_with_retries(self): + # Enable retries and run test_get_release_all_params. + _service.enable_retries() + self.test_get_release_all_params() + + # Disable retries and run test_get_release_all_params. + _service.disable_retries() + self.test_get_release_all_params() @responses.activate - def test_get_skill_all_params(self): + def test_get_release_required_params(self): """ - get_skill() + test_get_release_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.GET, url, @@ -2603,12 +3406,12 @@ def test_get_skill_all_params(self): # Set up parameter values assistant_id = 'testString' - skill_id = 'testString' + release = 'testString' # Invoke method - response = _service.get_skill( + response = _service.get_release( assistant_id, - skill_id, + release, headers={}, ) @@ -2616,23 +3419,23 @@ def test_get_skill_all_params(self): assert len(responses.calls) == 1 assert response.status_code == 200 - def test_get_skill_all_params_with_retries(self): - # Enable retries and run test_get_skill_all_params. + def test_get_release_required_params_with_retries(self): + # Enable retries and run test_get_release_required_params. _service.enable_retries() - self.test_get_skill_all_params() + self.test_get_release_required_params() - # Disable retries and run test_get_skill_all_params. + # Disable retries and run test_get_release_required_params. _service.disable_retries() - self.test_get_skill_all_params() + self.test_get_release_required_params() @responses.activate - def test_get_skill_value_error(self): + def test_get_release_value_error(self): """ - test_get_skill_value_error() + test_get_release_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + url = preprocess_url('/v2/assistants/testString/releases/testString') + mock_response = '{"release": "release", "description": "description", "environment_references": [{"name": "name", "environment_id": "environment_id", "environment": "draft"}], "content": {"skills": [{"skill_id": "skill_id", "type": "dialog", "snapshot": "snapshot"}]}, "status": "Available", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( responses.GET, url, @@ -2643,220 +3446,122 @@ def test_get_skill_value_error(self): # Set up parameter values assistant_id = 'testString' - skill_id = 'testString' + release = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "skill_id": skill_id, + "release": release, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.get_skill(**req_copy) + _service.get_release(**req_copy) - def test_get_skill_value_error_with_retries(self): - # Enable retries and run test_get_skill_value_error. + def test_get_release_value_error_with_retries(self): + # Enable retries and run test_get_release_value_error. _service.enable_retries() - self.test_get_skill_value_error() + self.test_get_release_value_error() - # Disable retries and run test_get_skill_value_error. + # Disable retries and run test_get_release_value_error. _service.disable_retries() - self.test_get_skill_value_error() + self.test_get_release_value_error() -class TestUpdateSkill: +class TestDeleteRelease: """ - Test Class for update_skill + Test Class for delete_release """ @responses.activate - def test_update_skill_all_params(self): + def test_delete_release_all_params(self): """ - update_skill() + delete_release() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + url = preprocess_url('/v2/assistants/testString/releases/testString') responses.add( - responses.POST, + responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=202, + status=200, ) - # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model = {} - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - # Construct a dict representation of a SearchSettingsDiscovery model - search_settings_discovery_model = {} - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - # Construct a dict representation of a SearchSettingsMessages model - search_settings_messages_model = {} - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - # Construct a dict representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model = {} - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - # Construct a dict representation of a SearchSettings model - search_settings_model = {} - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - # Set up parameter values assistant_id = 'testString' - skill_id = 'testString' - name = 'testString' - description = 'testString' - workspace = {'anyKey': 'anyValue'} - dialog_settings = {'anyKey': 'anyValue'} - search_settings = search_settings_model + release = 'testString' # Invoke method - response = _service.update_skill( + response = _service.delete_release( assistant_id, - skill_id, - name=name, - description=description, - workspace=workspace, - dialog_settings=dialog_settings, - search_settings=search_settings, + release, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['name'] == 'testString' - assert req_body['description'] == 'testString' - assert req_body['workspace'] == {'anyKey': 'anyValue'} - assert req_body['dialog_settings'] == {'anyKey': 'anyValue'} - assert req_body['search_settings'] == search_settings_model + assert response.status_code == 200 - def test_update_skill_all_params_with_retries(self): - # Enable retries and run test_update_skill_all_params. + def test_delete_release_all_params_with_retries(self): + # Enable retries and run test_delete_release_all_params. _service.enable_retries() - self.test_update_skill_all_params() + self.test_delete_release_all_params() - # Disable retries and run test_update_skill_all_params. + # Disable retries and run test_delete_release_all_params. _service.disable_retries() - self.test_update_skill_all_params() + self.test_delete_release_all_params() @responses.activate - def test_update_skill_value_error(self): + def test_delete_release_value_error(self): """ - test_update_skill_value_error() + test_delete_release_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills/testString') - mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + url = preprocess_url('/v2/assistants/testString/releases/testString') responses.add( - responses.POST, + responses.DELETE, url, - body=mock_response, - content_type='application/json', - status=202, + status=200, ) - # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model = {} - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - # Construct a dict representation of a SearchSettingsDiscovery model - search_settings_discovery_model = {} - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - # Construct a dict representation of a SearchSettingsMessages model - search_settings_messages_model = {} - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - # Construct a dict representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model = {} - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - # Construct a dict representation of a SearchSettings model - search_settings_model = {} - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - # Set up parameter values assistant_id = 'testString' - skill_id = 'testString' - name = 'testString' - description = 'testString' - workspace = {'anyKey': 'anyValue'} - dialog_settings = {'anyKey': 'anyValue'} - search_settings = search_settings_model + release = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "skill_id": skill_id, + "release": release, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.update_skill(**req_copy) + _service.delete_release(**req_copy) - def test_update_skill_value_error_with_retries(self): - # Enable retries and run test_update_skill_value_error. + def test_delete_release_value_error_with_retries(self): + # Enable retries and run test_delete_release_value_error. _service.enable_retries() - self.test_update_skill_value_error() + self.test_delete_release_value_error() - # Disable retries and run test_update_skill_value_error. + # Disable retries and run test_delete_release_value_error. _service.disable_retries() - self.test_update_skill_value_error() + self.test_delete_release_value_error() -class TestExportSkills: +class TestDeployRelease: """ - Test Class for export_skills + Test Class for deploy_release """ @responses.activate - def test_export_skills_all_params(self): + def test_deploy_release_all_params(self): """ - export_skills() + deploy_release() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_export') - mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', @@ -2865,11 +3570,15 @@ def test_export_skills_all_params(self): # Set up parameter values assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' include_audit = False # Invoke method - response = _service.export_skills( + response = _service.deploy_release( assistant_id, + release, + environment_id, include_audit=include_audit, headers={}, ) @@ -2881,26 +3590,29 @@ def test_export_skills_all_params(self): query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['environment_id'] == 'testString' - def test_export_skills_all_params_with_retries(self): - # Enable retries and run test_export_skills_all_params. + def test_deploy_release_all_params_with_retries(self): + # Enable retries and run test_deploy_release_all_params. _service.enable_retries() - self.test_export_skills_all_params() + self.test_deploy_release_all_params() - # Disable retries and run test_export_skills_all_params. + # Disable retries and run test_deploy_release_all_params. _service.disable_retries() - self.test_export_skills_all_params() + self.test_deploy_release_all_params() @responses.activate - def test_export_skills_required_params(self): + def test_deploy_release_required_params(self): """ - test_export_skills_required_params() + test_deploy_release_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_export') - mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', @@ -2909,36 +3621,43 @@ def test_export_skills_required_params(self): # Set up parameter values assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' # Invoke method - response = _service.export_skills( + response = _service.deploy_release( assistant_id, + release, + environment_id, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['environment_id'] == 'testString' - def test_export_skills_required_params_with_retries(self): - # Enable retries and run test_export_skills_required_params. + def test_deploy_release_required_params_with_retries(self): + # Enable retries and run test_deploy_release_required_params. _service.enable_retries() - self.test_export_skills_required_params() + self.test_deploy_release_required_params() - # Disable retries and run test_export_skills_required_params. + # Disable retries and run test_deploy_release_required_params. _service.disable_retries() - self.test_export_skills_required_params() + self.test_deploy_release_required_params() @responses.activate - def test_export_skills_value_error(self): + def test_deploy_release_value_error(self): """ - test_export_skills_value_error() + test_deploy_release_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_export') - mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + url = preprocess_url('/v2/assistants/testString/releases/testString/deploy') + mock_response = '{"name": "name", "description": "description", "assistant_id": "assistant_id", "environment_id": "environment_id", "environment": "environment", "release_reference": {"release": "release"}, "orchestration": {"search_skill_fallback": false}, "session_timeout": 10, "integration_references": [{"integration_id": "integration_id", "type": "type"}], "skill_references": [{"skill_id": "skill_id", "type": "dialog", "disabled": true, "snapshot": "snapshot", "skill_reference": "skill_reference"}], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' responses.add( - responses.GET, + responses.POST, url, body=mock_response, content_type='application/json', @@ -2947,334 +3666,174 @@ def test_export_skills_value_error(self): # Set up parameter values assistant_id = 'testString' + release = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "release": release, + "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.export_skills(**req_copy) + _service.deploy_release(**req_copy) - def test_export_skills_value_error_with_retries(self): - # Enable retries and run test_export_skills_value_error. + def test_deploy_release_value_error_with_retries(self): + # Enable retries and run test_deploy_release_value_error. _service.enable_retries() - self.test_export_skills_value_error() + self.test_deploy_release_value_error() - # Disable retries and run test_export_skills_value_error. + # Disable retries and run test_deploy_release_value_error. _service.disable_retries() - self.test_export_skills_value_error() + self.test_deploy_release_value_error() -class TestImportSkills: +class TestCreateReleaseExport: """ - Test Class for import_skills + Test Class for create_release_export """ @responses.activate - def test_import_skills_all_params(self): + def test_create_release_export_all_params(self): """ - import_skills() + create_release_export() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_import') - mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' responses.add( responses.POST, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) - # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model = {} - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + include_audit = False - # Construct a dict representation of a SearchSettingsDiscovery model - search_settings_discovery_model = {} - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - # Construct a dict representation of a SearchSettingsMessages model - search_settings_messages_model = {} - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - # Construct a dict representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model = {} - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - # Construct a dict representation of a SearchSettings model - search_settings_model = {} - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - - # Construct a dict representation of a SkillImport model - skill_import_model = {} - skill_import_model['name'] = 'testString' - skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'anyKey': 'anyValue'} - skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} - skill_import_model['search_settings'] = search_settings_model - skill_import_model['language'] = 'testString' - skill_import_model['type'] = 'action' - - # Construct a dict representation of a AssistantState model - assistant_state_model = {} - assistant_state_model['action_disabled'] = True - assistant_state_model['dialog_disabled'] = True - - # Set up parameter values - assistant_id = 'testString' - assistant_skills = [skill_import_model] - assistant_state = assistant_state_model - include_audit = False - - # Invoke method - response = _service.import_skills( - assistant_id, - assistant_skills, - assistant_state, - include_audit=include_audit, - headers={}, - ) + # Invoke method + response = _service.create_release_export( + assistant_id, + release, + include_audit=include_audit, + headers={}, + ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 + assert response.status_code == 200 # Validate query params query_string = responses.calls[0].request.url.split('?', 1)[1] query_string = urllib.parse.unquote_plus(query_string) assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['assistant_skills'] == [skill_import_model] - assert req_body['assistant_state'] == assistant_state_model - def test_import_skills_all_params_with_retries(self): - # Enable retries and run test_import_skills_all_params. + def test_create_release_export_all_params_with_retries(self): + # Enable retries and run test_create_release_export_all_params. _service.enable_retries() - self.test_import_skills_all_params() + self.test_create_release_export_all_params() - # Disable retries and run test_import_skills_all_params. + # Disable retries and run test_create_release_export_all_params. _service.disable_retries() - self.test_import_skills_all_params() + self.test_create_release_export_all_params() @responses.activate - def test_import_skills_required_params(self): + def test_create_release_export_required_params(self): """ - test_import_skills_required_params() + test_create_release_export_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_import') - mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' responses.add( responses.POST, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) - # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model = {} - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - # Construct a dict representation of a SearchSettingsDiscovery model - search_settings_discovery_model = {} - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - # Construct a dict representation of a SearchSettingsMessages model - search_settings_messages_model = {} - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - # Construct a dict representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model = {} - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - # Construct a dict representation of a SearchSettings model - search_settings_model = {} - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - - # Construct a dict representation of a SkillImport model - skill_import_model = {} - skill_import_model['name'] = 'testString' - skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'anyKey': 'anyValue'} - skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} - skill_import_model['search_settings'] = search_settings_model - skill_import_model['language'] = 'testString' - skill_import_model['type'] = 'action' - - # Construct a dict representation of a AssistantState model - assistant_state_model = {} - assistant_state_model['action_disabled'] = True - assistant_state_model['dialog_disabled'] = True - # Set up parameter values assistant_id = 'testString' - assistant_skills = [skill_import_model] - assistant_state = assistant_state_model + release = 'testString' # Invoke method - response = _service.import_skills( + response = _service.create_release_export( assistant_id, - assistant_skills, - assistant_state, + release, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 - assert response.status_code == 202 - # Validate body params - req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) - assert req_body['assistant_skills'] == [skill_import_model] - assert req_body['assistant_state'] == assistant_state_model + assert response.status_code == 200 - def test_import_skills_required_params_with_retries(self): - # Enable retries and run test_import_skills_required_params. + def test_create_release_export_required_params_with_retries(self): + # Enable retries and run test_create_release_export_required_params. _service.enable_retries() - self.test_import_skills_required_params() + self.test_create_release_export_required_params() - # Disable retries and run test_import_skills_required_params. + # Disable retries and run test_create_release_export_required_params. _service.disable_retries() - self.test_import_skills_required_params() + self.test_create_release_export_required_params() @responses.activate - def test_import_skills_value_error(self): + def test_create_release_export_value_error(self): """ - test_import_skills_value_error() + test_create_release_export_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_import') - mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' responses.add( responses.POST, url, body=mock_response, content_type='application/json', - status=202, + status=200, ) - # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model = {} - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - # Construct a dict representation of a SearchSettingsDiscovery model - search_settings_discovery_model = {} - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model - - # Construct a dict representation of a SearchSettingsMessages model - search_settings_messages_model = {} - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' - - # Construct a dict representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model = {} - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' - - # Construct a dict representation of a SearchSettings model - search_settings_model = {} - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - - # Construct a dict representation of a SkillImport model - skill_import_model = {} - skill_import_model['name'] = 'testString' - skill_import_model['description'] = 'testString' - skill_import_model['workspace'] = {'anyKey': 'anyValue'} - skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} - skill_import_model['search_settings'] = search_settings_model - skill_import_model['language'] = 'testString' - skill_import_model['type'] = 'action' - - # Construct a dict representation of a AssistantState model - assistant_state_model = {} - assistant_state_model['action_disabled'] = True - assistant_state_model['dialog_disabled'] = True - # Set up parameter values assistant_id = 'testString' - assistant_skills = [skill_import_model] - assistant_state = assistant_state_model + release = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, - "assistant_skills": assistant_skills, - "assistant_state": assistant_state, + "release": release, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.import_skills(**req_copy) + _service.create_release_export(**req_copy) - def test_import_skills_value_error_with_retries(self): - # Enable retries and run test_import_skills_value_error. + def test_create_release_export_value_error_with_retries(self): + # Enable retries and run test_create_release_export_value_error. _service.enable_retries() - self.test_import_skills_value_error() + self.test_create_release_export_value_error() - # Disable retries and run test_import_skills_value_error. + # Disable retries and run test_create_release_export_value_error. _service.disable_retries() - self.test_import_skills_value_error() + self.test_create_release_export_value_error() -class TestImportSkillsStatus: +class TestDownloadReleaseExport: """ - Test Class for import_skills_status + Test Class for download_release_export """ @responses.activate - def test_import_skills_status_all_params(self): + def test_download_release_export_all_params(self): """ - import_skills_status() + download_release_export() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_import/status') - mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' responses.add( responses.GET, url, @@ -3285,34 +3844,84 @@ def test_import_skills_status_all_params(self): # Set up parameter values assistant_id = 'testString' + release = 'testString' + accept = 'application/json' + include_audit = False # Invoke method - response = _service.import_skills_status( + response = _service.download_release_export( assistant_id, + release, + accept=accept, + include_audit=include_audit, headers={}, ) # Check for correct operation assert len(responses.calls) == 1 assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string - def test_import_skills_status_all_params_with_retries(self): - # Enable retries and run test_import_skills_status_all_params. + def test_download_release_export_all_params_with_retries(self): + # Enable retries and run test_download_release_export_all_params. _service.enable_retries() - self.test_import_skills_status_all_params() + self.test_download_release_export_all_params() - # Disable retries and run test_import_skills_status_all_params. + # Disable retries and run test_download_release_export_all_params. _service.disable_retries() - self.test_import_skills_status_all_params() + self.test_download_release_export_all_params() @responses.activate - def test_import_skills_status_value_error(self): + def test_download_release_export_required_params(self): """ - test_import_skills_status_value_error() + test_download_release_export_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/skills_import/status') - mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + release = 'testString' + + # Invoke method + response = _service.download_release_export( + assistant_id, + release, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_download_release_export_required_params_with_retries(self): + # Enable retries and run test_download_release_export_required_params. + _service.enable_retries() + self.test_download_release_export_required_params() + + # Disable retries and run test_download_release_export_required_params. + _service.disable_retries() + self.test_download_release_export_required_params() + + @responses.activate + def test_download_release_export_value_error(self): + """ + test_download_release_export_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/releases/testString/export') + mock_response = '{"status": "Available", "task_id": "task_id", "assistant_id": "assistant_id", "release": "release", "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z", "status_errors": [{"message": "message"}], "status_description": "status_description"}' responses.add( responses.GET, url, @@ -3323,282 +3932,2342 @@ def test_import_skills_status_value_error(self): # Set up parameter values assistant_id = 'testString' + release = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "release": release, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} with pytest.raises(ValueError): - _service.import_skills_status(**req_copy) + _service.download_release_export(**req_copy) - def test_import_skills_status_value_error_with_retries(self): - # Enable retries and run test_import_skills_status_value_error. + def test_download_release_export_value_error_with_retries(self): + # Enable retries and run test_download_release_export_value_error. _service.enable_retries() - self.test_import_skills_status_value_error() + self.test_download_release_export_value_error() - # Disable retries and run test_import_skills_status_value_error. + # Disable retries and run test_download_release_export_value_error. _service.disable_retries() - self.test_import_skills_status_value_error() - - -# endregion -############################################################################## -# End of Service: Skills -############################################################################## - - -############################################################################## -# Start of Model Tests -############################################################################## -# region + self.test_download_release_export_value_error() -class TestModel_AgentAvailabilityMessage: +class TestCreateReleaseImport: """ - Test Class for AgentAvailabilityMessage + Test Class for create_release_import """ - def test_agent_availability_message_serialization(self): + @responses.activate + def test_create_release_import_all_params(self): """ - Test serialization/deserialization for AgentAvailabilityMessage + create_release_import() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Failed", "task_id": "task_id", "assistant_id": "assistant_id", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) - # Construct a json representation of a AgentAvailabilityMessage model - agent_availability_message_model_json = {} - agent_availability_message_model_json['message'] = 'testString' - - # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation - agent_availability_message_model = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json) - assert agent_availability_message_model != False - - # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation - agent_availability_message_model_dict = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json).__dict__ - agent_availability_message_model2 = AgentAvailabilityMessage(**agent_availability_message_model_dict) + # Set up parameter values + assistant_id = 'testString' + body = io.BytesIO(b'This is a mock file.').getvalue() + include_audit = False - # Verify the model instances are equivalent - assert agent_availability_message_model == agent_availability_message_model2 + # Invoke method + response = _service.create_release_import( + assistant_id, + body, + include_audit=include_audit, + headers={}, + ) - # Convert model instance back to dict and verify no loss of data - agent_availability_message_model_json2 = agent_availability_message_model.to_dict() - assert agent_availability_message_model_json2 == agent_availability_message_model_json + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + assert responses.calls[0].request.body == body + def test_create_release_import_all_params_with_retries(self): + # Enable retries and run test_create_release_import_all_params. + _service.enable_retries() + self.test_create_release_import_all_params() -class TestModel_AssistantCollection: - """ - Test Class for AssistantCollection - """ + # Disable retries and run test_create_release_import_all_params. + _service.disable_retries() + self.test_create_release_import_all_params() - def test_assistant_collection_serialization(self): + @responses.activate + def test_create_release_import_required_params(self): """ - Test serialization/deserialization for AssistantCollection + test_create_release_import_required_params() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Failed", "task_id": "task_id", "assistant_id": "assistant_id", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) - # Construct dict forms of any model objects needed in order to build this model. - - assistant_data_model = {} # AssistantData - assistant_data_model['name'] = 'testString' - assistant_data_model['description'] = 'testString' - assistant_data_model['language'] = 'testString' - - pagination_model = {} # Pagination - pagination_model['refresh_url'] = 'testString' - pagination_model['next_url'] = 'testString' - pagination_model['total'] = 38 - pagination_model['matched'] = 38 - pagination_model['refresh_cursor'] = 'testString' - pagination_model['next_cursor'] = 'testString' - - # Construct a json representation of a AssistantCollection model - assistant_collection_model_json = {} - assistant_collection_model_json['assistants'] = [assistant_data_model] - assistant_collection_model_json['pagination'] = pagination_model - - # Construct a model instance of AssistantCollection by calling from_dict on the json representation - assistant_collection_model = AssistantCollection.from_dict(assistant_collection_model_json) - assert assistant_collection_model != False - - # Construct a model instance of AssistantCollection by calling from_dict on the json representation - assistant_collection_model_dict = AssistantCollection.from_dict(assistant_collection_model_json).__dict__ - assistant_collection_model2 = AssistantCollection(**assistant_collection_model_dict) + # Set up parameter values + assistant_id = 'testString' + body = io.BytesIO(b'This is a mock file.').getvalue() - # Verify the model instances are equivalent - assert assistant_collection_model == assistant_collection_model2 + # Invoke method + response = _service.create_release_import( + assistant_id, + body, + headers={}, + ) - # Convert model instance back to dict and verify no loss of data - assistant_collection_model_json2 = assistant_collection_model.to_dict() - assert assistant_collection_model_json2 == assistant_collection_model_json + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + assert responses.calls[0].request.body == body + def test_create_release_import_required_params_with_retries(self): + # Enable retries and run test_create_release_import_required_params. + _service.enable_retries() + self.test_create_release_import_required_params() -class TestModel_AssistantData: - """ - Test Class for AssistantData - """ + # Disable retries and run test_create_release_import_required_params. + _service.disable_retries() + self.test_create_release_import_required_params() - def test_assistant_data_serialization(self): + @responses.activate + def test_create_release_import_value_error(self): """ - Test serialization/deserialization for AssistantData + test_create_release_import_value_error() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Failed", "task_id": "task_id", "assistant_id": "assistant_id", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) - # Construct a json representation of a AssistantData model - assistant_data_model_json = {} - assistant_data_model_json['name'] = 'testString' - assistant_data_model_json['description'] = 'testString' - assistant_data_model_json['language'] = 'testString' - - # Construct a model instance of AssistantData by calling from_dict on the json representation - assistant_data_model = AssistantData.from_dict(assistant_data_model_json) - assert assistant_data_model != False + # Set up parameter values + assistant_id = 'testString' + body = io.BytesIO(b'This is a mock file.').getvalue() - # Construct a model instance of AssistantData by calling from_dict on the json representation - assistant_data_model_dict = AssistantData.from_dict(assistant_data_model_json).__dict__ - assistant_data_model2 = AssistantData(**assistant_data_model_dict) + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "body": body, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.create_release_import(**req_copy) - # Verify the model instances are equivalent - assert assistant_data_model == assistant_data_model2 + def test_create_release_import_value_error_with_retries(self): + # Enable retries and run test_create_release_import_value_error. + _service.enable_retries() + self.test_create_release_import_value_error() - # Convert model instance back to dict and verify no loss of data - assistant_data_model_json2 = assistant_data_model.to_dict() - assert assistant_data_model_json2 == assistant_data_model_json + # Disable retries and run test_create_release_import_value_error. + _service.disable_retries() + self.test_create_release_import_value_error() -class TestModel_AssistantSkill: +class TestGetReleaseImportStatus: """ - Test Class for AssistantSkill + Test Class for get_release_import_status """ - def test_assistant_skill_serialization(self): + @responses.activate + def test_get_release_import_status_all_params(self): """ - Test serialization/deserialization for AssistantSkill + get_release_import_status() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Completed", "task_id": "task_id", "assistant_id": "assistant_id", "status_errors": [{"message": "message"}], "status_description": "status_description", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) - # Construct a json representation of a AssistantSkill model - assistant_skill_model_json = {} - assistant_skill_model_json['skill_id'] = 'testString' - assistant_skill_model_json['type'] = 'dialog' - - # Construct a model instance of AssistantSkill by calling from_dict on the json representation - assistant_skill_model = AssistantSkill.from_dict(assistant_skill_model_json) - assert assistant_skill_model != False - - # Construct a model instance of AssistantSkill by calling from_dict on the json representation - assistant_skill_model_dict = AssistantSkill.from_dict(assistant_skill_model_json).__dict__ - assistant_skill_model2 = AssistantSkill(**assistant_skill_model_dict) + # Set up parameter values + assistant_id = 'testString' + include_audit = False - # Verify the model instances are equivalent - assert assistant_skill_model == assistant_skill_model2 + # Invoke method + response = _service.get_release_import_status( + assistant_id, + include_audit=include_audit, + headers={}, + ) - # Convert model instance back to dict and verify no loss of data - assistant_skill_model_json2 = assistant_skill_model.to_dict() - assert assistant_skill_model_json2 == assistant_skill_model_json + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + def test_get_release_import_status_all_params_with_retries(self): + # Enable retries and run test_get_release_import_status_all_params. + _service.enable_retries() + self.test_get_release_import_status_all_params() -class TestModel_AssistantState: - """ - Test Class for AssistantState - """ + # Disable retries and run test_get_release_import_status_all_params. + _service.disable_retries() + self.test_get_release_import_status_all_params() - def test_assistant_state_serialization(self): + @responses.activate + def test_get_release_import_status_required_params(self): """ - Test serialization/deserialization for AssistantState + test_get_release_import_status_required_params() """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Completed", "task_id": "task_id", "assistant_id": "assistant_id", "status_errors": [{"message": "message"}], "status_description": "status_description", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) - # Construct a json representation of a AssistantState model - assistant_state_model_json = {} - assistant_state_model_json['action_disabled'] = True - assistant_state_model_json['dialog_disabled'] = True - - # Construct a model instance of AssistantState by calling from_dict on the json representation - assistant_state_model = AssistantState.from_dict(assistant_state_model_json) - assert assistant_state_model != False + # Set up parameter values + assistant_id = 'testString' - # Construct a model instance of AssistantState by calling from_dict on the json representation - assistant_state_model_dict = AssistantState.from_dict(assistant_state_model_json).__dict__ - assistant_state_model2 = AssistantState(**assistant_state_model_dict) + # Invoke method + response = _service.get_release_import_status( + assistant_id, + headers={}, + ) - # Verify the model instances are equivalent - assert assistant_state_model == assistant_state_model2 + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 - # Convert model instance back to dict and verify no loss of data - assistant_state_model_json2 = assistant_state_model.to_dict() - assert assistant_state_model_json2 == assistant_state_model_json + def test_get_release_import_status_required_params_with_retries(self): + # Enable retries and run test_get_release_import_status_required_params. + _service.enable_retries() + self.test_get_release_import_status_required_params() + # Disable retries and run test_get_release_import_status_required_params. + _service.disable_retries() + self.test_get_release_import_status_required_params() -class TestModel_BaseEnvironmentOrchestration: - """ + @responses.activate + def test_get_release_import_status_value_error(self): + """ + test_get_release_import_status_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/import') + mock_response = '{"status": "Completed", "task_id": "task_id", "assistant_id": "assistant_id", "status_errors": [{"message": "message"}], "status_description": "status_description", "skill_impact_in_draft": ["action"], "created": "2019-01-01T12:00:00.000Z", "updated": "2019-01-01T12:00:00.000Z"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_release_import_status(**req_copy) + + def test_get_release_import_status_value_error_with_retries(self): + # Enable retries and run test_get_release_import_status_value_error. + _service.enable_retries() + self.test_get_release_import_status_value_error() + + # Disable retries and run test_get_release_import_status_value_error. + _service.disable_retries() + self.test_get_release_import_status_value_error() + + +# endregion +############################################################################## +# End of Service: Releases +############################################################################## + +############################################################################## +# Start of Service: Skills +############################################################################## +# region + + +class TestGetSkill: + """ + Test Class for get_skill + """ + + @responses.activate + def test_get_skill_all_params(self): + """ + get_skill() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + + # Invoke method + response = _service.get_skill( + assistant_id, + skill_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_get_skill_all_params_with_retries(self): + # Enable retries and run test_get_skill_all_params. + _service.enable_retries() + self.test_get_skill_all_params() + + # Disable retries and run test_get_skill_all_params. + _service.disable_retries() + self.test_get_skill_all_params() + + @responses.activate + def test_get_skill_value_error(self): + """ + test_get_skill_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "skill_id": skill_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.get_skill(**req_copy) + + def test_get_skill_value_error_with_retries(self): + # Enable retries and run test_get_skill_value_error. + _service.enable_retries() + self.test_get_skill_value_error() + + # Disable retries and run test_get_skill_value_error. + _service.disable_retries() + self.test_get_skill_value_error() + + +class TestUpdateSkill: + """ + Test Class for update_skill + """ + + @responses.activate + def test_update_skill_all_params(self): + """ + update_skill() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model = {} + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + # Construct a dict representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model = {} + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + # Construct a dict representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model = {} + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a dict representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model = {} + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a dict representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model = {} + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + # Construct a dict representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model = {} + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + name = 'testString' + description = 'testString' + workspace = {'anyKey': 'anyValue'} + dialog_settings = {'anyKey': 'anyValue'} + search_settings = search_settings_model + + # Invoke method + response = _service.update_skill( + assistant_id, + skill_id, + name=name, + description=description, + workspace=workspace, + dialog_settings=dialog_settings, + search_settings=search_settings, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['name'] == 'testString' + assert req_body['description'] == 'testString' + assert req_body['workspace'] == {'anyKey': 'anyValue'} + assert req_body['dialog_settings'] == {'anyKey': 'anyValue'} + assert req_body['search_settings'] == search_settings_model + + def test_update_skill_all_params_with_retries(self): + # Enable retries and run test_update_skill_all_params. + _service.enable_retries() + self.test_update_skill_all_params() + + # Disable retries and run test_update_skill_all_params. + _service.disable_retries() + self.test_update_skill_all_params() + + @responses.activate + def test_update_skill_value_error(self): + """ + test_update_skill_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills/testString') + mock_response = '{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model = {} + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + # Construct a dict representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model = {} + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + # Construct a dict representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model = {} + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a dict representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model = {} + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a dict representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model = {} + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + # Construct a dict representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model = {} + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Set up parameter values + assistant_id = 'testString' + skill_id = 'testString' + name = 'testString' + description = 'testString' + workspace = {'anyKey': 'anyValue'} + dialog_settings = {'anyKey': 'anyValue'} + search_settings = search_settings_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "skill_id": skill_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.update_skill(**req_copy) + + def test_update_skill_value_error_with_retries(self): + # Enable retries and run test_update_skill_value_error. + _service.enable_retries() + self.test_update_skill_value_error() + + # Disable retries and run test_update_skill_value_error. + _service.disable_retries() + self.test_update_skill_value_error() + + +class TestExportSkills: + """ + Test Class for export_skills + """ + + @responses.activate + def test_export_skills_all_params(self): + """ + export_skills() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + include_audit = False + + # Invoke method + response = _service.export_skills( + assistant_id, + include_audit=include_audit, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + + def test_export_skills_all_params_with_retries(self): + # Enable retries and run test_export_skills_all_params. + _service.enable_retries() + self.test_export_skills_all_params() + + # Disable retries and run test_export_skills_all_params. + _service.disable_retries() + self.test_export_skills_all_params() + + @responses.activate + def test_export_skills_required_params(self): + """ + test_export_skills_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.export_skills( + assistant_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_export_skills_required_params_with_retries(self): + # Enable retries and run test_export_skills_required_params. + _service.enable_retries() + self.test_export_skills_required_params() + + # Disable retries and run test_export_skills_required_params. + _service.disable_retries() + self.test_export_skills_required_params() + + @responses.activate + def test_export_skills_value_error(self): + """ + test_export_skills_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_export') + mock_response = '{"assistant_skills": [{"name": "name", "description": "description", "workspace": {"anyKey": "anyValue"}, "skill_id": "skill_id", "status": "Available", "status_errors": [{"message": "message"}], "status_description": "status_description", "dialog_settings": {"anyKey": "anyValue"}, "assistant_id": "assistant_id", "workspace_id": "workspace_id", "environment_id": "environment_id", "valid": false, "next_snapshot_version": "next_snapshot_version", "search_settings": {"discovery": {"instance_id": "instance_id", "project_id": "project_id", "url": "url", "max_primary_results": 10000, "max_total_results": 10000, "confidence_threshold": 0.0, "highlight": false, "find_answers": true, "authentication": {"basic": "basic", "bearer": "bearer"}}, "messages": {"success": "success", "error": "error", "no_result": "no_result"}, "schema_mapping": {"url": "url", "body": "body", "title": "title"}, "elastic_search": {"url": "url", "port": "port", "username": "username", "password": "password", "index": "index", "filter": ["anyValue"], "query_body": {"anyKey": "anyValue"}, "managed_index": "managed_index", "apikey": "apikey"}, "conversational_search": {"enabled": true, "response_length": {"option": "moderate"}, "search_confidence": {"threshold": "less_often"}}, "server_side_search": {"url": "url", "port": "port", "username": "username", "password": "password", "filter": "filter", "metadata": {"anyKey": "anyValue"}, "apikey": "apikey", "no_auth": false, "auth_type": "basic"}, "client_side_search": {"filter": "filter", "metadata": {"anyKey": "anyValue"}}}, "warnings": [{"code": "code", "path": "path", "message": "message"}], "language": "language", "type": "action"}], "assistant_state": {"action_disabled": false, "dialog_disabled": false}}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.export_skills(**req_copy) + + def test_export_skills_value_error_with_retries(self): + # Enable retries and run test_export_skills_value_error. + _service.enable_retries() + self.test_export_skills_value_error() + + # Disable retries and run test_export_skills_value_error. + _service.disable_retries() + self.test_export_skills_value_error() + + +class TestImportSkills: + """ + Test Class for import_skills + """ + + @responses.activate + def test_import_skills_all_params(self): + """ + import_skills() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model = {} + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + # Construct a dict representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model = {} + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + # Construct a dict representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model = {} + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a dict representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model = {} + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a dict representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model = {} + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + # Construct a dict representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model = {} + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} + skill_import_model['search_settings'] = search_settings_model + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + include_audit = False + + # Invoke method + response = _service.import_skills( + assistant_id, + assistant_skills, + assistant_state, + include_audit=include_audit, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + assert 'include_audit={}'.format('true' if include_audit else 'false') in query_string + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['assistant_skills'] == [skill_import_model] + assert req_body['assistant_state'] == assistant_state_model + + def test_import_skills_all_params_with_retries(self): + # Enable retries and run test_import_skills_all_params. + _service.enable_retries() + self.test_import_skills_all_params() + + # Disable retries and run test_import_skills_all_params. + _service.disable_retries() + self.test_import_skills_all_params() + + @responses.activate + def test_import_skills_required_params(self): + """ + test_import_skills_required_params() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model = {} + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + # Construct a dict representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model = {} + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + # Construct a dict representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model = {} + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a dict representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model = {} + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a dict representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model = {} + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + # Construct a dict representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model = {} + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} + skill_import_model['search_settings'] = search_settings_model + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + + # Invoke method + response = _service.import_skills( + assistant_id, + assistant_skills, + assistant_state, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 202 + # Validate body params + req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) + assert req_body['assistant_skills'] == [skill_import_model] + assert req_body['assistant_state'] == assistant_state_model + + def test_import_skills_required_params_with_retries(self): + # Enable retries and run test_import_skills_required_params. + _service.enable_retries() + self.test_import_skills_required_params() + + # Disable retries and run test_import_skills_required_params. + _service.disable_retries() + self.test_import_skills_required_params() + + @responses.activate + def test_import_skills_value_error(self): + """ + test_import_skills_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=202, + ) + + # Construct a dict representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model = {} + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a dict representation of a SearchSettingsDiscovery model + search_settings_discovery_model = {} + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + # Construct a dict representation of a SearchSettingsMessages model + search_settings_messages_model = {} + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + # Construct a dict representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model = {} + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + # Construct a dict representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model = {} + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + # Construct a dict representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model = {} + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + # Construct a dict representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model = {} + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a dict representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model = {} + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a dict representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model = {} + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + # Construct a dict representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model = {} + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + # Construct a dict representation of a SearchSettings model + search_settings_model = {} + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Construct a dict representation of a SkillImport model + skill_import_model = {} + skill_import_model['name'] = 'testString' + skill_import_model['description'] = 'testString' + skill_import_model['workspace'] = {'anyKey': 'anyValue'} + skill_import_model['dialog_settings'] = {'anyKey': 'anyValue'} + skill_import_model['search_settings'] = search_settings_model + skill_import_model['language'] = 'testString' + skill_import_model['type'] = 'action' + + # Construct a dict representation of a AssistantState model + assistant_state_model = {} + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Set up parameter values + assistant_id = 'testString' + assistant_skills = [skill_import_model] + assistant_state = assistant_state_model + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + "assistant_skills": assistant_skills, + "assistant_state": assistant_state, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.import_skills(**req_copy) + + def test_import_skills_value_error_with_retries(self): + # Enable retries and run test_import_skills_value_error. + _service.enable_retries() + self.test_import_skills_value_error() + + # Disable retries and run test_import_skills_value_error. + _service.disable_retries() + self.test_import_skills_value_error() + + +class TestImportSkillsStatus: + """ + Test Class for import_skills_status + """ + + @responses.activate + def test_import_skills_status_all_params(self): + """ + import_skills_status() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import/status') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Invoke method + response = _service.import_skills_status( + assistant_id, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + + def test_import_skills_status_all_params_with_retries(self): + # Enable retries and run test_import_skills_status_all_params. + _service.enable_retries() + self.test_import_skills_status_all_params() + + # Disable retries and run test_import_skills_status_all_params. + _service.disable_retries() + self.test_import_skills_status_all_params() + + @responses.activate + def test_import_skills_status_value_error(self): + """ + test_import_skills_status_value_error() + """ + # Set up mock + url = preprocess_url('/v2/assistants/testString/skills_import/status') + mock_response = '{"assistant_id": "assistant_id", "status": "Available", "status_description": "status_description", "status_errors": [{"message": "message"}]}' + responses.add( + responses.GET, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + assistant_id = 'testString' + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "assistant_id": assistant_id, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.import_skills_status(**req_copy) + + def test_import_skills_status_value_error_with_retries(self): + # Enable retries and run test_import_skills_status_value_error. + _service.enable_retries() + self.test_import_skills_status_value_error() + + # Disable retries and run test_import_skills_status_value_error. + _service.disable_retries() + self.test_import_skills_status_value_error() + + +# endregion +############################################################################## +# End of Service: Skills +############################################################################## + + +############################################################################## +# Start of Model Tests +############################################################################## +# region + + +class TestModel_AgentAvailabilityMessage: + """ + Test Class for AgentAvailabilityMessage + """ + + def test_agent_availability_message_serialization(self): + """ + Test serialization/deserialization for AgentAvailabilityMessage + """ + + # Construct a json representation of a AgentAvailabilityMessage model + agent_availability_message_model_json = {} + agent_availability_message_model_json['message'] = 'testString' + + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json) + assert agent_availability_message_model != False + + # Construct a model instance of AgentAvailabilityMessage by calling from_dict on the json representation + agent_availability_message_model_dict = AgentAvailabilityMessage.from_dict(agent_availability_message_model_json).__dict__ + agent_availability_message_model2 = AgentAvailabilityMessage(**agent_availability_message_model_dict) + + # Verify the model instances are equivalent + assert agent_availability_message_model == agent_availability_message_model2 + + # Convert model instance back to dict and verify no loss of data + agent_availability_message_model_json2 = agent_availability_message_model.to_dict() + assert agent_availability_message_model_json2 == agent_availability_message_model_json + + +class TestModel_AssistantCollection: + """ + Test Class for AssistantCollection + """ + + def test_assistant_collection_serialization(self): + """ + Test serialization/deserialization for AssistantCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + assistant_data_model = {} # AssistantData + assistant_data_model['name'] = 'testString' + assistant_data_model['description'] = 'testString' + assistant_data_model['language'] = 'testString' + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a AssistantCollection model + assistant_collection_model_json = {} + assistant_collection_model_json['assistants'] = [assistant_data_model] + assistant_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of AssistantCollection by calling from_dict on the json representation + assistant_collection_model = AssistantCollection.from_dict(assistant_collection_model_json) + assert assistant_collection_model != False + + # Construct a model instance of AssistantCollection by calling from_dict on the json representation + assistant_collection_model_dict = AssistantCollection.from_dict(assistant_collection_model_json).__dict__ + assistant_collection_model2 = AssistantCollection(**assistant_collection_model_dict) + + # Verify the model instances are equivalent + assert assistant_collection_model == assistant_collection_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_collection_model_json2 = assistant_collection_model.to_dict() + assert assistant_collection_model_json2 == assistant_collection_model_json + + +class TestModel_AssistantData: + """ + Test Class for AssistantData + """ + + def test_assistant_data_serialization(self): + """ + Test serialization/deserialization for AssistantData + """ + + # Construct a json representation of a AssistantData model + assistant_data_model_json = {} + assistant_data_model_json['name'] = 'testString' + assistant_data_model_json['description'] = 'testString' + assistant_data_model_json['language'] = 'testString' + + # Construct a model instance of AssistantData by calling from_dict on the json representation + assistant_data_model = AssistantData.from_dict(assistant_data_model_json) + assert assistant_data_model != False + + # Construct a model instance of AssistantData by calling from_dict on the json representation + assistant_data_model_dict = AssistantData.from_dict(assistant_data_model_json).__dict__ + assistant_data_model2 = AssistantData(**assistant_data_model_dict) + + # Verify the model instances are equivalent + assert assistant_data_model == assistant_data_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_data_model_json2 = assistant_data_model.to_dict() + assert assistant_data_model_json2 == assistant_data_model_json + + +class TestModel_AssistantSkill: + """ + Test Class for AssistantSkill + """ + + def test_assistant_skill_serialization(self): + """ + Test serialization/deserialization for AssistantSkill + """ + + # Construct a json representation of a AssistantSkill model + assistant_skill_model_json = {} + assistant_skill_model_json['skill_id'] = 'testString' + assistant_skill_model_json['type'] = 'dialog' + + # Construct a model instance of AssistantSkill by calling from_dict on the json representation + assistant_skill_model = AssistantSkill.from_dict(assistant_skill_model_json) + assert assistant_skill_model != False + + # Construct a model instance of AssistantSkill by calling from_dict on the json representation + assistant_skill_model_dict = AssistantSkill.from_dict(assistant_skill_model_json).__dict__ + assistant_skill_model2 = AssistantSkill(**assistant_skill_model_dict) + + # Verify the model instances are equivalent + assert assistant_skill_model == assistant_skill_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_skill_model_json2 = assistant_skill_model.to_dict() + assert assistant_skill_model_json2 == assistant_skill_model_json + + +class TestModel_AssistantState: + """ + Test Class for AssistantState + """ + + def test_assistant_state_serialization(self): + """ + Test serialization/deserialization for AssistantState + """ + + # Construct a json representation of a AssistantState model + assistant_state_model_json = {} + assistant_state_model_json['action_disabled'] = True + assistant_state_model_json['dialog_disabled'] = True + + # Construct a model instance of AssistantState by calling from_dict on the json representation + assistant_state_model = AssistantState.from_dict(assistant_state_model_json) + assert assistant_state_model != False + + # Construct a model instance of AssistantState by calling from_dict on the json representation + assistant_state_model_dict = AssistantState.from_dict(assistant_state_model_json).__dict__ + assistant_state_model2 = AssistantState(**assistant_state_model_dict) + + # Verify the model instances are equivalent + assert assistant_state_model == assistant_state_model2 + + # Convert model instance back to dict and verify no loss of data + assistant_state_model_json2 = assistant_state_model.to_dict() + assert assistant_state_model_json2 == assistant_state_model_json + + +class TestModel_BaseEnvironmentOrchestration: + """ Test Class for BaseEnvironmentOrchestration """ - def test_base_environment_orchestration_serialization(self): + def test_base_environment_orchestration_serialization(self): + """ + Test serialization/deserialization for BaseEnvironmentOrchestration + """ + + # Construct a json representation of a BaseEnvironmentOrchestration model + base_environment_orchestration_model_json = {} + base_environment_orchestration_model_json['search_skill_fallback'] = True + + # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation + base_environment_orchestration_model = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json) + assert base_environment_orchestration_model != False + + # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation + base_environment_orchestration_model_dict = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json).__dict__ + base_environment_orchestration_model2 = BaseEnvironmentOrchestration(**base_environment_orchestration_model_dict) + + # Verify the model instances are equivalent + assert base_environment_orchestration_model == base_environment_orchestration_model2 + + # Convert model instance back to dict and verify no loss of data + base_environment_orchestration_model_json2 = base_environment_orchestration_model.to_dict() + assert base_environment_orchestration_model_json2 == base_environment_orchestration_model_json + + +class TestModel_BaseEnvironmentReleaseReference: + """ + Test Class for BaseEnvironmentReleaseReference + """ + + def test_base_environment_release_reference_serialization(self): + """ + Test serialization/deserialization for BaseEnvironmentReleaseReference + """ + + # Construct a json representation of a BaseEnvironmentReleaseReference model + base_environment_release_reference_model_json = {} + base_environment_release_reference_model_json['release'] = 'testString' + + # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation + base_environment_release_reference_model = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json) + assert base_environment_release_reference_model != False + + # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation + base_environment_release_reference_model_dict = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json).__dict__ + base_environment_release_reference_model2 = BaseEnvironmentReleaseReference(**base_environment_release_reference_model_dict) + + # Verify the model instances are equivalent + assert base_environment_release_reference_model == base_environment_release_reference_model2 + + # Convert model instance back to dict and verify no loss of data + base_environment_release_reference_model_json2 = base_environment_release_reference_model.to_dict() + assert base_environment_release_reference_model_json2 == base_environment_release_reference_model_json + + +class TestModel_BulkClassifyOutput: + """ + Test Class for BulkClassifyOutput + """ + + def test_bulk_classify_output_serialization(self): + """ + Test serialization/deserialization for BulkClassifyOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + # Construct a json representation of a BulkClassifyOutput model + bulk_classify_output_model_json = {} + bulk_classify_output_model_json['input'] = bulk_classify_utterance_model + bulk_classify_output_model_json['entities'] = [runtime_entity_model] + bulk_classify_output_model_json['intents'] = [runtime_intent_model] + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model = BulkClassifyOutput.from_dict(bulk_classify_output_model_json) + assert bulk_classify_output_model != False + + # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation + bulk_classify_output_model_dict = BulkClassifyOutput.from_dict(bulk_classify_output_model_json).__dict__ + bulk_classify_output_model2 = BulkClassifyOutput(**bulk_classify_output_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_output_model == bulk_classify_output_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() + assert bulk_classify_output_model_json2 == bulk_classify_output_model_json + + +class TestModel_BulkClassifyResponse: + """ + Test Class for BulkClassifyResponse + """ + + def test_bulk_classify_response_serialization(self): + """ + Test serialization/deserialization for BulkClassifyResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + bulk_classify_utterance_model = {} # BulkClassifyUtterance + bulk_classify_utterance_model['text'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + bulk_classify_output_model = {} # BulkClassifyOutput + bulk_classify_output_model['input'] = bulk_classify_utterance_model + bulk_classify_output_model['entities'] = [runtime_entity_model] + bulk_classify_output_model['intents'] = [runtime_intent_model] + + # Construct a json representation of a BulkClassifyResponse model + bulk_classify_response_model_json = {} + bulk_classify_response_model_json['output'] = [bulk_classify_output_model] + + # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation + bulk_classify_response_model = BulkClassifyResponse.from_dict(bulk_classify_response_model_json) + assert bulk_classify_response_model != False + + # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation + bulk_classify_response_model_dict = BulkClassifyResponse.from_dict(bulk_classify_response_model_json).__dict__ + bulk_classify_response_model2 = BulkClassifyResponse(**bulk_classify_response_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_response_model == bulk_classify_response_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() + assert bulk_classify_response_model_json2 == bulk_classify_response_model_json + + +class TestModel_BulkClassifyUtterance: + """ + Test Class for BulkClassifyUtterance + """ + + def test_bulk_classify_utterance_serialization(self): + """ + Test serialization/deserialization for BulkClassifyUtterance + """ + + # Construct a json representation of a BulkClassifyUtterance model + bulk_classify_utterance_model_json = {} + bulk_classify_utterance_model_json['text'] = 'testString' + + # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation + bulk_classify_utterance_model = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json) + assert bulk_classify_utterance_model != False + + # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation + bulk_classify_utterance_model_dict = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json).__dict__ + bulk_classify_utterance_model2 = BulkClassifyUtterance(**bulk_classify_utterance_model_dict) + + # Verify the model instances are equivalent + assert bulk_classify_utterance_model == bulk_classify_utterance_model2 + + # Convert model instance back to dict and verify no loss of data + bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() + assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json + + +class TestModel_CaptureGroup: + """ + Test Class for CaptureGroup + """ + + def test_capture_group_serialization(self): + """ + Test serialization/deserialization for CaptureGroup + """ + + # Construct a json representation of a CaptureGroup model + capture_group_model_json = {} + capture_group_model_json['group'] = 'testString' + capture_group_model_json['location'] = [38] + + # Construct a model instance of CaptureGroup by calling from_dict on the json representation + capture_group_model = CaptureGroup.from_dict(capture_group_model_json) + assert capture_group_model != False + + # Construct a model instance of CaptureGroup by calling from_dict on the json representation + capture_group_model_dict = CaptureGroup.from_dict(capture_group_model_json).__dict__ + capture_group_model2 = CaptureGroup(**capture_group_model_dict) + + # Verify the model instances are equivalent + assert capture_group_model == capture_group_model2 + + # Convert model instance back to dict and verify no loss of data + capture_group_model_json2 = capture_group_model.to_dict() + assert capture_group_model_json2 == capture_group_model_json + + +class TestModel_ChannelTransferInfo: + """ + Test Class for ChannelTransferInfo + """ + + def test_channel_transfer_info_serialization(self): + """ + Test serialization/deserialization for ChannelTransferInfo + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + channel_transfer_target_model = {} # ChannelTransferTarget + channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + + # Construct a json representation of a ChannelTransferInfo model + channel_transfer_info_model_json = {} + channel_transfer_info_model_json['target'] = channel_transfer_target_model + + # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation + channel_transfer_info_model = ChannelTransferInfo.from_dict(channel_transfer_info_model_json) + assert channel_transfer_info_model != False + + # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation + channel_transfer_info_model_dict = ChannelTransferInfo.from_dict(channel_transfer_info_model_json).__dict__ + channel_transfer_info_model2 = ChannelTransferInfo(**channel_transfer_info_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_info_model == channel_transfer_info_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() + assert channel_transfer_info_model_json2 == channel_transfer_info_model_json + + +class TestModel_ChannelTransferTarget: + """ + Test Class for ChannelTransferTarget + """ + + def test_channel_transfer_target_serialization(self): + """ + Test serialization/deserialization for ChannelTransferTarget + """ + + # Construct dict forms of any model objects needed in order to build this model. + + channel_transfer_target_chat_model = {} # ChannelTransferTargetChat + channel_transfer_target_chat_model['url'] = 'testString' + + # Construct a json representation of a ChannelTransferTarget model + channel_transfer_target_model_json = {} + channel_transfer_target_model_json['chat'] = channel_transfer_target_chat_model + + # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation + channel_transfer_target_model = ChannelTransferTarget.from_dict(channel_transfer_target_model_json) + assert channel_transfer_target_model != False + + # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation + channel_transfer_target_model_dict = ChannelTransferTarget.from_dict(channel_transfer_target_model_json).__dict__ + channel_transfer_target_model2 = ChannelTransferTarget(**channel_transfer_target_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_target_model == channel_transfer_target_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() + assert channel_transfer_target_model_json2 == channel_transfer_target_model_json + + +class TestModel_ChannelTransferTargetChat: + """ + Test Class for ChannelTransferTargetChat + """ + + def test_channel_transfer_target_chat_serialization(self): + """ + Test serialization/deserialization for ChannelTransferTargetChat + """ + + # Construct a json representation of a ChannelTransferTargetChat model + channel_transfer_target_chat_model_json = {} + channel_transfer_target_chat_model_json['url'] = 'testString' + + # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation + channel_transfer_target_chat_model = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json) + assert channel_transfer_target_chat_model != False + + # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation + channel_transfer_target_chat_model_dict = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json).__dict__ + channel_transfer_target_chat_model2 = ChannelTransferTargetChat(**channel_transfer_target_chat_model_dict) + + # Verify the model instances are equivalent + assert channel_transfer_target_chat_model == channel_transfer_target_chat_model2 + + # Convert model instance back to dict and verify no loss of data + channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() + assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json + + +class TestModel_CreateAssistantReleaseImportResponse: + """ + Test Class for CreateAssistantReleaseImportResponse + """ + + def test_create_assistant_release_import_response_serialization(self): + """ + Test serialization/deserialization for CreateAssistantReleaseImportResponse + """ + + # Construct a json representation of a CreateAssistantReleaseImportResponse model + create_assistant_release_import_response_model_json = {} + create_assistant_release_import_response_model_json['skill_impact_in_draft'] = ['action'] + + # Construct a model instance of CreateAssistantReleaseImportResponse by calling from_dict on the json representation + create_assistant_release_import_response_model = CreateAssistantReleaseImportResponse.from_dict(create_assistant_release_import_response_model_json) + assert create_assistant_release_import_response_model != False + + # Construct a model instance of CreateAssistantReleaseImportResponse by calling from_dict on the json representation + create_assistant_release_import_response_model_dict = CreateAssistantReleaseImportResponse.from_dict(create_assistant_release_import_response_model_json).__dict__ + create_assistant_release_import_response_model2 = CreateAssistantReleaseImportResponse(**create_assistant_release_import_response_model_dict) + + # Verify the model instances are equivalent + assert create_assistant_release_import_response_model == create_assistant_release_import_response_model2 + + # Convert model instance back to dict and verify no loss of data + create_assistant_release_import_response_model_json2 = create_assistant_release_import_response_model.to_dict() + assert create_assistant_release_import_response_model_json2 == create_assistant_release_import_response_model_json + + +class TestModel_CreateReleaseExportWithStatusErrors: + """ + Test Class for CreateReleaseExportWithStatusErrors + """ + + def test_create_release_export_with_status_errors_serialization(self): + """ + Test serialization/deserialization for CreateReleaseExportWithStatusErrors + """ + + # Construct a json representation of a CreateReleaseExportWithStatusErrors model + create_release_export_with_status_errors_model_json = {} + + # Construct a model instance of CreateReleaseExportWithStatusErrors by calling from_dict on the json representation + create_release_export_with_status_errors_model = CreateReleaseExportWithStatusErrors.from_dict(create_release_export_with_status_errors_model_json) + assert create_release_export_with_status_errors_model != False + + # Construct a model instance of CreateReleaseExportWithStatusErrors by calling from_dict on the json representation + create_release_export_with_status_errors_model_dict = CreateReleaseExportWithStatusErrors.from_dict(create_release_export_with_status_errors_model_json).__dict__ + create_release_export_with_status_errors_model2 = CreateReleaseExportWithStatusErrors(**create_release_export_with_status_errors_model_dict) + + # Verify the model instances are equivalent + assert create_release_export_with_status_errors_model == create_release_export_with_status_errors_model2 + + # Convert model instance back to dict and verify no loss of data + create_release_export_with_status_errors_model_json2 = create_release_export_with_status_errors_model.to_dict() + assert create_release_export_with_status_errors_model_json2 == create_release_export_with_status_errors_model_json + + +class TestModel_DialogLogMessage: + """ + Test Class for DialogLogMessage + """ + + def test_dialog_log_message_serialization(self): + """ + Test serialization/deserialization for DialogLogMessage + """ + + # Construct dict forms of any model objects needed in order to build this model. + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + # Construct a json representation of a DialogLogMessage model + dialog_log_message_model_json = {} + dialog_log_message_model_json['level'] = 'info' + dialog_log_message_model_json['message'] = 'testString' + dialog_log_message_model_json['code'] = 'testString' + dialog_log_message_model_json['source'] = log_message_source_model + + # Construct a model instance of DialogLogMessage by calling from_dict on the json representation + dialog_log_message_model = DialogLogMessage.from_dict(dialog_log_message_model_json) + assert dialog_log_message_model != False + + # Construct a model instance of DialogLogMessage by calling from_dict on the json representation + dialog_log_message_model_dict = DialogLogMessage.from_dict(dialog_log_message_model_json).__dict__ + dialog_log_message_model2 = DialogLogMessage(**dialog_log_message_model_dict) + + # Verify the model instances are equivalent + assert dialog_log_message_model == dialog_log_message_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_log_message_model_json2 = dialog_log_message_model.to_dict() + assert dialog_log_message_model_json2 == dialog_log_message_model_json + + +class TestModel_DialogNodeAction: + """ + Test Class for DialogNodeAction + """ + + def test_dialog_node_action_serialization(self): + """ + Test serialization/deserialization for DialogNodeAction + """ + + # Construct a json representation of a DialogNodeAction model + dialog_node_action_model_json = {} + dialog_node_action_model_json['name'] = 'testString' + dialog_node_action_model_json['type'] = 'client' + dialog_node_action_model_json['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model_json['result_variable'] = 'testString' + dialog_node_action_model_json['credentials'] = 'testString' + + # Construct a model instance of DialogNodeAction by calling from_dict on the json representation + dialog_node_action_model = DialogNodeAction.from_dict(dialog_node_action_model_json) + assert dialog_node_action_model != False + + # Construct a model instance of DialogNodeAction by calling from_dict on the json representation + dialog_node_action_model_dict = DialogNodeAction.from_dict(dialog_node_action_model_json).__dict__ + dialog_node_action_model2 = DialogNodeAction(**dialog_node_action_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_action_model == dialog_node_action_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_action_model_json2 = dialog_node_action_model.to_dict() + assert dialog_node_action_model_json2 == dialog_node_action_model_json + + +class TestModel_DialogNodeOutputConnectToAgentTransferInfo: + """ + Test Class for DialogNodeOutputConnectToAgentTransferInfo + """ + + def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): """ - Test serialization/deserialization for BaseEnvironmentOrchestration + Test serialization/deserialization for DialogNodeOutputConnectToAgentTransferInfo + """ + + # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model + dialog_node_output_connect_to_agent_transfer_info_model_json = {} + dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'anyKey': 'anyValue'}} + + # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation + dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) + assert dialog_node_output_connect_to_agent_transfer_info_model != False + + # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation + dialog_node_output_connect_to_agent_transfer_info_model_dict = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json).__dict__ + dialog_node_output_connect_to_agent_transfer_info_model2 = DialogNodeOutputConnectToAgentTransferInfo(**dialog_node_output_connect_to_agent_transfer_info_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_connect_to_agent_transfer_info_model == dialog_node_output_connect_to_agent_transfer_info_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() + assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json + + +class TestModel_DialogNodeOutputOptionsElement: + """ + Test Class for DialogNodeOutputOptionsElement + """ + + def test_dialog_node_output_options_element_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputOptionsElement + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue + dialog_node_output_options_element_value_model['input'] = message_input_model + + # Construct a json representation of a DialogNodeOutputOptionsElement model + dialog_node_output_options_element_model_json = {} + dialog_node_output_options_element_model_json['label'] = 'testString' + dialog_node_output_options_element_model_json['value'] = dialog_node_output_options_element_value_model + + # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation + dialog_node_output_options_element_model = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json) + assert dialog_node_output_options_element_model != False + + # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation + dialog_node_output_options_element_model_dict = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json).__dict__ + dialog_node_output_options_element_model2 = DialogNodeOutputOptionsElement(**dialog_node_output_options_element_model_dict) + + # Verify the model instances are equivalent + assert dialog_node_output_options_element_model == dialog_node_output_options_element_model2 + + # Convert model instance back to dict and verify no loss of data + dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() + assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json + + +class TestModel_DialogNodeOutputOptionsElementValue: + """ + Test Class for DialogNodeOutputOptionsElementValue + """ + + def test_dialog_node_output_options_element_value_serialization(self): + """ + Test serialization/deserialization for DialogNodeOutputOptionsElementValue """ - # Construct a json representation of a BaseEnvironmentOrchestration model - base_environment_orchestration_model_json = {} - base_environment_orchestration_model_json['search_skill_fallback'] = True + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model - # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation - base_environment_orchestration_model = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json) - assert base_environment_orchestration_model != False + # Construct a json representation of a DialogNodeOutputOptionsElementValue model + dialog_node_output_options_element_value_model_json = {} + dialog_node_output_options_element_value_model_json['input'] = message_input_model - # Construct a model instance of BaseEnvironmentOrchestration by calling from_dict on the json representation - base_environment_orchestration_model_dict = BaseEnvironmentOrchestration.from_dict(base_environment_orchestration_model_json).__dict__ - base_environment_orchestration_model2 = BaseEnvironmentOrchestration(**base_environment_orchestration_model_dict) + # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation + dialog_node_output_options_element_value_model = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json) + assert dialog_node_output_options_element_value_model != False + + # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation + dialog_node_output_options_element_value_model_dict = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json).__dict__ + dialog_node_output_options_element_value_model2 = DialogNodeOutputOptionsElementValue(**dialog_node_output_options_element_value_model_dict) # Verify the model instances are equivalent - assert base_environment_orchestration_model == base_environment_orchestration_model2 + assert dialog_node_output_options_element_value_model == dialog_node_output_options_element_value_model2 # Convert model instance back to dict and verify no loss of data - base_environment_orchestration_model_json2 = base_environment_orchestration_model.to_dict() - assert base_environment_orchestration_model_json2 == base_environment_orchestration_model_json + dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() + assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json -class TestModel_BaseEnvironmentReleaseReference: +class TestModel_DialogNodeVisited: """ - Test Class for BaseEnvironmentReleaseReference + Test Class for DialogNodeVisited """ - def test_base_environment_release_reference_serialization(self): + def test_dialog_node_visited_serialization(self): """ - Test serialization/deserialization for BaseEnvironmentReleaseReference + Test serialization/deserialization for DialogNodeVisited """ - # Construct a json representation of a BaseEnvironmentReleaseReference model - base_environment_release_reference_model_json = {} - base_environment_release_reference_model_json['release'] = 'testString' + # Construct a json representation of a DialogNodeVisited model + dialog_node_visited_model_json = {} + dialog_node_visited_model_json['dialog_node'] = 'testString' + dialog_node_visited_model_json['title'] = 'testString' + dialog_node_visited_model_json['conditions'] = 'testString' - # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation - base_environment_release_reference_model = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json) - assert base_environment_release_reference_model != False + # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation + dialog_node_visited_model = DialogNodeVisited.from_dict(dialog_node_visited_model_json) + assert dialog_node_visited_model != False - # Construct a model instance of BaseEnvironmentReleaseReference by calling from_dict on the json representation - base_environment_release_reference_model_dict = BaseEnvironmentReleaseReference.from_dict(base_environment_release_reference_model_json).__dict__ - base_environment_release_reference_model2 = BaseEnvironmentReleaseReference(**base_environment_release_reference_model_dict) + # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation + dialog_node_visited_model_dict = DialogNodeVisited.from_dict(dialog_node_visited_model_json).__dict__ + dialog_node_visited_model2 = DialogNodeVisited(**dialog_node_visited_model_dict) # Verify the model instances are equivalent - assert base_environment_release_reference_model == base_environment_release_reference_model2 + assert dialog_node_visited_model == dialog_node_visited_model2 # Convert model instance back to dict and verify no loss of data - base_environment_release_reference_model_json2 = base_environment_release_reference_model.to_dict() - assert base_environment_release_reference_model_json2 == base_environment_release_reference_model_json + dialog_node_visited_model_json2 = dialog_node_visited_model.to_dict() + assert dialog_node_visited_model_json2 == dialog_node_visited_model_json -class TestModel_BulkClassifyOutput: +class TestModel_DialogSuggestion: """ - Test Class for BulkClassifyOutput + Test Class for DialogSuggestion """ - def test_bulk_classify_output_serialization(self): + def test_dialog_suggestion_serialization(self): """ - Test serialization/deserialization for BulkClassifyOutput + Test serialization/deserialization for DialogSuggestion """ # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance - bulk_classify_utterance_model['text'] = 'testString' + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3650,47 +6319,79 @@ def test_bulk_classify_output_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' - # Construct a json representation of a BulkClassifyOutput model - bulk_classify_output_model_json = {} - bulk_classify_output_model_json['input'] = bulk_classify_utterance_model - bulk_classify_output_model_json['entities'] = [runtime_entity_model] - bulk_classify_output_model_json['intents'] = [runtime_intent_model] + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' - # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation - bulk_classify_output_model = BulkClassifyOutput.from_dict(bulk_classify_output_model_json) - assert bulk_classify_output_model != False + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - # Construct a model instance of BulkClassifyOutput by calling from_dict on the json representation - bulk_classify_output_model_dict = BulkClassifyOutput.from_dict(bulk_classify_output_model_json).__dict__ - bulk_classify_output_model2 = BulkClassifyOutput(**bulk_classify_output_model_dict) + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + dialog_suggestion_value_model = {} # DialogSuggestionValue + dialog_suggestion_value_model['input'] = message_input_model + + # Construct a json representation of a DialogSuggestion model + dialog_suggestion_model_json = {} + dialog_suggestion_model_json['label'] = 'testString' + dialog_suggestion_model_json['value'] = dialog_suggestion_value_model + dialog_suggestion_model_json['output'] = {'anyKey': 'anyValue'} + + # Construct a model instance of DialogSuggestion by calling from_dict on the json representation + dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) + assert dialog_suggestion_model != False + + # Construct a model instance of DialogSuggestion by calling from_dict on the json representation + dialog_suggestion_model_dict = DialogSuggestion.from_dict(dialog_suggestion_model_json).__dict__ + dialog_suggestion_model2 = DialogSuggestion(**dialog_suggestion_model_dict) # Verify the model instances are equivalent - assert bulk_classify_output_model == bulk_classify_output_model2 + assert dialog_suggestion_model == dialog_suggestion_model2 # Convert model instance back to dict and verify no loss of data - bulk_classify_output_model_json2 = bulk_classify_output_model.to_dict() - assert bulk_classify_output_model_json2 == bulk_classify_output_model_json + dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() + assert dialog_suggestion_model_json2 == dialog_suggestion_model_json -class TestModel_BulkClassifyResponse: +class TestModel_DialogSuggestionValue: """ - Test Class for BulkClassifyResponse + Test Class for DialogSuggestionValue """ - def test_bulk_classify_response_serialization(self): + def test_dialog_suggestion_value_serialization(self): """ - Test serialization/deserialization for BulkClassifyResponse + Test serialization/deserialization for DialogSuggestionValue """ # Construct dict forms of any model objects needed in order to build this model. - bulk_classify_utterance_model = {} # BulkClassifyUtterance - bulk_classify_utterance_model['text'] = 'testString' + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -3742,311 +6443,265 @@ def test_bulk_classify_response_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' - - bulk_classify_output_model = {} # BulkClassifyOutput - bulk_classify_output_model['input'] = bulk_classify_utterance_model - bulk_classify_output_model['entities'] = [runtime_entity_model] - bulk_classify_output_model['intents'] = [runtime_intent_model] - - # Construct a json representation of a BulkClassifyResponse model - bulk_classify_response_model_json = {} - bulk_classify_response_model_json['output'] = [bulk_classify_output_model] - - # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation - bulk_classify_response_model = BulkClassifyResponse.from_dict(bulk_classify_response_model_json) - assert bulk_classify_response_model != False - - # Construct a model instance of BulkClassifyResponse by calling from_dict on the json representation - bulk_classify_response_model_dict = BulkClassifyResponse.from_dict(bulk_classify_response_model_json).__dict__ - bulk_classify_response_model2 = BulkClassifyResponse(**bulk_classify_response_model_dict) - - # Verify the model instances are equivalent - assert bulk_classify_response_model == bulk_classify_response_model2 - - # Convert model instance back to dict and verify no loss of data - bulk_classify_response_model_json2 = bulk_classify_response_model.to_dict() - assert bulk_classify_response_model_json2 == bulk_classify_response_model_json - - -class TestModel_BulkClassifyUtterance: - """ - Test Class for BulkClassifyUtterance - """ - - def test_bulk_classify_utterance_serialization(self): - """ - Test serialization/deserialization for BulkClassifyUtterance - """ - - # Construct a json representation of a BulkClassifyUtterance model - bulk_classify_utterance_model_json = {} - bulk_classify_utterance_model_json['text'] = 'testString' - - # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation - bulk_classify_utterance_model = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json) - assert bulk_classify_utterance_model != False - - # Construct a model instance of BulkClassifyUtterance by calling from_dict on the json representation - bulk_classify_utterance_model_dict = BulkClassifyUtterance.from_dict(bulk_classify_utterance_model_json).__dict__ - bulk_classify_utterance_model2 = BulkClassifyUtterance(**bulk_classify_utterance_model_dict) - - # Verify the model instances are equivalent - assert bulk_classify_utterance_model == bulk_classify_utterance_model2 + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' - # Convert model instance back to dict and verify no loss of data - bulk_classify_utterance_model_json2 = bulk_classify_utterance_model.to_dict() - assert bulk_classify_utterance_model_json2 == bulk_classify_utterance_model_json + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True -class TestModel_CaptureGroup: - """ - Test Class for CaptureGroup - """ + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False - def test_capture_group_serialization(self): - """ - Test serialization/deserialization for CaptureGroup - """ + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model - # Construct a json representation of a CaptureGroup model - capture_group_model_json = {} - capture_group_model_json['group'] = 'testString' - capture_group_model_json['location'] = [38] + # Construct a json representation of a DialogSuggestionValue model + dialog_suggestion_value_model_json = {} + dialog_suggestion_value_model_json['input'] = message_input_model - # Construct a model instance of CaptureGroup by calling from_dict on the json representation - capture_group_model = CaptureGroup.from_dict(capture_group_model_json) - assert capture_group_model != False + # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation + dialog_suggestion_value_model = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json) + assert dialog_suggestion_value_model != False - # Construct a model instance of CaptureGroup by calling from_dict on the json representation - capture_group_model_dict = CaptureGroup.from_dict(capture_group_model_json).__dict__ - capture_group_model2 = CaptureGroup(**capture_group_model_dict) + # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation + dialog_suggestion_value_model_dict = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json).__dict__ + dialog_suggestion_value_model2 = DialogSuggestionValue(**dialog_suggestion_value_model_dict) # Verify the model instances are equivalent - assert capture_group_model == capture_group_model2 + assert dialog_suggestion_value_model == dialog_suggestion_value_model2 # Convert model instance back to dict and verify no loss of data - capture_group_model_json2 = capture_group_model.to_dict() - assert capture_group_model_json2 == capture_group_model_json + dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() + assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json -class TestModel_ChannelTransferInfo: +class TestModel_Environment: """ - Test Class for ChannelTransferInfo + Test Class for Environment """ - def test_channel_transfer_info_serialization(self): + def test_environment_serialization(self): """ - Test serialization/deserialization for ChannelTransferInfo + Test serialization/deserialization for Environment """ # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat - channel_transfer_target_chat_model['url'] = 'testString' + base_environment_orchestration_model = {} # BaseEnvironmentOrchestration + base_environment_orchestration_model['search_skill_fallback'] = True - channel_transfer_target_model = {} # ChannelTransferTarget - channel_transfer_target_model['chat'] = channel_transfer_target_chat_model + environment_skill_model = {} # EnvironmentSkill + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' - # Construct a json representation of a ChannelTransferInfo model - channel_transfer_info_model_json = {} - channel_transfer_info_model_json['target'] = channel_transfer_target_model + # Construct a json representation of a Environment model + environment_model_json = {} + environment_model_json['name'] = 'testString' + environment_model_json['description'] = 'testString' + environment_model_json['orchestration'] = base_environment_orchestration_model + environment_model_json['session_timeout'] = 10 + environment_model_json['skill_references'] = [environment_skill_model] - # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation - channel_transfer_info_model = ChannelTransferInfo.from_dict(channel_transfer_info_model_json) - assert channel_transfer_info_model != False + # Construct a model instance of Environment by calling from_dict on the json representation + environment_model = Environment.from_dict(environment_model_json) + assert environment_model != False - # Construct a model instance of ChannelTransferInfo by calling from_dict on the json representation - channel_transfer_info_model_dict = ChannelTransferInfo.from_dict(channel_transfer_info_model_json).__dict__ - channel_transfer_info_model2 = ChannelTransferInfo(**channel_transfer_info_model_dict) + # Construct a model instance of Environment by calling from_dict on the json representation + environment_model_dict = Environment.from_dict(environment_model_json).__dict__ + environment_model2 = Environment(**environment_model_dict) # Verify the model instances are equivalent - assert channel_transfer_info_model == channel_transfer_info_model2 + assert environment_model == environment_model2 # Convert model instance back to dict and verify no loss of data - channel_transfer_info_model_json2 = channel_transfer_info_model.to_dict() - assert channel_transfer_info_model_json2 == channel_transfer_info_model_json + environment_model_json2 = environment_model.to_dict() + assert environment_model_json2 == environment_model_json -class TestModel_ChannelTransferTarget: +class TestModel_EnvironmentCollection: """ - Test Class for ChannelTransferTarget + Test Class for EnvironmentCollection """ - def test_channel_transfer_target_serialization(self): + def test_environment_collection_serialization(self): """ - Test serialization/deserialization for ChannelTransferTarget + Test serialization/deserialization for EnvironmentCollection """ # Construct dict forms of any model objects needed in order to build this model. - channel_transfer_target_chat_model = {} # ChannelTransferTargetChat - channel_transfer_target_chat_model['url'] = 'testString' - - # Construct a json representation of a ChannelTransferTarget model - channel_transfer_target_model_json = {} - channel_transfer_target_model_json['chat'] = channel_transfer_target_chat_model - - # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation - channel_transfer_target_model = ChannelTransferTarget.from_dict(channel_transfer_target_model_json) - assert channel_transfer_target_model != False - - # Construct a model instance of ChannelTransferTarget by calling from_dict on the json representation - channel_transfer_target_model_dict = ChannelTransferTarget.from_dict(channel_transfer_target_model_json).__dict__ - channel_transfer_target_model2 = ChannelTransferTarget(**channel_transfer_target_model_dict) - - # Verify the model instances are equivalent - assert channel_transfer_target_model == channel_transfer_target_model2 - - # Convert model instance back to dict and verify no loss of data - channel_transfer_target_model_json2 = channel_transfer_target_model.to_dict() - assert channel_transfer_target_model_json2 == channel_transfer_target_model_json + base_environment_orchestration_model = {} # BaseEnvironmentOrchestration + base_environment_orchestration_model['search_skill_fallback'] = True + environment_skill_model = {} # EnvironmentSkill + environment_skill_model['skill_id'] = 'testString' + environment_skill_model['type'] = 'dialog' + environment_skill_model['disabled'] = True + environment_skill_model['snapshot'] = 'testString' + environment_skill_model['skill_reference'] = 'testString' -class TestModel_ChannelTransferTargetChat: - """ - Test Class for ChannelTransferTargetChat - """ + environment_model = {} # Environment + environment_model['name'] = 'testString' + environment_model['description'] = 'testString' + environment_model['orchestration'] = base_environment_orchestration_model + environment_model['session_timeout'] = 10 + environment_model['skill_references'] = [environment_skill_model] - def test_channel_transfer_target_chat_serialization(self): - """ - Test serialization/deserialization for ChannelTransferTargetChat - """ + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' - # Construct a json representation of a ChannelTransferTargetChat model - channel_transfer_target_chat_model_json = {} - channel_transfer_target_chat_model_json['url'] = 'testString' + # Construct a json representation of a EnvironmentCollection model + environment_collection_model_json = {} + environment_collection_model_json['environments'] = [environment_model] + environment_collection_model_json['pagination'] = pagination_model - # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation - channel_transfer_target_chat_model = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json) - assert channel_transfer_target_chat_model != False + # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation + environment_collection_model = EnvironmentCollection.from_dict(environment_collection_model_json) + assert environment_collection_model != False - # Construct a model instance of ChannelTransferTargetChat by calling from_dict on the json representation - channel_transfer_target_chat_model_dict = ChannelTransferTargetChat.from_dict(channel_transfer_target_chat_model_json).__dict__ - channel_transfer_target_chat_model2 = ChannelTransferTargetChat(**channel_transfer_target_chat_model_dict) + # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation + environment_collection_model_dict = EnvironmentCollection.from_dict(environment_collection_model_json).__dict__ + environment_collection_model2 = EnvironmentCollection(**environment_collection_model_dict) # Verify the model instances are equivalent - assert channel_transfer_target_chat_model == channel_transfer_target_chat_model2 + assert environment_collection_model == environment_collection_model2 # Convert model instance back to dict and verify no loss of data - channel_transfer_target_chat_model_json2 = channel_transfer_target_chat_model.to_dict() - assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json + environment_collection_model_json2 = environment_collection_model.to_dict() + assert environment_collection_model_json2 == environment_collection_model_json -class TestModel_DialogLogMessage: +class TestModel_EnvironmentReference: """ - Test Class for DialogLogMessage + Test Class for EnvironmentReference """ - def test_dialog_log_message_serialization(self): + def test_environment_reference_serialization(self): """ - Test serialization/deserialization for DialogLogMessage + Test serialization/deserialization for EnvironmentReference """ - # Construct dict forms of any model objects needed in order to build this model. - - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' - - # Construct a json representation of a DialogLogMessage model - dialog_log_message_model_json = {} - dialog_log_message_model_json['level'] = 'info' - dialog_log_message_model_json['message'] = 'testString' - dialog_log_message_model_json['code'] = 'testString' - dialog_log_message_model_json['source'] = log_message_source_model + # Construct a json representation of a EnvironmentReference model + environment_reference_model_json = {} + environment_reference_model_json['name'] = 'testString' - # Construct a model instance of DialogLogMessage by calling from_dict on the json representation - dialog_log_message_model = DialogLogMessage.from_dict(dialog_log_message_model_json) - assert dialog_log_message_model != False + # Construct a model instance of EnvironmentReference by calling from_dict on the json representation + environment_reference_model = EnvironmentReference.from_dict(environment_reference_model_json) + assert environment_reference_model != False - # Construct a model instance of DialogLogMessage by calling from_dict on the json representation - dialog_log_message_model_dict = DialogLogMessage.from_dict(dialog_log_message_model_json).__dict__ - dialog_log_message_model2 = DialogLogMessage(**dialog_log_message_model_dict) + # Construct a model instance of EnvironmentReference by calling from_dict on the json representation + environment_reference_model_dict = EnvironmentReference.from_dict(environment_reference_model_json).__dict__ + environment_reference_model2 = EnvironmentReference(**environment_reference_model_dict) # Verify the model instances are equivalent - assert dialog_log_message_model == dialog_log_message_model2 + assert environment_reference_model == environment_reference_model2 # Convert model instance back to dict and verify no loss of data - dialog_log_message_model_json2 = dialog_log_message_model.to_dict() - assert dialog_log_message_model_json2 == dialog_log_message_model_json + environment_reference_model_json2 = environment_reference_model.to_dict() + assert environment_reference_model_json2 == environment_reference_model_json -class TestModel_DialogNodeAction: +class TestModel_EnvironmentSkill: """ - Test Class for DialogNodeAction + Test Class for EnvironmentSkill """ - def test_dialog_node_action_serialization(self): + def test_environment_skill_serialization(self): """ - Test serialization/deserialization for DialogNodeAction + Test serialization/deserialization for EnvironmentSkill """ - # Construct a json representation of a DialogNodeAction model - dialog_node_action_model_json = {} - dialog_node_action_model_json['name'] = 'testString' - dialog_node_action_model_json['type'] = 'client' - dialog_node_action_model_json['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model_json['result_variable'] = 'testString' - dialog_node_action_model_json['credentials'] = 'testString' + # Construct a json representation of a EnvironmentSkill model + environment_skill_model_json = {} + environment_skill_model_json['skill_id'] = 'testString' + environment_skill_model_json['type'] = 'dialog' + environment_skill_model_json['disabled'] = True + environment_skill_model_json['snapshot'] = 'testString' + environment_skill_model_json['skill_reference'] = 'testString' - # Construct a model instance of DialogNodeAction by calling from_dict on the json representation - dialog_node_action_model = DialogNodeAction.from_dict(dialog_node_action_model_json) - assert dialog_node_action_model != False + # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation + environment_skill_model = EnvironmentSkill.from_dict(environment_skill_model_json) + assert environment_skill_model != False - # Construct a model instance of DialogNodeAction by calling from_dict on the json representation - dialog_node_action_model_dict = DialogNodeAction.from_dict(dialog_node_action_model_json).__dict__ - dialog_node_action_model2 = DialogNodeAction(**dialog_node_action_model_dict) + # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation + environment_skill_model_dict = EnvironmentSkill.from_dict(environment_skill_model_json).__dict__ + environment_skill_model2 = EnvironmentSkill(**environment_skill_model_dict) # Verify the model instances are equivalent - assert dialog_node_action_model == dialog_node_action_model2 + assert environment_skill_model == environment_skill_model2 # Convert model instance back to dict and verify no loss of data - dialog_node_action_model_json2 = dialog_node_action_model.to_dict() - assert dialog_node_action_model_json2 == dialog_node_action_model_json + environment_skill_model_json2 = environment_skill_model.to_dict() + assert environment_skill_model_json2 == environment_skill_model_json -class TestModel_DialogNodeOutputConnectToAgentTransferInfo: +class TestModel_IntegrationReference: """ - Test Class for DialogNodeOutputConnectToAgentTransferInfo + Test Class for IntegrationReference """ - def test_dialog_node_output_connect_to_agent_transfer_info_serialization(self): + def test_integration_reference_serialization(self): """ - Test serialization/deserialization for DialogNodeOutputConnectToAgentTransferInfo + Test serialization/deserialization for IntegrationReference """ - # Construct a json representation of a DialogNodeOutputConnectToAgentTransferInfo model - dialog_node_output_connect_to_agent_transfer_info_model_json = {} - dialog_node_output_connect_to_agent_transfer_info_model_json['target'] = {'key1': {'anyKey': 'anyValue'}} + # Construct a json representation of a IntegrationReference model + integration_reference_model_json = {} + integration_reference_model_json['integration_id'] = 'testString' + integration_reference_model_json['type'] = 'testString' - # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation - dialog_node_output_connect_to_agent_transfer_info_model = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json) - assert dialog_node_output_connect_to_agent_transfer_info_model != False + # Construct a model instance of IntegrationReference by calling from_dict on the json representation + integration_reference_model = IntegrationReference.from_dict(integration_reference_model_json) + assert integration_reference_model != False - # Construct a model instance of DialogNodeOutputConnectToAgentTransferInfo by calling from_dict on the json representation - dialog_node_output_connect_to_agent_transfer_info_model_dict = DialogNodeOutputConnectToAgentTransferInfo.from_dict(dialog_node_output_connect_to_agent_transfer_info_model_json).__dict__ - dialog_node_output_connect_to_agent_transfer_info_model2 = DialogNodeOutputConnectToAgentTransferInfo(**dialog_node_output_connect_to_agent_transfer_info_model_dict) + # Construct a model instance of IntegrationReference by calling from_dict on the json representation + integration_reference_model_dict = IntegrationReference.from_dict(integration_reference_model_json).__dict__ + integration_reference_model2 = IntegrationReference(**integration_reference_model_dict) # Verify the model instances are equivalent - assert dialog_node_output_connect_to_agent_transfer_info_model == dialog_node_output_connect_to_agent_transfer_info_model2 + assert integration_reference_model == integration_reference_model2 # Convert model instance back to dict and verify no loss of data - dialog_node_output_connect_to_agent_transfer_info_model_json2 = dialog_node_output_connect_to_agent_transfer_info_model.to_dict() - assert dialog_node_output_connect_to_agent_transfer_info_model_json2 == dialog_node_output_connect_to_agent_transfer_info_model_json + integration_reference_model_json2 = integration_reference_model.to_dict() + assert integration_reference_model_json2 == integration_reference_model_json -class TestModel_DialogNodeOutputOptionsElement: +class TestModel_Log: """ - Test Class for DialogNodeOutputOptionsElement + Test Class for Log """ - def test_dialog_node_output_options_element_serialization(self): + def test_log_serialization(self): """ - Test serialization/deserialization for DialogNodeOutputOptionsElement + Test serialization/deserialization for Log """ # Construct dict forms of any model objects needed in order to build this model. @@ -4128,199 +6783,165 @@ def test_dialog_node_output_options_element_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model - - dialog_node_output_options_element_value_model = {} # DialogNodeOutputOptionsElementValue - dialog_node_output_options_element_value_model['input'] = message_input_model - - # Construct a json representation of a DialogNodeOutputOptionsElement model - dialog_node_output_options_element_model_json = {} - dialog_node_output_options_element_model_json['label'] = 'testString' - dialog_node_output_options_element_model_json['value'] = dialog_node_output_options_element_value_model - - # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation - dialog_node_output_options_element_model = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json) - assert dialog_node_output_options_element_model != False - - # Construct a model instance of DialogNodeOutputOptionsElement by calling from_dict on the json representation - dialog_node_output_options_element_model_dict = DialogNodeOutputOptionsElement.from_dict(dialog_node_output_options_element_model_json).__dict__ - dialog_node_output_options_element_model2 = DialogNodeOutputOptionsElement(**dialog_node_output_options_element_model_dict) - - # Verify the model instances are equivalent - assert dialog_node_output_options_element_model == dialog_node_output_options_element_model2 - - # Convert model instance back to dict and verify no loss of data - dialog_node_output_options_element_model_json2 = dialog_node_output_options_element_model.to_dict() - assert dialog_node_output_options_element_model_json2 == dialog_node_output_options_element_model_json - - -class TestModel_DialogNodeOutputOptionsElementValue: - """ - Test Class for DialogNodeOutputOptionsElementValue - """ - - def test_dialog_node_output_options_element_value_serialization(self): - """ - Test serialization/deserialization for DialogNodeOutputOptionsElementValue - """ + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'testString' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model - # Construct dict forms of any model objects needed in order to build this model. + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + log_request_model = {} # LogRequest + log_request_model['input'] = log_request_input_model + log_request_model['context'] = message_context_model + log_request_model['user_id'] = 'testString' - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['async_callout'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - # Construct a json representation of a DialogNodeOutputOptionsElementValue model - dialog_node_output_options_element_value_model_json = {} - dialog_node_output_options_element_value_model_json['input'] = message_input_model + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' - # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation - dialog_node_output_options_element_value_model = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json) - assert dialog_node_output_options_element_value_model != False + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model - # Construct a model instance of DialogNodeOutputOptionsElementValue by calling from_dict on the json representation - dialog_node_output_options_element_value_model_dict = DialogNodeOutputOptionsElementValue.from_dict(dialog_node_output_options_element_value_model_json).__dict__ - dialog_node_output_options_element_value_model2 = DialogNodeOutputOptionsElementValue(**dialog_node_output_options_element_value_model_dict) + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - # Verify the model instances are equivalent - assert dialog_node_output_options_element_value_model == dialog_node_output_options_element_value_model2 + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' - # Convert model instance back to dict and verify no loss of data - dialog_node_output_options_element_value_model_json2 = dialog_node_output_options_element_value_model.to_dict() - assert dialog_node_output_options_element_value_model_json2 == dialog_node_output_options_element_value_model_json + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' -class TestModel_DialogNodeVisited: - """ - Test Class for DialogNodeVisited - """ + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model - def test_dialog_node_visited_serialization(self): - """ - Test serialization/deserialization for DialogNodeVisited - """ + log_response_model = {} # LogResponse + log_response_model['output'] = log_response_output_model + log_response_model['context'] = message_context_model + log_response_model['user_id'] = 'testString' - # Construct a json representation of a DialogNodeVisited model - dialog_node_visited_model_json = {} - dialog_node_visited_model_json['dialog_node'] = 'testString' - dialog_node_visited_model_json['title'] = 'testString' - dialog_node_visited_model_json['conditions'] = 'testString' + # Construct a json representation of a Log model + log_model_json = {} + log_model_json['log_id'] = 'testString' + log_model_json['request'] = log_request_model + log_model_json['response'] = log_response_model + log_model_json['assistant_id'] = 'testString' + log_model_json['session_id'] = 'testString' + log_model_json['skill_id'] = 'testString' + log_model_json['snapshot'] = 'testString' + log_model_json['request_timestamp'] = 'testString' + log_model_json['response_timestamp'] = 'testString' + log_model_json['language'] = 'testString' + log_model_json['customer_id'] = 'testString' - # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation - dialog_node_visited_model = DialogNodeVisited.from_dict(dialog_node_visited_model_json) - assert dialog_node_visited_model != False + # Construct a model instance of Log by calling from_dict on the json representation + log_model = Log.from_dict(log_model_json) + assert log_model != False - # Construct a model instance of DialogNodeVisited by calling from_dict on the json representation - dialog_node_visited_model_dict = DialogNodeVisited.from_dict(dialog_node_visited_model_json).__dict__ - dialog_node_visited_model2 = DialogNodeVisited(**dialog_node_visited_model_dict) + # Construct a model instance of Log by calling from_dict on the json representation + log_model_dict = Log.from_dict(log_model_json).__dict__ + log_model2 = Log(**log_model_dict) # Verify the model instances are equivalent - assert dialog_node_visited_model == dialog_node_visited_model2 + assert log_model == log_model2 # Convert model instance back to dict and verify no loss of data - dialog_node_visited_model_json2 = dialog_node_visited_model.to_dict() - assert dialog_node_visited_model_json2 == dialog_node_visited_model_json + log_model_json2 = log_model.to_dict() + assert log_model_json2 == log_model_json -class TestModel_DialogSuggestion: +class TestModel_LogCollection: """ - Test Class for DialogSuggestion + Test Class for LogCollection """ - def test_dialog_suggestion_serialization(self): + def test_log_collection_serialization(self): """ - Test serialization/deserialization for DialogSuggestion + Test serialization/deserialization for LogCollection """ # Construct dict forms of any model objects needed in order to build this model. @@ -4402,49 +7023,206 @@ def test_dialog_suggestion_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'testString' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model - dialog_suggestion_value_model = {} # DialogSuggestionValue - dialog_suggestion_value_model['input'] = message_input_model + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a json representation of a DialogSuggestion model - dialog_suggestion_model_json = {} - dialog_suggestion_model_json['label'] = 'testString' - dialog_suggestion_model_json['value'] = dialog_suggestion_value_model - dialog_suggestion_model_json['output'] = {'anyKey': 'anyValue'} + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model - # Construct a model instance of DialogSuggestion by calling from_dict on the json representation - dialog_suggestion_model = DialogSuggestion.from_dict(dialog_suggestion_model_json) - assert dialog_suggestion_model != False + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - # Construct a model instance of DialogSuggestion by calling from_dict on the json representation - dialog_suggestion_model_dict = DialogSuggestion.from_dict(dialog_suggestion_model_json).__dict__ - dialog_suggestion_model2 = DialogSuggestion(**dialog_suggestion_model_dict) + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + log_request_model = {} # LogRequest + log_request_model['input'] = log_request_input_model + log_request_model['context'] = message_context_model + log_request_model['user_id'] = 'testString' + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model + + log_response_model = {} # LogResponse + log_response_model['output'] = log_response_output_model + log_response_model['context'] = message_context_model + log_response_model['user_id'] = 'testString' + + log_model = {} # Log + log_model['log_id'] = 'testString' + log_model['request'] = log_request_model + log_model['response'] = log_response_model + log_model['assistant_id'] = 'testString' + log_model['session_id'] = 'testString' + log_model['skill_id'] = 'testString' + log_model['snapshot'] = 'testString' + log_model['request_timestamp'] = 'testString' + log_model['response_timestamp'] = 'testString' + log_model['language'] = 'testString' + log_model['customer_id'] = 'testString' + + log_pagination_model = {} # LogPagination + log_pagination_model['next_url'] = 'testString' + log_pagination_model['matched'] = 38 + log_pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a LogCollection model + log_collection_model_json = {} + log_collection_model_json['logs'] = [log_model] + log_collection_model_json['pagination'] = log_pagination_model + + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model = LogCollection.from_dict(log_collection_model_json) + assert log_collection_model != False + + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model_dict = LogCollection.from_dict(log_collection_model_json).__dict__ + log_collection_model2 = LogCollection(**log_collection_model_dict) # Verify the model instances are equivalent - assert dialog_suggestion_model == dialog_suggestion_model2 + assert log_collection_model == log_collection_model2 # Convert model instance back to dict and verify no loss of data - dialog_suggestion_model_json2 = dialog_suggestion_model.to_dict() - assert dialog_suggestion_model_json2 == dialog_suggestion_model_json + log_collection_model_json2 = log_collection_model.to_dict() + assert log_collection_model_json2 == log_collection_model_json + + +class TestModel_LogPagination: + """ + Test Class for LogPagination + """ + + def test_log_pagination_serialization(self): + """ + Test serialization/deserialization for LogPagination + """ + + # Construct a json representation of a LogPagination model + log_pagination_model_json = {} + log_pagination_model_json['next_url'] = 'testString' + log_pagination_model_json['matched'] = 38 + log_pagination_model_json['next_cursor'] = 'testString' + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model = LogPagination.from_dict(log_pagination_model_json) + assert log_pagination_model != False + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model_dict = LogPagination.from_dict(log_pagination_model_json).__dict__ + log_pagination_model2 = LogPagination(**log_pagination_model_dict) + + # Verify the model instances are equivalent + assert log_pagination_model == log_pagination_model2 + + # Convert model instance back to dict and verify no loss of data + log_pagination_model_json2 = log_pagination_model.to_dict() + assert log_pagination_model_json2 == log_pagination_model_json -class TestModel_DialogSuggestionValue: +class TestModel_LogRequest: """ - Test Class for DialogSuggestionValue + Test Class for LogRequest """ - def test_dialog_suggestion_value_serialization(self): + def test_log_request_serialization(self): """ - Test serialization/deserialization for DialogSuggestionValue + Test serialization/deserialization for LogRequest """ # Construct dict forms of any model objects needed in order to build this model. @@ -4523,246 +7301,85 @@ def test_dialog_suggestion_value_serialization(self): message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False - - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model - - # Construct a json representation of a DialogSuggestionValue model - dialog_suggestion_value_model_json = {} - dialog_suggestion_value_model_json['input'] = message_input_model - - # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation - dialog_suggestion_value_model = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json) - assert dialog_suggestion_value_model != False - - # Construct a model instance of DialogSuggestionValue by calling from_dict on the json representation - dialog_suggestion_value_model_dict = DialogSuggestionValue.from_dict(dialog_suggestion_value_model_json).__dict__ - dialog_suggestion_value_model2 = DialogSuggestionValue(**dialog_suggestion_value_model_dict) - - # Verify the model instances are equivalent - assert dialog_suggestion_value_model == dialog_suggestion_value_model2 - - # Convert model instance back to dict and verify no loss of data - dialog_suggestion_value_model_json2 = dialog_suggestion_value_model.to_dict() - assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json - - -class TestModel_Environment: - """ - Test Class for Environment - """ - - def test_environment_serialization(self): - """ - Test serialization/deserialization for Environment - """ - - # Construct dict forms of any model objects needed in order to build this model. - - base_environment_orchestration_model = {} # BaseEnvironmentOrchestration - base_environment_orchestration_model['search_skill_fallback'] = True - - environment_skill_model = {} # EnvironmentSkill - environment_skill_model['skill_id'] = 'testString' - environment_skill_model['type'] = 'dialog' - environment_skill_model['disabled'] = True - environment_skill_model['snapshot'] = 'testString' - environment_skill_model['skill_reference'] = 'testString' - - # Construct a json representation of a Environment model - environment_model_json = {} - environment_model_json['name'] = 'testString' - environment_model_json['description'] = 'testString' - environment_model_json['orchestration'] = base_environment_orchestration_model - environment_model_json['session_timeout'] = 10 - environment_model_json['skill_references'] = [environment_skill_model] - - # Construct a model instance of Environment by calling from_dict on the json representation - environment_model = Environment.from_dict(environment_model_json) - assert environment_model != False - - # Construct a model instance of Environment by calling from_dict on the json representation - environment_model_dict = Environment.from_dict(environment_model_json).__dict__ - environment_model2 = Environment(**environment_model_dict) - - # Verify the model instances are equivalent - assert environment_model == environment_model2 - - # Convert model instance back to dict and verify no loss of data - environment_model_json2 = environment_model.to_dict() - assert environment_model_json2 == environment_model_json - - -class TestModel_EnvironmentCollection: - """ - Test Class for EnvironmentCollection - """ - - def test_environment_collection_serialization(self): - """ - Test serialization/deserialization for EnvironmentCollection - """ - - # Construct dict forms of any model objects needed in order to build this model. - - base_environment_orchestration_model = {} # BaseEnvironmentOrchestration - base_environment_orchestration_model['search_skill_fallback'] = True - - environment_skill_model = {} # EnvironmentSkill - environment_skill_model['skill_id'] = 'testString' - environment_skill_model['type'] = 'dialog' - environment_skill_model['disabled'] = True - environment_skill_model['snapshot'] = 'testString' - environment_skill_model['skill_reference'] = 'testString' - - environment_model = {} # Environment - environment_model['name'] = 'testString' - environment_model['description'] = 'testString' - environment_model['orchestration'] = base_environment_orchestration_model - environment_model['session_timeout'] = 10 - environment_model['skill_references'] = [environment_skill_model] - - pagination_model = {} # Pagination - pagination_model['refresh_url'] = 'testString' - pagination_model['next_url'] = 'testString' - pagination_model['total'] = 38 - pagination_model['matched'] = 38 - pagination_model['refresh_cursor'] = 'testString' - pagination_model['next_cursor'] = 'testString' - - # Construct a json representation of a EnvironmentCollection model - environment_collection_model_json = {} - environment_collection_model_json['environments'] = [environment_model] - environment_collection_model_json['pagination'] = pagination_model - - # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation - environment_collection_model = EnvironmentCollection.from_dict(environment_collection_model_json) - assert environment_collection_model != False - - # Construct a model instance of EnvironmentCollection by calling from_dict on the json representation - environment_collection_model_dict = EnvironmentCollection.from_dict(environment_collection_model_json).__dict__ - environment_collection_model2 = EnvironmentCollection(**environment_collection_model_dict) - - # Verify the model instances are equivalent - assert environment_collection_model == environment_collection_model2 - - # Convert model instance back to dict and verify no loss of data - environment_collection_model_json2 = environment_collection_model.to_dict() - assert environment_collection_model_json2 == environment_collection_model_json - - -class TestModel_EnvironmentReference: - """ - Test Class for EnvironmentReference - """ - - def test_environment_reference_serialization(self): - """ - Test serialization/deserialization for EnvironmentReference - """ - - # Construct a json representation of a EnvironmentReference model - environment_reference_model_json = {} - environment_reference_model_json['name'] = 'testString' - - # Construct a model instance of EnvironmentReference by calling from_dict on the json representation - environment_reference_model = EnvironmentReference.from_dict(environment_reference_model_json) - assert environment_reference_model != False - - # Construct a model instance of EnvironmentReference by calling from_dict on the json representation - environment_reference_model_dict = EnvironmentReference.from_dict(environment_reference_model_json).__dict__ - environment_reference_model2 = EnvironmentReference(**environment_reference_model_dict) - - # Verify the model instances are equivalent - assert environment_reference_model == environment_reference_model2 - - # Convert model instance back to dict and verify no loss of data - environment_reference_model_json2 = environment_reference_model.to_dict() - assert environment_reference_model_json2 == environment_reference_model_json - - -class TestModel_EnvironmentSkill: - """ - Test Class for EnvironmentSkill - """ - - def test_environment_skill_serialization(self): - """ - Test serialization/deserialization for EnvironmentSkill - """ - - # Construct a json representation of a EnvironmentSkill model - environment_skill_model_json = {} - environment_skill_model_json['skill_id'] = 'testString' - environment_skill_model_json['type'] = 'dialog' - environment_skill_model_json['disabled'] = True - environment_skill_model_json['snapshot'] = 'testString' - environment_skill_model_json['skill_reference'] = 'testString' + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True - # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation - environment_skill_model = EnvironmentSkill.from_dict(environment_skill_model_json) - assert environment_skill_model != False + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'Hello' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model - # Construct a model instance of EnvironmentSkill by calling from_dict on the json representation - environment_skill_model_dict = EnvironmentSkill.from_dict(environment_skill_model_json).__dict__ - environment_skill_model2 = EnvironmentSkill(**environment_skill_model_dict) + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'my_user_id' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Verify the model instances are equivalent - assert environment_skill_model == environment_skill_model2 + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model - # Convert model instance back to dict and verify no loss of data - environment_skill_model_json2 = environment_skill_model.to_dict() - assert environment_skill_model_json2 == environment_skill_model_json + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model -class TestModel_IntegrationReference: - """ - Test Class for IntegrationReference - """ + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - def test_integration_reference_serialization(self): - """ - Test serialization/deserialization for IntegrationReference - """ + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - # Construct a json representation of a IntegrationReference model - integration_reference_model_json = {} - integration_reference_model_json['integration_id'] = 'testString' - integration_reference_model_json['type'] = 'testString' + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} - # Construct a model instance of IntegrationReference by calling from_dict on the json representation - integration_reference_model = IntegrationReference.from_dict(integration_reference_model_json) - assert integration_reference_model != False + # Construct a json representation of a LogRequest model + log_request_model_json = {} + log_request_model_json['input'] = log_request_input_model + log_request_model_json['context'] = message_context_model + log_request_model_json['user_id'] = 'testString' - # Construct a model instance of IntegrationReference by calling from_dict on the json representation - integration_reference_model_dict = IntegrationReference.from_dict(integration_reference_model_json).__dict__ - integration_reference_model2 = IntegrationReference(**integration_reference_model_dict) + # Construct a model instance of LogRequest by calling from_dict on the json representation + log_request_model = LogRequest.from_dict(log_request_model_json) + assert log_request_model != False + + # Construct a model instance of LogRequest by calling from_dict on the json representation + log_request_model_dict = LogRequest.from_dict(log_request_model_json).__dict__ + log_request_model2 = LogRequest(**log_request_model_dict) # Verify the model instances are equivalent - assert integration_reference_model == integration_reference_model2 + assert log_request_model == log_request_model2 # Convert model instance back to dict and verify no loss of data - integration_reference_model_json2 = integration_reference_model.to_dict() - assert integration_reference_model_json2 == integration_reference_model_json + log_request_model_json2 = log_request_model.to_dict() + assert log_request_model_json2 == log_request_model_json -class TestModel_Log: +class TestModel_LogRequestInput: """ - Test Class for Log + Test Class for LogRequestInput """ - def test_log_serialization(self): + def test_log_request_input_serialization(self): """ - Test serialization/deserialization for Log + Test serialization/deserialization for LogRequestInput """ # Construct dict forms of any model objects needed in order to build this model. @@ -4844,15 +7461,164 @@ def test_log_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - log_request_input_model = {} # LogRequestInput - log_request_input_model['message_type'] = 'text' - log_request_input_model['text'] = 'testString' - log_request_input_model['intents'] = [runtime_intent_model] - log_request_input_model['entities'] = [runtime_entity_model] - log_request_input_model['suggestion_id'] = 'testString' - log_request_input_model['attachments'] = [message_input_attachment_model] - log_request_input_model['analytics'] = request_analytics_model - log_request_input_model['options'] = message_input_options_model + # Construct a json representation of a LogRequestInput model + log_request_input_model_json = {} + log_request_input_model_json['message_type'] = 'text' + log_request_input_model_json['text'] = 'testString' + log_request_input_model_json['intents'] = [runtime_intent_model] + log_request_input_model_json['entities'] = [runtime_entity_model] + log_request_input_model_json['suggestion_id'] = 'testString' + log_request_input_model_json['attachments'] = [message_input_attachment_model] + log_request_input_model_json['analytics'] = request_analytics_model + log_request_input_model_json['options'] = message_input_options_model + + # Construct a model instance of LogRequestInput by calling from_dict on the json representation + log_request_input_model = LogRequestInput.from_dict(log_request_input_model_json) + assert log_request_input_model != False + + # Construct a model instance of LogRequestInput by calling from_dict on the json representation + log_request_input_model_dict = LogRequestInput.from_dict(log_request_input_model_json).__dict__ + log_request_input_model2 = LogRequestInput(**log_request_input_model_dict) + + # Verify the model instances are equivalent + assert log_request_input_model == log_request_input_model2 + + # Convert model instance back to dict and verify no loss of data + log_request_input_model_json2 = log_request_input_model.to_dict() + assert log_request_input_model_json2 == log_request_input_model_json + + +class TestModel_LogResponse: + """ + Test Class for LogResponse + """ + + def test_log_response_serialization(self): + """ + Test serialization/deserialization for LogResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' @@ -4890,18 +7656,102 @@ def test_log_serialization(self): message_context_model['skills'] = message_context_skills_model message_context_model['integrations'] = {'anyKey': 'anyValue'} - log_request_model = {} # LogRequest - log_request_model['input'] = log_request_input_model - log_request_model['context'] = message_context_model - log_request_model['user_id'] = 'testString' + # Construct a json representation of a LogResponse model + log_response_model_json = {} + log_response_model_json['output'] = log_response_output_model + log_response_model_json['context'] = message_context_model + log_response_model_json['user_id'] = 'testString' + + # Construct a model instance of LogResponse by calling from_dict on the json representation + log_response_model = LogResponse.from_dict(log_response_model_json) + assert log_response_model != False + + # Construct a model instance of LogResponse by calling from_dict on the json representation + log_response_model_dict = LogResponse.from_dict(log_response_model_json).__dict__ + log_response_model2 = LogResponse(**log_response_model_dict) + + # Verify the model instances are equivalent + assert log_response_model == log_response_model2 + + # Convert model instance back to dict and verify no loss of data + log_response_model_json2 = log_response_model.to_dict() + assert log_response_model_json2 == log_response_model_json + + +class TestModel_LogResponseOutput: + """ + Test Class for LogResponseOutput + """ + + def test_log_response_output_serialization(self): + """ + Test serialization/deserialization for LogResponseOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText + runtime_response_generic_model['response_type'] = 'text' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['channels'] = [response_generic_channel_model] + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -4951,148 +7801,184 @@ def test_log_serialization(self): message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - log_response_output_model = {} # LogResponseOutput - log_response_output_model['generic'] = [runtime_response_generic_model] - log_response_output_model['intents'] = [runtime_intent_model] - log_response_output_model['entities'] = [runtime_entity_model] - log_response_output_model['actions'] = [dialog_node_action_model] - log_response_output_model['debug'] = message_output_debug_model - log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} - log_response_output_model['spelling'] = message_output_spelling_model + # Construct a json representation of a LogResponseOutput model + log_response_output_model_json = {} + log_response_output_model_json['generic'] = [runtime_response_generic_model] + log_response_output_model_json['intents'] = [runtime_intent_model] + log_response_output_model_json['entities'] = [runtime_entity_model] + log_response_output_model_json['actions'] = [dialog_node_action_model] + log_response_output_model_json['debug'] = message_output_debug_model + log_response_output_model_json['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model_json['spelling'] = message_output_spelling_model - log_response_model = {} # LogResponse - log_response_model['output'] = log_response_output_model - log_response_model['context'] = message_context_model - log_response_model['user_id'] = 'testString' + # Construct a model instance of LogResponseOutput by calling from_dict on the json representation + log_response_output_model = LogResponseOutput.from_dict(log_response_output_model_json) + assert log_response_output_model != False - # Construct a json representation of a Log model - log_model_json = {} - log_model_json['log_id'] = 'testString' - log_model_json['request'] = log_request_model - log_model_json['response'] = log_response_model - log_model_json['assistant_id'] = 'testString' - log_model_json['session_id'] = 'testString' - log_model_json['skill_id'] = 'testString' - log_model_json['snapshot'] = 'testString' - log_model_json['request_timestamp'] = 'testString' - log_model_json['response_timestamp'] = 'testString' - log_model_json['language'] = 'testString' - log_model_json['customer_id'] = 'testString' + # Construct a model instance of LogResponseOutput by calling from_dict on the json representation + log_response_output_model_dict = LogResponseOutput.from_dict(log_response_output_model_json).__dict__ + log_response_output_model2 = LogResponseOutput(**log_response_output_model_dict) - # Construct a model instance of Log by calling from_dict on the json representation - log_model = Log.from_dict(log_model_json) - assert log_model != False + # Verify the model instances are equivalent + assert log_response_output_model == log_response_output_model2 - # Construct a model instance of Log by calling from_dict on the json representation - log_model_dict = Log.from_dict(log_model_json).__dict__ - log_model2 = Log(**log_model_dict) + # Convert model instance back to dict and verify no loss of data + log_response_output_model_json2 = log_response_output_model.to_dict() + assert log_response_output_model_json2 == log_response_output_model_json + + +class TestModel_MessageContext: + """ + Test Class for MessageContext + """ + + def test_message_context_serialization(self): + """ + Test serialization/deserialization for MessageContext + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + # Construct a json representation of a MessageContext model + message_context_model_json = {} + message_context_model_json['global'] = message_context_global_model + message_context_model_json['skills'] = message_context_skills_model + message_context_model_json['integrations'] = {'anyKey': 'anyValue'} + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model = MessageContext.from_dict(message_context_model_json) + assert message_context_model != False + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ + message_context_model2 = MessageContext(**message_context_model_dict) # Verify the model instances are equivalent - assert log_model == log_model2 + assert message_context_model == message_context_model2 # Convert model instance back to dict and verify no loss of data - log_model_json2 = log_model.to_dict() - assert log_model_json2 == log_model_json + message_context_model_json2 = message_context_model.to_dict() + assert message_context_model_json2 == message_context_model_json -class TestModel_LogCollection: +class TestModel_MessageContextActionSkill: """ - Test Class for LogCollection + Test Class for MessageContextActionSkill """ - def test_log_collection_serialization(self): + def test_message_context_action_skill_serialization(self): """ - Test serialization/deserialization for LogCollection + Test serialization/deserialization for MessageContextActionSkill """ # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Construct a json representation of a MessageContextActionSkill model + message_context_action_skill_model_json = {} + message_context_action_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model_json['system'] = message_context_skill_system_model + message_context_action_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation + message_context_action_skill_model = MessageContextActionSkill.from_dict(message_context_action_skill_model_json) + assert message_context_action_skill_model != False - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation + message_context_action_skill_model_dict = MessageContextActionSkill.from_dict(message_context_action_skill_model_json).__dict__ + message_context_action_skill_model2 = MessageContextActionSkill(**message_context_action_skill_model_dict) + + # Verify the model instances are equivalent + assert message_context_action_skill_model == message_context_action_skill_model2 + + # Convert model instance back to dict and verify no loss of data + message_context_action_skill_model_json2 = message_context_action_skill_model.to_dict() + assert message_context_action_skill_model_json2 == message_context_action_skill_model_json + + +class TestModel_MessageContextDialogSkill: + """ + Test Class for MessageContextDialogSkill + """ + + def test_message_context_dialog_skill_serialization(self): + """ + Test serialization/deserialization for MessageContextDialogSkill + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + # Construct a json representation of a MessageContextDialogSkill model + message_context_dialog_skill_model_json = {} + message_context_dialog_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model_json['system'] = message_context_skill_system_model + + # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation + message_context_dialog_skill_model = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json) + assert message_context_dialog_skill_model != False - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation + message_context_dialog_skill_model_dict = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json).__dict__ + message_context_dialog_skill_model2 = MessageContextDialogSkill(**message_context_dialog_skill_model_dict) - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + # Verify the model instances are equivalent + assert message_context_dialog_skill_model == message_context_dialog_skill_model2 - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + # Convert model instance back to dict and verify no loss of data + message_context_dialog_skill_model_json2 = message_context_dialog_skill_model.to_dict() + assert message_context_dialog_skill_model_json2 == message_context_dialog_skill_model_json - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True +class TestModel_MessageContextGlobal: + """ + Test Class for MessageContextGlobal + """ - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['async_callout'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + def test_message_context_global_serialization(self): + """ + Test serialization/deserialization for MessageContextGlobal + """ - log_request_input_model = {} # LogRequestInput - log_request_input_model['message_type'] = 'text' - log_request_input_model['text'] = 'testString' - log_request_input_model['intents'] = [runtime_intent_model] - log_request_input_model['entities'] = [runtime_entity_model] - log_request_input_model['suggestion_id'] = 'testString' - log_request_input_model['attachments'] = [message_input_attachment_model] - log_request_input_model['analytics'] = request_analytics_model - log_request_input_model['options'] = message_input_options_model + # Construct dict forms of any model objects needed in order to build this model. message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' @@ -5104,186 +7990,159 @@ def test_log_collection_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + # Construct a json representation of a MessageContextGlobal model + message_context_global_model_json = {} + message_context_global_model_json['system'] = message_context_global_system_model - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) + assert message_context_global_model != False - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ + message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + # Verify the model instances are equivalent + assert message_context_global_model == message_context_global_model2 - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model + # Convert model instance back to dict and verify no loss of data + message_context_global_model_json2 = message_context_global_model.to_dict() + assert message_context_global_model_json2 == message_context_global_model_json - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} - log_request_model = {} # LogRequest - log_request_model['input'] = log_request_input_model - log_request_model['context'] = message_context_model - log_request_model['user_id'] = 'testString' +class TestModel_MessageContextGlobalSystem: + """ + Test Class for MessageContextGlobalSystem + """ - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + def test_message_context_global_system_serialization(self): + """ + Test serialization/deserialization for MessageContextGlobalSystem + """ - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + # Construct a json representation of a MessageContextGlobalSystem model + message_context_global_system_model_json = {} + message_context_global_system_model_json['timezone'] = 'testString' + message_context_global_system_model_json['user_id'] = 'testString' + message_context_global_system_model_json['turn_count'] = 38 + message_context_global_system_model_json['locale'] = 'en-us' + message_context_global_system_model_json['reference_time'] = 'testString' + message_context_global_system_model_json['session_start_time'] = 'testString' + message_context_global_system_model_json['state'] = 'testString' + message_context_global_system_model_json['skip_user_input'] = True - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) + assert message_context_global_system_model != False - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ + message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + # Verify the model instances are equivalent + assert message_context_global_system_model == message_context_global_system_model2 - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + # Convert model instance back to dict and verify no loss of data + message_context_global_system_model_json2 = message_context_global_system_model.to_dict() + assert message_context_global_system_model_json2 == message_context_global_system_model_json - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' +class TestModel_MessageContextSkillSystem: + """ + Test Class for MessageContextSkillSystem + """ - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + def test_message_context_skill_system_serialization(self): + """ + Test serialization/deserialization for MessageContextSkillSystem + """ - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' + # Construct a json representation of a MessageContextSkillSystem model + message_context_skill_system_model_json = {} + message_context_skill_system_model_json['state'] = 'testString' + message_context_skill_system_model_json['foo'] = 'testString' - log_response_output_model = {} # LogResponseOutput - log_response_output_model['generic'] = [runtime_response_generic_model] - log_response_output_model['intents'] = [runtime_intent_model] - log_response_output_model['entities'] = [runtime_entity_model] - log_response_output_model['actions'] = [dialog_node_action_model] - log_response_output_model['debug'] = message_output_debug_model - log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} - log_response_output_model['spelling'] = message_output_spelling_model + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) + assert message_context_skill_system_model != False - log_response_model = {} # LogResponse - log_response_model['output'] = log_response_output_model - log_response_model['context'] = message_context_model - log_response_model['user_id'] = 'testString' + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ + message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) - log_model = {} # Log - log_model['log_id'] = 'testString' - log_model['request'] = log_request_model - log_model['response'] = log_response_model - log_model['assistant_id'] = 'testString' - log_model['session_id'] = 'testString' - log_model['skill_id'] = 'testString' - log_model['snapshot'] = 'testString' - log_model['request_timestamp'] = 'testString' - log_model['response_timestamp'] = 'testString' - log_model['language'] = 'testString' - log_model['customer_id'] = 'testString' + # Verify the model instances are equivalent + assert message_context_skill_system_model == message_context_skill_system_model2 - log_pagination_model = {} # LogPagination - log_pagination_model['next_url'] = 'testString' - log_pagination_model['matched'] = 38 - log_pagination_model['next_cursor'] = 'testString' + # Convert model instance back to dict and verify no loss of data + message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() + assert message_context_skill_system_model_json2 == message_context_skill_system_model_json - # Construct a json representation of a LogCollection model - log_collection_model_json = {} - log_collection_model_json['logs'] = [log_model] - log_collection_model_json['pagination'] = log_pagination_model + # Test get_properties and set_properties methods. + message_context_skill_system_model.set_properties({}) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict == {} - # Construct a model instance of LogCollection by calling from_dict on the json representation - log_collection_model = LogCollection.from_dict(log_collection_model_json) - assert log_collection_model != False + expected_dict = {'foo': 'testString'} + message_context_skill_system_model.set_properties(expected_dict) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict.keys() == expected_dict.keys() - # Construct a model instance of LogCollection by calling from_dict on the json representation - log_collection_model_dict = LogCollection.from_dict(log_collection_model_json).__dict__ - log_collection_model2 = LogCollection(**log_collection_model_dict) - # Verify the model instances are equivalent - assert log_collection_model == log_collection_model2 +class TestModel_MessageContextSkills: + """ + Test Class for MessageContextSkills + """ - # Convert model instance back to dict and verify no loss of data - log_collection_model_json2 = log_collection_model.to_dict() - assert log_collection_model_json2 == log_collection_model_json + def test_message_context_skills_serialization(self): + """ + Test serialization/deserialization for MessageContextSkills + """ + + # Construct dict forms of any model objects needed in order to build this model. + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' -class TestModel_LogPagination: - """ - Test Class for LogPagination - """ + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - def test_log_pagination_serialization(self): - """ - Test serialization/deserialization for LogPagination - """ + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - # Construct a json representation of a LogPagination model - log_pagination_model_json = {} - log_pagination_model_json['next_url'] = 'testString' - log_pagination_model_json['matched'] = 38 - log_pagination_model_json['next_cursor'] = 'testString' + # Construct a json representation of a MessageContextSkills model + message_context_skills_model_json = {} + message_context_skills_model_json['main skill'] = message_context_dialog_skill_model + message_context_skills_model_json['actions skill'] = message_context_action_skill_model - # Construct a model instance of LogPagination by calling from_dict on the json representation - log_pagination_model = LogPagination.from_dict(log_pagination_model_json) - assert log_pagination_model != False + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) + assert message_context_skills_model != False - # Construct a model instance of LogPagination by calling from_dict on the json representation - log_pagination_model_dict = LogPagination.from_dict(log_pagination_model_json).__dict__ - log_pagination_model2 = LogPagination(**log_pagination_model_dict) + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ + message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) # Verify the model instances are equivalent - assert log_pagination_model == log_pagination_model2 + assert message_context_skills_model == message_context_skills_model2 # Convert model instance back to dict and verify no loss of data - log_pagination_model_json2 = log_pagination_model.to_dict() - assert log_pagination_model_json2 == log_pagination_model_json + message_context_skills_model_json2 = message_context_skills_model.to_dict() + assert message_context_skills_model_json2 == message_context_skills_model_json -class TestModel_LogRequest: +class TestModel_MessageInput: """ - Test Class for LogRequest + Test Class for MessageInput """ - def test_log_request_serialization(self): + def test_message_input_serialization(self): """ - Test serialization/deserialization for LogRequest + Test serialization/deserialization for MessageInput """ # Construct dict forms of any model objects needed in order to build this model. @@ -5362,201 +8221,148 @@ def test_log_request_serialization(self): message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False - log_request_input_model = {} # LogRequestInput - log_request_input_model['message_type'] = 'text' - log_request_input_model['text'] = 'Hello' - log_request_input_model['intents'] = [runtime_intent_model] - log_request_input_model['entities'] = [runtime_entity_model] - log_request_input_model['suggestion_id'] = 'testString' - log_request_input_model['attachments'] = [message_input_attachment_model] - log_request_input_model['analytics'] = request_analytics_model - log_request_input_model['options'] = message_input_options_model + # Construct a json representation of a MessageInput model + message_input_model_json = {} + message_input_model_json['message_type'] = 'text' + message_input_model_json['text'] = 'testString' + message_input_model_json['intents'] = [runtime_intent_model] + message_input_model_json['entities'] = [runtime_entity_model] + message_input_model_json['suggestion_id'] = 'testString' + message_input_model_json['attachments'] = [message_input_attachment_model] + message_input_model_json['analytics'] = request_analytics_model + message_input_model_json['options'] = message_input_options_model - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'my_user_id' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model = MessageInput.from_dict(message_input_model_json) + assert message_input_model != False - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ + message_input_model2 = MessageInput(**message_input_model_dict) - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Verify the model instances are equivalent + assert message_input_model == message_input_model2 - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Convert model instance back to dict and verify no loss of data + message_input_model_json2 = message_input_model.to_dict() + assert message_input_model_json2 == message_input_model_json - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model +class TestModel_MessageInputAttachment: + """ + Test Class for MessageInputAttachment + """ - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} + def test_message_input_attachment_serialization(self): + """ + Test serialization/deserialization for MessageInputAttachment + """ - # Construct a json representation of a LogRequest model - log_request_model_json = {} - log_request_model_json['input'] = log_request_input_model - log_request_model_json['context'] = message_context_model - log_request_model_json['user_id'] = 'testString' + # Construct a json representation of a MessageInputAttachment model + message_input_attachment_model_json = {} + message_input_attachment_model_json['url'] = 'testString' + message_input_attachment_model_json['media_type'] = 'testString' - # Construct a model instance of LogRequest by calling from_dict on the json representation - log_request_model = LogRequest.from_dict(log_request_model_json) - assert log_request_model != False + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) + assert message_input_attachment_model != False - # Construct a model instance of LogRequest by calling from_dict on the json representation - log_request_model_dict = LogRequest.from_dict(log_request_model_json).__dict__ - log_request_model2 = LogRequest(**log_request_model_dict) + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ + message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) # Verify the model instances are equivalent - assert log_request_model == log_request_model2 + assert message_input_attachment_model == message_input_attachment_model2 # Convert model instance back to dict and verify no loss of data - log_request_model_json2 = log_request_model.to_dict() - assert log_request_model_json2 == log_request_model_json + message_input_attachment_model_json2 = message_input_attachment_model.to_dict() + assert message_input_attachment_model_json2 == message_input_attachment_model_json -class TestModel_LogRequestInput: +class TestModel_MessageInputOptions: """ - Test Class for LogRequestInput + Test Class for MessageInputOptions """ - def test_log_request_input_serialization(self): + def test_message_input_options_serialization(self): """ - Test serialization/deserialization for LogRequestInput + Test serialization/deserialization for MessageInputOptions """ # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Construct a json representation of a MessageInputOptions model + message_input_options_model_json = {} + message_input_options_model_json['restart'] = False + message_input_options_model_json['alternate_intents'] = False + message_input_options_model_json['async_callout'] = False + message_input_options_model_json['spelling'] = message_input_options_spelling_model + message_input_options_model_json['debug'] = False + message_input_options_model_json['return_context'] = False + message_input_options_model_json['export'] = False - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) + assert message_input_options_model != False - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ + message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + # Verify the model instances are equivalent + assert message_input_options_model == message_input_options_model2 - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + # Convert model instance back to dict and verify no loss of data + message_input_options_model_json2 = message_input_options_model.to_dict() + assert message_input_options_model_json2 == message_input_options_model_json - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True +class TestModel_MessageInputOptionsSpelling: + """ + Test Class for MessageInputOptionsSpelling + """ - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['async_callout'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + def test_message_input_options_spelling_serialization(self): + """ + Test serialization/deserialization for MessageInputOptionsSpelling + """ - # Construct a json representation of a LogRequestInput model - log_request_input_model_json = {} - log_request_input_model_json['message_type'] = 'text' - log_request_input_model_json['text'] = 'testString' - log_request_input_model_json['intents'] = [runtime_intent_model] - log_request_input_model_json['entities'] = [runtime_entity_model] - log_request_input_model_json['suggestion_id'] = 'testString' - log_request_input_model_json['attachments'] = [message_input_attachment_model] - log_request_input_model_json['analytics'] = request_analytics_model - log_request_input_model_json['options'] = message_input_options_model + # Construct a json representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model_json = {} + message_input_options_spelling_model_json['suggestions'] = True + message_input_options_spelling_model_json['auto_correct'] = True - # Construct a model instance of LogRequestInput by calling from_dict on the json representation - log_request_input_model = LogRequestInput.from_dict(log_request_input_model_json) - assert log_request_input_model != False + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) + assert message_input_options_spelling_model != False - # Construct a model instance of LogRequestInput by calling from_dict on the json representation - log_request_input_model_dict = LogRequestInput.from_dict(log_request_input_model_json).__dict__ - log_request_input_model2 = LogRequestInput(**log_request_input_model_dict) + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ + message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) # Verify the model instances are equivalent - assert log_request_input_model == log_request_input_model2 + assert message_input_options_spelling_model == message_input_options_spelling_model2 # Convert model instance back to dict and verify no loss of data - log_request_input_model_json2 = log_request_input_model.to_dict() - assert log_request_input_model_json2 == log_request_input_model_json + message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() + assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json -class TestModel_LogResponse: +class TestModel_MessageOutput: """ - Test Class for LogResponse + Test Class for MessageOutput """ - def test_log_response_serialization(self): + def test_message_output_serialization(self): """ - Test serialization/deserialization for LogResponse + Test serialization/deserialization for MessageOutput """ # Construct dict forms of any model objects needed in order to build this model. @@ -5672,1029 +8478,1053 @@ def test_log_response_serialization(self): message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - log_response_output_model = {} # LogResponseOutput - log_response_output_model['generic'] = [runtime_response_generic_model] - log_response_output_model['intents'] = [runtime_intent_model] - log_response_output_model['entities'] = [runtime_entity_model] - log_response_output_model['actions'] = [dialog_node_action_model] - log_response_output_model['debug'] = message_output_debug_model - log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} - log_response_output_model['spelling'] = message_output_spelling_model + # Construct a json representation of a MessageOutput model + message_output_model_json = {} + message_output_model_json['generic'] = [runtime_response_generic_model] + message_output_model_json['intents'] = [runtime_intent_model] + message_output_model_json['entities'] = [runtime_entity_model] + message_output_model_json['actions'] = [dialog_node_action_model] + message_output_model_json['debug'] = message_output_debug_model + message_output_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_output_model_json['spelling'] = message_output_spelling_model - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model = MessageOutput.from_dict(message_output_model_json) + assert message_output_model != False - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model_dict = MessageOutput.from_dict(message_output_model_json).__dict__ + message_output_model2 = MessageOutput(**message_output_model_dict) - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Verify the model instances are equivalent + assert message_output_model == message_output_model2 - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Convert model instance back to dict and verify no loss of data + message_output_model_json2 = message_output_model.to_dict() + assert message_output_model_json2 == message_output_model_json - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model +class TestModel_MessageOutputDebug: + """ + Test Class for MessageOutputDebug + """ - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} + def test_message_output_debug_serialization(self): + """ + Test serialization/deserialization for MessageOutputDebug + """ - # Construct a json representation of a LogResponse model - log_response_model_json = {} - log_response_model_json['output'] = log_response_output_model - log_response_model_json['context'] = message_context_model - log_response_model_json['user_id'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of LogResponse by calling from_dict on the json representation - log_response_model = LogResponse.from_dict(log_response_model_json) - assert log_response_model != False + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - # Construct a model instance of LogResponse by calling from_dict on the json representation - log_response_model_dict = LogResponse.from_dict(log_response_model_json).__dict__ - log_response_model2 = LogResponse(**log_response_model_dict) + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + # Construct a json representation of a MessageOutputDebug model + message_output_debug_model_json = {} + message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model_json['log_messages'] = [dialog_log_message_model] + message_output_debug_model_json['branch_exited'] = True + message_output_debug_model_json['branch_exited_reason'] = 'completed' + message_output_debug_model_json['turn_events'] = [message_output_debug_turn_event_model] + + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) + assert message_output_debug_model != False + + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model_dict = MessageOutputDebug.from_dict(message_output_debug_model_json).__dict__ + message_output_debug_model2 = MessageOutputDebug(**message_output_debug_model_dict) # Verify the model instances are equivalent - assert log_response_model == log_response_model2 + assert message_output_debug_model == message_output_debug_model2 # Convert model instance back to dict and verify no loss of data - log_response_model_json2 = log_response_model.to_dict() - assert log_response_model_json2 == log_response_model_json + message_output_debug_model_json2 = message_output_debug_model.to_dict() + assert message_output_debug_model_json2 == message_output_debug_model_json -class TestModel_LogResponseOutput: +class TestModel_MessageOutputSpelling: """ - Test Class for LogResponseOutput + Test Class for MessageOutputSpelling """ - def test_log_response_output_serialization(self): + def test_message_output_spelling_serialization(self): """ - Test serialization/deserialization for LogResponseOutput + Test serialization/deserialization for MessageOutputSpelling """ - # Construct dict forms of any model objects needed in order to build this model. - - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + # Construct a json representation of a MessageOutputSpelling model + message_output_spelling_model_json = {} + message_output_spelling_model_json['text'] = 'testString' + message_output_spelling_model_json['original_text'] = 'testString' + message_output_spelling_model_json['suggested_text'] = 'testString' - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model = MessageOutputSpelling.from_dict(message_output_spelling_model_json) + assert message_output_spelling_model != False - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model_dict = MessageOutputSpelling.from_dict(message_output_spelling_model_json).__dict__ + message_output_spelling_model2 = MessageOutputSpelling(**message_output_spelling_model_dict) - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Verify the model instances are equivalent + assert message_output_spelling_model == message_output_spelling_model2 - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Convert model instance back to dict and verify no loss of data + message_output_spelling_model_json2 = message_output_spelling_model.to_dict() + assert message_output_spelling_model_json2 == message_output_spelling_model_json - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' +class TestModel_Metadata: + """ + Test Class for Metadata + """ - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' + def test_metadata_serialization(self): + """ + Test serialization/deserialization for Metadata + """ - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + # Construct a json representation of a Metadata model + metadata_model_json = {} + metadata_model_json['id'] = 38 - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + # Construct a model instance of Metadata by calling from_dict on the json representation + metadata_model = Metadata.from_dict(metadata_model_json) + assert metadata_model != False - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + # Construct a model instance of Metadata by calling from_dict on the json representation + metadata_model_dict = Metadata.from_dict(metadata_model_json).__dict__ + metadata_model2 = Metadata(**metadata_model_dict) - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' + # Verify the model instances are equivalent + assert metadata_model == metadata_model2 - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' + # Convert model instance back to dict and verify no loss of data + metadata_model_json2 = metadata_model.to_dict() + assert metadata_model_json2 == metadata_model_json - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' +class TestModel_MonitorAssistantReleaseImportArtifactResponse: + """ + Test Class for MonitorAssistantReleaseImportArtifactResponse + """ - # Construct a json representation of a LogResponseOutput model - log_response_output_model_json = {} - log_response_output_model_json['generic'] = [runtime_response_generic_model] - log_response_output_model_json['intents'] = [runtime_intent_model] - log_response_output_model_json['entities'] = [runtime_entity_model] - log_response_output_model_json['actions'] = [dialog_node_action_model] - log_response_output_model_json['debug'] = message_output_debug_model - log_response_output_model_json['user_defined'] = {'anyKey': 'anyValue'} - log_response_output_model_json['spelling'] = message_output_spelling_model + def test_monitor_assistant_release_import_artifact_response_serialization(self): + """ + Test serialization/deserialization for MonitorAssistantReleaseImportArtifactResponse + """ - # Construct a model instance of LogResponseOutput by calling from_dict on the json representation - log_response_output_model = LogResponseOutput.from_dict(log_response_output_model_json) - assert log_response_output_model != False + # Construct a json representation of a MonitorAssistantReleaseImportArtifactResponse model + monitor_assistant_release_import_artifact_response_model_json = {} + monitor_assistant_release_import_artifact_response_model_json['skill_impact_in_draft'] = ['action'] - # Construct a model instance of LogResponseOutput by calling from_dict on the json representation - log_response_output_model_dict = LogResponseOutput.from_dict(log_response_output_model_json).__dict__ - log_response_output_model2 = LogResponseOutput(**log_response_output_model_dict) + # Construct a model instance of MonitorAssistantReleaseImportArtifactResponse by calling from_dict on the json representation + monitor_assistant_release_import_artifact_response_model = MonitorAssistantReleaseImportArtifactResponse.from_dict(monitor_assistant_release_import_artifact_response_model_json) + assert monitor_assistant_release_import_artifact_response_model != False + + # Construct a model instance of MonitorAssistantReleaseImportArtifactResponse by calling from_dict on the json representation + monitor_assistant_release_import_artifact_response_model_dict = MonitorAssistantReleaseImportArtifactResponse.from_dict(monitor_assistant_release_import_artifact_response_model_json).__dict__ + monitor_assistant_release_import_artifact_response_model2 = MonitorAssistantReleaseImportArtifactResponse(**monitor_assistant_release_import_artifact_response_model_dict) # Verify the model instances are equivalent - assert log_response_output_model == log_response_output_model2 + assert monitor_assistant_release_import_artifact_response_model == monitor_assistant_release_import_artifact_response_model2 # Convert model instance back to dict and verify no loss of data - log_response_output_model_json2 = log_response_output_model.to_dict() - assert log_response_output_model_json2 == log_response_output_model_json + monitor_assistant_release_import_artifact_response_model_json2 = monitor_assistant_release_import_artifact_response_model.to_dict() + assert monitor_assistant_release_import_artifact_response_model_json2 == monitor_assistant_release_import_artifact_response_model_json -class TestModel_MessageContext: +class TestModel_Pagination: """ - Test Class for MessageContext + Test Class for Pagination """ - def test_message_context_serialization(self): + def test_pagination_serialization(self): """ - Test serialization/deserialization for MessageContext + Test serialization/deserialization for Pagination """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a Pagination model + pagination_model_json = {} + pagination_model_json['refresh_url'] = 'testString' + pagination_model_json['next_url'] = 'testString' + pagination_model_json['total'] = 38 + pagination_model_json['matched'] = 38 + pagination_model_json['refresh_cursor'] = 'testString' + pagination_model_json['next_cursor'] = 'testString' - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model = Pagination.from_dict(pagination_model_json) + assert pagination_model != False - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ + pagination_model2 = Pagination(**pagination_model_dict) - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Verify the model instances are equivalent + assert pagination_model == pagination_model2 - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Convert model instance back to dict and verify no loss of data + pagination_model_json2 = pagination_model.to_dict() + assert pagination_model_json2 == pagination_model_json - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model +class TestModel_ProviderAuthenticationOAuth2: + """ + Test Class for ProviderAuthenticationOAuth2 + """ - # Construct a json representation of a MessageContext model - message_context_model_json = {} - message_context_model_json['global'] = message_context_global_model - message_context_model_json['skills'] = message_context_skills_model - message_context_model_json['integrations'] = {'anyKey': 'anyValue'} + def test_provider_authentication_o_auth2_serialization(self): + """ + Test serialization/deserialization for ProviderAuthenticationOAuth2 + """ - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model = MessageContext.from_dict(message_context_model_json) - assert message_context_model != False + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ - message_context_model2 = MessageContext(**message_context_model_dict) + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a json representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model_json = {} + provider_authentication_o_auth2_model_json['preferred_flow'] = 'password' + provider_authentication_o_auth2_model_json['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a model instance of ProviderAuthenticationOAuth2 by calling from_dict on the json representation + provider_authentication_o_auth2_model = ProviderAuthenticationOAuth2.from_dict(provider_authentication_o_auth2_model_json) + assert provider_authentication_o_auth2_model != False + + # Construct a model instance of ProviderAuthenticationOAuth2 by calling from_dict on the json representation + provider_authentication_o_auth2_model_dict = ProviderAuthenticationOAuth2.from_dict(provider_authentication_o_auth2_model_json).__dict__ + provider_authentication_o_auth2_model2 = ProviderAuthenticationOAuth2(**provider_authentication_o_auth2_model_dict) # Verify the model instances are equivalent - assert message_context_model == message_context_model2 + assert provider_authentication_o_auth2_model == provider_authentication_o_auth2_model2 # Convert model instance back to dict and verify no loss of data - message_context_model_json2 = message_context_model.to_dict() - assert message_context_model_json2 == message_context_model_json + provider_authentication_o_auth2_model_json2 = provider_authentication_o_auth2_model.to_dict() + assert provider_authentication_o_auth2_model_json2 == provider_authentication_o_auth2_model_json -class TestModel_MessageContextActionSkill: +class TestModel_ProviderAuthenticationOAuth2PasswordUsername: """ - Test Class for MessageContextActionSkill + Test Class for ProviderAuthenticationOAuth2PasswordUsername """ - def test_message_context_action_skill_serialization(self): + def test_provider_authentication_o_auth2_password_username_serialization(self): """ - Test serialization/deserialization for MessageContextActionSkill + Test serialization/deserialization for ProviderAuthenticationOAuth2PasswordUsername """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model_json = {} + provider_authentication_o_auth2_password_username_model_json['type'] = 'value' + provider_authentication_o_auth2_password_username_model_json['value'] = 'testString' - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Construct a model instance of ProviderAuthenticationOAuth2PasswordUsername by calling from_dict on the json representation + provider_authentication_o_auth2_password_username_model = ProviderAuthenticationOAuth2PasswordUsername.from_dict(provider_authentication_o_auth2_password_username_model_json) + assert provider_authentication_o_auth2_password_username_model != False - # Construct a json representation of a MessageContextActionSkill model - message_context_action_skill_model_json = {} - message_context_action_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model_json['system'] = message_context_skill_system_model - message_context_action_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} + # Construct a model instance of ProviderAuthenticationOAuth2PasswordUsername by calling from_dict on the json representation + provider_authentication_o_auth2_password_username_model_dict = ProviderAuthenticationOAuth2PasswordUsername.from_dict(provider_authentication_o_auth2_password_username_model_json).__dict__ + provider_authentication_o_auth2_password_username_model2 = ProviderAuthenticationOAuth2PasswordUsername(**provider_authentication_o_auth2_password_username_model_dict) - # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation - message_context_action_skill_model = MessageContextActionSkill.from_dict(message_context_action_skill_model_json) - assert message_context_action_skill_model != False + # Verify the model instances are equivalent + assert provider_authentication_o_auth2_password_username_model == provider_authentication_o_auth2_password_username_model2 + + # Convert model instance back to dict and verify no loss of data + provider_authentication_o_auth2_password_username_model_json2 = provider_authentication_o_auth2_password_username_model.to_dict() + assert provider_authentication_o_auth2_password_username_model_json2 == provider_authentication_o_auth2_password_username_model_json - # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation - message_context_action_skill_model_dict = MessageContextActionSkill.from_dict(message_context_action_skill_model_json).__dict__ - message_context_action_skill_model2 = MessageContextActionSkill(**message_context_action_skill_model_dict) + +class TestModel_ProviderAuthenticationTypeAndValue: + """ + Test Class for ProviderAuthenticationTypeAndValue + """ + + def test_provider_authentication_type_and_value_serialization(self): + """ + Test serialization/deserialization for ProviderAuthenticationTypeAndValue + """ + + # Construct a json representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model_json = {} + provider_authentication_type_and_value_model_json['type'] = 'value' + provider_authentication_type_and_value_model_json['value'] = 'testString' + + # Construct a model instance of ProviderAuthenticationTypeAndValue by calling from_dict on the json representation + provider_authentication_type_and_value_model = ProviderAuthenticationTypeAndValue.from_dict(provider_authentication_type_and_value_model_json) + assert provider_authentication_type_and_value_model != False + + # Construct a model instance of ProviderAuthenticationTypeAndValue by calling from_dict on the json representation + provider_authentication_type_and_value_model_dict = ProviderAuthenticationTypeAndValue.from_dict(provider_authentication_type_and_value_model_json).__dict__ + provider_authentication_type_and_value_model2 = ProviderAuthenticationTypeAndValue(**provider_authentication_type_and_value_model_dict) # Verify the model instances are equivalent - assert message_context_action_skill_model == message_context_action_skill_model2 + assert provider_authentication_type_and_value_model == provider_authentication_type_and_value_model2 # Convert model instance back to dict and verify no loss of data - message_context_action_skill_model_json2 = message_context_action_skill_model.to_dict() - assert message_context_action_skill_model_json2 == message_context_action_skill_model_json + provider_authentication_type_and_value_model_json2 = provider_authentication_type_and_value_model.to_dict() + assert provider_authentication_type_and_value_model_json2 == provider_authentication_type_and_value_model_json -class TestModel_MessageContextDialogSkill: +class TestModel_ProviderCollection: """ - Test Class for MessageContextDialogSkill + Test Class for ProviderCollection """ - def test_message_context_dialog_skill_serialization(self): + def test_provider_collection_serialization(self): """ - Test serialization/deserialization for MessageContextDialogSkill + Test serialization/deserialization for ProviderCollection """ # Construct dict forms of any model objects needed in order to build this model. - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem + provider_response_specification_servers_item_model['url'] = 'testString' - # Construct a json representation of a MessageContextDialogSkill model - message_context_dialog_skill_model_json = {} - message_context_dialog_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model_json['system'] = message_context_skill_system_model + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation - message_context_dialog_skill_model = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json) - assert message_context_dialog_skill_model != False + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation - message_context_dialog_skill_model_dict = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json).__dict__ - message_context_dialog_skill_model2 = MessageContextDialogSkill(**message_context_dialog_skill_model_dict) + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents + provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model + + provider_response_specification_model = {} # ProviderResponseSpecification + provider_response_specification_model['servers'] = [provider_response_specification_servers_item_model] + provider_response_specification_model['components'] = provider_response_specification_components_model + + provider_response_model = {} # ProviderResponse + provider_response_model['provider_id'] = 'testString' + provider_response_model['specification'] = provider_response_specification_model + + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a ProviderCollection model + provider_collection_model_json = {} + provider_collection_model_json['conversational_skill_providers'] = [provider_response_model] + provider_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of ProviderCollection by calling from_dict on the json representation + provider_collection_model = ProviderCollection.from_dict(provider_collection_model_json) + assert provider_collection_model != False + + # Construct a model instance of ProviderCollection by calling from_dict on the json representation + provider_collection_model_dict = ProviderCollection.from_dict(provider_collection_model_json).__dict__ + provider_collection_model2 = ProviderCollection(**provider_collection_model_dict) # Verify the model instances are equivalent - assert message_context_dialog_skill_model == message_context_dialog_skill_model2 + assert provider_collection_model == provider_collection_model2 # Convert model instance back to dict and verify no loss of data - message_context_dialog_skill_model_json2 = message_context_dialog_skill_model.to_dict() - assert message_context_dialog_skill_model_json2 == message_context_dialog_skill_model_json + provider_collection_model_json2 = provider_collection_model.to_dict() + assert provider_collection_model_json2 == provider_collection_model_json -class TestModel_MessageContextGlobal: +class TestModel_ProviderPrivate: """ - Test Class for MessageContextGlobal + Test Class for ProviderPrivate """ - def test_message_context_global_serialization(self): + def test_provider_private_serialization(self): """ - Test serialization/deserialization for MessageContextGlobal + Test serialization/deserialization for ProviderPrivate """ # Construct dict forms of any model objects needed in order to build this model. - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a json representation of a MessageContextGlobal model - message_context_global_model_json = {} - message_context_global_model_json['system'] = message_context_global_system_model + provider_private_authentication_model = {} # ProviderPrivateAuthenticationBearerFlow + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) - assert message_context_global_model != False + # Construct a json representation of a ProviderPrivate model + provider_private_model_json = {} + provider_private_model_json['authentication'] = provider_private_authentication_model - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ - message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) + # Construct a model instance of ProviderPrivate by calling from_dict on the json representation + provider_private_model = ProviderPrivate.from_dict(provider_private_model_json) + assert provider_private_model != False + + # Construct a model instance of ProviderPrivate by calling from_dict on the json representation + provider_private_model_dict = ProviderPrivate.from_dict(provider_private_model_json).__dict__ + provider_private_model2 = ProviderPrivate(**provider_private_model_dict) # Verify the model instances are equivalent - assert message_context_global_model == message_context_global_model2 + assert provider_private_model == provider_private_model2 # Convert model instance back to dict and verify no loss of data - message_context_global_model_json2 = message_context_global_model.to_dict() - assert message_context_global_model_json2 == message_context_global_model_json + provider_private_model_json2 = provider_private_model.to_dict() + assert provider_private_model_json2 == provider_private_model_json -class TestModel_MessageContextGlobalSystem: +class TestModel_ProviderPrivateAuthenticationOAuth2PasswordPassword: """ - Test Class for MessageContextGlobalSystem + Test Class for ProviderPrivateAuthenticationOAuth2PasswordPassword """ - def test_message_context_global_system_serialization(self): + def test_provider_private_authentication_o_auth2_password_password_serialization(self): """ - Test serialization/deserialization for MessageContextGlobalSystem + Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2PasswordPassword """ - # Construct a json representation of a MessageContextGlobalSystem model - message_context_global_system_model_json = {} - message_context_global_system_model_json['timezone'] = 'testString' - message_context_global_system_model_json['user_id'] = 'testString' - message_context_global_system_model_json['turn_count'] = 38 - message_context_global_system_model_json['locale'] = 'en-us' - message_context_global_system_model_json['reference_time'] = 'testString' - message_context_global_system_model_json['session_start_time'] = 'testString' - message_context_global_system_model_json['state'] = 'testString' - message_context_global_system_model_json['skip_user_input'] = True + # Construct a json representation of a ProviderPrivateAuthenticationOAuth2PasswordPassword model + provider_private_authentication_o_auth2_password_password_model_json = {} + provider_private_authentication_o_auth2_password_password_model_json['type'] = 'value' + provider_private_authentication_o_auth2_password_password_model_json['value'] = 'testString' - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) - assert message_context_global_system_model != False + # Construct a model instance of ProviderPrivateAuthenticationOAuth2PasswordPassword by calling from_dict on the json representation + provider_private_authentication_o_auth2_password_password_model = ProviderPrivateAuthenticationOAuth2PasswordPassword.from_dict(provider_private_authentication_o_auth2_password_password_model_json) + assert provider_private_authentication_o_auth2_password_password_model != False - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ - message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) + # Construct a model instance of ProviderPrivateAuthenticationOAuth2PasswordPassword by calling from_dict on the json representation + provider_private_authentication_o_auth2_password_password_model_dict = ProviderPrivateAuthenticationOAuth2PasswordPassword.from_dict(provider_private_authentication_o_auth2_password_password_model_json).__dict__ + provider_private_authentication_o_auth2_password_password_model2 = ProviderPrivateAuthenticationOAuth2PasswordPassword(**provider_private_authentication_o_auth2_password_password_model_dict) # Verify the model instances are equivalent - assert message_context_global_system_model == message_context_global_system_model2 + assert provider_private_authentication_o_auth2_password_password_model == provider_private_authentication_o_auth2_password_password_model2 # Convert model instance back to dict and verify no loss of data - message_context_global_system_model_json2 = message_context_global_system_model.to_dict() - assert message_context_global_system_model_json2 == message_context_global_system_model_json + provider_private_authentication_o_auth2_password_password_model_json2 = provider_private_authentication_o_auth2_password_password_model.to_dict() + assert provider_private_authentication_o_auth2_password_password_model_json2 == provider_private_authentication_o_auth2_password_password_model_json -class TestModel_MessageContextSkillSystem: +class TestModel_ProviderResponse: """ - Test Class for MessageContextSkillSystem + Test Class for ProviderResponse """ - def test_message_context_skill_system_serialization(self): + def test_provider_response_serialization(self): """ - Test serialization/deserialization for MessageContextSkillSystem + Test serialization/deserialization for ProviderResponse """ - # Construct a json representation of a MessageContextSkillSystem model - message_context_skill_system_model_json = {} - message_context_skill_system_model_json['state'] = 'testString' - message_context_skill_system_model_json['foo'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) - assert message_context_skill_system_model != False + provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem + provider_response_specification_servers_item_model['url'] = 'testString' - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ - message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Verify the model instances are equivalent - assert message_context_skill_system_model == message_context_skill_system_model2 + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - # Convert model instance back to dict and verify no loss of data - message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() - assert message_context_skill_system_model_json2 == message_context_skill_system_model_json + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - # Test get_properties and set_properties methods. - message_context_skill_system_model.set_properties({}) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict == {} + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - expected_dict = {'foo': 'testString'} - message_context_skill_system_model.set_properties(expected_dict) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict == expected_dict + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model -class TestModel_MessageContextSkills: + provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents + provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model + + provider_response_specification_model = {} # ProviderResponseSpecification + provider_response_specification_model['servers'] = [provider_response_specification_servers_item_model] + provider_response_specification_model['components'] = provider_response_specification_components_model + + # Construct a json representation of a ProviderResponse model + provider_response_model_json = {} + provider_response_model_json['provider_id'] = 'testString' + provider_response_model_json['specification'] = provider_response_specification_model + + # Construct a model instance of ProviderResponse by calling from_dict on the json representation + provider_response_model = ProviderResponse.from_dict(provider_response_model_json) + assert provider_response_model != False + + # Construct a model instance of ProviderResponse by calling from_dict on the json representation + provider_response_model_dict = ProviderResponse.from_dict(provider_response_model_json).__dict__ + provider_response_model2 = ProviderResponse(**provider_response_model_dict) + + # Verify the model instances are equivalent + assert provider_response_model == provider_response_model2 + + # Convert model instance back to dict and verify no loss of data + provider_response_model_json2 = provider_response_model.to_dict() + assert provider_response_model_json2 == provider_response_model_json + + +class TestModel_ProviderResponseSpecification: """ - Test Class for MessageContextSkills + Test Class for ProviderResponseSpecification """ - def test_message_context_skills_serialization(self): + def test_provider_response_specification_serialization(self): """ - Test serialization/deserialization for MessageContextSkills + Test serialization/deserialization for ProviderResponseSpecification """ # Construct dict forms of any model objects needed in order to build this model. - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem + provider_response_specification_servers_item_model['url'] = 'testString' - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - # Construct a json representation of a MessageContextSkills model - message_context_skills_model_json = {} - message_context_skills_model_json['main skill'] = message_context_dialog_skill_model - message_context_skills_model_json['actions skill'] = message_context_action_skill_model + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - # Construct a model instance of MessageContextSkills by calling from_dict on the json representation - message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) - assert message_context_skills_model != False + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - # Construct a model instance of MessageContextSkills by calling from_dict on the json representation - message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ - message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents + provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model + + # Construct a json representation of a ProviderResponseSpecification model + provider_response_specification_model_json = {} + provider_response_specification_model_json['servers'] = [provider_response_specification_servers_item_model] + provider_response_specification_model_json['components'] = provider_response_specification_components_model + + # Construct a model instance of ProviderResponseSpecification by calling from_dict on the json representation + provider_response_specification_model = ProviderResponseSpecification.from_dict(provider_response_specification_model_json) + assert provider_response_specification_model != False + + # Construct a model instance of ProviderResponseSpecification by calling from_dict on the json representation + provider_response_specification_model_dict = ProviderResponseSpecification.from_dict(provider_response_specification_model_json).__dict__ + provider_response_specification_model2 = ProviderResponseSpecification(**provider_response_specification_model_dict) # Verify the model instances are equivalent - assert message_context_skills_model == message_context_skills_model2 + assert provider_response_specification_model == provider_response_specification_model2 # Convert model instance back to dict and verify no loss of data - message_context_skills_model_json2 = message_context_skills_model.to_dict() - assert message_context_skills_model_json2 == message_context_skills_model_json + provider_response_specification_model_json2 = provider_response_specification_model.to_dict() + assert provider_response_specification_model_json2 == provider_response_specification_model_json -class TestModel_MessageInput: +class TestModel_ProviderResponseSpecificationComponents: """ - Test Class for MessageInput + Test Class for ProviderResponseSpecificationComponents """ - def test_message_input_serialization(self): + def test_provider_response_specification_components_serialization(self): """ - Test serialization/deserialization for MessageInput + Test serialization/deserialization for ProviderResponseSpecificationComponents """ # Construct dict forms of any model objects needed in order to build this model. - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' - - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 - - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['async_callout'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - # Construct a json representation of a MessageInput model - message_input_model_json = {} - message_input_model_json['message_type'] = 'text' - message_input_model_json['text'] = 'testString' - message_input_model_json['intents'] = [runtime_intent_model] - message_input_model_json['entities'] = [runtime_entity_model] - message_input_model_json['suggestion_id'] = 'testString' - message_input_model_json['attachments'] = [message_input_attachment_model] - message_input_model_json['analytics'] = request_analytics_model - message_input_model_json['options'] = message_input_options_model + # Construct a json representation of a ProviderResponseSpecificationComponents model + provider_response_specification_components_model_json = {} + provider_response_specification_components_model_json['securitySchemes'] = provider_response_specification_components_security_schemes_model - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model = MessageInput.from_dict(message_input_model_json) - assert message_input_model != False + # Construct a model instance of ProviderResponseSpecificationComponents by calling from_dict on the json representation + provider_response_specification_components_model = ProviderResponseSpecificationComponents.from_dict(provider_response_specification_components_model_json) + assert provider_response_specification_components_model != False - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ - message_input_model2 = MessageInput(**message_input_model_dict) + # Construct a model instance of ProviderResponseSpecificationComponents by calling from_dict on the json representation + provider_response_specification_components_model_dict = ProviderResponseSpecificationComponents.from_dict(provider_response_specification_components_model_json).__dict__ + provider_response_specification_components_model2 = ProviderResponseSpecificationComponents(**provider_response_specification_components_model_dict) # Verify the model instances are equivalent - assert message_input_model == message_input_model2 + assert provider_response_specification_components_model == provider_response_specification_components_model2 # Convert model instance back to dict and verify no loss of data - message_input_model_json2 = message_input_model.to_dict() - assert message_input_model_json2 == message_input_model_json + provider_response_specification_components_model_json2 = provider_response_specification_components_model.to_dict() + assert provider_response_specification_components_model_json2 == provider_response_specification_components_model_json -class TestModel_MessageInputAttachment: +class TestModel_ProviderResponseSpecificationComponentsSecuritySchemes: """ - Test Class for MessageInputAttachment + Test Class for ProviderResponseSpecificationComponentsSecuritySchemes """ - def test_message_input_attachment_serialization(self): + def test_provider_response_specification_components_security_schemes_serialization(self): """ - Test serialization/deserialization for MessageInputAttachment + Test serialization/deserialization for ProviderResponseSpecificationComponentsSecuritySchemes """ - # Construct a json representation of a MessageInputAttachment model - message_input_attachment_model_json = {} - message_input_attachment_model_json['url'] = 'testString' - message_input_attachment_model_json['media_type'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) - assert message_input_attachment_model != False + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ - message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a json representation of a ProviderResponseSpecificationComponentsSecuritySchemes model + provider_response_specification_components_security_schemes_model_json = {} + provider_response_specification_components_security_schemes_model_json['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model_json['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model_json['oauth2'] = provider_authentication_o_auth2_model + + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_response_specification_components_security_schemes_model = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict(provider_response_specification_components_security_schemes_model_json) + assert provider_response_specification_components_security_schemes_model != False + + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_response_specification_components_security_schemes_model_dict = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict(provider_response_specification_components_security_schemes_model_json).__dict__ + provider_response_specification_components_security_schemes_model2 = ProviderResponseSpecificationComponentsSecuritySchemes(**provider_response_specification_components_security_schemes_model_dict) # Verify the model instances are equivalent - assert message_input_attachment_model == message_input_attachment_model2 + assert provider_response_specification_components_security_schemes_model == provider_response_specification_components_security_schemes_model2 # Convert model instance back to dict and verify no loss of data - message_input_attachment_model_json2 = message_input_attachment_model.to_dict() - assert message_input_attachment_model_json2 == message_input_attachment_model_json + provider_response_specification_components_security_schemes_model_json2 = provider_response_specification_components_security_schemes_model.to_dict() + assert provider_response_specification_components_security_schemes_model_json2 == provider_response_specification_components_security_schemes_model_json -class TestModel_MessageInputOptions: +class TestModel_ProviderResponseSpecificationComponentsSecuritySchemesBasic: """ - Test Class for MessageInputOptions + Test Class for ProviderResponseSpecificationComponentsSecuritySchemesBasic """ - def test_message_input_options_serialization(self): + def test_provider_response_specification_components_security_schemes_basic_serialization(self): """ - Test serialization/deserialization for MessageInputOptions + Test serialization/deserialization for ProviderResponseSpecificationComponentsSecuritySchemesBasic """ # Construct dict forms of any model objects needed in order to build this model. - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a json representation of a MessageInputOptions model - message_input_options_model_json = {} - message_input_options_model_json['restart'] = False - message_input_options_model_json['alternate_intents'] = False - message_input_options_model_json['async_callout'] = False - message_input_options_model_json['spelling'] = message_input_options_spelling_model - message_input_options_model_json['debug'] = False - message_input_options_model_json['return_context'] = False - message_input_options_model_json['export'] = False + # Construct a json representation of a ProviderResponseSpecificationComponentsSecuritySchemesBasic model + provider_response_specification_components_security_schemes_basic_model_json = {} + provider_response_specification_components_security_schemes_basic_model_json['username'] = provider_authentication_type_and_value_model - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) - assert message_input_options_model != False + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_response_specification_components_security_schemes_basic_model = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict(provider_response_specification_components_security_schemes_basic_model_json) + assert provider_response_specification_components_security_schemes_basic_model != False - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ - message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_response_specification_components_security_schemes_basic_model_dict = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict(provider_response_specification_components_security_schemes_basic_model_json).__dict__ + provider_response_specification_components_security_schemes_basic_model2 = ProviderResponseSpecificationComponentsSecuritySchemesBasic(**provider_response_specification_components_security_schemes_basic_model_dict) # Verify the model instances are equivalent - assert message_input_options_model == message_input_options_model2 + assert provider_response_specification_components_security_schemes_basic_model == provider_response_specification_components_security_schemes_basic_model2 # Convert model instance back to dict and verify no loss of data - message_input_options_model_json2 = message_input_options_model.to_dict() - assert message_input_options_model_json2 == message_input_options_model_json + provider_response_specification_components_security_schemes_basic_model_json2 = provider_response_specification_components_security_schemes_basic_model.to_dict() + assert provider_response_specification_components_security_schemes_basic_model_json2 == provider_response_specification_components_security_schemes_basic_model_json -class TestModel_MessageInputOptionsSpelling: +class TestModel_ProviderResponseSpecificationServersItem: """ - Test Class for MessageInputOptionsSpelling + Test Class for ProviderResponseSpecificationServersItem """ - def test_message_input_options_spelling_serialization(self): + def test_provider_response_specification_servers_item_serialization(self): """ - Test serialization/deserialization for MessageInputOptionsSpelling + Test serialization/deserialization for ProviderResponseSpecificationServersItem """ - # Construct a json representation of a MessageInputOptionsSpelling model - message_input_options_spelling_model_json = {} - message_input_options_spelling_model_json['suggestions'] = True - message_input_options_spelling_model_json['auto_correct'] = True + # Construct a json representation of a ProviderResponseSpecificationServersItem model + provider_response_specification_servers_item_model_json = {} + provider_response_specification_servers_item_model_json['url'] = 'testString' - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) - assert message_input_options_spelling_model != False + # Construct a model instance of ProviderResponseSpecificationServersItem by calling from_dict on the json representation + provider_response_specification_servers_item_model = ProviderResponseSpecificationServersItem.from_dict(provider_response_specification_servers_item_model_json) + assert provider_response_specification_servers_item_model != False - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ - message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) + # Construct a model instance of ProviderResponseSpecificationServersItem by calling from_dict on the json representation + provider_response_specification_servers_item_model_dict = ProviderResponseSpecificationServersItem.from_dict(provider_response_specification_servers_item_model_json).__dict__ + provider_response_specification_servers_item_model2 = ProviderResponseSpecificationServersItem(**provider_response_specification_servers_item_model_dict) # Verify the model instances are equivalent - assert message_input_options_spelling_model == message_input_options_spelling_model2 + assert provider_response_specification_servers_item_model == provider_response_specification_servers_item_model2 # Convert model instance back to dict and verify no loss of data - message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() - assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json + provider_response_specification_servers_item_model_json2 = provider_response_specification_servers_item_model.to_dict() + assert provider_response_specification_servers_item_model_json2 == provider_response_specification_servers_item_model_json -class TestModel_MessageOutput: +class TestModel_ProviderSpecification: """ - Test Class for MessageOutput + Test Class for ProviderSpecification """ - def test_message_output_serialization(self): + def test_provider_specification_serialization(self): """ - Test serialization/deserialization for MessageOutput + Test serialization/deserialization for ProviderSpecification """ # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + provider_specification_servers_item_model = {} # ProviderSpecificationServersItem + provider_specification_servers_item_model['url'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + provider_specification_components_security_schemes_model = {} # ProviderSpecificationComponentsSecuritySchemes + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + provider_specification_components_model = {} # ProviderSpecificationComponents + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model + + # Construct a json representation of a ProviderSpecification model + provider_specification_model_json = {} + provider_specification_model_json['servers'] = [provider_specification_servers_item_model] + provider_specification_model_json['components'] = provider_specification_components_model + + # Construct a model instance of ProviderSpecification by calling from_dict on the json representation + provider_specification_model = ProviderSpecification.from_dict(provider_specification_model_json) + assert provider_specification_model != False + + # Construct a model instance of ProviderSpecification by calling from_dict on the json representation + provider_specification_model_dict = ProviderSpecification.from_dict(provider_specification_model_json).__dict__ + provider_specification_model2 = ProviderSpecification(**provider_specification_model_dict) - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Verify the model instances are equivalent + assert provider_specification_model == provider_specification_model2 - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Convert model instance back to dict and verify no loss of data + provider_specification_model_json2 = provider_specification_model.to_dict() + assert provider_specification_model_json2 == provider_specification_model_json - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' +class TestModel_ProviderSpecificationComponents: + """ + Test Class for ProviderSpecificationComponents + """ - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' + def test_provider_specification_components_serialization(self): + """ + Test serialization/deserialization for ProviderSpecificationComponents + """ - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' + provider_specification_components_security_schemes_model = {} # ProviderSpecificationComponentsSecuritySchemes + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - # Construct a json representation of a MessageOutput model - message_output_model_json = {} - message_output_model_json['generic'] = [runtime_response_generic_model] - message_output_model_json['intents'] = [runtime_intent_model] - message_output_model_json['entities'] = [runtime_entity_model] - message_output_model_json['actions'] = [dialog_node_action_model] - message_output_model_json['debug'] = message_output_debug_model - message_output_model_json['user_defined'] = {'anyKey': 'anyValue'} - message_output_model_json['spelling'] = message_output_spelling_model + # Construct a json representation of a ProviderSpecificationComponents model + provider_specification_components_model_json = {} + provider_specification_components_model_json['securitySchemes'] = provider_specification_components_security_schemes_model - # Construct a model instance of MessageOutput by calling from_dict on the json representation - message_output_model = MessageOutput.from_dict(message_output_model_json) - assert message_output_model != False + # Construct a model instance of ProviderSpecificationComponents by calling from_dict on the json representation + provider_specification_components_model = ProviderSpecificationComponents.from_dict(provider_specification_components_model_json) + assert provider_specification_components_model != False - # Construct a model instance of MessageOutput by calling from_dict on the json representation - message_output_model_dict = MessageOutput.from_dict(message_output_model_json).__dict__ - message_output_model2 = MessageOutput(**message_output_model_dict) + # Construct a model instance of ProviderSpecificationComponents by calling from_dict on the json representation + provider_specification_components_model_dict = ProviderSpecificationComponents.from_dict(provider_specification_components_model_json).__dict__ + provider_specification_components_model2 = ProviderSpecificationComponents(**provider_specification_components_model_dict) # Verify the model instances are equivalent - assert message_output_model == message_output_model2 + assert provider_specification_components_model == provider_specification_components_model2 # Convert model instance back to dict and verify no loss of data - message_output_model_json2 = message_output_model.to_dict() - assert message_output_model_json2 == message_output_model_json + provider_specification_components_model_json2 = provider_specification_components_model.to_dict() + assert provider_specification_components_model_json2 == provider_specification_components_model_json -class TestModel_MessageOutputDebug: +class TestModel_ProviderSpecificationComponentsSecuritySchemes: """ - Test Class for MessageOutputDebug + Test Class for ProviderSpecificationComponentsSecuritySchemes """ - def test_message_output_debug_serialization(self): + def test_provider_specification_components_security_schemes_serialization(self): """ - Test serialization/deserialization for MessageOutputDebug + Test serialization/deserialization for ProviderSpecificationComponentsSecuritySchemes """ # Construct dict forms of any model objects needed in order to build this model. - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - # Construct a json representation of a MessageOutputDebug model - message_output_debug_model_json = {} - message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model_json['log_messages'] = [dialog_log_message_model] - message_output_debug_model_json['branch_exited'] = True - message_output_debug_model_json['branch_exited_reason'] = 'completed' - message_output_debug_model_json['turn_events'] = [message_output_debug_turn_event_model] + # Construct a json representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model_json = {} + provider_specification_components_security_schemes_model_json['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model_json['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model_json['oauth2'] = provider_authentication_o_auth2_model - # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation - message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) - assert message_output_debug_model != False + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_specification_components_security_schemes_model = ProviderSpecificationComponentsSecuritySchemes.from_dict(provider_specification_components_security_schemes_model_json) + assert provider_specification_components_security_schemes_model != False - # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation - message_output_debug_model_dict = MessageOutputDebug.from_dict(message_output_debug_model_json).__dict__ - message_output_debug_model2 = MessageOutputDebug(**message_output_debug_model_dict) + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_specification_components_security_schemes_model_dict = ProviderSpecificationComponentsSecuritySchemes.from_dict(provider_specification_components_security_schemes_model_json).__dict__ + provider_specification_components_security_schemes_model2 = ProviderSpecificationComponentsSecuritySchemes(**provider_specification_components_security_schemes_model_dict) # Verify the model instances are equivalent - assert message_output_debug_model == message_output_debug_model2 + assert provider_specification_components_security_schemes_model == provider_specification_components_security_schemes_model2 # Convert model instance back to dict and verify no loss of data - message_output_debug_model_json2 = message_output_debug_model.to_dict() - assert message_output_debug_model_json2 == message_output_debug_model_json + provider_specification_components_security_schemes_model_json2 = provider_specification_components_security_schemes_model.to_dict() + assert provider_specification_components_security_schemes_model_json2 == provider_specification_components_security_schemes_model_json -class TestModel_MessageOutputSpelling: +class TestModel_ProviderSpecificationComponentsSecuritySchemesBasic: """ - Test Class for MessageOutputSpelling + Test Class for ProviderSpecificationComponentsSecuritySchemesBasic """ - def test_message_output_spelling_serialization(self): + def test_provider_specification_components_security_schemes_basic_serialization(self): """ - Test serialization/deserialization for MessageOutputSpelling + Test serialization/deserialization for ProviderSpecificationComponentsSecuritySchemesBasic """ - # Construct a json representation of a MessageOutputSpelling model - message_output_spelling_model_json = {} - message_output_spelling_model_json['text'] = 'testString' - message_output_spelling_model_json['original_text'] = 'testString' - message_output_spelling_model_json['suggested_text'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation - message_output_spelling_model = MessageOutputSpelling.from_dict(message_output_spelling_model_json) - assert message_output_spelling_model != False + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation - message_output_spelling_model_dict = MessageOutputSpelling.from_dict(message_output_spelling_model_json).__dict__ - message_output_spelling_model2 = MessageOutputSpelling(**message_output_spelling_model_dict) + # Construct a json representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model_json = {} + provider_specification_components_security_schemes_basic_model_json['username'] = provider_authentication_type_and_value_model + + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_specification_components_security_schemes_basic_model = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict(provider_specification_components_security_schemes_basic_model_json) + assert provider_specification_components_security_schemes_basic_model != False + + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_specification_components_security_schemes_basic_model_dict = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict(provider_specification_components_security_schemes_basic_model_json).__dict__ + provider_specification_components_security_schemes_basic_model2 = ProviderSpecificationComponentsSecuritySchemesBasic(**provider_specification_components_security_schemes_basic_model_dict) # Verify the model instances are equivalent - assert message_output_spelling_model == message_output_spelling_model2 + assert provider_specification_components_security_schemes_basic_model == provider_specification_components_security_schemes_basic_model2 # Convert model instance back to dict and verify no loss of data - message_output_spelling_model_json2 = message_output_spelling_model.to_dict() - assert message_output_spelling_model_json2 == message_output_spelling_model_json + provider_specification_components_security_schemes_basic_model_json2 = provider_specification_components_security_schemes_basic_model.to_dict() + assert provider_specification_components_security_schemes_basic_model_json2 == provider_specification_components_security_schemes_basic_model_json -class TestModel_Pagination: +class TestModel_ProviderSpecificationServersItem: """ - Test Class for Pagination + Test Class for ProviderSpecificationServersItem """ - def test_pagination_serialization(self): + def test_provider_specification_servers_item_serialization(self): """ - Test serialization/deserialization for Pagination + Test serialization/deserialization for ProviderSpecificationServersItem """ - # Construct a json representation of a Pagination model - pagination_model_json = {} - pagination_model_json['refresh_url'] = 'testString' - pagination_model_json['next_url'] = 'testString' - pagination_model_json['total'] = 38 - pagination_model_json['matched'] = 38 - pagination_model_json['refresh_cursor'] = 'testString' - pagination_model_json['next_cursor'] = 'testString' + # Construct a json representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model_json = {} + provider_specification_servers_item_model_json['url'] = 'testString' - # Construct a model instance of Pagination by calling from_dict on the json representation - pagination_model = Pagination.from_dict(pagination_model_json) - assert pagination_model != False + # Construct a model instance of ProviderSpecificationServersItem by calling from_dict on the json representation + provider_specification_servers_item_model = ProviderSpecificationServersItem.from_dict(provider_specification_servers_item_model_json) + assert provider_specification_servers_item_model != False - # Construct a model instance of Pagination by calling from_dict on the json representation - pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ - pagination_model2 = Pagination(**pagination_model_dict) + # Construct a model instance of ProviderSpecificationServersItem by calling from_dict on the json representation + provider_specification_servers_item_model_dict = ProviderSpecificationServersItem.from_dict(provider_specification_servers_item_model_json).__dict__ + provider_specification_servers_item_model2 = ProviderSpecificationServersItem(**provider_specification_servers_item_model_dict) # Verify the model instances are equivalent - assert pagination_model == pagination_model2 + assert provider_specification_servers_item_model == provider_specification_servers_item_model2 # Convert model instance back to dict and verify no loss of data - pagination_model_json2 = pagination_model.to_dict() - assert pagination_model_json2 == pagination_model_json + provider_specification_servers_item_model_json2 = provider_specification_servers_item_model.to_dict() + assert provider_specification_servers_item_model_json2 == provider_specification_servers_item_model_json class TestModel_Release: @@ -7244,7 +10074,7 @@ def test_search_result_highlight_serialization(self): expected_dict = {'foo': ['testString']} search_result_highlight_model.set_properties(expected_dict) actual_dict = search_result_highlight_model.get_properties() - assert actual_dict == expected_dict + assert actual_dict.keys() == expected_dict.keys() class TestModel_SearchResultMetadata: @@ -7315,11 +10145,52 @@ def test_search_settings_serialization(self): search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' + search_settings_elastic_search_model = {} # SearchSettingsElasticSearch + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + # Construct a json representation of a SearchSettings model search_settings_model_json = {} search_settings_model_json['discovery'] = search_settings_discovery_model search_settings_model_json['messages'] = search_settings_messages_model search_settings_model_json['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model_json['elastic_search'] = search_settings_elastic_search_model + search_settings_model_json['conversational_search'] = search_settings_conversational_search_model + search_settings_model_json['server_side_search'] = search_settings_server_side_search_model + search_settings_model_json['client_side_search'] = search_settings_client_side_search_model # Construct a model instance of SearchSettings by calling from_dict on the json representation search_settings_model = SearchSettings.from_dict(search_settings_model_json) @@ -7330,11 +10201,142 @@ def test_search_settings_serialization(self): search_settings_model2 = SearchSettings(**search_settings_model_dict) # Verify the model instances are equivalent - assert search_settings_model == search_settings_model2 + assert search_settings_model == search_settings_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_model_json2 = search_settings_model.to_dict() + assert search_settings_model_json2 == search_settings_model_json + + +class TestModel_SearchSettingsClientSideSearch: + """ + Test Class for SearchSettingsClientSideSearch + """ + + def test_search_settings_client_side_search_serialization(self): + """ + Test serialization/deserialization for SearchSettingsClientSideSearch + """ + + # Construct a json representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model_json = {} + search_settings_client_side_search_model_json['filter'] = 'testString' + search_settings_client_side_search_model_json['metadata'] = {'anyKey': 'anyValue'} + + # Construct a model instance of SearchSettingsClientSideSearch by calling from_dict on the json representation + search_settings_client_side_search_model = SearchSettingsClientSideSearch.from_dict(search_settings_client_side_search_model_json) + assert search_settings_client_side_search_model != False + + # Construct a model instance of SearchSettingsClientSideSearch by calling from_dict on the json representation + search_settings_client_side_search_model_dict = SearchSettingsClientSideSearch.from_dict(search_settings_client_side_search_model_json).__dict__ + search_settings_client_side_search_model2 = SearchSettingsClientSideSearch(**search_settings_client_side_search_model_dict) + + # Verify the model instances are equivalent + assert search_settings_client_side_search_model == search_settings_client_side_search_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_client_side_search_model_json2 = search_settings_client_side_search_model.to_dict() + assert search_settings_client_side_search_model_json2 == search_settings_client_side_search_model_json + + +class TestModel_SearchSettingsConversationalSearch: + """ + Test Class for SearchSettingsConversationalSearch + """ + + def test_search_settings_conversational_search_serialization(self): + """ + Test serialization/deserialization for SearchSettingsConversationalSearch + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + # Construct a json representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model_json = {} + search_settings_conversational_search_model_json['enabled'] = True + search_settings_conversational_search_model_json['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model_json['search_confidence'] = search_settings_conversational_search_search_confidence_model + + # Construct a model instance of SearchSettingsConversationalSearch by calling from_dict on the json representation + search_settings_conversational_search_model = SearchSettingsConversationalSearch.from_dict(search_settings_conversational_search_model_json) + assert search_settings_conversational_search_model != False + + # Construct a model instance of SearchSettingsConversationalSearch by calling from_dict on the json representation + search_settings_conversational_search_model_dict = SearchSettingsConversationalSearch.from_dict(search_settings_conversational_search_model_json).__dict__ + search_settings_conversational_search_model2 = SearchSettingsConversationalSearch(**search_settings_conversational_search_model_dict) + + # Verify the model instances are equivalent + assert search_settings_conversational_search_model == search_settings_conversational_search_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_conversational_search_model_json2 = search_settings_conversational_search_model.to_dict() + assert search_settings_conversational_search_model_json2 == search_settings_conversational_search_model_json + + +class TestModel_SearchSettingsConversationalSearchResponseLength: + """ + Test Class for SearchSettingsConversationalSearchResponseLength + """ + + def test_search_settings_conversational_search_response_length_serialization(self): + """ + Test serialization/deserialization for SearchSettingsConversationalSearchResponseLength + """ + + # Construct a json representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model_json = {} + search_settings_conversational_search_response_length_model_json['option'] = 'moderate' + + # Construct a model instance of SearchSettingsConversationalSearchResponseLength by calling from_dict on the json representation + search_settings_conversational_search_response_length_model = SearchSettingsConversationalSearchResponseLength.from_dict(search_settings_conversational_search_response_length_model_json) + assert search_settings_conversational_search_response_length_model != False + + # Construct a model instance of SearchSettingsConversationalSearchResponseLength by calling from_dict on the json representation + search_settings_conversational_search_response_length_model_dict = SearchSettingsConversationalSearchResponseLength.from_dict(search_settings_conversational_search_response_length_model_json).__dict__ + search_settings_conversational_search_response_length_model2 = SearchSettingsConversationalSearchResponseLength(**search_settings_conversational_search_response_length_model_dict) + + # Verify the model instances are equivalent + assert search_settings_conversational_search_response_length_model == search_settings_conversational_search_response_length_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_conversational_search_response_length_model_json2 = search_settings_conversational_search_response_length_model.to_dict() + assert search_settings_conversational_search_response_length_model_json2 == search_settings_conversational_search_response_length_model_json + + +class TestModel_SearchSettingsConversationalSearchSearchConfidence: + """ + Test Class for SearchSettingsConversationalSearchSearchConfidence + """ + + def test_search_settings_conversational_search_search_confidence_serialization(self): + """ + Test serialization/deserialization for SearchSettingsConversationalSearchSearchConfidence + """ + + # Construct a json representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model_json = {} + search_settings_conversational_search_search_confidence_model_json['threshold'] = 'less_often' + + # Construct a model instance of SearchSettingsConversationalSearchSearchConfidence by calling from_dict on the json representation + search_settings_conversational_search_search_confidence_model = SearchSettingsConversationalSearchSearchConfidence.from_dict(search_settings_conversational_search_search_confidence_model_json) + assert search_settings_conversational_search_search_confidence_model != False + + # Construct a model instance of SearchSettingsConversationalSearchSearchConfidence by calling from_dict on the json representation + search_settings_conversational_search_search_confidence_model_dict = SearchSettingsConversationalSearchSearchConfidence.from_dict(search_settings_conversational_search_search_confidence_model_json).__dict__ + search_settings_conversational_search_search_confidence_model2 = SearchSettingsConversationalSearchSearchConfidence(**search_settings_conversational_search_search_confidence_model_dict) + + # Verify the model instances are equivalent + assert search_settings_conversational_search_search_confidence_model == search_settings_conversational_search_search_confidence_model2 # Convert model instance back to dict and verify no loss of data - search_settings_model_json2 = search_settings_model.to_dict() - assert search_settings_model_json2 == search_settings_model_json + search_settings_conversational_search_search_confidence_model_json2 = search_settings_conversational_search_search_confidence_model.to_dict() + assert search_settings_conversational_search_search_confidence_model_json2 == search_settings_conversational_search_search_confidence_model_json class TestModel_SearchSettingsDiscovery: @@ -7412,6 +10414,44 @@ def test_search_settings_discovery_authentication_serialization(self): assert search_settings_discovery_authentication_model_json2 == search_settings_discovery_authentication_model_json +class TestModel_SearchSettingsElasticSearch: + """ + Test Class for SearchSettingsElasticSearch + """ + + def test_search_settings_elastic_search_serialization(self): + """ + Test serialization/deserialization for SearchSettingsElasticSearch + """ + + # Construct a json representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model_json = {} + search_settings_elastic_search_model_json['url'] = 'testString' + search_settings_elastic_search_model_json['port'] = 'testString' + search_settings_elastic_search_model_json['username'] = 'testString' + search_settings_elastic_search_model_json['password'] = 'testString' + search_settings_elastic_search_model_json['index'] = 'testString' + search_settings_elastic_search_model_json['filter'] = ['testString'] + search_settings_elastic_search_model_json['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model_json['managed_index'] = 'testString' + search_settings_elastic_search_model_json['apikey'] = 'testString' + + # Construct a model instance of SearchSettingsElasticSearch by calling from_dict on the json representation + search_settings_elastic_search_model = SearchSettingsElasticSearch.from_dict(search_settings_elastic_search_model_json) + assert search_settings_elastic_search_model != False + + # Construct a model instance of SearchSettingsElasticSearch by calling from_dict on the json representation + search_settings_elastic_search_model_dict = SearchSettingsElasticSearch.from_dict(search_settings_elastic_search_model_json).__dict__ + search_settings_elastic_search_model2 = SearchSettingsElasticSearch(**search_settings_elastic_search_model_dict) + + # Verify the model instances are equivalent + assert search_settings_elastic_search_model == search_settings_elastic_search_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_elastic_search_model_json2 = search_settings_elastic_search_model.to_dict() + assert search_settings_elastic_search_model_json2 == search_settings_elastic_search_model_json + + class TestModel_SearchSettingsMessages: """ Test Class for SearchSettingsMessages @@ -7476,6 +10516,44 @@ def test_search_settings_schema_mapping_serialization(self): assert search_settings_schema_mapping_model_json2 == search_settings_schema_mapping_model_json +class TestModel_SearchSettingsServerSideSearch: + """ + Test Class for SearchSettingsServerSideSearch + """ + + def test_search_settings_server_side_search_serialization(self): + """ + Test serialization/deserialization for SearchSettingsServerSideSearch + """ + + # Construct a json representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model_json = {} + search_settings_server_side_search_model_json['url'] = 'testString' + search_settings_server_side_search_model_json['port'] = 'testString' + search_settings_server_side_search_model_json['username'] = 'testString' + search_settings_server_side_search_model_json['password'] = 'testString' + search_settings_server_side_search_model_json['filter'] = 'testString' + search_settings_server_side_search_model_json['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model_json['apikey'] = 'testString' + search_settings_server_side_search_model_json['no_auth'] = True + search_settings_server_side_search_model_json['auth_type'] = 'basic' + + # Construct a model instance of SearchSettingsServerSideSearch by calling from_dict on the json representation + search_settings_server_side_search_model = SearchSettingsServerSideSearch.from_dict(search_settings_server_side_search_model_json) + assert search_settings_server_side_search_model != False + + # Construct a model instance of SearchSettingsServerSideSearch by calling from_dict on the json representation + search_settings_server_side_search_model_dict = SearchSettingsServerSideSearch.from_dict(search_settings_server_side_search_model_json).__dict__ + search_settings_server_side_search_model2 = SearchSettingsServerSideSearch(**search_settings_server_side_search_model_dict) + + # Verify the model instances are equivalent + assert search_settings_server_side_search_model == search_settings_server_side_search_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_server_side_search_model_json2 = search_settings_server_side_search_model.to_dict() + assert search_settings_server_side_search_model_json2 == search_settings_server_side_search_model_json + + class TestModel_SearchSkillWarning: """ Test Class for SearchSkillWarning @@ -7575,10 +10653,51 @@ def test_skill_serialization(self): search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' + search_settings_elastic_search_model = {} # SearchSettingsElasticSearch + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_model = {} # SearchSettings search_settings_model['discovery'] = search_settings_discovery_model search_settings_model['messages'] = search_settings_messages_model search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model # Construct a json representation of a Skill model skill_model_json = {} @@ -7643,10 +10762,51 @@ def test_skill_import_serialization(self): search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' + search_settings_elastic_search_model = {} # SearchSettingsElasticSearch + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_model = {} # SearchSettings search_settings_model['discovery'] = search_settings_discovery_model search_settings_model['messages'] = search_settings_messages_model search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model # Construct a json representation of a SkillImport model skill_import_model_json = {} @@ -7740,10 +10900,51 @@ def test_skills_export_serialization(self): search_settings_schema_mapping_model['body'] = 'testString' search_settings_schema_mapping_model['title'] = 'testString' + search_settings_elastic_search_model = {} # SearchSettingsElasticSearch + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_model = {} # SearchSettings search_settings_model['discovery'] = search_settings_discovery_model search_settings_model['messages'] = search_settings_messages_model search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model skill_model = {} # Skill skill_model['name'] = 'testString' @@ -8658,11 +11859,28 @@ def test_turn_event_callout_callout_serialization(self): Test serialization/deserialization for TurnEventCalloutCallout """ + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_callout_callout_request_model = {} # TurnEventCalloutCalloutRequest + turn_event_callout_callout_request_model['method'] = 'get' + turn_event_callout_callout_request_model['url'] = 'testString' + turn_event_callout_callout_request_model['path'] = 'testString' + turn_event_callout_callout_request_model['query_parameters'] = 'testString' + turn_event_callout_callout_request_model['headers'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_request_model['body'] = {'anyKey': 'anyValue'} + + turn_event_callout_callout_response_model = {} # TurnEventCalloutCalloutResponse + turn_event_callout_callout_response_model['body'] = 'testString' + turn_event_callout_callout_response_model['status_code'] = 38 + turn_event_callout_callout_response_model['last_event'] = {'anyKey': 'anyValue'} + # Construct a json representation of a TurnEventCalloutCallout model turn_event_callout_callout_model_json = {} turn_event_callout_callout_model_json['type'] = 'integration_interaction' turn_event_callout_callout_model_json['internal'] = {'anyKey': 'anyValue'} turn_event_callout_callout_model_json['result_variable'] = 'testString' + turn_event_callout_callout_model_json['request'] = turn_event_callout_callout_request_model + turn_event_callout_callout_model_json['response'] = turn_event_callout_callout_response_model # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation turn_event_callout_callout_model = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json) @@ -8680,6 +11898,73 @@ def test_turn_event_callout_callout_serialization(self): assert turn_event_callout_callout_model_json2 == turn_event_callout_callout_model_json +class TestModel_TurnEventCalloutCalloutRequest: + """ + Test Class for TurnEventCalloutCalloutRequest + """ + + def test_turn_event_callout_callout_request_serialization(self): + """ + Test serialization/deserialization for TurnEventCalloutCalloutRequest + """ + + # Construct a json representation of a TurnEventCalloutCalloutRequest model + turn_event_callout_callout_request_model_json = {} + turn_event_callout_callout_request_model_json['method'] = 'get' + turn_event_callout_callout_request_model_json['url'] = 'testString' + turn_event_callout_callout_request_model_json['path'] = 'testString' + turn_event_callout_callout_request_model_json['query_parameters'] = 'testString' + turn_event_callout_callout_request_model_json['headers'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_request_model_json['body'] = {'anyKey': 'anyValue'} + + # Construct a model instance of TurnEventCalloutCalloutRequest by calling from_dict on the json representation + turn_event_callout_callout_request_model = TurnEventCalloutCalloutRequest.from_dict(turn_event_callout_callout_request_model_json) + assert turn_event_callout_callout_request_model != False + + # Construct a model instance of TurnEventCalloutCalloutRequest by calling from_dict on the json representation + turn_event_callout_callout_request_model_dict = TurnEventCalloutCalloutRequest.from_dict(turn_event_callout_callout_request_model_json).__dict__ + turn_event_callout_callout_request_model2 = TurnEventCalloutCalloutRequest(**turn_event_callout_callout_request_model_dict) + + # Verify the model instances are equivalent + assert turn_event_callout_callout_request_model == turn_event_callout_callout_request_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_callout_callout_request_model_json2 = turn_event_callout_callout_request_model.to_dict() + assert turn_event_callout_callout_request_model_json2 == turn_event_callout_callout_request_model_json + + +class TestModel_TurnEventCalloutCalloutResponse: + """ + Test Class for TurnEventCalloutCalloutResponse + """ + + def test_turn_event_callout_callout_response_serialization(self): + """ + Test serialization/deserialization for TurnEventCalloutCalloutResponse + """ + + # Construct a json representation of a TurnEventCalloutCalloutResponse model + turn_event_callout_callout_response_model_json = {} + turn_event_callout_callout_response_model_json['body'] = 'testString' + turn_event_callout_callout_response_model_json['status_code'] = 38 + turn_event_callout_callout_response_model_json['last_event'] = {'anyKey': 'anyValue'} + + # Construct a model instance of TurnEventCalloutCalloutResponse by calling from_dict on the json representation + turn_event_callout_callout_response_model = TurnEventCalloutCalloutResponse.from_dict(turn_event_callout_callout_response_model_json) + assert turn_event_callout_callout_response_model != False + + # Construct a model instance of TurnEventCalloutCalloutResponse by calling from_dict on the json representation + turn_event_callout_callout_response_model_dict = TurnEventCalloutCalloutResponse.from_dict(turn_event_callout_callout_response_model_json).__dict__ + turn_event_callout_callout_response_model2 = TurnEventCalloutCalloutResponse(**turn_event_callout_callout_response_model_dict) + + # Verify the model instances are equivalent + assert turn_event_callout_callout_response_model == turn_event_callout_callout_response_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_callout_callout_response_model_json2 = turn_event_callout_callout_response_model.to_dict() + assert turn_event_callout_callout_response_model_json2 == turn_event_callout_callout_response_model_json + + class TestModel_TurnEventCalloutError: """ Test Class for TurnEventCalloutError @@ -8773,6 +12058,101 @@ def test_turn_event_search_error_serialization(self): assert turn_event_search_error_model_json2 == turn_event_search_error_model_json +class TestModel_UpdateEnvironmentOrchestration: + """ + Test Class for UpdateEnvironmentOrchestration + """ + + def test_update_environment_orchestration_serialization(self): + """ + Test serialization/deserialization for UpdateEnvironmentOrchestration + """ + + # Construct a json representation of a UpdateEnvironmentOrchestration model + update_environment_orchestration_model_json = {} + update_environment_orchestration_model_json['search_skill_fallback'] = True + + # Construct a model instance of UpdateEnvironmentOrchestration by calling from_dict on the json representation + update_environment_orchestration_model = UpdateEnvironmentOrchestration.from_dict(update_environment_orchestration_model_json) + assert update_environment_orchestration_model != False + + # Construct a model instance of UpdateEnvironmentOrchestration by calling from_dict on the json representation + update_environment_orchestration_model_dict = UpdateEnvironmentOrchestration.from_dict(update_environment_orchestration_model_json).__dict__ + update_environment_orchestration_model2 = UpdateEnvironmentOrchestration(**update_environment_orchestration_model_dict) + + # Verify the model instances are equivalent + assert update_environment_orchestration_model == update_environment_orchestration_model2 + + # Convert model instance back to dict and verify no loss of data + update_environment_orchestration_model_json2 = update_environment_orchestration_model.to_dict() + assert update_environment_orchestration_model_json2 == update_environment_orchestration_model_json + + +class TestModel_UpdateEnvironmentReleaseReference: + """ + Test Class for UpdateEnvironmentReleaseReference + """ + + def test_update_environment_release_reference_serialization(self): + """ + Test serialization/deserialization for UpdateEnvironmentReleaseReference + """ + + # Construct a json representation of a UpdateEnvironmentReleaseReference model + update_environment_release_reference_model_json = {} + update_environment_release_reference_model_json['release'] = 'testString' + + # Construct a model instance of UpdateEnvironmentReleaseReference by calling from_dict on the json representation + update_environment_release_reference_model = UpdateEnvironmentReleaseReference.from_dict(update_environment_release_reference_model_json) + assert update_environment_release_reference_model != False + + # Construct a model instance of UpdateEnvironmentReleaseReference by calling from_dict on the json representation + update_environment_release_reference_model_dict = UpdateEnvironmentReleaseReference.from_dict(update_environment_release_reference_model_json).__dict__ + update_environment_release_reference_model2 = UpdateEnvironmentReleaseReference(**update_environment_release_reference_model_dict) + + # Verify the model instances are equivalent + assert update_environment_release_reference_model == update_environment_release_reference_model2 + + # Convert model instance back to dict and verify no loss of data + update_environment_release_reference_model_json2 = update_environment_release_reference_model.to_dict() + assert update_environment_release_reference_model_json2 == update_environment_release_reference_model_json + + +class TestModel_CompleteItem: + """ + Test Class for CompleteItem + """ + + def test_complete_item_serialization(self): + """ + Test serialization/deserialization for CompleteItem + """ + + # Construct dict forms of any model objects needed in order to build this model. + + metadata_model = {} # Metadata + metadata_model['id'] = 38 + + # Construct a json representation of a CompleteItem model + complete_item_model_json = {} + complete_item_model_json['streaming_metadata'] = metadata_model + + # Construct a model instance of CompleteItem by calling from_dict on the json representation + complete_item_model = CompleteItem.from_dict(complete_item_model_json) + assert complete_item_model != False + + # Construct a model instance of CompleteItem by calling from_dict on the json representation + complete_item_model_dict = CompleteItem.from_dict(complete_item_model_json).__dict__ + complete_item_model2 = CompleteItem(**complete_item_model_dict) + + # Verify the model instances are equivalent + assert complete_item_model == complete_item_model2 + + # Convert model instance back to dict and verify no loss of data + complete_item_model_json2 = complete_item_model.to_dict() + assert complete_item_model_json2 == complete_item_model_json + + class TestModel_LogMessageSourceAction: """ Test Class for LogMessageSourceAction @@ -9004,10 +12384,25 @@ def test_message_output_debug_turn_event_turn_event_callout_serialization(self): turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' + turn_event_callout_callout_request_model = {} # TurnEventCalloutCalloutRequest + turn_event_callout_callout_request_model['method'] = 'get' + turn_event_callout_callout_request_model['url'] = 'testString' + turn_event_callout_callout_request_model['path'] = 'testString' + turn_event_callout_callout_request_model['query_parameters'] = 'testString' + turn_event_callout_callout_request_model['headers'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_request_model['body'] = {'anyKey': 'anyValue'} + + turn_event_callout_callout_response_model = {} # TurnEventCalloutCalloutResponse + turn_event_callout_callout_response_model['body'] = 'testString' + turn_event_callout_callout_response_model['status_code'] = 38 + turn_event_callout_callout_response_model['last_event'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_model = {} # TurnEventCalloutCallout turn_event_callout_callout_model['type'] = 'integration_interaction' turn_event_callout_callout_model['internal'] = {'anyKey': 'anyValue'} turn_event_callout_callout_model['result_variable'] = 'testString' + turn_event_callout_callout_model['request'] = turn_event_callout_callout_request_model + turn_event_callout_callout_model['response'] = turn_event_callout_callout_response_model turn_event_callout_error_model = {} # TurnEventCalloutError turn_event_callout_error_model['message'] = 'testString' @@ -9242,6 +12637,339 @@ def test_message_output_debug_turn_event_turn_event_step_visited_serialization(s assert message_output_debug_turn_event_turn_event_step_visited_model_json2 == message_output_debug_turn_event_turn_event_step_visited_model_json +class TestModel_ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode: + """ + Test Class for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode + """ + + def test_provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_serialization(self): + """ + Test serialization/deserialization for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode + """ + + # Construct a json representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode model + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json = {} + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['token_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['content_type'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['authorization_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json['redirect_uri'] = 'testString' + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json) + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model != False + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_dict = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json).__dict__ + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model2 = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode(**provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_dict) + + # Verify the model instances are equivalent + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model2 + + # Convert model instance back to dict and verify no loss of data + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json2 = provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model.to_dict() + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json2 == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_authorization_code_model_json + + +class TestModel_ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials: + """ + Test Class for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials + """ + + def test_provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_serialization(self): + """ + Test serialization/deserialization for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials + """ + + # Construct a json representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials model + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json = {} + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json['token_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json['content_type'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json['header_prefix'] = 'testString' + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json) + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model != False + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_dict = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json).__dict__ + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model2 = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials(**provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_dict) + + # Verify the model instances are equivalent + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model2 + + # Convert model instance back to dict and verify no loss of data + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json2 = provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model.to_dict() + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json2 == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_client_credentials_model_json + + +class TestModel_ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password: + """ + Test Class for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + """ + + def test_provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_serialization(self): + """ + Test serialization/deserialization for ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + """ + + # Construct dict forms of any model objects needed in order to build this model. + + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + # Construct a json representation of a ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password model + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json = {} + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['token_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['content_type'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json['username'] = provider_authentication_o_auth2_password_username_model + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json) + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model != False + + # Construct a model instance of ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password by calling from_dict on the json representation + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_dict = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password.from_dict(provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json).__dict__ + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model2 = ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password(**provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_dict) + + # Verify the model instances are equivalent + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model2 + + # Convert model instance back to dict and verify no loss of data + provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json2 = provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model.to_dict() + assert provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json2 == provider_authentication_o_auth2_flows_provider_authentication_o_auth2_password_model_json + + +class TestModel_ProviderPrivateAuthenticationBasicFlow: + """ + Test Class for ProviderPrivateAuthenticationBasicFlow + """ + + def test_provider_private_authentication_basic_flow_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationBasicFlow + """ + + # Construct dict forms of any model objects needed in order to build this model. + + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a json representation of a ProviderPrivateAuthenticationBasicFlow model + provider_private_authentication_basic_flow_model_json = {} + provider_private_authentication_basic_flow_model_json['password'] = provider_authentication_type_and_value_model + + # Construct a model instance of ProviderPrivateAuthenticationBasicFlow by calling from_dict on the json representation + provider_private_authentication_basic_flow_model = ProviderPrivateAuthenticationBasicFlow.from_dict(provider_private_authentication_basic_flow_model_json) + assert provider_private_authentication_basic_flow_model != False + + # Construct a model instance of ProviderPrivateAuthenticationBasicFlow by calling from_dict on the json representation + provider_private_authentication_basic_flow_model_dict = ProviderPrivateAuthenticationBasicFlow.from_dict(provider_private_authentication_basic_flow_model_json).__dict__ + provider_private_authentication_basic_flow_model2 = ProviderPrivateAuthenticationBasicFlow(**provider_private_authentication_basic_flow_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_basic_flow_model == provider_private_authentication_basic_flow_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_basic_flow_model_json2 = provider_private_authentication_basic_flow_model.to_dict() + assert provider_private_authentication_basic_flow_model_json2 == provider_private_authentication_basic_flow_model_json + + +class TestModel_ProviderPrivateAuthenticationBearerFlow: + """ + Test Class for ProviderPrivateAuthenticationBearerFlow + """ + + def test_provider_private_authentication_bearer_flow_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationBearerFlow + """ + + # Construct dict forms of any model objects needed in order to build this model. + + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a json representation of a ProviderPrivateAuthenticationBearerFlow model + provider_private_authentication_bearer_flow_model_json = {} + provider_private_authentication_bearer_flow_model_json['token'] = provider_authentication_type_and_value_model + + # Construct a model instance of ProviderPrivateAuthenticationBearerFlow by calling from_dict on the json representation + provider_private_authentication_bearer_flow_model = ProviderPrivateAuthenticationBearerFlow.from_dict(provider_private_authentication_bearer_flow_model_json) + assert provider_private_authentication_bearer_flow_model != False + + # Construct a model instance of ProviderPrivateAuthenticationBearerFlow by calling from_dict on the json representation + provider_private_authentication_bearer_flow_model_dict = ProviderPrivateAuthenticationBearerFlow.from_dict(provider_private_authentication_bearer_flow_model_json).__dict__ + provider_private_authentication_bearer_flow_model2 = ProviderPrivateAuthenticationBearerFlow(**provider_private_authentication_bearer_flow_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_bearer_flow_model == provider_private_authentication_bearer_flow_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_bearer_flow_model_json2 = provider_private_authentication_bearer_flow_model.to_dict() + assert provider_private_authentication_bearer_flow_model_json2 == provider_private_authentication_bearer_flow_model_json + + +class TestModel_ProviderPrivateAuthenticationOAuth2Flow: + """ + Test Class for ProviderPrivateAuthenticationOAuth2Flow + """ + + def test_provider_private_authentication_o_auth2_flow_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2Flow + """ + + # Construct dict forms of any model objects needed in order to build this model. + + provider_private_authentication_o_auth2_password_password_model = {} # ProviderPrivateAuthenticationOAuth2PasswordPassword + provider_private_authentication_o_auth2_password_password_model['type'] = 'value' + provider_private_authentication_o_auth2_password_password_model['value'] = 'testString' + + provider_private_authentication_o_auth2_flow_flows_model = {} # ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password + provider_private_authentication_o_auth2_flow_flows_model['client_id'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_model['client_secret'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_model['access_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_model['refresh_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_model['password'] = provider_private_authentication_o_auth2_password_password_model + + # Construct a json representation of a ProviderPrivateAuthenticationOAuth2Flow model + provider_private_authentication_o_auth2_flow_model_json = {} + provider_private_authentication_o_auth2_flow_model_json['flows'] = provider_private_authentication_o_auth2_flow_flows_model + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2Flow by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_model = ProviderPrivateAuthenticationOAuth2Flow.from_dict(provider_private_authentication_o_auth2_flow_model_json) + assert provider_private_authentication_o_auth2_flow_model != False + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2Flow by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_model_dict = ProviderPrivateAuthenticationOAuth2Flow.from_dict(provider_private_authentication_o_auth2_flow_model_json).__dict__ + provider_private_authentication_o_auth2_flow_model2 = ProviderPrivateAuthenticationOAuth2Flow(**provider_private_authentication_o_auth2_flow_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_o_auth2_flow_model == provider_private_authentication_o_auth2_flow_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_o_auth2_flow_model_json2 = provider_private_authentication_o_auth2_flow_model.to_dict() + assert provider_private_authentication_o_auth2_flow_model_json2 == provider_private_authentication_o_auth2_flow_model_json + + +class TestModel_ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode: + """ + Test Class for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode + """ + + def test_provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode + """ + + # Construct a json representation of a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode model + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json = {} + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json['client_id'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json['client_secret'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json['access_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json['refresh_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json['authorization_code'] = 'testString' + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json) + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model != False + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_dict = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json).__dict__ + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model2 = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode(**provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json2 = provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model.to_dict() + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json2 == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_authorization_code_model_json + + +class TestModel_ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials: + """ + Test Class for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials + """ + + def test_provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials + """ + + # Construct a json representation of a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials model + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json = {} + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json['client_id'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json['client_secret'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json['access_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json['refresh_token'] = 'testString' + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json) + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model != False + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_dict = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json).__dict__ + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model2 = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials(**provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json2 = provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model.to_dict() + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json2 == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_client_credentials_model_json + + +class TestModel_ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password: + """ + Test Class for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password + """ + + def test_provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_serialization(self): + """ + Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password + """ + + # Construct dict forms of any model objects needed in order to build this model. + + provider_private_authentication_o_auth2_password_password_model = {} # ProviderPrivateAuthenticationOAuth2PasswordPassword + provider_private_authentication_o_auth2_password_password_model['type'] = 'value' + provider_private_authentication_o_auth2_password_password_model['value'] = 'testString' + + # Construct a json representation of a ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password model + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json = {} + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json['client_id'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json['client_secret'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json['access_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json['refresh_token'] = 'testString' + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json['password'] = provider_private_authentication_o_auth2_password_password_model + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json) + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model != False + + # Construct a model instance of ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password by calling from_dict on the json representation + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_dict = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password.from_dict(provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json).__dict__ + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model2 = ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password(**provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_dict) + + # Verify the model instances are equivalent + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model2 + + # Convert model instance back to dict and verify no loss of data + provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json2 = provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model.to_dict() + assert provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json2 == provider_private_authentication_o_auth2_flow_flows_provider_private_authentication_o_auth2_password_model_json + + class TestModel_RuntimeResponseGenericRuntimeResponseTypeAudio: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeAudio From 8692b136abfe68c049bf0474b0bf6b242510cf57 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 22 Nov 2024 12:29:29 -0500 Subject: [PATCH 436/455] feat(common): add parse_sse_stream_data function This function parses the raw buffer recieved from sse requests and yields a parsed dictionary --- ibm_watson/common.py | 23 +++++++++- test/integration/test_assistant_v2.py | 65 +++++++++++++++++++++++++++ 2 files changed, 87 insertions(+), 1 deletion(-) create mode 100644 test/integration/test_assistant_v2.py diff --git a/ibm_watson/common.py b/ibm_watson/common.py index 81ecc7ec0..a1595d614 100644 --- a/ibm_watson/common.py +++ b/ibm_watson/common.py @@ -1,6 +1,6 @@ # coding: utf-8 -# Copyright 2019 IBM All Rights Reserved. +# Copyright 2019, 2024 IBM All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,7 +15,9 @@ # limitations under the License. import platform +import json from .version import __version__ +from typing import Iterator SDK_ANALYTICS_HEADER = 'X-IBMCloud-SDK-Analytics' USER_AGENT_HEADER = 'User-Agent' @@ -48,3 +50,22 @@ def get_sdk_headers(service_name, service_version, operation_id): operation_id) headers[USER_AGENT_HEADER] = get_user_agent() return headers + + +def parse_sse_stream_data(response) -> Iterator[dict]: + event_message = None # Can be used in the future to return the event message to the user + data_json = None + + for chunk in response.iter_lines(): + decoded_chunk = chunk.decode("utf-8") + + if decoded_chunk.find("event", 0, len("event")) == 0: + event_message = decoded_chunk[len("event") + 2:] + elif decoded_chunk.find("data", 0, len("data")) == 0: + data_json_str = decoded_chunk[len("data") + 2:] + data_json = json.loads(data_json_str) + + if event_message and data_json is not None: + yield data_json + event_message = None + data_json = None diff --git a/test/integration/test_assistant_v2.py b/test/integration/test_assistant_v2.py new file mode 100644 index 000000000..db17bcae0 --- /dev/null +++ b/test/integration/test_assistant_v2.py @@ -0,0 +1,65 @@ +# coding: utf-8 + +# Copyright 2019, 2024 IBM All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from unittest import TestCase +import ibm_watson +from ibm_watson.assistant_v2 import MessageInput +from ibm_watson.common import parse_sse_stream_data +import pytest +import json +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator + +class TestAssistantV2(TestCase): + + def setUp(self): + + with open('./auth.json') as f: + data = json.load(f) + assistant_auth = data.get("assistantv2") + self.assistant_id = assistant_auth.get("assistantId") + self.environment_id = assistant_auth.get("environmentId") + + self.authenticator = IAMAuthenticator(apikey=assistant_auth.get("apikey")) + self.assistant = ibm_watson.AssistantV2(version='2024-08-25', authenticator=self.authenticator) + self.assistant.set_service_url(assistant_auth.get("serviceUrl")) + self.assistant.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) + + def test_list_assistants(self): + response = self.assistant.list_assistants().get_result() + assert response is not None + + def test_message_stream_stateless(self): + input = MessageInput(message_type="text", text="can you list the steps to create a custom extension?") + user_id = "Angelo" + + response = self.assistant.message_stream_stateless(self.assistant_id, self.environment_id, input=input, user_id=user_id).get_result() + + for data in parse_sse_stream_data(response): + # One of these items must exist + # assert "partial_item" in data_json or "complete_item" in data_json or "final_item" in data_json + + if "partial_item" in data: + assert data["partial_item"]["text"] is not None + elif "complete_item" in data: + assert data["complete_item"]["text"] is not None + elif "final_response" in data: + assert data["final_response"] is not None + else: + pytest.fail("Should be impossible to get here") + From 39ee7871bea970838007c38d7d4591cf5ba1cced Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 4 Dec 2024 12:37:52 -0600 Subject: [PATCH 437/455] build(actions): update tested python versions --- .github/workflows/build-test.yml | 37 ++++++++------------------------ 1 file changed, 9 insertions(+), 28 deletions(-) diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 4849b2f45..c5175d316 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -21,11 +21,8 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ['3.9', '3.10', '3.11'] - os: [ubuntu-latest, windows-latest] - exclude: - - os: windows-latest - python-version: '3.9' + python-version: ['3.11', '3.12', '3.13'] + os: [ubuntu-latest] steps: - uses: actions/checkout@v2 @@ -39,39 +36,23 @@ jobs: pip3 install -r requirements.txt pip3 install -r requirements-dev.txt pip3 install --editable . - - name: Install dependencies (windows) - if: matrix.os == 'windows-latest' - run: | - pip3 install -r requirements.txt --use-deprecated=legacy-resolver - pip3 install -r requirements-dev.txt --use-deprecated=legacy-resolver - pip3 install --editable . --use-deprecated=legacy-resolver - - name: Execute Python 3.9 unit tests - if: matrix.python-version == '3.9' + - name: Execute Python 3.11 unit tests + if: matrix.python-version == '3.11' run: | pip3 install -U python-dotenv py.test test/unit - - name: Execute Python 3.10 unit tests (windows) - if: matrix.python-version == '3.10' && matrix.os == 'windows-latest' - run: | - pip3 install -U python-dotenv - py.test test/unit --reruns 3 - - name: Execute Python 3.10 unit tests (ubuntu) - if: matrix.python-version == '3.10' && matrix.os == 'ubuntu-latest' + - name: Execute Python 3.12 unit tests (ubuntu) + if: matrix.python-version == '3.12' && matrix.os == 'ubuntu-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 --cov=ibm_watson - - name: Execute Python 3.11 unit tests (windows) - if: matrix.python-version == '3.11' && matrix.os == 'windows-latest' - run: | - pip3 install -U python-dotenv - py.test test/unit --reruns 3 - - name: Execute Python 3.11 unit tests (ubuntu) - if: matrix.python-version == '3.11' && matrix.os == 'ubuntu-latest' + - name: Execute Python 3.13 unit tests (ubuntu) + if: matrix.python-version == '3.13' && matrix.os == 'ubuntu-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 - name: Upload coverage to Codecov - if: matrix.python-version == '3.10' && matrix.os == 'ubuntu-latest' + if: matrix.python-version == '3.12' && matrix.os == 'ubuntu-latest' uses: codecov/codecov-action@v1 with: name: py${{ matrix.python-version }}-${{ matrix.os }} From 1929ceb86598f3be03aedb5ebc0e991e3e21396e Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 4 Dec 2024 17:05:38 -0600 Subject: [PATCH 438/455] chore: update changelog and version numbers --- .bumpversion.cfg | 2 +- .github/workflows/deploy.yml | 2 +- CHANGELOG.md | 20 ++++++++++++++++++++ ibm_watson/version.py | 2 +- setup.py | 2 +- 5 files changed, 24 insertions(+), 4 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 9a2744e14..654bd4b5a 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 8.1.0 +current_version = 9.0.0 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 45b7fee7c..3b58867e7 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -62,7 +62,7 @@ jobs: env: GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN }} - run: npx semantic-release #--dry-run --branches 9388_gha Uncomment for testxing purposes + run: npx semantic-release #--dry-run --branches 9388_gha Uncomment for testing purposes - name: Build binary wheel and a source tarball run: | diff --git a/CHANGELOG.md b/CHANGELOG.md index 1c3541a5e..d3d27edf0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,23 @@ +# [9.0.0](https://github.com/watson-developer-cloud/python-sdk/compare/v8.1.0...v9.0.0) (2024-12-04) + + +### Features + +* **discov2:** add functions for new batches api ([043eed4](https://github.com/watson-developer-cloud/python-sdk/commit/043eed48f1808ad3c0c325be18e2bd7ecc339c14)) +* **stt:** add new speech models ([4948b8f](https://github.com/watson-developer-cloud/python-sdk/commit/4948b8f210e5b9cd2d856aa90f2262a8bdf64444)) +* **stt:** readd interimResults and lowLatency wss params ([ffc67b8](https://github.com/watson-developer-cloud/python-sdk/commit/ffc67b8a0b213530cda23157848d79b5fea4b146)) +* **WxA:** add new functions and update required params ([3fe6243](https://github.com/watson-developer-cloud/python-sdk/commit/3fe62430c57e660b0903b0988fa3c53c489012d3)) +* Add support for message streaming and new APIs + +New functions: create_providers, list_providers, update_providers, create_release_export, download_release_export, create_release_import, get_release_import_status, message_stream, message_stream_stateless, parse_sse_stream_data, list_batches, pull_batches, push_batches + +### BREAKING CHANGES + +* **WxA:** `environmentId` now required for `message` and `messageStateless` functions +* **lt:** LanguageTranslator functionality has been removed +* **discov1:** DiscoveryV1 functionality has been removed +* **nlu:** training_data_content_type default changed to None + # [8.1.0](https://github.com/watson-developer-cloud/python-sdk/compare/v8.0.0...v8.1.0) (2024-05-17) diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 2d63b74a6..33de8d16f 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '8.1.0' +__version__ = '9.0.0' diff --git a/setup.py b/setup.py index 3e639723e..9fd6acf31 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '8.1.0' +__version__ = '9.0.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From 859db477c3d430e2ca87e60f89be74e4d3bdd1f5 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 15 Jan 2025 08:21:17 -0600 Subject: [PATCH 439/455] docs(ctr): add bug bounty hunter revoked keys notice (#854) --- CONTRIBUTING.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c431459c8..3fbf576f1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -49,6 +49,9 @@ You probably want to set up a [virtualenv]. py.test test ``` +## Bug Bounty Hunters Notice +API keys found from commit bec3ae23b53782370851e28cbda5033a596b58b5 have already been revoked and will not be accepted for bug bounties. + ## Additional Resources - [General GitHub documentation](https://help.github.com/) From 9679858f886b3da07faa9e551aaef89260347623 Mon Sep 17 00:00:00 2001 From: Darragh McGonigle Date: Fri, 13 Jun 2025 14:42:00 +0100 Subject: [PATCH 440/455] chore(comments): Add comment changes to discovery --- ibm_watson/discovery_v2.py | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index f9a994904..642007426 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2024. +# (C) Copyright IBM Corp. 2019, 2025. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 +# IBM OpenAPI SDK Code Generator Version: 3.105.0-3c13b041-20250605-193116 """ IBM Watson® Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive better @@ -1206,6 +1206,23 @@ def delete_document( remove subdocuments that are generated by an uploaded file, delete the original document instead. You can get the document ID of the original document from the `parent_document_id` of the subdocument result. + If the document with the given document ID exists, Watson Discovery first marks or + tags the document as deleted when it sends the 200 response code. At a later time + (within a couple of minutes unless the document has many child documents), it + removes the document from the collection. + There is no bulk document delete API. Documents must be deleted one at a time + using this API. However, you can delete a collection, and all the documents from + the collection are removed along with the collection. + The document will be deleted from the given collection only, not from the + corresponding data source. Wherever relevant, an incremental crawl will not bring + back the document into Watson Discovery from the data source. Only a full crawl + will retrieve the deleted document back from the data source provided it is still + present in the same data source. + Finally, if multiple collections share the same dataset, deleting a document from + a collection will remove it from that collection only (in other remaining + collections the document will still exist). The document will be removed from the + dataset, if this document is deleted from all the collections that share the same + dataset. :param str project_id: The Universally Unique Identifier (UUID) of the project. This information can be found from the *Integrate and Deploy* page From 463ae836699a3f08213cc86ff3e99004153ac436 Mon Sep 17 00:00:00 2001 From: Darragh McGonigle Date: Fri, 13 Jun 2025 14:43:08 +0100 Subject: [PATCH 441/455] feat(stt&tts): Add new model enum values --- ibm_watson/speech_to_text_v1.py | 7 +++++-- ibm_watson/text_to_speech_v1.py | 31 ++++++++++++++++++++++--------- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 459564a85..1f413afb7 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2024. +# (C) Copyright IBM Corp. 2015, 2025. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 +# IBM OpenAPI SDK Code Generator Version: 3.105.0-3c13b041-20250605-193116 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's speech-recognition capabilities to produce transcripts of spoken audio. The service can @@ -4309,6 +4309,7 @@ class ModelId(str, Enum): AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' + DE_DE = 'de-DE' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' @@ -4438,6 +4439,7 @@ class Model(str, Enum): AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' + DE_DE = 'de-DE' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' @@ -4567,6 +4569,7 @@ class Model(str, Enum): AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' CS_CZ_TELEPHONY = 'cs-CZ_Telephony' + DE_DE = 'de-DE' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 145fdcae3..5cdac13f3 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2024. +# (C) Copyright IBM Corp. 2015, 2025. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 +# IBM OpenAPI SDK Code Generator Version: 3.105.0-3c13b041-20250605-193116 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, @@ -232,31 +232,32 @@ def synthesize( * `audio/alaw` - You must specify the `rate` of the audio. * `audio/basic` - The service returns audio with a sampling rate of 8000 Hz. * `audio/flac` - You can optionally specify the `rate` of the audio. The default - sampling rate is 22,050 Hz. + sampling rate is 24,000 Hz for Natural voices and 22,050 Hz for all other voices. * `audio/l16` - You must specify the `rate` of the audio. You can optionally specify the `endianness` of the audio. The default endianness is `little-endian`. * `audio/mp3` - You can optionally specify the `rate` of the audio. The default - sampling rate is 22,050 Hz. + sampling rate is 24,000 Hz for Natural voices and 22,050 Hz for for all other + voices. * `audio/mpeg` - You can optionally specify the `rate` of the audio. The default - sampling rate is 22,050 Hz. + sampling rate is 24,000 Hz for Natural voices and 22,050 Hz for all other voices. * `audio/mulaw` - You must specify the `rate` of the audio. * `audio/ogg` - The service returns the audio in the `vorbis` codec. You can - optionally specify the `rate` of the audio. The default sampling rate is 22,050 + optionally specify the `rate` of the audio. The default sampling rate is 48,000 Hz. * `audio/ogg;codecs=opus` - You can optionally specify the `rate` of the audio. Only the following values are valid sampling rates: `48000`, `24000`, `16000`, `12000`, or `8000`. If you specify a value other than one of these, the service returns an error. The default sampling rate is 48,000 Hz. * `audio/ogg;codecs=vorbis` - You can optionally specify the `rate` of the audio. - The default sampling rate is 22,050 Hz. + The default sampling rate is 48,000 Hz. * `audio/wav` - You can optionally specify the `rate` of the audio. The default - sampling rate is 22,050 Hz. + sampling rate is 24,000 Hz for Natural voices and 22,050 Hz for all other voices. * `audio/webm` - The service returns the audio in the `opus` codec. The service returns audio with a sampling rate of 48,000 Hz. * `audio/webm;codecs=opus` - The service returns audio with a sampling rate of 48,000 Hz. * `audio/webm;codecs=vorbis` - You can optionally specify the `rate` of the audio. - The default sampling rate is 22,050 Hz. + The default sampling rate is 48,000 Hz. For more information about specifying an audio format, including additional details about some of the formats, see [Using audio formats](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-audio-formats). @@ -1808,10 +1809,12 @@ class Voice(str, Enum): EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_GEORGEEXPRESSIVE = 'en-GB_GeorgeExpressive' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_ELLIENATURAL = 'en-US_EllieNatural' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' @@ -1823,6 +1826,7 @@ class Voice(str, Enum): EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' + ES_LA_DANIELAEXPRESSIVE = 'es-LA_DanielaExpressive' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' @@ -1833,6 +1837,7 @@ class Voice(str, Enum): KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + PT_BR_LUCASEXPRESSIVE = 'pt-BR_LucasExpressive' class SynthesizeEnums: @@ -1883,10 +1888,12 @@ class Voice(str, Enum): EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_GEORGEEXPRESSIVE = 'en-GB_GeorgeExpressive' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_ELLIENATURAL = 'en-US_EllieNatural' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' @@ -1898,6 +1905,7 @@ class Voice(str, Enum): EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' + ES_LA_DANIELAEXPRESSIVE = 'es-LA_DanielaExpressive' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' @@ -1908,6 +1916,7 @@ class Voice(str, Enum): KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + PT_BR_LUCASEXPRESSIVE = 'pt-BR_LucasExpressive' class SpellOutMode(str, Enum): """ @@ -1957,10 +1966,12 @@ class Voice(str, Enum): EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_GEORGEEXPRESSIVE = 'en-GB_GeorgeExpressive' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' + EN_US_ELLIENATURAL = 'en-US_EllieNatural' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' @@ -1972,6 +1983,7 @@ class Voice(str, Enum): EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' + ES_LA_DANIELAEXPRESSIVE = 'es-LA_DanielaExpressive' ES_LA_SOFIAV3VOICE = 'es-LA_SofiaV3Voice' ES_US_SOFIAV3VOICE = 'es-US_SofiaV3Voice' FR_CA_LOUISEV3VOICE = 'fr-CA_LouiseV3Voice' @@ -1982,6 +1994,7 @@ class Voice(str, Enum): KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + PT_BR_LUCASEXPRESSIVE = 'pt-BR_LucasExpressive' class Format(str, Enum): """ From cd53f30350497dc5f7d844d13481592e78125f19 Mon Sep 17 00:00:00 2001 From: Darragh McGonigle Date: Fri, 13 Jun 2025 14:46:06 +0100 Subject: [PATCH 442/455] feat(wav2): Add turn events and required properties BREAKING CHANGE - Add required search setting param conservation search --- ibm_watson/assistant_v2.py | 18680 +++++++++++++++++++------------ test/unit/test_assistant_v2.py | 10151 +++++++++++------ 2 files changed, 17991 insertions(+), 10840 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 31ff57d20..fec430c07 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2024. +# (C) Copyright IBM Corp. 2019, 2025. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.97.0-0e90eab1-20241120-170029 +# IBM OpenAPI SDK Code Generator Version: 3.105.0-3c13b041-20250605-193116 """ The IBM® watsonx™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -49,7 +49,7 @@ class AssistantV2(BaseService): """The Assistant V2 service.""" DEFAULT_SERVICE_URL = 'https://api.us-south.assistant.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'assistant' + DEFAULT_SERVICE_NAME = 'conversation' def __init__( self, @@ -61,7 +61,7 @@ def __init__( Construct a new client for the Assistant service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2023-06-15`. + Specify dates in YYYY-MM-DD format. The current version is `2024-08-25`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md @@ -428,17 +428,18 @@ def delete_assistant( Delete an assistant. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -498,17 +499,18 @@ def create_session( [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings).). :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param RequestAnalytics analytics: (optional) An optional object containing analytics data. Currently, this data is used only for events sent to the Segment extension. @@ -574,17 +576,18 @@ def delete_session( [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings)). :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str session_id: Unique identifier of the session. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -650,17 +653,18 @@ def message( session. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -759,17 +763,18 @@ def message_stateless( (including context data) managed by your application. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -870,17 +875,18 @@ def message_stream( session. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -979,17 +985,18 @@ def message_stream_stateless( (including context data) managed by your application. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -1086,9 +1093,11 @@ def bulk_classify( versions. This method is available only with Enterprise with Data Isolation plans. - :param str skill_id: Unique identifier of the skill. To find the skill ID - in the watsonx Assistant user interface, open the skill settings and click - **API Details**. + :param str skill_id: Unique identifier of the skill. To find the action or + dialog skill ID in the watsonx Assistant user interface, open the skill + settings and click **API Details**. To find the search skill ID, use the + Get environment API to retrieve the skill references for an environment and + it will include the search skill info, if available. :param List[BulkClassifyUtterance] input: An array of input utterances to classify. :param dict headers: A `dict` containing the request headers @@ -1166,17 +1175,18 @@ def list_logs( about using pagination, see [Pagination](#pagination). :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :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 (`-`). @@ -1314,17 +1324,18 @@ def list_environments( List the environments associated with an assistant. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param int page_limit: (optional) The number of records to return in each page of results. :param bool include_count: (optional) Whether to include information about @@ -1397,17 +1408,18 @@ def get_environment( [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -1476,17 +1488,18 @@ def update_environment( [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -1576,17 +1589,18 @@ def create_release( called a *version*.). :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str description: (optional) The description of the release. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1652,17 +1666,18 @@ def list_releases( interface, a release is called a *version*.). :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param int page_limit: (optional) The number of records to return in each page of results. :param bool include_count: (optional) Whether to include information about @@ -1737,17 +1752,18 @@ def get_release( has completed, the request returns the release data. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str release: Unique identifier of the release. :param bool include_audit: (optional) Whether to include the audit properties (`created` and `updated` timestamps) in the response. @@ -1806,17 +1822,18 @@ def delete_release( *version*.). :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str release: Unique identifier of the release. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1875,17 +1892,18 @@ def deploy_release( part of the release become active in the environment. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str release: Unique identifier of the release. :param str environment_id: The environment ID of the environment where the release is to be deployed. @@ -1964,17 +1982,18 @@ def create_release_export( (/scope) of the release. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str release: Unique identifier of the release. :param bool include_audit: (optional) Whether to include the audit properties (`created` and `updated` timestamps) in the response. @@ -2049,17 +2068,18 @@ def download_release_export( skill update endpoints.. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param str release: Unique identifier of the release. :param str accept: (optional) The type of the response: application/json or application/octet-stream. @@ -2138,17 +2158,18 @@ def create_release_import( Status" endpoint. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param BinaryIO body: Request body is an Octet-stream of the artifact Zip file that is being imported. :param bool include_audit: (optional) Whether to include the audit @@ -2212,17 +2233,18 @@ def get_release_import_status( until the status of the import has either succeeded or failed. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :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 @@ -2280,20 +2302,23 @@ def get_skill( Get information about a skill. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. - :param str skill_id: Unique identifier of the skill. To find the skill ID - in the watsonx Assistant user interface, open the skill settings and click - **API Details**. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. + :param str skill_id: Unique identifier of the skill. To find the action or + dialog skill ID in the watsonx Assistant user interface, open the skill + settings and click **API Details**. To find the search skill ID, use the + Get environment API to retrieve the skill references for an environment and + it will include the search skill info, if available. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Skill` object @@ -2356,20 +2381,23 @@ def update_skill( **status** property. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. - :param str skill_id: Unique identifier of the skill. To find the skill ID - in the watsonx Assistant user interface, open the skill settings and click - **API Details**. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. + :param str skill_id: Unique identifier of the skill. To find the action or + dialog skill ID in the watsonx Assistant user interface, open the skill + settings and click **API Details**. To find the search skill ID, use the + Get environment API to retrieve the skill references for an environment and + it will include the search skill info, if available. :param str name: (optional) The name of the skill. This string cannot contain carriage return, newline, or tab characters. :param str description: (optional) The description of the skill. This @@ -2447,8 +2475,9 @@ def export_skills( Export skills. Asynchronously export the action skill and dialog skill (if enabled) for the - assistant. Use this method to save all skill data so that you can import it to a - different assistant using the **Import skills** method. + assistant. Use this method to save all skill data from the draft environment so + that you can import it to a different assistant using the **Import skills** + method. Use `assistant_id` instead of `environment_id` to call this endpoint. A successful call to this method only initiates an asynchronous export. The exported JSON data is not available until processing completes. After the initial request is submitted, you can poll the status of the operation @@ -2461,17 +2490,18 @@ def export_skills( Remember that the usual rate limits apply. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :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 @@ -2527,7 +2557,8 @@ def import_skills( Import skills. Asynchronously import skills into an existing assistant from a previously exported - file. + file. This method only imports assistants into a draft environment. Use + `assistant_id` instead of `environment_id` to call this endpoint. The request body for this method should contain the response data that was received from a previous call to the **Export skills** method, without modification. @@ -2537,17 +2568,18 @@ def import_skills( skills import** method. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param List[SkillImport] assistant_skills: An array of objects describing the skills for the assistant. Included in responses only if **status**=`Available`. @@ -2622,17 +2654,18 @@ def import_skills_status( using the **Import skills** method. :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed, depending on the type of - request: - - For message, session, and log requests, specify the environment ID of + environment where the assistant is deployed. + Set the value for this ID depending on the type of request: + - For message, session, and log requests, specify the environment ID of the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To find the environment ID or assistant ID in the watsonx Assistant user - interface, open the assistant settings and scroll to the **Environments** - section. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. To find the assistant ID in the user interface, open - the assistant settings and click API Details. + - For all other requests, specify the assistant ID of the assistant. + To get the **assistant ID** and **environment ID** in the watsonx + Assistant interface, open the **Assistant settings** page, and scroll to + the **Assistant IDs and API details** section and click **View Details**. + **Note:** If you are using the classic Watson Assistant experience, always + use the assistant ID. + To find the **assistant ID** in the user interface, open the **Assistant + settings** and click **API Details**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object @@ -3794,6 +3827,111 @@ def __ne__(self, other: 'ChannelTransferTargetChat') -> bool: return not self == other +class ClientAction: + """ + ClientAction. + + :param str name: (optional) The name of the client action. + :param str result_variable: (optional) The name of the variable that the results + are stored in. + :param str type: (optional) The type of turn event. + :param str skill: (optional) The skill that is requesting the action. Included + only if **type**=`client`. + :param dict parameters: (optional) An object containing arbitrary variables that + are included in the turn event. + """ + + def __init__( + self, + *, + name: Optional[str] = None, + result_variable: Optional[str] = None, + type: Optional[str] = None, + skill: Optional[str] = None, + parameters: Optional[dict] = None, + ) -> None: + """ + Initialize a ClientAction object. + + :param str name: (optional) The name of the client action. + :param str result_variable: (optional) The name of the variable that the + results are stored in. + :param str type: (optional) The type of turn event. + :param str skill: (optional) The skill that is requesting the action. + Included only if **type**=`client`. + :param dict parameters: (optional) An object containing arbitrary variables + that are included in the turn event. + """ + self.name = name + self.result_variable = result_variable + self.type = type + self.skill = skill + self.parameters = parameters + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ClientAction': + """Initialize a ClientAction object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable + if (type := _dict.get('type')) is not None: + args['type'] = type + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill + if (parameters := _dict.get('parameters')) is not None: + args['parameters'] = parameters + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ClientAction 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + if hasattr(self, 'parameters') and self.parameters is not None: + _dict['parameters'] = self.parameters + 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 ClientAction object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ClientAction') -> 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: 'ClientAction') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class SkillEnum(str, Enum): + """ + The skill that is requesting the action. Included only if **type**=`client`. + """ + + MAIN_SKILL = 'main skill' + ACTIONS_SKILL = 'actions skill' + + class CreateAssistantReleaseImportResponse: """ CreateAssistantReleaseImportResponse. @@ -5223,52 +5361,119 @@ class TypeEnum(str, Enum): SEARCH = 'search' -class IntegrationReference: +class FinalResponse: """ - IntegrationReference. + Message final response content. - :param str integration_id: (optional) The integration ID of the integration. - :param str type: (optional) The type of the integration. + :param FinalResponseOutput output: (optional) Assistant output to be rendered or + processed by the client. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. """ def __init__( self, *, - integration_id: Optional[str] = None, - type: Optional[str] = None, + output: Optional['FinalResponseOutput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, ) -> None: """ - Initialize a IntegrationReference object. + Initialize a FinalResponse object. - :param str integration_id: (optional) The integration ID of the - integration. - :param str type: (optional) The type of the integration. + :param FinalResponseOutput output: (optional) Assistant output to be + rendered or processed by the client. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. """ - self.integration_id = integration_id - self.type = type + self.output = output + self.context = context + self.user_id = user_id + self.masked_output = masked_output + self.masked_input = masked_input @classmethod - def from_dict(cls, _dict: Dict) -> 'IntegrationReference': - """Initialize a IntegrationReference object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'FinalResponse': + """Initialize a FinalResponse object from a json dictionary.""" args = {} - if (integration_id := _dict.get('integration_id')) is not None: - args['integration_id'] = integration_id - if (type := _dict.get('type')) is not None: - args['type'] = type + if (output := _dict.get('output')) is not None: + args['output'] = FinalResponseOutput.from_dict(output) + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a IntegrationReference object from a json dictionary.""" + """Initialize a FinalResponse 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, 'integration_id') and self.integration_id is not None: - _dict['integration_id'] = self.integration_id - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() return _dict def _to_dict(self): @@ -5276,190 +5481,196 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this IntegrationReference object.""" + """Return a `str` version of this FinalResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'IntegrationReference') -> bool: + def __eq__(self, other: 'FinalResponse') -> 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: 'IntegrationReference') -> bool: + def __ne__(self, other: 'FinalResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Log: +class FinalResponseOutput: """ - Log. + Assistant output to be rendered or processed by the client. - :param str log_id: A unique identifier for the logged event. - :param LogRequest request: A message request formatted for the watsonx Assistant - service. - :param LogResponse response: A response from the watsonx Assistant service. - :param str assistant_id: Unique identifier of the assistant. - :param str session_id: The ID of the session the message was part of. - :param str skill_id: The unique identifier of the skill that responded to the - message. - :param str snapshot: The name of the snapshot (dialog skill version) that - responded to the message (for example, `draft`). - :param str request_timestamp: The timestamp for receipt of the message. - :param str response_timestamp: The timestamp for the system response to the - message. - :param str language: The language of the assistant to which the message request - was made. - :param str customer_id: (optional) The customer ID specified for the message, if - any. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + :param MessageStreamMetadata streaming_metadata: Contains meta-information about + the item(s) being streamed. """ def __init__( self, - log_id: str, - request: 'LogRequest', - response: 'LogResponse', - assistant_id: str, - session_id: str, - skill_id: str, - snapshot: str, - request_timestamp: str, - response_timestamp: str, - language: str, + streaming_metadata: 'MessageStreamMetadata', *, - customer_id: Optional[str] = None, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, + llm_metadata: Optional[List['MessageOutputLLMMetadata']] = None, ) -> None: """ - Initialize a Log object. + Initialize a FinalResponseOutput object. - :param str log_id: A unique identifier for the logged event. - :param LogRequest request: A message request formatted for the watsonx - Assistant service. - :param LogResponse response: A response from the watsonx Assistant service. - :param str assistant_id: Unique identifier of the assistant. - :param str session_id: The ID of the session the message was part of. - :param str skill_id: The unique identifier of the skill that responded to - the message. - :param str snapshot: The name of the snapshot (dialog skill version) that - responded to the message (for example, `draft`). - :param str request_timestamp: The timestamp for receipt of the message. - :param str response_timestamp: The timestamp for the system response to the - message. - :param str language: The language of the assistant to which the message - request was made. - :param str customer_id: (optional) The customer ID specified for the - message, if any. - """ - self.log_id = log_id - self.request = request - self.response = response - self.assistant_id = assistant_id - self.session_id = session_id - self.skill_id = skill_id - self.snapshot = snapshot - self.request_timestamp = request_timestamp - self.response_timestamp = response_timestamp - self.language = language - self.customer_id = customer_id + :param MessageStreamMetadata streaming_metadata: Contains meta-information + about the item(s) being streamed. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + """ + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling + self.llm_metadata = llm_metadata + self.streaming_metadata = streaming_metadata @classmethod - def from_dict(cls, _dict: Dict) -> 'Log': - """Initialize a Log object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'FinalResponseOutput': + """Initialize a FinalResponseOutput object from a json dictionary.""" args = {} - if (log_id := _dict.get('log_id')) is not None: - args['log_id'] = log_id - else: - raise ValueError( - 'Required property \'log_id\' not present in Log JSON') - if (request := _dict.get('request')) is not None: - args['request'] = LogRequest.from_dict(request) - else: - raise ValueError( - 'Required property \'request\' not present in Log JSON') - if (response := _dict.get('response')) is not None: - args['response'] = LogResponse.from_dict(response) - else: - raise ValueError( - 'Required property \'response\' not present in Log JSON') - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - else: - raise ValueError( - 'Required property \'assistant_id\' not present in Log JSON') - if (session_id := _dict.get('session_id')) is not None: - args['session_id'] = session_id - else: - raise ValueError( - 'Required property \'session_id\' not present in Log JSON') - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - else: - raise ValueError( - 'Required property \'skill_id\' not present in Log JSON') - if (snapshot := _dict.get('snapshot')) is not None: - args['snapshot'] = snapshot - else: - raise ValueError( - 'Required property \'snapshot\' not present in Log JSON') - if (request_timestamp := _dict.get('request_timestamp')) is not None: - args['request_timestamp'] = request_timestamp - else: - raise ValueError( - 'Required property \'request_timestamp\' not present in Log JSON' - ) - if (response_timestamp := _dict.get('response_timestamp')) is not None: - args['response_timestamp'] = response_timestamp + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) + if (llm_metadata := _dict.get('llm_metadata')) is not None: + args['llm_metadata'] = [ + MessageOutputLLMMetadata.from_dict(v) for v in llm_metadata + ] + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = MessageStreamMetadata.from_dict( + streaming_metadata) else: raise ValueError( - 'Required property \'response_timestamp\' not present in Log JSON' + 'Required property \'streaming_metadata\' not present in FinalResponseOutput JSON' ) - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in Log JSON') - if (customer_id := _dict.get('customer_id')) is not None: - args['customer_id'] = customer_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Log object from a json dictionary.""" + """Initialize a FinalResponseOutput 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, 'log_id') and self.log_id is not None: - _dict['log_id'] = self.log_id - if hasattr(self, 'request') and self.request is not None: - if isinstance(self.request, dict): - _dict['request'] = self.request + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug else: - _dict['request'] = self.request.to_dict() - if hasattr(self, 'response') and self.response is not None: - if isinstance(self.response, dict): - _dict['response'] = self.response + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling else: - _dict['response'] = self.response.to_dict() - if hasattr(self, 'assistant_id') and self.assistant_id is not None: - _dict['assistant_id'] = self.assistant_id - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id - if hasattr(self, 'skill_id') and self.skill_id is not None: - _dict['skill_id'] = self.skill_id - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot - if hasattr(self, - 'request_timestamp') and self.request_timestamp is not None: - _dict['request_timestamp'] = self.request_timestamp + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'llm_metadata') and self.llm_metadata is not None: + llm_metadata_list = [] + for v in self.llm_metadata: + if isinstance(v, dict): + llm_metadata_list.append(v) + else: + llm_metadata_list.append(v.to_dict()) + _dict['llm_metadata'] = llm_metadata_list if hasattr( self, - 'response_timestamp') and self.response_timestamp is not None: - _dict['response_timestamp'] = self.response_timestamp - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'customer_id') and self.customer_id is not None: - _dict['customer_id'] = self.customer_id + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata + else: + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() return _dict def _to_dict(self): @@ -5467,151 +5678,67 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Log object.""" + """Return a `str` version of this FinalResponseOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Log') -> bool: + def __eq__(self, other: 'FinalResponseOutput') -> 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: 'Log') -> bool: + def __ne__(self, other: 'FinalResponseOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogCollection: +class GenerativeAITask: """ - LogCollection. + GenerativeAITask. - :param List[Log] logs: An array of objects describing log events. - :param LogPagination pagination: The pagination data for the returned objects. - For more information about using pagination, see [Pagination](#pagination). """ - def __init__( - self, - logs: List['Log'], - pagination: 'LogPagination', - ) -> None: + def __init__(self,) -> None: """ - Initialize a LogCollection object. + Initialize a GenerativeAITask object. - :param List[Log] logs: An array of objects describing log events. - :param LogPagination pagination: The pagination data for the returned - objects. For more information about using pagination, see - [Pagination](#pagination). """ - self.logs = logs - self.pagination = pagination + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'GenerativeAITaskContentGroundedAnswering', + 'GenerativeAITaskGeneralPurposeAnswering' + ])) + raise Exception(msg) @classmethod - def from_dict(cls, _dict: Dict) -> 'LogCollection': - """Initialize a LogCollection object from a json dictionary.""" - args = {} - if (logs := _dict.get('logs')) is not None: - args['logs'] = [Log.from_dict(v) for v in logs] - else: - raise ValueError( - 'Required property \'logs\' not present in LogCollection JSON') - if (pagination := _dict.get('pagination')) is not None: - args['pagination'] = LogPagination.from_dict(pagination) - else: - raise ValueError( - 'Required property \'pagination\' not present in LogCollection JSON' - ) - return cls(**args) + def from_dict(cls, _dict: Dict) -> 'GenerativeAITask': + """Initialize a GenerativeAITask object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'GenerativeAITask'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'GenerativeAITaskContentGroundedAnswering', + 'GenerativeAITaskGeneralPurposeAnswering' + ])) + raise Exception(msg) @classmethod - def _from_dict(cls, _dict): - """Initialize a LogCollection 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, 'logs') and self.logs is not None: - logs_list = [] - for v in self.logs: - if isinstance(v, dict): - logs_list.append(v) - else: - logs_list.append(v.to_dict()) - _dict['logs'] = logs_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination - else: - _dict['pagination'] = self.pagination.to_dict() - 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 LogCollection object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'LogCollection') -> 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: 'LogCollection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LogMessageSource: - """ - An object that identifies the dialog element that generated the error message. - - """ - - def __init__(self,) -> None: - """ - Initialize a LogMessageSource object. - - """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSource': - """Initialize a LogMessageSource object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = "Cannot convert dictionary into an instance of base class 'LogMessageSource'. The discriminator value should map to a valid subclass: {1}".format( - ", ".join([ - 'LogMessageSourceDialogNode', 'LogMessageSourceAction', - 'LogMessageSourceStep', 'LogMessageSourceHandler' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a LogMessageSource object from a json dictionary.""" + def _from_dict(cls, _dict: Dict): + """Initialize a GenerativeAITask object from a json dictionary.""" return cls.from_dict(_dict) @classmethod def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping = {} - mapping['dialog_node'] = 'LogMessageSourceDialogNode' - mapping['action'] = 'LogMessageSourceAction' - mapping['step'] = 'LogMessageSourceStep' - mapping['handler'] = 'LogMessageSourceHandler' - disc_value = _dict.get('type') + mapping[ + 'content_grounded_answering'] = 'GenerativeAITaskContentGroundedAnswering' + mapping[ + 'general_purpose_answering'] = 'GenerativeAITaskGeneralPurposeAnswering' + disc_value = _dict.get('task') if disc_value is None: raise ValueError( - 'Discriminator property \'type\' not found in LogMessageSource JSON' + 'Discriminator property \'task\' not found in GenerativeAITask JSON' ) class_name = mapping.get(disc_value, disc_value) try: @@ -5623,63 +5750,87 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) -class LogPagination: +class GenerativeAITaskConfidenceScores: """ - The pagination data for the returned objects. For more information about using - pagination, see [Pagination](#pagination). + The confidence scores for determining whether to show the generated response or an “I + don't know” response. - :param str next_url: (optional) The URL that will return the next page of - results, if any. - :param int matched: (optional) Reserved for future use. - :param str next_cursor: (optional) A token identifying the next page of results. + :param float pre_gen: (optional) The confidence score based on user query and + search results. + :param float pre_gen_threshold: (optional) The pre_gen confidence score + threshold. If the pre_gen score is below this threshold, it shows an “I don't + know” response instead of the generated response. Shown in the conversational + search skill UI as the “Retrieval Confidence threshold”. + :param float post_gen: (optional) The confidence score based on user query, + search results, and the generated response. + :param float post_gen_threshold: (optional) The post_gen confidence score + threshold. If the post_gen score is below this threshold, it shows an “I don't + know” response instead of the generated response. Shown in the conversational + search skill UI as the “Response Confidence threshold”. """ def __init__( self, *, - next_url: Optional[str] = None, - matched: Optional[int] = None, - next_cursor: Optional[str] = None, + pre_gen: Optional[float] = None, + pre_gen_threshold: Optional[float] = None, + post_gen: Optional[float] = None, + post_gen_threshold: Optional[float] = None, ) -> None: """ - Initialize a LogPagination object. - - :param str next_url: (optional) The URL that will return the next page of - results, if any. - :param int matched: (optional) Reserved for future use. - :param str next_cursor: (optional) A token identifying the next page of - results. - """ - self.next_url = next_url - self.matched = matched - self.next_cursor = next_cursor - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LogPagination': - """Initialize a LogPagination object from a json dictionary.""" + Initialize a GenerativeAITaskConfidenceScores object. + + :param float pre_gen: (optional) The confidence score based on user query + and search results. + :param float pre_gen_threshold: (optional) The pre_gen confidence score + threshold. If the pre_gen score is below this threshold, it shows an “I + don't know” response instead of the generated response. Shown in the + conversational search skill UI as the “Retrieval Confidence threshold”. + :param float post_gen: (optional) The confidence score based on user query, + search results, and the generated response. + :param float post_gen_threshold: (optional) The post_gen confidence score + threshold. If the post_gen score is below this threshold, it shows an “I + don't know” response instead of the generated response. Shown in the + conversational search skill UI as the “Response Confidence threshold”. + """ + self.pre_gen = pre_gen + self.pre_gen_threshold = pre_gen_threshold + self.post_gen = post_gen + self.post_gen_threshold = post_gen_threshold + + @classmethod + def from_dict(cls, _dict: Dict) -> 'GenerativeAITaskConfidenceScores': + """Initialize a GenerativeAITaskConfidenceScores object from a json dictionary.""" args = {} - if (next_url := _dict.get('next_url')) is not None: - args['next_url'] = next_url - if (matched := _dict.get('matched')) is not None: - args['matched'] = matched - if (next_cursor := _dict.get('next_cursor')) is not None: - args['next_cursor'] = next_cursor + if (pre_gen := _dict.get('pre_gen')) is not None: + args['pre_gen'] = pre_gen + if (pre_gen_threshold := _dict.get('pre_gen_threshold')) is not None: + args['pre_gen_threshold'] = pre_gen_threshold + if (post_gen := _dict.get('post_gen')) is not None: + args['post_gen'] = post_gen + if (post_gen_threshold := _dict.get('post_gen_threshold')) is not None: + args['post_gen_threshold'] = post_gen_threshold return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogPagination object from a json dictionary.""" + """Initialize a GenerativeAITaskConfidenceScores 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, 'next_url') and self.next_url is not None: - _dict['next_url'] = self.next_url - if hasattr(self, 'matched') and self.matched is not None: - _dict['matched'] = self.matched - if hasattr(self, 'next_cursor') and self.next_cursor is not None: - _dict['next_cursor'] = self.next_cursor + if hasattr(self, 'pre_gen') and self.pre_gen is not None: + _dict['pre_gen'] = self.pre_gen + if hasattr(self, + 'pre_gen_threshold') and self.pre_gen_threshold is not None: + _dict['pre_gen_threshold'] = self.pre_gen_threshold + if hasattr(self, 'post_gen') and self.post_gen is not None: + _dict['post_gen'] = self.post_gen + if hasattr( + self, + 'post_gen_threshold') and self.post_gen_threshold is not None: + _dict['post_gen_threshold'] = self.post_gen_threshold return _dict def _to_dict(self): @@ -5687,109 +5838,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogPagination object.""" + """Return a `str` version of this GenerativeAITaskConfidenceScores object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogPagination') -> bool: + def __eq__(self, other: 'GenerativeAITaskConfidenceScores') -> 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: 'LogPagination') -> bool: + def __ne__(self, other: 'GenerativeAITaskConfidenceScores') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogRequest: +class IntegrationReference: """ - A message request formatted for the watsonx Assistant service. + IntegrationReference. - :param LogRequestInput input: (optional) An input object that includes the input - text. All private data is masked or removed. - :param MessageContext context: (optional) Context data for the conversation. You - can use this property to set or modify context variables, which can also be - accessed by dialog nodes. The context is stored by the assistant on a - per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :param str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. If **user_id** is specified in both locations, the value - specified at the root is used. + :param str integration_id: (optional) The integration ID of the integration. + :param str type: (optional) The type of the integration. """ def __init__( self, *, - input: Optional['LogRequestInput'] = None, - context: Optional['MessageContext'] = None, - user_id: Optional[str] = None, + integration_id: Optional[str] = None, + type: Optional[str] = None, ) -> None: """ - Initialize a LogRequest object. + Initialize a IntegrationReference object. - :param LogRequestInput input: (optional) An input object that includes the - input text. All private data is masked or removed. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to set or modify context variables, - which can also be accessed by dialog nodes. The context is stored by the - assistant on a per-session basis. - **Note:** The total size of the context data stored for a stateful session - cannot exceed 100KB. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. If **user_id** is specified in both locations, the - value specified at the root is used. + :param str integration_id: (optional) The integration ID of the + integration. + :param str type: (optional) The type of the integration. """ - self.input = input - self.context = context - self.user_id = user_id + self.integration_id = integration_id + self.type = type @classmethod - def from_dict(cls, _dict: Dict) -> 'LogRequest': - """Initialize a LogRequest object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'IntegrationReference': + """Initialize a IntegrationReference object from a json dictionary.""" args = {} - if (input := _dict.get('input')) is not None: - args['input'] = LogRequestInput.from_dict(input) - if (context := _dict.get('context')) is not None: - args['context'] = MessageContext.from_dict(context) - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id + if (integration_id := _dict.get('integration_id')) is not None: + args['integration_id'] = integration_id + if (type := _dict.get('type')) is not None: + args['type'] = type return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogRequest object from a json dictionary.""" + """Initialize a IntegrationReference 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, 'input') and self.input is not None: - if isinstance(self.input, dict): - _dict['input'] = self.input - else: - _dict['input'] = self.input.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + if hasattr(self, 'integration_id') and self.integration_id is not None: + _dict['integration_id'] = self.integration_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -5797,175 +5905,190 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogRequest object.""" + """Return a `str` version of this IntegrationReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogRequest') -> bool: + def __eq__(self, other: 'IntegrationReference') -> 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: 'LogRequest') -> bool: + def __ne__(self, other: 'IntegrationReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogRequestInput: +class Log: """ - An input object that includes the input text. All private data is masked or removed. + Log. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating - the user input. Include intents from the previous response to continue using - those intents rather than trying to recognize intents in the new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the Segment - extension. - :param MessageInputOptions options: (optional) Optional properties that control - how the assistant responds. + :param str log_id: A unique identifier for the logged event. + :param LogRequest request: A message request formatted for the watsonx Assistant + service. + :param LogResponse response: A response from the watsonx Assistant service. + :param str assistant_id: Unique identifier of the assistant. + :param str session_id: The ID of the session the message was part of. + :param str skill_id: The unique identifier of the skill that responded to the + message. + :param str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the + message. + :param str language: The language of the assistant to which the message request + was made. + :param str customer_id: (optional) The customer ID specified for the message, if + any. """ def __init__( self, + log_id: str, + request: 'LogRequest', + response: 'LogResponse', + assistant_id: str, + session_id: str, + skill_id: str, + snapshot: str, + request_timestamp: str, + response_timestamp: str, + language: str, *, - message_type: Optional[str] = None, - text: Optional[str] = None, - intents: Optional[List['RuntimeIntent']] = None, - entities: Optional[List['RuntimeEntity']] = None, - suggestion_id: Optional[str] = None, - attachments: Optional[List['MessageInputAttachment']] = None, - analytics: Optional['RequestAnalytics'] = None, - options: Optional['MessageInputOptions'] = None, + customer_id: Optional[str] = None, ) -> None: """ - Initialize a LogRequestInput object. + Initialize a Log object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the - Segment extension. - :param MessageInputOptions options: (optional) Optional properties that - control how the assistant responds. + :param str log_id: A unique identifier for the logged event. + :param LogRequest request: A message request formatted for the watsonx + Assistant service. + :param LogResponse response: A response from the watsonx Assistant service. + :param str assistant_id: Unique identifier of the assistant. + :param str session_id: The ID of the session the message was part of. + :param str skill_id: The unique identifier of the skill that responded to + the message. + :param str snapshot: The name of the snapshot (dialog skill version) that + responded to the message (for example, `draft`). + :param str request_timestamp: The timestamp for receipt of the message. + :param str response_timestamp: The timestamp for the system response to the + message. + :param str language: The language of the assistant to which the message + request was made. + :param str customer_id: (optional) The customer ID specified for the + message, if any. """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.analytics = analytics - self.options = options + self.log_id = log_id + self.request = request + self.response = response + self.assistant_id = assistant_id + self.session_id = session_id + self.skill_id = skill_id + self.snapshot = snapshot + self.request_timestamp = request_timestamp + self.response_timestamp = response_timestamp + self.language = language + self.customer_id = customer_id @classmethod - def from_dict(cls, _dict: Dict) -> 'LogRequestInput': - """Initialize a LogRequestInput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Log': + """Initialize a Log object from a json dictionary.""" args = {} - if (message_type := _dict.get('message_type')) is not None: - args['message_type'] = message_type - if (text := _dict.get('text')) is not None: - args['text'] = text - if (intents := _dict.get('intents')) is not None: - args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] - if (entities := _dict.get('entities')) is not None: - args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] - if (suggestion_id := _dict.get('suggestion_id')) is not None: - args['suggestion_id'] = suggestion_id - if (attachments := _dict.get('attachments')) is not None: - args['attachments'] = [ - MessageInputAttachment.from_dict(v) for v in attachments - ] - if (analytics := _dict.get('analytics')) is not None: - args['analytics'] = RequestAnalytics.from_dict(analytics) - if (options := _dict.get('options')) is not None: - args['options'] = MessageInputOptions.from_dict(options) + if (log_id := _dict.get('log_id')) is not None: + args['log_id'] = log_id + else: + raise ValueError( + 'Required property \'log_id\' not present in Log JSON') + if (request := _dict.get('request')) is not None: + args['request'] = LogRequest.from_dict(request) + else: + raise ValueError( + 'Required property \'request\' not present in Log JSON') + if (response := _dict.get('response')) is not None: + args['response'] = LogResponse.from_dict(response) + else: + raise ValueError( + 'Required property \'response\' not present in Log JSON') + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + else: + raise ValueError( + 'Required property \'assistant_id\' not present in Log JSON') + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id + else: + raise ValueError( + 'Required property \'session_id\' not present in Log JSON') + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + else: + raise ValueError( + 'Required property \'skill_id\' not present in Log JSON') + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot + else: + raise ValueError( + 'Required property \'snapshot\' not present in Log JSON') + if (request_timestamp := _dict.get('request_timestamp')) is not None: + args['request_timestamp'] = request_timestamp + else: + raise ValueError( + 'Required property \'request_timestamp\' not present in Log JSON' + ) + if (response_timestamp := _dict.get('response_timestamp')) is not None: + args['response_timestamp'] = response_timestamp + else: + raise ValueError( + 'Required property \'response_timestamp\' not present in Log JSON' + ) + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in Log JSON') + if (customer_id := _dict.get('customer_id')) is not None: + args['customer_id'] = customer_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogRequestInput object from a json dictionary.""" + """Initialize a Log 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, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - attachments_list = [] - for v in self.attachments: - if isinstance(v, dict): - attachments_list.append(v) - else: - attachments_list.append(v.to_dict()) - _dict['attachments'] = attachments_list - if hasattr(self, 'analytics') and self.analytics is not None: - if isinstance(self.analytics, dict): - _dict['analytics'] = self.analytics + if hasattr(self, 'log_id') and self.log_id is not None: + _dict['log_id'] = self.log_id + if hasattr(self, 'request') and self.request is not None: + if isinstance(self.request, dict): + _dict['request'] = self.request else: - _dict['analytics'] = self.analytics.to_dict() - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options + _dict['request'] = self.request.to_dict() + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response else: - _dict['options'] = self.options.to_dict() + _dict['response'] = self.response.to_dict() + if hasattr(self, 'assistant_id') and self.assistant_id is not None: + _dict['assistant_id'] = self.assistant_id + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + if hasattr(self, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + if hasattr(self, + 'request_timestamp') and self.request_timestamp is not None: + _dict['request_timestamp'] = self.request_timestamp + if hasattr( + self, + 'response_timestamp') and self.response_timestamp is not None: + _dict['response_timestamp'] = self.response_timestamp + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'customer_id') and self.customer_id is not None: + _dict['customer_id'] = self.customer_id return _dict def _to_dict(self): @@ -5973,126 +6096,83 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogRequestInput object.""" + """Return a `str` version of this Log object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogRequestInput') -> bool: + def __eq__(self, other: 'Log') -> 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: 'LogRequestInput') -> bool: + def __ne__(self, other: 'Log') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): - """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. - """ - - TEXT = 'text' - SEARCH = 'search' +class LogCollection: + """ + LogCollection. -class LogResponse: - """ - A response from the watsonx Assistant service. - - :param LogResponseOutput output: Assistant output to be rendered or processed by - the client. All private data is masked or removed. - :param MessageContext context: (optional) Context data for the conversation. You - can use this property to access context variables. The context is stored by the - assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :param str user_id: A string value that identifies the user who is interacting - with the assistant. The client must provide a unique identifier for each - individual end user who accesses the application. For user-based plans, this - user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ def __init__( self, - output: 'LogResponseOutput', - user_id: str, - *, - context: Optional['MessageContext'] = None, + logs: List['Log'], + pagination: 'LogPagination', ) -> None: """ - Initialize a LogResponse object. + Initialize a LogCollection object. - :param LogResponseOutput output: Assistant output to be rendered or - processed by the client. All private data is masked or removed. - :param str user_id: A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier - for each individual end user who accesses the application. For user-based - plans, this user ID is used to identify unique users for billing purposes. - This string cannot contain carriage return, newline, or tab characters. If - no value is specified in the input, **user_id** is automatically set to the - value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to access context variables. The - context is stored by the assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. + :param List[Log] logs: An array of objects describing log events. + :param LogPagination pagination: The pagination data for the returned + objects. For more information about using pagination, see + [Pagination](#pagination). """ - self.output = output - self.context = context - self.user_id = user_id + self.logs = logs + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'LogResponse': - """Initialize a LogResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogCollection': + """Initialize a LogCollection object from a json dictionary.""" args = {} - if (output := _dict.get('output')) is not None: - args['output'] = LogResponseOutput.from_dict(output) + if (logs := _dict.get('logs')) is not None: + args['logs'] = [Log.from_dict(v) for v in logs] else: raise ValueError( - 'Required property \'output\' not present in LogResponse JSON') - if (context := _dict.get('context')) is not None: - args['context'] = MessageContext.from_dict(context) - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id + 'Required property \'logs\' not present in LogCollection JSON') + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = LogPagination.from_dict(pagination) else: raise ValueError( - 'Required property \'user_id\' not present in LogResponse JSON') + 'Required property \'pagination\' not present in LogCollection JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogResponse object from a json dictionary.""" + """Initialize a LogCollection 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, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context + if hasattr(self, 'logs') and self.logs is not None: + logs_list = [] + for v in self.logs: + if isinstance(v, dict): + logs_list.append(v) + else: + logs_list.append(v.to_dict()) + _dict['logs'] = logs_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -6100,157 +6180,135 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogResponse object.""" + """Return a `str` version of this LogCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogResponse') -> bool: + def __eq__(self, other: 'LogCollection') -> 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: 'LogResponse') -> bool: + def __ne__(self, other: 'LogCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogResponseOutput: +class LogMessageSource: """ - Assistant output to be rendered or processed by the client. All private data is masked - or removed. + An object that identifies the dialog element that generated the error message. - :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any - channel. It is the responsibility of the client application to implement the - supported response types. - :param List[RuntimeIntent] intents: (optional) An array of intents recognized in - the user input, sorted in descending order of confidence. - :param List[RuntimeEntity] entities: (optional) An array of entities identified - in the user input. - :param List[DialogNodeAction] actions: (optional) An array of objects describing - any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information - about a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom properties - included in the response. This object includes any arbitrary properties defined - in the dialog JSON editor as part of the dialog node output. - :param MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + """ + + def __init__(self,) -> None: + """ + Initialize a LogMessageSource object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogMessageSource': + """Initialize a LogMessageSource object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'LogMessageSource'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'LogMessageSourceDialogNode', 'LogMessageSourceAction', + 'LogMessageSourceStep', 'LogMessageSourceHandler' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a LogMessageSource object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping['dialog_node'] = 'LogMessageSourceDialogNode' + mapping['action'] = 'LogMessageSourceAction' + mapping['step'] = 'LogMessageSourceStep' + mapping['handler'] = 'LogMessageSourceHandler' + disc_value = _dict.get('type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'type\' not found in LogMessageSource JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class LogPagination: + """ + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). + + :param str next_url: (optional) The URL that will return the next page of + results, if any. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of results. """ def __init__( self, *, - generic: Optional[List['RuntimeResponseGeneric']] = None, - intents: Optional[List['RuntimeIntent']] = None, - entities: Optional[List['RuntimeEntity']] = None, - actions: Optional[List['DialogNodeAction']] = None, - debug: Optional['MessageOutputDebug'] = None, - user_defined: Optional[dict] = None, - spelling: Optional['MessageOutputSpelling'] = None, + next_url: Optional[str] = None, + matched: Optional[int] = None, + next_cursor: Optional[str] = None, ) -> None: """ - Initialize a LogResponseOutput object. + Initialize a LogPagination object. - :param List[RuntimeResponseGeneric] generic: (optional) Output intended for - any channel. It is the responsibility of the client application to - implement the supported response types. - :param List[RuntimeIntent] intents: (optional) An array of intents - recognized in the user input, sorted in descending order of confidence. - :param List[RuntimeEntity] entities: (optional) An array of entities - identified in the user input. - :param List[DialogNodeAction] actions: (optional) An array of objects - describing any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information - about a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom - properties included in the response. This object includes any arbitrary - properties defined in the dialog JSON editor as part of the dialog node - output. - :param MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + :param str next_url: (optional) The URL that will return the next page of + results, if any. + :param int matched: (optional) Reserved for future use. + :param str next_cursor: (optional) A token identifying the next page of + results. """ - self.generic = generic - self.intents = intents - self.entities = entities - self.actions = actions - self.debug = debug - self.user_defined = user_defined - self.spelling = spelling + self.next_url = next_url + self.matched = matched + self.next_cursor = next_cursor @classmethod - def from_dict(cls, _dict: Dict) -> 'LogResponseOutput': - """Initialize a LogResponseOutput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogPagination': + """Initialize a LogPagination object from a json dictionary.""" args = {} - if (generic := _dict.get('generic')) is not None: - args['generic'] = [ - RuntimeResponseGeneric.from_dict(v) for v in generic - ] - if (intents := _dict.get('intents')) is not None: - args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] - if (entities := _dict.get('entities')) is not None: - args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] - if (actions := _dict.get('actions')) is not None: - args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] - if (debug := _dict.get('debug')) is not None: - args['debug'] = MessageOutputDebug.from_dict(debug) - if (user_defined := _dict.get('user_defined')) is not None: - args['user_defined'] = user_defined - if (spelling := _dict.get('spelling')) is not None: - args['spelling'] = MessageOutputSpelling.from_dict(spelling) + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogResponseOutput object from a json dictionary.""" + """Initialize a LogPagination 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, 'generic') and self.generic is not None: - generic_list = [] - for v in self.generic: - if isinstance(v, dict): - generic_list.append(v) - else: - generic_list.append(v.to_dict()) - _dict['generic'] = generic_list - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'actions') and self.actions is not None: - actions_list = [] - for v in self.actions: - if isinstance(v, dict): - actions_list.append(v) - else: - actions_list.append(v.to_dict()) - _dict['actions'] = actions_list - if hasattr(self, 'debug') and self.debug is not None: - if isinstance(self.debug, dict): - _dict['debug'] = self.debug - else: - _dict['debug'] = self.debug.to_dict() - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'spelling') and self.spelling is not None: - if isinstance(self.spelling, dict): - _dict['spelling'] = self.spelling - else: - _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor return _dict def _to_dict(self): @@ -6258,87 +6316,109 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogResponseOutput object.""" + """Return a `str` version of this LogPagination object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogResponseOutput') -> bool: + def __eq__(self, other: 'LogPagination') -> 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: 'LogResponseOutput') -> bool: + def __ne__(self, other: 'LogPagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContext: +class LogRequest: """ - MessageContext. + A message request formatted for the watsonx Assistant service. - :param MessageContextGlobal global_: (optional) Session context data that is - shared by all skills used by the assistant. - :param MessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param LogRequestInput input: (optional) An input object that includes the input + text. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to set or modify context variables, which can also be + accessed by dialog nodes. The context is stored by the assistant on a + per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. If **user_id** is specified in both locations, the value + specified at the root is used. """ def __init__( self, *, - global_: Optional['MessageContextGlobal'] = None, - skills: Optional['MessageContextSkills'] = None, - integrations: Optional[dict] = None, + input: Optional['LogRequestInput'] = None, + context: Optional['MessageContext'] = None, + user_id: Optional[str] = None, ) -> None: """ - Initialize a MessageContext object. + Initialize a LogRequest object. - :param MessageContextGlobal global_: (optional) Session context data that - is shared by all skills used by the assistant. - :param MessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that - is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param LogRequestInput input: (optional) An input object that includes the + input text. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to set or modify context variables, + which can also be accessed by dialog nodes. The context is stored by the + assistant on a per-session basis. + **Note:** The total size of the context data stored for a stateful session + cannot exceed 100KB. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. If **user_id** is specified in both locations, the + value specified at the root is used. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.input = input + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContext': - """Initialize a MessageContext object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogRequest': + """Initialize a LogRequest object from a json dictionary.""" args = {} - if (global_ := _dict.get('global')) is not None: - args['global_'] = MessageContextGlobal.from_dict(global_) - if (skills := _dict.get('skills')) is not None: - args['skills'] = MessageContextSkills.from_dict(skills) - if (integrations := _dict.get('integrations')) is not None: - args['integrations'] = integrations + if (input := _dict.get('input')) is not None: + args['input'] = LogRequestInput.from_dict(input) + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContext object from a json dictionary.""" + """Initialize a LogRequest 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, 'global_') and self.global_ is not None: - if isinstance(self.global_, dict): - _dict['global'] = self.global_ + if hasattr(self, 'input') and self.input is not None: + if isinstance(self.input, dict): + _dict['input'] = self.input else: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - if isinstance(self.skills, dict): - _dict['skills'] = self.skills + _dict['input'] = self.input.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context else: - _dict['skills'] = self.skills.to_dict() - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -6346,101 +6426,175 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContext object.""" + """Return a `str` version of this LogRequest object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContext') -> bool: + def __eq__(self, other: 'LogRequest') -> 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: 'MessageContext') -> bool: + def __ne__(self, other: 'LogRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextActionSkill: +class LogRequestInput: """ - Context variables that are used by the action skill. Private variables are persisted, - but not shown. + An input object that includes the input text. All private data is masked or removed. - :param dict user_defined: (optional) An object containing any arbitrary - variables that can be read and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data used by - the skill. - :param dict action_variables: (optional) An object containing action variables. - Action variables can be accessed only by steps in the same action, and do not - persist after the action ends. - :param dict skill_variables: (optional) An object containing skill variables. - (In the watsonx Assistant user interface, skill variables are called _session - variables_.) Skill variables can be accessed by any action and persist for the - duration of the session. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param MessageInputOptions options: (optional) Optional properties that control + how the assistant responds. """ def __init__( self, *, - user_defined: Optional[dict] = None, - system: Optional['MessageContextSkillSystem'] = None, - action_variables: Optional[dict] = None, - skill_variables: Optional[dict] = None, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['MessageInputOptions'] = None, ) -> None: """ - Initialize a MessageContextActionSkill object. + Initialize a LogRequestInput object. - :param dict user_defined: (optional) An object containing any arbitrary - variables that can be read and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data - used by the skill. - :param dict action_variables: (optional) An object containing action - variables. Action variables can be accessed only by steps in the same - action, and do not persist after the action ends. - :param dict skill_variables: (optional) An object containing skill - variables. (In the watsonx Assistant user interface, skill variables are - called _session variables_.) Skill variables can be accessed by any action - and persist for the duration of the session. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param MessageInputOptions options: (optional) Optional properties that + control how the assistant responds. """ - self.user_defined = user_defined - self.system = system - self.action_variables = action_variables - self.skill_variables = skill_variables - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextActionSkill': - """Initialize a MessageContextActionSkill object from a json dictionary.""" + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LogRequestInput': + """Initialize a LogRequestInput object from a json dictionary.""" args = {} - if (user_defined := _dict.get('user_defined')) is not None: - args['user_defined'] = user_defined - if (system := _dict.get('system')) is not None: - args['system'] = MessageContextSkillSystem.from_dict(system) - if (action_variables := _dict.get('action_variables')) is not None: - args['action_variables'] = action_variables - if (skill_variables := _dict.get('skill_variables')) is not None: - args['skill_variables'] = skill_variables + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments + ] + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = MessageInputOptions.from_dict(options) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextActionSkill object from a json dictionary.""" + """Initialize a LogRequestInput 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, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics else: - _dict['system'] = self.system.to_dict() - if hasattr(self, - 'action_variables') and self.action_variables is not None: - _dict['action_variables'] = self.action_variables - if hasattr(self, - 'skill_variables') and self.skill_variables is not None: - _dict['skill_variables'] = self.skill_variables + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -6448,72 +6602,126 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextActionSkill object.""" + """Return a `str` version of this LogRequestInput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextActionSkill') -> bool: + def __eq__(self, other: 'LogRequestInput') -> 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: 'MessageContextActionSkill') -> bool: + def __ne__(self, other: 'LogRequestInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ + + TEXT = 'text' + SEARCH = 'search' -class MessageContextDialogSkill: + +class LogResponse: """ - Context variables that are used by the dialog skill. + A response from the watsonx Assistant service. - :param dict user_defined: (optional) An object containing any arbitrary - variables that can be read and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data used by - the skill. + :param LogResponseOutput output: Assistant output to be rendered or processed by + the client. All private data is masked or removed. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ def __init__( self, + output: 'LogResponseOutput', + user_id: str, *, - user_defined: Optional[dict] = None, - system: Optional['MessageContextSkillSystem'] = None, + context: Optional['MessageContext'] = None, ) -> None: """ - Initialize a MessageContextDialogSkill object. + Initialize a LogResponse object. - :param dict user_defined: (optional) An object containing any arbitrary - variables that can be read and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data - used by the skill. + :param LogResponseOutput output: Assistant output to be rendered or + processed by the client. All private data is masked or removed. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. """ - self.user_defined = user_defined - self.system = system + self.output = output + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextDialogSkill': - """Initialize a MessageContextDialogSkill object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogResponse': + """Initialize a LogResponse object from a json dictionary.""" args = {} - if (user_defined := _dict.get('user_defined')) is not None: - args['user_defined'] = user_defined - if (system := _dict.get('system')) is not None: - args['system'] = MessageContextSkillSystem.from_dict(system) + if (output := _dict.get('output')) is not None: + args['output'] = LogResponseOutput.from_dict(output) + else: + raise ValueError( + 'Required property \'output\' not present in LogResponse JSON') + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + else: + raise ValueError( + 'Required property \'user_id\' not present in LogResponse JSON') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextDialogSkill object from a json dictionary.""" + """Initialize a LogResponse 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, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output else: - _dict['system'] = self.system.to_dict() + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -6521,70 +6729,177 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextDialogSkill object.""" + """Return a `str` version of this LogResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextDialogSkill') -> bool: + def __eq__(self, other: 'LogResponse') -> 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: 'MessageContextDialogSkill') -> bool: + def __ne__(self, other: 'LogResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobal: +class LogResponseOutput: """ - Session context data that is shared by all skills used by the assistant. + Assistant output to be rendered or processed by the client. All private data is masked + or removed. - :param MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :param str session_id: (optional) The session ID. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. """ def __init__( self, *, - system: Optional['MessageContextGlobalSystem'] = None, - session_id: Optional[str] = None, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, + llm_metadata: Optional[List['MessageOutputLLMMetadata']] = None, ) -> None: """ - Initialize a MessageContextGlobal object. - - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. - """ - self.system = system - self.session_id = session_id + Initialize a LogResponseOutput object. + + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + """ + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling + self.llm_metadata = llm_metadata @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': - """Initialize a MessageContextGlobal object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogResponseOutput': + """Initialize a LogResponseOutput object from a json dictionary.""" args = {} - if (system := _dict.get('system')) is not None: - args['system'] = MessageContextGlobalSystem.from_dict(system) - if (session_id := _dict.get('session_id')) is not None: - args['session_id'] = session_id + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) + if (llm_metadata := _dict.get('llm_metadata')) is not None: + args['llm_metadata'] = [ + MessageOutputLLMMetadata.from_dict(v) for v in llm_metadata + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobal object from a json dictionary.""" + """Initialize a LogResponseOutput 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, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug else: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and getattr(self, - 'session_id') is not None: - _dict['session_id'] = getattr(self, 'session_id') + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'llm_metadata') and self.llm_metadata is not None: + llm_metadata_list = [] + for v in self.llm_metadata: + if isinstance(v, dict): + llm_metadata_list.append(v) + else: + llm_metadata_list.append(v.to_dict()) + _dict['llm_metadata'] = llm_metadata_list return _dict def _to_dict(self): @@ -6592,196 +6907,87 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobal object.""" + """Return a `str` version of this LogResponseOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobal') -> bool: + def __eq__(self, other: 'LogResponseOutput') -> 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: 'MessageContextGlobal') -> bool: + def __ne__(self, other: 'LogResponseOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextGlobalSystem: +class MessageContext: """ - Built-in system properties that apply to all skills used by the assistant. + MessageContext. - :param str timezone: (optional) The user time zone. The assistant uses the time - zone to correctly resolve relative time references. - :param str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root of - the message body. If **user_id** is specified in both locations in a message - request, the value specified at the root is used. - :param int turn_count: (optional) A counter that is automatically incremented - 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). - :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for the - skill. - :param str session_start_time: (optional) The time at which the session started. - With the stateful `message` method, the start time is always present, and is set - by the service based on the time the session was created. With the stateless - `message` method, the start time is set by the service in the response to the - first message, and should be returned as part of the context with each - subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for example, - `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :param str state: (optional) An encoded string that represents the configuration - state of the assistant at the beginning of the conversation. If you are using - the stateless `message` method, save this value and then send it in the context - of the subsequent message request to avoid disruptions if there are - configuration changes during the conversation (such as a change to a skill the - assistant uses). - :param bool skip_user_input: (optional) For internal use only. + :param MessageContextGlobal global_: (optional) Session context data that is + shared by all skills used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ def __init__( self, *, - timezone: Optional[str] = None, - user_id: Optional[str] = None, - turn_count: Optional[int] = None, - locale: Optional[str] = None, - reference_time: Optional[str] = None, - session_start_time: Optional[str] = None, - state: Optional[str] = None, - skip_user_input: Optional[bool] = None, + global_: Optional['MessageContextGlobal'] = None, + skills: Optional['MessageContextSkills'] = None, + integrations: Optional[dict] = None, ) -> None: """ - Initialize a MessageContextGlobalSystem object. + Initialize a MessageContext object. - :param str timezone: (optional) The user time zone. The assistant uses the - time zone to correctly resolve relative time references. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property at the root - of the message body. If **user_id** is specified in both locations in a - message request, the value specified at the root is used. - :param int turn_count: (optional) A counter that is automatically - incremented 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). - :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - This property is included only if the new system entities are enabled for - the skill. - :param str session_start_time: (optional) The time at which the session - started. With the stateful `message` method, the start time is always - present, and is set by the service based on the time the session was - created. With the stateless `message` method, the start time is set by the - service in the response to the first message, and should be returned as - part of the context with each subsequent message in the session. - This value is a UTC time value formatted according to ISO 8601 (for - example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). - :param str state: (optional) An encoded string that represents the - configuration state of the assistant at the beginning of the conversation. - If you are using the stateless `message` method, save this value and then - send it in the context of the subsequent message request to avoid - disruptions if there are configuration changes during the conversation - (such as a change to a skill the assistant uses). - :param bool skip_user_input: (optional) For internal use only. + :param MessageContextGlobal global_: (optional) Session context data that + is shared by all skills used by the assistant. + :param MessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - self.timezone = timezone - self.user_id = user_id - self.turn_count = turn_count - self.locale = locale - self.reference_time = reference_time - self.session_start_time = session_start_time - self.state = state - self.skip_user_input = skip_user_input + self.global_ = global_ + self.skills = skills + self.integrations = integrations @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContext': + """Initialize a MessageContext object from a json dictionary.""" args = {} - if (timezone := _dict.get('timezone')) is not None: - args['timezone'] = timezone - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id - if (turn_count := _dict.get('turn_count')) is not None: - args['turn_count'] = turn_count - if (locale := _dict.get('locale')) is not None: - args['locale'] = locale - if (reference_time := _dict.get('reference_time')) is not None: - args['reference_time'] = reference_time - if (session_start_time := _dict.get('session_start_time')) is not None: - args['session_start_time'] = session_start_time - if (state := _dict.get('state')) is not None: - args['state'] = state - if (skip_user_input := _dict.get('skip_user_input')) is not None: - args['skip_user_input'] = skip_user_input + if (global_ := _dict.get('global')) is not None: + args['global_'] = MessageContextGlobal.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = MessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + """Initialize a MessageContext 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, 'timezone') and self.timezone is not None: - _dict['timezone'] = self.timezone - if hasattr(self, 'user_id') and self.user_id is not None: - _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 - if hasattr( - self, - 'session_start_time') and self.session_start_time is not None: - _dict['session_start_time'] = self.session_start_time - if hasattr(self, 'state') and self.state is not None: - _dict['state'] = self.state - if hasattr(self, - 'skip_user_input') and self.skip_user_input is not None: - _dict['skip_user_input'] = self.skip_user_input + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations return _dict def _to_dict(self): @@ -6789,229 +6995,174 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextGlobalSystem object.""" + """Return a `str` version of this MessageContext object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextGlobalSystem') -> bool: + def __eq__(self, other: 'MessageContext') -> 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: 'MessageContextGlobalSystem') -> bool: + def __ne__(self, other: 'MessageContext') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class LocaleEnum(str, 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 MessageContextSkillSystem: +class MessageContextActionSkill: """ - System context data used by the skill. - - :param str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context of a - subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. + Context variables that are used by the action skill. Private variables are persisted, + but not shown. - This type supports additional properties of type object. For internal use only. + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by + the skill. + :param dict action_variables: (optional) An object containing action variables. + Action variables can be accessed only by steps in the same action, and do not + persist after the action ends. + :param dict skill_variables: (optional) An object containing skill variables. + (In the watsonx Assistant user interface, skill variables are called _session + variables_.) Skill variables can be accessed by any action and persist for the + duration of the session. """ - # The set of defined properties for the class - _properties = frozenset(['state']) - def __init__( self, *, - state: Optional[str] = None, - **kwargs: Optional[object], + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + action_variables: Optional[dict] = None, + skill_variables: Optional[dict] = None, ) -> None: """ - Initialize a MessageContextSkillSystem object. + Initialize a MessageContextActionSkill object. - :param str state: (optional) An encoded string that represents the current - conversation state. By saving this value and then sending it in the context - of a subsequent message request, you can return to an earlier point in the - conversation. If you are using stateful sessions, you can also use a stored - state value to restore a paused conversation whose session is expired. - :param object **kwargs: (optional) For internal use only. + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + :param dict action_variables: (optional) An object containing action + variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. + :param dict skill_variables: (optional) An object containing skill + variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action + and persist for the duration of the session. """ - self.state = state - for k, v in kwargs.items(): - if k not in MessageContextSkillSystem._properties: - if not isinstance(v, object): - raise ValueError( - 'Value for additional property {} must be of type object' - .format(k)) - setattr(self, k, v) - else: - raise ValueError( - 'Property {} cannot be specified as an additional property'. - format(k)) + self.user_defined = user_defined + self.system = system + self.action_variables = action_variables + self.skill_variables = skill_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextActionSkill': + """Initialize a MessageContextActionSkill object from a json dictionary.""" args = {} - if (state := _dict.get('state')) is not None: - args['state'] = state - for k, v in _dict.items(): - if k not in cls._properties: - if not isinstance(v, object): - raise ValueError( - 'Value for additional property {} must be of type object' - .format(k)) - args[k] = v + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables + if (skill_variables := _dict.get('skill_variables')) is not None: + args['skill_variables'] = skill_variables return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkillSystem object from a json dictionary.""" + """Initialize a MessageContextActionSkill 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, 'state') and self.state is not None: - _dict['state'] = self.state - for k in [ - _k for _k in vars(self).keys() - if _k not in MessageContextSkillSystem._properties - ]: - _dict[k] = getattr(self, k) + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system + else: + _dict['system'] = self.system.to_dict() + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables + if hasattr(self, + 'skill_variables') and self.skill_variables is not None: + _dict['skill_variables'] = self.skill_variables return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return the additional properties from this instance of MessageContextSkillSystem in the form of a dict.""" - _dict = {} - for k in [ - _k for _k in vars(self).keys() - if _k not in MessageContextSkillSystem._properties - ]: - _dict[k] = getattr(self, k) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of additional properties in this instance of MessageContextSkillSystem""" - for k in [ - _k for _k in vars(self).keys() - if _k not in MessageContextSkillSystem._properties - ]: - delattr(self, k) - for k, v in _dict.items(): - if k not in MessageContextSkillSystem._properties: - if not isinstance(v, object): - raise ValueError( - 'Value for additional property {} must be of type object' - .format(k)) - setattr(self, k, v) - else: - raise ValueError( - 'Property {} cannot be specified as an additional property'. - format(k)) - def __str__(self) -> str: - """Return a `str` version of this MessageContextSkillSystem object.""" + """Return a `str` version of this MessageContextActionSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkillSystem') -> bool: + def __eq__(self, other: 'MessageContextActionSkill') -> 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: 'MessageContextSkillSystem') -> bool: + def __ne__(self, other: 'MessageContextActionSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageContextSkills: +class MessageContextDialogSkill: """ - Context data specific to particular skills used by the assistant. + Context variables that are used by the dialog skill. - :param MessageContextDialogSkill main_skill: (optional) Context variables that - are used by the dialog skill. - :param MessageContextActionSkill actions_skill: (optional) Context variables - that are used by the action skill. Private variables are persisted, but not - shown. + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by + the skill. """ def __init__( self, *, - main_skill: Optional['MessageContextDialogSkill'] = None, - actions_skill: Optional['MessageContextActionSkill'] = None, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, ) -> None: """ - Initialize a MessageContextSkills object. + Initialize a MessageContextDialogSkill object. - :param MessageContextDialogSkill main_skill: (optional) Context variables - that are used by the dialog skill. - :param MessageContextActionSkill actions_skill: (optional) Context - variables that are used by the action skill. Private variables are - persisted, but not shown. - """ - self.main_skill = main_skill - self.actions_skill = actions_skill + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + """ + self.user_defined = user_defined + self.system = system @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': - """Initialize a MessageContextSkills object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextDialogSkill': + """Initialize a MessageContextDialogSkill object from a json dictionary.""" args = {} - if (main_skill := _dict.get('main skill')) is not None: - args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) - if (actions_skill := _dict.get('actions skill')) is not None: - args['actions_skill'] = MessageContextActionSkill.from_dict( - actions_skill) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageContextSkills object from a json dictionary.""" + """Initialize a MessageContextDialogSkill 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, 'main_skill') and self.main_skill is not None: - if isinstance(self.main_skill, dict): - _dict['main skill'] = self.main_skill - else: - _dict['main skill'] = self.main_skill.to_dict() - if hasattr(self, 'actions_skill') and self.actions_skill is not None: - if isinstance(self.actions_skill, dict): - _dict['actions skill'] = self.actions_skill + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system else: - _dict['actions skill'] = self.actions_skill.to_dict() + _dict['system'] = self.system.to_dict() return _dict def _to_dict(self): @@ -7019,175 +7170,70 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageContextSkills object.""" + """Return a `str` version of this MessageContextDialogSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageContextSkills') -> bool: + def __eq__(self, other: 'MessageContextDialogSkill') -> 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: 'MessageContextSkills') -> bool: + def __ne__(self, other: 'MessageContextDialogSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInput: +class MessageContextGlobal: """ - An input object that includes the input text. + Session context data that is shared by all skills used by the assistant. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating - the user input. Include intents from the previous response to continue using - those intents rather than trying to recognize intents in the new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the Segment - extension. - :param MessageInputOptions options: (optional) Optional properties that control - how the assistant responds. + :param MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :param str session_id: (optional) The session ID. """ def __init__( self, *, - message_type: Optional[str] = None, - text: Optional[str] = None, - intents: Optional[List['RuntimeIntent']] = None, - entities: Optional[List['RuntimeEntity']] = None, - suggestion_id: Optional[str] = None, - attachments: Optional[List['MessageInputAttachment']] = None, - analytics: Optional['RequestAnalytics'] = None, - options: Optional['MessageInputOptions'] = None, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, ) -> None: """ - Initialize a MessageInput object. + Initialize a MessageContextGlobal object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the - Segment extension. - :param MessageInputOptions options: (optional) Optional properties that - control how the assistant responds. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.analytics = analytics - self.options = options + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInput': - """Initialize a MessageInput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobal': + """Initialize a MessageContextGlobal object from a json dictionary.""" args = {} - if (message_type := _dict.get('message_type')) is not None: - args['message_type'] = message_type - if (text := _dict.get('text')) is not None: - args['text'] = text - if (intents := _dict.get('intents')) is not None: - args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] - if (entities := _dict.get('entities')) is not None: - args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] - if (suggestion_id := _dict.get('suggestion_id')) is not None: - args['suggestion_id'] = suggestion_id - if (attachments := _dict.get('attachments')) is not None: - args['attachments'] = [ - MessageInputAttachment.from_dict(v) for v in attachments - ] - if (analytics := _dict.get('analytics')) is not None: - args['analytics'] = RequestAnalytics.from_dict(analytics) - if (options := _dict.get('options')) is not None: - args['options'] = MessageInputOptions.from_dict(options) + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInput object from a json dictionary.""" + """Initialize a MessageContextGlobal 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, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - attachments_list = [] - for v in self.attachments: - if isinstance(v, dict): - attachments_list.append(v) - else: - attachments_list.append(v.to_dict()) - _dict['attachments'] = attachments_list - if hasattr(self, 'analytics') and self.analytics is not None: - if isinstance(self.analytics, dict): - _dict['analytics'] = self.analytics - else: - _dict['analytics'] = self.analytics.to_dict() - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system else: - _dict['options'] = self.options.to_dict() + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and getattr(self, + 'session_id') is not None: + _dict['session_id'] = getattr(self, 'session_id') return _dict def _to_dict(self): @@ -7195,84 +7241,196 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInput object.""" + """Return a `str` version of this MessageContextGlobal object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInput') -> bool: + def __eq__(self, other: 'MessageContextGlobal') -> 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: 'MessageInput') -> bool: + def __ne__(self, other: 'MessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): - """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. - """ - - TEXT = 'text' - SEARCH = 'search' - - -class MessageInputAttachment: - """ - A reference to a media file to be sent as an attachment with the message. - :param str url: The URL of the media file. - :param str media_type: (optional) The media content type (such as a MIME type) - of the attachment. +class MessageContextGlobalSystem: """ + Built-in system properties that apply to all skills used by the assistant. - def __init__( - self, - url: str, - *, - media_type: Optional[str] = None, - ) -> None: - """ - Initialize a MessageInputAttachment object. - - :param str url: The URL of the media file. - :param str media_type: (optional) The media content type (such as a MIME - type) of the attachment. - """ - self.url = url - self.media_type = media_type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': - """Initialize a MessageInputAttachment object from a json dictionary.""" - args = {} - if (url := _dict.get('url')) is not None: - args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in MessageInputAttachment JSON' - ) - if (media_type := _dict.get('media_type')) is not None: - args['media_type'] = media_type + :param str timezone: (optional) The user time zone. The assistant uses the time + zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root of + the message body. If **user_id** is specified in both locations in a message + request, the value specified at the root is used. + :param int turn_count: (optional) A counter that is automatically incremented + 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). + :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for the + skill. + :param str session_start_time: (optional) The time at which the session started. + With the stateful `message` method, the start time is always present, and is set + by the service based on the time the session was created. With the stateless + `message` method, the start time is set by the service in the response to the + first message, and should be returned as part of the context with each + subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for example, + `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the configuration + state of the assistant at the beginning of the conversation. If you are using + the stateless `message` method, save this value and then send it in the context + of the subsequent message request to avoid disruptions if there are + configuration changes during the conversation (such as a change to a skill the + assistant uses). + :param bool skip_user_input: (optional) For internal use only. + """ + + def __init__( + self, + *, + timezone: Optional[str] = None, + user_id: Optional[str] = None, + turn_count: Optional[int] = None, + locale: Optional[str] = None, + reference_time: Optional[str] = None, + session_start_time: Optional[str] = None, + state: Optional[str] = None, + skip_user_input: Optional[bool] = None, + ) -> None: + """ + Initialize a MessageContextGlobalSystem object. + + :param str timezone: (optional) The user time zone. The assistant uses the + time zone to correctly resolve relative time references. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property at the root + of the message body. If **user_id** is specified in both locations in a + message request, the value specified at the root is used. + :param int turn_count: (optional) A counter that is automatically + incremented 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). + :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, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + This property is included only if the new system entities are enabled for + the skill. + :param str session_start_time: (optional) The time at which the session + started. With the stateful `message` method, the start time is always + present, and is set by the service based on the time the session was + created. With the stateless `message` method, the start time is set by the + service in the response to the first message, and should be returned as + part of the context with each subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the + configuration state of the assistant at the beginning of the conversation. + If you are using the stateless `message` method, save this value and then + send it in the context of the subsequent message request to avoid + disruptions if there are configuration changes during the conversation + (such as a change to a skill the assistant uses). + :param bool skip_user_input: (optional) For internal use only. + """ + self.timezone = timezone + self.user_id = user_id + self.turn_count = turn_count + self.locale = locale + self.reference_time = reference_time + self.session_start_time = session_start_time + self.state = state + self.skip_user_input = skip_user_input + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': + """Initialize a MessageContextGlobalSystem object from a json dictionary.""" + args = {} + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = timezone + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id + if (turn_count := _dict.get('turn_count')) is not None: + args['turn_count'] = turn_count + if (locale := _dict.get('locale')) is not None: + args['locale'] = locale + if (reference_time := _dict.get('reference_time')) is not None: + args['reference_time'] = reference_time + if (session_start_time := _dict.get('session_start_time')) is not None: + args['session_start_time'] = session_start_time + if (state := _dict.get('state')) is not None: + args['state'] = state + if (skip_user_input := _dict.get('skip_user_input')) is not None: + args['skip_user_input'] = skip_user_input return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputAttachment object from a json dictionary.""" + """Initialize a MessageContextGlobalSystem 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, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'media_type') and self.media_type is not None: - _dict['media_type'] = self.media_type + if hasattr(self, 'timezone') and self.timezone is not None: + _dict['timezone'] = self.timezone + if hasattr(self, 'user_id') and self.user_id is not None: + _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 + if hasattr( + self, + 'session_start_time') and self.session_start_time is not None: + _dict['session_start_time'] = self.session_start_time + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state + if hasattr(self, + 'skip_user_input') and self.skip_user_input is not None: + _dict['skip_user_input'] = self.skip_user_input return _dict def _to_dict(self): @@ -7280,242 +7438,229 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputAttachment object.""" + """Return a `str` version of this MessageContextGlobalSystem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputAttachment') -> bool: + def __eq__(self, other: 'MessageContextGlobalSystem') -> 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: 'MessageInputAttachment') -> bool: + def __ne__(self, other: 'MessageContextGlobalSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class LocaleEnum(str, 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. + """ -class MessageInputOptions: + 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 MessageContextSkillSystem: """ - Optional properties that control how the assistant responds. + System context data used by the skill. - :param bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param bool async_callout: (optional) Whether custom extension callouts are - executed asynchronously. Asynchronous execution means the response to the - extension callout will be processed on the subsequent message call, the initial - message response signals to the client that the operation may be long running. - With synchronous execution the custom extension is executed and returns the - response in a single message turn. **Note:** **async_callout** defaults to true - for API versions earlier than 2023-06-15. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. - :param bool return_context: (optional) Whether to return session context with - the response. If you specify `true`, the response includes the `context` - property. If you also specify **debug**=`true`, the returned skill context - includes the `system.state` property. - :param bool export: (optional) Whether to return session context, including full - conversation state. If you specify `true`, the response includes the `context` - property, and the skill context includes the `system.state` property. - **Note:** If **export**=`true`, the context is returned regardless of the value - of **return_context**. + :param str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context of a + subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + + This type supports additional properties of type object. For internal use only. """ + # The set of defined properties for the class + _properties = frozenset(['state']) + def __init__( self, *, - restart: Optional[bool] = None, - alternate_intents: Optional[bool] = None, - async_callout: Optional[bool] = None, - spelling: Optional['MessageInputOptionsSpelling'] = None, - debug: Optional[bool] = None, - return_context: Optional[bool] = None, - export: Optional[bool] = None, + state: Optional[str] = None, + **kwargs: Optional[object], ) -> None: """ - Initialize a MessageInputOptions object. + Initialize a MessageContextSkillSystem object. - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param bool async_callout: (optional) Whether custom extension callouts are - executed asynchronously. Asynchronous execution means the response to the - extension callout will be processed on the subsequent message call, the - initial message response signals to the client that the operation may be - long running. With synchronous execution the custom extension is executed - and returns the response in a single message turn. **Note:** - **async_callout** defaults to true for API versions earlier than - 2023-06-15. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. If you also specify **return_context**=`true`, the - returned skill context includes the `system.state` property. - :param bool return_context: (optional) Whether to return session context - with the response. If you specify `true`, the response includes the - `context` property. If you also specify **debug**=`true`, the returned - skill context includes the `system.state` property. - :param bool export: (optional) Whether to return session context, including - full conversation state. If you specify `true`, the response includes the - `context` property, and the skill context includes the `system.state` - property. - **Note:** If **export**=`true`, the context is returned regardless of the - value of **return_context**. + :param str state: (optional) An encoded string that represents the current + conversation state. By saving this value and then sending it in the context + of a subsequent message request, you can return to an earlier point in the + conversation. If you are using stateful sessions, you can also use a stored + state value to restore a paused conversation whose session is expired. + :param object **kwargs: (optional) For internal use only. """ - self.restart = restart - self.alternate_intents = alternate_intents - self.async_callout = async_callout - self.spelling = spelling - self.debug = debug - self.return_context = return_context - self.export = export + self.state = state + for k, v in kwargs.items(): + if k not in MessageContextSkillSystem._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': - """Initialize a MessageInputOptions object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextSkillSystem': + """Initialize a MessageContextSkillSystem object from a json dictionary.""" args = {} - if (restart := _dict.get('restart')) is not None: - args['restart'] = restart - if (alternate_intents := _dict.get('alternate_intents')) is not None: - args['alternate_intents'] = alternate_intents - if (async_callout := _dict.get('async_callout')) is not None: - args['async_callout'] = async_callout - if (spelling := _dict.get('spelling')) is not None: - args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) - if (debug := _dict.get('debug')) is not None: - args['debug'] = debug - if (return_context := _dict.get('return_context')) is not None: - args['return_context'] = return_context - if (export := _dict.get('export')) is not None: - args['export'] = export + if (state := _dict.get('state')) is not None: + args['state'] = state + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + args[k] = v return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptions object from a json dictionary.""" + """Initialize a MessageContextSkillSystem 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, 'restart') and self.restart is not None: - _dict['restart'] = self.restart - if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'async_callout') and self.async_callout is not None: - _dict['async_callout'] = self.async_callout - if hasattr(self, 'spelling') and self.spelling is not None: - if isinstance(self.spelling, dict): - _dict['spelling'] = self.spelling - else: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug - if hasattr(self, 'return_context') and self.return_context is not None: - _dict['return_context'] = self.return_context - if hasattr(self, 'export') and self.export is not None: - _dict['export'] = self.export + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties + ]: + _dict[k] = getattr(self, k) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return the additional properties from this instance of MessageContextSkillSystem in the form of a dict.""" + _dict = {} + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of additional properties in this instance of MessageContextSkillSystem""" + for k in [ + _k for _k in vars(self).keys() + if _k not in MessageContextSkillSystem._properties + ]: + delattr(self, k) + for k, v in _dict.items(): + if k not in MessageContextSkillSystem._properties: + if not isinstance(v, object): + raise ValueError( + 'Value for additional property {} must be of type object' + .format(k)) + setattr(self, k, v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + def __str__(self) -> str: - """Return a `str` version of this MessageInputOptions object.""" + """Return a `str` version of this MessageContextSkillSystem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptions') -> bool: + def __eq__(self, other: 'MessageContextSkillSystem') -> 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: 'MessageInputOptions') -> bool: + def __ne__(self, other: 'MessageContextSkillSystem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageInputOptionsSpelling: +class MessageContextSkills: """ - Spelling correction options for the message. Any options specified on an individual - message override the settings configured for the skill. + Context data specific to particular skills used by the assistant. - :param bool suggestions: (optional) Whether to use spelling correction when - processing the input. If spelling correction is used and **auto_correct** is - `true`, any spelling corrections are automatically applied to the user input. If - **auto_correct** is `false`, any suggested corrections are returned in the - **output.spelling** property. - This property overrides the value of the **spelling_suggestions** property in - the workspace settings for the skill. - :param bool auto_correct: (optional) Whether to use autocorrection when - processing the input. If this property is `true`, any corrections are - automatically applied to the user input, and the original text is returned in - the **output.spelling** property of the message response. This property - overrides the value of the **spelling_auto_correct** property in the workspace - settings for the skill. + :param MessageContextDialogSkill main_skill: (optional) Context variables that + are used by the dialog skill. + :param MessageContextActionSkill actions_skill: (optional) Context variables + that are used by the action skill. Private variables are persisted, but not + shown. """ def __init__( self, *, - suggestions: Optional[bool] = None, - auto_correct: Optional[bool] = None, + main_skill: Optional['MessageContextDialogSkill'] = None, + actions_skill: Optional['MessageContextActionSkill'] = None, ) -> None: """ - Initialize a MessageInputOptionsSpelling object. + Initialize a MessageContextSkills object. - :param bool suggestions: (optional) Whether to use spelling correction when - processing the input. If spelling correction is used and **auto_correct** - is `true`, any spelling corrections are automatically applied to the user - input. If **auto_correct** is `false`, any suggested corrections are - returned in the **output.spelling** property. - This property overrides the value of the **spelling_suggestions** property - in the workspace settings for the skill. - :param bool auto_correct: (optional) Whether to use autocorrection when - processing the input. If this property is `true`, any corrections are - automatically applied to the user input, and the original text is returned - in the **output.spelling** property of the message response. This property - overrides the value of the **spelling_auto_correct** property in the - workspace settings for the skill. + :param MessageContextDialogSkill main_skill: (optional) Context variables + that are used by the dialog skill. + :param MessageContextActionSkill actions_skill: (optional) Context + variables that are used by the action skill. Private variables are + persisted, but not shown. """ - self.suggestions = suggestions - self.auto_correct = auto_correct + self.main_skill = main_skill + self.actions_skill = actions_skill @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': - """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageContextSkills': + """Initialize a MessageContextSkills object from a json dictionary.""" args = {} - if (suggestions := _dict.get('suggestions')) is not None: - args['suggestions'] = suggestions - if (auto_correct := _dict.get('auto_correct')) is not None: - args['auto_correct'] = auto_correct + if (main_skill := _dict.get('main skill')) is not None: + args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) + if (actions_skill := _dict.get('actions skill')) is not None: + args['actions_skill'] = MessageContextActionSkill.from_dict( + actions_skill) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" + """Initialize a MessageContextSkills 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, 'suggestions') and self.suggestions is not None: - _dict['suggestions'] = self.suggestions - if hasattr(self, 'auto_correct') and self.auto_correct is not None: - _dict['auto_correct'] = self.auto_correct + if hasattr(self, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill + else: + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill + else: + _dict['actions skill'] = self.actions_skill.to_dict() return _dict def _to_dict(self): @@ -7523,120 +7668,139 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageInputOptionsSpelling object.""" + """Return a `str` version of this MessageContextSkills object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageInputOptionsSpelling') -> bool: + def __eq__(self, other: 'MessageContextSkills') -> 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: 'MessageInputOptionsSpelling') -> bool: + def __ne__(self, other: 'MessageContextSkills') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutput: - """ - Assistant output to be rendered or processed by the client. - - :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any - channel. It is the responsibility of the client application to implement the - supported response types. - :param List[RuntimeIntent] intents: (optional) An array of intents recognized in - the user input, sorted in descending order of confidence. - :param List[RuntimeEntity] entities: (optional) An array of entities identified - in the user input. - :param List[DialogNodeAction] actions: (optional) An array of objects describing - any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information - about a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom properties - included in the response. This object includes any arbitrary properties defined - in the dialog JSON editor as part of the dialog node output. - :param MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. +class MessageInput: """ + An input object that includes the input text. - def __init__( - self, - *, - generic: Optional[List['RuntimeResponseGeneric']] = None, - intents: Optional[List['RuntimeIntent']] = None, - entities: Optional[List['RuntimeEntity']] = None, - actions: Optional[List['DialogNodeAction']] = None, - debug: Optional['MessageOutputDebug'] = None, - user_defined: Optional[dict] = None, - spelling: Optional['MessageOutputSpelling'] = None, + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param MessageInputOptions options: (optional) Optional properties that control + how the assistant responds. + """ + + def __init__( + self, + *, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['MessageInputOptions'] = None, ) -> None: """ - Initialize a MessageOutput object. + Initialize a MessageInput object. - :param List[RuntimeResponseGeneric] generic: (optional) Output intended for - any channel. It is the responsibility of the client application to - implement the supported response types. - :param List[RuntimeIntent] intents: (optional) An array of intents - recognized in the user input, sorted in descending order of confidence. - :param List[RuntimeEntity] entities: (optional) An array of entities - identified in the user input. - :param List[DialogNodeAction] actions: (optional) An array of objects - describing any actions requested by the dialog node. - :param MessageOutputDebug debug: (optional) Additional detailed information - about a message response and how it was generated. - :param dict user_defined: (optional) An object containing any custom - properties included in the response. This object includes any arbitrary - properties defined in the dialog JSON editor as part of the dialog node - output. - :param MessageOutputSpelling spelling: (optional) Properties describing any - spelling corrections in the user input that was received. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param MessageInputOptions options: (optional) Optional properties that + control how the assistant responds. """ - self.generic = generic + self.message_type = message_type + self.text = text self.intents = intents self.entities = entities - self.actions = actions - self.debug = debug - self.user_defined = user_defined - self.spelling = spelling + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutput': - """Initialize a MessageOutput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInput': + """Initialize a MessageInput object from a json dictionary.""" args = {} - if (generic := _dict.get('generic')) is not None: - args['generic'] = [ - RuntimeResponseGeneric.from_dict(v) for v in generic - ] + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text if (intents := _dict.get('intents')) is not None: args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] if (entities := _dict.get('entities')) is not None: args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] - if (actions := _dict.get('actions')) is not None: - args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] - if (debug := _dict.get('debug')) is not None: - args['debug'] = MessageOutputDebug.from_dict(debug) - if (user_defined := _dict.get('user_defined')) is not None: - args['user_defined'] = user_defined - if (spelling := _dict.get('spelling')) is not None: - args['spelling'] = MessageOutputSpelling.from_dict(spelling) + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments + ] + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = MessageInputOptions.from_dict(options) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutput object from a json dictionary.""" + """Initialize a MessageInput 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, 'generic') and self.generic is not None: - generic_list = [] - for v in self.generic: - if isinstance(v, dict): - generic_list.append(v) - else: - generic_list.append(v.to_dict()) - _dict['generic'] = generic_list + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text if hasattr(self, 'intents') and self.intents is not None: intents_list = [] for v in self.intents: @@ -7653,26 +7817,26 @@ def to_dict(self) -> Dict: else: entities_list.append(v.to_dict()) _dict['entities'] = entities_list - if hasattr(self, 'actions') and self.actions is not None: - actions_list = [] - for v in self.actions: + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: if isinstance(v, dict): - actions_list.append(v) + attachments_list.append(v) else: - actions_list.append(v.to_dict()) - _dict['actions'] = actions_list - if hasattr(self, 'debug') and self.debug is not None: - if isinstance(self.debug, dict): - _dict['debug'] = self.debug + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics else: - _dict['debug'] = self.debug.to_dict() - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'spelling') and self.spelling is not None: - if isinstance(self.spelling, dict): - _dict['spelling'] = self.spelling + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options else: - _dict['spelling'] = self.spelling.to_dict() + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -7680,133 +7844,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutput object.""" + """Return a `str` version of this MessageInput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutput') -> bool: + def __eq__(self, other: 'MessageInput') -> 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: 'MessageOutput') -> bool: + def __ne__(self, other: 'MessageInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class MessageTypeEnum(str, Enum): + """ + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. + """ -class MessageOutputDebug: + TEXT = 'text' + SEARCH = 'search' + + +class MessageInputAttachment: """ - Additional detailed information about a message response and how it was generated. + A reference to a media file to be sent as an attachment with the message. - :param List[DialogNodeVisited] nodes_visited: (optional) An array of objects - containing detailed diagnostic information about dialog nodes that were visited - during processing of the input message. - :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :param bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :param str branch_exited_reason: (optional) When `branch_exited` is set to - `true` by the assistant, the `branch_exited_reason` specifies whether the dialog - completed by itself or got interrupted. - :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of - objects containing detailed diagnostic information about dialog nodes and - actions that were visited during processing of the input message. - This property is present only if the assistant has an action skill. + :param str url: The URL of the media file. + :param str media_type: (optional) The media content type (such as a MIME type) + of the attachment. """ def __init__( self, + url: str, *, - nodes_visited: Optional[List['DialogNodeVisited']] = None, - log_messages: Optional[List['DialogLogMessage']] = None, - branch_exited: Optional[bool] = None, - branch_exited_reason: Optional[str] = None, - turn_events: Optional[List['MessageOutputDebugTurnEvent']] = None, + media_type: Optional[str] = None, ) -> None: """ - Initialize a MessageOutputDebug object. + Initialize a MessageInputAttachment object. - :param List[DialogNodeVisited] nodes_visited: (optional) An array of - objects containing detailed diagnostic information about dialog nodes that - were visited during processing of the input message. - :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 - messages logged with the request. - :param bool branch_exited: (optional) Assistant sets this to true when this - message response concludes or interrupts a dialog. - :param str branch_exited_reason: (optional) When `branch_exited` is set to - `true` by the assistant, the `branch_exited_reason` specifies whether the - dialog completed by itself or got interrupted. - :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array - of objects containing detailed diagnostic information about dialog nodes - and actions that were visited during processing of the input message. - This property is present only if the assistant has an action skill. + :param str url: The URL of the media file. + :param str media_type: (optional) The media content type (such as a MIME + type) of the attachment. """ - self.nodes_visited = nodes_visited - self.log_messages = log_messages - self.branch_exited = branch_exited - self.branch_exited_reason = branch_exited_reason - self.turn_events = turn_events + self.url = url + self.media_type = media_type @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': - """Initialize a MessageOutputDebug object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': + """Initialize a MessageInputAttachment object from a json dictionary.""" args = {} - if (nodes_visited := _dict.get('nodes_visited')) is not None: - args['nodes_visited'] = [ - DialogNodeVisited.from_dict(v) for v in nodes_visited - ] - if (log_messages := _dict.get('log_messages')) is not None: - args['log_messages'] = [ - DialogLogMessage.from_dict(v) for v in log_messages - ] - if (branch_exited := _dict.get('branch_exited')) is not None: - args['branch_exited'] = branch_exited - if (branch_exited_reason := - _dict.get('branch_exited_reason')) is not None: - args['branch_exited_reason'] = branch_exited_reason - if (turn_events := _dict.get('turn_events')) is not None: - args['turn_events'] = [ - MessageOutputDebugTurnEvent.from_dict(v) for v in turn_events - ] + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in MessageInputAttachment JSON' + ) + if (media_type := _dict.get('media_type')) is not None: + args['media_type'] = media_type return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebug object from a json dictionary.""" + """Initialize a MessageInputAttachment 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, 'nodes_visited') and self.nodes_visited is not None: - nodes_visited_list = [] - for v in self.nodes_visited: - if isinstance(v, dict): - nodes_visited_list.append(v) - else: - nodes_visited_list.append(v.to_dict()) - _dict['nodes_visited'] = nodes_visited_list - if hasattr(self, 'log_messages') and self.log_messages is not None: - log_messages_list = [] - for v in self.log_messages: - if isinstance(v, dict): - log_messages_list.append(v) - else: - log_messages_list.append(v.to_dict()) - _dict['log_messages'] = log_messages_list - if hasattr(self, 'branch_exited') and self.branch_exited is not None: - _dict['branch_exited'] = self.branch_exited - if hasattr(self, 'branch_exited_reason' - ) and self.branch_exited_reason is not None: - _dict['branch_exited_reason'] = self.branch_exited_reason - if hasattr(self, 'turn_events') and self.turn_events is not None: - turn_events_list = [] - for v in self.turn_events: - if isinstance(v, dict): - turn_events_list.append(v) - else: - turn_events_list.append(v.to_dict()) - _dict['turn_events'] = turn_events_list + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'media_type') and self.media_type is not None: + _dict['media_type'] = self.media_type return _dict def _to_dict(self): @@ -7814,173 +7929,153 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebug object.""" + """Return a `str` version of this MessageInputAttachment object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputDebug') -> bool: + def __eq__(self, other: 'MessageInputAttachment') -> 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: 'MessageOutputDebug') -> bool: + def __ne__(self, other: 'MessageInputAttachment') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class BranchExitedReasonEnum(str, Enum): - """ - When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` - specifies whether the dialog completed by itself or got interrupted. - """ - - COMPLETED = 'completed' - FALLBACK = 'fallback' - - -class MessageOutputDebugTurnEvent: - """ - MessageOutputDebugTurnEvent. - - """ - - def __init__(self,) -> None: - """ - Initialize a MessageOutputDebugTurnEvent object. - - """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'MessageOutputDebugTurnEventTurnEventActionVisited', - 'MessageOutputDebugTurnEventTurnEventActionFinished', - 'MessageOutputDebugTurnEventTurnEventStepVisited', - 'MessageOutputDebugTurnEventTurnEventStepAnswered', - 'MessageOutputDebugTurnEventTurnEventHandlerVisited', - 'MessageOutputDebugTurnEventTurnEventCallout', - 'MessageOutputDebugTurnEventTurnEventSearch', - 'MessageOutputDebugTurnEventTurnEventNodeVisited' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': - """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. The discriminator value should map to a valid subclass: {1}".format( - ", ".join([ - 'MessageOutputDebugTurnEventTurnEventActionVisited', - 'MessageOutputDebugTurnEventTurnEventActionFinished', - 'MessageOutputDebugTurnEventTurnEventStepVisited', - 'MessageOutputDebugTurnEventTurnEventStepAnswered', - 'MessageOutputDebugTurnEventTurnEventHandlerVisited', - 'MessageOutputDebugTurnEventTurnEventCallout', - 'MessageOutputDebugTurnEventTurnEventSearch', - 'MessageOutputDebugTurnEventTurnEventNodeVisited' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" - return cls.from_dict(_dict) - - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping[ - 'action_visited'] = 'MessageOutputDebugTurnEventTurnEventActionVisited' - mapping[ - 'action_finished'] = 'MessageOutputDebugTurnEventTurnEventActionFinished' - mapping[ - 'step_visited'] = 'MessageOutputDebugTurnEventTurnEventStepVisited' - mapping[ - 'step_answered'] = 'MessageOutputDebugTurnEventTurnEventStepAnswered' - mapping[ - 'handler_visited'] = 'MessageOutputDebugTurnEventTurnEventHandlerVisited' - mapping['callout'] = 'MessageOutputDebugTurnEventTurnEventCallout' - mapping['search'] = 'MessageOutputDebugTurnEventTurnEventSearch' - mapping[ - 'node_visited'] = 'MessageOutputDebugTurnEventTurnEventNodeVisited' - disc_value = _dict.get('event') - if disc_value is None: - raise ValueError( - 'Discriminator property \'event\' not found in MessageOutputDebugTurnEvent JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - -class MessageOutputSpelling: +class MessageInputOptions: """ - Properties describing any spelling corrections in the user input that was received. + Optional properties that control how the assistant responds. - :param str text: (optional) The user input text that was used to generate the - response. If spelling autocorrection is enabled, this text reflects any spelling - corrections that were applied. - :param str original_text: (optional) The original user input text. This property - is returned only if autocorrection is enabled and the user input was corrected. - :param str suggested_text: (optional) Any suggested corrections of the input - text. This property is returned only if spelling correction is enabled and - autocorrection is disabled. + :param bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the initial + message response signals to the client that the operation may be long running. + With synchronous execution the custom extension is executed and returns the + response in a single message turn. **Note:** **async_callout** defaults to true + for API versions earlier than 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. + :param bool return_context: (optional) Whether to return session context with + the response. If you specify `true`, the response includes the `context` + property. If you also specify **debug**=`true`, the returned skill context + includes the `system.state` property. + :param bool export: (optional) Whether to return session context, including full + conversation state. If you specify `true`, the response includes the `context` + property, and the skill context includes the `system.state` property. + **Note:** If **export**=`true`, the context is returned regardless of the value + of **return_context**. """ def __init__( self, *, - text: Optional[str] = None, - original_text: Optional[str] = None, - suggested_text: Optional[str] = None, + restart: Optional[bool] = None, + alternate_intents: Optional[bool] = None, + async_callout: Optional[bool] = None, + spelling: Optional['MessageInputOptionsSpelling'] = None, + debug: Optional[bool] = None, + return_context: Optional[bool] = None, + export: Optional[bool] = None, ) -> None: """ - Initialize a MessageOutputSpelling object. + Initialize a MessageInputOptions object. - :param str text: (optional) The user input text that was used to generate - the response. If spelling autocorrection is enabled, this text reflects any - spelling corrections that were applied. - :param str original_text: (optional) The original user input text. This - property is returned only if autocorrection is enabled and the user input - was corrected. - :param str suggested_text: (optional) Any suggested corrections of the - input text. This property is returned only if spelling correction is - enabled and autocorrection is disabled. + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the + initial message response signals to the client that the operation may be + long running. With synchronous execution the custom extension is executed + and returns the response in a single message turn. **Note:** + **async_callout** defaults to true for API versions earlier than + 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. If you also specify **return_context**=`true`, the + returned skill context includes the `system.state` property. + :param bool return_context: (optional) Whether to return session context + with the response. If you specify `true`, the response includes the + `context` property. If you also specify **debug**=`true`, the returned + skill context includes the `system.state` property. + :param bool export: (optional) Whether to return session context, including + full conversation state. If you specify `true`, the response includes the + `context` property, and the skill context includes the `system.state` + property. + **Note:** If **export**=`true`, the context is returned regardless of the + value of **return_context**. """ - self.text = text - self.original_text = original_text - self.suggested_text = suggested_text + self.restart = restart + self.alternate_intents = alternate_intents + self.async_callout = async_callout + self.spelling = spelling + self.debug = debug + self.return_context = return_context + self.export = export @classmethod - def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': - """Initialize a MessageOutputSpelling object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputOptions': + """Initialize a MessageInputOptions object from a json dictionary.""" args = {} - if (text := _dict.get('text')) is not None: - args['text'] = text - if (original_text := _dict.get('original_text')) is not None: - args['original_text'] = original_text - if (suggested_text := _dict.get('suggested_text')) is not None: - args['suggested_text'] = suggested_text + if (restart := _dict.get('restart')) is not None: + args['restart'] = restart + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (async_callout := _dict.get('async_callout')) is not None: + args['async_callout'] = async_callout + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (debug := _dict.get('debug')) is not None: + args['debug'] = debug + if (return_context := _dict.get('return_context')) is not None: + args['return_context'] = return_context + if (export := _dict.get('export')) is not None: + args['export'] = export return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputSpelling object from a json dictionary.""" + """Initialize a MessageInputOptions 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'original_text') and self.original_text is not None: - _dict['original_text'] = self.original_text - if hasattr(self, 'suggested_text') and self.suggested_text is not None: - _dict['suggested_text'] = self.suggested_text + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'async_callout') and self.async_callout is not None: + _dict['async_callout'] = self.async_callout + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug + if hasattr(self, 'return_context') and self.return_context is not None: + _dict['return_context'] = self.return_context + if hasattr(self, 'export') and self.export is not None: + _dict['export'] = self.export return _dict def _to_dict(self): @@ -7988,59 +8083,88 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputSpelling object.""" + """Return a `str` version of this MessageInputOptions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'MessageOutputSpelling') -> bool: + def __eq__(self, other: 'MessageInputOptions') -> 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: 'MessageOutputSpelling') -> bool: + def __ne__(self, other: 'MessageInputOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Metadata: +class MessageInputOptionsSpelling: """ - Contains meta-information about the item(s) being streamed. + Spelling correction options for the message. Any options specified on an individual + message override the settings configured for the skill. - :param int id: (optional) Identifies the index and sequence of the current - streamed response item. + :param bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** is + `true`, any spelling corrections are automatically applied to the user input. If + **auto_correct** is `false`, any suggested corrections are returned in the + **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property in + the workspace settings for the skill. + :param bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned in + the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the workspace + settings for the skill. """ def __init__( self, *, - id: Optional[int] = None, + suggestions: Optional[bool] = None, + auto_correct: Optional[bool] = None, ) -> None: """ - Initialize a Metadata object. + Initialize a MessageInputOptionsSpelling object. - :param int id: (optional) Identifies the index and sequence of the current - streamed response item. + :param bool suggestions: (optional) Whether to use spelling correction when + processing the input. If spelling correction is used and **auto_correct** + is `true`, any spelling corrections are automatically applied to the user + input. If **auto_correct** is `false`, any suggested corrections are + returned in the **output.spelling** property. + This property overrides the value of the **spelling_suggestions** property + in the workspace settings for the skill. + :param bool auto_correct: (optional) Whether to use autocorrection when + processing the input. If this property is `true`, any corrections are + automatically applied to the user input, and the original text is returned + in the **output.spelling** property of the message response. This property + overrides the value of the **spelling_auto_correct** property in the + workspace settings for the skill. """ - self.id = id + self.suggestions = suggestions + self.auto_correct = auto_correct @classmethod - def from_dict(cls, _dict: Dict) -> 'Metadata': - """Initialize a Metadata object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageInputOptionsSpelling': + """Initialize a MessageInputOptionsSpelling object from a json dictionary.""" args = {} - if (id := _dict.get('id')) is not None: - args['id'] = id + if (suggestions := _dict.get('suggestions')) is not None: + args['suggestions'] = suggestions + if (auto_correct := _dict.get('auto_correct')) is not None: + args['auto_correct'] = auto_correct return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Metadata object from a json dictionary.""" + """Initialize a MessageInputOptionsSpelling 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, 'id') and self.id is not None: - _dict['id'] = self.id + if hasattr(self, 'suggestions') and self.suggestions is not None: + _dict['suggestions'] = self.suggestions + if hasattr(self, 'auto_correct') and self.auto_correct is not None: + _dict['auto_correct'] = self.auto_correct return _dict def _to_dict(self): @@ -8048,135 +8172,176 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Metadata object.""" + """Return a `str` version of this MessageInputOptionsSpelling object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Metadata') -> bool: + def __eq__(self, other: 'MessageInputOptionsSpelling') -> 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: 'Metadata') -> bool: + def __ne__(self, other: 'MessageInputOptionsSpelling') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MonitorAssistantReleaseImportArtifactResponse: +class MessageOutput: """ - MonitorAssistantReleaseImportArtifactResponse. + Assistant output to be rendered or processed by the client. - :param str status: (optional) The current status of the release import process: - - **Completed**: The artifact import has completed. - - **Failed**: The asynchronous artifact import process has failed. - - **Processing**: An asynchronous operation to import the artifact is underway - and not yet completed. - :param str task_id: (optional) A unique identifier for a background asynchronous - task that is executing or has executed the operation. - :param str assistant_id: (optional) The ID of the assistant to which the release - belongs. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param List[str] skill_impact_in_draft: (optional) An array of skill types in - the draft environment which will be overridden with skills from the artifact - being imported. - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. """ def __init__( self, *, - status: Optional[str] = None, - task_id: Optional[str] = None, - assistant_id: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, - status_description: Optional[str] = None, - skill_impact_in_draft: Optional[List[str]] = None, - created: Optional[datetime] = None, - updated: Optional[datetime] = None, + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, + llm_metadata: Optional[List['MessageOutputLLMMetadata']] = None, ) -> None: """ - Initialize a MonitorAssistantReleaseImportArtifactResponse object. + Initialize a MessageOutput object. - :param List[str] skill_impact_in_draft: (optional) An array of skill types - in the draft environment which will be overridden with skills from the - artifact being imported. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. """ - self.status = status - self.task_id = task_id - self.assistant_id = assistant_id - self.status_errors = status_errors - self.status_description = status_description - self.skill_impact_in_draft = skill_impact_in_draft - self.created = created - self.updated = updated + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling + self.llm_metadata = llm_metadata @classmethod - def from_dict( - cls, - _dict: Dict) -> 'MonitorAssistantReleaseImportArtifactResponse': - """Initialize a MonitorAssistantReleaseImportArtifactResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutput': + """Initialize a MessageOutput object from a json dictionary.""" args = {} - if (status := _dict.get('status')) is not None: - args['status'] = status - if (task_id := _dict.get('task_id')) is not None: - args['task_id'] = task_id - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) + if (llm_metadata := _dict.get('llm_metadata')) is not None: + args['llm_metadata'] = [ + MessageOutputLLMMetadata.from_dict(v) for v in llm_metadata ] - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (skill_impact_in_draft := - _dict.get('skill_impact_in_draft')) is not None: - args['skill_impact_in_draft'] = skill_impact_in_draft - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - if (updated := _dict.get('updated')) is not None: - args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MonitorAssistantReleaseImportArtifactResponse object from a json dictionary.""" + """Initialize a MessageOutput 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, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'task_id') and getattr(self, 'task_id') is not None: - _dict['task_id'] = getattr(self, 'task_id') - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: if isinstance(v, dict): - status_errors_list.append(v) + generic_list.append(v) else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, 'skill_impact_in_draft' - ) and self.skill_impact_in_draft is not None: - _dict['skill_impact_in_draft'] = self.skill_impact_in_draft - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'llm_metadata') and self.llm_metadata is not None: + llm_metadata_list = [] + for v in self.llm_metadata: + if isinstance(v, dict): + llm_metadata_list.append(v) + else: + llm_metadata_list.append(v.to_dict()) + _dict['llm_metadata'] = llm_metadata_list return _dict def _to_dict(self): @@ -8184,134 +8349,133 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MonitorAssistantReleaseImportArtifactResponse object.""" + """Return a `str` version of this MessageOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'MonitorAssistantReleaseImportArtifactResponse') -> bool: + def __eq__(self, other: 'MessageOutput') -> 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: 'MonitorAssistantReleaseImportArtifactResponse') -> bool: + def __ne__(self, other: 'MessageOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the release import process: - - **Completed**: The artifact import has completed. - - **Failed**: The asynchronous artifact import process has failed. - - **Processing**: An asynchronous operation to import the artifact is underway - and not yet completed. - """ - - COMPLETED = 'Completed' - FAILED = 'Failed' - PROCESSING = 'Processing' - - class SkillImpactInDraftEnum(str, Enum): - """ - The type of the skill in the draft environment. - """ - - ACTION = 'action' - DIALOG = 'dialog' - -class Pagination: +class MessageOutputDebug: """ - The pagination data for the returned objects. For more information about using - pagination, see [Pagination](#pagination). + Additional detailed information about a message response and how it was generated. - :param str refresh_url: The URL that will return the same page of results. - :param str next_url: (optional) The URL that will return the next page of - results. - :param int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the current - page. - :param int matched: (optional) Reserved for future use. - :param str refresh_cursor: (optional) A token identifying the current page of - results. - :param str next_cursor: (optional) A token identifying the next page of results. + :param List[DialogNodeVisited] nodes_visited: (optional) An array of objects + containing detailed diagnostic information about dialog nodes that were visited + during processing of the input message. + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :param bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the dialog + completed by itself or got interrupted. + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array of + objects containing detailed diagnostic information about dialog nodes and + actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. """ def __init__( self, - refresh_url: str, *, - next_url: Optional[str] = None, - total: Optional[int] = None, - matched: Optional[int] = None, - refresh_cursor: Optional[str] = None, - next_cursor: Optional[str] = None, + nodes_visited: Optional[List['DialogNodeVisited']] = None, + log_messages: Optional[List['DialogLogMessage']] = None, + branch_exited: Optional[bool] = None, + branch_exited_reason: Optional[str] = None, + turn_events: Optional[List['MessageOutputDebugTurnEvent']] = None, ) -> None: """ - Initialize a Pagination object. + Initialize a MessageOutputDebug object. - :param str refresh_url: The URL that will return the same page of results. - :param str next_url: (optional) The URL that will return the next page of - results. - :param int total: (optional) The total number of objects that satisfy the - request. This total includes all results, not just those included in the - current page. - :param int matched: (optional) Reserved for future use. - :param str refresh_cursor: (optional) A token identifying the current page - of results. - :param str next_cursor: (optional) A token identifying the next page of - results. + :param List[DialogNodeVisited] nodes_visited: (optional) An array of + objects containing detailed diagnostic information about dialog nodes that + were visited during processing of the input message. + :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 + messages logged with the request. + :param bool branch_exited: (optional) Assistant sets this to true when this + message response concludes or interrupts a dialog. + :param str branch_exited_reason: (optional) When `branch_exited` is set to + `true` by the assistant, the `branch_exited_reason` specifies whether the + dialog completed by itself or got interrupted. + :param List[MessageOutputDebugTurnEvent] turn_events: (optional) An array + of objects containing detailed diagnostic information about dialog nodes + and actions that were visited during processing of the input message. + This property is present only if the assistant has an action skill. """ - self.refresh_url = refresh_url - self.next_url = next_url - self.total = total - self.matched = matched - self.refresh_cursor = refresh_cursor - self.next_cursor = next_cursor + self.nodes_visited = nodes_visited + self.log_messages = log_messages + self.branch_exited = branch_exited + self.branch_exited_reason = branch_exited_reason + self.turn_events = turn_events @classmethod - def from_dict(cls, _dict: Dict) -> 'Pagination': - """Initialize a Pagination object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': + """Initialize a MessageOutputDebug object from a json dictionary.""" args = {} - if (refresh_url := _dict.get('refresh_url')) is not None: - args['refresh_url'] = refresh_url - else: - raise ValueError( - 'Required property \'refresh_url\' not present in Pagination JSON' - ) - if (next_url := _dict.get('next_url')) is not None: - args['next_url'] = next_url - if (total := _dict.get('total')) is not None: - args['total'] = total - if (matched := _dict.get('matched')) is not None: - args['matched'] = matched - if (refresh_cursor := _dict.get('refresh_cursor')) is not None: - args['refresh_cursor'] = refresh_cursor - if (next_cursor := _dict.get('next_cursor')) is not None: - args['next_cursor'] = next_cursor + if (nodes_visited := _dict.get('nodes_visited')) is not None: + args['nodes_visited'] = [ + DialogNodeVisited.from_dict(v) for v in nodes_visited + ] + if (log_messages := _dict.get('log_messages')) is not None: + args['log_messages'] = [ + DialogLogMessage.from_dict(v) for v in log_messages + ] + if (branch_exited := _dict.get('branch_exited')) is not None: + args['branch_exited'] = branch_exited + if (branch_exited_reason := + _dict.get('branch_exited_reason')) is not None: + args['branch_exited_reason'] = branch_exited_reason + if (turn_events := _dict.get('turn_events')) is not None: + args['turn_events'] = [ + MessageOutputDebugTurnEvent.from_dict(v) for v in turn_events + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Pagination object from a json dictionary.""" + """Initialize a MessageOutputDebug 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, 'refresh_url') and self.refresh_url is not None: - _dict['refresh_url'] = self.refresh_url - if hasattr(self, 'next_url') and self.next_url is not None: - _dict['next_url'] = self.next_url - if hasattr(self, 'total') and self.total is not None: - _dict['total'] = self.total - if hasattr(self, 'matched') and self.matched is not None: - _dict['matched'] = self.matched - if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: - _dict['refresh_cursor'] = self.refresh_cursor - if hasattr(self, 'next_cursor') and self.next_cursor is not None: - _dict['next_cursor'] = self.next_cursor + if hasattr(self, 'nodes_visited') and self.nodes_visited is not None: + nodes_visited_list = [] + for v in self.nodes_visited: + if isinstance(v, dict): + nodes_visited_list.append(v) + else: + nodes_visited_list.append(v.to_dict()) + _dict['nodes_visited'] = nodes_visited_list + if hasattr(self, 'log_messages') and self.log_messages is not None: + log_messages_list = [] + for v in self.log_messages: + if isinstance(v, dict): + log_messages_list.append(v) + else: + log_messages_list.append(v.to_dict()) + _dict['log_messages'] = log_messages_list + if hasattr(self, 'branch_exited') and self.branch_exited is not None: + _dict['branch_exited'] = self.branch_exited + if hasattr(self, 'branch_exited_reason' + ) and self.branch_exited_reason is not None: + _dict['branch_exited_reason'] = self.branch_exited_reason + if hasattr(self, 'turn_events') and self.turn_events is not None: + turn_events_list = [] + for v in self.turn_events: + if isinstance(v, dict): + turn_events_list.append(v) + else: + turn_events_list.append(v.to_dict()) + _dict['turn_events'] = turn_events_list return _dict def _to_dict(self): @@ -8319,73 +8483,184 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Pagination object.""" + """Return a `str` version of this MessageOutputDebug object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Pagination') -> bool: + def __eq__(self, other: 'MessageOutputDebug') -> 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: 'Pagination') -> bool: + def __ne__(self, other: 'MessageOutputDebug') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - -class ProviderAuthenticationOAuth2: + class BranchExitedReasonEnum(str, Enum): + """ + When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` + specifies whether the dialog completed by itself or got interrupted. + """ + + COMPLETED = 'completed' + FALLBACK = 'fallback' + + +class MessageOutputDebugTurnEvent: """ - Non-private settings for oauth2 authentication. + MessageOutputDebugTurnEvent. - :param str preferred_flow: (optional) The preferred "flow" or "grant type" for - the API client to fetch an access token from the authorization server. - :param ProviderAuthenticationOAuth2Flows flows: (optional) Scenarios performed - by the API client to fetch an access token from the authorization server. + """ + + def __init__(self,) -> None: + """ + Initialize a MessageOutputDebugTurnEvent object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited', + 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd', + 'MessageOutputDebugTurnEventTurnEventManualRoute', + 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied', + 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied', + 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied', + 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled', + 'MessageOutputDebugTurnEventTurnEventClientActions' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageOutputDebugTurnEvent': + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'MessageOutputDebugTurnEvent'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'MessageOutputDebugTurnEventTurnEventActionVisited', + 'MessageOutputDebugTurnEventTurnEventActionFinished', + 'MessageOutputDebugTurnEventTurnEventStepVisited', + 'MessageOutputDebugTurnEventTurnEventStepAnswered', + 'MessageOutputDebugTurnEventTurnEventHandlerVisited', + 'MessageOutputDebugTurnEventTurnEventCallout', + 'MessageOutputDebugTurnEventTurnEventSearch', + 'MessageOutputDebugTurnEventTurnEventNodeVisited', + 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd', + 'MessageOutputDebugTurnEventTurnEventManualRoute', + 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied', + 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied', + 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied', + 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled', + 'MessageOutputDebugTurnEventTurnEventClientActions' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a MessageOutputDebugTurnEvent object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'action_visited'] = 'MessageOutputDebugTurnEventTurnEventActionVisited' + mapping[ + 'action_finished'] = 'MessageOutputDebugTurnEventTurnEventActionFinished' + mapping[ + 'step_visited'] = 'MessageOutputDebugTurnEventTurnEventStepVisited' + mapping[ + 'step_answered'] = 'MessageOutputDebugTurnEventTurnEventStepAnswered' + mapping[ + 'handler_visited'] = 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + mapping['callout'] = 'MessageOutputDebugTurnEventTurnEventCallout' + mapping['search'] = 'MessageOutputDebugTurnEventTurnEventSearch' + mapping[ + 'node_visited'] = 'MessageOutputDebugTurnEventTurnEventNodeVisited' + mapping[ + 'conversational_search_end'] = 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd' + mapping[ + 'manual_route'] = 'MessageOutputDebugTurnEventTurnEventManualRoute' + mapping[ + 'topic_switch_denied'] = 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied' + mapping[ + 'action_routing_denied'] = 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied' + mapping[ + 'suggestion_intents_denied'] = 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied' + mapping[ + 'generative_ai_called'] = 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled' + mapping[ + 'client_actions'] = 'MessageOutputDebugTurnEventTurnEventClientActions' + disc_value = _dict.get('event') + if disc_value is None: + raise ValueError( + 'Discriminator property \'event\' not found in MessageOutputDebugTurnEvent JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class MessageOutputLLMMetadata: + """ + MessageOutputLLMMetadata. + + :param str task: (optional) The task that used a large language model. + :param str model_id: (optional) The id for the large language model used for the + task. """ def __init__( self, *, - preferred_flow: Optional[str] = None, - flows: Optional['ProviderAuthenticationOAuth2Flows'] = None, + task: Optional[str] = None, + model_id: Optional[str] = None, ) -> None: """ - Initialize a ProviderAuthenticationOAuth2 object. + Initialize a MessageOutputLLMMetadata object. - :param str preferred_flow: (optional) The preferred "flow" or "grant type" - for the API client to fetch an access token from the authorization server. - :param ProviderAuthenticationOAuth2Flows flows: (optional) Scenarios - performed by the API client to fetch an access token from the authorization - server. + :param str task: (optional) The task that used a large language model. + :param str model_id: (optional) The id for the large language model used + for the task. """ - self.preferred_flow = preferred_flow - self.flows = flows + self.task = task + self.model_id = model_id @classmethod - def from_dict(cls, _dict: Dict) -> 'ProviderAuthenticationOAuth2': - """Initialize a ProviderAuthenticationOAuth2 object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutputLLMMetadata': + """Initialize a MessageOutputLLMMetadata object from a json dictionary.""" args = {} - if (preferred_flow := _dict.get('preferred_flow')) is not None: - args['preferred_flow'] = preferred_flow - if (flows := _dict.get('flows')) is not None: - args['flows'] = flows + if (task := _dict.get('task')) is not None: + args['task'] = task + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderAuthenticationOAuth2 object from a json dictionary.""" + """Initialize a MessageOutputLLMMetadata 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, 'preferred_flow') and self.preferred_flow is not None: - _dict['preferred_flow'] = self.preferred_flow - if hasattr(self, 'flows') and self.flows is not None: - if isinstance(self.flows, dict): - _dict['flows'] = self.flows - else: - _dict['flows'] = self.flows.to_dict() + if hasattr(self, 'task') and self.task is not None: + _dict['task'] = self.task + if hasattr(self, 'model_id') and self.model_id is not None: + _dict['model_id'] = self.model_id return _dict def _to_dict(self): @@ -8393,98 +8668,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderAuthenticationOAuth2 object.""" + """Return a `str` version of this MessageOutputLLMMetadata object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ProviderAuthenticationOAuth2') -> bool: + def __eq__(self, other: 'MessageOutputLLMMetadata') -> 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: 'ProviderAuthenticationOAuth2') -> bool: + def __ne__(self, other: 'MessageOutputLLMMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class PreferredFlowEnum(str, Enum): - """ - The preferred "flow" or "grant type" for the API client to fetch an access token - from the authorization server. - """ - - PASSWORD = 'password' - CLIENT_CREDENTIALS = 'client_credentials' - AUTHORIZATION_CODE = 'authorization_code' - CUSTOM_FLOW_NAME = '<$custom_flow_name>' - - -class ProviderAuthenticationOAuth2Flows: - """ - Scenarios performed by the API client to fetch an access token from the authorization - server. - - """ - - def __init__(self,) -> None: - """ - Initialize a ProviderAuthenticationOAuth2Flows object. - - """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password', - 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials', - 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode' - ])) - raise Exception(msg) - -class ProviderAuthenticationOAuth2PasswordUsername: +class MessageOutputSpelling: """ - The username for oauth2 authentication when the preferred flow is "password". + Properties describing any spelling corrections in the user input that was received. - :param str type: (optional) The type of property observed in "value". - :param str value: (optional) The stored information of the value. + :param str text: (optional) The user input text that was used to generate the + response. If spelling autocorrection is enabled, this text reflects any spelling + corrections that were applied. + :param str original_text: (optional) The original user input text. This property + is returned only if autocorrection is enabled and the user input was corrected. + :param str suggested_text: (optional) Any suggested corrections of the input + text. This property is returned only if spelling correction is enabled and + autocorrection is disabled. """ def __init__( self, *, - type: Optional[str] = None, - value: Optional[str] = None, + text: Optional[str] = None, + original_text: Optional[str] = None, + suggested_text: Optional[str] = None, ) -> None: """ - Initialize a ProviderAuthenticationOAuth2PasswordUsername object. + Initialize a MessageOutputSpelling object. - :param str type: (optional) The type of property observed in "value". - :param str value: (optional) The stored information of the value. + :param str text: (optional) The user input text that was used to generate + the response. If spelling autocorrection is enabled, this text reflects any + spelling corrections that were applied. + :param str original_text: (optional) The original user input text. This + property is returned only if autocorrection is enabled and the user input + was corrected. + :param str suggested_text: (optional) Any suggested corrections of the + input text. This property is returned only if spelling correction is + enabled and autocorrection is disabled. """ - self.type = type - self.value = value + self.text = text + self.original_text = original_text + self.suggested_text = suggested_text @classmethod - def from_dict( - cls, _dict: Dict) -> 'ProviderAuthenticationOAuth2PasswordUsername': - """Initialize a ProviderAuthenticationOAuth2PasswordUsername object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageOutputSpelling': + """Initialize a MessageOutputSpelling object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (value := _dict.get('value')) is not None: - args['value'] = value + if (text := _dict.get('text')) is not None: + args['text'] = text + if (original_text := _dict.get('original_text')) is not None: + args['original_text'] = original_text + if (suggested_text := _dict.get('suggested_text')) is not None: + args['suggested_text'] = suggested_text return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderAuthenticationOAuth2PasswordUsername object from a json dictionary.""" + """Initialize a MessageOutputSpelling 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 - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'original_text') and self.original_text is not None: + _dict['original_text'] = self.original_text + if hasattr(self, 'suggested_text') and self.suggested_text is not None: + _dict['suggested_text'] = self.suggested_text return _dict def _to_dict(self): @@ -8492,74 +8753,67 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderAuthenticationOAuth2PasswordUsername object.""" + """Return a `str` version of this MessageOutputSpelling object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'ProviderAuthenticationOAuth2PasswordUsername') -> bool: + def __eq__(self, other: 'MessageOutputSpelling') -> 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: 'ProviderAuthenticationOAuth2PasswordUsername') -> bool: + def __ne__(self, other: 'MessageOutputSpelling') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of property observed in "value". - """ - VALUE = 'value' - - -class ProviderAuthenticationTypeAndValue: +class MessageStreamMetadata: """ - ProviderAuthenticationTypeAndValue. + Contains meta-information about the item(s) being streamed. - :param str type: (optional) The type of property observed in "value". - :param str value: (optional) The stored information of the value. + :param Metadata streaming_metadata: Contains meta-information about the item(s) + being streamed. """ def __init__( self, - *, - type: Optional[str] = None, - value: Optional[str] = None, + streaming_metadata: 'Metadata', ) -> None: """ - Initialize a ProviderAuthenticationTypeAndValue object. + Initialize a MessageStreamMetadata object. - :param str type: (optional) The type of property observed in "value". - :param str value: (optional) The stored information of the value. + :param Metadata streaming_metadata: Contains meta-information about the + item(s) being streamed. """ - self.type = type - self.value = value + self.streaming_metadata = streaming_metadata @classmethod - def from_dict(cls, _dict: Dict) -> 'ProviderAuthenticationTypeAndValue': - """Initialize a ProviderAuthenticationTypeAndValue object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'MessageStreamMetadata': + """Initialize a MessageStreamMetadata object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (value := _dict.get('value')) is not None: - args['value'] = value + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = Metadata.from_dict(streaming_metadata) + else: + raise ValueError( + 'Required property \'streaming_metadata\' not present in MessageStreamMetadata JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderAuthenticationTypeAndValue object from a json dictionary.""" + """Initialize a MessageStreamMetadata 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 - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value + if hasattr( + self, + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata + else: + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() return _dict def _to_dict(self): @@ -8567,100 +8821,79 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderAuthenticationTypeAndValue object.""" + """Return a `str` version of this MessageStreamMetadata object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ProviderAuthenticationTypeAndValue') -> bool: + def __eq__(self, other: 'MessageStreamMetadata') -> 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: 'ProviderAuthenticationTypeAndValue') -> bool: + def __ne__(self, other: 'MessageStreamMetadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of property observed in "value". + +class MessageStreamResponse: + """ + A streamed response from the watsonx Assistant service. + + """ + + def __init__(self,) -> None: """ + Initialize a MessageStreamResponse object. - VALUE = 'value' + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'MessageStreamResponseMessageStreamPartialItem', + 'MessageStreamResponseMessageStreamCompleteItem', + 'MessageStreamResponseStatefulMessageStreamFinalResponse' + ])) + raise Exception(msg) -class ProviderCollection: +class Metadata: """ - ProviderCollection. + Contains meta-information about the item(s) being streamed. - :param List[ProviderResponse] conversational_skill_providers: An array of - objects describing the conversational skill providers associated with the - instance. - :param Pagination pagination: The pagination data for the returned objects. For - more information about using pagination, see [Pagination](#pagination). + :param int id: (optional) Identifies the index and sequence of the current + streamed response item. """ def __init__( self, - conversational_skill_providers: List['ProviderResponse'], - pagination: 'Pagination', + *, + id: Optional[int] = None, ) -> None: """ - Initialize a ProviderCollection object. + Initialize a Metadata object. - :param List[ProviderResponse] conversational_skill_providers: An array of - objects describing the conversational skill providers associated with the - instance. - :param Pagination pagination: The pagination data for the returned objects. - For more information about using pagination, see [Pagination](#pagination). + :param int id: (optional) Identifies the index and sequence of the current + streamed response item. """ - self.conversational_skill_providers = conversational_skill_providers - self.pagination = pagination + self.id = id @classmethod - def from_dict(cls, _dict: Dict) -> 'ProviderCollection': - """Initialize a ProviderCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Metadata': + """Initialize a Metadata object from a json dictionary.""" args = {} - if (conversational_skill_providers := - _dict.get('conversational_skill_providers')) is not None: - args['conversational_skill_providers'] = [ - ProviderResponse.from_dict(v) - for v in conversational_skill_providers - ] - else: - raise ValueError( - 'Required property \'conversational_skill_providers\' not present in ProviderCollection JSON' - ) - if (pagination := _dict.get('pagination')) is not None: - args['pagination'] = Pagination.from_dict(pagination) - else: - raise ValueError( - 'Required property \'pagination\' not present in ProviderCollection JSON' - ) + if (id := _dict.get('id')) is not None: + args['id'] = id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderCollection object from a json dictionary.""" + """Initialize a Metadata 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, 'conversational_skill_providers' - ) and self.conversational_skill_providers is not None: - conversational_skill_providers_list = [] - for v in self.conversational_skill_providers: - if isinstance(v, dict): - conversational_skill_providers_list.append(v) - else: - conversational_skill_providers_list.append(v.to_dict()) - _dict[ - 'conversational_skill_providers'] = conversational_skill_providers_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination - else: - _dict['pagination'] = self.pagination.to_dict() + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id return _dict def _to_dict(self): @@ -8668,65 +8901,135 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderCollection object.""" + """Return a `str` version of this Metadata object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ProviderCollection') -> bool: + def __eq__(self, other: 'Metadata') -> 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: 'ProviderCollection') -> bool: + def __ne__(self, other: 'Metadata') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ProviderPrivate: +class MonitorAssistantReleaseImportArtifactResponse: """ - Private information of the provider. + MonitorAssistantReleaseImportArtifactResponse. - :param ProviderPrivateAuthentication authentication: Private authentication - information of the provider. + :param str status: (optional) The current status of the release import process: + - **Completed**: The artifact import has completed. + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import the artifact is underway + and not yet completed. + :param str task_id: (optional) A unique identifier for a background asynchronous + task that is executing or has executed the operation. + :param str assistant_id: (optional) The ID of the assistant to which the release + belongs. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param List[str] skill_impact_in_draft: (optional) An array of skill types in + the draft environment which will be overridden with skills from the artifact + being imported. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. """ def __init__( self, - authentication: 'ProviderPrivateAuthentication', + *, + status: Optional[str] = None, + task_id: Optional[str] = None, + assistant_id: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + skill_impact_in_draft: Optional[List[str]] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, ) -> None: """ - Initialize a ProviderPrivate object. + Initialize a MonitorAssistantReleaseImportArtifactResponse object. - :param ProviderPrivateAuthentication authentication: Private authentication - information of the provider. + :param List[str] skill_impact_in_draft: (optional) An array of skill types + in the draft environment which will be overridden with skills from the + artifact being imported. """ - self.authentication = authentication + self.status = status + self.task_id = task_id + self.assistant_id = assistant_id + self.status_errors = status_errors + self.status_description = status_description + self.skill_impact_in_draft = skill_impact_in_draft + self.created = created + self.updated = updated @classmethod - def from_dict(cls, _dict: Dict) -> 'ProviderPrivate': - """Initialize a ProviderPrivate object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MonitorAssistantReleaseImportArtifactResponse': + """Initialize a MonitorAssistantReleaseImportArtifactResponse object from a json dictionary.""" args = {} - if (authentication := _dict.get('authentication')) is not None: - args['authentication'] = authentication - else: - raise ValueError( - 'Required property \'authentication\' not present in ProviderPrivate JSON' - ) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (task_id := _dict.get('task_id')) is not None: + args['task_id'] = task_id + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (skill_impact_in_draft := + _dict.get('skill_impact_in_draft')) is not None: + args['skill_impact_in_draft'] = skill_impact_in_draft + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderPrivate object from a json dictionary.""" + """Initialize a MonitorAssistantReleaseImportArtifactResponse 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, 'authentication') and self.authentication is not None: - if isinstance(self.authentication, dict): - _dict['authentication'] = self.authentication - else: - _dict['authentication'] = self.authentication.to_dict() + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'task_id') and getattr(self, 'task_id') is not None: + _dict['task_id'] = getattr(self, 'task_id') + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'skill_impact_in_draft' + ) and self.skill_impact_in_draft is not None: + _dict['skill_impact_in_draft'] = self.skill_impact_in_draft + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) return _dict def _to_dict(self): @@ -8734,108 +9037,134 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderPrivate object.""" + """Return a `str` version of this MonitorAssistantReleaseImportArtifactResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ProviderPrivate') -> bool: + def __eq__(self, + other: 'MonitorAssistantReleaseImportArtifactResponse') -> 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: 'ProviderPrivate') -> bool: + def __ne__(self, + other: 'MonitorAssistantReleaseImportArtifactResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The current status of the release import process: + - **Completed**: The artifact import has completed. + - **Failed**: The asynchronous artifact import process has failed. + - **Processing**: An asynchronous operation to import the artifact is underway + and not yet completed. + """ -class ProviderPrivateAuthentication: - """ - Private authentication information of the provider. - - """ + COMPLETED = 'Completed' + FAILED = 'Failed' + PROCESSING = 'Processing' - def __init__(self,) -> None: + class SkillImpactInDraftEnum(str, Enum): """ - Initialize a ProviderPrivateAuthentication object. - - """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'ProviderPrivateAuthenticationBearerFlow', - 'ProviderPrivateAuthenticationBasicFlow', - 'ProviderPrivateAuthenticationOAuth2Flow' - ])) - raise Exception(msg) - - -class ProviderPrivateAuthenticationOAuth2FlowFlows: - """ - Scenarios performed by the API client to fetch an access token from the authorization - server. - - """ - - def __init__(self,) -> None: + The type of the skill in the draft environment. """ - Initialize a ProviderPrivateAuthenticationOAuth2FlowFlows object. - """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password', - 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials', - 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode' - ])) - raise Exception(msg) + ACTION = 'action' + DIALOG = 'dialog' -class ProviderPrivateAuthenticationOAuth2PasswordPassword: +class Pagination: """ - The password for oauth2 authentication when the preferred flow is "password". + The pagination data for the returned objects. For more information about using + pagination, see [Pagination](#pagination). - :param str type: (optional) The type of property observed in "value". - :param str value: (optional) The stored information of the value. + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the current + page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page of + results. + :param str next_cursor: (optional) A token identifying the next page of results. """ def __init__( self, + refresh_url: str, *, - type: Optional[str] = None, - value: Optional[str] = None, + next_url: Optional[str] = None, + total: Optional[int] = None, + matched: Optional[int] = None, + refresh_cursor: Optional[str] = None, + next_cursor: Optional[str] = None, ) -> None: """ - Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object. + Initialize a Pagination object. - :param str type: (optional) The type of property observed in "value". - :param str value: (optional) The stored information of the value. + :param str refresh_url: The URL that will return the same page of results. + :param str next_url: (optional) The URL that will return the next page of + results. + :param int total: (optional) The total number of objects that satisfy the + request. This total includes all results, not just those included in the + current page. + :param int matched: (optional) Reserved for future use. + :param str refresh_cursor: (optional) A token identifying the current page + of results. + :param str next_cursor: (optional) A token identifying the next page of + results. """ - self.type = type - self.value = value + self.refresh_url = refresh_url + self.next_url = next_url + self.total = total + self.matched = matched + self.refresh_cursor = refresh_cursor + self.next_cursor = next_cursor @classmethod - def from_dict( - cls, _dict: Dict - ) -> 'ProviderPrivateAuthenticationOAuth2PasswordPassword': - """Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Pagination': + """Initialize a Pagination object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (value := _dict.get('value')) is not None: - args['value'] = value + if (refresh_url := _dict.get('refresh_url')) is not None: + args['refresh_url'] = refresh_url + else: + raise ValueError( + 'Required property \'refresh_url\' not present in Pagination JSON' + ) + if (next_url := _dict.get('next_url')) is not None: + args['next_url'] = next_url + if (total := _dict.get('total')) is not None: + args['total'] = total + if (matched := _dict.get('matched')) is not None: + args['matched'] = matched + if (refresh_cursor := _dict.get('refresh_cursor')) is not None: + args['refresh_cursor'] = refresh_cursor + if (next_cursor := _dict.get('next_cursor')) is not None: + args['next_cursor'] = next_cursor return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object from a json dictionary.""" + """Initialize a Pagination 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 - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = self.value + if hasattr(self, 'refresh_url') and self.refresh_url is not None: + _dict['refresh_url'] = self.refresh_url + if hasattr(self, 'next_url') and self.next_url is not None: + _dict['next_url'] = self.next_url + if hasattr(self, 'total') and self.total is not None: + _dict['total'] = self.total + if hasattr(self, 'matched') and self.matched is not None: + _dict['matched'] = self.matched + if hasattr(self, 'refresh_cursor') and self.refresh_cursor is not None: + _dict['refresh_cursor'] = self.refresh_cursor + if hasattr(self, 'next_cursor') and self.next_cursor is not None: + _dict['next_cursor'] = self.next_cursor return _dict def _to_dict(self): @@ -8843,82 +9172,93 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderPrivateAuthenticationOAuth2PasswordPassword object.""" + """Return a `str` version of this Pagination object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, other: 'ProviderPrivateAuthenticationOAuth2PasswordPassword' - ) -> bool: + def __eq__(self, other: 'Pagination') -> 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: 'ProviderPrivateAuthenticationOAuth2PasswordPassword' - ) -> bool: + def __ne__(self, other: 'Pagination') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of property observed in "value". - """ - - VALUE = 'value' - -class ProviderResponse: +class PartialItem: """ - ProviderResponse. + Message response partial item content. - :param str provider_id: (optional) The unique identifier of the provider. - :param ProviderResponseSpecification specification: (optional) The specification - of the provider. + :param str response_type: (optional) The type of response returned by the dialog + node. The specified response type must be supported by the client application or + channel. + :param str text: The text within the partial chunk of the message stream + response. + :param Metadata streaming_metadata: Contains meta-information about the item(s) + being streamed. """ def __init__( self, + text: str, + streaming_metadata: 'Metadata', *, - provider_id: Optional[str] = None, - specification: Optional['ProviderResponseSpecification'] = None, + response_type: Optional[str] = None, ) -> None: """ - Initialize a ProviderResponse object. + Initialize a PartialItem object. - :param str provider_id: (optional) The unique identifier of the provider. - :param ProviderResponseSpecification specification: (optional) The - specification of the provider. + :param str text: The text within the partial chunk of the message stream + response. + :param Metadata streaming_metadata: Contains meta-information about the + item(s) being streamed. + :param str response_type: (optional) The type of response returned by the + dialog node. The specified response type must be supported by the client + application or channel. """ - self.provider_id = provider_id - self.specification = specification + self.response_type = response_type + self.text = text + self.streaming_metadata = streaming_metadata @classmethod - def from_dict(cls, _dict: Dict) -> 'ProviderResponse': - """Initialize a ProviderResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'PartialItem': + """Initialize a PartialItem object from a json dictionary.""" args = {} - if (provider_id := _dict.get('provider_id')) is not None: - args['provider_id'] = provider_id - if (specification := _dict.get('specification')) is not None: - args['specification'] = ProviderResponseSpecification.from_dict( - specification) + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type + if (text := _dict.get('text')) is not None: + args['text'] = text + else: + raise ValueError( + 'Required property \'text\' not present in PartialItem JSON') + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = Metadata.from_dict(streaming_metadata) + else: + raise ValueError( + 'Required property \'streaming_metadata\' not present in PartialItem JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderResponse object from a json dictionary.""" + """Initialize a PartialItem 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, 'provider_id') and self.provider_id is not None: - _dict['provider_id'] = self.provider_id - if hasattr(self, 'specification') and self.specification is not None: - if isinstance(self.specification, dict): - _dict['specification'] = self.specification + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr( + self, + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata else: - _dict['specification'] = self.specification.to_dict() + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() return _dict def _to_dict(self): @@ -8926,86 +9266,73 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderResponse object.""" + """Return a `str` version of this PartialItem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ProviderResponse') -> bool: + def __eq__(self, other: 'PartialItem') -> 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: 'ProviderResponse') -> bool: + def __ne__(self, other: 'PartialItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ProviderResponseSpecification: +class ProviderAuthenticationOAuth2: """ - The specification of the provider. + Non-private settings for oauth2 authentication. - :param List[ProviderResponseSpecificationServersItem] servers: (optional) An - array of objects defining all endpoints of the provider. - **Note:** Multiple array items are reserved for future use. - :param ProviderResponseSpecificationComponents components: (optional) An object - defining various reusable definitions of the provider. + :param str preferred_flow: (optional) The preferred "flow" or "grant type" for + the API client to fetch an access token from the authorization server. + :param ProviderAuthenticationOAuth2Flows flows: (optional) Scenarios performed + by the API client to fetch an access token from the authorization server. """ def __init__( self, *, - servers: Optional[ - List['ProviderResponseSpecificationServersItem']] = None, - components: Optional['ProviderResponseSpecificationComponents'] = None, + preferred_flow: Optional[str] = None, + flows: Optional['ProviderAuthenticationOAuth2Flows'] = None, ) -> None: """ - Initialize a ProviderResponseSpecification object. + Initialize a ProviderAuthenticationOAuth2 object. - :param List[ProviderResponseSpecificationServersItem] servers: (optional) - An array of objects defining all endpoints of the provider. - **Note:** Multiple array items are reserved for future use. - :param ProviderResponseSpecificationComponents components: (optional) An - object defining various reusable definitions of the provider. + :param str preferred_flow: (optional) The preferred "flow" or "grant type" + for the API client to fetch an access token from the authorization server. + :param ProviderAuthenticationOAuth2Flows flows: (optional) Scenarios + performed by the API client to fetch an access token from the authorization + server. """ - self.servers = servers - self.components = components + self.preferred_flow = preferred_flow + self.flows = flows @classmethod - def from_dict(cls, _dict: Dict) -> 'ProviderResponseSpecification': - """Initialize a ProviderResponseSpecification object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderAuthenticationOAuth2': + """Initialize a ProviderAuthenticationOAuth2 object from a json dictionary.""" args = {} - if (servers := _dict.get('servers')) is not None: - args['servers'] = [ - ProviderResponseSpecificationServersItem.from_dict(v) - for v in servers - ] - if (components := _dict.get('components')) is not None: - args[ - 'components'] = ProviderResponseSpecificationComponents.from_dict( - components) + if (preferred_flow := _dict.get('preferred_flow')) is not None: + args['preferred_flow'] = preferred_flow + if (flows := _dict.get('flows')) is not None: + args['flows'] = flows return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderResponseSpecification object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2 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, 'servers') and self.servers is not None: - servers_list = [] - for v in self.servers: - if isinstance(v, dict): - servers_list.append(v) - else: - servers_list.append(v.to_dict()) - _dict['servers'] = servers_list - if hasattr(self, 'components') and self.components is not None: - if isinstance(self.components, dict): - _dict['components'] = self.components + if hasattr(self, 'preferred_flow') and self.preferred_flow is not None: + _dict['preferred_flow'] = self.preferred_flow + if hasattr(self, 'flows') and self.flows is not None: + if isinstance(self.flows, dict): + _dict['flows'] = self.flows else: - _dict['components'] = self.components.to_dict() + _dict['flows'] = self.flows.to_dict() return _dict def _to_dict(self): @@ -9013,68 +9340,98 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderResponseSpecification object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2 object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ProviderResponseSpecification') -> bool: + def __eq__(self, other: 'ProviderAuthenticationOAuth2') -> 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: 'ProviderResponseSpecification') -> bool: + def __ne__(self, other: 'ProviderAuthenticationOAuth2') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class PreferredFlowEnum(str, Enum): + """ + The preferred "flow" or "grant type" for the API client to fetch an access token + from the authorization server. + """ + + PASSWORD = 'password' + CLIENT_CREDENTIALS = 'client_credentials' + AUTHORIZATION_CODE = 'authorization_code' + CUSTOM_FLOW_NAME = '<$custom_flow_name>' + -class ProviderResponseSpecificationComponents: +class ProviderAuthenticationOAuth2Flows: """ - An object defining various reusable definitions of the provider. + Scenarios performed by the API client to fetch an access token from the authorization + server. - :param ProviderResponseSpecificationComponentsSecuritySchemes security_schemes: - (optional) The definition of the security scheme for the provider. + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderAuthenticationOAuth2Flows object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password', + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2ClientCredentials', + 'ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode' + ])) + raise Exception(msg) + + +class ProviderAuthenticationOAuth2PasswordUsername: + """ + The username for oauth2 authentication when the preferred flow is "password". + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ def __init__( self, *, - security_schemes: Optional[ - 'ProviderResponseSpecificationComponentsSecuritySchemes'] = None, + type: Optional[str] = None, + value: Optional[str] = None, ) -> None: """ - Initialize a ProviderResponseSpecificationComponents object. + Initialize a ProviderAuthenticationOAuth2PasswordUsername object. - :param ProviderResponseSpecificationComponentsSecuritySchemes - security_schemes: (optional) The definition of the security scheme for the - provider. + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ - self.security_schemes = security_schemes + self.type = type + self.value = value @classmethod - def from_dict(cls, - _dict: Dict) -> 'ProviderResponseSpecificationComponents': - """Initialize a ProviderResponseSpecificationComponents object from a json dictionary.""" + def from_dict( + cls, _dict: Dict) -> 'ProviderAuthenticationOAuth2PasswordUsername': + """Initialize a ProviderAuthenticationOAuth2PasswordUsername object from a json dictionary.""" args = {} - if (security_schemes := _dict.get('securitySchemes')) is not None: - args[ - 'security_schemes'] = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict( - security_schemes) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderResponseSpecificationComponents object from a json dictionary.""" + """Initialize a ProviderAuthenticationOAuth2PasswordUsername 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, - 'security_schemes') and self.security_schemes is not None: - if isinstance(self.security_schemes, dict): - _dict['securitySchemes'] = self.security_schemes - else: - _dict['securitySchemes'] = self.security_schemes.to_dict() + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value return _dict def _to_dict(self): @@ -9082,93 +9439,74 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderResponseSpecificationComponents object.""" + """Return a `str` version of this ProviderAuthenticationOAuth2PasswordUsername object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ProviderResponseSpecificationComponents') -> bool: + def __eq__(self, + other: 'ProviderAuthenticationOAuth2PasswordUsername') -> 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: 'ProviderResponseSpecificationComponents') -> bool: + def __ne__(self, + other: 'ProviderAuthenticationOAuth2PasswordUsername') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of property observed in "value". + """ -class ProviderResponseSpecificationComponentsSecuritySchemes: + VALUE = 'value' + + +class ProviderAuthenticationTypeAndValue: """ - The definition of the security scheme for the provider. + ProviderAuthenticationTypeAndValue. - :param str authentication_method: (optional) The authentication method required - for requests made from watsonx Assistant to the conversational skill provider. - :param ProviderResponseSpecificationComponentsSecuritySchemesBasic basic: - (optional) Non-private settings for basic access authentication. - :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings for - oauth2 authentication. + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ def __init__( self, *, - authentication_method: Optional[str] = None, - basic: Optional[ - 'ProviderResponseSpecificationComponentsSecuritySchemesBasic'] = None, - oauth2: Optional['ProviderAuthenticationOAuth2'] = None, + type: Optional[str] = None, + value: Optional[str] = None, ) -> None: """ - Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object. + Initialize a ProviderAuthenticationTypeAndValue object. - :param str authentication_method: (optional) The authentication method - required for requests made from watsonx Assistant to the conversational - skill provider. - :param ProviderResponseSpecificationComponentsSecuritySchemesBasic basic: - (optional) Non-private settings for basic access authentication. - :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings - for oauth2 authentication. + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ - self.authentication_method = authentication_method - self.basic = basic - self.oauth2 = oauth2 + self.type = type + self.value = value @classmethod - def from_dict( - cls, _dict: Dict - ) -> 'ProviderResponseSpecificationComponentsSecuritySchemes': - """Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderAuthenticationTypeAndValue': + """Initialize a ProviderAuthenticationTypeAndValue object from a json dictionary.""" args = {} - if (authentication_method := - _dict.get('authentication_method')) is not None: - args['authentication_method'] = authentication_method - if (basic := _dict.get('basic')) is not None: - args[ - 'basic'] = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict( - basic) - if (oauth2 := _dict.get('oauth2')) is not None: - args['oauth2'] = ProviderAuthenticationOAuth2.from_dict(oauth2) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object from a json dictionary.""" + """Initialize a ProviderAuthenticationTypeAndValue 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, 'authentication_method' - ) and self.authentication_method is not None: - _dict['authentication_method'] = self.authentication_method - if hasattr(self, 'basic') and self.basic is not None: - if isinstance(self.basic, dict): - _dict['basic'] = self.basic - else: - _dict['basic'] = self.basic.to_dict() - if hasattr(self, 'oauth2') and self.oauth2 is not None: - if isinstance(self.oauth2, dict): - _dict['oauth2'] = self.oauth2 - else: - _dict['oauth2'] = self.oauth2.to_dict() + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value return _dict def _to_dict(self): @@ -9176,81 +9514,100 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderResponseSpecificationComponentsSecuritySchemes object.""" + """Return a `str` version of this ProviderAuthenticationTypeAndValue object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, other: 'ProviderResponseSpecificationComponentsSecuritySchemes' - ) -> bool: + def __eq__(self, other: 'ProviderAuthenticationTypeAndValue') -> 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: 'ProviderResponseSpecificationComponentsSecuritySchemes' - ) -> bool: + def __ne__(self, other: 'ProviderAuthenticationTypeAndValue') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class AuthenticationMethodEnum(str, Enum): + class TypeEnum(str, Enum): """ - The authentication method required for requests made from watsonx Assistant to the - conversational skill provider. + The type of property observed in "value". """ - BASIC = 'basic' - BEARER = 'bearer' - API_KEY = 'api_key' - OAUTH2 = 'oauth2' - NONE = 'none' + VALUE = 'value' -class ProviderResponseSpecificationComponentsSecuritySchemesBasic: +class ProviderCollection: """ - Non-private settings for basic access authentication. + ProviderCollection. - :param ProviderAuthenticationTypeAndValue username: (optional) The username for - basic access authentication. + :param List[ProviderResponse] conversational_skill_providers: An array of + objects describing the conversational skill providers associated with the + instance. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__( self, - *, - username: Optional['ProviderAuthenticationTypeAndValue'] = None, + conversational_skill_providers: List['ProviderResponse'], + pagination: 'Pagination', ) -> None: """ - Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object. + Initialize a ProviderCollection object. - :param ProviderAuthenticationTypeAndValue username: (optional) The username - for basic access authentication. + :param List[ProviderResponse] conversational_skill_providers: An array of + objects describing the conversational skill providers associated with the + instance. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - self.username = username + self.conversational_skill_providers = conversational_skill_providers + self.pagination = pagination @classmethod - def from_dict( - cls, _dict: Dict - ) -> 'ProviderResponseSpecificationComponentsSecuritySchemesBasic': - """Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderCollection': + """Initialize a ProviderCollection object from a json dictionary.""" args = {} - if (username := _dict.get('username')) is not None: - args['username'] = ProviderAuthenticationTypeAndValue.from_dict( - username) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic 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, 'username') and self.username is not None: - if isinstance(self.username, dict): - _dict['username'] = self.username + if (conversational_skill_providers := + _dict.get('conversational_skill_providers')) is not None: + args['conversational_skill_providers'] = [ + ProviderResponse.from_dict(v) + for v in conversational_skill_providers + ] + else: + raise ValueError( + 'Required property \'conversational_skill_providers\' not present in ProviderCollection JSON' + ) + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) + else: + raise ValueError( + 'Required property \'pagination\' not present in ProviderCollection JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderCollection 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, 'conversational_skill_providers' + ) and self.conversational_skill_providers is not None: + conversational_skill_providers_list = [] + for v in self.conversational_skill_providers: + if isinstance(v, dict): + conversational_skill_providers_list.append(v) + else: + conversational_skill_providers_list.append(v.to_dict()) + _dict[ + 'conversational_skill_providers'] = conversational_skill_providers_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination else: - _dict['username'] = self.username.to_dict() + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -9258,64 +9615,65 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderResponseSpecificationComponentsSecuritySchemesBasic object.""" + """Return a `str` version of this ProviderCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, - other: 'ProviderResponseSpecificationComponentsSecuritySchemesBasic' - ) -> bool: + def __eq__(self, other: 'ProviderCollection') -> 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: 'ProviderResponseSpecificationComponentsSecuritySchemesBasic' - ) -> bool: + def __ne__(self, other: 'ProviderCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ProviderResponseSpecificationServersItem: +class ProviderPrivate: """ - ProviderResponseSpecificationServersItem. + Private information of the provider. - :param str url: (optional) The URL of the conversational skill provider. + :param ProviderPrivateAuthentication authentication: Private authentication + information of the provider. """ def __init__( self, - *, - url: Optional[str] = None, + authentication: 'ProviderPrivateAuthentication', ) -> None: """ - Initialize a ProviderResponseSpecificationServersItem object. + Initialize a ProviderPrivate object. - :param str url: (optional) The URL of the conversational skill provider. + :param ProviderPrivateAuthentication authentication: Private authentication + information of the provider. """ - self.url = url + self.authentication = authentication @classmethod - def from_dict(cls, - _dict: Dict) -> 'ProviderResponseSpecificationServersItem': - """Initialize a ProviderResponseSpecificationServersItem object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderPrivate': + """Initialize a ProviderPrivate object from a json dictionary.""" args = {} - if (url := _dict.get('url')) is not None: - args['url'] = url + if (authentication := _dict.get('authentication')) is not None: + args['authentication'] = authentication + else: + raise ValueError( + 'Required property \'authentication\' not present in ProviderPrivate JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderResponseSpecificationServersItem object from a json dictionary.""" + """Initialize a ProviderPrivate 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, 'url') and self.url is not None: - _dict['url'] = self.url + if hasattr(self, 'authentication') and self.authentication is not None: + if isinstance(self.authentication, dict): + _dict['authentication'] = self.authentication + else: + _dict['authentication'] = self.authentication.to_dict() return _dict def _to_dict(self): @@ -9323,87 +9681,108 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderResponseSpecificationServersItem object.""" + """Return a `str` version of this ProviderPrivate object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ProviderResponseSpecificationServersItem') -> bool: + def __eq__(self, other: 'ProviderPrivate') -> 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: 'ProviderResponseSpecificationServersItem') -> bool: + def __ne__(self, other: 'ProviderPrivate') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ProviderSpecification: +class ProviderPrivateAuthentication: """ - The specification of the provider. + Private authentication information of the provider. + + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderPrivateAuthentication object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderPrivateAuthenticationBearerFlow', + 'ProviderPrivateAuthenticationBasicFlow', + 'ProviderPrivateAuthenticationOAuth2Flow' + ])) + raise Exception(msg) + + +class ProviderPrivateAuthenticationOAuth2FlowFlows: + """ + Scenarios performed by the API client to fetch an access token from the authorization + server. - :param List[ProviderSpecificationServersItem] servers: An array of objects - defining all endpoints of the provider. - **Note:** Multiple array items are reserved for future use. - :param ProviderSpecificationComponents components: (optional) An object defining - various reusable definitions of the provider. + """ + + def __init__(self,) -> None: + """ + Initialize a ProviderPrivateAuthenticationOAuth2FlowFlows object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2Password', + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2ClientCredentials', + 'ProviderPrivateAuthenticationOAuth2FlowFlowsProviderPrivateAuthenticationOAuth2AuthorizationCode' + ])) + raise Exception(msg) + + +class ProviderPrivateAuthenticationOAuth2PasswordPassword: + """ + The password for oauth2 authentication when the preferred flow is "password". + + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ def __init__( self, - servers: List['ProviderSpecificationServersItem'], *, - components: Optional['ProviderSpecificationComponents'] = None, + type: Optional[str] = None, + value: Optional[str] = None, ) -> None: """ - Initialize a ProviderSpecification object. + Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object. - :param List[ProviderSpecificationServersItem] servers: An array of objects - defining all endpoints of the provider. - **Note:** Multiple array items are reserved for future use. - :param ProviderSpecificationComponents components: (optional) An object - defining various reusable definitions of the provider. + :param str type: (optional) The type of property observed in "value". + :param str value: (optional) The stored information of the value. """ - self.servers = servers - self.components = components + self.type = type + self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'ProviderSpecification': - """Initialize a ProviderSpecification object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderPrivateAuthenticationOAuth2PasswordPassword': + """Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword object from a json dictionary.""" args = {} - if (servers := _dict.get('servers')) is not None: - args['servers'] = [ - ProviderSpecificationServersItem.from_dict(v) for v in servers - ] - else: - raise ValueError( - 'Required property \'servers\' not present in ProviderSpecification JSON' - ) - if (components := _dict.get('components')) is not None: - args['components'] = ProviderSpecificationComponents.from_dict( - components) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (value := _dict.get('value')) is not None: + args['value'] = value return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderSpecification object from a json dictionary.""" + """Initialize a ProviderPrivateAuthenticationOAuth2PasswordPassword 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, 'servers') and self.servers is not None: - servers_list = [] - for v in self.servers: - if isinstance(v, dict): - servers_list.append(v) - else: - servers_list.append(v.to_dict()) - _dict['servers'] = servers_list - if hasattr(self, 'components') and self.components is not None: - if isinstance(self.components, dict): - _dict['components'] = self.components - else: - _dict['components'] = self.components.to_dict() + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'value') and self.value is not None: + _dict['value'] = self.value return _dict def _to_dict(self): @@ -9411,55 +9790,227 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderSpecification object.""" + """Return a `str` version of this ProviderPrivateAuthenticationOAuth2PasswordPassword object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ProviderSpecification') -> bool: + def __eq__( + self, other: 'ProviderPrivateAuthenticationOAuth2PasswordPassword' + ) -> 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: 'ProviderSpecification') -> bool: + def __ne__( + self, other: 'ProviderPrivateAuthenticationOAuth2PasswordPassword' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of property observed in "value". + """ + + VALUE = 'value' -class ProviderSpecificationComponents: + +class ProviderResponse: """ - An object defining various reusable definitions of the provider. + ProviderResponse. - :param ProviderSpecificationComponentsSecuritySchemes security_schemes: - (optional) The definition of the security scheme for the provider. + :param str provider_id: (optional) The unique identifier of the provider. + :param ProviderResponseSpecification specification: (optional) The specification + of the provider. """ def __init__( self, *, - security_schemes: Optional[ - 'ProviderSpecificationComponentsSecuritySchemes'] = None, + provider_id: Optional[str] = None, + specification: Optional['ProviderResponseSpecification'] = None, ) -> None: """ - Initialize a ProviderSpecificationComponents object. + Initialize a ProviderResponse object. - :param ProviderSpecificationComponentsSecuritySchemes security_schemes: - (optional) The definition of the security scheme for the provider. + :param str provider_id: (optional) The unique identifier of the provider. + :param ProviderResponseSpecification specification: (optional) The + specification of the provider. """ - self.security_schemes = security_schemes + self.provider_id = provider_id + self.specification = specification @classmethod - def from_dict(cls, _dict: Dict) -> 'ProviderSpecificationComponents': - """Initialize a ProviderSpecificationComponents object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderResponse': + """Initialize a ProviderResponse object from a json dictionary.""" args = {} - if (security_schemes := _dict.get('securitySchemes')) is not None: - args[ - 'security_schemes'] = ProviderSpecificationComponentsSecuritySchemes.from_dict( - security_schemes) - return cls(**args) + if (provider_id := _dict.get('provider_id')) is not None: + args['provider_id'] = provider_id + if (specification := _dict.get('specification')) is not None: + args['specification'] = ProviderResponseSpecification.from_dict( + specification) + return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderSpecificationComponents object from a json dictionary.""" + """Initialize a ProviderResponse 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, 'provider_id') and self.provider_id is not None: + _dict['provider_id'] = self.provider_id + if hasattr(self, 'specification') and self.specification is not None: + if isinstance(self.specification, dict): + _dict['specification'] = self.specification + else: + _dict['specification'] = self.specification.to_dict() + 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 ProviderResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponse') -> 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: 'ProviderResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecification: + """ + The specification of the provider. + + :param List[ProviderResponseSpecificationServersItem] servers: (optional) An + array of objects defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderResponseSpecificationComponents components: (optional) An object + defining various reusable definitions of the provider. + """ + + def __init__( + self, + *, + servers: Optional[ + List['ProviderResponseSpecificationServersItem']] = None, + components: Optional['ProviderResponseSpecificationComponents'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecification object. + + :param List[ProviderResponseSpecificationServersItem] servers: (optional) + An array of objects defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderResponseSpecificationComponents components: (optional) An + object defining various reusable definitions of the provider. + """ + self.servers = servers + self.components = components + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ProviderResponseSpecification': + """Initialize a ProviderResponseSpecification object from a json dictionary.""" + args = {} + if (servers := _dict.get('servers')) is not None: + args['servers'] = [ + ProviderResponseSpecificationServersItem.from_dict(v) + for v in servers + ] + if (components := _dict.get('components')) is not None: + args[ + 'components'] = ProviderResponseSpecificationComponents.from_dict( + components) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecification 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, 'servers') and self.servers is not None: + servers_list = [] + for v in self.servers: + if isinstance(v, dict): + servers_list.append(v) + else: + servers_list.append(v.to_dict()) + _dict['servers'] = servers_list + if hasattr(self, 'components') and self.components is not None: + if isinstance(self.components, dict): + _dict['components'] = self.components + else: + _dict['components'] = self.components.to_dict() + 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 ProviderResponseSpecification object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ProviderResponseSpecification') -> 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: 'ProviderResponseSpecification') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ProviderResponseSpecificationComponents: + """ + An object defining various reusable definitions of the provider. + + :param ProviderResponseSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. + """ + + def __init__( + self, + *, + security_schemes: Optional[ + 'ProviderResponseSpecificationComponentsSecuritySchemes'] = None, + ) -> None: + """ + Initialize a ProviderResponseSpecificationComponents object. + + :param ProviderResponseSpecificationComponentsSecuritySchemes + security_schemes: (optional) The definition of the security scheme for the + provider. + """ + self.security_schemes = security_schemes + + @classmethod + def from_dict(cls, + _dict: Dict) -> 'ProviderResponseSpecificationComponents': + """Initialize a ProviderResponseSpecificationComponents object from a json dictionary.""" + args = {} + if (security_schemes := _dict.get('securitySchemes')) is not None: + args[ + 'security_schemes'] = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict( + security_schemes) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ProviderResponseSpecificationComponents object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -9478,28 +10029,28 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderSpecificationComponents object.""" + """Return a `str` version of this ProviderResponseSpecificationComponents object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ProviderSpecificationComponents') -> bool: + def __eq__(self, other: 'ProviderResponseSpecificationComponents') -> 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: 'ProviderSpecificationComponents') -> bool: + def __ne__(self, other: 'ProviderResponseSpecificationComponents') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ProviderSpecificationComponentsSecuritySchemes: +class ProviderResponseSpecificationComponentsSecuritySchemes: """ The definition of the security scheme for the provider. :param str authentication_method: (optional) The authentication method required for requests made from watsonx Assistant to the conversational skill provider. - :param ProviderSpecificationComponentsSecuritySchemesBasic basic: (optional) - Non-private settings for basic access authentication. + :param ProviderResponseSpecificationComponentsSecuritySchemesBasic basic: + (optional) Non-private settings for basic access authentication. :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings for oauth2 authentication. """ @@ -9509,16 +10060,16 @@ def __init__( *, authentication_method: Optional[str] = None, basic: Optional[ - 'ProviderSpecificationComponentsSecuritySchemesBasic'] = None, + 'ProviderResponseSpecificationComponentsSecuritySchemesBasic'] = None, oauth2: Optional['ProviderAuthenticationOAuth2'] = None, ) -> None: """ - Initialize a ProviderSpecificationComponentsSecuritySchemes object. + Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object. :param str authentication_method: (optional) The authentication method required for requests made from watsonx Assistant to the conversational skill provider. - :param ProviderSpecificationComponentsSecuritySchemesBasic basic: + :param ProviderResponseSpecificationComponentsSecuritySchemesBasic basic: (optional) Non-private settings for basic access authentication. :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings for oauth2 authentication. @@ -9529,16 +10080,16 @@ def __init__( @classmethod def from_dict( - cls, - _dict: Dict) -> 'ProviderSpecificationComponentsSecuritySchemes': - """Initialize a ProviderSpecificationComponentsSecuritySchemes object from a json dictionary.""" + cls, _dict: Dict + ) -> 'ProviderResponseSpecificationComponentsSecuritySchemes': + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object from a json dictionary.""" args = {} if (authentication_method := _dict.get('authentication_method')) is not None: args['authentication_method'] = authentication_method if (basic := _dict.get('basic')) is not None: args[ - 'basic'] = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict( + 'basic'] = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict( basic) if (oauth2 := _dict.get('oauth2')) is not None: args['oauth2'] = ProviderAuthenticationOAuth2.from_dict(oauth2) @@ -9546,7 +10097,7 @@ def from_dict( @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderSpecificationComponentsSecuritySchemes object from a json dictionary.""" + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemes object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -9572,18 +10123,20 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderSpecificationComponentsSecuritySchemes object.""" + """Return a `str` version of this ProviderResponseSpecificationComponentsSecuritySchemes object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'ProviderSpecificationComponentsSecuritySchemes') -> bool: + def __eq__( + self, other: 'ProviderResponseSpecificationComponentsSecuritySchemes' + ) -> 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: 'ProviderSpecificationComponentsSecuritySchemes') -> bool: + def __ne__( + self, other: 'ProviderResponseSpecificationComponentsSecuritySchemes' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -9600,7 +10153,7 @@ class AuthenticationMethodEnum(str, Enum): NONE = 'none' -class ProviderSpecificationComponentsSecuritySchemesBasic: +class ProviderResponseSpecificationComponentsSecuritySchemesBasic: """ Non-private settings for basic access authentication. @@ -9614,7 +10167,7 @@ def __init__( username: Optional['ProviderAuthenticationTypeAndValue'] = None, ) -> None: """ - Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object. + Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object. :param ProviderAuthenticationTypeAndValue username: (optional) The username for basic access authentication. @@ -9623,9 +10176,9 @@ def __init__( @classmethod def from_dict( - cls, _dict: Dict - ) -> 'ProviderSpecificationComponentsSecuritySchemesBasic': - """Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + cls, _dict: Dict + ) -> 'ProviderResponseSpecificationComponentsSecuritySchemesBasic': + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" args = {} if (username := _dict.get('username')) is not None: args['username'] = ProviderAuthenticationTypeAndValue.from_dict( @@ -9634,7 +10187,7 @@ def from_dict( @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" + """Initialize a ProviderResponseSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -9652,11 +10205,12 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderSpecificationComponentsSecuritySchemesBasic object.""" + """Return a `str` version of this ProviderResponseSpecificationComponentsSecuritySchemesBasic object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, other: 'ProviderSpecificationComponentsSecuritySchemesBasic' + self, + other: 'ProviderResponseSpecificationComponentsSecuritySchemesBasic' ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): @@ -9664,15 +10218,16 @@ def __eq__( return self.__dict__ == other.__dict__ def __ne__( - self, other: 'ProviderSpecificationComponentsSecuritySchemesBasic' + self, + other: 'ProviderResponseSpecificationComponentsSecuritySchemesBasic' ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ProviderSpecificationServersItem: +class ProviderResponseSpecificationServersItem: """ - ProviderSpecificationServersItem. + ProviderResponseSpecificationServersItem. :param str url: (optional) The URL of the conversational skill provider. """ @@ -9683,15 +10238,16 @@ def __init__( url: Optional[str] = None, ) -> None: """ - Initialize a ProviderSpecificationServersItem object. + Initialize a ProviderResponseSpecificationServersItem object. :param str url: (optional) The URL of the conversational skill provider. """ self.url = url @classmethod - def from_dict(cls, _dict: Dict) -> 'ProviderSpecificationServersItem': - """Initialize a ProviderSpecificationServersItem object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'ProviderResponseSpecificationServersItem': + """Initialize a ProviderResponseSpecificationServersItem object from a json dictionary.""" args = {} if (url := _dict.get('url')) is not None: args['url'] = url @@ -9699,7 +10255,7 @@ def from_dict(cls, _dict: Dict) -> 'ProviderSpecificationServersItem': @classmethod def _from_dict(cls, _dict): - """Initialize a ProviderSpecificationServersItem object from a json dictionary.""" + """Initialize a ProviderResponseSpecificationServersItem object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -9714,120 +10270,87 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ProviderSpecificationServersItem object.""" + """Return a `str` version of this ProviderResponseSpecificationServersItem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ProviderSpecificationServersItem') -> bool: + def __eq__(self, other: 'ProviderResponseSpecificationServersItem') -> 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: 'ProviderSpecificationServersItem') -> bool: + def __ne__(self, other: 'ProviderResponseSpecificationServersItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Release: +class ProviderSpecification: """ - Release. + The specification of the provider. - :param str release: (optional) The name of the release. The name is the version - number (an integer), returned as a string. - :param str description: (optional) The description of the release. - :param List[EnvironmentReference] environment_references: (optional) An array of - objects describing the environments where this release has been deployed. - :param ReleaseContent content: (optional) An object identifying the versionable - content objects (such as skill snapshots) that are included in the release. - :param str status: (optional) The current status of the release: - - **Available**: The release is available for deployment. - - **Failed**: An asynchronous publish operation has failed. - - **Processing**: An asynchronous publish operation has not yet completed. - :param datetime created: (optional) The timestamp for creation of the object. - :param datetime updated: (optional) The timestamp for the most recent update to - the object. + :param List[ProviderSpecificationServersItem] servers: An array of objects + defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderSpecificationComponents components: (optional) An object defining + various reusable definitions of the provider. """ def __init__( self, + servers: List['ProviderSpecificationServersItem'], *, - release: Optional[str] = None, - description: Optional[str] = None, - environment_references: Optional[List['EnvironmentReference']] = None, - content: Optional['ReleaseContent'] = None, - status: Optional[str] = None, - created: Optional[datetime] = None, - updated: Optional[datetime] = None, + components: Optional['ProviderSpecificationComponents'] = None, ) -> None: """ - Initialize a Release object. + Initialize a ProviderSpecification object. - :param str description: (optional) The description of the release. + :param List[ProviderSpecificationServersItem] servers: An array of objects + defining all endpoints of the provider. + **Note:** Multiple array items are reserved for future use. + :param ProviderSpecificationComponents components: (optional) An object + defining various reusable definitions of the provider. """ - self.release = release - self.description = description - self.environment_references = environment_references - self.content = content - self.status = status - self.created = created - self.updated = updated + self.servers = servers + self.components = components @classmethod - def from_dict(cls, _dict: Dict) -> 'Release': - """Initialize a Release object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderSpecification': + """Initialize a ProviderSpecification object from a json dictionary.""" args = {} - if (release := _dict.get('release')) is not None: - args['release'] = release - if (description := _dict.get('description')) is not None: - args['description'] = description - if (environment_references := - _dict.get('environment_references')) is not None: - args['environment_references'] = [ - EnvironmentReference.from_dict(v) - for v in environment_references + if (servers := _dict.get('servers')) is not None: + args['servers'] = [ + ProviderSpecificationServersItem.from_dict(v) for v in servers ] - if (content := _dict.get('content')) is not None: - args['content'] = ReleaseContent.from_dict(content) - if (status := _dict.get('status')) is not None: - args['status'] = status - if (created := _dict.get('created')) is not None: - args['created'] = string_to_datetime(created) - if (updated := _dict.get('updated')) is not None: - args['updated'] = string_to_datetime(updated) + else: + raise ValueError( + 'Required property \'servers\' not present in ProviderSpecification JSON' + ) + if (components := _dict.get('components')) is not None: + args['components'] = ProviderSpecificationComponents.from_dict( + components) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Release object from a json dictionary.""" + """Initialize a ProviderSpecification 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, 'release') and getattr(self, 'release') is not None: - _dict['release'] = getattr(self, 'release') - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'environment_references') and getattr( - self, 'environment_references') is not None: - environment_references_list = [] - for v in getattr(self, 'environment_references'): + if hasattr(self, 'servers') and self.servers is not None: + servers_list = [] + for v in self.servers: if isinstance(v, dict): - environment_references_list.append(v) + servers_list.append(v) else: - environment_references_list.append(v.to_dict()) - _dict['environment_references'] = environment_references_list - if hasattr(self, 'content') and getattr(self, 'content') is not None: - if isinstance(getattr(self, 'content'), dict): - _dict['content'] = getattr(self, 'content') + servers_list.append(v.to_dict()) + _dict['servers'] = servers_list + if hasattr(self, 'components') and self.components is not None: + if isinstance(self.components, dict): + _dict['components'] = self.components else: - _dict['content'] = getattr(self, 'content').to_dict() - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + _dict['components'] = self.components.to_dict() return _dict def _to_dict(self): @@ -9835,97 +10358,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Release object.""" + """Return a `str` version of this ProviderSpecification object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Release') -> bool: + def __eq__(self, other: 'ProviderSpecification') -> 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: 'Release') -> bool: + def __ne__(self, other: 'ProviderSpecification') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the release: - - **Available**: The release is available for deployment. - - **Failed**: An asynchronous publish operation has failed. - - **Processing**: An asynchronous publish operation has not yet completed. - """ - - AVAILABLE = 'Available' - FAILED = 'Failed' - PROCESSING = 'Processing' - -class ReleaseCollection: +class ProviderSpecificationComponents: """ - ReleaseCollection. + An object defining various reusable definitions of the provider. - :param List[Release] releases: An array of objects describing the releases - associated with an assistant. - :param Pagination pagination: The pagination data for the returned objects. For - more information about using pagination, see [Pagination](#pagination). + :param ProviderSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. """ def __init__( self, - releases: List['Release'], - pagination: 'Pagination', + *, + security_schemes: Optional[ + 'ProviderSpecificationComponentsSecuritySchemes'] = None, ) -> None: """ - Initialize a ReleaseCollection object. + Initialize a ProviderSpecificationComponents object. - :param List[Release] releases: An array of objects describing the releases - associated with an assistant. - :param Pagination pagination: The pagination data for the returned objects. - For more information about using pagination, see [Pagination](#pagination). + :param ProviderSpecificationComponentsSecuritySchemes security_schemes: + (optional) The definition of the security scheme for the provider. """ - self.releases = releases - self.pagination = pagination + self.security_schemes = security_schemes @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': - """Initialize a ReleaseCollection object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderSpecificationComponents': + """Initialize a ProviderSpecificationComponents object from a json dictionary.""" args = {} - if (releases := _dict.get('releases')) is not None: - args['releases'] = [Release.from_dict(v) for v in releases] - else: - raise ValueError( - 'Required property \'releases\' not present in ReleaseCollection JSON' - ) - if (pagination := _dict.get('pagination')) is not None: - args['pagination'] = Pagination.from_dict(pagination) - else: - raise ValueError( - 'Required property \'pagination\' not present in ReleaseCollection JSON' - ) + if (security_schemes := _dict.get('securitySchemes')) is not None: + args[ + 'security_schemes'] = ProviderSpecificationComponentsSecuritySchemes.from_dict( + security_schemes) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseCollection object from a json dictionary.""" + """Initialize a ProviderSpecificationComponents 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, 'releases') and self.releases is not None: - releases_list = [] - for v in self.releases: - if isinstance(v, dict): - releases_list.append(v) - else: - releases_list.append(v.to_dict()) - _dict['releases'] = releases_list - if hasattr(self, 'pagination') and self.pagination is not None: - if isinstance(self.pagination, dict): - _dict['pagination'] = self.pagination + if hasattr(self, + 'security_schemes') and self.security_schemes is not None: + if isinstance(self.security_schemes, dict): + _dict['securitySchemes'] = self.security_schemes else: - _dict['pagination'] = self.pagination.to_dict() + _dict['securitySchemes'] = self.security_schemes.to_dict() return _dict def _to_dict(self): @@ -9933,144 +10425,173 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseCollection object.""" + """Return a `str` version of this ProviderSpecificationComponents object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseCollection') -> bool: + def __eq__(self, other: 'ProviderSpecificationComponents') -> 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: 'ReleaseCollection') -> bool: + def __ne__(self, other: 'ProviderSpecificationComponents') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ReleaseContent: +class ProviderSpecificationComponentsSecuritySchemes: """ - An object identifying the versionable content objects (such as skill snapshots) that - are included in the release. + The definition of the security scheme for the provider. - :param List[ReleaseSkill] skills: (optional) The skill snapshots that are - included in the release. + :param str authentication_method: (optional) The authentication method required + for requests made from watsonx Assistant to the conversational skill provider. + :param ProviderSpecificationComponentsSecuritySchemesBasic basic: (optional) + Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings for + oauth2 authentication. """ def __init__( self, *, - skills: Optional[List['ReleaseSkill']] = None, + authentication_method: Optional[str] = None, + basic: Optional[ + 'ProviderSpecificationComponentsSecuritySchemesBasic'] = None, + oauth2: Optional['ProviderAuthenticationOAuth2'] = None, ) -> None: """ - Initialize a ReleaseContent object. + Initialize a ProviderSpecificationComponentsSecuritySchemes object. + :param str authentication_method: (optional) The authentication method + required for requests made from watsonx Assistant to the conversational + skill provider. + :param ProviderSpecificationComponentsSecuritySchemesBasic basic: + (optional) Non-private settings for basic access authentication. + :param ProviderAuthenticationOAuth2 oauth2: (optional) Non-private settings + for oauth2 authentication. """ - self.skills = skills + self.authentication_method = authentication_method + self.basic = basic + self.oauth2 = oauth2 @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseContent': - """Initialize a ReleaseContent object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'ProviderSpecificationComponentsSecuritySchemes': + """Initialize a ProviderSpecificationComponentsSecuritySchemes object from a json dictionary.""" args = {} - if (skills := _dict.get('skills')) is not None: - args['skills'] = [ReleaseSkill.from_dict(v) for v in skills] + if (authentication_method := + _dict.get('authentication_method')) is not None: + args['authentication_method'] = authentication_method + if (basic := _dict.get('basic')) is not None: + args[ + 'basic'] = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict( + basic) + if (oauth2 := _dict.get('oauth2')) is not None: + args['oauth2'] = ProviderAuthenticationOAuth2.from_dict(oauth2) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseContent object from a json dictionary.""" + """Initialize a ProviderSpecificationComponentsSecuritySchemes 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, 'skills') and getattr(self, 'skills') is not None: - skills_list = [] - for v in getattr(self, 'skills'): - if isinstance(v, dict): - skills_list.append(v) - else: - skills_list.append(v.to_dict()) - _dict['skills'] = skills_list - 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 ReleaseContent object.""" + if hasattr(self, 'authentication_method' + ) and self.authentication_method is not None: + _dict['authentication_method'] = self.authentication_method + if hasattr(self, 'basic') and self.basic is not None: + if isinstance(self.basic, dict): + _dict['basic'] = self.basic + else: + _dict['basic'] = self.basic.to_dict() + if hasattr(self, 'oauth2') and self.oauth2 is not None: + if isinstance(self.oauth2, dict): + _dict['oauth2'] = self.oauth2 + else: + _dict['oauth2'] = self.oauth2.to_dict() + 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 ProviderSpecificationComponentsSecuritySchemes object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseContent') -> bool: + def __eq__(self, + other: 'ProviderSpecificationComponentsSecuritySchemes') -> 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: 'ReleaseContent') -> bool: + def __ne__(self, + other: 'ProviderSpecificationComponentsSecuritySchemes') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class AuthenticationMethodEnum(str, Enum): + """ + The authentication method required for requests made from watsonx Assistant to the + conversational skill provider. + """ + + BASIC = 'basic' + BEARER = 'bearer' + API_KEY = 'api_key' + OAUTH2 = 'oauth2' + NONE = 'none' + -class ReleaseSkill: +class ProviderSpecificationComponentsSecuritySchemesBasic: """ - ReleaseSkill. + Non-private settings for basic access authentication. - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. - :param str snapshot: (optional) The name of the skill snapshot that is saved as - part of the release (for example, `draft` or `1`). + :param ProviderAuthenticationTypeAndValue username: (optional) The username for + basic access authentication. """ def __init__( self, - skill_id: str, *, - type: Optional[str] = None, - snapshot: Optional[str] = None, + username: Optional['ProviderAuthenticationTypeAndValue'] = None, ) -> None: """ - Initialize a ReleaseSkill object. + Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object. - :param str skill_id: The skill ID of the skill. - :param str type: (optional) The type of the skill. - :param str snapshot: (optional) The name of the skill snapshot that is - saved as part of the release (for example, `draft` or `1`). + :param ProviderAuthenticationTypeAndValue username: (optional) The username + for basic access authentication. """ - self.skill_id = skill_id - self.type = type - self.snapshot = snapshot + self.username = username @classmethod - def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': - """Initialize a ReleaseSkill object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'ProviderSpecificationComponentsSecuritySchemesBasic': + """Initialize a ProviderSpecificationComponentsSecuritySchemesBasic object from a json dictionary.""" args = {} - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - else: - raise ValueError( - 'Required property \'skill_id\' not present in ReleaseSkill JSON' - ) - if (type := _dict.get('type')) is not None: - args['type'] = type - if (snapshot := _dict.get('snapshot')) is not None: - args['snapshot'] = snapshot + if (username := _dict.get('username')) is not None: + args['username'] = ProviderAuthenticationTypeAndValue.from_dict( + username) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ReleaseSkill object from a json dictionary.""" + """Initialize a ProviderSpecificationComponentsSecuritySchemesBasic 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, 'skill_id') and self.skill_id is not None: - _dict['skill_id'] = self.skill_id - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type - if hasattr(self, 'snapshot') and self.snapshot is not None: - _dict['snapshot'] = self.snapshot + if hasattr(self, 'username') and self.username is not None: + if isinstance(self.username, dict): + _dict['username'] = self.username + else: + _dict['username'] = self.username.to_dict() return _dict def _to_dict(self): @@ -10078,89 +10599,61 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this ReleaseSkill object.""" + """Return a `str` version of this ProviderSpecificationComponentsSecuritySchemesBasic object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'ReleaseSkill') -> bool: + def __eq__( + self, other: 'ProviderSpecificationComponentsSecuritySchemesBasic' + ) -> 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: 'ReleaseSkill') -> bool: + def __ne__( + self, other: 'ProviderSpecificationComponentsSecuritySchemesBasic' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of the skill. - """ - - DIALOG = 'dialog' - ACTION = 'action' - SEARCH = 'search' - -class RequestAnalytics: +class ProviderSpecificationServersItem: """ - An optional object containing analytics data. Currently, this data is used only for - events sent to the Segment extension. + ProviderSpecificationServersItem. - :param str browser: (optional) The browser that was used to send the message - that triggered the event. - :param str device: (optional) The type of device that was used to send the - message that triggered the event. - :param str page_url: (optional) The URL of the web page that was used to send - the message that triggered the event. + :param str url: (optional) The URL of the conversational skill provider. """ def __init__( self, *, - browser: Optional[str] = None, - device: Optional[str] = None, - page_url: Optional[str] = None, + url: Optional[str] = None, ) -> None: """ - Initialize a RequestAnalytics object. + Initialize a ProviderSpecificationServersItem object. - :param str browser: (optional) The browser that was used to send the - message that triggered the event. - :param str device: (optional) The type of device that was used to send the - message that triggered the event. - :param str page_url: (optional) The URL of the web page that was used to - send the message that triggered the event. + :param str url: (optional) The URL of the conversational skill provider. """ - self.browser = browser - self.device = device - self.page_url = page_url + self.url = url @classmethod - def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': - """Initialize a RequestAnalytics object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ProviderSpecificationServersItem': + """Initialize a ProviderSpecificationServersItem object from a json dictionary.""" args = {} - if (browser := _dict.get('browser')) is not None: - args['browser'] = browser - if (device := _dict.get('device')) is not None: - args['device'] = device - if (page_url := _dict.get('pageUrl')) is not None: - args['page_url'] = page_url + if (url := _dict.get('url')) is not None: + args['url'] = url return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RequestAnalytics object from a json dictionary.""" + """Initialize a ProviderSpecificationServersItem 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, 'browser') and self.browser is not None: - _dict['browser'] = self.browser - if hasattr(self, 'device') and self.device is not None: - _dict['device'] = self.device - if hasattr(self, 'page_url') and self.page_url is not None: - _dict['pageUrl'] = self.page_url + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url return _dict def _to_dict(self): @@ -10168,253 +10661,218 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RequestAnalytics object.""" + """Return a `str` version of this ProviderSpecificationServersItem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RequestAnalytics') -> bool: + def __eq__(self, other: 'ProviderSpecificationServersItem') -> 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: 'RequestAnalytics') -> bool: + def __ne__(self, other: 'ProviderSpecificationServersItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class ResponseGenericChannel: +class Release: """ - ResponseGenericChannel. + Release. - :param str channel: (optional) A channel for which the response is intended. + :param str release: (optional) The name of the release. The name is the version + number (an integer), returned as a string. + :param str description: (optional) The description of the release. + :param List[EnvironmentReference] environment_references: (optional) An array of + objects describing the environments where this release has been deployed. + :param ReleaseContent content: (optional) An object identifying the versionable + content objects (such as skill snapshots) that are included in the release. + :param str status: (optional) The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + :param datetime created: (optional) The timestamp for creation of the object. + :param datetime updated: (optional) The timestamp for the most recent update to + the object. """ def __init__( self, *, - channel: Optional[str] = None, + release: Optional[str] = None, + description: Optional[str] = None, + environment_references: Optional[List['EnvironmentReference']] = None, + content: Optional['ReleaseContent'] = None, + status: Optional[str] = None, + created: Optional[datetime] = None, + updated: Optional[datetime] = None, ) -> None: """ - Initialize a ResponseGenericChannel object. + Initialize a Release object. - :param str channel: (optional) A channel for which the response is - intended. + :param str description: (optional) The description of the release. """ - self.channel = channel + self.release = release + self.description = description + self.environment_references = environment_references + self.content = content + self.status = status + self.created = created + self.updated = updated @classmethod - def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': - """Initialize a ResponseGenericChannel object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'Release': + """Initialize a Release object from a json dictionary.""" args = {} - if (channel := _dict.get('channel')) is not None: - args['channel'] = channel + if (release := _dict.get('release')) is not None: + args['release'] = release + if (description := _dict.get('description')) is not None: + args['description'] = description + if (environment_references := + _dict.get('environment_references')) is not None: + args['environment_references'] = [ + EnvironmentReference.from_dict(v) + for v in environment_references + ] + if (content := _dict.get('content')) is not None: + args['content'] = ReleaseContent.from_dict(content) + if (status := _dict.get('status')) is not None: + args['status'] = status + if (created := _dict.get('created')) is not None: + args['created'] = string_to_datetime(created) + if (updated := _dict.get('updated')) is not None: + args['updated'] = string_to_datetime(updated) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a ResponseGenericChannel object from a json dictionary.""" + """Initialize a Release 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, 'channel') and self.channel is not None: - _dict['channel'] = self.channel - 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 ResponseGenericChannel object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ResponseGenericChannel') -> bool: - """Return `true` when self and other are equal, false otherwise.""" - if not isinstance(other, self.__class__): - return False - return self.__dict__ == other.__dict__ + if hasattr(self, 'release') and getattr(self, 'release') is not None: + _dict['release'] = getattr(self, 'release') + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'environment_references') and getattr( + self, 'environment_references') is not None: + environment_references_list = [] + for v in getattr(self, 'environment_references'): + if isinstance(v, dict): + environment_references_list.append(v) + else: + environment_references_list.append(v.to_dict()) + _dict['environment_references'] = environment_references_list + if hasattr(self, 'content') and getattr(self, 'content') is not None: + if isinstance(getattr(self, 'content'), dict): + _dict['content'] = getattr(self, 'content') + else: + _dict['content'] = getattr(self, 'content').to_dict() + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'created') and getattr(self, 'created') is not None: + _dict['created'] = datetime_to_string(getattr(self, 'created')) + if hasattr(self, 'updated') and getattr(self, 'updated') is not None: + _dict['updated'] = datetime_to_string(getattr(self, 'updated')) + return _dict - def __ne__(self, other: 'ResponseGenericChannel') -> bool: + 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 Release object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Release') -> 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: 'Release') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class StatusEnum(str, Enum): + """ + The current status of the release: + - **Available**: The release is available for deployment. + - **Failed**: An asynchronous publish operation has failed. + - **Processing**: An asynchronous publish operation has not yet completed. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + PROCESSING = 'Processing' + -class RuntimeEntity: +class ReleaseCollection: """ - The entity value that was recognized in the user input. + ReleaseCollection. - :param str entity: An entity detected in the input. - :param List[int] location: (optional) An array of zero-based character offsets - that indicate where the detected entity values begin and end in the input text. - :param str value: The term in the input text that was recognized as an entity - value. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized 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. - :param str skill: (optional) The skill that recognized the entity value. - Currently, the only possible values are `main skill` for the dialog skill (if - enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and an - action skill. + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. For + more information about using pagination, see [Pagination](#pagination). """ def __init__( self, - entity: str, - value: str, - *, - location: Optional[List[int]] = None, - confidence: Optional[float] = None, - groups: Optional[List['CaptureGroup']] = None, - interpretation: Optional['RuntimeEntityInterpretation'] = None, - alternatives: Optional[List['RuntimeEntityAlternative']] = None, - role: Optional['RuntimeEntityRole'] = None, - skill: Optional[str] = None, + releases: List['Release'], + pagination: 'Pagination', ) -> None: """ - Initialize a RuntimeEntity object. + Initialize a ReleaseCollection object. - :param str entity: An entity detected in the input. - :param str value: The term in the input text that was recognized as an - entity value. - :param List[int] location: (optional) An array of zero-based character - offsets that indicate where the detected entity values begin and end in the - input text. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized 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. - :param str skill: (optional) The skill that recognized the entity value. - Currently, the only possible values are `main skill` for the dialog skill - (if enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and - an action skill. + :param List[Release] releases: An array of objects describing the releases + associated with an assistant. + :param Pagination pagination: The pagination data for the returned objects. + For more information about using pagination, see [Pagination](#pagination). """ - self.entity = entity - self.location = location - self.value = value - self.confidence = confidence - self.groups = groups - self.interpretation = interpretation - self.alternatives = alternatives - self.role = role - self.skill = skill + self.releases = releases + self.pagination = pagination @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': - """Initialize a RuntimeEntity object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ReleaseCollection': + """Initialize a ReleaseCollection object from a json dictionary.""" args = {} - if (entity := _dict.get('entity')) is not None: - args['entity'] = entity + if (releases := _dict.get('releases')) is not None: + args['releases'] = [Release.from_dict(v) for v in releases] else: raise ValueError( - 'Required property \'entity\' not present in RuntimeEntity JSON' + 'Required property \'releases\' not present in ReleaseCollection JSON' ) - if (location := _dict.get('location')) is not None: - args['location'] = location - if (value := _dict.get('value')) is not None: - args['value'] = value + if (pagination := _dict.get('pagination')) is not None: + args['pagination'] = Pagination.from_dict(pagination) else: raise ValueError( - 'Required property \'value\' not present in RuntimeEntity JSON') - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (groups := _dict.get('groups')) is not None: - args['groups'] = [CaptureGroup.from_dict(v) for v in groups] - if (interpretation := _dict.get('interpretation')) is not None: - args['interpretation'] = RuntimeEntityInterpretation.from_dict( - interpretation) - if (alternatives := _dict.get('alternatives')) is not None: - args['alternatives'] = [ - RuntimeEntityAlternative.from_dict(v) for v in alternatives - ] - if (role := _dict.get('role')) is not None: - args['role'] = RuntimeEntityRole.from_dict(role) - if (skill := _dict.get('skill')) is not None: - args['skill'] = skill + 'Required property \'pagination\' not present in ReleaseCollection JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntity object from a json dictionary.""" + """Initialize a ReleaseCollection 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, 'entity') and self.entity is not None: - _dict['entity'] = self.entity - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location - 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 - if hasattr(self, 'groups') and self.groups is not None: - groups_list = [] - for v in self.groups: - if isinstance(v, dict): - groups_list.append(v) - else: - groups_list.append(v.to_dict()) - _dict['groups'] = groups_list - if hasattr(self, 'interpretation') and self.interpretation is not None: - if isinstance(self.interpretation, dict): - _dict['interpretation'] = self.interpretation - else: - _dict['interpretation'] = self.interpretation.to_dict() - if hasattr(self, 'alternatives') and self.alternatives is not None: - alternatives_list = [] - for v in self.alternatives: + if hasattr(self, 'releases') and self.releases is not None: + releases_list = [] + for v in self.releases: if isinstance(v, dict): - alternatives_list.append(v) + releases_list.append(v) else: - alternatives_list.append(v.to_dict()) - _dict['alternatives'] = alternatives_list - if hasattr(self, 'role') and self.role is not None: - if isinstance(self.role, dict): - _dict['role'] = self.role + releases_list.append(v.to_dict()) + _dict['releases'] = releases_list + if hasattr(self, 'pagination') and self.pagination is not None: + if isinstance(self.pagination, dict): + _dict['pagination'] = self.pagination else: - _dict['role'] = self.role.to_dict() - if hasattr(self, 'skill') and self.skill is not None: - _dict['skill'] = self.skill + _dict['pagination'] = self.pagination.to_dict() return _dict def _to_dict(self): @@ -10422,69 +10880,64 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntity object.""" + """Return a `str` version of this ReleaseCollection object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntity') -> bool: + def __eq__(self, other: 'ReleaseCollection') -> 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: 'RuntimeEntity') -> bool: + def __ne__(self, other: 'ReleaseCollection') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityAlternative: +class ReleaseContent: """ - An alternative value for the recognized entity. + An object identifying the versionable content objects (such as skill snapshots) that + are included in the release. - :param str value: (optional) The entity value that was recognized in the user - input. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized entity. + :param List[ReleaseSkill] skills: (optional) The skill snapshots that are + included in the release. """ def __init__( self, *, - value: Optional[str] = None, - confidence: Optional[float] = None, + skills: Optional[List['ReleaseSkill']] = None, ) -> None: """ - Initialize a RuntimeEntityAlternative object. + Initialize a ReleaseContent object. - :param str value: (optional) The entity value that was recognized in the - user input. - :param float confidence: (optional) A decimal percentage that represents - confidence in the recognized entity. """ - self.value = value - self.confidence = confidence + self.skills = skills @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityAlternative': - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ReleaseContent': + """Initialize a ReleaseContent object from a json dictionary.""" args = {} - if (value := _dict.get('value')) is not None: - args['value'] = value - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence + if (skills := _dict.get('skills')) is not None: + args['skills'] = [ReleaseSkill.from_dict(v) for v in skills] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityAlternative object from a json dictionary.""" + """Initialize a ReleaseContent 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 + if hasattr(self, 'skills') and getattr(self, 'skills') is not None: + skills_list = [] + for v in getattr(self, 'skills'): + if isinstance(v, dict): + skills_list.append(v) + else: + skills_list.append(v.to_dict()) + _dict['skills'] = skills_list return _dict def _to_dict(self): @@ -10492,354 +10945,3960 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityAlternative object.""" + """Return a `str` version of this ReleaseContent object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityAlternative') -> bool: + def __eq__(self, other: 'ReleaseContent') -> 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: + def __ne__(self, other: 'ReleaseContent') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeEntityInterpretation: +class ReleaseSkill: """ - RuntimeEntityInterpretation. + ReleaseSkill. - :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`). + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is saved as + part of the release (for example, `draft` or `1`). """ def __init__( self, + skill_id: str, *, - calendar_type: Optional[str] = None, - datetime_link: Optional[str] = None, - festival: Optional[str] = None, - granularity: Optional[str] = None, - range_link: Optional[str] = None, - range_modifier: Optional[str] = None, - relative_day: Optional[float] = None, - relative_month: Optional[float] = None, - relative_week: Optional[float] = None, - relative_weekend: Optional[float] = None, - relative_year: Optional[float] = None, - specific_day: Optional[float] = None, - specific_day_of_week: Optional[str] = None, - specific_month: Optional[float] = None, - specific_quarter: Optional[float] = None, - specific_year: Optional[float] = None, - numeric_value: Optional[float] = None, - subtype: Optional[str] = None, - part_of_day: Optional[str] = None, - relative_hour: Optional[float] = None, - relative_minute: Optional[float] = None, - relative_second: Optional[float] = None, - specific_hour: Optional[float] = None, - specific_minute: Optional[float] = None, - specific_second: Optional[float] = None, - timezone: Optional[str] = None, + type: Optional[str] = None, + snapshot: Optional[str] = None, ) -> None: """ - Initialize a RuntimeEntityInterpretation object. + Initialize a ReleaseSkill 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`). + :param str skill_id: The skill ID of the skill. + :param str type: (optional) The type of the skill. + :param str snapshot: (optional) The name of the skill snapshot that is + saved as part of the release (for example, `draft` or `1`). """ - 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 + self.skill_id = skill_id + self.type = type + self.snapshot = snapshot @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityInterpretation': - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'ReleaseSkill': + """Initialize a ReleaseSkill object from a json dictionary.""" args = {} - if (calendar_type := _dict.get('calendar_type')) is not None: - args['calendar_type'] = calendar_type - if (datetime_link := _dict.get('datetime_link')) is not None: - args['datetime_link'] = datetime_link - if (festival := _dict.get('festival')) is not None: - args['festival'] = festival - if (granularity := _dict.get('granularity')) is not None: - args['granularity'] = granularity - if (range_link := _dict.get('range_link')) is not None: - args['range_link'] = range_link - if (range_modifier := _dict.get('range_modifier')) is not None: - args['range_modifier'] = range_modifier - if (relative_day := _dict.get('relative_day')) is not None: - args['relative_day'] = relative_day - if (relative_month := _dict.get('relative_month')) is not None: - args['relative_month'] = relative_month - if (relative_week := _dict.get('relative_week')) is not None: - args['relative_week'] = relative_week - if (relative_weekend := _dict.get('relative_weekend')) is not None: - args['relative_weekend'] = relative_weekend - if (relative_year := _dict.get('relative_year')) is not None: - args['relative_year'] = relative_year - if (specific_day := _dict.get('specific_day')) is not None: - args['specific_day'] = specific_day - if (specific_day_of_week := - _dict.get('specific_day_of_week')) is not None: - args['specific_day_of_week'] = specific_day_of_week - if (specific_month := _dict.get('specific_month')) is not None: - args['specific_month'] = specific_month - if (specific_quarter := _dict.get('specific_quarter')) is not None: - args['specific_quarter'] = specific_quarter - if (specific_year := _dict.get('specific_year')) is not None: - args['specific_year'] = specific_year - if (numeric_value := _dict.get('numeric_value')) is not None: - args['numeric_value'] = numeric_value - if (subtype := _dict.get('subtype')) is not None: - args['subtype'] = subtype - if (part_of_day := _dict.get('part_of_day')) is not None: - args['part_of_day'] = part_of_day - if (relative_hour := _dict.get('relative_hour')) is not None: - args['relative_hour'] = relative_hour - if (relative_minute := _dict.get('relative_minute')) is not None: - args['relative_minute'] = relative_minute - if (relative_second := _dict.get('relative_second')) is not None: - args['relative_second'] = relative_second - if (specific_hour := _dict.get('specific_hour')) is not None: - args['specific_hour'] = specific_hour - if (specific_minute := _dict.get('specific_minute')) is not None: - args['specific_minute'] = specific_minute - if (specific_second := _dict.get('specific_second')) is not None: - args['specific_second'] = specific_second - if (timezone := _dict.get('timezone')) is not None: - args['timezone'] = timezone + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + else: + raise ValueError( + 'Required property \'skill_id\' not present in ReleaseSkill JSON' + ) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (snapshot := _dict.get('snapshot')) is not None: + args['snapshot'] = snapshot return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityInterpretation object from a json dictionary.""" + """Initialize a ReleaseSkill 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, 'skill_id') and self.skill_id is not None: + _dict['skill_id'] = self.skill_id + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'snapshot') and self.snapshot is not None: + _dict['snapshot'] = self.snapshot + 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 ReleaseSkill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ReleaseSkill') -> 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: 'ReleaseSkill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + The type of the skill. + """ + + DIALOG = 'dialog' + ACTION = 'action' + SEARCH = 'search' + + +class RequestAnalytics: + """ + An optional object containing analytics data. Currently, this data is used only for + events sent to the Segment extension. + + :param str browser: (optional) The browser that was used to send the message + that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to send + the message that triggered the event. + """ + + def __init__( + self, + *, + browser: Optional[str] = None, + device: Optional[str] = None, + page_url: Optional[str] = None, + ) -> None: + """ + Initialize a RequestAnalytics object. + + :param str browser: (optional) The browser that was used to send the + message that triggered the event. + :param str device: (optional) The type of device that was used to send the + message that triggered the event. + :param str page_url: (optional) The URL of the web page that was used to + send the message that triggered the event. + """ + self.browser = browser + self.device = device + self.page_url = page_url + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RequestAnalytics': + """Initialize a RequestAnalytics object from a json dictionary.""" + args = {} + if (browser := _dict.get('browser')) is not None: + args['browser'] = browser + if (device := _dict.get('device')) is not None: + args['device'] = device + if (page_url := _dict.get('pageUrl')) is not None: + args['page_url'] = page_url + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RequestAnalytics 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, 'browser') and self.browser is not None: + _dict['browser'] = self.browser + if hasattr(self, 'device') and self.device is not None: + _dict['device'] = self.device + if hasattr(self, 'page_url') and self.page_url is not None: + _dict['pageUrl'] = self.page_url + 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 RequestAnalytics object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RequestAnalytics') -> 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: 'RequestAnalytics') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericChannel: + """ + ResponseGenericChannel. + + :param str channel: (optional) A channel for which the response is intended. + """ + + def __init__( + self, + *, + channel: Optional[str] = None, + ) -> None: + """ + Initialize a ResponseGenericChannel object. + + :param str channel: (optional) A channel for which the response is + intended. + """ + self.channel = channel + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericChannel': + """Initialize a ResponseGenericChannel object from a json dictionary.""" + args = {} + if (channel := _dict.get('channel')) is not None: + args['channel'] = channel + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericChannel 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, 'channel') and self.channel is not None: + _dict['channel'] = self.channel + 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 ResponseGenericChannel object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericChannel') -> 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: 'ResponseGenericChannel') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericCitation: + """ + ResponseGenericCitation. + + :param str title: The title of the citation text. + :param str text: The text of the citation. + :param str body: The body content of the citation. + :param int search_result_index: (optional) The index of the search_result where + the citation is generated. + :param List[ResponseGenericCitationRangesItem] ranges: The offsets of the start + and end of the citation in the generated response. For example, `ranges:[ { + start:0, end:5 }, ...]`. + """ + + def __init__( + self, + title: str, + text: str, + body: str, + ranges: List['ResponseGenericCitationRangesItem'], + *, + search_result_index: Optional[int] = None, + ) -> None: + """ + Initialize a ResponseGenericCitation object. + + :param str title: The title of the citation text. + :param str text: The text of the citation. + :param str body: The body content of the citation. + :param List[ResponseGenericCitationRangesItem] ranges: The offsets of the + start and end of the citation in the generated response. For example, + `ranges:[ { start:0, end:5 }, ...]`. + :param int search_result_index: (optional) The index of the search_result + where the citation is generated. + """ + self.title = title + self.text = text + self.body = body + self.search_result_index = search_result_index + self.ranges = ranges + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericCitation': + """Initialize a ResponseGenericCitation object from a json dictionary.""" + args = {} + if (title := _dict.get('title')) is not None: + args['title'] = title + else: + raise ValueError( + 'Required property \'title\' not present in ResponseGenericCitation JSON' + ) + if (text := _dict.get('text')) is not None: + args['text'] = text + else: + raise ValueError( + 'Required property \'text\' not present in ResponseGenericCitation JSON' + ) + if (body := _dict.get('body')) is not None: + args['body'] = body + else: + raise ValueError( + 'Required property \'body\' not present in ResponseGenericCitation JSON' + ) + if (search_result_index := + _dict.get('search_result_index')) is not None: + args['search_result_index'] = search_result_index + if (ranges := _dict.get('ranges')) is not None: + args['ranges'] = [ + ResponseGenericCitationRangesItem.from_dict(v) for v in ranges + ] + else: + raise ValueError( + 'Required property \'ranges\' not present in ResponseGenericCitation JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericCitation 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, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr( + self, + 'search_result_index') and self.search_result_index is not None: + _dict['search_result_index'] = self.search_result_index + if hasattr(self, 'ranges') and self.ranges is not None: + ranges_list = [] + for v in self.ranges: + if isinstance(v, dict): + ranges_list.append(v) + else: + ranges_list.append(v.to_dict()) + _dict['ranges'] = ranges_list + 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 ResponseGenericCitation object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericCitation') -> 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: 'ResponseGenericCitation') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericCitationRangesItem: + """ + ResponseGenericCitationRangesItem. + + :param int start: (optional) The offset of the start of the citation in the + generated response. + :param int end: (optional) The offset of the end of the citation in the + generated response. + """ + + def __init__( + self, + *, + start: Optional[int] = None, + end: Optional[int] = None, + ) -> None: + """ + Initialize a ResponseGenericCitationRangesItem object. + + :param int start: (optional) The offset of the start of the citation in the + generated response. + :param int end: (optional) The offset of the end of the citation in the + generated response. + """ + self.start = start + self.end = end + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericCitationRangesItem': + """Initialize a ResponseGenericCitationRangesItem object from a json dictionary.""" + args = {} + if (start := _dict.get('start')) is not None: + args['start'] = start + if (end := _dict.get('end')) is not None: + args['end'] = end + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericCitationRangesItem 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, 'start') and self.start is not None: + _dict['start'] = self.start + if hasattr(self, 'end') and self.end is not None: + _dict['end'] = self.end + 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 ResponseGenericCitationRangesItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericCitationRangesItem') -> 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: 'ResponseGenericCitationRangesItem') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class ResponseGenericConfidenceScores: + """ + The confidence scores for determining whether to show the generated response or an “I + don't know” response. + + :param float threshold: (optional) The confidence score threshold. If either the + pre_gen or post_gen score is below this threshold, it shows an “I don't know” + response to replace the generated text. You can configure the threshold in + either the user interface or through the Update skill API. For more information, + see the [watsonx Assistant documentation]( + https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-conversational-search#behavioral-tuning-conversational-search). + :param float pre_gen: (optional) The confidence score based on user query and + search results. + :param float post_gen: (optional) The confidence score based on user query, + search results, and the generated response. + :param float extractiveness: (optional) It indicates how extractive the + generated response is from the search results. + """ + + def __init__( + self, + *, + threshold: Optional[float] = None, + pre_gen: Optional[float] = None, + post_gen: Optional[float] = None, + extractiveness: Optional[float] = None, + ) -> None: + """ + Initialize a ResponseGenericConfidenceScores object. + + :param float threshold: (optional) The confidence score threshold. If + either the pre_gen or post_gen score is below this threshold, it shows an + “I don't know” response to replace the generated text. You can configure + the threshold in either the user interface or through the Update skill API. + For more information, see the [watsonx Assistant documentation]( + https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-conversational-search#behavioral-tuning-conversational-search). + :param float pre_gen: (optional) The confidence score based on user query + and search results. + :param float post_gen: (optional) The confidence score based on user query, + search results, and the generated response. + :param float extractiveness: (optional) It indicates how extractive the + generated response is from the search results. + """ + self.threshold = threshold + self.pre_gen = pre_gen + self.post_gen = post_gen + self.extractiveness = extractiveness + + @classmethod + def from_dict(cls, _dict: Dict) -> 'ResponseGenericConfidenceScores': + """Initialize a ResponseGenericConfidenceScores object from a json dictionary.""" + args = {} + if (threshold := _dict.get('threshold')) is not None: + args['threshold'] = threshold + if (pre_gen := _dict.get('pre_gen')) is not None: + args['pre_gen'] = pre_gen + if (post_gen := _dict.get('post_gen')) is not None: + args['post_gen'] = post_gen + if (extractiveness := _dict.get('extractiveness')) is not None: + args['extractiveness'] = extractiveness + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a ResponseGenericConfidenceScores 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, 'threshold') and self.threshold is not None: + _dict['threshold'] = self.threshold + if hasattr(self, 'pre_gen') and self.pre_gen is not None: + _dict['pre_gen'] = self.pre_gen + if hasattr(self, 'post_gen') and self.post_gen is not None: + _dict['post_gen'] = self.post_gen + if hasattr(self, 'extractiveness') and self.extractiveness is not None: + _dict['extractiveness'] = self.extractiveness + 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 ResponseGenericConfidenceScores object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'ResponseGenericConfidenceScores') -> 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: 'ResponseGenericConfidenceScores') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntity: + """ + The entity value that was recognized in the user input. + + :param str entity: An entity detected in the input. + :param List[int] location: (optional) An array of zero-based character offsets + that indicate where the detected entity values begin and end in the input text. + :param str value: The term in the input text that was recognized as an entity + value. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized 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. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill (if + enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__( + self, + entity: str, + value: str, + *, + location: Optional[List[int]] = None, + confidence: Optional[float] = None, + groups: Optional[List['CaptureGroup']] = None, + interpretation: Optional['RuntimeEntityInterpretation'] = None, + alternatives: Optional[List['RuntimeEntityAlternative']] = None, + role: Optional['RuntimeEntityRole'] = None, + skill: Optional[str] = None, + ) -> None: + """ + Initialize a RuntimeEntity object. + + :param str entity: An entity detected in the input. + :param str value: The term in the input text that was recognized as an + entity value. + :param List[int] location: (optional) An array of zero-based character + offsets that indicate where the detected entity values begin and end in the + input text. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized 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. + :param str skill: (optional) The skill that recognized the entity value. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.entity = entity + self.location = location + self.value = value + self.confidence = confidence + self.groups = groups + self.interpretation = interpretation + self.alternatives = alternatives + self.role = role + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': + """Initialize a RuntimeEntity object from a json dictionary.""" + args = {} + if (entity := _dict.get('entity')) is not None: + args['entity'] = entity + else: + raise ValueError( + 'Required property \'entity\' not present in RuntimeEntity JSON' + ) + if (location := _dict.get('location')) is not None: + args['location'] = location + if (value := _dict.get('value')) is not None: + args['value'] = value + else: + raise ValueError( + 'Required property \'value\' not present in RuntimeEntity JSON') + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (groups := _dict.get('groups')) is not None: + args['groups'] = [CaptureGroup.from_dict(v) for v in groups] + if (interpretation := _dict.get('interpretation')) is not None: + args['interpretation'] = RuntimeEntityInterpretation.from_dict( + interpretation) + if (alternatives := _dict.get('alternatives')) is not None: + args['alternatives'] = [ + RuntimeEntityAlternative.from_dict(v) for v in alternatives + ] + if (role := _dict.get('role')) is not None: + args['role'] = RuntimeEntityRole.from_dict(role) + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeEntity 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, 'entity') and self.entity is not None: + _dict['entity'] = self.entity + if hasattr(self, 'location') and self.location is not None: + _dict['location'] = self.location + 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 + if hasattr(self, 'groups') and self.groups is not None: + groups_list = [] + for v in self.groups: + if isinstance(v, dict): + groups_list.append(v) + else: + groups_list.append(v.to_dict()) + _dict['groups'] = groups_list + if hasattr(self, 'interpretation') and self.interpretation is not None: + if isinstance(self.interpretation, dict): + _dict['interpretation'] = self.interpretation + else: + _dict['interpretation'] = self.interpretation.to_dict() + if hasattr(self, 'alternatives') and self.alternatives is not None: + alternatives_list = [] + for v in self.alternatives: + if isinstance(v, dict): + alternatives_list.append(v) + else: + alternatives_list.append(v.to_dict()) + _dict['alternatives'] = alternatives_list + if hasattr(self, 'role') and self.role is not None: + if isinstance(self.role, dict): + _dict['role'] = self.role + else: + _dict['role'] = self.role.to_dict() + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + 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 RuntimeEntity object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeEntity') -> 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: 'RuntimeEntity') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeEntityAlternative: + """ + An alternative value for the recognized entity. + + :param str value: (optional) The entity value that was recognized in the user + input. + :param float confidence: (optional) A decimal percentage that represents + confidence in the recognized entity. + """ + + def __init__( + self, + *, + value: Optional[str] = None, + confidence: Optional[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 + 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 = {} + if (value := _dict.get('value')) is not None: + args['value'] = value + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = 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. + + :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`). + """ + + def __init__( + self, + *, + calendar_type: Optional[str] = None, + datetime_link: Optional[str] = None, + festival: Optional[str] = None, + granularity: Optional[str] = None, + range_link: Optional[str] = None, + range_modifier: Optional[str] = None, + relative_day: Optional[float] = None, + relative_month: Optional[float] = None, + relative_week: Optional[float] = None, + relative_weekend: Optional[float] = None, + relative_year: Optional[float] = None, + specific_day: Optional[float] = None, + specific_day_of_week: Optional[str] = None, + specific_month: Optional[float] = None, + specific_quarter: Optional[float] = None, + specific_year: Optional[float] = None, + numeric_value: Optional[float] = None, + subtype: Optional[str] = None, + part_of_day: Optional[str] = None, + relative_hour: Optional[float] = None, + relative_minute: Optional[float] = None, + relative_second: Optional[float] = None, + specific_hour: Optional[float] = None, + specific_minute: Optional[float] = None, + specific_second: Optional[float] = None, + timezone: Optional[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 = {} + if (calendar_type := _dict.get('calendar_type')) is not None: + args['calendar_type'] = calendar_type + if (datetime_link := _dict.get('datetime_link')) is not None: + args['datetime_link'] = datetime_link + if (festival := _dict.get('festival')) is not None: + args['festival'] = festival + if (granularity := _dict.get('granularity')) is not None: + args['granularity'] = granularity + if (range_link := _dict.get('range_link')) is not None: + args['range_link'] = range_link + if (range_modifier := _dict.get('range_modifier')) is not None: + args['range_modifier'] = range_modifier + if (relative_day := _dict.get('relative_day')) is not None: + args['relative_day'] = relative_day + if (relative_month := _dict.get('relative_month')) is not None: + args['relative_month'] = relative_month + if (relative_week := _dict.get('relative_week')) is not None: + args['relative_week'] = relative_week + if (relative_weekend := _dict.get('relative_weekend')) is not None: + args['relative_weekend'] = relative_weekend + if (relative_year := _dict.get('relative_year')) is not None: + args['relative_year'] = relative_year + if (specific_day := _dict.get('specific_day')) is not None: + args['specific_day'] = specific_day + if (specific_day_of_week := + _dict.get('specific_day_of_week')) is not None: + args['specific_day_of_week'] = specific_day_of_week + if (specific_month := _dict.get('specific_month')) is not None: + args['specific_month'] = specific_month + if (specific_quarter := _dict.get('specific_quarter')) is not None: + args['specific_quarter'] = specific_quarter + if (specific_year := _dict.get('specific_year')) is not None: + args['specific_year'] = specific_year + if (numeric_value := _dict.get('numeric_value')) is not None: + args['numeric_value'] = numeric_value + if (subtype := _dict.get('subtype')) is not None: + args['subtype'] = subtype + if (part_of_day := _dict.get('part_of_day')) is not None: + args['part_of_day'] = part_of_day + if (relative_hour := _dict.get('relative_hour')) is not None: + args['relative_hour'] = relative_hour + if (relative_minute := _dict.get('relative_minute')) is not None: + args['relative_minute'] = relative_minute + if (relative_second := _dict.get('relative_second')) is not None: + args['relative_second'] = relative_second + if (specific_hour := _dict.get('specific_hour')) is not None: + args['specific_hour'] = specific_hour + if (specific_minute := _dict.get('specific_minute')) is not None: + args['specific_minute'] = specific_minute + if (specific_second := _dict.get('specific_second')) is not None: + args['specific_second'] = specific_second + if (timezone := _dict.get('timezone')) is not None: + args['timezone'] = 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(str, 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. + + :param str type: (optional) The relationship of the entity to the range. + """ + + def __init__( + self, + *, + type: Optional[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 = {} + if (type := _dict.get('type')) is not None: + args['type'] = 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(str, 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. + + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a request, + but you do not have a calculated confidence value, specify `1`. + :param str skill: (optional) The skill that identified the intent. Currently, + the only possible values are `main skill` for the dialog skill (if enabled) and + `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and an + action skill. + """ + + def __init__( + self, + intent: str, + *, + confidence: Optional[float] = None, + skill: Optional[str] = None, + ) -> None: + """ + Initialize a RuntimeIntent object. + + :param str intent: The name of the recognized intent. + :param float confidence: (optional) A decimal percentage that represents + confidence in the intent. If you are specifying an intent as part of a + request, but you do not have a calculated confidence value, specify `1`. + :param str skill: (optional) The skill that identified the intent. + Currently, the only possible values are `main skill` for the dialog skill + (if enabled) and `actions skill` for the action skill. + This property is present only if the assistant has both a dialog skill and + an action skill. + """ + self.intent = intent + self.confidence = confidence + self.skill = skill + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': + """Initialize a RuntimeIntent object from a json dictionary.""" + args = {} + if (intent := _dict.get('intent')) is not None: + args['intent'] = intent + else: + raise ValueError( + 'Required property \'intent\' not present in RuntimeIntent JSON' + ) + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (skill := _dict.get('skill')) is not None: + args['skill'] = skill + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeIntent 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, 'intent') and self.intent is not None: + _dict['intent'] = self.intent + if hasattr(self, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'skill') and self.skill is not None: + _dict['skill'] = self.skill + 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 RuntimeIntent object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RuntimeIntent') -> 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: 'RuntimeIntent') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGeneric: + """ + RuntimeResponseGeneric. + + """ + + def __init__(self,) -> None: + """ + Initialize a RuntimeResponseGeneric object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch', + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + disc_class = cls._get_class_by_discriminator(_dict) + if disc_class != cls: + return disc_class.from_dict(_dict) + msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( + ", ".join([ + 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch', + 'RuntimeResponseGenericRuntimeResponseTypeText', + 'RuntimeResponseGenericRuntimeResponseTypePause', + 'RuntimeResponseGenericRuntimeResponseTypeImage', + 'RuntimeResponseGenericRuntimeResponseTypeOption', + 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', + 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', + 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', + 'RuntimeResponseGenericRuntimeResponseTypeSearch', + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe', + 'RuntimeResponseGenericRuntimeResponseTypeDate' + ])) + raise Exception(msg) + + @classmethod + def _from_dict(cls, _dict: Dict): + """Initialize a RuntimeResponseGeneric object from a json dictionary.""" + return cls.from_dict(_dict) + + @classmethod + def _get_class_by_discriminator(cls, _dict: Dict) -> object: + mapping = {} + mapping[ + 'conversation_search'] = 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch' + mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' + mapping[ + 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' + mapping[ + 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' + mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' + mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' + mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' + mapping[ + 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' + mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' + mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' + mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' + mapping[ + 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' + disc_value = _dict.get('response_type') + if disc_value is None: + raise ValueError( + 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' + ) + class_name = mapping.get(disc_value, disc_value) + try: + disc_class = getattr(sys.modules[__name__], class_name) + except AttributeError: + disc_class = cls + if isinstance(disc_class, object): + return disc_class + raise TypeError('%s is not a discriminator class' % class_name) + + +class SearchResult: + """ + SearchResult. + + :param str id: The unique identifier of the document in the Discovery service + collection. + This property is included in responses from search skills, which are available + only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search result + metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is taken + from an abstract, summary, or highlight field in the Discovery service response, + as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken from + a title or name field in the Discovery service response, as specified in the + search skill configuration. + :param str url: (optional) The URL of the original data object in its native + data source. + :param SearchResultHighlight highlight: (optional) An object containing segments + of text from search results with query-matching text highlighted using HTML + `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying segments + of text within the result that were identified as direct answers to the search + query. Currently, only the single answer with the highest confidence (if any) is + returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + + def __init__( + self, + id: str, + result_metadata: 'SearchResultMetadata', + *, + body: Optional[str] = None, + title: Optional[str] = None, + url: Optional[str] = None, + highlight: Optional['SearchResultHighlight'] = None, + answers: Optional[List['SearchResultAnswer']] = None, + ) -> None: + """ + Initialize a SearchResult object. + + :param str id: The unique identifier of the document in the Discovery + service collection. + This property is included in responses from search skills, which are + available only to Plus or Enterprise plan users. + :param SearchResultMetadata result_metadata: An object containing search + result metadata from the Discovery service. + :param str body: (optional) A description of the search result. This is + taken from an abstract, summary, or highlight field in the Discovery + service response, as specified in the search skill configuration. + :param str title: (optional) The title of the search result. This is taken + from a title or name field in the Discovery service response, as specified + in the search skill configuration. + :param str url: (optional) The URL of the original data object in its + native data source. + :param SearchResultHighlight highlight: (optional) An object containing + segments of text from search results with query-matching text highlighted + using HTML `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying + segments of text within the result that were identified as direct answers + to the search query. Currently, only the single answer with the highest + confidence (if any) is returned. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.id = id + self.result_metadata = result_metadata + self.body = body + self.title = title + self.url = url + self.highlight = highlight + self.answers = answers + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResult': + """Initialize a SearchResult object from a json dictionary.""" + args = {} + if (id := _dict.get('id')) is not None: + args['id'] = id + else: + raise ValueError( + 'Required property \'id\' not present in SearchResult JSON') + if (result_metadata := _dict.get('result_metadata')) is not None: + args['result_metadata'] = SearchResultMetadata.from_dict( + result_metadata) + else: + raise ValueError( + 'Required property \'result_metadata\' not present in SearchResult JSON' + ) + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = SearchResultHighlight.from_dict(highlight) + if (answers := _dict.get('answers')) is not None: + args['answers'] = [SearchResultAnswer.from_dict(v) for v in answers] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResult 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, 'id') and self.id is not None: + _dict['id'] = self.id + if hasattr(self, + 'result_metadata') and self.result_metadata is not None: + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'highlight') and self.highlight is not None: + if isinstance(self.highlight, dict): + _dict['highlight'] = self.highlight + else: + _dict['highlight'] = self.highlight.to_dict() + if hasattr(self, 'answers') and self.answers is not None: + answers_list = [] + for v in self.answers: + if isinstance(v, dict): + answers_list.append(v) + else: + answers_list.append(v.to_dict()) + _dict['answers'] = answers_list + 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 SearchResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResult') -> 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: 'SearchResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultAnswer: + """ + An object specifing a segment of text that was identified as a direct answer to the + search query. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned by the + Discovery service. + """ + + def __init__( + self, + text: str, + confidence: float, + ) -> None: + """ + Initialize a SearchResultAnswer object. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned + by the Discovery service. + """ + self.text = text + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': + """Initialize a SearchResultAnswer object from a json dictionary.""" + args = {} + if (text := _dict.get('text')) is not None: + args['text'] = text + else: + raise ValueError( + 'Required property \'text\' not present in SearchResultAnswer JSON' + ) + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + else: + raise ValueError( + 'Required property \'confidence\' not present in SearchResultAnswer JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultAnswer 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, 'text') and self.text is not None: + _dict['text'] = self.text + 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 SearchResultAnswer object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultAnswer') -> 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: 'SearchResultAnswer') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultHighlight: + """ + An object containing segments of text from search results with query-matching text + highlighted using HTML `` tags. + + :param List[str] body: (optional) An array of strings containing segments taken + from body text in the search results, with query-matching substrings + highlighted. + :param List[str] title: (optional) An array of strings containing segments taken + from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments taken + from URLs in the search results, with query-matching substrings highlighted. + + This type supports additional properties of type List[str]. An array of strings + containing segments taken from a field in the search results that is not mapped to the + `body`, `title`, or `url` property, with query-matching substrings highlighted. The + property name is the name of the field in the Discovery collection. + """ + + # The set of defined properties for the class + _properties = frozenset(['body', 'title', 'url']) + + def __init__( + self, + *, + body: Optional[List[str]] = None, + title: Optional[List[str]] = None, + url: Optional[List[str]] = None, + **kwargs: Optional[List[str]], + ) -> None: + """ + Initialize a SearchResultHighlight object. + + :param List[str] body: (optional) An array of strings containing segments + taken from body text in the search results, with query-matching substrings + highlighted. + :param List[str] title: (optional) An array of strings containing segments + taken from title text in the search results, with query-matching substrings + highlighted. + :param List[str] url: (optional) An array of strings containing segments + taken from URLs in the search results, with query-matching substrings + highlighted. + :param List[str] **kwargs: (optional) An array of strings containing + segments taken from a field in the search results that is not mapped to the + `body`, `title`, or `url` property, with query-matching substrings + highlighted. The property name is the name of the field in the Discovery + collection. + """ + self.body = body + self.title = title + self.url = url + for k, v in kwargs.items(): + if k not in SearchResultHighlight._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[Foo]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + setattr(self, k, _v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': + """Initialize a SearchResultHighlight object from a json dictionary.""" + args = {} + if (body := _dict.get('body')) is not None: + args['body'] = body + if (title := _dict.get('title')) is not None: + args['title'] = title + if (url := _dict.get('url')) is not None: + args['url'] = url + for k, v in _dict.items(): + if k not in cls._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + args[k] = _v + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultHighlight 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, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def _to_dict(self): + """Return a json dictionary representing this model.""" + return self.to_dict() + + def get_properties(self) -> Dict: + """Return the additional properties from this instance of SearchResultHighlight in the form of a dict.""" + _dict = {} + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + _dict[k] = getattr(self, k) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of additional properties in this instance of SearchResultHighlight""" + for k in [ + _k for _k in vars(self).keys() + if _k not in SearchResultHighlight._properties + ]: + delattr(self, k) + for k, v in _dict.items(): + if k not in SearchResultHighlight._properties: + if not isinstance(v, List): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v = [] + for elem in v: + if not isinstance(elem, str): + raise ValueError( + 'Value for additional property {} must be of type List[str]' + .format(k)) + _v.append(elem) + setattr(self, k, _v) + else: + raise ValueError( + 'Property {} cannot be specified as an additional property'. + format(k)) + + def __str__(self) -> str: + """Return a `str` version of this SearchResultHighlight object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultHighlight') -> 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: 'SearchResultHighlight') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultMetadata: + """ + An object containing search result metadata from the Discovery service. + + :param float confidence: (optional) The confidence score for the given result, + as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher score + indicates a greater match to the query parameters. + """ + + def __init__( + self, + *, + confidence: Optional[float] = None, + score: Optional[float] = None, + ) -> None: + """ + Initialize a SearchResultMetadata object. + + :param float confidence: (optional) The confidence score for the given + result, as returned by the Discovery service. + :param float score: (optional) An unbounded measure of the relevance of a + particular result, dependent on the query and matching document. A higher + score indicates a greater match to the query parameters. + """ + self.confidence = confidence + self.score = score + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': + """Initialize a SearchResultMetadata object from a json dictionary.""" + args = {} + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (score := _dict.get('score')) is not None: + args['score'] = score + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultMetadata 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, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score + 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 SearchResultMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultMetadata') -> 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: 'SearchResultMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResults: + """ + SearchResults. + + :param SearchResultsResultMetadata result_metadata: The metadata of the search + result. + :param str id: The ID of the search result. It may not be unique. + :param str title: The title of the search result. + :param str body: The body content of the search result. + """ + + def __init__( + self, + result_metadata: 'SearchResultsResultMetadata', + id: str, + title: str, + body: str, + ) -> None: + """ + Initialize a SearchResults object. + + :param SearchResultsResultMetadata result_metadata: The metadata of the + search result. + :param str id: The ID of the search result. It may not be unique. + :param str title: The title of the search result. + :param str body: The body content of the search result. + """ + self.result_metadata = result_metadata + self.id = id + self.title = title + self.body = body + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResults': + """Initialize a SearchResults object from a json dictionary.""" + args = {} + if (result_metadata := _dict.get('result_metadata')) is not None: + args['result_metadata'] = SearchResultsResultMetadata.from_dict( + result_metadata) + else: + raise ValueError( + 'Required property \'result_metadata\' not present in SearchResults JSON' + ) + if (id := _dict.get('id')) is not None: + args['id'] = id + else: + raise ValueError( + 'Required property \'id\' not present in SearchResults JSON') + if (title := _dict.get('title')) is not None: + args['title'] = title + else: + raise ValueError( + 'Required property \'title\' not present in SearchResults JSON') + if (body := _dict.get('body')) is not None: + args['body'] = body + else: + raise ValueError( + 'Required property \'body\' not present in SearchResults JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResults 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, + 'result_metadata') and self.result_metadata is not None: + if isinstance(self.result_metadata, dict): + _dict['result_metadata'] = self.result_metadata + else: + _dict['result_metadata'] = self.result_metadata.to_dict() + if hasattr(self, 'id') and self.id is not None: + _dict['id'] = self.id + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + 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 SearchResults object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResults') -> 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: 'SearchResults') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchResultsResultMetadata: + """ + The metadata of the search result. + + :param str document_retrieval_source: (optional) The source of the search + result. + :param int score: (optional) The relevance score of the search result to the + user query. + """ + + def __init__( + self, + *, + document_retrieval_source: Optional[str] = None, + score: Optional[int] = None, + ) -> None: + """ + Initialize a SearchResultsResultMetadata object. + + :param str document_retrieval_source: (optional) The source of the search + result. + :param int score: (optional) The relevance score of the search result to + the user query. + """ + self.document_retrieval_source = document_retrieval_source + self.score = score + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultsResultMetadata': + """Initialize a SearchResultsResultMetadata object from a json dictionary.""" + args = {} + if (document_retrieval_source := + _dict.get('document_retrieval_source')) is not None: + args['document_retrieval_source'] = document_retrieval_source + if (score := _dict.get('score')) is not None: + args['score'] = score + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultsResultMetadata 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, 'document_retrieval_source' + ) and self.document_retrieval_source is not None: + _dict['document_retrieval_source'] = self.document_retrieval_source + if hasattr(self, 'score') and self.score is not None: + _dict['score'] = self.score + 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 SearchResultsResultMetadata object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultsResultMetadata') -> 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: 'SearchResultsResultMetadata') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettings: + """ + An object describing the search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and are not + included in **Export skills** responses. + + :param SearchSettingsDiscovery discovery: (optional) Configuration settings for + the Watson Discovery service instance used by the search integration. + :param SearchSettingsMessages messages: The messages included with responses + from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between fields in + the Watson Discovery collection and properties in the search response. + :param SearchSettingsElasticSearch elastic_search: (optional) Configuration + settings for the Elasticsearch service used by the search integration. You can + provide either basic auth or apiKey auth. + :param SearchSettingsConversationalSearch conversational_search: Configuration + settings for conversational search. + :param SearchSettingsServerSideSearch server_side_search: (optional) + Configuration settings for the server-side search service used by the search + integration. You can provide either basic auth, apiKey auth or none. + :param SearchSettingsClientSideSearch client_side_search: (optional) + Configuration settings for the client-side search service or server-side search + service used by the search integration. + """ + + def __init__( + self, + messages: 'SearchSettingsMessages', + schema_mapping: 'SearchSettingsSchemaMapping', + conversational_search: 'SearchSettingsConversationalSearch', + *, + discovery: Optional['SearchSettingsDiscovery'] = None, + elastic_search: Optional['SearchSettingsElasticSearch'] = None, + server_side_search: Optional['SearchSettingsServerSideSearch'] = None, + client_side_search: Optional['SearchSettingsClientSideSearch'] = None, + ) -> None: + """ + Initialize a SearchSettings object. + + :param SearchSettingsMessages messages: The messages included with + responses from the search integration. + :param SearchSettingsSchemaMapping schema_mapping: The mapping between + fields in the Watson Discovery collection and properties in the search + response. + :param SearchSettingsConversationalSearch conversational_search: + Configuration settings for conversational search. + :param SearchSettingsDiscovery discovery: (optional) Configuration settings + for the Watson Discovery service instance used by the search integration. + :param SearchSettingsElasticSearch elastic_search: (optional) Configuration + settings for the Elasticsearch service used by the search integration. You + can provide either basic auth or apiKey auth. + :param SearchSettingsServerSideSearch server_side_search: (optional) + Configuration settings for the server-side search service used by the + search integration. You can provide either basic auth, apiKey auth or none. + :param SearchSettingsClientSideSearch client_side_search: (optional) + Configuration settings for the client-side search service or server-side + search service used by the search integration. + """ + self.discovery = discovery + self.messages = messages + self.schema_mapping = schema_mapping + self.elastic_search = elastic_search + self.conversational_search = conversational_search + self.server_side_search = server_side_search + self.client_side_search = client_side_search + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettings': + """Initialize a SearchSettings object from a json dictionary.""" + args = {} + if (discovery := _dict.get('discovery')) is not None: + args['discovery'] = SearchSettingsDiscovery.from_dict(discovery) + if (messages := _dict.get('messages')) is not None: + args['messages'] = SearchSettingsMessages.from_dict(messages) + else: + raise ValueError( + 'Required property \'messages\' not present in SearchSettings JSON' + ) + if (schema_mapping := _dict.get('schema_mapping')) is not None: + args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( + schema_mapping) + else: + raise ValueError( + 'Required property \'schema_mapping\' not present in SearchSettings JSON' + ) + if (elastic_search := _dict.get('elastic_search')) is not None: + args['elastic_search'] = SearchSettingsElasticSearch.from_dict( + elastic_search) + if (conversational_search := + _dict.get('conversational_search')) is not None: + args[ + 'conversational_search'] = SearchSettingsConversationalSearch.from_dict( + conversational_search) + else: + raise ValueError( + 'Required property \'conversational_search\' not present in SearchSettings JSON' + ) + if (server_side_search := _dict.get('server_side_search')) is not None: + args[ + 'server_side_search'] = SearchSettingsServerSideSearch.from_dict( + server_side_search) + if (client_side_search := _dict.get('client_side_search')) is not None: + args[ + 'client_side_search'] = SearchSettingsClientSideSearch.from_dict( + client_side_search) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettings 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, 'discovery') and self.discovery is not None: + if isinstance(self.discovery, dict): + _dict['discovery'] = self.discovery + else: + _dict['discovery'] = self.discovery.to_dict() + if hasattr(self, 'messages') and self.messages is not None: + if isinstance(self.messages, dict): + _dict['messages'] = self.messages + else: + _dict['messages'] = self.messages.to_dict() + if hasattr(self, 'schema_mapping') and self.schema_mapping is not None: + if isinstance(self.schema_mapping, dict): + _dict['schema_mapping'] = self.schema_mapping + else: + _dict['schema_mapping'] = self.schema_mapping.to_dict() + if hasattr(self, 'elastic_search') and self.elastic_search is not None: + if isinstance(self.elastic_search, dict): + _dict['elastic_search'] = self.elastic_search + else: + _dict['elastic_search'] = self.elastic_search.to_dict() + if hasattr(self, 'conversational_search' + ) and self.conversational_search is not None: + if isinstance(self.conversational_search, dict): + _dict['conversational_search'] = self.conversational_search + else: + _dict[ + 'conversational_search'] = self.conversational_search.to_dict( + ) + if hasattr( + self, + 'server_side_search') and self.server_side_search is not None: + if isinstance(self.server_side_search, dict): + _dict['server_side_search'] = self.server_side_search + else: + _dict['server_side_search'] = self.server_side_search.to_dict() + if hasattr( + self, + 'client_side_search') and self.client_side_search is not None: + if isinstance(self.client_side_search, dict): + _dict['client_side_search'] = self.client_side_search + else: + _dict['client_side_search'] = self.client_side_search.to_dict() + 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 SearchSettings object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettings') -> 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: 'SearchSettings') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsClientSideSearch: + """ + Configuration settings for the client-side search service or server-side search + service used by the search integration. + + :param str filter: (optional) The filter string that is applied to the search + results. + :param dict metadata: (optional) The metadata object. + """ + + def __init__( + self, + *, + filter: Optional[str] = None, + metadata: Optional[dict] = None, + ) -> None: + """ + Initialize a SearchSettingsClientSideSearch object. + + :param str filter: (optional) The filter string that is applied to the + search results. + :param dict metadata: (optional) The metadata object. + """ + self.filter = filter + self.metadata = metadata + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsClientSideSearch': + """Initialize a SearchSettingsClientSideSearch object from a json dictionary.""" + args = {} + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsClientSideSearch 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, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + 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 SearchSettingsClientSideSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsClientSideSearch') -> 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: 'SearchSettingsClientSideSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsConversationalSearch: + """ + Configuration settings for conversational search. + + :param bool enabled: Whether to enable conversational search. + :param SearchSettingsConversationalSearchResponseLength response_length: + (optional) + :param SearchSettingsConversationalSearchSearchConfidence search_confidence: + (optional) + """ + + def __init__( + self, + enabled: bool, + *, + response_length: Optional[ + 'SearchSettingsConversationalSearchResponseLength'] = None, + search_confidence: Optional[ + 'SearchSettingsConversationalSearchSearchConfidence'] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearch object. + + :param bool enabled: Whether to enable conversational search. + :param SearchSettingsConversationalSearchResponseLength response_length: + (optional) + :param SearchSettingsConversationalSearchSearchConfidence + search_confidence: (optional) + """ + self.enabled = enabled + self.response_length = response_length + self.search_confidence = search_confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsConversationalSearch': + """Initialize a SearchSettingsConversationalSearch object from a json dictionary.""" + args = {} + if (enabled := _dict.get('enabled')) is not None: + args['enabled'] = enabled + else: + raise ValueError( + 'Required property \'enabled\' not present in SearchSettingsConversationalSearch JSON' + ) + if (response_length := _dict.get('response_length')) is not None: + args[ + 'response_length'] = SearchSettingsConversationalSearchResponseLength.from_dict( + response_length) + if (search_confidence := _dict.get('search_confidence')) is not None: + args[ + 'search_confidence'] = SearchSettingsConversationalSearchSearchConfidence.from_dict( + search_confidence) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearch 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 + if hasattr(self, + 'response_length') and self.response_length is not None: + if isinstance(self.response_length, dict): + _dict['response_length'] = self.response_length + else: + _dict['response_length'] = self.response_length.to_dict() + if hasattr(self, + 'search_confidence') and self.search_confidence is not None: + if isinstance(self.search_confidence, dict): + _dict['search_confidence'] = self.search_confidence + else: + _dict['search_confidence'] = self.search_confidence.to_dict() + 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 SearchSettingsConversationalSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsConversationalSearch') -> 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: 'SearchSettingsConversationalSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsConversationalSearchResponseLength: + """ + SearchSettingsConversationalSearchResponseLength. + + :param str option: (optional) The response length option. It controls the length + of the generated response. + """ + + def __init__( + self, + *, + option: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearchResponseLength object. + + :param str option: (optional) The response length option. It controls the + length of the generated response. + """ + self.option = option + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'SearchSettingsConversationalSearchResponseLength': + """Initialize a SearchSettingsConversationalSearchResponseLength object from a json dictionary.""" + args = {} + if (option := _dict.get('option')) is not None: + args['option'] = option + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearchResponseLength 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, 'option') and self.option is not None: + _dict['option'] = self.option + 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 SearchSettingsConversationalSearchResponseLength object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'SearchSettingsConversationalSearchResponseLength') -> 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: 'SearchSettingsConversationalSearchResponseLength') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class OptionEnum(str, Enum): + """ + The response length option. It controls the length of the generated response. + """ + + CONCISE = 'concise' + MODERATE = 'moderate' + VERBOSE = 'verbose' + + +class SearchSettingsConversationalSearchSearchConfidence: + """ + SearchSettingsConversationalSearchSearchConfidence. + + :param str threshold: (optional) The search confidence threshold. + It controls the tendency for conversational search to produce “I don't know” + answers. + """ + + def __init__( + self, + *, + threshold: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsConversationalSearchSearchConfidence object. + + :param str threshold: (optional) The search confidence threshold. + It controls the tendency for conversational search to produce “I don't + know” answers. + """ + self.threshold = threshold + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'SearchSettingsConversationalSearchSearchConfidence': + """Initialize a SearchSettingsConversationalSearchSearchConfidence object from a json dictionary.""" + args = {} + if (threshold := _dict.get('threshold')) is not None: + args['threshold'] = threshold + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsConversationalSearchSearchConfidence 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, 'threshold') and self.threshold is not None: + _dict['threshold'] = self.threshold + 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 SearchSettingsConversationalSearchSearchConfidence object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'SearchSettingsConversationalSearchSearchConfidence' + ) -> 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: 'SearchSettingsConversationalSearchSearchConfidence' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class ThresholdEnum(str, Enum): + """ + The search confidence threshold. + It controls the tendency for conversational search to produce “I don't know” + answers. + """ + + RARELY = 'rarely' + LESS_OFTEN = 'less_often' + MORE_OFTEN = 'more_often' + MOST_OFTEN = 'most_often' + + +class SearchSettingsDiscovery: + """ + Configuration settings for the Watson Discovery service instance used by the search + integration. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param int max_primary_results: (optional) The maximum number of primary results + to include in the response. + :param int max_total_results: (optional) The maximum total number of primary and + additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence threshold + for included results. Any results with a confidence below this threshold will be + discarded. + :param bool highlight: (optional) Whether to include the most relevant passages + of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding feature + to emphasize answers within highlighted passages. This property is ignored if + **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + """ + + def __init__( + self, + instance_id: str, + project_id: str, + url: str, + authentication: 'SearchSettingsDiscoveryAuthentication', + *, + max_primary_results: Optional[int] = None, + max_total_results: Optional[int] = None, + confidence_threshold: Optional[float] = None, + highlight: Optional[bool] = None, + find_answers: Optional[bool] = None, + ) -> None: + """ + Initialize a SearchSettingsDiscovery object. + + :param str instance_id: The ID for the Watson Discovery service instance. + :param str project_id: The ID for the Watson Discovery project. + :param str url: The URL for the Watson Discovery service instance. + :param SearchSettingsDiscoveryAuthentication authentication: Authentication + information for the Watson Discovery service. For more information, see the + [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + :param int max_primary_results: (optional) The maximum number of primary + results to include in the response. + :param int max_total_results: (optional) The maximum total number of + primary and additional results to include in the response. + :param float confidence_threshold: (optional) The minimum confidence + threshold for included results. Any results with a confidence below this + threshold will be discarded. + :param bool highlight: (optional) Whether to include the most relevant + passages of text in the **highlight** property of each result. + :param bool find_answers: (optional) Whether to use the answer finding + feature to emphasize answers within highlighted passages. This property is + ignored if **highlight**=`false`. + **Notes:** + - Answer finding is available only if the search skill is connected to a + Discovery v2 service instance. + - Answer finding is not supported on IBM Cloud Pak for Data. + """ + self.instance_id = instance_id + self.project_id = project_id + self.url = url + self.max_primary_results = max_primary_results + self.max_total_results = max_total_results + self.confidence_threshold = confidence_threshold + self.highlight = highlight + self.find_answers = find_answers + self.authentication = authentication + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': + """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + args = {} + if (instance_id := _dict.get('instance_id')) is not None: + args['instance_id'] = instance_id + else: + raise ValueError( + 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' + ) + if (project_id := _dict.get('project_id')) is not None: + args['project_id'] = project_id + else: + raise ValueError( + 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' + ) + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsDiscovery JSON' + ) + if (max_primary_results := + _dict.get('max_primary_results')) is not None: + args['max_primary_results'] = max_primary_results + if (max_total_results := _dict.get('max_total_results')) is not None: + args['max_total_results'] = max_total_results + if (confidence_threshold := + _dict.get('confidence_threshold')) is not None: + args['confidence_threshold'] = confidence_threshold + if (highlight := _dict.get('highlight')) is not None: + args['highlight'] = highlight + if (find_answers := _dict.get('find_answers')) is not None: + args['find_answers'] = find_answers + if (authentication := _dict.get('authentication')) is not None: + args[ + 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( + authentication) + else: + raise ValueError( + 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscovery 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, 'instance_id') and self.instance_id is not None: + _dict['instance_id'] = self.instance_id + if hasattr(self, 'project_id') and self.project_id is not None: + _dict['project_id'] = self.project_id + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr( + self, + 'max_primary_results') and self.max_primary_results is not None: + _dict['max_primary_results'] = self.max_primary_results + if hasattr(self, + 'max_total_results') and self.max_total_results is not None: + _dict['max_total_results'] = self.max_total_results + if hasattr(self, 'confidence_threshold' + ) and self.confidence_threshold is not None: + _dict['confidence_threshold'] = self.confidence_threshold + if hasattr(self, 'highlight') and self.highlight is not None: + _dict['highlight'] = self.highlight + if hasattr(self, 'find_answers') and self.find_answers is not None: + _dict['find_answers'] = self.find_answers + if hasattr(self, 'authentication') and self.authentication is not None: + if isinstance(self.authentication, dict): + _dict['authentication'] = self.authentication + else: + _dict['authentication'] = self.authentication.to_dict() + 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 SearchSettingsDiscovery object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscovery') -> 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: 'SearchSettingsDiscovery') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsDiscoveryAuthentication: + """ + Authentication information for the Watson Discovery service. For more information, see + the [Watson Discovery + documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). + **Note:** You must specify either **basic** or **bearer**, but not both. + + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + + def __init__( + self, + *, + basic: Optional[str] = None, + bearer: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsDiscoveryAuthentication object. + + :param str basic: (optional) The HTTP basic authentication credentials for + Watson Discovery. Specify your Watson Discovery API key in the format + `apikey:{apikey}`. + :param str bearer: (optional) The authentication bearer token for Watson + Discovery. + """ + self.basic = basic + self.bearer = bearer + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': + """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + args = {} + if (basic := _dict.get('basic')) is not None: + args['basic'] = basic + if (bearer := _dict.get('bearer')) is not None: + args['bearer'] = bearer + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsDiscoveryAuthentication 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, 'basic') and self.basic is not None: + _dict['basic'] = self.basic + if hasattr(self, 'bearer') and self.bearer is not None: + _dict['bearer'] = self.bearer + 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 SearchSettingsDiscoveryAuthentication object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsDiscoveryAuthentication') -> 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: 'SearchSettingsDiscoveryAuthentication') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsElasticSearch: + """ + Configuration settings for the Elasticsearch service used by the search integration. + You can provide either basic auth or apiKey auth. + + :param str url: The URL for the Elasticsearch service. + :param str port: The port number for the Elasticsearch service URL. + **Note:** It can be omitted if a port number is appended to the URL. + :param str username: (optional) The username of the basic authentication method. + :param str password: (optional) The password of the basic authentication method. + The credentials are not returned due to security reasons. + :param str index: The Elasticsearch index to use for the search integration. + :param List[object] filter: (optional) An array of filters that can be applied + to the search results via the `$FILTER` variable in the `query_body`.For more + information, see [Elasticsearch filter + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/filter-search-results.html). + :param dict query_body: (optional) The Elasticsearch query object. For more + information, see [Elasticsearch search API + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html). + :param str managed_index: (optional) The Elasticsearch index for uploading + documents. It is created automatically when the upload document option is + selected from the user interface. + :param str apikey: (optional) The API key of the apiKey authentication method. + Use either basic auth or apiKey auth. The credentials are not returned due to + security reasons. + """ + + def __init__( + self, + url: str, + port: str, + index: str, + *, + username: Optional[str] = None, + password: Optional[str] = None, + filter: Optional[List[object]] = None, + query_body: Optional[dict] = None, + managed_index: Optional[str] = None, + apikey: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsElasticSearch object. + + :param str url: The URL for the Elasticsearch service. + :param str port: The port number for the Elasticsearch service URL. + **Note:** It can be omitted if a port number is appended to the URL. + :param str index: The Elasticsearch index to use for the search + integration. + :param str username: (optional) The username of the basic authentication + method. + :param str password: (optional) The password of the basic authentication + method. The credentials are not returned due to security reasons. + :param List[object] filter: (optional) An array of filters that can be + applied to the search results via the `$FILTER` variable in the + `query_body`.For more information, see [Elasticsearch filter + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/filter-search-results.html). + :param dict query_body: (optional) The Elasticsearch query object. For more + information, see [Elasticsearch search API + documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html). + :param str managed_index: (optional) The Elasticsearch index for uploading + documents. It is created automatically when the upload document option is + selected from the user interface. + :param str apikey: (optional) The API key of the apiKey authentication + method. Use either basic auth or apiKey auth. The credentials are not + returned due to security reasons. + """ + self.url = url + self.port = port + self.username = username + self.password = password + self.index = index + self.filter = filter + self.query_body = query_body + self.managed_index = managed_index + self.apikey = apikey + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsElasticSearch': + """Initialize a SearchSettingsElasticSearch object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsElasticSearch JSON' + ) + if (port := _dict.get('port')) is not None: + args['port'] = port + else: + raise ValueError( + 'Required property \'port\' not present in SearchSettingsElasticSearch JSON' + ) + if (username := _dict.get('username')) is not None: + args['username'] = username + if (password := _dict.get('password')) is not None: + args['password'] = password + if (index := _dict.get('index')) is not None: + args['index'] = index + else: + raise ValueError( + 'Required property \'index\' not present in SearchSettingsElasticSearch JSON' + ) + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (query_body := _dict.get('query_body')) is not None: + args['query_body'] = query_body + if (managed_index := _dict.get('managed_index')) is not None: + args['managed_index'] = managed_index + if (apikey := _dict.get('apikey')) is not None: + args['apikey'] = apikey + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsElasticSearch 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, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'port') and self.port is not None: + _dict['port'] = self.port + if hasattr(self, 'username') and self.username is not None: + _dict['username'] = self.username + if hasattr(self, 'password') and self.password is not None: + _dict['password'] = self.password + if hasattr(self, 'index') and self.index is not None: + _dict['index'] = self.index + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'query_body') and self.query_body is not None: + _dict['query_body'] = self.query_body + if hasattr(self, 'managed_index') and self.managed_index is not None: + _dict['managed_index'] = self.managed_index + if hasattr(self, 'apikey') and self.apikey is not None: + _dict['apikey'] = self.apikey + 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 SearchSettingsElasticSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsElasticSearch') -> 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: 'SearchSettingsElasticSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsMessages: + """ + The messages included with responses from the search integration. + + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is no + result from the query. + """ + + def __init__( + self, + success: str, + error: str, + no_result: str, + ) -> None: + """ + Initialize a SearchSettingsMessages object. + + :param str success: The message to include in the response to a successful + query. + :param str error: The message to include in the response when the query + encounters an error. + :param str no_result: The message to include in the response when there is + no result from the query. + """ + self.success = success + self.error = error + self.no_result = no_result + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': + """Initialize a SearchSettingsMessages object from a json dictionary.""" + args = {} + if (success := _dict.get('success')) is not None: + args['success'] = success + else: + raise ValueError( + 'Required property \'success\' not present in SearchSettingsMessages JSON' + ) + if (error := _dict.get('error')) is not None: + args['error'] = error + else: + raise ValueError( + 'Required property \'error\' not present in SearchSettingsMessages JSON' + ) + if (no_result := _dict.get('no_result')) is not None: + args['no_result'] = no_result + else: + raise ValueError( + 'Required property \'no_result\' not present in SearchSettingsMessages JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsMessages 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, 'success') and self.success is not None: + _dict['success'] = self.success + if hasattr(self, 'error') and self.error is not None: + _dict['error'] = self.error + if hasattr(self, 'no_result') and self.no_result is not None: + _dict['no_result'] = self.no_result + 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 SearchSettingsMessages object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsMessages') -> 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: 'SearchSettingsMessages') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsSchemaMapping: + """ + The mapping between fields in the Watson Discovery collection and properties in the + search response. + + :param str url: The field in the collection to map to the **url** property of + the response. + :param str body: The field in the collection to map to the **body** property in + the response. + :param str title: The field in the collection to map to the **title** property + for the schema. + """ + + def __init__( + self, + url: str, + body: str, + title: str, + ) -> None: + """ + Initialize a SearchSettingsSchemaMapping object. + + :param str url: The field in the collection to map to the **url** property + of the response. + :param str body: The field in the collection to map to the **body** + property in the response. + :param str title: The field in the collection to map to the **title** + property for the schema. + """ + self.url = url + self.body = body + self.title = title + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': + """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' + ) + if (body := _dict.get('body')) is not None: + args['body'] = body + else: + raise ValueError( + 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' + ) + if (title := _dict.get('title')) is not None: + args['title'] = title + else: + raise ValueError( + 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsSchemaMapping 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, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + 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 SearchSettingsSchemaMapping object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsSchemaMapping') -> 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: 'SearchSettingsSchemaMapping') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SearchSettingsServerSideSearch: + """ + Configuration settings for the server-side search service used by the search + integration. You can provide either basic auth, apiKey auth or none. + + :param str url: The URL of the server-side search service. + :param str port: (optional) The port number of the server-side search service. + :param str username: (optional) The username of the basic authentication method. + :param str password: (optional) The password of the basic authentication method. + The credentials are not returned due to security reasons. + :param str filter: (optional) The filter string that is applied to the search + results. + :param dict metadata: (optional) The metadata object. + :param str apikey: (optional) The API key of the apiKey authentication method. + The credentails are not returned due to security reasons. + :param bool no_auth: (optional) To clear previous auth, specify `no_auth = + true`. + :param str auth_type: (optional) The authorization type that is used. + """ + + def __init__( + self, + url: str, + *, + port: Optional[str] = None, + username: Optional[str] = None, + password: Optional[str] = None, + filter: Optional[str] = None, + metadata: Optional[dict] = None, + apikey: Optional[str] = None, + no_auth: Optional[bool] = None, + auth_type: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSettingsServerSideSearch object. + + :param str url: The URL of the server-side search service. + :param str port: (optional) The port number of the server-side search + service. + :param str username: (optional) The username of the basic authentication + method. + :param str password: (optional) The password of the basic authentication + method. The credentials are not returned due to security reasons. + :param str filter: (optional) The filter string that is applied to the + search results. + :param dict metadata: (optional) The metadata object. + :param str apikey: (optional) The API key of the apiKey authentication + method. The credentails are not returned due to security reasons. + :param bool no_auth: (optional) To clear previous auth, specify `no_auth = + true`. + :param str auth_type: (optional) The authorization type that is used. + """ + self.url = url + self.port = port + self.username = username + self.password = password + self.filter = filter + self.metadata = metadata + self.apikey = apikey + self.no_auth = no_auth + self.auth_type = auth_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSettingsServerSideSearch': + """Initialize a SearchSettingsServerSideSearch object from a json dictionary.""" + args = {} + if (url := _dict.get('url')) is not None: + args['url'] = url + else: + raise ValueError( + 'Required property \'url\' not present in SearchSettingsServerSideSearch JSON' + ) + if (port := _dict.get('port')) is not None: + args['port'] = port + if (username := _dict.get('username')) is not None: + args['username'] = username + if (password := _dict.get('password')) is not None: + args['password'] = password + if (filter := _dict.get('filter')) is not None: + args['filter'] = filter + if (metadata := _dict.get('metadata')) is not None: + args['metadata'] = metadata + if (apikey := _dict.get('apikey')) is not None: + args['apikey'] = apikey + if (no_auth := _dict.get('no_auth')) is not None: + args['no_auth'] = no_auth + if (auth_type := _dict.get('auth_type')) is not None: + args['auth_type'] = auth_type + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSettingsServerSideSearch 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, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'port') and self.port is not None: + _dict['port'] = self.port + if hasattr(self, 'username') and self.username is not None: + _dict['username'] = self.username + if hasattr(self, 'password') and self.password is not None: + _dict['password'] = self.password + if hasattr(self, 'filter') and self.filter is not None: + _dict['filter'] = self.filter + if hasattr(self, 'metadata') and self.metadata is not None: + _dict['metadata'] = self.metadata + if hasattr(self, 'apikey') and self.apikey is not None: + _dict['apikey'] = self.apikey + if hasattr(self, 'no_auth') and self.no_auth is not None: + _dict['no_auth'] = self.no_auth + if hasattr(self, 'auth_type') and self.auth_type is not None: + _dict['auth_type'] = self.auth_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 SearchSettingsServerSideSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSettingsServerSideSearch') -> 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: 'SearchSettingsServerSideSearch') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class AuthTypeEnum(str, Enum): + """ + The authorization type that is used. + """ + + BASIC = 'basic' + APIKEY = 'apikey' + NONE = 'none' + + +class SearchSkillWarning: + """ + A warning describing an error in the search skill configuration. + + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. + """ + + def __init__( + self, + *, + code: Optional[str] = None, + path: Optional[str] = None, + message: Optional[str] = None, + ) -> None: + """ + Initialize a SearchSkillWarning object. + + :param str code: (optional) The error code. + :param str path: (optional) The location of the error in the search skill + configuration object. + :param str message: (optional) The error message. + """ + self.code = code + self.path = path + self.message = message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': + """Initialize a SearchSkillWarning object from a json dictionary.""" + args = {} + if (code := _dict.get('code')) is not None: + args['code'] = code + if (path := _dict.get('path')) is not None: + args['path'] = path + if (message := _dict.get('message')) is not None: + args['message'] = message + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchSkillWarning 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, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + 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 SearchSkillWarning object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchSkillWarning') -> 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: 'SearchSkillWarning') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class SessionResponse: + """ + SessionResponse. + + :param str session_id: The session ID. + """ + + def __init__( + self, + session_id: str, + ) -> None: + """ + Initialize a SessionResponse object. + + :param str session_id: The session ID. + """ + self.session_id = session_id + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SessionResponse': + """Initialize a SessionResponse object from a json dictionary.""" + args = {} + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id + else: + raise ValueError( + 'Required property \'session_id\' not present in SessionResponse JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SessionResponse 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, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id + 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 SessionResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SessionResponse') -> 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: 'SessionResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Skill: + """ + Skill. + + :param str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :param str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :param str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :param str language: The language of the skill. + :param str type: The type of skill. + """ + + def __init__( + self, + language: str, + type: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, + ) -> None: + """ + Initialize a Skill object. + + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. + """ + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'Skill': + """Initialize a Skill object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in warnings + ] + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in Skill JSON') + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in Skill JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Skill 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') + if hasattr(self, + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + 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 Skill object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'Skill') -> 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: 'Skill') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class StatusEnum(str, Enum): + """ + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + """ + + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' + + class TypeEnum(str, Enum): + """ + The type of skill. + """ + + ACTION = 'action' + DIALOG = 'dialog' + SEARCH = 'search' + + +class SkillImport: + """ + SkillImport. + + :param str name: (optional) The name of the skill. This string cannot contain + carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This string + cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param str skill_id: (optional) The skill ID of the skill. + :param str status: (optional) The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param dict dialog_settings: (optional) For internal use only. + :param str assistant_id: (optional) The unique identifier of the assistant the + skill is associated with. + :param str workspace_id: (optional) The unique identifier of the workspace that + contains the skill content. Included only for action and dialog skills. + :param str environment_id: (optional) The unique identifier of the environment + where the skill is defined. For action and dialog skills, this is always the + draft environment. + :param bool valid: (optional) Whether the skill is structurally valid. + :param str next_snapshot_version: (optional) The name that will be given to the + next snapshot that is created for the skill. A snapshot of each versionable + skill is saved for each new release of an assistant. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, and + are not included in **Export skills** responses. + :param List[SearchSkillWarning] warnings: (optional) An array of warnings + describing errors with the search skill configuration. Included only for search + skills. + :param str language: The language of the skill. + :param str type: The type of skill. + """ + + def __init__( + self, + language: str, + type: str, + *, + name: Optional[str] = None, + description: Optional[str] = None, + workspace: Optional[dict] = None, + skill_id: Optional[str] = None, + status: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, + status_description: Optional[str] = None, + dialog_settings: Optional[dict] = None, + assistant_id: Optional[str] = None, + workspace_id: Optional[str] = None, + environment_id: Optional[str] = None, + valid: Optional[bool] = None, + next_snapshot_version: Optional[str] = None, + search_settings: Optional['SearchSettings'] = None, + warnings: Optional[List['SearchSkillWarning']] = None, + ) -> None: + """ + Initialize a SkillImport object. + + :param str language: The language of the skill. + :param str type: The type of skill. + :param str name: (optional) The name of the skill. This string cannot + contain carriage return, newline, or tab characters. + :param str description: (optional) The description of the skill. This + string cannot contain carriage return, newline, or tab characters. + :param dict workspace: (optional) An object containing the conversational + content of an action or dialog skill. + :param dict dialog_settings: (optional) For internal use only. + :param SearchSettings search_settings: (optional) An object describing the + search skill configuration. + **Note:** Search settings are not supported in **Import skills** requests, + and are not included in **Export skills** responses. + """ + self.name = name + self.description = description + self.workspace = workspace + self.skill_id = skill_id + self.status = status + self.status_errors = status_errors + self.status_description = status_description + self.dialog_settings = dialog_settings + self.assistant_id = assistant_id + self.workspace_id = workspace_id + self.environment_id = environment_id + self.valid = valid + self.next_snapshot_version = next_snapshot_version + self.search_settings = search_settings + self.warnings = warnings + self.language = language + self.type = type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SkillImport': + """Initialize a SkillImport object from a json dictionary.""" + args = {} + if (name := _dict.get('name')) is not None: + args['name'] = name + if (description := _dict.get('description')) is not None: + args['description'] = description + if (workspace := _dict.get('workspace')) is not None: + args['workspace'] = workspace + if (skill_id := _dict.get('skill_id')) is not None: + args['skill_id'] = skill_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (dialog_settings := _dict.get('dialog_settings')) is not None: + args['dialog_settings'] = dialog_settings + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (workspace_id := _dict.get('workspace_id')) is not None: + args['workspace_id'] = workspace_id + if (environment_id := _dict.get('environment_id')) is not None: + args['environment_id'] = environment_id + if (valid := _dict.get('valid')) is not None: + args['valid'] = valid + if (next_snapshot_version := + _dict.get('next_snapshot_version')) is not None: + args['next_snapshot_version'] = next_snapshot_version + if (search_settings := _dict.get('search_settings')) is not None: + args['search_settings'] = SearchSettings.from_dict(search_settings) + if (warnings := _dict.get('warnings')) is not None: + args['warnings'] = [ + SearchSkillWarning.from_dict(v) for v in warnings + ] + if (language := _dict.get('language')) is not None: + args['language'] = language + else: + raise ValueError( + 'Required property \'language\' not present in SkillImport JSON' + ) + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in SkillImport JSON') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SkillImport 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, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'workspace') and self.workspace is not None: + _dict['workspace'] = self.workspace + if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: + _dict['skill_id'] = getattr(self, 'skill_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') if hasattr(self, - 'specific_minute') and self.specific_minute is not None: - _dict['specific_minute'] = self.specific_minute + 'dialog_settings') and self.dialog_settings is not None: + _dict['dialog_settings'] = self.dialog_settings + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'workspace_id') and getattr( + self, 'workspace_id') is not None: + _dict['workspace_id'] = getattr(self, 'workspace_id') + if hasattr(self, 'environment_id') and getattr( + self, 'environment_id') is not None: + _dict['environment_id'] = getattr(self, 'environment_id') + if hasattr(self, 'valid') and getattr(self, 'valid') is not None: + _dict['valid'] = getattr(self, 'valid') + if hasattr(self, 'next_snapshot_version') and getattr( + self, 'next_snapshot_version') is not None: + _dict['next_snapshot_version'] = getattr(self, + 'next_snapshot_version') 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 + 'search_settings') and self.search_settings is not None: + if isinstance(self.search_settings, dict): + _dict['search_settings'] = self.search_settings + else: + _dict['search_settings'] = self.search_settings.to_dict() + if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: + warnings_list = [] + for v in getattr(self, 'warnings'): + if isinstance(v, dict): + warnings_list.append(v) + else: + warnings_list.append(v.to_dict()) + _dict['warnings'] = warnings_list + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type return _dict def _to_dict(self): @@ -10847,77 +14906,122 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityInterpretation object.""" + """Return a `str` version of this SkillImport object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityInterpretation') -> bool: + def __eq__(self, other: 'SkillImport') -> 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: + def __ne__(self, other: 'SkillImport') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class GranularityEnum(str, Enum): + class StatusEnum(str, Enum): """ - The precision or duration of a time range specified by a recognized `@sys-time` or - `@sys-date` entity. + The current status of the skill: + - **Available**: The skill is available and ready to process messages. + - **Failed**: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - **Non Existent**: The skill does not exist. + - **Processing**: An asynchronous operation has not yet completed. + - **Training**: The skill is training based on new data. """ - DAY = 'day' - FORTNIGHT = 'fortnight' - HOUR = 'hour' - INSTANT = 'instant' - MINUTE = 'minute' - MONTH = 'month' - QUARTER = 'quarter' - SECOND = 'second' - WEEK = 'week' - WEEKEND = 'weekend' - YEAR = 'year' + AVAILABLE = 'Available' + FAILED = 'Failed' + NON_EXISTENT = 'Non Existent' + PROCESSING = 'Processing' + TRAINING = 'Training' + UNAVAILABLE = 'Unavailable' + + class TypeEnum(str, Enum): + """ + The type of skill. + """ + + ACTION = 'action' + DIALOG = 'dialog' -class RuntimeEntityRole: +class SkillsAsyncRequestStatus: """ - 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. + SkillsAsyncRequestStatus. - :param str type: (optional) The relationship of the entity to the range. + :param str assistant_id: (optional) The assistant ID of the assistant. + :param str status: (optional) The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. + :param str status_description: (optional) The description of the failed + asynchronous operation. Included only if **status**=`Failed`. + :param List[StatusError] status_errors: (optional) An array of messages about + errors that caused an asynchronous operation to fail. Included only if + **status**=`Failed`. """ def __init__( self, *, - type: Optional[str] = None, + assistant_id: Optional[str] = None, + status: Optional[str] = None, + status_description: Optional[str] = None, + status_errors: Optional[List['StatusError']] = None, ) -> None: """ - Initialize a RuntimeEntityRole object. + Initialize a SkillsAsyncRequestStatus object. - :param str type: (optional) The relationship of the entity to the range. """ - self.type = type + self.assistant_id = assistant_id + self.status = status + self.status_description = status_description + self.status_errors = status_errors @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeEntityRole': - """Initialize a RuntimeEntityRole object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': + """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type + if (assistant_id := _dict.get('assistant_id')) is not None: + args['assistant_id'] = assistant_id + if (status := _dict.get('status')) is not None: + args['status'] = status + if (status_description := _dict.get('status_description')) is not None: + args['status_description'] = status_description + if (status_errors := _dict.get('status_errors')) is not None: + args['status_errors'] = [ + StatusError.from_dict(v) for v in status_errors + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeEntityRole object from a json dictionary.""" + """Initialize a SkillsAsyncRequestStatus 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 + if hasattr(self, 'assistant_id') and getattr( + self, 'assistant_id') is not None: + _dict['assistant_id'] = getattr(self, 'assistant_id') + if hasattr(self, 'status') and getattr(self, 'status') is not None: + _dict['status'] = getattr(self, 'status') + if hasattr(self, 'status_description') and getattr( + self, 'status_description') is not None: + _dict['status_description'] = getattr(self, 'status_description') + if hasattr(self, 'status_errors') and getattr( + self, 'status_errors') is not None: + status_errors_list = [] + for v in getattr(self, 'status_errors'): + if isinstance(v, dict): + status_errors_list.append(v) + else: + status_errors_list.append(v.to_dict()) + _dict['status_errors'] = status_errors_list return _dict def _to_dict(self): @@ -10925,101 +15029,105 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeEntityRole object.""" + """Return a `str` version of this SkillsAsyncRequestStatus object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeEntityRole') -> bool: + def __eq__(self, other: 'SkillsAsyncRequestStatus') -> 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: + def __ne__(self, other: 'SkillsAsyncRequestStatus') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): + class StatusEnum(str, Enum): """ - The relationship of the entity to the range. + The current status of the asynchronous operation: + - `Available`: An asynchronous export is available. + - `Completed`: An asynchronous import operation has completed successfully. + - `Failed`: An asynchronous operation has failed. See the **status_errors** + property for more information about the cause of the failure. + - `Processing`: An asynchronous operation has not yet completed. """ - DATE_FROM = 'date_from' - DATE_TO = 'date_to' - NUMBER_FROM = 'number_from' - NUMBER_TO = 'number_to' - TIME_FROM = 'time_from' - TIME_TO = 'time_to' + AVAILABLE = 'Available' + COMPLETED = 'Completed' + FAILED = 'Failed' + PROCESSING = 'Processing' -class RuntimeIntent: +class SkillsExport: """ - An intent identified in the user input. + SkillsExport. - :param str intent: The name of the recognized intent. - :param float confidence: (optional) A decimal percentage that represents - confidence in the intent. If you are specifying an intent as part of a request, - but you do not have a calculated confidence value, specify `1`. - :param str skill: (optional) The skill that identified the intent. Currently, - the only possible values are `main skill` for the dialog skill (if enabled) and - `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and an - action skill. + :param List[Skill] assistant_skills: An array of objects describing the skills + for the assistant. Included in responses only if **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills for + the assistant. Included in responses only if **status**=`Available`. """ def __init__( self, - intent: str, - *, - confidence: Optional[float] = None, - skill: Optional[str] = None, + assistant_skills: List['Skill'], + assistant_state: 'AssistantState', ) -> None: """ - Initialize a RuntimeIntent object. + Initialize a SkillsExport object. - :param str intent: The name of the recognized intent. - :param float confidence: (optional) A decimal percentage that represents - confidence in the intent. If you are specifying an intent as part of a - request, but you do not have a calculated confidence value, specify `1`. - :param str skill: (optional) The skill that identified the intent. - Currently, the only possible values are `main skill` for the dialog skill - (if enabled) and `actions skill` for the action skill. - This property is present only if the assistant has both a dialog skill and - an action skill. + :param List[Skill] assistant_skills: An array of objects describing the + skills for the assistant. Included in responses only if + **status**=`Available`. + :param AssistantState assistant_state: Status information about the skills + for the assistant. Included in responses only if **status**=`Available`. """ - self.intent = intent - self.confidence = confidence - self.skill = skill + self.assistant_skills = assistant_skills + self.assistant_state = assistant_state @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeIntent': - """Initialize a RuntimeIntent object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'SkillsExport': + """Initialize a SkillsExport object from a json dictionary.""" args = {} - if (intent := _dict.get('intent')) is not None: - args['intent'] = intent + if (assistant_skills := _dict.get('assistant_skills')) is not None: + args['assistant_skills'] = [ + Skill.from_dict(v) for v in assistant_skills + ] else: raise ValueError( - 'Required property \'intent\' not present in RuntimeIntent JSON' + 'Required property \'assistant_skills\' not present in SkillsExport JSON' + ) + if (assistant_state := _dict.get('assistant_state')) is not None: + args['assistant_state'] = AssistantState.from_dict(assistant_state) + else: + raise ValueError( + 'Required property \'assistant_state\' not present in SkillsExport JSON' ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (skill := _dict.get('skill')) is not None: - args['skill'] = skill return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RuntimeIntent object from a json dictionary.""" + """Initialize a SkillsExport 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, 'intent') and self.intent is not None: - _dict['intent'] = self.intent - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'skill') and self.skill is not None: - _dict['skill'] = self.skill + if hasattr(self, + 'assistant_skills') and self.assistant_skills is not None: + assistant_skills_list = [] + for v in self.assistant_skills: + if isinstance(v, dict): + assistant_skills_list.append(v) + else: + assistant_skills_list.append(v.to_dict()) + _dict['assistant_skills'] = assistant_skills_list + if hasattr(self, + 'assistant_state') and self.assistant_state is not None: + if isinstance(self.assistant_state, dict): + _dict['assistant_state'] = self.assistant_state + else: + _dict['assistant_state'] = self.assistant_state.to_dict() return _dict def _to_dict(self): @@ -11027,255 +15135,141 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RuntimeIntent object.""" + """Return a `str` version of this SkillsExport object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RuntimeIntent') -> bool: + def __eq__(self, other: 'SkillsExport') -> 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: 'RuntimeIntent') -> bool: + def __ne__(self, other: 'SkillsExport') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class RuntimeResponseGeneric: - """ - RuntimeResponseGeneric. - - """ - - def __init__(self,) -> None: - """ - Initialize a RuntimeResponseGeneric object. - - """ - msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) - raise Exception(msg) - - @classmethod - def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - disc_class = cls._get_class_by_discriminator(_dict) - if disc_class != cls: - return disc_class.from_dict(_dict) - msg = "Cannot convert dictionary into an instance of base class 'RuntimeResponseGeneric'. The discriminator value should map to a valid subclass: {1}".format( - ", ".join([ - 'RuntimeResponseGenericRuntimeResponseTypeText', - 'RuntimeResponseGenericRuntimeResponseTypePause', - 'RuntimeResponseGenericRuntimeResponseTypeImage', - 'RuntimeResponseGenericRuntimeResponseTypeOption', - 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', - 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', - 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', - 'RuntimeResponseGenericRuntimeResponseTypeVideo', - 'RuntimeResponseGenericRuntimeResponseTypeAudio', - 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' - ])) - raise Exception(msg) - - @classmethod - def _from_dict(cls, _dict: Dict): - """Initialize a RuntimeResponseGeneric object from a json dictionary.""" - return cls.from_dict(_dict) - - @classmethod - def _get_class_by_discriminator(cls, _dict: Dict) -> object: - mapping = {} - mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' - mapping[ - 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' - mapping[ - 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' - mapping['date'] = 'RuntimeResponseGenericRuntimeResponseTypeDate' - mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' - mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' - mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' - mapping[ - 'suggestion'] = 'RuntimeResponseGenericRuntimeResponseTypeSuggestion' - mapping['pause'] = 'RuntimeResponseGenericRuntimeResponseTypePause' - mapping['search'] = 'RuntimeResponseGenericRuntimeResponseTypeSearch' - mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' - mapping[ - 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' - mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' - disc_value = _dict.get('response_type') - if disc_value is None: - raise ValueError( - 'Discriminator property \'response_type\' not found in RuntimeResponseGeneric JSON' - ) - class_name = mapping.get(disc_value, disc_value) - try: - disc_class = getattr(sys.modules[__name__], class_name) - except AttributeError: - disc_class = cls - if isinstance(disc_class, object): - return disc_class - raise TypeError('%s is not a discriminator class' % class_name) - - -class SearchResult: +class StatefulMessageResponse: """ - SearchResult. + A response from the watsonx Assistant service. - :param str id: The unique identifier of the document in the Discovery service - collection. - This property is included in responses from search skills, which are available - only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search result - metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is taken - from an abstract, summary, or highlight field in the Discovery service response, - as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken from - a title or name field in the Discovery service response, as specified in the - search skill configuration. - :param str url: (optional) The URL of the original data object in its native - data source. - :param SearchResultHighlight highlight: (optional) An object containing segments - of text from search results with query-matching text highlighted using HTML - `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying segments - of text within the result that were identified as direct answers to the search - query. Currently, only the single answer with the highest confidence (if any) is - returned. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param MessageContext context: (optional) Context data for the conversation. You + can use this property to access context variables. The context is stored by the + assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: A string value that identifies the user who is interacting + with the assistant. The client must provide a unique identifier for each + individual end user who accesses the application. For user-based plans, this + user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. """ def __init__( self, - id: str, - result_metadata: 'SearchResultMetadata', + output: 'MessageOutput', + user_id: str, *, - body: Optional[str] = None, - title: Optional[str] = None, - url: Optional[str] = None, - highlight: Optional['SearchResultHighlight'] = None, - answers: Optional[List['SearchResultAnswer']] = None, + context: Optional['MessageContext'] = None, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, ) -> None: """ - Initialize a SearchResult object. + Initialize a StatefulMessageResponse object. - :param str id: The unique identifier of the document in the Discovery - service collection. - This property is included in responses from search skills, which are - available only to Plus or Enterprise plan users. - :param SearchResultMetadata result_metadata: An object containing search - result metadata from the Discovery service. - :param str body: (optional) A description of the search result. This is - taken from an abstract, summary, or highlight field in the Discovery - service response, as specified in the search skill configuration. - :param str title: (optional) The title of the search result. This is taken - from a title or name field in the Discovery service response, as specified - in the search skill configuration. - :param str url: (optional) The URL of the original data object in its - native data source. - :param SearchResultHighlight highlight: (optional) An object containing - segments of text from search results with query-matching text highlighted - using HTML `` tags. - :param List[SearchResultAnswer] answers: (optional) An array specifying - segments of text within the result that were identified as direct answers - to the search query. Currently, only the single answer with the highest - confidence (if any) is returned. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param str user_id: A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier + for each individual end user who accesses the application. For user-based + plans, this user ID is used to identify unique users for billing purposes. + This string cannot contain carriage return, newline, or tab characters. If + no value is specified in the input, **user_id** is automatically set to the + value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + :param MessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. """ - self.id = id - self.result_metadata = result_metadata - self.body = body - self.title = title - self.url = url - self.highlight = highlight - self.answers = answers + self.output = output + self.context = context + self.user_id = user_id + self.masked_output = masked_output + self.masked_input = masked_input @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResult': - """Initialize a SearchResult object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatefulMessageResponse': + """Initialize a StatefulMessageResponse object from a json dictionary.""" args = {} - if (id := _dict.get('id')) is not None: - args['id'] = id + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) else: raise ValueError( - 'Required property \'id\' not present in SearchResult JSON') - if (result_metadata := _dict.get('result_metadata')) is not None: - args['result_metadata'] = SearchResultMetadata.from_dict( - result_metadata) + 'Required property \'output\' not present in StatefulMessageResponse JSON' + ) + if (context := _dict.get('context')) is not None: + args['context'] = MessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id else: raise ValueError( - 'Required property \'result_metadata\' not present in SearchResult JSON' + 'Required property \'user_id\' not present in StatefulMessageResponse JSON' ) - if (body := _dict.get('body')) is not None: - args['body'] = body - if (title := _dict.get('title')) is not None: - args['title'] = title - if (url := _dict.get('url')) is not None: - args['url'] = url - if (highlight := _dict.get('highlight')) is not None: - args['highlight'] = SearchResultHighlight.from_dict(highlight) - if (answers := _dict.get('answers')) is not None: - args['answers'] = [SearchResultAnswer.from_dict(v) for v in answers] + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResult object from a json dictionary.""" + """Initialize a StatefulMessageResponse 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, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, - 'result_metadata') and self.result_metadata is not None: - if isinstance(self.result_metadata, dict): - _dict['result_metadata'] = self.result_metadata + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output else: - _dict['result_metadata'] = self.result_metadata.to_dict() - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'highlight') and self.highlight is not None: - if isinstance(self.highlight, dict): - _dict['highlight'] = self.highlight + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context else: - _dict['highlight'] = self.highlight.to_dict() - if hasattr(self, 'answers') and self.answers is not None: - answers_list = [] - for v in self.answers: - if isinstance(v, dict): - answers_list.append(v) - else: - answers_list.append(v.to_dict()) - _dict['answers'] = answers_list + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() return _dict def _to_dict(self): @@ -11283,75 +15277,107 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResult object.""" + """Return a `str` version of this StatefulMessageResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResult') -> bool: + def __eq__(self, other: 'StatefulMessageResponse') -> 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: 'SearchResult') -> bool: + def __ne__(self, other: 'StatefulMessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultAnswer: +class StatelessFinalResponse: """ - An object specifing a segment of text that was identified as a direct answer to the - search query. + Message final response content. - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned by the - Discovery service. + :param StatelessFinalResponseOutput output: (optional) Assistant output to be + rendered or processed by the client. + :param StatelessMessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The context + is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ def __init__( self, - text: str, - confidence: float, + *, + output: Optional['StatelessFinalResponseOutput'] = None, + context: Optional['StatelessMessageContext'] = None, + user_id: Optional[str] = None, ) -> None: """ - Initialize a SearchResultAnswer object. + Initialize a StatelessFinalResponse object. - :param str text: The text of the answer. - :param float confidence: The confidence score for the answer, as returned - by the Discovery service. + :param StatelessFinalResponseOutput output: (optional) Assistant output to + be rendered or processed by the client. + :param StatelessMessageContext context: (optional) Context data for the + conversation. You can use this property to access context variables. The + context is stored by the assistant on a per-session basis. + **Note:** The context is included in message responses only if + **return_context**=`true` in the message request. Full context is always + included in logs. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. """ - self.text = text - self.confidence = confidence + self.output = output + self.context = context + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': - """Initialize a SearchResultAnswer object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessFinalResponse': + """Initialize a StatelessFinalResponse object from a json dictionary.""" args = {} - if (text := _dict.get('text')) is not None: - args['text'] = text - else: - raise ValueError( - 'Required property \'text\' not present in SearchResultAnswer JSON' - ) - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - else: - raise ValueError( - 'Required property \'confidence\' not present in SearchResultAnswer JSON' - ) + if (output := _dict.get('output')) is not None: + args['output'] = StatelessFinalResponseOutput.from_dict(output) + if (context := _dict.get('context')) is not None: + args['context'] = StatelessMessageContext.from_dict(context) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultAnswer object from a json dictionary.""" + """Initialize a StatelessFinalResponse 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output + else: + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -11359,244 +15385,282 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultAnswer object.""" + """Return a `str` version of this StatelessFinalResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultAnswer') -> bool: + def __eq__(self, other: 'StatelessFinalResponse') -> 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: 'SearchResultAnswer') -> bool: + def __ne__(self, other: 'StatelessFinalResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultHighlight: +class StatelessFinalResponseOutput: """ - An object containing segments of text from search results with query-matching text - highlighted using HTML `` tags. - - :param List[str] body: (optional) An array of strings containing segments taken - from body text in the search results, with query-matching substrings - highlighted. - :param List[str] title: (optional) An array of strings containing segments taken - from title text in the search results, with query-matching substrings - highlighted. - :param List[str] url: (optional) An array of strings containing segments taken - from URLs in the search results, with query-matching substrings highlighted. + Assistant output to be rendered or processed by the client. - This type supports additional properties of type List[str]. An array of strings - containing segments taken from a field in the search results that is not mapped to the - `body`, `title`, or `url` property, with query-matching substrings highlighted. The - property name is the name of the field in the Discovery collection. + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for any + channel. It is the responsibility of the client application to implement the + supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents recognized in + the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities identified + in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects describing + any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom properties + included in the response. This object includes any arbitrary properties defined + in the dialog JSON editor as part of the dialog node output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + :param StatelessMessageContext streaming_metadata: """ - # The set of defined properties for the class - _properties = frozenset(['body', 'title', 'url']) - def __init__( self, + streaming_metadata: 'StatelessMessageContext', *, - body: Optional[List[str]] = None, - title: Optional[List[str]] = None, - url: Optional[List[str]] = None, - **kwargs: Optional[List[str]], - ) -> None: - """ - Initialize a SearchResultHighlight object. - - :param List[str] body: (optional) An array of strings containing segments - taken from body text in the search results, with query-matching substrings - highlighted. - :param List[str] title: (optional) An array of strings containing segments - taken from title text in the search results, with query-matching substrings - highlighted. - :param List[str] url: (optional) An array of strings containing segments - taken from URLs in the search results, with query-matching substrings - highlighted. - :param List[str] **kwargs: (optional) An array of strings containing - segments taken from a field in the search results that is not mapped to the - `body`, `title`, or `url` property, with query-matching substrings - highlighted. The property name is the name of the field in the Discovery - collection. + generic: Optional[List['RuntimeResponseGeneric']] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + actions: Optional[List['DialogNodeAction']] = None, + debug: Optional['MessageOutputDebug'] = None, + user_defined: Optional[dict] = None, + spelling: Optional['MessageOutputSpelling'] = None, + llm_metadata: Optional[List['MessageOutputLLMMetadata']] = None, + ) -> None: """ - self.body = body - self.title = title - self.url = url - for k, v in kwargs.items(): - if k not in SearchResultHighlight._properties: - if not isinstance(v, List): - raise ValueError( - 'Value for additional property {} must be of type List[Foo]' - .format(k)) - _v = [] - for elem in v: - if not isinstance(elem, str): - raise ValueError( - 'Value for additional property {} must be of type List[str]' - .format(k)) - _v.append(elem) - setattr(self, k, _v) - else: - raise ValueError( - 'Property {} cannot be specified as an additional property'. - format(k)) + Initialize a StatelessFinalResponseOutput object. + + :param StatelessMessageContext streaming_metadata: + :param List[RuntimeResponseGeneric] generic: (optional) Output intended for + any channel. It is the responsibility of the client application to + implement the supported response types. + :param List[RuntimeIntent] intents: (optional) An array of intents + recognized in the user input, sorted in descending order of confidence. + :param List[RuntimeEntity] entities: (optional) An array of entities + identified in the user input. + :param List[DialogNodeAction] actions: (optional) An array of objects + describing any actions requested by the dialog node. + :param MessageOutputDebug debug: (optional) Additional detailed information + about a message response and how it was generated. + :param dict user_defined: (optional) An object containing any custom + properties included in the response. This object includes any arbitrary + properties defined in the dialog JSON editor as part of the dialog node + output. + :param MessageOutputSpelling spelling: (optional) Properties describing any + spelling corrections in the user input that was received. + :param List[MessageOutputLLMMetadata] llm_metadata: (optional) An array of + objects that provide information about calls to large language models that + occured as part of handling this message. + """ + self.generic = generic + self.intents = intents + self.entities = entities + self.actions = actions + self.debug = debug + self.user_defined = user_defined + self.spelling = spelling + self.llm_metadata = llm_metadata + self.streaming_metadata = streaming_metadata @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultHighlight': - """Initialize a SearchResultHighlight object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessFinalResponseOutput': + """Initialize a StatelessFinalResponseOutput object from a json dictionary.""" args = {} - if (body := _dict.get('body')) is not None: - args['body'] = body - if (title := _dict.get('title')) is not None: - args['title'] = title - if (url := _dict.get('url')) is not None: - args['url'] = url - for k, v in _dict.items(): - if k not in cls._properties: - if not isinstance(v, List): - raise ValueError( - 'Value for additional property {} must be of type List[str]' - .format(k)) - _v = [] - for elem in v: - if not isinstance(elem, str): - raise ValueError( - 'Value for additional property {} must be of type List[str]' - .format(k)) - _v.append(elem) - args[k] = _v + if (generic := _dict.get('generic')) is not None: + args['generic'] = [ + RuntimeResponseGeneric.from_dict(v) for v in generic + ] + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (actions := _dict.get('actions')) is not None: + args['actions'] = [DialogNodeAction.from_dict(v) for v in actions] + if (debug := _dict.get('debug')) is not None: + args['debug'] = MessageOutputDebug.from_dict(debug) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageOutputSpelling.from_dict(spelling) + if (llm_metadata := _dict.get('llm_metadata')) is not None: + args['llm_metadata'] = [ + MessageOutputLLMMetadata.from_dict(v) for v in llm_metadata + ] + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = StatelessMessageContext.from_dict( + streaming_metadata) + else: + raise ValueError( + 'Required property \'streaming_metadata\' not present in StatelessFinalResponseOutput JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultHighlight object from a json dictionary.""" + """Initialize a StatelessFinalResponseOutput 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, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - for k in [ - _k for _k in vars(self).keys() - if _k not in SearchResultHighlight._properties - ]: - _dict[k] = getattr(self, k) + if hasattr(self, 'generic') and self.generic is not None: + generic_list = [] + for v in self.generic: + if isinstance(v, dict): + generic_list.append(v) + else: + generic_list.append(v.to_dict()) + _dict['generic'] = generic_list + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'actions') and self.actions is not None: + actions_list = [] + for v in self.actions: + if isinstance(v, dict): + actions_list.append(v) + else: + actions_list.append(v.to_dict()) + _dict['actions'] = actions_list + if hasattr(self, 'debug') and self.debug is not None: + if isinstance(self.debug, dict): + _dict['debug'] = self.debug + else: + _dict['debug'] = self.debug.to_dict() + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'llm_metadata') and self.llm_metadata is not None: + llm_metadata_list = [] + for v in self.llm_metadata: + if isinstance(v, dict): + llm_metadata_list.append(v) + else: + llm_metadata_list.append(v.to_dict()) + _dict['llm_metadata'] = llm_metadata_list + if hasattr( + self, + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata + else: + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() - def get_properties(self) -> Dict: - """Return the additional properties from this instance of SearchResultHighlight in the form of a dict.""" - _dict = {} - for k in [ - _k for _k in vars(self).keys() - if _k not in SearchResultHighlight._properties - ]: - _dict[k] = getattr(self, k) - return _dict - - def set_properties(self, _dict: dict): - """Set a dictionary of additional properties in this instance of SearchResultHighlight""" - for k in [ - _k for _k in vars(self).keys() - if _k not in SearchResultHighlight._properties - ]: - delattr(self, k) - for k, v in _dict.items(): - if k not in SearchResultHighlight._properties: - if not isinstance(v, List): - raise ValueError( - 'Value for additional property {} must be of type List[str]' - .format(k)) - _v = [] - for elem in v: - if not isinstance(elem, str): - raise ValueError( - 'Value for additional property {} must be of type List[str]' - .format(k)) - _v.append(elem) - setattr(self, k, _v) - else: - raise ValueError( - 'Property {} cannot be specified as an additional property'. - format(k)) - def __str__(self) -> str: - """Return a `str` version of this SearchResultHighlight object.""" + """Return a `str` version of this StatelessFinalResponseOutput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultHighlight') -> bool: + def __eq__(self, other: 'StatelessFinalResponseOutput') -> 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: 'SearchResultHighlight') -> bool: + def __ne__(self, other: 'StatelessFinalResponseOutput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchResultMetadata: +class StatelessMessageContext: """ - An object containing search result metadata from the Discovery service. + StatelessMessageContext. - :param float confidence: (optional) The confidence score for the given result, - as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher score - indicates a greater match to the query parameters. + :param StatelessMessageContextGlobal global_: (optional) Session context data + that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data specific to + particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ def __init__( self, *, - confidence: Optional[float] = None, - score: Optional[float] = None, + global_: Optional['StatelessMessageContextGlobal'] = None, + skills: Optional['StatelessMessageContextSkills'] = None, + integrations: Optional[dict] = None, ) -> None: """ - Initialize a SearchResultMetadata object. + Initialize a StatelessMessageContext object. - :param float confidence: (optional) The confidence score for the given - result, as returned by the Discovery service. - :param float score: (optional) An unbounded measure of the relevance of a - particular result, dependent on the query and matching document. A higher - score indicates a greater match to the query parameters. + :param StatelessMessageContextGlobal global_: (optional) Session context + data that is shared by all skills used by the assistant. + :param StatelessMessageContextSkills skills: (optional) Context data + specific to particular skills used by the assistant. + :param dict integrations: (optional) An object containing context data that + is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ - self.confidence = confidence - self.score = score + self.global_ = global_ + self.skills = skills + self.integrations = integrations @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchResultMetadata': - """Initialize a SearchResultMetadata object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContext': + """Initialize a StatelessMessageContext object from a json dictionary.""" args = {} - if (confidence := _dict.get('confidence')) is not None: - args['confidence'] = confidence - if (score := _dict.get('score')) is not None: - args['score'] = score + if (global_ := _dict.get('global')) is not None: + args['global_'] = StatelessMessageContextGlobal.from_dict(global_) + if (skills := _dict.get('skills')) is not None: + args['skills'] = StatelessMessageContextSkills.from_dict(skills) + if (integrations := _dict.get('integrations')) is not None: + args['integrations'] = integrations return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchResultMetadata object from a json dictionary.""" + """Initialize a StatelessMessageContext 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, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score + if hasattr(self, 'global_') and self.global_ is not None: + if isinstance(self.global_, dict): + _dict['global'] = self.global_ + else: + _dict['global'] = self.global_.to_dict() + if hasattr(self, 'skills') and self.skills is not None: + if isinstance(self.skills, dict): + _dict['skills'] = self.skills + else: + _dict['skills'] = self.skills.to_dict() + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations return _dict def _to_dict(self): @@ -11604,178 +15668,70 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchResultMetadata object.""" + """Return a `str` version of this StatelessMessageContext object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchResultMetadata') -> bool: + def __eq__(self, other: 'StatelessMessageContext') -> 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: 'SearchResultMetadata') -> bool: + def __ne__(self, other: 'StatelessMessageContext') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettings: +class StatelessMessageContextGlobal: """ - An object describing the search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and are not - included in **Export skills** responses. + Session context data that is shared by all skills used by the assistant. - :param SearchSettingsDiscovery discovery: Configuration settings for the Watson - Discovery service instance used by the search integration. - :param SearchSettingsMessages messages: The messages included with responses - from the search integration. - :param SearchSettingsSchemaMapping schema_mapping: The mapping between fields in - the Watson Discovery collection and properties in the search response. - :param SearchSettingsElasticSearch elastic_search: (optional) Configuration - settings for the Elasticsearch service used by the search integration. You can - provide either basic auth or apiKey auth. - :param SearchSettingsConversationalSearch conversational_search: (optional) - Configuration settings for conversational search. - :param SearchSettingsServerSideSearch server_side_search: (optional) - Configuration settings for the server-side search service used by the search - integration. You can provide either basic auth, apiKey auth or none. - :param SearchSettingsClientSideSearch client_side_search: (optional) - Configuration settings for the client-side search service or server-side search - service used by the search integration. + :param MessageContextGlobalSystem system: (optional) Built-in system properties + that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. """ def __init__( self, - discovery: 'SearchSettingsDiscovery', - messages: 'SearchSettingsMessages', - schema_mapping: 'SearchSettingsSchemaMapping', *, - elastic_search: Optional['SearchSettingsElasticSearch'] = None, - conversational_search: Optional[ - 'SearchSettingsConversationalSearch'] = None, - server_side_search: Optional['SearchSettingsServerSideSearch'] = None, - client_side_search: Optional['SearchSettingsClientSideSearch'] = None, + system: Optional['MessageContextGlobalSystem'] = None, + session_id: Optional[str] = None, ) -> None: """ - Initialize a SearchSettings object. + Initialize a StatelessMessageContextGlobal object. - :param SearchSettingsDiscovery discovery: Configuration settings for the - Watson Discovery service instance used by the search integration. - :param SearchSettingsMessages messages: The messages included with - responses from the search integration. - :param SearchSettingsSchemaMapping schema_mapping: The mapping between - fields in the Watson Discovery collection and properties in the search - response. - :param SearchSettingsElasticSearch elastic_search: (optional) Configuration - settings for the Elasticsearch service used by the search integration. You - can provide either basic auth or apiKey auth. - :param SearchSettingsConversationalSearch conversational_search: (optional) - Configuration settings for conversational search. - :param SearchSettingsServerSideSearch server_side_search: (optional) - Configuration settings for the server-side search service used by the - search integration. You can provide either basic auth, apiKey auth or none. - :param SearchSettingsClientSideSearch client_side_search: (optional) - Configuration settings for the client-side search service or server-side - search service used by the search integration. + :param MessageContextGlobalSystem system: (optional) Built-in system + properties that apply to all skills used by the assistant. + :param str session_id: (optional) The unique identifier of the session. """ - self.discovery = discovery - self.messages = messages - self.schema_mapping = schema_mapping - self.elastic_search = elastic_search - self.conversational_search = conversational_search - self.server_side_search = server_side_search - self.client_side_search = client_side_search + self.system = system + self.session_id = session_id @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettings': - """Initialize a SearchSettings object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextGlobal': + """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" args = {} - if (discovery := _dict.get('discovery')) is not None: - args['discovery'] = SearchSettingsDiscovery.from_dict(discovery) - else: - raise ValueError( - 'Required property \'discovery\' not present in SearchSettings JSON' - ) - if (messages := _dict.get('messages')) is not None: - args['messages'] = SearchSettingsMessages.from_dict(messages) - else: - raise ValueError( - 'Required property \'messages\' not present in SearchSettings JSON' - ) - if (schema_mapping := _dict.get('schema_mapping')) is not None: - args['schema_mapping'] = SearchSettingsSchemaMapping.from_dict( - schema_mapping) - else: - raise ValueError( - 'Required property \'schema_mapping\' not present in SearchSettings JSON' - ) - if (elastic_search := _dict.get('elastic_search')) is not None: - args['elastic_search'] = SearchSettingsElasticSearch.from_dict( - elastic_search) - if (conversational_search := - _dict.get('conversational_search')) is not None: - args[ - 'conversational_search'] = SearchSettingsConversationalSearch.from_dict( - conversational_search) - if (server_side_search := _dict.get('server_side_search')) is not None: - args[ - 'server_side_search'] = SearchSettingsServerSideSearch.from_dict( - server_side_search) - if (client_side_search := _dict.get('client_side_search')) is not None: - args[ - 'client_side_search'] = SearchSettingsClientSideSearch.from_dict( - client_side_search) + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextGlobalSystem.from_dict(system) + if (session_id := _dict.get('session_id')) is not None: + args['session_id'] = session_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettings object from a json dictionary.""" + """Initialize a StatelessMessageContextGlobal 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, 'discovery') and self.discovery is not None: - if isinstance(self.discovery, dict): - _dict['discovery'] = self.discovery - else: - _dict['discovery'] = self.discovery.to_dict() - if hasattr(self, 'messages') and self.messages is not None: - if isinstance(self.messages, dict): - _dict['messages'] = self.messages - else: - _dict['messages'] = self.messages.to_dict() - if hasattr(self, 'schema_mapping') and self.schema_mapping is not None: - if isinstance(self.schema_mapping, dict): - _dict['schema_mapping'] = self.schema_mapping - else: - _dict['schema_mapping'] = self.schema_mapping.to_dict() - if hasattr(self, 'elastic_search') and self.elastic_search is not None: - if isinstance(self.elastic_search, dict): - _dict['elastic_search'] = self.elastic_search - else: - _dict['elastic_search'] = self.elastic_search.to_dict() - if hasattr(self, 'conversational_search' - ) and self.conversational_search is not None: - if isinstance(self.conversational_search, dict): - _dict['conversational_search'] = self.conversational_search - else: - _dict[ - 'conversational_search'] = self.conversational_search.to_dict( - ) - if hasattr( - self, - 'server_side_search') and self.server_side_search is not None: - if isinstance(self.server_side_search, dict): - _dict['server_side_search'] = self.server_side_search - else: - _dict['server_side_search'] = self.server_side_search.to_dict() - if hasattr( - self, - 'client_side_search') and self.client_side_search is not None: - if isinstance(self.client_side_search, dict): - _dict['client_side_search'] = self.client_side_search + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system else: - _dict['client_side_search'] = self.client_side_search.to_dict() + _dict['system'] = self.system.to_dict() + if hasattr(self, 'session_id') and self.session_id is not None: + _dict['session_id'] = self.session_id return _dict def _to_dict(self): @@ -11783,68 +15739,78 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettings object.""" + """Return a `str` version of this StatelessMessageContextGlobal object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettings') -> bool: + def __eq__(self, other: 'StatelessMessageContextGlobal') -> 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: 'SearchSettings') -> bool: + def __ne__(self, other: 'StatelessMessageContextGlobal') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsClientSideSearch: +class StatelessMessageContextSkills: """ - Configuration settings for the client-side search service or server-side search - service used by the search integration. + Context data specific to particular skills used by the assistant. - :param str filter: (optional) The filter string that is applied to the search - results. - :param dict metadata: (optional) The metadata object. + :param MessageContextDialogSkill main_skill: (optional) Context variables that + are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. """ def __init__( self, *, - filter: Optional[str] = None, - metadata: Optional[dict] = None, + main_skill: Optional['MessageContextDialogSkill'] = None, + actions_skill: Optional[ + 'StatelessMessageContextSkillsActionsSkill'] = None, ) -> None: """ - Initialize a SearchSettingsClientSideSearch object. + Initialize a StatelessMessageContextSkills object. - :param str filter: (optional) The filter string that is applied to the - search results. - :param dict metadata: (optional) The metadata object. + :param MessageContextDialogSkill main_skill: (optional) Context variables + that are used by the dialog skill. + :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) + Context variables that are used by the action skill. """ - self.filter = filter - self.metadata = metadata + self.main_skill = main_skill + self.actions_skill = actions_skill @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsClientSideSearch': - """Initialize a SearchSettingsClientSideSearch object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextSkills': + """Initialize a StatelessMessageContextSkills object from a json dictionary.""" args = {} - if (filter := _dict.get('filter')) is not None: - args['filter'] = filter - if (metadata := _dict.get('metadata')) is not None: - args['metadata'] = metadata + if (main_skill := _dict.get('main skill')) is not None: + args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) + if (actions_skill := _dict.get('actions skill')) is not None: + args[ + 'actions_skill'] = StatelessMessageContextSkillsActionsSkill.from_dict( + actions_skill) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsClientSideSearch object from a json dictionary.""" + """Initialize a StatelessMessageContextSkills 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, 'filter') and self.filter is not None: - _dict['filter'] = self.filter - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata + if hasattr(self, 'main_skill') and self.main_skill is not None: + if isinstance(self.main_skill, dict): + _dict['main skill'] = self.main_skill + else: + _dict['main skill'] = self.main_skill.to_dict() + if hasattr(self, 'actions_skill') and self.actions_skill is not None: + if isinstance(self.actions_skill, dict): + _dict['actions skill'] = self.actions_skill + else: + _dict['actions skill'] = self.actions_skill.to_dict() return _dict def _to_dict(self): @@ -11852,95 +15818,134 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsClientSideSearch object.""" + """Return a `str` version of this StatelessMessageContextSkills object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsClientSideSearch') -> bool: + def __eq__(self, other: 'StatelessMessageContextSkills') -> 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: 'SearchSettingsClientSideSearch') -> bool: + def __ne__(self, other: 'StatelessMessageContextSkills') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsConversationalSearch: +class StatelessMessageContextSkillsActionsSkill: """ - Configuration settings for conversational search. + Context variables that are used by the action skill. - :param bool enabled: Whether to enable conversational search. - :param SearchSettingsConversationalSearchResponseLength response_length: - (optional) - :param SearchSettingsConversationalSearchSearchConfidence search_confidence: - (optional) + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data used by + the skill. + :param dict action_variables: (optional) An object containing action variables. + Action variables can be accessed only by steps in the same action, and do not + persist after the action ends. + :param dict skill_variables: (optional) An object containing skill variables. + (In the watsonx Assistant user interface, skill variables are called _session + variables_.) Skill variables can be accessed by any action and persist for the + duration of the session. + :param dict private_action_variables: (optional) An object containing private + action variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. Private variables are + encrypted. + :param dict private_skill_variables: (optional) An object containing private + skill variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action and + persist for the duration of the session. Private variables are encrypted. """ def __init__( self, - enabled: bool, *, - response_length: Optional[ - 'SearchSettingsConversationalSearchResponseLength'] = None, - search_confidence: Optional[ - 'SearchSettingsConversationalSearchSearchConfidence'] = None, + user_defined: Optional[dict] = None, + system: Optional['MessageContextSkillSystem'] = None, + action_variables: Optional[dict] = None, + skill_variables: Optional[dict] = None, + private_action_variables: Optional[dict] = None, + private_skill_variables: Optional[dict] = None, ) -> None: """ - Initialize a SearchSettingsConversationalSearch object. + Initialize a StatelessMessageContextSkillsActionsSkill object. - :param bool enabled: Whether to enable conversational search. - :param SearchSettingsConversationalSearchResponseLength response_length: - (optional) - :param SearchSettingsConversationalSearchSearchConfidence - search_confidence: (optional) + :param dict user_defined: (optional) An object containing any arbitrary + variables that can be read and written by a particular skill. + :param MessageContextSkillSystem system: (optional) System context data + used by the skill. + :param dict action_variables: (optional) An object containing action + variables. Action variables can be accessed only by steps in the same + action, and do not persist after the action ends. + :param dict skill_variables: (optional) An object containing skill + variables. (In the watsonx Assistant user interface, skill variables are + called _session variables_.) Skill variables can be accessed by any action + and persist for the duration of the session. + :param dict private_action_variables: (optional) An object containing + private action variables. Action variables can be accessed only by steps in + the same action, and do not persist after the action ends. Private + variables are encrypted. + :param dict private_skill_variables: (optional) An object containing + private skill variables. (In the watsonx Assistant user interface, skill + variables are called _session variables_.) Skill variables can be accessed + by any action and persist for the duration of the session. Private + variables are encrypted. """ - self.enabled = enabled - self.response_length = response_length - self.search_confidence = search_confidence + self.user_defined = user_defined + self.system = system + self.action_variables = action_variables + self.skill_variables = skill_variables + self.private_action_variables = private_action_variables + self.private_skill_variables = private_skill_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsConversationalSearch': - """Initialize a SearchSettingsConversationalSearch object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'StatelessMessageContextSkillsActionsSkill': + """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" args = {} - if (enabled := _dict.get('enabled')) is not None: - args['enabled'] = enabled - else: - raise ValueError( - 'Required property \'enabled\' not present in SearchSettingsConversationalSearch JSON' - ) - if (response_length := _dict.get('response_length')) is not None: - args[ - 'response_length'] = SearchSettingsConversationalSearchResponseLength.from_dict( - response_length) - if (search_confidence := _dict.get('search_confidence')) is not None: - args[ - 'search_confidence'] = SearchSettingsConversationalSearchSearchConfidence.from_dict( - search_confidence) + if (user_defined := _dict.get('user_defined')) is not None: + args['user_defined'] = user_defined + if (system := _dict.get('system')) is not None: + args['system'] = MessageContextSkillSystem.from_dict(system) + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables + if (skill_variables := _dict.get('skill_variables')) is not None: + args['skill_variables'] = skill_variables + if (private_action_variables := + _dict.get('private_action_variables')) is not None: + args['private_action_variables'] = private_action_variables + if (private_skill_variables := + _dict.get('private_skill_variables')) is not None: + args['private_skill_variables'] = private_skill_variables return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsConversationalSearch object from a json dictionary.""" + """Initialize a StatelessMessageContextSkillsActionsSkill 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 - if hasattr(self, - 'response_length') and self.response_length is not None: - if isinstance(self.response_length, dict): - _dict['response_length'] = self.response_length + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'system') and self.system is not None: + if isinstance(self.system, dict): + _dict['system'] = self.system else: - _dict['response_length'] = self.response_length.to_dict() + _dict['system'] = self.system.to_dict() if hasattr(self, - 'search_confidence') and self.search_confidence is not None: - if isinstance(self.search_confidence, dict): - _dict['search_confidence'] = self.search_confidence - else: - _dict['search_confidence'] = self.search_confidence.to_dict() + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables + if hasattr(self, + 'skill_variables') and self.skill_variables is not None: + _dict['skill_variables'] = self.skill_variables + if hasattr(self, 'private_action_variables' + ) and self.private_action_variables is not None: + _dict['private_action_variables'] = self.private_action_variables + if hasattr(self, 'private_skill_variables' + ) and self.private_skill_variables is not None: + _dict['private_skill_variables'] = self.private_skill_variables return _dict def _to_dict(self): @@ -11948,61 +15953,177 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsConversationalSearch object.""" + """Return a `str` version of this StatelessMessageContextSkillsActionsSkill object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsConversationalSearch') -> bool: + def __eq__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> 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: 'SearchSettingsConversationalSearch') -> bool: + def __ne__(self, + other: 'StatelessMessageContextSkillsActionsSkill') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsConversationalSearchResponseLength: +class StatelessMessageInput: """ - SearchSettingsConversationalSearchResponseLength. + An input object that includes the input text. - :param str option: (optional) The response length option. It controls the length - of the generated response. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating + the user input. Include intents from the previous response to continue using + those intents rather than trying to recognize intents in the new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating + the message. Include entities from the previous response to continue using those + entities rather than detecting entities in the new input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the Segment + extension. + :param StatelessMessageInputOptions options: (optional) Optional properties that + control how the assistant responds. """ def __init__( self, *, - option: Optional[str] = None, + message_type: Optional[str] = None, + text: Optional[str] = None, + intents: Optional[List['RuntimeIntent']] = None, + entities: Optional[List['RuntimeEntity']] = None, + suggestion_id: Optional[str] = None, + attachments: Optional[List['MessageInputAttachment']] = None, + analytics: Optional['RequestAnalytics'] = None, + options: Optional['StatelessMessageInputOptions'] = None, ) -> None: """ - Initialize a SearchSettingsConversationalSearchResponseLength object. + Initialize a StatelessMessageInput object. - :param str option: (optional) The response length option. It controls the - length of the generated response. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. + :param str text: (optional) The text of the user input. This string cannot + contain carriage return, newline, or tab characters. + :param List[RuntimeIntent] intents: (optional) Intents to use when + evaluating the user input. Include intents from the previous response to + continue using those intents rather than trying to recognize intents in the + new input. + :param List[RuntimeEntity] entities: (optional) Entities to use when + evaluating the message. Include entities from the previous response to + continue using those entities rather than detecting entities in the new + input. + :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. Attachments are not + processed by the assistant itself, but can be sent to external services by + webhooks. + **Note:** Attachments are not supported on IBM Cloud Pak for Data. + :param RequestAnalytics analytics: (optional) An optional object containing + analytics data. Currently, this data is used only for events sent to the + Segment extension. + :param StatelessMessageInputOptions options: (optional) Optional properties + that control how the assistant responds. """ - self.option = option + self.message_type = message_type + self.text = text + self.intents = intents + self.entities = entities + self.suggestion_id = suggestion_id + self.attachments = attachments + self.analytics = analytics + self.options = options @classmethod - def from_dict( - cls, - _dict: Dict) -> 'SearchSettingsConversationalSearchResponseLength': - """Initialize a SearchSettingsConversationalSearchResponseLength object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInput': + """Initialize a StatelessMessageInput object from a json dictionary.""" args = {} - if (option := _dict.get('option')) is not None: - args['option'] = option + if (message_type := _dict.get('message_type')) is not None: + args['message_type'] = message_type + if (text := _dict.get('text')) is not None: + args['text'] = text + if (intents := _dict.get('intents')) is not None: + args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] + if (entities := _dict.get('entities')) is not None: + args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] + if (suggestion_id := _dict.get('suggestion_id')) is not None: + args['suggestion_id'] = suggestion_id + if (attachments := _dict.get('attachments')) is not None: + args['attachments'] = [ + MessageInputAttachment.from_dict(v) for v in attachments + ] + if (analytics := _dict.get('analytics')) is not None: + args['analytics'] = RequestAnalytics.from_dict(analytics) + if (options := _dict.get('options')) is not None: + args['options'] = StatelessMessageInputOptions.from_dict(options) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsConversationalSearchResponseLength object from a json dictionary.""" + """Initialize a StatelessMessageInput 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, 'option') and self.option is not None: - _dict['option'] = self.option + if hasattr(self, 'message_type') and self.message_type is not None: + _dict['message_type'] = self.message_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'intents') and self.intents is not None: + intents_list = [] + for v in self.intents: + if isinstance(v, dict): + intents_list.append(v) + else: + intents_list.append(v.to_dict()) + _dict['intents'] = intents_list + if hasattr(self, 'entities') and self.entities is not None: + entities_list = [] + for v in self.entities: + if isinstance(v, dict): + entities_list.append(v) + else: + entities_list.append(v.to_dict()) + _dict['entities'] = entities_list + if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: + _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + attachments_list = [] + for v in self.attachments: + if isinstance(v, dict): + attachments_list.append(v) + else: + attachments_list.append(v.to_dict()) + _dict['attachments'] = attachments_list + if hasattr(self, 'analytics') and self.analytics is not None: + if isinstance(self.analytics, dict): + _dict['analytics'] = self.analytics + else: + _dict['analytics'] = self.analytics.to_dict() + if hasattr(self, 'options') and self.options is not None: + if isinstance(self.options, dict): + _dict['options'] = self.options + else: + _dict['options'] = self.options.to_dict() return _dict def _to_dict(self): @@ -12010,76 +16131,133 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsConversationalSearchResponseLength object.""" + """Return a `str` version of this StatelessMessageInput object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, - other: 'SearchSettingsConversationalSearchResponseLength') -> bool: + def __eq__(self, other: 'StatelessMessageInput') -> 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: 'SearchSettingsConversationalSearchResponseLength') -> bool: + def __ne__(self, other: 'StatelessMessageInput') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class OptionEnum(str, Enum): + class MessageTypeEnum(str, Enum): """ - The response length option. It controls the length of the generated response. + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or action skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. """ - CONCISE = 'concise' - MODERATE = 'moderate' - VERBOSE = 'verbose' + TEXT = 'text' + SEARCH = 'search' -class SearchSettingsConversationalSearchSearchConfidence: +class StatelessMessageInputOptions: """ - SearchSettingsConversationalSearchSearchConfidence. + Optional properties that control how the assistant responds. - :param str threshold: (optional) The search confidence threshold. - It controls the tendency for conversational search to produce “I don't know” - answers. + :param bool restart: (optional) Whether to restart dialog processing at the root + of the dialog, regardless of any previously visited nodes. **Note:** This does + not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the initial + message response signals to the client that the operation may be long running. + With synchronous execution the custom extension is executed and returns the + response in a single message turn. **Note:** **async_callout** defaults to true + for API versions earlier than 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message override + the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ def __init__( self, *, - threshold: Optional[str] = None, + restart: Optional[bool] = None, + alternate_intents: Optional[bool] = None, + async_callout: Optional[bool] = None, + spelling: Optional['MessageInputOptionsSpelling'] = None, + debug: Optional[bool] = None, ) -> None: """ - Initialize a SearchSettingsConversationalSearchSearchConfidence object. + Initialize a StatelessMessageInputOptions object. - :param str threshold: (optional) The search confidence threshold. - It controls the tendency for conversational search to produce “I don't - know” answers. + :param bool restart: (optional) Whether to restart dialog processing at the + root of the dialog, regardless of any previously visited nodes. **Note:** + This does not affect `turn_count` or any other context variables. + :param bool alternate_intents: (optional) Whether to return more than one + intent. Set to `true` to return all matching intents. + :param bool async_callout: (optional) Whether custom extension callouts are + executed asynchronously. Asynchronous execution means the response to the + extension callout will be processed on the subsequent message call, the + initial message response signals to the client that the operation may be + long running. With synchronous execution the custom extension is executed + and returns the response in a single message turn. **Note:** + **async_callout** defaults to true for API versions earlier than + 2023-06-15. + :param MessageInputOptionsSpelling spelling: (optional) Spelling correction + options for the message. Any options specified on an individual message + override the settings configured for the skill. + :param bool debug: (optional) Whether to return additional diagnostic + information. Set to `true` to return additional information in the + `output.debug` property. """ - self.threshold = threshold + self.restart = restart + self.alternate_intents = alternate_intents + self.async_callout = async_callout + self.spelling = spelling + self.debug = debug @classmethod - def from_dict( - cls, _dict: Dict - ) -> 'SearchSettingsConversationalSearchSearchConfidence': - """Initialize a SearchSettingsConversationalSearchSearchConfidence object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageInputOptions': + """Initialize a StatelessMessageInputOptions object from a json dictionary.""" args = {} - if (threshold := _dict.get('threshold')) is not None: - args['threshold'] = threshold + if (restart := _dict.get('restart')) is not None: + args['restart'] = restart + if (alternate_intents := _dict.get('alternate_intents')) is not None: + args['alternate_intents'] = alternate_intents + if (async_callout := _dict.get('async_callout')) is not None: + args['async_callout'] = async_callout + if (spelling := _dict.get('spelling')) is not None: + args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) + if (debug := _dict.get('debug')) is not None: + args['debug'] = debug return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsConversationalSearchSearchConfidence object from a json dictionary.""" + """Initialize a StatelessMessageInputOptions 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, 'threshold') and self.threshold is not None: - _dict['threshold'] = self.threshold + if hasattr(self, 'restart') and self.restart is not None: + _dict['restart'] = self.restart + if hasattr(self, + 'alternate_intents') and self.alternate_intents is not None: + _dict['alternate_intents'] = self.alternate_intents + if hasattr(self, 'async_callout') and self.async_callout is not None: + _dict['async_callout'] = self.async_callout + if hasattr(self, 'spelling') and self.spelling is not None: + if isinstance(self.spelling, dict): + _dict['spelling'] = self.spelling + else: + _dict['spelling'] = self.spelling.to_dict() + if hasattr(self, 'debug') and self.debug is not None: + _dict['debug'] = self.debug return _dict def _to_dict(self): @@ -12087,195 +16265,137 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsConversationalSearchSearchConfidence object.""" + """Return a `str` version of this StatelessMessageInputOptions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, other: 'SearchSettingsConversationalSearchSearchConfidence' - ) -> bool: + def __eq__(self, other: 'StatelessMessageInputOptions') -> 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: 'SearchSettingsConversationalSearchSearchConfidence' - ) -> bool: + def __ne__(self, other: 'StatelessMessageInputOptions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ThresholdEnum(str, Enum): - """ - The search confidence threshold. - It controls the tendency for conversational search to produce “I don't know” - answers. - """ - - RARELY = 'rarely' - LESS_OFTEN = 'less_often' - MORE_OFTEN = 'more_often' - MOST_OFTEN = 'most_often' - -class SearchSettingsDiscovery: +class StatelessMessageResponse: """ - Configuration settings for the Watson Discovery service instance used by the search - integration. + A stateless response from the watsonx Assistant service. - :param str instance_id: The ID for the Watson Discovery service instance. - :param str project_id: The ID for the Watson Discovery project. - :param str url: The URL for the Watson Discovery service instance. - :param int max_primary_results: (optional) The maximum number of primary results - to include in the response. - :param int max_total_results: (optional) The maximum total number of primary and - additional results to include in the response. - :param float confidence_threshold: (optional) The minimum confidence threshold - for included results. Any results with a confidence below this threshold will be - discarded. - :param bool highlight: (optional) Whether to include the most relevant passages - of text in the **highlight** property of each result. - :param bool find_answers: (optional) Whether to use the answer finding feature - to emphasize answers within highlighted passages. This property is ignored if - **highlight**=`false`. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. - :param SearchSettingsDiscoveryAuthentication authentication: Authentication - information for the Watson Discovery service. For more information, see the - [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. + :param MessageOutput output: Assistant output to be rendered or processed by the + client. + :param StatelessMessageContext context: Context data for the conversation. You + can use this property to access context variables. The context is not stored by + the assistant; to maintain session state, include the context from the response + in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be rendered + or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes the + input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who is + interacting with the assistant. The client must provide a unique identifier for + each individual end user who accesses the application. For user-based plans, + this user ID is used to identify unique users for billing purposes. This string + cannot contain carriage return, newline, or tab characters. If no value is + specified in the input, **user_id** is automatically set to the value of + **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the global + system context. """ - - def __init__( - self, - instance_id: str, - project_id: str, - url: str, - authentication: 'SearchSettingsDiscoveryAuthentication', - *, - max_primary_results: Optional[int] = None, - max_total_results: Optional[int] = None, - confidence_threshold: Optional[float] = None, - highlight: Optional[bool] = None, - find_answers: Optional[bool] = None, - ) -> None: - """ - Initialize a SearchSettingsDiscovery object. - - :param str instance_id: The ID for the Watson Discovery service instance. - :param str project_id: The ID for the Watson Discovery project. - :param str url: The URL for the Watson Discovery service instance. - :param SearchSettingsDiscoveryAuthentication authentication: Authentication - information for the Watson Discovery service. For more information, see the - [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. - :param int max_primary_results: (optional) The maximum number of primary - results to include in the response. - :param int max_total_results: (optional) The maximum total number of - primary and additional results to include in the response. - :param float confidence_threshold: (optional) The minimum confidence - threshold for included results. Any results with a confidence below this - threshold will be discarded. - :param bool highlight: (optional) Whether to include the most relevant - passages of text in the **highlight** property of each result. - :param bool find_answers: (optional) Whether to use the answer finding - feature to emphasize answers within highlighted passages. This property is - ignored if **highlight**=`false`. - **Notes:** - - Answer finding is available only if the search skill is connected to a - Discovery v2 service instance. - - Answer finding is not supported on IBM Cloud Pak for Data. + + def __init__( + self, + output: 'MessageOutput', + context: 'StatelessMessageContext', + *, + masked_output: Optional['MessageOutput'] = None, + masked_input: Optional['MessageInput'] = None, + user_id: Optional[str] = None, + ) -> None: """ - self.instance_id = instance_id - self.project_id = project_id - self.url = url - self.max_primary_results = max_primary_results - self.max_total_results = max_total_results - self.confidence_threshold = confidence_threshold - self.highlight = highlight - self.find_answers = find_answers - self.authentication = authentication + Initialize a StatelessMessageResponse object. + + :param MessageOutput output: Assistant output to be rendered or processed + by the client. + :param StatelessMessageContext context: Context data for the conversation. + You can use this property to access context variables. The context is not + stored by the assistant; to maintain session state, include the context + from the response in the next message. + :param MessageOutput masked_output: (optional) Assistant output to be + rendered or processed by the client. All private data is masked or removed. + :param MessageInput masked_input: (optional) An input object that includes + the input text. All private data is masked or removed. + :param str user_id: (optional) A string value that identifies the user who + is interacting with the assistant. The client must provide a unique + identifier for each individual end user who accesses the application. For + user-based plans, this user ID is used to identify unique users for billing + purposes. This string cannot contain carriage return, newline, or tab + characters. If no value is specified in the input, **user_id** is + automatically set to the value of **context.global.session_id**. + **Note:** This property is the same as the **user_id** property in the + global system context. + """ + self.output = output + self.context = context + self.masked_output = masked_output + self.masked_input = masked_input + self.user_id = user_id @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscovery': - """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatelessMessageResponse': + """Initialize a StatelessMessageResponse object from a json dictionary.""" args = {} - if (instance_id := _dict.get('instance_id')) is not None: - args['instance_id'] = instance_id - else: - raise ValueError( - 'Required property \'instance_id\' not present in SearchSettingsDiscovery JSON' - ) - if (project_id := _dict.get('project_id')) is not None: - args['project_id'] = project_id - else: - raise ValueError( - 'Required property \'project_id\' not present in SearchSettingsDiscovery JSON' - ) - if (url := _dict.get('url')) is not None: - args['url'] = url + if (output := _dict.get('output')) is not None: + args['output'] = MessageOutput.from_dict(output) else: raise ValueError( - 'Required property \'url\' not present in SearchSettingsDiscovery JSON' + 'Required property \'output\' not present in StatelessMessageResponse JSON' ) - if (max_primary_results := - _dict.get('max_primary_results')) is not None: - args['max_primary_results'] = max_primary_results - if (max_total_results := _dict.get('max_total_results')) is not None: - args['max_total_results'] = max_total_results - if (confidence_threshold := - _dict.get('confidence_threshold')) is not None: - args['confidence_threshold'] = confidence_threshold - if (highlight := _dict.get('highlight')) is not None: - args['highlight'] = highlight - if (find_answers := _dict.get('find_answers')) is not None: - args['find_answers'] = find_answers - if (authentication := _dict.get('authentication')) is not None: - args[ - 'authentication'] = SearchSettingsDiscoveryAuthentication.from_dict( - authentication) + if (context := _dict.get('context')) is not None: + args['context'] = StatelessMessageContext.from_dict(context) else: raise ValueError( - 'Required property \'authentication\' not present in SearchSettingsDiscovery JSON' + 'Required property \'context\' not present in StatelessMessageResponse JSON' ) + if (masked_output := _dict.get('masked_output')) is not None: + args['masked_output'] = MessageOutput.from_dict(masked_output) + if (masked_input := _dict.get('masked_input')) is not None: + args['masked_input'] = MessageInput.from_dict(masked_input) + if (user_id := _dict.get('user_id')) is not None: + args['user_id'] = user_id return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsDiscovery object from a json dictionary.""" + """Initialize a StatelessMessageResponse 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, 'instance_id') and self.instance_id is not None: - _dict['instance_id'] = self.instance_id - if hasattr(self, 'project_id') and self.project_id is not None: - _dict['project_id'] = self.project_id - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr( - self, - 'max_primary_results') and self.max_primary_results is not None: - _dict['max_primary_results'] = self.max_primary_results - if hasattr(self, - 'max_total_results') and self.max_total_results is not None: - _dict['max_total_results'] = self.max_total_results - if hasattr(self, 'confidence_threshold' - ) and self.confidence_threshold is not None: - _dict['confidence_threshold'] = self.confidence_threshold - if hasattr(self, 'highlight') and self.highlight is not None: - _dict['highlight'] = self.highlight - if hasattr(self, 'find_answers') and self.find_answers is not None: - _dict['find_answers'] = self.find_answers - if hasattr(self, 'authentication') and self.authentication is not None: - if isinstance(self.authentication, dict): - _dict['authentication'] = self.authentication + if hasattr(self, 'output') and self.output is not None: + if isinstance(self.output, dict): + _dict['output'] = self.output else: - _dict['authentication'] = self.authentication.to_dict() + _dict['output'] = self.output.to_dict() + if hasattr(self, 'context') and self.context is not None: + if isinstance(self.context, dict): + _dict['context'] = self.context + else: + _dict['context'] = self.context.to_dict() + if hasattr(self, 'masked_output') and self.masked_output is not None: + if isinstance(self.masked_output, dict): + _dict['masked_output'] = self.masked_output + else: + _dict['masked_output'] = self.masked_output.to_dict() + if hasattr(self, 'masked_input') and self.masked_input is not None: + if isinstance(self.masked_input, dict): + _dict['masked_input'] = self.masked_input + else: + _dict['masked_input'] = self.masked_input.to_dict() + if hasattr(self, 'user_id') and self.user_id is not None: + _dict['user_id'] = self.user_id return _dict def _to_dict(self): @@ -12283,74 +16403,78 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsDiscovery object.""" + """Return a `str` version of this StatelessMessageResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsDiscovery') -> bool: + def __eq__(self, other: 'StatelessMessageResponse') -> 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: 'SearchSettingsDiscovery') -> bool: + def __ne__(self, other: 'StatelessMessageResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsDiscoveryAuthentication: +class StatelessMessageStreamResponse: """ - Authentication information for the Watson Discovery service. For more information, see - the [Watson Discovery - documentation](https://cloud.ibm.com/apidocs/discovery-data#authentication). - **Note:** You must specify either **basic** or **bearer**, but not both. + A stateless streamed response form the watsonx Assistant service. - :param str basic: (optional) The HTTP basic authentication credentials for - Watson Discovery. Specify your Watson Discovery API key in the format - `apikey:{apikey}`. - :param str bearer: (optional) The authentication bearer token for Watson - Discovery. + """ + + def __init__(self,) -> None: + """ + Initialize a StatelessMessageStreamResponse object. + + """ + msg = "Cannot instantiate base class. Instead, instantiate one of the defined subclasses: {0}".format( + ", ".join([ + 'StatelessMessageStreamResponseMessageStreamPartialItem', + 'StatelessMessageStreamResponseMessageStreamCompleteItem', + 'StatelessMessageStreamResponseStatelessMessageStreamFinalResponse' + ])) + raise Exception(msg) + + +class StatusError: + """ + An object describing an error that occurred during processing of an asynchronous + operation. + + :param str message: (optional) The text of the error message. """ def __init__( self, *, - basic: Optional[str] = None, - bearer: Optional[str] = None, + message: Optional[str] = None, ) -> None: """ - Initialize a SearchSettingsDiscoveryAuthentication object. + Initialize a StatusError object. - :param str basic: (optional) The HTTP basic authentication credentials for - Watson Discovery. Specify your Watson Discovery API key in the format - `apikey:{apikey}`. - :param str bearer: (optional) The authentication bearer token for Watson - Discovery. + :param str message: (optional) The text of the error message. """ - self.basic = basic - self.bearer = bearer + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsDiscoveryAuthentication': - """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'StatusError': + """Initialize a StatusError object from a json dictionary.""" args = {} - if (basic := _dict.get('basic')) is not None: - args['basic'] = basic - if (bearer := _dict.get('bearer')) is not None: - args['bearer'] = bearer + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsDiscoveryAuthentication object from a json dictionary.""" + """Initialize a StatusError 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, 'basic') and self.basic is not None: - _dict['basic'] = self.basic - if hasattr(self, 'bearer') and self.bearer is not None: - _dict['bearer'] = self.bearer + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -12358,158 +16482,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsDiscoveryAuthentication object.""" + """Return a `str` version of this StatusError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsDiscoveryAuthentication') -> bool: + def __eq__(self, other: 'StatusError') -> 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: 'SearchSettingsDiscoveryAuthentication') -> bool: + def __ne__(self, other: 'StatusError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SearchSettingsElasticSearch: +class TurnEventActionSource: """ - Configuration settings for the Elasticsearch service used by the search integration. - You can provide either basic auth or apiKey auth. + TurnEventActionSource. - :param str url: The URL for the Elasticsearch service. - :param str port: The port number for the Elasticsearch service URL. - **Note:** It can be omitted if a port number is appended to the URL. - :param str username: (optional) The username of the basic authentication method. - :param str password: (optional) The password of the basic authentication method. - The credentials are not returned due to security reasons. - :param str index: The Elasticsearch index to use for the search integration. - :param List[object] filter: (optional) An array of filters that can be applied - to the search results via the `$FILTER` variable in the `query_body`.For more - information, see [Elasticsearch filter - documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/filter-search-results.html). - :param dict query_body: (optional) The Elasticsearch query object. For more - information, see [Elasticsearch search API - documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html). - :param str managed_index: (optional) The Elasticsearch index for uploading - documents. It is created automatically when the upload document option is - selected from the user interface. - :param str apikey: (optional) The API key of the apiKey authentication method. - Use either basic auth or apiKey auth. The credentials are not returned due to - security reasons. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing of + the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog node. """ def __init__( self, - url: str, - port: str, - index: str, *, - username: Optional[str] = None, - password: Optional[str] = None, - filter: Optional[List[object]] = None, - query_body: Optional[dict] = None, - managed_index: Optional[str] = None, - apikey: Optional[str] = None, + type: Optional[str] = None, + action: Optional[str] = None, + action_title: Optional[str] = None, + condition: Optional[str] = None, ) -> None: """ - Initialize a SearchSettingsElasticSearch object. + Initialize a TurnEventActionSource object. - :param str url: The URL for the Elasticsearch service. - :param str port: The port number for the Elasticsearch service URL. - **Note:** It can be omitted if a port number is appended to the URL. - :param str index: The Elasticsearch index to use for the search - integration. - :param str username: (optional) The username of the basic authentication - method. - :param str password: (optional) The password of the basic authentication - method. The credentials are not returned due to security reasons. - :param List[object] filter: (optional) An array of filters that can be - applied to the search results via the `$FILTER` variable in the - `query_body`.For more information, see [Elasticsearch filter - documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/filter-search-results.html). - :param dict query_body: (optional) The Elasticsearch query object. For more - information, see [Elasticsearch search API - documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html). - :param str managed_index: (optional) The Elasticsearch index for uploading - documents. It is created automatically when the upload document option is - selected from the user interface. - :param str apikey: (optional) The API key of the apiKey authentication - method. Use either basic auth or apiKey auth. The credentials are not - returned due to security reasons. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing + of the message. + :param str action_title: (optional) The title of the action. + :param str condition: (optional) The condition that triggered the dialog + node. """ - self.url = url - self.port = port - self.username = username - self.password = password - self.index = index - self.filter = filter - self.query_body = query_body - self.managed_index = managed_index - self.apikey = apikey + self.type = type + self.action = action + self.action_title = action_title + self.condition = condition @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsElasticSearch': - """Initialize a SearchSettingsElasticSearch object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventActionSource': + """Initialize a TurnEventActionSource object from a json dictionary.""" args = {} - if (url := _dict.get('url')) is not None: - args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in SearchSettingsElasticSearch JSON' - ) - if (port := _dict.get('port')) is not None: - args['port'] = port - else: - raise ValueError( - 'Required property \'port\' not present in SearchSettingsElasticSearch JSON' - ) - if (username := _dict.get('username')) is not None: - args['username'] = username - if (password := _dict.get('password')) is not None: - args['password'] = password - if (index := _dict.get('index')) is not None: - args['index'] = index - else: - raise ValueError( - 'Required property \'index\' not present in SearchSettingsElasticSearch JSON' - ) - if (filter := _dict.get('filter')) is not None: - args['filter'] = filter - if (query_body := _dict.get('query_body')) is not None: - args['query_body'] = query_body - if (managed_index := _dict.get('managed_index')) is not None: - args['managed_index'] = managed_index - if (apikey := _dict.get('apikey')) is not None: - args['apikey'] = apikey + if (type := _dict.get('type')) is not None: + args['type'] = type + if (action := _dict.get('action')) is not None: + args['action'] = action + if (action_title := _dict.get('action_title')) is not None: + args['action_title'] = action_title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsElasticSearch object from a json dictionary.""" + """Initialize a TurnEventActionSource 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, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'port') and self.port is not None: - _dict['port'] = self.port - if hasattr(self, 'username') and self.username is not None: - _dict['username'] = self.username - if hasattr(self, 'password') and self.password is not None: - _dict['password'] = self.password - if hasattr(self, 'index') and self.index is not None: - _dict['index'] = self.index - if hasattr(self, 'filter') and self.filter is not None: - _dict['filter'] = self.filter - if hasattr(self, 'query_body') and self.query_body is not None: - _dict['query_body'] = self.query_body - if hasattr(self, 'managed_index') and self.managed_index is not None: - _dict['managed_index'] = self.managed_index - if hasattr(self, 'apikey') and self.apikey is not None: - _dict['apikey'] = self.apikey + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'action_title') and self.action_title is not None: + _dict['action_title'] = self.action_title + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition return _dict def _to_dict(self): @@ -12517,90 +16567,112 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsElasticSearch object.""" + """Return a `str` version of this TurnEventActionSource object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsElasticSearch') -> bool: + def __eq__(self, other: 'TurnEventActionSource') -> 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: 'SearchSettingsElasticSearch') -> bool: + def __ne__(self, other: 'TurnEventActionSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of turn event. + """ + + ACTION = 'action' -class SearchSettingsMessages: + +class TurnEventCalloutCallout: """ - The messages included with responses from the search integration. + TurnEventCalloutCallout. - :param str success: The message to include in the response to a successful - query. - :param str error: The message to include in the response when the query - encounters an error. - :param str no_result: The message to include in the response when there is no - result from the query. + :param str type: (optional) The type of callout. Currently, the only supported + value is `integration_interaction` (for calls to extensions). + :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. + :param TurnEventCalloutCalloutRequest request: (optional) The request object + executed to the external server specified by the extension. + :param TurnEventCalloutCalloutResponse response: (optional) The response object + received by the external server made by the extension. """ def __init__( self, - success: str, - error: str, - no_result: str, + *, + type: Optional[str] = None, + internal: Optional[dict] = None, + result_variable: Optional[str] = None, + request: Optional['TurnEventCalloutCalloutRequest'] = None, + response: Optional['TurnEventCalloutCalloutResponse'] = None, ) -> None: """ - Initialize a SearchSettingsMessages object. + Initialize a TurnEventCalloutCallout object. - :param str success: The message to include in the response to a successful - query. - :param str error: The message to include in the response when the query - encounters an error. - :param str no_result: The message to include in the response when there is - no result from the query. + :param str type: (optional) The type of callout. Currently, the only + supported value is `integration_interaction` (for calls to extensions). + :param dict internal: (optional) For internal use only. + :param str result_variable: (optional) The name of the variable where the + callout result is stored. + :param TurnEventCalloutCalloutRequest request: (optional) The request + object executed to the external server specified by the extension. + :param TurnEventCalloutCalloutResponse response: (optional) The response + object received by the external server made by the extension. """ - self.success = success - self.error = error - self.no_result = no_result + self.type = type + self.internal = internal + self.result_variable = result_variable + self.request = request + self.response = response @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsMessages': - """Initialize a SearchSettingsMessages object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': + """Initialize a TurnEventCalloutCallout object from a json dictionary.""" args = {} - if (success := _dict.get('success')) is not None: - args['success'] = success - else: - raise ValueError( - 'Required property \'success\' not present in SearchSettingsMessages JSON' - ) - if (error := _dict.get('error')) is not None: - args['error'] = error - else: - raise ValueError( - 'Required property \'error\' not present in SearchSettingsMessages JSON' - ) - if (no_result := _dict.get('no_result')) is not None: - args['no_result'] = no_result - else: - raise ValueError( - 'Required property \'no_result\' not present in SearchSettingsMessages JSON' - ) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (internal := _dict.get('internal')) is not None: + args['internal'] = internal + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable + if (request := _dict.get('request')) is not None: + args['request'] = TurnEventCalloutCalloutRequest.from_dict(request) + if (response := _dict.get('response')) is not None: + args['response'] = TurnEventCalloutCalloutResponse.from_dict( + response) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsMessages object from a json dictionary.""" + """Initialize a TurnEventCalloutCallout 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, 'success') and self.success is not None: - _dict['success'] = self.success - if hasattr(self, 'error') and self.error is not None: - _dict['error'] = self.error - if hasattr(self, 'no_result') and self.no_result is not None: - _dict['no_result'] = self.no_result + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'internal') and self.internal is not None: + _dict['internal'] = self.internal + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable + if hasattr(self, 'request') and self.request is not None: + if isinstance(self.request, dict): + _dict['request'] = self.request + else: + _dict['request'] = self.request.to_dict() + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() return _dict def _to_dict(self): @@ -12608,91 +16680,112 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsMessages object.""" + """Return a `str` version of this TurnEventCalloutCallout object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsMessages') -> bool: + def __eq__(self, other: 'TurnEventCalloutCallout') -> 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: 'SearchSettingsMessages') -> bool: + def __ne__(self, other: 'TurnEventCalloutCallout') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of callout. Currently, the only supported value is + `integration_interaction` (for calls to extensions). + """ + + INTEGRATION_INTERACTION = 'integration_interaction' -class SearchSettingsSchemaMapping: - """ - The mapping between fields in the Watson Discovery collection and properties in the - search response. - :param str url: The field in the collection to map to the **url** property of - the response. - :param str body: The field in the collection to map to the **body** property in - the response. - :param str title: The field in the collection to map to the **title** property - for the schema. +class TurnEventCalloutCalloutRequest: + """ + TurnEventCalloutCalloutRequest. + + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to the URL + of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server or an + object. In cases like timeouts or connections errors, it will contain details of + why the callout to the external server failed. """ def __init__( self, - url: str, - body: str, - title: str, + *, + method: Optional[str] = None, + url: Optional[str] = None, + path: Optional[str] = None, + query_parameters: Optional[str] = None, + headers_: Optional[dict] = None, + body: Optional[dict] = None, ) -> None: """ - Initialize a SearchSettingsSchemaMapping object. + Initialize a TurnEventCalloutCalloutRequest object. - :param str url: The field in the collection to map to the **url** property - of the response. - :param str body: The field in the collection to map to the **body** - property in the response. - :param str title: The field in the collection to map to the **title** - property for the schema. + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to + the URL of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server + or an object. In cases like timeouts or connections errors, it will contain + details of why the callout to the external server failed. """ + self.method = method self.url = url + self.path = path + self.query_parameters = query_parameters + self.headers_ = headers_ self.body = body - self.title = title @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsSchemaMapping': - """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCalloutRequest': + """Initialize a TurnEventCalloutCalloutRequest object from a json dictionary.""" args = {} + if (method := _dict.get('method')) is not None: + args['method'] = method if (url := _dict.get('url')) is not None: args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in SearchSettingsSchemaMapping JSON' - ) + if (path := _dict.get('path')) is not None: + args['path'] = path + if (query_parameters := _dict.get('query_parameters')) is not None: + args['query_parameters'] = query_parameters + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = headers_ if (body := _dict.get('body')) is not None: args['body'] = body - else: - raise ValueError( - 'Required property \'body\' not present in SearchSettingsSchemaMapping JSON' - ) - if (title := _dict.get('title')) is not None: - args['title'] = title - else: - raise ValueError( - 'Required property \'title\' not present in SearchSettingsSchemaMapping JSON' - ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsSchemaMapping object from a json dictionary.""" + """Initialize a TurnEventCalloutCalloutRequest 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, 'method') and self.method is not None: + _dict['method'] = self.method if hasattr(self, 'url') and self.url is not None: _dict['url'] = self.url + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path + if hasattr(self, + 'query_parameters') and self.query_parameters is not None: + _dict['query_parameters'] = self.query_parameters + if hasattr(self, 'headers_') and self.headers_ is not None: + _dict['headers'] = self.headers_ if hasattr(self, 'body') and self.body is not None: _dict['body'] = self.body - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title return _dict def _to_dict(self): @@ -12700,136 +16793,88 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsSchemaMapping object.""" + """Return a `str` version of this TurnEventCalloutCalloutRequest object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsSchemaMapping') -> bool: + def __eq__(self, other: 'TurnEventCalloutCalloutRequest') -> 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: 'SearchSettingsSchemaMapping') -> bool: + def __ne__(self, other: 'TurnEventCalloutCalloutRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class MethodEnum(str, Enum): + """ + The REST method of the request. + """ + + GET = 'get' + POST = 'post' + PUT = 'put' + DELETE = 'delete' + PATCH = 'patch' + -class SearchSettingsServerSideSearch: +class TurnEventCalloutCalloutResponse: """ - Configuration settings for the server-side search service used by the search - integration. You can provide either basic auth, apiKey auth or none. + TurnEventCalloutCalloutResponse. - :param str url: The URL of the server-side search service. - :param str port: (optional) The port number of the server-side search service. - :param str username: (optional) The username of the basic authentication method. - :param str password: (optional) The password of the basic authentication method. - The credentials are not returned due to security reasons. - :param str filter: (optional) The filter string that is applied to the search - results. - :param dict metadata: (optional) The metadata object. - :param str apikey: (optional) The API key of the apiKey authentication method. - The credentails are not returned due to security reasons. - :param bool no_auth: (optional) To clear previous auth, specify `no_auth = - true`. - :param str auth_type: (optional) The authorization type that is used. + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. + :param dict last_event: (optional) The response from the last chunk received + from the response stream. """ def __init__( self, - url: str, *, - port: Optional[str] = None, - username: Optional[str] = None, - password: Optional[str] = None, - filter: Optional[str] = None, - metadata: Optional[dict] = None, - apikey: Optional[str] = None, - no_auth: Optional[bool] = None, - auth_type: Optional[str] = None, + body: Optional[str] = None, + status_code: Optional[int] = None, + last_event: Optional[dict] = None, ) -> None: """ - Initialize a SearchSettingsServerSideSearch object. + Initialize a TurnEventCalloutCalloutResponse object. - :param str url: The URL of the server-side search service. - :param str port: (optional) The port number of the server-side search - service. - :param str username: (optional) The username of the basic authentication - method. - :param str password: (optional) The password of the basic authentication - method. The credentials are not returned due to security reasons. - :param str filter: (optional) The filter string that is applied to the - search results. - :param dict metadata: (optional) The metadata object. - :param str apikey: (optional) The API key of the apiKey authentication - method. The credentails are not returned due to security reasons. - :param bool no_auth: (optional) To clear previous auth, specify `no_auth = - true`. - :param str auth_type: (optional) The authorization type that is used. + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. + :param dict last_event: (optional) The response from the last chunk + received from the response stream. """ - self.url = url - self.port = port - self.username = username - self.password = password - self.filter = filter - self.metadata = metadata - self.apikey = apikey - self.no_auth = no_auth - self.auth_type = auth_type + self.body = body + self.status_code = status_code + self.last_event = last_event @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSettingsServerSideSearch': - """Initialize a SearchSettingsServerSideSearch object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCalloutResponse': + """Initialize a TurnEventCalloutCalloutResponse object from a json dictionary.""" args = {} - if (url := _dict.get('url')) is not None: - args['url'] = url - else: - raise ValueError( - 'Required property \'url\' not present in SearchSettingsServerSideSearch JSON' - ) - if (port := _dict.get('port')) is not None: - args['port'] = port - if (username := _dict.get('username')) is not None: - args['username'] = username - if (password := _dict.get('password')) is not None: - args['password'] = password - if (filter := _dict.get('filter')) is not None: - args['filter'] = filter - if (metadata := _dict.get('metadata')) is not None: - args['metadata'] = metadata - if (apikey := _dict.get('apikey')) is not None: - args['apikey'] = apikey - if (no_auth := _dict.get('no_auth')) is not None: - args['no_auth'] = no_auth - if (auth_type := _dict.get('auth_type')) is not None: - args['auth_type'] = auth_type + if (body := _dict.get('body')) is not None: + args['body'] = body + if (status_code := _dict.get('status_code')) is not None: + args['status_code'] = status_code + if (last_event := _dict.get('last_event')) is not None: + args['last_event'] = last_event return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSettingsServerSideSearch object from a json dictionary.""" + """Initialize a TurnEventCalloutCalloutResponse 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, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'port') and self.port is not None: - _dict['port'] = self.port - if hasattr(self, 'username') and self.username is not None: - _dict['username'] = self.username - if hasattr(self, 'password') and self.password is not None: - _dict['password'] = self.password - if hasattr(self, 'filter') and self.filter is not None: - _dict['filter'] = self.filter - if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata - if hasattr(self, 'apikey') and self.apikey is not None: - _dict['apikey'] = self.apikey - if hasattr(self, 'no_auth') and self.no_auth is not None: - _dict['no_auth'] = self.no_auth - if hasattr(self, 'auth_type') and self.auth_type is not None: - _dict['auth_type'] = self.auth_type + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'status_code') and self.status_code is not None: + _dict['status_code'] = self.status_code + if hasattr(self, 'last_event') and self.last_event is not None: + _dict['last_event'] = self.last_event return _dict def _to_dict(self): @@ -12837,82 +16882,57 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSettingsServerSideSearch object.""" + """Return a `str` version of this TurnEventCalloutCalloutResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSettingsServerSideSearch') -> bool: + def __eq__(self, other: 'TurnEventCalloutCalloutResponse') -> 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: 'SearchSettingsServerSideSearch') -> bool: + def __ne__(self, other: 'TurnEventCalloutCalloutResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class AuthTypeEnum(str, Enum): - """ - The authorization type that is used. - """ - - BASIC = 'basic' - APIKEY = 'apikey' - NONE = 'none' - -class SearchSkillWarning: +class TurnEventCalloutError: """ - A warning describing an error in the search skill configuration. + TurnEventCalloutError. - :param str code: (optional) The error code. - :param str path: (optional) The location of the error in the search skill - configuration object. - :param str message: (optional) The error message. + :param str message: (optional) Any error message returned by a failed call to an + external service. """ def __init__( self, *, - code: Optional[str] = None, - path: Optional[str] = None, message: Optional[str] = None, ) -> None: """ - Initialize a SearchSkillWarning object. + Initialize a TurnEventCalloutError object. - :param str code: (optional) The error code. - :param str path: (optional) The location of the error in the search skill - configuration object. - :param str message: (optional) The error message. + :param str message: (optional) Any error message returned by a failed call + to an external service. """ - self.code = code - self.path = path self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'SearchSkillWarning': - """Initialize a SearchSkillWarning object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutError': + """Initialize a TurnEventCalloutError object from a json dictionary.""" args = {} - if (code := _dict.get('code')) is not None: - args['code'] = code - if (path := _dict.get('path')) is not None: - args['path'] = path if (message := _dict.get('message')) is not None: args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SearchSkillWarning object from a json dictionary.""" + """Initialize a TurnEventCalloutError 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, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path if hasattr(self, 'message') and self.message is not None: _dict['message'] = self.message return _dict @@ -12922,60 +16942,105 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SearchSkillWarning object.""" + """Return a `str` version of this TurnEventCalloutError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SearchSkillWarning') -> bool: + def __eq__(self, other: 'TurnEventCalloutError') -> 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: 'SearchSkillWarning') -> bool: + def __ne__(self, other: 'TurnEventCalloutError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class SessionResponse: +class TurnEventGenerativeAICalledCallout: """ - SessionResponse. + TurnEventGenerativeAICalledCallout. - :param str session_id: The session ID. + :param bool search_called: (optional) Whether the document search engine was + called. + :param bool llm_called: (optional) Whether watsonx.ai was called during answer + generation. + :param TurnEventGenerativeAICalledCalloutSearch search: (optional) + :param TurnEventGenerativeAICalledCalloutLlm llm: (optional) + :param str idk_reason_code: (optional) Indicates why a conversational search + response resolved to an idk response. This field will only be available when the + conversational search response is an idk response. """ def __init__( self, - session_id: str, + *, + search_called: Optional[bool] = None, + llm_called: Optional[bool] = None, + search: Optional['TurnEventGenerativeAICalledCalloutSearch'] = None, + llm: Optional['TurnEventGenerativeAICalledCalloutLlm'] = None, + idk_reason_code: Optional[str] = None, ) -> None: """ - Initialize a SessionResponse object. + Initialize a TurnEventGenerativeAICalledCallout object. - :param str session_id: The session ID. + :param bool search_called: (optional) Whether the document search engine + was called. + :param bool llm_called: (optional) Whether watsonx.ai was called during + answer generation. + :param TurnEventGenerativeAICalledCalloutSearch search: (optional) + :param TurnEventGenerativeAICalledCalloutLlm llm: (optional) + :param str idk_reason_code: (optional) Indicates why a conversational + search response resolved to an idk response. This field will only be + available when the conversational search response is an idk response. """ - self.session_id = session_id + self.search_called = search_called + self.llm_called = llm_called + self.search = search + self.llm = llm + self.idk_reason_code = idk_reason_code @classmethod - def from_dict(cls, _dict: Dict) -> 'SessionResponse': - """Initialize a SessionResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventGenerativeAICalledCallout': + """Initialize a TurnEventGenerativeAICalledCallout object from a json dictionary.""" args = {} - if (session_id := _dict.get('session_id')) is not None: - args['session_id'] = session_id - else: - raise ValueError( - 'Required property \'session_id\' not present in SessionResponse JSON' - ) + if (search_called := _dict.get('search_called')) is not None: + args['search_called'] = search_called + if (llm_called := _dict.get('llm_called')) is not None: + args['llm_called'] = llm_called + if (search := _dict.get('search')) is not None: + args['search'] = TurnEventGenerativeAICalledCalloutSearch.from_dict( + search) + if (llm := _dict.get('llm')) is not None: + args['llm'] = TurnEventGenerativeAICalledCalloutLlm.from_dict(llm) + if (idk_reason_code := _dict.get('idk_reason_code')) is not None: + args['idk_reason_code'] = idk_reason_code return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SessionResponse object from a json dictionary.""" + """Initialize a TurnEventGenerativeAICalledCallout 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, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, 'search_called') and self.search_called is not None: + _dict['search_called'] = self.search_called + if hasattr(self, 'llm_called') and self.llm_called is not None: + _dict['llm_called'] = self.llm_called + if hasattr(self, 'search') and self.search is not None: + if isinstance(self.search, dict): + _dict['search'] = self.search + else: + _dict['search'] = self.search.to_dict() + if hasattr(self, 'llm') and self.llm is not None: + if isinstance(self.llm, dict): + _dict['llm'] = self.llm + else: + _dict['llm'] = self.llm.to_dict() + if hasattr(self, + 'idk_reason_code') and self.idk_reason_code is not None: + _dict['idk_reason_code'] = self.idk_reason_code return _dict def _to_dict(self): @@ -12983,239 +17048,146 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SessionResponse object.""" + """Return a `str` version of this TurnEventGenerativeAICalledCallout object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SessionResponse') -> bool: + def __eq__(self, other: 'TurnEventGenerativeAICalledCallout') -> 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: 'SessionResponse') -> bool: + def __ne__(self, other: 'TurnEventGenerativeAICalledCallout') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Skill: +class TurnEventGenerativeAICalledCalloutLlm: """ - Skill. + TurnEventGenerativeAICalledCalloutLlm. - :param str name: (optional) The name of the skill. This string cannot contain - carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This string - cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param str skill_id: (optional) The skill ID of the skill. - :param str status: (optional) The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param dict dialog_settings: (optional) For internal use only. - :param str assistant_id: (optional) The unique identifier of the assistant the - skill is associated with. - :param str workspace_id: (optional) The unique identifier of the workspace that - contains the skill content. Included only for action and dialog skills. - :param str environment_id: (optional) The unique identifier of the environment - where the skill is defined. For action and dialog skills, this is always the - draft environment. - :param bool valid: (optional) Whether the skill is structurally valid. - :param str next_snapshot_version: (optional) The name that will be given to the - next snapshot that is created for the skill. A snapshot of each versionable - skill is saved for each new release of an assistant. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and - are not included in **Export skills** responses. - :param List[SearchSkillWarning] warnings: (optional) An array of warnings - describing errors with the search skill configuration. Included only for search - skills. - :param str language: The language of the skill. - :param str type: The type of skill. + :param str type: (optional) The name of the LLM engine called by the system. + :param str model_id: (optional) The LLM model used to generate the response. + :param str model_class_id: (optional) The watsonx.ai class ID that was used + during the answer generation request to the LLM. This is only included when a + request to the LLM has been made by the system. + :param int generated_token_count: (optional) The number of tokens that were + generated in the response by the LLM. This is only included when a request to + the LLM was successful and a response was generated. + :param int input_token_count: (optional) The number of tokens that were sent to + the LLM during answer generation. This is only included when a request to the + LLM has been made by the system. + :param bool success: (optional) Whether the answer generation request to the LLM + was successful. + :param TurnEventGenerativeAICalledCalloutLlmResponse response: (optional) + :param List[SearchResults] request: (optional) n array of objects containing the + search results. """ - - def __init__( - self, - language: str, - type: str, - *, - name: Optional[str] = None, - description: Optional[str] = None, - workspace: Optional[dict] = None, - skill_id: Optional[str] = None, - status: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, - status_description: Optional[str] = None, - dialog_settings: Optional[dict] = None, - assistant_id: Optional[str] = None, - workspace_id: Optional[str] = None, - environment_id: Optional[str] = None, - valid: Optional[bool] = None, - next_snapshot_version: Optional[str] = None, - search_settings: Optional['SearchSettings'] = None, - warnings: Optional[List['SearchSkillWarning']] = None, - ) -> None: - """ - Initialize a Skill object. - - :param str language: The language of the skill. - :param str type: The type of skill. - :param str name: (optional) The name of the skill. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This - string cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param dict dialog_settings: (optional) For internal use only. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, - and are not included in **Export skills** responses. - """ - self.name = name - self.description = description - self.workspace = workspace - self.skill_id = skill_id - self.status = status - self.status_errors = status_errors - self.status_description = status_description - self.dialog_settings = dialog_settings - self.assistant_id = assistant_id - self.workspace_id = workspace_id - self.environment_id = environment_id - self.valid = valid - self.next_snapshot_version = next_snapshot_version - self.search_settings = search_settings - self.warnings = warnings - self.language = language - self.type = type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Skill': - """Initialize a Skill object from a json dictionary.""" - args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (workspace := _dict.get('workspace')) is not None: - args['workspace'] = workspace - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (dialog_settings := _dict.get('dialog_settings')) is not None: - args['dialog_settings'] = dialog_settings - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (workspace_id := _dict.get('workspace_id')) is not None: - args['workspace_id'] = workspace_id - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (valid := _dict.get('valid')) is not None: - args['valid'] = valid - if (next_snapshot_version := - _dict.get('next_snapshot_version')) is not None: - args['next_snapshot_version'] = next_snapshot_version - if (search_settings := _dict.get('search_settings')) is not None: - args['search_settings'] = SearchSettings.from_dict(search_settings) - if (warnings := _dict.get('warnings')) is not None: - args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in warnings - ] - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in Skill JSON') - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in Skill JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Skill 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'workspace') and self.workspace is not None: - _dict['workspace'] = self.workspace - if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: - _dict['skill_id'] = getattr(self, 'skill_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, - 'dialog_settings') and self.dialog_settings is not None: - _dict['dialog_settings'] = self.dialog_settings - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'workspace_id') and getattr( - self, 'workspace_id') is not None: - _dict['workspace_id'] = getattr(self, 'workspace_id') - if hasattr(self, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'valid') and getattr(self, 'valid') is not None: - _dict['valid'] = getattr(self, 'valid') - if hasattr(self, 'next_snapshot_version') and getattr( - self, 'next_snapshot_version') is not None: - _dict['next_snapshot_version'] = getattr(self, - 'next_snapshot_version') + + def __init__( + self, + *, + type: Optional[str] = None, + model_id: Optional[str] = None, + model_class_id: Optional[str] = None, + generated_token_count: Optional[int] = None, + input_token_count: Optional[int] = None, + success: Optional[bool] = None, + response: Optional[ + 'TurnEventGenerativeAICalledCalloutLlmResponse'] = None, + request: Optional[List['SearchResults']] = None, + ) -> None: + """ + Initialize a TurnEventGenerativeAICalledCalloutLlm object. + + :param str type: (optional) The name of the LLM engine called by the + system. + :param str model_id: (optional) The LLM model used to generate the + response. + :param str model_class_id: (optional) The watsonx.ai class ID that was used + during the answer generation request to the LLM. This is only included when + a request to the LLM has been made by the system. + :param int generated_token_count: (optional) The number of tokens that were + generated in the response by the LLM. This is only included when a request + to the LLM was successful and a response was generated. + :param int input_token_count: (optional) The number of tokens that were + sent to the LLM during answer generation. This is only included when a + request to the LLM has been made by the system. + :param bool success: (optional) Whether the answer generation request to + the LLM was successful. + :param TurnEventGenerativeAICalledCalloutLlmResponse response: (optional) + :param List[SearchResults] request: (optional) n array of objects + containing the search results. + """ + self.type = type + self.model_id = model_id + self.model_class_id = model_class_id + self.generated_token_count = generated_token_count + self.input_token_count = input_token_count + self.success = success + self.response = response + self.request = request + + @classmethod + def from_dict(cls, _dict: Dict) -> 'TurnEventGenerativeAICalledCalloutLlm': + """Initialize a TurnEventGenerativeAICalledCalloutLlm object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + if (model_id := _dict.get('model_id')) is not None: + args['model_id'] = model_id + if (model_class_id := _dict.get('model_class_id')) is not None: + args['model_class_id'] = model_class_id + if (generated_token_count := + _dict.get('generated_token_count')) is not None: + args['generated_token_count'] = generated_token_count + if (input_token_count := _dict.get('input_token_count')) is not None: + args['input_token_count'] = input_token_count + if (success := _dict.get('success')) is not None: + args['success'] = success + if (response := _dict.get('response')) is not None: + args[ + 'response'] = TurnEventGenerativeAICalledCalloutLlmResponse.from_dict( + response) + if (request := _dict.get('request')) is not None: + args['request'] = [SearchResults.from_dict(v) for v in request] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventGenerativeAICalledCalloutLlm 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 + if hasattr(self, 'model_id') and self.model_id is not None: + _dict['model_id'] = self.model_id + if hasattr(self, 'model_class_id') and self.model_class_id is not None: + _dict['model_class_id'] = self.model_class_id + if hasattr(self, 'generated_token_count' + ) and self.generated_token_count is not None: + _dict['generated_token_count'] = self.generated_token_count if hasattr(self, - 'search_settings') and self.search_settings is not None: - if isinstance(self.search_settings, dict): - _dict['search_settings'] = self.search_settings + 'input_token_count') and self.input_token_count is not None: + _dict['input_token_count'] = self.input_token_count + if hasattr(self, 'success') and self.success is not None: + _dict['success'] = self.success + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response else: - _dict['search_settings'] = self.search_settings.to_dict() - if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: - warnings_list = [] - for v in getattr(self, 'warnings'): + _dict['response'] = self.response.to_dict() + if hasattr(self, 'request') and self.request is not None: + request_list = [] + for v in self.request: if isinstance(v, dict): - warnings_list.append(v) + request_list.append(v) else: - warnings_list.append(v.to_dict()) - _dict['warnings'] = warnings_list - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type + request_list.append(v.to_dict()) + _dict['request'] = request_list return _dict def _to_dict(self): @@ -13223,267 +17195,193 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Skill object.""" + """Return a `str` version of this TurnEventGenerativeAICalledCalloutLlm object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Skill') -> bool: + def __eq__(self, other: 'TurnEventGenerativeAICalledCalloutLlm') -> 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: 'Skill') -> bool: + def __ne__(self, other: 'TurnEventGenerativeAICalledCalloutLlm') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - """ - AVAILABLE = 'Available' - FAILED = 'Failed' - NON_EXISTENT = 'Non Existent' - PROCESSING = 'Processing' - TRAINING = 'Training' - UNAVAILABLE = 'Unavailable' +class TurnEventGenerativeAICalledCalloutLlmResponse: + """ + - class TypeEnum(str, Enum): + :param str text: (optional) The LLM response that is returned. + :param str response_type: (optional) The type of response that is returned. + :param bool is_idk_response: (optional) Whether the response is an idk response. + """ + + def __init__( + self, + *, + text: Optional[str] = None, + response_type: Optional[str] = None, + is_idk_response: Optional[bool] = None, + ) -> None: """ - The type of skill. + Initialize a TurnEventGenerativeAICalledCalloutLlmResponse object. + + :param str text: (optional) The LLM response that is returned. + :param str response_type: (optional) The type of response that is returned. + :param bool is_idk_response: (optional) Whether the response is an idk + response. """ + self.text = text + self.response_type = response_type + self.is_idk_response = is_idk_response - ACTION = 'action' - DIALOG = 'dialog' - SEARCH = 'search' + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'TurnEventGenerativeAICalledCalloutLlmResponse': + """Initialize a TurnEventGenerativeAICalledCalloutLlmResponse object from a json dictionary.""" + args = {} + if (text := _dict.get('text')) is not None: + args['text'] = text + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type + if (is_idk_response := _dict.get('is_idk_response')) is not None: + args['is_idk_response'] = is_idk_response + return cls(**args) + @classmethod + def _from_dict(cls, _dict): + """Initialize a TurnEventGenerativeAICalledCalloutLlmResponse object from a json dictionary.""" + return cls.from_dict(_dict) -class SkillImport: + def to_dict(self) -> Dict: + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, + 'is_idk_response') and self.is_idk_response is not None: + _dict['is_idk_response'] = self.is_idk_response + 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 TurnEventGenerativeAICalledCalloutLlmResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'TurnEventGenerativeAICalledCalloutLlmResponse') -> 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: 'TurnEventGenerativeAICalledCalloutLlmResponse') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class TurnEventGenerativeAICalledCalloutRequest: """ - SkillImport. + TurnEventGenerativeAICalledCalloutRequest. - :param str name: (optional) The name of the skill. This string cannot contain - carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This string - cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param str skill_id: (optional) The skill ID of the skill. - :param str status: (optional) The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param dict dialog_settings: (optional) For internal use only. - :param str assistant_id: (optional) The unique identifier of the assistant the - skill is associated with. - :param str workspace_id: (optional) The unique identifier of the workspace that - contains the skill content. Included only for action and dialog skills. - :param str environment_id: (optional) The unique identifier of the environment - where the skill is defined. For action and dialog skills, this is always the - draft environment. - :param bool valid: (optional) Whether the skill is structurally valid. - :param str next_snapshot_version: (optional) The name that will be given to the - next snapshot that is created for the skill. A snapshot of each versionable - skill is saved for each new release of an assistant. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, and - are not included in **Export skills** responses. - :param List[SearchSkillWarning] warnings: (optional) An array of warnings - describing errors with the search skill configuration. Included only for search - skills. - :param str language: The language of the skill. - :param str type: The type of skill. + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str port: (optional) The host port of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to the URL + of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server or an + object. In cases like timeouts or connections errors, it will contain details of + why the callout to the external server failed. """ def __init__( self, - language: str, - type: str, *, - name: Optional[str] = None, - description: Optional[str] = None, - workspace: Optional[dict] = None, - skill_id: Optional[str] = None, - status: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, - status_description: Optional[str] = None, - dialog_settings: Optional[dict] = None, - assistant_id: Optional[str] = None, - workspace_id: Optional[str] = None, - environment_id: Optional[str] = None, - valid: Optional[bool] = None, - next_snapshot_version: Optional[str] = None, - search_settings: Optional['SearchSettings'] = None, - warnings: Optional[List['SearchSkillWarning']] = None, + method: Optional[str] = None, + url: Optional[str] = None, + port: Optional[str] = None, + path: Optional[str] = None, + query_parameters: Optional[str] = None, + headers_: Optional[dict] = None, + body: Optional[dict] = None, ) -> None: """ - Initialize a SkillImport object. + Initialize a TurnEventGenerativeAICalledCalloutRequest object. - :param str language: The language of the skill. - :param str type: The type of skill. - :param str name: (optional) The name of the skill. This string cannot - contain carriage return, newline, or tab characters. - :param str description: (optional) The description of the skill. This - string cannot contain carriage return, newline, or tab characters. - :param dict workspace: (optional) An object containing the conversational - content of an action or dialog skill. - :param dict dialog_settings: (optional) For internal use only. - :param SearchSettings search_settings: (optional) An object describing the - search skill configuration. - **Note:** Search settings are not supported in **Import skills** requests, - and are not included in **Export skills** responses. + :param str method: (optional) The REST method of the request. + :param str url: (optional) The host URL of the request call. + :param str port: (optional) The host port of the request call. + :param str path: (optional) The URL path of the request call. + :param str query_parameters: (optional) Any query parameters appended to + the URL of the request call. + :param dict headers_: (optional) Any headers included in the request call. + :param dict body: (optional) Contains the response of the external server + or an object. In cases like timeouts or connections errors, it will contain + details of why the callout to the external server failed. """ - self.name = name - self.description = description - self.workspace = workspace - self.skill_id = skill_id - self.status = status - self.status_errors = status_errors - self.status_description = status_description - self.dialog_settings = dialog_settings - self.assistant_id = assistant_id - self.workspace_id = workspace_id - self.environment_id = environment_id - self.valid = valid - self.next_snapshot_version = next_snapshot_version - self.search_settings = search_settings - self.warnings = warnings - self.language = language - self.type = type + self.method = method + self.url = url + self.port = port + self.path = path + self.query_parameters = query_parameters + self.headers_ = headers_ + self.body = body @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillImport': - """Initialize a SkillImport object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'TurnEventGenerativeAICalledCalloutRequest': + """Initialize a TurnEventGenerativeAICalledCalloutRequest object from a json dictionary.""" args = {} - if (name := _dict.get('name')) is not None: - args['name'] = name - if (description := _dict.get('description')) is not None: - args['description'] = description - if (workspace := _dict.get('workspace')) is not None: - args['workspace'] = workspace - if (skill_id := _dict.get('skill_id')) is not None: - args['skill_id'] = skill_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (dialog_settings := _dict.get('dialog_settings')) is not None: - args['dialog_settings'] = dialog_settings - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (workspace_id := _dict.get('workspace_id')) is not None: - args['workspace_id'] = workspace_id - if (environment_id := _dict.get('environment_id')) is not None: - args['environment_id'] = environment_id - if (valid := _dict.get('valid')) is not None: - args['valid'] = valid - if (next_snapshot_version := - _dict.get('next_snapshot_version')) is not None: - args['next_snapshot_version'] = next_snapshot_version - if (search_settings := _dict.get('search_settings')) is not None: - args['search_settings'] = SearchSettings.from_dict(search_settings) - if (warnings := _dict.get('warnings')) is not None: - args['warnings'] = [ - SearchSkillWarning.from_dict(v) for v in warnings - ] - if (language := _dict.get('language')) is not None: - args['language'] = language - else: - raise ValueError( - 'Required property \'language\' not present in SkillImport JSON' - ) - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in SkillImport JSON') + if (method := _dict.get('method')) is not None: + args['method'] = method + if (url := _dict.get('url')) is not None: + args['url'] = url + if (port := _dict.get('port')) is not None: + args['port'] = port + if (path := _dict.get('path')) is not None: + args['path'] = path + if (query_parameters := _dict.get('query_parameters')) is not None: + args['query_parameters'] = query_parameters + if (headers_ := _dict.get('headers')) is not None: + args['headers_'] = headers_ + if (body := _dict.get('body')) is not None: + args['body'] = body return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillImport object from a json dictionary.""" + """Initialize a TurnEventGenerativeAICalledCalloutRequest 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'workspace') and self.workspace is not None: - _dict['workspace'] = self.workspace - if hasattr(self, 'skill_id') and getattr(self, 'skill_id') is not None: - _dict['skill_id'] = getattr(self, 'skill_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, - 'dialog_settings') and self.dialog_settings is not None: - _dict['dialog_settings'] = self.dialog_settings - if hasattr(self, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'workspace_id') and getattr( - self, 'workspace_id') is not None: - _dict['workspace_id'] = getattr(self, 'workspace_id') - if hasattr(self, 'environment_id') and getattr( - self, 'environment_id') is not None: - _dict['environment_id'] = getattr(self, 'environment_id') - if hasattr(self, 'valid') and getattr(self, 'valid') is not None: - _dict['valid'] = getattr(self, 'valid') - if hasattr(self, 'next_snapshot_version') and getattr( - self, 'next_snapshot_version') is not None: - _dict['next_snapshot_version'] = getattr(self, - 'next_snapshot_version') + if hasattr(self, 'method') and self.method is not None: + _dict['method'] = self.method + if hasattr(self, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'port') and self.port is not None: + _dict['port'] = self.port + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path if hasattr(self, - 'search_settings') and self.search_settings is not None: - if isinstance(self.search_settings, dict): - _dict['search_settings'] = self.search_settings - else: - _dict['search_settings'] = self.search_settings.to_dict() - if hasattr(self, 'warnings') and getattr(self, 'warnings') is not None: - warnings_list = [] - for v in getattr(self, 'warnings'): - if isinstance(v, dict): - warnings_list.append(v) - else: - warnings_list.append(v.to_dict()) - _dict['warnings'] = warnings_list - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'type') and self.type is not None: - _dict['type'] = self.type + 'query_parameters') and self.query_parameters is not None: + _dict['query_parameters'] = self.query_parameters + if hasattr(self, 'headers_') and self.headers_ is not None: + _dict['headers'] = self.headers_ + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body return _dict def _to_dict(self): @@ -13491,122 +17389,81 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillImport object.""" + """Return a `str` version of this TurnEventGenerativeAICalledCalloutRequest object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillImport') -> bool: + def __eq__(self, + other: 'TurnEventGenerativeAICalledCalloutRequest') -> 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: 'SkillImport') -> bool: + def __ne__(self, + other: 'TurnEventGenerativeAICalledCalloutRequest') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the skill: - - **Available**: The skill is available and ready to process messages. - - **Failed**: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - **Non Existent**: The skill does not exist. - - **Processing**: An asynchronous operation has not yet completed. - - **Training**: The skill is training based on new data. - """ - - AVAILABLE = 'Available' - FAILED = 'Failed' - NON_EXISTENT = 'Non Existent' - PROCESSING = 'Processing' - TRAINING = 'Training' - UNAVAILABLE = 'Unavailable' - - class TypeEnum(str, Enum): + class MethodEnum(str, Enum): """ - The type of skill. + The REST method of the request. """ - ACTION = 'action' - DIALOG = 'dialog' + GET = 'GET' + POST = 'POST' + PUT = 'PUT' + DELETE = 'DELETE' + PATCH = 'PATCH' -class SkillsAsyncRequestStatus: +class TurnEventGenerativeAICalledCalloutResponse: """ - SkillsAsyncRequestStatus. + TurnEventGenerativeAICalledCalloutResponse. - :param str assistant_id: (optional) The assistant ID of the assistant. - :param str status: (optional) The current status of the asynchronous operation: - - `Available`: An asynchronous export is available. - - `Completed`: An asynchronous import operation has completed successfully. - - `Failed`: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - `Processing`: An asynchronous operation has not yet completed. - :param str status_description: (optional) The description of the failed - asynchronous operation. Included only if **status**=`Failed`. - :param List[StatusError] status_errors: (optional) An array of messages about - errors that caused an asynchronous operation to fail. Included only if - **status**=`Failed`. + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. """ def __init__( self, *, - assistant_id: Optional[str] = None, - status: Optional[str] = None, - status_description: Optional[str] = None, - status_errors: Optional[List['StatusError']] = None, + body: Optional[str] = None, + status_code: Optional[int] = None, ) -> None: """ - Initialize a SkillsAsyncRequestStatus object. + Initialize a TurnEventGenerativeAICalledCalloutResponse object. + :param str body: (optional) The final response string. This response is a + composition of every partial chunk received from the stream. + :param int status_code: (optional) The final status code of the response. """ - self.assistant_id = assistant_id - self.status = status - self.status_description = status_description - self.status_errors = status_errors + self.body = body + self.status_code = status_code @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillsAsyncRequestStatus': - """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'TurnEventGenerativeAICalledCalloutResponse': + """Initialize a TurnEventGenerativeAICalledCalloutResponse object from a json dictionary.""" args = {} - if (assistant_id := _dict.get('assistant_id')) is not None: - args['assistant_id'] = assistant_id - if (status := _dict.get('status')) is not None: - args['status'] = status - if (status_description := _dict.get('status_description')) is not None: - args['status_description'] = status_description - if (status_errors := _dict.get('status_errors')) is not None: - args['status_errors'] = [ - StatusError.from_dict(v) for v in status_errors - ] + if (body := _dict.get('body')) is not None: + args['body'] = body + if (status_code := _dict.get('status_code')) is not None: + args['status_code'] = status_code return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillsAsyncRequestStatus object from a json dictionary.""" + """Initialize a TurnEventGenerativeAICalledCalloutResponse 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, 'assistant_id') and getattr( - self, 'assistant_id') is not None: - _dict['assistant_id'] = getattr(self, 'assistant_id') - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, 'status_errors') and getattr( - self, 'status_errors') is not None: - status_errors_list = [] - for v in getattr(self, 'status_errors'): - if isinstance(v, dict): - status_errors_list.append(v) - else: - status_errors_list.append(v.to_dict()) - _dict['status_errors'] = status_errors_list + if hasattr(self, 'body') and self.body is not None: + _dict['body'] = self.body + if hasattr(self, 'status_code') and self.status_code is not None: + _dict['status_code'] = self.status_code return _dict def _to_dict(self): @@ -13614,105 +17471,109 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillsAsyncRequestStatus object.""" + """Return a `str` version of this TurnEventGenerativeAICalledCalloutResponse object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillsAsyncRequestStatus') -> bool: + def __eq__(self, + other: 'TurnEventGenerativeAICalledCalloutResponse') -> 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: 'SkillsAsyncRequestStatus') -> bool: + def __ne__(self, + other: 'TurnEventGenerativeAICalledCalloutResponse') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class StatusEnum(str, Enum): - """ - The current status of the asynchronous operation: - - `Available`: An asynchronous export is available. - - `Completed`: An asynchronous import operation has completed successfully. - - `Failed`: An asynchronous operation has failed. See the **status_errors** - property for more information about the cause of the failure. - - `Processing`: An asynchronous operation has not yet completed. - """ - - AVAILABLE = 'Available' - COMPLETED = 'Completed' - FAILED = 'Failed' - PROCESSING = 'Processing' - -class SkillsExport: +class TurnEventGenerativeAICalledCalloutSearch: """ - SkillsExport. + TurnEventGenerativeAICalledCalloutSearch. - :param List[Skill] assistant_skills: An array of objects describing the skills - for the assistant. Included in responses only if **status**=`Available`. - :param AssistantState assistant_state: Status information about the skills for - the assistant. Included in responses only if **status**=`Available`. + :param str engine: (optional) The search engine that was used to scan the + documents. + :param str index: (optional) The name of the Elasticsearch index being used. + This field is only available if the engine being used is Elasticsearch. + :param str query: (optional) The query that will be used by the system to + initiate search on the document search engine. + :param TurnEventGenerativeAICalledCalloutRequest request: (optional) + :param TurnEventGenerativeAICalledCalloutResponse response: (optional) """ def __init__( self, - assistant_skills: List['Skill'], - assistant_state: 'AssistantState', + *, + engine: Optional[str] = None, + index: Optional[str] = None, + query: Optional[str] = None, + request: Optional['TurnEventGenerativeAICalledCalloutRequest'] = None, + response: Optional['TurnEventGenerativeAICalledCalloutResponse'] = None, ) -> None: """ - Initialize a SkillsExport object. + Initialize a TurnEventGenerativeAICalledCalloutSearch object. - :param List[Skill] assistant_skills: An array of objects describing the - skills for the assistant. Included in responses only if - **status**=`Available`. - :param AssistantState assistant_state: Status information about the skills - for the assistant. Included in responses only if **status**=`Available`. + :param str engine: (optional) The search engine that was used to scan the + documents. + :param str index: (optional) The name of the Elasticsearch index being + used. This field is only available if the engine being used is + Elasticsearch. + :param str query: (optional) The query that will be used by the system to + initiate search on the document search engine. + :param TurnEventGenerativeAICalledCalloutRequest request: (optional) + :param TurnEventGenerativeAICalledCalloutResponse response: (optional) """ - self.assistant_skills = assistant_skills - self.assistant_state = assistant_state + self.engine = engine + self.index = index + self.query = query + self.request = request + self.response = response @classmethod - def from_dict(cls, _dict: Dict) -> 'SkillsExport': - """Initialize a SkillsExport object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'TurnEventGenerativeAICalledCalloutSearch': + """Initialize a TurnEventGenerativeAICalledCalloutSearch object from a json dictionary.""" args = {} - if (assistant_skills := _dict.get('assistant_skills')) is not None: - args['assistant_skills'] = [ - Skill.from_dict(v) for v in assistant_skills - ] - else: - raise ValueError( - 'Required property \'assistant_skills\' not present in SkillsExport JSON' - ) - if (assistant_state := _dict.get('assistant_state')) is not None: - args['assistant_state'] = AssistantState.from_dict(assistant_state) - else: - raise ValueError( - 'Required property \'assistant_state\' not present in SkillsExport JSON' - ) + if (engine := _dict.get('engine')) is not None: + args['engine'] = engine + if (index := _dict.get('index')) is not None: + args['index'] = index + if (query := _dict.get('query')) is not None: + args['query'] = query + if (request := _dict.get('request')) is not None: + args[ + 'request'] = TurnEventGenerativeAICalledCalloutRequest.from_dict( + request) + if (response := _dict.get('response')) is not None: + args[ + 'response'] = TurnEventGenerativeAICalledCalloutResponse.from_dict( + response) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a SkillsExport object from a json dictionary.""" + """Initialize a TurnEventGenerativeAICalledCalloutSearch 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, - 'assistant_skills') and self.assistant_skills is not None: - assistant_skills_list = [] - for v in self.assistant_skills: - if isinstance(v, dict): - assistant_skills_list.append(v) - else: - assistant_skills_list.append(v.to_dict()) - _dict['assistant_skills'] = assistant_skills_list - if hasattr(self, - 'assistant_state') and self.assistant_state is not None: - if isinstance(self.assistant_state, dict): - _dict['assistant_state'] = self.assistant_state + if hasattr(self, 'engine') and self.engine is not None: + _dict['engine'] = self.engine + if hasattr(self, 'index') and self.index is not None: + _dict['index'] = self.index + if hasattr(self, 'query') and self.query is not None: + _dict['query'] = self.query + if hasattr(self, 'request') and self.request is not None: + if isinstance(self.request, dict): + _dict['request'] = self.request else: - _dict['assistant_state'] = self.assistant_state.to_dict() + _dict['request'] = self.request.to_dict() + if hasattr(self, 'response') and self.response is not None: + if isinstance(self.response, dict): + _dict['response'] = self.response + else: + _dict['response'] = self.response.to_dict() return _dict def _to_dict(self): @@ -13720,141 +17581,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this SkillsExport object.""" + """Return a `str` version of this TurnEventGenerativeAICalledCalloutSearch object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'SkillsExport') -> bool: + def __eq__(self, other: 'TurnEventGenerativeAICalledCalloutSearch') -> 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: 'SkillsExport') -> bool: + def __ne__(self, other: 'TurnEventGenerativeAICalledCalloutSearch') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatefulMessageResponse: +class TurnEventGenerativeAICalledMetrics: """ - A response from the watsonx Assistant service. + TurnEventGenerativeAICalledMetrics. - :param MessageOutput output: Assistant output to be rendered or processed by the - client. - :param MessageContext context: (optional) Context data for the conversation. You - can use this property to access context variables. The context is stored by the - assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :param str user_id: A string value that identifies the user who is interacting - with the assistant. The client must provide a unique identifier for each - individual end user who accesses the application. For user-based plans, this - user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. - :param MessageOutput masked_output: (optional) Assistant output to be rendered - or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes the - input text. All private data is masked or removed. + :param float search_time_ms: (optional) The amount of time (in milliseconds) it + took for the system to complete the search using the document search engine. + :param float answer_generation_time_ms: (optional) The amount of time (in + milliseconds) it took for the system to complete answer generation process by + reaching out to watsonx.ai. + :param float total_time_ms: (optional) The amount of time (in milliseconds) it + took for the system to fully process the conversational search. """ def __init__( self, - output: 'MessageOutput', - user_id: str, *, - context: Optional['MessageContext'] = None, - masked_output: Optional['MessageOutput'] = None, - masked_input: Optional['MessageInput'] = None, + search_time_ms: Optional[float] = None, + answer_generation_time_ms: Optional[float] = None, + total_time_ms: Optional[float] = None, ) -> None: """ - Initialize a StatefulMessageResponse object. + Initialize a TurnEventGenerativeAICalledMetrics object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param str user_id: A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier - for each individual end user who accesses the application. For user-based - plans, this user ID is used to identify unique users for billing purposes. - This string cannot contain carriage return, newline, or tab characters. If - no value is specified in the input, **user_id** is automatically set to the - value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. - :param MessageContext context: (optional) Context data for the - conversation. You can use this property to access context variables. The - context is stored by the assistant on a per-session basis. - **Note:** The context is included in message responses only if - **return_context**=`true` in the message request. Full context is always - included in logs. - :param MessageOutput masked_output: (optional) Assistant output to be - rendered or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes - the input text. All private data is masked or removed. + :param float search_time_ms: (optional) The amount of time (in + milliseconds) it took for the system to complete the search using the + document search engine. + :param float answer_generation_time_ms: (optional) The amount of time (in + milliseconds) it took for the system to complete answer generation process + by reaching out to watsonx.ai. + :param float total_time_ms: (optional) The amount of time (in milliseconds) + it took for the system to fully process the conversational search. """ - self.output = output - self.context = context - self.user_id = user_id - self.masked_output = masked_output - self.masked_input = masked_input + self.search_time_ms = search_time_ms + self.answer_generation_time_ms = answer_generation_time_ms + self.total_time_ms = total_time_ms @classmethod - def from_dict(cls, _dict: Dict) -> 'StatefulMessageResponse': - """Initialize a StatefulMessageResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventGenerativeAICalledMetrics': + """Initialize a TurnEventGenerativeAICalledMetrics object from a json dictionary.""" args = {} - if (output := _dict.get('output')) is not None: - args['output'] = MessageOutput.from_dict(output) - else: - raise ValueError( - 'Required property \'output\' not present in StatefulMessageResponse JSON' - ) - if (context := _dict.get('context')) is not None: - args['context'] = MessageContext.from_dict(context) - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id - else: - raise ValueError( - 'Required property \'user_id\' not present in StatefulMessageResponse JSON' - ) - if (masked_output := _dict.get('masked_output')) is not None: - args['masked_output'] = MessageOutput.from_dict(masked_output) - if (masked_input := _dict.get('masked_input')) is not None: - args['masked_input'] = MessageInput.from_dict(masked_input) + if (search_time_ms := _dict.get('search_time_ms')) is not None: + args['search_time_ms'] = search_time_ms + if (answer_generation_time_ms := + _dict.get('answer_generation_time_ms')) is not None: + args['answer_generation_time_ms'] = answer_generation_time_ms + if (total_time_ms := _dict.get('total_time_ms')) is not None: + args['total_time_ms'] = total_time_ms return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatefulMessageResponse object from a json dictionary.""" + """Initialize a TurnEventGenerativeAICalledMetrics 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, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - if hasattr(self, 'masked_output') and self.masked_output is not None: - if isinstance(self.masked_output, dict): - _dict['masked_output'] = self.masked_output - else: - _dict['masked_output'] = self.masked_output.to_dict() - if hasattr(self, 'masked_input') and self.masked_input is not None: - if isinstance(self.masked_input, dict): - _dict['masked_input'] = self.masked_input - else: - _dict['masked_input'] = self.masked_input.to_dict() + if hasattr(self, 'search_time_ms') and self.search_time_ms is not None: + _dict['search_time_ms'] = self.search_time_ms + if hasattr(self, 'answer_generation_time_ms' + ) and self.answer_generation_time_ms is not None: + _dict['answer_generation_time_ms'] = self.answer_generation_time_ms + if hasattr(self, 'total_time_ms') and self.total_time_ms is not None: + _dict['total_time_ms'] = self.total_time_ms return _dict def _to_dict(self): @@ -13862,87 +17666,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatefulMessageResponse object.""" + """Return a `str` version of this TurnEventGenerativeAICalledMetrics object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatefulMessageResponse') -> bool: + def __eq__(self, other: 'TurnEventGenerativeAICalledMetrics') -> 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: 'StatefulMessageResponse') -> bool: + def __ne__(self, other: 'TurnEventGenerativeAICalledMetrics') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageContext: +class TurnEventNodeSource: """ - StatelessMessageContext. + TurnEventNodeSource. - :param StatelessMessageContextGlobal global_: (optional) Session context data - that is shared by all skills used by the assistant. - :param StatelessMessageContextSkills skills: (optional) Context data specific to - particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that is - specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str condition: (optional) The condition that triggered the dialog node. """ def __init__( self, *, - global_: Optional['StatelessMessageContextGlobal'] = None, - skills: Optional['StatelessMessageContextSkills'] = None, - integrations: Optional[dict] = None, + type: Optional[str] = None, + dialog_node: Optional[str] = None, + title: Optional[str] = None, + condition: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageContext object. + Initialize a TurnEventNodeSource object. - :param StatelessMessageContextGlobal global_: (optional) Session context - data that is shared by all skills used by the assistant. - :param StatelessMessageContextSkills skills: (optional) Context data - specific to particular skills used by the assistant. - :param dict integrations: (optional) An object containing context data that - is specific to particular integrations. For more information, see the - [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). + :param str type: (optional) The type of turn event. + :param str dialog_node: (optional) A dialog node that was visited during + processing of the input message. + :param str title: (optional) The title of the dialog node. + :param str condition: (optional) The condition that triggered the dialog + node. """ - self.global_ = global_ - self.skills = skills - self.integrations = integrations + self.type = type + self.dialog_node = dialog_node + self.title = title + self.condition = condition @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageContext': - """Initialize a StatelessMessageContext object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventNodeSource': + """Initialize a TurnEventNodeSource object from a json dictionary.""" args = {} - if (global_ := _dict.get('global')) is not None: - args['global_'] = StatelessMessageContextGlobal.from_dict(global_) - if (skills := _dict.get('skills')) is not None: - args['skills'] = StatelessMessageContextSkills.from_dict(skills) - if (integrations := _dict.get('integrations')) is not None: - args['integrations'] = integrations + if (type := _dict.get('type')) is not None: + args['type'] = type + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + if (title := _dict.get('title')) is not None: + args['title'] = title + if (condition := _dict.get('condition')) is not None: + args['condition'] = condition return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageContext object from a json dictionary.""" + """Initialize a TurnEventNodeSource 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, 'global_') and self.global_ is not None: - if isinstance(self.global_, dict): - _dict['global'] = self.global_ - else: - _dict['global'] = self.global_.to_dict() - if hasattr(self, 'skills') and self.skills is not None: - if isinstance(self.skills, dict): - _dict['skills'] = self.skills - else: - _dict['skills'] = self.skills.to_dict() - if hasattr(self, 'integrations') and self.integrations is not None: - _dict['integrations'] = self.integrations + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'condition') and self.condition is not None: + _dict['condition'] = self.condition return _dict def _to_dict(self): @@ -13950,70 +17751,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContext object.""" + """Return a `str` version of this TurnEventNodeSource object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageContext') -> bool: + def __eq__(self, other: 'TurnEventNodeSource') -> 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: 'StatelessMessageContext') -> bool: + def __ne__(self, other: 'TurnEventNodeSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of turn event. + """ + + DIALOG_NODE = 'dialog_node' + -class StatelessMessageContextGlobal: +class TurnEventSearchError: """ - Session context data that is shared by all skills used by the assistant. + TurnEventSearchError. - :param MessageContextGlobalSystem system: (optional) Built-in system properties - that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param str message: (optional) Any error message returned by a failed call to a + search skill. """ def __init__( self, *, - system: Optional['MessageContextGlobalSystem'] = None, - session_id: Optional[str] = None, + message: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageContextGlobal object. + Initialize a TurnEventSearchError object. - :param MessageContextGlobalSystem system: (optional) Built-in system - properties that apply to all skills used by the assistant. - :param str session_id: (optional) The unique identifier of the session. + :param str message: (optional) Any error message returned by a failed call + to a search skill. """ - self.system = system - self.session_id = session_id + self.message = message @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextGlobal': - """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError': + """Initialize a TurnEventSearchError object from a json dictionary.""" args = {} - if (system := _dict.get('system')) is not None: - args['system'] = MessageContextGlobalSystem.from_dict(system) - if (session_id := _dict.get('session_id')) is not None: - args['session_id'] = session_id + if (message := _dict.get('message')) is not None: + args['message'] = message return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageContextGlobal object from a json dictionary.""" + """Initialize a TurnEventSearchError 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, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system - else: - _dict['system'] = self.system.to_dict() - if hasattr(self, 'session_id') and self.session_id is not None: - _dict['session_id'] = self.session_id + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message return _dict def _to_dict(self): @@ -14021,78 +17818,105 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContextGlobal object.""" + """Return a `str` version of this TurnEventSearchError object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageContextGlobal') -> bool: + def __eq__(self, other: 'TurnEventSearchError') -> 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: 'StatelessMessageContextGlobal') -> bool: + def __ne__(self, other: 'TurnEventSearchError') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageContextSkills: +class TurnEventStepSource: """ - Context data specific to particular skills used by the assistant. + TurnEventStepSource. - :param MessageContextDialogSkill main_skill: (optional) Context variables that - are used by the dialog skill. - :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) - Context variables that are used by the action skill. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing of + the message. + :param str action_title: (optional) The title of the action. + :param str step: (optional) A step that was visited during processing of the + message. + :param bool is_ai_guided: (optional) Whether the action that the turn event was + generated from is an AI-guided action. + :param bool is_skill_based: (optional) Whether the action that the turn event + was generated from is a skill-guided action. """ def __init__( self, *, - main_skill: Optional['MessageContextDialogSkill'] = None, - actions_skill: Optional[ - 'StatelessMessageContextSkillsActionsSkill'] = None, + type: Optional[str] = None, + action: Optional[str] = None, + action_title: Optional[str] = None, + step: Optional[str] = None, + is_ai_guided: Optional[bool] = None, + is_skill_based: Optional[bool] = None, ) -> None: """ - Initialize a StatelessMessageContextSkills object. + Initialize a TurnEventStepSource object. - :param MessageContextDialogSkill main_skill: (optional) Context variables - that are used by the dialog skill. - :param StatelessMessageContextSkillsActionsSkill actions_skill: (optional) - Context variables that are used by the action skill. + :param str type: (optional) The type of turn event. + :param str action: (optional) An action that was visited during processing + of the message. + :param str action_title: (optional) The title of the action. + :param str step: (optional) A step that was visited during processing of + the message. + :param bool is_ai_guided: (optional) Whether the action that the turn event + was generated from is an AI-guided action. + :param bool is_skill_based: (optional) Whether the action that the turn + event was generated from is a skill-guided action. """ - self.main_skill = main_skill - self.actions_skill = actions_skill + self.type = type + self.action = action + self.action_title = action_title + self.step = step + self.is_ai_guided = is_ai_guided + self.is_skill_based = is_skill_based @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageContextSkills': - """Initialize a StatelessMessageContextSkills object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'TurnEventStepSource': + """Initialize a TurnEventStepSource object from a json dictionary.""" args = {} - if (main_skill := _dict.get('main skill')) is not None: - args['main_skill'] = MessageContextDialogSkill.from_dict(main_skill) - if (actions_skill := _dict.get('actions skill')) is not None: - args[ - 'actions_skill'] = StatelessMessageContextSkillsActionsSkill.from_dict( - actions_skill) + if (type := _dict.get('type')) is not None: + args['type'] = type + if (action := _dict.get('action')) is not None: + args['action'] = action + if (action_title := _dict.get('action_title')) is not None: + args['action_title'] = action_title + if (step := _dict.get('step')) is not None: + args['step'] = step + if (is_ai_guided := _dict.get('is_ai_guided')) is not None: + args['is_ai_guided'] = is_ai_guided + if (is_skill_based := _dict.get('is_skill_based')) is not None: + args['is_skill_based'] = is_skill_based return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageContextSkills object from a json dictionary.""" + """Initialize a TurnEventStepSource 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, 'main_skill') and self.main_skill is not None: - if isinstance(self.main_skill, dict): - _dict['main skill'] = self.main_skill - else: - _dict['main skill'] = self.main_skill.to_dict() - if hasattr(self, 'actions_skill') and self.actions_skill is not None: - if isinstance(self.actions_skill, dict): - _dict['actions skill'] = self.actions_skill - else: - _dict['actions skill'] = self.actions_skill.to_dict() + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'action_title') and self.action_title is not None: + _dict['action_title'] = self.action_title + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'is_ai_guided') and self.is_ai_guided is not None: + _dict['is_ai_guided'] = self.is_ai_guided + if hasattr(self, 'is_skill_based') and self.is_skill_based is not None: + _dict['is_skill_based'] = self.is_skill_based return _dict def _to_dict(self): @@ -14100,134 +17924,72 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContextSkills object.""" + """Return a `str` version of this TurnEventStepSource object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageContextSkills') -> bool: + def __eq__(self, other: 'TurnEventStepSource') -> 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: 'StatelessMessageContextSkills') -> bool: + def __ne__(self, other: 'TurnEventStepSource') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class TypeEnum(str, Enum): + """ + The type of turn event. + """ + + STEP = 'step' -class StatelessMessageContextSkillsActionsSkill: + +class UpdateEnvironmentOrchestration: """ - Context variables that are used by the action skill. + The search skill orchestration settings for the environment. - :param dict user_defined: (optional) An object containing any arbitrary - variables that can be read and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data used by - the skill. - :param dict action_variables: (optional) An object containing action variables. - Action variables can be accessed only by steps in the same action, and do not - persist after the action ends. - :param dict skill_variables: (optional) An object containing skill variables. - (In the watsonx Assistant user interface, skill variables are called _session - variables_.) Skill variables can be accessed by any action and persist for the - duration of the session. - :param dict private_action_variables: (optional) An object containing private - action variables. Action variables can be accessed only by steps in the same - action, and do not persist after the action ends. Private variables are - encrypted. - :param dict private_skill_variables: (optional) An object containing private - skill variables. (In the watsonx Assistant user interface, skill variables are - called _session variables_.) Skill variables can be accessed by any action and - persist for the duration of the session. Private variables are encrypted. + :param bool search_skill_fallback: (optional) Whether to fall back to a search + skill when responding to messages that do not match any intent or action defined + in dialog or action skills. (If no search skill is configured for the + environment, this property is ignored.). """ def __init__( self, *, - user_defined: Optional[dict] = None, - system: Optional['MessageContextSkillSystem'] = None, - action_variables: Optional[dict] = None, - skill_variables: Optional[dict] = None, - private_action_variables: Optional[dict] = None, - private_skill_variables: Optional[dict] = None, + search_skill_fallback: Optional[bool] = None, ) -> None: """ - Initialize a StatelessMessageContextSkillsActionsSkill object. + Initialize a UpdateEnvironmentOrchestration object. - :param dict user_defined: (optional) An object containing any arbitrary - variables that can be read and written by a particular skill. - :param MessageContextSkillSystem system: (optional) System context data - used by the skill. - :param dict action_variables: (optional) An object containing action - variables. Action variables can be accessed only by steps in the same - action, and do not persist after the action ends. - :param dict skill_variables: (optional) An object containing skill - variables. (In the watsonx Assistant user interface, skill variables are - called _session variables_.) Skill variables can be accessed by any action - and persist for the duration of the session. - :param dict private_action_variables: (optional) An object containing - private action variables. Action variables can be accessed only by steps in - the same action, and do not persist after the action ends. Private - variables are encrypted. - :param dict private_skill_variables: (optional) An object containing - private skill variables. (In the watsonx Assistant user interface, skill - variables are called _session variables_.) Skill variables can be accessed - by any action and persist for the duration of the session. Private - variables are encrypted. + :param bool search_skill_fallback: (optional) Whether to fall back to a + search skill when responding to messages that do not match any intent or + action defined in dialog or action skills. (If no search skill is + configured for the environment, this property is ignored.). """ - self.user_defined = user_defined - self.system = system - self.action_variables = action_variables - self.skill_variables = skill_variables - self.private_action_variables = private_action_variables - self.private_skill_variables = private_skill_variables + self.search_skill_fallback = search_skill_fallback @classmethod - def from_dict(cls, - _dict: Dict) -> 'StatelessMessageContextSkillsActionsSkill': - """Initialize a StatelessMessageContextSkillsActionsSkill object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'UpdateEnvironmentOrchestration': + """Initialize a UpdateEnvironmentOrchestration object from a json dictionary.""" args = {} - if (user_defined := _dict.get('user_defined')) is not None: - args['user_defined'] = user_defined - if (system := _dict.get('system')) is not None: - args['system'] = MessageContextSkillSystem.from_dict(system) - if (action_variables := _dict.get('action_variables')) is not None: - args['action_variables'] = action_variables - if (skill_variables := _dict.get('skill_variables')) is not None: - args['skill_variables'] = skill_variables - if (private_action_variables := - _dict.get('private_action_variables')) is not None: - args['private_action_variables'] = private_action_variables - if (private_skill_variables := - _dict.get('private_skill_variables')) is not None: - args['private_skill_variables'] = private_skill_variables + if (search_skill_fallback := + _dict.get('search_skill_fallback')) is not None: + args['search_skill_fallback'] = search_skill_fallback return cls(**args) - @classmethod - def _from_dict(cls, _dict): - """Initialize a StatelessMessageContextSkillsActionsSkill 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, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined - if hasattr(self, 'system') and self.system is not None: - if isinstance(self.system, dict): - _dict['system'] = self.system - else: - _dict['system'] = self.system.to_dict() - if hasattr(self, - 'action_variables') and self.action_variables is not None: - _dict['action_variables'] = self.action_variables - if hasattr(self, - 'skill_variables') and self.skill_variables is not None: - _dict['skill_variables'] = self.skill_variables - if hasattr(self, 'private_action_variables' - ) and self.private_action_variables is not None: - _dict['private_action_variables'] = self.private_action_variables - if hasattr(self, 'private_skill_variables' - ) and self.private_skill_variables is not None: - _dict['private_skill_variables'] = self.private_skill_variables + @classmethod + def _from_dict(cls, _dict): + """Initialize a UpdateEnvironmentOrchestration 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, 'search_skill_fallback' + ) and self.search_skill_fallback is not None: + _dict['search_skill_fallback'] = self.search_skill_fallback return _dict def _to_dict(self): @@ -14235,177 +17997,57 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageContextSkillsActionsSkill object.""" + """Return a `str` version of this UpdateEnvironmentOrchestration object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'StatelessMessageContextSkillsActionsSkill') -> bool: + def __eq__(self, other: 'UpdateEnvironmentOrchestration') -> 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: 'StatelessMessageContextSkillsActionsSkill') -> bool: + def __ne__(self, other: 'UpdateEnvironmentOrchestration') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageInput: +class UpdateEnvironmentReleaseReference: """ - An input object that includes the input text. + An object describing the release that is currently deployed in the environment. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when evaluating - the user input. Include intents from the previous response to continue using - those intents rather than trying to recognize intents in the new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when evaluating - the message. Include entities from the previous response to continue using those - entities rather than detecting entities in the new input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the Segment - extension. - :param StatelessMessageInputOptions options: (optional) Optional properties that - control how the assistant responds. + :param str release: (optional) The name of the deployed release. """ def __init__( self, *, - message_type: Optional[str] = None, - text: Optional[str] = None, - intents: Optional[List['RuntimeIntent']] = None, - entities: Optional[List['RuntimeEntity']] = None, - suggestion_id: Optional[str] = None, - attachments: Optional[List['MessageInputAttachment']] = None, - analytics: Optional['RequestAnalytics'] = None, - options: Optional['StatelessMessageInputOptions'] = None, + release: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageInput object. + Initialize a UpdateEnvironmentReleaseReference object. - :param str message_type: (optional) The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill - is bypassed.) - **Note:** A `search` message results in an error if no search skill is - configured for the assistant. - :param str text: (optional) The text of the user input. This string cannot - contain carriage return, newline, or tab characters. - :param List[RuntimeIntent] intents: (optional) Intents to use when - evaluating the user input. Include intents from the previous response to - continue using those intents rather than trying to recognize intents in the - new input. - :param List[RuntimeEntity] entities: (optional) Entities to use when - evaluating the message. Include entities from the previous response to - continue using those entities rather than detecting entities in the new - input. - :param str suggestion_id: (optional) For internal use only. - :param List[MessageInputAttachment] attachments: (optional) An array of - multimedia attachments to be sent with the message. Attachments are not - processed by the assistant itself, but can be sent to external services by - webhooks. - **Note:** Attachments are not supported on IBM Cloud Pak for Data. - :param RequestAnalytics analytics: (optional) An optional object containing - analytics data. Currently, this data is used only for events sent to the - Segment extension. - :param StatelessMessageInputOptions options: (optional) Optional properties - that control how the assistant responds. + :param str release: (optional) The name of the deployed release. """ - self.message_type = message_type - self.text = text - self.intents = intents - self.entities = entities - self.suggestion_id = suggestion_id - self.attachments = attachments - self.analytics = analytics - self.options = options + self.release = release @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageInput': - """Initialize a StatelessMessageInput object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'UpdateEnvironmentReleaseReference': + """Initialize a UpdateEnvironmentReleaseReference object from a json dictionary.""" args = {} - if (message_type := _dict.get('message_type')) is not None: - args['message_type'] = message_type - if (text := _dict.get('text')) is not None: - args['text'] = text - if (intents := _dict.get('intents')) is not None: - args['intents'] = [RuntimeIntent.from_dict(v) for v in intents] - if (entities := _dict.get('entities')) is not None: - args['entities'] = [RuntimeEntity.from_dict(v) for v in entities] - if (suggestion_id := _dict.get('suggestion_id')) is not None: - args['suggestion_id'] = suggestion_id - if (attachments := _dict.get('attachments')) is not None: - args['attachments'] = [ - MessageInputAttachment.from_dict(v) for v in attachments - ] - if (analytics := _dict.get('analytics')) is not None: - args['analytics'] = RequestAnalytics.from_dict(analytics) - if (options := _dict.get('options')) is not None: - args['options'] = StatelessMessageInputOptions.from_dict(options) + if (release := _dict.get('release')) is not None: + args['release'] = release return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageInput object from a json dictionary.""" + """Initialize a UpdateEnvironmentReleaseReference 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, 'message_type') and self.message_type is not None: - _dict['message_type'] = self.message_type - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'intents') and self.intents is not None: - intents_list = [] - for v in self.intents: - if isinstance(v, dict): - intents_list.append(v) - else: - intents_list.append(v.to_dict()) - _dict['intents'] = intents_list - if hasattr(self, 'entities') and self.entities is not None: - entities_list = [] - for v in self.entities: - if isinstance(v, dict): - entities_list.append(v) - else: - entities_list.append(v.to_dict()) - _dict['entities'] = entities_list - if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: - _dict['suggestion_id'] = self.suggestion_id - if hasattr(self, 'attachments') and self.attachments is not None: - attachments_list = [] - for v in self.attachments: - if isinstance(v, dict): - attachments_list.append(v) - else: - attachments_list.append(v.to_dict()) - _dict['attachments'] = attachments_list - if hasattr(self, 'analytics') and self.analytics is not None: - if isinstance(self.analytics, dict): - _dict['analytics'] = self.analytics - else: - _dict['analytics'] = self.analytics.to_dict() - if hasattr(self, 'options') and self.options is not None: - if isinstance(self.options, dict): - _dict['options'] = self.options - else: - _dict['options'] = self.options.to_dict() + if hasattr(self, 'release') and self.release is not None: + _dict['release'] = self.release return _dict def _to_dict(self): @@ -14413,133 +18055,66 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageInput object.""" + """Return a `str` version of this UpdateEnvironmentReleaseReference object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageInput') -> bool: + def __eq__(self, other: 'UpdateEnvironmentReleaseReference') -> 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: 'StatelessMessageInput') -> bool: + def __ne__(self, other: 'UpdateEnvironmentReleaseReference') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MessageTypeEnum(str, Enum): - """ - The type of the message: - - `text`: The user input is processed normally by the assistant. - - `search`: Only search results are returned. (Any dialog or action skill is - bypassed.) - **Note:** A `search` message results in an error if no search skill is configured - for the assistant. - """ - - TEXT = 'text' - SEARCH = 'search' - -class StatelessMessageInputOptions: +class CompleteItem(RuntimeResponseGeneric): """ - Optional properties that control how the assistant responds. + CompleteItem. - :param bool restart: (optional) Whether to restart dialog processing at the root - of the dialog, regardless of any previously visited nodes. **Note:** This does - not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param bool async_callout: (optional) Whether custom extension callouts are - executed asynchronously. Asynchronous execution means the response to the - extension callout will be processed on the subsequent message call, the initial - message response signals to the client that the operation may be long running. - With synchronous execution the custom extension is executed and returns the - response in a single message turn. **Note:** **async_callout** defaults to true - for API versions earlier than 2023-06-15. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message override - the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. + :param Metadata streaming_metadata: """ def __init__( self, - *, - restart: Optional[bool] = None, - alternate_intents: Optional[bool] = None, - async_callout: Optional[bool] = None, - spelling: Optional['MessageInputOptionsSpelling'] = None, - debug: Optional[bool] = None, + streaming_metadata: 'Metadata', ) -> None: """ - Initialize a StatelessMessageInputOptions object. - - :param bool restart: (optional) Whether to restart dialog processing at the - root of the dialog, regardless of any previously visited nodes. **Note:** - This does not affect `turn_count` or any other context variables. - :param bool alternate_intents: (optional) Whether to return more than one - intent. Set to `true` to return all matching intents. - :param bool async_callout: (optional) Whether custom extension callouts are - executed asynchronously. Asynchronous execution means the response to the - extension callout will be processed on the subsequent message call, the - initial message response signals to the client that the operation may be - long running. With synchronous execution the custom extension is executed - and returns the response in a single message turn. **Note:** - **async_callout** defaults to true for API versions earlier than - 2023-06-15. - :param MessageInputOptionsSpelling spelling: (optional) Spelling correction - options for the message. Any options specified on an individual message - override the settings configured for the skill. - :param bool debug: (optional) Whether to return additional diagnostic - information. Set to `true` to return additional information in the - `output.debug` property. - """ - self.restart = restart - self.alternate_intents = alternate_intents - self.async_callout = async_callout - self.spelling = spelling - self.debug = debug + Initialize a CompleteItem object. - @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageInputOptions': - """Initialize a StatelessMessageInputOptions object from a json dictionary.""" - args = {} - if (restart := _dict.get('restart')) is not None: - args['restart'] = restart - if (alternate_intents := _dict.get('alternate_intents')) is not None: - args['alternate_intents'] = alternate_intents - if (async_callout := _dict.get('async_callout')) is not None: - args['async_callout'] = async_callout - if (spelling := _dict.get('spelling')) is not None: - args['spelling'] = MessageInputOptionsSpelling.from_dict(spelling) - if (debug := _dict.get('debug')) is not None: - args['debug'] = debug + :param Metadata streaming_metadata: + """ + # pylint: disable=super-init-not-called + self.streaming_metadata = streaming_metadata + + @classmethod + def from_dict(cls, _dict: Dict) -> 'CompleteItem': + """Initialize a CompleteItem object from a json dictionary.""" + args = {} + if (streaming_metadata := _dict.get('streaming_metadata')) is not None: + args['streaming_metadata'] = Metadata.from_dict(streaming_metadata) + else: + raise ValueError( + 'Required property \'streaming_metadata\' not present in CompleteItem JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageInputOptions object from a json dictionary.""" + """Initialize a CompleteItem 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, 'restart') and self.restart is not None: - _dict['restart'] = self.restart - if hasattr(self, - 'alternate_intents') and self.alternate_intents is not None: - _dict['alternate_intents'] = self.alternate_intents - if hasattr(self, 'async_callout') and self.async_callout is not None: - _dict['async_callout'] = self.async_callout - if hasattr(self, 'spelling') and self.spelling is not None: - if isinstance(self.spelling, dict): - _dict['spelling'] = self.spelling + if hasattr( + self, + 'streaming_metadata') and self.streaming_metadata is not None: + if isinstance(self.streaming_metadata, dict): + _dict['streaming_metadata'] = self.streaming_metadata else: - _dict['spelling'] = self.spelling.to_dict() - if hasattr(self, 'debug') and self.debug is not None: - _dict['debug'] = self.debug + _dict['streaming_metadata'] = self.streaming_metadata.to_dict() return _dict def _to_dict(self): @@ -14547,137 +18122,120 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageInputOptions object.""" + """Return a `str` version of this CompleteItem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageInputOptions') -> bool: + def __eq__(self, other: 'CompleteItem') -> 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: 'StatelessMessageInputOptions') -> bool: + def __ne__(self, other: 'CompleteItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatelessMessageResponse: +class GenerativeAITaskContentGroundedAnswering(GenerativeAITask): """ - A stateless response from the watsonx Assistant service. + GenerativeAITaskContentGroundedAnswering. - :param MessageOutput output: Assistant output to be rendered or processed by the - client. - :param StatelessMessageContext context: Context data for the conversation. You - can use this property to access context variables. The context is not stored by - the assistant; to maintain session state, include the context from the response - in the next message. - :param MessageOutput masked_output: (optional) Assistant output to be rendered - or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes the - input text. All private data is masked or removed. - :param str user_id: (optional) A string value that identifies the user who is - interacting with the assistant. The client must provide a unique identifier for - each individual end user who accesses the application. For user-based plans, - this user ID is used to identify unique users for billing purposes. This string - cannot contain carriage return, newline, or tab characters. If no value is - specified in the input, **user_id** is automatically set to the value of - **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the global - system context. + :param str task: (optional) The type of generative ai task. + :param bool is_idk_response: (optional) Whether response was an idk response. + :param bool is_hap_detected: (optional) Whether response was a hap response. + :param GenerativeAITaskConfidenceScores confidence_scores: (optional) The + confidence scores for determining whether to show the generated response or an + “I don't know” response. + :param str original_response: (optional) The original response returned by the + generative ai. + :param str inferred_query: (optional) Generated from the input text after + auto-correction. If this field is not present, the input text was used as the + query to the generative ai. """ def __init__( self, - output: 'MessageOutput', - context: 'StatelessMessageContext', *, - masked_output: Optional['MessageOutput'] = None, - masked_input: Optional['MessageInput'] = None, - user_id: Optional[str] = None, + task: Optional[str] = None, + is_idk_response: Optional[bool] = None, + is_hap_detected: Optional[bool] = None, + confidence_scores: Optional['GenerativeAITaskConfidenceScores'] = None, + original_response: Optional[str] = None, + inferred_query: Optional[str] = None, ) -> None: """ - Initialize a StatelessMessageResponse object. + Initialize a GenerativeAITaskContentGroundedAnswering object. - :param MessageOutput output: Assistant output to be rendered or processed - by the client. - :param StatelessMessageContext context: Context data for the conversation. - You can use this property to access context variables. The context is not - stored by the assistant; to maintain session state, include the context - from the response in the next message. - :param MessageOutput masked_output: (optional) Assistant output to be - rendered or processed by the client. All private data is masked or removed. - :param MessageInput masked_input: (optional) An input object that includes - the input text. All private data is masked or removed. - :param str user_id: (optional) A string value that identifies the user who - is interacting with the assistant. The client must provide a unique - identifier for each individual end user who accesses the application. For - user-based plans, this user ID is used to identify unique users for billing - purposes. This string cannot contain carriage return, newline, or tab - characters. If no value is specified in the input, **user_id** is - automatically set to the value of **context.global.session_id**. - **Note:** This property is the same as the **user_id** property in the - global system context. + :param str task: (optional) The type of generative ai task. + :param bool is_idk_response: (optional) Whether response was an idk + response. + :param bool is_hap_detected: (optional) Whether response was a hap + response. + :param GenerativeAITaskConfidenceScores confidence_scores: (optional) The + confidence scores for determining whether to show the generated response or + an “I don't know” response. + :param str original_response: (optional) The original response returned by + the generative ai. + :param str inferred_query: (optional) Generated from the input text after + auto-correction. If this field is not present, the input text was used as + the query to the generative ai. """ - self.output = output - self.context = context - self.masked_output = masked_output - self.masked_input = masked_input - self.user_id = user_id + # pylint: disable=super-init-not-called + self.task = task + self.is_idk_response = is_idk_response + self.is_hap_detected = is_hap_detected + self.confidence_scores = confidence_scores + self.original_response = original_response + self.inferred_query = inferred_query @classmethod - def from_dict(cls, _dict: Dict) -> 'StatelessMessageResponse': - """Initialize a StatelessMessageResponse object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'GenerativeAITaskContentGroundedAnswering': + """Initialize a GenerativeAITaskContentGroundedAnswering object from a json dictionary.""" args = {} - if (output := _dict.get('output')) is not None: - args['output'] = MessageOutput.from_dict(output) - else: - raise ValueError( - 'Required property \'output\' not present in StatelessMessageResponse JSON' - ) - if (context := _dict.get('context')) is not None: - args['context'] = StatelessMessageContext.from_dict(context) - else: - raise ValueError( - 'Required property \'context\' not present in StatelessMessageResponse JSON' - ) - if (masked_output := _dict.get('masked_output')) is not None: - args['masked_output'] = MessageOutput.from_dict(masked_output) - if (masked_input := _dict.get('masked_input')) is not None: - args['masked_input'] = MessageInput.from_dict(masked_input) - if (user_id := _dict.get('user_id')) is not None: - args['user_id'] = user_id + if (task := _dict.get('task')) is not None: + args['task'] = task + if (is_idk_response := _dict.get('is_idk_response')) is not None: + args['is_idk_response'] = is_idk_response + if (is_hap_detected := _dict.get('is_hap_detected')) is not None: + args['is_hap_detected'] = is_hap_detected + if (confidence_scores := _dict.get('confidence_scores')) is not None: + args[ + 'confidence_scores'] = GenerativeAITaskConfidenceScores.from_dict( + confidence_scores) + if (original_response := _dict.get('original_response')) is not None: + args['original_response'] = original_response + if (inferred_query := _dict.get('inferred_query')) is not None: + args['inferred_query'] = inferred_query return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatelessMessageResponse object from a json dictionary.""" + """Initialize a GenerativeAITaskContentGroundedAnswering 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, 'output') and self.output is not None: - if isinstance(self.output, dict): - _dict['output'] = self.output - else: - _dict['output'] = self.output.to_dict() - if hasattr(self, 'context') and self.context is not None: - if isinstance(self.context, dict): - _dict['context'] = self.context - else: - _dict['context'] = self.context.to_dict() - if hasattr(self, 'masked_output') and self.masked_output is not None: - if isinstance(self.masked_output, dict): - _dict['masked_output'] = self.masked_output - else: - _dict['masked_output'] = self.masked_output.to_dict() - if hasattr(self, 'masked_input') and self.masked_input is not None: - if isinstance(self.masked_input, dict): - _dict['masked_input'] = self.masked_input + if hasattr(self, 'task') and self.task is not None: + _dict['task'] = self.task + if hasattr(self, + 'is_idk_response') and self.is_idk_response is not None: + _dict['is_idk_response'] = self.is_idk_response + if hasattr(self, + 'is_hap_detected') and self.is_hap_detected is not None: + _dict['is_hap_detected'] = self.is_hap_detected + if hasattr(self, + 'confidence_scores') and self.confidence_scores is not None: + if isinstance(self.confidence_scores, dict): + _dict['confidence_scores'] = self.confidence_scores else: - _dict['masked_input'] = self.masked_input.to_dict() - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id + _dict['confidence_scores'] = self.confidence_scores.to_dict() + if hasattr(self, + 'original_response') and self.original_response is not None: + _dict['original_response'] = self.original_response + if hasattr(self, 'inferred_query') and self.inferred_query is not None: + _dict['inferred_query'] = self.inferred_query return _dict def _to_dict(self): @@ -14685,58 +18243,79 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatelessMessageResponse object.""" + """Return a `str` version of this GenerativeAITaskContentGroundedAnswering object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatelessMessageResponse') -> bool: + def __eq__(self, other: 'GenerativeAITaskContentGroundedAnswering') -> 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: 'StatelessMessageResponse') -> bool: + def __ne__(self, other: 'GenerativeAITaskContentGroundedAnswering') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class StatusError: +class GenerativeAITaskGeneralPurposeAnswering(GenerativeAITask): """ - An object describing an error that occurred during processing of an asynchronous - operation. + GenerativeAITaskGeneralPurposeAnswering. - :param str message: (optional) The text of the error message. + :param str task: (optional) The type of generative ai task. + :param bool is_idk_response: (optional) Whether response was an idk response. + :param bool is_hap_detected: (optional) Whether response was a hap response. """ def __init__( self, *, - message: Optional[str] = None, + task: Optional[str] = None, + is_idk_response: Optional[bool] = None, + is_hap_detected: Optional[bool] = None, ) -> None: """ - Initialize a StatusError object. + Initialize a GenerativeAITaskGeneralPurposeAnswering object. - :param str message: (optional) The text of the error message. + :param str task: (optional) The type of generative ai task. + :param bool is_idk_response: (optional) Whether response was an idk + response. + :param bool is_hap_detected: (optional) Whether response was a hap + response. """ - self.message = message + # pylint: disable=super-init-not-called + self.task = task + self.is_idk_response = is_idk_response + self.is_hap_detected = is_hap_detected @classmethod - def from_dict(cls, _dict: Dict) -> 'StatusError': - """Initialize a StatusError object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'GenerativeAITaskGeneralPurposeAnswering': + """Initialize a GenerativeAITaskGeneralPurposeAnswering object from a json dictionary.""" args = {} - if (message := _dict.get('message')) is not None: - args['message'] = message + if (task := _dict.get('task')) is not None: + args['task'] = task + if (is_idk_response := _dict.get('is_idk_response')) is not None: + args['is_idk_response'] = is_idk_response + if (is_hap_detected := _dict.get('is_hap_detected')) is not None: + args['is_hap_detected'] = is_hap_detected return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a StatusError object from a json dictionary.""" + """Initialize a GenerativeAITaskGeneralPurposeAnswering 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, 'message') and self.message is not None: - _dict['message'] = self.message + if hasattr(self, 'task') and self.task is not None: + _dict['task'] = self.task + if hasattr(self, + 'is_idk_response') and self.is_idk_response is not None: + _dict['is_idk_response'] = self.is_idk_response + if hasattr(self, + 'is_hap_detected') and self.is_hap_detected is not None: + _dict['is_hap_detected'] = self.is_hap_detected return _dict def _to_dict(self): @@ -14744,71 +18323,68 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this StatusError object.""" + """Return a `str` version of this GenerativeAITaskGeneralPurposeAnswering object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'StatusError') -> bool: + def __eq__(self, other: 'GenerativeAITaskGeneralPurposeAnswering') -> 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: 'StatusError') -> bool: + def __ne__(self, other: 'GenerativeAITaskGeneralPurposeAnswering') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TurnEventActionSource: +class LogMessageSourceAction(LogMessageSource): """ - TurnEventActionSource. + An object that identifies the dialog element that generated the error message. - :param str type: (optional) The type of turn event. - :param str action: (optional) An action that was visited during processing of - the message. - :param str action_title: (optional) The title of the action. - :param str condition: (optional) The condition that triggered the dialog node. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. """ def __init__( self, - *, - type: Optional[str] = None, - action: Optional[str] = None, - action_title: Optional[str] = None, - condition: Optional[str] = None, + type: str, + action: str, ) -> None: """ - Initialize a TurnEventActionSource object. + Initialize a LogMessageSourceAction object. - :param str type: (optional) The type of turn event. - :param str action: (optional) An action that was visited during processing - of the message. - :param str action_title: (optional) The title of the action. - :param str condition: (optional) The condition that triggered the dialog - node. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. """ + # pylint: disable=super-init-not-called self.type = type self.action = action - self.action_title = action_title - self.condition = condition @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventActionSource': - """Initialize a TurnEventActionSource object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': + """Initialize a LogMessageSourceAction object from a json dictionary.""" args = {} if (type := _dict.get('type')) is not None: args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceAction JSON' + ) if (action := _dict.get('action')) is not None: args['action'] = action - if (action_title := _dict.get('action_title')) is not None: - args['action_title'] = action_title - if (condition := _dict.get('condition')) is not None: - args['condition'] = condition + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceAction JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventActionSource object from a json dictionary.""" + """Initialize a LogMessageSourceAction object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -14818,10 +18394,6 @@ def to_dict(self) -> Dict: _dict['type'] = self.type if hasattr(self, 'action') and self.action is not None: _dict['action'] = self.action - if hasattr(self, 'action_title') and self.action_title is not None: - _dict['action_title'] = self.action_title - if hasattr(self, 'condition') and self.condition is not None: - _dict['condition'] = self.condition return _dict def _to_dict(self): @@ -14829,90 +18401,68 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventActionSource object.""" + """Return a `str` version of this LogMessageSourceAction object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventActionSource') -> bool: + def __eq__(self, other: 'LogMessageSourceAction') -> 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: 'TurnEventActionSource') -> bool: + def __ne__(self, other: 'LogMessageSourceAction') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - - class TypeEnum(str, Enum): - """ - The type of turn event. - """ - - ACTION = 'action' - - -class TurnEventCalloutCallout: - """ - TurnEventCalloutCallout. - - :param str type: (optional) The type of callout. Currently, the only supported - value is `integration_interaction` (for calls to extensions). - :param dict internal: (optional) For internal use only. - :param str result_variable: (optional) The name of the variable where the - callout result is stored. - :param TurnEventCalloutCalloutRequest request: (optional) The request object - executed to the external server specified by the extension. - :param TurnEventCalloutCalloutResponse response: (optional) The response object - received by the external server made by the extension. + + +class LogMessageSourceDialogNode(LogMessageSource): + """ + An object that identifies the dialog element that generated the error message. + + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str dialog_node: The unique identifier of the dialog node that generated + the error message. """ def __init__( self, - *, - type: Optional[str] = None, - internal: Optional[dict] = None, - result_variable: Optional[str] = None, - request: Optional['TurnEventCalloutCalloutRequest'] = None, - response: Optional['TurnEventCalloutCalloutResponse'] = None, + type: str, + dialog_node: str, ) -> None: """ - Initialize a TurnEventCalloutCallout object. + Initialize a LogMessageSourceDialogNode object. - :param str type: (optional) The type of callout. Currently, the only - supported value is `integration_interaction` (for calls to extensions). - :param dict internal: (optional) For internal use only. - :param str result_variable: (optional) The name of the variable where the - callout result is stored. - :param TurnEventCalloutCalloutRequest request: (optional) The request - object executed to the external server specified by the extension. - :param TurnEventCalloutCalloutResponse response: (optional) The response - object received by the external server made by the extension. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str dialog_node: The unique identifier of the dialog node that + generated the error message. """ + # pylint: disable=super-init-not-called self.type = type - self.internal = internal - self.result_variable = result_variable - self.request = request - self.response = response + self.dialog_node = dialog_node @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCallout': - """Initialize a TurnEventCalloutCallout object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': + """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" args = {} if (type := _dict.get('type')) is not None: args['type'] = type - if (internal := _dict.get('internal')) is not None: - args['internal'] = internal - if (result_variable := _dict.get('result_variable')) is not None: - args['result_variable'] = result_variable - if (request := _dict.get('request')) is not None: - args['request'] = TurnEventCalloutCalloutRequest.from_dict(request) - if (response := _dict.get('response')) is not None: - args['response'] = TurnEventCalloutCalloutResponse.from_dict( - response) + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' + ) + if (dialog_node := _dict.get('dialog_node')) is not None: + args['dialog_node'] = dialog_node + else: + raise ValueError( + 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventCalloutCallout object from a json dictionary.""" + """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -14920,21 +18470,8 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'internal') and self.internal is not None: - _dict['internal'] = self.internal - if hasattr(self, - 'result_variable') and self.result_variable is not None: - _dict['result_variable'] = self.result_variable - if hasattr(self, 'request') and self.request is not None: - if isinstance(self.request, dict): - _dict['request'] = self.request - else: - _dict['request'] = self.request.to_dict() - if hasattr(self, 'response') and self.response is not None: - if isinstance(self.response, dict): - _dict['response'] = self.response - else: - _dict['response'] = self.response.to_dict() + if hasattr(self, 'dialog_node') and self.dialog_node is not None: + _dict['dialog_node'] = self.dialog_node return _dict def _to_dict(self): @@ -14942,112 +18479,102 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventCalloutCallout object.""" + """Return a `str` version of this LogMessageSourceDialogNode object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventCalloutCallout') -> bool: + def __eq__(self, other: 'LogMessageSourceDialogNode') -> 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: 'TurnEventCalloutCallout') -> bool: + def __ne__(self, other: 'LogMessageSourceDialogNode') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): - """ - The type of callout. Currently, the only supported value is - `integration_interaction` (for calls to extensions). - """ - - INTEGRATION_INTERACTION = 'integration_interaction' - -class TurnEventCalloutCalloutRequest: +class LogMessageSourceHandler(LogMessageSource): """ - TurnEventCalloutCalloutRequest. + An object that identifies the dialog element that generated the error message. - :param str method: (optional) The REST method of the request. - :param str url: (optional) The host URL of the request call. - :param str path: (optional) The URL path of the request call. - :param str query_parameters: (optional) Any query parameters appended to the URL - of the request call. - :param dict headers_: (optional) Any headers included in the request call. - :param dict body: (optional) Contains the response of the external server or an - object. In cases like timeouts or connections errors, it will contain details of - why the callout to the external server failed. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. + :param str step: (optional) The unique identifier of the step that generated the + error message. + :param str handler: The unique identifier of the handler that generated the + error message. """ def __init__( self, + type: str, + action: str, + handler: str, *, - method: Optional[str] = None, - url: Optional[str] = None, - path: Optional[str] = None, - query_parameters: Optional[str] = None, - headers_: Optional[dict] = None, - body: Optional[dict] = None, + step: Optional[str] = None, ) -> None: """ - Initialize a TurnEventCalloutCalloutRequest object. + Initialize a LogMessageSourceHandler object. - :param str method: (optional) The REST method of the request. - :param str url: (optional) The host URL of the request call. - :param str path: (optional) The URL path of the request call. - :param str query_parameters: (optional) Any query parameters appended to - the URL of the request call. - :param dict headers_: (optional) Any headers included in the request call. - :param dict body: (optional) Contains the response of the external server - or an object. In cases like timeouts or connections errors, it will contain - details of why the callout to the external server failed. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str handler: The unique identifier of the handler that generated the + error message. + :param str step: (optional) The unique identifier of the step that + generated the error message. """ - self.method = method - self.url = url - self.path = path - self.query_parameters = query_parameters - self.headers_ = headers_ - self.body = body + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step + self.handler = handler @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCalloutRequest': - """Initialize a TurnEventCalloutCalloutRequest object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': + """Initialize a LogMessageSourceHandler object from a json dictionary.""" args = {} - if (method := _dict.get('method')) is not None: - args['method'] = method - if (url := _dict.get('url')) is not None: - args['url'] = url - if (path := _dict.get('path')) is not None: - args['path'] = path - if (query_parameters := _dict.get('query_parameters')) is not None: - args['query_parameters'] = query_parameters - if (headers_ := _dict.get('headers')) is not None: - args['headers_'] = headers_ - if (body := _dict.get('body')) is not None: - args['body'] = body + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceHandler JSON' + ) + if (action := _dict.get('action')) is not None: + args['action'] = action + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceHandler JSON' + ) + if (step := _dict.get('step')) is not None: + args['step'] = step + if (handler := _dict.get('handler')) is not None: + args['handler'] = handler + else: + raise ValueError( + 'Required property \'handler\' not present in LogMessageSourceHandler JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventCalloutCalloutRequest object from a json dictionary.""" + """Initialize a LogMessageSourceHandler 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, 'method') and self.method is not None: - _dict['method'] = self.method - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path - if hasattr(self, - 'query_parameters') and self.query_parameters is not None: - _dict['query_parameters'] = self.query_parameters - if hasattr(self, 'headers_') and self.headers_ is not None: - _dict['headers'] = self.headers_ - if hasattr(self, 'body') and self.body is not None: - _dict['body'] = self.body + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step + if hasattr(self, 'handler') and self.handler is not None: + _dict['handler'] = self.handler return _dict def _to_dict(self): @@ -15055,88 +18582,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventCalloutCalloutRequest object.""" + """Return a `str` version of this LogMessageSourceHandler object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventCalloutCalloutRequest') -> bool: + def __eq__(self, other: 'LogMessageSourceHandler') -> 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: 'TurnEventCalloutCalloutRequest') -> bool: + def __ne__(self, other: 'LogMessageSourceHandler') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class MethodEnum(str, Enum): - """ - The REST method of the request. - """ - - GET = 'get' - POST = 'post' - PUT = 'put' - DELETE = 'delete' - PATCH = 'patch' - -class TurnEventCalloutCalloutResponse: +class LogMessageSourceStep(LogMessageSource): """ - TurnEventCalloutCalloutResponse. + An object that identifies the dialog element that generated the error message. - :param str body: (optional) The final response string. This response is a - composition of every partial chunk received from the stream. - :param int status_code: (optional) The final status code of the response. - :param dict last_event: (optional) The response from the last chunk received - from the response stream. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the error + message. + :param str step: The unique identifier of the step that generated the error + message. """ def __init__( self, - *, - body: Optional[str] = None, - status_code: Optional[int] = None, - last_event: Optional[dict] = None, + type: str, + action: str, + step: str, ) -> None: """ - Initialize a TurnEventCalloutCalloutResponse object. + Initialize a LogMessageSourceStep object. - :param str body: (optional) The final response string. This response is a - composition of every partial chunk received from the stream. - :param int status_code: (optional) The final status code of the response. - :param dict last_event: (optional) The response from the last chunk - received from the response stream. + :param str type: A string that indicates the type of dialog element that + generated the error message. + :param str action: The unique identifier of the action that generated the + error message. + :param str step: The unique identifier of the step that generated the error + message. """ - self.body = body - self.status_code = status_code - self.last_event = last_event + # pylint: disable=super-init-not-called + self.type = type + self.action = action + self.step = step @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutCalloutResponse': - """Initialize a TurnEventCalloutCalloutResponse object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': + """Initialize a LogMessageSourceStep object from a json dictionary.""" args = {} - if (body := _dict.get('body')) is not None: - args['body'] = body - if (status_code := _dict.get('status_code')) is not None: - args['status_code'] = status_code - if (last_event := _dict.get('last_event')) is not None: - args['last_event'] = last_event + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in LogMessageSourceStep JSON' + ) + if (action := _dict.get('action')) is not None: + args['action'] = action + else: + raise ValueError( + 'Required property \'action\' not present in LogMessageSourceStep JSON' + ) + if (step := _dict.get('step')) is not None: + args['step'] = step + else: + raise ValueError( + 'Required property \'step\' not present in LogMessageSourceStep JSON' + ) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventCalloutCalloutResponse object from a json dictionary.""" + """Initialize a LogMessageSourceStep 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, 'body') and self.body is not None: - _dict['body'] = self.body - if hasattr(self, 'status_code') and self.status_code is not None: - _dict['status_code'] = self.status_code - if hasattr(self, 'last_event') and self.last_event is not None: - _dict['last_event'] = self.last_event + if hasattr(self, 'type') and self.type is not None: + _dict['type'] = self.type + if hasattr(self, 'action') and self.action is not None: + _dict['action'] = self.action + if hasattr(self, 'step') and self.step is not None: + _dict['step'] = self.step return _dict def _to_dict(self): @@ -15144,59 +18674,112 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventCalloutCalloutResponse object.""" + """Return a `str` version of this LogMessageSourceStep object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventCalloutCalloutResponse') -> bool: + def __eq__(self, other: 'LogMessageSourceStep') -> 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: 'TurnEventCalloutCalloutResponse') -> bool: + def __ne__(self, other: 'LogMessageSourceStep') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TurnEventCalloutError: +class MessageOutputDebugTurnEventTurnEventActionFinished( + MessageOutputDebugTurnEvent): """ - TurnEventCalloutError. + MessageOutputDebugTurnEventTurnEventActionFinished. - :param str message: (optional) Any error message returned by a failed call to an - external service. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables at + the time the action finished. """ def __init__( self, *, - message: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + action_variables: Optional[dict] = None, ) -> None: """ - Initialize a TurnEventCalloutError object. + Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object. - :param str message: (optional) Any error message returned by a failed call - to an external service. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action finished processing. + :param dict action_variables: (optional) The state of all action variables + at the time the action finished. """ - self.message = message + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason + self.action_variables = action_variables @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventCalloutError': - """Initialize a TurnEventCalloutError object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventActionFinished': + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" args = {} - if (message := _dict.get('message')) is not None: - args['message'] = message + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason + if (action_variables := _dict.get('action_variables')) is not None: + args['action_variables'] = action_variables return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventCalloutError object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished 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, 'message') and self.message is not None: - _dict['message'] = self.message + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason + if hasattr(self, + 'action_variables') and self.action_variables is not None: + _dict['action_variables'] = self.action_variables return _dict def _to_dict(self): @@ -15204,84 +18787,115 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventCalloutError object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionFinished object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventCalloutError') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> 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: 'TurnEventCalloutError') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ -class TurnEventNodeSource: + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + class ReasonEnum(str, Enum): + """ + The reason the action finished processing. + """ + + ALL_STEPS_DONE = 'all_steps_done' + NO_STEPS_VISITED = 'no_steps_visited' + ENDED_BY_STEP = 'ended_by_step' + CONNECT_TO_AGENT = 'connect_to_agent' + MAX_RETRIES_REACHED = 'max_retries_reached' + FALLBACK = 'fallback' + + +class MessageOutputDebugTurnEventTurnEventActionRoutingDenied( + MessageOutputDebugTurnEvent): """ - TurnEventNodeSource. + MessageOutputDebugTurnEventTurnEventActionRoutingDenied. - :param str type: (optional) The type of turn event. - :param str dialog_node: (optional) A dialog node that was visited during - processing of the input message. - :param str title: (optional) The title of the dialog node. - :param str condition: (optional) The condition that triggered the dialog node. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action was visited. """ def __init__( self, *, - type: Optional[str] = None, - dialog_node: Optional[str] = None, - title: Optional[str] = None, - condition: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, ) -> None: """ - Initialize a TurnEventNodeSource object. + Initialize a MessageOutputDebugTurnEventTurnEventActionRoutingDenied object. - :param str type: (optional) The type of turn event. - :param str dialog_node: (optional) A dialog node that was visited during - processing of the input message. - :param str title: (optional) The title of the dialog node. - :param str condition: (optional) The condition that triggered the dialog - node. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action was visited. """ - self.type = type - self.dialog_node = dialog_node - self.title = title - self.condition = condition + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.condition_type = condition_type + self.reason = reason @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventNodeSource': - """Initialize a TurnEventNodeSource object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied': + """Initialize a MessageOutputDebugTurnEventTurnEventActionRoutingDenied object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - if (dialog_node := _dict.get('dialog_node')) is not None: - args['dialog_node'] = dialog_node - if (title := _dict.get('title')) is not None: - args['title'] = title - if (condition := _dict.get('condition')) is not None: - args['condition'] = condition + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventNodeSource object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionRoutingDenied 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 - if hasattr(self, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'condition') and self.condition is not None: - _dict['condition'] = self.condition + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason return _dict def _to_dict(self): @@ -15289,66 +18903,133 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventNodeSource object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionRoutingDenied object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventNodeSource') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied' + ) -> 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: 'TurnEventNodeSource') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventActionRoutingDenied' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class TypeEnum(str, Enum): + class ConditionTypeEnum(str, Enum): """ - The type of turn event. + The type of condition (if any) that is defined for the action. """ - DIALOG_NODE = 'dialog_node' + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + class ReasonEnum(str, Enum): + """ + The reason the action was visited. + """ + ACTION_CONDITIONS_FAILED = 'action_conditions_failed' -class TurnEventSearchError: + +class MessageOutputDebugTurnEventTurnEventActionVisited( + MessageOutputDebugTurnEvent): """ - TurnEventSearchError. + MessageOutputDebugTurnEventTurnEventActionVisited. - :param str message: (optional) Any error message returned by a failed call to a - search skill. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the call + to the action is stored. Included only if **reason**=`subaction_return`. """ def __init__( self, *, - message: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, + condition_type: Optional[str] = None, + reason: Optional[str] = None, + result_variable: Optional[str] = None, ) -> None: """ - Initialize a TurnEventSearchError object. + Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. - :param str message: (optional) Any error message returned by a failed call - to a search skill. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action was visited. + :param str result_variable: (optional) The variable where the result of the + call to the action is stored. Included only if + **reason**=`subaction_return`. """ - self.message = message + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.action_start_time = action_start_time + self.condition_type = condition_type + self.reason = reason + self.result_variable = result_variable @classmethod - def from_dict(cls, _dict: Dict) -> 'TurnEventSearchError': - """Initialize a TurnEventSearchError object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventActionVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" args = {} - if (message := _dict.get('message')) is not None: - args['message'] = message + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason + if (result_variable := _dict.get('result_variable')) is not None: + args['result_variable'] = result_variable return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TurnEventSearchError object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited 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, 'message') and self.message is not None: - _dict['message'] = self.message + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason + if hasattr(self, + 'result_variable') and self.result_variable is not None: + _dict['result_variable'] = self.result_variable return _dict def _to_dict(self): @@ -15356,65 +19037,120 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TurnEventSearchError object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TurnEventSearchError') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> 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: 'TurnEventSearchError') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' -class UpdateEnvironmentOrchestration: + class ReasonEnum(str, Enum): + """ + The reason the action was visited. + """ + + INTENT = 'intent' + INVOKE_SUBACTION = 'invoke_subaction' + SUBACTION_RETURN = 'subaction_return' + INVOKE_EXTERNAL = 'invoke_external' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + AGENT_REQUESTED = 'agent_requested' + STEP_VALIDATION_FAILED = 'step_validation_failed' + NO_ACTION_MATCHES = 'no_action_matches' + + +class MessageOutputDebugTurnEventTurnEventCallout(MessageOutputDebugTurnEvent): """ - The search skill orchestration settings for the environment. + MessageOutputDebugTurnEventTurnEventCallout. - :param bool search_skill_fallback: (optional) Whether to fall back to a search - skill when responding to messages that do not match any intent or action defined - in dialog or action skills. (If no search skill is configured for the - environment, this property is ignored.). + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ def __init__( self, *, - search_skill_fallback: Optional[bool] = None, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + callout: Optional['TurnEventCalloutCallout'] = None, + error: Optional['TurnEventCalloutError'] = None, ) -> None: """ - Initialize a UpdateEnvironmentOrchestration object. + Initialize a MessageOutputDebugTurnEventTurnEventCallout object. - :param bool search_skill_fallback: (optional) Whether to fall back to a - search skill when responding to messages that do not match any intent or - action defined in dialog or action skills. (If no search skill is - configured for the environment, this property is ignored.). + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param TurnEventCalloutCallout callout: (optional) + :param TurnEventCalloutError error: (optional) """ - self.search_skill_fallback = search_skill_fallback + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.callout = callout + self.error = error @classmethod - def from_dict(cls, _dict: Dict) -> 'UpdateEnvironmentOrchestration': - """Initialize a UpdateEnvironmentOrchestration object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventCallout': + """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" args = {} - if (search_skill_fallback := - _dict.get('search_skill_fallback')) is not None: - args['search_skill_fallback'] = search_skill_fallback + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (callout := _dict.get('callout')) is not None: + args['callout'] = TurnEventCalloutCallout.from_dict(callout) + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventCalloutError.from_dict(error) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a UpdateEnvironmentOrchestration object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventCallout 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, 'search_skill_fallback' - ) and self.search_skill_fallback is not None: - _dict['search_skill_fallback'] = self.search_skill_fallback + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'callout') and self.callout is not None: + if isinstance(self.callout, dict): + _dict['callout'] = self.callout + else: + _dict['callout'] = self.callout.to_dict() + if hasattr(self, 'error') and self.error is not None: + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -15422,57 +19158,91 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this UpdateEnvironmentOrchestration object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventCallout object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'UpdateEnvironmentOrchestration') -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> 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: 'UpdateEnvironmentOrchestration') -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class UpdateEnvironmentReleaseReference: +class MessageOutputDebugTurnEventTurnEventClientActions( + MessageOutputDebugTurnEvent): """ - An object describing the release that is currently deployed in the environment. + MessageOutputDebugTurnEventTurnEventClientActions. - :param str release: (optional) The name of the deployed release. + :param str event: (optional) The type of turn event. + :param TurnEventStepSource source: (optional) + :param List[ClientAction] client_actions: (optional) An array of client actions. """ def __init__( self, *, - release: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventStepSource'] = None, + client_actions: Optional[List['ClientAction']] = None, ) -> None: """ - Initialize a UpdateEnvironmentReleaseReference object. + Initialize a MessageOutputDebugTurnEventTurnEventClientActions object. - :param str release: (optional) The name of the deployed release. + :param str event: (optional) The type of turn event. + :param TurnEventStepSource source: (optional) + :param List[ClientAction] client_actions: (optional) An array of client + actions. """ - self.release = release + # pylint: disable=super-init-not-called + self.event = event + self.source = source + self.client_actions = client_actions @classmethod - def from_dict(cls, _dict: Dict) -> 'UpdateEnvironmentReleaseReference': - """Initialize a UpdateEnvironmentReleaseReference object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventClientActions': + """Initialize a MessageOutputDebugTurnEventTurnEventClientActions object from a json dictionary.""" args = {} - if (release := _dict.get('release')) is not None: - args['release'] = release + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventStepSource.from_dict(source) + if (client_actions := _dict.get('client_actions')) is not None: + args['client_actions'] = [ + ClientAction.from_dict(v) for v in client_actions + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a UpdateEnvironmentReleaseReference object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventClientActions 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, 'release') and self.release is not None: - _dict['release'] = self.release + _dict = {} + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'client_actions') and self.client_actions is not None: + client_actions_list = [] + for v in self.client_actions: + if isinstance(v, dict): + client_actions_list.append(v) + else: + client_actions_list.append(v.to_dict()) + _dict['client_actions'] = client_actions_list return _dict def _to_dict(self): @@ -15480,66 +19250,86 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this UpdateEnvironmentReleaseReference object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventClientActions object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'UpdateEnvironmentReleaseReference') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventClientActions') -> 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: 'UpdateEnvironmentReleaseReference') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventClientActions') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class CompleteItem(RuntimeResponseGeneric): +class MessageOutputDebugTurnEventTurnEventConversationalSearchEnd( + MessageOutputDebugTurnEvent): """ - CompleteItem. + MessageOutputDebugTurnEventTurnEventConversationalSearchEnd. - :param Metadata streaming_metadata: + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. """ def __init__( self, - streaming_metadata: 'Metadata', + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, ) -> None: """ - Initialize a CompleteItem object. + Initialize a MessageOutputDebugTurnEventTurnEventConversationalSearchEnd object. - :param Metadata streaming_metadata: + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. """ # pylint: disable=super-init-not-called - self.streaming_metadata = streaming_metadata + self.event = event + self.source = source + self.condition_type = condition_type @classmethod - def from_dict(cls, _dict: Dict) -> 'CompleteItem': - """Initialize a CompleteItem object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd': + """Initialize a MessageOutputDebugTurnEventTurnEventConversationalSearchEnd object from a json dictionary.""" args = {} - if (streaming_metadata := _dict.get('streaming_metadata')) is not None: - args['streaming_metadata'] = Metadata.from_dict(streaming_metadata) - else: - raise ValueError( - 'Required property \'streaming_metadata\' not present in CompleteItem JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a CompleteItem object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventConversationalSearchEnd 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, - 'streaming_metadata') and self.streaming_metadata is not None: - if isinstance(self.streaming_metadata, dict): - _dict['streaming_metadata'] = self.streaming_metadata + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source else: - _dict['streaming_metadata'] = self.streaming_metadata.to_dict() + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type return _dict def _to_dict(self): @@ -15547,77 +19337,131 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this CompleteItem object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventConversationalSearchEnd object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'CompleteItem') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd' + ) -> 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: 'CompleteItem') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventConversationalSearchEnd' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ -class LogMessageSourceAction(LogMessageSource): + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + +class MessageOutputDebugTurnEventTurnEventGenerativeAICalled( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventGenerativeAICalled. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the error - message. + :param str event: (optional) The type of turn event. + :param dict source: (optional) For internal use only. + :param str generative_ai_start_time: (optional) The time when generative ai + started processing the message. + :param GenerativeAITask generative_ai: (optional) + :param TurnEventGenerativeAICalledCallout callout: (optional) + :param TurnEventGenerativeAICalledMetrics metrics: (optional) """ def __init__( self, - type: str, - action: str, + *, + event: Optional[str] = None, + source: Optional[dict] = None, + generative_ai_start_time: Optional[str] = None, + generative_ai: Optional['GenerativeAITask'] = None, + callout: Optional['TurnEventGenerativeAICalledCallout'] = None, + metrics: Optional['TurnEventGenerativeAICalledMetrics'] = None, ) -> None: """ - Initialize a LogMessageSourceAction object. + Initialize a MessageOutputDebugTurnEventTurnEventGenerativeAICalled object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. + :param str event: (optional) The type of turn event. + :param dict source: (optional) For internal use only. + :param str generative_ai_start_time: (optional) The time when generative ai + started processing the message. + :param GenerativeAITask generative_ai: (optional) + :param TurnEventGenerativeAICalledCallout callout: (optional) + :param TurnEventGenerativeAICalledMetrics metrics: (optional) """ # pylint: disable=super-init-not-called - self.type = type - self.action = action + self.event = event + self.source = source + self.generative_ai_start_time = generative_ai_start_time + self.generative_ai = generative_ai + self.callout = callout + self.metrics = metrics @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceAction': - """Initialize a LogMessageSourceAction object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled': + """Initialize a MessageOutputDebugTurnEventTurnEventGenerativeAICalled object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceAction JSON' - ) - if (action := _dict.get('action')) is not None: - args['action'] = action - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceAction JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = source + if (generative_ai_start_time := + _dict.get('generative_ai_start_time')) is not None: + args['generative_ai_start_time'] = generative_ai_start_time + if (generative_ai := _dict.get('generative_ai')) is not None: + args['generative_ai'] = GenerativeAITask.from_dict(generative_ai) + if (callout := _dict.get('callout')) is not None: + args['callout'] = TurnEventGenerativeAICalledCallout.from_dict( + callout) + if (metrics := _dict.get('metrics')) is not None: + args['metrics'] = TurnEventGenerativeAICalledMetrics.from_dict( + metrics) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceAction object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventGenerativeAICalled 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 - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'generative_ai_start_time' + ) and self.generative_ai_start_time is not None: + _dict['generative_ai_start_time'] = self.generative_ai_start_time + if hasattr(self, 'generative_ai') and self.generative_ai is not None: + if isinstance(self.generative_ai, dict): + _dict['generative_ai'] = self.generative_ai + else: + _dict['generative_ai'] = self.generative_ai.to_dict() + if hasattr(self, 'callout') and self.callout is not None: + if isinstance(self.callout, dict): + _dict['callout'] = self.callout + else: + _dict['callout'] = self.callout.to_dict() + if hasattr(self, 'metrics') and self.metrics is not None: + if isinstance(self.metrics, dict): + _dict['metrics'] = self.metrics + else: + _dict['metrics'] = self.metrics.to_dict() return _dict def _to_dict(self): @@ -15625,77 +19469,87 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceAction object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventGenerativeAICalled object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceAction') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled' + ) -> 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: 'LogMessageSourceAction') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventGenerativeAICalled' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSourceDialogNode(LogMessageSource): +class MessageOutputDebugTurnEventTurnEventHandlerVisited( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventHandlerVisited. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str dialog_node: The unique identifier of the dialog node that generated - the error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. """ def __init__( self, - type: str, - dialog_node: str, + *, + event: Optional[str] = None, + source: Optional['TurnEventActionSource'] = None, + action_start_time: Optional[str] = None, ) -> None: """ - Initialize a LogMessageSourceDialogNode object. + Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str dialog_node: The unique identifier of the dialog node that - generated the error message. + :param str event: (optional) The type of turn event. + :param TurnEventActionSource source: (optional) + :param str action_start_time: (optional) The time when the action started + processing the message. """ # pylint: disable=super-init-not-called - self.type = type - self.dialog_node = dialog_node + self.event = event + self.source = source + self.action_start_time = action_start_time @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceDialogNode': - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + def from_dict( + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventHandlerVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceDialogNode JSON' - ) - if (dialog_node := _dict.get('dialog_node')) is not None: - args['dialog_node'] = dialog_node - else: - raise ValueError( - 'Required property \'dialog_node\' not present in LogMessageSourceDialogNode JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventActionSource.from_dict(source) + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceDialogNode object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited 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 - if hasattr(self, 'dialog_node') and self.dialog_node is not None: - _dict['dialog_node'] = self.dialog_node + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time return _dict def _to_dict(self): @@ -15703,102 +19557,105 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceDialogNode object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventHandlerVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceDialogNode') -> bool: + def __eq__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> 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: 'LogMessageSourceDialogNode') -> bool: + def __ne__( + self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class LogMessageSourceHandler(LogMessageSource): +class MessageOutputDebugTurnEventTurnEventManualRoute( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventManualRoute. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the error - message. - :param str step: (optional) The unique identifier of the step that generated the - error message. - :param str handler: The unique identifier of the handler that generated the - error message. + :param str event: (optional) The type of turn event. + :param TurnEventStepSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str route_name: (optional) The name of the route. """ def __init__( self, - type: str, - action: str, - handler: str, *, - step: Optional[str] = None, + event: Optional[str] = None, + source: Optional['TurnEventStepSource'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + route_name: Optional[str] = None, ) -> None: """ - Initialize a LogMessageSourceHandler object. + Initialize a MessageOutputDebugTurnEventTurnEventManualRoute object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str handler: The unique identifier of the handler that generated the - error message. - :param str step: (optional) The unique identifier of the step that - generated the error message. + :param str event: (optional) The type of turn event. + :param TurnEventStepSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param str route_name: (optional) The name of the route. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step - self.handler = handler + self.event = event + self.source = source + self.condition_type = condition_type + self.action_start_time = action_start_time + self.route_name = route_name @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceHandler': - """Initialize a LogMessageSourceHandler object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventManualRoute': + """Initialize a MessageOutputDebugTurnEventTurnEventManualRoute object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceHandler JSON' - ) - if (action := _dict.get('action')) is not None: - args['action'] = action - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceHandler JSON' - ) - if (step := _dict.get('step')) is not None: - args['step'] = step - if (handler := _dict.get('handler')) is not None: - args['handler'] = handler - else: - raise ValueError( - 'Required property \'handler\' not present in LogMessageSourceHandler JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventStepSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (route_name := _dict.get('route_name')) is not None: + args['route_name'] = route_name return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceHandler object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventManualRoute 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 - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step - if hasattr(self, 'handler') and self.handler is not None: - _dict['handler'] = self.handler + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'route_name') and self.route_name is not None: + _dict['route_name'] = self.route_name return _dict def _to_dict(self): @@ -15806,91 +19663,93 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceHandler object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventManualRoute object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceHandler') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventManualRoute') -> 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: 'LogMessageSourceHandler') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventManualRoute') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ -class LogMessageSourceStep(LogMessageSource): + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + + +class MessageOutputDebugTurnEventTurnEventNodeVisited( + MessageOutputDebugTurnEvent): """ - An object that identifies the dialog element that generated the error message. + MessageOutputDebugTurnEventTurnEventNodeVisited. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the error - message. - :param str step: The unique identifier of the step that generated the error - message. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ def __init__( self, - type: str, - action: str, - step: str, + *, + event: Optional[str] = None, + source: Optional['TurnEventNodeSource'] = None, + reason: Optional[str] = None, ) -> None: """ - Initialize a LogMessageSourceStep object. + Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object. - :param str type: A string that indicates the type of dialog element that - generated the error message. - :param str action: The unique identifier of the action that generated the - error message. - :param str step: The unique identifier of the step that generated the error - message. + :param str event: (optional) The type of turn event. + :param TurnEventNodeSource source: (optional) + :param str reason: (optional) The reason the dialog node was visited. """ # pylint: disable=super-init-not-called - self.type = type - self.action = action - self.step = step + self.event = event + self.source = source + self.reason = reason @classmethod - def from_dict(cls, _dict: Dict) -> 'LogMessageSourceStep': - """Initialize a LogMessageSourceStep object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventNodeVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" args = {} - if (type := _dict.get('type')) is not None: - args['type'] = type - else: - raise ValueError( - 'Required property \'type\' not present in LogMessageSourceStep JSON' - ) - if (action := _dict.get('action')) is not None: - args['action'] = action - else: - raise ValueError( - 'Required property \'action\' not present in LogMessageSourceStep JSON' - ) - if (step := _dict.get('step')) is not None: - args['step'] = step - else: - raise ValueError( - 'Required property \'step\' not present in LogMessageSourceStep JSON' - ) + if (event := _dict.get('event')) is not None: + args['event'] = event + if (source := _dict.get('source')) is not None: + args['source'] = TurnEventNodeSource.from_dict(source) + if (reason := _dict.get('reason')) is not None: + args['reason'] = reason return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a LogMessageSourceStep object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited 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 - if hasattr(self, 'action') and self.action is not None: - _dict['action'] = self.action - if hasattr(self, 'step') and self.step is not None: - _dict['step'] = self.step + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'source') and self.source is not None: + if isinstance(self.source, dict): + _dict['source'] = self.source + else: + _dict['source'] = self.source.to_dict() + if hasattr(self, 'reason') and self.reason is not None: + _dict['reason'] = self.reason return _dict def _to_dict(self): @@ -15898,34 +19757,43 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this LogMessageSourceStep object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventNodeVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'LogMessageSourceStep') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> 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: 'LogMessageSourceStep') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ReasonEnum(str, Enum): + """ + The reason the dialog node was visited. + """ -class MessageOutputDebugTurnEventTurnEventActionFinished( - MessageOutputDebugTurnEvent): + WELCOME = 'welcome' + BRANCH_START = 'branch_start' + TOPIC_SWITCH = 'topic_switch' + TOPIC_RETURN = 'topic_return' + TOPIC_SWITCH_WITHOUT_RETURN = 'topic_switch_without_return' + JUMP = 'jump' + + +class MessageOutputDebugTurnEventTurnEventSearch(MessageOutputDebugTurnEvent): """ - MessageOutputDebugTurnEventTurnEventActionFinished. + MessageOutputDebugTurnEventTurnEventSearch. :param str event: (optional) The type of turn event. :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. - :param str condition_type: (optional) The type of condition (if any) that is - defined for the action. - :param str reason: (optional) The reason the action finished processing. - :param dict action_variables: (optional) The state of all action variables at - the time the action finished. + :param TurnEventSearchError error: (optional) """ def __init__( @@ -15933,55 +19801,36 @@ def __init__( *, event: Optional[str] = None, source: Optional['TurnEventActionSource'] = None, - action_start_time: Optional[str] = None, - condition_type: Optional[str] = None, - reason: Optional[str] = None, - action_variables: Optional[dict] = None, + error: Optional['TurnEventSearchError'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object. + Initialize a MessageOutputDebugTurnEventTurnEventSearch object. :param str event: (optional) The type of turn event. :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. - :param str condition_type: (optional) The type of condition (if any) that - is defined for the action. - :param str reason: (optional) The reason the action finished processing. - :param dict action_variables: (optional) The state of all action variables - at the time the action finished. + :param TurnEventSearchError error: (optional) """ # pylint: disable=super-init-not-called self.event = event self.source = source - self.action_start_time = action_start_time - self.condition_type = condition_type - self.reason = reason - self.action_variables = action_variables + self.error = error @classmethod - def from_dict( - cls, _dict: Dict - ) -> 'MessageOutputDebugTurnEventTurnEventActionFinished': - """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" + def from_dict(cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventSearch': + """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" args = {} if (event := _dict.get('event')) is not None: args['event'] = event if (source := _dict.get('source')) is not None: args['source'] = TurnEventActionSource.from_dict(source) - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time - if (condition_type := _dict.get('condition_type')) is not None: - args['condition_type'] = condition_type - if (reason := _dict.get('reason')) is not None: - args['reason'] = reason - if (action_variables := _dict.get('action_variables')) is not None: - args['action_variables'] = action_variables + if (error := _dict.get('error')) is not None: + args['error'] = TurnEventSearchError.from_dict(error) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventActionFinished object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -15994,16 +19843,11 @@ def to_dict(self) -> Dict: _dict['source'] = self.source else: _dict['source'] = self.source.to_dict() - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time - if hasattr(self, 'condition_type') and self.condition_type is not None: - _dict['condition_type'] = self.condition_type - if hasattr(self, 'reason') and self.reason is not None: - _dict['reason'] = self.reason - if hasattr(self, - 'action_variables') and self.action_variables is not None: - _dict['action_variables'] = self.action_variables + if hasattr(self, 'error') and self.error is not None: + if isinstance(self.error, dict): + _dict['error'] = self.error + else: + _dict['error'] = self.error.to_dict() return _dict def _to_dict(self): @@ -16011,59 +19855,36 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionFinished object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventSearch object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, other: 'MessageOutputDebugTurnEventTurnEventActionFinished' - ) -> bool: + def __eq__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> 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: 'MessageOutputDebugTurnEventTurnEventActionFinished' - ) -> bool: + def __ne__(self, + other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConditionTypeEnum(str, Enum): - """ - The type of condition (if any) that is defined for the action. - """ - - USER_DEFINED = 'user_defined' - WELCOME = 'welcome' - ANYTHING_ELSE = 'anything_else' - - class ReasonEnum(str, Enum): - """ - The reason the action finished processing. - """ - - ALL_STEPS_DONE = 'all_steps_done' - NO_STEPS_VISITED = 'no_steps_visited' - ENDED_BY_STEP = 'ended_by_step' - CONNECT_TO_AGENT = 'connect_to_agent' - MAX_RETRIES_REACHED = 'max_retries_reached' - FALLBACK = 'fallback' - -class MessageOutputDebugTurnEventTurnEventActionVisited( +class MessageOutputDebugTurnEventTurnEventStepAnswered( MessageOutputDebugTurnEvent): """ - MessageOutputDebugTurnEventTurnEventActionVisited. + MessageOutputDebugTurnEventTurnEventStepAnswered. :param str event: (optional) The type of turn event. :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. :param str condition_type: (optional) The type of condition (if any) that is defined for the action. - :param str reason: (optional) The reason the action was visited. - :param str result_variable: (optional) The variable where the result of the call - to the action is stored. Included only if **reason**=`subaction_return`. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool prompted: (optional) Whether the step was answered in response to a + prompt from the assistant. If this property is `false`, the user provided the + answer without visiting the step. """ def __init__( @@ -16071,56 +19892,51 @@ def __init__( *, event: Optional[str] = None, source: Optional['TurnEventActionSource'] = None, - action_start_time: Optional[str] = None, condition_type: Optional[str] = None, - reason: Optional[str] = None, - result_variable: Optional[str] = None, + action_start_time: Optional[str] = None, + prompted: Optional[bool] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object. + Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object. :param str event: (optional) The type of turn event. :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. :param str condition_type: (optional) The type of condition (if any) that is defined for the action. - :param str reason: (optional) The reason the action was visited. - :param str result_variable: (optional) The variable where the result of the - call to the action is stored. Included only if - **reason**=`subaction_return`. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool prompted: (optional) Whether the step was answered in response + to a prompt from the assistant. If this property is `false`, the user + provided the answer without visiting the step. """ # pylint: disable=super-init-not-called self.event = event self.source = source - self.action_start_time = action_start_time self.condition_type = condition_type - self.reason = reason - self.result_variable = result_variable + self.action_start_time = action_start_time + self.prompted = prompted @classmethod def from_dict( cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventActionVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepAnswered': + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" args = {} if (event := _dict.get('event')) is not None: args['event'] = event if (source := _dict.get('source')) is not None: args['source'] = TurnEventActionSource.from_dict(source) - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time if (condition_type := _dict.get('condition_type')) is not None: args['condition_type'] = condition_type - if (reason := _dict.get('reason')) is not None: - args['reason'] = reason - if (result_variable := _dict.get('result_variable')) is not None: - args['result_variable'] = result_variable + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (prompted := _dict.get('prompted')) is not None: + args['prompted'] = prompted return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventActionVisited object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -16133,16 +19949,13 @@ def to_dict(self) -> Dict: _dict['source'] = self.source else: _dict['source'] = self.source.to_dict() - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time if hasattr(self, 'condition_type') and self.condition_type is not None: _dict['condition_type'] = self.condition_type - if hasattr(self, 'reason') and self.reason is not None: - _dict['reason'] = self.reason if hasattr(self, - 'result_variable') and self.result_variable is not None: - _dict['result_variable'] = self.result_variable + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'prompted') and self.prompted is not None: + _dict['prompted'] = self.prompted return _dict def _to_dict(self): @@ -16150,12 +19963,12 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventActionVisited object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepAnswered object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( self, - other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): return False @@ -16163,7 +19976,7 @@ def __eq__( def __ne__( self, - other: 'MessageOutputDebugTurnEventTurnEventActionVisited') -> bool: + other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -16176,30 +19989,20 @@ class ConditionTypeEnum(str, Enum): WELCOME = 'welcome' ANYTHING_ELSE = 'anything_else' - class ReasonEnum(str, Enum): - """ - The reason the action was visited. - """ - - INTENT = 'intent' - INVOKE_SUBACTION = 'invoke_subaction' - SUBACTION_RETURN = 'subaction_return' - INVOKE_EXTERNAL = 'invoke_external' - TOPIC_SWITCH = 'topic_switch' - TOPIC_RETURN = 'topic_return' - AGENT_REQUESTED = 'agent_requested' - STEP_VALIDATION_FAILED = 'step_validation_failed' - NO_ACTION_MATCHES = 'no_action_matches' - -class MessageOutputDebugTurnEventTurnEventCallout(MessageOutputDebugTurnEvent): +class MessageOutputDebugTurnEventTurnEventStepVisited( + MessageOutputDebugTurnEvent): """ - MessageOutputDebugTurnEventTurnEventCallout. + MessageOutputDebugTurnEventTurnEventStepVisited. :param str event: (optional) The type of turn event. :param TurnEventActionSource source: (optional) - :param TurnEventCalloutCallout callout: (optional) - :param TurnEventCalloutError error: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool has_question: (optional) Whether the step collects a customer + response. """ def __init__( @@ -16207,41 +20010,50 @@ def __init__( *, event: Optional[str] = None, source: Optional['TurnEventActionSource'] = None, - callout: Optional['TurnEventCalloutCallout'] = None, - error: Optional['TurnEventCalloutError'] = None, + condition_type: Optional[str] = None, + action_start_time: Optional[str] = None, + has_question: Optional[bool] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventCallout object. + Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object. :param str event: (optional) The type of turn event. :param TurnEventActionSource source: (optional) - :param TurnEventCalloutCallout callout: (optional) - :param TurnEventCalloutError error: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str action_start_time: (optional) The time when the action started + processing the message. + :param bool has_question: (optional) Whether the step collects a customer + response. """ # pylint: disable=super-init-not-called self.event = event self.source = source - self.callout = callout - self.error = error + self.condition_type = condition_type + self.action_start_time = action_start_time + self.has_question = has_question @classmethod - def from_dict(cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventCallout': - """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepVisited': + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" args = {} if (event := _dict.get('event')) is not None: args['event'] = event if (source := _dict.get('source')) is not None: args['source'] = TurnEventActionSource.from_dict(source) - if (callout := _dict.get('callout')) is not None: - args['callout'] = TurnEventCalloutCallout.from_dict(callout) - if (error := _dict.get('error')) is not None: - args['error'] = TurnEventCalloutError.from_dict(error) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type + if (action_start_time := _dict.get('action_start_time')) is not None: + args['action_start_time'] = action_start_time + if (has_question := _dict.get('has_question')) is not None: + args['has_question'] = has_question return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventCallout object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -16254,16 +20066,13 @@ def to_dict(self) -> Dict: _dict['source'] = self.source else: _dict['source'] = self.source.to_dict() - if hasattr(self, 'callout') and self.callout is not None: - if isinstance(self.callout, dict): - _dict['callout'] = self.callout - else: - _dict['callout'] = self.callout.to_dict() - if hasattr(self, 'error') and self.error is not None: - if isinstance(self.error, dict): - _dict['error'] = self.error - else: - _dict['error'] = self.error.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type + if hasattr(self, + 'action_start_time') and self.action_start_time is not None: + _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'has_question') and self.has_question is not None: + _dict['has_question'] = self.has_question return _dict def _to_dict(self): @@ -16271,85 +20080,92 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventCallout object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, - other: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: + def __eq__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> 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: 'MessageOutputDebugTurnEventTurnEventCallout') -> bool: + def __ne__( + self, + other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + class ConditionTypeEnum(str, Enum): + """ + The type of condition (if any) that is defined for the action. + """ + + USER_DEFINED = 'user_defined' + WELCOME = 'welcome' + ANYTHING_ELSE = 'anything_else' + -class MessageOutputDebugTurnEventTurnEventHandlerVisited( +class MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied( MessageOutputDebugTurnEvent): """ - MessageOutputDebugTurnEventTurnEventHandlerVisited. + MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied. :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. + :param List[RuntimeIntent] intents_denied: (optional) An array of denied + intents. """ def __init__( self, *, event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - action_start_time: Optional[str] = None, + intents_denied: Optional[List['RuntimeIntent']] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object. + Initialize a MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied object. :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str action_start_time: (optional) The time when the action started - processing the message. + :param List[RuntimeIntent] intents_denied: (optional) An array of denied + intents. """ # pylint: disable=super-init-not-called self.event = event - self.source = source - self.action_start_time = action_start_time + self.intents_denied = intents_denied @classmethod def from_dict( - cls, _dict: Dict - ) -> 'MessageOutputDebugTurnEventTurnEventHandlerVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied': + """Initialize a MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied object from a json dictionary.""" args = {} if (event := _dict.get('event')) is not None: args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time + if (intents_denied := _dict.get('intents_denied')) is not None: + args['intents_denied'] = [ + RuntimeIntent.from_dict(v) for v in intents_denied + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventHandlerVisited object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time + if hasattr(self, 'event') and self.event is not None: + _dict['event'] = self.event + if hasattr(self, 'intents_denied') and self.intents_denied is not None: + intents_denied_list = [] + for v in self.intents_denied: + if isinstance(v, dict): + intents_denied_list.append(v) + else: + intents_denied_list.append(v.to_dict()) + _dict['intents_denied'] = intents_denied_list return _dict def _to_dict(self): @@ -16357,11 +20173,12 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventHandlerVisited object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + self, + other: 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied' ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): @@ -16369,58 +20186,67 @@ def __eq__( return self.__dict__ == other.__dict__ def __ne__( - self, other: 'MessageOutputDebugTurnEventTurnEventHandlerVisited' + self, + other: 'MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied' ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebugTurnEventTurnEventNodeVisited( +class MessageOutputDebugTurnEventTurnEventTopicSwitchDenied( MessageOutputDebugTurnEvent): """ - MessageOutputDebugTurnEventTurnEventNodeVisited. + MessageOutputDebugTurnEventTurnEventTopicSwitchDenied. :param str event: (optional) The type of turn event. - :param TurnEventNodeSource source: (optional) - :param str reason: (optional) The reason the dialog node was visited. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that is + defined for the action. + :param str reason: (optional) The reason the action was visited. """ def __init__( self, *, event: Optional[str] = None, - source: Optional['TurnEventNodeSource'] = None, + source: Optional['TurnEventActionSource'] = None, + condition_type: Optional[str] = None, reason: Optional[str] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object. + Initialize a MessageOutputDebugTurnEventTurnEventTopicSwitchDenied object. :param str event: (optional) The type of turn event. - :param TurnEventNodeSource source: (optional) - :param str reason: (optional) The reason the dialog node was visited. + :param TurnEventActionSource source: (optional) + :param str condition_type: (optional) The type of condition (if any) that + is defined for the action. + :param str reason: (optional) The reason the action was visited. """ # pylint: disable=super-init-not-called self.event = event self.source = source + self.condition_type = condition_type self.reason = reason @classmethod def from_dict( - cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventNodeVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" + cls, _dict: Dict + ) -> 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied': + """Initialize a MessageOutputDebugTurnEventTurnEventTopicSwitchDenied object from a json dictionary.""" args = {} if (event := _dict.get('event')) is not None: args['event'] = event if (source := _dict.get('source')) is not None: - args['source'] = TurnEventNodeSource.from_dict(source) + args['source'] = TurnEventActionSource.from_dict(source) + if (condition_type := _dict.get('condition_type')) is not None: + args['condition_type'] = condition_type if (reason := _dict.get('reason')) is not None: args['reason'] = reason return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventNodeVisited object from a json dictionary.""" + """Initialize a MessageOutputDebugTurnEventTurnEventTopicSwitchDenied object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -16433,6 +20259,8 @@ def to_dict(self) -> Dict: _dict['source'] = self.source else: _dict['source'] = self.source.to_dict() + if hasattr(self, 'condition_type') and self.condition_type is not None: + _dict['condition_type'] = self.condition_type if hasattr(self, 'reason') and self.reason is not None: _dict['reason'] = self.reason return _dict @@ -16442,97 +20270,85 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventNodeVisited object.""" + """Return a `str` version of this MessageOutputDebugTurnEventTurnEventTopicSwitchDenied object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, - other: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: + self, other: 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied' + ) -> 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: 'MessageOutputDebugTurnEventTurnEventNodeVisited') -> bool: + self, other: 'MessageOutputDebugTurnEventTurnEventTopicSwitchDenied' + ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ReasonEnum(str, Enum): + class ConditionTypeEnum(str, Enum): """ - The reason the dialog node was visited. + The type of condition (if any) that is defined for the action. """ + USER_DEFINED = 'user_defined' WELCOME = 'welcome' - BRANCH_START = 'branch_start' - TOPIC_SWITCH = 'topic_switch' - TOPIC_RETURN = 'topic_return' - TOPIC_SWITCH_WITHOUT_RETURN = 'topic_switch_without_return' - JUMP = 'jump' + ANYTHING_ELSE = 'anything_else' + + class ReasonEnum(str, Enum): + """ + The reason the action was visited. + """ + ACTION_CONDITIONS_FAILED = 'action_conditions_failed' -class MessageOutputDebugTurnEventTurnEventSearch(MessageOutputDebugTurnEvent): + +class MessageStreamResponseMessageStreamCompleteItem(MessageStreamResponse): """ - MessageOutputDebugTurnEventTurnEventSearch. + A completed response item. A complete item is a composition of every streamed partial + item with the same streaming_metadata.id, and each complete item contains its own + unique streaming_metadata.id. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param TurnEventSearchError error: (optional) + :param CompleteItem complete_item: (optional) """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - error: Optional['TurnEventSearchError'] = None, + complete_item: Optional['CompleteItem'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventSearch object. + Initialize a MessageStreamResponseMessageStreamCompleteItem object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param TurnEventSearchError error: (optional) + :param CompleteItem complete_item: (optional) """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.error = error + self.complete_item = complete_item @classmethod - def from_dict(cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventSearch': - """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" + def from_dict( + cls, + _dict: Dict) -> 'MessageStreamResponseMessageStreamCompleteItem': + """Initialize a MessageStreamResponseMessageStreamCompleteItem object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (error := _dict.get('error')) is not None: - args['error'] = TurnEventSearchError.from_dict(error) + if (complete_item := _dict.get('complete_item')) is not None: + args['complete_item'] = CompleteItem.from_dict(complete_item) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventSearch object from a json dictionary.""" + """Initialize a MessageStreamResponseMessageStreamCompleteItem 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source - else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'error') and self.error is not None: - if isinstance(self.error, dict): - _dict['error'] = self.error + if hasattr(self, 'complete_item') and self.complete_item is not None: + if isinstance(self.complete_item, dict): + _dict['complete_item'] = self.complete_item else: - _dict['error'] = self.error.to_dict() + _dict['complete_item'] = self.complete_item.to_dict() return _dict def _to_dict(self): @@ -16540,107 +20356,67 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventSearch object.""" + """Return a `str` version of this MessageStreamResponseMessageStreamCompleteItem object.""" return json.dumps(self.to_dict(), indent=2) def __eq__(self, - other: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: + other: 'MessageStreamResponseMessageStreamCompleteItem') -> 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: 'MessageOutputDebugTurnEventTurnEventSearch') -> bool: + other: 'MessageStreamResponseMessageStreamCompleteItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class MessageOutputDebugTurnEventTurnEventStepAnswered( - MessageOutputDebugTurnEvent): +class MessageStreamResponseMessageStreamPartialItem(MessageStreamResponse): """ - MessageOutputDebugTurnEventTurnEventStepAnswered. + A chunk of the streamed message response. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that is - defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool prompted: (optional) Whether the step was answered in response to a - prompt from the assistant. If this property is `false`, the user provided the - answer without visiting the step. + :param PartialItem partial_item: (optional) Message response partial item + content. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - condition_type: Optional[str] = None, - action_start_time: Optional[str] = None, - prompted: Optional[bool] = None, + partial_item: Optional['PartialItem'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object. + Initialize a MessageStreamResponseMessageStreamPartialItem object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that - is defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool prompted: (optional) Whether the step was answered in response - to a prompt from the assistant. If this property is `false`, the user - provided the answer without visiting the step. + :param PartialItem partial_item: (optional) Message response partial item + content. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.condition_type = condition_type - self.action_start_time = action_start_time - self.prompted = prompted + self.partial_item = partial_item @classmethod def from_dict( cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepAnswered': - """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" + _dict: Dict) -> 'MessageStreamResponseMessageStreamPartialItem': + """Initialize a MessageStreamResponseMessageStreamPartialItem object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (condition_type := _dict.get('condition_type')) is not None: - args['condition_type'] = condition_type - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time - if (prompted := _dict.get('prompted')) is not None: - args['prompted'] = prompted + if (partial_item := _dict.get('partial_item')) is not None: + args['partial_item'] = PartialItem.from_dict(partial_item) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventStepAnswered object from a json dictionary.""" + """Initialize a MessageStreamResponseMessageStreamPartialItem 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source + if hasattr(self, 'partial_item') and self.partial_item is not None: + if isinstance(self.partial_item, dict): + _dict['partial_item'] = self.partial_item else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'condition_type') and self.condition_type is not None: - _dict['condition_type'] = self.condition_type - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time - if hasattr(self, 'prompted') and self.prompted is not None: - _dict['prompted'] = self.prompted + _dict['partial_item'] = self.partial_item.to_dict() return _dict def _to_dict(self): @@ -16648,116 +20424,67 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepAnswered object.""" + """Return a `str` version of this MessageStreamResponseMessageStreamPartialItem object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, - other: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: + def __eq__(self, + other: 'MessageStreamResponseMessageStreamPartialItem') -> 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: 'MessageOutputDebugTurnEventTurnEventStepAnswered') -> bool: + def __ne__(self, + other: 'MessageStreamResponseMessageStreamPartialItem') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class ConditionTypeEnum(str, Enum): - """ - The type of condition (if any) that is defined for the action. - """ - - USER_DEFINED = 'user_defined' - WELCOME = 'welcome' - ANYTHING_ELSE = 'anything_else' - -class MessageOutputDebugTurnEventTurnEventStepVisited( - MessageOutputDebugTurnEvent): +class MessageStreamResponseStatefulMessageStreamFinalResponse( + MessageStreamResponse): """ - MessageOutputDebugTurnEventTurnEventStepVisited. + The final and stateful message response. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that is - defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool has_question: (optional) Whether the step collects a customer - response. + :param FinalResponse final_response: (optional) Message final response content. """ def __init__( self, *, - event: Optional[str] = None, - source: Optional['TurnEventActionSource'] = None, - condition_type: Optional[str] = None, - action_start_time: Optional[str] = None, - has_question: Optional[bool] = None, + final_response: Optional['FinalResponse'] = None, ) -> None: """ - Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object. + Initialize a MessageStreamResponseStatefulMessageStreamFinalResponse object. - :param str event: (optional) The type of turn event. - :param TurnEventActionSource source: (optional) - :param str condition_type: (optional) The type of condition (if any) that - is defined for the action. - :param str action_start_time: (optional) The time when the action started - processing the message. - :param bool has_question: (optional) Whether the step collects a customer - response. + :param FinalResponse final_response: (optional) Message final response + content. """ # pylint: disable=super-init-not-called - self.event = event - self.source = source - self.condition_type = condition_type - self.action_start_time = action_start_time - self.has_question = has_question + self.final_response = final_response @classmethod def from_dict( - cls, - _dict: Dict) -> 'MessageOutputDebugTurnEventTurnEventStepVisited': - """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" + cls, _dict: Dict + ) -> 'MessageStreamResponseStatefulMessageStreamFinalResponse': + """Initialize a MessageStreamResponseStatefulMessageStreamFinalResponse object from a json dictionary.""" args = {} - if (event := _dict.get('event')) is not None: - args['event'] = event - if (source := _dict.get('source')) is not None: - args['source'] = TurnEventActionSource.from_dict(source) - if (condition_type := _dict.get('condition_type')) is not None: - args['condition_type'] = condition_type - if (action_start_time := _dict.get('action_start_time')) is not None: - args['action_start_time'] = action_start_time - if (has_question := _dict.get('has_question')) is not None: - args['has_question'] = has_question + if (final_response := _dict.get('final_response')) is not None: + args['final_response'] = FinalResponse.from_dict(final_response) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a MessageOutputDebugTurnEventTurnEventStepVisited object from a json dictionary.""" + """Initialize a MessageStreamResponseStatefulMessageStreamFinalResponse 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, 'event') and self.event is not None: - _dict['event'] = self.event - if hasattr(self, 'source') and self.source is not None: - if isinstance(self.source, dict): - _dict['source'] = self.source + if hasattr(self, 'final_response') and self.final_response is not None: + if isinstance(self.final_response, dict): + _dict['final_response'] = self.final_response else: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'condition_type') and self.condition_type is not None: - _dict['condition_type'] = self.condition_type - if hasattr(self, - 'action_start_time') and self.action_start_time is not None: - _dict['action_start_time'] = self.action_start_time - if hasattr(self, 'has_question') and self.has_question is not None: - _dict['has_question'] = self.has_question + _dict['final_response'] = self.final_response.to_dict() return _dict def _to_dict(self): @@ -16765,31 +20492,22 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this MessageOutputDebugTurnEventTurnEventStepVisited object.""" + """Return a `str` version of this MessageStreamResponseStatefulMessageStreamFinalResponse object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, - other: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: + self, other: 'MessageStreamResponseStatefulMessageStreamFinalResponse' + ) -> 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: 'MessageOutputDebugTurnEventTurnEventStepVisited') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ConditionTypeEnum(str, Enum): - """ - The type of condition (if any) that is defined for the action. - """ - - USER_DEFINED = 'user_defined' - WELCOME = 'welcome' - ANYTHING_ELSE = 'anything_else' + def __ne__( + self, other: 'MessageStreamResponseStatefulMessageStreamFinalResponse' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other class ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode( @@ -18098,6 +21816,208 @@ def __ne__( return not self == other +class RuntimeResponseGenericRuntimeResponseTypeConversationalSearch( + RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeConversationalSearch. + + :param str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :param str text: The text of the conversational search response. + :param str citations_title: The title of the citations. The default is “How do + we know?”. It can be updated in the conversational search user interface. + :param List[ResponseGenericCitation] citations: The citations for the generated + response. + :param ResponseGenericConfidenceScores confidence_scores: The confidence scores + for determining whether to show the generated response or an “I don't know” + response. + :param str response_length_option: The response length option. It is used to + control the length of the generated response. It is configured either in the + user interface or through the Update skill API. For more information, see + [watsonx Assistant documentation]( + https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-conversational-search#tuning-the-generated-response-length-in-conversational-search). + :param List[SearchResults] search_results: An array of objects containing the + search results. + :param str disclaimer: A disclaimer for the conversational search response. + """ + + def __init__( + self, + response_type: str, + text: str, + citations_title: str, + citations: List['ResponseGenericCitation'], + confidence_scores: 'ResponseGenericConfidenceScores', + response_length_option: str, + search_results: List['SearchResults'], + disclaimer: str, + ) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeConversationalSearch object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str text: The text of the conversational search response. + :param str citations_title: The title of the citations. The default is “How + do we know?”. It can be updated in the conversational search user + interface. + :param List[ResponseGenericCitation] citations: The citations for the + generated response. + :param ResponseGenericConfidenceScores confidence_scores: The confidence + scores for determining whether to show the generated response or an “I + don't know” response. + :param str response_length_option: The response length option. It is used + to control the length of the generated response. It is configured either in + the user interface or through the Update skill API. For more information, + see [watsonx Assistant documentation]( + https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-conversational-search#tuning-the-generated-response-length-in-conversational-search). + :param List[SearchResults] search_results: An array of objects containing + the search results. + :param str disclaimer: A disclaimer for the conversational search response. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.text = text + self.citations_title = citations_title + self.citations = citations + self.confidence_scores = confidence_scores + self.response_length_option = response_length_option + self.search_results = search_results + self.disclaimer = disclaimer + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeConversationalSearch object from a json dictionary.""" + args = {} + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' + ) + if (text := _dict.get('text')) is not None: + args['text'] = text + else: + raise ValueError( + 'Required property \'text\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' + ) + if (citations_title := _dict.get('citations_title')) is not None: + args['citations_title'] = citations_title + else: + raise ValueError( + 'Required property \'citations_title\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' + ) + if (citations := _dict.get('citations')) is not None: + args['citations'] = [ + ResponseGenericCitation.from_dict(v) for v in citations + ] + else: + raise ValueError( + 'Required property \'citations\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' + ) + if (confidence_scores := _dict.get('confidence_scores')) is not None: + args[ + 'confidence_scores'] = ResponseGenericConfidenceScores.from_dict( + confidence_scores) + else: + raise ValueError( + 'Required property \'confidence_scores\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' + ) + if (response_length_option := + _dict.get('response_length_option')) is not None: + args['response_length_option'] = response_length_option + else: + raise ValueError( + 'Required property \'response_length_option\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' + ) + if (search_results := _dict.get('search_results')) is not None: + args['search_results'] = [ + SearchResults.from_dict(v) for v in search_results + ] + else: + raise ValueError( + 'Required property \'search_results\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' + ) + if (disclaimer := _dict.get('disclaimer')) is not None: + args['disclaimer'] = disclaimer + else: + raise ValueError( + 'Required property \'disclaimer\' not present in RuntimeResponseGenericRuntimeResponseTypeConversationalSearch JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeConversationalSearch 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, + 'citations_title') and self.citations_title is not None: + _dict['citations_title'] = self.citations_title + if hasattr(self, 'citations') and self.citations is not None: + citations_list = [] + for v in self.citations: + if isinstance(v, dict): + citations_list.append(v) + else: + citations_list.append(v.to_dict()) + _dict['citations'] = citations_list + if hasattr(self, + 'confidence_scores') and self.confidence_scores is not None: + if isinstance(self.confidence_scores, dict): + _dict['confidence_scores'] = self.confidence_scores + else: + _dict['confidence_scores'] = self.confidence_scores.to_dict() + if hasattr(self, 'response_length_option' + ) and self.response_length_option is not None: + _dict['response_length_option'] = self.response_length_option + if hasattr(self, 'search_results') and self.search_results is not None: + search_results_list = [] + for v in self.search_results: + if isinstance(v, dict): + search_results_list.append(v) + else: + search_results_list.append(v.to_dict()) + _dict['search_results'] = search_results_list + if hasattr(self, 'disclaimer') and self.disclaimer is not None: + _dict['disclaimer'] = self.disclaimer + 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 RuntimeResponseGenericRuntimeResponseTypeConversationalSearch object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch' + ) -> 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: 'RuntimeResponseGenericRuntimeResponseTypeConversationalSearch' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuntimeResponseGenericRuntimeResponseTypeDate(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeDate. @@ -19345,3 +23265,219 @@ def __ne__(self, other: 'RuntimeResponseGenericRuntimeResponseTypeVideo') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + + +class StatelessMessageStreamResponseMessageStreamCompleteItem( + StatelessMessageStreamResponse): + """ + A completed response item. A complete item is a composition of every streamed partial + item with the same streaming_metadata.id, and each complete item contains its own + unique streaming_metadata.id. + + :param CompleteItem complete_item: (optional) + """ + + def __init__( + self, + *, + complete_item: Optional['CompleteItem'] = None, + ) -> None: + """ + Initialize a StatelessMessageStreamResponseMessageStreamCompleteItem object. + + :param CompleteItem complete_item: (optional) + """ + # pylint: disable=super-init-not-called + self.complete_item = complete_item + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'StatelessMessageStreamResponseMessageStreamCompleteItem': + """Initialize a StatelessMessageStreamResponseMessageStreamCompleteItem object from a json dictionary.""" + args = {} + if (complete_item := _dict.get('complete_item')) is not None: + args['complete_item'] = CompleteItem.from_dict(complete_item) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageStreamResponseMessageStreamCompleteItem 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, 'complete_item') and self.complete_item is not None: + if isinstance(self.complete_item, dict): + _dict['complete_item'] = self.complete_item + else: + _dict['complete_item'] = self.complete_item.to_dict() + 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 StatelessMessageStreamResponseMessageStreamCompleteItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'StatelessMessageStreamResponseMessageStreamCompleteItem' + ) -> 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: 'StatelessMessageStreamResponseMessageStreamCompleteItem' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageStreamResponseMessageStreamPartialItem( + StatelessMessageStreamResponse): + """ + A chunk of the streamed message response. + + :param PartialItem partial_item: (optional) Message response partial item + content. + """ + + def __init__( + self, + *, + partial_item: Optional['PartialItem'] = None, + ) -> None: + """ + Initialize a StatelessMessageStreamResponseMessageStreamPartialItem object. + + :param PartialItem partial_item: (optional) Message response partial item + content. + """ + # pylint: disable=super-init-not-called + self.partial_item = partial_item + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'StatelessMessageStreamResponseMessageStreamPartialItem': + """Initialize a StatelessMessageStreamResponseMessageStreamPartialItem object from a json dictionary.""" + args = {} + if (partial_item := _dict.get('partial_item')) is not None: + args['partial_item'] = PartialItem.from_dict(partial_item) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageStreamResponseMessageStreamPartialItem 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, 'partial_item') and self.partial_item is not None: + if isinstance(self.partial_item, dict): + _dict['partial_item'] = self.partial_item + else: + _dict['partial_item'] = self.partial_item.to_dict() + 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 StatelessMessageStreamResponseMessageStreamPartialItem object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'StatelessMessageStreamResponseMessageStreamPartialItem' + ) -> 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: 'StatelessMessageStreamResponseMessageStreamPartialItem' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class StatelessMessageStreamResponseStatelessMessageStreamFinalResponse( + StatelessMessageStreamResponse): + """ + The final and stateless message response. + + :param StatelessFinalResponse final_response: (optional) Message final response + content. + """ + + def __init__( + self, + *, + final_response: Optional['StatelessFinalResponse'] = None, + ) -> None: + """ + Initialize a StatelessMessageStreamResponseStatelessMessageStreamFinalResponse object. + + :param StatelessFinalResponse final_response: (optional) Message final + response content. + """ + # pylint: disable=super-init-not-called + self.final_response = final_response + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'StatelessMessageStreamResponseStatelessMessageStreamFinalResponse': + """Initialize a StatelessMessageStreamResponseStatelessMessageStreamFinalResponse object from a json dictionary.""" + args = {} + if (final_response := _dict.get('final_response')) is not None: + args['final_response'] = StatelessFinalResponse.from_dict( + final_response) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatelessMessageStreamResponseStatelessMessageStreamFinalResponse 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, 'final_response') and self.final_response is not None: + if isinstance(self.final_response, dict): + _dict['final_response'] = self.final_response + else: + _dict['final_response'] = self.final_response.to_dict() + 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 StatelessMessageStreamResponseStatelessMessageStreamFinalResponse object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'StatelessMessageStreamResponseStatelessMessageStreamFinalResponse' + ) -> 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: 'StatelessMessageStreamResponseStatelessMessageStreamFinalResponse' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 9ae2b0d2e..a59ad0d83 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2024. +# (C) Copyright IBM Corp. 2019, 2025. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -1170,7 +1170,7 @@ def test_message_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' responses.add( responses.POST, url, @@ -1364,7 +1364,7 @@ def test_message_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' responses.add( responses.POST, url, @@ -1406,7 +1406,7 @@ def test_message_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/sessions/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' responses.add( responses.POST, url, @@ -1453,7 +1453,7 @@ def test_message_stateless_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' responses.add( responses.POST, url, @@ -1646,7 +1646,7 @@ def test_message_stateless_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' responses.add( responses.POST, url, @@ -1686,7 +1686,7 @@ def test_message_stateless_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/message') - mock_response = '{"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' + mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' responses.add( responses.POST, url, @@ -2420,7 +2420,7 @@ def test_list_logs_all_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -2473,7 +2473,7 @@ def test_list_logs_required_params(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -2511,7 +2511,7 @@ def test_list_logs_value_error(self): """ # Set up mock url = preprocess_url('/v2/assistants/testString/logs') - mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "text", "text": "text", "channels": [{"channel": "channel"}]}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' + mock_response = '{"logs": [{"log_id": "log_id", "request": {"input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "response": {"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id"}, "assistant_id": "assistant_id", "session_id": "session_id", "skill_id": "skill_id", "snapshot": "snapshot", "request_timestamp": "request_timestamp", "response_timestamp": "response_timestamp", "language": "language", "customer_id": "customer_id"}], "pagination": {"next_url": "next_url", "matched": 7, "next_cursor": "next_cursor"}}' responses.add( responses.GET, url, @@ -5816,6 +5816,40 @@ def test_channel_transfer_target_chat_serialization(self): assert channel_transfer_target_chat_model_json2 == channel_transfer_target_chat_model_json +class TestModel_ClientAction: + """ + Test Class for ClientAction + """ + + def test_client_action_serialization(self): + """ + Test serialization/deserialization for ClientAction + """ + + # Construct a json representation of a ClientAction model + client_action_model_json = {} + client_action_model_json['name'] = 'testString' + client_action_model_json['result_variable'] = 'testString' + client_action_model_json['type'] = 'testString' + client_action_model_json['skill'] = 'main skill' + client_action_model_json['parameters'] = {'anyKey': 'anyValue'} + + # Construct a model instance of ClientAction by calling from_dict on the json representation + client_action_model = ClientAction.from_dict(client_action_model_json) + assert client_action_model != False + + # Construct a model instance of ClientAction by calling from_dict on the json representation + client_action_model_dict = ClientAction.from_dict(client_action_model_json).__dict__ + client_action_model2 = ClientAction(**client_action_model_dict) + + # Verify the model instances are equivalent + assert client_action_model == client_action_model2 + + # Convert model instance back to dict and verify no loss of data + client_action_model_json2 = client_action_model.to_dict() + assert client_action_model_json2 == client_action_model_json + + class TestModel_CreateAssistantReleaseImportResponse: """ Test Class for CreateAssistantReleaseImportResponse @@ -6663,49 +6697,55 @@ def test_environment_skill_serialization(self): assert environment_skill_model_json2 == environment_skill_model_json -class TestModel_IntegrationReference: - """ - Test Class for IntegrationReference - """ - - def test_integration_reference_serialization(self): - """ - Test serialization/deserialization for IntegrationReference - """ - - # Construct a json representation of a IntegrationReference model - integration_reference_model_json = {} - integration_reference_model_json['integration_id'] = 'testString' - integration_reference_model_json['type'] = 'testString' - - # Construct a model instance of IntegrationReference by calling from_dict on the json representation - integration_reference_model = IntegrationReference.from_dict(integration_reference_model_json) - assert integration_reference_model != False - - # Construct a model instance of IntegrationReference by calling from_dict on the json representation - integration_reference_model_dict = IntegrationReference.from_dict(integration_reference_model_json).__dict__ - integration_reference_model2 = IntegrationReference(**integration_reference_model_dict) - - # Verify the model instances are equivalent - assert integration_reference_model == integration_reference_model2 - - # Convert model instance back to dict and verify no loss of data - integration_reference_model_json2 = integration_reference_model.to_dict() - assert integration_reference_model_json2 == integration_reference_model_json - - -class TestModel_Log: +class TestModel_FinalResponse: """ - Test Class for Log + Test Class for FinalResponse """ - def test_log_serialization(self): + def test_final_response_serialization(self): """ - Test serialization/deserialization for Log + Test serialization/deserialization for FinalResponse """ # Construct dict forms of any model objects needed in order to build this model. + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 @@ -6761,87 +6801,6 @@ def test_log_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' - - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' - - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['async_callout'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False - - log_request_input_model = {} # LogRequestInput - log_request_input_model['message_type'] = 'text' - log_request_input_model['text'] = 'testString' - log_request_input_model['intents'] = [runtime_intent_model] - log_request_input_model['entities'] = [runtime_entity_model] - log_request_input_model['suggestion_id'] = 'testString' - log_request_input_model['attachments'] = [message_input_attachment_model] - log_request_input_model['analytics'] = request_analytics_model - log_request_input_model['options'] = message_input_options_model - - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model - - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model - - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} - - log_request_model = {} # LogRequest - log_request_model['input'] = log_request_input_model - log_request_model['context'] = message_context_model - log_request_model['user_id'] = 'testString' - - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] - dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' @@ -6890,62 +6849,178 @@ def test_log_serialization(self): message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - log_response_output_model = {} # LogResponseOutput - log_response_output_model['generic'] = [runtime_response_generic_model] - log_response_output_model['intents'] = [runtime_intent_model] - log_response_output_model['entities'] = [runtime_entity_model] - log_response_output_model['actions'] = [dialog_node_action_model] - log_response_output_model['debug'] = message_output_debug_model - log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} - log_response_output_model['spelling'] = message_output_spelling_model + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' - log_response_model = {} # LogResponse - log_response_model['output'] = log_response_output_model - log_response_model['context'] = message_context_model - log_response_model['user_id'] = 'testString' + metadata_model = {} # Metadata + metadata_model['id'] = 38 - # Construct a json representation of a Log model - log_model_json = {} - log_model_json['log_id'] = 'testString' - log_model_json['request'] = log_request_model - log_model_json['response'] = log_response_model - log_model_json['assistant_id'] = 'testString' - log_model_json['session_id'] = 'testString' - log_model_json['skill_id'] = 'testString' - log_model_json['snapshot'] = 'testString' - log_model_json['request_timestamp'] = 'testString' - log_model_json['response_timestamp'] = 'testString' - log_model_json['language'] = 'testString' - log_model_json['customer_id'] = 'testString' + message_stream_metadata_model = {} # MessageStreamMetadata + message_stream_metadata_model['streaming_metadata'] = metadata_model - # Construct a model instance of Log by calling from_dict on the json representation - log_model = Log.from_dict(log_model_json) - assert log_model != False + final_response_output_model = {} # FinalResponseOutput + final_response_output_model['generic'] = [runtime_response_generic_model] + final_response_output_model['intents'] = [runtime_intent_model] + final_response_output_model['entities'] = [runtime_entity_model] + final_response_output_model['actions'] = [dialog_node_action_model] + final_response_output_model['debug'] = message_output_debug_model + final_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + final_response_output_model['spelling'] = message_output_spelling_model + final_response_output_model['llm_metadata'] = [message_output_llm_metadata_model] + final_response_output_model['streaming_metadata'] = message_stream_metadata_model - # Construct a model instance of Log by calling from_dict on the json representation - log_model_dict = Log.from_dict(log_model_json).__dict__ - log_model2 = Log(**log_model_dict) + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {'anyKey': 'anyValue'} + message_output_model['spelling'] = message_output_spelling_model + message_output_model['llm_metadata'] = [message_output_llm_metadata_model] + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a json representation of a FinalResponse model + final_response_model_json = {} + final_response_model_json['output'] = final_response_output_model + final_response_model_json['context'] = message_context_model + final_response_model_json['user_id'] = 'testString' + final_response_model_json['masked_output'] = message_output_model + final_response_model_json['masked_input'] = message_input_model + + # Construct a model instance of FinalResponse by calling from_dict on the json representation + final_response_model = FinalResponse.from_dict(final_response_model_json) + assert final_response_model != False + + # Construct a model instance of FinalResponse by calling from_dict on the json representation + final_response_model_dict = FinalResponse.from_dict(final_response_model_json).__dict__ + final_response_model2 = FinalResponse(**final_response_model_dict) # Verify the model instances are equivalent - assert log_model == log_model2 + assert final_response_model == final_response_model2 # Convert model instance back to dict and verify no loss of data - log_model_json2 = log_model.to_dict() - assert log_model_json2 == log_model_json + final_response_model_json2 = final_response_model.to_dict() + assert final_response_model_json2 == final_response_model_json -class TestModel_LogCollection: +class TestModel_FinalResponseOutput: """ - Test Class for LogCollection + Test Class for FinalResponseOutput """ - def test_log_collection_serialization(self): + def test_final_response_output_serialization(self): """ - Test serialization/deserialization for LogCollection + Test serialization/deserialization for FinalResponseOutput """ # Construct dict forms of any model objects needed in order to build this model. + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' + runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 @@ -7001,87 +7076,6 @@ def test_log_collection_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' - - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' - - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['async_callout'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False - - log_request_input_model = {} # LogRequestInput - log_request_input_model['message_type'] = 'text' - log_request_input_model['text'] = 'testString' - log_request_input_model['intents'] = [runtime_intent_model] - log_request_input_model['entities'] = [runtime_entity_model] - log_request_input_model['suggestion_id'] = 'testString' - log_request_input_model['attachments'] = [message_input_attachment_model] - log_request_input_model['analytics'] = request_analytics_model - log_request_input_model['options'] = message_input_options_model - - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model - - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model - - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} - - log_request_model = {} # LogRequest - log_request_model['input'] = log_request_input_model - log_request_model['context'] = message_context_model - log_request_model['user_id'] = 'testString' - - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] - dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' dialog_node_action_model['type'] = 'client' @@ -7130,99 +7124,116 @@ def test_log_collection_serialization(self): message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - log_response_output_model = {} # LogResponseOutput - log_response_output_model['generic'] = [runtime_response_generic_model] - log_response_output_model['intents'] = [runtime_intent_model] - log_response_output_model['entities'] = [runtime_entity_model] - log_response_output_model['actions'] = [dialog_node_action_model] - log_response_output_model['debug'] = message_output_debug_model - log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} - log_response_output_model['spelling'] = message_output_spelling_model + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' - log_response_model = {} # LogResponse - log_response_model['output'] = log_response_output_model - log_response_model['context'] = message_context_model - log_response_model['user_id'] = 'testString' + metadata_model = {} # Metadata + metadata_model['id'] = 38 - log_model = {} # Log - log_model['log_id'] = 'testString' - log_model['request'] = log_request_model - log_model['response'] = log_response_model - log_model['assistant_id'] = 'testString' - log_model['session_id'] = 'testString' - log_model['skill_id'] = 'testString' - log_model['snapshot'] = 'testString' - log_model['request_timestamp'] = 'testString' - log_model['response_timestamp'] = 'testString' - log_model['language'] = 'testString' - log_model['customer_id'] = 'testString' + message_stream_metadata_model = {} # MessageStreamMetadata + message_stream_metadata_model['streaming_metadata'] = metadata_model + + # Construct a json representation of a FinalResponseOutput model + final_response_output_model_json = {} + final_response_output_model_json['generic'] = [runtime_response_generic_model] + final_response_output_model_json['intents'] = [runtime_intent_model] + final_response_output_model_json['entities'] = [runtime_entity_model] + final_response_output_model_json['actions'] = [dialog_node_action_model] + final_response_output_model_json['debug'] = message_output_debug_model + final_response_output_model_json['user_defined'] = {'anyKey': 'anyValue'} + final_response_output_model_json['spelling'] = message_output_spelling_model + final_response_output_model_json['llm_metadata'] = [message_output_llm_metadata_model] + final_response_output_model_json['streaming_metadata'] = message_stream_metadata_model + + # Construct a model instance of FinalResponseOutput by calling from_dict on the json representation + final_response_output_model = FinalResponseOutput.from_dict(final_response_output_model_json) + assert final_response_output_model != False + + # Construct a model instance of FinalResponseOutput by calling from_dict on the json representation + final_response_output_model_dict = FinalResponseOutput.from_dict(final_response_output_model_json).__dict__ + final_response_output_model2 = FinalResponseOutput(**final_response_output_model_dict) - log_pagination_model = {} # LogPagination - log_pagination_model['next_url'] = 'testString' - log_pagination_model['matched'] = 38 - log_pagination_model['next_cursor'] = 'testString' + # Verify the model instances are equivalent + assert final_response_output_model == final_response_output_model2 - # Construct a json representation of a LogCollection model - log_collection_model_json = {} - log_collection_model_json['logs'] = [log_model] - log_collection_model_json['pagination'] = log_pagination_model + # Convert model instance back to dict and verify no loss of data + final_response_output_model_json2 = final_response_output_model.to_dict() + assert final_response_output_model_json2 == final_response_output_model_json - # Construct a model instance of LogCollection by calling from_dict on the json representation - log_collection_model = LogCollection.from_dict(log_collection_model_json) - assert log_collection_model != False - # Construct a model instance of LogCollection by calling from_dict on the json representation - log_collection_model_dict = LogCollection.from_dict(log_collection_model_json).__dict__ - log_collection_model2 = LogCollection(**log_collection_model_dict) +class TestModel_GenerativeAITaskConfidenceScores: + """ + Test Class for GenerativeAITaskConfidenceScores + """ + + def test_generative_ai_task_confidence_scores_serialization(self): + """ + Test serialization/deserialization for GenerativeAITaskConfidenceScores + """ + + # Construct a json representation of a GenerativeAITaskConfidenceScores model + generative_ai_task_confidence_scores_model_json = {} + generative_ai_task_confidence_scores_model_json['pre_gen'] = 72.5 + generative_ai_task_confidence_scores_model_json['pre_gen_threshold'] = 72.5 + generative_ai_task_confidence_scores_model_json['post_gen'] = 72.5 + generative_ai_task_confidence_scores_model_json['post_gen_threshold'] = 72.5 + + # Construct a model instance of GenerativeAITaskConfidenceScores by calling from_dict on the json representation + generative_ai_task_confidence_scores_model = GenerativeAITaskConfidenceScores.from_dict(generative_ai_task_confidence_scores_model_json) + assert generative_ai_task_confidence_scores_model != False + + # Construct a model instance of GenerativeAITaskConfidenceScores by calling from_dict on the json representation + generative_ai_task_confidence_scores_model_dict = GenerativeAITaskConfidenceScores.from_dict(generative_ai_task_confidence_scores_model_json).__dict__ + generative_ai_task_confidence_scores_model2 = GenerativeAITaskConfidenceScores(**generative_ai_task_confidence_scores_model_dict) # Verify the model instances are equivalent - assert log_collection_model == log_collection_model2 + assert generative_ai_task_confidence_scores_model == generative_ai_task_confidence_scores_model2 # Convert model instance back to dict and verify no loss of data - log_collection_model_json2 = log_collection_model.to_dict() - assert log_collection_model_json2 == log_collection_model_json + generative_ai_task_confidence_scores_model_json2 = generative_ai_task_confidence_scores_model.to_dict() + assert generative_ai_task_confidence_scores_model_json2 == generative_ai_task_confidence_scores_model_json -class TestModel_LogPagination: +class TestModel_IntegrationReference: """ - Test Class for LogPagination + Test Class for IntegrationReference """ - def test_log_pagination_serialization(self): + def test_integration_reference_serialization(self): """ - Test serialization/deserialization for LogPagination + Test serialization/deserialization for IntegrationReference """ - # Construct a json representation of a LogPagination model - log_pagination_model_json = {} - log_pagination_model_json['next_url'] = 'testString' - log_pagination_model_json['matched'] = 38 - log_pagination_model_json['next_cursor'] = 'testString' + # Construct a json representation of a IntegrationReference model + integration_reference_model_json = {} + integration_reference_model_json['integration_id'] = 'testString' + integration_reference_model_json['type'] = 'testString' - # Construct a model instance of LogPagination by calling from_dict on the json representation - log_pagination_model = LogPagination.from_dict(log_pagination_model_json) - assert log_pagination_model != False + # Construct a model instance of IntegrationReference by calling from_dict on the json representation + integration_reference_model = IntegrationReference.from_dict(integration_reference_model_json) + assert integration_reference_model != False - # Construct a model instance of LogPagination by calling from_dict on the json representation - log_pagination_model_dict = LogPagination.from_dict(log_pagination_model_json).__dict__ - log_pagination_model2 = LogPagination(**log_pagination_model_dict) + # Construct a model instance of IntegrationReference by calling from_dict on the json representation + integration_reference_model_dict = IntegrationReference.from_dict(integration_reference_model_json).__dict__ + integration_reference_model2 = IntegrationReference(**integration_reference_model_dict) # Verify the model instances are equivalent - assert log_pagination_model == log_pagination_model2 + assert integration_reference_model == integration_reference_model2 # Convert model instance back to dict and verify no loss of data - log_pagination_model_json2 = log_pagination_model.to_dict() - assert log_pagination_model_json2 == log_pagination_model_json + integration_reference_model_json2 = integration_reference_model.to_dict() + assert integration_reference_model_json2 == integration_reference_model_json -class TestModel_LogRequest: +class TestModel_Log: """ - Test Class for LogRequest + Test Class for Log """ - def test_log_request_serialization(self): + def test_log_serialization(self): """ - Test serialization/deserialization for LogRequest + Test serialization/deserialization for Log """ # Construct dict forms of any model objects needed in order to build this model. @@ -7301,12 +7312,12 @@ def test_log_request_serialization(self): message_input_options_model['async_callout'] = False message_input_options_model['spelling'] = message_input_options_spelling_model message_input_options_model['debug'] = False - message_input_options_model['return_context'] = True - message_input_options_model['export'] = True + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False log_request_input_model = {} # LogRequestInput log_request_input_model['message_type'] = 'text' - log_request_input_model['text'] = 'Hello' + log_request_input_model['text'] = 'testString' log_request_input_model['intents'] = [runtime_intent_model] log_request_input_model['entities'] = [runtime_entity_model] log_request_input_model['suggestion_id'] = 'testString' @@ -7316,7 +7327,7 @@ def test_log_request_serialization(self): message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'my_user_id' + message_context_global_system_model['user_id'] = 'testString' message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' @@ -7350,52 +7361,169 @@ def test_log_request_serialization(self): message_context_model['skills'] = message_context_skills_model message_context_model['integrations'] = {'anyKey': 'anyValue'} - # Construct a json representation of a LogRequest model - log_request_model_json = {} - log_request_model_json['input'] = log_request_input_model - log_request_model_json['context'] = message_context_model - log_request_model_json['user_id'] = 'testString' + log_request_model = {} # LogRequest + log_request_model['input'] = log_request_input_model + log_request_model['context'] = message_context_model + log_request_model['user_id'] = 'testString' - # Construct a model instance of LogRequest by calling from_dict on the json representation - log_request_model = LogRequest.from_dict(log_request_model_json) - assert log_request_model != False + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' - # Construct a model instance of LogRequest by calling from_dict on the json representation - log_request_model_dict = LogRequest.from_dict(log_request_model_json).__dict__ - log_request_model2 = LogRequest(**log_request_model_dict) + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' - # Verify the model instances are equivalent - assert log_request_model == log_request_model2 + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - # Convert model instance back to dict and verify no loss of data - log_request_model_json2 = log_request_model.to_dict() - assert log_request_model_json2 == log_request_model_json + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model -class TestModel_LogRequestInput: - """ - Test Class for LogRequestInput - """ + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - def test_log_request_input_serialization(self): - """ - Test serialization/deserialization for LogRequestInput - """ + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' - # Construct dict forms of any model objects needed in order to build this model. + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model + log_response_output_model['llm_metadata'] = [message_output_llm_metadata_model] + + log_response_model = {} # LogResponse + log_response_model['output'] = log_response_output_model + log_response_model['context'] = message_context_model + log_response_model['user_id'] = 'testString' + + # Construct a json representation of a Log model + log_model_json = {} + log_model_json['log_id'] = 'testString' + log_model_json['request'] = log_request_model + log_model_json['response'] = log_response_model + log_model_json['assistant_id'] = 'testString' + log_model_json['session_id'] = 'testString' + log_model_json['skill_id'] = 'testString' + log_model_json['snapshot'] = 'testString' + log_model_json['request_timestamp'] = 'testString' + log_model_json['response_timestamp'] = 'testString' + log_model_json['language'] = 'testString' + log_model_json['customer_id'] = 'testString' + + # Construct a model instance of Log by calling from_dict on the json representation + log_model = Log.from_dict(log_model_json) + assert log_model != False + + # Construct a model instance of Log by calling from_dict on the json representation + log_model_dict = Log.from_dict(log_model_json).__dict__ + log_model2 = Log(**log_model_dict) + + # Verify the model instances are equivalent + assert log_model == log_model2 + + # Convert model instance back to dict and verify no loss of data + log_model_json2 = log_model.to_dict() + assert log_model_json2 == log_model_json + + +class TestModel_LogCollection: + """ + Test Class for LogCollection + """ + + def test_log_collection_serialization(self): + """ + Test serialization/deserialization for LogCollection + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' runtime_entity_interpretation_model['festival'] = 'testString' runtime_entity_interpretation_model['granularity'] = 'day' runtime_entity_interpretation_model['range_link'] = 'testString' @@ -7461,107 +7589,93 @@ def test_log_request_input_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - # Construct a json representation of a LogRequestInput model - log_request_input_model_json = {} - log_request_input_model_json['message_type'] = 'text' - log_request_input_model_json['text'] = 'testString' - log_request_input_model_json['intents'] = [runtime_intent_model] - log_request_input_model_json['entities'] = [runtime_entity_model] - log_request_input_model_json['suggestion_id'] = 'testString' - log_request_input_model_json['attachments'] = [message_input_attachment_model] - log_request_input_model_json['analytics'] = request_analytics_model - log_request_input_model_json['options'] = message_input_options_model - - # Construct a model instance of LogRequestInput by calling from_dict on the json representation - log_request_input_model = LogRequestInput.from_dict(log_request_input_model_json) - assert log_request_input_model != False + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'testString' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model - # Construct a model instance of LogRequestInput by calling from_dict on the json representation - log_request_input_model_dict = LogRequestInput.from_dict(log_request_input_model_json).__dict__ - log_request_input_model2 = LogRequestInput(**log_request_input_model_dict) + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Verify the model instances are equivalent - assert log_request_input_model == log_request_input_model2 + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model - # Convert model instance back to dict and verify no loss of data - log_request_input_model_json2 = log_request_input_model.to_dict() - assert log_request_input_model_json2 == log_request_input_model_json + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model -class TestModel_LogResponse: - """ - Test Class for LogResponse - """ + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - def test_log_response_serialization(self): - """ - Test serialization/deserialization for LogResponse - """ + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model - # Construct dict forms of any model objects needed in order to build this model. + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + log_request_model = {} # LogRequest + log_request_model['input'] = log_request_input_model + log_request_model['context'] = message_context_model + log_request_model['user_id'] = 'testString' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] - - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' - - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 - - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' - - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' dialog_node_action_model = {} # DialogNodeAction dialog_node_action_model['name'] = 'testString' @@ -7611,6 +7725,10 @@ def test_log_response_serialization(self): message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' + log_response_output_model = {} # LogResponseOutput log_response_output_model['generic'] = [runtime_response_generic_model] log_response_output_model['intents'] = [runtime_intent_model] @@ -7619,85 +7737,96 @@ def test_log_response_serialization(self): log_response_output_model['debug'] = message_output_debug_model log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} log_response_output_model['spelling'] = message_output_spelling_model + log_response_output_model['llm_metadata'] = [message_output_llm_metadata_model] - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + log_response_model = {} # LogResponse + log_response_model['output'] = log_response_output_model + log_response_model['context'] = message_context_model + log_response_model['user_id'] = 'testString' - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + log_model = {} # Log + log_model['log_id'] = 'testString' + log_model['request'] = log_request_model + log_model['response'] = log_response_model + log_model['assistant_id'] = 'testString' + log_model['session_id'] = 'testString' + log_model['skill_id'] = 'testString' + log_model['snapshot'] = 'testString' + log_model['request_timestamp'] = 'testString' + log_model['response_timestamp'] = 'testString' + log_model['language'] = 'testString' + log_model['customer_id'] = 'testString' - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + log_pagination_model = {} # LogPagination + log_pagination_model['next_url'] = 'testString' + log_pagination_model['matched'] = 38 + log_pagination_model['next_cursor'] = 'testString' - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Construct a json representation of a LogCollection model + log_collection_model_json = {} + log_collection_model_json['logs'] = [log_model] + log_collection_model_json['pagination'] = log_pagination_model - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model = LogCollection.from_dict(log_collection_model_json) + assert log_collection_model != False - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model + # Construct a model instance of LogCollection by calling from_dict on the json representation + log_collection_model_dict = LogCollection.from_dict(log_collection_model_json).__dict__ + log_collection_model2 = LogCollection(**log_collection_model_dict) - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} + # Verify the model instances are equivalent + assert log_collection_model == log_collection_model2 - # Construct a json representation of a LogResponse model - log_response_model_json = {} - log_response_model_json['output'] = log_response_output_model - log_response_model_json['context'] = message_context_model - log_response_model_json['user_id'] = 'testString' + # Convert model instance back to dict and verify no loss of data + log_collection_model_json2 = log_collection_model.to_dict() + assert log_collection_model_json2 == log_collection_model_json - # Construct a model instance of LogResponse by calling from_dict on the json representation - log_response_model = LogResponse.from_dict(log_response_model_json) - assert log_response_model != False - # Construct a model instance of LogResponse by calling from_dict on the json representation - log_response_model_dict = LogResponse.from_dict(log_response_model_json).__dict__ - log_response_model2 = LogResponse(**log_response_model_dict) +class TestModel_LogPagination: + """ + Test Class for LogPagination + """ + + def test_log_pagination_serialization(self): + """ + Test serialization/deserialization for LogPagination + """ + + # Construct a json representation of a LogPagination model + log_pagination_model_json = {} + log_pagination_model_json['next_url'] = 'testString' + log_pagination_model_json['matched'] = 38 + log_pagination_model_json['next_cursor'] = 'testString' + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model = LogPagination.from_dict(log_pagination_model_json) + assert log_pagination_model != False + + # Construct a model instance of LogPagination by calling from_dict on the json representation + log_pagination_model_dict = LogPagination.from_dict(log_pagination_model_json).__dict__ + log_pagination_model2 = LogPagination(**log_pagination_model_dict) # Verify the model instances are equivalent - assert log_response_model == log_response_model2 + assert log_pagination_model == log_pagination_model2 # Convert model instance back to dict and verify no loss of data - log_response_model_json2 = log_response_model.to_dict() - assert log_response_model_json2 == log_response_model_json + log_pagination_model_json2 = log_pagination_model.to_dict() + assert log_pagination_model_json2 == log_pagination_model_json -class TestModel_LogResponseOutput: +class TestModel_LogRequest: """ - Test Class for LogResponseOutput + Test Class for LogRequest """ - def test_log_response_output_serialization(self): + def test_log_request_serialization(self): """ - Test serialization/deserialization for LogResponseOutput + Test serialization/deserialization for LogRequest """ # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] - runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' runtime_intent_model['confidence'] = 72.5 @@ -7753,95 +7882,41 @@ def test_log_response_output_serialization(self): runtime_entity_model['role'] = runtime_entity_role_model runtime_entity_model['skill'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' - - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' - - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' - - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model - - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' - - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' - - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' - - # Construct a json representation of a LogResponseOutput model - log_response_output_model_json = {} - log_response_output_model_json['generic'] = [runtime_response_generic_model] - log_response_output_model_json['intents'] = [runtime_intent_model] - log_response_output_model_json['entities'] = [runtime_entity_model] - log_response_output_model_json['actions'] = [dialog_node_action_model] - log_response_output_model_json['debug'] = message_output_debug_model - log_response_output_model_json['user_defined'] = {'anyKey': 'anyValue'} - log_response_output_model_json['spelling'] = message_output_spelling_model - - # Construct a model instance of LogResponseOutput by calling from_dict on the json representation - log_response_output_model = LogResponseOutput.from_dict(log_response_output_model_json) - assert log_response_output_model != False - - # Construct a model instance of LogResponseOutput by calling from_dict on the json representation - log_response_output_model_dict = LogResponseOutput.from_dict(log_response_output_model_json).__dict__ - log_response_output_model2 = LogResponseOutput(**log_response_output_model_dict) - - # Verify the model instances are equivalent - assert log_response_output_model == log_response_output_model2 - - # Convert model instance back to dict and verify no loss of data - log_response_output_model_json2 = log_response_output_model.to_dict() - assert log_response_output_model_json2 == log_response_output_model_json + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' -class TestModel_MessageContext: - """ - Test Class for MessageContext - """ + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - def test_message_context_serialization(self): - """ - Test serialization/deserialization for MessageContext - """ + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = True + message_input_options_model['export'] = True - # Construct dict forms of any model objects needed in order to build this model. + log_request_input_model = {} # LogRequestInput + log_request_input_model['message_type'] = 'text' + log_request_input_model['text'] = 'Hello' + log_request_input_model['intents'] = [runtime_intent_model] + log_request_input_model['entities'] = [runtime_entity_model] + log_request_input_model['suggestion_id'] = 'testString' + log_request_input_model['attachments'] = [message_input_attachment_model] + log_request_input_model['analytics'] = request_analytics_model + log_request_input_model['options'] = message_input_options_model message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['user_id'] = 'my_user_id' message_context_global_system_model['turn_count'] = 38 message_context_global_system_model['locale'] = 'en-us' message_context_global_system_model['reference_time'] = 'testString' @@ -7870,287 +7945,49 @@ def test_message_context_serialization(self): message_context_skills_model['main skill'] = message_context_dialog_skill_model message_context_skills_model['actions skill'] = message_context_action_skill_model - # Construct a json representation of a MessageContext model - message_context_model_json = {} - message_context_model_json['global'] = message_context_global_model - message_context_model_json['skills'] = message_context_skills_model - message_context_model_json['integrations'] = {'anyKey': 'anyValue'} - - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model = MessageContext.from_dict(message_context_model_json) - assert message_context_model != False - - # Construct a model instance of MessageContext by calling from_dict on the json representation - message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ - message_context_model2 = MessageContext(**message_context_model_dict) - - # Verify the model instances are equivalent - assert message_context_model == message_context_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_model_json2 = message_context_model.to_dict() - assert message_context_model_json2 == message_context_model_json - - -class TestModel_MessageContextActionSkill: - """ - Test Class for MessageContextActionSkill - """ - - def test_message_context_action_skill_serialization(self): - """ - Test serialization/deserialization for MessageContextActionSkill - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} - # Construct a json representation of a MessageContextActionSkill model - message_context_action_skill_model_json = {} - message_context_action_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model_json['system'] = message_context_skill_system_model - message_context_action_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} + # Construct a json representation of a LogRequest model + log_request_model_json = {} + log_request_model_json['input'] = log_request_input_model + log_request_model_json['context'] = message_context_model + log_request_model_json['user_id'] = 'testString' - # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation - message_context_action_skill_model = MessageContextActionSkill.from_dict(message_context_action_skill_model_json) - assert message_context_action_skill_model != False + # Construct a model instance of LogRequest by calling from_dict on the json representation + log_request_model = LogRequest.from_dict(log_request_model_json) + assert log_request_model != False - # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation - message_context_action_skill_model_dict = MessageContextActionSkill.from_dict(message_context_action_skill_model_json).__dict__ - message_context_action_skill_model2 = MessageContextActionSkill(**message_context_action_skill_model_dict) + # Construct a model instance of LogRequest by calling from_dict on the json representation + log_request_model_dict = LogRequest.from_dict(log_request_model_json).__dict__ + log_request_model2 = LogRequest(**log_request_model_dict) # Verify the model instances are equivalent - assert message_context_action_skill_model == message_context_action_skill_model2 + assert log_request_model == log_request_model2 # Convert model instance back to dict and verify no loss of data - message_context_action_skill_model_json2 = message_context_action_skill_model.to_dict() - assert message_context_action_skill_model_json2 == message_context_action_skill_model_json + log_request_model_json2 = log_request_model.to_dict() + assert log_request_model_json2 == log_request_model_json -class TestModel_MessageContextDialogSkill: +class TestModel_LogRequestInput: """ - Test Class for MessageContextDialogSkill + Test Class for LogRequestInput """ - def test_message_context_dialog_skill_serialization(self): + def test_log_request_input_serialization(self): """ - Test serialization/deserialization for MessageContextDialogSkill + Test serialization/deserialization for LogRequestInput """ # Construct dict forms of any model objects needed in order to build this model. - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - # Construct a json representation of a MessageContextDialogSkill model - message_context_dialog_skill_model_json = {} - message_context_dialog_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model_json['system'] = message_context_skill_system_model - - # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation - message_context_dialog_skill_model = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json) - assert message_context_dialog_skill_model != False - - # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation - message_context_dialog_skill_model_dict = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json).__dict__ - message_context_dialog_skill_model2 = MessageContextDialogSkill(**message_context_dialog_skill_model_dict) - - # Verify the model instances are equivalent - assert message_context_dialog_skill_model == message_context_dialog_skill_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_dialog_skill_model_json2 = message_context_dialog_skill_model.to_dict() - assert message_context_dialog_skill_model_json2 == message_context_dialog_skill_model_json - - -class TestModel_MessageContextGlobal: - """ - Test Class for MessageContextGlobal - """ - - def test_message_context_global_serialization(self): - """ - Test serialization/deserialization for MessageContextGlobal - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - - # Construct a json representation of a MessageContextGlobal model - message_context_global_model_json = {} - message_context_global_model_json['system'] = message_context_global_system_model - - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) - assert message_context_global_model != False - - # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation - message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ - message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) - - # Verify the model instances are equivalent - assert message_context_global_model == message_context_global_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_global_model_json2 = message_context_global_model.to_dict() - assert message_context_global_model_json2 == message_context_global_model_json - - -class TestModel_MessageContextGlobalSystem: - """ - Test Class for MessageContextGlobalSystem - """ - - def test_message_context_global_system_serialization(self): - """ - Test serialization/deserialization for MessageContextGlobalSystem - """ - - # Construct a json representation of a MessageContextGlobalSystem model - message_context_global_system_model_json = {} - message_context_global_system_model_json['timezone'] = 'testString' - message_context_global_system_model_json['user_id'] = 'testString' - message_context_global_system_model_json['turn_count'] = 38 - message_context_global_system_model_json['locale'] = 'en-us' - message_context_global_system_model_json['reference_time'] = 'testString' - message_context_global_system_model_json['session_start_time'] = 'testString' - message_context_global_system_model_json['state'] = 'testString' - message_context_global_system_model_json['skip_user_input'] = True - - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) - assert message_context_global_system_model != False - - # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation - message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ - message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) - - # Verify the model instances are equivalent - assert message_context_global_system_model == message_context_global_system_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_global_system_model_json2 = message_context_global_system_model.to_dict() - assert message_context_global_system_model_json2 == message_context_global_system_model_json - - -class TestModel_MessageContextSkillSystem: - """ - Test Class for MessageContextSkillSystem - """ - - def test_message_context_skill_system_serialization(self): - """ - Test serialization/deserialization for MessageContextSkillSystem - """ - - # Construct a json representation of a MessageContextSkillSystem model - message_context_skill_system_model_json = {} - message_context_skill_system_model_json['state'] = 'testString' - message_context_skill_system_model_json['foo'] = 'testString' - - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) - assert message_context_skill_system_model != False - - # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation - message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ - message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) - - # Verify the model instances are equivalent - assert message_context_skill_system_model == message_context_skill_system_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() - assert message_context_skill_system_model_json2 == message_context_skill_system_model_json - - # Test get_properties and set_properties methods. - message_context_skill_system_model.set_properties({}) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict == {} - - expected_dict = {'foo': 'testString'} - message_context_skill_system_model.set_properties(expected_dict) - actual_dict = message_context_skill_system_model.get_properties() - assert actual_dict.keys() == expected_dict.keys() - - -class TestModel_MessageContextSkills: - """ - Test Class for MessageContextSkills - """ - - def test_message_context_skills_serialization(self): - """ - Test serialization/deserialization for MessageContextSkills - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model - - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - - # Construct a json representation of a MessageContextSkills model - message_context_skills_model_json = {} - message_context_skills_model_json['main skill'] = message_context_dialog_skill_model - message_context_skills_model_json['actions skill'] = message_context_action_skill_model - - # Construct a model instance of MessageContextSkills by calling from_dict on the json representation - message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) - assert message_context_skills_model != False - - # Construct a model instance of MessageContextSkills by calling from_dict on the json representation - message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ - message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) - - # Verify the model instances are equivalent - assert message_context_skills_model == message_context_skills_model2 - - # Convert model instance back to dict and verify no loss of data - message_context_skills_model_json2 = message_context_skills_model.to_dict() - assert message_context_skills_model_json2 == message_context_skills_model_json - - -class TestModel_MessageInput: - """ - Test Class for MessageInput - """ - - def test_message_input_serialization(self): - """ - Test serialization/deserialization for MessageInput - """ - - # Construct dict forms of any model objects needed in order to build this model. - - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' capture_group_model = {} # CaptureGroup capture_group_model['group'] = 'testString' @@ -8224,156 +8061,81 @@ def test_message_input_serialization(self): message_input_options_model['return_context'] = False message_input_options_model['export'] = False - # Construct a json representation of a MessageInput model - message_input_model_json = {} - message_input_model_json['message_type'] = 'text' - message_input_model_json['text'] = 'testString' - message_input_model_json['intents'] = [runtime_intent_model] - message_input_model_json['entities'] = [runtime_entity_model] - message_input_model_json['suggestion_id'] = 'testString' - message_input_model_json['attachments'] = [message_input_attachment_model] - message_input_model_json['analytics'] = request_analytics_model - message_input_model_json['options'] = message_input_options_model + # Construct a json representation of a LogRequestInput model + log_request_input_model_json = {} + log_request_input_model_json['message_type'] = 'text' + log_request_input_model_json['text'] = 'testString' + log_request_input_model_json['intents'] = [runtime_intent_model] + log_request_input_model_json['entities'] = [runtime_entity_model] + log_request_input_model_json['suggestion_id'] = 'testString' + log_request_input_model_json['attachments'] = [message_input_attachment_model] + log_request_input_model_json['analytics'] = request_analytics_model + log_request_input_model_json['options'] = message_input_options_model - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model = MessageInput.from_dict(message_input_model_json) - assert message_input_model != False + # Construct a model instance of LogRequestInput by calling from_dict on the json representation + log_request_input_model = LogRequestInput.from_dict(log_request_input_model_json) + assert log_request_input_model != False - # Construct a model instance of MessageInput by calling from_dict on the json representation - message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ - message_input_model2 = MessageInput(**message_input_model_dict) + # Construct a model instance of LogRequestInput by calling from_dict on the json representation + log_request_input_model_dict = LogRequestInput.from_dict(log_request_input_model_json).__dict__ + log_request_input_model2 = LogRequestInput(**log_request_input_model_dict) # Verify the model instances are equivalent - assert message_input_model == message_input_model2 + assert log_request_input_model == log_request_input_model2 # Convert model instance back to dict and verify no loss of data - message_input_model_json2 = message_input_model.to_dict() - assert message_input_model_json2 == message_input_model_json + log_request_input_model_json2 = log_request_input_model.to_dict() + assert log_request_input_model_json2 == log_request_input_model_json -class TestModel_MessageInputAttachment: +class TestModel_LogResponse: """ - Test Class for MessageInputAttachment + Test Class for LogResponse """ - def test_message_input_attachment_serialization(self): + def test_log_response_serialization(self): """ - Test serialization/deserialization for MessageInputAttachment + Test serialization/deserialization for LogResponse """ - # Construct a json representation of a MessageInputAttachment model - message_input_attachment_model_json = {} - message_input_attachment_model_json['url'] = 'testString' - message_input_attachment_model_json['media_type'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) - assert message_input_attachment_model != False - - # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation - message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ - message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) - - # Verify the model instances are equivalent - assert message_input_attachment_model == message_input_attachment_model2 - - # Convert model instance back to dict and verify no loss of data - message_input_attachment_model_json2 = message_input_attachment_model.to_dict() - assert message_input_attachment_model_json2 == message_input_attachment_model_json - - -class TestModel_MessageInputOptions: - """ - Test Class for MessageInputOptions - """ - - def test_message_input_options_serialization(self): - """ - Test serialization/deserialization for MessageInputOptions - """ - - # Construct dict forms of any model objects needed in order to build this model. - - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - # Construct a json representation of a MessageInputOptions model - message_input_options_model_json = {} - message_input_options_model_json['restart'] = False - message_input_options_model_json['alternate_intents'] = False - message_input_options_model_json['async_callout'] = False - message_input_options_model_json['spelling'] = message_input_options_spelling_model - message_input_options_model_json['debug'] = False - message_input_options_model_json['return_context'] = False - message_input_options_model_json['export'] = False - - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) - assert message_input_options_model != False - - # Construct a model instance of MessageInputOptions by calling from_dict on the json representation - message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ - message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) - - # Verify the model instances are equivalent - assert message_input_options_model == message_input_options_model2 - - # Convert model instance back to dict and verify no loss of data - message_input_options_model_json2 = message_input_options_model.to_dict() - assert message_input_options_model_json2 == message_input_options_model_json - - -class TestModel_MessageInputOptionsSpelling: - """ - Test Class for MessageInputOptionsSpelling - """ - - def test_message_input_options_spelling_serialization(self): - """ - Test serialization/deserialization for MessageInputOptionsSpelling - """ - - # Construct a json representation of a MessageInputOptionsSpelling model - message_input_options_spelling_model_json = {} - message_input_options_spelling_model_json['suggestions'] = True - message_input_options_spelling_model_json['auto_correct'] = True - - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) - assert message_input_options_spelling_model != False - - # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation - message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ - message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) - - # Verify the model instances are equivalent - assert message_input_options_spelling_model == message_input_options_spelling_model2 - - # Convert model instance back to dict and verify no loss of data - message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() - assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json - - -class TestModel_MessageOutput: - """ - Test Class for MessageOutput - """ - - def test_message_output_serialization(self): - """ - Test serialization/deserialization for MessageOutput - """ - - # Construct dict forms of any model objects needed in order to build this model. - - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' - - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' runtime_intent_model = {} # RuntimeIntent runtime_intent_model['intent'] = 'testString' @@ -8478,44 +8240,189 @@ def test_message_output_serialization(self): message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' - # Construct a json representation of a MessageOutput model - message_output_model_json = {} - message_output_model_json['generic'] = [runtime_response_generic_model] - message_output_model_json['intents'] = [runtime_intent_model] - message_output_model_json['entities'] = [runtime_entity_model] - message_output_model_json['actions'] = [dialog_node_action_model] - message_output_model_json['debug'] = message_output_debug_model - message_output_model_json['user_defined'] = {'anyKey': 'anyValue'} - message_output_model_json['spelling'] = message_output_spelling_model + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' - # Construct a model instance of MessageOutput by calling from_dict on the json representation - message_output_model = MessageOutput.from_dict(message_output_model_json) - assert message_output_model != False + log_response_output_model = {} # LogResponseOutput + log_response_output_model['generic'] = [runtime_response_generic_model] + log_response_output_model['intents'] = [runtime_intent_model] + log_response_output_model['entities'] = [runtime_entity_model] + log_response_output_model['actions'] = [dialog_node_action_model] + log_response_output_model['debug'] = message_output_debug_model + log_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model['spelling'] = message_output_spelling_model + log_response_output_model['llm_metadata'] = [message_output_llm_metadata_model] - # Construct a model instance of MessageOutput by calling from_dict on the json representation - message_output_model_dict = MessageOutput.from_dict(message_output_model_json).__dict__ - message_output_model2 = MessageOutput(**message_output_model_dict) + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + # Construct a json representation of a LogResponse model + log_response_model_json = {} + log_response_model_json['output'] = log_response_output_model + log_response_model_json['context'] = message_context_model + log_response_model_json['user_id'] = 'testString' + + # Construct a model instance of LogResponse by calling from_dict on the json representation + log_response_model = LogResponse.from_dict(log_response_model_json) + assert log_response_model != False + + # Construct a model instance of LogResponse by calling from_dict on the json representation + log_response_model_dict = LogResponse.from_dict(log_response_model_json).__dict__ + log_response_model2 = LogResponse(**log_response_model_dict) # Verify the model instances are equivalent - assert message_output_model == message_output_model2 + assert log_response_model == log_response_model2 # Convert model instance back to dict and verify no loss of data - message_output_model_json2 = message_output_model.to_dict() - assert message_output_model_json2 == message_output_model_json + log_response_model_json2 = log_response_model.to_dict() + assert log_response_model_json2 == log_response_model_json -class TestModel_MessageOutputDebug: +class TestModel_LogResponseOutput: """ - Test Class for MessageOutputDebug + Test Class for LogResponseOutput """ - def test_message_output_debug_serialization(self): + def test_log_response_output_serialization(self): """ - Test serialization/deserialization for MessageOutputDebug + Test serialization/deserialization for LogResponseOutput """ # Construct dict forms of any model objects needed in order to build this model. + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + dialog_node_visited_model = {} # DialogNodeVisited dialog_node_visited_model['dialog_node'] = 'testString' dialog_node_visited_model['title'] = 'testString' @@ -8545,883 +8452,1066 @@ def test_message_output_debug_serialization(self): message_output_debug_turn_event_model['reason'] = 'intent' message_output_debug_turn_event_model['result_variable'] = 'testString' - # Construct a json representation of a MessageOutputDebug model - message_output_debug_model_json = {} - message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model_json['log_messages'] = [dialog_log_message_model] - message_output_debug_model_json['branch_exited'] = True - message_output_debug_model_json['branch_exited_reason'] = 'completed' - message_output_debug_model_json['turn_events'] = [message_output_debug_turn_event_model] + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation - message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) - assert message_output_debug_model != False + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' - # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation - message_output_debug_model_dict = MessageOutputDebug.from_dict(message_output_debug_model_json).__dict__ - message_output_debug_model2 = MessageOutputDebug(**message_output_debug_model_dict) + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' + + # Construct a json representation of a LogResponseOutput model + log_response_output_model_json = {} + log_response_output_model_json['generic'] = [runtime_response_generic_model] + log_response_output_model_json['intents'] = [runtime_intent_model] + log_response_output_model_json['entities'] = [runtime_entity_model] + log_response_output_model_json['actions'] = [dialog_node_action_model] + log_response_output_model_json['debug'] = message_output_debug_model + log_response_output_model_json['user_defined'] = {'anyKey': 'anyValue'} + log_response_output_model_json['spelling'] = message_output_spelling_model + log_response_output_model_json['llm_metadata'] = [message_output_llm_metadata_model] + + # Construct a model instance of LogResponseOutput by calling from_dict on the json representation + log_response_output_model = LogResponseOutput.from_dict(log_response_output_model_json) + assert log_response_output_model != False + + # Construct a model instance of LogResponseOutput by calling from_dict on the json representation + log_response_output_model_dict = LogResponseOutput.from_dict(log_response_output_model_json).__dict__ + log_response_output_model2 = LogResponseOutput(**log_response_output_model_dict) # Verify the model instances are equivalent - assert message_output_debug_model == message_output_debug_model2 + assert log_response_output_model == log_response_output_model2 # Convert model instance back to dict and verify no loss of data - message_output_debug_model_json2 = message_output_debug_model.to_dict() - assert message_output_debug_model_json2 == message_output_debug_model_json + log_response_output_model_json2 = log_response_output_model.to_dict() + assert log_response_output_model_json2 == log_response_output_model_json -class TestModel_MessageOutputSpelling: +class TestModel_MessageContext: """ - Test Class for MessageOutputSpelling + Test Class for MessageContext """ - def test_message_output_spelling_serialization(self): + def test_message_context_serialization(self): """ - Test serialization/deserialization for MessageOutputSpelling + Test serialization/deserialization for MessageContext """ - # Construct a json representation of a MessageOutputSpelling model - message_output_spelling_model_json = {} - message_output_spelling_model_json['text'] = 'testString' - message_output_spelling_model_json['original_text'] = 'testString' - message_output_spelling_model_json['suggested_text'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation - message_output_spelling_model = MessageOutputSpelling.from_dict(message_output_spelling_model_json) - assert message_output_spelling_model != False + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation - message_output_spelling_model_dict = MessageOutputSpelling.from_dict(message_output_spelling_model_json).__dict__ - message_output_spelling_model2 = MessageOutputSpelling(**message_output_spelling_model_dict) + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + # Construct a json representation of a MessageContext model + message_context_model_json = {} + message_context_model_json['global'] = message_context_global_model + message_context_model_json['skills'] = message_context_skills_model + message_context_model_json['integrations'] = {'anyKey': 'anyValue'} + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model = MessageContext.from_dict(message_context_model_json) + assert message_context_model != False + + # Construct a model instance of MessageContext by calling from_dict on the json representation + message_context_model_dict = MessageContext.from_dict(message_context_model_json).__dict__ + message_context_model2 = MessageContext(**message_context_model_dict) # Verify the model instances are equivalent - assert message_output_spelling_model == message_output_spelling_model2 + assert message_context_model == message_context_model2 # Convert model instance back to dict and verify no loss of data - message_output_spelling_model_json2 = message_output_spelling_model.to_dict() - assert message_output_spelling_model_json2 == message_output_spelling_model_json + message_context_model_json2 = message_context_model.to_dict() + assert message_context_model_json2 == message_context_model_json -class TestModel_Metadata: +class TestModel_MessageContextActionSkill: """ - Test Class for Metadata + Test Class for MessageContextActionSkill """ - def test_metadata_serialization(self): + def test_message_context_action_skill_serialization(self): """ - Test serialization/deserialization for Metadata + Test serialization/deserialization for MessageContextActionSkill """ - # Construct a json representation of a Metadata model - metadata_model_json = {} - metadata_model_json['id'] = 38 + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of Metadata by calling from_dict on the json representation - metadata_model = Metadata.from_dict(metadata_model_json) - assert metadata_model != False + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - # Construct a model instance of Metadata by calling from_dict on the json representation - metadata_model_dict = Metadata.from_dict(metadata_model_json).__dict__ - metadata_model2 = Metadata(**metadata_model_dict) + # Construct a json representation of a MessageContextActionSkill model + message_context_action_skill_model_json = {} + message_context_action_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model_json['system'] = message_context_skill_system_model + message_context_action_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation + message_context_action_skill_model = MessageContextActionSkill.from_dict(message_context_action_skill_model_json) + assert message_context_action_skill_model != False + + # Construct a model instance of MessageContextActionSkill by calling from_dict on the json representation + message_context_action_skill_model_dict = MessageContextActionSkill.from_dict(message_context_action_skill_model_json).__dict__ + message_context_action_skill_model2 = MessageContextActionSkill(**message_context_action_skill_model_dict) # Verify the model instances are equivalent - assert metadata_model == metadata_model2 + assert message_context_action_skill_model == message_context_action_skill_model2 # Convert model instance back to dict and verify no loss of data - metadata_model_json2 = metadata_model.to_dict() - assert metadata_model_json2 == metadata_model_json + message_context_action_skill_model_json2 = message_context_action_skill_model.to_dict() + assert message_context_action_skill_model_json2 == message_context_action_skill_model_json -class TestModel_MonitorAssistantReleaseImportArtifactResponse: +class TestModel_MessageContextDialogSkill: """ - Test Class for MonitorAssistantReleaseImportArtifactResponse + Test Class for MessageContextDialogSkill """ - def test_monitor_assistant_release_import_artifact_response_serialization(self): + def test_message_context_dialog_skill_serialization(self): """ - Test serialization/deserialization for MonitorAssistantReleaseImportArtifactResponse + Test serialization/deserialization for MessageContextDialogSkill """ - # Construct a json representation of a MonitorAssistantReleaseImportArtifactResponse model - monitor_assistant_release_import_artifact_response_model_json = {} - monitor_assistant_release_import_artifact_response_model_json['skill_impact_in_draft'] = ['action'] + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of MonitorAssistantReleaseImportArtifactResponse by calling from_dict on the json representation - monitor_assistant_release_import_artifact_response_model = MonitorAssistantReleaseImportArtifactResponse.from_dict(monitor_assistant_release_import_artifact_response_model_json) - assert monitor_assistant_release_import_artifact_response_model != False + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - # Construct a model instance of MonitorAssistantReleaseImportArtifactResponse by calling from_dict on the json representation - monitor_assistant_release_import_artifact_response_model_dict = MonitorAssistantReleaseImportArtifactResponse.from_dict(monitor_assistant_release_import_artifact_response_model_json).__dict__ - monitor_assistant_release_import_artifact_response_model2 = MonitorAssistantReleaseImportArtifactResponse(**monitor_assistant_release_import_artifact_response_model_dict) + # Construct a json representation of a MessageContextDialogSkill model + message_context_dialog_skill_model_json = {} + message_context_dialog_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model_json['system'] = message_context_skill_system_model + + # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation + message_context_dialog_skill_model = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json) + assert message_context_dialog_skill_model != False + + # Construct a model instance of MessageContextDialogSkill by calling from_dict on the json representation + message_context_dialog_skill_model_dict = MessageContextDialogSkill.from_dict(message_context_dialog_skill_model_json).__dict__ + message_context_dialog_skill_model2 = MessageContextDialogSkill(**message_context_dialog_skill_model_dict) # Verify the model instances are equivalent - assert monitor_assistant_release_import_artifact_response_model == monitor_assistant_release_import_artifact_response_model2 + assert message_context_dialog_skill_model == message_context_dialog_skill_model2 # Convert model instance back to dict and verify no loss of data - monitor_assistant_release_import_artifact_response_model_json2 = monitor_assistant_release_import_artifact_response_model.to_dict() - assert monitor_assistant_release_import_artifact_response_model_json2 == monitor_assistant_release_import_artifact_response_model_json + message_context_dialog_skill_model_json2 = message_context_dialog_skill_model.to_dict() + assert message_context_dialog_skill_model_json2 == message_context_dialog_skill_model_json -class TestModel_Pagination: +class TestModel_MessageContextGlobal: """ - Test Class for Pagination + Test Class for MessageContextGlobal """ - def test_pagination_serialization(self): + def test_message_context_global_serialization(self): """ - Test serialization/deserialization for Pagination + Test serialization/deserialization for MessageContextGlobal """ - # Construct a json representation of a Pagination model - pagination_model_json = {} - pagination_model_json['refresh_url'] = 'testString' - pagination_model_json['next_url'] = 'testString' - pagination_model_json['total'] = 38 - pagination_model_json['matched'] = 38 - pagination_model_json['refresh_cursor'] = 'testString' - pagination_model_json['next_cursor'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of Pagination by calling from_dict on the json representation - pagination_model = Pagination.from_dict(pagination_model_json) - assert pagination_model != False + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True - # Construct a model instance of Pagination by calling from_dict on the json representation - pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ - pagination_model2 = Pagination(**pagination_model_dict) + # Construct a json representation of a MessageContextGlobal model + message_context_global_model_json = {} + message_context_global_model_json['system'] = message_context_global_system_model + + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model = MessageContextGlobal.from_dict(message_context_global_model_json) + assert message_context_global_model != False + + # Construct a model instance of MessageContextGlobal by calling from_dict on the json representation + message_context_global_model_dict = MessageContextGlobal.from_dict(message_context_global_model_json).__dict__ + message_context_global_model2 = MessageContextGlobal(**message_context_global_model_dict) # Verify the model instances are equivalent - assert pagination_model == pagination_model2 + assert message_context_global_model == message_context_global_model2 # Convert model instance back to dict and verify no loss of data - pagination_model_json2 = pagination_model.to_dict() - assert pagination_model_json2 == pagination_model_json + message_context_global_model_json2 = message_context_global_model.to_dict() + assert message_context_global_model_json2 == message_context_global_model_json -class TestModel_ProviderAuthenticationOAuth2: +class TestModel_MessageContextGlobalSystem: """ - Test Class for ProviderAuthenticationOAuth2 + Test Class for MessageContextGlobalSystem """ - def test_provider_authentication_o_auth2_serialization(self): + def test_message_context_global_system_serialization(self): """ - Test serialization/deserialization for ProviderAuthenticationOAuth2 + Test serialization/deserialization for MessageContextGlobalSystem """ - # Construct dict forms of any model objects needed in order to build this model. - - provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername - provider_authentication_o_auth2_password_username_model['type'] = 'value' - provider_authentication_o_auth2_password_username_model['value'] = 'testString' - - provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password - provider_authentication_o_auth2_flows_model['token_url'] = 'testString' - provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' - provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' - provider_authentication_o_auth2_flows_model['content_type'] = 'testString' - provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' - provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - - # Construct a json representation of a ProviderAuthenticationOAuth2 model - provider_authentication_o_auth2_model_json = {} - provider_authentication_o_auth2_model_json['preferred_flow'] = 'password' - provider_authentication_o_auth2_model_json['flows'] = provider_authentication_o_auth2_flows_model + # Construct a json representation of a MessageContextGlobalSystem model + message_context_global_system_model_json = {} + message_context_global_system_model_json['timezone'] = 'testString' + message_context_global_system_model_json['user_id'] = 'testString' + message_context_global_system_model_json['turn_count'] = 38 + message_context_global_system_model_json['locale'] = 'en-us' + message_context_global_system_model_json['reference_time'] = 'testString' + message_context_global_system_model_json['session_start_time'] = 'testString' + message_context_global_system_model_json['state'] = 'testString' + message_context_global_system_model_json['skip_user_input'] = True - # Construct a model instance of ProviderAuthenticationOAuth2 by calling from_dict on the json representation - provider_authentication_o_auth2_model = ProviderAuthenticationOAuth2.from_dict(provider_authentication_o_auth2_model_json) - assert provider_authentication_o_auth2_model != False + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json) + assert message_context_global_system_model != False - # Construct a model instance of ProviderAuthenticationOAuth2 by calling from_dict on the json representation - provider_authentication_o_auth2_model_dict = ProviderAuthenticationOAuth2.from_dict(provider_authentication_o_auth2_model_json).__dict__ - provider_authentication_o_auth2_model2 = ProviderAuthenticationOAuth2(**provider_authentication_o_auth2_model_dict) + # Construct a model instance of MessageContextGlobalSystem by calling from_dict on the json representation + message_context_global_system_model_dict = MessageContextGlobalSystem.from_dict(message_context_global_system_model_json).__dict__ + message_context_global_system_model2 = MessageContextGlobalSystem(**message_context_global_system_model_dict) # Verify the model instances are equivalent - assert provider_authentication_o_auth2_model == provider_authentication_o_auth2_model2 + assert message_context_global_system_model == message_context_global_system_model2 # Convert model instance back to dict and verify no loss of data - provider_authentication_o_auth2_model_json2 = provider_authentication_o_auth2_model.to_dict() - assert provider_authentication_o_auth2_model_json2 == provider_authentication_o_auth2_model_json + message_context_global_system_model_json2 = message_context_global_system_model.to_dict() + assert message_context_global_system_model_json2 == message_context_global_system_model_json -class TestModel_ProviderAuthenticationOAuth2PasswordUsername: +class TestModel_MessageContextSkillSystem: """ - Test Class for ProviderAuthenticationOAuth2PasswordUsername + Test Class for MessageContextSkillSystem """ - def test_provider_authentication_o_auth2_password_username_serialization(self): + def test_message_context_skill_system_serialization(self): """ - Test serialization/deserialization for ProviderAuthenticationOAuth2PasswordUsername + Test serialization/deserialization for MessageContextSkillSystem """ - # Construct a json representation of a ProviderAuthenticationOAuth2PasswordUsername model - provider_authentication_o_auth2_password_username_model_json = {} - provider_authentication_o_auth2_password_username_model_json['type'] = 'value' - provider_authentication_o_auth2_password_username_model_json['value'] = 'testString' + # Construct a json representation of a MessageContextSkillSystem model + message_context_skill_system_model_json = {} + message_context_skill_system_model_json['state'] = 'testString' + message_context_skill_system_model_json['foo'] = 'testString' - # Construct a model instance of ProviderAuthenticationOAuth2PasswordUsername by calling from_dict on the json representation - provider_authentication_o_auth2_password_username_model = ProviderAuthenticationOAuth2PasswordUsername.from_dict(provider_authentication_o_auth2_password_username_model_json) - assert provider_authentication_o_auth2_password_username_model != False + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json) + assert message_context_skill_system_model != False - # Construct a model instance of ProviderAuthenticationOAuth2PasswordUsername by calling from_dict on the json representation - provider_authentication_o_auth2_password_username_model_dict = ProviderAuthenticationOAuth2PasswordUsername.from_dict(provider_authentication_o_auth2_password_username_model_json).__dict__ - provider_authentication_o_auth2_password_username_model2 = ProviderAuthenticationOAuth2PasswordUsername(**provider_authentication_o_auth2_password_username_model_dict) + # Construct a model instance of MessageContextSkillSystem by calling from_dict on the json representation + message_context_skill_system_model_dict = MessageContextSkillSystem.from_dict(message_context_skill_system_model_json).__dict__ + message_context_skill_system_model2 = MessageContextSkillSystem(**message_context_skill_system_model_dict) # Verify the model instances are equivalent - assert provider_authentication_o_auth2_password_username_model == provider_authentication_o_auth2_password_username_model2 + assert message_context_skill_system_model == message_context_skill_system_model2 # Convert model instance back to dict and verify no loss of data - provider_authentication_o_auth2_password_username_model_json2 = provider_authentication_o_auth2_password_username_model.to_dict() - assert provider_authentication_o_auth2_password_username_model_json2 == provider_authentication_o_auth2_password_username_model_json - - -class TestModel_ProviderAuthenticationTypeAndValue: - """ - Test Class for ProviderAuthenticationTypeAndValue - """ - - def test_provider_authentication_type_and_value_serialization(self): - """ - Test serialization/deserialization for ProviderAuthenticationTypeAndValue - """ - - # Construct a json representation of a ProviderAuthenticationTypeAndValue model - provider_authentication_type_and_value_model_json = {} - provider_authentication_type_and_value_model_json['type'] = 'value' - provider_authentication_type_and_value_model_json['value'] = 'testString' - - # Construct a model instance of ProviderAuthenticationTypeAndValue by calling from_dict on the json representation - provider_authentication_type_and_value_model = ProviderAuthenticationTypeAndValue.from_dict(provider_authentication_type_and_value_model_json) - assert provider_authentication_type_and_value_model != False - - # Construct a model instance of ProviderAuthenticationTypeAndValue by calling from_dict on the json representation - provider_authentication_type_and_value_model_dict = ProviderAuthenticationTypeAndValue.from_dict(provider_authentication_type_and_value_model_json).__dict__ - provider_authentication_type_and_value_model2 = ProviderAuthenticationTypeAndValue(**provider_authentication_type_and_value_model_dict) + message_context_skill_system_model_json2 = message_context_skill_system_model.to_dict() + assert message_context_skill_system_model_json2 == message_context_skill_system_model_json - # Verify the model instances are equivalent - assert provider_authentication_type_and_value_model == provider_authentication_type_and_value_model2 + # Test get_properties and set_properties methods. + message_context_skill_system_model.set_properties({}) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict == {} - # Convert model instance back to dict and verify no loss of data - provider_authentication_type_and_value_model_json2 = provider_authentication_type_and_value_model.to_dict() - assert provider_authentication_type_and_value_model_json2 == provider_authentication_type_and_value_model_json + expected_dict = {'foo': 'testString'} + message_context_skill_system_model.set_properties(expected_dict) + actual_dict = message_context_skill_system_model.get_properties() + assert actual_dict.keys() == expected_dict.keys() -class TestModel_ProviderCollection: +class TestModel_MessageContextSkills: """ - Test Class for ProviderCollection + Test Class for MessageContextSkills """ - def test_provider_collection_serialization(self): + def test_message_context_skills_serialization(self): """ - Test serialization/deserialization for ProviderCollection + Test serialization/deserialization for MessageContextSkills """ # Construct dict forms of any model objects needed in order to build this model. - provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem - provider_response_specification_servers_item_model['url'] = 'testString' - - provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue - provider_authentication_type_and_value_model['type'] = 'value' - provider_authentication_type_and_value_model['value'] = 'testString' - - provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic - provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - - provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername - provider_authentication_o_auth2_password_username_model['type'] = 'value' - provider_authentication_o_auth2_password_username_model['value'] = 'testString' - - provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password - provider_authentication_o_auth2_flows_model['token_url'] = 'testString' - provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' - provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' - provider_authentication_o_auth2_flows_model['content_type'] = 'testString' - provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' - provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - - provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 - provider_authentication_o_auth2_model['preferred_flow'] = 'password' - provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - - provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes - provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' - provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model - provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - - provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents - provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model - - provider_response_specification_model = {} # ProviderResponseSpecification - provider_response_specification_model['servers'] = [provider_response_specification_servers_item_model] - provider_response_specification_model['components'] = provider_response_specification_components_model + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' - provider_response_model = {} # ProviderResponse - provider_response_model['provider_id'] = 'testString' - provider_response_model['specification'] = provider_response_specification_model + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model - pagination_model = {} # Pagination - pagination_model['refresh_url'] = 'testString' - pagination_model['next_url'] = 'testString' - pagination_model['total'] = 38 - pagination_model['matched'] = 38 - pagination_model['refresh_cursor'] = 'testString' - pagination_model['next_cursor'] = 'testString' + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - # Construct a json representation of a ProviderCollection model - provider_collection_model_json = {} - provider_collection_model_json['conversational_skill_providers'] = [provider_response_model] - provider_collection_model_json['pagination'] = pagination_model + # Construct a json representation of a MessageContextSkills model + message_context_skills_model_json = {} + message_context_skills_model_json['main skill'] = message_context_dialog_skill_model + message_context_skills_model_json['actions skill'] = message_context_action_skill_model - # Construct a model instance of ProviderCollection by calling from_dict on the json representation - provider_collection_model = ProviderCollection.from_dict(provider_collection_model_json) - assert provider_collection_model != False + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model = MessageContextSkills.from_dict(message_context_skills_model_json) + assert message_context_skills_model != False - # Construct a model instance of ProviderCollection by calling from_dict on the json representation - provider_collection_model_dict = ProviderCollection.from_dict(provider_collection_model_json).__dict__ - provider_collection_model2 = ProviderCollection(**provider_collection_model_dict) + # Construct a model instance of MessageContextSkills by calling from_dict on the json representation + message_context_skills_model_dict = MessageContextSkills.from_dict(message_context_skills_model_json).__dict__ + message_context_skills_model2 = MessageContextSkills(**message_context_skills_model_dict) # Verify the model instances are equivalent - assert provider_collection_model == provider_collection_model2 + assert message_context_skills_model == message_context_skills_model2 # Convert model instance back to dict and verify no loss of data - provider_collection_model_json2 = provider_collection_model.to_dict() - assert provider_collection_model_json2 == provider_collection_model_json + message_context_skills_model_json2 = message_context_skills_model.to_dict() + assert message_context_skills_model_json2 == message_context_skills_model_json -class TestModel_ProviderPrivate: +class TestModel_MessageInput: """ - Test Class for ProviderPrivate + Test Class for MessageInput """ - def test_provider_private_serialization(self): + def test_message_input_serialization(self): """ - Test serialization/deserialization for ProviderPrivate + Test serialization/deserialization for MessageInput """ # Construct dict forms of any model objects needed in order to build this model. - provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue - provider_authentication_type_and_value_model['type'] = 'value' - provider_authentication_type_and_value_model['value'] = 'testString' + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' - provider_private_authentication_model = {} # ProviderPrivateAuthenticationBearerFlow - provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] - # Construct a json representation of a ProviderPrivate model - provider_private_model_json = {} - provider_private_model_json['authentication'] = provider_private_authentication_model + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' - # Construct a model instance of ProviderPrivate by calling from_dict on the json representation - provider_private_model = ProviderPrivate.from_dict(provider_private_model_json) - assert provider_private_model != False + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 - # Construct a model instance of ProviderPrivate by calling from_dict on the json representation - provider_private_model_dict = ProviderPrivate.from_dict(provider_private_model_json).__dict__ - provider_private_model2 = ProviderPrivate(**provider_private_model_dict) + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' - # Verify the model instances are equivalent - assert provider_private_model == provider_private_model2 + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - # Convert model instance back to dict and verify no loss of data - provider_private_model_json2 = provider_private_model.to_dict() - assert provider_private_model_json2 == provider_private_model_json + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' -class TestModel_ProviderPrivateAuthenticationOAuth2PasswordPassword: - """ - Test Class for ProviderPrivateAuthenticationOAuth2PasswordPassword - """ + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - def test_provider_private_authentication_o_auth2_password_password_serialization(self): - """ - Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2PasswordPassword - """ + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False - # Construct a json representation of a ProviderPrivateAuthenticationOAuth2PasswordPassword model - provider_private_authentication_o_auth2_password_password_model_json = {} - provider_private_authentication_o_auth2_password_password_model_json['type'] = 'value' - provider_private_authentication_o_auth2_password_password_model_json['value'] = 'testString' + # Construct a json representation of a MessageInput model + message_input_model_json = {} + message_input_model_json['message_type'] = 'text' + message_input_model_json['text'] = 'testString' + message_input_model_json['intents'] = [runtime_intent_model] + message_input_model_json['entities'] = [runtime_entity_model] + message_input_model_json['suggestion_id'] = 'testString' + message_input_model_json['attachments'] = [message_input_attachment_model] + message_input_model_json['analytics'] = request_analytics_model + message_input_model_json['options'] = message_input_options_model - # Construct a model instance of ProviderPrivateAuthenticationOAuth2PasswordPassword by calling from_dict on the json representation - provider_private_authentication_o_auth2_password_password_model = ProviderPrivateAuthenticationOAuth2PasswordPassword.from_dict(provider_private_authentication_o_auth2_password_password_model_json) - assert provider_private_authentication_o_auth2_password_password_model != False + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model = MessageInput.from_dict(message_input_model_json) + assert message_input_model != False - # Construct a model instance of ProviderPrivateAuthenticationOAuth2PasswordPassword by calling from_dict on the json representation - provider_private_authentication_o_auth2_password_password_model_dict = ProviderPrivateAuthenticationOAuth2PasswordPassword.from_dict(provider_private_authentication_o_auth2_password_password_model_json).__dict__ - provider_private_authentication_o_auth2_password_password_model2 = ProviderPrivateAuthenticationOAuth2PasswordPassword(**provider_private_authentication_o_auth2_password_password_model_dict) + # Construct a model instance of MessageInput by calling from_dict on the json representation + message_input_model_dict = MessageInput.from_dict(message_input_model_json).__dict__ + message_input_model2 = MessageInput(**message_input_model_dict) # Verify the model instances are equivalent - assert provider_private_authentication_o_auth2_password_password_model == provider_private_authentication_o_auth2_password_password_model2 + assert message_input_model == message_input_model2 # Convert model instance back to dict and verify no loss of data - provider_private_authentication_o_auth2_password_password_model_json2 = provider_private_authentication_o_auth2_password_password_model.to_dict() - assert provider_private_authentication_o_auth2_password_password_model_json2 == provider_private_authentication_o_auth2_password_password_model_json + message_input_model_json2 = message_input_model.to_dict() + assert message_input_model_json2 == message_input_model_json -class TestModel_ProviderResponse: +class TestModel_MessageInputAttachment: """ - Test Class for ProviderResponse + Test Class for MessageInputAttachment """ - def test_provider_response_serialization(self): + def test_message_input_attachment_serialization(self): """ - Test serialization/deserialization for ProviderResponse + Test serialization/deserialization for MessageInputAttachment """ - # Construct dict forms of any model objects needed in order to build this model. - - provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem - provider_response_specification_servers_item_model['url'] = 'testString' - - provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue - provider_authentication_type_and_value_model['type'] = 'value' - provider_authentication_type_and_value_model['value'] = 'testString' - - provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic - provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - - provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername - provider_authentication_o_auth2_password_username_model['type'] = 'value' - provider_authentication_o_auth2_password_username_model['value'] = 'testString' - - provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password - provider_authentication_o_auth2_flows_model['token_url'] = 'testString' - provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' - provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' - provider_authentication_o_auth2_flows_model['content_type'] = 'testString' - provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' - provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - - provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 - provider_authentication_o_auth2_model['preferred_flow'] = 'password' - provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - - provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes - provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' - provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model - provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - - provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents - provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model - - provider_response_specification_model = {} # ProviderResponseSpecification - provider_response_specification_model['servers'] = [provider_response_specification_servers_item_model] - provider_response_specification_model['components'] = provider_response_specification_components_model - - # Construct a json representation of a ProviderResponse model - provider_response_model_json = {} - provider_response_model_json['provider_id'] = 'testString' - provider_response_model_json['specification'] = provider_response_specification_model + # Construct a json representation of a MessageInputAttachment model + message_input_attachment_model_json = {} + message_input_attachment_model_json['url'] = 'testString' + message_input_attachment_model_json['media_type'] = 'testString' - # Construct a model instance of ProviderResponse by calling from_dict on the json representation - provider_response_model = ProviderResponse.from_dict(provider_response_model_json) - assert provider_response_model != False + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model = MessageInputAttachment.from_dict(message_input_attachment_model_json) + assert message_input_attachment_model != False - # Construct a model instance of ProviderResponse by calling from_dict on the json representation - provider_response_model_dict = ProviderResponse.from_dict(provider_response_model_json).__dict__ - provider_response_model2 = ProviderResponse(**provider_response_model_dict) + # Construct a model instance of MessageInputAttachment by calling from_dict on the json representation + message_input_attachment_model_dict = MessageInputAttachment.from_dict(message_input_attachment_model_json).__dict__ + message_input_attachment_model2 = MessageInputAttachment(**message_input_attachment_model_dict) # Verify the model instances are equivalent - assert provider_response_model == provider_response_model2 + assert message_input_attachment_model == message_input_attachment_model2 # Convert model instance back to dict and verify no loss of data - provider_response_model_json2 = provider_response_model.to_dict() - assert provider_response_model_json2 == provider_response_model_json + message_input_attachment_model_json2 = message_input_attachment_model.to_dict() + assert message_input_attachment_model_json2 == message_input_attachment_model_json -class TestModel_ProviderResponseSpecification: +class TestModel_MessageInputOptions: """ - Test Class for ProviderResponseSpecification + Test Class for MessageInputOptions """ - def test_provider_response_specification_serialization(self): + def test_message_input_options_serialization(self): """ - Test serialization/deserialization for ProviderResponseSpecification + Test serialization/deserialization for MessageInputOptions """ # Construct dict forms of any model objects needed in order to build this model. - provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem - provider_response_specification_servers_item_model['url'] = 'testString' + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue - provider_authentication_type_and_value_model['type'] = 'value' - provider_authentication_type_and_value_model['value'] = 'testString' + # Construct a json representation of a MessageInputOptions model + message_input_options_model_json = {} + message_input_options_model_json['restart'] = False + message_input_options_model_json['alternate_intents'] = False + message_input_options_model_json['async_callout'] = False + message_input_options_model_json['spelling'] = message_input_options_spelling_model + message_input_options_model_json['debug'] = False + message_input_options_model_json['return_context'] = False + message_input_options_model_json['export'] = False - provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic - provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model = MessageInputOptions.from_dict(message_input_options_model_json) + assert message_input_options_model != False - provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername - provider_authentication_o_auth2_password_username_model['type'] = 'value' - provider_authentication_o_auth2_password_username_model['value'] = 'testString' + # Construct a model instance of MessageInputOptions by calling from_dict on the json representation + message_input_options_model_dict = MessageInputOptions.from_dict(message_input_options_model_json).__dict__ + message_input_options_model2 = MessageInputOptions(**message_input_options_model_dict) - provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password - provider_authentication_o_auth2_flows_model['token_url'] = 'testString' - provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' - provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' - provider_authentication_o_auth2_flows_model['content_type'] = 'testString' - provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' - provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + # Verify the model instances are equivalent + assert message_input_options_model == message_input_options_model2 - provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 - provider_authentication_o_auth2_model['preferred_flow'] = 'password' - provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + # Convert model instance back to dict and verify no loss of data + message_input_options_model_json2 = message_input_options_model.to_dict() + assert message_input_options_model_json2 == message_input_options_model_json - provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes - provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' - provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model - provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents - provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model +class TestModel_MessageInputOptionsSpelling: + """ + Test Class for MessageInputOptionsSpelling + """ - # Construct a json representation of a ProviderResponseSpecification model - provider_response_specification_model_json = {} - provider_response_specification_model_json['servers'] = [provider_response_specification_servers_item_model] - provider_response_specification_model_json['components'] = provider_response_specification_components_model + def test_message_input_options_spelling_serialization(self): + """ + Test serialization/deserialization for MessageInputOptionsSpelling + """ - # Construct a model instance of ProviderResponseSpecification by calling from_dict on the json representation - provider_response_specification_model = ProviderResponseSpecification.from_dict(provider_response_specification_model_json) - assert provider_response_specification_model != False + # Construct a json representation of a MessageInputOptionsSpelling model + message_input_options_spelling_model_json = {} + message_input_options_spelling_model_json['suggestions'] = True + message_input_options_spelling_model_json['auto_correct'] = True - # Construct a model instance of ProviderResponseSpecification by calling from_dict on the json representation - provider_response_specification_model_dict = ProviderResponseSpecification.from_dict(provider_response_specification_model_json).__dict__ - provider_response_specification_model2 = ProviderResponseSpecification(**provider_response_specification_model_dict) + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json) + assert message_input_options_spelling_model != False + + # Construct a model instance of MessageInputOptionsSpelling by calling from_dict on the json representation + message_input_options_spelling_model_dict = MessageInputOptionsSpelling.from_dict(message_input_options_spelling_model_json).__dict__ + message_input_options_spelling_model2 = MessageInputOptionsSpelling(**message_input_options_spelling_model_dict) # Verify the model instances are equivalent - assert provider_response_specification_model == provider_response_specification_model2 + assert message_input_options_spelling_model == message_input_options_spelling_model2 # Convert model instance back to dict and verify no loss of data - provider_response_specification_model_json2 = provider_response_specification_model.to_dict() - assert provider_response_specification_model_json2 == provider_response_specification_model_json + message_input_options_spelling_model_json2 = message_input_options_spelling_model.to_dict() + assert message_input_options_spelling_model_json2 == message_input_options_spelling_model_json -class TestModel_ProviderResponseSpecificationComponents: +class TestModel_MessageOutput: """ - Test Class for ProviderResponseSpecificationComponents + Test Class for MessageOutput """ - def test_provider_response_specification_components_serialization(self): + def test_message_output_serialization(self): """ - Test serialization/deserialization for ProviderResponseSpecificationComponents + Test serialization/deserialization for MessageOutput """ # Construct dict forms of any model objects needed in order to build this model. - provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue - provider_authentication_type_and_value_model['type'] = 'value' - provider_authentication_type_and_value_model['value'] = 'testString' + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' - provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic - provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' - provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername - provider_authentication_o_auth2_password_username_model['type'] = 'value' - provider_authentication_o_auth2_password_username_model['value'] = 'testString' + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] - provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password - provider_authentication_o_auth2_flows_model['token_url'] = 'testString' - provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' - provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' - provider_authentication_o_auth2_flows_model['content_type'] = 'testString' - provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' - provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' - provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 - provider_authentication_o_auth2_model['preferred_flow'] = 'password' - provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 - provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes - provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' - provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model - provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' - # Construct a json representation of a ProviderResponseSpecificationComponents model - provider_response_specification_components_model_json = {} - provider_response_specification_components_model_json['securitySchemes'] = provider_response_specification_components_security_schemes_model + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' - # Construct a model instance of ProviderResponseSpecificationComponents by calling from_dict on the json representation - provider_response_specification_components_model = ProviderResponseSpecificationComponents.from_dict(provider_response_specification_components_model_json) - assert provider_response_specification_components_model != False + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' - # Construct a model instance of ProviderResponseSpecificationComponents by calling from_dict on the json representation - provider_response_specification_components_model_dict = ProviderResponseSpecificationComponents.from_dict(provider_response_specification_components_model_json).__dict__ - provider_response_specification_components_model2 = ProviderResponseSpecificationComponents(**provider_response_specification_components_model_dict) + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' + + # Construct a json representation of a MessageOutput model + message_output_model_json = {} + message_output_model_json['generic'] = [runtime_response_generic_model] + message_output_model_json['intents'] = [runtime_intent_model] + message_output_model_json['entities'] = [runtime_entity_model] + message_output_model_json['actions'] = [dialog_node_action_model] + message_output_model_json['debug'] = message_output_debug_model + message_output_model_json['user_defined'] = {'anyKey': 'anyValue'} + message_output_model_json['spelling'] = message_output_spelling_model + message_output_model_json['llm_metadata'] = [message_output_llm_metadata_model] + + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model = MessageOutput.from_dict(message_output_model_json) + assert message_output_model != False + + # Construct a model instance of MessageOutput by calling from_dict on the json representation + message_output_model_dict = MessageOutput.from_dict(message_output_model_json).__dict__ + message_output_model2 = MessageOutput(**message_output_model_dict) # Verify the model instances are equivalent - assert provider_response_specification_components_model == provider_response_specification_components_model2 + assert message_output_model == message_output_model2 # Convert model instance back to dict and verify no loss of data - provider_response_specification_components_model_json2 = provider_response_specification_components_model.to_dict() - assert provider_response_specification_components_model_json2 == provider_response_specification_components_model_json + message_output_model_json2 = message_output_model.to_dict() + assert message_output_model_json2 == message_output_model_json -class TestModel_ProviderResponseSpecificationComponentsSecuritySchemes: +class TestModel_MessageOutputDebug: """ - Test Class for ProviderResponseSpecificationComponentsSecuritySchemes + Test Class for MessageOutputDebug """ - def test_provider_response_specification_components_security_schemes_serialization(self): + def test_message_output_debug_serialization(self): """ - Test serialization/deserialization for ProviderResponseSpecificationComponentsSecuritySchemes + Test serialization/deserialization for MessageOutputDebug """ # Construct dict forms of any model objects needed in order to build this model. - provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue - provider_authentication_type_and_value_model['type'] = 'value' - provider_authentication_type_and_value_model['value'] = 'testString' + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' - provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic - provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' - provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername - provider_authentication_o_auth2_password_username_model['type'] = 'value' - provider_authentication_o_auth2_password_username_model['value'] = 'testString' + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model - provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password - provider_authentication_o_auth2_flows_model['token_url'] = 'testString' - provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' - provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' - provider_authentication_o_auth2_flows_model['content_type'] = 'testString' - provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' - provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 - provider_authentication_o_auth2_model['preferred_flow'] = 'password' - provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' - # Construct a json representation of a ProviderResponseSpecificationComponentsSecuritySchemes model - provider_response_specification_components_security_schemes_model_json = {} - provider_response_specification_components_security_schemes_model_json['authentication_method'] = 'basic' - provider_response_specification_components_security_schemes_model_json['basic'] = provider_response_specification_components_security_schemes_basic_model - provider_response_specification_components_security_schemes_model_json['oauth2'] = provider_authentication_o_auth2_model + # Construct a json representation of a MessageOutputDebug model + message_output_debug_model_json = {} + message_output_debug_model_json['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model_json['log_messages'] = [dialog_log_message_model] + message_output_debug_model_json['branch_exited'] = True + message_output_debug_model_json['branch_exited_reason'] = 'completed' + message_output_debug_model_json['turn_events'] = [message_output_debug_turn_event_model] - # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemes by calling from_dict on the json representation - provider_response_specification_components_security_schemes_model = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict(provider_response_specification_components_security_schemes_model_json) - assert provider_response_specification_components_security_schemes_model != False + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model = MessageOutputDebug.from_dict(message_output_debug_model_json) + assert message_output_debug_model != False - # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemes by calling from_dict on the json representation - provider_response_specification_components_security_schemes_model_dict = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict(provider_response_specification_components_security_schemes_model_json).__dict__ - provider_response_specification_components_security_schemes_model2 = ProviderResponseSpecificationComponentsSecuritySchemes(**provider_response_specification_components_security_schemes_model_dict) + # Construct a model instance of MessageOutputDebug by calling from_dict on the json representation + message_output_debug_model_dict = MessageOutputDebug.from_dict(message_output_debug_model_json).__dict__ + message_output_debug_model2 = MessageOutputDebug(**message_output_debug_model_dict) # Verify the model instances are equivalent - assert provider_response_specification_components_security_schemes_model == provider_response_specification_components_security_schemes_model2 + assert message_output_debug_model == message_output_debug_model2 # Convert model instance back to dict and verify no loss of data - provider_response_specification_components_security_schemes_model_json2 = provider_response_specification_components_security_schemes_model.to_dict() - assert provider_response_specification_components_security_schemes_model_json2 == provider_response_specification_components_security_schemes_model_json + message_output_debug_model_json2 = message_output_debug_model.to_dict() + assert message_output_debug_model_json2 == message_output_debug_model_json -class TestModel_ProviderResponseSpecificationComponentsSecuritySchemesBasic: +class TestModel_MessageOutputLLMMetadata: """ - Test Class for ProviderResponseSpecificationComponentsSecuritySchemesBasic + Test Class for MessageOutputLLMMetadata """ - def test_provider_response_specification_components_security_schemes_basic_serialization(self): + def test_message_output_llm_metadata_serialization(self): """ - Test serialization/deserialization for ProviderResponseSpecificationComponentsSecuritySchemesBasic + Test serialization/deserialization for MessageOutputLLMMetadata """ - # Construct dict forms of any model objects needed in order to build this model. - - provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue - provider_authentication_type_and_value_model['type'] = 'value' - provider_authentication_type_and_value_model['value'] = 'testString' - - # Construct a json representation of a ProviderResponseSpecificationComponentsSecuritySchemesBasic model - provider_response_specification_components_security_schemes_basic_model_json = {} - provider_response_specification_components_security_schemes_basic_model_json['username'] = provider_authentication_type_and_value_model + # Construct a json representation of a MessageOutputLLMMetadata model + message_output_llm_metadata_model_json = {} + message_output_llm_metadata_model_json['task'] = 'testString' + message_output_llm_metadata_model_json['model_id'] = 'testString' - # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation - provider_response_specification_components_security_schemes_basic_model = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict(provider_response_specification_components_security_schemes_basic_model_json) - assert provider_response_specification_components_security_schemes_basic_model != False + # Construct a model instance of MessageOutputLLMMetadata by calling from_dict on the json representation + message_output_llm_metadata_model = MessageOutputLLMMetadata.from_dict(message_output_llm_metadata_model_json) + assert message_output_llm_metadata_model != False - # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation - provider_response_specification_components_security_schemes_basic_model_dict = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict(provider_response_specification_components_security_schemes_basic_model_json).__dict__ - provider_response_specification_components_security_schemes_basic_model2 = ProviderResponseSpecificationComponentsSecuritySchemesBasic(**provider_response_specification_components_security_schemes_basic_model_dict) + # Construct a model instance of MessageOutputLLMMetadata by calling from_dict on the json representation + message_output_llm_metadata_model_dict = MessageOutputLLMMetadata.from_dict(message_output_llm_metadata_model_json).__dict__ + message_output_llm_metadata_model2 = MessageOutputLLMMetadata(**message_output_llm_metadata_model_dict) # Verify the model instances are equivalent - assert provider_response_specification_components_security_schemes_basic_model == provider_response_specification_components_security_schemes_basic_model2 + assert message_output_llm_metadata_model == message_output_llm_metadata_model2 # Convert model instance back to dict and verify no loss of data - provider_response_specification_components_security_schemes_basic_model_json2 = provider_response_specification_components_security_schemes_basic_model.to_dict() - assert provider_response_specification_components_security_schemes_basic_model_json2 == provider_response_specification_components_security_schemes_basic_model_json + message_output_llm_metadata_model_json2 = message_output_llm_metadata_model.to_dict() + assert message_output_llm_metadata_model_json2 == message_output_llm_metadata_model_json -class TestModel_ProviderResponseSpecificationServersItem: +class TestModel_MessageOutputSpelling: """ - Test Class for ProviderResponseSpecificationServersItem + Test Class for MessageOutputSpelling """ - def test_provider_response_specification_servers_item_serialization(self): + def test_message_output_spelling_serialization(self): """ - Test serialization/deserialization for ProviderResponseSpecificationServersItem + Test serialization/deserialization for MessageOutputSpelling """ - # Construct a json representation of a ProviderResponseSpecificationServersItem model - provider_response_specification_servers_item_model_json = {} - provider_response_specification_servers_item_model_json['url'] = 'testString' + # Construct a json representation of a MessageOutputSpelling model + message_output_spelling_model_json = {} + message_output_spelling_model_json['text'] = 'testString' + message_output_spelling_model_json['original_text'] = 'testString' + message_output_spelling_model_json['suggested_text'] = 'testString' - # Construct a model instance of ProviderResponseSpecificationServersItem by calling from_dict on the json representation - provider_response_specification_servers_item_model = ProviderResponseSpecificationServersItem.from_dict(provider_response_specification_servers_item_model_json) - assert provider_response_specification_servers_item_model != False + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model = MessageOutputSpelling.from_dict(message_output_spelling_model_json) + assert message_output_spelling_model != False - # Construct a model instance of ProviderResponseSpecificationServersItem by calling from_dict on the json representation - provider_response_specification_servers_item_model_dict = ProviderResponseSpecificationServersItem.from_dict(provider_response_specification_servers_item_model_json).__dict__ - provider_response_specification_servers_item_model2 = ProviderResponseSpecificationServersItem(**provider_response_specification_servers_item_model_dict) + # Construct a model instance of MessageOutputSpelling by calling from_dict on the json representation + message_output_spelling_model_dict = MessageOutputSpelling.from_dict(message_output_spelling_model_json).__dict__ + message_output_spelling_model2 = MessageOutputSpelling(**message_output_spelling_model_dict) # Verify the model instances are equivalent - assert provider_response_specification_servers_item_model == provider_response_specification_servers_item_model2 + assert message_output_spelling_model == message_output_spelling_model2 # Convert model instance back to dict and verify no loss of data - provider_response_specification_servers_item_model_json2 = provider_response_specification_servers_item_model.to_dict() - assert provider_response_specification_servers_item_model_json2 == provider_response_specification_servers_item_model_json + message_output_spelling_model_json2 = message_output_spelling_model.to_dict() + assert message_output_spelling_model_json2 == message_output_spelling_model_json -class TestModel_ProviderSpecification: +class TestModel_MessageStreamMetadata: """ - Test Class for ProviderSpecification + Test Class for MessageStreamMetadata """ - def test_provider_specification_serialization(self): + def test_message_stream_metadata_serialization(self): """ - Test serialization/deserialization for ProviderSpecification + Test serialization/deserialization for MessageStreamMetadata """ # Construct dict forms of any model objects needed in order to build this model. - provider_specification_servers_item_model = {} # ProviderSpecificationServersItem - provider_specification_servers_item_model['url'] = 'testString' + metadata_model = {} # Metadata + metadata_model['id'] = 38 - provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue - provider_authentication_type_and_value_model['type'] = 'value' - provider_authentication_type_and_value_model['value'] = 'testString' + # Construct a json representation of a MessageStreamMetadata model + message_stream_metadata_model_json = {} + message_stream_metadata_model_json['streaming_metadata'] = metadata_model - provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic - provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + # Construct a model instance of MessageStreamMetadata by calling from_dict on the json representation + message_stream_metadata_model = MessageStreamMetadata.from_dict(message_stream_metadata_model_json) + assert message_stream_metadata_model != False - provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername - provider_authentication_o_auth2_password_username_model['type'] = 'value' - provider_authentication_o_auth2_password_username_model['value'] = 'testString' + # Construct a model instance of MessageStreamMetadata by calling from_dict on the json representation + message_stream_metadata_model_dict = MessageStreamMetadata.from_dict(message_stream_metadata_model_json).__dict__ + message_stream_metadata_model2 = MessageStreamMetadata(**message_stream_metadata_model_dict) - provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password - provider_authentication_o_auth2_flows_model['token_url'] = 'testString' - provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' - provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' - provider_authentication_o_auth2_flows_model['content_type'] = 'testString' - provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' - provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + # Verify the model instances are equivalent + assert message_stream_metadata_model == message_stream_metadata_model2 - provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 - provider_authentication_o_auth2_model['preferred_flow'] = 'password' - provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + # Convert model instance back to dict and verify no loss of data + message_stream_metadata_model_json2 = message_stream_metadata_model.to_dict() + assert message_stream_metadata_model_json2 == message_stream_metadata_model_json - provider_specification_components_security_schemes_model = {} # ProviderSpecificationComponentsSecuritySchemes - provider_specification_components_security_schemes_model['authentication_method'] = 'basic' - provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model - provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - provider_specification_components_model = {} # ProviderSpecificationComponents - provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model +class TestModel_Metadata: + """ + Test Class for Metadata + """ - # Construct a json representation of a ProviderSpecification model - provider_specification_model_json = {} - provider_specification_model_json['servers'] = [provider_specification_servers_item_model] - provider_specification_model_json['components'] = provider_specification_components_model + def test_metadata_serialization(self): + """ + Test serialization/deserialization for Metadata + """ - # Construct a model instance of ProviderSpecification by calling from_dict on the json representation - provider_specification_model = ProviderSpecification.from_dict(provider_specification_model_json) - assert provider_specification_model != False + # Construct a json representation of a Metadata model + metadata_model_json = {} + metadata_model_json['id'] = 38 - # Construct a model instance of ProviderSpecification by calling from_dict on the json representation - provider_specification_model_dict = ProviderSpecification.from_dict(provider_specification_model_json).__dict__ - provider_specification_model2 = ProviderSpecification(**provider_specification_model_dict) + # Construct a model instance of Metadata by calling from_dict on the json representation + metadata_model = Metadata.from_dict(metadata_model_json) + assert metadata_model != False + + # Construct a model instance of Metadata by calling from_dict on the json representation + metadata_model_dict = Metadata.from_dict(metadata_model_json).__dict__ + metadata_model2 = Metadata(**metadata_model_dict) # Verify the model instances are equivalent - assert provider_specification_model == provider_specification_model2 + assert metadata_model == metadata_model2 # Convert model instance back to dict and verify no loss of data - provider_specification_model_json2 = provider_specification_model.to_dict() - assert provider_specification_model_json2 == provider_specification_model_json + metadata_model_json2 = metadata_model.to_dict() + assert metadata_model_json2 == metadata_model_json -class TestModel_ProviderSpecificationComponents: +class TestModel_MonitorAssistantReleaseImportArtifactResponse: """ - Test Class for ProviderSpecificationComponents + Test Class for MonitorAssistantReleaseImportArtifactResponse """ - def test_provider_specification_components_serialization(self): + def test_monitor_assistant_release_import_artifact_response_serialization(self): """ - Test serialization/deserialization for ProviderSpecificationComponents + Test serialization/deserialization for MonitorAssistantReleaseImportArtifactResponse """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a MonitorAssistantReleaseImportArtifactResponse model + monitor_assistant_release_import_artifact_response_model_json = {} + monitor_assistant_release_import_artifact_response_model_json['skill_impact_in_draft'] = ['action'] - provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue - provider_authentication_type_and_value_model['type'] = 'value' - provider_authentication_type_and_value_model['value'] = 'testString' + # Construct a model instance of MonitorAssistantReleaseImportArtifactResponse by calling from_dict on the json representation + monitor_assistant_release_import_artifact_response_model = MonitorAssistantReleaseImportArtifactResponse.from_dict(monitor_assistant_release_import_artifact_response_model_json) + assert monitor_assistant_release_import_artifact_response_model != False - provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic - provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + # Construct a model instance of MonitorAssistantReleaseImportArtifactResponse by calling from_dict on the json representation + monitor_assistant_release_import_artifact_response_model_dict = MonitorAssistantReleaseImportArtifactResponse.from_dict(monitor_assistant_release_import_artifact_response_model_json).__dict__ + monitor_assistant_release_import_artifact_response_model2 = MonitorAssistantReleaseImportArtifactResponse(**monitor_assistant_release_import_artifact_response_model_dict) - provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername - provider_authentication_o_auth2_password_username_model['type'] = 'value' - provider_authentication_o_auth2_password_username_model['value'] = 'testString' + # Verify the model instances are equivalent + assert monitor_assistant_release_import_artifact_response_model == monitor_assistant_release_import_artifact_response_model2 - provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password - provider_authentication_o_auth2_flows_model['token_url'] = 'testString' - provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' - provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' - provider_authentication_o_auth2_flows_model['content_type'] = 'testString' - provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' - provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + # Convert model instance back to dict and verify no loss of data + monitor_assistant_release_import_artifact_response_model_json2 = monitor_assistant_release_import_artifact_response_model.to_dict() + assert monitor_assistant_release_import_artifact_response_model_json2 == monitor_assistant_release_import_artifact_response_model_json - provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 - provider_authentication_o_auth2_model['preferred_flow'] = 'password' - provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - provider_specification_components_security_schemes_model = {} # ProviderSpecificationComponentsSecuritySchemes - provider_specification_components_security_schemes_model['authentication_method'] = 'basic' - provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model - provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model +class TestModel_Pagination: + """ + Test Class for Pagination + """ - # Construct a json representation of a ProviderSpecificationComponents model - provider_specification_components_model_json = {} - provider_specification_components_model_json['securitySchemes'] = provider_specification_components_security_schemes_model + def test_pagination_serialization(self): + """ + Test serialization/deserialization for Pagination + """ - # Construct a model instance of ProviderSpecificationComponents by calling from_dict on the json representation - provider_specification_components_model = ProviderSpecificationComponents.from_dict(provider_specification_components_model_json) - assert provider_specification_components_model != False + # Construct a json representation of a Pagination model + pagination_model_json = {} + pagination_model_json['refresh_url'] = 'testString' + pagination_model_json['next_url'] = 'testString' + pagination_model_json['total'] = 38 + pagination_model_json['matched'] = 38 + pagination_model_json['refresh_cursor'] = 'testString' + pagination_model_json['next_cursor'] = 'testString' - # Construct a model instance of ProviderSpecificationComponents by calling from_dict on the json representation - provider_specification_components_model_dict = ProviderSpecificationComponents.from_dict(provider_specification_components_model_json).__dict__ - provider_specification_components_model2 = ProviderSpecificationComponents(**provider_specification_components_model_dict) + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model = Pagination.from_dict(pagination_model_json) + assert pagination_model != False + + # Construct a model instance of Pagination by calling from_dict on the json representation + pagination_model_dict = Pagination.from_dict(pagination_model_json).__dict__ + pagination_model2 = Pagination(**pagination_model_dict) # Verify the model instances are equivalent - assert provider_specification_components_model == provider_specification_components_model2 + assert pagination_model == pagination_model2 # Convert model instance back to dict and verify no loss of data - provider_specification_components_model_json2 = provider_specification_components_model.to_dict() - assert provider_specification_components_model_json2 == provider_specification_components_model_json + pagination_model_json2 = pagination_model.to_dict() + assert pagination_model_json2 == pagination_model_json -class TestModel_ProviderSpecificationComponentsSecuritySchemes: +class TestModel_PartialItem: """ - Test Class for ProviderSpecificationComponentsSecuritySchemes + Test Class for PartialItem """ - def test_provider_specification_components_security_schemes_serialization(self): + def test_partial_item_serialization(self): """ - Test serialization/deserialization for ProviderSpecificationComponentsSecuritySchemes + Test serialization/deserialization for PartialItem """ # Construct dict forms of any model objects needed in order to build this model. - provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue - provider_authentication_type_and_value_model['type'] = 'value' - provider_authentication_type_and_value_model['value'] = 'testString' + metadata_model = {} # Metadata + metadata_model['id'] = 38 - provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic - provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + # Construct a json representation of a PartialItem model + partial_item_model_json = {} + partial_item_model_json['response_type'] = 'testString' + partial_item_model_json['text'] = 'testString' + partial_item_model_json['streaming_metadata'] = metadata_model + + # Construct a model instance of PartialItem by calling from_dict on the json representation + partial_item_model = PartialItem.from_dict(partial_item_model_json) + assert partial_item_model != False + + # Construct a model instance of PartialItem by calling from_dict on the json representation + partial_item_model_dict = PartialItem.from_dict(partial_item_model_json).__dict__ + partial_item_model2 = PartialItem(**partial_item_model_dict) + + # Verify the model instances are equivalent + assert partial_item_model == partial_item_model2 + + # Convert model instance back to dict and verify no loss of data + partial_item_model_json2 = partial_item_model.to_dict() + assert partial_item_model_json2 == partial_item_model_json + + +class TestModel_ProviderAuthenticationOAuth2: + """ + Test Class for ProviderAuthenticationOAuth2 + """ + + def test_provider_authentication_o_auth2_serialization(self): + """ + Test serialization/deserialization for ProviderAuthenticationOAuth2 + """ + + # Construct dict forms of any model objects needed in order to build this model. provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername provider_authentication_o_auth2_password_username_model['type'] = 'value' @@ -9435,142 +9525,142 @@ def test_provider_specification_components_security_schemes_serialization(self): provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 - provider_authentication_o_auth2_model['preferred_flow'] = 'password' - provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - - # Construct a json representation of a ProviderSpecificationComponentsSecuritySchemes model - provider_specification_components_security_schemes_model_json = {} - provider_specification_components_security_schemes_model_json['authentication_method'] = 'basic' - provider_specification_components_security_schemes_model_json['basic'] = provider_specification_components_security_schemes_basic_model - provider_specification_components_security_schemes_model_json['oauth2'] = provider_authentication_o_auth2_model + # Construct a json representation of a ProviderAuthenticationOAuth2 model + provider_authentication_o_auth2_model_json = {} + provider_authentication_o_auth2_model_json['preferred_flow'] = 'password' + provider_authentication_o_auth2_model_json['flows'] = provider_authentication_o_auth2_flows_model - # Construct a model instance of ProviderSpecificationComponentsSecuritySchemes by calling from_dict on the json representation - provider_specification_components_security_schemes_model = ProviderSpecificationComponentsSecuritySchemes.from_dict(provider_specification_components_security_schemes_model_json) - assert provider_specification_components_security_schemes_model != False + # Construct a model instance of ProviderAuthenticationOAuth2 by calling from_dict on the json representation + provider_authentication_o_auth2_model = ProviderAuthenticationOAuth2.from_dict(provider_authentication_o_auth2_model_json) + assert provider_authentication_o_auth2_model != False - # Construct a model instance of ProviderSpecificationComponentsSecuritySchemes by calling from_dict on the json representation - provider_specification_components_security_schemes_model_dict = ProviderSpecificationComponentsSecuritySchemes.from_dict(provider_specification_components_security_schemes_model_json).__dict__ - provider_specification_components_security_schemes_model2 = ProviderSpecificationComponentsSecuritySchemes(**provider_specification_components_security_schemes_model_dict) + # Construct a model instance of ProviderAuthenticationOAuth2 by calling from_dict on the json representation + provider_authentication_o_auth2_model_dict = ProviderAuthenticationOAuth2.from_dict(provider_authentication_o_auth2_model_json).__dict__ + provider_authentication_o_auth2_model2 = ProviderAuthenticationOAuth2(**provider_authentication_o_auth2_model_dict) # Verify the model instances are equivalent - assert provider_specification_components_security_schemes_model == provider_specification_components_security_schemes_model2 + assert provider_authentication_o_auth2_model == provider_authentication_o_auth2_model2 # Convert model instance back to dict and verify no loss of data - provider_specification_components_security_schemes_model_json2 = provider_specification_components_security_schemes_model.to_dict() - assert provider_specification_components_security_schemes_model_json2 == provider_specification_components_security_schemes_model_json + provider_authentication_o_auth2_model_json2 = provider_authentication_o_auth2_model.to_dict() + assert provider_authentication_o_auth2_model_json2 == provider_authentication_o_auth2_model_json -class TestModel_ProviderSpecificationComponentsSecuritySchemesBasic: +class TestModel_ProviderAuthenticationOAuth2PasswordUsername: """ - Test Class for ProviderSpecificationComponentsSecuritySchemesBasic + Test Class for ProviderAuthenticationOAuth2PasswordUsername """ - def test_provider_specification_components_security_schemes_basic_serialization(self): + def test_provider_authentication_o_auth2_password_username_serialization(self): """ - Test serialization/deserialization for ProviderSpecificationComponentsSecuritySchemesBasic + Test serialization/deserialization for ProviderAuthenticationOAuth2PasswordUsername """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a ProviderAuthenticationOAuth2PasswordUsername model + provider_authentication_o_auth2_password_username_model_json = {} + provider_authentication_o_auth2_password_username_model_json['type'] = 'value' + provider_authentication_o_auth2_password_username_model_json['value'] = 'testString' - provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue - provider_authentication_type_and_value_model['type'] = 'value' - provider_authentication_type_and_value_model['value'] = 'testString' - - # Construct a json representation of a ProviderSpecificationComponentsSecuritySchemesBasic model - provider_specification_components_security_schemes_basic_model_json = {} - provider_specification_components_security_schemes_basic_model_json['username'] = provider_authentication_type_and_value_model - - # Construct a model instance of ProviderSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation - provider_specification_components_security_schemes_basic_model = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict(provider_specification_components_security_schemes_basic_model_json) - assert provider_specification_components_security_schemes_basic_model != False + # Construct a model instance of ProviderAuthenticationOAuth2PasswordUsername by calling from_dict on the json representation + provider_authentication_o_auth2_password_username_model = ProviderAuthenticationOAuth2PasswordUsername.from_dict(provider_authentication_o_auth2_password_username_model_json) + assert provider_authentication_o_auth2_password_username_model != False - # Construct a model instance of ProviderSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation - provider_specification_components_security_schemes_basic_model_dict = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict(provider_specification_components_security_schemes_basic_model_json).__dict__ - provider_specification_components_security_schemes_basic_model2 = ProviderSpecificationComponentsSecuritySchemesBasic(**provider_specification_components_security_schemes_basic_model_dict) + # Construct a model instance of ProviderAuthenticationOAuth2PasswordUsername by calling from_dict on the json representation + provider_authentication_o_auth2_password_username_model_dict = ProviderAuthenticationOAuth2PasswordUsername.from_dict(provider_authentication_o_auth2_password_username_model_json).__dict__ + provider_authentication_o_auth2_password_username_model2 = ProviderAuthenticationOAuth2PasswordUsername(**provider_authentication_o_auth2_password_username_model_dict) # Verify the model instances are equivalent - assert provider_specification_components_security_schemes_basic_model == provider_specification_components_security_schemes_basic_model2 + assert provider_authentication_o_auth2_password_username_model == provider_authentication_o_auth2_password_username_model2 # Convert model instance back to dict and verify no loss of data - provider_specification_components_security_schemes_basic_model_json2 = provider_specification_components_security_schemes_basic_model.to_dict() - assert provider_specification_components_security_schemes_basic_model_json2 == provider_specification_components_security_schemes_basic_model_json + provider_authentication_o_auth2_password_username_model_json2 = provider_authentication_o_auth2_password_username_model.to_dict() + assert provider_authentication_o_auth2_password_username_model_json2 == provider_authentication_o_auth2_password_username_model_json -class TestModel_ProviderSpecificationServersItem: +class TestModel_ProviderAuthenticationTypeAndValue: """ - Test Class for ProviderSpecificationServersItem + Test Class for ProviderAuthenticationTypeAndValue """ - def test_provider_specification_servers_item_serialization(self): + def test_provider_authentication_type_and_value_serialization(self): """ - Test serialization/deserialization for ProviderSpecificationServersItem + Test serialization/deserialization for ProviderAuthenticationTypeAndValue """ - # Construct a json representation of a ProviderSpecificationServersItem model - provider_specification_servers_item_model_json = {} - provider_specification_servers_item_model_json['url'] = 'testString' + # Construct a json representation of a ProviderAuthenticationTypeAndValue model + provider_authentication_type_and_value_model_json = {} + provider_authentication_type_and_value_model_json['type'] = 'value' + provider_authentication_type_and_value_model_json['value'] = 'testString' - # Construct a model instance of ProviderSpecificationServersItem by calling from_dict on the json representation - provider_specification_servers_item_model = ProviderSpecificationServersItem.from_dict(provider_specification_servers_item_model_json) - assert provider_specification_servers_item_model != False + # Construct a model instance of ProviderAuthenticationTypeAndValue by calling from_dict on the json representation + provider_authentication_type_and_value_model = ProviderAuthenticationTypeAndValue.from_dict(provider_authentication_type_and_value_model_json) + assert provider_authentication_type_and_value_model != False - # Construct a model instance of ProviderSpecificationServersItem by calling from_dict on the json representation - provider_specification_servers_item_model_dict = ProviderSpecificationServersItem.from_dict(provider_specification_servers_item_model_json).__dict__ - provider_specification_servers_item_model2 = ProviderSpecificationServersItem(**provider_specification_servers_item_model_dict) + # Construct a model instance of ProviderAuthenticationTypeAndValue by calling from_dict on the json representation + provider_authentication_type_and_value_model_dict = ProviderAuthenticationTypeAndValue.from_dict(provider_authentication_type_and_value_model_json).__dict__ + provider_authentication_type_and_value_model2 = ProviderAuthenticationTypeAndValue(**provider_authentication_type_and_value_model_dict) # Verify the model instances are equivalent - assert provider_specification_servers_item_model == provider_specification_servers_item_model2 + assert provider_authentication_type_and_value_model == provider_authentication_type_and_value_model2 # Convert model instance back to dict and verify no loss of data - provider_specification_servers_item_model_json2 = provider_specification_servers_item_model.to_dict() - assert provider_specification_servers_item_model_json2 == provider_specification_servers_item_model_json + provider_authentication_type_and_value_model_json2 = provider_authentication_type_and_value_model.to_dict() + assert provider_authentication_type_and_value_model_json2 == provider_authentication_type_and_value_model_json -class TestModel_Release: +class TestModel_ProviderCollection: """ - Test Class for Release + Test Class for ProviderCollection """ - def test_release_serialization(self): + def test_provider_collection_serialization(self): """ - Test serialization/deserialization for Release + Test serialization/deserialization for ProviderCollection """ - # Construct a json representation of a Release model - release_model_json = {} - release_model_json['description'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of Release by calling from_dict on the json representation - release_model = Release.from_dict(release_model_json) - assert release_model != False + provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem + provider_response_specification_servers_item_model['url'] = 'testString' - # Construct a model instance of Release by calling from_dict on the json representation - release_model_dict = Release.from_dict(release_model_json).__dict__ - release_model2 = Release(**release_model_dict) + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Verify the model instances are equivalent - assert release_model == release_model2 + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - # Convert model instance back to dict and verify no loss of data - release_model_json2 = release_model.to_dict() - assert release_model_json2 == release_model_json + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model -class TestModel_ReleaseCollection: - """ - Test Class for ReleaseCollection - """ + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - def test_release_collection_serialization(self): - """ - Test serialization/deserialization for ReleaseCollection - """ + provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents + provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model - # Construct dict forms of any model objects needed in order to build this model. + provider_response_specification_model = {} # ProviderResponseSpecification + provider_response_specification_model['servers'] = [provider_response_specification_servers_item_model] + provider_response_specification_model['components'] = provider_response_specification_components_model - release_model = {} # Release - release_model['description'] = 'testString' + provider_response_model = {} # ProviderResponse + provider_response_model['provider_id'] = 'testString' + provider_response_model['specification'] = provider_response_specification_model pagination_model = {} # Pagination pagination_model['refresh_url'] = 'testString' @@ -9580,1320 +9670,1454 @@ def test_release_collection_serialization(self): pagination_model['refresh_cursor'] = 'testString' pagination_model['next_cursor'] = 'testString' - # Construct a json representation of a ReleaseCollection model - release_collection_model_json = {} - release_collection_model_json['releases'] = [release_model] - release_collection_model_json['pagination'] = pagination_model + # Construct a json representation of a ProviderCollection model + provider_collection_model_json = {} + provider_collection_model_json['conversational_skill_providers'] = [provider_response_model] + provider_collection_model_json['pagination'] = pagination_model - # Construct a model instance of ReleaseCollection by calling from_dict on the json representation - release_collection_model = ReleaseCollection.from_dict(release_collection_model_json) - assert release_collection_model != False + # Construct a model instance of ProviderCollection by calling from_dict on the json representation + provider_collection_model = ProviderCollection.from_dict(provider_collection_model_json) + assert provider_collection_model != False - # Construct a model instance of ReleaseCollection by calling from_dict on the json representation - release_collection_model_dict = ReleaseCollection.from_dict(release_collection_model_json).__dict__ - release_collection_model2 = ReleaseCollection(**release_collection_model_dict) + # Construct a model instance of ProviderCollection by calling from_dict on the json representation + provider_collection_model_dict = ProviderCollection.from_dict(provider_collection_model_json).__dict__ + provider_collection_model2 = ProviderCollection(**provider_collection_model_dict) # Verify the model instances are equivalent - assert release_collection_model == release_collection_model2 + assert provider_collection_model == provider_collection_model2 # Convert model instance back to dict and verify no loss of data - release_collection_model_json2 = release_collection_model.to_dict() - assert release_collection_model_json2 == release_collection_model_json + provider_collection_model_json2 = provider_collection_model.to_dict() + assert provider_collection_model_json2 == provider_collection_model_json -class TestModel_ReleaseContent: +class TestModel_ProviderPrivate: """ - Test Class for ReleaseContent + Test Class for ProviderPrivate """ - def test_release_content_serialization(self): + def test_provider_private_serialization(self): """ - Test serialization/deserialization for ReleaseContent + Test serialization/deserialization for ProviderPrivate """ - # Construct a json representation of a ReleaseContent model - release_content_model_json = {} + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of ReleaseContent by calling from_dict on the json representation - release_content_model = ReleaseContent.from_dict(release_content_model_json) - assert release_content_model != False + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a model instance of ReleaseContent by calling from_dict on the json representation - release_content_model_dict = ReleaseContent.from_dict(release_content_model_json).__dict__ - release_content_model2 = ReleaseContent(**release_content_model_dict) + provider_private_authentication_model = {} # ProviderPrivateAuthenticationBearerFlow + provider_private_authentication_model['token'] = provider_authentication_type_and_value_model + + # Construct a json representation of a ProviderPrivate model + provider_private_model_json = {} + provider_private_model_json['authentication'] = provider_private_authentication_model + + # Construct a model instance of ProviderPrivate by calling from_dict on the json representation + provider_private_model = ProviderPrivate.from_dict(provider_private_model_json) + assert provider_private_model != False + + # Construct a model instance of ProviderPrivate by calling from_dict on the json representation + provider_private_model_dict = ProviderPrivate.from_dict(provider_private_model_json).__dict__ + provider_private_model2 = ProviderPrivate(**provider_private_model_dict) # Verify the model instances are equivalent - assert release_content_model == release_content_model2 + assert provider_private_model == provider_private_model2 # Convert model instance back to dict and verify no loss of data - release_content_model_json2 = release_content_model.to_dict() - assert release_content_model_json2 == release_content_model_json + provider_private_model_json2 = provider_private_model.to_dict() + assert provider_private_model_json2 == provider_private_model_json -class TestModel_ReleaseSkill: +class TestModel_ProviderPrivateAuthenticationOAuth2PasswordPassword: """ - Test Class for ReleaseSkill + Test Class for ProviderPrivateAuthenticationOAuth2PasswordPassword """ - def test_release_skill_serialization(self): + def test_provider_private_authentication_o_auth2_password_password_serialization(self): """ - Test serialization/deserialization for ReleaseSkill + Test serialization/deserialization for ProviderPrivateAuthenticationOAuth2PasswordPassword """ - # Construct a json representation of a ReleaseSkill model - release_skill_model_json = {} - release_skill_model_json['skill_id'] = 'testString' - release_skill_model_json['type'] = 'dialog' - release_skill_model_json['snapshot'] = 'testString' + # Construct a json representation of a ProviderPrivateAuthenticationOAuth2PasswordPassword model + provider_private_authentication_o_auth2_password_password_model_json = {} + provider_private_authentication_o_auth2_password_password_model_json['type'] = 'value' + provider_private_authentication_o_auth2_password_password_model_json['value'] = 'testString' - # Construct a model instance of ReleaseSkill by calling from_dict on the json representation - release_skill_model = ReleaseSkill.from_dict(release_skill_model_json) - assert release_skill_model != False + # Construct a model instance of ProviderPrivateAuthenticationOAuth2PasswordPassword by calling from_dict on the json representation + provider_private_authentication_o_auth2_password_password_model = ProviderPrivateAuthenticationOAuth2PasswordPassword.from_dict(provider_private_authentication_o_auth2_password_password_model_json) + assert provider_private_authentication_o_auth2_password_password_model != False - # Construct a model instance of ReleaseSkill by calling from_dict on the json representation - release_skill_model_dict = ReleaseSkill.from_dict(release_skill_model_json).__dict__ - release_skill_model2 = ReleaseSkill(**release_skill_model_dict) + # Construct a model instance of ProviderPrivateAuthenticationOAuth2PasswordPassword by calling from_dict on the json representation + provider_private_authentication_o_auth2_password_password_model_dict = ProviderPrivateAuthenticationOAuth2PasswordPassword.from_dict(provider_private_authentication_o_auth2_password_password_model_json).__dict__ + provider_private_authentication_o_auth2_password_password_model2 = ProviderPrivateAuthenticationOAuth2PasswordPassword(**provider_private_authentication_o_auth2_password_password_model_dict) # Verify the model instances are equivalent - assert release_skill_model == release_skill_model2 + assert provider_private_authentication_o_auth2_password_password_model == provider_private_authentication_o_auth2_password_password_model2 # Convert model instance back to dict and verify no loss of data - release_skill_model_json2 = release_skill_model.to_dict() - assert release_skill_model_json2 == release_skill_model_json + provider_private_authentication_o_auth2_password_password_model_json2 = provider_private_authentication_o_auth2_password_password_model.to_dict() + assert provider_private_authentication_o_auth2_password_password_model_json2 == provider_private_authentication_o_auth2_password_password_model_json -class TestModel_RequestAnalytics: +class TestModel_ProviderResponse: """ - Test Class for RequestAnalytics + Test Class for ProviderResponse """ - def test_request_analytics_serialization(self): + def test_provider_response_serialization(self): """ - Test serialization/deserialization for RequestAnalytics + Test serialization/deserialization for ProviderResponse """ - # Construct a json representation of a RequestAnalytics model - request_analytics_model_json = {} - request_analytics_model_json['browser'] = 'testString' - request_analytics_model_json['device'] = 'testString' - request_analytics_model_json['pageUrl'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of RequestAnalytics by calling from_dict on the json representation - request_analytics_model = RequestAnalytics.from_dict(request_analytics_model_json) - assert request_analytics_model != False + provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem + provider_response_specification_servers_item_model['url'] = 'testString' - # Construct a model instance of RequestAnalytics by calling from_dict on the json representation - request_analytics_model_dict = RequestAnalytics.from_dict(request_analytics_model_json).__dict__ - request_analytics_model2 = RequestAnalytics(**request_analytics_model_dict) + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Verify the model instances are equivalent - assert request_analytics_model == request_analytics_model2 + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - # Convert model instance back to dict and verify no loss of data - request_analytics_model_json2 = request_analytics_model.to_dict() - assert request_analytics_model_json2 == request_analytics_model_json + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model -class TestModel_ResponseGenericChannel: - """ - Test Class for ResponseGenericChannel - """ + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - def test_response_generic_channel_serialization(self): - """ - Test serialization/deserialization for ResponseGenericChannel - """ + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - # Construct a json representation of a ResponseGenericChannel model - response_generic_channel_model_json = {} - response_generic_channel_model_json['channel'] = 'testString' + provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents + provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model - # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation - response_generic_channel_model = ResponseGenericChannel.from_dict(response_generic_channel_model_json) - assert response_generic_channel_model != False + provider_response_specification_model = {} # ProviderResponseSpecification + provider_response_specification_model['servers'] = [provider_response_specification_servers_item_model] + provider_response_specification_model['components'] = provider_response_specification_components_model - # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation - response_generic_channel_model_dict = ResponseGenericChannel.from_dict(response_generic_channel_model_json).__dict__ - response_generic_channel_model2 = ResponseGenericChannel(**response_generic_channel_model_dict) + # Construct a json representation of a ProviderResponse model + provider_response_model_json = {} + provider_response_model_json['provider_id'] = 'testString' + provider_response_model_json['specification'] = provider_response_specification_model + + # Construct a model instance of ProviderResponse by calling from_dict on the json representation + provider_response_model = ProviderResponse.from_dict(provider_response_model_json) + assert provider_response_model != False + + # Construct a model instance of ProviderResponse by calling from_dict on the json representation + provider_response_model_dict = ProviderResponse.from_dict(provider_response_model_json).__dict__ + provider_response_model2 = ProviderResponse(**provider_response_model_dict) # Verify the model instances are equivalent - assert response_generic_channel_model == response_generic_channel_model2 + assert provider_response_model == provider_response_model2 # Convert model instance back to dict and verify no loss of data - response_generic_channel_model_json2 = response_generic_channel_model.to_dict() - assert response_generic_channel_model_json2 == response_generic_channel_model_json + provider_response_model_json2 = provider_response_model.to_dict() + assert provider_response_model_json2 == provider_response_model_json -class TestModel_RuntimeEntity: +class TestModel_ProviderResponseSpecification: """ - Test Class for RuntimeEntity + Test Class for ProviderResponseSpecification """ - def test_runtime_entity_serialization(self): + def test_provider_response_specification_serialization(self): """ - Test serialization/deserialization for RuntimeEntity + Test serialization/deserialization for ProviderResponseSpecification """ # Construct dict forms of any model objects needed in order to build this model. - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + provider_response_specification_servers_item_model = {} # ProviderResponseSpecificationServersItem + provider_response_specification_servers_item_model['url'] = 'testString' - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - # Construct a json representation of a RuntimeEntity model - runtime_entity_model_json = {} - runtime_entity_model_json['entity'] = 'testString' - runtime_entity_model_json['location'] = [38] - runtime_entity_model_json['value'] = 'testString' - runtime_entity_model_json['confidence'] = 72.5 - runtime_entity_model_json['groups'] = [capture_group_model] - runtime_entity_model_json['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model_json['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model_json['role'] = runtime_entity_role_model - runtime_entity_model_json['skill'] = 'testString' + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - # Construct a model instance of RuntimeEntity by calling from_dict on the json representation - runtime_entity_model = RuntimeEntity.from_dict(runtime_entity_model_json) - assert runtime_entity_model != False + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - # Construct a model instance of RuntimeEntity by calling from_dict on the json representation - runtime_entity_model_dict = RuntimeEntity.from_dict(runtime_entity_model_json).__dict__ - runtime_entity_model2 = RuntimeEntity(**runtime_entity_model_dict) + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + provider_response_specification_components_model = {} # ProviderResponseSpecificationComponents + provider_response_specification_components_model['securitySchemes'] = provider_response_specification_components_security_schemes_model + + # Construct a json representation of a ProviderResponseSpecification model + provider_response_specification_model_json = {} + provider_response_specification_model_json['servers'] = [provider_response_specification_servers_item_model] + provider_response_specification_model_json['components'] = provider_response_specification_components_model + + # Construct a model instance of ProviderResponseSpecification by calling from_dict on the json representation + provider_response_specification_model = ProviderResponseSpecification.from_dict(provider_response_specification_model_json) + assert provider_response_specification_model != False + + # Construct a model instance of ProviderResponseSpecification by calling from_dict on the json representation + provider_response_specification_model_dict = ProviderResponseSpecification.from_dict(provider_response_specification_model_json).__dict__ + provider_response_specification_model2 = ProviderResponseSpecification(**provider_response_specification_model_dict) # Verify the model instances are equivalent - assert runtime_entity_model == runtime_entity_model2 + assert provider_response_specification_model == provider_response_specification_model2 # Convert model instance back to dict and verify no loss of data - runtime_entity_model_json2 = runtime_entity_model.to_dict() - assert runtime_entity_model_json2 == runtime_entity_model_json + provider_response_specification_model_json2 = provider_response_specification_model.to_dict() + assert provider_response_specification_model_json2 == provider_response_specification_model_json -class TestModel_RuntimeEntityAlternative: +class TestModel_ProviderResponseSpecificationComponents: """ - Test Class for RuntimeEntityAlternative + Test Class for ProviderResponseSpecificationComponents """ - def test_runtime_entity_alternative_serialization(self): + def test_provider_response_specification_components_serialization(self): """ - Test serialization/deserialization for RuntimeEntityAlternative + Test serialization/deserialization for ProviderResponseSpecificationComponents """ - # Construct a json representation of a RuntimeEntityAlternative model - runtime_entity_alternative_model_json = {} - runtime_entity_alternative_model_json['value'] = 'testString' - runtime_entity_alternative_model_json['confidence'] = 72.5 + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation - runtime_entity_alternative_model = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json) - assert runtime_entity_alternative_model != False + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation - runtime_entity_alternative_model_dict = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json).__dict__ - runtime_entity_alternative_model2 = RuntimeEntityAlternative(**runtime_entity_alternative_model_dict) + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + provider_response_specification_components_security_schemes_model = {} # ProviderResponseSpecificationComponentsSecuritySchemes + provider_response_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model + + # Construct a json representation of a ProviderResponseSpecificationComponents model + provider_response_specification_components_model_json = {} + provider_response_specification_components_model_json['securitySchemes'] = provider_response_specification_components_security_schemes_model + + # Construct a model instance of ProviderResponseSpecificationComponents by calling from_dict on the json representation + provider_response_specification_components_model = ProviderResponseSpecificationComponents.from_dict(provider_response_specification_components_model_json) + assert provider_response_specification_components_model != False + + # Construct a model instance of ProviderResponseSpecificationComponents by calling from_dict on the json representation + provider_response_specification_components_model_dict = ProviderResponseSpecificationComponents.from_dict(provider_response_specification_components_model_json).__dict__ + provider_response_specification_components_model2 = ProviderResponseSpecificationComponents(**provider_response_specification_components_model_dict) # Verify the model instances are equivalent - assert runtime_entity_alternative_model == runtime_entity_alternative_model2 + assert provider_response_specification_components_model == provider_response_specification_components_model2 # Convert model instance back to dict and verify no loss of data - runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() - assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json + provider_response_specification_components_model_json2 = provider_response_specification_components_model.to_dict() + assert provider_response_specification_components_model_json2 == provider_response_specification_components_model_json -class TestModel_RuntimeEntityInterpretation: +class TestModel_ProviderResponseSpecificationComponentsSecuritySchemes: """ - Test Class for RuntimeEntityInterpretation + Test Class for ProviderResponseSpecificationComponentsSecuritySchemes """ - def test_runtime_entity_interpretation_serialization(self): + def test_provider_response_specification_components_security_schemes_serialization(self): """ - Test serialization/deserialization for RuntimeEntityInterpretation + Test serialization/deserialization for ProviderResponseSpecificationComponentsSecuritySchemes """ - # Construct a json representation of a RuntimeEntityInterpretation model - runtime_entity_interpretation_model_json = {} - runtime_entity_interpretation_model_json['calendar_type'] = 'testString' - runtime_entity_interpretation_model_json['datetime_link'] = 'testString' - runtime_entity_interpretation_model_json['festival'] = 'testString' - runtime_entity_interpretation_model_json['granularity'] = 'day' - runtime_entity_interpretation_model_json['range_link'] = 'testString' - runtime_entity_interpretation_model_json['range_modifier'] = 'testString' - runtime_entity_interpretation_model_json['relative_day'] = 72.5 - runtime_entity_interpretation_model_json['relative_month'] = 72.5 - runtime_entity_interpretation_model_json['relative_week'] = 72.5 - runtime_entity_interpretation_model_json['relative_weekend'] = 72.5 - runtime_entity_interpretation_model_json['relative_year'] = 72.5 - runtime_entity_interpretation_model_json['specific_day'] = 72.5 - runtime_entity_interpretation_model_json['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model_json['specific_month'] = 72.5 - runtime_entity_interpretation_model_json['specific_quarter'] = 72.5 - runtime_entity_interpretation_model_json['specific_year'] = 72.5 - runtime_entity_interpretation_model_json['numeric_value'] = 72.5 - runtime_entity_interpretation_model_json['subtype'] = 'testString' - runtime_entity_interpretation_model_json['part_of_day'] = 'testString' - runtime_entity_interpretation_model_json['relative_hour'] = 72.5 - runtime_entity_interpretation_model_json['relative_minute'] = 72.5 - runtime_entity_interpretation_model_json['relative_second'] = 72.5 - runtime_entity_interpretation_model_json['specific_hour'] = 72.5 - runtime_entity_interpretation_model_json['specific_minute'] = 72.5 - runtime_entity_interpretation_model_json['specific_second'] = 72.5 - runtime_entity_interpretation_model_json['timezone'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation - runtime_entity_interpretation_model = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json) - assert runtime_entity_interpretation_model != False + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation - runtime_entity_interpretation_model_dict = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json).__dict__ - runtime_entity_interpretation_model2 = RuntimeEntityInterpretation(**runtime_entity_interpretation_model_dict) + provider_response_specification_components_security_schemes_basic_model = {} # ProviderResponseSpecificationComponentsSecuritySchemesBasic + provider_response_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model + + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model + + # Construct a json representation of a ProviderResponseSpecificationComponentsSecuritySchemes model + provider_response_specification_components_security_schemes_model_json = {} + provider_response_specification_components_security_schemes_model_json['authentication_method'] = 'basic' + provider_response_specification_components_security_schemes_model_json['basic'] = provider_response_specification_components_security_schemes_basic_model + provider_response_specification_components_security_schemes_model_json['oauth2'] = provider_authentication_o_auth2_model + + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_response_specification_components_security_schemes_model = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict(provider_response_specification_components_security_schemes_model_json) + assert provider_response_specification_components_security_schemes_model != False + + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_response_specification_components_security_schemes_model_dict = ProviderResponseSpecificationComponentsSecuritySchemes.from_dict(provider_response_specification_components_security_schemes_model_json).__dict__ + provider_response_specification_components_security_schemes_model2 = ProviderResponseSpecificationComponentsSecuritySchemes(**provider_response_specification_components_security_schemes_model_dict) # Verify the model instances are equivalent - assert runtime_entity_interpretation_model == runtime_entity_interpretation_model2 + assert provider_response_specification_components_security_schemes_model == provider_response_specification_components_security_schemes_model2 # Convert model instance back to dict and verify no loss of data - runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() - assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json + provider_response_specification_components_security_schemes_model_json2 = provider_response_specification_components_security_schemes_model.to_dict() + assert provider_response_specification_components_security_schemes_model_json2 == provider_response_specification_components_security_schemes_model_json -class TestModel_RuntimeEntityRole: +class TestModel_ProviderResponseSpecificationComponentsSecuritySchemesBasic: """ - Test Class for RuntimeEntityRole + Test Class for ProviderResponseSpecificationComponentsSecuritySchemesBasic """ - def test_runtime_entity_role_serialization(self): + def test_provider_response_specification_components_security_schemes_basic_serialization(self): """ - Test serialization/deserialization for RuntimeEntityRole + Test serialization/deserialization for ProviderResponseSpecificationComponentsSecuritySchemesBasic """ - # Construct a json representation of a RuntimeEntityRole model - runtime_entity_role_model_json = {} - runtime_entity_role_model_json['type'] = 'date_from' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation - runtime_entity_role_model = RuntimeEntityRole.from_dict(runtime_entity_role_model_json) - assert runtime_entity_role_model != False + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation - runtime_entity_role_model_dict = RuntimeEntityRole.from_dict(runtime_entity_role_model_json).__dict__ - runtime_entity_role_model2 = RuntimeEntityRole(**runtime_entity_role_model_dict) + # Construct a json representation of a ProviderResponseSpecificationComponentsSecuritySchemesBasic model + provider_response_specification_components_security_schemes_basic_model_json = {} + provider_response_specification_components_security_schemes_basic_model_json['username'] = provider_authentication_type_and_value_model + + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_response_specification_components_security_schemes_basic_model = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict(provider_response_specification_components_security_schemes_basic_model_json) + assert provider_response_specification_components_security_schemes_basic_model != False + + # Construct a model instance of ProviderResponseSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_response_specification_components_security_schemes_basic_model_dict = ProviderResponseSpecificationComponentsSecuritySchemesBasic.from_dict(provider_response_specification_components_security_schemes_basic_model_json).__dict__ + provider_response_specification_components_security_schemes_basic_model2 = ProviderResponseSpecificationComponentsSecuritySchemesBasic(**provider_response_specification_components_security_schemes_basic_model_dict) # Verify the model instances are equivalent - assert runtime_entity_role_model == runtime_entity_role_model2 + assert provider_response_specification_components_security_schemes_basic_model == provider_response_specification_components_security_schemes_basic_model2 # Convert model instance back to dict and verify no loss of data - runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() - assert runtime_entity_role_model_json2 == runtime_entity_role_model_json + provider_response_specification_components_security_schemes_basic_model_json2 = provider_response_specification_components_security_schemes_basic_model.to_dict() + assert provider_response_specification_components_security_schemes_basic_model_json2 == provider_response_specification_components_security_schemes_basic_model_json -class TestModel_RuntimeIntent: +class TestModel_ProviderResponseSpecificationServersItem: """ - Test Class for RuntimeIntent + Test Class for ProviderResponseSpecificationServersItem """ - def test_runtime_intent_serialization(self): + def test_provider_response_specification_servers_item_serialization(self): """ - Test serialization/deserialization for RuntimeIntent + Test serialization/deserialization for ProviderResponseSpecificationServersItem """ - # Construct a json representation of a RuntimeIntent model - runtime_intent_model_json = {} - runtime_intent_model_json['intent'] = 'testString' - runtime_intent_model_json['confidence'] = 72.5 - runtime_intent_model_json['skill'] = 'testString' + # Construct a json representation of a ProviderResponseSpecificationServersItem model + provider_response_specification_servers_item_model_json = {} + provider_response_specification_servers_item_model_json['url'] = 'testString' - # Construct a model instance of RuntimeIntent by calling from_dict on the json representation - runtime_intent_model = RuntimeIntent.from_dict(runtime_intent_model_json) - assert runtime_intent_model != False + # Construct a model instance of ProviderResponseSpecificationServersItem by calling from_dict on the json representation + provider_response_specification_servers_item_model = ProviderResponseSpecificationServersItem.from_dict(provider_response_specification_servers_item_model_json) + assert provider_response_specification_servers_item_model != False - # Construct a model instance of RuntimeIntent by calling from_dict on the json representation - runtime_intent_model_dict = RuntimeIntent.from_dict(runtime_intent_model_json).__dict__ - runtime_intent_model2 = RuntimeIntent(**runtime_intent_model_dict) + # Construct a model instance of ProviderResponseSpecificationServersItem by calling from_dict on the json representation + provider_response_specification_servers_item_model_dict = ProviderResponseSpecificationServersItem.from_dict(provider_response_specification_servers_item_model_json).__dict__ + provider_response_specification_servers_item_model2 = ProviderResponseSpecificationServersItem(**provider_response_specification_servers_item_model_dict) # Verify the model instances are equivalent - assert runtime_intent_model == runtime_intent_model2 + assert provider_response_specification_servers_item_model == provider_response_specification_servers_item_model2 # Convert model instance back to dict and verify no loss of data - runtime_intent_model_json2 = runtime_intent_model.to_dict() - assert runtime_intent_model_json2 == runtime_intent_model_json + provider_response_specification_servers_item_model_json2 = provider_response_specification_servers_item_model.to_dict() + assert provider_response_specification_servers_item_model_json2 == provider_response_specification_servers_item_model_json -class TestModel_SearchResult: +class TestModel_ProviderSpecification: """ - Test Class for SearchResult + Test Class for ProviderSpecification """ - def test_search_result_serialization(self): + def test_provider_specification_serialization(self): """ - Test serialization/deserialization for SearchResult + Test serialization/deserialization for ProviderSpecification """ # Construct dict forms of any model objects needed in order to build this model. - search_result_metadata_model = {} # SearchResultMetadata - search_result_metadata_model['confidence'] = 72.5 - search_result_metadata_model['score'] = 72.5 - - search_result_highlight_model = {} # SearchResultHighlight - search_result_highlight_model['body'] = ['testString'] - search_result_highlight_model['title'] = ['testString'] - search_result_highlight_model['url'] = ['testString'] - search_result_highlight_model['foo'] = ['testString'] - - search_result_answer_model = {} # SearchResultAnswer - search_result_answer_model['text'] = 'testString' - search_result_answer_model['confidence'] = 0 - - # Construct a json representation of a SearchResult model - search_result_model_json = {} - search_result_model_json['id'] = 'testString' - search_result_model_json['result_metadata'] = search_result_metadata_model - search_result_model_json['body'] = 'testString' - search_result_model_json['title'] = 'testString' - search_result_model_json['url'] = 'testString' - search_result_model_json['highlight'] = search_result_highlight_model - search_result_model_json['answers'] = [search_result_answer_model] + provider_specification_servers_item_model = {} # ProviderSpecificationServersItem + provider_specification_servers_item_model['url'] = 'testString' - # Construct a model instance of SearchResult by calling from_dict on the json representation - search_result_model = SearchResult.from_dict(search_result_model_json) - assert search_result_model != False + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Construct a model instance of SearchResult by calling from_dict on the json representation - search_result_model_dict = SearchResult.from_dict(search_result_model_json).__dict__ - search_result_model2 = SearchResult(**search_result_model_dict) + provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - # Verify the model instances are equivalent - assert search_result_model == search_result_model2 + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - # Convert model instance back to dict and verify no loss of data - search_result_model_json2 = search_result_model.to_dict() - assert search_result_model_json2 == search_result_model_json + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model -class TestModel_SearchResultAnswer: - """ - Test Class for SearchResultAnswer - """ + provider_specification_components_security_schemes_model = {} # ProviderSpecificationComponentsSecuritySchemes + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - def test_search_result_answer_serialization(self): - """ - Test serialization/deserialization for SearchResultAnswer - """ + provider_specification_components_model = {} # ProviderSpecificationComponents + provider_specification_components_model['securitySchemes'] = provider_specification_components_security_schemes_model - # Construct a json representation of a SearchResultAnswer model - search_result_answer_model_json = {} - search_result_answer_model_json['text'] = 'testString' - search_result_answer_model_json['confidence'] = 0 + # Construct a json representation of a ProviderSpecification model + provider_specification_model_json = {} + provider_specification_model_json['servers'] = [provider_specification_servers_item_model] + provider_specification_model_json['components'] = provider_specification_components_model - # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation - search_result_answer_model = SearchResultAnswer.from_dict(search_result_answer_model_json) - assert search_result_answer_model != False + # Construct a model instance of ProviderSpecification by calling from_dict on the json representation + provider_specification_model = ProviderSpecification.from_dict(provider_specification_model_json) + assert provider_specification_model != False - # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation - search_result_answer_model_dict = SearchResultAnswer.from_dict(search_result_answer_model_json).__dict__ - search_result_answer_model2 = SearchResultAnswer(**search_result_answer_model_dict) + # Construct a model instance of ProviderSpecification by calling from_dict on the json representation + provider_specification_model_dict = ProviderSpecification.from_dict(provider_specification_model_json).__dict__ + provider_specification_model2 = ProviderSpecification(**provider_specification_model_dict) # Verify the model instances are equivalent - assert search_result_answer_model == search_result_answer_model2 + assert provider_specification_model == provider_specification_model2 # Convert model instance back to dict and verify no loss of data - search_result_answer_model_json2 = search_result_answer_model.to_dict() - assert search_result_answer_model_json2 == search_result_answer_model_json + provider_specification_model_json2 = provider_specification_model.to_dict() + assert provider_specification_model_json2 == provider_specification_model_json -class TestModel_SearchResultHighlight: +class TestModel_ProviderSpecificationComponents: """ - Test Class for SearchResultHighlight + Test Class for ProviderSpecificationComponents """ - def test_search_result_highlight_serialization(self): + def test_provider_specification_components_serialization(self): """ - Test serialization/deserialization for SearchResultHighlight + Test serialization/deserialization for ProviderSpecificationComponents """ - # Construct a json representation of a SearchResultHighlight model - search_result_highlight_model_json = {} - search_result_highlight_model_json['body'] = ['testString'] - search_result_highlight_model_json['title'] = ['testString'] - search_result_highlight_model_json['url'] = ['testString'] - search_result_highlight_model_json['foo'] = ['testString'] - - # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation - search_result_highlight_model = SearchResultHighlight.from_dict(search_result_highlight_model_json) - assert search_result_highlight_model != False + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation - search_result_highlight_model_dict = SearchResultHighlight.from_dict(search_result_highlight_model_json).__dict__ - search_result_highlight_model2 = SearchResultHighlight(**search_result_highlight_model_dict) + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - # Verify the model instances are equivalent - assert search_result_highlight_model == search_result_highlight_model2 - - # Convert model instance back to dict and verify no loss of data - search_result_highlight_model_json2 = search_result_highlight_model.to_dict() - assert search_result_highlight_model_json2 == search_result_highlight_model_json - - # Test get_properties and set_properties methods. - search_result_highlight_model.set_properties({}) - actual_dict = search_result_highlight_model.get_properties() - assert actual_dict == {} + provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - expected_dict = {'foo': ['testString']} - search_result_highlight_model.set_properties(expected_dict) - actual_dict = search_result_highlight_model.get_properties() - assert actual_dict.keys() == expected_dict.keys() + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model -class TestModel_SearchResultMetadata: - """ - Test Class for SearchResultMetadata - """ + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - def test_search_result_metadata_serialization(self): - """ - Test serialization/deserialization for SearchResultMetadata - """ + provider_specification_components_security_schemes_model = {} # ProviderSpecificationComponentsSecuritySchemes + provider_specification_components_security_schemes_model['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model['oauth2'] = provider_authentication_o_auth2_model - # Construct a json representation of a SearchResultMetadata model - search_result_metadata_model_json = {} - search_result_metadata_model_json['confidence'] = 72.5 - search_result_metadata_model_json['score'] = 72.5 + # Construct a json representation of a ProviderSpecificationComponents model + provider_specification_components_model_json = {} + provider_specification_components_model_json['securitySchemes'] = provider_specification_components_security_schemes_model - # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation - search_result_metadata_model = SearchResultMetadata.from_dict(search_result_metadata_model_json) - assert search_result_metadata_model != False + # Construct a model instance of ProviderSpecificationComponents by calling from_dict on the json representation + provider_specification_components_model = ProviderSpecificationComponents.from_dict(provider_specification_components_model_json) + assert provider_specification_components_model != False - # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation - search_result_metadata_model_dict = SearchResultMetadata.from_dict(search_result_metadata_model_json).__dict__ - search_result_metadata_model2 = SearchResultMetadata(**search_result_metadata_model_dict) + # Construct a model instance of ProviderSpecificationComponents by calling from_dict on the json representation + provider_specification_components_model_dict = ProviderSpecificationComponents.from_dict(provider_specification_components_model_json).__dict__ + provider_specification_components_model2 = ProviderSpecificationComponents(**provider_specification_components_model_dict) # Verify the model instances are equivalent - assert search_result_metadata_model == search_result_metadata_model2 + assert provider_specification_components_model == provider_specification_components_model2 # Convert model instance back to dict and verify no loss of data - search_result_metadata_model_json2 = search_result_metadata_model.to_dict() - assert search_result_metadata_model_json2 == search_result_metadata_model_json + provider_specification_components_model_json2 = provider_specification_components_model.to_dict() + assert provider_specification_components_model_json2 == provider_specification_components_model_json -class TestModel_SearchSettings: +class TestModel_ProviderSpecificationComponentsSecuritySchemes: """ - Test Class for SearchSettings + Test Class for ProviderSpecificationComponentsSecuritySchemes """ - def test_search_settings_serialization(self): + def test_provider_specification_components_security_schemes_serialization(self): """ - Test serialization/deserialization for SearchSettings + Test serialization/deserialization for ProviderSpecificationComponentsSecuritySchemes """ # Construct dict forms of any model objects needed in order to build this model. - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' - search_settings_discovery_model = {} # SearchSettingsDiscovery - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + provider_specification_components_security_schemes_basic_model = {} # ProviderSpecificationComponentsSecuritySchemesBasic + provider_specification_components_security_schemes_basic_model['username'] = provider_authentication_type_and_value_model - search_settings_messages_model = {} # SearchSettingsMessages - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' + provider_authentication_o_auth2_password_username_model = {} # ProviderAuthenticationOAuth2PasswordUsername + provider_authentication_o_auth2_password_username_model['type'] = 'value' + provider_authentication_o_auth2_password_username_model['value'] = 'testString' - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' + provider_authentication_o_auth2_flows_model = {} # ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2Password + provider_authentication_o_auth2_flows_model['token_url'] = 'testString' + provider_authentication_o_auth2_flows_model['refresh_url'] = 'testString' + provider_authentication_o_auth2_flows_model['client_auth_type'] = 'Body' + provider_authentication_o_auth2_flows_model['content_type'] = 'testString' + provider_authentication_o_auth2_flows_model['header_prefix'] = 'testString' + provider_authentication_o_auth2_flows_model['username'] = provider_authentication_o_auth2_password_username_model - search_settings_elastic_search_model = {} # SearchSettingsElasticSearch - search_settings_elastic_search_model['url'] = 'testString' - search_settings_elastic_search_model['port'] = 'testString' - search_settings_elastic_search_model['username'] = 'testString' - search_settings_elastic_search_model['password'] = 'testString' - search_settings_elastic_search_model['index'] = 'testString' - search_settings_elastic_search_model['filter'] = ['testString'] - search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} - search_settings_elastic_search_model['managed_index'] = 'testString' - search_settings_elastic_search_model['apikey'] = 'testString' + provider_authentication_o_auth2_model = {} # ProviderAuthenticationOAuth2 + provider_authentication_o_auth2_model['preferred_flow'] = 'password' + provider_authentication_o_auth2_model['flows'] = provider_authentication_o_auth2_flows_model - search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength - search_settings_conversational_search_response_length_model['option'] = 'moderate' + # Construct a json representation of a ProviderSpecificationComponentsSecuritySchemes model + provider_specification_components_security_schemes_model_json = {} + provider_specification_components_security_schemes_model_json['authentication_method'] = 'basic' + provider_specification_components_security_schemes_model_json['basic'] = provider_specification_components_security_schemes_basic_model + provider_specification_components_security_schemes_model_json['oauth2'] = provider_authentication_o_auth2_model - search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence - search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_specification_components_security_schemes_model = ProviderSpecificationComponentsSecuritySchemes.from_dict(provider_specification_components_security_schemes_model_json) + assert provider_specification_components_security_schemes_model != False - search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch - search_settings_conversational_search_model['enabled'] = True - search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model - search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemes by calling from_dict on the json representation + provider_specification_components_security_schemes_model_dict = ProviderSpecificationComponentsSecuritySchemes.from_dict(provider_specification_components_security_schemes_model_json).__dict__ + provider_specification_components_security_schemes_model2 = ProviderSpecificationComponentsSecuritySchemes(**provider_specification_components_security_schemes_model_dict) - search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch - search_settings_server_side_search_model['url'] = 'testString' - search_settings_server_side_search_model['port'] = 'testString' - search_settings_server_side_search_model['username'] = 'testString' - search_settings_server_side_search_model['password'] = 'testString' - search_settings_server_side_search_model['filter'] = 'testString' - search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} - search_settings_server_side_search_model['apikey'] = 'testString' - search_settings_server_side_search_model['no_auth'] = True - search_settings_server_side_search_model['auth_type'] = 'basic' + # Verify the model instances are equivalent + assert provider_specification_components_security_schemes_model == provider_specification_components_security_schemes_model2 - search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch - search_settings_client_side_search_model['filter'] = 'testString' - search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + # Convert model instance back to dict and verify no loss of data + provider_specification_components_security_schemes_model_json2 = provider_specification_components_security_schemes_model.to_dict() + assert provider_specification_components_security_schemes_model_json2 == provider_specification_components_security_schemes_model_json - # Construct a json representation of a SearchSettings model - search_settings_model_json = {} - search_settings_model_json['discovery'] = search_settings_discovery_model - search_settings_model_json['messages'] = search_settings_messages_model - search_settings_model_json['schema_mapping'] = search_settings_schema_mapping_model - search_settings_model_json['elastic_search'] = search_settings_elastic_search_model - search_settings_model_json['conversational_search'] = search_settings_conversational_search_model - search_settings_model_json['server_side_search'] = search_settings_server_side_search_model - search_settings_model_json['client_side_search'] = search_settings_client_side_search_model - # Construct a model instance of SearchSettings by calling from_dict on the json representation - search_settings_model = SearchSettings.from_dict(search_settings_model_json) - assert search_settings_model != False +class TestModel_ProviderSpecificationComponentsSecuritySchemesBasic: + """ + Test Class for ProviderSpecificationComponentsSecuritySchemesBasic + """ - # Construct a model instance of SearchSettings by calling from_dict on the json representation - search_settings_model_dict = SearchSettings.from_dict(search_settings_model_json).__dict__ - search_settings_model2 = SearchSettings(**search_settings_model_dict) + def test_provider_specification_components_security_schemes_basic_serialization(self): + """ + Test serialization/deserialization for ProviderSpecificationComponentsSecuritySchemesBasic + """ + + # Construct dict forms of any model objects needed in order to build this model. + + provider_authentication_type_and_value_model = {} # ProviderAuthenticationTypeAndValue + provider_authentication_type_and_value_model['type'] = 'value' + provider_authentication_type_and_value_model['value'] = 'testString' + + # Construct a json representation of a ProviderSpecificationComponentsSecuritySchemesBasic model + provider_specification_components_security_schemes_basic_model_json = {} + provider_specification_components_security_schemes_basic_model_json['username'] = provider_authentication_type_and_value_model + + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_specification_components_security_schemes_basic_model = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict(provider_specification_components_security_schemes_basic_model_json) + assert provider_specification_components_security_schemes_basic_model != False + + # Construct a model instance of ProviderSpecificationComponentsSecuritySchemesBasic by calling from_dict on the json representation + provider_specification_components_security_schemes_basic_model_dict = ProviderSpecificationComponentsSecuritySchemesBasic.from_dict(provider_specification_components_security_schemes_basic_model_json).__dict__ + provider_specification_components_security_schemes_basic_model2 = ProviderSpecificationComponentsSecuritySchemesBasic(**provider_specification_components_security_schemes_basic_model_dict) # Verify the model instances are equivalent - assert search_settings_model == search_settings_model2 + assert provider_specification_components_security_schemes_basic_model == provider_specification_components_security_schemes_basic_model2 # Convert model instance back to dict and verify no loss of data - search_settings_model_json2 = search_settings_model.to_dict() - assert search_settings_model_json2 == search_settings_model_json + provider_specification_components_security_schemes_basic_model_json2 = provider_specification_components_security_schemes_basic_model.to_dict() + assert provider_specification_components_security_schemes_basic_model_json2 == provider_specification_components_security_schemes_basic_model_json -class TestModel_SearchSettingsClientSideSearch: +class TestModel_ProviderSpecificationServersItem: """ - Test Class for SearchSettingsClientSideSearch + Test Class for ProviderSpecificationServersItem """ - def test_search_settings_client_side_search_serialization(self): + def test_provider_specification_servers_item_serialization(self): """ - Test serialization/deserialization for SearchSettingsClientSideSearch + Test serialization/deserialization for ProviderSpecificationServersItem """ - # Construct a json representation of a SearchSettingsClientSideSearch model - search_settings_client_side_search_model_json = {} - search_settings_client_side_search_model_json['filter'] = 'testString' - search_settings_client_side_search_model_json['metadata'] = {'anyKey': 'anyValue'} + # Construct a json representation of a ProviderSpecificationServersItem model + provider_specification_servers_item_model_json = {} + provider_specification_servers_item_model_json['url'] = 'testString' - # Construct a model instance of SearchSettingsClientSideSearch by calling from_dict on the json representation - search_settings_client_side_search_model = SearchSettingsClientSideSearch.from_dict(search_settings_client_side_search_model_json) - assert search_settings_client_side_search_model != False + # Construct a model instance of ProviderSpecificationServersItem by calling from_dict on the json representation + provider_specification_servers_item_model = ProviderSpecificationServersItem.from_dict(provider_specification_servers_item_model_json) + assert provider_specification_servers_item_model != False - # Construct a model instance of SearchSettingsClientSideSearch by calling from_dict on the json representation - search_settings_client_side_search_model_dict = SearchSettingsClientSideSearch.from_dict(search_settings_client_side_search_model_json).__dict__ - search_settings_client_side_search_model2 = SearchSettingsClientSideSearch(**search_settings_client_side_search_model_dict) + # Construct a model instance of ProviderSpecificationServersItem by calling from_dict on the json representation + provider_specification_servers_item_model_dict = ProviderSpecificationServersItem.from_dict(provider_specification_servers_item_model_json).__dict__ + provider_specification_servers_item_model2 = ProviderSpecificationServersItem(**provider_specification_servers_item_model_dict) # Verify the model instances are equivalent - assert search_settings_client_side_search_model == search_settings_client_side_search_model2 + assert provider_specification_servers_item_model == provider_specification_servers_item_model2 # Convert model instance back to dict and verify no loss of data - search_settings_client_side_search_model_json2 = search_settings_client_side_search_model.to_dict() - assert search_settings_client_side_search_model_json2 == search_settings_client_side_search_model_json + provider_specification_servers_item_model_json2 = provider_specification_servers_item_model.to_dict() + assert provider_specification_servers_item_model_json2 == provider_specification_servers_item_model_json -class TestModel_SearchSettingsConversationalSearch: +class TestModel_Release: """ - Test Class for SearchSettingsConversationalSearch + Test Class for Release """ - def test_search_settings_conversational_search_serialization(self): + def test_release_serialization(self): """ - Test serialization/deserialization for SearchSettingsConversationalSearch + Test serialization/deserialization for Release """ - # Construct dict forms of any model objects needed in order to build this model. - - search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength - search_settings_conversational_search_response_length_model['option'] = 'moderate' + # Construct a json representation of a Release model + release_model_json = {} + release_model_json['description'] = 'testString' - search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence - search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' - - # Construct a json representation of a SearchSettingsConversationalSearch model - search_settings_conversational_search_model_json = {} - search_settings_conversational_search_model_json['enabled'] = True - search_settings_conversational_search_model_json['response_length'] = search_settings_conversational_search_response_length_model - search_settings_conversational_search_model_json['search_confidence'] = search_settings_conversational_search_search_confidence_model - - # Construct a model instance of SearchSettingsConversationalSearch by calling from_dict on the json representation - search_settings_conversational_search_model = SearchSettingsConversationalSearch.from_dict(search_settings_conversational_search_model_json) - assert search_settings_conversational_search_model != False + # Construct a model instance of Release by calling from_dict on the json representation + release_model = Release.from_dict(release_model_json) + assert release_model != False - # Construct a model instance of SearchSettingsConversationalSearch by calling from_dict on the json representation - search_settings_conversational_search_model_dict = SearchSettingsConversationalSearch.from_dict(search_settings_conversational_search_model_json).__dict__ - search_settings_conversational_search_model2 = SearchSettingsConversationalSearch(**search_settings_conversational_search_model_dict) + # Construct a model instance of Release by calling from_dict on the json representation + release_model_dict = Release.from_dict(release_model_json).__dict__ + release_model2 = Release(**release_model_dict) # Verify the model instances are equivalent - assert search_settings_conversational_search_model == search_settings_conversational_search_model2 + assert release_model == release_model2 # Convert model instance back to dict and verify no loss of data - search_settings_conversational_search_model_json2 = search_settings_conversational_search_model.to_dict() - assert search_settings_conversational_search_model_json2 == search_settings_conversational_search_model_json + release_model_json2 = release_model.to_dict() + assert release_model_json2 == release_model_json -class TestModel_SearchSettingsConversationalSearchResponseLength: +class TestModel_ReleaseCollection: """ - Test Class for SearchSettingsConversationalSearchResponseLength + Test Class for ReleaseCollection """ - def test_search_settings_conversational_search_response_length_serialization(self): + def test_release_collection_serialization(self): """ - Test serialization/deserialization for SearchSettingsConversationalSearchResponseLength + Test serialization/deserialization for ReleaseCollection """ - # Construct a json representation of a SearchSettingsConversationalSearchResponseLength model - search_settings_conversational_search_response_length_model_json = {} - search_settings_conversational_search_response_length_model_json['option'] = 'moderate' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of SearchSettingsConversationalSearchResponseLength by calling from_dict on the json representation - search_settings_conversational_search_response_length_model = SearchSettingsConversationalSearchResponseLength.from_dict(search_settings_conversational_search_response_length_model_json) - assert search_settings_conversational_search_response_length_model != False + release_model = {} # Release + release_model['description'] = 'testString' - # Construct a model instance of SearchSettingsConversationalSearchResponseLength by calling from_dict on the json representation - search_settings_conversational_search_response_length_model_dict = SearchSettingsConversationalSearchResponseLength.from_dict(search_settings_conversational_search_response_length_model_json).__dict__ - search_settings_conversational_search_response_length_model2 = SearchSettingsConversationalSearchResponseLength(**search_settings_conversational_search_response_length_model_dict) + pagination_model = {} # Pagination + pagination_model['refresh_url'] = 'testString' + pagination_model['next_url'] = 'testString' + pagination_model['total'] = 38 + pagination_model['matched'] = 38 + pagination_model['refresh_cursor'] = 'testString' + pagination_model['next_cursor'] = 'testString' + + # Construct a json representation of a ReleaseCollection model + release_collection_model_json = {} + release_collection_model_json['releases'] = [release_model] + release_collection_model_json['pagination'] = pagination_model + + # Construct a model instance of ReleaseCollection by calling from_dict on the json representation + release_collection_model = ReleaseCollection.from_dict(release_collection_model_json) + assert release_collection_model != False + + # Construct a model instance of ReleaseCollection by calling from_dict on the json representation + release_collection_model_dict = ReleaseCollection.from_dict(release_collection_model_json).__dict__ + release_collection_model2 = ReleaseCollection(**release_collection_model_dict) # Verify the model instances are equivalent - assert search_settings_conversational_search_response_length_model == search_settings_conversational_search_response_length_model2 + assert release_collection_model == release_collection_model2 # Convert model instance back to dict and verify no loss of data - search_settings_conversational_search_response_length_model_json2 = search_settings_conversational_search_response_length_model.to_dict() - assert search_settings_conversational_search_response_length_model_json2 == search_settings_conversational_search_response_length_model_json + release_collection_model_json2 = release_collection_model.to_dict() + assert release_collection_model_json2 == release_collection_model_json -class TestModel_SearchSettingsConversationalSearchSearchConfidence: +class TestModel_ReleaseContent: """ - Test Class for SearchSettingsConversationalSearchSearchConfidence + Test Class for ReleaseContent """ - def test_search_settings_conversational_search_search_confidence_serialization(self): + def test_release_content_serialization(self): """ - Test serialization/deserialization for SearchSettingsConversationalSearchSearchConfidence + Test serialization/deserialization for ReleaseContent """ - # Construct a json representation of a SearchSettingsConversationalSearchSearchConfidence model - search_settings_conversational_search_search_confidence_model_json = {} - search_settings_conversational_search_search_confidence_model_json['threshold'] = 'less_often' + # Construct a json representation of a ReleaseContent model + release_content_model_json = {} - # Construct a model instance of SearchSettingsConversationalSearchSearchConfidence by calling from_dict on the json representation - search_settings_conversational_search_search_confidence_model = SearchSettingsConversationalSearchSearchConfidence.from_dict(search_settings_conversational_search_search_confidence_model_json) - assert search_settings_conversational_search_search_confidence_model != False + # Construct a model instance of ReleaseContent by calling from_dict on the json representation + release_content_model = ReleaseContent.from_dict(release_content_model_json) + assert release_content_model != False - # Construct a model instance of SearchSettingsConversationalSearchSearchConfidence by calling from_dict on the json representation - search_settings_conversational_search_search_confidence_model_dict = SearchSettingsConversationalSearchSearchConfidence.from_dict(search_settings_conversational_search_search_confidence_model_json).__dict__ - search_settings_conversational_search_search_confidence_model2 = SearchSettingsConversationalSearchSearchConfidence(**search_settings_conversational_search_search_confidence_model_dict) + # Construct a model instance of ReleaseContent by calling from_dict on the json representation + release_content_model_dict = ReleaseContent.from_dict(release_content_model_json).__dict__ + release_content_model2 = ReleaseContent(**release_content_model_dict) # Verify the model instances are equivalent - assert search_settings_conversational_search_search_confidence_model == search_settings_conversational_search_search_confidence_model2 + assert release_content_model == release_content_model2 # Convert model instance back to dict and verify no loss of data - search_settings_conversational_search_search_confidence_model_json2 = search_settings_conversational_search_search_confidence_model.to_dict() - assert search_settings_conversational_search_search_confidence_model_json2 == search_settings_conversational_search_search_confidence_model_json + release_content_model_json2 = release_content_model.to_dict() + assert release_content_model_json2 == release_content_model_json -class TestModel_SearchSettingsDiscovery: +class TestModel_ReleaseSkill: """ - Test Class for SearchSettingsDiscovery + Test Class for ReleaseSkill """ - def test_search_settings_discovery_serialization(self): + def test_release_skill_serialization(self): """ - Test serialization/deserialization for SearchSettingsDiscovery + Test serialization/deserialization for ReleaseSkill """ - # Construct dict forms of any model objects needed in order to build this model. - - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' - - # Construct a json representation of a SearchSettingsDiscovery model - search_settings_discovery_model_json = {} - search_settings_discovery_model_json['instance_id'] = 'testString' - search_settings_discovery_model_json['project_id'] = 'testString' - search_settings_discovery_model_json['url'] = 'testString' - search_settings_discovery_model_json['max_primary_results'] = 10000 - search_settings_discovery_model_json['max_total_results'] = 10000 - search_settings_discovery_model_json['confidence_threshold'] = 0.0 - search_settings_discovery_model_json['highlight'] = True - search_settings_discovery_model_json['find_answers'] = True - search_settings_discovery_model_json['authentication'] = search_settings_discovery_authentication_model + # Construct a json representation of a ReleaseSkill model + release_skill_model_json = {} + release_skill_model_json['skill_id'] = 'testString' + release_skill_model_json['type'] = 'dialog' + release_skill_model_json['snapshot'] = 'testString' - # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation - search_settings_discovery_model = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json) - assert search_settings_discovery_model != False + # Construct a model instance of ReleaseSkill by calling from_dict on the json representation + release_skill_model = ReleaseSkill.from_dict(release_skill_model_json) + assert release_skill_model != False - # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation - search_settings_discovery_model_dict = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json).__dict__ - search_settings_discovery_model2 = SearchSettingsDiscovery(**search_settings_discovery_model_dict) + # Construct a model instance of ReleaseSkill by calling from_dict on the json representation + release_skill_model_dict = ReleaseSkill.from_dict(release_skill_model_json).__dict__ + release_skill_model2 = ReleaseSkill(**release_skill_model_dict) # Verify the model instances are equivalent - assert search_settings_discovery_model == search_settings_discovery_model2 + assert release_skill_model == release_skill_model2 # Convert model instance back to dict and verify no loss of data - search_settings_discovery_model_json2 = search_settings_discovery_model.to_dict() - assert search_settings_discovery_model_json2 == search_settings_discovery_model_json + release_skill_model_json2 = release_skill_model.to_dict() + assert release_skill_model_json2 == release_skill_model_json -class TestModel_SearchSettingsDiscoveryAuthentication: +class TestModel_RequestAnalytics: """ - Test Class for SearchSettingsDiscoveryAuthentication + Test Class for RequestAnalytics """ - def test_search_settings_discovery_authentication_serialization(self): + def test_request_analytics_serialization(self): """ - Test serialization/deserialization for SearchSettingsDiscoveryAuthentication + Test serialization/deserialization for RequestAnalytics """ - # Construct a json representation of a SearchSettingsDiscoveryAuthentication model - search_settings_discovery_authentication_model_json = {} - search_settings_discovery_authentication_model_json['basic'] = 'testString' - search_settings_discovery_authentication_model_json['bearer'] = 'testString' + # Construct a json representation of a RequestAnalytics model + request_analytics_model_json = {} + request_analytics_model_json['browser'] = 'testString' + request_analytics_model_json['device'] = 'testString' + request_analytics_model_json['pageUrl'] = 'testString' - # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation - search_settings_discovery_authentication_model = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json) - assert search_settings_discovery_authentication_model != False + # Construct a model instance of RequestAnalytics by calling from_dict on the json representation + request_analytics_model = RequestAnalytics.from_dict(request_analytics_model_json) + assert request_analytics_model != False - # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation - search_settings_discovery_authentication_model_dict = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json).__dict__ - search_settings_discovery_authentication_model2 = SearchSettingsDiscoveryAuthentication(**search_settings_discovery_authentication_model_dict) + # Construct a model instance of RequestAnalytics by calling from_dict on the json representation + request_analytics_model_dict = RequestAnalytics.from_dict(request_analytics_model_json).__dict__ + request_analytics_model2 = RequestAnalytics(**request_analytics_model_dict) # Verify the model instances are equivalent - assert search_settings_discovery_authentication_model == search_settings_discovery_authentication_model2 + assert request_analytics_model == request_analytics_model2 # Convert model instance back to dict and verify no loss of data - search_settings_discovery_authentication_model_json2 = search_settings_discovery_authentication_model.to_dict() - assert search_settings_discovery_authentication_model_json2 == search_settings_discovery_authentication_model_json + request_analytics_model_json2 = request_analytics_model.to_dict() + assert request_analytics_model_json2 == request_analytics_model_json -class TestModel_SearchSettingsElasticSearch: +class TestModel_ResponseGenericChannel: """ - Test Class for SearchSettingsElasticSearch + Test Class for ResponseGenericChannel """ - def test_search_settings_elastic_search_serialization(self): + def test_response_generic_channel_serialization(self): """ - Test serialization/deserialization for SearchSettingsElasticSearch + Test serialization/deserialization for ResponseGenericChannel """ - # Construct a json representation of a SearchSettingsElasticSearch model - search_settings_elastic_search_model_json = {} - search_settings_elastic_search_model_json['url'] = 'testString' - search_settings_elastic_search_model_json['port'] = 'testString' - search_settings_elastic_search_model_json['username'] = 'testString' - search_settings_elastic_search_model_json['password'] = 'testString' - search_settings_elastic_search_model_json['index'] = 'testString' - search_settings_elastic_search_model_json['filter'] = ['testString'] - search_settings_elastic_search_model_json['query_body'] = {'anyKey': 'anyValue'} - search_settings_elastic_search_model_json['managed_index'] = 'testString' - search_settings_elastic_search_model_json['apikey'] = 'testString' + # Construct a json representation of a ResponseGenericChannel model + response_generic_channel_model_json = {} + response_generic_channel_model_json['channel'] = 'testString' - # Construct a model instance of SearchSettingsElasticSearch by calling from_dict on the json representation - search_settings_elastic_search_model = SearchSettingsElasticSearch.from_dict(search_settings_elastic_search_model_json) - assert search_settings_elastic_search_model != False + # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation + response_generic_channel_model = ResponseGenericChannel.from_dict(response_generic_channel_model_json) + assert response_generic_channel_model != False - # Construct a model instance of SearchSettingsElasticSearch by calling from_dict on the json representation - search_settings_elastic_search_model_dict = SearchSettingsElasticSearch.from_dict(search_settings_elastic_search_model_json).__dict__ - search_settings_elastic_search_model2 = SearchSettingsElasticSearch(**search_settings_elastic_search_model_dict) + # Construct a model instance of ResponseGenericChannel by calling from_dict on the json representation + response_generic_channel_model_dict = ResponseGenericChannel.from_dict(response_generic_channel_model_json).__dict__ + response_generic_channel_model2 = ResponseGenericChannel(**response_generic_channel_model_dict) # Verify the model instances are equivalent - assert search_settings_elastic_search_model == search_settings_elastic_search_model2 + assert response_generic_channel_model == response_generic_channel_model2 # Convert model instance back to dict and verify no loss of data - search_settings_elastic_search_model_json2 = search_settings_elastic_search_model.to_dict() - assert search_settings_elastic_search_model_json2 == search_settings_elastic_search_model_json + response_generic_channel_model_json2 = response_generic_channel_model.to_dict() + assert response_generic_channel_model_json2 == response_generic_channel_model_json -class TestModel_SearchSettingsMessages: +class TestModel_ResponseGenericCitation: """ - Test Class for SearchSettingsMessages + Test Class for ResponseGenericCitation """ - def test_search_settings_messages_serialization(self): + def test_response_generic_citation_serialization(self): """ - Test serialization/deserialization for SearchSettingsMessages + Test serialization/deserialization for ResponseGenericCitation """ - # Construct a json representation of a SearchSettingsMessages model - search_settings_messages_model_json = {} - search_settings_messages_model_json['success'] = 'testString' - search_settings_messages_model_json['error'] = 'testString' - search_settings_messages_model_json['no_result'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation - search_settings_messages_model = SearchSettingsMessages.from_dict(search_settings_messages_model_json) - assert search_settings_messages_model != False + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 - # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation - search_settings_messages_model_dict = SearchSettingsMessages.from_dict(search_settings_messages_model_json).__dict__ - search_settings_messages_model2 = SearchSettingsMessages(**search_settings_messages_model_dict) + # Construct a json representation of a ResponseGenericCitation model + response_generic_citation_model_json = {} + response_generic_citation_model_json['title'] = 'testString' + response_generic_citation_model_json['text'] = 'testString' + response_generic_citation_model_json['body'] = 'testString' + response_generic_citation_model_json['search_result_index'] = 38 + response_generic_citation_model_json['ranges'] = [response_generic_citation_ranges_item_model] + + # Construct a model instance of ResponseGenericCitation by calling from_dict on the json representation + response_generic_citation_model = ResponseGenericCitation.from_dict(response_generic_citation_model_json) + assert response_generic_citation_model != False + + # Construct a model instance of ResponseGenericCitation by calling from_dict on the json representation + response_generic_citation_model_dict = ResponseGenericCitation.from_dict(response_generic_citation_model_json).__dict__ + response_generic_citation_model2 = ResponseGenericCitation(**response_generic_citation_model_dict) # Verify the model instances are equivalent - assert search_settings_messages_model == search_settings_messages_model2 + assert response_generic_citation_model == response_generic_citation_model2 # Convert model instance back to dict and verify no loss of data - search_settings_messages_model_json2 = search_settings_messages_model.to_dict() - assert search_settings_messages_model_json2 == search_settings_messages_model_json + response_generic_citation_model_json2 = response_generic_citation_model.to_dict() + assert response_generic_citation_model_json2 == response_generic_citation_model_json -class TestModel_SearchSettingsSchemaMapping: +class TestModel_ResponseGenericCitationRangesItem: """ - Test Class for SearchSettingsSchemaMapping + Test Class for ResponseGenericCitationRangesItem """ - def test_search_settings_schema_mapping_serialization(self): + def test_response_generic_citation_ranges_item_serialization(self): """ - Test serialization/deserialization for SearchSettingsSchemaMapping + Test serialization/deserialization for ResponseGenericCitationRangesItem """ - # Construct a json representation of a SearchSettingsSchemaMapping model - search_settings_schema_mapping_model_json = {} - search_settings_schema_mapping_model_json['url'] = 'testString' - search_settings_schema_mapping_model_json['body'] = 'testString' - search_settings_schema_mapping_model_json['title'] = 'testString' + # Construct a json representation of a ResponseGenericCitationRangesItem model + response_generic_citation_ranges_item_model_json = {} + response_generic_citation_ranges_item_model_json['start'] = 38 + response_generic_citation_ranges_item_model_json['end'] = 38 - # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation - search_settings_schema_mapping_model = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json) - assert search_settings_schema_mapping_model != False + # Construct a model instance of ResponseGenericCitationRangesItem by calling from_dict on the json representation + response_generic_citation_ranges_item_model = ResponseGenericCitationRangesItem.from_dict(response_generic_citation_ranges_item_model_json) + assert response_generic_citation_ranges_item_model != False - # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation - search_settings_schema_mapping_model_dict = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json).__dict__ - search_settings_schema_mapping_model2 = SearchSettingsSchemaMapping(**search_settings_schema_mapping_model_dict) + # Construct a model instance of ResponseGenericCitationRangesItem by calling from_dict on the json representation + response_generic_citation_ranges_item_model_dict = ResponseGenericCitationRangesItem.from_dict(response_generic_citation_ranges_item_model_json).__dict__ + response_generic_citation_ranges_item_model2 = ResponseGenericCitationRangesItem(**response_generic_citation_ranges_item_model_dict) # Verify the model instances are equivalent - assert search_settings_schema_mapping_model == search_settings_schema_mapping_model2 + assert response_generic_citation_ranges_item_model == response_generic_citation_ranges_item_model2 # Convert model instance back to dict and verify no loss of data - search_settings_schema_mapping_model_json2 = search_settings_schema_mapping_model.to_dict() - assert search_settings_schema_mapping_model_json2 == search_settings_schema_mapping_model_json + response_generic_citation_ranges_item_model_json2 = response_generic_citation_ranges_item_model.to_dict() + assert response_generic_citation_ranges_item_model_json2 == response_generic_citation_ranges_item_model_json -class TestModel_SearchSettingsServerSideSearch: +class TestModel_ResponseGenericConfidenceScores: """ - Test Class for SearchSettingsServerSideSearch + Test Class for ResponseGenericConfidenceScores """ - def test_search_settings_server_side_search_serialization(self): + def test_response_generic_confidence_scores_serialization(self): """ - Test serialization/deserialization for SearchSettingsServerSideSearch + Test serialization/deserialization for ResponseGenericConfidenceScores """ - # Construct a json representation of a SearchSettingsServerSideSearch model - search_settings_server_side_search_model_json = {} - search_settings_server_side_search_model_json['url'] = 'testString' - search_settings_server_side_search_model_json['port'] = 'testString' - search_settings_server_side_search_model_json['username'] = 'testString' - search_settings_server_side_search_model_json['password'] = 'testString' - search_settings_server_side_search_model_json['filter'] = 'testString' - search_settings_server_side_search_model_json['metadata'] = {'anyKey': 'anyValue'} - search_settings_server_side_search_model_json['apikey'] = 'testString' - search_settings_server_side_search_model_json['no_auth'] = True - search_settings_server_side_search_model_json['auth_type'] = 'basic' + # Construct a json representation of a ResponseGenericConfidenceScores model + response_generic_confidence_scores_model_json = {} + response_generic_confidence_scores_model_json['threshold'] = 72.5 + response_generic_confidence_scores_model_json['pre_gen'] = 72.5 + response_generic_confidence_scores_model_json['post_gen'] = 72.5 + response_generic_confidence_scores_model_json['extractiveness'] = 72.5 - # Construct a model instance of SearchSettingsServerSideSearch by calling from_dict on the json representation - search_settings_server_side_search_model = SearchSettingsServerSideSearch.from_dict(search_settings_server_side_search_model_json) - assert search_settings_server_side_search_model != False + # Construct a model instance of ResponseGenericConfidenceScores by calling from_dict on the json representation + response_generic_confidence_scores_model = ResponseGenericConfidenceScores.from_dict(response_generic_confidence_scores_model_json) + assert response_generic_confidence_scores_model != False - # Construct a model instance of SearchSettingsServerSideSearch by calling from_dict on the json representation - search_settings_server_side_search_model_dict = SearchSettingsServerSideSearch.from_dict(search_settings_server_side_search_model_json).__dict__ - search_settings_server_side_search_model2 = SearchSettingsServerSideSearch(**search_settings_server_side_search_model_dict) + # Construct a model instance of ResponseGenericConfidenceScores by calling from_dict on the json representation + response_generic_confidence_scores_model_dict = ResponseGenericConfidenceScores.from_dict(response_generic_confidence_scores_model_json).__dict__ + response_generic_confidence_scores_model2 = ResponseGenericConfidenceScores(**response_generic_confidence_scores_model_dict) # Verify the model instances are equivalent - assert search_settings_server_side_search_model == search_settings_server_side_search_model2 + assert response_generic_confidence_scores_model == response_generic_confidence_scores_model2 # Convert model instance back to dict and verify no loss of data - search_settings_server_side_search_model_json2 = search_settings_server_side_search_model.to_dict() - assert search_settings_server_side_search_model_json2 == search_settings_server_side_search_model_json + response_generic_confidence_scores_model_json2 = response_generic_confidence_scores_model.to_dict() + assert response_generic_confidence_scores_model_json2 == response_generic_confidence_scores_model_json -class TestModel_SearchSkillWarning: +class TestModel_RuntimeEntity: """ - Test Class for SearchSkillWarning + Test Class for RuntimeEntity """ - def test_search_skill_warning_serialization(self): + def test_runtime_entity_serialization(self): """ - Test serialization/deserialization for SearchSkillWarning + Test serialization/deserialization for RuntimeEntity """ - # Construct a json representation of a SearchSkillWarning model - search_skill_warning_model_json = {} - search_skill_warning_model_json['code'] = 'testString' - search_skill_warning_model_json['path'] = 'testString' - search_skill_warning_model_json['message'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation - search_skill_warning_model = SearchSkillWarning.from_dict(search_skill_warning_model_json) - assert search_skill_warning_model != False + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] - # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation - search_skill_warning_model_dict = SearchSkillWarning.from_dict(search_skill_warning_model_json).__dict__ - search_skill_warning_model2 = SearchSkillWarning(**search_skill_warning_model_dict) + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + # Construct a json representation of a RuntimeEntity model + runtime_entity_model_json = {} + runtime_entity_model_json['entity'] = 'testString' + runtime_entity_model_json['location'] = [38] + runtime_entity_model_json['value'] = 'testString' + runtime_entity_model_json['confidence'] = 72.5 + runtime_entity_model_json['groups'] = [capture_group_model] + runtime_entity_model_json['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model_json['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model_json['role'] = runtime_entity_role_model + runtime_entity_model_json['skill'] = 'testString' + + # Construct a model instance of RuntimeEntity by calling from_dict on the json representation + runtime_entity_model = RuntimeEntity.from_dict(runtime_entity_model_json) + assert runtime_entity_model != False + + # Construct a model instance of RuntimeEntity by calling from_dict on the json representation + runtime_entity_model_dict = RuntimeEntity.from_dict(runtime_entity_model_json).__dict__ + runtime_entity_model2 = RuntimeEntity(**runtime_entity_model_dict) # Verify the model instances are equivalent - assert search_skill_warning_model == search_skill_warning_model2 + assert runtime_entity_model == runtime_entity_model2 # Convert model instance back to dict and verify no loss of data - search_skill_warning_model_json2 = search_skill_warning_model.to_dict() - assert search_skill_warning_model_json2 == search_skill_warning_model_json + runtime_entity_model_json2 = runtime_entity_model.to_dict() + assert runtime_entity_model_json2 == runtime_entity_model_json -class TestModel_SessionResponse: +class TestModel_RuntimeEntityAlternative: """ - Test Class for SessionResponse + Test Class for RuntimeEntityAlternative """ - def test_session_response_serialization(self): + def test_runtime_entity_alternative_serialization(self): """ - Test serialization/deserialization for SessionResponse + Test serialization/deserialization for RuntimeEntityAlternative """ - # Construct a json representation of a SessionResponse model - session_response_model_json = {} - session_response_model_json['session_id'] = 'testString' + # Construct a json representation of a RuntimeEntityAlternative model + runtime_entity_alternative_model_json = {} + runtime_entity_alternative_model_json['value'] = 'testString' + runtime_entity_alternative_model_json['confidence'] = 72.5 - # Construct a model instance of SessionResponse by calling from_dict on the json representation - session_response_model = SessionResponse.from_dict(session_response_model_json) - assert session_response_model != False + # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation + runtime_entity_alternative_model = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json) + assert runtime_entity_alternative_model != False - # Construct a model instance of SessionResponse by calling from_dict on the json representation - session_response_model_dict = SessionResponse.from_dict(session_response_model_json).__dict__ - session_response_model2 = SessionResponse(**session_response_model_dict) + # Construct a model instance of RuntimeEntityAlternative by calling from_dict on the json representation + runtime_entity_alternative_model_dict = RuntimeEntityAlternative.from_dict(runtime_entity_alternative_model_json).__dict__ + runtime_entity_alternative_model2 = RuntimeEntityAlternative(**runtime_entity_alternative_model_dict) # Verify the model instances are equivalent - assert session_response_model == session_response_model2 + assert runtime_entity_alternative_model == runtime_entity_alternative_model2 # Convert model instance back to dict and verify no loss of data - session_response_model_json2 = session_response_model.to_dict() - assert session_response_model_json2 == session_response_model_json + runtime_entity_alternative_model_json2 = runtime_entity_alternative_model.to_dict() + assert runtime_entity_alternative_model_json2 == runtime_entity_alternative_model_json -class TestModel_Skill: +class TestModel_RuntimeEntityInterpretation: """ - Test Class for Skill + Test Class for RuntimeEntityInterpretation """ - def test_skill_serialization(self): + def test_runtime_entity_interpretation_serialization(self): """ - Test serialization/deserialization for Skill + Test serialization/deserialization for RuntimeEntityInterpretation """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a RuntimeEntityInterpretation model + runtime_entity_interpretation_model_json = {} + runtime_entity_interpretation_model_json['calendar_type'] = 'testString' + runtime_entity_interpretation_model_json['datetime_link'] = 'testString' + runtime_entity_interpretation_model_json['festival'] = 'testString' + runtime_entity_interpretation_model_json['granularity'] = 'day' + runtime_entity_interpretation_model_json['range_link'] = 'testString' + runtime_entity_interpretation_model_json['range_modifier'] = 'testString' + runtime_entity_interpretation_model_json['relative_day'] = 72.5 + runtime_entity_interpretation_model_json['relative_month'] = 72.5 + runtime_entity_interpretation_model_json['relative_week'] = 72.5 + runtime_entity_interpretation_model_json['relative_weekend'] = 72.5 + runtime_entity_interpretation_model_json['relative_year'] = 72.5 + runtime_entity_interpretation_model_json['specific_day'] = 72.5 + runtime_entity_interpretation_model_json['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model_json['specific_month'] = 72.5 + runtime_entity_interpretation_model_json['specific_quarter'] = 72.5 + runtime_entity_interpretation_model_json['specific_year'] = 72.5 + runtime_entity_interpretation_model_json['numeric_value'] = 72.5 + runtime_entity_interpretation_model_json['subtype'] = 'testString' + runtime_entity_interpretation_model_json['part_of_day'] = 'testString' + runtime_entity_interpretation_model_json['relative_hour'] = 72.5 + runtime_entity_interpretation_model_json['relative_minute'] = 72.5 + runtime_entity_interpretation_model_json['relative_second'] = 72.5 + runtime_entity_interpretation_model_json['specific_hour'] = 72.5 + runtime_entity_interpretation_model_json['specific_minute'] = 72.5 + runtime_entity_interpretation_model_json['specific_second'] = 72.5 + runtime_entity_interpretation_model_json['timezone'] = 'testString' - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' + # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation + runtime_entity_interpretation_model = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json) + assert runtime_entity_interpretation_model != False - search_settings_discovery_model = {} # SearchSettingsDiscovery - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + # Construct a model instance of RuntimeEntityInterpretation by calling from_dict on the json representation + runtime_entity_interpretation_model_dict = RuntimeEntityInterpretation.from_dict(runtime_entity_interpretation_model_json).__dict__ + runtime_entity_interpretation_model2 = RuntimeEntityInterpretation(**runtime_entity_interpretation_model_dict) - search_settings_messages_model = {} # SearchSettingsMessages - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' + # Verify the model instances are equivalent + assert runtime_entity_interpretation_model == runtime_entity_interpretation_model2 - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' + # Convert model instance back to dict and verify no loss of data + runtime_entity_interpretation_model_json2 = runtime_entity_interpretation_model.to_dict() + assert runtime_entity_interpretation_model_json2 == runtime_entity_interpretation_model_json - search_settings_elastic_search_model = {} # SearchSettingsElasticSearch - search_settings_elastic_search_model['url'] = 'testString' - search_settings_elastic_search_model['port'] = 'testString' - search_settings_elastic_search_model['username'] = 'testString' - search_settings_elastic_search_model['password'] = 'testString' - search_settings_elastic_search_model['index'] = 'testString' - search_settings_elastic_search_model['filter'] = ['testString'] - search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} - search_settings_elastic_search_model['managed_index'] = 'testString' - search_settings_elastic_search_model['apikey'] = 'testString' - search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength - search_settings_conversational_search_response_length_model['option'] = 'moderate' +class TestModel_RuntimeEntityRole: + """ + Test Class for RuntimeEntityRole + """ - search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence - search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + def test_runtime_entity_role_serialization(self): + """ + Test serialization/deserialization for RuntimeEntityRole + """ - search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch - search_settings_conversational_search_model['enabled'] = True - search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model - search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + # Construct a json representation of a RuntimeEntityRole model + runtime_entity_role_model_json = {} + runtime_entity_role_model_json['type'] = 'date_from' - search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch - search_settings_server_side_search_model['url'] = 'testString' - search_settings_server_side_search_model['port'] = 'testString' - search_settings_server_side_search_model['username'] = 'testString' - search_settings_server_side_search_model['password'] = 'testString' - search_settings_server_side_search_model['filter'] = 'testString' - search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} - search_settings_server_side_search_model['apikey'] = 'testString' - search_settings_server_side_search_model['no_auth'] = True - search_settings_server_side_search_model['auth_type'] = 'basic' - - search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch - search_settings_client_side_search_model['filter'] = 'testString' - search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} - - search_settings_model = {} # SearchSettings - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - search_settings_model['elastic_search'] = search_settings_elastic_search_model - search_settings_model['conversational_search'] = search_settings_conversational_search_model - search_settings_model['server_side_search'] = search_settings_server_side_search_model - search_settings_model['client_side_search'] = search_settings_client_side_search_model - - # Construct a json representation of a Skill model - skill_model_json = {} - skill_model_json['name'] = 'testString' - skill_model_json['description'] = 'testString' - skill_model_json['workspace'] = {'anyKey': 'anyValue'} - skill_model_json['dialog_settings'] = {'anyKey': 'anyValue'} - skill_model_json['search_settings'] = search_settings_model - skill_model_json['language'] = 'testString' - skill_model_json['type'] = 'action' - - # Construct a model instance of Skill by calling from_dict on the json representation - skill_model = Skill.from_dict(skill_model_json) - assert skill_model != False + # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation + runtime_entity_role_model = RuntimeEntityRole.from_dict(runtime_entity_role_model_json) + assert runtime_entity_role_model != False - # Construct a model instance of Skill by calling from_dict on the json representation - skill_model_dict = Skill.from_dict(skill_model_json).__dict__ - skill_model2 = Skill(**skill_model_dict) + # Construct a model instance of RuntimeEntityRole by calling from_dict on the json representation + runtime_entity_role_model_dict = RuntimeEntityRole.from_dict(runtime_entity_role_model_json).__dict__ + runtime_entity_role_model2 = RuntimeEntityRole(**runtime_entity_role_model_dict) # Verify the model instances are equivalent - assert skill_model == skill_model2 + assert runtime_entity_role_model == runtime_entity_role_model2 # Convert model instance back to dict and verify no loss of data - skill_model_json2 = skill_model.to_dict() - assert skill_model_json2 == skill_model_json + runtime_entity_role_model_json2 = runtime_entity_role_model.to_dict() + assert runtime_entity_role_model_json2 == runtime_entity_role_model_json -class TestModel_SkillImport: +class TestModel_RuntimeIntent: """ - Test Class for SkillImport + Test Class for RuntimeIntent """ - def test_skill_import_serialization(self): + def test_runtime_intent_serialization(self): """ - Test serialization/deserialization for SkillImport + Test serialization/deserialization for RuntimeIntent """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a RuntimeIntent model + runtime_intent_model_json = {} + runtime_intent_model_json['intent'] = 'testString' + runtime_intent_model_json['confidence'] = 72.5 + runtime_intent_model_json['skill'] = 'testString' - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' + # Construct a model instance of RuntimeIntent by calling from_dict on the json representation + runtime_intent_model = RuntimeIntent.from_dict(runtime_intent_model_json) + assert runtime_intent_model != False - search_settings_discovery_model = {} # SearchSettingsDiscovery - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + # Construct a model instance of RuntimeIntent by calling from_dict on the json representation + runtime_intent_model_dict = RuntimeIntent.from_dict(runtime_intent_model_json).__dict__ + runtime_intent_model2 = RuntimeIntent(**runtime_intent_model_dict) - search_settings_messages_model = {} # SearchSettingsMessages - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' + # Verify the model instances are equivalent + assert runtime_intent_model == runtime_intent_model2 - search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping - search_settings_schema_mapping_model['url'] = 'testString' - search_settings_schema_mapping_model['body'] = 'testString' - search_settings_schema_mapping_model['title'] = 'testString' + # Convert model instance back to dict and verify no loss of data + runtime_intent_model_json2 = runtime_intent_model.to_dict() + assert runtime_intent_model_json2 == runtime_intent_model_json - search_settings_elastic_search_model = {} # SearchSettingsElasticSearch - search_settings_elastic_search_model['url'] = 'testString' - search_settings_elastic_search_model['port'] = 'testString' - search_settings_elastic_search_model['username'] = 'testString' - search_settings_elastic_search_model['password'] = 'testString' - search_settings_elastic_search_model['index'] = 'testString' - search_settings_elastic_search_model['filter'] = ['testString'] - search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} - search_settings_elastic_search_model['managed_index'] = 'testString' - search_settings_elastic_search_model['apikey'] = 'testString' - search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength - search_settings_conversational_search_response_length_model['option'] = 'moderate' +class TestModel_SearchResult: + """ + Test Class for SearchResult + """ - search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence - search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + def test_search_result_serialization(self): + """ + Test serialization/deserialization for SearchResult + """ - search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch - search_settings_conversational_search_model['enabled'] = True - search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model - search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + # Construct dict forms of any model objects needed in order to build this model. - search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch - search_settings_server_side_search_model['url'] = 'testString' - search_settings_server_side_search_model['port'] = 'testString' - search_settings_server_side_search_model['username'] = 'testString' - search_settings_server_side_search_model['password'] = 'testString' - search_settings_server_side_search_model['filter'] = 'testString' - search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} - search_settings_server_side_search_model['apikey'] = 'testString' - search_settings_server_side_search_model['no_auth'] = True - search_settings_server_side_search_model['auth_type'] = 'basic' + search_result_metadata_model = {} # SearchResultMetadata + search_result_metadata_model['confidence'] = 72.5 + search_result_metadata_model['score'] = 72.5 - search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch - search_settings_client_side_search_model['filter'] = 'testString' - search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_result_highlight_model = {} # SearchResultHighlight + search_result_highlight_model['body'] = ['testString'] + search_result_highlight_model['title'] = ['testString'] + search_result_highlight_model['url'] = ['testString'] + search_result_highlight_model['foo'] = ['testString'] - search_settings_model = {} # SearchSettings - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - search_settings_model['elastic_search'] = search_settings_elastic_search_model - search_settings_model['conversational_search'] = search_settings_conversational_search_model - search_settings_model['server_side_search'] = search_settings_server_side_search_model - search_settings_model['client_side_search'] = search_settings_client_side_search_model + search_result_answer_model = {} # SearchResultAnswer + search_result_answer_model['text'] = 'testString' + search_result_answer_model['confidence'] = 0 - # Construct a json representation of a SkillImport model - skill_import_model_json = {} - skill_import_model_json['name'] = 'testString' - skill_import_model_json['description'] = 'testString' - skill_import_model_json['workspace'] = {'anyKey': 'anyValue'} - skill_import_model_json['dialog_settings'] = {'anyKey': 'anyValue'} - skill_import_model_json['search_settings'] = search_settings_model - skill_import_model_json['language'] = 'testString' - skill_import_model_json['type'] = 'action' + # Construct a json representation of a SearchResult model + search_result_model_json = {} + search_result_model_json['id'] = 'testString' + search_result_model_json['result_metadata'] = search_result_metadata_model + search_result_model_json['body'] = 'testString' + search_result_model_json['title'] = 'testString' + search_result_model_json['url'] = 'testString' + search_result_model_json['highlight'] = search_result_highlight_model + search_result_model_json['answers'] = [search_result_answer_model] - # Construct a model instance of SkillImport by calling from_dict on the json representation - skill_import_model = SkillImport.from_dict(skill_import_model_json) - assert skill_import_model != False + # Construct a model instance of SearchResult by calling from_dict on the json representation + search_result_model = SearchResult.from_dict(search_result_model_json) + assert search_result_model != False - # Construct a model instance of SkillImport by calling from_dict on the json representation - skill_import_model_dict = SkillImport.from_dict(skill_import_model_json).__dict__ - skill_import_model2 = SkillImport(**skill_import_model_dict) + # Construct a model instance of SearchResult by calling from_dict on the json representation + search_result_model_dict = SearchResult.from_dict(search_result_model_json).__dict__ + search_result_model2 = SearchResult(**search_result_model_dict) # Verify the model instances are equivalent - assert skill_import_model == skill_import_model2 + assert search_result_model == search_result_model2 # Convert model instance back to dict and verify no loss of data - skill_import_model_json2 = skill_import_model.to_dict() - assert skill_import_model_json2 == skill_import_model_json + search_result_model_json2 = search_result_model.to_dict() + assert search_result_model_json2 == search_result_model_json -class TestModel_SkillsAsyncRequestStatus: +class TestModel_SearchResultAnswer: """ - Test Class for SkillsAsyncRequestStatus + Test Class for SearchResultAnswer """ - def test_skills_async_request_status_serialization(self): + def test_search_result_answer_serialization(self): """ - Test serialization/deserialization for SkillsAsyncRequestStatus + Test serialization/deserialization for SearchResultAnswer """ - # Construct a json representation of a SkillsAsyncRequestStatus model - skills_async_request_status_model_json = {} + # Construct a json representation of a SearchResultAnswer model + search_result_answer_model_json = {} + search_result_answer_model_json['text'] = 'testString' + search_result_answer_model_json['confidence'] = 0 - # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation - skills_async_request_status_model = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json) - assert skills_async_request_status_model != False + # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation + search_result_answer_model = SearchResultAnswer.from_dict(search_result_answer_model_json) + assert search_result_answer_model != False - # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation - skills_async_request_status_model_dict = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json).__dict__ - skills_async_request_status_model2 = SkillsAsyncRequestStatus(**skills_async_request_status_model_dict) + # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation + search_result_answer_model_dict = SearchResultAnswer.from_dict(search_result_answer_model_json).__dict__ + search_result_answer_model2 = SearchResultAnswer(**search_result_answer_model_dict) # Verify the model instances are equivalent - assert skills_async_request_status_model == skills_async_request_status_model2 + assert search_result_answer_model == search_result_answer_model2 # Convert model instance back to dict and verify no loss of data - skills_async_request_status_model_json2 = skills_async_request_status_model.to_dict() - assert skills_async_request_status_model_json2 == skills_async_request_status_model_json + search_result_answer_model_json2 = search_result_answer_model.to_dict() + assert search_result_answer_model_json2 == search_result_answer_model_json -class TestModel_SkillsExport: +class TestModel_SearchResultHighlight: """ - Test Class for SkillsExport + Test Class for SearchResultHighlight """ - def test_skills_export_serialization(self): + def test_search_result_highlight_serialization(self): """ - Test serialization/deserialization for SkillsExport + Test serialization/deserialization for SearchResultHighlight """ - # Construct dict forms of any model objects needed in order to build this model. - - search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication - search_settings_discovery_authentication_model['basic'] = 'testString' - search_settings_discovery_authentication_model['bearer'] = 'testString' + # Construct a json representation of a SearchResultHighlight model + search_result_highlight_model_json = {} + search_result_highlight_model_json['body'] = ['testString'] + search_result_highlight_model_json['title'] = ['testString'] + search_result_highlight_model_json['url'] = ['testString'] + search_result_highlight_model_json['foo'] = ['testString'] - search_settings_discovery_model = {} # SearchSettingsDiscovery - search_settings_discovery_model['instance_id'] = 'testString' - search_settings_discovery_model['project_id'] = 'testString' - search_settings_discovery_model['url'] = 'testString' - search_settings_discovery_model['max_primary_results'] = 10000 - search_settings_discovery_model['max_total_results'] = 10000 - search_settings_discovery_model['confidence_threshold'] = 0.0 - search_settings_discovery_model['highlight'] = True - search_settings_discovery_model['find_answers'] = True - search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation + search_result_highlight_model = SearchResultHighlight.from_dict(search_result_highlight_model_json) + assert search_result_highlight_model != False - search_settings_messages_model = {} # SearchSettingsMessages - search_settings_messages_model['success'] = 'testString' - search_settings_messages_model['error'] = 'testString' - search_settings_messages_model['no_result'] = 'testString' + # Construct a model instance of SearchResultHighlight by calling from_dict on the json representation + search_result_highlight_model_dict = SearchResultHighlight.from_dict(search_result_highlight_model_json).__dict__ + search_result_highlight_model2 = SearchResultHighlight(**search_result_highlight_model_dict) + + # Verify the model instances are equivalent + assert search_result_highlight_model == search_result_highlight_model2 + + # Convert model instance back to dict and verify no loss of data + search_result_highlight_model_json2 = search_result_highlight_model.to_dict() + assert search_result_highlight_model_json2 == search_result_highlight_model_json + + # Test get_properties and set_properties methods. + search_result_highlight_model.set_properties({}) + actual_dict = search_result_highlight_model.get_properties() + assert actual_dict == {} + + expected_dict = {'foo': ['testString']} + search_result_highlight_model.set_properties(expected_dict) + actual_dict = search_result_highlight_model.get_properties() + assert actual_dict.keys() == expected_dict.keys() + + +class TestModel_SearchResultMetadata: + """ + Test Class for SearchResultMetadata + """ + + def test_search_result_metadata_serialization(self): + """ + Test serialization/deserialization for SearchResultMetadata + """ + + # Construct a json representation of a SearchResultMetadata model + search_result_metadata_model_json = {} + search_result_metadata_model_json['confidence'] = 72.5 + search_result_metadata_model_json['score'] = 72.5 + + # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation + search_result_metadata_model = SearchResultMetadata.from_dict(search_result_metadata_model_json) + assert search_result_metadata_model != False + + # Construct a model instance of SearchResultMetadata by calling from_dict on the json representation + search_result_metadata_model_dict = SearchResultMetadata.from_dict(search_result_metadata_model_json).__dict__ + search_result_metadata_model2 = SearchResultMetadata(**search_result_metadata_model_dict) + + # Verify the model instances are equivalent + assert search_result_metadata_model == search_result_metadata_model2 + + # Convert model instance back to dict and verify no loss of data + search_result_metadata_model_json2 = search_result_metadata_model.to_dict() + assert search_result_metadata_model_json2 == search_result_metadata_model_json + + +class TestModel_SearchResults: + """ + Test Class for SearchResults + """ + + def test_search_results_serialization(self): + """ + Test serialization/deserialization for SearchResults + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + # Construct a json representation of a SearchResults model + search_results_model_json = {} + search_results_model_json['result_metadata'] = search_results_result_metadata_model + search_results_model_json['id'] = 'testString' + search_results_model_json['title'] = 'testString' + search_results_model_json['body'] = 'testString' + + # Construct a model instance of SearchResults by calling from_dict on the json representation + search_results_model = SearchResults.from_dict(search_results_model_json) + assert search_results_model != False + + # Construct a model instance of SearchResults by calling from_dict on the json representation + search_results_model_dict = SearchResults.from_dict(search_results_model_json).__dict__ + search_results_model2 = SearchResults(**search_results_model_dict) + + # Verify the model instances are equivalent + assert search_results_model == search_results_model2 + + # Convert model instance back to dict and verify no loss of data + search_results_model_json2 = search_results_model.to_dict() + assert search_results_model_json2 == search_results_model_json + + +class TestModel_SearchResultsResultMetadata: + """ + Test Class for SearchResultsResultMetadata + """ + + def test_search_results_result_metadata_serialization(self): + """ + Test serialization/deserialization for SearchResultsResultMetadata + """ + + # Construct a json representation of a SearchResultsResultMetadata model + search_results_result_metadata_model_json = {} + search_results_result_metadata_model_json['document_retrieval_source'] = 'testString' + search_results_result_metadata_model_json['score'] = 38 + + # Construct a model instance of SearchResultsResultMetadata by calling from_dict on the json representation + search_results_result_metadata_model = SearchResultsResultMetadata.from_dict(search_results_result_metadata_model_json) + assert search_results_result_metadata_model != False + + # Construct a model instance of SearchResultsResultMetadata by calling from_dict on the json representation + search_results_result_metadata_model_dict = SearchResultsResultMetadata.from_dict(search_results_result_metadata_model_json).__dict__ + search_results_result_metadata_model2 = SearchResultsResultMetadata(**search_results_result_metadata_model_dict) + + # Verify the model instances are equivalent + assert search_results_result_metadata_model == search_results_result_metadata_model2 + + # Convert model instance back to dict and verify no loss of data + search_results_result_metadata_model_json2 = search_results_result_metadata_model.to_dict() + assert search_results_result_metadata_model_json2 == search_results_result_metadata_model_json + + +class TestModel_SearchSettings: + """ + Test Class for SearchSettings + """ + + def test_search_settings_serialization(self): + """ + Test serialization/deserialization for SearchSettings + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping search_settings_schema_mapping_model['url'] = 'testString' @@ -10937,111 +11161,1959 @@ def test_skills_export_serialization(self): search_settings_client_side_search_model['filter'] = 'testString' search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} - search_settings_model = {} # SearchSettings - search_settings_model['discovery'] = search_settings_discovery_model - search_settings_model['messages'] = search_settings_messages_model - search_settings_model['schema_mapping'] = search_settings_schema_mapping_model - search_settings_model['elastic_search'] = search_settings_elastic_search_model - search_settings_model['conversational_search'] = search_settings_conversational_search_model - search_settings_model['server_side_search'] = search_settings_server_side_search_model - search_settings_model['client_side_search'] = search_settings_client_side_search_model + # Construct a json representation of a SearchSettings model + search_settings_model_json = {} + search_settings_model_json['discovery'] = search_settings_discovery_model + search_settings_model_json['messages'] = search_settings_messages_model + search_settings_model_json['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model_json['elastic_search'] = search_settings_elastic_search_model + search_settings_model_json['conversational_search'] = search_settings_conversational_search_model + search_settings_model_json['server_side_search'] = search_settings_server_side_search_model + search_settings_model_json['client_side_search'] = search_settings_client_side_search_model - skill_model = {} # Skill - skill_model['name'] = 'testString' - skill_model['description'] = 'testString' - skill_model['workspace'] = {'anyKey': 'anyValue'} - skill_model['dialog_settings'] = {'anyKey': 'anyValue'} - skill_model['search_settings'] = search_settings_model - skill_model['language'] = 'testString' - skill_model['type'] = 'action' + # Construct a model instance of SearchSettings by calling from_dict on the json representation + search_settings_model = SearchSettings.from_dict(search_settings_model_json) + assert search_settings_model != False - assistant_state_model = {} # AssistantState - assistant_state_model['action_disabled'] = True - assistant_state_model['dialog_disabled'] = True + # Construct a model instance of SearchSettings by calling from_dict on the json representation + search_settings_model_dict = SearchSettings.from_dict(search_settings_model_json).__dict__ + search_settings_model2 = SearchSettings(**search_settings_model_dict) - # Construct a json representation of a SkillsExport model - skills_export_model_json = {} - skills_export_model_json['assistant_skills'] = [skill_model] - skills_export_model_json['assistant_state'] = assistant_state_model + # Verify the model instances are equivalent + assert search_settings_model == search_settings_model2 - # Construct a model instance of SkillsExport by calling from_dict on the json representation - skills_export_model = SkillsExport.from_dict(skills_export_model_json) - assert skills_export_model != False + # Convert model instance back to dict and verify no loss of data + search_settings_model_json2 = search_settings_model.to_dict() + assert search_settings_model_json2 == search_settings_model_json - # Construct a model instance of SkillsExport by calling from_dict on the json representation - skills_export_model_dict = SkillsExport.from_dict(skills_export_model_json).__dict__ - skills_export_model2 = SkillsExport(**skills_export_model_dict) + +class TestModel_SearchSettingsClientSideSearch: + """ + Test Class for SearchSettingsClientSideSearch + """ + + def test_search_settings_client_side_search_serialization(self): + """ + Test serialization/deserialization for SearchSettingsClientSideSearch + """ + + # Construct a json representation of a SearchSettingsClientSideSearch model + search_settings_client_side_search_model_json = {} + search_settings_client_side_search_model_json['filter'] = 'testString' + search_settings_client_side_search_model_json['metadata'] = {'anyKey': 'anyValue'} + + # Construct a model instance of SearchSettingsClientSideSearch by calling from_dict on the json representation + search_settings_client_side_search_model = SearchSettingsClientSideSearch.from_dict(search_settings_client_side_search_model_json) + assert search_settings_client_side_search_model != False + + # Construct a model instance of SearchSettingsClientSideSearch by calling from_dict on the json representation + search_settings_client_side_search_model_dict = SearchSettingsClientSideSearch.from_dict(search_settings_client_side_search_model_json).__dict__ + search_settings_client_side_search_model2 = SearchSettingsClientSideSearch(**search_settings_client_side_search_model_dict) # Verify the model instances are equivalent - assert skills_export_model == skills_export_model2 + assert search_settings_client_side_search_model == search_settings_client_side_search_model2 # Convert model instance back to dict and verify no loss of data - skills_export_model_json2 = skills_export_model.to_dict() - assert skills_export_model_json2 == skills_export_model_json + search_settings_client_side_search_model_json2 = search_settings_client_side_search_model.to_dict() + assert search_settings_client_side_search_model_json2 == search_settings_client_side_search_model_json -class TestModel_StatefulMessageResponse: +class TestModel_SearchSettingsConversationalSearch: """ - Test Class for StatefulMessageResponse + Test Class for SearchSettingsConversationalSearch """ - def test_stateful_message_response_serialization(self): + def test_search_settings_conversational_search_serialization(self): """ - Test serialization/deserialization for StatefulMessageResponse + Test serialization/deserialization for SearchSettingsConversationalSearch """ # Construct dict forms of any model objects needed in order to build this model. - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + # Construct a json representation of a SearchSettingsConversationalSearch model + search_settings_conversational_search_model_json = {} + search_settings_conversational_search_model_json['enabled'] = True + search_settings_conversational_search_model_json['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model_json['search_confidence'] = search_settings_conversational_search_search_confidence_model - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Construct a model instance of SearchSettingsConversationalSearch by calling from_dict on the json representation + search_settings_conversational_search_model = SearchSettingsConversationalSearch.from_dict(search_settings_conversational_search_model_json) + assert search_settings_conversational_search_model != False - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Construct a model instance of SearchSettingsConversationalSearch by calling from_dict on the json representation + search_settings_conversational_search_model_dict = SearchSettingsConversationalSearch.from_dict(search_settings_conversational_search_model_json).__dict__ + search_settings_conversational_search_model2 = SearchSettingsConversationalSearch(**search_settings_conversational_search_model_dict) - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Verify the model instances are equivalent + assert search_settings_conversational_search_model == search_settings_conversational_search_model2 - runtime_entity_role_model = {} # RuntimeEntityRole + # Convert model instance back to dict and verify no loss of data + search_settings_conversational_search_model_json2 = search_settings_conversational_search_model.to_dict() + assert search_settings_conversational_search_model_json2 == search_settings_conversational_search_model_json + + +class TestModel_SearchSettingsConversationalSearchResponseLength: + """ + Test Class for SearchSettingsConversationalSearchResponseLength + """ + + def test_search_settings_conversational_search_response_length_serialization(self): + """ + Test serialization/deserialization for SearchSettingsConversationalSearchResponseLength + """ + + # Construct a json representation of a SearchSettingsConversationalSearchResponseLength model + search_settings_conversational_search_response_length_model_json = {} + search_settings_conversational_search_response_length_model_json['option'] = 'moderate' + + # Construct a model instance of SearchSettingsConversationalSearchResponseLength by calling from_dict on the json representation + search_settings_conversational_search_response_length_model = SearchSettingsConversationalSearchResponseLength.from_dict(search_settings_conversational_search_response_length_model_json) + assert search_settings_conversational_search_response_length_model != False + + # Construct a model instance of SearchSettingsConversationalSearchResponseLength by calling from_dict on the json representation + search_settings_conversational_search_response_length_model_dict = SearchSettingsConversationalSearchResponseLength.from_dict(search_settings_conversational_search_response_length_model_json).__dict__ + search_settings_conversational_search_response_length_model2 = SearchSettingsConversationalSearchResponseLength(**search_settings_conversational_search_response_length_model_dict) + + # Verify the model instances are equivalent + assert search_settings_conversational_search_response_length_model == search_settings_conversational_search_response_length_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_conversational_search_response_length_model_json2 = search_settings_conversational_search_response_length_model.to_dict() + assert search_settings_conversational_search_response_length_model_json2 == search_settings_conversational_search_response_length_model_json + + +class TestModel_SearchSettingsConversationalSearchSearchConfidence: + """ + Test Class for SearchSettingsConversationalSearchSearchConfidence + """ + + def test_search_settings_conversational_search_search_confidence_serialization(self): + """ + Test serialization/deserialization for SearchSettingsConversationalSearchSearchConfidence + """ + + # Construct a json representation of a SearchSettingsConversationalSearchSearchConfidence model + search_settings_conversational_search_search_confidence_model_json = {} + search_settings_conversational_search_search_confidence_model_json['threshold'] = 'less_often' + + # Construct a model instance of SearchSettingsConversationalSearchSearchConfidence by calling from_dict on the json representation + search_settings_conversational_search_search_confidence_model = SearchSettingsConversationalSearchSearchConfidence.from_dict(search_settings_conversational_search_search_confidence_model_json) + assert search_settings_conversational_search_search_confidence_model != False + + # Construct a model instance of SearchSettingsConversationalSearchSearchConfidence by calling from_dict on the json representation + search_settings_conversational_search_search_confidence_model_dict = SearchSettingsConversationalSearchSearchConfidence.from_dict(search_settings_conversational_search_search_confidence_model_json).__dict__ + search_settings_conversational_search_search_confidence_model2 = SearchSettingsConversationalSearchSearchConfidence(**search_settings_conversational_search_search_confidence_model_dict) + + # Verify the model instances are equivalent + assert search_settings_conversational_search_search_confidence_model == search_settings_conversational_search_search_confidence_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_conversational_search_search_confidence_model_json2 = search_settings_conversational_search_search_confidence_model.to_dict() + assert search_settings_conversational_search_search_confidence_model_json2 == search_settings_conversational_search_search_confidence_model_json + + +class TestModel_SearchSettingsDiscovery: + """ + Test Class for SearchSettingsDiscovery + """ + + def test_search_settings_discovery_serialization(self): + """ + Test serialization/deserialization for SearchSettingsDiscovery + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + # Construct a json representation of a SearchSettingsDiscovery model + search_settings_discovery_model_json = {} + search_settings_discovery_model_json['instance_id'] = 'testString' + search_settings_discovery_model_json['project_id'] = 'testString' + search_settings_discovery_model_json['url'] = 'testString' + search_settings_discovery_model_json['max_primary_results'] = 10000 + search_settings_discovery_model_json['max_total_results'] = 10000 + search_settings_discovery_model_json['confidence_threshold'] = 0.0 + search_settings_discovery_model_json['highlight'] = True + search_settings_discovery_model_json['find_answers'] = True + search_settings_discovery_model_json['authentication'] = search_settings_discovery_authentication_model + + # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation + search_settings_discovery_model = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json) + assert search_settings_discovery_model != False + + # Construct a model instance of SearchSettingsDiscovery by calling from_dict on the json representation + search_settings_discovery_model_dict = SearchSettingsDiscovery.from_dict(search_settings_discovery_model_json).__dict__ + search_settings_discovery_model2 = SearchSettingsDiscovery(**search_settings_discovery_model_dict) + + # Verify the model instances are equivalent + assert search_settings_discovery_model == search_settings_discovery_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_discovery_model_json2 = search_settings_discovery_model.to_dict() + assert search_settings_discovery_model_json2 == search_settings_discovery_model_json + + +class TestModel_SearchSettingsDiscoveryAuthentication: + """ + Test Class for SearchSettingsDiscoveryAuthentication + """ + + def test_search_settings_discovery_authentication_serialization(self): + """ + Test serialization/deserialization for SearchSettingsDiscoveryAuthentication + """ + + # Construct a json representation of a SearchSettingsDiscoveryAuthentication model + search_settings_discovery_authentication_model_json = {} + search_settings_discovery_authentication_model_json['basic'] = 'testString' + search_settings_discovery_authentication_model_json['bearer'] = 'testString' + + # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation + search_settings_discovery_authentication_model = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json) + assert search_settings_discovery_authentication_model != False + + # Construct a model instance of SearchSettingsDiscoveryAuthentication by calling from_dict on the json representation + search_settings_discovery_authentication_model_dict = SearchSettingsDiscoveryAuthentication.from_dict(search_settings_discovery_authentication_model_json).__dict__ + search_settings_discovery_authentication_model2 = SearchSettingsDiscoveryAuthentication(**search_settings_discovery_authentication_model_dict) + + # Verify the model instances are equivalent + assert search_settings_discovery_authentication_model == search_settings_discovery_authentication_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_discovery_authentication_model_json2 = search_settings_discovery_authentication_model.to_dict() + assert search_settings_discovery_authentication_model_json2 == search_settings_discovery_authentication_model_json + + +class TestModel_SearchSettingsElasticSearch: + """ + Test Class for SearchSettingsElasticSearch + """ + + def test_search_settings_elastic_search_serialization(self): + """ + Test serialization/deserialization for SearchSettingsElasticSearch + """ + + # Construct a json representation of a SearchSettingsElasticSearch model + search_settings_elastic_search_model_json = {} + search_settings_elastic_search_model_json['url'] = 'testString' + search_settings_elastic_search_model_json['port'] = 'testString' + search_settings_elastic_search_model_json['username'] = 'testString' + search_settings_elastic_search_model_json['password'] = 'testString' + search_settings_elastic_search_model_json['index'] = 'testString' + search_settings_elastic_search_model_json['filter'] = ['testString'] + search_settings_elastic_search_model_json['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model_json['managed_index'] = 'testString' + search_settings_elastic_search_model_json['apikey'] = 'testString' + + # Construct a model instance of SearchSettingsElasticSearch by calling from_dict on the json representation + search_settings_elastic_search_model = SearchSettingsElasticSearch.from_dict(search_settings_elastic_search_model_json) + assert search_settings_elastic_search_model != False + + # Construct a model instance of SearchSettingsElasticSearch by calling from_dict on the json representation + search_settings_elastic_search_model_dict = SearchSettingsElasticSearch.from_dict(search_settings_elastic_search_model_json).__dict__ + search_settings_elastic_search_model2 = SearchSettingsElasticSearch(**search_settings_elastic_search_model_dict) + + # Verify the model instances are equivalent + assert search_settings_elastic_search_model == search_settings_elastic_search_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_elastic_search_model_json2 = search_settings_elastic_search_model.to_dict() + assert search_settings_elastic_search_model_json2 == search_settings_elastic_search_model_json + + +class TestModel_SearchSettingsMessages: + """ + Test Class for SearchSettingsMessages + """ + + def test_search_settings_messages_serialization(self): + """ + Test serialization/deserialization for SearchSettingsMessages + """ + + # Construct a json representation of a SearchSettingsMessages model + search_settings_messages_model_json = {} + search_settings_messages_model_json['success'] = 'testString' + search_settings_messages_model_json['error'] = 'testString' + search_settings_messages_model_json['no_result'] = 'testString' + + # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation + search_settings_messages_model = SearchSettingsMessages.from_dict(search_settings_messages_model_json) + assert search_settings_messages_model != False + + # Construct a model instance of SearchSettingsMessages by calling from_dict on the json representation + search_settings_messages_model_dict = SearchSettingsMessages.from_dict(search_settings_messages_model_json).__dict__ + search_settings_messages_model2 = SearchSettingsMessages(**search_settings_messages_model_dict) + + # Verify the model instances are equivalent + assert search_settings_messages_model == search_settings_messages_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_messages_model_json2 = search_settings_messages_model.to_dict() + assert search_settings_messages_model_json2 == search_settings_messages_model_json + + +class TestModel_SearchSettingsSchemaMapping: + """ + Test Class for SearchSettingsSchemaMapping + """ + + def test_search_settings_schema_mapping_serialization(self): + """ + Test serialization/deserialization for SearchSettingsSchemaMapping + """ + + # Construct a json representation of a SearchSettingsSchemaMapping model + search_settings_schema_mapping_model_json = {} + search_settings_schema_mapping_model_json['url'] = 'testString' + search_settings_schema_mapping_model_json['body'] = 'testString' + search_settings_schema_mapping_model_json['title'] = 'testString' + + # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation + search_settings_schema_mapping_model = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json) + assert search_settings_schema_mapping_model != False + + # Construct a model instance of SearchSettingsSchemaMapping by calling from_dict on the json representation + search_settings_schema_mapping_model_dict = SearchSettingsSchemaMapping.from_dict(search_settings_schema_mapping_model_json).__dict__ + search_settings_schema_mapping_model2 = SearchSettingsSchemaMapping(**search_settings_schema_mapping_model_dict) + + # Verify the model instances are equivalent + assert search_settings_schema_mapping_model == search_settings_schema_mapping_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_schema_mapping_model_json2 = search_settings_schema_mapping_model.to_dict() + assert search_settings_schema_mapping_model_json2 == search_settings_schema_mapping_model_json + + +class TestModel_SearchSettingsServerSideSearch: + """ + Test Class for SearchSettingsServerSideSearch + """ + + def test_search_settings_server_side_search_serialization(self): + """ + Test serialization/deserialization for SearchSettingsServerSideSearch + """ + + # Construct a json representation of a SearchSettingsServerSideSearch model + search_settings_server_side_search_model_json = {} + search_settings_server_side_search_model_json['url'] = 'testString' + search_settings_server_side_search_model_json['port'] = 'testString' + search_settings_server_side_search_model_json['username'] = 'testString' + search_settings_server_side_search_model_json['password'] = 'testString' + search_settings_server_side_search_model_json['filter'] = 'testString' + search_settings_server_side_search_model_json['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model_json['apikey'] = 'testString' + search_settings_server_side_search_model_json['no_auth'] = True + search_settings_server_side_search_model_json['auth_type'] = 'basic' + + # Construct a model instance of SearchSettingsServerSideSearch by calling from_dict on the json representation + search_settings_server_side_search_model = SearchSettingsServerSideSearch.from_dict(search_settings_server_side_search_model_json) + assert search_settings_server_side_search_model != False + + # Construct a model instance of SearchSettingsServerSideSearch by calling from_dict on the json representation + search_settings_server_side_search_model_dict = SearchSettingsServerSideSearch.from_dict(search_settings_server_side_search_model_json).__dict__ + search_settings_server_side_search_model2 = SearchSettingsServerSideSearch(**search_settings_server_side_search_model_dict) + + # Verify the model instances are equivalent + assert search_settings_server_side_search_model == search_settings_server_side_search_model2 + + # Convert model instance back to dict and verify no loss of data + search_settings_server_side_search_model_json2 = search_settings_server_side_search_model.to_dict() + assert search_settings_server_side_search_model_json2 == search_settings_server_side_search_model_json + + +class TestModel_SearchSkillWarning: + """ + Test Class for SearchSkillWarning + """ + + def test_search_skill_warning_serialization(self): + """ + Test serialization/deserialization for SearchSkillWarning + """ + + # Construct a json representation of a SearchSkillWarning model + search_skill_warning_model_json = {} + search_skill_warning_model_json['code'] = 'testString' + search_skill_warning_model_json['path'] = 'testString' + search_skill_warning_model_json['message'] = 'testString' + + # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation + search_skill_warning_model = SearchSkillWarning.from_dict(search_skill_warning_model_json) + assert search_skill_warning_model != False + + # Construct a model instance of SearchSkillWarning by calling from_dict on the json representation + search_skill_warning_model_dict = SearchSkillWarning.from_dict(search_skill_warning_model_json).__dict__ + search_skill_warning_model2 = SearchSkillWarning(**search_skill_warning_model_dict) + + # Verify the model instances are equivalent + assert search_skill_warning_model == search_skill_warning_model2 + + # Convert model instance back to dict and verify no loss of data + search_skill_warning_model_json2 = search_skill_warning_model.to_dict() + assert search_skill_warning_model_json2 == search_skill_warning_model_json + + +class TestModel_SessionResponse: + """ + Test Class for SessionResponse + """ + + def test_session_response_serialization(self): + """ + Test serialization/deserialization for SessionResponse + """ + + # Construct a json representation of a SessionResponse model + session_response_model_json = {} + session_response_model_json['session_id'] = 'testString' + + # Construct a model instance of SessionResponse by calling from_dict on the json representation + session_response_model = SessionResponse.from_dict(session_response_model_json) + assert session_response_model != False + + # Construct a model instance of SessionResponse by calling from_dict on the json representation + session_response_model_dict = SessionResponse.from_dict(session_response_model_json).__dict__ + session_response_model2 = SessionResponse(**session_response_model_dict) + + # Verify the model instances are equivalent + assert session_response_model == session_response_model2 + + # Convert model instance back to dict and verify no loss of data + session_response_model_json2 = session_response_model.to_dict() + assert session_response_model_json2 == session_response_model_json + + +class TestModel_Skill: + """ + Test Class for Skill + """ + + def test_skill_serialization(self): + """ + Test serialization/deserialization for Skill + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_elastic_search_model = {} # SearchSettingsElasticSearch + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Construct a json representation of a Skill model + skill_model_json = {} + skill_model_json['name'] = 'testString' + skill_model_json['description'] = 'testString' + skill_model_json['workspace'] = {'anyKey': 'anyValue'} + skill_model_json['dialog_settings'] = {'anyKey': 'anyValue'} + skill_model_json['search_settings'] = search_settings_model + skill_model_json['language'] = 'testString' + skill_model_json['type'] = 'action' + + # Construct a model instance of Skill by calling from_dict on the json representation + skill_model = Skill.from_dict(skill_model_json) + assert skill_model != False + + # Construct a model instance of Skill by calling from_dict on the json representation + skill_model_dict = Skill.from_dict(skill_model_json).__dict__ + skill_model2 = Skill(**skill_model_dict) + + # Verify the model instances are equivalent + assert skill_model == skill_model2 + + # Convert model instance back to dict and verify no loss of data + skill_model_json2 = skill_model.to_dict() + assert skill_model_json2 == skill_model_json + + +class TestModel_SkillImport: + """ + Test Class for SkillImport + """ + + def test_skill_import_serialization(self): + """ + Test serialization/deserialization for SkillImport + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_elastic_search_model = {} # SearchSettingsElasticSearch + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + # Construct a json representation of a SkillImport model + skill_import_model_json = {} + skill_import_model_json['name'] = 'testString' + skill_import_model_json['description'] = 'testString' + skill_import_model_json['workspace'] = {'anyKey': 'anyValue'} + skill_import_model_json['dialog_settings'] = {'anyKey': 'anyValue'} + skill_import_model_json['search_settings'] = search_settings_model + skill_import_model_json['language'] = 'testString' + skill_import_model_json['type'] = 'action' + + # Construct a model instance of SkillImport by calling from_dict on the json representation + skill_import_model = SkillImport.from_dict(skill_import_model_json) + assert skill_import_model != False + + # Construct a model instance of SkillImport by calling from_dict on the json representation + skill_import_model_dict = SkillImport.from_dict(skill_import_model_json).__dict__ + skill_import_model2 = SkillImport(**skill_import_model_dict) + + # Verify the model instances are equivalent + assert skill_import_model == skill_import_model2 + + # Convert model instance back to dict and verify no loss of data + skill_import_model_json2 = skill_import_model.to_dict() + assert skill_import_model_json2 == skill_import_model_json + + +class TestModel_SkillsAsyncRequestStatus: + """ + Test Class for SkillsAsyncRequestStatus + """ + + def test_skills_async_request_status_serialization(self): + """ + Test serialization/deserialization for SkillsAsyncRequestStatus + """ + + # Construct a json representation of a SkillsAsyncRequestStatus model + skills_async_request_status_model_json = {} + + # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation + skills_async_request_status_model = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json) + assert skills_async_request_status_model != False + + # Construct a model instance of SkillsAsyncRequestStatus by calling from_dict on the json representation + skills_async_request_status_model_dict = SkillsAsyncRequestStatus.from_dict(skills_async_request_status_model_json).__dict__ + skills_async_request_status_model2 = SkillsAsyncRequestStatus(**skills_async_request_status_model_dict) + + # Verify the model instances are equivalent + assert skills_async_request_status_model == skills_async_request_status_model2 + + # Convert model instance back to dict and verify no loss of data + skills_async_request_status_model_json2 = skills_async_request_status_model.to_dict() + assert skills_async_request_status_model_json2 == skills_async_request_status_model_json + + +class TestModel_SkillsExport: + """ + Test Class for SkillsExport + """ + + def test_skills_export_serialization(self): + """ + Test serialization/deserialization for SkillsExport + """ + + # Construct dict forms of any model objects needed in order to build this model. + + search_settings_discovery_authentication_model = {} # SearchSettingsDiscoveryAuthentication + search_settings_discovery_authentication_model['basic'] = 'testString' + search_settings_discovery_authentication_model['bearer'] = 'testString' + + search_settings_discovery_model = {} # SearchSettingsDiscovery + search_settings_discovery_model['instance_id'] = 'testString' + search_settings_discovery_model['project_id'] = 'testString' + search_settings_discovery_model['url'] = 'testString' + search_settings_discovery_model['max_primary_results'] = 10000 + search_settings_discovery_model['max_total_results'] = 10000 + search_settings_discovery_model['confidence_threshold'] = 0.0 + search_settings_discovery_model['highlight'] = True + search_settings_discovery_model['find_answers'] = True + search_settings_discovery_model['authentication'] = search_settings_discovery_authentication_model + + search_settings_messages_model = {} # SearchSettingsMessages + search_settings_messages_model['success'] = 'testString' + search_settings_messages_model['error'] = 'testString' + search_settings_messages_model['no_result'] = 'testString' + + search_settings_schema_mapping_model = {} # SearchSettingsSchemaMapping + search_settings_schema_mapping_model['url'] = 'testString' + search_settings_schema_mapping_model['body'] = 'testString' + search_settings_schema_mapping_model['title'] = 'testString' + + search_settings_elastic_search_model = {} # SearchSettingsElasticSearch + search_settings_elastic_search_model['url'] = 'testString' + search_settings_elastic_search_model['port'] = 'testString' + search_settings_elastic_search_model['username'] = 'testString' + search_settings_elastic_search_model['password'] = 'testString' + search_settings_elastic_search_model['index'] = 'testString' + search_settings_elastic_search_model['filter'] = ['testString'] + search_settings_elastic_search_model['query_body'] = {'anyKey': 'anyValue'} + search_settings_elastic_search_model['managed_index'] = 'testString' + search_settings_elastic_search_model['apikey'] = 'testString' + + search_settings_conversational_search_response_length_model = {} # SearchSettingsConversationalSearchResponseLength + search_settings_conversational_search_response_length_model['option'] = 'moderate' + + search_settings_conversational_search_search_confidence_model = {} # SearchSettingsConversationalSearchSearchConfidence + search_settings_conversational_search_search_confidence_model['threshold'] = 'less_often' + + search_settings_conversational_search_model = {} # SearchSettingsConversationalSearch + search_settings_conversational_search_model['enabled'] = True + search_settings_conversational_search_model['response_length'] = search_settings_conversational_search_response_length_model + search_settings_conversational_search_model['search_confidence'] = search_settings_conversational_search_search_confidence_model + + search_settings_server_side_search_model = {} # SearchSettingsServerSideSearch + search_settings_server_side_search_model['url'] = 'testString' + search_settings_server_side_search_model['port'] = 'testString' + search_settings_server_side_search_model['username'] = 'testString' + search_settings_server_side_search_model['password'] = 'testString' + search_settings_server_side_search_model['filter'] = 'testString' + search_settings_server_side_search_model['metadata'] = {'anyKey': 'anyValue'} + search_settings_server_side_search_model['apikey'] = 'testString' + search_settings_server_side_search_model['no_auth'] = True + search_settings_server_side_search_model['auth_type'] = 'basic' + + search_settings_client_side_search_model = {} # SearchSettingsClientSideSearch + search_settings_client_side_search_model['filter'] = 'testString' + search_settings_client_side_search_model['metadata'] = {'anyKey': 'anyValue'} + + search_settings_model = {} # SearchSettings + search_settings_model['discovery'] = search_settings_discovery_model + search_settings_model['messages'] = search_settings_messages_model + search_settings_model['schema_mapping'] = search_settings_schema_mapping_model + search_settings_model['elastic_search'] = search_settings_elastic_search_model + search_settings_model['conversational_search'] = search_settings_conversational_search_model + search_settings_model['server_side_search'] = search_settings_server_side_search_model + search_settings_model['client_side_search'] = search_settings_client_side_search_model + + skill_model = {} # Skill + skill_model['name'] = 'testString' + skill_model['description'] = 'testString' + skill_model['workspace'] = {'anyKey': 'anyValue'} + skill_model['dialog_settings'] = {'anyKey': 'anyValue'} + skill_model['search_settings'] = search_settings_model + skill_model['language'] = 'testString' + skill_model['type'] = 'action' + + assistant_state_model = {} # AssistantState + assistant_state_model['action_disabled'] = True + assistant_state_model['dialog_disabled'] = True + + # Construct a json representation of a SkillsExport model + skills_export_model_json = {} + skills_export_model_json['assistant_skills'] = [skill_model] + skills_export_model_json['assistant_state'] = assistant_state_model + + # Construct a model instance of SkillsExport by calling from_dict on the json representation + skills_export_model = SkillsExport.from_dict(skills_export_model_json) + assert skills_export_model != False + + # Construct a model instance of SkillsExport by calling from_dict on the json representation + skills_export_model_dict = SkillsExport.from_dict(skills_export_model_json).__dict__ + skills_export_model2 = SkillsExport(**skills_export_model_dict) + + # Verify the model instances are equivalent + assert skills_export_model == skills_export_model2 + + # Convert model instance back to dict and verify no loss of data + skills_export_model_json2 = skills_export_model.to_dict() + assert skills_export_model_json2 == skills_export_model_json + + +class TestModel_StatefulMessageResponse: + """ + Test Class for StatefulMessageResponse + """ + + def test_stateful_message_response_serialization(self): + """ + Test serialization/deserialization for StatefulMessageResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {'anyKey': 'anyValue'} + message_output_model['spelling'] = message_output_spelling_model + message_output_model['llm_metadata'] = [message_output_llm_metadata_model] + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False + + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model + + # Construct a json representation of a StatefulMessageResponse model + stateful_message_response_model_json = {} + stateful_message_response_model_json['output'] = message_output_model + stateful_message_response_model_json['context'] = message_context_model + stateful_message_response_model_json['user_id'] = 'testString' + stateful_message_response_model_json['masked_output'] = message_output_model + stateful_message_response_model_json['masked_input'] = message_input_model + + # Construct a model instance of StatefulMessageResponse by calling from_dict on the json representation + stateful_message_response_model = StatefulMessageResponse.from_dict(stateful_message_response_model_json) + assert stateful_message_response_model != False + + # Construct a model instance of StatefulMessageResponse by calling from_dict on the json representation + stateful_message_response_model_dict = StatefulMessageResponse.from_dict(stateful_message_response_model_json).__dict__ + stateful_message_response_model2 = StatefulMessageResponse(**stateful_message_response_model_dict) + + # Verify the model instances are equivalent + assert stateful_message_response_model == stateful_message_response_model2 + + # Convert model instance back to dict and verify no loss of data + stateful_message_response_model_json2 = stateful_message_response_model.to_dict() + assert stateful_message_response_model_json2 == stateful_message_response_model_json + + +class TestModel_StatelessFinalResponse: + """ + Test Class for StatelessFinalResponse + """ + + def test_stateless_final_response_serialization(self): + """ + Test serialization/deserialization for StatelessFinalResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + stateless_message_context_global_model = {} # StatelessMessageContextGlobal + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + stateless_message_context_skills_model = {} # StatelessMessageContextSkills + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model + + stateless_message_context_model = {} # StatelessMessageContext + stateless_message_context_model['global'] = stateless_message_context_global_model + stateless_message_context_model['skills'] = stateless_message_context_skills_model + stateless_message_context_model['integrations'] = {'anyKey': 'anyValue'} + + stateless_final_response_output_model = {} # StatelessFinalResponseOutput + stateless_final_response_output_model['generic'] = [runtime_response_generic_model] + stateless_final_response_output_model['intents'] = [runtime_intent_model] + stateless_final_response_output_model['entities'] = [runtime_entity_model] + stateless_final_response_output_model['actions'] = [dialog_node_action_model] + stateless_final_response_output_model['debug'] = message_output_debug_model + stateless_final_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_final_response_output_model['spelling'] = message_output_spelling_model + stateless_final_response_output_model['llm_metadata'] = [message_output_llm_metadata_model] + stateless_final_response_output_model['streaming_metadata'] = stateless_message_context_model + + # Construct a json representation of a StatelessFinalResponse model + stateless_final_response_model_json = {} + stateless_final_response_model_json['output'] = stateless_final_response_output_model + stateless_final_response_model_json['context'] = stateless_message_context_model + stateless_final_response_model_json['user_id'] = 'testString' + + # Construct a model instance of StatelessFinalResponse by calling from_dict on the json representation + stateless_final_response_model = StatelessFinalResponse.from_dict(stateless_final_response_model_json) + assert stateless_final_response_model != False + + # Construct a model instance of StatelessFinalResponse by calling from_dict on the json representation + stateless_final_response_model_dict = StatelessFinalResponse.from_dict(stateless_final_response_model_json).__dict__ + stateless_final_response_model2 = StatelessFinalResponse(**stateless_final_response_model_dict) + + # Verify the model instances are equivalent + assert stateless_final_response_model == stateless_final_response_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_final_response_model_json2 = stateless_final_response_model.to_dict() + assert stateless_final_response_model_json2 == stateless_final_response_model_json + + +class TestModel_StatelessFinalResponseOutput: + """ + Test Class for StatelessFinalResponseOutput + """ + + def test_stateless_final_response_output_serialization(self): + """ + Test serialization/deserialization for StatelessFinalResponseOutput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + stateless_message_context_global_model = {} # StatelessMessageContextGlobal + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + stateless_message_context_skills_model = {} # StatelessMessageContextSkills + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model + + stateless_message_context_model = {} # StatelessMessageContext + stateless_message_context_model['global'] = stateless_message_context_global_model + stateless_message_context_model['skills'] = stateless_message_context_skills_model + stateless_message_context_model['integrations'] = {'anyKey': 'anyValue'} + + # Construct a json representation of a StatelessFinalResponseOutput model + stateless_final_response_output_model_json = {} + stateless_final_response_output_model_json['generic'] = [runtime_response_generic_model] + stateless_final_response_output_model_json['intents'] = [runtime_intent_model] + stateless_final_response_output_model_json['entities'] = [runtime_entity_model] + stateless_final_response_output_model_json['actions'] = [dialog_node_action_model] + stateless_final_response_output_model_json['debug'] = message_output_debug_model + stateless_final_response_output_model_json['user_defined'] = {'anyKey': 'anyValue'} + stateless_final_response_output_model_json['spelling'] = message_output_spelling_model + stateless_final_response_output_model_json['llm_metadata'] = [message_output_llm_metadata_model] + stateless_final_response_output_model_json['streaming_metadata'] = stateless_message_context_model + + # Construct a model instance of StatelessFinalResponseOutput by calling from_dict on the json representation + stateless_final_response_output_model = StatelessFinalResponseOutput.from_dict(stateless_final_response_output_model_json) + assert stateless_final_response_output_model != False + + # Construct a model instance of StatelessFinalResponseOutput by calling from_dict on the json representation + stateless_final_response_output_model_dict = StatelessFinalResponseOutput.from_dict(stateless_final_response_output_model_json).__dict__ + stateless_final_response_output_model2 = StatelessFinalResponseOutput(**stateless_final_response_output_model_dict) + + # Verify the model instances are equivalent + assert stateless_final_response_output_model == stateless_final_response_output_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_final_response_output_model_json2 = stateless_final_response_output_model.to_dict() + assert stateless_final_response_output_model_json2 == stateless_final_response_output_model_json + + +class TestModel_StatelessMessageContext: + """ + Test Class for StatelessMessageContext + """ + + def test_stateless_message_context_serialization(self): + """ + Test serialization/deserialization for StatelessMessageContext + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + stateless_message_context_global_model = {} # StatelessMessageContextGlobal + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + stateless_message_context_skills_model = {} # StatelessMessageContextSkills + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model + + # Construct a json representation of a StatelessMessageContext model + stateless_message_context_model_json = {} + stateless_message_context_model_json['global'] = stateless_message_context_global_model + stateless_message_context_model_json['skills'] = stateless_message_context_skills_model + stateless_message_context_model_json['integrations'] = {'anyKey': 'anyValue'} + + # Construct a model instance of StatelessMessageContext by calling from_dict on the json representation + stateless_message_context_model = StatelessMessageContext.from_dict(stateless_message_context_model_json) + assert stateless_message_context_model != False + + # Construct a model instance of StatelessMessageContext by calling from_dict on the json representation + stateless_message_context_model_dict = StatelessMessageContext.from_dict(stateless_message_context_model_json).__dict__ + stateless_message_context_model2 = StatelessMessageContext(**stateless_message_context_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_context_model == stateless_message_context_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_context_model_json2 = stateless_message_context_model.to_dict() + assert stateless_message_context_model_json2 == stateless_message_context_model_json + + +class TestModel_StatelessMessageContextGlobal: + """ + Test Class for StatelessMessageContextGlobal + """ + + def test_stateless_message_context_global_serialization(self): + """ + Test serialization/deserialization for StatelessMessageContextGlobal + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + # Construct a json representation of a StatelessMessageContextGlobal model + stateless_message_context_global_model_json = {} + stateless_message_context_global_model_json['system'] = message_context_global_system_model + stateless_message_context_global_model_json['session_id'] = 'testString' + + # Construct a model instance of StatelessMessageContextGlobal by calling from_dict on the json representation + stateless_message_context_global_model = StatelessMessageContextGlobal.from_dict(stateless_message_context_global_model_json) + assert stateless_message_context_global_model != False + + # Construct a model instance of StatelessMessageContextGlobal by calling from_dict on the json representation + stateless_message_context_global_model_dict = StatelessMessageContextGlobal.from_dict(stateless_message_context_global_model_json).__dict__ + stateless_message_context_global_model2 = StatelessMessageContextGlobal(**stateless_message_context_global_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_context_global_model == stateless_message_context_global_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_context_global_model_json2 = stateless_message_context_global_model.to_dict() + assert stateless_message_context_global_model_json2 == stateless_message_context_global_model_json + + +class TestModel_StatelessMessageContextSkills: + """ + Test Class for StatelessMessageContextSkills + """ + + def test_stateless_message_context_skills_serialization(self): + """ + Test serialization/deserialization for StatelessMessageContextSkills + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a json representation of a StatelessMessageContextSkills model + stateless_message_context_skills_model_json = {} + stateless_message_context_skills_model_json['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model_json['actions skill'] = stateless_message_context_skills_actions_skill_model + + # Construct a model instance of StatelessMessageContextSkills by calling from_dict on the json representation + stateless_message_context_skills_model = StatelessMessageContextSkills.from_dict(stateless_message_context_skills_model_json) + assert stateless_message_context_skills_model != False + + # Construct a model instance of StatelessMessageContextSkills by calling from_dict on the json representation + stateless_message_context_skills_model_dict = StatelessMessageContextSkills.from_dict(stateless_message_context_skills_model_json).__dict__ + stateless_message_context_skills_model2 = StatelessMessageContextSkills(**stateless_message_context_skills_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_context_skills_model == stateless_message_context_skills_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_context_skills_model_json2 = stateless_message_context_skills_model.to_dict() + assert stateless_message_context_skills_model_json2 == stateless_message_context_skills_model_json + + +class TestModel_StatelessMessageContextSkillsActionsSkill: + """ + Test Class for StatelessMessageContextSkillsActionsSkill + """ + + def test_stateless_message_context_skills_actions_skill_serialization(self): + """ + Test serialization/deserialization for StatelessMessageContextSkillsActionsSkill + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + # Construct a json representation of a StatelessMessageContextSkillsActionsSkill model + stateless_message_context_skills_actions_skill_model_json = {} + stateless_message_context_skills_actions_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model_json['private_skill_variables'] = {'anyKey': 'anyValue'} + + # Construct a model instance of StatelessMessageContextSkillsActionsSkill by calling from_dict on the json representation + stateless_message_context_skills_actions_skill_model = StatelessMessageContextSkillsActionsSkill.from_dict(stateless_message_context_skills_actions_skill_model_json) + assert stateless_message_context_skills_actions_skill_model != False + + # Construct a model instance of StatelessMessageContextSkillsActionsSkill by calling from_dict on the json representation + stateless_message_context_skills_actions_skill_model_dict = StatelessMessageContextSkillsActionsSkill.from_dict(stateless_message_context_skills_actions_skill_model_json).__dict__ + stateless_message_context_skills_actions_skill_model2 = StatelessMessageContextSkillsActionsSkill(**stateless_message_context_skills_actions_skill_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_context_skills_actions_skill_model == stateless_message_context_skills_actions_skill_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_context_skills_actions_skill_model_json2 = stateless_message_context_skills_actions_skill_model.to_dict() + assert stateless_message_context_skills_actions_skill_model_json2 == stateless_message_context_skills_actions_skill_model_json + + +class TestModel_StatelessMessageInput: + """ + Test Class for StatelessMessageInput + """ + + def test_stateless_message_input_serialization(self): + """ + Test serialization/deserialization for StatelessMessageInput + """ + + # Construct dict forms of any model objects needed in order to build this model. + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + stateless_message_input_options_model = {} # StatelessMessageInputOptions + stateless_message_input_options_model['restart'] = False + stateless_message_input_options_model['alternate_intents'] = False + stateless_message_input_options_model['async_callout'] = False + stateless_message_input_options_model['spelling'] = message_input_options_spelling_model + stateless_message_input_options_model['debug'] = False + + # Construct a json representation of a StatelessMessageInput model + stateless_message_input_model_json = {} + stateless_message_input_model_json['message_type'] = 'text' + stateless_message_input_model_json['text'] = 'testString' + stateless_message_input_model_json['intents'] = [runtime_intent_model] + stateless_message_input_model_json['entities'] = [runtime_entity_model] + stateless_message_input_model_json['suggestion_id'] = 'testString' + stateless_message_input_model_json['attachments'] = [message_input_attachment_model] + stateless_message_input_model_json['analytics'] = request_analytics_model + stateless_message_input_model_json['options'] = stateless_message_input_options_model + + # Construct a model instance of StatelessMessageInput by calling from_dict on the json representation + stateless_message_input_model = StatelessMessageInput.from_dict(stateless_message_input_model_json) + assert stateless_message_input_model != False + + # Construct a model instance of StatelessMessageInput by calling from_dict on the json representation + stateless_message_input_model_dict = StatelessMessageInput.from_dict(stateless_message_input_model_json).__dict__ + stateless_message_input_model2 = StatelessMessageInput(**stateless_message_input_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_input_model == stateless_message_input_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_input_model_json2 = stateless_message_input_model.to_dict() + assert stateless_message_input_model_json2 == stateless_message_input_model_json + + +class TestModel_StatelessMessageInputOptions: + """ + Test Class for StatelessMessageInputOptions + """ + + def test_stateless_message_input_options_serialization(self): + """ + Test serialization/deserialization for StatelessMessageInputOptions + """ + + # Construct dict forms of any model objects needed in order to build this model. + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True + + # Construct a json representation of a StatelessMessageInputOptions model + stateless_message_input_options_model_json = {} + stateless_message_input_options_model_json['restart'] = False + stateless_message_input_options_model_json['alternate_intents'] = False + stateless_message_input_options_model_json['async_callout'] = False + stateless_message_input_options_model_json['spelling'] = message_input_options_spelling_model + stateless_message_input_options_model_json['debug'] = False + + # Construct a model instance of StatelessMessageInputOptions by calling from_dict on the json representation + stateless_message_input_options_model = StatelessMessageInputOptions.from_dict(stateless_message_input_options_model_json) + assert stateless_message_input_options_model != False + + # Construct a model instance of StatelessMessageInputOptions by calling from_dict on the json representation + stateless_message_input_options_model_dict = StatelessMessageInputOptions.from_dict(stateless_message_input_options_model_json).__dict__ + stateless_message_input_options_model2 = StatelessMessageInputOptions(**stateless_message_input_options_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_input_options_model == stateless_message_input_options_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_input_options_model_json2 = stateless_message_input_options_model.to_dict() + assert stateless_message_input_options_model_json2 == stateless_message_input_options_model_json + + +class TestModel_StatelessMessageResponse: + """ + Test Class for StatelessMessageResponse + """ + + def test_stateless_message_response_serialization(self): + """ + Test serialization/deserialization for StatelessMessageResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole runtime_entity_role_model['type'] = 'date_from' runtime_entity_model = {} # RuntimeEntity @@ -11103,6 +13175,10 @@ def test_stateful_message_response_serialization(self): message_output_spelling_model['original_text'] = 'testString' message_output_spelling_model['suggested_text'] = 'testString' + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' + message_output_model = {} # MessageOutput message_output_model['generic'] = [runtime_response_generic_model] message_output_model['intents'] = [runtime_intent_model] @@ -11111,6 +13187,7 @@ def test_stateful_message_response_serialization(self): message_output_model['debug'] = message_output_debug_model message_output_model['user_defined'] = {'anyKey': 'anyValue'} message_output_model['spelling'] = message_output_spelling_model + message_output_model['llm_metadata'] = [message_output_llm_metadata_model] message_context_global_system_model = {} # MessageContextGlobalSystem message_context_global_system_model['timezone'] = 'testString' @@ -11122,8 +13199,9 @@ def test_stateful_message_response_serialization(self): message_context_global_system_model['state'] = 'testString' message_context_global_system_model['skip_user_input'] = True - message_context_global_model = {} # MessageContextGlobal - message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model = {} # StatelessMessageContextGlobal + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' message_context_skill_system_model = {} # MessageContextSkillSystem message_context_skill_system_model['state'] = 'testString' @@ -11133,20 +13211,22 @@ def test_stateful_message_response_serialization(self): message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} message_context_dialog_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model = {} # MessageContextActionSkill - message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['system'] = message_context_skill_system_model - message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} - message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} - message_context_skills_model = {} # MessageContextSkills - message_context_skills_model['main skill'] = message_context_dialog_skill_model - message_context_skills_model['actions skill'] = message_context_action_skill_model + stateless_message_context_skills_model = {} # StatelessMessageContextSkills + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model - message_context_model = {} # MessageContext - message_context_model['global'] = message_context_global_model - message_context_model['skills'] = message_context_skills_model - message_context_model['integrations'] = {'anyKey': 'anyValue'} + stateless_message_context_model = {} # StatelessMessageContext + stateless_message_context_model['global'] = stateless_message_context_global_model + stateless_message_context_model['skills'] = stateless_message_context_skills_model + stateless_message_context_model['integrations'] = {'anyKey': 'anyValue'} message_input_attachment_model = {} # MessageInputAttachment message_input_attachment_model['url'] = 'testString' @@ -11180,1114 +13260,1512 @@ def test_stateful_message_response_serialization(self): message_input_model['analytics'] = request_analytics_model message_input_model['options'] = message_input_options_model - # Construct a json representation of a StatefulMessageResponse model - stateful_message_response_model_json = {} - stateful_message_response_model_json['output'] = message_output_model - stateful_message_response_model_json['context'] = message_context_model - stateful_message_response_model_json['user_id'] = 'testString' - stateful_message_response_model_json['masked_output'] = message_output_model - stateful_message_response_model_json['masked_input'] = message_input_model + # Construct a json representation of a StatelessMessageResponse model + stateless_message_response_model_json = {} + stateless_message_response_model_json['output'] = message_output_model + stateless_message_response_model_json['context'] = stateless_message_context_model + stateless_message_response_model_json['masked_output'] = message_output_model + stateless_message_response_model_json['masked_input'] = message_input_model + stateless_message_response_model_json['user_id'] = 'testString' - # Construct a model instance of StatefulMessageResponse by calling from_dict on the json representation - stateful_message_response_model = StatefulMessageResponse.from_dict(stateful_message_response_model_json) - assert stateful_message_response_model != False + # Construct a model instance of StatelessMessageResponse by calling from_dict on the json representation + stateless_message_response_model = StatelessMessageResponse.from_dict(stateless_message_response_model_json) + assert stateless_message_response_model != False + + # Construct a model instance of StatelessMessageResponse by calling from_dict on the json representation + stateless_message_response_model_dict = StatelessMessageResponse.from_dict(stateless_message_response_model_json).__dict__ + stateless_message_response_model2 = StatelessMessageResponse(**stateless_message_response_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_response_model == stateless_message_response_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_response_model_json2 = stateless_message_response_model.to_dict() + assert stateless_message_response_model_json2 == stateless_message_response_model_json + + +class TestModel_StatusError: + """ + Test Class for StatusError + """ + + def test_status_error_serialization(self): + """ + Test serialization/deserialization for StatusError + """ + + # Construct a json representation of a StatusError model + status_error_model_json = {} + status_error_model_json['message'] = 'testString' + + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model = StatusError.from_dict(status_error_model_json) + assert status_error_model != False + + # Construct a model instance of StatusError by calling from_dict on the json representation + status_error_model_dict = StatusError.from_dict(status_error_model_json).__dict__ + status_error_model2 = StatusError(**status_error_model_dict) + + # Verify the model instances are equivalent + assert status_error_model == status_error_model2 + + # Convert model instance back to dict and verify no loss of data + status_error_model_json2 = status_error_model.to_dict() + assert status_error_model_json2 == status_error_model_json + + +class TestModel_TurnEventActionSource: + """ + Test Class for TurnEventActionSource + """ + + def test_turn_event_action_source_serialization(self): + """ + Test serialization/deserialization for TurnEventActionSource + """ + + # Construct a json representation of a TurnEventActionSource model + turn_event_action_source_model_json = {} + turn_event_action_source_model_json['type'] = 'action' + turn_event_action_source_model_json['action'] = 'testString' + turn_event_action_source_model_json['action_title'] = 'testString' + turn_event_action_source_model_json['condition'] = 'testString' + + # Construct a model instance of TurnEventActionSource by calling from_dict on the json representation + turn_event_action_source_model = TurnEventActionSource.from_dict(turn_event_action_source_model_json) + assert turn_event_action_source_model != False + + # Construct a model instance of TurnEventActionSource by calling from_dict on the json representation + turn_event_action_source_model_dict = TurnEventActionSource.from_dict(turn_event_action_source_model_json).__dict__ + turn_event_action_source_model2 = TurnEventActionSource(**turn_event_action_source_model_dict) + + # Verify the model instances are equivalent + assert turn_event_action_source_model == turn_event_action_source_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_action_source_model_json2 = turn_event_action_source_model.to_dict() + assert turn_event_action_source_model_json2 == turn_event_action_source_model_json + + +class TestModel_TurnEventCalloutCallout: + """ + Test Class for TurnEventCalloutCallout + """ + + def test_turn_event_callout_callout_serialization(self): + """ + Test serialization/deserialization for TurnEventCalloutCallout + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_callout_callout_request_model = {} # TurnEventCalloutCalloutRequest + turn_event_callout_callout_request_model['method'] = 'get' + turn_event_callout_callout_request_model['url'] = 'testString' + turn_event_callout_callout_request_model['path'] = 'testString' + turn_event_callout_callout_request_model['query_parameters'] = 'testString' + turn_event_callout_callout_request_model['headers'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_request_model['body'] = {'anyKey': 'anyValue'} + + turn_event_callout_callout_response_model = {} # TurnEventCalloutCalloutResponse + turn_event_callout_callout_response_model['body'] = 'testString' + turn_event_callout_callout_response_model['status_code'] = 38 + turn_event_callout_callout_response_model['last_event'] = {'anyKey': 'anyValue'} + + # Construct a json representation of a TurnEventCalloutCallout model + turn_event_callout_callout_model_json = {} + turn_event_callout_callout_model_json['type'] = 'integration_interaction' + turn_event_callout_callout_model_json['internal'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_model_json['result_variable'] = 'testString' + turn_event_callout_callout_model_json['request'] = turn_event_callout_callout_request_model + turn_event_callout_callout_model_json['response'] = turn_event_callout_callout_response_model + + # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation + turn_event_callout_callout_model = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json) + assert turn_event_callout_callout_model != False + + # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation + turn_event_callout_callout_model_dict = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json).__dict__ + turn_event_callout_callout_model2 = TurnEventCalloutCallout(**turn_event_callout_callout_model_dict) + + # Verify the model instances are equivalent + assert turn_event_callout_callout_model == turn_event_callout_callout_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_callout_callout_model_json2 = turn_event_callout_callout_model.to_dict() + assert turn_event_callout_callout_model_json2 == turn_event_callout_callout_model_json + + +class TestModel_TurnEventCalloutCalloutRequest: + """ + Test Class for TurnEventCalloutCalloutRequest + """ + + def test_turn_event_callout_callout_request_serialization(self): + """ + Test serialization/deserialization for TurnEventCalloutCalloutRequest + """ + + # Construct a json representation of a TurnEventCalloutCalloutRequest model + turn_event_callout_callout_request_model_json = {} + turn_event_callout_callout_request_model_json['method'] = 'get' + turn_event_callout_callout_request_model_json['url'] = 'testString' + turn_event_callout_callout_request_model_json['path'] = 'testString' + turn_event_callout_callout_request_model_json['query_parameters'] = 'testString' + turn_event_callout_callout_request_model_json['headers'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_request_model_json['body'] = {'anyKey': 'anyValue'} + + # Construct a model instance of TurnEventCalloutCalloutRequest by calling from_dict on the json representation + turn_event_callout_callout_request_model = TurnEventCalloutCalloutRequest.from_dict(turn_event_callout_callout_request_model_json) + assert turn_event_callout_callout_request_model != False + + # Construct a model instance of TurnEventCalloutCalloutRequest by calling from_dict on the json representation + turn_event_callout_callout_request_model_dict = TurnEventCalloutCalloutRequest.from_dict(turn_event_callout_callout_request_model_json).__dict__ + turn_event_callout_callout_request_model2 = TurnEventCalloutCalloutRequest(**turn_event_callout_callout_request_model_dict) + + # Verify the model instances are equivalent + assert turn_event_callout_callout_request_model == turn_event_callout_callout_request_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_callout_callout_request_model_json2 = turn_event_callout_callout_request_model.to_dict() + assert turn_event_callout_callout_request_model_json2 == turn_event_callout_callout_request_model_json + + +class TestModel_TurnEventCalloutCalloutResponse: + """ + Test Class for TurnEventCalloutCalloutResponse + """ + + def test_turn_event_callout_callout_response_serialization(self): + """ + Test serialization/deserialization for TurnEventCalloutCalloutResponse + """ + + # Construct a json representation of a TurnEventCalloutCalloutResponse model + turn_event_callout_callout_response_model_json = {} + turn_event_callout_callout_response_model_json['body'] = 'testString' + turn_event_callout_callout_response_model_json['status_code'] = 38 + turn_event_callout_callout_response_model_json['last_event'] = {'anyKey': 'anyValue'} + + # Construct a model instance of TurnEventCalloutCalloutResponse by calling from_dict on the json representation + turn_event_callout_callout_response_model = TurnEventCalloutCalloutResponse.from_dict(turn_event_callout_callout_response_model_json) + assert turn_event_callout_callout_response_model != False + + # Construct a model instance of TurnEventCalloutCalloutResponse by calling from_dict on the json representation + turn_event_callout_callout_response_model_dict = TurnEventCalloutCalloutResponse.from_dict(turn_event_callout_callout_response_model_json).__dict__ + turn_event_callout_callout_response_model2 = TurnEventCalloutCalloutResponse(**turn_event_callout_callout_response_model_dict) + + # Verify the model instances are equivalent + assert turn_event_callout_callout_response_model == turn_event_callout_callout_response_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_callout_callout_response_model_json2 = turn_event_callout_callout_response_model.to_dict() + assert turn_event_callout_callout_response_model_json2 == turn_event_callout_callout_response_model_json + + +class TestModel_TurnEventCalloutError: + """ + Test Class for TurnEventCalloutError + """ + + def test_turn_event_callout_error_serialization(self): + """ + Test serialization/deserialization for TurnEventCalloutError + """ + + # Construct a json representation of a TurnEventCalloutError model + turn_event_callout_error_model_json = {} + turn_event_callout_error_model_json['message'] = 'testString' + + # Construct a model instance of TurnEventCalloutError by calling from_dict on the json representation + turn_event_callout_error_model = TurnEventCalloutError.from_dict(turn_event_callout_error_model_json) + assert turn_event_callout_error_model != False + + # Construct a model instance of TurnEventCalloutError by calling from_dict on the json representation + turn_event_callout_error_model_dict = TurnEventCalloutError.from_dict(turn_event_callout_error_model_json).__dict__ + turn_event_callout_error_model2 = TurnEventCalloutError(**turn_event_callout_error_model_dict) + + # Verify the model instances are equivalent + assert turn_event_callout_error_model == turn_event_callout_error_model2 + + # Convert model instance back to dict and verify no loss of data + turn_event_callout_error_model_json2 = turn_event_callout_error_model.to_dict() + assert turn_event_callout_error_model_json2 == turn_event_callout_error_model_json + + +class TestModel_TurnEventGenerativeAICalledCallout: + """ + Test Class for TurnEventGenerativeAICalledCallout + """ + + def test_turn_event_generative_ai_called_callout_serialization(self): + """ + Test serialization/deserialization for TurnEventGenerativeAICalledCallout + """ - # Construct a model instance of StatefulMessageResponse by calling from_dict on the json representation - stateful_message_response_model_dict = StatefulMessageResponse.from_dict(stateful_message_response_model_json).__dict__ - stateful_message_response_model2 = StatefulMessageResponse(**stateful_message_response_model_dict) + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_generative_ai_called_callout_request_model = {} # TurnEventGenerativeAICalledCalloutRequest + turn_event_generative_ai_called_callout_request_model['method'] = 'GET' + turn_event_generative_ai_called_callout_request_model['url'] = 'testString' + turn_event_generative_ai_called_callout_request_model['port'] = 'testString' + turn_event_generative_ai_called_callout_request_model['path'] = 'testString' + turn_event_generative_ai_called_callout_request_model['query_parameters'] = 'testString' + turn_event_generative_ai_called_callout_request_model['headers'] = {'anyKey': 'anyValue'} + turn_event_generative_ai_called_callout_request_model['body'] = {'anyKey': 'anyValue'} + + turn_event_generative_ai_called_callout_response_model = {} # TurnEventGenerativeAICalledCalloutResponse + turn_event_generative_ai_called_callout_response_model['body'] = 'testString' + turn_event_generative_ai_called_callout_response_model['status_code'] = 38 + + turn_event_generative_ai_called_callout_search_model = {} # TurnEventGenerativeAICalledCalloutSearch + turn_event_generative_ai_called_callout_search_model['engine'] = 'testString' + turn_event_generative_ai_called_callout_search_model['index'] = 'testString' + turn_event_generative_ai_called_callout_search_model['query'] = 'testString' + turn_event_generative_ai_called_callout_search_model['request'] = turn_event_generative_ai_called_callout_request_model + turn_event_generative_ai_called_callout_search_model['response'] = turn_event_generative_ai_called_callout_response_model + + turn_event_generative_ai_called_callout_llm_response_model = {} # TurnEventGenerativeAICalledCalloutLlmResponse + turn_event_generative_ai_called_callout_llm_response_model['text'] = 'testString' + turn_event_generative_ai_called_callout_llm_response_model['response_type'] = 'testString' + turn_event_generative_ai_called_callout_llm_response_model['is_idk_response'] = True + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + turn_event_generative_ai_called_callout_llm_model = {} # TurnEventGenerativeAICalledCalloutLlm + turn_event_generative_ai_called_callout_llm_model['type'] = 'testString' + turn_event_generative_ai_called_callout_llm_model['model_id'] = 'testString' + turn_event_generative_ai_called_callout_llm_model['model_class_id'] = 'testString' + turn_event_generative_ai_called_callout_llm_model['generated_token_count'] = 38 + turn_event_generative_ai_called_callout_llm_model['input_token_count'] = 38 + turn_event_generative_ai_called_callout_llm_model['success'] = True + turn_event_generative_ai_called_callout_llm_model['response'] = turn_event_generative_ai_called_callout_llm_response_model + turn_event_generative_ai_called_callout_llm_model['request'] = [search_results_model] + + # Construct a json representation of a TurnEventGenerativeAICalledCallout model + turn_event_generative_ai_called_callout_model_json = {} + turn_event_generative_ai_called_callout_model_json['search_called'] = True + turn_event_generative_ai_called_callout_model_json['llm_called'] = True + turn_event_generative_ai_called_callout_model_json['search'] = turn_event_generative_ai_called_callout_search_model + turn_event_generative_ai_called_callout_model_json['llm'] = turn_event_generative_ai_called_callout_llm_model + turn_event_generative_ai_called_callout_model_json['idk_reason_code'] = 'testString' + + # Construct a model instance of TurnEventGenerativeAICalledCallout by calling from_dict on the json representation + turn_event_generative_ai_called_callout_model = TurnEventGenerativeAICalledCallout.from_dict(turn_event_generative_ai_called_callout_model_json) + assert turn_event_generative_ai_called_callout_model != False + + # Construct a model instance of TurnEventGenerativeAICalledCallout by calling from_dict on the json representation + turn_event_generative_ai_called_callout_model_dict = TurnEventGenerativeAICalledCallout.from_dict(turn_event_generative_ai_called_callout_model_json).__dict__ + turn_event_generative_ai_called_callout_model2 = TurnEventGenerativeAICalledCallout(**turn_event_generative_ai_called_callout_model_dict) # Verify the model instances are equivalent - assert stateful_message_response_model == stateful_message_response_model2 + assert turn_event_generative_ai_called_callout_model == turn_event_generative_ai_called_callout_model2 # Convert model instance back to dict and verify no loss of data - stateful_message_response_model_json2 = stateful_message_response_model.to_dict() - assert stateful_message_response_model_json2 == stateful_message_response_model_json + turn_event_generative_ai_called_callout_model_json2 = turn_event_generative_ai_called_callout_model.to_dict() + assert turn_event_generative_ai_called_callout_model_json2 == turn_event_generative_ai_called_callout_model_json -class TestModel_StatelessMessageContext: +class TestModel_TurnEventGenerativeAICalledCalloutLlm: """ - Test Class for StatelessMessageContext + Test Class for TurnEventGenerativeAICalledCalloutLlm """ - def test_stateless_message_context_serialization(self): + def test_turn_event_generative_ai_called_callout_llm_serialization(self): """ - Test serialization/deserialization for StatelessMessageContext + Test serialization/deserialization for TurnEventGenerativeAICalledCalloutLlm """ # Construct dict forms of any model objects needed in order to build this model. - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + turn_event_generative_ai_called_callout_llm_response_model = {} # TurnEventGenerativeAICalledCalloutLlmResponse + turn_event_generative_ai_called_callout_llm_response_model['text'] = 'testString' + turn_event_generative_ai_called_callout_llm_response_model['response_type'] = 'testString' + turn_event_generative_ai_called_callout_llm_response_model['is_idk_response'] = True + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + # Construct a json representation of a TurnEventGenerativeAICalledCalloutLlm model + turn_event_generative_ai_called_callout_llm_model_json = {} + turn_event_generative_ai_called_callout_llm_model_json['type'] = 'testString' + turn_event_generative_ai_called_callout_llm_model_json['model_id'] = 'testString' + turn_event_generative_ai_called_callout_llm_model_json['model_class_id'] = 'testString' + turn_event_generative_ai_called_callout_llm_model_json['generated_token_count'] = 38 + turn_event_generative_ai_called_callout_llm_model_json['input_token_count'] = 38 + turn_event_generative_ai_called_callout_llm_model_json['success'] = True + turn_event_generative_ai_called_callout_llm_model_json['response'] = turn_event_generative_ai_called_callout_llm_response_model + turn_event_generative_ai_called_callout_llm_model_json['request'] = [search_results_model] + + # Construct a model instance of TurnEventGenerativeAICalledCalloutLlm by calling from_dict on the json representation + turn_event_generative_ai_called_callout_llm_model = TurnEventGenerativeAICalledCalloutLlm.from_dict(turn_event_generative_ai_called_callout_llm_model_json) + assert turn_event_generative_ai_called_callout_llm_model != False + + # Construct a model instance of TurnEventGenerativeAICalledCalloutLlm by calling from_dict on the json representation + turn_event_generative_ai_called_callout_llm_model_dict = TurnEventGenerativeAICalledCalloutLlm.from_dict(turn_event_generative_ai_called_callout_llm_model_json).__dict__ + turn_event_generative_ai_called_callout_llm_model2 = TurnEventGenerativeAICalledCalloutLlm(**turn_event_generative_ai_called_callout_llm_model_dict) - stateless_message_context_global_model = {} # StatelessMessageContextGlobal - stateless_message_context_global_model['system'] = message_context_global_system_model - stateless_message_context_global_model['session_id'] = 'testString' + # Verify the model instances are equivalent + assert turn_event_generative_ai_called_callout_llm_model == turn_event_generative_ai_called_callout_llm_model2 - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Convert model instance back to dict and verify no loss of data + turn_event_generative_ai_called_callout_llm_model_json2 = turn_event_generative_ai_called_callout_llm_model.to_dict() + assert turn_event_generative_ai_called_callout_llm_model_json2 == turn_event_generative_ai_called_callout_llm_model_json - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model - stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill - stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model - stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} +class TestModel_TurnEventGenerativeAICalledCalloutLlmResponse: + """ + Test Class for TurnEventGenerativeAICalledCalloutLlmResponse + """ - stateless_message_context_skills_model = {} # StatelessMessageContextSkills - stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model - stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model + def test_turn_event_generative_ai_called_callout_llm_response_serialization(self): + """ + Test serialization/deserialization for TurnEventGenerativeAICalledCalloutLlmResponse + """ - # Construct a json representation of a StatelessMessageContext model - stateless_message_context_model_json = {} - stateless_message_context_model_json['global'] = stateless_message_context_global_model - stateless_message_context_model_json['skills'] = stateless_message_context_skills_model - stateless_message_context_model_json['integrations'] = {'anyKey': 'anyValue'} + # Construct a json representation of a TurnEventGenerativeAICalledCalloutLlmResponse model + turn_event_generative_ai_called_callout_llm_response_model_json = {} + turn_event_generative_ai_called_callout_llm_response_model_json['text'] = 'testString' + turn_event_generative_ai_called_callout_llm_response_model_json['response_type'] = 'testString' + turn_event_generative_ai_called_callout_llm_response_model_json['is_idk_response'] = True - # Construct a model instance of StatelessMessageContext by calling from_dict on the json representation - stateless_message_context_model = StatelessMessageContext.from_dict(stateless_message_context_model_json) - assert stateless_message_context_model != False + # Construct a model instance of TurnEventGenerativeAICalledCalloutLlmResponse by calling from_dict on the json representation + turn_event_generative_ai_called_callout_llm_response_model = TurnEventGenerativeAICalledCalloutLlmResponse.from_dict(turn_event_generative_ai_called_callout_llm_response_model_json) + assert turn_event_generative_ai_called_callout_llm_response_model != False - # Construct a model instance of StatelessMessageContext by calling from_dict on the json representation - stateless_message_context_model_dict = StatelessMessageContext.from_dict(stateless_message_context_model_json).__dict__ - stateless_message_context_model2 = StatelessMessageContext(**stateless_message_context_model_dict) + # Construct a model instance of TurnEventGenerativeAICalledCalloutLlmResponse by calling from_dict on the json representation + turn_event_generative_ai_called_callout_llm_response_model_dict = TurnEventGenerativeAICalledCalloutLlmResponse.from_dict(turn_event_generative_ai_called_callout_llm_response_model_json).__dict__ + turn_event_generative_ai_called_callout_llm_response_model2 = TurnEventGenerativeAICalledCalloutLlmResponse(**turn_event_generative_ai_called_callout_llm_response_model_dict) # Verify the model instances are equivalent - assert stateless_message_context_model == stateless_message_context_model2 + assert turn_event_generative_ai_called_callout_llm_response_model == turn_event_generative_ai_called_callout_llm_response_model2 # Convert model instance back to dict and verify no loss of data - stateless_message_context_model_json2 = stateless_message_context_model.to_dict() - assert stateless_message_context_model_json2 == stateless_message_context_model_json + turn_event_generative_ai_called_callout_llm_response_model_json2 = turn_event_generative_ai_called_callout_llm_response_model.to_dict() + assert turn_event_generative_ai_called_callout_llm_response_model_json2 == turn_event_generative_ai_called_callout_llm_response_model_json -class TestModel_StatelessMessageContextGlobal: +class TestModel_TurnEventGenerativeAICalledCalloutRequest: """ - Test Class for StatelessMessageContextGlobal + Test Class for TurnEventGenerativeAICalledCalloutRequest """ - def test_stateless_message_context_global_serialization(self): + def test_turn_event_generative_ai_called_callout_request_serialization(self): """ - Test serialization/deserialization for StatelessMessageContextGlobal + Test serialization/deserialization for TurnEventGenerativeAICalledCalloutRequest """ - # Construct dict forms of any model objects needed in order to build this model. - - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True - - # Construct a json representation of a StatelessMessageContextGlobal model - stateless_message_context_global_model_json = {} - stateless_message_context_global_model_json['system'] = message_context_global_system_model - stateless_message_context_global_model_json['session_id'] = 'testString' + # Construct a json representation of a TurnEventGenerativeAICalledCalloutRequest model + turn_event_generative_ai_called_callout_request_model_json = {} + turn_event_generative_ai_called_callout_request_model_json['method'] = 'GET' + turn_event_generative_ai_called_callout_request_model_json['url'] = 'testString' + turn_event_generative_ai_called_callout_request_model_json['port'] = 'testString' + turn_event_generative_ai_called_callout_request_model_json['path'] = 'testString' + turn_event_generative_ai_called_callout_request_model_json['query_parameters'] = 'testString' + turn_event_generative_ai_called_callout_request_model_json['headers'] = {'anyKey': 'anyValue'} + turn_event_generative_ai_called_callout_request_model_json['body'] = {'anyKey': 'anyValue'} - # Construct a model instance of StatelessMessageContextGlobal by calling from_dict on the json representation - stateless_message_context_global_model = StatelessMessageContextGlobal.from_dict(stateless_message_context_global_model_json) - assert stateless_message_context_global_model != False + # Construct a model instance of TurnEventGenerativeAICalledCalloutRequest by calling from_dict on the json representation + turn_event_generative_ai_called_callout_request_model = TurnEventGenerativeAICalledCalloutRequest.from_dict(turn_event_generative_ai_called_callout_request_model_json) + assert turn_event_generative_ai_called_callout_request_model != False - # Construct a model instance of StatelessMessageContextGlobal by calling from_dict on the json representation - stateless_message_context_global_model_dict = StatelessMessageContextGlobal.from_dict(stateless_message_context_global_model_json).__dict__ - stateless_message_context_global_model2 = StatelessMessageContextGlobal(**stateless_message_context_global_model_dict) + # Construct a model instance of TurnEventGenerativeAICalledCalloutRequest by calling from_dict on the json representation + turn_event_generative_ai_called_callout_request_model_dict = TurnEventGenerativeAICalledCalloutRequest.from_dict(turn_event_generative_ai_called_callout_request_model_json).__dict__ + turn_event_generative_ai_called_callout_request_model2 = TurnEventGenerativeAICalledCalloutRequest(**turn_event_generative_ai_called_callout_request_model_dict) # Verify the model instances are equivalent - assert stateless_message_context_global_model == stateless_message_context_global_model2 + assert turn_event_generative_ai_called_callout_request_model == turn_event_generative_ai_called_callout_request_model2 # Convert model instance back to dict and verify no loss of data - stateless_message_context_global_model_json2 = stateless_message_context_global_model.to_dict() - assert stateless_message_context_global_model_json2 == stateless_message_context_global_model_json + turn_event_generative_ai_called_callout_request_model_json2 = turn_event_generative_ai_called_callout_request_model.to_dict() + assert turn_event_generative_ai_called_callout_request_model_json2 == turn_event_generative_ai_called_callout_request_model_json -class TestModel_StatelessMessageContextSkills: +class TestModel_TurnEventGenerativeAICalledCalloutResponse: """ - Test Class for StatelessMessageContextSkills + Test Class for TurnEventGenerativeAICalledCalloutResponse """ - def test_stateless_message_context_skills_serialization(self): + def test_turn_event_generative_ai_called_callout_response_serialization(self): """ - Test serialization/deserialization for StatelessMessageContextSkills + Test serialization/deserialization for TurnEventGenerativeAICalledCalloutResponse """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a TurnEventGenerativeAICalledCalloutResponse model + turn_event_generative_ai_called_callout_response_model_json = {} + turn_event_generative_ai_called_callout_response_model_json['body'] = 'testString' + turn_event_generative_ai_called_callout_response_model_json['status_code'] = 38 - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Construct a model instance of TurnEventGenerativeAICalledCalloutResponse by calling from_dict on the json representation + turn_event_generative_ai_called_callout_response_model = TurnEventGenerativeAICalledCalloutResponse.from_dict(turn_event_generative_ai_called_callout_response_model_json) + assert turn_event_generative_ai_called_callout_response_model != False - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Construct a model instance of TurnEventGenerativeAICalledCalloutResponse by calling from_dict on the json representation + turn_event_generative_ai_called_callout_response_model_dict = TurnEventGenerativeAICalledCalloutResponse.from_dict(turn_event_generative_ai_called_callout_response_model_json).__dict__ + turn_event_generative_ai_called_callout_response_model2 = TurnEventGenerativeAICalledCalloutResponse(**turn_event_generative_ai_called_callout_response_model_dict) - stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill - stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model - stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + # Verify the model instances are equivalent + assert turn_event_generative_ai_called_callout_response_model == turn_event_generative_ai_called_callout_response_model2 - # Construct a json representation of a StatelessMessageContextSkills model - stateless_message_context_skills_model_json = {} - stateless_message_context_skills_model_json['main skill'] = message_context_dialog_skill_model - stateless_message_context_skills_model_json['actions skill'] = stateless_message_context_skills_actions_skill_model + # Convert model instance back to dict and verify no loss of data + turn_event_generative_ai_called_callout_response_model_json2 = turn_event_generative_ai_called_callout_response_model.to_dict() + assert turn_event_generative_ai_called_callout_response_model_json2 == turn_event_generative_ai_called_callout_response_model_json - # Construct a model instance of StatelessMessageContextSkills by calling from_dict on the json representation - stateless_message_context_skills_model = StatelessMessageContextSkills.from_dict(stateless_message_context_skills_model_json) - assert stateless_message_context_skills_model != False - # Construct a model instance of StatelessMessageContextSkills by calling from_dict on the json representation - stateless_message_context_skills_model_dict = StatelessMessageContextSkills.from_dict(stateless_message_context_skills_model_json).__dict__ - stateless_message_context_skills_model2 = StatelessMessageContextSkills(**stateless_message_context_skills_model_dict) +class TestModel_TurnEventGenerativeAICalledCalloutSearch: + """ + Test Class for TurnEventGenerativeAICalledCalloutSearch + """ + + def test_turn_event_generative_ai_called_callout_search_serialization(self): + """ + Test serialization/deserialization for TurnEventGenerativeAICalledCalloutSearch + """ + + # Construct dict forms of any model objects needed in order to build this model. + + turn_event_generative_ai_called_callout_request_model = {} # TurnEventGenerativeAICalledCalloutRequest + turn_event_generative_ai_called_callout_request_model['method'] = 'GET' + turn_event_generative_ai_called_callout_request_model['url'] = 'testString' + turn_event_generative_ai_called_callout_request_model['port'] = 'testString' + turn_event_generative_ai_called_callout_request_model['path'] = 'testString' + turn_event_generative_ai_called_callout_request_model['query_parameters'] = 'testString' + turn_event_generative_ai_called_callout_request_model['headers'] = {'anyKey': 'anyValue'} + turn_event_generative_ai_called_callout_request_model['body'] = {'anyKey': 'anyValue'} + + turn_event_generative_ai_called_callout_response_model = {} # TurnEventGenerativeAICalledCalloutResponse + turn_event_generative_ai_called_callout_response_model['body'] = 'testString' + turn_event_generative_ai_called_callout_response_model['status_code'] = 38 + + # Construct a json representation of a TurnEventGenerativeAICalledCalloutSearch model + turn_event_generative_ai_called_callout_search_model_json = {} + turn_event_generative_ai_called_callout_search_model_json['engine'] = 'testString' + turn_event_generative_ai_called_callout_search_model_json['index'] = 'testString' + turn_event_generative_ai_called_callout_search_model_json['query'] = 'testString' + turn_event_generative_ai_called_callout_search_model_json['request'] = turn_event_generative_ai_called_callout_request_model + turn_event_generative_ai_called_callout_search_model_json['response'] = turn_event_generative_ai_called_callout_response_model + + # Construct a model instance of TurnEventGenerativeAICalledCalloutSearch by calling from_dict on the json representation + turn_event_generative_ai_called_callout_search_model = TurnEventGenerativeAICalledCalloutSearch.from_dict(turn_event_generative_ai_called_callout_search_model_json) + assert turn_event_generative_ai_called_callout_search_model != False + + # Construct a model instance of TurnEventGenerativeAICalledCalloutSearch by calling from_dict on the json representation + turn_event_generative_ai_called_callout_search_model_dict = TurnEventGenerativeAICalledCalloutSearch.from_dict(turn_event_generative_ai_called_callout_search_model_json).__dict__ + turn_event_generative_ai_called_callout_search_model2 = TurnEventGenerativeAICalledCalloutSearch(**turn_event_generative_ai_called_callout_search_model_dict) # Verify the model instances are equivalent - assert stateless_message_context_skills_model == stateless_message_context_skills_model2 + assert turn_event_generative_ai_called_callout_search_model == turn_event_generative_ai_called_callout_search_model2 # Convert model instance back to dict and verify no loss of data - stateless_message_context_skills_model_json2 = stateless_message_context_skills_model.to_dict() - assert stateless_message_context_skills_model_json2 == stateless_message_context_skills_model_json + turn_event_generative_ai_called_callout_search_model_json2 = turn_event_generative_ai_called_callout_search_model.to_dict() + assert turn_event_generative_ai_called_callout_search_model_json2 == turn_event_generative_ai_called_callout_search_model_json -class TestModel_StatelessMessageContextSkillsActionsSkill: +class TestModel_TurnEventGenerativeAICalledMetrics: """ - Test Class for StatelessMessageContextSkillsActionsSkill + Test Class for TurnEventGenerativeAICalledMetrics """ - def test_stateless_message_context_skills_actions_skill_serialization(self): + def test_turn_event_generative_ai_called_metrics_serialization(self): """ - Test serialization/deserialization for StatelessMessageContextSkillsActionsSkill + Test serialization/deserialization for TurnEventGenerativeAICalledMetrics """ - # Construct dict forms of any model objects needed in order to build this model. - - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' - - # Construct a json representation of a StatelessMessageContextSkillsActionsSkill model - stateless_message_context_skills_actions_skill_model_json = {} - stateless_message_context_skills_actions_skill_model_json['user_defined'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model_json['system'] = message_context_skill_system_model - stateless_message_context_skills_actions_skill_model_json['action_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model_json['skill_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model_json['private_action_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model_json['private_skill_variables'] = {'anyKey': 'anyValue'} + # Construct a json representation of a TurnEventGenerativeAICalledMetrics model + turn_event_generative_ai_called_metrics_model_json = {} + turn_event_generative_ai_called_metrics_model_json['search_time_ms'] = 'unknown type: float' + turn_event_generative_ai_called_metrics_model_json['answer_generation_time_ms'] = 'unknown type: float' + turn_event_generative_ai_called_metrics_model_json['total_time_ms'] = 'unknown type: float' - # Construct a model instance of StatelessMessageContextSkillsActionsSkill by calling from_dict on the json representation - stateless_message_context_skills_actions_skill_model = StatelessMessageContextSkillsActionsSkill.from_dict(stateless_message_context_skills_actions_skill_model_json) - assert stateless_message_context_skills_actions_skill_model != False + # Construct a model instance of TurnEventGenerativeAICalledMetrics by calling from_dict on the json representation + turn_event_generative_ai_called_metrics_model = TurnEventGenerativeAICalledMetrics.from_dict(turn_event_generative_ai_called_metrics_model_json) + assert turn_event_generative_ai_called_metrics_model != False - # Construct a model instance of StatelessMessageContextSkillsActionsSkill by calling from_dict on the json representation - stateless_message_context_skills_actions_skill_model_dict = StatelessMessageContextSkillsActionsSkill.from_dict(stateless_message_context_skills_actions_skill_model_json).__dict__ - stateless_message_context_skills_actions_skill_model2 = StatelessMessageContextSkillsActionsSkill(**stateless_message_context_skills_actions_skill_model_dict) + # Construct a model instance of TurnEventGenerativeAICalledMetrics by calling from_dict on the json representation + turn_event_generative_ai_called_metrics_model_dict = TurnEventGenerativeAICalledMetrics.from_dict(turn_event_generative_ai_called_metrics_model_json).__dict__ + turn_event_generative_ai_called_metrics_model2 = TurnEventGenerativeAICalledMetrics(**turn_event_generative_ai_called_metrics_model_dict) # Verify the model instances are equivalent - assert stateless_message_context_skills_actions_skill_model == stateless_message_context_skills_actions_skill_model2 + assert turn_event_generative_ai_called_metrics_model == turn_event_generative_ai_called_metrics_model2 # Convert model instance back to dict and verify no loss of data - stateless_message_context_skills_actions_skill_model_json2 = stateless_message_context_skills_actions_skill_model.to_dict() - assert stateless_message_context_skills_actions_skill_model_json2 == stateless_message_context_skills_actions_skill_model_json + turn_event_generative_ai_called_metrics_model_json2 = turn_event_generative_ai_called_metrics_model.to_dict() + assert turn_event_generative_ai_called_metrics_model_json2 == turn_event_generative_ai_called_metrics_model_json -class TestModel_StatelessMessageInput: +class TestModel_TurnEventNodeSource: """ - Test Class for StatelessMessageInput + Test Class for TurnEventNodeSource """ - def test_stateless_message_input_serialization(self): + def test_turn_event_node_source_serialization(self): """ - Test serialization/deserialization for StatelessMessageInput + Test serialization/deserialization for TurnEventNodeSource """ - # Construct dict forms of any model objects needed in order to build this model. - - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' - - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] - - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' + # Construct a json representation of a TurnEventNodeSource model + turn_event_node_source_model_json = {} + turn_event_node_source_model_json['type'] = 'dialog_node' + turn_event_node_source_model_json['dialog_node'] = 'testString' + turn_event_node_source_model_json['title'] = 'testString' + turn_event_node_source_model_json['condition'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 + # Construct a model instance of TurnEventNodeSource by calling from_dict on the json representation + turn_event_node_source_model = TurnEventNodeSource.from_dict(turn_event_node_source_model_json) + assert turn_event_node_source_model != False - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + # Construct a model instance of TurnEventNodeSource by calling from_dict on the json representation + turn_event_node_source_model_dict = TurnEventNodeSource.from_dict(turn_event_node_source_model_json).__dict__ + turn_event_node_source_model2 = TurnEventNodeSource(**turn_event_node_source_model_dict) - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + # Verify the model instances are equivalent + assert turn_event_node_source_model == turn_event_node_source_model2 - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + # Convert model instance back to dict and verify no loss of data + turn_event_node_source_model_json2 = turn_event_node_source_model.to_dict() + assert turn_event_node_source_model_json2 == turn_event_node_source_model_json - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True +class TestModel_TurnEventSearchError: + """ + Test Class for TurnEventSearchError + """ - stateless_message_input_options_model = {} # StatelessMessageInputOptions - stateless_message_input_options_model['restart'] = False - stateless_message_input_options_model['alternate_intents'] = False - stateless_message_input_options_model['async_callout'] = False - stateless_message_input_options_model['spelling'] = message_input_options_spelling_model - stateless_message_input_options_model['debug'] = False + def test_turn_event_search_error_serialization(self): + """ + Test serialization/deserialization for TurnEventSearchError + """ - # Construct a json representation of a StatelessMessageInput model - stateless_message_input_model_json = {} - stateless_message_input_model_json['message_type'] = 'text' - stateless_message_input_model_json['text'] = 'testString' - stateless_message_input_model_json['intents'] = [runtime_intent_model] - stateless_message_input_model_json['entities'] = [runtime_entity_model] - stateless_message_input_model_json['suggestion_id'] = 'testString' - stateless_message_input_model_json['attachments'] = [message_input_attachment_model] - stateless_message_input_model_json['analytics'] = request_analytics_model - stateless_message_input_model_json['options'] = stateless_message_input_options_model + # Construct a json representation of a TurnEventSearchError model + turn_event_search_error_model_json = {} + turn_event_search_error_model_json['message'] = 'testString' - # Construct a model instance of StatelessMessageInput by calling from_dict on the json representation - stateless_message_input_model = StatelessMessageInput.from_dict(stateless_message_input_model_json) - assert stateless_message_input_model != False + # Construct a model instance of TurnEventSearchError by calling from_dict on the json representation + turn_event_search_error_model = TurnEventSearchError.from_dict(turn_event_search_error_model_json) + assert turn_event_search_error_model != False - # Construct a model instance of StatelessMessageInput by calling from_dict on the json representation - stateless_message_input_model_dict = StatelessMessageInput.from_dict(stateless_message_input_model_json).__dict__ - stateless_message_input_model2 = StatelessMessageInput(**stateless_message_input_model_dict) + # Construct a model instance of TurnEventSearchError by calling from_dict on the json representation + turn_event_search_error_model_dict = TurnEventSearchError.from_dict(turn_event_search_error_model_json).__dict__ + turn_event_search_error_model2 = TurnEventSearchError(**turn_event_search_error_model_dict) # Verify the model instances are equivalent - assert stateless_message_input_model == stateless_message_input_model2 + assert turn_event_search_error_model == turn_event_search_error_model2 # Convert model instance back to dict and verify no loss of data - stateless_message_input_model_json2 = stateless_message_input_model.to_dict() - assert stateless_message_input_model_json2 == stateless_message_input_model_json + turn_event_search_error_model_json2 = turn_event_search_error_model.to_dict() + assert turn_event_search_error_model_json2 == turn_event_search_error_model_json -class TestModel_StatelessMessageInputOptions: +class TestModel_TurnEventStepSource: """ - Test Class for StatelessMessageInputOptions + Test Class for TurnEventStepSource """ - def test_stateless_message_input_options_serialization(self): + def test_turn_event_step_source_serialization(self): """ - Test serialization/deserialization for StatelessMessageInputOptions + Test serialization/deserialization for TurnEventStepSource """ - # Construct dict forms of any model objects needed in order to build this model. - - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True - - # Construct a json representation of a StatelessMessageInputOptions model - stateless_message_input_options_model_json = {} - stateless_message_input_options_model_json['restart'] = False - stateless_message_input_options_model_json['alternate_intents'] = False - stateless_message_input_options_model_json['async_callout'] = False - stateless_message_input_options_model_json['spelling'] = message_input_options_spelling_model - stateless_message_input_options_model_json['debug'] = False + # Construct a json representation of a TurnEventStepSource model + turn_event_step_source_model_json = {} + turn_event_step_source_model_json['type'] = 'step' + turn_event_step_source_model_json['action'] = 'testString' + turn_event_step_source_model_json['action_title'] = 'testString' + turn_event_step_source_model_json['step'] = 'testString' + turn_event_step_source_model_json['is_ai_guided'] = True + turn_event_step_source_model_json['is_skill_based'] = True - # Construct a model instance of StatelessMessageInputOptions by calling from_dict on the json representation - stateless_message_input_options_model = StatelessMessageInputOptions.from_dict(stateless_message_input_options_model_json) - assert stateless_message_input_options_model != False + # Construct a model instance of TurnEventStepSource by calling from_dict on the json representation + turn_event_step_source_model = TurnEventStepSource.from_dict(turn_event_step_source_model_json) + assert turn_event_step_source_model != False - # Construct a model instance of StatelessMessageInputOptions by calling from_dict on the json representation - stateless_message_input_options_model_dict = StatelessMessageInputOptions.from_dict(stateless_message_input_options_model_json).__dict__ - stateless_message_input_options_model2 = StatelessMessageInputOptions(**stateless_message_input_options_model_dict) + # Construct a model instance of TurnEventStepSource by calling from_dict on the json representation + turn_event_step_source_model_dict = TurnEventStepSource.from_dict(turn_event_step_source_model_json).__dict__ + turn_event_step_source_model2 = TurnEventStepSource(**turn_event_step_source_model_dict) # Verify the model instances are equivalent - assert stateless_message_input_options_model == stateless_message_input_options_model2 + assert turn_event_step_source_model == turn_event_step_source_model2 # Convert model instance back to dict and verify no loss of data - stateless_message_input_options_model_json2 = stateless_message_input_options_model.to_dict() - assert stateless_message_input_options_model_json2 == stateless_message_input_options_model_json + turn_event_step_source_model_json2 = turn_event_step_source_model.to_dict() + assert turn_event_step_source_model_json2 == turn_event_step_source_model_json -class TestModel_StatelessMessageResponse: +class TestModel_UpdateEnvironmentOrchestration: """ - Test Class for StatelessMessageResponse + Test Class for UpdateEnvironmentOrchestration """ - def test_stateless_message_response_serialization(self): + def test_update_environment_orchestration_serialization(self): """ - Test serialization/deserialization for StatelessMessageResponse + Test serialization/deserialization for UpdateEnvironmentOrchestration """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a UpdateEnvironmentOrchestration model + update_environment_orchestration_model_json = {} + update_environment_orchestration_model_json['search_skill_fallback'] = True - response_generic_channel_model = {} # ResponseGenericChannel - response_generic_channel_model['channel'] = 'testString' + # Construct a model instance of UpdateEnvironmentOrchestration by calling from_dict on the json representation + update_environment_orchestration_model = UpdateEnvironmentOrchestration.from_dict(update_environment_orchestration_model_json) + assert update_environment_orchestration_model != False - runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeText - runtime_response_generic_model['response_type'] = 'text' - runtime_response_generic_model['text'] = 'testString' - runtime_response_generic_model['channels'] = [response_generic_channel_model] + # Construct a model instance of UpdateEnvironmentOrchestration by calling from_dict on the json representation + update_environment_orchestration_model_dict = UpdateEnvironmentOrchestration.from_dict(update_environment_orchestration_model_json).__dict__ + update_environment_orchestration_model2 = UpdateEnvironmentOrchestration(**update_environment_orchestration_model_dict) - runtime_intent_model = {} # RuntimeIntent - runtime_intent_model['intent'] = 'testString' - runtime_intent_model['confidence'] = 72.5 - runtime_intent_model['skill'] = 'testString' + # Verify the model instances are equivalent + assert update_environment_orchestration_model == update_environment_orchestration_model2 - capture_group_model = {} # CaptureGroup - capture_group_model['group'] = 'testString' - capture_group_model['location'] = [38] + # Convert model instance back to dict and verify no loss of data + update_environment_orchestration_model_json2 = update_environment_orchestration_model.to_dict() + assert update_environment_orchestration_model_json2 == update_environment_orchestration_model_json - runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation - runtime_entity_interpretation_model['calendar_type'] = 'testString' - runtime_entity_interpretation_model['datetime_link'] = 'testString' - runtime_entity_interpretation_model['festival'] = 'testString' - runtime_entity_interpretation_model['granularity'] = 'day' - runtime_entity_interpretation_model['range_link'] = 'testString' - runtime_entity_interpretation_model['range_modifier'] = 'testString' - runtime_entity_interpretation_model['relative_day'] = 72.5 - runtime_entity_interpretation_model['relative_month'] = 72.5 - runtime_entity_interpretation_model['relative_week'] = 72.5 - runtime_entity_interpretation_model['relative_weekend'] = 72.5 - runtime_entity_interpretation_model['relative_year'] = 72.5 - runtime_entity_interpretation_model['specific_day'] = 72.5 - runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' - runtime_entity_interpretation_model['specific_month'] = 72.5 - runtime_entity_interpretation_model['specific_quarter'] = 72.5 - runtime_entity_interpretation_model['specific_year'] = 72.5 - runtime_entity_interpretation_model['numeric_value'] = 72.5 - runtime_entity_interpretation_model['subtype'] = 'testString' - runtime_entity_interpretation_model['part_of_day'] = 'testString' - runtime_entity_interpretation_model['relative_hour'] = 72.5 - runtime_entity_interpretation_model['relative_minute'] = 72.5 - runtime_entity_interpretation_model['relative_second'] = 72.5 - runtime_entity_interpretation_model['specific_hour'] = 72.5 - runtime_entity_interpretation_model['specific_minute'] = 72.5 - runtime_entity_interpretation_model['specific_second'] = 72.5 - runtime_entity_interpretation_model['timezone'] = 'testString' - runtime_entity_alternative_model = {} # RuntimeEntityAlternative - runtime_entity_alternative_model['value'] = 'testString' - runtime_entity_alternative_model['confidence'] = 72.5 +class TestModel_UpdateEnvironmentReleaseReference: + """ + Test Class for UpdateEnvironmentReleaseReference + """ - runtime_entity_role_model = {} # RuntimeEntityRole - runtime_entity_role_model['type'] = 'date_from' + def test_update_environment_release_reference_serialization(self): + """ + Test serialization/deserialization for UpdateEnvironmentReleaseReference + """ - runtime_entity_model = {} # RuntimeEntity - runtime_entity_model['entity'] = 'testString' - runtime_entity_model['location'] = [38] - runtime_entity_model['value'] = 'testString' - runtime_entity_model['confidence'] = 72.5 - runtime_entity_model['groups'] = [capture_group_model] - runtime_entity_model['interpretation'] = runtime_entity_interpretation_model - runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] - runtime_entity_model['role'] = runtime_entity_role_model - runtime_entity_model['skill'] = 'testString' + # Construct a json representation of a UpdateEnvironmentReleaseReference model + update_environment_release_reference_model_json = {} + update_environment_release_reference_model_json['release'] = 'testString' - dialog_node_action_model = {} # DialogNodeAction - dialog_node_action_model['name'] = 'testString' - dialog_node_action_model['type'] = 'client' - dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} - dialog_node_action_model['result_variable'] = 'testString' - dialog_node_action_model['credentials'] = 'testString' + # Construct a model instance of UpdateEnvironmentReleaseReference by calling from_dict on the json representation + update_environment_release_reference_model = UpdateEnvironmentReleaseReference.from_dict(update_environment_release_reference_model_json) + assert update_environment_release_reference_model != False - dialog_node_visited_model = {} # DialogNodeVisited - dialog_node_visited_model['dialog_node'] = 'testString' - dialog_node_visited_model['title'] = 'testString' - dialog_node_visited_model['conditions'] = 'testString' + # Construct a model instance of UpdateEnvironmentReleaseReference by calling from_dict on the json representation + update_environment_release_reference_model_dict = UpdateEnvironmentReleaseReference.from_dict(update_environment_release_reference_model_json).__dict__ + update_environment_release_reference_model2 = UpdateEnvironmentReleaseReference(**update_environment_release_reference_model_dict) - log_message_source_model = {} # LogMessageSourceDialogNode - log_message_source_model['type'] = 'dialog_node' - log_message_source_model['dialog_node'] = 'testString' + # Verify the model instances are equivalent + assert update_environment_release_reference_model == update_environment_release_reference_model2 - dialog_log_message_model = {} # DialogLogMessage - dialog_log_message_model['level'] = 'info' - dialog_log_message_model['message'] = 'testString' - dialog_log_message_model['code'] = 'testString' - dialog_log_message_model['source'] = log_message_source_model + # Convert model instance back to dict and verify no loss of data + update_environment_release_reference_model_json2 = update_environment_release_reference_model.to_dict() + assert update_environment_release_reference_model_json2 == update_environment_release_reference_model_json - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' - message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited - message_output_debug_turn_event_model['event'] = 'action_visited' - message_output_debug_turn_event_model['source'] = turn_event_action_source_model - message_output_debug_turn_event_model['action_start_time'] = 'testString' - message_output_debug_turn_event_model['condition_type'] = 'user_defined' - message_output_debug_turn_event_model['reason'] = 'intent' - message_output_debug_turn_event_model['result_variable'] = 'testString' +class TestModel_CompleteItem: + """ + Test Class for CompleteItem + """ - message_output_debug_model = {} # MessageOutputDebug - message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] - message_output_debug_model['log_messages'] = [dialog_log_message_model] - message_output_debug_model['branch_exited'] = True - message_output_debug_model['branch_exited_reason'] = 'completed' - message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + def test_complete_item_serialization(self): + """ + Test serialization/deserialization for CompleteItem + """ - message_output_spelling_model = {} # MessageOutputSpelling - message_output_spelling_model['text'] = 'testString' - message_output_spelling_model['original_text'] = 'testString' - message_output_spelling_model['suggested_text'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - message_output_model = {} # MessageOutput - message_output_model['generic'] = [runtime_response_generic_model] - message_output_model['intents'] = [runtime_intent_model] - message_output_model['entities'] = [runtime_entity_model] - message_output_model['actions'] = [dialog_node_action_model] - message_output_model['debug'] = message_output_debug_model - message_output_model['user_defined'] = {'anyKey': 'anyValue'} - message_output_model['spelling'] = message_output_spelling_model + metadata_model = {} # Metadata + metadata_model['id'] = 38 - message_context_global_system_model = {} # MessageContextGlobalSystem - message_context_global_system_model['timezone'] = 'testString' - message_context_global_system_model['user_id'] = 'testString' - message_context_global_system_model['turn_count'] = 38 - message_context_global_system_model['locale'] = 'en-us' - message_context_global_system_model['reference_time'] = 'testString' - message_context_global_system_model['session_start_time'] = 'testString' - message_context_global_system_model['state'] = 'testString' - message_context_global_system_model['skip_user_input'] = True + # Construct a json representation of a CompleteItem model + complete_item_model_json = {} + complete_item_model_json['streaming_metadata'] = metadata_model - stateless_message_context_global_model = {} # StatelessMessageContextGlobal - stateless_message_context_global_model['system'] = message_context_global_system_model - stateless_message_context_global_model['session_id'] = 'testString' + # Construct a model instance of CompleteItem by calling from_dict on the json representation + complete_item_model = CompleteItem.from_dict(complete_item_model_json) + assert complete_item_model != False - message_context_skill_system_model = {} # MessageContextSkillSystem - message_context_skill_system_model['state'] = 'testString' - message_context_skill_system_model['foo'] = 'testString' + # Construct a model instance of CompleteItem by calling from_dict on the json representation + complete_item_model_dict = CompleteItem.from_dict(complete_item_model_json).__dict__ + complete_item_model2 = CompleteItem(**complete_item_model_dict) - message_context_dialog_skill_model = {} # MessageContextDialogSkill - message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} - message_context_dialog_skill_model['system'] = message_context_skill_system_model + # Verify the model instances are equivalent + assert complete_item_model == complete_item_model2 - stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill - stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model - stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} - stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + # Convert model instance back to dict and verify no loss of data + complete_item_model_json2 = complete_item_model.to_dict() + assert complete_item_model_json2 == complete_item_model_json - stateless_message_context_skills_model = {} # StatelessMessageContextSkills - stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model - stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model - stateless_message_context_model = {} # StatelessMessageContext - stateless_message_context_model['global'] = stateless_message_context_global_model - stateless_message_context_model['skills'] = stateless_message_context_skills_model - stateless_message_context_model['integrations'] = {'anyKey': 'anyValue'} +class TestModel_GenerativeAITaskContentGroundedAnswering: + """ + Test Class for GenerativeAITaskContentGroundedAnswering + """ - message_input_attachment_model = {} # MessageInputAttachment - message_input_attachment_model['url'] = 'testString' - message_input_attachment_model['media_type'] = 'testString' + def test_generative_ai_task_content_grounded_answering_serialization(self): + """ + Test serialization/deserialization for GenerativeAITaskContentGroundedAnswering + """ - request_analytics_model = {} # RequestAnalytics - request_analytics_model['browser'] = 'testString' - request_analytics_model['device'] = 'testString' - request_analytics_model['pageUrl'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - message_input_options_spelling_model = {} # MessageInputOptionsSpelling - message_input_options_spelling_model['suggestions'] = True - message_input_options_spelling_model['auto_correct'] = True + generative_ai_task_confidence_scores_model = {} # GenerativeAITaskConfidenceScores + generative_ai_task_confidence_scores_model['pre_gen'] = 72.5 + generative_ai_task_confidence_scores_model['pre_gen_threshold'] = 72.5 + generative_ai_task_confidence_scores_model['post_gen'] = 72.5 + generative_ai_task_confidence_scores_model['post_gen_threshold'] = 72.5 + + # Construct a json representation of a GenerativeAITaskContentGroundedAnswering model + generative_ai_task_content_grounded_answering_model_json = {} + generative_ai_task_content_grounded_answering_model_json['task'] = 'content_grounded_answering' + generative_ai_task_content_grounded_answering_model_json['is_idk_response'] = True + generative_ai_task_content_grounded_answering_model_json['is_hap_detected'] = True + generative_ai_task_content_grounded_answering_model_json['confidence_scores'] = generative_ai_task_confidence_scores_model + generative_ai_task_content_grounded_answering_model_json['original_response'] = 'testString' + generative_ai_task_content_grounded_answering_model_json['inferred_query'] = 'testString' + + # Construct a model instance of GenerativeAITaskContentGroundedAnswering by calling from_dict on the json representation + generative_ai_task_content_grounded_answering_model = GenerativeAITaskContentGroundedAnswering.from_dict(generative_ai_task_content_grounded_answering_model_json) + assert generative_ai_task_content_grounded_answering_model != False + + # Construct a model instance of GenerativeAITaskContentGroundedAnswering by calling from_dict on the json representation + generative_ai_task_content_grounded_answering_model_dict = GenerativeAITaskContentGroundedAnswering.from_dict(generative_ai_task_content_grounded_answering_model_json).__dict__ + generative_ai_task_content_grounded_answering_model2 = GenerativeAITaskContentGroundedAnswering(**generative_ai_task_content_grounded_answering_model_dict) - message_input_options_model = {} # MessageInputOptions - message_input_options_model['restart'] = False - message_input_options_model['alternate_intents'] = False - message_input_options_model['async_callout'] = False - message_input_options_model['spelling'] = message_input_options_spelling_model - message_input_options_model['debug'] = False - message_input_options_model['return_context'] = False - message_input_options_model['export'] = False + # Verify the model instances are equivalent + assert generative_ai_task_content_grounded_answering_model == generative_ai_task_content_grounded_answering_model2 - message_input_model = {} # MessageInput - message_input_model['message_type'] = 'text' - message_input_model['text'] = 'testString' - message_input_model['intents'] = [runtime_intent_model] - message_input_model['entities'] = [runtime_entity_model] - message_input_model['suggestion_id'] = 'testString' - message_input_model['attachments'] = [message_input_attachment_model] - message_input_model['analytics'] = request_analytics_model - message_input_model['options'] = message_input_options_model + # Convert model instance back to dict and verify no loss of data + generative_ai_task_content_grounded_answering_model_json2 = generative_ai_task_content_grounded_answering_model.to_dict() + assert generative_ai_task_content_grounded_answering_model_json2 == generative_ai_task_content_grounded_answering_model_json - # Construct a json representation of a StatelessMessageResponse model - stateless_message_response_model_json = {} - stateless_message_response_model_json['output'] = message_output_model - stateless_message_response_model_json['context'] = stateless_message_context_model - stateless_message_response_model_json['masked_output'] = message_output_model - stateless_message_response_model_json['masked_input'] = message_input_model - stateless_message_response_model_json['user_id'] = 'testString' - # Construct a model instance of StatelessMessageResponse by calling from_dict on the json representation - stateless_message_response_model = StatelessMessageResponse.from_dict(stateless_message_response_model_json) - assert stateless_message_response_model != False +class TestModel_GenerativeAITaskGeneralPurposeAnswering: + """ + Test Class for GenerativeAITaskGeneralPurposeAnswering + """ - # Construct a model instance of StatelessMessageResponse by calling from_dict on the json representation - stateless_message_response_model_dict = StatelessMessageResponse.from_dict(stateless_message_response_model_json).__dict__ - stateless_message_response_model2 = StatelessMessageResponse(**stateless_message_response_model_dict) + def test_generative_ai_task_general_purpose_answering_serialization(self): + """ + Test serialization/deserialization for GenerativeAITaskGeneralPurposeAnswering + """ + + # Construct a json representation of a GenerativeAITaskGeneralPurposeAnswering model + generative_ai_task_general_purpose_answering_model_json = {} + generative_ai_task_general_purpose_answering_model_json['task'] = 'general_purpose_answering' + generative_ai_task_general_purpose_answering_model_json['is_idk_response'] = True + generative_ai_task_general_purpose_answering_model_json['is_hap_detected'] = True + + # Construct a model instance of GenerativeAITaskGeneralPurposeAnswering by calling from_dict on the json representation + generative_ai_task_general_purpose_answering_model = GenerativeAITaskGeneralPurposeAnswering.from_dict(generative_ai_task_general_purpose_answering_model_json) + assert generative_ai_task_general_purpose_answering_model != False + + # Construct a model instance of GenerativeAITaskGeneralPurposeAnswering by calling from_dict on the json representation + generative_ai_task_general_purpose_answering_model_dict = GenerativeAITaskGeneralPurposeAnswering.from_dict(generative_ai_task_general_purpose_answering_model_json).__dict__ + generative_ai_task_general_purpose_answering_model2 = GenerativeAITaskGeneralPurposeAnswering(**generative_ai_task_general_purpose_answering_model_dict) # Verify the model instances are equivalent - assert stateless_message_response_model == stateless_message_response_model2 + assert generative_ai_task_general_purpose_answering_model == generative_ai_task_general_purpose_answering_model2 # Convert model instance back to dict and verify no loss of data - stateless_message_response_model_json2 = stateless_message_response_model.to_dict() - assert stateless_message_response_model_json2 == stateless_message_response_model_json + generative_ai_task_general_purpose_answering_model_json2 = generative_ai_task_general_purpose_answering_model.to_dict() + assert generative_ai_task_general_purpose_answering_model_json2 == generative_ai_task_general_purpose_answering_model_json -class TestModel_StatusError: +class TestModel_LogMessageSourceAction: """ - Test Class for StatusError + Test Class for LogMessageSourceAction """ - def test_status_error_serialization(self): + def test_log_message_source_action_serialization(self): """ - Test serialization/deserialization for StatusError + Test serialization/deserialization for LogMessageSourceAction """ - # Construct a json representation of a StatusError model - status_error_model_json = {} - status_error_model_json['message'] = 'testString' + # Construct a json representation of a LogMessageSourceAction model + log_message_source_action_model_json = {} + log_message_source_action_model_json['type'] = 'action' + log_message_source_action_model_json['action'] = 'testString' - # Construct a model instance of StatusError by calling from_dict on the json representation - status_error_model = StatusError.from_dict(status_error_model_json) - assert status_error_model != False + # Construct a model instance of LogMessageSourceAction by calling from_dict on the json representation + log_message_source_action_model = LogMessageSourceAction.from_dict(log_message_source_action_model_json) + assert log_message_source_action_model != False - # Construct a model instance of StatusError by calling from_dict on the json representation - status_error_model_dict = StatusError.from_dict(status_error_model_json).__dict__ - status_error_model2 = StatusError(**status_error_model_dict) + # Construct a model instance of LogMessageSourceAction by calling from_dict on the json representation + log_message_source_action_model_dict = LogMessageSourceAction.from_dict(log_message_source_action_model_json).__dict__ + log_message_source_action_model2 = LogMessageSourceAction(**log_message_source_action_model_dict) # Verify the model instances are equivalent - assert status_error_model == status_error_model2 + assert log_message_source_action_model == log_message_source_action_model2 # Convert model instance back to dict and verify no loss of data - status_error_model_json2 = status_error_model.to_dict() - assert status_error_model_json2 == status_error_model_json + log_message_source_action_model_json2 = log_message_source_action_model.to_dict() + assert log_message_source_action_model_json2 == log_message_source_action_model_json -class TestModel_TurnEventActionSource: +class TestModel_LogMessageSourceDialogNode: """ - Test Class for TurnEventActionSource + Test Class for LogMessageSourceDialogNode """ - def test_turn_event_action_source_serialization(self): + def test_log_message_source_dialog_node_serialization(self): """ - Test serialization/deserialization for TurnEventActionSource + Test serialization/deserialization for LogMessageSourceDialogNode """ - # Construct a json representation of a TurnEventActionSource model - turn_event_action_source_model_json = {} - turn_event_action_source_model_json['type'] = 'action' - turn_event_action_source_model_json['action'] = 'testString' - turn_event_action_source_model_json['action_title'] = 'testString' - turn_event_action_source_model_json['condition'] = 'testString' + # Construct a json representation of a LogMessageSourceDialogNode model + log_message_source_dialog_node_model_json = {} + log_message_source_dialog_node_model_json['type'] = 'dialog_node' + log_message_source_dialog_node_model_json['dialog_node'] = 'testString' - # Construct a model instance of TurnEventActionSource by calling from_dict on the json representation - turn_event_action_source_model = TurnEventActionSource.from_dict(turn_event_action_source_model_json) - assert turn_event_action_source_model != False + # Construct a model instance of LogMessageSourceDialogNode by calling from_dict on the json representation + log_message_source_dialog_node_model = LogMessageSourceDialogNode.from_dict(log_message_source_dialog_node_model_json) + assert log_message_source_dialog_node_model != False - # Construct a model instance of TurnEventActionSource by calling from_dict on the json representation - turn_event_action_source_model_dict = TurnEventActionSource.from_dict(turn_event_action_source_model_json).__dict__ - turn_event_action_source_model2 = TurnEventActionSource(**turn_event_action_source_model_dict) + # Construct a model instance of LogMessageSourceDialogNode by calling from_dict on the json representation + log_message_source_dialog_node_model_dict = LogMessageSourceDialogNode.from_dict(log_message_source_dialog_node_model_json).__dict__ + log_message_source_dialog_node_model2 = LogMessageSourceDialogNode(**log_message_source_dialog_node_model_dict) # Verify the model instances are equivalent - assert turn_event_action_source_model == turn_event_action_source_model2 + assert log_message_source_dialog_node_model == log_message_source_dialog_node_model2 # Convert model instance back to dict and verify no loss of data - turn_event_action_source_model_json2 = turn_event_action_source_model.to_dict() - assert turn_event_action_source_model_json2 == turn_event_action_source_model_json + log_message_source_dialog_node_model_json2 = log_message_source_dialog_node_model.to_dict() + assert log_message_source_dialog_node_model_json2 == log_message_source_dialog_node_model_json -class TestModel_TurnEventCalloutCallout: +class TestModel_LogMessageSourceHandler: """ - Test Class for TurnEventCalloutCallout + Test Class for LogMessageSourceHandler """ - def test_turn_event_callout_callout_serialization(self): + def test_log_message_source_handler_serialization(self): """ - Test serialization/deserialization for TurnEventCalloutCallout + Test serialization/deserialization for LogMessageSourceHandler """ - # Construct dict forms of any model objects needed in order to build this model. + # Construct a json representation of a LogMessageSourceHandler model + log_message_source_handler_model_json = {} + log_message_source_handler_model_json['type'] = 'handler' + log_message_source_handler_model_json['action'] = 'testString' + log_message_source_handler_model_json['step'] = 'testString' + log_message_source_handler_model_json['handler'] = 'testString' - turn_event_callout_callout_request_model = {} # TurnEventCalloutCalloutRequest - turn_event_callout_callout_request_model['method'] = 'get' - turn_event_callout_callout_request_model['url'] = 'testString' - turn_event_callout_callout_request_model['path'] = 'testString' - turn_event_callout_callout_request_model['query_parameters'] = 'testString' - turn_event_callout_callout_request_model['headers'] = {'anyKey': 'anyValue'} - turn_event_callout_callout_request_model['body'] = {'anyKey': 'anyValue'} + # Construct a model instance of LogMessageSourceHandler by calling from_dict on the json representation + log_message_source_handler_model = LogMessageSourceHandler.from_dict(log_message_source_handler_model_json) + assert log_message_source_handler_model != False - turn_event_callout_callout_response_model = {} # TurnEventCalloutCalloutResponse - turn_event_callout_callout_response_model['body'] = 'testString' - turn_event_callout_callout_response_model['status_code'] = 38 - turn_event_callout_callout_response_model['last_event'] = {'anyKey': 'anyValue'} + # Construct a model instance of LogMessageSourceHandler by calling from_dict on the json representation + log_message_source_handler_model_dict = LogMessageSourceHandler.from_dict(log_message_source_handler_model_json).__dict__ + log_message_source_handler_model2 = LogMessageSourceHandler(**log_message_source_handler_model_dict) - # Construct a json representation of a TurnEventCalloutCallout model - turn_event_callout_callout_model_json = {} - turn_event_callout_callout_model_json['type'] = 'integration_interaction' - turn_event_callout_callout_model_json['internal'] = {'anyKey': 'anyValue'} - turn_event_callout_callout_model_json['result_variable'] = 'testString' - turn_event_callout_callout_model_json['request'] = turn_event_callout_callout_request_model - turn_event_callout_callout_model_json['response'] = turn_event_callout_callout_response_model + # Verify the model instances are equivalent + assert log_message_source_handler_model == log_message_source_handler_model2 - # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation - turn_event_callout_callout_model = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json) - assert turn_event_callout_callout_model != False + # Convert model instance back to dict and verify no loss of data + log_message_source_handler_model_json2 = log_message_source_handler_model.to_dict() + assert log_message_source_handler_model_json2 == log_message_source_handler_model_json - # Construct a model instance of TurnEventCalloutCallout by calling from_dict on the json representation - turn_event_callout_callout_model_dict = TurnEventCalloutCallout.from_dict(turn_event_callout_callout_model_json).__dict__ - turn_event_callout_callout_model2 = TurnEventCalloutCallout(**turn_event_callout_callout_model_dict) + +class TestModel_LogMessageSourceStep: + """ + Test Class for LogMessageSourceStep + """ + + def test_log_message_source_step_serialization(self): + """ + Test serialization/deserialization for LogMessageSourceStep + """ + + # Construct a json representation of a LogMessageSourceStep model + log_message_source_step_model_json = {} + log_message_source_step_model_json['type'] = 'step' + log_message_source_step_model_json['action'] = 'testString' + log_message_source_step_model_json['step'] = 'testString' + + # Construct a model instance of LogMessageSourceStep by calling from_dict on the json representation + log_message_source_step_model = LogMessageSourceStep.from_dict(log_message_source_step_model_json) + assert log_message_source_step_model != False + + # Construct a model instance of LogMessageSourceStep by calling from_dict on the json representation + log_message_source_step_model_dict = LogMessageSourceStep.from_dict(log_message_source_step_model_json).__dict__ + log_message_source_step_model2 = LogMessageSourceStep(**log_message_source_step_model_dict) # Verify the model instances are equivalent - assert turn_event_callout_callout_model == turn_event_callout_callout_model2 + assert log_message_source_step_model == log_message_source_step_model2 # Convert model instance back to dict and verify no loss of data - turn_event_callout_callout_model_json2 = turn_event_callout_callout_model.to_dict() - assert turn_event_callout_callout_model_json2 == turn_event_callout_callout_model_json + log_message_source_step_model_json2 = log_message_source_step_model.to_dict() + assert log_message_source_step_model_json2 == log_message_source_step_model_json -class TestModel_TurnEventCalloutCalloutRequest: +class TestModel_MessageOutputDebugTurnEventTurnEventActionFinished: """ - Test Class for TurnEventCalloutCalloutRequest + Test Class for MessageOutputDebugTurnEventTurnEventActionFinished """ - def test_turn_event_callout_callout_request_serialization(self): + def test_message_output_debug_turn_event_turn_event_action_finished_serialization(self): """ - Test serialization/deserialization for TurnEventCalloutCalloutRequest + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventActionFinished """ - # Construct a json representation of a TurnEventCalloutCalloutRequest model - turn_event_callout_callout_request_model_json = {} - turn_event_callout_callout_request_model_json['method'] = 'get' - turn_event_callout_callout_request_model_json['url'] = 'testString' - turn_event_callout_callout_request_model_json['path'] = 'testString' - turn_event_callout_callout_request_model_json['query_parameters'] = 'testString' - turn_event_callout_callout_request_model_json['headers'] = {'anyKey': 'anyValue'} - turn_event_callout_callout_request_model_json['body'] = {'anyKey': 'anyValue'} + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of TurnEventCalloutCalloutRequest by calling from_dict on the json representation - turn_event_callout_callout_request_model = TurnEventCalloutCalloutRequest.from_dict(turn_event_callout_callout_request_model_json) - assert turn_event_callout_callout_request_model != False + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - # Construct a model instance of TurnEventCalloutCalloutRequest by calling from_dict on the json representation - turn_event_callout_callout_request_model_dict = TurnEventCalloutCalloutRequest.from_dict(turn_event_callout_callout_request_model_json).__dict__ - turn_event_callout_callout_request_model2 = TurnEventCalloutCalloutRequest(**turn_event_callout_callout_request_model_dict) + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventActionFinished model + message_output_debug_turn_event_turn_event_action_finished_model_json = {} + message_output_debug_turn_event_turn_event_action_finished_model_json['event'] = 'action_finished' + message_output_debug_turn_event_turn_event_action_finished_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_action_finished_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_action_finished_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_action_finished_model_json['reason'] = 'all_steps_done' + message_output_debug_turn_event_turn_event_action_finished_model_json['action_variables'] = {'anyKey': 'anyValue'} + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionFinished by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_finished_model = MessageOutputDebugTurnEventTurnEventActionFinished.from_dict(message_output_debug_turn_event_turn_event_action_finished_model_json) + assert message_output_debug_turn_event_turn_event_action_finished_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionFinished by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_finished_model_dict = MessageOutputDebugTurnEventTurnEventActionFinished.from_dict(message_output_debug_turn_event_turn_event_action_finished_model_json).__dict__ + message_output_debug_turn_event_turn_event_action_finished_model2 = MessageOutputDebugTurnEventTurnEventActionFinished(**message_output_debug_turn_event_turn_event_action_finished_model_dict) # Verify the model instances are equivalent - assert turn_event_callout_callout_request_model == turn_event_callout_callout_request_model2 + assert message_output_debug_turn_event_turn_event_action_finished_model == message_output_debug_turn_event_turn_event_action_finished_model2 # Convert model instance back to dict and verify no loss of data - turn_event_callout_callout_request_model_json2 = turn_event_callout_callout_request_model.to_dict() - assert turn_event_callout_callout_request_model_json2 == turn_event_callout_callout_request_model_json + message_output_debug_turn_event_turn_event_action_finished_model_json2 = message_output_debug_turn_event_turn_event_action_finished_model.to_dict() + assert message_output_debug_turn_event_turn_event_action_finished_model_json2 == message_output_debug_turn_event_turn_event_action_finished_model_json -class TestModel_TurnEventCalloutCalloutResponse: +class TestModel_MessageOutputDebugTurnEventTurnEventActionRoutingDenied: """ - Test Class for TurnEventCalloutCalloutResponse + Test Class for MessageOutputDebugTurnEventTurnEventActionRoutingDenied """ - def test_turn_event_callout_callout_response_serialization(self): + def test_message_output_debug_turn_event_turn_event_action_routing_denied_serialization(self): """ - Test serialization/deserialization for TurnEventCalloutCalloutResponse + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventActionRoutingDenied """ - # Construct a json representation of a TurnEventCalloutCalloutResponse model - turn_event_callout_callout_response_model_json = {} - turn_event_callout_callout_response_model_json['body'] = 'testString' - turn_event_callout_callout_response_model_json['status_code'] = 38 - turn_event_callout_callout_response_model_json['last_event'] = {'anyKey': 'anyValue'} + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of TurnEventCalloutCalloutResponse by calling from_dict on the json representation - turn_event_callout_callout_response_model = TurnEventCalloutCalloutResponse.from_dict(turn_event_callout_callout_response_model_json) - assert turn_event_callout_callout_response_model != False + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - # Construct a model instance of TurnEventCalloutCalloutResponse by calling from_dict on the json representation - turn_event_callout_callout_response_model_dict = TurnEventCalloutCalloutResponse.from_dict(turn_event_callout_callout_response_model_json).__dict__ - turn_event_callout_callout_response_model2 = TurnEventCalloutCalloutResponse(**turn_event_callout_callout_response_model_dict) + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventActionRoutingDenied model + message_output_debug_turn_event_turn_event_action_routing_denied_model_json = {} + message_output_debug_turn_event_turn_event_action_routing_denied_model_json['event'] = 'action_routing_denied' + message_output_debug_turn_event_turn_event_action_routing_denied_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_action_routing_denied_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_action_routing_denied_model_json['reason'] = 'action_conditions_failed' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionRoutingDenied by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_routing_denied_model = MessageOutputDebugTurnEventTurnEventActionRoutingDenied.from_dict(message_output_debug_turn_event_turn_event_action_routing_denied_model_json) + assert message_output_debug_turn_event_turn_event_action_routing_denied_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionRoutingDenied by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_routing_denied_model_dict = MessageOutputDebugTurnEventTurnEventActionRoutingDenied.from_dict(message_output_debug_turn_event_turn_event_action_routing_denied_model_json).__dict__ + message_output_debug_turn_event_turn_event_action_routing_denied_model2 = MessageOutputDebugTurnEventTurnEventActionRoutingDenied(**message_output_debug_turn_event_turn_event_action_routing_denied_model_dict) # Verify the model instances are equivalent - assert turn_event_callout_callout_response_model == turn_event_callout_callout_response_model2 + assert message_output_debug_turn_event_turn_event_action_routing_denied_model == message_output_debug_turn_event_turn_event_action_routing_denied_model2 # Convert model instance back to dict and verify no loss of data - turn_event_callout_callout_response_model_json2 = turn_event_callout_callout_response_model.to_dict() - assert turn_event_callout_callout_response_model_json2 == turn_event_callout_callout_response_model_json + message_output_debug_turn_event_turn_event_action_routing_denied_model_json2 = message_output_debug_turn_event_turn_event_action_routing_denied_model.to_dict() + assert message_output_debug_turn_event_turn_event_action_routing_denied_model_json2 == message_output_debug_turn_event_turn_event_action_routing_denied_model_json -class TestModel_TurnEventCalloutError: +class TestModel_MessageOutputDebugTurnEventTurnEventActionVisited: """ - Test Class for TurnEventCalloutError + Test Class for MessageOutputDebugTurnEventTurnEventActionVisited """ - def test_turn_event_callout_error_serialization(self): + def test_message_output_debug_turn_event_turn_event_action_visited_serialization(self): """ - Test serialization/deserialization for TurnEventCalloutError + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventActionVisited """ - # Construct a json representation of a TurnEventCalloutError model - turn_event_callout_error_model_json = {} - turn_event_callout_error_model_json['message'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of TurnEventCalloutError by calling from_dict on the json representation - turn_event_callout_error_model = TurnEventCalloutError.from_dict(turn_event_callout_error_model_json) - assert turn_event_callout_error_model != False + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - # Construct a model instance of TurnEventCalloutError by calling from_dict on the json representation - turn_event_callout_error_model_dict = TurnEventCalloutError.from_dict(turn_event_callout_error_model_json).__dict__ - turn_event_callout_error_model2 = TurnEventCalloutError(**turn_event_callout_error_model_dict) + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventActionVisited model + message_output_debug_turn_event_turn_event_action_visited_model_json = {} + message_output_debug_turn_event_turn_event_action_visited_model_json['event'] = 'action_visited' + message_output_debug_turn_event_turn_event_action_visited_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_action_visited_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_action_visited_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_action_visited_model_json['reason'] = 'intent' + message_output_debug_turn_event_turn_event_action_visited_model_json['result_variable'] = 'testString' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_visited_model = MessageOutputDebugTurnEventTurnEventActionVisited.from_dict(message_output_debug_turn_event_turn_event_action_visited_model_json) + assert message_output_debug_turn_event_turn_event_action_visited_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_action_visited_model_dict = MessageOutputDebugTurnEventTurnEventActionVisited.from_dict(message_output_debug_turn_event_turn_event_action_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_action_visited_model2 = MessageOutputDebugTurnEventTurnEventActionVisited(**message_output_debug_turn_event_turn_event_action_visited_model_dict) # Verify the model instances are equivalent - assert turn_event_callout_error_model == turn_event_callout_error_model2 + assert message_output_debug_turn_event_turn_event_action_visited_model == message_output_debug_turn_event_turn_event_action_visited_model2 # Convert model instance back to dict and verify no loss of data - turn_event_callout_error_model_json2 = turn_event_callout_error_model.to_dict() - assert turn_event_callout_error_model_json2 == turn_event_callout_error_model_json + message_output_debug_turn_event_turn_event_action_visited_model_json2 = message_output_debug_turn_event_turn_event_action_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_action_visited_model_json2 == message_output_debug_turn_event_turn_event_action_visited_model_json -class TestModel_TurnEventNodeSource: +class TestModel_MessageOutputDebugTurnEventTurnEventCallout: """ - Test Class for TurnEventNodeSource + Test Class for MessageOutputDebugTurnEventTurnEventCallout """ - def test_turn_event_node_source_serialization(self): + def test_message_output_debug_turn_event_turn_event_callout_serialization(self): """ - Test serialization/deserialization for TurnEventNodeSource + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventCallout """ - # Construct a json representation of a TurnEventNodeSource model - turn_event_node_source_model_json = {} - turn_event_node_source_model_json['type'] = 'dialog_node' - turn_event_node_source_model_json['dialog_node'] = 'testString' - turn_event_node_source_model_json['title'] = 'testString' - turn_event_node_source_model_json['condition'] = 'testString' - - # Construct a model instance of TurnEventNodeSource by calling from_dict on the json representation - turn_event_node_source_model = TurnEventNodeSource.from_dict(turn_event_node_source_model_json) - assert turn_event_node_source_model != False - - # Construct a model instance of TurnEventNodeSource by calling from_dict on the json representation - turn_event_node_source_model_dict = TurnEventNodeSource.from_dict(turn_event_node_source_model_json).__dict__ - turn_event_node_source_model2 = TurnEventNodeSource(**turn_event_node_source_model_dict) + # Construct dict forms of any model objects needed in order to build this model. - # Verify the model instances are equivalent - assert turn_event_node_source_model == turn_event_node_source_model2 + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - # Convert model instance back to dict and verify no loss of data - turn_event_node_source_model_json2 = turn_event_node_source_model.to_dict() - assert turn_event_node_source_model_json2 == turn_event_node_source_model_json + turn_event_callout_callout_request_model = {} # TurnEventCalloutCalloutRequest + turn_event_callout_callout_request_model['method'] = 'get' + turn_event_callout_callout_request_model['url'] = 'testString' + turn_event_callout_callout_request_model['path'] = 'testString' + turn_event_callout_callout_request_model['query_parameters'] = 'testString' + turn_event_callout_callout_request_model['headers'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_request_model['body'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_response_model = {} # TurnEventCalloutCalloutResponse + turn_event_callout_callout_response_model['body'] = 'testString' + turn_event_callout_callout_response_model['status_code'] = 38 + turn_event_callout_callout_response_model['last_event'] = {'anyKey': 'anyValue'} -class TestModel_TurnEventSearchError: - """ - Test Class for TurnEventSearchError - """ + turn_event_callout_callout_model = {} # TurnEventCalloutCallout + turn_event_callout_callout_model['type'] = 'integration_interaction' + turn_event_callout_callout_model['internal'] = {'anyKey': 'anyValue'} + turn_event_callout_callout_model['result_variable'] = 'testString' + turn_event_callout_callout_model['request'] = turn_event_callout_callout_request_model + turn_event_callout_callout_model['response'] = turn_event_callout_callout_response_model - def test_turn_event_search_error_serialization(self): - """ - Test serialization/deserialization for TurnEventSearchError - """ + turn_event_callout_error_model = {} # TurnEventCalloutError + turn_event_callout_error_model['message'] = 'testString' - # Construct a json representation of a TurnEventSearchError model - turn_event_search_error_model_json = {} - turn_event_search_error_model_json['message'] = 'testString' + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventCallout model + message_output_debug_turn_event_turn_event_callout_model_json = {} + message_output_debug_turn_event_turn_event_callout_model_json['event'] = 'callout' + message_output_debug_turn_event_turn_event_callout_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_callout_model_json['callout'] = turn_event_callout_callout_model + message_output_debug_turn_event_turn_event_callout_model_json['error'] = turn_event_callout_error_model - # Construct a model instance of TurnEventSearchError by calling from_dict on the json representation - turn_event_search_error_model = TurnEventSearchError.from_dict(turn_event_search_error_model_json) - assert turn_event_search_error_model != False + # Construct a model instance of MessageOutputDebugTurnEventTurnEventCallout by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_callout_model = MessageOutputDebugTurnEventTurnEventCallout.from_dict(message_output_debug_turn_event_turn_event_callout_model_json) + assert message_output_debug_turn_event_turn_event_callout_model != False - # Construct a model instance of TurnEventSearchError by calling from_dict on the json representation - turn_event_search_error_model_dict = TurnEventSearchError.from_dict(turn_event_search_error_model_json).__dict__ - turn_event_search_error_model2 = TurnEventSearchError(**turn_event_search_error_model_dict) + # Construct a model instance of MessageOutputDebugTurnEventTurnEventCallout by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_callout_model_dict = MessageOutputDebugTurnEventTurnEventCallout.from_dict(message_output_debug_turn_event_turn_event_callout_model_json).__dict__ + message_output_debug_turn_event_turn_event_callout_model2 = MessageOutputDebugTurnEventTurnEventCallout(**message_output_debug_turn_event_turn_event_callout_model_dict) # Verify the model instances are equivalent - assert turn_event_search_error_model == turn_event_search_error_model2 + assert message_output_debug_turn_event_turn_event_callout_model == message_output_debug_turn_event_turn_event_callout_model2 # Convert model instance back to dict and verify no loss of data - turn_event_search_error_model_json2 = turn_event_search_error_model.to_dict() - assert turn_event_search_error_model_json2 == turn_event_search_error_model_json + message_output_debug_turn_event_turn_event_callout_model_json2 = message_output_debug_turn_event_turn_event_callout_model.to_dict() + assert message_output_debug_turn_event_turn_event_callout_model_json2 == message_output_debug_turn_event_turn_event_callout_model_json -class TestModel_UpdateEnvironmentOrchestration: +class TestModel_MessageOutputDebugTurnEventTurnEventClientActions: """ - Test Class for UpdateEnvironmentOrchestration + Test Class for MessageOutputDebugTurnEventTurnEventClientActions """ - def test_update_environment_orchestration_serialization(self): + def test_message_output_debug_turn_event_turn_event_client_actions_serialization(self): """ - Test serialization/deserialization for UpdateEnvironmentOrchestration + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventClientActions """ - # Construct a json representation of a UpdateEnvironmentOrchestration model - update_environment_orchestration_model_json = {} - update_environment_orchestration_model_json['search_skill_fallback'] = True - - # Construct a model instance of UpdateEnvironmentOrchestration by calling from_dict on the json representation - update_environment_orchestration_model = UpdateEnvironmentOrchestration.from_dict(update_environment_orchestration_model_json) - assert update_environment_orchestration_model != False + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of UpdateEnvironmentOrchestration by calling from_dict on the json representation - update_environment_orchestration_model_dict = UpdateEnvironmentOrchestration.from_dict(update_environment_orchestration_model_json).__dict__ - update_environment_orchestration_model2 = UpdateEnvironmentOrchestration(**update_environment_orchestration_model_dict) + turn_event_step_source_model = {} # TurnEventStepSource + turn_event_step_source_model['type'] = 'step' + turn_event_step_source_model['action'] = 'testString' + turn_event_step_source_model['action_title'] = 'testString' + turn_event_step_source_model['step'] = 'testString' + turn_event_step_source_model['is_ai_guided'] = True + turn_event_step_source_model['is_skill_based'] = True + + client_action_model = {} # ClientAction + client_action_model['name'] = 'testString' + client_action_model['result_variable'] = 'testString' + client_action_model['type'] = 'testString' + client_action_model['skill'] = 'main skill' + client_action_model['parameters'] = {'anyKey': 'anyValue'} + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventClientActions model + message_output_debug_turn_event_turn_event_client_actions_model_json = {} + message_output_debug_turn_event_turn_event_client_actions_model_json['event'] = 'client_actions' + message_output_debug_turn_event_turn_event_client_actions_model_json['source'] = turn_event_step_source_model + message_output_debug_turn_event_turn_event_client_actions_model_json['client_actions'] = [client_action_model] + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventClientActions by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_client_actions_model = MessageOutputDebugTurnEventTurnEventClientActions.from_dict(message_output_debug_turn_event_turn_event_client_actions_model_json) + assert message_output_debug_turn_event_turn_event_client_actions_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventClientActions by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_client_actions_model_dict = MessageOutputDebugTurnEventTurnEventClientActions.from_dict(message_output_debug_turn_event_turn_event_client_actions_model_json).__dict__ + message_output_debug_turn_event_turn_event_client_actions_model2 = MessageOutputDebugTurnEventTurnEventClientActions(**message_output_debug_turn_event_turn_event_client_actions_model_dict) # Verify the model instances are equivalent - assert update_environment_orchestration_model == update_environment_orchestration_model2 + assert message_output_debug_turn_event_turn_event_client_actions_model == message_output_debug_turn_event_turn_event_client_actions_model2 # Convert model instance back to dict and verify no loss of data - update_environment_orchestration_model_json2 = update_environment_orchestration_model.to_dict() - assert update_environment_orchestration_model_json2 == update_environment_orchestration_model_json + message_output_debug_turn_event_turn_event_client_actions_model_json2 = message_output_debug_turn_event_turn_event_client_actions_model.to_dict() + assert message_output_debug_turn_event_turn_event_client_actions_model_json2 == message_output_debug_turn_event_turn_event_client_actions_model_json -class TestModel_UpdateEnvironmentReleaseReference: +class TestModel_MessageOutputDebugTurnEventTurnEventConversationalSearchEnd: """ - Test Class for UpdateEnvironmentReleaseReference + Test Class for MessageOutputDebugTurnEventTurnEventConversationalSearchEnd """ - def test_update_environment_release_reference_serialization(self): + def test_message_output_debug_turn_event_turn_event_conversational_search_end_serialization(self): """ - Test serialization/deserialization for UpdateEnvironmentReleaseReference + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventConversationalSearchEnd """ - # Construct a json representation of a UpdateEnvironmentReleaseReference model - update_environment_release_reference_model_json = {} - update_environment_release_reference_model_json['release'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of UpdateEnvironmentReleaseReference by calling from_dict on the json representation - update_environment_release_reference_model = UpdateEnvironmentReleaseReference.from_dict(update_environment_release_reference_model_json) - assert update_environment_release_reference_model != False + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - # Construct a model instance of UpdateEnvironmentReleaseReference by calling from_dict on the json representation - update_environment_release_reference_model_dict = UpdateEnvironmentReleaseReference.from_dict(update_environment_release_reference_model_json).__dict__ - update_environment_release_reference_model2 = UpdateEnvironmentReleaseReference(**update_environment_release_reference_model_dict) + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventConversationalSearchEnd model + message_output_debug_turn_event_turn_event_conversational_search_end_model_json = {} + message_output_debug_turn_event_turn_event_conversational_search_end_model_json['event'] = 'conversational_search_end' + message_output_debug_turn_event_turn_event_conversational_search_end_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_conversational_search_end_model_json['condition_type'] = 'user_defined' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventConversationalSearchEnd by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_conversational_search_end_model = MessageOutputDebugTurnEventTurnEventConversationalSearchEnd.from_dict(message_output_debug_turn_event_turn_event_conversational_search_end_model_json) + assert message_output_debug_turn_event_turn_event_conversational_search_end_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventConversationalSearchEnd by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_conversational_search_end_model_dict = MessageOutputDebugTurnEventTurnEventConversationalSearchEnd.from_dict(message_output_debug_turn_event_turn_event_conversational_search_end_model_json).__dict__ + message_output_debug_turn_event_turn_event_conversational_search_end_model2 = MessageOutputDebugTurnEventTurnEventConversationalSearchEnd(**message_output_debug_turn_event_turn_event_conversational_search_end_model_dict) # Verify the model instances are equivalent - assert update_environment_release_reference_model == update_environment_release_reference_model2 + assert message_output_debug_turn_event_turn_event_conversational_search_end_model == message_output_debug_turn_event_turn_event_conversational_search_end_model2 # Convert model instance back to dict and verify no loss of data - update_environment_release_reference_model_json2 = update_environment_release_reference_model.to_dict() - assert update_environment_release_reference_model_json2 == update_environment_release_reference_model_json + message_output_debug_turn_event_turn_event_conversational_search_end_model_json2 = message_output_debug_turn_event_turn_event_conversational_search_end_model.to_dict() + assert message_output_debug_turn_event_turn_event_conversational_search_end_model_json2 == message_output_debug_turn_event_turn_event_conversational_search_end_model_json -class TestModel_CompleteItem: +class TestModel_MessageOutputDebugTurnEventTurnEventGenerativeAICalled: """ - Test Class for CompleteItem + Test Class for MessageOutputDebugTurnEventTurnEventGenerativeAICalled """ - def test_complete_item_serialization(self): + def test_message_output_debug_turn_event_turn_event_generative_ai_called_serialization(self): """ - Test serialization/deserialization for CompleteItem + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventGenerativeAICalled """ # Construct dict forms of any model objects needed in order to build this model. - metadata_model = {} # Metadata - metadata_model['id'] = 38 - - # Construct a json representation of a CompleteItem model - complete_item_model_json = {} - complete_item_model_json['streaming_metadata'] = metadata_model - - # Construct a model instance of CompleteItem by calling from_dict on the json representation - complete_item_model = CompleteItem.from_dict(complete_item_model_json) - assert complete_item_model != False - - # Construct a model instance of CompleteItem by calling from_dict on the json representation - complete_item_model_dict = CompleteItem.from_dict(complete_item_model_json).__dict__ - complete_item_model2 = CompleteItem(**complete_item_model_dict) + generative_ai_task_confidence_scores_model = {} # GenerativeAITaskConfidenceScores + generative_ai_task_confidence_scores_model['pre_gen'] = 72.5 + generative_ai_task_confidence_scores_model['pre_gen_threshold'] = 72.5 + generative_ai_task_confidence_scores_model['post_gen'] = 72.5 + generative_ai_task_confidence_scores_model['post_gen_threshold'] = 72.5 + + generative_ai_task_model = {} # GenerativeAITaskContentGroundedAnswering + generative_ai_task_model['task'] = 'content_grounded_answering' + generative_ai_task_model['is_idk_response'] = True + generative_ai_task_model['is_hap_detected'] = True + generative_ai_task_model['confidence_scores'] = generative_ai_task_confidence_scores_model + generative_ai_task_model['original_response'] = 'testString' + generative_ai_task_model['inferred_query'] = 'testString' + + turn_event_generative_ai_called_callout_request_model = {} # TurnEventGenerativeAICalledCalloutRequest + turn_event_generative_ai_called_callout_request_model['method'] = 'GET' + turn_event_generative_ai_called_callout_request_model['url'] = 'testString' + turn_event_generative_ai_called_callout_request_model['port'] = 'testString' + turn_event_generative_ai_called_callout_request_model['path'] = 'testString' + turn_event_generative_ai_called_callout_request_model['query_parameters'] = 'testString' + turn_event_generative_ai_called_callout_request_model['headers'] = {'anyKey': 'anyValue'} + turn_event_generative_ai_called_callout_request_model['body'] = {'anyKey': 'anyValue'} + + turn_event_generative_ai_called_callout_response_model = {} # TurnEventGenerativeAICalledCalloutResponse + turn_event_generative_ai_called_callout_response_model['body'] = 'testString' + turn_event_generative_ai_called_callout_response_model['status_code'] = 38 + + turn_event_generative_ai_called_callout_search_model = {} # TurnEventGenerativeAICalledCalloutSearch + turn_event_generative_ai_called_callout_search_model['engine'] = 'testString' + turn_event_generative_ai_called_callout_search_model['index'] = 'testString' + turn_event_generative_ai_called_callout_search_model['query'] = 'testString' + turn_event_generative_ai_called_callout_search_model['request'] = turn_event_generative_ai_called_callout_request_model + turn_event_generative_ai_called_callout_search_model['response'] = turn_event_generative_ai_called_callout_response_model + + turn_event_generative_ai_called_callout_llm_response_model = {} # TurnEventGenerativeAICalledCalloutLlmResponse + turn_event_generative_ai_called_callout_llm_response_model['text'] = 'testString' + turn_event_generative_ai_called_callout_llm_response_model['response_type'] = 'testString' + turn_event_generative_ai_called_callout_llm_response_model['is_idk_response'] = True + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + turn_event_generative_ai_called_callout_llm_model = {} # TurnEventGenerativeAICalledCalloutLlm + turn_event_generative_ai_called_callout_llm_model['type'] = 'testString' + turn_event_generative_ai_called_callout_llm_model['model_id'] = 'testString' + turn_event_generative_ai_called_callout_llm_model['model_class_id'] = 'testString' + turn_event_generative_ai_called_callout_llm_model['generated_token_count'] = 38 + turn_event_generative_ai_called_callout_llm_model['input_token_count'] = 38 + turn_event_generative_ai_called_callout_llm_model['success'] = True + turn_event_generative_ai_called_callout_llm_model['response'] = turn_event_generative_ai_called_callout_llm_response_model + turn_event_generative_ai_called_callout_llm_model['request'] = [search_results_model] + + turn_event_generative_ai_called_callout_model = {} # TurnEventGenerativeAICalledCallout + turn_event_generative_ai_called_callout_model['search_called'] = True + turn_event_generative_ai_called_callout_model['llm_called'] = True + turn_event_generative_ai_called_callout_model['search'] = turn_event_generative_ai_called_callout_search_model + turn_event_generative_ai_called_callout_model['llm'] = turn_event_generative_ai_called_callout_llm_model + turn_event_generative_ai_called_callout_model['idk_reason_code'] = 'testString' + + turn_event_generative_ai_called_metrics_model = {} # TurnEventGenerativeAICalledMetrics + turn_event_generative_ai_called_metrics_model['search_time_ms'] = 'unknown type: float' + turn_event_generative_ai_called_metrics_model['answer_generation_time_ms'] = 'unknown type: float' + turn_event_generative_ai_called_metrics_model['total_time_ms'] = 'unknown type: float' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventGenerativeAICalled model + message_output_debug_turn_event_turn_event_generative_ai_called_model_json = {} + message_output_debug_turn_event_turn_event_generative_ai_called_model_json['event'] = 'generative_ai_called' + message_output_debug_turn_event_turn_event_generative_ai_called_model_json['source'] = {'anyKey': 'anyValue'} + message_output_debug_turn_event_turn_event_generative_ai_called_model_json['generative_ai_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_generative_ai_called_model_json['generative_ai'] = generative_ai_task_model + message_output_debug_turn_event_turn_event_generative_ai_called_model_json['callout'] = turn_event_generative_ai_called_callout_model + message_output_debug_turn_event_turn_event_generative_ai_called_model_json['metrics'] = turn_event_generative_ai_called_metrics_model + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventGenerativeAICalled by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_generative_ai_called_model = MessageOutputDebugTurnEventTurnEventGenerativeAICalled.from_dict(message_output_debug_turn_event_turn_event_generative_ai_called_model_json) + assert message_output_debug_turn_event_turn_event_generative_ai_called_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventGenerativeAICalled by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_generative_ai_called_model_dict = MessageOutputDebugTurnEventTurnEventGenerativeAICalled.from_dict(message_output_debug_turn_event_turn_event_generative_ai_called_model_json).__dict__ + message_output_debug_turn_event_turn_event_generative_ai_called_model2 = MessageOutputDebugTurnEventTurnEventGenerativeAICalled(**message_output_debug_turn_event_turn_event_generative_ai_called_model_dict) # Verify the model instances are equivalent - assert complete_item_model == complete_item_model2 + assert message_output_debug_turn_event_turn_event_generative_ai_called_model == message_output_debug_turn_event_turn_event_generative_ai_called_model2 # Convert model instance back to dict and verify no loss of data - complete_item_model_json2 = complete_item_model.to_dict() - assert complete_item_model_json2 == complete_item_model_json + message_output_debug_turn_event_turn_event_generative_ai_called_model_json2 = message_output_debug_turn_event_turn_event_generative_ai_called_model.to_dict() + assert message_output_debug_turn_event_turn_event_generative_ai_called_model_json2 == message_output_debug_turn_event_turn_event_generative_ai_called_model_json -class TestModel_LogMessageSourceAction: +class TestModel_MessageOutputDebugTurnEventTurnEventHandlerVisited: """ - Test Class for LogMessageSourceAction + Test Class for MessageOutputDebugTurnEventTurnEventHandlerVisited """ - def test_log_message_source_action_serialization(self): + def test_message_output_debug_turn_event_turn_event_handler_visited_serialization(self): """ - Test serialization/deserialization for LogMessageSourceAction + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventHandlerVisited """ - # Construct a json representation of a LogMessageSourceAction model - log_message_source_action_model_json = {} - log_message_source_action_model_json['type'] = 'action' - log_message_source_action_model_json['action'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of LogMessageSourceAction by calling from_dict on the json representation - log_message_source_action_model = LogMessageSourceAction.from_dict(log_message_source_action_model_json) - assert log_message_source_action_model != False + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventHandlerVisited model + message_output_debug_turn_event_turn_event_handler_visited_model_json = {} + message_output_debug_turn_event_turn_event_handler_visited_model_json['event'] = 'handler_visited' + message_output_debug_turn_event_turn_event_handler_visited_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_handler_visited_model_json['action_start_time'] = 'testString' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventHandlerVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_handler_visited_model = MessageOutputDebugTurnEventTurnEventHandlerVisited.from_dict(message_output_debug_turn_event_turn_event_handler_visited_model_json) + assert message_output_debug_turn_event_turn_event_handler_visited_model != False - # Construct a model instance of LogMessageSourceAction by calling from_dict on the json representation - log_message_source_action_model_dict = LogMessageSourceAction.from_dict(log_message_source_action_model_json).__dict__ - log_message_source_action_model2 = LogMessageSourceAction(**log_message_source_action_model_dict) + # Construct a model instance of MessageOutputDebugTurnEventTurnEventHandlerVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_handler_visited_model_dict = MessageOutputDebugTurnEventTurnEventHandlerVisited.from_dict(message_output_debug_turn_event_turn_event_handler_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_handler_visited_model2 = MessageOutputDebugTurnEventTurnEventHandlerVisited(**message_output_debug_turn_event_turn_event_handler_visited_model_dict) # Verify the model instances are equivalent - assert log_message_source_action_model == log_message_source_action_model2 + assert message_output_debug_turn_event_turn_event_handler_visited_model == message_output_debug_turn_event_turn_event_handler_visited_model2 # Convert model instance back to dict and verify no loss of data - log_message_source_action_model_json2 = log_message_source_action_model.to_dict() - assert log_message_source_action_model_json2 == log_message_source_action_model_json + message_output_debug_turn_event_turn_event_handler_visited_model_json2 = message_output_debug_turn_event_turn_event_handler_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_handler_visited_model_json2 == message_output_debug_turn_event_turn_event_handler_visited_model_json -class TestModel_LogMessageSourceDialogNode: +class TestModel_MessageOutputDebugTurnEventTurnEventManualRoute: """ - Test Class for LogMessageSourceDialogNode + Test Class for MessageOutputDebugTurnEventTurnEventManualRoute """ - def test_log_message_source_dialog_node_serialization(self): + def test_message_output_debug_turn_event_turn_event_manual_route_serialization(self): """ - Test serialization/deserialization for LogMessageSourceDialogNode + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventManualRoute """ - # Construct a json representation of a LogMessageSourceDialogNode model - log_message_source_dialog_node_model_json = {} - log_message_source_dialog_node_model_json['type'] = 'dialog_node' - log_message_source_dialog_node_model_json['dialog_node'] = 'testString' - - # Construct a model instance of LogMessageSourceDialogNode by calling from_dict on the json representation - log_message_source_dialog_node_model = LogMessageSourceDialogNode.from_dict(log_message_source_dialog_node_model_json) - assert log_message_source_dialog_node_model != False + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of LogMessageSourceDialogNode by calling from_dict on the json representation - log_message_source_dialog_node_model_dict = LogMessageSourceDialogNode.from_dict(log_message_source_dialog_node_model_json).__dict__ - log_message_source_dialog_node_model2 = LogMessageSourceDialogNode(**log_message_source_dialog_node_model_dict) + turn_event_step_source_model = {} # TurnEventStepSource + turn_event_step_source_model['type'] = 'step' + turn_event_step_source_model['action'] = 'testString' + turn_event_step_source_model['action_title'] = 'testString' + turn_event_step_source_model['step'] = 'testString' + turn_event_step_source_model['is_ai_guided'] = True + turn_event_step_source_model['is_skill_based'] = True + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventManualRoute model + message_output_debug_turn_event_turn_event_manual_route_model_json = {} + message_output_debug_turn_event_turn_event_manual_route_model_json['event'] = 'manual_route' + message_output_debug_turn_event_turn_event_manual_route_model_json['source'] = turn_event_step_source_model + message_output_debug_turn_event_turn_event_manual_route_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_manual_route_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_manual_route_model_json['route_name'] = 'testString' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventManualRoute by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_manual_route_model = MessageOutputDebugTurnEventTurnEventManualRoute.from_dict(message_output_debug_turn_event_turn_event_manual_route_model_json) + assert message_output_debug_turn_event_turn_event_manual_route_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventManualRoute by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_manual_route_model_dict = MessageOutputDebugTurnEventTurnEventManualRoute.from_dict(message_output_debug_turn_event_turn_event_manual_route_model_json).__dict__ + message_output_debug_turn_event_turn_event_manual_route_model2 = MessageOutputDebugTurnEventTurnEventManualRoute(**message_output_debug_turn_event_turn_event_manual_route_model_dict) # Verify the model instances are equivalent - assert log_message_source_dialog_node_model == log_message_source_dialog_node_model2 + assert message_output_debug_turn_event_turn_event_manual_route_model == message_output_debug_turn_event_turn_event_manual_route_model2 # Convert model instance back to dict and verify no loss of data - log_message_source_dialog_node_model_json2 = log_message_source_dialog_node_model.to_dict() - assert log_message_source_dialog_node_model_json2 == log_message_source_dialog_node_model_json + message_output_debug_turn_event_turn_event_manual_route_model_json2 = message_output_debug_turn_event_turn_event_manual_route_model.to_dict() + assert message_output_debug_turn_event_turn_event_manual_route_model_json2 == message_output_debug_turn_event_turn_event_manual_route_model_json -class TestModel_LogMessageSourceHandler: +class TestModel_MessageOutputDebugTurnEventTurnEventNodeVisited: """ - Test Class for LogMessageSourceHandler + Test Class for MessageOutputDebugTurnEventTurnEventNodeVisited """ - def test_log_message_source_handler_serialization(self): + def test_message_output_debug_turn_event_turn_event_node_visited_serialization(self): """ - Test serialization/deserialization for LogMessageSourceHandler + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventNodeVisited """ - # Construct a json representation of a LogMessageSourceHandler model - log_message_source_handler_model_json = {} - log_message_source_handler_model_json['type'] = 'handler' - log_message_source_handler_model_json['action'] = 'testString' - log_message_source_handler_model_json['step'] = 'testString' - log_message_source_handler_model_json['handler'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of LogMessageSourceHandler by calling from_dict on the json representation - log_message_source_handler_model = LogMessageSourceHandler.from_dict(log_message_source_handler_model_json) - assert log_message_source_handler_model != False + turn_event_node_source_model = {} # TurnEventNodeSource + turn_event_node_source_model['type'] = 'dialog_node' + turn_event_node_source_model['dialog_node'] = 'testString' + turn_event_node_source_model['title'] = 'testString' + turn_event_node_source_model['condition'] = 'testString' - # Construct a model instance of LogMessageSourceHandler by calling from_dict on the json representation - log_message_source_handler_model_dict = LogMessageSourceHandler.from_dict(log_message_source_handler_model_json).__dict__ - log_message_source_handler_model2 = LogMessageSourceHandler(**log_message_source_handler_model_dict) + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventNodeVisited model + message_output_debug_turn_event_turn_event_node_visited_model_json = {} + message_output_debug_turn_event_turn_event_node_visited_model_json['event'] = 'node_visited' + message_output_debug_turn_event_turn_event_node_visited_model_json['source'] = turn_event_node_source_model + message_output_debug_turn_event_turn_event_node_visited_model_json['reason'] = 'welcome' + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventNodeVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_node_visited_model = MessageOutputDebugTurnEventTurnEventNodeVisited.from_dict(message_output_debug_turn_event_turn_event_node_visited_model_json) + assert message_output_debug_turn_event_turn_event_node_visited_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventNodeVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_node_visited_model_dict = MessageOutputDebugTurnEventTurnEventNodeVisited.from_dict(message_output_debug_turn_event_turn_event_node_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_node_visited_model2 = MessageOutputDebugTurnEventTurnEventNodeVisited(**message_output_debug_turn_event_turn_event_node_visited_model_dict) # Verify the model instances are equivalent - assert log_message_source_handler_model == log_message_source_handler_model2 + assert message_output_debug_turn_event_turn_event_node_visited_model == message_output_debug_turn_event_turn_event_node_visited_model2 # Convert model instance back to dict and verify no loss of data - log_message_source_handler_model_json2 = log_message_source_handler_model.to_dict() - assert log_message_source_handler_model_json2 == log_message_source_handler_model_json + message_output_debug_turn_event_turn_event_node_visited_model_json2 = message_output_debug_turn_event_turn_event_node_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_node_visited_model_json2 == message_output_debug_turn_event_turn_event_node_visited_model_json -class TestModel_LogMessageSourceStep: +class TestModel_MessageOutputDebugTurnEventTurnEventSearch: """ - Test Class for LogMessageSourceStep + Test Class for MessageOutputDebugTurnEventTurnEventSearch """ - def test_log_message_source_step_serialization(self): + def test_message_output_debug_turn_event_turn_event_search_serialization(self): """ - Test serialization/deserialization for LogMessageSourceStep + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventSearch """ - # Construct a json representation of a LogMessageSourceStep model - log_message_source_step_model_json = {} - log_message_source_step_model_json['type'] = 'step' - log_message_source_step_model_json['action'] = 'testString' - log_message_source_step_model_json['step'] = 'testString' + # Construct dict forms of any model objects needed in order to build this model. - # Construct a model instance of LogMessageSourceStep by calling from_dict on the json representation - log_message_source_step_model = LogMessageSourceStep.from_dict(log_message_source_step_model_json) - assert log_message_source_step_model != False + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' - # Construct a model instance of LogMessageSourceStep by calling from_dict on the json representation - log_message_source_step_model_dict = LogMessageSourceStep.from_dict(log_message_source_step_model_json).__dict__ - log_message_source_step_model2 = LogMessageSourceStep(**log_message_source_step_model_dict) + turn_event_search_error_model = {} # TurnEventSearchError + turn_event_search_error_model['message'] = 'testString' + + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventSearch model + message_output_debug_turn_event_turn_event_search_model_json = {} + message_output_debug_turn_event_turn_event_search_model_json['event'] = 'search' + message_output_debug_turn_event_turn_event_search_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_search_model_json['error'] = turn_event_search_error_model + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventSearch by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_search_model = MessageOutputDebugTurnEventTurnEventSearch.from_dict(message_output_debug_turn_event_turn_event_search_model_json) + assert message_output_debug_turn_event_turn_event_search_model != False + + # Construct a model instance of MessageOutputDebugTurnEventTurnEventSearch by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_search_model_dict = MessageOutputDebugTurnEventTurnEventSearch.from_dict(message_output_debug_turn_event_turn_event_search_model_json).__dict__ + message_output_debug_turn_event_turn_event_search_model2 = MessageOutputDebugTurnEventTurnEventSearch(**message_output_debug_turn_event_turn_event_search_model_dict) # Verify the model instances are equivalent - assert log_message_source_step_model == log_message_source_step_model2 + assert message_output_debug_turn_event_turn_event_search_model == message_output_debug_turn_event_turn_event_search_model2 # Convert model instance back to dict and verify no loss of data - log_message_source_step_model_json2 = log_message_source_step_model.to_dict() - assert log_message_source_step_model_json2 == log_message_source_step_model_json + message_output_debug_turn_event_turn_event_search_model_json2 = message_output_debug_turn_event_turn_event_search_model.to_dict() + assert message_output_debug_turn_event_turn_event_search_model_json2 == message_output_debug_turn_event_turn_event_search_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventActionFinished: +class TestModel_MessageOutputDebugTurnEventTurnEventStepAnswered: """ - Test Class for MessageOutputDebugTurnEventTurnEventActionFinished + Test Class for MessageOutputDebugTurnEventTurnEventStepAnswered """ - def test_message_output_debug_turn_event_turn_event_action_finished_serialization(self): + def test_message_output_debug_turn_event_turn_event_step_answered_serialization(self): """ - Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventActionFinished + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventStepAnswered """ # Construct dict forms of any model objects needed in order to build this model. @@ -12298,39 +14776,38 @@ def test_message_output_debug_turn_event_turn_event_action_finished_serializatio turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - # Construct a json representation of a MessageOutputDebugTurnEventTurnEventActionFinished model - message_output_debug_turn_event_turn_event_action_finished_model_json = {} - message_output_debug_turn_event_turn_event_action_finished_model_json['event'] = 'action_finished' - message_output_debug_turn_event_turn_event_action_finished_model_json['source'] = turn_event_action_source_model - message_output_debug_turn_event_turn_event_action_finished_model_json['action_start_time'] = 'testString' - message_output_debug_turn_event_turn_event_action_finished_model_json['condition_type'] = 'user_defined' - message_output_debug_turn_event_turn_event_action_finished_model_json['reason'] = 'all_steps_done' - message_output_debug_turn_event_turn_event_action_finished_model_json['action_variables'] = {'anyKey': 'anyValue'} + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventStepAnswered model + message_output_debug_turn_event_turn_event_step_answered_model_json = {} + message_output_debug_turn_event_turn_event_step_answered_model_json['event'] = 'step_answered' + message_output_debug_turn_event_turn_event_step_answered_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_step_answered_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_step_answered_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_step_answered_model_json['prompted'] = True - # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionFinished by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_action_finished_model = MessageOutputDebugTurnEventTurnEventActionFinished.from_dict(message_output_debug_turn_event_turn_event_action_finished_model_json) - assert message_output_debug_turn_event_turn_event_action_finished_model != False + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepAnswered by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_answered_model = MessageOutputDebugTurnEventTurnEventStepAnswered.from_dict(message_output_debug_turn_event_turn_event_step_answered_model_json) + assert message_output_debug_turn_event_turn_event_step_answered_model != False - # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionFinished by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_action_finished_model_dict = MessageOutputDebugTurnEventTurnEventActionFinished.from_dict(message_output_debug_turn_event_turn_event_action_finished_model_json).__dict__ - message_output_debug_turn_event_turn_event_action_finished_model2 = MessageOutputDebugTurnEventTurnEventActionFinished(**message_output_debug_turn_event_turn_event_action_finished_model_dict) + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepAnswered by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_answered_model_dict = MessageOutputDebugTurnEventTurnEventStepAnswered.from_dict(message_output_debug_turn_event_turn_event_step_answered_model_json).__dict__ + message_output_debug_turn_event_turn_event_step_answered_model2 = MessageOutputDebugTurnEventTurnEventStepAnswered(**message_output_debug_turn_event_turn_event_step_answered_model_dict) # Verify the model instances are equivalent - assert message_output_debug_turn_event_turn_event_action_finished_model == message_output_debug_turn_event_turn_event_action_finished_model2 + assert message_output_debug_turn_event_turn_event_step_answered_model == message_output_debug_turn_event_turn_event_step_answered_model2 # Convert model instance back to dict and verify no loss of data - message_output_debug_turn_event_turn_event_action_finished_model_json2 = message_output_debug_turn_event_turn_event_action_finished_model.to_dict() - assert message_output_debug_turn_event_turn_event_action_finished_model_json2 == message_output_debug_turn_event_turn_event_action_finished_model_json + message_output_debug_turn_event_turn_event_step_answered_model_json2 = message_output_debug_turn_event_turn_event_step_answered_model.to_dict() + assert message_output_debug_turn_event_turn_event_step_answered_model_json2 == message_output_debug_turn_event_turn_event_step_answered_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventActionVisited: +class TestModel_MessageOutputDebugTurnEventTurnEventStepVisited: """ - Test Class for MessageOutputDebugTurnEventTurnEventActionVisited + Test Class for MessageOutputDebugTurnEventTurnEventStepVisited """ - def test_message_output_debug_turn_event_turn_event_action_visited_serialization(self): + def test_message_output_debug_turn_event_turn_event_step_visited_serialization(self): """ - Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventActionVisited + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventStepVisited """ # Construct dict forms of any model objects needed in order to build this model. @@ -12341,103 +14818,76 @@ def test_message_output_debug_turn_event_turn_event_action_visited_serialization turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - # Construct a json representation of a MessageOutputDebugTurnEventTurnEventActionVisited model - message_output_debug_turn_event_turn_event_action_visited_model_json = {} - message_output_debug_turn_event_turn_event_action_visited_model_json['event'] = 'action_visited' - message_output_debug_turn_event_turn_event_action_visited_model_json['source'] = turn_event_action_source_model - message_output_debug_turn_event_turn_event_action_visited_model_json['action_start_time'] = 'testString' - message_output_debug_turn_event_turn_event_action_visited_model_json['condition_type'] = 'user_defined' - message_output_debug_turn_event_turn_event_action_visited_model_json['reason'] = 'intent' - message_output_debug_turn_event_turn_event_action_visited_model_json['result_variable'] = 'testString' + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventStepVisited model + message_output_debug_turn_event_turn_event_step_visited_model_json = {} + message_output_debug_turn_event_turn_event_step_visited_model_json['event'] = 'step_visited' + message_output_debug_turn_event_turn_event_step_visited_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_step_visited_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_step_visited_model_json['action_start_time'] = 'testString' + message_output_debug_turn_event_turn_event_step_visited_model_json['has_question'] = True - # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionVisited by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_action_visited_model = MessageOutputDebugTurnEventTurnEventActionVisited.from_dict(message_output_debug_turn_event_turn_event_action_visited_model_json) - assert message_output_debug_turn_event_turn_event_action_visited_model != False + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_visited_model = MessageOutputDebugTurnEventTurnEventStepVisited.from_dict(message_output_debug_turn_event_turn_event_step_visited_model_json) + assert message_output_debug_turn_event_turn_event_step_visited_model != False - # Construct a model instance of MessageOutputDebugTurnEventTurnEventActionVisited by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_action_visited_model_dict = MessageOutputDebugTurnEventTurnEventActionVisited.from_dict(message_output_debug_turn_event_turn_event_action_visited_model_json).__dict__ - message_output_debug_turn_event_turn_event_action_visited_model2 = MessageOutputDebugTurnEventTurnEventActionVisited(**message_output_debug_turn_event_turn_event_action_visited_model_dict) + # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepVisited by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_step_visited_model_dict = MessageOutputDebugTurnEventTurnEventStepVisited.from_dict(message_output_debug_turn_event_turn_event_step_visited_model_json).__dict__ + message_output_debug_turn_event_turn_event_step_visited_model2 = MessageOutputDebugTurnEventTurnEventStepVisited(**message_output_debug_turn_event_turn_event_step_visited_model_dict) # Verify the model instances are equivalent - assert message_output_debug_turn_event_turn_event_action_visited_model == message_output_debug_turn_event_turn_event_action_visited_model2 + assert message_output_debug_turn_event_turn_event_step_visited_model == message_output_debug_turn_event_turn_event_step_visited_model2 # Convert model instance back to dict and verify no loss of data - message_output_debug_turn_event_turn_event_action_visited_model_json2 = message_output_debug_turn_event_turn_event_action_visited_model.to_dict() - assert message_output_debug_turn_event_turn_event_action_visited_model_json2 == message_output_debug_turn_event_turn_event_action_visited_model_json + message_output_debug_turn_event_turn_event_step_visited_model_json2 = message_output_debug_turn_event_turn_event_step_visited_model.to_dict() + assert message_output_debug_turn_event_turn_event_step_visited_model_json2 == message_output_debug_turn_event_turn_event_step_visited_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventCallout: +class TestModel_MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied: """ - Test Class for MessageOutputDebugTurnEventTurnEventCallout + Test Class for MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied """ - def test_message_output_debug_turn_event_turn_event_callout_serialization(self): + def test_message_output_debug_turn_event_turn_event_suggestion_intents_denied_serialization(self): """ - Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventCallout + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied """ # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' - - turn_event_callout_callout_request_model = {} # TurnEventCalloutCalloutRequest - turn_event_callout_callout_request_model['method'] = 'get' - turn_event_callout_callout_request_model['url'] = 'testString' - turn_event_callout_callout_request_model['path'] = 'testString' - turn_event_callout_callout_request_model['query_parameters'] = 'testString' - turn_event_callout_callout_request_model['headers'] = {'anyKey': 'anyValue'} - turn_event_callout_callout_request_model['body'] = {'anyKey': 'anyValue'} - - turn_event_callout_callout_response_model = {} # TurnEventCalloutCalloutResponse - turn_event_callout_callout_response_model['body'] = 'testString' - turn_event_callout_callout_response_model['status_code'] = 38 - turn_event_callout_callout_response_model['last_event'] = {'anyKey': 'anyValue'} - - turn_event_callout_callout_model = {} # TurnEventCalloutCallout - turn_event_callout_callout_model['type'] = 'integration_interaction' - turn_event_callout_callout_model['internal'] = {'anyKey': 'anyValue'} - turn_event_callout_callout_model['result_variable'] = 'testString' - turn_event_callout_callout_model['request'] = turn_event_callout_callout_request_model - turn_event_callout_callout_model['response'] = turn_event_callout_callout_response_model - - turn_event_callout_error_model = {} # TurnEventCalloutError - turn_event_callout_error_model['message'] = 'testString' + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' - # Construct a json representation of a MessageOutputDebugTurnEventTurnEventCallout model - message_output_debug_turn_event_turn_event_callout_model_json = {} - message_output_debug_turn_event_turn_event_callout_model_json['event'] = 'callout' - message_output_debug_turn_event_turn_event_callout_model_json['source'] = turn_event_action_source_model - message_output_debug_turn_event_turn_event_callout_model_json['callout'] = turn_event_callout_callout_model - message_output_debug_turn_event_turn_event_callout_model_json['error'] = turn_event_callout_error_model + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied model + message_output_debug_turn_event_turn_event_suggestion_intents_denied_model_json = {} + message_output_debug_turn_event_turn_event_suggestion_intents_denied_model_json['event'] = 'suggestion_intents_denied' + message_output_debug_turn_event_turn_event_suggestion_intents_denied_model_json['intents_denied'] = [runtime_intent_model] - # Construct a model instance of MessageOutputDebugTurnEventTurnEventCallout by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_callout_model = MessageOutputDebugTurnEventTurnEventCallout.from_dict(message_output_debug_turn_event_turn_event_callout_model_json) - assert message_output_debug_turn_event_turn_event_callout_model != False + # Construct a model instance of MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_suggestion_intents_denied_model = MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied.from_dict(message_output_debug_turn_event_turn_event_suggestion_intents_denied_model_json) + assert message_output_debug_turn_event_turn_event_suggestion_intents_denied_model != False - # Construct a model instance of MessageOutputDebugTurnEventTurnEventCallout by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_callout_model_dict = MessageOutputDebugTurnEventTurnEventCallout.from_dict(message_output_debug_turn_event_turn_event_callout_model_json).__dict__ - message_output_debug_turn_event_turn_event_callout_model2 = MessageOutputDebugTurnEventTurnEventCallout(**message_output_debug_turn_event_turn_event_callout_model_dict) + # Construct a model instance of MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_suggestion_intents_denied_model_dict = MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied.from_dict(message_output_debug_turn_event_turn_event_suggestion_intents_denied_model_json).__dict__ + message_output_debug_turn_event_turn_event_suggestion_intents_denied_model2 = MessageOutputDebugTurnEventTurnEventSuggestionIntentsDenied(**message_output_debug_turn_event_turn_event_suggestion_intents_denied_model_dict) # Verify the model instances are equivalent - assert message_output_debug_turn_event_turn_event_callout_model == message_output_debug_turn_event_turn_event_callout_model2 + assert message_output_debug_turn_event_turn_event_suggestion_intents_denied_model == message_output_debug_turn_event_turn_event_suggestion_intents_denied_model2 # Convert model instance back to dict and verify no loss of data - message_output_debug_turn_event_turn_event_callout_model_json2 = message_output_debug_turn_event_turn_event_callout_model.to_dict() - assert message_output_debug_turn_event_turn_event_callout_model_json2 == message_output_debug_turn_event_turn_event_callout_model_json + message_output_debug_turn_event_turn_event_suggestion_intents_denied_model_json2 = message_output_debug_turn_event_turn_event_suggestion_intents_denied_model.to_dict() + assert message_output_debug_turn_event_turn_event_suggestion_intents_denied_model_json2 == message_output_debug_turn_event_turn_event_suggestion_intents_denied_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventHandlerVisited: +class TestModel_MessageOutputDebugTurnEventTurnEventTopicSwitchDenied: """ - Test Class for MessageOutputDebugTurnEventTurnEventHandlerVisited + Test Class for MessageOutputDebugTurnEventTurnEventTopicSwitchDenied """ - def test_message_output_debug_turn_event_turn_event_handler_visited_serialization(self): + def test_message_output_debug_turn_event_turn_event_topic_switch_denied_serialization(self): """ - Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventHandlerVisited + Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventTopicSwitchDenied """ # Construct dict forms of any model objects needed in order to build this model. @@ -12448,193 +14898,383 @@ def test_message_output_debug_turn_event_turn_event_handler_visited_serializatio turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - # Construct a json representation of a MessageOutputDebugTurnEventTurnEventHandlerVisited model - message_output_debug_turn_event_turn_event_handler_visited_model_json = {} - message_output_debug_turn_event_turn_event_handler_visited_model_json['event'] = 'handler_visited' - message_output_debug_turn_event_turn_event_handler_visited_model_json['source'] = turn_event_action_source_model - message_output_debug_turn_event_turn_event_handler_visited_model_json['action_start_time'] = 'testString' + # Construct a json representation of a MessageOutputDebugTurnEventTurnEventTopicSwitchDenied model + message_output_debug_turn_event_turn_event_topic_switch_denied_model_json = {} + message_output_debug_turn_event_turn_event_topic_switch_denied_model_json['event'] = 'topic_switch_denied' + message_output_debug_turn_event_turn_event_topic_switch_denied_model_json['source'] = turn_event_action_source_model + message_output_debug_turn_event_turn_event_topic_switch_denied_model_json['condition_type'] = 'user_defined' + message_output_debug_turn_event_turn_event_topic_switch_denied_model_json['reason'] = 'action_conditions_failed' - # Construct a model instance of MessageOutputDebugTurnEventTurnEventHandlerVisited by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_handler_visited_model = MessageOutputDebugTurnEventTurnEventHandlerVisited.from_dict(message_output_debug_turn_event_turn_event_handler_visited_model_json) - assert message_output_debug_turn_event_turn_event_handler_visited_model != False + # Construct a model instance of MessageOutputDebugTurnEventTurnEventTopicSwitchDenied by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_topic_switch_denied_model = MessageOutputDebugTurnEventTurnEventTopicSwitchDenied.from_dict(message_output_debug_turn_event_turn_event_topic_switch_denied_model_json) + assert message_output_debug_turn_event_turn_event_topic_switch_denied_model != False - # Construct a model instance of MessageOutputDebugTurnEventTurnEventHandlerVisited by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_handler_visited_model_dict = MessageOutputDebugTurnEventTurnEventHandlerVisited.from_dict(message_output_debug_turn_event_turn_event_handler_visited_model_json).__dict__ - message_output_debug_turn_event_turn_event_handler_visited_model2 = MessageOutputDebugTurnEventTurnEventHandlerVisited(**message_output_debug_turn_event_turn_event_handler_visited_model_dict) + # Construct a model instance of MessageOutputDebugTurnEventTurnEventTopicSwitchDenied by calling from_dict on the json representation + message_output_debug_turn_event_turn_event_topic_switch_denied_model_dict = MessageOutputDebugTurnEventTurnEventTopicSwitchDenied.from_dict(message_output_debug_turn_event_turn_event_topic_switch_denied_model_json).__dict__ + message_output_debug_turn_event_turn_event_topic_switch_denied_model2 = MessageOutputDebugTurnEventTurnEventTopicSwitchDenied(**message_output_debug_turn_event_turn_event_topic_switch_denied_model_dict) # Verify the model instances are equivalent - assert message_output_debug_turn_event_turn_event_handler_visited_model == message_output_debug_turn_event_turn_event_handler_visited_model2 + assert message_output_debug_turn_event_turn_event_topic_switch_denied_model == message_output_debug_turn_event_turn_event_topic_switch_denied_model2 # Convert model instance back to dict and verify no loss of data - message_output_debug_turn_event_turn_event_handler_visited_model_json2 = message_output_debug_turn_event_turn_event_handler_visited_model.to_dict() - assert message_output_debug_turn_event_turn_event_handler_visited_model_json2 == message_output_debug_turn_event_turn_event_handler_visited_model_json + message_output_debug_turn_event_turn_event_topic_switch_denied_model_json2 = message_output_debug_turn_event_turn_event_topic_switch_denied_model.to_dict() + assert message_output_debug_turn_event_turn_event_topic_switch_denied_model_json2 == message_output_debug_turn_event_turn_event_topic_switch_denied_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventNodeVisited: +class TestModel_MessageStreamResponseMessageStreamCompleteItem: """ - Test Class for MessageOutputDebugTurnEventTurnEventNodeVisited + Test Class for MessageStreamResponseMessageStreamCompleteItem """ - def test_message_output_debug_turn_event_turn_event_node_visited_serialization(self): + def test_message_stream_response_message_stream_complete_item_serialization(self): """ - Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventNodeVisited + Test serialization/deserialization for MessageStreamResponseMessageStreamCompleteItem """ # Construct dict forms of any model objects needed in order to build this model. - turn_event_node_source_model = {} # TurnEventNodeSource - turn_event_node_source_model['type'] = 'dialog_node' - turn_event_node_source_model['dialog_node'] = 'testString' - turn_event_node_source_model['title'] = 'testString' - turn_event_node_source_model['condition'] = 'testString' + metadata_model = {} # Metadata + metadata_model['id'] = 38 - # Construct a json representation of a MessageOutputDebugTurnEventTurnEventNodeVisited model - message_output_debug_turn_event_turn_event_node_visited_model_json = {} - message_output_debug_turn_event_turn_event_node_visited_model_json['event'] = 'node_visited' - message_output_debug_turn_event_turn_event_node_visited_model_json['source'] = turn_event_node_source_model - message_output_debug_turn_event_turn_event_node_visited_model_json['reason'] = 'welcome' + complete_item_model = {} # CompleteItem + complete_item_model['streaming_metadata'] = metadata_model - # Construct a model instance of MessageOutputDebugTurnEventTurnEventNodeVisited by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_node_visited_model = MessageOutputDebugTurnEventTurnEventNodeVisited.from_dict(message_output_debug_turn_event_turn_event_node_visited_model_json) - assert message_output_debug_turn_event_turn_event_node_visited_model != False + # Construct a json representation of a MessageStreamResponseMessageStreamCompleteItem model + message_stream_response_message_stream_complete_item_model_json = {} + message_stream_response_message_stream_complete_item_model_json['complete_item'] = complete_item_model - # Construct a model instance of MessageOutputDebugTurnEventTurnEventNodeVisited by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_node_visited_model_dict = MessageOutputDebugTurnEventTurnEventNodeVisited.from_dict(message_output_debug_turn_event_turn_event_node_visited_model_json).__dict__ - message_output_debug_turn_event_turn_event_node_visited_model2 = MessageOutputDebugTurnEventTurnEventNodeVisited(**message_output_debug_turn_event_turn_event_node_visited_model_dict) + # Construct a model instance of MessageStreamResponseMessageStreamCompleteItem by calling from_dict on the json representation + message_stream_response_message_stream_complete_item_model = MessageStreamResponseMessageStreamCompleteItem.from_dict(message_stream_response_message_stream_complete_item_model_json) + assert message_stream_response_message_stream_complete_item_model != False + + # Construct a model instance of MessageStreamResponseMessageStreamCompleteItem by calling from_dict on the json representation + message_stream_response_message_stream_complete_item_model_dict = MessageStreamResponseMessageStreamCompleteItem.from_dict(message_stream_response_message_stream_complete_item_model_json).__dict__ + message_stream_response_message_stream_complete_item_model2 = MessageStreamResponseMessageStreamCompleteItem(**message_stream_response_message_stream_complete_item_model_dict) # Verify the model instances are equivalent - assert message_output_debug_turn_event_turn_event_node_visited_model == message_output_debug_turn_event_turn_event_node_visited_model2 + assert message_stream_response_message_stream_complete_item_model == message_stream_response_message_stream_complete_item_model2 # Convert model instance back to dict and verify no loss of data - message_output_debug_turn_event_turn_event_node_visited_model_json2 = message_output_debug_turn_event_turn_event_node_visited_model.to_dict() - assert message_output_debug_turn_event_turn_event_node_visited_model_json2 == message_output_debug_turn_event_turn_event_node_visited_model_json + message_stream_response_message_stream_complete_item_model_json2 = message_stream_response_message_stream_complete_item_model.to_dict() + assert message_stream_response_message_stream_complete_item_model_json2 == message_stream_response_message_stream_complete_item_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventSearch: +class TestModel_MessageStreamResponseMessageStreamPartialItem: """ - Test Class for MessageOutputDebugTurnEventTurnEventSearch + Test Class for MessageStreamResponseMessageStreamPartialItem """ - def test_message_output_debug_turn_event_turn_event_search_serialization(self): + def test_message_stream_response_message_stream_partial_item_serialization(self): """ - Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventSearch + Test serialization/deserialization for MessageStreamResponseMessageStreamPartialItem """ # Construct dict forms of any model objects needed in order to build this model. - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' + metadata_model = {} # Metadata + metadata_model['id'] = 38 - turn_event_search_error_model = {} # TurnEventSearchError - turn_event_search_error_model['message'] = 'testString' + partial_item_model = {} # PartialItem + partial_item_model['response_type'] = 'testString' + partial_item_model['text'] = 'testString' + partial_item_model['streaming_metadata'] = metadata_model - # Construct a json representation of a MessageOutputDebugTurnEventTurnEventSearch model - message_output_debug_turn_event_turn_event_search_model_json = {} - message_output_debug_turn_event_turn_event_search_model_json['event'] = 'search' - message_output_debug_turn_event_turn_event_search_model_json['source'] = turn_event_action_source_model - message_output_debug_turn_event_turn_event_search_model_json['error'] = turn_event_search_error_model + # Construct a json representation of a MessageStreamResponseMessageStreamPartialItem model + message_stream_response_message_stream_partial_item_model_json = {} + message_stream_response_message_stream_partial_item_model_json['partial_item'] = partial_item_model - # Construct a model instance of MessageOutputDebugTurnEventTurnEventSearch by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_search_model = MessageOutputDebugTurnEventTurnEventSearch.from_dict(message_output_debug_turn_event_turn_event_search_model_json) - assert message_output_debug_turn_event_turn_event_search_model != False + # Construct a model instance of MessageStreamResponseMessageStreamPartialItem by calling from_dict on the json representation + message_stream_response_message_stream_partial_item_model = MessageStreamResponseMessageStreamPartialItem.from_dict(message_stream_response_message_stream_partial_item_model_json) + assert message_stream_response_message_stream_partial_item_model != False - # Construct a model instance of MessageOutputDebugTurnEventTurnEventSearch by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_search_model_dict = MessageOutputDebugTurnEventTurnEventSearch.from_dict(message_output_debug_turn_event_turn_event_search_model_json).__dict__ - message_output_debug_turn_event_turn_event_search_model2 = MessageOutputDebugTurnEventTurnEventSearch(**message_output_debug_turn_event_turn_event_search_model_dict) + # Construct a model instance of MessageStreamResponseMessageStreamPartialItem by calling from_dict on the json representation + message_stream_response_message_stream_partial_item_model_dict = MessageStreamResponseMessageStreamPartialItem.from_dict(message_stream_response_message_stream_partial_item_model_json).__dict__ + message_stream_response_message_stream_partial_item_model2 = MessageStreamResponseMessageStreamPartialItem(**message_stream_response_message_stream_partial_item_model_dict) # Verify the model instances are equivalent - assert message_output_debug_turn_event_turn_event_search_model == message_output_debug_turn_event_turn_event_search_model2 + assert message_stream_response_message_stream_partial_item_model == message_stream_response_message_stream_partial_item_model2 # Convert model instance back to dict and verify no loss of data - message_output_debug_turn_event_turn_event_search_model_json2 = message_output_debug_turn_event_turn_event_search_model.to_dict() - assert message_output_debug_turn_event_turn_event_search_model_json2 == message_output_debug_turn_event_turn_event_search_model_json + message_stream_response_message_stream_partial_item_model_json2 = message_stream_response_message_stream_partial_item_model.to_dict() + assert message_stream_response_message_stream_partial_item_model_json2 == message_stream_response_message_stream_partial_item_model_json -class TestModel_MessageOutputDebugTurnEventTurnEventStepAnswered: +class TestModel_MessageStreamResponseStatefulMessageStreamFinalResponse: """ - Test Class for MessageOutputDebugTurnEventTurnEventStepAnswered + Test Class for MessageStreamResponseStatefulMessageStreamFinalResponse """ - def test_message_output_debug_turn_event_turn_event_step_answered_serialization(self): + def test_message_stream_response_stateful_message_stream_final_response_serialization(self): """ - Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventStepAnswered + Test serialization/deserialization for MessageStreamResponseStatefulMessageStreamFinalResponse """ # Construct dict forms of any model objects needed in order to build this model. + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + turn_event_action_source_model = {} # TurnEventActionSource turn_event_action_source_model['type'] = 'action' turn_event_action_source_model['action'] = 'testString' turn_event_action_source_model['action_title'] = 'testString' turn_event_action_source_model['condition'] = 'testString' - # Construct a json representation of a MessageOutputDebugTurnEventTurnEventStepAnswered model - message_output_debug_turn_event_turn_event_step_answered_model_json = {} - message_output_debug_turn_event_turn_event_step_answered_model_json['event'] = 'step_answered' - message_output_debug_turn_event_turn_event_step_answered_model_json['source'] = turn_event_action_source_model - message_output_debug_turn_event_turn_event_step_answered_model_json['condition_type'] = 'user_defined' - message_output_debug_turn_event_turn_event_step_answered_model_json['action_start_time'] = 'testString' - message_output_debug_turn_event_turn_event_step_answered_model_json['prompted'] = True + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' - # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepAnswered by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_step_answered_model = MessageOutputDebugTurnEventTurnEventStepAnswered.from_dict(message_output_debug_turn_event_turn_event_step_answered_model_json) - assert message_output_debug_turn_event_turn_event_step_answered_model != False + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] - # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepAnswered by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_step_answered_model_dict = MessageOutputDebugTurnEventTurnEventStepAnswered.from_dict(message_output_debug_turn_event_turn_event_step_answered_model_json).__dict__ - message_output_debug_turn_event_turn_event_step_answered_model2 = MessageOutputDebugTurnEventTurnEventStepAnswered(**message_output_debug_turn_event_turn_event_step_answered_model_dict) + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' - # Verify the model instances are equivalent - assert message_output_debug_turn_event_turn_event_step_answered_model == message_output_debug_turn_event_turn_event_step_answered_model2 + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' - # Convert model instance back to dict and verify no loss of data - message_output_debug_turn_event_turn_event_step_answered_model_json2 = message_output_debug_turn_event_turn_event_step_answered_model.to_dict() - assert message_output_debug_turn_event_turn_event_step_answered_model_json2 == message_output_debug_turn_event_turn_event_step_answered_model_json + metadata_model = {} # Metadata + metadata_model['id'] = 38 + message_stream_metadata_model = {} # MessageStreamMetadata + message_stream_metadata_model['streaming_metadata'] = metadata_model -class TestModel_MessageOutputDebugTurnEventTurnEventStepVisited: - """ - Test Class for MessageOutputDebugTurnEventTurnEventStepVisited - """ + final_response_output_model = {} # FinalResponseOutput + final_response_output_model['generic'] = [runtime_response_generic_model] + final_response_output_model['intents'] = [runtime_intent_model] + final_response_output_model['entities'] = [runtime_entity_model] + final_response_output_model['actions'] = [dialog_node_action_model] + final_response_output_model['debug'] = message_output_debug_model + final_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + final_response_output_model['spelling'] = message_output_spelling_model + final_response_output_model['llm_metadata'] = [message_output_llm_metadata_model] + final_response_output_model['streaming_metadata'] = message_stream_metadata_model + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + message_context_global_model = {} # MessageContextGlobal + message_context_global_model['system'] = message_context_global_system_model + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + message_context_action_skill_model = {} # MessageContextActionSkill + message_context_action_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['system'] = message_context_skill_system_model + message_context_action_skill_model['action_variables'] = {'anyKey': 'anyValue'} + message_context_action_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + + message_context_skills_model = {} # MessageContextSkills + message_context_skills_model['main skill'] = message_context_dialog_skill_model + message_context_skills_model['actions skill'] = message_context_action_skill_model + + message_context_model = {} # MessageContext + message_context_model['global'] = message_context_global_model + message_context_model['skills'] = message_context_skills_model + message_context_model['integrations'] = {'anyKey': 'anyValue'} + + message_output_model = {} # MessageOutput + message_output_model['generic'] = [runtime_response_generic_model] + message_output_model['intents'] = [runtime_intent_model] + message_output_model['entities'] = [runtime_entity_model] + message_output_model['actions'] = [dialog_node_action_model] + message_output_model['debug'] = message_output_debug_model + message_output_model['user_defined'] = {'anyKey': 'anyValue'} + message_output_model['spelling'] = message_output_spelling_model + message_output_model['llm_metadata'] = [message_output_llm_metadata_model] + + message_input_attachment_model = {} # MessageInputAttachment + message_input_attachment_model['url'] = 'testString' + message_input_attachment_model['media_type'] = 'testString' + + request_analytics_model = {} # RequestAnalytics + request_analytics_model['browser'] = 'testString' + request_analytics_model['device'] = 'testString' + request_analytics_model['pageUrl'] = 'testString' + + message_input_options_spelling_model = {} # MessageInputOptionsSpelling + message_input_options_spelling_model['suggestions'] = True + message_input_options_spelling_model['auto_correct'] = True - def test_message_output_debug_turn_event_turn_event_step_visited_serialization(self): - """ - Test serialization/deserialization for MessageOutputDebugTurnEventTurnEventStepVisited - """ + message_input_options_model = {} # MessageInputOptions + message_input_options_model['restart'] = False + message_input_options_model['alternate_intents'] = False + message_input_options_model['async_callout'] = False + message_input_options_model['spelling'] = message_input_options_spelling_model + message_input_options_model['debug'] = False + message_input_options_model['return_context'] = False + message_input_options_model['export'] = False - # Construct dict forms of any model objects needed in order to build this model. + message_input_model = {} # MessageInput + message_input_model['message_type'] = 'text' + message_input_model['text'] = 'testString' + message_input_model['intents'] = [runtime_intent_model] + message_input_model['entities'] = [runtime_entity_model] + message_input_model['suggestion_id'] = 'testString' + message_input_model['attachments'] = [message_input_attachment_model] + message_input_model['analytics'] = request_analytics_model + message_input_model['options'] = message_input_options_model - turn_event_action_source_model = {} # TurnEventActionSource - turn_event_action_source_model['type'] = 'action' - turn_event_action_source_model['action'] = 'testString' - turn_event_action_source_model['action_title'] = 'testString' - turn_event_action_source_model['condition'] = 'testString' + final_response_model = {} # FinalResponse + final_response_model['output'] = final_response_output_model + final_response_model['context'] = message_context_model + final_response_model['user_id'] = 'testString' + final_response_model['masked_output'] = message_output_model + final_response_model['masked_input'] = message_input_model - # Construct a json representation of a MessageOutputDebugTurnEventTurnEventStepVisited model - message_output_debug_turn_event_turn_event_step_visited_model_json = {} - message_output_debug_turn_event_turn_event_step_visited_model_json['event'] = 'step_visited' - message_output_debug_turn_event_turn_event_step_visited_model_json['source'] = turn_event_action_source_model - message_output_debug_turn_event_turn_event_step_visited_model_json['condition_type'] = 'user_defined' - message_output_debug_turn_event_turn_event_step_visited_model_json['action_start_time'] = 'testString' - message_output_debug_turn_event_turn_event_step_visited_model_json['has_question'] = True + # Construct a json representation of a MessageStreamResponseStatefulMessageStreamFinalResponse model + message_stream_response_stateful_message_stream_final_response_model_json = {} + message_stream_response_stateful_message_stream_final_response_model_json['final_response'] = final_response_model - # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepVisited by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_step_visited_model = MessageOutputDebugTurnEventTurnEventStepVisited.from_dict(message_output_debug_turn_event_turn_event_step_visited_model_json) - assert message_output_debug_turn_event_turn_event_step_visited_model != False + # Construct a model instance of MessageStreamResponseStatefulMessageStreamFinalResponse by calling from_dict on the json representation + message_stream_response_stateful_message_stream_final_response_model = MessageStreamResponseStatefulMessageStreamFinalResponse.from_dict(message_stream_response_stateful_message_stream_final_response_model_json) + assert message_stream_response_stateful_message_stream_final_response_model != False - # Construct a model instance of MessageOutputDebugTurnEventTurnEventStepVisited by calling from_dict on the json representation - message_output_debug_turn_event_turn_event_step_visited_model_dict = MessageOutputDebugTurnEventTurnEventStepVisited.from_dict(message_output_debug_turn_event_turn_event_step_visited_model_json).__dict__ - message_output_debug_turn_event_turn_event_step_visited_model2 = MessageOutputDebugTurnEventTurnEventStepVisited(**message_output_debug_turn_event_turn_event_step_visited_model_dict) + # Construct a model instance of MessageStreamResponseStatefulMessageStreamFinalResponse by calling from_dict on the json representation + message_stream_response_stateful_message_stream_final_response_model_dict = MessageStreamResponseStatefulMessageStreamFinalResponse.from_dict(message_stream_response_stateful_message_stream_final_response_model_json).__dict__ + message_stream_response_stateful_message_stream_final_response_model2 = MessageStreamResponseStatefulMessageStreamFinalResponse(**message_stream_response_stateful_message_stream_final_response_model_dict) # Verify the model instances are equivalent - assert message_output_debug_turn_event_turn_event_step_visited_model == message_output_debug_turn_event_turn_event_step_visited_model2 + assert message_stream_response_stateful_message_stream_final_response_model == message_stream_response_stateful_message_stream_final_response_model2 # Convert model instance back to dict and verify no loss of data - message_output_debug_turn_event_turn_event_step_visited_model_json2 = message_output_debug_turn_event_turn_event_step_visited_model.to_dict() - assert message_output_debug_turn_event_turn_event_step_visited_model_json2 == message_output_debug_turn_event_turn_event_step_visited_model_json + message_stream_response_stateful_message_stream_final_response_model_json2 = message_stream_response_stateful_message_stream_final_response_model.to_dict() + assert message_stream_response_stateful_message_stream_final_response_model_json2 == message_stream_response_stateful_message_stream_final_response_model_json class TestModel_ProviderAuthenticationOAuth2FlowsProviderAuthenticationOAuth2AuthorizationCode: @@ -13105,6 +15745,72 @@ def test_runtime_response_generic_runtime_response_type_connect_to_agent_seriali assert runtime_response_generic_runtime_response_type_connect_to_agent_model_json2 == runtime_response_generic_runtime_response_type_connect_to_agent_model_json +class TestModel_RuntimeResponseGenericRuntimeResponseTypeConversationalSearch: + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + """ + + def test_runtime_response_generic_runtime_response_type_conversational_search_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeConversationalSearch model + runtime_response_generic_runtime_response_type_conversational_search_model_json = {} + runtime_response_generic_runtime_response_type_conversational_search_model_json['response_type'] = 'conversation_search' + runtime_response_generic_runtime_response_type_conversational_search_model_json['text'] = 'testString' + runtime_response_generic_runtime_response_type_conversational_search_model_json['citations_title'] = 'testString' + runtime_response_generic_runtime_response_type_conversational_search_model_json['citations'] = [response_generic_citation_model] + runtime_response_generic_runtime_response_type_conversational_search_model_json['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_runtime_response_type_conversational_search_model_json['response_length_option'] = 'testString' + runtime_response_generic_runtime_response_type_conversational_search_model_json['search_results'] = [search_results_model] + runtime_response_generic_runtime_response_type_conversational_search_model_json['disclaimer'] = 'testString' + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeConversationalSearch by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_conversational_search_model = RuntimeResponseGenericRuntimeResponseTypeConversationalSearch.from_dict(runtime_response_generic_runtime_response_type_conversational_search_model_json) + assert runtime_response_generic_runtime_response_type_conversational_search_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeConversationalSearch by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_conversational_search_model_dict = RuntimeResponseGenericRuntimeResponseTypeConversationalSearch.from_dict(runtime_response_generic_runtime_response_type_conversational_search_model_json).__dict__ + runtime_response_generic_runtime_response_type_conversational_search_model2 = RuntimeResponseGenericRuntimeResponseTypeConversationalSearch(**runtime_response_generic_runtime_response_type_conversational_search_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_conversational_search_model == runtime_response_generic_runtime_response_type_conversational_search_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_conversational_search_model_json2 = runtime_response_generic_runtime_response_type_conversational_search_model.to_dict() + assert runtime_response_generic_runtime_response_type_conversational_search_model_json2 == runtime_response_generic_runtime_response_type_conversational_search_model_json + + class TestModel_RuntimeResponseGenericRuntimeResponseTypeDate: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeDate @@ -13697,6 +16403,315 @@ def test_runtime_response_generic_runtime_response_type_video_serialization(self assert runtime_response_generic_runtime_response_type_video_model_json2 == runtime_response_generic_runtime_response_type_video_model_json +class TestModel_StatelessMessageStreamResponseMessageStreamCompleteItem: + """ + Test Class for StatelessMessageStreamResponseMessageStreamCompleteItem + """ + + def test_stateless_message_stream_response_message_stream_complete_item_serialization(self): + """ + Test serialization/deserialization for StatelessMessageStreamResponseMessageStreamCompleteItem + """ + + # Construct dict forms of any model objects needed in order to build this model. + + metadata_model = {} # Metadata + metadata_model['id'] = 38 + + complete_item_model = {} # CompleteItem + complete_item_model['streaming_metadata'] = metadata_model + + # Construct a json representation of a StatelessMessageStreamResponseMessageStreamCompleteItem model + stateless_message_stream_response_message_stream_complete_item_model_json = {} + stateless_message_stream_response_message_stream_complete_item_model_json['complete_item'] = complete_item_model + + # Construct a model instance of StatelessMessageStreamResponseMessageStreamCompleteItem by calling from_dict on the json representation + stateless_message_stream_response_message_stream_complete_item_model = StatelessMessageStreamResponseMessageStreamCompleteItem.from_dict(stateless_message_stream_response_message_stream_complete_item_model_json) + assert stateless_message_stream_response_message_stream_complete_item_model != False + + # Construct a model instance of StatelessMessageStreamResponseMessageStreamCompleteItem by calling from_dict on the json representation + stateless_message_stream_response_message_stream_complete_item_model_dict = StatelessMessageStreamResponseMessageStreamCompleteItem.from_dict(stateless_message_stream_response_message_stream_complete_item_model_json).__dict__ + stateless_message_stream_response_message_stream_complete_item_model2 = StatelessMessageStreamResponseMessageStreamCompleteItem(**stateless_message_stream_response_message_stream_complete_item_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_stream_response_message_stream_complete_item_model == stateless_message_stream_response_message_stream_complete_item_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_stream_response_message_stream_complete_item_model_json2 = stateless_message_stream_response_message_stream_complete_item_model.to_dict() + assert stateless_message_stream_response_message_stream_complete_item_model_json2 == stateless_message_stream_response_message_stream_complete_item_model_json + + +class TestModel_StatelessMessageStreamResponseMessageStreamPartialItem: + """ + Test Class for StatelessMessageStreamResponseMessageStreamPartialItem + """ + + def test_stateless_message_stream_response_message_stream_partial_item_serialization(self): + """ + Test serialization/deserialization for StatelessMessageStreamResponseMessageStreamPartialItem + """ + + # Construct dict forms of any model objects needed in order to build this model. + + metadata_model = {} # Metadata + metadata_model['id'] = 38 + + partial_item_model = {} # PartialItem + partial_item_model['response_type'] = 'testString' + partial_item_model['text'] = 'testString' + partial_item_model['streaming_metadata'] = metadata_model + + # Construct a json representation of a StatelessMessageStreamResponseMessageStreamPartialItem model + stateless_message_stream_response_message_stream_partial_item_model_json = {} + stateless_message_stream_response_message_stream_partial_item_model_json['partial_item'] = partial_item_model + + # Construct a model instance of StatelessMessageStreamResponseMessageStreamPartialItem by calling from_dict on the json representation + stateless_message_stream_response_message_stream_partial_item_model = StatelessMessageStreamResponseMessageStreamPartialItem.from_dict(stateless_message_stream_response_message_stream_partial_item_model_json) + assert stateless_message_stream_response_message_stream_partial_item_model != False + + # Construct a model instance of StatelessMessageStreamResponseMessageStreamPartialItem by calling from_dict on the json representation + stateless_message_stream_response_message_stream_partial_item_model_dict = StatelessMessageStreamResponseMessageStreamPartialItem.from_dict(stateless_message_stream_response_message_stream_partial_item_model_json).__dict__ + stateless_message_stream_response_message_stream_partial_item_model2 = StatelessMessageStreamResponseMessageStreamPartialItem(**stateless_message_stream_response_message_stream_partial_item_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_stream_response_message_stream_partial_item_model == stateless_message_stream_response_message_stream_partial_item_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_stream_response_message_stream_partial_item_model_json2 = stateless_message_stream_response_message_stream_partial_item_model.to_dict() + assert stateless_message_stream_response_message_stream_partial_item_model_json2 == stateless_message_stream_response_message_stream_partial_item_model_json + + +class TestModel_StatelessMessageStreamResponseStatelessMessageStreamFinalResponse: + """ + Test Class for StatelessMessageStreamResponseStatelessMessageStreamFinalResponse + """ + + def test_stateless_message_stream_response_stateless_message_stream_final_response_serialization(self): + """ + Test serialization/deserialization for StatelessMessageStreamResponseStatelessMessageStreamFinalResponse + """ + + # Construct dict forms of any model objects needed in order to build this model. + + response_generic_citation_ranges_item_model = {} # ResponseGenericCitationRangesItem + response_generic_citation_ranges_item_model['start'] = 38 + response_generic_citation_ranges_item_model['end'] = 38 + + response_generic_citation_model = {} # ResponseGenericCitation + response_generic_citation_model['title'] = 'testString' + response_generic_citation_model['text'] = 'testString' + response_generic_citation_model['body'] = 'testString' + response_generic_citation_model['search_result_index'] = 38 + response_generic_citation_model['ranges'] = [response_generic_citation_ranges_item_model] + + response_generic_confidence_scores_model = {} # ResponseGenericConfidenceScores + response_generic_confidence_scores_model['threshold'] = 72.5 + response_generic_confidence_scores_model['pre_gen'] = 72.5 + response_generic_confidence_scores_model['post_gen'] = 72.5 + response_generic_confidence_scores_model['extractiveness'] = 72.5 + + search_results_result_metadata_model = {} # SearchResultsResultMetadata + search_results_result_metadata_model['document_retrieval_source'] = 'testString' + search_results_result_metadata_model['score'] = 38 + + search_results_model = {} # SearchResults + search_results_model['result_metadata'] = search_results_result_metadata_model + search_results_model['id'] = 'testString' + search_results_model['title'] = 'testString' + search_results_model['body'] = 'testString' + + runtime_response_generic_model = {} # RuntimeResponseGenericRuntimeResponseTypeConversationalSearch + runtime_response_generic_model['response_type'] = 'conversation_search' + runtime_response_generic_model['text'] = 'testString' + runtime_response_generic_model['citations_title'] = 'testString' + runtime_response_generic_model['citations'] = [response_generic_citation_model] + runtime_response_generic_model['confidence_scores'] = response_generic_confidence_scores_model + runtime_response_generic_model['response_length_option'] = 'testString' + runtime_response_generic_model['search_results'] = [search_results_model] + runtime_response_generic_model['disclaimer'] = 'testString' + + runtime_intent_model = {} # RuntimeIntent + runtime_intent_model['intent'] = 'testString' + runtime_intent_model['confidence'] = 72.5 + runtime_intent_model['skill'] = 'testString' + + capture_group_model = {} # CaptureGroup + capture_group_model['group'] = 'testString' + capture_group_model['location'] = [38] + + runtime_entity_interpretation_model = {} # RuntimeEntityInterpretation + runtime_entity_interpretation_model['calendar_type'] = 'testString' + runtime_entity_interpretation_model['datetime_link'] = 'testString' + runtime_entity_interpretation_model['festival'] = 'testString' + runtime_entity_interpretation_model['granularity'] = 'day' + runtime_entity_interpretation_model['range_link'] = 'testString' + runtime_entity_interpretation_model['range_modifier'] = 'testString' + runtime_entity_interpretation_model['relative_day'] = 72.5 + runtime_entity_interpretation_model['relative_month'] = 72.5 + runtime_entity_interpretation_model['relative_week'] = 72.5 + runtime_entity_interpretation_model['relative_weekend'] = 72.5 + runtime_entity_interpretation_model['relative_year'] = 72.5 + runtime_entity_interpretation_model['specific_day'] = 72.5 + runtime_entity_interpretation_model['specific_day_of_week'] = 'testString' + runtime_entity_interpretation_model['specific_month'] = 72.5 + runtime_entity_interpretation_model['specific_quarter'] = 72.5 + runtime_entity_interpretation_model['specific_year'] = 72.5 + runtime_entity_interpretation_model['numeric_value'] = 72.5 + runtime_entity_interpretation_model['subtype'] = 'testString' + runtime_entity_interpretation_model['part_of_day'] = 'testString' + runtime_entity_interpretation_model['relative_hour'] = 72.5 + runtime_entity_interpretation_model['relative_minute'] = 72.5 + runtime_entity_interpretation_model['relative_second'] = 72.5 + runtime_entity_interpretation_model['specific_hour'] = 72.5 + runtime_entity_interpretation_model['specific_minute'] = 72.5 + runtime_entity_interpretation_model['specific_second'] = 72.5 + runtime_entity_interpretation_model['timezone'] = 'testString' + + runtime_entity_alternative_model = {} # RuntimeEntityAlternative + runtime_entity_alternative_model['value'] = 'testString' + runtime_entity_alternative_model['confidence'] = 72.5 + + runtime_entity_role_model = {} # RuntimeEntityRole + runtime_entity_role_model['type'] = 'date_from' + + runtime_entity_model = {} # RuntimeEntity + runtime_entity_model['entity'] = 'testString' + runtime_entity_model['location'] = [38] + runtime_entity_model['value'] = 'testString' + runtime_entity_model['confidence'] = 72.5 + runtime_entity_model['groups'] = [capture_group_model] + runtime_entity_model['interpretation'] = runtime_entity_interpretation_model + runtime_entity_model['alternatives'] = [runtime_entity_alternative_model] + runtime_entity_model['role'] = runtime_entity_role_model + runtime_entity_model['skill'] = 'testString' + + dialog_node_action_model = {} # DialogNodeAction + dialog_node_action_model['name'] = 'testString' + dialog_node_action_model['type'] = 'client' + dialog_node_action_model['parameters'] = {'anyKey': 'anyValue'} + dialog_node_action_model['result_variable'] = 'testString' + dialog_node_action_model['credentials'] = 'testString' + + dialog_node_visited_model = {} # DialogNodeVisited + dialog_node_visited_model['dialog_node'] = 'testString' + dialog_node_visited_model['title'] = 'testString' + dialog_node_visited_model['conditions'] = 'testString' + + log_message_source_model = {} # LogMessageSourceDialogNode + log_message_source_model['type'] = 'dialog_node' + log_message_source_model['dialog_node'] = 'testString' + + dialog_log_message_model = {} # DialogLogMessage + dialog_log_message_model['level'] = 'info' + dialog_log_message_model['message'] = 'testString' + dialog_log_message_model['code'] = 'testString' + dialog_log_message_model['source'] = log_message_source_model + + turn_event_action_source_model = {} # TurnEventActionSource + turn_event_action_source_model['type'] = 'action' + turn_event_action_source_model['action'] = 'testString' + turn_event_action_source_model['action_title'] = 'testString' + turn_event_action_source_model['condition'] = 'testString' + + message_output_debug_turn_event_model = {} # MessageOutputDebugTurnEventTurnEventActionVisited + message_output_debug_turn_event_model['event'] = 'action_visited' + message_output_debug_turn_event_model['source'] = turn_event_action_source_model + message_output_debug_turn_event_model['action_start_time'] = 'testString' + message_output_debug_turn_event_model['condition_type'] = 'user_defined' + message_output_debug_turn_event_model['reason'] = 'intent' + message_output_debug_turn_event_model['result_variable'] = 'testString' + + message_output_debug_model = {} # MessageOutputDebug + message_output_debug_model['nodes_visited'] = [dialog_node_visited_model] + message_output_debug_model['log_messages'] = [dialog_log_message_model] + message_output_debug_model['branch_exited'] = True + message_output_debug_model['branch_exited_reason'] = 'completed' + message_output_debug_model['turn_events'] = [message_output_debug_turn_event_model] + + message_output_spelling_model = {} # MessageOutputSpelling + message_output_spelling_model['text'] = 'testString' + message_output_spelling_model['original_text'] = 'testString' + message_output_spelling_model['suggested_text'] = 'testString' + + message_output_llm_metadata_model = {} # MessageOutputLLMMetadata + message_output_llm_metadata_model['task'] = 'testString' + message_output_llm_metadata_model['model_id'] = 'testString' + + message_context_global_system_model = {} # MessageContextGlobalSystem + message_context_global_system_model['timezone'] = 'testString' + message_context_global_system_model['user_id'] = 'testString' + message_context_global_system_model['turn_count'] = 38 + message_context_global_system_model['locale'] = 'en-us' + message_context_global_system_model['reference_time'] = 'testString' + message_context_global_system_model['session_start_time'] = 'testString' + message_context_global_system_model['state'] = 'testString' + message_context_global_system_model['skip_user_input'] = True + + stateless_message_context_global_model = {} # StatelessMessageContextGlobal + stateless_message_context_global_model['system'] = message_context_global_system_model + stateless_message_context_global_model['session_id'] = 'testString' + + message_context_skill_system_model = {} # MessageContextSkillSystem + message_context_skill_system_model['state'] = 'testString' + message_context_skill_system_model['foo'] = 'testString' + + message_context_dialog_skill_model = {} # MessageContextDialogSkill + message_context_dialog_skill_model['user_defined'] = {'anyKey': 'anyValue'} + message_context_dialog_skill_model['system'] = message_context_skill_system_model + + stateless_message_context_skills_actions_skill_model = {} # StatelessMessageContextSkillsActionsSkill + stateless_message_context_skills_actions_skill_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['system'] = message_context_skill_system_model + stateless_message_context_skills_actions_skill_model['action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['skill_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_action_variables'] = {'anyKey': 'anyValue'} + stateless_message_context_skills_actions_skill_model['private_skill_variables'] = {'anyKey': 'anyValue'} + + stateless_message_context_skills_model = {} # StatelessMessageContextSkills + stateless_message_context_skills_model['main skill'] = message_context_dialog_skill_model + stateless_message_context_skills_model['actions skill'] = stateless_message_context_skills_actions_skill_model + + stateless_message_context_model = {} # StatelessMessageContext + stateless_message_context_model['global'] = stateless_message_context_global_model + stateless_message_context_model['skills'] = stateless_message_context_skills_model + stateless_message_context_model['integrations'] = {'anyKey': 'anyValue'} + + stateless_final_response_output_model = {} # StatelessFinalResponseOutput + stateless_final_response_output_model['generic'] = [runtime_response_generic_model] + stateless_final_response_output_model['intents'] = [runtime_intent_model] + stateless_final_response_output_model['entities'] = [runtime_entity_model] + stateless_final_response_output_model['actions'] = [dialog_node_action_model] + stateless_final_response_output_model['debug'] = message_output_debug_model + stateless_final_response_output_model['user_defined'] = {'anyKey': 'anyValue'} + stateless_final_response_output_model['spelling'] = message_output_spelling_model + stateless_final_response_output_model['llm_metadata'] = [message_output_llm_metadata_model] + stateless_final_response_output_model['streaming_metadata'] = stateless_message_context_model + + stateless_final_response_model = {} # StatelessFinalResponse + stateless_final_response_model['output'] = stateless_final_response_output_model + stateless_final_response_model['context'] = stateless_message_context_model + stateless_final_response_model['user_id'] = 'testString' + + # Construct a json representation of a StatelessMessageStreamResponseStatelessMessageStreamFinalResponse model + stateless_message_stream_response_stateless_message_stream_final_response_model_json = {} + stateless_message_stream_response_stateless_message_stream_final_response_model_json['final_response'] = stateless_final_response_model + + # Construct a model instance of StatelessMessageStreamResponseStatelessMessageStreamFinalResponse by calling from_dict on the json representation + stateless_message_stream_response_stateless_message_stream_final_response_model = StatelessMessageStreamResponseStatelessMessageStreamFinalResponse.from_dict(stateless_message_stream_response_stateless_message_stream_final_response_model_json) + assert stateless_message_stream_response_stateless_message_stream_final_response_model != False + + # Construct a model instance of StatelessMessageStreamResponseStatelessMessageStreamFinalResponse by calling from_dict on the json representation + stateless_message_stream_response_stateless_message_stream_final_response_model_dict = StatelessMessageStreamResponseStatelessMessageStreamFinalResponse.from_dict(stateless_message_stream_response_stateless_message_stream_final_response_model_json).__dict__ + stateless_message_stream_response_stateless_message_stream_final_response_model2 = StatelessMessageStreamResponseStatelessMessageStreamFinalResponse(**stateless_message_stream_response_stateless_message_stream_final_response_model_dict) + + # Verify the model instances are equivalent + assert stateless_message_stream_response_stateless_message_stream_final_response_model == stateless_message_stream_response_stateless_message_stream_final_response_model2 + + # Convert model instance back to dict and verify no loss of data + stateless_message_stream_response_stateless_message_stream_final_response_model_json2 = stateless_message_stream_response_stateless_message_stream_final_response_model.to_dict() + assert stateless_message_stream_response_stateless_message_stream_final_response_model_json2 == stateless_message_stream_response_stateless_message_stream_final_response_model_json + + # endregion ############################################################################## # End of Model Tests From 88dfd02357fd5a616a7312fa524c70e8bb8eb794 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 16 Jun 2025 12:47:32 -0500 Subject: [PATCH 443/455] chore: update wa-v2 service name --- ibm_watson/assistant_v2.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index fec430c07..23d9b197c 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -49,7 +49,7 @@ class AssistantV2(BaseService): """The Assistant V2 service.""" DEFAULT_SERVICE_URL = 'https://api.us-south.assistant.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'conversation' + DEFAULT_SERVICE_NAME = 'assistant' def __init__( self, From f4f2ba9061fce42541e09177f057658979038be7 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 8 Oct 2025 13:02:50 -0500 Subject: [PATCH 444/455] feat(wa-v2): add environmentId param to sessions functions BREAKING CHANGE: `assistantId` and `environmentId` are now required parameters for the `createSession` and `deleteSession` functions --- ibm_watson/assistant_v2.py | 402 +++++++++------------------------ test/unit/test_assistant_v2.py | 44 ++-- 2 files changed, 137 insertions(+), 309 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 23d9b197c..0e546f825 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -427,19 +427,10 @@ def delete_assistant( Delete an assistant. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -485,6 +476,7 @@ def delete_assistant( def create_session( self, assistant_id: str, + environment_id: str, *, analytics: Optional['RequestAnalytics'] = None, **kwargs, @@ -498,19 +490,14 @@ def create_session( information, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings).). - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. :param RequestAnalytics analytics: (optional) An optional object containing analytics data. Currently, this data is used only for events sent to the Segment extension. @@ -521,6 +508,8 @@ def create_session( if not assistant_id: raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') if analytics is not None: analytics = convert_model(analytics) headers = {} @@ -547,10 +536,11 @@ def create_session( del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id'] - path_param_values = self.encode_path_vars(assistant_id) + path_param_keys = ['assistant_id', 'environment_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/sessions'.format(**path_param_dict) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/sessions'.format( + **path_param_dict) request = self.prepare_request( method='POST', url=url, @@ -565,6 +555,7 @@ def create_session( def delete_session( self, assistant_id: str, + environment_id: str, session_id: str, **kwargs, ) -> DetailedResponse: @@ -575,19 +566,14 @@ def delete_session( session inactivity timeout, see the [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-assistant-settings)). - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. + :param str environment_id: Unique identifier of the environment. To find + the environment ID in the watsonx Assistant user interface, open the + environment settings and click **API Details**. **Note:** Currently, the + API does not support creating environments. :param str session_id: Unique identifier of the session. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -596,6 +582,8 @@ def delete_session( if not assistant_id: raise ValueError('assistant_id must be provided') + if not environment_id: + raise ValueError('environment_id must be provided') if not session_id: raise ValueError('session_id must be provided') headers = {} @@ -615,10 +603,11 @@ def delete_session( del kwargs['headers'] headers['Accept'] = 'application/json' - path_param_keys = ['assistant_id', 'session_id'] - path_param_values = self.encode_path_vars(assistant_id, session_id) + path_param_keys = ['assistant_id', 'environment_id', 'session_id'] + path_param_values = self.encode_path_vars(assistant_id, environment_id, + session_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/sessions/{session_id}'.format( + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/sessions/{session_id}'.format( **path_param_dict) request = self.prepare_request( method='DELETE', @@ -874,19 +863,10 @@ def message_stream( state (including context data) stored by watsonx Assistant for the duration of the session. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -984,19 +964,10 @@ def message_stream_stateless( Send user input to an assistant and receive a response, with conversation state (including context data) managed by your application. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -1323,19 +1294,10 @@ def list_environments( List the environments associated with an assistant. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param int page_limit: (optional) The number of records to return in each page of results. :param bool include_count: (optional) Whether to include information about @@ -1407,19 +1369,10 @@ def get_environment( Get information about an environment. For more information about environments, see [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -1487,19 +1440,10 @@ def update_environment( environments, see [Environments](https://cloud.ibm.com/docs/watson-assistant?topic=watson-assistant-publish-overview#environments). - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -1588,19 +1532,10 @@ def create_release( the draft environment. (In the watsonx Assistant user interface, a release is called a *version*.). - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str description: (optional) The description of the release. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1665,19 +1600,10 @@ def list_releases( List the releases associated with an assistant. (In the watsonx Assistant user interface, a release is called a *version*.). - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param int page_limit: (optional) The number of records to return in each page of results. :param bool include_count: (optional) Whether to include information about @@ -1751,19 +1677,10 @@ def get_release( request again and checking the value of the **status** property. When processing has completed, the request returns the release data. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str release: Unique identifier of the release. :param bool include_audit: (optional) Whether to include the audit properties (`created` and `updated` timestamps) in the response. @@ -1821,19 +1738,10 @@ def delete_release( Delete a release. (In the watsonx Assistant user interface, a release is called a *version*.). - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str release: Unique identifier of the release. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1891,19 +1799,10 @@ def deploy_release( Update the environment with the content of the release. All snapshots saved as part of the release become active in the environment. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str release: Unique identifier of the release. :param str environment_id: The environment ID of the environment where the release is to be deployed. @@ -1981,19 +1880,10 @@ def create_release_export( the artifact. Once the artifact has been created, it will last for the duration (/scope) of the release. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str release: Unique identifier of the release. :param bool include_audit: (optional) Whether to include the audit properties (`created` and `updated` timestamps) in the response. @@ -2067,19 +1957,10 @@ def download_release_export( the contents of the Zip file artifact and individually import the skill JSONs via skill update endpoints.. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str release: Unique identifier of the release. :param str accept: (optional) The type of the response: application/json or application/octet-stream. @@ -2157,19 +2038,10 @@ def create_release_import( created, you may poll the completion of the import via the "Get release import Status" endpoint. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param BinaryIO body: Request body is an Octet-stream of the artifact Zip file that is being imported. :param bool include_audit: (optional) Whether to include the audit @@ -2232,19 +2104,10 @@ def get_release_import_status( Monitor the status of an assistant release import. You may poll this endpoint until the status of the import has either succeeded or failed. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :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 @@ -2301,19 +2164,10 @@ def get_skill( Get information about a skill. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str skill_id: Unique identifier of the skill. To find the action or dialog skill ID in the watsonx Assistant user interface, open the skill settings and click **API Details**. To find the search skill ID, use the @@ -2380,19 +2234,10 @@ def update_skill( update by calling the **Get skill** method and checking the value of the **status** property. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str skill_id: Unique identifier of the skill. To find the action or dialog skill ID in the watsonx Assistant user interface, open the skill settings and click **API Details**. To find the search skill ID, use the @@ -2489,19 +2334,10 @@ def export_skills( When processing has completed, the request returns the exported JSON data. Remember that the usual rate limits apply. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :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 @@ -2567,19 +2403,10 @@ def import_skills( check the status of the asynchronous import operation, use the **Get status of skills import** method. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param List[SkillImport] assistant_skills: An array of objects describing the skills for the assistant. Included in responses only if **status**=`Available`. @@ -2653,19 +2480,10 @@ def import_skills_status( Retrieve the status of an asynchronous import operation previously initiated by using the **Import skills** method. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SkillsAsyncRequestStatus` object diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index a59ad0d83..21613a15d 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -949,7 +949,7 @@ def test_create_session_all_params(self): create_session() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions') + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions') mock_response = '{"session_id": "session_id"}' responses.add( responses.POST, @@ -967,11 +967,13 @@ def test_create_session_all_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' analytics = request_analytics_model # Invoke method response = _service.create_session( assistant_id, + environment_id, analytics=analytics, headers={}, ) @@ -998,7 +1000,7 @@ def test_create_session_required_params(self): test_create_session_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions') + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions') mock_response = '{"session_id": "session_id"}' responses.add( responses.POST, @@ -1010,10 +1012,12 @@ def test_create_session_required_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' # Invoke method response = _service.create_session( assistant_id, + environment_id, headers={}, ) @@ -1036,7 +1040,7 @@ def test_create_session_value_error(self): test_create_session_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions') + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions') mock_response = '{"session_id": "session_id"}' responses.add( responses.POST, @@ -1048,10 +1052,12 @@ def test_create_session_value_error(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "environment_id": environment_id, } for param in req_param_dict.keys(): req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} @@ -1079,7 +1085,7 @@ def test_delete_session_all_params(self): delete_session() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions/testString') + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString') responses.add( responses.DELETE, url, @@ -1088,11 +1094,13 @@ def test_delete_session_all_params(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' session_id = 'testString' # Invoke method response = _service.delete_session( assistant_id, + environment_id, session_id, headers={}, ) @@ -1116,7 +1124,7 @@ def test_delete_session_value_error(self): test_delete_session_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions/testString') + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString') responses.add( responses.DELETE, url, @@ -1125,11 +1133,13 @@ def test_delete_session_value_error(self): # Set up parameter values assistant_id = 'testString' + environment_id = 'testString' session_id = 'testString' # Pass in all but one required param and check for a ValueError req_param_dict = { "assistant_id": assistant_id, + "environment_id": environment_id, "session_id": session_id, } for param in req_param_dict.keys(): @@ -1169,7 +1179,7 @@ def test_message_all_params(self): message() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions/testString/message') + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message') mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' responses.add( responses.POST, @@ -1363,7 +1373,7 @@ def test_message_required_params(self): test_message_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions/testString/message') + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message') mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' responses.add( responses.POST, @@ -1405,7 +1415,7 @@ def test_message_value_error(self): test_message_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/sessions/testString/message') + url = preprocess_url('/v2/assistants/testString/environments/testString/sessions/testString/message') mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "user_id": "user_id", "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}}' responses.add( responses.POST, @@ -1452,7 +1462,7 @@ def test_message_stateless_all_params(self): message_stateless() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/message') + url = preprocess_url('/v2/assistants/testString/environments/testString/message') mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' responses.add( responses.POST, @@ -1645,7 +1655,7 @@ def test_message_stateless_required_params(self): test_message_stateless_required_params() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/message') + url = preprocess_url('/v2/assistants/testString/environments/testString/message') mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' responses.add( responses.POST, @@ -1685,7 +1695,7 @@ def test_message_stateless_value_error(self): test_message_stateless_value_error() """ # Set up mock - url = preprocess_url('/v2/assistants/testString/message') + url = preprocess_url('/v2/assistants/testString/environments/testString/message') mock_response = '{"output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "context": {"global": {"system": {"timezone": "timezone", "user_id": "user_id", "turn_count": 10, "locale": "en-us", "reference_time": "reference_time", "session_start_time": "session_start_time", "state": "state", "skip_user_input": false}, "session_id": "session_id"}, "skills": {"main skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}}, "actions skill": {"user_defined": {"anyKey": "anyValue"}, "system": {"state": "state"}, "action_variables": {"anyKey": "anyValue"}, "skill_variables": {"anyKey": "anyValue"}, "private_action_variables": {"anyKey": "anyValue"}, "private_skill_variables": {"anyKey": "anyValue"}}}, "integrations": {"anyKey": "anyValue"}}, "masked_output": {"generic": [{"response_type": "conversation_search", "text": "text", "citations_title": "citations_title", "citations": [{"title": "title", "text": "text", "body": "body", "search_result_index": 19, "ranges": [{"start": 5, "end": 3}]}], "confidence_scores": {"threshold": 9, "pre_gen": 7, "post_gen": 8, "extractiveness": 14}, "response_length_option": "response_length_option", "search_results": [{"result_metadata": {"document_retrieval_source": "document_retrieval_source", "score": 5}, "id": "id", "title": "title", "body": "body"}], "disclaimer": "disclaimer"}], "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "actions": [{"name": "name", "type": "client", "parameters": {"anyKey": "anyValue"}, "result_variable": "result_variable", "credentials": "credentials"}], "debug": {"nodes_visited": [{"dialog_node": "dialog_node", "title": "title", "conditions": "conditions"}], "log_messages": [{"level": "info", "message": "message", "code": "code", "source": {"type": "dialog_node", "dialog_node": "dialog_node"}}], "branch_exited": false, "branch_exited_reason": "completed", "turn_events": [{"event": "action_visited", "source": {"type": "action", "action": "action", "action_title": "action_title", "condition": "condition"}, "action_start_time": "action_start_time", "condition_type": "user_defined", "reason": "intent", "result_variable": "result_variable"}]}, "user_defined": {"anyKey": "anyValue"}, "spelling": {"text": "text", "original_text": "original_text", "suggested_text": "suggested_text"}, "llm_metadata": [{"task": "task", "model_id": "model_id"}]}, "masked_input": {"message_type": "text", "text": "text", "intents": [{"intent": "intent", "confidence": 10, "skill": "skill"}], "entities": [{"entity": "entity", "location": [8], "value": "value", "confidence": 10, "groups": [{"group": "group", "location": [8]}], "interpretation": {"calendar_type": "calendar_type", "datetime_link": "datetime_link", "festival": "festival", "granularity": "day", "range_link": "range_link", "range_modifier": "range_modifier", "relative_day": 12, "relative_month": 14, "relative_week": 13, "relative_weekend": 16, "relative_year": 13, "specific_day": 12, "specific_day_of_week": "specific_day_of_week", "specific_month": 14, "specific_quarter": 16, "specific_year": 13, "numeric_value": 13, "subtype": "subtype", "part_of_day": "part_of_day", "relative_hour": 13, "relative_minute": 15, "relative_second": 15, "specific_hour": 13, "specific_minute": 15, "specific_second": 15, "timezone": "timezone"}, "alternatives": [{"value": "value", "confidence": 10}], "role": {"type": "date_from"}, "skill": "skill"}], "suggestion_id": "suggestion_id", "attachments": [{"url": "url", "media_type": "media_type"}], "analytics": {"browser": "browser", "device": "device", "pageUrl": "page_url"}, "options": {"restart": false, "alternate_intents": false, "async_callout": false, "spelling": {"suggestions": false, "auto_correct": true}, "debug": false, "return_context": false, "export": false}}, "user_id": "user_id"}' responses.add( responses.POST, @@ -13788,9 +13798,9 @@ def test_turn_event_generative_ai_called_metrics_serialization(self): # Construct a json representation of a TurnEventGenerativeAICalledMetrics model turn_event_generative_ai_called_metrics_model_json = {} - turn_event_generative_ai_called_metrics_model_json['search_time_ms'] = 'unknown type: float' - turn_event_generative_ai_called_metrics_model_json['answer_generation_time_ms'] = 'unknown type: float' - turn_event_generative_ai_called_metrics_model_json['total_time_ms'] = 'unknown type: float' + turn_event_generative_ai_called_metrics_model_json['search_time_ms'] = 72.5 + turn_event_generative_ai_called_metrics_model_json['answer_generation_time_ms'] = 72.5 + turn_event_generative_ai_called_metrics_model_json['total_time_ms'] = 72.5 # Construct a model instance of TurnEventGenerativeAICalledMetrics by calling from_dict on the json representation turn_event_generative_ai_called_metrics_model = TurnEventGenerativeAICalledMetrics.from_dict(turn_event_generative_ai_called_metrics_model_json) @@ -14562,9 +14572,9 @@ def test_message_output_debug_turn_event_turn_event_generative_ai_called_seriali turn_event_generative_ai_called_callout_model['idk_reason_code'] = 'testString' turn_event_generative_ai_called_metrics_model = {} # TurnEventGenerativeAICalledMetrics - turn_event_generative_ai_called_metrics_model['search_time_ms'] = 'unknown type: float' - turn_event_generative_ai_called_metrics_model['answer_generation_time_ms'] = 'unknown type: float' - turn_event_generative_ai_called_metrics_model['total_time_ms'] = 'unknown type: float' + turn_event_generative_ai_called_metrics_model['search_time_ms'] = 72.5 + turn_event_generative_ai_called_metrics_model['answer_generation_time_ms'] = 72.5 + turn_event_generative_ai_called_metrics_model['total_time_ms'] = 72.5 # Construct a json representation of a MessageOutputDebugTurnEventTurnEventGenerativeAICalled model message_output_debug_turn_event_turn_event_generative_ai_called_model_json = {} From 49851cac29258cd83153aa975f2899bfdaba7b4f Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 8 Oct 2025 13:05:26 -0500 Subject: [PATCH 445/455] fix(wa-v2): fix missing path parameter in HTTP request creation for message functions --- ibm_watson/assistant_v2.py | 39 +++++++++++--------------------------- 1 file changed, 11 insertions(+), 28 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 0e546f825..32d898abb 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -641,19 +641,10 @@ def message( (including context data) stored by watsonx Assistant for the duration of the session. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -722,7 +713,7 @@ def message( path_param_values = self.encode_path_vars(assistant_id, environment_id, session_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/sessions/{session_id}/message'.format( + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/sessions/{session_id}/message'.format( **path_param_dict) request = self.prepare_request( method='POST', @@ -751,19 +742,10 @@ def message_stateless( Send user input to an assistant and receive a response, with conversation state (including context data) managed by your application. - :param str assistant_id: The assistant ID or the environment ID of the - environment where the assistant is deployed. - Set the value for this ID depending on the type of request: - - For message, session, and log requests, specify the environment ID of - the environment where the assistant is deployed. - - For all other requests, specify the assistant ID of the assistant. - To get the **assistant ID** and **environment ID** in the watsonx - Assistant interface, open the **Assistant settings** page, and scroll to - the **Assistant IDs and API details** section and click **View Details**. - **Note:** If you are using the classic Watson Assistant experience, always - use the assistant ID. - To find the **assistant ID** in the user interface, open the **Assistant - settings** and click **API Details**. + :param str assistant_id: Unique identifier of the assistant. To get the + **assistant ID** in the watsonx Assistant interface, open the **Assistant + settings** page, and scroll to the **Assistant IDs and API details** + section and click **View Details**. :param str environment_id: Unique identifier of the environment. To find the environment ID in the watsonx Assistant user interface, open the environment settings and click **API Details**. **Note:** Currently, the @@ -829,7 +811,8 @@ def message_stateless( path_param_keys = ['assistant_id', 'environment_id'] path_param_values = self.encode_path_vars(assistant_id, environment_id) path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v2/assistants/{assistant_id}/message'.format(**path_param_dict) + url = '/v2/assistants/{assistant_id}/environments/{environment_id}/message'.format( + **path_param_dict) request = self.prepare_request( method='POST', url=url, From 2142ab0516da49d043eae835ef61cd5c433c647f Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 10 Oct 2025 11:40:51 -0500 Subject: [PATCH 446/455] ci(deploy): fix automated release process --- .bumpversion.cfg | 2 +- .github/workflows/deploy.yml | 8 +++----- ibm_watson/version.py | 2 +- setup.py | 2 +- 4 files changed, 6 insertions(+), 8 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 654bd4b5a..8edc96571 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 9.0.0 +current_version = 10.0.0 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 3b58867e7..781cee26a 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -67,11 +67,9 @@ jobs: - name: Build binary wheel and a source tarball run: | pip3 install setuptools wheel twine build - python -m build --sdist --outdir dist/ + python setup.py sdist - - name: Publish distribution to Test PyPI - continue-on-error: true - uses: pypa/gh-action-pypi-publish@v1.4.2 # Try to update version tag every release + - name: Publish package distributions to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 with: password: ${{ secrets.PYPI_TOKEN }} - repository_url: https://upload.pypi.org/legacy/ # This must be changed if testing deploys to test.pypi.org diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 33de8d16f..2e568bf45 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '9.0.0' +__version__ = '10.0.0' diff --git a/setup.py b/setup.py index 9fd6acf31..566a960de 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '9.0.0' +__version__ = '10.0.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From b291b5348722d7c2e514196b620911b93addf348 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 10 Nov 2025 11:57:12 -0600 Subject: [PATCH 447/455] feat(tts): add new voice models --- ibm_watson/text_to_speech_v1.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 5cdac13f3..7748b75b1 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1808,22 +1808,29 @@ class Voice(str, Enum): DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' + EN_CA_HANNAHNATURAL = 'en-CA_HannahNatural' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_CHLOENATURAL = 'en-GB_ChloeNatural' EN_GB_GEORGEEXPRESSIVE = 'en-GB_GeorgeExpressive' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' + EN_GB_GEORGENATURAL = 'en-GB_GeorgeNatural' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_ELLIENATURAL = 'en-US_EllieNatural' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' + EN_US_EMMANATURAL = 'en-US_EmmaNatural' + EN_US_ETHANNATURAL = 'en-US_EthanNatural' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' + EN_US_JACKSONNATURAL = 'en-US_JacksonNatural' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' + EN_US_VICTORIANATURAL = 'en-US_VictoriaNatural' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' ES_LA_DANIELAEXPRESSIVE = 'es-LA_DanielaExpressive' @@ -1836,8 +1843,10 @@ class Voice(str, Enum): JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' + PT_BR_CAMILANATURAL = 'pt-BR_CamilaNatural' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' PT_BR_LUCASEXPRESSIVE = 'pt-BR_LucasExpressive' + PT_BR_LUCASNATURAL = 'pt-BR_LucasNatural' class SynthesizeEnums: @@ -1887,22 +1896,29 @@ class Voice(str, Enum): DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' + EN_CA_HANNAHNATURAL = 'en-CA_HannahNatural' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_CHLOENATURAL = 'en-GB_ChloeNatural' EN_GB_GEORGEEXPRESSIVE = 'en-GB_GeorgeExpressive' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' + EN_GB_GEORGENATURAL = 'en-GB_GeorgeNatural' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_ELLIENATURAL = 'en-US_EllieNatural' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' + EN_US_EMMANATURAL = 'en-US_EmmaNatural' + EN_US_ETHANNATURAL = 'en-US_EthanNatural' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' + EN_US_JACKSONNATURAL = 'en-US_JacksonNatural' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' + EN_US_VICTORIANATURAL = 'en-US_VictoriaNatural' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' ES_LA_DANIELAEXPRESSIVE = 'es-LA_DanielaExpressive' @@ -1915,8 +1931,10 @@ class Voice(str, Enum): JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' + PT_BR_CAMILANATURAL = 'pt-BR_CamilaNatural' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' PT_BR_LUCASEXPRESSIVE = 'pt-BR_LucasExpressive' + PT_BR_LUCASNATURAL = 'pt-BR_LucasNatural' class SpellOutMode(str, Enum): """ @@ -1965,22 +1983,29 @@ class Voice(str, Enum): DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' EN_AU_HEIDIEXPRESSIVE = 'en-AU_HeidiExpressive' EN_AU_JACKEXPRESSIVE = 'en-AU_JackExpressive' + EN_CA_HANNAHNATURAL = 'en-CA_HannahNatural' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' + EN_GB_CHLOENATURAL = 'en-GB_ChloeNatural' EN_GB_GEORGEEXPRESSIVE = 'en-GB_GeorgeExpressive' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' + EN_GB_GEORGENATURAL = 'en-GB_GeorgeNatural' EN_GB_KATEV3VOICE = 'en-GB_KateV3Voice' EN_US_ALLISONEXPRESSIVE = 'en-US_AllisonExpressive' EN_US_ALLISONV3VOICE = 'en-US_AllisonV3Voice' EN_US_ELLIENATURAL = 'en-US_EllieNatural' EN_US_EMILYV3VOICE = 'en-US_EmilyV3Voice' EN_US_EMMAEXPRESSIVE = 'en-US_EmmaExpressive' + EN_US_EMMANATURAL = 'en-US_EmmaNatural' + EN_US_ETHANNATURAL = 'en-US_EthanNatural' EN_US_HENRYV3VOICE = 'en-US_HenryV3Voice' + EN_US_JACKSONNATURAL = 'en-US_JacksonNatural' EN_US_KEVINV3VOICE = 'en-US_KevinV3Voice' EN_US_LISAEXPRESSIVE = 'en-US_LisaExpressive' EN_US_LISAV3VOICE = 'en-US_LisaV3Voice' EN_US_MICHAELEXPRESSIVE = 'en-US_MichaelExpressive' EN_US_MICHAELV3VOICE = 'en-US_MichaelV3Voice' EN_US_OLIVIAV3VOICE = 'en-US_OliviaV3Voice' + EN_US_VICTORIANATURAL = 'en-US_VictoriaNatural' ES_ES_ENRIQUEV3VOICE = 'es-ES_EnriqueV3Voice' ES_ES_LAURAV3VOICE = 'es-ES_LauraV3Voice' ES_LA_DANIELAEXPRESSIVE = 'es-LA_DanielaExpressive' @@ -1993,8 +2018,10 @@ class Voice(str, Enum): JA_JP_EMIV3VOICE = 'ja-JP_EmiV3Voice' KO_KR_JINV3VOICE = 'ko-KR_JinV3Voice' NL_NL_MERELV3VOICE = 'nl-NL_MerelV3Voice' + PT_BR_CAMILANATURAL = 'pt-BR_CamilaNatural' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' PT_BR_LUCASEXPRESSIVE = 'pt-BR_LucasExpressive' + PT_BR_LUCASNATURAL = 'pt-BR_LucasNatural' class Format(str, Enum): """ From 99d4fdd1e7f0761e633a2ce31f3a1d1bb16110aa Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 10 Nov 2025 11:57:39 -0600 Subject: [PATCH 448/455] feat(stt): add new sad_module param to recognize functions --- ibm_watson/speech_to_text_v1.py | 21 +++++++++++++++++++-- ibm_watson/speech_to_text_v1_adapter.py | 8 ++++++++ test/unit/test_speech_to_text_v1.py | 8 +++++++- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 1f413afb7..64e600645 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -218,6 +218,7 @@ def recognize( end_of_phrase_silence_time: Optional[float] = None, split_transcript_at_phrase_end: Optional[bool] = None, speech_detector_sensitivity: Optional[float] = None, + sad_module: Optional[int] = None, background_audio_suppression: Optional[float] = None, low_latency: Optional[bool] = None, character_insertion_bias: Optional[float] = None, @@ -351,8 +352,9 @@ def recognize( activity is detected in the stream. This can be used both in standard and low latency mode. This feature enables client applications to know that some words/speech has been detected and the service is in the process of - decoding. This can be used in lieu of interim results in standard mode. See - [Using speech recognition + decoding. This can be used in lieu of interim results in standard mode. Use + `sad_module: 2` to increase accuracy and performance in detecting speech + boundaries within the audio stream. See [Using speech recognition parameters](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-service-features#features-parameters). :param str language_customization_id: (optional) The customization ID (GUID) of a custom language model that is to be used with the recognition @@ -555,6 +557,12 @@ def recognize( sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) and [Language model support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). + :param int sad_module: (optional) Detects speech boundaries within the + audio stream with better performance, improved noise suppression, faster + responsiveness, and increased accuracy. + Specify `sad_module: 2` + See [Speech Activity Detection + (SAD)](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#sad). :param float background_audio_suppression: (optional) The level to which the service is to suppress background audio based on its volume to prevent it from being transcribed as speech. Use the parameter to suppress side @@ -647,6 +655,7 @@ def recognize( 'end_of_phrase_silence_time': end_of_phrase_silence_time, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, + 'sad_module': sad_module, 'background_audio_suppression': background_audio_suppression, 'low_latency': low_latency, 'character_insertion_bias': character_insertion_bias, @@ -845,6 +854,7 @@ def create_job( end_of_phrase_silence_time: Optional[float] = None, split_transcript_at_phrase_end: Optional[bool] = None, speech_detector_sensitivity: Optional[float] = None, + sad_module: Optional[int] = None, background_audio_suppression: Optional[float] = None, low_latency: Optional[bool] = None, character_insertion_bias: Optional[float] = None, @@ -1244,6 +1254,12 @@ def create_job( sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) and [Language model support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). + :param int sad_module: (optional) Detects speech boundaries within the + audio stream with better performance, improved noise suppression, faster + responsiveness, and increased accuracy. + Specify `sad_module: 2` + See [Speech Activity Detection + (SAD)](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#sad). :param float background_audio_suppression: (optional) The level to which the service is to suppress background audio based on its volume to prevent it from being transcribed as speech. Use the parameter to suppress side @@ -1341,6 +1357,7 @@ def create_job( 'end_of_phrase_silence_time': end_of_phrase_silence_time, 'split_transcript_at_phrase_end': split_transcript_at_phrase_end, 'speech_detector_sensitivity': speech_detector_sensitivity, + 'sad_module': sad_module, 'background_audio_suppression': background_audio_suppression, 'low_latency': low_latency, 'character_insertion_bias': character_insertion_bias, diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index dabe6526d..5f3b3969a 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -57,6 +57,7 @@ def recognize_using_websocket(self, background_audio_suppression=None, low_latency=None, character_insertion_bias=None, + sad_module=None, **kwargs): """ Sends audio for speech recognition using web sockets. @@ -309,6 +310,12 @@ def recognize_using_websocket(self, `Narrowband` models. See [Character insertion bias](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#insertion-bias). + :param int sad_module: (optional) Detects speech boundaries within the + audio stream with better performance, improved noise suppression, faster + responsiveness, and increased accuracy. + Specify `sad_module: 2` + See [Speech Activity Detection + (SAD)](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#sad). :param dict headers: A `dict` containing the request headers :return: A `dict` containing the `SpeechRecognitionResults` response. :rtype: dict @@ -377,6 +384,7 @@ def recognize_using_websocket(self, 'background_audio_suppression': background_audio_suppression, 'character_insertion_bias': character_insertion_bias, 'low_latency': low_latency, + 'sad_module': sad_module, } options = {k: v for k, v in options.items() if v is not None} request['options'] = options diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 658ae8999..348bbb6cf 100644 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2024. +# (C) Copyright IBM Corp. 2025. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -239,6 +239,7 @@ def test_recognize_all_params(self): end_of_phrase_silence_time = 0.8 split_transcript_at_phrase_end = False speech_detector_sensitivity = 0.5 + sad_module = 1 background_audio_suppression = 0.0 low_latency = False character_insertion_bias = 0.0 @@ -270,6 +271,7 @@ def test_recognize_all_params(self): end_of_phrase_silence_time=end_of_phrase_silence_time, split_transcript_at_phrase_end=split_transcript_at_phrase_end, speech_detector_sensitivity=speech_detector_sensitivity, + sad_module=sad_module, background_audio_suppression=background_audio_suppression, low_latency=low_latency, character_insertion_bias=character_insertion_bias, @@ -302,6 +304,7 @@ def test_recognize_all_params(self): assert 'audio_metrics={}'.format('true' if audio_metrics else 'false') in query_string assert 'end_of_phrase_silence_time={}'.format(end_of_phrase_silence_time) in query_string assert 'split_transcript_at_phrase_end={}'.format('true' if split_transcript_at_phrase_end else 'false') in query_string + assert 'sad_module={}'.format(sad_module) in query_string assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string # Validate body params @@ -663,6 +666,7 @@ def test_create_job_all_params(self): end_of_phrase_silence_time = 0.8 split_transcript_at_phrase_end = False speech_detector_sensitivity = 0.5 + sad_module = 1 background_audio_suppression = 0.0 low_latency = False character_insertion_bias = 0.0 @@ -699,6 +703,7 @@ def test_create_job_all_params(self): end_of_phrase_silence_time=end_of_phrase_silence_time, split_transcript_at_phrase_end=split_transcript_at_phrase_end, speech_detector_sensitivity=speech_detector_sensitivity, + sad_module=sad_module, background_audio_suppression=background_audio_suppression, low_latency=low_latency, character_insertion_bias=character_insertion_bias, @@ -735,6 +740,7 @@ def test_create_job_all_params(self): assert 'audio_metrics={}'.format('true' if audio_metrics else 'false') in query_string assert 'end_of_phrase_silence_time={}'.format(end_of_phrase_silence_time) in query_string assert 'split_transcript_at_phrase_end={}'.format('true' if split_transcript_at_phrase_end else 'false') in query_string + assert 'sad_module={}'.format(sad_module) in query_string assert 'low_latency={}'.format('true' if low_latency else 'false') in query_string # Validate body params From 42efff7977fc50a3f406258a0145b7fa7c2ded28 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 10 Nov 2025 11:57:48 -0600 Subject: [PATCH 449/455] chore: update version numbers --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 8edc96571..7e3cb47aa 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 10.0.0 +current_version = 11.0.0 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 2e568bf45..344ed4c94 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '10.0.0' +__version__ = '11.0.0' diff --git a/setup.py b/setup.py index 566a960de..c0dd43034 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,5 @@ #!/usr/bin/env python -# (C) Copyright IBM Corp. 2015, 2020. +# (C) Copyright IBM Corp. 2015, 2025. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '10.0.0' +__version__ = '11.0.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From 58e325d0ffc4299f3f00a013da325adfed6d0b61 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 14 Jan 2026 14:27:12 -0600 Subject: [PATCH 450/455] feat(wa-v2): add dtmf and end_session response types --- ibm_watson/assistant_v2.py | 280 ++++++++++++++++++++++++++++++++- test/unit/test_assistant_v2.py | 105 ++++++++++++- 2 files changed, 381 insertions(+), 4 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 32d898abb..72dbd34c3 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2025. +# (C) Copyright IBM Corp. 2019, 2026. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -4677,6 +4677,88 @@ def __ne__(self, other: 'DialogSuggestionValue') -> bool: return not self == other +class DtmfCommandInfo: + """ + DtmfCommandInfo. + + :param str type: Specifies the type of DTMF command for the phone integration. + :param dict parameters: (optional) Parameters specified by the command type. + """ + + def __init__( + self, + type: str, + *, + parameters: Optional[dict] = None, + ) -> None: + """ + Initialize a DtmfCommandInfo object. + + :param str type: Specifies the type of DTMF command for the phone + integration. + :param dict parameters: (optional) Parameters specified by the command + type. + """ + self.type = type + self.parameters = parameters + + @classmethod + def from_dict(cls, _dict: Dict) -> 'DtmfCommandInfo': + """Initialize a DtmfCommandInfo object from a json dictionary.""" + args = {} + if (type := _dict.get('type')) is not None: + args['type'] = type + else: + raise ValueError( + 'Required property \'type\' not present in DtmfCommandInfo JSON' + ) + if (parameters := _dict.get('parameters')) is not None: + args['parameters'] = parameters + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DtmfCommandInfo 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 + if hasattr(self, 'parameters') and self.parameters is not None: + _dict['parameters'] = self.parameters + 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 DtmfCommandInfo object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'DtmfCommandInfo') -> 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: 'DtmfCommandInfo') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TypeEnum(str, Enum): + """ + Specifies the type of DTMF command for the phone integration. + """ + + COLLECT = 'collect' + DISABLE_BARGE_IN = 'disable_barge_in' + ENABLE_BARGE_IN = 'enable_barge_in' + SEND = 'send' + + class Environment: """ Environment. @@ -12107,7 +12189,9 @@ def __init__(self,) -> None: 'RuntimeResponseGenericRuntimeResponseTypeVideo', 'RuntimeResponseGenericRuntimeResponseTypeAudio', 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' + 'RuntimeResponseGenericRuntimeResponseTypeDate', + 'RuntimeResponseGenericRuntimeResponseTypeDtmf', + 'RuntimeResponseGenericRuntimeResponseTypeEndSession' ])) raise Exception(msg) @@ -12132,7 +12216,9 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': 'RuntimeResponseGenericRuntimeResponseTypeVideo', 'RuntimeResponseGenericRuntimeResponseTypeAudio', 'RuntimeResponseGenericRuntimeResponseTypeIframe', - 'RuntimeResponseGenericRuntimeResponseTypeDate' + 'RuntimeResponseGenericRuntimeResponseTypeDate', + 'RuntimeResponseGenericRuntimeResponseTypeDtmf', + 'RuntimeResponseGenericRuntimeResponseTypeEndSession' ])) raise Exception(msg) @@ -12163,6 +12249,9 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping[ 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' + mapping['dtmf'] = 'RuntimeResponseGenericRuntimeResponseTypeDtmf' + mapping[ + 'end_session'] = 'RuntimeResponseGenericRuntimeResponseTypeEndSession' disc_value = _dict.get('response_type') if disc_value is None: raise ValueError( @@ -21888,6 +21977,191 @@ def __ne__(self, return not self == other +class RuntimeResponseGenericRuntimeResponseTypeDtmf(RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeDtmf. + + :param str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :param DtmfCommandInfo command_info: (optional) + :param List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + """ + + def __init__( + self, + response_type: str, + *, + command_info: Optional['DtmfCommandInfo'] = None, + channels: Optional[List['ResponseGenericChannel']] = None, + ) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeDtmf object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param DtmfCommandInfo command_info: (optional) + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.command_info = command_info + self.channels = channels + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeDtmf': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeDtmf object from a json dictionary.""" + args = {} + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeDtmf JSON' + ) + if (command_info := _dict.get('command_info')) is not None: + args['command_info'] = DtmfCommandInfo.from_dict(command_info) + if (channels := _dict.get('channels')) is not None: + args['channels'] = [ + ResponseGenericChannel.from_dict(v) for v in channels + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeDtmf 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'command_info') and self.command_info is not None: + if isinstance(self.command_info, dict): + _dict['command_info'] = self.command_info + else: + _dict['command_info'] = self.command_info.to_dict() + if hasattr(self, 'channels') and self.channels is not None: + channels_list = [] + for v in self.channels: + if isinstance(v, dict): + channels_list.append(v) + else: + channels_list.append(v.to_dict()) + _dict['channels'] = channels_list + 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 RuntimeResponseGenericRuntimeResponseTypeDtmf object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeDtmf') -> 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: 'RuntimeResponseGenericRuntimeResponseTypeDtmf') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGenericRuntimeResponseTypeEndSession( + RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeEndSession. + + :param str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :param dict channel_options: (optional) For internal use only. + """ + + def __init__( + self, + response_type: str, + *, + channel_options: Optional[dict] = None, + ) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeEndSession object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param dict channel_options: (optional) For internal use only. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.channel_options = channel_options + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'RuntimeResponseGenericRuntimeResponseTypeEndSession': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeEndSession object from a json dictionary.""" + args = {} + if (response_type := _dict.get('response_type')) is not None: + args['response_type'] = response_type + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeEndSession JSON' + ) + if (channel_options := _dict.get('channel_options')) is not None: + args['channel_options'] = channel_options + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeEndSession 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, + 'channel_options') and self.channel_options is not None: + _dict['channel_options'] = self.channel_options + 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 RuntimeResponseGenericRuntimeResponseTypeEndSession object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'RuntimeResponseGenericRuntimeResponseTypeEndSession' + ) -> 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: 'RuntimeResponseGenericRuntimeResponseTypeEndSession' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuntimeResponseGenericRuntimeResponseTypeIframe(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeIframe. diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 21613a15d..f2ab84821 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2019, 2025. +# (C) Copyright IBM Corp. 2019, 2026. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -6539,6 +6539,37 @@ def test_dialog_suggestion_value_serialization(self): assert dialog_suggestion_value_model_json2 == dialog_suggestion_value_model_json +class TestModel_DtmfCommandInfo: + """ + Test Class for DtmfCommandInfo + """ + + def test_dtmf_command_info_serialization(self): + """ + Test serialization/deserialization for DtmfCommandInfo + """ + + # Construct a json representation of a DtmfCommandInfo model + dtmf_command_info_model_json = {} + dtmf_command_info_model_json['type'] = 'collect' + dtmf_command_info_model_json['parameters'] = {'anyKey': 'anyValue'} + + # Construct a model instance of DtmfCommandInfo by calling from_dict on the json representation + dtmf_command_info_model = DtmfCommandInfo.from_dict(dtmf_command_info_model_json) + assert dtmf_command_info_model != False + + # Construct a model instance of DtmfCommandInfo by calling from_dict on the json representation + dtmf_command_info_model_dict = DtmfCommandInfo.from_dict(dtmf_command_info_model_json).__dict__ + dtmf_command_info_model2 = DtmfCommandInfo(**dtmf_command_info_model_dict) + + # Verify the model instances are equivalent + assert dtmf_command_info_model == dtmf_command_info_model2 + + # Convert model instance back to dict and verify no loss of data + dtmf_command_info_model_json2 = dtmf_command_info_model.to_dict() + assert dtmf_command_info_model_json2 == dtmf_command_info_model_json + + class TestModel_Environment: """ Test Class for Environment @@ -15851,6 +15882,78 @@ def test_runtime_response_generic_runtime_response_type_date_serialization(self) assert runtime_response_generic_runtime_response_type_date_model_json2 == runtime_response_generic_runtime_response_type_date_model_json +class TestModel_RuntimeResponseGenericRuntimeResponseTypeDtmf: + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeDtmf + """ + + def test_runtime_response_generic_runtime_response_type_dtmf_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeDtmf + """ + + # Construct dict forms of any model objects needed in order to build this model. + + dtmf_command_info_model = {} # DtmfCommandInfo + dtmf_command_info_model['type'] = 'collect' + dtmf_command_info_model['parameters'] = {'anyKey': 'anyValue'} + + response_generic_channel_model = {} # ResponseGenericChannel + response_generic_channel_model['channel'] = 'testString' + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeDtmf model + runtime_response_generic_runtime_response_type_dtmf_model_json = {} + runtime_response_generic_runtime_response_type_dtmf_model_json['response_type'] = 'dtmf' + runtime_response_generic_runtime_response_type_dtmf_model_json['command_info'] = dtmf_command_info_model + runtime_response_generic_runtime_response_type_dtmf_model_json['channels'] = [response_generic_channel_model] + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeDtmf by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_dtmf_model = RuntimeResponseGenericRuntimeResponseTypeDtmf.from_dict(runtime_response_generic_runtime_response_type_dtmf_model_json) + assert runtime_response_generic_runtime_response_type_dtmf_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeDtmf by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_dtmf_model_dict = RuntimeResponseGenericRuntimeResponseTypeDtmf.from_dict(runtime_response_generic_runtime_response_type_dtmf_model_json).__dict__ + runtime_response_generic_runtime_response_type_dtmf_model2 = RuntimeResponseGenericRuntimeResponseTypeDtmf(**runtime_response_generic_runtime_response_type_dtmf_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_dtmf_model == runtime_response_generic_runtime_response_type_dtmf_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_dtmf_model_json2 = runtime_response_generic_runtime_response_type_dtmf_model.to_dict() + assert runtime_response_generic_runtime_response_type_dtmf_model_json2 == runtime_response_generic_runtime_response_type_dtmf_model_json + + +class TestModel_RuntimeResponseGenericRuntimeResponseTypeEndSession: + """ + Test Class for RuntimeResponseGenericRuntimeResponseTypeEndSession + """ + + def test_runtime_response_generic_runtime_response_type_end_session_serialization(self): + """ + Test serialization/deserialization for RuntimeResponseGenericRuntimeResponseTypeEndSession + """ + + # Construct a json representation of a RuntimeResponseGenericRuntimeResponseTypeEndSession model + runtime_response_generic_runtime_response_type_end_session_model_json = {} + runtime_response_generic_runtime_response_type_end_session_model_json['response_type'] = 'end_session' + runtime_response_generic_runtime_response_type_end_session_model_json['channel_options'] = {'anyKey': 'anyValue'} + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeEndSession by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_end_session_model = RuntimeResponseGenericRuntimeResponseTypeEndSession.from_dict(runtime_response_generic_runtime_response_type_end_session_model_json) + assert runtime_response_generic_runtime_response_type_end_session_model != False + + # Construct a model instance of RuntimeResponseGenericRuntimeResponseTypeEndSession by calling from_dict on the json representation + runtime_response_generic_runtime_response_type_end_session_model_dict = RuntimeResponseGenericRuntimeResponseTypeEndSession.from_dict(runtime_response_generic_runtime_response_type_end_session_model_json).__dict__ + runtime_response_generic_runtime_response_type_end_session_model2 = RuntimeResponseGenericRuntimeResponseTypeEndSession(**runtime_response_generic_runtime_response_type_end_session_model_dict) + + # Verify the model instances are equivalent + assert runtime_response_generic_runtime_response_type_end_session_model == runtime_response_generic_runtime_response_type_end_session_model2 + + # Convert model instance back to dict and verify no loss of data + runtime_response_generic_runtime_response_type_end_session_model_json2 = runtime_response_generic_runtime_response_type_end_session_model.to_dict() + assert runtime_response_generic_runtime_response_type_end_session_model_json2 == runtime_response_generic_runtime_response_type_end_session_model_json + + class TestModel_RuntimeResponseGenericRuntimeResponseTypeIframe: """ Test Class for RuntimeResponseGenericRuntimeResponseTypeIframe From 5789e237ca7470bf5cb4db646f479f193c7257ef Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 14 Jan 2026 14:28:21 -0600 Subject: [PATCH 451/455] feat(stt): add recognize enrichments, add new function detectLanguage --- ibm_watson/speech_to_text_v1.py | 608 +++++++++++++++++++++++++++- test/unit/test_speech_to_text_v1.py | 433 +++++++++++++++++++- 2 files changed, 1026 insertions(+), 15 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index 64e600645..1b1b47bc6 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2025. +# (C) Copyright IBM Corp. 2015, 2026. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -197,6 +197,7 @@ def recognize( content_type: Optional[str] = None, model: Optional[str] = None, speech_begin_event: Optional[bool] = None, + enrichments: Optional[str] = None, language_customization_id: Optional[str] = None, acoustic_customization_id: Optional[str] = None, base_model_version: Optional[str] = None, @@ -356,6 +357,16 @@ def recognize( `sad_module: 2` to increase accuracy and performance in detecting speech boundaries within the audio stream. See [Using speech recognition parameters](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-service-features#features-parameters). + :param str enrichments: (optional) Speech transcript enrichment improves + readability of raw ASR transcripts by adding punctuation (periods, commas, + question marks, exclamation points) and intelligent capitalization + (sentence beginnings, proper nouns, acronyms, brand names). To enable + enrichment, add the `enrichments=punctuation` parameter to your recognition + request. Supported languages include English (US, UK, Australia, India), + French (France, Canada), German, Italian, Portuguese (Brazil, Portugal), + Spanish (Spain, Latin America, Argentina, Chile, Colombia, Mexico, Peru), + and Japanese. See [Speech transcript + enrichment](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speech-transcript-enrichment). :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 @@ -634,6 +645,7 @@ def recognize( params = { 'model': model, 'speech_begin_event': speech_begin_event, + 'enrichments': enrichments, 'language_customization_id': language_customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, @@ -831,6 +843,8 @@ def create_job( events: Optional[str] = None, user_token: Optional[str] = None, results_ttl: Optional[int] = None, + speech_begin_event: Optional[bool] = None, + enrichments: Optional[str] = None, language_customization_id: Optional[str] = None, acoustic_customization_id: Optional[str] = None, base_model_version: Optional[str] = None, @@ -1031,6 +1045,25 @@ def create_job( via a callback, the results must be retrieved within this time. Omit the parameter to use a time to live of one week. The parameter is valid with or without a callback URL. + :param bool speech_begin_event: (optional) If `true`, the service returns a + response object `SpeechActivity` which contains the time when a speech + activity is detected in the stream. This can be used both in standard and + low latency mode. This feature enables client applications to know that + some words/speech has been detected and the service is in the process of + decoding. This can be used in lieu of interim results in standard mode. Use + `sad_module: 2` to increase accuracy and performance in detecting speech + boundaries within the audio stream. See [Using speech recognition + parameters](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-service-features#features-parameters). + :param str enrichments: (optional) Speech transcript enrichment improves + readability of raw ASR transcripts by adding punctuation (periods, commas, + question marks, exclamation points) and intelligent capitalization + (sentence beginnings, proper nouns, acronyms, brand names). To enable + enrichment, add the `enrichments=punctuation` parameter to your recognition + request. Supported languages include English (US, UK, Australia, India), + French (France, Canada), German, Italian, Portuguese (Brazil, Portugal), + Spanish (Spain, Latin America, Argentina, Chile, Colombia, Mexico, Peru), + and Japanese. See [Speech transcript + enrichment](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speech-transcript-enrichment). :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 @@ -1334,6 +1367,8 @@ def create_job( 'events': events, 'user_token': user_token, 'results_ttl': results_ttl, + 'speech_begin_event': speech_begin_event, + 'enrichments': enrichments, 'language_customization_id': language_customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, @@ -4311,6 +4346,75 @@ def delete_user_data( response = self.send(request, **kwargs) return response + ######################### + # Language identification + ######################### + + def detect_language( + self, + lid_confidence: float, + audio: BinaryIO, + *, + content_type: Optional[str] = None, + **kwargs, + ) -> DetailedResponse: + """ + Spoken language identification. + + Detects the spoken language in audio streams. The endpoint is + `/v1/detect_language` and user can optionally include `lid_confidence` parameter + to set a custom confidence threshold for detection. The model continuously + processes incoming audio and returns the identified language when it reaches a + confidence level higher than the specified threshold (0.99 by default). See + [Spoken language + identification](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speech-language-identification). + + :param float lid_confidence: Set a custom confidence threshold for + detection. + :param BinaryIO audio: The audio to transcribe. + :param str content_type: (optional) The type of the input. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse with `dict` result representing a `LanguageDetectionResults` object + """ + + if lid_confidence is None: + raise ValueError('lid_confidence must be provided') + if audio is None: + raise ValueError('audio must be provided') + headers = { + 'Content-Type': content_type, + } + sdk_headers = get_sdk_headers( + service_name=self.DEFAULT_SERVICE_NAME, + service_version='V1', + operation_id='detect_language', + ) + headers.update(sdk_headers) + + params = { + 'lid_confidence': lid_confidence, + } + + data = audio + + if 'headers' in kwargs: + headers.update(kwargs.get('headers')) + del kwargs['headers'] + headers['Accept'] = 'application/json' + + url = '/v1/detect_language' + request = self.prepare_request( + method='POST', + url=url, + headers=headers, + params=params, + data=data, + ) + + response = self.send(request, **kwargs) + return response + class GetModelEnums: """ @@ -4933,6 +5037,34 @@ class ContainedContentType(str, Enum): AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' +class DetectLanguageEnums: + """ + Enums for detect_language parameters. + """ + + class ContentType(str, Enum): + """ + The type of the input. + """ + + APPLICATION_OCTET_STREAM = 'application/octet-stream' + AUDIO_ALAW = 'audio/alaw' + AUDIO_BASIC = 'audio/basic' + AUDIO_FLAC = 'audio/flac' + AUDIO_G729 = 'audio/g729' + AUDIO_L16 = 'audio/l16' + AUDIO_MP3 = 'audio/mp3' + AUDIO_MPEG = 'audio/mpeg' + AUDIO_MULAW = 'audio/mulaw' + AUDIO_OGG = 'audio/ogg' + AUDIO_OGG_CODECS_OPUS = 'audio/ogg;codecs=opus' + AUDIO_OGG_CODECS_VORBIS = 'audio/ogg;codecs=vorbis' + AUDIO_WAV = 'audio/wav' + AUDIO_WEBM = 'audio/webm' + AUDIO_WEBM_CODECS_OPUS = 'audio/webm;codecs=opus' + AUDIO_WEBM_CODECS_VORBIS = 'audio/webm;codecs=vorbis' + + ############################################################################## # Models ############################################################################## @@ -6593,6 +6725,224 @@ def __ne__(self, other: 'CustomWord') -> bool: return not self == other +class EnrichedResults: + """ + If enriched results are requested, transcription with inserted punctuation marks such + as periods, commas, question marks, and exclamation points. + + :param EnrichedResultsTranscript transcript: (optional) If enriched results are + requested, transcription with inserted punctuation marks such as periods, + commas, question marks, and exclamation points. + :param str status: (optional) The status of the enriched transcription. + """ + + def __init__( + self, + *, + transcript: Optional['EnrichedResultsTranscript'] = None, + status: Optional[str] = None, + ) -> None: + """ + Initialize a EnrichedResults object. + + :param EnrichedResultsTranscript transcript: (optional) If enriched results + are requested, transcription with inserted punctuation marks such as + periods, commas, question marks, and exclamation points. + :param str status: (optional) The status of the enriched transcription. + """ + self.transcript = transcript + self.status = status + + @classmethod + def from_dict(cls, _dict: Dict) -> 'EnrichedResults': + """Initialize a EnrichedResults object from a json dictionary.""" + args = {} + if (transcript := _dict.get('transcript')) is not None: + args['transcript'] = EnrichedResultsTranscript.from_dict(transcript) + if (status := _dict.get('status')) is not None: + args['status'] = status + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnrichedResults 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, 'transcript') and self.transcript is not None: + if isinstance(self.transcript, dict): + _dict['transcript'] = self.transcript + else: + _dict['transcript'] = self.transcript.to_dict() + if hasattr(self, 'status') and self.status is not None: + _dict['status'] = self.status + 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 EnrichedResults object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'EnrichedResults') -> 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: 'EnrichedResults') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class EnrichedResultsTranscript: + """ + If enriched results are requested, transcription with inserted punctuation marks such + as periods, commas, question marks, and exclamation points. + + :param str text: (optional) The transcript text. + :param EnrichedResultsTranscriptTimestamp timestamp: (optional) The speaking + time from the beginning of the transcript to the end. + """ + + def __init__( + self, + *, + text: Optional[str] = None, + timestamp: Optional['EnrichedResultsTranscriptTimestamp'] = None, + ) -> None: + """ + Initialize a EnrichedResultsTranscript object. + + :param str text: (optional) The transcript text. + :param EnrichedResultsTranscriptTimestamp timestamp: (optional) The + speaking time from the beginning of the transcript to the end. + """ + self.text = text + self.timestamp = timestamp + + @classmethod + def from_dict(cls, _dict: Dict) -> 'EnrichedResultsTranscript': + """Initialize a EnrichedResultsTranscript object from a json dictionary.""" + args = {} + if (text := _dict.get('text')) is not None: + args['text'] = text + if (timestamp := _dict.get('timestamp')) is not None: + args['timestamp'] = EnrichedResultsTranscriptTimestamp.from_dict( + timestamp) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnrichedResultsTranscript 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, 'text') and self.text is not None: + _dict['text'] = self.text + if hasattr(self, 'timestamp') and self.timestamp is not None: + if isinstance(self.timestamp, dict): + _dict['timestamp'] = self.timestamp + else: + _dict['timestamp'] = self.timestamp.to_dict() + 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 EnrichedResultsTranscript object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'EnrichedResultsTranscript') -> 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: 'EnrichedResultsTranscript') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class EnrichedResultsTranscriptTimestamp: + """ + The speaking time from the beginning of the transcript to the end. + + :param float from_: (optional) The start time of a word from the transcript. The + value matches the start time of a word from the `timestamps` array. + :param float to: (optional) The end time of a word from the transcript. The + value matches the end time of a word from the `timestamps` array. + """ + + def __init__( + self, + *, + from_: Optional[float] = None, + to: Optional[float] = None, + ) -> None: + """ + Initialize a EnrichedResultsTranscriptTimestamp object. + + :param float from_: (optional) The start time of a word from the + transcript. The value matches the start time of a word from the + `timestamps` array. + :param float to: (optional) The end time of a word from the transcript. The + value matches the end time of a word from the `timestamps` array. + """ + self.from_ = from_ + self.to = to + + @classmethod + def from_dict(cls, _dict: Dict) -> 'EnrichedResultsTranscriptTimestamp': + """Initialize a EnrichedResultsTranscriptTimestamp object from a json dictionary.""" + args = {} + if (from_ := _dict.get('from')) is not None: + args['from_'] = from_ + if (to := _dict.get('to')) is not None: + args['to'] = to + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a EnrichedResultsTranscriptTimestamp 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, 'from_') and self.from_ is not None: + _dict['from'] = self.from_ + if hasattr(self, 'to') and self.to is not None: + _dict['to'] = self.to + 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 EnrichedResultsTranscriptTimestamp object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'EnrichedResultsTranscriptTimestamp') -> 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: 'EnrichedResultsTranscriptTimestamp') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Grammar: """ Information about a grammar from a custom language model. @@ -6901,6 +7251,237 @@ def __ne__(self, other: 'KeywordResult') -> bool: return not self == other +class LanguageDetectionResult: + """ + Language detection results. + + :param List[LanguageInfo] language_info: (optional) An array of `LanguageInfo` + objects. + """ + + def __init__( + self, + *, + language_info: Optional[List['LanguageInfo']] = None, + ) -> None: + """ + Initialize a LanguageDetectionResult object. + + :param List[LanguageInfo] language_info: (optional) An array of + `LanguageInfo` objects. + """ + self.language_info = language_info + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LanguageDetectionResult': + """Initialize a LanguageDetectionResult object from a json dictionary.""" + args = {} + if (language_info := _dict.get('language_info')) is not None: + args['language_info'] = [ + LanguageInfo.from_dict(v) for v in language_info + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LanguageDetectionResult 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, 'language_info') and self.language_info is not None: + language_info_list = [] + for v in self.language_info: + if isinstance(v, dict): + language_info_list.append(v) + else: + language_info_list.append(v.to_dict()) + _dict['language_info'] = language_info_list + 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 LanguageDetectionResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LanguageDetectionResult') -> 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: 'LanguageDetectionResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LanguageDetectionResults: + """ + Language detection results. + + :param List[LanguageDetectionResult] results: (optional) An array of + `LanguageDetectionResult` objects. + :param int result_index: (optional) An index that indicates a change point in + the `results` array. The service increments the index for additional results + that it sends for new audio for the same request. All results with the same + index are delivered at the same time. The same index can include multiple final + results that are delivered with the same response. + """ + + def __init__( + self, + *, + results: Optional[List['LanguageDetectionResult']] = None, + result_index: Optional[int] = None, + ) -> None: + """ + Initialize a LanguageDetectionResults object. + + :param List[LanguageDetectionResult] results: (optional) An array of + `LanguageDetectionResult` objects. + :param int result_index: (optional) An index that indicates a change point + in the `results` array. The service increments the index for additional + results that it sends for new audio for the same request. All results with + the same index are delivered at the same time. The same index can include + multiple final results that are delivered with the same response. + """ + self.results = results + self.result_index = result_index + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LanguageDetectionResults': + """Initialize a LanguageDetectionResults object from a json dictionary.""" + args = {} + if (results := _dict.get('results')) is not None: + args['results'] = [ + LanguageDetectionResult.from_dict(v) for v in results + ] + if (result_index := _dict.get('result_index')) is not None: + args['result_index'] = result_index + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LanguageDetectionResults 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, 'results') and self.results is not None: + results_list = [] + for v in self.results: + if isinstance(v, dict): + results_list.append(v) + else: + results_list.append(v.to_dict()) + _dict['results'] = results_list + if hasattr(self, 'result_index') and self.result_index is not None: + _dict['result_index'] = self.result_index + 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 LanguageDetectionResults object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LanguageDetectionResults') -> 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: 'LanguageDetectionResults') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class LanguageInfo: + """ + Language detection info such as confidence and language detected. + + :param float confidence: (optional) A score that indicates the service's + confidence in its identification of the language in the range of 0.0 to 1.0. + :param str language: (optional) The language detected in standard abbreviated + ISO 639 format. + :param float timestamp: (optional) The timestamp of the detected language. + """ + + def __init__( + self, + *, + confidence: Optional[float] = None, + language: Optional[str] = None, + timestamp: Optional[float] = None, + ) -> None: + """ + Initialize a LanguageInfo object. + + :param float confidence: (optional) A score that indicates the service's + confidence in its identification of the language in the range of 0.0 to + 1.0. + :param str language: (optional) The language detected in standard + abbreviated ISO 639 format. + :param float timestamp: (optional) The timestamp of the detected language. + """ + self.confidence = confidence + self.language = language + self.timestamp = timestamp + + @classmethod + def from_dict(cls, _dict: Dict) -> 'LanguageInfo': + """Initialize a LanguageInfo object from a json dictionary.""" + args = {} + if (confidence := _dict.get('confidence')) is not None: + args['confidence'] = confidence + if (language := _dict.get('language')) is not None: + args['language'] = language + if (timestamp := _dict.get('timestamp')) is not None: + args['timestamp'] = timestamp + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a LanguageInfo 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, 'confidence') and self.confidence is not None: + _dict['confidence'] = self.confidence + if hasattr(self, 'language') and self.language is not None: + _dict['language'] = self.language + if hasattr(self, 'timestamp') and self.timestamp is not None: + _dict['timestamp'] = self.timestamp + 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 LanguageInfo object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'LanguageInfo') -> 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: 'LanguageInfo') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class LanguageModel: """ Information about an existing custom language model. @@ -8350,8 +8931,8 @@ class SpeechRecognitionResult: to be updated further. * If `false`, the results are interim. They can be updated with further interim results until final results are eventually sent. - **Note:** Because `final` is a reserved word in Java and Swift, the field is - renamed `xFinal` in Java and is escaped with back quotes in Swift. + **Note:** Because `final` is a reserved word in Java, the field is renamed + `xFinal` in Java. :param List[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. @@ -8395,8 +8976,8 @@ def __init__( not to be updated further. * If `false`, the results are interim. They can be updated with further interim results until final results are eventually sent. - **Note:** Because `final` is a reserved word in Java and Swift, the field - is renamed `xFinal` in Java and is escaped with back quotes in Swift. + **Note:** Because `final` is a reserved word in Java, the field is renamed + `xFinal` in Java. :param List[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. @@ -8578,6 +9159,9 @@ class SpeechRecognitionResults: do not do that you will be automatically switched to base model when you used the non-updated custom model."` In both cases, the request succeeds despite the warnings. + :param EnrichedResults enriched_results: (optional) If enriched results are + requested, transcription with inserted punctuation marks such as periods, + commas, question marks, and exclamation points. """ def __init__( @@ -8589,6 +9173,7 @@ def __init__( processing_metrics: Optional['ProcessingMetrics'] = None, audio_metrics: Optional['AudioMetrics'] = None, warnings: Optional[List[str]] = None, + enriched_results: Optional['EnrichedResults'] = None, ) -> None: """ Initialize a SpeechRecognitionResults object. @@ -8639,6 +9224,9 @@ def __init__( the new base model. If you do not do that you will be automatically switched to base model when you used the non-updated custom model."` In both cases, the request succeeds despite the warnings. + :param EnrichedResults enriched_results: (optional) If enriched results are + requested, transcription with inserted punctuation marks such as periods, + commas, question marks, and exclamation points. """ self.results = results self.result_index = result_index @@ -8646,6 +9234,7 @@ def __init__( self.processing_metrics = processing_metrics self.audio_metrics = audio_metrics self.warnings = warnings + self.enriched_results = enriched_results @classmethod def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResults': @@ -8668,6 +9257,9 @@ def from_dict(cls, _dict: Dict) -> 'SpeechRecognitionResults': args['audio_metrics'] = AudioMetrics.from_dict(audio_metrics) if (warnings := _dict.get('warnings')) is not None: args['warnings'] = warnings + if (enriched_results := _dict.get('enriched_results')) is not None: + args['enriched_results'] = EnrichedResults.from_dict( + enriched_results) return cls(**args) @classmethod @@ -8710,6 +9302,12 @@ def to_dict(self) -> Dict: _dict['audio_metrics'] = self.audio_metrics.to_dict() if hasattr(self, 'warnings') and self.warnings is not None: _dict['warnings'] = self.warnings + if hasattr(self, + 'enriched_results') and self.enriched_results is not None: + if isinstance(self.enriched_results, dict): + _dict['enriched_results'] = self.enriched_results + else: + _dict['enriched_results'] = self.enriched_results.to_dict() return _dict def _to_dict(self): diff --git a/test/unit/test_speech_to_text_v1.py b/test/unit/test_speech_to_text_v1.py index 348bbb6cf..cb5babf87 100644 --- a/test/unit/test_speech_to_text_v1.py +++ b/test/unit/test_speech_to_text_v1.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -# (C) Copyright IBM Corp. 2025. +# (C) Copyright IBM Corp. 2026. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -204,7 +204,7 @@ def test_recognize_all_params(self): """ # Set up mock url = preprocess_url('/v1/recognize') - mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' + mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"], "enriched_results": {"transcript": {"text": "text", "timestamp": {"from": 5, "to": 2}}, "status": "status"}}' responses.add( responses.POST, url, @@ -218,6 +218,7 @@ def test_recognize_all_params(self): content_type = 'application/octet-stream' model = 'en-US_BroadbandModel' speech_begin_event = False + enrichments = 'testString' language_customization_id = 'testString' acoustic_customization_id = 'testString' base_model_version = 'testString' @@ -250,6 +251,7 @@ def test_recognize_all_params(self): content_type=content_type, model=model, speech_begin_event=speech_begin_event, + enrichments=enrichments, language_customization_id=language_customization_id, acoustic_customization_id=acoustic_customization_id, base_model_version=base_model_version, @@ -286,6 +288,7 @@ def test_recognize_all_params(self): query_string = urllib.parse.unquote_plus(query_string) assert 'model={}'.format(model) in query_string assert 'speech_begin_event={}'.format('true' if speech_begin_event else 'false') in query_string + assert 'enrichments={}'.format(enrichments) in query_string assert 'language_customization_id={}'.format(language_customization_id) in query_string assert 'acoustic_customization_id={}'.format(acoustic_customization_id) in query_string assert 'base_model_version={}'.format(base_model_version) in query_string @@ -324,7 +327,7 @@ def test_recognize_required_params(self): """ # Set up mock url = preprocess_url('/v1/recognize') - mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' + mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"], "enriched_results": {"transcript": {"text": "text", "timestamp": {"from": 5, "to": 2}}, "status": "status"}}' responses.add( responses.POST, url, @@ -363,7 +366,7 @@ def test_recognize_value_error(self): """ # Set up mock url = preprocess_url('/v1/recognize') - mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}' + mock_response = '{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"], "enriched_results": {"transcript": {"text": "text", "timestamp": {"from": 5, "to": 2}}, "status": "status"}}' responses.add( responses.POST, url, @@ -626,7 +629,7 @@ def test_create_job_all_params(self): """ # Set up mock url = preprocess_url('/v1/recognitions') - mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' + mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"], "enriched_results": {"transcript": {"text": "text", "timestamp": {"from": 5, "to": 2}}, "status": "status"}}], "warnings": ["warnings"]}' responses.add( responses.POST, url, @@ -643,6 +646,8 @@ def test_create_job_all_params(self): events = 'recognitions.started' user_token = 'testString' results_ttl = 38 + speech_begin_event = False + enrichments = 'testString' language_customization_id = 'testString' acoustic_customization_id = 'testString' base_model_version = 'testString' @@ -680,6 +685,8 @@ def test_create_job_all_params(self): events=events, user_token=user_token, results_ttl=results_ttl, + speech_begin_event=speech_begin_event, + enrichments=enrichments, language_customization_id=language_customization_id, acoustic_customization_id=acoustic_customization_id, base_model_version=base_model_version, @@ -721,6 +728,8 @@ def test_create_job_all_params(self): assert 'events={}'.format(events) in query_string assert 'user_token={}'.format(user_token) in query_string assert 'results_ttl={}'.format(results_ttl) in query_string + assert 'speech_begin_event={}'.format('true' if speech_begin_event else 'false') in query_string + assert 'enrichments={}'.format(enrichments) in query_string assert 'language_customization_id={}'.format(language_customization_id) in query_string assert 'acoustic_customization_id={}'.format(acoustic_customization_id) in query_string assert 'base_model_version={}'.format(base_model_version) in query_string @@ -760,7 +769,7 @@ def test_create_job_required_params(self): """ # Set up mock url = preprocess_url('/v1/recognitions') - mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' + mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"], "enriched_results": {"transcript": {"text": "text", "timestamp": {"from": 5, "to": 2}}, "status": "status"}}], "warnings": ["warnings"]}' responses.add( responses.POST, url, @@ -799,7 +808,7 @@ def test_create_job_value_error(self): """ # Set up mock url = preprocess_url('/v1/recognitions') - mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' + mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"], "enriched_results": {"transcript": {"text": "text", "timestamp": {"from": 5, "to": 2}}, "status": "status"}}], "warnings": ["warnings"]}' responses.add( responses.POST, url, @@ -842,7 +851,7 @@ def test_check_jobs_all_params(self): """ # Set up mock url = preprocess_url('/v1/recognitions') - mock_response = '{"recognitions": [{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}]}' + mock_response = '{"recognitions": [{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"], "enriched_results": {"transcript": {"text": "text", "timestamp": {"from": 5, "to": 2}}, "status": "status"}}], "warnings": ["warnings"]}]}' responses.add( responses.GET, url, @@ -880,7 +889,7 @@ def test_check_job_all_params(self): """ # Set up mock url = preprocess_url('/v1/recognitions/testString') - mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' + mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"], "enriched_results": {"transcript": {"text": "text", "timestamp": {"from": 5, "to": 2}}, "status": "status"}}], "warnings": ["warnings"]}' responses.add( responses.GET, url, @@ -918,7 +927,7 @@ def test_check_job_value_error(self): """ # Set up mock url = preprocess_url('/v1/recognitions/testString') - mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"]}], "warnings": ["warnings"]}' + mock_response = '{"id": "id", "status": "waiting", "created": "created", "updated": "updated", "url": "url", "user_token": "user_token", "results": [{"results": [{"final": false, "alternatives": [{"transcript": "transcript", "confidence": 0, "timestamps": ["timestamps"], "word_confidence": ["word_confidence"]}], "keywords_result": {"mapKey": [{"normalized_text": "normalized_text", "start_time": 10, "end_time": 8, "confidence": 0}]}, "word_alternatives": [{"start_time": 10, "end_time": 8, "alternatives": [{"confidence": 0, "word": "word"}]}], "end_of_utterance": "end_of_data"}], "result_index": 12, "speaker_labels": [{"from": 5, "to": 2, "speaker": 7, "confidence": 10, "final": false}], "processing_metrics": {"processed_audio": {"received": 8, "seen_by_engine": 14, "transcription": 13, "speaker_labels": 14}, "wall_clock_since_first_byte_received": 36, "periodic": true}, "audio_metrics": {"sampling_interval": 17, "accumulated": {"final": false, "end_time": 8, "signal_to_noise_ratio": 21, "speech_ratio": 12, "high_frequency_loss": 19, "direct_current_offset": [{"begin": 5, "end": 3, "count": 5}], "clipping_rate": [{"begin": 5, "end": 3, "count": 5}], "speech_level": [{"begin": 5, "end": 3, "count": 5}], "non_speech_level": [{"begin": 5, "end": 3, "count": 5}]}}, "warnings": ["warnings"], "enriched_results": {"transcript": {"text": "text", "timestamp": {"from": 5, "to": 2}}, "status": "status"}}], "warnings": ["warnings"]}' responses.add( responses.GET, url, @@ -4071,6 +4080,152 @@ def test_delete_user_data_value_error_with_retries(self): # End of Service: UserData ############################################################################## +############################################################################## +# Start of Service: LanguageIdentification +############################################################################## +# region + + +class TestDetectLanguage: + """ + Test Class for detect_language + """ + + @responses.activate + def test_detect_language_all_params(self): + """ + detect_language() + """ + # Set up mock + url = preprocess_url('/v1/detect_language') + mock_response = '{"results": [{"language_info": [{"confidence": 10, "language": "language", "timestamp": 9}]}], "result_index": 12}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + lid_confidence = 36.0 + audio = io.BytesIO(b'This is a mock file.').getvalue() + content_type = 'application/octet-stream' + + # Invoke method + response = _service.detect_language( + lid_confidence, + audio, + content_type=content_type, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + # Validate body params + + def test_detect_language_all_params_with_retries(self): + # Enable retries and run test_detect_language_all_params. + _service.enable_retries() + self.test_detect_language_all_params() + + # Disable retries and run test_detect_language_all_params. + _service.disable_retries() + self.test_detect_language_all_params() + + @responses.activate + def test_detect_language_required_params(self): + """ + test_detect_language_required_params() + """ + # Set up mock + url = preprocess_url('/v1/detect_language') + mock_response = '{"results": [{"language_info": [{"confidence": 10, "language": "language", "timestamp": 9}]}], "result_index": 12}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + lid_confidence = 36.0 + audio = io.BytesIO(b'This is a mock file.').getvalue() + + # Invoke method + response = _service.detect_language( + lid_confidence, + audio, + headers={}, + ) + + # Check for correct operation + assert len(responses.calls) == 1 + assert response.status_code == 200 + # Validate query params + query_string = responses.calls[0].request.url.split('?', 1)[1] + query_string = urllib.parse.unquote_plus(query_string) + # Validate body params + + def test_detect_language_required_params_with_retries(self): + # Enable retries and run test_detect_language_required_params. + _service.enable_retries() + self.test_detect_language_required_params() + + # Disable retries and run test_detect_language_required_params. + _service.disable_retries() + self.test_detect_language_required_params() + + @responses.activate + def test_detect_language_value_error(self): + """ + test_detect_language_value_error() + """ + # Set up mock + url = preprocess_url('/v1/detect_language') + mock_response = '{"results": [{"language_info": [{"confidence": 10, "language": "language", "timestamp": 9}]}], "result_index": 12}' + responses.add( + responses.POST, + url, + body=mock_response, + content_type='application/json', + status=200, + ) + + # Set up parameter values + lid_confidence = 36.0 + audio = io.BytesIO(b'This is a mock file.').getvalue() + + # Pass in all but one required param and check for a ValueError + req_param_dict = { + "lid_confidence": lid_confidence, + "audio": audio, + } + for param in req_param_dict.keys(): + req_copy = {key: val if key is not param else None for (key, val) in req_param_dict.items()} + with pytest.raises(ValueError): + _service.detect_language(**req_copy) + + def test_detect_language_value_error_with_retries(self): + # Enable retries and run test_detect_language_value_error. + _service.enable_retries() + self.test_detect_language_value_error() + + # Disable retries and run test_detect_language_value_error. + _service.disable_retries() + self.test_detect_language_value_error() + + +# endregion +############################################################################## +# End of Service: LanguageIdentification +############################################################################## + ############################################################################## # Start of Model Tests @@ -4565,6 +4720,115 @@ def test_custom_word_serialization(self): assert custom_word_model_json2 == custom_word_model_json +class TestModel_EnrichedResults: + """ + Test Class for EnrichedResults + """ + + def test_enriched_results_serialization(self): + """ + Test serialization/deserialization for EnrichedResults + """ + + # Construct dict forms of any model objects needed in order to build this model. + + enriched_results_transcript_timestamp_model = {} # EnrichedResultsTranscriptTimestamp + enriched_results_transcript_timestamp_model['from'] = 36.0 + enriched_results_transcript_timestamp_model['to'] = 36.0 + + enriched_results_transcript_model = {} # EnrichedResultsTranscript + enriched_results_transcript_model['text'] = 'testString' + enriched_results_transcript_model['timestamp'] = enriched_results_transcript_timestamp_model + + # Construct a json representation of a EnrichedResults model + enriched_results_model_json = {} + enriched_results_model_json['transcript'] = enriched_results_transcript_model + enriched_results_model_json['status'] = 'testString' + + # Construct a model instance of EnrichedResults by calling from_dict on the json representation + enriched_results_model = EnrichedResults.from_dict(enriched_results_model_json) + assert enriched_results_model != False + + # Construct a model instance of EnrichedResults by calling from_dict on the json representation + enriched_results_model_dict = EnrichedResults.from_dict(enriched_results_model_json).__dict__ + enriched_results_model2 = EnrichedResults(**enriched_results_model_dict) + + # Verify the model instances are equivalent + assert enriched_results_model == enriched_results_model2 + + # Convert model instance back to dict and verify no loss of data + enriched_results_model_json2 = enriched_results_model.to_dict() + assert enriched_results_model_json2 == enriched_results_model_json + + +class TestModel_EnrichedResultsTranscript: + """ + Test Class for EnrichedResultsTranscript + """ + + def test_enriched_results_transcript_serialization(self): + """ + Test serialization/deserialization for EnrichedResultsTranscript + """ + + # Construct dict forms of any model objects needed in order to build this model. + + enriched_results_transcript_timestamp_model = {} # EnrichedResultsTranscriptTimestamp + enriched_results_transcript_timestamp_model['from'] = 36.0 + enriched_results_transcript_timestamp_model['to'] = 36.0 + + # Construct a json representation of a EnrichedResultsTranscript model + enriched_results_transcript_model_json = {} + enriched_results_transcript_model_json['text'] = 'testString' + enriched_results_transcript_model_json['timestamp'] = enriched_results_transcript_timestamp_model + + # Construct a model instance of EnrichedResultsTranscript by calling from_dict on the json representation + enriched_results_transcript_model = EnrichedResultsTranscript.from_dict(enriched_results_transcript_model_json) + assert enriched_results_transcript_model != False + + # Construct a model instance of EnrichedResultsTranscript by calling from_dict on the json representation + enriched_results_transcript_model_dict = EnrichedResultsTranscript.from_dict(enriched_results_transcript_model_json).__dict__ + enriched_results_transcript_model2 = EnrichedResultsTranscript(**enriched_results_transcript_model_dict) + + # Verify the model instances are equivalent + assert enriched_results_transcript_model == enriched_results_transcript_model2 + + # Convert model instance back to dict and verify no loss of data + enriched_results_transcript_model_json2 = enriched_results_transcript_model.to_dict() + assert enriched_results_transcript_model_json2 == enriched_results_transcript_model_json + + +class TestModel_EnrichedResultsTranscriptTimestamp: + """ + Test Class for EnrichedResultsTranscriptTimestamp + """ + + def test_enriched_results_transcript_timestamp_serialization(self): + """ + Test serialization/deserialization for EnrichedResultsTranscriptTimestamp + """ + + # Construct a json representation of a EnrichedResultsTranscriptTimestamp model + enriched_results_transcript_timestamp_model_json = {} + enriched_results_transcript_timestamp_model_json['from'] = 36.0 + enriched_results_transcript_timestamp_model_json['to'] = 36.0 + + # Construct a model instance of EnrichedResultsTranscriptTimestamp by calling from_dict on the json representation + enriched_results_transcript_timestamp_model = EnrichedResultsTranscriptTimestamp.from_dict(enriched_results_transcript_timestamp_model_json) + assert enriched_results_transcript_timestamp_model != False + + # Construct a model instance of EnrichedResultsTranscriptTimestamp by calling from_dict on the json representation + enriched_results_transcript_timestamp_model_dict = EnrichedResultsTranscriptTimestamp.from_dict(enriched_results_transcript_timestamp_model_json).__dict__ + enriched_results_transcript_timestamp_model2 = EnrichedResultsTranscriptTimestamp(**enriched_results_transcript_timestamp_model_dict) + + # Verify the model instances are equivalent + assert enriched_results_transcript_timestamp_model == enriched_results_transcript_timestamp_model2 + + # Convert model instance back to dict and verify no loss of data + enriched_results_transcript_timestamp_model_json2 = enriched_results_transcript_timestamp_model.to_dict() + assert enriched_results_transcript_timestamp_model_json2 == enriched_results_transcript_timestamp_model_json + + class TestModel_Grammar: """ Test Class for Grammar @@ -4669,6 +4933,116 @@ def test_keyword_result_serialization(self): assert keyword_result_model_json2 == keyword_result_model_json +class TestModel_LanguageDetectionResult: + """ + Test Class for LanguageDetectionResult + """ + + def test_language_detection_result_serialization(self): + """ + Test serialization/deserialization for LanguageDetectionResult + """ + + # Construct dict forms of any model objects needed in order to build this model. + + language_info_model = {} # LanguageInfo + language_info_model['confidence'] = 36.0 + language_info_model['language'] = 'testString' + language_info_model['timestamp'] = 36.0 + + # Construct a json representation of a LanguageDetectionResult model + language_detection_result_model_json = {} + language_detection_result_model_json['language_info'] = [language_info_model] + + # Construct a model instance of LanguageDetectionResult by calling from_dict on the json representation + language_detection_result_model = LanguageDetectionResult.from_dict(language_detection_result_model_json) + assert language_detection_result_model != False + + # Construct a model instance of LanguageDetectionResult by calling from_dict on the json representation + language_detection_result_model_dict = LanguageDetectionResult.from_dict(language_detection_result_model_json).__dict__ + language_detection_result_model2 = LanguageDetectionResult(**language_detection_result_model_dict) + + # Verify the model instances are equivalent + assert language_detection_result_model == language_detection_result_model2 + + # Convert model instance back to dict and verify no loss of data + language_detection_result_model_json2 = language_detection_result_model.to_dict() + assert language_detection_result_model_json2 == language_detection_result_model_json + + +class TestModel_LanguageDetectionResults: + """ + Test Class for LanguageDetectionResults + """ + + def test_language_detection_results_serialization(self): + """ + Test serialization/deserialization for LanguageDetectionResults + """ + + # Construct dict forms of any model objects needed in order to build this model. + + language_info_model = {} # LanguageInfo + language_info_model['confidence'] = 36.0 + language_info_model['language'] = 'testString' + language_info_model['timestamp'] = 36.0 + + language_detection_result_model = {} # LanguageDetectionResult + language_detection_result_model['language_info'] = [language_info_model] + + # Construct a json representation of a LanguageDetectionResults model + language_detection_results_model_json = {} + language_detection_results_model_json['results'] = [language_detection_result_model] + language_detection_results_model_json['result_index'] = 38 + + # Construct a model instance of LanguageDetectionResults by calling from_dict on the json representation + language_detection_results_model = LanguageDetectionResults.from_dict(language_detection_results_model_json) + assert language_detection_results_model != False + + # Construct a model instance of LanguageDetectionResults by calling from_dict on the json representation + language_detection_results_model_dict = LanguageDetectionResults.from_dict(language_detection_results_model_json).__dict__ + language_detection_results_model2 = LanguageDetectionResults(**language_detection_results_model_dict) + + # Verify the model instances are equivalent + assert language_detection_results_model == language_detection_results_model2 + + # Convert model instance back to dict and verify no loss of data + language_detection_results_model_json2 = language_detection_results_model.to_dict() + assert language_detection_results_model_json2 == language_detection_results_model_json + + +class TestModel_LanguageInfo: + """ + Test Class for LanguageInfo + """ + + def test_language_info_serialization(self): + """ + Test serialization/deserialization for LanguageInfo + """ + + # Construct a json representation of a LanguageInfo model + language_info_model_json = {} + language_info_model_json['confidence'] = 36.0 + language_info_model_json['language'] = 'testString' + language_info_model_json['timestamp'] = 36.0 + + # Construct a model instance of LanguageInfo by calling from_dict on the json representation + language_info_model = LanguageInfo.from_dict(language_info_model_json) + assert language_info_model != False + + # Construct a model instance of LanguageInfo by calling from_dict on the json representation + language_info_model_dict = LanguageInfo.from_dict(language_info_model_json).__dict__ + language_info_model2 = LanguageInfo(**language_info_model_dict) + + # Verify the model instances are equivalent + assert language_info_model == language_info_model2 + + # Convert model instance back to dict and verify no loss of data + language_info_model_json2 = language_info_model.to_dict() + assert language_info_model_json2 == language_info_model_json + + class TestModel_LanguageModel: """ Test Class for LanguageModel @@ -4911,6 +5285,18 @@ def test_recognition_job_serialization(self): audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model + enriched_results_transcript_timestamp_model = {} # EnrichedResultsTranscriptTimestamp + enriched_results_transcript_timestamp_model['from'] = 36.0 + enriched_results_transcript_timestamp_model['to'] = 36.0 + + enriched_results_transcript_model = {} # EnrichedResultsTranscript + enriched_results_transcript_model['text'] = 'testString' + enriched_results_transcript_model['timestamp'] = enriched_results_transcript_timestamp_model + + enriched_results_model = {} # EnrichedResults + enriched_results_model['transcript'] = enriched_results_transcript_model + enriched_results_model['status'] = 'testString' + speech_recognition_results_model = {} # SpeechRecognitionResults speech_recognition_results_model['results'] = [speech_recognition_result_model] speech_recognition_results_model['result_index'] = 38 @@ -4918,6 +5304,7 @@ def test_recognition_job_serialization(self): speech_recognition_results_model['processing_metrics'] = processing_metrics_model speech_recognition_results_model['audio_metrics'] = audio_metrics_model speech_recognition_results_model['warnings'] = ['testString'] + speech_recognition_results_model['enriched_results'] = enriched_results_model # Construct a json representation of a RecognitionJob model recognition_job_model_json = {} @@ -5024,6 +5411,18 @@ def test_recognition_jobs_serialization(self): audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model + enriched_results_transcript_timestamp_model = {} # EnrichedResultsTranscriptTimestamp + enriched_results_transcript_timestamp_model['from'] = 36.0 + enriched_results_transcript_timestamp_model['to'] = 36.0 + + enriched_results_transcript_model = {} # EnrichedResultsTranscript + enriched_results_transcript_model['text'] = 'testString' + enriched_results_transcript_model['timestamp'] = enriched_results_transcript_timestamp_model + + enriched_results_model = {} # EnrichedResults + enriched_results_model['transcript'] = enriched_results_transcript_model + enriched_results_model['status'] = 'testString' + speech_recognition_results_model = {} # SpeechRecognitionResults speech_recognition_results_model['results'] = [speech_recognition_result_model] speech_recognition_results_model['result_index'] = 38 @@ -5031,6 +5430,7 @@ def test_recognition_jobs_serialization(self): speech_recognition_results_model['processing_metrics'] = processing_metrics_model speech_recognition_results_model['audio_metrics'] = audio_metrics_model speech_recognition_results_model['warnings'] = ['testString'] + speech_recognition_results_model['enriched_results'] = enriched_results_model recognition_job_model = {} # RecognitionJob recognition_job_model['id'] = 'testString' @@ -5384,6 +5784,18 @@ def test_speech_recognition_results_serialization(self): audio_metrics_model['sampling_interval'] = 36.0 audio_metrics_model['accumulated'] = audio_metrics_details_model + enriched_results_transcript_timestamp_model = {} # EnrichedResultsTranscriptTimestamp + enriched_results_transcript_timestamp_model['from'] = 36.0 + enriched_results_transcript_timestamp_model['to'] = 36.0 + + enriched_results_transcript_model = {} # EnrichedResultsTranscript + enriched_results_transcript_model['text'] = 'testString' + enriched_results_transcript_model['timestamp'] = enriched_results_transcript_timestamp_model + + enriched_results_model = {} # EnrichedResults + enriched_results_model['transcript'] = enriched_results_transcript_model + enriched_results_model['status'] = 'testString' + # Construct a json representation of a SpeechRecognitionResults model speech_recognition_results_model_json = {} speech_recognition_results_model_json['results'] = [speech_recognition_result_model] @@ -5392,6 +5804,7 @@ def test_speech_recognition_results_serialization(self): speech_recognition_results_model_json['processing_metrics'] = processing_metrics_model speech_recognition_results_model_json['audio_metrics'] = audio_metrics_model speech_recognition_results_model_json['warnings'] = ['testString'] + speech_recognition_results_model_json['enriched_results'] = enriched_results_model # Construct a model instance of SpeechRecognitionResults by calling from_dict on the json representation speech_recognition_results_model = SpeechRecognitionResults.from_dict(speech_recognition_results_model_json) From 79edcfb5793e53d51e0eab38de11526e441674d1 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 23 Jan 2026 16:32:27 -0600 Subject: [PATCH 452/455] ci: update versions --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 7e3cb47aa..f74892b1d 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 11.0.0 +current_version = 11.1.0 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 344ed4c94..77f1fe77f 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '11.0.0' +__version__ = '11.1.0' diff --git a/setup.py b/setup.py index c0dd43034..b2f7001a4 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '11.0.0' +__version__ = '11.1.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From 2704b1fb0927f9df1ad3bbb6049e53ebf73b573d Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 23 Jan 2026 16:35:09 -0600 Subject: [PATCH 453/455] ci: update deploy job upgrade authentication to trusted publishing and use python-semantic-release --- .github/workflows/deploy.yml | 114 ++++++++++++++++++++--------------- 1 file changed, 67 insertions(+), 47 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 781cee26a..d0aad3e74 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -15,61 +15,81 @@ on: # Allows you to run this workflow manually from the Actions tab workflow_dispatch: +# default: least privileged permissions across all jobs +permissions: + contents: read + jobs: - deploy: - if: "!contains(github.event.head_commit.message, 'skip ci')" - name: Deploy and Publish + release: runs-on: ubuntu-latest + concurrency: + group: ${{ github.workflow }}-release-${{ github.ref_name }} + cancel-in-progress: false + + permissions: + contents: write steps: - - uses: actions/checkout@v2 - with: - persist-credentials: false + # Note: We checkout the repository at the branch that triggered the workflow. + # Python Semantic Release will automatically convert shallow clones to full clones + # if needed to ensure proper history evaluation. However, we forcefully reset the + # branch to the workflow sha because it is possible that the branch was updated + # while the workflow was running, which prevents accidentally releasing un-evaluated + # changes. + - name: Setup | Checkout Repository on Release Branch + uses: actions/checkout@v6 + with: + ref: ${{ github.ref_name }} + + - name: Setup | Force release branch to be at workflow sha + run: | + git reset --hard ${{ github.sha }} - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: '3.11' + - name: Action | Semantic Version Release + id: release + # Adjust tag with desired version if applicable. + uses: python-semantic-release/python-semantic-release@v10.5.3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + git_committer_name: "github-actions" + git_committer_email: "actions@users.noreply.github.com" - - name: Setup Node - uses: actions/setup-node@v2 - with: - node-version: 20 + - name: Publish | Upload to GitHub Release Assets + uses: python-semantic-release/publish-action@v10.5.3 + if: steps.release.outputs.released == 'true' + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + tag: ${{ steps.release.outputs.tag }} - - name: Install Semantic Release dependencies - run: | - sudo apt-get install bumpversion - npm install -g semantic-release - npm install -g @semantic-release/changelog - npm install -g @semantic-release/exec - npm install -g @semantic-release/git - npm install -g @semantic-release/github - npm install -g @semantic-release/commit-analyzer - npm install -g @semantic-release/release-notes-generator + - name: Upload | Distribution Artifacts + uses: actions/upload-artifact@v5 + with: + name: distribution-artifacts + path: dist/ + if-no-files-found: error - - name: Publish js docs - if: ${{ github.event.workflow_run.conclusion == 'success' }} - env: - GH_TOKEN: ${{ secrets.GH_TOKEN }} - GHA_BRANCH: ${{ github.ref }} # non PR only need to get last part - GHA_COMMIT: ${{ github.sha }} - run: | - sudo apt-get install python3-sphinx - docs/publish_gha.sh + outputs: + released: ${{ steps.release.outputs.released || 'false' }} - - name: Publish to Git Releases and Tags - if: ${{ github.event.workflow_run.conclusion == 'success' }} - env: - GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} - NPM_TOKEN: ${{ secrets.NPM_TOKEN }} - run: npx semantic-release #--dry-run --branches 9388_gha Uncomment for testing purposes + deploy: + # 1. Separate out the deploy step from the publish step to run each step at + # the least amount of token privilege + # 2. Also, deployments can fail, and its better to have a separate job if you need to retry + # and it won't require reversing the release. + runs-on: ubuntu-latest + needs: release + if: ${{ needs.release.outputs.released == 'true' }} - - name: Build binary wheel and a source tarball - run: | - pip3 install setuptools wheel twine build - python setup.py sdist + permissions: + contents: read + id-token: write # IMPORTANT: mandatory for trusted publishing + + steps: + - name: Download all the dists + uses: actions/download-artifact@v6 + with: + name: distribution-artifacts + path: dist/ - - name: Publish package distributions to PyPI - uses: pypa/gh-action-pypi-publish@release/v1 - with: - password: ${{ secrets.PYPI_TOKEN }} + - name: Publish distribution 📦 to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 From fb4c5800496e7081c4cb7e9dae1205a88ccec3cc Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 26 Jan 2026 11:51:28 -0600 Subject: [PATCH 454/455] ci: add configurations for python-semantic-release --- .github/workflows/deploy.yml | 17 +++++++++++++---- pyproject.toml | 19 ++++++++++++++++++- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index d0aad3e74..a99ab6f9b 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -22,6 +22,7 @@ permissions: jobs: release: runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'success' }} concurrency: group: ${{ github.workflow }}-release-${{ github.ref_name }} cancel-in-progress: false @@ -45,20 +46,28 @@ jobs: run: | git reset --hard ${{ github.sha }} + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.13" + - name: Action | Semantic Version Release id: release # Adjust tag with desired version if applicable. uses: python-semantic-release/python-semantic-release@v10.5.3 with: - github_token: ${{ secrets.GITHUB_TOKEN }} - git_committer_name: "github-actions" - git_committer_email: "actions@users.noreply.github.com" + github_token: ${{ secrets.GH_TOKEN }} + git_committer_name: "Watson Github Bot" + git_committer_email: "watdevex@us.ibm.com" + + - name: Build a binary wheel and a source tarball + run: pip3 install setuptools wheel twine build && python setup.py sdist - name: Publish | Upload to GitHub Release Assets uses: python-semantic-release/publish-action@v10.5.3 if: steps.release.outputs.released == 'true' with: - github_token: ${{ secrets.GITHUB_TOKEN }} + github_token: ${{ secrets.GH_TOKEN }} tag: ${{ steps.release.outputs.tag }} - name: Upload | Distribution Artifacts diff --git a/pyproject.toml b/pyproject.toml index 07de284aa..09eb447dc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,20 @@ [build-system] requires = ["setuptools", "wheel"] -build-backend = "setuptools.build_meta" \ No newline at end of file +build-backend = "setuptools.build_meta" + +[tool.semantic_release] +version_variables = [ + "setup.py:__version__", + "ibm_watson/version.py:__version__", +] +version_toml = [] +branch = "master" + +[tool.semantic_release.changelog] +exclude_commit_patterns = [ + '''chore(?:\([^)]*?\))?: .+''', + '''ci(?:\([^)]*?\))?: .+''', + '''refactor(?:\([^)]*?\))?: .+''', + '''test(?:\([^)]*?\))?: .+''', + '''build\((?!deps\): .+)''', +] \ No newline at end of file From fe72a0e3e0ba8ef1ee6f5beefb1e4b91e38389a8 Mon Sep 17 00:00:00 2001 From: Watson Github Bot Date: Mon, 26 Jan 2026 19:34:43 +0000 Subject: [PATCH 455/455] 11.2.0 Automatically generated by python-semantic-release --- ibm_watson/version.py | 2 +- setup.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ibm_watson/version.py b/ibm_watson/version.py index 77f1fe77f..00eae9620 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '11.1.0' +__version__ = '11.2.0' diff --git a/setup.py b/setup.py index b2f7001a4..6947cb83d 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '11.1.0' +__version__ = '11.2.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__))

fqOc??jRL))w#OLhXyNf(e0gqZ}bpX;rk;^go+QY)}Ty+sNzf0R`C#jroS{w>L1+ zl=ZvAyKkZ86sCsh1@g`xBg3wwd&4S5kb{0Ov8FU9$aG*rDg4)0qHyN`aB1!YkK#p6dwK%eC}_E;t16i zkRf{uy(S-6Iz}u4LuOEU=bSi$99A4I6+?f;FGS?{uwFUDKyjAYzGt_SiFy42g_;Q^ zyhet|U}6)3MP_zpKfBeGt`s$pA)bi(XicrjPPf1(4})>Np+LK_FGW+U%rt%QPIm^* zCsW(cC5O;GaR}dhr(Z=iBDo$=XW%su7DVTB3*PNFXmMrW)f%*E0kUR3s8L6-X)`@m zv(sOuEgNR(yf| zsMOdRDBb}6rV@A9^?c}*%Q>5!J!%G>?hf}U3+6n6YDGdfZP30*&14kk$QvI{|IJ$X>4wVzc<>s67u1>8meD=3 zsVqp3mupnFt1l*l`TJS%vaDoBW_3Vz1%7|C6Yc0s8c08xibQ+(GoQX<32VC=zgreo zq9Us_g8vSIe>*u=K;z2MtL~M&PVO=s52#=0ovr#NFS6$;s8S{5k8yNY^F@L`!aO~! zRSvM`8#;JAv;Lc>?Pq;#SaB`@Q^c8&5mt{l&@_xjheLj$Cry52^)X1xlXzM?cAyHQ zufSYdu~wzH>JvMb3`RvDe|?qvS&zX$!7h5Gw!@xQ3%tL;Zj^%ej0FO-@&pBo%fW+4 z&JAT{vg2oO#tz=$irVZ`F{}=IktWi6*CH9Zng&SN#@SZDL7eQuI_zPeUh~uoW{lYb zdG;$_>nC9KL~>4Z0MGk?mWizPGVtXFaMc$`X$FQKhVMOxX0~Lf6lWN~&NT-rR|92v zp{UsBk!iXUm+=oY=>(j@WL4Fvj6Vmg@)RcK}AxvTIMVv}UFD z*BL10eqgwPXvnv7!LYXM?t3g|7odbckTR-6t+sN$5IA-SY;Ox@q|^M7ID0c6+&D5P zTzCyJMONgT2Vlcs{_hT*JA$=fLW1JaadH#W2Fd_}VLhKT$yL1nB4A%%cn5;p0>-+rqnY!!g1b=}_py zF(ioXV2m$(-|L*XX@fi=0eBL822GE`$#mqVN9vfgQ-CUc=hRT#k}YPPE1kDC<($47oiRD^hLbt9#5UEfgx8-Tr}Q zeuK)O>w)xBtVcd5UJh`6HZWWm44A>{l)wtv2aF0u;@gf4ge?i(z6F%06?h*B75f2p zK821Y%S2?HS4e8Nz@^<_(gy6H+ko1CynA&Vso*f983wKH1s+adwTLo6&PW8$H*&rw ztGAC4e&FmDuBruhFNuWF397XS3|bES4}_|BVRg3iG$rY8hkwn1haBggPsCn5BC7Ee z*nSkak7j-!pd^WKOCMx_yx3X_gAQxw5dMHaC*18{% zFbVjt#teM8E)^NaO`)!%z|t1nks3S+;`-)5=y*SiXk5zY$vac^!`B^NuN%)Rfx zq!f%OB~X17*dNUvZGzU`=ZQa|IYpRVUDhWAY!s}#g=f3rJij=;vK~i(i22~(Yj{94 z-jbaWz2WX?M)eE~k;tqr{$CHwv;iw$5Iv>fzYiSQ2dotE%85{w8|>O*b|o*^t>)1Q zyM*Gsi;y+yvO5jgml;sj4QO7I;A{jW-uA;qjg&tJs%=a}zxpm{xOF$Ig+6nNWCD8WU(Imr8#v8Jb4tye(!PdGp* zyH^Z}E)90F$MC3|WFM<1hcNmOR^<+NZK4bNBlL;}Kx!{wA%W+w0vn@|8_EOomDtah z{7;ui#&!yvP>`OPJ$laCKV^T?@Q#weP=I&~w(Vn={$oV1cuzc6M>D>Y{C|_(i3JY6 zFt!)aSTajlpS7&hS)QaYPeNz!f}z_ve~7U;WJVxbMX|nNe*ZwzR&)NocV>xvzY)oy zIedCNXWu|q;(5+R^rW?1dx+=%z@qs8sy+=WGMHW1%(G9iUNeD_diYY(=x2M$j$3n#mt1Vy_D9eEA>7G|wV1N%1M zJC<>L1tN2SC5^z_qTo*ekYB)CRk=EAoEP}b1~z2nuShVj9;=)iO!WtfQn6p9!NGi7 zk&fAC=I%h?>?^SK9oTxn8Xv*3rXXt}w0AM|ihM zF!JwSn6JzgYP1@AWMNdD!0CnHa|a+bfVH&oj5If}+dT}34Eg-9Rkky4j)-4J+PHRQ2Ij7i0Y{|)so0`7#c zhEH1U^fF;)u!<44y=AfRx&GV zlau`@$JmQ{;UguKHVLdzkp2P8I13za28y?`j|xT(u-`X$)>m*biEG|NEAO$}Pk4u- ziJ`z&dS+jmJ*>nM&=MqTla1|ABEn;;Ki`h9A5) zJ?oZ<`z4V5itFyOO0S?E-@v|y(6YPSNi-&NKEf<7p}kz^?*q(zBRIVQs6PrFy$B`V z4mPj$V#Gag^*z{m3yQQKh(FBtSGj607&8Hhz5^7Y8#G}J-z!<=2V=Yl#aIbW?c)t! zfJh&t!r%P$l3jYo+FRixsW?)w(?QJ4m)YC+J1eUh1!ru*rxwtd$Ga|0;4uyRn4Oi* z$66JKM`i=+Q*e)fQ-0;0O3z9QL@KyU$NOBYfD4T=J6BibD8iaL*}<1k0}r}cAy&UE zpTaz=IC!BTa15|J4p{3CKkEs8{f)#i7CdZ)tWlb4E3kuAf!FfOf9b`1Vs)@-9!-`L8rbUY?%FY?N$~9f%*~#kfIUN>P+&mVrJhno^xL zvmr;m;>x%19g}rR4UD7)&g_iy3+rUzS-BaFqM&&gQ!ef=;Dz7_?|&KDqeOP~1@CvT zrkS8Rp>X$)z}+3M7Wa-(*uj=h-ZQs=$d_KIO~tCHoeE+)EB`KKA3=9ZliJxGAh5w4N z^OafaB8)Ygmp-Ls&Y!$Hq-5&f%-_NNv8?Syo*u(@7FH%dFq@ZkNCT9F0a@vocVV8A zj~S=%Ql+Box#AC3%YBIT*cMMT0E_R#!rm7xT?>B)=8jpVQHi`=IA_!{VW?+2ZAJCs>#D z$kJ1hh8FO9IuJe_4X_VhfWvXXoy+f6v(8k6^|FAVEn}F+h&OmLE{KH{QQIz_*(fd%^MCyE882 z=oG+YFfgO>UGo1{^sAQ>-2-FQdp-j#zCc|T@GKY9xFknWAWu=Z0Qjc|KBFjGN$9nb zw(>$xivZz@L)wsjzA%FK?6n7Ld=~Cgv?G*vhI7AqcOXyk^+K(ZAr+-eW+#5~=Bvn) zC*Yu$fl)Isg+oq zr}K9otZEIRaEc!&i7%J;2};870V0%il?rId4YwcW&-#gEgTyHiXW| z&Ap+d?T|yN0Y7=zN>l>^8uM3eRxdYHEfX{@C2JT6hNWdaOK`q0ye2cB zNUm19S(iIHd7sgf9cazblof5qxlXK;(mN`7cS6aGN_tcrEd$TZ%pR2Dovo1j2eG#O zSl8y<+l=ScN3v2+uFejXpRh+bGIUrOlV}!kgj-8nRUaupPkI6wN8@#gS0Pt)$(w zyeIqrxUSN5)C{umto)o!$D5UX#08$%SSxiXe&>clco9T^f+(0 zz;#C$;~{=3&0dZF0@Q8~6j+O^o1 zCgCp~3?ChXy<|DObG!H1>KW&`_9AmR%Bc4<-YeYql##xNi~V9}|Lm}m(_^^uG|yKu zkK%@Ez6an6GvUeum_-NdVyePVUFa8=v+c~$ z13hh^cWiyI@OH!|)4_Yb6LLWp@7nZ)^AF_CsjS)(c=;?Wzq64ICLmjM#`jVdYjIiZ zKee%Vw_pTy@qU%U3sj7smGIpt%W+4t{K@Lzn;KZStMIcH-?YRd)Y9u2s>8X`#LpJu zXEm%zEx5ijBO8fLZZ_|nhjg(Rd)zYQj%Cbv2kUx<)m8g)fi?RVX?#91%vcU(3!Q}86&`c3{Y|to~HENJFMY<+`j=Gb|p_+!E+b!*A|{}fZg57-Yn<;ZS2QIu8-lk z$2|x6W(8NS0lv<9@!=+KS6KDhi<5TtN^!+!+;fH}ZDH4!@TAoo>locmp1%(cy$z{o zBk$P3Q|@_TUrBCC5B~)&8DN2j-^u(J=fx(9e1d83ndMwoFcOXWiY$Om+79a4(d*s# z2a5YQ6j9N^C}@_O(ayp%*pRCu@L)t@Ya5I9qAYz$U}q|5Q3vcSpNJ_5C8Fyd)|dWJ zz?9fN9s#-AS&kBkh{hcm3f?4msmLFOJYAx<11T&oqq`5wT7?MU>z$$wUvC5i;-7@`~MAx zTL$-A&9Qf>s)HS{QL)ihrG317PsvUd_|#$^Z8@(9K)?W`k@@WX0l5AdB#3=n zJ(DpjZd#8Ws0vRl%STCUb-f%|*)zys#sbopyGL;UIIn~-kLS$gui>mlbGT|0Bdo+v zwWl4CYlg7fd#_i2*W;f0j6}`2BkyX)Q>w6M#k|r%1t6p`tJ(*NYzlC<5P4@3 zFxrptx8ylhfgUAeR^hkOFO)8>4kcX_;~OQNwrAX(xVkpiE1ORp-l5*slk=_lzc>&Z z4hI!pPUwKfD5*htX)^$m#ekGDjHfJ5RdQ?)oLf;0RsUA$BFev_5p#PP~sh7QlCg;<@P!W$Fq?8RX@L)1cZ*ptdWa z>WiS-6X8~qps*pqLjFvbmx@EkMz#C$Et6dvaE2C8*}XU~OG4u{)JFqXBsn_&j{2k zm9MTFRJ;`uM;GEpMlt89T)P!HL&-I#7~=`%yPEfmhEEUTim~w8N#6f@!!2vTSMzcd zBUZZsv+T*pr?4(dScxr+YY(GQp4k07WfO0m>s_(MtlAPrF@+~hWJGfr%@(fM#||B4 zo&V#$OpzTqFHcdQ13X3fMU(}_ zgBM468`8pWf>`U{K-v$WOj*tofz)qsmG?l@Lm=)j&sf77m0ekRuy!*hB^zFX!zyj` z0enf>3!ZRC0(%z-YzrvoXWn#;H|}8^tGQo!s&+66<-xnfJul$RZ~4R`nSJ(3sY>&H zi*yyu@tE_<&!c2!gHiqDKP4yJWJFhZb2RUL0zX%NcJ*Ed*D24XizmHeJlDMAyUP_n zz%LurMcLAngzw=R<#|Z*Vr&qcH4I!<+G|E6`C`z7NT_inl&ApoI5Vr13A&_eSS!nQ zN~HcQ;D1f%Krb(ap9UZ43ms|#cZ}qIMMX;SxAF}snxVAC=1{1roKqb44^64SD=~>CV zJVVW0jjIwXszz7Bdq(Mtd3kqE?>eOd%9W?*98^JJ!#!YDS&HJpF2xD5L;aOBP?4P~ z&PtYGREk?S;%6j~6$&i=u{C`{?|bdl<{o=>3k9(ns~pI9{eV}cIV#9j(IjfT$}bbZ zXfrcACDD{(uF8&~WP(z>Rjo`xW>AGUDo*9+^_wYgz2ZO09%^D?Q!5(Gy5->x1@i@Y zT3W6(xZ=+>lrr;LH2u9R{KxMT1eYSggcS@2GO}@xg1$`LskD2=zfy3fIPY%2PIu?{ zocHWwbJ1to1 z6xB**_iVgXY3Knw%ke)+{|$Tb4j5GYR?!gse{)fEFPx8pBlUhC{z{LG`)7x#v;g)g zkDXd?wMuGS$^w#x^JzGg?@M`lRlG+bKDpV2^gvZM*747(E4Z$}%2#CcrI>3L-WSNo z6jy(SzH-y6YhQtaePEsaxm#K9m9?P&Pf?a-WouBhDkY=I&Nm7YBfaaEmzB%Nh?L(z zt-rEjDNBZm(Q1ekrljMdyiv_etx0MyM0p1?@vH!^FHd;}K0|w-0=c)mTJvSJv^zkr zqTx4?Dvlr%9O5{ICaW~v*Br0-{fU*evnqdNjR%Zh-SrT-eGiRQkm+JC{(r?3J^JI* z31WX$1dpQ3-?@@(SUw+lqB@ji)yiC`@4);Oy~)Zd2YDe}(QHMTRTPqf{RDR0g?ylF z8lT|@FBzB8!+&_seB$qSoK={l_FhGZDt|2z;H+LnR;G?u+Ei90MT6BYmFM&4P=4Oh zj36s}saDsI5gWWsS$Gw!)S? zL)b?Jnachc%6$C!DCh;NKYNnpyhqdZVn4hn;U^Cq))vsWpBsXRO-g6Af)Cd$Kn$!jUO<&{U3e_L6b zla*nN0{AM;aq6Tv%`1xewl8ut@u=5sInDB1V}JEyGX3a*~0 zS%Yl45xGg(kxp>_8c+SkJ_|;yD3RjvsTiqRSA|hZf{*8?vi&I>`mW5DWj9M@Q9 z zd!PK=i{Bqu)7N18H{>maHOjj~F@K(*?3a(Y@;+m_;~mv$W_6C)DCzJyG)h6W@--@t z(><@;L6$#5Z|M%bZxIf+Zb**cybDirvkMVuHk1TV)ADvzQ z_I~^(#w07`DV^8IKhyW!h1g~M96hD4_so9Weg0oFd;RW)^toZH0``Nx_)6arD?O*< zztmlc6aTh3Tz!!WGRik^eefo&WI3)+b#^&E@zu{I(a-C97xp~}j(@ec>27j`h4uSp z`I4T2JN`!h|4Gm0-&^DVnH1t>i#2STyrISZ*)zMO5sA57+Vde}f7`gno-l(@aKG+- z`M{CwGRSvHnmr_$3m@{>`5!w%UiY)j%$K^)-}V%4om}F7@7zly=@I?4LA#7i zO5bkSNJg)&pA@-qd;eFhU#I}{cuCj&YZ<|{+uP&KZ_u~d@p6b&bM+#r@7sHuWm9b3 z{m}>yYefIG=>N?c z7qo3U<&ph=*P<}u1iSam-Ij>QBfG+XHUiq+j=p^}aPQ_9ri%}8$bzkU&yuxyOSbd@ zUF~^&vPbcr7xe#K((I4wXi<%)_uk(9yr}W)SH$K;q007N{Ex>r`VG26dgDKOzHFF3 zHLnm4kPp9W&3GDjPV#M>K9uQse7*#%8D!c4{p{JOpR_#jdnemqP1Nm>xHoQn$@oPc z){BKpB16cC;ms3b4~eFbt9R<>4#_z3`?~3ltCA5vZPl=UzT9*FV(ao#?d8+jmCzdR zTVeOb|Q#G1uH{;l0g^W9*PP^2{5>8CwY7@n^;n{dkJ=l{B%IQOr+ z8a;kxd)rIA>2G~17e6n#A^rvHmlU{O($ljYiNapHrYFqe`D5Rcg%+Qxv0eX?wAX8W z-67j^{q_wDO8$Q1p1kJ{*C_@dTYHaI{if}-$1IV%$F+VR(~8@%pRM`^%mmcrZCXRO zZx!9Wqxo)fzjy8IYxT*k7R?U5e2dNt;Z1|wASr1+MoZqhvD~pUc(L8#Ag@?f+SeC} z%hDDjfT6nKvi|RpMBw9X(hnTY-Mcz0!mYasU-5SxEmQvYd}hAE294=I^LOcdKJr}~ z`I^g49;;?Dq_mJ{{+H(bCq0?Zwen7D?N}FI=;{8rXCf?dh z+^Fu~+^n<6E0~1qFCLl5%+)=in=LcXyL(XkblXK%!HYeqdELJM^8$8CV(gmq*`wF9 z`%O0YA)OU&iN$h*o*~Z@Lh`$<{qtM5@?4{dSdmtX93&Kn49AtND(|wjATz{C;XgNN z4Xo31mWjP{XC@PP<4|+_LB7oOds47rGLvIZ%THdloQ)T1ecz(l=gBzFI*szK$*73} zz?$E%b3qo6L$E#KB6nEUjaVyRUmQggMJ8e0#sd@Ld>i)6Ak;i*|30LZ#}5#venPV+ zYRvDwQzKrpmsNO=uFbcDTNd}Z}D3!kCG|hNiGg{i;ml%d!yg} za~c0_TlZ^(G8M7=daLcTz0O;n=y!U?|J%8)(-_Sq3j^L|ksjK%b^TOk`^6%VVtc`#6nT#^Y@|)z*_mW0mNuqxwNqF)iF`-ykmp|)l zqSvrRm-MgPsolk6WO0tvkt-K@;1T_*W9Y0)d;PF8{IGBTv~!5^{W(eZ(^jpx^QvUs<=0)wvZ}xvN7x=y3cE>!}S*w3* zWX47|u4=D}QrPWcM=-H0($BZUKbU@ip@;r?M^gQ*#i-wrZuoE`QET(d<;lV=L(yK` z6$iz5&SLq*ww*qaC5Jx~1u{1I_^`OD6I@$$TQL2}!yVyorWtrry( zJmNofH^1vs-uq9w(uG~sNag*>SfASrh`l=qUx-##^-UTFi(Cwt1*+y3mXq&h#jeo^`Lz(5 z_Tv4P&)4lrx9wd~S^hetCPdU)z5IK-zJHsJ5W9q*AdSu0?|QP(*6tCyf?iy!d%aT< z>R!uT-ffX=~Rq~(nIW-O#XAb@5SG_O2y=H2yG;8E*BB$;mh8Ex)mh)_*Uk zmzR`DgT6T-9dcGS@n;&N`W#x|+x@0aV``O-%=eaw`hPi1nXs|7U_@m2j>`Wghfhip ze!tIqYa#=Y{)_z$W>#Oi+CnIW`b z!@u3Q&B+hC^6%4sR-sW&W{vgsuU5s)y1oc0O?h?eXDmDQ95Qd`HLqv%Ja|Je*}v#2 zVzOTD}(=eKJvjn2qq3fMk;tn2idNS3Jj7QNK* zj#aMG2D+6-^yF8fxU3pG{C|6za)aWse{09dc!?Pdij%J_n*JZlvr!An+9Bir*pYl0 z5tbDU$OD^~2c-{>N`BvQ_yMcZj+_Y>lZ;hr@F)|(!Z6+dqx90HXJymfF zW02>7@V?`6Bs45-zfotj{^Y}1GBgt$fje2r5=_Kk5H0q=ty-zP>l-(Vf9W2110&^R zYDl4&*|T_LBY9s|w_Nj$m;EJPEYhrEkmY)_u6wt}e!rfr6~@=Xgzr& zPg!N=e=KuC+sm*|j{T0Efo_+VRoS`KVrQ^Dtk>^-?QiN;AVH5ejc;T$padl%E|9%m7JB%hE+N% zxz9eKG3Zg8LU!N(wwk`0ycX*|H_0vc@x6{xXSBw$cV+WLyZ@*6VXgTos{Nor{+hM) z^WK37R!RDyULyXd_19Os+U1@97v1N@X$AQpHUwPFIemK3qR;q1Rz{k36F z@o$aIRYke}H<@tb)`d!IGM?;I-2mke8MsH0>%Etl@@}1Dn|9EhmVIkoiK?;vC&MTY zYX$N?Si1Hit;EKad6NmEQLjnUiOaBPJc~ahwbW((v)z2lz7J8eN%BurODtdho|Yot z)lk}hqV@FZZQ4Ws>dCSrAlv1J)Y^QbyF0%bI%9b*DrV$={@R`1x$oQk8z&9c>f0(s zWpLEh8Uz1zG~?_N^@*b5bUciZCp9zA!uokLc|~U+{r}vZ@sVj=`wgbaO1rXEB};kH z^2B8qq3(I)gPM>ZQ=R{-R+=pPC0%23Fl-)GYO?IE`-N8OxmhssI##Y+6D#)QUJ&eO z_sO|^SLTRqE`Rj7-urZ~Pc9by$weJ7MZCU$kL_D$b>@qjvu}0wbNdUjZ*o#^$>u(? zqhPdUs_bouJ^Uf!*N!@(*!Mx<*j|x6epo*T_xt{#0{0EQ_wq34V&eN28{aFO;Pb=r z#j&^4obB6Dkaw?dB!~5_mvroY{d-`Uwj(>UDEEgOub7NnDE@~}cXuCe#NzeG_f*;A zr}sL$Bh(1sKVan_(>_x#Ab$rnhg;#o=3lI4tZ9*J`(I6(EaV>+J)!bJ{6-vIRBpUI z`iS>u&;PykA=)K6qHg!o{bo%~m4~>sSfT2Z(Ev~=YX8?;UMw5&hfNkOPoHD^V0noa z;L};V_rxSyJCPl+4>9HVjhAykJh%hM6kaj>G`SDsJvrHbE|xuOitHxA#V=GO z!_z)Jsj*L5>_z3Ao|oo(LL+)$qqLvx@(q`xc1izE+$4}{6w1PQM0ZS*V#2q{bD^+A0mcd>% z8?1Zs#mK~E*a@sr_$HD}M(W=>Qtp(GAh%#`T(?h1X!g2ql1l2T@7`UC-%iw7UC(ur zQ)CH$aU_HK(tkGl-oJihxl7M!(?te9c(MKwm-UUqs#tma7rV^1b`E{vXnjGM?(U zUf5H9ZcljEtaa=PgF^GKNRYXMhcSDis{h{E*6y|LGK$$F?tPw+$}0Io)`Dot^?NQN zaN>Kg7x!ttSVMIBztXMZiE|9RB#&mBtca}|p9}>*r+~V4+KwYVa6_phq_*v4377;;ZZTjZD`hAV= zi9a#Wdg)oMBh}I_V}- z`>SM{3Tl<8YItcz`bu`eYifCa+?kD+g(C)m(}f)gO~oS-D}@&mXTGR^G2zhAgCK(e zUx~h`j~dj(*-82@H8QoX_&3ILx~Bg_3|-V`SjgV9XdYG1s(s+qUzZ+I*FqP3dC_J+ z>MnQ(a!b&Hu*L36wV5cu=lb_cjR}V0?~DBA2SNnhxV84Lv;+Q~^E%%r8>hIBc+fd% z+zXpSb;NQnJf1%^Qjs)~5qOy&E#FgB_TC~@^qV@TqqF`_?OagItOm9)P622-coW(i zzs&nP>Vy5TT%okpq(K5<{kWvpcbaK4ui~0#r($X9*u4)M?HTy@7d-*^JHN}cz=RC` z=R;ZOI8gBUz}%mj*8gPpxPldtZ4jjr!Md>PP9-ruvTt<%kmGm~FeeR9A0h!BJo}5|jFCpIJ3_A6(R*vLk#;Y*kio^a@!{r^-{~Y`9mF3@TCeY@LGA z1)DVrwVpTX#p+ZcuP%xeutPd`x8&=yvi=|4h{g3u!v`em#Jacb`!eiL>`1Te)3c9H z_HVx+Sya^01FCCP)4hvVP}(P*U{KeH#wwA<0N_ zeW+^)HhMrbN>mK@mTUu!0WHM$6^C25XC!kX($Ch}s3V}%H}AS^_KDKTmaMbfjaWSl z0Dl0ggf0~MW?fl*!^j|dg8gFf_^|SL7(~@>*R$b=z|-+VWTHmK@=9qfI88YN=ys7f zIq}={tX2NQ#_~#iM;vNZPmmY3s%H*EIr^R?8Vv!X%i5D$84Y*y)(tI#`G=N;Rkn`s zZHVhZGm_|bGkn{Xtq>73c}6*TIUrFN{1Wo4b{Q0hk*P%_lV#MfC5oJg{mZM;1`{I| zeGp~ltKX8M}!} z$dt$kui3jW3gQb!Z??VIQ!AR;NLa@rrgN`i#w;e;FaL+N9aO+bViNxbo%?Rf+OpO~ zxa=R6sW|bP&HOOTKmn-e8l;yxIyesT&#SsW67$Px3Hk7eY>P5t-J592AQVJ}hpUNS zJ4oi0oDNM4Cp)}3UvIX5-rchPhR;Mc6ideEl4GAvwtYHDqdx1xp2)8|7wd!-1HmuD z4F}3I6~z+m8r=6ylBu55L}~}=AvVc&`D@Qm4g~Mc#93CA1>j%brF91hJX}n$@K)zk zi}OOQ=b!YF-~MY-4`0k6Z8mEcuzAF;)NzlOr1}RES2jQf0?*rl zy*(BN@@=wcY$NhPE&Z^)tXkp#>@53PyxN+ClJT7X)RVtOdvNn)%nnOjW0&OAc0J2` zHcoqfyft`H){G4KkCxSbS>yYkzJJ}G&F!1PO_NW29A3iIhr*J}K(cVjAq-n2ueb)8 zw8Bb9R$0-o++x^9@|2`46yF}%)w?eiEezzH+Rc!-gQS{u4hJqf3^@XKNWRFCLY_eL zY?g%Irg_6@v0iIg40YorjtGhJh_1I`qhb5mXZDwjAIp@Tj?F}NM|B|f4fUb-OOB4` z$rGe8NIX%je=L^mT{`1~dO~UsCMpSgU?td{f6G6Vfww2j5jR;^gJJA5Ttxy>qbyp>oJxQFkj= zL{X$$^pJf3Q!>``u(LqD;C_V;`1kIX4jV6>cc`8~hE_yYd;*iv#2>%c_(iA?#p`Gdu*f#fBqyvVNyDU3jCP5Zq>t!5MuO!kU3UJRxbi1Ac zMkkogU-z%rC;iA%mkp!GR$>6d^#L0)Pv!Q_tjwdlncN|%1`~u$$rBn)Y>oY5Irkc! zb4Dy5qn1)#B&5@DOYjV2Q)QUdT+&d`GH?g~+q*D9gABEb{*soR>WDQ$@W2IpzI}{O z!OH(w8VmMsxPxG_CWm2-(pNHa^r2|Gl`mg?#bU|BPkFKHMND~7BBW|$R*M~*Xh^E@rlqq zu$TC=-9Y!rCwjp?35zbX8}>nW>%yuI%#W?;qJb&S7jDCV8+gk~)uQ z=iaWT{qsg96Jktih_GZ`(aM}$)6d&oS2WV^bvCv#6e2xg#=JbK;cA04`)Mmn8~`IZ zTaSgqig9mrw7jQ13eUv58BgVU?bTuI1TGAUv71fR4NK(Enth)$jWYr>U^Q+b5Wmut@l4(ya8(Ry=mP~^ga(nL`HsJ zF8;D>-{B?60^_QrD`~;Wxt*U35&w~KQzrujB>rMXKh_Uc7kHm@mT|#+Ld24v*hgh) ztN}Glc-`dpPA}$gbhssaH81bypb$!LSP(}aENUVD@cq8cXHrq6M(4|Y3&#!ap?7CP z$i;l5k%;+VACUEc%!D=-bKm!VR)itw3I-=qcZb zMad!*YlhBaV~VN51B!E#RoK_8hP(HP>JY4l@G4gK@7wXJ?C#L#_s@owYryJ7M?a}3 z!FEXwcE3z9w7ZPx_MK_V#`uW-WnsWJ zKffHr%gQ3Cn#a+CT^N4~s1yYF!k;z1^edq57FsvQ64SmIZFpGmul5x{urbj8gGnK6#V$$duP=ImX1C+dTXy6p z+l?m{n>(TX02TLx?r7K@WkP7r2lq5Q5jC%qY2l0U*WB?`N#f}Ic4Lwc#oc8O|Gaxw znP^qXN6YZDT&!&PA2ATQFt+jk^EuSW$j?qCCGP=KDIY@Y8^gYc_2umgH5zi*V*l&5 ztKea+TJiq-FKZi~1)AjceLj40^niUQ8{|rC2+F?;(p662p7MwY$u?Nh^^9jL#S~WO3BoLuEm7LH_v< zn$b#O#mg3tbvrD5E7m-O20f4KfCWe!WA?dcV|;MqctF41uJho%;~fq^gX)bzjf&LB zicBrAI)Rv&GD^Lr;s&3?iu$OirQ&JN1}nQ12vUo(GI1n;a~GUzhm zXZJfTcXE6B_*4_T15?{3eZ(LO)Bm-<@A;$y+)a_qJLhm{q#e|=eed^*pH zn`hTp;c&z4T^9eSzA=11m}ow__znDX`xVmYs==mrLoAD zi0aFV9ABR2&1qA-LMJvyGVfnXa==2X!?3Sa#O^nZWq0PLxCEa z$bp&%71p>0r{-7Q0fza&Y=%R-ySF!AAL)n-8uNTl_6@rttO=HF@mG1e$ztI#YD{|MqWL?87|*(wxi z^*ba{*eqKn??|?1CUG8>M8utk??xp69Rq_qb`IXWjXPdeMFqtQrdCDsJ=5d36U@H+ z1e~eaWRb2gOkjjqt7A9s`#UC2pO-YZ^Q{&=~YiS4j4;bmD_Yy;@E zojS*EX(l-`ahdz}TyB-#h09gZ3DGPIHZ>%$wro_HCg^5)0Wlm18(ApX`>6|DVK^G( zEUpz1Tv20p<>~Y8AhzKgo{+A^N%xFinCZ6b9@w~iEa}A!)lja@`rMTDoeNR zILAYFv(MSvcmUbkV(yRX_-BXzcuB9l8?*5~t@Zx&{#6^l=Q38_l_h~$` z!K!60PpXKLoSO_I$<9j#sw5DrgAKZ0vp(1w2rN;#iK>Xpsfkws^W~)8Zx*}U$`X$n zZUsnJC_3ltg~Ra(T~J)cfnbcoOPn#2yA&LF>}EG$>w+Q@WoI^upLmGm0ym(eK!KX#=PN zSV0yN%^>1GvA+v?2Q~sm1(!Ycb{-E@FifZCI{Zw-CX8hmW>bAV&8kiY(m{2mSvkM) zUfer4reroIZY8Qn1O2mSCi<^_P!1LLS3Z}Y;)SWiIaP(h`^wJ@>eu_K_eGd#=9OLo zA}^5nQ;GGnMzf;PS+B37t{@9wjNzzj!_MT}a(GF;md-UCPmY4bi)e&B# z^6@Tjve@J-+@;(MyE{AIJE+7C8N&B6b4wm&vbmZ2!Ntcv~QsZSpn@gSHx} zGQ^djM1HyKAI}_{;59vSkrJ5)D2(Yh2+sh`XTQzbA}t01z$(4Erz74r{PVnFNCtOj z-sGvpuyBmY5Du@67zsAI>6J9~Gti)T7(^%Ky2(L#b2$*`Th^&_iH_*{^w?~N=Pg#Y zE(>s+>_ID!<;K1gy?b(Y21{dytdNNvK|<&ur|KKF3NA{Xk&VmRR0B5E#dv>*HBTR? zr+1#GXLVrl84Ks>*&?rsHTjJ(^Sn6@VXQv~WYOvWFg*_RPZTYL-jKr>4!HX+XWgo6 zLf$^LV+Z?;D+mwbBO3+8)uxSZtE?@I!WbByoIf$I9r{03V|J4soHC^1sMga;3=nb` zYF89ibrTenS!5NGacmf?8uk&6ksgpqR_#be!0}FuLnhv{8`J?SUY?dG0okqMlC?U~ z5^)ranXpl-%6zJz9Grr6EJIAD$`7h#8+Jad{#Uj7#C_SwbnO+bHl1czIK%u5DCzeBK9hz)eX^t zq|WdVtg-C(!5Q-(NdYgi29gR=X@vvlntmsJE^pUBR*J^ZK$toHu>Y!Q}9+R4tBv!Dl!;Ej%}#H%#6jU_4!w zx>hL*g2cS0Ihg)YYUSm=pv?wDt=jhH>3teSd>q?{=$QyO%UBfbEB&PxAB%z2#{v}x zX6ea5lm76ZkUp4%&d;(rDJ%Nz3qIr>+0t0uuxfv>_i=w5*X!N=|JXh`I&1r=K7Via zgIwKoR+3YcFN1KE5&S@(zq7c}VMWOf@Bdyns72 zBlGSeY_9Xc>ui+R0cK~}%EPY>=Mj_jQJy|Jyo*}f84I(xC~*Ga8BreMOm+N#M79)m|^E$UV{8Do%9|`Gih7Ut&+p%~b$h$k+dmr#jf-hik2AG1nBC}}hb6m*IZxg|BxB3YBo=aD zl`RJ*^`DR~xM#bFRD^Dmd!OEU>RZK|XcKX65gNYvFaH1NG$S;c$oyo_Xrsq=UHN|u zN)PP!$9ME|7L7YKtB^W4JT_{kAn!Ks|MHOH58F4ky~}7E+LaGmIPLaoyt{W+j2)YG zzAd^BD4j<)ZY)f)mOOQpsq1uARY$TCkLs+rTU5H=D7mP2mCn+7J?+w!rv8>Zk%f_u zd+-wf*sgDTYLgpzdiS|&KQt}f>R;MdRP7~82Ihb=Fo)OG;XS?dUHD|LGnekCM^&>c zhxo#t-gA5HnO1*xvn#S=^zNF*+NK$jW!a^>+P-l=v={ynu`D$y+x3loim&NPaA@%` zJs0+BPUK&9YBYOvjf0yl9UJs$dST~+rV@iOzv5{+k9rrk$vv8r)#?$6HAM7~&n(W% ziWGN-Ui)Jj=MK#u9ya!ntkI7BU}7|L>n!I`W&72<6|5kara@^>nGwDd>?)=Q8A@J= zyfjV2w&WY~LZLtC$-ngXpyb7NRn1Oa?H3mbruISxee|WiD&ny?F5vp01-{h2)TI=f zJ zUsToN?)9#DT-^T8td8*&eTTgHNN3k68f%iVKns7Y_mAj22UPR8XW!bboXB&MZ7=Pt zBK#*L!FaoTJ#qz>>2t}JGm@-2E6c;2)bC^_hNxo}Ic?N0?B`WwOWu`yhQ0bka%lQo z4s!|F|H00CNwdAG{=T#yL^)rXB_SIBwWQj2`&*w>9l0QM@HOH^{8h)0c*CHJD`W+U z&&puSv2DcBZq~Ekq*Z|NLCySQTfcVV{W=%hk{q+^w{EpOx2W?0OY|A*q+GgwYcFUg z?A5o)3VBFTzA!swGZ{{LC64S9xP_|h@sxSph*8rU1(o_17cq9YU@N_zPti#4DN zlFk#S_a1Gbd@MylPteRd-H1c6-Td&u)N2Yq0Rz9e`@aDdK>au!aiReLF@K^u#!z z{iQ3$i>m~Faj*URU0(~mD~@WEhja%0pblR4>06sGUC0kvcIopv@6+0GFX(EAHqR$# zEr^FsjlJlc-KMkD*dj7UaJ-^|bh>?YR>wdHl2GFnLmA8H;VNMF@lC{9`0m4rz(bz; z4E!DtE8d}vG5X=Al%rOm0z0pUgbgpIkB7nDf*9m8G$r~Ez=JCV1DM_?NOb4 zUe$h*XL(9H8g|E-CwJ~D@+a6p_=sXQ5N4_{$D4#38^rv29kp@aduX~#btJD0Q`h$C zy#w=%-%9hZ(+G?@X_f^9m}y{?@l`6$&ou#+?< zHVs(@dwuGTU?_Q@Gc)E)4{-LAsKPeg75^58kq@TPG)ZI17V4St$(xOK!MDjw8)%w7D!1J9d z(Y3lqwOZTs!pEr#*3Lb{$M;-^EsZ5LtfMNSU(mQ55`Yb0BWtaYc1{6DzQ#>OU}ZIOqKQ?{kB8j zRoSI#!I&_{uzaVMOgG1;wGN+~R41F+a8F*WNNmH_{%|~CRL1keQdTWy%|lZ^x~uEg zv_;Q`KR=8u5I^ipw#Y}P&NUK=gmJTOV z86r~ni*~d4CLbAZ8x00M0w)ehVm=$K;mOfSOP?AE&2wpC!>r>=Iohgg z;BjS<>&c>enT;(PI~aMn%Zcwo)m@!*Qxl9InI|l!M*CsuP}PsGLOf*Hj9{bHtBKi6 z-Hr+nH6f}Mr(SESvH0!3OiEs~SYGO7b)7#yo8%W=XKJHl6DDH@X+yt?cEB{Kr&Z@6 z_P$2ibaGda*q61FuvlW_9SzKLQVAitE4IWQoEnnfrjy0(aRr)Lae+H^rE5Ayo`w{M zei-gDmK*$=vqH^~_3{VeraUXFNM-g^s>&GYoCHVlg~jXteX>GLC!W3Q7fV&o^{wt- zZcBGwe4LokFfL=fgpI(0H&{+pDB?kKRBG&a)+ePgk4~c;3(+B{6yE z8FfT2J)sV&1J>g^_CHtMW!3Fh-D=gX>n*tcst4B1ajR9^^u5Q_op7h6`{Nd?Hmj54 zdaLfe>Tavn>FBjrt=sSSt`p&%`u%S8t$I*>ARpRm^ZG+RwC``%x3}x{xH=VX(P%d8 zTen(uqgB_9aDVkxH(Yh|u6U1nOm0*6tEV>lXD%Hocdm!l_I1PBxNEK3x$oFfx9xlX zvFeuncBg*3VQ08u|6h02MqP2+uJVMXv*b?wf7|Z);a%(Dee$4HoAlbWzl`ajjmkT^ zQQo8P-o3G}SHG=wx`R9Sx@+&gD^_w8F|bCd3IgH`wG zd+Yc6mR)y;r6ZZHUpp_p!CpOu7iYojpG~7*nelA7%*Eq7<{7b`=*r2WIjGrxYc|sd zv-QsEDPm}Wff;_5ld>2w1*w9@z<=3dZ@}2tmDBr5WbYfT1k8fJY2Vy5nIgKUiy+1_ z+-#3YPCg^)`@AH|Gm|Ti>0LVfu1TJICC@NSO~m@BIx_NKkIsWUB&~elViCL|i{OpD z`_Xy{>LvWu)h?*t;Th@b+r1hW9ka1JLJiA zNj$0lzo)-W$_6-l=}>rH{fR%f+Bx~mr+36reeWgd3UTaRl7BDAhIw6Qcwd(PX{&v( zpEEl4Gpn7|m_C-5eRi);WKDdqBTned@9NlhEw2;nM0jei5B1rJ^&xyy^q4$q_XK0<1w*r6W7>Q1P!7mOIW!yQ z$j<$`j@mzMCr08owIaqJip$JpXv8cG%lT(-_|!@*132td-d9{*?dXg zdP&!Lbw9(;@rq?8U(?BH(f@eo*gI^LEz)~z12|MYx?!0P?yLuNM)&xP<$FBICoQ^9G;8ofzVr0Hv2Vv8 z(K>!zS9@`z)b-#Qt^BcZA<(z${CH|!)VL1r=fGYs?XGt343EuXP$kAfd3;x3bEgIiKx>)P70!zSOhb_=GMoe1u7zFlDlN#sd>AXMB?c^d6 zgMgD$9d_I4)&o}#1t>m>6&(JMKI1{bFrJ>zq-)@tmk0{xjraWjJWjP{P#IW1R86RA zq;X{m)z)L4{zBf?F@0BuW4#@pTeRfGd30|~CZ5*y$hGfvmd`ZOccrTiiWzF}Vj%k^ zUG-oYj@HSq<6I+0#fU^i-k)SWptC+H&9Zfxfb90#B)zt2dgZ_R*{W{D+jrgPE&lYO zT~{YZcufB3OO|-_^YSG1ne^H-$^P>EQvH$lZM3xP<2uKqJIgbc&tBfW?ALKmN#<|X zHSXK%{%MR2`*+jy-_~ip|VkL%Xvr7tN+G^e&B6A8OI9SElFjU#Vqbt9+`N@x0#Iys#?x z_PRxjt{>QJ9^6Y8&;6Hiy{6A!mz4lrKo7kq>%#2d<{i%6gPVzidUiTczOfm5V@F#F zZ%(I)#ZTri&#_+I$XkI$Zw2RXXy>EWzf z4vWRiAJEyvz>e*SpOf9BmK#eAUNkn;ms**k8nmbteq!f4v12js$+C!xe6-aC+xgR0 zq6p6KvQ5QvdCl6GFCK=-y)Ab zNc=q(AB3iVe(&s^?0sGO;mu35`Ox&l%Q~y5+76u)@Al&spHaTz^=X<@(kXgbzop|} z+j}odOVFZw=M&PGJaRJAb)VK*p3-mPf%~UfUYk8|LK^&xC8B;t`svJUhO-u1fwnrc zPd?Py-<&piQRfml$Ji}TF2eDY#w)gQSeom7*%zNF!tklAg%cakk?H6E?gzf~@U+=6 zY2_38_jMh=&*HD{l_q#ynp)T9lNTG}4IO__Iz%5GjEIn$ukF5QL%o9a-w~Cc9ub3) zeNeI)r_^MF9+QrEaPnVOuo#N0rn;YDz*XzO)6}7Pq6u&syg1Pnx&rsCCk8uVJ;3V7 zGGmA!?d8`e3ye8#I9rD&Lia-)b8wBaxbTysh1O~{(GIefzq)pft9P@?;lid)ck0## z5r8XhFlvwi!zs-NqL-jr)nBVmx^8QH76%VjCkX*1LJT@pUewW+>rl_x_8DO|! z*iTQI!?8n$>n%9kLRd)jH-K5>QK`b=TYa;0@ZI2S)EL4E=mInto?$QG+Gpj00Lk-zM99074wQn_-Jm(RQFw;S z8a=c8f>zfba?WK&ap~QmSi^l<%X)RIbCD66xF0Ob zru{AQXSG0KnR&HOc**<@bG1=N$sqCvtV4A#`cv(=tj6i7!>VE>s%6vh<$--ujXz|E zo~FZ(A>uMz{ts&u>vs)3o?sksN8GZ%H%Oj5d^tbXIIG;K?%eGBE4ivFbNWE427@q| zZk(bp;#crN5Q{pD*%Q#|kmnHS&`>I=9SOBPoM^)u1m~e^!t^qO+mjPr;Yjf0#2f4g zb+;@a7KnNRtW0VjM#la!>HdS(jn^=k4-!FjtQf=e+4H+|U)kEiMun+$#l}&YDN}z@ z{`toiFaAC0+_O4DkFwQ!rtV93M|gUC;lE3(e5dsxn*NQxJ5|HbCMq+mT$#8lT7l}L z*Iu44?(W;PwpMi?GGr<)@X)J8RRM^#^2X_fzxBQEx9(J%;OzWxyXvBjbCjCosVY+& zYPYVw+V490ymTWT{*&5u=XX|h5mTcCFAqmK2+~2=;;ERrBWP&|9+?u_b1J8?=##V`63J1j0dC7yzE_+ucsjMvKDP7nhs8lJ7JL7_~ zUnVLInFLWrZbFI3G`qH)Av!DqsxE!H-L7!&VIUaxb@+f`y0P2TYh8a~(NS%S4P= zQ`JZi-71dRNP`%Wmn31aoTwgxd6731xq@G}Ix)`;#$xKi(*v@5dL`CrN$!x)R zh%K-x+#Q|2dGhkHeUrV8eRtpN)n_+1y2`WaA#9Gw+C3#}_(Mgcj$0x=d-dt|ofRj} z&K<34NsjFCy#u47Mp%XLZg~e2Ejg^X%G;KR&>`8)aIT^&G9S;)7T&)rPmjsRHAXgw z$}^l<@|dC?SYBB{q&PW_efR;{HN$S`y4VBN%|i!?1F0_BqIXtm=f@hr{I6RQ8+Y;; zx9xe!eYg(np_=>Y#3%1h7u>!h?a<2?t!+K4%3wQUi6T8NUA#Xzl7B35e%NK0Wn9o> zS>WYUxhI!5RRio^EUi;GIRtxjt#dF5R{q9~TCS#{N4UTi2+jKa`Bc&6{U?0gvJzH5Er{;mf zBfK-MB+g9!D+brSvzp7-Y()%40esj<)q z?DtP4v(+1^aKJG7spT(u6kMGjN>8}5tUH@rW$j?{ri+S78vN$i`Dt5xC^AZ4Np=lS z*b4uQ+O5Ios)P2zrai2Gu*jH`)J93yO)CB^v6-%ZjLS1#)dKg-XPZxGAVjT`?4t6dfhTjOt% zfp~G%y<$bcoWkCqXX%*9CE+0?FV$uY^Uh!MU2fibUa!@S*X=HiLM_Eq-ApaaRP(5X z8U6y147d|n2eAs3tiM|_dAPiEvF8b1+;i2@K@3Pf;sZS?*{5$d0@=SmWtl=3eZLXX z(E4S=WwR3}ZUNDyN`0zvrZ?5}k6@p9K@+H(!|sRmakw<0Xg=R+(P;_l(%JP}Hhb4= zu4rG}6*`=-N&b{(gA90R(vbAspr>=)rLsY6hUS@B#bOK{#tNQJ8*s>K^=RVhX{SFZ z&rh`x+%+bZ+a*CrZ#avMd$KS9Y+`yEbBAp1ppFMok8@g|5x(12S+_eU55-Kd5gXQ=H>nMd(lH-=m7pzj=vz%TGA-fyv`Nm*~%98x>p$y|j5_kR?)Udq6Ra z*LAG=g|{Zx-`f9Q)%*J`@tS8gf=6}yU{Xc8pV~-d_l-%_CQRs)v*1OZU<)RXuX8ID z1r#b?S=sQ1clQr%r_hVg1EXnK3?kLo&Un>!8Ez+ecF_ckP`B#X2c%74K-Kkbl|EHT zK{M-l!khLqtt`IqXqG#4M%*>(f2IZq-iCkanmT~95wPRHPN=Efs8P}Qtb$Fu-mX2n z1B(_N*jzuOr*Z$TbG>*X{;n?2SxZl@(z)5|yv+69N zQ!O4ukyb~)yHQ|~z(xRrc6_fB7QONM#`XH5%5Y-P?;mSa(*Z*b8Ps{kms*Rx^p^;?O0sePn*k`;3KhF6xcdO4p6IH+O0y+1;o2 z-9f#dl2!H2ed-KWqtO z(~G02l~uiXZ0CSIIIOX}tG_?hC-gI|qm#8B+^`Vl6^?bPZ`CUBqh^=!M#R-cDcCi5 z=AbjwbNqY0EB?yiGsEy88m}X~xtnSsy2|QM&r9FSd-KHPsrW}ceEBiEbfOHyp{ED% za9`_R!ykaBd2+IXUcOg*oDC=1uJVJAanJTV3sZju3e@Gn`|4!xamB15U5`$FAD-Nqj_of^Q@o?N_g7Z??rJ|+?b6l0UAFq{)jnQk z{M79D_ZFuAh5wOQu?9rs90@k>vbFA8|Ygr>IIE1%cR$?e#p~zdOEhK z(Vh;|!;`^lRRfECd8PlhswlDUD_h?ryol*^`x>4pT+(_*V0Ii$C$huF8BU?3DPWp1Ar8@ibUQYMR9O zCziuy?-H6DO~(>_=^z{+a9q{Az5eWbnaMC?}@$;;Jrc{ny1d~EXgoIa5q97M6K#dn+G>8bvy#w8Lr`4_lj z&l`?k3|F|oVbLUrB>$?LK6laPALz)p z_q{iz_1?Z{x3{HR-VmzomHj}Ozp~e%jhWZ!6B%h$7yFj&eRY3Bt-r6U$N<}XaQ zC(;Zil+~*K9wUjm0vz|#rE+-3r)n3n6~pdt)0y%Y;(cnz#p30U1}8l+MLlTrl*Aye z+KN?+S)8;RWU-i%9)Y|*$YC+_^^(YHo?*p?6A~AwK5pWTH%Z38E5qS#pHzNU9>sH# z&(Jq`)Y<+d`w9XT6OzspcA(c})>i9m;u6!d2FpLrQofiUnNIOHa)KW(KaIx@dS)u1 zq0@C4BCYYTOwUL48?v5abi>4hy>j|%Pyb1=+0oq7KU%a7ZupUn-N@x#q4KALxHzw< zs(30asEmdx@!@rp>0~4DR|W}=zY%AX{My#dG`z6<%2X(;Q5P2!jZ%xg(xdAUT~)ks z-R@k*7AKK>+th+hkCCao78|@@-`lQO9M4ca9zRkY8Qk;aSJduq+Vk5kn`h5(Ob~9b z$a;7|9@^sh0WM6QpO)Md zMPpgNVey4dP1E2ilbsLbs^3VaJNtu!VPB-h*+)3-+|$c~(~uf3c(BB43g9ym!Z8g5|TQvu7!(F%a2Qm)Dv9BqQ^l!vRL=(0n7C~q2mk*&qOuByZJj-cu}41zu@Zbc;;qA^$xl}4 z=Kqto`&ujYv}_BOgNpd$T5TU`KZphM->r7_k1Dl?S!XaX!-l0E_2aEq{jE+|tR3H_ zv&B0xKS7jOnX;_xGuSclhm}t6$9GL!x8p&-|61!~C3b+bnk8V*Vx;;+zkemE0Iw)J zte>ov&xR9U{aR<|or{x*Nr;h*O$6O`M3Uh3-6ixJf8CD$=yF~e&QEnFmW~*$8eQ1Q z^Sf_&7|fWu?5gv3XXZxyMBY+XbgU!sPw{!N3VdJUHn_aMw9LdX4nZIMIvYhT%YRI@sTznu;)&-Ni4L=#Ha3TwE_-fp z0qV7AL*1xwylvFVT(@&$<+y39eJotH8X^SH2y7@>Q0rCfZFu~xr{S={ZZ#dQ|JAXp zWl70~|6=*vF;{kv?(n8rB%+Mh&mvKKEC<9NV#TWFzoM~1j_8Pi3*<*VSNxGUHpw%U zGdMHFde{iCdgLgN1?!c}CVx#F9IuX;h**Xg-uMW7GEosVpq{Cilx`xYv;v?u)q+fS zyi;5K(_L-iHS*oOIWc%Ior+{K#2d%2OI*~~Ycel^2%E(7BJ{+10SW};gnOA@Miv*ad=VtQ{wCXxj5F?{8*K?lctyZ&OM z$)ip68b(82pu7W{OSh6?K-LHA7Ok;Ol5US*@|I*L9`51w*>Jg@Ox|#X>%K6oX~S{7 zdgGrS&8pFF*_rT0dx`UGn^fKmad$Mu3nRGqM6ww!uL z__;NkV;$Hx?>&~(Hpy|gm#MMFxxPhb**y*Q@^r<^8uI~-TJ`gAFb>-yCidyh_K?1d zWBLZg25{`ic>Sssj7dvxE>RbZ?6TOZru|G-+I`P%hgQ>Hh2HhF%=mOvr(rkgo0yVR z^U;Yiw=(0{C(Yd866tHtT3&rRgUFW3RLa-k@xcT|61Y=WgOkvuO${6QRZkk@kC znAgO7rYnhfFRbbfdp7Q#KlS~j5agzwG-FYaMKT|r9tJlZzC2wS8`4`(jbXJL>;0Qa zH_@jLCo!Q?$T_)DouK4|zu72p`sq6%FKo@JvmWbTpKBelM|S9>#D6UDtsQ?x3w|6PPid)#jCx9 zr2KUw|H5J=u(nD3_bu@Xx&XFH7X6dy1bjkoTq@-Esg_{x;ykY|Tc9$ZW}3(iD~B}$ zw=?K^JU%RTy)wvtC@z_BF%FRq87Sy6*<1Zfb#|Fci`a`^7C-Db9SDaT zQYKtvk4A?*ovIbSFS(498%pi3twXGllP$wdAcliEAEVblW5O98F}ZR07{2nbtkM_G zq|j`F9@_6CpGg%t26|97L)Si5iw-x#wX6q( z$g|2GHaY3K63>S3mJf&Vhg#J=MyzPq-Q_IwQqV>|r=)L7votn8JDr*5TiE7R8q=b8Iqk%_E|hYr_)rz=A_on6E- z?fl^eAD%ULB6?({z{}tWRpZOLQu*MS&Ms%^4NszM=r9Kob+f?DM#^`eU;xbW{)@naX;2FuovmO*u?l<_z(|Z)(qGxAUjU2bGMDlLb{p&`rT7H-)w(hrK zjn*9xpIEiMGn(ey5R( zsmK+GBY&!U!jpv2nfEKJBkFralJ&<~_WUe0LQp!`_gE5knEX3txU)LP`xdGE(QDVL zc=T{;UYS;agcJ3|7J0A!!u1TDN?H$YKxM<17tMg5PM2<3a%|ChsyUkXG2FlqIJyoE zCX}a2zW=b#?KfF#7C)beByb;BE;~hsQocGZK$}5m>HQ<#j9UTUpep`9_mq7udgYiw z`{S0K3K7AInR;-AWyvoxk)QyUYE;N2@*(4a6~t%VwBZahpAC@kH<1Jwpsx zd!E6p26ZE(iX83my*)5VDGx$+iT``S5UVuC@#dwo!9IC~lc6WI2Ym$<3z?;RrEb~c zZF(RK2i3Ea?E2vB+}Jir@?!L*{|BY4;{Jd#=tq}%e{Y%gw=CIoRdg>{vMHkL2le95 z?bTUD8F9m5<Dd+G!{Qx_~FEZ_fCmxQ4LV`p#233Txk!`?j$UyY1kT zrzUy5R^C0Do54A=NuZoJN(!m9ko8dEq+j^f{U2&ehoul>*XDJyq-E`&G`7>mjT?uWI@*V=u97K5l!*I=)a@L2cA15#uvzC~61t(p`9^+%oAIi?4!SdbU2uzq`!1(wqo zZf$ukIX}$Jys+PQweKx^U6hGWId?`%T-mo}(y^KGCLtAgHuMecL1U|tm9wA`v87Jm zUp6GEH(3L6X?)P}k>xl^AGm;#M#HabG-^8_6hs;EcA7mHCLX081A3CVcRgFguXr58 z639!qqEI@T!*j=aDJ`oqQs5jWN}L^yQw*=g#*PN_>iCjaaBUeIa!1=8MM>U$~< zp_ivapJ=77yO(vn;e+Ra`BCpY$TVmJY=DEo)suJnr(=;Ni|HcKOR`XpLGipV4VzNmZl_nK+Bf3$}5 z9=fXkU)8tNd`{*LfM@yI-?vjl$abk^eeVC9wVC?n-2A>{Dm>)RAC#7ue$%&JbT(dF+;Zw!x6Aj@D^A8(wwSKPf&q6g9?VMg zt#y{?1M7e@TgR2TUsXH0$MNA+7}EOicY5A!)m@9F-KS%9`f(@zRzrw)O@5re$G6k@ z=YAb8YPxyH(wDv|dNEi9v0D~`*e?z}ye4|m4X2*^o#DI}Nw$6-n=PVt7F!pKS8hdw zh=(Kpr_vh}r%NCu%b5o&EhDc!2PS-{b`4}Y%-+o9dd-x$K2CYK zC2WpqlAMtT{8W-ewFERZ9Zq6T z2VI#k2pP3cy)LZm5utnEkrX|<^Ie*>(j(2?>M3S#5388ShEe=Ht@yb{cuE<;x0eOP z$8}g|cz0(wziG_6V zX_T(58gvk7(A`kz?_Io4Q9(5|s)Hwk#B&qDnQHy9!!cEhiVjzrk$*Q?&lf(eZ$nd^ zmnA{F%cQCVQmb#2lV6;U+c1D;!|eK<bfG z&+QX=+%L5fAhe+1bP>X?CYCuqmNf<057*^){0LAUDm&bb2(M>uhV+0F(VF@#wF3IR z!8<~>@jkCsR!O?^IuKc8P(LT3qFRC^ZLF8eIn6RFBPga4ReO8tT#8g$=#o`*` z^lZ={cf~=9!G7`3u+`(5q`xL!3;i*Dj$}D$kI9`6V={}AMao~NBRxZBQqkgS?5*J^ zm6@A39KUxksBkcRMLNrziF8}L{D1bfjJ?r!NiEe{fYf6!?$g6dh_(i zCSCQR$#g6yye=~Gfs521?ok+)%{p?b*XdBYO~hDi?osI(xyIqdd||rlhrYJ*Tb`j6O!rM zEi(dbHi$#|fMR@N>y{^4QkQKf|Hy31c@9 zrSL@YLaN%aRz$KrNj*aD)JhY@9WPAZQ&q+4?qpI{YUSt}cs>!@$h|dkSW1`{TYEQ}D;D@x&G4`!wbz5`x1n}aPj8WK_0I9VW_-bKd8KA#-aR9cII zimZ?o!+fN!hF405lCnHl6_LXlZoJ>=cQe3>=9ST4beI?xWb4)KeW+*=;=v55&?A$@ z7$IO`OH^1*|3RxozR-Q>@&e^5B45BMlSOwFpP9q$FXy8lJ+CWzIwe?Zt^r|9H_;gQVx3i}KplaJaYap4_v2Oxi)5!PO3WhYulNH|!o{EaWX@ zfWDhItkU|j_6B4*%iyg3WgS2xeZQ3`H}$V2*J8xe9Tc8b7Jquh^SodyFz@M&3e!n; zyEoUQ9b^JXpR2lyZzmB3)umU-yZZS^e~V7D%>K5_sQVD}nwcY;R_gNc$_)0vd|R)R zd*s#sv@?heiBwNrhqXw~(0zIuSOpL;!yTZe45kCOE{>tUwp;84y*l6(d2l!Ad3px+ z7nUTNdW9(mK6{M?kHz|BRZhnq>w}iXcMCbe>lAa7C!6RnJ$>tDU;c;2UBNEM!l^l# z?Cf9K5$?#dm%Y~)VysoxF3SOS!HyJ_f&0_%0KN%^gvYu@D}+A;ovGe>xRlr}*tkWDrcHg|+r0V&yMJC$eItj9BG;{7!2{wnep@-i>GU_qSRp>PX0v;j)rp z*2(TKjY7=FSpBfPez)A$u(puPvJ>LhUuoT)k)8aOkatI9d!LrPzO<{t!iZ%~rW3wi z^|Gj%;wi_btJ zh^AvQfs+#h8bq?LQ7UOj=ASm7_^4zm<|*?EMHJY!q735XDwgS549M05J4=>#ssqfL z9$xm8nm1KY{6lgBie%VvHs~4ISNNlSVn43iY8}=knqTyMh5MbyoY_cX!AS<>l*`0#7S0k6-nfSw(w= zkHsyzfA)}WD*EKQUlAa-8`Qa8^SV8-VMH2a((rxUvmYq`TQqy(q-IYy$C3FY0tTw# z*~glN)r+mTO;^J0x=&V^O75L||9-7{ybe|zdk5e69l8RqTMYxWBpwn>Xwzlo=dCnI zOa8llJz@$nMRFSK2ukQJdoe7_lwKqFJ{t2Ry-DNGRMjAhnw3_G=J)|=t zzlW!;gO*73g;`5tj6C&A+C`A!^4co)^yQN;n_gWv>Dyj-{-+|)4C2RQokCoA3gS;t zax}7?3IQqZ552-yx}tr;ql0R?dO=QMN6-gE%tbF^cx{+HmFQ4vJP3Ui#B3%SrLw@4 zARDI|e019#dYYn&tQB?UgQunkX+U10@5vfQKlgB*}=8e9r=h4VaQTJa7wS!dhc^d=I?YrBEk4cKAHD_e4{zC z`mmQ)$F)byq0g-f4NLfQ`)i+Aw4W27=uR=PJ}g$(jpA5+Sp2HH#HV^-F_d9VKe+Gi z+mX+WVRh#?Qn!uu^^q})KRnjdM|AYgoljlc-W{`NKhNwqf4``6V50i(ehx3Pb6CH< zs&_D+;!Qua*Wry0!zv6mc2QP7q`Gb-as#@aylMI7!Pjz@V#tMJ7n7k4zSdofQ}Gbg ze5(Y1Z}Wl0<;-SrYO-Z#WNp|;m-i%C-C{>!zHLzNVT)7p*y$l;IO8fp_)s5LjSFA z-m5)ER_a=DufBhi>`FP^KX-Q88S~$*lf3X)q`Zi%ydvv|RuUD!<%GotVvugTPFMP8 z-**;P#PvGzF6}KAr=BX}->SZSkNwB1Aj|)~v%sZ1Bn?B03^T=!?Ryo#BKpv!tS=IX z*R1w;w3@yTTcv&QkL!-IZ~0ivM$b=w>8+qU2DVjPQ%_s;%ro=ohpS27@+T%$#Fc5l zZM(jX=sTph#8qLK_gHGNp3*0HuEi77oo~PR+_)HZDcY;+;>^a$fiLx?A$+ko?b)5| z)|rM;Lv4w=a_o)ITVe|PrxUT7zN~nGy6dNRW!PctA*#2Xci+wlGyL+-|GXtqixFy{ z<^4nB40(68;HSk4^^v&Bz0RmQ{2f)Dzp(pNza^fqYgg5$$(gX4;Cj-h;BfMik?eScYn|_ooe}`vBQ2dkF7z zLh?x+j@+f3r+nh+9g9;M5A>0X{&?LY8(-h=`csm8uSj;1mpGr_(7)p32PKuClk9zJ z68$+z--C;LAJS)sBxPTdWX1RFT1WT$!BrhUKdDUalhk`A{rBpf=dF5n-^I#}Vfq!F z^HrVMDBjvgb=rJ==QEww-!2r-CI&bQaDK39b8vnwy;?I+Rley48_H*e+uVM8N zbrSQ@A4U9z?$#Ru^DG;HCXlfm>;Ml!7F2(4krlkuDqaSmJbvB9tr2+?u_r5O`bz&S zjRC(iui>Z`F%Sz<*#bjBd&2-++PagQx1zADoY8CQ6V_)b3+B1;U*ig9M@jw2#+~cs|hmH)^d`)*hGP%Gyx&B4*l1uh=kIoMe)=u;Zs6W0?_=G{H8=>D8ey>2>HoCWiS z>SMjE^cNPvnQSurvzX7lu9aT&E_+zD_V9SA8y^-9Q6CMdcO z-q8!A$!n6FFHGyGuh}VWtLvs1HBPBL`_{`sKphhQ)KRgNyg5ltU%j~ZX^ex?6|YUJ z9MQk{$474CT{%2y??<1^S0=yd&x6u8hb({V#i?_~;}$D`tbKTLSBD4Qr!j1^=xtFZ z5pOwJnpRiweLB<2uGKEA0-RWwT8z@&xxZm);g8Do>eU53H9j+oMcuM$RI>+Fb^qo1 zJEb>vOV6l1I(T`h{xtT{PI@fLmFsDUnN#kBPox@t^Tn$Xn}2wB!-^ivBXb*aQ^ki*)@ZvXA3#|a9%#J z`+|v}x&CeOUgTHpbyDPq$%@s|Trl(-EVCeI0Ye5WkC|C!cq%Ubr}YXy#cqY$5P^ai z<{9DGyHDfNMbB)=O^Z%?iEPMd%NSVE&}r~#!?&zD1&)cw1P60b`$0SfyD~On`F*&x z8!lcp{G;5(O**H(@Kbwq=Z@uF!{tmI4v!psr9Sp+H8PB94{6pn>Wp`~_H2-l;;3R) zivHNQ#YN~Nehsfx{XI0C>=SR@%!=ZRq>7EoJ&EOF_?VZB zsmgsh4cd0RT=U~cT$k4+3V3Coi>Zk7L)qWFHKPZ*hzkxkSauP4RU@9w4f+%=56_Jn zXRBNFkop%GDBY>2tG!Bm%pvlwlWP@$myN)c0eJ$yc%3D$4A+OnZLnu%R;`38F4vOz z7K8caay94!Id^`PJhy09Hvz22^|K$K0VILK@B^tWb6g_-W2W4W-1 zSj(Qrk9$f+%GH=iVN_4Y4VS^j=$D7)yqJIjVAwKT3$bQU0grDtaFw;#@Ms7O-}4Aug(^I(Gs=T zKkN7KY@g$^#@Ry0_xoX8Unds5-PxpK50Hmy%TMXYOU{y&g#8;s_^JJ--q_1obTNKO z7V?2v9eCi_*01Y6bidiX*R!*v@$0;{^B>#sc!$J4)Ug|hjw|?n-qkzr&*s%RRt$?h zA{H-WDK3b`o0l=sB7Afz^VR1Mg9TQ<;eln%s&kOLo%;K+c~#-5#6Kj zeqPszb!nFKVU_)4*>(J)?=DsrHdlx^*3D!QRFwWtM^8oHa80S)kOy0%^({jKukT-Z zk<}M%B;HM1icYEl(`ivhax53>XP^$~A~lFAAO;gJDhsnnVy~aZkY#^NmV=&|`(`X^@fVS3xGyM>t$iE-ZPS+Q$#@~rHzt$Sy~ zt~nTR)yKE$4EJm7ERhGa&*kdmZ{&IZoW zAvT5^Lmpr-jDwq_ld;_C(!x_8JcLY!JO>0KmKk?>-L8$tj^FQr!=9_UOTX8Lb&smdWk$E_ zg&|z@2~K6F#e&>+SqU&NA`t2xATP}^^dQ??|DD~kcc0Q+$+h4tgt45ibeM!*vqWlM z+(@=x#sO&y!#_5sn3os`7IW*2tsSnGJt-2uB-&PL=?&PtUg4l7Y4_(g~l_LQHgVIM~Mby^*x zcUVeO+YX_i(ts6B7s+$MxJ*a3$s0k7tI6S|t>B=i=84W0>m2KGP)+v1*dHu6_))eJ zt4-aY+&Y^Cw>LY9q+02QGiVV$B~%QY8a)NEtg3wMMl2PR9is1{=~yu=AT<{^SayKA zMmcEA(8I9z=S3%DE>c4_5&RRA)%tkp1g@vo$nF(ZJi1Dq^*7UZQ$+_`&(>mnsk@?! z;lOkX5o?}0U)UZj(h%V)kmYl6NsIlToK~VGFpi6d=nD3sB!^-;}Q##!Lt)*?m!(@e^RN)KlZNa^LjG zc;zeEYglMJW+dH{x<|dg2DkXgS3BUuTW2)}f7~vq=w@#|kdvXM_?NdGcghg_Sl;d;VeUbWd7%~|< z_Z%FDp#-bk7LAu4fz=<56TPOfgRFG7kh#$Fk~GFL;{I^yJuXXR$7M9)+R%qPHip3< z;tAJhe5+)>oG!b^Rd5I5g=Oi`0kj{~xM-c{!d{1an7TgMDXbto5qwr=LOcPoaO%UR z%b3^!JAYUmf0(p@&KnN3;oT9xBZ*FG_1mX}L_wOVLy@l?#(CXj_zc6u zwqmWqk+W9qGu%>Ya$tr(v&g4&`&Ul~ypd!%Je_r`mL7^rog2*URHujlihHVBQmX^c zCuWKZ`DcBHg~fZv8Hx!*XB=!xA5W^usM^o|V$q+x$aTz`;`DD{(1SPRBM=!DOmo2gL-HM(+KcC=`u6OuqkrOnnD@6y+D~PTiiK&_SvcX;KwXkRsheM?pbAKtT~jM5!VmSWpxY zsfrZoAiYVG4kBH859!JFY5UH}{C)4azr>L2&d$z!-!12!doH<^#9Q~_-N+H-)Gc=X zl2^$4Y;%ywXdtFQ))^~;j3!wbC+orX0mQJ`ZI_9i$eB8&VZ*7S$Z8;`z}wog%=0hd zjLA#4HPP9-O(qfbD~R`maPF**5_LU`Yd~!kW|H>g0%G2bS&2`OWk4*-)-0l?4Y_m@ z`1!a0uW!DJ>q2(Ke@ZKyx4>)5UPLl2$&{xy8vOyan7A5Hv&@IeX6L%Q5a@2N3&cs3${anXT4EJp*1hVix3jGh@!cvu%Ax zs$cx4N5N;>eI~T^j8R!}Wi<3O_C0Y?PMaYE<4K%p9G{T52(_}qg&<~tmskc+Gb7jS`kqt-pl?a zGNw7HgDi691+=H^Fsg~GY|k~a`(zo(@)L5B54&<$TcnN@c~E^|w>iO@wazi{6gGlx z$I-2E7Oik>qPH#aTH4eXaCTMknaI_rRpsg>(#N~XtkTvqWt2>w7rF6#Fs818Yr**z zL`5a|LTV=yL1M=pcPW3zjylE%%!+x1h!@%Do86;J&&!C>p1VgqflR!@fjhw-eC|_P zY@5eM<|{drjA9vI=HtD%w%C_oDGKx>EG(RDNKOF!OcB z6Zf$PIc3dO`QvQ$zp%G>w$$5ri1VVVwLOvHAzneWnh#s&$~n20U2*I)MFt5jK|i8}&jNrCfv``U{?db8oKU49FQJh`IAHn zALF_7G_)l)kCL$oXET#^$}S0BD=G>xLm(1J_BuU~tyQ=gG4HRi_rzd0!+|&qtGZ;Y zGy2_+_r8uJ+iX*E;kfIGw6Sl4(VMLbc?GtUolcym%V|M-VZk^RjaQDbEAMB#cvn7w z)x^w;wG*y?cK0!xw%KshW@pAjg=4NHt{mPS>Vl`j>M`eHM-gPwv1K+ROU z_m%Sx*tN`FCZdPDv&4Dt;H(eBwln)$jQh0%?@2WaBCY{Ek9??Y@Zqch5UXHs* zo)tZCA*>K%W3m>R+tLcMXM$a0I@Sk0-wAvcD#EfpX)8dI2Vl>4WxxBu;>d*20Q)cK zi;8evl5qve|NMWQI@AKS8P2w+W(@7cyU|`V?tXv`)=kM9q%R`Uzz6$mXh-d1Q^AS7 zvSghTTP7Qn(i(5@d_AN2XhGJlYwbhc?vaDbX_4#Ie}d zLmS@>U&Je@_Cby!nNSOg3$Q(m+leTVvjL72N4yWPrf9Y9!P?nMm7I+77b3ttSbbDe zJr4WDOrH@2yV%%`PyPzyQO>C0UgW>I2btlq+mL$oaeRBdrFtJo#7JK;kGoPpX|z@tG<GNC}-!a;>d70z~`~geAshC72$cEtz08S*QDgbd8b_wy{oV3V(e9pAt ztM~rT?l4;?H-h~>tb(!ok!()JkB?zRbsz`q(X|zP$oC~5kWn?&>B(!iImWEXFs~&O z)%K9o8)S`+Iz=|`lYWX{)WUJYuhzucW~RmofPITsDrW&RYwv&^VRvt{e}yO-drufS z{ih2;6oRT{RAl1x1@@e<^MG23?8CH`zF2pn)n)|G{N7f0WSr0Jo7p|R6sNq=GqH}! zS&po&6X9m3I45e$h{EsTUj2n@PyJx>D#^03S(mJnaaNN(WsN?7QV{pR4 z0%U4G!8=nynA3@NZXno*^rEE>G_DPu)@JPKkR<{8Q9y`$mnKbMcOl$*5Tdx zzO1%vhX-3(%%NF~_n;o(CY;@0_)P44;Z#CmD6I66tsKPXXMAjTr7a_A#QF`HHyiO;Rv|j!G+8pAn2F!S^<=HUjz7umq<#WD19LK4wTkc0 z9dAbmX?QMi0lgfx+a7tSjpc)I0ci8N``A|Bwraz+ljfv85o>&p%l>ZX>0U0`n* z>nUU}uy$;-49Fkh6d>vZcoDPM5j#~^OW+-w;m)vb!I=`Q=Q1W_jg1`uv?A;}=9+Ng z*<|C>I+L|eAJ0ApYCPM@M0S?U=qM4dvU!tKFR>YJjGxJ-XKj*k6+MDIAAtQB?5iRc zXwMg>&N$I+s@hP=^dw$kYqi?ih{UW|C$>2cHkXalBX}-0o0*=HtZVWX$PD5BWPOnK zoA1X7A)NfnZavPPqS6LGJ3ANb$w{mc**uW?h;GQcZi&y$XoUSH>{VpmL}r(*X4$HE zebZ{ci0enSKi2YSr#U^F{cluswmW(lF)(9gw+#72MA#ThQID8i6gKlF1AC4d;dcK% zu@f@a_#i9Yu1=6a!$^-j17?f7PgHWS=lQV%)K+?BtjAt>cA2vSmEFBWirE)NZ0aVy zGa@DnmK`k25b4`kosZ#_p#43SYt5mDJ=T za`YI-qy9H7FDI%p8sMzA*?7?YuEhEMS0^COL$r?^3|0ro^&qBps5sUjuaI*XST*NN z9Cj~L6`VL4)d;EG$?6g_eok77;#1P*QuA;hj=-s!w!+m7yoQt2I7fzfm)+mbyTxl^ zbB(DY$-0%T!kUa@yRpN0d|RJ`ngQ$#dHjE`KC=koo5Y65eX%1AR&I#)Fv7EAdU920 zkBQANucH=;t@_NaBvyx6d$wzbEwT294U?tC3N(A2h|jR&+^!Gu*^JR&z%!XQQlHG$ z_v79pkISAgL3E6B5A6OO^6(hF+enSwJ4@@ux;m>9UH_NKk_$&380`yHTv$W3`F&*e z@!v#KSnnnN-VIjyHCXev@I^eoFRU2j6kBzg>T1-NvHSO#EfEjnR8jtCcT=;XMimLM zn0G)+K_AEJ5LYUz4$PQrRsk^`ve2lTMCQ_6tlBg1znl+Ayp^gU`>}$rVvi9yBqypI zc6|k0A=b;;r%w;g${ll4t_t=pvQM0O08t3L(}O*_eAm*jD|UBQCHzbd1(|n5lxR1q z`oMGlU~nXc@1XI9Laj%4K0TCj?0YlNLI-fM^8k?57kP^W?>J9eqc!iwTK z{Dqjta^%DF5jD?4G)+}5&Xlt2U{qf@SZtB0Zpr+G_Q}S$X_3$1xLbf?u)F9R#6Hw* z`J%Yrhl~-j$A86+qJE3r2g@U{zl@fN9dNANF4wY}5l_jL0s1+9X?pnnz@Q!ZT-=4!OEy#t~;@He=5<=iZ@q zJ2P3kmxl9%iD{cSD;}RU`5|2HJEcTMoY$OBBzU0^TzNNtjOCw%${UVJcjyx>}jOW;i@T* z^CpXx87{dUwl0O8Kaf8|^q6%H_8PNZO6<`p{_L#p*oavYj>i5vK9f3W%ouI`1$#!w zL0H`5_{_xfY14T{$auHa-stgs#Dv+GWzPj;M<*j}#@MtQR1hOmoSn3c<%slf4i>X*#+k%N z?dj{}TX0?0#l3A?96@(OmvPHRWhR92z(88Iw&ZPLba7f`#Knlrp^RD+;5MMMQ|5&M)A-`T3vzU#!J0Sb9Ou__F!iWYUm{&dwknl{%R=&xO8{ zQ^cq|#ySTPA+oTk#KzeY?3!j*7(2i?CD~SXX;+N**h;6(aaX7T!;FplDsS9`{Xz4mG6X~XUA zlyk7_?1E%IYfqtKkNqX=KJq5)Ix2hVsWQ)K;UV@U>+e+hC1TGyy}i$L{KO6vsswVM zaP5^o!or)`#G<10tX{9>cwB^W+#M z|EF_CdzFuKPQg8(WhH~pzW*6G8?s+*1}tllMC+-G%4#>6g|^B&r>$_kvzA0{2HtPR zZ?>L=J&BY^E8}##qRG8(_b9V_n|Te@GRO_LYZK|%H>|ze8YE;)+I^=~ey7c0zc8&P z)poAo`jd&lxy-bZL_?^3N{oeQ*#`J>GEZ5RWrdT|k64u^%Eb!$+TwbHJ%5Rj%vwY; zoPc0YP9|o?y2h{g&VCnup9`Np6aIWE_^%(MTZ^4vqw&)OczMpQ{0;BI>DfFEyM9=k zwwXxFfpf4QYdwxn{^}Y$hZ<&Nq!PK{%4D|>&y+_XwzmuC$xfPEcyL{lqsysFL@I4| zxBYJ_CEGO__F_{pf*op{1pO2K&Dm7{si*S#*vfXS-PrR;sWndiJFy{RMXYn!)5aM~ z5F_Omy%yO7+%3EdtjF6mc`^*R%I!Wa;x62Y%@&6V8=_D|#O(NlQ5hpZuEGB* zeykmHrX*{E?22Hw1E;;Pm!5W|E$q?%!ybs_({q`?kDtK$Wdv={=jEy=gPUpzjLK=R zi2yJnWsE?N!n!usE!8K8FcZmT{>_|$6aGr#xs~y1+RK)BfA-fB4|xUFxGv7m1^>zT z%GL^`;wUq9Ml8(ri7hdrrNtmS#OBhoXOfW^6{!BJZ;?Ah4lrlkkX?`r3#Va~vx-MV z+MbBQ=zx(RxfzW8Sf`_s2~jGZGpqGBhGnzZi9pyh)QAMwQx|x@h@aVv04fW!W^OZJ zs5MUA7h(qN!?PL4HYw|4lKo`C@0WUWg)7k%qRNwMq7TP_>DuXjR8V zlO0wHcZyz-3|jg=S~DUHHpEgQJ z_9QbgqBQLFV3b8fgIqY`iB$aHZfK3TW++%%v(Vu-4_$BUP8)^X?=^UQ)nI!(l-Wp;1t9>qY?YOg?OPo{0|ug>=CPnt7Ln4&Ws}7-UfeV6^nTm)g_qG(q9n) zVif%hu7DkN*}d(Ig1EQX=|$#jXS_FA(2Z~VWvTLJFyL-hD7q& zW5s@CvOC!a!)Tb=_tYUJBgeQz3}edSdl9H-R2HA4j+IBxZ!0W;|l!^tmTKp)iNY?H+ zua~QZyN#S`YTWSOjQp8R5ldiZNLD8~FudM2{$ocPti@7~jQ5Oonl(^baq{+w=yK{L zuLS2(F^(c;%ui3Q2U(-EWXv;dt{1T{;347u**?4wu39I;=A7W?tw4LNp(0;O3LjT4)M4Ln| z3Hvp2aWuv*^a|AOp^YHo$QmitrC7tTE0N?0P~ptR*I0jH*2V|B!x)=#<`Wf~?7lIZ zMH0q6V;2kA!c=^>dB)6IInje&o?pDL%u0!V+S=H*o+^0j_D$rGlc7uOB@uz6kWYHKe3Mhuyj zi5*7N>u3JL2#*iuNA%zJbTJ;CH49EjVf4V5gSxD&ywElf)!^S5$B?zc-YI)#0kL$l zrifKBbNWx+$<|l2C(IL-vUQ%g>yBd`Gx}wP)5g8+z5?zODjo7aR%eM((K6Y+3-|E} z*w^#*OSL#+=s0&(3&~xivWyL{RDXSbwO4$gdKvw~DL69FJX> zM1RNyC-;}$hOc4wPgA^x>UYE{Xq$<-Fpr{-CYy;>XEKb)2O&PpY9Cd(yWz`56=?gO z#H*>z$a*-hFByKEjmTV^UbYop`(I}eS#w-b_3-b12 zNUy_plM_PZgZ{M>jzBD$%uHJ+<$c5vU!oIz5j0%Z;~0A#haAToM;tpGzvIX}1ELVN zrp-jeDRc1n5p~Gfs4Y${t~QQG{9>!KQ1^zqGoKY#CaFt10O!d`-c*O>^kXt+sCz>l zTTaV-2fv{rZWnkHyGlfag5H2?ygc7l@X7Sb^c7Tl?})2E0LNe_{b{cd&kL-;&qHji;tm$Q7MbS60uFJns*`9GJb^eK%GA<{+zz0#kY^+yW+;qIU5zeI} z-h(PU@8OKeoFr$d5$-*sp%Cspt9q=yu#2WmA#s4D5Fvo@1*q+EX;iAmmvy`ylRX_fqrN{M^J_iQ<#7xEeNe z67pDTmP|(GxBym^{W#><(8ICA#b!C!N>Pt-RAwIBr`$bc6B4(!*#qRs(H5|xMvgA6 z4^9nxh5QM2>}<#JRwDmg2)q6x?6$3ZMgI64_>lF*S^9 zP4S(W8!^jaE=blN@6u&lBi8+yZ*$t=QXF?#@%Kge7x{d=YRsCcSpE~vU@G!@J7eC5 z`@?!5?J-d%KP)GwnzFh@k57IgbrgAL>>dxh4~F^|d{?sbn7wm$GWE#z!$wkN+}183 zGn_1At{7_4+LPpou93@VSDx7$MCKqX%ZvsMT;Dsma>Uh{5!&6{|J6MCOkQJ7%Cq&; zsLIFOjdzKjfp{=$ZLH`}`O3o8B2rCXLZqI&9AewH)*I`7yzA7AVa1T>0J|D!QCTPA zZlKM*4bQ#}cagsNOCTV2uh0s-<|I4_y_0Rx?JSj9r9A0h~QPDRESAh8sIeLs% znE9~3oM-ZGzCpjLhMD4*{VBLhzBcqR+ z2V{AZ7s$QEUO0Ys)=%k2sUJZm2rC%OgBh=JEs-H>_jDY@5;b1z?qYImI8}%BQ+t|@&Aw#pLq->SeyChP4Pv7E>?|PT zjrjvHm;d}K>k^#I$k@;B8zyE!y#ww-1Ft0)i;RL~+;{GUJNS${u*R1F@gd*qDDLxp zSgcg!pJcMrW070g33jn6?uU-oP`R1@*5+H-Gn1*aYU|E2j^KMy4Vjz*cAMJjkrCW4 z8v$S)>o(3>!?UPENnQpsDOUQ4*%RTh`33aME#W7rGxjFDCNt1xI5Q%V%)O}@Vl&gc;8IiH@jIHZo46 znv7mfxhI>!_TR++d&0lGfUCrut7>s%M!j*WH?y`xhCRCk$c!h8jhH&~QbrBbKc$K} z--$>8y#Q6CiL8?OO%_JYVo%i-ew)6IT40q^Rh+T7V!g3?>*3Q- z1C_OZ`Z)*g5BaoY@Y*x;>{_xNpK;EN-R1iVK1DNJw`8p7$JiIUixJz6*t6HM+RNgu z_eI<=9yx7qoOzAn=aDC9&uper46ABX>}!P;P#;&-!rnRz3&DQSE!gw-u%|hDn#dl} zAhkF)#sm@BzlY}e&EUpscv37VbX3s=Q?5RWa!>q^K z-AxXxl1lj84R9`u;~L?pK6ozHMyM{&IxzEDc9#-4BRhrYBxjuxk+6G(sJ}{2a~a1a ztH|yn_7q!AYHU-}ix?geYcjh}%1fwSPwAbrmt}2m6-lbIRuzalA-LS9Z2+W6nV3#br-iT^Du{YS4L+#fW zU}M|j-lXF-?B*c4bDq(Fs@@Hb{gw&AFlZg9Nk1VY)=zz)UwB;>t}qcITWy=uNqK*nFtkY{#B$NDp8~ZuI`V&YU{PzY*Ca zE0tKO3+Kt%7n%6%tY)%m#5wEi#Nn)Y)*=EpSLQR1@zky(hnO_gAxN7Rs+2i=!Jcm}&cC&L1K4J)!1 zdyx4=Ha-)15uEXE@4BTpcj97X15@GeMDcpwk2BnX&rXX+#ai~gIPN&(xa7!k7!E;@ge2h!;c20z&`x+xsE&_fs~3=nz?U4{0-tHK*Xf8k}k=4qjx&`@Y9G{$o>1iz3bRL5^$6guOtZwMoV zF~WG^BjFw417WK0o$$RdO&Bc<72Xp*#p8XUAKtl&P(mn!*F_zdk*RNhw&|aazo1gO z2K9rVk-=}prpINXdE0G^kxp*e-?o_B`_Kv@f z`#lgUmCfT7<0ax{;$`C{<8u6_wZr<(8fT5N23Rev@|J3a%*W<+bF(?hY-lE$su?tn z8$TKE8?PE|jTenhMi=8HJYF_>8r_YihQm0lf1`KPE9riayB=tlwTGHpudBbTzoSpo zXXw-P@%kvemtIp>^nC4x_E<~Oo9KP?5A{|0W4*lbywT72%=pk4ZOk|J7<-Lf#x=ud zHZ}*F8_a-N*6M__``dEI--LCn3XXIYVUtipTqx#=ekn<+C{>mu>9V+6{7sxLP8C;* z7ez~KCC!rpQcroOoTzkEK2d&BmMM#rxynrCV`ZSyOX;DsQyM8Xlw{?Oyh)xXPm=q{ z&E+O?9l4hLygWqyTHYvMk|VOHMCEMxZ#<*BoFSi=7E4p4sW|p_sYq%de;}`wAIhba z#>(@`lZv2R#j(DSUzRJ#h0;ms4{5EmQQ9S)lPsyG{F3~hJQ43R5f)!R@a0{1#0KJEJ%I)|YK5GbeWy^RA z?8;uKWlzU_CWG}La=7)_kDp^lcZyeyJL8Y7W7Z;Tgw@unVtFjfw9KG+*F1%*`lZ?1 ztZZf)zZe5>|4JL8QKa9{ci}Gf)RXkX+E}f;wlmf@ro^^K-;LIa=0$c#7DOgRhDN$X zYDJup+u@Djk>P6L`=O1YFG5{IiJ{ZM1;I~(eS>v^cLHApx(Dh9)WAPQzZ890^h43n zqN;&E0~>?;Lp#EIBiYePT5Y|oQOWFJ&4{N81>!!rw|c^9xwg6gcF%BYE}u(vzM_Vd z2gIUVIyjA)} zd_#EFQ7zuq+HQVkPBhn=iZ#&MYn6dT8x?OKH>}^R+SVd7)tq4j^!M~Kx>J8rAEyh( zR%3=a&YBb-=6F)LD2x&>i!Q9JXQUQVU8#oDOzJ6(llDld@+di1{#4PGf$9!5rdDv) zb5?TZtE<%))gwwBWrloC5~UjA0AUki#8L66^}W@?ikTP9E#_pilbLLuGd{;P59lkg z0~CFS_P$m}b74?}$Jd8D1TPOt!_q;G%SRfn}{uQnY`|#68SckM? zufc}R7PbjR!i(Zh;ytk}UimI|#0=>ZX@JyM8ioClExn9gS3-G1nWOxH$Ir?rV?lz#0D{&ywGl+sUQm9BGMEU)mwI6R!(ng>u3^SoRP+`G9!kc!6~k z>-ZC^x7E(7gLV9u`Gwisj2SzPPmPv_YTVRM>3`~5^xyPF`W*dB{abwruI?gOp0WC8 z`fU9deY1X2&(sy8tkDGatC5jx~Yc3(W=pjc&BG$vtw6cy#V8F)ms=p z8&8{+tjX~@!fCOOyj{srOS$q~9o)6tOI`WS-p*vF&so}8!`a9=$yv$u!1c4+aHn_@ zJi1%)l=8&fd)yzmySP7bZ+A!BXzt+duz+pI0t5^JpWyrr4z&7S6Ccn^*gb~GoGJk zrNz?_q~66o+GicM9$30nU}aljtI)bt1O zZ;VpLFM2ioS1nolA=WmQ6w8b5i4Koej)o$KBcDg=Mg9p731^2sgcaN#d@;Bw;0}CJ zRJQ19;nKpMh4}?v7BnlUSWvSdrQksRi2T0!OcMO-?xc~4^O+K8qKBGd3RvClS@{<2b=;?jk)lc1}3{V@m&U#k( zze{SG`a$|jCF+&@rG${tC~akmocwj-w1gf0bpLwa8sBbT9p7Qk`>sXG9`R&cHFs+b zV%?(^qt4iU&1>GXK5`rv7K-#i2ZbIEw{=c0txb*QhF6A+;JM%np&8++(d$}yvv2%Y zVWsqjazWkWeC(X=%u$=FBa~(GBWbWy2DZ^5`;>}mTjwXPt?qw3JG~=(mwXp}lYB|O zuf5wmKe~Imf@)7?sZ>vt1aMcZCRW7Ef^TnZ&9OG(TK|C9BgL9#UN@dFy6SIfQ)0)X z)uVGGEg~f&6(a9Of{`WBVX>at>-uOK>%HRb?_29T?c3lR?R(Kz-B;e%$T!Tl(zgwso=la)@9GBg8%MAA_a8rDx?ea((5n(n?*gmU51CE_H5ku6O?E z9O%q&9#n^@g1Sg)rAV-lI;aCBmGX+HoRUA4tH^7mWa(Y;iqH%Ge-OOMtoUuKm9^h& zYwk447}Mdo=4h$fH&~A~qLU(WWI?!o_*7_0sB|gjsVcEht1zGv;<(JA|k>}1EpIbinRL+E)cXFoX zyqQy!y*zt-cHQhFS@W_+WLT&W{=>Xp3pAwmBf_9F$tD0?s?Pwook$HtLvoe z2UiK#8_urkW_gVGb-bSOZ}i#lso*=oW5L^@O%bnl#5fSgm5?q=rnp5oA0KMo(P~8d zg=zv_jY zp`*A>jANC~m(EKC@Q!;C_tlq5Nv)(6Sgo>>rx<{Hy){b;2ij#Pop zU3XMOPO?cjE?mIlFJU=i(b~chWEq#@FUPlAiPl6j!CVd>dQIP{|Dmtd7r;~gjIS2@ z?^-C963dRv4>t&13#=&mp>R(@<$|;M2l6lF8~N!4B?|QXMfuUZ%6YAFhv$5s{ax0~ z$61*-GaqGc$()n9HS^!h?U|ouPS4zv`EBNdM|&S-XD-OPoBdku&HNI9FT)$PS@Dwc zDQ7wF;Dpl2vr_&@DNHVt)YE^_Gsyj$D-pi#fNPOwlz&6gk<^znd?oLcjFhZUs!ge( zB|pk&lXg9&PRf?#Cduz7HBJ1*U&^=IbHUYBO_dhMml|`mt+BcA)@8Ka+I{^Gb87rU zmw@hOg4!WQ8baX)Qi`(Z9$qCZr~u^7rvy_qFoP@diBY zJs;ybJ6zM99_Lu~oKix0OFk~OleUOHag5*;cEayZM!k3fdRCd4zl3aMMf|yVj#6i-tW0W?#LV?drEdVYhu>ZSwhzJ#}^*|{doH0%*?i# zIgjQ(y8iIWgPi-V@9(+y^1aaAt#`-Yb>7`|r_$ZkcNg9rcX#pK3wPVzYkmLtgA0%P zX7$YNU$`f{*%%^ja}MyGP3)R-D|KV)hUC5p!#sbfZDm#3ApRg-QR=(D@Q+MsQsQCh ziskN=`=Z>RWha!`QtJB>zomCgTc27xt!Da#^gZbt()5(QNnw8<&m-l1VXm2@1!G@n z9wTNBcT|+NDp6-Ucii=y^JV#lW2V_ddnVE=ShDCq!GwY_g=*kf@YnF7=sxY5A;k|m z?g(FCJ-Vb9rRGwm*g>2v+y-;t31N>gPV9-buvER_8t%RCua;yb4@upeHYa^&dbRZA zv^gm&la?gR_kHV`>iSakD-A$QZ7y$-rzs=Ve$FngyRJ;v)2;%wnbJY(BDmvQjqkKw z(H@bv!a1P}A%A#kxNPKRIuE#s)+G0T~5Q$y_RGi#gu&3)zzR>%s( zs|w@AEa?NKwDS*FW6yl=7T+lUpZlv)%&oMouY5blw)cOui~1!4nZC!$TFe?-be zI)y(Doe$Ouz8$z!G^*%M;nRg{3hEa8oc|~`%ie0cXk z>cj329S=Ww(Dp&XgCX~SyZ6++(RW|I^Xu*Qw?Dsi>gL{?X}7xHx_@i|C@r1g~6hqf~~^;Mh3?gYdiI^ z$X%Z>^Ni`nDt(c*5V^~@k*nd8;X#qtqGqgt@xWRmyeiAiUhWKUYu|03>3h%jgLkFp z2lo`$80Qi7b+tV5>5Xbj=Q-yr*V}H(J<78ikM}&g+!tLJoj>5L#`@6OX_W#iAOV%88?eeB2|po5>x*nQ3QkKC$9bS(RpKG6y?UrNtakh(w3qJ5 zU#bbN7H*g42hT~*hn|1kP2B@r1D(s%Cy>vdQp%}o)w#~)F3mj_>+^U2iwUO_o=!|m zT%FJ=;fntqe-u&WNw4TtJ+ix&tFv>Y`Vg_+RmH0gQ!~}}&JUfVoRytZ)WgaRd5iR^ zSXThM&?;w*!hU#cxZ#nPA`-4{^|9VXJ~JD6&27sWuMHgaJ3M;DGx4di%@@rLMlYj= zQPFtaIA*+NhRwNHrxSp&j*FL$53stK4UI&!uO!AgMIS~^L~$9{>Oh%G|i zxjLE}?H(Bv{wTC7m>e7$*iv+@FjC+zsFgoBZ(D9^?v$MBIic)b*&k$A&pwdVA?w&< z&*KW2Egrr4u=WG_zIgAiJJW7QZaup7`>lGn?%(v?>UXR2t&2B*y7~9bmbd!f{_*Y) z4~9N|CGSySa_n2{q1a39==#>x!I>%d6tBhqHWhP<*(?5zxK_RIJ(HA_KB?q`(r=ZW zQTBS7bEQ8hHM3;HlB-JwOYJD5map-|sESuAzEJU_3jNEzR?>fnc8KS! zZ+YVAlyhmnWqev9n9(!+R?5A^DZV?d50xR}&A4c7HVTl%Z$e(L=_PTcni};CP5)b8 zt^cI=({E`#wdJu3(F>97;bS33=$qhpWH>8Ad&93s+iGQvBr7+*Ovn~5OLJsPPF4Pt zTgm@OFH4ui$zm_@V`RGHrPt+FN>B9z=a;VD?i=pfo;IFpo{jEw_c+%LXGg^HuVc*w zmD|c4#Z;=R?bN>N+v;p&6sOgz>Unja`nx(u9iYnUcS?QbiaY?ve+!XdX-S3OA0j=L z#>fS72W6JBQTZMIaD#joe`zgl5?aB#x`8ww6J8R-;!3GK{9z|$rE)`&)dV$1IRRYr zRi!#;$2a8d$fg_0URean6Ol>+)!d8c-T_**MZKb)QKzdl)YXbx86{tmo|U$Vt;KV~ z5W&FyXo$)@C&v5+WdAg34yA#!_d(V_7&X~Uti>nd3$1kP3o~F$1Y%pp@ZynVJPEtk z$9Nk!a5>{|AiBx=I<1vxn-SQ_Zk0v7p&#l1^Myv@Y2e4RflP@%v3k1%hkiG+c^dVtHrKb?l0Zz-E-Z;-Kp+ru1sfR=QpZT zT@DnaBch#8m7_{|b+q~`aKLv9>K@4eavfE=hj?VR*iEbT;B&vhPL?pv=#%w&dKUcq0IjliF*Z3?J$5=eEb55< z0vtOxyeQm1Ts`aw7lrPG{tB%QtpJ+6BlJgTL1;o~M5tq^T+!0(D>=%3zYxHzrZeU=bW*}B{ujoOM9C!k2wOODgzIy|~ zqQgZki>4#@zEH5EU|qrEg1&{<3Re`}4O9;$ginWmh%}A<96cUA8=Vj>h)jzNiVTZ< z9N87=5v>+`607#K;kJsbt?@pN?T!nmSj|G!@b&l|YdKKSMb-(cD>64pXd(V8<;rK2 z@oI*1mh+hNn)9afu=9X3*|p#GmAj3ntk>x~@B6}EBVl>M`h)=qzJ%@metw@n;FJAj z{IB~T`4=VBPW&qITB4j3Ox%??DDieeQbIX@OWzRh6wg+7vU{GZrK=%U#W~lL?yuab zo-v-UJfC=;@hk!gzp6L}bIH2cK>QIEvw$NVi1AlKA#lLo#e?D*@rd}fSWo;1QHh1R zRkGtE>J}4$n=C-Im5R(E?iebZ5uO&m6|ab?Qh(_epgASw335p8tb7em98yHprzWe4 zdLA}%kkUn|rnnRtnL@f!SLuhk&b#!ec%1{ayGzTO24Ripx=ty9wS(S=8q*qQ*j9 zroG^k%|_LwMO=*Uu|Bt6w$d!tRQ8*{!jo?{cbi**^lvwpm>;9Y(!h+MqBX^6XCxRm z;EVpzkLyQ(E?asTqn1(K@BzDC1C084y-52_8=|$<>T6GF4YY>%ss(K4UTkUX)mS{b zGTI|rDOwU=Pedz38$@eImFSJgsz~d|Hefz~hPs7{f?I==QGE#n9%F?r47?DyS@d2} zQqhURFAM7z9xWJ(?E6IiyZPty%H_?%u#Q zjZm)<0!;!{P`^nCJQ;W^kQMkacq-UFR5RQn(l}Zw7K!cAhUlWP)KJY7_;!z33bmv* z=GW#!vz>Lt+7-XxC=x`;3q0!|Ws&-hv%G7zE9m;%-O}UpW_xpe*ZjXGyqDN5sc!O) zuv|kiHgQ5S`*} z;W}1gk&q*(VzL+$E(^Pb6{xwkMYZD=_ERG;w05FC)D$RlFU0jH;%&f@ZZ2#T8ltXP zR{BtSB(=eMIwn7%^o4yM0(<|J@);@{AEMIIA1iMua@XUC`|^}RB~!Vm{EGVGS-HO~ z$tzJo%7;~6Elv^N5#L0e#VOu{FJCVFfXd2RVLR$9*+O~oS+PALjn`l!TZ@gv(&8OF zW0Eik-oG5YzXQm^#o{{fbTFtmee@l8=U2f+a5@e^1HMlDlr;qY`4U#%4D)mIQ}YA! zBXc~y_e9R6V-Ag?c5@yx6B_q7wLV_$kCxqeG2CkApu2Uk_Fd z-U`eK^nndLRWz(9x#&DRb-%)@g^vqj!W^2K=RL9DmVytNB5&f+b zK2Q8P>8Iq$DScAY)7GS=rPoe(rr%CGlXf*NJIzS*q?bs4G5wqLi|Il}FnwG4u=HB# zIcZ;|`O`j4y$U4he*Hk zurb2%7oi2V2%Up-z+JfRFdcQk8ORa3iF?J`(j4iY_zMrP?kd6(UP2XqFSs1+ek}{uNn`M0uH#&L;T|kTMdq>j zgW1b`8aaQe>4kN$jGM+rV;tf{hjC0_udmR5)MugUwh}*Y0fx95b-K~0#17G4!HTSh zH7V-%wO!gY?HMg6wk|d*_GIjK^k8&LbaC{1RN4kbTOpe{5&0mJ5Lp}U8ZHQZ9jXIQ zy)5`)utV^vU}<>c+ku0DDS^bm&qa-kHWdnmZ3`CUhx3NynYl}H8|I$NS)Q{f=kuIS zIli1j*{@}1WlhOavW7p-&-^{}i_FQHJ2UG&{^#+UtX0`lb6VwA%&U|i%O72^vEXh& z?ZOp>`G*?l9IGjj{I*nzzhaKnSXXsdEzO?|0%~QbpxE zHRi13c6#=C-t$)UZS~dlFY{MVxR(%2Y?M4UWk>4Kw7u!eGp3YiTXKKN+>#GV-Y+@9XA|d}>U7i<>d32rJm)CU^&zVNslpJz#}*N33t45|$LNho2{c8F>YKlB(bz^u-!j@5pmB7M2PP5GD7< z`e_Jm#7)_+lvNUyfc&p~9JSq5!0f&QezyWE@L&11d=5XoC%2G&@=a+S>gZjhvQkXE z0h>5ftSa6TR-)$n3Ya!d;gRECJTe^$m@sXNIWu1%iWr6S%R(1R8ON4*2ki7AR)TfK zJYXKj)pnsKGPbyWcgfmseQUM0{xyeV-K_^pr4Vauvi>HxDX;2X^yl$i?t5thCXg zgwWC8wBWGdr@^_wHNn4vkAre31M9DLD1;R_DA+LgAn<9Rbl_0Y@S-P*9u_V}&82ps z4^@{F1qTX_6kII0R&cIhXTkD<*#(0Nl!8z5i}Hr%UC8Z_dp_rboOU^*bMkWL=DwEK zF@I3OM}>om>IT*$|EY^?bxCkl@Nh6USQC-zxNx^fVl))3qP?MyGd>1>FcBPwhlmm_ z%MsTt2@}na#>YCk3(t$y5%E-2UPV4K!PUV11vnOcJP$mdcvDdo>+f%p&?9kj(#OdS zQnsa(N*$Z}IQ7M}!D*e+GScFyX=yK}eULUOZCcvQwB>2n(v);5{ol0tXm)8ukP^E2Px)r}#sJId@9XMo>Z|CBdAE6A@$U1K@x0?c;Hu*K z!WmM(LauNF8S6;IaD$Z(;6Vo{O;G(>ESHfdNjKpA_6gkt6*ZQf=v2DxCu%eq(b1%4p=)&%t2ni0AAODSg)f{2!7R2u;^suySKnX6u}N8pXvfQYF}fr zuOAWLNUM@{$6Rjq04wUOvCdcm4$X37C9=qUKst{iznl&>Q!Vg2_Q1{!!U7M)&fFG`{J)yafLGJ;VpiL|x_Bgsf zx-j}#^tEWqX!)oo`XI78G9pqfaxVN~xNP_Y)?`L#Pw=f^Qt;ovF|3wZfw6c@z+(oy zX8pi%_+V$z)Ivw$G$1|;^E>9J<>%&I&%2s;Bk$k5GkH7mHs>9{_wVyY=Jm>ZA+LE} z(>!n9&fI~yRe+Y~A+5G@s^@-{TQ5(|FU-GRu)lC}(ZE2bpfj{AD- zk(tqUu_oHP`cb3EyoxyR8%G-!U-QH1{1$c8kRgfrE995x;*X8^fDQnGcrnaEK#GxzZt(|e2`H#V{Q5y z>5bDXq*qPvmOegxX8OGJwdtGEm!wZg@0=b=8ERy=y$T+%EUCu8GcTYA5w?teYg|n!E#CnIBPk=q1;c z^RdF4mesG4CNFPbBBKvkoyTwUjN3o2U4kutQ$h`J1gjzIEdy?09n{*&3mO=I zv%#e(=Qs(3*%@DEH3uW_pg9jY#Yl4kyv%;{hM8ktLdMYtmTtN6l(88r?HqVpEwvH= z+Vf(uSSoUfp4xEmi{8|lA(yxYB=Fr>^H^yxQJi2gREjkK2HqC=MVnZ?ScO;w@!lqQ z*fG)mSZiaVUq*j`$6b!f<{yXy$3?qEukf$g`qv68=+kMCM%R2ZV-M0$DI-W4aapvUXJ{P%7Pj#8*LtaA^H;Ra%}yeHuFub84?>E3_=FqW%&him$;8N(Dakm2uKYH{Ug{n(a~RJZm)t z^RyQH$$dvVVV&SdmF%YY9PZeC=~bXP8W6Ju%0s1=I!V0-jKdG?=6mN3=Urzl*SoGo zF3mN?9dbYCnd1q1Ui2>Zn!vCJ_(u5Vf^Tuecg1(jciDHsw-=A2z_uUw@_lLkHvWkHRcuJ2tlTpzgxy1KYBT>m)dJKu43MV;H{yrUik+PFzwqE1x1 zsHwmrbAd)4R(=64^&u=_Po)`n1_$KN<>%yFFeX|f-rFyJCyo){75l*MHWVv~68HwY zk(a!Ib$Ac<@Lh0g%Q+r`{XHc9EY{*N>uamC<+W~^C(J|UHt_4#A?sa_l{nKJVm@a& z&A*IUMtj3=+|qvs9@rAhnOb0mKA~6E%jp&Ia~-`3_*5FI3&*vs+FY%>RuY-VK48@| zP&pYA>mPe7HVhtlWbw}(k%>Ho2(Vu4S$w6#Pluw{qPu~Yd=woF=GACmCSOLUM!$=0 z1>$`ndNq0@dOErn&tSAT8mqPmR!MXG|BdK}(ecq4sMW8+b2mlTMc3kMUGzxw3b2<$ zc+GaK^+WjAmFT@_QPhV$Q5XATcx*j((~H^yEvUT;o4!rIt{3TkqciOM>&8fUfcvO$ zHNj4tX#Q>123Pf%b<1+ap9W8Q85sABoVuYOWg#kX3(%R;5q(ufz!Q$4L*g)4_bwo> zZvg39>p0-}2k6c=$5QmJ)I`PV%XnwhE2_k+$35V{*%4CDi$b3lqREJ}c-#eeh&mK>QX-*e z&Qco#C9k2jS6idTBdDj84$55l2v*|zKwLHorG;GN-#+7h6{s8|x%Q|FT zMz&WCHIM!1THxH0onX59;`goJtzWF&sGOw6yMUPhGcZs*Mh(IeoT$cj0(~BP{}J1 zsTz3-T(7~A^N75XfzvGop8aV!68b7sDs&+DdvI6qLNFPYP7J>Si}iXWJJKHb_qpi9 zXioG_G%xCjb;3$Y(FSRYv{RaR$+(P(YX0Un?L5%?0THP5IG=JpA2UmF^2P%r5N)?8<^pZN^X zoVW0dUFJ!1vH2dpcK|cI60Xi-?DIu<$Mwc!SX9ZpXskgD^smtYHQm~Xy-T47XA79B zy}(@`k1mim;WOtHGx8UJ9oW;c9F_m5;}zkGuue<>!=?jpxeze+O2|s9A%8t1jgeeZ z9Gn{&tkhSLS=^P!C`XioSe=DR8+DMnM)f+Ma>mu;>N{#HV9_nq1!`^Q8mI1zIv+R- zoO_+qoHLxa5bMrzed^ldN=Ef)An>P;fMsuY>8@P-et@e8So`a00eCc;@~e7QU59F8 z0wREgu#kJ@@4>#>gDhsQJWQ?)hU`t?hReYE7NptYNYNBlp<>bujIh&=e8=lx$`lF( zu$cYe&F^C$zk;s0C(uzi89a>2;L9Et1W`nm^Q>4~ECR2)13Z1)5p=kPXThhP1x96M zu`&>$4d@DZ2FR%*TmsvBJh~Tl;aVjK{{r=Hj-Ho)ftS9Ddf+dP&|3#{-Ikf{r( z(!Hs#(LUEqt*`zpcuNoT{l+O{pwR=J06(G1v_vlf4(`|b6-3ItuwQEEy1vl(&UnQb zf^LLc`UhZq-q91mMyhX|)tl;%z?@Dq1{o!dJ^C5ot+(|qKq>zL&#*2&(SCEfISklX zbF;DWGWN=9J;~T_ylZYU$ARa$*T^tSTM6iqs2`tbjR1G88fpk#P{)1_%+a0JQgEai zI=X_}S3z8j{Nz(af;Sv}(aDh{^mAN^R|Gzzh?Aw~fyazR9&=HAUz#g-Md!g%V1><; zWAb0}5v-{@s3yG$OZOfgIl^FZoH!Bp|C|sPlB5OlXUdn#P4Hy9AV01RuGmv@iu{(e z8gb)%ag_K0{PbSr#WRIZ#C}qt)Lc%NuL7GagN}uD@>wvdTgW@5n_`L>1%o|Fnh5so zc|@T%rPlHRIR}3~Ev*+V;jS=9EG3Nq=2KVv84Ry`!gcX)sh)gPswM3bw}?+m$B@?# z2S58OFd#<)zgz?S>PNAY_^aR*7Q#dI7uJh=!TUUp>XISqB6o6o99t5{VimUmll(hj z2{QMA=zl3CY(qtUqay{^YA@L1gVE#S2DZK$c>f^ba|i0!RteO^hohEJ4(NI#$9Yr_ z+(IQ(5UL4>fjUHh&Fa=x*!ZSE;m@Pr=r?p|F2)|JDf|UX{wi1)dl1(Z!aKYg?-4H* zUxQATA}~xV1Cgq3-A1Ic7^}aTSrr`o!NBD&BX9fN_}-{&Ow~R5U39JFYZtUNh)JHr zs(M{_=qI(P)(n_bJ)rZ~^fAU*<9_iPJdbCM1ybKh+pIN&{r*E6seOr8)i$EAh}(=! zh6P4;O|uZ|{ViiLSTC<2LV6y%t%N08PXXIoh-!ajMD$gxF4kwLTz!E(+7?|>oe&9} z1BzD7+Gu_V-0UB{hxTpkSnRyk%~)t=Se?!LdJ356XZ2DLF|qVzdO*8``p^tLL4QG4 zQPHer+yj!fOB)7m_GS4#XRYaJNQUt4$4 zkCqxAg56#pJze)u>8OF{R*iE4+Gp4gCD1X|6VT?t zZ=w6CjiWDY|MQ4(ZXgbM432|0KEv@0xM%Z#F5W}NJyYrqL~=d45q6*hpg-8)&9Nq{ zC@p~lR6#wuGpeWy)fLWc=LTn4=P#(18|q4DT~}q-pXjhSrT(oZI%|XZaZBkAoaq<& z8~FivV^vWFdMvNRzfJjPRJpIATKbgwnQ}*dRlX(lmhOma#UHT4h9LvJEq#i2tgM_> zM&Rfh)R~AyPNHr;K>k{ag0K6%co>zZm!t#O!zbmYh?vI$oA^yh#}RibN966&a`75E zxL$?b?jn?h2dE<~6Y8L5l#UJ&3w5jYKz1|X308w^5(86cJ8*&_u*W5U?s_cU%s1O0 zhWP+Bq+#g4T8{f)-ZIf?^_IB?9SPIXtFTMY*Gm``z-i0Ys~8)M5oROA0z+W?{{i>- zPgI|WTP|4K2IgzVDg7{F(VO~J*s<}3f&LXAu&_ELtbu30WWH(`dS`g@#fD&10AFXT7Dl9-rPn}(YLU?k9{+E1 zqcterCVtoY5^JW4F;I`|rtv$xjnnL7Y||t9ljdUUmG~@cwAl!LXp{98m{XO(TilNh zqo<85M9uTjTeLqMxf|j(f@T$c|olXj`m5pK-wbpkn1X&P>UR({)tNdVs)@;p`Xl)b=W}3miuDO zU6cCAG5Kv}ijtzd0egI095jet|Bu7V%ZUB3}o8ZYU7E+xQw>+zFiG_y_BL0=P{g-ls>rX50l^cK{Jc zAHn?+{1t1)uXViCDApw5_wi9qo%O~I9hY8;dQ7}rD)q?7h)ZOYE;v*V%4>8 z&?$3HTaAvHUHJQUZKt+TTd&pEw2{hoiFqZz5}>aAsnY%tY%3 z#frOYad+1Oi@UqKOL3RQ-T7JE-K~_i6zVRK@tOQ*_sO$mp>5h^?%eyyIq!#i?zePN zrj$Eyr~D9SqRTrQ`tY`hvzDkO;n7?NKj#8;cv=vpalYO_t!xBYnfwapRW7j(C+7@Q zAS-MB)*L0~qEa~&ZkrVBI)~9MZ%5wLCh1D+yP|4ZPy1NAT9>Vh&@a*r(?*gV5L-CN zK??pGr0te1)9j%{=y1*!X9er!4%1;~2Mw9U=G$2(B z6AgKWhQ?CHd4_O(2;vz z`|}tg0ZNepSl0@Ax^sLbeG1f?>wP6rP0mB6-O^WCorP@uyD}7Oc!26wo-0m74+Fs; z5TSF*!p&nTTE$`K7WFC-pHzf|petT(skH%C%KrC^}^fa>fG5 zh|~9!R0Y-Eepq4U;Z19UfBy&F);?HuCs9GzCax53VsAT$6&a06aF%#ToQTH-@i~04 zuf)@0NAWP$;A`Y<e=OKVXj6NMe91~NjR@C+4{ z1pc~kMO*-N!hZb3rqXV4tFVV}&DY~=@pbvF{6wJ*Vv3tm0HWg2a#`erVaPwGAR;~l zrOryYv%6vyZ@}5Vh={_8`;6>MZbwCP4KaZ{to6f*TiaODcnfFlc;syz46#@@Ee*d= z`LC~Qr(H=!I-K4oQ5)!l+-M@| zaE0PW(S;bG0(_AKyxje;%dNpPRD&klAM0wlybEipqkIvu?`z>R&!Nw-oU`y7_*+;X zLxf7=LdgMVi^bR2r>e5jRo*GK5l->#__N$2HW?M%X>1j~nwTtUkYPrtH4uB(P)YR| zqJ#^mFg%uqqtj7OdME9YZ=s%%E*iu$LPudMuj5@@d91b#d_SR<*c084Ho_I&!XM#g za4XqdPp*4_rv>W6x4bD{J$%Ra*jTPAI&^WU#SG$~a=+L|>;!Hw*NLmb-$zYvET7BU z#8%Q3*{!@(JNlMsVo9IwtzjqDQ7m?~g{bvEgo^H-_5}1s&9xnMPQxYRS&A?ZV-8t+ z*<99|)`^xm%qhA%eZ@S^bPk9&yYUBhx^;$Ws9Js0rx^aA;?Ubz&X{EMQDw|Na}b?x znnYMgon9-t2L z7DZvibmNK)MGnN}EgNOEj zxKt_!m*+#dI%0-=+!NIi4Y!suaQ@#H?}}T+CRjsWp$FW%U8KLo^+E@J9h9fnxhCip zc=%-0er0}}5RYALA>xRJ!b1KD_midBgK%;FhTf^7N9%S%wdZk#xD#AkT{T_l#aDq$ z?*V<(Ur?c3_9S`!pa)jcyT`kcoyGOyy9v*PT!9xBi5H|vaz~{)a@qHquH-&#d8lza zBJZhYs6kCLT`>pJ-_2fAN7G8v1XBxBn5nMmiz&vO2#?S=`XD`#UPQk_t+lb)A8L{s zW+S>(BTQYW_D0@t#CU=_X9}ky83&V0>zP<)3Ge9Ig4= zNh53MVmxW=OBGVzs58`VYCJx-&N$9s)}PVlA&TsT4y~Tp3dU1gIMTPE?%~z6M6J~i zJLG<{KKTVX|3}nty{LcJM=m)Nbs;@8EUIPy5n2N(Y?BbT9zzXqFLuA<$n+i1 z3_ipOG8Veya-g-8z}jsCc1vy0QPNRY>H z{}&V@W_YkC3S)3Rv*6LqTH1D|4lT)$}Ql&Kw^%PhlnPP8OiOWDiW zhuO+oKQi6v4^$6Bk@hBW9aTlEZxM335}+o|(`+LSX#eOlja^O8%sKQ?#>GhJPR&E@ zKaGA&_oAPgS765)Z7K~F!Fcm^I>u7krq~}kOZg8DI1s=DeDwd}-^%}}^P7ENe&@R7U-ru>ka|h)9$UTxbJ>QkTx8Qeye_@TncLjb0xAWTNzR%vB6_;tx zJd{zCQ6;N#u3Fg4J5S8^oz*{}=h_{9BmF!0U-f(8tm}AfJ7*b9Uo)LIQieewn>5yW z$!uaac~pB?9}8N?L-SmwitT~pgY%hFbu@Iu+tymHnQIyYwH17Gq_%uGd)L#?v)$9g zyM%qgCrTAnm#+%R=>4erW{K`?d2gw14Y#(jq|p~m3ymIlBF^Zej1x??m`b+J&OHIQ zgBylbix^$PQ^HcRWrsG{wvw;5+sQ%vp6Kg~zr z#EdpgrxqD^81A7Kbpv^P7ia)Vp?`YSu-;95XW z*#;}1mvBl@g~g&-s)OpbANI8vF;mzKXWDaK<$7`|YvKBGXSwS9FaCk>TD&dQgqpZ7 zVz)}jU(X;jPDLg1GuA30oa4jzW?Ut8?Vb7%zp90 zHsE>dDpg#o@J@ckdVV-A&*pM5NQOSUI_ zO%9*)BX>Yv%e+6i&2m$7va-qSQrV-kr)H;T^~tK0Wy=c7{E@yV-H@>LY1eB zj+?t%V;qrwqTgWufqs7WU}l%`Em2hp^$JDD@}K3*$zGT}C}&M>>4F4TN$$8<)i+${ zrAjfMtznL4jw0I~Ym}w0`Ig~{_6o7xR~l7`lbY#duCBM~mNm`qRq*$Sg&6Z47L^pG zi7G06y~MlFz@R*5CtEv9JEj)Rnkn?|6PXH@BFhqM1$ew1)`gZA^a67O^L0~2Y6|WJ ze_d&EnC6kXQTF0&aYLye$zKu5$)nYQ8mqRVVL0`ViH2YCk7cYi*D6~pTb)qR&!xl7 zhp80fL1PrEH@}VbP5aGdnOfFq_U6u0ey{w40(SWC^lRW8Y0t0>r8~lF_fkIxy{9SK zWK;$cKzUgVU&Tx9I`j|bk{^hCxF4RW=aeaOEvb^&Ss2JKfX5~Z8~~MV#BJah{xZKn zn2DUOCvw+O@L+90Z>YX<65Wvps1oOjd$8+t7VC=L#GPWM*h`9&mdkC>%V_{FS_kzJ za>btVCFu*g^X-Kb{5S3{`^anY*7uBahq;5{bzq=!o9B98>?~eblwY{0Fre^G!NdYS zzf=Cpyg_+8a`SSI=bX;@nzJXTdyXcjd-mC^Cz&rZ3er!eElrhEPN(coX_ne7t#o=^ zI+^LtYL>Gh$CcA7*PD}`{UvL5W~KCilzz!oel_|P^SdCuY(X%;n7qY!0~?o2DYLrV z`Lfqbb&GHZ%l;qj-P{WqhCFze+D;T5wsUzI) zm|wP|sWa*Z%&eAb{~eutC3)xXE~(=)|H_+L+>Pxar<3ETB&MxB%vt1E zWZ!DtL|cuw39C{%T@6=E4B@BosCSeG z@)z-y5G^!E|F)uZLGA{6LX>uk{-N=k=^1^~a>iEA(bBoc8RHCb?rdjbBw75H4HuYI4Iafyjut1 z4x0-Goi z6_m>$sHCD(eH^uvwWyawqn`asaVgb6^tcAnN^7v>c0oUP3e`n;8^J%SBaf86; zZbAn9V0YL6b~XG9hdjMJ0$g8f;5&$Mr4)BAo>kPlD7t7%;im#2e@Om|yyv;v+}1hc zvIl3M&%TrWF1uIuiYzJfO-37dWe;OT?M>O3G9cBG);sN4+T^qYsnb%Iq^?TMP1*Qo z-tW4}J(FS+4#t=KVfw+xH~w8cXP5UL@zfF=vbMBe#o<+ERu-b}M}7>+@hfXBq~i3C zh%>%v=XI)~0<##ryz zBmA!UzYnMuu+>j=+_SB>B%Aje+vz)Mn-KLilrLM!kaNTdf}3m1cJN;IjP-o?JoJv? zyuxm|zwa>FR$tB7(^QL=m@sQ&YcCK023R62H<{nGg&t-mpdTJipJnD+JK8%s@A>x$ zN)6c+)+M}Wc#p74A=iR>2W)emvgs^Z`nc%^r5cwTzarngrccy|7z8LWM}vjdAN-QN zWPRd_uZ;RlzJsXhlJJOExQ|c@w&y?dm4z%JT5jE!5Y9C*3O;4gB^7LxxpxX73V5EQ>rL9Zu!7DwbgvwXNxxy6w4g7_>SlPSY z+t1s|Tg&V4zVeKMd&}dV>^|&@D}Gn>1ipj01!8`e{1JKkb6@4eXD`TZnteIToV6x% zXXd%gPMMc87Nyrt`<3cV)uu(IHBXC4>zwv9H9sZe&!^wlk~P2jCw@-Ym5}t){`1|B z`EgC-=KWZkSS9sDZaa25agTW#v?_9Ll(E9)a(7By4;vTo**4f**3gAq4_@>NB0#s& zc+j+l{%P@8``bU-o%S=fcUIoo-_h9rSzump?~wJuMS)4qSSCUjB;G4(o<;uYnb;_P za~vBN^s~vY*QqPBClylOOu_7Xq7sUsJ04_%gmk2#;SN@fc=pYy|A z48OwHi0baR8geCaOSz;9#g+UjM^qe9E-La}=-|M8&d0V4OH&JFeQK-k+#7H*_*Urs zu=-(+(6+&E0-S!6Y_sVR)I$;<}Dtv-P6A=ELRzW&`RRYfNQ8meSGF7=yLQR@3>$e`iq5&=ujABd8LQ zC7MR;340u}H7G1#sPnE(wIqQ+Q4hOgEqwQ0bFsNKeFE8U2h(h-hw+p?L#rp#eMa@N zyh)mg`Xnj5;2(iybV%?CO;BmCB`;H!!VO133-wA<1DeffsM-gC+`1A~;Hu!_9R*F& zt64$@>(+n}WQMPJ5*(OIOy{Y!#xjPJI!4=$_~x6VT9wDrKJlYaM%V|HSvyogqu_(7 z30Bu)PGM`YExiprf4T3wt`{#ZT2Xka;9&m9yv4aca{O~~_TnbI{iUvn58+Y00|-#+<*(2%8E6$=7$+honp_?B@fD=7DDfx%Ns z`a>3&oA_N0trYpR%;$2|qPmo=8aXy>THq8%jOBoN9jY14>A$RvoKFH`LPmx6Ea5E? zP@-S>`H(JwoO6{elKIOt+E~-D7M-wj}$k`w|(JSR^OUR zGTG=_%uc2W(*_RvAd_O8Z*b{OXdfdRd_Zp0H8G}`HZU`7b(|OcO9TamGzt9{Iyx*d zEH-R)s4>JZ=%7FCblDbKD_FkM;k0CSLRWc(Zp75UK4)giKn3hipEvnY8TviiL&RyH zik@i)IHf+w4ya{1smq~WnG0phPgPJmgHHMwwXQWiwjQV_s$=ke<)vsGvH%E|H8yV|DxE! z)tEDwa zTa?~1D-w9?hTIahv_WeL^cxafCp@M^LW$oI)501B69GnNl1b-ZYN^8XHFu!e8faY{@zqyb4Oa4?l(;HA zkf8E%x?MyEzogHo+ZT^Vjt!>8YHlnC~2ekp4>2YiT9Id06feI?uGEJ%yH$wPyeCt zO~IY~CwY%@_vBp3KAlxDb6Yx{Hb3R#?`g?re+B(olTF2X}=||@u zcjETPwT;X9p8EaB_kwSmzmEA*?n~(})K~fYk%W>dM{-Ede&wWLrS*V+<6uv4%b=eA znYQufw)*dyn~DJnf$HiqqPsrF1bUA1PC#bR@Q_WRRM?F$HGEr%pOIfmUn_g0+`6*$ zOV=$C5*%RfXDm`Fjx9{iDb6gFIUviB+o!M$#x%TA_7c&$;rc=Pxw?2FQtc{IY;y7E z{PH>DGTWvHroBjwO52ehnKeGwUNqFZNvx?!&{wCI*lsx;0Y3sF0$%wgIQrTyFw@K& zs;ExtjHwh8VADEB1f&Lsg>NolhBaWq%S(II za^xQUdTJ0|-#Xs@*0IO=$T`WGftto{+eb?T<4@l(&oVzZf1>r4nO52M%%Sx!3b+}x zDWqiB;qcE9B}%M_C>L%G-5RvfzlOtUb<#tqa;SksYY&p;(VLn@)`w%Jv_2RliuzDL zelR5Hhv|-xJ2cDHadKO6EWeI@?%Cl^buDqtcNyKSJ#O!N?w61xT~Ydjb&#u}pv0=E zY3Hk}mQXs%+o0T-1n*QisGmNHOQa!kB_&ub@53AhLW_P`e^Mrv!QJ=*N}|CECoK~} zN8_rp-;h04ag8sohDZ0}OT~Iuu!}1`P+Saua=AkPg2KGlxyN#vX3x)@m)bQ&T*7+1~>%kCAzk;wAQJqp&nLxsfn8Yx<1r2ODkvTz+EA~ z!$KoAMZ`vwDsiX8j*_iP*~-)^r!T*{JX!uj+1HVs!jAesupBZJ`M!uHI6v=8kJmee zpCtwRs%p;~Mw=*l4E@-Amx|S&BEHL)xzDbd1)iJ|Ss&7eq-oRkrXYm6aj9 z(A~{7O?D~@{i+)9>l@+4KBeyjV#Qf)Pcn!|_f1yoDRbm3X)H7ykI=7q2fv0vBG5Ot z<6lmSCB>!4Hc?TL*D}6)mhT>yftTLH=tG@>Q+F!;wdRqHd zGg;jV9?c;+R`n;=>kd-&nacJ|zi)v`aO2QvVSB>=ifCTqddbtJK9$i%Wt1OO@p{GV z3ik5n%9JkoEo6*;J6m^iCBuBJKY4?gO7_qN8UxK$E&c3IoPGRx|JnWppy9lwL6juc z$@91%_qM{Lc?mh~a?a(P&!zGM3fG~BFr3ZdjnXQ)FZcvI!A*;kE{Uo?!lCI%7IwI%ry98fI#5Drw4~R)Yk+6J4)q=zDtfJ3xBa3u?mx zxcZNSB=HCe(Sc1!hZ>a~H;$7)&;RsiT4zHN_q!_F0vo>*oodU-hG}7RMKj=dKF(Ts#)~3a9QE%!cT=2i>81RQdm?} z^r~nh{{3d5zOYn5o&4%~=G>g@r&$*>lQV{Aw91&2@h)RjrW4e}9@)>c#q7-N)!8Mp ze`Gz$>X^MOr(@pkf`=D zIA`2W^#;}B6*@a+%N^@Ad#aNTC?8ZV|rI{wi9EP}$vMy%J|@a<9mQkuyfq@!XlcpDyy zS0%f0QJtrmM8@c<8m<}>sC%Z4=E3H4>~^)Nj>a*Dlln0IYj{KZ=&evKnW*-rRpuk~ zVbD(+TlZPFTWeVNTYfV#9Yv2e-#0Zg<)Guf6)e*6R9C7pTve6v=N#$;6-Nc3L)+Wb z4bS`!C_Y<^ZbN^=3-GK@K_wCo)zwQ7UcK5{pn~6lYGsxFJ4Uz%8_F93Kq=`8XUiLH zBGg=OpoXvFI|AL@C^(fJsEE;U?wo?cKNkJ@X}&LNC3S+bR=$A_z&DF zt~Xa7l#hknL-Z_{@(TI|D})omaZsff31yN0PDbzZ12{^XxL#Zc$FdLDh3slL@M7Rk zF(8}DC1(ixt)c9HH-;^6<8;Bldu!&=I}FG0>JD2G3;~^tCfI zjnKokYi*#irs}sE?8X_!H^xY+H@qWfsW0%73`cI;5m8td`Zv80l+2BmB#Y1T8;-tG zmP^P|-_f(^%5jJkqP#_Eh>GhY-)wLq+7knaR)m6A{1uwbF5qP5fZNpty`va;Ivhlg&=aVP z_bpJli*qs$j^yq*e_uc;_Erps28@KpXd?7LJ8(s_L8uYnB(;bvoN%QO_dP);{JXSP z9;&3{Jzl9^QKv#l{6QHGzU)Xa*6V>)w?@tYsjd)N^me#a`l}wLhmwnD)W}Pvk?=vc zkj8_|u7Jrk0NT$q=$H;b0a6EArNvMyHHROhJ|YAYvhfso7P=CZp*dZoj)4#99=aI& zHe}DU#Ol&l={nfZ)1mdd?~BA_o$gpA$=KyM%O>0G+jV6V;7r|2zk1obp5Fbu`Vp@z<259LA$9szz^ zSwl^OKeTB)+?7i}EZ6B5=$=AD(*m;xx@pG1J#rlmt5m$Ad=PfqgT-Q@e!o_FA<>STDRS9Dd-EqMSH+dWjxT0_6l396!f#51T+X>=!g zKtX+i{0MbhTlhSZw9PS1AYIp99}8ydNjO#->Tl{Q>UP6ZKObKD1GvMwVzo{s-V$w~ z1uOz{bTb~k;JhD1jw8ls{)RIsSlt8NSskzq?}A^@A8JBTbwgV@9a{MqEp{hr9QNbPB^|+z?-=k9xt0F1+$PAz?aw^b5)|?ril7a)%>q7Wdi&w|L!tN ziG^TLF2%Ds;1_aWn#^GM!S)jzF%*QUw`6TFsZK*JXxDWD4R9{r(-SBx^`G$O<*0CIKhNK&WHxVK4j%=V=Sos20NY(gYf9 zMSbp@51!p1c+FKpCen#t#C0%*_T#!tf_ia02uQzBRbK$raVWZqR(ObFpjUV3RBe{_ z1iVAr;d_hM{>1%}s7=>?1Fw2Kd=8(;xul+41*bX(b+;Fhlm<$)d^p;)n30nYEvNuh z_-CxvKgtI99|Dwj*hzHgIj)deK^b%{lLUCas^aWf3pMOB z?1R%W<)j&WHN4smzO~z!Hx&ubZ7BHdZQw>Eh~aP{S>OnXC)*(38mcv-Pf-sJyoGR| zeuEzSGzcWM;qT7{Ey@R%e=(7b9e6T95jU_tHsa)>;MwnhJ7pQpkyCg_$G|Q94HJ6S z;YtmIekl@EpXC|@xD_%HN{$B+pdBV;tke$1?!FxntA)G>A60kFP1I$&!Lc+SlP>N< zF~33+fqKp=VmE&JM)0ZD;yNY$x87Pq1#U-0=qt2Thv94ZcM7ouURDvFnGJ&>n%L5ers9xb_`r zFoVgS(A!J`>EIRKgBa`?Z$bM>gCA=)^nybOJvk3kKP24EO|{urH@VPV5Bl$v8LN4X zyMflEYOdh@>Pn6#N0MbgKDYx0U^EDT>rjJeh1VTP#zL`Og!Q|cI0m=m6wG7tYHYZ( z8X?w8)3n2xOcTFBx+(%kKL`^}4iR2x!G`%xse{!^>M#&_X-qo$pJo_5mrdcDBjBrC z4iDWVD28eghj5MeVlIvz^B(5HCsqQg#d3JYahUkF5>p_Ksx4Iu+*Lc3pEwb!!ZC6N z?ts;B4-A*?L;Jj3qM=HBj;h8TVX)9&2*j+SLy`xRKR%#pctGk3526uYu@#d)vY;LO z3#`i$=#Q5XpNcEMbQ=lJ*M96bncy8=#&czgwJ}@fZ#*7={q`1)#BJEow&3s6;my*3 zbyN`(MlM2wI1d`2JW+=;m^@lq7DYzBW;4JKnkJrg8G6Z*p10>N#I0-xHdw_2?3I4@6%r2?`CV3U~*1Kb# zM{ivgyi)g|&kBQr`3n410r>kW?S7E^enJD2hyTkZIU<1g3LorBc+p$H2YU_f+1KEu zheAJCR}%|w`((`i%Ky&|e;c*+DagmR4+WWv#%-qgWK@BrsGsu zi=P#wjU|7>DR39=hW4O>uha(M)pXW=)%Mf<*6tzKVF!MMpQ-%`!goe(rnXc1 zL$%{C50EN~7vaqw18u4-HJ5)v^;0ZFimDh3B31z+qIyu!{!cy%rs@~$Z+}Z;z#X_Q z#o#>bD0^i%x0M;tajcQUL9AYl>0O=Gk%)jND7Dlc~?c`z~s_!&|ulgzO2Rcir%HMfMwwQ?~=2hg1HY4z*lail5L8&hpLhF!sW} z>cUC-0xL67Oc5(!P4|%@duq>xM@k3-Gc6x5dY__}ydKy+}i9@hRwUbhwW-!O1g zRq_$`Gl6&rCwD#(2Bma3*6|DC7PtZ~TxANsX>~lJ;m(PM!te}s{T=Y%tcFW>40MWm zA`5JXv4}PPooV+Stjk{5T_sI4_BJ=>D6PQ?I|=s2OL!&v!v!%3-**R-ohrfcn*w^% zGWcb(!8>}4)8h~5GM8|N+OUcX$jjKrE8twYt-YZ=g|GW}U(P3wU>}bJ#bYCKD<@$@ zm7^xK;!}tv@Z~B+@!JL6f zb#JkL*Wxh@GrL-%R?to@r3R{LpuDyPDIo-|vl?o+`V}$cKmTPnciXy ztH@>U;!zBBon2}Vb$V?$xdhDD+Aem5#`7KKC|wu+fnwMQF6?D~BRai0xCu6M_d&W0 z5H#X@@x63YKBq(@DxD7M$tLBeTusJ_05y9hXjt}&6~Rv!2d(-tw?@8 zW%v#zZxUj{R76|~B8D!w7si63IzTIFck1fuZ|nW=RXJduJ_O&ifp#0IBlqGYu7HgC zFm(MVaQbdR98ej$*JdCqWP!PshaHZ^s%Qkp+AYmTI3#<*z50VlLlhVf2lzWghv(qC zT8Y@>3aFI#P+hx%mAniNgPH%$DQu0HuMMK7MTk#Uz|XPmLH%LpFYkoA~L8n4cMowYdcUZNxJNYc~6)s;`ulN|fRQ z31b(WWsSiJo1j)!9qKRmcfKQ&%f_6PY4912fby<0dcgDHAG`&R?O^nQd!ur(0*^+R zVf7LFyaKum2X;Xc_Wpm_Q$u<%(+RbZk=Bt`3M9DBObyy;j;G!lMO4gKcxIpJhZwpWM^np8J6 zhJv<*>5kEAn5v_+*NB;#MR1pVK!xZaxR*Z7e!_;c`8v+y3%GA)5tB6|ee>0;U^ReL zfKJ zJ|d22tcXg)c0@`|$u|EvxPn0EY=t$?oIQ8oAXQ=k3oRnp4v3YfAhKQqjr$Z3n9kvB-iK&zyU+Gtyz0Zgn+3{Y11RiRxOW!$ zX21)fVrCYlj=%{$Q8vOMy9n>cU96mjsJ=wOw_O+BnTe<$?3B;S7f~DA0@q$AFkS-C zce#Q3N*A2RbKz3dfnY?TQdS#Of_OCr@BZIvj9LsLMop~SRj8z`hF2>`Zl>%;p8gd( z|4~phrYM6z5{XtSqu#Ra=pO>Dz)fZ(QMSbuN2$d7d(U59{eQnC0w{E=-(XUH?jvk z$*zjUwxW7Pm5M#C7%#`Y7Aq+A(VZxZ*me#G;_DD63OF++AU}RZ_{gTZSa`HL!xh-e z)Wp=-BvD7e?wUs3qNDYr3?_V_i;Vn zz{PT9L8lreG)1RB3_eROSfYx$0w?AW?1WmP26o**a0;r!(R~Aa`e<+vo?zPI0ewk> z+hCxonuePf)7zOYmf4mw7RBPV>;j{98k2;|7 z)&bUOmYz&Wy1IFaX%+R!xWHH*PT;YqWV8Aom`1P~_4I|P3+w{P_9mPe=QUS+AK~0y z0`Jub`JFTyv1t=9y^cdm%n9d&<)~8chqC>MunF4Hb@;dd{kkliuL;}(?lJcSzKLVp zORgeL-Lk?2VK3CKV?|CJiF^7Y7)Lwtd{vP>9Y&lu7TMMb__&rxtP}(G%O$xOPVwH# zR8SKJD3d^&y#%dJ7q}$fp-#LWWTG9Ynteo^Tne?f{z?Prn16t6FcK#>i>l>q?8E+` zApC$M;0Kh?ZNSE(u)n^A=kN$Rid`|OB$%xP1QNXjI6knr3)%eB97YW`BG5>A(Y2WOp z30xc0CwOtN5L7N`Xuw+MD_aH2IkQYPp!$LYcathM^Ct z`T(+muO_D5)B&Ao3HTE|eRg6r*$6zshlprb5v*^Tx?Zj)p62>_=eb+C%DT?D2DyFi zo1TU&%@0GBx3qW*e)ucs29)PVa+kr$|JyqT-K?3I^b^fyurfDBC@*>B)#_beANYRl z$ahX6$_yl4z>)oyctu`B#^lgbn0hyqnr|8jj+lkXVLn>gST9%wYnZLCt%@~tJu5P)?pS^9uvk)$0Vw$m?-!WlNCH* zBy2St(BA>$U?B*LPvCxRNxX#j`z%N$nW$_pkPai`SSASIzKw^ES>y^(KY9yxu!%dv zwt{E%f8M>`DDN>(45+SNPfzc0Z!#RF-Oxv=%ngB_{u}$0eTd05xolN*W4zpcexTq$ zoqPj2DNDh6DU`?Jybo5RpnJ|&tf)QSQ}e-0ssV=hR!vh>hwdPXI){j28!ARFOb6?Y z2saZ`uHPW$UW)wpiaHR48W+g%LzI_@1)TD0?9YGTnVcmQ@<*XM+=fc=9!x5Dk3P2u z%4}87DR(*d3fJS}A4NrlbqYfYUgU|n_i`ih_UBVYXI-7WRr$u!SVW`)m4_nDRdAOn z+?zWzJ2b0b*4>=#1;^YfKTz$U?PPccrr|Y1tnM_iLR~3U5lX-@&{qE22a2>YhPi7u z`Zoxi8W`{2*4f`SkqI)7qc$47#tx=H=ACVgU$3ABp-R}B@E+mq!Z`E>xBCxvw6g{= zyqN;`m1cf2e_Ja!F8j?7SR7b6@Vfs$&iVG|mRjaP28Z@OcE~e0>6>C!nvXDPDUe~T z`ecxgx{|FmYgCsUCVk`Ev*kRiTqlb+Kqp&2HZbrB@^%N}z6+!%Jcx1Pu1uJ1}J{$1?vn&JB8TI}xV zF~MK`9W>3Epbh`eQ`>U`Ua&u|v#$GK1b@f;FQ2y(*OqSs0&6`?yG;WfsGd{+b;aM< zKi7cy5`dl#sT6_JQVTrifnW`mA<7UsA{RN@d{h_Xp>O;fS>Q1AhL<2ZO8Rg5RZpMQ zM}zQj8TE_Xh@_G*Iq)2OZSBNo=s)h_Yw-8DVc_C@WUI0pykXv0@Y)016{+ld|9sxr+;2J8a@yn`%KKihpjhYG$m)gXVh?Gu=;o}R2ZhEaE>lz4+txi3S^w2K0U~G8PkBg{*0g1p2pDT z?^wwj4IPX+lS~u#2L4R&*U*9CpTY-*PYxqPi-V#AqMWla`!APi57qM{>p5FlM{mDN z0lS0t2bT#x7ntOK+F8fm+tR>1%~(+{!8x)H>^UQ%y)!sjgN!YV2BXn1QFoZENhJBI zs9og{F@>wZmh={S1P|*8!~Bqg>=AAQA1MS23lNhh;hyc}9pV}49^=|poKy4`(aVA2 z+OE>>C7z0`$h{IuBYU)hf~J%AOW9zzUcot;C!~u@ufiWB6 z^(y|R8q(46mP`h^9y1p6s3_Zb+ZbCk)Hl7XrL3wY9}_-~SbNwS+jH#e9j_fTF*~7+ zy}Zq2{mxv4ii|P8HYKCaKLC2NmS#V!Re`Ec*^DproptHR!53i0%@$niMqp)4MkHMU zwC#GJ{umUad`!&Yy=(*TMd;}pxmvlNxK_I7dQM=9(pj!K-xtJyx|lMx7wV{Ztj!v( zd&S4#nSSf~;!gMYvwgUo{8}(uCV}k!0%yxEz5(1*@3=&+F`V6TLaLZ0ossK9ol@h! zPH`c~N3TGT8;d;OsJ_KK@9yY@-B(IMoiYLy!HTFBOh;$r-#eS}^+ne$NZAb%!Y*(| zU&Gtf1ikd$Vk?~Os$dZR2KRO`f15kZHuUDXKf10JAB6|^pMvjj11!s*S0EPV7LW0i z;$npjk{kZ*6e*GS_f{(&kpV=;_VZmy5NuiuNoD_9GF@a>6_KGG#*&$qJ zJ)T0(d$zJTP$jh|jX{jTzSDWl&(H6s{fuRf`Hk@_v@6GScEbefEN!)q_ZNajgzgE8 z3ZE3_3TYhtG=TBzWskPbvUIm>w+yz9ux+xljvIdK1MUPS1x^TD5RmIfIkTZ?txlh% z3ekbI8oFVcQ*+}9OcH`FfjUYBQ`L+GI1Be{r;=rf<-X0zb7{0VP&f%ru7Nj#9&HpP zAx<0wrkNF*<8<&SXYt#)MQnHPSkHCLiJgWSH)-xgo(tZ#oQU{lhcpX4%&*7-NT@I7 zi7$o4i0NvJ9igA?r&5}oghRVrw^={YkOC&rHBe_~8hRK?8JdAWTgjMdG@8027TpaM zSxxIv>rXi0+|~!y#n#f+-RcOrD;nuOy zY-@HtdzBT~i8%AyL0estU&0+^k9u!;6!$3iSJx0%E!QGfc}(+BJb%2G*-2akh_R30 zB5%p>=k(lhaE(W?%h>NYZN~7+g&WAB-SR0gwrb%K00vhbL>T?#P}vWW!&!> zx9TEafMz}B^kkw2wo=2QrZx#=#TkkRl!D%Jf8=FDQB^%H&qgkG2mZ|f>3|q0Zh-UG z2Ty1V)KX7-Gd-<5>*20z;rd2?@s^DygEXaB%Y!4pH((4nD*kcgn({yN74OI`ZC zsgY@i>9jeH?qV5e3vj;jpAc9WxHWKMz(K#s4x_CeLz_xs_T@ZnCv>7_=mvq}B4Ee5 z1oCDq_1d_^@K$Hmjv~Z!Qdmj;I9vi}yhGwig zyAx{cP|qHBD|b3_k3p`(uCDGd>@8Qlz1SqS6L%c%(-+KNdBe7WGV(RDN`H13`}w~$ zItdzr22wJzr1MZ7)J5*oUI|swkPRI{^?pBiF-c&(oK}XYAhRLzT8N46W1+b@?P~!I zdOJ)A-T{Z`-%2WW*ha|i3}DuMQu-;+a6%20mV?7lR#=B@wGsD#=q!_)_u0qwj*E(+%+$yRvI2-ciW@= zp(|~SGHi5%r+EU5<)}YntNLlj$B!NPr4<>X38gr;&@P`ze@mVU%0Dcd#Rh=l^;p4#A zU+OLNdf4fFcX7HrMSbsEh-%_--$eDL>=yMx5ZBZD%KZitK99TFyQ4izylL!wzP^|# zHC6PON5Mnqunn`Bp;8el@>e($7}nLrN75pttFJ8anyjev*RKG5c`}GJyLGj6GP>4wj~WhOHk zW)Izw&NQ#Ze8OAM=T(E2ayWIwm}006^35waJ}YR)f;c*wup?L7q-l-r=w7ITPpbLg z0ENju%tsY)HlOC&aCT@^%5r~k=h4^s4wYGXMBNeWd`vZM>UrRv;O^&MaE76u^W-o?*W1PKEDFo?VI4XOQ7|fWE0tec-=4g^}+-&Ukq5GHI>cKVKG2 z6bd5e1voAiq7M2L9OQqL0cxf?2~^A>pavh-j7RSv0sXZ?bpfiXHxQXr01Ih4d^A1q zJxAqhc*av;V2yw-h{fC(S{RBs!0(XbF>Imtp*Pms!}|j~f+TlOcZw^=b#S!f*HL^dKT)e_;t(hMX&B#c@W39S zLQxa@{de`Hh9hg}n`0l5Ol8gIP&N9Ee18_sXFg52?ObRyY8@xls^>UQ)UoqmDy=n8tje z$7-w+Ax{vG@B+KfyWc}VciPJni9G%US6z4|b_8dVQuXQvaQ{5$L6c%6oNrrrli(IA zKryT+t9&MKHpXMx;YcXeY`UH3C9ec;tsl7reYB_AN6-k*H~x=036@cgc{Dwj9!Try z^_b7q7!$g-n!lT?(C49cUjujjH^#%fWCk&rbWi%Vxs&;Wsh{Z%RgWSlAk>VU@vZTw zaWiHl*2b=S73=ki_7wRK@fd2ZI@qUnV>cZH-QRK$ySqbGwg3|;o5>TT8R95J-7i2( zpmE(_uv%^eR%|E!EEwE3`FS}1W3j`wU~htk&;)w%C*F~4Jy1N7`Hi5hEfF7}XVh7| zj@W%SUk8-}4dQ_JprSnzGb9r-`(J7d?vmx0)iek-Xp1r!{Dq6~%=ZNEHCHKCJw5|E zlsi$ITTfcaA;cWar(UeSM5QVidbNL){?IoagTiPsG_G3B0^i^2PN?AfO3lTwLIOVx zvpotpC)k*0!Jt0{Ui~$wE_JNi^UNLR+U{aq=iIwJSj*gY;e+@9H1D#~FJTmanqB0X z>#AA2s%Sz{aPcr#RnHjqKF^7n@(T47rkHI9*X1AId#ER>g9%y&@7_Y+35}UNk6rYX zeubf;@tDzLw7{!Yit0gKf_Gpe*i@&@eQ6VOiD_#|v&33euv>mxcVQafW=lSkMJJid z;p8i8j>Y^Ao_@l-uza*GMir;3t%ucSnNMFfJutr22kM@Jcl|%~xH8Fhy65_G#%`ED zbJH~6G=N%YFzW^p&(+~_6|o~9$iWN4UEzC){&I?P(HDsKu|9c(h|wHYH_6?QC1!Ys zd-}Rn*J$@BPo_7UD}~d@ciD$4Wyr_Hb?R2QKj*5lrUMO<$KB$pOe^1 zK13#$g3kRqbiyv8`qdGt1eK_VZq$D57Tp&8OE_sunckSjn*U%zof8$NtC(vz7W3pr z!UuiAoNca8&!Fef?P!Mn24`ze%%$FEs%7#~ged{q&}i`Hen2Z~GOjW_*PHdD&{HyC zYKWFR55<=Ss-Z#fd0qDT`DUok6#|65f3=JA5rOX(W`o?(Rj7k`931}zcU%MhJ?c&b z;)A`=pU+?qvp?C=s8?O%GB`g(@-;x8A$Su$RtA&iFMLNj-$S@2P^h|}5M{9sR4R9+ zPpFlKqo33tHL7#)>W@b+WE$A{%Y7WW9%Dg4EQQ_l6zGVZ(EVTLdk-(!d(6VvP9&h` zVuKcH4SHt>H4Qa6=j5tj(j{4G}W^mZo}|5FrR)S^f( zdR**w?e{c8Rq?H`SW1&~lsl-Qh5IzP--?j$&BNsF*|>wwp~v?g>K`3RK!rF4GYq1P zHBi&9Z7xfH#2MKP(=-k-|1h_(&%`tDFo)nAa}(#|DP|!P&b+7Zq52)e9A};|nTY3( zLF8$-ezLT)++yl6hv{@UmQPUYF^BcGo`)W;JoE(((ebLM|EV8~39L79g7!up(n|XQ zT$fJjNqH)mwk46buMzGELr~KgCyzvz{C|kBT7UrDL2aabm)eP+`Gs6Nb}^_>#d-8 zG1+npR3~e(``#vBpm%&qI}+1M1{>BG-%%uV_-j#j8^nxd>cZRF4Q#Jya{}V^k)}bW z$)?Sw2c}=9pQgvAL)dYPsTGtTb;{V%n1RW%6%C(IZK(wR+8{8(>w`G%PmUr^ATo&d zZB+|UY5$5@xwWBS&4AMO*Z)~M3+SlMtqmU^i4inNahHp`yB3Oj@#608?(R^W;_k(v zxVt+9l8pPzIsXIeUo3iQFNDd=clNjUyI;XM^=4=p9Ns5z^6v-Q2A-jZu;V(?8PA$V zIPuK^-OofaivgB=kki>X*gp6Nxt2jT?nBvnzd&6ifsW*pLP@F`jEwF0xlNqK<@$l#t!b0pPrjV)8hv#cJ`{DfTc5}ma z`zV>Ek=JqBzL;F$TaIhaMAul4?v3YGNXyeY+&|n`$@|uw(>2b~)IQnP z$X3_3&-TS0@0{Xl?6POwNH$I8GuZp}fV+{1S66M)&@_Co zhm$KAP+v2q=dpC4*PFt|>3!^#xY2B{ePi-Omy7C%X5pmeu;r1Z zp;eBG1*hB>(>3-=?6=tWvHfC?#>|X<0lR#F>4aKBc}vz%1G3XZ_WHj`XHk5)LMz{>mT1tW=kl1~CMXu%eLqQ61lP@pvoomOo1Ub7|az{#u}+=MP+3<;!9 zNCBEcFL=)P(ih8quRnau_x?(O<$CpGU&ZSnFZyBkO(Z7Ap!4 zYI3q=t7V3zrsb)5JD5jba~5-2b5XF5*QU*;A*MJ}U$Vu9!&URZ-5HP5eM49-S>ajM zA@}_%?78`RNAe9m@yhTpCAT^SPF3Dea_|OhkpnopPlwaj93(C`*zA4Yh4q0G@IY{7 z#W!;gp03NnA$*bhvi-~-c@v&X=Mlgi{(C4LJoPO2C2t@F!3^W&9Z8M#VIoBEv{*}e zaW^trR*~!U)AxQQh<8OeFF%u_Bp618x}+-TnU;`c*V?@p zpF^*EHJMCpy#;*9zSI7xfjYs`ID;36bk+YhJ_>p8C7J;ic1deyx@dBk4w^ceRMQGv zu_wS`=}U62g4g;OQ-AYJ%L{9j=ru79V&BI-PE|d=L44`>W29&|IV z#G-Ur;!E_c;6@dKSAttYBVh~-A*bOyEgmdJ0`_S%8!zbP3!)onfQ#{Elt|r~ zrPf3WgH6nVKiwJ^;j7GLN6~D&)%)T%KLDnIOb22CN!*iBB0QyX4?;_D^Vi&Y9k%okxYFHW zOa4qa{f7_fymJ zkreKR?oY0Tu0pPVINg6a-q?S)f20y`wLP(wv_H4sbKG>EcI|f0_jL1mz18`&cl!o1 z$6i7ymCifQ)6G-OlR$#v8Q7m zM87A~tDv>Dr-Ghx-vf=KSU+=1Jz= z=4+&nuY-4y-~52;MTWLr#ML#DX%2Mm-v|!-xXGJ3!Ih(_{8n#K6~KOSoD|M z>@)7{+HepHg1P=oA)1I=kG;i!R{^50ec4vee8FjD$Px`QK3hb4WLS+)h93g=)> zRDkz=%kUfV@c&~4JDabwpvG&_kv;gu)V;~K-FXh%$sGMwVtZzAL_(et}zUKyYBFWw>Ibg+A2SDtr^m%4?M*HHONR z(elMIzrYOa3vKY0uc$ z*ikWGQMWCNvPSi>{%0v=nP(1~MxvOU0_r+KO+jPzf=uB6IqNOa16W`{`C-)F;@z*0 zXM0m&AMa5O(g$vZ(=*TC4OYSHzZSZX;b2?&~;N4I-NLqSW9K+FbG&B3dc#qxE<(M@&(4%sDyb0zQ7P!6^=#cA55? z_D~Uqn!20n<0<}yT!`5)!ETU2nxGzpfB6j^O%+_r*Ku|VQNvG=ojVJ4RcrdPN^rdd z6dt?j56r?2`d-C2$=R+*8k0be8Ua64aL_jC(Rklx29qrYp4bSr)L$?R`%&+k=nc^V zcBl4lCZ#B%|BtWHi|$|;XRj?;xz(BQTB9%7M=Ew6n3LP#<2upTmLjdHB$_5OuDkE3 z@;8P1yeE=a0IhAFQ||&tyjMVhxZ+G^Npi}?=a)Ojl5e1B`4S{H$#bSM2U*X=2f3lbvf;mSlvYdWrDZTnU()~e#vQ*N+Kgs= z&O^BII-z07NJh*6l$>4h+fySA!;3>N=~C9=w0D{=y9F7SJy76Y_Gg1l^_gz`W3U_S zrQgFx@h0j5=jjvNqj)lfQgb#$bb&hmu92ct4P0zLNx+Rr+tB#CUJ3QlNR)*0T3voB z4^!gM$k$_IH=Zgz#(dWtWhr1OXoi?nDGp#j! zXU^_Q9av^wYhFVFfDw;}1d4C?!5I6~JElE^ZwV|)jfszrj?d8+sH$Y{{r;gOk<#W2lxfDYe` zJjc1*M6OL2R9zp?S&V?6kd;2@7!K%J`I_xv4gbuFvVj%1pw8dqtB&Q=Z$Mj8k*=jF zs-&e-MfrhTUs+4`#0_Pu(m|2&pRNrrdOZrQ+A#3TOSQ=FX%Ba~8Nb4-7QfreJOMNK z`uW5pSo343QiVuD`iKwIN$Pt?P?0yNEaGt9Ne*`opG6_Dfqv^eNtVUHbUymG`v<~1 zdJYz8r)Rm~N#*I!ZoHgpxigFNl%u^vbKHdcxYXX19p4YzS=%UEaa&GX60bUe z8j3PrR6De6=4qC9*2ht6ql?6hj9E|eXpDpwYn^yEkR2T>tOKc zVo_V8;>a`IO^T@YvxW9*kV}tI%5T@uUByC^!Eu|xC z>8lTN&;_mgL7$bZ&Y*u)pk1(hC~G(dM~Y*5C*!+On^e8ERH9KND8#T^{YKW{CnoFa zC@j*T)2s-;eBLjn@*ubp6Sbh$6Q}H|<^$#gdhC-H$y&kAdN>|X3)(|E$ zg%#F!kSz8&{116zi%>Wp34aOaiu58C)yXEUn%;`~+?OAHKp#5OwKV_rqXDdn9Mtyj z>_B$lg)o*=Kagy`-I14(^!(1paDA^C4cI$$C$FtFvwK!JpR?hZE`iP8Le52I<_(zk zgQa@tWn$6YhEXe7rL0mp^a6h}N3N3oMb+Y$vXJ=Roqp zk!CPrFAD#Y9?EUi!X~eIkkuPiIi_K3p16r|d*aT=4T|%|4v4)N6CG0-#^712P7m|J zJf54|WeS>dn!Dlmkj=7`bVznz7knJ1{#8| zxUC;SSG$Bv%gO8`#-l=-it_V04iNq5yvviDmX4&AuX1USu$9W+%2H(z*;~J%uA3{D zkYDgB^GOfrL<+%HJB_kv2$@pdQG?9ptK1U2Jo`n_k<>&vQjH9icz)N%(x zSU~#aR(QaV!hJ}Y_!l>WdgKwuge>UC1^Vx(kVcZl3-&(~f;ECd@F+@)QXqlb=qJA6 zj1dHff5()#9p>dO*Ke+)&aTc3@Yd%#202mz)Q=ch#XjWzEl`Gli%f=Zag#Z>GgIyvm&Sd8r6HTl3HD%TC`F4C^j)I1vklPu1=Ou1#>>`p3SCurjIBw0-#He z(S0sM$yZO>Pp7qxw1{`8qvwJl>_LH5Uf6;fs1FIi6*)nNrK>0hZ=v-ZhFb3~clte{ zoUnnxoVNCQ+AjmZ9)10UE153U#cmRs~ZN$el5f`gBOhbhuAjs$;v4~u9B zrzS7VlJDTOk3yI5cv*^KxIg-i0-<>B*|$`vi(o&y&}9rE^(hTr@w3R(zDbW9!p+p_ z?E{Zw02vm8-09qhTvc5%JlZwRcFr8mFOJ2I0*>?ciuQkOm2D4Fwvr`K#&*?q$}Ttu zy1uz5ddvF12Kt7+g)8Y9j5o%5JOJ{s@7l+P={P-IHNAP{5KbU#m;fB1F5&5skNPTM zmz0PPZfa}q= zuf>ii9vUb^)iv5$(_B)i&sa2T0*>rCE$z*<@NT`RRFU6srZXCL&Sfh0s=I@&;W5lW z#hn}MC|w{e)4&$oYDS{z9#2=X2d3dE6xFl1X;nUh)F{cWasLIli(?~W*@F)YC4h<_ z2|hrV{U@HCH^PS^@Ab^&Hp%iBeAAk;ho8V6bi8$ywYBx5rH-W!c>oi%+3Mf;{=~~G z=ps$1S8IWMRYQ}1Lpg}gQa}3Wd*&vV?UrYjua*mzv3w7!&B>>yPnUehSuaT?vUfyBJ`!B?G7$em}h3OJOW>iAd37C%x@EfTX?*U zCv9>S9wD{h0F8<~j?{rk`6nFcJ#-U!(Q5CM+mbmrh1|CWJWKtwirPnJ^lwyw4i<0`Eyg~I4pD%z0r`b=BAp1Cw(9Ev>D`wsF(6f$MDJ6ii^_< zvi)Z08QFHu0F~)LFEkI{rU`cZDLtDplV`IQ)4>C_5?1uF9^pT7KS+Hw{=_$;u6~<@ z>6a*=^MI{?W;axUUmu3M+=dL-Td0M9gTt+pQFIIih!gflRCq3*Q@P;HK$*Zye=@z~ zXV^(UbGgTIqI0|UI5Z^18H8SOUUppLtMh<47<}8PB%17w|H;tmgwfzAMC|N7{vQ=;d(C& z23@kqZIo+jE7N-OMawN~hp1&yQ=@ciZmScY_G_v`zJnj}XE-_2$c~7B=`UtpF6}Ms zZSCFSO<>Cw@~!i?2$SWYDvab$XAA(k%HOnCg0sQ9Qm)~43Yp!E+-+qC{_UgeFn zh+Td+V~D;j@*AAV=~S)x^mdhattIh~pGY>}zrP$EI-&MUVZZ05PLBs6nn==LZ?+xr z#y}ihYJmv12iHzb&h1DvxAWjslrS=bPrnk+lDu3{xyYt=s=5X2ya(xY3S-!lcuV&gPN#6)J?cjH(~?-Ka>eaz;Yf^{nvBqYvGsqAW#mi=6}Ad zFqSiU$ASoMbyss=aJ6;CyN)?4J0CeFfdy{0=eBRKWwiB7nVWnd>DG^%-=8F=Ph9$K zz_%;krYG+F-aM&)${~AZ*9K21|FK|V_zigi7s0jL%R}YX@=YpDE0PDix+h|1Hai*G z4zI}`ZmBn>)-gHMYoXr@M`M=B;GmDw`W;~RkZMsdV7skzxo@&{m zWm4XWHHC^~j9u4f8<&K3Qb8r7mKs;K0#WsuBE^_((fgyCTBn(ZXr+{cVisdNtd4^I z7Ty=`+pZ#Taql}*yXK(V2)lps>|Xm``@aXi2JeM7hdY96OyrE{yjRKkf1ts|L40eo zFV7hsfDYj&lYB;?2d6qIFoemWOL$`>i*Z2cBIQ>;sk==rInCav*U?jAuEeZ~$sY52 zboQwImh9#!+B>C#94qP6ox}8FKlzX*F+u9i%v?`y*6sr z6KtPWsXyfA(tkp8!>Y$cx`rL0Yj7=ElWabdsiZVG^B3WaIF`D6lXUL+%#yE_YvjzP zRwl^zV1#5B%L{Fd>H1+S6&%bN+vM(Y0{zMi z`jtdZ_!zqDG;B0~fE3zs<0whDGXrhYPwYHI$D`qXa0l#g3O)D{{EAi@=Q#Hv)D2;} zYL&FCdQ6JBLAUeZh&YjM`Um*-R98dSW9JZO8Ru1p;HZa3e@e>bD&Z(dIEf1&A-h~8G%B5ssw;7w5y*NWWAQ|`@= z?83&NS`9LHFT%B{b0i7;pe0XX8}`bv%;2L?Ijk1mi+SXAN*-+pIfCmf-SB68Pj+Ai zYaYuR^0SsIXQW3$qFxoA$@btERF?+>MS{6Pqr;+p%)sqQuBTqq(woy*c3Ey%7Fq;L zwE4EyisZxG(p(|lc*9g=K|g$kMCXO!QIYlf4LDQNq~~(9S_*E>XH#GEY4dyYb@MRu zH&by_AJVioDG%slo5IPf2eV)kd%KOCA2T}nh&TYJjbXA){zLf(<#a=JoVs598!Wsa z%7k=EJ9(ls0Y9=;#(w=J8P+G!4i|Pxu)A#guTLDOkg2`zwr=6QmF{C;#$0UZJBrH`%gxah-F990eUy?VqX3gGqIp zo}4E6YSN;lKa;X0UHLKSN7^6jzi0k_Ht|K`AKyLSb0xWwtK03)3!WAJ#i5zHD#pmy z6&bFPu03T7F_skR)^e1z2d2gY?hO^zV_k#JOsb^THP4PBKO*&yyJ#p}Xwo+k*~P_1|JAdox&?l6vZjv zzu&kmp2DQd1)e`m*f0Ftom>$Pz(Xh?e8C-}DO{5SIH#0jhw~}&6c2(cVA!uC{zw+i za9ifhNo*%Kz!H0|%VY?2VOrI|G+yGJy@O|{Ciu)UP?&z89%p&R?y)aOp?hh_9a`1We+}QyIi}lX;4Y)t)65_vU8m1D2ZQdV?jW@|0ls7^ zxK;ns(^&Mic;u}L$K#V67a9?KAL!0bxxW91udwfs_kZ3U>|~C)i;`Mcn$$uKOfSK) z9t3Y9)8LDgHYs0|mnYXrUXt|SNAn+hzCTFJn0Wu2^IQMKW#1boO-dQ$c;W8ie;KN3 ztd~Zq<4i8I3vO^Sn}%nmA*f9rNo~Z_MsxQ3Ps8r;q{w0YrBF*Qt$ndviP;=qC|$dR zT$vNIZ2WE7Z!NO;Gww;hGIb!vZ+>)7fk(TWnT`*)_w{**`2aPoFN9P{wFI z%`YwJjiTISvR<>Cz~{BM){yygj{I2~Ks7Pg42ygk9oYi^0}}g2iUE=9O{#T*vO-Cx zu2c(vZbX43S0LMKE9{pN42{YITr4N6)0L_8@%6+Q{WMs;-hR}HsEKw$=?(1Lk2V^>3#dq zs`m7(cPrHDRnC`=ijL#ETDB00n|V_HN$#2~Cbvv_@?*=7DL?l8SeTSAC1lIv ztnc~ZuMwVVoR$u-&}eGO40fDs`Dk8Z3R3-sNgsLQ-oh>X5-9>xwV_a2dZ^4XO|eGD z&W&G_wp@lkGVaY3mAONv2MJBn-%Y(a)^1VMlEV7XcHdyP!!gHR-|n=Jb6#=p_r-Wb7>&2BDX9T$}nwTA9Fm${XyNQ3n+!Lh#KZq3=uKG(L~*4b`2>bZkndmuhiPADSZ zR%P>g%SLPQs1i{-t%oeV%ofvTwK`EvnW>Xyn9oK+N}+eb?;BvDXjz#{)n$oBX(dL*(jC;Wt#~X{}y|V7`oA6k@BEX zC2@7`02kvV+d41RH%3p3S8HXxKj$hnPC40d6`TxLDp^`8mm|r&0vX>A)Nks4OlvjO zTOfIR#feFB5THc%S>(FBFVyk93A{ z8Y}pPkK!SzIc}T4+MKJ?uJevg>^pQt1ZghPP1zZiP>UC*uw40+o6UOL!*EYoAalR`*Uu z(HKIzXAX&EG^Buw3EsSrlaRZ2-U!2aI)|0DGrNSl=s?f z%fjdfai>$KOZOtZoKQYtOoq7hPtxp5^&tAN8NVFib*R06s;7m^>p1TC%X!t6?AhY~ zC-hwRi%Ci^QwErwsM9i;+d1JM1wc$f9V;k1V|LEfcYR*z^?Of^u()Q0Wc z*^<|C2iD43QsR16=SOOa)CUvW5H{w-GJ_HE2Q%_e6?wN+fnt^{F|^kXx3 zg;Sg#pRZ^5Unz8?*QIW-Os;^p)zh3>JJVFtEV9FsaS)n`E_k!NUD_<3XA-Dx9M!wQ zT^a|MqX|yeJ3;F*Q$=gwUic7C&$ajtzTs&cC7u*Q-0ibLjfa!7?GKBfBc~&^Nsu{d zOcxq4kIj&L{J9>u!fE(}g>mkhK|huSZFeC(2u4&^UkL8Gh^OU=&`taxwv%=;|6Rb1 zt)BE2-t1!GF53T2JXvKT-$+FI8qOT)jW%$M9&Ic)GQru4(D4#V#{{`sTbK6JYWo%LeFRD)^(t_m_#@#J%5t zPqL+CbKde44@UI-@(8W7WolH#=+#jZtu}Li?Xo-t#c3M-0Xy18&C=n52x0*4mbWrbfySp-1FPV3>EQYYn+gyKPzQs~jI(Tf7$oc_J-@ z|H&8B2d2svyCoAn#$AwN8;Kv?q`^#YAJN*s!^5f$d;8YnIQfXW)6~Xt$NDvDO!T4X zU3gLqk7{SFX31pUsU@geb^5Lpg)v{iS_lyd_D}$c7sFNnk;!O{9SF6r5y_yaeyLQR+}S;)(RrCOMZ>4i|uL z_<)VT-{_9fn$6xRaiP>nuB>EMo$5}lw&{zh3wqw!=1ykKJjwJQ=@wB6)E5zDGrU1b+CK&Uq)bI2P~D zvH0vw5#QqbI|N=*8#X-aa182&hrn*U3%lbqJ=@5FQ))a@>tXSnxE%h-caZfc5SHfP zjUP#ixJ?Fz1@yfZOsd|nNv2V~hw|%I{FkhTACBw=eW;!aJh*P;JW9m#p*(n6JOYh+ zi+1cKOw~VqU%Z>W8@vO(ChsLUPHFHe>Ftg~`Lcv6y^S33x^|nbr|nounG`u?e{xDv zhop{4)01pTVQH47y`Q#5+P-NTrJk6odhCm+hLz-gbjJyjb1Ty;X z`I@0_OA0m8X9$`+ldO_vmg?38bGf=$x$hW)0$eHN^AzFHX~GJTaSc3cpZGbHZOLj6Y!|{0B3E+2!QCSA|WQ zz#jgmMmNOo9>)!l8cc%JAzmFQ{Z~#AS?1tAm6;4@m=ER8p1ucz-T3yvx zz%H{f^Qo1uR}RMCZDvCW=8A!SAc;+5qez;_1NxzpcnU;dFZ|p~v8+)svNY76 z)ZFKR_rc}i!+N6dK{}@l(vF(OP@(RcI%y@8OJaB9K{#*lxNo1QhWn%|i@TU-vv;ch zYj8=Vp>RRkq#RPCaMWzCwo@X~pW<#Ko9;kU@iFu;B*E(05-AEURzNPT8rmvzZfjrk zk-tS>Wnz42S!Etzs;b$Q-SSbAwr-0D=#}v@MZj%Dvqo=CF3R4_~B@%pSsUvUP8+B3FlQ;m80c|0c~ z=uDeip-#eK@aF{8501wWG$!AqJh*b+l5;8@Q4ya( z3Hg;DAL+mkvuW=E_H_?dQ91cKdWzF*{m!#@e1)!Z4C=st_&erPBUg#3n0+UJOVpBH z;Aj63=H40h7A9PeA92cR!2vCSt7rw>on2x9IMQ9{wcfx4$;D}#AXJ6j`i)a4!on_! zKYCrzp`3WZCZLOyU}b-U+vUIo`XwGj<6zoUBP}H}n!|$ldzLg>Q1Lq(?Ks&>IO*}s zedoB5GPCQw)}+c88>7Y?Kk z)bY>vNxoy=b>7+DvEHTLYdA1`@?Ik4q=MJ!x!`H$ne9H|O7EKKeBg+6^tNBHrM9h1 z=?dTaVe;(coyotYd`uZ;k8`;_dpXa8jW<$ywVC#eRERW6q8KftL{^7#!;o4O%oLud zFBE$y&$Jen`%zzFYQ?$Y%A`s~4${cD5pl_}J7fNg9zf!5jAflEwI(S4h+&j0=g_uy zW=~cyGFI;|Op+4VYyFS8znJMCZJv5xo-6*)_k>>uAN#+6reB~#YVCP|>q5g|rSL@Z z&U;F8<*>X--X@I`TMKE7t&wUtxR4$n%tuTkWFm12@ej=liwQ=w?jR z7oxr?6kbi1eJb?HQ(#`#pkG|gesQ!I&Dn{Q=940K5hcUfh>z`s#xAcn-qNQd$8nL{ zi{s}QDIc5V>ue#Kf@EcYeRUOI^Urv>$CKBPn&+wsHddSE>~NrVaYrO7kKl6lL(g_i z9uI=6z}Z?OEn#OdfZfMP^b4h=6tLiFuuhAMIr!O5TqHgKsrV@VhjV`q{OHf&>KcU} z_8BKIHG8{JY$J92na6`@EW$^&8hG#{o`b?{irN^(e%0QQ=m=t&-7ZtP3yLOjKXu%1 zEQ9U;n!dUN7;R^GplK$G1@6CHs#0R`}NW zPWo>69>I#fgAy}`Z-+OFcbez1JJ#LMb%2fGNz{y2;NTUp-(?3r6F0++DFdj`3sOQU zP3^0kRXnNubwVH*(ii!f@)QokO>rbXmS~DmCrI$s8t6mBXmzf+PSl?<8RLFB_6>-; z80%uMwghE=x9E>in_!O)fK7eV@{hTgskwTRdppQxzYg6~QK5i1Q_9S?<`2|SrQzA# zQM)Tkq;W!ho$e`ED)0fPiIHgX6JTllFMKgl%s9pVqZe+hL9mN-!fob?e{nEvPddy% z)J!A7O(LarEAE)J#qH8-IR+){1XC^Z4RdO^++)rAO-Y(r%L?-?1}x(#bJ}HPJSi?m zv<{{hAPPyQmrP<$ack(Pu2(?UBq%E-Zy}J%?Cprh~MW_ zPU2r6vl4SySz#oJMFsRrd@{R0ev)7eo_Oq28R z|Bpr^XaSXZg$65tkF3Om_lcd!P!w_bade)}$dp{>ByvhXZy!##Q*9@G((-I_RE zh{qLRG!?uVr|>iA{6(RecvH+uB)Q@JM5+IQl2cQG9Bg zjXVxD52g-G^$*~lO{4b~14?`IeQVd~7cpmI*TufagUSRQ^ECad+7qH-a6zCOI`ucg|`cU3TzHT`B1ObfN4>Ld9xi1wjK{&0iPTsYu^ z1G@sPf_2%&U5%XNjy#3}qbxq?X$)^?i?T(Y6fP6FAIZ+HDTaE` zRQy}=%Y{@`+fLPQYx<VgMoG7q@^g6Fi=e1^P zP(BZTrv+GFL)@(Ii33sRO=IJz!lo)9<`U}TD;$TT+XlMgd3sZxp59D89bwP?FuEBV z;ornX7UBH6lZ2>yk)dcx6g2l8P=%EeH{#!3!dMHtXiOv@e7QrB8Tt&Eatp-%+!6QW zj>B{VAluoyMp6KYo>w-ncp(P))qSxyvi;HHsQn!J%8CgBj0rm4e!9 z4UQ)b*hp@t-`&L=+8CDjFs8Y7`U^O7MNn|&W_x%g(unD8fZ@VTU^-v_DQujJFp@ff zCc8+->S0du1-6pu za77p#&Kf=xDo$Qq1{CGF0*C!|{6BoN@W#u4v%`Hlj-Y3K{T+0xkW6 zd~JN={E5N8^nOxjEo_+{{UzpT?CIEG%)V%+b)@B>d5O6iTjPOIt)tV${2P-HyCtS) z^a1N4^8lQ7o;Px=fS?7h-J+htln=3Q!YdhqP?N&&g1IEdZFTlBPlz`-8QteG9J z)2(_7aJR+0_eWuZZj4+-cYK^=u+4!_fw^#@CxKj62|o(AK!-XZGWF*Z4s!U9NaBpr znf%#7S_kczIzsVDE5yw>Otcc<6NypsVP(D6!o1Hip5*rm*2$JZ=1it(>OJ;ufAO9t za98)0TF52PX}wp|YWwLun#qaca(ci2*hl2jC-a1r6mpW+l!w}Vh^<8jp@ESXZTl#8 z%;jO&wxK#_F>(sgXgU(vMOF|83w?|M`t-;?x|V#fo2Stiy*IMpYM++VT9#?=gWQK5 zP&ayr{W!QT7OzpY-_czafTir@wbVv6mcVPN0CF-|{vW;iF}5%h*=DRHD`ys23|Zh# zoC7CYh?D+!5*W9Fi3s?N|ID4p3M1qde9_`KDi;KuTaLT;UsUA=%yv^qF0xTi<4F3+ zz`6XNkRIH9F}<-wde(W8?HYlv|3uh_gGxWu%`k~JbD~R9ktfn~j|bNriaVki^m;5i z#=*umdhC{DQ+0q(S&iOkB(LB-TL@ zbBSbr+=W5<4!%t_oC2<*x2lfLyteP6w~}{{CzEFa39F4lfom|HOoW70&gw|+HG#967P>4C`(EBad0tLTw24`RmSqcq8S-t5pis3n!1 z?DXp@3F=Von&}=+0zq>Pvm3qm8@ZSCfn=cXJh2bps*YfT`-&Uu3-8x=ri%2&J~-l| z!6Sd?$#s#&(=E6X%(oBeWAV6NbiqCC9G=oKk-a2OhK!M-U#g{OC`QVt^Oec)h&Bon z;6JU@8-rlvm%Q?O^)?)$OxE7k?ADrK-IFy#StFN|YO&wDMD}hDkmFfOZ#Ad336Bqy%acXFS@8!H;8{8YWMy}}(;pN7VLSaK?*qUkU45#FXVS+Q!Ni@TT zu1lUNzfd`b21Zabs-@IA{4}WBFcQafS?p5zlKAgZe zl5JQT--KTD9li0h6?~0wi7Ml{?j8WPp}VfS7T|Mca;=3&y4z9Mv5#%xW}7pmOG+ep zMRJSeKFQCLZ7FZOrVaa0^XA9HsWCeyB`aEba6ZzST>vyU909pnS8!W*Eoeh=o# zG;}oE*kr8cp9e!}$Ofnmm$5lL>uTcobXWhSoMHBre_gkRsEG>tl-D9g0ZsAg~DoZC>%h6BkF7z_MKQG@NLH+TYPNCZ1u0N&OO)a3d9>W{=l{1inM@!xia6|PgdJ8(oi1p zzZ;k%BmBKN>Eq_pC$ylJ+#^+R1FzvTCvqgGbP6tYT|gsVklc`-z4b1phP>4D&PNVd>6yO?m~ReTZQkSELnds>Lzm^Y$SJOB3;lQd{4i@x7|ZUZ;e_Z6C377 zJQqhn<$qASUgIk>44mW?d&Z4yX=*bSc172+70(N6@D5yqVu1^|na%aNNrlbsJ@09c zTk&>xPcZ1Uu8gip&Zmx&j=eZ0glrpag>8>hj;G8{`6HzTGvRNx9`>=$6n8b>n84;x zHE#Yvk@DdI!S4Rv-VvUYp55LB{^23fI3t<0%jUgkX%|@cTNavYm_+S&Tnq}5GymFr z$(k?P6!TY1yO{gY{iAMKs+(JB+vsDbGt*R7qSQ|C`KOu-S!!7>nva<}Xm!<6N{~Bq z7FmK9VV`e7H54r@Gs+kr$h7(k=c#Ns0k44DJ}43eOW#iJMPX8XvN91iATM-B$c(GY zAvCg6*g+rG*Bi5iLgF|y%{`dnm$CWV&fPkVOuLRE`%SqH&s1J!z)>dAlpAb45d@(n zshQ8k)L>{0^Z0m3cJ{a2xPQIhhSRl2}+DoL1H{82$I2fPP4m94}MV}{NfmU{ULN7=jl5d zfwxSg`o_>_*8`L4$`tq%Kj>HRO{>!*3`3*XkL`X_^pA0HiE{J2t_E{13W9fyw9(pV zw1$JF3}m|KiAU2AVHsVtjSj6TwQ2~nNqRovKlxi%(Ya(~CzuhmuOLjn;%q5DQMHQ0 z7mtoifj>F}XPdL!%B6#!$dnj@N8e)H0Jh+6aMIhz`_a=EU;GX3dhYkGiLOkpUCxG1 zyJHQ`x%cgZNp84_BFmL>0lnd_l*YE(_8ZPuFeVxVeh>W}F3;}tRVY_*DxI{%zGk?8 zMzB+4r0_&Gw2_vZWc^OIiq>o9HKvnV4K@YIS}Su}>$Ipv(d9|jXdSbV&78$L3YW$y zD8HX5DjovGw5q1x%yE_zmPO=_q&Al{wa_xFVdkO2(im>yEPUtRc;+YY?sR5CNs9_8 z0hL-Ec1cUA()-A_se!NMX0)?k!me;e7>^UsV{XKQ=0v2B?$dSSl`xe&#`gFq{f@$9 zKghoC7do~=S|+bjrmFR|uP6hHna;33sRUy)zj8y~4JSE0O!rvzB0l09U>81y|1nB? zq-v@mf5MO9cd{4Hq1fw4uKK@l#IMr@FMyZST-pWqt()+Pn|CJZK-uBFeH4nq&m7Nf zuY;d$1KAMR{$!10jP!xCeMp~TbOWPZ%~tLnzFalMC&FLkVx|T4?TLP6Dn0g1(D9>W zvU$ktn}_Gv3$n{5b3TW_$BRXy`T}Ho2))Q+Wfm1Yzw!mQkhz@dF=z!>kkYo3e?P^K z?Ql5<<6T?>t)vK!JrQig1(U8G%96cw54FLZbJIZ=WM<68&wNyYSlEeg=?^x7f>dLp za)*BU4^qbBQI<&bBK67F`HlkjI337#nBk33G;rvu6kaTS(5g%#%(H(elYtc`Y8yT@L7jrCYm7yR=6jy6aC8CBn!Y~H|jW;V%>dDLa3%RJ+EtueR3 z!Lgm?Z#I$Zw282Arpm{ewl;BJ9UwbvF+IaKZsZO^e&Ga+^Rb-hFW{E5Il+1119-z} z;R@x5yg>;*fZHky4nLKdFCQ^^t<+B$%Y{nh=e>m4IO!LMyfRg@DXiTa;zQ|{yqYb_ z7qyI*8LsG4@`l&q7~_#d6305o&*Ywpp$t?vssFHJsjMC&6C^Bs4R5d%gZxcGVDY!xCsHxu=*Ag8oD-1RqPEd9;iuxmtN!ad1TSPunL zbvQg_VO8#D7q^c5uLM$XR)Rfjr+euRE;xhPascndO&k}NabC)TR{TsO+l#VbGOWSk zau+IdYhLj+dW-Z@GLzT`(7Pt+Ub4U(*~Sxhj}tuyJ(nFOU1dbN(Kjvtr47a-*yo14ncXIMrSu51wNi`MW!#&{`!F`UmInrVqTAz+&S}7T;!UYW@-;quaXI^(>-`F zcR(Gc@rjlrMe%2npPkLX5IVe7_!EAkvo`6=NTW{09rA$Nd^9_oR(PHaV_$d;r|nyj zIeJUp%Qr$#Twm^>py)^yY%8Q=3M-1Pu8a6P+ETxK3J1p(a7a6;snpHXxtH=0Dq0_T zK6NpZ(uKs)yZA0`RmLkhlv%tkJP^U5BB=6);*`1=*2ha&YdMw2Y^)ne?ZrOyOLpqn z&m_=z<0n6UHP28C%%{Ut!L?Mob}+ieqcR-=2AC9SK|flUy8aknm#45Yw^G>}80FzP zOya*a07q`f2~I6_l7GuY_>@$g+jPfUndrx`FDwsB zBOmP$_kb?=a0{wMYp$*xbwRxsK(^rpyUlq|$ z!q!fuZvyGO00x#A8WfUoimXa@Wb43Z|4=lvi||8FL5MRO<9 zcJdeAsbRH+b_1npPLia)nce0q<_0A9Y|_q>Dk&+wm>6%tS6t3#u#Nk+Ec)dwDCp0y zX*&nQ;5yx1m>#<(Xl7Bgm>pnvE~E1}#XfZ(SzBB1Ijj#h)Pat5DLlqjY=n!li5<(S zHq$TGriYk@pTS`E*I{KT9MA9SVYY?uIHP^#cknyYQu+L1KGH80PPzi?VxBTnsRL&z zx4fAw?z{92d)Xv6#5L(HJCJv%0r@v_@oa3&DzZlzOj>&bFkZh^@N7A5$yvSXyqoUppN25C4_O)R?T*bHGsWFsIaznb&UYv&z&&OoY z-4jd?WwqXPTyIKjke`wv8Q9$W5O_=LH@ z-Tvd%-9ptR(+@ZO)p3R497?$3C3C|6=DF<4?;a116JZ~7Q7A#3vWW$ms*7{Fw~{n} zg*zb=lf)IChim+)82YZ?_%EvPjH=(xh#_~XDXPD}(FfmxyL1+>z+-4=cL%Zs4zPVG z;t%75cnxQkw!gBnih4JCeE54Ta~aN2Xv32ocO91;*HJs!9YIHm7ut7IBb*)I zn9`Y|ng34W(DPo|tG>}Ln%2T)o?%U~o&raEYWajeWC|{M$KdK5RXc0hOt($b%;5|U%L%` za2Y1G_Oc|;VL#W79&hCd{PgILB%BqCl+yZd=u; zz)mJ3s*|_+E6&Y%FwU@E5@g`6QHXwKHXYe3HgX{$JN?7o;27zc0Y}2;n8J@CY?B5` zi^$kK#T@w+JS2#xT>-l3PSo-H+)pCC)D3>!9yQ<_5XnjOE`4|+=c7_t$v?-jWv|K1 z{(+M>kR6R#e9rrJkniGeZnpI_<@MHO4!^^6+?+XaD#%GQ zX5T01XU4$v7{YXYkN3YR^Zymp#%aJ5UDTDCR2L_m^)P1AGJM~ScoJrFqW9Cu_obV= z0lxS7mo9vHxEA`#OZ3+r@c7t+NA+!dl|T9?`g8hU`8F`?CHQW5yLrEmYWLaQ87<-_ z7^hWTS?EiOxT?Eyy6n#L&S6g7F&!6#)Aq*pPIikU%2~yA&;86R1?~k^+%i4kx?yYR zE8gRGaOtiJqpnSe95^rV02O`Fr(J)jOA#1}CgTinw4A$G!zs}-!C zMQpU(q}AkLvb#j)Yb>8tTQNTl$|L1BvIT!eTv@0pOGOzi^fbE8GjM!vqw+Ju84~bl zX{D6pca4+3@O)ii%KOfKL8YFW=?vP^6Z}spO>~JDA-<#Zu-J@-H5#VV4jj>^G2_mocApe4uroSNcfW~FyeZik$2hqz&ff35 zG7orOexpA;yl5tl3GB$X;dtDEn)?=&cuO|vF?2Ao@I(63TX@K~T~6J8O>cOWN-&sD z;3?g7YkHPa+`xap44Dl!z8wFDra0Ja0pI&Tf878 zTbUw(5B{xq#&z`<^~?VIxC4}XSk=RNAY}fUvuwuuX3+&uf*}A5IGRr zUEN(3Tz}xzUd^4?)7$&T*C}uyc$t0lDYhON!c{`;gMSB_;2Kgg*f?}Ayg_dvoDjXz z4zT}k@=4sN>QZm(QXjIC!rl;GWjd`AF1SB4Z*!{qar7y#R8!_Cc4Y>tx+v3mQ-1L4 zjd*emH2*L)GHqnD-9o*>Il01VTSfMIZe^Hq8ue&dHV^Ua)-ouALLY8hANky19N=y9I2S+ABjo1y{|`hsPJGN+Y0F9aLbZHjSgDC8!CuzE zVai9{txPX|m1n9X-@{KQ#|QlB7}(6q>8SHcy?F(X>0}~Q^`8#BQMB-`pE9QK29D%bdITbzsKVI>muVbvzQI^%8!fWVJh=z z`mUc|PRqc*w}Er~L~G~&LhuI){dgxw{Mtf}+a@m>F(v;;ZE=zA_1!#04b}N~LI= zdFRQcxeb?tsJ?-N8AS^35_O=K8%NM&b~GpGd+zXc!XIj zBY4v_&TRoYi5YlHW(FlEkpM={Q4(T(b>) zQsd|`3JVIGj5AczSgP=87^TbDjTfL2mZCN%kyF1Cwo5gpvBvyui z`H2qoBxr&YM~>c9b1w?*Rrn`;5*=`Co^VP>f}jMb>t~t0FYw(3>0)X!Nl)aJtrPdb z;(Nu`Cz?}Th#!Si7)2$*M516z80`z}aRY z)%_?P|9Sq@3ZA5n^l$&;>HEpZuECwPfOq`|2u^XfTorl7qu^Z~<7{-`E2!kc-@)B% z8y)>(18)f|bl=tO%SIr<#^IUWD^YPY>A-K=kN{Ik~^D(ChDK98ye^?*gmY{MEBhvnbj{Qt|m%Ir}y1qqO~sY zG~P<+0m^d#-S#&1O$)MZLYF4-PUD1|h;eU#|CAdY`z>{+eX&Aq!S0)*vx|XH$kC_* zmQaWJH3A*@9+>Yku5}}0yN#<@fmZ(s|8)`C{|#cy$I*#*;_>##)`zRQm%pB29#7)l zmN195;qm52LT^YINPWsvbkrD2r@U^=!ZO@zjs%$KNbc)&HY*K}WH3Jb19UFE96R+i zacsea%wRuyF{*p8R&A(2>&NGf&>8!g(KDFE3z%D336-%1L&+gL1n;jFG3r93zXewA z2(>$VxcBT>p;q)(?TrQ~h8=wa=IRc7_`GBshtZMyEZFX3D$sh-@h~ClN7jn(KsTn1 z_}n+peQZzqXX*FT4K+P&E$b*eMrXNtX$ff?Q>UihPdD;Bsk_gAg$94<{H^C3oi9Sx zeQ(M<)@-~n<;s+^BpIhvi^J~Yu_!Rg5kZa>=$k&gLIG{0JGsbw8dL^o2PIbU-2TD;u6Gi?;~fu z6E`IG1Em@a+qDiAP+!AsE}G*CFqFnrnckh_o*ez@>DwvC^&pD1sfyhT>v>u7XUU_J z2eSHSD|C7PZHXTYi(w#YBF- zh2L;JjEQyB+w})a+li-nH&@jX%~K9`UtUxf(Et?nN@S>raCz^dJje33*R~SN9M7#0p_` zu0-mqApZqHMrC=dN2f2u%FhC2p2d-Vg6Z)$K2CPNmB2pv$e@(WR-32NABNHdX6Op; zP``aSnshGP9Ij?9G0GWu*seWrnvBsNSf{Q(u#{S_lg!E@+|5bw570E(=4M!>mYf^W* za0aw|5T5owptzsG!XHGhof4VHSMxTtbbk={5n$SY&d()PsO{Q1mt*qdD1#6>h zWIc(yS-~j>{eEYiAA9~mdfL`GpZ)xn0C{dkuhLTF-wwbu{t(HlpO~C@2)UbtWod%nm=Ct} zNj&tu_~3`K{mIk)o$WYJss_HzNILFs24~3zlldYZ{J&(U|Hc!^L2u!H#B7_1*IL3c zdKYYbA*_xmbfCL0sZCPBq@6HNUc*=KK$Mr6aEO}QO;n^VCj;|s!cwgI=Ul;~1?6OAq< z|M4cQ>6h?rCV<6#L%ezx#%??EMx&XH^T2HMRhA*cOQ?BYPc*uR*>-~YrZnefEb8IG zbmyAxz!T}n=+wd2sKl!*RkT;2b1NhiW#%7YrhbQ=`y2%58?3^9j!=+wxh_XTUtkPZ zp$ncPgWMk6wLC~-0@3o>fP?=CLNW?@3vhGAm_m%9)gEFt!(+FV0HlKc|*X8$?&?M2_=d`ulL4Po$Tj zuUYSmhco80%wKnU{$wLJwT_zoc^9$~-9L#Jn02ut(eqF4Z8$=8zQTSCvLlga6Dqzl2|KgSwfzY~4_jE0^?K4mN%lmYBlA~`o} zc^#s!^UCb=vcC_y_%Up%r?TIby&Kh4h3OGD6HY}5Fy^^n;q{Q(Ga%17=s?i~Ejl3a z3GlA_$+BOGr?L_6xHnJd3>s!L&-e?ZX$DW{E1uGqJn!ZBB%66MXR$Js@Ky$4xu;P7 zw*)WhtAuIv(s-8bMPkTBc$DR^$>X@UlXxKc@pB3!T>yDm&g^*^e*ZnpvQ-|)Q(ppkom0zS*VzDgGNK|H5=FmDc_Ju&uN_f2UcCYpDM7l3oBuxK1EN3 zeqen4sOjwnDpKh}R@SfhAiY_+bQ4_#uZ7{ZG-E9NPs`Amb_25f3DWmk`Y?R$4s@z5 zPbab+$n)#0A8{N0NM0gKJJ)_l&;1_w+-Jy^k0GjTeZD4a?b0A9cbxy2wIJ_EU7T8! z?kzv3UCxo-P5&wVaC**+I?S2p=$W?x&!Y-?>?N7Sk?G}Gjo{rSf#%FZqOSolo{IOk z4Zov0arr}JRri5^4MvCl2xF%lxZp?BZ8xAo`bhTcS(|uq@*m0jU^)Ln|MB~i>%+eM zgSx%xFf>0RV%$sx-`VVtKa!J^vtZJ%fNwtt^dud2$LypDXvJIM`_zZQb_AqrJYK*x z_!k-EnfDS^?I2!SOm5`^o=smgPYJa0X=dAxNYXT;u7$@5P&a13k8j zOiNLsq5Be^$I^U&2RR3+6cJmBe4fP*ZGo5h27Igwv_ZBnV}++b(Y`Cu zw~xZ2YYbcH0J1s*mc~2q!hXJRnErq@K*MhYYrBCAQ4O&2LfG>xWH|?XBD0wfk-2}D zoXL8Qb&}jwA+%-#V&}fx?USJ7uV5EgwG&AkNKU;Umh~>qKNcBZfi5o2vm3&wy#<0k z1@G~Vgy*OY>y7QY7C)pua^Dp1tqrrj6X-UB zQhqqKDSItUOJjY(*YPfjWi-y{mN6RNW?#lXth`+X2J{o;&h};I!>j)uHtrDEqh~L4 zV>O91)=e2ejItG8PaCoveG^_HFOnC`YjEQKc*1>P0tB7@_tWu{Ffa=U|hQy+_d7K#3d z2y_UNP!U_b3mMQ-kH=DXhWA#04wsuQEFo(@2ju=!BwfUBqH$@LDsG(H#mwM_{T`t5?C7FViD%>*ZWBS+hEF*@yi$D zrxa1>d7vMpe48|4pyuMN~u$ryF_O^jhh;S-)x?EY=68Kd+OPn~eL0)U~NUvbyx@ z)MKgDS!LtHw9{!F_{P!nIvIDu1zms?7h{!x_ViP~kNWj7nG-nIqRc;8k>Or)*!i&< zlP>&up$WOCAE;)ljgFg%FPevFq9f7oES_5qkdJ5ZY)jDn=skJ}Rm=V`KEn^$cOlLB zl8b?I9Hy7c;^0k;LVh2hlld?tw{P~2^b@=;dp&p><=Lw7TQktYy4mZ18Ww>6u!wAT zFS-h35qHj}PGofAqvSz`f-w)nW4;~auQz#$>Qwd}C(AMiPvK_pwS25{xfO3?2HNC# zG}QxvPx&an{}0XdH+s1>dU+DM^INc*J;?FjFgyQcJ*(_s0#%U5R`dlM!aYqU-?0QV zWihYW$m?`$(7U{*@X17U_ayMliOi|TxvppMyB-IJ8OHV)Gw*hEc5QIS1hn=FFuF(Z zV5_60Hw7Q$ZqV~0*^ZFOo`r-xPnNzPS&X(wV+~kRxygO#bDSr7IZkHk82Na&V`#kX z^zm4I;XBq5_!4&2Ml^Z)g#vu5E%Df+RL;J@lX?c-eH-3vOSqvm$kW!xA81A9vn{!j z=DcgY%y4)fZ=q!)*>c0=`gG|nv2aD@`RymlWgJ2)cCEJ^H zu`=_01X-v}%;Z*Buj$B2CfTpn*rpLk#XM@3{sO&h4My|{8IQAxCCS!21yAQ!dXnb@ zd2UOOtb1Ts4nga7rp}`xSoGGUWkgw@CQXHtwg_I&4)TH9*|xz+`Xy-|tk6g4Ep#(% zo+6-U-*e;_(aFsc%d!$lb`aQOcpB>hPCOI8cPf7KIIgA_S5=M3JsSwqYP@H&>0RjQ zQW2eV8Aw7syuydE`YVX>j}k5A0huU8R8)p2zai*XGmzO{c)<_B5gNnnm;eSg4p!V_ zARjLT{BSzH%@XeTClKAw@lxJmzxx@9c39`eM4H9HR1#r&oFnr5gKJoT&+|Um##7jb zPFzVPwA^VV=M&_jAI#7ytgg77k)8ybY9PAfS~_{Pg)etI%;zV-ci+HTze?@d{d8?= z&dRd6;E$fA|5;Af>#Bl(dMjL-M=w0XHio_6VDhae`0aWAevDj2BykD%;%r zEC)xg3%rC!IQF~9-(t8cKVMjjUDynB?^pbTC9v9OT$svANFU()jE7@Bnct@18^6X8 z@8OJHkk@+f&&#q-LqX~gPEv=k9WVI@vcMm~>v^4S>|?0TdzNVMS-QjD&w5h*S^1!C zRs*Ud3&T!d!^%BR!sBb4S)LU$GBaql%j+ys`6nx$Z=pNcVpbY>FXLsRx!YL%q!n`A zIJ_FdBk7RQk1l0zpo{4|M3w(b%!~7xmFX!mnhNPvbizE#_~hpLTEXagh_PJ;JEs+V zmc?LBm&0`!OjIxpjkgO7G6h>*4GVfF^>fpZs8jUWz8H+4_DtS6ne=zkaef}A=3sTwa`=_sBHL48@=OMadxgFM!@=fy zfyXt(!lx61{Z41E4cPx<^cu*OR1CIgSt7&)DgjsF>5PQaQ%@8Q^O^z%H5)&73Ha(<;=rZc#ac2EDO6@(i^hKdT{}K#;#c^+ z9U41(qPdSB(6j3kj=~QunOK$hvo4<$gCTMNAAUM={|Nr){mg}DiL_$P$TQ%@?a|7G z$;TXI4y_G{^Ve985AoYZrDKEad0nsp;1~R z`>oKgoyff3j-`Jb9sCUX_(3$~AXbVSg=hdGWvjg#a1+v@cVWn(DTGvs1w2i3p zJo+g=)pf9hZOeDz>CSnXT@MXHODvZ$dxoB zd!7@{&RUoa?=Wv3hP^YK{^_qF_w&fItfrdg5Zo6v_P2OPFY)OeR9`fuGPe#h>N4g) z3Y|dcb&S^j8X269E`1qk92t5--H~-Ges(+LzcsqNISl1mtYK9hE_)e%Hsdqb<5-H` zZ@~O|3oEsgn7IJgou9i&L_;KE;fk;pSUX1O6L1Xs%C*I_coBc^JFtR_*(#Ftx($?T zB5}@q8~<}V^&cA&xANOjwv%KvE>fd+g!g74TaRG>TOvQz=vZVHs{>b;>Ndhdv1gdJ}$UMaKRV zaz{^NWMDVH9iVU58BmTK)R3i66@Gwsx6zw^AysA{V$q*Pe)_|UX^pO}jh?JVCZjD@ zo=RYJ?k8ybxoFsT(bcXN-U!=Y3_W@o+PN^lm4h$d5Y66+&w9|!pbr}NW`1wS@miqE z8_{j140-LmVdcg&`raKy`>w+a{*;wPo?dFGFx*&8zVa+I=2x+`*gMdi`ytczLsuv;zB#P?u7CK65m z!fZ;wYpc!pJ_ZZrb9}0`pr2`QTdsr^Fpx-j9=gTsTQ<7176cKiLd<(L*8LWq?+2i- zyO8aIcmp+&xB5s;6YznKNX#I7-gn5hEd?e1p8VU-paoNrzQ@t%_t3GZ6Y|vs#CHT< z=s4IJQ~2~vJkjC!uXpn8fyA1RaEyuI2ygM}XKbJF|7&nb$FkoDq<8??%I+Mc12W&3 zvsWUYo{66Rm3V9hk~yB({R4iRj&^>NzeMF8!Gpeoh_)AaRS#Zn-N?suARksAjan9+ zTA0jC89a#M{FWd5?HqB#Msm_$k(n8T&AJI6xF%jqQR1frG7M?tJpQ`4@8VXn?+d`> z-lAeqZ}wSa_aU_C?O+vM(6!frXVkq|l{&t%=*c8lPDha09q7=_tWC2O={-oqav0C~ z82|4>+x?C_|BBvQK}7f^U1r{Z6F3f!VI2Rzgg^2o@6AFN{=}>}K+nZA^l$<6b3XKF zc6{-4BKp5L#*ch|7P01Retv;=U5dA{jtFiI$6f|*{0T=MO{Lec3q$F2@I1bT{RXEn zH(m+8Mt7vXC0iS2Ll3;8&dh_`s1)mmhtz=xureM|}qV$7@>e0mMDr~&_1;@vakst>T8q+?}8&eQ`>>uK)sJ?`*RuJ3cM zdBcT0#1%OhyV_W*d$Cm$uw@IV0R9@Z=X0XpWyINAzeLKLNdP~hWddRaXmVFHJ->) z$v(5q+IRgTA0&Sd^Rjz6#RY8;2fnQk;EFqD#tB!z+?Fzbk zKX^k1XhR8jtF_s)Fcr-^@i^u&V@4At-pTyvg2!+*TK9Ue<8J8dw#2ICxULN1zO}@E z(_k=6M5ZU;`M(N2^E~r$AefYhR2Es64R}?v(X~^^9llJq>;X{M&S0`t$$7{RE)cSF z`S?EO3{h4Q`2+r{|+q2>4DE1l6o&z~TFJ!SlI=Tl(=*)3$ z!85o!`0mfL&uI346xklkdv~#4KQwt~uBdg8>Xyi1!wXk&Rjs+ER{T{Tzq&r}U4sPQ zz}|y6(nHvdp zbO9FaJ7jeRBRv*w)G++5$6(J)1G(9O7Re36pgOThV{(`6kl)_e$>)gu=aFsL1LiLO zF+W+*BJhN&prcABR3wK~9YpeablL;h-#6j2EyQd5jcq5<;NP$!kE5Y8$hYMMIV+7^ zH%FdsM+=V(n)g+55M$7%as!6*-n0Dm5^^|=?8Ia|ic!3K57_c;$Ygg|1l`Cp-;9^h zga11)N7|u#ufk`ofXAAToL&~^N`a$(3}oUYS8#yq*on;U#t&YDM>G|-&T!C<2HeL9 zJXdooQ}J0x5f47dOLoKyc(CHL_u$30B;#B#TPD1rV`RLx6a5c_k^g8SX8(sp97R{|M7wSWl{k*yZ~{LQ)uJDe4_@KSqo5%&LGy^u?4sCQ~bI=axoHQ;x#afX)y$oWO0oJz`(15G0K^~4#w)OSfAef>;tZH z2S~`nXiZnleVW(9c=f%p{WlW<4?-3n!Sf%*2#OqjgjQY7+UZBY&gegw?Hc0uJ|LPS zcs8$+5qcl|;S=oPyX5tsgXQu7F~@^Evxj(wBiJ4UU4MkS;upYWU&fD^5WX=NR?Zfz z=}~f=d(h0=$P8~GJ~vl1wQ4&jE z8tkDEZ1#fuT^<~+AvnKVBanppYz@g$)C{@W93ToQuoX^l4_?a_u3U zKZLyhPW1LO(*6Tj?3c*MJ3OKLd6r#>*{%c05*urWq<7$F3p95_Ix5yd-dYk--NJLd z6a4Fbo^D^Xko{&lgjlOB`!+{LYJnqs)dy_&u4O9c)|4 z(*MBs=7;Z14QH8yhW!x@u@;NAg3ap3pUIYPWZMc7eh^RX3|P08Pd3+Oyz*lMlZceF zsN+rGx1^AhOkw5oBSGhE;TiY@)ZX*BhIhG|r-+aTFnjtiuI-6Vu4Ze_v*=3x=?*@# zqjKCH1@#}ySPl$v^u5f%A#8euJ^p)Ujfkq7Fkjp7PH(om`2J9=!((BdjzpIYk2LDQ9fKH8tb^R#=MGVeR!^ zT>o(F$Y|!?c)XwYu%K@-7ss(_S;nx9Ml+2f%l#PI>H+pQ8ui{9G79y1wL;tV=h_|$ z8f<(xhS~5}`TL3Rtw%Y>Q1spy^xGtk|2Ah()4j@H@=nHZHqUML+azui{JXQZ%-t@3v);Pq;6`)Y--A@0U3Zg zArH`)zpg($EdoN7K=5lzudb}l= z?Rozjx#GxJg&?I>`B?=$T#9`Q@@Z~fxsW+I)^!;7W=O@=NJInV`by@DwJME}v#va| zJCWb}kRC1FKq^W*Ac4*J^eXml5T02J-s^^}_d=HLMB@AKgu7z{ZsIxjqu#YQ&;KT# zco*L9#b39v*AR~PC^Gg0^6~`IIhgPDMLv4+&F*}!Z{UzdsqM?RI|MnoI{1v&FtfUH z#_sIhAHLAtT%8vAfpC=Ge7gsq-oj`1aE?((rIz_Mevai__lEOyNBTO2qc-K3O}KmK znOh6C#@tzL^hG7cwIUX*4C7jXIbA)BOf|-`3ZKcO%8e8zB71p|zC`@DROawGw$tI~ zzdWBqJf%&@;7Xp@m%)#lk1T$JeqS7H$(P9CY;499SXi$GNqig+yfW!NOK*op&ZX!tzM2Rs>W=%3VEo{ zCzXP(c1~3Z@3!I!)nL&!bP6+|JAXGtmsLZn7h(UB%&>}lqcY#A%C~CsSu^CfGiU9~ zRjYmP<8JIt^EkTpL0-d|507&F_cBj%<|5i zU4yy9hnW$2st@wlo$T3zJMDtZ%i5@g>=s2==0S3m-n>{X|I!MjA+uVbV?3R+Y*{=v z??nAlo~(GK-7}vghb|;!<2qSwxPoq2EZ_8M=4|3X?dVw&lq<7ULwO22OT#jXo;!lpwIASmy%oGh&*iJ_*=2kzw)hBd}mS6j8^xE zaqVS0%-K%`eX2a^@vdTDWoj#*od!{m`&@{7O8`?ht~iBk{*L7R9*(^M>G?HC;jg^2 zFL;R=u($KzU&!4qjQ^$omV-O_hdc4!w{hM-k)wn7(z|&_+58LE_hCL+jfPWue}^8Q zj}BkLy_%W#?teh{{m5M`#6r(N(|&}np?;suy?@2G=JVSO^yCaapU>YSd21Qv-JI=D zu6i5CnvZ=ShgQD_-}%-MOZUSsc?yj@h40N~LXxdPgjxA7W8YF`W%3OV#rY30QpZ9RafmTeetzTLKI3YQ_NNDbYcWS&!?hh? z&*O}vbN)}Rcr*8}bzH%yeZ!s~VRc@`q8Ss7_45A)t{*LmV61|=0x{se*IPWIpZ#~+@xbr9e-x{9y zsi1$-`FR?-{wqj8j7}YyZyEhxIMyMK{x5Ur6z4ez;?AM@igV8&)ZJm&WjyaZicNmGi+P&mdCCgJ#fvUx|Kd!*TCM zhu*{W-_G^lg`MphuAl=~(h5(r4o510g(%FGU(T8Gal|70R*W-hb87~T){twd#Cx7C znP+$k$@+^s&tz@Me7s+Y&+DM^>hY?@RaWL|Yjc14agDf_B3$Dco~TylA8bKB-jN4i zn$fAmX7pAaEmnnZmf*AKEm!534LQbj_#L;R^#=yuSMT>BHa&*{Jdc}sB1Vaq{Kl5t znbtt7-aB}t_c8`@Bs+2>{pGrhp|T(c_%!nWFVF8Xv}t+9yAoHWKUo?bmXny~FRu9S zpbOR^nX8bO<;dwar0g{J;ZxTBWk;_5V)kuAiq<1pYmm$J{JtHD)dHU694W}ZW98GU z5$?xM8KZqY7H}Xw{&4)cNAccz@q{`dZPy}O#*nSUNH^!{H|M<;eCH~jZwch8 zI9p-Hwix4Gl6SmXFb|qS%b{KTmnU=x4W&Na`QKF@=1LvyUE%M8T=`C{ z$+n;Y4>B5Ox!?1Qx)QgC?J&nU$+3(<_p$G9?7fH4OGQuQ=c-CD4$iMS*!!!n)*V7j zqX*juFQgy$*O`0nzKjWi`&#!B>@w-j#Q+M`xrD*8KO~zd36b_3xz^mBvBGUBd`83ZtYBQv){&@>~s>EQUN?;HW3V%+oF? zxk{#Mw0H$FLo=C?nQR$cgSzG@XWz#)o@7%N^kmntZREFoeCi(iu(a0Dti_&)AYaBT zsmRW7UUf3F zxaxCUxA&EeeMM-h1sS-4^Ce~bhi`3UG=JbOehSa(C{lO?nNk|{rT*r->L7j4(~ON; zwg}%6sqqXZ-(cm_eB!WQpjs3w$>p*IkHjmO_f`8+iq@S)Hyf zEEc4-B3G!q8RglIiJ)ieMuJ1=YW}}!T$kO**g;B?W za2>gM3L;5bNv*vs(L}B|m9yv*??r}1;q|=jEIt=GG`H{>FXN`^ykoqfPSs~!!<;Y< zikQFiQIAxwHEQ7<+`l91lT&*w#=riUBYnWn*~s}SzG)O;r1v||YXfsi`Jc(>AK*>D z&Cd_n|5N_{ge#fH*?lgn7}-CN{=+=~zmSjv$n)k9V{HsaGV=0x#!-4FUh7&u-^%s; z$*4xz%s_|7*`bXt#*+~x(GM!ZcxN%r=NVaJ_~^M+=Cd-)05xZ1@fYB)!i-_eC}nd0 zfAhrBuwex_UPbg$UF<-8EJ8WPTGTT+=%5ow^Y7sfj&Y7$%#8BP3t3uXex*649)jAt z4mQ)uF7c)7v6!{F%7Q`4Pa^&Mcw&2b=GuZI{I3q)jC9Ut1kKZYOa$~bGP;h@-x8$! zC{O1+5~=o4Z#KYs-57kvyYOiS;V<6?wr~UQY5UvrX^i6a&&)~a>*_Bw<9xu`Y4izIf&XINMP6H9MeZJ0f5bFVOd4 zGMT-Ps9Bx^&+=oK6(5ihco`&ZDBtReKT zlAqu6^Nfq~jIZK*E%E=1ELw4dj=Zj8l!{^~x40>COm51}>cp*KurTq_$ii<|nkvGJbC1tX_wsS&(~( z$fog+=)Q=jnYC18dk6b&=IB53`klY_^4@WNuICKuy6<>>gVtV-r2EMkMkZ&_c4dQQ zDaf6xKedZz!W|_9yXd^D7tW0+f%738Yv ze;#dXeA-sL+6SDo13%3}w?R7UA+e>om!d)EmcYX(6V4+ht8Z1Azl;rhzZ9F^Z(Zcc zOj|c**^L~l3p26}a_LNL9LA?n@G+G-qikaku{NuYjMK#(90TQ6DKf@2J5>I(w_2n#=n#EX^9}zZ346n{{fTEF(q_K;3;q{x zTEP?Bgk+1fDNmxL(MvcLp2lgUI36*Dv!wD~Ca-h6x0`P+#@?7Cdo$!5MEu9Iy%BJz zZ#ec!Wa+n{(~Sqcpa1i!E<>*MgHCbPd$>M*ez9WrQwEHeJXq^E%JZ>hI^&9R^jBYyjIE#^6z~&q>KG_=NeG5l9#E7Y}^=R|)^qk?b=Y#(DB~+mb za-h51V) zC7tIga(#sV)y8HA3NZ5KY(#{N!+Zkz{d#Pow|j$R8Atqr*TeTdKo3WMuk8t)3I+^)o^)f|KDxmlDr3)i5$y}|vEG0<28ZFL@ zzxk#fzkZZjxD?mjIy{X#7^Uu5!q&WV1xFFvHf~aD7U9U|VH_JhpX}l2H0zDsvR>tuz!u@5Um&Ak28RiHh z=~Fb8ug(Zm;CO{NuDD???D|Q@UrTL-_GkE(n3vwWx=|b>FW0O8W_GtO&m;D8F-xlz z)#7PSTrX)4df_`Xz!zwnFY#@EUn#mDXAtC#j<^KkYDY_!Q zqJ`7m8RH%2)5Gjz{Hc#*@9l#~;(n~L_=lL4{*=*+Ig4ly@*uypi4EH0-3~;P-hy_l zi6mdjsEY83-bChwo{hO=ZG#?wY~<`{7WXnPZGyIz6QMR0XSVx&$KW%|UD7sO7qqmV zNC)1p9(1I~i8@QX?n<<4dp^Gn%`D$&FtNaWL@qb;o)$sx-~Yu0J9Cs49H$9)&v&L<+0bpsM8gQyLk^yI8}pw(qZ-otPGIBT0= z+suA8z>fH;$B5P9XUvCIVty7w1E?`XX9@*9Q}4# zyKo=gi5-vXF(&E=>$>&tN}*Fcw$?g(hy#ob#WH-_$ATW#FE_FfbM`mu!izAnHMqaF zjJKAu8|P_)7O5I^nVy~gTr$^{g6vRi!Zmt)k%2URW}#yfk+7UWzZw^avU|^0^L(!2 zH}$!9S&(~CqZQ-2<*FIm)!@^bY-U|5^Si95=xfG|ul7Xz$FWe-vU8riY<8`x!QQPH z6McePdG0rcCuw(*YDh;h&L$^HTwTpClBiu3WmL0kDUHQSaz);wIT>RXxoK)jbH`q* z*m+6zuEJG{X_^&sw6#TQawB=YXcj5Gp-L>q~gdlhEL5+==8TUnNWFHXfh)3-sC=yiD<9@vLw8ww7QXI#1N+ zv!Ge$p_}LOiJTg-86&;LLCc8?O$~a~oTv<)Nu1+NbicOcYxY{kw`7~n=2$X*)VAMq z7jiH3#m#PPL9?yl{L9g!%elLs`CB|&^v-zr4}R)juMZKVqc3km%u&QcdwqcUbUcjv zQI2UYKjxpeawapK>T`WM8=rC~tGan6*rE&|{h1ipsp&uLdT?anx z&8K&vtMr?1Mysj&^uSv)gZxZ}njDdi0?eazOqMO z0NZ&jbQO6R%W*4v$#d<@wGYO#AH!!8;dZ_kx+J{?*YhpdrZ4inr(v;(@;u159N%u? zdBi+(jKMqed}PKn;tBb5&48L0jPqGruHP#fpAGG+$C?|hCf?+(FRe;A(0sGz0a3I6WXfHu5~MxD%+yn+rN z#rHz@S zJOyhofqRo%X+QKgd5N=6<}Wubhm}3!IMQggQ5YEfCn>>a<(aE`QF>SM;Y9akIcpR2g^e?v;qo2K8fcU1vDIcj86#?BnbCFeIU2CP zI#QHHCP)+ZGmo#ACsUyZdUhbX@kx+)x%iJ`NA6%>`7e6dt%IeB$ck3O^N1hmD_O4~ zKSMlO4yqY=eXFuumw1qRC|XJPP?xAx3UTMw92f!IjGmXPXxFdqoJ;#?-ccrvSb>^0 zC%?yUiguW>y}-z-ZOkT`aWpGZ5*=r)LcIT~97n8HE^Lg<)qV0r+(VmPnvoW_5li*T z)Rgj)^yZR+J~e_jF1HfH`}8@?&q%r~?lc8DBsIZ1N4%`g}d6yne+3G#8ptmC;*d)^EIojUSH}Fpj@uM;p)H$`NJQ-^}^t zqYUE89%cU#_(X$vuM1Zq*T#rO{%K^-%Re#O=DD?_M!iZ$MgEqjB^yE?&)7gtlKC$= z{l+*}Aw<5czw1NAx)&o%&((luayd^&`)ACqtVV>_%$s)4?C@?Z*AZ-sIY8~dk%Tzm zZgim@v>8*8Ev>0p(u4mU=@5U5$!nP|v5_M0+1XcwmrqoG>At;lg=kg7ak9*cxU&sHsG9_J9(BVSV_TdvF3=+1@MbYqN|i^|1Z(8F*h zc`R|Z7;Wk6h@Hs?(3+YJ(kez2MmumAZJCp+D$i)wMEcBMinZxQ?Fu93SR6sN9Z%V> za&zPpm>1AjGdC@g?x;sLfL@nOSy6hcYxF_P=&#`VHwV8;-qdbhGE}W&6+bfbWWK<> z+fh7(BxaoabN!${xl?<6ieW9qnyki>#Hd5mC$hW$<*ahk4|9b^F!Dws+Gh?VMrdm| z&qnS|Z^LIAnG_KPHFhz(zM4_`9=oJ9Gbf_NMCQ49Jw38aA{3vxHFIjQh_f2m=VRQ( zhSh8$7A4tBgkOo!UzHVUWN8Gd9TN$NXtlT#CAz^gW7!4n-S}EQhs?vW%$8CdJ%JU$ zL|^4u=;6v>R$BGOe4XIPk$L$ST?2Y)$Z<^1s&SOEi zcQZqBuXl2MS-5ME8u`o%*hh~_t8YHVOymaki+Otyc1OTSItN#Kj`ziixAXjD8+hGb zQ)JQ14w$2vs0EyD7tbz>k=3h?HbX1t{4wih)}#WuR)(sqdEYOlQGM^*JZ2I{tAw73bxGoHM^E7i zC9}7g9Bq-9i5wC07<$pN<3*lhMW)r9ZVQ;NOBgG2M^?QUr-~)TnieCu^2}ek_vswP zC*+ZgIhJUnbtIx@juGyJoSM1mKMOjWV)m?E=Iq3gN;#Z$c8SDB$}Tw3lY5xk&ZlM zj1O|1KQkWIF@DMDSWB=PjiFvV$#Lb}Y8%8q&AdC-)|F;3OUzpqK+5HbYop5{V-c|v zpSGq=j)54N$B{jyM^}Vn#h%A6QA(wte`PyT5&B)ch6-35#9!}^-y^tRi$r_%k!9+LB*^=aw<5PJX8f%?(J$89G}|t2oE)U99M9S-YQVKt z4V&JT2#)@gsIih~#f@`Ec8Ri?pX;c|-VtY2K3s*-`Y4};Tl}3y0YPT9PJUCirPthq z5$+f~$QE3;t4Zezv)HV+6%FzN$08 zxW7K37;q_`d8~{xDpM9>p3oSCg;tQ7n1dC`S9X+3ZG$MYauRa}dJf6ljdmazc`nT7 za_N<4k5~*@H5)3*@CS3=Y@JyuE#)TkjVx}f&-R8*zhFD>{KYd8sgafA9EqE=Qbfro zoxmB*=0{$dSe22Nvs4D9qZGYCpOZOOV^AZYiyYS(Xx)p}ST5_YXuZfUH{!|+TEU(O z=fYE!Ygz_5P)1{9REE)T?0gjqBj?=p%tnUwgBNX<#dyW>D!|D2#I5z0RWEPBn8Y|x z4xK(@_5F=@4wmg&+bf%1KIk@7*i}>DmXzsN^tFA}?$hy>b zGaDz*$aiE6d7p9tH}Z)L&qaJ&tYTBp-h0ARh(5$0VIN0k2QRUKKNz!pJR4D^RAkp0 zTlq4gNjuqFEw}_-TY15L)#$cy^?Ji7DX=O54_|OYa6^X zc_7gX(i>7{#5k7YJ$=I{neR2@s&)F3_hP-${<0CZ?}!YF!8sQC zuUZE^SlQI%=Xrwn#ZTj><`QEpU_QusWTsoK zuZ0si5lc~LoZvU}ou1vw7}?ThzRcQt1nsz5LA_H2Ig0%{jHWI_>Z}fl8a8I!jCaj) zX-R4#t&zQHhCY?E>9L>Z_|8!4FO25pXXu|9^O>7(Oay2Kpjr576?#>U7d4Po!um_v zPOZDuqB7#rVF>75sXf&3`ZuwLq6d20)x!s%we15{gT0&w@=Oabe~d>XW>GQB5aSPh z@j~3G+SlV)0d9{zwYOO?ZK&End#V2;AEyS#(O-A1JJ}~zt?DIdSFOLYF4K7{b|fND zI6RMp|MZp5#;QqW!zu$;d$tN8gZs+I_vKc)jkEM%r$GyAYtOR za(MSMR^Fw^v{g*nI_r9@|7y!mdq|iCu&&x{#g!aGTW{A1Ibf&JKl!*PpReeM7OoQ4 zVm40g72|GeH7@xO#kjZXpb_SgE zTummrZpO!G&d5=w;ZA-Rt(JejjlcFG3+K_$MLADXMx`s>fxIQ_nyuSc|0#!B6}4~y zp0Al?;{|7hJowlZT+OEbj{KI$e^*+}J;c0&a%+sQpJLU9&(Uvt&C%Le(=C1%J?JYL zJsIXAK+#t^8RoDR((;4KvbTJ%nnA+tZ{eIX9@2{vA&~`X?$>Oryc(}vK99JmIHy-8 z&)F#C7c_+$SU$K~b`v8cf95!6)6ev-jZDpBYE!HPv+B#y@wuimmg_mjcW5;|NZIr< zEw(ZCzGTtKMPGt9F6%_j+;Vj29%M!2)$8&4PI5+TKFu5KL>AStMubNHVj61b$X1uH zXO6+DDKnquV18qN^|FzeSb@lL)YDc4`;N>$nKoY%6L^(oDXlPG$2YVzer_GE=!4un zkq58jcm6hSv5-+Rd!fCGwH@D}`Q2A5WBx{?@2N-)8bL)b?5hvoQWN_mvWS3)zR-C)r`q zLb!faI@jVASXU8aBV+xee9Oua5hrmAwYk}HyRi7=jZPwps~>EvT#9$JA4V`SgBSaZ z$d1-4ik3w$&iG01Ums2enFzEjh>FY)J|@ns7NYN6z-;=o6y|bF%f(QL=QeMQ2#^<{Ebqp;kjxrTxjSb48KP=CcS5Hm6^P;WTHjdLPiT$a76hx=)Sj+Ik+4SH6t zr&)#=TN?dX(_pk&g)6^?xI=!;05ZMzlli?nL?t}}gU9T#*J4Z~iYk^W-zL`1s!1G0 zEtXkv+41c-r@C59L@O%;>MYv9>OWDH99*kRJ@uQJ6eB~mSstF2uZVeR^F{LA)UbsZ zd+Rs!fVJ>?pA{I-#^~hEV8}P4p+%>~@4bS?jGJs7D+sl~_Wy`jn9nW|#K(~re^ly> znncp{Vq*s@u{7%xtrm+tL(IEaL21t!5%rk=wx^IbA)@`-y;z4}zE*3b1&VA%^A<)r zN{rD%mc%x)dBu45@Y8l>@kd_cx=#_Jlhywi0jM#a}Wv)I^cBE`n`#&-rC0Pn79M&}_>>hICpu z-h7T`EwjB1HgOG6$A5zsxAyP=-%&RFu9&T!p%{?b)J(JaW_4`j7TE1VmZu)Jm~!0I zpl1K0ckZzqOS9?`E&Y{Ikms`kyP=Q2mhah(WHo2E0RhoY{2P+rS9K0PP z)|xxFek?LGjRNHJ$N|vX`h)+)&SXsL z5$Z9hLn{5J7tgZyHpa%tY8_*`lYKL&uyelK!OJX9F`n^h?$MevYfT+%Yox`WQh4(6 zI;@;i>ln?+*cBHv>W(#C-j67Tb12%K6h1er7Beo&@I}6LjO&)wFB14W^;t;GuHd&QixlWT8>7VS$kCBtYizjZ;I$Mpn7?62TV5uFm*(Fdr)|DqL<;b|^h z3)dRGY~5MpOxbZlYhbq>tNHEU^fWx8p;)#)?Ae_AFq?QC=QdwCgtOmGKGG^TtIO`f z20p<`F*26M^8Yh@+a6C(airJ_>OSzh0byTRPLGg(w{P8K7)-8GZYR%4y!SMGso`WZ z?T+N$y}3fOs2%y~)x|0~bEX40ry0?nj7I}TMk{9z9G`Pz^nY8dO~eU%|F`!Y9PMVl zF_e3Ik5F}8%xH@TMN6vnvS)>M+-^En#;FUe2-0se&W(J1{lJL8FJPQ4JvzT6UEE z4fLdC{Ox0ItVaLD>Y0!6cW0mhmofYPKp$I?Wu$H%&(11x-o?+&#cIj_Vg7GKbD7`x zf^W*xk-sj(#C|hoEY+0e62<>z^T=&?k6E16{xIM1-H+k2kAv54k2E{ty#!0={ScYV z<2&M5B1?M6)*2fhsW(MzJ`KzkSuP*Jvl$P+CiaGX5Jt}s*fkHqw0Qyc&3JrySv9iS z{pRPeV(g$MBj|0;_BQ96!slAP4+3ZC6OQ>sh{HUu8M~MVvtrJwbXnv3&??sJ84s=G zJ|i#E3g5Y$Wd+x2_XI8brf}6}fsDAU;fnWT4gLZ2T8vJ9L-!iF$pwwo_*&Um0UWy~ znBCgM)6+}PXHP-~tQJWNlA|O|tWoJ0zYtYU4SwTLowtaCB;6xot7 zCg05ZDy@as+`sH$R#@J=brR}+t)^Ltz3g|1b071y##igO%8iWDZgi@dSNrB!;dh94 zV#WAxT*;rDSJtTUrdYPv^JTnJw6cDYH@5CxbJ9}*7xT~>+Vs?LUgzV_?E6}>N z(GlVg+H`9xO9q`<4-I-PIza#2JbYrd6O4>erVQdujGZjRyx0e08@WE^(ad?+?_BU; z^uV;J#=pOWtKQ8M@M-+T)meL|wXTJCDlbHStQ}Is8_IDUqZ%zp^qyrASm$iF11K7z2U)*kcFFiK<}s|Q5UYp?r5pk)akSgzuud(x z9?=@>D6J8TIRR0_$a~U$*@eg~n{kWmAn`c6zgWF+BR1g{G;3FM?p2J9UXmDzzOk{I z`B}Y8eeMHnasYNBrS>2YKR(46C33G?J*zS7bE7@fvS0Fl^&Ss!-H~Bt#B6k8?57ru zKAQ2Z9V6tYiF$12>B+JCzfM>1jBgqRXP!9$!94tl|^j6kk?`VlA2RpOLq|ntXY= z6jq0cGZ?wpN9!2JFftJRFvAi%X()TzG%F6wvd2CMdh}5fDXZEg^OwefMo1zfDM*{h zfw5cc6JX7nd>}P|h~<@+>2BU_j$9a- z>StP;QY1*DIV>Y>Gv=bYv9iqmxyI&tCByMT#s;s%iuz%AE_Uy-7wSzRf7qFQJL2Iu zFRkpiE?G909C$0=jqV$!koL7_pOh=fivlQ4daSmq(8uv(Bpg> z9?}H3iVx#)^=FTpIl|5Gz~rBG$M>nvoH6eo`#Kum#n{p;ukoyyzD&yIczxG!N3yo; z;@O$+-wrBoC$RopQ>-(!BGt~B;@Z|8wFq92IRN>P=F(zL+MZ&v^{!*g?4_k&ZI@R4 z9lIJe;(RUn>?V$UH)Aj&FyQqV<-qsgK4jNfwc3{bYw~1s1zjr7N&m$8E(2Tsj``8p zo5>z-O&O;<@gHBoUwo1NoR0-h)Viz=Y@N6dz0m>u)OT#p(d{-RdL3)^%_7RtFh3Z3 zHR>DNu}lwL^r|*juOznRc=ogP8buSzaE-EwWO|8u$o4YpdMUGAiNC~O4V=$PU9mfHH<1gotHz7w1!Cp7I?%Yx z8G5NVQp7N2dpqOQ5Pvd?^6+Ebn|!}3(Xg=sSGJpX6xmVg2&?xZy08pQ^+WIw#D(<; zBBm?;pp`QxX4kwW=vYx&P1QSOdX^= z>Sw@eUq-vC4XtsU8noh6G~(yzT6;0d4H1i8$=|cklh)SAOP2}$B8=-X_>JPdukzcY zaIj^R528EtAQ;*Y)2r|qyh_&{7|CaH#s`Jo&#p=^5D)WdzWWx(oW^z90seK4YmakT z-+G>QW_&j=!zc6Ud;C3~^F9^$-*%_Aw)9@u=MQq;hvAz)#wQPjzlY)xKhJep&1vPM zm7Z1ySp@0x*V<&*^mCzx3alr!br|G4P3*1mezXO#pGS?cLe9W zgF6|?*uBLu^>)AD=X+fJv*Fr?^4Tapoy@sD<=(8M)q9=B*&W?!oLLr+6{dD4n8MgQ zvi38!FY$Q3`vN2C>Xl=|eZ0wMKBM=7&pi=8|0VXa@_#NqY3w^-?SibHh_dJjf6Mc> zlFI%WOOcvI|M}0d4$VDiYxSJ$Qll-E{i)9>*TpDB>!IgozVs4ar8lZ4DJm~}$r^0s z+z4Dh#dy~WmrBf1F*@;p$Pd+9&^kt*sJ&<8dx&|6xyoX->zMV`@+2Ce$E>fn=DQKI z(ph7Dr#)LE@~JN&m#abWh_o2?h-rnNR)aY#Vr1lJHrHIMvssMR?`Z$*bLGs|d-FH( zT(e(tDk^bIaRf7Y=3lMK6OWJeh}I#=KZ+|kM8>lSs@Xkls%&|YRy$tS3i{caEHQhv zvsS>)kI~}UIs9tQ(|~U^=2J0gyC(L+LKtb^fgbO{o!M_A>REdh+a+F|D~@1QyvR+g zC)LZ=hlmU!kt!L4^8U20UD#XRPV6(^n(x`?JXS;LiyG@|i5y3LQZ<%1u6*9oL3hS` zH#cXjAMYi08|;h)u&&E4_xx$e34_s(E{Z(%<<_@x8E04wyxAN_W@sD0%_324? zH_rqwsR#FZE!%axV#j{FKHAwtFHRX0;gE@-|7Jv?4b+k=W!mnTjW%Oz-{eb`e`blS z*i4!K~2_)GS;nNGLGpuWb==1xU_zvh~j^OrHKybtx2 zJ>rbt<#pKmKo+4foH3`YWc$WAULx_obF7$IHLJdddlo5mjJ--Te)8XqcFllBHhk;^ zF3(K8W!Dy;famk=1c5|CF}fB{jj=5Puw^-cA8TgS)Cp0P-Ku; zXIGy27i**K@*wLVUXA^Q<*k@uHcuKerRHQ(8Q1I_w*vC4f8|^$|{Ox$fL~PT6nIQJ`Fb47&i5qAOA`?&T9C;K+xf4-# z_)N{jn)NsY`e8Q1&Tl(8??vp08Cmm?GA(2ZrEncF53Zbv8_4d`uZnoNsEAd|-(f3% zL_QAkRJ9(FQ(QY}AnVCv#2#5OR+F0{wf~_kUu(=(BdOvq^5^8ZMp^exjRy4+wVuur z`%;R)$gg)yjT!6+8*@_nv)aZ~JX$+xiiMk5l?y4GM0TOsLfKz26XqPUrob9zvs9P5 z46bIb%*4mAlJE`u4E@2m+@*YPYY0WCHu4QCpY0=gsnb^E*!$BQk_>t=P(25`ZR;@@ zaqIQ^xm7265RrqG#S`0IDpboO{sK}aqa;=~jU9o?QQKpqb-c_syFiMq2 z<(|_TT*MtJeLJ} zsS}OeaYT{iG0FNga)~HF9BJ`j`#ze*QD@kPDt3Pq8*>EAxQGxq7d*F7(7%k5y=UxU z8F|)ba>W+xq+&MCXJ-Fxxp!($^I~G4;#tlu^^aBN_7{{X5-afSduY~8wt{hj*~#sk zE3&<1CYW6*%jlYe^;+y9k-!}}PO(l<4w%uba%}t{`@#H?2!&5fZ7N18{&A^?l!&9} zv@3n&j%pPm-ts-V*@}wwd}=Htf?*t}c8J*0C5DU@62CM1)wi*uT-3UHpYiUsG}cST zE)t@L@-XxBOpJBhOADi9TDubag&KwJ4%a0XD_2X#p*1~X@M>y%F3R#VwiCILzi$18 zey-9Pxh5qU7qkDe5F$1cxf=2`^iJd?XszW1nu*XNM5|*p@Ri7`b$X%@;t zjp&0XVJ=AqgVASiJeasTkUgj5aa-AUE#5)wf)!Uzkkuz=O^$bK{Hqq|$JjYbUbw4+ zSk2(O(c?7hCdS$V&C(cM9(!fQ{>b_}t_i7sC9mARZB5a(X5sahWf@zUBL7PHh->QT z8|&M8JpEi(k}_sCZ>G&MlP?F(%1%8*E8z8Nt;;j(WoJYY6xRVZPS6(F{mcH;&haMf z?b=e2n_(Y>+8on7o_avOnCsm*I^r4LZ8P?WoEtN~u^X^HyiAD5Ofc`(lp~qF)N-3@2^V$Pv zuRWa91G0}JGf9@Ao`^{0@61|RRrZ9oj>DK=KD3+yd9|@#dKS5trF^=L*`U7C*N8l) z*iFkkhA5~it$-wm6*veYawQRhWTbkfXEJT%?mSM zv1VCZC@J_-rdSeR-=|zfj=KyI*O<^xkX@)& zcAr>vs=oZc$}vYX_L`E{tT*@-_Ux0uYhJ)ve?i|x97L_AuC^B1?6SC#=&BiKYyXWh z<0=K(v|U`a)q&RPSxK{wr*WA3mnCRke=8$k?k@6B(^}l?V|Z@fZ8vP6s`h zf(@U9HGc#A;cd<_ov|>B_X@c{*NSuXqesAFo(3flgK&*pb9b@ti1k@^(p|`zt(B9# zVkMD`ZZUFuCVqyu@Y;V!i)h9(;1O?fmao`jG2i_RG{O#FPXuh|X?~x<(RLzH)=4_D z^44X0SSRla8D_oY5{N124emqAmvOIVHRGCr_Gq+=;%4@W=)PG!EB02h?_Q)+ma~2H zMgAhkELKlw4R-FMJ_XYJ96ujLlZ)q?%XhUcv-Ly3l!vp|Xz)_kh#McW^sZO* zJb3o2pvx19BHtkg{{b2K*LZ(42((qj_7Jq2$TNKFt!y8%p6|SDUkA*4PPUn>Yd4W^ zkK??fIP+ud_cRgdSpI&7zx?hn@b{s_sgLl1{~kUSMKJR26Yy+v0j^y( zj(Z=@clvVm?YJAc*`+QGLN z`^1PTW|pG9vMM_=55?W&lN-wyLSDt0?2K(azy7l}C1%g{%glV~5Bi?WS6M^m8)G%L zYdA!{YV^Iu^4!dH>#^E7MjN1CC%Ui&J#OX5rFh#45o-(W%Wgi`D#E|GI`y(SEF)Xv zsa?!$7MuQc4Yp^WhmUdn-p0GAh4Q=Fjg!g6m zev5t(9d)&~Phl?D5y}`%yJn8quJUKYJ?-Zl*4oZRBih$*5<2T0^rhbr2UQc<_1GvU z9>L0LD{~@Wd~-l9jD*&)$9%M$tGZ9*^%gpJ7TQnC6T1$&`l%6=cF|Rlws1Z6XBA!c zeD?X+&M28zAKHi5Rrcgg*ylVR{T;slIyTA9Dq}hBlVIAf z20I~ZLvG%RU<*WjL|?RLmo_VXM6<=atwi-|-(!?wFLYNSup6Xxz*Yy%Wvtv>S8oMR z%g*-l3L?|dUbu&O!q!RIM@;`=Ipg6vQd&}buK2$lzpR^G#6B|pd_FQ~J`Wb}1z0cf z`lqwkw>(>84xeOPvq}b}@?~~-AJ0iV%ASRKJF+5TPZjqvcWeg*b7A^5@*<=4H{W}X z=U9-rEyAm}Xw)yRAfHjthb_ho8kA$x6p%d)>{xcN zUGpL)Ca!IrYDd1`lcUA1y;@znd5H#VnOxJd9o9qbYu|VylD2%uSfn$*+e5?dgVqt- zyWOm6M8VC%x-zVv%Sg5YsWwM3J85@%SJ;$$J^-s}k6)uPW3lFZZnv~MuvXroo`pSq zWub{ySeI#*q%!`?wOpaAgE}Un(PmBcH;nF#ldR=!!E+a(mqls?lq?W?N5&qoK2xiM zWt|uUXnoAFn8k2a1<^0RRgL{F=Y4BsU;|Ta-X6p0v)c17ROVJvv{pdNg)KEXnuGKbT*MS?{a4M(`q{>*%jy{t6uc-e`h`(VIMnK%W>CNl>2Yoqwg7!7j2!)3h|>D55yW8d#ajGbcN4p z=)QN*o$p~G>{n$cSaqv8yjS^6@7vx55tq?M%DajzI3pIZ3G-`OUwd&cNktvan@1+8=l?XI{Wn+sF2O zj$qvIAzIux#ok=n6D^vN%(vJm*XOeXW9$LGkK@roBVVY%0(C zu6nulA2J)O{*X_b3=dyx=<1@!@D+2hw~T4^p1Hx!jI~`e)H~)R?eAqSRSR=jusX3r zkH;`09BZFM>+7+eq_ESl?&;egatdQD#i6TXwE*z}m~lw`+rSC87(?XEzxo zu?Ik8cdy`L@>=J z{fX6&wRo{!MQk@R72QAfUly0Oicp;+L*8}1Qv^Y$fl*8ha} zr2k}A%vjr+LpzD6L(C9~VqD@Ni*d?6jXjyn*NBnEI%=)DNVQkz+05R=zKe2pV?{)a zLX1S5+4@_ePO0(mQqwpoXzg8 zqG~=tQEGAO$lMdtw-zL3Z4R@K<0!&y)&37?)Y#p|D|PN`b7FOteUIhND#y_?vf@O& z82Nn1IhNg`y!*(qapi`%ex5l~`!Oih&XuUy?b{&ZTo#Zl$PMgeRgarEqaCwi=Rq?# z@~+Ly#%E*40B5}Zpjt#`RLn=q>a(kZ9XMi5o~wUl3s){G?kuz>(q0W}Q~gOf6IPqc zdC*2XyOr78%vEc~Wv@m|I<7(&duVucJIu#bOdKnt05QxhW2NA`4JIP1c?) zIdK(xzIFOffA+$=x|OXLpSj9|Oh3_bD@@98MP|-2k#6UZd5*|svmcB0!tAU5nB4=M zbN)->TbHAMM2%yoIOBIK8sqx!`cZKu192qtZ{E4JR7MfzeAI^4y;ut(!_0n(u{!>e z#}-+`a>~qN##Qk|3gp4L8jyL0nDbX##(asHY~|i@lAnA9y4=+fW%$XsbJKHkrHT63 zW^s5efzgSbw9LT8O1#)pCiX6oe=VY2i@S>KmdJcILu`y-W;TwWBc~phw_v|F`4F*> zv@1eIl>JIZ$>Ycuk-wUZJ#!^NS0|JE?uyA`&91Je9n}Z+x@1~7OU$EaxBRYtVNS+X w97Be=ebr*FK4vvz-Jm+jxfbVZCOSb|QGyY)n}S(FpH&&|#!il+w&@rDA28@CG5`Po literal 0 HcmV?d00001 diff --git a/test/integration/test_speech_to_text_v1.py b/test/integration/test_speech_to_text_v1.py index 3b58aa854..0efc3130a 100644 --- a/test/integration/test_speech_to_text_v1.py +++ b/test/integration/test_speech_to_text_v1.py @@ -100,8 +100,8 @@ def __init__(self): def on_error(self, error): self.error = error - def on_transcription(self, transcript): - self.transcript = transcript + def on_data(self, data): + self.data = data test_callback = MyRecognizeCallback() with open( @@ -114,9 +114,86 @@ def on_transcription(self, transcript): t.start() t.join() assert test_callback.error is None - assert test_callback.transcript is not None - assert test_callback.transcript[0][ - 'transcript'] == 'thunderstorms could produce large hail isolated tornadoes and heavy rain ' + assert test_callback.data is not None + assert test_callback.data['results'][0]['alternatives'][0] + ['transcript'] == 'thunderstorms could produce large hail isolated tornadoes and heavy rain ' + + def test_on_transcription_interim_results_false(self): + + class MyRecognizeCallback(RecognizeCallback): + + def __init__(self): + RecognizeCallback.__init__(self) + self.error = None + self.transcript = None + + def on_error(self, error): + self.error = error + + def on_transcription(self, transcript): + self.transcript = transcript + + test_callback = MyRecognizeCallback() + with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: + audio_source = AudioSource(audio_file, False) + self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", + interim_results=False, low_latency=False) + assert test_callback.error is None + assert test_callback.transcript is not None + assert test_callback.transcript[0][0]['transcript'] == 'isolated tornadoes ' + assert test_callback.transcript[1][0]['transcript'] == 'and heavy rain ' + + def test_on_transcription_interim_results_true(self): + + class MyRecognizeCallback(RecognizeCallback): + + def __init__(self): + RecognizeCallback.__init__(self) + self.error = None + self.transcript = None + + def on_error(self, error): + self.error = error + + def on_transcription(self, transcript): + self.transcript = transcript + assert transcript[0]['confidence'] is not None + assert transcript[0]['transcript'] is not None + + test_callback = MyRecognizeCallback() + with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: + audio_source = AudioSource(audio_file, False) + self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", + interim_results=True, low_latency=True) + assert test_callback.error is None + assert test_callback.transcript is not None + assert test_callback.transcript[0]['transcript'] == 'and heavy rain ' + + def test_on_transcription_interim_results_true_low_latency_false(self): + + class MyRecognizeCallback(RecognizeCallback): + + def __init__(self): + RecognizeCallback.__init__(self) + self.error = None + self.transcript = None + + def on_error(self, error): + self.error = error + + def on_transcription(self, transcript): + self.transcript = transcript + assert transcript[0]['confidence'] is not None + assert transcript[0]['transcript'] is not None + + test_callback = MyRecognizeCallback() + with open(os.path.join(os.path.dirname(__file__), '../../resources/speech_with_pause.wav'), 'rb') as audio_file: + audio_source = AudioSource(audio_file, False) + self.speech_to_text.recognize_using_websocket(audio_source, "audio/wav", test_callback, model="en-US_Telephony", + interim_results=True, low_latency=False) + assert test_callback.error is None + assert test_callback.transcript is not None + assert test_callback.transcript[0]['transcript'] == 'and heavy rain ' def test_custom_grammars(self): customization_id = None From 0a6c540f4a5d6abf25e35f9b8b20d6d191744a43 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 9 Sep 2021 15:52:35 -0400 Subject: [PATCH 353/455] feat(assistant_v1): add alt_text and sensitivity options, location now optional --- ibm_watson/assistant_v1.py | 292 +++++++++++++++++++++++++++---------- 1 file changed, 217 insertions(+), 75 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index a5f1d9679..13f764e60 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -14,13 +14,16 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your apps and your users. The Assistant v1 API provides authoring methods your application can use to create or update a workspace. + +API Version: 1.0 +See: https://cloud.ibm.com/docs/assistant """ from datetime import datetime @@ -57,7 +60,7 @@ def __init__( Construct a new client for the Assistant service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2020-04-01`. + Specify dates in YYYY-MM-DD format. The current version is `2021-06-14`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md @@ -185,7 +188,7 @@ def message(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -245,7 +248,7 @@ def bulk_classify(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -308,7 +311,7 @@ def list_workspaces(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_workspace(self, @@ -408,7 +411,7 @@ def create_workspace(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_workspace(self, @@ -467,7 +470,7 @@ def get_workspace(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_workspace(self, @@ -588,7 +591,7 @@ def update_workspace(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: @@ -626,7 +629,7 @@ def delete_workspace(self, workspace_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -702,7 +705,7 @@ def list_intents(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_intent(self, @@ -774,7 +777,7 @@ def create_intent(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_intent(self, @@ -832,7 +835,7 @@ def get_intent(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_intent(self, @@ -922,7 +925,7 @@ def update_intent(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_intent(self, workspace_id: str, intent: str, @@ -965,7 +968,7 @@ def delete_intent(self, workspace_id: str, intent: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1041,7 +1044,7 @@ def list_examples(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_example(self, @@ -1110,7 +1113,7 @@ def create_example(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_example(self, @@ -1163,7 +1166,7 @@ def get_example(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_example(self, @@ -1234,7 +1237,7 @@ def update_example(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_example(self, workspace_id: str, intent: str, text: str, @@ -1280,7 +1283,7 @@ def delete_example(self, workspace_id: str, intent: str, text: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1352,7 +1355,7 @@ def list_counterexamples(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_counterexample(self, @@ -1413,7 +1416,7 @@ def create_counterexample(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_counterexample(self, @@ -1464,7 +1467,7 @@ def get_counterexample(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_counterexample(self, @@ -1526,7 +1529,7 @@ def update_counterexample(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_counterexample(self, workspace_id: str, text: str, @@ -1571,7 +1574,7 @@ def delete_counterexample(self, workspace_id: str, text: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1647,7 +1650,7 @@ def list_entities(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_entity(self, @@ -1728,7 +1731,7 @@ def create_entity(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_entity(self, @@ -1786,7 +1789,7 @@ def get_entity(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_entity(self, @@ -1883,7 +1886,7 @@ def update_entity(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_entity(self, workspace_id: str, entity: str, @@ -1926,7 +1929,7 @@ def delete_entity(self, workspace_id: str, entity: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1989,7 +1992,7 @@ def list_mentions(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -2070,7 +2073,7 @@ def list_values(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_value(self, @@ -2157,7 +2160,7 @@ def create_value(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_value(self, @@ -2219,7 +2222,7 @@ def get_value(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_value(self, @@ -2325,7 +2328,7 @@ def update_value(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_value(self, workspace_id: str, entity: str, value: str, @@ -2371,7 +2374,7 @@ def delete_value(self, workspace_id: str, entity: str, value: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -2450,7 +2453,7 @@ def list_synonyms(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_synonym(self, @@ -2519,7 +2522,7 @@ def create_synonym(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_synonym(self, @@ -2577,7 +2580,7 @@ def get_synonym(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_synonym(self, @@ -2649,7 +2652,7 @@ def update_synonym(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_synonym(self, workspace_id: str, entity: str, value: str, @@ -2699,7 +2702,7 @@ def delete_synonym(self, workspace_id: str, entity: str, value: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -2770,7 +2773,7 @@ def list_dialog_nodes(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_dialog_node(self, @@ -2922,7 +2925,7 @@ def create_dialog_node(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_dialog_node(self, @@ -2972,7 +2975,7 @@ def get_dialog_node(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_dialog_node(self, @@ -3129,7 +3132,7 @@ def update_dialog_node(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_dialog_node(self, workspace_id: str, dialog_node: str, @@ -3173,7 +3176,7 @@ def delete_dialog_node(self, workspace_id: str, dialog_node: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -3239,7 +3242,7 @@ def list_logs(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_all_logs(self, @@ -3258,7 +3261,9 @@ def list_all_logs(self, matching the specified filter. You must specify a filter query that 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 + `request.context.metadata.deployment`. These required filters must be + specified using the exact match (`::`) operator. For more information, see + the [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 @@ -3298,7 +3303,7 @@ def list_all_logs(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -3348,7 +3353,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response @@ -4057,6 +4062,27 @@ def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of Context""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() if k not in Context._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of Context""" + for _key in [ + k for k in vars(self).keys() if k not in Context._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in Context._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this Context object.""" return json.dumps(self.to_dict(), indent=2) @@ -5176,6 +5202,29 @@ def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of DialogNodeContext""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in DialogNodeContext._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of DialogNodeContext""" + for _key in [ + k for k in vars(self).keys() + if k not in DialogNodeContext._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in DialogNodeContext._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this DialogNodeContext object.""" return json.dumps(self.to_dict(), indent=2) @@ -5436,6 +5485,29 @@ def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of DialogNodeOutput""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in DialogNodeOutput._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of DialogNodeOutput""" + for _key in [ + k for k in vars(self).keys() + if k not in DialogNodeOutput._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in DialogNodeOutput._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this DialogNodeOutput object.""" return json.dumps(self.to_dict(), indent=2) @@ -7550,6 +7622,29 @@ def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of MessageInput""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in MessageInput._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of MessageInput""" + for _key in [ + k for k in vars(self).keys() + if k not in MessageInput._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in MessageInput._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this MessageInput object.""" return json.dumps(self.to_dict(), indent=2) @@ -8020,6 +8115,27 @@ def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of OutputData""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() if k not in OutputData._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of OutputData""" + for _key in [ + k for k in vars(self).keys() if k not in OutputData._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in OutputData._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this OutputData object.""" return json.dumps(self.to_dict(), indent=2) @@ -8216,12 +8332,15 @@ class RuntimeEntity(): A term from the request that was identified as an entity. :attr str entity: An entity detected in the input. - :attr List[int] location: An array of zero-based character offsets that indicate - where the detected entity values begin and end in the input text. + :attr List[int] location: (optional) An array of zero-based character offsets + that indicate where the detected entity values begin and end in the input text. :attr str value: 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. - :attr dict metadata: (optional) Any metadata for the entity. + :attr dict metadata: (optional) **Deprecated.** Any metadata for the entity. + Beginning with the `2021-06-14` API version, the `metadata` property is no + longer returned. For information about system entities recognized in the user + input, see the `interpretation` property. :attr List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :attr RuntimeEntityInterpretation interpretation: (optional) An object @@ -8242,9 +8361,9 @@ class RuntimeEntity(): def __init__(self, entity: str, - location: List[int], value: str, *, + location: List[int] = None, confidence: float = None, metadata: dict = None, groups: List['CaptureGroup'] = None, @@ -8255,12 +8374,17 @@ def __init__(self, Initialize a RuntimeEntity object. :param str entity: An entity detected in the input. - :param List[int] location: An array of zero-based character offsets that - indicate where the detected entity values begin and end in the input text. :param str value: The entity value that was recognized in the user input. + :param List[int] location: (optional) An array of zero-based character + offsets that indicate where the detected entity values begin and end in the + input text. :param float confidence: (optional) A decimal percentage that represents Watson's confidence in the recognized entity. - :param dict metadata: (optional) Any metadata for the entity. + :param dict metadata: (optional) **Deprecated.** Any metadata for the + entity. + Beginning with the `2021-06-14` API version, the `metadata` property is no + longer returned. For information about system entities recognized in the + user input, see the `interpretation` property. :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :param RuntimeEntityInterpretation interpretation: (optional) An object @@ -8302,10 +8426,6 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': ) if 'location' in _dict: args['location'] = _dict.get('location') - else: - raise ValueError( - 'Required property \'location\' not present in RuntimeEntity JSON' - ) if 'value' in _dict: args['value'] = _dict.get('value') else: @@ -9993,9 +10113,8 @@ class WorkspaceSystemSettingsDisambiguation(): :attr bool enabled: (optional) Whether the disambiguation feature is enabled for the workspace. :attr str sensitivity: (optional) The sensitivity of the disambiguation feature - to intent detection conflicts. Set to **high** if you want the disambiguation - feature to be triggered more often. This can be useful for testing or - demonstration purposes. + to intent detection uncertainty. Higher sensitivity means that the + disambiguation feature is triggered more often and includes more choices. :attr bool randomize: (optional) Whether the order in which disambiguation suggestions are presented should be randomized (but still influenced by relative confidence). @@ -10024,9 +10143,8 @@ def __init__(self, :param bool enabled: (optional) Whether the disambiguation feature is enabled for the workspace. :param str sensitivity: (optional) The sensitivity of the disambiguation - feature to intent detection conflicts. Set to **high** if you want the - disambiguation feature to be triggered more often. This can be useful for - testing or demonstration purposes. + feature to intent detection uncertainty. Higher sensitivity means that the + disambiguation feature is triggered more often and includes more choices. :param bool randomize: (optional) Whether the order in which disambiguation suggestions are presented should be randomized (but still influenced by relative confidence). @@ -10110,12 +10228,16 @@ def __ne__(self, other: 'WorkspaceSystemSettingsDisambiguation') -> bool: class SensitivityEnum(str, Enum): """ - The sensitivity of the disambiguation feature to intent detection conflicts. Set - to **high** if you want the disambiguation feature to be triggered more often. - This can be useful for testing or demonstration purposes. + The sensitivity of the disambiguation feature to intent detection uncertainty. + Higher sensitivity means that the disambiguation feature is triggered more often + and includes more choices. """ AUTO = 'auto' HIGH = 'high' + MEDIUM_HIGH = 'medium_high' + MEDIUM = 'medium' + MEDIUM_LOW = 'medium_low' + LOW = 'low' class WorkspaceSystemSettingsOffTopic(): @@ -10551,12 +10673,14 @@ class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage( :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The URL of the image. + :attr str source: The `https:` URL of the image. :attr str title: (optional) An optional title to show before the response. :attr str description: (optional) An optional description to show with the response. :attr List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. + :attr str alt_text: (optional) Descriptive text that can be used for screen + readers or other situations where the image cannot be seen. """ def __init__(self, @@ -10565,19 +10689,22 @@ def __init__(self, *, title: str = None, description: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + channels: List['ResponseGenericChannel'] = None, + alt_text: str = None) -> None: """ Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :param str source: The URL of the image. + :param str source: The `https:` URL of the image. :param str title: (optional) An optional title to show before the response. :param str description: (optional) An optional description to show with the response. :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. + :param str alt_text: (optional) Descriptive text that can be used for + screen readers or other situations where the image cannot be seen. """ # pylint: disable=super-init-not-called self.response_type = response_type @@ -10585,6 +10712,7 @@ def __init__(self, self.title = title self.description = description self.channels = channels + self.alt_text = alt_text @classmethod def from_dict( @@ -10613,6 +10741,8 @@ def from_dict( ResponseGenericChannel.from_dict(x) for x in _dict.get('channels') ] + if 'alt_text' in _dict: + args['alt_text'] = _dict.get('alt_text') return cls(**args) @classmethod @@ -10633,6 +10763,8 @@ def to_dict(self) -> Dict: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: _dict['channels'] = [x.to_dict() for x in self.channels] + if hasattr(self, 'alt_text') and self.alt_text is not None: + _dict['alt_text'] = self.alt_text return _dict def _to_dict(self): @@ -11583,7 +11715,7 @@ class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The URL of the image. + :attr str source: The `https:` URL of the image. :attr str title: (optional) The title or introductory text to show before the response. :attr str description: (optional) The description to show with the the response. @@ -11591,6 +11723,8 @@ class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. + :attr str alt_text: (optional) Descriptive text that can be used for screen + readers or other situations where the image cannot be seen. """ def __init__(self, @@ -11599,14 +11733,15 @@ def __init__(self, *, title: str = None, description: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + channels: List['ResponseGenericChannel'] = None, + alt_text: str = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :param str source: The URL of the image. + :param str source: The `https:` URL of the image. :param str title: (optional) The title or introductory text to show before the response. :param str description: (optional) The description to show with the the @@ -11615,6 +11750,8 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. + :param str alt_text: (optional) Descriptive text that can be used for + screen readers or other situations where the image cannot be seen. """ # pylint: disable=super-init-not-called self.response_type = response_type @@ -11622,6 +11759,7 @@ def __init__(self, self.title = title self.description = description self.channels = channels + self.alt_text = alt_text @classmethod def from_dict( @@ -11650,6 +11788,8 @@ def from_dict( ResponseGenericChannel.from_dict(x) for x in _dict.get('channels') ] + if 'alt_text' in _dict: + args['alt_text'] = _dict.get('alt_text') return cls(**args) @classmethod @@ -11670,6 +11810,8 @@ def to_dict(self) -> Dict: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: _dict['channels'] = [x.to_dict() for x in self.channels] + if hasattr(self, 'alt_text') and self.alt_text is not None: + _dict['alt_text'] = self.alt_text return _dict def _to_dict(self): From c2ca53bf1bdc55790787d926ffa23f1cc12b3cee Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 9 Sep 2021 15:53:01 -0400 Subject: [PATCH 354/455] feat(assistant_v2): same as v1, add more properties --- ibm_watson/assistant_v2.py | 205 ++++++++++++++++++++++++++++++------- 1 file changed, 169 insertions(+), 36 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 1f0a52c87..ab82f6383 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -14,13 +14,16 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your apps and your users. The Assistant v2 API provides runtime methods your client application can use to send user input to an assistant and receive a response. + +API Version: 2.0 +See: https://cloud.ibm.com/docs/assistant """ from enum import Enum @@ -56,7 +59,7 @@ def __init__( Construct a new client for the Assistant service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2020-09-24`. + Specify dates in YYYY-MM-DD format. The current version is `2021-06-14`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md @@ -121,7 +124,7 @@ def create_session(self, assistant_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_session(self, assistant_id: str, session_id: str, @@ -171,7 +174,7 @@ def delete_session(self, assistant_id: str, session_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -259,7 +262,7 @@ def message(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def message_stateless(self, @@ -338,7 +341,7 @@ def message_stateless(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -401,7 +404,7 @@ def bulk_classify(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -472,7 +475,7 @@ def list_logs(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -522,7 +525,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response @@ -2286,9 +2289,23 @@ class MessageContextGlobalSystem(): 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. + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). This property is included only if the new system entities are enabled for the skill. + :attr str session_start_time: (optional) The time at which the session started. + With the stateful `message` method, the start time is always present, and is set + by the service based on the time the session was created. With the stateless + `message` method, the start time is set by the service in the response to the + first message, and should be returned as part of the context with each + subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for example, + `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :attr str state: (optional) An encoded string that represents the configuration + state of the assistant at the beginning of the conversation. If you are using + the stateless `message` method, save this value and then send it in the context + of the subsequent message request to avoid disruptions if there are + configuration changes during the conversation (such as a change to a skill the + assistant uses). """ def __init__(self, @@ -2297,7 +2314,9 @@ def __init__(self, user_id: str = None, turn_count: int = None, locale: str = None, - reference_time: str = None) -> None: + reference_time: str = None, + session_start_time: str = None, + state: str = None) -> None: """ Initialize a MessageContextGlobalSystem object. @@ -2332,15 +2351,31 @@ def __init__(self, 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. + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). This property is included only if the new system entities are enabled for the skill. + :param str session_start_time: (optional) The time at which the session + started. With the stateful `message` method, the start time is always + present, and is set by the service based on the time the session was + created. With the stateless `message` method, the start time is set by the + service in the response to the first message, and should be returned as + part of the context with each subsequent message in the session. + This value is a UTC time value formatted according to ISO 8601 (for + example, `2021-06-26T12:00:00Z` for noon UTC on 26 June 2021). + :param str state: (optional) An encoded string that represents the + configuration state of the assistant at the beginning of the conversation. + If you are using the stateless `message` method, save this value and then + send it in the context of the subsequent message request to avoid + disruptions if there are configuration changes during the conversation + (such as a change to a skill the assistant uses). """ self.timezone = timezone self.user_id = user_id self.turn_count = turn_count self.locale = locale self.reference_time = reference_time + self.session_start_time = session_start_time + self.state = state @classmethod def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': @@ -2356,6 +2391,10 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': args['locale'] = _dict.get('locale') if 'reference_time' in _dict: args['reference_time'] = _dict.get('reference_time') + if 'session_start_time' in _dict: + args['session_start_time'] = _dict.get('session_start_time') + if 'state' in _dict: + args['state'] = _dict.get('state') return cls(**args) @classmethod @@ -2376,6 +2415,12 @@ def to_dict(self) -> Dict: _dict['locale'] = self.locale if hasattr(self, 'reference_time') and self.reference_time is not None: _dict['reference_time'] = self.reference_time + if hasattr( + self, + 'session_start_time') and self.session_start_time is not None: + _dict['session_start_time'] = self.session_start_time + if hasattr(self, 'state') and self.state is not None: + _dict['state'] = self.state return _dict def _to_dict(self): @@ -2553,6 +2598,29 @@ def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of MessageContextSkillSystem""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of MessageContextSkillSystem""" + for _key in [ + k for k in vars(self).keys() + if k not in MessageContextSkillSystem._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in MessageContextSkillSystem._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this MessageContextSkillSystem object.""" return json.dumps(self.to_dict(), indent=2) @@ -2648,8 +2716,12 @@ class MessageInput(): """ An input object that includes the input text. - :attr str message_type: (optional) The type of user input. Currently, only text - input is supported. + :attr str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or actions skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. :attr str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the @@ -2674,8 +2746,12 @@ def __init__(self, """ Initialize a MessageInput object. - :param str message_type: (optional) The type of user input. Currently, only - text input is supported. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or actions skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. :param List[RuntimeIntent] intents: (optional) Intents to use when @@ -2762,9 +2838,15 @@ def __ne__(self, other: 'MessageInput') -> bool: class MessageTypeEnum(str, Enum): """ - The type of user input. Currently, only text input is supported. + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or actions skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. """ TEXT = 'text' + SEARCH = 'search' class MessageInputOptions(): @@ -3083,8 +3165,12 @@ class MessageInputStateless(): """ An input object that includes the input text. - :attr str message_type: (optional) The type of user input. Currently, only text - input is supported. + :attr str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or actions skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. :attr str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. :attr List[RuntimeIntent] intents: (optional) Intents to use when evaluating the @@ -3109,8 +3195,12 @@ def __init__(self, """ Initialize a MessageInputStateless object. - :param str message_type: (optional) The type of user input. Currently, only - text input is supported. + :param str message_type: (optional) The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or actions skill + is bypassed.) + **Note:** A `search` message results in an error if no search skill is + configured for the assistant. :param str text: (optional) The text of the user input. This string cannot contain carriage return, newline, or tab characters. :param List[RuntimeIntent] intents: (optional) Intents to use when @@ -3197,9 +3287,15 @@ def __ne__(self, other: 'MessageInputStateless') -> bool: class MessageTypeEnum(str, Enum): """ - The type of user input. Currently, only text input is supported. + The type of the message: + - `text`: The user input is processed normally by the assistant. + - `search`: Only search results are returned. (Any dialog or actions skill is + bypassed.) + **Note:** A `search` message results in an error if no search skill is configured + for the assistant. """ TEXT = 'text' + SEARCH = 'search' class MessageOutput(): @@ -3899,13 +3995,16 @@ class RuntimeEntity(): The entity value that was recognized in the user input. :attr str entity: An entity detected in the input. - :attr List[int] location: An array of zero-based character offsets that indicate - where the detected entity values begin and end in the input text. + :attr List[int] location: (optional) An array of zero-based character offsets + that indicate where the detected entity values begin and end in the input text. :attr str value: The term in the input text that was recognized as an entity value. :attr float confidence: (optional) A decimal percentage that represents Watson's confidence in the recognized entity. - :attr dict metadata: (optional) Any metadata for the entity. + :attr dict metadata: (optional) **Deprecated.** Any metadata for the entity. + Beginning with the `2021-06-14` API version, the `metadata` property is no + longer returned. For information about system entities recognized in the user + input, see the `interpretation` property. :attr List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :attr RuntimeEntityInterpretation interpretation: (optional) An object @@ -3928,9 +4027,9 @@ class RuntimeEntity(): def __init__(self, entity: str, - location: List[int], value: str, *, + location: List[int] = None, confidence: float = None, metadata: dict = None, groups: List['CaptureGroup'] = None, @@ -3941,13 +4040,18 @@ def __init__(self, Initialize a RuntimeEntity object. :param str entity: An entity detected in the input. - :param List[int] location: An array of zero-based character offsets that - indicate where the detected entity values begin and end in the input text. :param str value: The term in the input text that was recognized as an entity value. + :param List[int] location: (optional) An array of zero-based character + offsets that indicate where the detected entity values begin and end in the + input text. :param float confidence: (optional) A decimal percentage that represents Watson's confidence in the recognized entity. - :param dict metadata: (optional) Any metadata for the entity. + :param dict metadata: (optional) **Deprecated.** Any metadata for the + entity. + Beginning with the `2021-06-14` API version, the `metadata` property is no + longer returned. For information about system entities recognized in the + user input, see the `interpretation` property. :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :param RuntimeEntityInterpretation interpretation: (optional) An object @@ -3991,10 +4095,6 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': ) if 'location' in _dict: args['location'] = _dict.get('location') - else: - raise ValueError( - 'Required property \'location\' not present in RuntimeEntity JSON' - ) if 'value' in _dict: args['value'] = _dict.get('value') else: @@ -4934,6 +5034,29 @@ def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of SearchResultHighlight""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of SearchResultHighlight""" + for _key in [ + k for k in vars(self).keys() + if k not in SearchResultHighlight._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in SearchResultHighlight._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this SearchResultHighlight object.""" return json.dumps(self.to_dict(), indent=2) @@ -5691,13 +5814,15 @@ class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The URL of the image. + :attr str source: The `https:` URL of the image. :attr str title: (optional) The title to show before the response. :attr str description: (optional) The description to show with the the response. :attr List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. + :attr str alt_text: (optional) Descriptive text that can be used for screen + readers or other situations where the image cannot be seen. """ def __init__(self, @@ -5706,14 +5831,15 @@ def __init__(self, *, title: str = None, description: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + channels: List['ResponseGenericChannel'] = None, + alt_text: str = None) -> None: """ Initialize a RuntimeResponseGenericRuntimeResponseTypeImage object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :param str source: The URL of the image. + :param str source: The `https:` URL of the image. :param str title: (optional) The title to show before the response. :param str description: (optional) The description to show with the the response. @@ -5721,6 +5847,8 @@ def __init__(self, objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be handled by an API client. + :param str alt_text: (optional) Descriptive text that can be used for + screen readers or other situations where the image cannot be seen. """ # pylint: disable=super-init-not-called self.response_type = response_type @@ -5728,6 +5856,7 @@ def __init__(self, self.title = title self.description = description self.channels = channels + self.alt_text = alt_text @classmethod def from_dict( @@ -5756,6 +5885,8 @@ def from_dict( ResponseGenericChannel.from_dict(x) for x in _dict.get('channels') ] + if 'alt_text' in _dict: + args['alt_text'] = _dict.get('alt_text') return cls(**args) @classmethod @@ -5776,6 +5907,8 @@ def to_dict(self) -> Dict: _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: _dict['channels'] = [x.to_dict() for x in self.channels] + if hasattr(self, 'alt_text') and self.alt_text is not None: + _dict['alt_text'] = self.alt_text return _dict def _to_dict(self): From 9795c659a2c730df373244db563b9d4d3b4e7297 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 9 Sep 2021 15:56:05 -0400 Subject: [PATCH 355/455] refactor(docs): no significant changes --- ibm_watson/compare_comply_v1.py | 29 +-- ibm_watson/discovery_v1.py | 201 ++++++++++++------- ibm_watson/language_translator_v3.py | 31 +-- ibm_watson/natural_language_classifier_v1.py | 34 ++-- ibm_watson/personality_insights_v3.py | 7 +- ibm_watson/tone_analyzer_v3.py | 9 +- ibm_watson/visual_recognition_v3.py | 23 ++- ibm_watson/visual_recognition_v4.py | 45 +++-- 8 files changed, 227 insertions(+), 152 deletions(-) diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py index 6ecc8d374..1518ea731 100644 --- a/ibm_watson/compare_comply_v1.py +++ b/ibm_watson/compare_comply_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ IBM Watson™ Compare and Comply is discontinued. Existing instances are supported until 30 November 2021, but as of 1 December 2020, you can't create instances. Any @@ -25,6 +25,9 @@ {: deprecated} Compare and Comply analyzes governing documents to provide details about critical aspects of the documents. + +API Version: 1.0 +See: https://cloud.ibm.com/docs/compare-comply?topic=compare-comply-about """ from datetime import datetime @@ -132,7 +135,7 @@ def convert_to_html(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -187,7 +190,7 @@ def classify_elements(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -242,7 +245,7 @@ def extract_tables(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -314,7 +317,7 @@ def compare_documents(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -376,7 +379,7 @@ def add_feedback(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_feedback(self, @@ -488,7 +491,7 @@ def list_feedback(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_feedback(self, @@ -536,7 +539,7 @@ def get_feedback(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_feedback(self, @@ -584,7 +587,7 @@ def delete_feedback(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -690,7 +693,7 @@ def create_batch(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_batches(self, **kwargs) -> DetailedResponse: @@ -722,7 +725,7 @@ def list_batches(self, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_batch(self, batch_id: str, **kwargs) -> DetailedResponse: @@ -761,7 +764,7 @@ def get_batch(self, batch_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_batch(self, @@ -814,7 +817,7 @@ def update_batch(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index 3dc4d4d50..b9be41b35 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -14,13 +14,16 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ IBM Watson™ Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive better decision-making. Securely unify structured and unstructured data with pre-enriched content, and use a simplified query language to eliminate the need for manual filtering of results. + +API Version: 1.0 +See: https://cloud.ibm.com/docs/discovery """ from datetime import date @@ -130,7 +133,7 @@ def create_environment(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_environments(self, @@ -166,7 +169,7 @@ def list_environments(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_environment(self, environment_id: str, @@ -203,7 +206,7 @@ def get_environment(self, environment_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_environment(self, @@ -259,7 +262,7 @@ def update_environment(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_environment(self, environment_id: str, @@ -296,7 +299,7 @@ def delete_environment(self, environment_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_fields(self, environment_id: str, collection_ids: List[str], @@ -344,7 +347,7 @@ def list_fields(self, environment_id: str, collection_ids: List[str], headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -441,7 +444,7 @@ def create_configuration( params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_configurations(self, @@ -485,7 +488,7 @@ def list_configurations(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_configuration(self, environment_id: str, configuration_id: str, @@ -527,7 +530,7 @@ def get_configuration(self, environment_id: str, configuration_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_configuration( @@ -624,7 +627,7 @@ def update_configuration( params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_configuration(self, environment_id: str, configuration_id: str, @@ -673,7 +676,7 @@ def delete_configuration(self, environment_id: str, configuration_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -740,7 +743,7 @@ def create_collection(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_collections(self, @@ -784,7 +787,7 @@ def list_collections(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_collection(self, environment_id: str, collection_id: str, @@ -825,7 +828,7 @@ def get_collection(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_collection(self, @@ -888,7 +891,7 @@ def update_collection(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_collection(self, environment_id: str, collection_id: str, @@ -929,7 +932,7 @@ def delete_collection(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_collection_fields(self, environment_id: str, collection_id: str, @@ -972,7 +975,7 @@ def list_collection_fields(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1020,7 +1023,7 @@ def list_expansions(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_expansions(self, environment_id: str, collection_id: str, @@ -1088,7 +1091,7 @@ def create_expansions(self, environment_id: str, collection_id: str, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_expansions(self, environment_id: str, collection_id: str, @@ -1131,7 +1134,7 @@ def delete_expansions(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_tokenization_dictionary_status(self, environment_id: str, @@ -1177,7 +1180,7 @@ def get_tokenization_dictionary_status(self, environment_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_tokenization_dictionary( @@ -1238,7 +1241,7 @@ def create_tokenization_dictionary( params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_tokenization_dictionary(self, environment_id: str, @@ -1282,7 +1285,7 @@ def delete_tokenization_dictionary(self, environment_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_stopword_list_status(self, environment_id: str, collection_id: str, @@ -1325,7 +1328,7 @@ def get_stopword_list_status(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_stopword_list(self, @@ -1386,7 +1389,7 @@ def create_stopword_list(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_stopword_list(self, environment_id: str, collection_id: str, @@ -1429,7 +1432,7 @@ def delete_stopword_list(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1525,7 +1528,7 @@ def add_document(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_document_status(self, environment_id: str, collection_id: str, @@ -1575,7 +1578,7 @@ def get_document_status(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_document(self, @@ -1656,7 +1659,7 @@ def update_document(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_document(self, environment_id: str, collection_id: str, @@ -1705,7 +1708,7 @@ def delete_document(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1879,7 +1882,7 @@ def query(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def query_notices(self, @@ -2019,7 +2022,7 @@ def query_notices(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def federated_query(self, @@ -2183,7 +2186,7 @@ def federated_query(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def federated_query_notices(self, @@ -2307,7 +2310,7 @@ def federated_query_notices(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_autocompletion(self, @@ -2328,8 +2331,7 @@ def get_autocompletion(self, :param str environment_id: The ID of the environment. :param str collection_id: The ID of the collection. :param str prefix: The prefix to use for autocompletion. For example, the - prefix `Ho` could autocomplete to `Hot`, `Housing`, or `How do I upgrade`. - Possible completions are. + prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. :param str field: (optional) The field in the result documents that autocompletion suggestions are identified from. :param int count: (optional) The number of autocompletion suggestions to @@ -2372,7 +2374,7 @@ def get_autocompletion(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -2419,7 +2421,7 @@ def list_training_data(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def add_training_data(self, @@ -2487,7 +2489,7 @@ def add_training_data(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_all_training_data(self, environment_id: str, collection_id: str, @@ -2529,7 +2531,7 @@ def delete_all_training_data(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_training_data(self, environment_id: str, collection_id: str, @@ -2577,7 +2579,7 @@ def get_training_data(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_training_data(self, environment_id: str, collection_id: str, @@ -2624,7 +2626,7 @@ def delete_training_data(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_training_examples(self, environment_id: str, collection_id: str, @@ -2671,7 +2673,7 @@ def list_training_examples(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_training_example(self, @@ -2740,7 +2742,7 @@ def create_training_example(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_training_example(self, environment_id: str, collection_id: str, @@ -2792,7 +2794,7 @@ def delete_training_example(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_training_example(self, @@ -2859,7 +2861,7 @@ def update_training_example(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_training_example(self, environment_id: str, collection_id: str, @@ -2912,7 +2914,7 @@ def get_training_example(self, environment_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -2956,7 +2958,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -3008,7 +3010,7 @@ def create_event(self, type: str, data: 'EventData', params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def query_log(self, @@ -3072,7 +3074,7 @@ def query_log(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_metrics_query(self, @@ -3121,7 +3123,7 @@ def get_metrics_query(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_metrics_query_event(self, @@ -3171,7 +3173,7 @@ def get_metrics_query_event(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_metrics_query_no_results(self, @@ -3221,7 +3223,7 @@ def get_metrics_query_no_results(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_metrics_event_rate(self, @@ -3271,7 +3273,7 @@ def get_metrics_event_rate(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_metrics_query_token_event(self, @@ -3312,7 +3314,7 @@ def get_metrics_query_token_event(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -3358,7 +3360,7 @@ def list_credentials(self, environment_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_credentials(self, @@ -3437,7 +3439,7 @@ def create_credentials(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_credentials(self, environment_id: str, credential_id: str, @@ -3483,7 +3485,7 @@ def get_credentials(self, environment_id: str, credential_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_credentials(self, @@ -3566,7 +3568,7 @@ def update_credentials(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_credentials(self, environment_id: str, credential_id: str, @@ -3610,7 +3612,7 @@ def delete_credentials(self, environment_id: str, credential_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -3653,7 +3655,7 @@ def list_gateways(self, environment_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_gateway(self, @@ -3703,7 +3705,7 @@ def create_gateway(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_gateway(self, environment_id: str, gateway_id: str, @@ -3746,7 +3748,7 @@ def get_gateway(self, environment_id: str, gateway_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_gateway(self, environment_id: str, gateway_id: str, @@ -3789,7 +3791,7 @@ def delete_gateway(self, environment_id: str, gateway_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response @@ -6063,10 +6065,9 @@ class Enrichment(): are `natural_language_understanding` and `elements`. When using `natual_language_understanding`, the **options** object must contain Natural Language Understanding options. - When using `elements` the **options** object must contain Element - Classification options. Additionally, when using the `elements` enrichment the - configuration specified and files ingested must meet all the criteria specified - in [the + When using `elements` the **options** object must contain Element Classification + options. Additionally, when using the `elements` enrichment the configuration + specified and files ingested must meet all the criteria specified in [the documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-element-classification#element-classification). :attr bool ignore_downstream_errors: (optional) If true, then most errors generated during the enrichment process will be treated as warnings and will not @@ -6098,7 +6099,7 @@ def __init__(self, options are `natural_language_understanding` and `elements`. When using `natual_language_understanding`, the **options** object must contain Natural Language Understanding options. - When using `elements` the **options** object must contain Element + When using `elements` the **options** object must contain Element Classification options. Additionally, when using the `elements` enrichment the configuration specified and files ingested must meet all the criteria specified in [the @@ -6210,8 +6211,8 @@ class EnrichmentOptions(): (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. - :attr str model: (optional) *For use with `elements` enrichments only.* The - element extraction model to use. Models available are: `contract`. + :attr str model: (optional) For use with `elements` enrichments only. The + element extraction model to use. The only model available is `contract`. """ def __init__(self, @@ -6230,8 +6231,8 @@ def __init__(self, `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. - :param str model: (optional) *For use with `elements` enrichments only.* - The element extraction model to use. Models available are: `contract`. + :param str model: (optional) For use with `elements` enrichments only. The + element extraction model to use. The only model available is `contract`. """ self.features = features self.language = language @@ -9472,7 +9473,7 @@ class Notice(): `smart_document_understanding_failed_warning`, `smart_document_understanding_page_error`, `smart_document_understanding_page_warning`. **Note:** This is not a complete - list, other values might be returned. + list; other values might be returned. :attr datetime created: (optional) The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. :attr str document_id: (optional) Unique identifier of the document. @@ -9480,9 +9481,9 @@ class Notice(): training. :attr str severity: (optional) Severity level of the notice. :attr str step: (optional) Ingestion or training step in which the notice - occurred. Typical step values include: `classify_elements`, - `smartDocumentUnderstanding`, `ingestion`, `indexing`, `convert`. **Note:** This - is not a complete list, other values might be returned. + occurred. Typical step values include: `smartDocumentUnderstanding`, + `ingestion`, `indexing`, `convert`. **Note:** This is not a complete list; other + values might be returned. :attr str description: (optional) The description of the notice. """ @@ -10057,6 +10058,29 @@ def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of QueryNoticesResult""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in QueryNoticesResult._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of QueryNoticesResult""" + for _key in [ + k for k in vars(self).keys() + if k not in QueryNoticesResult._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in QueryNoticesResult._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this QueryNoticesResult object.""" return json.dumps(self.to_dict(), indent=2) @@ -10417,6 +10441,27 @@ def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of QueryResult""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() if k not in QueryResult._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of QueryResult""" + for _key in [ + k for k in vars(self).keys() if k not in QueryResult._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in QueryResult._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this QueryResult object.""" return json.dumps(self.to_dict(), indent=2) diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index d5b9b184d..59a3663d6 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -14,13 +14,16 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM-provided translation models that you can customize based on your unique terminology and language. Use Language Translator to take news from across the globe and present it in your language, communicate with your customers in their own language, and more. + +API Version: 3.0.0 +See: https://cloud.ibm.com/docs/language-translator """ from datetime import datetime @@ -112,7 +115,7 @@ def list_languages(self, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -188,7 +191,7 @@ def translate(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -226,7 +229,7 @@ def list_identifiable_languages(self, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: @@ -265,7 +268,7 @@ def identify(self, text: Union[str, TextIO], **kwargs) -> DetailedResponse: params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -320,7 +323,7 @@ def list_models(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_model(self, @@ -459,7 +462,7 @@ def create_model(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: @@ -497,7 +500,7 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_model(self, model_id: str, **kwargs) -> DetailedResponse: @@ -537,7 +540,7 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -573,7 +576,7 @@ def list_documents(self, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def translate_document(self, @@ -659,7 +662,7 @@ def translate_document(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_document_status(self, document_id: str, @@ -698,7 +701,7 @@ def get_document_status(self, document_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: @@ -735,7 +738,7 @@ def delete_document(self, document_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_translated_document(self, @@ -792,7 +795,7 @@ def get_translated_document(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py index 4049ac1f9..4b8543694 100644 --- a/ibm_watson/natural_language_classifier_v1.py +++ b/ibm_watson/natural_language_classifier_v1.py @@ -14,12 +14,22 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ -IBM Watson™ Natural Language Classifier uses machine learning algorithms to return -the top matching predefined classes for short text input. You create and train a -classifier to connect predefined classes to example texts so that the service can apply -those classes to new inputs. +On 9 August 2021, IBM announced the deprecation of IBM Watson™ Natural Language +Classifier. As of 9 September 2021, you cannot create new instances. However, existing +instances are supported until 8 August 2022. The service will no longer be available on 8 +August 2022.

As an alternative, consider migrating to IBM Watson Natural Language +Understanding. For more information, see [Migrating to Natural Language +Understanding](https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating). +{: deprecated} +Natural Language Classifier uses machine learning algorithms to return the top matching +predefined classes for short text input. You create and train a classifier to connect +predefined classes to example texts so that the service can apply those classes to new +inputs. + +API Version: 1.0 +See: https://cloud.ibm.com/docs/natural-language-classifier """ from datetime import datetime @@ -56,7 +66,7 @@ def __init__( :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md about initializing the authenticator of your choice. - """ + """ print( """ On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. @@ -121,7 +131,7 @@ def classify(self, classifier_id: str, text: str, headers=headers, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def classify_collection(self, classifier_id: str, @@ -171,7 +181,7 @@ def classify_collection(self, classifier_id: str, headers=headers, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -228,7 +238,7 @@ def create_classifier(self, training_metadata: BinaryIO, headers=headers, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_classifiers(self, **kwargs) -> DetailedResponse: @@ -255,7 +265,7 @@ def list_classifiers(self, **kwargs) -> DetailedResponse: url = '/v1/classifiers' request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_classifier(self, classifier_id: str, **kwargs) -> DetailedResponse: @@ -288,7 +298,7 @@ def get_classifier(self, classifier_id: str, **kwargs) -> DetailedResponse: url = '/v1/classifiers/{classifier_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_classifier(self, classifier_id: str, @@ -322,7 +332,7 @@ def delete_classifier(self, classifier_id: str, url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py index f049a5fcf..4ef2e1d75 100644 --- a/ibm_watson/personality_insights_v3.py +++ b/ibm_watson/personality_insights_v3.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ IBM Watson™ Personality Insights is discontinued. Existing instances are supported until 1 December 2021, but as of 1 December 2020, you cannot create new instances. Any @@ -45,6 +45,9 @@ **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. + +API Version: 3.4.4 +See: https://cloud.ibm.com/docs/personality-insights """ from enum import Enum @@ -233,7 +236,7 @@ def profile(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py index c1f45c4a2..61985fc5d 100644 --- a/ibm_watson/tone_analyzer_v3.py +++ b/ibm_watson/tone_analyzer_v3.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ The IBM Watson™ Tone Analyzer service uses linguistic analysis to detect emotional and language tones in written text. The service can analyze tone at both the document and @@ -25,6 +25,9 @@ **Note:** Request logging is disabled for the Tone Analyzer 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. + +API Version: 3.5.3 +See: https://cloud.ibm.com/docs/tone-analyzer """ from enum import Enum @@ -184,7 +187,7 @@ def tone(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def tone_chat(self, @@ -258,7 +261,7 @@ def tone_chat(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index cf371461c..431a379a5 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ IBM Watson™ Visual Recognition is discontinued. Existing instances are supported until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance @@ -23,6 +23,9 @@ The IBM Watson Visual Recognition service uses deep learning algorithms to identify scenes and objects in images that you upload to the service. You can create and train a custom classifier to identify subjects that suit your needs. + +API Version: 3.0 +See: https://cloud.ibm.com/docs/visual-recognition """ from datetime import datetime @@ -182,7 +185,7 @@ def classify(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -236,6 +239,7 @@ def create_classifier(self, :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Classifier` object """ + if name is None: raise ValueError('name must be provided') if not positive_examples: @@ -279,7 +283,7 @@ def create_classifier(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_classifiers(self, @@ -314,7 +318,7 @@ def list_classifiers(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_classifier(self, classifier_id: str, **kwargs) -> DetailedResponse: @@ -352,7 +356,7 @@ def get_classifier(self, classifier_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_classifier(self, @@ -406,6 +410,7 @@ def update_classifier(self, :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Classifier` object """ + if classifier_id is None: raise ValueError('classifier_id must be provided') headers = {} @@ -449,7 +454,7 @@ def update_classifier(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_classifier(self, classifier_id: str, @@ -486,7 +491,7 @@ def delete_classifier(self, classifier_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -531,7 +536,7 @@ def get_core_ml_model(self, classifier_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -576,7 +581,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index f1dd4200d..0c62cee04 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-a45d89ef-20201209-192237 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ IBM Watson™ Visual Recognition is discontinued. Existing instances are supported until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance @@ -22,6 +22,9 @@ {: deprecated} Provide images to the IBM Watson Visual Recognition service for analysis. The service detects objects based on a set of images with training data. + +API Version: 4.0 +See: https://cloud.ibm.com/docs/visual-recognition?topic=visual-recognition-object-detection-overview """ from datetime import date @@ -164,7 +167,7 @@ def analyze(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -227,7 +230,7 @@ def create_collection(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_collections(self, **kwargs) -> DetailedResponse: @@ -259,7 +262,7 @@ def list_collections(self, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_collection(self, collection_id: str, **kwargs) -> DetailedResponse: @@ -297,7 +300,7 @@ def get_collection(self, collection_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_collection(self, @@ -361,7 +364,7 @@ def update_collection(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_collection(self, collection_id: str, @@ -400,7 +403,7 @@ def delete_collection(self, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_model_file(self, collection_id: str, feature: str, @@ -455,7 +458,7 @@ def get_model_file(self, collection_id: str, feature: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -540,7 +543,7 @@ def add_images(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_images(self, collection_id: str, **kwargs) -> DetailedResponse: @@ -578,7 +581,7 @@ def list_images(self, collection_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_image_details(self, collection_id: str, image_id: str, @@ -621,7 +624,7 @@ def get_image_details(self, collection_id: str, image_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_image(self, collection_id: str, image_id: str, @@ -664,7 +667,7 @@ def delete_image(self, collection_id: str, image_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_jpeg_image(self, @@ -715,7 +718,7 @@ def get_jpeg_image(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -759,7 +762,7 @@ def list_object_metadata(self, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_object_metadata(self, collection_id: str, object: str, @@ -814,7 +817,7 @@ def update_object_metadata(self, collection_id: str, object: str, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_object_metadata(self, collection_id: str, object: str, @@ -857,7 +860,7 @@ def get_object_metadata(self, collection_id: str, object: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_object(self, collection_id: str, object: str, @@ -901,7 +904,7 @@ def delete_object(self, collection_id: str, object: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -945,7 +948,7 @@ def train(self, collection_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def add_image_training_data(self, @@ -1008,7 +1011,7 @@ def add_image_training_data(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_training_usage(self, @@ -1056,7 +1059,7 @@ def get_training_usage(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1101,7 +1104,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response From 67ee967726c022b9e883bef786cb82a59b86be28 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 9 Sep 2021 15:56:25 -0400 Subject: [PATCH 356/455] feat(stt&tts): new models added --- ibm_watson/speech_to_text_v1.py | 1156 ++++++++++++++++++------------- ibm_watson/text_to_speech_v1.py | 277 ++++---- 2 files changed, 815 insertions(+), 618 deletions(-) diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index b29557c08..f768b59b7 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's speech-recognition capabilities to produce transcripts of spoken audio. The service can @@ -22,11 +22,11 @@ transcription, the service can produce detailed information about many different aspects of the audio. It returns all JSON response content in the UTF-8 character set. The service supports two types of models: previous-generation models that include the -terms `Broadband` and `Narrowband` in their names, and beta next-generation models that -include the terms `Multimedia` and `Telephony` in their names. Broadband and multimedia -models have minimum sampling rates of 16 kHz. Narrowband and telephony models have minimum -sampling rates of 8 kHz. The beta next-generation models currently support fewer languages -and features, but they offer high throughput and greater transcription accuracy. +terms `Broadband` and `Narrowband` in their names, and next-generation models that include +the terms `Multimedia` and `Telephony` in their names. Broadband and multimedia models +have minimum sampling rates of 16 kHz. Narrowband and telephony models have minimum +sampling rates of 8 kHz. The next-generation models offer high throughput and greater +transcription accuracy. For speech recognition, the service supports synchronous and asynchronous HTTP Representational State Transfer (REST) interfaces. It also supports a WebSocket interface that provides a full-duplex, low-latency communication channel: Clients send requests and @@ -36,10 +36,13 @@ customization to adapt a base model for the acoustic characteristics of your audio. For language model customization, the service also supports grammars. A grammar is a formal language specification that lets you restrict the phrases that the service can recognize. -Language model customization and acoustic model customization are generally available for -production use with all previous-generation models that are generally available. Grammars -are beta functionality for all previous-generation models that support language model -customization. Next-generation models do not support customization at this time. +Language model customization is available for most previous- and next-generation models. +Acoustic model customization is available for all previous-generation models. Grammars are +beta functionality that is available for all previous-generation models that support +language model customization. + +API Version: 1.0.0 +See: https://cloud.ibm.com/docs/speech-to-text """ from enum import Enum @@ -116,7 +119,7 @@ def list_models(self, **kwargs) -> DetailedResponse: url = '/v1/models' request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_model(self, model_id: str, **kwargs) -> DetailedResponse: @@ -130,8 +133,9 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list). :param str model_id: The identifier of the model in the form of its name - from the output of the **Get a model** method. (**Note:** The model - `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.). + from the output of the [List models](#listmodels) method. (**Note:** The + model `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` + instead.). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `SpeechModel` object @@ -155,7 +159,7 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: url = '/v1/models/{model_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -251,28 +255,19 @@ def recognize(self, **See also:** [Supported audio formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats). ### Next-generation models - **Note:** The next-generation language models are beta functionality. They - support a limited number of languages and features at this time. The supported - languages, models, and features will increase with future releases. - The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 kHz) - models for many languages. Next-generation models have higher throughput than the - service's previous generation of `Broadband` and `Narrowband` models. When you use - next-generation models, the service can return transcriptions more quickly and + The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 + kHz) models for many languages. Next-generation models have higher throughput than + the service's previous generation of `Broadband` and `Narrowband` models. When you + use next-generation models, the service can return transcriptions more quickly and also provide noticeably better transcription accuracy. You specify a next-generation model by using the `model` query parameter, as you - do a previous-generation model. Next-generation models support the same request - headers as previous-generation models, but they support only the following - additional query parameters: - * `background_audio_suppression` - * `inactivity_timeout` - * `profanity_filter` - * `redaction` - * `smart_formatting` - * `speaker_labels` - * `speech_detector_sensitivity` - * `timestamps` - Many next-generation models also support the beta `low_latency` parameter, which - is not available with previous-generation models. + do a previous-generation model. Many next-generation models also support the + `low_latency` parameter, which is not available with previous-generation models. + But next-generation models do not support all of the parameters that are available + for use with previous-generation models. For more information about all parameters + that are supported for use with next-generation models, see [Supported features + for next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-features). **See also:** [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). ### Multipart speech recognition @@ -295,7 +290,8 @@ 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. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) See [Languages and + deprecated; use `ar-MS_BroadbandModel` instead.) See [Previous-generation + languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) and [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). @@ -397,7 +393,8 @@ def recognize(self, the final transcript of a recognition request. For US English, the service also converts certain keyword strings to punctuation symbols. By default, the service performs no smart formatting. - **Note:** Applies to US English, Japanese, and Spanish transcription only. + **Beta:** The parameter is beta functionality. Applies to US English, + Japanese, and Spanish transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). :param bool speaker_labels: (optional) If `true`, the response includes @@ -405,11 +402,14 @@ def recognize(self, multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - * For previous-generation models, can be used for US English, Australian - English, German, Japanese, Korean, and Spanish (both broadband and - narrowband models) and UK English (narrowband model) transcription only. - * For next-generation models, can be used for English (Australian, UK, and - US), German, and Spanish transcription only. + **Beta:** The parameter is beta functionality. + * For previous-generation models, the parameter can be used for Australian + English, US English, German, Japanese, Korean, and Spanish (both broadband + and narrowband models) and UK English (narrowband model) transcription + only. + * For next-generation models, the parameter can be used for English + (Australian, Indian, UK, and US), German, Japanese, Korean, and Spanish + transcription only. Restrictions and limitations apply to the use of speaker labels for both types of models. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). @@ -422,8 +422,9 @@ def recognize(self, use the `language_customization_id` parameter to specify the name of the 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 - [Using a grammar for speech + does not recognize other custom words from the model's words resource. + **Beta:** The parameter is beta functionality. + See [Using a grammar for speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUse). :param bool redaction: (optional) If `true`, the service redacts, or masks, numeric data from final transcripts. The feature redacts any number that @@ -436,7 +437,8 @@ def recognize(self, (ignores the `keywords` and `keywords_threshold` parameters) and returns only a single final transcript (forces the `max_alternatives` parameter to be `1`). - **Note:** Applies to US English, Japanese, and Korean transcription only. + **Beta:** The parameter is beta functionality. Applies to US English, + Japanese, and Korean transcription only. See [Numeric redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#numeric-redaction). :param bool audio_metrics: (optional) If `true`, requests detailed @@ -501,13 +503,11 @@ def recognize(self, previous-generation models. The `low_latency` parameter causes the models to produce results even more quickly, though the results might be less accurate when the parameter is used. - **Note:** The parameter is beta functionality. It is not available for - previous-generation `Broadband` and `Narrowband` models. It is available - only for some next-generation models. - * For a list of next-generation models that support low latency, see - [Supported language - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported) - for next-generation models. + The parameter is not available for previous-generation `Broadband` and + `Narrowband` models. It is available only for some next-generation models. + For a list of next-generation models that support low latency, see + [Supported next-generation language + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported). * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). :param dict headers: A `dict` containing the request headers @@ -563,7 +563,7 @@ def recognize(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -592,9 +592,9 @@ def register_callback(self, The service sends only a single `GET` request to the callback URL. If the service does not receive a reply with a response code of 200 and a body that echoes the challenge string sent by the service within five seconds, it does not allowlist - the URL; it instead sends status code 400 in response to the **Register a - callback** request. If the requested callback URL is already allowlisted, the - service responds to the initial registration request with response code 200. + the URL; it instead sends status code 400 in response to the request to register a + callback. If the requested callback URL is already allowlisted, the service + responds to the initial registration request with response code 200. If you specify a user secret with the request, the service uses it as a key to calculate an HMAC-SHA1 signature of the challenge string in its response to the `POST` request. It sends this signature in the `X-Callback-Signature` header of @@ -644,7 +644,7 @@ def register_callback(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def unregister_callback(self, callback_url: str, @@ -652,9 +652,10 @@ def unregister_callback(self, callback_url: str, """ Unregister a callback. - Unregisters a callback URL that was previously allowlisted with a **Register a - callback** request for use with the asynchronous interface. Once unregistered, the - URL can no longer be used with asynchronous recognition requests. + Unregisters a callback URL that was previously allowlisted with a [Register a + callback](#registercallback) 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/speech-to-text?topic=speech-to-text-async#unregister). @@ -683,7 +684,7 @@ def unregister_callback(self, callback_url: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_job(self, @@ -734,16 +735,16 @@ def create_job(self, to subscribe to specific events and to specify a string that is to be included with each notification for the job. * By polling the service: Omit the `callback_url`, `events`, and `user_token` - parameters. You must then use the **Check jobs** or **Check a job** methods to - check the status of the job, using the latter to retrieve the results when the job - is complete. + parameters. You must then use the [Check jobs](#checkjobs) or [Check a + job](#checkjob) methods to check the status of the job, using the latter to + retrieve the results when the job is complete. The two approaches are not mutually exclusive. You can poll the service for job status or obtain results from the service manually even if you include a callback URL. In both cases, you can include the `results_ttl` parameter to specify how long the results are to remain available after the job is complete. Using the - HTTPS **Check a job** method to retrieve results is more secure than receiving - them via callback notification over HTTP because it provides confidentiality in - addition to authentication and data integrity. + HTTPS [Check a job](#checkjob) method to retrieve results is more secure than + receiving them via callback notification over HTTP because it provides + confidentiality in addition to authentication and data integrity. The method supports the same basic parameters as other HTTP and WebSocket recognition requests. It also supports the following parameters specific to the asynchronous interface: @@ -807,28 +808,19 @@ def create_job(self, **See also:** [Supported audio formats](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-audio-formats). ### Next-generation models - **Note:** The next-generation language models are beta functionality. They - support a limited number of languages and features at this time. The supported - languages, models, and features will increase with future releases. - The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 kHz) - models for many languages. Next-generation models have higher throughput than the - service's previous generation of `Broadband` and `Narrowband` models. When you use - next-generation models, the service can return transcriptions more quickly and + The service supports next-generation `Multimedia` (16 kHz) and `Telephony` (8 + kHz) models for many languages. Next-generation models have higher throughput than + the service's previous generation of `Broadband` and `Narrowband` models. When you + use next-generation models, the service can return transcriptions more quickly and also provide noticeably better transcription accuracy. You specify a next-generation model by using the `model` query parameter, as you - do a previous-generation model. Next-generation models support the same request - headers as previous-generation models, but they support only the following - additional query parameters: - * `background_audio_suppression` - * `inactivity_timeout` - * `profanity_filter` - * `redaction` - * `smart_formatting` - * `speaker_labels` - * `speech_detector_sensitivity` - * `timestamps` - Many next-generation models also support the beta `low_latency` parameter, which - is not available with previous-generation models. + do a previous-generation model. Many next-generation models also support the + `low_latency` parameter, which is not available with previous-generation models. + But next-generation models do not support all of the parameters that are available + for use with previous-generation models. For more information about all parameters + that are supported for use with next-generation models, see [Supported features + for next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-features). **See also:** [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). @@ -838,15 +830,16 @@ 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. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) See [Languages and + deprecated; use `ar-MS_BroadbandModel` instead.) See [Previous-generation + languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) and [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). :param str callback_url: (optional) A URL to which callback notifications are to be sent. The URL must already be successfully allowlisted by using - the **Register a callback** method. You can include the same callback URL - with any number of job creation requests. Omit the parameter to poll the - service for job completion and results. + the [Register a callback](#registercallback) method. You can include the + same callback URL with any number of job creation requests. Omit the + parameter to poll the service for job completion and results. Use the `user_token` parameter to specify a unique user-specified string with each job to differentiate the callback notifications for the jobs. :param str events: (optional) If the job includes a callback URL, a @@ -855,8 +848,8 @@ def create_job(self, * `recognitions.started` generates a callback notification when the service begins to process the job. * `recognitions.completed` generates a callback notification when the job - is complete. You must use the **Check a job** method to retrieve the - results before they time out or are deleted. + is complete. You must use the [Check a job](#checkjob) method to retrieve + the results before they time out or are deleted. * `recognitions.completed_with_results` generates a callback notification when the job is complete. The notification includes the results of the request. @@ -976,7 +969,8 @@ def create_job(self, the final transcript of a recognition request. For US English, the service also converts certain keyword strings to punctuation symbols. By default, the service performs no smart formatting. - **Note:** Applies to US English, Japanese, and Spanish transcription only. + **Beta:** The parameter is beta functionality. Applies to US English, + Japanese, and Spanish transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). :param bool speaker_labels: (optional) If `true`, the response includes @@ -984,11 +978,14 @@ def create_job(self, multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - * For previous-generation models, can be used for US English, Australian - English, German, Japanese, Korean, and Spanish (both broadband and - narrowband models) and UK English (narrowband model) transcription only. - * For next-generation models, can be used for English (Australian, UK, and - US), German, and Spanish transcription only. + **Beta:** The parameter is beta functionality. + * For previous-generation models, the parameter can be used for Australian + English, US English, German, Japanese, Korean, and Spanish (both broadband + and narrowband models) and UK English (narrowband model) transcription + only. + * For next-generation models, the parameter can be used for English + (Australian, Indian, UK, and US), German, Japanese, Korean, and Spanish + transcription only. Restrictions and limitations apply to the use of speaker labels for both types of models. See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). @@ -1001,8 +998,9 @@ def create_job(self, use the `language_customization_id` parameter to specify the name of the 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 - [Using a grammar for speech + does not recognize other custom words from the model's words resource. + **Beta:** The parameter is beta functionality. + See [Using a grammar for speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUse). :param bool redaction: (optional) If `true`, the service redacts, or masks, numeric data from final transcripts. The feature redacts any number that @@ -1015,7 +1013,8 @@ def create_job(self, (ignores the `keywords` and `keywords_threshold` parameters) and returns only a single final transcript (forces the `max_alternatives` parameter to be `1`). - **Note:** Applies to US English, Japanese, and Korean transcription only. + **Beta:** The parameter is beta functionality. Applies to US English, + Japanese, and Korean transcription only. See [Numeric redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#numeric-redaction). :param bool processing_metrics: (optional) If `true`, requests processing @@ -1102,13 +1101,11 @@ def create_job(self, previous-generation models. The `low_latency` parameter causes the models to produce results even more quickly, though the results might be less accurate when the parameter is used. - **Note:** The parameter is beta functionality. It is not available for - previous-generation `Broadband` and `Narrowband` models. It is available - only for some next-generation models. - * For a list of next-generation models that support low latency, see - [Supported language - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported) - for next-generation models. + The parameter is not available for previous-generation `Broadband` and + `Narrowband` models. It is available only for some next-generation models. + For a list of next-generation models that support low latency, see + [Supported next-generation language + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-supported). * For more information about the `low_latency` parameter, see [Low latency](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-interim#low-latency). :param dict headers: A `dict` containing the request headers @@ -1170,7 +1167,7 @@ def create_job(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def check_jobs(self, **kwargs) -> DetailedResponse: @@ -1181,10 +1178,10 @@ def check_jobs(self, **kwargs) -> DetailedResponse: credentials with which it is called. The method also returns the creation and update times of each job, and, if a job was created with a callback URL and a user token, the user token for the job. To obtain the results for a job whose status is - `completed` or not one of the latest 100 outstanding jobs, use the **Check a job** - method. A job and its results remain available until you delete them with the - **Delete a job** method or until the job's time to live expires, whichever comes - first. + `completed` or not one of the latest 100 outstanding jobs, use the [Check a + job[(#checkjob) method. A job and its results remain available until you delete + them with the [Delete a job](#deletejob) 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/speech-to-text?topic=speech-to-text-async#jobs). @@ -1206,7 +1203,7 @@ def check_jobs(self, **kwargs) -> DetailedResponse: url = '/v1/recognitions' request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def check_job(self, id: str, **kwargs) -> DetailedResponse: @@ -1221,8 +1218,8 @@ def check_job(self, id: str, **kwargs) -> DetailedResponse: You can use the method to retrieve the results of any job, regardless of whether it was submitted with a callback URL and the `recognitions.completed_with_results` event, and you can retrieve the results multiple times for as long as they remain - available. Use the **Check jobs** method to request information about the most - recent jobs associated with the calling credentials. + available. Use the [Check jobs](#checkjobs) 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/speech-to-text?topic=speech-to-text-async#job). @@ -1252,7 +1249,7 @@ def check_job(self, id: str, **kwargs) -> DetailedResponse: url = '/v1/recognitions/{id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_job(self, id: str, **kwargs) -> DetailedResponse: @@ -1294,7 +1291,7 @@ def delete_job(self, id: str, **kwargs) -> DetailedResponse: url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1331,28 +1328,27 @@ def create_language_model(self, be customized by the new custom language model. The new custom model can be used only with the base model that it customizes. To determine whether a base model supports language model customization, - use the **Get a model** method and check that the attribute + use the [Get a model](#getmodel) 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/speech-to-text?topic=speech-to-text-customization#languageSupport). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). :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, - `en-US` is used for either of the US English language models. - For a Spanish language, the service creates a custom language model that is + `en-US` is used for the US English language models. All dialect values are + case-insensitive. + The parameter is meaningful only for Spanish language models, for which you + can always safely omit the parameter to have the service create the correct + mapping. For Spanish, the service creates a custom language model that is suited for speech in one of the following dialects: * `es-ES` for Castilian Spanish (`es-ES` models) * `es-LA` for Latin American Spanish (`es-AR`, `es-CL`, `es-CO`, and `es-PE` models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) - The parameter is meaningful only for Spanish models, for which you can - always safely omit the parameter to have the service create the correct - mapping. - If you specify the `dialect` parameter for non-Spanish language models, its - value must match the language of the base model. If you specify the - `dialect` for Spanish language models, its value must match one of the - defined mappings as indicated (`es-ES`, `es-LA`, or `es-MX`). All dialect - values are case-insensitive. + If you specify the `dialect` parameter for a non-Spanish language model, + its value must match the language of the base model. If you specify the + `dialect` for a Spanish language model, its value must match one of the + defined mappings (`es-ES`, `es-LA`, or `es-MX`). :param str description: (optional) A description of the new custom language model. Use a localized description that matches the language of the custom model. @@ -1391,7 +1387,7 @@ def create_language_model(self, headers=headers, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_language_models(self, @@ -1416,7 +1412,7 @@ def list_language_models(self, deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `LanguageModels` object @@ -1440,7 +1436,7 @@ def list_language_models(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_language_model(self, customization_id: str, @@ -1480,7 +1476,7 @@ def get_language_model(self, customization_id: str, url = '/v1/customizations/{customization_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_language_model(self, customization_id: str, @@ -1524,7 +1520,7 @@ def delete_language_model(self, customization_id: str, url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def train_language_model(self, @@ -1547,12 +1543,13 @@ def train_language_model(self, complete depending on the amount of data on which the service is being trained and the current load on the service. The method returns an HTTP 200 response code to indicate that the training process has begun. - You can monitor the status of the training by using the **Get a custom language - model** method to poll the model's status. Use a loop to check the status every 10 - seconds. The method returns a `LanguageModel` object that includes `status` and - `progress` fields. A status of `available` means that the custom model is trained - and ready to use. The service cannot accept subsequent training requests or - requests to add new resources until the existing request completes. + You can monitor the status of the training by using the [Get a custom language + model](#getlanguagemodel) method to poll the model's status. Use a loop to check + the status every 10 seconds. The method returns a `LanguageModel` object that + includes `status` and `progress` fields. A status of `available` means that the + custom model is trained 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/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language). ### Training failures @@ -1570,14 +1567,18 @@ def train_language_model(self, language model that is to be used for the request. You must make the request with credentials for the instance of the service that owns the custom model. - :param str word_type_to_add: (optional) The type of words from the custom - language model's words resource on which to train the model: + :param str word_type_to_add: (optional) _For custom models that are based + on previous-generation models_, the type of words from the custom language + model's words resource on which to train the model: * `all` (the default) trains the model on all new words, regardless of whether they were extracted from corpora or grammars or were added or modified by the user. - * `user` trains the model only on new words that were added or modified by - the user directly. The model is not trained on new words extracted from + * `user` trains the model only on custom words that were added or modified + by the user directly. The model is not trained on new words extracted from corpora or grammars. + _For custom models that are based on next-generation models_, the service + ignores the parameter. The words resource contains only custom words that + the user adds or modifies directly, so the parameter is unnecessary. :param float customization_weight: (optional) Specifies a customization weight for the custom language model. The customization weight tells the service how much weight to give to words from the custom language model @@ -1625,7 +1626,7 @@ def train_language_model(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def reset_language_model(self, customization_id: str, @@ -1670,7 +1671,7 @@ def reset_language_model(self, customization_id: str, **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def upgrade_language_model(self, customization_id: str, @@ -1686,12 +1687,15 @@ def upgrade_language_model(self, customization_id: str, that owns a model to upgrade it. The method returns an HTTP 200 response code to indicate that the upgrade process has begun successfully. You can monitor the status of the upgrade by using the - **Get a custom language model** method to poll the model's status. The method - returns a `LanguageModel` object that includes `status` and `progress` fields. Use - a loop to check the status every 10 seconds. While it is being upgraded, the - custom model has the status `upgrading`. When the upgrade is complete, the model - resumes the status that it had prior to upgrade. The service cannot accept - subsequent requests for the model until the upgrade completes. + [Get a custom language model](#getlanguagemodel) method to poll the model's + status. The method returns a `LanguageModel` object that includes `status` and + `progress` fields. Use a loop to check the status every 10 seconds. While it is + being upgraded, the custom model has the status `upgrading`. When the upgrade is + complete, the model resumes the status that it had prior to upgrade. The service + cannot accept subsequent requests for the model until the upgrade completes. + **Note:** Upgrading is necessary only for custom language models that are based on + previous-generation models. Only a single version of a custom model that is based + on a next-generation model is ever available. **See also:** [Upgrading a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language). @@ -1723,7 +1727,7 @@ def upgrade_language_model(self, customization_id: str, **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1735,9 +1739,10 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: List corpora. Lists information about all corpora from a custom language model. The information - includes the total number of words and out-of-vocabulary (OOV) words, name, and - status of each corpus. You must use credentials for the instance of the service - that owns a model to list its corpora. + includes the name, status, and total number of words for each corpus. _For custom + models that are based on previous-generation models_, it also includes the number + of out-of-vocabulary (OOV) words from 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/speech-to-text?topic=speech-to-text-manageCorpora#listCorpora). @@ -1769,7 +1774,7 @@ def list_corpora(self, customization_id: str, **kwargs) -> DetailedResponse: **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def add_corpus(self, @@ -1786,45 +1791,52 @@ def add_corpus(self, Use multiple requests to submit multiple corpus text files. You must use credentials for the instance of the service that owns a model to add a corpus to it. Adding a corpus does not affect the custom language model until you train the - model for the new data by using the **Train a custom language model** method. + model for the new data by using the [Train a custom language + model](#trainlanguagemodel) method. Submit a plain text file that contains sample sentences from the domain of - interest to enable the service to extract words in context. The more sentences you - add that represent the context in which speakers use words from the domain, the - better the service's recognition accuracy. + interest to enable the service to parse the words in context. The more sentences + you add that represent the context in which speakers use words from the domain, + the better the service's recognition accuracy. The call returns an HTTP 201 response code if the corpus is valid. The service - then asynchronously processes the contents of the corpus and automatically - extracts new words that it finds. This operation can take on the order of minutes - to complete depending on the total number of words and the number of new words in - the corpus, as well as the current load on the service. You cannot submit requests - to add additional resources to the custom model or to train the model until the - service's analysis of the corpus for the current request completes. Use the **List - a corpus** method to check the status of the analysis. - The service auto-populates the model's words resource with words from the corpus - that are not found in its base vocabulary. These words are referred to as - out-of-vocabulary (OOV) words. After adding a corpus, you must validate the words - resource to ensure that each OOV word's definition is complete and valid. You can - use the **List custom words** method to examine the words resource. You can use - other words method to eliminate typos and modify how words are pronounced as - needed. + then asynchronously processes and automatically extracts data from the contents of + the corpus. This operation can take on the order of minutes to complete depending + on the current load on the service, the total number of words in the corpus, and, + _for custom models that are based on previous-generation models_, the number of + new (out-of-vocabulary) words in the corpus. You cannot submit requests to add + additional resources to the custom model or to train the model until the service's + analysis of the corpus for the current request completes. Use the [Get a + corpus](#getcorpus) method to check the status of the analysis. + _For custom models that are based on previous-generation models_, the service + auto-populates the model's words resource with words from the corpus that are not + found in its base vocabulary. These words are referred to as out-of-vocabulary + (OOV) words. After adding a corpus, you must validate the words resource to ensure + that each OOV word's definition is complete and valid. You can use the [List + custom words](#listwords) method to examine the words resource. You can use other + words method to eliminate typos and modify how words are pronounced as needed. To add a corpus file that has the same name as an existing corpus, set the `allow_overwrite` parameter to `true`; otherwise, the request fails. Overwriting an existing corpus causes the service to process the corpus text file and extract - OOV words anew. Before doing so, it removes any OOV words associated with the - existing corpus from the model's words resource unless they were also added by - another corpus or grammar, or they have been modified in some way with the **Add - custom words** or **Add a custom word** method. + its data anew. _For a custom model that is based on a previous-generation model_, + the service first removes any OOV words that are associated with the existing + corpus from the model's words resource unless they were also added by another + corpus or grammar, or they have been modified in some way with the [Add custom + words](#addwords) or [Add a custom word](#addword) method. The service limits the overall amount of data that you can add to a custom model - to a maximum of 10 million total words from all sources combined. Also, you can - add no more than 90 thousand custom (OOV) words to a model. This includes words - that the service extracts from corpora and grammars, and words that you add - directly. + to a maximum of 10 million total words from all sources combined. _For a custom + model that is based on a previous-generation model_, you can add no more than 90 + thousand custom (OOV) words to a model. This includes words that the service + extracts from corpora and grammars, and words that you add directly. **See also:** * [Add a corpus to the custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addCorpus) - * [Working with - corpora](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingCorpora) - * [Validating a words - resource](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel). + * [Working with corpora for previous-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingCorpora) + * [Working with corpora for next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingCorpora-ng) + * [Validating a words resource for previous-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel) + * [Validating a words resource for next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng). :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 @@ -1850,9 +1862,9 @@ def add_corpus(self, characters; the service assumes UTF-8 encoding if it encounters non-ASCII characters. 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/speech-to-text?topic=speech-to-text-corporaWords#charEncoding). + that same encoding when working with the words in the custom language + model. For more information, see [Character encoding for custom + words](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageWords#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 @@ -1896,7 +1908,7 @@ def add_corpus(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_corpus(self, customization_id: str, corpus_name: str, @@ -1905,9 +1917,10 @@ def get_corpus(self, customization_id: str, corpus_name: str, Get a corpus. Gets information about a corpus from a custom language model. The information - includes the total number of words and out-of-vocabulary (OOV) words, name, and - status of the corpus. You must use credentials for the instance of the service - that owns a model to list its corpora. + includes the name, status, and total number of words for the corpus. _For custom + models that are based on previous-generation models_, it also includes the number + of out-of-vocabulary (OOV) words from 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/speech-to-text?topic=speech-to-text-manageCorpora#listCorpora). @@ -1943,7 +1956,7 @@ def get_corpus(self, customization_id: str, corpus_name: str, **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_corpus(self, customization_id: str, corpus_name: str, @@ -1951,14 +1964,15 @@ def delete_corpus(self, customization_id: str, corpus_name: str, """ Delete a corpus. - Deletes an existing corpus from a custom language model. The service removes any - out-of-vocabulary (OOV) words that are associated with the corpus from the custom - model's words resource unless they were also added by another corpus or grammar, - or they were modified in some way with the **Add custom words** or **Add a custom - word** method. Removing a corpus does not affect the custom model until you train - the 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 - corpora. + Deletes an existing corpus from a custom language model. Removing a corpus does + not affect the custom model until you train the model with the [Train a custom + language model](#trainlanguagemodel) method. You must use credentials for the + instance of the service that owns a model to delete its corpora. + _For custom models that are based on previous-generation models_, the service + removes any out-of-vocabulary (OOV) words that are associated with the corpus from + the custom model's words resource unless they were also added by another corpus or + grammar, or they were modified in some way with the [Add custom words](#addwords) + or [Add a custom word](#addword) method. **See also:** [Deleting a corpus from a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageCorpora#deleteCorpus). @@ -1996,7 +2010,7 @@ def delete_corpus(self, customization_id: str, corpus_name: str, url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -2014,10 +2028,11 @@ def list_words(self, Lists information about custom words from a custom language model. You can list all words from the custom model's words resource, only custom words that were - added or modified by the user, or only out-of-vocabulary (OOV) words that were - extracted from corpora or are recognized by grammars. You can also indicate the - order in which the service is to return words; by default, the service lists words - in ascending alphabetical order. You must use credentials for the instance of the + added or modified by the user, or, _for a custom model that is based on a + previous-generation model_, only out-of-vocabulary (OOV) words that were extracted + from corpora or are recognized by grammars. You can also indicate the order in + which the service is to return words; by default, the service lists words 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/speech-to-text?topic=speech-to-text-manageWords#listWords). @@ -2033,6 +2048,10 @@ def list_words(self, directly. * `corpora` shows only OOV that were extracted from corpora. * `grammars` shows only OOV words that are recognized by grammars. + _For a custom model that is based on a next-generation model_, only `all` + and `user` apply. Both options return the same results. Words from other + sources are not added to custom models that are based on next-generation + models. :param str sort: (optional) Indicates the order in which the words are to be listed, `alphabetical` or by `count`. You can prepend an optional `+` or `-` to an argument to indicate whether the results are to be sorted in @@ -2070,7 +2089,7 @@ def list_words(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def add_words(self, customization_id: str, words: List['CustomWord'], @@ -2078,34 +2097,38 @@ def add_words(self, customization_id: str, words: List['CustomWord'], """ Add custom words. - Adds one or more custom words to a custom language model. The service populates + Adds one or more custom words to a custom language model. You can use this method + to add words or to modify existing words in a custom model's words resource. _For + custom models that are based on previous-generation models_, the service populates the words resource for a custom model with out-of-vocabulary (OOV) words from each - corpus or grammar that is added to the model. You can use this method to add - additional words or to modify existing words in the words resource. The words + corpus or grammar that is added to the model. You can use this method to modify + OOV words in the model's words resource. + _For a custom model that is based on a previous-generation model_, the words resource for a model can contain a maximum of 90 thousand custom (OOV) words. This includes words that the service extracts from corpora and grammars and words that you add directly. You must use credentials for the instance of the service that owns a model to add or modify custom words for the model. Adding or modifying custom words does not affect the custom model until you train the model for the new data by using the - **Train a custom language model** method. + [Train a custom language model](#trainlanguagemodel) method. You add custom words by providing a `CustomWords` object, which is an array of - `CustomWord` objects, one per word. You must use the object's `word` parameter to - identify the word that is to be added. You can also provide one or both of the - optional `sounds_like` and `display_as` fields for each word. - * The `sounds_like` field provides an array of one or more pronunciations for the - word. Use the parameter to specify how the word can be pronounced by users. Use - the parameter for words that are difficult to pronounce, foreign words, acronyms, - and so on. For example, you might specify that the word `IEEE` can sound like `i - triple e`. You can specify a maximum of five sounds-like pronunciations for a - word. If you omit the `sounds_like` field, the service attempts to set the field - to its pronunciation of the word. It cannot generate a pronunciation for all - words, so you must review the word's definition to ensure that it is complete and - valid. + `CustomWord` objects, one per word. Use the object's `word` parameter to identify + the word that is to be added. You can also provide one or both of the optional + `display_as` or `sounds_like` fields for each word. * The `display_as` field provides a different way of spelling the word in a transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might - indicate that the word `IBM(trademark)` is to be displayed as `IBM™`. + indicate that the word `IBM` is to be displayed as `IBM™`. + * The `sounds_like` field, _which can be used only with a custom model that is + based on a previous-generation model_, provides an array of one or more + pronunciations for the word. Use the parameter to specify how the word can be + pronounced by users. Use the parameter for words that are difficult to pronounce, + foreign words, acronyms, and so on. For example, you might specify that the word + `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like + pronunciations for a word. If you omit the `sounds_like` field, the service + attempts to set the field to its pronunciation of the word. It cannot generate a + pronunciation for all words, so you must review the word's definition to ensure + that it is complete and valid. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error with the input data, it returns a failure code and @@ -2114,23 +2137,28 @@ def add_words(self, customization_id: str, words: List['CustomWord'], asynchronously processes the words to add them to the model's words resource. The time that it takes for the analysis to complete depends on the number of new words that you add but is generally faster than adding a corpus or grammar. - You can monitor the status of the request by using the **List a custom language - model** method to poll the model's status. Use a loop to check the status every 10 - seconds. The method returns a `Customization` object that includes a `status` - field. A status of `ready` means that the words have been added to the custom - model. The service cannot accept requests to add new data or to train the model - until the existing request completes. - You can use the **List custom words** or **List a custom word** method to review - the words that you add. Words with an invalid `sounds_like` field include an - `error` field that describes the problem. You can use other words-related methods - to correct errors, eliminate typos, and modify how words are pronounced as needed. + You can monitor the status of the request by using the [Get a custom language + model](#getlanguagemodel) method to poll the model's status. Use a loop to check + the status every 10 seconds. The method returns a `Customization` object that + includes a `status` field. A status of `ready` means that the words have been + added to the custom model. The service cannot accept requests to add new data or + to train the model until the existing request completes. + You can use the [List custom words](#listwords) or [Get a custom word](#getword) + method to review the words that you add. Words with an invalid `sounds_like` field + include an `error` field that describes the problem. You can use other + words-related methods to correct errors, eliminate typos, and modify how words are + pronounced as needed. **See also:** * [Add words to the custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords) - * [Working with custom - words](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords) - * [Validating a words - resource](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel). + * [Working with custom words for previous-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords) + * [Working with custom words for next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingWords-ng) + * [Validating a words resource for previous-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel) + * [Validating a words resource for next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng). :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 @@ -2174,7 +2202,7 @@ def add_words(self, customization_id: str, words: List['CustomWord'], headers=headers, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def add_word(self, @@ -2188,43 +2216,52 @@ def add_word(self, """ Add a custom word. - Adds a custom word to a custom language model. The service populates the words - resource for a custom model with out-of-vocabulary (OOV) words from each corpus or - grammar that is added to the model. You can use this method to add a word or to - modify an existing word in the words resource. The words resource for a model can - contain a maximum of 90 thousand custom (OOV) words. This includes words that the - service extracts from corpora and grammars and words that you add directly. + Adds a custom word to a custom language model. You can use this method to add a + word or to modify an existing word in the words resource. _For custom models that + are based on previous-generation models_, the service populates the words resource + for a custom model with out-of-vocabulary (OOV) words from each corpus or grammar + that is added to the model. You can use this method to modify OOV words in the + model's words resource. + _For a custom model that is based on a previous-generation models_, the words + resource for a model can contain a maximum of 90 thousand custom (OOV) words. This + includes words that the service extracts from corpora and grammars and words that + you add directly. You must use credentials for the instance of the service that owns a model to add or modify a custom word for the model. Adding or modifying a custom word does not affect the custom model until you train the model for the new data by using the - **Train a custom language model** method. + [Train a custom language model](#trainlanguagemodel) method. Use the `word_name` parameter to specify the custom word that is to be added or modified. Use the `CustomWord` object to provide one or both of the optional - `sounds_like` and `display_as` fields for the word. - * The `sounds_like` field provides an array of one or more pronunciations for the - word. Use the parameter to specify how the word can be pronounced by users. Use - the parameter for words that are difficult to pronounce, foreign words, acronyms, - and so on. For example, you might specify that the word `IEEE` can sound like `i - triple e`. You can specify a maximum of five sounds-like pronunciations for a - word. If you omit the `sounds_like` field, the service attempts to set the field - to its pronunciation of the word. It cannot generate a pronunciation for all - words, so you must review the word's definition to ensure that it is complete and - valid. + `display_as` or `sounds_like` fields for the word. * The `display_as` field provides a different way of spelling the word in a transcript. Use the parameter when you want the word to appear different from its usual representation or from its spelling in training data. For example, you might - indicate that the word `IBM(trademark)` is to be displayed as `IBM™`. + indicate that the word `IBM` is to be displayed as `IBM™`. + * The `sounds_like` field, _which can be used only with a custom model that is + based on a previous-generation model_, provides an array of one or more + pronunciations for the word. Use the parameter to specify how the word can be + pronounced by users. Use the parameter for words that are difficult to pronounce, + foreign words, acronyms, and so on. For example, you might specify that the word + `IEEE` can sound like `i triple e`. You can specify a maximum of five sounds-like + pronunciations for a word. If you omit the `sounds_like` field, the service + attempts to set the field to its pronunciation of the word. It cannot generate a + pronunciation for all words, so you must review the word's definition to ensure + that it is complete and valid. If you add a custom word that already exists in the words resource for the custom model, the new definition overwrites the existing data for the word. If the service encounters an error, it does not add the word to the words resource. Use - the **List a custom word** method to review the word that you add. + the [Get a custom word](#getword) method to review the word that you add. **See also:** * [Add words to the custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#addWords) - * [Working with custom - words](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords) - * [Validating a words - resource](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel). + * [Working with custom words for previous-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#workingWords) + * [Working with custom words for next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#workingWords-ng) + * [Validating a words resource for previous-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords#validateModel) + * [Validating a words resource for next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-corporaWords-ng#validateModel-ng). :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 @@ -2236,14 +2273,15 @@ def add_word(self, URL-encode the word if it includes non-ASCII characters. For more information, see [Character 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 `_` + :param str word: (optional) For the [Add custom words](#addwords) 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 `_` (underscore) to connect the tokens of compound words. - Omit this parameter for the **Add a custom word** method. - :param List[str] sounds_like: (optional) An array of sounds-like - pronunciations for the custom word. Specify how words that are difficult to - pronounce, foreign words, acronyms, and so on can be pronounced by users. + Omit this parameter for the [Add a custom word](#addword) method. + :param List[str] sounds_like: (optional) _For a custom model that is based + on a previous-generation model_, an array of sounds-like pronunciations for + the custom word. Specify how words that are difficult to pronounce, foreign + words, acronyms, and so on can be pronounced by users. * For a word that is not in the service's base vocabulary, omit the parameter to have the service automatically generate a sounds-like pronunciation for the word. @@ -2253,6 +2291,9 @@ def add_word(self, pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. + _For a custom model that is based on a next-generation model_, omit this + field. Custom models based on next-generation models do not support the + `sounds_like` field. The service ignores the field. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or @@ -2295,7 +2336,7 @@ def add_word(self, headers=headers, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_word(self, customization_id: str, word_name: str, @@ -2343,7 +2384,7 @@ def get_word(self, customization_id: str, word_name: str, **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_word(self, customization_id: str, word_name: str, @@ -2353,11 +2394,11 @@ def delete_word(self, customization_id: str, word_name: str, Deletes a custom word from a custom language model. You can remove any word that you added to the custom model's words resource via any means. However, if the word - also exists in the service's base vocabulary, the service removes only the custom - pronunciation for the word; the word remains in the base vocabulary. Removing a + also exists in the service's base vocabulary, the service removes the word only + from the words resource; the word remains in the base vocabulary. Removing a custom word does not affect the custom model until you train the 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 words. + [Train a custom language model](#trainlanguagemodel) 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/speech-to-text?topic=speech-to-text-manageWords#deleteWord). @@ -2397,7 +2438,7 @@ def delete_word(self, customization_id: str, word_name: str, url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -2412,7 +2453,10 @@ def list_grammars(self, customization_id: str, Lists information about all grammars from a custom language model. The information includes the total number of out-of-vocabulary (OOV) words, name, and status of each grammar. You must use credentials for the instance of the service that owns a - model to list its grammars. + model to list its grammars. Grammars are available for all languages and models + that support language customization. + **Note:** Grammars are supported only for use with previous-generation models. + They are not supported for next-generation models. **See also:** [Listing grammars from a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars). @@ -2444,7 +2488,7 @@ def list_grammars(self, customization_id: str, **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def add_grammar(self, @@ -2462,32 +2506,37 @@ def add_grammar(self, UTF-8 format that defines the grammar. Use multiple requests to submit multiple grammar files. You must use credentials for the instance of the service that owns a model to add a grammar to it. Adding a grammar does not affect the custom - language model until you train the model for the new data by using the **Train a - custom language model** method. + language model until you train the model for the new data by using the [Train a + custom language model](#trainlanguagemodel) method. The call returns an HTTP 201 response code if the grammar is valid. The service then asynchronously processes the contents of the grammar and automatically extracts new words that it finds. This operation can take a few seconds or minutes to complete depending on the size and complexity of the grammar, as well as the current load on the service. You cannot submit requests to add additional resources to the custom model or to train the model until the service's analysis - of the grammar for the current request completes. Use the **Get a grammar** method - to check the status of the analysis. + of the grammar for the current request completes. Use the [Get a + grammar](#getgrammar) method to check the status of the analysis. The service populates the model's words resource with any word that is recognized by the grammar that is not found in the model's base vocabulary. These are - referred to as out-of-vocabulary (OOV) words. You can use the **List custom - words** method to examine the words resource and use other words-related methods - to eliminate typos and modify how words are pronounced as needed. + referred to as out-of-vocabulary (OOV) words. You can use the [List custom + words](#listwords) method to examine the words resource and use other + words-related methods to eliminate typos and modify how words are pronounced as + needed. To add a grammar that has the same name as an existing grammar, set the `allow_overwrite` parameter to `true`; otherwise, the request fails. Overwriting an existing grammar causes the service to process the grammar file and extract OOV words anew. Before doing so, it removes any OOV words associated with the existing grammar from the model's words resource unless they were also added by another - resource or they have been modified in some way with the **Add custom words** or - **Add a custom word** method. + resource or they have been modified in some way with the [Add custom + words](#addwords) or [Add a custom word](#addword) method. The service limits the overall amount of data that you can add to a custom model to a maximum of 10 million total words from all sources combined. Also, you can add no more than 90 thousand OOV words to a model. This includes words that the service extracts from corpora and grammars and words that you add directly. + Grammars are available for all languages and models that support language + customization. + **Note:** Grammars are supported only for use with previous-generation models. + They are not supported for next-generation models. **See also:** * [Understanding grammars](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUnderstand#grammarUnderstand) @@ -2568,7 +2617,7 @@ def add_grammar(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_grammar(self, customization_id: str, grammar_name: str, @@ -2579,7 +2628,10 @@ def get_grammar(self, customization_id: str, grammar_name: str, Gets information about a grammar from a custom language model. The information includes the total number of out-of-vocabulary (OOV) words, name, and status of the grammar. You must use credentials for the instance of the service that owns a - model to list its grammars. + model to list its grammars. Grammars are available for all languages and models + that support language customization. + **Note:** Grammars are supported only for use with previous-generation models. + They are not supported for next-generation models. **See also:** [Listing grammars from a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars). @@ -2616,7 +2668,7 @@ def get_grammar(self, customization_id: str, grammar_name: str, **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_grammar(self, customization_id: str, grammar_name: str, @@ -2627,10 +2679,14 @@ def delete_grammar(self, customization_id: str, grammar_name: str, Deletes an existing grammar from a custom language model. The service removes any out-of-vocabulary (OOV) words associated with the grammar from the custom model's words resource unless they were also added by another resource or they were - modified in some way with the **Add custom words** or **Add a custom word** - method. Removing a grammar does not affect the custom model until you train the - 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. + modified in some way with the [Add custom words](#addwords) or [Add a custom + word](#addword) method. Removing a grammar does not affect the custom model until + you train the model with the [Train a custom language model](#trainlanguagemodel) + method. You must use credentials for the instance of the service that owns a model + to delete its grammar. Grammars are available for all languages and models that + support language customization. + **Note:** Grammars are supported only for use with previous-generation models. + They are not supported for next-generation models. **See also:** [Deleting a grammar from a custom language model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#deleteGrammar). @@ -2669,7 +2725,7 @@ def delete_grammar(self, customization_id: str, grammar_name: str, url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -2693,6 +2749,8 @@ def create_acoustic_model(self, The service returns an error if you attempt to create more than 1024 models. You do not lose any models, but you cannot create any more until your model count is below the limit. + **Note:** Acoustic model customization is supported only for use with + previous-generation models. It is not supported for next-generation models. **See also:** [Create a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#createModel-acoustic). @@ -2707,7 +2765,7 @@ def create_acoustic_model(self, `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) To determine whether a base model supports acoustic model customization, refer to [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). :param str description: (optional) A description of the new custom acoustic model. Use a localized description that matches the language of the custom model. @@ -2745,7 +2803,7 @@ def create_acoustic_model(self, headers=headers, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_acoustic_models(self, @@ -2760,6 +2818,8 @@ def list_acoustic_models(self, the specified language. Omit the parameter to see all custom acoustic models for all languages. You must use credentials for the instance of the service that owns a model to list information about it. + **Note:** Acoustic model customization is supported only for use with + previous-generation models. It is not supported for next-generation models. **See also:** [Listing custom acoustic models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). @@ -2770,7 +2830,7 @@ def list_acoustic_models(self, deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `AcousticModels` object @@ -2794,7 +2854,7 @@ def list_acoustic_models(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_acoustic_model(self, customization_id: str, @@ -2804,6 +2864,8 @@ 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. + **Note:** Acoustic model customization is supported only for use with + previous-generation models. It is not supported for next-generation models. **See also:** [Listing custom acoustic models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#listModels-acoustic). @@ -2835,7 +2897,7 @@ def get_acoustic_model(self, customization_id: str, **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_acoustic_model(self, customization_id: str, @@ -2847,6 +2909,8 @@ def delete_acoustic_model(self, customization_id: str, another request, such as adding an audio resource to the model, is currently being processed. You must use credentials for the instance of the service that owns a model to delete it. + **Note:** Acoustic model customization is supported only for use with + previous-generation models. It is not supported for next-generation models. **See also:** [Deleting a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#deleteModel-acoustic). @@ -2880,7 +2944,7 @@ def delete_acoustic_model(self, customization_id: str, url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def train_acoustic_model(self, @@ -2905,14 +2969,14 @@ def train_acoustic_model(self, takes approximately 2 hours to train a model that contains a total of 2 hours of audio. The method returns an HTTP 200 response code to indicate that the training process has begun. - You can monitor the status of the training by using the **Get a custom acoustic - model** method to poll the model's status. Use a loop to check the status once a - minute. The method returns an `AcousticModel` object that includes `status` and - `progress` fields. A status of `available` indicates that the custom model is - trained and ready to use. The service cannot train a model while it is handling - another request for the model. The service cannot accept subsequent training - requests, or requests to add new audio resources, until the existing training - request completes. + You can monitor the status of the training by using the [Get a custom acoustic + model](#getacousticmodel) method to poll the model's status. Use a loop to check + the status once a minute. The method returns an `AcousticModel` object that + includes `status` and `progress` fields. A status of `available` indicates that + the custom model is trained and ready to use. The service cannot train a model + while it is handling another request for the model. The service cannot accept + subsequent training requests, or requests to add new audio resources, until the + existing training request completes. You can use the optional `custom_language_model_id` parameter to specify the GUID of a separately created custom language model that is to be used during training. Train with a custom language model if you have verbatim transcriptions of the @@ -2921,6 +2985,8 @@ def train_acoustic_model(self, files. For training to succeed, both of the custom models must be based on the same version of the same base model, and the custom language model must be fully trained and available. + **Note:** Acoustic model customization is supported only for use with + previous-generation models. It is not supported for next-generation models. **See also:** * [Train the custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#trainModel-acoustic) @@ -2985,7 +3051,7 @@ def train_acoustic_model(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def reset_acoustic_model(self, customization_id: str, @@ -3001,6 +3067,8 @@ def reset_acoustic_model(self, customization_id: str, service cannot accept subsequent requests for the model until the existing reset request completes. You must use credentials for the instance of the service that owns a model to reset it. + **Note:** Acoustic model customization is supported only for use with + previous-generation models. It is not supported for next-generation models. **See also:** [Resetting a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAcousticModels#resetModel-acoustic). @@ -3032,7 +3100,7 @@ def reset_acoustic_model(self, customization_id: str, **path_param_dict) request = self.prepare_request(method='POST', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def upgrade_acoustic_model(self, @@ -3053,19 +3121,21 @@ def upgrade_acoustic_model(self, for the instance of the service that owns a model to upgrade it. The method returns an HTTP 200 response code to indicate that the upgrade process has begun successfully. You can monitor the status of the upgrade by using the - **Get a custom acoustic model** method to poll the model's status. The method - returns an `AcousticModel` object that includes `status` and `progress` fields. - Use a loop to check the status once a minute. While it is being upgraded, the - custom model has the status `upgrading`. When the upgrade is complete, the model - resumes the status that it had prior to upgrade. The service cannot upgrade a - model while it is handling another request for the model. The service cannot - accept subsequent requests for the model until the existing upgrade request - completes. + [Get a custom acoustic model](#getacousticmodel) method to poll the model's + status. The method returns an `AcousticModel` object that includes `status` and + `progress` fields. Use a loop to check the status once a minute. While it is being + upgraded, the custom model has the status `upgrading`. When the upgrade is + complete, the model resumes the status that it had prior to upgrade. The service + cannot upgrade a model while it is handling another request for the model. The + service cannot accept subsequent requests for the model until the existing upgrade + request completes. If the custom acoustic model was trained with a separately created custom language model, you must use the `custom_language_model_id` parameter to specify the GUID of that custom language model. The custom language model must be upgraded before the custom acoustic model can be upgraded. Omit the parameter if the custom acoustic model was not trained with a custom language model. + **Note:** Acoustic model customization is supported only for use with + previous-generation models. It is not supported for next-generation models. **See also:** [Upgrading a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-acoustic). @@ -3118,7 +3188,7 @@ def upgrade_acoustic_model(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -3135,6 +3205,8 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: which is important for checking the service's analysis of the resource in response 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. + **Note:** Acoustic model customization is supported only for use with + previous-generation models. It is not supported for next-generation models. **See also:** [Listing audio resources for a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#listAudio). @@ -3166,7 +3238,7 @@ def list_audio(self, customization_id: str, **kwargs) -> DetailedResponse: **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def add_audio(self, @@ -3185,8 +3257,8 @@ def add_audio(self, the acoustic characteristics of the audio that you plan to transcribe. You must use credentials for the instance of the service that owns a model to add an audio resource to it. Adding audio data does not affect the custom acoustic model until - you train the model for the new data by using the **Train a custom acoustic - model** method. + you train the model for the new data by using the [Train a custom acoustic + model](#trainacousticmodel) method. You can add individual audio files or an archive file that contains multiple audio files. Adding multiple audio files via a single archive file is significantly more efficient than adding each file individually. You can add audio resources in any @@ -3207,11 +3279,13 @@ def add_audio(self, its length, sampling rate, and encoding. You cannot submit requests to train or upgrade the model until the service's analysis of all audio resources for current requests completes. - To determine the status of the service's analysis of the audio, use the **Get an - audio resource** method to poll the status of the audio. The method accepts the - customization ID of the custom model and the name of the audio resource, and it - returns the status of the resource. Use a loop to check the status of the audio - every few seconds until it becomes `ok`. + To determine the status of the service's analysis of the audio, use the [Get an + audio resource](#getaudio) method to poll the status of the audio. The method + accepts the customization ID of the custom model and the name of the audio + resource, and it returns the status of the resource. Use a loop to check the + status of the audio every few seconds until it becomes `ok`. + **Note:** Acoustic model customization is supported only for use with + previous-generation models. It is not supported for next-generation models. **See also:** [Add audio to the custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#addAudio). ### Content types for audio-type resources @@ -3292,8 +3366,8 @@ def add_audio(self, For an archive-type resource, the media type of the archive file. For more information, see **Content types for archive-type resources** in the method description. - :param str contained_content_type: (optional) **For an archive-type - resource,** specify the format of the audio files that are contained in the + :param str contained_content_type: (optional) _For an archive-type + resource_, specify the format of the audio files that are contained in the archive file if they are of type `audio/alaw`, `audio/basic`, `audio/l16`, or `audio/mulaw`. Include the `rate`, `channels`, and `endianness` parameters where necessary. In this case, all audio files that are @@ -3304,7 +3378,7 @@ def add_audio(self, The parameter accepts all of the audio formats that are supported for use with speech recognition. For more information, see **Content types for audio-type resources** in the method description. - **For an audio-type resource,** omit the header. + _For an audio-type resource_, omit the header. :param bool allow_overwrite: (optional) If `true`, the specified audio resource overwrites an existing audio resource with the same name. If `false`, the request fails if an audio resource with the same name already @@ -3349,7 +3423,7 @@ def add_audio(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_audio(self, customization_id: str, audio_name: str, @@ -3360,21 +3434,23 @@ def get_audio(self, customization_id: str, audio_name: str, Gets information about an audio resource from a custom acoustic model. The method returns an `AudioListing` object whose fields depend on the type of audio resource that you specify with the method's `audio_name` parameter: - * **For an audio-type resource,** the object's fields match those of an + * _For an audio-type resource_, the object's fields match those of an `AudioResource` object: `duration`, `name`, `details`, and `status`. - * **For an archive-type resource,** the object includes a `container` field whose + * _For an archive-type resource_, the object includes a `container` field whose fields match those of an `AudioResource` object. It also includes an `audio` field, which contains an array of `AudioResource` objects that provides information about the audio files that are contained in the archive. The information includes the status of the specified audio resource. The status is important for checking the service's analysis of a resource that you add to the custom model. - * For an audio-type resource, the `status` field is located in the `AudioListing` - object. - * For an archive-type resource, the `status` field is located in the + * _For an audio-type resource_, the `status` field is located in the + `AudioListing` object. + * _For an archive-type resource_, the `status` field is located in the `AudioResource` object that is returned in the `container` field. You must use credentials for the instance of the service that owns a model to list its audio resources. + **Note:** Acoustic model customization is supported only for use with + previous-generation models. It is not supported for next-generation models. **See also:** [Listing audio resources for a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#listAudio). @@ -3410,7 +3486,7 @@ def get_audio(self, customization_id: str, audio_name: str, **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_audio(self, customization_id: str, audio_name: str, @@ -3422,10 +3498,13 @@ def delete_audio(self, customization_id: str, audio_name: str, archive-type audio resource removes the entire archive of files. The service does not allow deletion of individual files from an archive resource. Removing an audio resource does not affect the custom model until you train the - model on its updated data by using the **Train a custom acoustic model** method. - You can delete an existing audio resource from a model while a different resource - 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. + model on its updated data by using the [Train a custom acoustic + model](#trainacousticmodel) method. You can delete an existing audio resource from + a model while a different resource 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. + **Note:** Acoustic model customization is supported only for use with + previous-generation models. It is not supported for next-generation models. **See also:** [Deleting an audio resource from a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageAudio#deleteAudio). @@ -3463,7 +3542,7 @@ def delete_audio(self, customization_id: str, audio_name: str, url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -3515,7 +3594,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response @@ -3526,9 +3605,9 @@ class GetModelEnums: class ModelId(str, Enum): """ - The identifier of the model in the form of its name from the output of the **Get a - model** method. (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use - `ar-MS_BroadbandModel` instead.). + The identifier of the model in the form of its name from the output of the [List + models](#listmodels) method. (**Note:** The model `ar-AR_BroadbandModel` is + deprecated; use `ar-MS_BroadbandModel` instead.). """ AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' @@ -3542,6 +3621,7 @@ class ModelId(str, Enum): EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' + EN_IN_TELEPHONY = 'en-IN_Telephony' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' EN_US_MULTIMEDIA = 'en-US_Multimedia' EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' @@ -3564,15 +3644,21 @@ class ModelId(str, Enum): FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' + FR_FR_MULTIMEDIA = 'fr-FR_Multimedia' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' FR_FR_TELEPHONY = 'fr-FR_Telephony' + HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' + JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' + KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + KO_KR_TELEPHONY = 'ko-KR_Telephony' + NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' @@ -3613,7 +3699,7 @@ class Model(str, Enum): """ The identifier of the model that is to be used for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use - `ar-MS_BroadbandModel` instead.) See [Languages and + `ar-MS_BroadbandModel` instead.) See [Previous-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) and [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). @@ -3627,6 +3713,7 @@ class Model(str, Enum): EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_AU_TELEPHONY = 'en-AU_Telephony' + EN_IN_TELEPHONY = 'en-IN_Telephony' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' @@ -3652,15 +3739,21 @@ class Model(str, Enum): FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' + FR_FR_MULTIMEDIA = 'fr-FR_Multimedia' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' FR_FR_TELEPHONY = 'fr-FR_Telephony' + HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' + JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' + KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + KO_KR_TELEPHONY = 'ko-KR_Telephony' + NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' @@ -3701,7 +3794,7 @@ class Model(str, Enum): """ The identifier of the model that is to be used for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use - `ar-MS_BroadbandModel` instead.) See [Languages and + `ar-MS_BroadbandModel` instead.) See [Previous-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) and [Next-generation languages and models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). @@ -3715,6 +3808,7 @@ class Model(str, Enum): EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_AU_TELEPHONY = 'en-AU_Telephony' + EN_IN_TELEPHONY = 'en-IN_Telephony' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' @@ -3740,15 +3834,21 @@ class Model(str, Enum): FR_CA_NARROWBANDMODEL = 'fr-CA_NarrowbandModel' FR_CA_TELEPHONY = 'fr-CA_Telephony' FR_FR_BROADBANDMODEL = 'fr-FR_BroadbandModel' + FR_FR_MULTIMEDIA = 'fr-FR_Multimedia' FR_FR_NARROWBANDMODEL = 'fr-FR_NarrowbandModel' FR_FR_TELEPHONY = 'fr-FR_Telephony' + HI_IN_TELEPHONY = 'hi-IN_Telephony' IT_IT_BROADBANDMODEL = 'it-IT_BroadbandModel' IT_IT_NARROWBANDMODEL = 'it-IT_NarrowbandModel' IT_IT_TELEPHONY = 'it-IT_Telephony' JA_JP_BROADBANDMODEL = 'ja-JP_BroadbandModel' + JA_JP_MULTIMEDIA = 'ja-JP_Multimedia' JA_JP_NARROWBANDMODEL = 'ja-JP_NarrowbandModel' KO_KR_BROADBANDMODEL = 'ko-KR_BroadbandModel' + KO_KR_MULTIMEDIA = 'ko-KR_Multimedia' KO_KR_NARROWBANDMODEL = 'ko-KR_NarrowbandModel' + KO_KR_TELEPHONY = 'ko-KR_Telephony' + NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' @@ -3764,8 +3864,8 @@ class Events(str, Enum): * `recognitions.started` generates a callback notification when the service begins to process the job. * `recognitions.completed` generates a callback notification when the job is - complete. You must use the **Check a job** method to retrieve the results before - they time out or are deleted. + complete. You must use the [Check a job](#checkjob) method to retrieve the results + before they time out or are deleted. * `recognitions.completed_with_results` generates a callback notification when the job is complete. The notification includes the results of the request. * `recognitions.failed` generates a callback notification if the service @@ -3796,13 +3896,14 @@ class Language(str, Enum): identifier `ar-AR` is deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). """ AR_AR = 'ar-AR' AR_MS = 'ar-MS' DE_DE = 'de-DE' EN_AU = 'en-AU' EN_GB = 'en-GB' + EN_IN = 'en-IN' EN_US = 'en-US' ES_AR = 'es-AR' ES_ES = 'es-ES' @@ -3812,9 +3913,11 @@ class Language(str, Enum): ES_PE = 'es-PE' FR_CA = 'fr-CA' FR_FR = 'fr-FR' + HI_IN = 'hi-IN' IT_IT = 'it-IT' JA_JP = 'ja-JP' KO_KR = 'ko-KR' + NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' ZH_CN = 'zh-CN' @@ -3827,14 +3930,17 @@ class TrainLanguageModelEnums: class WordTypeToAdd(str, Enum): """ - The type of words from the custom language model's words resource on which to - train the model: + _For custom models that are based on previous-generation models_, the type of + words from the custom language model's words resource on which to train the model: * `all` (the default) trains the model on all new words, regardless of whether they were extracted from corpora or grammars or were added or modified by the user. - * `user` trains the model only on new words that were added or modified by the + * `user` trains the model only on custom words that were added or modified by the user directly. The model is not trained on new words extracted from corpora or grammars. + _For custom models that are based on next-generation models_, the service ignores + the parameter. The words resource contains only custom words that the user adds or + modifies directly, so the parameter is unnecessary. """ ALL = 'all' USER = 'user' @@ -3852,6 +3958,9 @@ class WordType(str, Enum): * `user` shows only custom words that were added or modified by the user directly. * `corpora` shows only OOV that were extracted from corpora. * `grammars` shows only OOV words that are recognized by grammars. + _For a custom model that is based on a next-generation model_, only `all` and + `user` apply. Both options return the same results. Words from other sources are + not added to custom models that are based on next-generation models. """ ALL = 'all' USER = 'user' @@ -3902,13 +4011,14 @@ class Language(str, Enum): identifier `ar-AR` is deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-customization#languageSupport). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). """ AR_AR = 'ar-AR' AR_MS = 'ar-MS' DE_DE = 'de-DE' EN_AU = 'en-AU' EN_GB = 'en-GB' + EN_IN = 'en-IN' EN_US = 'en-US' ES_AR = 'es-AR' ES_ES = 'es-ES' @@ -3918,9 +4028,11 @@ class Language(str, Enum): ES_PE = 'es-PE' FR_CA = 'fr-CA' FR_FR = 'fr-FR' + HI_IN = 'hi-IN' IT_IT = 'it-IT' JA_JP = 'ja-JP' KO_KR = 'ko-KR' + NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' ZH_CN = 'zh-CN' @@ -3960,7 +4072,7 @@ class ContentType(str, Enum): class ContainedContentType(str, Enum): """ - **For an archive-type resource,** specify the format of the audio files that are + _For an archive-type resource_, specify the format of the audio files that are contained in the archive file if they are of type `audio/alaw`, `audio/basic`, `audio/l16`, or `audio/mulaw`. Include the `rate`, `channels`, and `endianness` parameters where necessary. In this case, all audio files that are contained in @@ -3971,7 +4083,7 @@ class ContainedContentType(str, Enum): The parameter accepts all of the audio formats that are supported for use with speech recognition. For more information, see **Content types for audio-type resources** in the method description. - **For an audio-type resource,** omit the header. + _For an audio-type resource_, omit the header. """ AUDIO_ALAW = 'audio/alaw' AUDIO_BASIC = 'audio/basic' @@ -4000,8 +4112,8 @@ class AcousticModel(): Information about an existing custom acoustic model. :attr str customization_id: The customization ID (GUID) of the custom acoustic - model. The **Create a custom acoustic model** method returns only this field of - the object; it does not return the other fields. + model. The [Create a custom acoustic model](#createacousticmodel) method returns + only this field of the object; it does not return the other fields. :attr str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom acoustic model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). @@ -4061,8 +4173,9 @@ def __init__(self, Initialize a AcousticModel object. :param str customization_id: The customization ID (GUID) of the custom - acoustic model. The **Create a custom acoustic model** method returns only - this field of the object; it does not return the other fields. + acoustic model. The [Create a custom acoustic model](#createacousticmodel) + method returns only this field of the object; it does not return the other + fields. :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom acoustic model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). @@ -4307,13 +4420,13 @@ class AudioDetails(): * `undetermined` for a resource that the service cannot validate (for example, if the user mistakenly passes a file that does not contain audio, such as a JPEG file). - :attr str codec: (optional) **For an audio-type resource,** the codec in which - the audio is encoded. Omitted for an archive-type resource. - :attr int frequency: (optional) **For an audio-type resource,** the sampling - rate of the audio in Hertz (samples per second). Omitted for an archive-type + :attr str codec: (optional) _For an audio-type resource_, the codec in which the + audio is encoded. Omitted for an archive-type resource. + :attr int frequency: (optional) _For an audio-type resource_, the sampling rate + of the audio in Hertz (samples per second). Omitted for an archive-type resource. - :attr str compression: (optional) **For an archive-type resource,** the format - of the compressed archive: + :attr str compression: (optional) _For an archive-type resource_, the format of + the compressed archive: * `zip` for a **.zip** file * `gzip` for a **.tar.gz** file Omitted for an audio-type resource. @@ -4335,12 +4448,12 @@ def __init__(self, * `undetermined` for a resource that the service cannot validate (for example, if the user mistakenly passes a file that does not contain audio, such as a JPEG file). - :param str codec: (optional) **For an audio-type resource,** the codec in + :param str codec: (optional) _For an audio-type resource_, the codec in which the audio is encoded. Omitted for an archive-type resource. - :param int frequency: (optional) **For an audio-type resource,** the - sampling rate of the audio in Hertz (samples per second). Omitted for an + :param int frequency: (optional) _For an audio-type resource_, the sampling + rate of the audio in Hertz (samples per second). Omitted for an archive-type resource. - :param str compression: (optional) **For an archive-type resource,** the + :param str compression: (optional) _For an archive-type resource_, the format of the compressed archive: * `zip` for a **.zip** file * `gzip` for a **.tar.gz** file @@ -4417,7 +4530,7 @@ class TypeEnum(str, Enum): class CompressionEnum(str, Enum): """ - **For an archive-type resource,** the format of the compressed archive: + _For an archive-type resource_, the format of the compressed archive: * `zip` for a **.zip** file * `gzip` for a **.tar.gz** file Omitted for an audio-type resource. @@ -4430,15 +4543,15 @@ class AudioListing(): """ Information about an audio resource from a custom acoustic model. - :attr int duration: (optional) **For an audio-type resource,** the total - seconds of audio in the resource. Omitted for an archive-type resource. - :attr str name: (optional) **For an audio-type resource,** the user-specified - name of the resource. Omitted for an archive-type resource. - :attr AudioDetails details: (optional) **For an audio-type resource,** an + :attr int duration: (optional) _For an audio-type resource_, the total seconds + of audio in the resource. Omitted for an archive-type resource. + :attr str name: (optional) _For an audio-type resource_, the user-specified name + of the resource. Omitted for an archive-type resource. + :attr AudioDetails details: (optional) _For an audio-type resource_, an `AudioDetails` object that provides detailed information about the resource. The object is empty until the service finishes processing the audio. Omitted for an archive-type resource. - :attr str status: (optional) **For an audio-type resource,** the status of the + :attr str status: (optional) _For an audio-type resource_, the status of the resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. @@ -4448,10 +4561,10 @@ class AudioListing(): * `invalid`: The audio data is not valid for training the custom model (possibly because it has the wrong format or sampling rate, or because it is corrupted). Omitted for an archive-type resource. - :attr AudioResource container: (optional) **For an archive-type resource,** an + :attr AudioResource container: (optional) _For an archive-type resource_, an object of type `AudioResource` that provides information about the resource. Omitted for an audio-type resource. - :attr List[AudioResource] audio: (optional) **For an archive-type resource,** an + :attr List[AudioResource] audio: (optional) _For an archive-type resource_, an array of `AudioResource` objects that provides information about the audio-type resources that are contained in the resource. Omitted for an audio-type resource. @@ -4468,15 +4581,15 @@ def __init__(self, """ Initialize a AudioListing object. - :param int duration: (optional) **For an audio-type resource,** the total + :param int duration: (optional) _For an audio-type resource_, the total seconds of audio in the resource. Omitted for an archive-type resource. - :param str name: (optional) **For an audio-type resource,** the + :param str name: (optional) _For an audio-type resource_, the user-specified name of the resource. Omitted for an archive-type resource. - :param AudioDetails details: (optional) **For an audio-type resource,** an + :param AudioDetails details: (optional) _For an audio-type resource_, an `AudioDetails` object that provides detailed information about the resource. The object is empty until the service finishes processing the audio. Omitted for an archive-type resource. - :param str status: (optional) **For an audio-type resource,** the status of + :param str status: (optional) _For an audio-type resource_, the status of the resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. @@ -4487,11 +4600,11 @@ def __init__(self, (possibly because it has the wrong format or sampling rate, or because it is corrupted). Omitted for an archive-type resource. - :param AudioResource container: (optional) **For an archive-type - resource,** an object of type `AudioResource` that provides information - about the resource. Omitted for an audio-type resource. - :param List[AudioResource] audio: (optional) **For an archive-type - resource,** an array of `AudioResource` objects that provides information + :param AudioResource container: (optional) _For an archive-type resource_, + an object of type `AudioResource` that provides information about the + resource. Omitted for an audio-type resource. + :param List[AudioResource] audio: (optional) _For an archive-type + resource_, an array of `AudioResource` objects that provides information about the audio-type resources that are contained in the resource. Omitted for an audio-type resource. """ @@ -4564,7 +4677,7 @@ def __ne__(self, other: 'AudioListing') -> bool: class StatusEnum(str, Enum): """ - **For an audio-type resource,** the status of the resource: + _For an audio-type resource_, the status of the resource: * `ok`: The service successfully analyzed the audio data. The data can be used to train the custom model. * `being_processed`: The service is still analyzing the audio data. The service @@ -4988,9 +5101,9 @@ class AudioResource(): Information about an audio resource from a custom acoustic model. :attr int duration: The total seconds of audio in the audio resource. - :attr str name: **For an archive-type resource,** the user-specified name of the + :attr str name: _For an archive-type resource_, the user-specified name of the resource. - **For an audio-type resource,** the user-specified name of the resource or the + _For an audio-type resource_, the user-specified name of the resource or the name of the audio file that the user added for the resource. The value depends on the method that is called. :attr AudioDetails details: An `AudioDetails` object that provides detailed @@ -5014,9 +5127,9 @@ def __init__(self, duration: int, name: str, details: 'AudioDetails', Initialize a AudioResource object. :param int duration: The total seconds of audio in the audio resource. - :param str name: **For an archive-type resource,** the user-specified name - of the resource. - **For an audio-type resource,** the user-specified name of the resource or + :param str name: _For an archive-type resource_, the user-specified name of + the resource. + _For an audio-type resource_, the user-specified name of the resource or the name of the audio file that the user added for the resource. The value depends on the method that is called. :param AudioDetails details: An `AudioDetails` object that provides @@ -5274,8 +5387,11 @@ class Corpus(): :attr str name: The name of the corpus. :attr int total_words: The total number of words in the corpus. The value is `0` while the corpus is being processed. - :attr int out_of_vocabulary_words: The number of OOV words in the corpus. The - value is `0` while the corpus is being processed. + :attr int out_of_vocabulary_words: _For custom models that are based on + previous-generation models_, the number of OOV words extracted from the corpus. + The value is `0` while the corpus is being processed. + _For custom models that are based on next-generation models_, no OOV words are + extracted from corpora, so the value is always `0`. :attr str status: The status of the corpus: * `analyzed`: The service successfully analyzed the corpus. The custom model can be trained with data from the corpus. @@ -5301,8 +5417,11 @@ def __init__(self, :param str name: The name of the corpus. :param int total_words: The total number of words in the corpus. The value is `0` while the corpus is being processed. - :param int out_of_vocabulary_words: The number of OOV words in the corpus. - The value is `0` while the corpus is being processed. + :param int out_of_vocabulary_words: _For custom models that are based on + previous-generation models_, the number of OOV words extracted from the + corpus. The value is `0` while the corpus is being processed. + _For custom models that are based on next-generation models_, no OOV words + are extracted from corpora, so the value is always `0`. :param str status: The status of the corpus: * `analyzed`: The service successfully analyzed the corpus. The custom model can be trained with data from the corpus. @@ -5408,14 +5527,15 @@ class CustomWord(): """ Information about a word that is to be added to a custom language model. - :attr 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 `_` (underscore) to connect the - tokens of compound words. - Omit this parameter for the **Add a custom word** method. - :attr List[str] sounds_like: (optional) An array of sounds-like pronunciations - for the custom word. Specify how words that are difficult to pronounce, foreign - words, acronyms, and so on can be pronounced by users. + :attr str word: (optional) For the [Add custom words](#addwords) 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 `_` (underscore) + to connect the tokens of compound words. + Omit this parameter for the [Add a custom word](#addword) method. + :attr List[str] sounds_like: (optional) _For a custom model that is based on a + previous-generation model_, an array of sounds-like pronunciations for the + custom word. Specify how words that are difficult to pronounce, foreign words, + acronyms, and so on can be pronounced by users. * For a word that is not in the service's base vocabulary, omit the parameter to have the service automatically generate a sounds-like pronunciation for the word. @@ -5425,6 +5545,9 @@ class CustomWord(): the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. + _For a custom model that is based on a next-generation model_, omit this field. + Custom models based on next-generation models do not support the `sounds_like` + field. The service ignores the field. :attr str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or from its @@ -5439,14 +5562,15 @@ def __init__(self, """ Initialize a CustomWord object. - :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 `_` + :param str word: (optional) For the [Add custom words](#addwords) 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 `_` (underscore) to connect the tokens of compound words. - Omit this parameter for the **Add a custom word** method. - :param List[str] sounds_like: (optional) An array of sounds-like - pronunciations for the custom word. Specify how words that are difficult to - pronounce, foreign words, acronyms, and so on can be pronounced by users. + Omit this parameter for the [Add a custom word](#addword) method. + :param List[str] sounds_like: (optional) _For a custom model that is based + on a previous-generation model_, an array of sounds-like pronunciations for + the custom word. Specify how words that are difficult to pronounce, foreign + words, acronyms, and so on can be pronounced by users. * For a word that is not in the service's base vocabulary, omit the parameter to have the service automatically generate a sounds-like pronunciation for the word. @@ -5456,6 +5580,9 @@ def __init__(self, pronunciation from the base vocabulary. A word can have at most five sounds-like pronunciations. A pronunciation can include at most 40 characters not including spaces. + _For a custom model that is based on a next-generation model_, omit this + field. Custom models based on next-generation models do not support the + `sounds_like` field. The service ignores the field. :param str display_as: (optional) An alternative spelling for the custom word when it appears in a transcript. Use the parameter when you want the word to have a spelling that is different from its usual representation or @@ -5804,8 +5931,8 @@ class LanguageModel(): Information about an existing custom language model. :attr str customization_id: The customization ID (GUID) of the custom language - model. The **Create a custom language model** method returns only this field of - the object; it does not return the other fields. + model. The [Create a custom language model](#createlanguagemodel) method returns + only this field of the object; it does not return the other fields. :attr str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom language model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). @@ -5826,10 +5953,14 @@ class LanguageModel(): models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) Dialect values are case-insensitive. - :attr List[str] versions: (optional) A list of the available versions of the - custom language model. Each element of the array indicates a version of the base - model with which the custom model can be used. Multiple versions exist only if - the custom model has been upgraded; otherwise, only a single version is shown. + :attr List[str] versions: (optional) _For custom models that are based on + previous-generation models_, a list of the available versions of the custom + language model. Each element of the array indicates a version of the base model + with which the custom model can be used. Multiple versions exist only if the + custom model has been upgraded; otherwise, only a single version is shown. + _For custom models that are based on next-generation models_, a single version + of the custom model. Only one version of a custom model that is based on a + next-generation model is ever available, and upgrading does not apply. :attr str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom language model. :attr str name: (optional) The name of the custom language model. @@ -5881,8 +6012,9 @@ def __init__(self, Initialize a LanguageModel object. :param str customization_id: The customization ID (GUID) of the custom - language model. The **Create a custom language model** method returns only - this field of the object; it does not return the other fields. + language model. The [Create a custom language model](#createlanguagemodel) + method returns only this field of the object; it does not return the other + fields. :param str created: (optional) The date and time in Coordinated Universal Time (UTC) at which the custom language model was created. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). @@ -5903,11 +6035,16 @@ def __init__(self, `es-PE` models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) Dialect values are case-insensitive. - :param List[str] versions: (optional) A list of the available versions of - the custom language model. Each element of the array indicates a version of - the base model with which the custom model can be used. Multiple versions - exist only if the custom model has been upgraded; otherwise, only a single - version is shown. + :param List[str] versions: (optional) _For custom models that are based on + previous-generation models_, a list of the available versions of the custom + language model. Each element of the array indicates a version of the base + model with which the custom model can be used. Multiple versions exist only + if the custom model has been upgraded; otherwise, only a single version is + shown. + _For custom models that are based on next-generation models_, a single + version of the custom model. Only one version of a custom model that is + based on a next-generation model is ever available, and upgrading does not + apply. :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom language model. :param str name: (optional) The name of the custom language model. @@ -6271,8 +6408,8 @@ def __ne__(self, other: 'ProcessedAudio') -> bool: class ProcessingMetrics(): """ If processing metrics are requested, information about the service's processing of the - input audio. Processing metrics are not available with the synchronous **Recognize - audio** method. + input audio. Processing metrics are not available with the synchronous [Recognize + audio](#recognize) method. :attr ProcessedAudio processed_audio: Detailed timing information about the service's processing of the input audio. @@ -6413,23 +6550,23 @@ class RecognitionJob(): :attr str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the job was last updated by the service. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). This field is returned only - by the **Check jobs** and **Check a job** methods. + by the [Check jobs](#checkjobs) and [Check a job[(#checkjob) methods. :attr str url: (optional) The URL to use to request information about the job - with the **Check a job** method. This field is returned only by the **Create a - job** method. + with the [Check a job](#checkjob) method. This field is returned only by the + [Create a job](#createjob) method. :attr str user_token: (optional) The user token associated with a job that was created with a callback URL and a user token. This field can be returned only by - the **Check jobs** method. + the [Check jobs](#checkjobs) method. :attr List[SpeechRecognitionResults] results: (optional) If the status is `completed`, the results of the recognition request as an array that includes a single instance of a `SpeechRecognitionResults` object. This field is returned - only by the **Check a job** method. + only by the [Check a job](#checkjob) method. :attr List[str] warnings: (optional) An array of warning messages about invalid parameters included with the request. Each warning includes a descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds despite the warnings. This field can be returned only by the - **Create a job** method. + [Create a job](#createjob) method. """ def __init__(self, @@ -6464,23 +6601,24 @@ def __init__(self, :param str updated: (optional) The date and time in Coordinated Universal Time (UTC) at which the job was last updated by the service. The value is provided in full ISO 8601 format (`YYYY-MM-DDThh:mm:ss.sTZD`). This field - is returned only by the **Check jobs** and **Check a job** methods. + is returned only by the [Check jobs](#checkjobs) and [Check a + job[(#checkjob) methods. :param str url: (optional) The URL to use to request information about the - job with the **Check a job** method. This field is returned only by the - **Create a job** method. + job with the [Check a job](#checkjob) method. This field is returned only + by the [Create a job](#createjob) method. :param str user_token: (optional) The user token associated with a job that was created with a callback URL and a user token. This field can be - returned only by the **Check jobs** method. + returned only by the [Check jobs](#checkjobs) method. :param List[SpeechRecognitionResults] results: (optional) If the status is `completed`, the results of the recognition request as an array that includes a single instance of a `SpeechRecognitionResults` object. This - field is returned only by the **Check a job** method. + field is returned only by the [Check a job](#checkjob) method. :param List[str] warnings: (optional) An array of warning messages about invalid parameters included with the request. Each warning includes a descriptive message and a list of invalid argument strings, for example, `"unexpected query parameter 'user_token', query parameter 'callback_url' was not specified"`. The request succeeds despite the warnings. This field - can be returned only by the **Create a job** method. + can be returned only by the [Create a job](#createjob) method. """ self.id = id self.status = status @@ -7053,10 +7191,9 @@ class SpeechRecognitionAlternative(): :attr str transcript: A transcription of the audio. :attr float confidence: (optional) A score that indicates the service's - confidence in the transcript in the range of 0.0 to 1.0. For speech recognition - with previous-generation models, a confidence score is returned only for the - best alternative and only with results marked as final. For speech recognition - with next-generation models, a confidence score is never returned. + confidence in the transcript in the range of 0.0 to 1.0. The service returns a + confidence score only for the best alternative and only with results marked as + final. :attr List[str] timestamps: (optional) Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds, for example: @@ -7080,11 +7217,9 @@ def __init__(self, :param str transcript: A transcription of the audio. :param float confidence: (optional) A score that indicates the service's - confidence in the transcript in the range of 0.0 to 1.0. For speech - recognition with previous-generation models, a confidence score is returned - only for the best alternative and only with results marked as final. For - speech recognition with next-generation models, a confidence score is never - returned. + confidence in the transcript in the range of 0.0 to 1.0. The service + returns a confidence score only for the best alternative and only with + results marked as final. :param List[str] timestamps: (optional) Time alignments for each word from the transcript as a list of lists. Each inner list consists of three elements: the word followed by its start and end time in seconds, for @@ -7349,8 +7484,8 @@ class SpeechRecognitionResults(): object to include only the `speaker_labels` field. :attr ProcessingMetrics processing_metrics: (optional) If processing metrics are requested, information about the service's processing of the input audio. - Processing metrics are not available with the synchronous **Recognize audio** - method. + Processing metrics are not available with the synchronous [Recognize + audio](#recognize) method. :attr AudioMetrics audio_metrics: (optional) If audio metrics are requested, information about the signal characteristics of the input audio. :attr List[str] warnings: (optional) An array of warning messages associated @@ -7401,7 +7536,7 @@ def __init__(self, :param ProcessingMetrics processing_metrics: (optional) If processing metrics are requested, information about the service's processing of the input audio. Processing metrics are not available with the synchronous - **Recognize audio** method. + [Recognize audio](#recognize) method. :param AudioMetrics audio_metrics: (optional) If audio metrics are requested, information about the signal characteristics of the input audio. :param List[str] warnings: (optional) An array of warning messages @@ -7504,9 +7639,13 @@ class SupportedFeatures(): :attr bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. **Note:** The field returns `true` for all models. However, speaker labels are - supported only for US English, Australian English, German, Japanese, Korean, and - Spanish (both broadband and narrowband models) and UK English (narrowband model - only). Speaker labels are not supported for any other models. + supported as beta functionality only for the following languages and models: + * For previous-generation models, the parameter can be used for Australian + English, US English, German, Japanese, Korean, and Spanish (both broadband and + narrowband models) and UK English (narrowband model) transcription only. + * For next-generation models, the parameter can be used for English (Australian, + Indian, UK, and US), German, Japanese, Korean, and Spanish transcription only. + Speaker labels are not supported for any other models. :attr bool low_latency: (optional) Indicates whether the `low_latency` parameter can be used with a next-generation language model. The field is returned only for next-generation models. Previous-generation models do not support the @@ -7527,10 +7666,16 @@ def __init__(self, :param bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. **Note:** The field returns `true` for all models. However, speaker labels - are supported only for US English, Australian English, German, Japanese, - Korean, and Spanish (both broadband and narrowband models) and UK English - (narrowband model only). Speaker labels are not supported for any other - models. + are supported as beta functionality only for the following languages and + models: + * For previous-generation models, the parameter can be used for Australian + English, US English, German, Japanese, Korean, and Spanish (both broadband + and narrowband models) and UK English (narrowband model) transcription + only. + * For next-generation models, the parameter can be used for English + (Australian, Indian, UK, and US), German, Japanese, Korean, and Spanish + transcription only. + Speaker labels are not supported for any other models. :param bool low_latency: (optional) Indicates whether the `low_latency` parameter can be used with a next-generation language model. The field is returned only for next-generation models. Previous-generation models do not @@ -7754,25 +7899,39 @@ class Word(): :attr str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :attr List[str] sounds_like: An array of pronunciations for the word. The array - can include the sounds-like pronunciation automatically generated by the service - if none is provided for the word; the service adds this pronunciation when it - finishes processing the word. + :attr List[str] sounds_like: _For a custom model that is based on a + previous-generation model_, an array of as many as five pronunciations for the + word. The array can include the sounds-like pronunciation that is automatically + generated by the service if none is provided when the word is added to the + custom model; the service adds this pronunciation when it finishes processing + the word. + _For a custom model that is based on a next-generation model_, this field does + not apply. Custom models based on next-generation models do not support the + `sounds_like` field, which is ignored. :attr str display_as: The spelling of the word that the service uses to display the word in a transcript. The field contains an empty string if no display-as value is provided for the word, in which case the word is displayed as it is spelled. - :attr int count: A sum of the number of times the word is found across all - corpora. For example, if the word occurs five times in one corpus and seven + :attr int count: _For a custom model that is based on a previous-generation + model_, a sum of the number of times the word is found across all corpora and + grammars. For example, if the word occurs five times in one corpus and seven times in another, its count is `12`. If you add a custom word to a model before - it is added by any corpora, the count begins at `1`; if the word is added from a - corpus first and later modified, the count reflects only the number of times it - is found in corpora. + it is added by any corpora or grammars, the count begins at `1`; if the word is + added from a corpus or grammar first and later modified, the count reflects only + the number of times it is found in corpora and grammars. + _For a custom model that is based on a next-generation model_, the `count` field + for any word is always `1`. :attr List[str] source: An array of sources that describes how the word was - added to the custom model's words resource. For OOV words added from a corpus, - includes the name of the corpus; if the word was added by multiple corpora, the - names of all corpora are listed. If the word was modified or added by the user - directly, the field includes the string `user`. + added to the custom model's words resource. + * _For a custom model that is based on previous-generation model,_ the field + includes the name of each corpus and grammar from which the service extracted + the word. For OOV that are added by multiple corpora or grammars, the names of + all corpora and grammars are listed. If you modified or added the word directly, + the field includes the string `user`. + * _For a custom model that is based on a next-generation model,_ this field + shows only `user` for custom words that were added directly to the custom model. + Words from corpora and grammars are not added to the words resource for custom + models that are based on next-generation models. :attr List[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. @@ -7791,25 +7950,40 @@ def __init__(self, :param str word: A word from the custom model's words resource. The spelling of the word is used to train the model. - :param List[str] sounds_like: An array of pronunciations for the word. The - array can include the sounds-like pronunciation automatically generated by - the service if none is provided for the word; the service adds this - pronunciation when it finishes processing the word. + :param List[str] sounds_like: _For a custom model that is based on a + previous-generation model_, an array of as many as five pronunciations for + the word. The array can include the sounds-like pronunciation that is + automatically generated by the service if none is provided when the word is + added to the custom model; the service adds this pronunciation when it + finishes processing the word. + _For a custom model that is based on a next-generation model_, this field + does not apply. Custom models based on next-generation models do not + support the `sounds_like` field, which is ignored. :param str display_as: The spelling of the word that the service uses to display the word in a transcript. The field contains an empty string if no display-as value is provided for the word, in which case the word is displayed as it is spelled. - :param int count: A sum of the number of times the word is found across all - corpora. For example, if the word occurs five times in one corpus and seven - times in another, its count is `12`. If you add a custom word to a model - before it is added by any corpora, the count begins at `1`; if the word is - added from a corpus first and later modified, the count reflects only the - number of times it is found in corpora. + :param int count: _For a custom model that is based on a + previous-generation model_, a sum of the number of times the word is found + across all corpora and grammars. For example, if the word occurs five times + in one corpus and seven times in another, its count is `12`. If you add a + custom word to a model before it is added by any corpora or grammars, the + count begins at `1`; if the word is added from a corpus or grammar first + and later modified, the count reflects only the number of times it is found + in corpora and grammars. + _For a custom model that is based on a next-generation model_, the `count` + field for any word is always `1`. :param List[str] source: An array of sources that describes how the word - was added to the custom model's words resource. For OOV words added from a - corpus, includes the name of the corpus; if the word was added by multiple - corpora, the names of all corpora are listed. If the word was modified or - added by the user directly, the field includes the string `user`. + was added to the custom model's words resource. + * _For a custom model that is based on previous-generation model,_ the + field includes the name of each corpus and grammar from which the service + extracted the word. For OOV that are added by multiple corpora or grammars, + the names of all corpora and grammars are listed. If you modified or added + the word directly, the field includes the string `user`. + * _For a custom model that is based on a next-generation model,_ this field + shows only `user` for custom words that were added directly to the custom + model. Words from corpora and grammars are not added to the words resource + for custom models that are based on next-generation models. :param List[WordError] error: (optional) If the service discovered one or more problems that you need to correct for the word's definition, an array that describes each of the errors. diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index fb0716e77..4924eeed8 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, @@ -30,11 +30,16 @@ that, when combined, sound like the word. A phonetic translation is based on the SSML phoneme format for representing a word. You can specify a phonetic translation in standard International Phonetic Alphabet (IPA) representation or in the proprietary IBM Symbolic -Phonetic Representation (SPR). The Arabic, Chinese, Dutch, Australian English, and Korean -languages support only IPA. +Phonetic Representation (SPR). The service also offers a Tune by Example feature that lets you define custom prompts. You can also define speaker models to improve the quality of your custom prompts. The service support custom prompts only for US English custom models and voices. +**IBM Cloud®.** The Arabic, Chinese, Dutch, Australian English, and Korean languages +and voices are supported only for IBM Cloud. For phonetic translation, they support only +IPA, not SPR. + +API Version: 1.0.0 +See: https://cloud.ibm.com/docs/text-to-speech """ from enum import Enum @@ -89,8 +94,8 @@ def list_voices(self, **kwargs) -> DetailedResponse: Lists all voices available for use with the service. The information includes the name, language, gender, and other details about the voice. The ordering of the list of voices can change from call to call; do not rely on an alphabetized or - static list of voices. To see information about a specific voice, use the **Get a - voice** method. + static list of voices. To see information about a specific voice, use the [Get a + voice](#getvoice). **See also:** [Listing all available voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoices). @@ -112,7 +117,7 @@ def list_voices(self, **kwargs) -> DetailedResponse: url = '/v1/voices' request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_voice(self, @@ -126,11 +131,11 @@ def get_voice(self, Gets information about the specified voice. The information includes the name, language, gender, and other details about the voice. Specify a customization ID to obtain information for a custom model that is defined for the language of the - specified voice. To list information about all available voices, use the **List - voices** method. + specified voice. To list information about all available voices, use the [List + voices](#listvoices) method. **See also:** [Listing a specific voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoice). - ### Important voice updates + ### Important voice updates for IBM Cloud The service's voices underwent significant change on 2 December 2020. * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural instead of concatenative. @@ -150,11 +155,13 @@ def get_voice(self, equivalent neural voices at your earliest convenience. For more information about all voice updates, see the [2 December 2020 service update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) - in the release notes. + in the release notes for IBM Cloud. :param str voice: The voice for which information is to be returned. For - more information about specifying a voice, see **Important voice updates** - in the method description. + more information about specifying a voice, see **Important voice updates + for IBM Cloud** in the method description. + **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean + languages and voices are supported only for IBM Cloud. :param str customization_id: (optional) The customization ID (GUID) of a custom model for which information is to be returned. You must make the request with credentials for the instance of the service that owns the @@ -188,7 +195,7 @@ def get_voice(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -254,9 +261,9 @@ def synthesize(self, * `audio/webm;codecs=vorbis` - You can optionally specify the `rate` of the audio. 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/text-to-speech?topic=text-to-speech-audioFormats#audioFormats). - ### Important voice updates + details about some of the formats, see [Using audio + formats](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-audio-formats). + ### Important voice updates for IBM Cloud The service's voices underwent significant change on 2 December 2020. * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural instead of concatenative. @@ -276,7 +283,7 @@ def synthesize(self, equivalent neural voices at your earliest convenience. For more information about all voice updates, see the [2 December 2020 service update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) - in the release notes. + in the release notes for IBM Cloud. ### 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 @@ -291,8 +298,12 @@ def synthesize(self, the audio format. For more information about specifying an audio format, see **Audio formats (accept types)** in the method description. :param str voice: (optional) The voice to use for synthesis. For more - information about specifying a voice, see **Important voice updates** in - the method description. + information about specifying a voice, see **Important voice updates for IBM + Cloud** in the method description. + **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean + languages and voices are supported only for IBM Cloud. + **See also:** See also [Using languages and + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices). :param str customization_id: (optional) The customization ID (GUID) of a custom model to use for the synthesis. If a custom model is specified, it works only if it matches the language of the indicated voice. You must make @@ -329,7 +340,7 @@ def synthesize(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -352,7 +363,7 @@ def get_pronunciation(self, for a specific custom model to see the translation for that model. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). - ### Important voice updates + ### Important voice updates for IBM Cloud The service's voices underwent significant change on 2 December 2020. * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural instead of concatenative. @@ -372,14 +383,16 @@ def get_pronunciation(self, equivalent neural voices at your earliest convenience. For more information about all voice updates, see the [2 December 2020 service update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) - in the release notes. + in the release notes for IBM Cloud. :param str text: The word for which the pronunciation is requested. :param str voice: (optional) A voice that specifies the language in which the pronunciation is to be returned. All voices for the same language (for example, `en-US`) return the same translation. For more information about - specifying a voice, see **Important voice updates** in the method - description. + specifying a voice, see **Important voice updates for IBM Cloud** in the + method description. + **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean + languages and voices are supported only for IBM Cloud. :param str format: (optional) The phoneme format in which to return the pronunciation. The Arabic, Chinese, Dutch, Australian English, and Korean languages support only IPA. Omit the parameter to obtain the pronunciation @@ -422,7 +435,7 @@ def get_pronunciation(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -444,7 +457,7 @@ def create_custom_model(self, used to create it. **See also:** [Creating a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). - ### Important voice updates + ### Important voice updates for IBM Cloud The service's voices underwent significant change on 2 December 2020. * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural instead of concatenative. @@ -464,7 +477,7 @@ def create_custom_model(self, equivalent neural voices at your earliest convenience. For more information about all voice updates, see the [2 December 2020 service update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) - in the release notes. + in the release notes for IBM Cloud. :param str name: The name of the new custom model. :param str language: (optional) The language of the new custom model. You @@ -473,6 +486,8 @@ def create_custom_model(self, the parameter to use the the default language, `en-US`. **Note:** The `ar-AR` language identifier cannot be used to create a custom model. Use the `ar-MS` identifier instead. + **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean + languages and voices are supported only for IBM Cloud. :param str description: (optional) A description of the new custom model. Specifying a description is recommended. :param dict headers: A `dict` containing the request headers @@ -503,7 +518,7 @@ def create_custom_model(self, headers=headers, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_custom_models(self, @@ -516,9 +531,9 @@ def list_custom_models(self, Lists metadata such as the name and description for all custom models that are owned by an instance of the service. Specify a language to list the custom models for that language only. To see the words and prompts in addition to the metadata - for a specific custom model, use the **Get a custom model** method. You must use - credentials for the instance of the service that owns a model to list information - about it. + for a specific custom model, use the [Get a custom model](#getcustommodel) method. + You must use credentials for the instance of the service that owns a model to list + information about it. **See also:** [Querying all custom models](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsQueryAll). @@ -548,7 +563,7 @@ def list_custom_models(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_custom_model(self, @@ -626,7 +641,7 @@ def update_custom_model(self, headers=headers, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_custom_model(self, customization_id: str, @@ -637,8 +652,8 @@ def get_custom_model(self, customization_id: str, Gets all information about a specified custom model. In addition to metadata such as the name and description of the custom model, the output includes the words and their translations that are defined for the model, as well as any prompts that are - defined for the model. To see just the metadata for a model, use the **List custom - models** method. + defined for the model. To see just the metadata for a model, use the [List custom + models](#listcustommodels) method. **See also:** [Querying a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsQuery). @@ -668,7 +683,7 @@ def get_custom_model(self, customization_id: str, url = '/v1/customizations/{customization_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_custom_model(self, customization_id: str, @@ -708,7 +723,7 @@ def delete_custom_model(self, customization_id: str, url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -746,14 +761,14 @@ def add_words(self, customization_id: str, words: List['Word'], :param str customization_id: The customization ID (GUID) of the custom model. You must make the request with credentials for the instance of the service that owns the custom model. - :param List[Word] words: The **Add custom words** method accepts an array - of `Word` objects. Each object provides a word that is to be added or - updated for the custom model and the word's translation. - The **List custom words** method returns an array of `Word` objects. Each - object shows a word and its translation from the custom model. The words - are listed in alphabetical order, with uppercase letters listed before - lowercase letters. The array is empty if the custom model contains no - words. + :param List[Word] words: The [Add custom words](#addwords) method accepts + an array of `Word` objects. Each object provides a word that is to be added + or updated for the custom model and the word's translation. + The [List custom words](#listwords) method returns an array of `Word` + objects. Each object shows a word and its translation from the custom + model. The words are listed in alphabetical order, with uppercase letters + listed before lowercase letters. The array is empty if the custom model + contains no words. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -789,7 +804,7 @@ def add_words(self, customization_id: str, words: List['Word'], headers=headers, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: @@ -829,7 +844,7 @@ def list_words(self, customization_id: str, **kwargs) -> DetailedResponse: **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def add_word(self, @@ -918,7 +933,7 @@ def add_word(self, headers=headers, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_word(self, customization_id: str, word: str, @@ -962,7 +977,7 @@ def get_word(self, customization_id: str, word: str, **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_word(self, customization_id: str, word: str, @@ -1006,7 +1021,7 @@ def delete_word(self, customization_id: str, word: str, url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1022,11 +1037,11 @@ def list_custom_prompts(self, customization_id: str, The information includes the prompt ID, prompt text, status, and optional speaker ID for each prompt of the custom model. You must use credentials for the instance of the service that owns the custom model. The same information about all of the - prompts for a custom model is also provided by the **Get a custom model** method. - That method provides complete details about a specified custom model, including - its language, owner, custom words, and more. - **Beta:** Custom prompts are beta functionality that is supported only for use - with US English custom models and voices. + prompts for a custom model is also provided by the [Get a custom + model](#getcustommodel) method. That method provides complete details about a + specified custom model, including its language, owner, custom words, and more. + Custom prompts are supported only for use with US English custom models and + voices. **See also:** [Listing custom prompts](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-custom-prompts#tbe-custom-prompts-list). @@ -1057,7 +1072,7 @@ def list_custom_prompts(self, customization_id: str, **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def add_custom_prompt(self, customization_id: str, prompt_id: str, @@ -1091,11 +1106,11 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, processing time for a reasonably sized prompt generally matches the length of the audio (for example, it takes 20 seconds to process a 20-second prompt). For shorter prompts, you can wait for a reasonable amount of time and then check - the status of the prompt with the **Get a custom prompt** method. For longer - prompts, consider using that method to poll the service every few seconds to - determine when the prompt becomes available. No prompt can be used for speech - synthesis if it is in the `processing` or `failed` state. Only prompts that are in - the `available` state can be used for speech synthesis. + the status of the prompt with the [Get a custom prompt](#getcustomprompt) method. + For longer prompts, consider using that method to poll the service every few + seconds to determine when the prompt becomes available. No prompt can be used for + speech synthesis if it is in the `processing` or `failed` state. Only prompts that + are in the `available` state can be used for speech synthesis. When it processes a request, the service attempts to align the text and the audio that are provided for the prompt. The text that is passed with a prompt must match the spoken audio as closely as possible. Optimally, the text and audio match @@ -1126,8 +1141,8 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, is one recommended means of potentially improving the quality of the prompt. This is especially important for shorter prompts such as "good-bye" or "thank you," where less audio data makes it more difficult to match the prosody of the speaker. - **Beta:** Custom prompts are beta functionality that is supported only for use - with US English custom models and voices. + Custom prompts are supported only for use with US English custom models and + voices. **See also:** * [Add a custom prompt](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-create#tbe-create-add-prompt) @@ -1198,7 +1213,7 @@ def add_custom_prompt(self, customization_id: str, prompt_id: str, headers=headers, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_custom_prompt(self, customization_id: str, prompt_id: str, @@ -1209,8 +1224,7 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, Gets information about a specified custom prompt for a specified custom model. The information includes the prompt ID, prompt text, status, and optional speaker ID for each prompt of the custom model. You must use credentials for the instance of - the service that owns the custom model. - **Beta:** Custom prompts are beta functionality that is supported only for use + the service that owns the custom model. Custom prompts are supported only for use with US English custom models and voices. **See also:** [Listing custom prompts](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-custom-prompts#tbe-custom-prompts-list). @@ -1245,7 +1259,7 @@ def get_custom_prompt(self, customization_id: str, prompt_id: str, **path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_custom_prompt(self, customization_id: str, prompt_id: str, @@ -1258,9 +1272,8 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, service that owns the custom model from which the prompt is to be deleted. **Caution:** Deleting a custom prompt elicits a 400 response code from synthesis requests that attempt to use the prompt. Make sure that you do not attempt to use - a deleted prompt in a production application. - **Beta:** Custom prompts are beta functionality that is supported only for use - with US English custom models and voices. + a deleted prompt in a production application. Custom prompts are supported only + for use with US English custom models and voices. **See also:** [Deleting a custom prompt](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-custom-prompts#tbe-custom-prompts-delete). @@ -1296,7 +1309,7 @@ def delete_custom_prompt(self, customization_id: str, prompt_id: str, url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1310,10 +1323,8 @@ def list_speaker_models(self, **kwargs) -> DetailedResponse: Lists information about all speaker models that are defined for a service instance. The information includes the speaker ID and speaker name of each defined speaker. You must use credentials for the instance of a service to list its - speakers. - **Beta:** Speaker models and the custom prompts with which they are used are beta - functionality that is supported only for use with US English custom models and - voices. + speakers. Speaker models and the custom prompts with which they are used are + supported only for use with US English custom models and voices. **See also:** [Listing speaker models](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-speaker-models#tbe-speaker-models-list). @@ -1335,7 +1346,7 @@ def list_speaker_models(self, **kwargs) -> DetailedResponse: url = '/v1/speakers' request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_speaker_model(self, speaker_name: str, audio: BinaryIO, @@ -1375,10 +1386,8 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, returns, the audio is fully processed and the speaker enrollment is complete. The service returns a speaker ID with the request. A speaker ID is globally unique identifier (GUID) that you use to identify the speaker in subsequent requests to - the service. - **Beta:** Speaker models and the custom prompts with which they are used are beta - functionality that is supported only for use with US English custom models and - voices. + the service. Speaker models and the custom prompts with which they are used are + supported only for use with US English custom models and voices. **See also:** * [Create a speaker model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-create#tbe-create-speaker-model) @@ -1432,7 +1441,7 @@ def create_speaker_model(self, speaker_name: str, audio: BinaryIO, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: @@ -1444,9 +1453,8 @@ def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: the customization IDs of the custom models. For each custom model, the information lists information about each prompt that is defined for that custom model by the speaker. You must use credentials for the instance of the service that owns a - speaker model to list its prompts. - **Beta:** Speaker models and the custom prompts with which they are used are beta - functionality that is supported only for use with US English custom models and + speaker model to list its prompts. Speaker models and the custom prompts with + which they are used are supported only for use with US English custom models and voices. **See also:** [Listing the custom prompts for a speaker model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-speaker-models#tbe-speaker-models-list-prompts). @@ -1477,7 +1485,7 @@ def get_speaker_model(self, speaker_id: str, **kwargs) -> DetailedResponse: url = '/v1/speakers/{speaker_id}'.format(**path_param_dict) request = self.prepare_request(method='GET', url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_speaker_model(self, speaker_id: str, @@ -1492,10 +1500,9 @@ def delete_speaker_model(self, speaker_id: str, speaker's deletion. The prosodic data that defines the quality of a prompt is established when the prompt is created. A prompt is static and remains unaffected by deletion of its associated speaker. However, the prompt cannot be resubmitted - or updated with its original speaker once that speaker is deleted. - **Beta:** Speaker models and the custom prompts with which they are used are beta - functionality that is supported only for use with US English custom models and - voices. + or updated with its original speaker once that speaker is deleted. Speaker models + and the custom prompts with which they are used are supported only for use with US + English custom models and voices. **See also:** [Deleting a speaker model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-tbe-speaker-models#tbe-speaker-models-delete). @@ -1526,7 +1533,7 @@ def delete_speaker_model(self, speaker_id: str, url=url, headers=headers) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1577,7 +1584,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response @@ -1589,7 +1596,10 @@ class GetVoiceEnums: class Voice(str, Enum): """ The voice for which information is to be returned. For more information about - specifying a voice, see **Important voice updates** in the method description. + specifying a voice, see **Important voice updates for IBM Cloud** in the method + description. + **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean + languages and voices are supported only for IBM Cloud. """ AR_AR_OMARVOICE = 'ar-AR_OmarVoice' AR_MS_OMARVOICE = 'ar-MS_OmarVoice' @@ -1634,6 +1644,7 @@ class Voice(str, Enum): KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' + NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' @@ -1672,7 +1683,11 @@ class Accept(str, Enum): class Voice(str, Enum): """ The voice to use for synthesis. For more information about specifying a voice, see - **Important voice updates** in the method description. + **Important voice updates for IBM Cloud** in the method description. + **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean + languages and voices are supported only for IBM Cloud. + **See also:** See also [Using languages and + voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices). """ AR_AR_OMARVOICE = 'ar-AR_OmarVoice' AR_MS_OMARVOICE = 'ar-MS_OmarVoice' @@ -1717,6 +1732,7 @@ class Voice(str, Enum): KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' + NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' @@ -1736,7 +1752,9 @@ class Voice(str, Enum): A voice that specifies the language in which the pronunciation is to be returned. All voices for the same language (for example, `en-US`) return the same translation. For more information about specifying a voice, see **Important voice - updates** in the method description. + updates for IBM Cloud** in the method description. + **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean + languages and voices are supported only for IBM Cloud. """ AR_AR_OMARVOICE = 'ar-AR_OmarVoice' AR_MS_OMARVOICE = 'ar-MS_OmarVoice' @@ -1781,6 +1799,7 @@ class Voice(str, Enum): KO_KR_SIWOOVOICE = 'ko-KR_SiWooVoice' KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' + NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' @@ -1823,6 +1842,7 @@ class Language(str, Enum): IT_IT = 'it-IT' JA_JP = 'ja-JP' KO_KR = 'ko-KR' + NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' ZH_CN = 'zh-CN' @@ -1838,8 +1858,8 @@ class CustomModel(): Information about an existing custom model. :attr str customization_id: The customization ID (GUID) of the custom model. The - **Create a custom model** method returns only this field. It does not not return - the other fields of this object. + [Create a custom model](#createcustommodel) method returns only this field. It + does not not return the other fields of this object. :attr str name: (optional) The name of the custom model. :attr str language: (optional) The language identifier of the custom model (for example, `en-US`). @@ -1858,11 +1878,11 @@ class CustomModel(): words and their translations from the custom model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if no words are defined for the custom model. This field is - returned only by the **Get a custom model** method. + returned only by the [Get a custom model](#getcustommodel) method. :attr List[Prompt] prompts: (optional) An array of `Prompt` objects that provides information about the prompts that are defined for the specified custom model. The array is empty if no prompts are defined for the custom model. This - field is returned only by the **Get a custom model** method. + field is returned only by the [Get a custom model](#getcustommodel) method. """ def __init__(self, @@ -1880,8 +1900,8 @@ def __init__(self, Initialize a CustomModel object. :param str customization_id: The customization ID (GUID) of the custom - model. The **Create a custom model** method returns only this field. It - does not not return the other fields of this object. + model. The [Create a custom model](#createcustommodel) method returns only + this field. It does not not return the other fields of this object. :param str name: (optional) The name of the custom model. :param str language: (optional) The language identifier of the custom model (for example, `en-US`). @@ -1900,12 +1920,13 @@ def __init__(self, the words and their translations from the custom model. The words are listed in alphabetical order, with uppercase letters listed before lowercase letters. The array is empty if no words are defined for the - custom model. This field is returned only by the **Get a custom model** - method. + custom model. This field is returned only by the [Get a custom + model](#getcustommodel) method. :param List[Prompt] prompts: (optional) An array of `Prompt` objects that provides information about the prompts that are defined for the specified custom model. The array is empty if no prompts are defined for the custom - model. This field is returned only by the **Get a custom model** method. + model. This field is returned only by the [Get a custom + model](#getcustommodel) method. """ self.customization_id = customization_id self.name = name @@ -3038,8 +3059,9 @@ class Voice(): :attr SupportedFeatures supported_features: Additional service features that are supported with the voice. :attr CustomModel customization: (optional) Returns information about a - specified custom model. This field is returned only by the **Get a voice** - method and only when you specify the customization ID of a custom model. + specified custom model. This field is returned only by the [Get a + voice](#getvoice) method and only when you specify the customization ID of a + custom model. """ def __init__(self, @@ -3068,8 +3090,9 @@ def __init__(self, :param SupportedFeatures supported_features: Additional service features that are supported with the voice. :param CustomModel customization: (optional) Returns information about a - specified custom model. This field is returned only by the **Get a voice** - method and only when you specify the customization ID of a custom model. + specified custom model. This field is returned only by the [Get a + voice](#getvoice) method and only when you specify the customization ID of + a custom model. """ self.url = url self.gender = gender @@ -3361,32 +3384,32 @@ class PartOfSpeechEnum(str, Enum): class Words(): """ - For the **Add custom words** method, one or more words that are to be added or updated - for the custom model and the translation for each specified word. - For the **List custom words** method, the words and their translations from the custom - model. - - :attr List[Word] words: The **Add custom words** method accepts an array of - `Word` objects. Each object provides a word that is to be added or updated for - the custom model and the word's translation. - The **List custom words** method returns an array of `Word` objects. Each object - shows a word and its translation from the custom model. The words are listed in - alphabetical order, with uppercase letters listed before lowercase letters. The - array is empty if the custom model contains no words. + For the [Add custom words](#addwords) method, one or more words that are to be added + or updated for the custom model and the translation for each specified word. + For the [List custom words](#listwords) method, the words and their translations from + the custom model. + + :attr List[Word] words: The [Add custom words](#addwords) method accepts an + array of `Word` objects. Each object provides a word that is to be added or + updated for the custom model and the word's translation. + The [List custom words](#listwords) method returns an array of `Word` objects. + Each object shows a word and its translation from the custom model. The words + are listed in alphabetical order, with uppercase letters listed before lowercase + letters. The array is empty if the custom model contains no words. """ def __init__(self, words: List['Word']) -> None: """ Initialize a Words object. - :param List[Word] words: The **Add custom words** method accepts an array - of `Word` objects. Each object provides a word that is to be added or - updated for the custom model and the word's translation. - The **List custom words** method returns an array of `Word` objects. Each - object shows a word and its translation from the custom model. The words - are listed in alphabetical order, with uppercase letters listed before - lowercase letters. The array is empty if the custom model contains no - words. + :param List[Word] words: The [Add custom words](#addwords) method accepts + an array of `Word` objects. Each object provides a word that is to be added + or updated for the custom model and the word's translation. + The [List custom words](#listwords) method returns an array of `Word` + objects. Each object shows a word and its translation from the custom + model. The words are listed in alphabetical order, with uppercase letters + listed before lowercase letters. The array is empty if the custom model + contains no words. """ self.words = words From a598231df416e8cbf4453342b42ce5a5d8c6be85 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 9 Sep 2021 15:57:09 -0400 Subject: [PATCH 357/455] fix(disco_v2): project types enum updated/fixed --- ibm_watson/discovery_v2.py | 661 +++++++++++++++++++++---------------- 1 file changed, 380 insertions(+), 281 deletions(-) diff --git a/ibm_watson/discovery_v2.py b/ibm_watson/discovery_v2.py index c17756c7c..708007d08 100644 --- a/ibm_watson/discovery_v2.py +++ b/ibm_watson/discovery_v2.py @@ -14,13 +14,16 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ IBM Watson™ Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive better decision-making. Securely unify structured and unstructured data with pre-enriched content, and use a simplified query language to eliminate the need for manual filtering of results. + +API Version: 2.0 +See: https://cloud.ibm.com/docs/discovery-data """ from datetime import datetime @@ -58,7 +61,7 @@ def __init__( Construct a new client for the Discovery service. :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2019-11-22`. + Specify dates in YYYY-MM-DD format. The current version is `2020-08-30`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md @@ -86,7 +89,7 @@ def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: Lists existing collections for the specified project. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ListCollectionsResponse` object @@ -115,7 +118,7 @@ def list_collections(self, project_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_collection(self, @@ -132,7 +135,7 @@ def create_collection(self, Create a new collection in the specified project. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str name: The name of the collection. :param str description: (optional) A description of the collection. :param str language: (optional) The language of the collection. @@ -181,7 +184,7 @@ def create_collection(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_collection(self, project_id: str, collection_id: str, @@ -192,7 +195,7 @@ def get_collection(self, project_id: str, collection_id: str, Get details about the specified collection. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -225,7 +228,7 @@ def get_collection(self, project_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_collection(self, @@ -242,7 +245,7 @@ def update_collection(self, Updates the specified collection's name, description, and enrichments. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. :param str name: (optional) The name of the collection. :param str description: (optional) A description of the collection. @@ -291,7 +294,7 @@ def update_collection(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_collection(self, project_id: str, collection_id: str, @@ -303,7 +306,7 @@ def delete_collection(self, project_id: str, collection_id: str, specified collection and not shared is also deleted. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -335,7 +338,7 @@ def delete_collection(self, project_id: str, collection_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -373,7 +376,7 @@ def query(self, settings. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param List[str] collection_ids: (optional) A comma-separated list of collection IDs to be queried against. :param str filter: (optional) A cacheable query that excludes documents @@ -392,16 +395,15 @@ def query(self, possible aggregations, see the Query reference. :param int count: (optional) Number of results to return. :param List[str] return_: (optional) A list of the fields in the document - hierarchy to return. If this parameter not specified, then all top-level - fields are returned. + hierarchy to return. If this parameter is an empty list, then all fields + are returned. :param int offset: (optional) The number of query results to skip at the beginning. For example, if the total number of results that are returned is 10 and the offset is 8, it returns the last two results. :param str sort: (optional) A comma-separated list of fields in the document to sort on. You can optionally specify a sort direction by prefixing the field with `-` for descending or `+` for ascending. Ascending - is the default sort direction if no prefix is specified. This parameter - cannot be used in the same query as the **bias** parameter. + is the default sort direction if no prefix is specified. :param bool highlight: (optional) When `true`, a highlight field is returned for each result which contains the fields which match the query with `` tags around the matching query terms. @@ -413,7 +415,7 @@ def query(self, :param QueryLargeTableResults table_results: (optional) Configuration for table retrieval. :param QueryLargeSuggestedRefinements suggested_refinements: (optional) - Configuration for suggested refinements. + Configuration for suggested refinements. Available with Premium plans only. :param QueryLargePassages passages: (optional) Configuration for passage retrieval. :param dict headers: A `dict` containing the request headers @@ -471,7 +473,7 @@ def query(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_autocompletion(self, @@ -488,10 +490,9 @@ def get_autocompletion(self, Returns completion query suggestions for the specified prefix. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str prefix: The prefix to use for autocompletion. For example, the - prefix `Ho` could autocomplete to `Hot`, `Housing`, or `How do I upgrade`. - Possible completions are. + prefix `Ho` could autocomplete to `hot`, `housing`, or `how`. :param List[str] collection_ids: (optional) Comma separated list of the collection IDs. If this parameter is not specified, all collections in the project are used. @@ -536,7 +537,7 @@ def get_autocompletion(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def query_collection_notices(self, @@ -556,7 +557,7 @@ def query_collection_notices(self, documents are ingested. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. :param str filter: (optional) A cacheable query that excludes documents that don't mention the query content. Filter searches are better for @@ -611,7 +612,7 @@ def query_collection_notices(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def query_notices(self, @@ -630,7 +631,7 @@ def query_notices(self, notices are generated by relevancy training. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str filter: (optional) A cacheable query that excludes documents that don't mention the query content. Filter searches are better for metadata-type searches and for assessing the concepts in the data set. @@ -681,7 +682,7 @@ def query_notices(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_fields(self, @@ -696,7 +697,7 @@ def list_fields(self, collections. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param List[str] collection_ids: (optional) Comma separated list of the collection IDs. If this parameter is not specified, all collections in the project are used. @@ -731,7 +732,7 @@ def list_fields(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -746,7 +747,7 @@ def get_component_settings(self, project_id: str, Returns default configuration settings for components. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ComponentSettingsResponse` object @@ -776,7 +777,7 @@ def get_component_settings(self, project_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -797,36 +798,35 @@ def add_document(self, Add a document. Add a document to a collection with optional metadata. - Returns immediately after the system has accepted the document for processing. + Returns immediately after the system has accepted the document for processing. * The user must provide document content, metadata, or both. If the request is missing both document content and metadata, it is rejected. - * The user can set the **Content-Type** parameter on the **file** part to - indicate the media type of the document. If the **Content-Type** parameter is - missing or is one of the generic media types (for example, - `application/octet-stream`), then the service attempts to automatically detect the - document's media type. - * The following field names are reserved and will be filtered out if present - after normalization: `id`, `score`, `highlight`, and any field with the prefix of: - `_`, `+`, or `-` + * You can set the **Content-Type** parameter on the **file** part to indicate + the media type of the document. If the **Content-Type** parameter is missing or is + one of the generic media types (for example, `application/octet-stream`), then the + service attempts to automatically detect the document's media type. + * The following field names are reserved and are filtered out if present after + normalization: `id`, `score`, `highlight`, and any field with the prefix of: `_`, + `+`, or `-` * Fields with empty name values after normalization are filtered out before indexing. - * Fields containing the following characters after normalization are filtered + * Fields that contain the following characters after normalization are filtered out before indexing: `#` and `,` - If the document is uploaded to a collection that has it's data shared with - another collection, the **X-Watson-Discovery-Force** header must be set to `true`. - **Note:** Documents can be added with a specific **document_id** by using the - **/v2/projects/{project_id}/collections/{collection_id}/documents** method. - **Note:** This operation only works on collections created to accept direct file - uploads. It cannot be used to modify a collection that connects to an external - source such as Microsoft SharePoint. + If the document is uploaded to a collection that shares its data with another + collection, the **X-Watson-Discovery-Force** header must be set to `true`. + **Note:** You can assign an ID to a document that you add by appending the ID to + the endpoint + (`/v2/projects/{project_id}/collections/{collection_id}/documents/{document_id}`). + If a document already exists with the specified ID, it is replaced. + **Note:** This operation works with a file upload collection. It cannot be used to + modify a collection that crawls an external data source. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) The content of the document to ingest. The - maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a configuration is - 1 megabyte. Files larger than the supported size are rejected. + :param BinaryIO file: (optional) The content of the document to ingest. For + maximum supported file size limits, see [the + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str metadata: (optional) The maximum supported metadata file size is @@ -881,7 +881,7 @@ def add_document(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_document(self, @@ -900,24 +900,23 @@ def update_document(self, Replace an existing document or add a document with a specified **document_id**. Starts ingesting a document with optional metadata. - If the document is uploaded to a collection that has it's data shared with another + If the document is uploaded to a collection that shares its data with another collection, the **X-Watson-Discovery-Force** header must be set to `true`. **Note:** When uploading a new document with this method it automatically replaces any document stored with the same **document_id** if it exists. **Note:** This operation only works on collections created to accept direct file uploads. It cannot be used to modify a collection that connects to an external source such as Microsoft SharePoint. - **Note:** If an uploaded document is segmented, all segments will be overwritten, - even if the updated version of the document has fewer segments. + **Note:** If an uploaded document is segmented, all segments are overwritten, even + if the updated version of the document has fewer segments. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. - :param BinaryIO file: (optional) The content of the document to ingest. The - maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a configuration is - 1 megabyte. Files larger than the supported size are rejected. + :param BinaryIO file: (optional) The content of the document to ingest. For + maximum supported file size limits, see [the + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str metadata: (optional) The maximum supported metadata file size is @@ -975,7 +974,7 @@ def update_document(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_document(self, @@ -998,7 +997,7 @@ def delete_document(self, all segments by deleting using the `parent_document_id` of a segment result. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. :param str document_id: The ID of the document. :param bool x_watson_discovery_force: (optional) When `true`, the uploaded @@ -1038,7 +1037,7 @@ def delete_document(self, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1053,7 +1052,7 @@ def list_training_queries(self, project_id: str, List the training queries for the specified project. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `TrainingQuerySet` object @@ -1083,7 +1082,7 @@ def list_training_queries(self, project_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_training_queries(self, project_id: str, @@ -1094,7 +1093,7 @@ def delete_training_queries(self, project_id: str, Removes all training queries for the specified project. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1123,7 +1122,7 @@ def delete_training_queries(self, project_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_training_query(self, @@ -1140,7 +1139,7 @@ def create_training_query(self, and natural language query. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str natural_language_query: The natural text query for the training query. :param List[TrainingExample] examples: Array of training examples. @@ -1190,7 +1189,7 @@ def create_training_query(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_training_query(self, project_id: str, query_id: str, @@ -1202,7 +1201,7 @@ def get_training_query(self, project_id: str, query_id: str, examples. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1235,7 +1234,7 @@ def get_training_query(self, project_id: str, query_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_training_query(self, @@ -1252,7 +1251,7 @@ def update_training_query(self, Updates an existing training query and it's examples. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str query_id: The ID of the query used for training. :param str natural_language_query: The natural text query for the training query. @@ -1305,7 +1304,7 @@ def update_training_query(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_training_query(self, project_id: str, query_id: str, @@ -1317,7 +1316,7 @@ def delete_training_query(self, project_id: str, query_id: str, examples. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str query_id: The ID of the query used for training. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1349,7 +1348,7 @@ def delete_training_query(self, project_id: str, query_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1368,20 +1367,17 @@ def analyze_document(self, """ Analyze a Document. - Process a document using the specified collection's settings and return it for - realtime use. - **Note:** Documents processed using this method are not added to the specified - collection. - **Note:** This method is only supported on IBM Cloud Pak for Data instances of - Discovery. + Process a document and return it for realtime use. Supports JSON files only. + The document is processed according to the collection's configuration settings but + is not stored in the collection. + **Note:** This method is supported on installed instances of Discovery only. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str collection_id: The ID of the collection. - :param BinaryIO file: (optional) The content of the document to ingest. The - maximum supported file size when adding a file to a collection is 50 - megabytes, the maximum supported file size when testing a configuration is - 1 megabyte. Files larger than the supported size are rejected. + :param BinaryIO file: (optional) The content of the document to ingest. For + maximum supported file size limits, see [the + documentation](https://cloud.ibm.com/docs/discovery-data?topic=discovery-data-collections#collections-doc-limits). :param str filename: (optional) The filename for file. :param str file_content_type: (optional) The content type of file. :param str metadata: (optional) The maximum supported metadata file size is @@ -1433,7 +1429,7 @@ def analyze_document(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1444,10 +1440,12 @@ def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: """ List Enrichments. - List the enrichments available to this project. + Lists the enrichments available to this project. The *Part of Speech* and + *Sentiment of Phrases* enrichments might be listed, but are reserved for internal + use only. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Enrichments` object @@ -1476,7 +1474,7 @@ def list_enrichments(self, project_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_enrichment(self, @@ -1488,10 +1486,10 @@ def create_enrichment(self, """ Create an enrichment. - Create an enrichment for use with the specified project/. + Create an enrichment for use with the specified project. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param CreateEnrichment enrichment: Information about a specific enrichment. :param BinaryIO file: (optional) The enrichment file to upload. @@ -1532,7 +1530,7 @@ def create_enrichment(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_enrichment(self, project_id: str, enrichment_id: str, @@ -1543,7 +1541,7 @@ def get_enrichment(self, project_id: str, enrichment_id: str, Get details about a specific enrichment. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str enrichment_id: The ID of the enrichment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1576,7 +1574,7 @@ def get_enrichment(self, project_id: str, enrichment_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_enrichment(self, @@ -1592,7 +1590,7 @@ def update_enrichment(self, Updates an existing enrichment's name and description. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str enrichment_id: The ID of the enrichment. :param str name: A new name for the enrichment. :param str description: (optional) A new description for the enrichment. @@ -1635,7 +1633,7 @@ def update_enrichment(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_enrichment(self, project_id: str, enrichment_id: str, @@ -1647,7 +1645,7 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, **Note:** Only enrichments that have been manually created can be deleted. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str enrichment_id: The ID of the enrichment. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1679,7 +1677,7 @@ def delete_enrichment(self, project_id: str, enrichment_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1715,7 +1713,7 @@ def list_projects(self, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def create_project(self, @@ -1730,7 +1728,11 @@ def create_project(self, Create a new project for this instance. :param str name: The human readable name of this project. - :param str type: The project type of this project. + :param str type: The type of project. + The `content_intelligence` type is a *Document Retrieval for Contracts* + project and the `other` type is a *Custom* project. + The `content_mining` and `content_intelligence` types are available with + Premium plan managed deployments and installed deployments only. :param DefaultQueryParams default_query_parameters: (optional) Default query parameters for this project. :param dict headers: A `dict` containing the request headers @@ -1772,7 +1774,7 @@ def create_project(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_project(self, project_id: str, **kwargs) -> DetailedResponse: @@ -1782,7 +1784,7 @@ def get_project(self, project_id: str, **kwargs) -> DetailedResponse: Get details on the specified project. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `ProjectDetails` object @@ -1811,7 +1813,7 @@ def get_project(self, project_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_project(self, @@ -1825,7 +1827,7 @@ def update_project(self, Update the specified project's name. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param str name: (optional) The new name to give this project. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -1861,7 +1863,7 @@ def update_project(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: @@ -1873,7 +1875,7 @@ def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: project, including all collections. :param str project_id: The ID of the project. This information can be found - from the deploy page of the Discovery administrative tooling. + from the *Integrate and Deploy* page in Discovery. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -1901,7 +1903,7 @@ def delete_project(self, project_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -1946,7 +1948,7 @@ def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response @@ -2008,7 +2010,7 @@ class FileContentType(str, Enum): class AnalyzedDocument(): """ - An object containing the converted document and any identified enrichments. + An object that contains the converted document and any identified enrichments. :attr List[Notice] notices: (optional) Array of document results that match the query. @@ -2127,6 +2129,29 @@ def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of AnalyzedResult""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in AnalyzedResult._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of AnalyzedResult""" + for _key in [ + k for k in vars(self).keys() + if k not in AnalyzedResult._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in AnalyzedResult._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this AnalyzedResult object.""" return json.dumps(self.to_dict(), indent=2) @@ -2314,6 +2339,8 @@ class CollectionEnrichment(): :attr str enrichment_id: (optional) The unique identifier of this enrichment. :attr List[str] fields: (optional) An array of field names that the enrichment is applied to. + If you apply an enrichment to a field from a JSON file, the data is converted to + an array automatically, even if the field contains a single value. """ def __init__(self, @@ -2327,6 +2354,9 @@ def __init__(self, enrichment. :param List[str] fields: (optional) An array of field names that the enrichment is applied to. + If you apply an enrichment to a field from a JSON file, the data is + converted to an array automatically, even if the field contains a single + value. """ self.enrichment_id = enrichment_id self.fields = fields @@ -2376,7 +2406,7 @@ def __ne__(self, other: 'CollectionEnrichment') -> bool: class Completions(): """ - An object containing an array of autocompletion suggestions. + An object that contains an array of autocompletion suggestions. :attr List[str] completions: (optional) Array of autocomplete suggestion based on the provided prefix. @@ -2820,8 +2850,9 @@ class CreateEnrichment(): :attr str name: (optional) The human readable name for this enrichment. :attr str description: (optional) The description of this enrichment. :attr str type: (optional) The type of this enrichment. - :attr EnrichmentOptions options: (optional) A object containing options for the - current enrichment. + :attr EnrichmentOptions options: (optional) An object that contains options for + the current enrichment. Starting with version `2020-08-30`, the enrichment + options are not included in responses from the List Enrichments method. """ def __init__(self, @@ -2836,8 +2867,10 @@ def __init__(self, :param str name: (optional) The human readable name for this enrichment. :param str description: (optional) The description of this enrichment. :param str type: (optional) The type of this enrichment. - :param EnrichmentOptions options: (optional) A object containing options - for the current enrichment. + :param EnrichmentOptions options: (optional) An object that contains + options for the current enrichment. Starting with version `2020-08-30`, the + enrichment options are not included in responses from the List Enrichments + method. """ self.name = name self.description = description @@ -2918,7 +2951,8 @@ class DefaultQueryParams(): :attr str aggregation: (optional) A string representing the default aggregation query for the project. :attr DefaultQueryParamsSuggestedRefinements suggested_refinements: (optional) - Object containing suggested refinement settings. + Object that contains suggested refinement settings. Available with Premium plans + only. :attr bool spelling_suggestions: (optional) When `true`, a spelling suggestions for the query are returned by default. :attr bool highlight: (optional) When `true`, a highlights for the query are @@ -2956,7 +2990,8 @@ def __init__(self, :param str aggregation: (optional) A string representing the default aggregation query for the project. :param DefaultQueryParamsSuggestedRefinements suggested_refinements: - (optional) Object containing suggested refinement settings. + (optional) Object that contains suggested refinement settings. Available + with Premium plans only. :param bool spelling_suggestions: (optional) When `true`, a spelling suggestions for the query are returned by default. :param bool highlight: (optional) When `true`, a highlights for the query @@ -3173,10 +3208,10 @@ def __ne__(self, other: 'DefaultQueryParamsPassages') -> bool: class DefaultQueryParamsSuggestedRefinements(): """ - Object containing suggested refinement settings. + Object that contains suggested refinement settings. Available with Premium plans only. - :attr bool enabled: (optional) When `true`, a suggested refinements for the - query are returned by default. + :attr bool enabled: (optional) When `true`, suggested refinements for the query + are returned by default. :attr int count: (optional) The number of suggested refinements to return by default. """ @@ -3185,8 +3220,8 @@ def __init__(self, *, enabled: bool = None, count: int = None) -> None: """ Initialize a DefaultQueryParamsSuggestedRefinements object. - :param bool enabled: (optional) When `true`, a suggested refinements for - the query are returned by default. + :param bool enabled: (optional) When `true`, suggested refinements for the + query are returned by default. :param int count: (optional) The number of suggested refinements to return by default. """ @@ -3545,8 +3580,9 @@ class Enrichment(): :attr str name: (optional) The human readable name for this enrichment. :attr str description: (optional) The description of this enrichment. :attr str type: (optional) The type of this enrichment. - :attr EnrichmentOptions options: (optional) A object containing options for the - current enrichment. + :attr EnrichmentOptions options: (optional) An object that contains options for + the current enrichment. Starting with version `2020-08-30`, the enrichment + options are not included in responses from the List Enrichments method. """ def __init__(self, @@ -3562,8 +3598,10 @@ def __init__(self, :param str name: (optional) The human readable name for this enrichment. :param str description: (optional) The description of this enrichment. :param str type: (optional) The type of this enrichment. - :param EnrichmentOptions options: (optional) A object containing options - for the current enrichment. + :param EnrichmentOptions options: (optional) An object that contains + options for the current enrichment. Starting with version `2020-08-30`, the + enrichment options are not included in responses from the List Enrichments + method. """ self.enrichment_id = enrichment_id self.name = name @@ -3642,19 +3680,22 @@ class TypeEnum(str, Enum): class EnrichmentOptions(): """ - A object containing options for the current enrichment. + An object that contains options for the current enrichment. Starting with version + `2020-08-30`, the enrichment options are not included in responses from the List + Enrichments method. :attr List[str] languages: (optional) An array of supported languages for this - enrichment. - :attr str entity_type: (optional) The type of entity. Required when creating - `dictionary` and `regular_expression` **type** enrichment. Not valid when - creating any other type of enrichment. + enrichment. Required when `type` is `dictionary`. Optional when `type` is + `rule_based`. Not valid when creating any other type of enrichment. + :attr str entity_type: (optional) The name of the entity type. This value is + used as the field name in the index. Required when `type` is `dictionary` or + `regular_expression`. Not valid when creating any other type of enrichment. :attr str regular_expression: (optional) The regular expression to apply for - this enrichment. Required only when the **type** of enrichment being created is - a `regular_expression`. Not valid when creating any other type of enrichment. + this enrichment. Required when `type` is `regular_expression`. Not valid when + creating any other type of enrichment. :attr str result_field: (optional) The name of the result document field that - this enrichment creates. Required only when the enrichment **type** is - `rule_based`. Not valid when creating any other type of enrichment. + this enrichment creates. Required when `type` is `rule_based`. Not valid when + creating any other type of enrichment. """ def __init__(self, @@ -3667,17 +3708,18 @@ def __init__(self, Initialize a EnrichmentOptions object. :param List[str] languages: (optional) An array of supported languages for - this enrichment. - :param str entity_type: (optional) The type of entity. Required when - creating `dictionary` and `regular_expression` **type** enrichment. Not - valid when creating any other type of enrichment. + this enrichment. Required when `type` is `dictionary`. Optional when `type` + is `rule_based`. Not valid when creating any other type of enrichment. + :param str entity_type: (optional) The name of the entity type. This value + is used as the field name in the index. Required when `type` is + `dictionary` or `regular_expression`. Not valid when creating any other + type of enrichment. :param str regular_expression: (optional) The regular expression to apply - for this enrichment. Required only when the **type** of enrichment being - created is a `regular_expression`. Not valid when creating any other type - of enrichment. + for this enrichment. Required when `type` is `regular_expression`. Not + valid when creating any other type of enrichment. :param str result_field: (optional) The name of the result document field - that this enrichment creates. Required only when the enrichment **type** is - `rule_based`. Not valid when creating any other type of enrichment. + that this enrichment creates. Required when `type` is `rule_based`. Not + valid when creating any other type of enrichment. """ self.languages = languages self.entity_type = entity_type @@ -3739,7 +3781,7 @@ def __ne__(self, other: 'EnrichmentOptions') -> bool: class Enrichments(): """ - An object containing an array of enrichment definitions. + An object that contains an array of enrichment definitions. :attr List[Enrichment] enrichments: (optional) An array of enrichment definitions. @@ -3797,7 +3839,7 @@ def __ne__(self, other: 'Enrichments') -> bool: class Field(): """ - Object containing field details. + Object that contains field details. :attr str field: (optional) The name of the field. :attr str type: (optional) The type of the field. @@ -3884,17 +3926,17 @@ class TypeEnum(str, Enum): class ListCollectionsResponse(): """ - Response object containing an array of collection details. + Response object that contains an array of collection details. - :attr List[Collection] collections: (optional) An array containing information - about each collection in the project. + :attr List[Collection] collections: (optional) An array that contains + information about each collection in the project. """ def __init__(self, *, collections: List['Collection'] = None) -> None: """ Initialize a ListCollectionsResponse object. - :param List[Collection] collections: (optional) An array containing + :param List[Collection] collections: (optional) An array that contains information about each collection in the project. """ self.collections = collections @@ -3950,16 +3992,16 @@ class ListFieldsResponse(): example, `warnings.properties.severity` means that the `warnings` object has a property called `severity`). - :attr List[Field] fields: (optional) An array containing information about each - field in the collections. + :attr List[Field] fields: (optional) An array that contains information about + each field in the collections. """ def __init__(self, *, fields: List['Field'] = None) -> None: """ Initialize a ListFieldsResponse object. - :param List[Field] fields: (optional) An array containing information about - each field in the collections. + :param List[Field] fields: (optional) An array that contains information + about each field in the collections. """ self.fields = fields @@ -4196,7 +4238,11 @@ class ProjectDetails(): :attr str project_id: (optional) The unique identifier of this project. :attr str name: (optional) The human readable name of this project. - :attr str type: (optional) The project type of this project. + :attr str type: (optional) The type of project. + The `content_intelligence` type is a *Document Retrieval for Contracts* project + and the `other` type is a *Custom* project. + The `content_mining` and `content_intelligence` types are available with Premium + plan managed deployments and installed deployments only. :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. :attr int collection_count: (optional) The number of collections configured in @@ -4218,7 +4264,11 @@ def __init__(self, Initialize a ProjectDetails object. :param str name: (optional) The human readable name of this project. - :param str type: (optional) The project type of this project. + :param str type: (optional) The type of project. + The `content_intelligence` type is a *Document Retrieval for Contracts* + project and the `other` type is a *Custom* project. + The `content_mining` and `content_intelligence` types are available with + Premium plan managed deployments and installed deployments only. :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. :param DefaultQueryParams default_query_parameters: (optional) Default @@ -4302,11 +4352,16 @@ def __ne__(self, other: 'ProjectDetails') -> bool: class TypeEnum(str, Enum): """ - The project type of this project. + The type of project. + The `content_intelligence` type is a *Document Retrieval for Contracts* project + and the `other` type is a *Custom* project. + The `content_mining` and `content_intelligence` types are available with Premium + plan managed deployments and installed deployments only. """ DOCUMENT_RETRIEVAL = 'document_retrieval' - ANSWER_RETRIEVAL = 'answer_retrieval' + CONVERSATIONAL_SEARCH = 'conversational_search' CONTENT_MINING = 'content_mining' + CONTENT_INTELLIGENCE = 'content_intelligence' OTHER = 'other' @@ -4316,7 +4371,11 @@ class ProjectListDetails(): :attr str project_id: (optional) The unique identifier of this project. :attr str name: (optional) The human readable name of this project. - :attr str type: (optional) The project type of this project. + :attr str type: (optional) The type of project. + The `content_intelligence` type is a *Document Retrieval for Contracts* project + and the `other` type is a *Custom* project. + The `content_mining` and `content_intelligence` types are available with Premium + plan managed deployments and installed deployments only. :attr ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. :attr int collection_count: (optional) The number of collections configured in @@ -4335,7 +4394,11 @@ def __init__(self, Initialize a ProjectListDetails object. :param str name: (optional) The human readable name of this project. - :param str type: (optional) The project type of this project. + :param str type: (optional) The type of project. + The `content_intelligence` type is a *Document Retrieval for Contracts* + project and the `other` type is a *Custom* project. + The `content_mining` and `content_intelligence` types are available with + Premium plan managed deployments and installed deployments only. :param ProjectListDetailsRelevancyTrainingStatus relevancy_training_status: (optional) Relevancy training status information for this project. """ @@ -4408,11 +4471,16 @@ def __ne__(self, other: 'ProjectListDetails') -> bool: class TypeEnum(str, Enum): """ - The project type of this project. + The type of project. + The `content_intelligence` type is a *Document Retrieval for Contracts* project + and the `other` type is a *Custom* project. + The `content_mining` and `content_intelligence` types are available with Premium + plan managed deployments and installed deployments only. """ DOCUMENT_RETRIEVAL = 'document_retrieval' - ANSWER_RETRIEVAL = 'answer_retrieval' + CONVERSATIONAL_SEARCH = 'conversational_search' CONTENT_MINING = 'content_mining' + CONTENT_INTELLIGENCE = 'content_intelligence' OTHER = 'other' @@ -4658,7 +4726,7 @@ class QueryGroupByAggregationResult(): Top value result for the term aggregation. :attr str key: Value of the field with a non-zero frequency in the document set. - :attr int matching_results: Number of documents containing the 'key'. + :attr int matching_results: Number of documents that contain the 'key'. :attr float relevancy: (optional) The relevancy for this group. :attr int total_matching_documents: (optional) The number of documents which have the group as the value of specified field in the whole set of documents in @@ -4666,8 +4734,8 @@ class QueryGroupByAggregationResult(): :attr int estimated_matching_documents: (optional) The estimated number of documents which would match the query and also meet the condition. Returned only when the `relevancy` parameter is set to `true`. - :attr List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :attr List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ def __init__(self, @@ -4683,7 +4751,7 @@ def __init__(self, :param str key: Value of the field with a non-zero frequency in the document set. - :param int matching_results: Number of documents containing the 'key'. + :param int matching_results: Number of documents that contain the 'key'. :param float relevancy: (optional) The relevancy for this group. :param int total_matching_documents: (optional) The number of documents which have the group as the value of specified field in the whole set of @@ -4692,8 +4760,8 @@ def __init__(self, :param int estimated_matching_documents: (optional) The estimated number of documents which would match the query and also meet the condition. Returned only when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :param List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ self.key = key self.matching_results = matching_results @@ -4784,8 +4852,8 @@ class QueryHistogramAggregationResult(): :attr int key: The value of the upper bound for the numeric segment. :attr int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :attr List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ def __init__(self, @@ -4799,8 +4867,8 @@ def __init__(self, :param int key: The value of the upper bound for the numeric segment. :param int matching_results: Number of documents with the specified key as the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :param List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ self.key = key self.matching_results = matching_results @@ -4870,35 +4938,38 @@ class QueryLargePassages(): :attr bool enabled: (optional) A passages query that returns the most relevant passages from the results. - :attr bool per_document: (optional) When `true`, passages will be returned - within their respective result. + :attr bool per_document: (optional) If `true`, ranks the documents by document + quality, and then returns the highest-ranked passages per document in a + `document_passages` field for each document entry in the results list of the + response. + If `false`, ranks the passages from all of the documents by passage quality + regardless of the document quality and returns them in a separate `passages` + field in the response. :attr int max_per_document: (optional) Maximum number of passages to return per - result. - :attr List[str] fields: (optional) A list of fields that passages are drawn - from. If this parameter not specified, then all top-level fields are included. - :attr int count: (optional) The maximum number of passages to return. The search - returns fewer passages if the requested total is not found. The maximum is - `100`. + document in the result. Ignored if `passages.per_document` is `false`. + :attr List[str] fields: (optional) A list of fields to extract passages from. If + this parameter is an empty list, then all root-level fields are included. + :attr int count: (optional) The maximum number of passages to return. Ignored if + `passages.per_document` is `true`. :attr int characters: (optional) The approximate number of characters that any one passage will have. :attr bool find_answers: (optional) When true, `answer` objects are returned as part of each passage in the query results. The primary difference between an `answer` and a `passage` is that the length of a passage is defined by the query, where the length of an `answer` is calculated by Discovery based on how - much text is needed to answer the question./n/nThis parameter is ignored if - passages are not enabled for the query, or no **natural_language_query** is - specified./n/nIf the **find_answers** parameter is set to `true` and - **per_document** parameter is also set to `true`, then the document search - results and the passage search results within each document are reordered using - the answer confidences. The goal of this reordering is to do as much as possible - to make sure that the first answer of the first passage of the first document is - the best answer. Similarly, if the **find_answers** parameter is set to `true` - and **per_document** parameter is set to `false`, then the passage search - results are reordered in decreasing order of the highest confidence answer for - each document and passage./n/nThe **find_answers** parameter is **beta** - functionality available only on managed instances and should not be used in a - production environment. This parameter is not available on installed instances - of Discovery. + much text is needed to answer the question. + This parameter is ignored if passages are not enabled for the query, or no + **natural_language_query** is specified. + If the **find_answers** parameter is set to `true` and **per_document** + parameter is also set to `true`, then the document search results and the + passage search results within each document are reordered using the answer + confidences. The goal of this reordering is to place the best answer as the + first answer of the first passage of the first document. Similarly, if the + **find_answers** parameter is set to `true` and **per_document** parameter is + set to `false`, then the passage search results are reordered in decreasing + order of the highest confidence answer for each document and passage. + The **find_answers** parameter is available only on managed instances of + Discovery. :attr int max_answers_per_passage: (optional) The number of `answer` objects to return per passage if the **find_answers** parmeter is specified as `true`. """ @@ -4918,16 +4989,21 @@ def __init__(self, :param bool enabled: (optional) A passages query that returns the most relevant passages from the results. - :param bool per_document: (optional) When `true`, passages will be returned - within their respective result. + :param bool per_document: (optional) If `true`, ranks the documents by + document quality, and then returns the highest-ranked passages per document + in a `document_passages` field for each document entry in the results list + of the response. + If `false`, ranks the passages from all of the documents by passage quality + regardless of the document quality and returns them in a separate + `passages` field in the response. :param int max_per_document: (optional) Maximum number of passages to - return per result. - :param List[str] fields: (optional) A list of fields that passages are - drawn from. If this parameter not specified, then all top-level fields are + return per document in the result. Ignored if `passages.per_document` is + `false`. + :param List[str] fields: (optional) A list of fields to extract passages + from. If this parameter is an empty list, then all root-level fields are included. - :param int count: (optional) The maximum number of passages to return. The - search returns fewer passages if the requested total is not found. The - maximum is `100`. + :param int count: (optional) The maximum number of passages to return. + Ignored if `passages.per_document` is `true`. :param int characters: (optional) The approximate number of characters that any one passage will have. :param bool find_answers: (optional) When true, `answer` objects are @@ -4935,20 +5011,20 @@ def __init__(self, difference between an `answer` and a `passage` is that the length of a passage is defined by the query, where the length of an `answer` is calculated by Discovery based on how much text is needed to answer the - question./n/nThis parameter is ignored if passages are not enabled for the - query, or no **natural_language_query** is specified./n/nIf the + question. + This parameter is ignored if passages are not enabled for the query, or no + **natural_language_query** is specified. + If the **find_answers** parameter is set to `true` and **per_document** + parameter is also set to `true`, then the document search results and the + passage search results within each document are reordered using the answer + confidences. The goal of this reordering is to place the best answer as the + first answer of the first passage of the first document. Similarly, if the **find_answers** parameter is set to `true` and **per_document** parameter - is also set to `true`, then the document search results and the passage - search results within each document are reordered using the answer - confidences. The goal of this reordering is to do as much as possible to - make sure that the first answer of the first passage of the first document - is the best answer. Similarly, if the **find_answers** parameter is set to - `true` and **per_document** parameter is set to `false`, then the passage - search results are reordered in decreasing order of the highest confidence - answer for each document and passage./n/nThe **find_answers** parameter is - **beta** functionality available only on managed instances and should not - be used in a production environment. This parameter is not available on - installed instances of Discovery. + is set to `false`, then the passage search results are reordered in + decreasing order of the highest confidence answer for each document and + passage. + The **find_answers** parameter is available only on managed instances of + Discovery. :param int max_answers_per_passage: (optional) The number of `answer` objects to return per passage if the **find_answers** parmeter is specified as `true`. @@ -5034,7 +5110,7 @@ def __ne__(self, other: 'QueryLargePassages') -> bool: class QueryLargeSuggestedRefinements(): """ - Configuration for suggested refinements. + Configuration for suggested refinements. Available with Premium plans only. :attr bool enabled: (optional) Whether to perform suggested refinements. :attr int count: (optional) Maximum number of suggested refinements texts to be @@ -5158,7 +5234,7 @@ def __ne__(self, other: 'QueryLargeTableResults') -> bool: class QueryNoticesResponse(): """ - Object containing notice query results. + Object that contains notice query results. :attr int matching_results: (optional) The number of matching results. :attr List[Notice] notices: (optional) Array of document results that match the @@ -5227,10 +5303,10 @@ def __ne__(self, other: 'QueryNoticesResponse') -> bool: class QueryResponse(): """ - A response containing the documents and aggregations for the query. + A response that contains the documents and aggregations for the query. :attr int matching_results: (optional) The number of matching results for the - query. + query. Results that match due to a curation only are not counted in the total. :attr List[QueryResult] results: (optional) Array of document results for the query. :attr List[QueryAggregation] aggregations: (optional) Array of aggregations for @@ -5242,8 +5318,8 @@ class QueryResponse(): :attr List[QuerySuggestedRefinement] suggested_refinements: (optional) Array of suggested refinements. :attr List[QueryTableResult] table_results: (optional) Array of table results. - :attr List[QueryResponsePassage] passages: (optional) Passages returned by - Discovery. + :attr List[QueryResponsePassage] passages: (optional) Passages that best match + the query from across all of the collections in the project. """ def __init__(self, @@ -5260,7 +5336,8 @@ def __init__(self, Initialize a QueryResponse object. :param int matching_results: (optional) The number of matching results for - the query. + the query. Results that match due to a curation only are not counted in the + total. :param List[QueryResult] results: (optional) Array of document results for the query. :param List[QueryAggregation] aggregations: (optional) Array of @@ -5273,8 +5350,8 @@ def __init__(self, Array of suggested refinements. :param List[QueryTableResult] table_results: (optional) Array of table results. - :param List[QueryResponsePassage] passages: (optional) Passages returned by - Discovery. + :param List[QueryResponsePassage] passages: (optional) Passages that best + match the query from across all of the collections in the project. """ self.matching_results = matching_results self.results = results @@ -5383,7 +5460,7 @@ class QueryResponsePassage(): :attr str collection_id: (optional) The unique identifier of the collection. :attr int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :attr int end_offset: (optional) The position of the last character of the + :attr int end_offset: (optional) The position after the last character of the extracted passage in the originating field. :attr str field: (optional) The label of the field from which the passage has been extracted. @@ -5416,8 +5493,8 @@ def __init__(self, collection. :param int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :param int end_offset: (optional) The position of the last character of the - extracted passage in the originating field. + :param int end_offset: (optional) The position after the last character of + the extracted passage in the originating field. :param str field: (optional) The label of the field from which the passage has been extracted. :param float confidence: (optional) An estimate of the probability that the @@ -5515,8 +5592,8 @@ class QueryResult(): :attr str document_id: The unique identifier of the document. :attr dict metadata: (optional) Metadata of the document. :attr QueryResultMetadata result_metadata: Metadata of a query result. - :attr List[QueryResultPassage] document_passages: (optional) Passages returned - by Discovery. + :attr List[QueryResultPassage] document_passages: (optional) Passages from the + document that best matches the query. """ # The set of defined properties for the class @@ -5536,8 +5613,8 @@ def __init__(self, :param str document_id: The unique identifier of the document. :param QueryResultMetadata result_metadata: Metadata of a query result. :param dict metadata: (optional) Metadata of the document. - :param List[QueryResultPassage] document_passages: (optional) Passages - returned by Discovery. + :param List[QueryResultPassage] document_passages: (optional) Passages from + the document that best matches the query. :param **kwargs: (optional) Any additional properties. """ self.document_id = document_id @@ -5606,6 +5683,27 @@ def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of QueryResult""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() if k not in QueryResult._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of QueryResult""" + for _key in [ + k for k in vars(self).keys() if k not in QueryResult._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in QueryResult._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this QueryResult object.""" return json.dumps(self.to_dict(), indent=2) @@ -5729,7 +5827,7 @@ class QueryResultPassage(): :attr str passage_text: (optional) The content of the extracted passage. :attr int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :attr int end_offset: (optional) The position of the last character of the + :attr int end_offset: (optional) The position after the last character of the extracted passage in the originating field. :attr str field: (optional) The label of the field from which the passage has been extracted. @@ -5753,8 +5851,8 @@ def __init__(self, :param str passage_text: (optional) The content of the extracted passage. :param int start_offset: (optional) The position of the first character of the extracted passage in the originating field. - :param int end_offset: (optional) The position of the last character of the - extracted passage in the originating field. + :param int end_offset: (optional) The position after the last character of + the extracted passage in the originating field. :param str field: (optional) The label of the field from which the passage has been extracted. :param float confidence: (optional) Estimate of the probability that the @@ -5996,7 +6094,7 @@ class QueryTermAggregationResult(): Top value result for the term aggregation. :attr str key: Value of the field with a non-zero frequency in the document set. - :attr int matching_results: Number of documents containing the 'key'. + :attr int matching_results: Number of documents that contain the 'key'. :attr float relevancy: (optional) The relevancy for this term. :attr int total_matching_documents: (optional) The number of documents which have the term as the value of specified field in the whole set of documents in @@ -6004,8 +6102,8 @@ class QueryTermAggregationResult(): :attr int estimated_matching_documents: (optional) The estimated number of documents which would match the query and also meet the condition. Returned only when the `relevancy` parameter is set to `true`. - :attr List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :attr List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ def __init__(self, @@ -6021,7 +6119,7 @@ def __init__(self, :param str key: Value of the field with a non-zero frequency in the document set. - :param int matching_results: Number of documents containing the 'key'. + :param int matching_results: Number of documents that contain the 'key'. :param float relevancy: (optional) The relevancy for this term. :param int total_matching_documents: (optional) The number of documents which have the term as the value of specified field in the whole set of @@ -6030,8 +6128,8 @@ def __init__(self, :param int estimated_matching_documents: (optional) The estimated number of documents which would match the query and also meet the condition. Returned only when the `relevancy` parameter is set to `true`. - :param List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :param List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ self.key = key self.matching_results = matching_results @@ -6125,8 +6223,8 @@ class QueryTimesliceAggregationResult(): in UNIX milliseconds since epoch. :attr int matching_results: Number of documents with the specified key as the upper bound. - :attr List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :attr List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ def __init__(self, @@ -6144,8 +6242,8 @@ def __init__(self, interval in UNIX milliseconds since epoch. :param int matching_results: Number of documents with the specified key as the upper bound. - :param List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :param List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ self.key_as_string = key_as_string self.key = key @@ -6220,7 +6318,7 @@ def __ne__(self, other: 'QueryTimesliceAggregationResult') -> bool: class QueryTopHitsAggregationResult(): """ - A query response containing the matching documents for the preceding aggregations. + A query response that contains the matching documents for the preceding aggregations. :attr int matching_results: Number of matching results. :attr List[dict] hits: (optional) An array of the document results. @@ -6289,13 +6387,13 @@ def __ne__(self, other: 'QueryTopHitsAggregationResult') -> bool: class ResultPassageAnswer(): """ - Object containing a potential answer to the specified query. + Object that contains a potential answer to the specified query. :attr str answer_text: (optional) Answer text for the specified query as identified by Discovery. :attr int start_offset: (optional) The position of the first character of the extracted answer in the originating field. - :attr int end_offset: (optional) The position of the last character of the + :attr int end_offset: (optional) The position after the last character of the extracted answer in the originating field. :attr float confidence: (optional) An estimate of the probability that the answer is relevant. @@ -6314,8 +6412,8 @@ def __init__(self, identified by Discovery. :param int start_offset: (optional) The position of the first character of the extracted answer in the originating field. - :param int end_offset: (optional) The position of the last character of the - extracted answer in the originating field. + :param int end_offset: (optional) The position after the last character of + the extracted answer in the originating field. :param float confidence: (optional) An estimate of the probability that the answer is relevant. """ @@ -6382,8 +6480,8 @@ class RetrievalDetails(): :attr str document_retrieval_strategy: (optional) Identifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. - **Note**: In the event of trained collections being queried, but the trained - model is not used to return results, the **document_retrieval_strategy** will be + **Note**: In the event of trained collections being queried, but the trained + model is not used to return results, the **document_retrieval_strategy** is listed as `untrained`. """ @@ -6394,9 +6492,9 @@ def __init__(self, *, document_retrieval_strategy: str = None) -> None: :param str document_retrieval_strategy: (optional) Identifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. - **Note**: In the event of trained collections being queried, but the + **Note**: In the event of trained collections being queried, but the trained model is not used to return results, the - **document_retrieval_strategy** will be listed as `untrained`. + **document_retrieval_strategy** is listed as `untrained`. """ self.document_retrieval_strategy = document_retrieval_strategy @@ -6446,9 +6544,9 @@ class DocumentRetrievalStrategyEnum(str, Enum): Identifies the document retrieval strategy used for this query. `relevancy_training` indicates that the results were returned using a relevancy trained model. - **Note**: In the event of trained collections being queried, but the trained - model is not used to return results, the **document_retrieval_strategy** will be - listed as `untrained`. + **Note**: In the event of trained collections being queried, but the trained model + is not used to return results, the **document_retrieval_strategy** is listed as + `untrained`. """ UNTRAINED = 'untrained' RELEVANCY_TRAINING = 'relevancy_training' @@ -7964,7 +8062,7 @@ def __ne__(self, other: 'TableTextLocation') -> bool: class TrainingExample(): """ - Object containing example response details for a training query. + Object that contains example response details for a training query. :attr str document_id: The document ID associated with this training example. :attr str collection_id: The collection ID associated with this training @@ -8065,7 +8163,7 @@ def __ne__(self, other: 'TrainingExample') -> bool: class TrainingQuery(): """ - Object containing training query details. + Object that contains training query details. :attr str query_id: (optional) The query ID associated with the training query. :attr str natural_language_query: The natural text query for the training query. @@ -8306,13 +8404,13 @@ def __ne__(self, other: 'QueryCalculationAggregation') -> bool: class QueryFilterAggregation(QueryAggregation): """ - A modifier that will narrow down the document set of the sub aggregations it precedes. + A modifier that narrows the document set of the sub-aggregations it precedes. - :attr str match: The filter written in Discovery Query Language syntax applied - to the documents before sub aggregations are run. - :attr int matching_results: Number of documents matching the filter. - :attr List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :attr str match: The filter that is written in Discovery Query Language syntax + and is applied to the documents before sub-aggregations are run. + :attr int matching_results: Number of documents that match the filter. + :attr List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ def __init__(self, @@ -8327,11 +8425,11 @@ def __init__(self, :param str type: The type of aggregation command used. Options include: term, histogram, timeslice, nested, filter, min, max, sum, average, unique_count, and top_hits. - :param str match: The filter written in Discovery Query Language syntax - applied to the documents before sub aggregations are run. - :param int matching_results: Number of documents matching the filter. - :param List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :param str match: The filter that is written in Discovery Query Language + syntax and is applied to the documents before sub-aggregations are run. + :param int matching_results: Number of documents that match the filter. + :param List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ self.type = type self.match = match @@ -8484,7 +8582,7 @@ class QueryHistogramAggregation(QueryAggregation): numeric field to describe the category. :attr str field: The numeric field name used to create the histogram. - :attr int interval: The size of the sections the results are split into. + :attr int interval: The size of the sections that the results are split into. :attr str name: (optional) Identifier specified in the query request of this aggregation. :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric @@ -8506,7 +8604,8 @@ def __init__( term, histogram, timeslice, nested, filter, min, max, sum, average, unique_count, and top_hits. :param str field: The numeric field name used to create the histogram. - :param int interval: The size of the sections the results are split into. + :param int interval: The size of the sections that the results are split + into. :param str name: (optional) Identifier specified in the query request of this aggregation. :param List[QueryHistogramAggregationResult] results: (optional) Array of @@ -8590,14 +8689,14 @@ def __ne__(self, other: 'QueryHistogramAggregation') -> bool: class QueryNestedAggregation(QueryAggregation): """ - A restriction that alter the document set used for sub aggregations it precedes to - nested documents found in the field specified. + A restriction that alters the document set that is used for sub-aggregations it + precedes to nested documents found in the field specified. - :attr str path: The path to the document field to scope sub aggregations to. + :attr str path: The path to the document field to scope sub-aggregations to. :attr int matching_results: Number of nested documents found in the specified field. - :attr List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :attr List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ def __init__(self, @@ -8612,12 +8711,12 @@ def __init__(self, :param str type: The type of aggregation command used. Options include: term, histogram, timeslice, nested, filter, min, max, sum, average, unique_count, and top_hits. - :param str path: The path to the document field to scope sub aggregations + :param str path: The path to the document field to scope sub-aggregations to. :param int matching_results: Number of nested documents found in the specified field. - :param List[QueryAggregation] aggregations: (optional) An array of sub - aggregations. + :param List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ self.type = type self.path = path From 9954e59df889b45b761ef206ad8dedd9502e762a Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Thu, 9 Sep 2021 15:58:29 -0400 Subject: [PATCH 358/455] fix(nlu): fix listClassificationsModels response model --- .../natural_language_understanding_v1.py | 149 ++++++------------ 1 file changed, 46 insertions(+), 103 deletions(-) diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index 9840166cf..bd3456a5b 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2021. +# (C) Copyright IBM Corp. 2017, 2021. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 99-SNAPSHOT-902c9336-20210507-162723 +# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you @@ -24,6 +24,9 @@ models](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) with Watson Knowledge Studio to detect custom entities and relations in Natural Language Understanding. + +API Version: 1.0 +See: https://cloud.ibm.com/docs/natural-language-understanding """ from datetime import datetime @@ -59,7 +62,7 @@ def __init__( Construct a new client for the Natural Language Understanding service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2021-03-25`. + Specify dates in YYYY-MM-DD format. The current version is `2021-08-01`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md @@ -182,7 +185,7 @@ def analyze(self, params=params, data=data) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -220,7 +223,7 @@ def list_models(self, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: @@ -258,7 +261,7 @@ def delete_model(self, model_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -337,7 +340,7 @@ def create_sentiment_model(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_sentiment_models(self, **kwargs) -> DetailedResponse: @@ -369,7 +372,7 @@ def list_sentiment_models(self, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_sentiment_model(self, model_id: str, **kwargs) -> DetailedResponse: @@ -407,7 +410,7 @@ def get_sentiment_model(self, model_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_sentiment_model(self, @@ -488,7 +491,7 @@ def update_sentiment_model(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_sentiment_model(self, model_id: str, @@ -528,7 +531,7 @@ def delete_sentiment_model(self, model_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -612,7 +615,7 @@ def create_categories_model(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_categories_models(self, **kwargs) -> DetailedResponse: @@ -644,7 +647,7 @@ def list_categories_models(self, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: @@ -682,7 +685,7 @@ def get_categories_model(self, model_id: str, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_categories_model(self, @@ -768,7 +771,7 @@ def update_categories_model(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_categories_model(self, model_id: str, @@ -808,7 +811,7 @@ def delete_categories_model(self, model_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response ######################### @@ -829,9 +832,9 @@ def create_classifications_model(self, """ Create classifications model. - (Beta) Creates a custom classifications model by uploading training data and - associated metadata. The model begins the training and deploying process and is - ready to use when the `status` is `available`. + Creates a custom classifications model by uploading training data and associated + metadata. The model begins the training and deploying process and is ready to use + when the `status` is `available`. :param str language: The 2-letter language code of this model. :param BinaryIO training_data: Training data in JSON format. For more @@ -893,19 +896,18 @@ def create_classifications_model(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def list_classifications_models(self, **kwargs) -> DetailedResponse: """ List classifications models. - (Beta) Returns all custom classifications models associated with this service - instance. + Returns all custom classifications models associated with this service instance. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ListClassificationsModelsResponse` object + :rtype: DetailedResponse with `dict` result representing a `ClassificationsModelList` object """ headers = {} @@ -927,7 +929,7 @@ def list_classifications_models(self, **kwargs) -> DetailedResponse: headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def get_classifications_model(self, model_id: str, @@ -935,7 +937,7 @@ def get_classifications_model(self, model_id: str, """ Get classifications model details. - (Beta) Returns the status of the classifications model with the given model ID. + Returns the status of the classifications model with the given model ID. :param str model_id: ID of the model. :param dict headers: A `dict` containing the request headers @@ -966,7 +968,7 @@ def get_classifications_model(self, model_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response def update_classifications_model(self, @@ -984,8 +986,8 @@ def update_classifications_model(self, """ Update classifications model. - (Beta) Overwrites the training data associated with this custom classifications - model and retrains the model. The new model replaces the current deployment. + Overwrites the training data associated with this custom classifications model and + retrains the model. The new model replaces the current deployment. :param str model_id: ID of the model. :param str language: The 2-letter language code of this model. @@ -1053,7 +1055,7 @@ def update_classifications_model(self, params=params, files=form_data) - response = self.send(request) + response = self.send(request, **kwargs) return response def delete_classifications_model(self, model_id: str, @@ -1061,9 +1063,8 @@ def delete_classifications_model(self, model_id: str, """ Delete classifications model. - (Beta) Un-deploys the custom classifications model with the given model ID and - deletes all associated customer data, including any training data or binary - artifacts. + Un-deploys the custom classifications model with the given model ID and deletes + all associated customer data, including any training data or binary artifacts. :param str model_id: ID of the model. :param dict headers: A `dict` containing the request headers @@ -1095,7 +1096,7 @@ def delete_classifications_model(self, model_id: str, headers=headers, params=params) - response = self.send(request) + response = self.send(request, **kwargs) return response @@ -1756,7 +1757,8 @@ def __ne__(self, other: 'CategoriesModelList') -> bool: class CategoriesOptions(): """ - Returns a five-level taxonomy of the content. The top three categories are returned. + Returns a hierarchical taxonomy of the content. The top three categories are returned + by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. @@ -1897,7 +1899,7 @@ class CategoriesResult(): """ A categorization of the analyzed text. - :attr str label: (optional) The path to the category through the 5-level + :attr str label: (optional) The path to the category through the multi-level taxonomy hierarchy. For more information about the categories, see [Categories hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). :attr float score: (optional) Confidence score for the category classification. @@ -1914,9 +1916,9 @@ def __init__(self, """ Initialize a CategoriesResult object. - :param str label: (optional) The path to the category through the 5-level - taxonomy hierarchy. For more information about the categories, see - [Categories + :param str label: (optional) The path to the category through the + multi-level taxonomy hierarchy. For more information about the categories, + see [Categories hierarchy](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-categories#categories-hierarchy). :param float score: (optional) Confidence score for the category classification. Higher values indicate greater confidence. @@ -2305,7 +2307,7 @@ class ClassificationsOptions(): Returns text classifications for the content. Supported languages: English only. - :attr str model: (optional) (Beta) Enter a [custom + :attr str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID of the classification model to be used. """ @@ -2314,7 +2316,7 @@ def __init__(self, *, model: str = None) -> None: """ Initialize a ClassificationsOptions object. - :param str model: (optional) (Beta) Enter a [custom + :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) ID of the classification model to be used. """ @@ -3485,8 +3487,8 @@ class Features(): :attr SummarizationOptions summarization: (optional) (Experimental) Returns a summary of content. Supported languages: English only. - :attr CategoriesOptions categories: (optional) Returns a five-level taxonomy of - the content. The top three categories are returned. + :attr CategoriesOptions categories: (optional) Returns a hierarchical taxonomy + of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. :attr SyntaxOptions syntax: (optional) Returns tokens and sentences from the @@ -3558,8 +3560,8 @@ def __init__(self, :param SummarizationOptions summarization: (optional) (Experimental) Returns a summary of content. Supported languages: English only. - :param CategoriesOptions categories: (optional) Returns a five-level - taxonomy of the content. The top three categories are returned. + :param CategoriesOptions categories: (optional) Returns a hierarchical + taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. :param SyntaxOptions syntax: (optional) Returns tokens and sentences from @@ -3990,65 +3992,6 @@ def __ne__(self, other: 'KeywordsResult') -> bool: return not self == other -class ListClassificationsModelsResponse(): - """ - ListClassificationsModelsResponse. - - :attr List[ClassificationsModelList] models: (optional) - """ - - def __init__(self, - *, - models: List['ClassificationsModelList'] = None) -> None: - """ - Initialize a ListClassificationsModelsResponse object. - - :param List[ClassificationsModelList] models: (optional) - """ - self.models = models - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ListClassificationsModelsResponse': - """Initialize a ListClassificationsModelsResponse object from a json dictionary.""" - args = {} - if 'models' in _dict: - args['models'] = [ - ClassificationsModelList.from_dict(x) - for x in _dict.get('models') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ListClassificationsModelsResponse 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, 'models') and self.models is not None: - _dict['models'] = [x.to_dict() for x in self.models] - 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 ListClassificationsModelsResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ListClassificationsModelsResponse') -> 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: 'ListClassificationsModelsResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ListModelsResults(): """ Custom models that are available for entities and relations. From ab880f04ae2ec5983e74175cd7b1dc83bd24f022 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 13 Sep 2021 09:22:52 -0400 Subject: [PATCH 359/455] fix(disco_v1): update type of status to reflect service changes --- ibm_watson/discovery_v1.py | 120 +++++++++++++++++++++++---------- test/unit/test_discovery_v1.py | 90 ++++++++++++++++++++----- 2 files changed, 159 insertions(+), 51 deletions(-) diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index b9be41b35..a00c1b9e9 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -3368,7 +3368,7 @@ def create_credentials(self, *, source_type: str = None, credential_details: 'CredentialDetails' = None, - status: str = None, + status: 'StatusDetails' = None, **kwargs) -> DetailedResponse: """ Create credentials. @@ -3393,11 +3393,8 @@ def create_credentials(self, :param CredentialDetails credential_details: (optional) Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. - :param str status: (optional) The current status of this set of - credentials. `connected` indicates that the credentials are available to - use with the source configuration of a collection. `invalid` refers to the - credentials (for example, the password provided has expired) and must be - corrected before they can be used with a collection. + :param StatusDetails status: (optional) Object that contains details about + the status of the authentication process. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Credentials` object @@ -3407,6 +3404,8 @@ def create_credentials(self, raise ValueError('environment_id must be provided') if credential_details is not None: credential_details = convert_model(credential_details) + if status is not None: + status = convert_model(status) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', @@ -3494,7 +3493,7 @@ def update_credentials(self, *, source_type: str = None, credential_details: 'CredentialDetails' = None, - status: str = None, + status: 'StatusDetails' = None, **kwargs) -> DetailedResponse: """ Update credentials. @@ -3520,11 +3519,8 @@ def update_credentials(self, :param CredentialDetails credential_details: (optional) Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. - :param str status: (optional) The current status of this set of - credentials. `connected` indicates that the credentials are available to - use with the source configuration of a collection. `invalid` refers to the - credentials (for example, the password provided has expired) and must be - corrected before they can be used with a collection. + :param StatusDetails status: (optional) Object that contains details about + the status of the authentication process. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Credentials` object @@ -3536,6 +3532,8 @@ def update_credentials(self, raise ValueError('credential_id must be provided') if credential_details is not None: credential_details = convert_model(credential_details) + if status is not None: + status = convert_model(status) headers = {} sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, service_version='V1', @@ -5077,11 +5075,8 @@ class Credentials(): :attr CredentialDetails credential_details: (optional) Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. - :attr str status: (optional) The current status of this set of credentials. - `connected` indicates that the credentials are available to use with the source - configuration of a collection. `invalid` refers to the credentials (for example, - the password provided has expired) and must be corrected before they can be used - with a collection. + :attr StatusDetails status: (optional) Object that contains details about the + status of the authentication process. """ def __init__(self, @@ -5089,7 +5084,7 @@ def __init__(self, credential_id: str = None, source_type: str = None, credential_details: 'CredentialDetails' = None, - status: str = None) -> None: + status: 'StatusDetails' = None) -> None: """ Initialize a Credentials object. @@ -5107,11 +5102,8 @@ def __init__(self, :param CredentialDetails credential_details: (optional) Object containing details of the stored credentials. Obtain credentials for your source from the administrator of the source. - :param str status: (optional) The current status of this set of - credentials. `connected` indicates that the credentials are available to - use with the source configuration of a collection. `invalid` refers to the - credentials (for example, the password provided has expired) and must be - corrected before they can be used with a collection. + :param StatusDetails status: (optional) Object that contains details about + the status of the authentication process. """ self.credential_id = credential_id self.source_type = source_type @@ -5130,7 +5122,7 @@ def from_dict(cls, _dict: Dict) -> 'Credentials': args['credential_details'] = CredentialDetails.from_dict( _dict.get('credential_details')) if 'status' in _dict: - args['status'] = _dict.get('status') + args['status'] = StatusDetails.from_dict(_dict.get('status')) return cls(**args) @classmethod @@ -5151,7 +5143,7 @@ def to_dict(self) -> Dict: 'credential_details') and self.credential_details is not None: _dict['credential_details'] = self.credential_details.to_dict() if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status + _dict['status'] = self.status.to_dict() return _dict def _to_dict(self): @@ -5190,16 +5182,6 @@ class SourceTypeEnum(str, Enum): WEB_CRAWL = 'web_crawl' CLOUD_OBJECT_STORAGE = 'cloud_object_storage' - class StatusEnum(str, Enum): - """ - The current status of this set of credentials. `connected` indicates that the - credentials are available to use with the source configuration of a collection. - `invalid` refers to the credentials (for example, the password provided has - expired) and must be corrected before they can be used with a collection. - """ - CONNECTED = 'connected' - INVALID = 'invalid' - class CredentialsList(): """ @@ -11981,6 +11963,74 @@ class StatusEnum(str, Enum): UNKNOWN = 'unknown' +class StatusDetails(): + """ + Object that contains details about the status of the authentication process. + + :attr bool authentication: (optional) Indicates whether the credential is + accepted by the target data source. + :attr str error_message: (optional) If `authentication` is `false`, a message + describes why the authentication was unsuccessful. + """ + + def __init__(self, + *, + authentication: bool = None, + error_message: str = None) -> None: + """ + Initialize a StatusDetails object. + + :param bool authentication: (optional) Indicates whether the credential is + accepted by the target data source. + :param str error_message: (optional) If `authentication` is `false`, a + message describes why the authentication was unsuccessful. + """ + self.authentication = authentication + self.error_message = error_message + + @classmethod + def from_dict(cls, _dict: Dict) -> 'StatusDetails': + """Initialize a StatusDetails object from a json dictionary.""" + args = {} + if 'authentication' in _dict: + args['authentication'] = _dict.get('authentication') + if 'error_message' in _dict: + args['error_message'] = _dict.get('error_message') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a StatusDetails 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, 'authentication') and self.authentication is not None: + _dict['authentication'] = self.authentication + if hasattr(self, 'error_message') and self.error_message is not None: + _dict['error_message'] = self.error_message + 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 StatusDetails object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'StatusDetails') -> 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: 'StatusDetails') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class TokenDictRule(): """ An object defining a single tokenizaion rule. diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 19746cfae..5080612c5 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -5982,7 +5982,7 @@ def test_list_credentials_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') - mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}]}' + mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}]}' responses.add(responses.GET, url, body=mock_response, @@ -6010,7 +6010,7 @@ def test_list_credentials_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') - mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}]}' + mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}]}' responses.add(responses.GET, url, body=mock_response, @@ -6054,7 +6054,7 @@ def test_create_credentials_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' responses.add(responses.POST, url, body=mock_response, @@ -6083,11 +6083,16 @@ def test_create_credentials_all_params(self): credential_details_model['access_key_id'] = 'testString' credential_details_model['secret_access_key'] = 'testString' + # Construct a dict representation of a StatusDetails model + status_details_model = {} + status_details_model['authentication'] = True + status_details_model['error_message'] = 'testString' + # Set up parameter values environment_id = 'testString' source_type = 'box' credential_details = credential_details_model - status = 'connected' + status = status_details_model # Invoke method response = _service.create_credentials( @@ -6105,7 +6110,7 @@ def test_create_credentials_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['source_type'] == 'box' assert req_body['credential_details'] == credential_details_model - assert req_body['status'] == 'connected' + assert req_body['status'] == status_details_model @responses.activate @@ -6115,7 +6120,7 @@ def test_create_credentials_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' responses.add(responses.POST, url, body=mock_response, @@ -6144,11 +6149,16 @@ def test_create_credentials_value_error(self): credential_details_model['access_key_id'] = 'testString' credential_details_model['secret_access_key'] = 'testString' + # Construct a dict representation of a StatusDetails model + status_details_model = {} + status_details_model['authentication'] = True + status_details_model['error_message'] = 'testString' + # Set up parameter values environment_id = 'testString' source_type = 'box' credential_details = credential_details_model - status = 'connected' + status = status_details_model # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -6184,7 +6194,7 @@ def test_get_credentials_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' responses.add(responses.GET, url, body=mock_response, @@ -6214,7 +6224,7 @@ def test_get_credentials_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' responses.add(responses.GET, url, body=mock_response, @@ -6260,7 +6270,7 @@ def test_update_credentials_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' responses.add(responses.PUT, url, body=mock_response, @@ -6289,12 +6299,17 @@ def test_update_credentials_all_params(self): credential_details_model['access_key_id'] = 'testString' credential_details_model['secret_access_key'] = 'testString' + # Construct a dict representation of a StatusDetails model + status_details_model = {} + status_details_model['authentication'] = True + status_details_model['error_message'] = 'testString' + # Set up parameter values environment_id = 'testString' credential_id = 'testString' source_type = 'box' credential_details = credential_details_model - status = 'connected' + status = status_details_model # Invoke method response = _service.update_credentials( @@ -6313,7 +6328,7 @@ def test_update_credentials_all_params(self): req_body = json.loads(str(responses.calls[0].request.body, 'utf-8')) assert req_body['source_type'] == 'box' assert req_body['credential_details'] == credential_details_model - assert req_body['status'] == 'connected' + assert req_body['status'] == status_details_model @responses.activate @@ -6323,7 +6338,7 @@ def test_update_credentials_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": "connected"}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' responses.add(responses.PUT, url, body=mock_response, @@ -6352,12 +6367,17 @@ def test_update_credentials_value_error(self): credential_details_model['access_key_id'] = 'testString' credential_details_model['secret_access_key'] = 'testString' + # Construct a dict representation of a StatusDetails model + status_details_model = {} + status_details_model['authentication'] = True + status_details_model['error_message'] = 'testString' + # Set up parameter values environment_id = 'testString' credential_id = 'testString' source_type = 'box' credential_details = credential_details_model - status = 'connected' + status = status_details_model # Pass in all but one required param and check for a ValueError req_param_dict = { @@ -7429,12 +7449,16 @@ def test_credentials_serialization(self): credential_details_model['access_key_id'] = 'testString' credential_details_model['secret_access_key'] = 'testString' + status_details_model = {} # StatusDetails + status_details_model['authentication'] = True + status_details_model['error_message'] = 'testString' + # Construct a json representation of a Credentials model credentials_model_json = {} credentials_model_json['credential_id'] = 'testString' credentials_model_json['source_type'] = 'box' credentials_model_json['credential_details'] = credential_details_model - credentials_model_json['status'] = 'connected' + credentials_model_json['status'] = status_details_model # Construct a model instance of Credentials by calling from_dict on the json representation credentials_model = Credentials.from_dict(credentials_model_json) @@ -7484,11 +7508,15 @@ def test_credentials_list_serialization(self): credential_details_model['access_key_id'] = 'testString' credential_details_model['secret_access_key'] = 'testString' + status_details_model = {} # StatusDetails + status_details_model['authentication'] = True + status_details_model['error_message'] = 'testString' + credentials_model = {} # Credentials credentials_model['credential_id'] = '00000d8c-0000-00e8-ba89-0ed5f89f718b' credentials_model['source_type'] = 'salesforce' credentials_model['credential_details'] = credential_details_model - credentials_model['status'] = 'connected' + credentials_model['status'] = status_details_model # Construct a json representation of a CredentialsList model credentials_list_model_json = {} @@ -10513,6 +10541,36 @@ def test_source_status_serialization(self): source_status_model_json2 = source_status_model.to_dict() assert source_status_model_json2 == source_status_model_json +class TestModel_StatusDetails(): + """ + Test Class for StatusDetails + """ + + def test_status_details_serialization(self): + """ + Test serialization/deserialization for StatusDetails + """ + + # Construct a json representation of a StatusDetails model + status_details_model_json = {} + status_details_model_json['authentication'] = True + status_details_model_json['error_message'] = 'testString' + + # Construct a model instance of StatusDetails by calling from_dict on the json representation + status_details_model = StatusDetails.from_dict(status_details_model_json) + assert status_details_model != False + + # Construct a model instance of StatusDetails by calling from_dict on the json representation + status_details_model_dict = StatusDetails.from_dict(status_details_model_json).__dict__ + status_details_model2 = StatusDetails(**status_details_model_dict) + + # Verify the model instances are equivalent + assert status_details_model == status_details_model2 + + # Convert model instance back to dict and verify no loss of data + status_details_model_json2 = status_details_model.to_dict() + assert status_details_model_json2 == status_details_model_json + class TestModel_TokenDictRule(): """ Test Class for TokenDictRule From 611b7c91644fb2238712cfed964ea7376b0d076a Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Tue, 14 Sep 2021 10:20:46 -0400 Subject: [PATCH 360/455] feat(assistant_v2,disco_v1): add answers property to response model, fix typo --- ibm_watson/assistant_v2.py | 95 +++++++++++++++++++++++++++++++++- ibm_watson/discovery_v1.py | 20 +++---- test/unit/test_assistant_v2.py | 40 ++++++++++++++ test/unit/test_discovery_v1.py | 30 +++++------ 4 files changed, 159 insertions(+), 26 deletions(-) diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index ab82f6383..12b60fd41 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -4843,6 +4843,12 @@ class SearchResult(): :attr SearchResultHighlight highlight: (optional) An object containing segments of text from search results with query-matching text highlighted using HTML `` tags. + :attr List[SearchResultAnswer] answers: (optional) An array specifying segments + of text within the result that were identified as direct answers to the search + query. Currently, only the single answer with the highest confidence (if any) is + returned. + **Note:** This property uses the answer finding beta feature, and is available + only if the search skill is connected to a Discovery v2 service instance. """ def __init__(self, @@ -4852,7 +4858,8 @@ def __init__(self, body: str = None, title: str = None, url: str = None, - highlight: 'SearchResultHighlight' = None) -> None: + highlight: 'SearchResultHighlight' = None, + answers: List['SearchResultAnswer'] = None) -> None: """ Initialize a SearchResult object. @@ -4873,6 +4880,13 @@ def __init__(self, :param SearchResultHighlight highlight: (optional) An object containing segments of text from search results with query-matching text highlighted using HTML `` tags. + :param List[SearchResultAnswer] answers: (optional) An array specifying + segments of text within the result that were identified as direct answers + to the search query. Currently, only the single answer with the highest + confidence (if any) is returned. + **Note:** This property uses the answer finding beta feature, and is + available only if the search skill is connected to a Discovery v2 service + instance. """ self.id = id self.result_metadata = result_metadata @@ -4880,6 +4894,7 @@ def __init__(self, self.title = title self.url = url self.highlight = highlight + self.answers = answers @classmethod def from_dict(cls, _dict: Dict) -> 'SearchResult': @@ -4906,6 +4921,10 @@ def from_dict(cls, _dict: Dict) -> 'SearchResult': if 'highlight' in _dict: args['highlight'] = SearchResultHighlight.from_dict( _dict.get('highlight')) + if 'answers' in _dict: + args['answers'] = [ + SearchResultAnswer.from_dict(x) for x in _dict.get('answers') + ] return cls(**args) @classmethod @@ -4929,6 +4948,8 @@ def to_dict(self) -> Dict: _dict['url'] = self.url if hasattr(self, 'highlight') and self.highlight is not None: _dict['highlight'] = self.highlight.to_dict() + if hasattr(self, 'answers') and self.answers is not None: + _dict['answers'] = [x.to_dict() for x in self.answers] return _dict def _to_dict(self): @@ -4950,6 +4971,78 @@ def __ne__(self, other: 'SearchResult') -> bool: return not self == other +class SearchResultAnswer(): + """ + An object specifing a segment of text that was identified as a direct answer to the + search query. + + :attr str text: The text of the answer. + :attr float confidence: The confidence score for the answer, as returned by the + Discovery service. + """ + + def __init__(self, text: str, confidence: float) -> None: + """ + Initialize a SearchResultAnswer object. + + :param str text: The text of the answer. + :param float confidence: The confidence score for the answer, as returned + by the Discovery service. + """ + self.text = text + self.confidence = confidence + + @classmethod + def from_dict(cls, _dict: Dict) -> 'SearchResultAnswer': + """Initialize a SearchResultAnswer object from a json dictionary.""" + args = {} + if 'text' in _dict: + args['text'] = _dict.get('text') + else: + raise ValueError( + 'Required property \'text\' not present in SearchResultAnswer JSON' + ) + if 'confidence' in _dict: + args['confidence'] = _dict.get('confidence') + else: + raise ValueError( + 'Required property \'confidence\' not present in SearchResultAnswer JSON' + ) + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a SearchResultAnswer 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, 'text') and self.text is not None: + _dict['text'] = self.text + 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 SearchResultAnswer object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'SearchResultAnswer') -> 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: 'SearchResultAnswer') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class SearchResultHighlight(): """ An object containing segments of text from search results with query-matching text diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index a00c1b9e9..d826fd940 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -11967,33 +11967,33 @@ class StatusDetails(): """ Object that contains details about the status of the authentication process. - :attr bool authentication: (optional) Indicates whether the credential is + :attr bool authenticated: (optional) Indicates whether the credential is accepted by the target data source. - :attr str error_message: (optional) If `authentication` is `false`, a message + :attr str error_message: (optional) If `authenticated` is `false`, a message describes why the authentication was unsuccessful. """ def __init__(self, *, - authentication: bool = None, + authenticated: bool = None, error_message: str = None) -> None: """ Initialize a StatusDetails object. - :param bool authentication: (optional) Indicates whether the credential is + :param bool authenticated: (optional) Indicates whether the credential is accepted by the target data source. - :param str error_message: (optional) If `authentication` is `false`, a + :param str error_message: (optional) If `authenticated` is `false`, a message describes why the authentication was unsuccessful. """ - self.authentication = authentication + self.authenticated = authenticated self.error_message = error_message @classmethod def from_dict(cls, _dict: Dict) -> 'StatusDetails': """Initialize a StatusDetails object from a json dictionary.""" args = {} - if 'authentication' in _dict: - args['authentication'] = _dict.get('authentication') + if 'authenticated' in _dict: + args['authenticated'] = _dict.get('authenticated') if 'error_message' in _dict: args['error_message'] = _dict.get('error_message') return cls(**args) @@ -12006,8 +12006,8 @@ def _from_dict(cls, _dict): def to_dict(self) -> Dict: """Return a json dictionary representing this model.""" _dict = {} - if hasattr(self, 'authentication') and self.authentication is not None: - _dict['authentication'] = self.authentication + if hasattr(self, 'authenticated') and self.authenticated is not None: + _dict['authenticated'] = self.authenticated if hasattr(self, 'error_message') and self.error_message is not None: _dict['error_message'] = self.error_message return _dict diff --git a/test/unit/test_assistant_v2.py b/test/unit/test_assistant_v2.py index 886337542..1ba9a3ee1 100644 --- a/test/unit/test_assistant_v2.py +++ b/test/unit/test_assistant_v2.py @@ -4009,6 +4009,10 @@ def test_search_result_serialization(self): search_result_highlight_model['url'] = ['testString'] search_result_highlight_model['foo'] = ['testString'] + search_result_answer_model = {} # SearchResultAnswer + search_result_answer_model['text'] = 'testString' + search_result_answer_model['confidence'] = 0 + # Construct a json representation of a SearchResult model search_result_model_json = {} search_result_model_json['id'] = 'testString' @@ -4017,6 +4021,7 @@ def test_search_result_serialization(self): search_result_model_json['title'] = 'testString' search_result_model_json['url'] = 'testString' search_result_model_json['highlight'] = search_result_highlight_model + search_result_model_json['answers'] = [search_result_answer_model] # Construct a model instance of SearchResult by calling from_dict on the json representation search_result_model = SearchResult.from_dict(search_result_model_json) @@ -4033,6 +4038,36 @@ def test_search_result_serialization(self): search_result_model_json2 = search_result_model.to_dict() assert search_result_model_json2 == search_result_model_json +class TestModel_SearchResultAnswer(): + """ + Test Class for SearchResultAnswer + """ + + def test_search_result_answer_serialization(self): + """ + Test serialization/deserialization for SearchResultAnswer + """ + + # Construct a json representation of a SearchResultAnswer model + search_result_answer_model_json = {} + search_result_answer_model_json['text'] = 'testString' + search_result_answer_model_json['confidence'] = 0 + + # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation + search_result_answer_model = SearchResultAnswer.from_dict(search_result_answer_model_json) + assert search_result_answer_model != False + + # Construct a model instance of SearchResultAnswer by calling from_dict on the json representation + search_result_answer_model_dict = SearchResultAnswer.from_dict(search_result_answer_model_json).__dict__ + search_result_answer_model2 = SearchResultAnswer(**search_result_answer_model_dict) + + # Verify the model instances are equivalent + assert search_result_answer_model == search_result_answer_model2 + + # Convert model instance back to dict and verify no loss of data + search_result_answer_model_json2 = search_result_answer_model.to_dict() + assert search_result_answer_model_json2 == search_result_answer_model_json + class TestModel_SearchResultHighlight(): """ Test Class for SearchResultHighlight @@ -4567,6 +4602,10 @@ def test_runtime_response_generic_runtime_response_type_search_serialization(sel search_result_highlight_model['url'] = ['testString'] search_result_highlight_model['foo'] = ['testString'] + search_result_answer_model = {} # SearchResultAnswer + search_result_answer_model['text'] = 'testString' + search_result_answer_model['confidence'] = 0 + search_result_model = {} # SearchResult search_result_model['id'] = 'testString' search_result_model['result_metadata'] = search_result_metadata_model @@ -4574,6 +4613,7 @@ def test_runtime_response_generic_runtime_response_type_search_serialization(sel search_result_model['title'] = 'testString' search_result_model['url'] = 'testString' search_result_model['highlight'] = search_result_highlight_model + search_result_model['answers'] = [search_result_answer_model] response_generic_channel_model = {} # ResponseGenericChannel response_generic_channel_model['channel'] = 'testString' diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 5080612c5..96f2d9cb5 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -5982,7 +5982,7 @@ def test_list_credentials_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') - mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}]}' + mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' responses.add(responses.GET, url, body=mock_response, @@ -6010,7 +6010,7 @@ def test_list_credentials_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') - mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}]}' + mock_response = '{"credentials": [{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}]}' responses.add(responses.GET, url, body=mock_response, @@ -6054,7 +6054,7 @@ def test_create_credentials_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.POST, url, body=mock_response, @@ -6085,7 +6085,7 @@ def test_create_credentials_all_params(self): # Construct a dict representation of a StatusDetails model status_details_model = {} - status_details_model['authentication'] = True + status_details_model['authenticated'] = True status_details_model['error_message'] = 'testString' # Set up parameter values @@ -6120,7 +6120,7 @@ def test_create_credentials_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.POST, url, body=mock_response, @@ -6151,7 +6151,7 @@ def test_create_credentials_value_error(self): # Construct a dict representation of a StatusDetails model status_details_model = {} - status_details_model['authentication'] = True + status_details_model['authenticated'] = True status_details_model['error_message'] = 'testString' # Set up parameter values @@ -6194,7 +6194,7 @@ def test_get_credentials_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.GET, url, body=mock_response, @@ -6224,7 +6224,7 @@ def test_get_credentials_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.GET, url, body=mock_response, @@ -6270,7 +6270,7 @@ def test_update_credentials_all_params(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.PUT, url, body=mock_response, @@ -6301,7 +6301,7 @@ def test_update_credentials_all_params(self): # Construct a dict representation of a StatusDetails model status_details_model = {} - status_details_model['authentication'] = True + status_details_model['authenticated'] = True status_details_model['error_message'] = 'testString' # Set up parameter values @@ -6338,7 +6338,7 @@ def test_update_credentials_value_error(self): """ # Set up mock url = self.preprocess_url(_base_url + '/v1/environments/testString/credentials/testString') - mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authentication": true, "error_message": "error_message"}}' + mock_response = '{"credential_id": "credential_id", "source_type": "box", "credential_details": {"credential_type": "oauth2", "client_id": "client_id", "enterprise_id": "enterprise_id", "url": "url", "username": "username", "organization_url": "organization_url", "site_collection.path": "site_collection_path", "client_secret": "client_secret", "public_key_id": "public_key_id", "private_key": "private_key", "passphrase": "passphrase", "password": "password", "gateway_id": "gateway_id", "source_version": "online", "web_application_url": "web_application_url", "domain": "domain", "endpoint": "endpoint", "access_key_id": "access_key_id", "secret_access_key": "secret_access_key"}, "status": {"authenticated": false, "error_message": "error_message"}}' responses.add(responses.PUT, url, body=mock_response, @@ -6369,7 +6369,7 @@ def test_update_credentials_value_error(self): # Construct a dict representation of a StatusDetails model status_details_model = {} - status_details_model['authentication'] = True + status_details_model['authenticated'] = True status_details_model['error_message'] = 'testString' # Set up parameter values @@ -7450,7 +7450,7 @@ def test_credentials_serialization(self): credential_details_model['secret_access_key'] = 'testString' status_details_model = {} # StatusDetails - status_details_model['authentication'] = True + status_details_model['authenticated'] = True status_details_model['error_message'] = 'testString' # Construct a json representation of a Credentials model @@ -7509,7 +7509,7 @@ def test_credentials_list_serialization(self): credential_details_model['secret_access_key'] = 'testString' status_details_model = {} # StatusDetails - status_details_model['authentication'] = True + status_details_model['authenticated'] = True status_details_model['error_message'] = 'testString' credentials_model = {} # Credentials @@ -10553,7 +10553,7 @@ def test_status_details_serialization(self): # Construct a json representation of a StatusDetails model status_details_model_json = {} - status_details_model_json['authentication'] = True + status_details_model_json['authenticated'] = True status_details_model_json['error_message'] = 'testString' # Construct a model instance of StatusDetails by calling from_dict on the json representation From 59029f44ef86dba9a3681f7ae71e24ceaae67584 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Tue, 14 Sep 2021 17:01:00 +0000 Subject: [PATCH 361/455] =?UTF-8?q?Bump=20version:=205.2.3=20=E2=86=92=205?= =?UTF-8?q?.3.0=20[skip=20ci]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 08f707c39..3b4781f21 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 5.2.3 +current_version = 5.3.0 commit = True message = Bump version: {current_version} → {new_version} [skip ci] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index f9bc7375f..1d4672ff0 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '5.2.3' +__version__ = '5.3.0' diff --git a/setup.py b/setup.py index 2c060053c..09a62b2a8 100644 --- a/setup.py +++ b/setup.py @@ -16,7 +16,7 @@ from setuptools import setup from os import path -__version__ = '5.2.3' +__version__ = '5.3.0' # read contents of README file this_directory = path.abspath(path.dirname(__file__)) From 0dc3dc6eda01a46d9974b3a168320824106ec958 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Wed, 15 Sep 2021 11:14:46 -0400 Subject: [PATCH 362/455] chore: update CHANGELOG --- CHANGELOG.md | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 248fa0ceb..cbb2fead0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,31 @@ +# [5.3.0](https://github.com/watson-developer-cloud/python-sdk/compare/v5.2.3...v5.3.0) (2021-09-14) + + +### Bug Fixes + +* **disco_v1:** update type of status to reflect service changes ([ab880f0](https://github.com/watson-developer-cloud/python-sdk/commit/ab880f04ae2ec5983e74175cd7b1dc83bd24f022)) +* **disco_v2:** project types enum updated/fixed ([a598231](https://github.com/watson-developer-cloud/python-sdk/commit/a598231df416e8cbf4453342b42ce5a5d8c6be85)) +* **nlu:** fix listClassificationsModels response model ([9954e59](https://github.com/watson-developer-cloud/python-sdk/commit/9954e59df889b45b761ef206ad8dedd9502e762a)) +* **wss:** fix on_transcription parsing issue including tests ([1b05e1b](https://github.com/watson-developer-cloud/python-sdk/commit/1b05e1b3169b8c904fd17c3834d4e61779fa511c)) + + +### Features + +* **assistant_v1:** add alt_text and sensitivity options, location now optional ([0a6c540](https://github.com/watson-developer-cloud/python-sdk/commit/0a6c540f4a5d6abf25e35f9b8b20d6d191744a43)) +* **assistant_v2:** same as v1, add more properties ([c2ca53b](https://github.com/watson-developer-cloud/python-sdk/commit/c2ca53bf1bdc55790787d926ffa23f1cc12b3cee)) +* **assistant_v2,disco_v1:** add answers property to response model, fix typo ([611b7c9](https://github.com/watson-developer-cloud/python-sdk/commit/611b7c91644fb2238712cfed964ea7376b0d076a)) +* **stt&tts:** new models added ([67ee967](https://github.com/watson-developer-cloud/python-sdk/commit/67ee967726c022b9e883bef786cb82a59b86be28)) + + +## [5.2.3](https://github.com/watson-developer-cloud/python-sdk/compare/v5.2.2...v5.2.3) (2021-08-26) + + +### Bug Fixes + +* **nlc:** add deprecation warning ([d1ec209](https://github.com/watson-developer-cloud/python-sdk/commit/d1ec209484320c2a61c735721148a66f58e6f7b1)), closes [#9624](https://github.com/watson-developer-cloud/python-sdk/issues/9624) +* **nlc:** move deprecation warning ([09a6dd4](https://github.com/watson-developer-cloud/python-sdk/commit/09a6dd4d7b26664cb92d8652f8d54ca96d9404a9)) +* **nlc:** move deprecation warning ([3658ee8](https://github.com/watson-developer-cloud/python-sdk/commit/3658ee856c3ddba77a64589631b4605ae3c8c86c)) + ## [5.2.2](https://github.com/watson-developer-cloud/python-sdk/compare/v5.2.1...v5.2.2) (2021-07-06) From f3f537d13b93974dbefadbd9c68211fd1f69ee20 Mon Sep 17 00:00:00 2001 From: Michael G Mosca Date: Wed, 17 Nov 2021 12:53:10 -0500 Subject: [PATCH 363/455] ci: Gha 9895 (#809) * ci: fix * ci: fix * ci : fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix * ci: fix --- .github/workflows/integration-test.yml | 106 ++++++++++++++++ test/integration/test_assistant_v1.py | 117 ++++++++++++++++++ test/integration/test_compare_comply_v1.py | 4 +- test/integration/test_discovery_v1.py | 6 +- test/integration/test_discovery_v2.py | 11 +- .../test_language_translator_v3.py | 4 +- .../test_natural_language_classifier_v1.py | 4 +- .../test_natural_language_understanding_v1.py | 26 ++++ .../test_personality_insights_v3.py | 29 +++++ test/integration/test_speech_to_text_v1.py | 4 +- test/integration/test_text_to_speech_v1.py | 4 +- test/integration/test_tone_analyzer_v3.py | 60 +++++++++ .../integration/test_visual_recognition_v3.py | 4 +- .../integration/test_visual_recognition_v4.py | 4 +- 14 files changed, 361 insertions(+), 22 deletions(-) create mode 100644 .github/workflows/integration-test.yml create mode 100644 test/integration/test_assistant_v1.py create mode 100644 test/integration/test_natural_language_understanding_v1.py create mode 100644 test/integration/test_personality_insights_v3.py create mode 100644 test/integration/test_tone_analyzer_v3.py diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml new file mode 100644 index 000000000..221b42925 --- /dev/null +++ b/.github/workflows/integration-test.yml @@ -0,0 +1,106 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support documentation. +# This workflow will download a prebuilt Python version, install dependencies and run integration tests + +name: Run Integration Tests + +on: + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +jobs: + integration_test: + name: Build and Run Integration Tests on Python ${{ matrix.python-version }} and ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + matrix: + python-version: ['3.8'] + os: [ubuntu-latest] + + steps: + - uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + + - name: Install Python dependencies (ubuntu) + run: | + pip3 install -r requirements.txt + pip3 install -r requirements-dev.txt + pip3 install --editable . + + - name: Execute Python integration tests + # continue-on-error: true + env: + NATURAL_LANGUAGE_CLASSIFIER_URL: "https://api.us-south.natural-language-classifier.watson.cloud.ibm.com" + NATURAL_LANGUAGE_CLASSIFIER_APIKEY: ${{ secrets.NLC_APIKEY }} + LANGUAGE_TRANSLATOR_APIKEY: ${{ secrets.LT_APIKEY }} + LANGUAGE_TRANSLATOR_URL: "https://api.us-south.language-translator.watson.cloud.ibm.com" + NATURAL_LANGUAGE_UNDERSTANDING_APIKEY: ${{ secrets.NLU_APIKEY }} + NATURAL_LANGUAGE_UNDERSTANDING_URL: "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com" + PERSONALITY_INSIGHTS_APIKEY: ${{ secrets.PI_APIKEY }} + PERSONALITY_INSIGHTS_URL: "https://api.us-south.personality-insights.watson.cloud.ibm.com" + TONE_ANALYZER_APIKEY: ${{ secrets.TA_APIKEY }} + TONE_ANALYZER_URL: "https://api.us-south.tone-analyzer.watson.cloud.ibm.com" + SPEECH_TO_TEXT_APIKEY: ${{ secrets.STT_APIKEY }} + SPEECH_TO_TEXT_URL: "https://api.us-south.speech-to-text.watson.cloud.ibm.com" + TEXT_TO_SPEECH_APIKEY: ${{ secrets.TTS_APIKEY }} + TEXT_TO_SPEECH_URL: "https://api.us-south.text-to-speech.watson.cloud.ibm.com" + VISUAL_RECOGNITION_APIKEY: ${{ secrets.VR_APIKEY }} + VISUAL_RECOGNITION_COLLECTION_ID: ${{ secrets.VR_COLLECTION_ID }} + VISUAL_RECOGNITION_URL: "https://api.us-south.visual-recognition.watson.cloud.ibm.com" + COMPARE_COMPLY_APIKEY: ${{ secrets.CC_APIKEY }} + COMPARE_COMPLY_FEEDBACK_ID: ${{ secrets.CC_FEEDBACK_ID }} + COMPARE_COMPLY_URL: "https://api.us-south.compare-comply.watson.cloud.ibm.com" + ASSISTANT_APIKEY: ${{ secrets.WA_APIKEY }} + ASSISTANT_WORKSPACE_ID: ${{ secrets.WA_WORKSPACE_ID }} + ASSISTANT_ASSISTANT_ID: ${{ secrets.WA_ASSISTANT_ID }} + ASSISTANT_URL: "https://api.us-south.assistant.watson.cloud.ibm.com" + DISCOVERY_APIKEY: ${{ secrets.D1_APIKEY }} + DISCOVERY_ENVIRONMENT_ID: ${{ secrets.D1_ENVIRONMENT_ID }} + DISCOVERY_COLLECTION_ID: ${{ secrets.D1_COLLECTION_ID }} + DISCOVERY_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" + DISCOVERY_V2_APIKEY: ${{ secrets.D2_APIKEY }} + DISCOVERY_V2_PROJECT_ID: ${{ secrets.D2_PROJECT_ID }} + DISCOVERY_V2_COLLECTION_ID: ${{ secrets.D2_COLLECTION_ID }} + DISCOVERY_V2_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" + run: | + pip3 install -U python-dotenv + pytest test/integration/test_assistant_v1.py -rap + pytest test/integration/test_compare_comply_v1.py -rap + pytest test/integration/test_discovery_v1.py -rap + pytest test/integration/test_discovery_v2.py -rap + pytest test/integration/test_language_translator_v3.py -rap + pytest test/integration/test_natural_language_classifier_v1.py -rap + pytest test/integration/test_natural_language_understanding_v1.py -rap + pytest test/integration/test_personality_insights_v3.py -rap + pytest test/integration/test_speech_to_text_v1.py -rap + pytest test/integration/test_text_to_speech_v1.py -rap + pytest test/integration/test_tone_analyzer_v3.py -rap + pytest test/integration/test_visual_recognition_v3.py -rap + pytest test/integration/test_visual_recognition_v4.py -rap + + # Do not notify on success. We will leave the code here just in case we decide to switch gears + - name: Notify slack on success + if: false # success() + env: + SLACK_BOT_TOKEN: ${{ secrets.SLACK_NOTIFICATIONS_BOT_TOKEN }} + uses: voxmedia/github-action-slack-notify-build@v1 + with: + channel: watson-e2e-tests + status: SUCCESS + color: good + + - name: Notify slack on failure + if: false # failure() + env: + SLACK_BOT_TOKEN: ${{ secrets.SLACK_NOTIFICATIONS_BOT_TOKEN }} + uses: voxmedia/github-action-slack-notify-build@v1 + with: + channel: watson-e2e-tests + status: FAILED + color: danger diff --git a/test/integration/test_assistant_v1.py b/test/integration/test_assistant_v1.py new file mode 100644 index 000000000..306e5d489 --- /dev/null +++ b/test/integration/test_assistant_v1.py @@ -0,0 +1,117 @@ +# coding: utf-8 +from unittest import TestCase +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator, BearerTokenAuthenticator +from os.path import abspath +import os +import ibm_watson +import pytest +import json + +@pytest.mark.skipif(os.getenv('ASSISTANT_APIKEY') is None, + reason='requires ASSISTANT_APIKEY') +class TestAssistantV1(TestCase): + + @classmethod + def setup_class(cls): + + create_workspace_data = { + "name": + "test_workspace", + "description": + "integration tests", + "language": + "en", + "intents": [{ + "intent": "hello", + "description": "string", + "examples": [{ + "text": "good morning" + }] + }], + "entities": [{ + "entity": "pizza_toppings", + "description": "Tasty pizza toppings", + "metadata": { + "property": "value" + } + }], + "counterexamples": [{ + "text": "string" + }], + "metadata": {}, + } + + authenticator = IAMAuthenticator(os.getenv('ASSISTANT_APIKEY')) + cls.assistant = ibm_watson.AssistantV1( + version='2018-07-10', + authenticator=authenticator + ) + cls.assistant.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) + + response = cls.assistant.create_workspace( + name=create_workspace_data['name'], + description=create_workspace_data['description'], + language='en', + intents=create_workspace_data['intents'], + entities=create_workspace_data['entities'], + counterexamples=create_workspace_data['counterexamples'], + metadata=create_workspace_data['metadata']).get_result() + + cls.workspace_id = response['workspace_id'] + + examples = [{"text": "good morning"}] + response = cls.assistant.create_intent( + workspace_id=cls.workspace_id, + intent='test_intent', + description='Test intent.', + examples=examples).get_result() + + @classmethod + def teardown_class(cls): + response = cls.assistant.delete_intent(workspace_id=cls.workspace_id, intent='updated_test_intent').get_result() + assert response is not None + + response = cls.assistant.delete_workspace(cls.workspace_id).get_result() + assert response is not None + + def test_workspace(self): + response = self.assistant.get_workspace(self.workspace_id, export=True).get_result() + assert response is not None + + response = self.assistant.list_workspaces().get_result() + assert response is not None + print(json.dumps(response, indent=2)) + + response = self.assistant.message(self.workspace_id, + input={ + 'text': 'What\'s the weather like?' + }, + context={ + 'metadata': { + 'deployment': 'myDeployment' + } + }).get_result() + assert response is not None + + response = self.assistant.update_workspace(workspace_id=self.workspace_id, description='Updated test workspace.').get_result() + assert response is not None + + def test_intent(self): + response = self.assistant.get_intent( + workspace_id=self.workspace_id, intent='test_intent', export=True).get_result() + assert response is not None + + response = self.assistant.update_intent( + workspace_id=self.workspace_id, + intent='test_intent', + new_intent='updated_test_intent', + new_description='Updated test intent.').get_result() + assert response is not None + + response = self.assistant.list_intents( + workspace_id=self.workspace_id, export=True).get_result() + assert response is not None + print(json.dumps(response, indent=2)) diff --git a/test/integration/test_compare_comply_v1.py b/test/integration/test_compare_comply_v1.py index 28cca19fe..c0e6e5150 100644 --- a/test/integration/test_compare_comply_v1.py +++ b/test/integration/test_compare_comply_v1.py @@ -7,8 +7,8 @@ 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('COMPARE_COMPLY_APIKEY') is None, + reason='requires COMPARE_COMPLY_APIKEY') class IntegrationTestCompareComplyV1(TestCase): compare_comply = None diff --git a/test/integration/test_discovery_v1.py b/test/integration/test_discovery_v1.py index 32428e00c..6809fefe6 100644 --- a/test/integration/test_discovery_v1.py +++ b/test/integration/test_discovery_v1.py @@ -6,11 +6,11 @@ import pytest -@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, - reason='requires VCAP_SERVICES') +@pytest.mark.skipif(os.getenv('DISCOVERY_APIKEY') is None, + reason='requires DISCOVERY_APIKEY') class Discoveryv1(TestCase): discovery = None - environment_id = '62b0dd87-eefa-40bf-81d6-cf9bc82692ab' # This environment is created for integration testing + environment_id = os.getenv('DISCOVERY_ENVIRONMENT_ID') # This environment is created for integration testing collection_id = None collection_name = 'FOR-PYTHON-DELETE-ME' diff --git a/test/integration/test_discovery_v2.py b/test/integration/test_discovery_v2.py index a06391f39..aa1a402cc 100644 --- a/test/integration/test_discovery_v2.py +++ b/test/integration/test_discovery_v2.py @@ -8,22 +8,22 @@ import pytest -@pytest.mark.skipif(os.getenv('TEST_DISCO_V2') is None, - reason='only test in cpd and prem') +@pytest.mark.skipif(os.getenv('DISCOVERY_V2_APIKEY') is None, + reason='requires DISCOVERY_V2_APIKEY') class Discoveryv2(TestCase): discovery = None - project_id = 'f0b9920b-caa8-4b89-abf7-e250989eee5a' # This project is created for integration testing + project_id = os.getenv('DISCOVERY_V2_PROJECT_ID') # This project is created for integration testing collection_id = None collection_name = 'python_test_collection' @classmethod def setup_class(cls): - authenticator = IAMAuthenticator('apikey') + authenticator = IAMAuthenticator(os.getenv('DISCOVERY_V2_APIKEY')) cls.discovery = ibm_watson.DiscoveryV2( version='2020-08-12', authenticator=authenticator ) - cls.discovery.set_service_url('url') + cls.discovery.set_service_url(os.getenv('DISCOVERY_V2_URL')) cls.discovery.set_default_headers({ 'X-Watson-Learning-Opt-Out': '1', 'X-Watson-Test': '1' @@ -111,6 +111,7 @@ def test_enrichments(self): ) # can only test in CPD + @pytest.mark.skip(reason="can only test in CPD") def test_analyze(self): authenticator = BearerTokenAuthenticator('') discovery_cpd = ibm_watson.DiscoveryV2( diff --git a/test/integration/test_language_translator_v3.py b/test/integration/test_language_translator_v3.py index 439a5322f..1fcfd057d 100644 --- a/test/integration/test_language_translator_v3.py +++ b/test/integration/test_language_translator_v3.py @@ -6,8 +6,8 @@ import os -@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, - reason='requires VCAP_SERVICES') +@pytest.mark.skipif(os.getenv('LANGUAGE_TRANSLATOR_APIKEY') is None, + reason='requires LANGUAGE_TRANSLATOR_APIKEY') class TestIntegrationLanguageTranslatorV3(unittest.TestCase): @classmethod diff --git a/test/integration/test_natural_language_classifier_v1.py b/test/integration/test_natural_language_classifier_v1.py index e3f71ad34..76729011a 100644 --- a/test/integration/test_natural_language_classifier_v1.py +++ b/test/integration/test_natural_language_classifier_v1.py @@ -9,8 +9,8 @@ FIVE_SECONDS = 5 -@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, - reason='requires VCAP_SERVICES') +@pytest.mark.skipif(os.getenv('NATURAL_LANGUAGE_CLASSIFIER_APIKEY') is None, + reason='requires NATURAL_LANGUAGE_CLASSIFIER_APIKEY') class TestNaturalLanguageClassifierV1(TestCase): def setUp(self): diff --git a/test/integration/test_natural_language_understanding_v1.py b/test/integration/test_natural_language_understanding_v1.py new file mode 100644 index 000000000..faedb7593 --- /dev/null +++ b/test/integration/test_natural_language_understanding_v1.py @@ -0,0 +1,26 @@ +# coding: utf-8 +from unittest import TestCase +import os +import ibm_watson +import pytest +import json +import time +from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions + +@pytest.mark.skipif(os.getenv('NATURAL_LANGUAGE_UNDERSTANDING_APIKEY') is None, + reason='requires NATURAL_LANGUAGE_UNDERSTANDING_APIKEY') +class TestNaturalLanguageUnderstandingV1(TestCase): + + def setUp(self): + self.natural_language_understanding = ibm_watson.NaturalLanguageUnderstandingV1(version='2018-03-16') + self.natural_language_understanding.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) + + def test_analyze(self): + response = self.natural_language_understanding.analyze( + text='Bruce Banner is the Hulk and Bruce Wayne is BATMAN! ' + 'Superman fears not Banner, but Wayne.', + features=Features(entities=EntitiesOptions(), keywords=KeywordsOptions())).get_result() + assert response is not None diff --git a/test/integration/test_personality_insights_v3.py b/test/integration/test_personality_insights_v3.py new file mode 100644 index 000000000..fb04be696 --- /dev/null +++ b/test/integration/test_personality_insights_v3.py @@ -0,0 +1,29 @@ +# coding: utf-8 +from unittest import TestCase +import os +import ibm_watson +import pytest +import json +import time +from os.path import join + +@pytest.mark.skipif(os.getenv('PERSONALITY_INSIGHTS_APIKEY') is None, + reason='requires PERSONALITY_INSIGHTS_APIKEY') +class TestPersonalityInsightsV3(TestCase): + + def setUp(self): + self.personality_insights = ibm_watson.PersonalityInsightsV3(version='2017-10-13') + self.personality_insights.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) + + def test_profile1(self): + with open(join(os.getcwd(), 'resources/personality-v3.json')) as \ + profile_json: + profile = self.personality_insights.profile( + profile_json.read(), + 'application/json', + raw_scores=True, + consumption_preferences=True).get_result() + assert profile is not None diff --git a/test/integration/test_speech_to_text_v1.py b/test/integration/test_speech_to_text_v1.py index 0efc3130a..c0e0d1865 100644 --- a/test/integration/test_speech_to_text_v1.py +++ b/test/integration/test_speech_to_text_v1.py @@ -6,8 +6,8 @@ import threading -@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, - reason='requires VCAP_SERVICES') +@pytest.mark.skipif(os.getenv('SPEECH_TO_TEXT_APIKEY') is None, + reason='requires SPEECH_TO_TEXT_APIKEY') class TestSpeechToTextV1(TestCase): text_to_speech = None custom_models = None diff --git a/test/integration/test_text_to_speech_v1.py b/test/integration/test_text_to_speech_v1.py index 41fab2fe5..d0eee91a1 100644 --- a/test/integration/test_text_to_speech_v1.py +++ b/test/integration/test_text_to_speech_v1.py @@ -6,8 +6,8 @@ import os -@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, - reason='requires VCAP_SERVICES') +@pytest.mark.skipif(os.getenv('TEXT_TO_SPEECH_APIKEY') is None, + reason='requires TEXT_TO_SPEECH_APIKEY') class TestIntegrationTextToSpeechV1(unittest.TestCase): text_to_speech = None original_customizations = None diff --git a/test/integration/test_tone_analyzer_v3.py b/test/integration/test_tone_analyzer_v3.py new file mode 100644 index 000000000..d4b03103b --- /dev/null +++ b/test/integration/test_tone_analyzer_v3.py @@ -0,0 +1,60 @@ +# coding: utf-8 +from unittest import TestCase +import os +import ibm_watson +import pytest +import json +import time +from os.path import join +from ibm_watson.tone_analyzer_v3 import ToneInput + +@pytest.mark.skipif(os.getenv('TONE_ANALYZER_APIKEY') is None, + reason='requires PTONE_ANALYZER_APIKEY') +class TestToneAnalyzerV3(TestCase): + + def setUp(self): + self.tone_analyzer = ibm_watson.ToneAnalyzerV3(version='2017-09-21') + self.tone_analyzer.set_default_headers({ + 'X-Watson-Learning-Opt-Out': '1', + 'X-Watson-Test': '1' + }) + + def test_tone_chat(self): + utterances = [{ + 'text': 'I am very happy.', + 'user': 'glenn' + }, { + 'text': 'It is a good day.', + 'user': 'glenn' + }] + tone_chat = self.tone_analyzer.tone_chat(utterances).get_result() + assert tone_chat is not None + + def test_tone1(self): + tone = self.tone_analyzer.tone(tone_input='I am very happy. It is a good day.', content_type="text/plain").get_result() + assert tone is not None + + def test_tone2(self): + with open(join(os.getcwd(), 'resources/tone-example.json')) as tone_json: + tone = self.tone_analyzer.tone(json.load(tone_json)['text'], content_type="text/plain").get_result() + assert tone is not None + + def test_tone3(self): + with open(join(os.getcwd(), 'resources/tone-example.json')) as tone_json: + tone = self.tone_analyzer.tone(tone_input=json.load(tone_json)['text'], content_type='text/plain', sentences=True).get_result() + assert tone is not None + + def test_tone4(self): + with open(join(os.getcwd(), 'resources/tone-example.json')) as tone_json: + tone = self.tone_analyzer.tone(tone_input=json.load(tone_json), content_type='application/json').get_result() + assert tone is not None + + def test_tone5(self): + with open(join(os.getcwd(), 'resources/tone-example-html.json')) as tone_html: + tone = self.tone_analyzer.tone(json.load(tone_html)['text'],content_type='text/html').get_result() + assert tone is not None + + def test_tone6(self): + tone_input = ToneInput('I am very happy. It is a good day.') + tone = self.tone_analyzer.tone(tone_input=tone_input, content_type="application/json").get_result() + assert tone is not None \ No newline at end of file diff --git a/test/integration/test_visual_recognition_v3.py b/test/integration/test_visual_recognition_v3.py index 1dff4ee0c..a71054596 100644 --- a/test/integration/test_visual_recognition_v3.py +++ b/test/integration/test_visual_recognition_v3.py @@ -6,8 +6,8 @@ from unittest import TestCase -@pytest.mark.skipif(os.getenv('VCAP_SERVICES') is None, - reason='requires VCAP_SERVICES') +@pytest.mark.skipif(os.getenv('VISUAL_RECOGNITION_APIKEY') is None, + reason='requires VISUAL_RECOGNITION_APIKEY') class IntegrationTestVisualRecognitionV3(TestCase): visual_recognition = None classifier_id = None diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index 96d07f8c2..97d9e8e53 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -7,8 +7,8 @@ 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('VISUAL_RECOGNITION_APIKEY') is None, + reason='requires VISUAL_RECOGNITION_APIKEY') class IntegrationTestVisualRecognitionV3(TestCase): visual_recognition = None From b2366867060d9dcb31299927a74a8c1087bc7ad3 Mon Sep 17 00:00:00 2001 From: Michael G Mosca Date: Mon, 13 Dec 2021 12:29:52 -0500 Subject: [PATCH 364/455] ci: Gha 9926 (#811) * ci: fix * ci: fix * ci: fix --- .github/workflows/deploy.yml | 9 ++++++++- .github/workflows/integration-test.yml | 6 +++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 268186eb5..82326bdce 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -25,14 +25,17 @@ jobs: - uses: actions/checkout@v2 with: persist-credentials: false + - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.8' + - name: Setup Node uses: actions/setup-node@v1 with: - node-version: 12 + node-version: 14 + - name: Install Semantic Release dependencies run: | sudo apt-get install bumpversion @@ -43,6 +46,7 @@ jobs: npm install -g @semantic-release/github npm install -g @semantic-release/commit-analyzer npm install -g @semantic-release/release-notes-generator + - name: Publish js docs if: ${{ github.event.workflow_run.conclusion == 'success' }} env: @@ -52,16 +56,19 @@ jobs: run: | sudo apt-get install python3-sphinx docs/publish_gha.sh + - name: Publish to Git Releases and Tags if: ${{ github.event.workflow_run.conclusion == 'success' }} env: GITHUB_TOKEN: ${{ secrets.GH_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN }} run: npx semantic-release #--dry-run --branches 9388_gha Uncomment for testxing purposes + - name: Build binary wheel and a source tarball run: | pip3 install setuptools wheel twine build python -m build --sdist --outdir dist/ + - name: Publish distribution to Test PyPI continue-on-error: true uses: pypa/gh-action-pypi-publish@v1.4.2 # Try to update version tag every release diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index 221b42925..8b3245b06 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -71,7 +71,7 @@ jobs: run: | pip3 install -U python-dotenv pytest test/integration/test_assistant_v1.py -rap - pytest test/integration/test_compare_comply_v1.py -rap + echo -e "\n\033[0;35mSKIP: pytest test/integration/test_compare_comply_v1.py -rap" pytest test/integration/test_discovery_v1.py -rap pytest test/integration/test_discovery_v2.py -rap pytest test/integration/test_language_translator_v3.py -rap @@ -81,8 +81,8 @@ jobs: pytest test/integration/test_speech_to_text_v1.py -rap pytest test/integration/test_text_to_speech_v1.py -rap pytest test/integration/test_tone_analyzer_v3.py -rap - pytest test/integration/test_visual_recognition_v3.py -rap - pytest test/integration/test_visual_recognition_v4.py -rap + echo -e "\n\033[0;35mSKIP: pytest test/integration/test_visual_recognition_v3.py -rap" + echo -e "\n\033[0;35mSKIP: pytest test/integration/test_visual_recognition_v4.py -rap" # Do not notify on success. We will leave the code here just in case we decide to switch gears - name: Notify slack on success From e8a2f1883822f0ad2d655d31a595dbd93f5c81c9 Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Fri, 10 Dec 2021 09:03:47 -0800 Subject: [PATCH 365/455] docs(readme): add example for using cert and key files as well as new links --- README.md | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1a9f3d543..46241a296 100755 --- a/README.md +++ b/README.md @@ -260,7 +260,7 @@ For more information, follow the [MIGRATION-V4](https://github.com/watson-develo To move from v3.x to v4.0, refer to the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md). ## Configuring the http client (Supported from v1.1.0) -To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. For example for a Assistant service instance +To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://2.python-requests.org/en/master/api/#requests.request) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance ```python from ibm_watson import AssistantV1 @@ -268,9 +268,9 @@ from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your apikey') assistant = AssistantV1( - version='2018-07-10', + version='2021-11-27', authenticator=authenticator) -assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') +assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') assistant.set_http_config({'timeout': 100}) response = assistant.message(workspace_id=workspace_id, input={ @@ -278,6 +278,41 @@ response = assistant.message(workspace_id=workspace_id, input={ print(json.dumps(response, indent=2)) ``` +### Use behind a corporate proxy +To use the SDK with any proxies you may have they can be set as shown below. For documentation on proxies see [here](https://2.python-requests.org/en/latest/user/advanced/#proxies) + +See this example configuration: +```python +from ibm_watson import AssistantV1 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator + +authenticator = IAMAuthenticator('your apikey') +assistant = AssistantV1( + version='2021-11-27', + authenticator=authenticator) +assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') + +assistant.set_http_config({'proxies': { + 'http': 'http://10.10.1.10:3128', + 'https': 'http://10.10.1.10:1080', +}}) +``` + +### Sending custom certificates +To send custom certificates as a security measure in your request, use the cert property of the HTTPS Agent. +```python +from ibm_watson import AssistantV1 +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator + +authenticator = IAMAuthenticator('your apikey') +assistant = AssistantV1( + version='2021-11-27', + authenticator=authenticator) +assistant.set_service_url('https://api.us-south.assistant.watson.cloud.ibm.com') + +assistant.set_http_config({'cert': ('path_to_cert_file','path_to_key_file')}) +``` + ## Disable SSL certificate verification For ICP(IBM Cloud Private), you can disable the SSL certificate verification by: From 21399b769608a25f00fe4790b850ced77a8fc748 Mon Sep 17 00:00:00 2001 From: Johann Petrak Date: Wed, 26 Jan 2022 21:38:00 +0100 Subject: [PATCH 366/455] fix(ws): remove websocket debug code --- ibm_watson/websocket/recognize_listener.py | 2 -- ibm_watson/websocket/synthesize_listener.py | 2 -- 2 files changed, 4 deletions(-) diff --git a/ibm_watson/websocket/recognize_listener.py b/ibm_watson/websocket/recognize_listener.py index 9847e9192..c0d988c58 100644 --- a/ibm_watson/websocket/recognize_listener.py +++ b/ibm_watson/websocket/recognize_listener.py @@ -53,8 +53,6 @@ def __init__(self, self.isListening = False self.verify = verify - websocket.enableTrace(True) - self.ws_client = websocket.WebSocketApp( self.url, header=self.headers, diff --git a/ibm_watson/websocket/synthesize_listener.py b/ibm_watson/websocket/synthesize_listener.py index ed57d3547..dee6e28a6 100644 --- a/ibm_watson/websocket/synthesize_listener.py +++ b/ibm_watson/websocket/synthesize_listener.py @@ -44,8 +44,6 @@ def __init__(self, self.http_proxy_port = http_proxy_port self.verify = verify - websocket.enableTrace(True) - self.ws_client = websocket.WebSocketApp( self.url, header=self.headers, From 97de097b8c86622ab2f30f5386bb74321d28addf Mon Sep 17 00:00:00 2001 From: Angelo Paparazzi Date: Mon, 21 Mar 2022 17:27:58 -0400 Subject: [PATCH 367/455] Major release 2022 (#816) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(assistantv1): add three new response types and remove properties BREAKING CHANGE: OutputData: required text property removed, RuntimeEntity: optional metadata property removed RuntimeResponseGeneric: Three new response types added Workspace: workspaceID changed form required to optional * feat(assistantv2): add three new response types, rename model, remove properties BREAKING CHANGE: RuntimeEntity: optional metadata property removed, MessageOutputDebug: nodesVisited type DialogNodesVisited changed to DialogNodeVisited. MessageContext: integrations property added MessageContextGlobalSystem: skipUserInput property added MessageContextStateless: integrations property added MessageInput: attachments property added MessageInputStateless: attachments property added RuntimeResponseGeneric: Three new response types added * refactor(cc): remove compare and comply ヾ(・‿・) * refactor(nlc): remove nlc ヾ(・‿・) * feat(nlu): remove MetadataOptions model * refactor(lt): comment change and test updates * refactor(pi): remove personality insights ヾ(・‿・) * feat(stt/tts): add new property and comment changes * refactor(ta/visrec): remove ta and visrec ヾ(・‿・) * refactor(all): remove remaining traces of removed services * feat(assistantv1): add new dialogNode models and additional properties for Workspace * feat(discov1): update QueryAggregation subclasses BREAKING CHANGE: QueryAggregation: QueryAggregation subclasses changed. DocumentStatus: documentID, status, and statusDescription are now optional * feat(stt): change grammarFile property type BREAKING CHANGE: addGrammar parameter grammarFile changed from String to Data type SupportedFeatures: customAcousticModel property added * chore: copyright changes * build(secrets): upload detect-secrets baseline * docs(readme): add deprecation note and remove old references * ci(version): remove python 3.6 support and add 3.9 support --- .github/workflows/build-test.yml | 20 +- .github/workflows/deploy.yml | 2 +- .github/workflows/integration-test.yml | 143 +- .gitignore | 3 +- .secrets.baseline | 236 + CONTRIBUTING.md | 42 +- README.md | 94 +- .../.env.example | 6 - .../README.md | 32 - .../__init__.py | 21 - .../tone_assistant_integration.v1.py | 71 - .../tone_detection.py | 226 - examples/compare_comply_v1.py | 29 - examples/natural_language_classifier_v1.py | 47 - examples/personality_insights_v3.py | 52 - examples/tone_analyzer_v3.py | 87 - examples/visual_recognition_v3.py | 52 - examples/visual_recognition_v4.py | 70 - ibm_watson/__init__.py | 6 - ibm_watson/assistant_v1.py | 1080 +- ibm_watson/assistant_v2.py | 627 +- ibm_watson/compare_comply_v1.py | 6877 ------------- ibm_watson/discovery_v1.py | 1441 +-- ibm_watson/language_translator_v3.py | 6 +- ibm_watson/natural_language_classifier_v1.py | 895 -- .../natural_language_understanding_v1.py | 84 +- ibm_watson/personality_insights_v3.py | 1342 --- ibm_watson/speech_to_text_v1.py | 702 +- ibm_watson/text_to_speech_v1.py | 205 +- ibm_watson/tone_analyzer_v3.py | 1298 --- ibm_watson/visual_recognition_v3.py | 1425 --- ibm_watson/visual_recognition_v4.py | 3541 ------- resources/ibm-credentials.env | 4 - resources/personality-v3-es.txt | 13 - resources/personality-v3-expect1.txt | 1 - resources/personality-v3-expect2.txt | 1 - resources/personality-v3-expect3.txt | 2 - resources/personality-v3-expect4.txt | 1 - resources/personality-v3.json | 6941 ------------- resources/personality-v3.txt | 137 - resources/personality.es.txt | 13 - resources/personality.txt | 15 - resources/tone-example-html.json | 3 - resources/tone-example.json | 3 - resources/tone-v3-expect1.json | 8680 ----------------- resources/tone-v3-expect2.json | 30 - test/integration/test_compare_comply_v1.py | 160 - test/integration/test_examples.py | 5 +- .../test_natural_language_classifier_v1.py | 67 - .../test_personality_insights_v3.py | 29 - test/integration/test_tone_analyzer_v3.py | 60 - .../integration/test_visual_recognition_v3.py | 59 - .../integration/test_visual_recognition_v4.py | 164 - test/unit/test_assistant_v1.py | 2606 +++-- test/unit/test_assistant_v2.py | 679 +- test/unit/test_compare_comply_v1.py | 4502 --------- test/unit/test_discovery_v1.py | 2770 +++--- test/unit/test_language_translator_v3.py | 482 +- .../test_natural_language_classifier_v1.py | 741 -- .../test_natural_language_understanding_v1.py | 731 +- test/unit/test_personality_insights_v3.py | 544 -- test/unit/test_speech_to_text_v1.py | 1397 +-- test/unit/test_text_to_speech_v1.py | 754 +- test/unit/test_tone_analyzer_v3.py | 698 -- test/unit/test_visual_recognition_v3.py | 1147 --- test/unit/test_visual_recognition_v4.py | 3058 ------ 66 files changed, 9107 insertions(+), 48152 deletions(-) create mode 100644 .secrets.baseline delete mode 100644 examples/assistant_tone_analyzer_integration/.env.example delete mode 100644 examples/assistant_tone_analyzer_integration/README.md delete mode 100644 examples/assistant_tone_analyzer_integration/__init__.py delete mode 100644 examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py delete mode 100644 examples/assistant_tone_analyzer_integration/tone_detection.py delete mode 100644 examples/compare_comply_v1.py delete mode 100644 examples/natural_language_classifier_v1.py delete mode 100755 examples/personality_insights_v3.py delete mode 100755 examples/tone_analyzer_v3.py delete mode 100644 examples/visual_recognition_v3.py delete mode 100644 examples/visual_recognition_v4.py delete mode 100644 ibm_watson/compare_comply_v1.py delete mode 100644 ibm_watson/natural_language_classifier_v1.py delete mode 100644 ibm_watson/personality_insights_v3.py delete mode 100644 ibm_watson/tone_analyzer_v3.py delete mode 100644 ibm_watson/visual_recognition_v3.py delete mode 100644 ibm_watson/visual_recognition_v4.py delete mode 100644 resources/ibm-credentials.env delete mode 100644 resources/personality-v3-es.txt delete mode 100755 resources/personality-v3-expect1.txt delete mode 100755 resources/personality-v3-expect2.txt delete mode 100755 resources/personality-v3-expect3.txt delete mode 100755 resources/personality-v3-expect4.txt delete mode 100755 resources/personality-v3.json delete mode 100644 resources/personality-v3.txt delete mode 100644 resources/personality.es.txt delete mode 100644 resources/personality.txt delete mode 100755 resources/tone-example-html.json delete mode 100755 resources/tone-example.json delete mode 100644 resources/tone-v3-expect1.json delete mode 100644 resources/tone-v3-expect2.json delete mode 100644 test/integration/test_compare_comply_v1.py delete mode 100644 test/integration/test_natural_language_classifier_v1.py delete mode 100644 test/integration/test_personality_insights_v3.py delete mode 100644 test/integration/test_tone_analyzer_v3.py delete mode 100644 test/integration/test_visual_recognition_v3.py delete mode 100644 test/integration/test_visual_recognition_v4.py delete mode 100644 test/unit/test_compare_comply_v1.py delete mode 100644 test/unit/test_natural_language_classifier_v1.py delete mode 100755 test/unit/test_personality_insights_v3.py delete mode 100755 test/unit/test_tone_analyzer_v3.py delete mode 100644 test/unit/test_visual_recognition_v3.py delete mode 100644 test/unit/test_visual_recognition_v4.py diff --git a/.github/workflows/build-test.yml b/.github/workflows/build-test.yml index 57d158c75..dad38e7f5 100644 --- a/.github/workflows/build-test.yml +++ b/.github/workflows/build-test.yml @@ -21,11 +21,9 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ['3.6', '3.7', '3.8'] + python-version: ['3.7', '3.8', '3.9'] os: [ubuntu-latest, windows-latest] exclude: - - os: windows-latest - python-version: '3.6' - os: windows-latest python-version: '3.7' @@ -47,13 +45,13 @@ jobs: pip3 install -r requirements.txt --use-deprecated=legacy-resolver pip3 install -r requirements-dev.txt --use-deprecated=legacy-resolver pip3 install --editable . --use-deprecated=legacy-resolver - - name: Execute Python 3.6/3.7 unit tests - if: matrix.python-version != '3.8' + - name: Execute Python 3.7 unit tests + if: matrix.python-version == '3.7' run: | pip3 install -U python-dotenv py.test test/unit - name: Execute Python 3.8 unit tests (windows) - if: matrix.os == 'windows-latest' + if: matrix.python-version == '3.8' && matrix.os == 'windows-latest' run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 @@ -62,6 +60,16 @@ jobs: run: | pip3 install -U python-dotenv py.test test/unit --reruns 3 --cov=ibm_watson + - name: Execute Python 3.9 unit tests (windows) + if: matrix.python-version == '3.9' && matrix.os == 'windows-latest' + run: | + pip3 install -U python-dotenv + py.test test/unit --reruns 3 + - name: Execute Python 3.9 unit tests (ubuntu) + if: matrix.python-version == '3.9' && matrix.os == 'ubuntu-latest' + run: | + pip3 install -U python-dotenv + py.test test/unit --reruns 3 - name: Upload coverage to Codecov if: matrix.python-version == '3.8' && matrix.os == 'ubuntu-latest' uses: codecov/codecov-action@v1 diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 82326bdce..d8bae9d26 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -29,7 +29,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v2 with: - python-version: '3.8' + python-version: '3.9' - name: Setup Node uses: actions/setup-node@v1 diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index 8b3245b06..059bf7220 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -6,7 +6,6 @@ name: Run Integration Tests on: - # Allows you to run this workflow manually from the Actions tab workflow_dispatch: @@ -16,91 +15,73 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ['3.8'] + python-version: ["3.8"] os: [ubuntu-latest] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v2 - - name: Set up Python - uses: actions/setup-python@v2 - with: - python-version: ${{ matrix.python-version }} + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} - - name: Install Python dependencies (ubuntu) - run: | - pip3 install -r requirements.txt - pip3 install -r requirements-dev.txt - pip3 install --editable . + - name: Install Python dependencies (ubuntu) + run: | + pip3 install -r requirements.txt + pip3 install -r requirements-dev.txt + pip3 install --editable . - - name: Execute Python integration tests - # continue-on-error: true - env: - NATURAL_LANGUAGE_CLASSIFIER_URL: "https://api.us-south.natural-language-classifier.watson.cloud.ibm.com" - NATURAL_LANGUAGE_CLASSIFIER_APIKEY: ${{ secrets.NLC_APIKEY }} - LANGUAGE_TRANSLATOR_APIKEY: ${{ secrets.LT_APIKEY }} - LANGUAGE_TRANSLATOR_URL: "https://api.us-south.language-translator.watson.cloud.ibm.com" - NATURAL_LANGUAGE_UNDERSTANDING_APIKEY: ${{ secrets.NLU_APIKEY }} - NATURAL_LANGUAGE_UNDERSTANDING_URL: "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com" - PERSONALITY_INSIGHTS_APIKEY: ${{ secrets.PI_APIKEY }} - PERSONALITY_INSIGHTS_URL: "https://api.us-south.personality-insights.watson.cloud.ibm.com" - TONE_ANALYZER_APIKEY: ${{ secrets.TA_APIKEY }} - TONE_ANALYZER_URL: "https://api.us-south.tone-analyzer.watson.cloud.ibm.com" - SPEECH_TO_TEXT_APIKEY: ${{ secrets.STT_APIKEY }} - SPEECH_TO_TEXT_URL: "https://api.us-south.speech-to-text.watson.cloud.ibm.com" - TEXT_TO_SPEECH_APIKEY: ${{ secrets.TTS_APIKEY }} - TEXT_TO_SPEECH_URL: "https://api.us-south.text-to-speech.watson.cloud.ibm.com" - VISUAL_RECOGNITION_APIKEY: ${{ secrets.VR_APIKEY }} - VISUAL_RECOGNITION_COLLECTION_ID: ${{ secrets.VR_COLLECTION_ID }} - VISUAL_RECOGNITION_URL: "https://api.us-south.visual-recognition.watson.cloud.ibm.com" - COMPARE_COMPLY_APIKEY: ${{ secrets.CC_APIKEY }} - COMPARE_COMPLY_FEEDBACK_ID: ${{ secrets.CC_FEEDBACK_ID }} - COMPARE_COMPLY_URL: "https://api.us-south.compare-comply.watson.cloud.ibm.com" - ASSISTANT_APIKEY: ${{ secrets.WA_APIKEY }} - ASSISTANT_WORKSPACE_ID: ${{ secrets.WA_WORKSPACE_ID }} - ASSISTANT_ASSISTANT_ID: ${{ secrets.WA_ASSISTANT_ID }} - ASSISTANT_URL: "https://api.us-south.assistant.watson.cloud.ibm.com" - DISCOVERY_APIKEY: ${{ secrets.D1_APIKEY }} - DISCOVERY_ENVIRONMENT_ID: ${{ secrets.D1_ENVIRONMENT_ID }} - DISCOVERY_COLLECTION_ID: ${{ secrets.D1_COLLECTION_ID }} - DISCOVERY_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" - DISCOVERY_V2_APIKEY: ${{ secrets.D2_APIKEY }} - DISCOVERY_V2_PROJECT_ID: ${{ secrets.D2_PROJECT_ID }} - DISCOVERY_V2_COLLECTION_ID: ${{ secrets.D2_COLLECTION_ID }} - DISCOVERY_V2_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" - run: | - pip3 install -U python-dotenv - pytest test/integration/test_assistant_v1.py -rap - echo -e "\n\033[0;35mSKIP: pytest test/integration/test_compare_comply_v1.py -rap" - pytest test/integration/test_discovery_v1.py -rap - pytest test/integration/test_discovery_v2.py -rap - pytest test/integration/test_language_translator_v3.py -rap - pytest test/integration/test_natural_language_classifier_v1.py -rap - pytest test/integration/test_natural_language_understanding_v1.py -rap - pytest test/integration/test_personality_insights_v3.py -rap - pytest test/integration/test_speech_to_text_v1.py -rap - pytest test/integration/test_text_to_speech_v1.py -rap - pytest test/integration/test_tone_analyzer_v3.py -rap - echo -e "\n\033[0;35mSKIP: pytest test/integration/test_visual_recognition_v3.py -rap" - echo -e "\n\033[0;35mSKIP: pytest test/integration/test_visual_recognition_v4.py -rap" + - name: Execute Python integration tests + # continue-on-error: true + env: + LANGUAGE_TRANSLATOR_APIKEY: ${{ secrets.LT_APIKEY }} + LANGUAGE_TRANSLATOR_URL: "https://api.us-south.language-translator.watson.cloud.ibm.com" + NATURAL_LANGUAGE_UNDERSTANDING_APIKEY: ${{ secrets.NLU_APIKEY }} + NATURAL_LANGUAGE_UNDERSTANDING_URL: "https://api.us-south.natural-language-understanding.watson.cloud.ibm.com" + SPEECH_TO_TEXT_APIKEY: ${{ secrets.STT_APIKEY }} + SPEECH_TO_TEXT_URL: "https://api.us-south.speech-to-text.watson.cloud.ibm.com" + TEXT_TO_SPEECH_APIKEY: ${{ secrets.TTS_APIKEY }} + TEXT_TO_SPEECH_URL: "https://api.us-south.text-to-speech.watson.cloud.ibm.com" + ASSISTANT_APIKEY: ${{ secrets.WA_APIKEY }} + ASSISTANT_WORKSPACE_ID: ${{ secrets.WA_WORKSPACE_ID }} + ASSISTANT_ASSISTANT_ID: ${{ secrets.WA_ASSISTANT_ID }} + ASSISTANT_URL: "https://api.us-south.assistant.watson.cloud.ibm.com" + DISCOVERY_APIKEY: ${{ secrets.D1_APIKEY }} + DISCOVERY_ENVIRONMENT_ID: ${{ secrets.D1_ENVIRONMENT_ID }} + DISCOVERY_COLLECTION_ID: ${{ secrets.D1_COLLECTION_ID }} + DISCOVERY_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" + DISCOVERY_V2_APIKEY: ${{ secrets.D2_APIKEY }} + DISCOVERY_V2_PROJECT_ID: ${{ secrets.D2_PROJECT_ID }} + DISCOVERY_V2_COLLECTION_ID: ${{ secrets.D2_COLLECTION_ID }} + DISCOVERY_V2_URL: "https://api.us-south.discovery.watson.cloud.ibm.com" + run: | + pip3 install -U python-dotenv + pytest test/integration/test_assistant_v1.py -rap + pytest test/integration/test_discovery_v1.py -rap + pytest test/integration/test_discovery_v2.py -rap + pytest test/integration/test_language_translator_v3.py -rap + pytest test/integration/test_natural_language_understanding_v1.py -rap + pytest test/integration/test_speech_to_text_v1.py -rap + pytest test/integration/test_text_to_speech_v1.py -rap - # Do not notify on success. We will leave the code here just in case we decide to switch gears - - name: Notify slack on success - if: false # success() - env: - SLACK_BOT_TOKEN: ${{ secrets.SLACK_NOTIFICATIONS_BOT_TOKEN }} - uses: voxmedia/github-action-slack-notify-build@v1 - with: - channel: watson-e2e-tests - status: SUCCESS - color: good + # Do not notify on success. We will leave the code here just in case we decide to switch gears + - name: Notify slack on success + if: false # success() + env: + SLACK_BOT_TOKEN: ${{ secrets.SLACK_NOTIFICATIONS_BOT_TOKEN }} + uses: voxmedia/github-action-slack-notify-build@v1 + with: + channel: watson-e2e-tests + status: SUCCESS + color: good - - name: Notify slack on failure - if: false # failure() - env: - SLACK_BOT_TOKEN: ${{ secrets.SLACK_NOTIFICATIONS_BOT_TOKEN }} - uses: voxmedia/github-action-slack-notify-build@v1 - with: - channel: watson-e2e-tests - status: FAILED - color: danger + - name: Notify slack on failure + if: false # failure() + env: + SLACK_BOT_TOKEN: ${{ secrets.SLACK_NOTIFICATIONS_BOT_TOKEN }} + uses: voxmedia/github-action-slack-notify-build@v1 + with: + channel: watson-e2e-tests + status: FAILED + color: danger diff --git a/.gitignore b/.gitignore index c9e5714d6..54f100b3d 100644 --- a/.gitignore +++ b/.gitignore @@ -67,9 +67,8 @@ test/__init__.py .sfdx/tools/apex.db .pytest_cache/ -# ignore detect secrets files +# ignore pre-commit config file .pre-commit-config.yaml -.secrets.baseline .openapi-generator-ignore .openapi-generator/ \ No newline at end of file diff --git a/.secrets.baseline b/.secrets.baseline new file mode 100644 index 000000000..a9c0826d5 --- /dev/null +++ b/.secrets.baseline @@ -0,0 +1,236 @@ +{ + "exclude": { + "files": "package-lock.json|^.secrets.baseline$", + "lines": null + }, + "generated_at": "2022-03-21T19:21:18Z", + "plugins_used": [ + { + "name": "AWSKeyDetector" + }, + { + "name": "ArtifactoryDetector" + }, + { + "base64_limit": 4.5, + "name": "Base64HighEntropyString" + }, + { + "name": "BasicAuthDetector" + }, + { + "name": "BoxDetector" + }, + { + "name": "CloudantDetector" + }, + { + "name": "Db2Detector" + }, + { + "name": "GheDetector" + }, + { + "hex_limit": 3, + "name": "HexHighEntropyString" + }, + { + "name": "IbmCloudIamDetector" + }, + { + "name": "IbmCosHmacDetector" + }, + { + "name": "JwtTokenDetector" + }, + { + "keyword_exclude": null, + "name": "KeywordDetector" + }, + { + "name": "MailchimpDetector" + }, + { + "name": "PrivateKeyDetector" + }, + { + "name": "SlackDetector" + }, + { + "name": "SoftlayerDetector" + }, + { + "name": "StripeDetector" + }, + { + "name": "TwilioKeyDetector" + } + ], + "results": { + ".github/workflows/deploy.yml": [ + { + "hashed_secret": "51543e129a641c2ece91b32b5bbeaa704dbfe764", + "is_secret": false, + "is_verified": false, + "line_number": 76, + "type": "DB2 Credentials", + "verified_result": null + } + ], + "README.md": [ + { + "hashed_secret": "d9e9019d9eb455a3d72a3bc252c26927bb148a10", + "is_secret": false, + "is_verified": false, + "line_number": 132, + "type": "Secret Keyword", + "verified_result": null + }, + { + "hashed_secret": "32e8612d8ca77c7ea8374aa7918db8e5df9252ed", + "is_secret": false, + "is_verified": false, + "line_number": 174, + "type": "Secret Keyword", + "verified_result": null + }, + { + "hashed_secret": "186154712b2d5f6791d85b9a0987b98fa231779c", + "is_secret": false, + "is_verified": false, + "line_number": 228, + "type": "DB2 Credentials", + "verified_result": null + }, + { + "hashed_secret": "186154712b2d5f6791d85b9a0987b98fa231779c", + "is_secret": false, + "is_verified": false, + "line_number": 228, + "type": "Secret Keyword", + "verified_result": null + } + ], + "docs/generate_index_html.sh": [ + { + "hashed_secret": "973f71aa51bf4dcef6aa10f52089747a85c64a73", + "is_secret": false, + "is_verified": false, + "line_number": 12, + "type": "Base64 High Entropy String", + "verified_result": null + } + ], + "ibm_watson/discovery_v1.py": [ + { + "hashed_secret": "3442496b96dd01591a8cd44b1eec1368ab728aba", + "is_secret": false, + "is_verified": false, + "line_number": 4723, + "type": "DB2 Credentials", + "verified_result": null + }, + { + "hashed_secret": "b16c7ac6faff07d7e255da685e52bd66d3bf1575", + "is_secret": false, + "is_verified": false, + "line_number": 4781, + "type": "DB2 Credentials", + "verified_result": null + }, + { + "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "is_secret": false, + "is_verified": false, + "line_number": 4828, + "type": "DB2 Credentials", + "verified_result": null + }, + { + "hashed_secret": "e8fc807ce6fbcda13f91c5b64850173873de0cdc", + "is_secret": false, + "is_verified": false, + "line_number": 4967, + "type": "Secret Keyword", + "verified_result": null + } + ], + "resources/dummy-storage-credentials.json": [ + { + "hashed_secret": "1b9863aec116b7c1c537f8100173aba52d7384d7", + "is_secret": false, + "is_verified": false, + "line_number": 2, + "type": "Secret Keyword", + "verified_result": null + } + ], + "test/integration/test_discovery_v1.py": [ + { + "hashed_secret": "b60d121b438a380c343d5ec3c2037564b82ffef3", + "is_secret": false, + "is_verified": false, + "line_number": 168, + "type": "DB2 Credentials", + "verified_result": null + }, + { + "hashed_secret": "b60d121b438a380c343d5ec3c2037564b82ffef3", + "is_secret": false, + "is_verified": false, + "line_number": 168, + "type": "Secret Keyword", + "verified_result": null + } + ], + "test/unit/test_discovery_v1.py": [ + { + "hashed_secret": "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8", + "is_secret": false, + "is_verified": false, + "line_number": 6789, + "type": "DB2 Credentials", + "verified_result": null + }, + { + "hashed_secret": "8318df9ecda039deac9868adf1944a29a95c7114", + "is_secret": false, + "is_verified": false, + "line_number": 6789, + "type": "Secret Keyword", + "verified_result": null + }, + { + "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", + "is_secret": false, + "is_verified": false, + "line_number": 7961, + "type": "Secret Keyword", + "verified_result": null + }, + { + "hashed_secret": "b8e758b5ad59a72f146fcf065239d5c7b695a39a", + "is_secret": false, + "is_verified": false, + "line_number": 10241, + "type": "Hex High Entropy String", + "verified_result": null + } + ], + "test/unit/test_speech_to_text_v1.py": [ + { + "hashed_secret": "b8473b86d4c2072ca9b08bd28e373e8253e865c4", + "is_secret": false, + "is_verified": false, + "line_number": 418, + "type": "Secret Keyword", + "verified_result": null + } + ] + }, + "version": "0.13.1+ibm.26.dss", + "word_list": { + "file": null, + "hash": null + } +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f46847fe0..85c67d0af 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,14 +16,16 @@ If you want to contribute to the repository, here's a quick guide: 1. Fork the repository 1. Install `virtualenv` and `tox` 1. Develop and test your code changes with [pytest]. - * Respect the original code [style guide][styleguide]. - * Only use spaces for indentation. - * Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change. - * Check for unnecessary whitespace with `git diff --check` before committing. - * Make sure your code supports Python 3.5, 3.6 and 3.7. You can use `pyenv` and `tox` for this + - Respect the original code [style guide][styleguide]. + - Only use spaces for indentation. + - Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change. + - Check for unnecessary whitespace with `git diff --check` before committing. + - Make sure your code supports Python 3.7, 3.8, 3.9. You can use `pyenv` and `tox` for this 1. Make the test pass 1. Commit your changes -* Commits should follow the [Angular commit message guidelines](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-commit-message-guidelines). This is because our release tool uses this format for determining release versions and generating changelogs. To make this easier, we recommend using the [Commitizen CLI](https://github.com/commitizen/cz-cli) with the `cz-conventional-changelog` adapter. + +- Commits should follow the [Angular commit message guidelines](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-commit-message-guidelines). This is because our release tool uses this format for determining release versions and generating changelogs. To make this easier, we recommend using the [Commitizen CLI](https://github.com/commitizen/cz-cli) with the `cz-conventional-changelog` adapter. + 1. Push to your fork and submit a pull request to the `dev` branch ## Running the tests @@ -31,26 +33,26 @@ If you want to contribute to the repository, here's a quick guide: You probably want to set up a [virtualenv]. 1. Clone this repository: - ```sh - git clone https://github.com/watson-developer-cloud/python-sdk.git - ``` + ```sh + git clone https://github.com/watson-developer-cloud/python-sdk.git + ``` 1. Install the sdk as an editable package using the current source: - ```sh - pip install --editable . - ``` + ```sh + pip install --editable . + ``` 1. Install the test dependencies with: - ```sh - pip install -r requirements-dev.txt - ``` + ```sh + pip install -r requirements-dev.txt + ``` 1. Run the test cases with: - ```sh - py.test test - ``` + ```sh + py.test test + ``` ## Additional Resources -* [General GitHub documentation](https://help.github.com/) -* [GitHub pull request documentation](https://help.github.com/send-pull-requests/) +- [General GitHub documentation](https://help.github.com/) +- [GitHub pull request documentation](https://help.github.com/send-pull-requests/) [dw]: https://developer.ibm.com/answers/questions/ask/?topics=watson [stackoverflow]: http://stackoverflow.com/questions/ask?tags=ibm-watson diff --git a/README.md b/README.md index 46241a296..8fb71fc37 100755 --- a/README.md +++ b/README.md @@ -7,34 +7,35 @@ [![CLA assistant](https://cla-assistant.io/readme/badge/watson-developer-cloud/python-sdk)](https://cla-assistant.io/watson-developer-cloud/python-sdk) ## Deprecated builds + [![Build Status](https://travis-ci.org/watson-developer-cloud/python-sdk.svg?branch=master)](https://travis-ci.org/watson-developer-cloud/python-sdk) Python client library to quickly get started with the various [Watson APIs][wdc] services. ## Announcements -### Natural Language Classifier deprecation -On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. -As an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud that uses deep learning to extract data and insights from text such as keywords, categories, sentiment, emotion, and syntax, along with advanced multi-label text classification capabilities, to provide even richer insights for your business or industry. For more information, see [Migrating to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating). +### Tone Analyzer Deprecation + +As of this major release, 6.0.0, the Tone Analyzer api has been removed in preparation for deprecation. If you wish to continue using this sdk to make calls to Tone Analyzer until its final deprecation, you will have to use a previous version. -### Updating endpoint URLs from watsonplatform.net -Watson API endpoint URLs at watsonplatform.net are changing and will not work after 26 May 2021. Update your calls to use the newer endpoint URLs. For more information, see https://cloud.ibm.com/docs/watson?topic=watson-endpoint-change. +On 24 February 2022, IBM announced the deprecation of the Tone Analyzer service. The service will no longer be available as of 24 February 2023. As of 24 February 2022, you will not be able to create new instances. Existing instances will be supported until 24 February 2023. -### Personality Insights deprecation -IBM Watson™ Personality Insights is discontinued. For a period of one year from 1 December 2020, you will still be able to use Watson Personality Insights. However, as of 1 December 2021, the offering will no longer be available. +As an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud. With Natural Language Understanding, tone analysis is done by using a pre-built classifications model, which provides an easy way to detect language tones in written text. For more information, see [Migrating from Watson Tone Analyzer Customer Engagement endpoint to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-tone_analytics). -As an alternative, we encourage you to consider migrating to IBM Watson™ [Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-understanding), a service on IBM Cloud® that uses deep learning to extract data and insights from text such as keywords, categories, sentiment, emotion, and syntax to provide insights for your business or industry. For more information, see About Natural Language Understanding. +### Natural Language Classifier Deprecation -### Visual Recognition deprecation -IBM Watson™ Visual Recognition is discontinued. Existing instances are supported until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance that is provisioned on 1 December 2021 will be deleted. +As of this major release, 6.0.0, the NLC api has been removed in preparation for deprecation. If you wish to continue using this sdk to make calls to NLC until its final deprecation, you will have to use a previous version. -### Compare and Comply deprecation -IBM Watson™ Compare and Comply is discontinued. Existing instances are supported until 30 November 2021, but as of 1 December 2020, you can't create instances. Any instance that exists on 30 November 2021 will be deleted. Consider migrating to Watson Discovery Premium on IBM Cloud for your Compare and Comply use cases. To start the migration process, visit https://ibm.biz/contact-wdc-premium. +On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. + +As an alternative, we encourage you to consider migrating to the Natural Language Understanding service on IBM Cloud that uses deep learning to extract data and insights from text such as keywords, categories, sentiment, emotion, and syntax, along with advanced multi-label text classification capabilities, to provide even richer insights for your business or industry. For more information, see [Migrating to Natural Language Understanding](https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating). ## Before you begin -* You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support `python 3.5` and above + +- You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support `python 3.5` and above ## Installation + To install, use `pip` or `easy_install`: ```bash @@ -63,9 +64,11 @@ sudo -H pip install --ignore-installed six ibm-watson For more details see [#225](https://github.com/watson-developer-cloud/python-sdk/issues/225) c) In case you run into problems installing the SDK in DSX, try + ``` !pip install --upgrade pip ``` + Restarting the kernel For more details see [#405](https://github.com/watson-developer-cloud/python-sdk/issues/405) @@ -86,6 +89,7 @@ Watson services are migrating to token-based Identity and Access Management (IAM - In other instances, you authenticate by providing the **[username and password](#username-and-password)** for the service instance. ### Getting credentials + To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services: 1. Go to the IBM Cloud [Dashboard](https://cloud.ibm.com/) page. @@ -126,7 +130,8 @@ export IBM_CREDENTIALS_FILE="" where `` is something like `/home/user/Downloads/.env`. #### Environment Variables -Simply set the environment variables using _ syntax. For example, using your favourite terminal, you can set environment variables for Assistant service instance: + +Simply set the environment variables using \_ syntax. For example, using your favourite terminal, you can set environment variables for Assistant service instance: ```bash export ASSISTANT_APIKEY="" @@ -139,8 +144,8 @@ The credentials will be loaded from the environment automatically assistant = AssistantV1(version='2018-08-01') ``` - #### Manually + If you'd prefer to set authentication values manually in your code, the SDK supports that as well. The way you'll do this depends on what type of credentials your service instance gives you. ### IAM @@ -154,6 +159,7 @@ You supply either an IAM service **API key** or a **bearer token**: - Use a server-side to generate access tokens using your IAM API key for untrusted environments like client-side scripts. The generated access tokens will be valid for one hour and can be refreshed. #### Supplying the API key + ```python from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator @@ -167,6 +173,7 @@ discovery.set_service_url('') ``` #### Generating bearer tokens using API key + ```python from ibm_watson import IAMTokenManager @@ -176,6 +183,7 @@ token = iam_token_manager.get_token() ``` ##### Supplying the bearer token + ```python from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator @@ -188,6 +196,7 @@ discovery.set_service_url('') ``` ### Username and password + ```python from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators import BasicAuthenticator @@ -198,6 +207,7 @@ discovery.set_service_url('') ``` ### No Authentication + ```python from ibm_watson import DiscoveryV1 from ibm_cloud_sdk_core.authenticators import NoAuthAuthenticator @@ -216,10 +226,13 @@ Tested on Python 3.5, 3.6, and 3.7. If you have issues with the APIs or have a question about the Watson services, see [Stack Overflow](https://stackoverflow.com/questions/tagged/ibm-watson+python). ## Changes for v1.0 + Version 1.0 focuses on the move to programmatically-generated code for many of the services. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. ## Changes for v2.0 + `DetailedResponse` which contains the result, headers and HTTP status code is now the default response for all methods. + ```python from ibm_watson import AssistantV1 @@ -234,14 +247,17 @@ print(response.get_result()) print(response.get_headers()) print(response.get_status_code()) ``` + See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. ## Changes for v3.0 + The SDK is generated using OpenAPI Specification(OAS3). Changes are basic reordering of parameters in function calls. The package is renamed to ibm_watson. See the [changelog](https://github.com/watson-developer-cloud/python-sdk/wiki/Changelog) for the details. ## Changes for v4.0 + Authenticator variable indicates the type of authentication to be used. ```python @@ -254,12 +270,15 @@ assistant = AssistantV1( authenticator=authenticator) assistant.set_service_url('') ``` + For more information, follow the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md) ## Migration + To move from v3.x to v4.0, refer to the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/blob/master/MIGRATION-V4.md). ## Configuring the http client (Supported from v1.1.0) + To set client configs like timeout use the `set_http_config()` function and pass it a dictionary of configs. See this [documentation](https://2.python-requests.org/en/master/api/#requests.request) for more information about the options. All options shown except `method`, `url`, `headers`, `params`, `data`, and `auth` are configurable via `set_http_config()`. For example for a Assistant service instance ```python @@ -279,9 +298,11 @@ print(json.dumps(response, indent=2)) ``` ### Use behind a corporate proxy + To use the SDK with any proxies you may have they can be set as shown below. For documentation on proxies see [here](https://2.python-requests.org/en/latest/user/advanced/#proxies) See this example configuration: + ```python from ibm_watson import AssistantV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator @@ -299,7 +320,9 @@ assistant.set_http_config({'proxies': { ``` ### Sending custom certificates + To send custom certificates as a security measure in your request, use the cert property of the HTTPS Agent. + ```python from ibm_watson import AssistantV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator @@ -314,6 +337,7 @@ assistant.set_http_config({'cert': ('path_to_cert_file','path_to_key_file')}) ``` ## Disable SSL certificate verification + For ICP(IBM Cloud Private), you can disable the SSL certificate verification by: ```python @@ -327,6 +351,7 @@ export _DISABLE_SSL=True ``` ## Setting the service url + To set the base service to be used when contacting the service ```python @@ -340,14 +365,18 @@ export _URL="" ``` ## Sending request headers + Custom headers can be passed in any request in the form of a `dict` as: + ```python headers = { 'Custom-Header': 'custom_value' } ``` + For example, to send a header called `Custom-Header` to a call in Watson Assistant, pass the headers parameter as: + ```python from ibm_watson import AssistantV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator @@ -362,7 +391,9 @@ response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}). ``` ## Parsing HTTP response information + If you would like access to some HTTP response information along with the response model, you can set the `set_detailed_response()` to `True`. Since Python SDK `v2.0`, it is set to `True` + ```python from ibm_watson import AssistantV1 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator @@ -379,6 +410,7 @@ print(response) ``` This would give an output of `DetailedResponse` having the structure: + ```python { 'result': , @@ -386,12 +418,15 @@ This would give an output of `DetailedResponse` having the structure: 'status_code': } ``` + You can use the `get_result()`, `get_headers()` and get_status_code() to return the result, headers and status code respectively. ## Getting the transaction ID + Every SDK call returns a response with a transaction ID in the `X-Global-Transaction-Id` header. Together the service instance region, this ID helps support teams troubleshoot issues from relevant logs. ### Suceess + ```python from ibm_watson import AssistantV1 @@ -401,6 +436,7 @@ print(response_headers.get('X-Global-Transaction-Id')) ``` ### Failure + ```python from ibm_watson import AssistantV1, ApiException @@ -423,6 +459,7 @@ service.my_service_call(headers={'X-Global-Transaction-Id': '= 2.5.3 -* [responses] for testing -* Following for web sockets support in speech to text - * `websocket-client` 0.48.0 -* `ibm_cloud_sdk_core` == 1.0.0 +- [requests] +- `python_dateutil` >= 2.5.3 +- [responses] for testing +- Following for web sockets support in speech to text + - `websocket-client` 0.48.0 +- `ibm_cloud_sdk_core` == 1.0.0 ## Contributing -See [CONTRIBUTING.md][CONTRIBUTING]. +See [CONTRIBUTING.md][contributing]. ## Featured Projects Here are some projects that have been using the SDK: -* [NLC ICD-10 Classifier](https://github.com/IBM/nlc-icd10-classifier) -* [Cognitive Moderator Service](https://github.com/IBM/cognitive-moderator-service) +- [NLC ICD-10 Classifier](https://github.com/IBM/nlc-icd10-classifier) +- [Cognitive Moderator Service](https://github.com/IBM/cognitive-moderator-service) We'd love to highlight cool open-source projects that use this SDK! If you'd like to get your project added to the list, feel free to make an issue linking us to it. - ## License This library is licensed under the [Apache 2.0 license][license]. @@ -542,7 +584,7 @@ This library is licensed under the [Apache 2.0 license][license]. [responses]: https://github.com/getsentry/responses [requests]: http://docs.python-requests.org/en/latest/ [examples]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples -[CONTRIBUTING]: https://github.com/watson-developer-cloud/python-sdk/blob/master/CONTRIBUTING.md +[contributing]: https://github.com/watson-developer-cloud/python-sdk/blob/master/CONTRIBUTING.md [license]: http://www.apache.org/licenses/LICENSE-2.0 [vcap_services]: https://cloud.ibm.com/docs/watson?topic=watson-vcapServices [ibm-cloud-onboarding]: https://cloud.ibm.com/registration?target=/developer/watson&cm_sp=WatsonPlatform-WatsonServices-_-OnPageNavLink-IBMWatson_SDKs-_-Python diff --git a/examples/assistant_tone_analyzer_integration/.env.example b/examples/assistant_tone_analyzer_integration/.env.example deleted file mode 100644 index 416fe383b..000000000 --- a/examples/assistant_tone_analyzer_integration/.env.example +++ /dev/null @@ -1,6 +0,0 @@ -# see README.md for details - -ASSISTANT_APIKEY= -WORKSPACE_ID= - -TONE_ANALYZER_APIKEY= diff --git a/examples/assistant_tone_analyzer_integration/README.md b/examples/assistant_tone_analyzer_integration/README.md deleted file mode 100644 index f75c1c7c7..000000000 --- a/examples/assistant_tone_analyzer_integration/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# Assistant and Tone Analyzer Integration Example - -This example provides sample code for integrating [Tone Analyzer][tone_analyzer] and [Assistant][assistant] in Python 2.6+. All calls are made synchronously. For sample Python 3.5 asynchronous code, please see [https://github.com/aprilwebster/python-sdk][aprilwebster_python_sdk_github]. - - * [tone_detection.py][tone_assistant_integration_example_tone_detection] - sample code to initialize a user object in the assistant payload's context (initUser), to call Tone Analyzer to retrieve tone for a user's input (invokeToneAsync), and to update tone in the user object in the assistant payload's context (updateUserTone). - - * [tone_assistant_integration.v1.py][tone_assistant_integration_example] - sample code to use tone_detection.py to get and add tone to the payload and send a request to the Assistant Service's message endpoint both in a synchronous and asynchronous manner. - - -Requirements to run the sample code - - * [Tone Analyzer Service credentials][ibm_cloud_tone_analyzer_service] - * [Assistant Service credentials][ibm_cloud_assistant_service] - * [Assistant Workspace ID][assistant_simple_workspace] - -Credentials & the Workspace ID can be set in environment properties, a .env file, or directly in the code. - -Dependencies provided in -`init.py` - -Command to run the sample code - -`python tone_assistant_integration.v1.py` - -[assistant]: https://cloud.ibm.com/apidocs/assistant -[tone_analyzer]: https://cloud.ibm.com/apidocs/tone-analyzer -[ibm_cloud_assistant_service]: https://cloud.ibm.com/catalog/services/watson-assistant -[ibm_cloud_tone_analyzer_service]: https://cloud.ibm.com/catalog/services/tone-analyzer -[assistant_simple_workspace]: https://github.com/watson-developer-cloud/conversation-simple#workspace -[tone_assistant_integration_example]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py -[tone_assistant_integration_example_tone_detection]: https://github.com/watson-developer-cloud/python-sdk/tree/master/examples/assistant_tone_analyzer_integration/tone_detection.py -[aprilwebster_python_sdk_github]: https://github.com/aprilwebster/python-sdk \ No newline at end of file diff --git a/examples/assistant_tone_analyzer_integration/__init__.py b/examples/assistant_tone_analyzer_integration/__init__.py deleted file mode 100644 index 5264e58b4..000000000 --- a/examples/assistant_tone_analyzer_integration/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# (C) Copyright IBM Corp. 2016, 2020. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -from .ibm_watson import WatsonService -from .ibm_watson import WatsonException -from .assistant import AssistantV1 -from .tone_analyzer_v3 import ToneAnalyzerV3 - - -from .version import __version__ diff --git a/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py b/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py deleted file mode 100644 index 1e4695c40..000000000 --- a/examples/assistant_tone_analyzer_integration/tone_assistant_integration.v1.py +++ /dev/null @@ -1,71 +0,0 @@ -import json -import os -from dotenv import load_dotenv, find_dotenv - -from ibm_watson import AssistantV1 -from ibm_watson import ToneAnalyzerV3 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -# import tone detection -import tone_detection - -# load the .env file containing your environment variables for the required -# services (conversation and tone) -load_dotenv(find_dotenv()) - -# replace with your own assistant credentials or put them in a .env file -assistant_authenticator = IAMAuthenticator(os.environ.get('ASSISTANT_APIKEY') or 'YOUR ASSISTANT APIKEY') -assistant = AssistantV1( - version='2018-07-10', - authenticator=assistant_authenticator) - -# replace with your own tone analyzer credentials -tone_analyzer_authenticator = IAMAuthenticator(os.environ.get('TONE_ANALYZER_APIKEY') or 'YOUR TONE ANALYZER APIKEY') -tone_analyzer = ToneAnalyzerV3( - version='2016-05-19', - authenticator=tone_analyzer_authenticator) - -# replace with your own workspace_id -workspace_id = os.environ.get('WORKSPACE_ID') or 'YOUR WORKSPACE ID' - -# This example stores tone for each user utterance in conversation context. -# Change this to false, if you do not want to maintain history -global_maintainToneHistoryInContext = True - -# Payload for the Watson Conversation Service -# user input text required - replace "I am happy" with user input text. -global_payload = { - 'workspace_id': workspace_id, - 'input': { - 'text': "I am happy" - } -} - - -def invokeToneConversation(payload, maintainToneHistoryInContext): - """ - invokeToneConversation calls the Tone Analyzer service to get the - tone information for the user's input text (input['text'] in the payload - json object), adds/updates the user's tone in the payload's context, - and sends the payload to the - conversation service to get a response which is printed to screen. - :param payload: a json object containing the basic information needed to - converse with the Conversation Service's message endpoint. - :param maintainHistoryInContext: - - - Note: as indicated below, the console.log statements can be replaced - with application-specific code to process the err or data object - returned by the Conversation Service. - """ - tone = tone_analyzer.tone(tone_input=payload['input'], content_type='application/json').get_result() - conversation_payload = tone_detection.\ - updateUserTone(payload, tone, maintainToneHistoryInContext) - response = assistant.message(workspace_id=workspace_id, - input=conversation_payload['input'], - context=conversation_payload['context']).get_result() - print(json.dumps(response, indent=2)) - - -# synchronous call to conversation with tone included in the context -invokeToneConversation(global_payload, global_maintainToneHistoryInContext) diff --git a/examples/assistant_tone_analyzer_integration/tone_detection.py b/examples/assistant_tone_analyzer_integration/tone_detection.py deleted file mode 100644 index c5717893c..000000000 --- a/examples/assistant_tone_analyzer_integration/tone_detection.py +++ /dev/null @@ -1,226 +0,0 @@ -# (C) Copyright IBM Corp. 2016, 2020. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -""" - * Thresholds for identifying meaningful tones returned by the Watson Tone - Analyzer. Current values are - * based on the recommendations made by the Watson Tone Analyzer at - * https://cloud.ibm.com/docs/tone-analyzer?topic=tone-analyzer-utgpe - * These thresholds can be adjusted to client/domain requirements. -""" - -PRIMARY_EMOTION_SCORE_THRESHOLD = 0.5 -WRITING_HIGH_SCORE_THRESHOLD = 0.75 -WRITING_NO_SCORE_THRESHOLD = 0.0 -SOCIAL_HIGH_SCORE_THRESHOLD = 0.75 -SOCIAL_LOW_SCORE_THRESHOLD = 0.25 - -# Labels for the tone categories returned by the Watson Tone Analyzer -EMOTION_TONE_LABEL = 'emotion_tone' -LANGUAGE_TONE_LABEL = 'language_tone' -SOCIAL_TONE_LABEL = 'social_tone' - - -def updateUserTone(conversationPayload, toneAnalyzerPayload, maintainHistory): - """ - updateUserTone processes the Tone Analyzer payload to pull out the emotion, - writing and social tones, and identify the meaningful tones (i.e., - those tones that meet the specified thresholds). - The conversationPayload json object is updated to include these tones. - @param conversationPayload json object returned by the Watson Conversation - Service - @param toneAnalyzerPayload json object returned by the Watson Tone Analyzer - Service - @returns conversationPayload where the user object has been updated with tone - information from the toneAnalyzerPayload - """ - emotionTone = None - writingTone = None - socialTone = None - - # if there is no context in a - if 'context' not in conversationPayload: - conversationPayload['context'] = {} - - if 'user' not in conversationPayload['context']: - conversationPayload['context'] = initUser() - - # For convenience sake, define a variable for the user object - user = conversationPayload['context']['user'] - - # Extract the tones - emotion, writing and social - if toneAnalyzerPayload and toneAnalyzerPayload['document_tone']: - for toneCategory in toneAnalyzerPayload['document_tone']['tone_categories']: - if toneCategory['category_id'] == EMOTION_TONE_LABEL: - emotionTone = toneCategory - if toneCategory['category_id'] == LANGUAGE_TONE_LABEL: - writingTone = toneCategory - if toneCategory['category_id'] == SOCIAL_TONE_LABEL: - socialTone = toneCategory - - updateEmotionTone(user, emotionTone, maintainHistory) - updateWritingTone(user, writingTone, maintainHistory) - updateSocialTone(user, socialTone, maintainHistory) - - conversationPayload['context']['user'] = user - - return conversationPayload - - -def initUser(): - """ - initUser initializes a user object containing tone data (from the - Watson Tone Analyzer) - @returns user json object with the emotion, writing and social tones. The - current tone identifies the tone for a specific conversation turn, and the - history provides the conversation for all tones up to the current tone for a - conversation instance with a user. - """ - return { - 'user': { - 'tone': { - 'emotion': { - 'current': None - }, - 'writing': { - 'current': None - }, - 'social': { - 'current': None - } - } - } - } - - - - -def updateEmotionTone(user, emotionTone, maintainHistory): - """ - updateEmotionTone updates the user emotion tone with the primary emotion - - the emotion tone that has a score greater than or equal to the - EMOTION_SCORE_THRESHOLD; otherwise primary emotion will be 'neutral' - @param user a json object representing user information (tone) to be used in - conversing with the Conversation Service - @param emotionTone a json object containing the emotion tones in the payload - returned by the Tone Analyzer - """ - maxScore = 0.0 - primaryEmotion = None - primaryEmotionScore = None - - for tone in emotionTone['tones']: - if tone['score'] > maxScore: - maxScore = tone['score'] - primaryEmotion = tone['tone_name'].lower() - primaryEmotionScore = tone['score'] - - if maxScore <= PRIMARY_EMOTION_SCORE_THRESHOLD: - primaryEmotion = 'neutral' - primaryEmotionScore = None - - # update user emotion tone - user['tone']['emotion']['current'] = primaryEmotion - - if maintainHistory: - if 'history' not in user['tone']['emotion']: - user['tone']['emotion']['history'] = [] - user['tone']['emotion']['history'].append({ - 'tone_name': primaryEmotion, - 'score': primaryEmotionScore - }) - - -def updateWritingTone(user, writingTone, maintainHistory): - """ - updateWritingTone updates the user with the writing tones interpreted based - on the specified thresholds - @param: user a json object representing user information (tone) to be used - in conversing with the Conversation Service - @param: writingTone a json object containing the writing tones in the - payload returned by the Tone Analyzer - """ - currentWriting = [] - currentWritingObject = [] - - # Process each writing tone and determine if it is high or low - for tone in writingTone['tones']: - if tone['score'] >= WRITING_HIGH_SCORE_THRESHOLD: - currentWriting.append(tone['tone_name'].lower() + '_high') - currentWritingObject.append({ - 'tone_name': tone['tone_name'].lower(), - 'score': tone['score'], - 'interpretation': 'likely high' - }) - elif tone['score'] <= WRITING_NO_SCORE_THRESHOLD: - currentWritingObject.append({ - 'tone_name': tone['tone_name'].lower(), - 'score': tone['score'], - 'interpretation': 'no evidence' - }) - else: - currentWritingObject.append({ - 'tone_name': tone['tone_name'].lower(), - 'score': tone['score'], - 'interpretation': 'likely medium' - }) - - # update user writing tone - user['tone']['writing']['current'] = currentWriting - if maintainHistory: - if 'history' not in user['tone']['writing']: - user['tone']['writing']['history'] = [] - user['tone']['writing']['history'].append(currentWritingObject) - - -def updateSocialTone(user, socialTone, maintainHistory): - """ - updateSocialTone updates the user with the social tones interpreted based on - the specified thresholds - @param user a json object representing user information (tone) to be used in - conversing with the Conversation Service - @param socialTone a json object containing the social tones in the payload - returned by the Tone Analyzer - """ - currentSocial = [] - currentSocialObject = [] - - # Process each social tone and determine if it is high or low - for tone in socialTone['tones']: - if tone['score'] >= SOCIAL_HIGH_SCORE_THRESHOLD: - currentSocial.append(tone['tone_name'].lower() + '_high') - currentSocialObject.append({ - 'tone_name': tone['tone_name'].lower(), - 'score': tone['score'], - 'interpretation': 'likely high' - }) - elif tone['score'] <= SOCIAL_LOW_SCORE_THRESHOLD: - currentSocial.append(tone['tone_name'].lower() + '_low') - currentSocialObject.append({ - 'tone_name': tone['tone_name'].lower(), - 'score': tone['score'], - 'interpretation': 'likely low' - }) - else: - currentSocialObject.append({ - 'tone_name': tone['tone_name'].lower(), - 'score': tone['score'], - 'interpretation': 'likely medium' - }) - - # update user social tone - user['tone']['social']['current'] = currentSocial - if maintainHistory: - if not user['tone']['social']['current']: - user['tone']['social']['current'] = [] - user['tone']['social']['current'].append(currentSocialObject) diff --git a/examples/compare_comply_v1.py b/examples/compare_comply_v1.py deleted file mode 100644 index 63e339860..000000000 --- a/examples/compare_comply_v1.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding: utf-8 -import json -import os -from ibm_watson import CompareComplyV1 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your apikey') -compare_comply = CompareComplyV1( - version='2018-03-23', - authenticator=authenticator) -compare_comply.set_service_url('https://api.us-south.compare-comply.watson.cloud.ibm.com') - -print('Convert to HTML') -contract = os.path.abspath('resources/contract_A.pdf') -with open(contract, 'rb') as file: - result = compare_comply.convert_to_html(file).get_result() - print(json.dumps(result, indent=2)) - -print('Classify elements') -contract = os.path.abspath('resources/contract_A.pdf') -with open(contract, 'rb') as file: - result = compare_comply.classify_elements(file, file_content_type='application/pdf').get_result() - print(json.dumps(result, indent=2)) - -print('Extract tables') -table = os.path.abspath('resources/contract_A.pdf') -with open(table, 'rb') as file: - result = compare_comply.extract_tables(file).get_result() - print(json.dumps(result, indent=2)) diff --git a/examples/natural_language_classifier_v1.py b/examples/natural_language_classifier_v1.py deleted file mode 100644 index 62457e509..000000000 --- a/examples/natural_language_classifier_v1.py +++ /dev/null @@ -1,47 +0,0 @@ -import json -import os - -from ibm_watson import NaturalLanguageClassifierV1 -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your_api_key') -service = NaturalLanguageClassifierV1(authenticator=authenticator) -service.set_service_url('https://api.us-south.natural-language-classifier.watson.cloud.ibm.com') - -classifiers = service.list_classifiers().get_result() -print(json.dumps(classifiers, indent=2)) - -# create a classifier -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 = service.create_classifier( - training_metadata=metadata, training_data=training_data).get_result() - classifier_id = classifier['classifier_id'] - print(json.dumps(classifier, indent=2)) - -status = service.get_classifier(classifier_id).get_result() -print(json.dumps(status, indent=2)) - -if status['status'] == 'Available': - classes = service.classify(classifier_id, 'How hot will it be ' - 'tomorrow?').get_result() - print(json.dumps(classes, indent=2)) - -if status['status'] == 'Available': - collection = [ - '{"text":"How hot will it be today?"}', '{"text":"Is it hot outside?"}' - ] - classes = service.classify_collection(classifier_id, - collection).get_result() - print(json.dumps(classes, indent=2)) - -delete = service.delete_classifier(classifier_id).get_result() -print(json.dumps(delete, indent=2)) - -# example of raising a ValueError -# print(json.dumps( -# service.create_classifier(training_data='', training_metadata='metadata'), -# indent=2)) diff --git a/examples/personality_insights_v3.py b/examples/personality_insights_v3.py deleted file mode 100755 index b2951465a..000000000 --- a/examples/personality_insights_v3.py +++ /dev/null @@ -1,52 +0,0 @@ -""" -The example returns a JSON response whose content is the same as that in - ../resources/personality-v3-expect2.txt -""" -import json -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 -# authenticator = IAMAuthenticator('your_api_key') -# service = PersonalityInsightsV3( -# version='2017-10-13', -# authenticator=authenticator) -# service.set_service_url('https://gateway.watsonplatform.net/personality-insights/api') - -# Authentication via external config like VCAP_SERVICES -service = PersonalityInsightsV3(version='2017-10-13') -service.set_service_url('https://api.us-east.personality-insights.watson.cloud.ibm.com/instances/4c18b521-3abd-4c7c-bec7-6a3fd03644f1') - -############################ -# Profile with JSON output # -############################ - -with open(join(os.getcwd(), 'resources/personality-v3.json')) as \ - profile_json: - profile = service.profile( - profile_json.read(), - 'application/json', - raw_scores=True, - consumption_preferences=True).get_result() - - print(json.dumps(profile, indent=2)) - -########################### -# Profile with CSV output # -########################### - -with open(join(os.getcwd(), 'resources/personality-v3.json'), 'r') as \ - profile_json: - response = service.profile( - profile_json.read(), - accept='text/csv', - csv_headers=True).get_result() - -profile = response.content -cr = csv.reader(profile.decode('utf-8').splitlines()) -my_list = list(cr) -for row in my_list: - print(row) diff --git a/examples/tone_analyzer_v3.py b/examples/tone_analyzer_v3.py deleted file mode 100755 index db4833180..000000000 --- a/examples/tone_analyzer_v3.py +++ /dev/null @@ -1,87 +0,0 @@ -import json -import os -from os.path import join -from ibm_watson import ToneAnalyzerV3 -from ibm_watson.tone_analyzer_v3 import ToneInput -# from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -# Authentication via IAM -# authenticator = IAMAuthenticator('your_api_key') -# service = ToneAnalyzerV3( -# version='2017-09-21', -# authenticator=authenticator) -# service.set_service_url('https://gateway.watsonplatform.net/tone-analyzer/api') - -# Authentication via external config like VCAP_SERVICES -service = ToneAnalyzerV3(version='2017-09-21') -service.set_service_url('https://api.us-south.tone-analyzer.watson.cloud.ibm.com') - -print("\ntone_chat() example 1:\n") -utterances = [{ - 'text': 'I am very happy.', - 'user': 'glenn' -}, { - 'text': 'It is a good day.', - 'user': 'glenn' -}] -tone_chat = service.tone_chat(utterances).get_result() -print(json.dumps(tone_chat, indent=2)) - -print("\ntone() example 1:\n") -print( - json.dumps( - service.tone( - tone_input='I am very happy. It is a good day.', - content_type="text/plain").get_result(), - indent=2)) - -print("\ntone() example 2:\n") -with open(join(os.getcwd(), - 'resources/tone-example.json')) as tone_json: - tone = service.tone(json.load(tone_json)['text'], content_type="text/plain").get_result() -print(json.dumps(tone, indent=2)) - -print("\ntone() example 3:\n") -with open(join(os.getcwd(), - 'resources/tone-example.json')) as tone_json: - tone = service.tone( - tone_input=json.load(tone_json)['text'], - content_type='text/plain', - sentences=True).get_result() -print(json.dumps(tone, indent=2)) - -print("\ntone() example 4:\n") -with open(join(os.getcwd(), - 'resources/tone-example.json')) as tone_json: - tone = service.tone( - tone_input=json.load(tone_json), - content_type='application/json').get_result() -print(json.dumps(tone, indent=2)) - -print("\ntone() example 5:\n") -with open(join(os.getcwd(), - 'resources/tone-example-html.json')) as tone_html: - tone = service.tone( - json.load(tone_html)['text'], - content_type='text/html').get_result() -print(json.dumps(tone, indent=2)) - -print("\ntone() example 6 with GDPR support:\n") -with open(join(os.getcwd(), - 'resources/tone-example-html.json')) as tone_html: - tone = service.tone( - json.load(tone_html)['text'], - content_type='text/html', - headers={ - 'Custom-Header': 'custom_value' - }) - -print(tone) -print(tone.get_headers()) -print(tone.get_result()) -print(tone.get_status_code()) - -print("\ntone() example 7:\n") -tone_input = ToneInput('I am very happy. It is a good day.') -tone = service.tone(tone_input=tone_input, content_type="application/json").get_result() -print(json.dumps(tone, indent=2)) diff --git a/examples/visual_recognition_v3.py b/examples/visual_recognition_v3.py deleted file mode 100644 index 01ddeb7b8..000000000 --- a/examples/visual_recognition_v3.py +++ /dev/null @@ -1,52 +0,0 @@ -import json -from os.path import abspath -from ibm_watson import VisualRecognitionV3, ApiException -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator('your_apikey') -test_url = 'https://www.ibm.com/ibm/ginni/images' \ - '/ginni_bio_780x981_v4_03162016.jpg' - -# If service instance provides IAM API key authentication -service = VisualRecognitionV3( - '2018-03-19', - authenticator=authenticator) -service.set_service_url('https://api.us-south.visual-recognition.watson.cloud.ibm.com') - -# with open(abspath('resources/cars.zip'), 'rb') as cars, \ -# open(abspath('resources/trucks.zip'), 'rb') as trucks: -# classifier = service.create_classifier('Cars vs Trucks', -# positive_examples={'cars': cars}, -# negative_examples=trucks).get_result() -# print(json.dumps(classifier, indent=2)) - -car_path = abspath("resources/cars.zip") -try: - with open(car_path, 'rb') as images_file: - car_results = service.classify( - images_file=images_file, - threshold='0.1', - classifier_ids=['default']).get_result() - print(json.dumps(car_results, indent=2)) -except ApiException as ex: - print(ex) - -# classifier = service.get_classifier('YOUR CLASSIFIER ID').get_result() -# print(json.dumps(classifier, indent=2)) - -# with open(abspath('resources/car.jpg'), 'rb') as image_file: -# classifier = service.update_classifier('CarsvsTrucks_1479118188', -# positive_examples={'cars_positive_examples': image_file}).get_result() -# print(json.dumps(classifier, indent=2)) - -# response = service.delete_classifier(classifier_id='YOUR CLASSIFIER ID').get_result() -# print(json.dumps(response, indent=2)) - -classifiers = service.list_classifiers().get_result() -print(json.dumps(classifiers, indent=2)) - -#Core ml model example -# model_name = '{0}.mlmodel'.format(classifier_id) -# core_ml_model = service.get_core_ml_model(classifier_id).get_result() -# with open('/tmp/{0}'.format(model_name), 'wb') as fp: -# fp.write(core_ml_model.content) diff --git a/examples/visual_recognition_v4.py b/examples/visual_recognition_v4.py deleted file mode 100644 index 5febf8986..000000000 --- a/examples/visual_recognition_v4.py +++ /dev/null @@ -1,70 +0,0 @@ -import json -import os -from ibm_watson import VisualRecognitionV4 -from ibm_watson.visual_recognition_v4 import FileWithMetadata, TrainingDataObject, Location, AnalyzeEnums -from ibm_cloud_sdk_core.authenticators import IAMAuthenticator - -authenticator = IAMAuthenticator( - 'YOUR APIKEY') -service = VisualRecognitionV4( - '2018-03-19', - authenticator=authenticator) -service.set_service_url('https://api.us-south.visual-recognition.watson.cloud.ibm.com') - -# create a classifier -my_collection = service.create_collection( - name='', - description='testing for python' -).get_result() -collection_id = my_collection.get('collection_id') - -# add images -with open(os.path.join(os.path.dirname(__file__), '../resources/South_Africa_Luca_Galuzzi_2004.jpeg'), 'rb') as giraffe_info: - add_images_result = service.add_images( - collection_id, - images_file=[FileWithMetadata(giraffe_info)], - ).get_result() -print(json.dumps(add_images_result, indent=2)) -image_id = add_images_result.get('images')[0].get('image_id') - -# add image training data -training_data = service.add_image_training_data( - collection_id, - image_id, - objects=[ - TrainingDataObject(object='giraffe training data', - location=Location(64, 270, 755, 784)) - ]).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)) - -# training usage -training_usage = service.get_training_usage() -print(json.dumps(training_usage, indent=2)) - -# analyze -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: - analyze_images = service.analyze( - collection_ids=[collection_id], - features=[AnalyzeEnums.Features.OBJECTS.value], - images_file=[ - 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() - print(json.dumps(analyze_images, indent=2)) - -# delete collection -service.delete_collection(collection_id) diff --git a/ibm_watson/__init__.py b/ibm_watson/__init__.py index 105e04d40..aed80a796 100755 --- a/ibm_watson/__init__.py +++ b/ibm_watson/__init__.py @@ -18,17 +18,11 @@ from .assistant_v1 import AssistantV1 from .assistant_v2 import AssistantV2 from .language_translator_v3 import LanguageTranslatorV3 -from .natural_language_classifier_v1 import NaturalLanguageClassifierV1 from .natural_language_understanding_v1 import NaturalLanguageUnderstandingV1 -from .personality_insights_v3 import PersonalityInsightsV3 from .text_to_speech_v1 import TextToSpeechV1 -from .tone_analyzer_v3 import ToneAnalyzerV3 from .discovery_v1 import DiscoveryV1 from .discovery_v2 import DiscoveryV2 -from .compare_comply_v1 import CompareComplyV1 -from .visual_recognition_v3 import VisualRecognitionV3 from .version import __version__ from .common import get_sdk_headers from .speech_to_text_v1_adapter import SpeechToTextV1Adapter as SpeechToTextV1 from .text_to_speech_adapter_v1 import TextToSpeechV1Adapter as TextToSpeechV1 -from .visual_recognition_v4 import VisualRecognitionV4 diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index 13f764e60..bbdb45f5b 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2021. +# (C) Copyright IBM Corp. 2019, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 +# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -60,10 +60,10 @@ def __init__( Construct a new client for the Assistant service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2021-06-14`. + Specify dates in YYYY-MM-DD format. The current version is `2021-11-27`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md about initializing the authenticator of your choice. """ if version is None: @@ -5600,7 +5600,10 @@ def __init__(self) -> None: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill', 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe' ])) raise Exception(msg) @@ -5621,7 +5624,10 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodeOutputGeneric': 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent', 'DialogNodeOutputGenericDialogNodeOutputResponseTypeSearchSkill', 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer', - 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio', + 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe' ])) raise Exception(msg) @@ -5633,10 +5639,14 @@ def _from_dict(cls, _dict: Dict): @classmethod def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping = {} + mapping[ + 'audio'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio' mapping[ 'channel_transfer'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer' mapping[ 'connect_to_agent'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeConnectToAgent' + mapping[ + 'iframe'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe' mapping[ 'image'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage' mapping[ @@ -5649,6 +5659,8 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: 'text'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeText' mapping[ 'user_defined'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' + mapping[ + 'video'] = 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo' disc_value = _dict.get('response_type') if disc_value is None: raise ValueError( @@ -8003,21 +8015,17 @@ class OutputData(): **nodes_visited_details** is set to `true` in the message request. :attr List[LogMessage] log_messages: An array of up to 50 messages logged with the request. - :attr List[str] text: An array of responses to the user. :attr List[RuntimeResponseGeneric] generic: (optional) Output intended for any channel. It is the responsibility of the client application to implement the supported response types. """ # The set of defined properties for the class - _properties = frozenset([ - 'nodes_visited', 'nodes_visited_details', 'log_messages', 'text', - 'generic' - ]) + _properties = frozenset( + ['nodes_visited', 'nodes_visited_details', 'log_messages', 'generic']) def __init__(self, log_messages: List['LogMessage'], - text: List[str], *, nodes_visited: List[str] = None, nodes_visited_details: List['DialogNodeVisitedDetails'] = None, @@ -8028,7 +8036,6 @@ def __init__(self, :param List[LogMessage] log_messages: An array of up to 50 messages logged with the request. - :param List[str] text: An array of responses to the user. :param List[str] nodes_visited: (optional) An array of the nodes that were triggered to create the response, in the order in which they were visited. This information is useful for debugging and for tracing the path taken @@ -8045,7 +8052,6 @@ def __init__(self, self.nodes_visited = nodes_visited self.nodes_visited_details = nodes_visited_details self.log_messages = log_messages - self.text = text self.generic = generic for _key, _value in kwargs.items(): setattr(self, _key, _value) @@ -8069,11 +8075,6 @@ def from_dict(cls, _dict: Dict) -> 'OutputData': raise ValueError( 'Required property \'log_messages\' not present in OutputData JSON' ) - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in OutputData JSON') if 'generic' in _dict: args['generic'] = [ RuntimeResponseGeneric.from_dict(x) @@ -8100,8 +8101,6 @@ def to_dict(self) -> Dict: ] if hasattr(self, 'log_messages') and self.log_messages is not None: _dict['log_messages'] = [x.to_dict() for x in self.log_messages] - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text if hasattr(self, 'generic') and self.generic is not None: _dict['generic'] = [x.to_dict() for x in self.generic] for _key in [ @@ -8337,10 +8336,6 @@ class RuntimeEntity(): :attr str value: 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. - :attr dict metadata: (optional) **Deprecated.** Any metadata for the entity. - Beginning with the `2021-06-14` API version, the `metadata` property is no - longer returned. For information about system entities recognized in the user - input, see the `interpretation` property. :attr List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :attr RuntimeEntityInterpretation interpretation: (optional) An object @@ -8365,7 +8360,6 @@ def __init__(self, *, location: List[int] = None, confidence: float = None, - metadata: dict = None, groups: List['CaptureGroup'] = None, interpretation: 'RuntimeEntityInterpretation' = None, alternatives: List['RuntimeEntityAlternative'] = None, @@ -8380,11 +8374,6 @@ def __init__(self, input text. :param float confidence: (optional) A decimal percentage that represents Watson's confidence in the recognized entity. - :param dict metadata: (optional) **Deprecated.** Any metadata for the - entity. - Beginning with the `2021-06-14` API version, the `metadata` property is no - longer returned. For information about system entities recognized in the - user input, see the `interpretation` property. :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :param RuntimeEntityInterpretation interpretation: (optional) An object @@ -8408,7 +8397,6 @@ def __init__(self, self.location = location self.value = value self.confidence = confidence - self.metadata = metadata self.groups = groups self.interpretation = interpretation self.alternatives = alternatives @@ -8433,8 +8421,6 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': 'Required property \'value\' not present in RuntimeEntity JSON') if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') if 'groups' in _dict: args['groups'] = [ CaptureGroup.from_dict(x) for x in _dict.get('groups') @@ -8467,8 +8453,6 @@ def to_dict(self) -> Dict: _dict['value'] = self.value if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence - if hasattr(self, 'metadata') and self.metadata is not None: - _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: @@ -9090,7 +9074,10 @@ def __init__(self) -> None: 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe' ])) raise Exception(msg) @@ -9111,7 +9098,10 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent', 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe' ])) raise Exception(msg) @@ -9123,10 +9113,12 @@ def _from_dict(cls, _dict: Dict): @classmethod def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping = {} + mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' mapping[ 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' mapping[ 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' mapping[ @@ -9135,6 +9127,7 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' mapping[ 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' disc_value = _dict.get('response_type') if disc_value is None: raise ValueError( @@ -9674,7 +9667,7 @@ class Workspace(): :attr str description: (optional) The description of the workspace. This string cannot contain carriage return, newline, or tab characters. :attr str language: The language of the workspace. - :attr str workspace_id: The workspace ID of the workspace. + :attr str workspace_id: (optional) The workspace ID of the workspace. :attr List[DialogNode] dialog_nodes: (optional) An array of objects describing the dialog nodes in the workspace. :attr List[Counterexample] counterexamples: (optional) An array of objects @@ -9698,10 +9691,10 @@ class Workspace(): def __init__(self, name: str, language: str, - workspace_id: str, learning_opt_out: bool, *, description: str = None, + workspace_id: str = None, dialog_nodes: List['DialogNode'] = None, counterexamples: List['Counterexample'] = None, created: datetime = None, @@ -9718,7 +9711,6 @@ def __init__(self, :param str name: The name of the workspace. This string cannot contain carriage return, newline, or tab characters. :param str language: The language of the workspace. - :param str workspace_id: The workspace ID of the workspace. :param bool learning_opt_out: Whether training data from the workspace (including artifacts such as intents and entities) can be used by IBM for general service improvements. `true` indicates that workspace training data @@ -9771,10 +9763,6 @@ def from_dict(cls, _dict: Dict) -> 'Workspace': 'Required property \'language\' not present in Workspace JSON') if 'workspace_id' in _dict: args['workspace_id'] = _dict.get('workspace_id') - else: - raise ValueError( - 'Required property \'workspace_id\' not present in Workspace JSON' - ) if 'dialog_nodes' in _dict: args['dialog_nodes'] = [ DialogNode.from_dict(x) for x in _dict.get('dialog_nodes') @@ -9987,6 +9975,13 @@ class WorkspaceSystemSettings(): related to detection of irrelevant input. """ + # The set of defined properties for the class + _properties = frozenset([ + 'tooling', 'disambiguation', 'human_agent_assist', + 'spelling_suggestions', 'spelling_auto_correct', 'system_entities', + 'off_topic' + ]) + def __init__( self, *, @@ -9996,7 +9991,8 @@ def __init__( spelling_suggestions: bool = None, spelling_auto_correct: bool = None, system_entities: 'WorkspaceSystemSettingsSystemEntities' = None, - off_topic: 'WorkspaceSystemSettingsOffTopic' = None) -> None: + off_topic: 'WorkspaceSystemSettingsOffTopic' = None, + **kwargs) -> None: """ Initialize a WorkspaceSystemSettings object. @@ -10018,6 +10014,7 @@ def __init__( Workspace settings related to the behavior of system entities. :param WorkspaceSystemSettingsOffTopic off_topic: (optional) Workspace settings related to detection of irrelevant input. + :param **kwargs: (optional) Any additional properties. """ self.tooling = tooling self.disambiguation = disambiguation @@ -10026,6 +10023,8 @@ def __init__( self.spelling_auto_correct = spelling_auto_correct self.system_entities = system_entities self.off_topic = off_topic + for _key, _value in kwargs.items(): + setattr(self, _key, _value) @classmethod def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': @@ -10051,6 +10050,8 @@ def from_dict(cls, _dict: Dict) -> 'WorkspaceSystemSettings': if 'off_topic' in _dict: args['off_topic'] = WorkspaceSystemSettingsOffTopic.from_dict( _dict.get('off_topic')) + args.update( + {k: v for (k, v) in _dict.items() if k not in cls._properties}) return cls(**args) @classmethod @@ -10080,12 +10081,41 @@ def to_dict(self) -> Dict: _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() + for _key in [ + k for k in vars(self).keys() + if k not in WorkspaceSystemSettings._properties + ]: + if getattr(self, _key, None) is not None: + _dict[_key] = getattr(self, _key) return _dict def _to_dict(self): """Return a json dictionary representing this model.""" return self.to_dict() + def get_properties(self) -> Dict: + """Return a dictionary of arbitrary properties from this instance of WorkspaceSystemSettings""" + _dict = {} + + for _key in [ + k for k in vars(self).keys() + if k not in WorkspaceSystemSettings._properties + ]: + _dict[_key] = getattr(self, _key) + return _dict + + def set_properties(self, _dict: dict): + """Set a dictionary of arbitrary properties to this instance of WorkspaceSystemSettings""" + for _key in [ + k for k in vars(self).keys() + if k not in WorkspaceSystemSettings._properties + ]: + delattr(self, _key) + + for _key, _value in _dict.items(): + if _key not in WorkspaceSystemSettings._properties: + setattr(self, _key, _value) + def __str__(self) -> str: """Return a `str` version of this WorkspaceSystemSettings object.""" return json.dumps(self.to_dict(), indent=2) @@ -10410,6 +10440,143 @@ def __ne__(self, other: 'WorkspaceSystemSettingsTooling') -> bool: return not self == other +class DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio( + DialogNodeOutputGeneric): + """ + DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str source: The `https:` URL of the audio clip. + :attr str title: (optional) An optional title to show before the response. + :attr str description: (optional) An optional description to show with the + response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + :attr object channel_options: (optional) For internal use only. + :attr str alt_text: (optional) Descriptive text that can be used for screen + readers or other situations where the audio player cannot be seen. + """ + + def __init__(self, + response_type: str, + source: str, + *, + title: str = None, + description: str = None, + channels: List['ResponseGenericChannel'] = None, + channel_options: object = None, + alt_text: str = None) -> None: + """ + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. + :param object channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for + screen readers or other situations where the audio player cannot be seen. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.source = source + self.title = title + self.description = description + self.channels = channels + self.channel_options = channel_options + self.alt_text = alt_text + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio JSON' + ) + if 'source' in _dict: + args['source'] = _dict.get('source') + else: + raise ValueError( + 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + if 'channel_options' in _dict: + args['channel_options'] = _dict.get('channel_options') + if 'alt_text' in _dict: + args['alt_text'] = _dict.get('alt_text') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + if hasattr(self, + 'channel_options') and self.channel_options is not None: + _dict['channel_options'] = self.channel_options + if hasattr(self, 'alt_text') and self.alt_text is not None: + _dict['alt_text'] = self.alt_text + 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 DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio' + ) -> 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: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeAudio' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class DialogNodeOutputGenericDialogNodeOutputResponseTypeChannelTransfer( DialogNodeOutputGeneric): """ @@ -10666,21 +10833,23 @@ def __ne__( return not self == other -class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage( +class DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe( DialogNodeOutputGeneric): """ - DialogNodeOutputGenericDialogNodeOutputResponseTypeImage. + DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str source: The `https:` URL of the image. + :attr str source: The `https:` URL of the embeddable content. :attr str title: (optional) An optional title to show before the response. :attr str description: (optional) An optional description to show with the response. + :attr str image_url: (optional) The URL of an image that shows a preview of the + embedded content. :attr List[ResponseGenericChannel] channels: (optional) An array of objects - specifying channels for which the response is intended. - :attr str alt_text: (optional) Descriptive text that can be used for screen - readers or other situations where the image cannot be seen. + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. """ def __init__(self, @@ -10689,65 +10858,67 @@ def __init__(self, *, title: str = None, description: str = None, - channels: List['ResponseGenericChannel'] = None, - alt_text: str = None) -> None: + image_url: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: """ - Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object. + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :param str source: The `https:` URL of the image. + :param str source: The `https:` URL of the embeddable content. :param str title: (optional) An optional title to show before the response. :param str description: (optional) An optional description to show with the response. + :param str image_url: (optional) The URL of an image that shows a preview + of the embedded content. :param List[ResponseGenericChannel] channels: (optional) An array of - objects specifying channels for which the response is intended. - :param str alt_text: (optional) Descriptive text that can be used for - screen readers or other situations where the image cannot be seen. + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. """ # pylint: disable=super-init-not-called self.response_type = response_type self.source = source self.title = title self.description = description + self.image_url = image_url self.channels = channels - self.alt_text = alt_text @classmethod def from_dict( cls, _dict: Dict - ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage': - """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object from a json dictionary.""" + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe object from a json dictionary.""" args = {} if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: raise ValueError( - 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe JSON' ) if 'source' in _dict: args['source'] = _dict.get('source') else: raise ValueError( - 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' + 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe JSON' ) if 'title' in _dict: args['title'] = _dict.get('title') if 'description' in _dict: args['description'] = _dict.get('description') + if 'image_url' in _dict: + args['image_url'] = _dict.get('image_url') if 'channels' in _dict: args['channels'] = [ ResponseGenericChannel.from_dict(x) for x in _dict.get('channels') ] - if 'alt_text' in _dict: - args['alt_text'] = _dict.get('alt_text') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object from a json dictionary.""" + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -10761,10 +10932,10 @@ def to_dict(self) -> Dict: _dict['title'] = self.title if hasattr(self, 'description') and self.description is not None: _dict['description'] = self.description + if hasattr(self, 'image_url') and self.image_url is not None: + _dict['image_url'] = self.image_url if hasattr(self, 'channels') and self.channels is not None: _dict['channels'] = [x.to_dict() for x in self.channels] - if hasattr(self, 'alt_text') and self.alt_text is not None: - _dict['alt_text'] = self.alt_text return _dict def _to_dict(self): @@ -10772,11 +10943,11 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object.""" + """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe object.""" return json.dumps(self.to_dict(), indent=2) def __eq__( - self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage' + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe' ) -> bool: """Return `true` when self and other are equal, false otherwise.""" if not isinstance(other, self.__class__): @@ -10784,87 +10955,211 @@ def __eq__( return self.__dict__ == other.__dict__ def __ne__( - self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage' + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeIframe' ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class DialogNodeOutputGenericDialogNodeOutputResponseTypeOption( +class DialogNodeOutputGenericDialogNodeOutputResponseTypeImage( DialogNodeOutputGeneric): """ - DialogNodeOutputGenericDialogNodeOutputResponseTypeOption. + DialogNodeOutputGenericDialogNodeOutputResponseTypeImage. :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :attr str title: An optional title to show before the response. + :attr str source: The `https:` URL of the image. + :attr str title: (optional) An optional title to show before the response. :attr str description: (optional) An optional description to show with the response. - :attr str preference: (optional) The preferred type of control to display, if - supported by the channel. - :attr List[DialogNodeOutputOptionsElement] options: An array of objects - describing the options from which the user can choose. You can include up to 20 - options. :attr List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. + :attr str alt_text: (optional) Descriptive text that can be used for screen + readers or other situations where the image cannot be seen. """ def __init__(self, response_type: str, - title: str, - options: List['DialogNodeOutputOptionsElement'], + source: str, *, + title: str = None, description: str = None, - preference: str = None, - channels: List['ResponseGenericChannel'] = None) -> None: + channels: List['ResponseGenericChannel'] = None, + alt_text: str = None) -> None: """ - Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object. + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object. :param str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. - :param str title: An optional title to show before the response. - :param List[DialogNodeOutputOptionsElement] options: An array of objects - describing the options from which the user can choose. You can include up - to 20 options. + :param str source: The `https:` URL of the image. + :param str title: (optional) An optional title to show before the response. :param str description: (optional) An optional description to show with the response. - :param str preference: (optional) The preferred type of control to display, - if supported by the channel. :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. + :param str alt_text: (optional) Descriptive text that can be used for + screen readers or other situations where the image cannot be seen. """ # pylint: disable=super-init-not-called self.response_type = response_type + self.source = source self.title = title self.description = description - self.preference = preference - self.options = options self.channels = channels + self.alt_text = alt_text @classmethod def from_dict( cls, _dict: Dict - ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption': - """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object from a json dictionary.""" + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object from a json dictionary.""" args = {} if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: raise ValueError( - 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' ) - if 'title' in _dict: - args['title'] = _dict.get('title') + if 'source' in _dict: + args['source'] = _dict.get('source') else: raise ValueError( - 'Required property \'title\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' + 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeImage JSON' ) + if 'title' in _dict: + args['title'] = _dict.get('title') if 'description' in _dict: args['description'] = _dict.get('description') - if 'preference' in _dict: - args['preference'] = _dict.get('preference') - if 'options' in _dict: + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + if 'alt_text' in _dict: + args['alt_text'] = _dict.get('alt_text') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeImage 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + if hasattr(self, 'alt_text') and self.alt_text is not None: + _dict['alt_text'] = self.alt_text + 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 DialogNodeOutputGenericDialogNodeOutputResponseTypeImage object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage' + ) -> 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: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeImage' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DialogNodeOutputGenericDialogNodeOutputResponseTypeOption( + DialogNodeOutputGeneric): + """ + DialogNodeOutputGenericDialogNodeOutputResponseTypeOption. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str title: An optional title to show before the response. + :attr str description: (optional) An optional description to show with the + response. + :attr str preference: (optional) The preferred type of control to display, if + supported by the channel. + :attr List[DialogNodeOutputOptionsElement] options: An array of objects + describing the options from which the user can choose. You can include up to 20 + options. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. + """ + + def __init__(self, + response_type: str, + title: str, + options: List['DialogNodeOutputOptionsElement'], + *, + description: str = None, + preference: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: + """ + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str title: An optional title to show before the response. + :param List[DialogNodeOutputOptionsElement] options: An array of objects + describing the options from which the user can choose. You can include up + to 20 options. + :param str description: (optional) An optional description to show with the + response. + :param str preference: (optional) The preferred type of control to display, + if supported by the channel. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.title = title + self.description = description + self.preference = preference + self.options = options + self.channels = channels + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeOption': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeOption object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + else: + raise ValueError( + 'Required property \'title\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeOption JSON' + ) + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'preference' in _dict: + args['preference'] = _dict.get('preference') + if 'options' in _dict: args['options'] = [ DialogNodeOutputOptionsElement.from_dict(x) for x in _dict.get('options') @@ -11361,32 +11656,299 @@ def __init__(self, @classmethod def from_dict( - cls, _dict: Dict - ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined': - """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object from a json dictionary.""" + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' + ) + if 'user_defined' in _dict: + args['user_defined'] = _dict.get('user_defined') + else: + raise ValueError( + 'Required property \'user_defined\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' + ) + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'user_defined') and self.user_defined is not None: + _dict['user_defined'] = self.user_defined + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + 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 DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' + ) -> 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: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo( + DialogNodeOutputGeneric): + """ + DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str source: The `https:` URL of the video. + :attr str title: (optional) An optional title to show before the response. + :attr str description: (optional) An optional description to show with the + response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + :attr object channel_options: (optional) For internal use only. + :attr str alt_text: (optional) Descriptive text that can be used for screen + readers or other situations where the video cannot be seen. + """ + + def __init__(self, + response_type: str, + source: str, + *, + title: str = None, + description: str = None, + channels: List['ResponseGenericChannel'] = None, + channel_options: object = None, + alt_text: str = None) -> None: + """ + Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The `https:` URL of the video. + :param str title: (optional) An optional title to show before the response. + :param str description: (optional) An optional description to show with the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. + :param object channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for + screen readers or other situations where the video cannot be seen. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.source = source + self.title = title + self.description = description + self.channels = channels + self.channel_options = channel_options + self.alt_text = alt_text + + @classmethod + def from_dict( + cls, _dict: Dict + ) -> 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo': + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo JSON' + ) + if 'source' in _dict: + args['source'] = _dict.get('source') + else: + raise ValueError( + 'Required property \'source\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + if 'channel_options' in _dict: + args['channel_options'] = _dict.get('channel_options') + if 'alt_text' in _dict: + args['alt_text'] = _dict.get('alt_text') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + if hasattr(self, + 'channel_options') and self.channel_options is not None: + _dict['channel_options'] = self.channel_options + if hasattr(self, 'alt_text') and self.alt_text is not None: + _dict['alt_text'] = self.alt_text + 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 DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo' + ) -> 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: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeVideo' + ) -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeAudio. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str source: The `https:` URL of the audio clip. + :attr str title: (optional) The title or introductory text to show before the + response. + :attr str description: (optional) The description to show with the response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + :attr object channel_options: (optional) For internal use only. + :attr str alt_text: (optional) Descriptive text that can be used for screen + readers or other situations where the audio player cannot be seen. + """ + + def __init__(self, + response_type: str, + source: str, + *, + title: str = None, + description: str = None, + channels: List['ResponseGenericChannel'] = None, + channel_options: object = None, + alt_text: str = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) The title or introductory text to show before + the response. + :param str description: (optional) The description to show with the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. + :param object channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for + screen readers or other situations where the audio player cannot be seen. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.source = source + self.title = title + self.description = description + self.channels = channels + self.channel_options = channel_options + self.alt_text = alt_text + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeAudio': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" args = {} if 'response_type' in _dict: args['response_type'] = _dict.get('response_type') else: raise ValueError( - 'Required property \'response_type\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) - if 'user_defined' in _dict: - args['user_defined'] = _dict.get('user_defined') + if 'source' in _dict: + args['source'] = _dict.get('source') else: raise ValueError( - 'Required property \'user_defined\' not present in DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined JSON' + 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' ) + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') if 'channels' in _dict: args['channels'] = [ ResponseGenericChannel.from_dict(x) for x in _dict.get('channels') ] + if 'channel_options' in _dict: + args['channel_options'] = _dict.get('channel_options') + if 'alt_text' in _dict: + args['alt_text'] = _dict.get('alt_text') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object from a json dictionary.""" + """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -11394,10 +11956,19 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'response_type') and self.response_type is not None: _dict['response_type'] = self.response_type - if hasattr(self, 'user_defined') and self.user_defined is not None: - _dict['user_defined'] = self.user_defined + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description if hasattr(self, 'channels') and self.channels is not None: _dict['channels'] = [x.to_dict() for x in self.channels] + if hasattr(self, + 'channel_options') and self.channel_options is not None: + _dict['channel_options'] = self.channel_options + if hasattr(self, 'alt_text') and self.alt_text is not None: + _dict['alt_text'] = self.alt_text return _dict def _to_dict(self): @@ -11405,22 +11976,18 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined object.""" + """Return a `str` version of this RuntimeResponseGenericRuntimeResponseTypeAudio object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__( - self, - other: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' - ) -> bool: + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeAudio') -> 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: 'DialogNodeOutputGenericDialogNodeOutputResponseTypeUserDefined' - ) -> bool: + def __ne__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeAudio') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -11709,6 +12276,134 @@ def __ne__( return not self == other +class RuntimeResponseGenericRuntimeResponseTypeIframe(RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeIframe. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str source: The `https:` URL of the embeddable content. + :attr str title: (optional) The title or introductory text to show before the + response. + :attr str description: (optional) The description to show with the response. + :attr str image_url: (optional) The URL of an image that shows a preview of the + embedded content. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + """ + + def __init__(self, + response_type: str, + source: str, + *, + title: str = None, + description: str = None, + image_url: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The `https:` URL of the embeddable content. + :param str title: (optional) The title or introductory text to show before + the response. + :param str description: (optional) The description to show with the + response. + :param str image_url: (optional) The URL of an image that shows a preview + of the embedded content. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.source = source + self.title = title + self.description = description + self.image_url = image_url + self.channels = channels + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeIframe': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' + ) + if 'source' in _dict: + args['source'] = _dict.get('source') + else: + raise ValueError( + 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'image_url' in _dict: + args['image_url'] = _dict.get('image_url') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'image_url') and self.image_url is not None: + _dict['image_url'] = self.image_url + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + 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 RuntimeResponseGenericRuntimeResponseTypeIframe object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'RuntimeResponseGenericRuntimeResponseTypeIframe') -> 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: 'RuntimeResponseGenericRuntimeResponseTypeIframe') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeImage. @@ -11718,7 +12413,7 @@ class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): :attr str source: The `https:` URL of the image. :attr str title: (optional) The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the the response. + :attr str description: (optional) The description to show with the response. :attr List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If **channels** is present, the response is intended for a built-in integration and should not be @@ -11744,7 +12439,7 @@ def __init__(self, :param str source: The `https:` URL of the image. :param str title: (optional) The title or introductory text to show before the response. - :param str description: (optional) The description to show with the the + :param str description: (optional) The description to show with the response. :param List[ResponseGenericChannel] channels: (optional) An array of objects specifying channels for which the response is intended. If @@ -11842,7 +12537,7 @@ class RuntimeResponseGenericRuntimeResponseTypeOption(RuntimeResponseGeneric): :attr str response_type: The type of response returned by the dialog node. The specified response type must be supported by the client application or channel. :attr str title: The title or introductory text to show before the response. - :attr str description: (optional) The description to show with the the response. + :attr str description: (optional) The description to show with the response. :attr str preference: (optional) The preferred type of control to display. :attr List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. @@ -11870,7 +12565,7 @@ def __init__(self, response. :param List[DialogNodeOutputOptionsElement] options: An array of objects describing the options from which the user can choose. - :param str description: (optional) The description to show with the the + :param str description: (optional) The description to show with the response. :param str preference: (optional) The preferred type of control to display. :param List[ResponseGenericChannel] channels: (optional) An array of @@ -12397,3 +13092,138 @@ def __ne__( ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + + +class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeVideo. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str source: The `https:` URL of the video. + :attr str title: (optional) The title or introductory text to show before the + response. + :attr str description: (optional) The description to show with the response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + :attr object channel_options: (optional) For internal use only. + :attr str alt_text: (optional) Descriptive text that can be used for screen + readers or other situations where the video cannot be seen. + """ + + def __init__(self, + response_type: str, + source: str, + *, + title: str = None, + description: str = None, + channels: List['ResponseGenericChannel'] = None, + channel_options: object = None, + alt_text: str = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The `https:` URL of the video. + :param str title: (optional) The title or introductory text to show before + the response. + :param str description: (optional) The description to show with the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. + :param object channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for + screen readers or other situations where the video cannot be seen. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.source = source + self.title = title + self.description = description + self.channels = channels + self.channel_options = channel_options + self.alt_text = alt_text + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeVideo': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' + ) + if 'source' in _dict: + args['source'] = _dict.get('source') + else: + raise ValueError( + 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + if 'channel_options' in _dict: + args['channel_options'] = _dict.get('channel_options') + if 'alt_text' in _dict: + args['alt_text'] = _dict.get('alt_text') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + if hasattr(self, + 'channel_options') and self.channel_options is not None: + _dict['channel_options'] = self.channel_options + if hasattr(self, 'alt_text') and self.alt_text is not None: + _dict['alt_text'] = self.alt_text + 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 RuntimeResponseGenericRuntimeResponseTypeVideo object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeVideo') -> 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: 'RuntimeResponseGenericRuntimeResponseTypeVideo') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 12b60fd41..b9413e510 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2021. +# (C) Copyright IBM Corp. 2019, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 +# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 """ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your @@ -59,10 +59,10 @@ def __init__( Construct a new client for the Assistant service. :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2021-06-14`. + Specify dates in YYYY-MM-DD format. The current version is `2021-11-27`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md about initializing the authenticator of your choice. """ if version is None: @@ -1435,9 +1435,10 @@ def __ne__(self, other: 'DialogNodeOutputOptionsElementValue') -> bool: return not self == other -class DialogNodesVisited(): +class DialogNodeVisited(): """ - DialogNodesVisited. + An objects containing detailed diagnostic information about a dialog node that was + triggered during processing of the input message. :attr str dialog_node: (optional) A dialog node that was triggered during processing of the input message. @@ -1451,7 +1452,7 @@ def __init__(self, title: str = None, conditions: str = None) -> None: """ - Initialize a DialogNodesVisited object. + Initialize a DialogNodeVisited object. :param str dialog_node: (optional) A dialog node that was triggered during processing of the input message. @@ -1464,8 +1465,8 @@ def __init__(self, self.conditions = conditions @classmethod - def from_dict(cls, _dict: Dict) -> 'DialogNodesVisited': - """Initialize a DialogNodesVisited object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'DialogNodeVisited': + """Initialize a DialogNodeVisited object from a json dictionary.""" args = {} if 'dialog_node' in _dict: args['dialog_node'] = _dict.get('dialog_node') @@ -1477,7 +1478,7 @@ def from_dict(cls, _dict: Dict) -> 'DialogNodesVisited': @classmethod def _from_dict(cls, _dict): - """Initialize a DialogNodesVisited object from a json dictionary.""" + """Initialize a DialogNodeVisited object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -1496,16 +1497,16 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this DialogNodesVisited object.""" + """Return a `str` version of this DialogNodeVisited object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'DialogNodesVisited') -> bool: + def __eq__(self, other: 'DialogNodeVisited') -> 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: 'DialogNodesVisited') -> bool: + def __ne__(self, other: 'DialogNodeVisited') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other @@ -2051,29 +2052,37 @@ class MessageContext(): MessageContext. :attr MessageContextGlobal global_: (optional) Session context data that is - shared by all skills used by the Assistant. + shared by all skills used by the assistant. :attr dict skills: (optional) Information specific to particular skills used by the assistant. **Note:** Currently, only a single child property is supported, containing variables that apply to the dialog skill used by the assistant. + :attr object integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ def __init__(self, *, global_: 'MessageContextGlobal' = None, - skills: dict = None) -> None: + skills: dict = None, + integrations: object = None) -> None: """ Initialize a MessageContext object. :param MessageContextGlobal global_: (optional) Session context data that - is shared by all skills used by the Assistant. + is shared by all skills used by the assistant. :param dict skills: (optional) Information specific to particular skills used by the assistant. **Note:** Currently, only a single child property is supported, containing variables that apply to the dialog skill used by the assistant. + :param object integrations: (optional) An object containing context data + that is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ self.global_ = global_ self.skills = skills + self.integrations = integrations @classmethod def from_dict(cls, _dict: Dict) -> 'MessageContext': @@ -2087,6 +2096,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageContext': k: MessageContextSkill.from_dict(v) for k, v in _dict.get('skills').items() } + if 'integrations' in _dict: + args['integrations'] = _dict.get('integrations') return cls(**args) @classmethod @@ -2101,6 +2112,8 @@ def to_dict(self) -> Dict: _dict['global'] = self.global_.to_dict() if hasattr(self, 'skills') and self.skills is not None: _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations return _dict def _to_dict(self): @@ -2124,7 +2137,7 @@ def __ne__(self, other: 'MessageContext') -> bool: class MessageContextGlobal(): """ - Session context data that is shared by all skills used by the Assistant. + Session context data that is shared by all skills used by the assistant. :attr MessageContextGlobalSystem system: (optional) Built-in system properties that apply to all skills used by the assistant. @@ -2191,7 +2204,7 @@ def __ne__(self, other: 'MessageContextGlobal') -> bool: class MessageContextGlobalStateless(): """ - Session context data that is shared by all skills used by the Assistant. + Session context data that is shared by all skills used by the assistant. :attr MessageContextGlobalSystem system: (optional) Built-in system properties that apply to all skills used by the assistant. @@ -2306,6 +2319,7 @@ class MessageContextGlobalSystem(): of the subsequent message request to avoid disruptions if there are configuration changes during the conversation (such as a change to a skill the assistant uses). + :attr bool skip_user_input: (optional) For internal use only. """ def __init__(self, @@ -2316,7 +2330,8 @@ def __init__(self, locale: str = None, reference_time: str = None, session_start_time: str = None, - state: str = None) -> None: + state: str = None, + skip_user_input: bool = None) -> None: """ Initialize a MessageContextGlobalSystem object. @@ -2368,6 +2383,7 @@ def __init__(self, send it in the context of the subsequent message request to avoid disruptions if there are configuration changes during the conversation (such as a change to a skill the assistant uses). + :param bool skip_user_input: (optional) For internal use only. """ self.timezone = timezone self.user_id = user_id @@ -2376,6 +2392,7 @@ def __init__(self, self.reference_time = reference_time self.session_start_time = session_start_time self.state = state + self.skip_user_input = skip_user_input @classmethod def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': @@ -2395,6 +2412,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem': args['session_start_time'] = _dict.get('session_start_time') if 'state' in _dict: args['state'] = _dict.get('state') + if 'skip_user_input' in _dict: + args['skip_user_input'] = _dict.get('skip_user_input') return cls(**args) @classmethod @@ -2421,6 +2440,9 @@ def to_dict(self) -> Dict: _dict['session_start_time'] = self.session_start_time if hasattr(self, 'state') and self.state is not None: _dict['state'] = self.state + if hasattr(self, + 'skip_user_input') and self.skip_user_input is not None: + _dict['skip_user_input'] = self.skip_user_input return _dict def _to_dict(self): @@ -2469,7 +2491,7 @@ class LocaleEnum(str, Enum): class MessageContextSkill(): """ - Contains information specific to a particular skill used by the Assistant. The + Contains information specific to a particular skill used by the assistant. The property name must be the same as the name of the skill (for example, `main skill`). :attr dict user_defined: (optional) Arbitrary variables that can be read and @@ -2641,29 +2663,37 @@ class MessageContextStateless(): MessageContextStateless. :attr MessageContextGlobalStateless global_: (optional) Session context data - that is shared by all skills used by the Assistant. + that is shared by all skills used by the assistant. :attr dict skills: (optional) Information specific to particular skills used by the assistant. **Note:** Currently, only a single child property is supported, containing variables that apply to the dialog skill used by the assistant. + :attr object integrations: (optional) An object containing context data that is + specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ def __init__(self, *, global_: 'MessageContextGlobalStateless' = None, - skills: dict = None) -> None: + skills: dict = None, + integrations: object = None) -> None: """ Initialize a MessageContextStateless object. :param MessageContextGlobalStateless global_: (optional) Session context - data that is shared by all skills used by the Assistant. + data that is shared by all skills used by the assistant. :param dict skills: (optional) Information specific to particular skills used by the assistant. **Note:** Currently, only a single child property is supported, containing variables that apply to the dialog skill used by the assistant. + :param object integrations: (optional) An object containing context data + that is specific to particular integrations. For more information, see the + [documentation](https://cloud.ibm.com/docs/assistant?topic=assistant-dialog-integrations). """ self.global_ = global_ self.skills = skills + self.integrations = integrations @classmethod def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': @@ -2677,6 +2707,8 @@ def from_dict(cls, _dict: Dict) -> 'MessageContextStateless': k: MessageContextSkill.from_dict(v) for k, v in _dict.get('skills').items() } + if 'integrations' in _dict: + args['integrations'] = _dict.get('integrations') return cls(**args) @classmethod @@ -2691,6 +2723,8 @@ def to_dict(self) -> Dict: _dict['global'] = self.global_.to_dict() if hasattr(self, 'skills') and self.skills is not None: _dict['skills'] = {k: v.to_dict() for k, v in self.skills.items()} + if hasattr(self, 'integrations') and self.integrations is not None: + _dict['integrations'] = self.integrations return _dict def _to_dict(self): @@ -2731,6 +2765,10 @@ class MessageInput(): the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. :attr str suggestion_id: (optional) For internal use only. + :attr List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. + **Note:** Attachments are not processed by the assistant itself, but can be sent + to external services by webhooks. :attr MessageInputOptions options: (optional) Optional properties that control how the assistant responds. """ @@ -2742,6 +2780,7 @@ def __init__(self, intents: List['RuntimeIntent'] = None, entities: List['RuntimeEntity'] = None, suggestion_id: str = None, + attachments: List['MessageInputAttachment'] = None, options: 'MessageInputOptions' = None) -> None: """ Initialize a MessageInput object. @@ -2763,6 +2802,10 @@ def __init__(self, continue using those entities rather than detecting entities in the new input. :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. + **Note:** Attachments are not processed by the assistant itself, but can be + sent to external services by webhooks. :param MessageInputOptions options: (optional) Optional properties that control how the assistant responds. """ @@ -2771,6 +2814,7 @@ def __init__(self, self.intents = intents self.entities = entities self.suggestion_id = suggestion_id + self.attachments = attachments self.options = options @classmethod @@ -2791,6 +2835,11 @@ def from_dict(cls, _dict: Dict) -> 'MessageInput': ] if 'suggestion_id' in _dict: args['suggestion_id'] = _dict.get('suggestion_id') + if 'attachments' in _dict: + args['attachments'] = [ + MessageInputAttachment.from_dict(x) + for x in _dict.get('attachments') + ] if 'options' in _dict: args['options'] = MessageInputOptions.from_dict( _dict.get('options')) @@ -2814,6 +2863,8 @@ def to_dict(self) -> Dict: _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + _dict['attachments'] = [x.to_dict() for x in self.attachments] if hasattr(self, 'options') and self.options is not None: _dict['options'] = self.options.to_dict() return _dict @@ -2849,6 +2900,73 @@ class MessageTypeEnum(str, Enum): SEARCH = 'search' +class MessageInputAttachment(): + """ + A reference to a media file to be sent as an attachment with the message. + + :attr str url: The URL of the media file. + :attr str media_type: (optional) The media content type (such as a MIME type) of + the attachment. + """ + + def __init__(self, url: str, *, media_type: str = None) -> None: + """ + Initialize a MessageInputAttachment object. + + :param str url: The URL of the media file. + :param str media_type: (optional) The media content type (such as a MIME + type) of the attachment. + """ + self.url = url + self.media_type = media_type + + @classmethod + def from_dict(cls, _dict: Dict) -> 'MessageInputAttachment': + """Initialize a MessageInputAttachment object from a json dictionary.""" + args = {} + if 'url' in _dict: + args['url'] = _dict.get('url') + else: + raise ValueError( + 'Required property \'url\' not present in MessageInputAttachment JSON' + ) + if 'media_type' in _dict: + args['media_type'] = _dict.get('media_type') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a MessageInputAttachment 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, 'url') and self.url is not None: + _dict['url'] = self.url + if hasattr(self, 'media_type') and self.media_type is not None: + _dict['media_type'] = self.media_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 MessageInputAttachment object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'MessageInputAttachment') -> 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: 'MessageInputAttachment') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class MessageInputOptions(): """ Optional properties that control how the assistant responds. @@ -3180,6 +3298,10 @@ class MessageInputStateless(): the message. Include entities from the previous response to continue using those entities rather than detecting entities in the new input. :attr str suggestion_id: (optional) For internal use only. + :attr List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. + **Note:** Attachments are not processed by the assistant itself, but can be sent + to external services by webhooks. :attr MessageInputOptionsStateless options: (optional) Optional properties that control how the assistant responds. """ @@ -3191,6 +3313,7 @@ def __init__(self, intents: List['RuntimeIntent'] = None, entities: List['RuntimeEntity'] = None, suggestion_id: str = None, + attachments: List['MessageInputAttachment'] = None, options: 'MessageInputOptionsStateless' = None) -> None: """ Initialize a MessageInputStateless object. @@ -3212,6 +3335,10 @@ def __init__(self, continue using those entities rather than detecting entities in the new input. :param str suggestion_id: (optional) For internal use only. + :param List[MessageInputAttachment] attachments: (optional) An array of + multimedia attachments to be sent with the message. + **Note:** Attachments are not processed by the assistant itself, but can be + sent to external services by webhooks. :param MessageInputOptionsStateless options: (optional) Optional properties that control how the assistant responds. """ @@ -3220,6 +3347,7 @@ def __init__(self, self.intents = intents self.entities = entities self.suggestion_id = suggestion_id + self.attachments = attachments self.options = options @classmethod @@ -3240,6 +3368,11 @@ def from_dict(cls, _dict: Dict) -> 'MessageInputStateless': ] if 'suggestion_id' in _dict: args['suggestion_id'] = _dict.get('suggestion_id') + if 'attachments' in _dict: + args['attachments'] = [ + MessageInputAttachment.from_dict(x) + for x in _dict.get('attachments') + ] if 'options' in _dict: args['options'] = MessageInputOptionsStateless.from_dict( _dict.get('options')) @@ -3263,6 +3396,8 @@ def to_dict(self) -> Dict: _dict['entities'] = [x.to_dict() for x in self.entities] if hasattr(self, 'suggestion_id') and self.suggestion_id is not None: _dict['suggestion_id'] = self.suggestion_id + if hasattr(self, 'attachments') and self.attachments is not None: + _dict['attachments'] = [x.to_dict() for x in self.attachments] if hasattr(self, 'options') and self.options is not None: _dict['options'] = self.options.to_dict() return _dict @@ -3435,36 +3570,36 @@ class MessageOutputDebug(): """ Additional detailed information about a message response and how it was generated. - :attr List[DialogNodesVisited] nodes_visited: (optional) An array of objects - containing detailed diagnostic information about the nodes that were triggered - during processing of the input message. + :attr List[DialogNodeVisited] nodes_visited: (optional) An array of objects + containing detailed diagnostic information about dialog nodes that were + triggered during processing of the input message. :attr List[DialogLogMessage] log_messages: (optional) An array of up to 50 messages logged with the request. :attr bool branch_exited: (optional) Assistant sets this to true when this message response concludes or interrupts a dialog. :attr str branch_exited_reason: (optional) When `branch_exited` is set to `true` - by the Assistant, the `branch_exited_reason` specifies whether the dialog + by the assistant, the `branch_exited_reason` specifies whether the dialog completed by itself or got interrupted. """ def __init__(self, *, - nodes_visited: List['DialogNodesVisited'] = None, + nodes_visited: List['DialogNodeVisited'] = None, log_messages: List['DialogLogMessage'] = None, branch_exited: bool = None, branch_exited_reason: str = None) -> None: """ Initialize a MessageOutputDebug object. - :param List[DialogNodesVisited] nodes_visited: (optional) An array of - objects containing detailed diagnostic information about the nodes that + :param List[DialogNodeVisited] nodes_visited: (optional) An array of + objects containing detailed diagnostic information about dialog nodes that were triggered during processing of the input message. :param List[DialogLogMessage] log_messages: (optional) An array of up to 50 messages logged with the request. :param bool branch_exited: (optional) Assistant sets this to true when this message response concludes or interrupts a dialog. :param str branch_exited_reason: (optional) When `branch_exited` is set to - `true` by the Assistant, the `branch_exited_reason` specifies whether the + `true` by the assistant, the `branch_exited_reason` specifies whether the dialog completed by itself or got interrupted. """ self.nodes_visited = nodes_visited @@ -3478,7 +3613,7 @@ def from_dict(cls, _dict: Dict) -> 'MessageOutputDebug': args = {} if 'nodes_visited' in _dict: args['nodes_visited'] = [ - DialogNodesVisited.from_dict(x) + DialogNodeVisited.from_dict(x) for x in _dict.get('nodes_visited') ] if 'log_messages' in _dict: @@ -3530,7 +3665,7 @@ def __ne__(self, other: 'MessageOutputDebug') -> bool: class BranchExitedReasonEnum(str, Enum): """ - When `branch_exited` is set to `true` by the Assistant, the `branch_exited_reason` + When `branch_exited` is set to `true` by the assistant, the `branch_exited_reason` specifies whether the dialog completed by itself or got interrupted. """ COMPLETED = 'completed' @@ -4001,10 +4136,6 @@ class RuntimeEntity(): value. :attr float confidence: (optional) A decimal percentage that represents Watson's confidence in the recognized entity. - :attr dict metadata: (optional) **Deprecated.** Any metadata for the entity. - Beginning with the `2021-06-14` API version, the `metadata` property is no - longer returned. For information about system entities recognized in the user - input, see the `interpretation` property. :attr List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :attr RuntimeEntityInterpretation interpretation: (optional) An object @@ -4031,7 +4162,6 @@ def __init__(self, *, location: List[int] = None, confidence: float = None, - metadata: dict = None, groups: List['CaptureGroup'] = None, interpretation: 'RuntimeEntityInterpretation' = None, alternatives: List['RuntimeEntityAlternative'] = None, @@ -4047,11 +4177,6 @@ def __init__(self, input text. :param float confidence: (optional) A decimal percentage that represents Watson's confidence in the recognized entity. - :param dict metadata: (optional) **Deprecated.** Any metadata for the - entity. - Beginning with the `2021-06-14` API version, the `metadata` property is no - longer returned. For information about system entities recognized in the - user input, see the `interpretation` property. :param List[CaptureGroup] groups: (optional) The recognized capture groups for the entity, as defined by the entity pattern. :param RuntimeEntityInterpretation interpretation: (optional) An object @@ -4077,7 +4202,6 @@ def __init__(self, self.location = location self.value = value self.confidence = confidence - self.metadata = metadata self.groups = groups self.interpretation = interpretation self.alternatives = alternatives @@ -4102,8 +4226,6 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeEntity': 'Required property \'value\' not present in RuntimeEntity JSON') if 'confidence' in _dict: args['confidence'] = _dict.get('confidence') - if 'metadata' in _dict: - args['metadata'] = _dict.get('metadata') if 'groups' in _dict: args['groups'] = [ CaptureGroup.from_dict(x) for x in _dict.get('groups') @@ -4136,8 +4258,6 @@ def to_dict(self) -> Dict: _dict['value'] = self.value if hasattr(self, 'confidence') and self.confidence is not None: _dict['confidence'] = self.confidence - if hasattr(self, 'metadata') and self.metadata is not None: - _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: @@ -4760,7 +4880,10 @@ def __init__(self) -> None: 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe' ])) raise Exception(msg) @@ -4782,7 +4905,10 @@ def from_dict(cls, _dict: Dict) -> 'RuntimeResponseGeneric': 'RuntimeResponseGenericRuntimeResponseTypeSuggestion', 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer', 'RuntimeResponseGenericRuntimeResponseTypeSearch', - 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + 'RuntimeResponseGenericRuntimeResponseTypeUserDefined', + 'RuntimeResponseGenericRuntimeResponseTypeVideo', + 'RuntimeResponseGenericRuntimeResponseTypeAudio', + 'RuntimeResponseGenericRuntimeResponseTypeIframe' ])) raise Exception(msg) @@ -4794,10 +4920,12 @@ def _from_dict(cls, _dict: Dict): @classmethod def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping = {} + mapping['audio'] = 'RuntimeResponseGenericRuntimeResponseTypeAudio' mapping[ 'channel_transfer'] = 'RuntimeResponseGenericRuntimeResponseTypeChannelTransfer' mapping[ 'connect_to_agent'] = 'RuntimeResponseGenericRuntimeResponseTypeConnectToAgent' + mapping['iframe'] = 'RuntimeResponseGenericRuntimeResponseTypeIframe' mapping['image'] = 'RuntimeResponseGenericRuntimeResponseTypeImage' mapping['option'] = 'RuntimeResponseGenericRuntimeResponseTypeOption' mapping[ @@ -4807,6 +4935,7 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping['text'] = 'RuntimeResponseGenericRuntimeResponseTypeText' mapping[ 'user_defined'] = 'RuntimeResponseGenericRuntimeResponseTypeUserDefined' + mapping['video'] = 'RuntimeResponseGenericRuntimeResponseTypeVideo' disc_value = _dict.get('response_type') if disc_value is None: raise ValueError( @@ -5629,6 +5758,141 @@ def __ne__(self, other: 'LogMessageSourceStep') -> bool: return not self == other +class RuntimeResponseGenericRuntimeResponseTypeAudio(RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeAudio. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str source: The `https:` URL of the audio clip. + :attr str title: (optional) The title or introductory text to show before the + response. + :attr str description: (optional) The description to show with the the response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + :attr object channel_options: (optional) For internal use only. + :attr str alt_text: (optional) Descriptive text that can be used for screen + readers or other situations where the audio player cannot be seen. + """ + + def __init__(self, + response_type: str, + source: str, + *, + title: str = None, + description: str = None, + channels: List['ResponseGenericChannel'] = None, + channel_options: object = None, + alt_text: str = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The `https:` URL of the audio clip. + :param str title: (optional) The title or introductory text to show before + the response. + :param str description: (optional) The description to show with the the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. + :param object channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for + screen readers or other situations where the audio player cannot be seen. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.source = source + self.title = title + self.description = description + self.channels = channels + self.channel_options = channel_options + self.alt_text = alt_text + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeAudio': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' + ) + if 'source' in _dict: + args['source'] = _dict.get('source') + else: + raise ValueError( + 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeAudio JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + if 'channel_options' in _dict: + args['channel_options'] = _dict.get('channel_options') + if 'alt_text' in _dict: + args['alt_text'] = _dict.get('alt_text') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeAudio 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + if hasattr(self, + 'channel_options') and self.channel_options is not None: + _dict['channel_options'] = self.channel_options + if hasattr(self, 'alt_text') and self.alt_text is not None: + _dict['alt_text'] = self.alt_text + 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 RuntimeResponseGenericRuntimeResponseTypeAudio object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeAudio') -> 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: 'RuntimeResponseGenericRuntimeResponseTypeAudio') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuntimeResponseGenericRuntimeResponseTypeChannelTransfer( RuntimeResponseGeneric): """ @@ -5901,6 +6165,134 @@ def __ne__( return not self == other +class RuntimeResponseGenericRuntimeResponseTypeIframe(RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeIframe. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str source: The `https:` URL of the embeddable content. + :attr str title: (optional) The title or introductory text to show before the + response. + :attr str description: (optional) The description to show with the the response. + :attr str image_url: (optional) The URL of an image that shows a preview of the + embedded content. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + """ + + def __init__(self, + response_type: str, + source: str, + *, + title: str = None, + description: str = None, + image_url: str = None, + channels: List['ResponseGenericChannel'] = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The `https:` URL of the embeddable content. + :param str title: (optional) The title or introductory text to show before + the response. + :param str description: (optional) The description to show with the the + response. + :param str image_url: (optional) The URL of an image that shows a preview + of the embedded content. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.source = source + self.title = title + self.description = description + self.image_url = image_url + self.channels = channels + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeIframe': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' + ) + if 'source' in _dict: + args['source'] = _dict.get('source') + else: + raise ValueError( + 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeIframe JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'image_url' in _dict: + args['image_url'] = _dict.get('image_url') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeIframe 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'image_url') and self.image_url is not None: + _dict['image_url'] = self.image_url + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + 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 RuntimeResponseGenericRuntimeResponseTypeIframe object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__( + self, + other: 'RuntimeResponseGenericRuntimeResponseTypeIframe') -> 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: 'RuntimeResponseGenericRuntimeResponseTypeIframe') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class RuntimeResponseGenericRuntimeResponseTypeImage(RuntimeResponseGeneric): """ RuntimeResponseGenericRuntimeResponseTypeImage. @@ -6730,3 +7122,138 @@ def __ne__( ) -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other + + +class RuntimeResponseGenericRuntimeResponseTypeVideo(RuntimeResponseGeneric): + """ + RuntimeResponseGenericRuntimeResponseTypeVideo. + + :attr str response_type: The type of response returned by the dialog node. The + specified response type must be supported by the client application or channel. + :attr str source: The `https:` URL of the video. + :attr str title: (optional) The title or introductory text to show before the + response. + :attr str description: (optional) The description to show with the the response. + :attr List[ResponseGenericChannel] channels: (optional) An array of objects + specifying channels for which the response is intended. If **channels** is + present, the response is intended for a built-in integration and should not be + handled by an API client. + :attr object channel_options: (optional) For internal use only. + :attr str alt_text: (optional) Descriptive text that can be used for screen + readers or other situations where the video cannot be seen. + """ + + def __init__(self, + response_type: str, + source: str, + *, + title: str = None, + description: str = None, + channels: List['ResponseGenericChannel'] = None, + channel_options: object = None, + alt_text: str = None) -> None: + """ + Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object. + + :param str response_type: The type of response returned by the dialog node. + The specified response type must be supported by the client application or + channel. + :param str source: The `https:` URL of the video. + :param str title: (optional) The title or introductory text to show before + the response. + :param str description: (optional) The description to show with the the + response. + :param List[ResponseGenericChannel] channels: (optional) An array of + objects specifying channels for which the response is intended. If + **channels** is present, the response is intended for a built-in + integration and should not be handled by an API client. + :param object channel_options: (optional) For internal use only. + :param str alt_text: (optional) Descriptive text that can be used for + screen readers or other situations where the video cannot be seen. + """ + # pylint: disable=super-init-not-called + self.response_type = response_type + self.source = source + self.title = title + self.description = description + self.channels = channels + self.channel_options = channel_options + self.alt_text = alt_text + + @classmethod + def from_dict( + cls, + _dict: Dict) -> 'RuntimeResponseGenericRuntimeResponseTypeVideo': + """Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo object from a json dictionary.""" + args = {} + if 'response_type' in _dict: + args['response_type'] = _dict.get('response_type') + else: + raise ValueError( + 'Required property \'response_type\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' + ) + if 'source' in _dict: + args['source'] = _dict.get('source') + else: + raise ValueError( + 'Required property \'source\' not present in RuntimeResponseGenericRuntimeResponseTypeVideo JSON' + ) + if 'title' in _dict: + args['title'] = _dict.get('title') + if 'description' in _dict: + args['description'] = _dict.get('description') + if 'channels' in _dict: + args['channels'] = [ + ResponseGenericChannel.from_dict(x) + for x in _dict.get('channels') + ] + if 'channel_options' in _dict: + args['channel_options'] = _dict.get('channel_options') + if 'alt_text' in _dict: + args['alt_text'] = _dict.get('alt_text') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RuntimeResponseGenericRuntimeResponseTypeVideo 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, 'response_type') and self.response_type is not None: + _dict['response_type'] = self.response_type + if hasattr(self, 'source') and self.source is not None: + _dict['source'] = self.source + if hasattr(self, 'title') and self.title is not None: + _dict['title'] = self.title + if hasattr(self, 'description') and self.description is not None: + _dict['description'] = self.description + if hasattr(self, 'channels') and self.channels is not None: + _dict['channels'] = [x.to_dict() for x in self.channels] + if hasattr(self, + 'channel_options') and self.channel_options is not None: + _dict['channel_options'] = self.channel_options + if hasattr(self, 'alt_text') and self.alt_text is not None: + _dict['alt_text'] = self.alt_text + 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 RuntimeResponseGenericRuntimeResponseTypeVideo object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, + other: 'RuntimeResponseGenericRuntimeResponseTypeVideo') -> 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: 'RuntimeResponseGenericRuntimeResponseTypeVideo') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other diff --git a/ibm_watson/compare_comply_v1.py b/ibm_watson/compare_comply_v1.py deleted file mode 100644 index 1518ea731..000000000 --- a/ibm_watson/compare_comply_v1.py +++ /dev/null @@ -1,6877 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2019, 2021. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 -""" -IBM Watson™ Compare and Comply is discontinued. Existing instances are supported -until 30 November 2021, but as of 1 December 2020, you can't create instances. Any -instance that exists on 30 November 2021 will be deleted. Consider migrating to Watson -Discovery Premium on IBM Cloud for your Compare and Comply use cases. To start the -migration process, visit -[https://ibm.biz/contact-wdc-premium](https://ibm.biz/contact-wdc-premium). -{: deprecated} -Compare and Comply analyzes governing documents to provide details about critical aspects -of the documents. - -API Version: 1.0 -See: https://cloud.ibm.com/docs/compare-comply?topic=compare-comply-about -""" - -from datetime import datetime -from enum import Enum -from typing import BinaryIO, Dict, List -import json - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import convert_model, datetime_to_string, string_to_datetime - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class CompareComplyV1(BaseService): - """The Compare Comply V1 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.compare-comply.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'compare_comply' - - def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Compare Comply service. - - :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2018-10-15`. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md - about initializing the authenticator of your choice. - """ - print( - 'warning: On 30 November 2021, Compare and Comply will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk#compare-and-comply-deprecation.' - ) - if version is None: - raise ValueError('version must be provided') - - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.version = version - self.configure_service(service_name) - - ######################### - # HTML conversion - ######################### - - def convert_to_html(self, - file: BinaryIO, - *, - file_content_type: str = None, - model: str = None, - **kwargs) -> DetailedResponse: - """ - Convert document to HTML. - - Converts a document to HTML. - - :param BinaryIO file: The document to convert. - :param str file_content_type: (optional) The content type of file. - :param str model: (optional) The analysis model to be used by the service. - For the **Element classification** and **Compare two documents** methods, - the default is `contracts`. For the **Extract tables** method, the default - is `tables`. These defaults apply to the standalone methods as well as to - the methods' use in batch-processing requests. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `HTMLReturn` object - """ - - if file is None: - raise ValueError('file must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='convert_to_html') - headers.update(sdk_headers) - - params = {'version': self.version, 'model': model} - - form_data = [] - form_data.append(('file', (None, file, file_content_type or - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/html_conversion' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - ######################### - # Element classification - ######################### - - def classify_elements(self, - file: BinaryIO, - *, - file_content_type: str = None, - model: str = None, - **kwargs) -> DetailedResponse: - """ - Classify the elements of a document. - - Analyzes the structural and semantic elements of a document. - - :param BinaryIO file: The document to classify. - :param str file_content_type: (optional) The content type of file. - :param str model: (optional) The analysis model to be used by the service. - For the **Element classification** and **Compare two documents** methods, - the default is `contracts`. For the **Extract tables** method, the default - is `tables`. These defaults apply to the standalone methods as well as to - the methods' use in batch-processing requests. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ClassifyReturn` object - """ - - if file is None: - raise ValueError('file must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='classify_elements') - headers.update(sdk_headers) - - params = {'version': self.version, 'model': model} - - form_data = [] - form_data.append(('file', (None, file, file_content_type or - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/element_classification' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - ######################### - # Tables - ######################### - - def extract_tables(self, - file: BinaryIO, - *, - file_content_type: str = None, - model: str = None, - **kwargs) -> DetailedResponse: - """ - Extract a document's tables. - - Analyzes the tables in a document. - - :param BinaryIO file: The document on which to run table extraction. - :param str file_content_type: (optional) The content type of file. - :param str model: (optional) The analysis model to be used by the service. - For the **Element classification** and **Compare two documents** methods, - the default is `contracts`. For the **Extract tables** method, the default - is `tables`. These defaults apply to the standalone methods as well as to - the methods' use in batch-processing requests. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TableReturn` object - """ - - if file is None: - raise ValueError('file must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='extract_tables') - headers.update(sdk_headers) - - params = {'version': self.version, 'model': model} - - form_data = [] - form_data.append(('file', (None, file, file_content_type or - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/tables' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - ######################### - # Comparison - ######################### - - def compare_documents(self, - file_1: BinaryIO, - file_2: BinaryIO, - *, - file_1_content_type: str = None, - file_2_content_type: str = None, - file_1_label: str = None, - file_2_label: str = None, - model: str = None, - **kwargs) -> DetailedResponse: - """ - Compare two documents. - - Compares two input documents. Documents must be in the same format. - - :param BinaryIO file_1: The first document to compare. - :param BinaryIO file_2: The second document to compare. - :param str file_1_content_type: (optional) The content type of file_1. - :param str file_2_content_type: (optional) The content type of file_2. - :param str file_1_label: (optional) A text label for the first document. - :param str file_2_label: (optional) A text label for the second document. - :param str model: (optional) The analysis model to be used by the service. - For the **Element classification** and **Compare two documents** methods, - the default is `contracts`. For the **Extract tables** method, the default - is `tables`. These defaults apply to the standalone methods as well as to - the methods' use in batch-processing requests. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CompareReturn` object - """ - - if file_1 is None: - raise ValueError('file_1 must be provided') - if file_2 is None: - raise ValueError('file_2 must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='compare_documents') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'file_1_label': file_1_label, - 'file_2_label': file_2_label, - 'model': model - } - - form_data = [] - form_data.append(('file_1', (None, file_1, file_1_content_type or - 'application/octet-stream'))) - form_data.append(('file_2', (None, file_2, file_2_content_type or - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/comparison' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - ######################### - # Feedback - ######################### - - def add_feedback(self, - feedback_data: 'FeedbackDataInput', - *, - user_id: str = None, - comment: str = None, - **kwargs) -> DetailedResponse: - """ - Add feedback. - - Adds feedback in the form of _labels_ from a subject-matter expert (SME) to a - governing document. - **Important:** Feedback is not immediately incorporated into the training model, - nor is it guaranteed to be incorporated at a later date. Instead, submitted - feedback is used to suggest future updates to the training model. - - :param FeedbackDataInput feedback_data: Feedback data for submission. - :param str user_id: (optional) An optional string identifying the user. - :param str comment: (optional) An optional comment on or description of the - feedback. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `FeedbackReturn` object - """ - - if feedback_data is None: - raise ValueError('feedback_data must be provided') - feedback_data = convert_model(feedback_data) - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='add_feedback') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'feedback_data': feedback_data, - 'user_id': user_id, - 'comment': comment - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/feedback' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def list_feedback(self, - *, - feedback_type: str = None, - document_title: str = None, - model_id: str = None, - model_version: str = None, - category_removed: str = None, - category_added: str = None, - category_not_changed: str = None, - type_removed: str = None, - type_added: str = None, - type_not_changed: str = None, - page_limit: int = None, - cursor: str = None, - sort: str = None, - include_total: bool = None, - **kwargs) -> DetailedResponse: - """ - List the feedback in a document. - - Lists the feedback in a document. - - :param str feedback_type: (optional) An optional string that filters the - output to include only feedback with the specified feedback type. The only - permitted value is `element_classification`. - :param str document_title: (optional) An optional string that filters the - output to include only feedback from the document with the specified - `document_title`. - :param str model_id: (optional) An optional string that filters the output - to include only feedback with the specified `model_id`. The only permitted - value is `contracts`. - :param str model_version: (optional) An optional string that filters the - output to include only feedback with the specified `model_version`. - :param str category_removed: (optional) An optional string in the form of a - comma-separated list of categories. If it is specified, the service filters - the output to include only feedback that has at least one category from the - list removed. - :param str category_added: (optional) An optional string in the form of a - comma-separated list of categories. If this is specified, the service - filters the output to include only feedback that has at least one category - from the list added. - :param str category_not_changed: (optional) An optional string in the form - of a comma-separated list of categories. If this is specified, the service - filters the output to include only feedback that has at least one category - from the list unchanged. - :param str type_removed: (optional) An optional string of comma-separated - `nature`:`party` pairs. If this is specified, the service filters the - output to include only feedback that has at least one `nature`:`party` pair - from the list removed. - :param str type_added: (optional) An optional string of comma-separated - `nature`:`party` pairs. If this is specified, the service filters the - output to include only feedback that has at least one `nature`:`party` pair - from the list removed. - :param str type_not_changed: (optional) An optional string of - comma-separated `nature`:`party` pairs. If this is specified, the service - filters the output to include only feedback that has at least one - `nature`:`party` pair from the list unchanged. - :param int page_limit: (optional) An optional integer specifying the number - of documents that you want the service to return. - :param str cursor: (optional) An optional string that returns the set of - documents after the previous set. Use this parameter with the `page_limit` - parameter. - :param str sort: (optional) An optional comma-separated list of fields in - the document to sort on. You can optionally specify the sort direction by - prefixing the value of the field with `-` for descending order or `+` for - ascending order (the default). Currently permitted sorting fields are - `created`, `user_id`, and `document_title`. - :param bool include_total: (optional) An optional boolean value. If - specified as `true`, the `pagination` object in the output includes a value - called `total` that gives the total count of feedback created. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `FeedbackList` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_feedback') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'feedback_type': feedback_type, - 'document_title': document_title, - 'model_id': model_id, - 'model_version': model_version, - 'category_removed': category_removed, - 'category_added': category_added, - 'category_not_changed': category_not_changed, - 'type_removed': type_removed, - 'type_added': type_added, - 'type_not_changed': type_not_changed, - 'page_limit': page_limit, - 'cursor': cursor, - 'sort': sort, - 'include_total': include_total - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/feedback' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_feedback(self, - feedback_id: str, - *, - model: str = None, - **kwargs) -> DetailedResponse: - """ - Get a specified feedback entry. - - Gets a feedback entry with a specified `feedback_id`. - - :param str feedback_id: A string that specifies the feedback entry to be - included in the output. - :param str model: (optional) The analysis model to be used by the service. - For the **Element classification** and **Compare two documents** methods, - the default is `contracts`. For the **Extract tables** method, the default - is `tables`. These defaults apply to the standalone methods as well as to - the methods' use in batch-processing requests. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `GetFeedback` object - """ - - if feedback_id is None: - raise ValueError('feedback_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_feedback') - headers.update(sdk_headers) - - params = {'version': self.version, 'model': model} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['feedback_id'] - path_param_values = self.encode_path_vars(feedback_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/feedback/{feedback_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def delete_feedback(self, - feedback_id: str, - *, - model: str = None, - **kwargs) -> DetailedResponse: - """ - Delete a specified feedback entry. - - Deletes a feedback entry with a specified `feedback_id`. - - :param str feedback_id: A string that specifies the feedback entry to be - deleted from the document. - :param str model: (optional) The analysis model to be used by the service. - For the **Element classification** and **Compare two documents** methods, - the default is `contracts`. For the **Extract tables** method, the default - is `tables`. These defaults apply to the standalone methods as well as to - the methods' use in batch-processing requests. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `FeedbackDeleted` object - """ - - if feedback_id is None: - raise ValueError('feedback_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_feedback') - headers.update(sdk_headers) - - params = {'version': self.version, 'model': model} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['feedback_id'] - path_param_values = self.encode_path_vars(feedback_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/feedback/{feedback_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Batches - ######################### - - def create_batch(self, - function: str, - input_credentials_file: BinaryIO, - input_bucket_location: str, - input_bucket_name: str, - output_credentials_file: BinaryIO, - output_bucket_location: str, - output_bucket_name: str, - *, - model: str = None, - **kwargs) -> DetailedResponse: - """ - Submit a batch-processing request. - - Run Compare and Comply methods over a collection of input documents. - **Important:** Batch processing requires the use of the [IBM Cloud Object Storage - service](https://cloud.ibm.com/docs/cloud-object-storage?topic=cloud-object-storage-about#about-ibm-cloud-object-storage). - The use of IBM Cloud Object Storage with Compare and Comply is discussed at [Using - batch - processing](https://cloud.ibm.com/docs/compare-comply?topic=compare-comply-batching#before-you-batch). - - :param str function: The Compare and Comply method to run across the - submitted input documents. - :param BinaryIO input_credentials_file: A JSON file containing the input - Cloud Object Storage credentials. At a minimum, the credentials must enable - `READ` permissions on the bucket defined by the `input_bucket_name` - parameter. - :param str input_bucket_location: The geographical location of the Cloud - Object Storage input bucket as listed on the **Endpoint** tab of your Cloud - Object Storage instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. - :param str input_bucket_name: The name of the Cloud Object Storage input - bucket. - :param BinaryIO output_credentials_file: A JSON file that lists the Cloud - Object Storage output credentials. At a minimum, the credentials must - enable `READ` and `WRITE` permissions on the bucket defined by the - `output_bucket_name` parameter. - :param str output_bucket_location: The geographical location of the Cloud - Object Storage output bucket as listed on the **Endpoint** tab of your - Cloud Object Storage instance; for example, `us-geo`, `eu-geo`, or - `ap-geo`. - :param str output_bucket_name: The name of the Cloud Object Storage output - bucket. - :param str model: (optional) The analysis model to be used by the service. - For the **Element classification** and **Compare two documents** methods, - the default is `contracts`. For the **Extract tables** method, the default - is `tables`. These defaults apply to the standalone methods as well as to - the methods' use in batch-processing requests. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `BatchStatus` object - """ - - if function is None: - raise ValueError('function must be provided') - if input_credentials_file is None: - raise ValueError('input_credentials_file must be provided') - if input_bucket_location is None: - raise ValueError('input_bucket_location must be provided') - if input_bucket_name is None: - raise ValueError('input_bucket_name must be provided') - if output_credentials_file is None: - raise ValueError('output_credentials_file must be provided') - if output_bucket_location is None: - raise ValueError('output_bucket_location must be provided') - if output_bucket_name is None: - raise ValueError('output_bucket_name must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_batch') - headers.update(sdk_headers) - - params = {'version': self.version, 'function': function, 'model': model} - - form_data = [] - form_data.append(('input_credentials_file', - (None, input_credentials_file, 'application/json'))) - form_data.append(('input_bucket_location', (None, input_bucket_location, - 'text/plain'))) - form_data.append( - ('input_bucket_name', (None, input_bucket_name, 'text/plain'))) - form_data.append(('output_credentials_file', - (None, output_credentials_file, 'application/json'))) - form_data.append(('output_bucket_location', - (None, output_bucket_location, 'text/plain'))) - form_data.append( - ('output_bucket_name', (None, output_bucket_name, 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/batches' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def list_batches(self, **kwargs) -> DetailedResponse: - """ - List submitted batch-processing jobs. - - Lists batch-processing jobs submitted by users. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Batches` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_batches') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/batches' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_batch(self, batch_id: str, **kwargs) -> DetailedResponse: - """ - Get information about a specific batch-processing job. - - Gets information about a batch-processing job with a specified ID. - - :param str batch_id: The ID of the batch-processing job whose information - you want to retrieve. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `BatchStatus` object - """ - - if batch_id is None: - raise ValueError('batch_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_batch') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['batch_id'] - path_param_values = self.encode_path_vars(batch_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/batches/{batch_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_batch(self, - batch_id: str, - action: str, - *, - model: str = None, - **kwargs) -> DetailedResponse: - """ - Update a pending or active batch-processing job. - - Updates a pending or active batch-processing job. You can rescan the input bucket - to check for new documents or cancel a job. - - :param str batch_id: The ID of the batch-processing job you want to update. - :param str action: The action you want to perform on the specified - batch-processing job. - :param str model: (optional) The analysis model to be used by the service. - For the **Element classification** and **Compare two documents** methods, - the default is `contracts`. For the **Extract tables** method, the default - is `tables`. These defaults apply to the standalone methods as well as to - the methods' use in batch-processing requests. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `BatchStatus` object - """ - - if batch_id is None: - raise ValueError('batch_id must be provided') - if action is None: - raise ValueError('action must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='update_batch') - headers.update(sdk_headers) - - params = {'version': self.version, 'action': action, 'model': model} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['batch_id'] - path_param_values = self.encode_path_vars(batch_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/batches/{batch_id}'.format(**path_param_dict) - request = self.prepare_request(method='PUT', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - -class ConvertToHtmlEnums: - """ - Enums for convert_to_html parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - APPLICATION_PDF = 'application/pdf' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - IMAGE_BMP = 'image/bmp' - IMAGE_GIF = 'image/gif' - IMAGE_JPEG = 'image/jpeg' - IMAGE_PNG = 'image/png' - IMAGE_TIFF = 'image/tiff' - TEXT_PLAIN = 'text/plain' - - class Model(str, Enum): - """ - The analysis model to be used by the service. For the **Element classification** - and **Compare two documents** methods, the default is `contracts`. For the - **Extract tables** method, the default is `tables`. These defaults apply to the - standalone methods as well as to the methods' use in batch-processing requests. - """ - CONTRACTS = 'contracts' - TABLES = 'tables' - - -class ClassifyElementsEnums: - """ - Enums for classify_elements parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - APPLICATION_PDF = 'application/pdf' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - IMAGE_BMP = 'image/bmp' - IMAGE_GIF = 'image/gif' - IMAGE_JPEG = 'image/jpeg' - IMAGE_PNG = 'image/png' - IMAGE_TIFF = 'image/tiff' - - class Model(str, Enum): - """ - The analysis model to be used by the service. For the **Element classification** - and **Compare two documents** methods, the default is `contracts`. For the - **Extract tables** method, the default is `tables`. These defaults apply to the - standalone methods as well as to the methods' use in batch-processing requests. - """ - CONTRACTS = 'contracts' - TABLES = 'tables' - - -class ExtractTablesEnums: - """ - Enums for extract_tables parameters. - """ - - class FileContentType(str, Enum): - """ - The content type of file. - """ - APPLICATION_PDF = 'application/pdf' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - IMAGE_BMP = 'image/bmp' - IMAGE_GIF = 'image/gif' - IMAGE_JPEG = 'image/jpeg' - IMAGE_PNG = 'image/png' - IMAGE_TIFF = 'image/tiff' - TEXT_PLAIN = 'text/plain' - - class Model(str, Enum): - """ - The analysis model to be used by the service. For the **Element classification** - and **Compare two documents** methods, the default is `contracts`. For the - **Extract tables** method, the default is `tables`. These defaults apply to the - standalone methods as well as to the methods' use in batch-processing requests. - """ - CONTRACTS = 'contracts' - TABLES = 'tables' - - -class CompareDocumentsEnums: - """ - Enums for compare_documents parameters. - """ - - class File1ContentType(str, Enum): - """ - The content type of file_1. - """ - APPLICATION_PDF = 'application/pdf' - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - IMAGE_BMP = 'image/bmp' - IMAGE_GIF = 'image/gif' - IMAGE_JPEG = 'image/jpeg' - IMAGE_PNG = 'image/png' - IMAGE_TIFF = 'image/tiff' - - class File2ContentType(str, Enum): - """ - The content type of file_2. - """ - APPLICATION_PDF = 'application/pdf' - APPLICATION_JSON = 'application/json' - APPLICATION_MSWORD = 'application/msword' - APPLICATION_VND_OPENXMLFORMATS_OFFICEDOCUMENT_WORDPROCESSINGML_DOCUMENT = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' - IMAGE_BMP = 'image/bmp' - IMAGE_GIF = 'image/gif' - IMAGE_JPEG = 'image/jpeg' - IMAGE_PNG = 'image/png' - IMAGE_TIFF = 'image/tiff' - - class Model(str, Enum): - """ - The analysis model to be used by the service. For the **Element classification** - and **Compare two documents** methods, the default is `contracts`. For the - **Extract tables** method, the default is `tables`. These defaults apply to the - standalone methods as well as to the methods' use in batch-processing requests. - """ - CONTRACTS = 'contracts' - TABLES = 'tables' - - -class GetFeedbackEnums: - """ - Enums for get_feedback parameters. - """ - - class Model(str, Enum): - """ - The analysis model to be used by the service. For the **Element classification** - and **Compare two documents** methods, the default is `contracts`. For the - **Extract tables** method, the default is `tables`. These defaults apply to the - standalone methods as well as to the methods' use in batch-processing requests. - """ - CONTRACTS = 'contracts' - TABLES = 'tables' - - -class DeleteFeedbackEnums: - """ - Enums for delete_feedback parameters. - """ - - class Model(str, Enum): - """ - The analysis model to be used by the service. For the **Element classification** - and **Compare two documents** methods, the default is `contracts`. For the - **Extract tables** method, the default is `tables`. These defaults apply to the - standalone methods as well as to the methods' use in batch-processing requests. - """ - CONTRACTS = 'contracts' - TABLES = 'tables' - - -class CreateBatchEnums: - """ - Enums for create_batch parameters. - """ - - class Function(str, Enum): - """ - The Compare and Comply method to run across the submitted input documents. - """ - HTML_CONVERSION = 'html_conversion' - ELEMENT_CLASSIFICATION = 'element_classification' - TABLES = 'tables' - - class Model(str, Enum): - """ - The analysis model to be used by the service. For the **Element classification** - and **Compare two documents** methods, the default is `contracts`. For the - **Extract tables** method, the default is `tables`. These defaults apply to the - standalone methods as well as to the methods' use in batch-processing requests. - """ - CONTRACTS = 'contracts' - TABLES = 'tables' - - -class UpdateBatchEnums: - """ - Enums for update_batch parameters. - """ - - class Action(str, Enum): - """ - The action you want to perform on the specified batch-processing job. - """ - RESCAN = 'rescan' - CANCEL = 'cancel' - - class Model(str, Enum): - """ - The analysis model to be used by the service. For the **Element classification** - and **Compare two documents** methods, the default is `contracts`. For the - **Extract tables** method, the default is `tables`. These defaults apply to the - standalone methods as well as to the methods' use in batch-processing requests. - """ - CONTRACTS = 'contracts' - TABLES = 'tables' - - -############################################################################## -# Models -############################################################################## - - -class Address(): - """ - A party's address. - - :attr str text: (optional) A string listing the address. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - text: str = None, - location: 'Location' = None) -> None: - """ - Initialize a Address object. - - :param str text: (optional) A string listing the address. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.text = text - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Address': - """Initialize a Address object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Address 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 Address object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Address') -> 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: 'Address') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class AlignedElement(): - """ - AlignedElement. - - :attr List[ElementPair] element_pair: (optional) Identifies two elements that - semantically align between the compared documents. - :attr bool identical_text: (optional) Specifies whether the aligned element is - identical. Elements are considered identical despite minor differences such as - leading punctuation, end-of-sentence punctuation, whitespace, the presence or - absence of definite or indefinite articles, and others. - :attr List[str] provenance_ids: (optional) Hashed values that you can send to - IBM to provide feedback or receive support. - :attr bool significant_elements: (optional) Indicates that the elements aligned - are contractual clauses of significance. - """ - - def __init__(self, - *, - element_pair: List['ElementPair'] = None, - identical_text: bool = None, - provenance_ids: List[str] = None, - significant_elements: bool = None) -> None: - """ - Initialize a AlignedElement object. - - :param List[ElementPair] element_pair: (optional) Identifies two elements - that semantically align between the compared documents. - :param bool identical_text: (optional) Specifies whether the aligned - element is identical. Elements are considered identical despite minor - differences such as leading punctuation, end-of-sentence punctuation, - whitespace, the presence or absence of definite or indefinite articles, and - others. - :param List[str] provenance_ids: (optional) Hashed values that you can send - to IBM to provide feedback or receive support. - :param bool significant_elements: (optional) Indicates that the elements - aligned are contractual clauses of significance. - """ - self.element_pair = element_pair - self.identical_text = identical_text - self.provenance_ids = provenance_ids - self.significant_elements = significant_elements - - @classmethod - def from_dict(cls, _dict: Dict) -> 'AlignedElement': - """Initialize a AlignedElement object from a json dictionary.""" - args = {} - if 'element_pair' in _dict: - args['element_pair'] = [ - ElementPair.from_dict(x) for x in _dict.get('element_pair') - ] - if 'identical_text' in _dict: - args['identical_text'] = _dict.get('identical_text') - if 'provenance_ids' in _dict: - args['provenance_ids'] = _dict.get('provenance_ids') - if 'significant_elements' in _dict: - args['significant_elements'] = _dict.get('significant_elements') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a AlignedElement 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, 'element_pair') and self.element_pair is not None: - _dict['element_pair'] = [x.to_dict() for x in self.element_pair] - if hasattr(self, 'identical_text') and self.identical_text is not None: - _dict['identical_text'] = self.identical_text - if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: - _dict['provenance_ids'] = self.provenance_ids - if hasattr(self, 'significant_elements' - ) and self.significant_elements is not None: - _dict['significant_elements'] = self.significant_elements - 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 AlignedElement object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'AlignedElement') -> 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: 'AlignedElement') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Attribute(): - """ - List of document attributes. - - :attr str type: (optional) The type of attribute. - :attr str text: (optional) The text associated with the attribute. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - type: str = None, - text: str = None, - location: 'Location' = None) -> None: - """ - Initialize a Attribute object. - - :param str type: (optional) The type of attribute. - :param str text: (optional) The text associated with the attribute. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.type = type - self.text = text - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Attribute': - """Initialize a Attribute object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Attribute 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 - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 Attribute object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Attribute') -> 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: 'Attribute') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The type of attribute. - """ - CURRENCY = 'Currency' - DATETIME = 'DateTime' - DEFINEDTERM = 'DefinedTerm' - DURATION = 'Duration' - LOCATION = 'Location' - NUMBER = 'Number' - ORGANIZATION = 'Organization' - PERCENTAGE = 'Percentage' - PERSON = 'Person' - - -class BatchStatus(): - """ - The batch-request status. - - :attr str function: (optional) The method to be run against the documents. - Possible values are `html_conversion`, `element_classification`, and `tables`. - :attr str input_bucket_location: (optional) The geographical location of the - Cloud Object Storage input bucket as listed on the **Endpoint** tab of your COS - instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. - :attr str input_bucket_name: (optional) The name of the Cloud Object Storage - input bucket. - :attr str output_bucket_location: (optional) The geographical location of the - Cloud Object Storage output bucket as listed on the **Endpoint** tab of your COS - instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. - :attr str output_bucket_name: (optional) The name of the Cloud Object Storage - output bucket. - :attr str batch_id: (optional) The unique identifier for the batch request. - :attr DocCounts document_counts: (optional) Document counts. - :attr str status: (optional) The status of the batch request. - :attr datetime created: (optional) The creation time of the batch request. - :attr datetime updated: (optional) The time of the most recent update to the - batch request. - """ - - def __init__(self, - *, - function: str = None, - input_bucket_location: str = None, - input_bucket_name: str = None, - output_bucket_location: str = None, - output_bucket_name: str = None, - batch_id: str = None, - document_counts: 'DocCounts' = None, - status: str = None, - created: datetime = None, - updated: datetime = None) -> None: - """ - Initialize a BatchStatus object. - - :param str function: (optional) The method to be run against the documents. - Possible values are `html_conversion`, `element_classification`, and - `tables`. - :param str input_bucket_location: (optional) The geographical location of - the Cloud Object Storage input bucket as listed on the **Endpoint** tab of - your COS instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. - :param str input_bucket_name: (optional) The name of the Cloud Object - Storage input bucket. - :param str output_bucket_location: (optional) The geographical location of - the Cloud Object Storage output bucket as listed on the **Endpoint** tab of - your COS instance; for example, `us-geo`, `eu-geo`, or `ap-geo`. - :param str output_bucket_name: (optional) The name of the Cloud Object - Storage output bucket. - :param str batch_id: (optional) The unique identifier for the batch - request. - :param DocCounts document_counts: (optional) Document counts. - :param str status: (optional) The status of the batch request. - :param datetime created: (optional) The creation time of the batch request. - :param datetime updated: (optional) The time of the most recent update to - the batch request. - """ - self.function = function - self.input_bucket_location = input_bucket_location - self.input_bucket_name = input_bucket_name - self.output_bucket_location = output_bucket_location - self.output_bucket_name = output_bucket_name - self.batch_id = batch_id - self.document_counts = document_counts - self.status = status - self.created = created - self.updated = updated - - @classmethod - def from_dict(cls, _dict: Dict) -> 'BatchStatus': - """Initialize a BatchStatus object from a json dictionary.""" - args = {} - if 'function' in _dict: - args['function'] = _dict.get('function') - if 'input_bucket_location' in _dict: - args['input_bucket_location'] = _dict.get('input_bucket_location') - if 'input_bucket_name' in _dict: - args['input_bucket_name'] = _dict.get('input_bucket_name') - if 'output_bucket_location' in _dict: - args['output_bucket_location'] = _dict.get('output_bucket_location') - if 'output_bucket_name' in _dict: - args['output_bucket_name'] = _dict.get('output_bucket_name') - if 'batch_id' in _dict: - args['batch_id'] = _dict.get('batch_id') - if 'document_counts' in _dict: - args['document_counts'] = DocCounts.from_dict( - _dict.get('document_counts')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a BatchStatus 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, 'function') and self.function is not None: - _dict['function'] = self.function - if hasattr(self, 'input_bucket_location' - ) and self.input_bucket_location is not None: - _dict['input_bucket_location'] = self.input_bucket_location - if hasattr(self, - 'input_bucket_name') and self.input_bucket_name is not None: - _dict['input_bucket_name'] = self.input_bucket_name - if hasattr(self, 'output_bucket_location' - ) and self.output_bucket_location is not None: - _dict['output_bucket_location'] = self.output_bucket_location - if hasattr( - self, - 'output_bucket_name') and self.output_bucket_name is not None: - _dict['output_bucket_name'] = self.output_bucket_name - if hasattr(self, 'batch_id') and self.batch_id is not None: - _dict['batch_id'] = self.batch_id - if hasattr(self, - 'document_counts') and self.document_counts is not None: - _dict['document_counts'] = self.document_counts.to_dict() - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) - 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 BatchStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'BatchStatus') -> 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: 'BatchStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class FunctionEnum(str, Enum): - """ - The method to be run against the documents. Possible values are `html_conversion`, - `element_classification`, and `tables`. - """ - ELEMENT_CLASSIFICATION = 'element_classification' - HTML_CONVERSION = 'html_conversion' - TABLES = 'tables' - - -class Batches(): - """ - The results of a successful **List Batches** request. - - :attr List[BatchStatus] batches: (optional) A list of the status of all batch - requests. - """ - - def __init__(self, *, batches: List['BatchStatus'] = None) -> None: - """ - Initialize a Batches object. - - :param List[BatchStatus] batches: (optional) A list of the status of all - batch requests. - """ - self.batches = batches - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Batches': - """Initialize a Batches object from a json dictionary.""" - args = {} - if 'batches' in _dict: - args['batches'] = [ - BatchStatus.from_dict(x) for x in _dict.get('batches') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Batches 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, 'batches') and self.batches is not None: - _dict['batches'] = [x.to_dict() for x in self.batches] - 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 Batches object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Batches') -> 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: 'Batches') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class BodyCells(): - """ - Cells that are not table header, column header, or row header cells. - - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr str text: (optional) The textual contents of this cell from the input - document without associated markup content. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` - location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` - location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. - :attr List[str] row_header_ids: (optional) An array that contains the `id` value - of a row header that is applicable to this body cell. - :attr List[str] row_header_texts: (optional) An array that contains the `text` - value of a row header that is applicable to this body cell. - :attr List[str] row_header_texts_normalized: (optional) If you provide - customization input, the normalized version of the row header texts according to - the customization; otherwise, the same value as `row_header_texts`. - :attr List[str] column_header_ids: (optional) An array that contains the `id` - value of a column header that is applicable to the current cell. - :attr List[str] column_header_texts: (optional) An array that contains the - `text` value of a column header that is applicable to the current cell. - :attr List[str] column_header_texts_normalized: (optional) If you provide - customization input, the normalized version of the column header texts according - to the customization; otherwise, the same value as `column_header_texts`. - :attr List[Attribute] attributes: (optional) - """ - - def __init__(self, - *, - cell_id: str = None, - location: 'Location' = None, - text: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None, - row_header_ids: List[str] = None, - row_header_texts: List[str] = None, - row_header_texts_normalized: List[str] = None, - column_header_ids: List[str] = None, - column_header_texts: List[str] = None, - column_header_texts_normalized: List[str] = None, - attributes: List['Attribute'] = None) -> None: - """ - Initialize a BodyCells object. - - :param str cell_id: (optional) The unique ID of the cell in the current - table. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param str text: (optional) The textual contents of this cell from the - input document without associated markup content. - :param int row_index_begin: (optional) The `begin` index of this cell's - `row` location in the current table. - :param int row_index_end: (optional) The `end` index of this cell's `row` - location in the current table. - :param int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :param int column_index_end: (optional) The `end` index of this cell's - `column` location in the current table. - :param List[str] row_header_ids: (optional) An array that contains the `id` - value of a row header that is applicable to this body cell. - :param List[str] row_header_texts: (optional) An array that contains the - `text` value of a row header that is applicable to this body cell. - :param List[str] row_header_texts_normalized: (optional) If you provide - customization input, the normalized version of the row header texts - according to the customization; otherwise, the same value as - `row_header_texts`. - :param List[str] column_header_ids: (optional) An array that contains the - `id` value of a column header that is applicable to the current cell. - :param List[str] column_header_texts: (optional) An array that contains the - `text` value of a column header that is applicable to the current cell. - :param List[str] column_header_texts_normalized: (optional) If you provide - customization input, the normalized version of the column header texts - according to the customization; otherwise, the same value as - `column_header_texts`. - :param List[Attribute] attributes: (optional) - """ - self.cell_id = cell_id - self.location = location - self.text = text - self.row_index_begin = row_index_begin - self.row_index_end = row_index_end - self.column_index_begin = column_index_begin - self.column_index_end = column_index_end - self.row_header_ids = row_header_ids - self.row_header_texts = row_header_texts - self.row_header_texts_normalized = row_header_texts_normalized - self.column_header_ids = column_header_ids - self.column_header_texts = column_header_texts - self.column_header_texts_normalized = column_header_texts_normalized - self.attributes = attributes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'BodyCells': - """Initialize a BodyCells object from a json dictionary.""" - args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') - if 'row_header_ids' in _dict: - args['row_header_ids'] = _dict.get('row_header_ids') - if 'row_header_texts' in _dict: - args['row_header_texts'] = _dict.get('row_header_texts') - if 'row_header_texts_normalized' in _dict: - args['row_header_texts_normalized'] = _dict.get( - 'row_header_texts_normalized') - if 'column_header_ids' in _dict: - args['column_header_ids'] = _dict.get('column_header_ids') - if 'column_header_texts' in _dict: - args['column_header_texts'] = _dict.get('column_header_texts') - if 'column_header_texts_normalized' in _dict: - args['column_header_texts_normalized'] = _dict.get( - 'column_header_texts_normalized') - if 'attributes' in _dict: - args['attributes'] = [ - Attribute.from_dict(x) for x in _dict.get('attributes') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a BodyCells 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, 'cell_id') and self.cell_id is not None: - _dict['cell_id'] = self.cell_id - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'row_index_begin') and self.row_index_begin is not None: - _dict['row_index_begin'] = self.row_index_begin - if hasattr(self, 'row_index_end') and self.row_index_end is not None: - _dict['row_index_end'] = self.row_index_end - if hasattr( - self, - 'column_index_begin') and self.column_index_begin is not None: - _dict['column_index_begin'] = self.column_index_begin - if hasattr(self, - 'column_index_end') and self.column_index_end is not None: - _dict['column_index_end'] = self.column_index_end - if hasattr(self, 'row_header_ids') and self.row_header_ids is not None: - _dict['row_header_ids'] = self.row_header_ids - if hasattr(self, - 'row_header_texts') and self.row_header_texts is not None: - _dict['row_header_texts'] = self.row_header_texts - if hasattr(self, 'row_header_texts_normalized' - ) and self.row_header_texts_normalized is not None: - _dict[ - 'row_header_texts_normalized'] = self.row_header_texts_normalized - if hasattr(self, - 'column_header_ids') and self.column_header_ids is not None: - _dict['column_header_ids'] = self.column_header_ids - if hasattr( - self, - 'column_header_texts') and self.column_header_texts is not None: - _dict['column_header_texts'] = self.column_header_texts - if hasattr(self, 'column_header_texts_normalized' - ) and self.column_header_texts_normalized is not None: - _dict[ - 'column_header_texts_normalized'] = self.column_header_texts_normalized - if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x.to_dict() for x in self.attributes] - 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 BodyCells object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'BodyCells') -> 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: 'BodyCells') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Category(): - """ - Information defining an element's subject matter. - - :attr str label: (optional) The category of the associated element. - :attr List[str] provenance_ids: (optional) Hashed values that you can send to - IBM to provide feedback or receive support. - :attr str modification: (optional) The type of modification of the feedback - entry in the updated labels response. - """ - - def __init__(self, - *, - label: str = None, - provenance_ids: List[str] = None, - modification: str = None) -> None: - """ - Initialize a Category object. - - :param str label: (optional) The category of the associated element. - :param List[str] provenance_ids: (optional) Hashed values that you can send - to IBM to provide feedback or receive support. - :param str modification: (optional) The type of modification of the - feedback entry in the updated labels response. - """ - self.label = label - self.provenance_ids = provenance_ids - self.modification = modification - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Category': - """Initialize a Category object from a json dictionary.""" - args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - if 'provenance_ids' in _dict: - args['provenance_ids'] = _dict.get('provenance_ids') - if 'modification' in _dict: - args['modification'] = _dict.get('modification') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Category 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, 'label') and self.label is not None: - _dict['label'] = self.label - if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: - _dict['provenance_ids'] = self.provenance_ids - if hasattr(self, 'modification') and self.modification is not None: - _dict['modification'] = self.modification - 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 Category object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Category') -> 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: 'Category') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class LabelEnum(str, Enum): - """ - The category of the associated element. - """ - AMENDMENTS = 'Amendments' - ASSET_USE = 'Asset Use' - ASSIGNMENTS = 'Assignments' - AUDITS = 'Audits' - BUSINESS_CONTINUITY = 'Business Continuity' - COMMUNICATION = 'Communication' - CONFIDENTIALITY = 'Confidentiality' - DELIVERABLES = 'Deliverables' - DELIVERY = 'Delivery' - DISPUTE_RESOLUTION = 'Dispute Resolution' - FORCE_MAJEURE = 'Force Majeure' - INDEMNIFICATION = 'Indemnification' - INSURANCE = 'Insurance' - INTELLECTUAL_PROPERTY = 'Intellectual Property' - LIABILITY = 'Liability' - ORDER_OF_PRECEDENCE = 'Order of Precedence' - PAYMENT_TERMS_BILLING = 'Payment Terms & Billing' - PRICING_TAXES = 'Pricing & Taxes' - PRIVACY = 'Privacy' - RESPONSIBILITIES = 'Responsibilities' - SAFETY_AND_SECURITY = 'Safety and Security' - SCOPE_OF_WORK = 'Scope of Work' - SUBCONTRACTS = 'Subcontracts' - TERM_TERMINATION = 'Term & Termination' - WARRANTIES = 'Warranties' - - class ModificationEnum(str, Enum): - """ - The type of modification of the feedback entry in the updated labels response. - """ - ADDED = 'added' - UNCHANGED = 'unchanged' - REMOVED = 'removed' - - -class CategoryComparison(): - """ - Information defining an element's subject matter. - - :attr str label: (optional) The category of the associated element. - """ - - def __init__(self, *, label: str = None) -> None: - """ - Initialize a CategoryComparison object. - - :param str label: (optional) The category of the associated element. - """ - self.label = label - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CategoryComparison': - """Initialize a CategoryComparison object from a json dictionary.""" - args = {} - if 'label' in _dict: - args['label'] = _dict.get('label') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CategoryComparison 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, 'label') and self.label is not None: - _dict['label'] = self.label - 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 CategoryComparison object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CategoryComparison') -> 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: 'CategoryComparison') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class LabelEnum(str, Enum): - """ - The category of the associated element. - """ - AMENDMENTS = 'Amendments' - ASSET_USE = 'Asset Use' - ASSIGNMENTS = 'Assignments' - AUDITS = 'Audits' - BUSINESS_CONTINUITY = 'Business Continuity' - COMMUNICATION = 'Communication' - CONFIDENTIALITY = 'Confidentiality' - DELIVERABLES = 'Deliverables' - DELIVERY = 'Delivery' - DISPUTE_RESOLUTION = 'Dispute Resolution' - FORCE_MAJEURE = 'Force Majeure' - INDEMNIFICATION = 'Indemnification' - INSURANCE = 'Insurance' - INTELLECTUAL_PROPERTY = 'Intellectual Property' - LIABILITY = 'Liability' - ORDER_OF_PRECEDENCE = 'Order of Precedence' - PAYMENT_TERMS_BILLING = 'Payment Terms & Billing' - PRICING_TAXES = 'Pricing & Taxes' - PRIVACY = 'Privacy' - RESPONSIBILITIES = 'Responsibilities' - SAFETY_AND_SECURITY = 'Safety and Security' - SCOPE_OF_WORK = 'Scope of Work' - SUBCONTRACTS = 'Subcontracts' - TERM_TERMINATION = 'Term & Termination' - WARRANTIES = 'Warranties' - - -class ClassifyReturn(): - """ - The analysis of objects returned by the **Element classification** method. - - :attr Document document: (optional) Basic information about the input document. - :attr str model_id: (optional) The analysis model used to classify the input - document. For the **Element classification** method, the only valid value is - `contracts`. - :attr str model_version: (optional) The version of the analysis model identified - by the value of the `model_id` key. - :attr List[Element] elements: (optional) Document elements identified by the - service. - :attr List[EffectiveDates] effective_dates: (optional) The date or dates on - which the document becomes effective. - :attr List[ContractAmts] contract_amounts: (optional) The monetary amounts that - identify the total amount of the contract that needs to be paid from one party - to another. - :attr List[TerminationDates] termination_dates: (optional) The dates on which - the document is to be terminated. - :attr List[ContractTypes] contract_types: (optional) The contract type as - declared in the document. - :attr List[ContractTerms] contract_terms: (optional) The durations of the - contract. - :attr List[PaymentTerms] payment_terms: (optional) The document's payment - durations. - :attr List[ContractCurrencies] contract_currencies: (optional) The contract - currencies as declared in the document. - :attr List[Tables] tables: (optional) Definition of tables identified in the - input document. - :attr DocStructure document_structure: (optional) The structure of the input - document. - :attr List[Parties] parties: (optional) Definitions of the parties identified in - the input document. - """ - - def __init__(self, - *, - document: 'Document' = None, - model_id: str = None, - model_version: str = None, - elements: List['Element'] = None, - effective_dates: List['EffectiveDates'] = None, - contract_amounts: List['ContractAmts'] = None, - termination_dates: List['TerminationDates'] = None, - contract_types: List['ContractTypes'] = None, - contract_terms: List['ContractTerms'] = None, - payment_terms: List['PaymentTerms'] = None, - contract_currencies: List['ContractCurrencies'] = None, - tables: List['Tables'] = None, - document_structure: 'DocStructure' = None, - parties: List['Parties'] = None) -> None: - """ - Initialize a ClassifyReturn object. - - :param Document document: (optional) Basic information about the input - document. - :param str model_id: (optional) The analysis model used to classify the - input document. For the **Element classification** method, the only valid - value is `contracts`. - :param str model_version: (optional) The version of the analysis model - identified by the value of the `model_id` key. - :param List[Element] elements: (optional) Document elements identified by - the service. - :param List[EffectiveDates] effective_dates: (optional) The date or dates - on which the document becomes effective. - :param List[ContractAmts] contract_amounts: (optional) The monetary amounts - that identify the total amount of the contract that needs to be paid from - one party to another. - :param List[TerminationDates] termination_dates: (optional) The dates on - which the document is to be terminated. - :param List[ContractTypes] contract_types: (optional) The contract type as - declared in the document. - :param List[ContractTerms] contract_terms: (optional) The durations of the - contract. - :param List[PaymentTerms] payment_terms: (optional) The document's payment - durations. - :param List[ContractCurrencies] contract_currencies: (optional) The - contract currencies as declared in the document. - :param List[Tables] tables: (optional) Definition of tables identified in - the input document. - :param DocStructure document_structure: (optional) The structure of the - input document. - :param List[Parties] parties: (optional) Definitions of the parties - identified in the input document. - """ - self.document = document - self.model_id = model_id - self.model_version = model_version - self.elements = elements - self.effective_dates = effective_dates - self.contract_amounts = contract_amounts - self.termination_dates = termination_dates - self.contract_types = contract_types - self.contract_terms = contract_terms - self.payment_terms = payment_terms - self.contract_currencies = contract_currencies - self.tables = tables - self.document_structure = document_structure - self.parties = parties - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ClassifyReturn': - """Initialize a ClassifyReturn object from a json dictionary.""" - args = {} - if 'document' in _dict: - args['document'] = Document.from_dict(_dict.get('document')) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'elements' in _dict: - args['elements'] = [ - Element.from_dict(x) for x in _dict.get('elements') - ] - if 'effective_dates' in _dict: - args['effective_dates'] = [ - EffectiveDates.from_dict(x) - for x in _dict.get('effective_dates') - ] - if 'contract_amounts' in _dict: - args['contract_amounts'] = [ - ContractAmts.from_dict(x) for x in _dict.get('contract_amounts') - ] - if 'termination_dates' in _dict: - args['termination_dates'] = [ - TerminationDates.from_dict(x) - for x in _dict.get('termination_dates') - ] - if 'contract_types' in _dict: - args['contract_types'] = [ - ContractTypes.from_dict(x) for x in _dict.get('contract_types') - ] - if 'contract_terms' in _dict: - args['contract_terms'] = [ - ContractTerms.from_dict(x) for x in _dict.get('contract_terms') - ] - if 'payment_terms' in _dict: - args['payment_terms'] = [ - PaymentTerms.from_dict(x) for x in _dict.get('payment_terms') - ] - if 'contract_currencies' in _dict: - args['contract_currencies'] = [ - ContractCurrencies.from_dict(x) - for x in _dict.get('contract_currencies') - ] - if 'tables' in _dict: - args['tables'] = [Tables.from_dict(x) for x in _dict.get('tables')] - if 'document_structure' in _dict: - args['document_structure'] = DocStructure.from_dict( - _dict.get('document_structure')) - if 'parties' in _dict: - args['parties'] = [ - Parties.from_dict(x) for x in _dict.get('parties') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ClassifyReturn 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, 'document') and self.document is not None: - _dict['document'] = self.document.to_dict() - if hasattr(self, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'model_version') and self.model_version is not None: - _dict['model_version'] = self.model_version - if hasattr(self, 'elements') and self.elements is not None: - _dict['elements'] = [x.to_dict() for x in self.elements] - if hasattr(self, - 'effective_dates') and self.effective_dates is not None: - _dict['effective_dates'] = [ - x.to_dict() for x in self.effective_dates - ] - if hasattr(self, - 'contract_amounts') and self.contract_amounts is not None: - _dict['contract_amounts'] = [ - x.to_dict() for x in self.contract_amounts - ] - if hasattr(self, - 'termination_dates') and self.termination_dates is not None: - _dict['termination_dates'] = [ - x.to_dict() for x in self.termination_dates - ] - if hasattr(self, 'contract_types') and self.contract_types is not None: - _dict['contract_types'] = [x.to_dict() for x in self.contract_types] - if hasattr(self, 'contract_terms') and self.contract_terms is not None: - _dict['contract_terms'] = [x.to_dict() for x in self.contract_terms] - if hasattr(self, 'payment_terms') and self.payment_terms is not None: - _dict['payment_terms'] = [x.to_dict() for x in self.payment_terms] - if hasattr( - self, - 'contract_currencies') and self.contract_currencies is not None: - _dict['contract_currencies'] = [ - x.to_dict() for x in self.contract_currencies - ] - if hasattr(self, 'tables') and self.tables is not None: - _dict['tables'] = [x.to_dict() for x in self.tables] - if hasattr( - self, - 'document_structure') and self.document_structure is not None: - _dict['document_structure'] = self.document_structure.to_dict() - if hasattr(self, 'parties') and self.parties is not None: - _dict['parties'] = [x.to_dict() for x in self.parties] - 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 ClassifyReturn object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ClassifyReturn') -> 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: 'ClassifyReturn') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ColumnHeaders(): - """ - Column-level cells, each applicable as a header to other cells in the same column as - itself, of the current table. - - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr object location: (optional) The location of the column header cell in the - current table as defined by its `begin` and `end` offsets, respectfully, in the - input document. - :attr str text: (optional) The textual contents of this cell from the input - document without associated markup content. - :attr str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, - the same value as `text`. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` - location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` - location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. - """ - - def __init__(self, - *, - cell_id: str = None, - location: object = None, - text: str = None, - text_normalized: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: - """ - Initialize a ColumnHeaders object. - - :param str cell_id: (optional) The unique ID of the cell in the current - table. - :param object location: (optional) The location of the column header cell - in the current table as defined by its `begin` and `end` offsets, - respectfully, in the input document. - :param str text: (optional) The textual contents of this cell from the - input document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, - the normalized version of the cell text according to the customization; - otherwise, the same value as `text`. - :param int row_index_begin: (optional) The `begin` index of this cell's - `row` location in the current table. - :param int row_index_end: (optional) The `end` index of this cell's `row` - location in the current table. - :param int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :param int column_index_end: (optional) The `end` index of this cell's - `column` location in the current table. - """ - self.cell_id = cell_id - self.location = location - self.text = text - self.text_normalized = text_normalized - self.row_index_begin = row_index_begin - self.row_index_end = row_index_end - self.column_index_begin = column_index_begin - self.column_index_end = column_index_end - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ColumnHeaders': - """Initialize a ColumnHeaders object from a json dictionary.""" - args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ColumnHeaders 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, 'cell_id') and self.cell_id is not None: - _dict['cell_id'] = self.cell_id - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - if hasattr(self, - 'row_index_begin') and self.row_index_begin is not None: - _dict['row_index_begin'] = self.row_index_begin - if hasattr(self, 'row_index_end') and self.row_index_end is not None: - _dict['row_index_end'] = self.row_index_end - if hasattr( - self, - 'column_index_begin') and self.column_index_begin is not None: - _dict['column_index_begin'] = self.column_index_begin - if hasattr(self, - 'column_index_end') and self.column_index_end is not None: - _dict['column_index_end'] = self.column_index_end - 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 ColumnHeaders object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ColumnHeaders') -> 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: 'ColumnHeaders') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CompareReturn(): - """ - The comparison of the two submitted documents. - - :attr str model_id: (optional) The analysis model used to compare the input - documents. For the **Compare two documents** method, the only valid value is - `contracts`. - :attr str model_version: (optional) The version of the analysis model identified - by the value of the `model_id` key. - :attr List[Document] documents: (optional) Information about the documents being - compared. - :attr List[AlignedElement] aligned_elements: (optional) A list of pairs of - elements that semantically align between the compared documents. - :attr List[UnalignedElement] unaligned_elements: (optional) A list of elements - that do not semantically align between the compared documents. - """ - - def __init__(self, - *, - model_id: str = None, - model_version: str = None, - documents: List['Document'] = None, - aligned_elements: List['AlignedElement'] = None, - unaligned_elements: List['UnalignedElement'] = None) -> None: - """ - Initialize a CompareReturn object. - - :param str model_id: (optional) The analysis model used to compare the - input documents. For the **Compare two documents** method, the only valid - value is `contracts`. - :param str model_version: (optional) The version of the analysis model - identified by the value of the `model_id` key. - :param List[Document] documents: (optional) Information about the documents - being compared. - :param List[AlignedElement] aligned_elements: (optional) A list of pairs of - elements that semantically align between the compared documents. - :param List[UnalignedElement] unaligned_elements: (optional) A list of - elements that do not semantically align between the compared documents. - """ - self.model_id = model_id - self.model_version = model_version - self.documents = documents - self.aligned_elements = aligned_elements - self.unaligned_elements = unaligned_elements - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CompareReturn': - """Initialize a CompareReturn object from a json dictionary.""" - args = {} - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'documents' in _dict: - args['documents'] = [ - Document.from_dict(x) for x in _dict.get('documents') - ] - if 'aligned_elements' in _dict: - args['aligned_elements'] = [ - AlignedElement.from_dict(x) - for x in _dict.get('aligned_elements') - ] - if 'unaligned_elements' in _dict: - args['unaligned_elements'] = [ - UnalignedElement.from_dict(x) - for x in _dict.get('unaligned_elements') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CompareReturn 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, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'model_version') and self.model_version is not None: - _dict['model_version'] = self.model_version - if hasattr(self, 'documents') and self.documents is not None: - _dict['documents'] = [x.to_dict() for x in self.documents] - if hasattr(self, - 'aligned_elements') and self.aligned_elements is not None: - _dict['aligned_elements'] = [ - x.to_dict() for x in self.aligned_elements - ] - if hasattr( - self, - 'unaligned_elements') and self.unaligned_elements is not None: - _dict['unaligned_elements'] = [ - x.to_dict() for x in self.unaligned_elements - ] - 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 CompareReturn object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CompareReturn') -> 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: 'CompareReturn') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Contact(): - """ - A contact. - - :attr str name: (optional) A string listing the name of the contact. - :attr str role: (optional) A string listing the role of the contact. - """ - - def __init__(self, *, name: str = None, role: str = None) -> None: - """ - Initialize a Contact object. - - :param str name: (optional) A string listing the name of the contact. - :param str role: (optional) A string listing the role of the contact. - """ - self.name = name - self.role = role - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Contact': - """Initialize a Contact object from a json dictionary.""" - args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'role' in _dict: - args['role'] = _dict.get('role') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Contact 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'role') and self.role is not None: - _dict['role'] = self.role - 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 Contact object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Contact') -> 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: 'Contact') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Contexts(): - """ - Text that is related to the contents of the table and that precedes or follows the - current table. - - :attr str text: (optional) The related text. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - text: str = None, - location: 'Location' = None) -> None: - """ - Initialize a Contexts object. - - :param str text: (optional) The related text. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.text = text - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Contexts': - """Initialize a Contexts object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Contexts 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 Contexts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Contexts') -> 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: 'Contexts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ContractAmts(): - """ - A monetary amount identified in the input document. - - :attr str confidence_level: (optional) The confidence level in the - identification of the contract amount. - :attr str text: (optional) The monetary amount. - :attr str text_normalized: (optional) The normalized form of the amount, which - is listed as a string. This element is optional; it is returned only if - normalized text exists. - :attr Interpretation interpretation: (optional) The details of the normalized - text, if applicable. This element is optional; it is returned only if normalized - text exists. - :attr List[str] provenance_ids: (optional) Hashed values that you can send to - IBM to provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - confidence_level: str = None, - text: str = None, - text_normalized: str = None, - interpretation: 'Interpretation' = None, - provenance_ids: List[str] = None, - location: 'Location' = None) -> None: - """ - Initialize a ContractAmts object. - - :param str confidence_level: (optional) The confidence level in the - identification of the contract amount. - :param str text: (optional) The monetary amount. - :param str text_normalized: (optional) The normalized form of the amount, - which is listed as a string. This element is optional; it is returned only - if normalized text exists. - :param Interpretation interpretation: (optional) The details of the - normalized text, if applicable. This element is optional; it is returned - only if normalized text exists. - :param List[str] provenance_ids: (optional) Hashed values that you can send - to IBM to provide feedback or receive support. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.confidence_level = confidence_level - self.text = text - self.text_normalized = text_normalized - self.interpretation = interpretation - self.provenance_ids = provenance_ids - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ContractAmts': - """Initialize a ContractAmts object from a json dictionary.""" - args = {} - if 'confidence_level' in _dict: - args['confidence_level'] = _dict.get('confidence_level') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'interpretation' in _dict: - args['interpretation'] = Interpretation.from_dict( - _dict.get('interpretation')) - if 'provenance_ids' in _dict: - args['provenance_ids'] = _dict.get('provenance_ids') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ContractAmts 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, - 'confidence_level') and self.confidence_level is not None: - _dict['confidence_level'] = self.confidence_level - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation.to_dict() - if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: - _dict['provenance_ids'] = self.provenance_ids - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 ContractAmts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ContractAmts') -> 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: 'ContractAmts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ConfidenceLevelEnum(str, Enum): - """ - The confidence level in the identification of the contract amount. - """ - HIGH = 'High' - MEDIUM = 'Medium' - LOW = 'Low' - - -class ContractCurrencies(): - """ - The contract currencies that are declared in the document. - - :attr str confidence_level: (optional) The confidence level in the - identification of the contract currency. - :attr str text: (optional) The contract currency. - :attr str text_normalized: (optional) The normalized form of the contract - currency, which is listed as a string in - [ISO-4217](https://www.iso.org/iso-4217-currency-codes.html) format. This - element is optional; it is returned only if normalized text exists. - :attr List[str] provenance_ids: (optional) Hashed values that you can send to - IBM to provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - confidence_level: str = None, - text: str = None, - text_normalized: str = None, - provenance_ids: List[str] = None, - location: 'Location' = None) -> None: - """ - Initialize a ContractCurrencies object. - - :param str confidence_level: (optional) The confidence level in the - identification of the contract currency. - :param str text: (optional) The contract currency. - :param str text_normalized: (optional) The normalized form of the contract - currency, which is listed as a string in - [ISO-4217](https://www.iso.org/iso-4217-currency-codes.html) format. This - element is optional; it is returned only if normalized text exists. - :param List[str] provenance_ids: (optional) Hashed values that you can send - to IBM to provide feedback or receive support. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.confidence_level = confidence_level - self.text = text - self.text_normalized = text_normalized - self.provenance_ids = provenance_ids - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ContractCurrencies': - """Initialize a ContractCurrencies object from a json dictionary.""" - args = {} - if 'confidence_level' in _dict: - args['confidence_level'] = _dict.get('confidence_level') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'provenance_ids' in _dict: - args['provenance_ids'] = _dict.get('provenance_ids') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ContractCurrencies 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, - 'confidence_level') and self.confidence_level is not None: - _dict['confidence_level'] = self.confidence_level - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: - _dict['provenance_ids'] = self.provenance_ids - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 ContractCurrencies object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ContractCurrencies') -> 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: 'ContractCurrencies') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ConfidenceLevelEnum(str, Enum): - """ - The confidence level in the identification of the contract currency. - """ - HIGH = 'High' - MEDIUM = 'Medium' - LOW = 'Low' - - -class ContractTerms(): - """ - The duration or durations of the contract. - - :attr str confidence_level: (optional) The confidence level in the - identification of the contract term. - :attr str text: (optional) The contract term (duration). - :attr str text_normalized: (optional) The normalized form of the contract term, - which is listed as a string. This element is optional; it is returned only if - normalized text exists. - :attr Interpretation interpretation: (optional) The details of the normalized - text, if applicable. This element is optional; it is returned only if normalized - text exists. - :attr List[str] provenance_ids: (optional) Hashed values that you can send to - IBM to provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - confidence_level: str = None, - text: str = None, - text_normalized: str = None, - interpretation: 'Interpretation' = None, - provenance_ids: List[str] = None, - location: 'Location' = None) -> None: - """ - Initialize a ContractTerms object. - - :param str confidence_level: (optional) The confidence level in the - identification of the contract term. - :param str text: (optional) The contract term (duration). - :param str text_normalized: (optional) The normalized form of the contract - term, which is listed as a string. This element is optional; it is returned - only if normalized text exists. - :param Interpretation interpretation: (optional) The details of the - normalized text, if applicable. This element is optional; it is returned - only if normalized text exists. - :param List[str] provenance_ids: (optional) Hashed values that you can send - to IBM to provide feedback or receive support. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.confidence_level = confidence_level - self.text = text - self.text_normalized = text_normalized - self.interpretation = interpretation - self.provenance_ids = provenance_ids - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ContractTerms': - """Initialize a ContractTerms object from a json dictionary.""" - args = {} - if 'confidence_level' in _dict: - args['confidence_level'] = _dict.get('confidence_level') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'interpretation' in _dict: - args['interpretation'] = Interpretation.from_dict( - _dict.get('interpretation')) - if 'provenance_ids' in _dict: - args['provenance_ids'] = _dict.get('provenance_ids') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ContractTerms 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, - 'confidence_level') and self.confidence_level is not None: - _dict['confidence_level'] = self.confidence_level - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation.to_dict() - if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: - _dict['provenance_ids'] = self.provenance_ids - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 ContractTerms object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ContractTerms') -> 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: 'ContractTerms') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ConfidenceLevelEnum(str, Enum): - """ - The confidence level in the identification of the contract term. - """ - HIGH = 'High' - MEDIUM = 'Medium' - LOW = 'Low' - - -class ContractTypes(): - """ - The contract type identified in the input document. - - :attr str confidence_level: (optional) The confidence level in the - identification of the contract type. - :attr str text: (optional) The contract type. - :attr List[str] provenance_ids: (optional) Hashed values that you can send to - IBM to provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - confidence_level: str = None, - text: str = None, - provenance_ids: List[str] = None, - location: 'Location' = None) -> None: - """ - Initialize a ContractTypes object. - - :param str confidence_level: (optional) The confidence level in the - identification of the contract type. - :param str text: (optional) The contract type. - :param List[str] provenance_ids: (optional) Hashed values that you can send - to IBM to provide feedback or receive support. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.confidence_level = confidence_level - self.text = text - self.provenance_ids = provenance_ids - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ContractTypes': - """Initialize a ContractTypes object from a json dictionary.""" - args = {} - if 'confidence_level' in _dict: - args['confidence_level'] = _dict.get('confidence_level') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'provenance_ids' in _dict: - args['provenance_ids'] = _dict.get('provenance_ids') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ContractTypes 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, - 'confidence_level') and self.confidence_level is not None: - _dict['confidence_level'] = self.confidence_level - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: - _dict['provenance_ids'] = self.provenance_ids - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 ContractTypes object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ContractTypes') -> 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: 'ContractTypes') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ConfidenceLevelEnum(str, Enum): - """ - The confidence level in the identification of the contract type. - """ - HIGH = 'High' - MEDIUM = 'Medium' - LOW = 'Low' - - -class DocCounts(): - """ - Document counts. - - :attr int total: (optional) Total number of documents. - :attr int pending: (optional) Number of pending documents. - :attr int successful: (optional) Number of documents successfully processed. - :attr int failed: (optional) Number of documents not successfully processed. - """ - - def __init__(self, - *, - total: int = None, - pending: int = None, - successful: int = None, - failed: int = None) -> None: - """ - Initialize a DocCounts object. - - :param int total: (optional) Total number of documents. - :param int pending: (optional) Number of pending documents. - :param int successful: (optional) Number of documents successfully - processed. - :param int failed: (optional) Number of documents not successfully - processed. - """ - self.total = total - self.pending = pending - self.successful = successful - self.failed = failed - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocCounts': - """Initialize a DocCounts object from a json dictionary.""" - args = {} - if 'total' in _dict: - args['total'] = _dict.get('total') - if 'pending' in _dict: - args['pending'] = _dict.get('pending') - if 'successful' in _dict: - args['successful'] = _dict.get('successful') - if 'failed' in _dict: - args['failed'] = _dict.get('failed') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocCounts 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, 'total') and self.total is not None: - _dict['total'] = self.total - if hasattr(self, 'pending') and self.pending is not None: - _dict['pending'] = self.pending - if hasattr(self, 'successful') and self.successful is not None: - _dict['successful'] = self.successful - if hasattr(self, 'failed') and self.failed is not None: - _dict['failed'] = self.failed - 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 DocCounts object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocCounts') -> 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: 'DocCounts') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocInfo(): - """ - Information about the parsed input document. - - :attr str html: (optional) The full text of the parsed document in HTML format. - :attr str title: (optional) The title of the parsed document. If the service did - not detect a title, the value of this element is `null`. - :attr str hash: (optional) The MD5 hash of the input document. - """ - - def __init__(self, - *, - html: str = None, - title: str = None, - hash: str = None) -> None: - """ - Initialize a DocInfo object. - - :param str html: (optional) The full text of the parsed document in HTML - format. - :param str title: (optional) The title of the parsed document. If the - service did not detect a title, the value of this element is `null`. - :param str hash: (optional) The MD5 hash of the input document. - """ - self.html = html - self.title = title - self.hash = hash - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocInfo': - """Initialize a DocInfo object from a json dictionary.""" - args = {} - if 'html' in _dict: - args['html'] = _dict.get('html') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'hash' in _dict: - args['hash'] = _dict.get('hash') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocInfo 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, 'html') and self.html is not None: - _dict['html'] = self.html - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'hash') and self.hash is not None: - _dict['hash'] = self.hash - 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 DocInfo object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocInfo') -> 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: 'DocInfo') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DocStructure(): - """ - The structure of the input document. - - :attr List[SectionTitles] section_titles: (optional) An array containing one - object per section or subsection identified in the input document. - :attr List[LeadingSentence] leading_sentences: (optional) An array containing - one object per section or subsection, in parallel with the `section_titles` - array, that details the leading sentences in the corresponding section or - subsection. - :attr List[Paragraphs] paragraphs: (optional) An array containing one object per - paragraph, in parallel with the `section_titles` and `leading_sentences` arrays. - """ - - def __init__(self, - *, - section_titles: List['SectionTitles'] = None, - leading_sentences: List['LeadingSentence'] = None, - paragraphs: List['Paragraphs'] = None) -> None: - """ - Initialize a DocStructure object. - - :param List[SectionTitles] section_titles: (optional) An array containing - one object per section or subsection identified in the input document. - :param List[LeadingSentence] leading_sentences: (optional) An array - containing one object per section or subsection, in parallel with the - `section_titles` array, that details the leading sentences in the - corresponding section or subsection. - :param List[Paragraphs] paragraphs: (optional) An array containing one - object per paragraph, in parallel with the `section_titles` and - `leading_sentences` arrays. - """ - self.section_titles = section_titles - self.leading_sentences = leading_sentences - self.paragraphs = paragraphs - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocStructure': - """Initialize a DocStructure object from a json dictionary.""" - args = {} - if 'section_titles' in _dict: - args['section_titles'] = [ - SectionTitles.from_dict(x) for x in _dict.get('section_titles') - ] - if 'leading_sentences' in _dict: - args['leading_sentences'] = [ - LeadingSentence.from_dict(x) - for x in _dict.get('leading_sentences') - ] - if 'paragraphs' in _dict: - args['paragraphs'] = [ - Paragraphs.from_dict(x) for x in _dict.get('paragraphs') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocStructure 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, 'section_titles') and self.section_titles is not None: - _dict['section_titles'] = [x.to_dict() for x in self.section_titles] - if hasattr(self, - 'leading_sentences') and self.leading_sentences is not None: - _dict['leading_sentences'] = [ - x.to_dict() for x in self.leading_sentences - ] - if hasattr(self, 'paragraphs') and self.paragraphs is not None: - _dict['paragraphs'] = [x.to_dict() for x in self.paragraphs] - 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 DocStructure object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocStructure') -> 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: 'DocStructure') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Document(): - """ - Basic information about the input document. - - :attr str title: (optional) Document title, if detected. - :attr str html: (optional) The input document converted into HTML format. - :attr str hash: (optional) The MD5 hash value of the input document. - :attr str label: (optional) The label applied to the input document with the - calling method's `file_1_label` or `file_2_label` value. This field is specified - only in the output of the **Comparing two documents** method. - """ - - def __init__(self, - *, - title: str = None, - html: str = None, - hash: str = None, - label: str = None) -> None: - """ - Initialize a Document object. - - :param str title: (optional) Document title, if detected. - :param str html: (optional) The input document converted into HTML format. - :param str hash: (optional) The MD5 hash value of the input document. - :param str label: (optional) The label applied to the input document with - the calling method's `file_1_label` or `file_2_label` value. This field is - specified only in the output of the **Comparing two documents** method. - """ - self.title = title - self.html = html - self.hash = hash - self.label = label - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Document': - """Initialize a Document object from a json dictionary.""" - args = {} - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'html' in _dict: - args['html'] = _dict.get('html') - if 'hash' in _dict: - args['hash'] = _dict.get('hash') - if 'label' in _dict: - args['label'] = _dict.get('label') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Document 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, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'html') and self.html is not None: - _dict['html'] = self.html - if hasattr(self, 'hash') and self.hash is not None: - _dict['hash'] = self.hash - if hasattr(self, 'label') and self.label is not None: - _dict['label'] = self.label - 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 Document object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Document') -> 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: 'Document') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class EffectiveDates(): - """ - An effective date. - - :attr str confidence_level: (optional) The confidence level in the - identification of the effective date. - :attr str text: (optional) The effective date, listed as a string. - :attr str text_normalized: (optional) The normalized form of the effective date, - which is listed as a string. This element is optional; it is returned only if - normalized text exists. - :attr List[str] provenance_ids: (optional) Hashed values that you can send to - IBM to provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - confidence_level: str = None, - text: str = None, - text_normalized: str = None, - provenance_ids: List[str] = None, - location: 'Location' = None) -> None: - """ - Initialize a EffectiveDates object. - - :param str confidence_level: (optional) The confidence level in the - identification of the effective date. - :param str text: (optional) The effective date, listed as a string. - :param str text_normalized: (optional) The normalized form of the effective - date, which is listed as a string. This element is optional; it is returned - only if normalized text exists. - :param List[str] provenance_ids: (optional) Hashed values that you can send - to IBM to provide feedback or receive support. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.confidence_level = confidence_level - self.text = text - self.text_normalized = text_normalized - self.provenance_ids = provenance_ids - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'EffectiveDates': - """Initialize a EffectiveDates object from a json dictionary.""" - args = {} - if 'confidence_level' in _dict: - args['confidence_level'] = _dict.get('confidence_level') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'provenance_ids' in _dict: - args['provenance_ids'] = _dict.get('provenance_ids') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a EffectiveDates 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, - 'confidence_level') and self.confidence_level is not None: - _dict['confidence_level'] = self.confidence_level - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: - _dict['provenance_ids'] = self.provenance_ids - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 EffectiveDates object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'EffectiveDates') -> 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: 'EffectiveDates') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ConfidenceLevelEnum(str, Enum): - """ - The confidence level in the identification of the effective date. - """ - HIGH = 'High' - MEDIUM = 'Medium' - LOW = 'Low' - - -class Element(): - """ - A component part of the document. - - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr str text: (optional) The text of the element. - :attr List[TypeLabel] types: (optional) Description of the action specified by - the element and whom it affects. - :attr List[Category] categories: (optional) List of functional categories into - which the element falls; in other words, the subject matter of the element. - :attr List[Attribute] attributes: (optional) List of document attributes. - """ - - def __init__(self, - *, - location: 'Location' = None, - text: str = None, - types: List['TypeLabel'] = None, - categories: List['Category'] = None, - attributes: List['Attribute'] = None) -> None: - """ - Initialize a Element object. - - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param str text: (optional) The text of the element. - :param List[TypeLabel] types: (optional) Description of the action - specified by the element and whom it affects. - :param List[Category] categories: (optional) List of functional categories - into which the element falls; in other words, the subject matter of the - element. - :param List[Attribute] attributes: (optional) List of document attributes. - """ - self.location = location - self.text = text - self.types = types - self.categories = categories - self.attributes = attributes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Element': - """Initialize a Element object from a json dictionary.""" - args = {} - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'types' in _dict: - args['types'] = [TypeLabel.from_dict(x) for x in _dict.get('types')] - if 'categories' in _dict: - args['categories'] = [ - Category.from_dict(x) for x in _dict.get('categories') - ] - if 'attributes' in _dict: - args['attributes'] = [ - Attribute.from_dict(x) for x in _dict.get('attributes') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Element 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, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'types') and self.types is not None: - _dict['types'] = [x.to_dict() for x in self.types] - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x.to_dict() for x in self.categories] - if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x.to_dict() for x in self.attributes] - 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 Element object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Element') -> 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: 'Element') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ElementLocations(): - """ - A list of `begin` and `end` indexes that indicate the locations of the elements in the - input document. - - :attr int begin: (optional) An integer that indicates the starting position of - the element in the input document. - :attr int end: (optional) An integer that indicates the ending position of the - element in the input document. - """ - - def __init__(self, *, begin: int = None, end: int = None) -> None: - """ - Initialize a ElementLocations object. - - :param int begin: (optional) An integer that indicates the starting - position of the element in the input document. - :param int end: (optional) An integer that indicates the ending position of - the element in the input document. - """ - self.begin = begin - self.end = end - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ElementLocations': - """Initialize a ElementLocations object from a json dictionary.""" - args = {} - if 'begin' in _dict: - args['begin'] = _dict.get('begin') - if 'end' in _dict: - args['end'] = _dict.get('end') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ElementLocations 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, 'begin') and self.begin is not None: - _dict['begin'] = self.begin - if hasattr(self, 'end') and self.end is not None: - _dict['end'] = self.end - 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 ElementLocations object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ElementLocations') -> 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: 'ElementLocations') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ElementPair(): - """ - Details of semantically aligned elements. - - :attr str document_label: (optional) The label of the document (that is, the - value of either the `file_1_label` or `file_2_label` parameters) in which the - element occurs. - :attr str text: (optional) The contents of the element. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr List[TypeLabelComparison] types: (optional) Description of the action - specified by the element and whom it affects. - :attr List[CategoryComparison] categories: (optional) List of functional - categories into which the element falls; in other words, the subject matter of - the element. - :attr List[Attribute] attributes: (optional) List of document attributes. - """ - - def __init__(self, - *, - document_label: str = None, - text: str = None, - location: 'Location' = None, - types: List['TypeLabelComparison'] = None, - categories: List['CategoryComparison'] = None, - attributes: List['Attribute'] = None) -> None: - """ - Initialize a ElementPair object. - - :param str document_label: (optional) The label of the document (that is, - the value of either the `file_1_label` or `file_2_label` parameters) in - which the element occurs. - :param str text: (optional) The contents of the element. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param List[TypeLabelComparison] types: (optional) Description of the - action specified by the element and whom it affects. - :param List[CategoryComparison] categories: (optional) List of functional - categories into which the element falls; in other words, the subject matter - of the element. - :param List[Attribute] attributes: (optional) List of document attributes. - """ - self.document_label = document_label - self.text = text - self.location = location - self.types = types - self.categories = categories - self.attributes = attributes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ElementPair': - """Initialize a ElementPair object from a json dictionary.""" - args = {} - if 'document_label' in _dict: - args['document_label'] = _dict.get('document_label') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'types' in _dict: - args['types'] = [ - TypeLabelComparison.from_dict(x) for x in _dict.get('types') - ] - if 'categories' in _dict: - args['categories'] = [ - CategoryComparison.from_dict(x) for x in _dict.get('categories') - ] - if 'attributes' in _dict: - args['attributes'] = [ - Attribute.from_dict(x) for x in _dict.get('attributes') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ElementPair 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, 'document_label') and self.document_label is not None: - _dict['document_label'] = self.document_label - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'types') and self.types is not None: - _dict['types'] = [x.to_dict() for x in self.types] - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x.to_dict() for x in self.categories] - if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x.to_dict() for x in self.attributes] - 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 ElementPair object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ElementPair') -> 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: 'ElementPair') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class FeedbackDataInput(): - """ - Feedback data for submission. - - :attr str feedback_type: The type of feedback. The only permitted value is - `element_classification`. - :attr ShortDoc document: (optional) Brief information about the input document. - :attr str model_id: (optional) An optional string identifying the model ID. The - only permitted value is `contracts`. - :attr str model_version: (optional) An optional string identifying the version - of the model used. - :attr Location location: The numeric location of the identified element in the - document, represented with two integers labeled `begin` and `end`. - :attr str text: The text on which to submit feedback. - :attr OriginalLabelsIn original_labels: The original labeling from the input - document, without the submitted feedback. - :attr UpdatedLabelsIn updated_labels: The updated labeling from the input - document, accounting for the submitted feedback. - """ - - def __init__(self, - feedback_type: str, - location: 'Location', - text: str, - original_labels: 'OriginalLabelsIn', - updated_labels: 'UpdatedLabelsIn', - *, - document: 'ShortDoc' = None, - model_id: str = None, - model_version: str = None) -> None: - """ - Initialize a FeedbackDataInput object. - - :param str feedback_type: The type of feedback. The only permitted value is - `element_classification`. - :param Location location: The numeric location of the identified element in - the document, represented with two integers labeled `begin` and `end`. - :param str text: The text on which to submit feedback. - :param OriginalLabelsIn original_labels: The original labeling from the - input document, without the submitted feedback. - :param UpdatedLabelsIn updated_labels: The updated labeling from the input - document, accounting for the submitted feedback. - :param ShortDoc document: (optional) Brief information about the input - document. - :param str model_id: (optional) An optional string identifying the model - ID. The only permitted value is `contracts`. - :param str model_version: (optional) An optional string identifying the - version of the model used. - """ - self.feedback_type = feedback_type - self.document = document - self.model_id = model_id - self.model_version = model_version - self.location = location - self.text = text - self.original_labels = original_labels - self.updated_labels = updated_labels - - @classmethod - def from_dict(cls, _dict: Dict) -> 'FeedbackDataInput': - """Initialize a FeedbackDataInput object from a json dictionary.""" - args = {} - if 'feedback_type' in _dict: - args['feedback_type'] = _dict.get('feedback_type') - else: - raise ValueError( - 'Required property \'feedback_type\' not present in FeedbackDataInput JSON' - ) - if 'document' in _dict: - args['document'] = ShortDoc.from_dict(_dict.get('document')) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - else: - raise ValueError( - 'Required property \'location\' not present in FeedbackDataInput JSON' - ) - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in FeedbackDataInput JSON' - ) - if 'original_labels' in _dict: - args['original_labels'] = OriginalLabelsIn.from_dict( - _dict.get('original_labels')) - else: - raise ValueError( - 'Required property \'original_labels\' not present in FeedbackDataInput JSON' - ) - if 'updated_labels' in _dict: - args['updated_labels'] = UpdatedLabelsIn.from_dict( - _dict.get('updated_labels')) - else: - raise ValueError( - 'Required property \'updated_labels\' not present in FeedbackDataInput JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a FeedbackDataInput 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, 'feedback_type') and self.feedback_type is not None: - _dict['feedback_type'] = self.feedback_type - if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document.to_dict() - if hasattr(self, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'model_version') and self.model_version is not None: - _dict['model_version'] = self.model_version - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'original_labels') and self.original_labels is not None: - _dict['original_labels'] = self.original_labels.to_dict() - if hasattr(self, 'updated_labels') and self.updated_labels is not None: - _dict['updated_labels'] = self.updated_labels.to_dict() - 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 FeedbackDataInput object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'FeedbackDataInput') -> 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: 'FeedbackDataInput') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class FeedbackDataOutput(): - """ - Information returned from the **Add Feedback** method. - - :attr str feedback_type: (optional) A string identifying the user adding the - feedback. The only permitted value is `element_classification`. - :attr ShortDoc document: (optional) Brief information about the input document. - :attr str model_id: (optional) An optional string identifying the model ID. The - only permitted value is `contracts`. - :attr str model_version: (optional) An optional string identifying the version - of the model used. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr str text: (optional) The text to which the feedback applies. - :attr OriginalLabelsOut original_labels: (optional) The original labeling from - the input document, without the submitted feedback. - :attr UpdatedLabelsOut updated_labels: (optional) The updated labeling from the - input document, accounting for the submitted feedback. - :attr Pagination pagination: (optional) Pagination details, if required by the - length of the output. - """ - - def __init__(self, - *, - feedback_type: str = None, - document: 'ShortDoc' = None, - model_id: str = None, - model_version: str = None, - location: 'Location' = None, - text: str = None, - original_labels: 'OriginalLabelsOut' = None, - updated_labels: 'UpdatedLabelsOut' = None, - pagination: 'Pagination' = None) -> None: - """ - Initialize a FeedbackDataOutput object. - - :param str feedback_type: (optional) A string identifying the user adding - the feedback. The only permitted value is `element_classification`. - :param ShortDoc document: (optional) Brief information about the input - document. - :param str model_id: (optional) An optional string identifying the model - ID. The only permitted value is `contracts`. - :param str model_version: (optional) An optional string identifying the - version of the model used. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param str text: (optional) The text to which the feedback applies. - :param OriginalLabelsOut original_labels: (optional) The original labeling - from the input document, without the submitted feedback. - :param UpdatedLabelsOut updated_labels: (optional) The updated labeling - from the input document, accounting for the submitted feedback. - :param Pagination pagination: (optional) Pagination details, if required by - the length of the output. - """ - self.feedback_type = feedback_type - self.document = document - self.model_id = model_id - self.model_version = model_version - self.location = location - self.text = text - self.original_labels = original_labels - self.updated_labels = updated_labels - self.pagination = pagination - - @classmethod - def from_dict(cls, _dict: Dict) -> 'FeedbackDataOutput': - """Initialize a FeedbackDataOutput object from a json dictionary.""" - args = {} - if 'feedback_type' in _dict: - args['feedback_type'] = _dict.get('feedback_type') - if 'document' in _dict: - args['document'] = ShortDoc.from_dict(_dict.get('document')) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'original_labels' in _dict: - args['original_labels'] = OriginalLabelsOut.from_dict( - _dict.get('original_labels')) - if 'updated_labels' in _dict: - args['updated_labels'] = UpdatedLabelsOut.from_dict( - _dict.get('updated_labels')) - if 'pagination' in _dict: - args['pagination'] = Pagination.from_dict(_dict.get('pagination')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a FeedbackDataOutput 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, 'feedback_type') and self.feedback_type is not None: - _dict['feedback_type'] = self.feedback_type - if hasattr(self, 'document') and self.document is not None: - _dict['document'] = self.document.to_dict() - if hasattr(self, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'model_version') and self.model_version is not None: - _dict['model_version'] = self.model_version - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'original_labels') and self.original_labels is not None: - _dict['original_labels'] = self.original_labels.to_dict() - if hasattr(self, 'updated_labels') and self.updated_labels is not None: - _dict['updated_labels'] = self.updated_labels.to_dict() - if hasattr(self, 'pagination') and self.pagination is not None: - _dict['pagination'] = self.pagination.to_dict() - 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 FeedbackDataOutput object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'FeedbackDataOutput') -> 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: 'FeedbackDataOutput') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class FeedbackDeleted(): - """ - The status and message of the deletion request. - - :attr int status: (optional) HTTP return code. - :attr str message: (optional) Status message returned from the service. - """ - - def __init__(self, *, status: int = None, message: str = None) -> None: - """ - Initialize a FeedbackDeleted object. - - :param int status: (optional) HTTP return code. - :param str message: (optional) Status message returned from the service. - """ - self.status = status - self.message = message - - @classmethod - def from_dict(cls, _dict: Dict) -> 'FeedbackDeleted': - """Initialize a FeedbackDeleted object from a json dictionary.""" - args = {} - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'message' in _dict: - args['message'] = _dict.get('message') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a FeedbackDeleted 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, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message - 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 FeedbackDeleted object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'FeedbackDeleted') -> 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: 'FeedbackDeleted') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class FeedbackList(): - """ - The results of a successful **List Feedback** request for all feedback. - - :attr List[GetFeedback] feedback: (optional) A list of all feedback for the - document. - """ - - def __init__(self, *, feedback: List['GetFeedback'] = None) -> None: - """ - Initialize a FeedbackList object. - - :param List[GetFeedback] feedback: (optional) A list of all feedback for - the document. - """ - self.feedback = feedback - - @classmethod - def from_dict(cls, _dict: Dict) -> 'FeedbackList': - """Initialize a FeedbackList object from a json dictionary.""" - args = {} - if 'feedback' in _dict: - args['feedback'] = [ - GetFeedback.from_dict(x) for x in _dict.get('feedback') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a FeedbackList 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, 'feedback') and self.feedback is not None: - _dict['feedback'] = [x.to_dict() for x in self.feedback] - 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 FeedbackList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'FeedbackList') -> 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: 'FeedbackList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class FeedbackReturn(): - """ - Information about the document and the submitted feedback. - - :attr str feedback_id: (optional) The unique ID of the feedback object. - :attr str user_id: (optional) An optional string identifying the person - submitting feedback. - :attr str comment: (optional) An optional comment from the person submitting the - feedback. - :attr datetime created: (optional) Timestamp listing the creation time of the - feedback submission. - :attr FeedbackDataOutput feedback_data: (optional) Information returned from the - **Add Feedback** method. - """ - - def __init__(self, - *, - feedback_id: str = None, - user_id: str = None, - comment: str = None, - created: datetime = None, - feedback_data: 'FeedbackDataOutput' = None) -> None: - """ - Initialize a FeedbackReturn object. - - :param str feedback_id: (optional) The unique ID of the feedback object. - :param str user_id: (optional) An optional string identifying the person - submitting feedback. - :param str comment: (optional) An optional comment from the person - submitting the feedback. - :param datetime created: (optional) Timestamp listing the creation time of - the feedback submission. - :param FeedbackDataOutput feedback_data: (optional) Information returned - from the **Add Feedback** method. - """ - self.feedback_id = feedback_id - self.user_id = user_id - self.comment = comment - self.created = created - self.feedback_data = feedback_data - - @classmethod - def from_dict(cls, _dict: Dict) -> 'FeedbackReturn': - """Initialize a FeedbackReturn object from a json dictionary.""" - args = {} - if 'feedback_id' in _dict: - args['feedback_id'] = _dict.get('feedback_id') - if 'user_id' in _dict: - args['user_id'] = _dict.get('user_id') - if 'comment' in _dict: - args['comment'] = _dict.get('comment') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'feedback_data' in _dict: - args['feedback_data'] = FeedbackDataOutput.from_dict( - _dict.get('feedback_data')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a FeedbackReturn 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, 'feedback_id') and self.feedback_id is not None: - _dict['feedback_id'] = self.feedback_id - if hasattr(self, 'user_id') and self.user_id is not None: - _dict['user_id'] = self.user_id - if hasattr(self, 'comment') and self.comment is not None: - _dict['comment'] = self.comment - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'feedback_data') and self.feedback_data is not None: - _dict['feedback_data'] = self.feedback_data.to_dict() - 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 FeedbackReturn object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'FeedbackReturn') -> 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: 'FeedbackReturn') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class GetFeedback(): - """ - The results of a successful **Get Feedback** request for a single feedback entry. - - :attr str feedback_id: (optional) A string uniquely identifying the feedback - entry. - :attr datetime created: (optional) A timestamp identifying the creation time of - the feedback entry. - :attr str comment: (optional) A string containing the user's comment about the - feedback entry. - :attr FeedbackDataOutput feedback_data: (optional) Information returned from the - **Add Feedback** method. - """ - - def __init__(self, - *, - feedback_id: str = None, - created: datetime = None, - comment: str = None, - feedback_data: 'FeedbackDataOutput' = None) -> None: - """ - Initialize a GetFeedback object. - - :param str feedback_id: (optional) A string uniquely identifying the - feedback entry. - :param datetime created: (optional) A timestamp identifying the creation - time of the feedback entry. - :param str comment: (optional) A string containing the user's comment about - the feedback entry. - :param FeedbackDataOutput feedback_data: (optional) Information returned - from the **Add Feedback** method. - """ - self.feedback_id = feedback_id - self.created = created - self.comment = comment - self.feedback_data = feedback_data - - @classmethod - def from_dict(cls, _dict: Dict) -> 'GetFeedback': - """Initialize a GetFeedback object from a json dictionary.""" - args = {} - if 'feedback_id' in _dict: - args['feedback_id'] = _dict.get('feedback_id') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'comment' in _dict: - args['comment'] = _dict.get('comment') - if 'feedback_data' in _dict: - args['feedback_data'] = FeedbackDataOutput.from_dict( - _dict.get('feedback_data')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a GetFeedback 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, 'feedback_id') and self.feedback_id is not None: - _dict['feedback_id'] = self.feedback_id - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'comment') and self.comment is not None: - _dict['comment'] = self.comment - if hasattr(self, 'feedback_data') and self.feedback_data is not None: - _dict['feedback_data'] = self.feedback_data.to_dict() - 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 GetFeedback object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'GetFeedback') -> 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: 'GetFeedback') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class HTMLReturn(): - """ - The HTML converted from an input document. - - :attr str num_pages: (optional) The number of pages in the input document. - :attr str author: (optional) The author of the input document, if identified. - :attr str publication_date: (optional) The publication date of the input - document, if identified. - :attr str title: (optional) The title of the input document, if identified. - :attr str html: (optional) The HTML version of the input document. - """ - - def __init__(self, - *, - num_pages: str = None, - author: str = None, - publication_date: str = None, - title: str = None, - html: str = None) -> None: - """ - Initialize a HTMLReturn object. - - :param str num_pages: (optional) The number of pages in the input document. - :param str author: (optional) The author of the input document, if - identified. - :param str publication_date: (optional) The publication date of the input - document, if identified. - :param str title: (optional) The title of the input document, if - identified. - :param str html: (optional) The HTML version of the input document. - """ - self.num_pages = num_pages - self.author = author - self.publication_date = publication_date - self.title = title - self.html = html - - @classmethod - def from_dict(cls, _dict: Dict) -> 'HTMLReturn': - """Initialize a HTMLReturn object from a json dictionary.""" - args = {} - if 'num_pages' in _dict: - args['num_pages'] = _dict.get('num_pages') - if 'author' in _dict: - args['author'] = _dict.get('author') - if 'publication_date' in _dict: - args['publication_date'] = _dict.get('publication_date') - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'html' in _dict: - args['html'] = _dict.get('html') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a HTMLReturn 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, 'num_pages') and self.num_pages is not None: - _dict['num_pages'] = self.num_pages - if hasattr(self, 'author') and self.author is not None: - _dict['author'] = self.author - if hasattr(self, - 'publication_date') and self.publication_date is not None: - _dict['publication_date'] = self.publication_date - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'html') and self.html is not None: - _dict['html'] = self.html - 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 HTMLReturn object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'HTMLReturn') -> 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: 'HTMLReturn') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Interpretation(): - """ - The details of the normalized text, if applicable. This element is optional; it is - returned only if normalized text exists. - - :attr str value: (optional) The value that was located in the normalized text. - :attr float numeric_value: (optional) An integer or float expressing the numeric - value of the `value` key. - :attr str unit: (optional) A string listing the unit of the value that was found - in the normalized text. - **Note:** The value of `unit` is the [ISO-4217 currency - code](https://www.iso.org/iso-4217-currency-codes.html) identified for the - currency amount (for example, `USD` or `EUR`). If the service cannot - disambiguate a currency symbol (for example, `$` or `£`), the value of `unit` - contains the ambiguous symbol as-is. - """ - - def __init__(self, - *, - value: str = None, - numeric_value: float = None, - unit: str = None) -> None: - """ - Initialize a Interpretation object. - - :param str value: (optional) The value that was located in the normalized - text. - :param float numeric_value: (optional) An integer or float expressing the - numeric value of the `value` key. - :param str unit: (optional) A string listing the unit of the value that was - found in the normalized text. - **Note:** The value of `unit` is the [ISO-4217 currency - code](https://www.iso.org/iso-4217-currency-codes.html) identified for the - currency amount (for example, `USD` or `EUR`). If the service cannot - disambiguate a currency symbol (for example, `$` or `£`), the value of - `unit` contains the ambiguous symbol as-is. - """ - self.value = value - self.numeric_value = numeric_value - self.unit = unit - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Interpretation': - """Initialize a Interpretation object from a json dictionary.""" - args = {} - if 'value' in _dict: - args['value'] = _dict.get('value') - if 'numeric_value' in _dict: - args['numeric_value'] = _dict.get('numeric_value') - if 'unit' in _dict: - args['unit'] = _dict.get('unit') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Interpretation 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, 'numeric_value') and self.numeric_value is not None: - _dict['numeric_value'] = self.numeric_value - if hasattr(self, 'unit') and self.unit is not None: - _dict['unit'] = self.unit - 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 Interpretation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Interpretation') -> 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: 'Interpretation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Key(): - """ - A key in a key-value pair. - - :attr str cell_id: (optional) The unique ID of the key in the table. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr str text: (optional) The text content of the table cell without HTML - markup. - """ - - def __init__(self, - *, - cell_id: str = None, - location: 'Location' = None, - text: str = None) -> None: - """ - Initialize a Key object. - - :param str cell_id: (optional) The unique ID of the key in the table. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param str text: (optional) The text content of the table cell without HTML - markup. - """ - self.cell_id = cell_id - self.location = location - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Key': - """Initialize a Key object from a json dictionary.""" - args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Key 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, 'cell_id') and self.cell_id is not None: - _dict['cell_id'] = self.cell_id - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - 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 Key object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Key') -> 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: 'Key') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class KeyValuePair(): - """ - Key-value pairs detected across cell boundaries. - - :attr Key key: (optional) A key in a key-value pair. - :attr List[Value] value: (optional) A list of values in a key-value pair. - """ - - def __init__(self, - *, - key: 'Key' = None, - value: List['Value'] = None) -> None: - """ - Initialize a KeyValuePair object. - - :param Key key: (optional) A key in a key-value pair. - :param List[Value] value: (optional) A list of values in a key-value pair. - """ - self.key = key - self.value = value - - @classmethod - def from_dict(cls, _dict: Dict) -> 'KeyValuePair': - """Initialize a KeyValuePair object from a json dictionary.""" - args = {} - if 'key' in _dict: - args['key'] = Key.from_dict(_dict.get('key')) - if 'value' in _dict: - args['value'] = [Value.from_dict(x) for x in _dict.get('value')] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a KeyValuePair 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, 'key') and self.key is not None: - _dict['key'] = self.key.to_dict() - if hasattr(self, 'value') and self.value is not None: - _dict['value'] = [x.to_dict() for x in self.value] - 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 KeyValuePair object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'KeyValuePair') -> 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: 'KeyValuePair') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Label(): - """ - A pair of `nature` and `party` objects. The `nature` object identifies the effect of - the element on the identified `party`, and the `party` object identifies the affected - party. - - :attr str nature: The identified `nature` of the element. - :attr str party: The identified `party` of the element. - """ - - def __init__(self, nature: str, party: str) -> None: - """ - Initialize a Label object. - - :param str nature: The identified `nature` of the element. - :param str party: The identified `party` of the element. - """ - self.nature = nature - self.party = party - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Label': - """Initialize a Label object from a json dictionary.""" - args = {} - if 'nature' in _dict: - args['nature'] = _dict.get('nature') - else: - raise ValueError( - 'Required property \'nature\' not present in Label JSON') - if 'party' in _dict: - args['party'] = _dict.get('party') - else: - raise ValueError( - 'Required property \'party\' not present in Label JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Label 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, 'nature') and self.nature is not None: - _dict['nature'] = self.nature - if hasattr(self, 'party') and self.party is not None: - _dict['party'] = self.party - 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 Label object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Label') -> 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: 'Label') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class LeadingSentence(): - """ - The leading sentences in a section or subsection of the input document. - - :attr str text: (optional) The text of the leading sentence. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr List[ElementLocations] element_locations: (optional) An array of - `location` objects that lists the locations of detected leading sentences. - """ - - def __init__(self, - *, - text: str = None, - location: 'Location' = None, - element_locations: List['ElementLocations'] = None) -> None: - """ - Initialize a LeadingSentence object. - - :param str text: (optional) The text of the leading sentence. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param List[ElementLocations] element_locations: (optional) An array of - `location` objects that lists the locations of detected leading sentences. - """ - self.text = text - self.location = location - self.element_locations = element_locations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'LeadingSentence': - """Initialize a LeadingSentence object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'element_locations' in _dict: - args['element_locations'] = [ - ElementLocations.from_dict(x) - for x in _dict.get('element_locations') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a LeadingSentence 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, - 'element_locations') and self.element_locations is not None: - _dict['element_locations'] = [ - x.to_dict() for x in self.element_locations - ] - 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 LeadingSentence object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'LeadingSentence') -> 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: 'LeadingSentence') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Location(): - """ - The numeric location of the identified element in the document, represented with two - integers labeled `begin` and `end`. - - :attr int begin: The element's `begin` index. - :attr int end: The element's `end` index. - """ - - def __init__(self, begin: int, end: int) -> None: - """ - Initialize a Location object. - - :param int begin: The element's `begin` index. - :param int end: The element's `end` index. - """ - self.begin = begin - self.end = end - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Location': - """Initialize a Location object from a json dictionary.""" - args = {} - if 'begin' in _dict: - args['begin'] = _dict.get('begin') - else: - raise ValueError( - 'Required property \'begin\' not present in Location JSON') - if 'end' in _dict: - args['end'] = _dict.get('end') - else: - raise ValueError( - 'Required property \'end\' not present in Location JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Location 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, 'begin') and self.begin is not None: - _dict['begin'] = self.begin - if hasattr(self, 'end') and self.end is not None: - _dict['end'] = self.end - 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 Location object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Location') -> 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: 'Location') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Mention(): - """ - A mention of a party. - - :attr str text: (optional) The name of the party. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - text: str = None, - location: 'Location' = None) -> None: - """ - Initialize a Mention object. - - :param str text: (optional) The name of the party. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.text = text - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Mention': - """Initialize a Mention object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Mention 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 Mention object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Mention') -> 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: 'Mention') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class OriginalLabelsIn(): - """ - The original labeling from the input document, without the submitted feedback. - - :attr List[TypeLabel] types: Description of the action specified by the element - and whom it affects. - :attr List[Category] categories: List of functional categories into which the - element falls; in other words, the subject matter of the element. - """ - - def __init__(self, types: List['TypeLabel'], - categories: List['Category']) -> None: - """ - Initialize a OriginalLabelsIn object. - - :param List[TypeLabel] types: Description of the action specified by the - element and whom it affects. - :param List[Category] categories: List of functional categories into which - the element falls; in other words, the subject matter of the element. - """ - self.types = types - self.categories = categories - - @classmethod - def from_dict(cls, _dict: Dict) -> 'OriginalLabelsIn': - """Initialize a OriginalLabelsIn object from a json dictionary.""" - args = {} - if 'types' in _dict: - args['types'] = [TypeLabel.from_dict(x) for x in _dict.get('types')] - else: - raise ValueError( - 'Required property \'types\' not present in OriginalLabelsIn JSON' - ) - if 'categories' in _dict: - args['categories'] = [ - Category.from_dict(x) for x in _dict.get('categories') - ] - else: - raise ValueError( - 'Required property \'categories\' not present in OriginalLabelsIn JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a OriginalLabelsIn 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, 'types') and self.types is not None: - _dict['types'] = [x.to_dict() for x in self.types] - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x.to_dict() for x in self.categories] - 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 OriginalLabelsIn object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'OriginalLabelsIn') -> 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: 'OriginalLabelsIn') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class OriginalLabelsOut(): - """ - The original labeling from the input document, without the submitted feedback. - - :attr List[TypeLabel] types: (optional) Description of the action specified by - the element and whom it affects. - :attr List[Category] categories: (optional) List of functional categories into - which the element falls; in other words, the subject matter of the element. - """ - - def __init__(self, - *, - types: List['TypeLabel'] = None, - categories: List['Category'] = None) -> None: - """ - Initialize a OriginalLabelsOut object. - - :param List[TypeLabel] types: (optional) Description of the action - specified by the element and whom it affects. - :param List[Category] categories: (optional) List of functional categories - into which the element falls; in other words, the subject matter of the - element. - """ - self.types = types - self.categories = categories - - @classmethod - def from_dict(cls, _dict: Dict) -> 'OriginalLabelsOut': - """Initialize a OriginalLabelsOut object from a json dictionary.""" - args = {} - if 'types' in _dict: - args['types'] = [TypeLabel.from_dict(x) for x in _dict.get('types')] - if 'categories' in _dict: - args['categories'] = [ - Category.from_dict(x) for x in _dict.get('categories') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a OriginalLabelsOut 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, 'types') and self.types is not None: - _dict['types'] = [x.to_dict() for x in self.types] - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x.to_dict() for x in self.categories] - 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 OriginalLabelsOut object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'OriginalLabelsOut') -> 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: 'OriginalLabelsOut') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Pagination(): - """ - Pagination details, if required by the length of the output. - - :attr str refresh_cursor: (optional) A token identifying the current page of - results. - :attr str next_cursor: (optional) A token identifying the next page of results. - :attr str refresh_url: (optional) The URL that returns the current page of - results. - :attr str next_url: (optional) The URL that returns the next page of results. - :attr int total: (optional) Reserved for future use. - """ - - def __init__(self, - *, - refresh_cursor: str = None, - next_cursor: str = None, - refresh_url: str = None, - next_url: str = None, - total: int = None) -> None: - """ - Initialize a Pagination object. - - :param str refresh_cursor: (optional) A token identifying the current page - of results. - :param str next_cursor: (optional) A token identifying the next page of - results. - :param str refresh_url: (optional) The URL that returns the current page of - results. - :param str next_url: (optional) The URL that returns the next page of - results. - :param int total: (optional) Reserved for future use. - """ - self.refresh_cursor = refresh_cursor - self.next_cursor = next_cursor - self.refresh_url = refresh_url - self.next_url = next_url - self.total = total - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Pagination': - """Initialize a Pagination object from a json dictionary.""" - args = {} - if 'refresh_cursor' in _dict: - args['refresh_cursor'] = _dict.get('refresh_cursor') - if 'next_cursor' in _dict: - args['next_cursor'] = _dict.get('next_cursor') - if 'refresh_url' in _dict: - args['refresh_url'] = _dict.get('refresh_url') - if 'next_url' in _dict: - args['next_url'] = _dict.get('next_url') - if 'total' in _dict: - args['total'] = _dict.get('total') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Pagination 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, 'refresh_cursor') and self.refresh_cursor is not None: - _dict['refresh_cursor'] = self.refresh_cursor - if hasattr(self, 'next_cursor') and self.next_cursor is not None: - _dict['next_cursor'] = self.next_cursor - if hasattr(self, 'refresh_url') and self.refresh_url is not None: - _dict['refresh_url'] = self.refresh_url - if hasattr(self, 'next_url') and self.next_url is not None: - _dict['next_url'] = self.next_url - if hasattr(self, 'total') and self.total is not None: - _dict['total'] = self.total - 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 Pagination object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Pagination') -> 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: 'Pagination') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Paragraphs(): - """ - The locations of each paragraph in the input document. - - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, *, location: 'Location' = None) -> None: - """ - Initialize a Paragraphs object. - - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Paragraphs': - """Initialize a Paragraphs object from a json dictionary.""" - args = {} - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Paragraphs 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, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 Paragraphs object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Paragraphs') -> 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: 'Paragraphs') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Parties(): - """ - A party and its corresponding role, including address and contact information if - identified. - - :attr str party: (optional) The normalized form of the party's name. - :attr str role: (optional) A string identifying the party's role. - :attr str importance: (optional) A string that identifies the importance of the - party. - :attr List[Address] addresses: (optional) A list of the party's address or - addresses. - :attr List[Contact] contacts: (optional) A list of the names and roles of - contacts identified in the input document. - :attr List[Mention] mentions: (optional) A list of the party's mentions in the - input document. - """ - - def __init__(self, - *, - party: str = None, - role: str = None, - importance: str = None, - addresses: List['Address'] = None, - contacts: List['Contact'] = None, - mentions: List['Mention'] = None) -> None: - """ - Initialize a Parties object. - - :param str party: (optional) The normalized form of the party's name. - :param str role: (optional) A string identifying the party's role. - :param str importance: (optional) A string that identifies the importance - of the party. - :param List[Address] addresses: (optional) A list of the party's address or - addresses. - :param List[Contact] contacts: (optional) A list of the names and roles of - contacts identified in the input document. - :param List[Mention] mentions: (optional) A list of the party's mentions in - the input document. - """ - self.party = party - self.role = role - self.importance = importance - self.addresses = addresses - self.contacts = contacts - self.mentions = mentions - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Parties': - """Initialize a Parties object from a json dictionary.""" - args = {} - if 'party' in _dict: - args['party'] = _dict.get('party') - if 'role' in _dict: - args['role'] = _dict.get('role') - if 'importance' in _dict: - args['importance'] = _dict.get('importance') - if 'addresses' in _dict: - args['addresses'] = [ - Address.from_dict(x) for x in _dict.get('addresses') - ] - if 'contacts' in _dict: - args['contacts'] = [ - Contact.from_dict(x) for x in _dict.get('contacts') - ] - if 'mentions' in _dict: - args['mentions'] = [ - Mention.from_dict(x) for x in _dict.get('mentions') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Parties 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, 'party') and self.party is not None: - _dict['party'] = self.party - if hasattr(self, 'role') and self.role is not None: - _dict['role'] = self.role - if hasattr(self, 'importance') and self.importance is not None: - _dict['importance'] = self.importance - if hasattr(self, 'addresses') and self.addresses is not None: - _dict['addresses'] = [x.to_dict() for x in self.addresses] - if hasattr(self, 'contacts') and self.contacts is not None: - _dict['contacts'] = [x.to_dict() for x in self.contacts] - if hasattr(self, 'mentions') and self.mentions is not None: - _dict['mentions'] = [x.to_dict() for x in self.mentions] - 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 Parties object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Parties') -> 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: 'Parties') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ImportanceEnum(str, Enum): - """ - A string that identifies the importance of the party. - """ - PRIMARY = 'Primary' - UNKNOWN = 'Unknown' - - -class PaymentTerms(): - """ - The document's payment duration or durations. - - :attr str confidence_level: (optional) The confidence level in the - identification of the payment term. - :attr str text: (optional) The payment term (duration). - :attr str text_normalized: (optional) The normalized form of the payment term, - which is listed as a string. This element is optional; it is returned only if - normalized text exists. - :attr Interpretation interpretation: (optional) The details of the normalized - text, if applicable. This element is optional; it is returned only if normalized - text exists. - :attr List[str] provenance_ids: (optional) Hashed values that you can send to - IBM to provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - confidence_level: str = None, - text: str = None, - text_normalized: str = None, - interpretation: 'Interpretation' = None, - provenance_ids: List[str] = None, - location: 'Location' = None) -> None: - """ - Initialize a PaymentTerms object. - - :param str confidence_level: (optional) The confidence level in the - identification of the payment term. - :param str text: (optional) The payment term (duration). - :param str text_normalized: (optional) The normalized form of the payment - term, which is listed as a string. This element is optional; it is returned - only if normalized text exists. - :param Interpretation interpretation: (optional) The details of the - normalized text, if applicable. This element is optional; it is returned - only if normalized text exists. - :param List[str] provenance_ids: (optional) Hashed values that you can send - to IBM to provide feedback or receive support. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.confidence_level = confidence_level - self.text = text - self.text_normalized = text_normalized - self.interpretation = interpretation - self.provenance_ids = provenance_ids - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'PaymentTerms': - """Initialize a PaymentTerms object from a json dictionary.""" - args = {} - if 'confidence_level' in _dict: - args['confidence_level'] = _dict.get('confidence_level') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'interpretation' in _dict: - args['interpretation'] = Interpretation.from_dict( - _dict.get('interpretation')) - if 'provenance_ids' in _dict: - args['provenance_ids'] = _dict.get('provenance_ids') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a PaymentTerms 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, - 'confidence_level') and self.confidence_level is not None: - _dict['confidence_level'] = self.confidence_level - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - if hasattr(self, 'interpretation') and self.interpretation is not None: - _dict['interpretation'] = self.interpretation.to_dict() - if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: - _dict['provenance_ids'] = self.provenance_ids - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 PaymentTerms object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'PaymentTerms') -> 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: 'PaymentTerms') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ConfidenceLevelEnum(str, Enum): - """ - The confidence level in the identification of the payment term. - """ - HIGH = 'High' - MEDIUM = 'Medium' - LOW = 'Low' - - -class RowHeaders(): - """ - Row-level cells, each applicable as a header to other cells in the same row as itself, - of the current table. - - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr str text: (optional) The textual contents of this cell from the input - document without associated markup content. - :attr str text_normalized: (optional) If you provide customization input, the - normalized version of the cell text according to the customization; otherwise, - the same value as `text`. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` - location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` - location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. - """ - - def __init__(self, - *, - cell_id: str = None, - location: 'Location' = None, - text: str = None, - text_normalized: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: - """ - Initialize a RowHeaders object. - - :param str cell_id: (optional) The unique ID of the cell in the current - table. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param str text: (optional) The textual contents of this cell from the - input document without associated markup content. - :param str text_normalized: (optional) If you provide customization input, - the normalized version of the cell text according to the customization; - otherwise, the same value as `text`. - :param int row_index_begin: (optional) The `begin` index of this cell's - `row` location in the current table. - :param int row_index_end: (optional) The `end` index of this cell's `row` - location in the current table. - :param int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :param int column_index_end: (optional) The `end` index of this cell's - `column` location in the current table. - """ - self.cell_id = cell_id - self.location = location - self.text = text - self.text_normalized = text_normalized - self.row_index_begin = row_index_begin - self.row_index_end = row_index_end - self.column_index_begin = column_index_begin - self.column_index_end = column_index_end - - @classmethod - def from_dict(cls, _dict: Dict) -> 'RowHeaders': - """Initialize a RowHeaders object from a json dictionary.""" - args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a RowHeaders 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, 'cell_id') and self.cell_id is not None: - _dict['cell_id'] = self.cell_id - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - if hasattr(self, - 'row_index_begin') and self.row_index_begin is not None: - _dict['row_index_begin'] = self.row_index_begin - if hasattr(self, 'row_index_end') and self.row_index_end is not None: - _dict['row_index_end'] = self.row_index_end - if hasattr( - self, - 'column_index_begin') and self.column_index_begin is not None: - _dict['column_index_begin'] = self.column_index_begin - if hasattr(self, - 'column_index_end') and self.column_index_end is not None: - _dict['column_index_end'] = self.column_index_end - 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 RowHeaders object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'RowHeaders') -> 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: 'RowHeaders') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SectionTitle(): - """ - The table's section title, if identified. - - :attr str text: (optional) The text of the section title, if identified. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - text: str = None, - location: 'Location' = None) -> None: - """ - Initialize a SectionTitle object. - - :param str text: (optional) The text of the section title, if identified. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.text = text - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SectionTitle': - """Initialize a SectionTitle object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SectionTitle 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 SectionTitle object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SectionTitle') -> 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: 'SectionTitle') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SectionTitles(): - """ - An array containing one object per section or subsection detected in the input - document. Sections and subsections are not nested; instead, they are flattened out and - can be placed back in order by using the `begin` and `end` values of the element and - the `level` value of the section. - - :attr str text: (optional) The text of the section title, if identified. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr int level: (optional) An integer indicating the level at which the section - is located in the input document. For example, `1` represents a top-level - section, `2` represents a subsection within the level `1` section, and so forth. - :attr List[ElementLocations] element_locations: (optional) An array of - `location` objects that lists the locations of detected section titles. - """ - - def __init__(self, - *, - text: str = None, - location: 'Location' = None, - level: int = None, - element_locations: List['ElementLocations'] = None) -> None: - """ - Initialize a SectionTitles object. - - :param str text: (optional) The text of the section title, if identified. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param int level: (optional) An integer indicating the level at which the - section is located in the input document. For example, `1` represents a - top-level section, `2` represents a subsection within the level `1` - section, and so forth. - :param List[ElementLocations] element_locations: (optional) An array of - `location` objects that lists the locations of detected section titles. - """ - self.text = text - self.location = location - self.level = level - self.element_locations = element_locations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SectionTitles': - """Initialize a SectionTitles object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'level' in _dict: - args['level'] = _dict.get('level') - if 'element_locations' in _dict: - args['element_locations'] = [ - ElementLocations.from_dict(x) - for x in _dict.get('element_locations') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SectionTitles 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'level') and self.level is not None: - _dict['level'] = self.level - if hasattr(self, - 'element_locations') and self.element_locations is not None: - _dict['element_locations'] = [ - x.to_dict() for x in self.element_locations - ] - 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 SectionTitles object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SectionTitles') -> 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: 'SectionTitles') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ShortDoc(): - """ - Brief information about the input document. - - :attr str title: (optional) The title of the input document, if identified. - :attr str hash: (optional) The MD5 hash of the input document. - """ - - def __init__(self, *, title: str = None, hash: str = None) -> None: - """ - Initialize a ShortDoc object. - - :param str title: (optional) The title of the input document, if - identified. - :param str hash: (optional) The MD5 hash of the input document. - """ - self.title = title - self.hash = hash - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ShortDoc': - """Initialize a ShortDoc object from a json dictionary.""" - args = {} - if 'title' in _dict: - args['title'] = _dict.get('title') - if 'hash' in _dict: - args['hash'] = _dict.get('hash') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ShortDoc 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, 'title') and self.title is not None: - _dict['title'] = self.title - if hasattr(self, 'hash') and self.hash is not None: - _dict['hash'] = self.hash - 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 ShortDoc object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ShortDoc') -> 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: 'ShortDoc') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableHeaders(): - """ - The contents of the current table's header. - - :attr str cell_id: (optional) The unique ID of the cell in the current table. - :attr object location: (optional) The location of the table header cell in the - current table as defined by its `begin` and `end` offsets, respectfully, in the - input document. - :attr str text: (optional) The textual contents of the cell from the input - document without associated markup content. - :attr int row_index_begin: (optional) The `begin` index of this cell's `row` - location in the current table. - :attr int row_index_end: (optional) The `end` index of this cell's `row` - location in the current table. - :attr int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :attr int column_index_end: (optional) The `end` index of this cell's `column` - location in the current table. - """ - - def __init__(self, - *, - cell_id: str = None, - location: object = None, - text: str = None, - row_index_begin: int = None, - row_index_end: int = None, - column_index_begin: int = None, - column_index_end: int = None) -> None: - """ - Initialize a TableHeaders object. - - :param str cell_id: (optional) The unique ID of the cell in the current - table. - :param object location: (optional) The location of the table header cell in - the current table as defined by its `begin` and `end` offsets, - respectfully, in the input document. - :param str text: (optional) The textual contents of the cell from the input - document without associated markup content. - :param int row_index_begin: (optional) The `begin` index of this cell's - `row` location in the current table. - :param int row_index_end: (optional) The `end` index of this cell's `row` - location in the current table. - :param int column_index_begin: (optional) The `begin` index of this cell's - `column` location in the current table. - :param int column_index_end: (optional) The `end` index of this cell's - `column` location in the current table. - """ - self.cell_id = cell_id - self.location = location - self.text = text - self.row_index_begin = row_index_begin - self.row_index_end = row_index_end - self.column_index_begin = column_index_begin - self.column_index_end = column_index_end - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableHeaders': - """Initialize a TableHeaders object from a json dictionary.""" - args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = _dict.get('location') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'row_index_begin' in _dict: - args['row_index_begin'] = _dict.get('row_index_begin') - if 'row_index_end' in _dict: - args['row_index_end'] = _dict.get('row_index_end') - if 'column_index_begin' in _dict: - args['column_index_begin'] = _dict.get('column_index_begin') - if 'column_index_end' in _dict: - args['column_index_end'] = _dict.get('column_index_end') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableHeaders 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, 'cell_id') and self.cell_id is not None: - _dict['cell_id'] = self.cell_id - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'row_index_begin') and self.row_index_begin is not None: - _dict['row_index_begin'] = self.row_index_begin - if hasattr(self, 'row_index_end') and self.row_index_end is not None: - _dict['row_index_end'] = self.row_index_end - if hasattr( - self, - 'column_index_begin') and self.column_index_begin is not None: - _dict['column_index_begin'] = self.column_index_begin - if hasattr(self, - 'column_index_end') and self.column_index_end is not None: - _dict['column_index_end'] = self.column_index_end - 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 TableHeaders object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableHeaders') -> 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: 'TableHeaders') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableReturn(): - """ - The analysis of the document's tables. - - :attr DocInfo document: (optional) Information about the parsed input document. - :attr str model_id: (optional) The ID of the model used to extract the table - contents. The value for table extraction is `tables`. - :attr str model_version: (optional) The version of the `tables` model ID. - :attr List[Tables] tables: (optional) Definitions of the tables identified in - the input document. - """ - - def __init__(self, - *, - document: 'DocInfo' = None, - model_id: str = None, - model_version: str = None, - tables: List['Tables'] = None) -> None: - """ - Initialize a TableReturn object. - - :param DocInfo document: (optional) Information about the parsed input - document. - :param str model_id: (optional) The ID of the model used to extract the - table contents. The value for table extraction is `tables`. - :param str model_version: (optional) The version of the `tables` model ID. - :param List[Tables] tables: (optional) Definitions of the tables identified - in the input document. - """ - self.document = document - self.model_id = model_id - self.model_version = model_version - self.tables = tables - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableReturn': - """Initialize a TableReturn object from a json dictionary.""" - args = {} - if 'document' in _dict: - args['document'] = DocInfo.from_dict(_dict.get('document')) - if 'model_id' in _dict: - args['model_id'] = _dict.get('model_id') - if 'model_version' in _dict: - args['model_version'] = _dict.get('model_version') - if 'tables' in _dict: - args['tables'] = [Tables.from_dict(x) for x in _dict.get('tables')] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableReturn 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, 'document') and self.document is not None: - _dict['document'] = self.document.to_dict() - if hasattr(self, 'model_id') and self.model_id is not None: - _dict['model_id'] = self.model_id - if hasattr(self, 'model_version') and self.model_version is not None: - _dict['model_version'] = self.model_version - if hasattr(self, 'tables') and self.tables is not None: - _dict['tables'] = [x.to_dict() for x in self.tables] - 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 TableReturn object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableReturn') -> 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: 'TableReturn') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TableTitle(): - """ - If identified, the title or caption of the current table of the form `Table x.: ...`. - Empty when no title is identified. When exposed, the `title` is also excluded from the - `contexts` array of the same table. - - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr str text: (optional) The text of the identified table title or caption. - """ - - def __init__(self, - *, - location: 'Location' = None, - text: str = None) -> None: - """ - Initialize a TableTitle object. - - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param str text: (optional) The text of the identified table title or - caption. - """ - self.location = location - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TableTitle': - """Initialize a TableTitle object from a json dictionary.""" - args = {} - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TableTitle 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, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - 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 TableTitle object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TableTitle') -> 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: 'TableTitle') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Tables(): - """ - The contents of the tables extracted from a document. - - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr str text: (optional) The textual contents of the current table from the - input document without associated markup content. - :attr SectionTitle section_title: (optional) The table's section title, if - identified. - :attr TableTitle title: (optional) If identified, the title or caption of the - current table of the form `Table x.: ...`. Empty when no title is identified. - When exposed, the `title` is also excluded from the `contexts` array of the same - table. - :attr List[TableHeaders] table_headers: (optional) An array of table-level cells - that apply as headers to all the other cells in the current table. - :attr List[RowHeaders] row_headers: (optional) An array of row-level cells, each - applicable as a header to other cells in the same row as itself, of the current - table. - :attr List[ColumnHeaders] column_headers: (optional) An array of column-level - cells, each applicable as a header to other cells in the same column as itself, - of the current table. - :attr List[BodyCells] body_cells: (optional) An array of cells that are neither - table header nor column header nor row header cells, of the current table with - corresponding row and column header associations. - :attr List[Contexts] contexts: (optional) An array of objects that list text - that is related to the table contents and that precedes or follows the current - table. - :attr List[KeyValuePair] key_value_pairs: (optional) An array of key-value pairs - identified in the current table. - """ - - def __init__(self, - *, - location: 'Location' = None, - text: str = None, - section_title: 'SectionTitle' = None, - title: 'TableTitle' = None, - table_headers: List['TableHeaders'] = None, - row_headers: List['RowHeaders'] = None, - column_headers: List['ColumnHeaders'] = None, - body_cells: List['BodyCells'] = None, - contexts: List['Contexts'] = None, - key_value_pairs: List['KeyValuePair'] = None) -> None: - """ - Initialize a Tables object. - - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param str text: (optional) The textual contents of the current table from - the input document without associated markup content. - :param SectionTitle section_title: (optional) The table's section title, if - identified. - :param TableTitle title: (optional) If identified, the title or caption of - the current table of the form `Table x.: ...`. Empty when no title is - identified. When exposed, the `title` is also excluded from the `contexts` - array of the same table. - :param List[TableHeaders] table_headers: (optional) An array of table-level - cells that apply as headers to all the other cells in the current table. - :param List[RowHeaders] row_headers: (optional) An array of row-level - cells, each applicable as a header to other cells in the same row as - itself, of the current table. - :param List[ColumnHeaders] column_headers: (optional) An array of - column-level cells, each applicable as a header to other cells in the same - column as itself, of the current table. - :param List[BodyCells] body_cells: (optional) An array of cells that are - neither table header nor column header nor row header cells, of the current - table with corresponding row and column header associations. - :param List[Contexts] contexts: (optional) An array of objects that list - text that is related to the table contents and that precedes or follows the - current table. - :param List[KeyValuePair] key_value_pairs: (optional) An array of key-value - pairs identified in the current table. - """ - self.location = location - self.text = text - self.section_title = section_title - self.title = title - self.table_headers = table_headers - self.row_headers = row_headers - self.column_headers = column_headers - self.body_cells = body_cells - self.contexts = contexts - self.key_value_pairs = key_value_pairs - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Tables': - """Initialize a Tables object from a json dictionary.""" - args = {} - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'section_title' in _dict: - args['section_title'] = SectionTitle.from_dict( - _dict.get('section_title')) - if 'title' in _dict: - args['title'] = TableTitle.from_dict(_dict.get('title')) - if 'table_headers' in _dict: - args['table_headers'] = [ - TableHeaders.from_dict(x) for x in _dict.get('table_headers') - ] - if 'row_headers' in _dict: - args['row_headers'] = [ - RowHeaders.from_dict(x) for x in _dict.get('row_headers') - ] - if 'column_headers' in _dict: - args['column_headers'] = [ - ColumnHeaders.from_dict(x) for x in _dict.get('column_headers') - ] - if 'body_cells' in _dict: - args['body_cells'] = [ - BodyCells.from_dict(x) for x in _dict.get('body_cells') - ] - if 'contexts' in _dict: - args['contexts'] = [ - Contexts.from_dict(x) for x in _dict.get('contexts') - ] - if 'key_value_pairs' in _dict: - args['key_value_pairs'] = [ - KeyValuePair.from_dict(x) for x in _dict.get('key_value_pairs') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Tables 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, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'section_title') and self.section_title is not None: - _dict['section_title'] = self.section_title.to_dict() - if hasattr(self, 'title') and self.title is not None: - _dict['title'] = self.title.to_dict() - if hasattr(self, 'table_headers') and self.table_headers is not None: - _dict['table_headers'] = [x.to_dict() for x in self.table_headers] - if hasattr(self, 'row_headers') and self.row_headers is not None: - _dict['row_headers'] = [x.to_dict() for x in self.row_headers] - if hasattr(self, 'column_headers') and self.column_headers is not None: - _dict['column_headers'] = [x.to_dict() for x in self.column_headers] - if hasattr(self, 'body_cells') and self.body_cells is not None: - _dict['body_cells'] = [x.to_dict() for x in self.body_cells] - if hasattr(self, 'contexts') and self.contexts is not None: - _dict['contexts'] = [x.to_dict() for x in self.contexts] - if hasattr(self, - 'key_value_pairs') and self.key_value_pairs is not None: - _dict['key_value_pairs'] = [ - x.to_dict() for x in self.key_value_pairs - ] - 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 Tables object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Tables') -> 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: 'Tables') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TerminationDates(): - """ - Termination dates identified in the input document. - - :attr str confidence_level: (optional) The confidence level in the - identification of the termination date. - :attr str text: (optional) The termination date. - :attr str text_normalized: (optional) The normalized form of the termination - date, which is listed as a string. This element is optional; it is returned only - if normalized text exists. - :attr List[str] provenance_ids: (optional) Hashed values that you can send to - IBM to provide feedback or receive support. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - - def __init__(self, - *, - confidence_level: str = None, - text: str = None, - text_normalized: str = None, - provenance_ids: List[str] = None, - location: 'Location' = None) -> None: - """ - Initialize a TerminationDates object. - - :param str confidence_level: (optional) The confidence level in the - identification of the termination date. - :param str text: (optional) The termination date. - :param str text_normalized: (optional) The normalized form of the - termination date, which is listed as a string. This element is optional; it - is returned only if normalized text exists. - :param List[str] provenance_ids: (optional) Hashed values that you can send - to IBM to provide feedback or receive support. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - """ - self.confidence_level = confidence_level - self.text = text - self.text_normalized = text_normalized - self.provenance_ids = provenance_ids - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TerminationDates': - """Initialize a TerminationDates object from a json dictionary.""" - args = {} - if 'confidence_level' in _dict: - args['confidence_level'] = _dict.get('confidence_level') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'text_normalized' in _dict: - args['text_normalized'] = _dict.get('text_normalized') - if 'provenance_ids' in _dict: - args['provenance_ids'] = _dict.get('provenance_ids') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TerminationDates 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, - 'confidence_level') and self.confidence_level is not None: - _dict['confidence_level'] = self.confidence_level - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, - 'text_normalized') and self.text_normalized is not None: - _dict['text_normalized'] = self.text_normalized - if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: - _dict['provenance_ids'] = self.provenance_ids - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 TerminationDates object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TerminationDates') -> 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: 'TerminationDates') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ConfidenceLevelEnum(str, Enum): - """ - The confidence level in the identification of the termination date. - """ - HIGH = 'High' - MEDIUM = 'Medium' - LOW = 'Low' - - -class TypeLabel(): - """ - Identification of a specific type. - - :attr Label label: (optional) A pair of `nature` and `party` objects. The - `nature` object identifies the effect of the element on the identified `party`, - and the `party` object identifies the affected party. - :attr List[str] provenance_ids: (optional) Hashed values that you can send to - IBM to provide feedback or receive support. - :attr str modification: (optional) The type of modification of the feedback - entry in the updated labels response. - """ - - def __init__(self, - *, - label: 'Label' = None, - provenance_ids: List[str] = None, - modification: str = None) -> None: - """ - Initialize a TypeLabel object. - - :param Label label: (optional) A pair of `nature` and `party` objects. The - `nature` object identifies the effect of the element on the identified - `party`, and the `party` object identifies the affected party. - :param List[str] provenance_ids: (optional) Hashed values that you can send - to IBM to provide feedback or receive support. - :param str modification: (optional) The type of modification of the - feedback entry in the updated labels response. - """ - self.label = label - self.provenance_ids = provenance_ids - self.modification = modification - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TypeLabel': - """Initialize a TypeLabel object from a json dictionary.""" - args = {} - if 'label' in _dict: - args['label'] = Label.from_dict(_dict.get('label')) - if 'provenance_ids' in _dict: - args['provenance_ids'] = _dict.get('provenance_ids') - if 'modification' in _dict: - args['modification'] = _dict.get('modification') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TypeLabel 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, 'label') and self.label is not None: - _dict['label'] = self.label.to_dict() - if hasattr(self, 'provenance_ids') and self.provenance_ids is not None: - _dict['provenance_ids'] = self.provenance_ids - if hasattr(self, 'modification') and self.modification is not None: - _dict['modification'] = self.modification - 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 TypeLabel object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TypeLabel') -> 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: 'TypeLabel') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ModificationEnum(str, Enum): - """ - The type of modification of the feedback entry in the updated labels response. - """ - ADDED = 'added' - UNCHANGED = 'unchanged' - REMOVED = 'removed' - - -class TypeLabelComparison(): - """ - Identification of a specific type. - - :attr Label label: (optional) A pair of `nature` and `party` objects. The - `nature` object identifies the effect of the element on the identified `party`, - and the `party` object identifies the affected party. - """ - - def __init__(self, *, label: 'Label' = None) -> None: - """ - Initialize a TypeLabelComparison object. - - :param Label label: (optional) A pair of `nature` and `party` objects. The - `nature` object identifies the effect of the element on the identified - `party`, and the `party` object identifies the affected party. - """ - self.label = label - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TypeLabelComparison': - """Initialize a TypeLabelComparison object from a json dictionary.""" - args = {} - if 'label' in _dict: - args['label'] = Label.from_dict(_dict.get('label')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TypeLabelComparison 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, 'label') and self.label is not None: - _dict['label'] = self.label.to_dict() - 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 TypeLabelComparison object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TypeLabelComparison') -> 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: 'TypeLabelComparison') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class UnalignedElement(): - """ - Element that does not align semantically between two compared documents. - - :attr str document_label: (optional) The label assigned to the document by the - value of the `file_1_label` or `file_2_label` parameters on the **Compare two - documents** method. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr str text: (optional) The text of the element. - :attr List[TypeLabelComparison] types: (optional) Description of the action - specified by the element and whom it affects. - :attr List[CategoryComparison] categories: (optional) List of functional - categories into which the element falls; in other words, the subject matter of - the element. - :attr List[Attribute] attributes: (optional) List of document attributes. - """ - - def __init__(self, - *, - document_label: str = None, - location: 'Location' = None, - text: str = None, - types: List['TypeLabelComparison'] = None, - categories: List['CategoryComparison'] = None, - attributes: List['Attribute'] = None) -> None: - """ - Initialize a UnalignedElement object. - - :param str document_label: (optional) The label assigned to the document by - the value of the `file_1_label` or `file_2_label` parameters on the - **Compare two documents** method. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param str text: (optional) The text of the element. - :param List[TypeLabelComparison] types: (optional) Description of the - action specified by the element and whom it affects. - :param List[CategoryComparison] categories: (optional) List of functional - categories into which the element falls; in other words, the subject matter - of the element. - :param List[Attribute] attributes: (optional) List of document attributes. - """ - self.document_label = document_label - self.location = location - self.text = text - self.types = types - self.categories = categories - self.attributes = attributes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'UnalignedElement': - """Initialize a UnalignedElement object from a json dictionary.""" - args = {} - if 'document_label' in _dict: - args['document_label'] = _dict.get('document_label') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'types' in _dict: - args['types'] = [ - TypeLabelComparison.from_dict(x) for x in _dict.get('types') - ] - if 'categories' in _dict: - args['categories'] = [ - CategoryComparison.from_dict(x) for x in _dict.get('categories') - ] - if 'attributes' in _dict: - args['attributes'] = [ - Attribute.from_dict(x) for x in _dict.get('attributes') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a UnalignedElement 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, 'document_label') and self.document_label is not None: - _dict['document_label'] = self.document_label - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'types') and self.types is not None: - _dict['types'] = [x.to_dict() for x in self.types] - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x.to_dict() for x in self.categories] - if hasattr(self, 'attributes') and self.attributes is not None: - _dict['attributes'] = [x.to_dict() for x in self.attributes] - 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 UnalignedElement object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'UnalignedElement') -> 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: 'UnalignedElement') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class UpdatedLabelsIn(): - """ - The updated labeling from the input document, accounting for the submitted feedback. - - :attr List[TypeLabel] types: Description of the action specified by the element - and whom it affects. - :attr List[Category] categories: List of functional categories into which the - element falls; in other words, the subject matter of the element. - """ - - def __init__(self, types: List['TypeLabel'], - categories: List['Category']) -> None: - """ - Initialize a UpdatedLabelsIn object. - - :param List[TypeLabel] types: Description of the action specified by the - element and whom it affects. - :param List[Category] categories: List of functional categories into which - the element falls; in other words, the subject matter of the element. - """ - self.types = types - self.categories = categories - - @classmethod - def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsIn': - """Initialize a UpdatedLabelsIn object from a json dictionary.""" - args = {} - if 'types' in _dict: - args['types'] = [TypeLabel.from_dict(x) for x in _dict.get('types')] - else: - raise ValueError( - 'Required property \'types\' not present in UpdatedLabelsIn JSON' - ) - if 'categories' in _dict: - args['categories'] = [ - Category.from_dict(x) for x in _dict.get('categories') - ] - else: - raise ValueError( - 'Required property \'categories\' not present in UpdatedLabelsIn JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a UpdatedLabelsIn 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, 'types') and self.types is not None: - _dict['types'] = [x.to_dict() for x in self.types] - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x.to_dict() for x in self.categories] - 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 UpdatedLabelsIn object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'UpdatedLabelsIn') -> 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: 'UpdatedLabelsIn') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class UpdatedLabelsOut(): - """ - The updated labeling from the input document, accounting for the submitted feedback. - - :attr List[TypeLabel] types: (optional) Description of the action specified by - the element and whom it affects. - :attr List[Category] categories: (optional) List of functional categories into - which the element falls; in other words, the subject matter of the element. - """ - - def __init__(self, - *, - types: List['TypeLabel'] = None, - categories: List['Category'] = None) -> None: - """ - Initialize a UpdatedLabelsOut object. - - :param List[TypeLabel] types: (optional) Description of the action - specified by the element and whom it affects. - :param List[Category] categories: (optional) List of functional categories - into which the element falls; in other words, the subject matter of the - element. - """ - self.types = types - self.categories = categories - - @classmethod - def from_dict(cls, _dict: Dict) -> 'UpdatedLabelsOut': - """Initialize a UpdatedLabelsOut object from a json dictionary.""" - args = {} - if 'types' in _dict: - args['types'] = [TypeLabel.from_dict(x) for x in _dict.get('types')] - if 'categories' in _dict: - args['categories'] = [ - Category.from_dict(x) for x in _dict.get('categories') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a UpdatedLabelsOut 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, 'types') and self.types is not None: - _dict['types'] = [x.to_dict() for x in self.types] - if hasattr(self, 'categories') and self.categories is not None: - _dict['categories'] = [x.to_dict() for x in self.categories] - 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 UpdatedLabelsOut object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'UpdatedLabelsOut') -> 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: 'UpdatedLabelsOut') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Value(): - """ - A value in a key-value pair. - - :attr str cell_id: (optional) The unique ID of the value in the table. - :attr Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :attr str text: (optional) The text content of the table cell without HTML - markup. - """ - - def __init__(self, - *, - cell_id: str = None, - location: 'Location' = None, - text: str = None) -> None: - """ - Initialize a Value object. - - :param str cell_id: (optional) The unique ID of the value in the table. - :param Location location: (optional) The numeric location of the identified - element in the document, represented with two integers labeled `begin` and - `end`. - :param str text: (optional) The text content of the table cell without HTML - markup. - """ - self.cell_id = cell_id - self.location = location - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Value': - """Initialize a Value object from a json dictionary.""" - args = {} - if 'cell_id' in _dict: - args['cell_id'] = _dict.get('cell_id') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - if 'text' in _dict: - args['text'] = _dict.get('text') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Value 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, 'cell_id') and self.cell_id is not None: - _dict['cell_id'] = self.cell_id - if hasattr(self, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - 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 Value object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Value') -> 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: 'Value') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index d826fd940..08411eb79 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2019, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 +# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 """ IBM Watson™ Discovery is a cognitive search and content analytics engine that you can add to applications to identify patterns, trends and actionable insights to drive @@ -65,7 +65,7 @@ def __init__( Specify dates in YYYY-MM-DD format. The current version is `2019-04-30`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md about initializing the authenticator of your choice. """ if version is None: @@ -225,9 +225,8 @@ def update_environment(self, :param str environment_id: The ID of the environment. :param str name: (optional) Name that identifies the environment. :param str description: (optional) Description of the environment. - :param str size: (optional) Size that the environment should be increased - to. Environment size cannot be modified when using a Lite plan. Environment - size can only increased and not decreased. + :param str size: (optional) Size to change the environment to. **Note:** + Lite plan users cannot change the environment size. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `Environment` object @@ -3880,83 +3879,6 @@ class ResultType(str, Enum): ############################################################################## -class AggregationResult(): - """ - Aggregation results for the specified query. - - :attr str key: (optional) Key that matched the aggregation type. - :attr int matching_results: (optional) Number of matching results. - :attr List[QueryAggregation] aggregations: (optional) Aggregations returned in - the case of chained aggregations. - """ - - def __init__(self, - *, - key: str = None, - matching_results: int = None, - aggregations: List['QueryAggregation'] = None) -> None: - """ - Initialize a AggregationResult object. - - :param str key: (optional) Key that matched the aggregation type. - :param int matching_results: (optional) Number of matching results. - :param List[QueryAggregation] aggregations: (optional) Aggregations - returned in the case of chained aggregations. - """ - self.key = key - self.matching_results = matching_results - self.aggregations = aggregations - - @classmethod - def from_dict(cls, _dict: Dict) -> 'AggregationResult': - """Initialize a AggregationResult object from a json dictionary.""" - args = {} - if 'key' in _dict: - args['key'] = _dict.get('key') - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a AggregationResult 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, 'key') and self.key is not None: - _dict['key'] = self.key - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - 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 AggregationResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'AggregationResult') -> 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: 'AggregationResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class Collection(): """ A collection for storing documents. @@ -5875,37 +5797,32 @@ class DocumentStatus(): """ Status information about a submitted document. - :attr str document_id: The unique identifier of the document. + :attr str document_id: (optional) The unique identifier of the document. :attr str configuration_id: (optional) The unique identifier for the configuration. - :attr str status: Status of the document in the ingestion process. - :attr str status_description: Description of the document status. + :attr str status: (optional) Status of the document in the ingestion process. + :attr str status_description: (optional) Description of the document status. :attr str filename: (optional) Name of the original source file (if available). :attr str file_type: (optional) The type of the original source file. :attr str sha1: (optional) The SHA-1 hash of the original source file (formatted as a hexadecimal string). - :attr List[Notice] notices: Array of notices produced by the document-ingestion - process. + :attr List[Notice] notices: (optional) Array of notices produced by the + document-ingestion process. """ def __init__(self, - document_id: str, - status: str, - status_description: str, - notices: List['Notice'], *, + document_id: str = None, configuration_id: str = None, + status: str = None, + status_description: str = None, filename: str = None, file_type: str = None, - sha1: str = None) -> None: + sha1: str = None, + notices: List['Notice'] = None) -> None: """ Initialize a DocumentStatus object. - :param str document_id: The unique identifier of the document. - :param str status: Status of the document in the ingestion process. - :param str status_description: Description of the document status. - :param List[Notice] notices: Array of notices produced by the - document-ingestion process. :param str filename: (optional) Name of the original source file (if available). :param str file_type: (optional) The type of the original source file. @@ -5927,24 +5844,12 @@ def from_dict(cls, _dict: Dict) -> 'DocumentStatus': args = {} if 'document_id' in _dict: args['document_id'] = _dict.get('document_id') - else: - raise ValueError( - 'Required property \'document_id\' not present in DocumentStatus JSON' - ) if 'configuration_id' in _dict: args['configuration_id'] = _dict.get('configuration_id') if 'status' in _dict: args['status'] = _dict.get('status') - else: - raise ValueError( - 'Required property \'status\' not present in DocumentStatus JSON' - ) if 'status_description' in _dict: args['status_description'] = _dict.get('status_description') - else: - raise ValueError( - 'Required property \'status_description\' not present in DocumentStatus JSON' - ) if 'filename' in _dict: args['filename'] = _dict.get('filename') if 'file_type' in _dict: @@ -5955,10 +5860,6 @@ def from_dict(cls, _dict: Dict) -> 'DocumentStatus': args['notices'] = [ Notice.from_dict(x) for x in _dict.get('notices') ] - else: - raise ValueError( - 'Required property \'notices\' not present in DocumentStatus JSON' - ) return cls(**args) @classmethod @@ -6043,19 +5944,18 @@ class Enrichment(): for this enrichment is set to `natural_language_undstanding`. :attr bool overwrite: (optional) Indicates that the enrichments will overwrite the destination_field field if it already exists. - :attr str enrichment: Name of the enrichment service to call. Current options - are `natural_language_understanding` and `elements`. - When using `natual_language_understanding`, the **options** object must contain - Natural Language Understanding options. - When using `elements` the **options** object must contain Element Classification - options. Additionally, when using the `elements` enrichment the configuration - specified and files ingested must meet all the criteria specified in [the - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-element-classification#element-classification). + :attr str enrichment: Name of the enrichment service to call. The only supported + option is `natural_language_understanding`. The `elements` option is deprecated + and support ended on 10 July 2020. + The **options** object must contain Natural Language Understanding options. :attr bool ignore_downstream_errors: (optional) If true, then most errors generated during the enrichment process will be treated as warnings and will not cause the document to fail processing. - :attr EnrichmentOptions options: (optional) Options which are specific to a + :attr EnrichmentOptions options: (optional) Options that are specific to a particular enrichment. + The `elements` enrichment type is deprecated. Use the [Create a + project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of + the Discovery v2 API to create a `content_intelligence` project type instead. """ def __init__(self, @@ -6077,23 +5977,23 @@ def __init__(self, :param str source_field: Field to be enriched. Arrays can be specified as the **source_field** if the **enrichment** service for this enrichment is set to `natural_language_undstanding`. - :param str enrichment: Name of the enrichment service to call. Current - options are `natural_language_understanding` and `elements`. - When using `natual_language_understanding`, the **options** object must - contain Natural Language Understanding options. - When using `elements` the **options** object must contain Element - Classification options. Additionally, when using the `elements` enrichment - the configuration specified and files ingested must meet all the criteria - specified in [the - documentation](https://cloud.ibm.com/docs/discovery?topic=discovery-element-classification#element-classification). + :param str enrichment: Name of the enrichment service to call. The only + supported option is `natural_language_understanding`. The `elements` option + is deprecated and support ended on 10 July 2020. + The **options** object must contain Natural Language Understanding + options. :param str description: (optional) Describes what the enrichment step does. :param bool overwrite: (optional) Indicates that the enrichments will overwrite the destination_field field if it already exists. :param bool ignore_downstream_errors: (optional) If true, then most errors generated during the enrichment process will be treated as warnings and will not cause the document to fail processing. - :param EnrichmentOptions options: (optional) Options which are specific to - a particular enrichment. + :param EnrichmentOptions options: (optional) Options that are specific to a + particular enrichment. + The `elements` enrichment type is deprecated. Use the [Create a + project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method + of the Discovery v2 API to create a `content_intelligence` project type + instead. """ self.description = description self.destination_field = destination_field @@ -6183,7 +6083,10 @@ def __ne__(self, other: 'Enrichment') -> bool: class EnrichmentOptions(): """ - Options which are specific to a particular enrichment. + Options that are specific to a particular enrichment. + The `elements` enrichment type is deprecated. Use the [Create a + project](https://cloud.ibm.com/apidocs/discovery-data#createproject) method of the + Discovery v2 API to create a `content_intelligence` project type instead. :attr NluEnrichmentFeatures features: (optional) Object containing Natural Language Understanding features to be used. @@ -6193,8 +6096,8 @@ class EnrichmentOptions(): (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. - :attr str model: (optional) For use with `elements` enrichments only. The - element extraction model to use. The only model available is `contract`. + :attr str model: (optional) The element extraction model to use, which can be + `contract` only. The `elements` enrichment is deprecated. """ def __init__(self, @@ -6213,8 +6116,8 @@ def __init__(self, `fr` (French), `de` (German), `it` (Italian), `pt` (Portuguese), `ru` (Russian), `es` (Spanish), and `sv` (Swedish). **Note:** Not all features support all languages, automatic detection is recommended. - :param str model: (optional) For use with `elements` enrichments only. The - element extraction model to use. The only model available is `contract`. + :param str model: (optional) The element extraction model to use, which can + be `contract` only. The `elements` enrichment is deprecated. """ self.features = features self.language = language @@ -9681,35 +9584,18 @@ class QueryAggregation(): """ An aggregation produced by Discovery to analyze the input provided. - :attr str type: (optional) The type of aggregation command used. For example: - term, filter, max, min, etc. - :attr List[AggregationResult] results: (optional) Array of aggregation results. - :attr int matching_results: (optional) Number of matching results. - :attr List[QueryAggregation] aggregations: (optional) Aggregations returned by - Discovery. + :attr str type: The type of aggregation command used. For example: term, filter, + max, min, etc. """ - def __init__(self, - *, - type: str = None, - results: List['AggregationResult'] = None, - matching_results: int = None, - aggregations: List['QueryAggregation'] = None) -> None: + def __init__(self, type: str) -> None: """ Initialize a QueryAggregation object. - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param List[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param List[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. + :param str type: The type of aggregation command used. For example: term, + filter, max, min, etc. """ self.type = type - self.results = results - self.matching_results = matching_results - self.aggregations = aggregations @classmethod def from_dict(cls, _dict: Dict) -> 'QueryAggregation': @@ -9720,16 +9606,10 @@ def from_dict(cls, _dict: Dict) -> 'QueryAggregation': args = {} if 'type' in _dict: args['type'] = _dict.get('type') - if 'results' in _dict: - args['results'] = [ - AggregationResult.from_dict(x) for x in _dict.get('results') - ] - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + else: + raise ValueError( + 'Required property \'type\' not present in QueryAggregation JSON' + ) return cls(**args) @classmethod @@ -9742,13 +9622,6 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -9772,17 +9645,17 @@ def __ne__(self, other: 'QueryAggregation') -> bool: @classmethod def _get_class_by_discriminator(cls, _dict: Dict) -> object: mapping = {} - mapping['histogram'] = 'Histogram' - mapping['max'] = 'Calculation' - mapping['min'] = 'Calculation' - mapping['average'] = 'Calculation' - mapping['sum'] = 'Calculation' - mapping['unique_count'] = 'Calculation' - mapping['term'] = 'Term' - mapping['filter'] = 'Filter' - mapping['nested'] = 'Nested' - mapping['timeslice'] = 'Timeslice' - mapping['top_hits'] = 'TopHits' + mapping['histogram'] = 'QueryHistogramAggregation' + mapping['max'] = 'QueryCalculationAggregation' + mapping['min'] = 'QueryCalculationAggregation' + mapping['average'] = 'QueryCalculationAggregation' + mapping['sum'] = 'QueryCalculationAggregation' + mapping['unique_count'] = 'QueryCalculationAggregation' + mapping['term'] = 'QueryTermAggregation' + mapping['filter'] = 'QueryFilterAggregation' + mapping['nested'] = 'QueryNestedAggregation' + mapping['timeslice'] = 'QueryTimesliceAggregation' + mapping['top_hits'] = 'QueryTopHitsAggregation' disc_value = _dict.get('type') if disc_value is None: raise ValueError( @@ -9798,6 +9671,93 @@ def _get_class_by_discriminator(cls, _dict: Dict) -> object: raise TypeError('%s is not a discriminator class' % class_name) +class QueryHistogramAggregationResult(): + """ + Histogram numeric interval result. + + :attr int key: The value of the upper bound for the numeric segment. + :attr int matching_results: Number of documents with the specified key as the + upper bound. + :attr List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. + """ + + def __init__(self, + key: int, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: + """ + Initialize a QueryHistogramAggregationResult object. + + :param int key: The value of the upper bound for the numeric segment. + :param int matching_results: Number of documents with the specified key as + the upper bound. + :param List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. + """ + self.key = key + self.matching_results = matching_results + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregationResult': + """Initialize a QueryHistogramAggregationResult object from a json dictionary.""" + args = {} + if 'key' in _dict: + args['key'] = _dict.get('key') + else: + raise ValueError( + 'Required property \'key\' not present in QueryHistogramAggregationResult JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryHistogramAggregationResult JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryHistogramAggregationResult 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, 'key') and self.key is not None: + _dict['key'] = self.key + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + 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 QueryHistogramAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryHistogramAggregationResult') -> 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: 'QueryHistogramAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class QueryNoticesResponse(): """ Object containing notice query results. @@ -10537,59 +10497,109 @@ def __ne__(self, other: 'QueryResultMetadata') -> bool: return not self == other -class RetrievalDetails(): +class QueryTermAggregationResult(): """ - An object contain retrieval type information. + Top value result for the term aggregation. - :attr str document_retrieval_strategy: (optional) Indentifies the document - retrieval strategy used for this query. `relevancy_training` indicates that the - results were returned using a relevancy trained model. - `continuous_relevancy_training` indicates that the results were returned using - the continuous relevancy training model created by result feedback analysis. - `untrained` means the results were returned using the standard untrained model. - **Note**: In the event of trained collections being queried, but the trained - model is not used to return results, the **document_retrieval_strategy** will be - listed as `untrained`. + :attr str key: Value of the field with a non-zero frequency in the document set. + :attr int matching_results: Number of documents that contain the 'key'. + :attr float relevancy: (optional) The relevancy for this term. + :attr int total_matching_documents: (optional) The number of documents which + have the term as the value of specified field in the whole set of documents in + this collection. Returned only when the `relevancy` parameter is set to `true`. + :attr int estimated_matching_documents: (optional) The estimated number of + documents which would match the query and also meet the condition. Returned only + when the `relevancy` parameter is set to `true`. + :attr List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ - def __init__(self, *, document_retrieval_strategy: str = None) -> None: + def __init__(self, + key: str, + matching_results: int, + *, + relevancy: float = None, + total_matching_documents: int = None, + estimated_matching_documents: int = None, + aggregations: List['QueryAggregation'] = None) -> None: """ - Initialize a RetrievalDetails object. - - :param str document_retrieval_strategy: (optional) Indentifies the document - retrieval strategy used for this query. `relevancy_training` indicates that - the results were returned using a relevancy trained model. - `continuous_relevancy_training` indicates that the results were returned - using the continuous relevancy training model created by result feedback - analysis. `untrained` means the results were returned using the standard - untrained model. - **Note**: In the event of trained collections being queried, but the - trained model is not used to return results, the - **document_retrieval_strategy** will be listed as `untrained`. + Initialize a QueryTermAggregationResult object. + + :param str key: Value of the field with a non-zero frequency in the + document set. + :param int matching_results: Number of documents that contain the 'key'. + :param float relevancy: (optional) The relevancy for this term. + :param int total_matching_documents: (optional) The number of documents + which have the term as the value of specified field in the whole set of + documents in this collection. Returned only when the `relevancy` parameter + is set to `true`. + :param int estimated_matching_documents: (optional) The estimated number of + documents which would match the query and also meet the condition. Returned + only when the `relevancy` parameter is set to `true`. + :param List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ - self.document_retrieval_strategy = document_retrieval_strategy + self.key = key + self.matching_results = matching_results + self.relevancy = relevancy + self.total_matching_documents = total_matching_documents + self.estimated_matching_documents = estimated_matching_documents + self.aggregations = aggregations @classmethod - def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': - """Initialize a RetrievalDetails object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryTermAggregationResult': + """Initialize a QueryTermAggregationResult object from a json dictionary.""" args = {} - if 'document_retrieval_strategy' in _dict: - args['document_retrieval_strategy'] = _dict.get( - 'document_retrieval_strategy') + if 'key' in _dict: + args['key'] = _dict.get('key') + else: + raise ValueError( + 'Required property \'key\' not present in QueryTermAggregationResult JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryTermAggregationResult JSON' + ) + if 'relevancy' in _dict: + args['relevancy'] = _dict.get('relevancy') + if 'total_matching_documents' in _dict: + args['total_matching_documents'] = _dict.get( + 'total_matching_documents') + if 'estimated_matching_documents' in _dict: + args['estimated_matching_documents'] = _dict.get( + 'estimated_matching_documents') + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a RetrievalDetails object from a json dictionary.""" + """Initialize a QueryTermAggregationResult 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, 'document_retrieval_strategy' - ) and self.document_retrieval_strategy is not None: + if hasattr(self, 'key') and self.key is not None: + _dict['key'] = self.key + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'relevancy') and self.relevancy is not None: + _dict['relevancy'] = self.relevancy + if hasattr(self, 'total_matching_documents' + ) and self.total_matching_documents is not None: + _dict['total_matching_documents'] = self.total_matching_documents + if hasattr(self, 'estimated_matching_documents' + ) and self.estimated_matching_documents is not None: _dict[ - 'document_retrieval_strategy'] = self.document_retrieval_strategy + 'estimated_matching_documents'] = self.estimated_matching_documents + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] return _dict def _to_dict(self): @@ -10597,26 +10607,272 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this RetrievalDetails object.""" + """Return a `str` version of this QueryTermAggregationResult object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'RetrievalDetails') -> bool: + def __eq__(self, other: 'QueryTermAggregationResult') -> 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: 'RetrievalDetails') -> bool: + def __ne__(self, other: 'QueryTermAggregationResult') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other - class DocumentRetrievalStrategyEnum(str, Enum): + +class QueryTimesliceAggregationResult(): + """ + A timeslice interval segment. + + :attr str key_as_string: String date value of the upper bound for the timeslice + interval in ISO-8601 format. + :attr int key: Numeric date value of the upper bound for the timeslice interval + in UNIX milliseconds since epoch. + :attr int matching_results: Number of documents with the specified key as the + upper bound. + :attr List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. + """ + + def __init__(self, + key_as_string: str, + key: int, + matching_results: int, + *, + aggregations: List['QueryAggregation'] = None) -> None: """ - Indentifies the document retrieval strategy used for this query. - `relevancy_training` indicates that the results were returned using a relevancy - trained model. `continuous_relevancy_training` indicates that the results were - returned using the continuous relevancy training model created by result feedback - analysis. `untrained` means the results were returned using the standard untrained + Initialize a QueryTimesliceAggregationResult object. + + :param str key_as_string: String date value of the upper bound for the + timeslice interval in ISO-8601 format. + :param int key: Numeric date value of the upper bound for the timeslice + interval in UNIX milliseconds since epoch. + :param int matching_results: Number of documents with the specified key as + the upper bound. + :param List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. + """ + self.key_as_string = key_as_string + self.key = key + self.matching_results = matching_results + self.aggregations = aggregations + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregationResult': + """Initialize a QueryTimesliceAggregationResult object from a json dictionary.""" + args = {} + if 'key_as_string' in _dict: + args['key_as_string'] = _dict.get('key_as_string') + else: + raise ValueError( + 'Required property \'key_as_string\' not present in QueryTimesliceAggregationResult JSON' + ) + if 'key' in _dict: + args['key'] = _dict.get('key') + else: + raise ValueError( + 'Required property \'key\' not present in QueryTimesliceAggregationResult JSON' + ) + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryTimesliceAggregationResult JSON' + ) + if 'aggregations' in _dict: + args['aggregations'] = [ + QueryAggregation.from_dict(x) for x in _dict.get('aggregations') + ] + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTimesliceAggregationResult 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, 'key_as_string') and self.key_as_string is not None: + _dict['key_as_string'] = self.key_as_string + if hasattr(self, 'key') and self.key is not None: + _dict['key'] = self.key + if hasattr(self, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'aggregations') and self.aggregations is not None: + _dict['aggregations'] = [x.to_dict() for x in self.aggregations] + 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 QueryTimesliceAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryTimesliceAggregationResult') -> 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: 'QueryTimesliceAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class QueryTopHitsAggregationResult(): + """ + A query response that contains the matching documents for the preceding aggregations. + + :attr int matching_results: Number of matching results. + :attr List[dict] hits: (optional) An array of the document results. + """ + + def __init__(self, + matching_results: int, + *, + hits: List[dict] = None) -> None: + """ + Initialize a QueryTopHitsAggregationResult object. + + :param int matching_results: Number of matching results. + :param List[dict] hits: (optional) An array of the document results. + """ + self.matching_results = matching_results + self.hits = hits + + @classmethod + def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregationResult': + """Initialize a QueryTopHitsAggregationResult object from a json dictionary.""" + args = {} + if 'matching_results' in _dict: + args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryTopHitsAggregationResult JSON' + ) + if 'hits' in _dict: + args['hits'] = _dict.get('hits') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a QueryTopHitsAggregationResult 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, + 'matching_results') and self.matching_results is not None: + _dict['matching_results'] = self.matching_results + if hasattr(self, 'hits') and self.hits is not None: + _dict['hits'] = self.hits + 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 QueryTopHitsAggregationResult object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'QueryTopHitsAggregationResult') -> 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: 'QueryTopHitsAggregationResult') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class RetrievalDetails(): + """ + An object contain retrieval type information. + + :attr str document_retrieval_strategy: (optional) Indentifies the document + retrieval strategy used for this query. `relevancy_training` indicates that the + results were returned using a relevancy trained model. + `continuous_relevancy_training` indicates that the results were returned using + the continuous relevancy training model created by result feedback analysis. + `untrained` means the results were returned using the standard untrained model. + **Note**: In the event of trained collections being queried, but the trained + model is not used to return results, the **document_retrieval_strategy** will be + listed as `untrained`. + """ + + def __init__(self, *, document_retrieval_strategy: str = None) -> None: + """ + Initialize a RetrievalDetails object. + + :param str document_retrieval_strategy: (optional) Indentifies the document + retrieval strategy used for this query. `relevancy_training` indicates that + the results were returned using a relevancy trained model. + `continuous_relevancy_training` indicates that the results were returned + using the continuous relevancy training model created by result feedback + analysis. `untrained` means the results were returned using the standard + untrained model. + **Note**: In the event of trained collections being queried, but the + trained model is not used to return results, the + **document_retrieval_strategy** will be listed as `untrained`. + """ + self.document_retrieval_strategy = document_retrieval_strategy + + @classmethod + def from_dict(cls, _dict: Dict) -> 'RetrievalDetails': + """Initialize a RetrievalDetails object from a json dictionary.""" + args = {} + if 'document_retrieval_strategy' in _dict: + args['document_retrieval_strategy'] = _dict.get( + 'document_retrieval_strategy') + return cls(**args) + + @classmethod + def _from_dict(cls, _dict): + """Initialize a RetrievalDetails 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, 'document_retrieval_strategy' + ) and self.document_retrieval_strategy is not None: + _dict[ + 'document_retrieval_strategy'] = self.document_retrieval_strategy + 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 RetrievalDetails object.""" + return json.dumps(self.to_dict(), indent=2) + + def __eq__(self, other: 'RetrievalDetails') -> 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: 'RetrievalDetails') -> bool: + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class DocumentRetrievalStrategyEnum(str, Enum): + """ + Indentifies the document retrieval strategy used for this query. + `relevancy_training` indicates that the results were returned using a relevancy + trained model. `continuous_relevancy_training` indicates that the results were + returned using the continuous relevancy training model created by result feedback + analysis. `untrained` means the results were returned using the standard untrained model. **Note**: In the event of trained collections being queried, but the trained model is not used to return results, the **document_retrieval_strategy** will be @@ -11970,7 +12226,7 @@ class StatusDetails(): :attr bool authenticated: (optional) Indicates whether the credential is accepted by the target data source. :attr str error_message: (optional) If `authenticated` is `false`, a message - describes why the authentication was unsuccessful. + describes why authentication is unsuccessful. """ def __init__(self, @@ -11983,7 +12239,7 @@ def __init__(self, :param bool authenticated: (optional) Indicates whether the credential is accepted by the target data source. :param str error_message: (optional) If `authenticated` is `false`, a - message describes why the authentication was unsuccessful. + message describes why authentication is unsuccessful. """ self.authenticated = authenticated self.error_message = error_message @@ -12201,73 +12457,6 @@ class StatusEnum(str, Enum): NOT_FOUND = 'not found' -class TopHitsResults(): - """ - Top hit information for this query. - - :attr int matching_results: (optional) Number of matching results. - :attr List[QueryResult] hits: (optional) Top results returned by the - aggregation. - """ - - def __init__(self, - *, - matching_results: int = None, - hits: List['QueryResult'] = None) -> None: - """ - Initialize a TopHitsResults object. - - :param int matching_results: (optional) Number of matching results. - :param List[QueryResult] hits: (optional) Top results returned by the - aggregation. - """ - self.matching_results = matching_results - self.hits = hits - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TopHitsResults': - """Initialize a TopHitsResults object from a json dictionary.""" - args = {} - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'hits' in _dict: - args['hits'] = [QueryResult.from_dict(x) for x in _dict.get('hits')] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TopHitsResults 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, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'hits') and self.hits is not None: - _dict['hits'] = [x.to_dict() for x in self.hits] - 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 TopHitsResults object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TopHitsResults') -> 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: 'TopHitsResults') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TrainingDataSet(): """ Training information for a specific collection. @@ -12961,69 +13150,51 @@ def __ne__(self, other: 'XPathPatterns') -> bool: return not self == other -class Calculation(QueryAggregation): +class QueryCalculationAggregation(QueryAggregation): """ - Calculation. + Returns a scalar calculation across all documents for the field specified. Possible + calculations include min, max, sum, average, and unique_count. - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr float value: (optional) Value of the aggregation. + :attr str field: The field to perform the calculation on. + :attr float value: (optional) The value of the calculation. """ - def __init__(self, - *, - type: str = None, - results: List['AggregationResult'] = None, - matching_results: int = None, - aggregations: List['QueryAggregation'] = None, - field: str = None, - value: float = None) -> None: + def __init__(self, type: str, field: str, *, value: float = None) -> None: """ - Initialize a Calculation object. + Initialize a QueryCalculationAggregation object. - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param List[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param List[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param float value: (optional) Value of the aggregation. + :param str type: The type of aggregation command used. For example: term, + filter, max, min, etc. + :param str field: The field to perform the calculation on. + :param float value: (optional) The value of the calculation. """ self.type = type - self.results = results - self.matching_results = matching_results - self.aggregations = aggregations self.field = field self.value = value @classmethod - def from_dict(cls, _dict: Dict) -> 'Calculation': - """Initialize a Calculation object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryCalculationAggregation': + """Initialize a QueryCalculationAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - if 'results' in _dict: - args['results'] = [ - AggregationResult.from_dict(x) for x in _dict.get('results') - ] - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + else: + raise ValueError( + 'Required property \'type\' not present in QueryCalculationAggregation JSON' + ) if 'field' in _dict: args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryCalculationAggregation JSON' + ) if 'value' in _dict: args['value'] = _dict.get('value') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Calculation object from a json dictionary.""" + """Initialize a QueryCalculationAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -13031,13 +13202,6 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'value') and self.value is not None: @@ -13049,75 +13213,84 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Calculation object.""" + """Return a `str` version of this QueryCalculationAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Calculation') -> bool: + def __eq__(self, other: 'QueryCalculationAggregation') -> 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: 'Calculation') -> bool: + def __ne__(self, other: 'QueryCalculationAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Filter(QueryAggregation): +class QueryFilterAggregation(QueryAggregation): """ - Filter. + A modifier that narrows the document set of the sub-aggregations it precedes. - :attr str match: (optional) The match the aggregated results queried for. + :attr str match: The filter that is written in Discovery Query Language syntax + and is applied to the documents before sub-aggregations are run. + :attr int matching_results: Number of documents that match the filter. + :attr List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ def __init__(self, + type: str, + match: str, + matching_results: int, *, - type: str = None, - results: List['AggregationResult'] = None, - matching_results: int = None, - aggregations: List['QueryAggregation'] = None, - match: str = None) -> None: + aggregations: List['QueryAggregation'] = None) -> None: """ - Initialize a Filter object. + Initialize a QueryFilterAggregation object. - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param List[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param List[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str match: (optional) The match the aggregated results queried for. + :param str type: The type of aggregation command used. For example: term, + filter, max, min, etc. + :param str match: The filter that is written in Discovery Query Language + syntax and is applied to the documents before sub-aggregations are run. + :param int matching_results: Number of documents that match the filter. + :param List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ self.type = type - self.results = results + self.match = match self.matching_results = matching_results self.aggregations = aggregations - self.match = match @classmethod - def from_dict(cls, _dict: Dict) -> 'Filter': - """Initialize a Filter object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryFilterAggregation': + """Initialize a QueryFilterAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - if 'results' in _dict: - args['results'] = [ - AggregationResult.from_dict(x) for x in _dict.get('results') - ] + else: + raise ValueError( + 'Required property \'type\' not present in QueryFilterAggregation JSON' + ) + if 'match' in _dict: + args['match'] = _dict.get('match') + else: + raise ValueError( + 'Required property \'match\' not present in QueryFilterAggregation JSON' + ) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryFilterAggregation JSON' + ) if 'aggregations' in _dict: args['aggregations'] = [ QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] - if 'match' in _dict: - args['match'] = _dict.get('match') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Filter object from a json dictionary.""" + """Initialize a QueryFilterAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -13125,15 +13298,13 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + if hasattr(self, 'match') and self.match is not None: + _dict['match'] = self.match if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - if hasattr(self, 'match') and self.match is not None: - _dict['match'] = self.match return _dict def _to_dict(self): @@ -13141,85 +13312,94 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Filter object.""" + """Return a `str` version of this QueryFilterAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Filter') -> bool: + def __eq__(self, other: 'QueryFilterAggregation') -> 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: 'Filter') -> bool: + def __ne__(self, other: 'QueryFilterAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Histogram(QueryAggregation): +class QueryHistogramAggregation(QueryAggregation): """ - Histogram. + Numeric interval segments to categorize documents by using field values from a single + numeric field to describe the category. - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr int interval: (optional) Interval of the aggregation. (For 'histogram' - type). + :attr str field: The numeric field name used to create the histogram. + :attr int interval: The size of the sections that the results are split into. + :attr str name: (optional) Identifier specified in the query request of this + aggregation. + :attr List[QueryHistogramAggregationResult] results: (optional) Array of numeric + intervals. """ - def __init__(self, - *, - type: str = None, - results: List['AggregationResult'] = None, - matching_results: int = None, - aggregations: List['QueryAggregation'] = None, - field: str = None, - interval: int = None) -> None: + def __init__( + self, + type: str, + field: str, + interval: int, + *, + name: str = None, + results: List['QueryHistogramAggregationResult'] = None) -> None: """ - Initialize a Histogram object. + Initialize a QueryHistogramAggregation object. - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param List[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param List[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param int interval: (optional) Interval of the aggregation. (For - 'histogram' type). + :param str type: The type of aggregation command used. For example: term, + filter, max, min, etc. + :param str field: The numeric field name used to create the histogram. + :param int interval: The size of the sections that the results are split + into. + :param str name: (optional) Identifier specified in the query request of + this aggregation. + :param List[QueryHistogramAggregationResult] results: (optional) Array of + numeric intervals. """ self.type = type - self.results = results - self.matching_results = matching_results - self.aggregations = aggregations self.field = field self.interval = interval + self.name = name + self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'Histogram': - """Initialize a Histogram object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryHistogramAggregation': + """Initialize a QueryHistogramAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - if 'results' in _dict: - args['results'] = [ - AggregationResult.from_dict(x) for x in _dict.get('results') - ] - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + else: + raise ValueError( + 'Required property \'type\' not present in QueryHistogramAggregation JSON' + ) if 'field' in _dict: args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryHistogramAggregation JSON' + ) if 'interval' in _dict: args['interval'] = _dict.get('interval') + else: + raise ValueError( + 'Required property \'interval\' not present in QueryHistogramAggregation JSON' + ) + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'results' in _dict: + args['results'] = [ + QueryHistogramAggregationResult.from_dict(x) + for x in _dict.get('results') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Histogram object from a json dictionary.""" + """Initialize a QueryHistogramAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -13227,17 +13407,14 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'interval') and self.interval is not None: _dict['interval'] = self.interval + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x.to_dict() for x in self.results] return _dict def _to_dict(self): @@ -13245,77 +13422,86 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Histogram object.""" + """Return a `str` version of this QueryHistogramAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Histogram') -> bool: + def __eq__(self, other: 'QueryHistogramAggregation') -> 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: 'Histogram') -> bool: + def __ne__(self, other: 'QueryHistogramAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Nested(QueryAggregation): +class QueryNestedAggregation(QueryAggregation): """ - Nested. + A restriction that alters the document set that is used for sub-aggregations it + precedes to nested documents found in the field specified. - :attr str path: (optional) The area of the results the aggregation was - restricted to. + :attr str path: The path to the document field to scope sub-aggregations to. + :attr int matching_results: Number of nested documents found in the specified + field. + :attr List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ def __init__(self, + type: str, + path: str, + matching_results: int, *, - type: str = None, - results: List['AggregationResult'] = None, - matching_results: int = None, - aggregations: List['QueryAggregation'] = None, - path: str = None) -> None: + aggregations: List['QueryAggregation'] = None) -> None: """ - Initialize a Nested object. + Initialize a QueryNestedAggregation object. - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param List[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param List[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str path: (optional) The area of the results the aggregation was - restricted to. + :param str type: The type of aggregation command used. For example: term, + filter, max, min, etc. + :param str path: The path to the document field to scope sub-aggregations + to. + :param int matching_results: Number of nested documents found in the + specified field. + :param List[QueryAggregation] aggregations: (optional) An array of + sub-aggregations. """ self.type = type - self.results = results + self.path = path self.matching_results = matching_results self.aggregations = aggregations - self.path = path @classmethod - def from_dict(cls, _dict: Dict) -> 'Nested': - """Initialize a Nested object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryNestedAggregation': + """Initialize a QueryNestedAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - if 'results' in _dict: - args['results'] = [ - AggregationResult.from_dict(x) for x in _dict.get('results') - ] + else: + raise ValueError( + 'Required property \'type\' not present in QueryNestedAggregation JSON' + ) + if 'path' in _dict: + args['path'] = _dict.get('path') + else: + raise ValueError( + 'Required property \'path\' not present in QueryNestedAggregation JSON' + ) if 'matching_results' in _dict: args['matching_results'] = _dict.get('matching_results') + else: + raise ValueError( + 'Required property \'matching_results\' not present in QueryNestedAggregation JSON' + ) if 'aggregations' in _dict: args['aggregations'] = [ QueryAggregation.from_dict(x) for x in _dict.get('aggregations') ] - if 'path' in _dict: - args['path'] = _dict.get('path') return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Nested object from a json dictionary.""" + """Initialize a QueryNestedAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -13323,15 +13509,13 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] + if hasattr(self, 'path') and self.path is not None: + _dict['path'] = self.path if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['matching_results'] = self.matching_results if hasattr(self, 'aggregations') and self.aggregations is not None: _dict['aggregations'] = [x.to_dict() for x in self.aggregations] - if hasattr(self, 'path') and self.path is not None: - _dict['path'] = self.path return _dict def _to_dict(self): @@ -13339,83 +13523,88 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Nested object.""" + """Return a `str` version of this QueryNestedAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Nested') -> bool: + def __eq__(self, other: 'QueryNestedAggregation') -> 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: 'Nested') -> bool: + def __ne__(self, other: 'QueryNestedAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Term(QueryAggregation): +class QueryTermAggregation(QueryAggregation): """ - Term. + Returns the top values for the field specified. - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr int count: (optional) The number of terms identified. + :attr str field: The field in the document used to generate top values from. + :attr int count: (optional) The number of top values returned. + :attr str name: (optional) Identifier specified in the query request of this + aggregation. + :attr List[QueryTermAggregationResult] results: (optional) Array of top values + for the field. """ def __init__(self, + type: str, + field: str, *, - type: str = None, - results: List['AggregationResult'] = None, - matching_results: int = None, - aggregations: List['QueryAggregation'] = None, - field: str = None, - count: int = None) -> None: + count: int = None, + name: str = None, + results: List['QueryTermAggregationResult'] = None) -> None: """ - Initialize a Term object. + Initialize a QueryTermAggregation object. - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param List[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param List[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param int count: (optional) The number of terms identified. + :param str type: The type of aggregation command used. For example: term, + filter, max, min, etc. + :param str field: The field in the document used to generate top values + from. + :param int count: (optional) The number of top values returned. + :param str name: (optional) Identifier specified in the query request of + this aggregation. + :param List[QueryTermAggregationResult] results: (optional) Array of top + values for the field. """ self.type = type - self.results = results - self.matching_results = matching_results - self.aggregations = aggregations self.field = field self.count = count + self.name = name + self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'Term': - """Initialize a Term object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryTermAggregation': + """Initialize a QueryTermAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - if 'results' in _dict: - args['results'] = [ - AggregationResult.from_dict(x) for x in _dict.get('results') - ] - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + else: + raise ValueError( + 'Required property \'type\' not present in QueryTermAggregation JSON' + ) if 'field' in _dict: args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryTermAggregation JSON' + ) if 'count' in _dict: args['count'] = _dict.get('count') + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'results' in _dict: + args['results'] = [ + QueryTermAggregationResult.from_dict(x) + for x in _dict.get('results') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Term object from a json dictionary.""" + """Initialize a QueryTermAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -13423,17 +13612,14 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'count') and self.count is not None: _dict['count'] = self.count + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x.to_dict() for x in self.results] return _dict def _to_dict(self): @@ -13441,97 +13627,94 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Term object.""" + """Return a `str` version of this QueryTermAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Term') -> bool: + def __eq__(self, other: 'QueryTermAggregation') -> 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: 'Term') -> bool: + def __ne__(self, other: 'QueryTermAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class Timeslice(QueryAggregation): +class QueryTimesliceAggregation(QueryAggregation): """ - Timeslice. + A specialized histogram aggregation that uses dates to create interval segments. - :attr str field: (optional) The field where the aggregation is located in the - document. - :attr str interval: (optional) Interval of the aggregation. Valid date interval - values are second/seconds minute/minutes, hour/hours, day/days, week/weeks, - month/months, and year/years. - :attr bool anomaly: (optional) Used to indicate that anomaly detection should be - performed. Anomaly detection is used to locate unusual datapoints within a time - series. + :attr str field: The date field name used to create the timeslice. + :attr str interval: The date interval value. Valid values are seconds, minutes, + hours, days, weeks, and years. + :attr str name: (optional) Identifier specified in the query request of this + aggregation. + :attr List[QueryTimesliceAggregationResult] results: (optional) Array of + aggregation results. """ - def __init__(self, - *, - type: str = None, - results: List['AggregationResult'] = None, - matching_results: int = None, - aggregations: List['QueryAggregation'] = None, - field: str = None, - interval: str = None, - anomaly: bool = None) -> None: + def __init__( + self, + type: str, + field: str, + interval: str, + *, + name: str = None, + results: List['QueryTimesliceAggregationResult'] = None) -> None: """ - Initialize a Timeslice object. + Initialize a QueryTimesliceAggregation object. - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param List[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param List[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param str field: (optional) The field where the aggregation is located in - the document. - :param str interval: (optional) Interval of the aggregation. Valid date - interval values are second/seconds minute/minutes, hour/hours, day/days, - week/weeks, month/months, and year/years. - :param bool anomaly: (optional) Used to indicate that anomaly detection - should be performed. Anomaly detection is used to locate unusual datapoints - within a time series. + :param str type: The type of aggregation command used. For example: term, + filter, max, min, etc. + :param str field: The date field name used to create the timeslice. + :param str interval: The date interval value. Valid values are seconds, + minutes, hours, days, weeks, and years. + :param str name: (optional) Identifier specified in the query request of + this aggregation. + :param List[QueryTimesliceAggregationResult] results: (optional) Array of + aggregation results. """ self.type = type - self.results = results - self.matching_results = matching_results - self.aggregations = aggregations self.field = field self.interval = interval - self.anomaly = anomaly + self.name = name + self.results = results @classmethod - def from_dict(cls, _dict: Dict) -> 'Timeslice': - """Initialize a Timeslice object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryTimesliceAggregation': + """Initialize a QueryTimesliceAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - if 'results' in _dict: - args['results'] = [ - AggregationResult.from_dict(x) for x in _dict.get('results') - ] - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + else: + raise ValueError( + 'Required property \'type\' not present in QueryTimesliceAggregation JSON' + ) if 'field' in _dict: args['field'] = _dict.get('field') + else: + raise ValueError( + 'Required property \'field\' not present in QueryTimesliceAggregation JSON' + ) if 'interval' in _dict: args['interval'] = _dict.get('interval') - if 'anomaly' in _dict: - args['anomaly'] = _dict.get('anomaly') + else: + raise ValueError( + 'Required property \'interval\' not present in QueryTimesliceAggregation JSON' + ) + if 'name' in _dict: + args['name'] = _dict.get('name') + if 'results' in _dict: + args['results'] = [ + QueryTimesliceAggregationResult.from_dict(x) + for x in _dict.get('results') + ] return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a Timeslice object from a json dictionary.""" + """Initialize a QueryTimesliceAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -13539,19 +13722,14 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'field') and self.field is not None: _dict['field'] = self.field if hasattr(self, 'interval') and self.interval is not None: _dict['interval'] = self.interval - if hasattr(self, 'anomaly') and self.anomaly is not None: - _dict['anomaly'] = self.anomaly + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name + if hasattr(self, 'results') and self.results is not None: + _dict['results'] = [x.to_dict() for x in self.results] return _dict def _to_dict(self): @@ -13559,81 +13737,77 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this Timeslice object.""" + """Return a `str` version of this QueryTimesliceAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'Timeslice') -> bool: + def __eq__(self, other: 'QueryTimesliceAggregation') -> 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: 'Timeslice') -> bool: + def __ne__(self, other: 'QueryTimesliceAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other -class TopHits(QueryAggregation): +class QueryTopHitsAggregation(QueryAggregation): """ - TopHits. + Returns the top documents ranked by the score of the query. - :attr int size: (optional) Number of top hits returned by the aggregation. - :attr TopHitsResults hits: (optional) + :attr int size: The number of documents to return. + :attr str name: (optional) Identifier specified in the query request of this + aggregation. + :attr QueryTopHitsAggregationResult hits: (optional) """ def __init__(self, + type: str, + size: int, *, - type: str = None, - results: List['AggregationResult'] = None, - matching_results: int = None, - aggregations: List['QueryAggregation'] = None, - size: int = None, - hits: 'TopHitsResults' = None) -> None: + name: str = None, + hits: 'QueryTopHitsAggregationResult' = None) -> None: """ - Initialize a TopHits object. + Initialize a QueryTopHitsAggregation object. - :param str type: (optional) The type of aggregation command used. For - example: term, filter, max, min, etc. - :param List[AggregationResult] results: (optional) Array of aggregation - results. - :param int matching_results: (optional) Number of matching results. - :param List[QueryAggregation] aggregations: (optional) Aggregations - returned by Discovery. - :param int size: (optional) Number of top hits returned by the aggregation. - :param TopHitsResults hits: (optional) + :param str type: The type of aggregation command used. For example: term, + filter, max, min, etc. + :param int size: The number of documents to return. + :param str name: (optional) Identifier specified in the query request of + this aggregation. + :param QueryTopHitsAggregationResult hits: (optional) """ self.type = type - self.results = results - self.matching_results = matching_results - self.aggregations = aggregations self.size = size + self.name = name self.hits = hits @classmethod - def from_dict(cls, _dict: Dict) -> 'TopHits': - """Initialize a TopHits object from a json dictionary.""" + def from_dict(cls, _dict: Dict) -> 'QueryTopHitsAggregation': + """Initialize a QueryTopHitsAggregation object from a json dictionary.""" args = {} if 'type' in _dict: args['type'] = _dict.get('type') - if 'results' in _dict: - args['results'] = [ - AggregationResult.from_dict(x) for x in _dict.get('results') - ] - if 'matching_results' in _dict: - args['matching_results'] = _dict.get('matching_results') - if 'aggregations' in _dict: - args['aggregations'] = [ - QueryAggregation.from_dict(x) for x in _dict.get('aggregations') - ] + else: + raise ValueError( + 'Required property \'type\' not present in QueryTopHitsAggregation JSON' + ) if 'size' in _dict: args['size'] = _dict.get('size') + else: + raise ValueError( + 'Required property \'size\' not present in QueryTopHitsAggregation JSON' + ) + if 'name' in _dict: + args['name'] = _dict.get('name') if 'hits' in _dict: - args['hits'] = TopHitsResults.from_dict(_dict.get('hits')) + args['hits'] = QueryTopHitsAggregationResult.from_dict( + _dict.get('hits')) return cls(**args) @classmethod def _from_dict(cls, _dict): - """Initialize a TopHits object from a json dictionary.""" + """Initialize a QueryTopHitsAggregation object from a json dictionary.""" return cls.from_dict(_dict) def to_dict(self) -> Dict: @@ -13641,15 +13815,10 @@ def to_dict(self) -> Dict: _dict = {} if hasattr(self, 'type') and self.type is not None: _dict['type'] = self.type - if hasattr(self, 'results') and self.results is not None: - _dict['results'] = [x.to_dict() for x in self.results] - if hasattr(self, - 'matching_results') and self.matching_results is not None: - _dict['matching_results'] = self.matching_results - if hasattr(self, 'aggregations') and self.aggregations is not None: - _dict['aggregations'] = [x.to_dict() for x in self.aggregations] if hasattr(self, 'size') and self.size is not None: _dict['size'] = self.size + if hasattr(self, 'name') and self.name is not None: + _dict['name'] = self.name if hasattr(self, 'hits') and self.hits is not None: _dict['hits'] = self.hits.to_dict() return _dict @@ -13659,15 +13828,15 @@ def _to_dict(self): return self.to_dict() def __str__(self) -> str: - """Return a `str` version of this TopHits object.""" + """Return a `str` version of this QueryTopHitsAggregation object.""" return json.dumps(self.to_dict(), indent=2) - def __eq__(self, other: 'TopHits') -> bool: + def __eq__(self, other: 'QueryTopHitsAggregation') -> 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: 'TopHits') -> bool: + def __ne__(self, other: 'QueryTopHitsAggregation') -> bool: """Return `true` when self and other are not equal, false otherwise.""" return not self == other diff --git a/ibm_watson/language_translator_v3.py b/ibm_watson/language_translator_v3.py index 59a3663d6..d24244403 100644 --- a/ibm_watson/language_translator_v3.py +++ b/ibm_watson/language_translator_v3.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2019, 2020. +# (C) Copyright IBM Corp. 2019, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 +# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 """ IBM Watson™ Language Translator translates text from one language to another. The service offers multiple IBM-provided translation models that you can customize based on @@ -63,7 +63,7 @@ def __init__( Specify dates in YYYY-MM-DD format. The current version is `2018-05-01`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md about initializing the authenticator of your choice. """ if version is None: diff --git a/ibm_watson/natural_language_classifier_v1.py b/ibm_watson/natural_language_classifier_v1.py deleted file mode 100644 index 4b8543694..000000000 --- a/ibm_watson/natural_language_classifier_v1.py +++ /dev/null @@ -1,895 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2019, 2020. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 -""" -On 9 August 2021, IBM announced the deprecation of IBM Watson™ Natural Language -Classifier. As of 9 September 2021, you cannot create new instances. However, existing -instances are supported until 8 August 2022. The service will no longer be available on 8 -August 2022.

As an alternative, consider migrating to IBM Watson Natural Language -Understanding. For more information, see [Migrating to Natural Language -Understanding](https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating). -{: deprecated} -Natural Language Classifier uses machine learning algorithms to return the top matching -predefined classes for short text input. You create and train a classifier to connect -predefined classes to example texts so that the service can apply those classes to new -inputs. - -API Version: 1.0 -See: https://cloud.ibm.com/docs/natural-language-classifier -""" - -from datetime import datetime -from enum import Enum -from typing import BinaryIO, Dict, List -import json - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import convert_model, datetime_to_string, string_to_datetime - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class NaturalLanguageClassifierV1(BaseService): - """The Natural Language Classifier V1 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.natural-language-classifier.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'natural_language_classifier' - - def __init__( - self, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Natural Language Classifier service. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md - about initializing the authenticator of your choice. - """ - print( - """ - On 9 August 2021, IBM announced the deprecation of the Natural Language Classifier service. - The service will no longer be available from 8 August 2022. As of 9 September 2021, you will not be able to create new instances. - Existing instances will be supported until 8 August 2022. Any instance that still exists on that date will be deleted. - For more information, see https://cloud.ibm.com/docs/natural-language-classifier?topic=natural-language-classifier-migrating - """ - ) - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.configure_service(service_name) - - ######################### - # Classify text - ######################### - - def classify(self, classifier_id: str, text: str, - **kwargs) -> DetailedResponse: - """ - Classify a phrase. - - Returns label information for the input. The status must be `Available` before you - can use the classifier to classify text. - - :param str classifier_id: Classifier ID to use. - :param str text: The submitted phrase. The maximum length is 2048 - characters. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Classification` object - """ - - if classifier_id is None: - raise ValueError('classifier_id must be provided') - if text is None: - raise ValueError('text must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='classify') - headers.update(sdk_headers) - - data = {'text': text} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['classifier_id'] - path_param_values = self.encode_path_vars(classifier_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/classifiers/{classifier_id}/classify'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) - - response = self.send(request, **kwargs) - return response - - def classify_collection(self, classifier_id: str, - collection: List['ClassifyInput'], - **kwargs) -> DetailedResponse: - """ - Classify multiple phrases. - - Returns label information for multiple phrases. The status must be `Available` - before you can use the classifier to classify text. - Note that classifying Japanese texts is a beta feature. - - :param str classifier_id: Classifier ID to use. - :param List[ClassifyInput] collection: The submitted phrases. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ClassificationCollection` object - """ - - if classifier_id is None: - raise ValueError('classifier_id must be provided') - if collection is None: - raise ValueError('collection must be provided') - collection = [convert_model(x) for x in collection] - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='classify_collection') - headers.update(sdk_headers) - - data = {'collection': collection} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['classifier_id'] - path_param_values = self.encode_path_vars(classifier_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/classifiers/{classifier_id}/classify_collection'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - data=data) - - response = self.send(request, **kwargs) - return response - - ######################### - # Manage classifiers - ######################### - - def create_classifier(self, training_metadata: BinaryIO, - training_data: BinaryIO, - **kwargs) -> DetailedResponse: - """ - Create classifier. - - Sends data to create and train a classifier and returns information about the new - classifier. - - :param BinaryIO training_metadata: Metadata in JSON format. The metadata - identifies the language of the data, and an optional name to identify the - classifier. Specify the language with the 2-letter primary language code as - assigned in ISO standard 639. - Supported languages are English (`en`), Arabic (`ar`), French (`fr`), - German, (`de`), Italian (`it`), Japanese (`ja`), Korean (`ko`), Brazilian - Portuguese (`pt`), and Spanish (`es`). - :param BinaryIO 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/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 with `dict` result representing a `Classifier` object - """ - - if training_metadata is None: - raise ValueError('training_metadata must be provided') - if training_data is None: - raise ValueError('training_data must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='create_classifier') - headers.update(sdk_headers) - - form_data = [] - form_data.append(('training_metadata', (None, training_metadata, - 'application/json'))) - form_data.append(('training_data', (None, training_data, 'text/csv'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/classifiers' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def list_classifiers(self, **kwargs) -> DetailedResponse: - """ - List classifiers. - - Returns an empty array if no classifiers are available. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ClassifierList` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='list_classifiers') - headers.update(sdk_headers) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v1/classifiers' - request = self.prepare_request(method='GET', url=url, headers=headers) - - response = self.send(request, **kwargs) - return response - - def get_classifier(self, classifier_id: str, **kwargs) -> DetailedResponse: - """ - Get information about a classifier. - - Returns status and other information about a classifier. - - :param str classifier_id: Classifier ID to query. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Classifier` object - """ - - if classifier_id is None: - raise ValueError('classifier_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='get_classifier') - headers.update(sdk_headers) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['classifier_id'] - path_param_values = self.encode_path_vars(classifier_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/classifiers/{classifier_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', url=url, headers=headers) - - response = self.send(request, **kwargs) - return response - - def delete_classifier(self, classifier_id: str, - **kwargs) -> DetailedResponse: - """ - Delete classifier. - - :param str classifier_id: Classifier ID to delete. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if classifier_id is None: - raise ValueError('classifier_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V1', - operation_id='delete_classifier') - headers.update(sdk_headers) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['classifier_id'] - path_param_values = self.encode_path_vars(classifier_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v1/classifiers/{classifier_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers) - - response = self.send(request, **kwargs) - return response - - -############################################################################## -# Models -############################################################################## - - -class Classification(): - """ - Response from the classifier for a phrase. - - :attr str classifier_id: (optional) Unique identifier for this classifier. - :attr str url: (optional) Link to the classifier. - :attr str text: (optional) The submitted phrase. - :attr str top_class: (optional) The class with the highest confidence. - :attr List[ClassifiedClass] classes: (optional) An array of up to ten - class-confidence pairs sorted in descending order of confidence. - """ - - def __init__(self, - *, - classifier_id: str = None, - url: str = None, - text: str = None, - top_class: str = None, - classes: List['ClassifiedClass'] = None) -> None: - """ - Initialize a Classification object. - - :param str classifier_id: (optional) Unique identifier for this classifier. - :param str url: (optional) Link to the classifier. - :param str text: (optional) The submitted phrase. - :param str top_class: (optional) The class with the highest confidence. - :param List[ClassifiedClass] classes: (optional) An array of up to ten - class-confidence pairs sorted in descending order of confidence. - """ - self.classifier_id = classifier_id - self.url = url - self.text = text - self.top_class = top_class - self.classes = classes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Classification': - """Initialize a Classification object from a json dictionary.""" - args = {} - if 'classifier_id' in _dict: - args['classifier_id'] = _dict.get('classifier_id') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'top_class' in _dict: - args['top_class'] = _dict.get('top_class') - if 'classes' in _dict: - args['classes'] = [ - ClassifiedClass.from_dict(x) for x in _dict.get('classes') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Classification 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, 'classifier_id') and self.classifier_id is not None: - _dict['classifier_id'] = self.classifier_id - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'top_class') and self.top_class is not None: - _dict['top_class'] = self.top_class - if hasattr(self, 'classes') and self.classes is not None: - _dict['classes'] = [x.to_dict() for x in self.classes] - 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 Classification object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Classification') -> 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: 'Classification') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ClassificationCollection(): - """ - Response from the classifier for multiple phrases. - - :attr str classifier_id: (optional) Unique identifier for this classifier. - :attr str url: (optional) Link to the classifier. - :attr List[CollectionItem] collection: (optional) An array of classifier - responses for each submitted phrase. - """ - - def __init__(self, - *, - classifier_id: str = None, - url: str = None, - collection: List['CollectionItem'] = None) -> None: - """ - Initialize a ClassificationCollection object. - - :param str classifier_id: (optional) Unique identifier for this classifier. - :param str url: (optional) Link to the classifier. - :param List[CollectionItem] collection: (optional) An array of classifier - responses for each submitted phrase. - """ - self.classifier_id = classifier_id - self.url = url - self.collection = collection - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ClassificationCollection': - """Initialize a ClassificationCollection object from a json dictionary.""" - args = {} - if 'classifier_id' in _dict: - args['classifier_id'] = _dict.get('classifier_id') - if 'url' in _dict: - args['url'] = _dict.get('url') - if 'collection' in _dict: - args['collection'] = [ - CollectionItem.from_dict(x) for x in _dict.get('collection') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ClassificationCollection 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, 'classifier_id') and self.classifier_id is not None: - _dict['classifier_id'] = self.classifier_id - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'collection') and self.collection is not None: - _dict['collection'] = [x.to_dict() for x in self.collection] - 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 ClassificationCollection object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ClassificationCollection') -> 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: 'ClassificationCollection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ClassifiedClass(): - """ - Class and confidence. - - :attr float confidence: (optional) A decimal percentage that represents the - confidence that Watson has in this class. Higher values represent higher - confidences. - :attr str class_name: (optional) Class label. - """ - - def __init__(self, - *, - confidence: float = None, - class_name: str = None) -> None: - """ - Initialize a ClassifiedClass object. - - :param float confidence: (optional) A decimal percentage that represents - the confidence that Watson has in this class. Higher values represent - higher confidences. - :param str class_name: (optional) Class label. - """ - self.confidence = confidence - self.class_name = class_name - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ClassifiedClass': - """Initialize a ClassifiedClass object from a json dictionary.""" - args = {} - if 'confidence' in _dict: - args['confidence'] = _dict.get('confidence') - if 'class_name' in _dict: - args['class_name'] = _dict.get('class_name') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ClassifiedClass 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, 'confidence') and self.confidence is not None: - _dict['confidence'] = self.confidence - if hasattr(self, 'class_name') and self.class_name is not None: - _dict['class_name'] = self.class_name - 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 ClassifiedClass object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ClassifiedClass') -> 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: 'ClassifiedClass') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Classifier(): - """ - A classifier for natural language phrases. - - :attr str name: (optional) User-supplied name for the classifier. - :attr str url: Link to the classifier. - :attr str status: (optional) The state of the classifier. - :attr str classifier_id: Unique identifier for this classifier. - :attr datetime created: (optional) Date and time (UTC) the classifier was - created. - :attr str status_description: (optional) Additional detail about the status. - :attr str language: (optional) The language used for the classifier. - """ - - def __init__(self, - url: str, - classifier_id: str, - *, - name: str = None, - status: str = None, - created: datetime = None, - status_description: str = None, - language: str = None) -> None: - """ - Initialize a Classifier object. - - :param str url: Link to the classifier. - :param str classifier_id: Unique identifier for this classifier. - :param str name: (optional) User-supplied name for the classifier. - :param str language: (optional) The language used for the classifier. - """ - self.name = name - self.url = url - self.status = status - self.classifier_id = classifier_id - self.created = created - self.status_description = status_description - self.language = language - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Classifier': - """Initialize a Classifier object from a json dictionary.""" - args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'url' in _dict: - args['url'] = _dict.get('url') - else: - raise ValueError( - 'Required property \'url\' not present in Classifier JSON') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'classifier_id' in _dict: - args['classifier_id'] = _dict.get('classifier_id') - else: - raise ValueError( - 'Required property \'classifier_id\' not present in Classifier JSON' - ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'status_description' in _dict: - args['status_description'] = _dict.get('status_description') - if 'language' in _dict: - args['language'] = _dict.get('language') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Classifier 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'url') and self.url is not None: - _dict['url'] = self.url - if hasattr(self, 'status') and getattr(self, 'status') is not None: - _dict['status'] = getattr(self, 'status') - if hasattr(self, 'classifier_id') and self.classifier_id is not None: - _dict['classifier_id'] = self.classifier_id - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'status_description') and getattr( - self, 'status_description') is not None: - _dict['status_description'] = getattr(self, 'status_description') - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - 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 Classifier object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Classifier') -> 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: 'Classifier') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - The state of the classifier. - """ - NON_EXISTENT = 'Non Existent' - TRAINING = 'Training' - FAILED = 'Failed' - AVAILABLE = 'Available' - UNAVAILABLE = 'Unavailable' - - -class ClassifierList(): - """ - List of available classifiers. - - :attr List[Classifier] classifiers: The classifiers available to the user. - Returns an empty array if no classifiers are available. - """ - - def __init__(self, classifiers: List['Classifier']) -> None: - """ - Initialize a ClassifierList object. - - :param List[Classifier] classifiers: The classifiers available to the user. - Returns an empty array if no classifiers are available. - """ - self.classifiers = classifiers - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ClassifierList': - """Initialize a ClassifierList object from a json dictionary.""" - args = {} - if 'classifiers' in _dict: - args['classifiers'] = [ - Classifier.from_dict(x) for x in _dict.get('classifiers') - ] - else: - raise ValueError( - 'Required property \'classifiers\' not present in ClassifierList JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ClassifierList 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, 'classifiers') and self.classifiers is not None: - _dict['classifiers'] = [x.to_dict() for x in self.classifiers] - 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 ClassifierList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ClassifierList') -> 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: 'ClassifierList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ClassifyInput(): - """ - Request payload to classify. - - :attr str text: The submitted phrase. The maximum length is 2048 characters. - """ - - def __init__(self, text: str) -> None: - """ - Initialize a ClassifyInput object. - - :param str text: The submitted phrase. The maximum length is 2048 - characters. - """ - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ClassifyInput': - """Initialize a ClassifyInput object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in ClassifyInput JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ClassifyInput 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, 'text') and self.text is not None: - _dict['text'] = self.text - 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 ClassifyInput object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ClassifyInput') -> 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: 'ClassifyInput') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CollectionItem(): - """ - Response from the classifier for a phrase in a collection. - - :attr str text: (optional) The submitted phrase. The maximum length is 2048 - characters. - :attr str top_class: (optional) The class with the highest confidence. - :attr List[ClassifiedClass] classes: (optional) An array of up to ten - class-confidence pairs sorted in descending order of confidence. - """ - - def __init__(self, - *, - text: str = None, - top_class: str = None, - classes: List['ClassifiedClass'] = None) -> None: - """ - Initialize a CollectionItem object. - - :param str text: (optional) The submitted phrase. The maximum length is - 2048 characters. - :param str top_class: (optional) The class with the highest confidence. - :param List[ClassifiedClass] classes: (optional) An array of up to ten - class-confidence pairs sorted in descending order of confidence. - """ - self.text = text - self.top_class = top_class - self.classes = classes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionItem': - """Initialize a CollectionItem object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - if 'top_class' in _dict: - args['top_class'] = _dict.get('top_class') - if 'classes' in _dict: - args['classes'] = [ - ClassifiedClass.from_dict(x) for x in _dict.get('classes') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CollectionItem 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'top_class') and self.top_class is not None: - _dict['top_class'] = self.top_class - if hasattr(self, 'classes') and self.classes is not None: - _dict['classes'] = [x.to_dict() for x in self.classes] - 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 CollectionItem object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CollectionItem') -> 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: 'CollectionItem') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other diff --git a/ibm_watson/natural_language_understanding_v1.py b/ibm_watson/natural_language_understanding_v1.py index bd3456a5b..0ae9da787 100644 --- a/ibm_watson/natural_language_understanding_v1.py +++ b/ibm_watson/natural_language_understanding_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2017, 2021. +# (C) Copyright IBM Corp. 2017, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 +# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 """ Analyze various features of text content at scale. Provide text, raw HTML, or a public URL and IBM Watson Natural Language Understanding will give you results for the features you @@ -65,7 +65,7 @@ def __init__( Specify dates in YYYY-MM-DD format. The current version is `2021-08-01`. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md about initializing the authenticator of your choice. """ if version is None: @@ -2305,11 +2305,13 @@ def __ne__(self, other: 'ClassificationsModelList') -> bool: class ClassificationsOptions(): """ Returns text classifications for the content. - Supported languages: English only. :attr str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) - ID of the classification model to be used. + ID of the classifications model to be used. + You can analyze tone by using a language-specific model ID. See [Tone analytics + (Classifications)](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-tone_analytics) + for more information. """ def __init__(self, *, model: str = None) -> None: @@ -2318,7 +2320,11 @@ def __init__(self, *, model: str = None) -> None: :param str model: (optional) Enter a [custom model](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-customizing) - ID of the classification model to be used. + ID of the classifications model to be used. + You can analyze tone by using a language-specific model ID. See [Tone + analytics + (Classifications)](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-tone_analytics) + for more information. """ self.model = model @@ -3442,7 +3448,6 @@ class Features(): :attr ClassificationsOptions classifications: (optional) Returns text classifications for the content. - Supported languages: English only. :attr ConceptsOptions concepts: (optional) Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. @@ -3464,9 +3469,9 @@ class Features(): content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :attr MetadataOptions metadata: (optional) Returns information from the - document, including author name, title, RSS/ATOM feeds, prominent page image, - and publication date. Supports URL and HTML input types only. + :attr dict metadata: (optional) Returns information from the document, including + author name, title, RSS/ATOM feeds, prominent page image, and publication date. + Supports URL and HTML input types only. :attr RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". For @@ -3502,7 +3507,7 @@ def __init__(self, emotion: 'EmotionOptions' = None, entities: 'EntitiesOptions' = None, keywords: 'KeywordsOptions' = None, - metadata: 'MetadataOptions' = None, + metadata: dict = None, relations: 'RelationsOptions' = None, semantic_roles: 'SemanticRolesOptions' = None, sentiment: 'SentimentOptions' = None, @@ -3514,7 +3519,6 @@ def __init__(self, :param ClassificationsOptions classifications: (optional) Returns text classifications for the content. - Supported languages: English only. :param ConceptsOptions concepts: (optional) Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. @@ -3537,9 +3541,9 @@ def __init__(self, the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - :param MetadataOptions metadata: (optional) Returns information from the - document, including author name, title, RSS/ATOM feeds, prominent page - image, and publication date. Supports URL and HTML input types only. + :param dict metadata: (optional) Returns information from the document, + including author name, title, RSS/ATOM feeds, prominent page image, and + publication date. Supports URL and HTML input types only. :param RelationsOptions relations: (optional) Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert @@ -3596,7 +3600,7 @@ def from_dict(cls, _dict: Dict) -> 'Features': if 'keywords' in _dict: args['keywords'] = KeywordsOptions.from_dict(_dict.get('keywords')) if 'metadata' in _dict: - args['metadata'] = MetadataOptions.from_dict(_dict.get('metadata')) + args['metadata'] = _dict.get('metadata') if 'relations' in _dict: args['relations'] = RelationsOptions.from_dict( _dict.get('relations')) @@ -3636,7 +3640,7 @@ def to_dict(self) -> Dict: if hasattr(self, 'keywords') and self.keywords is not None: _dict['keywords'] = self.keywords.to_dict() if hasattr(self, 'metadata') and self.metadata is not None: - _dict['metadata'] = self.metadata.to_dict() + _dict['metadata'] = self.metadata if hasattr(self, 'relations') and self.relations is not None: _dict['relations'] = self.relations.to_dict() if hasattr(self, 'semantic_roles') and self.semantic_roles is not None: @@ -4102,52 +4106,6 @@ def __ne__(self, other: 'ListSentimentModelsResponse') -> bool: return not self == other -class MetadataOptions(): - """ - Returns information from the document, including author name, title, RSS/ATOM feeds, - prominent page image, and publication date. Supports URL and HTML input types only. - - """ - - def __init__(self) -> None: - """ - Initialize a MetadataOptions object. - - """ - - @classmethod - def from_dict(cls, _dict: Dict) -> 'MetadataOptions': - """Initialize a MetadataOptions object from a json dictionary.""" - return cls(**_dict) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a MetadataOptions object from a json dictionary.""" - return cls.from_dict(_dict) - - def to_dict(self) -> Dict: - """Return a json dictionary representing this model.""" - return vars(self) - - 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 MetadataOptions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'MetadataOptions') -> 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: 'MetadataOptions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class Model(): """ Model. diff --git a/ibm_watson/personality_insights_v3.py b/ibm_watson/personality_insights_v3.py deleted file mode 100644 index 4ef2e1d75..000000000 --- a/ibm_watson/personality_insights_v3.py +++ /dev/null @@ -1,1342 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2016, 2021. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 -""" -IBM Watson™ Personality Insights is discontinued. Existing instances are supported -until 1 December 2021, but as of 1 December 2020, you cannot create new instances. Any -instance that exists on 1 December 2021 will be deleted.

No direct replacement -exists for Personality Insights. However, you can consider using [IBM Watson™ -Natural Language -Understanding](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-about) -on IBM Cloud® as part of a replacement analytic workflow for your Personality Insights -use cases. You can use Natural Language Understanding to extract data and insights from -text, such as keywords, categories, sentiment, emotion, and syntax. For more information -about the personality models in Personality Insights, see [The science behind the -service](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-science). -{: deprecated} -The IBM Watson Personality Insights service enables applications to derive insights from -social media, enterprise data, or other digital communications. The service uses -linguistic analytics to infer individuals' intrinsic personality characteristics, -including Big Five, Needs, and Values, from digital communications such as email, text -messages, tweets, and forum posts. -The service can automatically infer, from potentially noisy social media, portraits of -individuals that reflect their personality characteristics. The service can infer -consumption preferences based on the results of its analysis and, for JSON content that is -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/personality-insights?topic=personality-insights-models#models). -* For information about the meaning of the consumption preferences, see [Consumption -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. - -API Version: 3.4.4 -See: https://cloud.ibm.com/docs/personality-insights -""" - -from enum import Enum -from typing import Dict, List, TextIO, Union -import json - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import convert_model - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class PersonalityInsightsV3(BaseService): - """The Personality Insights V3 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.personality-insights.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'personality_insights' - - def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Personality Insights service. - - :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2017-10-13`. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md - about initializing the authenticator of your choice. - """ - print( - 'warning: On 1 December 2021, Personality Insights will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#personality-insights-deprecation.' - ) - if version is None: - raise ValueError('version must be provided') - - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.version = version - self.configure_service(service_name) - - ######################### - # Methods - ######################### - - def profile(self, - content: Union['Content', str, TextIO], - accept: str, - *, - content_type: str = None, - content_language: str = None, - accept_language: str = None, - raw_scores: bool = None, - csv_headers: bool = None, - consumption_preferences: bool = None, - **kwargs) -> DetailedResponse: - """ - Get profile. - - Generates a personality profile for the author of the input text. The service - accepts a maximum of 20 MB of input content, but it requires much less text to - produce an accurate profile. The service can analyze text in Arabic, English, - Japanese, Korean, or Spanish. It can return its results in a variety of languages. - **See also:** - * [Requesting a - profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-input#input) - * [Providing 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 - default is `text/plain`. - * Per the JSON specification, the default character encoding for JSON content is - effectively always UTF-8. - * Per the HTTP specification, the default encoding for plain text and HTML is - ISO-8859-1 (effectively, the ASCII character set). - When specifying a content type of plain text or HTML, include the `charset` - 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/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 - fixed number of columns. Set the **csv_headers** parameter to `true` to request - optional column headers for CSV output. - **See also:** - * [Understanding a JSON - profile](https://cloud.ibm.com/docs/personality-insights?topic=personality-insights-output#output) - * [Understanding a CSV - 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/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. - :param str content_type: (optional) The type of the input. For more - information, see **Content types** in the method description. - :param str content_language: (optional) The language of the input text for - the request: Arabic, English, Japanese, Korean, or Spanish. Regional - variants are treated as their parent language; for example, `en-US` is - interpreted as `en`. - The effect of the **Content-Language** parameter depends on the - **Content-Type** parameter. When **Content-Type** is `text/plain` or - `text/html`, **Content-Language** is the only way to specify the language. - When **Content-Type** is `application/json`, **Content-Language** overrides - a language specified with the `language` parameter of a `ContentItem` - object, and content items that specify a different language are ignored; - omit this parameter to base the language on the specification of the - content items. You can specify any combination of languages for - **Content-Language** and **Accept-Language**. - :param str accept_language: (optional) The desired language of the - response. For two-character arguments, regional variants are treated as - their parent language; for example, `en-US` is interpreted as `en`. You can - specify any combination of languages for the input and response content. - :param bool raw_scores: (optional) Indicates whether a raw score in - addition to a normalized percentile is returned for each characteristic; - raw scores are not compared with a sample population. By default, only - normalized percentiles are returned. - :param bool csv_headers: (optional) Indicates whether column labels are - returned with a CSV response. By default, no column labels are returned. - Applies only when the response type is CSV (`text/csv`). - :param bool consumption_preferences: (optional) Indicates whether - consumption preferences are returned with the results. By default, no - consumption preferences are returned. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Profile` object - """ - - if content is None: - raise ValueError('content must be provided') - if accept is None: - raise ValueError('accept must be provided') - if isinstance(content, Content): - content = convert_model(content) - content_type = content_type or 'application/json' - headers = { - 'Accept': accept, - 'Content-Type': content_type, - 'Content-Language': content_language, - 'Accept-Language': accept_language - } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='profile') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'raw_scores': raw_scores, - 'csv_headers': csv_headers, - 'consumption_preferences': consumption_preferences - } - - if isinstance(content, dict): - data = json.dumps(content) - if content_type is None: - headers['Content-Type'] = 'application/json' - else: - data = content - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - - url = '/v3/profile' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - -class ProfileEnums: - """ - Enums for profile parameters. - """ - - class Accept(str, Enum): - """ - The type of the response. For more information, see **Accept types** in the method - description. - """ - APPLICATION_JSON = 'application/json' - TEXT_CSV = 'text/csv' - - class ContentType(str, Enum): - """ - The type of the input. For more information, see **Content types** in the method - description. - """ - APPLICATION_JSON = 'application/json' - TEXT_HTML = 'text/html' - TEXT_PLAIN = 'text/plain' - - class ContentLanguage(str, Enum): - """ - The language of the input text for the request: Arabic, English, Japanese, Korean, - or Spanish. Regional variants are treated as their parent language; for example, - `en-US` is interpreted as `en`. - The effect of the **Content-Language** parameter depends on the **Content-Type** - parameter. When **Content-Type** is `text/plain` or `text/html`, - **Content-Language** is the only way to specify the language. When - **Content-Type** is `application/json`, **Content-Language** overrides a language - specified with the `language` parameter of a `ContentItem` object, and content - items that specify a different language are ignored; omit this parameter to base - the language on the specification of the content items. You can specify any - combination of languages for **Content-Language** and **Accept-Language**. - """ - AR = 'ar' - EN = 'en' - ES = 'es' - JA = 'ja' - KO = 'ko' - - class AcceptLanguage(str, Enum): - """ - The desired language of the response. For two-character arguments, regional - variants are treated as their parent language; for example, `en-US` is interpreted - as `en`. You can specify any combination of languages for the input and response - content. - """ - AR = 'ar' - DE = 'de' - EN = 'en' - ES = 'es' - FR = 'fr' - IT = 'it' - JA = 'ja' - KO = 'ko' - PT_BR = 'pt-br' - ZH_CN = 'zh-cn' - ZH_TW = 'zh-tw' - - -############################################################################## -# Models -############################################################################## - - -class Behavior(): - """ - The temporal behavior for the input content. - - :attr str trait_id: The unique, non-localized identifier of the characteristic - to which the results pertain. IDs have the form `behavior_{value}`. - :attr str name: The user-visible, localized name of the characteristic. - :attr str category: The category of the characteristic: `behavior` for temporal - data. - :attr float percentage: For JSON content that is timestamped, the percentage of - timestamped input data that occurred during that day of the week or hour of the - day. The range is 0 to 1. - """ - - def __init__(self, trait_id: str, name: str, category: str, - percentage: float) -> None: - """ - Initialize a Behavior object. - - :param str trait_id: The unique, non-localized identifier of the - characteristic to which the results pertain. IDs have the form - `behavior_{value}`. - :param str name: The user-visible, localized name of the characteristic. - :param str category: The category of the characteristic: `behavior` for - temporal data. - :param float percentage: For JSON content that is timestamped, the - percentage of timestamped input data that occurred during that day of the - week or hour of the day. The range is 0 to 1. - """ - self.trait_id = trait_id - self.name = name - self.category = category - self.percentage = percentage - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Behavior': - """Initialize a Behavior object from a json dictionary.""" - args = {} - if 'trait_id' in _dict: - args['trait_id'] = _dict.get('trait_id') - else: - raise ValueError( - 'Required property \'trait_id\' not present in Behavior JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in Behavior JSON') - if 'category' in _dict: - args['category'] = _dict.get('category') - else: - raise ValueError( - 'Required property \'category\' not present in Behavior JSON') - if 'percentage' in _dict: - args['percentage'] = _dict.get('percentage') - else: - raise ValueError( - 'Required property \'percentage\' not present in Behavior JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Behavior 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, 'trait_id') and self.trait_id is not None: - _dict['trait_id'] = self.trait_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'category') and self.category is not None: - _dict['category'] = self.category - if hasattr(self, 'percentage') and self.percentage is not None: - _dict['percentage'] = self.percentage - 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 Behavior object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Behavior') -> 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: 'Behavior') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ConsumptionPreferences(): - """ - A consumption preference that the service inferred from the input content. - - :attr str consumption_preference_id: The unique, non-localized identifier of the - consumption preference to which the results pertain. IDs have the form - `consumption_preferences_{preference}`. - :attr str name: The user-visible, localized name of the consumption preference. - :attr float score: The score for the consumption preference: - * `0.0`: Unlikely - * `0.5`: Neutral - * `1.0`: Likely - The scores for some preferences are binary and do not allow a neutral value. The - score is an indication of preference based on the results inferred from the - input text, not a normalized percentile. - """ - - def __init__(self, consumption_preference_id: str, name: str, - score: float) -> None: - """ - Initialize a ConsumptionPreferences object. - - :param str consumption_preference_id: The unique, non-localized identifier - of the consumption preference to which the results pertain. IDs have the - form `consumption_preferences_{preference}`. - :param str name: The user-visible, localized name of the consumption - preference. - :param float score: The score for the consumption preference: - * `0.0`: Unlikely - * `0.5`: Neutral - * `1.0`: Likely - The scores for some preferences are binary and do not allow a neutral - value. The score is an indication of preference based on the results - inferred from the input text, not a normalized percentile. - """ - self.consumption_preference_id = consumption_preference_id - self.name = name - self.score = score - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ConsumptionPreferences': - """Initialize a ConsumptionPreferences object from a json dictionary.""" - args = {} - if 'consumption_preference_id' in _dict: - args['consumption_preference_id'] = _dict.get( - 'consumption_preference_id') - else: - raise ValueError( - 'Required property \'consumption_preference_id\' not present in ConsumptionPreferences JSON' - ) - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in ConsumptionPreferences JSON' - ) - if 'score' in _dict: - args['score'] = _dict.get('score') - else: - raise ValueError( - 'Required property \'score\' not present in ConsumptionPreferences JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ConsumptionPreferences 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, 'consumption_preference_id' - ) and self.consumption_preference_id is not None: - _dict['consumption_preference_id'] = self.consumption_preference_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score - 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 ConsumptionPreferences object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ConsumptionPreferences') -> 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: 'ConsumptionPreferences') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ConsumptionPreferencesCategory(): - """ - The consumption preferences that the service inferred from the input content. - - :attr str consumption_preference_category_id: The unique, non-localized - identifier of the consumption preferences category to which the results pertain. - IDs have the form `consumption_preferences_{category}`. - :attr str name: The user-visible name of the consumption preferences category. - :attr List[ConsumptionPreferences] consumption_preferences: Detailed results - inferred from the input text for the individual preferences of the category. - """ - - def __init__( - self, consumption_preference_category_id: str, name: str, - consumption_preferences: List['ConsumptionPreferences']) -> None: - """ - Initialize a ConsumptionPreferencesCategory object. - - :param str consumption_preference_category_id: The unique, non-localized - identifier of the consumption preferences category to which the results - pertain. IDs have the form `consumption_preferences_{category}`. - :param str name: The user-visible name of the consumption preferences - category. - :param List[ConsumptionPreferences] consumption_preferences: Detailed - results inferred from the input text for the individual preferences of the - category. - """ - self.consumption_preference_category_id = consumption_preference_category_id - self.name = name - self.consumption_preferences = consumption_preferences - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ConsumptionPreferencesCategory': - """Initialize a ConsumptionPreferencesCategory object from a json dictionary.""" - args = {} - if 'consumption_preference_category_id' in _dict: - args['consumption_preference_category_id'] = _dict.get( - 'consumption_preference_category_id') - else: - raise ValueError( - 'Required property \'consumption_preference_category_id\' not present in ConsumptionPreferencesCategory JSON' - ) - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in ConsumptionPreferencesCategory JSON' - ) - if 'consumption_preferences' in _dict: - args['consumption_preferences'] = [ - ConsumptionPreferences.from_dict(x) - for x in _dict.get('consumption_preferences') - ] - else: - raise ValueError( - 'Required property \'consumption_preferences\' not present in ConsumptionPreferencesCategory JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ConsumptionPreferencesCategory 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, 'consumption_preference_category_id' - ) and self.consumption_preference_category_id is not None: - _dict[ - 'consumption_preference_category_id'] = self.consumption_preference_category_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'consumption_preferences' - ) and self.consumption_preferences is not None: - _dict['consumption_preferences'] = [ - x.to_dict() for x in self.consumption_preferences - ] - 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 ConsumptionPreferencesCategory object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ConsumptionPreferencesCategory') -> 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: 'ConsumptionPreferencesCategory') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Content(): - """ - The full input content that the service is to analyze. - - :attr List[ContentItem] content_items: An array of `ContentItem` objects that - provides the text that is to be analyzed. - """ - - def __init__(self, content_items: List['ContentItem']) -> None: - """ - Initialize a Content object. - - :param List[ContentItem] content_items: An array of `ContentItem` objects - that provides the text that is to be analyzed. - """ - self.content_items = content_items - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Content': - """Initialize a Content object from a json dictionary.""" - args = {} - if 'contentItems' in _dict: - args['content_items'] = [ - ContentItem.from_dict(x) for x in _dict.get('contentItems') - ] - else: - raise ValueError( - 'Required property \'contentItems\' not present in Content JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Content 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, 'content_items') and self.content_items is not None: - _dict['contentItems'] = [x.to_dict() for x in self.content_items] - 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 Content object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Content') -> 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: 'Content') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ContentItem(): - """ - An input content item that the service is to analyze. - - :attr str content: The content that is to be analyzed. The service supports up - to 20 MB of content for all `ContentItem` objects combined. - :attr str id: (optional) A unique identifier for this content item. - :attr int created: (optional) A timestamp that identifies when this content was - created. Specify a value in milliseconds since the UNIX Epoch (January 1, 1970, - at 0:00 UTC). Required only for results that include temporal behavior data. - :attr int updated: (optional) A timestamp that identifies when this content was - last updated. Specify a value in milliseconds since the UNIX Epoch (January 1, - 1970, at 0:00 UTC). Required only for results that include temporal behavior - data. - :attr str contenttype: (optional) The MIME type of the content. The default is - plain text. The tags are stripped from HTML content before it is analyzed; plain - text is processed as submitted. - :attr str language: (optional) The language identifier (two-letter ISO 639-1 - identifier) for the language of the content item. The default is `en` (English). - Regional variants are treated as their parent language; for example, `en-US` is - interpreted as `en`. A language specified with the **Content-Type** parameter - overrides the value of this parameter; any content items that specify a - different language are ignored. Omit the **Content-Type** parameter to base the - language on the most prevalent specification among the content items; again, - content items that specify a different language are ignored. You can specify any - combination of languages for the input and response content. - :attr str parentid: (optional) The unique ID of the parent content item for this - item. Used to identify hierarchical relationships between posts/replies, - messages/replies, and so on. - :attr bool reply: (optional) Indicates whether this content item is a reply to - another content item. - :attr bool forward: (optional) Indicates whether this content item is a - forwarded/copied version of another content item. - """ - - def __init__(self, - content: str, - *, - id: str = None, - created: int = None, - updated: int = None, - contenttype: str = None, - language: str = None, - parentid: str = None, - reply: bool = None, - forward: bool = None) -> None: - """ - Initialize a ContentItem object. - - :param str content: The content that is to be analyzed. The service - supports up to 20 MB of content for all `ContentItem` objects combined. - :param str id: (optional) A unique identifier for this content item. - :param int created: (optional) A timestamp that identifies when this - content was created. Specify a value in milliseconds since the UNIX Epoch - (January 1, 1970, at 0:00 UTC). Required only for results that include - temporal behavior data. - :param int updated: (optional) A timestamp that identifies when this - content was last updated. Specify a value in milliseconds since the UNIX - Epoch (January 1, 1970, at 0:00 UTC). Required only for results that - include temporal behavior data. - :param str contenttype: (optional) The MIME type of the content. The - default is plain text. The tags are stripped from HTML content before it is - analyzed; plain text is processed as submitted. - :param str language: (optional) The language identifier (two-letter ISO - 639-1 identifier) for the language of the content item. The default is `en` - (English). Regional variants are treated as their parent language; for - example, `en-US` is interpreted as `en`. A language specified with the - **Content-Type** parameter overrides the value of this parameter; any - content items that specify a different language are ignored. Omit the - **Content-Type** parameter to base the language on the most prevalent - specification among the content items; again, content items that specify a - different language are ignored. You can specify any combination of - languages for the input and response content. - :param str parentid: (optional) The unique ID of the parent content item - for this item. Used to identify hierarchical relationships between - posts/replies, messages/replies, and so on. - :param bool reply: (optional) Indicates whether this content item is a - reply to another content item. - :param bool forward: (optional) Indicates whether this content item is a - forwarded/copied version of another content item. - """ - self.content = content - self.id = id - self.created = created - self.updated = updated - self.contenttype = contenttype - self.language = language - self.parentid = parentid - self.reply = reply - self.forward = forward - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ContentItem': - """Initialize a ContentItem object from a json dictionary.""" - args = {} - if 'content' in _dict: - args['content'] = _dict.get('content') - else: - raise ValueError( - 'Required property \'content\' not present in ContentItem JSON') - if 'id' in _dict: - args['id'] = _dict.get('id') - if 'created' in _dict: - args['created'] = _dict.get('created') - if 'updated' in _dict: - args['updated'] = _dict.get('updated') - if 'contenttype' in _dict: - args['contenttype'] = _dict.get('contenttype') - if 'language' in _dict: - args['language'] = _dict.get('language') - if 'parentid' in _dict: - args['parentid'] = _dict.get('parentid') - if 'reply' in _dict: - args['reply'] = _dict.get('reply') - if 'forward' in _dict: - args['forward'] = _dict.get('forward') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ContentItem 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, 'content') and self.content is not None: - _dict['content'] = self.content - if hasattr(self, 'id') and self.id is not None: - _dict['id'] = self.id - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = self.created - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = self.updated - if hasattr(self, 'contenttype') and self.contenttype is not None: - _dict['contenttype'] = self.contenttype - if hasattr(self, 'language') and self.language is not None: - _dict['language'] = self.language - if hasattr(self, 'parentid') and self.parentid is not None: - _dict['parentid'] = self.parentid - if hasattr(self, 'reply') and self.reply is not None: - _dict['reply'] = self.reply - if hasattr(self, 'forward') and self.forward is not None: - _dict['forward'] = self.forward - 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 ContentItem object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ContentItem') -> 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: 'ContentItem') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ContenttypeEnum(str, Enum): - """ - The MIME type of the content. The default is plain text. The tags are stripped - from HTML content before it is analyzed; plain text is processed as submitted. - """ - TEXT_PLAIN = 'text/plain' - TEXT_HTML = 'text/html' - - class LanguageEnum(str, Enum): - """ - The language identifier (two-letter ISO 639-1 identifier) for the language of the - content item. The default is `en` (English). Regional variants are treated as - their parent language; for example, `en-US` is interpreted as `en`. A language - specified with the **Content-Type** parameter overrides the value of this - parameter; any content items that specify a different language are ignored. Omit - the **Content-Type** parameter to base the language on the most prevalent - specification among the content items; again, content items that specify a - different language are ignored. You can specify any combination of languages for - the input and response content. - """ - AR = 'ar' - EN = 'en' - ES = 'es' - JA = 'ja' - KO = 'ko' - - -class Profile(): - """ - The personality profile that the service generated for the input content. - - :attr str processed_language: The language model that was used to process the - input. - :attr int word_count: The number of words from the input that were used to - produce the profile. - :attr str word_count_message: (optional) When guidance is appropriate, a string - that provides a message that indicates the number of words found and where that - value falls in the range of required or suggested number of words. - :attr List[Trait] personality: A recursive array of `Trait` objects that - provides detailed results for the Big Five personality characteristics - (dimensions and facets) inferred from the input text. - :attr List[Trait] needs: Detailed results for the Needs characteristics inferred - from the input text. - :attr List[Trait] values: Detailed results for the Values characteristics - inferred from the input text. - :attr List[Behavior] behavior: (optional) For JSON content that is timestamped, - detailed results about the social behavior disclosed by the input in terms of - temporal characteristics. The results include information about the distribution - of the content over the days of the week and the hours of the day. - :attr List[ConsumptionPreferencesCategory] consumption_preferences: (optional) - If the **consumption_preferences** parameter is `true`, detailed results for - each category of consumption preferences. Each element of the array provides - information inferred from the input text for the individual preferences of that - category. - :attr List[Warning] warnings: An array of warning messages that are associated - with the input text for the request. The array is empty if the input generated - no warnings. - """ - - def __init__( - self, - processed_language: str, - word_count: int, - personality: List['Trait'], - needs: List['Trait'], - values: List['Trait'], - warnings: List['Warning'], - *, - word_count_message: str = None, - behavior: List['Behavior'] = None, - consumption_preferences: List['ConsumptionPreferencesCategory'] = None - ) -> None: - """ - Initialize a Profile object. - - :param str processed_language: The language model that was used to process - the input. - :param int word_count: The number of words from the input that were used to - produce the profile. - :param List[Trait] personality: A recursive array of `Trait` objects that - provides detailed results for the Big Five personality characteristics - (dimensions and facets) inferred from the input text. - :param List[Trait] needs: Detailed results for the Needs characteristics - inferred from the input text. - :param List[Trait] values: Detailed results for the Values characteristics - inferred from the input text. - :param List[Warning] warnings: An array of warning messages that are - associated with the input text for the request. The array is empty if the - input generated no warnings. - :param str word_count_message: (optional) When guidance is appropriate, a - string that provides a message that indicates the number of words found and - where that value falls in the range of required or suggested number of - words. - :param List[Behavior] behavior: (optional) For JSON content that is - timestamped, detailed results about the social behavior disclosed by the - input in terms of temporal characteristics. The results include information - about the distribution of the content over the days of the week and the - hours of the day. - :param List[ConsumptionPreferencesCategory] consumption_preferences: - (optional) If the **consumption_preferences** parameter is `true`, detailed - results for each category of consumption preferences. Each element of the - array provides information inferred from the input text for the individual - preferences of that category. - """ - self.processed_language = processed_language - self.word_count = word_count - self.word_count_message = word_count_message - self.personality = personality - self.needs = needs - self.values = values - self.behavior = behavior - self.consumption_preferences = consumption_preferences - self.warnings = warnings - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Profile': - """Initialize a Profile object from a json dictionary.""" - args = {} - if 'processed_language' in _dict: - args['processed_language'] = _dict.get('processed_language') - else: - raise ValueError( - 'Required property \'processed_language\' not present in Profile JSON' - ) - if 'word_count' in _dict: - args['word_count'] = _dict.get('word_count') - else: - raise ValueError( - 'Required property \'word_count\' not present in Profile JSON') - if 'word_count_message' in _dict: - args['word_count_message'] = _dict.get('word_count_message') - if 'personality' in _dict: - args['personality'] = [ - Trait.from_dict(x) for x in _dict.get('personality') - ] - else: - raise ValueError( - 'Required property \'personality\' not present in Profile JSON') - if 'needs' in _dict: - args['needs'] = [Trait.from_dict(x) for x in _dict.get('needs')] - else: - raise ValueError( - 'Required property \'needs\' not present in Profile JSON') - if 'values' in _dict: - args['values'] = [Trait.from_dict(x) for x in _dict.get('values')] - else: - raise ValueError( - 'Required property \'values\' not present in Profile JSON') - if 'behavior' in _dict: - args['behavior'] = [ - Behavior.from_dict(x) for x in _dict.get('behavior') - ] - if 'consumption_preferences' in _dict: - args['consumption_preferences'] = [ - ConsumptionPreferencesCategory.from_dict(x) - for x in _dict.get('consumption_preferences') - ] - if 'warnings' in _dict: - args['warnings'] = [ - Warning.from_dict(x) for x in _dict.get('warnings') - ] - else: - raise ValueError( - 'Required property \'warnings\' not present in Profile JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Profile 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, - 'processed_language') and self.processed_language is not None: - _dict['processed_language'] = self.processed_language - if hasattr(self, 'word_count') and self.word_count is not None: - _dict['word_count'] = self.word_count - if hasattr( - self, - 'word_count_message') and self.word_count_message is not None: - _dict['word_count_message'] = self.word_count_message - if hasattr(self, 'personality') and self.personality is not None: - _dict['personality'] = [x.to_dict() for x in self.personality] - if hasattr(self, 'needs') and self.needs is not None: - _dict['needs'] = [x.to_dict() for x in self.needs] - if hasattr(self, 'values') and self.values is not None: - _dict['values'] = [x.to_dict() for x in self.values] - if hasattr(self, 'behavior') and self.behavior is not None: - _dict['behavior'] = [x.to_dict() for x in self.behavior] - if hasattr(self, 'consumption_preferences' - ) and self.consumption_preferences is not None: - _dict['consumption_preferences'] = [ - x.to_dict() for x in self.consumption_preferences - ] - if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x.to_dict() for x in self.warnings] - 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 Profile object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Profile') -> 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: 'Profile') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ProcessedLanguageEnum(str, Enum): - """ - The language model that was used to process the input. - """ - AR = 'ar' - EN = 'en' - ES = 'es' - JA = 'ja' - KO = 'ko' - - -class Trait(): - """ - The characteristics that the service inferred from the input content. - - :attr str trait_id: The unique, non-localized identifier of the characteristic - to which the results pertain. IDs have the form - * `big5_{characteristic}` for Big Five personality dimensions - * `facet_{characteristic}` for Big Five personality facets - * `need_{characteristic}` for Needs - *`value_{characteristic}` for Values. - :attr str name: The user-visible, localized name of the characteristic. - :attr str category: The category of the characteristic: `personality` for Big - Five personality characteristics, `needs` for Needs, and `values` for Values. - :attr float percentile: The normalized percentile score for the characteristic. - The range is 0 to 1. For example, if the percentage for Openness is 0.60, the - author scored in the 60th percentile; the author is more open than 59 percent of - the population and less open than 39 percent of the population. - :attr float raw_score: (optional) The raw score for the characteristic. The - range is 0 to 1. A higher score generally indicates a greater likelihood that - the author has that characteristic, but raw scores must be considered in - aggregate: The range of values in practice might be much smaller than 0 to 1, so - an individual score must be considered in the context of the overall scores and - their range. - The raw score is computed based on the input and the service model; it is not - normalized or compared with a sample population. The raw score enables - comparison of the results against a different sampling population and with a - custom normalization approach. - :attr bool significant: (optional) **`2017-10-13`**: Indicates whether the - characteristic is meaningful for the input language. The field is always `true` - for all characteristics of English, Spanish, and Japanese input. The field is - `false` for the subset of characteristics of Arabic and Korean input for which - the service's models are unable to generate meaningful results. - **`2016-10-19`**: Not returned. - :attr List[Trait] children: (optional) For `personality` (Big Five) dimensions, - more detailed results for the facets of each dimension as inferred from the - input text. - """ - - def __init__(self, - trait_id: str, - name: str, - category: str, - percentile: float, - *, - raw_score: float = None, - significant: bool = None, - children: List['Trait'] = None) -> None: - """ - Initialize a Trait object. - - :param str trait_id: The unique, non-localized identifier of the - characteristic to which the results pertain. IDs have the form - * `big5_{characteristic}` for Big Five personality dimensions - * `facet_{characteristic}` for Big Five personality facets - * `need_{characteristic}` for Needs - *`value_{characteristic}` for Values. - :param str name: The user-visible, localized name of the characteristic. - :param str category: The category of the characteristic: `personality` for - Big Five personality characteristics, `needs` for Needs, and `values` for - Values. - :param float percentile: The normalized percentile score for the - characteristic. The range is 0 to 1. For example, if the percentage for - Openness is 0.60, the author scored in the 60th percentile; the author is - more open than 59 percent of the population and less open than 39 percent - of the population. - :param float raw_score: (optional) The raw score for the characteristic. - The range is 0 to 1. A higher score generally indicates a greater - likelihood that the author has that characteristic, but raw scores must be - considered in aggregate: The range of values in practice might be much - smaller than 0 to 1, so an individual score must be considered in the - context of the overall scores and their range. - The raw score is computed based on the input and the service model; it is - not normalized or compared with a sample population. The raw score enables - comparison of the results against a different sampling population and with - a custom normalization approach. - :param bool significant: (optional) **`2017-10-13`**: Indicates whether the - characteristic is meaningful for the input language. The field is always - `true` for all characteristics of English, Spanish, and Japanese input. The - field is `false` for the subset of characteristics of Arabic and Korean - input for which the service's models are unable to generate meaningful - results. **`2016-10-19`**: Not returned. - :param List[Trait] children: (optional) For `personality` (Big Five) - dimensions, more detailed results for the facets of each dimension as - inferred from the input text. - """ - self.trait_id = trait_id - self.name = name - self.category = category - self.percentile = percentile - self.raw_score = raw_score - self.significant = significant - self.children = children - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Trait': - """Initialize a Trait object from a json dictionary.""" - args = {} - if 'trait_id' in _dict: - args['trait_id'] = _dict.get('trait_id') - else: - raise ValueError( - 'Required property \'trait_id\' not present in Trait JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in Trait JSON') - if 'category' in _dict: - args['category'] = _dict.get('category') - else: - raise ValueError( - 'Required property \'category\' not present in Trait JSON') - if 'percentile' in _dict: - args['percentile'] = _dict.get('percentile') - else: - raise ValueError( - 'Required property \'percentile\' not present in Trait JSON') - if 'raw_score' in _dict: - args['raw_score'] = _dict.get('raw_score') - if 'significant' in _dict: - args['significant'] = _dict.get('significant') - if 'children' in _dict: - args['children'] = [ - Trait.from_dict(x) for x in _dict.get('children') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Trait 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, 'trait_id') and self.trait_id is not None: - _dict['trait_id'] = self.trait_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'category') and self.category is not None: - _dict['category'] = self.category - if hasattr(self, 'percentile') and self.percentile is not None: - _dict['percentile'] = self.percentile - if hasattr(self, 'raw_score') and self.raw_score is not None: - _dict['raw_score'] = self.raw_score - if hasattr(self, 'significant') and self.significant is not None: - _dict['significant'] = self.significant - if hasattr(self, 'children') and self.children is not None: - _dict['children'] = [x.to_dict() for x in self.children] - 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 Trait object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Trait') -> 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: 'Trait') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class CategoryEnum(str, Enum): - """ - The category of the characteristic: `personality` for Big Five personality - characteristics, `needs` for Needs, and `values` for Values. - """ - PERSONALITY = 'personality' - NEEDS = 'needs' - VALUES = 'values' - - -class Warning(): - """ - A warning message that is associated with the input content. - - :attr str warning_id: The identifier of the warning message. - :attr str message: The message associated with the `warning_id`: - * `WORD_COUNT_MESSAGE`: "There were {number} words in the input. We need a - minimum of 600, preferably 1,200 or more, to compute statistically significant - estimates." - * `JSON_AS_TEXT`: "Request input was processed as text/plain as indicated, - however detected a JSON input. Did you mean application/json?" - * `CONTENT_TRUNCATED`: "For maximum accuracy while also optimizing processing - time, only the first 250KB of input text (excluding markup) was analyzed. - Accuracy levels off at approximately 3,000 words so this did not affect the - accuracy of the profile." - * `PARTIAL_TEXT_USED`, "The text provided to compute the profile was trimmed for - performance reasons. This action does not affect the accuracy of the output, as - not all of the input text was required." Applies only when Arabic input text - exceeds a threshold at which additional words do not contribute to the accuracy - of the profile. - """ - - def __init__(self, warning_id: str, message: str) -> None: - """ - Initialize a Warning object. - - :param str warning_id: The identifier of the warning message. - :param str message: The message associated with the `warning_id`: - * `WORD_COUNT_MESSAGE`: "There were {number} words in the input. We need a - minimum of 600, preferably 1,200 or more, to compute statistically - significant estimates." - * `JSON_AS_TEXT`: "Request input was processed as text/plain as indicated, - however detected a JSON input. Did you mean application/json?" - * `CONTENT_TRUNCATED`: "For maximum accuracy while also optimizing - processing time, only the first 250KB of input text (excluding markup) was - analyzed. Accuracy levels off at approximately 3,000 words so this did not - affect the accuracy of the profile." - * `PARTIAL_TEXT_USED`, "The text provided to compute the profile was - trimmed for performance reasons. This action does not affect the accuracy - of the output, as not all of the input text was required." Applies only - when Arabic input text exceeds a threshold at which additional words do not - contribute to the accuracy of the profile. - """ - self.warning_id = warning_id - self.message = message - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Warning': - """Initialize a Warning object from a json dictionary.""" - args = {} - if 'warning_id' in _dict: - args['warning_id'] = _dict.get('warning_id') - else: - raise ValueError( - 'Required property \'warning_id\' not present in Warning JSON') - if 'message' in _dict: - args['message'] = _dict.get('message') - else: - raise ValueError( - 'Required property \'message\' not present in Warning JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Warning 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, 'warning_id') and self.warning_id is not None: - _dict['warning_id'] = self.warning_id - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message - 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 Warning object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Warning') -> 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: 'Warning') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class WarningIdEnum(str, Enum): - """ - The identifier of the warning message. - """ - WORD_COUNT_MESSAGE = 'WORD_COUNT_MESSAGE' - JSON_AS_TEXT = 'JSON_AS_TEXT' - CONTENT_TRUNCATED = 'CONTENT_TRUNCATED' - PARTIAL_TEXT_USED = 'PARTIAL_TEXT_USED' diff --git a/ibm_watson/speech_to_text_v1.py b/ibm_watson/speech_to_text_v1.py index f768b59b7..c769fb495 100644 --- a/ibm_watson/speech_to_text_v1.py +++ b/ibm_watson/speech_to_text_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2021. +# (C) Copyright IBM Corp. 2015, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,10 +14,10 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 +# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 """ The IBM Watson™ Speech to Text service provides APIs that use IBM's -speech-recognition capabilities to produce transcripts of spoken audio. The service can +speech-recognition capabilities to produce transcripts of spoken audio. The service can transcribe speech from various languages and audio formats. In addition to basic transcription, the service can produce detailed information about many different aspects of the audio. It returns all JSON response content in the UTF-8 character set. @@ -27,6 +27,13 @@ have minimum sampling rates of 16 kHz. Narrowband and telephony models have minimum sampling rates of 8 kHz. The next-generation models offer high throughput and greater transcription accuracy. +Effective 15 March 2022, previous-generation models for all languages other than Arabic +and Japanese are deprecated. The deprecated models remain available until 15 September +2022, when they will be removed from the service and the documentation. You must migrate +to the equivalent next-generation model by the end of service date. For more information, +see [Migrating to next-generation +models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate).{: +deprecated} For speech recognition, the service supports synchronous and asynchronous HTTP Representational State Transfer (REST) interfaces. It also supports a WebSocket interface that provides a full-duplex, low-latency communication channel: Clients send requests and @@ -36,17 +43,16 @@ customization to adapt a base model for the acoustic characteristics of your audio. For language model customization, the service also supports grammars. A grammar is a formal language specification that lets you restrict the phrases that the service can recognize. -Language model customization is available for most previous- and next-generation models. -Acoustic model customization is available for all previous-generation models. Grammars are -beta functionality that is available for all previous-generation models that support -language model customization. +Language model customization and grammars are available for most previous- and +next-generation models. Acoustic model customization is available for all +previous-generation models. API Version: 1.0.0 See: https://cloud.ibm.com/docs/speech-to-text """ from enum import Enum -from typing import BinaryIO, Dict, List, TextIO, Union +from typing import BinaryIO, Dict, List import json from ibm_cloud_sdk_core import BaseService, DetailedResponse @@ -76,7 +82,7 @@ def __init__( Construct a new client for the Speech to Text service. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md about initializing the authenticator of your choice. """ if not authenticator: @@ -98,8 +104,8 @@ def list_models(self, **kwargs) -> DetailedResponse: information includes the name of the model and its minimum sampling rate in Hertz, among other things. The ordering of the list of models can change from call to call; do not rely on an alphabetized or static list of models. - **See also:** [Listing - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list). + **See also:** [Listing all + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list#models-list-all). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. @@ -129,8 +135,8 @@ def get_model(self, model_id: str, **kwargs) -> DetailedResponse: Gets information for a single specified language model that is available for use with the service. The information includes the name of the model and its minimum sampling rate in Hertz, among other things. - **See also:** [Listing - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list). + **See also:** [Listing a specific + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-list#models-list-specific). :param str model_id: The identifier of the model in the form of its name from the output of the [List models](#listmodels) method. (**Note:** The @@ -263,15 +269,23 @@ def recognize(self, You specify a next-generation model by using the `model` query parameter, as you do a previous-generation model. Many next-generation models also support the `low_latency` parameter, which is not available with previous-generation models. - But next-generation models do not support all of the parameters that are available - for use with previous-generation models. For more information about all parameters - that are supported for use with next-generation models, see [Supported features - for next-generation - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-features). - **See also:** [Next-generation languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). + Next-generation models do not support all of the parameters that are available for + use with previous-generation models. + **Important:** Effective 15 March 2022, previous-generation models for all + languages other than Arabic and Japanese are deprecated. The deprecated models + remain available until 15 September 2022, when they will be removed from the + service and the documentation. You must migrate to the equivalent next-generation + model by the end of service date. For more information, see [Migrating to + next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). + **See also:** + * [Next-generation languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng) + * [Supported features for next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-features) ### Multipart speech recognition - **Note:** The Watson SDKs do not support multipart speech recognition. + **Note:** The asynchronous HTTP interface, WebSocket interface, and Watson SDKs + do not support multipart speech recognition. The HTTP `POST` method of the service also supports multipart speech recognition. With multipart requests, you pass all audio data as multipart form data. You specify some parameters as request headers and query parameters, but you pass JSON @@ -290,11 +304,9 @@ 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. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) See [Previous-generation - languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) - and [Next-generation languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). + deprecated; use `ar-MS_BroadbandModel` instead.) See [Using a model for + speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). :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 @@ -384,8 +396,9 @@ def recognize(self, :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 and - Japanese transcription only. See [Profanity + `false` to return results with no censoring. + **Note:** The parameter can be used with US English and Japanese + transcription only. See [Profanity filtering](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#profanity-filtering). :param bool smart_formatting: (optional) If `true`, the service converts dates, times, series of digits and numbers, phone numbers, currency values, @@ -393,8 +406,8 @@ def recognize(self, the final transcript of a recognition request. For US English, the service also converts certain keyword strings to punctuation symbols. By default, the service performs no smart formatting. - **Beta:** The parameter is beta functionality. Applies to US English, - Japanese, and Spanish transcription only. + **Note:** The parameter can be used with US English, Japanese, and Spanish + (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). :param bool speaker_labels: (optional) If `true`, the response includes @@ -402,16 +415,14 @@ def recognize(self, multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - **Beta:** The parameter is beta functionality. - * For previous-generation models, the parameter can be used for Australian - English, US English, German, Japanese, Korean, and Spanish (both broadband - and narrowband models) and UK English (narrowband model) transcription - only. - * For next-generation models, the parameter can be used for English - (Australian, Indian, UK, and US), German, Japanese, Korean, and Spanish + * _For previous-generation models,_ the parameter can be used with + Australian English, US English, German, Japanese, Korean, and Spanish (both + broadband and narrowband models) and UK English (narrowband model) transcription only. - Restrictions and limitations apply to the use of speaker labels for both - types of models. See [Speaker + * _For next-generation models,_ the parameter can be used with Czech, + English (Australian, Indian, UK, and US), German, Japanese, Korean, and + Spanish transcription only. + See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). :param str customization_id: (optional) **Deprecated.** Use the `language_customization_id` parameter to specify the customization ID @@ -423,7 +434,6 @@ 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. - **Beta:** The parameter is beta functionality. See [Using a grammar for speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUse). :param bool redaction: (optional) If `true`, the service redacts, or masks, @@ -437,8 +447,8 @@ def recognize(self, (ignores the `keywords` and `keywords_threshold` parameters) and returns only a single final transcript (forces the `max_alternatives` parameter to be `1`). - **Beta:** The parameter is beta functionality. Applies to US English, - Japanese, and Korean transcription only. + **Note:** The parameter can be used with US English, Japanese, and Korean + transcription only. See [Numeric redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#numeric-redaction). :param bool audio_metrics: (optional) If `true`, requests detailed @@ -468,8 +478,11 @@ def recognize(self, meaningful phrases such as sentences. The service bases its understanding of semantic features on the base language model that you use with a request. Custom language models and grammars can also influence how and - where the service splits a transcript. By default, the service splits - transcripts based solely on the pause interval. + where the service splits a transcript. + By default, the service splits transcripts based solely on the pause + interval. If the parameters are used together on the same request, + `end_of_phrase_silence_time` has precedence over + `split_transcript_at_phrase_end`. See [Split transcript at phrase end](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#split-transcript). :param float speech_detector_sensitivity: (optional) The sensitivity of @@ -483,8 +496,12 @@ def recognize(self, * 0.5 (the default) provides a reasonable compromise for the level of sensitivity. * 1.0 suppresses no audio (speech detection sensitivity is disabled). - The values increase on a monotonic curve. See [Speech detector - sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity). + The values increase on a monotonic curve. + The parameter is supported with all next-generation models and with most + previous-generation models. See [Speech detector + sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) + and [Language model + support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). :param float background_audio_suppression: (optional) The level to which the service is to suppress background audio based on its volume to prevent it from being transcribed as speech. Use the parameter to suppress side @@ -494,8 +511,12 @@ def recognize(self, is disabled). * 0.5 provides a reasonable level of audio suppression for general usage. * 1.0 suppresses all audio (no audio is transcribed). - The values increase on a monotonic curve. See [Background audio - suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression). + The values increase on a monotonic curve. + The parameter is supported with all next-generation models and with most + previous-generation models. See [Background audio + suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression) + and [Language model + support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). :param bool low_latency: (optional) If `true` for next-generation `Multimedia` and `Telephony` models that support low latency, directs the service to produce results even more quickly than it usually does. @@ -816,13 +837,20 @@ def create_job(self, You specify a next-generation model by using the `model` query parameter, as you do a previous-generation model. Many next-generation models also support the `low_latency` parameter, which is not available with previous-generation models. - But next-generation models do not support all of the parameters that are available - for use with previous-generation models. For more information about all parameters - that are supported for use with next-generation models, see [Supported features - for next-generation + Next-generation models do not support all of the parameters that are available for + use with previous-generation models. + **Important:** Effective 15 March 2022, previous-generation models for all + languages other than Arabic and Japanese are deprecated. The deprecated models + remain available until 15 September 2022, when they will be removed from the + service and the documentation. You must migrate to the equivalent next-generation + model by the end of service date. For more information, see [Migrating to + next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). + **See also:** + * [Next-generation languages and + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng) + * [Supported features for next-generation models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng#models-ng-features). - **See also:** [Next-generation languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). :param BinaryIO audio: The audio to transcribe. :param str content_type: (optional) The format (MIME type) of the audio. @@ -830,11 +858,9 @@ 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. (**Note:** The model `ar-AR_BroadbandModel` is - deprecated; use `ar-MS_BroadbandModel` instead.) See [Previous-generation - languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) - and [Next-generation languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). + deprecated; use `ar-MS_BroadbandModel` instead.) See [Using a model for + speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). :param str callback_url: (optional) A URL to which callback notifications are to be sent. The URL must already be successfully allowlisted by using the [Register a callback](#registercallback) method. You can include the @@ -960,8 +986,9 @@ def create_job(self, :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 and - Japanese transcription only. See [Profanity + `false` to return results with no censoring. + **Note:** The parameter can be used with US English and Japanese + transcription only. See [Profanity filtering](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#profanity-filtering). :param bool smart_formatting: (optional) If `true`, the service converts dates, times, series of digits and numbers, phone numbers, currency values, @@ -969,8 +996,8 @@ def create_job(self, the final transcript of a recognition request. For US English, the service also converts certain keyword strings to punctuation symbols. By default, the service performs no smart formatting. - **Beta:** The parameter is beta functionality. Applies to US English, - Japanese, and Spanish transcription only. + **Note:** The parameter can be used with US English, Japanese, and Spanish + (all dialects) transcription only. See [Smart formatting](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#smart-formatting). :param bool speaker_labels: (optional) If `true`, the response includes @@ -978,16 +1005,14 @@ def create_job(self, multi-person exchange. By default, the service returns no speaker labels. Setting `speaker_labels` to `true` forces the `timestamps` parameter to be `true`, regardless of whether you specify `false` for the parameter. - **Beta:** The parameter is beta functionality. - * For previous-generation models, the parameter can be used for Australian - English, US English, German, Japanese, Korean, and Spanish (both broadband - and narrowband models) and UK English (narrowband model) transcription - only. - * For next-generation models, the parameter can be used for English - (Australian, Indian, UK, and US), German, Japanese, Korean, and Spanish + * _For previous-generation models,_ the parameter can be used with + Australian English, US English, German, Japanese, Korean, and Spanish (both + broadband and narrowband models) and UK English (narrowband model) transcription only. - Restrictions and limitations apply to the use of speaker labels for both - types of models. See [Speaker + * _For next-generation models,_ the parameter can be used with Czech, + English (Australian, Indian, UK, and US), German, Japanese, Korean, and + Spanish transcription only. + See [Speaker labels](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-speaker-labels). :param str customization_id: (optional) **Deprecated.** Use the `language_customization_id` parameter to specify the customization ID @@ -999,7 +1024,6 @@ 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. - **Beta:** The parameter is beta functionality. See [Using a grammar for speech recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarUse). :param bool redaction: (optional) If `true`, the service redacts, or masks, @@ -1013,8 +1037,8 @@ def create_job(self, (ignores the `keywords` and `keywords_threshold` parameters) and returns only a single final transcript (forces the `max_alternatives` parameter to be `1`). - **Beta:** The parameter is beta functionality. Applies to US English, - Japanese, and Korean transcription only. + **Note:** The parameter can be used with US English, Japanese, and Korean + transcription only. See [Numeric redaction](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-formatting#numeric-redaction). :param bool processing_metrics: (optional) If `true`, requests processing @@ -1066,8 +1090,11 @@ def create_job(self, meaningful phrases such as sentences. The service bases its understanding of semantic features on the base language model that you use with a request. Custom language models and grammars can also influence how and - where the service splits a transcript. By default, the service splits - transcripts based solely on the pause interval. + where the service splits a transcript. + By default, the service splits transcripts based solely on the pause + interval. If the parameters are used together on the same request, + `end_of_phrase_silence_time` has precedence over + `split_transcript_at_phrase_end`. See [Split transcript at phrase end](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-parsing#split-transcript). :param float speech_detector_sensitivity: (optional) The sensitivity of @@ -1081,8 +1108,12 @@ def create_job(self, * 0.5 (the default) provides a reasonable compromise for the level of sensitivity. * 1.0 suppresses no audio (speech detection sensitivity is disabled). - The values increase on a monotonic curve. See [Speech detector - sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity). + The values increase on a monotonic curve. + The parameter is supported with all next-generation models and with most + previous-generation models. See [Speech detector + sensitivity](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-sensitivity) + and [Language model + support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). :param float background_audio_suppression: (optional) The level to which the service is to suppress background audio based on its volume to prevent it from being transcribed as speech. Use the parameter to suppress side @@ -1092,8 +1123,12 @@ def create_job(self, is disabled). * 0.5 provides a reasonable level of audio suppression for general usage. * 1.0 suppresses all audio (no audio is transcribed). - The values increase on a monotonic curve. See [Background audio - suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression). + The values increase on a monotonic curve. + The parameter is supported with all next-generation models and with most + previous-generation models. See [Background audio + suppression](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-parameters-suppression) + and [Language model + support](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-detection#detection-support). :param bool low_latency: (optional) If `true` for next-generation `Multimedia` and `Telephony` models that support low latency, directs the service to produce results even more quickly than it usually does. @@ -1316,8 +1351,18 @@ def create_language_model(self, The service returns an error if you attempt to create more than 1024 models. You 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/speech-to-text?topic=speech-to-text-languageCreate#createModel-language). + **Important:** Effective 15 March 2022, previous-generation models for all + languages other than Arabic and Japanese are deprecated. The deprecated models + remain available until 15 September 2022, when they will be removed from the + service and the documentation. You must migrate to the equivalent next-generation + model by the end of service date. For more information, see [Migrating to + next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). + **See also:** + * [Create a custom language + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#createModel-language) + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :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 @@ -1331,24 +1376,23 @@ def create_language_model(self, use the [Get a model](#getmodel) 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/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :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, - `en-US` is used for the US English language models. All dialect values are - case-insensitive. - The parameter is meaningful only for Spanish language models, for which you - can always safely omit the parameter to have the service create the correct - mapping. For Spanish, the service creates a custom language model that is - suited for speech in one of the following dialects: + is to be used with the custom language model. _For all languages, it is + always safe to omit this field._ The service automatically uses the + language identifier from the name of the base model. For example, the + service automatically uses `en-US` for all US English models. + If you specify the `dialect` for a new custom model, follow these + guidelines. _For non-Spanish previous-generation models and for + next-generation models,_ you must specify a value that matches the + five-character language identifier from the name of the base model. _For + Spanish previous-generation models,_ you must specify one of the following + values: * `es-ES` for Castilian Spanish (`es-ES` models) * `es-LA` for Latin American Spanish (`es-AR`, `es-CL`, `es-CO`, and `es-PE` models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) - If you specify the `dialect` parameter for a non-Spanish language model, - its value must match the language of the base model. If you specify the - `dialect` for a Spanish language model, its value must match one of the - defined mappings (`es-ES`, `es-LA`, or `es-MX`). + All values that you pass for the `dialect` field are case-insensitive. :param str description: (optional) A description of the new custom language model. Use a localized description that matches the language of the custom model. @@ -1402,17 +1446,22 @@ def list_language_models(self, the specified language. Omit the parameter to see all custom language models for 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/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language). + **See also:** + * [Listing custom language + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language) + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :param str language: (optional) The identifier of the language for which - custom language or custom acoustic models are to be returned. Omit the - parameter to see all custom language or custom acoustic models that are - owned by the requesting credentials. (**Note:** The identifier `ar-AR` is - deprecated; use `ar-MS` instead.) + custom language or custom acoustic models are to be returned. Specify the + five-character language identifier; for example, specify `en-US` to see all + custom language or custom acoustic models that are based on US English + models. Omit the parameter to see all custom language or custom acoustic + models that are owned by the requesting credentials. (**Note:** The + identifier `ar-AR` is deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `LanguageModels` object @@ -1446,8 +1495,11 @@ 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/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language). + **See also:** + * [Listing custom language + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#listModels-language) + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :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 @@ -1488,8 +1540,11 @@ def delete_language_model(self, customization_id: str, another request, such as adding a corpus or grammar to the model, is currently 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/speech-to-text?topic=speech-to-text-manageLanguageModels#deleteModel-language). + **See also:** + * [Deleting a custom language + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#deleteModel-language) + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :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 @@ -1550,8 +1605,11 @@ def train_language_model(self, custom model is trained 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/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language). + **See also:** + * [Train the custom language + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-languageCreate#trainModel-language) + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support) ### Training failures Training can fail to start for the following reasons: * The service is currently handling another request for the custom model, such as @@ -1640,8 +1698,11 @@ def reset_language_model(self, customization_id: str, preserved, but the model's words resource is removed and must be re-created. You 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/speech-to-text?topic=speech-to-text-manageLanguageModels#resetModel-language). + **See also:** + * [Resetting a custom language + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageLanguageModels#resetModel-language) + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :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 @@ -1689,15 +1750,16 @@ def upgrade_language_model(self, customization_id: str, has begun successfully. You can monitor the status of the upgrade by using the [Get a custom language model](#getlanguagemodel) method to poll the model's status. The method returns a `LanguageModel` object that includes `status` and - `progress` fields. Use a loop to check the status every 10 seconds. While it is - being upgraded, the custom model has the status `upgrading`. When the upgrade is - complete, the model resumes the status that it had prior to upgrade. The service - cannot accept subsequent requests for the model until the upgrade completes. - **Note:** Upgrading is necessary only for custom language models that are based on - previous-generation models. Only a single version of a custom model that is based - on a next-generation model is ever available. - **See also:** [Upgrading a custom language - model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language). + `progress` fields. Use a loop to check the status every 10 seconds. + While it is being upgraded, the custom model has the status `upgrading`. When the + upgrade is complete, the model 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/speech-to-text?topic=speech-to-text-custom-upgrade#custom-upgrade-language) + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :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 @@ -2450,15 +2512,16 @@ def list_grammars(self, customization_id: str, """ List grammars. - Lists information about all grammars from a custom language model. The information - includes the total number of out-of-vocabulary (OOV) words, name, and status of - each grammar. You must use credentials for the instance of the service that owns a - model to list its grammars. Grammars are available for all languages and models - that support language customization. - **Note:** Grammars are supported only for use with previous-generation models. - They are not supported for next-generation models. - **See also:** [Listing grammars from a custom language - model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars). + Lists information about all grammars from a custom language model. For each + grammar, the information includes the name, status, and (for grammars that are + based on previous-generation models) the total number of out-of-vocabulary (OOV) + words. 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/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars) + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :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 @@ -2494,7 +2557,7 @@ def list_grammars(self, customization_id: str, def add_grammar(self, customization_id: str, grammar_name: str, - grammar_file: Union[str, TextIO], + grammar_file: BinaryIO, content_type: str, *, allow_overwrite: bool = None, @@ -2516,12 +2579,14 @@ def add_grammar(self, resources to the custom model or to train the model until the service's analysis of the grammar for the current request completes. Use the [Get a grammar](#getgrammar) method to check the status of the analysis. - The service populates the model's words resource with any word that is recognized - by the grammar that is not found in the model's base vocabulary. These are - referred to as out-of-vocabulary (OOV) words. You can use the [List custom - words](#listwords) method to examine the words resource and use other - words-related methods to eliminate typos and modify how words are pronounced as - needed. + _For grammars that are based on previous-generation models,_ the service populates + the model's words resource with any word that is recognized by the grammar that is + not found in the model's base vocabulary. These are referred to as + out-of-vocabulary (OOV) words. You can use the [List custom words](#listwords) + method to examine the words resource and use other words-related methods to + eliminate typos and modify how words are pronounced as needed. _For grammars that + are based on next-generation models,_ the service extracts no OOV words from the + grammars. To add a grammar that has the same name as an existing grammar, set the `allow_overwrite` parameter to `true`; otherwise, the request fails. Overwriting an existing grammar causes the service to process the grammar file and extract OOV @@ -2529,19 +2594,18 @@ def add_grammar(self, grammar from the model's words resource unless they were also added by another resource or they have been modified in some way with the [Add custom words](#addwords) or [Add a custom word](#addword) method. - The service limits the overall amount of data that you can add to a custom model - to a maximum of 10 million total words from all sources combined. Also, you can - add no more than 90 thousand OOV words to a model. This includes words that the - service extracts from corpora and grammars and words that you add directly. - Grammars are available for all languages and models that support language - customization. - **Note:** Grammars are supported only for use with previous-generation models. - They are not supported for next-generation models. + _For grammars that are based on previous-generation models,_ the service limits + the overall amount of data that you can add to a custom model to a maximum of 10 + million total words from all sources combined. Also, you can add no more than 90 + thousand OOV words to a model. This includes words that the service extracts from + corpora and grammars and words that you add directly. **See also:** * [Understanding 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/speech-to-text?topic=speech-to-text-grammarAdd#addGrammar). + model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-grammarAdd#addGrammar) + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :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 @@ -2562,10 +2626,10 @@ def add_grammar(self, custom words that are added or modified by the user. * Do not use the name `base_lm` or `default_lm`. Both names are reserved for future use by the service. - :param str grammar_file: A plain text file that contains the grammar in the - format specified by the `Content-Type` header. Encode the file in UTF-8 - (ASCII is a subset of UTF-8). Using any other encoding can lead to issues - when compiling the grammar or to unexpected results in decoding. The + :param BinaryIO grammar_file: A plain text file that contains the grammar + in the format specified by the `Content-Type` header. Encode the file in + UTF-8 (ASCII is a subset of UTF-8). Using any other encoding can lead to + issues when compiling the grammar or to unexpected results in decoding. The service ignores an encoding that is specified in the header of the grammar. With the `curl` command, use the `--data-binary` option to upload the file for the request. @@ -2625,15 +2689,16 @@ def get_grammar(self, customization_id: str, grammar_name: str, """ Get a grammar. - Gets information about a grammar from a custom language model. The information - includes the total number of out-of-vocabulary (OOV) words, name, and status of - the grammar. You must use credentials for the instance of the service that owns a - model to list its grammars. Grammars are available for all languages and models - that support language customization. - **Note:** Grammars are supported only for use with previous-generation models. - They are not supported for next-generation models. - **See also:** [Listing grammars from a custom language - model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars). + Gets information about a grammar from a custom language model. For each grammar, + the information includes the name, status, and (for grammars that are based on + previous-generation models) the total number of out-of-vocabulary (OOV) words. 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/speech-to-text?topic=speech-to-text-manageGrammars#listGrammars) + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :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 @@ -2676,19 +2741,20 @@ def delete_grammar(self, customization_id: str, grammar_name: str, """ Delete a grammar. - Deletes an existing grammar from a custom language model. The service removes any - out-of-vocabulary (OOV) words associated with the grammar from the custom model's - words resource unless they were also added by another resource or they were - modified in some way with the [Add custom words](#addwords) or [Add a custom - word](#addword) method. Removing a grammar does not affect the custom model until - you train the model with the [Train a custom language model](#trainlanguagemodel) - method. You must use credentials for the instance of the service that owns a model - to delete its grammar. Grammars are available for all languages and models that - support language customization. - **Note:** Grammars are supported only for use with previous-generation models. - They are not supported for next-generation models. - **See also:** [Deleting a grammar from a custom language - model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-manageGrammars#deleteGrammar). + Deletes an existing grammar from a custom language model. _For grammars that are + based on previous-generation models,_ the service removes any out-of-vocabulary + (OOV) words associated with the grammar from the custom model's words resource + unless they were also added by another resource or they were modified in some way + with the [Add custom words](#addwords) or [Add a custom word](#addword) method. + Removing a grammar does not affect the custom model until you train the model with + the [Train a custom language model](#trainlanguagemodel) 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/speech-to-text?topic=speech-to-text-manageGrammars#deleteGrammar) + * [Language support for + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :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 @@ -2751,6 +2817,13 @@ def create_acoustic_model(self, below the limit. **Note:** Acoustic model customization is supported only for use with previous-generation models. It is not supported for next-generation models. + **Important:** Effective 15 March 2022, previous-generation models for all + languages other than Arabic and Japanese are deprecated. The deprecated models + remain available until 15 September 2022, when they will be removed from the + service and the documentation. You must migrate to the equivalent next-generation + model by the end of service date. For more information, see [Migrating to + next-generation + models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-migrate). **See also:** [Create a custom acoustic model](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-acoustic#createModel-acoustic). @@ -2765,7 +2838,7 @@ def create_acoustic_model(self, `ar-AR_BroadbandModel` is deprecated; use `ar-MS_BroadbandModel` instead.) To determine whether a base model supports acoustic model customization, refer to [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :param str description: (optional) A description of the new custom acoustic model. Use a localized description that matches the language of the custom model. @@ -2824,13 +2897,15 @@ def list_acoustic_models(self, 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. Omit the - parameter to see all custom language or custom acoustic models that are - owned by the requesting credentials. (**Note:** The identifier `ar-AR` is - deprecated; use `ar-MS` instead.) + custom language or custom acoustic models are to be returned. Specify the + five-character language identifier; for example, specify `en-US` to see all + custom language or custom acoustic models that are based on US English + models. Omit the parameter to see all custom language or custom acoustic + models that are owned by the requesting credentials. (**Note:** The + identifier `ar-AR` is deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse with `dict` result representing a `AcousticModels` object @@ -3123,12 +3198,12 @@ def upgrade_acoustic_model(self, has begun successfully. You can monitor the status of the upgrade by using the [Get a custom acoustic model](#getacousticmodel) method to poll the model's status. The method returns an `AcousticModel` object that includes `status` and - `progress` fields. Use a loop to check the status once a minute. While it is being - upgraded, the custom model has the status `upgrading`. When the upgrade is - complete, the model resumes the status that it had prior to upgrade. The service - cannot upgrade a model while it is handling another request for the model. The - service cannot accept subsequent requests for the model until the existing upgrade - request completes. + `progress` fields. Use a loop to check the status once a minute. + While it is being upgraded, the custom model has the status `upgrading`. When the + upgrade is complete, the model resumes the status that it had prior to upgrade. + The service cannot upgrade a model while it is handling another request for the + model. The service cannot accept subsequent requests for the model until the + existing upgrade request completes. If the custom acoustic model was trained with a separately created custom language model, you must use the `custom_language_model_id` parameter to specify the GUID of that custom language model. The custom language model must be upgraded before @@ -3612,13 +3687,17 @@ class ModelId(str, Enum): AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' + CS_CZ_TELEPHONY = 'cs-CZ_Telephony' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' + DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' DE_DE_TELEPHONY = 'de-DE_Telephony' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' + EN_AU_MULTIMEDIA = 'en-AU_Multimedia' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_AU_TELEPHONY = 'en-AU_Telephony' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' + EN_GB_MULTIMEDIA = 'en-GB_Multimedia' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' EN_IN_TELEPHONY = 'en-IN_Telephony' @@ -3627,6 +3706,7 @@ class ModelId(str, Enum): EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' + EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' @@ -3635,7 +3715,9 @@ class ModelId(str, Enum): ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' + ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' + ES_LA_TELEPHONY = 'es-LA_Telephony' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' @@ -3661,11 +3743,13 @@ class ModelId(str, Enum): NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' + NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' + ZH_CN_TELEPHONY = 'zh-CN_Telephony' class RecognizeEnums: @@ -3699,22 +3783,24 @@ class Model(str, Enum): """ The identifier of the model that is to be used for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use - `ar-MS_BroadbandModel` instead.) See [Previous-generation languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) and - [Next-generation languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). + `ar-MS_BroadbandModel` instead.) See [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). """ AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' + CS_CZ_TELEPHONY = 'cs-CZ_Telephony' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' + DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' DE_DE_TELEPHONY = 'de-DE_Telephony' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' + EN_AU_MULTIMEDIA = 'en-AU_Multimedia' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_AU_TELEPHONY = 'en-AU_Telephony' EN_IN_TELEPHONY = 'en-IN_Telephony' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' + EN_GB_MULTIMEDIA = 'en-GB_Multimedia' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' @@ -3722,6 +3808,7 @@ class Model(str, Enum): EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' + EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' @@ -3730,7 +3817,9 @@ class Model(str, Enum): ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' + ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' + ES_LA_TELEPHONY = 'es-LA_Telephony' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' @@ -3756,11 +3845,13 @@ class Model(str, Enum): NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' + NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' + ZH_CN_TELEPHONY = 'zh-CN_Telephony' class CreateJobEnums: @@ -3794,22 +3885,24 @@ class Model(str, Enum): """ The identifier of the model that is to be used for the recognition request. (**Note:** The model `ar-AR_BroadbandModel` is deprecated; use - `ar-MS_BroadbandModel` instead.) See [Previous-generation languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models) and - [Next-generation languages and - models](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-ng). + `ar-MS_BroadbandModel` instead.) See [Using a model for speech + recognition](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-models-use). """ AR_AR_BROADBANDMODEL = 'ar-AR_BroadbandModel' AR_MS_BROADBANDMODEL = 'ar-MS_BroadbandModel' AR_MS_TELEPHONY = 'ar-MS_Telephony' + CS_CZ_TELEPHONY = 'cs-CZ_Telephony' DE_DE_BROADBANDMODEL = 'de-DE_BroadbandModel' + DE_DE_MULTIMEDIA = 'de-DE_Multimedia' DE_DE_NARROWBANDMODEL = 'de-DE_NarrowbandModel' DE_DE_TELEPHONY = 'de-DE_Telephony' EN_AU_BROADBANDMODEL = 'en-AU_BroadbandModel' + EN_AU_MULTIMEDIA = 'en-AU_Multimedia' EN_AU_NARROWBANDMODEL = 'en-AU_NarrowbandModel' EN_AU_TELEPHONY = 'en-AU_Telephony' EN_IN_TELEPHONY = 'en-IN_Telephony' EN_GB_BROADBANDMODEL = 'en-GB_BroadbandModel' + EN_GB_MULTIMEDIA = 'en-GB_Multimedia' EN_GB_NARROWBANDMODEL = 'en-GB_NarrowbandModel' EN_GB_TELEPHONY = 'en-GB_Telephony' EN_US_BROADBANDMODEL = 'en-US_BroadbandModel' @@ -3817,6 +3910,7 @@ class Model(str, Enum): EN_US_NARROWBANDMODEL = 'en-US_NarrowbandModel' EN_US_SHORTFORM_NARROWBANDMODEL = 'en-US_ShortForm_NarrowbandModel' EN_US_TELEPHONY = 'en-US_Telephony' + EN_WW_MEDICAL_TELEPHONY = 'en-WW_Medical_Telephony' ES_AR_BROADBANDMODEL = 'es-AR_BroadbandModel' ES_AR_NARROWBANDMODEL = 'es-AR_NarrowbandModel' ES_CL_BROADBANDMODEL = 'es-CL_BroadbandModel' @@ -3825,7 +3919,9 @@ class Model(str, Enum): ES_CO_NARROWBANDMODEL = 'es-CO_NarrowbandModel' ES_ES_BROADBANDMODEL = 'es-ES_BroadbandModel' ES_ES_NARROWBANDMODEL = 'es-ES_NarrowbandModel' + ES_ES_MULTIMEDIA = 'es-ES_Multimedia' ES_ES_TELEPHONY = 'es-ES_Telephony' + ES_LA_TELEPHONY = 'es-LA_Telephony' ES_MX_BROADBANDMODEL = 'es-MX_BroadbandModel' ES_MX_NARROWBANDMODEL = 'es-MX_NarrowbandModel' ES_PE_BROADBANDMODEL = 'es-PE_BroadbandModel' @@ -3851,11 +3947,13 @@ class Model(str, Enum): NL_BE_TELEPHONY = 'nl-BE_Telephony' NL_NL_BROADBANDMODEL = 'nl-NL_BroadbandModel' NL_NL_NARROWBANDMODEL = 'nl-NL_NarrowbandModel' + NL_NL_TELEPHONY = 'nl-NL_Telephony' PT_BR_BROADBANDMODEL = 'pt-BR_BroadbandModel' PT_BR_NARROWBANDMODEL = 'pt-BR_NarrowbandModel' PT_BR_TELEPHONY = 'pt-BR_Telephony' ZH_CN_BROADBANDMODEL = 'zh-CN_BroadbandModel' ZH_CN_NARROWBANDMODEL = 'zh-CN_NarrowbandModel' + ZH_CN_TELEPHONY = 'zh-CN_Telephony' class Events(str, Enum): """ @@ -3891,24 +3989,29 @@ class ListLanguageModelsEnums: class Language(str, Enum): """ The identifier of the language for which custom language or custom acoustic models - are to be returned. Omit the parameter to see all custom language or custom - acoustic models that are owned by the requesting credentials. (**Note:** The - identifier `ar-AR` is deprecated; use `ar-MS` instead.) + are to be returned. Specify the five-character language identifier; for example, + specify `en-US` to see all custom language or custom acoustic models that are + based on US English models. Omit the parameter to see all custom language or + custom acoustic models that are owned by the requesting credentials. (**Note:** + The identifier `ar-AR` is deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ AR_AR = 'ar-AR' AR_MS = 'ar-MS' + CS_CZ = 'cs-CZ' DE_DE = 'de-DE' EN_AU = 'en-AU' EN_GB = 'en-GB' EN_IN = 'en-IN' EN_US = 'en-US' + EN_WW = 'en-WW' ES_AR = 'es-AR' - ES_ES = 'es-ES' ES_CL = 'es-CL' ES_CO = 'es-CO' + ES_ES = 'es-ES' + ES_LA = 'es-LA' ES_MX = 'es-MX' ES_PE = 'es-PE' FR_CA = 'fr-CA' @@ -4006,24 +4109,29 @@ class ListAcousticModelsEnums: class Language(str, Enum): """ The identifier of the language for which custom language or custom acoustic models - are to be returned. Omit the parameter to see all custom language or custom - acoustic models that are owned by the requesting credentials. (**Note:** The - identifier `ar-AR` is deprecated; use `ar-MS` instead.) + are to be returned. Specify the five-character language identifier; for example, + specify `en-US` to see all custom language or custom acoustic models that are + based on US English models. Omit the parameter to see all custom language or + custom acoustic models that are owned by the requesting credentials. (**Note:** + The identifier `ar-AR` is deprecated; use `ar-MS` instead.) To determine the languages for which customization is available, see [Language support for - customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support#custom-language-support). + customization](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-custom-support). """ AR_AR = 'ar-AR' AR_MS = 'ar-MS' + CS_CZ = 'cs-CZ' DE_DE = 'de-DE' EN_AU = 'en-AU' EN_GB = 'en-GB' EN_IN = 'en-IN' EN_US = 'en-US' + EN_WW = 'en-WW' ES_AR = 'es-AR' - ES_ES = 'es-ES' ES_CL = 'es-CL' ES_CO = 'es-CO' + ES_ES = 'es-ES' + ES_LA = 'es-LA' ES_MX = 'es-MX' ES_PE = 'es-PE' FR_CA = 'fr-CA' @@ -4127,7 +4235,8 @@ class AcousticModel(): :attr List[str] versions: (optional) A list of the available versions of the custom acoustic model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions exist only if - the custom model has been upgraded; otherwise, only a single version is shown. + the custom model has been upgraded to a new version of its base model. + Otherwise, only a single version is shown. :attr str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom acoustic model. :attr str name: (optional) The name of the custom acoustic model. @@ -4189,8 +4298,8 @@ def __init__(self, :param List[str] versions: (optional) A list of the available versions of the custom acoustic model. Each element of the array indicates a version of the base model with which the custom model can be used. Multiple versions - exist only if the custom model has been upgraded; otherwise, only a single - version is shown. + exist only if the custom model has been upgraded to a new version of its + base model. Otherwise, only a single version is shown. :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom acoustic model. :param str name: (optional) The name of the custom acoustic model. @@ -5644,8 +5753,11 @@ class Grammar(): Information about a grammar from a custom language model. :attr str name: The name of the grammar. - :attr int out_of_vocabulary_words: The number of OOV words in the grammar. The - value is `0` while the grammar is being processed. + :attr int out_of_vocabulary_words: _For custom models that are based on + previous-generation models_, the number of OOV words extracted from the grammar. + The value is `0` while the grammar is being processed. + _For custom models that are based on next-generation models_, no OOV words are + extracted from grammars, so the value is always `0`. :attr str status: The status of the grammar: * `analyzed`: The service successfully analyzed the grammar. The custom model can be trained with data from the grammar. @@ -5669,8 +5781,11 @@ def __init__(self, Initialize a Grammar object. :param str name: The name of the grammar. - :param int out_of_vocabulary_words: The number of OOV words in the grammar. - The value is `0` while the grammar is being processed. + :param int out_of_vocabulary_words: _For custom models that are based on + previous-generation models_, the number of OOV words extracted from the + grammar. The value is `0` while the grammar is being processed. + _For custom models that are based on next-generation models_, no OOV words + are extracted from grammars, so the value is always `0`. :param str status: The status of the grammar: * `analyzed`: The service successfully analyzed the grammar. The custom model can be trained with data from the grammar. @@ -5942,25 +6057,27 @@ class LanguageModel(): be updated. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). :attr str language: (optional) The language identifier of the custom language - model (for example, `en-US`). + model (for example, `en-US`). The value matches the five-character language + identifier from the name of the base model for the custom model. This value + might be different from the value of the `dialect` field. :attr str dialect: (optional) The dialect of the language for the custom - language model. For non-Spanish models, the field matches the language of the - base model; for example, `en-US` for either of the US English language models. - For Spanish models, the field indicates the dialect for which the model was - created: + language model. _For custom models that are based on non-Spanish + previous-generation models and on next-generation models,_ the field matches the + language of the base model; for example, `en-US` for one of the US English + models. _For custom models that are based on Spanish previous-generation + models,_ the field indicates the dialect with which the model was created. The + value can match the name of the base model or, if it was specified by the user, + can be one of the following: * `es-ES` for Castilian Spanish (`es-ES` models) * `es-LA` for Latin American Spanish (`es-AR`, `es-CL`, `es-CO`, and `es-PE` models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) Dialect values are case-insensitive. - :attr List[str] versions: (optional) _For custom models that are based on - previous-generation models_, a list of the available versions of the custom - language model. Each element of the array indicates a version of the base model - with which the custom model can be used. Multiple versions exist only if the - custom model has been upgraded; otherwise, only a single version is shown. - _For custom models that are based on next-generation models_, a single version - of the custom model. Only one version of a custom model that is based on a - next-generation model is ever available, and upgrading does not apply. + :attr List[str] versions: (optional) A list of the available versions of the + custom language model. Each element of the array indicates a version of the base + model with which the custom model can be used. Multiple versions exist only if + the custom model has been upgraded to a new version of its base model. + Otherwise, only a single version is shown. :attr str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom language model. :attr str name: (optional) The name of the custom language model. @@ -6024,27 +6141,27 @@ def __init__(self, added but has yet to be updated. The value is provided in full ISO 8601 format (YYYY-MM-DDThh:mm:ss.sTZD). :param str language: (optional) The language identifier of the custom - language model (for example, `en-US`). + language model (for example, `en-US`). The value matches the five-character + language identifier from the name of the base model for the custom model. + This value might be different from the value of the `dialect` field. :param str dialect: (optional) The dialect of the language for the custom - language model. For non-Spanish models, the field matches the language of - the base model; for example, `en-US` for either of the US English language - models. For Spanish models, the field indicates the dialect for which the - model was created: + language model. _For custom models that are based on non-Spanish + previous-generation models and on next-generation models,_ the field + matches the language of the base model; for example, `en-US` for one of the + US English models. _For custom models that are based on Spanish + previous-generation models,_ the field indicates the dialect with which the + model was created. The value can match the name of the base model or, if it + was specified by the user, can be one of the following: * `es-ES` for Castilian Spanish (`es-ES` models) * `es-LA` for Latin American Spanish (`es-AR`, `es-CL`, `es-CO`, and `es-PE` models) * `es-US` for Mexican (North American) Spanish (`es-MX` models) Dialect values are case-insensitive. - :param List[str] versions: (optional) _For custom models that are based on - previous-generation models_, a list of the available versions of the custom - language model. Each element of the array indicates a version of the base - model with which the custom model can be used. Multiple versions exist only - if the custom model has been upgraded; otherwise, only a single version is - shown. - _For custom models that are based on next-generation models_, a single - version of the custom model. Only one version of a custom model that is - based on a next-generation model is ever available, and upgrading does not - apply. + :param List[str] versions: (optional) A list of the available versions of + the custom language model. Each element of the array indicates a version of + the base model with which the custom model can be used. Multiple versions + exist only if the custom model has been upgraded to a new version of its + base model. Otherwise, only a single version is shown. :param str owner: (optional) The GUID of the credentials for the instance of the service that owns the custom language model. :param str name: (optional) The name of the custom language model. @@ -7012,8 +7129,8 @@ class SpeechModel(): :attr int rate: The sampling rate (minimum acceptable rate for audio) used by the model in Hertz. :attr str url: The URI for the model. - :attr SupportedFeatures supported_features: Additional service features that are - supported with the model. + :attr SupportedFeatures supported_features: Indicates whether select service + features are supported with the model. :attr str description: A brief description of the model. """ @@ -7030,8 +7147,8 @@ def __init__(self, name: str, language: str, rate: int, url: str, :param int rate: The sampling rate (minimum acceptable rate for audio) used by the model in Hertz. :param str url: The URI for the model. - :param SupportedFeatures supported_features: Additional service features - that are supported with the model. + :param SupportedFeatures supported_features: Indicates whether select + service features are supported with the model. :param str description: A brief description of the model. """ self.name = name @@ -7202,7 +7319,7 @@ class SpeechRecognitionAlternative(): :attr List[str] word_confidence: (optional) A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0.0 to 1.0, for example: - `[["hello",0.95],["world",0.866]]`. Confidence scores are returned only for the + `[["hello",0.95],["world",0.86]]`. Confidence scores are returned only for the best alternative and only with results marked as final. """ @@ -7228,7 +7345,7 @@ def __init__(self, :param List[str] word_confidence: (optional) A confidence score for each word of the transcript as a list of lists. Each inner list consists of two elements: the word and its confidence score in the range of 0.0 to 1.0, for - example: `[["hello",0.95],["world",0.866]]`. Confidence scores are returned + example: `[["hello",0.95],["world",0.86]]`. Confidence scores are returned only for the best alternative and only with results marked as final. """ self.transcript = transcript @@ -7296,9 +7413,13 @@ class SpeechRecognitionResult(): """ Component results for a speech recognition request. - :attr bool final: An indication of whether the transcription results are final. - If `true`, the results for this utterance are not updated further; no additional - results are sent for a `result_index` once its results are indicated as final. + :attr bool final: An indication of whether the transcription results are final: + * If `true`, the results for this utterance are final. They are guaranteed not + to be updated further. + * If `false`, the results are interim. They can be updated with further interim + results until final results are eventually sent. + **Note:** Because `final` is a reserved word in Java and Swift, the field is + renamed `xFinal` in Java and is escaped with back quotes in Swift. :attr List[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. @@ -7335,9 +7456,13 @@ def __init__(self, Initialize a SpeechRecognitionResult object. :param bool final: An indication of whether the transcription results are - final. If `true`, the results for this utterance are not updated further; - no additional results are sent for a `result_index` once its results are - indicated as final. + final: + * If `true`, the results for this utterance are final. They are guaranteed + not to be updated further. + * If `false`, the results are interim. They can be updated with further + interim results until final results are eventually sent. + **Note:** Because `final` is a reserved word in Java and Swift, the field + is renamed `xFinal` in Java and is escaped with back quotes in Swift. :param List[SpeechRecognitionAlternative] alternatives: An array of alternative transcripts. The `alternatives` array can include additional requested output such as word confidence or timestamps. @@ -7470,12 +7595,18 @@ class SpeechRecognitionResults(): `SpeechRecognitionResult` objects that can include interim and final results (interim results are returned only if supported by the method). Final results are guaranteed not to change; interim results might be replaced by further - interim results and final results. The service periodically sends updates to the - results list; the `result_index` is set to the lowest index in the array that - has changed; it is incremented for new results. + interim results and eventually final results. + For the HTTP interfaces, all results arrive at the same time. For the WebSocket + interface, results can be sent as multiple separate responses. The service + periodically sends updates to the results list. The `result_index` is + incremented to the lowest index in the array that has changed for new results. + For more information, see [Understanding speech recognition + results](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-basic-response). :attr int result_index: (optional) An index that indicates a change point in the - `results` array. The service increments the index only for additional results - that it sends for new audio for the same request. + `results` array. The service increments the index for additional results that it + sends for new audio for the same request. All results with the same index are + delivered at the same time. The same index can include multiple final results + that are delivered with the same response. :attr List[SpeakerLabelsResult] speaker_labels: (optional) An array of `SpeakerLabelsResult` objects that identifies which words were spoken by which speakers in a multi-person exchange. The array is returned only if the @@ -7519,13 +7650,19 @@ def __init__(self, `SpeechRecognitionResult` objects that can include interim and final results (interim results are returned only if supported by the method). Final results are guaranteed not to change; interim results might be - replaced by further interim results and final results. The service - periodically sends updates to the results list; the `result_index` is set - to the lowest index in the array that has changed; it is incremented for - new results. + replaced by further interim results and eventually final results. + For the HTTP interfaces, all results arrive at the same time. For the + WebSocket interface, results can be sent as multiple separate responses. + The service periodically sends updates to the results list. The + `result_index` is incremented to the lowest index in the array that has + changed for new results. + For more information, see [Understanding speech recognition + results](https://cloud.ibm.com/docs/speech-to-text?topic=speech-to-text-basic-response). :param int result_index: (optional) An index that indicates a change point - in the `results` array. The service increments the index only for - additional results that it sends for new audio for the same request. + in the `results` array. The service increments the index for additional + results that it sends for new audio for the same request. All results with + the same index are delivered at the same time. The same index can include + multiple final results that are delivered with the same response. :param List[SpeakerLabelsResult] speaker_labels: (optional) An array of `SpeakerLabelsResult` objects that identifies which words were spoken by which speakers in a multi-person exchange. The array is returned only if @@ -7632,20 +7769,23 @@ def __ne__(self, other: 'SpeechRecognitionResults') -> bool: class SupportedFeatures(): """ - Additional service features that are supported with the model. + Indicates whether select service features are supported with the model. :attr bool custom_language_model: Indicates whether the customization interface can be used to create a custom language model based on the language model. + :attr bool custom_acoustic_model: Indicates whether the customization interface + can be used to create a custom acoustic model based on the language model. :attr bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. **Note:** The field returns `true` for all models. However, speaker labels are - supported as beta functionality only for the following languages and models: - * For previous-generation models, the parameter can be used for Australian + supported for use only with the following languages and models: + * _For previous-generation models,_ the parameter can be used with Australian English, US English, German, Japanese, Korean, and Spanish (both broadband and narrowband models) and UK English (narrowband model) transcription only. - * For next-generation models, the parameter can be used for English (Australian, - Indian, UK, and US), German, Japanese, Korean, and Spanish transcription only. - Speaker labels are not supported for any other models. + * _For next-generation models,_ the parameter can be used with Czech, English + (Australian, Indian, UK, and US), German, Japanese, Korean, and Spanish + transcription only. + Speaker labels are not supported for use with any other languages or models. :attr bool low_latency: (optional) Indicates whether the `low_latency` parameter can be used with a next-generation language model. The field is returned only for next-generation models. Previous-generation models do not support the @@ -7654,6 +7794,7 @@ class SupportedFeatures(): def __init__(self, custom_language_model: bool, + custom_acoustic_model: bool, speaker_labels: bool, *, low_latency: bool = None) -> None: @@ -7663,25 +7804,29 @@ def __init__(self, :param bool custom_language_model: Indicates whether the customization interface can be used to create a custom language model based on the language model. + :param bool custom_acoustic_model: Indicates whether the customization + interface can be used to create a custom acoustic model based on the + language model. :param bool speaker_labels: Indicates whether the `speaker_labels` parameter can be used with the language model. **Note:** The field returns `true` for all models. However, speaker labels - are supported as beta functionality only for the following languages and - models: - * For previous-generation models, the parameter can be used for Australian - English, US English, German, Japanese, Korean, and Spanish (both broadband - and narrowband models) and UK English (narrowband model) transcription - only. - * For next-generation models, the parameter can be used for English - (Australian, Indian, UK, and US), German, Japanese, Korean, and Spanish + are supported for use only with the following languages and models: + * _For previous-generation models,_ the parameter can be used with + Australian English, US English, German, Japanese, Korean, and Spanish (both + broadband and narrowband models) and UK English (narrowband model) transcription only. - Speaker labels are not supported for any other models. + * _For next-generation models,_ the parameter can be used with Czech, + English (Australian, Indian, UK, and US), German, Japanese, Korean, and + Spanish transcription only. + Speaker labels are not supported for use with any other languages or + models. :param bool low_latency: (optional) Indicates whether the `low_latency` parameter can be used with a next-generation language model. The field is returned only for next-generation models. Previous-generation models do not support the `low_latency` parameter. """ self.custom_language_model = custom_language_model + self.custom_acoustic_model = custom_acoustic_model self.speaker_labels = speaker_labels self.low_latency = low_latency @@ -7695,6 +7840,12 @@ def from_dict(cls, _dict: Dict) -> 'SupportedFeatures': raise ValueError( 'Required property \'custom_language_model\' not present in SupportedFeatures JSON' ) + if 'custom_acoustic_model' in _dict: + args['custom_acoustic_model'] = _dict.get('custom_acoustic_model') + else: + raise ValueError( + 'Required property \'custom_acoustic_model\' not present in SupportedFeatures JSON' + ) if 'speaker_labels' in _dict: args['speaker_labels'] = _dict.get('speaker_labels') else: @@ -7716,6 +7867,9 @@ def to_dict(self) -> Dict: if hasattr(self, 'custom_language_model' ) and self.custom_language_model is not None: _dict['custom_language_model'] = self.custom_language_model + if hasattr(self, 'custom_acoustic_model' + ) and self.custom_acoustic_model is not None: + _dict['custom_acoustic_model'] = self.custom_acoustic_model if hasattr(self, 'speaker_labels') and self.speaker_labels is not None: _dict['speaker_labels'] = self.speaker_labels if hasattr(self, 'low_latency') and self.low_latency is not None: diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 4924eeed8..9d5514257 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -1,6 +1,6 @@ # coding: utf-8 -# (C) Copyright IBM Corp. 2015, 2021. +# (C) Copyright IBM Corp. 2015, 2022. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 +# IBM OpenAPI SDK Code Generator Version: 3.46.0-a4e29da0-20220224-210428 """ The IBM Watson™ Text to Speech service provides APIs that use IBM's speech-synthesis capabilities to synthesize text into natural-sounding speech in a variety of languages, @@ -30,13 +30,11 @@ that, when combined, sound like the word. A phonetic translation is based on the SSML phoneme format for representing a word. You can specify a phonetic translation in standard International Phonetic Alphabet (IPA) representation or in the proprietary IBM Symbolic -Phonetic Representation (SPR). +Phonetic Representation (SPR). For phonetic translation, the Arabic, Chinese, Dutch, +Australian English, Korean, and Swedish voices support only IPA, not SPR. The service also offers a Tune by Example feature that lets you define custom prompts. You can also define speaker models to improve the quality of your custom prompts. The service support custom prompts only for US English custom models and voices. -**IBM Cloud®.** The Arabic, Chinese, Dutch, Australian English, and Korean languages -and voices are supported only for IBM Cloud. For phonetic translation, they support only -IPA, not SPR. API Version: 1.0.0 See: https://cloud.ibm.com/docs/text-to-speech @@ -73,7 +71,7 @@ def __init__( Construct a new client for the Text to Speech service. :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md + Get up to date information from https://github.com/IBM/python-sdk-core/blob/main/README.md about initializing the authenticator of your choice. """ if not authenticator: @@ -135,33 +133,12 @@ def get_voice(self, voices](#listvoices) method. **See also:** [Listing a specific voice](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices#listVoice). - ### Important voice updates for IBM Cloud - The service's voices underwent significant change on 2 December 2020. - * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural - instead of concatenative. - * The `ar-AR_OmarVoice` voice is deprecated. Use `ar-MS_OmarVoice` voice instead. - * The `ar-AR` language identifier cannot be used to create a custom model. Use the - `ar-MS` identifier instead. - * The standard concatenative voices for the following languages are now - deprecated: Brazilian Portuguese, United Kingdom and United States English, - French, German, Italian, Japanese, and Spanish (all dialects). - * The features expressive SSML, voice transformation SSML, and use of the `volume` - attribute of the `` element are deprecated and are not supported with any - of the service's neural voices. - * All of the service's voices are now customizable and generally available (GA) - for production use. - The deprecated voices and features will continue to function for at least one year - but might be removed at a future date. You are encouraged to migrate to the - equivalent neural voices at your earliest convenience. For more information about - all voice updates, see the [2 December 2020 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) - in the release notes for IBM Cloud. - - :param str voice: The voice for which information is to be returned. For - more information about specifying a voice, see **Important voice updates - for IBM Cloud** in the method description. - **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean - languages and voices are supported only for IBM Cloud. + **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian + English, Korean, and Swedish languages and voices are supported only for IBM + Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` + voice is deprecated; use the `ar-MS_OmarVoice` voice instead. + + :param str voice: The voice for which information is to be returned. :param str customization_id: (optional) The customization ID (GUID) of a custom model for which information is to be returned. You must make the request with credentials for the instance of the service that owns the @@ -220,6 +197,10 @@ def synthesize(self, specify. The service returns the synthesized audio stream as an array of bytes. **See also:** [The HTTP interface](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-usingHTTP#usingHTTP). + **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian + English, Korean, and Swedish languages and voices are supported only for IBM + Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` + voice is deprecated; use the `ar-MS_OmarVoice` voice instead. ### 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 @@ -263,27 +244,6 @@ def synthesize(self, For more information about specifying an audio format, including additional details about some of the formats, see [Using audio formats](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-audio-formats). - ### Important voice updates for IBM Cloud - The service's voices underwent significant change on 2 December 2020. - * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural - instead of concatenative. - * The `ar-AR_OmarVoice` voice is deprecated. Use `ar-MS_OmarVoice` voice instead. - * The `ar-AR` language identifier cannot be used to create a custom model. Use the - `ar-MS` identifier instead. - * The standard concatenative voices for the following languages are now - deprecated: Brazilian Portuguese, United Kingdom and United States English, - French, German, Italian, Japanese, and Spanish (all dialects). - * The features expressive SSML, voice transformation SSML, and use of the `volume` - attribute of the `` element are deprecated and are not supported with any - of the service's neural voices. - * All of the service's voices are now customizable and generally available (GA) - for production use. - The deprecated voices and features will continue to function for at least one year - but might be removed at a future date. You are encouraged to migrate to the - equivalent neural voices at your earliest convenience. For more information about - all voice updates, see the [2 December 2020 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) - in the release notes for IBM Cloud. ### 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 @@ -297,11 +257,17 @@ def synthesize(self, audio. You can use the `Accept` header or the `accept` parameter to specify the audio format. For more information about specifying an audio format, see **Audio formats (accept types)** in the method description. - :param str voice: (optional) The voice to use for synthesis. For more - information about specifying a voice, see **Important voice updates for IBM - Cloud** in the method description. - **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean - languages and voices are supported only for IBM Cloud. + :param str voice: (optional) The voice to use for synthesis. If you omit + the `voice` parameter, the service uses a default voice, which depends on + the version of the service that you are using: + * _For IBM Cloud,_ the service always uses the US English + `en-US_MichaelV3Voice` by default. + * _For IBM Cloud Pak for Data,_ the default voice depends on the voices + that you installed. If you installed the _enhanced neural voices_, the + service uses the US English `en-US_MichaelV3Voice` by default; if that + voice is not installed, you must specify a voice. If you installed the + _neural voices_, the service always uses the Australian English + `en-AU_MadisonVoice` by default. **See also:** See also [Using languages and voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices). :param str customization_id: (optional) The customization ID (GUID) of a @@ -363,36 +329,15 @@ def get_pronunciation(self, for a specific custom model to see the translation for that model. **See also:** [Querying a word from a language](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customWords#cuWordsQueryLanguage). - ### Important voice updates for IBM Cloud - The service's voices underwent significant change on 2 December 2020. - * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural - instead of concatenative. - * The `ar-AR_OmarVoice` voice is deprecated. Use `ar-MS_OmarVoice` voice instead. - * The `ar-AR` language identifier cannot be used to create a custom model. Use the - `ar-MS` identifier instead. - * The standard concatenative voices for the following languages are now - deprecated: Brazilian Portuguese, United Kingdom and United States English, - French, German, Italian, Japanese, and Spanish (all dialects). - * The features expressive SSML, voice transformation SSML, and use of the `volume` - attribute of the `` element are deprecated and are not supported with any - of the service's neural voices. - * All of the service's voices are now customizable and generally available (GA) - for production use. - The deprecated voices and features will continue to function for at least one year - but might be removed at a future date. You are encouraged to migrate to the - equivalent neural voices at your earliest convenience. For more information about - all voice updates, see the [2 December 2020 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) - in the release notes for IBM Cloud. + **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian + English, Korean, and Swedish languages and voices are supported only for IBM + Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR_OmarVoice` + voice is deprecated; use the `ar-MS_OmarVoice` voice instead. :param str text: The word for which the pronunciation is requested. :param str voice: (optional) A voice that specifies the language in which the pronunciation is to be returned. All voices for the same language (for - example, `en-US`) return the same translation. For more information about - specifying a voice, see **Important voice updates for IBM Cloud** in the - method description. - **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean - languages and voices are supported only for IBM Cloud. + example, `en-US`) return the same translation. :param str format: (optional) The phoneme format in which to return the pronunciation. The Arabic, Chinese, Dutch, Australian English, and Korean languages support only IPA. Omit the parameter to obtain the pronunciation @@ -457,37 +402,22 @@ def create_custom_model(self, used to create it. **See also:** [Creating a custom model](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-customModels#cuModelsCreate). - ### Important voice updates for IBM Cloud - The service's voices underwent significant change on 2 December 2020. - * The Arabic, Chinese, Dutch, Australian English, and Korean voices are now neural - instead of concatenative. - * The `ar-AR_OmarVoice` voice is deprecated. Use `ar-MS_OmarVoice` voice instead. - * The `ar-AR` language identifier cannot be used to create a custom model. Use the - `ar-MS` identifier instead. - * The standard concatenative voices for the following languages are now - deprecated: Brazilian Portuguese, United Kingdom and United States English, - French, German, Italian, Japanese, and Spanish (all dialects). - * The features expressive SSML, voice transformation SSML, and use of the `volume` - attribute of the `` element are deprecated and are not supported with any - of the service's neural voices. - * All of the service's voices are now customizable and generally available (GA) - for production use. - The deprecated voices and features will continue to function for at least one year - but might be removed at a future date. You are encouraged to migrate to the - equivalent neural voices at your earliest convenience. For more information about - all voice updates, see the [2 December 2020 service - update](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-release-notes#December2020) - in the release notes for IBM Cloud. + **Note:** The Arabic, Chinese, Czech, Dutch (Belgian and Netherlands), Australian + English, Korean, and Swedish languages and voices are supported only for IBM + Cloud; they are deprecated for IBM Cloud Pak for Data. Also, the `ar-AR` language + identifier cannot be used to create a custom model; use the `ar-MS` identifier + instead. :param str name: The name of the new custom model. :param str language: (optional) The language of the new custom model. You create a custom model for a specific language, not for a specific voice. A custom model can be used with any voice for its specified language. Omit - the parameter to use the the default language, `en-US`. **Note:** The - `ar-AR` language identifier cannot be used to create a custom model. Use - the `ar-MS` identifier instead. - **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean - languages and voices are supported only for IBM Cloud. + the parameter to use the the default language, `en-US`. + **Important:** If you are using the service on IBM Cloud Pak for Data _and_ + you install the neural voices, the `language`parameter is required. You + must specify the language for the custom model in the indicated format (for + example, `en-AU` for Australian English). The request fails if you do not + specify a language. :param str description: (optional) A description of the new custom model. Specifying a description is recommended. :param dict headers: A `dict` containing the request headers @@ -1595,21 +1525,19 @@ class GetVoiceEnums: class Voice(str, Enum): """ - The voice for which information is to be returned. For more information about - specifying a voice, see **Important voice updates for IBM Cloud** in the method - description. - **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean - languages and voices are supported only for IBM Cloud. + The voice for which information is to be returned. """ AR_AR_OMARVOICE = 'ar-AR_OmarVoice' AR_MS_OMARVOICE = 'ar-MS_OmarVoice' + CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU-CraigVoice' - EN_AU_MADISONVOICE = 'en-AU-MadisonVoice' + EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' + EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' + EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' @@ -1645,10 +1573,12 @@ class Voice(str, Enum): KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' + NL_BE_BRAMVOICE = 'nl-BE_BramVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' @@ -1682,22 +1612,30 @@ class Accept(str, Enum): class Voice(str, Enum): """ - The voice to use for synthesis. For more information about specifying a voice, see - **Important voice updates for IBM Cloud** in the method description. - **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean - languages and voices are supported only for IBM Cloud. + The voice to use for synthesis. If you omit the `voice` parameter, the service + uses a default voice, which depends on the version of the service that you are + using: + * _For IBM Cloud,_ the service always uses the US English `en-US_MichaelV3Voice` + by default. + * _For IBM Cloud Pak for Data,_ the default voice depends on the voices that you + installed. If you installed the _enhanced neural voices_, the service uses the US + English `en-US_MichaelV3Voice` by default; if that voice is not installed, you + must specify a voice. If you installed the _neural voices_, the service always + uses the Australian English `en-AU_MadisonVoice` by default. **See also:** See also [Using languages and voices](https://cloud.ibm.com/docs/text-to-speech?topic=text-to-speech-voices). """ AR_AR_OMARVOICE = 'ar-AR_OmarVoice' AR_MS_OMARVOICE = 'ar-MS_OmarVoice' + CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU-CraigVoice' - EN_AU_MADISONVOICE = 'en-AU-MadisonVoice' + EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' + EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' + EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' @@ -1733,10 +1671,12 @@ class Voice(str, Enum): KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' + NL_BE_BRAMVOICE = 'nl-BE_BramVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' @@ -1751,20 +1691,19 @@ class Voice(str, Enum): """ A voice that specifies the language in which the pronunciation is to be returned. All voices for the same language (for example, `en-US`) return the same - translation. For more information about specifying a voice, see **Important voice - updates for IBM Cloud** in the method description. - **IBM Cloud:** The Arabic, Chinese, Dutch, Australian English, and Korean - languages and voices are supported only for IBM Cloud. + translation. """ AR_AR_OMARVOICE = 'ar-AR_OmarVoice' AR_MS_OMARVOICE = 'ar-MS_OmarVoice' + CS_CZ_ALENAVOICE = 'cs-CZ_AlenaVoice' DE_DE_BIRGITVOICE = 'de-DE_BirgitVoice' DE_DE_BIRGITV3VOICE = 'de-DE_BirgitV3Voice' DE_DE_DIETERVOICE = 'de-DE_DieterVoice' DE_DE_DIETERV3VOICE = 'de-DE_DieterV3Voice' DE_DE_ERIKAV3VOICE = 'de-DE_ErikaV3Voice' - EN_AU_CRAIGVOICE = 'en-AU-CraigVoice' - EN_AU_MADISONVOICE = 'en-AU-MadisonVoice' + EN_AU_CRAIGVOICE = 'en-AU_CraigVoice' + EN_AU_MADISONVOICE = 'en-AU_MadisonVoice' + EN_AU_STEVEVOICE = 'en-AU_SteveVoice' EN_GB_CHARLOTTEV3VOICE = 'en-GB_CharlotteV3Voice' EN_GB_JAMESV3VOICE = 'en-GB_JamesV3Voice' EN_GB_KATEVOICE = 'en-GB_KateVoice' @@ -1800,10 +1739,12 @@ class Voice(str, Enum): KO_KR_YOUNGMIVOICE = 'ko-KR_YoungmiVoice' KO_KR_YUNAVOICE = 'ko-KR_YunaVoice' NL_BE_ADELEVOICE = 'nl-BE_AdeleVoice' + NL_BE_BRAMVOICE = 'nl-BE_BramVoice' NL_NL_EMMAVOICE = 'nl-NL_EmmaVoice' NL_NL_LIAMVOICE = 'nl-NL_LiamVoice' PT_BR_ISABELAVOICE = 'pt-BR_IsabelaVoice' PT_BR_ISABELAV3VOICE = 'pt-BR_IsabelaV3Voice' + SV_SE_INGRIDVOICE = 'sv-SE_IngridVoice' ZH_CN_LINAVOICE = 'zh-CN_LiNaVoice' ZH_CN_WANGWEIVOICE = 'zh-CN_WangWeiVoice' ZH_CN_ZHANGJINGVOICE = 'zh-CN_ZhangJingVoice' @@ -1830,6 +1771,7 @@ class Language(str, Enum): the requester. """ AR_MS = 'ar-MS' + CS_CZ = 'cs-CZ' DE_DE = 'de-DE' EN_AU = 'en-AU' EN_GB = 'en-GB' @@ -1845,6 +1787,7 @@ class Language(str, Enum): NL_BE = 'nl-BE' NL_NL = 'nl-NL' PT_BR = 'pt-BR' + SV_SE = 'sv-SE' ZH_CN = 'zh-CN' diff --git a/ibm_watson/tone_analyzer_v3.py b/ibm_watson/tone_analyzer_v3.py deleted file mode 100644 index 61985fc5d..000000000 --- a/ibm_watson/tone_analyzer_v3.py +++ /dev/null @@ -1,1298 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2016, 2020. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 -""" -The IBM Watson™ Tone Analyzer service uses linguistic analysis to detect emotional -and language tones in written text. The service can analyze tone at both the document and -sentence levels. You can use the service to understand how your written communications are -perceived and then to improve the tone of your communications. Businesses can use the -service to learn the tone of their customers' communications and to respond to each -customer appropriately, or to understand and improve their customer conversations. -**Note:** Request logging is disabled for the Tone Analyzer 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. - -API Version: 3.5.3 -See: https://cloud.ibm.com/docs/tone-analyzer -""" - -from enum import Enum -from typing import Dict, List, TextIO, Union -import json - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import convert_list, convert_model - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class ToneAnalyzerV3(BaseService): - """The Tone Analyzer V3 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'tone_analyzer' - - def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Tone Analyzer service. - - :param str version: Release date of the version of the API you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2017-09-21`. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md - about initializing the authenticator of your choice. - """ - if version is None: - raise ValueError('version must be provided') - - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.version = version - self.configure_service(service_name) - - ######################### - # Methods - ######################### - - def tone(self, - tone_input: Union['ToneInput', str, TextIO], - *, - content_type: str = None, - sentences: bool = None, - tones: List[str] = None, - content_language: str = None, - accept_language: str = None, - **kwargs) -> DetailedResponse: - """ - Analyze general tone. - - Use the general-purpose endpoint to analyze the tone of your input content. The - service analyzes the content for emotional and language tones. The method always - analyzes the tone of the full document; by default, it also analyzes the tone of - each individual sentence of the content. - You can submit no more than 128 KB of total input content and no more than 1000 - individual sentences in JSON, plain text, or HTML format. The service analyzes the - first 1000 sentences for document-level analysis and only the first 100 sentences - for sentence-level analysis. - Per the JSON specification, the default character encoding for JSON content is - effectively always UTF-8; per the HTTP specification, the default encoding for - plain text and HTML is ISO-8859-1 (effectively, the ASCII character set). When - specifying a content type of plain text or HTML, include the `charset` parameter - to indicate the character encoding of the input text; for example: `Content-Type: - 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/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 - `ToneInput`. - :param str content_type: (optional) The type of the input. A character - encoding can be specified by including a `charset` parameter. For example, - 'text/plain;charset=utf-8'. - :param bool sentences: (optional) Indicates whether the service is to - return an analysis of each individual sentence in addition to its analysis - of the full document. If `true` (the default), the service returns results - for each sentence. - :param List[str] tones: (optional) **`2017-09-21`:** Deprecated. The - service continues to accept the parameter for backward-compatibility, but - the parameter no longer affects the response. - **`2016-05-19`:** A comma-separated list of tones for which the service is - to return its analysis of the input; the indicated tones apply both to the - full document and to individual sentences of the document. You can specify - one or more of the valid values. Omit the parameter to request results for - all three tones. - :param str content_language: (optional) The language of the input text for - the request: English or French. Regional variants are treated as their - parent language; for example, `en-US` is interpreted as `en`. The input - content must match the specified language. Do not submit content that - contains both languages. You can use different languages for - **Content-Language** and **Accept-Language**. - * **`2017-09-21`:** Accepts `en` or `fr`. - * **`2016-05-19`:** Accepts only `en`. - :param str accept_language: (optional) The desired language of the - response. For two-character arguments, regional variants are treated as - their parent language; for example, `en-US` is interpreted as `en`. You can - use different languages for **Content-Language** and **Accept-Language**. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ToneAnalysis` object - """ - - if tone_input is None: - raise ValueError('tone_input must be provided') - if isinstance(tone_input, ToneInput): - tone_input = convert_model(tone_input) - content_type = content_type or 'application/json' - headers = { - 'Content-Type': content_type, - 'Content-Language': content_language, - 'Accept-Language': accept_language - } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='tone') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'sentences': sentences, - 'tones': convert_list(tones) - } - - if isinstance(tone_input, dict): - data = json.dumps(tone_input) - if content_type is None: - headers['Content-Type'] = 'application/json' - else: - data = tone_input - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/tone' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def tone_chat(self, - utterances: List['Utterance'], - *, - content_language: str = None, - accept_language: str = None, - **kwargs) -> DetailedResponse: - """ - Analyze customer-engagement tone. - - Use the customer-engagement endpoint to analyze the tone of customer service and - customer support conversations. For each utterance of a conversation, the method - reports the most prevalent subset of the following seven tones: sad, frustrated, - satisfied, excited, polite, impolite, and sympathetic. - If you submit more than 50 utterances, the service returns a warning for the - overall content and analyzes only the first 50 utterances. If you submit a single - utterance that contains more than 500 characters, the service returns an error for - that utterance and does not analyze the utterance. The request fails if all - 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/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. - :param str content_language: (optional) The language of the input text for - the request: English or French. Regional variants are treated as their - parent language; for example, `en-US` is interpreted as `en`. The input - content must match the specified language. Do not submit content that - contains both languages. You can use different languages for - **Content-Language** and **Accept-Language**. - * **`2017-09-21`:** Accepts `en` or `fr`. - * **`2016-05-19`:** Accepts only `en`. - :param str accept_language: (optional) The desired language of the - response. For two-character arguments, regional variants are treated as - their parent language; for example, `en-US` is interpreted as `en`. You can - use different languages for **Content-Language** and **Accept-Language**. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `UtteranceAnalyses` object - """ - - if utterances is None: - raise ValueError('utterances must be provided') - utterances = [convert_model(x) for x in utterances] - headers = { - 'Content-Language': content_language, - 'Accept-Language': accept_language - } - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='tone_chat') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = {'utterances': utterances} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/tone_chat' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - -class ToneEnums: - """ - Enums for tone parameters. - """ - - class ContentType(str, Enum): - """ - The type of the input. A character encoding can be specified by including a - `charset` parameter. For example, 'text/plain;charset=utf-8'. - """ - APPLICATION_JSON = 'application/json' - TEXT_PLAIN = 'text/plain' - TEXT_HTML = 'text/html' - - class Tones(str, Enum): - """ - **`2017-09-21`:** Deprecated. The service continues to accept the parameter for - backward-compatibility, but the parameter no longer affects the response. - **`2016-05-19`:** A comma-separated list of tones for which the service is to - return its analysis of the input; the indicated tones apply both to the full - document and to individual sentences of the document. You can specify one or more - of the valid values. Omit the parameter to request results for all three tones. - """ - EMOTION = 'emotion' - LANGUAGE = 'language' - SOCIAL = 'social' - - class ContentLanguage(str, Enum): - """ - The language of the input text for the request: English or French. Regional - variants are treated as their parent language; for example, `en-US` is interpreted - as `en`. The input content must match the specified language. Do not submit - content that contains both languages. You can use different languages for - **Content-Language** and **Accept-Language**. - * **`2017-09-21`:** Accepts `en` or `fr`. - * **`2016-05-19`:** Accepts only `en`. - """ - EN = 'en' - FR = 'fr' - - class AcceptLanguage(str, Enum): - """ - The desired language of the response. For two-character arguments, regional - variants are treated as their parent language; for example, `en-US` is interpreted - as `en`. You can use different languages for **Content-Language** and - **Accept-Language**. - """ - AR = 'ar' - DE = 'de' - EN = 'en' - ES = 'es' - FR = 'fr' - IT = 'it' - JA = 'ja' - KO = 'ko' - PT_BR = 'pt-br' - ZH_CN = 'zh-cn' - ZH_TW = 'zh-tw' - - -class ToneChatEnums: - """ - Enums for tone_chat parameters. - """ - - class ContentLanguage(str, Enum): - """ - The language of the input text for the request: English or French. Regional - variants are treated as their parent language; for example, `en-US` is interpreted - as `en`. The input content must match the specified language. Do not submit - content that contains both languages. You can use different languages for - **Content-Language** and **Accept-Language**. - * **`2017-09-21`:** Accepts `en` or `fr`. - * **`2016-05-19`:** Accepts only `en`. - """ - EN = 'en' - FR = 'fr' - - class AcceptLanguage(str, Enum): - """ - The desired language of the response. For two-character arguments, regional - variants are treated as their parent language; for example, `en-US` is interpreted - as `en`. You can use different languages for **Content-Language** and - **Accept-Language**. - """ - AR = 'ar' - DE = 'de' - EN = 'en' - ES = 'es' - FR = 'fr' - IT = 'it' - JA = 'ja' - KO = 'ko' - PT_BR = 'pt-br' - ZH_CN = 'zh-cn' - ZH_TW = 'zh-tw' - - -############################################################################## -# Models -############################################################################## - - -class DocumentAnalysis(): - """ - The results of the analysis for the full input content. - - :attr List[ToneScore] tones: (optional) **`2017-09-21`:** An array of - `ToneScore` objects that provides the results of the analysis for each - qualifying tone of the document. The array includes results for any tone whose - score is at least 0.5. The array is empty if no tone has a score that meets this - threshold. **`2016-05-19`:** Not returned. - :attr List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not - returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the - results of the tone analysis for the full document of the input content. The - service returns results only for the tones specified with the `tones` parameter - of the request. - :attr str warning: (optional) **`2017-09-21`:** A warning message if the overall - content exceeds 128 KB or contains more than 1000 sentences. The service - analyzes only the first 1000 sentences for document-level analysis and the first - 100 sentences for sentence-level analysis. **`2016-05-19`:** Not returned. - """ - - def __init__(self, - *, - tones: List['ToneScore'] = None, - tone_categories: List['ToneCategory'] = None, - warning: str = None) -> None: - """ - Initialize a DocumentAnalysis object. - - :param List[ToneScore] tones: (optional) **`2017-09-21`:** An array of - `ToneScore` objects that provides the results of the analysis for each - qualifying tone of the document. The array includes results for any tone - whose score is at least 0.5. The array is empty if no tone has a score that - meets this threshold. **`2016-05-19`:** Not returned. - :param List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not - returned. **`2016-05-19`:** An array of `ToneCategory` objects that - provides the results of the tone analysis for the full document of the - input content. The service returns results only for the tones specified - with the `tones` parameter of the request. - :param str warning: (optional) **`2017-09-21`:** A warning message if the - overall content exceeds 128 KB or contains more than 1000 sentences. The - service analyzes only the first 1000 sentences for document-level analysis - and the first 100 sentences for sentence-level analysis. **`2016-05-19`:** - Not returned. - """ - self.tones = tones - self.tone_categories = tone_categories - self.warning = warning - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DocumentAnalysis': - """Initialize a DocumentAnalysis object from a json dictionary.""" - args = {} - if 'tones' in _dict: - args['tones'] = [ToneScore.from_dict(x) for x in _dict.get('tones')] - if 'tone_categories' in _dict: - args['tone_categories'] = [ - ToneCategory.from_dict(x) for x in _dict.get('tone_categories') - ] - if 'warning' in _dict: - args['warning'] = _dict.get('warning') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DocumentAnalysis 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, 'tones') and self.tones is not None: - _dict['tones'] = [x.to_dict() for x in self.tones] - if hasattr(self, - 'tone_categories') and self.tone_categories is not None: - _dict['tone_categories'] = [ - x.to_dict() for x in self.tone_categories - ] - if hasattr(self, 'warning') and self.warning is not None: - _dict['warning'] = self.warning - 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 DocumentAnalysis object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DocumentAnalysis') -> 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: 'DocumentAnalysis') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class SentenceAnalysis(): - """ - The results of the analysis for the individual sentences of the input content. - - :attr int sentence_id: The unique identifier of a sentence of the input content. - The first sentence has ID 0, and the ID of each subsequent sentence is - incremented by one. - :attr str text: The text of the input sentence. - :attr List[ToneScore] tones: (optional) **`2017-09-21`:** An array of - `ToneScore` objects that provides the results of the analysis for each - qualifying tone of the sentence. The array includes results for any tone whose - score is at least 0.5. The array is empty if no tone has a score that meets this - threshold. **`2016-05-19`:** Not returned. - :attr List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not - returned. **`2016-05-19`:** An array of `ToneCategory` objects that provides the - results of the tone analysis for the sentence. The service returns results only - for the tones specified with the `tones` parameter of the request. - :attr int input_from: (optional) **`2017-09-21`:** Not returned. - **`2016-05-19`:** The offset of the first character of the sentence in the - overall input content. - :attr int input_to: (optional) **`2017-09-21`:** Not returned. **`2016-05-19`:** - The offset of the last character of the sentence in the overall input content. - """ - - def __init__(self, - sentence_id: int, - text: str, - *, - tones: List['ToneScore'] = None, - tone_categories: List['ToneCategory'] = None, - input_from: int = None, - input_to: int = None) -> None: - """ - Initialize a SentenceAnalysis object. - - :param int sentence_id: The unique identifier of a sentence of the input - content. The first sentence has ID 0, and the ID of each subsequent - sentence is incremented by one. - :param str text: The text of the input sentence. - :param List[ToneScore] tones: (optional) **`2017-09-21`:** An array of - `ToneScore` objects that provides the results of the analysis for each - qualifying tone of the sentence. The array includes results for any tone - whose score is at least 0.5. The array is empty if no tone has a score that - meets this threshold. **`2016-05-19`:** Not returned. - :param List[ToneCategory] tone_categories: (optional) **`2017-09-21`:** Not - returned. **`2016-05-19`:** An array of `ToneCategory` objects that - provides the results of the tone analysis for the sentence. The service - returns results only for the tones specified with the `tones` parameter of - the request. - :param int input_from: (optional) **`2017-09-21`:** Not returned. - **`2016-05-19`:** The offset of the first character of the sentence in the - overall input content. - :param int input_to: (optional) **`2017-09-21`:** Not returned. - **`2016-05-19`:** The offset of the last character of the sentence in the - overall input content. - """ - self.sentence_id = sentence_id - self.text = text - self.tones = tones - self.tone_categories = tone_categories - self.input_from = input_from - self.input_to = input_to - - @classmethod - def from_dict(cls, _dict: Dict) -> 'SentenceAnalysis': - """Initialize a SentenceAnalysis object from a json dictionary.""" - args = {} - if 'sentence_id' in _dict: - args['sentence_id'] = _dict.get('sentence_id') - else: - raise ValueError( - 'Required property \'sentence_id\' not present in SentenceAnalysis JSON' - ) - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in SentenceAnalysis JSON' - ) - if 'tones' in _dict: - args['tones'] = [ToneScore.from_dict(x) for x in _dict.get('tones')] - if 'tone_categories' in _dict: - args['tone_categories'] = [ - ToneCategory.from_dict(x) for x in _dict.get('tone_categories') - ] - if 'input_from' in _dict: - args['input_from'] = _dict.get('input_from') - if 'input_to' in _dict: - args['input_to'] = _dict.get('input_to') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a SentenceAnalysis 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, 'sentence_id') and self.sentence_id is not None: - _dict['sentence_id'] = self.sentence_id - if hasattr(self, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'tones') and self.tones is not None: - _dict['tones'] = [x.to_dict() for x in self.tones] - if hasattr(self, - 'tone_categories') and self.tone_categories is not None: - _dict['tone_categories'] = [ - x.to_dict() for x in self.tone_categories - ] - if hasattr(self, 'input_from') and self.input_from is not None: - _dict['input_from'] = self.input_from - if hasattr(self, 'input_to') and self.input_to is not None: - _dict['input_to'] = self.input_to - 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 SentenceAnalysis object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'SentenceAnalysis') -> 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: 'SentenceAnalysis') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ToneAnalysis(): - """ - The tone analysis results for the input from the general-purpose endpoint. - - :attr DocumentAnalysis document_tone: The results of the analysis for the full - input content. - :attr List[SentenceAnalysis] sentences_tone: (optional) An array of - `SentenceAnalysis` objects that provides the results of the analysis for the - individual sentences of the input content. The service returns results only for - the first 100 sentences of the input. The field is omitted if the `sentences` - parameter of the request is set to `false`. - """ - - def __init__(self, - document_tone: 'DocumentAnalysis', - *, - sentences_tone: List['SentenceAnalysis'] = None) -> None: - """ - Initialize a ToneAnalysis object. - - :param DocumentAnalysis document_tone: The results of the analysis for the - full input content. - :param List[SentenceAnalysis] sentences_tone: (optional) An array of - `SentenceAnalysis` objects that provides the results of the analysis for - the individual sentences of the input content. The service returns results - only for the first 100 sentences of the input. The field is omitted if the - `sentences` parameter of the request is set to `false`. - """ - self.document_tone = document_tone - self.sentences_tone = sentences_tone - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ToneAnalysis': - """Initialize a ToneAnalysis object from a json dictionary.""" - args = {} - if 'document_tone' in _dict: - args['document_tone'] = DocumentAnalysis.from_dict( - _dict.get('document_tone')) - else: - raise ValueError( - 'Required property \'document_tone\' not present in ToneAnalysis JSON' - ) - if 'sentences_tone' in _dict: - args['sentences_tone'] = [ - SentenceAnalysis.from_dict(x) - for x in _dict.get('sentences_tone') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ToneAnalysis 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, 'document_tone') and self.document_tone is not None: - _dict['document_tone'] = self.document_tone.to_dict() - if hasattr(self, 'sentences_tone') and self.sentences_tone is not None: - _dict['sentences_tone'] = [x.to_dict() for x in self.sentences_tone] - 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 ToneAnalysis object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ToneAnalysis') -> 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: 'ToneAnalysis') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ToneCategory(): - """ - The category for a tone from the input content. - - :attr List[ToneScore] tones: An array of `ToneScore` objects that provides the - results for the tones of the category. - :attr str category_id: The unique, non-localized identifier of the category for - the results. The service can return results for the following category IDs: - `emotion_tone`, `language_tone`, and `social_tone`. - :attr str category_name: The user-visible, localized name of the category. - """ - - def __init__(self, tones: List['ToneScore'], category_id: str, - category_name: str) -> None: - """ - Initialize a ToneCategory object. - - :param List[ToneScore] tones: An array of `ToneScore` objects that provides - the results for the tones of the category. - :param str category_id: The unique, non-localized identifier of the - category for the results. The service can return results for the following - category IDs: `emotion_tone`, `language_tone`, and `social_tone`. - :param str category_name: The user-visible, localized name of the category. - """ - self.tones = tones - self.category_id = category_id - self.category_name = category_name - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ToneCategory': - """Initialize a ToneCategory object from a json dictionary.""" - args = {} - if 'tones' in _dict: - args['tones'] = [ToneScore.from_dict(x) for x in _dict.get('tones')] - else: - raise ValueError( - 'Required property \'tones\' not present in ToneCategory JSON') - if 'category_id' in _dict: - args['category_id'] = _dict.get('category_id') - else: - raise ValueError( - 'Required property \'category_id\' not present in ToneCategory JSON' - ) - if 'category_name' in _dict: - args['category_name'] = _dict.get('category_name') - else: - raise ValueError( - 'Required property \'category_name\' not present in ToneCategory JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ToneCategory 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, 'tones') and self.tones is not None: - _dict['tones'] = [x.to_dict() for x in self.tones] - if hasattr(self, 'category_id') and self.category_id is not None: - _dict['category_id'] = self.category_id - if hasattr(self, 'category_name') and self.category_name is not None: - _dict['category_name'] = self.category_name - 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 ToneCategory object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ToneCategory') -> 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: 'ToneCategory') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ToneChatScore(): - """ - The score for an utterance from the input content. - - :attr float score: The score for the tone in the range of 0.5 to 1. A score - greater than 0.75 indicates a high likelihood that the tone is perceived in the - utterance. - :attr str tone_id: The unique, non-localized identifier of the tone for the - results. The service returns results only for tones whose scores meet a minimum - threshold of 0.5. - :attr str tone_name: The user-visible, localized name of the tone. - """ - - def __init__(self, score: float, tone_id: str, tone_name: str) -> None: - """ - Initialize a ToneChatScore object. - - :param float score: The score for the tone in the range of 0.5 to 1. A - score greater than 0.75 indicates a high likelihood that the tone is - perceived in the utterance. - :param str tone_id: The unique, non-localized identifier of the tone for - the results. The service returns results only for tones whose scores meet a - minimum threshold of 0.5. - :param str tone_name: The user-visible, localized name of the tone. - """ - self.score = score - self.tone_id = tone_id - self.tone_name = tone_name - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ToneChatScore': - """Initialize a ToneChatScore object from a json dictionary.""" - args = {} - if 'score' in _dict: - args['score'] = _dict.get('score') - else: - raise ValueError( - 'Required property \'score\' not present in ToneChatScore JSON') - if 'tone_id' in _dict: - args['tone_id'] = _dict.get('tone_id') - else: - raise ValueError( - 'Required property \'tone_id\' not present in ToneChatScore JSON' - ) - if 'tone_name' in _dict: - args['tone_name'] = _dict.get('tone_name') - else: - raise ValueError( - 'Required property \'tone_name\' not present in ToneChatScore JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ToneChatScore 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, 'score') and self.score is not None: - _dict['score'] = self.score - if hasattr(self, 'tone_id') and self.tone_id is not None: - _dict['tone_id'] = self.tone_id - if hasattr(self, 'tone_name') and self.tone_name is not None: - _dict['tone_name'] = self.tone_name - 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 ToneChatScore object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ToneChatScore') -> 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: 'ToneChatScore') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class ToneIdEnum(str, Enum): - """ - The unique, non-localized identifier of the tone for the results. The service - returns results only for tones whose scores meet a minimum threshold of 0.5. - """ - EXCITED = 'excited' - FRUSTRATED = 'frustrated' - IMPOLITE = 'impolite' - POLITE = 'polite' - SAD = 'sad' - SATISFIED = 'satisfied' - SYMPATHETIC = 'sympathetic' - - -class ToneInput(): - """ - Input for the general-purpose endpoint. - - :attr str text: The input content that the service is to analyze. - """ - - def __init__(self, text: str) -> None: - """ - Initialize a ToneInput object. - - :param str text: The input content that the service is to analyze. - """ - self.text = text - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ToneInput': - """Initialize a ToneInput object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in ToneInput JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ToneInput 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, 'text') and self.text is not None: - _dict['text'] = self.text - 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 ToneInput object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ToneInput') -> 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: 'ToneInput') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ToneScore(): - """ - The score for a tone from the input content. - - :attr float score: The score for the tone. - * **`2017-09-21`:** The score that is returned lies in the range of 0.5 to 1. A - score greater than 0.75 indicates a high likelihood that the tone is perceived - in the content. - * **`2016-05-19`:** The score that is returned lies in the range of 0 to 1. A - score less than 0.5 indicates that the tone is unlikely to be perceived in the - content; a score greater than 0.75 indicates a high likelihood that the tone is - perceived. - :attr str tone_id: The unique, non-localized identifier of the tone. - * **`2017-09-21`:** The service can return results for the following tone IDs: - `anger`, `fear`, `joy`, and `sadness` (emotional tones); `analytical`, - `confident`, and `tentative` (language tones). The service returns results only - for tones whose scores meet a minimum threshold of 0.5. - * **`2016-05-19`:** The service can return results for the following tone IDs of - the different categories: for the `emotion` category: `anger`, `disgust`, - `fear`, `joy`, and `sadness`; for the `language` category: `analytical`, - `confident`, and `tentative`; for the `social` category: `openness_big5`, - `conscientiousness_big5`, `extraversion_big5`, `agreeableness_big5`, and - `emotional_range_big5`. The service returns scores for all tones of a category, - regardless of their values. - :attr str tone_name: The user-visible, localized name of the tone. - """ - - def __init__(self, score: float, tone_id: str, tone_name: str) -> None: - """ - Initialize a ToneScore object. - - :param float score: The score for the tone. - * **`2017-09-21`:** The score that is returned lies in the range of 0.5 to - 1. A score greater than 0.75 indicates a high likelihood that the tone is - perceived in the content. - * **`2016-05-19`:** The score that is returned lies in the range of 0 to 1. - A score less than 0.5 indicates that the tone is unlikely to be perceived - in the content; a score greater than 0.75 indicates a high likelihood that - the tone is perceived. - :param str tone_id: The unique, non-localized identifier of the tone. - * **`2017-09-21`:** The service can return results for the following tone - IDs: `anger`, `fear`, `joy`, and `sadness` (emotional tones); `analytical`, - `confident`, and `tentative` (language tones). The service returns results - only for tones whose scores meet a minimum threshold of 0.5. - * **`2016-05-19`:** The service can return results for the following tone - IDs of the different categories: for the `emotion` category: `anger`, - `disgust`, `fear`, `joy`, and `sadness`; for the `language` category: - `analytical`, `confident`, and `tentative`; for the `social` category: - `openness_big5`, `conscientiousness_big5`, `extraversion_big5`, - `agreeableness_big5`, and `emotional_range_big5`. The service returns - scores for all tones of a category, regardless of their values. - :param str tone_name: The user-visible, localized name of the tone. - """ - self.score = score - self.tone_id = tone_id - self.tone_name = tone_name - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ToneScore': - """Initialize a ToneScore object from a json dictionary.""" - args = {} - if 'score' in _dict: - args['score'] = _dict.get('score') - else: - raise ValueError( - 'Required property \'score\' not present in ToneScore JSON') - if 'tone_id' in _dict: - args['tone_id'] = _dict.get('tone_id') - else: - raise ValueError( - 'Required property \'tone_id\' not present in ToneScore JSON') - if 'tone_name' in _dict: - args['tone_name'] = _dict.get('tone_name') - else: - raise ValueError( - 'Required property \'tone_name\' not present in ToneScore JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ToneScore 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, 'score') and self.score is not None: - _dict['score'] = self.score - if hasattr(self, 'tone_id') and self.tone_id is not None: - _dict['tone_id'] = self.tone_id - if hasattr(self, 'tone_name') and self.tone_name is not None: - _dict['tone_name'] = self.tone_name - 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 ToneScore object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ToneScore') -> 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: 'ToneScore') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Utterance(): - """ - An utterance for the input of the general-purpose endpoint. - - :attr str text: An utterance contributed by a user in the conversation that is - to be analyzed. The utterance can contain multiple sentences. - :attr str user: (optional) A string that identifies the user who contributed the - utterance specified by the `text` parameter. - """ - - def __init__(self, text: str, *, user: str = None) -> None: - """ - Initialize a Utterance object. - - :param str text: An utterance contributed by a user in the conversation - that is to be analyzed. The utterance can contain multiple sentences. - :param str user: (optional) A string that identifies the user who - contributed the utterance specified by the `text` parameter. - """ - self.text = text - self.user = user - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Utterance': - """Initialize a Utterance object from a json dictionary.""" - args = {} - if 'text' in _dict: - args['text'] = _dict.get('text') - else: - raise ValueError( - 'Required property \'text\' not present in Utterance JSON') - if 'user' in _dict: - args['user'] = _dict.get('user') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Utterance 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, 'text') and self.text is not None: - _dict['text'] = self.text - if hasattr(self, 'user') and self.user is not None: - _dict['user'] = self.user - 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 Utterance object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Utterance') -> 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: 'Utterance') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class UtteranceAnalyses(): - """ - The results of the analysis for the utterances of the input content. - - :attr List[UtteranceAnalysis] utterances_tone: An array of `UtteranceAnalysis` - objects that provides the results for each utterance of the input. - :attr str warning: (optional) **`2017-09-21`:** A warning message if the content - contains more than 50 utterances. The service analyzes only the first 50 - utterances. **`2016-05-19`:** Not returned. - """ - - def __init__(self, - utterances_tone: List['UtteranceAnalysis'], - *, - warning: str = None) -> None: - """ - Initialize a UtteranceAnalyses object. - - :param List[UtteranceAnalysis] utterances_tone: An array of - `UtteranceAnalysis` objects that provides the results for each utterance of - the input. - :param str warning: (optional) **`2017-09-21`:** A warning message if the - content contains more than 50 utterances. The service analyzes only the - first 50 utterances. **`2016-05-19`:** Not returned. - """ - self.utterances_tone = utterances_tone - self.warning = warning - - @classmethod - def from_dict(cls, _dict: Dict) -> 'UtteranceAnalyses': - """Initialize a UtteranceAnalyses object from a json dictionary.""" - args = {} - if 'utterances_tone' in _dict: - args['utterances_tone'] = [ - UtteranceAnalysis.from_dict(x) - for x in _dict.get('utterances_tone') - ] - else: - raise ValueError( - 'Required property \'utterances_tone\' not present in UtteranceAnalyses JSON' - ) - if 'warning' in _dict: - args['warning'] = _dict.get('warning') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a UtteranceAnalyses 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, - 'utterances_tone') and self.utterances_tone is not None: - _dict['utterances_tone'] = [ - x.to_dict() for x in self.utterances_tone - ] - if hasattr(self, 'warning') and self.warning is not None: - _dict['warning'] = self.warning - 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 UtteranceAnalyses object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'UtteranceAnalyses') -> 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: 'UtteranceAnalyses') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class UtteranceAnalysis(): - """ - The results of the analysis for an utterance of the input content. - - :attr int utterance_id: The unique identifier of the utterance. The first - utterance has ID 0, and the ID of each subsequent utterance is incremented by - one. - :attr str utterance_text: The text of the utterance. - :attr List[ToneChatScore] tones: An array of `ToneChatScore` objects that - provides results for the most prevalent tones of the utterance. The array - includes results for any tone whose score is at least 0.5. The array is empty if - no tone has a score that meets this threshold. - :attr str error: (optional) **`2017-09-21`:** An error message if the utterance - contains more than 500 characters. The service does not analyze the utterance. - **`2016-05-19`:** Not returned. - """ - - def __init__(self, - utterance_id: int, - utterance_text: str, - tones: List['ToneChatScore'], - *, - error: str = None) -> None: - """ - Initialize a UtteranceAnalysis object. - - :param int utterance_id: The unique identifier of the utterance. The first - utterance has ID 0, and the ID of each subsequent utterance is incremented - by one. - :param str utterance_text: The text of the utterance. - :param List[ToneChatScore] tones: An array of `ToneChatScore` objects that - provides results for the most prevalent tones of the utterance. The array - includes results for any tone whose score is at least 0.5. The array is - empty if no tone has a score that meets this threshold. - :param str error: (optional) **`2017-09-21`:** An error message if the - utterance contains more than 500 characters. The service does not analyze - the utterance. **`2016-05-19`:** Not returned. - """ - self.utterance_id = utterance_id - self.utterance_text = utterance_text - self.tones = tones - self.error = error - - @classmethod - def from_dict(cls, _dict: Dict) -> 'UtteranceAnalysis': - """Initialize a UtteranceAnalysis object from a json dictionary.""" - args = {} - if 'utterance_id' in _dict: - args['utterance_id'] = _dict.get('utterance_id') - else: - raise ValueError( - 'Required property \'utterance_id\' not present in UtteranceAnalysis JSON' - ) - if 'utterance_text' in _dict: - args['utterance_text'] = _dict.get('utterance_text') - else: - raise ValueError( - 'Required property \'utterance_text\' not present in UtteranceAnalysis JSON' - ) - if 'tones' in _dict: - args['tones'] = [ - ToneChatScore.from_dict(x) for x in _dict.get('tones') - ] - else: - raise ValueError( - 'Required property \'tones\' not present in UtteranceAnalysis JSON' - ) - if 'error' in _dict: - args['error'] = _dict.get('error') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a UtteranceAnalysis 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, 'utterance_id') and self.utterance_id is not None: - _dict['utterance_id'] = self.utterance_id - if hasattr(self, 'utterance_text') and self.utterance_text is not None: - _dict['utterance_text'] = self.utterance_text - if hasattr(self, 'tones') and self.tones is not None: - _dict['tones'] = [x.to_dict() for x in self.tones] - if hasattr(self, 'error') and self.error is not None: - _dict['error'] = self.error - 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 UtteranceAnalysis object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'UtteranceAnalysis') -> 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: 'UtteranceAnalysis') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py deleted file mode 100644 index 431a379a5..000000000 --- a/ibm_watson/visual_recognition_v3.py +++ /dev/null @@ -1,1425 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2016, 2020. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 -""" -IBM Watson™ Visual Recognition is discontinued. Existing instances are supported -until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance -that is provisioned on 1 December 2021 will be deleted. -{: deprecated} -The IBM Watson Visual Recognition service uses deep learning algorithms to identify scenes -and objects in images that you upload to the service. You can create and train a custom -classifier to identify subjects that suit your needs. - -API Version: 3.0 -See: https://cloud.ibm.com/docs/visual-recognition -""" - -from datetime import datetime -from enum import Enum -from os.path import basename -from typing import BinaryIO, Dict, List -import json - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import datetime_to_string, string_to_datetime - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class VisualRecognitionV3(BaseService): - """The Visual Recognition V3 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'visual_recognition' - - def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Visual Recognition service. - - :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2018-03-19`. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md - about initializing the authenticator of your choice. - """ - print( - 'warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#visual-recognition-deprecation.' - ) - if version is None: - raise ValueError('version must be provided') - - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.version = version - self.configure_service(service_name) - - ######################### - # General - ######################### - - def classify(self, - *, - images_file: BinaryIO = None, - images_filename: str = None, - images_file_content_type: str = None, - url: str = None, - threshold: float = None, - owners: List[str] = None, - classifier_ids: List[str] = None, - accept_language: str = None, - **kwargs) -> DetailedResponse: - """ - Classify images. - - Classify images with built-in or custom classifiers. - - :param BinaryIO images_file: (optional) An image file (.gif, .jpg, .png, - .tif) or .zip file with images. Maximum image size is 10 MB. Include no - more than 20 images and limit the .zip file to 100 MB. Encode the image and - .zip file names in UTF-8 if they contain non-ASCII characters. The service - assumes UTF-8 encoding if it encounters non-ASCII characters. - You can also include an image with the **url** parameter. - :param str images_filename: (optional) The filename for images_file. - :param str images_file_content_type: (optional) The content type of - images_file. - :param str url: (optional) The URL of an image (.gif, .jpg, .png, .tif) to - analyze. The minimum recommended pixel density is 32X32 pixels, but the - service tends to perform better with images that are at least 224 x 224 - pixels. The maximum image size is 10 MB. - You can also include images with the **images_file** parameter. - :param float threshold: (optional) The minimum score a class must have to - be displayed in the response. Set the threshold to `0.0` to return all - identified classes. - :param List[str] owners: (optional) The categories of classifiers to apply. - The **classifier_ids** parameter overrides **owners**, so make sure that - **classifier_ids** is empty. - - Use `IBM` to classify against the `default` general classifier. You get - the same result if both **classifier_ids** and **owners** parameters are - empty. - - Use `me` to classify against all your custom classifiers. However, for - better performance use **classifier_ids** to specify the specific custom - classifiers to apply. - - Use both `IBM` and `me` to analyze the image against both classifier - categories. - :param List[str] classifier_ids: (optional) Which classifiers to apply. - Overrides the **owners** parameter. You can specify both custom and - built-in classifier IDs. The built-in `default` classifier is used if both - **classifier_ids** and **owners** parameters are empty. - The following built-in classifier IDs require no training: - - `default`: Returns classes from thousands of general tags. - - `food`: Enhances specificity and accuracy for images of food items. - - `explicit`: Evaluates whether the image might be pornographic. - :param str accept_language: (optional) The desired language of parts of the - response. See the response for details. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ClassifiedImages` object - """ - - headers = {'Accept-Language': accept_language} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='classify') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - if images_file: - if not images_filename and hasattr(images_file, 'name'): - images_filename = basename(images_file.name) - if not images_filename: - raise ValueError('images_filename must be provided') - form_data.append(('images_file', (images_filename, images_file, - images_file_content_type or - 'application/octet-stream'))) - if url: - form_data.append(('url', (None, url, 'text/plain'))) - if threshold: - form_data.append( - ('threshold', (None, str(threshold), 'text/plain'))) - if owners: - owners = self._convert_list(owners) - form_data.append(('owners', (None, owners, 'text/plain'))) - if classifier_ids: - classifier_ids = self._convert_list(classifier_ids) - form_data.append( - ('classifier_ids', (None, classifier_ids, 'text/plain'))) - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/classify' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - ######################### - # Custom - ######################### - - def create_classifier(self, - name: str, - positive_examples: Dict[str, BinaryIO], - *, - negative_examples: BinaryIO = None, - negative_examples_filename: str = None, - **kwargs) -> DetailedResponse: - """ - Create a classifier. - - Train a new multi-faceted classifier on the uploaded image data. Create your - custom classifier with positive or negative example training images. Include at - least two sets of examples, either two positive example files or one positive and - one negative file. You can upload a maximum of 256 MB per call. - **Tips when creating:** - - If you set the **X-Watson-Learning-Opt-Out** header parameter to `true` when you - create a classifier, the example training images are not stored. Save your - training images locally. For more information, see [Data - collection](#data-collection). - - 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. - - :param str name: The name of the new classifier. Encode special characters - in UTF-8. - :param dict positive_examples: A dictionary that contains the value for - each classname. The value is a .zip file of images that depict the visual - subject of a class in the new classifier. You can include more than one - positive example file in a call. - Specify the parameter name by appending `_positive_examples` to the class - name. For example, `goldenretriever_positive_examples` creates the class - **goldenretriever**. The string cannot contain the following characters: - ``$ * - { } \ | / ' " ` [ ]``. - Include at least 10 images in .jpg or .png format. The minimum recommended - image resolution is 32X32 pixels. The maximum number of images is 10,000 - images or 100 MB per .zip file. - Encode special characters in the file name in UTF-8. - :param BinaryIO negative_examples: (optional) A .zip file of images that do - not depict the visual subject of any of the classes of the new classifier. - Must contain a minimum of 10 images. - Encode special characters in the file name in UTF-8. - :param str negative_examples_filename: (optional) The filename for - negative_examples. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Classifier` object - """ - - if name is None: - raise ValueError('name must be provided') - if not positive_examples: - raise ValueError('positive_examples must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='create_classifier') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - form_data.append(('name', (None, name, 'text/plain'))) - for key in positive_examples.keys(): - part_name = '%s_positive_examples' % (key) - value = positive_examples[key] - filename = None - if hasattr(value, 'name'): - filename = basename(value.name) - form_data.append( - (part_name, (filename, value, 'application/octet-stream'))) - if negative_examples: - if not negative_examples_filename and hasattr( - negative_examples, 'name'): - negative_examples_filename = basename(negative_examples.name) - if not negative_examples_filename: - raise ValueError('negative_examples_filename must be provided') - form_data.append(('negative_examples', - (negative_examples_filename, negative_examples, - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/classifiers' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def list_classifiers(self, - *, - verbose: bool = None, - **kwargs) -> DetailedResponse: - """ - Retrieve a list of classifiers. - - :param bool verbose: (optional) Specify `true` to return details about the - classifiers. Omit this parameter to return a brief list of classifiers. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Classifiers` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='list_classifiers') - headers.update(sdk_headers) - - params = {'version': self.version, 'verbose': verbose} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/classifiers' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_classifier(self, classifier_id: str, **kwargs) -> DetailedResponse: - """ - Retrieve classifier details. - - Retrieve information about a custom classifier. - - :param str classifier_id: The ID of the classifier. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Classifier` object - """ - - if classifier_id is None: - raise ValueError('classifier_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_classifier') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['classifier_id'] - path_param_values = self.encode_path_vars(classifier_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/classifiers/{classifier_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_classifier(self, - classifier_id: str, - *, - positive_examples: Dict[str, BinaryIO] = {}, - negative_examples: BinaryIO = None, - negative_examples_filename: str = None, - **kwargs) -> DetailedResponse: - """ - Update a classifier. - - 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/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. - **Tips about retraining:** - - You can't update the classifier if the **X-Watson-Learning-Opt-Out** header - parameter was set to `true` when the classifier was created. Training images are - not stored in that case. Instead, create another classifier. For more information, - see [Data collection](#data-collection). - - Don't make retraining calls on a classifier until the status is ready. When you - submit retraining requests in parallel, the last request overwrites the previous - requests. The `retrained` property shows the last time the classifier retraining - finished. - - :param str classifier_id: The ID of the classifier. - :param dict positive_examples: (optional) A dictionary that contains the - value for each classname. The value is a .zip file of images that depict - the visual subject of a class in the classifier. The positive examples - create or update classes in the classifier. You can include more than one - positive example file in a call. - Specify the parameter name by appending `_positive_examples` to the class - name. For example, `goldenretriever_positive_examples` creates the class - `goldenretriever`. The string cannot contain the following characters: ``$ - * - { } \ | / ' " ` [ ]``. - Include at least 10 images in .jpg or .png format. The minimum recommended - image resolution is 32X32 pixels. The maximum number of images is 10,000 - images or 100 MB per .zip file. - Encode special characters in the file name in UTF-8. - :param BinaryIO negative_examples: (optional) A .zip file of images that do - not depict the visual subject of any of the classes of the new classifier. - Must contain a minimum of 10 images. - Encode special characters in the file name in UTF-8. - :param str negative_examples_filename: (optional) The filename for - negative_examples. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Classifier` object - """ - - if classifier_id is None: - raise ValueError('classifier_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='update_classifier') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - for key in positive_examples.keys(): - part_name = '%s_positive_examples' % (key) - value = positive_examples[key] - filename = None - if hasattr(value, 'name'): - filename = basename(value.name) - form_data.append( - (part_name, (filename, value, 'application/octet-stream'))) - if negative_examples: - if not negative_examples_filename and hasattr( - negative_examples, 'name'): - negative_examples_filename = basename(negative_examples.name) - if not negative_examples_filename: - raise ValueError('negative_examples_filename must be provided') - form_data.append(('negative_examples', - (negative_examples_filename, negative_examples, - 'application/octet-stream'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['classifier_id'] - path_param_values = self.encode_path_vars(classifier_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/classifiers/{classifier_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def delete_classifier(self, classifier_id: str, - **kwargs) -> DetailedResponse: - """ - Delete a classifier. - - :param str classifier_id: The ID of the classifier. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if classifier_id is None: - raise ValueError('classifier_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_classifier') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['classifier_id'] - path_param_values = self.encode_path_vars(classifier_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/classifiers/{classifier_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Core ML - ######################### - - def get_core_ml_model(self, classifier_id: str, - **kwargs) -> DetailedResponse: - """ - Retrieve a Core ML model of a classifier. - - Download a Core ML model file (.mlmodel) of a custom classifier that returns - "core_ml_enabled": true in the classifier details. - - :param str classifier_id: The ID of the classifier. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `BinaryIO` result - """ - - if classifier_id is None: - raise ValueError('classifier_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='get_core_ml_model') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/octet-stream' - - path_param_keys = ['classifier_id'] - path_param_values = self.encode_path_vars(classifier_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v3/classifiers/{classifier_id}/core_ml_model'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # User data - ######################### - - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: - """ - Delete labeled data. - - Deletes all data associated with a specified customer ID. The method has no effect - if no data is associated with the customer ID. - 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/visual-recognition?topic=visual-recognition-information-security). - - :param str customer_id: The customer ID for which all data is to be - deleted. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if customer_id is None: - raise ValueError('customer_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V3', - operation_id='delete_user_data') - headers.update(sdk_headers) - - params = {'version': self.version, 'customer_id': customer_id} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v3/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - -class ClassifyEnums: - """ - Enums for classify parameters. - """ - - class AcceptLanguage(str, Enum): - """ - The desired language of parts of the response. See the response for details. - """ - EN = 'en' - AR = 'ar' - DE = 'de' - ES = 'es' - FR = 'fr' - IT = 'it' - JA = 'ja' - KO = 'ko' - PT_BR = 'pt-br' - ZH_CN = 'zh-cn' - ZH_TW = 'zh-tw' - - -############################################################################## -# Models -############################################################################## - - -class Class(): - """ - A category within a classifier. - - :attr str class_: The name of the class. - """ - - def __init__(self, class_: str) -> None: - """ - Initialize a Class object. - - :param str class_: The name of the class. - """ - self.class_ = class_ - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Class': - """Initialize a Class object from a json dictionary.""" - args = {} - if 'class' in _dict: - args['class_'] = _dict.get('class') - else: - raise ValueError( - 'Required property \'class\' not present in Class JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Class 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, 'class_') and self.class_ is not None: - _dict['class'] = self.class_ - 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 Class object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Class') -> 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: 'Class') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ClassResult(): - """ - Result of a class within a classifier. - - :attr str class_: Name of the class. - Class names are translated in the language defined by the **Accept-Language** - request header for the build-in classifier IDs (`default`, `food`, and - `explicit`). Class names of custom classifiers are not translated. The response - might not be in the specified language when the requested language is not - supported or when there is no translation for the class name. - :attr float score: Confidence score for the property in the range of 0 to 1. A - higher score indicates greater likelihood that the class is depicted in the - image. The default threshold for returning scores from a classifier is 0.5. - :attr str type_hierarchy: (optional) Knowledge graph of the property. For - example, `/fruit/pome/apple/eating apple/Granny Smith`. Included only if - identified. - """ - - def __init__(self, - class_: str, - score: float, - *, - type_hierarchy: str = None) -> None: - """ - Initialize a ClassResult object. - - :param str class_: Name of the class. - Class names are translated in the language defined by the - **Accept-Language** request header for the build-in classifier IDs - (`default`, `food`, and `explicit`). Class names of custom classifiers are - not translated. The response might not be in the specified language when - the requested language is not supported or when there is no translation for - the class name. - :param float score: Confidence score for the property in the range of 0 to - 1. A higher score indicates greater likelihood that the class is depicted - in the image. The default threshold for returning scores from a classifier - is 0.5. - :param str type_hierarchy: (optional) Knowledge graph of the property. For - example, `/fruit/pome/apple/eating apple/Granny Smith`. Included only if - identified. - """ - self.class_ = class_ - self.score = score - self.type_hierarchy = type_hierarchy - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ClassResult': - """Initialize a ClassResult object from a json dictionary.""" - args = {} - if 'class' in _dict: - args['class_'] = _dict.get('class') - else: - raise ValueError( - 'Required property \'class\' not present in ClassResult JSON') - if 'score' in _dict: - args['score'] = _dict.get('score') - else: - raise ValueError( - 'Required property \'score\' not present in ClassResult JSON') - if 'type_hierarchy' in _dict: - args['type_hierarchy'] = _dict.get('type_hierarchy') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ClassResult 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, 'class_') and self.class_ is not None: - _dict['class'] = self.class_ - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score - if hasattr(self, 'type_hierarchy') and self.type_hierarchy is not None: - _dict['type_hierarchy'] = self.type_hierarchy - 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 ClassResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ClassResult') -> 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: 'ClassResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ClassifiedImage(): - """ - Results for one image. - - :attr str source_url: (optional) Source of the image before any redirects. Not - returned when the image is uploaded. - :attr str resolved_url: (optional) Fully resolved URL of the image after - redirects are followed. Not returned when the image is uploaded. - :attr str image: (optional) Relative path of the image file if uploaded - directly. Not returned when the image is passed by URL. - :attr ErrorInfo error: (optional) Information about what might have caused a - failure, such as an image that is too large. Not returned when there is no - error. - :attr List[ClassifierResult] classifiers: The classifiers. - """ - - def __init__(self, - classifiers: List['ClassifierResult'], - *, - source_url: str = None, - resolved_url: str = None, - image: str = None, - error: 'ErrorInfo' = None) -> None: - """ - Initialize a ClassifiedImage object. - - :param List[ClassifierResult] classifiers: The classifiers. - :param str source_url: (optional) Source of the image before any redirects. - Not returned when the image is uploaded. - :param str resolved_url: (optional) Fully resolved URL of the image after - redirects are followed. Not returned when the image is uploaded. - :param str image: (optional) Relative path of the image file if uploaded - directly. Not returned when the image is passed by URL. - :param ErrorInfo error: (optional) Information about what might have caused - a failure, such as an image that is too large. Not returned when there is - no error. - """ - self.source_url = source_url - self.resolved_url = resolved_url - self.image = image - self.error = error - self.classifiers = classifiers - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ClassifiedImage': - """Initialize a ClassifiedImage object from a json dictionary.""" - args = {} - if 'source_url' in _dict: - args['source_url'] = _dict.get('source_url') - if 'resolved_url' in _dict: - args['resolved_url'] = _dict.get('resolved_url') - if 'image' in _dict: - args['image'] = _dict.get('image') - if 'error' in _dict: - args['error'] = ErrorInfo.from_dict(_dict.get('error')) - if 'classifiers' in _dict: - args['classifiers'] = [ - ClassifierResult.from_dict(x) for x in _dict.get('classifiers') - ] - else: - raise ValueError( - 'Required property \'classifiers\' not present in ClassifiedImage JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ClassifiedImage 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, 'source_url') and self.source_url is not None: - _dict['source_url'] = self.source_url - if hasattr(self, 'resolved_url') and self.resolved_url is not None: - _dict['resolved_url'] = self.resolved_url - if hasattr(self, 'image') and self.image is not None: - _dict['image'] = self.image - if hasattr(self, 'error') and self.error is not None: - _dict['error'] = self.error.to_dict() - if hasattr(self, 'classifiers') and self.classifiers is not None: - _dict['classifiers'] = [x.to_dict() for x in self.classifiers] - 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 ClassifiedImage object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ClassifiedImage') -> 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: 'ClassifiedImage') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ClassifiedImages(): - """ - Results for all images. - - :attr int custom_classes: (optional) Number of custom classes identified in the - images. - :attr int images_processed: (optional) Number of images processed for the API - call. - :attr List[ClassifiedImage] images: Classified images. - :attr List[WarningInfo] warnings: (optional) Information about what might cause - less than optimal output. For example, a request sent with a corrupt .zip file - and a list of image URLs will still complete, but does not return the expected - output. Not returned when there is no warning. - """ - - def __init__(self, - images: List['ClassifiedImage'], - *, - custom_classes: int = None, - images_processed: int = None, - warnings: List['WarningInfo'] = None) -> None: - """ - Initialize a ClassifiedImages object. - - :param List[ClassifiedImage] images: Classified images. - :param int custom_classes: (optional) Number of custom classes identified - in the images. - :param int images_processed: (optional) Number of images processed for the - API call. - :param List[WarningInfo] warnings: (optional) Information about what might - cause less than optimal output. For example, a request sent with a corrupt - .zip file and a list of image URLs will still complete, but does not return - the expected output. Not returned when there is no warning. - """ - self.custom_classes = custom_classes - self.images_processed = images_processed - self.images = images - self.warnings = warnings - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ClassifiedImages': - """Initialize a ClassifiedImages object from a json dictionary.""" - args = {} - if 'custom_classes' in _dict: - args['custom_classes'] = _dict.get('custom_classes') - if 'images_processed' in _dict: - args['images_processed'] = _dict.get('images_processed') - if 'images' in _dict: - args['images'] = [ - ClassifiedImage.from_dict(x) for x in _dict.get('images') - ] - else: - raise ValueError( - 'Required property \'images\' not present in ClassifiedImages JSON' - ) - if 'warnings' in _dict: - args['warnings'] = [ - WarningInfo.from_dict(x) for x in _dict.get('warnings') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ClassifiedImages 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, 'custom_classes') and self.custom_classes is not None: - _dict['custom_classes'] = self.custom_classes - if hasattr(self, - 'images_processed') and self.images_processed is not None: - _dict['images_processed'] = self.images_processed - if hasattr(self, 'images') and self.images is not None: - _dict['images'] = [x.to_dict() for x in self.images] - if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x.to_dict() for x in self.warnings] - 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 ClassifiedImages object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ClassifiedImages') -> 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: 'ClassifiedImages') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Classifier(): - """ - Information about a classifier. - - :attr str classifier_id: ID of a classifier identified in the image. - :attr str name: Name of the classifier. - :attr str owner: (optional) Unique ID of the account who owns the classifier. - Might not be returned by some requests. - :attr str status: (optional) Training status of classifier. - :attr bool core_ml_enabled: (optional) Whether the classifier can be downloaded - as a Core ML model after the training status is `ready`. - :attr str explanation: (optional) If classifier training has failed, this field - might explain why. - :attr datetime created: (optional) Date and time in Coordinated Universal Time - (UTC) that the classifier was created. - :attr List[Class] classes: (optional) Classes that define a classifier. - :attr datetime retrained: (optional) Date and time in Coordinated Universal Time - (UTC) that the classifier was updated. Might not be returned by some requests. - Identical to `updated` and retained for backward compatibility. - :attr datetime updated: (optional) Date and time in Coordinated Universal Time - (UTC) that the classifier was most recently updated. The field matches either - `retrained` or `created`. Might not be returned by some requests. - """ - - def __init__(self, - classifier_id: str, - name: str, - *, - owner: str = None, - status: str = None, - core_ml_enabled: bool = None, - explanation: str = None, - created: datetime = None, - classes: List['Class'] = None, - retrained: datetime = None, - updated: datetime = None) -> None: - """ - Initialize a Classifier object. - - :param str classifier_id: ID of a classifier identified in the image. - :param str name: Name of the classifier. - :param str owner: (optional) Unique ID of the account who owns the - classifier. Might not be returned by some requests. - :param str status: (optional) Training status of classifier. - :param bool core_ml_enabled: (optional) Whether the classifier can be - downloaded as a Core ML model after the training status is `ready`. - :param str explanation: (optional) If classifier training has failed, this - field might explain why. - :param datetime created: (optional) Date and time in Coordinated Universal - Time (UTC) that the classifier was created. - :param List[Class] classes: (optional) Classes that define a classifier. - :param datetime retrained: (optional) Date and time in Coordinated - Universal Time (UTC) that the classifier was updated. Might not be returned - by some requests. Identical to `updated` and retained for backward - compatibility. - :param datetime updated: (optional) Date and time in Coordinated Universal - Time (UTC) that the classifier was most recently updated. The field matches - either `retrained` or `created`. Might not be returned by some requests. - """ - self.classifier_id = classifier_id - self.name = name - self.owner = owner - self.status = status - self.core_ml_enabled = core_ml_enabled - self.explanation = explanation - self.created = created - self.classes = classes - self.retrained = retrained - self.updated = updated - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Classifier': - """Initialize a Classifier object from a json dictionary.""" - args = {} - if 'classifier_id' in _dict: - args['classifier_id'] = _dict.get('classifier_id') - else: - raise ValueError( - 'Required property \'classifier_id\' not present in Classifier JSON' - ) - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in Classifier JSON') - if 'owner' in _dict: - args['owner'] = _dict.get('owner') - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'core_ml_enabled' in _dict: - args['core_ml_enabled'] = _dict.get('core_ml_enabled') - if 'explanation' in _dict: - args['explanation'] = _dict.get('explanation') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'classes' in _dict: - args['classes'] = [Class.from_dict(x) for x in _dict.get('classes')] - if 'retrained' in _dict: - args['retrained'] = string_to_datetime(_dict.get('retrained')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Classifier 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, 'classifier_id') and self.classifier_id is not None: - _dict['classifier_id'] = self.classifier_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'owner') and self.owner is not None: - _dict['owner'] = self.owner - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, - 'core_ml_enabled') and self.core_ml_enabled is not None: - _dict['core_ml_enabled'] = self.core_ml_enabled - if hasattr(self, 'explanation') and self.explanation is not None: - _dict['explanation'] = self.explanation - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'classes') and self.classes is not None: - _dict['classes'] = [x.to_dict() for x in self.classes] - if hasattr(self, 'retrained') and self.retrained is not None: - _dict['retrained'] = datetime_to_string(self.retrained) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) - 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 Classifier object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Classifier') -> 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: 'Classifier') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class StatusEnum(str, Enum): - """ - Training status of classifier. - """ - READY = 'ready' - TRAINING = 'training' - RETRAINING = 'retraining' - FAILED = 'failed' - - -class ClassifierResult(): - """ - Classifier and score combination. - - :attr str name: Name of the classifier. - :attr str classifier_id: ID of a classifier identified in the image. - :attr List[ClassResult] classes: Classes within the classifier. - """ - - def __init__(self, name: str, classifier_id: str, - classes: List['ClassResult']) -> None: - """ - Initialize a ClassifierResult object. - - :param str name: Name of the classifier. - :param str classifier_id: ID of a classifier identified in the image. - :param List[ClassResult] classes: Classes within the classifier. - """ - self.name = name - self.classifier_id = classifier_id - self.classes = classes - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ClassifierResult': - """Initialize a ClassifierResult object from a json dictionary.""" - args = {} - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in ClassifierResult JSON' - ) - if 'classifier_id' in _dict: - args['classifier_id'] = _dict.get('classifier_id') - else: - raise ValueError( - 'Required property \'classifier_id\' not present in ClassifierResult JSON' - ) - if 'classes' in _dict: - args['classes'] = [ - ClassResult.from_dict(x) for x in _dict.get('classes') - ] - else: - raise ValueError( - 'Required property \'classes\' not present in ClassifierResult JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ClassifierResult 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, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'classifier_id') and self.classifier_id is not None: - _dict['classifier_id'] = self.classifier_id - if hasattr(self, 'classes') and self.classes is not None: - _dict['classes'] = [x.to_dict() for x in self.classes] - 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 ClassifierResult object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ClassifierResult') -> 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: 'ClassifierResult') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Classifiers(): - """ - A container for the list of classifiers. - - :attr List[Classifier] classifiers: List of classifiers. - """ - - def __init__(self, classifiers: List['Classifier']) -> None: - """ - Initialize a Classifiers object. - - :param List[Classifier] classifiers: List of classifiers. - """ - self.classifiers = classifiers - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Classifiers': - """Initialize a Classifiers object from a json dictionary.""" - args = {} - if 'classifiers' in _dict: - args['classifiers'] = [ - Classifier.from_dict(x) for x in _dict.get('classifiers') - ] - else: - raise ValueError( - 'Required property \'classifiers\' not present in Classifiers JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Classifiers 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, 'classifiers') and self.classifiers is not None: - _dict['classifiers'] = [x.to_dict() for x in self.classifiers] - 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 Classifiers object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Classifiers') -> 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: 'Classifiers') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ErrorInfo(): - """ - Information about what might have caused a failure, such as an image that is too - large. Not returned when there is no error. - - :attr int code: HTTP status code. - :attr str description: Human-readable error description. For example, `File size - limit exceeded`. - :attr str error_id: Codified error string. For example, `limit_exceeded`. - """ - - def __init__(self, code: int, description: str, error_id: str) -> None: - """ - Initialize a ErrorInfo object. - - :param int code: HTTP status code. - :param str description: Human-readable error description. For example, - `File size limit exceeded`. - :param str error_id: Codified error string. For example, `limit_exceeded`. - """ - self.code = code - self.description = description - self.error_id = error_id - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ErrorInfo': - """Initialize a ErrorInfo object from a json dictionary.""" - args = {} - if 'code' in _dict: - args['code'] = _dict.get('code') - else: - raise ValueError( - 'Required property \'code\' not present in ErrorInfo JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - else: - raise ValueError( - 'Required property \'description\' not present in ErrorInfo JSON' - ) - if 'error_id' in _dict: - args['error_id'] = _dict.get('error_id') - else: - raise ValueError( - 'Required property \'error_id\' not present in ErrorInfo JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ErrorInfo 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, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'error_id') and self.error_id is not None: - _dict['error_id'] = self.error_id - 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 ErrorInfo object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ErrorInfo') -> 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: 'ErrorInfo') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class WarningInfo(): - """ - Information about something that went wrong. - - :attr str warning_id: Codified warning string, such as `limit_reached`. - :attr str description: Information about the error. - """ - - def __init__(self, warning_id: str, description: str) -> None: - """ - Initialize a WarningInfo object. - - :param str warning_id: Codified warning string, such as `limit_reached`. - :param str description: Information about the error. - """ - self.warning_id = warning_id - self.description = description - - @classmethod - def from_dict(cls, _dict: Dict) -> 'WarningInfo': - """Initialize a WarningInfo object from a json dictionary.""" - args = {} - if 'warning_id' in _dict: - args['warning_id'] = _dict.get('warning_id') - else: - raise ValueError( - 'Required property \'warning_id\' not present in WarningInfo JSON' - ) - if 'description' in _dict: - args['description'] = _dict.get('description') - else: - raise ValueError( - 'Required property \'description\' not present in WarningInfo JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a WarningInfo 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, 'warning_id') and self.warning_id is not None: - _dict['warning_id'] = self.warning_id - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - 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 WarningInfo object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'WarningInfo') -> 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: 'WarningInfo') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py deleted file mode 100644 index 0c62cee04..000000000 --- a/ibm_watson/visual_recognition_v4.py +++ /dev/null @@ -1,3541 +0,0 @@ -# coding: utf-8 - -# (C) Copyright IBM Corp. 2019, 2020. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -# IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025 -""" -IBM Watson™ Visual Recognition is discontinued. Existing instances are supported -until 1 December 2021, but as of 7 January 2021, you can't create instances. Any instance -that is provisioned on 1 December 2021 will be deleted. -{: deprecated} -Provide images to the IBM Watson Visual Recognition service for analysis. The service -detects objects based on a set of images with training data. - -API Version: 4.0 -See: https://cloud.ibm.com/docs/visual-recognition?topic=visual-recognition-object-detection-overview -""" - -from datetime import date -from datetime import datetime -from enum import Enum -from typing import BinaryIO, Dict, List -import json - -from ibm_cloud_sdk_core import BaseService, DetailedResponse -from ibm_cloud_sdk_core.authenticators.authenticator import Authenticator -from ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment -from ibm_cloud_sdk_core.utils import convert_model, datetime_to_string, string_to_datetime - -from .common import get_sdk_headers - -############################################################################## -# Service -############################################################################## - - -class VisualRecognitionV4(BaseService): - """The Visual Recognition V4 service.""" - - DEFAULT_SERVICE_URL = 'https://api.us-south.visual-recognition.watson.cloud.ibm.com' - DEFAULT_SERVICE_NAME = 'visual_recognition' - - def __init__( - self, - version: str, - authenticator: Authenticator = None, - service_name: str = DEFAULT_SERVICE_NAME, - ) -> None: - """ - Construct a new client for the Visual Recognition service. - - :param str version: Release date of the API version you want to use. - Specify dates in YYYY-MM-DD format. The current version is `2019-02-11`. - - :param Authenticator authenticator: The authenticator specifies the authentication mechanism. - Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md - about initializing the authenticator of your choice. - """ - print( - 'warning: On 1 December 2021, Visual Recognition will no longer be available. For more information, see https://github.com/watson-developer-cloud/python-sdk/tree/master#visual-recognition-deprecation.' - ) - if version is None: - raise ValueError('version must be provided') - - if not authenticator: - authenticator = get_authenticator_from_environment(service_name) - BaseService.__init__(self, - service_url=self.DEFAULT_SERVICE_URL, - authenticator=authenticator) - self.version = version - self.configure_service(service_name) - - ######################### - # Analysis - ######################### - - def analyze(self, - collection_ids: List[str], - features: List[str], - *, - images_file: List[BinaryIO] = None, - image_url: List[str] = None, - threshold: float = None, - **kwargs) -> DetailedResponse: - """ - Analyze images. - - Analyze images by URL, by file, or both against your own collection. Make sure - that **training_status.objects.ready** is `true` for the feature before you use a - collection to analyze images. - Encode the image and .zip file names in UTF-8 if they contain non-ASCII - characters. The service assumes UTF-8 encoding if it encounters non-ASCII - characters. - - :param List[str] collection_ids: The IDs of the collections to analyze. - :param List[str] features: The features to analyze. - :param list[FileWithMetadata] images_file: (optional) An array of image - files (.jpg or .png) or .zip files with images. - - Include a maximum of 20 images in a request. - - Limit the .zip file to 100 MB. - - Limit each image file to 10 MB. - You can also include an image with the **image_url** parameter. - :param List[str] image_url: (optional) An array of URLs of image files - (.jpg or .png). - - Include a maximum of 20 images in a request. - - Limit each image file to 10 MB. - - Minimum width and height is 30 pixels, but the service tends to perform - better with images that are at least 300 x 300 pixels. Maximum is 5400 - pixels for either height or width. - You can also include images with the **images_file** parameter. - :param float threshold: (optional) The minimum score a feature must have to - be returned. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `AnalyzeResponse` object - """ - - if collection_ids is None: - raise ValueError('collection_ids must be provided') - if features is None: - raise ValueError('features must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='analyze') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - for item in collection_ids: - form_data.append(('collection_ids', (None, item, 'text/plain'))) - for item in features: - form_data.append(('features', (None, item, 'text/plain'))) - if images_file: - for item in images_file: - item = convert_model(item) - _file = (item.get('filename') or None, item['data'], - item.get('content_type') or 'application/octet-stream') - form_data.append(('images_file', _file)) - if image_url: - for item in image_url: - form_data.append(('image_url', (None, item, 'text/plain'))) - if threshold: - form_data.append( - ('threshold', (None, str(threshold), 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v4/analyze' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - ######################### - # Collections - ######################### - - def create_collection(self, - *, - name: str = None, - description: str = None, - training_status: 'TrainingStatus' = None, - **kwargs) -> DetailedResponse: - """ - Create a collection. - - Create a collection that can be used to store images. - To create a collection without specifying a name and description, include an empty - JSON object in the request body. - Encode the name and description in UTF-8 if they contain non-ASCII characters. The - service assumes UTF-8 encoding if it encounters non-ASCII characters. - - :param str name: (optional) The name of the collection. The name can - contain alphanumeric, underscore, hyphen, and dot characters. It cannot - begin with the reserved prefix `sys-`. - :param str description: (optional) The description of the collection. - :param TrainingStatus training_status: (optional) Training status - information for the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Collection` object - """ - - if training_status is not None: - training_status = convert_model(training_status) - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='create_collection') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'name': name, - 'description': description, - 'training_status': training_status - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v4/collections' - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def list_collections(self, **kwargs) -> DetailedResponse: - """ - List collections. - - Retrieves a list of collections for the service instance. - - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `CollectionsList` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='list_collections') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v4/collections' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_collection(self, collection_id: str, **kwargs) -> DetailedResponse: - """ - Get collection details. - - Get details of one 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 with `dict` result representing a `Collection` object - """ - - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='get_collection') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id'] - path_param_values = self.encode_path_vars(collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def update_collection(self, - collection_id: str, - *, - name: str = None, - description: str = None, - training_status: 'TrainingStatus' = None, - **kwargs) -> DetailedResponse: - """ - Update a collection. - - Update the name or description of a collection. - Encode the name and description in UTF-8 if they contain non-ASCII characters. The - service assumes UTF-8 encoding if it encounters non-ASCII characters. - - :param str collection_id: The identifier of the collection. - :param str name: (optional) The name of the collection. The name can - contain alphanumeric, underscore, hyphen, and dot characters. It cannot - begin with the reserved prefix `sys-`. - :param str description: (optional) The description of the collection. - :param TrainingStatus training_status: (optional) Training status - information for the collection. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `Collection` object - """ - - if collection_id is None: - raise ValueError('collection_id must be provided') - if training_status is not None: - training_status = convert_model(training_status) - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='update_collection') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = { - 'name': name, - 'description': description, - 'training_status': training_status - } - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id'] - path_param_values = self.encode_path_vars(collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def delete_collection(self, collection_id: str, - **kwargs) -> DetailedResponse: - """ - Delete a collection. - - Delete a collection from the service instance. - - :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 = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='delete_collection') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id'] - path_param_values = self.encode_path_vars(collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}'.format(**path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_model_file(self, collection_id: str, feature: str, - model_format: str, **kwargs) -> DetailedResponse: - """ - Get a model. - - Download a model that you can deploy to detect objects in images. The collection - must include a generated model, which is indicated in the response for the - collection details as `"rscnn_ready": true`. If the value is `false`, train or - retrain the collection to generate the model. - Currently, the model format is specific to Android apps. For more information - about how to deploy the model to your app, see the [Watson Visual Recognition on - Android](https://github.com/matt-ny/rscnn) project in GitHub. - - :param str collection_id: The identifier of the collection. - :param str feature: The feature for the model. - :param str model_format: The format of the returned model. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `BinaryIO` result - """ - - if collection_id is None: - raise ValueError('collection_id must be provided') - if feature is None: - raise ValueError('feature must be provided') - if model_format is None: - raise ValueError('model_format must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='get_model_file') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'feature': feature, - 'model_format': model_format - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/octet-stream' - - path_param_keys = ['collection_id'] - path_param_values = self.encode_path_vars(collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/model'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Images - ######################### - - def add_images(self, - collection_id: str, - *, - images_file: List[BinaryIO] = None, - image_url: List[str] = None, - training_data: str = None, - **kwargs) -> DetailedResponse: - """ - Add images. - - Add images to a collection by URL, by file, or both. - Encode the image and .zip file names in UTF-8 if they contain non-ASCII - characters. The service assumes UTF-8 encoding if it encounters non-ASCII - characters. - - :param str collection_id: The identifier of the collection. - :param list[FileWithMetadata] images_file: (optional) An array of image - files (.jpg or .png) or .zip files with images. - - Include a maximum of 20 images in a request. - - Limit the .zip file to 100 MB. - - Limit each image file to 10 MB. - You can also include an image with the **image_url** parameter. - :param List[str] image_url: (optional) The array of URLs of image files - (.jpg or .png). - - Include a maximum of 20 images in a request. - - Limit each image file to 10 MB. - - Minimum width and height is 30 pixels, but the service tends to perform - better with images that are at least 300 x 300 pixels. Maximum is 5400 - pixels for either height or width. - You can also include images with the **images_file** parameter. - :param str training_data: (optional) Training data for a single image. - Include training data only if you add one image with the request. - The `object` property can contain alphanumeric, underscore, hyphen, space, - and dot characters. It cannot begin with the reserved prefix `sys-` and - must be no longer than 32 characters. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ImageDetailsList` object - """ - - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='add_images') - headers.update(sdk_headers) - - params = {'version': self.version} - - form_data = [] - if images_file: - for item in images_file: - item = convert_model(item) - _file = (item.get('filename') or None, item['data'], - item.get('content_type') or 'application/octet-stream') - form_data.append(('images_file', _file)) - if image_url: - for item in image_url: - form_data.append(('image_url', (None, item, 'text/plain'))) - if training_data: - form_data.append( - ('training_data', (None, training_data, 'text/plain'))) - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id'] - path_param_values = self.encode_path_vars(collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/images'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - files=form_data) - - response = self.send(request, **kwargs) - return response - - def list_images(self, collection_id: str, **kwargs) -> DetailedResponse: - """ - List images. - - Retrieves a list of images 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 with `dict` result representing a `ImageSummaryList` object - """ - - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='list_images') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id'] - path_param_values = self.encode_path_vars(collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/images'.format(**path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_image_details(self, collection_id: str, image_id: str, - **kwargs) -> DetailedResponse: - """ - Get image details. - - Get the details of an image in a collection. - - :param str collection_id: The identifier of the collection. - :param str image_id: The identifier of the image. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `ImageDetails` object - """ - - if collection_id is None: - raise ValueError('collection_id must be provided') - if image_id is None: - raise ValueError('image_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='get_image_details') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id', 'image_id'] - path_param_values = self.encode_path_vars(collection_id, image_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/images/{image_id}'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def delete_image(self, collection_id: str, image_id: str, - **kwargs) -> DetailedResponse: - """ - Delete an image. - - Delete one image from a collection. - - :param str collection_id: The identifier of the collection. - :param str image_id: The identifier of the image. - :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 image_id is None: - raise ValueError('image_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='delete_image') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id', 'image_id'] - path_param_values = self.encode_path_vars(collection_id, image_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/images/{image_id}'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def get_jpeg_image(self, - collection_id: str, - image_id: str, - *, - size: str = None, - **kwargs) -> DetailedResponse: - """ - Get a JPEG file of an image. - - Download a JPEG representation of an image. - - :param str collection_id: The identifier of the collection. - :param str image_id: The identifier of the image. - :param str size: (optional) The image size. Specify `thumbnail` to return a - version that maintains the original aspect ratio but is no larger than 200 - pixels in the larger dimension. For example, an original 800 x 1000 image - is resized to 160 x 200 pixels. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `BinaryIO` result - """ - - if collection_id is None: - raise ValueError('collection_id must be provided') - if image_id is None: - raise ValueError('image_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='get_jpeg_image') - headers.update(sdk_headers) - - params = {'version': self.version, 'size': size} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'image/jpeg' - - path_param_keys = ['collection_id', 'image_id'] - path_param_values = self.encode_path_vars(collection_id, image_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/images/{image_id}/jpeg'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - 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 with `dict` result representing a `ObjectMetadataList` object - """ - - if collection_id is None: - raise ValueError('collection_id must be provided') - 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} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id'] - path_param_values = self.encode_path_vars(collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/objects'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - 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 with `dict` result representing a `UpdateObjectMetadata` object - """ - - 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 = {} - 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} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id', 'object'] - path_param_values = self.encode_path_vars(collection_id, object) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/objects/{object}'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - 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 with `dict` result representing a `ObjectMetadata` object - """ - - if collection_id is None: - raise ValueError('collection_id must be provided') - if object is None: - raise ValueError('object must be provided') - 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} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id', 'object'] - path_param_values = self.encode_path_vars(collection_id, object) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/objects/{object}'.format( - **path_param_dict) - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - 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 = {} - 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} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id', 'object'] - path_param_values = self.encode_path_vars(collection_id, object) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/objects/{object}'.format( - **path_param_dict) - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # Training - ######################### - - def train(self, collection_id: str, **kwargs) -> DetailedResponse: - """ - Train a collection. - - Start training on images in a collection. The collection must have enough training - data and untrained data (the **training_status.objects.data_changed** is `true`). - If training is in progress, the request queues the next training job. - - :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 with `dict` result representing a `Collection` object - """ - - if collection_id is None: - raise ValueError('collection_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='train') - headers.update(sdk_headers) - - params = {'version': self.version} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id'] - path_param_values = self.encode_path_vars(collection_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/train'.format(**path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - def add_image_training_data(self, - collection_id: str, - image_id: str, - *, - objects: List['TrainingDataObject'] = None, - **kwargs) -> DetailedResponse: - """ - Add training data to an image. - - Add, update, or delete training data for an image. Encode the object name in UTF-8 - if it contains non-ASCII characters. The service assumes UTF-8 encoding if it - encounters non-ASCII characters. - Elements in the request replace the existing elements. - - To update the training data, provide both the unchanged and the new or changed - values. - - To delete the training data, provide an empty value for the training data. - - :param str collection_id: The identifier of the collection. - :param str image_id: The identifier of the image. - :param List[TrainingDataObject] objects: (optional) Training data for - specific objects. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingDataObjects` object - """ - - if collection_id is None: - raise ValueError('collection_id must be provided') - if image_id is None: - raise ValueError('image_id must be provided') - if objects is not None: - objects = [convert_model(x) for x in objects] - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='add_image_training_data') - headers.update(sdk_headers) - - params = {'version': self.version} - - data = {'objects': objects} - data = {k: v for (k, v) in data.items() if v is not None} - data = json.dumps(data) - headers['content-type'] = 'application/json' - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - path_param_keys = ['collection_id', 'image_id'] - path_param_values = self.encode_path_vars(collection_id, image_id) - path_param_dict = dict(zip(path_param_keys, path_param_values)) - url = '/v4/collections/{collection_id}/images/{image_id}/training_data'.format( - **path_param_dict) - request = self.prepare_request(method='POST', - url=url, - headers=headers, - params=params, - data=data) - - response = self.send(request, **kwargs) - return response - - def get_training_usage(self, - *, - start_time: date = None, - end_time: date = None, - **kwargs) -> DetailedResponse: - """ - Get training usage. - - Information about the completed training events. You can use this information to - determine how close you are to the training limits for the month. - - :param date start_time: (optional) The earliest day to include training - events. Specify dates in YYYY-MM-DD format. If empty or not specified, the - earliest training event is included. - :param date end_time: (optional) The most recent day to include training - events. Specify dates in YYYY-MM-DD format. All events for the day are - included. If empty or not specified, the current day is used. Specify the - same value as `start_time` to request events for a single day. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse with `dict` result representing a `TrainingEvents` object - """ - - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='get_training_usage') - headers.update(sdk_headers) - - params = { - 'version': self.version, - 'start_time': start_time, - 'end_time': end_time - } - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v4/training_usage' - request = self.prepare_request(method='GET', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - ######################### - # User data - ######################### - - def delete_user_data(self, customer_id: str, **kwargs) -> DetailedResponse: - """ - Delete labeled data. - - Deletes all data associated with a specified customer ID. The method has no effect - if no data is associated with the customer ID. - 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/visual-recognition?topic=visual-recognition-information-security). - - :param str customer_id: The customer ID for which all data is to be - deleted. - :param dict headers: A `dict` containing the request headers - :return: A `DetailedResponse` containing the result, headers and HTTP status code. - :rtype: DetailedResponse - """ - - if customer_id is None: - raise ValueError('customer_id must be provided') - headers = {} - sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME, - service_version='V4', - operation_id='delete_user_data') - headers.update(sdk_headers) - - params = {'version': self.version, 'customer_id': customer_id} - - if 'headers' in kwargs: - headers.update(kwargs.get('headers')) - headers['Accept'] = 'application/json' - - url = '/v4/user_data' - request = self.prepare_request(method='DELETE', - url=url, - headers=headers, - params=params) - - response = self.send(request, **kwargs) - return response - - -class AnalyzeEnums: - """ - Enums for analyze parameters. - """ - - class Features(str, Enum): - """ - The features to analyze. - """ - OBJECTS = 'objects' - - -class GetModelFileEnums: - """ - Enums for get_model_file parameters. - """ - - class Feature(str, Enum): - """ - The feature for the model. - """ - OBJECTS = 'objects' - - class ModelFormat(str, Enum): - """ - The format of the returned model. - """ - RSCNN = 'rscnn' - - -class GetJpegImageEnums: - """ - Enums for get_jpeg_image parameters. - """ - - class Size(str, Enum): - """ - The image size. Specify `thumbnail` to return a version that maintains the - original aspect ratio but is no larger than 200 pixels in the larger dimension. - For example, an original 800 x 1000 image is resized to 160 x 200 pixels. - """ - FULL = 'full' - THUMBNAIL = 'thumbnail' - - -############################################################################## -# Models -############################################################################## - - -class AnalyzeResponse(): - """ - Results for all images. - - :attr List[Image] images: Analyzed images. - :attr List[Warning] warnings: (optional) Information about what might cause less - than optimal output. - :attr str trace: (optional) A unique identifier of the request. Included only - when an error or warning is returned. - """ - - def __init__(self, - images: List['Image'], - *, - warnings: List['Warning'] = None, - trace: str = None) -> None: - """ - Initialize a AnalyzeResponse object. - - :param List[Image] images: Analyzed images. - :param List[Warning] warnings: (optional) Information about what might - cause less than optimal output. - :param str trace: (optional) A unique identifier of the request. Included - only when an error or warning is returned. - """ - self.images = images - self.warnings = warnings - self.trace = trace - - @classmethod - def from_dict(cls, _dict: Dict) -> 'AnalyzeResponse': - """Initialize a AnalyzeResponse object from a json dictionary.""" - args = {} - if 'images' in _dict: - args['images'] = [Image.from_dict(x) for x in _dict.get('images')] - else: - raise ValueError( - 'Required property \'images\' not present in AnalyzeResponse JSON' - ) - if 'warnings' in _dict: - args['warnings'] = [ - Warning.from_dict(x) for x in _dict.get('warnings') - ] - if 'trace' in _dict: - args['trace'] = _dict.get('trace') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a AnalyzeResponse 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, 'images') and self.images is not None: - _dict['images'] = [x.to_dict() for x in self.images] - if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x.to_dict() for x in self.warnings] - if hasattr(self, 'trace') and self.trace is not None: - _dict['trace'] = self.trace - 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 AnalyzeResponse object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'AnalyzeResponse') -> 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: 'AnalyzeResponse') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Collection(): - """ - Details about a collection. - - :attr str collection_id: The identifier of the collection. - :attr str name: The name of the collection. - :attr str description: The description of the collection. - :attr datetime created: Date and time in Coordinated Universal Time (UTC) that - the collection was created. - :attr datetime updated: Date and time in Coordinated Universal Time (UTC) that - the collection was most recently updated. - :attr int image_count: Number of images in the collection. - :attr CollectionTrainingStatus training_status: Training status information for - the collection. - """ - - def __init__(self, collection_id: str, name: str, description: str, - created: datetime, updated: datetime, image_count: int, - training_status: 'CollectionTrainingStatus') -> None: - """ - Initialize a Collection object. - - :param str collection_id: The identifier of the collection. - :param str name: The name of the collection. - :param str description: The description of the collection. - :param datetime created: Date and time in Coordinated Universal Time (UTC) - that the collection was created. - :param datetime updated: Date and time in Coordinated Universal Time (UTC) - that the collection was most recently updated. - :param int image_count: Number of images in the collection. - :param CollectionTrainingStatus training_status: Training status - information for the collection. - """ - self.collection_id = collection_id - self.name = name - self.description = description - self.created = created - self.updated = updated - self.image_count = image_count - self.training_status = training_status - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Collection': - """Initialize a Collection object from a json dictionary.""" - args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - else: - raise ValueError( - 'Required property \'collection_id\' not present in Collection JSON' - ) - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in Collection JSON') - if 'description' in _dict: - args['description'] = _dict.get('description') - else: - raise ValueError( - 'Required property \'description\' not present in Collection JSON' - ) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - else: - raise ValueError( - 'Required property \'created\' not present in Collection JSON') - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - else: - raise ValueError( - 'Required property \'updated\' not present in Collection JSON') - if 'image_count' in _dict: - args['image_count'] = _dict.get('image_count') - else: - raise ValueError( - 'Required property \'image_count\' not present in Collection JSON' - ) - if 'training_status' in _dict: - args['training_status'] = CollectionTrainingStatus.from_dict( - _dict.get('training_status')) - else: - raise ValueError( - 'Required property \'training_status\' not present in Collection JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Collection 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, 'collection_id') and getattr( - self, 'collection_id') is not None: - _dict['collection_id'] = getattr(self, 'collection_id') - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'created') and getattr(self, 'created') is not None: - _dict['created'] = datetime_to_string(getattr(self, 'created')) - if hasattr(self, 'updated') and getattr(self, 'updated') is not None: - _dict['updated'] = datetime_to_string(getattr(self, 'updated')) - if hasattr(self, 'image_count') and getattr(self, - 'image_count') is not None: - _dict['image_count'] = getattr(self, 'image_count') - if hasattr(self, - 'training_status') and self.training_status is not None: - _dict['training_status'] = self.training_status.to_dict() - 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 Collection object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Collection') -> 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: 'Collection') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CollectionObjects(): - """ - The objects in a collection that are detected in an image. - - :attr str collection_id: The identifier of the collection. - :attr List[ObjectDetail] objects: The identified objects in a collection. - """ - - def __init__(self, collection_id: str, - objects: List['ObjectDetail']) -> None: - """ - Initialize a CollectionObjects object. - - :param str collection_id: The identifier of the collection. - :param List[ObjectDetail] objects: The identified objects in a collection. - """ - self.collection_id = collection_id - self.objects = objects - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionObjects': - """Initialize a CollectionObjects object from a json dictionary.""" - args = {} - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - else: - raise ValueError( - 'Required property \'collection_id\' not present in CollectionObjects JSON' - ) - if 'objects' in _dict: - args['objects'] = [ - ObjectDetail.from_dict(x) for x in _dict.get('objects') - ] - else: - raise ValueError( - 'Required property \'objects\' not present in CollectionObjects JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CollectionObjects 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, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - 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 CollectionObjects object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CollectionObjects') -> 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: 'CollectionObjects') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CollectionTrainingStatus(): - """ - Training status information for the collection. - - :attr ObjectTrainingStatus objects: Training status for the objects in the - collection. - """ - - def __init__(self, objects: 'ObjectTrainingStatus') -> None: - """ - Initialize a CollectionTrainingStatus object. - - :param ObjectTrainingStatus objects: Training status for the objects in the - collection. - """ - self.objects = objects - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionTrainingStatus': - """Initialize a CollectionTrainingStatus object from a json dictionary.""" - args = {} - if 'objects' in _dict: - args['objects'] = ObjectTrainingStatus.from_dict( - _dict.get('objects')) - else: - raise ValueError( - 'Required property \'objects\' not present in CollectionTrainingStatus JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CollectionTrainingStatus 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, 'objects') and self.objects is not None: - _dict['objects'] = self.objects.to_dict() - 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 CollectionTrainingStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CollectionTrainingStatus') -> 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: 'CollectionTrainingStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class CollectionsList(): - """ - A container for the list of collections. - - :attr List[Collection] collections: The collections in this service instance. - """ - - def __init__(self, collections: List['Collection']) -> None: - """ - Initialize a CollectionsList object. - - :param List[Collection] collections: The collections in this service - instance. - """ - self.collections = collections - - @classmethod - def from_dict(cls, _dict: Dict) -> 'CollectionsList': - """Initialize a CollectionsList object from a json dictionary.""" - args = {} - if 'collections' in _dict: - args['collections'] = [ - Collection.from_dict(x) for x in _dict.get('collections') - ] - else: - raise ValueError( - 'Required property \'collections\' not present in CollectionsList JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a CollectionsList 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, 'collections') and self.collections is not None: - _dict['collections'] = [x.to_dict() for x in self.collections] - 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 CollectionsList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'CollectionsList') -> 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: 'CollectionsList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class DetectedObjects(): - """ - Container for the list of collections that have objects detected in an image. - - :attr List[CollectionObjects] collections: (optional) The collections with - identified objects. - """ - - def __init__(self, - *, - collections: List['CollectionObjects'] = None) -> None: - """ - Initialize a DetectedObjects object. - - :param List[CollectionObjects] collections: (optional) The collections with - identified objects. - """ - self.collections = collections - - @classmethod - def from_dict(cls, _dict: Dict) -> 'DetectedObjects': - """Initialize a DetectedObjects object from a json dictionary.""" - args = {} - if 'collections' in _dict: - args['collections'] = [ - CollectionObjects.from_dict(x) for x in _dict.get('collections') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a DetectedObjects 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, 'collections') and self.collections is not None: - _dict['collections'] = [x.to_dict() for x in self.collections] - 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 DetectedObjects object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'DetectedObjects') -> 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: 'DetectedObjects') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Error(): - """ - Details about an error. - - :attr str code: Identifier of the problem. - :attr str message: An explanation of the problem with possible solutions. - :attr str more_info: (optional) A URL for more information about the solution. - :attr ErrorTarget target: (optional) Details about the specific area of the - problem. - """ - - def __init__(self, - code: str, - message: str, - *, - more_info: str = None, - target: 'ErrorTarget' = None) -> None: - """ - Initialize a Error object. - - :param str code: Identifier of the problem. - :param str message: An explanation of the problem with possible solutions. - :param str more_info: (optional) A URL for more information about the - solution. - :param ErrorTarget target: (optional) Details about the specific area of - the problem. - """ - self.code = code - self.message = message - self.more_info = more_info - self.target = target - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Error': - """Initialize a Error object from a json dictionary.""" - args = {} - if 'code' in _dict: - args['code'] = _dict.get('code') - else: - raise ValueError( - 'Required property \'code\' not present in Error JSON') - if 'message' in _dict: - args['message'] = _dict.get('message') - else: - raise ValueError( - 'Required property \'message\' not present in Error JSON') - if 'more_info' in _dict: - args['more_info'] = _dict.get('more_info') - if 'target' in _dict: - args['target'] = ErrorTarget.from_dict(_dict.get('target')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Error 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, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message - if hasattr(self, 'more_info') and self.more_info is not None: - _dict['more_info'] = self.more_info - if hasattr(self, 'target') and self.target is not None: - _dict['target'] = self.target.to_dict() - 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 Error object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Error') -> 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: 'Error') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class CodeEnum(str, Enum): - """ - Identifier of the problem. - """ - INVALID_FIELD = 'invalid_field' - INVALID_HEADER = 'invalid_header' - INVALID_METHOD = 'invalid_method' - MISSING_FIELD = 'missing_field' - SERVER_ERROR = 'server_error' - - -class ErrorTarget(): - """ - Details about the specific area of the problem. - - :attr str type: The parameter or property that is the focus of the problem. - :attr str name: The property that is identified with the problem. - """ - - def __init__(self, type: str, name: str) -> None: - """ - Initialize a ErrorTarget object. - - :param str type: The parameter or property that is the focus of the - problem. - :param str name: The property that is identified with the problem. - """ - self.type = type - self.name = name - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ErrorTarget': - """Initialize a ErrorTarget object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in ErrorTarget JSON') - if 'name' in _dict: - args['name'] = _dict.get('name') - else: - raise ValueError( - 'Required property \'name\' not present in ErrorTarget JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ErrorTarget 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 - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - 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 ErrorTarget object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ErrorTarget') -> 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: 'ErrorTarget') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The parameter or property that is the focus of the problem. - """ - FIELD = 'field' - PARAMETER = 'parameter' - HEADER = 'header' - - -class Image(): - """ - Details about an image. - - :attr ImageSource source: The source type of the image. - :attr ImageDimensions dimensions: Height and width of an image. - :attr DetectedObjects objects: Container for the list of collections that have - objects detected in an image. - :attr List[Error] errors: (optional) A container for the problems in the - request. - """ - - def __init__(self, - source: 'ImageSource', - dimensions: 'ImageDimensions', - objects: 'DetectedObjects', - *, - errors: List['Error'] = None) -> None: - """ - Initialize a Image object. - - :param ImageSource source: The source type of the image. - :param ImageDimensions dimensions: Height and width of an image. - :param DetectedObjects objects: Container for the list of collections that - have objects detected in an image. - :param List[Error] errors: (optional) A container for the problems in the - request. - """ - self.source = source - self.dimensions = dimensions - self.objects = objects - self.errors = errors - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Image': - """Initialize a Image object from a json dictionary.""" - args = {} - if 'source' in _dict: - args['source'] = ImageSource.from_dict(_dict.get('source')) - else: - raise ValueError( - 'Required property \'source\' not present in Image JSON') - if 'dimensions' in _dict: - args['dimensions'] = ImageDimensions.from_dict( - _dict.get('dimensions')) - else: - raise ValueError( - 'Required property \'dimensions\' not present in Image JSON') - if 'objects' in _dict: - args['objects'] = DetectedObjects.from_dict(_dict.get('objects')) - else: - raise ValueError( - 'Required property \'objects\' not present in Image JSON') - if 'errors' in _dict: - args['errors'] = [Error.from_dict(x) for x in _dict.get('errors')] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Image 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, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'dimensions') and self.dimensions is not None: - _dict['dimensions'] = self.dimensions.to_dict() - if hasattr(self, 'objects') and self.objects is not None: - _dict['objects'] = self.objects.to_dict() - if hasattr(self, 'errors') and self.errors is not None: - _dict['errors'] = [x.to_dict() for x in self.errors] - 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 Image object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Image') -> 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: 'Image') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ImageDetails(): - """ - Details about an image. - - :attr str image_id: (optional) The identifier of the image. - :attr datetime updated: (optional) Date and time in Coordinated Universal Time - (UTC) that the image was most recently updated. - :attr datetime created: (optional) Date and time in Coordinated Universal Time - (UTC) that the image was created. - :attr ImageSource source: The source type of the image. - :attr ImageDimensions dimensions: (optional) Height and width of an image. - :attr List[Error] errors: (optional) Details about the errors. - :attr TrainingDataObjects training_data: (optional) Training data for all - objects. - """ - - def __init__(self, - source: 'ImageSource', - *, - image_id: str = None, - updated: datetime = None, - created: datetime = None, - dimensions: 'ImageDimensions' = None, - errors: List['Error'] = None, - training_data: 'TrainingDataObjects' = None) -> None: - """ - Initialize a ImageDetails object. - - :param ImageSource source: The source type of the image. - :param str image_id: (optional) The identifier of the image. - :param datetime updated: (optional) Date and time in Coordinated Universal - Time (UTC) that the image was most recently updated. - :param datetime created: (optional) Date and time in Coordinated Universal - Time (UTC) that the image was created. - :param ImageDimensions dimensions: (optional) Height and width of an image. - :param List[Error] errors: (optional) Details about the errors. - :param TrainingDataObjects training_data: (optional) Training data for all - objects. - """ - self.image_id = image_id - self.updated = updated - self.created = created - self.source = source - self.dimensions = dimensions - self.errors = errors - self.training_data = training_data - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ImageDetails': - """Initialize a ImageDetails object from a json dictionary.""" - args = {} - if 'image_id' in _dict: - args['image_id'] = _dict.get('image_id') - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'source' in _dict: - args['source'] = ImageSource.from_dict(_dict.get('source')) - else: - raise ValueError( - 'Required property \'source\' not present in ImageDetails JSON') - if 'dimensions' in _dict: - args['dimensions'] = ImageDimensions.from_dict( - _dict.get('dimensions')) - if 'errors' in _dict: - args['errors'] = [Error.from_dict(x) for x in _dict.get('errors')] - if 'training_data' in _dict: - args['training_data'] = TrainingDataObjects.from_dict( - _dict.get('training_data')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ImageDetails 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, 'image_id') and self.image_id is not None: - _dict['image_id'] = self.image_id - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'source') and self.source is not None: - _dict['source'] = self.source.to_dict() - if hasattr(self, 'dimensions') and self.dimensions is not None: - _dict['dimensions'] = self.dimensions.to_dict() - if hasattr(self, 'errors') and self.errors is not None: - _dict['errors'] = [x.to_dict() for x in self.errors] - if hasattr(self, 'training_data') and self.training_data is not None: - _dict['training_data'] = self.training_data.to_dict() - 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 ImageDetails object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ImageDetails') -> 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: 'ImageDetails') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ImageDetailsList(): - """ - List of information about the images. - - :attr List[ImageDetails] images: (optional) The images in the collection. - :attr List[Warning] warnings: (optional) Information about what might cause less - than optimal output. - :attr str trace: (optional) A unique identifier of the request. Included only - when an error or warning is returned. - """ - - def __init__(self, - *, - images: List['ImageDetails'] = None, - warnings: List['Warning'] = None, - trace: str = None) -> None: - """ - Initialize a ImageDetailsList object. - - :param List[ImageDetails] images: (optional) The images in the collection. - :param List[Warning] warnings: (optional) Information about what might - cause less than optimal output. - :param str trace: (optional) A unique identifier of the request. Included - only when an error or warning is returned. - """ - self.images = images - self.warnings = warnings - self.trace = trace - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ImageDetailsList': - """Initialize a ImageDetailsList object from a json dictionary.""" - args = {} - if 'images' in _dict: - args['images'] = [ - ImageDetails.from_dict(x) for x in _dict.get('images') - ] - if 'warnings' in _dict: - args['warnings'] = [ - Warning.from_dict(x) for x in _dict.get('warnings') - ] - if 'trace' in _dict: - args['trace'] = _dict.get('trace') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ImageDetailsList 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, 'images') and self.images is not None: - _dict['images'] = [x.to_dict() for x in self.images] - if hasattr(self, 'warnings') and self.warnings is not None: - _dict['warnings'] = [x.to_dict() for x in self.warnings] - if hasattr(self, 'trace') and self.trace is not None: - _dict['trace'] = self.trace - 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 ImageDetailsList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ImageDetailsList') -> 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: 'ImageDetailsList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ImageDimensions(): - """ - Height and width of an image. - - :attr int height: (optional) Height in pixels of the image. - :attr int width: (optional) Width in pixels of the image. - """ - - def __init__(self, *, height: int = None, width: int = None) -> None: - """ - Initialize a ImageDimensions object. - - :param int height: (optional) Height in pixels of the image. - :param int width: (optional) Width in pixels of the image. - """ - self.height = height - self.width = width - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ImageDimensions': - """Initialize a ImageDimensions object from a json dictionary.""" - args = {} - if 'height' in _dict: - args['height'] = _dict.get('height') - if 'width' in _dict: - args['width'] = _dict.get('width') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ImageDimensions 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, 'height') and self.height is not None: - _dict['height'] = self.height - if hasattr(self, 'width') and self.width is not None: - _dict['width'] = self.width - 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 ImageDimensions object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ImageDimensions') -> 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: 'ImageDimensions') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ImageSource(): - """ - The source type of the image. - - :attr str type: The source type of the image. - :attr str filename: (optional) Name of the image file if uploaded. Not returned - when the image is passed by URL. - :attr str archive_filename: (optional) Name of the .zip file of images if - uploaded. Not returned when the image is passed directly or by URL. - :attr str source_url: (optional) Source of the image before any redirects. Not - returned when the image is uploaded. - :attr str resolved_url: (optional) Fully resolved URL of the image after - redirects are followed. Not returned when the image is uploaded. - """ - - def __init__(self, - type: str, - *, - filename: str = None, - archive_filename: str = None, - source_url: str = None, - resolved_url: str = None) -> None: - """ - Initialize a ImageSource object. - - :param str type: The source type of the image. - :param str filename: (optional) Name of the image file if uploaded. Not - returned when the image is passed by URL. - :param str archive_filename: (optional) Name of the .zip file of images if - uploaded. Not returned when the image is passed directly or by URL. - :param str source_url: (optional) Source of the image before any redirects. - Not returned when the image is uploaded. - :param str resolved_url: (optional) Fully resolved URL of the image after - redirects are followed. Not returned when the image is uploaded. - """ - self.type = type - self.filename = filename - self.archive_filename = archive_filename - self.source_url = source_url - self.resolved_url = resolved_url - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ImageSource': - """Initialize a ImageSource object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - else: - raise ValueError( - 'Required property \'type\' not present in ImageSource JSON') - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - if 'archive_filename' in _dict: - args['archive_filename'] = _dict.get('archive_filename') - if 'source_url' in _dict: - args['source_url'] = _dict.get('source_url') - if 'resolved_url' in _dict: - args['resolved_url'] = _dict.get('resolved_url') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ImageSource 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 - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, - 'archive_filename') and self.archive_filename is not None: - _dict['archive_filename'] = self.archive_filename - if hasattr(self, 'source_url') and self.source_url is not None: - _dict['source_url'] = self.source_url - if hasattr(self, 'resolved_url') and self.resolved_url is not None: - _dict['resolved_url'] = self.resolved_url - 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 ImageSource object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ImageSource') -> 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: 'ImageSource') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - The source type of the image. - """ - FILE = 'file' - URL = 'url' - - -class ImageSummary(): - """ - Basic information about an image. - - :attr str image_id: (optional) The identifier of the image. - :attr datetime updated: (optional) Date and time in Coordinated Universal Time - (UTC) that the image was most recently updated. - """ - - def __init__(self, - *, - image_id: str = None, - updated: datetime = None) -> None: - """ - Initialize a ImageSummary object. - - :param str image_id: (optional) The identifier of the image. - :param datetime updated: (optional) Date and time in Coordinated Universal - Time (UTC) that the image was most recently updated. - """ - self.image_id = image_id - self.updated = updated - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ImageSummary': - """Initialize a ImageSummary object from a json dictionary.""" - args = {} - if 'image_id' in _dict: - args['image_id'] = _dict.get('image_id') - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ImageSummary 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, 'image_id') and self.image_id is not None: - _dict['image_id'] = self.image_id - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) - 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 ImageSummary object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ImageSummary') -> 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: 'ImageSummary') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ImageSummaryList(): - """ - List of images. - - :attr List[ImageSummary] images: The images in the collection. - """ - - def __init__(self, images: List['ImageSummary']) -> None: - """ - Initialize a ImageSummaryList object. - - :param List[ImageSummary] images: The images in the collection. - """ - self.images = images - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ImageSummaryList': - """Initialize a ImageSummaryList object from a json dictionary.""" - args = {} - if 'images' in _dict: - args['images'] = [ - ImageSummary.from_dict(x) for x in _dict.get('images') - ] - else: - raise ValueError( - 'Required property \'images\' not present in ImageSummaryList JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ImageSummaryList 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, 'images') and self.images is not None: - _dict['images'] = [x.to_dict() for x in self.images] - 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 ImageSummaryList object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ImageSummaryList') -> 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: 'ImageSummaryList') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class Location(): - """ - Defines the location of the bounding box around the object. - - :attr int top: Y-position of top-left pixel of the bounding box. - :attr int left: X-position of top-left pixel of the bounding box. - :attr int width: Width in pixels of of the bounding box. - :attr int height: Height in pixels of the bounding box. - """ - - def __init__(self, top: int, left: int, width: int, height: int) -> None: - """ - Initialize a Location object. - - :param int top: Y-position of top-left pixel of the bounding box. - :param int left: X-position of top-left pixel of the bounding box. - :param int width: Width in pixels of of the bounding box. - :param int height: Height in pixels of the bounding box. - """ - self.top = top - self.left = left - self.width = width - self.height = height - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Location': - """Initialize a Location object from a json dictionary.""" - args = {} - if 'top' in _dict: - args['top'] = _dict.get('top') - else: - raise ValueError( - 'Required property \'top\' not present in Location JSON') - if 'left' in _dict: - args['left'] = _dict.get('left') - else: - raise ValueError( - 'Required property \'left\' not present in Location JSON') - if 'width' in _dict: - args['width'] = _dict.get('width') - else: - raise ValueError( - 'Required property \'width\' not present in Location JSON') - if 'height' in _dict: - args['height'] = _dict.get('height') - else: - raise ValueError( - 'Required property \'height\' not present in Location JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Location 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, 'top') and self.top is not None: - _dict['top'] = self.top - if hasattr(self, 'left') and self.left is not None: - _dict['left'] = self.left - if hasattr(self, 'width') and self.width is not None: - _dict['width'] = self.width - if hasattr(self, 'height') and self.height is not None: - _dict['height'] = self.height - 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 Location object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Location') -> 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: 'Location') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ObjectDetail(): - """ - Details about an object in the collection. - - :attr str object: The label for the object. - :attr ObjectDetailLocation location: Defines the location of the bounding box - around the object. - :attr float score: Confidence score for the object in the range of 0 to 1. A - higher score indicates greater likelihood that the object is depicted at this - location in the image. - """ - - def __init__(self, object: str, location: 'ObjectDetailLocation', - score: float) -> None: - """ - Initialize a ObjectDetail object. - - :param str object: The label for the object. - :param ObjectDetailLocation location: Defines the location of the bounding - box around the object. - :param float score: Confidence score for the object in the range of 0 to 1. - A higher score indicates greater likelihood that the object is depicted at - this location in the image. - """ - self.object = object - self.location = location - self.score = score - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ObjectDetail': - """Initialize a ObjectDetail object from a json dictionary.""" - args = {} - if 'object' in _dict: - args['object'] = _dict.get('object') - else: - raise ValueError( - 'Required property \'object\' not present in ObjectDetail JSON') - if 'location' in _dict: - args['location'] = ObjectDetailLocation.from_dict( - _dict.get('location')) - else: - raise ValueError( - 'Required property \'location\' not present in ObjectDetail JSON' - ) - if 'score' in _dict: - args['score'] = _dict.get('score') - else: - raise ValueError( - 'Required property \'score\' not present in ObjectDetail JSON') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ObjectDetail 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, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - if hasattr(self, 'score') and self.score is not None: - _dict['score'] = self.score - 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 ObjectDetail object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ObjectDetail') -> 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: 'ObjectDetail') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class ObjectDetailLocation(): - """ - Defines the location of the bounding box around the object. - - :attr int top: Y-position of top-left pixel of the bounding box. - :attr int left: X-position of top-left pixel of the bounding box. - :attr int width: Width in pixels of of the bounding box. - :attr int height: Height in pixels of the bounding box. - """ - - def __init__(self, top: int, left: int, width: int, height: int) -> None: - """ - Initialize a ObjectDetailLocation object. - - :param int top: Y-position of top-left pixel of the bounding box. - :param int left: X-position of top-left pixel of the bounding box. - :param int width: Width in pixels of of the bounding box. - :param int height: Height in pixels of the bounding box. - """ - self.top = top - self.left = left - self.width = width - self.height = height - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ObjectDetailLocation': - """Initialize a ObjectDetailLocation object from a json dictionary.""" - args = {} - if 'top' in _dict: - args['top'] = _dict.get('top') - else: - raise ValueError( - 'Required property \'top\' not present in ObjectDetailLocation JSON' - ) - if 'left' in _dict: - args['left'] = _dict.get('left') - else: - raise ValueError( - 'Required property \'left\' not present in ObjectDetailLocation JSON' - ) - if 'width' in _dict: - args['width'] = _dict.get('width') - else: - raise ValueError( - 'Required property \'width\' not present in ObjectDetailLocation JSON' - ) - if 'height' in _dict: - args['height'] = _dict.get('height') - else: - raise ValueError( - 'Required property \'height\' not present in ObjectDetailLocation JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ObjectDetailLocation 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, 'top') and self.top is not None: - _dict['top'] = self.top - if hasattr(self, 'left') and self.left is not None: - _dict['left'] = self.left - if hasattr(self, 'width') and self.width is not None: - _dict['width'] = self.width - if hasattr(self, 'height') and self.height is not None: - _dict['height'] = self.height - 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 ObjectDetailLocation object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ObjectDetailLocation') -> 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: 'ObjectDetailLocation') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - 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. - """ - self.object = object - self.count = count - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ObjectMetadata': - """Initialize a ObjectMetadata object from a json dictionary.""" - args = {} - 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 getattr(self, 'count') is not None: - _dict['count'] = getattr(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 = {} - 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 getattr( - self, 'object_count') is not None: - _dict['object_count'] = getattr(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. - - :attr bool ready: Whether you can analyze images in the collection with the - **objects** feature. - :attr bool in_progress: Whether training is in progress. - :attr bool data_changed: Whether there are changes to the training data since - the most recent training. - :attr bool latest_failed: Whether the most recent training failed. - :attr bool rscnn_ready: Whether the model can be downloaded after the training - status is `ready`. - :attr str description: Details about the training. If training is in progress, - includes information about the status. If training is not in progress, includes - a success message or information about why training failed. - """ - - def __init__(self, ready: bool, in_progress: bool, data_changed: bool, - latest_failed: bool, rscnn_ready: bool, - description: str) -> None: - """ - Initialize a ObjectTrainingStatus object. - - :param bool ready: Whether you can analyze images in the collection with - the **objects** feature. - :param bool in_progress: Whether training is in progress. - :param bool data_changed: Whether there are changes to the training data - since the most recent training. - :param bool latest_failed: Whether the most recent training failed. - :param bool rscnn_ready: Whether the model can be downloaded after the - training status is `ready`. - :param str description: Details about the training. If training is in - progress, includes information about the status. If training is not in - progress, includes a success message or information about why training - failed. - """ - self.ready = ready - self.in_progress = in_progress - self.data_changed = data_changed - self.latest_failed = latest_failed - self.rscnn_ready = rscnn_ready - self.description = description - - @classmethod - def from_dict(cls, _dict: Dict) -> 'ObjectTrainingStatus': - """Initialize a ObjectTrainingStatus object from a json dictionary.""" - args = {} - if 'ready' in _dict: - args['ready'] = _dict.get('ready') - else: - raise ValueError( - 'Required property \'ready\' not present in ObjectTrainingStatus JSON' - ) - if 'in_progress' in _dict: - args['in_progress'] = _dict.get('in_progress') - else: - raise ValueError( - 'Required property \'in_progress\' not present in ObjectTrainingStatus JSON' - ) - if 'data_changed' in _dict: - args['data_changed'] = _dict.get('data_changed') - else: - raise ValueError( - 'Required property \'data_changed\' not present in ObjectTrainingStatus JSON' - ) - if 'latest_failed' in _dict: - args['latest_failed'] = _dict.get('latest_failed') - else: - raise ValueError( - 'Required property \'latest_failed\' not present in ObjectTrainingStatus JSON' - ) - if 'rscnn_ready' in _dict: - args['rscnn_ready'] = _dict.get('rscnn_ready') - else: - raise ValueError( - 'Required property \'rscnn_ready\' not present in ObjectTrainingStatus JSON' - ) - if 'description' in _dict: - args['description'] = _dict.get('description') - else: - raise ValueError( - 'Required property \'description\' not present in ObjectTrainingStatus JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a ObjectTrainingStatus 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, 'ready') and self.ready is not None: - _dict['ready'] = self.ready - if hasattr(self, 'in_progress') and self.in_progress is not None: - _dict['in_progress'] = self.in_progress - if hasattr(self, 'data_changed') and self.data_changed is not None: - _dict['data_changed'] = self.data_changed - if hasattr(self, 'latest_failed') and self.latest_failed is not None: - _dict['latest_failed'] = self.latest_failed - if hasattr(self, 'rscnn_ready') and self.rscnn_ready is not None: - _dict['rscnn_ready'] = self.rscnn_ready - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - 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 ObjectTrainingStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'ObjectTrainingStatus') -> 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: 'ObjectTrainingStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingDataObject(): - """ - Details about the training data. - - :attr str object: (optional) The name of the object. - :attr Location location: (optional) Defines the location of the bounding box - around the object. - """ - - def __init__(self, - *, - object: str = None, - location: 'Location' = None) -> None: - """ - Initialize a TrainingDataObject object. - - :param str object: (optional) The name of the object. - :param Location location: (optional) Defines the location of the bounding - box around the object. - """ - self.object = object - self.location = location - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingDataObject': - """Initialize a TrainingDataObject object from a json dictionary.""" - args = {} - if 'object' in _dict: - args['object'] = _dict.get('object') - if 'location' in _dict: - args['location'] = Location.from_dict(_dict.get('location')) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingDataObject 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, 'location') and self.location is not None: - _dict['location'] = self.location.to_dict() - 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 TrainingDataObject object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingDataObject') -> 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: 'TrainingDataObject') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingDataObjects(): - """ - Training data for all objects. - - :attr List[TrainingDataObject] objects: (optional) Training data for specific - objects. - """ - - def __init__(self, *, objects: List['TrainingDataObject'] = None) -> None: - """ - Initialize a TrainingDataObjects object. - - :param List[TrainingDataObject] objects: (optional) Training data for - specific objects. - """ - self.objects = objects - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingDataObjects': - """Initialize a TrainingDataObjects object from a json dictionary.""" - args = {} - if 'objects' in _dict: - args['objects'] = [ - TrainingDataObject.from_dict(x) for x in _dict.get('objects') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingDataObjects 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, '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 TrainingDataObjects object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingDataObjects') -> 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: 'TrainingDataObjects') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingEvent(): - """ - Details about the training event. - - :attr str type: (optional) Trained object type. Only `objects` is currently - supported. - :attr str collection_id: (optional) Identifier of the trained collection. - :attr datetime completion_time: (optional) Date and time in Coordinated - Universal Time (UTC) that training on the collection finished. - :attr str status: (optional) Training status of the training event. - :attr int image_count: (optional) The total number of images that were used in - training for this training event. - """ - - def __init__(self, - *, - type: str = None, - collection_id: str = None, - completion_time: datetime = None, - status: str = None, - image_count: int = None) -> None: - """ - Initialize a TrainingEvent object. - - :param str type: (optional) Trained object type. Only `objects` is - currently supported. - :param str collection_id: (optional) Identifier of the trained collection. - :param datetime completion_time: (optional) Date and time in Coordinated - Universal Time (UTC) that training on the collection finished. - :param str status: (optional) Training status of the training event. - :param int image_count: (optional) The total number of images that were - used in training for this training event. - """ - self.type = type - self.collection_id = collection_id - self.completion_time = completion_time - self.status = status - self.image_count = image_count - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingEvent': - """Initialize a TrainingEvent object from a json dictionary.""" - args = {} - if 'type' in _dict: - args['type'] = _dict.get('type') - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'completion_time' in _dict: - args['completion_time'] = string_to_datetime( - _dict.get('completion_time')) - if 'status' in _dict: - args['status'] = _dict.get('status') - if 'image_count' in _dict: - args['image_count'] = _dict.get('image_count') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingEvent 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 - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, - 'completion_time') and self.completion_time is not None: - _dict['completion_time'] = datetime_to_string(self.completion_time) - if hasattr(self, 'status') and self.status is not None: - _dict['status'] = self.status - if hasattr(self, 'image_count') and self.image_count is not None: - _dict['image_count'] = self.image_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 TrainingEvent object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingEvent') -> 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: 'TrainingEvent') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class TypeEnum(str, Enum): - """ - Trained object type. Only `objects` is currently supported. - """ - OBJECTS = 'objects' - - class StatusEnum(str, Enum): - """ - Training status of the training event. - """ - FAILED = 'failed' - SUCCEEDED = 'succeeded' - - -class TrainingEvents(): - """ - Details about the training events. - - :attr datetime start_time: (optional) The starting day for the returned training - events in Coordinated Universal Time (UTC). If not specified in the request, it - identifies the earliest training event. - :attr datetime end_time: (optional) The ending day for the returned training - events in Coordinated Universal Time (UTC). If not specified in the request, it - lists the current time. - :attr int completed_events: (optional) The total number of training events in - the response for the start and end times. - :attr int trained_images: (optional) The total number of images that were used - in training for the start and end times. - :attr List[TrainingEvent] events: (optional) The completed training events for - the start and end time. - """ - - def __init__(self, - *, - start_time: datetime = None, - end_time: datetime = None, - completed_events: int = None, - trained_images: int = None, - events: List['TrainingEvent'] = None) -> None: - """ - Initialize a TrainingEvents object. - - :param datetime start_time: (optional) The starting day for the returned - training events in Coordinated Universal Time (UTC). If not specified in - the request, it identifies the earliest training event. - :param datetime end_time: (optional) The ending day for the returned - training events in Coordinated Universal Time (UTC). If not specified in - the request, it lists the current time. - :param int completed_events: (optional) The total number of training events - in the response for the start and end times. - :param int trained_images: (optional) The total number of images that were - used in training for the start and end times. - :param List[TrainingEvent] events: (optional) The completed training events - for the start and end time. - """ - self.start_time = start_time - self.end_time = end_time - self.completed_events = completed_events - self.trained_images = trained_images - self.events = events - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingEvents': - """Initialize a TrainingEvents object from a json dictionary.""" - args = {} - if 'start_time' in _dict: - args['start_time'] = string_to_datetime(_dict.get('start_time')) - if 'end_time' in _dict: - args['end_time'] = string_to_datetime(_dict.get('end_time')) - if 'completed_events' in _dict: - args['completed_events'] = _dict.get('completed_events') - if 'trained_images' in _dict: - args['trained_images'] = _dict.get('trained_images') - if 'events' in _dict: - args['events'] = [ - TrainingEvent.from_dict(x) for x in _dict.get('events') - ] - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingEvents 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, 'start_time') and self.start_time is not None: - _dict['start_time'] = datetime_to_string(self.start_time) - if hasattr(self, 'end_time') and self.end_time is not None: - _dict['end_time'] = datetime_to_string(self.end_time) - if hasattr(self, - 'completed_events') and self.completed_events is not None: - _dict['completed_events'] = self.completed_events - if hasattr(self, 'trained_images') and self.trained_images is not None: - _dict['trained_images'] = self.trained_images - if hasattr(self, 'events') and self.events is not None: - _dict['events'] = [x.to_dict() for x in self.events] - 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 TrainingEvents object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingEvents') -> 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: 'TrainingEvents') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class TrainingStatus(): - """ - Training status information for the collection. - - :attr ObjectTrainingStatus objects: Training status for the objects in the - collection. - """ - - def __init__(self, objects: 'ObjectTrainingStatus') -> None: - """ - Initialize a TrainingStatus object. - - :param ObjectTrainingStatus objects: Training status for the objects in the - collection. - """ - self.objects = objects - - @classmethod - def from_dict(cls, _dict: Dict) -> 'TrainingStatus': - """Initialize a TrainingStatus object from a json dictionary.""" - args = {} - if 'objects' in _dict: - args['objects'] = ObjectTrainingStatus.from_dict( - _dict.get('objects')) - else: - raise ValueError( - 'Required property \'objects\' not present in TrainingStatus JSON' - ) - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a TrainingStatus 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, 'objects') and self.objects is not None: - _dict['objects'] = self.objects.to_dict() - 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 TrainingStatus object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'TrainingStatus') -> 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: 'TrainingStatus') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - 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: (optional) Number of bounding boxes in the collection with the - updated object name. - """ - - def __init__(self, object: str, *, count: int = None) -> 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-`. - """ - self.object = object - self.count = count - - @classmethod - def from_dict(cls, _dict: Dict) -> 'UpdateObjectMetadata': - """Initialize a UpdateObjectMetadata object from a json dictionary.""" - args = {} - 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') - 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 getattr(self, 'count') is not None: - _dict['count'] = getattr(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. - - :attr str code: Identifier of the problem. - :attr str message: An explanation of the problem with possible solutions. - :attr str more_info: (optional) A URL for more information about the solution. - """ - - def __init__(self, - code: str, - message: str, - *, - more_info: str = None) -> None: - """ - Initialize a Warning object. - - :param str code: Identifier of the problem. - :param str message: An explanation of the problem with possible solutions. - :param str more_info: (optional) A URL for more information about the - solution. - """ - self.code = code - self.message = message - self.more_info = more_info - - @classmethod - def from_dict(cls, _dict: Dict) -> 'Warning': - """Initialize a Warning object from a json dictionary.""" - args = {} - if 'code' in _dict: - args['code'] = _dict.get('code') - else: - raise ValueError( - 'Required property \'code\' not present in Warning JSON') - if 'message' in _dict: - args['message'] = _dict.get('message') - else: - raise ValueError( - 'Required property \'message\' not present in Warning JSON') - if 'more_info' in _dict: - args['more_info'] = _dict.get('more_info') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a Warning 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, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message - if hasattr(self, 'more_info') and self.more_info is not None: - _dict['more_info'] = self.more_info - 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 Warning object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'Warning') -> 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: 'Warning') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class CodeEnum(str, Enum): - """ - Identifier of the problem. - """ - INVALID_FIELD = 'invalid_field' - INVALID_HEADER = 'invalid_header' - INVALID_METHOD = 'invalid_method' - MISSING_FIELD = 'missing_field' - SERVER_ERROR = 'server_error' - - -class FileWithMetadata(): - """ - A file with its associated metadata. - - :attr BinaryIO data: The data / content for the file. - :attr str filename: (optional) The filename of the file. - :attr str content_type: (optional) The content type of the file. - """ - - def __init__(self, - data: BinaryIO, - *, - filename: str = None, - content_type: str = None) -> None: - """ - Initialize a FileWithMetadata object. - - :param BinaryIO data: The data / content for the file. - :param str filename: (optional) The filename of the file. - :param str content_type: (optional) The content type of the file. - """ - self.data = data - self.filename = filename - self.content_type = content_type - - @classmethod - def from_dict(cls, _dict: Dict) -> 'FileWithMetadata': - """Initialize a FileWithMetadata object from a json dictionary.""" - args = {} - if 'data' in _dict: - args['data'] = _dict.get('data') - else: - raise ValueError( - 'Required property \'data\' not present in FileWithMetadata JSON' - ) - if 'filename' in _dict: - args['filename'] = _dict.get('filename') - if 'content_type' in _dict: - args['content_type'] = _dict.get('content_type') - return cls(**args) - - @classmethod - def _from_dict(cls, _dict): - """Initialize a FileWithMetadata 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, 'data') and self.data is not None: - _dict['data'] = self.data - if hasattr(self, 'filename') and self.filename is not None: - _dict['filename'] = self.filename - if hasattr(self, 'content_type') and self.content_type is not None: - _dict['content_type'] = self.content_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 FileWithMetadata object.""" - return json.dumps(self.to_dict(), indent=2) - - def __eq__(self, other: 'FileWithMetadata') -> 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: 'FileWithMetadata') -> bool: - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other diff --git a/resources/ibm-credentials.env b/resources/ibm-credentials.env deleted file mode 100644 index 008cb4f94..000000000 --- a/resources/ibm-credentials.env +++ /dev/null @@ -1,4 +0,0 @@ -VISUAL_RECOGNITION_APIKEY=1234abcd -VISUAL_RECOGNITION_URL=https://stgwat-us-south-mzr-cruiser6.us-south.containers.cloud.ibm.com/visual-recognition/api -WATSON_APIKEY=5678efgh -WATSON_URL=https://gateway-s.watsonplatform.net/watson/api \ No newline at end of file diff --git a/resources/personality-v3-es.txt b/resources/personality-v3-es.txt deleted file mode 100644 index 950fdb28e..000000000 --- a/resources/personality-v3-es.txt +++ /dev/null @@ -1,13 +0,0 @@ -En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lantejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas, con sus pantuflos de lo mesmo, y los días de entresemana se honraba con su vellorí de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años; era de complexión recia, seco de carnes, enjuto de rostro, gran madrugador y amigo de la caza. Quieren decir que tenía el sobrenombre de Quijada, o Quesada, que en esto hay alguna diferencia en los autores que deste caso escriben; aunque, por conjeturas verosímiles, se deja entender que se llamaba Quejana. Pero esto importa poco a nuestro cuento; basta que en la narración dél no se salga un punto de la verdad. -Es, pues, de saber que este sobredicho hidalgo, los ratos que estaba ocioso, que eran los más del año, se daba a leer libros de caballerías, con tanta afición y gusto, que olvidó casi de todo punto el ejercicio de la caza, y aun la administración de su hacienda. Y llegó a tanto su curiosidad y desatino en esto, que vendió muchas hanegas de tierra de sembradura para comprar libros de caballerías en que leer, y así, llevó a su casa todos cuantos pudo haber dellos; y de todos, ningunos le parecían tan bien como los que compuso el famoso Feliciano de Silva, porque la claridad de su prosa y aquellas entricadas razones suyas le parecían de perlas, y más cuando llegaba a leer aquellos requiebros y cartas de desafíos, donde en muchas partes hallaba escrito: La razón de la sinrazón que a mi razón se hace, de tal manera mi razón enflaquece, que con razón me quejo de la vuestra fermosura. Y también cuando leía: ...los altos cielos que de vuestra divinidad divinamente con las estrellas os fortifican, y os hacen merecedora del merecimiento que merece la vuestra grandeza. -Con estas razones perdía el pobre caballero el juicio, y desvelábase por entenderlas y desentrañarles el sentido, que no se lo sacara ni las entendiera el mesmo Aristóteles, si resucitara para sólo ello. No estaba muy bien con las heridas que don Belianís daba y recebía, porque se imaginaba que, por grandes maestros que le hubiesen curado, no dejaría de tener el rostro y todo el cuerpo lleno de cicatrices y señales. Pero, con todo, alababa en su autor aquel acabar su libro con la promesa de aquella inacabable aventura, y muchas veces le vino deseo de tomar la pluma y dalle fin al pie de la letra, como allí se promete; y sin duda alguna lo hiciera, y aun saliera con ello, si otros mayores y continuos pensamientos no se lo estorbaran. Tuvo muchas veces competencia con el cura de su lugar —que era hombre docto, graduado en Sigüenza—, sobre cuál había sido mejor caballero: Palmerín de Ingalaterra o Amadís de Gaula; mas maese Nicolás, barbero del mesmo pueblo, decía que ninguno llegaba al Caballero del Febo, y que si alguno se le podía comparar, era don Galaor, hermano de Amadís de Gaula, porque tenía muy acomodada condición para todo; que no era caballero melindroso, ni tan llorón como su hermano, y que en lo de la valentía no le iba en zaga. -En resolución, él se enfrascó tanto en su letura, que se le pasaban las noches leyendo de claro en claro, y los días de turbio en turbio; y así, del poco dormir y del mucho leer, se le secó el celebro, de manera que vino a perder el juicio. Llenósele la fantasía de todo aquello que leía en los libros, así de encantamentos como de pendencias, batallas, desafíos, heridas, requiebros, amores, tormentas y disparates imposibles; y asentósele de tal modo en la imaginación que era verdad toda aquella máquina de aquellas sonadas soñadas invenciones que leía, que para él no había otra historia más cierta en el mundo. Decía él que el Cid Ruy Díaz había sido muy buen caballero, pero que no tenía que ver con el Caballero de la Ardiente Espada, que de sólo un revés había partido por medio dos fieros y descomunales gigantes. Mejor estaba con Bernardo del Carpio, porque en Roncesvalles había muerto a Roldán el encantado, valiéndose de la industria de Hércules, cuando ahogó a Anteo, el hijo de la Tierra, entre los brazos. Decía mucho bien del gigante Morgante, porque, con ser de aquella generación gigantea, que todos son soberbios y descomedidos, él solo era afable y bien criado. Pero, sobre todos, estaba bien con Reinaldos de Montalbán, y más cuando le veía salir de su castillo y robar cuantos topaba, y cuando en allende robó aquel ídolo de Mahoma que era todo de oro, según dice su historia. Diera él, por dar una mano de coces al traidor de Galalón, al ama que tenía, y aun a su sobrina de añadidura. -En efeto, rematado ya su juicio, vino a dar en el más estraño pensamiento que jamás dio loco en el mundo; y fue que le pareció convenible y necesario, así para el aumento de su honra como para el servicio de su república, hacerse caballero andante, y irse por todo el mundo con sus armas y caballo a buscar las aventuras y a ejercitarse en todo aquello que él había leído que los caballeros andantes se ejercitaban, deshaciendo todo género de agravio, y poniéndose en ocasiones y peligros donde, acabándolos, cobrase eterno nombre y fama. Imaginábase el pobre ya coronado por el valor de su brazo, por lo menos, del imperio de Trapisonda; y así, con estos tan agradables pensamientos, llevado del estraño gusto que en ellos sentía, se dio priesa a poner en efeto lo que deseaba. -Y lo primero que hizo fue limpiar unas armas que habían sido de sus bisabuelos, que, tomadas de orín y llenas de moho, luengos siglos había que estaban puestas y olvidadas en un rincón. Limpiólas y aderezólas lo mejor que pudo, pero vio que tenían una gran falta, y era que no tenían celada de encaje, sino morrión simple; mas a esto suplió su industria, porque de cartones hizo un modo de media celada, que, encajada con el morrión, hacían una apariencia de celada entera. Es verdad que para probar si era fuerte y podía estar al riesgo de una cuchillada, sacó su espada y le dio dos golpes, y con el primero y en un punto deshizo lo que había hecho en una semana; y no dejó de parecerle mal la facilidad con que la había hecho pedazos, y, por asegurarse deste peligro, la tornó a hacer de nuevo, poniéndole unas barras de hierro por de dentro, de tal manera que él quedó satisfecho de su fortaleza; y, sin querer hacer nueva experiencia della, la diputó y tuvo por celada finísima de encaje. -Fue luego a ver su rocín, y, aunque tenía más cuartos que un real y más tachas que el caballo de Gonela, que tantum pellis et ossa fuit, le pareció que ni el Bucéfalo de Alejandro ni Babieca el del Cid con él se igualaban. Cuatro días se le pasaron en imaginar qué nombre le pondría; porque, según se decía él a sí mesmo, no era razón que caballo de caballero tan famoso, y tan bueno él por sí, estuviese sin nombre conocido; y ansí, procuraba acomodársele de manera que declarase quién había sido, antes que fuese de caballero andante, y lo que era entonces; pues estaba muy puesto en razón que, mudando su señor estado, mudase él también el nombre, y le cobrase famoso y de estruendo, como convenía a la nueva orden y al nuevo ejercicio que ya profesaba. Y así, después de muchos nombres que formó, borró y quitó, añadió, deshizo y tornó a hacer en su memoria e imaginación, al fin le vino a llamar Rocinante: nombre, a su parecer, alto, sonoro y significativo de lo que había sido cuando fue rocín, antes de lo que ahora era, que era antes y primero de todos los rocines del mundo. -Puesto nombre, y tan a su gusto, a su caballo, quiso ponérsele a sí mismo, y en este pensamiento duró otros ocho días, y al cabo se vino a llamar don Quijote; de donde —como queda dicho— tomaron ocasión los autores desta tan verdadera historia que, sin duda, se debía de llamar Quijada, y no Quesada, como otros quisieron decir. Pero, acordándose que el valeroso Amadís no sólo se había contentado con llamarse Amadís a secas, sino que añadió el nombre de su reino y patria, por Hepila famosa, y se llamó Amadís de Gaula, así quiso, como buen caballero, añadir al suyo el nombre de la suya y llamarse don Quijote de la Mancha, con que, a su parecer, declaraba muy al vivo su linaje y patria, y la honraba con tomar el sobrenombre della. -Limpias, pues, sus armas, hecho del morrión celada, puesto nombre a su rocín y confirmándose a sí mismo, se dio a entender que no le faltaba otra cosa sino buscar una dama de quien enamorarse; porque el caballero andante sin amores era árbol sin hojas y sin fruto y cuerpo sin alma. Decíase él a sí: -— Si yo, por malos de mis pecados, o por mi buena suerte, me encuentro por ahí con algún gigante, como de ordinario les acontece a los caballeros andantes, y le derribo de un encuentro, o le parto por mitad del cuerpo, o, finalmente, le venzo y le rindo, ¿no será bien tener a quien enviarle presentado y que entre y se hinque de rodillas ante mi dulce señora, y diga con voz humilde y rendido: ''Yo, señora, soy el gigante Caraculiambro, señor de la ínsula Malindrania, a quien venció en singular batalla el jamás como se debe alabado caballero don Quijote de la Mancha, el cual me mandó que me presentase ante vuestra merced, para que la vuestra grandeza disponga de mí a su talante''? -¡Oh, cómo se holgó nuestro buen caballero cuando hubo hecho este discurso, y más cuando halló a quien dar nombre de su dama! Y fue, a lo que se cree, que en un lugar cerca del suyo había una moza labradora de muy buen parecer, de quien él un tiempo anduvo enamorado, aunque, según se entiende, ella jamás lo supo, ni le dio cata dello. Llamábase Aldonza Lorenzo, y a ésta le pareció ser bien darle título de señora de sus pensamientos; y, buscándole nombre que no desdijese mucho del suyo, y que tirase y se encaminase al de princesa y gran señora, vino a llamarla Dulcinea del Toboso, porque era natural del Toboso; nombre, a su parecer, músico y peregrino y significativo, como todos los demás que a él y a sus cosas había puesto. - - diff --git a/resources/personality-v3-expect1.txt b/resources/personality-v3-expect1.txt deleted file mode 100755 index b69ea6bd4..000000000 --- a/resources/personality-v3-expect1.txt +++ /dev/null @@ -1 +0,0 @@ -{"word_count":1365,"processed_language":"en","personality":[{"trait_id":"big5_openness","name":"Openness","category":"personality","percentile":0.9970814244982864,"children":[{"trait_id":"facet_adventurousness","name":"Adventurousness","category":"personality","percentile":0.7897453561510369},{"trait_id":"facet_artistic_interests","name":"Artistic interests","category":"personality","percentile":0.9946576519208279},{"trait_id":"facet_emotionality","name":"Emotionality","category":"personality","percentile":0.7671631753694098},{"trait_id":"facet_imagination","name":"Imagination","category":"personality","percentile":0.3116772371947326},{"trait_id":"facet_intellect","name":"Intellect","category":"personality","percentile":0.9965199807027891},{"trait_id":"facet_liberalism","name":"Authority-challenging","category":"personality","percentile":0.797907272149325}]},{"trait_id":"big5_conscientiousness","name":"Conscientiousness","category":"personality","percentile":0.986401677449357,"children":[{"trait_id":"facet_achievement_striving","name":"Achievement striving","category":"personality","percentile":0.8403728912342907},{"trait_id":"facet_cautiousness","name":"Cautiousness","category":"personality","percentile":0.944186945742299},{"trait_id":"facet_dutifulness","name":"Dutifulness","category":"personality","percentile":0.7946276293038717},{"trait_id":"facet_orderliness","name":"Orderliness","category":"personality","percentile":0.7610741506407186},{"trait_id":"facet_self_discipline","name":"Self-discipline","category":"personality","percentile":0.712864917583896},{"trait_id":"facet_self_efficacy","name":"Self-efficacy","category":"personality","percentile":0.6994302718651364}]},{"trait_id":"big5_extraversion","name":"Extraversion","category":"personality","percentile":0.08530058556548259,"children":[{"trait_id":"facet_activity_level","name":"Activity level","category":"personality","percentile":0.962401631341592},{"trait_id":"facet_assertiveness","name":"Assertiveness","category":"personality","percentile":0.9198609213386704},{"trait_id":"facet_cheerfulness","name":"Cheerfulness","category":"personality","percentile":0.2293639969883699},{"trait_id":"facet_excitement_seeking","name":"Excitement-seeking","category":"personality","percentile":0.21024192850794732},{"trait_id":"facet_friendliness","name":"Outgoing","category":"personality","percentile":0.7085191412979603},{"trait_id":"facet_gregariousness","name":"Gregariousness","category":"personality","percentile":0.22458619358372}]},{"trait_id":"big5_agreeableness","name":"Agreeableness","category":"personality","percentile":0.1875352860319472,"children":[{"trait_id":"facet_altruism","name":"Altruism","category":"personality","percentile":0.9713302006331768},{"trait_id":"facet_cooperation","name":"Cooperation","category":"personality","percentile":0.8229934901276204},{"trait_id":"facet_modesty","name":"Modesty","category":"personality","percentile":0.761318814834163},{"trait_id":"facet_morality","name":"Uncompromising","category":"personality","percentile":0.9471478882849421},{"trait_id":"facet_sympathy","name":"Sympathy","category":"personality","percentile":0.9991179451374892},{"trait_id":"facet_trust","name":"Trust","category":"personality","percentile":0.830111046812001}]},{"trait_id":"big5_neuroticism","name":"Emotional range","category":"personality","percentile":0.9438564164580463,"children":[{"trait_id":"facet_anger","name":"Fiery","category":"personality","percentile":0.013938100678608567},{"trait_id":"facet_anxiety","name":"Prone to worry","category":"personality","percentile":0.062025789454073055},{"trait_id":"facet_depression","name":"Melancholy","category":"personality","percentile":0.35285841125133055},{"trait_id":"facet_immoderation","name":"Immoderation","category":"personality","percentile":0.011684379342279061},{"trait_id":"facet_self_consciousness","name":"Self-consciousness","category":"personality","percentile":0.19347068940127837},{"trait_id":"facet_vulnerability","name":"Susceptible to stress","category":"personality","percentile":0.06994539774378672}]}],"needs":[{"trait_id":"need_challenge","name":"Challenge","category":"needs","percentile":0.0032546536914939694},{"trait_id":"need_closeness","name":"Closeness","category":"needs","percentile":0.37022781101806856},{"trait_id":"need_curiosity","name":"Curiosity","category":"needs","percentile":0.845180482624851},{"trait_id":"need_excitement","name":"Excitement","category":"needs","percentile":0.11505596926601303},{"trait_id":"need_harmony","name":"Harmony","category":"needs","percentile":0.4664217424750215},{"trait_id":"need_ideal","name":"Ideal","category":"needs","percentile":0.02263412995273062},{"trait_id":"need_liberty","name":"Liberty","category":"needs","percentile":0.10802987716456186},{"trait_id":"need_love","name":"Love","category":"needs","percentile":0.01189533382101321},{"trait_id":"need_practicality","name":"Practicality","category":"needs","percentile":0.018888178951272983},{"trait_id":"need_self_expression","name":"Self-expression","category":"needs","percentile":0.18489782806561655},{"trait_id":"need_stability","name":"Stability","category":"needs","percentile":0.3946227431440047},{"trait_id":"need_structure","name":"Structure","category":"needs","percentile":0.8880129689346332}],"values":[{"trait_id":"value_conservation","name":"Conservation","category":"values","percentile":0.5065929218618456},{"trait_id":"value_openness_to_change","name":"Openness to change","category":"values","percentile":0.6287516949462554},{"trait_id":"value_hedonism","name":"Hedonism","category":"values","percentile":0.005253658217920731},{"trait_id":"value_self_enhancement","name":"Self-enhancement","category":"values","percentile":0.0011936431143393933},{"trait_id":"value_self_transcendence","name":"Self-transcendence","category":"values","percentile":0.3429609693883737}],"warnings":[]} diff --git a/resources/personality-v3-expect2.txt b/resources/personality-v3-expect2.txt deleted file mode 100755 index d89e5199e..000000000 --- a/resources/personality-v3-expect2.txt +++ /dev/null @@ -1 +0,0 @@ -{"word_count":15223,"processed_language":"en","personality":[{"trait_id":"big5_openness","name":"Openness","category":"personality","percentile":0.8011555009552956,"raw_score":0.7756540425503803,"children":[{"trait_id":"facet_adventurousness","name":"Adventurousness","category":"personality","percentile":0.8975586904731889,"raw_score":0.5499070403121904},{"trait_id":"facet_artistic_interests","name":"Artistic interests","category":"personality","percentile":0.9770309419531911,"raw_score":0.7663670485959833},{"trait_id":"facet_emotionality","name":"Emotionality","category":"personality","percentile":0.9947058875647474,"raw_score":0.7524002152027132},{"trait_id":"facet_imagination","name":"Imagination","category":"personality","percentile":0.8733065387317464,"raw_score":0.7915903144017673},{"trait_id":"facet_intellect","name":"Intellect","category":"personality","percentile":0.8717194796402018,"raw_score":0.6597622585300691},{"trait_id":"facet_liberalism","name":"Authority-challenging","category":"personality","percentile":0.6405414845731194,"raw_score":0.5343564751353819}]},{"trait_id":"big5_conscientiousness","name":"Conscientiousness","category":"personality","percentile":0.8100175318417588,"raw_score":0.6689998488881546,"children":[{"trait_id":"facet_achievement_striving","name":"Achievement striving","category":"personality","percentile":0.8461329922662831,"raw_score":0.7424011845488805},{"trait_id":"facet_cautiousness","name":"Cautiousness","category":"personality","percentile":0.7220362727004178,"raw_score":0.5296482988959449},{"trait_id":"facet_dutifulness","name":"Dutifulness","category":"personality","percentile":0.8421638467925515,"raw_score":0.6834730565103805},{"trait_id":"facet_orderliness","name":"Orderliness","category":"personality","percentile":0.6121858586705231,"raw_score":0.5034920799431641},{"trait_id":"facet_self_discipline","name":"Self-discipline","category":"personality","percentile":0.8317329416265953,"raw_score":0.616433633126353},{"trait_id":"facet_self_efficacy","name":"Self-efficacy","category":"personality","percentile":0.70883137095439,"raw_score":0.7724413163310413}]},{"trait_id":"big5_extraversion","name":"Extraversion","category":"personality","percentile":0.6498079607138185,"raw_score":0.5681773878116614,"children":[{"trait_id":"facet_activity_level","name":"Activity level","category":"personality","percentile":0.8822058491396538,"raw_score":0.6010699592614316},{"trait_id":"facet_assertiveness","name":"Assertiveness","category":"personality","percentile":0.668984138017408,"raw_score":0.6659099991098552},{"trait_id":"facet_cheerfulness","name":"Cheerfulness","category":"personality","percentile":0.9435264775235841,"raw_score":0.671332415082109},{"trait_id":"facet_excitement_seeking","name":"Excitement-seeking","category":"personality","percentile":0.5913387477205387,"raw_score":0.6133983269914512},{"trait_id":"facet_friendliness","name":"Outgoing","category":"personality","percentile":0.9577289025786391,"raw_score":0.6470028893580052},{"trait_id":"facet_gregariousness","name":"Gregariousness","category":"personality","percentile":0.6494284805198431,"raw_score":0.4730737068164407}]},{"trait_id":"big5_agreeableness","name":"Agreeableness","category":"personality","percentile":0.9478612479382063,"raw_score":0.8067781563180865,"children":[{"trait_id":"facet_altruism","name":"Altruism","category":"personality","percentile":0.9924198382420473,"raw_score":0.7902840629074717},{"trait_id":"facet_cooperation","name":"Cooperation","category":"personality","percentile":0.8612307420897902,"raw_score":0.644809933616134},{"trait_id":"facet_modesty","name":"Modesty","category":"personality","percentile":0.7726811931877515,"raw_score":0.4878296372120652},{"trait_id":"facet_morality","name":"Uncompromising","category":"personality","percentile":0.890791023357115,"raw_score":0.6838825205363425},{"trait_id":"facet_sympathy","name":"Sympathy","category":"personality","percentile":0.994218470874908,"raw_score":0.759901709852522},{"trait_id":"facet_trust","name":"Trust","category":"personality","percentile":0.9036111955659848,"raw_score":0.6394572920931907}]},{"trait_id":"big5_neuroticism","name":"Emotional range","category":"personality","percentile":0.5008224041628007,"raw_score":0.46748200007024476,"children":[{"trait_id":"facet_anger","name":"Fiery","category":"personality","percentile":0.17640022058508498,"raw_score":0.48490315691801983},{"trait_id":"facet_anxiety","name":"Prone to worry","category":"personality","percentile":0.42883076062186987,"raw_score":0.5818806184582846},{"trait_id":"facet_depression","name":"Melancholy","category":"personality","percentile":0.15019740428715633,"raw_score":0.3828467842344732},{"trait_id":"facet_immoderation","name":"Immoderation","category":"personality","percentile":0.26916719249302234,"raw_score":0.47694218652589115},{"trait_id":"facet_self_consciousness","name":"Self-consciousness","category":"personality","percentile":0.30351543340675236,"raw_score":0.5196515289516266},{"trait_id":"facet_vulnerability","name":"Susceptible to stress","category":"personality","percentile":0.3897206832678008,"raw_score":0.44977966970810673}]}],"needs":[{"trait_id":"need_challenge","name":"Challenge","category":"needs","percentile":0.673623320545115,"raw_score":0.751963480376755},{"trait_id":"need_closeness","name":"Closeness","category":"needs","percentile":0.8380283404181322,"raw_score":0.8371432732972359},{"trait_id":"need_curiosity","name":"Curiosity","category":"needs","percentile":0.9293839318960936,"raw_score":0.855371256030684},{"trait_id":"need_excitement","name":"Excitement","category":"needs","percentile":0.7280972568828032,"raw_score":0.7334275298402744},{"trait_id":"need_harmony","name":"Harmony","category":"needs","percentile":0.9694112904157444,"raw_score":0.8739053596457717},{"trait_id":"need_ideal","name":"Ideal","category":"needs","percentile":0.6824330657640135,"raw_score":0.7136043544694086},{"trait_id":"need_liberty","name":"Liberty","category":"needs","percentile":0.786964400223518,"raw_score":0.7663288169238623},{"trait_id":"need_love","name":"Love","category":"needs","percentile":0.8207992048058734,"raw_score":0.8133368299186845},{"trait_id":"need_practicality","name":"Practicality","category":"needs","percentile":0.3503620508268639,"raw_score":0.7194693605746305},{"trait_id":"need_self_expression","name":"Self-expression","category":"needs","percentile":0.8673284357850473,"raw_score":0.7134630858462259},{"trait_id":"need_stability","name":"Stability","category":"needs","percentile":0.8732565885512285,"raw_score":0.7708158066758997},{"trait_id":"need_structure","name":"Structure","category":"needs","percentile":0.7456082872690646,"raw_score":0.7139823598365089}],"values":[{"trait_id":"value_conservation","name":"Conservation","category":"values","percentile":0.8926822285613875,"raw_score":0.7213530818742335},{"trait_id":"value_openness_to_change","name":"Openness to change","category":"values","percentile":0.8575991638808613,"raw_score":0.825513084313229},{"trait_id":"value_hedonism","name":"Hedonism","category":"values","percentile":0.44128086884054324,"raw_score":0.7287543244960342},{"trait_id":"value_self_enhancement","name":"Self-enhancement","category":"values","percentile":0.6458578881392593,"raw_score":0.7227461699193419},{"trait_id":"value_self_transcendence","name":"Self-transcendence","category":"values","percentile":0.8237769534534466,"raw_score":0.8481040055218539}],"behavior":[{"trait_id":"behavior_sunday","name":"Sunday","category":"behavior","percentage":0.21392532795156408},{"trait_id":"behavior_monday","name":"Monday","category":"behavior","percentage":0.425832492431887},{"trait_id":"behavior_tuesday","name":"Tuesday","category":"behavior","percentage":0.07164480322906155},{"trait_id":"behavior_wednesday","name":"Wednesday","category":"behavior","percentage":0.011099899091826439},{"trait_id":"behavior_thursday","name":"Thursday","category":"behavior","percentage":0.12209889001009082},{"trait_id":"behavior_friday","name":"Friday","category":"behavior","percentage":0.07769929364278506},{"trait_id":"behavior_saturday","name":"Saturday","category":"behavior","percentage":0.07769929364278506},{"trait_id":"behavior_0000","name":"0:00 am","category":"behavior","percentage":0.45610494450050454},{"trait_id":"behavior_0100","name":"1:00 am","category":"behavior","percentage":0.12209889001009082},{"trait_id":"behavior_0200","name":"2:00 am","category":"behavior","percentage":0.02119071644803229},{"trait_id":"behavior_0300","name":"3:00 am","category":"behavior","percentage":0.09485368314833502},{"trait_id":"behavior_0400","name":"4:00 am","category":"behavior","percentage":0.020181634712411706},{"trait_id":"behavior_0500","name":"5:00 am","category":"behavior","percentage":0.0},{"trait_id":"behavior_0600","name":"6:00 am","category":"behavior","percentage":0.0},{"trait_id":"behavior_0700","name":"7:00 am","category":"behavior","percentage":0.011099899091826439},{"trait_id":"behavior_0800","name":"8:00 am","category":"behavior","percentage":0.0},{"trait_id":"behavior_0900","name":"9:00 am","category":"behavior","percentage":0.0},{"trait_id":"behavior_1000","name":"10:00 am","category":"behavior","percentage":0.0},{"trait_id":"behavior_1100","name":"11:00 am","category":"behavior","percentage":0.0},{"trait_id":"behavior_1200","name":"12:00 pm","category":"behavior","percentage":0.0},{"trait_id":"behavior_1300","name":"1:00 pm","category":"behavior","percentage":0.0},{"trait_id":"behavior_1400","name":"2:00 pm","category":"behavior","percentage":0.0},{"trait_id":"behavior_1500","name":"3:00 pm","category":"behavior","percentage":0.022199798183652877},{"trait_id":"behavior_1600","name":"4:00 pm","category":"behavior","percentage":0.022199798183652877},{"trait_id":"behavior_1700","name":"5:00 pm","category":"behavior","percentage":0.03229061553985873},{"trait_id":"behavior_1800","name":"6:00 pm","category":"behavior","percentage":0.010090817356205853},{"trait_id":"behavior_1900","name":"7:00 pm","category":"behavior","percentage":0.011099899091826439},{"trait_id":"behavior_2000","name":"8:00 pm","category":"behavior","percentage":0.022199798183652877},{"trait_id":"behavior_2100","name":"9:00 pm","category":"behavior","percentage":0.0},{"trait_id":"behavior_2200","name":"10:00 pm","category":"behavior","percentage":0.03128153380423814},{"trait_id":"behavior_2300","name":"11:00 pm","category":"behavior","percentage":0.1231079717457114}],"consumption_preferences":[{"consumption_preference_category_id":"consumption_preferences_shopping","name":"Purchasing Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_automobile_ownership_cost","name":"Likely to be sensitive to ownership cost when buying automobiles","score":0.0},{"consumption_preference_id":"consumption_preferences_automobile_safety","name":"Likely to prefer safety when buying automobiles","score":0.5},{"consumption_preference_id":"consumption_preferences_automobile_resale_value","name":"Likely to prefer resale value when buying automobiles","score":1.0},{"consumption_preference_id":"consumption_preferences_clothes_quality","name":"Likely to prefer quality when buying clothes","score":0.0},{"consumption_preference_id":"consumption_preferences_clothes_style","name":"Likely to prefer style when buying clothes","score":1.0},{"consumption_preference_id":"consumption_preferences_clothes_comfort","name":"Likely to prefer comfort when buying clothes","score":0.0},{"consumption_preference_id":"consumption_preferences_influence_brand_name","name":"Likely to be influenced by brand name when making product purchases","score":0.5},{"consumption_preference_id":"consumption_preferences_influence_utility","name":"Likely to be influenced by product utility when making product purchases","score":0.5},{"consumption_preference_id":"consumption_preferences_influence_online_ads","name":"Likely to be influenced by online ads when making product purchases","score":1.0},{"consumption_preference_id":"consumption_preferences_influence_social_media","name":"Likely to be influenced by social media when making product purchases","score":1.0},{"consumption_preference_id":"consumption_preferences_influence_family_members","name":"Likely to be influenced by family when making product purchases","score":1.0},{"consumption_preference_id":"consumption_preferences_spur_of_moment","name":"Likely to indulge in spur of the moment purchases","score":0.5},{"consumption_preference_id":"consumption_preferences_credit_card_payment","name":"Likely to prefer using credit cards for shopping","score":0.0}]},{"consumption_preference_category_id":"consumption_preferences_health_and_activity","name":"Health & Activity Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_eat_out","name":"Likely to eat out frequently","score":1.0},{"consumption_preference_id":"consumption_preferences_fast_food_frequency","name":"Likely to eat fast food frequently","score":1.0},{"consumption_preference_id":"consumption_preferences_gym_membership","name":"Likely to have a gym membership","score":1.0},{"consumption_preference_id":"consumption_preferences_adventurous_sports","name":"Likely to like adventurous sports","score":1.0},{"consumption_preference_id":"consumption_preferences_outdoor","name":"Likely to like outdoor activities","score":0.0}]},{"consumption_preference_category_id":"consumption_preferences_environmental_concern","name":"Environmental Concern Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_concerned_environment","name":"Likely to be concerned about the environment","score":0.0}]},{"consumption_preference_category_id":"consumption_preferences_entrepreneurship","name":"Entrepreneurship Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_start_business","name":"Likely to consider starting a business in next few years","score":1.0}]},{"consumption_preference_category_id":"consumption_preferences_movie","name":"Movie Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_movie_romance","name":"Likely to like romance movies","score":1.0},{"consumption_preference_id":"consumption_preferences_movie_adventure","name":"Likely to like adventure movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_horror","name":"Likely to like horror movies","score":1.0},{"consumption_preference_id":"consumption_preferences_movie_musical","name":"Likely to like musical movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_historical","name":"Likely to like historical movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_science_fiction","name":"Likely to like science-fiction movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_war","name":"Likely to like war movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_drama","name":"Likely to like drama movies","score":1.0},{"consumption_preference_id":"consumption_preferences_movie_action","name":"Likely to like action movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_documentary","name":"Likely to like documentary movies","score":0.0}]},{"consumption_preference_category_id":"consumption_preferences_music","name":"Music Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_music_rap","name":"Likely to like rap music","score":1.0},{"consumption_preference_id":"consumption_preferences_music_country","name":"Likely to like country music","score":1.0},{"consumption_preference_id":"consumption_preferences_music_r_b","name":"Likely to like R&B music","score":1.0},{"consumption_preference_id":"consumption_preferences_music_hip_hop","name":"Likely to like hip hop music","score":1.0},{"consumption_preference_id":"consumption_preferences_music_live_event","name":"Likely to attend live musical events","score":0.0},{"consumption_preference_id":"consumption_preferences_music_playing","name":"Likely to have experience playing music","score":0.0},{"consumption_preference_id":"consumption_preferences_music_latin","name":"Likely to like Latin music","score":1.0},{"consumption_preference_id":"consumption_preferences_music_rock","name":"Likely to like rock music","score":0.0},{"consumption_preference_id":"consumption_preferences_music_classical","name":"Likely to like classical music","score":0.0}]},{"consumption_preference_category_id":"consumption_preferences_reading","name":"Reading Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_read_frequency","name":"Likely to read often","score":0.0},{"consumption_preference_id":"consumption_preferences_read_motive_enjoyment","name":"Likely to read for enjoyment","score":0.0},{"consumption_preference_id":"consumption_preferences_read_motive_information","name":"Likely to read for information","score":0.0},{"consumption_preference_id":"consumption_preferences_books_entertainment_magazines","name":"Likely to read entertainment magazines","score":1.0},{"consumption_preference_id":"consumption_preferences_books_non_fiction","name":"Likely to read non-fiction books","score":0.0},{"consumption_preference_id":"consumption_preferences_read_motive_mandatory","name":"Likely to do mandatory reading only","score":1.0},{"consumption_preference_id":"consumption_preferences_read_motive_relaxation","name":"Likely to read for relaxation","score":1.0},{"consumption_preference_id":"consumption_preferences_books_financial_investing","name":"Likely to read financial investment books","score":1.0},{"consumption_preference_id":"consumption_preferences_books_autobiographies","name":"Likely to read autobiographical books","score":0.0}]},{"consumption_preference_category_id":"consumption_preferences_volunteering","name":"Volunteering Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_volunteer","name":"Likely to volunteer for social causes","score":0.0},{"consumption_preference_id":"consumption_preferences_volunteering_time","name":"Likely to have spent time volunteering","score":1.0},{"consumption_preference_id":"consumption_preferences_volunteer_learning","name":"Likely to volunteer to learn about social causes","score":0.0}]}],"warnings":[]} diff --git a/resources/personality-v3-expect3.txt b/resources/personality-v3-expect3.txt deleted file mode 100755 index ce84fc476..000000000 --- a/resources/personality-v3-expect3.txt +++ /dev/null @@ -1,2 +0,0 @@ -big5_agreeableness,facet_altruism,facet_cooperation,facet_modesty,facet_morality,facet_sympathy,facet_trust,big5_conscientiousness,facet_achievement_striving,facet_cautiousness,facet_dutifulness,facet_orderliness,facet_self_discipline,facet_self_efficacy,big5_extraversion,facet_activity_level,facet_assertiveness,facet_cheerfulness,facet_excitement_seeking,facet_friendliness,facet_gregariousness,big5_neuroticism,facet_anger,facet_anxiety,facet_depression,facet_immoderation,facet_self_consciousness,facet_vulnerability,big5_openness,facet_adventurousness,facet_artistic_interests,facet_emotionality,facet_imagination,facet_intellect,facet_liberalism,need_liberty,need_ideal,need_love,need_practicality,need_self_expression,need_stability,need_structure,need_challenge,need_closeness,need_curiosity,need_excitement,need_harmony,value_conservation,value_hedonism,value_openness_to_change,value_self_enhancement,value_self_transcendence,behavior_sunday,behavior_monday,behavior_tuesday,behavior_wednesday,behavior_thursday,behavior_friday,behavior_saturday,behavior_0000,behavior_0100,behavior_0200,behavior_0300,behavior_0400,behavior_0500,behavior_0600,behavior_0700,behavior_0800,behavior_0900,behavior_1000,behavior_1100,behavior_1200,behavior_1300,behavior_1400,behavior_1500,behavior_1600,behavior_1700,behavior_1800,behavior_1900,behavior_2000,behavior_2100,behavior_2200,behavior_2300,word_count,processed_language,big5_agreeableness_raw,facet_altruism_raw,facet_cooperation_raw,facet_modesty_raw,facet_morality_raw,facet_sympathy_raw,facet_trust_raw,big5_conscientiousness_raw,facet_achievement_striving_raw,facet_cautiousness_raw,facet_dutifulness_raw,facet_orderliness_raw,facet_self_discipline_raw,facet_self_efficacy_raw,big5_extraversion_raw,facet_activity_level_raw,facet_assertiveness_raw,facet_cheerfulness_raw,facet_excitement_seeking_raw,facet_friendliness_raw,facet_gregariousness_raw,big5_neuroticism_raw,facet_anger_raw,facet_anxiety_raw,facet_depression_raw,facet_immoderation_raw,facet_self_consciousness_raw,facet_vulnerability_raw,big5_openness_raw,facet_adventurousness_raw,facet_artistic_interests_raw,facet_emotionality_raw,facet_imagination_raw,facet_intellect_raw,facet_liberalism_raw,need_liberty_raw,need_ideal_raw,need_love_raw,need_practicality_raw,need_self_expression_raw,need_stability_raw,need_structure_raw,need_challenge_raw,need_closeness_raw,need_curiosity_raw,need_excitement_raw,need_harmony_raw,value_conservation_raw,value_hedonism_raw,value_openness_to_change_raw,value_self_enhancement_raw,value_self_transcendence_raw,consumption_preferences_spur_of_moment,consumption_preferences_credit_card_payment,consumption_preferences_influence_brand_name,consumption_preferences_influence_utility,consumption_preferences_influence_online_ads,consumption_preferences_influence_social_media,consumption_preferences_influence_family_members,consumption_preferences_clothes_quality,consumption_preferences_clothes_style,consumption_preferences_clothes_comfort,consumption_preferences_automobile_ownership_cost,consumption_preferences_automobile_safety,consumption_preferences_automobile_resale_value,consumption_preferences_music_rap,consumption_preferences_music_country,consumption_preferences_music_r_b,consumption_preferences_music_hip_hop,consumption_preferences_music_live_event,consumption_preferences_music_playing,consumption_preferences_music_latin,consumption_preferences_music_rock,consumption_preferences_music_classical,consumption_preferences_gym_membership,consumption_preferences_adventurous_sports,consumption_preferences_outdoor,consumption_preferences_eat_out,consumption_preferences_fast_food_frequency,consumption_preferences_movie_romance,consumption_preferences_movie_adventure,consumption_preferences_movie_horror,consumption_preferences_movie_musical,consumption_preferences_movie_historical,consumption_preferences_movie_science_fiction,consumption_preferences_movie_war,consumption_preferences_movie_drama,consumption_preferences_movie_action,consumption_preferences_movie_documentary,consumption_preferences_read_frequency,consumption_preferences_read_motive_enjoyment,consumption_preferences_read_motive_information,consumption_preferences_read_motive_mandatory,consumption_preferences_read_motive_relaxation,consumption_preferences_books_entertainment_magazines,consumption_preferences_books_non_fiction,consumption_preferences_books_financial_investing,consumption_preferences_books_autobiographies,consumption_preferences_volunteer,consumption_preferences_volunteering_time,consumption_preferences_volunteer_learning,consumption_preferences_concerned_environment,consumption_preferences_start_business -0.1875352860319472,0.9713302006331768,0.8229934901276204,0.761318814834163,0.9471478882849421,0.9991179451374892,0.830111046812001,0.986401677449357,0.8403728912342907,0.944186945742299,0.7946276293038717,0.7610741506407186,0.712864917583896,0.6994302718651364,0.08530058556548259,0.962401631341592,0.9198609213386704,0.2293639969883699,0.21024192850794732,0.7085191412979603,0.22458619358372,0.9438564164580463,0.013938100678608567,0.062025789454073055,0.35285841125133055,0.011684379342279061,0.19347068940127837,0.06994539774378672,0.9970814244982864,0.7897453561510369,0.9946576519208279,0.7671631753694098,0.3116772371947326,0.9965199807027891,0.797907272149325,0.10802987716456186,0.02263412995273062,0.01189533382101321,0.018888178951272983,0.18489782806561655,0.3946227431440047,0.8880129689346332,0.0032546536914939694,0.37022781101806856,0.845180482624851,0.11505596926601303,0.4664217424750215,0.5065929218618456,0.005253658217920731,0.6287516949462554,0.0011936431143393933,0.3429609693883737,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1365,en,0.7069355244930271,0.7717679751112927,0.6352286286618323,0.4858691141214019,0.702145642516,0.7828928930725229,0.6251288245815745,0.731065896229928,0.7411306938189824,0.5929015783660554,0.6790451583920154,0.5174048448459116,0.5974142772332323,0.7714843433917522,0.4898595875512197,0.6314221244549749,0.7142519242541164,0.5932729161331092,0.5694475628767053,0.5880272412488141,0.4144362156057161,0.5568839124901138,0.41546033577632724,0.489225611469312,0.42452148443292836,0.41344777510142944,0.5011894182219927,0.37357140402417355,0.83666730981323,0.5334674872694041,0.7945583831155767,0.677937382446223,0.7104655052955525,0.7321638770376435,0.5582434731245067,0.6901684496009852,0.5959081695663969,0.6586965498215966,0.6828926516103326,0.6441012500714469,0.7259366269839532,0.7290291261454519,0.6097534338543016,0.7786579590270303,0.8433898277044034,0.5898767782432288,0.8063478875213775,0.6661941759119986,0.5746924423258591,0.7969374222994671,0.5730785322934739,0.8263720901347662,0.0,1.0,0.0,1.0,1.0,0.0,1.0,1.0,0.0,1.0,0.5,0.0,1.0,0.0,0.5,1.0,0.5,0.0,0.0,1.0,0.5,1.0,0.0,0.0,0.5,0.0,0.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,1.0,1.0,1.0,1.0,1.0,0.0,1.0,0.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0,0.5 diff --git a/resources/personality-v3-expect4.txt b/resources/personality-v3-expect4.txt deleted file mode 100755 index cefac606d..000000000 --- a/resources/personality-v3-expect4.txt +++ /dev/null @@ -1 +0,0 @@ -{"word_count":2054,"processed_language":"es","personality":[{"trait_id":"big5_openness","name":"Apertura a experiencias","category":"personality","percentile":0.937254665925888,"raw_score":0.6665054437659199,"children":[{"trait_id":"facet_adventurousness","name":"Audacia","category":"personality","percentile":0.08223746859291331,"raw_score":0.42933795357475174},{"trait_id":"facet_artistic_interests","name":"Intereses artísticos","category":"personality","percentile":0.9763304400942869,"raw_score":0.7002492316426583},{"trait_id":"facet_emotionality","name":"Emocionalidad","category":"personality","percentile":0.7514798288441382,"raw_score":0.6329457809108067},{"trait_id":"facet_imagination","name":"Imaginación","category":"personality","percentile":0.8149758845160733,"raw_score":0.8358450161141352},{"trait_id":"facet_intellect","name":"Intelecto","category":"personality","percentile":0.709763785945054,"raw_score":0.5393985514175461},{"trait_id":"facet_liberalism","name":"Desafío a la autoridad","category":"personality","percentile":0.6238685851515903,"raw_score":0.5032730384879351}]},{"trait_id":"big5_conscientiousness","name":"Responsabilidad","category":"personality","percentile":0.8652601748372407,"raw_score":0.5675610518817606,"children":[{"trait_id":"facet_achievement_striving","name":"Necesidad de éxito","category":"personality","percentile":0.8616153196657172,"raw_score":0.5590390364812622},{"trait_id":"facet_cautiousness","name":"Cautela","category":"personality","percentile":0.8107894835477681,"raw_score":0.3956917603116589},{"trait_id":"facet_dutifulness","name":"Obediencia","category":"personality","percentile":0.7361183850960512,"raw_score":0.6242547149850359},{"trait_id":"facet_orderliness","name":"Disciplina","category":"personality","percentile":0.7239663954817621,"raw_score":0.4064822536153153},{"trait_id":"facet_self_discipline","name":"Autodisciplina","category":"personality","percentile":0.7198280681937614,"raw_score":0.5069844967090522},{"trait_id":"facet_self_efficacy","name":"Autoeficacia","category":"personality","percentile":0.6555485467551172,"raw_score":0.7166506366360331}]},{"trait_id":"big5_extraversion","name":"Extroversión","category":"personality","percentile":0.8312616324634844,"raw_score":0.5904152727753278,"children":[{"trait_id":"facet_activity_level","name":"Nivel de actividad","category":"personality","percentile":0.3050469697893306,"raw_score":0.48428799368416525},{"trait_id":"facet_assertiveness","name":"Seguridad en uno mismo","category":"personality","percentile":0.8397260688330984,"raw_score":0.6518273502161546},{"trait_id":"facet_cheerfulness","name":"Alegría","category":"personality","percentile":0.15273505645350988,"raw_score":0.6248204372077145},{"trait_id":"facet_excitement_seeking","name":"Búsqueda de emociones","category":"personality","percentile":0.7847013019475804,"raw_score":0.6442345985222767},{"trait_id":"facet_friendliness","name":"Simpatía","category":"personality","percentile":0.4308672854960358,"raw_score":0.5713958380902632},{"trait_id":"facet_gregariousness","name":"Sociabilidad","category":"personality","percentile":0.14583775819539813,"raw_score":0.4718274671256566}]},{"trait_id":"big5_agreeableness","name":"Amabilidad","category":"personality","percentile":0.964097852599053,"raw_score":0.6531530954966219,"children":[{"trait_id":"facet_altruism","name":"Altruismo","category":"personality","percentile":0.8454904962948867,"raw_score":0.6988130323165977},{"trait_id":"facet_cooperation","name":"Cooperación","category":"personality","percentile":0.7090285746898252,"raw_score":0.5034689841495227},{"trait_id":"facet_modesty","name":"Modestia","category":"personality","percentile":0.3356036734453778,"raw_score":0.37505142742666475},{"trait_id":"facet_morality","name":"Intransigencia","category":"personality","percentile":0.5970727450220207,"raw_score":0.5626043098951097},{"trait_id":"facet_sympathy","name":"Compasión","category":"personality","percentile":0.8405910443888318,"raw_score":0.6703129231871922},{"trait_id":"facet_trust","name":"Confianza","category":"personality","percentile":0.7434899651065617,"raw_score":0.584058726755165}]},{"trait_id":"big5_neuroticism","name":"Rango emocional","category":"personality","percentile":0.5289409694752685,"raw_score":0.487815337385794,"children":[{"trait_id":"facet_anger","name":"Vehemencia","category":"personality","percentile":0.49899417826927367,"raw_score":0.5721035977629064},{"trait_id":"facet_anxiety","name":"Tendencia a la preocupación","category":"personality","percentile":0.3288266523535158,"raw_score":0.7282190556201247},{"trait_id":"facet_depression","name":"Melancolía","category":"personality","percentile":0.29056657042415834,"raw_score":0.514863148159452},{"trait_id":"facet_immoderation","name":"Desmesura","category":"personality","percentile":0.4768272523338591,"raw_score":0.49394240481419255},{"trait_id":"facet_self_consciousness","name":"Timidez","category":"personality","percentile":0.41952877081366,"raw_score":0.5533629213910396},{"trait_id":"facet_vulnerability","name":"Susceptibilidad a la tensión","category":"personality","percentile":0.8928596088709371,"raw_score":0.7197355877820822}]}],"needs":[{"trait_id":"need_challenge","name":"Desafío","category":"needs","percentile":0.559611972188894,"raw_score":0.748742086057447},{"trait_id":"need_closeness","name":"Familiaridad","category":"needs","percentile":0.8955577050509591,"raw_score":0.8040722237206381},{"trait_id":"need_curiosity","name":"Curiosidad","category":"needs","percentile":0.09726991406313656,"raw_score":0.7301955596902647},{"trait_id":"need_excitement","name":"Entusiasmo","category":"needs","percentile":0.13382056325102437,"raw_score":0.7037297990204079},{"trait_id":"need_harmony","name":"Armonía","category":"needs","percentile":0.9573838279593837,"raw_score":0.8680468150331786},{"trait_id":"need_ideal","name":"Ideal","category":"needs","percentile":0.21515556100273503,"raw_score":0.6132355010854986},{"trait_id":"need_liberty","name":"Libertad","category":"needs","percentile":0.7345204750013818,"raw_score":0.7668148207046253},{"trait_id":"need_love","name":"Amor","category":"needs","percentile":0.279330012389927,"raw_score":0.7401357410740972},{"trait_id":"need_practicality","name":"Practicidad","category":"needs","percentile":0.9519859431515265,"raw_score":0.8152097612302944},{"trait_id":"need_self_expression","name":"Autoexpresión","category":"needs","percentile":0.45551641520878955,"raw_score":0.6552372473325437},{"trait_id":"need_stability","name":"Estabilidad","category":"needs","percentile":0.7890941903595212,"raw_score":0.7155622088047298},{"trait_id":"need_structure","name":"Estructura","category":"needs","percentile":0.8701561216649387,"raw_score":0.6872552118295897}],"values":[{"trait_id":"value_conservation","name":"Conservación","category":"values","percentile":0.7229840083480119,"raw_score":0.6823055252116184},{"trait_id":"value_openness_to_change","name":"Apertura al cambio","category":"values","percentile":0.25516943326837055,"raw_score":0.7776804808576244},{"trait_id":"value_hedonism","name":"Hedonismo","category":"values","percentile":0.2642599286231329,"raw_score":0.7968264374887243},{"trait_id":"value_self_enhancement","name":"Superación personal","category":"values","percentile":0.14635996017074898,"raw_score":0.6187436884883577},{"trait_id":"value_self_transcendence","name":"Autotranscendencia","category":"values","percentile":0.7717967307009796,"raw_score":0.8563743707155973}],"consumption_preferences":[{"consumption_preference_category_id":"consumption_preferences_shopping","name":"Purchasing Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_automobile_ownership_cost","name":"Likely to be sensitive to ownership cost when buying automobiles","score":0.0},{"consumption_preference_id":"consumption_preferences_automobile_safety","name":"Likely to prefer safety when buying automobiles","score":1.0},{"consumption_preference_id":"consumption_preferences_automobile_resale_value","name":"Likely to prefer resale value when buying automobiles","score":1.0},{"consumption_preference_id":"consumption_preferences_clothes_quality","name":"Likely to prefer quality when buying clothes","score":1.0},{"consumption_preference_id":"consumption_preferences_clothes_style","name":"Likely to prefer style when buying clothes","score":0.0},{"consumption_preference_id":"consumption_preferences_clothes_comfort","name":"Likely to prefer comfort when buying clothes","score":0.0},{"consumption_preference_id":"consumption_preferences_influence_brand_name","name":"Likely to be influenced by brand name when making product purchases","score":1.0},{"consumption_preference_id":"consumption_preferences_influence_utility","name":"Likely to be influenced by product utility when making product purchases","score":0.5},{"consumption_preference_id":"consumption_preferences_influence_online_ads","name":"Likely to be influenced by online ads when making product purchases","score":1.0},{"consumption_preference_id":"consumption_preferences_influence_social_media","name":"Likely to be influenced by social media when making product purchases","score":1.0},{"consumption_preference_id":"consumption_preferences_influence_family_members","name":"Likely to be influenced by family when making product purchases","score":1.0},{"consumption_preference_id":"consumption_preferences_spur_of_moment","name":"Likely to indulge in spur of the moment purchases","score":0.5},{"consumption_preference_id":"consumption_preferences_credit_card_payment","name":"Likely to prefer using credit cards for shopping","score":1.0}]},{"consumption_preference_category_id":"consumption_preferences_health_and_activity","name":"Health & Activity Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_eat_out","name":"Likely to eat out frequently","score":0.0},{"consumption_preference_id":"consumption_preferences_fast_food_frequency","name":"Likely to eat fast food frequently","score":0.5},{"consumption_preference_id":"consumption_preferences_gym_membership","name":"Likely to have a gym membership","score":0.0},{"consumption_preference_id":"consumption_preferences_adventurous_sports","name":"Likely to like adventurous sports","score":1.0},{"consumption_preference_id":"consumption_preferences_outdoor","name":"Likely to like outdoor activities","score":0.0}]},{"consumption_preference_category_id":"consumption_preferences_environmental_concern","name":"Environmental Concern Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_concerned_environment","name":"Likely to be concerned about the environment","score":0.5}]},{"consumption_preference_category_id":"consumption_preferences_entrepreneurship","name":"Entrepreneurship Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_start_business","name":"Likely to consider starting a business in next few years","score":1.0}]},{"consumption_preference_category_id":"consumption_preferences_movie","name":"Movie Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_movie_romance","name":"Likely to like romance movies","score":1.0},{"consumption_preference_id":"consumption_preferences_movie_adventure","name":"Likely to like adventure movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_horror","name":"Likely to like horror movies","score":1.0},{"consumption_preference_id":"consumption_preferences_movie_musical","name":"Likely to like musical movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_historical","name":"Likely to like historical movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_science_fiction","name":"Likely to like science-fiction movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_war","name":"Likely to like war movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_drama","name":"Likely to like drama movies","score":1.0},{"consumption_preference_id":"consumption_preferences_movie_action","name":"Likely to like action movies","score":0.0},{"consumption_preference_id":"consumption_preferences_movie_documentary","name":"Likely to like documentary movies","score":0.0}]},{"consumption_preference_category_id":"consumption_preferences_music","name":"Music Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_music_rap","name":"Likely to like rap music","score":1.0},{"consumption_preference_id":"consumption_preferences_music_country","name":"Likely to like country music","score":1.0},{"consumption_preference_id":"consumption_preferences_music_r_b","name":"Likely to like R&B music","score":1.0},{"consumption_preference_id":"consumption_preferences_music_hip_hop","name":"Likely to like hip hop music","score":1.0},{"consumption_preference_id":"consumption_preferences_music_live_event","name":"Likely to attend live musical events","score":0.0},{"consumption_preference_id":"consumption_preferences_music_playing","name":"Likely to have experience playing music","score":0.0},{"consumption_preference_id":"consumption_preferences_music_latin","name":"Likely to like Latin music","score":0.0},{"consumption_preference_id":"consumption_preferences_music_rock","name":"Likely to like rock music","score":0.5},{"consumption_preference_id":"consumption_preferences_music_classical","name":"Likely to like classical music","score":0.0}]},{"consumption_preference_category_id":"consumption_preferences_reading","name":"Reading Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_read_frequency","name":"Likely to read often","score":0.5},{"consumption_preference_id":"consumption_preferences_read_motive_enjoyment","name":"Likely to read for enjoyment","score":0.0},{"consumption_preference_id":"consumption_preferences_read_motive_information","name":"Likely to read for information","score":0.0},{"consumption_preference_id":"consumption_preferences_books_entertainment_magazines","name":"Likely to read entertainment magazines","score":1.0},{"consumption_preference_id":"consumption_preferences_books_non_fiction","name":"Likely to read non-fiction books","score":1.0},{"consumption_preference_id":"consumption_preferences_read_motive_mandatory","name":"Likely to do mandatory reading only","score":0.0},{"consumption_preference_id":"consumption_preferences_read_motive_relaxation","name":"Likely to read for relaxation","score":1.0},{"consumption_preference_id":"consumption_preferences_books_financial_investing","name":"Likely to read financial investment books","score":0.0},{"consumption_preference_id":"consumption_preferences_books_autobiographies","name":"Likely to read autobiographical books","score":0.0}]},{"consumption_preference_category_id":"consumption_preferences_volunteering","name":"Volunteering Preferences","consumption_preferences":[{"consumption_preference_id":"consumption_preferences_volunteer","name":"Likely to volunteer for social causes","score":0.0},{"consumption_preference_id":"consumption_preferences_volunteering_time","name":"Likely to have spent time volunteering","score":0.0},{"consumption_preference_id":"consumption_preferences_volunteer_learning","name":"Likely to volunteer to learn about social causes","score":0.0}]}],"warnings":[]} diff --git a/resources/personality-v3.json b/resources/personality-v3.json deleted file mode 100755 index 5b6c5d1a1..000000000 --- a/resources/personality-v3.json +++ /dev/null @@ -1,6941 +0,0 @@ -{ - "contentItems": [ - { - "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass", - "contenttype": "text/plain", - "created": 1447639154000, - "id": "666073008692314113", - "language": "en" - }, - { - "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass", - "contenttype": "text/plain", - "created": 1447638226000, - "id": "666069114889179136", - "language": "en" - }, - { - "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass", - "contenttype": "text/plain", - "created": 1447638067000, - "id": "666068446325665792", - "language": "en" - }, - { - "content": "Wow aren't you loving @TheRock and his candor? #Masterclass", - "contenttype": "text/plain", - "created": 1447637459000, - "id": "666065895932973057", - "language": "en" - }, - { - "content": "RT @patt_t: @TheRock @Oprah @RichOnOWN @OWNTV this interview makes me like you as a fellow human even more for being so real.", - "contenttype": "text/plain", - "created": 1447637030000, - "id": "666064097562247168", - "language": "en" - }, - { - "content": "\"Be You\".. That's the best advice ever @TheRock #MastersClass", - "contenttype": "text/plain", - "created": 1447636205000, - "id": "666060637181644800", - "language": "en" - }, - { - "content": "Supersoulers let's lift our spirits pray and hold Paris in the Light\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1447602477000, - "id": "665919171062927360", - "language": "en" - }, - { - "content": "RT @DeepakChopra: What I learned in week 1: Become What You Believe 21-Day Meditation Experience - https:\/\/t.co\/kqaMaMqEUp #GoogleAlerts", - "contenttype": "text/plain", - "created": 1447098990000, - "id": "663807393063538688", - "language": "en" - }, - { - "content": "Watching Bryan Stevenson on #SuperSoulSunday! \"You are not the worst mistake you ever made\".\nAren't we glad about that.", - "contenttype": "text/plain", - "created": 1446998643000, - "id": "663386507856736257", - "language": "en" - }, - { - "content": ".@CherylStrayed BRAVE ENOUGH my new favorite thing! Gonna buy a copy for all my girls. #Perfectgift https:\/\/t.co\/gz1tnv8t8K", - "contenttype": "text/plain", - "created": 1446915955000, - "id": "663039689360695296", - "language": "en" - }, - { - "content": "Stevie Wonder singing \"Happy Birthday to you!\" to my dear mariashriver. A phenomenal woman and\u2026 https:\/\/t.co\/Ygm5eDIs4f", - "contenttype": "text/plain", - "created": 1446881193000, - "id": "662893888080879616", - "language": "en" - }, - { - "content": "It\u2019s my faaaaavorite time of the Year! For the first time you can shop the list on @amazon! https:\/\/t.co\/a6GMvVrhjN https:\/\/t.co\/sJlQMROq5U", - "contenttype": "text/plain", - "created": 1446744186000, - "id": "662319239844380672", - "language": "en" - }, - { - "content": "Incredible story \"the spirit of the Lord is on you\" thanks for sharing @smokey_robinson #Masterclass", - "contenttype": "text/plain", - "created": 1446428929000, - "id": "660996956861280256", - "language": "en" - }, - { - "content": "Wasnt that incredible story about @smokey_robinson 's dad leaving his family at 12. #MasterClass", - "contenttype": "text/plain", - "created": 1446426630000, - "id": "660987310889041920", - "language": "en" - }, - { - "content": "Gayle, Charlie, Nora @CBSThisMorning Congratulations! #1000thshow", - "contenttype": "text/plain", - "created": 1446220097000, - "id": "660121050978611205", - "language": "en" - }, - { - "content": "I believe your home should rise up to meet you. @TheEllenShow you nailed it with HOME. Tweethearts, grab a copy! https:\/\/t.co\/iFMnpRAsno", - "contenttype": "text/plain", - "created": 1446074433000, - "id": "659510090748182528", - "language": "en" - }, - { - "content": "Can I get a Witness?!\u270b\ud83c\udffe https:\/\/t.co\/tZ1QyAeSdE", - "contenttype": "text/plain", - "created": 1445821114000, - "id": "658447593865945089", - "language": "en" - }, - { - "content": ".@TheEllenShow you're a treasure.\nYour truth set a lot of people free.\n#Masterclass", - "contenttype": "text/plain", - "created": 1445821003000, - "id": "658447130026188800", - "language": "en" - }, - { - "content": "Hope you all are enjoying @TheEllenShow on #MasterClass.", - "contenttype": "text/plain", - "created": 1445820161000, - "id": "658443598313181188", - "language": "en" - }, - { - "content": ".@GloriaSteinem, shero to women everywhere, on how far we\u2019ve come and how far we need to go. #SuperSoulSunday 7p\/6c.\nhttps:\/\/t.co\/3e7oxXW02J", - "contenttype": "text/plain", - "created": 1445811545000, - "id": "658407457438363648", - "language": "en" - }, - { - "content": "RT @TheEllenShow: I told a story from my @OWNTV's #MasterClass on my show. Normally I\u2019d save it all for Sunday, but @Oprah made me. https:\/\u2026", - "contenttype": "text/plain", - "created": 1445804181000, - "id": "658376572521459712", - "language": "en" - }, - { - "content": ".@TheEllenShow is a master teacher of living her truth & living authentically as herself. #MasterClass tonight 8\/7c.\nhttps:\/\/t.co\/iLT2KgRsSw", - "contenttype": "text/plain", - "created": 1445804072000, - "id": "658376116575449088", - "language": "en" - }, - { - "content": ".@SheriSalata , @jonnysinc @part2pictures . Tears of joy and gratitude to you and our entire #BeliefTeam We DID IT!! My heart is full.\ud83d\ude4f\ud83c\udffe\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1445734755000, - "id": "658085377140363264", - "language": "en" - }, - { - "content": "Donna and Bob saw the tape of their story just days before she passed. They appreciated it. #RIPDonna", - "contenttype": "text/plain", - "created": 1445734097000, - "id": "658082618819280896", - "language": "en" - }, - { - "content": "RT @rempower: .@Oprah this series allowed me to slide into people's lives around the world and see the same in them ... we all have a belie\u2026", - "contenttype": "text/plain", - "created": 1445732769000, - "id": "658077046858383360", - "language": "en" - }, - { - "content": "All the stories moved me, My favorite line \" I must pass the stories on to my grandson otherwise our people will loose their way. #Belief", - "contenttype": "text/plain", - "created": 1445732579000, - "id": "658076253618991104", - "language": "en" - }, - { - "content": ".@part2pictures some of your best imagery yet. Filming Alex on the rock.#Belief", - "contenttype": "text/plain", - "created": 1445731782000, - "id": "658072908237934592", - "language": "en" - }, - { - "content": "I just love Alex and his daring #Belief to live fully the present Moment.", - "contenttype": "text/plain", - "created": 1445731561000, - "id": "658071980982206464", - "language": "en" - }, - { - "content": "RT @GrowingOWN: Let's do this! #Belief finale tweet tweet party. Thank you @Oprah! \ud83d\ude4f", - "contenttype": "text/plain", - "created": 1445731248000, - "id": "658070668785770496", - "language": "en" - }, - { - "content": "RT @lizkinnell: The epic finale of #Belief on @OWNTV is about to start. 8\/et Are you ready? What do you Believe?", - "contenttype": "text/plain", - "created": 1445731081000, - "id": "658069968534171648", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night of Belief. Belief runs all day tomorrow for bingers and final episode!", - "contenttype": "text/plain", - "created": 1445648630000, - "id": "657724143115202560", - "language": "en" - }, - { - "content": "RT @OWNingLight: #Belief is the ultimate travel map to mass acceptance. \ud83d\ude4f\ud83c\udffb\u2764\ufe0f\ud83c\udf0d @Oprah", - "contenttype": "text/plain", - "created": 1445647285000, - "id": "657718501147197442", - "language": "en" - }, - { - "content": "\" I can feel my heart opening and faith coming back in\".. What's better than that? #Belief", - "contenttype": "text/plain", - "created": 1445646903000, - "id": "657716901951369218", - "language": "en" - }, - { - "content": "Hey Belief team mates can yo believe how quickly the week has passed? #Belief", - "contenttype": "text/plain", - "created": 1445645633000, - "id": "657711572492533760", - "language": "en" - }, - { - "content": "Ran into @5SOS backstage. Fun times with @TheEllenShow today! https:\/\/t.co\/2PP3W3RzXc", - "contenttype": "text/plain", - "created": 1445618531000, - "id": "657597898394173440", - "language": "en" - }, - { - "content": "Thanks All for another great night of #BELIEF", - "contenttype": "text/plain", - "created": 1445572548000, - "id": "657405031822430208", - "language": "en" - }, - { - "content": "RT @3LWTV: #BecomeWhatYouBelieve New meditation w\/ @Oprah @DeepakChopra begins 11\/2 Register https:\/\/t.co\/x0R9HWTAX0 #Belief https:\/\/t.co\/\u2026", - "contenttype": "text/plain", - "created": 1445571500000, - "id": "657400636745510912", - "language": "en" - }, - { - "content": "Ok west coast let's do it! #belief", - "contenttype": "text/plain", - "created": 1445569367000, - "id": "657391689439404033", - "language": "en" - }, - { - "content": "Thank u kind gentleman who told me I had kale in my teeth. Was eating kale chips with Quincy Jones. Went straight to @LairdLife party.", - "contenttype": "text/plain", - "created": 1445569296000, - "id": "657391393883619328", - "language": "en" - }, - { - "content": "Hello west coast twitterati.. See you at 8 for #Belief", - "contenttype": "text/plain", - "created": 1445566144000, - "id": "657378171872874496", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night.#Belief", - "contenttype": "text/plain", - "created": 1445475948000, - "id": "656999861254918145", - "language": "en" - }, - { - "content": "RT @PRanganathan: \"Transformation is the rule of the game. The universe is not standing still.\" - Marcelo @OWNTV @Oprah #Belief", - "contenttype": "text/plain", - "created": 1445475602000, - "id": "656998409933451264", - "language": "en" - }, - { - "content": "\"The Universe is not standing still.. The whole Universe is expanding\" I love the dance between science and spirituality! #Belief", - "contenttype": "text/plain", - "created": 1445475580000, - "id": "656998320133398528", - "language": "en" - }, - { - "content": "\"Without our prayers and our songs we won't be here\" Apache leader.#Belief", - "contenttype": "text/plain", - "created": 1445473768000, - "id": "656990717504393216", - "language": "en" - }, - { - "content": "Notice her mother crying. She knows its last tine she will ever see her daughter.#Belief", - "contenttype": "text/plain", - "created": 1445473150000, - "id": "656988127433637888", - "language": "en" - }, - { - "content": "This final trial is unbelievable. Every hair gets pulled from her head one at a time. Now that is Something!!#Belief", - "contenttype": "text/plain", - "created": 1445473063000, - "id": "656987763644891136", - "language": "en" - }, - { - "content": "\"What my faith gives me no one can match\"#Belief", - "contenttype": "text/plain", - "created": 1445472961000, - "id": "656987336266223616", - "language": "en" - }, - { - "content": "It's a devotion to faith beyond anything Ive seen. Fascinating.Jain nuns. #Belief", - "contenttype": "text/plain", - "created": 1445472531000, - "id": "656985529951522816", - "language": "en" - }, - { - "content": "I'd never heard of Jain monks and nuns before doing this series. #Belief", - "contenttype": "text/plain", - "created": 1445472393000, - "id": "656984953037586433", - "language": "en" - }, - { - "content": "Good evening Team #Belief the Tweet is on!", - "contenttype": "text/plain", - "created": 1445472098000, - "id": "656983714883239937", - "language": "en" - }, - { - "content": "Thanks everyone for another Epic #Belief night!", - "contenttype": "text/plain", - "created": 1445302792000, - "id": "656273592485810176", - "language": "en" - }, - { - "content": "The Pastor and Imam represent the possibility of PEACE in the world. If they can do it. We can. Peace to All\ud83d\ude4f\ud83c\udffe #Belief", - "contenttype": "text/plain", - "created": 1445302749000, - "id": "656273415280705536", - "language": "en" - }, - { - "content": "We felt privileged to film the Hajj and explore the beauty of Islam.\n#99namesforGod #Belief", - "contenttype": "text/plain", - "created": 1445301110000, - "id": "656266540967424000", - "language": "en" - }, - { - "content": "Do you all believe in \"soul mates\"?\n#Belief", - "contenttype": "text/plain", - "created": 1445300138000, - "id": "656262462426238976", - "language": "en" - }, - { - "content": ".@RevEdBacon thank you so much for hosting tonight's #Belief at All Saints Church.", - "contenttype": "text/plain", - "created": 1445299749000, - "id": "656260832628756480", - "language": "en" - }, - { - "content": "This is one of the best love stories I've ever seen. #belief Ian and Larissa showing us the depths of love.#Belief", - "contenttype": "text/plain", - "created": 1445299614000, - "id": "656260263604310016", - "language": "en" - }, - { - "content": "Hey Everyone .. Tweeting from a bar in Atlanta with @SheriSalata OWN not in my hotel. Anything for #Belief", - "contenttype": "text/plain", - "created": 1445299326000, - "id": "656259057758654464", - "language": "en" - }, - { - "content": "RT @joshuadubois: When you see Ian & Larissa tonight on #BELIEF, you'll know what Christian love is all about. 8pmET, @OWNTV. Tune in! http\u2026", - "contenttype": "text/plain", - "created": 1445295716000, - "id": "656243916224638976", - "language": "en" - }, - { - "content": "RT @KimHaleDance: I Believe LAUGHTER. IS. CONTAGIOUS. What do you believe? See you tonight! 8\/7c.\u2764\ufe0f #Belief #Beliefin3words https:\/\/t.co\/x\u2026", - "contenttype": "text/plain", - "created": 1445295702000, - "id": "656243854610337793", - "language": "en" - }, - { - "content": "RT @OWNTV: See the world through someone else\u2019s soul. The epic journey of #Belief continues tonight at 8\/7c.\nhttps:\/\/t.co\/UKKMHZuC0g", - "contenttype": "text/plain", - "created": 1445295668000, - "id": "656243714507931648", - "language": "en" - }, - { - "content": "RT @OWNTV: Mendel Hurwitz's inquisitive nature grounded him in his faith. See where it's taken him now: https:\/\/t.co\/2iWmNOxK9r https:\/\/t.c\u2026", - "contenttype": "text/plain", - "created": 1445295661000, - "id": "656243684720050176", - "language": "en" - }, - { - "content": "Thank you for opening up the heart space and letting #Belief in. Tonight it keeps getting better. See you at 8\/7c\nhttps:\/\/t.co\/E65vkTray9", - "contenttype": "text/plain", - "created": 1445279425000, - "id": "656175584943341568", - "language": "en" - }, - { - "content": "I believe in the @weightwatchers program so much I decided to invest, join the Board, and partner in #wwfamily evolution.", - "contenttype": "text/plain", - "created": 1445275802000, - "id": "656160388526899200", - "language": "en" - }, - { - "content": "RT @AVAETC: Debut episode of #BELIEF has now aired on both coasts. Trended for 4 hours. Brava, @Oprah + team. 6 beautiful nights to come. B\u2026", - "contenttype": "text/plain", - "created": 1445229489000, - "id": "655966138279432192", - "language": "en" - }, - { - "content": "RT @3LWTV: 6 more epic nights of #Belief to come! See you tomorrow 8pET\/7pCT for the next installment! @OWNTV @Oprah", - "contenttype": "text/plain", - "created": 1445227342000, - "id": "655957135688241152", - "language": "en" - }, - { - "content": "RT @ledisi: I love how Ancestry and Tradition is honored throughout every story in #Belief @OWNTV @OWN Thank you @Oprah this is so importa\u2026", - "contenttype": "text/plain", - "created": 1445225935000, - "id": "655951232981295104", - "language": "en" - }, - { - "content": "RT @UN: Showing #Belief at the UN \"is a bigger dream than I had\" - @Oprah https:\/\/t.co\/VC4OqD8yub #Belief #GlobalGoals https:\/\/t.co\/LZyGuC7\u2026", - "contenttype": "text/plain", - "created": 1445225228000, - "id": "655948267868426240", - "language": "en" - }, - { - "content": "RT @UzoAduba: To seek, to question, to learn, to teach, to pass it on; some of the breathtaking themes running like water throughout #Belie\u2026", - "contenttype": "text/plain", - "created": 1445225008000, - "id": "655947345197076480", - "language": "en" - }, - { - "content": "RT @iamtikasumpter: #Belief had me in awe. Faith in the divine is the constant that links us together. It's all beautiful and righteous. Gi\u2026", - "contenttype": "text/plain", - "created": 1445224852000, - "id": "655946689249828864", - "language": "en" - }, - { - "content": "West Coast... Here we go. #Belief", - "contenttype": "text/plain", - "created": 1445224140000, - "id": "655943701840048128", - "language": "en" - }, - { - "content": "Big surprise at icanady watch party. Epic night. #Belief. So much more to come. https:\/\/t.co\/kBDtFwGyQs", - "contenttype": "text/plain", - "created": 1445220694000, - "id": "655929249669378048", - "language": "en" - }, - { - "content": "I loved the Mendel story so much because it represents right of passasge. \" bye bye to childhood\".#Belief", - "contenttype": "text/plain", - "created": 1445215032000, - "id": "655905500056391682", - "language": "en" - }, - { - "content": "RT @squee_machine: This is a visual feast! Completely gorgeous and I am transfixed. The colors, the composition, cinematography, vibe. #Bel\u2026", - "contenttype": "text/plain", - "created": 1445214538000, - "id": "655903432079904768", - "language": "en" - }, - { - "content": "RT @JamesTyphany: Looking at @ #Belief I really needed this in my life thanks @OWNTV", - "contenttype": "text/plain", - "created": 1445214534000, - "id": "655903413385891840", - "language": "en" - }, - { - "content": "Just surprised a \"watch party\" @icanady 's house. #Belief http:\/\/t.co\/Di0I3OooCh", - "contenttype": "text/plain", - "created": 1445214502000, - "id": "655903277796732931", - "language": "en" - }, - { - "content": "RT @MsLaWandaa: I love moments of sitting among elders and learning. I can feel this moment was special for @ReshThakkar #Belief", - "contenttype": "text/plain", - "created": 1445214498000, - "id": "655903264374812672", - "language": "en" - }, - { - "content": "RT @xonecole: \"Do you have to have religion or is being a good person...is that enough?\" #Belief", - "contenttype": "text/plain", - "created": 1445214339000, - "id": "655902594171203584", - "language": "en" - }, - { - "content": "RT @ChivonJohn: Very inspired by the stories on #belief https:\/\/t.co\/uMRCCfCWcY", - "contenttype": "text/plain", - "created": 1445214327000, - "id": "655902545903140864", - "language": "en" - }, - { - "content": "RT @KiranSArora: powerful personal story that many of us can connect to. searching for what's missing, spiritual liberation. @ReshThakkar #\u2026", - "contenttype": "text/plain", - "created": 1445214128000, - "id": "655901708506103812", - "language": "en" - }, - { - "content": "RT @createdbyerica: \"I'm willing to go as far as I have to go to get that feeling in my heart of being connected to the Divine.\" - Reshma @\u2026", - "contenttype": "text/plain", - "created": 1445213967000, - "id": "655901033952993280", - "language": "en" - }, - { - "content": "RT @UrbnHealthNP: I am enjoying this so much. #Belief", - "contenttype": "text/plain", - "created": 1445213904000, - "id": "655900772467474435", - "language": "en" - }, - { - "content": "RT @DrMABrown: Your relationship with #belief can be completely different than how others experience it", - "contenttype": "text/plain", - "created": 1445213901000, - "id": "655900756604620800", - "language": "en" - }, - { - "content": "RT @ckerfin: On another river on the other side of the world... transition between stories, drawing connections to different beliefs #Belie\u2026", - "contenttype": "text/plain", - "created": 1445213721000, - "id": "655900002644987905", - "language": "en" - }, - { - "content": "RT @nikfarrior: So profound. We are all born into #Belief @Oprah @OWN @OWNTV", - "contenttype": "text/plain", - "created": 1445213706000, - "id": "655899942242775040", - "language": "en" - }, - { - "content": "RT @fgaboys: @Oprah the start of #Belief is riveting and edifying. It makes you want more and inspires you too see what's coming up next. \u2026", - "contenttype": "text/plain", - "created": 1445213699000, - "id": "655899910563217408", - "language": "en" - }, - { - "content": "RT @MalikaGhosh: Here we GO- let's lose ourselves #belief NOW @Oprah JOY http:\/\/t.co\/vYSNLd3LvC", - "contenttype": "text/plain", - "created": 1445212831000, - "id": "655896269542420480", - "language": "en" - }, - { - "content": "RT @MastinKipp: .@Oprah and team are about to bring the Light with #Belief.", - "contenttype": "text/plain", - "created": 1445212747000, - "id": "655895916675600384", - "language": "en" - }, - { - "content": "RT @GrowingOWN: 7 minutes, y'all! #BELIEF", - "contenttype": "text/plain", - "created": 1445212465000, - "id": "655894734968217600", - "language": "en" - }, - { - "content": "RT @LPToussaint: BELIEF defines experience.Choose wisely #Belief Tonight on OWN", - "contenttype": "text/plain", - "created": 1445211845000, - "id": "655892134524878848", - "language": "en" - }, - { - "content": "RT @TheBeBeWinans: Congratulations to my dear friend @Oprah on the launch of your series #BELIEF #Tonight on @OWNTV. Your friendship inspir\u2026", - "contenttype": "text/plain", - "created": 1445211835000, - "id": "655892094905532416", - "language": "en" - }, - { - "content": "RT @UzoAduba: Thirty minutes to @Oprah #Belief. Pretty sure it's about to be our favorite thing.", - "contenttype": "text/plain", - "created": 1445211833000, - "id": "655892084314890240", - "language": "en" - }, - { - "content": "RT @DeandresVoice: Moments away from the start of @SuperSoulSunday and the first night of the epic #Belief series on @OWNTV - are you ready\u2026", - "contenttype": "text/plain", - "created": 1445209201000, - "id": "655881046102142978", - "language": "en" - }, - { - "content": "RT @jennaldewan: I CANT WAIT FOR THIS TONIGHT!!!!!! Got my popcorn, got my tissues I am readyyyyyy! #Belief https:\/\/t.co\/WluTdeEqal", - "contenttype": "text/plain", - "created": 1445209181000, - "id": "655880959535939584", - "language": "en" - }, - { - "content": "RT @indiaarie: U heard about @Oprah passion project? It's called #Belief - I've see some & Its special! Tonight - 7c\/8e - 7 nights!! Whose\u2026", - "contenttype": "text/plain", - "created": 1445208945000, - "id": "655879970732949504", - "language": "en" - }, - { - "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass", - "contenttype": "text/plain", - "created": 1447639154000, - "id": "666073008692314113", - "language": "en" - }, - { - "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass", - "contenttype": "text/plain", - "created": 1447638226000, - "id": "666069114889179136", - "language": "en" - }, - { - "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass", - "contenttype": "text/plain", - "created": 1447638067000, - "id": "666068446325665792", - "language": "en" - }, - { - "content": "Wow aren't you loving @TheRock and his candor? #Masterclass", - "contenttype": "text/plain", - "created": 1447637459000, - "id": "666065895932973057", - "language": "en" - }, - { - "content": "RT @patt_t: @TheRock @Oprah @RichOnOWN @OWNTV this interview makes me like you as a fellow human even more for being so real.", - "contenttype": "text/plain", - "created": 1447637030000, - "id": "666064097562247168", - "language": "en" - }, - { - "content": "\"Be You\".. That's the best advice ever @TheRock #MastersClass", - "contenttype": "text/plain", - "created": 1447636205000, - "id": "666060637181644800", - "language": "en" - }, - { - "content": "Supersoulers let's lift our spirits pray and hold Paris in the Light\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1447602477000, - "id": "665919171062927360", - "language": "en" - }, - { - "content": "RT @DeepakChopra: What I learned in week 1: Become What You Believe 21-Day Meditation Experience - https:\/\/t.co\/kqaMaMqEUp #GoogleAlerts", - "contenttype": "text/plain", - "created": 1447098990000, - "id": "663807393063538688", - "language": "en" - }, - { - "content": "Watching Bryan Stevenson on #SuperSoulSunday! \"You are not the worst mistake you ever made\".\nAren't we glad about that.", - "contenttype": "text/plain", - "created": 1446998643000, - "id": "663386507856736257", - "language": "en" - }, - { - "content": ".@CherylStrayed BRAVE ENOUGH my new favorite thing! Gonna buy a copy for all my girls. #Perfectgift https:\/\/t.co\/gz1tnv8t8K", - "contenttype": "text/plain", - "created": 1446915955000, - "id": "663039689360695296", - "language": "en" - }, - { - "content": "Stevie Wonder singing \"Happy Birthday to you!\" to my dear mariashriver. A phenomenal woman and\u2026 https:\/\/t.co\/Ygm5eDIs4f", - "contenttype": "text/plain", - "created": 1446881193000, - "id": "662893888080879616", - "language": "en" - }, - { - "content": "It\u2019s my faaaaavorite time of the Year! For the first time you can shop the list on @amazon! https:\/\/t.co\/a6GMvVrhjN https:\/\/t.co\/sJlQMROq5U", - "contenttype": "text/plain", - "created": 1446744186000, - "id": "662319239844380672", - "language": "en" - }, - { - "content": "Incredible story \"the spirit of the Lord is on you\" thanks for sharing @smokey_robinson #Masterclass", - "contenttype": "text/plain", - "created": 1446428929000, - "id": "660996956861280256", - "language": "en" - }, - { - "content": "Wasnt that incredible story about @smokey_robinson 's dad leaving his family at 12. #MasterClass", - "contenttype": "text/plain", - "created": 1446426630000, - "id": "660987310889041920", - "language": "en" - }, - { - "content": "Gayle, Charlie, Nora @CBSThisMorning Congratulations! #1000thshow", - "contenttype": "text/plain", - "created": 1446220097000, - "id": "660121050978611205", - "language": "en" - }, - { - "content": "I believe your home should rise up to meet you. @TheEllenShow you nailed it with HOME. Tweethearts, grab a copy! https:\/\/t.co\/iFMnpRAsno", - "contenttype": "text/plain", - "created": 1446074433000, - "id": "659510090748182528", - "language": "en" - }, - { - "content": "Can I get a Witness?!\u270b\ud83c\udffe https:\/\/t.co\/tZ1QyAeSdE", - "contenttype": "text/plain", - "created": 1445821114000, - "id": "658447593865945089", - "language": "en" - }, - { - "content": ".@TheEllenShow you're a treasure.\nYour truth set a lot of people free.\n#Masterclass", - "contenttype": "text/plain", - "created": 1445821003000, - "id": "658447130026188800", - "language": "en" - }, - { - "content": "Hope you all are enjoying @TheEllenShow on #MasterClass.", - "contenttype": "text/plain", - "created": 1445820161000, - "id": "658443598313181188", - "language": "en" - }, - { - "content": ".@GloriaSteinem, shero to women everywhere, on how far we\u2019ve come and how far we need to go. #SuperSoulSunday 7p\/6c.\nhttps:\/\/t.co\/3e7oxXW02J", - "contenttype": "text/plain", - "created": 1445811545000, - "id": "658407457438363648", - "language": "en" - }, - { - "content": "RT @TheEllenShow: I told a story from my @OWNTV's #MasterClass on my show. Normally I\u2019d save it all for Sunday, but @Oprah made me. https:\/\u2026", - "contenttype": "text/plain", - "created": 1445804181000, - "id": "658376572521459712", - "language": "en" - }, - { - "content": ".@TheEllenShow is a master teacher of living her truth & living authentically as herself. #MasterClass tonight 8\/7c.\nhttps:\/\/t.co\/iLT2KgRsSw", - "contenttype": "text/plain", - "created": 1445804072000, - "id": "658376116575449088", - "language": "en" - }, - { - "content": ".@SheriSalata , @jonnysinc @part2pictures . Tears of joy and gratitude to you and our entire #BeliefTeam We DID IT!! My heart is full.\ud83d\ude4f\ud83c\udffe\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1445734755000, - "id": "658085377140363264", - "language": "en" - }, - { - "content": "Donna and Bob saw the tape of their story just days before she passed. They appreciated it. #RIPDonna", - "contenttype": "text/plain", - "created": 1445734097000, - "id": "658082618819280896", - "language": "en" - }, - { - "content": "RT @rempower: .@Oprah this series allowed me to slide into people's lives around the world and see the same in them ... we all have a belie\u2026", - "contenttype": "text/plain", - "created": 1445732769000, - "id": "658077046858383360", - "language": "en" - }, - { - "content": "All the stories moved me, My favorite line \" I must pass the stories on to my grandson otherwise our people will loose their way. #Belief", - "contenttype": "text/plain", - "created": 1445732579000, - "id": "658076253618991104", - "language": "en" - }, - { - "content": ".@part2pictures some of your best imagery yet. Filming Alex on the rock.#Belief", - "contenttype": "text/plain", - "created": 1445731782000, - "id": "658072908237934592", - "language": "en" - }, - { - "content": "I just love Alex and his daring #Belief to live fully the present Moment.", - "contenttype": "text/plain", - "created": 1445731561000, - "id": "658071980982206464", - "language": "en" - }, - { - "content": "RT @GrowingOWN: Let's do this! #Belief finale tweet tweet party. Thank you @Oprah! \ud83d\ude4f", - "contenttype": "text/plain", - "created": 1445731248000, - "id": "658070668785770496", - "language": "en" - }, - { - "content": "RT @lizkinnell: The epic finale of #Belief on @OWNTV is about to start. 8\/et Are you ready? What do you Believe?", - "contenttype": "text/plain", - "created": 1445731081000, - "id": "658069968534171648", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night of Belief. Belief runs all day tomorrow for bingers and final episode!", - "contenttype": "text/plain", - "created": 1445648630000, - "id": "657724143115202560", - "language": "en" - }, - { - "content": "RT @OWNingLight: #Belief is the ultimate travel map to mass acceptance. \ud83d\ude4f\ud83c\udffb\u2764\ufe0f\ud83c\udf0d @Oprah", - "contenttype": "text/plain", - "created": 1445647285000, - "id": "657718501147197442", - "language": "en" - }, - { - "content": "\" I can feel my heart opening and faith coming back in\".. What's better than that? #Belief", - "contenttype": "text/plain", - "created": 1445646903000, - "id": "657716901951369218", - "language": "en" - }, - { - "content": "Hey Belief team mates can yo believe how quickly the week has passed? #Belief", - "contenttype": "text/plain", - "created": 1445645633000, - "id": "657711572492533760", - "language": "en" - }, - { - "content": "Ran into @5SOS backstage. Fun times with @TheEllenShow today! https:\/\/t.co\/2PP3W3RzXc", - "contenttype": "text/plain", - "created": 1445618531000, - "id": "657597898394173440", - "language": "en" - }, - { - "content": "Thanks All for another great night of #BELIEF", - "contenttype": "text/plain", - "created": 1445572548000, - "id": "657405031822430208", - "language": "en" - }, - { - "content": "RT @3LWTV: #BecomeWhatYouBelieve New meditation w\/ @Oprah @DeepakChopra begins 11\/2 Register https:\/\/t.co\/x0R9HWTAX0 #Belief https:\/\/t.co\/\u2026", - "contenttype": "text/plain", - "created": 1445571500000, - "id": "657400636745510912", - "language": "en" - }, - { - "content": "Ok west coast let's do it! #belief", - "contenttype": "text/plain", - "created": 1445569367000, - "id": "657391689439404033", - "language": "en" - }, - { - "content": "Thank u kind gentleman who told me I had kale in my teeth. Was eating kale chips with Quincy Jones. Went straight to @LairdLife party.", - "contenttype": "text/plain", - "created": 1445569296000, - "id": "657391393883619328", - "language": "en" - }, - { - "content": "Hello west coast twitterati.. See you at 8 for #Belief", - "contenttype": "text/plain", - "created": 1445566144000, - "id": "657378171872874496", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night.#Belief", - "contenttype": "text/plain", - "created": 1445475948000, - "id": "656999861254918145", - "language": "en" - }, - { - "content": "RT @PRanganathan: \"Transformation is the rule of the game. The universe is not standing still.\" - Marcelo @OWNTV @Oprah #Belief", - "contenttype": "text/plain", - "created": 1445475602000, - "id": "656998409933451264", - "language": "en" - }, - { - "content": "\"The Universe is not standing still.. The whole Universe is expanding\" I love the dance between science and spirituality! #Belief", - "contenttype": "text/plain", - "created": 1445475580000, - "id": "656998320133398528", - "language": "en" - }, - { - "content": "\"Without our prayers and our songs we won't be here\" Apache leader.#Belief", - "contenttype": "text/plain", - "created": 1445473768000, - "id": "656990717504393216", - "language": "en" - }, - { - "content": "Notice her mother crying. She knows its last tine she will ever see her daughter.#Belief", - "contenttype": "text/plain", - "created": 1445473150000, - "id": "656988127433637888", - "language": "en" - }, - { - "content": "This final trial is unbelievable. Every hair gets pulled from her head one at a time. Now that is Something!!#Belief", - "contenttype": "text/plain", - "created": 1445473063000, - "id": "656987763644891136", - "language": "en" - }, - { - "content": "\"What my faith gives me no one can match\"#Belief", - "contenttype": "text/plain", - "created": 1445472961000, - "id": "656987336266223616", - "language": "en" - }, - { - "content": "It's a devotion to faith beyond anything Ive seen. Fascinating.Jain nuns. #Belief", - "contenttype": "text/plain", - "created": 1445472531000, - "id": "656985529951522816", - "language": "en" - }, - { - "content": "I'd never heard of Jain monks and nuns before doing this series. #Belief", - "contenttype": "text/plain", - "created": 1445472393000, - "id": "656984953037586433", - "language": "en" - }, - { - "content": "Good evening Team #Belief the Tweet is on!", - "contenttype": "text/plain", - "created": 1445472098000, - "id": "656983714883239937", - "language": "en" - }, - { - "content": "Thanks everyone for another Epic #Belief night!", - "contenttype": "text/plain", - "created": 1445302792000, - "id": "656273592485810176", - "language": "en" - }, - { - "content": "The Pastor and Imam represent the possibility of PEACE in the world. If they can do it. We can. Peace to All\ud83d\ude4f\ud83c\udffe #Belief", - "contenttype": "text/plain", - "created": 1445302749000, - "id": "656273415280705536", - "language": "en" - }, - { - "content": "We felt privileged to film the Hajj and explore the beauty of Islam.\n#99namesforGod #Belief", - "contenttype": "text/plain", - "created": 1445301110000, - "id": "656266540967424000", - "language": "en" - }, - { - "content": "Do you all believe in \"soul mates\"?\n#Belief", - "contenttype": "text/plain", - "created": 1445300138000, - "id": "656262462426238976", - "language": "en" - }, - { - "content": ".@RevEdBacon thank you so much for hosting tonight's #Belief at All Saints Church.", - "contenttype": "text/plain", - "created": 1445299749000, - "id": "656260832628756480", - "language": "en" - }, - { - "content": "This is one of the best love stories I've ever seen. #belief Ian and Larissa showing us the depths of love.#Belief", - "contenttype": "text/plain", - "created": 1445299614000, - "id": "656260263604310016", - "language": "en" - }, - { - "content": "Hey Everyone .. Tweeting from a bar in Atlanta with @SheriSalata OWN not in my hotel. Anything for #Belief", - "contenttype": "text/plain", - "created": 1445299326000, - "id": "656259057758654464", - "language": "en" - }, - { - "content": "RT @joshuadubois: When you see Ian & Larissa tonight on #BELIEF, you'll know what Christian love is all about. 8pmET, @OWNTV. Tune in! http\u2026", - "contenttype": "text/plain", - "created": 1445295716000, - "id": "656243916224638976", - "language": "en" - }, - { - "content": "RT @KimHaleDance: I Believe LAUGHTER. IS. CONTAGIOUS. What do you believe? See you tonight! 8\/7c.\u2764\ufe0f #Belief #Beliefin3words https:\/\/t.co\/x\u2026", - "contenttype": "text/plain", - "created": 1445295702000, - "id": "656243854610337793", - "language": "en" - }, - { - "content": "RT @OWNTV: See the world through someone else\u2019s soul. The epic journey of #Belief continues tonight at 8\/7c.\nhttps:\/\/t.co\/UKKMHZuC0g", - "contenttype": "text/plain", - "created": 1445295668000, - "id": "656243714507931648", - "language": "en" - }, - { - "content": "RT @OWNTV: Mendel Hurwitz's inquisitive nature grounded him in his faith. See where it's taken him now: https:\/\/t.co\/2iWmNOxK9r https:\/\/t.c\u2026", - "contenttype": "text/plain", - "created": 1445295661000, - "id": "656243684720050176", - "language": "en" - }, - { - "content": "Thank you for opening up the heart space and letting #Belief in. Tonight it keeps getting better. See you at 8\/7c\nhttps:\/\/t.co\/E65vkTray9", - "contenttype": "text/plain", - "created": 1445279425000, - "id": "656175584943341568", - "language": "en" - }, - { - "content": "I believe in the @weightwatchers program so much I decided to invest, join the Board, and partner in #wwfamily evolution.", - "contenttype": "text/plain", - "created": 1445275802000, - "id": "656160388526899200", - "language": "en" - }, - { - "content": "RT @AVAETC: Debut episode of #BELIEF has now aired on both coasts. Trended for 4 hours. Brava, @Oprah + team. 6 beautiful nights to come. B\u2026", - "contenttype": "text/plain", - "created": 1445229489000, - "id": "655966138279432192", - "language": "en" - }, - { - "content": "RT @3LWTV: 6 more epic nights of #Belief to come! See you tomorrow 8pET\/7pCT for the next installment! @OWNTV @Oprah", - "contenttype": "text/plain", - "created": 1445227342000, - "id": "655957135688241152", - "language": "en" - }, - { - "content": "RT @ledisi: I love how Ancestry and Tradition is honored throughout every story in #Belief @OWNTV @OWN Thank you @Oprah this is so importa\u2026", - "contenttype": "text/plain", - "created": 1445225935000, - "id": "655951232981295104", - "language": "en" - }, - { - "content": "RT @UN: Showing #Belief at the UN \"is a bigger dream than I had\" - @Oprah https:\/\/t.co\/VC4OqD8yub #Belief #GlobalGoals https:\/\/t.co\/LZyGuC7\u2026", - "contenttype": "text/plain", - "created": 1445225228000, - "id": "655948267868426240", - "language": "en" - }, - { - "content": "RT @UzoAduba: To seek, to question, to learn, to teach, to pass it on; some of the breathtaking themes running like water throughout #Belie\u2026", - "contenttype": "text/plain", - "created": 1445225008000, - "id": "655947345197076480", - "language": "en" - }, - { - "content": "RT @iamtikasumpter: #Belief had me in awe. Faith in the divine is the constant that links us together. It's all beautiful and righteous. Gi\u2026", - "contenttype": "text/plain", - "created": 1445224852000, - "id": "655946689249828864", - "language": "en" - }, - { - "content": "West Coast... Here we go. #Belief", - "contenttype": "text/plain", - "created": 1445224140000, - "id": "655943701840048128", - "language": "en" - }, - { - "content": "Big surprise at icanady watch party. Epic night. #Belief. So much more to come. https:\/\/t.co\/kBDtFwGyQs", - "contenttype": "text/plain", - "created": 1445220694000, - "id": "655929249669378048", - "language": "en" - }, - { - "content": "I loved the Mendel story so much because it represents right of passasge. \" bye bye to childhood\".#Belief", - "contenttype": "text/plain", - "created": 1445215032000, - "id": "655905500056391682", - "language": "en" - }, - { - "content": "RT @squee_machine: This is a visual feast! Completely gorgeous and I am transfixed. The colors, the composition, cinematography, vibe. #Bel\u2026", - "contenttype": "text/plain", - "created": 1445214538000, - "id": "655903432079904768", - "language": "en" - }, - { - "content": "RT @JamesTyphany: Looking at @ #Belief I really needed this in my life thanks @OWNTV", - "contenttype": "text/plain", - "created": 1445214534000, - "id": "655903413385891840", - "language": "en" - }, - { - "content": "Just surprised a \"watch party\" @icanady 's house. #Belief http:\/\/t.co\/Di0I3OooCh", - "contenttype": "text/plain", - "created": 1445214502000, - "id": "655903277796732931", - "language": "en" - }, - { - "content": "RT @MsLaWandaa: I love moments of sitting among elders and learning. I can feel this moment was special for @ReshThakkar #Belief", - "contenttype": "text/plain", - "created": 1445214498000, - "id": "655903264374812672", - "language": "en" - }, - { - "content": "RT @xonecole: \"Do you have to have religion or is being a good person...is that enough?\" #Belief", - "contenttype": "text/plain", - "created": 1445214339000, - "id": "655902594171203584", - "language": "en" - }, - { - "content": "RT @ChivonJohn: Very inspired by the stories on #belief https:\/\/t.co\/uMRCCfCWcY", - "contenttype": "text/plain", - "created": 1445214327000, - "id": "655902545903140864", - "language": "en" - }, - { - "content": "RT @KiranSArora: powerful personal story that many of us can connect to. searching for what's missing, spiritual liberation. @ReshThakkar #\u2026", - "contenttype": "text/plain", - "created": 1445214128000, - "id": "655901708506103812", - "language": "en" - }, - { - "content": "RT @createdbyerica: \"I'm willing to go as far as I have to go to get that feeling in my heart of being connected to the Divine.\" - Reshma @\u2026", - "contenttype": "text/plain", - "created": 1445213967000, - "id": "655901033952993280", - "language": "en" - }, - { - "content": "RT @UrbnHealthNP: I am enjoying this so much. #Belief", - "contenttype": "text/plain", - "created": 1445213904000, - "id": "655900772467474435", - "language": "en" - }, - { - "content": "RT @DrMABrown: Your relationship with #belief can be completely different than how others experience it", - "contenttype": "text/plain", - "created": 1445213901000, - "id": "655900756604620800", - "language": "en" - }, - { - "content": "RT @ckerfin: On another river on the other side of the world... transition between stories, drawing connections to different beliefs #Belie\u2026", - "contenttype": "text/plain", - "created": 1445213721000, - "id": "655900002644987905", - "language": "en" - }, - { - "content": "RT @nikfarrior: So profound. We are all born into #Belief @Oprah @OWN @OWNTV", - "contenttype": "text/plain", - "created": 1445213706000, - "id": "655899942242775040", - "language": "en" - }, - { - "content": "RT @fgaboys: @Oprah the start of #Belief is riveting and edifying. It makes you want more and inspires you too see what's coming up next. \u2026", - "contenttype": "text/plain", - "created": 1445213699000, - "id": "655899910563217408", - "language": "en" - }, - { - "content": "RT @MalikaGhosh: Here we GO- let's lose ourselves #belief NOW @Oprah JOY http:\/\/t.co\/vYSNLd3LvC", - "contenttype": "text/plain", - "created": 1445212831000, - "id": "655896269542420480", - "language": "en" - }, - { - "content": "RT @MastinKipp: .@Oprah and team are about to bring the Light with #Belief.", - "contenttype": "text/plain", - "created": 1445212747000, - "id": "655895916675600384", - "language": "en" - }, - { - "content": "RT @GrowingOWN: 7 minutes, y'all! #BELIEF", - "contenttype": "text/plain", - "created": 1445212465000, - "id": "655894734968217600", - "language": "en" - }, - { - "content": "RT @LPToussaint: BELIEF defines experience.Choose wisely #Belief Tonight on OWN", - "contenttype": "text/plain", - "created": 1445211845000, - "id": "655892134524878848", - "language": "en" - }, - { - "content": "RT @TheBeBeWinans: Congratulations to my dear friend @Oprah on the launch of your series #BELIEF #Tonight on @OWNTV. Your friendship inspir\u2026", - "contenttype": "text/plain", - "created": 1445211835000, - "id": "655892094905532416", - "language": "en" - }, - { - "content": "RT @UzoAduba: Thirty minutes to @Oprah #Belief. Pretty sure it's about to be our favorite thing.", - "contenttype": "text/plain", - "created": 1445211833000, - "id": "655892084314890240", - "language": "en" - }, - { - "content": "RT @DeandresVoice: Moments away from the start of @SuperSoulSunday and the first night of the epic #Belief series on @OWNTV - are you ready\u2026", - "contenttype": "text/plain", - "created": 1445209201000, - "id": "655881046102142978", - "language": "en" - }, - { - "content": "RT @jennaldewan: I CANT WAIT FOR THIS TONIGHT!!!!!! Got my popcorn, got my tissues I am readyyyyyy! #Belief https:\/\/t.co\/WluTdeEqal", - "contenttype": "text/plain", - "created": 1445209181000, - "id": "655880959535939584", - "language": "en" - }, - { - "content": "RT @indiaarie: U heard about @Oprah passion project? It's called #Belief - I've see some & Its special! Tonight - 7c\/8e - 7 nights!! Whose\u2026", - "contenttype": "text/plain", - "created": 1445208945000, - "id": "655879970732949504", - "language": "en" - }, - { - "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass", - "contenttype": "text/plain", - "created": 1447639154000, - "id": "666073008692314113", - "language": "en" - }, - { - "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass", - "contenttype": "text/plain", - "created": 1447638226000, - "id": "666069114889179136", - "language": "en" - }, - { - "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass", - "contenttype": "text/plain", - "created": 1447638067000, - "id": "666068446325665792", - "language": "en" - }, - { - "content": "Wow aren't you loving @TheRock and his candor? #Masterclass", - "contenttype": "text/plain", - "created": 1447637459000, - "id": "666065895932973057", - "language": "en" - }, - { - "content": "RT @patt_t: @TheRock @Oprah @RichOnOWN @OWNTV this interview makes me like you as a fellow human even more for being so real.", - "contenttype": "text/plain", - "created": 1447637030000, - "id": "666064097562247168", - "language": "en" - }, - { - "content": "\"Be You\".. That's the best advice ever @TheRock #MastersClass", - "contenttype": "text/plain", - "created": 1447636205000, - "id": "666060637181644800", - "language": "en" - }, - { - "content": "Supersoulers let's lift our spirits pray and hold Paris in the Light\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1447602477000, - "id": "665919171062927360", - "language": "en" - }, - { - "content": "RT @DeepakChopra: What I learned in week 1: Become What You Believe 21-Day Meditation Experience - https:\/\/t.co\/kqaMaMqEUp #GoogleAlerts", - "contenttype": "text/plain", - "created": 1447098990000, - "id": "663807393063538688", - "language": "en" - }, - { - "content": "Watching Bryan Stevenson on #SuperSoulSunday! \"You are not the worst mistake you ever made\".\nAren't we glad about that.", - "contenttype": "text/plain", - "created": 1446998643000, - "id": "663386507856736257", - "language": "en" - }, - { - "content": ".@CherylStrayed BRAVE ENOUGH my new favorite thing! Gonna buy a copy for all my girls. #Perfectgift https:\/\/t.co\/gz1tnv8t8K", - "contenttype": "text/plain", - "created": 1446915955000, - "id": "663039689360695296", - "language": "en" - }, - { - "content": "Stevie Wonder singing \"Happy Birthday to you!\" to my dear mariashriver. A phenomenal woman and\u2026 https:\/\/t.co\/Ygm5eDIs4f", - "contenttype": "text/plain", - "created": 1446881193000, - "id": "662893888080879616", - "language": "en" - }, - { - "content": "It\u2019s my faaaaavorite time of the Year! For the first time you can shop the list on @amazon! https:\/\/t.co\/a6GMvVrhjN https:\/\/t.co\/sJlQMROq5U", - "contenttype": "text/plain", - "created": 1446744186000, - "id": "662319239844380672", - "language": "en" - }, - { - "content": "Incredible story \"the spirit of the Lord is on you\" thanks for sharing @smokey_robinson #Masterclass", - "contenttype": "text/plain", - "created": 1446428929000, - "id": "660996956861280256", - "language": "en" - }, - { - "content": "Wasnt that incredible story about @smokey_robinson 's dad leaving his family at 12. #MasterClass", - "contenttype": "text/plain", - "created": 1446426630000, - "id": "660987310889041920", - "language": "en" - }, - { - "content": "Gayle, Charlie, Nora @CBSThisMorning Congratulations! #1000thshow", - "contenttype": "text/plain", - "created": 1446220097000, - "id": "660121050978611205", - "language": "en" - }, - { - "content": "I believe your home should rise up to meet you. @TheEllenShow you nailed it with HOME. Tweethearts, grab a copy! https:\/\/t.co\/iFMnpRAsno", - "contenttype": "text/plain", - "created": 1446074433000, - "id": "659510090748182528", - "language": "en" - }, - { - "content": "Can I get a Witness?!\u270b\ud83c\udffe https:\/\/t.co\/tZ1QyAeSdE", - "contenttype": "text/plain", - "created": 1445821114000, - "id": "658447593865945089", - "language": "en" - }, - { - "content": ".@TheEllenShow you're a treasure.\nYour truth set a lot of people free.\n#Masterclass", - "contenttype": "text/plain", - "created": 1445821003000, - "id": "658447130026188800", - "language": "en" - }, - { - "content": "Hope you all are enjoying @TheEllenShow on #MasterClass.", - "contenttype": "text/plain", - "created": 1445820161000, - "id": "658443598313181188", - "language": "en" - }, - { - "content": ".@GloriaSteinem, shero to women everywhere, on how far we\u2019ve come and how far we need to go. #SuperSoulSunday 7p\/6c.\nhttps:\/\/t.co\/3e7oxXW02J", - "contenttype": "text/plain", - "created": 1445811545000, - "id": "658407457438363648", - "language": "en" - }, - { - "content": "RT @TheEllenShow: I told a story from my @OWNTV's #MasterClass on my show. Normally I\u2019d save it all for Sunday, but @Oprah made me. https:\/\u2026", - "contenttype": "text/plain", - "created": 1445804181000, - "id": "658376572521459712", - "language": "en" - }, - { - "content": ".@TheEllenShow is a master teacher of living her truth & living authentically as herself. #MasterClass tonight 8\/7c.\nhttps:\/\/t.co\/iLT2KgRsSw", - "contenttype": "text/plain", - "created": 1445804072000, - "id": "658376116575449088", - "language": "en" - }, - { - "content": ".@SheriSalata , @jonnysinc @part2pictures . Tears of joy and gratitude to you and our entire #BeliefTeam We DID IT!! My heart is full.\ud83d\ude4f\ud83c\udffe\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1445734755000, - "id": "658085377140363264", - "language": "en" - }, - { - "content": "Donna and Bob saw the tape of their story just days before she passed. They appreciated it. #RIPDonna", - "contenttype": "text/plain", - "created": 1445734097000, - "id": "658082618819280896", - "language": "en" - }, - { - "content": "RT @rempower: .@Oprah this series allowed me to slide into people's lives around the world and see the same in them ... we all have a belie\u2026", - "contenttype": "text/plain", - "created": 1445732769000, - "id": "658077046858383360", - "language": "en" - }, - { - "content": "All the stories moved me, My favorite line \" I must pass the stories on to my grandson otherwise our people will loose their way. #Belief", - "contenttype": "text/plain", - "created": 1445732579000, - "id": "658076253618991104", - "language": "en" - }, - { - "content": ".@part2pictures some of your best imagery yet. Filming Alex on the rock.#Belief", - "contenttype": "text/plain", - "created": 1445731782000, - "id": "658072908237934592", - "language": "en" - }, - { - "content": "I just love Alex and his daring #Belief to live fully the present Moment.", - "contenttype": "text/plain", - "created": 1445731561000, - "id": "658071980982206464", - "language": "en" - }, - { - "content": "RT @GrowingOWN: Let's do this! #Belief finale tweet tweet party. Thank you @Oprah! \ud83d\ude4f", - "contenttype": "text/plain", - "created": 1445731248000, - "id": "658070668785770496", - "language": "en" - }, - { - "content": "RT @lizkinnell: The epic finale of #Belief on @OWNTV is about to start. 8\/et Are you ready? What do you Believe?", - "contenttype": "text/plain", - "created": 1445731081000, - "id": "658069968534171648", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night of Belief. Belief runs all day tomorrow for bingers and final episode!", - "contenttype": "text/plain", - "created": 1445648630000, - "id": "657724143115202560", - "language": "en" - }, - { - "content": "RT @OWNingLight: #Belief is the ultimate travel map to mass acceptance. \ud83d\ude4f\ud83c\udffb\u2764\ufe0f\ud83c\udf0d @Oprah", - "contenttype": "text/plain", - "created": 1445647285000, - "id": "657718501147197442", - "language": "en" - }, - { - "content": "\" I can feel my heart opening and faith coming back in\".. What's better than that? #Belief", - "contenttype": "text/plain", - "created": 1445646903000, - "id": "657716901951369218", - "language": "en" - }, - { - "content": "Hey Belief team mates can yo believe how quickly the week has passed? #Belief", - "contenttype": "text/plain", - "created": 1445645633000, - "id": "657711572492533760", - "language": "en" - }, - { - "content": "Ran into @5SOS backstage. Fun times with @TheEllenShow today! https:\/\/t.co\/2PP3W3RzXc", - "contenttype": "text/plain", - "created": 1445618531000, - "id": "657597898394173440", - "language": "en" - }, - { - "content": "Thanks All for another great night of #BELIEF", - "contenttype": "text/plain", - "created": 1445572548000, - "id": "657405031822430208", - "language": "en" - }, - { - "content": "RT @3LWTV: #BecomeWhatYouBelieve New meditation w\/ @Oprah @DeepakChopra begins 11\/2 Register https:\/\/t.co\/x0R9HWTAX0 #Belief https:\/\/t.co\/\u2026", - "contenttype": "text/plain", - "created": 1445571500000, - "id": "657400636745510912", - "language": "en" - }, - { - "content": "Ok west coast let's do it! #belief", - "contenttype": "text/plain", - "created": 1445569367000, - "id": "657391689439404033", - "language": "en" - }, - { - "content": "Thank u kind gentleman who told me I had kale in my teeth. Was eating kale chips with Quincy Jones. Went straight to @LairdLife party.", - "contenttype": "text/plain", - "created": 1445569296000, - "id": "657391393883619328", - "language": "en" - }, - { - "content": "Hello west coast twitterati.. See you at 8 for #Belief", - "contenttype": "text/plain", - "created": 1445566144000, - "id": "657378171872874496", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night.#Belief", - "contenttype": "text/plain", - "created": 1445475948000, - "id": "656999861254918145", - "language": "en" - }, - { - "content": "RT @PRanganathan: \"Transformation is the rule of the game. The universe is not standing still.\" - Marcelo @OWNTV @Oprah #Belief", - "contenttype": "text/plain", - "created": 1445475602000, - "id": "656998409933451264", - "language": "en" - }, - { - "content": "\"The Universe is not standing still.. The whole Universe is expanding\" I love the dance between science and spirituality! #Belief", - "contenttype": "text/plain", - "created": 1445475580000, - "id": "656998320133398528", - "language": "en" - }, - { - "content": "\"Without our prayers and our songs we won't be here\" Apache leader.#Belief", - "contenttype": "text/plain", - "created": 1445473768000, - "id": "656990717504393216", - "language": "en" - }, - { - "content": "Notice her mother crying. She knows its last tine she will ever see her daughter.#Belief", - "contenttype": "text/plain", - "created": 1445473150000, - "id": "656988127433637888", - "language": "en" - }, - { - "content": "This final trial is unbelievable. Every hair gets pulled from her head one at a time. Now that is Something!!#Belief", - "contenttype": "text/plain", - "created": 1445473063000, - "id": "656987763644891136", - "language": "en" - }, - { - "content": "\"What my faith gives me no one can match\"#Belief", - "contenttype": "text/plain", - "created": 1445472961000, - "id": "656987336266223616", - "language": "en" - }, - { - "content": "It's a devotion to faith beyond anything Ive seen. Fascinating.Jain nuns. #Belief", - "contenttype": "text/plain", - "created": 1445472531000, - "id": "656985529951522816", - "language": "en" - }, - { - "content": "I'd never heard of Jain monks and nuns before doing this series. #Belief", - "contenttype": "text/plain", - "created": 1445472393000, - "id": "656984953037586433", - "language": "en" - }, - { - "content": "Good evening Team #Belief the Tweet is on!", - "contenttype": "text/plain", - "created": 1445472098000, - "id": "656983714883239937", - "language": "en" - }, - { - "content": "Thanks everyone for another Epic #Belief night!", - "contenttype": "text/plain", - "created": 1445302792000, - "id": "656273592485810176", - "language": "en" - }, - { - "content": "The Pastor and Imam represent the possibility of PEACE in the world. If they can do it. We can. Peace to All\ud83d\ude4f\ud83c\udffe #Belief", - "contenttype": "text/plain", - "created": 1445302749000, - "id": "656273415280705536", - "language": "en" - }, - { - "content": "We felt privileged to film the Hajj and explore the beauty of Islam.\n#99namesforGod #Belief", - "contenttype": "text/plain", - "created": 1445301110000, - "id": "656266540967424000", - "language": "en" - }, - { - "content": "Do you all believe in \"soul mates\"?\n#Belief", - "contenttype": "text/plain", - "created": 1445300138000, - "id": "656262462426238976", - "language": "en" - }, - { - "content": ".@RevEdBacon thank you so much for hosting tonight's #Belief at All Saints Church.", - "contenttype": "text/plain", - "created": 1445299749000, - "id": "656260832628756480", - "language": "en" - }, - { - "content": "This is one of the best love stories I've ever seen. #belief Ian and Larissa showing us the depths of love.#Belief", - "contenttype": "text/plain", - "created": 1445299614000, - "id": "656260263604310016", - "language": "en" - }, - { - "content": "Hey Everyone .. Tweeting from a bar in Atlanta with @SheriSalata OWN not in my hotel. Anything for #Belief", - "contenttype": "text/plain", - "created": 1445299326000, - "id": "656259057758654464", - "language": "en" - }, - { - "content": "RT @joshuadubois: When you see Ian & Larissa tonight on #BELIEF, you'll know what Christian love is all about. 8pmET, @OWNTV. Tune in! http\u2026", - "contenttype": "text/plain", - "created": 1445295716000, - "id": "656243916224638976", - "language": "en" - }, - { - "content": "RT @KimHaleDance: I Believe LAUGHTER. IS. CONTAGIOUS. What do you believe? See you tonight! 8\/7c.\u2764\ufe0f #Belief #Beliefin3words https:\/\/t.co\/x\u2026", - "contenttype": "text/plain", - "created": 1445295702000, - "id": "656243854610337793", - "language": "en" - }, - { - "content": "RT @OWNTV: See the world through someone else\u2019s soul. The epic journey of #Belief continues tonight at 8\/7c.\nhttps:\/\/t.co\/UKKMHZuC0g", - "contenttype": "text/plain", - "created": 1445295668000, - "id": "656243714507931648", - "language": "en" - }, - { - "content": "RT @OWNTV: Mendel Hurwitz's inquisitive nature grounded him in his faith. See where it's taken him now: https:\/\/t.co\/2iWmNOxK9r https:\/\/t.c\u2026", - "contenttype": "text/plain", - "created": 1445295661000, - "id": "656243684720050176", - "language": "en" - }, - { - "content": "Thank you for opening up the heart space and letting #Belief in. Tonight it keeps getting better. See you at 8\/7c\nhttps:\/\/t.co\/E65vkTray9", - "contenttype": "text/plain", - "created": 1445279425000, - "id": "656175584943341568", - "language": "en" - }, - { - "content": "I believe in the @weightwatchers program so much I decided to invest, join the Board, and partner in #wwfamily evolution.", - "contenttype": "text/plain", - "created": 1445275802000, - "id": "656160388526899200", - "language": "en" - }, - { - "content": "RT @AVAETC: Debut episode of #BELIEF has now aired on both coasts. Trended for 4 hours. Brava, @Oprah + team. 6 beautiful nights to come. B\u2026", - "contenttype": "text/plain", - "created": 1445229489000, - "id": "655966138279432192", - "language": "en" - }, - { - "content": "RT @3LWTV: 6 more epic nights of #Belief to come! See you tomorrow 8pET\/7pCT for the next installment! @OWNTV @Oprah", - "contenttype": "text/plain", - "created": 1445227342000, - "id": "655957135688241152", - "language": "en" - }, - { - "content": "RT @ledisi: I love how Ancestry and Tradition is honored throughout every story in #Belief @OWNTV @OWN Thank you @Oprah this is so importa\u2026", - "contenttype": "text/plain", - "created": 1445225935000, - "id": "655951232981295104", - "language": "en" - }, - { - "content": "RT @UN: Showing #Belief at the UN \"is a bigger dream than I had\" - @Oprah https:\/\/t.co\/VC4OqD8yub #Belief #GlobalGoals https:\/\/t.co\/LZyGuC7\u2026", - "contenttype": "text/plain", - "created": 1445225228000, - "id": "655948267868426240", - "language": "en" - }, - { - "content": "RT @UzoAduba: To seek, to question, to learn, to teach, to pass it on; some of the breathtaking themes running like water throughout #Belie\u2026", - "contenttype": "text/plain", - "created": 1445225008000, - "id": "655947345197076480", - "language": "en" - }, - { - "content": "RT @iamtikasumpter: #Belief had me in awe. Faith in the divine is the constant that links us together. It's all beautiful and righteous. Gi\u2026", - "contenttype": "text/plain", - "created": 1445224852000, - "id": "655946689249828864", - "language": "en" - }, - { - "content": "West Coast... Here we go. #Belief", - "contenttype": "text/plain", - "created": 1445224140000, - "id": "655943701840048128", - "language": "en" - }, - { - "content": "Big surprise at icanady watch party. Epic night. #Belief. So much more to come. https:\/\/t.co\/kBDtFwGyQs", - "contenttype": "text/plain", - "created": 1445220694000, - "id": "655929249669378048", - "language": "en" - }, - { - "content": "I loved the Mendel story so much because it represents right of passasge. \" bye bye to childhood\".#Belief", - "contenttype": "text/plain", - "created": 1445215032000, - "id": "655905500056391682", - "language": "en" - }, - { - "content": "RT @squee_machine: This is a visual feast! Completely gorgeous and I am transfixed. The colors, the composition, cinematography, vibe. #Bel\u2026", - "contenttype": "text/plain", - "created": 1445214538000, - "id": "655903432079904768", - "language": "en" - }, - { - "content": "RT @JamesTyphany: Looking at @ #Belief I really needed this in my life thanks @OWNTV", - "contenttype": "text/plain", - "created": 1445214534000, - "id": "655903413385891840", - "language": "en" - }, - { - "content": "Just surprised a \"watch party\" @icanady 's house. #Belief http:\/\/t.co\/Di0I3OooCh", - "contenttype": "text/plain", - "created": 1445214502000, - "id": "655903277796732931", - "language": "en" - }, - { - "content": "RT @MsLaWandaa: I love moments of sitting among elders and learning. I can feel this moment was special for @ReshThakkar #Belief", - "contenttype": "text/plain", - "created": 1445214498000, - "id": "655903264374812672", - "language": "en" - }, - { - "content": "RT @xonecole: \"Do you have to have religion or is being a good person...is that enough?\" #Belief", - "contenttype": "text/plain", - "created": 1445214339000, - "id": "655902594171203584", - "language": "en" - }, - { - "content": "RT @ChivonJohn: Very inspired by the stories on #belief https:\/\/t.co\/uMRCCfCWcY", - "contenttype": "text/plain", - "created": 1445214327000, - "id": "655902545903140864", - "language": "en" - }, - { - "content": "RT @KiranSArora: powerful personal story that many of us can connect to. searching for what's missing, spiritual liberation. @ReshThakkar #\u2026", - "contenttype": "text/plain", - "created": 1445214128000, - "id": "655901708506103812", - "language": "en" - }, - { - "content": "RT @createdbyerica: \"I'm willing to go as far as I have to go to get that feeling in my heart of being connected to the Divine.\" - Reshma @\u2026", - "contenttype": "text/plain", - "created": 1445213967000, - "id": "655901033952993280", - "language": "en" - }, - { - "content": "RT @UrbnHealthNP: I am enjoying this so much. #Belief", - "contenttype": "text/plain", - "created": 1445213904000, - "id": "655900772467474435", - "language": "en" - }, - { - "content": "RT @DrMABrown: Your relationship with #belief can be completely different than how others experience it", - "contenttype": "text/plain", - "created": 1445213901000, - "id": "655900756604620800", - "language": "en" - }, - { - "content": "RT @ckerfin: On another river on the other side of the world... transition between stories, drawing connections to different beliefs #Belie\u2026", - "contenttype": "text/plain", - "created": 1445213721000, - "id": "655900002644987905", - "language": "en" - }, - { - "content": "RT @nikfarrior: So profound. We are all born into #Belief @Oprah @OWN @OWNTV", - "contenttype": "text/plain", - "created": 1445213706000, - "id": "655899942242775040", - "language": "en" - }, - { - "content": "RT @fgaboys: @Oprah the start of #Belief is riveting and edifying. It makes you want more and inspires you too see what's coming up next. \u2026", - "contenttype": "text/plain", - "created": 1445213699000, - "id": "655899910563217408", - "language": "en" - }, - { - "content": "RT @MalikaGhosh: Here we GO- let's lose ourselves #belief NOW @Oprah JOY http:\/\/t.co\/vYSNLd3LvC", - "contenttype": "text/plain", - "created": 1445212831000, - "id": "655896269542420480", - "language": "en" - }, - { - "content": "RT @MastinKipp: .@Oprah and team are about to bring the Light with #Belief.", - "contenttype": "text/plain", - "created": 1445212747000, - "id": "655895916675600384", - "language": "en" - }, - { - "content": "RT @GrowingOWN: 7 minutes, y'all! #BELIEF", - "contenttype": "text/plain", - "created": 1445212465000, - "id": "655894734968217600", - "language": "en" - }, - { - "content": "RT @LPToussaint: BELIEF defines experience.Choose wisely #Belief Tonight on OWN", - "contenttype": "text/plain", - "created": 1445211845000, - "id": "655892134524878848", - "language": "en" - }, - { - "content": "RT @TheBeBeWinans: Congratulations to my dear friend @Oprah on the launch of your series #BELIEF #Tonight on @OWNTV. Your friendship inspir\u2026", - "contenttype": "text/plain", - "created": 1445211835000, - "id": "655892094905532416", - "language": "en" - }, - { - "content": "RT @UzoAduba: Thirty minutes to @Oprah #Belief. Pretty sure it's about to be our favorite thing.", - "contenttype": "text/plain", - "created": 1445211833000, - "id": "655892084314890240", - "language": "en" - }, - { - "content": "RT @DeandresVoice: Moments away from the start of @SuperSoulSunday and the first night of the epic #Belief series on @OWNTV - are you ready\u2026", - "contenttype": "text/plain", - "created": 1445209201000, - "id": "655881046102142978", - "language": "en" - }, - { - "content": "RT @jennaldewan: I CANT WAIT FOR THIS TONIGHT!!!!!! Got my popcorn, got my tissues I am readyyyyyy! #Belief https:\/\/t.co\/WluTdeEqal", - "contenttype": "text/plain", - "created": 1445209181000, - "id": "655880959535939584", - "language": "en" - }, - { - "content": "RT @indiaarie: U heard about @Oprah passion project? It's called #Belief - I've see some & Its special! Tonight - 7c\/8e - 7 nights!! Whose\u2026", - "contenttype": "text/plain", - "created": 1445208945000, - "id": "655879970732949504", - "language": "en" - }, - { - "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass", - "contenttype": "text/plain", - "created": 1447639154000, - "id": "666073008692314113", - "language": "en" - }, - { - "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass", - "contenttype": "text/plain", - "created": 1447638226000, - "id": "666069114889179136", - "language": "en" - }, - { - "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass", - "contenttype": "text/plain", - "created": 1447638067000, - "id": "666068446325665792", - "language": "en" - }, - { - "content": "Wow aren't you loving @TheRock and his candor? #Masterclass", - "contenttype": "text/plain", - "created": 1447637459000, - "id": "666065895932973057", - "language": "en" - }, - { - "content": "RT @patt_t: @TheRock @Oprah @RichOnOWN @OWNTV this interview makes me like you as a fellow human even more for being so real.", - "contenttype": "text/plain", - "created": 1447637030000, - "id": "666064097562247168", - "language": "en" - }, - { - "content": "\"Be You\".. That's the best advice ever @TheRock #MastersClass", - "contenttype": "text/plain", - "created": 1447636205000, - "id": "666060637181644800", - "language": "en" - }, - { - "content": "Supersoulers let's lift our spirits pray and hold Paris in the Light\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1447602477000, - "id": "665919171062927360", - "language": "en" - }, - { - "content": "RT @DeepakChopra: What I learned in week 1: Become What You Believe 21-Day Meditation Experience - https:\/\/t.co\/kqaMaMqEUp #GoogleAlerts", - "contenttype": "text/plain", - "created": 1447098990000, - "id": "663807393063538688", - "language": "en" - }, - { - "content": "Watching Bryan Stevenson on #SuperSoulSunday! \"You are not the worst mistake you ever made\".\nAren't we glad about that.", - "contenttype": "text/plain", - "created": 1446998643000, - "id": "663386507856736257", - "language": "en" - }, - { - "content": ".@CherylStrayed BRAVE ENOUGH my new favorite thing! Gonna buy a copy for all my girls. #Perfectgift https:\/\/t.co\/gz1tnv8t8K", - "contenttype": "text/plain", - "created": 1446915955000, - "id": "663039689360695296", - "language": "en" - }, - { - "content": "Stevie Wonder singing \"Happy Birthday to you!\" to my dear mariashriver. A phenomenal woman and\u2026 https:\/\/t.co\/Ygm5eDIs4f", - "contenttype": "text/plain", - "created": 1446881193000, - "id": "662893888080879616", - "language": "en" - }, - { - "content": "It\u2019s my faaaaavorite time of the Year! For the first time you can shop the list on @amazon! https:\/\/t.co\/a6GMvVrhjN https:\/\/t.co\/sJlQMROq5U", - "contenttype": "text/plain", - "created": 1446744186000, - "id": "662319239844380672", - "language": "en" - }, - { - "content": "Incredible story \"the spirit of the Lord is on you\" thanks for sharing @smokey_robinson #Masterclass", - "contenttype": "text/plain", - "created": 1446428929000, - "id": "660996956861280256", - "language": "en" - }, - { - "content": "Wasnt that incredible story about @smokey_robinson 's dad leaving his family at 12. #MasterClass", - "contenttype": "text/plain", - "created": 1446426630000, - "id": "660987310889041920", - "language": "en" - }, - { - "content": "Gayle, Charlie, Nora @CBSThisMorning Congratulations! #1000thshow", - "contenttype": "text/plain", - "created": 1446220097000, - "id": "660121050978611205", - "language": "en" - }, - { - "content": "I believe your home should rise up to meet you. @TheEllenShow you nailed it with HOME. Tweethearts, grab a copy! https:\/\/t.co\/iFMnpRAsno", - "contenttype": "text/plain", - "created": 1446074433000, - "id": "659510090748182528", - "language": "en" - }, - { - "content": "Can I get a Witness?!\u270b\ud83c\udffe https:\/\/t.co\/tZ1QyAeSdE", - "contenttype": "text/plain", - "created": 1445821114000, - "id": "658447593865945089", - "language": "en" - }, - { - "content": ".@TheEllenShow you're a treasure.\nYour truth set a lot of people free.\n#Masterclass", - "contenttype": "text/plain", - "created": 1445821003000, - "id": "658447130026188800", - "language": "en" - }, - { - "content": "Hope you all are enjoying @TheEllenShow on #MasterClass.", - "contenttype": "text/plain", - "created": 1445820161000, - "id": "658443598313181188", - "language": "en" - }, - { - "content": ".@GloriaSteinem, shero to women everywhere, on how far we\u2019ve come and how far we need to go. #SuperSoulSunday 7p\/6c.\nhttps:\/\/t.co\/3e7oxXW02J", - "contenttype": "text/plain", - "created": 1445811545000, - "id": "658407457438363648", - "language": "en" - }, - { - "content": "RT @TheEllenShow: I told a story from my @OWNTV's #MasterClass on my show. Normally I\u2019d save it all for Sunday, but @Oprah made me. https:\/\u2026", - "contenttype": "text/plain", - "created": 1445804181000, - "id": "658376572521459712", - "language": "en" - }, - { - "content": ".@TheEllenShow is a master teacher of living her truth & living authentically as herself. #MasterClass tonight 8\/7c.\nhttps:\/\/t.co\/iLT2KgRsSw", - "contenttype": "text/plain", - "created": 1445804072000, - "id": "658376116575449088", - "language": "en" - }, - { - "content": ".@SheriSalata , @jonnysinc @part2pictures . Tears of joy and gratitude to you and our entire #BeliefTeam We DID IT!! My heart is full.\ud83d\ude4f\ud83c\udffe\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1445734755000, - "id": "658085377140363264", - "language": "en" - }, - { - "content": "Donna and Bob saw the tape of their story just days before she passed. They appreciated it. #RIPDonna", - "contenttype": "text/plain", - "created": 1445734097000, - "id": "658082618819280896", - "language": "en" - }, - { - "content": "RT @rempower: .@Oprah this series allowed me to slide into people's lives around the world and see the same in them ... we all have a belie\u2026", - "contenttype": "text/plain", - "created": 1445732769000, - "id": "658077046858383360", - "language": "en" - }, - { - "content": "All the stories moved me, My favorite line \" I must pass the stories on to my grandson otherwise our people will loose their way. #Belief", - "contenttype": "text/plain", - "created": 1445732579000, - "id": "658076253618991104", - "language": "en" - }, - { - "content": ".@part2pictures some of your best imagery yet. Filming Alex on the rock.#Belief", - "contenttype": "text/plain", - "created": 1445731782000, - "id": "658072908237934592", - "language": "en" - }, - { - "content": "I just love Alex and his daring #Belief to live fully the present Moment.", - "contenttype": "text/plain", - "created": 1445731561000, - "id": "658071980982206464", - "language": "en" - }, - { - "content": "RT @GrowingOWN: Let's do this! #Belief finale tweet tweet party. Thank you @Oprah! \ud83d\ude4f", - "contenttype": "text/plain", - "created": 1445731248000, - "id": "658070668785770496", - "language": "en" - }, - { - "content": "RT @lizkinnell: The epic finale of #Belief on @OWNTV is about to start. 8\/et Are you ready? What do you Believe?", - "contenttype": "text/plain", - "created": 1445731081000, - "id": "658069968534171648", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night of Belief. Belief runs all day tomorrow for bingers and final episode!", - "contenttype": "text/plain", - "created": 1445648630000, - "id": "657724143115202560", - "language": "en" - }, - { - "content": "RT @OWNingLight: #Belief is the ultimate travel map to mass acceptance. \ud83d\ude4f\ud83c\udffb\u2764\ufe0f\ud83c\udf0d @Oprah", - "contenttype": "text/plain", - "created": 1445647285000, - "id": "657718501147197442", - "language": "en" - }, - { - "content": "\" I can feel my heart opening and faith coming back in\".. What's better than that? #Belief", - "contenttype": "text/plain", - "created": 1445646903000, - "id": "657716901951369218", - "language": "en" - }, - { - "content": "Hey Belief team mates can yo believe how quickly the week has passed? #Belief", - "contenttype": "text/plain", - "created": 1445645633000, - "id": "657711572492533760", - "language": "en" - }, - { - "content": "Ran into @5SOS backstage. Fun times with @TheEllenShow today! https:\/\/t.co\/2PP3W3RzXc", - "contenttype": "text/plain", - "created": 1445618531000, - "id": "657597898394173440", - "language": "en" - }, - { - "content": "Thanks All for another great night of #BELIEF", - "contenttype": "text/plain", - "created": 1445572548000, - "id": "657405031822430208", - "language": "en" - }, - { - "content": "RT @3LWTV: #BecomeWhatYouBelieve New meditation w\/ @Oprah @DeepakChopra begins 11\/2 Register https:\/\/t.co\/x0R9HWTAX0 #Belief https:\/\/t.co\/\u2026", - "contenttype": "text/plain", - "created": 1445571500000, - "id": "657400636745510912", - "language": "en" - }, - { - "content": "Ok west coast let's do it! #belief", - "contenttype": "text/plain", - "created": 1445569367000, - "id": "657391689439404033", - "language": "en" - }, - { - "content": "Thank u kind gentleman who told me I had kale in my teeth. Was eating kale chips with Quincy Jones. Went straight to @LairdLife party.", - "contenttype": "text/plain", - "created": 1445569296000, - "id": "657391393883619328", - "language": "en" - }, - { - "content": "Hello west coast twitterati.. See you at 8 for #Belief", - "contenttype": "text/plain", - "created": 1445566144000, - "id": "657378171872874496", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night.#Belief", - "contenttype": "text/plain", - "created": 1445475948000, - "id": "656999861254918145", - "language": "en" - }, - { - "content": "RT @PRanganathan: \"Transformation is the rule of the game. The universe is not standing still.\" - Marcelo @OWNTV @Oprah #Belief", - "contenttype": "text/plain", - "created": 1445475602000, - "id": "656998409933451264", - "language": "en" - }, - { - "content": "\"The Universe is not standing still.. The whole Universe is expanding\" I love the dance between science and spirituality! #Belief", - "contenttype": "text/plain", - "created": 1445475580000, - "id": "656998320133398528", - "language": "en" - }, - { - "content": "\"Without our prayers and our songs we won't be here\" Apache leader.#Belief", - "contenttype": "text/plain", - "created": 1445473768000, - "id": "656990717504393216", - "language": "en" - }, - { - "content": "Notice her mother crying. She knows its last tine she will ever see her daughter.#Belief", - "contenttype": "text/plain", - "created": 1445473150000, - "id": "656988127433637888", - "language": "en" - }, - { - "content": "This final trial is unbelievable. Every hair gets pulled from her head one at a time. Now that is Something!!#Belief", - "contenttype": "text/plain", - "created": 1445473063000, - "id": "656987763644891136", - "language": "en" - }, - { - "content": "\"What my faith gives me no one can match\"#Belief", - "contenttype": "text/plain", - "created": 1445472961000, - "id": "656987336266223616", - "language": "en" - }, - { - "content": "It's a devotion to faith beyond anything Ive seen. Fascinating.Jain nuns. #Belief", - "contenttype": "text/plain", - "created": 1445472531000, - "id": "656985529951522816", - "language": "en" - }, - { - "content": "I'd never heard of Jain monks and nuns before doing this series. #Belief", - "contenttype": "text/plain", - "created": 1445472393000, - "id": "656984953037586433", - "language": "en" - }, - { - "content": "Good evening Team #Belief the Tweet is on!", - "contenttype": "text/plain", - "created": 1445472098000, - "id": "656983714883239937", - "language": "en" - }, - { - "content": "Thanks everyone for another Epic #Belief night!", - "contenttype": "text/plain", - "created": 1445302792000, - "id": "656273592485810176", - "language": "en" - }, - { - "content": "The Pastor and Imam represent the possibility of PEACE in the world. If they can do it. We can. Peace to All\ud83d\ude4f\ud83c\udffe #Belief", - "contenttype": "text/plain", - "created": 1445302749000, - "id": "656273415280705536", - "language": "en" - }, - { - "content": "We felt privileged to film the Hajj and explore the beauty of Islam.\n#99namesforGod #Belief", - "contenttype": "text/plain", - "created": 1445301110000, - "id": "656266540967424000", - "language": "en" - }, - { - "content": "Do you all believe in \"soul mates\"?\n#Belief", - "contenttype": "text/plain", - "created": 1445300138000, - "id": "656262462426238976", - "language": "en" - }, - { - "content": ".@RevEdBacon thank you so much for hosting tonight's #Belief at All Saints Church.", - "contenttype": "text/plain", - "created": 1445299749000, - "id": "656260832628756480", - "language": "en" - }, - { - "content": "This is one of the best love stories I've ever seen. #belief Ian and Larissa showing us the depths of love.#Belief", - "contenttype": "text/plain", - "created": 1445299614000, - "id": "656260263604310016", - "language": "en" - }, - { - "content": "Hey Everyone .. Tweeting from a bar in Atlanta with @SheriSalata OWN not in my hotel. Anything for #Belief", - "contenttype": "text/plain", - "created": 1445299326000, - "id": "656259057758654464", - "language": "en" - }, - { - "content": "RT @joshuadubois: When you see Ian & Larissa tonight on #BELIEF, you'll know what Christian love is all about. 8pmET, @OWNTV. Tune in! http\u2026", - "contenttype": "text/plain", - "created": 1445295716000, - "id": "656243916224638976", - "language": "en" - }, - { - "content": "RT @KimHaleDance: I Believe LAUGHTER. IS. CONTAGIOUS. What do you believe? See you tonight! 8\/7c.\u2764\ufe0f #Belief #Beliefin3words https:\/\/t.co\/x\u2026", - "contenttype": "text/plain", - "created": 1445295702000, - "id": "656243854610337793", - "language": "en" - }, - { - "content": "RT @OWNTV: See the world through someone else\u2019s soul. The epic journey of #Belief continues tonight at 8\/7c.\nhttps:\/\/t.co\/UKKMHZuC0g", - "contenttype": "text/plain", - "created": 1445295668000, - "id": "656243714507931648", - "language": "en" - }, - { - "content": "RT @OWNTV: Mendel Hurwitz's inquisitive nature grounded him in his faith. See where it's taken him now: https:\/\/t.co\/2iWmNOxK9r https:\/\/t.c\u2026", - "contenttype": "text/plain", - "created": 1445295661000, - "id": "656243684720050176", - "language": "en" - }, - { - "content": "Thank you for opening up the heart space and letting #Belief in. Tonight it keeps getting better. See you at 8\/7c\nhttps:\/\/t.co\/E65vkTray9", - "contenttype": "text/plain", - "created": 1445279425000, - "id": "656175584943341568", - "language": "en" - }, - { - "content": "I believe in the @weightwatchers program so much I decided to invest, join the Board, and partner in #wwfamily evolution.", - "contenttype": "text/plain", - "created": 1445275802000, - "id": "656160388526899200", - "language": "en" - }, - { - "content": "RT @AVAETC: Debut episode of #BELIEF has now aired on both coasts. Trended for 4 hours. Brava, @Oprah + team. 6 beautiful nights to come. B\u2026", - "contenttype": "text/plain", - "created": 1445229489000, - "id": "655966138279432192", - "language": "en" - }, - { - "content": "RT @3LWTV: 6 more epic nights of #Belief to come! See you tomorrow 8pET\/7pCT for the next installment! @OWNTV @Oprah", - "contenttype": "text/plain", - "created": 1445227342000, - "id": "655957135688241152", - "language": "en" - }, - { - "content": "RT @ledisi: I love how Ancestry and Tradition is honored throughout every story in #Belief @OWNTV @OWN Thank you @Oprah this is so importa\u2026", - "contenttype": "text/plain", - "created": 1445225935000, - "id": "655951232981295104", - "language": "en" - }, - { - "content": "RT @UN: Showing #Belief at the UN \"is a bigger dream than I had\" - @Oprah https:\/\/t.co\/VC4OqD8yub #Belief #GlobalGoals https:\/\/t.co\/LZyGuC7\u2026", - "contenttype": "text/plain", - "created": 1445225228000, - "id": "655948267868426240", - "language": "en" - }, - { - "content": "RT @UzoAduba: To seek, to question, to learn, to teach, to pass it on; some of the breathtaking themes running like water throughout #Belie\u2026", - "contenttype": "text/plain", - "created": 1445225008000, - "id": "655947345197076480", - "language": "en" - }, - { - "content": "RT @iamtikasumpter: #Belief had me in awe. Faith in the divine is the constant that links us together. It's all beautiful and righteous. Gi\u2026", - "contenttype": "text/plain", - "created": 1445224852000, - "id": "655946689249828864", - "language": "en" - }, - { - "content": "West Coast... Here we go. #Belief", - "contenttype": "text/plain", - "created": 1445224140000, - "id": "655943701840048128", - "language": "en" - }, - { - "content": "Big surprise at icanady watch party. Epic night. #Belief. So much more to come. https:\/\/t.co\/kBDtFwGyQs", - "contenttype": "text/plain", - "created": 1445220694000, - "id": "655929249669378048", - "language": "en" - }, - { - "content": "I loved the Mendel story so much because it represents right of passasge. \" bye bye to childhood\".#Belief", - "contenttype": "text/plain", - "created": 1445215032000, - "id": "655905500056391682", - "language": "en" - }, - { - "content": "RT @squee_machine: This is a visual feast! Completely gorgeous and I am transfixed. The colors, the composition, cinematography, vibe. #Bel\u2026", - "contenttype": "text/plain", - "created": 1445214538000, - "id": "655903432079904768", - "language": "en" - }, - { - "content": "RT @JamesTyphany: Looking at @ #Belief I really needed this in my life thanks @OWNTV", - "contenttype": "text/plain", - "created": 1445214534000, - "id": "655903413385891840", - "language": "en" - }, - { - "content": "Just surprised a \"watch party\" @icanady 's house. #Belief http:\/\/t.co\/Di0I3OooCh", - "contenttype": "text/plain", - "created": 1445214502000, - "id": "655903277796732931", - "language": "en" - }, - { - "content": "RT @MsLaWandaa: I love moments of sitting among elders and learning. I can feel this moment was special for @ReshThakkar #Belief", - "contenttype": "text/plain", - "created": 1445214498000, - "id": "655903264374812672", - "language": "en" - }, - { - "content": "RT @xonecole: \"Do you have to have religion or is being a good person...is that enough?\" #Belief", - "contenttype": "text/plain", - "created": 1445214339000, - "id": "655902594171203584", - "language": "en" - }, - { - "content": "RT @ChivonJohn: Very inspired by the stories on #belief https:\/\/t.co\/uMRCCfCWcY", - "contenttype": "text/plain", - "created": 1445214327000, - "id": "655902545903140864", - "language": "en" - }, - { - "content": "RT @KiranSArora: powerful personal story that many of us can connect to. searching for what's missing, spiritual liberation. @ReshThakkar #\u2026", - "contenttype": "text/plain", - "created": 1445214128000, - "id": "655901708506103812", - "language": "en" - }, - { - "content": "RT @createdbyerica: \"I'm willing to go as far as I have to go to get that feeling in my heart of being connected to the Divine.\" - Reshma @\u2026", - "contenttype": "text/plain", - "created": 1445213967000, - "id": "655901033952993280", - "language": "en" - }, - { - "content": "RT @UrbnHealthNP: I am enjoying this so much. #Belief", - "contenttype": "text/plain", - "created": 1445213904000, - "id": "655900772467474435", - "language": "en" - }, - { - "content": "RT @DrMABrown: Your relationship with #belief can be completely different than how others experience it", - "contenttype": "text/plain", - "created": 1445213901000, - "id": "655900756604620800", - "language": "en" - }, - { - "content": "RT @ckerfin: On another river on the other side of the world... transition between stories, drawing connections to different beliefs #Belie\u2026", - "contenttype": "text/plain", - "created": 1445213721000, - "id": "655900002644987905", - "language": "en" - }, - { - "content": "RT @nikfarrior: So profound. We are all born into #Belief @Oprah @OWN @OWNTV", - "contenttype": "text/plain", - "created": 1445213706000, - "id": "655899942242775040", - "language": "en" - }, - { - "content": "RT @fgaboys: @Oprah the start of #Belief is riveting and edifying. It makes you want more and inspires you too see what's coming up next. \u2026", - "contenttype": "text/plain", - "created": 1445213699000, - "id": "655899910563217408", - "language": "en" - }, - { - "content": "RT @MalikaGhosh: Here we GO- let's lose ourselves #belief NOW @Oprah JOY http:\/\/t.co\/vYSNLd3LvC", - "contenttype": "text/plain", - "created": 1445212831000, - "id": "655896269542420480", - "language": "en" - }, - { - "content": "RT @MastinKipp: .@Oprah and team are about to bring the Light with #Belief.", - "contenttype": "text/plain", - "created": 1445212747000, - "id": "655895916675600384", - "language": "en" - }, - { - "content": "RT @GrowingOWN: 7 minutes, y'all! #BELIEF", - "contenttype": "text/plain", - "created": 1445212465000, - "id": "655894734968217600", - "language": "en" - }, - { - "content": "RT @LPToussaint: BELIEF defines experience.Choose wisely #Belief Tonight on OWN", - "contenttype": "text/plain", - "created": 1445211845000, - "id": "655892134524878848", - "language": "en" - }, - { - "content": "RT @TheBeBeWinans: Congratulations to my dear friend @Oprah on the launch of your series #BELIEF #Tonight on @OWNTV. Your friendship inspir\u2026", - "contenttype": "text/plain", - "created": 1445211835000, - "id": "655892094905532416", - "language": "en" - }, - { - "content": "RT @UzoAduba: Thirty minutes to @Oprah #Belief. Pretty sure it's about to be our favorite thing.", - "contenttype": "text/plain", - "created": 1445211833000, - "id": "655892084314890240", - "language": "en" - }, - { - "content": "RT @DeandresVoice: Moments away from the start of @SuperSoulSunday and the first night of the epic #Belief series on @OWNTV - are you ready\u2026", - "contenttype": "text/plain", - "created": 1445209201000, - "id": "655881046102142978", - "language": "en" - }, - { - "content": "RT @jennaldewan: I CANT WAIT FOR THIS TONIGHT!!!!!! Got my popcorn, got my tissues I am readyyyyyy! #Belief https:\/\/t.co\/WluTdeEqal", - "contenttype": "text/plain", - "created": 1445209181000, - "id": "655880959535939584", - "language": "en" - }, - { - "content": "RT @indiaarie: U heard about @Oprah passion project? It's called #Belief - I've see some & Its special! Tonight - 7c\/8e - 7 nights!! Whose\u2026", - "contenttype": "text/plain", - "created": 1445208945000, - "id": "655879970732949504", - "language": "en" - }, - { - "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass", - "contenttype": "text/plain", - "created": 1447639154000, - "id": "666073008692314113", - "language": "en" - }, - { - "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass", - "contenttype": "text/plain", - "created": 1447638226000, - "id": "666069114889179136", - "language": "en" - }, - { - "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass", - "contenttype": "text/plain", - "created": 1447638067000, - "id": "666068446325665792", - "language": "en" - }, - { - "content": "Wow aren't you loving @TheRock and his candor? #Masterclass", - "contenttype": "text/plain", - "created": 1447637459000, - "id": "666065895932973057", - "language": "en" - }, - { - "content": "RT @patt_t: @TheRock @Oprah @RichOnOWN @OWNTV this interview makes me like you as a fellow human even more for being so real.", - "contenttype": "text/plain", - "created": 1447637030000, - "id": "666064097562247168", - "language": "en" - }, - { - "content": "\"Be You\".. That's the best advice ever @TheRock #MastersClass", - "contenttype": "text/plain", - "created": 1447636205000, - "id": "666060637181644800", - "language": "en" - }, - { - "content": "Supersoulers let's lift our spirits pray and hold Paris in the Light\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1447602477000, - "id": "665919171062927360", - "language": "en" - }, - { - "content": "RT @DeepakChopra: What I learned in week 1: Become What You Believe 21-Day Meditation Experience - https:\/\/t.co\/kqaMaMqEUp #GoogleAlerts", - "contenttype": "text/plain", - "created": 1447098990000, - "id": "663807393063538688", - "language": "en" - }, - { - "content": "Watching Bryan Stevenson on #SuperSoulSunday! \"You are not the worst mistake you ever made\".\nAren't we glad about that.", - "contenttype": "text/plain", - "created": 1446998643000, - "id": "663386507856736257", - "language": "en" - }, - { - "content": ".@CherylStrayed BRAVE ENOUGH my new favorite thing! Gonna buy a copy for all my girls. #Perfectgift https:\/\/t.co\/gz1tnv8t8K", - "contenttype": "text/plain", - "created": 1446915955000, - "id": "663039689360695296", - "language": "en" - }, - { - "content": "Stevie Wonder singing \"Happy Birthday to you!\" to my dear mariashriver. A phenomenal woman and\u2026 https:\/\/t.co\/Ygm5eDIs4f", - "contenttype": "text/plain", - "created": 1446881193000, - "id": "662893888080879616", - "language": "en" - }, - { - "content": "It\u2019s my faaaaavorite time of the Year! For the first time you can shop the list on @amazon! https:\/\/t.co\/a6GMvVrhjN https:\/\/t.co\/sJlQMROq5U", - "contenttype": "text/plain", - "created": 1446744186000, - "id": "662319239844380672", - "language": "en" - }, - { - "content": "Incredible story \"the spirit of the Lord is on you\" thanks for sharing @smokey_robinson #Masterclass", - "contenttype": "text/plain", - "created": 1446428929000, - "id": "660996956861280256", - "language": "en" - }, - { - "content": "Wasnt that incredible story about @smokey_robinson 's dad leaving his family at 12. #MasterClass", - "contenttype": "text/plain", - "created": 1446426630000, - "id": "660987310889041920", - "language": "en" - }, - { - "content": "Gayle, Charlie, Nora @CBSThisMorning Congratulations! #1000thshow", - "contenttype": "text/plain", - "created": 1446220097000, - "id": "660121050978611205", - "language": "en" - }, - { - "content": "I believe your home should rise up to meet you. @TheEllenShow you nailed it with HOME. Tweethearts, grab a copy! https:\/\/t.co\/iFMnpRAsno", - "contenttype": "text/plain", - "created": 1446074433000, - "id": "659510090748182528", - "language": "en" - }, - { - "content": "Can I get a Witness?!\u270b\ud83c\udffe https:\/\/t.co\/tZ1QyAeSdE", - "contenttype": "text/plain", - "created": 1445821114000, - "id": "658447593865945089", - "language": "en" - }, - { - "content": ".@TheEllenShow you're a treasure.\nYour truth set a lot of people free.\n#Masterclass", - "contenttype": "text/plain", - "created": 1445821003000, - "id": "658447130026188800", - "language": "en" - }, - { - "content": "Hope you all are enjoying @TheEllenShow on #MasterClass.", - "contenttype": "text/plain", - "created": 1445820161000, - "id": "658443598313181188", - "language": "en" - }, - { - "content": ".@GloriaSteinem, shero to women everywhere, on how far we\u2019ve come and how far we need to go. #SuperSoulSunday 7p\/6c.\nhttps:\/\/t.co\/3e7oxXW02J", - "contenttype": "text/plain", - "created": 1445811545000, - "id": "658407457438363648", - "language": "en" - }, - { - "content": "RT @TheEllenShow: I told a story from my @OWNTV's #MasterClass on my show. Normally I\u2019d save it all for Sunday, but @Oprah made me. https:\/\u2026", - "contenttype": "text/plain", - "created": 1445804181000, - "id": "658376572521459712", - "language": "en" - }, - { - "content": ".@TheEllenShow is a master teacher of living her truth & living authentically as herself. #MasterClass tonight 8\/7c.\nhttps:\/\/t.co\/iLT2KgRsSw", - "contenttype": "text/plain", - "created": 1445804072000, - "id": "658376116575449088", - "language": "en" - }, - { - "content": ".@SheriSalata , @jonnysinc @part2pictures . Tears of joy and gratitude to you and our entire #BeliefTeam We DID IT!! My heart is full.\ud83d\ude4f\ud83c\udffe\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1445734755000, - "id": "658085377140363264", - "language": "en" - }, - { - "content": "Donna and Bob saw the tape of their story just days before she passed. They appreciated it. #RIPDonna", - "contenttype": "text/plain", - "created": 1445734097000, - "id": "658082618819280896", - "language": "en" - }, - { - "content": "RT @rempower: .@Oprah this series allowed me to slide into people's lives around the world and see the same in them ... we all have a belie\u2026", - "contenttype": "text/plain", - "created": 1445732769000, - "id": "658077046858383360", - "language": "en" - }, - { - "content": "All the stories moved me, My favorite line \" I must pass the stories on to my grandson otherwise our people will loose their way. #Belief", - "contenttype": "text/plain", - "created": 1445732579000, - "id": "658076253618991104", - "language": "en" - }, - { - "content": ".@part2pictures some of your best imagery yet. Filming Alex on the rock.#Belief", - "contenttype": "text/plain", - "created": 1445731782000, - "id": "658072908237934592", - "language": "en" - }, - { - "content": "I just love Alex and his daring #Belief to live fully the present Moment.", - "contenttype": "text/plain", - "created": 1445731561000, - "id": "658071980982206464", - "language": "en" - }, - { - "content": "RT @GrowingOWN: Let's do this! #Belief finale tweet tweet party. Thank you @Oprah! \ud83d\ude4f", - "contenttype": "text/plain", - "created": 1445731248000, - "id": "658070668785770496", - "language": "en" - }, - { - "content": "RT @lizkinnell: The epic finale of #Belief on @OWNTV is about to start. 8\/et Are you ready? What do you Believe?", - "contenttype": "text/plain", - "created": 1445731081000, - "id": "658069968534171648", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night of Belief. Belief runs all day tomorrow for bingers and final episode!", - "contenttype": "text/plain", - "created": 1445648630000, - "id": "657724143115202560", - "language": "en" - }, - { - "content": "RT @OWNingLight: #Belief is the ultimate travel map to mass acceptance. \ud83d\ude4f\ud83c\udffb\u2764\ufe0f\ud83c\udf0d @Oprah", - "contenttype": "text/plain", - "created": 1445647285000, - "id": "657718501147197442", - "language": "en" - }, - { - "content": "\" I can feel my heart opening and faith coming back in\".. What's better than that? #Belief", - "contenttype": "text/plain", - "created": 1445646903000, - "id": "657716901951369218", - "language": "en" - }, - { - "content": "Hey Belief team mates can yo believe how quickly the week has passed? #Belief", - "contenttype": "text/plain", - "created": 1445645633000, - "id": "657711572492533760", - "language": "en" - }, - { - "content": "Ran into @5SOS backstage. Fun times with @TheEllenShow today! https:\/\/t.co\/2PP3W3RzXc", - "contenttype": "text/plain", - "created": 1445618531000, - "id": "657597898394173440", - "language": "en" - }, - { - "content": "Thanks All for another great night of #BELIEF", - "contenttype": "text/plain", - "created": 1445572548000, - "id": "657405031822430208", - "language": "en" - }, - { - "content": "RT @3LWTV: #BecomeWhatYouBelieve New meditation w\/ @Oprah @DeepakChopra begins 11\/2 Register https:\/\/t.co\/x0R9HWTAX0 #Belief https:\/\/t.co\/\u2026", - "contenttype": "text/plain", - "created": 1445571500000, - "id": "657400636745510912", - "language": "en" - }, - { - "content": "Ok west coast let's do it! #belief", - "contenttype": "text/plain", - "created": 1445569367000, - "id": "657391689439404033", - "language": "en" - }, - { - "content": "Thank u kind gentleman who told me I had kale in my teeth. Was eating kale chips with Quincy Jones. Went straight to @LairdLife party.", - "contenttype": "text/plain", - "created": 1445569296000, - "id": "657391393883619328", - "language": "en" - }, - { - "content": "Hello west coast twitterati.. See you at 8 for #Belief", - "contenttype": "text/plain", - "created": 1445566144000, - "id": "657378171872874496", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night.#Belief", - "contenttype": "text/plain", - "created": 1445475948000, - "id": "656999861254918145", - "language": "en" - }, - { - "content": "RT @PRanganathan: \"Transformation is the rule of the game. The universe is not standing still.\" - Marcelo @OWNTV @Oprah #Belief", - "contenttype": "text/plain", - "created": 1445475602000, - "id": "656998409933451264", - "language": "en" - }, - { - "content": "\"The Universe is not standing still.. The whole Universe is expanding\" I love the dance between science and spirituality! #Belief", - "contenttype": "text/plain", - "created": 1445475580000, - "id": "656998320133398528", - "language": "en" - }, - { - "content": "\"Without our prayers and our songs we won't be here\" Apache leader.#Belief", - "contenttype": "text/plain", - "created": 1445473768000, - "id": "656990717504393216", - "language": "en" - }, - { - "content": "Notice her mother crying. She knows its last tine she will ever see her daughter.#Belief", - "contenttype": "text/plain", - "created": 1445473150000, - "id": "656988127433637888", - "language": "en" - }, - { - "content": "This final trial is unbelievable. Every hair gets pulled from her head one at a time. Now that is Something!!#Belief", - "contenttype": "text/plain", - "created": 1445473063000, - "id": "656987763644891136", - "language": "en" - }, - { - "content": "\"What my faith gives me no one can match\"#Belief", - "contenttype": "text/plain", - "created": 1445472961000, - "id": "656987336266223616", - "language": "en" - }, - { - "content": "It's a devotion to faith beyond anything Ive seen. Fascinating.Jain nuns. #Belief", - "contenttype": "text/plain", - "created": 1445472531000, - "id": "656985529951522816", - "language": "en" - }, - { - "content": "I'd never heard of Jain monks and nuns before doing this series. #Belief", - "contenttype": "text/plain", - "created": 1445472393000, - "id": "656984953037586433", - "language": "en" - }, - { - "content": "Good evening Team #Belief the Tweet is on!", - "contenttype": "text/plain", - "created": 1445472098000, - "id": "656983714883239937", - "language": "en" - }, - { - "content": "Thanks everyone for another Epic #Belief night!", - "contenttype": "text/plain", - "created": 1445302792000, - "id": "656273592485810176", - "language": "en" - }, - { - "content": "The Pastor and Imam represent the possibility of PEACE in the world. If they can do it. We can. Peace to All\ud83d\ude4f\ud83c\udffe #Belief", - "contenttype": "text/plain", - "created": 1445302749000, - "id": "656273415280705536", - "language": "en" - }, - { - "content": "We felt privileged to film the Hajj and explore the beauty of Islam.\n#99namesforGod #Belief", - "contenttype": "text/plain", - "created": 1445301110000, - "id": "656266540967424000", - "language": "en" - }, - { - "content": "Do you all believe in \"soul mates\"?\n#Belief", - "contenttype": "text/plain", - "created": 1445300138000, - "id": "656262462426238976", - "language": "en" - }, - { - "content": ".@RevEdBacon thank you so much for hosting tonight's #Belief at All Saints Church.", - "contenttype": "text/plain", - "created": 1445299749000, - "id": "656260832628756480", - "language": "en" - }, - { - "content": "This is one of the best love stories I've ever seen. #belief Ian and Larissa showing us the depths of love.#Belief", - "contenttype": "text/plain", - "created": 1445299614000, - "id": "656260263604310016", - "language": "en" - }, - { - "content": "Hey Everyone .. Tweeting from a bar in Atlanta with @SheriSalata OWN not in my hotel. Anything for #Belief", - "contenttype": "text/plain", - "created": 1445299326000, - "id": "656259057758654464", - "language": "en" - }, - { - "content": "RT @joshuadubois: When you see Ian & Larissa tonight on #BELIEF, you'll know what Christian love is all about. 8pmET, @OWNTV. Tune in! http\u2026", - "contenttype": "text/plain", - "created": 1445295716000, - "id": "656243916224638976", - "language": "en" - }, - { - "content": "RT @KimHaleDance: I Believe LAUGHTER. IS. CONTAGIOUS. What do you believe? See you tonight! 8\/7c.\u2764\ufe0f #Belief #Beliefin3words https:\/\/t.co\/x\u2026", - "contenttype": "text/plain", - "created": 1445295702000, - "id": "656243854610337793", - "language": "en" - }, - { - "content": "RT @OWNTV: See the world through someone else\u2019s soul. The epic journey of #Belief continues tonight at 8\/7c.\nhttps:\/\/t.co\/UKKMHZuC0g", - "contenttype": "text/plain", - "created": 1445295668000, - "id": "656243714507931648", - "language": "en" - }, - { - "content": "RT @OWNTV: Mendel Hurwitz's inquisitive nature grounded him in his faith. See where it's taken him now: https:\/\/t.co\/2iWmNOxK9r https:\/\/t.c\u2026", - "contenttype": "text/plain", - "created": 1445295661000, - "id": "656243684720050176", - "language": "en" - }, - { - "content": "Thank you for opening up the heart space and letting #Belief in. Tonight it keeps getting better. See you at 8\/7c\nhttps:\/\/t.co\/E65vkTray9", - "contenttype": "text/plain", - "created": 1445279425000, - "id": "656175584943341568", - "language": "en" - }, - { - "content": "I believe in the @weightwatchers program so much I decided to invest, join the Board, and partner in #wwfamily evolution.", - "contenttype": "text/plain", - "created": 1445275802000, - "id": "656160388526899200", - "language": "en" - }, - { - "content": "RT @AVAETC: Debut episode of #BELIEF has now aired on both coasts. Trended for 4 hours. Brava, @Oprah + team. 6 beautiful nights to come. B\u2026", - "contenttype": "text/plain", - "created": 1445229489000, - "id": "655966138279432192", - "language": "en" - }, - { - "content": "RT @3LWTV: 6 more epic nights of #Belief to come! See you tomorrow 8pET\/7pCT for the next installment! @OWNTV @Oprah", - "contenttype": "text/plain", - "created": 1445227342000, - "id": "655957135688241152", - "language": "en" - }, - { - "content": "RT @ledisi: I love how Ancestry and Tradition is honored throughout every story in #Belief @OWNTV @OWN Thank you @Oprah this is so importa\u2026", - "contenttype": "text/plain", - "created": 1445225935000, - "id": "655951232981295104", - "language": "en" - }, - { - "content": "RT @UN: Showing #Belief at the UN \"is a bigger dream than I had\" - @Oprah https:\/\/t.co\/VC4OqD8yub #Belief #GlobalGoals https:\/\/t.co\/LZyGuC7\u2026", - "contenttype": "text/plain", - "created": 1445225228000, - "id": "655948267868426240", - "language": "en" - }, - { - "content": "RT @UzoAduba: To seek, to question, to learn, to teach, to pass it on; some of the breathtaking themes running like water throughout #Belie\u2026", - "contenttype": "text/plain", - "created": 1445225008000, - "id": "655947345197076480", - "language": "en" - }, - { - "content": "RT @iamtikasumpter: #Belief had me in awe. Faith in the divine is the constant that links us together. It's all beautiful and righteous. Gi\u2026", - "contenttype": "text/plain", - "created": 1445224852000, - "id": "655946689249828864", - "language": "en" - }, - { - "content": "West Coast... Here we go. #Belief", - "contenttype": "text/plain", - "created": 1445224140000, - "id": "655943701840048128", - "language": "en" - }, - { - "content": "Big surprise at icanady watch party. Epic night. #Belief. So much more to come. https:\/\/t.co\/kBDtFwGyQs", - "contenttype": "text/plain", - "created": 1445220694000, - "id": "655929249669378048", - "language": "en" - }, - { - "content": "I loved the Mendel story so much because it represents right of passasge. \" bye bye to childhood\".#Belief", - "contenttype": "text/plain", - "created": 1445215032000, - "id": "655905500056391682", - "language": "en" - }, - { - "content": "RT @squee_machine: This is a visual feast! Completely gorgeous and I am transfixed. The colors, the composition, cinematography, vibe. #Bel\u2026", - "contenttype": "text/plain", - "created": 1445214538000, - "id": "655903432079904768", - "language": "en" - }, - { - "content": "RT @JamesTyphany: Looking at @ #Belief I really needed this in my life thanks @OWNTV", - "contenttype": "text/plain", - "created": 1445214534000, - "id": "655903413385891840", - "language": "en" - }, - { - "content": "Just surprised a \"watch party\" @icanady 's house. #Belief http:\/\/t.co\/Di0I3OooCh", - "contenttype": "text/plain", - "created": 1445214502000, - "id": "655903277796732931", - "language": "en" - }, - { - "content": "RT @MsLaWandaa: I love moments of sitting among elders and learning. I can feel this moment was special for @ReshThakkar #Belief", - "contenttype": "text/plain", - "created": 1445214498000, - "id": "655903264374812672", - "language": "en" - }, - { - "content": "RT @xonecole: \"Do you have to have religion or is being a good person...is that enough?\" #Belief", - "contenttype": "text/plain", - "created": 1445214339000, - "id": "655902594171203584", - "language": "en" - }, - { - "content": "RT @ChivonJohn: Very inspired by the stories on #belief https:\/\/t.co\/uMRCCfCWcY", - "contenttype": "text/plain", - "created": 1445214327000, - "id": "655902545903140864", - "language": "en" - }, - { - "content": "RT @KiranSArora: powerful personal story that many of us can connect to. searching for what's missing, spiritual liberation. @ReshThakkar #\u2026", - "contenttype": "text/plain", - "created": 1445214128000, - "id": "655901708506103812", - "language": "en" - }, - { - "content": "RT @createdbyerica: \"I'm willing to go as far as I have to go to get that feeling in my heart of being connected to the Divine.\" - Reshma @\u2026", - "contenttype": "text/plain", - "created": 1445213967000, - "id": "655901033952993280", - "language": "en" - }, - { - "content": "RT @UrbnHealthNP: I am enjoying this so much. #Belief", - "contenttype": "text/plain", - "created": 1445213904000, - "id": "655900772467474435", - "language": "en" - }, - { - "content": "RT @DrMABrown: Your relationship with #belief can be completely different than how others experience it", - "contenttype": "text/plain", - "created": 1445213901000, - "id": "655900756604620800", - "language": "en" - }, - { - "content": "RT @ckerfin: On another river on the other side of the world... transition between stories, drawing connections to different beliefs #Belie\u2026", - "contenttype": "text/plain", - "created": 1445213721000, - "id": "655900002644987905", - "language": "en" - }, - { - "content": "RT @nikfarrior: So profound. We are all born into #Belief @Oprah @OWN @OWNTV", - "contenttype": "text/plain", - "created": 1445213706000, - "id": "655899942242775040", - "language": "en" - }, - { - "content": "RT @fgaboys: @Oprah the start of #Belief is riveting and edifying. It makes you want more and inspires you too see what's coming up next. \u2026", - "contenttype": "text/plain", - "created": 1445213699000, - "id": "655899910563217408", - "language": "en" - }, - { - "content": "RT @MalikaGhosh: Here we GO- let's lose ourselves #belief NOW @Oprah JOY http:\/\/t.co\/vYSNLd3LvC", - "contenttype": "text/plain", - "created": 1445212831000, - "id": "655896269542420480", - "language": "en" - }, - { - "content": "RT @MastinKipp: .@Oprah and team are about to bring the Light with #Belief.", - "contenttype": "text/plain", - "created": 1445212747000, - "id": "655895916675600384", - "language": "en" - }, - { - "content": "RT @GrowingOWN: 7 minutes, y'all! #BELIEF", - "contenttype": "text/plain", - "created": 1445212465000, - "id": "655894734968217600", - "language": "en" - }, - { - "content": "RT @LPToussaint: BELIEF defines experience.Choose wisely #Belief Tonight on OWN", - "contenttype": "text/plain", - "created": 1445211845000, - "id": "655892134524878848", - "language": "en" - }, - { - "content": "RT @TheBeBeWinans: Congratulations to my dear friend @Oprah on the launch of your series #BELIEF #Tonight on @OWNTV. Your friendship inspir\u2026", - "contenttype": "text/plain", - "created": 1445211835000, - "id": "655892094905532416", - "language": "en" - }, - { - "content": "RT @UzoAduba: Thirty minutes to @Oprah #Belief. Pretty sure it's about to be our favorite thing.", - "contenttype": "text/plain", - "created": 1445211833000, - "id": "655892084314890240", - "language": "en" - }, - { - "content": "RT @DeandresVoice: Moments away from the start of @SuperSoulSunday and the first night of the epic #Belief series on @OWNTV - are you ready\u2026", - "contenttype": "text/plain", - "created": 1445209201000, - "id": "655881046102142978", - "language": "en" - }, - { - "content": "RT @jennaldewan: I CANT WAIT FOR THIS TONIGHT!!!!!! Got my popcorn, got my tissues I am readyyyyyy! #Belief https:\/\/t.co\/WluTdeEqal", - "contenttype": "text/plain", - "created": 1445209181000, - "id": "655880959535939584", - "language": "en" - }, - { - "content": "RT @indiaarie: U heard about @Oprah passion project? It's called #Belief - I've see some & Its special! Tonight - 7c\/8e - 7 nights!! Whose\u2026", - "contenttype": "text/plain", - "created": 1445208945000, - "id": "655879970732949504", - "language": "en" - }, - { - "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass", - "contenttype": "text/plain", - "created": 1447639154000, - "id": "666073008692314113", - "language": "en" - }, - { - "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass", - "contenttype": "text/plain", - "created": 1447638226000, - "id": "666069114889179136", - "language": "en" - }, - { - "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass", - "contenttype": "text/plain", - "created": 1447638067000, - "id": "666068446325665792", - "language": "en" - }, - { - "content": "Wow aren't you loving @TheRock and his candor? #Masterclass", - "contenttype": "text/plain", - "created": 1447637459000, - "id": "666065895932973057", - "language": "en" - }, - { - "content": "RT @patt_t: @TheRock @Oprah @RichOnOWN @OWNTV this interview makes me like you as a fellow human even more for being so real.", - "contenttype": "text/plain", - "created": 1447637030000, - "id": "666064097562247168", - "language": "en" - }, - { - "content": "\"Be You\".. That's the best advice ever @TheRock #MastersClass", - "contenttype": "text/plain", - "created": 1447636205000, - "id": "666060637181644800", - "language": "en" - }, - { - "content": "Supersoulers let's lift our spirits pray and hold Paris in the Light\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1447602477000, - "id": "665919171062927360", - "language": "en" - }, - { - "content": "RT @DeepakChopra: What I learned in week 1: Become What You Believe 21-Day Meditation Experience - https:\/\/t.co\/kqaMaMqEUp #GoogleAlerts", - "contenttype": "text/plain", - "created": 1447098990000, - "id": "663807393063538688", - "language": "en" - }, - { - "content": "Watching Bryan Stevenson on #SuperSoulSunday! \"You are not the worst mistake you ever made\".\nAren't we glad about that.", - "contenttype": "text/plain", - "created": 1446998643000, - "id": "663386507856736257", - "language": "en" - }, - { - "content": ".@CherylStrayed BRAVE ENOUGH my new favorite thing! Gonna buy a copy for all my girls. #Perfectgift https:\/\/t.co\/gz1tnv8t8K", - "contenttype": "text/plain", - "created": 1446915955000, - "id": "663039689360695296", - "language": "en" - }, - { - "content": "Stevie Wonder singing \"Happy Birthday to you!\" to my dear mariashriver. A phenomenal woman and\u2026 https:\/\/t.co\/Ygm5eDIs4f", - "contenttype": "text/plain", - "created": 1446881193000, - "id": "662893888080879616", - "language": "en" - }, - { - "content": "It\u2019s my faaaaavorite time of the Year! For the first time you can shop the list on @amazon! https:\/\/t.co\/a6GMvVrhjN https:\/\/t.co\/sJlQMROq5U", - "contenttype": "text/plain", - "created": 1446744186000, - "id": "662319239844380672", - "language": "en" - }, - { - "content": "Incredible story \"the spirit of the Lord is on you\" thanks for sharing @smokey_robinson #Masterclass", - "contenttype": "text/plain", - "created": 1446428929000, - "id": "660996956861280256", - "language": "en" - }, - { - "content": "Wasnt that incredible story about @smokey_robinson 's dad leaving his family at 12. #MasterClass", - "contenttype": "text/plain", - "created": 1446426630000, - "id": "660987310889041920", - "language": "en" - }, - { - "content": "Gayle, Charlie, Nora @CBSThisMorning Congratulations! #1000thshow", - "contenttype": "text/plain", - "created": 1446220097000, - "id": "660121050978611205", - "language": "en" - }, - { - "content": "I believe your home should rise up to meet you. @TheEllenShow you nailed it with HOME. Tweethearts, grab a copy! https:\/\/t.co\/iFMnpRAsno", - "contenttype": "text/plain", - "created": 1446074433000, - "id": "659510090748182528", - "language": "en" - }, - { - "content": "Can I get a Witness?!\u270b\ud83c\udffe https:\/\/t.co\/tZ1QyAeSdE", - "contenttype": "text/plain", - "created": 1445821114000, - "id": "658447593865945089", - "language": "en" - }, - { - "content": ".@TheEllenShow you're a treasure.\nYour truth set a lot of people free.\n#Masterclass", - "contenttype": "text/plain", - "created": 1445821003000, - "id": "658447130026188800", - "language": "en" - }, - { - "content": "Hope you all are enjoying @TheEllenShow on #MasterClass.", - "contenttype": "text/plain", - "created": 1445820161000, - "id": "658443598313181188", - "language": "en" - }, - { - "content": ".@GloriaSteinem, shero to women everywhere, on how far we\u2019ve come and how far we need to go. #SuperSoulSunday 7p\/6c.\nhttps:\/\/t.co\/3e7oxXW02J", - "contenttype": "text/plain", - "created": 1445811545000, - "id": "658407457438363648", - "language": "en" - }, - { - "content": "RT @TheEllenShow: I told a story from my @OWNTV's #MasterClass on my show. Normally I\u2019d save it all for Sunday, but @Oprah made me. https:\/\u2026", - "contenttype": "text/plain", - "created": 1445804181000, - "id": "658376572521459712", - "language": "en" - }, - { - "content": ".@TheEllenShow is a master teacher of living her truth & living authentically as herself. #MasterClass tonight 8\/7c.\nhttps:\/\/t.co\/iLT2KgRsSw", - "contenttype": "text/plain", - "created": 1445804072000, - "id": "658376116575449088", - "language": "en" - }, - { - "content": ".@SheriSalata , @jonnysinc @part2pictures . Tears of joy and gratitude to you and our entire #BeliefTeam We DID IT!! My heart is full.\ud83d\ude4f\ud83c\udffe\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1445734755000, - "id": "658085377140363264", - "language": "en" - }, - { - "content": "Donna and Bob saw the tape of their story just days before she passed. They appreciated it. #RIPDonna", - "contenttype": "text/plain", - "created": 1445734097000, - "id": "658082618819280896", - "language": "en" - }, - { - "content": "RT @rempower: .@Oprah this series allowed me to slide into people's lives around the world and see the same in them ... we all have a belie\u2026", - "contenttype": "text/plain", - "created": 1445732769000, - "id": "658077046858383360", - "language": "en" - }, - { - "content": "All the stories moved me, My favorite line \" I must pass the stories on to my grandson otherwise our people will loose their way. #Belief", - "contenttype": "text/plain", - "created": 1445732579000, - "id": "658076253618991104", - "language": "en" - }, - { - "content": ".@part2pictures some of your best imagery yet. Filming Alex on the rock.#Belief", - "contenttype": "text/plain", - "created": 1445731782000, - "id": "658072908237934592", - "language": "en" - }, - { - "content": "I just love Alex and his daring #Belief to live fully the present Moment.", - "contenttype": "text/plain", - "created": 1445731561000, - "id": "658071980982206464", - "language": "en" - }, - { - "content": "RT @GrowingOWN: Let's do this! #Belief finale tweet tweet party. Thank you @Oprah! \ud83d\ude4f", - "contenttype": "text/plain", - "created": 1445731248000, - "id": "658070668785770496", - "language": "en" - }, - { - "content": "RT @lizkinnell: The epic finale of #Belief on @OWNTV is about to start. 8\/et Are you ready? What do you Believe?", - "contenttype": "text/plain", - "created": 1445731081000, - "id": "658069968534171648", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night of Belief. Belief runs all day tomorrow for bingers and final episode!", - "contenttype": "text/plain", - "created": 1445648630000, - "id": "657724143115202560", - "language": "en" - }, - { - "content": "RT @OWNingLight: #Belief is the ultimate travel map to mass acceptance. \ud83d\ude4f\ud83c\udffb\u2764\ufe0f\ud83c\udf0d @Oprah", - "contenttype": "text/plain", - "created": 1445647285000, - "id": "657718501147197442", - "language": "en" - }, - { - "content": "\" I can feel my heart opening and faith coming back in\".. What's better than that? #Belief", - "contenttype": "text/plain", - "created": 1445646903000, - "id": "657716901951369218", - "language": "en" - }, - { - "content": "Hey Belief team mates can yo believe how quickly the week has passed? #Belief", - "contenttype": "text/plain", - "created": 1445645633000, - "id": "657711572492533760", - "language": "en" - }, - { - "content": "Ran into @5SOS backstage. Fun times with @TheEllenShow today! https:\/\/t.co\/2PP3W3RzXc", - "contenttype": "text/plain", - "created": 1445618531000, - "id": "657597898394173440", - "language": "en" - }, - { - "content": "Thanks All for another great night of #BELIEF", - "contenttype": "text/plain", - "created": 1445572548000, - "id": "657405031822430208", - "language": "en" - }, - { - "content": "RT @3LWTV: #BecomeWhatYouBelieve New meditation w\/ @Oprah @DeepakChopra begins 11\/2 Register https:\/\/t.co\/x0R9HWTAX0 #Belief https:\/\/t.co\/\u2026", - "contenttype": "text/plain", - "created": 1445571500000, - "id": "657400636745510912", - "language": "en" - }, - { - "content": "Ok west coast let's do it! #belief", - "contenttype": "text/plain", - "created": 1445569367000, - "id": "657391689439404033", - "language": "en" - }, - { - "content": "Thank u kind gentleman who told me I had kale in my teeth. Was eating kale chips with Quincy Jones. Went straight to @LairdLife party.", - "contenttype": "text/plain", - "created": 1445569296000, - "id": "657391393883619328", - "language": "en" - }, - { - "content": "Hello west coast twitterati.. See you at 8 for #Belief", - "contenttype": "text/plain", - "created": 1445566144000, - "id": "657378171872874496", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night.#Belief", - "contenttype": "text/plain", - "created": 1445475948000, - "id": "656999861254918145", - "language": "en" - }, - { - "content": "RT @PRanganathan: \"Transformation is the rule of the game. The universe is not standing still.\" - Marcelo @OWNTV @Oprah #Belief", - "contenttype": "text/plain", - "created": 1445475602000, - "id": "656998409933451264", - "language": "en" - }, - { - "content": "\"The Universe is not standing still.. The whole Universe is expanding\" I love the dance between science and spirituality! #Belief", - "contenttype": "text/plain", - "created": 1445475580000, - "id": "656998320133398528", - "language": "en" - }, - { - "content": "\"Without our prayers and our songs we won't be here\" Apache leader.#Belief", - "contenttype": "text/plain", - "created": 1445473768000, - "id": "656990717504393216", - "language": "en" - }, - { - "content": "Notice her mother crying. She knows its last tine she will ever see her daughter.#Belief", - "contenttype": "text/plain", - "created": 1445473150000, - "id": "656988127433637888", - "language": "en" - }, - { - "content": "This final trial is unbelievable. Every hair gets pulled from her head one at a time. Now that is Something!!#Belief", - "contenttype": "text/plain", - "created": 1445473063000, - "id": "656987763644891136", - "language": "en" - }, - { - "content": "\"What my faith gives me no one can match\"#Belief", - "contenttype": "text/plain", - "created": 1445472961000, - "id": "656987336266223616", - "language": "en" - }, - { - "content": "It's a devotion to faith beyond anything Ive seen. Fascinating.Jain nuns. #Belief", - "contenttype": "text/plain", - "created": 1445472531000, - "id": "656985529951522816", - "language": "en" - }, - { - "content": "I'd never heard of Jain monks and nuns before doing this series. #Belief", - "contenttype": "text/plain", - "created": 1445472393000, - "id": "656984953037586433", - "language": "en" - }, - { - "content": "Good evening Team #Belief the Tweet is on!", - "contenttype": "text/plain", - "created": 1445472098000, - "id": "656983714883239937", - "language": "en" - }, - { - "content": "Thanks everyone for another Epic #Belief night!", - "contenttype": "text/plain", - "created": 1445302792000, - "id": "656273592485810176", - "language": "en" - }, - { - "content": "The Pastor and Imam represent the possibility of PEACE in the world. If they can do it. We can. Peace to All\ud83d\ude4f\ud83c\udffe #Belief", - "contenttype": "text/plain", - "created": 1445302749000, - "id": "656273415280705536", - "language": "en" - }, - { - "content": "We felt privileged to film the Hajj and explore the beauty of Islam.\n#99namesforGod #Belief", - "contenttype": "text/plain", - "created": 1445301110000, - "id": "656266540967424000", - "language": "en" - }, - { - "content": "Do you all believe in \"soul mates\"?\n#Belief", - "contenttype": "text/plain", - "created": 1445300138000, - "id": "656262462426238976", - "language": "en" - }, - { - "content": ".@RevEdBacon thank you so much for hosting tonight's #Belief at All Saints Church.", - "contenttype": "text/plain", - "created": 1445299749000, - "id": "656260832628756480", - "language": "en" - }, - { - "content": "This is one of the best love stories I've ever seen. #belief Ian and Larissa showing us the depths of love.#Belief", - "contenttype": "text/plain", - "created": 1445299614000, - "id": "656260263604310016", - "language": "en" - }, - { - "content": "Hey Everyone .. Tweeting from a bar in Atlanta with @SheriSalata OWN not in my hotel. Anything for #Belief", - "contenttype": "text/plain", - "created": 1445299326000, - "id": "656259057758654464", - "language": "en" - }, - { - "content": "RT @joshuadubois: When you see Ian & Larissa tonight on #BELIEF, you'll know what Christian love is all about. 8pmET, @OWNTV. Tune in! http\u2026", - "contenttype": "text/plain", - "created": 1445295716000, - "id": "656243916224638976", - "language": "en" - }, - { - "content": "RT @KimHaleDance: I Believe LAUGHTER. IS. CONTAGIOUS. What do you believe? See you tonight! 8\/7c.\u2764\ufe0f #Belief #Beliefin3words https:\/\/t.co\/x\u2026", - "contenttype": "text/plain", - "created": 1445295702000, - "id": "656243854610337793", - "language": "en" - }, - { - "content": "RT @OWNTV: See the world through someone else\u2019s soul. The epic journey of #Belief continues tonight at 8\/7c.\nhttps:\/\/t.co\/UKKMHZuC0g", - "contenttype": "text/plain", - "created": 1445295668000, - "id": "656243714507931648", - "language": "en" - }, - { - "content": "RT @OWNTV: Mendel Hurwitz's inquisitive nature grounded him in his faith. See where it's taken him now: https:\/\/t.co\/2iWmNOxK9r https:\/\/t.c\u2026", - "contenttype": "text/plain", - "created": 1445295661000, - "id": "656243684720050176", - "language": "en" - }, - { - "content": "Thank you for opening up the heart space and letting #Belief in. Tonight it keeps getting better. See you at 8\/7c\nhttps:\/\/t.co\/E65vkTray9", - "contenttype": "text/plain", - "created": 1445279425000, - "id": "656175584943341568", - "language": "en" - }, - { - "content": "I believe in the @weightwatchers program so much I decided to invest, join the Board, and partner in #wwfamily evolution.", - "contenttype": "text/plain", - "created": 1445275802000, - "id": "656160388526899200", - "language": "en" - }, - { - "content": "RT @AVAETC: Debut episode of #BELIEF has now aired on both coasts. Trended for 4 hours. Brava, @Oprah + team. 6 beautiful nights to come. B\u2026", - "contenttype": "text/plain", - "created": 1445229489000, - "id": "655966138279432192", - "language": "en" - }, - { - "content": "RT @3LWTV: 6 more epic nights of #Belief to come! See you tomorrow 8pET\/7pCT for the next installment! @OWNTV @Oprah", - "contenttype": "text/plain", - "created": 1445227342000, - "id": "655957135688241152", - "language": "en" - }, - { - "content": "RT @ledisi: I love how Ancestry and Tradition is honored throughout every story in #Belief @OWNTV @OWN Thank you @Oprah this is so importa\u2026", - "contenttype": "text/plain", - "created": 1445225935000, - "id": "655951232981295104", - "language": "en" - }, - { - "content": "RT @UN: Showing #Belief at the UN \"is a bigger dream than I had\" - @Oprah https:\/\/t.co\/VC4OqD8yub #Belief #GlobalGoals https:\/\/t.co\/LZyGuC7\u2026", - "contenttype": "text/plain", - "created": 1445225228000, - "id": "655948267868426240", - "language": "en" - }, - { - "content": "RT @UzoAduba: To seek, to question, to learn, to teach, to pass it on; some of the breathtaking themes running like water throughout #Belie\u2026", - "contenttype": "text/plain", - "created": 1445225008000, - "id": "655947345197076480", - "language": "en" - }, - { - "content": "RT @iamtikasumpter: #Belief had me in awe. Faith in the divine is the constant that links us together. It's all beautiful and righteous. Gi\u2026", - "contenttype": "text/plain", - "created": 1445224852000, - "id": "655946689249828864", - "language": "en" - }, - { - "content": "West Coast... Here we go. #Belief", - "contenttype": "text/plain", - "created": 1445224140000, - "id": "655943701840048128", - "language": "en" - }, - { - "content": "Big surprise at icanady watch party. Epic night. #Belief. So much more to come. https:\/\/t.co\/kBDtFwGyQs", - "contenttype": "text/plain", - "created": 1445220694000, - "id": "655929249669378048", - "language": "en" - }, - { - "content": "I loved the Mendel story so much because it represents right of passasge. \" bye bye to childhood\".#Belief", - "contenttype": "text/plain", - "created": 1445215032000, - "id": "655905500056391682", - "language": "en" - }, - { - "content": "RT @squee_machine: This is a visual feast! Completely gorgeous and I am transfixed. The colors, the composition, cinematography, vibe. #Bel\u2026", - "contenttype": "text/plain", - "created": 1445214538000, - "id": "655903432079904768", - "language": "en" - }, - { - "content": "RT @JamesTyphany: Looking at @ #Belief I really needed this in my life thanks @OWNTV", - "contenttype": "text/plain", - "created": 1445214534000, - "id": "655903413385891840", - "language": "en" - }, - { - "content": "Just surprised a \"watch party\" @icanady 's house. #Belief http:\/\/t.co\/Di0I3OooCh", - "contenttype": "text/plain", - "created": 1445214502000, - "id": "655903277796732931", - "language": "en" - }, - { - "content": "RT @MsLaWandaa: I love moments of sitting among elders and learning. I can feel this moment was special for @ReshThakkar #Belief", - "contenttype": "text/plain", - "created": 1445214498000, - "id": "655903264374812672", - "language": "en" - }, - { - "content": "RT @xonecole: \"Do you have to have religion or is being a good person...is that enough?\" #Belief", - "contenttype": "text/plain", - "created": 1445214339000, - "id": "655902594171203584", - "language": "en" - }, - { - "content": "RT @ChivonJohn: Very inspired by the stories on #belief https:\/\/t.co\/uMRCCfCWcY", - "contenttype": "text/plain", - "created": 1445214327000, - "id": "655902545903140864", - "language": "en" - }, - { - "content": "RT @KiranSArora: powerful personal story that many of us can connect to. searching for what's missing, spiritual liberation. @ReshThakkar #\u2026", - "contenttype": "text/plain", - "created": 1445214128000, - "id": "655901708506103812", - "language": "en" - }, - { - "content": "RT @createdbyerica: \"I'm willing to go as far as I have to go to get that feeling in my heart of being connected to the Divine.\" - Reshma @\u2026", - "contenttype": "text/plain", - "created": 1445213967000, - "id": "655901033952993280", - "language": "en" - }, - { - "content": "RT @UrbnHealthNP: I am enjoying this so much. #Belief", - "contenttype": "text/plain", - "created": 1445213904000, - "id": "655900772467474435", - "language": "en" - }, - { - "content": "RT @DrMABrown: Your relationship with #belief can be completely different than how others experience it", - "contenttype": "text/plain", - "created": 1445213901000, - "id": "655900756604620800", - "language": "en" - }, - { - "content": "RT @ckerfin: On another river on the other side of the world... transition between stories, drawing connections to different beliefs #Belie\u2026", - "contenttype": "text/plain", - "created": 1445213721000, - "id": "655900002644987905", - "language": "en" - }, - { - "content": "RT @nikfarrior: So profound. We are all born into #Belief @Oprah @OWN @OWNTV", - "contenttype": "text/plain", - "created": 1445213706000, - "id": "655899942242775040", - "language": "en" - }, - { - "content": "RT @fgaboys: @Oprah the start of #Belief is riveting and edifying. It makes you want more and inspires you too see what's coming up next. \u2026", - "contenttype": "text/plain", - "created": 1445213699000, - "id": "655899910563217408", - "language": "en" - }, - { - "content": "RT @MalikaGhosh: Here we GO- let's lose ourselves #belief NOW @Oprah JOY http:\/\/t.co\/vYSNLd3LvC", - "contenttype": "text/plain", - "created": 1445212831000, - "id": "655896269542420480", - "language": "en" - }, - { - "content": "RT @MastinKipp: .@Oprah and team are about to bring the Light with #Belief.", - "contenttype": "text/plain", - "created": 1445212747000, - "id": "655895916675600384", - "language": "en" - }, - { - "content": "RT @GrowingOWN: 7 minutes, y'all! #BELIEF", - "contenttype": "text/plain", - "created": 1445212465000, - "id": "655894734968217600", - "language": "en" - }, - { - "content": "RT @LPToussaint: BELIEF defines experience.Choose wisely #Belief Tonight on OWN", - "contenttype": "text/plain", - "created": 1445211845000, - "id": "655892134524878848", - "language": "en" - }, - { - "content": "RT @TheBeBeWinans: Congratulations to my dear friend @Oprah on the launch of your series #BELIEF #Tonight on @OWNTV. Your friendship inspir\u2026", - "contenttype": "text/plain", - "created": 1445211835000, - "id": "655892094905532416", - "language": "en" - }, - { - "content": "RT @UzoAduba: Thirty minutes to @Oprah #Belief. Pretty sure it's about to be our favorite thing.", - "contenttype": "text/plain", - "created": 1445211833000, - "id": "655892084314890240", - "language": "en" - }, - { - "content": "RT @DeandresVoice: Moments away from the start of @SuperSoulSunday and the first night of the epic #Belief series on @OWNTV - are you ready\u2026", - "contenttype": "text/plain", - "created": 1445209201000, - "id": "655881046102142978", - "language": "en" - }, - { - "content": "RT @jennaldewan: I CANT WAIT FOR THIS TONIGHT!!!!!! Got my popcorn, got my tissues I am readyyyyyy! #Belief https:\/\/t.co\/WluTdeEqal", - "contenttype": "text/plain", - "created": 1445209181000, - "id": "655880959535939584", - "language": "en" - }, - { - "content": "RT @indiaarie: U heard about @Oprah passion project? It's called #Belief - I've see some & Its special! Tonight - 7c\/8e - 7 nights!! Whose\u2026", - "contenttype": "text/plain", - "created": 1445208945000, - "id": "655879970732949504", - "language": "en" - }, - { - "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass", - "contenttype": "text/plain", - "created": 1447639154000, - "id": "666073008692314113", - "language": "en" - }, - { - "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass", - "contenttype": "text/plain", - "created": 1447638226000, - "id": "666069114889179136", - "language": "en" - }, - { - "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass", - "contenttype": "text/plain", - "created": 1447638067000, - "id": "666068446325665792", - "language": "en" - }, - { - "content": "Wow aren't you loving @TheRock and his candor? #Masterclass", - "contenttype": "text/plain", - "created": 1447637459000, - "id": "666065895932973057", - "language": "en" - }, - { - "content": "RT @patt_t: @TheRock @Oprah @RichOnOWN @OWNTV this interview makes me like you as a fellow human even more for being so real.", - "contenttype": "text/plain", - "created": 1447637030000, - "id": "666064097562247168", - "language": "en" - }, - { - "content": "\"Be You\".. That's the best advice ever @TheRock #MastersClass", - "contenttype": "text/plain", - "created": 1447636205000, - "id": "666060637181644800", - "language": "en" - }, - { - "content": "Supersoulers let's lift our spirits pray and hold Paris in the Light\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1447602477000, - "id": "665919171062927360", - "language": "en" - }, - { - "content": "RT @DeepakChopra: What I learned in week 1: Become What You Believe 21-Day Meditation Experience - https:\/\/t.co\/kqaMaMqEUp #GoogleAlerts", - "contenttype": "text/plain", - "created": 1447098990000, - "id": "663807393063538688", - "language": "en" - }, - { - "content": "Watching Bryan Stevenson on #SuperSoulSunday! \"You are not the worst mistake you ever made\".\nAren't we glad about that.", - "contenttype": "text/plain", - "created": 1446998643000, - "id": "663386507856736257", - "language": "en" - }, - { - "content": ".@CherylStrayed BRAVE ENOUGH my new favorite thing! Gonna buy a copy for all my girls. #Perfectgift https:\/\/t.co\/gz1tnv8t8K", - "contenttype": "text/plain", - "created": 1446915955000, - "id": "663039689360695296", - "language": "en" - }, - { - "content": "Stevie Wonder singing \"Happy Birthday to you!\" to my dear mariashriver. A phenomenal woman and\u2026 https:\/\/t.co\/Ygm5eDIs4f", - "contenttype": "text/plain", - "created": 1446881193000, - "id": "662893888080879616", - "language": "en" - }, - { - "content": "It\u2019s my faaaaavorite time of the Year! For the first time you can shop the list on @amazon! https:\/\/t.co\/a6GMvVrhjN https:\/\/t.co\/sJlQMROq5U", - "contenttype": "text/plain", - "created": 1446744186000, - "id": "662319239844380672", - "language": "en" - }, - { - "content": "Incredible story \"the spirit of the Lord is on you\" thanks for sharing @smokey_robinson #Masterclass", - "contenttype": "text/plain", - "created": 1446428929000, - "id": "660996956861280256", - "language": "en" - }, - { - "content": "Wasnt that incredible story about @smokey_robinson 's dad leaving his family at 12. #MasterClass", - "contenttype": "text/plain", - "created": 1446426630000, - "id": "660987310889041920", - "language": "en" - }, - { - "content": "Gayle, Charlie, Nora @CBSThisMorning Congratulations! #1000thshow", - "contenttype": "text/plain", - "created": 1446220097000, - "id": "660121050978611205", - "language": "en" - }, - { - "content": "I believe your home should rise up to meet you. @TheEllenShow you nailed it with HOME. Tweethearts, grab a copy! https:\/\/t.co\/iFMnpRAsno", - "contenttype": "text/plain", - "created": 1446074433000, - "id": "659510090748182528", - "language": "en" - }, - { - "content": "Can I get a Witness?!\u270b\ud83c\udffe https:\/\/t.co\/tZ1QyAeSdE", - "contenttype": "text/plain", - "created": 1445821114000, - "id": "658447593865945089", - "language": "en" - }, - { - "content": ".@TheEllenShow you're a treasure.\nYour truth set a lot of people free.\n#Masterclass", - "contenttype": "text/plain", - "created": 1445821003000, - "id": "658447130026188800", - "language": "en" - }, - { - "content": "Hope you all are enjoying @TheEllenShow on #MasterClass.", - "contenttype": "text/plain", - "created": 1445820161000, - "id": "658443598313181188", - "language": "en" - }, - { - "content": ".@GloriaSteinem, shero to women everywhere, on how far we\u2019ve come and how far we need to go. #SuperSoulSunday 7p\/6c.\nhttps:\/\/t.co\/3e7oxXW02J", - "contenttype": "text/plain", - "created": 1445811545000, - "id": "658407457438363648", - "language": "en" - }, - { - "content": "RT @TheEllenShow: I told a story from my @OWNTV's #MasterClass on my show. Normally I\u2019d save it all for Sunday, but @Oprah made me. https:\/\u2026", - "contenttype": "text/plain", - "created": 1445804181000, - "id": "658376572521459712", - "language": "en" - }, - { - "content": ".@TheEllenShow is a master teacher of living her truth & living authentically as herself. #MasterClass tonight 8\/7c.\nhttps:\/\/t.co\/iLT2KgRsSw", - "contenttype": "text/plain", - "created": 1445804072000, - "id": "658376116575449088", - "language": "en" - }, - { - "content": ".@SheriSalata , @jonnysinc @part2pictures . Tears of joy and gratitude to you and our entire #BeliefTeam We DID IT!! My heart is full.\ud83d\ude4f\ud83c\udffe\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1445734755000, - "id": "658085377140363264", - "language": "en" - }, - { - "content": "Donna and Bob saw the tape of their story just days before she passed. They appreciated it. #RIPDonna", - "contenttype": "text/plain", - "created": 1445734097000, - "id": "658082618819280896", - "language": "en" - }, - { - "content": "RT @rempower: .@Oprah this series allowed me to slide into people's lives around the world and see the same in them ... we all have a belie\u2026", - "contenttype": "text/plain", - "created": 1445732769000, - "id": "658077046858383360", - "language": "en" - }, - { - "content": "All the stories moved me, My favorite line \" I must pass the stories on to my grandson otherwise our people will loose their way. #Belief", - "contenttype": "text/plain", - "created": 1445732579000, - "id": "658076253618991104", - "language": "en" - }, - { - "content": ".@part2pictures some of your best imagery yet. Filming Alex on the rock.#Belief", - "contenttype": "text/plain", - "created": 1445731782000, - "id": "658072908237934592", - "language": "en" - }, - { - "content": "I just love Alex and his daring #Belief to live fully the present Moment.", - "contenttype": "text/plain", - "created": 1445731561000, - "id": "658071980982206464", - "language": "en" - }, - { - "content": "RT @GrowingOWN: Let's do this! #Belief finale tweet tweet party. Thank you @Oprah! \ud83d\ude4f", - "contenttype": "text/plain", - "created": 1445731248000, - "id": "658070668785770496", - "language": "en" - }, - { - "content": "RT @lizkinnell: The epic finale of #Belief on @OWNTV is about to start. 8\/et Are you ready? What do you Believe?", - "contenttype": "text/plain", - "created": 1445731081000, - "id": "658069968534171648", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night of Belief. Belief runs all day tomorrow for bingers and final episode!", - "contenttype": "text/plain", - "created": 1445648630000, - "id": "657724143115202560", - "language": "en" - }, - { - "content": "RT @OWNingLight: #Belief is the ultimate travel map to mass acceptance. \ud83d\ude4f\ud83c\udffb\u2764\ufe0f\ud83c\udf0d @Oprah", - "contenttype": "text/plain", - "created": 1445647285000, - "id": "657718501147197442", - "language": "en" - }, - { - "content": "\" I can feel my heart opening and faith coming back in\".. What's better than that? #Belief", - "contenttype": "text/plain", - "created": 1445646903000, - "id": "657716901951369218", - "language": "en" - }, - { - "content": "Hey Belief team mates can yo believe how quickly the week has passed? #Belief", - "contenttype": "text/plain", - "created": 1445645633000, - "id": "657711572492533760", - "language": "en" - }, - { - "content": "Ran into @5SOS backstage. Fun times with @TheEllenShow today! https:\/\/t.co\/2PP3W3RzXc", - "contenttype": "text/plain", - "created": 1445618531000, - "id": "657597898394173440", - "language": "en" - }, - { - "content": "Thanks All for another great night of #BELIEF", - "contenttype": "text/plain", - "created": 1445572548000, - "id": "657405031822430208", - "language": "en" - }, - { - "content": "RT @3LWTV: #BecomeWhatYouBelieve New meditation w\/ @Oprah @DeepakChopra begins 11\/2 Register https:\/\/t.co\/x0R9HWTAX0 #Belief https:\/\/t.co\/\u2026", - "contenttype": "text/plain", - "created": 1445571500000, - "id": "657400636745510912", - "language": "en" - }, - { - "content": "Ok west coast let's do it! #belief", - "contenttype": "text/plain", - "created": 1445569367000, - "id": "657391689439404033", - "language": "en" - }, - { - "content": "Thank u kind gentleman who told me I had kale in my teeth. Was eating kale chips with Quincy Jones. Went straight to @LairdLife party.", - "contenttype": "text/plain", - "created": 1445569296000, - "id": "657391393883619328", - "language": "en" - }, - { - "content": "Hello west coast twitterati.. See you at 8 for #Belief", - "contenttype": "text/plain", - "created": 1445566144000, - "id": "657378171872874496", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night.#Belief", - "contenttype": "text/plain", - "created": 1445475948000, - "id": "656999861254918145", - "language": "en" - }, - { - "content": "RT @PRanganathan: \"Transformation is the rule of the game. The universe is not standing still.\" - Marcelo @OWNTV @Oprah #Belief", - "contenttype": "text/plain", - "created": 1445475602000, - "id": "656998409933451264", - "language": "en" - }, - { - "content": "\"The Universe is not standing still.. The whole Universe is expanding\" I love the dance between science and spirituality! #Belief", - "contenttype": "text/plain", - "created": 1445475580000, - "id": "656998320133398528", - "language": "en" - }, - { - "content": "\"Without our prayers and our songs we won't be here\" Apache leader.#Belief", - "contenttype": "text/plain", - "created": 1445473768000, - "id": "656990717504393216", - "language": "en" - }, - { - "content": "Notice her mother crying. She knows its last tine she will ever see her daughter.#Belief", - "contenttype": "text/plain", - "created": 1445473150000, - "id": "656988127433637888", - "language": "en" - }, - { - "content": "This final trial is unbelievable. Every hair gets pulled from her head one at a time. Now that is Something!!#Belief", - "contenttype": "text/plain", - "created": 1445473063000, - "id": "656987763644891136", - "language": "en" - }, - { - "content": "\"What my faith gives me no one can match\"#Belief", - "contenttype": "text/plain", - "created": 1445472961000, - "id": "656987336266223616", - "language": "en" - }, - { - "content": "It's a devotion to faith beyond anything Ive seen. Fascinating.Jain nuns. #Belief", - "contenttype": "text/plain", - "created": 1445472531000, - "id": "656985529951522816", - "language": "en" - }, - { - "content": "I'd never heard of Jain monks and nuns before doing this series. #Belief", - "contenttype": "text/plain", - "created": 1445472393000, - "id": "656984953037586433", - "language": "en" - }, - { - "content": "Good evening Team #Belief the Tweet is on!", - "contenttype": "text/plain", - "created": 1445472098000, - "id": "656983714883239937", - "language": "en" - }, - { - "content": "Thanks everyone for another Epic #Belief night!", - "contenttype": "text/plain", - "created": 1445302792000, - "id": "656273592485810176", - "language": "en" - }, - { - "content": "The Pastor and Imam represent the possibility of PEACE in the world. If they can do it. We can. Peace to All\ud83d\ude4f\ud83c\udffe #Belief", - "contenttype": "text/plain", - "created": 1445302749000, - "id": "656273415280705536", - "language": "en" - }, - { - "content": "We felt privileged to film the Hajj and explore the beauty of Islam.\n#99namesforGod #Belief", - "contenttype": "text/plain", - "created": 1445301110000, - "id": "656266540967424000", - "language": "en" - }, - { - "content": "Do you all believe in \"soul mates\"?\n#Belief", - "contenttype": "text/plain", - "created": 1445300138000, - "id": "656262462426238976", - "language": "en" - }, - { - "content": ".@RevEdBacon thank you so much for hosting tonight's #Belief at All Saints Church.", - "contenttype": "text/plain", - "created": 1445299749000, - "id": "656260832628756480", - "language": "en" - }, - { - "content": "This is one of the best love stories I've ever seen. #belief Ian and Larissa showing us the depths of love.#Belief", - "contenttype": "text/plain", - "created": 1445299614000, - "id": "656260263604310016", - "language": "en" - }, - { - "content": "Hey Everyone .. Tweeting from a bar in Atlanta with @SheriSalata OWN not in my hotel. Anything for #Belief", - "contenttype": "text/plain", - "created": 1445299326000, - "id": "656259057758654464", - "language": "en" - }, - { - "content": "RT @joshuadubois: When you see Ian & Larissa tonight on #BELIEF, you'll know what Christian love is all about. 8pmET, @OWNTV. Tune in! http\u2026", - "contenttype": "text/plain", - "created": 1445295716000, - "id": "656243916224638976", - "language": "en" - }, - { - "content": "RT @KimHaleDance: I Believe LAUGHTER. IS. CONTAGIOUS. What do you believe? See you tonight! 8\/7c.\u2764\ufe0f #Belief #Beliefin3words https:\/\/t.co\/x\u2026", - "contenttype": "text/plain", - "created": 1445295702000, - "id": "656243854610337793", - "language": "en" - }, - { - "content": "RT @OWNTV: See the world through someone else\u2019s soul. The epic journey of #Belief continues tonight at 8\/7c.\nhttps:\/\/t.co\/UKKMHZuC0g", - "contenttype": "text/plain", - "created": 1445295668000, - "id": "656243714507931648", - "language": "en" - }, - { - "content": "RT @OWNTV: Mendel Hurwitz's inquisitive nature grounded him in his faith. See where it's taken him now: https:\/\/t.co\/2iWmNOxK9r https:\/\/t.c\u2026", - "contenttype": "text/plain", - "created": 1445295661000, - "id": "656243684720050176", - "language": "en" - }, - { - "content": "Thank you for opening up the heart space and letting #Belief in. Tonight it keeps getting better. See you at 8\/7c\nhttps:\/\/t.co\/E65vkTray9", - "contenttype": "text/plain", - "created": 1445279425000, - "id": "656175584943341568", - "language": "en" - }, - { - "content": "I believe in the @weightwatchers program so much I decided to invest, join the Board, and partner in #wwfamily evolution.", - "contenttype": "text/plain", - "created": 1445275802000, - "id": "656160388526899200", - "language": "en" - }, - { - "content": "RT @AVAETC: Debut episode of #BELIEF has now aired on both coasts. Trended for 4 hours. Brava, @Oprah + team. 6 beautiful nights to come. B\u2026", - "contenttype": "text/plain", - "created": 1445229489000, - "id": "655966138279432192", - "language": "en" - }, - { - "content": "RT @3LWTV: 6 more epic nights of #Belief to come! See you tomorrow 8pET\/7pCT for the next installment! @OWNTV @Oprah", - "contenttype": "text/plain", - "created": 1445227342000, - "id": "655957135688241152", - "language": "en" - }, - { - "content": "RT @ledisi: I love how Ancestry and Tradition is honored throughout every story in #Belief @OWNTV @OWN Thank you @Oprah this is so importa\u2026", - "contenttype": "text/plain", - "created": 1445225935000, - "id": "655951232981295104", - "language": "en" - }, - { - "content": "RT @UN: Showing #Belief at the UN \"is a bigger dream than I had\" - @Oprah https:\/\/t.co\/VC4OqD8yub #Belief #GlobalGoals https:\/\/t.co\/LZyGuC7\u2026", - "contenttype": "text/plain", - "created": 1445225228000, - "id": "655948267868426240", - "language": "en" - }, - { - "content": "RT @UzoAduba: To seek, to question, to learn, to teach, to pass it on; some of the breathtaking themes running like water throughout #Belie\u2026", - "contenttype": "text/plain", - "created": 1445225008000, - "id": "655947345197076480", - "language": "en" - }, - { - "content": "RT @iamtikasumpter: #Belief had me in awe. Faith in the divine is the constant that links us together. It's all beautiful and righteous. Gi\u2026", - "contenttype": "text/plain", - "created": 1445224852000, - "id": "655946689249828864", - "language": "en" - }, - { - "content": "West Coast... Here we go. #Belief", - "contenttype": "text/plain", - "created": 1445224140000, - "id": "655943701840048128", - "language": "en" - }, - { - "content": "Big surprise at icanady watch party. Epic night. #Belief. So much more to come. https:\/\/t.co\/kBDtFwGyQs", - "contenttype": "text/plain", - "created": 1445220694000, - "id": "655929249669378048", - "language": "en" - }, - { - "content": "I loved the Mendel story so much because it represents right of passasge. \" bye bye to childhood\".#Belief", - "contenttype": "text/plain", - "created": 1445215032000, - "id": "655905500056391682", - "language": "en" - }, - { - "content": "RT @squee_machine: This is a visual feast! Completely gorgeous and I am transfixed. The colors, the composition, cinematography, vibe. #Bel\u2026", - "contenttype": "text/plain", - "created": 1445214538000, - "id": "655903432079904768", - "language": "en" - }, - { - "content": "RT @JamesTyphany: Looking at @ #Belief I really needed this in my life thanks @OWNTV", - "contenttype": "text/plain", - "created": 1445214534000, - "id": "655903413385891840", - "language": "en" - }, - { - "content": "Just surprised a \"watch party\" @icanady 's house. #Belief http:\/\/t.co\/Di0I3OooCh", - "contenttype": "text/plain", - "created": 1445214502000, - "id": "655903277796732931", - "language": "en" - }, - { - "content": "RT @MsLaWandaa: I love moments of sitting among elders and learning. I can feel this moment was special for @ReshThakkar #Belief", - "contenttype": "text/plain", - "created": 1445214498000, - "id": "655903264374812672", - "language": "en" - }, - { - "content": "RT @xonecole: \"Do you have to have religion or is being a good person...is that enough?\" #Belief", - "contenttype": "text/plain", - "created": 1445214339000, - "id": "655902594171203584", - "language": "en" - }, - { - "content": "RT @ChivonJohn: Very inspired by the stories on #belief https:\/\/t.co\/uMRCCfCWcY", - "contenttype": "text/plain", - "created": 1445214327000, - "id": "655902545903140864", - "language": "en" - }, - { - "content": "RT @KiranSArora: powerful personal story that many of us can connect to. searching for what's missing, spiritual liberation. @ReshThakkar #\u2026", - "contenttype": "text/plain", - "created": 1445214128000, - "id": "655901708506103812", - "language": "en" - }, - { - "content": "RT @createdbyerica: \"I'm willing to go as far as I have to go to get that feeling in my heart of being connected to the Divine.\" - Reshma @\u2026", - "contenttype": "text/plain", - "created": 1445213967000, - "id": "655901033952993280", - "language": "en" - }, - { - "content": "RT @UrbnHealthNP: I am enjoying this so much. #Belief", - "contenttype": "text/plain", - "created": 1445213904000, - "id": "655900772467474435", - "language": "en" - }, - { - "content": "RT @DrMABrown: Your relationship with #belief can be completely different than how others experience it", - "contenttype": "text/plain", - "created": 1445213901000, - "id": "655900756604620800", - "language": "en" - }, - { - "content": "RT @ckerfin: On another river on the other side of the world... transition between stories, drawing connections to different beliefs #Belie\u2026", - "contenttype": "text/plain", - "created": 1445213721000, - "id": "655900002644987905", - "language": "en" - }, - { - "content": "RT @nikfarrior: So profound. We are all born into #Belief @Oprah @OWN @OWNTV", - "contenttype": "text/plain", - "created": 1445213706000, - "id": "655899942242775040", - "language": "en" - }, - { - "content": "RT @fgaboys: @Oprah the start of #Belief is riveting and edifying. It makes you want more and inspires you too see what's coming up next. \u2026", - "contenttype": "text/plain", - "created": 1445213699000, - "id": "655899910563217408", - "language": "en" - }, - { - "content": "RT @MalikaGhosh: Here we GO- let's lose ourselves #belief NOW @Oprah JOY http:\/\/t.co\/vYSNLd3LvC", - "contenttype": "text/plain", - "created": 1445212831000, - "id": "655896269542420480", - "language": "en" - }, - { - "content": "RT @MastinKipp: .@Oprah and team are about to bring the Light with #Belief.", - "contenttype": "text/plain", - "created": 1445212747000, - "id": "655895916675600384", - "language": "en" - }, - { - "content": "RT @GrowingOWN: 7 minutes, y'all! #BELIEF", - "contenttype": "text/plain", - "created": 1445212465000, - "id": "655894734968217600", - "language": "en" - }, - { - "content": "RT @LPToussaint: BELIEF defines experience.Choose wisely #Belief Tonight on OWN", - "contenttype": "text/plain", - "created": 1445211845000, - "id": "655892134524878848", - "language": "en" - }, - { - "content": "RT @TheBeBeWinans: Congratulations to my dear friend @Oprah on the launch of your series #BELIEF #Tonight on @OWNTV. Your friendship inspir\u2026", - "contenttype": "text/plain", - "created": 1445211835000, - "id": "655892094905532416", - "language": "en" - }, - { - "content": "RT @UzoAduba: Thirty minutes to @Oprah #Belief. Pretty sure it's about to be our favorite thing.", - "contenttype": "text/plain", - "created": 1445211833000, - "id": "655892084314890240", - "language": "en" - }, - { - "content": "RT @DeandresVoice: Moments away from the start of @SuperSoulSunday and the first night of the epic #Belief series on @OWNTV - are you ready\u2026", - "contenttype": "text/plain", - "created": 1445209201000, - "id": "655881046102142978", - "language": "en" - }, - { - "content": "RT @jennaldewan: I CANT WAIT FOR THIS TONIGHT!!!!!! Got my popcorn, got my tissues I am readyyyyyy! #Belief https:\/\/t.co\/WluTdeEqal", - "contenttype": "text/plain", - "created": 1445209181000, - "id": "655880959535939584", - "language": "en" - }, - { - "content": "RT @indiaarie: U heard about @Oprah passion project? It's called #Belief - I've see some & Its special! Tonight - 7c\/8e - 7 nights!! Whose\u2026", - "contenttype": "text/plain", - "created": 1445208945000, - "id": "655879970732949504", - "language": "en" - }, - { - "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass", - "contenttype": "text/plain", - "created": 1447639154000, - "id": "666073008692314113", - "language": "en" - }, - { - "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass", - "contenttype": "text/plain", - "created": 1447638226000, - "id": "666069114889179136", - "language": "en" - }, - { - "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass", - "contenttype": "text/plain", - "created": 1447638067000, - "id": "666068446325665792", - "language": "en" - }, - { - "content": "Wow aren't you loving @TheRock and his candor? #Masterclass", - "contenttype": "text/plain", - "created": 1447637459000, - "id": "666065895932973057", - "language": "en" - }, - { - "content": "RT @patt_t: @TheRock @Oprah @RichOnOWN @OWNTV this interview makes me like you as a fellow human even more for being so real.", - "contenttype": "text/plain", - "created": 1447637030000, - "id": "666064097562247168", - "language": "en" - }, - { - "content": "\"Be You\".. That's the best advice ever @TheRock #MastersClass", - "contenttype": "text/plain", - "created": 1447636205000, - "id": "666060637181644800", - "language": "en" - }, - { - "content": "Supersoulers let's lift our spirits pray and hold Paris in the Light\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1447602477000, - "id": "665919171062927360", - "language": "en" - }, - { - "content": "RT @DeepakChopra: What I learned in week 1: Become What You Believe 21-Day Meditation Experience - https:\/\/t.co\/kqaMaMqEUp #GoogleAlerts", - "contenttype": "text/plain", - "created": 1447098990000, - "id": "663807393063538688", - "language": "en" - }, - { - "content": "Watching Bryan Stevenson on #SuperSoulSunday! \"You are not the worst mistake you ever made\".\nAren't we glad about that.", - "contenttype": "text/plain", - "created": 1446998643000, - "id": "663386507856736257", - "language": "en" - }, - { - "content": ".@CherylStrayed BRAVE ENOUGH my new favorite thing! Gonna buy a copy for all my girls. #Perfectgift https:\/\/t.co\/gz1tnv8t8K", - "contenttype": "text/plain", - "created": 1446915955000, - "id": "663039689360695296", - "language": "en" - }, - { - "content": "Stevie Wonder singing \"Happy Birthday to you!\" to my dear mariashriver. A phenomenal woman and\u2026 https:\/\/t.co\/Ygm5eDIs4f", - "contenttype": "text/plain", - "created": 1446881193000, - "id": "662893888080879616", - "language": "en" - }, - { - "content": "It\u2019s my faaaaavorite time of the Year! For the first time you can shop the list on @amazon! https:\/\/t.co\/a6GMvVrhjN https:\/\/t.co\/sJlQMROq5U", - "contenttype": "text/plain", - "created": 1446744186000, - "id": "662319239844380672", - "language": "en" - }, - { - "content": "Incredible story \"the spirit of the Lord is on you\" thanks for sharing @smokey_robinson #Masterclass", - "contenttype": "text/plain", - "created": 1446428929000, - "id": "660996956861280256", - "language": "en" - }, - { - "content": "Wasnt that incredible story about @smokey_robinson 's dad leaving his family at 12. #MasterClass", - "contenttype": "text/plain", - "created": 1446426630000, - "id": "660987310889041920", - "language": "en" - }, - { - "content": "Gayle, Charlie, Nora @CBSThisMorning Congratulations! #1000thshow", - "contenttype": "text/plain", - "created": 1446220097000, - "id": "660121050978611205", - "language": "en" - }, - { - "content": "I believe your home should rise up to meet you. @TheEllenShow you nailed it with HOME. Tweethearts, grab a copy! https:\/\/t.co\/iFMnpRAsno", - "contenttype": "text/plain", - "created": 1446074433000, - "id": "659510090748182528", - "language": "en" - }, - { - "content": "Can I get a Witness?!\u270b\ud83c\udffe https:\/\/t.co\/tZ1QyAeSdE", - "contenttype": "text/plain", - "created": 1445821114000, - "id": "658447593865945089", - "language": "en" - }, - { - "content": ".@TheEllenShow you're a treasure.\nYour truth set a lot of people free.\n#Masterclass", - "contenttype": "text/plain", - "created": 1445821003000, - "id": "658447130026188800", - "language": "en" - }, - { - "content": "Hope you all are enjoying @TheEllenShow on #MasterClass.", - "contenttype": "text/plain", - "created": 1445820161000, - "id": "658443598313181188", - "language": "en" - }, - { - "content": ".@GloriaSteinem, shero to women everywhere, on how far we\u2019ve come and how far we need to go. #SuperSoulSunday 7p\/6c.\nhttps:\/\/t.co\/3e7oxXW02J", - "contenttype": "text/plain", - "created": 1445811545000, - "id": "658407457438363648", - "language": "en" - }, - { - "content": "RT @TheEllenShow: I told a story from my @OWNTV's #MasterClass on my show. Normally I\u2019d save it all for Sunday, but @Oprah made me. https:\/\u2026", - "contenttype": "text/plain", - "created": 1445804181000, - "id": "658376572521459712", - "language": "en" - }, - { - "content": ".@TheEllenShow is a master teacher of living her truth & living authentically as herself. #MasterClass tonight 8\/7c.\nhttps:\/\/t.co\/iLT2KgRsSw", - "contenttype": "text/plain", - "created": 1445804072000, - "id": "658376116575449088", - "language": "en" - }, - { - "content": ".@SheriSalata , @jonnysinc @part2pictures . Tears of joy and gratitude to you and our entire #BeliefTeam We DID IT!! My heart is full.\ud83d\ude4f\ud83c\udffe\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1445734755000, - "id": "658085377140363264", - "language": "en" - }, - { - "content": "Donna and Bob saw the tape of their story just days before she passed. They appreciated it. #RIPDonna", - "contenttype": "text/plain", - "created": 1445734097000, - "id": "658082618819280896", - "language": "en" - }, - { - "content": "RT @rempower: .@Oprah this series allowed me to slide into people's lives around the world and see the same in them ... we all have a belie\u2026", - "contenttype": "text/plain", - "created": 1445732769000, - "id": "658077046858383360", - "language": "en" - }, - { - "content": "All the stories moved me, My favorite line \" I must pass the stories on to my grandson otherwise our people will loose their way. #Belief", - "contenttype": "text/plain", - "created": 1445732579000, - "id": "658076253618991104", - "language": "en" - }, - { - "content": ".@part2pictures some of your best imagery yet. Filming Alex on the rock.#Belief", - "contenttype": "text/plain", - "created": 1445731782000, - "id": "658072908237934592", - "language": "en" - }, - { - "content": "I just love Alex and his daring #Belief to live fully the present Moment.", - "contenttype": "text/plain", - "created": 1445731561000, - "id": "658071980982206464", - "language": "en" - }, - { - "content": "RT @GrowingOWN: Let's do this! #Belief finale tweet tweet party. Thank you @Oprah! \ud83d\ude4f", - "contenttype": "text/plain", - "created": 1445731248000, - "id": "658070668785770496", - "language": "en" - }, - { - "content": "RT @lizkinnell: The epic finale of #Belief on @OWNTV is about to start. 8\/et Are you ready? What do you Believe?", - "contenttype": "text/plain", - "created": 1445731081000, - "id": "658069968534171648", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night of Belief. Belief runs all day tomorrow for bingers and final episode!", - "contenttype": "text/plain", - "created": 1445648630000, - "id": "657724143115202560", - "language": "en" - }, - { - "content": "RT @OWNingLight: #Belief is the ultimate travel map to mass acceptance. \ud83d\ude4f\ud83c\udffb\u2764\ufe0f\ud83c\udf0d @Oprah", - "contenttype": "text/plain", - "created": 1445647285000, - "id": "657718501147197442", - "language": "en" - }, - { - "content": "\" I can feel my heart opening and faith coming back in\".. What's better than that? #Belief", - "contenttype": "text/plain", - "created": 1445646903000, - "id": "657716901951369218", - "language": "en" - }, - { - "content": "Hey Belief team mates can yo believe how quickly the week has passed? #Belief", - "contenttype": "text/plain", - "created": 1445645633000, - "id": "657711572492533760", - "language": "en" - }, - { - "content": "Ran into @5SOS backstage. Fun times with @TheEllenShow today! https:\/\/t.co\/2PP3W3RzXc", - "contenttype": "text/plain", - "created": 1445618531000, - "id": "657597898394173440", - "language": "en" - }, - { - "content": "Thanks All for another great night of #BELIEF", - "contenttype": "text/plain", - "created": 1445572548000, - "id": "657405031822430208", - "language": "en" - }, - { - "content": "RT @3LWTV: #BecomeWhatYouBelieve New meditation w\/ @Oprah @DeepakChopra begins 11\/2 Register https:\/\/t.co\/x0R9HWTAX0 #Belief https:\/\/t.co\/\u2026", - "contenttype": "text/plain", - "created": 1445571500000, - "id": "657400636745510912", - "language": "en" - }, - { - "content": "Ok west coast let's do it! #belief", - "contenttype": "text/plain", - "created": 1445569367000, - "id": "657391689439404033", - "language": "en" - }, - { - "content": "Thank u kind gentleman who told me I had kale in my teeth. Was eating kale chips with Quincy Jones. Went straight to @LairdLife party.", - "contenttype": "text/plain", - "created": 1445569296000, - "id": "657391393883619328", - "language": "en" - }, - { - "content": "Hello west coast twitterati.. See you at 8 for #Belief", - "contenttype": "text/plain", - "created": 1445566144000, - "id": "657378171872874496", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night.#Belief", - "contenttype": "text/plain", - "created": 1445475948000, - "id": "656999861254918145", - "language": "en" - }, - { - "content": "RT @PRanganathan: \"Transformation is the rule of the game. The universe is not standing still.\" - Marcelo @OWNTV @Oprah #Belief", - "contenttype": "text/plain", - "created": 1445475602000, - "id": "656998409933451264", - "language": "en" - }, - { - "content": "\"The Universe is not standing still.. The whole Universe is expanding\" I love the dance between science and spirituality! #Belief", - "contenttype": "text/plain", - "created": 1445475580000, - "id": "656998320133398528", - "language": "en" - }, - { - "content": "\"Without our prayers and our songs we won't be here\" Apache leader.#Belief", - "contenttype": "text/plain", - "created": 1445473768000, - "id": "656990717504393216", - "language": "en" - }, - { - "content": "Notice her mother crying. She knows its last tine she will ever see her daughter.#Belief", - "contenttype": "text/plain", - "created": 1445473150000, - "id": "656988127433637888", - "language": "en" - }, - { - "content": "This final trial is unbelievable. Every hair gets pulled from her head one at a time. Now that is Something!!#Belief", - "contenttype": "text/plain", - "created": 1445473063000, - "id": "656987763644891136", - "language": "en" - }, - { - "content": "\"What my faith gives me no one can match\"#Belief", - "contenttype": "text/plain", - "created": 1445472961000, - "id": "656987336266223616", - "language": "en" - }, - { - "content": "It's a devotion to faith beyond anything Ive seen. Fascinating.Jain nuns. #Belief", - "contenttype": "text/plain", - "created": 1445472531000, - "id": "656985529951522816", - "language": "en" - }, - { - "content": "I'd never heard of Jain monks and nuns before doing this series. #Belief", - "contenttype": "text/plain", - "created": 1445472393000, - "id": "656984953037586433", - "language": "en" - }, - { - "content": "Good evening Team #Belief the Tweet is on!", - "contenttype": "text/plain", - "created": 1445472098000, - "id": "656983714883239937", - "language": "en" - }, - { - "content": "Thanks everyone for another Epic #Belief night!", - "contenttype": "text/plain", - "created": 1445302792000, - "id": "656273592485810176", - "language": "en" - }, - { - "content": "The Pastor and Imam represent the possibility of PEACE in the world. If they can do it. We can. Peace to All\ud83d\ude4f\ud83c\udffe #Belief", - "contenttype": "text/plain", - "created": 1445302749000, - "id": "656273415280705536", - "language": "en" - }, - { - "content": "We felt privileged to film the Hajj and explore the beauty of Islam.\n#99namesforGod #Belief", - "contenttype": "text/plain", - "created": 1445301110000, - "id": "656266540967424000", - "language": "en" - }, - { - "content": "Do you all believe in \"soul mates\"?\n#Belief", - "contenttype": "text/plain", - "created": 1445300138000, - "id": "656262462426238976", - "language": "en" - }, - { - "content": ".@RevEdBacon thank you so much for hosting tonight's #Belief at All Saints Church.", - "contenttype": "text/plain", - "created": 1445299749000, - "id": "656260832628756480", - "language": "en" - }, - { - "content": "This is one of the best love stories I've ever seen. #belief Ian and Larissa showing us the depths of love.#Belief", - "contenttype": "text/plain", - "created": 1445299614000, - "id": "656260263604310016", - "language": "en" - }, - { - "content": "Hey Everyone .. Tweeting from a bar in Atlanta with @SheriSalata OWN not in my hotel. Anything for #Belief", - "contenttype": "text/plain", - "created": 1445299326000, - "id": "656259057758654464", - "language": "en" - }, - { - "content": "RT @joshuadubois: When you see Ian & Larissa tonight on #BELIEF, you'll know what Christian love is all about. 8pmET, @OWNTV. Tune in! http\u2026", - "contenttype": "text/plain", - "created": 1445295716000, - "id": "656243916224638976", - "language": "en" - }, - { - "content": "RT @KimHaleDance: I Believe LAUGHTER. IS. CONTAGIOUS. What do you believe? See you tonight! 8\/7c.\u2764\ufe0f #Belief #Beliefin3words https:\/\/t.co\/x\u2026", - "contenttype": "text/plain", - "created": 1445295702000, - "id": "656243854610337793", - "language": "en" - }, - { - "content": "RT @OWNTV: See the world through someone else\u2019s soul. The epic journey of #Belief continues tonight at 8\/7c.\nhttps:\/\/t.co\/UKKMHZuC0g", - "contenttype": "text/plain", - "created": 1445295668000, - "id": "656243714507931648", - "language": "en" - }, - { - "content": "RT @OWNTV: Mendel Hurwitz's inquisitive nature grounded him in his faith. See where it's taken him now: https:\/\/t.co\/2iWmNOxK9r https:\/\/t.c\u2026", - "contenttype": "text/plain", - "created": 1445295661000, - "id": "656243684720050176", - "language": "en" - }, - { - "content": "Thank you for opening up the heart space and letting #Belief in. Tonight it keeps getting better. See you at 8\/7c\nhttps:\/\/t.co\/E65vkTray9", - "contenttype": "text/plain", - "created": 1445279425000, - "id": "656175584943341568", - "language": "en" - }, - { - "content": "I believe in the @weightwatchers program so much I decided to invest, join the Board, and partner in #wwfamily evolution.", - "contenttype": "text/plain", - "created": 1445275802000, - "id": "656160388526899200", - "language": "en" - }, - { - "content": "RT @AVAETC: Debut episode of #BELIEF has now aired on both coasts. Trended for 4 hours. Brava, @Oprah + team. 6 beautiful nights to come. B\u2026", - "contenttype": "text/plain", - "created": 1445229489000, - "id": "655966138279432192", - "language": "en" - }, - { - "content": "RT @3LWTV: 6 more epic nights of #Belief to come! See you tomorrow 8pET\/7pCT for the next installment! @OWNTV @Oprah", - "contenttype": "text/plain", - "created": 1445227342000, - "id": "655957135688241152", - "language": "en" - }, - { - "content": "RT @ledisi: I love how Ancestry and Tradition is honored throughout every story in #Belief @OWNTV @OWN Thank you @Oprah this is so importa\u2026", - "contenttype": "text/plain", - "created": 1445225935000, - "id": "655951232981295104", - "language": "en" - }, - { - "content": "RT @UN: Showing #Belief at the UN \"is a bigger dream than I had\" - @Oprah https:\/\/t.co\/VC4OqD8yub #Belief #GlobalGoals https:\/\/t.co\/LZyGuC7\u2026", - "contenttype": "text/plain", - "created": 1445225228000, - "id": "655948267868426240", - "language": "en" - }, - { - "content": "RT @UzoAduba: To seek, to question, to learn, to teach, to pass it on; some of the breathtaking themes running like water throughout #Belie\u2026", - "contenttype": "text/plain", - "created": 1445225008000, - "id": "655947345197076480", - "language": "en" - }, - { - "content": "RT @iamtikasumpter: #Belief had me in awe. Faith in the divine is the constant that links us together. It's all beautiful and righteous. Gi\u2026", - "contenttype": "text/plain", - "created": 1445224852000, - "id": "655946689249828864", - "language": "en" - }, - { - "content": "West Coast... Here we go. #Belief", - "contenttype": "text/plain", - "created": 1445224140000, - "id": "655943701840048128", - "language": "en" - }, - { - "content": "Big surprise at icanady watch party. Epic night. #Belief. So much more to come. https:\/\/t.co\/kBDtFwGyQs", - "contenttype": "text/plain", - "created": 1445220694000, - "id": "655929249669378048", - "language": "en" - }, - { - "content": "I loved the Mendel story so much because it represents right of passasge. \" bye bye to childhood\".#Belief", - "contenttype": "text/plain", - "created": 1445215032000, - "id": "655905500056391682", - "language": "en" - }, - { - "content": "RT @squee_machine: This is a visual feast! Completely gorgeous and I am transfixed. The colors, the composition, cinematography, vibe. #Bel\u2026", - "contenttype": "text/plain", - "created": 1445214538000, - "id": "655903432079904768", - "language": "en" - }, - { - "content": "RT @JamesTyphany: Looking at @ #Belief I really needed this in my life thanks @OWNTV", - "contenttype": "text/plain", - "created": 1445214534000, - "id": "655903413385891840", - "language": "en" - }, - { - "content": "Just surprised a \"watch party\" @icanady 's house. #Belief http:\/\/t.co\/Di0I3OooCh", - "contenttype": "text/plain", - "created": 1445214502000, - "id": "655903277796732931", - "language": "en" - }, - { - "content": "RT @MsLaWandaa: I love moments of sitting among elders and learning. I can feel this moment was special for @ReshThakkar #Belief", - "contenttype": "text/plain", - "created": 1445214498000, - "id": "655903264374812672", - "language": "en" - }, - { - "content": "RT @xonecole: \"Do you have to have religion or is being a good person...is that enough?\" #Belief", - "contenttype": "text/plain", - "created": 1445214339000, - "id": "655902594171203584", - "language": "en" - }, - { - "content": "RT @ChivonJohn: Very inspired by the stories on #belief https:\/\/t.co\/uMRCCfCWcY", - "contenttype": "text/plain", - "created": 1445214327000, - "id": "655902545903140864", - "language": "en" - }, - { - "content": "RT @KiranSArora: powerful personal story that many of us can connect to. searching for what's missing, spiritual liberation. @ReshThakkar #\u2026", - "contenttype": "text/plain", - "created": 1445214128000, - "id": "655901708506103812", - "language": "en" - }, - { - "content": "RT @createdbyerica: \"I'm willing to go as far as I have to go to get that feeling in my heart of being connected to the Divine.\" - Reshma @\u2026", - "contenttype": "text/plain", - "created": 1445213967000, - "id": "655901033952993280", - "language": "en" - }, - { - "content": "RT @UrbnHealthNP: I am enjoying this so much. #Belief", - "contenttype": "text/plain", - "created": 1445213904000, - "id": "655900772467474435", - "language": "en" - }, - { - "content": "RT @DrMABrown: Your relationship with #belief can be completely different than how others experience it", - "contenttype": "text/plain", - "created": 1445213901000, - "id": "655900756604620800", - "language": "en" - }, - { - "content": "RT @ckerfin: On another river on the other side of the world... transition between stories, drawing connections to different beliefs #Belie\u2026", - "contenttype": "text/plain", - "created": 1445213721000, - "id": "655900002644987905", - "language": "en" - }, - { - "content": "RT @nikfarrior: So profound. We are all born into #Belief @Oprah @OWN @OWNTV", - "contenttype": "text/plain", - "created": 1445213706000, - "id": "655899942242775040", - "language": "en" - }, - { - "content": "RT @fgaboys: @Oprah the start of #Belief is riveting and edifying. It makes you want more and inspires you too see what's coming up next. \u2026", - "contenttype": "text/plain", - "created": 1445213699000, - "id": "655899910563217408", - "language": "en" - }, - { - "content": "RT @MalikaGhosh: Here we GO- let's lose ourselves #belief NOW @Oprah JOY http:\/\/t.co\/vYSNLd3LvC", - "contenttype": "text/plain", - "created": 1445212831000, - "id": "655896269542420480", - "language": "en" - }, - { - "content": "RT @MastinKipp: .@Oprah and team are about to bring the Light with #Belief.", - "contenttype": "text/plain", - "created": 1445212747000, - "id": "655895916675600384", - "language": "en" - }, - { - "content": "RT @GrowingOWN: 7 minutes, y'all! #BELIEF", - "contenttype": "text/plain", - "created": 1445212465000, - "id": "655894734968217600", - "language": "en" - }, - { - "content": "RT @LPToussaint: BELIEF defines experience.Choose wisely #Belief Tonight on OWN", - "contenttype": "text/plain", - "created": 1445211845000, - "id": "655892134524878848", - "language": "en" - }, - { - "content": "RT @TheBeBeWinans: Congratulations to my dear friend @Oprah on the launch of your series #BELIEF #Tonight on @OWNTV. Your friendship inspir\u2026", - "contenttype": "text/plain", - "created": 1445211835000, - "id": "655892094905532416", - "language": "en" - }, - { - "content": "RT @UzoAduba: Thirty minutes to @Oprah #Belief. Pretty sure it's about to be our favorite thing.", - "contenttype": "text/plain", - "created": 1445211833000, - "id": "655892084314890240", - "language": "en" - }, - { - "content": "RT @DeandresVoice: Moments away from the start of @SuperSoulSunday and the first night of the epic #Belief series on @OWNTV - are you ready\u2026", - "contenttype": "text/plain", - "created": 1445209201000, - "id": "655881046102142978", - "language": "en" - }, - { - "content": "RT @jennaldewan: I CANT WAIT FOR THIS TONIGHT!!!!!! Got my popcorn, got my tissues I am readyyyyyy! #Belief https:\/\/t.co\/WluTdeEqal", - "contenttype": "text/plain", - "created": 1445209181000, - "id": "655880959535939584", - "language": "en" - }, - { - "content": "RT @indiaarie: U heard about @Oprah passion project? It's called #Belief - I've see some & Its special! Tonight - 7c\/8e - 7 nights!! Whose\u2026", - "contenttype": "text/plain", - "created": 1445208945000, - "id": "655879970732949504", - "language": "en" - }, - { - "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass", - "contenttype": "text/plain", - "created": 1447639154000, - "id": "666073008692314113", - "language": "en" - }, - { - "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass", - "contenttype": "text/plain", - "created": 1447638226000, - "id": "666069114889179136", - "language": "en" - }, - { - "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass", - "contenttype": "text/plain", - "created": 1447638067000, - "id": "666068446325665792", - "language": "en" - }, - { - "content": "Wow aren't you loving @TheRock and his candor? #Masterclass", - "contenttype": "text/plain", - "created": 1447637459000, - "id": "666065895932973057", - "language": "en" - }, - { - "content": "RT @patt_t: @TheRock @Oprah @RichOnOWN @OWNTV this interview makes me like you as a fellow human even more for being so real.", - "contenttype": "text/plain", - "created": 1447637030000, - "id": "666064097562247168", - "language": "en" - }, - { - "content": "\"Be You\".. That's the best advice ever @TheRock #MastersClass", - "contenttype": "text/plain", - "created": 1447636205000, - "id": "666060637181644800", - "language": "en" - }, - { - "content": "Supersoulers let's lift our spirits pray and hold Paris in the Light\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1447602477000, - "id": "665919171062927360", - "language": "en" - }, - { - "content": "RT @DeepakChopra: What I learned in week 1: Become What You Believe 21-Day Meditation Experience - https:\/\/t.co\/kqaMaMqEUp #GoogleAlerts", - "contenttype": "text/plain", - "created": 1447098990000, - "id": "663807393063538688", - "language": "en" - }, - { - "content": "Watching Bryan Stevenson on #SuperSoulSunday! \"You are not the worst mistake you ever made\".\nAren't we glad about that.", - "contenttype": "text/plain", - "created": 1446998643000, - "id": "663386507856736257", - "language": "en" - }, - { - "content": ".@CherylStrayed BRAVE ENOUGH my new favorite thing! Gonna buy a copy for all my girls. #Perfectgift https:\/\/t.co\/gz1tnv8t8K", - "contenttype": "text/plain", - "created": 1446915955000, - "id": "663039689360695296", - "language": "en" - }, - { - "content": "Stevie Wonder singing \"Happy Birthday to you!\" to my dear mariashriver. A phenomenal woman and\u2026 https:\/\/t.co\/Ygm5eDIs4f", - "contenttype": "text/plain", - "created": 1446881193000, - "id": "662893888080879616", - "language": "en" - }, - { - "content": "It\u2019s my faaaaavorite time of the Year! For the first time you can shop the list on @amazon! https:\/\/t.co\/a6GMvVrhjN https:\/\/t.co\/sJlQMROq5U", - "contenttype": "text/plain", - "created": 1446744186000, - "id": "662319239844380672", - "language": "en" - }, - { - "content": "Incredible story \"the spirit of the Lord is on you\" thanks for sharing @smokey_robinson #Masterclass", - "contenttype": "text/plain", - "created": 1446428929000, - "id": "660996956861280256", - "language": "en" - }, - { - "content": "Wasnt that incredible story about @smokey_robinson 's dad leaving his family at 12. #MasterClass", - "contenttype": "text/plain", - "created": 1446426630000, - "id": "660987310889041920", - "language": "en" - }, - { - "content": "Gayle, Charlie, Nora @CBSThisMorning Congratulations! #1000thshow", - "contenttype": "text/plain", - "created": 1446220097000, - "id": "660121050978611205", - "language": "en" - }, - { - "content": "I believe your home should rise up to meet you. @TheEllenShow you nailed it with HOME. Tweethearts, grab a copy! https:\/\/t.co\/iFMnpRAsno", - "contenttype": "text/plain", - "created": 1446074433000, - "id": "659510090748182528", - "language": "en" - }, - { - "content": "Can I get a Witness?!\u270b\ud83c\udffe https:\/\/t.co\/tZ1QyAeSdE", - "contenttype": "text/plain", - "created": 1445821114000, - "id": "658447593865945089", - "language": "en" - }, - { - "content": ".@TheEllenShow you're a treasure.\nYour truth set a lot of people free.\n#Masterclass", - "contenttype": "text/plain", - "created": 1445821003000, - "id": "658447130026188800", - "language": "en" - }, - { - "content": "Hope you all are enjoying @TheEllenShow on #MasterClass.", - "contenttype": "text/plain", - "created": 1445820161000, - "id": "658443598313181188", - "language": "en" - }, - { - "content": ".@GloriaSteinem, shero to women everywhere, on how far we\u2019ve come and how far we need to go. #SuperSoulSunday 7p\/6c.\nhttps:\/\/t.co\/3e7oxXW02J", - "contenttype": "text/plain", - "created": 1445811545000, - "id": "658407457438363648", - "language": "en" - }, - { - "content": "RT @TheEllenShow: I told a story from my @OWNTV's #MasterClass on my show. Normally I\u2019d save it all for Sunday, but @Oprah made me. https:\/\u2026", - "contenttype": "text/plain", - "created": 1445804181000, - "id": "658376572521459712", - "language": "en" - }, - { - "content": ".@TheEllenShow is a master teacher of living her truth & living authentically as herself. #MasterClass tonight 8\/7c.\nhttps:\/\/t.co\/iLT2KgRsSw", - "contenttype": "text/plain", - "created": 1445804072000, - "id": "658376116575449088", - "language": "en" - }, - { - "content": ".@SheriSalata , @jonnysinc @part2pictures . Tears of joy and gratitude to you and our entire #BeliefTeam We DID IT!! My heart is full.\ud83d\ude4f\ud83c\udffe\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1445734755000, - "id": "658085377140363264", - "language": "en" - }, - { - "content": "Donna and Bob saw the tape of their story just days before she passed. They appreciated it. #RIPDonna", - "contenttype": "text/plain", - "created": 1445734097000, - "id": "658082618819280896", - "language": "en" - }, - { - "content": "RT @rempower: .@Oprah this series allowed me to slide into people's lives around the world and see the same in them ... we all have a belie\u2026", - "contenttype": "text/plain", - "created": 1445732769000, - "id": "658077046858383360", - "language": "en" - }, - { - "content": "All the stories moved me, My favorite line \" I must pass the stories on to my grandson otherwise our people will loose their way. #Belief", - "contenttype": "text/plain", - "created": 1445732579000, - "id": "658076253618991104", - "language": "en" - }, - { - "content": ".@part2pictures some of your best imagery yet. Filming Alex on the rock.#Belief", - "contenttype": "text/plain", - "created": 1445731782000, - "id": "658072908237934592", - "language": "en" - }, - { - "content": "I just love Alex and his daring #Belief to live fully the present Moment.", - "contenttype": "text/plain", - "created": 1445731561000, - "id": "658071980982206464", - "language": "en" - }, - { - "content": "RT @GrowingOWN: Let's do this! #Belief finale tweet tweet party. Thank you @Oprah! \ud83d\ude4f", - "contenttype": "text/plain", - "created": 1445731248000, - "id": "658070668785770496", - "language": "en" - }, - { - "content": "RT @lizkinnell: The epic finale of #Belief on @OWNTV is about to start. 8\/et Are you ready? What do you Believe?", - "contenttype": "text/plain", - "created": 1445731081000, - "id": "658069968534171648", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night of Belief. Belief runs all day tomorrow for bingers and final episode!", - "contenttype": "text/plain", - "created": 1445648630000, - "id": "657724143115202560", - "language": "en" - }, - { - "content": "RT @OWNingLight: #Belief is the ultimate travel map to mass acceptance. \ud83d\ude4f\ud83c\udffb\u2764\ufe0f\ud83c\udf0d @Oprah", - "contenttype": "text/plain", - "created": 1445647285000, - "id": "657718501147197442", - "language": "en" - }, - { - "content": "\" I can feel my heart opening and faith coming back in\".. What's better than that? #Belief", - "contenttype": "text/plain", - "created": 1445646903000, - "id": "657716901951369218", - "language": "en" - }, - { - "content": "Hey Belief team mates can yo believe how quickly the week has passed? #Belief", - "contenttype": "text/plain", - "created": 1445645633000, - "id": "657711572492533760", - "language": "en" - }, - { - "content": "Ran into @5SOS backstage. Fun times with @TheEllenShow today! https:\/\/t.co\/2PP3W3RzXc", - "contenttype": "text/plain", - "created": 1445618531000, - "id": "657597898394173440", - "language": "en" - }, - { - "content": "Thanks All for another great night of #BELIEF", - "contenttype": "text/plain", - "created": 1445572548000, - "id": "657405031822430208", - "language": "en" - }, - { - "content": "RT @3LWTV: #BecomeWhatYouBelieve New meditation w\/ @Oprah @DeepakChopra begins 11\/2 Register https:\/\/t.co\/x0R9HWTAX0 #Belief https:\/\/t.co\/\u2026", - "contenttype": "text/plain", - "created": 1445571500000, - "id": "657400636745510912", - "language": "en" - }, - { - "content": "Ok west coast let's do it! #belief", - "contenttype": "text/plain", - "created": 1445569367000, - "id": "657391689439404033", - "language": "en" - }, - { - "content": "Thank u kind gentleman who told me I had kale in my teeth. Was eating kale chips with Quincy Jones. Went straight to @LairdLife party.", - "contenttype": "text/plain", - "created": 1445569296000, - "id": "657391393883619328", - "language": "en" - }, - { - "content": "Hello west coast twitterati.. See you at 8 for #Belief", - "contenttype": "text/plain", - "created": 1445566144000, - "id": "657378171872874496", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night.#Belief", - "contenttype": "text/plain", - "created": 1445475948000, - "id": "656999861254918145", - "language": "en" - }, - { - "content": "RT @PRanganathan: \"Transformation is the rule of the game. The universe is not standing still.\" - Marcelo @OWNTV @Oprah #Belief", - "contenttype": "text/plain", - "created": 1445475602000, - "id": "656998409933451264", - "language": "en" - }, - { - "content": "\"The Universe is not standing still.. The whole Universe is expanding\" I love the dance between science and spirituality! #Belief", - "contenttype": "text/plain", - "created": 1445475580000, - "id": "656998320133398528", - "language": "en" - }, - { - "content": "\"Without our prayers and our songs we won't be here\" Apache leader.#Belief", - "contenttype": "text/plain", - "created": 1445473768000, - "id": "656990717504393216", - "language": "en" - }, - { - "content": "Notice her mother crying. She knows its last tine she will ever see her daughter.#Belief", - "contenttype": "text/plain", - "created": 1445473150000, - "id": "656988127433637888", - "language": "en" - }, - { - "content": "This final trial is unbelievable. Every hair gets pulled from her head one at a time. Now that is Something!!#Belief", - "contenttype": "text/plain", - "created": 1445473063000, - "id": "656987763644891136", - "language": "en" - }, - { - "content": "\"What my faith gives me no one can match\"#Belief", - "contenttype": "text/plain", - "created": 1445472961000, - "id": "656987336266223616", - "language": "en" - }, - { - "content": "It's a devotion to faith beyond anything Ive seen. Fascinating.Jain nuns. #Belief", - "contenttype": "text/plain", - "created": 1445472531000, - "id": "656985529951522816", - "language": "en" - }, - { - "content": "I'd never heard of Jain monks and nuns before doing this series. #Belief", - "contenttype": "text/plain", - "created": 1445472393000, - "id": "656984953037586433", - "language": "en" - }, - { - "content": "Good evening Team #Belief the Tweet is on!", - "contenttype": "text/plain", - "created": 1445472098000, - "id": "656983714883239937", - "language": "en" - }, - { - "content": "Thanks everyone for another Epic #Belief night!", - "contenttype": "text/plain", - "created": 1445302792000, - "id": "656273592485810176", - "language": "en" - }, - { - "content": "The Pastor and Imam represent the possibility of PEACE in the world. If they can do it. We can. Peace to All\ud83d\ude4f\ud83c\udffe #Belief", - "contenttype": "text/plain", - "created": 1445302749000, - "id": "656273415280705536", - "language": "en" - }, - { - "content": "We felt privileged to film the Hajj and explore the beauty of Islam.\n#99namesforGod #Belief", - "contenttype": "text/plain", - "created": 1445301110000, - "id": "656266540967424000", - "language": "en" - }, - { - "content": "Do you all believe in \"soul mates\"?\n#Belief", - "contenttype": "text/plain", - "created": 1445300138000, - "id": "656262462426238976", - "language": "en" - }, - { - "content": ".@RevEdBacon thank you so much for hosting tonight's #Belief at All Saints Church.", - "contenttype": "text/plain", - "created": 1445299749000, - "id": "656260832628756480", - "language": "en" - }, - { - "content": "This is one of the best love stories I've ever seen. #belief Ian and Larissa showing us the depths of love.#Belief", - "contenttype": "text/plain", - "created": 1445299614000, - "id": "656260263604310016", - "language": "en" - }, - { - "content": "Hey Everyone .. Tweeting from a bar in Atlanta with @SheriSalata OWN not in my hotel. Anything for #Belief", - "contenttype": "text/plain", - "created": 1445299326000, - "id": "656259057758654464", - "language": "en" - }, - { - "content": "RT @joshuadubois: When you see Ian & Larissa tonight on #BELIEF, you'll know what Christian love is all about. 8pmET, @OWNTV. Tune in! http\u2026", - "contenttype": "text/plain", - "created": 1445295716000, - "id": "656243916224638976", - "language": "en" - }, - { - "content": "RT @KimHaleDance: I Believe LAUGHTER. IS. CONTAGIOUS. What do you believe? See you tonight! 8\/7c.\u2764\ufe0f #Belief #Beliefin3words https:\/\/t.co\/x\u2026", - "contenttype": "text/plain", - "created": 1445295702000, - "id": "656243854610337793", - "language": "en" - }, - { - "content": "RT @OWNTV: See the world through someone else\u2019s soul. The epic journey of #Belief continues tonight at 8\/7c.\nhttps:\/\/t.co\/UKKMHZuC0g", - "contenttype": "text/plain", - "created": 1445295668000, - "id": "656243714507931648", - "language": "en" - }, - { - "content": "RT @OWNTV: Mendel Hurwitz's inquisitive nature grounded him in his faith. See where it's taken him now: https:\/\/t.co\/2iWmNOxK9r https:\/\/t.c\u2026", - "contenttype": "text/plain", - "created": 1445295661000, - "id": "656243684720050176", - "language": "en" - }, - { - "content": "Thank you for opening up the heart space and letting #Belief in. Tonight it keeps getting better. See you at 8\/7c\nhttps:\/\/t.co\/E65vkTray9", - "contenttype": "text/plain", - "created": 1445279425000, - "id": "656175584943341568", - "language": "en" - }, - { - "content": "I believe in the @weightwatchers program so much I decided to invest, join the Board, and partner in #wwfamily evolution.", - "contenttype": "text/plain", - "created": 1445275802000, - "id": "656160388526899200", - "language": "en" - }, - { - "content": "RT @AVAETC: Debut episode of #BELIEF has now aired on both coasts. Trended for 4 hours. Brava, @Oprah + team. 6 beautiful nights to come. B\u2026", - "contenttype": "text/plain", - "created": 1445229489000, - "id": "655966138279432192", - "language": "en" - }, - { - "content": "RT @3LWTV: 6 more epic nights of #Belief to come! See you tomorrow 8pET\/7pCT for the next installment! @OWNTV @Oprah", - "contenttype": "text/plain", - "created": 1445227342000, - "id": "655957135688241152", - "language": "en" - }, - { - "content": "RT @ledisi: I love how Ancestry and Tradition is honored throughout every story in #Belief @OWNTV @OWN Thank you @Oprah this is so importa\u2026", - "contenttype": "text/plain", - "created": 1445225935000, - "id": "655951232981295104", - "language": "en" - }, - { - "content": "RT @UN: Showing #Belief at the UN \"is a bigger dream than I had\" - @Oprah https:\/\/t.co\/VC4OqD8yub #Belief #GlobalGoals https:\/\/t.co\/LZyGuC7\u2026", - "contenttype": "text/plain", - "created": 1445225228000, - "id": "655948267868426240", - "language": "en" - }, - { - "content": "RT @UzoAduba: To seek, to question, to learn, to teach, to pass it on; some of the breathtaking themes running like water throughout #Belie\u2026", - "contenttype": "text/plain", - "created": 1445225008000, - "id": "655947345197076480", - "language": "en" - }, - { - "content": "RT @iamtikasumpter: #Belief had me in awe. Faith in the divine is the constant that links us together. It's all beautiful and righteous. Gi\u2026", - "contenttype": "text/plain", - "created": 1445224852000, - "id": "655946689249828864", - "language": "en" - }, - { - "content": "West Coast... Here we go. #Belief", - "contenttype": "text/plain", - "created": 1445224140000, - "id": "655943701840048128", - "language": "en" - }, - { - "content": "Big surprise at icanady watch party. Epic night. #Belief. So much more to come. https:\/\/t.co\/kBDtFwGyQs", - "contenttype": "text/plain", - "created": 1445220694000, - "id": "655929249669378048", - "language": "en" - }, - { - "content": "I loved the Mendel story so much because it represents right of passasge. \" bye bye to childhood\".#Belief", - "contenttype": "text/plain", - "created": 1445215032000, - "id": "655905500056391682", - "language": "en" - }, - { - "content": "RT @squee_machine: This is a visual feast! Completely gorgeous and I am transfixed. The colors, the composition, cinematography, vibe. #Bel\u2026", - "contenttype": "text/plain", - "created": 1445214538000, - "id": "655903432079904768", - "language": "en" - }, - { - "content": "RT @JamesTyphany: Looking at @ #Belief I really needed this in my life thanks @OWNTV", - "contenttype": "text/plain", - "created": 1445214534000, - "id": "655903413385891840", - "language": "en" - }, - { - "content": "Just surprised a \"watch party\" @icanady 's house. #Belief http:\/\/t.co\/Di0I3OooCh", - "contenttype": "text/plain", - "created": 1445214502000, - "id": "655903277796732931", - "language": "en" - }, - { - "content": "RT @MsLaWandaa: I love moments of sitting among elders and learning. I can feel this moment was special for @ReshThakkar #Belief", - "contenttype": "text/plain", - "created": 1445214498000, - "id": "655903264374812672", - "language": "en" - }, - { - "content": "RT @xonecole: \"Do you have to have religion or is being a good person...is that enough?\" #Belief", - "contenttype": "text/plain", - "created": 1445214339000, - "id": "655902594171203584", - "language": "en" - }, - { - "content": "RT @ChivonJohn: Very inspired by the stories on #belief https:\/\/t.co\/uMRCCfCWcY", - "contenttype": "text/plain", - "created": 1445214327000, - "id": "655902545903140864", - "language": "en" - }, - { - "content": "RT @KiranSArora: powerful personal story that many of us can connect to. searching for what's missing, spiritual liberation. @ReshThakkar #\u2026", - "contenttype": "text/plain", - "created": 1445214128000, - "id": "655901708506103812", - "language": "en" - }, - { - "content": "RT @createdbyerica: \"I'm willing to go as far as I have to go to get that feeling in my heart of being connected to the Divine.\" - Reshma @\u2026", - "contenttype": "text/plain", - "created": 1445213967000, - "id": "655901033952993280", - "language": "en" - }, - { - "content": "RT @UrbnHealthNP: I am enjoying this so much. #Belief", - "contenttype": "text/plain", - "created": 1445213904000, - "id": "655900772467474435", - "language": "en" - }, - { - "content": "RT @DrMABrown: Your relationship with #belief can be completely different than how others experience it", - "contenttype": "text/plain", - "created": 1445213901000, - "id": "655900756604620800", - "language": "en" - }, - { - "content": "RT @ckerfin: On another river on the other side of the world... transition between stories, drawing connections to different beliefs #Belie\u2026", - "contenttype": "text/plain", - "created": 1445213721000, - "id": "655900002644987905", - "language": "en" - }, - { - "content": "RT @nikfarrior: So profound. We are all born into #Belief @Oprah @OWN @OWNTV", - "contenttype": "text/plain", - "created": 1445213706000, - "id": "655899942242775040", - "language": "en" - }, - { - "content": "RT @fgaboys: @Oprah the start of #Belief is riveting and edifying. It makes you want more and inspires you too see what's coming up next. \u2026", - "contenttype": "text/plain", - "created": 1445213699000, - "id": "655899910563217408", - "language": "en" - }, - { - "content": "RT @MalikaGhosh: Here we GO- let's lose ourselves #belief NOW @Oprah JOY http:\/\/t.co\/vYSNLd3LvC", - "contenttype": "text/plain", - "created": 1445212831000, - "id": "655896269542420480", - "language": "en" - }, - { - "content": "RT @MastinKipp: .@Oprah and team are about to bring the Light with #Belief.", - "contenttype": "text/plain", - "created": 1445212747000, - "id": "655895916675600384", - "language": "en" - }, - { - "content": "RT @GrowingOWN: 7 minutes, y'all! #BELIEF", - "contenttype": "text/plain", - "created": 1445212465000, - "id": "655894734968217600", - "language": "en" - }, - { - "content": "RT @LPToussaint: BELIEF defines experience.Choose wisely #Belief Tonight on OWN", - "contenttype": "text/plain", - "created": 1445211845000, - "id": "655892134524878848", - "language": "en" - }, - { - "content": "RT @TheBeBeWinans: Congratulations to my dear friend @Oprah on the launch of your series #BELIEF #Tonight on @OWNTV. Your friendship inspir\u2026", - "contenttype": "text/plain", - "created": 1445211835000, - "id": "655892094905532416", - "language": "en" - }, - { - "content": "RT @UzoAduba: Thirty minutes to @Oprah #Belief. Pretty sure it's about to be our favorite thing.", - "contenttype": "text/plain", - "created": 1445211833000, - "id": "655892084314890240", - "language": "en" - }, - { - "content": "RT @DeandresVoice: Moments away from the start of @SuperSoulSunday and the first night of the epic #Belief series on @OWNTV - are you ready\u2026", - "contenttype": "text/plain", - "created": 1445209201000, - "id": "655881046102142978", - "language": "en" - }, - { - "content": "RT @jennaldewan: I CANT WAIT FOR THIS TONIGHT!!!!!! Got my popcorn, got my tissues I am readyyyyyy! #Belief https:\/\/t.co\/WluTdeEqal", - "contenttype": "text/plain", - "created": 1445209181000, - "id": "655880959535939584", - "language": "en" - }, - { - "content": "RT @indiaarie: U heard about @Oprah passion project? It's called #Belief - I've see some & Its special! Tonight - 7c\/8e - 7 nights!! Whose\u2026", - "contenttype": "text/plain", - "created": 1445208945000, - "id": "655879970732949504", - "language": "en" - }, - { - "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass", - "contenttype": "text/plain", - "created": 1447639154000, - "id": "666073008692314113", - "language": "en" - }, - { - "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass", - "contenttype": "text/plain", - "created": 1447638226000, - "id": "666069114889179136", - "language": "en" - }, - { - "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass", - "contenttype": "text/plain", - "created": 1447638067000, - "id": "666068446325665792", - "language": "en" - }, - { - "content": "Wow aren't you loving @TheRock and his candor? #Masterclass", - "contenttype": "text/plain", - "created": 1447637459000, - "id": "666065895932973057", - "language": "en" - }, - { - "content": "RT @patt_t: @TheRock @Oprah @RichOnOWN @OWNTV this interview makes me like you as a fellow human even more for being so real.", - "contenttype": "text/plain", - "created": 1447637030000, - "id": "666064097562247168", - "language": "en" - }, - { - "content": "\"Be You\".. That's the best advice ever @TheRock #MastersClass", - "contenttype": "text/plain", - "created": 1447636205000, - "id": "666060637181644800", - "language": "en" - }, - { - "content": "Supersoulers let's lift our spirits pray and hold Paris in the Light\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1447602477000, - "id": "665919171062927360", - "language": "en" - }, - { - "content": "RT @DeepakChopra: What I learned in week 1: Become What You Believe 21-Day Meditation Experience - https:\/\/t.co\/kqaMaMqEUp #GoogleAlerts", - "contenttype": "text/plain", - "created": 1447098990000, - "id": "663807393063538688", - "language": "en" - }, - { - "content": "Watching Bryan Stevenson on #SuperSoulSunday! \"You are not the worst mistake you ever made\".\nAren't we glad about that.", - "contenttype": "text/plain", - "created": 1446998643000, - "id": "663386507856736257", - "language": "en" - }, - { - "content": ".@CherylStrayed BRAVE ENOUGH my new favorite thing! Gonna buy a copy for all my girls. #Perfectgift https:\/\/t.co\/gz1tnv8t8K", - "contenttype": "text/plain", - "created": 1446915955000, - "id": "663039689360695296", - "language": "en" - }, - { - "content": "Stevie Wonder singing \"Happy Birthday to you!\" to my dear mariashriver. A phenomenal woman and\u2026 https:\/\/t.co\/Ygm5eDIs4f", - "contenttype": "text/plain", - "created": 1446881193000, - "id": "662893888080879616", - "language": "en" - }, - { - "content": "It\u2019s my faaaaavorite time of the Year! For the first time you can shop the list on @amazon! https:\/\/t.co\/a6GMvVrhjN https:\/\/t.co\/sJlQMROq5U", - "contenttype": "text/plain", - "created": 1446744186000, - "id": "662319239844380672", - "language": "en" - }, - { - "content": "Incredible story \"the spirit of the Lord is on you\" thanks for sharing @smokey_robinson #Masterclass", - "contenttype": "text/plain", - "created": 1446428929000, - "id": "660996956861280256", - "language": "en" - }, - { - "content": "Wasnt that incredible story about @smokey_robinson 's dad leaving his family at 12. #MasterClass", - "contenttype": "text/plain", - "created": 1446426630000, - "id": "660987310889041920", - "language": "en" - }, - { - "content": "Gayle, Charlie, Nora @CBSThisMorning Congratulations! #1000thshow", - "contenttype": "text/plain", - "created": 1446220097000, - "id": "660121050978611205", - "language": "en" - }, - { - "content": "I believe your home should rise up to meet you. @TheEllenShow you nailed it with HOME. Tweethearts, grab a copy! https:\/\/t.co\/iFMnpRAsno", - "contenttype": "text/plain", - "created": 1446074433000, - "id": "659510090748182528", - "language": "en" - }, - { - "content": "Can I get a Witness?!\u270b\ud83c\udffe https:\/\/t.co\/tZ1QyAeSdE", - "contenttype": "text/plain", - "created": 1445821114000, - "id": "658447593865945089", - "language": "en" - }, - { - "content": ".@TheEllenShow you're a treasure.\nYour truth set a lot of people free.\n#Masterclass", - "contenttype": "text/plain", - "created": 1445821003000, - "id": "658447130026188800", - "language": "en" - }, - { - "content": "Hope you all are enjoying @TheEllenShow on #MasterClass.", - "contenttype": "text/plain", - "created": 1445820161000, - "id": "658443598313181188", - "language": "en" - }, - { - "content": ".@GloriaSteinem, shero to women everywhere, on how far we\u2019ve come and how far we need to go. #SuperSoulSunday 7p\/6c.\nhttps:\/\/t.co\/3e7oxXW02J", - "contenttype": "text/plain", - "created": 1445811545000, - "id": "658407457438363648", - "language": "en" - }, - { - "content": "RT @TheEllenShow: I told a story from my @OWNTV's #MasterClass on my show. Normally I\u2019d save it all for Sunday, but @Oprah made me. https:\/\u2026", - "contenttype": "text/plain", - "created": 1445804181000, - "id": "658376572521459712", - "language": "en" - }, - { - "content": ".@TheEllenShow is a master teacher of living her truth & living authentically as herself. #MasterClass tonight 8\/7c.\nhttps:\/\/t.co\/iLT2KgRsSw", - "contenttype": "text/plain", - "created": 1445804072000, - "id": "658376116575449088", - "language": "en" - }, - { - "content": ".@SheriSalata , @jonnysinc @part2pictures . Tears of joy and gratitude to you and our entire #BeliefTeam We DID IT!! My heart is full.\ud83d\ude4f\ud83c\udffe\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1445734755000, - "id": "658085377140363264", - "language": "en" - }, - { - "content": "Donna and Bob saw the tape of their story just days before she passed. They appreciated it. #RIPDonna", - "contenttype": "text/plain", - "created": 1445734097000, - "id": "658082618819280896", - "language": "en" - }, - { - "content": "RT @rempower: .@Oprah this series allowed me to slide into people's lives around the world and see the same in them ... we all have a belie\u2026", - "contenttype": "text/plain", - "created": 1445732769000, - "id": "658077046858383360", - "language": "en" - }, - { - "content": "All the stories moved me, My favorite line \" I must pass the stories on to my grandson otherwise our people will loose their way. #Belief", - "contenttype": "text/plain", - "created": 1445732579000, - "id": "658076253618991104", - "language": "en" - }, - { - "content": ".@part2pictures some of your best imagery yet. Filming Alex on the rock.#Belief", - "contenttype": "text/plain", - "created": 1445731782000, - "id": "658072908237934592", - "language": "en" - }, - { - "content": "I just love Alex and his daring #Belief to live fully the present Moment.", - "contenttype": "text/plain", - "created": 1445731561000, - "id": "658071980982206464", - "language": "en" - }, - { - "content": "RT @GrowingOWN: Let's do this! #Belief finale tweet tweet party. Thank you @Oprah! \ud83d\ude4f", - "contenttype": "text/plain", - "created": 1445731248000, - "id": "658070668785770496", - "language": "en" - }, - { - "content": "RT @lizkinnell: The epic finale of #Belief on @OWNTV is about to start. 8\/et Are you ready? What do you Believe?", - "contenttype": "text/plain", - "created": 1445731081000, - "id": "658069968534171648", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night of Belief. Belief runs all day tomorrow for bingers and final episode!", - "contenttype": "text/plain", - "created": 1445648630000, - "id": "657724143115202560", - "language": "en" - }, - { - "content": "RT @OWNingLight: #Belief is the ultimate travel map to mass acceptance. \ud83d\ude4f\ud83c\udffb\u2764\ufe0f\ud83c\udf0d @Oprah", - "contenttype": "text/plain", - "created": 1445647285000, - "id": "657718501147197442", - "language": "en" - }, - { - "content": "\" I can feel my heart opening and faith coming back in\".. What's better than that? #Belief", - "contenttype": "text/plain", - "created": 1445646903000, - "id": "657716901951369218", - "language": "en" - }, - { - "content": "Hey Belief team mates can yo believe how quickly the week has passed? #Belief", - "contenttype": "text/plain", - "created": 1445645633000, - "id": "657711572492533760", - "language": "en" - }, - { - "content": "Ran into @5SOS backstage. Fun times with @TheEllenShow today! https:\/\/t.co\/2PP3W3RzXc", - "contenttype": "text/plain", - "created": 1445618531000, - "id": "657597898394173440", - "language": "en" - }, - { - "content": "Thanks All for another great night of #BELIEF", - "contenttype": "text/plain", - "created": 1445572548000, - "id": "657405031822430208", - "language": "en" - }, - { - "content": "RT @3LWTV: #BecomeWhatYouBelieve New meditation w\/ @Oprah @DeepakChopra begins 11\/2 Register https:\/\/t.co\/x0R9HWTAX0 #Belief https:\/\/t.co\/\u2026", - "contenttype": "text/plain", - "created": 1445571500000, - "id": "657400636745510912", - "language": "en" - }, - { - "content": "Ok west coast let's do it! #belief", - "contenttype": "text/plain", - "created": 1445569367000, - "id": "657391689439404033", - "language": "en" - }, - { - "content": "Thank u kind gentleman who told me I had kale in my teeth. Was eating kale chips with Quincy Jones. Went straight to @LairdLife party.", - "contenttype": "text/plain", - "created": 1445569296000, - "id": "657391393883619328", - "language": "en" - }, - { - "content": "Hello west coast twitterati.. See you at 8 for #Belief", - "contenttype": "text/plain", - "created": 1445566144000, - "id": "657378171872874496", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night.#Belief", - "contenttype": "text/plain", - "created": 1445475948000, - "id": "656999861254918145", - "language": "en" - }, - { - "content": "RT @PRanganathan: \"Transformation is the rule of the game. The universe is not standing still.\" - Marcelo @OWNTV @Oprah #Belief", - "contenttype": "text/plain", - "created": 1445475602000, - "id": "656998409933451264", - "language": "en" - }, - { - "content": "\"The Universe is not standing still.. The whole Universe is expanding\" I love the dance between science and spirituality! #Belief", - "contenttype": "text/plain", - "created": 1445475580000, - "id": "656998320133398528", - "language": "en" - }, - { - "content": "\"Without our prayers and our songs we won't be here\" Apache leader.#Belief", - "contenttype": "text/plain", - "created": 1445473768000, - "id": "656990717504393216", - "language": "en" - }, - { - "content": "Notice her mother crying. She knows its last tine she will ever see her daughter.#Belief", - "contenttype": "text/plain", - "created": 1445473150000, - "id": "656988127433637888", - "language": "en" - }, - { - "content": "This final trial is unbelievable. Every hair gets pulled from her head one at a time. Now that is Something!!#Belief", - "contenttype": "text/plain", - "created": 1445473063000, - "id": "656987763644891136", - "language": "en" - }, - { - "content": "\"What my faith gives me no one can match\"#Belief", - "contenttype": "text/plain", - "created": 1445472961000, - "id": "656987336266223616", - "language": "en" - }, - { - "content": "It's a devotion to faith beyond anything Ive seen. Fascinating.Jain nuns. #Belief", - "contenttype": "text/plain", - "created": 1445472531000, - "id": "656985529951522816", - "language": "en" - }, - { - "content": "I'd never heard of Jain monks and nuns before doing this series. #Belief", - "contenttype": "text/plain", - "created": 1445472393000, - "id": "656984953037586433", - "language": "en" - }, - { - "content": "Good evening Team #Belief the Tweet is on!", - "contenttype": "text/plain", - "created": 1445472098000, - "id": "656983714883239937", - "language": "en" - }, - { - "content": "Thanks everyone for another Epic #Belief night!", - "contenttype": "text/plain", - "created": 1445302792000, - "id": "656273592485810176", - "language": "en" - }, - { - "content": "The Pastor and Imam represent the possibility of PEACE in the world. If they can do it. We can. Peace to All\ud83d\ude4f\ud83c\udffe #Belief", - "contenttype": "text/plain", - "created": 1445302749000, - "id": "656273415280705536", - "language": "en" - }, - { - "content": "We felt privileged to film the Hajj and explore the beauty of Islam.\n#99namesforGod #Belief", - "contenttype": "text/plain", - "created": 1445301110000, - "id": "656266540967424000", - "language": "en" - }, - { - "content": "Do you all believe in \"soul mates\"?\n#Belief", - "contenttype": "text/plain", - "created": 1445300138000, - "id": "656262462426238976", - "language": "en" - }, - { - "content": ".@RevEdBacon thank you so much for hosting tonight's #Belief at All Saints Church.", - "contenttype": "text/plain", - "created": 1445299749000, - "id": "656260832628756480", - "language": "en" - }, - { - "content": "This is one of the best love stories I've ever seen. #belief Ian and Larissa showing us the depths of love.#Belief", - "contenttype": "text/plain", - "created": 1445299614000, - "id": "656260263604310016", - "language": "en" - }, - { - "content": "Hey Everyone .. Tweeting from a bar in Atlanta with @SheriSalata OWN not in my hotel. Anything for #Belief", - "contenttype": "text/plain", - "created": 1445299326000, - "id": "656259057758654464", - "language": "en" - }, - { - "content": "RT @joshuadubois: When you see Ian & Larissa tonight on #BELIEF, you'll know what Christian love is all about. 8pmET, @OWNTV. Tune in! http\u2026", - "contenttype": "text/plain", - "created": 1445295716000, - "id": "656243916224638976", - "language": "en" - }, - { - "content": "RT @KimHaleDance: I Believe LAUGHTER. IS. CONTAGIOUS. What do you believe? See you tonight! 8\/7c.\u2764\ufe0f #Belief #Beliefin3words https:\/\/t.co\/x\u2026", - "contenttype": "text/plain", - "created": 1445295702000, - "id": "656243854610337793", - "language": "en" - }, - { - "content": "RT @OWNTV: See the world through someone else\u2019s soul. The epic journey of #Belief continues tonight at 8\/7c.\nhttps:\/\/t.co\/UKKMHZuC0g", - "contenttype": "text/plain", - "created": 1445295668000, - "id": "656243714507931648", - "language": "en" - }, - { - "content": "RT @OWNTV: Mendel Hurwitz's inquisitive nature grounded him in his faith. See where it's taken him now: https:\/\/t.co\/2iWmNOxK9r https:\/\/t.c\u2026", - "contenttype": "text/plain", - "created": 1445295661000, - "id": "656243684720050176", - "language": "en" - }, - { - "content": "Thank you for opening up the heart space and letting #Belief in. Tonight it keeps getting better. See you at 8\/7c\nhttps:\/\/t.co\/E65vkTray9", - "contenttype": "text/plain", - "created": 1445279425000, - "id": "656175584943341568", - "language": "en" - }, - { - "content": "I believe in the @weightwatchers program so much I decided to invest, join the Board, and partner in #wwfamily evolution.", - "contenttype": "text/plain", - "created": 1445275802000, - "id": "656160388526899200", - "language": "en" - }, - { - "content": "RT @AVAETC: Debut episode of #BELIEF has now aired on both coasts. Trended for 4 hours. Brava, @Oprah + team. 6 beautiful nights to come. B\u2026", - "contenttype": "text/plain", - "created": 1445229489000, - "id": "655966138279432192", - "language": "en" - }, - { - "content": "RT @3LWTV: 6 more epic nights of #Belief to come! See you tomorrow 8pET\/7pCT for the next installment! @OWNTV @Oprah", - "contenttype": "text/plain", - "created": 1445227342000, - "id": "655957135688241152", - "language": "en" - }, - { - "content": "RT @ledisi: I love how Ancestry and Tradition is honored throughout every story in #Belief @OWNTV @OWN Thank you @Oprah this is so importa\u2026", - "contenttype": "text/plain", - "created": 1445225935000, - "id": "655951232981295104", - "language": "en" - }, - { - "content": "RT @UN: Showing #Belief at the UN \"is a bigger dream than I had\" - @Oprah https:\/\/t.co\/VC4OqD8yub #Belief #GlobalGoals https:\/\/t.co\/LZyGuC7\u2026", - "contenttype": "text/plain", - "created": 1445225228000, - "id": "655948267868426240", - "language": "en" - }, - { - "content": "RT @UzoAduba: To seek, to question, to learn, to teach, to pass it on; some of the breathtaking themes running like water throughout #Belie\u2026", - "contenttype": "text/plain", - "created": 1445225008000, - "id": "655947345197076480", - "language": "en" - }, - { - "content": "RT @iamtikasumpter: #Belief had me in awe. Faith in the divine is the constant that links us together. It's all beautiful and righteous. Gi\u2026", - "contenttype": "text/plain", - "created": 1445224852000, - "id": "655946689249828864", - "language": "en" - }, - { - "content": "West Coast... Here we go. #Belief", - "contenttype": "text/plain", - "created": 1445224140000, - "id": "655943701840048128", - "language": "en" - }, - { - "content": "Big surprise at icanady watch party. Epic night. #Belief. So much more to come. https:\/\/t.co\/kBDtFwGyQs", - "contenttype": "text/plain", - "created": 1445220694000, - "id": "655929249669378048", - "language": "en" - }, - { - "content": "I loved the Mendel story so much because it represents right of passasge. \" bye bye to childhood\".#Belief", - "contenttype": "text/plain", - "created": 1445215032000, - "id": "655905500056391682", - "language": "en" - }, - { - "content": "RT @squee_machine: This is a visual feast! Completely gorgeous and I am transfixed. The colors, the composition, cinematography, vibe. #Bel\u2026", - "contenttype": "text/plain", - "created": 1445214538000, - "id": "655903432079904768", - "language": "en" - }, - { - "content": "RT @JamesTyphany: Looking at @ #Belief I really needed this in my life thanks @OWNTV", - "contenttype": "text/plain", - "created": 1445214534000, - "id": "655903413385891840", - "language": "en" - }, - { - "content": "Just surprised a \"watch party\" @icanady 's house. #Belief http:\/\/t.co\/Di0I3OooCh", - "contenttype": "text/plain", - "created": 1445214502000, - "id": "655903277796732931", - "language": "en" - }, - { - "content": "RT @MsLaWandaa: I love moments of sitting among elders and learning. I can feel this moment was special for @ReshThakkar #Belief", - "contenttype": "text/plain", - "created": 1445214498000, - "id": "655903264374812672", - "language": "en" - }, - { - "content": "RT @xonecole: \"Do you have to have religion or is being a good person...is that enough?\" #Belief", - "contenttype": "text/plain", - "created": 1445214339000, - "id": "655902594171203584", - "language": "en" - }, - { - "content": "RT @ChivonJohn: Very inspired by the stories on #belief https:\/\/t.co\/uMRCCfCWcY", - "contenttype": "text/plain", - "created": 1445214327000, - "id": "655902545903140864", - "language": "en" - }, - { - "content": "RT @KiranSArora: powerful personal story that many of us can connect to. searching for what's missing, spiritual liberation. @ReshThakkar #\u2026", - "contenttype": "text/plain", - "created": 1445214128000, - "id": "655901708506103812", - "language": "en" - }, - { - "content": "RT @createdbyerica: \"I'm willing to go as far as I have to go to get that feeling in my heart of being connected to the Divine.\" - Reshma @\u2026", - "contenttype": "text/plain", - "created": 1445213967000, - "id": "655901033952993280", - "language": "en" - }, - { - "content": "RT @UrbnHealthNP: I am enjoying this so much. #Belief", - "contenttype": "text/plain", - "created": 1445213904000, - "id": "655900772467474435", - "language": "en" - }, - { - "content": "RT @DrMABrown: Your relationship with #belief can be completely different than how others experience it", - "contenttype": "text/plain", - "created": 1445213901000, - "id": "655900756604620800", - "language": "en" - }, - { - "content": "RT @ckerfin: On another river on the other side of the world... transition between stories, drawing connections to different beliefs #Belie\u2026", - "contenttype": "text/plain", - "created": 1445213721000, - "id": "655900002644987905", - "language": "en" - }, - { - "content": "RT @nikfarrior: So profound. We are all born into #Belief @Oprah @OWN @OWNTV", - "contenttype": "text/plain", - "created": 1445213706000, - "id": "655899942242775040", - "language": "en" - }, - { - "content": "RT @fgaboys: @Oprah the start of #Belief is riveting and edifying. It makes you want more and inspires you too see what's coming up next. \u2026", - "contenttype": "text/plain", - "created": 1445213699000, - "id": "655899910563217408", - "language": "en" - }, - { - "content": "RT @MalikaGhosh: Here we GO- let's lose ourselves #belief NOW @Oprah JOY http:\/\/t.co\/vYSNLd3LvC", - "contenttype": "text/plain", - "created": 1445212831000, - "id": "655896269542420480", - "language": "en" - }, - { - "content": "RT @MastinKipp: .@Oprah and team are about to bring the Light with #Belief.", - "contenttype": "text/plain", - "created": 1445212747000, - "id": "655895916675600384", - "language": "en" - }, - { - "content": "RT @GrowingOWN: 7 minutes, y'all! #BELIEF", - "contenttype": "text/plain", - "created": 1445212465000, - "id": "655894734968217600", - "language": "en" - }, - { - "content": "RT @LPToussaint: BELIEF defines experience.Choose wisely #Belief Tonight on OWN", - "contenttype": "text/plain", - "created": 1445211845000, - "id": "655892134524878848", - "language": "en" - }, - { - "content": "RT @TheBeBeWinans: Congratulations to my dear friend @Oprah on the launch of your series #BELIEF #Tonight on @OWNTV. Your friendship inspir\u2026", - "contenttype": "text/plain", - "created": 1445211835000, - "id": "655892094905532416", - "language": "en" - }, - { - "content": "RT @UzoAduba: Thirty minutes to @Oprah #Belief. Pretty sure it's about to be our favorite thing.", - "contenttype": "text/plain", - "created": 1445211833000, - "id": "655892084314890240", - "language": "en" - }, - { - "content": "RT @DeandresVoice: Moments away from the start of @SuperSoulSunday and the first night of the epic #Belief series on @OWNTV - are you ready\u2026", - "contenttype": "text/plain", - "created": 1445209201000, - "id": "655881046102142978", - "language": "en" - }, - { - "content": "RT @jennaldewan: I CANT WAIT FOR THIS TONIGHT!!!!!! Got my popcorn, got my tissues I am readyyyyyy! #Belief https:\/\/t.co\/WluTdeEqal", - "contenttype": "text/plain", - "created": 1445209181000, - "id": "655880959535939584", - "language": "en" - }, - { - "content": "RT @indiaarie: U heard about @Oprah passion project? It's called #Belief - I've see some & Its special! Tonight - 7c\/8e - 7 nights!! Whose\u2026", - "contenttype": "text/plain", - "created": 1445208945000, - "id": "655879970732949504", - "language": "en" - }, - { - "content": "Wow, I liked @TheRock before, now I really SEE how special he is. The daughter story was IT for me. So great! #MasterClass", - "contenttype": "text/plain", - "created": 1447639154000, - "id": "666073008692314113", - "language": "en" - }, - { - "content": ".@TheRock how did you Know to listen to your gut and Not go back to football? #Masterclass", - "contenttype": "text/plain", - "created": 1447638226000, - "id": "666069114889179136", - "language": "en" - }, - { - "content": ".@TheRock moving back in with your parents so humbling. \" on the other side of your pain is something good if you can hold on\" #masterclass", - "contenttype": "text/plain", - "created": 1447638067000, - "id": "666068446325665792", - "language": "en" - }, - { - "content": "Wow aren't you loving @TheRock and his candor? #Masterclass", - "contenttype": "text/plain", - "created": 1447637459000, - "id": "666065895932973057", - "language": "en" - }, - { - "content": "RT @patt_t: @TheRock @Oprah @RichOnOWN @OWNTV this interview makes me like you as a fellow human even more for being so real.", - "contenttype": "text/plain", - "created": 1447637030000, - "id": "666064097562247168", - "language": "en" - }, - { - "content": "\"Be You\".. That's the best advice ever @TheRock #MastersClass", - "contenttype": "text/plain", - "created": 1447636205000, - "id": "666060637181644800", - "language": "en" - }, - { - "content": "Supersoulers let's lift our spirits pray and hold Paris in the Light\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1447602477000, - "id": "665919171062927360", - "language": "en" - }, - { - "content": "RT @DeepakChopra: What I learned in week 1: Become What You Believe 21-Day Meditation Experience - https:\/\/t.co\/kqaMaMqEUp #GoogleAlerts", - "contenttype": "text/plain", - "created": 1447098990000, - "id": "663807393063538688", - "language": "en" - }, - { - "content": "Watching Bryan Stevenson on #SuperSoulSunday! \"You are not the worst mistake you ever made\".\nAren't we glad about that.", - "contenttype": "text/plain", - "created": 1446998643000, - "id": "663386507856736257", - "language": "en" - }, - { - "content": ".@CherylStrayed BRAVE ENOUGH my new favorite thing! Gonna buy a copy for all my girls. #Perfectgift https:\/\/t.co\/gz1tnv8t8K", - "contenttype": "text/plain", - "created": 1446915955000, - "id": "663039689360695296", - "language": "en" - }, - { - "content": "Stevie Wonder singing \"Happy Birthday to you!\" to my dear mariashriver. A phenomenal woman and\u2026 https:\/\/t.co\/Ygm5eDIs4f", - "contenttype": "text/plain", - "created": 1446881193000, - "id": "662893888080879616", - "language": "en" - }, - { - "content": "It\u2019s my faaaaavorite time of the Year! For the first time you can shop the list on @amazon! https:\/\/t.co\/a6GMvVrhjN https:\/\/t.co\/sJlQMROq5U", - "contenttype": "text/plain", - "created": 1446744186000, - "id": "662319239844380672", - "language": "en" - }, - { - "content": "Incredible story \"the spirit of the Lord is on you\" thanks for sharing @smokey_robinson #Masterclass", - "contenttype": "text/plain", - "created": 1446428929000, - "id": "660996956861280256", - "language": "en" - }, - { - "content": "Wasnt that incredible story about @smokey_robinson 's dad leaving his family at 12. #MasterClass", - "contenttype": "text/plain", - "created": 1446426630000, - "id": "660987310889041920", - "language": "en" - }, - { - "content": "Gayle, Charlie, Nora @CBSThisMorning Congratulations! #1000thshow", - "contenttype": "text/plain", - "created": 1446220097000, - "id": "660121050978611205", - "language": "en" - }, - { - "content": "I believe your home should rise up to meet you. @TheEllenShow you nailed it with HOME. Tweethearts, grab a copy! https:\/\/t.co\/iFMnpRAsno", - "contenttype": "text/plain", - "created": 1446074433000, - "id": "659510090748182528", - "language": "en" - }, - { - "content": "Can I get a Witness?!\u270b\ud83c\udffe https:\/\/t.co\/tZ1QyAeSdE", - "contenttype": "text/plain", - "created": 1445821114000, - "id": "658447593865945089", - "language": "en" - }, - { - "content": ".@TheEllenShow you're a treasure.\nYour truth set a lot of people free.\n#Masterclass", - "contenttype": "text/plain", - "created": 1445821003000, - "id": "658447130026188800", - "language": "en" - }, - { - "content": "Hope you all are enjoying @TheEllenShow on #MasterClass.", - "contenttype": "text/plain", - "created": 1445820161000, - "id": "658443598313181188", - "language": "en" - }, - { - "content": ".@GloriaSteinem, shero to women everywhere, on how far we\u2019ve come and how far we need to go. #SuperSoulSunday 7p\/6c.\nhttps:\/\/t.co\/3e7oxXW02J", - "contenttype": "text/plain", - "created": 1445811545000, - "id": "658407457438363648", - "language": "en" - }, - { - "content": "RT @TheEllenShow: I told a story from my @OWNTV's #MasterClass on my show. Normally I\u2019d save it all for Sunday, but @Oprah made me. https:\/\u2026", - "contenttype": "text/plain", - "created": 1445804181000, - "id": "658376572521459712", - "language": "en" - }, - { - "content": ".@TheEllenShow is a master teacher of living her truth & living authentically as herself. #MasterClass tonight 8\/7c.\nhttps:\/\/t.co\/iLT2KgRsSw", - "contenttype": "text/plain", - "created": 1445804072000, - "id": "658376116575449088", - "language": "en" - }, - { - "content": ".@SheriSalata , @jonnysinc @part2pictures . Tears of joy and gratitude to you and our entire #BeliefTeam We DID IT!! My heart is full.\ud83d\ude4f\ud83c\udffe\ud83d\ude4f\ud83c\udffe", - "contenttype": "text/plain", - "created": 1445734755000, - "id": "658085377140363264", - "language": "en" - }, - { - "content": "Donna and Bob saw the tape of their story just days before she passed. They appreciated it. #RIPDonna", - "contenttype": "text/plain", - "created": 1445734097000, - "id": "658082618819280896", - "language": "en" - }, - { - "content": "RT @rempower: .@Oprah this series allowed me to slide into people's lives around the world and see the same in them ... we all have a belie\u2026", - "contenttype": "text/plain", - "created": 1445732769000, - "id": "658077046858383360", - "language": "en" - }, - { - "content": "All the stories moved me, My favorite line \" I must pass the stories on to my grandson otherwise our people will loose their way. #Belief", - "contenttype": "text/plain", - "created": 1445732579000, - "id": "658076253618991104", - "language": "en" - }, - { - "content": ".@part2pictures some of your best imagery yet. Filming Alex on the rock.#Belief", - "contenttype": "text/plain", - "created": 1445731782000, - "id": "658072908237934592", - "language": "en" - }, - { - "content": "I just love Alex and his daring #Belief to live fully the present Moment.", - "contenttype": "text/plain", - "created": 1445731561000, - "id": "658071980982206464", - "language": "en" - }, - { - "content": "RT @GrowingOWN: Let's do this! #Belief finale tweet tweet party. Thank you @Oprah! \ud83d\ude4f", - "contenttype": "text/plain", - "created": 1445731248000, - "id": "658070668785770496", - "language": "en" - }, - { - "content": "RT @lizkinnell: The epic finale of #Belief on @OWNTV is about to start. 8\/et Are you ready? What do you Believe?", - "contenttype": "text/plain", - "created": 1445731081000, - "id": "658069968534171648", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night of Belief. Belief runs all day tomorrow for bingers and final episode!", - "contenttype": "text/plain", - "created": 1445648630000, - "id": "657724143115202560", - "language": "en" - }, - { - "content": "RT @OWNingLight: #Belief is the ultimate travel map to mass acceptance. \ud83d\ude4f\ud83c\udffb\u2764\ufe0f\ud83c\udf0d @Oprah", - "contenttype": "text/plain", - "created": 1445647285000, - "id": "657718501147197442", - "language": "en" - }, - { - "content": "\" I can feel my heart opening and faith coming back in\".. What's better than that? #Belief", - "contenttype": "text/plain", - "created": 1445646903000, - "id": "657716901951369218", - "language": "en" - }, - { - "content": "Hey Belief team mates can yo believe how quickly the week has passed? #Belief", - "contenttype": "text/plain", - "created": 1445645633000, - "id": "657711572492533760", - "language": "en" - }, - { - "content": "Ran into @5SOS backstage. Fun times with @TheEllenShow today! https:\/\/t.co\/2PP3W3RzXc", - "contenttype": "text/plain", - "created": 1445618531000, - "id": "657597898394173440", - "language": "en" - }, - { - "content": "Thanks All for another great night of #BELIEF", - "contenttype": "text/plain", - "created": 1445572548000, - "id": "657405031822430208", - "language": "en" - }, - { - "content": "RT @3LWTV: #BecomeWhatYouBelieve New meditation w\/ @Oprah @DeepakChopra begins 11\/2 Register https:\/\/t.co\/x0R9HWTAX0 #Belief https:\/\/t.co\/\u2026", - "contenttype": "text/plain", - "created": 1445571500000, - "id": "657400636745510912", - "language": "en" - }, - { - "content": "Ok west coast let's do it! #belief", - "contenttype": "text/plain", - "created": 1445569367000, - "id": "657391689439404033", - "language": "en" - }, - { - "content": "Thank u kind gentleman who told me I had kale in my teeth. Was eating kale chips with Quincy Jones. Went straight to @LairdLife party.", - "contenttype": "text/plain", - "created": 1445569296000, - "id": "657391393883619328", - "language": "en" - }, - { - "content": "Hello west coast twitterati.. See you at 8 for #Belief", - "contenttype": "text/plain", - "created": 1445566144000, - "id": "657378171872874496", - "language": "en" - }, - { - "content": "Thank you all for another beautiful night.#Belief", - "contenttype": "text/plain", - "created": 1445475948000, - "id": "656999861254918145", - "language": "en" - }, - { - "content": "RT @PRanganathan: \"Transformation is the rule of the game. The universe is not standing still.\" - Marcelo @OWNTV @Oprah #Belief", - "contenttype": "text/plain", - "created": 1445475602000, - "id": "656998409933451264", - "language": "en" - }, - { - "content": "\"The Universe is not standing still.. The whole Universe is expanding\" I love the dance between science and spirituality! #Belief", - "contenttype": "text/plain", - "created": 1445475580000, - "id": "656998320133398528", - "language": "en" - }, - { - "content": "\"Without our prayers and our songs we won't be here\" Apache leader.#Belief", - "contenttype": "text/plain", - "created": 1445473768000, - "id": "656990717504393216", - "language": "en" - }, - { - "content": "Notice her mother crying. She knows its last tine she will ever see her daughter.#Belief", - "contenttype": "text/plain", - "created": 1445473150000, - "id": "656988127433637888", - "language": "en" - }, - { - "content": "This final trial is unbelievable. Every hair gets pulled from her head one at a time. Now that is Something!!#Belief", - "contenttype": "text/plain", - "created": 1445473063000, - "id": "656987763644891136", - "language": "en" - }, - { - "content": "\"What my faith gives me no one can match\"#Belief", - "contenttype": "text/plain", - "created": 1445472961000, - "id": "656987336266223616", - "language": "en" - }, - { - "content": "It's a devotion to faith beyond anything Ive seen. Fascinating.Jain nuns. #Belief", - "contenttype": "text/plain", - "created": 1445472531000, - "id": "656985529951522816", - "language": "en" - }, - { - "content": "I'd never heard of Jain monks and nuns before doing this series. #Belief", - "contenttype": "text/plain", - "created": 1445472393000, - "id": "656984953037586433", - "language": "en" - }, - { - "content": "Good evening Team #Belief the Tweet is on!", - "contenttype": "text/plain", - "created": 1445472098000, - "id": "656983714883239937", - "language": "en" - }, - { - "content": "Thanks everyone for another Epic #Belief night!", - "contenttype": "text/plain", - "created": 1445302792000, - "id": "656273592485810176", - "language": "en" - } - ] -} diff --git a/resources/personality-v3.txt b/resources/personality-v3.txt deleted file mode 100644 index b11508a4e..000000000 --- a/resources/personality-v3.txt +++ /dev/null @@ -1,137 +0,0 @@ -Vice President Johnson, Mr. Speaker, Mr. Chief Justice, President Eisenhower, -Vice President Nixon, President Truman, Reverend Clergy, fellow citizens: - -We observe today not a victory of party but a celebration of freedom -- -symbolizing an end as well as a beginning -- signifying renewal as well as -change. For I have sworn before you and Almighty God the same solemn oath our -forbears prescribed nearly a century and three-quarters ago. - -The world is very different now. For man holds in his mortal hands the power -to abolish all forms of human poverty and all forms of human life. And yet -the same revolutionary beliefs for which our forebears fought are still at -issue around the globe -- the belief that the rights of man come not from the -generosity of the state but from the hand of God. - -We dare not forget today that we are the heirs of that first revolution. Let -the word go forth from this time and place, to friend and foe alike, that the -torch has been passed to a new generation of Americans -- born in this century, -tempered by war, disciplined by a hard and bitter peace, proud of our ancient -heritage -- and unwilling to witness or permit the slow undoing of those human -rights to which this nation has always been committed, and to which we are -committed today at home and around the world. - -Let every nation know, whether it wishes us well or ill, that we shall pay -any price, bear any burden, meet any hardship, support any friend, oppose -any foe to assure the survival and the success of liberty. - -This much we pledge -- and more. - -To those old allies whose cultural and spiritual origins we share, we pledge -the loyalty of faithful friends. United there is little we cannot do in a host -of cooperative ventures. Divided there is little we can do -- for we dare not -meet a powerful challenge at odds and split asunder. - -To those new states whom we welcome to the ranks of the free, we pledge our -word that one form of colonial control shall not have passed away merely to -be replaced by a far more iron tyranny. We shall not always expect to find -them supporting our view. But we shall always hope to find them strongly -supporting their own freedom -- and to remember that, in the past, those who -foolishly sought power by riding the back of the tiger ended up inside. - -To those people in the huts and villages of half the globe struggling to -break the bonds of mass misery, we pledge our best efforts to help them help -themselves, for whatever period is required -- not because the communists may -be doing it, not because we seek their votes, but because it is right. If a -free society cannot help the many who are poor, it cannot save the few who -are rich. - -To our sister republics south of our border, we offer a special pledge -- to -convert our good words into good deeds -- in a new alliance for progress -- -to assist free men and free governments in casting off the chains of poverty. -But this peaceful revolution of hope cannot become the prey of hostile powers. -Let all our neighbors know that we shall join with them to oppose aggression -or subversion anywhere in the Americas. And let every other power know that -this Hemisphere intends to remain the master of its own house. - -To that world assembly of sovereign states, the United Nations, our last best -hope in an age where the instruments of war have far outpaced the instruments -of peace, we renew our pledge of support -- to prevent it from becoming merely -a forum for invective -- to strengthen its shield of the new and the weak -- -and to enlarge the area in which its writ may run. - -Finally, to those nations who would make themselves our adversary, we offer -not a pledge but a request: that both sides begin anew the quest for peace, -before the dark powers of destruction unleashed by science engulf all humanity -in planned or accidental self-destruction. - -We dare not tempt them with weakness. For only when our arms are sufficient -beyond doubt can we be certain beyond doubt that they will never be employed. - -But neither can two great and powerful groups of nations take comfort from -our present course -- both sides overburdened by the cost of modern weapons, -both rightly alarmed by the steady spread of the deadly atom, yet both racing -to alter that uncertain balance of terror that stays the hand of mankind's -final war. - -So let us begin anew -- remembering on both sides that civility is not a sign -of weakness, and sincerity is always subject to proof. Let us never negotiate -out of fear. But let us never fear to negotiate. - -Let both sides explore what problems unite us instead of belaboring those -problems which divide us. - -Let both sides, for the first time, formulate serious and precise proposals -for the inspection and control of arms -- and bring the absolute power to -destroy other nations under the absolute control of all nations. - -Let both sides seek to invoke the wonders of science instead of its terrors. -Together let us explore the stars, conquer the deserts, eradicate disease, -tap the ocean depths and encourage the arts and commerce. - -Let both sides unite to heed in all corners of the earth the command of -Isaiah -- to "undo the heavy burdens ... (and) let the oppressed go free." - -And if a beachhead of cooperation may push back the jungle of suspicion, let -both sides join in creating a new endeavor, not a new balance of power, but -a new world of law, where the strong are just and the weak secure and the -peace preserved. - -All this will not be finished in the first one hundred days. Nor will it be -finished in the first one thousand days, nor in the life of this -Administration, nor even perhaps in our lifetime on this planet. But let us -begin. - -In your hands, my fellow citizens, more than mine, will rest the final success -or failure of our course. Since this country was founded, each generation of -Americans has been summoned to give testimony to its national loyalty. The -graves of young Americans who answered the call to service surround the globe. - -Now the trumpet summons us again -- not as a call to bear arms, though arms we -need -- not as a call to battle, though embattled we are -- but a call to bear -the burden of a long twilight struggle, year in and year out, "rejoicing in -hope, patient in tribulation" -- a struggle against the common enemies of man: -tyranny, poverty, disease and war itself. - -Can we forge against these enemies a grand and global alliance, North and -South, East and West, that can assure a more fruitful life for all mankind? -Will you join in that historic effort? - -In the long history of the world, only a few generations have been granted -the role of defending freedom in its hour of maximum danger. I do not shrink -from this responsibility -- I welcome it. I do not believe that any of us -would exchange places with any other people or any other generation. The -energy, the faith, the devotion which we bring to this endeavor will light -our country and all who serve it -- and the glow from that fire can truly -light the world. - -And so, my fellow Americans: ask not what your country can do for you -- ask -what you can do for your country. - -My fellow citizens of the world: ask not what America will do for you, but -what together we can do for the freedom of man. - -Finally, whether you are citizens of America or citizens of the world, ask of -us here the same high standards of strength and sacrifice which we ask of you. -With a good conscience our only sure reward, with history the final judge of -our deeds, let us go forth to lead the land we love, asking His blessing and -His help, but knowing that here on earth God's work must truly be our own. diff --git a/resources/personality.es.txt b/resources/personality.es.txt deleted file mode 100644 index 950fdb28e..000000000 --- a/resources/personality.es.txt +++ /dev/null @@ -1,13 +0,0 @@ -En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lantejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas, con sus pantuflos de lo mesmo, y los días de entresemana se honraba con su vellorí de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años; era de complexión recia, seco de carnes, enjuto de rostro, gran madrugador y amigo de la caza. Quieren decir que tenía el sobrenombre de Quijada, o Quesada, que en esto hay alguna diferencia en los autores que deste caso escriben; aunque, por conjeturas verosímiles, se deja entender que se llamaba Quejana. Pero esto importa poco a nuestro cuento; basta que en la narración dél no se salga un punto de la verdad. -Es, pues, de saber que este sobredicho hidalgo, los ratos que estaba ocioso, que eran los más del año, se daba a leer libros de caballerías, con tanta afición y gusto, que olvidó casi de todo punto el ejercicio de la caza, y aun la administración de su hacienda. Y llegó a tanto su curiosidad y desatino en esto, que vendió muchas hanegas de tierra de sembradura para comprar libros de caballerías en que leer, y así, llevó a su casa todos cuantos pudo haber dellos; y de todos, ningunos le parecían tan bien como los que compuso el famoso Feliciano de Silva, porque la claridad de su prosa y aquellas entricadas razones suyas le parecían de perlas, y más cuando llegaba a leer aquellos requiebros y cartas de desafíos, donde en muchas partes hallaba escrito: La razón de la sinrazón que a mi razón se hace, de tal manera mi razón enflaquece, que con razón me quejo de la vuestra fermosura. Y también cuando leía: ...los altos cielos que de vuestra divinidad divinamente con las estrellas os fortifican, y os hacen merecedora del merecimiento que merece la vuestra grandeza. -Con estas razones perdía el pobre caballero el juicio, y desvelábase por entenderlas y desentrañarles el sentido, que no se lo sacara ni las entendiera el mesmo Aristóteles, si resucitara para sólo ello. No estaba muy bien con las heridas que don Belianís daba y recebía, porque se imaginaba que, por grandes maestros que le hubiesen curado, no dejaría de tener el rostro y todo el cuerpo lleno de cicatrices y señales. Pero, con todo, alababa en su autor aquel acabar su libro con la promesa de aquella inacabable aventura, y muchas veces le vino deseo de tomar la pluma y dalle fin al pie de la letra, como allí se promete; y sin duda alguna lo hiciera, y aun saliera con ello, si otros mayores y continuos pensamientos no se lo estorbaran. Tuvo muchas veces competencia con el cura de su lugar —que era hombre docto, graduado en Sigüenza—, sobre cuál había sido mejor caballero: Palmerín de Ingalaterra o Amadís de Gaula; mas maese Nicolás, barbero del mesmo pueblo, decía que ninguno llegaba al Caballero del Febo, y que si alguno se le podía comparar, era don Galaor, hermano de Amadís de Gaula, porque tenía muy acomodada condición para todo; que no era caballero melindroso, ni tan llorón como su hermano, y que en lo de la valentía no le iba en zaga. -En resolución, él se enfrascó tanto en su letura, que se le pasaban las noches leyendo de claro en claro, y los días de turbio en turbio; y así, del poco dormir y del mucho leer, se le secó el celebro, de manera que vino a perder el juicio. Llenósele la fantasía de todo aquello que leía en los libros, así de encantamentos como de pendencias, batallas, desafíos, heridas, requiebros, amores, tormentas y disparates imposibles; y asentósele de tal modo en la imaginación que era verdad toda aquella máquina de aquellas sonadas soñadas invenciones que leía, que para él no había otra historia más cierta en el mundo. Decía él que el Cid Ruy Díaz había sido muy buen caballero, pero que no tenía que ver con el Caballero de la Ardiente Espada, que de sólo un revés había partido por medio dos fieros y descomunales gigantes. Mejor estaba con Bernardo del Carpio, porque en Roncesvalles había muerto a Roldán el encantado, valiéndose de la industria de Hércules, cuando ahogó a Anteo, el hijo de la Tierra, entre los brazos. Decía mucho bien del gigante Morgante, porque, con ser de aquella generación gigantea, que todos son soberbios y descomedidos, él solo era afable y bien criado. Pero, sobre todos, estaba bien con Reinaldos de Montalbán, y más cuando le veía salir de su castillo y robar cuantos topaba, y cuando en allende robó aquel ídolo de Mahoma que era todo de oro, según dice su historia. Diera él, por dar una mano de coces al traidor de Galalón, al ama que tenía, y aun a su sobrina de añadidura. -En efeto, rematado ya su juicio, vino a dar en el más estraño pensamiento que jamás dio loco en el mundo; y fue que le pareció convenible y necesario, así para el aumento de su honra como para el servicio de su república, hacerse caballero andante, y irse por todo el mundo con sus armas y caballo a buscar las aventuras y a ejercitarse en todo aquello que él había leído que los caballeros andantes se ejercitaban, deshaciendo todo género de agravio, y poniéndose en ocasiones y peligros donde, acabándolos, cobrase eterno nombre y fama. Imaginábase el pobre ya coronado por el valor de su brazo, por lo menos, del imperio de Trapisonda; y así, con estos tan agradables pensamientos, llevado del estraño gusto que en ellos sentía, se dio priesa a poner en efeto lo que deseaba. -Y lo primero que hizo fue limpiar unas armas que habían sido de sus bisabuelos, que, tomadas de orín y llenas de moho, luengos siglos había que estaban puestas y olvidadas en un rincón. Limpiólas y aderezólas lo mejor que pudo, pero vio que tenían una gran falta, y era que no tenían celada de encaje, sino morrión simple; mas a esto suplió su industria, porque de cartones hizo un modo de media celada, que, encajada con el morrión, hacían una apariencia de celada entera. Es verdad que para probar si era fuerte y podía estar al riesgo de una cuchillada, sacó su espada y le dio dos golpes, y con el primero y en un punto deshizo lo que había hecho en una semana; y no dejó de parecerle mal la facilidad con que la había hecho pedazos, y, por asegurarse deste peligro, la tornó a hacer de nuevo, poniéndole unas barras de hierro por de dentro, de tal manera que él quedó satisfecho de su fortaleza; y, sin querer hacer nueva experiencia della, la diputó y tuvo por celada finísima de encaje. -Fue luego a ver su rocín, y, aunque tenía más cuartos que un real y más tachas que el caballo de Gonela, que tantum pellis et ossa fuit, le pareció que ni el Bucéfalo de Alejandro ni Babieca el del Cid con él se igualaban. Cuatro días se le pasaron en imaginar qué nombre le pondría; porque, según se decía él a sí mesmo, no era razón que caballo de caballero tan famoso, y tan bueno él por sí, estuviese sin nombre conocido; y ansí, procuraba acomodársele de manera que declarase quién había sido, antes que fuese de caballero andante, y lo que era entonces; pues estaba muy puesto en razón que, mudando su señor estado, mudase él también el nombre, y le cobrase famoso y de estruendo, como convenía a la nueva orden y al nuevo ejercicio que ya profesaba. Y así, después de muchos nombres que formó, borró y quitó, añadió, deshizo y tornó a hacer en su memoria e imaginación, al fin le vino a llamar Rocinante: nombre, a su parecer, alto, sonoro y significativo de lo que había sido cuando fue rocín, antes de lo que ahora era, que era antes y primero de todos los rocines del mundo. -Puesto nombre, y tan a su gusto, a su caballo, quiso ponérsele a sí mismo, y en este pensamiento duró otros ocho días, y al cabo se vino a llamar don Quijote; de donde —como queda dicho— tomaron ocasión los autores desta tan verdadera historia que, sin duda, se debía de llamar Quijada, y no Quesada, como otros quisieron decir. Pero, acordándose que el valeroso Amadís no sólo se había contentado con llamarse Amadís a secas, sino que añadió el nombre de su reino y patria, por Hepila famosa, y se llamó Amadís de Gaula, así quiso, como buen caballero, añadir al suyo el nombre de la suya y llamarse don Quijote de la Mancha, con que, a su parecer, declaraba muy al vivo su linaje y patria, y la honraba con tomar el sobrenombre della. -Limpias, pues, sus armas, hecho del morrión celada, puesto nombre a su rocín y confirmándose a sí mismo, se dio a entender que no le faltaba otra cosa sino buscar una dama de quien enamorarse; porque el caballero andante sin amores era árbol sin hojas y sin fruto y cuerpo sin alma. Decíase él a sí: -— Si yo, por malos de mis pecados, o por mi buena suerte, me encuentro por ahí con algún gigante, como de ordinario les acontece a los caballeros andantes, y le derribo de un encuentro, o le parto por mitad del cuerpo, o, finalmente, le venzo y le rindo, ¿no será bien tener a quien enviarle presentado y que entre y se hinque de rodillas ante mi dulce señora, y diga con voz humilde y rendido: ''Yo, señora, soy el gigante Caraculiambro, señor de la ínsula Malindrania, a quien venció en singular batalla el jamás como se debe alabado caballero don Quijote de la Mancha, el cual me mandó que me presentase ante vuestra merced, para que la vuestra grandeza disponga de mí a su talante''? -¡Oh, cómo se holgó nuestro buen caballero cuando hubo hecho este discurso, y más cuando halló a quien dar nombre de su dama! Y fue, a lo que se cree, que en un lugar cerca del suyo había una moza labradora de muy buen parecer, de quien él un tiempo anduvo enamorado, aunque, según se entiende, ella jamás lo supo, ni le dio cata dello. Llamábase Aldonza Lorenzo, y a ésta le pareció ser bien darle título de señora de sus pensamientos; y, buscándole nombre que no desdijese mucho del suyo, y que tirase y se encaminase al de princesa y gran señora, vino a llamarla Dulcinea del Toboso, porque era natural del Toboso; nombre, a su parecer, músico y peregrino y significativo, como todos los demás que a él y a sus cosas había puesto. - - diff --git a/resources/personality.txt b/resources/personality.txt deleted file mode 100644 index 9bdd68266..000000000 --- a/resources/personality.txt +++ /dev/null @@ -1,15 +0,0 @@ -Call me Ishmael. Some years ago-never mind how long precisely-having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off-then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me. -There now is your insular city of the Manhattoes, belted round by wharves as Indian isles by coral reefs-commerce surrounds it with her surf. Right and left, the streets take you waterward. Its extreme downtown is the battery, where that noble mole is washed by waves, and cooled by breezes, which a few hours previous were out of sight of land. Look at the crowds of water-gazers there. -Circumambulate the city of a dreamy Sabbath afternoon. Go from Corlears Hook to Coenties Slip, and from thence, by Whitehall, northward. What do you see?-Posted like silent sentinels all around the town, stand thousands upon thousands of mortal men fixed in ocean reveries. Some leaning against the spiles; some seated upon the pier-heads; some looking over the bulwarks of ships from China; some high aloft in the rigging, as if striving to get a still better seaward peep. But these are all landsmen; of week days pent up in lath and plaster-tied to counters, nailed to benches, clinched to desks. How then is this? Are the green fields gone? What do they here? -But look! here come more crowds, pacing straight for the water, and seemingly bound for a dive. Strange! Nothing will content them but the extremest limit of the land; loitering under the shady lee of yonder warehouses will not suffice. No. They must get just as nigh the water as they possibly can without falling in. And there they stand-miles of them-leagues. Inlanders all, they come from lanes and alleys, streets and avenues-north, east, south, and west. Yet here they all unite. Tell me, does the magnetic virtue of the needles of the compasses of all those ships attract them thither? -Once more. Say you are in the country; in some high land of lakes. Take almost any path you please, and ten to one it carries you down in a dale, and leaves you there by a pool in the stream. There is magic in it. Let the most absent-minded of men be plunged in his deepest reveries-stand that man on his legs, set his feet a-going, and he will infallibly lead you to water, if water there be in all that region. Should you ever be athirst in the great American desert, try this experiment, if your caravan happen to be supplied with a metaphysical professor. Yes, as every one knows, meditation and water are wedded for ever. -But here is an artist. He desires to paint you the dreamiest, shadiest, quietest, most enchanting bit of romantic landscape in all the valley of the Saco. What is the chief element he employs? There stand his trees, each with a hollow trunk, as if a hermit and a crucifix were within; and here sleeps his meadow, and there sleep his cattle; and up from yonder cottage goes a sleepy smoke. Deep into distant woodlands winds a mazy way, reaching to overlapping spurs of mountains bathed in their hill-side blue. But though the picture lies thus tranced, and though this pine-tree shakes down its sighs like leaves upon this shepherd's head, yet all were vain, unless the shepherd's eye were fixed upon the magic stream before him. Go visit the Prairies in June, when for scores on scores of miles you wade knee-deep among Tiger-lilies-what is the one charm wanting?-Water-there is not a drop of water there! Were Niagara but a cataract of sand, would you travel your thousand miles to see it? Why did the poor poet of Tennessee, upon suddenly receiving two handfuls of silver, deliberate whether to buy him a coat, which he sadly needed, or invest his money in a pedestrian trip to Rockaway Beach? Why is almost every robust healthy boy with a robust healthy soul in him, at some time or other crazy to go to sea? Why upon your first voyage as a passenger, did you yourself feel such a mystical vibration, when first told that you and your ship were now out of sight of land? Why did the old Persians hold the sea holy? Why did the Greeks give it a separate deity, and own brother of Jove? Surely all this is not without meaning. And still deeper the meaning of that story of Narcissus, who because he could not grasp the tormenting, mild image he saw in the fountain, plunged into it and was drowned. But that same image, we ourselves see in all rivers and oceans. It is the image of the ungraspable phantom of life; and this is the key to it all. -Now, when I say that I am in the habit of going to sea whenever I begin to grow hazy about the eyes, and begin to be over conscious of my lungs, I do not mean to have it inferred that I ever go to sea as a passenger. For to go as a passenger you must needs have a purse, and a purse is but a rag unless you have something in it. Besides, passengers get sea-sick-grow quarrelsome-don't sleep of nights-do not enjoy themselves much, as a general thing;-no, I never go as a passenger; nor, though I am something of a salt, do I ever go to sea as a Commodore, or a Captain, or a Cook. I abandon the glory and distinction of such offices to those who like them. For my part, I abominate all honourable respectable toils, trials, and tribulations of every kind whatsoever. It is quite as much as I can do to take care of myself, without taking care of ships, barques, brigs, schooners, and what not. And as for going as cook,-though I confess there is considerable glory in that, a cook being a sort of officer on ship-board-yet, somehow, I never fancied broiling fowls;-though once broiled, judiciously buttered, and judgmatically salted and peppered, there is no one who will speak more respectfully, not to say reverentially, of a broiled fowl than I will. It is out of the idolatrous dotings of the old Egyptians upon broiled ibis and roasted river horse, that you see the mummies of those creatures in their huge bake-houses the pyramids. -No, when I go to sea, I go as a simple sailor, right before the mast, plumb down into the forecastle, aloft there to the royal mast-head. True, they rather order me about some, and make me jump from spar to spar, like a grasshopper in a May meadow. And at first, this sort of thing is unpleasant enough. It touches one's sense of honour, particularly if you come of an old established family in the land, the Van Rensselaers, or Randolphs, or Hardicanutes. And more than all, if just previous to putting your hand into the tar-pot, you have been lording it as a country schoolmaster, making the tallest boys stand in awe of you. The transition is a keen one, I assure you, from a schoolmaster to a sailor, and requires a strong decoction of Seneca and the Stoics to enable you to grin and bear it. But even this wears off in time. -What of it, if some old hunks of a sea-captain orders me to get a broom and sweep down the decks? What does that indignity amount to, weighed, I mean, in the scales of the New Testament? Do you think the archangel Gabriel thinks anything the less of me, because I promptly and respectfully obey that old hunks in that particular instance? Who ain't a slave? Tell me that. Well, then, however the old sea-captains may order me about-however they may thump and punch me about, I have the satisfaction of knowing that it is all right; that everybody else is one way or other served in much the same way-either in a physical or metaphysical point of view, that is; and so the universal thump is passed round, and all hands should rub each other's shoulder-blades, and be content. -Again, I always go to sea as a sailor, because they make a point of paying me for my trouble, whereas they never pay passengers a single penny that I ever heard of. On the contrary, passengers themselves must pay. And there is all the difference in the world between paying and being paid. The act of paying is perhaps the most uncomfortable infliction that the two orchard thieves entailed upon us. But BEING PAID,-what will compare with it? The urbane activity with which a man receives money is really marvellous, considering that we so earnestly believe money to be the root of all earthly ills, and that on no account can a monied man enter heaven. Ah! how cheerfully we consign ourselves to perdition! -Finally, I always go to sea as a sailor, because of the wholesome exercise and pure air of the fore-castle deck. For as in this world, head winds are far more prevalent than winds from astern (that is, if you never violate the Pythagorean maxim), so for the most part the Commodore on the quarter-deck gets his atmosphere at second hand from the sailors on the forecastle. He thinks he breathes it first; but not so. In much the same way do the commonalty lead their leaders in many other things, at the same time that the leaders little suspect it. But wherefore it was that after having repeatedly smelt the sea as a merchant sailor, I should now take it into my head to go on a whaling voyage; this the invisible police officer of the Fates, who has the constant surveillance of me, and secretly dogs me, and influences me in some unaccountable way-he can better answer than any one else. And, doubtless, my going on this whaling voyage, formed part of the grand programme of Providence that was drawn up a long time ago. It came in as a sort of brief interlude and solo between more extensive performances. I take it that this part of the bill must have run something like this: -"GRAND CONTESTED ELECTION FOR THE PRESIDENCY OF THE UNITED STATES. "WHALING VOYAGE BY ONE ISHMAEL. "BLOODY BATTLE IN AFFGHANISTAN." -Though I cannot tell why it was exactly that those stage managers, the Fates, put me down for this shabby part of a whaling voyage, when others were set down for magnificent parts in high tragedies, and short and easy parts in genteel comedies, and jolly parts in farces-though I cannot tell why this was exactly; yet, now that I recall all the circumstances, I think I can see a little into the springs and motives which being cunningly presented to me under various disguises, induced me to set about performing the part I did, besides cajoling me into the delusion that it was a choice resulting from my own unbiased freewill and discriminating judgment. -Chief among these motives was the overwhelming idea of the great whale himself. Such a portentous and mysterious monster roused all my curiosity. Then the wild and distant seas where he rolled his island bulk; the undeliverable, nameless perils of the whale; these, with all the attending marvels of a thousand Patagonian sights and sounds, helped to sway me to my wish. With other men, perhaps, such things would not have been inducements; but as for me, I am tormented with an everlasting itch for things remote. I love to sail forbidden seas, and land on barbarous coasts. Not ignoring what is good, I am quick to perceive a horror, and could still be social with it-would they let me-since it is but well to be on friendly terms with all the inmates of the place one lodges in. -By reason of these things, then, the whaling voyage was welcome; the great flood-gates of the wonder-world swung open, and in the wild conceits that swayed me to my purpose, two and two there floated into my inmost soul, endless processions of the whale, and, mid most of them all, one grand hooded phantom, like a snow hill in the air. diff --git a/resources/tone-example-html.json b/resources/tone-example-html.json deleted file mode 100755 index e663b6cfb..000000000 --- a/resources/tone-example-html.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "text": "

E+q<&0A(=-*tyRK<;!IEIip|w93;|-CfTuluSG7b^{{V{Y$24_pCcB#BLyjA% zEt5r)_=$4?Q|0G{UNB1ojQRj+B>ePJGF>y(-l=V)rk`V{TtzgC7*$o;?4enSc5&)6 z^5cRadv1b50}pmxwT4>N_?)Fn_75B$oV^yCQC4d1kSKWm#VB#A>^- z@{UP3=so?ac=cp4+?G*7lASeCELu!6u`FBx%CG%7 zDwySLvNM~6eiHMUb{)Zi^ z5>{4hr%N1v8#skYBFteZ4E2EU%+jt1e4! zHB^bEa-m@4o;vbJw*Xc=tm#lq5D`xbUd;uVW3h@WKl6M409w^Y!YJa1y;pp<1WAbo zFcv--ed=zVGnQSH?Mq0yjPDSbm7L%c(z@ZEJu?YM*yh#?r%V3;5avl4ayE_uHL}Zn zB9%u^59uv^aXZT(5hocvDw%UAQb?5>4NpUw)hD@#ZbUiXy9T2dsZ(k!hZ@-*Vzc>? z-FYi26OFC>#PbmMQ04X)NQL%TYL$jGd* z6qjT@>bhLUwy%hXbL;f3xHz=z&Dqk{?n8MK-C_Ev&p;|NMKtJ?PR?wtz?K<|&gXZR zj-G@2S0jsMiCrgMx{7hO)I1I`jQaQb(Yi#YJ85mj=av`BSKx*n{{Y#nTc@oOalf~Y zJ4sO6I7A0yDg54*G1KUVQqt1tE;As`dBJYg+}di9LdS09qF7{wNyk<{@0#U(?H3_* z>8)Df1T8d^67o&)65=ifcN`v1UcQyrkvcR@wp{Ig4YauAStFHh2b(0%+>yj%J(mQN z(>xB9$tA~3+AqpGTSpm+5@Y`Wn41E|dX7%wPXJ?_nxad|svX3T#}AWW3pA)>-bXCz zcVv^$ardaCl|;H8+vxXmLM}t0h_H;6I0!M4Pp^I|tybBhRyLl>M7Mc_Pw?j;C|HuO!xki$dH^f?&|vKyMl>$|f1gmD+L-2O#s2kEC}ZgS+Uol#xq>nyY@QaD^$FV%E=Y%FCw{^ z%%DlP19Ywn?fzZ>JaT@On@xB3X0PZ@c+DN`w20$7XLKCncmyup$F|Xy8T6}4+DUdH z_$Q zb{A#IIR}lo&N0`}RXjO2_RD$VhFbNc*M2x#w2kL3^4vz5%EVJ@s{q^<2XOZ7)~?&+ z()0a_QsS)lG>~8GFtxPD$c9i7ZTNRkq&aU`^1()MO9R+cw69zKex$2QXANp$73`5l z>lc{LKQ7>12_Z6g&O+q}|2? z>h`ea#?atJC`09U+A)mtfydwLRc%M*UgfLH94z2TlEkxy!Bf?TL+(3bp`bp7Xnq%c z(cIEB+e!S`ByG+;G6n~&D_1Y68*fKj=wX&yKbK%@RvXl?W0>)PILh#UdX|%G^8Ug; ze=(MsVHfeFgrSK^F@v0i103VmAFWm@?Us5Z+QZJciqyNeoiI=ba&x!$=M`@??nTnF zwK0O?=@H`taWPv27>$@U~Idv+{B#~P|+4E^(;`lyvZ*j<%>5ZpZa zBz89L6wjyHq>Ro(M-c&8&mCCE5CO-2ifdeJi|6fM)TGs_UsBy=X=mY!Z8{G=aiq1J z@hOpTj);oDxENsB5^Xu^!~u$jE>7Q)Vz|bafph}*R|4*PX?&<-+=4(ArFJR;f&8or zfZu#qJap~&{raNv-jLr@mhRJ3w78y84ZJZ3OEC=B8?xCaJPqr&)Z(;;slWUCWIgmX zv$mE<JfP&T0-^r1puPSQVj-M3L1}^3ni09;HkZuRIag6#@-L$>TTB0vjzG)uh z+rAcAPDai*1}XxN{h?{yvo_8a*CHm%Nc-`HV#6Tgr%IY8G9(i9oyHC^z~dOBHcXeY zxKk6BH~~lip1<$=(IU;2FBx2`>DIedOTtxHkFNm#07}yu_c`;jnG9j2AwMW=f_cqt z`5Z-yO|c7ZtjwWH42nPPxl zW-GO9$eVIdw@uvj?^7&^7g*ah55uR^G=pR{3sZM>EJT;sSb?17N2g9Z=D8fB7j$(- z5^{Uf4+k^iA z;;ds^`{=Z#TN-$N@vLp$Nv1PDlF_C=l#`Nv-k#NHYi4qqAT?JKzzl8Am~sK=6+)=~ zr2T4m+WY+ue2iq5l3;{lIx!=)N;9*x7uzHp?qEUZ>s58pWhRR%>J4z95tb)|-l@Kh zsARLWjU(GER@;_VVGxuI1t&ab+ZoLp)gyK8K1tHT+iu2dS9W>M0oxj@Dz-`E@}>v2 zYfDjILLJDDv4VEgEEeD@q=<1GvGi0{9Irs7ILF?qyeH(J$e7Zt&GPEDH`ggOz4iU9 z%1rx@!kvJpBb}H~4{%qxH7%)9UTXgUul*9fUH)TTa%pbvVpmBPdz+`#CuLpF=0zb9 zF9U&su17#4$9kC0w|jT}{{XRW6p~&k5w;CFSZYGy-^{tYYoM(dL{*tYyOa*h2?2S) zP-@bAmA|Lo>QkmVv@Lx$z%wJTf6a}fIXOO+TD=o=IEvycyXmAqI>Q+exeNlv6t6+a zInTXQl9aF5RUnKXETy~wmK%Q}7F78l!36G8#(Bsmk%88sH(!6avA(rwXFY}Nvs=2v zV{)Z4<{y=L`kZv{SESvIjjfvE&dLFD$ggb~EU1KGh{g#%gQulMwZCFe`K8$mCP3x9 zoviG*3P>FR`hih;K<5Mx9-%x|^DqJ*Dn&*GLooS94<`W`vO4CbN&Xc6{`N}uAL}>b z7!SiVSV;V(+Az+fgCX}P0YIp4+wa`1c^FO>+rxU9xQINH+uX?De9QBIyL0NGD9QJ$ z!P`~Yocd(9;Xa3^_>)M9AidKijxmXBq1_br*%&c8F*#nONIK@aGGTLRr`e2i#wpq& zFLkXK!g@W{hG6r}y~9B67;HOELC$_*>*-w7_Zqftm6V?TL#&Mpk*#Lb_QOAt9Eq|dITIA0&DocJI&7%m# z=bl*diUAuoDej{zc|A>1O<&9Tu^lavb0*uX*JTWo+(u!IWFyXC03?CV#S7P|>F-yU zZv4G{`!C#u(qDh}MCvO5)n0v3W0>69o7X!B@z=`Oqa&a%BODB8uYA(`bK39r{_K4t z`3?L*bjhX1e|p~!6fNZftAm9{U8p-QK>LwaR_VPJ($XUQGi@EbARaC-3n^d-Eze)L z6*W=%mqnR_vt3VZZlw&3DSQ+05wPP6+bX?JVN`bQrT)<#$&tQ1)xX1_v$fOhJ~nMi zcwmCuFa_C_wg6B60JPbkOjhv5vP!&mXDRVl`I*m$pn~e|*5cyey~DYR<~2M@cNUei z(B+#P4mwtuA1A+aICfhu2bVnN=VN?c78r7&QAYr7>;M3I@mW8wlT=P=lUX~#aU?FX zqcM!2x72OLhl&>Cg;TkY78ZlfEdZcv{*?B#K6t zYb~r%fDZ)ZvlHvdJXLKvpgz~^lgySEf1e0j^Jlr^88nlp^(_@@$9nF9_gA;pu)K_3TRSr@ z>}*2L+d=P*yT~2bRj>X(S~F|OSMlV7Q-)Y{#4-uWS*F3sPc__N`Va@}>0KD5#kOOW zavf+IYQtf3VQS4Fu#PJT*>FFKT*)(M-H93WRTW=RCz8e}@h*{EJkj~Vyr9y@D9G~} zHf|-e{LH8KYUY0H@BWUYCAGB6eJ!oIju`D>jS#YKf8oZfo!uDWxjwlRcgmK((k*(i zjPT=5wbNJvSVwnwT}bm2Bu5eNfy=k4$GubV!;0_8D{``XSi#lhFA_)Q&hq(dgS2^n z!}h=&pQx#t0QEo$zxnp7f7?PIhwt?nU0p12PEZpptm>)=7zZDGbu~XyAF&e!zTH2` zh=2C@Vl$9V8NRs~{b>}GXot6FjV{_qrHnadkytZ^d?+DE&rVM~d(tbWLnpLiFKq9v zT21jr!)muoV`ez@-TwgY=B67>A{i6m`zE)B-I8mVV}dB;f;M5fyr{ge?g!;LAc3B_ zJk+^zZeOq8_7zHr8Ks`vM3^GGWR!?TyQEUlmOwl5dVT7twHhs3JU*IP{s2fM5ZXoY zi0jG$yL4&?1n($#?UBxNPAUAKPv}k7{-b1?NoKY>eY}1`*(|d$To|O}fKGAGm`icS z0HrVZ`2PT8KQ>8epdX2v+%rAJ&A-gexm##;!usTrJ8(Fn{{Z=Y(LHuJzDVw7fi3PH zRgU4juP>Y?WRSV_2yvQ}t*U;1%l(LMkzBJ#f{p(cArAH~Ejqrg00N~=I zvgfN{j?Nu+@y9-uWL2Ckr;=S}-rfNi0PSYk)G)ehYxRTCa0c4PD2oH^wc@-gY16Dkb7>eXzcBANr@9~9}<4{rmt#L>hZ ziB$5BcK-m{z5T0r%Vrg9yh&-STUhHF!&^mrX?qmW?h|5vEQ1_Oh)+O@rw14WRxPKq zsV0@b%#hOcweby&_NNP6TSl(ZOCz!QSdN4b%s?FUs>wFkQu%C%)jUZisTQEpUO9rw z*l#c~hs}()3RH4QWBF=f2Pezh^f{-O!+Ieuth9TLHr8z@y}QL3NtKV7f-UZ? zQfnvqppPo8-?lUQ)~YMF;L38RquY3b^5XK=Cd_tlL=_@d1Oz;uoln-HNhvBKGGsQp z;%nNig3isI$EP)H^0^TOW!1Fs$@0&# zMNxnjx%pYY5(;YtGjDat&*ta#sk0s=m9(-f2*J0isSq!&jz;slRv9u1~QC$^Xlpb5%#P0>VrqnH$3cT*BNnd26zP}rPhtCtJ ze2u}QJQ4kmwIG~km}=0=!#2@Ch?k6@07`+$2DHhMIdUqOf>%zqw1&pz1b-piL!Y7N z>)Nu6+^)^>tq_;ile;A9vH40cGt(Sakdm#LOR^q$4b{<(HVx(VIK_0om0Kb)DeV@ zVdciy+z&ssM-@cbchNj0tR}4`_K_8g&u+qdc;jS|FD6fzs0>sD+6x?y$~gSPIV_Qv z%O~_YqmEsjKgIN`tI2O9xSHb6Pn1q>q>W+@WN$F4An&-c?E`Mnp7d~OqSs>vywr7l zINn>>-%Sh5>jY_Uxn*E??sioeLVaM8q~yHOsuW5Abs)&6AzQhUWQ)O}N109Pw4RefD0E%U{v7t&tBmcA)H_7+Zb^ zVn?v!-l4eldnn_62G+W3J)X~phtK&`$j2MN1Y>W1UY)AyTKbTn#uwUAg7R1$gpr8? z8Bmo*Y;ZDoKD^bNT@{opma)|T0K@$0E)!%aGRGl+1a@`}hr=8{LU4A0fsWNyuHWDL zA$+ByLA$e>@tQpFJO1@j6>DQhrswr>p{>`q|hc|a(_R2e7J?Dl$ zk~LKa_-X+woOdAeP`a-l*&1m(7|&=UdwFBH$H3Z48!U3~DI|}AoM09zxgOX!#Y42K z*o#e*x^Qc2V)Md{XDruOVkdTW2o+-kvDyL_1OB5{d#!6_7n*z0EA6N=O{q#&;Lj^H zq$=n`gOP!>@CkMRfAP&#DLZAQR*}%f2A6!F5VpiiZe$`I+t+IBR8|0i=t=59J?ieF z$lF65R#XY4$24X+Ac8Ps=NUZY=eZ}G^)*$hL*9>9_Q@Tk(@G&*g(0T63!E>@gkEp} zCmF{lK9v(y7XJWp(N@VT`zvc}bdK3!5s1)&2Q0@qB=sYK`g_%$v=;V6{HAspJS!jX zRCQ#IrIssQT`ml4@-$4UjK}9Ck-7?08~k|_1e)fUgx$%H=2F4akz#lRWO8)Fzw_IQaS7IP|~#((kFD;B@OsQ znp-TJfT|Gfz(V*fASbWN_#UKzQweRg_w_3!;gk|)Zx?ChOi62FWpN{&*>q`GppS26 zAq!(10)4Ax^27E0wo*;GB1%B;M3$g=dsm#0tl0&!Pi{#+rDwJBms{A%MNfh-CP^-m zF)9Wd7*U?y^i@Z{=Yuy#1LdGv89UP!_aKAHtKyY*Qz{j>~YJlPh zjJkA<8zkA4;+6r=m>Ee^gZV+p=rVYyUxv#^x*2I!{(Zf+p>;Y4o)}o=3BpFJ6e*l= z11q;Z3uM)&JEh?eqDn@K4aShOFt|3P%v18lBzAIsQa)fesT~Ic7|mAcpw^h~4MnYN zZLK8pQsU`O*)X8K-dyD6hy{l|a!0La^Kt&<>AM;DjibA|Eq4rWI$FnP3P9wT2;j=V zf(wxD2s~j)6rM0=bg+jU;%ZM4y)Qx3 z6^ka3^xWOOBF5F7)*Bz7cV{`GjR9P%SKpEM{vF;V1%O2)-v@6AOUAtt^47Qn=I z&!t&tqmc!u?z;?;1Lc+nKHyc>%xAq3N~Q-R@`2kOD&1(tnkTf_-^rHdNt8nt3l=!% zuoVeD>;&=J-hqS%ah+n zTr^x?MYhvLmDQcNo#Ry^C!cXuA240LzV$LyQcBHY?_Cj+!TumGN<0?Yi|w4e%_Fp7 z{{WOEcwPp1`f*uWn{D^spX_T~X?XoVxg~8Y+W1+PE0ZsncD$~;1E>VyG6(Zun!Fui z)4#t3Cm)|{qJgW$J=|AMEON%>{Iy)*Z3J$}`i{P)s*`E|07EIQ5MiBTRNUA@!1{mU zv|Ulo$or|h=|)LihlQzhXCu527fwm%+v`zuLPMCW<4DKK3xArcX%j@1p=gIK*N!T* zZ;cXyjyT3D zR8?CgyLvcB6q0LO*_AAy(^;gAxoKIyC|n$c0N|YCClzX4KFB*<6c<*4V#y?cM1yeH zGJyQ34gvEKKAhDg>rc<$@>zWaxz<%Qd0>HGHDkQuk0UBhNQZQ*}ZGeINn}&Z< z*ckMvWZB(F#IY+pl1?4nIQdaH$FVu-?OFDynG9|91&m2%h-8-XRy)8W54YvW>^S|Z z6QtLXI{oVOha!T$j9 z9@Ray_w_B{ZEy_NKsMY)21@iK^Sj&a=~Z`R_&fNeptJDit8eA)2Es-lDLV+;wCAQd zCmy&Q^sTW+=Sb(u{#MQ(fLg3@UfpT)=+Vr8HqAyBiaC`?3}KWp23Ya|8*;>OXn3EtO6({AEvCX}>uHugeT@!vSft{Aw%+*KV?Zdw<^-WAn!y+LF* zKMJbi9v_f#z$3pH{c8C#a{4OT*oAgNpN|?F(fbjIQejUb*X7nqIYABUsL}8gf|R= z-DOs03b`twNKAqM08#1m^rWq;>+eLTv&@%~!kT5AG6p{f8DdwRx1i5N!57!(J#9sQ_ueZ6OQqS5ug#ozFtc>$jfp604YZ&)~~kte^0+;HC6Zj z0AyE*FA*=|v75_`n;@H}Q@J-`oN>n-1;;0hRc5tcK)uNS01?e)b0m;7$v2aK9G+Nq zRtl;jja-hImBVqIgsqb8)!9zyV;-F&U*E00%Cf9mL&kCo0f2MqyC0=zC2gcx6LLx< zi{YcWxDLBgc>%+fR>%j?V09g^DfCb653L2wtaqnQ)C^)TfxL?9DOE7!#T%S+(N0wR zkSj$x+FwGFN$Hf$D$XlAxn*@oqqKHdQ4{kon6hJ@x$`>z0MdObWj`#eVN8*eLz`5- zj@9K5TEja?iyME;EXQtt=^anM)~j!(Xp$c`nWWqJkp%MH8=X>nYXph{cSx%E*hl#r zA2I9~9qP(l+lSw=No(dNw6SM)_twx6FTv07$rwNV?S~`$pnSc%lUO*@roS)O{*5iw zklF;_;d;I9VrH3Q^9*Yt#!16+d(>moY_yiBknq9?@8eV}m&kS}KgvMB_Nm6UR!55~ zb0_$mHyiE*sUph@zR;+V+Z7U$+wuO(rCJ|&p5{@fw9bKUqIX0D;Ze$z!N;nH&N;{xHt%}-{{R+NyDC~` zqC=;{%#gzzksE`bn&E}N%B$Z4JOS6eZl|Lc5#5ptCV}RHH*ODBNxJINVQR>Gi3;$}#VT1hK+mmMKa|b1C2Q{MkJ{a0fq1img#A zq0E!dKA5se2#e!eY)3yfKa~1qv)8a*)kf|+U6Pi`WkF}7>Cwmr~Kr;^hf+qnth|ne6@rn zlf@f5{&ZNwlEWX&$6(3h1c69K_2K^jk|f4ASNc@*On|d$cQ;6}!)QmG9h_{z{Hh5f zla7bATjBDzRP3)R(d@$GRlU?RBS_hT-2~Z6>eN6J`*P*3%#y|#-}p|yhfT4tQm zxi<+X%ehV!JiZ%_r#K79@99*E();`R6CyHc0KRZA>&PT@V~#&ee$_|WQgzPM^ZrpB zQK(V=Vn7^VKx#b1mvDcKDA_tvz?2+9FQ<_2N=MlNMh;Gxwv}!CLVgASioS+0d3f9_27MK9C{@(x#BA)FeEn4fmH-5LHSD)fOFUb zkZP@^rcGGl`rZpjEbNtCQr$L1BmQ|)Cl14~B)J3A6?}mWD0sjCJw?EColhETM10L0Q_%e|hGBU+E=s;q9{VMCTIdoI!zPQpf)2P`^ zBo~q~wTeja8BhXTsp=2Rsy_A8hAH-8DK*i(>DG!r4|HK7G>n#OAcPPJb^&nYewgeB zHOG=af5F=scq!V}muR-p$!%qS9`MnaERHvjFkQP~oROUIQ3kw~oLlIm>i!+o-%4Ah zirsA?bR@aiBjlV0$5Ib^>4c-%$2<}mcw*(W`{}Orcul-=u>iI}kPe$c9Mz=OxQuI$ zWQ$uXT*Gl`&9tDC=%>^ARxh;Cx`{0ubAV$~6$yc)+NkGj)(b})?Keq%CRwj$R-9n8Bw>IjpzY7C zPCSp_WMqlsPPUF6QhcDbjSeG@5yo-A&(oaMr6$|5uvA<0Ng|rs;x}L7Z7j`@4$;MB zcFoaRy0eyFF`)#a{HM3gf^a_7Wh+`UaoEoI`8sk4)aPgGZ2|UP@Nz(lnhR^!8lI<_){hsr`uUT+>v}ylRlwRk(=V zOlNQ5h1<_enygxHW#!RUztpYm&|4xZ-Np;7@tpDKYoZafdHE*F^_A$kx!rp<(nuhV zKU&^+(ppAQm$_-yTEcG*h~p(CBsS$8aqH}VwP6pHqe*ROtjl%f`F=!OJh7fS6I!U* zld|98eKGItCOYa7ywR<2B70UXjrSNsOM`W}7SxA!m$m zp!?RTobp5tgQacMT10T@=NnJ2y>FK*oKm9rRXZ$~c8vDhJhn10DypMDdgoGZj)t^A z+*|6FwyU-!k}icn$*t6)^xH=qkk(rzi6NC`^4+*_#1apB`s!Ph)2SnWT15T1MQPWDEZQDf!M*CpqKIUxv=s z{0$@U{JPbR!N0W9&4-dDGC^q?jH%H(z>N{5LiH`s26;c>qmDJ& zBgh|{l6~>-nygmqwp*dLlxEZPviF7wAh?whId+EfMgYz@8SS3Ns^!Ku`u+=6=#Y4A z$+tHXT~4#cM1FGu<})tQy8sLp&H(5$Q6#m#{{YBM_!?d(m3MHFMH-}E!BmL?;lau0 z+pbMj{H?EH*y7&VZ0#qK?o~G-$`B6W7$>0hIM3@+wRXwxq6&L;<~t~u&4 zj9?z*`(mc_IPB}G>Ch#(W=5H!i*OjpL%0CI9u7Ai4{X(?Dj`K4wAdo}^EH&NhhQ5= z=R9>JdY*!-+^sUyqKgKdU7%H!>?zs!X8zN1Fc)JvypK3hv5xoh$WHo0;;AmNFOohpywIu z#aTYtRxoHJxx8;H3or!lJu!ntwl0pVAePM9K$$V|=RXDVF~&O_H$K&F*AlIc^m~N~ zZ6?7x#>kHda~|NVPb@h&87JIhB9VGe*jXsC+AoK6Xs#Ll9y>Rg5Dl@p$y8=j*!56( zVlrterF~QT`|Oo={{S*4QNFlKiEb^USs3KJ@}>elFrbd70~`<9t9!B^u+?C>g6iGw zFJ_$E#U=!bBl1CDcmq4I$)B4&iS1Xekrpv6b#Z+b_m)JGb2Bhqg5VXvVn=MRBcUTS z-+~mGH+Q8?J>y#|AQwd1tA_bTMq3|H2>Pu{PX7Qh>#HH2^h)>l2yn7Y!B0XFM$kU| z)4OBX#9pRs$*<8Kr87aztLIev+#(kUYeI8)yZFdHN6Z6@RNa+=e#5$tHRZ z)n3Vt$%M+na(L;`*#-H6*$~|H+?-T6qA)vx>Sqjfou2$CLXgXWjO5^tUEj4!sYWezXl+TS*_djQ%RZN(AD;(>Y{92)xHG6^jgZ@BQiC%)2eN+G3;! zB&aA{6WvYG}eo7BNjb?7d&L$Dkj*M6|5Z$*&N!_bYQ}YR@Ib{Bfa`@?i-3tcD*r0_c{+@G>QQH+MyV@a?-C_x( zwJ;);X%CbD0}SkV80w;y%<+r;N%aA*Ja&SHCKFhXO^~<4eJ9%u|dDwaoJCCnwwP?a}rhC!ncJrn! zBCyWY&Q}Cu^{3QD*!^RWvVf!<9D;BFJfG5t+-~KWF}UEN2kD>p`qUO4$ulLgp+${K zl7)B}9FkAaW9h|9=#$Nik1z3AfD#cQ8-0J4s=dn*J|~4+M%M1Ux02zbirr;9w#JVj zBo5iafsT5yt^GgaXFh+z9u3lBz3~2%a4c=_oL)^V;zrvbS3;^|=OuwbfH~yXOy-@V zni1)fUJlZ%^gj+*KA=Ntk_DCIkQ}B-B{><~KLqu7)JbEt}tP@r9ec7vC#~TYRGsPMr+)n=h5pxg|10scJzHBHB`(Rd|HGN9y zo~5#b<1Lmc3N7n=FXhGn1d@HmIQr(JxB2Lvj{X`+qnAj6bd6(nX&AJd{MTHmVlk2l zRL8b`YN=C-@Js2malF)2-^C~BpX5V4F1 zc5ct}g*f%;nzd5sSlasSPMvaOEG7761&b0(=lzdvYIx|22=18bO(QN^MlPTLe6fxX z?fcZpc?h2q%DQxE0BDu2q?Pc+vOKg3$FR;bk9y7BYuvKzl(tBfA&y5YFguYP<7oWM z%zw%<27QfEmc7Zk*&(Ih+T2`fw@U94#VE21BJA8Z24GX!BVtZ7&j*fWx^2I;{{Tsl z(^S6x_C?ERw;Jz<(Iyhk@I;w*7(o`)O{ckLEHXLc&{V^GRr?7#OiNo>lw4fPwdI=m z?&Hc0o1=%wTmjSgtY03y)!t1d`ToCbqK?RmOUYx^E^Yj^30>S`{mP}<7lP#5;(e5z0qeNbbksqgGDRBfVS zU35lauRz{hQO5$Kd8D5+%_pcm008ma`&HwqFQAh7M;b1b2AkpaHtctKa^7|2B_x#t zK7$MHOLJMJtNnjp^jpmkdS=xGa)^~q?Svd|BzO9IR*KilUP%dGT(T_$0RV(=mx6pzcm7#`hCJ&7RhBc2Oqlgi$Q zgY#he3Wq9ID$72DWNq~KXwV53HAA_wLy|c?eSb=tt0C5o?Wf1GA2#M0*(FAfC`S;L z>CZsK4B&M3sNt^f@(N!=mB;bfAir!f1rF*l<$!mwC%+`o?^65n67q(ZI_{n&x!T4V z?xiFmaT+D+Y8KIu2vXS%yFQAlIOKim^2pR_bV7o=FKKTCO1AOI z7?2EXWyTZ$%%eR%UVh`&v!uRXzq&QDA6k&!Tv=MR%gG^CLbmE0us<)BfOp9Q*CwI2 zDoy_YLLDV#e^!a%nS!#AT&olLgJT#!ZgM)D)>$odLfJ0665q;Qu3HkjZYMo}$F>D* zl`2KN*~F=oV4N;FsYIOPV5+aQfS~-j=t5;yz4yP0b@J_{=ReU5Mj1jQ)$6VBRw5*k`$9^!eI(3cQj8xkau1|7H1^rD@QSBDK zh$y6Mi=;cS6ct}ZP`gxphJRYOk_pIXcq7}@4Q_eu``_=DOR;-BCG}!F5cXrgO0~37lOV2bEp;tI zH@S@8Nf`N*$iS)RsXTSTtEp_Gg^OWmsb=xCVF7*Ndi|=mqRKQ$+r#F3%Ag?mNCX3% zdR3OmA@58Q-P^}3Y|xoiT|>F z^!3GH?`+c=q29V0_dwMx4qR-9@*7t#(Cbqf( z#_^N9k)PWYFjaq2ve}>BSjf<*4h%)k8w6(+y6;CkkrFidY)XOY6 z`Gk2H{`C=lS)`(xGv5|Nr^R|=(PEfJ4j8{sKK0v)+Ox{f8kH4mr1B|NXK{d?dOwlu~{k$4gta64PWZZ;v#yHI*ax6>#0E_uLDflKN zl>n&Vf7_|7oOiRUm&-_^3wxW1!^pdfbU45j-EoSjo_kv_8aIeo&0}oLme%%aM%Bqz zIRJj0YYdI~Ix&|GFk0%5cQuqL9m0aePaFf(3gmol*JoT3t(3h|ArK-RvdHa^&B&_7 zBo#wGaCN@F+PH|o3*m|)pkossM|-UNbWW>e+>D2H`b{Jnl*1k z9+z;5Y)aiZC5S5hG4-oBKL<6A_3Irb_S9bK*NoFbnUNTMJN?M_;l&jKg0z5q}N6)u5XKBq7m)Q&C5&?QArLFM{4MK zII1IwJ*TbH-X-n9jLN_yaqZ3r(z)_vy&}<#8e*9y)zzbQw}Qq~Ik_veI+ZNVkV$T* z1Ev7aB-fu?q;&Z_-0E*}EK0VQFs~k5A$B#aIQ*;!21f^TdSrUjB_~MM443d^?DpEc z)~I5-0vj7vRNhuu+^Ha+%2i3p?bfRZ_Sfb8OXHQwnKx-~cWv?QcM3xU)~M?gcL!$m zlq-)@yJk7;IH>UT_x|YV?v9t2f-4lYREWl#7zos|u`Eag9tjv3KdnP_sGldNjLmGQ z@XFD^*73(9a6v9usQ&<@jQjNUsB2qYP+#Qq>*UKcuP703^BLVnAxFa<-n}-1)SfD@ zzr9&2XG^(~czl(RAZf(tpoYjLj!zv(=bnI3?N`*FsMb-s_1P2zP!$woo_hQGRQBw6 zJYPz?oDly2^8WycdjLoPeR@&KnJD9HZ*(ElH48BuQ`k)$W+U?lW>z>S)CE4&SGKg# zNj0eZkGw5(*B%(TyYre`#xl=v9DvF56;)z?F9Z^M1^21CO|HUr)sAF}$_+V(nO$nnla_I`Yyv$eLCtl7{^3p{11jVVSz} z1x>nd?^|Lu%kT0S+LVh=eLfkkAX|9Ct;W^goPu_S$j?3V)`_LBV%_ZT1b#)tl0$Nj ze6sm!^S_$PU7eF4fzf_$gXTHM6*1Ga_Er0MBJ{h7-%=`2#zH8SF}rIJ2`$ego=EjI zFuqhvS{iA~C9M8UtdheUGlZ3tyY1*kduOFj(F!JIR2Ei|s(gfbiX434AIqOp*Y&FE zk|lXK*rFxSY4Tx55=qDMu1WpyDvhPKA6hI49I(rEbjs%7sYv+&Km_t}*k>QDTWPk) z`VpV;EiokvbMukM9@Sm4?vd8sX1LZC2*eF&B3W)H&nWwhN(VgWdwn)%rCUw+_t8$4 z{``&ZGr$Cf&_}!si&{)bUqe zQnDiE{uvW)A)g?T#{;k4r5UlB&h6&BM`{C*2ON`u_27Q>Z^+HNCUodyf+_EAfM%7E zVTU6niwtCXXCI|0D{Pef3#qV_X;$+p$t$WES(}w*EXUW6n2)KdPiZDzK2Ea6v0O=a zBLe3v75NAOCESDGJ?eUHMED~mm7dyZI8>G?88g?P$~}GR*51lUh8H(bU3r__6t@}K z`Bd!$0o#qnl>B=XvdyPmyjMvvLL-hgmK9t0IWmfq`y`uxmW1p$y z(mEzgt;sgdSd;1P=~^7Jk>kuVO}MYhyn14dTe7LyFKD@Cz&$FBoe(7!CNYr11Ja<{ zhfsu#cm!v?K?7Yz?PGz6{3+TPDm=d|jWIfO%|X z+)w2z(~nxWDrmYyg}t@4j))<+k)9=t%BY}%%o}r-$2i~*y;Z$aIwI*4J^@=;qGJn% zX5T!Z1Gj;WGwN99?NN@IHe0+aa~x7#EKIwbX8CY3sCN^eu={7;k(FH+YRZlMgAa#c zJk1FYJF>pqlH`DK)2&m5C9>0&*xK_~xwD=KzGg@pdm(J8f77>mv%MI%LtRf&^6a68 zGL0G`K4|0S86k1$`*T+6jO8Mzj_(mN62+GUd(k~xFl=|GTePF7Gr#8GmB z;eUjZppA38Y3x2+4trEzxzL>)Z*ErV=X+uII3Q$@amGz9*<|lTUHCxlu%25d=}{v@ zcCkq1lWdK)6-IdpSCPB^*qUUH_dUMjD$+e)G zA0$b2bkWyWhLac+I`5DMB$YR1UX&AlmpZN zIUe*$w9%tiv86R>n>ws!oP0=XlV*s0l^`TLmcNE*E8GK=4_KsWy-@& zZ9dA~Wpz;1cLy?bqtZA>yuhg?6wF&+U;u=t~y7W$JmvdMW3>~@MIc@=HE!~Xy*0mCUhh8wLy`K?FJhg8_+E6bhw zJT1g#=1CsmBG{OLHsOfLc{!7~&I44o={N8EFZ&C(_u0noD4WI;vaGiD+J2hQTQLNH z(gbK&;Bov%w(2gZ6#hmzW)GXEndo0Gu_{^-%P$+%!bw!c>e$( zRs^@ENzOe0&w8|-t0pVKIcqtB`HCqf|L&>TqQY_V>w!LvIvw2p?07&qI zJY(K`V|!btLjn z1CD~Gou&Gay~w=^-SmkyE4GkEzD!Y!w(_#bdJlZCKWag7Pw!$)ba>LQW1qx#mNuyx z0@4|7rT|H~lm*+*7#Jk=Iqh0Q>HSQbvIoL*ywlxX?0D^%szn#`TrCiL5KY$Fb;@Qkwpa6lQ!KHPrPYQ>S4 zM&kbfQ9lE{E!2U#Kc7F_1B%Y=>qY+nGG5x+JAFdf+@IjZD#+O#K*e2BYRbNy4y~js z0tkVQGb6qTg-#ofp|ODk?>KD=WU5sx&J_a(a7-r;Og+IjC4W;2G77%$Fw$L91bKp%ffvXZAM zZpupfMP}9*-u&C$Br3DW$#E)K<$ z_OLth2;>~(@s3HVuJ%>w72goKhUO_DZPBg^64?&>KqudxIjT)*G*-z-Wl;jFb1R+1 z01gm$C$K#Jm8#KeJ)$T>gPhc&Y>$|in8vv0Bxj(h4DqSlF8Jh`3uaF(+4kh zKd0WJeF(&kHY;xbZ+tVI`h_MzYWyC9nt_o|2jB zGTXi|!#tI%cO4XclQt@;43W%`Bkws__%SXrp#4v!VAVFh(W25T8m0ZTm&&Pc9I64Ix0FdDDFst+Js4w--D^aQ+p;Ps-6Fka zF|m03vRw8jB#+XjH?~ocv&NC#qcoeCfOyCNcI#D^n%FFQ7BmYvCf?%Sn3eCnk+w2 zjN_WD)gwqcE*=`Xdwpi^XO&pb1cxek;D20JEpKO3UXBxuK2aRW45)T|*v{47qy2~;X;wuYiY%{e>@hNP z*MW+{YnNoCcf7D)f|egL;&hSl5qLPyLr}g=qUjv}0KuY>v2P0`igvNy3jK{)&AlU4 z1U$CW5Zw!lcFV>vROkEsYE$+rD5O|y=F=e4ZLQ2UmsiusC4Gbqq~(G(c*bzp=y0PP z*D6&-(jGy3ePGgBYEiUo^T~I)Fz)iJ1!Wts9PS_xJ$R)_Y5xFH$)s7Kw~I-gO~8^_ zAh;0f5(L_fcA=Hn9&(r^LBRZgb*kj3wS6zYy&B_wNk)k!u~v-+I2VoyV&ChNA6prLXkn5Y{M{?K^$%_5py zJooyPl2^<0JzBt{RyPt`hqt65er)ZlT( zYX1N>1^HU>W^7*bE~$Gut7dn$BE3#!j^ACVuHHb>tJ!2Pf* zB=2uUzKD5cX7grE>N+!$c8(50oO6uepQTMUOLRGz-s<5#br9fyGr?V?mp}D!^r&v% z(3FxxTa+vR013D&OA!+@9Bo#?$EJ4RduFDe;rAu`o^*vvaU_rc$p%#CfMjpV2=BBn z_Nb1!@%Q@`mGnkSD%t9{cm8Pe;t^Y}L2bA~z;(icPIq_4DtS2k-rwL==#ic{wD_*A zpmbY^U`T_Z3{h|aUt&j6Ir>z!#?tl)-o|SCei>sb5mb;py-q#NSK5j9Iml$15|WUM zD~>bQ-}d5)+Sw07JN92KkYt2sEuVA8HFez?vK*1{a)G!u><3;jYW@tYkg>QQ;ufkw zDmJDMIUwY*&wfo+_heZnvn$S8W-29Oxl#aBB%F-)JHNd zo=*aXa?xJB-z45&m`3giBY-njYV>kWR>_S9HS?U@IapK$RZuxq$miERe)MRn5?h}& zOpbtIxjuyT{i=;#%Qr$xt2q*Ui;|m2C;57h+){}6jFHgqZ>8Lj6;Tq%>^ATfRYu%; zvpFX}pz0|uiSq^y}ekzOKebEd^5glLH*jGN>*a=9uA^*IF9tyQ9|hPtuxA!WH@uI#0O z7z#K)y-STPn9HM(w_hMgqYCao;~D<|d8dmoC2U|oBVREi0e~BZLCfODC6zUY9x!Y7C9UtC$4(c5i#uMRhtXfjs;I<;>RIP(Xk2$+HvWclbTYd zNLgGiQU3rpBfc^{Xo8iFY;_}L0|^utL}HFlMs~?Q{{Z%>hK+fUnyuf&1cC|V+Rj;z zY@SPfPc?L(NOBt9PJ+QB48vf_1J}3qty1t(Pex~~Ni3JZBNLW6B=t4X8mDIzmdjU$ zEFGZU`DQiCI=ectLXkInrSFA+P)m38s%X{0(bvN|7+Z#Lr-wZH3agcfV%eeEz$1u_ z%HovXaf$0CK2Ld~^Q*iUe}CkIcLC zcBojLb|W_mHk=He!yM<=)}=k!dhj@&G>%4D5yHBu{tye(x6tuW$wN;RLpGy#p<2YH zqDig`DZ?trV+0oUV4?koJ?o|uYonheY~X@BYflX6aZ7h|V`(tCnXPuFe6?ViBp&<8 z9Zr3!WhC_c{pig^b$_j`EB> zdj`f401*R$jI*;b{{Y%5Dwh8JiM{BK)nT@_mg7qjPPZ*GDK_85a(0cwC#l?d`hi+B zqw;#Q5Sq6G=N&c9tq*bypi_ber&T)h5jB;wk9WG;5 zO}hu18w-uVUvghdS#c;ntOKt0O^k=(gax~jx|k@oMuPMaC)AD>}sw2oqK-el_%Nf;odE3_U74x z>ChpCL~n&x+kl8am<;XDT!T|Jw%1>M6;DY%$MG~5mzOsZzGF!ul_NawRb8NCr&I?A zjt8|-HEsSwq>!36pBb`C*+6@bF9PaC`Sz0EFZ=6J3vsqxz0y20$fab7N;|gLS^9Iv z@1{@fin4FD`V#1^c#lnM*y4*#lXNL?!Ap=GWI#l@_6^7*voEb{#U;n@>SMRIPueR- zpnOK4H(Xq*Mu3n@7Ga4v<8BeKKDA%Z$v3@tD;IGr5&3bIc%f$zj`DMWeuJ8arTG!r zE2Y8kx`o}zCBsF)+nkOG!0Xo|C(@!$n~^DaC$zYyf*bde{zQs6B$6`>Vm4V>mNB`x zC#w;Yjty2V#Xb1_?umPAR&=|@m7}U#qN^mN5fMp{l9vJ?plv< z#vU0w#Tn0*GI5NI6QAC!y4ehh#4x?a#+cqsC(GrIRv6SK1#g39sUrE$k<|^Hxbt36tdt4tM|! z-+Wcl)4y`FWIctjwZE{`NI;TLE$p~ZF%vQ(?(TTczZGRJoBKs8w0g6*md4Se^IQo0 zuPe-5jQ9pta-?uKI`P|TiitW}R9P!y^pHl23<_CT>`r;-<<33*ed@hw8n3C|WoaP1 zdy%%_m>}v8mb=Mi&#n}YrhO_^@0WTaPpTkhxi2FHE%|u*ROq20cW@4!99BmXTp(6` z*x08T{+%kaR;oTrN4=8vsF23eoHqQp9;cw=u;2=ct(H4L%-4ue6a2eWXK~w;{b?V? zqOt%3LHxd262>7VgFV#m98yU$sgLF(Kb1%6jP~ZD3gfrkkte+kVUBs`x0Wc@D|3|C zoUjDoXYG&F(I(n{2`6oC*j;>zi)n6hiNAt#fb0Ot91;Nk0KHvG<@8^6RjqwUEmHD% zN_9b_|#yZ3w6Xa>=6%3E%qJhBYc2A%H zaf*lk0P4Q{lD*j_soGuX>j6IQOh1X^atD;tddlpf}QN`r;Nt#GCaU@?^j(HL-OE66r6EFP~Hdy&D3bS z9!Z;GDIk8i?L@7T`W?Y(@mi&roxq4rXXJ7K;BnKj^{9Jl!s|n;=YNU6xOY^NIX{Hm zaH>HZeQL6MY?Qi3y;AWW>PV#WBL!oTAwYgb+@(nM&VNdo_d*NUcYcxK*+TDP%qm%A zMrqd~=SaA@K3HWqVEw)7klM1cb)vNI=1S@t&2amj$iT_ZPWa;$p+Z94Jm&r`c8|(E zy(wj=^$wkFZ#JPlyJ5VIkx1u+e1Oge-ydqS@>9wrBSKaU$P7}-tblYx9X_P>`_&%m z%@DV7`RqdhjpwI087CjDJd(69NQ03i$X93?81I_5du1ebo)3qL=J91zxRKQZy6_Nx zE_(`BZ547MH641)$84mXm@>%gxPV*ot~+1>$>O8BL~G20&aDWg47`*Xg5U_!YPfX1CS1X zY}Ib%PqNjkBQE?sr_FkP0`5q!MqWjo!jbcI1F8GflE1=XD62czMI!D~ju`Y)f$m3Y zG|ghPNl68z%pytEe0Q!>=H)#&IE^%{{YIgTSikL2r-b7 zIcEeYK_DxRxIap|RoQ{&7;bK_Ar|qO9G($ZIs12|JJBaQ*OKb>jo+GOQMJ&nHlIvX z%jSC_B455Q4o zRgxXZ?8G+<=qtH8?BisPiv!9gcm4>4a?C;f>l~?ciHU9Su|}|W+sO=x@3>?B^~*I* zncI)>q4)eO#h_Fw**`GtTOZ=qUB&3PU5%NKyQ3jY8$Y9$oj zjbev3_b4o9XolGqL^vL~BR{yTm*I41nEu|}#i7r5vlWp}agJO4kOf)^q$IRX#Dwaa zg~AI~m*+=jwM&S_ynL6Bcq4hhAok!^QOQlwq@(U|)MoO;GQua+r_v%Dd&T2cu@ z6d+y+_U4~f2X_*ow~|@%h{dIu(Yg%ek8BUnnuoQrNlWFLJzDbK$H^=%QqtV1z-gS0 zLG%n*40>eM=X{!vx=ZsYn&O-M$=y0Q6H*bwF_YpHgiv<|11O9SafEUJ>DQ^LRm)Gm z`u@Z=>few1DR*}=+gV*nY^7YYF4Y;_6~Iz?#&<49Zrs%_qiD5k=dU@6=t2b7QCP;1 z1dUIa357|FhZs|g z)N6G9@1p+A{pjm)7NsLgZ47N4w55_MCC(NgSnlKe#NcOu6n$zMlXOOw%HFXh)@<$) zb(t;8%_afMFk`nLP^&Pby7 zfk_tX^T>WcPdf$8tX|@5wA08;hpt=6X<`Kqj3GA)3YIFYTWdQGHxR6G?e9_4e*XY*+avWUPLFASsF4-S>l%C|yO7HF z8+m3u)dOcA<{(wzlwT=*{{YwWR!;PUzj)=jj#-BJk}y<()xVqW3H`luNh^Eol*ZFA zMPj@tU7&j4)k(3qxZXoHH?9X-lvS~d%*@Q2j${D+g;^QNj9J*0KuA(Sho2GV)QpWcV;lJgmdETWQHDlV?jr$#3g;)5^s5|l?C6=NmhT8Orjh7rpqarZg@0DnrW)gvn& zE~Dh(!)fBiZiDP()Sp2~{hf{yw#35+f=+T-}Cn6p)Ng)${}0 z)TkG+m&e5uZ7c|0nC)69vUyP2?*19qU}nkdin7;bT&!ndp)LH6apj*bJQ7d7f3W@P z9Oy$IBHdwQ@X-_03@VR*O2$skl&F!neb);ZRU;Ta+|^s~PKySO0>x@TP^wtt1Ftnh zWu!WuL?p3bFpGut>;C|M(xT9Ai0O72C5Z6l%xc-r-a+g1U*4s!1yRW-9#zRKRV17; z5KiK}W9`3oFB?AO8-L;n?uydcMYP#AC_Z7>%%(5m7j~*92j(Gl^1xD?# zbhJno;^uv>$qR&zZMbO*kDTOtU}KJ^uLP59&R0mQXjf4kO8VHqsu@6q420t+2PAWo zj)S#dtr?^{MYp%Kv%0*FDI_yAafKw1pks{w)s69rZ?jJ&hfPSNzLxg(NLmOcNW+B! zIGlXMfzEITe&($gQf<92=!5E!5q8(pU9H80OO=94oJqiGc`C;pNq5dYx#?O)UP{U= z^`hKdSosU9-aO#M%qL(6n>R*fQO3|1p!QSiNliEOB}Y}{ZFMtSrNo|dE3|>bhTP{W z0bKS21Dc}xlFGr6*`<-f<^F7L*q`sJd+yOF?~T z!Zs+aB#6<-*i7fxVBiyX1JA<5{lA30OOII5Ix7eOLUTdnO@zUEaHsZYFndpeM;e`jI(Vh zh~%m$ACw5=UccN_$*Et9{?-!jc3{Yu){*Go6ovBI~Sgi9g<;@sPWE44O*ydKIwbLwc9*JL5WT1RNn6ph&mYF5hBQVP>vD-~^ z8%U>uv5wf_{NU%<4|=4ZJxiv=P`ZnxXf7`dYZ{?dW$BQ4EDz9qmZ5+9NG|B(b!L)k z@iE-Wf40j)l3IaQP13IVb-BcWSD)*>XNqUxK)|kVI|_ zVlC~Gs^m5a^!ZQpt1rUS?5w-7rGcJpYI&9<7VokJg)ls)iAs-~xnc_sPqk@jy)U$8 z*0#~8s_8By%WPw+K@2enq#r%Nc*}3kSqb5J$IQc?xE_@{s(*VZd5xM`uUVbi z&NXQN0Eps3?g;2e>5x4$fk{2TVq%Wc$G2c#kd#p19Fx%h0Hs4TI_fM1y97CvpDfuq zVn#EMToN-&HtF})^X=a)!T6hN06R!kd0?Jn&{ix*Awcx8tsh%f^ zpWy?8&}Vl~Zic41DQ7}_tv)E@VX#bNWh!zBg=dE{j09@whO{{Ynzz1Z7XjzOv|vjkg4#I5DA3Ke+S&sv$S*McKeXS<7M zy`IuYp^;-`C>~FgY#%d^ZaUPvlT;Ry97iVjCv-+zK>}ej^5BexC$>rHP~E2dQ8Y5w zuC5c|qy|>*R{I_FM0mLzc#`Z%BFQDZL1$$LX_c}{udv{Kv)-afrtiU(g`}Zvu$+>MpJP@} zS}cc9jm+h;NE}oeBuiWAsP`)Dv9xf+OM}1}2RS~KWUbi^=z@b$k^D=kUt7intT}=L zc-*V<y~!uFl1Tu`EEnY-!1So>lDDY&R`Xv*j1QZ&qfOWY1oQQ+B8+6n zYg4sMK<;)$l(&9K{{TZ)=@N?upYkMxHWaDJ&!tqb+*OEKs;#wp&(ApA!(g7i)qqvVoTpy`e~ z`qlhdjEFn;o?8aE8o8D#i^ z%IP5>?8rFIJ$lr&;k}D0>3Fx-axS+hp7sYT4Z%EZ^lT59Rh3Ip?7)$o#OH8-u7YciEkgkq2j*p7fM%+YY-1M7i5=t^UBfCOPZ4iIrv8BXpsInF~VU8Qpw^no6Mgp(>b&m8rwv8rZS9h899+gVe4O_R4B1$I`pU?stf`D+{PWgM|R>G}{~yfiGL z(U?f$Omf8c`CI$fotF8!JqTCBD3dxR)5mJLKzQ$6={BvLO&zDz?{3k7N-Rag>CfH!G!H{(v_Nc=Tnx)a6ZnRU9 z?)4d%%_s~oa(jI%zlJ`NIicC6cups|vmF{x09TOvbgwc?XQhv#$7?*gOiLLly^rM_ zlb+Rtk}TO?@jBdH>$0-D!ibq>2Lm|iTR}dKO#c9ggwiFrz0_V62g`)+k%v-0r{1*T zq{?I4C$+1cC16N2yu~HL5h&fzBE$QVCRd)9BOB@ZqpnRNKm zGAlcRRR<^iioNL;o3v=N0$|8~f0Nrlndh^rTsSB6P`#K)J zR3??>$qmGiLQ>*O#1auU5>Tn~mKetTF49Nl@69D`BvVO`^-IWLzY^TZ0F>Q0c0swr z73EZuouD=k9C}pgKh&+NAVtExoNm#g9FhQCqZuG^>HF1JOGVMmmK8%ID*^1}G-san3<#el3WwIZ$ip}_K#KvwM-l1r@!v|f77Ck{r*Jca$ByUXDT2_{KZRk zIbY$91_14XKBUptB+~r9BHQCb9ZOA-wX3+>3Z~-{xIZjWhVwRoj5BS|9l7LHT5eDI z`gi;eUn*xSn~QC;%WZD)$EaLla(-Vi_K;P-n*%33k0PzfO4?oh{ri)~zeAg91}`es z@WUWMvN@ zl2;pQn(_52p8FqOMwZWT$M~LfX%fb+OGx0I+z!N?eK0B;<8ApRY-xX|qRg<*EONAQ z$O^)x!Ug$?fH>u`*U)vVq?4w|Zq<+$>o7&U^5jHh0GSEM>67h~lSRLnr_hYKySNfy zs9fh6KD2l2LuVN7Nrjz55`UO`Q8d+yIebuQ02#_D8LK9Wv$ebq>Z~{i(yW#?BcGS?_P9rN|YLtaayKfk&VrOQG}$vb}$l;Z;&)qlC7bTGTsL4{*~ETy;xGmfN;b5^C- zv02Q57i{xnImkb~Rd!;S_U`IG_*nx5kd`fh*N;lq%4O_j8^t3#OyKVMa7Ur3iuV>V zjxE=W@chZqa(Dn$c<#|wa@A)sM0YMpI3Cq{D*7X=WDh1}VpR9^G^ON-?U#)WRv-fs z*aIEvl2xO(5~Mx9yYke!0(&s3c`rFqDq5`Va=d*i)Y-)+Y>Arip~QfezyR_w=~^o( zW4Nx_Vg-&nlhUrVwrH6Xsm|x-zyXf}tsRjjbML8a&VD0e?qBM}5h)-Pe)A}0M&6kTgMJS6* z0bNYSQm7AA0DQ-eoZ_nuBTpl5F^fjvkf45GPZ;Z0S`28jJf327+Q*J~#Z|kqq~@t} z9C}OGsud;GPSLfC9$AOm3Oy+%lHylyWHz@khVmwk+}h6De}YNMw}(ZVKd($X-b1D%a(2AG5-Ldj+pte_Nvz^ zEVMefj1+GtXkq*;=f6@9`}C;qqEXg7LuBD{hGbBVgn}8El2?QC05U!4bgYWDJJTVK z&rXg(=J}@#&cg;n<`q<5us*zVS?Vg+{re9zGVy8&FK%pX@a+LjV|ij1V$< zbRFqyX?Fhrxe-rCeaQ~BZ5v7)Z3an-kPgzo06hmETC|-{@4;yFI%feIOaxW{9)6sC zYM)a|@G;aDOk6syNV!r2F9m_!&)0!heLu{r>}jgQ2+-eT(>3EH^2`+*_(otsVlmW? z0AE6Cd|L0n>+Vx`^gYTmWR(eg5X{!V*<`Bqm*c;oY`X9ANN|!~_*yb&y?v&)`pZE5wB3TtMo_WJ8 zYydy4QQKq^F`KW53j(j4SOD1R%~?5Kic<16g%UX07^ILZ%)#G3nfvoqNpzWXKeQ~i z^AcN?3)FSS0Q%&LE}IPZCzLX-?8+W8$zbUy5<}lndo^o40*z~J+ zC-h&*Jul6Q)~0)_$m5YDCh=t?a=FRapme|-(W`A=mHvoNN&N`TR12#uK0XDtwfv=J z{$aBmLdh+FN7Hhd9 zmL$BBdY1XVV-8e${Mc{Ok7>42T07}5l+(kw8{|EGs3qDw}CFuB1eg1u_S=@Syj z)|RUiU|dRqVh=mL7a#AvOVXm9vWuxrB=^wi!ZlV&Lo=pHc5KK&Bd!z-RHbT+n|z5F zujbSBC$^3@NpD1L@{oMcINnceWS`ciO01Z&%CR`qW{?ChtX@kxjNySDKVR0el6QU$ zV#o3ah$PYQ6a@f|zSUl~iy7{+WEay-aIA6(1N@+Jb6P>twq()HHTY}D5Gt^i6@AC3 zBoY_tS8AF_giP2cnZM-QfzEpxty?rY-AyT9gttwa4Ze|D@_6Acop}lQ zGI`_Hr^#;z8QJo&q=YEW4mx|&=u~HO1ZyIapA+)oq>~|c5(&WSO-+8K8N&Ick{Oau znhyI12zaA<-$YR8OYoNvqJ=TRZz69ixGIvlE$j)aI!=i2b8B-3uFR6|hm|q_aO^st z-l4CUn3A#0FU~}J(0~ACiuE;X7*Z!sg1R1SF({$q{@Bdtna!LkojxR^Xc_}PSP zjhU5#k3dEbtzO+3QQixY<#4-3GJdr*Sn&4@Q~7Ybfl#6t%-={AkbI%fEKdiw_x-9$ zvx`gr03E`Gj1B^lNAFg@n5pEnTcwgxO(nM6>+;bWzI3hSHUqPW|^Xi zaBxWHBZKv!chLi^%F=~9O0WQBf15R=Uz3+1TYDK8%+L@~P6q_w_pOyPos4xmXdqd@ zo8k){k&>l)e>M$tL8Z}@h$9>@sLP)>Ipd{tC&?LfEz(-DtdPt@k(X8(=i02VqNKFb zGx%mNC4f8CTrXT;*E)hzc66t4NfvLzdmA6{txEe)L}IE$d%JPh=s7ixe2<+YXhkTu zBA9I+?rCn(L~t{bo4Cl&0=itdsyUMKTr@=ZVVn%8831?disGMkcEh8-xoLY1x=(v- z{{Rap`EY&u)gfu@rf!PzX^SP|`Doif1-sVIE2=Pzc3UkKtnH(cCOgAtXJK6L-08NE z-pf+By48pv%E(I}Z%VHp`7svkd9Nky&BKEUHo>xA91l)@#->-YnN_jIgQN=!Ync%q zWtnnF=m*qO;y2k4REQL^FR4o+EKV5VSLw(4)xL|sPRHwS9P!QNFdOn&IVC%(CqPRB(Mb{i>}u(0vkGLt8izY7okw4*viY%Nr2L*a|SK z%Vmp@FmNi>YNWouf2mHLla>M-iQ>FjLKJ)%Wy-oJ=K(wLJv}O#e=__13-qX#zKU1z z^pG>R!NY9VAv~}bd5rK0KQX{1jyUO)(zJ2^0O_~x{{Ui_@@wy9KgBoFzlX=cy9>9t z^AV(6x0mIB2+ufEy}9aNCZS5AUB_?oBP=7D#wj4UxSCl!^kwsuZ#%lVKAap?bAh!2}VQRz-VQ?PGOJ5M6wfR0NLM z-Sy_8lwZ?d!msX1m7<*lrDB%c5>5+x6^62j^z!tX!(5=nfrDG$flB6^J31$F$15tW++x`(p+V=kE zs~Cmd!x*yOW3v)ErvCuU`TqbnB>QpeM7ceA{{5A1hZ0=Fr>~m>Wv$s&9!1DU!Sc=r z=Euy$booctiKxAJ`(NB`_C*_(yt9+d^F$;JLWgGZ!*a35ZiIo*8Yx+O%$m!P7V&f`t;<0FljY>tCJ zn2+A3FJ#goBeemXjzKuZk346Zgo;Rl zmVMH*73hCcR!HTNJiyF%9(g#$N=9uBwIoo0u+O)>OH{T+5i-otuH`>!s%4X+7WVMX zaq|O^E2;THnbVCEM{=%BP}vP2UHi)(r-AEI zfNC}?Eu*$RVBTKS{c6Qzv{5b*?dIBgb~S1^%&ATq)SRlUI5PSpM1{Hc$!5jw<6Y*ei(WvS-S zCBPyu%FoX&=sx6BUzgBmb1ktJGF%xNYpaWfVE# z?nspK#Eb$@^Btf8?!?hMT)ITRVVV`lamE^{VGzXzN53A ztgSVqw)Ufa{n`adW|#8!W4F)@W88|fb@{Ti$98sSO|`a5vn9b+Rx(0%i6tjH3myOm zf<;5EH}=P8d8A`3vBw;5asgFP4#Z+NW8b$Y)}g)9?07s`+Dj^YH1iO$Vh=GBAmei7 zMtM0n82*(+uTA|4Z7q@-t2l_=+zkcU^r*kFq#l zwY99XvWAb(Wiv~VG4cbjo~NkbcQt6zSMT>kCfOTvB&jx#(_y40L@DT{au4oD+LB*} z{-%-hN4al9k1P8vPZ-5Zwy29q*xOr?-fPP{Lb5?? z9@mmK!m}t)xj$ar@N?F$F5F||`xJ`OZ^^>b&9%{X!L}w_W@cl-W!wl+?pTsXUVZ8| zq56IPtX24MO$q(j~Tz!^?wu{Oh>n zj&tez^`sJMr|e5@J3Bo1g$6&0>Ptl#Y1w z0LfA9{{Vbbu8f)QPMA+1*x>x%Hy+&41kN|`7~+6}p$v?~ckfh^(lktS3xjJT1k8C> z$>Sd9`qZtWud#*o+RHSL8tqNkD~@>lqx9s}tgUz>;E=ANHNH5OHIaSJK{XvVfpE7C zZ5#l|P|QdfKb1h~Q`HjoH@>xp%Z_Q_677+KvB4|27UMsreX6c0ZI!d!Vi+MvmDI6W>Y9Vc zAHiCHkhb6+Qd|OXexwRUT5|A;y|j)d8QV&+^P~R&g^uh=GVTF}{og4*;C1$^#xIKY zvKv;rtQMOZLY7T!)@ilBH$-amvi;$!Ocg9?QEYU4yOxT*iS5*4A9(&@)&%9 z5O)5a{8nwgE&D&U*ae#53y@V#PHM>2x;@<7$#Zm)5(IN8 zG4cm|1wHxzKJ;z3`ISjk5c=Ml_PXt~xP~a?j0bSvD?4pm{{Z+w9=YvTUJ5;t&?E<0 zmi9(0@gz|~p|S`E=03w2=}RJuC5-PjqdW`@kV`RjC^mt)GCxccS+%yAq!~Fa*-!|K zN@H)8PeYD5s-{`=XPzMjIbbX@g@_~6_2l>MS4hc>mQy9+Ge*cz0H+)<99EBSVKT|3 zI?Etj@s371)mfxR*D7s{azYfmXK)PMG0t)ORbIL!jIQNZk=PJjI3G&4)S%heo1`v7 zFv~E;1_x?+2b+j^jGeiWumBh%9=}}F(NoQ&=`42;5JNfnko4n>R3~MAqC{d#`?%g_ z5i})+PbNL!74^*%+d=F?0G10?e8+BtpxvE?pBQg_s6Sel?d(iRBw!*ya7jOzjQuLqQeBZVMqb$-c*?doUaj}5F1BXIb4pQ;o;IJ5>6h_mnT|H7c=0{&ocO9(OkU*kWJNGZkfsxH`2fAhwAhif( zdxlwp?VNq8 zpB*VvF0nSOobcX-YkQ?lI<$_XA1NL4kLg_5vdurp>&1yU>^w<#7LTXf>6Xp4CQxSE z*B|eSoG^JGCR03=K2%liwKDP~aHtmXoFdm>!`9AqJ<)H_LA$q-MU!bP2~+)R&&wBQ zY&s-wXT7_M+6m>~1S&wRTXjrLTRrItsVD(Ihn(^|`_Vf>F&|&DY;P>{jl>^JRJtzE zo*cW=;)?2bR5AtOdzvjGs!0uX3)_p2CKfK1GJ;uGBZ0sf`&2hd%%!$jbb~CKRFGLs z6e%i|U!N>~l@;t+bZ2)K7rJJp@S&T{+}XkCGh4Yut7TMQMaxFf&8~xYD?Tn5mL&G$ zBl=cS?COF^5W0q^CaAJUCDNs(s_sPt8E(1%0DiTqif1-Vt(s-5L*f=ViZZbXSP**u z04Y7st#ChM)mlWoyvku)Xr(s}E*pC!Ta_VBxdel^wtlr`{{ZTp@Ae{I<4rbHYm1*U z^(JYSG7YNkz)X>x;1hs8QPVw5RyBS1T@=~JUATq|cr7k>TSp=Drg;WdR%Xdk0UTqs zS-MrwlOE|YJa(5Wr~Dj4$x;f&5E$IxDD)WT1B~LOTes)@mDY%;te-AT$zdZM++=+{ z{=U^z%hA#sASandOTa&fHiPpL1`p60Id;8?qtu#gWJob4MgS?tLD%{Zy;bZDB6W?P zFEHrr0o(4a_C8)Okqi5V{-CvlOVpaUU5JoT+Lrcp_@$5*X%-YZwr%<)F@ zF^A16VYx4if;!~n4F3S7Or=hj`Y*=T$9Irj+}nvGd7(u92GtneR1=bW1qbh%qTNw7 zS}GRC;oR-v9Fkc_Lsyk}Dp>6yEg&oa$N&O*RSjZTtTsbyE4Bl=`C~nSZcpec6QtWE z?Dwcbu}!2{O9R7ocW!0#F`T(V+gNr1O8w~L_+wjWt=+#CH7OOHtnvAd>l_AFNaQH4 z9o)n&=2%u-STCF6~;=BI+URn4)33IOv@J%0ZH-lnusqs5-+$li0;nvJ3la?Bb+J7by>L|;plBiE;T zo1{`hMzbDJWaE**J*w-YIYk~M1}O6X0GraSXvv~3Ssr;oJfP`W-Lon<-dpB8punqs zMAnFdXcBgBl;gc@o1+G{c7ynM$8*}E+AR|0q70}c4h3O0bz>$cLeb#;Du#m_b=x3j zJOhkX(I|U&bs1Jy#$<3$euMtPuX`d-MKe=TE!o(+vQB>0FX(eiv&uk_f>_|=7^C`> zqp7-RV#1tp&U;jNBFJmI$>orMatW)aYh_z(l+tV@os>T12a;E?{?%S3lx*dwz+%St zjlFW9Jp=tYx}k=mSF=!D0y+%(PdoNnqxLvHBkfnl-Quw{tIsA%htL~gZmWDKe^ z+Z73H$1Ad|@Vn3Xj?wATx+2n4b8)i4rfH#VN!ya&F({mewpkWv{um(7PT#Fk(bL3c@d>06g2!`m zDy><=Fb+7WB`O-+?Tvz=91>XL_Mni?bedyt9BY9o+%P-({?#|qGogpV zx@AYoRAhtH^WX1KN{t?^r!02K)lW}eeJWG;G(?4#GN7D+OD>7P(TGT8R%XG+)1T}8 zY2b!-S%cZyiP%FDP3K66IN8^3KlqA^(!C-pZ0F&?R%=VC5fKKy@LHs54xv6i^? zo^e*HVRU=9wGdp&_Y<&b7idNxG0#A!_2_=IN}IM-@1vcR&o$Du^GfLotZ}XfmZx_+ zSE(cbGf@|9Ux3vu9ifJGxpOIrmML7ai41J)PeGjL1cCOcik0u`L!-5v?$#6A+cQCN z6mba7MosqW2B$BLu8go^+7D5OejL2UO6M**EOPdD`l5Q6pm>w z3p=VK9;cucT5XoH*gVT?@g&3k939Au)SZWDIQmqy)UEVawMdUfNp;nYU6RZxdDCXl zIrQ9A>9a$6XfaoYZcd!X!}N z#8MATJ}?O)uk|yp1SA(LWgY7(86%B@9j7B3dBOC~DzVj;?uh$4lW_uOJTU!6d;XM9 zMbSS6qQ`7xnCwlvhp+xBQu4@h_A0(0yI5g22ah^HPI{>9F;gAv%1)0S62CI#+4k~A zYAZr6$?N--B1pyxDuAaQbJYH|S$Rf?Znr3H8U|t%V>umL9DbBtQ4H;;#wV3Vzz_qD zah5&)v_a^PzGzch(&rfvtnCzx-jx=cOj9hHh=Sr6BYDdCHtgUI4oU1jn532W;SqFu zy^qhfiZlhbNEOC#O6|^nTnfCEq>5h1va`cwG5K+qEMk5C9&-<*X#%mTLk^=H=ss5r)|cZ!OSgAYkasDE-@zE@PdTfDo@Tjd)jnb7vpbgL zfVungimu%iXMtnzaiMrlZdsenh=a6)+#X0i-RY#iG6dJ9jyZIazb)Y0&I;g#JSabY ze@d42y~tK86&kLfhZ~f|9~j5VgP*QR%}kXyWuiHfZ-;=p0K{?yR*Scy5`95_C1mp3 z0RVMlo_Xo^trDXbBZEw4fRe|1l6Gf>sqidkK1_@o(-kBhQ3`@bZuAFxa(u;1;aii% zN6?eJl5Aj%#~C;Wr3H|eP3K&`0on-9Jaz9=^fG6JLlm+Q59TzgvSLcuLeowa$iemX z6$`zWqn52{J-wZ@_V8~&7?(l9l1B!w7W^1wTPvErqCi;Bk_s=D3LM~PJl3|~M>NLL zq<1q;NL|HMdgPuu)rvlf)Snk>-wNOxc5T2vO6yWmjhM7vJUep?{uaEnV$B!?e4`n_ z>H3gsizmw`XLcoUJ9swTbXzOyolDHOwLz4~>)apjRh+&glSZ+B4lT1Y*6*89)aSZ6 z!?(x}W$j+39Dfc9CzX^k*J$fkWF%d@IP7g&aF~c?cs&nn*O}@SNwd+# z(QnZ-L#x@ekVI8tQe~c5aHRSH?Oe$wx;5jgWDHj&C3J=|BTT4f$jQ$YFG$Tubw9*h z!tttRQ_zl>qU7|^XVDiWy~4-kJSw6y*CUhlts7}klP4}>H`)wQM$FtO4E!>k$MxXT z!CuMjF4ZlpBaA#nB2n|6yT9?Dy;fbCN1?0id(dNz9$uT?R9^vJ-$scG1j&w73J#q_rj$WrBHkrbnYxT^E{v(7Ql)g`y?N+%LDp61v^ zh>@9@@%+j-LxYv+H(RkDkP|~enOxsmTd96cH##oJmRI&@9*3FkVD-u z_=%BHBtS;ijq;=(ocdIGp=2JTJXZG)6`;bo8=f@*PI~0^{9G`GFmQ=daqV zmlbT9vVU1gF08CH`EN~=-C1oC&w&#r_4y6r%X{U2t%;S+_5c=qX2tn-m-40 zK0KF&-T5c{MzkxB z5rXdgs=G-f`u_mlkygZ+8+ms3z9_c~GsSNrj7)MEUt;) zM+4>H6VsDY-zUr8@AxQ}AD7r?x5*PUE4h-@ql(=C+Jgir`VHTDmwRj5q4YU2+?cMB z&^*yc7Uy-&@=|CQ@>wL9AsTFY|32Rnj@cl0?ZTt}t*r z)W2{ubuu9h`MVEVuYHs|L8lNE_6`Rpy-kWIbnBR6NrQ|yjD;iA)TU^(Mrx1dL`WIO z>rVw|vIw1|KGJB6Xyzt3A&y75=~hIetR=*ME_V0LM6QV*ga#ZoPaUckTOf+Kj69`B zZusj~Pme^UWX_EU+yMo+{VO~2b>fLsF1Nxd!%- zZrQlx=aGuN`7=nf+5SKVLif#4?A{@HGWnr-IO$7BGrpZ_w|5(e2M4EWiAad6Wsb{A z+w&2D+uxea$(=BQM47S>Mpy+nTn>59aaHSPr&~K9hs_`_Z>?6nib^Lz2FdSs~Ehw5pO$Fg?HDN`e|BB3-CAjnXRwBe$R* zwFsh8$)Y#!gc~Me0_Ptpf=})Mt1ZYrh|7&mCzeSSm6!s+DEU-isXTNUJ$V5RW1Mn?T^sawLpuQhJsWqOlyTx*qq=G zzpYDpXe3!;f;&q)*rZ_SQ6wQgZNqLz{lKcXN!eseM6lbuGq7${LfPtY0Ux|?9Qo_tZEK2@w`7d_bEF%>Sfmx3ZlTQG-DnPO5T zmOX%v*ZWjArd!C~7+K(oNe>MW81$^-ttS1AFTnOUbZ2!{REY145#Kz1^?PgdD9+I+ zg`%}>q1SYULCIamfKPLQnu@B49qcczB8oRfj7aiGq>u9B`LR~D(F}y1Qw7|z$vd%N zxd(*}kLys=w(PQcJq=t-V>Dwdh*a)=#Cm#C-BA^?MI^Rq;J9~IwzrXF4Ce!6V6o@j z$RBE(ji=#%3;mH!hI+#^QY;a~7L{%zf??)YPTu5cIH#Y%U7#2WJ zDmdv^<9jP;eJ$JS5Zx?Lc@fG=;~e3Rar+91HtvZ_-1h`NU-Dzr4#0M**`g*cBtBSa z2=X20e^#ZJ9%CCxSjm4llbG?hG{{Sc$1NN&$S)7PZ3=ssIeGgH_4NY1R(K9vX z`AVPzw@+@hSJ|RxyLU3UR_MJ(c&MULIRtxTiJc6JqkAM>cFkib&WriC zso(%X>yNEpg^-yGb#T+pvcn{@JP2bYQ}Z$E0X=HkvV;8{E)roC%#M=W!o@^?F&X~= z#aGQgBD6G}A&&J%qdwbDB}<~@v+itQ0pE|@)I~1jM6baeeH>D1YLgzJ1J+V1V9-wOWe~^;`2j%#%h0 z-b`r=5T_nm00un>Amiy%d(o9~(HZf73-K1N6bWV=NZRhc&sJ6 ze*Xa2-Yj1bNQV6*g@Lz3!ybA0v-aspEsG(qZY5-qRy^bd2aetU07|=)16iZR!pqbZ z5+7iDezh;VC_9bXD`ACTUQXQO9e&kWGEpS2=RB@QaezLREV}3x81@+n0rv$9?ewbs zN0Fu6xVQ+RvO1pJ(!)7{Exo+Vjmr~)yyA^Cik+`!b7dKjfYCZi2p^eLjt8exNiA6j z@8SkavUY+{M<7rJOF0-(^vzmSz{xNrmmx%s#zx!IB#xh@ACh8sx?J17;s_%+^`SE8 zuPkISeu~6^tUG_d?OG?~#iPnbkuK6kSKgwilzRN`PB|2^L}kQT9r?{jIzYo|h)PKuVnG3!oS|F* zRQmeWT_tS0bVq9XjAr_43y9?|2s=krI2bQu+(_or=frR-oOJ{;qRHoN285sx5KHl+G^>o3t3y0B1ed0%;03V^{!mDHTEhdxTAi~PvZ45Zzdz!SNOJyRhoi)8)Ip=E|33f*eg-I=) z$GINWM;1BwM9zls@0z-eQ!6%A*u$v3($2Cu_@szUKGHTKv1ULp zSFe5CpK7%yrf1}7Jf>NO^-!P*0{03BAMf6wyJe`D(XG)85}szbWs2ffIK**|NA1Vfw2t&ve}(>q zLt4F_c8+^((MKak8mVlJql8uLa6V#vYe~1-Ir=X?7)4z|=#<+G$8#W;auSP;*f_^; zT#;B`DN(*P#5Jj|FXE6|q~2pOjIK8-N8dg8sO8Ass7S7)ODizw;KodDv94JE0F_7e zqwvamoK3sUD~VNbBzG&Ga&grDl|Pv$D;R`Qy9Ed3X22fRL|qpD01qg8vXV9xpxSn} z(iCCXra{7G*)P1ouL+1;eY#0Aq9(ia1Bxy)O)I5OD0v@{Kj&~vudP`qS7e@Ht>Oh z-~*E1QZtWwI&%6D`q}EvW}8r0t<{*#@?&m3RT%npAAD4;y?HBI*zPix(rOZ0KKMjy zwYuelfKRzNHB{7GoO&#+)tz1yotao=U>R%WG`}`O?dd5`D1_b2^|^mwW{TP+$qamG-R44DTt%a)O@KFtF_a*^cV7U!Qz<8NnlIv&b@ zGd~Bmd(>HGakpGf3uhH{w`Oc>aVVZeKtDD~$6hF%vnddF5V_viIL_L-*^^X7NX%tW zy))X4+bVa7153X-!0%Gl>=QPTp+;#6s9wX9QjuaZ{D@hZ3Ci_8zSUN|qOFaDrd)62 z5Gu=LSdvDB5->+NZ|IlQthIJao$&pHk=QlaLamL& zf0STk)f?58glLU9v_s8p1vu=g7e?IuDqcScL4nR7Y zq$0*+W!;aIW9|A?r2HacCh)L1AbJWS);2e*7{DM8QC7MQSmA;=DC##bBXb_O89${} zr1Z?_j?`Gm1d?vU&bu@IP=A})oOGghzj9FmQxB2A00H_?x(1Z0=huNyNnz715$1`R zNdOjXbs<-A{=%j^XiKBOxG`P`SvD3vVeSF^%m>`jI&{i3dyyUQptYC~vZS*WL!GD& z2IKG83Yu-C%HFJ7NFYUNEuv5u1ObK>K<9zn@l{pYCvUTsqi(kvlLK%iG40#({J8@p zShdGw=uvMPu>$&20GMv&zhkS=)o57MUh zRqRx84WgMH(F2ll6b?55o_&Y*sr-u;8wkAU^vIMUSm9xHk&W9csw3Q2^&{MA zJaQ$x2Y4l*MtlyW<*)~?4Ohbaiy@A+tizzd;wainsfZ}5GmP_}+xD#zu8PT=t?Z>( z(o5$4Gp6H{ow?_yuQ{qU?pYQ)c#vDBK$1afS%Y*NvN8G!R{sD($=S*am5Lapl;IHu zIO;&E#i~u0k~`a74}p2ug*&)7&N0yc0D8BJDEpzMgpD&P2<%^TDCl99YK<)Y?EHm@OYm;*g>OkxVRbwxiXKTPP{W=%89${=rD?VGA}XmI zWV)Vv5~4hph$@l6+*czXQ<|ikaqF_wkjGM*C{o_op>&Ep%@9xF?#5WQe=*3%r&^Us zDEogxkKBW}m7Z%?m7C@)M?RE&rpQE;ObSAT923hQT-5yyD3Z0^@sLLvvj<)WeCP9i zl-rU>t!Rgm5G`UM%Wh&7@yiUJfA3UXBFCxjEfHfV<+8$EzWC&t(^@K%J6a;jVOV1% zGXhx^&(U!Iu?D4%cR&l|?1M(2Lg2LrWa z-McQ84jd#Zm`G7BX=AeboHozG<}M_GC#!^C0f?nHU1*P zcMwTGnEwEC`&O!3Mr{?1BHmC50|1lPwL*Fc5?0V{5;GD>{ZF+)qC~xwvYn);`F?CS zPrX%>MEr2>_-`Z)==oAt13ht3S5!y6mHz+`T>*6|XIUdIL1yET!TV&^i(QmB=&ECe zHk^edjo=OdC%3L@I;$$lSejdlresZ$GI>a=!#E9+e?UJ{Yi+!0+`XsfO4$mrh$|P2S*LdqAE(cC9Iv=em z=|5nZTAJnLk)H4I)S_UMHF(7VngT33G)Vi93Nl!mj$H zVC8I!M4I8HiuNK*GRPBe0Kf-aj;A=zeMMQT?1akY-HeH-wcJ+{PqZwhi05M{>Gl9q z>t%S+E2X20b(8pP$&fN~NvLX(q)8d!H#1uct*E~&sTesf6yrGb!9S%{t?aryUc?eN z91spk1Fkq9TC)$Kjhqi8S7tyIkf0OJ03@2K-H>)Amuo0J)N_xmN&|?<7UK*uaz#mG zacSg7+8G%~AD5bf8#u{6=L#@SAZ8u#xgCe4M7js7 z%a0)(sAgaas|DzBl4@l5k!M&f#8D>W%Eq9abDVSarBc~+gqP<8W8@j&ng&H(U`Dbp z92^R|GLXgs+pyej=k400gh<=Mtt)}k98`HOk>%qaUNU&@Dl9RqYE(+cxy4FlS>8L3 zF2%P#(oTAHBh%8QbVDIbQmm#;>$f9;MxSOw>morVxWMT{L~zumBG!G(c9F>I^dg9^ zN20Eu6g5j(WLJ_YuuQHx9)y0Cy(b$uypxvqT79h1L+7bk=Gio?xiNw5>+MjYmXUF_ ztkGO*cQ+Hu8pk+c6F4Xad*kRSR>9`?TGJ8;!-<$jA=*ZEpP=@sSliM?d9I0j#Fp2? zYWr9lry)Y{dB#4~n^um7oKfD{Y;UV$(iKHAwk;07ksdk+asv~baH>O1c z4>DVelD=ayNE$T@oQA8ZzO2c?6)TSpMQveic_ZZBPEsW4uyx7%S4zt!jMPzZ@N6j> z+$*pFh5;Pl^sY>uotT!19aT_i_i?PO$OhfWJ%wgW`YKv|gm%&|lvU18B~RD-)#o=h zV;GKg;sV60(MH^lr$5%A_DdqQxTm?h)2t%_$yL~=xhDd;VNp$)Nn4{qo$S0J;Zb0! zvR&LOH1Cjb8-jl40DBL5=eId*)=febjMG!uZV@F&8|K`hNmez}1ll;fll~hL&1~Qw z;xuH9$DqzD7QSYV*guqzg8AaT^4?Xrd@tqxP#E?8m77GF)s(jjcJf_peFR zQohaveIoB2gMWuw5|A&+D>2K>E;lhggC`Z>$))nHk8%n2#ngn8h?~yCMvRES@VR0} ze{OxNO@^$3wTf>fKGB%uXptCvzGR?DZ~Y})x>O8*`@OVMe>LQ@yB0$ew1yp z^gFuMA)4gM5iPz=ktTA{sNf9r9<`-gvZ+z#DCBFK8%Af6N#l2r1~?eW4V?A@v+|?v z8_^MYrxw&S&B-bz!6%fe%8t1sA+v%`54r7{x>`mpTP5_{aTTja8+mS3qK7I*&`tqA zL(l&J6IHs=qCmEb6w51Q!x$09qmlp|6X}pM^)ybuB3Tw8@}-Z-+%P0Zlmw4OkPgD9;lPbv@WekL59!U4={{V`HT@G!n zcS*OX2-}G5$NlQRLhR`&^6vbXZjq3Kk-H!U$JZ3C(=%*yd42x?6$Fv0vq0b|PemM` z(}DWcoVJ=Oqo#;tyB3HTfKFM{lgT3)ZsgTt@|J4OS2qS5c+@CsyM-Q7jz|RUWB0}f z-jexO)ON{>GQLq*3$&g~6(D15nE7&ky!|RKw7%ICIntwrotAY(1~M3rQS)c+YO(eu z{SR_PUPqCGD!UvhJaTxz{VLbwk{eP|(>fpIsGQX%^NdRRy?r~EUeVp@^5VC5!%K}c}#al)Wc6+zEGcW{( z$sI*B%*!o=Dj=Rx!0m*bp7|kh`_)mjO8%t+Op2vQ22cp=oO4>hOwM&%Qx)8@MfpQF zUvpj9=gCt!CD`vkn3+{}lKcVbSbBv@%`x_C{vNe5+X4VBk&*3#TrJx@2rUn8Ekpc( zbjK&wqRY_XtQI);Duc%(u^Vsn1$g3sK|>ZO36R){%m`F zYPP{1F36ai44+Ck`6WG)`eeJfCj|3Zd848Xv0Jl82M4FM4ur;%$_%>+KQYJJse7Xt zc37;LRxz}2dYsk2BWz>jm`E_AC3^~n&C?od03=`{5RZY^oRiH~PeoZ^hfs!X8N_Oc zU4jU}>WT>r-+pmddsakV$os8I6@-K#Mbv$e(OSjc$^%V!;c#aSY}h-jsfTaZS4w4-)PY_mjh0NL`D zLx4xGT+|~(N8My>OyN{6Ip7+ED2<(hMimz!OAL>5Q_>{}<0^pkW&qKWSW@9F67ksX z2?>iMxi}5`3N2Yz;DXcPeM0$OS7PZRxhvOUIKUp~tvKJ`g0@(1B%bQ{M;u}mNc^TN z#|eO-dz_j{w<<&=sB!W@t7{@gSSfTpfzKKGRH|PoKT)uNHl|*Gm^uW0dV+pz{f0jE zAM)8gG)C&4cu8(w_-G^tJ;7xl@$|v_Qr~Q^(2KRT5?Hk462@GCyYmh}{edUzR*JaU zUnjjT`{JW{llVw~fP{bd4?B<39A=}H?6nrHHARMk)3X^fIA_TGpo|gjDzD^LJ9Kco zVQplVf@m0e-c0u8HmJt=Q-iUoXe%Ow!LWDHKX@6Yu)eMY^(SSzx+PI^~8l z843`8m;sKzKslp)m`ah(ORP#8p^;ny+~5<(?fq$cvQff$!$!8zMj7xJ`h6+ZiN7P8 zJ9b+%ic$b97=zzDkx^QrFLph*`4otV4giCj&vwV@s<`w{Q05}|aoKjnHVIlR@J1w%u=X1Li66nz~M#SNw zCmYo~&6(+ejw#l`&s2qN?h@7k{{RmZYN*fDf(Jj>^rQJ*E|5;uvNB63Bl3>)SCL$j z{S=OI^)+I)JG8vFwzaUD_57m{CAS=f03HDDa%iWiWfKoqZiIk z+N(`%mqff9L@e#sY2JY z9hi^iJ$Cz!gWQ^z^3p5W5v|}|GRG>+BSnQ6o^ZV5JQcVSH?p~J8(xQ&>49C{eK&W<*A-{c1p7z)bS)W6H4F2p{K^-11M9_C&(MM0t>B99 zRK1=Dx3;mgkKt8EGD>=2ckWNpr8{n36$)u3?sK%hS*6opzJTwF<==8QQo|~^_9Ho{ zjeM#5{{SSr-4XY8uUK= zhQ=$4ojy&78fl(XC5t?PdS$u*Ndp+C1!SUmD4+k z>JER>w2sW#;wLv3CDeSXGoN58TfKxjwQao*QH<45qCLnC2=D1aMpq;F8wX69j|Ex6 z`bF6kZWXqtBiz;PbY&tk?Y2k+M{1GC9<+Msp)03Gs|jZ1h#Vf34@}lQ394Fo(CtuF z+!3{p1a@y~C+<@sv_sozw;F3g(&`HYGATY|seB%p0=JB}^f{bpCGg~T7m&0XgffTu zr3n_&2Xo1(bQEk&Urvq@HJmcXa}fjnVZqP8wOMPTvqU|P*>0hN=GZ|TV+B;?Fb5+a zrA*poajlZxCe)|D)pYwiCc#prS05rSM_ zhd-x1XyWAW*rSyWwY_ISveEBstuKBiMuYjl8IiHMR~?2a3=_1HD=e|CGKr~7e9b&; zbVLILzCq@?;~$ljPi4Quw_aJ06Tw_!xSHA1321z`3@@g)Kumc!4aYT4`B7)F)K47t z{Dg^6V4c4)Be1A@3q*dY9#YskSqK&v@msOxyPl3}$HZV}12 z?JB>N;N$B{rDC>1Tj>aze4b-5k|JLLeqf+=1Du?mm1xgJTG;1PSmD#H?k+{gkS$_S z8i3C%Y=eM1nx!b%glH?Y0Y8;@ZdqH&VC+4l$0L(Yx|e z4#^vsAxk84{6$EJCwJyz4{rPtKIW+UwrNCtqzElwELHArBDlM98UihpbfZe41hn&ob~HbcI}ELr-`C+%rHz~;P5IW=(-n4xsJm6 zX)g$CXG6OKJnd|KiK<8CcFC_}t&Q!~{gTMh6|uLt*@AZEp9g3?xWKD9w;r@EnP9Vx zU~7o(%EcV3BxWd|d}Wh`Vo1p&`A=%Jbob`W+P;XN58rvZPMUcT+ir=DagY_W$8c~z zK~W2FkJJ5^bgXX+u(pk*1iHe%o1QQ_e@d0s%Rb17t_sQKF5C$Ye!jJ9D#tc=MOdzJ zmd_Pd%c8++DwyB4b~We<4_~cg;@Up6_=6+Lfwbk`qay`P;012Z6SsTQ3T*S z!h?cNzy?RBT9>4f?2he_@);dnL}|U`SkPqUduQvxH5(?$9Tp@PUmRLFWsH3ie?G?O#c8bG2G^~k4FwyvbA9% zNg-@?;8LmV#S-ytjP7y)&N$+&M515f*{zur@IcQT5Gs^vh>OW&iTV7ioO>VjsZO?5 zL@mXMxI=&f=CxC$qaHRm@cxoT$YP@a);V%HBW!TlrfL5Gz=ZR`7zZ6|3-Wd)NOUF{ zR=^qP4O%-aEZ1ypBvd@NKq~eb2X$)mZk4ikHZTVR6i>;Fqh)^n*juBA<3BM6in=*w znq*nIMFbK7?T+N>I&zMYUf1}HwZ=I6UxzM!sxQwB$8?qNJ(%6YLKr+C4nbCyMLjoKg8KS1-+4BmPQeV_-+cQ&#p64-F}3m zag9_2at_itk3CNvPe3X@p^@776GZ|)Pv<3%%ydsI3np`>DU-3<$yEkwGdCJaw${KLoFFj-z(p z6&<3&ti&vg!0-+*Ijc9|FLFlLK2pUS4WZ*Cu)$y$;15imGwGVLTBI+?`Mj39WsDD& zFbT)yEx|w5mbq*0!{~s$-z&>LczwlGbOQhn)B#TRPtb3w$`P$Ta0|!0kTIUXVx~&y zi#lHFO&zM3&=qWg!>{|mq?IBQ+3!ue+^X_|(J&y6nd6V%p;9c}kk^+9{w87@TMd_E z`FZ1ywHI_$oYJI(T+9$`Nq;%dIqW|{R+ScsF>!1s6FU$C4ha3KtzDCKp}aRRtTv`K zXry&b**=G#wL*GS8uuDr%OlMyZY3S^*y!E*dS<1BMnuIXSi`JPo!Q91UwVYMLHnNW zE~D~eNhBz-r*rN|>GjSkZ``d5riGQQUP8mkG6K)g_Za(AzWf8RB59D0+0K2b=E8pd{G^KDU_4EOI-F2d-JlG&~xMxQGhZj_9%{*zk_PAt9+tHLOnp_((M=W zNA1(@DAAD|LDpR*?ty0j(Nz`5`w3nTJb#{@X zzySXMmp+)OgrCaF%gFZCJ|Y>Od_@#1&rq%I#o-N8se?Z^|iXp@XaEplFPv4XEmZ%O3Y>1R=2tG z??sK`Pc6bqu#~s_!WiEqr=t=(;2OG(syXELO=;SUmsf2#7YP%(x+BPW3-YKSanSR} zb5&Ap*`nx(@pbHWR<0r&t|gnvb}Ny9GI9E2?^?ljXOYnvqp?_&M8w8<1Ex9YMyXL~ z77=o>D@VU1e!0hQek&$ynZR8&LSWp1^TaM4q(y6gU8U$L~SvToo({tYU3E}GAd)>s~1jCkjlkQF^{pSWuiNc2qOS+Y73*J zgARUzppm4h&)n3I&o@yZf+6zxj7zZY02mc+jM)!7Upec=8#8E;umz$Eo~(c0?^Js) z7CP0n7;QA@NBjeNEu#8$C)8NF?|03de&Idri>Js zE2>?khLdXquInYsd5qY>LH_uvC^=~(OQOeSEwnEWU269TCAv1}$qmQ{xAy&O9BH{E zjb%`cludT&UqsV`s1mU(?gl@XrFP+pQgm}T308KOx)d z@=pTzi!?a1uM~@|%!zY1k!X#*NZ#1(*pvJI zm6O|}awV@}^R6Oy+>w$Ml#&S@2kTk2;gQIdWJ~L9K30)(vKYi$PC)CrqE6|WMOi&J zhAj0BKIX^D22sm0e9fJi108$RDam!(CBiJP>K7IoEVkNxy^*}Uh06J^Hw55k^fjy< zt8Bw7Nzx*9*^A94=Xn}dURklT)DJ=WRhg35>qIWra->^)*q9Y6cMfWX@VXu77js%! zTt*$kKH_u8=rR53k(P}TbUVG%o=qBAl@ZDicDGFb0JB;rWil-qHR&yJYa4APQNuEf zf=h$f>zd(xq<2K)Bn(2NL~mjMEHmHIkJ%SP(H7|zJPek36gfH0cJ4p^9+fG0E7BnE z?k>&Uy|k$up!~}xMgykS?0M#rzL_+Mg;}JAP|~6zs-m`VOE=8e2ZMq7deOJChYt{G z;AzT`yZLcEcB`Gh%7F}O+3UA0oZ#mjDqFAM&Pw!0={8MaYOu;87Xf^iFs{Htk`5@u zBSV?o%H}xB5Q;(!-~vY^{{T;=L+*_RvZRYNa!3>fjbVpz01y$7<+yVdvun5Ql9^$W#sWZBfq|>T0`6n4!d0#akz+=B1ZIvpI-He<;uEN)|ZypmD)1$prrZT9%5iSk`$K z;zg24k+2_jFnWKl6s6lBkG~BRaDb$_lY-610OyS7sTEtGNceKj;$1EsIo9LPoy*GZ zIgsI1Kt1Y>IW8;79c=gFIiA*eZ7n48VTsXEh8r)p5@7ll{eY`ZqP|}rZ}$f)4XBk%WP9ecjZw*wSqEckB6e(n&U*1h zx3iz4w9ZHYuziI@rS46VT5~ywuNfl%Vu_nU1h&QUrF6;v<{qg zry{BwB=m~~Rwr&(lUcWH>4a!`bvae+G18)}v(U!#P-v8{dE3V|qK=9=Q0qgy-!e3Z zpxw#NM_P46##T+j(I`BEp+g@`nyOS?l@Ax(B1j7JmFPS1+}4rk;?3EgOLG2Z-J}nC z=u64TXEQO`miV;uFWQDcL^!a{J__o?MtVvg3z$~n&+s*-j}M{TEeKnLEa*<_0zh`X5> z;~?~`DD1?GNN+MTlkJL=riiJcCgXNE98~>EQ0X@dY$i7!zf)4)g_4?FUQ}w?#~nJ= zO(HGD@~c0ZR4T9}o_k`YAl`^QS~Dyv(2c5iAN3PSD_S|^j~4J8s46nNbKan>GU;SI zt3=)TjZo-@jvBkCm6B8w#|Etu(s~)_K$%(Dcp%{VQ^64|uHW#RK?R(s9kGvEq`Edj zI|)p45J#A~=eh4uY3#B&#JieiDUpJs9S6VeY9r-_GPuLs2(z{@eqw%4 znX|ZvaSJx~0wc%rjFxY1yj4>{r{v=IE~>yOb0FTpfCoHt+|(w?p{&A3hBoX0+&#|~ zH0Y8d?oo59K>-;E4oG3f2S2S@Zd6h9H@%&rwrC_IJ22xtOAbFzN|`-T2z0U{F~-zI z9$(o;rfAnCeMWQpQSDc`E3zL|m^3m1N6I#?!HfVfIQmtV!_q3K zvfNz>0~|yEQco2>nVT%HWB&jH5SflqG6#0zk7%+XuWyzOkVJ6joKe?AHbtd{?4f3m zIwKwqGoSV5iECn;Egm1VFa~oxtk;@*#>Hf7==q5*DnhXJw z-`=A1340`Uun8MBT$OF!`0Y^csShNTmA(saC5Pn%jxSWpte@s*-dL`)(H3&9XJW)uop;E2CzD-M7qOJKL?)6h|BZy>_ z=PCgJ3}YO6Rnk^bIug@fhGj)5k1HrLI}wV9UI|XiBoic)+eDHAN(CE<&fFe8SHL6xANi7maU9|#y@fmRleFDMs}8-PMc?M2Mut+WOfCaLayWeMOr;1ypbY0 zOEDzq%@Y$WftceMOynQX3YP4x4t49MgGZd(MYSEUqdcGY){}3GqCAoMgbHl!E##Il z{{Ru^NO90G9DNQCG-*;yi`!%#zbLrYBAKF&AQ4DdeF^zg`})?2+p?nR&AwN6Ic$;7 zw-s3zfo9X>!vWX5X4$$P-0l#$LzX=N{=dCJB~!&SJ+;P}a*j?S2o!KbBNgZDMQslZ z!f#{*UR~a|BS~<^DG-Ec$INrd`Mp7{A7)i$z6g>Vconc8a`T^?)1Tg`{-%hnc&0M) z5aSUmmpgg`)2Gw=){xS(3HEc*?aWqaGBBzS9{m2bSuV7YM8sDa}#GIZU*87JG1y+>Exvc;w!*H1qnwI#ROG5vQvenxoYh$;SyAGN8CgkYJx8&tB}7S#^iBr$%M!$#{+Otb zR#fF7GEWKQ<~HJ`G6_93H(Bj&RN&(t^%h+SiUg<7o_#7WWsi4J;$xB68lNPLCR~*0 z0V0+`=g8d5%nnXRTAM1+%H|xF} zb@lb4Z3hwKXtv-a*2s{@Z!QUT-oSsdc&l=46r_s3ifkg*wIc0$_XtA7k>eQq4{~c* zHny3RqL{|VK#i`~Ow;XRG8up84?uB~{*`G>w@j>Y+tF9?+@c>5y_s<$qbkUKIqCiW z_0@_kr!yHkkmto(pPyrGYP>@!UOVj{G5-Mie@f33De_(sc}+-&*H+$bHr&TH3c2}D zBl3^EZRyiec4L>M$XKJhbsk%XMc^rZKSNzdJzqn1if=b##^wJ2%SS|{*<$eI1|>IA z5}{5GM|$MXv$Gna*`wY!nLL9ymx9Bv9qW^JZk~qHv_BOpTX|@bZd8%^+v>o2o^erW zGL}#25y=*ssPH}{J#p5p zmTLOZ7~oj+`*}3!2k>V#=h9@yGOA(#>jtC8!DDyY|q4<@vb zi^!x5%1KS5{r9WI*Jm`Hnw{$Go&+Ds7g6=ia<$RuBsqx{e5NWGvnuD%dsL;deT`ze zd9{0d0D>sQU=DMaZh7xjgSjCsM2yoXXV&L)%fi@F-1^kZTPxXZn%pOx%CM0o#8#g? zdx(gIW?bjKXyaG;rTS=(WJl|c(dy}Py)CT-qCU;XPj0l5so%0HmBg>hyUa%?lDp3y zy$9Nin2s#aJ=MwR$`2#he_whf^D@t*MruTx;~J6{JOPuF`qKABNr<6S7nOiA22Zcd z1sc0Wk>25p#Ql^$+f?sG5L3N z_2R6R63Hb&6}&1iL2}0h{GqOW7L?F9Sq57wqD zZ|K80X`({6LP<-9nTu{2$t0SLYV5l>`C&^kGzKJ95VpJgYIL&DmR!EJwkg3Po zx+1L1_W=!sBil6%Y$MgfVn8w8lu6#+X2?8dvy?$29J|#?9cvjDM|A~*H!IG8G^A9|TB5Tx#lRiHO(Zme)-mtj42 zjCTEN7q>@DA7`t18d5jlkt46$IR4cUe7iTJs&N}C@tpHkS|Ro@iG)m&72PD63V+Fr zay|K|TG)QW;=Wvwx*Ru|f!`goR=Odt1YGkOF3fH+oiR|IvM7<#mN^8@>6O^PE_!tD zQ{9!8k=Y!y`^OuX7#%7+*>3_|&dF?De=r1R*9N44j8_s)jkuBAKn#jsU5BrU`hXSzl`bu@Jrh#!nS$y$+8TS!8g> zCp~&~6`Z;V?p)hg&he6DXjOL}*#n>6tIZ*ncFU!rm2YMy z*D&r##~gJ30C}a+omqXph859P6p!*o0y8lsKqrCq%|xHdT0MhWta20#NL9{HQgAxe zn%xUM-NvnMBs{Pru6tsVj;vjkses))fk0=N4m)Fy?^Ukf!Zc zRc+A?9TWKR+lKybYU^|eyOa`nYT5aDUu>}-+NmXFiJduO_}P%gO0MT4JRB&%{mn{B z%D#u_+w5Z?D*1NN36XQZVO*2gRHRjqx4M+GD#pWy_vwt9(lJkFa*(=ID}8!`enxjUzkjt$(FzNnH2tRFsiHuKCWsd&|Qwa*Om#MMkY_ok;VbfPq4*ZZ8peiv^Tdcc|GZo zun~$V9e^M9sO`HARS~+P$#o+EF38|!RZL`O9Zf{p6mpofw=QI2$!!`HPRApkrCsgY z@Mg$A60#<@^2P(sgXRbFjN_-SJJsHbqm)0wl!4Hk;-YGeB3P~1!zv&-EV<9rpY*Iv zqDcHf^ETjNqvTYjvRPf%R5Uqk@7%##{JE}-NXH=sp$y$x^TIR6qa0%uE2A`7w6-$q zR>a_L!ynxL0BWs##h*n}TDzN3)@HSK2?#A13OfuR?^jP$VD~B|>|)9VE%G0iZaQFA zZ*1s_JINBi4%RCdxQz_yr@`eBS^*?Ht}delE8Gp+hCg6Yx7#&QVGazLs{ zY0yV2H{1d+1xhdP$M>m^u`FwHgUt5niq<7Yl3`_0fr3R#(;#^nA2%FqK=F24;MZ#v+NAOIYM%ydG`x8zpkqHV zKYUcKi5gps+$a4ie{oMClG=O!0K%^Wx7w;*9HKwP$Nf}DvK-DgyOZlmC83rE@x?(0 zNq`722LluXcw$$$i~ak&*sZ0Nl+(vAGV zkM+3z9>#GS9LUP#{XjiGPtuK2Wg8&jw^h_&c+S&o+tgqX#0>I2)wFcXnzBDt)UI?L z7g5!%oHgysxZRDSJdij8>sw-nH&4l)Sv+xV86>wab$J`j^Gxyr&Uq)A^my@$qmPri zEV{e_^;iR(q*m*-M;wuy)(Pv6xusUfO>Q8TvGPvY2>pd?fX^>PGD{?9_-@PeIIe>W zqSN55C3SgjUU^7pmmuRg;F{$1GjXJjuTLIJWTw9acG|+}&@R}ZgkCxKhQc_A@KK zSAVC*ns#zze=#$mYIhe6X%*86gwQ)S{{T_Yk4ncQFAnIkT|&0=q^t8gMCT{iaahSK pv#J8xa}%K8?NVF0$jPduqefP)ELZ$RSh*_FXK!k<(?=^u|Jf~A6(j%v literal 0 HcmV?d00001 diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index 3939e0662..9149391e6 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -40,7 +40,6 @@ def test_01_colllections(self): assert updated_collection is not None collections = self.visual_recognition.list_collections().get_result().get('collections') - print(json.dumps(collections, indent=2)) assert collections is not None self.visual_recognition.delete_collection(collection_id=collection_id) @@ -97,7 +96,7 @@ def test_04_training(self): assert collection_id is not None # add images - with open(os.path.join(os.path.dirname(__file__), '../../resources/South_Africa_Luca_Galuzzi_2004.jpg'), '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)], From 30f7b4c2e226715f629ab51f38a5e5cbe2817979 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 2 Oct 2019 09:01:33 -0700 Subject: [PATCH 093/455] chore(vr4): Regenerate and update visrec v4 --- examples/visual_recognition_v4.py | 22 +- ibm_watson/visual_recognition_v4.py | 588 ++++++------------ .../integration/test_visual_recognition_v4.py | 12 +- test/unit/test_visual_recognition_v4.py | 4 +- 4 files changed, 214 insertions(+), 412 deletions(-) diff --git a/examples/visual_recognition_v4.py b/examples/visual_recognition_v4.py index a9ddca0b8..93cfe26ae 100644 --- a/examples/visual_recognition_v4.py +++ b/examples/visual_recognition_v4.py @@ -1,10 +1,11 @@ import json import os from ibm_watson import VisualRecognitionV4 -from ibm_watson.visual_recognition_v4 import FileWithMetadata, BaseObject, Location +from ibm_watson.visual_recognition_v4 import FileWithMetadata, TrainingDataObject, Location, AnalyzeEnums from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -authenticator = IAMAuthenticator('') +authenticator = IAMAuthenticator( + 'YOUR APIKEY') service = VisualRecognitionV4( '2018-03-19', authenticator=authenticator) @@ -31,11 +32,26 @@ collection_id, image_id, objects=[ - BaseObject(object='giraffe training data', location=Location(64, 270, 755, 784)) + TrainingDataObject(object='giraffe training data', + location=Location(64, 270, 755, 784)) ]).get_result() # train collection train_result = service.train(collection_id).get_result() +# analyze +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: + analyze_images = service.analyze( + collection_ids=[collection_id], + features=[AnalyzeEnums.Features.OBJECTS.value], + images_file=[ + 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() + assert analyze_images is not None + # delete collection service.delete_collection(collection_id) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index d59b06eef..bc8c38086 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -105,26 +105,22 @@ def analyze(self, characters. The service assumes UTF-8 encoding if it encounters non-ASCII characters. - :param str collection_ids: The IDs of the collections to analyze. Separate - multiple values with commas. - :param str features: The features to analyze. Separate multiple values with - commas. - :param list[FileWithMetadata] images_file: (optional) An image file (.jpg - or .png) or .zip file with images. + :param list[str] collection_ids: The IDs of the collections to analyze. + :param list[str] features: The features to analyze. + :param list[FileWithMetadata] images_file: (optional) An array of image + files (.jpg or .png) or .zip files with images. - Include a maximum of 20 images in a request. - Limit the .zip file to 100 MB. - - You can provide multiple separate image files by including this form - field multiple times. - Limit each image file to 10 MB. You can also include an image with the **image_url** parameter. - :param list[str] image_url: (optional) The URL of an image (.jpg or .png). - - You can provide multiple separate image URLs by including this form field - multiple times. Include a maximum of 20 images in a request. + :param list[str] image_url: (optional) An array of URLs of image files + (.jpg or .png). + - Include a maximum of 20 images in a request. - Limit each image file to 10 MB. - Minimum width and height is 30 pixels, but the service tends to perform better with images that are at least 300 x 300 pixels. Maximum is 5400 pixels for either height or width. - You can also include images with the **images_url** parameter. + You can also include images with the **images_file** parameter. :param float threshold: (optional) The minimum score a feature must have to be returned. :param dict headers: A `dict` containing the request headers @@ -146,9 +142,10 @@ def analyze(self, params = {'version': self.version} form_data = [] - form_data.append( - ('collection_ids', (None, collection_ids, 'text/plain'))) - form_data.append(('features', (None, features, 'text/plain'))) + for item in collection_ids: + form_data.append(('collection_ids', (None, item, 'text/plain'))) + for item in features: + form_data.append(('features', (None, item, 'text/plain'))) if images_file: for item in images_file: form_data.append(('images_file', (item.filename, item.data, @@ -175,12 +172,7 @@ def analyze(self, # Collections ######################### - def create_collection(self, - *, - name=None, - description=None, - training_status=None, - **kwargs): + def create_collection(self, *, name=None, description=None, **kwargs): """ Create a collection. @@ -194,16 +186,11 @@ def create_collection(self, contain alphanumeric, underscore, hyphen, and dot characters. It cannot begin with the reserved prefix `sys-`. :param str description: (optional) The description of the collection. - :param BaseCollectionTrainingStatus training_status: (optional) Training - status information for 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 training_status is not None: - training_status = self._convert_model(training_status) - headers = {} if 'headers' in kwargs: headers.update(kwargs.get('headers')) @@ -213,11 +200,7 @@ def create_collection(self, params = {'version': self.version} - data = { - 'name': name, - 'description': description, - 'training_status': training_status - } + data = {'name': name, 'description': description} url = '/v4/collections' request = self.prepare_request(method='POST', @@ -297,7 +280,6 @@ def update_collection(self, *, name=None, description=None, - training_status=None, **kwargs): """ Update a collection. @@ -311,8 +293,6 @@ def update_collection(self, contain alphanumeric, underscore, hyphen, and dot characters. It cannot begin with the reserved prefix `sys-`. :param str description: (optional) The description of the collection. - :param BaseCollectionTrainingStatus training_status: (optional) Training - status information for the collection. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -320,8 +300,6 @@ def update_collection(self, if collection_id is None: raise ValueError('collection_id must be provided') - if training_status is not None: - training_status = self._convert_model(training_status) headers = {} if 'headers' in kwargs: @@ -332,11 +310,7 @@ def update_collection(self, params = {'version': self.version} - data = { - 'name': name, - 'description': description, - 'training_status': training_status - } + data = {'name': name, 'description': description} url = '/v4/collections/{0}'.format( *self._encode_path_vars(collection_id)) @@ -403,25 +377,20 @@ def add_images(self, characters. :param str collection_id: The identifier of the collection. - :param list[FileWithMetadata] images_file: (optional) An image file (.jpg - or .png) or .zip file with images. - - You can provide multiple separate image files by including this form - field multiple times. - - Limit each image file to 10 MB. - - Include a maximum of 100 images in a request. + :param list[FileWithMetadata] images_file: (optional) An array of image + files (.jpg or .png) or .zip files with images. + - Include a maximum of 20 images in a request. - Limit the .zip file to 100 MB. - -Minimum width and height is 30 pixels, but the service tends to perform - better with images that are at least 300 x 300 pixels. Maximum is 5400 - pixels for either height or width. + - Limit each image file to 10 MB. You can also include an image with the **image_url** parameter. - :param list[str] image_url: (optional) The URL of an image (.jpg or .png). - - You can provide multiple separate image URLs by including this form field - multiple times. Include a maximum of 20 images in a request. + :param list[str] image_url: (optional) The array of URLs of image files + (.jpg or .png). + - Include a maximum of 20 images in a request. - Limit each image file to 10 MB. - Minimum width and height is 30 pixels, but the service tends to perform better with images that are at least 300 x 300 pixels. Maximum is 5400 pixels for either height or width. - You can also include images with the **images_url** parameter. + You can also include images with the **images_file** parameter. :param str training_data: (optional) Training data for a single image. Include training data only if you add one image with the request. The `object` property can contain alphanumeric, underscore, hyphen, space, @@ -672,8 +641,8 @@ def add_image_training_data(self, :param str collection_id: The identifier of the collection. :param str image_id: The identifier of the image. - :param list[BaseObject] objects: (optional) Training data for specific - objects. + :param list[TrainingDataObject] objects: (optional) Training data for + specific objects. :param dict headers: A `dict` containing the request headers :return: A `DetailedResponse` containing the result, headers and HTTP status code. :rtype: DetailedResponse @@ -756,7 +725,7 @@ class AnalyzeEnums(object): class Features(Enum): """ - The features to analyze. Separate multiple values with commas. + The features to analyze. """ OBJECTS = 'objects' @@ -780,8 +749,8 @@ class AnalyzeResponse(): Results for all images. :attr list[Image] images: Analyzed images. - :attr list[BaseError] warnings: (optional) Information about what might cause - less than optimal output. + :attr list[Warning] warnings: (optional) Information about what might cause less + than optimal output. :attr str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. """ @@ -791,7 +760,7 @@ def __init__(self, images, *, warnings=None, trace=None): Initialize a AnalyzeResponse object. :param list[Image] images: Analyzed images. - :param list[BaseError] warnings: (optional) Information about what might + :param list[Warning] warnings: (optional) Information about what might cause less than optimal output. :param str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. @@ -820,7 +789,7 @@ def _from_dict(cls, _dict): ) if 'warnings' in _dict: args['warnings'] = [ - BaseError._from_dict(x) for x in (_dict.get('warnings')) + Warning._from_dict(x) for x in (_dict.get('warnings')) ] if 'trace' in _dict: args['trace'] = _dict.get('trace') @@ -852,340 +821,20 @@ def __ne__(self, other): return not self == other -class BaseCollection(): - """ - Base details about a collection. - - :attr str collection_id: (optional) The identifier of the collection. - :attr str name: (optional) The name of the collection. The name can contain - alphanumeric, underscore, hyphen, and dot characters. It cannot begin with the - reserved prefix `sys-`. - :attr str description: (optional) The description of the collection. - :attr datetime created: (optional) Date and time in Coordinated Universal Time - (UTC) that the collection was created. - :attr datetime updated: (optional) Date and time in Coordinated Universal Time - (UTC) that the collection was most recently updated. - :attr int image_count: (optional) Number of images in the collection. - :attr BaseCollectionTrainingStatus training_status: (optional) Training status - information for the collection. - """ - - def __init__(self, - *, - collection_id=None, - name=None, - description=None, - created=None, - updated=None, - image_count=None, - training_status=None): - """ - Initialize a BaseCollection object. - - :param str collection_id: (optional) The identifier of the collection. - :param str name: (optional) The name of the collection. The name can - contain alphanumeric, underscore, hyphen, and dot characters. It cannot - begin with the reserved prefix `sys-`. - :param str description: (optional) The description of the collection. - :param datetime created: (optional) Date and time in Coordinated Universal - Time (UTC) that the collection was created. - :param datetime updated: (optional) Date and time in Coordinated Universal - Time (UTC) that the collection was most recently updated. - :param int image_count: (optional) Number of images in the collection. - :param BaseCollectionTrainingStatus training_status: (optional) Training - status information for the collection. - """ - self.collection_id = collection_id - self.name = name - self.description = description - self.created = created - self.updated = updated - self.image_count = image_count - self.training_status = training_status - - @classmethod - def _from_dict(cls, _dict): - """Initialize a BaseCollection object from a json dictionary.""" - args = {} - valid_keys = [ - 'collection_id', 'name', 'description', 'created', 'updated', - 'image_count', 'training_status' - ] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BaseCollection: ' - + ', '.join(bad_keys)) - if 'collection_id' in _dict: - args['collection_id'] = _dict.get('collection_id') - if 'name' in _dict: - args['name'] = _dict.get('name') - if 'description' in _dict: - args['description'] = _dict.get('description') - if 'created' in _dict: - args['created'] = string_to_datetime(_dict.get('created')) - if 'updated' in _dict: - args['updated'] = string_to_datetime(_dict.get('updated')) - if 'image_count' in _dict: - args['image_count'] = _dict.get('image_count') - if 'training_status' in _dict: - args['training_status'] = BaseCollectionTrainingStatus._from_dict( - _dict.get('training_status')) - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'collection_id') and self.collection_id is not None: - _dict['collection_id'] = self.collection_id - if hasattr(self, 'name') and self.name is not None: - _dict['name'] = self.name - if hasattr(self, 'description') and self.description is not None: - _dict['description'] = self.description - if hasattr(self, 'created') and self.created is not None: - _dict['created'] = datetime_to_string(self.created) - if hasattr(self, 'updated') and self.updated is not None: - _dict['updated'] = datetime_to_string(self.updated) - if hasattr(self, 'image_count') and self.image_count is not None: - _dict['image_count'] = self.image_count - if hasattr(self, - 'training_status') and self.training_status is not None: - _dict['training_status'] = self.training_status._to_dict() - return _dict - - def __str__(self): - """Return a `str` version of this BaseCollection object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class BaseCollectionTrainingStatus(): - """ - Training status information for the collection. - - :attr ObjectTrainingStatus objects: Training status for the objects in the - collection. - """ - - def __init__(self, objects): - """ - Initialize a BaseCollectionTrainingStatus object. - - :param ObjectTrainingStatus objects: Training status for the objects in the - collection. - """ - self.objects = objects - - @classmethod - def _from_dict(cls, _dict): - """Initialize a BaseCollectionTrainingStatus object from a json dictionary.""" - args = {} - valid_keys = ['objects'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BaseCollectionTrainingStatus: ' - + ', '.join(bad_keys)) - if 'objects' in _dict: - args['objects'] = ObjectTrainingStatus._from_dict( - _dict.get('objects')) - else: - raise ValueError( - 'Required property \'objects\' not present in BaseCollectionTrainingStatus JSON' - ) - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'objects') and self.objects is not None: - _dict['objects'] = self.objects._to_dict() - return _dict - - def __str__(self): - """Return a `str` version of this BaseCollectionTrainingStatus object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - -class BaseError(): - """ - Details about a problem. - - :attr str code: Identifier of the problem. - :attr str message: An explanation of the problem with possible solutions. - :attr str more_info: (optional) A URL for more information about the solution. - """ - - def __init__(self, code, message, *, more_info=None): - """ - Initialize a BaseError object. - - :param str code: Identifier of the problem. - :param str message: An explanation of the problem with possible solutions. - :param str more_info: (optional) A URL for more information about the - solution. - """ - self.code = code - self.message = message - self.more_info = more_info - - @classmethod - def _from_dict(cls, _dict): - """Initialize a BaseError object from a json dictionary.""" - args = {} - valid_keys = ['code', 'message', 'more_info'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BaseError: ' - + ', '.join(bad_keys)) - if 'code' in _dict: - args['code'] = _dict.get('code') - else: - raise ValueError( - 'Required property \'code\' not present in BaseError JSON') - if 'message' in _dict: - args['message'] = _dict.get('message') - else: - raise ValueError( - 'Required property \'message\' not present in BaseError JSON') - if 'more_info' in _dict: - args['more_info'] = _dict.get('more_info') - return cls(**args) - - def _to_dict(self): - """Return a json dictionary representing this model.""" - _dict = {} - if hasattr(self, 'code') and self.code is not None: - _dict['code'] = self.code - if hasattr(self, 'message') and self.message is not None: - _dict['message'] = self.message - if hasattr(self, 'more_info') and self.more_info is not None: - _dict['more_info'] = self.more_info - return _dict - - def __str__(self): - """Return a `str` version of this BaseError object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class CodeEnum(Enum): - """ - Identifier of the problem. - """ - INVALID_FIELD = "invalid_field" - INVALID_HEADER = "invalid_header" - INVALID_METHOD = "invalid_method" - MISSING_FIELD = "missing_field" - SERVER_ERROR = "server_error" - - -class BaseObject(): - """ - Details about an object and its location. - - :attr str object: (optional) The name of the object. The name can contain - alphanumeric, underscore, hyphen, space, and dot characters. It cannot begin - with the reserved prefix `sys-`. - :attr Location location: (optional) Defines the location of the bounding box - around the object. - """ - - def __init__(self, *, object=None, location=None): - """ - Initialize a BaseObject object. - - :param str object: (optional) The name of the object. The name can contain - alphanumeric, underscore, hyphen, space, and dot characters. It cannot - begin with the reserved prefix `sys-`. - :param Location location: (optional) Defines the location of the bounding - box around the object. - """ - self.object = object - self.location = location - - @classmethod - def _from_dict(cls, _dict): - """Initialize a BaseObject object from a json dictionary.""" - args = {} - valid_keys = ['object', 'location'] - bad_keys = set(_dict.keys()) - set(valid_keys) - if bad_keys: - raise ValueError( - 'Unrecognized keys detected in dictionary for class BaseObject: ' - + ', '.join(bad_keys)) - if 'object' in _dict: - args['object'] = _dict.get('object') - if 'location' in _dict: - args['location'] = Location._from_dict(_dict.get('location')) - return cls(**args) - - def _to_dict(self): - """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, 'location') and self.location is not None: - _dict['location'] = self.location._to_dict() - return _dict - - def __str__(self): - """Return a `str` version of this BaseObject object.""" - return json.dumps(self._to_dict(), indent=2) - - def __eq__(self, other): - """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): - """Return `true` when self and other are not equal, false otherwise.""" - return not self == other - - class Collection(): """ Details about a collection. :attr str collection_id: The identifier of the collection. :attr str name: The name of the collection. - :attr str description: The descripion of the collection. + :attr str description: The description of the collection. :attr datetime created: Date and time in Coordinated Universal Time (UTC) that the collection was created. :attr datetime updated: Date and time in Coordinated Universal Time (UTC) that the collection was most recently updated. :attr int image_count: Number of images in the collection. - :attr BaseCollectionTrainingStatus training_status: Training status information - for the collection. + :attr TrainingStatus training_status: Training status information for the + collection. """ def __init__(self, collection_id, name, description, created, updated, @@ -1195,14 +844,14 @@ def __init__(self, collection_id, name, description, created, updated, :param str collection_id: The identifier of the collection. :param str name: The name of the collection. - :param str description: The descripion of the collection. + :param str description: The description of the collection. :param datetime created: Date and time in Coordinated Universal Time (UTC) that the collection was created. :param datetime updated: Date and time in Coordinated Universal Time (UTC) that the collection was most recently updated. :param int image_count: Number of images in the collection. - :param BaseCollectionTrainingStatus training_status: Training status - information for the collection. + :param TrainingStatus training_status: Training status information for the + collection. """ self.collection_id = collection_id self.name = name @@ -1259,7 +908,7 @@ def _from_dict(cls, _dict): 'Required property \'image_count\' not present in Collection JSON' ) if 'training_status' in _dict: - args['training_status'] = BaseCollectionTrainingStatus._from_dict( + args['training_status'] = TrainingStatus._from_dict( _dict.get('training_status')) else: raise ValueError( @@ -1374,15 +1023,14 @@ class CollectionsList(): """ A container for the list of collections. - :attr list[BaseCollection] collections: The collections in this service - instance. + :attr list[Collection] collections: The collections in this service instance. """ def __init__(self, collections): """ Initialize a CollectionsList object. - :param list[BaseCollection] collections: The collections in this service + :param list[Collection] collections: The collections in this service instance. """ self.collections = collections @@ -1399,7 +1047,7 @@ def _from_dict(cls, _dict): + ', '.join(bad_keys)) if 'collections' in _dict: args['collections'] = [ - BaseCollection._from_dict(x) for x in (_dict.get('collections')) + Collection._from_dict(x) for x in (_dict.get('collections')) ] else: raise ValueError( @@ -1492,7 +1140,7 @@ class Error(): :attr str code: Identifier of the problem. :attr str message: An explanation of the problem with possible solutions. :attr str more_info: (optional) A URL for more information about the solution. - :attr ErrorTarget target: (optional) Details about the specfic area of the + :attr ErrorTarget target: (optional) Details about the specific area of the problem. """ @@ -1504,8 +1152,8 @@ def __init__(self, code, message, *, more_info=None, target=None): :param str message: An explanation of the problem with possible solutions. :param str more_info: (optional) A URL for more information about the solution. - :param ErrorTarget target: (optional) Details about the specfic area of the - problem. + :param ErrorTarget target: (optional) Details about the specific area of + the problem. """ self.code = code self.message = message @@ -1578,7 +1226,7 @@ class CodeEnum(Enum): class ErrorTarget(): """ - Details about the specfic area of the problem. + Details about the specific area of the problem. :attr str type: The parameter or property that is the focus of the problem. :attr str name: The property that is identified with the problem. @@ -1871,8 +1519,8 @@ class ImageDetailsList(): List of information about the images. :attr list[ImageDetails] images: (optional) The images in the collection. - :attr list[BaseError] warnings: (optional) Information about what might cause - less than optimal output. + :attr list[Warning] warnings: (optional) Information about what might cause less + than optimal output. :attr str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. """ @@ -1882,7 +1530,7 @@ def __init__(self, *, images=None, warnings=None, trace=None): Initialize a ImageDetailsList object. :param list[ImageDetails] images: (optional) The images in the collection. - :param list[BaseError] warnings: (optional) Information about what might + :param list[Warning] warnings: (optional) Information about what might cause less than optimal output. :param str trace: (optional) A unique identifier of the request. Included only when an error or warning is returned. @@ -1907,7 +1555,7 @@ def _from_dict(cls, _dict): ] if 'warnings' in _dict: args['warnings'] = [ - BaseError._from_dict(x) for x in (_dict.get('warnings')) + Warning._from_dict(x) for x in (_dict.get('warnings')) ] if 'trace' in _dict: args['trace'] = _dict.get('trace') @@ -2623,6 +2271,146 @@ def __ne__(self, other): return not self == other +class TrainingStatus(): + """ + Training status information for the collection. + + :attr ObjectTrainingStatus objects: Training status for the objects in the + collection. + """ + + def __init__(self, objects): + """ + Initialize a TrainingStatus object. + + :param ObjectTrainingStatus objects: Training status for the objects in the + collection. + """ + self.objects = objects + + @classmethod + def _from_dict(cls, _dict): + """Initialize a TrainingStatus object from a json dictionary.""" + args = {} + valid_keys = ['objects'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class TrainingStatus: ' + + ', '.join(bad_keys)) + if 'objects' in _dict: + args['objects'] = ObjectTrainingStatus._from_dict( + _dict.get('objects')) + else: + raise ValueError( + 'Required property \'objects\' not present in TrainingStatus JSON' + ) + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'objects') and self.objects is not None: + _dict['objects'] = self.objects._to_dict() + return _dict + + def __str__(self): + """Return a `str` version of this TrainingStatus object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + +class Warning(): + """ + Details about a problem. + + :attr str code: Identifier of the problem. + :attr str message: An explanation of the problem with possible solutions. + :attr str more_info: (optional) A URL for more information about the solution. + """ + + def __init__(self, code, message, *, more_info=None): + """ + Initialize a Warning object. + + :param str code: Identifier of the problem. + :param str message: An explanation of the problem with possible solutions. + :param str more_info: (optional) A URL for more information about the + solution. + """ + self.code = code + self.message = message + self.more_info = more_info + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Warning object from a json dictionary.""" + args = {} + valid_keys = ['code', 'message', 'more_info'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Warning: ' + + ', '.join(bad_keys)) + if 'code' in _dict: + args['code'] = _dict.get('code') + else: + raise ValueError( + 'Required property \'code\' not present in Warning JSON') + if 'message' in _dict: + args['message'] = _dict.get('message') + else: + raise ValueError( + 'Required property \'message\' not present in Warning JSON') + if 'more_info' in _dict: + args['more_info'] = _dict.get('more_info') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'code') and self.code is not None: + _dict['code'] = self.code + if hasattr(self, 'message') and self.message is not None: + _dict['message'] = self.message + if hasattr(self, 'more_info') and self.more_info is not None: + _dict['more_info'] = self.more_info + return _dict + + def __str__(self): + """Return a `str` version of this Warning object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class CodeEnum(Enum): + """ + Identifier of the problem. + """ + INVALID_FIELD = "invalid_field" + INVALID_HEADER = "invalid_header" + INVALID_METHOD = "invalid_method" + MISSING_FIELD = "missing_field" + SERVER_ERROR = "server_error" + + class FileWithMetadata(): """ A file with its associated metadata. diff --git a/test/integration/test_visual_recognition_v4.py b/test/integration/test_visual_recognition_v4.py index 9149391e6..5677b6815 100644 --- a/test/integration/test_visual_recognition_v4.py +++ b/test/integration/test_visual_recognition_v4.py @@ -2,10 +2,9 @@ import pytest import ibm_watson import os -from os.path import abspath import json from unittest import TestCase -from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata, BaseObject, Location +from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata, TrainingDataObject, Location @pytest.mark.skipif( os.getenv('VCAP_SERVICES') is None, reason='requires VCAP_SERVICES') @@ -76,8 +75,8 @@ def test_03_analyze(self): '../../resources/my-giraffe.jpeg') with open(dog_path, 'rb') as dog_file, open(giraffe_path, 'rb') as giraffe_files: analyze_images = self.visual_recognition.analyze( - collection_ids='d31d6534-3458-40c4-b6de-2185a5f3cbe4', - features=AnalyzeEnums.Features.OBJECTS.value, + collection_ids=['d31d6534-3458-40c4-b6de-2185a5f3cbe4'], + features=[AnalyzeEnums.Features.OBJECTS.value], images_file=[ FileWithMetadata(dog_file), FileWithMetadata(giraffe_files) @@ -90,7 +89,7 @@ def test_04_training(self): # create a classifier my_collection = self.visual_recognition.create_collection( name='my_test_collection', - description='tetsing for python' + description='testing for python' ).get_result() collection_id = my_collection.get('collection_id') assert collection_id is not None @@ -110,7 +109,8 @@ def test_04_training(self): collection_id, image_id, objects=[ - BaseObject(object='giraffe training data', location=Location(64, 270, 755, 784)) + TrainingDataObject(object='giraffe training data', + location=Location(64, 270, 755, 784)) ]).get_result() assert training_data is not None diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 0215a52b8..2f03b1095 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -13,10 +13,8 @@ # limitations under the License. import json -import responses import ibm_watson import responses -import ibm_watson import json import os import jwt @@ -24,7 +22,7 @@ import pytest from unittest import TestCase from ibm_cloud_sdk_core.authenticators import IAMAuthenticator -from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata, BaseObject, Location +from ibm_watson.visual_recognition_v4 import AnalyzeEnums, FileWithMetadata platform_url = 'https://gateway.watsonplatform.net' service_path = '/visual-recognition/api' From c3877b9fd7140a3d3df6acb5aeff6bc3d9f67913 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 2 Oct 2019 09:31:26 -0700 Subject: [PATCH 094/455] chore(vr4): Hand edit visual recognition v4 --- ibm_watson/visual_recognition_v4.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index bc8c38086..b25dbf684 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -142,10 +142,12 @@ def analyze(self, params = {'version': self.version} form_data = [] - for item in collection_ids: - form_data.append(('collection_ids', (None, item, 'text/plain'))) - for item in features: - form_data.append(('features', (None, item, 'text/plain'))) + if collection_ids: + collection_ids = self._convert_list(collection_ids) + form_data.append(('collection_ids', (None, collection_ids, 'text/plain'))) + if features: + features = self._convert_list(features) + form_data.append(('features', (None, features, 'text/plain'))) if images_file: for item in images_file: form_data.append(('images_file', (item.filename, item.data, From ecb261e44061df277ade2798cbbde09976633949 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 2 Oct 2019 09:31:49 -0700 Subject: [PATCH 095/455] test(vr4): update vr4 test --- test/unit/test_visual_recognition_v4.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/unit/test_visual_recognition_v4.py b/test/unit/test_visual_recognition_v4.py index 2f03b1095..a670c9db6 100644 --- a/test/unit/test_visual_recognition_v4.py +++ b/test/unit/test_visual_recognition_v4.py @@ -246,8 +246,8 @@ def test_analyze(self): os.path.join(os.path.dirname(__file__), '../../resources/cars.zip'), 'rb') as cars: detailed_response = service.analyze( - collection_ids='collection_id1, collection_id2', - features=AnalyzeEnums.Features.OBJECTS.value, + collection_ids=['collection_id1, collection_id2'], + features=[AnalyzeEnums.Features.OBJECTS.value], images_file=[FileWithMetadata(cars)], image_url=[ 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/American_Eskimo_Dog.jpg/1280px-American_Eskimo_Dog.jpg' From 68ea837f5699f400b8829f0feb168369bb101967 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 2 Oct 2019 10:35:53 -0700 Subject: [PATCH 096/455] fix(core): Update core version for handling proxy in token managers --- README.md | 2 +- requirements-dev.txt | 2 +- requirements.txt | 2 +- setup.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 9b47efff2..3c75b697c 100755 --- a/README.md +++ b/README.md @@ -358,7 +358,7 @@ assistant.disable_SSL_verification() # MAKE SURE SSL VERIFICATION IS DISABLED * [responses] for testing * Following for web sockets support in speech to text * `websocket-client` 0.48.0 -* `ibm_cloud_sdk_core` >=0.5.1 +* `ibm_cloud_sdk_core` ==0.5.2 ## Contributing diff --git a/requirements-dev.txt b/requirements-dev.txt index ec79977bd..a1265db83 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ python_dotenv>=0.1.5;python_version!='3.2' pylint>=1.4.4 tox>=2.9.1 pytest-rerunfailures>=3.1 -ibm_cloud_sdk_core>=0.5.1 +ibm_cloud_sdk_core==0.5.2 # code coverage coverage<5 diff --git a/requirements.txt b/requirements.txt index 7f218b427..2fc85ad5d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ requests>=2.0,<3.0 python_dateutil>=2.5.3 websocket-client==0.48.0 -ibm_cloud_sdk_core>=0.5.1 \ No newline at end of file +ibm_cloud_sdk_core==0.5.2 \ No newline at end of file diff --git a/setup.py b/setup.py index 84a25409b..f44f9f033 100644 --- a/setup.py +++ b/setup.py @@ -64,7 +64,7 @@ def run_tests(self): version=__version__, description='Client library to use the IBM Watson Services', license='Apache 2.0', - install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core>=0.5.1'], + install_requires=['requests>=2.0, <3.0', 'python_dateutil>=2.5.3', 'websocket-client==0.48.0', 'ibm_cloud_sdk_core==0.5.2'], tests_require=['responses', 'pytest', 'python_dotenv', 'pytest-rerunfailures', 'tox'], cmdclass={'test': PyTest}, author='IBM Watson', From 6122ab129e17d8cb8770f163476e82297a6cf5ca Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 2 Oct 2019 11:12:03 -0700 Subject: [PATCH 097/455] feat(vr4): regenerate vr4 where TrainingDataObject is optional --- ibm_watson/visual_recognition_v4.py | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index b25dbf684..2ab2f083c 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -142,12 +142,10 @@ def analyze(self, params = {'version': self.version} form_data = [] - if collection_ids: - collection_ids = self._convert_list(collection_ids) - form_data.append(('collection_ids', (None, collection_ids, 'text/plain'))) - if features: - features = self._convert_list(features) - form_data.append(('features', (None, features, 'text/plain'))) + for item in collection_ids: + form_data.append(('collection_ids', (None, item, 'text/plain'))) + for item in features: + form_data.append(('features', (None, item, 'text/plain'))) if images_file: for item in images_file: form_data.append(('images_file', (item.filename, item.data, @@ -2219,15 +2217,16 @@ class TrainingDataObjects(): """ Training data for all objects. - :attr list[TrainingDataObject] objects: Training data for specific objects. + :attr list[TrainingDataObject] objects: (optional) Training data for specific + objects. """ - def __init__(self, objects): + def __init__(self, *, objects=None): """ Initialize a TrainingDataObjects object. - :param list[TrainingDataObject] objects: Training data for specific - objects. + :param list[TrainingDataObject] objects: (optional) Training data for + specific objects. """ self.objects = objects @@ -2245,10 +2244,6 @@ def _from_dict(cls, _dict): args['objects'] = [ TrainingDataObject._from_dict(x) for x in (_dict.get('objects')) ] - else: - raise ValueError( - 'Required property \'objects\' not present in TrainingDataObjects JSON' - ) return cls(**args) def _to_dict(self): From ed4e88c64deebe24f3fd32762e5b69308cd9014d Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 2 Oct 2019 11:14:04 -0700 Subject: [PATCH 098/455] chore(vr4): Hand edit collection_ids and features in analyze --- ibm_watson/visual_recognition_v4.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 2ab2f083c..7576e91ae 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -142,10 +142,12 @@ def analyze(self, params = {'version': self.version} form_data = [] - for item in collection_ids: - form_data.append(('collection_ids', (None, item, 'text/plain'))) - for item in features: - form_data.append(('features', (None, item, 'text/plain'))) + if collection_ids: + collection_ids = self._convert_list(collection_ids) + form_data.append(('collection_ids', (None, collection_ids, 'text/plain'))) + if features: + features = self._convert_list(features) + form_data.append(('features', (None, features, 'text/plain'))) if images_file: for item in images_file: form_data.append(('images_file', (item.filename, item.data, From b55593ef81b7025e981d0b014b8de8b458de74c6 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 2 Oct 2019 11:15:03 -0700 Subject: [PATCH 099/455] chore(vr3): regenerate vr3 --- ibm_watson/visual_recognition_v3.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 476f32ba9..75b87f5be 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -168,12 +168,11 @@ def classify(self, form_data.append( ('threshold', (None, threshold, 'application/json'))) if owners: - owners = self._convert_list(owners) - form_data.append(('owners', (None, owners, 'application/json'))) + for item in owners: + form_data.append(('owners', (None, item, 'text/plain'))) if classifier_ids: - classifier_ids = self._convert_list(classifier_ids) - form_data.append( - ('classifier_ids', (None, classifier_ids, 'application/json'))) + for item in classifier_ids: + form_data.append(('classifier_ids', (None, item, 'text/plain'))) url = '/v3/classify' request = self.prepare_request(method='POST', From b92aefe968be3294c1a49407dc5351c80e90ef65 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 2 Oct 2019 11:17:56 -0700 Subject: [PATCH 100/455] chore(vr3): Hand edit owners and classifier_ids in classify --- ibm_watson/visual_recognition_v3.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 75b87f5be..169f80884 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -168,11 +168,11 @@ def classify(self, form_data.append( ('threshold', (None, threshold, 'application/json'))) if owners: - for item in owners: - form_data.append(('owners', (None, item, 'text/plain'))) + owners = self._convert_list(owners) + form_data.append(('owners', (None, item, 'text/plain'))) if classifier_ids: - for item in classifier_ids: - form_data.append(('classifier_ids', (None, item, 'text/plain'))) + classifier_ids = self._convert_list(classifier_ids) + form_data.append(('classifier_ids', (None, item, 'text/plain'))) url = '/v3/classify' request = self.prepare_request(method='POST', From a24ff4e504519a7fcde5bf7018236ca9f5106a3a Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 2 Oct 2019 11:19:51 -0700 Subject: [PATCH 101/455] chore(services): update service information --- ibm_watson/assistant_v1.py | 6 ++- ibm_watson/assistant_v2.py | 2 + ibm_watson/text_to_speech_v1.py | 66 +++++++++++++++------------------ 3 files changed, 35 insertions(+), 39 deletions(-) diff --git a/ibm_watson/assistant_v1.py b/ibm_watson/assistant_v1.py index a24f38826..c47cd91d7 100644 --- a/ibm_watson/assistant_v1.py +++ b/ibm_watson/assistant_v1.py @@ -17,6 +17,8 @@ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your apps and your users. +The Assistant v1 API provides authoring methods your application can use to create or +update a workspace. """ import json @@ -98,8 +100,8 @@ def message(self, Get response to user input. Send user input to a workspace and receive a response. - **Note:** For most applications, there are significant advantages to using the v2 - runtime API instead. These advantages include ease of deployment, automatic state + **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). There is no rate limit for this operation. diff --git a/ibm_watson/assistant_v2.py b/ibm_watson/assistant_v2.py index 4bc1ea9f7..8f36be0bc 100644 --- a/ibm_watson/assistant_v2.py +++ b/ibm_watson/assistant_v2.py @@ -17,6 +17,8 @@ The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated dialog editor to create conversation flows between your apps and your users. +The Assistant v2 API provides runtime methods your client application can use to send user +input to an assistant and receive a response. """ import json diff --git a/ibm_watson/text_to_speech_v1.py b/ibm_watson/text_to_speech_v1.py index 50fc538cf..2b8084043 100644 --- a/ibm_watson/text_to_speech_v1.py +++ b/ibm_watson/text_to_speech_v1.py @@ -178,7 +178,8 @@ def synthesize(self, The service can return audio in the following formats (MIME types). * Where indicated, you can optionally specify the sampling rate (`rate`) of the audio. You must specify a sampling rate for the `audio/l16` and `audio/mulaw` - formats. A specified sampling rate must lie in the range of 8 kHz to 192 kHz. + formats. A specified sampling rate must lie in the range of 8 kHz to 192 kHz. Some + formats restrict the sampling rate to certain values, as noted. * For the `audio/l16` format, you can optionally specify the endianness (`endianness`) of the audio: `endianness=big-endian` or `endianness=little-endian`. @@ -186,42 +187,33 @@ def synthesize(self, of the response audio. If you omit an audio format altogether, the service returns the audio in Ogg format with the Opus codec (`audio/ogg;codecs=opus`). The service always returns single-channel audio. - * `audio/basic` - The service returns audio with a sampling rate of 8000 Hz. - * `audio/flac` - You can optionally specify the `rate` of the audio. The default sampling rate is - 22,050 Hz. - * `audio/l16` - You must specify the `rate` of the audio. You can optionally specify the - `endianness` of the audio. The default endianness is `little-endian`. - * `audio/mp3` - You can optionally specify the `rate` of the audio. The default sampling rate is - 22,050 Hz. - * `audio/mpeg` - You can optionally specify the `rate` of the audio. The default sampling rate is - 22,050 Hz. - * `audio/mulaw` - You must specify the `rate` of the audio. - * `audio/ogg` - The service returns the audio in the `vorbis` codec. You can optionally specify - the `rate` of the audio. The default sampling rate is 22,050 Hz. - * `audio/ogg;codecs=opus` - You can optionally specify the `rate` of the audio. The default sampling rate is - 22,050 Hz. - * `audio/ogg;codecs=vorbis` - You can optionally specify the `rate` of the audio. The default sampling rate is - 22,050 Hz. - * `audio/wav` - You can optionally specify the `rate` of the audio. The default sampling rate is - 22,050 Hz. - * `audio/webm` - The service returns the audio in the `opus` codec. The service returns audio - with a sampling rate of 48,000 Hz. - * `audio/webm;codecs=opus` - The service returns audio with a sampling rate of 48,000 Hz. - * `audio/webm;codecs=vorbis` - You can optionally specify the `rate` of the audio. The default sampling rate is - 22,050 Hz. + * `audio/basic` - The service returns audio with a sampling rate of 8000 Hz. + * `audio/flac` - You can optionally specify the `rate` of the audio. The default + sampling rate is 22,050 Hz. + * `audio/l16` - You must specify the `rate` of the audio. You can optionally + specify the `endianness` of the audio. The default endianness is `little-endian`. + * `audio/mp3` - You can optionally specify the `rate` of the audio. The default + sampling rate is 22,050 Hz. + * `audio/mpeg` - You can optionally specify the `rate` of the audio. The default + sampling rate is 22,050 Hz. + * `audio/mulaw` - You must specify the `rate` of the audio. + * `audio/ogg` - The service returns the audio in the `vorbis` codec. You can + optionally specify the `rate` of the audio. The default sampling rate is 22,050 + Hz. + * `audio/ogg;codecs=opus` - You can optionally specify the `rate` of the audio. + Only the following values are valid sampling rates: `48000`, `24000`, `16000`, + `12000`, or `8000`. If you specify a value other than one of these, the service + returns an error. The default sampling rate is 48,000 Hz. + * `audio/ogg;codecs=vorbis` - You can optionally specify the `rate` of the audio. + The default sampling rate is 22,050 Hz. + * `audio/wav` - You can optionally specify the `rate` of the audio. The default + sampling rate is 22,050 Hz. + * `audio/webm` - The service returns the audio in the `opus` codec. The service + returns audio with a sampling rate of 48,000 Hz. + * `audio/webm;codecs=opus` - The service returns audio with a sampling rate of + 48,000 Hz. + * `audio/webm;codecs=vorbis` - You can optionally specify the `rate` of the audio. + 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). From 2f44930514ecdd88b1b61bc29dbc8f9c99f62119 Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Wed, 2 Oct 2019 19:52:08 +0000 Subject: [PATCH 102/455] =?UTF-8?q?Bump=20version:=203.4.1=20=E2=86=92=203?= =?UTF-8?q?.4.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index 24b4b4b92..c259b7b89 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 3.4.1 +current_version = 3.4.2 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index da4564dd6..daee014fe 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '3.4.1' +__version__ = '3.4.2' diff --git a/setup.py b/setup.py index f44f9f033..0fb5fce0c 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ import os import sys -__version__ = '3.4.1' +__version__ = '3.4.2' if sys.argv[-1] == 'publish': # test server From d78b1b0e78fa17ec47c0dbb0914d9c49ac50b452 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Wed, 2 Oct 2019 13:10:05 -0700 Subject: [PATCH 103/455] feat(discovery): CPD-only functionality, Autocomplete method, spellingSuggestions in Query) --- ibm_watson/discovery_v1.py | 120 ++++++++++++++++++++++++++++++++- test/unit/test_discovery_v1.py | 27 ++++++++ 2 files changed, 146 insertions(+), 1 deletion(-) diff --git a/ibm_watson/discovery_v1.py b/ibm_watson/discovery_v1.py index eda9262d0..625678099 100644 --- a/ibm_watson/discovery_v1.py +++ b/ibm_watson/discovery_v1.py @@ -1511,6 +1511,7 @@ def query(self, similar_document_ids=None, similar_fields=None, bias=None, + spelling_suggestions=None, x_watson_logging_opt_out=None, **kwargs): """ @@ -1588,6 +1589,12 @@ def query(self, field is specified, returned results are biased towards higher field values. This parameter cannot be used in the same query as the **sort** parameter. + :param bool spelling_suggestions: (optional) When `true` and the + **natural_language_query** parameter is used, the **natural_languge_query** + parameter is spell checked. The most likely correction is retunred in the + **suggested_query** field of the response (if one exists). + **Important:** this parameter is only valid when using the Cloud Pak + version of Discovery. :param bool x_watson_logging_opt_out: (optional) If `true`, queries are not stored in the Discovery **Logs** endpoint. :param dict headers: A `dict` containing the request headers @@ -1627,7 +1634,8 @@ def query(self, 'similar': similar, 'similar.document_ids': similar_document_ids, 'similar.fields': similar_fields, - 'bias': bias + 'bias': bias, + 'spelling_suggestions': spelling_suggestions } url = '/v1/environments/{0}/collections/{1}/query'.format( @@ -2047,6 +2055,63 @@ def federated_query_notices(self, response = self.send(request) return response + def get_autocompletion(self, + environment_id, + collection_id, + *, + field=None, + prefix=None, + count=None, + **kwargs): + """ + Get Autocomplete Suggestions. + + Returns completion query suggestions for the specified prefix. /n/n + **Important:** this method is only valid when using the Cloud Pak version of + Discovery. + + :param str environment_id: The ID of the environment. + :param str collection_id: The ID of the collection. + :param str field: (optional) The field in the result documents that + autocompletion suggestions are identified from. + :param str prefix: (optional) The prefix to use for autocompletion. For + example, the prefix `Ho` could autocomplete to `Hot`, `Housing`, or `How do + I upgrade`. Possible completions are. + :param int count: (optional) The number of autocompletion suggestions to + return. + :param dict headers: A `dict` containing the request headers + :return: A `DetailedResponse` containing the result, headers and HTTP status code. + :rtype: DetailedResponse + """ + + if environment_id is None: + raise ValueError('environment_id must be provided') + 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('discovery', 'V1', 'get_autocompletion') + headers.update(sdk_headers) + + params = { + 'version': self.version, + 'field': field, + 'prefix': prefix, + 'count': count + } + + url = '/v1/environments/{0}/collections/{1}/autocompletion'.format( + *self._encode_path_vars(environment_id, collection_id)) + request = self.prepare_request(method='GET', + url=url, + headers=headers, + params=params, + accept_json=True) + response = self.send(request) + return response + ######################### # Training data ######################### @@ -3857,6 +3922,59 @@ def __ne__(self, other): return not self == other +class Completions(): + """ + An object containing an array of autocompletion suggestions. + + :attr list[str] completions: (optional) Array of autcomplete suggestion based on + the provided prefix. + """ + + def __init__(self, *, completions=None): + """ + Initialize a Completions object. + + :param list[str] completions: (optional) Array of autcomplete suggestion + based on the provided prefix. + """ + self.completions = completions + + @classmethod + def _from_dict(cls, _dict): + """Initialize a Completions object from a json dictionary.""" + args = {} + valid_keys = ['completions'] + bad_keys = set(_dict.keys()) - set(valid_keys) + if bad_keys: + raise ValueError( + 'Unrecognized keys detected in dictionary for class Completions: ' + + ', '.join(bad_keys)) + if 'completions' in _dict: + args['completions'] = _dict.get('completions') + return cls(**args) + + def _to_dict(self): + """Return a json dictionary representing this model.""" + _dict = {} + if hasattr(self, 'completions') and self.completions is not None: + _dict['completions'] = self.completions + return _dict + + def __str__(self): + """Return a `str` version of this Completions object.""" + return json.dumps(self._to_dict(), indent=2) + + def __eq__(self, other): + """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): + """Return `true` when self and other are not equal, false otherwise.""" + return not self == other + + class Configuration(): """ A custom configuration for the environment. diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 0182bf8f5..051ac48c3 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -1272,3 +1272,30 @@ def test_gateway_configuration(cls): discovery.get_gateway('envid', 'gateway_id') discovery.delete_gateway(environment_id='envid', gateway_id='gateway_id') assert len(responses.calls) == 8 + + + @responses.activate + def test_get_autocompletion(self): + endpoint = 'environments/{0}/collections/{1}/autocompletion?version=2018-08-13&field=field&prefix=prefix&count=count'.format('environment_id', 'collection_id').format('collection_id') + url = '{0}{1}'.format(base_discovery_url, endpoint) + print('hello') + print(url) + response = { + "completions" : [ "completions", "completions" ] + } + responses.add(responses.GET, + url, + body=json.dumps(response), + status=200, + content_type='application/json') + + authenticator = IAMAuthenticator('iam_apikey') + discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + + detailed_response = discovery.get_autocompletion(environment_id='environment_id', + collection_id='collection_id', + field='field', + prefix='prefix', + count='count') + result = detailed_response.get_result() + assert len(responses.calls) == 2 From a6163ac7b3b2c1672f02271c020a3bb0c6f2610e Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 3 Oct 2019 09:59:57 -0700 Subject: [PATCH 104/455] feat(stt): customization_id no longer a param in recognize_using_websocket --- MIGRATION-V4.md | 1 + ibm_watson/speech_to_text_v1_adapter.py | 6 ------ 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/MIGRATION-V4.md b/MIGRATION-V4.md index 2dd9e5a4a..174b7ff0e 100644 --- a/MIGRATION-V4.md +++ b/MIGRATION-V4.md @@ -192,6 +192,7 @@ The SDK no longer supports Pyhton versions 2.7 and <=3.4. #### Speech to Text V1 * `final_results` was renamed to `final` in the SpeakerLabelsResult model * `final_results` was renamed to `final` in the SpeechRecognitionResult model +* `customization_id` no longer a param in `recognize_using_websocket()` method #### Visual Recognition V3 * `detect_faces()` method was removed diff --git a/ibm_watson/speech_to_text_v1_adapter.py b/ibm_watson/speech_to_text_v1_adapter.py index d9eded45c..32b95dc7f 100644 --- a/ibm_watson/speech_to_text_v1_adapter.py +++ b/ibm_watson/speech_to_text_v1_adapter.py @@ -43,7 +43,6 @@ def recognize_using_websocket(self, speaker_labels=None, http_proxy_host=None, http_proxy_port=None, - customization_id=None, grammar_name=None, redaction=None, processing_metrics=None, @@ -145,10 +144,6 @@ def recognize_using_websocket(self, labels](https://cloud.ibm.com/docs/services/speech-to-text?topic=speech-to-text-output#speaker_labels). :param str http_proxy_host: http proxy host name. :param str http_proxy_port: http proxy port. If not set, set to 80. - :param str customization_id: **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 request. Do not specify both parameters with a - request. :param str grammar_name: The name of a grammar that is to be used with the recognition request. If you specify a grammar, you must also use the `language_customization_id` parameter to specify the name of the custom language @@ -219,7 +214,6 @@ def recognize_using_websocket(self, params = { 'model': model, - 'customization_id': customization_id, 'acoustic_customization_id': acoustic_customization_id, 'base_model_version': base_model_version, 'language_customization_id': language_customization_id From 16f0152be15f16754112288a759ba5a98e14e46f Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 3 Oct 2019 10:32:18 -0700 Subject: [PATCH 105/455] refactor(readme): Final updates to readme BREAKING CHANGE: This is a breaking change --- MIGRATION-V4.md | 11 +++++++++++ README.md | 31 ++++++++++++++++++------------- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/MIGRATION-V4.md b/MIGRATION-V4.md index 174b7ff0e..2a3828ef9 100644 --- a/MIGRATION-V4.md +++ b/MIGRATION-V4.md @@ -124,6 +124,17 @@ We need to specify the optional param name: assistant_service.list_workspaces(page_limit=10) ``` +## DISABLING SSL VERIFICATION +#### Before +```python +service.disable_ssl_verification(True) +``` + +#### After(v4.0) +```python +service.set_disable_ssl_verification(True) +``` + ## SUPPORT FOR CONSTANTS Constants for methods and models are shown in the form of Enums diff --git a/README.md b/README.md index 81b3424c5..509fb6804 100755 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Python client library to quickly get started with the various [Watson APIs][wdc] * [Disable SSL certificate verification](#disable-ssl-certificate-verification) * [Setting the service url](#setting-the-service-url) * [Sending request headers](#sending-request-headers) - * [Parsing HTTP response info](#parsing-http-response-info) + * [Parsing HTTP response information](#parsing-http-response-information) * [Using Websockets](#using-websockets) * [Cloud Pak for Data(CP4D)](#cloud-pak-for-data) * [Logging](#logging) @@ -41,7 +41,7 @@ Python client library to quickly get started with the various [Watson APIs][wdc] ## Before you begin -* You need an [IBM Cloud][ibm-cloud-onboarding] account. +* You need an [IBM Cloud][ibm-cloud-onboarding] account. We now only support `python 3.5` and above ## Installation To install, use `pip` or `easy_install`: @@ -94,8 +94,6 @@ Watson services are migrating to token-based Identity and Access Management (IAM - With some service instances, you authenticate to the API by using **[IAM](#iam)**. - In other instances, you authenticate by providing the **[username and password](#username-and-password)** for the service instance. -**Note:** Authenticating with the X-Watson-Authorization-Token header is deprecated. The token continues to work with Cloud Foundry services, but is not supported for services that use Identity and Access Management (IAM) authentication. See [here](#iam) for details. - ### Getting credentials To find out which authentication to use, view the service credentials. You find the service credentials for authentication the same way for all Watson services: @@ -115,8 +113,8 @@ With a credential file, you just need to put the file in the right place and the The file downloaded will be called `ibm-credentials.env`. This is the name the SDK will search for and **must** be preserved unless you want to configure the file path (more on that later). The SDK will look for your `ibm-credentials.env` file in the following places (in order): -- Your system's home directory - The top-level directory of the project you're using the SDK in +- Your system's home directory As long as you set that up correctly, you don't have to worry about setting any authentication options in your code. So, for example, if you created and downloaded the credential file for your Discovery instance, you just need to do the following: @@ -140,8 +138,8 @@ where `` is something like `/home/user/Downloads/.env`. Simply set the environment variables using _ syntax. For example, using your favourite terminal, you can set environment variables for Assistant service instance: ```bash -export assistant_apikey="" -export assistant_auth_type="iam" +export ASSISTANT_APIKEY="" +export ASSISTANT_AUTH_TYPE="iam" ``` The credentials will be loaded from the environment automatically @@ -177,11 +175,11 @@ discovery = DiscoveryV1(version='2018-08-01', discovery.set_service_url('') ``` -#### Generating access tokens using API key +#### Generating bearer tokens using API key ```python from ibm_watson import IAMTokenManager -# In your API endpoint use this to generate new access tokens +# In your API endpoint use this to generate new bearer tokens iam_token_manager = IAMTokenManager(apikey='') token = iam_token_manager.get_token() ``` @@ -261,12 +259,13 @@ assistant = AssistantV1( authenticator=authenticator) assistant.set_service_url('') ``` +For more information, follow the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/MIGRATION-V4.md) ## Migration -This version includes many breaking changes as a result of standardizing behavior across the new generated services. Full details on migration from previous versions can be found [here](https://github.com/watson-developer-cloud/python-sdk/wiki/Migration). +To move from v3.x to v4.0, refer to the [MIGRATION-V4](https://github.com/watson-developer-cloud/python-sdk/MIGRATION-V4.md). ## Configuring the http client (Supported from v1.1.0) -To set client configs like timeout use the `with_http_config()` function and pass it a dictionary of configs. +To set client configs like timeout use the `with_http_config()` function and pass it a dictionary of configs. For example for a Assistant service instance ```python from ibm_watson import AssistantV1 @@ -291,6 +290,12 @@ For ICP(IBM Cloud Private), you can disable the SSL certificate verification by: service.set_disable_ssl_verification(True) ``` +Or can set it from extrernal sources. For example set in the environment variable. + +``` +export _DISABLE_SSL=True +``` + ## Setting the service url To set the base service to be used when contacting the service @@ -298,7 +303,7 @@ To set the base service to be used when contacting the service service.set_service_url('my_new_service_url') ``` -Or can set it in the environment variable. +Or can set it from extrernal sources. For example set in the environment variable. ``` export _URL="" @@ -326,7 +331,7 @@ assistant.set_service_url('https://gateway.watsonplatform.net/assistant/api') response = assistant.list_workspaces(headers={'Custom-Header': 'custom_value'}).get_result() ``` -## Parsing HTTP response info +## Parsing HTTP response information If you would like access to some HTTP response information along with the response model, you can set the `set_detailed_response()` to `True`. Since Python SDK `v2.0`, it is set to `True` ```python from ibm_watson import AssistantV1 From 9ad68ab5ef7ad9aaa8f290dbc0d823db2168926d Mon Sep 17 00:00:00 2001 From: semantic-release-bot Date: Thu, 3 Oct 2019 10:32:52 -0700 Subject: [PATCH 106/455] =?UTF-8?q?Bump=20version:=203.4.2=20=E2=86=92=204?= =?UTF-8?q?.0.0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index c259b7b89..dc9167ad6 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 3.4.2 +current_version = 4.0.0 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index daee014fe..d6497a814 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '3.4.2' +__version__ = '4.0.0' diff --git a/setup.py b/setup.py index 30c5c38e8..56d5589c1 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '3.4.2' +__version__ = '4.0.0' if sys.argv[-1] == 'publish': From 0ef7e5dc9eeb11e87b3af1727202c63d3b8ad87f Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 3 Oct 2019 10:39:51 -0700 Subject: [PATCH 107/455] =?UTF-8?q?Revert=20"Bump=20version:=203.4.2=20?= =?UTF-8?q?=E2=86=92=204.0.0"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 9ad68ab5ef7ad9aaa8f290dbc0d823db2168926d. --- .bumpversion.cfg | 2 +- ibm_watson/version.py | 2 +- setup.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.bumpversion.cfg b/.bumpversion.cfg index dc9167ad6..c259b7b89 100644 --- a/.bumpversion.cfg +++ b/.bumpversion.cfg @@ -1,5 +1,5 @@ [bumpversion] -current_version = 4.0.0 +current_version = 3.4.2 commit = True [bumpversion:file:ibm_watson/version.py] diff --git a/ibm_watson/version.py b/ibm_watson/version.py index d6497a814..daee014fe 100644 --- a/ibm_watson/version.py +++ b/ibm_watson/version.py @@ -1 +1 @@ -__version__ = '4.0.0' +__version__ = '3.4.2' diff --git a/setup.py b/setup.py index 56d5589c1..30c5c38e8 100644 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ import os import sys -__version__ = '4.0.0' +__version__ = '3.4.2' if sys.argv[-1] == 'publish': From 050bd9a19b20a2807f6bda07306f7a3e0bf56f42 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 3 Oct 2019 10:41:40 -0700 Subject: [PATCH 108/455] chore(travis): remove the quotes from PYPY_PASSWORD --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 1f8eb8508..800863ac6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -39,7 +39,7 @@ deploy: branch: master - provider: pypi user: watson-devex - password: "$PYPI_PASSWORD" + password: $PYPI_PASSWORD repository: https://upload.pypi.org/legacy skip_cleanup: true on: From aedd181d7d60fd0415f583af7d3508b8256359e2 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 3 Oct 2019 11:00:09 -0700 Subject: [PATCH 109/455] chore(vr3): Incorrect item instead of actual variable --- ibm_watson/visual_recognition_v3.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ibm_watson/visual_recognition_v3.py b/ibm_watson/visual_recognition_v3.py index 169f80884..24cfb08d1 100644 --- a/ibm_watson/visual_recognition_v3.py +++ b/ibm_watson/visual_recognition_v3.py @@ -169,10 +169,10 @@ def classify(self, ('threshold', (None, threshold, 'application/json'))) if owners: owners = self._convert_list(owners) - form_data.append(('owners', (None, item, 'text/plain'))) + form_data.append(('owners', (None, owners, 'text/plain'))) if classifier_ids: classifier_ids = self._convert_list(classifier_ids) - form_data.append(('classifier_ids', (None, item, 'text/plain'))) + form_data.append(('classifier_ids', (None, classifier_ids, 'text/plain'))) url = '/v3/classify' request = self.prepare_request(method='POST', From b101789a5304360f5ef20ad06db31de3cebdb141 Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 3 Oct 2019 11:01:05 -0700 Subject: [PATCH 110/455] chore(FileWithMetadata): Hand edit _from_dict() --- ibm_watson/visual_recognition_v4.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ibm_watson/visual_recognition_v4.py b/ibm_watson/visual_recognition_v4.py index 7576e91ae..28f1e275b 100644 --- a/ibm_watson/visual_recognition_v4.py +++ b/ibm_watson/visual_recognition_v4.py @@ -2442,7 +2442,7 @@ def _from_dict(cls, _dict): 'Unrecognized keys detected in dictionary for class FileWithMetadata: ' + ', '.join(bad_keys)) if 'data' in _dict: - args['data'] = file._from_dict(_dict.get('data')) + args['data'] = _dict.get('data') else: raise ValueError( 'Required property \'data\' not present in FileWithMetadata JSON' From 3d68f5c59f426f3a20f543d9d8bf1128a458e3bb Mon Sep 17 00:00:00 2001 From: ehdsouza Date: Thu, 3 Oct 2019 11:37:52 -0700 Subject: [PATCH 111/455] chore(lint): Handle pylint errors --- .pylintrc | 2 +- examples/speaker_text_to_speech.py | 3 +- examples/visual_recognition_v4.py | 2 +- test/unit/test_discovery_v1.py | 972 +++++++++++++----------- test/unit/test_visual_recognition_v4.py | 44 +- 5 files changed, 565 insertions(+), 458 deletions(-) diff --git a/.pylintrc b/.pylintrc index 4dda025e2..b6d2de7b9 100644 --- a/.pylintrc +++ b/.pylintrc @@ -1,4 +1,4 @@ # lint Python modules using external checkers. [MASTER] ignore=SVN -disable=R0903,R0912,R0913,R0914,R0915,W0141,C0111,C0103,W0603,W0703,R0911,C0301,C0302,R0902,R0904,W0142,W0212,E1101,E1103,R0201,W0201,W0122,W0232,RP0001,RP0003,RP0101,RP0002,RP0401,RP0701,RP0801,F0401,E0611,R0801,I0011,F0401,E0611,E1004,C0111,I0011,I0012,W0704,W0142,W0212,W0232,W0613,W0702,R0201,W0614,R0914,R0912,R0915,R0913,R0904,R0801,C0301,C0411,R0204,W0622,E1121,inconsistent-return-statements,R0205,C0325 +disable=R0903,R0912,R0913,R0914,R0915,W0141,C0111,C0103,W0603,W0703,R0911,C0301,C0302,R0902,R0904,W0142,W0212,E1101,E1103,R0201,W0201,W0122,W0232,RP0001,RP0003,RP0101,RP0002,RP0401,RP0701,RP0801,F0401,E0611,R0801,I0011,F0401,E0611,E1004,C0111,I0011,I0012,W0704,W0142,W0212,W0232,W0613,W0702,R0201,W0614,R0914,R0912,R0915,R0913,R0904,R0801,C0301,C0411,R0204,W0622,E1121,inconsistent-return-statements,R0205,C0325,unsubscriptable-object diff --git a/examples/speaker_text_to_speech.py b/examples/speaker_text_to_speech.py index 78b8c6ab5..eb2646df7 100644 --- a/examples/speaker_text_to_speech.py +++ b/examples/speaker_text_to_speech.py @@ -5,9 +5,10 @@ # passed in the request. When the service responds with the synthesized # audio, the pyaudio would play it in a blocking mode -from ibm_watson import TextToSpeechV1 +from ibm_watson import SpeechToTextV1 from ibm_watson.websocket import SynthesizeCallback import pyaudio +from ibm_cloud_sdk_core.authenticators import IAMAuthenticator authenticator = IAMAuthenticator('your_api_key') service = SpeechToTextV1(authenticator=authenticator) diff --git a/examples/visual_recognition_v4.py b/examples/visual_recognition_v4.py index 93cfe26ae..ae51c5b7d 100644 --- a/examples/visual_recognition_v4.py +++ b/examples/visual_recognition_v4.py @@ -41,7 +41,7 @@ # analyze 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') +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: analyze_images = service.analyze( collection_ids=[collection_id], diff --git a/test/unit/test_discovery_v1.py b/test/unit/test_discovery_v1.py index 051ac48c3..ac731fb59 100644 --- a/test/unit/test_discovery_v1.py +++ b/test/unit/test_discovery_v1.py @@ -22,14 +22,12 @@ environment_id = 'envid' collection_id = 'collid' + def get_access_token(): access_token_layout = { "username": "dummy", "role": "Admin", - "permissions": [ - "administrator", - "manage_catalog" - ], + "permissions": ["administrator", "manage_catalog"], "sub": "admin", "iss": "sss", "aud": "sss", @@ -38,10 +36,16 @@ def get_access_token(): "exp": int(time.time()) } - access_token = jwt.encode(access_token_layout, 'secret', algorithm='HS256', headers={'kid': '230498151c214b788dd97f22b85410a5'}) + access_token = jwt.encode( + access_token_layout, + 'secret', + algorithm='HS256', + headers={'kid': '230498151c214b788dd97f22b85410a5'}) return access_token.decode('utf-8') + class TestDiscoveryV1(TestCase): + @classmethod def setUp(cls): iam_url = "https://iam.cloud.ibm.com/identity/token" @@ -52,8 +56,10 @@ def setUp(cls): "expiration": 1524167011, "refresh_token": "jy4gl91BQ" } - responses.add( - responses.POST, url=iam_url, body=json.dumps(iam_token_response), status=200) + responses.add(responses.POST, + url=iam_url, + body=json.dumps(iam_token_response), + status=200) @classmethod @responses.activate @@ -88,12 +94,15 @@ def test_environments(cls): ] }""" - responses.add(responses.GET, discovery_url, - body=discovery_response_body, status=200, + responses.add(responses.GET, + discovery_url, + body=discovery_response_body, + status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) discovery.list_environments() url_str = "{0}?version=2018-08-13".format(discovery_url) @@ -106,77 +115,89 @@ def test_environments(cls): @responses.activate def test_get_environment(cls): discovery_url = urljoin(base_discovery_url, 'environments/envid') - responses.add(responses.GET, discovery_url, - body="{\"resulting_key\": true}", status=200, + responses.add(responses.GET, + discovery_url, + body="{\"resulting_key\": true}", + status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) discovery.get_environment(environment_id='envid') url_str = "{0}?version=2018-08-13".format(discovery_url) assert responses.calls[0].request.url == url_str assert len(responses.calls) == 1 - @classmethod @responses.activate def test_create_environment(cls): discovery_url = urljoin(base_discovery_url, 'environments') - responses.add(responses.POST, discovery_url, - body="{\"resulting_key\": true}", status=200, + responses.add(responses.POST, + discovery_url, + body="{\"resulting_key\": true}", + status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) - discovery.create_environment(name="my name", description="my description") + discovery.create_environment(name="my name", + description="my description") assert len(responses.calls) == 1 - @classmethod @responses.activate def test_update_environment(cls): discovery_url = urljoin(base_discovery_url, 'environments/envid') - responses.add(responses.PUT, discovery_url, - body="{\"resulting_key\": true}", status=200, + responses.add(responses.PUT, + discovery_url, + body="{\"resulting_key\": true}", + status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) discovery.update_environment('envid', name="hello", description="new") assert len(responses.calls) == 1 - @classmethod @responses.activate def test_delete_environment(cls): discovery_url = urljoin(base_discovery_url, 'environments/envid') - responses.add(responses.DELETE, discovery_url, - body="{\"resulting_key\": true}", status=200, + responses.add(responses.DELETE, + discovery_url, + body="{\"resulting_key\": true}", + status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) discovery.delete_environment('envid') assert len(responses.calls) == 1 - @classmethod @responses.activate def test_collections(cls): discovery_url = urljoin(base_discovery_url, 'environments/envid/collections') - responses.add(responses.GET, discovery_url, - body="{\"body\": \"hello\"}", status=200, + responses.add(responses.GET, + discovery_url, + body="{\"body\": \"hello\"}", + status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) discovery.list_collections('envid') @@ -187,33 +208,39 @@ def test_collections(cls): assert called_url.path == test_url.path assert len(responses.calls) == 1 - @classmethod @responses.activate def test_collection(cls): discovery_url = urljoin(base_discovery_url, 'environments/envid/collections/collid') - discovery_fields = urljoin(base_discovery_url, - 'environments/envid/collections/collid/fields') + discovery_fields = urljoin( + base_discovery_url, 'environments/envid/collections/collid/fields') config_url = urljoin(base_discovery_url, 'environments/envid/configurations') - responses.add(responses.GET, config_url, + responses.add(responses.GET, + config_url, body="{\"body\": \"hello\"}", status=200, content_type='application/json') - responses.add(responses.GET, discovery_fields, - body="{\"body\": \"hello\"}", status=200, + responses.add(responses.GET, + discovery_fields, + body="{\"body\": \"hello\"}", + status=200, content_type='application/json') - responses.add(responses.GET, discovery_url, - body="{\"body\": \"hello\"}", status=200, + responses.add(responses.GET, + discovery_url, + body="{\"body\": \"hello\"}", + status=200, content_type='application/json') - responses.add(responses.DELETE, discovery_url, - body="{\"body\": \"hello\"}", status=200, + responses.add(responses.DELETE, + discovery_url, + body="{\"body\": \"hello\"}", + status=200, content_type='application/json') responses.add(responses.POST, @@ -224,7 +251,8 @@ def test_collection(cls): content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) discovery.create_collection(environment_id='envid', name="name", @@ -254,17 +282,21 @@ def test_collection(cls): @classmethod @responses.activate def test_federated_query(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/query') + discovery_url = urljoin(base_discovery_url, 'environments/envid/query') - responses.add(responses.POST, discovery_url, - body="{\"body\": \"hello\"}", status=200, + responses.add(responses.POST, + discovery_url, + body="{\"body\": \"hello\"}", + status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) - discovery.federated_query('envid', filter='colls.sha1::9181d244*', collection_ids=['collid1', 'collid2']) + discovery.federated_query('envid', + filter='colls.sha1::9181d244*', + collection_ids=['collid1', 'collid2']) called_url = urlparse(responses.calls[0].request.url) test_url = urlparse(discovery_url) @@ -276,17 +308,20 @@ def test_federated_query(cls): @classmethod @responses.activate def test_federated_query_2(cls): - discovery_url = urljoin(base_discovery_url, - 'environments/envid/query') + discovery_url = urljoin(base_discovery_url, 'environments/envid/query') - responses.add(responses.POST, discovery_url, - body="{\"body\": \"hello\"}", status=200, + responses.add(responses.POST, + discovery_url, + body="{\"body\": \"hello\"}", + status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) - discovery.federated_query('envid', collection_ids="'collid1', 'collid2'", + discovery.federated_query('envid', + collection_ids="'collid1', 'collid2'", filter='colls.sha1::9181d244*', bias='1', logging_opt_out=True) @@ -304,12 +339,17 @@ def test_federated_query_notices(cls): discovery_url = urljoin(base_discovery_url, 'environments/envid/notices') - responses.add(responses.GET, discovery_url, - body="{\"body\": \"hello\"}", status=200, + responses.add(responses.GET, + discovery_url, + body="{\"body\": \"hello\"}", + status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) - discovery.federated_query_notices('envid', collection_ids=['collid1', 'collid2'], filter='notices.sha1::9181d244*') + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) + discovery.federated_query_notices('envid', + collection_ids=['collid1', 'collid2'], + filter='notices.sha1::9181d244*') called_url = urlparse(responses.calls[0].request.url) test_url = urlparse(discovery_url) @@ -324,12 +364,16 @@ def test_query(cls): discovery_url = urljoin(base_discovery_url, 'environments/envid/collections/collid/query') - responses.add(responses.POST, discovery_url, - body="{\"body\": \"hello\"}", status=200, + responses.add(responses.POST, + discovery_url, + body="{\"body\": \"hello\"}", + status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) - discovery.query('envid', 'collid', + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) + discovery.query('envid', + 'collid', filter='extracted_metadata.sha1::9181d244*', count=1, passages=True, @@ -350,12 +394,16 @@ def test_query_2(cls): discovery_url = urljoin(base_discovery_url, 'environments/envid/collections/collid/query') - responses.add(responses.POST, discovery_url, - body="{\"body\": \"hello\"}", status=200, + responses.add(responses.POST, + discovery_url, + body="{\"body\": \"hello\"}", + status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) - discovery.query('envid', 'collid', + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) + discovery.query('envid', + 'collid', filter='extracted_metadata.sha1::9181d244*', count=1, passages=True, @@ -376,18 +424,17 @@ def test_query_2(cls): @responses.activate def test_query_notices(cls): discovery_url = urljoin( - base_discovery_url, - 'environments/envid/collections/collid/notices') + base_discovery_url, 'environments/envid/collections/collid/notices') - responses.add( - responses.GET, - discovery_url, - body="{\"body\": \"hello\"}", - status=200, - content_type='application/json') + responses.add(responses.GET, + discovery_url, + body="{\"body\": \"hello\"}", + status=200, + content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) discovery.query_notices('envid', 'collid', filter='notices.sha1::*') called_url = urlparse(responses.calls[0].request.url) @@ -396,41 +443,51 @@ def test_query_notices(cls): assert called_url.path == test_url.path assert len(responses.calls) == 1 - @classmethod @responses.activate def test_configs(cls): discovery_url = urljoin(base_discovery_url, 'environments/envid/configurations') - discovery_config_id = urljoin(base_discovery_url, - 'environments/envid/configurations/confid') - - results = {"configurations":[{"name": "Default Configuration", "configuration_id": "confid"}]} + discovery_config_id = urljoin( + base_discovery_url, 'environments/envid/configurations/confid') + + results = { + "configurations": [{ + "name": "Default Configuration", + "configuration_id": "confid" + }] + } - responses.add(responses.GET, discovery_url, + responses.add(responses.GET, + discovery_url, body=json.dumps(results), status=200, content_type='application/json') - responses.add(responses.GET, discovery_config_id, + responses.add(responses.GET, + discovery_config_id, body=json.dumps(results['configurations'][0]), status=200, content_type='application/json') - responses.add(responses.POST, discovery_url, + responses.add(responses.POST, + discovery_url, body=json.dumps(results['configurations'][0]), status=200, content_type='application/json') - responses.add(responses.PUT, discovery_config_id, + responses.add(responses.PUT, + discovery_config_id, body=json.dumps(results['configurations'][0]), status=200, content_type='application/json') - responses.add(responses.DELETE, discovery_config_id, + responses.add(responses.DELETE, + discovery_config_id, body=json.dumps({'deleted': 'bogus -- ok'}), status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) discovery.list_configurations(environment_id='envid') discovery.get_configuration(environment_id='envid', @@ -438,24 +495,28 @@ def test_configs(cls): assert len(responses.calls) == 2 - discovery.create_configuration(environment_id='envid', - name='my name') + discovery.create_configuration(environment_id='envid', name='my name') discovery.create_configuration(environment_id='envid', name='my name', - source={'type': 'salesforce', 'credential_id': 'xxx'}) + source={ + 'type': 'salesforce', + 'credential_id': 'xxx' + }) discovery.update_configuration(environment_id='envid', configuration_id='confid', name='my new name') discovery.update_configuration(environment_id='envid', configuration_id='confid', name='my new name', - source={'type': 'salesforce', 'credential_id': 'xxx'}) + source={ + 'type': 'salesforce', + 'credential_id': 'xxx' + }) discovery.delete_configuration(environment_id='envid', configuration_id='confid') assert len(responses.calls) == 7 - @classmethod @responses.activate def test_document(cls): @@ -463,52 +524,70 @@ def test_document(cls): 'environments/envid/preview') config_url = urljoin(base_discovery_url, 'environments/envid/configurations') - responses.add(responses.POST, discovery_url, + responses.add(responses.POST, + discovery_url, body="{\"configurations\": []}", status=200, content_type='application/json') - responses.add(responses.GET, config_url, - body=json.dumps({"configurations": [{"name": "Default Configuration", "configuration_id": "confid"}]}), + responses.add(responses.GET, + config_url, + body=json.dumps({ + "configurations": [{ + "name": "Default Configuration", + "configuration_id": "confid" + }] + }), status=200, content_type='application/json') authenticator = BasicAuthenticator('username', 'password') - discovery = ibm_watson.DiscoveryV1('2018-08-13', authenticator=authenticator) + discovery = ibm_watson.DiscoveryV1('2018-08-13', + authenticator=authenticator) - add_doc_url = urljoin(base_discovery_url, - 'environments/envid/collections/collid/documents') + add_doc_url = urljoin( + base_discovery_url, + 'environments/envid/collections/collid/documents') doc_id_path = 'environments/envid/collections/collid/documents/docid' update_doc_url = urljoin(base_discovery_url, doc_id_path) - del_doc_url = urljoin(base_discovery_url, - doc_id_path) - responses.add(responses.POST, add_doc_url, + del_doc_url = urljoin(base_discovery_url, doc_id_path) + responses.add(responses.POST, + add_doc_url, body="{\"body\": []}", status=200, content_type='application/json') doc_status = { - "document_id": "45556e23-f2b1-449d-8f27-489b514000ff", - "configuration_id": "2e079259-7dd2-40a9-998f-3e716f5a7b88", - "created" : "2016-06-16T10:56:54.957Z", - "updated" : "2017-05-16T13:56:54.957Z", - "status": "available", - "status_description": "Document is successfully ingested and indexed with no warnings", + "document_id": + "45556e23-f2b1-449d-8f27-489b514000ff", + "configuration_id": + "2e079259-7dd2-40a9-998f-3e716f5a7b88", + "created": + "2016-06-16T10:56:54.957Z", + "updated": + "2017-05-16T13:56:54.957Z", + "status": + "available", + "status_description": + "Document is successfully ingested and indexed with no warnings", "notices": [] - } + } - responses.add(responses.GET, del_doc_url, + responses.add(responses.GET, + del_doc_url, body=json.dumps(doc_status), status=200, content_type='application/json') - responses.add(responses.POST, update_doc_url, + responses.add(responses.POST, + update_doc_url, body="{\"body\": []}", status=200, content_type='application/json') - responses.add(responses.DELETE, del_doc_url, + responses.add(responses.DELETE, + del_doc_url, body="{\"body\": []}", status=200, content_type='application/json') @@ -553,24 +632,25 @@ def test_document(cls): assert len(responses.calls) == 6 - conf_id = discovery.add_document(environment_id='envid', - collection_id='collid', - file=io.StringIO(u'